{"text": "```python\nprint \"hello world\"\n```\n\n    hello world\n\n\n## large cells \n\n\n```python\n# simple code \n2 + 2 \n```\n\n\n\n\n    4\n\n\n\n\n```python\n# simple variable \nx = 3\n\n# print it \nprint x \n```\n\n    3\n\n\n\n```python\n# a function \ndef print_hello(name) : \n    print 'hello {0}'.format(name)\n```\n\n\n```python\nprint_hello(\"bro\")\n```\n\n    hello bro\n\n\n# help key board short cuts to find all the keyboard short cut, esc + l print line numbers\n\n\n\n```python\n!python --version \n\n```\n\n    Python 2.7.15 :: Anaconda, Inc.\n\n\n\n```python\n%matplotlib inline\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nplt.plot(range(100))\n```\n\nmatplotlib helps you plot stuff on the jupyther notebook\n\n\n```python\n%time x = range(10000)\n```\n\n    Wall time: 1 ms\n\n\n## time your functions with time\n\n\n\n```python\n%%timeit x = range(10000)\nmax(x)\n```\n\n    1000 loops, best of 3: 221 \u00b5s per loop\n\n\n# writes to files \n\n\n```python\n%%writefile test.txt\nthis is some stuff that i wrote form jupiter notebook \n```\n\n    Writing test.txt\n\n\n# ls list directory \n\n\n```python\n%ls\n\n```\n\n     Volume in drive F has no label.\n     Volume Serial Number is C816-9EA8\n    \n     Directory of F:\\anacondaWD\n    \n    23-Jul-18  00:19    <DIR>          .\n    23-Jul-18  00:19    <DIR>          ..\n    23-Jul-18  00:00    <DIR>          .ipynb_checkpoints\n    23-Jul-18  00:19            16,013 My First Notebook.ipynb\n    23-Jul-18  00:18                54 test.txt\n                   2 File(s)         16,067 bytes\n                   3 Dir(s)  528,140,967,936 bytes free\n\n\n# we can use latex in jupyter with %latex\n\n\n```latex\n%%latex\n\\begin{align}\nGradient: \\nabla J = -2H^T (Y -HW)\n\\end{align}\n```\n\n\n\\begin{align}\nGradient: \\nabla J = -2H^T (Y -HW)\n\\end{align}\n\n\n## load_ext loads extensions\n\n\n\n```python\n%%!\npip install ipython-sql\n\n```\n\n\n\n\n    ['Collecting ipython-sql',\n     '  Downloading https://files.pythonhosted.org/packages/ab/df/427e7cf05ffc67e78672ad57dce2436c1e825129033effe6fcaf804d0c60/ipython_sql-0.3.9-py2.py3-none-any.whl',\n     'Collecting sqlparse (from ipython-sql)',\n     '  Downloading https://files.pythonhosted.org/packages/65/85/20bdd72f4537cf2c4d5d005368d502b2f464ede22982e724a82c86268eda/sqlparse-0.2.4-py2.py3-none-any.whl',\n     'Requirement already satisfied: ipython-genutils>=0.1.0 in f:\\\\anaconda\\\\lib\\\\site-packages (from ipython-sql) (0.2.0)',\n     'Requirement already satisfied: ipython>=1.0 in f:\\\\anaconda\\\\lib\\\\site-packages (from ipython-sql) (5.7.0)',\n     'Requirement already satisfied: six in f:\\\\anaconda\\\\lib\\\\site-packages (from ipython-sql) (1.11.0)',\n     'Requirement already satisfied: sqlalchemy>=0.6.7 in f:\\\\anaconda\\\\lib\\\\site-packages (from ipython-sql) (1.2.7)',\n     'Collecting prettytable (from ipython-sql)',\n     '  Downloading https://files.pythonhosted.org/packages/ef/30/4b0746848746ed5941f052479e7c23d2b56d174b82f4fd34a25e389831f5/prettytable-0.7.2.tar.bz2',\n     'Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in f:\\\\anaconda\\\\lib\\\\site-packages (from ipython>=1.0->ipython-sql) (1.0.15)',\n     'Requirement already satisfied: setuptools>=18.5 in f:\\\\anaconda\\\\lib\\\\site-packages (from ipython>=1.0->ipython-sql) (39.1.0)',\n     'Requirement already satisfied: decorator in f:\\\\anaconda\\\\lib\\\\site-packages (from ipython>=1.0->ipython-sql) (4.3.0)',\n     'Requirement already satisfied: pickleshare in f:\\\\anaconda\\\\lib\\\\site-packages (from ipython>=1.0->ipython-sql) (0.7.4)',\n     'Requirement already satisfied: win-unicode-console>=0.5; sys_platform == \"win32\" and python_version < \"3.6\" in f:\\\\anaconda\\\\lib\\\\site-packages (from ipython>=1.0->ipython-sql) (0.5)',\n     'Requirement already satisfied: pygments in f:\\\\anaconda\\\\lib\\\\site-packages (from ipython>=1.0->ipython-sql) (2.2.0)',\n     'Requirement already satisfied: pathlib2; python_version == \"2.7\" or python_version == \"3.3\" in f:\\\\anaconda\\\\lib\\\\site-packages (from ipython>=1.0->ipython-sql) (2.3.2)',\n     'Requirement already satisfied: backports.shutil-get-terminal-size; python_version == \"2.7\" in f:\\\\anaconda\\\\lib\\\\site-packages (from ipython>=1.0->ipython-sql) (1.0.0)',\n     'Requirement already satisfied: colorama; sys_platform == \"win32\" in f:\\\\anaconda\\\\lib\\\\site-packages (from ipython>=1.0->ipython-sql) (0.3.9)',\n     'Requirement already satisfied: simplegeneric>0.8 in f:\\\\anaconda\\\\lib\\\\site-packages (from ipython>=1.0->ipython-sql) (0.8.1)',\n     'Requirement already satisfied: traitlets>=4.2 in f:\\\\anaconda\\\\lib\\\\site-packages (from ipython>=1.0->ipython-sql) (4.3.2)',\n     'Requirement already satisfied: wcwidth in f:\\\\anaconda\\\\lib\\\\site-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython>=1.0->ipython-sql) (0.1.7)',\n     'Requirement already satisfied: scandir in f:\\\\anaconda\\\\lib\\\\site-packages (from pathlib2; python_version == \"2.7\" or python_version == \"3.3\"->ipython>=1.0->ipython-sql) (1.7)',\n     'Requirement already satisfied: enum34 in f:\\\\anaconda\\\\lib\\\\site-packages (from traitlets>=4.2->ipython>=1.0->ipython-sql) (1.1.6)',\n     'Building wheels for collected packages: prettytable',\n     '  Running setup.py bdist_wheel for prettytable: started',\n     \"  Running setup.py bdist_wheel for prettytable: finished with status 'done'\",\n     '  Stored in directory: C:\\\\Users\\\\home\\\\AppData\\\\Local\\\\pip\\\\Cache\\\\wheels\\\\80\\\\34\\\\1c\\\\3967380d9676d162cb59513bd9dc862d0584e045a162095606',\n     'Successfully built prettytable',\n     'distributed 1.21.8 requires msgpack, which is not installed.',\n     'grin 1.2.1 requires argparse>=1.1, which is not installed.',\n     'Installing collected packages: sqlparse, prettytable, ipython-sql',\n     'Successfully installed ipython-sql-0.3.9 prettytable-0.7.2 sqlparse-0.2.4',\n     'You are using pip version 10.0.1, however version 18.0 is available.',\n     \"You should consider upgrading via the 'python -m pip install --upgrade pip' command.\"]\n\n\n\n\n```python\n%load_ext sql\n\n```\n\n\n```python\n%sql sqlite://\n```\n\n\n\n\n    'Connected: @None'\n\n\n\n\n```sql\n%%sql\ncreate table classT(name, age, marks);\ninsert into classT values(\"bob\", 22, 99);\ninsert into classT values(\"tom\", 21, 88);\n```\n\n     * sqlite://\n    Done.\n    1 rows affected.\n    1 rows affected.\n\n\n\n\n\n    []\n\n\n\n\n```python\n%sql select * from classT;\n```\n\n     * sqlite://\n    Done.\n\n\n\n\n\n<table>\n    <tr>\n        <th>name</th>\n        <th>age</th>\n        <th>marks</th>\n    </tr>\n    <tr>\n        <td>bob</td>\n        <td>22</td>\n        <td>99</td>\n    </tr>\n    <tr>\n        <td>tom</td>\n        <td>21</td>\n        <td>88</td>\n    </tr>\n</table>\n\n\n\n# List all of the magic functions %lsmagic\n\n\n```python\n%lsmagic \n```\n\n\n\n\n    Available line magics:\n    %alias  %alias_magic  %autocall  %automagic  %autosave  %bookmark  %cd  %clear  %cls  %colors  %config  %connect_info  %copy  %ddir  %debug  %dhist  %dirs  %doctest_mode  %echo  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %less  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %macro  %magic  %matplotlib  %mkdir  %more  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %popd  %pprint  %precision  %profile  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %ren  %rep  %rerun  %reset  %reset_selective  %rmdir  %run  %save  %sc  %set_env  %sql  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode\n    \n    Available cell magics:\n    %%!  %%HTML  %%SVG  %%bash  %%capture  %%cmd  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%sql  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile\n    \n    Automagic is ON, % prefix IS NOT needed for line magics.\n\n\n\n\n```python\nimport sklearn.tree \n\nhelp(sklearn.tree._tree.Tree)\n```\n\n    Help on class Tree in module sklearn.tree._tree:\n    \n    class Tree(__builtin__.object)\n     |  Array-based representation of a binary decision tree.\n     |  \n     |  The binary tree is represented as a number of parallel arrays. The i-th\n     |  element of each array holds information about the node `i`. Node 0 is the\n     |  tree's root. You can find a detailed description of all arrays in\n     |  `_tree.pxd`. NOTE: Some of the arrays only apply to either leaves or split\n     |  nodes, resp. In this case the values of nodes of the other type are\n     |  arbitrary!\n     |  \n     |  Attributes\n     |  ----------\n     |  node_count : int\n     |      The number of nodes (internal nodes + leaves) in the tree.\n     |  \n     |  capacity : int\n     |      The current capacity (i.e., size) of the arrays, which is at least as\n     |      great as `node_count`.\n     |  \n     |  max_depth : int\n     |      The maximal depth of the tree.\n     |  \n     |  children_left : array of int, shape [node_count]\n     |      children_left[i] holds the node id of the left child of node i.\n     |      For leaves, children_left[i] == TREE_LEAF. Otherwise,\n     |      children_left[i] > i. This child handles the case where\n     |      X[:, feature[i]] <= threshold[i].\n     |  \n     |  children_right : array of int, shape [node_count]\n     |      children_right[i] holds the node id of the right child of node i.\n     |      For leaves, children_right[i] == TREE_LEAF. Otherwise,\n     |      children_right[i] > i. This child handles the case where\n     |      X[:, feature[i]] > threshold[i].\n     |  \n     |  feature : array of int, shape [node_count]\n     |      feature[i] holds the feature to split on, for the internal node i.\n     |  \n     |  threshold : array of double, shape [node_count]\n     |      threshold[i] holds the threshold for the internal node i.\n     |  \n     |  value : array of double, shape [node_count, n_outputs, max_n_classes]\n     |      Contains the constant prediction value of each node.\n     |  \n     |  impurity : array of double, shape [node_count]\n     |      impurity[i] holds the impurity (i.e., the value of the splitting\n     |      criterion) at node i.\n     |  \n     |  n_node_samples : array of int, shape [node_count]\n     |      n_node_samples[i] holds the number of training samples reaching node i.\n     |  \n     |  weighted_n_node_samples : array of int, shape [node_count]\n     |      weighted_n_node_samples[i] holds the weighted number of training samples\n     |      reaching node i.\n     |  \n     |  Methods defined here:\n     |  \n     |  __getstate__(...)\n     |      Getstate re-implementation, for pickling.\n     |  \n     |  __reduce__(...)\n     |      Reduce re-implementation, for pickling.\n     |  \n     |  __setstate__(...)\n     |      Setstate re-implementation, for unpickling.\n     |  \n     |  apply(...)\n     |      Finds the terminal region (=leaf node) for each sample in X.\n     |  \n     |  compute_feature_importances(...)\n     |      Computes the importance of each feature (aka variable).\n     |  \n     |  decision_path(...)\n     |      Finds the decision path (=node) for each sample in X.\n     |  \n     |  predict(...)\n     |      Predict target for X.\n     |  \n     |  ----------------------------------------------------------------------\n     |  Data descriptors defined here:\n     |  \n     |  capacity\n     |  \n     |  children_left\n     |  \n     |  children_right\n     |  \n     |  feature\n     |  \n     |  impurity\n     |  \n     |  max_depth\n     |  \n     |  max_n_classes\n     |  \n     |  n_classes\n     |  \n     |  n_features\n     |  \n     |  n_node_samples\n     |  \n     |  n_outputs\n     |  \n     |  node_count\n     |  \n     |  threshold\n     |  \n     |  value\n     |  \n     |  weighted_n_node_samples\n     |  \n     |  ----------------------------------------------------------------------\n     |  Data and other attributes defined here:\n     |  \n     |  __new__ = <built-in method __new__ of type object>\n     |      T.__new__(S, ...) -> a new object with type S, a subtype of T\n     |  \n     |  __pyx_vtable__ = <capsule object NULL>\n    \n\n\n\n```python\n\n```\n", "meta": {"hexsha": "e74ad63a653d9482fbbf1a37d5da8a0bc601d003", "size": 35334, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/my first notebook.ipynb", "max_stars_repo_name": "maguas01/titanic", "max_stars_repo_head_hexsha": "f16e13e3a88e9ef4ead1c8b47a7b4cd65811dc07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/my first notebook.ipynb", "max_issues_repo_name": "maguas01/titanic", "max_issues_repo_head_hexsha": "f16e13e3a88e9ef4ead1c8b47a7b4cd65811dc07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/my first notebook.ipynb", "max_forks_repo_name": "maguas01/titanic", "max_forks_repo_head_hexsha": "f16e13e3a88e9ef4ead1c8b47a7b4cd65811dc07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.0573566085, "max_line_length": 11660, "alphanum_fraction": 0.6539593593, "converted": true, "num_tokens": 3605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.11757213818344736, "lm_q1q2_score": 0.04967477330752071}}
{"text": "```python\nfrom IPython.core.display import display_html\nfrom urllib.request import urlopen\n\ncssurl = 'http://j.mp/1DnuN9M'\ndisplay_html(urlopen(cssurl).read(), raw=True)\n```\n\n\n<link href='http://fonts.googleapis.com/css?family=EB+Garamond' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Lato:100,100italic' rel='stylesheet' type='text/css'>\n\n<style>\n\t@font-face{\n   \t\tfont-family: \"Computer Modern\";\n        \tsrc: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');}\n\n        div.cell{\n\t        max-width:    800px;\n\t        margin-left:  auto;\n\t        margin-right: auto;}\n\n\th1 {\n        \tfont-family: 'Lato', sans-serif;}\n\n\th2 {\n        \tfont-family: 'Lato', serif;}\n\n\th3{\n\t\tfont-family:   'Lato', serif;\n        \tmargin-top:    12px;\n\t\tmargin-bottom: 3px;}\n\n        h4{\n\t\tfont-family: 'Lato', serif;}\n\n\th5 {\n        \tfont-family: 'Lato', serif;}\n\n\tdiv.text_cell_render{\n        \tfont-family:  'EB Garamond', 'Computer Modern', 'Helvetica Neue', Arial, Helvetica, Geneva, sans-serif;\n\t        line-height:  140%;\n\t        font-size:    14pt;\n\t\tmax-width:    650px;\n\t\tmargin-left:  auto;\n        \tmargin-right: auto;}\n\n\t.CodeMirror{\n        \tfont-family: 'Consolas';}\n\n\t.text_cell_render h1 {\n\t        font-weight:   100;\n\t        font-size:     48pt;\n\t\tline-height:   100%;\n\t        color:         #CD2305;\n\t        margin-bottom: 0.5em;\n\t        margin-top:    0.5em;\n\t        display:       block;}\n\n\t.text_cell_render h2 {\n        \tfont-weight:   100;\n        \tfont-size:     36pt;}\n\n\t.text_cell_render h3 {\n        \tfont-weight:   100;\n        \tfont-size:     21pt;}\n\n\t.text_cell_render h4 {\n        \tfont-weight:   100;\n        \tfont-size:     18pt;}\n\n\t.text_cell_render h5 {\n\t        font-weight:   100;\n\t        font-size:     16pt;\n\t        color:         #CD2305;\n\t        font-style:    italic;\n\t        margin-bottom: 0.5em;\n\t        margin-top:    0.5em;\n\t        display:       block;}\n\n\t.text_cell_render h6 {\n\t        font-weight:   100;\n\t        font-size:     14pt;\n\t        color:         #CD2305;\n\t        font-style:    italic;\n\t        margin-bottom: 0.5em;\n\t        margin-top:    0.5em;\n\t        display:       block;}\n\n\t.warning{\n\t    \tbackground-color: #FFFFE0;\n\t    \tborder-color: #FFCC99;\n\t    \tborder-left: 5px solid #FFCC99;\n\t    \tpadding: 0.5em;}\n\n\t.error{\n\t    \tbackground-color: #fcf2f2;\n\t    \tborder-color: #dFb5b4;\n\t    \tborder-left: 5px solid #dfb5b4;\n\t    \tpadding: 0.5em;}\n\n</style>\n\n\n\n\n# Tarea 6\n\n## Simulaci\u00f3n de un sistema con retardo por medio de la construcci\u00f3n de una Matriz de Lyapunov\n\nDado el sistema:\n\n$$\n\\dot{x}(t) = A_0 x(t) + A_1 x(t - \\tau)\n$$\n\nproponemos una soluci\u00f3n de la forma $x(t) = U(\\tau)$ con $U(\\tau)$ de la forma:\n\n$$\nU(\\tau) = \\int_0^{\\infty} K^T(t) W K(t + \\tau) dt\n$$\n\nSoluci\u00f3n que sabemos satisface la condici\u00f3n din\u00e1mica del sistema:\n\n$$\n\\frac{d U(\\tau)}{d \\tau} = U(\\tau) A_0 + U(\\tau - h) A_1\n$$\n\nla cual, para un tiempo negativo ser\u00eda:\n\n$$\n\\frac{d U(- \\tau)}{d \\tau} = U(- \\tau) A_0 + U(- \\tau - h) A_1\n$$\n\nasi como la propiedad simetrica:\n\n$$\nU(-\\tau) = U^T(\\tau) \\quad \\tau \\geq 0 \n$$\n\npor lo que tenemos que la propiedad din\u00e1mica del sistema queda:\n\n$$\n\\frac{d U(\\tau)}{d \\tau} = -A_0^T U(\\tau) - A_1^T U(\\tau + h)\n$$\n\no bien:\n\n$$\n\\frac{d U(\\tau - h)}{d \\tau} = -A_0^T U(\\tau - h) - A_1^T U(\\tau)\n$$\n\nEn este punto introducimos dos variables auxiliares, $Y(\\tau) = U(\\tau)$ y $Z(\\tau) = U(\\tau - h)$, para expresar la condici\u00f3n din\u00e1mica del sistema y esta ultiima expresi\u00f3n en forma de un sistema acoplado:\n\n$$\n\\frac{d Y(\\tau)}{d \\tau} = Y(\\tau) A_0 + Z(\\tau) A_1\n$$\n\n$$\n\\frac{d Z(\\tau)}{d \\tau} = -A_1^T Y(\\tau) - A_0^T Z(\\tau)\n$$\n\nen donde notamos que tenemos un sistema sin retardos explicitos, por lo que podemos utilizar tecnicas convencionales para el analisis de este sistema, mas aun, podemos construir una matriz que de el comportamiento de este sistema acoplado.\n\nPara poder lograr esto, primero tenemos que hablar de la vectorizaci\u00f3n de una matriz y del producto de Kronecker; dada una matriz $A$ de la forma:\n\n$$\nA =\n\\begin{pmatrix}\na_1 & a_2 & \\dots & a_n\n\\end{pmatrix}\n$$\n\nen donde $a_1, a_2, \\dots, a_n$ son las columnas de $A$ definimos la vectorizaci\u00f3n de $A$ como:\n\n<div style=\"display:none\">\n  $\\DeclareMathOperator{\\vect}{vec}$\n</div>\n\n$$\n\\vect{(A)} =\n\\begin{pmatrix}\na_1 \\\\\na_2 \\\\\n\\vdots \\\\\na_n\n\\end{pmatrix}\n$$\n\nes decir, un vector en donde todas las columnas se colocan consecutivamente en la primera.\n\nDada esta definici\u00f3n, podemos decir que una manera de simplificar la vectorizaci\u00f3n de un producto es:\n\n$$\n\\vect{(AXB)} = (B^T \\otimes A) \\vect{(X)}\n$$\n\nen donde $\\otimes$ es el producto de Kronecker y se define como:\n\n$$\nA \\otimes B =\n\\begin{pmatrix}\na_{11} B & a_{12} B & \\dots & a_{1n} B \\\\\na_{21} B & a_{22} B & \\dots & a_{2n} B \\\\\n\\vdots & \\vdots & & \\vdots \\\\\na_{n1} B & a_{n2} B & \\dots & a_{nn} B \\\\\n\\end{pmatrix}\n$$\n\nEl sistema acoplado que obtuvimos es equivalente a:\n\n$$\n\\frac{d Y(\\tau)}{d \\tau} = I Y(\\tau) A_0 + I Z(\\tau) A_1\n$$\n\n$$\n\\frac{d Z(\\tau)}{d \\tau} = -A_1^T Y(\\tau) I - A_0^T Z(\\tau) I\n$$\n\npor lo que al vectorizar estas expresiones, obtendremos:\n\n$$\n\\frac{d \\bar{Y}(\\tau)}{d \\tau} = \\left( A_0^T \\otimes I \\right) \\bar{Y}(\\tau) + \\left( A_1^T \\otimes I \\right) \\bar{Z}(\\tau)\n$$\n\n$$\n\\frac{d \\bar{Z}(\\tau)}{d \\tau} = - \\left( I \\otimes A_1^T \\right) \\bar{Y}(\\tau) - \\left( I \\otimes A_0^T \\right) \\bar{Z}(\\tau)\n$$\n\no bien:\n\n$$\n\\frac{d}{d\\tau}\n\\begin{pmatrix}\n\\bar{Y}(\\tau) \\\\\n\\bar{Z}(\\tau)\n\\end{pmatrix} =\n\\begin{pmatrix}\nA_0^T \\otimes I & A_1^T \\otimes I \\\\\n-I \\otimes A_1^T & -I \\otimes A_0^T\n\\end{pmatrix}\n\\begin{pmatrix}\n\\bar{Y}(\\tau) \\\\\n\\bar{Z}(\\tau)\n\\end{pmatrix}\n$$\n\nlo que sugiere una soluci\u00f3n de la forma:\n\n$$\n\\begin{pmatrix}\n\\bar{Y}(\\tau) \\\\\n\\bar{Z}(\\tau)\n\\end{pmatrix} = e^{L \\tau}\n\\begin{pmatrix}\n\\bar{Y}(0) \\\\\n\\bar{Z}(0)\n\\end{pmatrix}\n$$\n\nen donde $L$ es la matriz de Lyapunov, de la forma:\n\n$$\nL =\n\\begin{pmatrix}\nA_0^T \\otimes I & A_1^T \\otimes I \\\\\n-I \\otimes A_1^T & -I \\otimes A_0^T\n\\end{pmatrix}\n$$\n\nAhora consideremos las condiciones iniciales, asi como la propiedad algebraica del sistema:\n\n$$\nU(0) A_0 + U(-h) A_1 + A_0^T U(0) + A_1^T U(h) = -W\n$$\n\nnotando que las condiciones iniciales para $U$ se traducen en:\n\n$$\nY(0) = U(0) \\quad Z(0) = U(-h) \\quad Y(h) = U(h)\n$$\n\npodemos reescribir esta propiedad como:\n\n$$\nY(0) A_0 + Z(0) A_1 + A_0^T Y(0) + A_1^T Y(h) = -W\n$$\n\nvectorizando, esto nos queda:\n\n$$\n\\left( A_0^T \\otimes I \\right) \\bar{Y}(0) + \\left( A_1^T \\otimes I \\right) \\bar{Z}(0) + \\left( I \\otimes A_0^T \\right) \\bar{Y}(0) + \\left( I \\otimes A_1^T \\right) \\bar{Y}(h) = -\\bar{W}\n$$\n\nA esta ecuaci\u00f3n le agregamos la vectorizaci\u00f3n de una condici\u00f3n inicial dada ya:\n\n$$\n\\bar{Y}(h) - \\bar{Z}(h) = \\bar{0}\n$$\n\ny tenemos que este sistema acoplado puede ser escrito como:\n\n$$\n\\begin{align}\n\\begin{pmatrix}\nA_0^T \\otimes I + I \\otimes A_0^T & A_1^T \\otimes I \\\\\nI \\otimes I & 0 \\otimes 0\n\\end{pmatrix}\n\\begin{pmatrix}\n\\bar{Y}(0) \\\\\n\\bar{Z}(0)\n\\end{pmatrix} &+ \\\\\n\\begin{pmatrix}\nI \\otimes A_1^T & 0 \\otimes 0 \\\\\n0 \\otimes 0 & -I \\otimes I\n\\end{pmatrix}\n\\begin{pmatrix}\n\\bar{Y}(h) \\\\\n\\bar{Z}(h)\n\\end{pmatrix} &=\n\\begin{pmatrix}\n- \\bar{W} \\\\\n\\bar{0}\n\\end{pmatrix}\n\\end{align}\n$$\n\no bien:\n\n$$\nM\n\\begin{pmatrix}\n\\bar{Y}(0) \\\\\n\\bar{Z}(0)\n\\end{pmatrix} + N\n\\begin{pmatrix}\n\\bar{Y}(h) \\\\\n\\bar{Z}(h)\n\\end{pmatrix} =\n\\begin{pmatrix}\n- \\bar{W} \\\\\n\\bar{0}\n\\end{pmatrix}\n$$\n\ncon\n\n$$\nM =\n\\begin{pmatrix}\nA_0^T \\otimes I + I \\otimes A_0^T & A_1^T \\otimes I \\\\\nI \\otimes I & 0 \\otimes 0\n\\end{pmatrix}\n$$\n\n$$\nN =\n\\begin{pmatrix}\nI \\otimes A_1^T & 0 \\otimes 0 \\\\\n0 \\otimes 0 & -I \\otimes I\n\\end{pmatrix}\n$$\n\naun m\u00e1s, vemos que el termino $\\begin{pmatrix} \\bar{Y}(h) \\\\ \\bar{Z}(h) \\end{pmatrix}$ se puede obtener con el resultado anterior:\n\n$$\n\\begin{pmatrix}\n\\bar{Y}(h) \\\\\n\\bar{Z}(h)\n\\end{pmatrix} = e^{L h}\n\\begin{pmatrix}\n\\bar{Y}(0) \\\\\n\\bar{Z}(0)\n\\end{pmatrix}\n$$\n\npor lo que al sustituir en esta expresi\u00f3n, tenemos:\n\n$$\nM\n\\begin{pmatrix}\n\\bar{Y}(0) \\\\\n\\bar{Z}(0)\n\\end{pmatrix} + N e^{L h}\n\\begin{pmatrix}\n\\bar{Y}(0) \\\\\n\\bar{Z}(0)\n\\end{pmatrix} =\n\\begin{pmatrix}\n- \\bar{W} \\\\\n\\bar{0}\n\\end{pmatrix}\n$$\n\n$$\n\\left( M + N e^{L h} \\right)\n\\begin{pmatrix}\n\\bar{Y}(0) \\\\\n\\bar{Z}(0)\n\\end{pmatrix} =\n\\begin{pmatrix}\n- \\bar{W} \\\\\n\\bar{0}\n\\end{pmatrix}\n$$\n\n$$\n\\begin{pmatrix}\n\\bar{Y}(0) \\\\\n\\bar{Z}(0)\n\\end{pmatrix} =\n\\left( M + N e^{L h} \\right)^{-1}\n\\begin{pmatrix}\n- \\bar{W} \\\\\n\\bar{0}\n\\end{pmatrix}\n$$\n\nEsta expresi\u00f3n la podemos sustituir en la original y obtener:\n\n$$\n\\begin{pmatrix}\n\\bar{Y}(\\tau) \\\\\n\\bar{Z}(\\tau)\n\\end{pmatrix} = e^{L \\tau} \\left( M + N e^{L h} \\right)^{-1}\n\\begin{pmatrix}\n- \\bar{W} \\\\\n\\bar{0}\n\\end{pmatrix}\n$$\n\nPara esta simulaci\u00f3n utilizaremos los siguientes valores:\n\n$$\nA_0 =\n\\begin{pmatrix}\n0 & 1 \\\\\n-1 & 0\n\\end{pmatrix} \\quad\nA_1 =\n\\begin{pmatrix}\n-2 & 0 \\\\\n0.3 & 0\n\\end{pmatrix} \\quad W = I \\quad \\tau \\in [0, 1]\n$$\n\nDeclaramos estas matrices, asi como una matriz de ceros, la identidad y las vectorizaciones de una matriz de ceros, asi como la de la matriz $W$.\n\n\n```python\nfrom numpy import array, matrix, kron, eye, zeros, vstack, hstack, linspace\nfrom scipy.linalg import expm\n```\n\n\n```python\nA0 = matrix([[0, 1], [-1, 0]])\nA0\n```\n\n\n\n\n    matrix([[ 0,  1],\n            [-1,  0]])\n\n\n\n\n```python\nA1 = matrix([[-2, 0], [0.3, 0]])\nA1\n```\n\n\n\n\n    matrix([[-2. ,  0. ],\n            [ 0.3,  0. ]])\n\n\n\n\n```python\nI = matrix(eye(2))\nI\n```\n\n\n\n\n    matrix([[ 1.,  0.],\n            [ 0.,  1.]])\n\n\n\n\n```python\ncero = zeros((2**2, 2**2))\ncero\n```\n\n\n\n\n    array([[ 0.,  0.,  0.,  0.],\n           [ 0.,  0.,  0.,  0.],\n           [ 0.,  0.,  0.,  0.],\n           [ 0.,  0.,  0.,  0.]])\n\n\n\n\n```python\nv0 = matrix(zeros(4))\nv0\n```\n\n\n\n\n    matrix([[ 0.,  0.,  0.,  0.]])\n\n\n\n\n```python\nW = I\nW.flatten(\"F\")\n```\n\n\n\n\n    matrix([[ 1.,  0.,  0.,  1.]])\n\n\n\nAhora calculamos la matriz de Lyapunov, asi como las matrices $M$ y $N$\n\n\n```python\nL = vstack((hstack((kron(A0.T, I), kron(A1.T, I))),\n        hstack((kron(-I, A1.T), kron(-I, A0.T)))))\nL\n```\n\n\n\n\n    matrix([[ 0. ,  0. , -1. , -0. , -2. , -0. ,  0.3,  0. ],\n            [ 0. ,  0. , -0. , -1. , -0. , -2. ,  0. ,  0.3],\n            [ 1. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ],\n            [ 0. ,  1. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ],\n            [ 2. , -0.3,  0. , -0. , -0. ,  1. , -0. ,  0. ],\n            [-0. , -0. , -0. , -0. , -1. , -0. , -0. , -0. ],\n            [ 0. , -0. ,  2. , -0.3, -0. ,  0. , -0. ,  1. ],\n            [-0. , -0. , -0. , -0. , -0. , -0. , -1. , -0. ]])\n\n\n\n\n```python\nM = vstack((hstack((kron(A0.T, I) + kron(I, A0.T), kron(A1.T, I))),\n            hstack((kron(I, I), cero))))\nM\n```\n\n\n\n\n    matrix([[ 0. , -1. , -1. , -0. , -2. , -0. ,  0.3,  0. ],\n            [ 1. ,  0. ,  0. , -1. , -0. , -2. ,  0. ,  0.3],\n            [ 1. ,  0. ,  0. , -1. ,  0. ,  0. ,  0. ,  0. ],\n            [ 0. ,  1. ,  1. ,  0. ,  0. ,  0. ,  0. ,  0. ],\n            [ 1. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ],\n            [ 0. ,  1. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ],\n            [ 0. ,  0. ,  1. ,  0. ,  0. ,  0. ,  0. ,  0. ],\n            [ 0. ,  0. ,  0. ,  1. ,  0. ,  0. ,  0. ,  0. ]])\n\n\n\n\n```python\nN = vstack((hstack((kron(I, A1.T), cero)),\n            hstack((cero, kron(-I, I)))))\nN\n```\n\n\n\n\n    matrix([[-2. ,  0.3, -0. ,  0. ,  0. ,  0. ,  0. ,  0. ],\n            [ 0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ],\n            [-0. ,  0. , -2. ,  0.3,  0. ,  0. ,  0. ,  0. ],\n            [ 0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ,  0. ],\n            [ 0. ,  0. ,  0. ,  0. , -1. , -0. , -0. , -0. ],\n            [ 0. ,  0. ,  0. ,  0. , -0. , -1. , -0. , -0. ],\n            [ 0. ,  0. ,  0. ,  0. , -0. , -0. , -1. , -0. ],\n            [ 0. ,  0. ,  0. ,  0. , -0. , -0. , -0. , -1. ]])\n\n\n\n\n```python\nv = vstack((- W.flatten(\"F\").T, v0.T))\nv\n```\n\n\n\n\n    matrix([[-1.],\n            [-0.],\n            [-0.],\n            [-1.],\n            [ 0.],\n            [ 0.],\n            [ 0.],\n            [ 0.]])\n\n\n\nAhora declaramos la funci\u00f3n $f(\\tau)$ la cual es de la forma:\n\n$$\nf(\\tau) := e^{L \\tau} \\left( M + N e^{L h} \\right)^{-1}\n\\begin{pmatrix}\n\\bar{0} \\\\\n\\bar{W}\n\\end{pmatrix}\n$$\n\ncon la que podremos calcular los valores de:\n\n$$\n\\begin{pmatrix}\n\\bar{Y}(\\tau) \\\\\n\\bar{Z}(\\tau)\n\\end{pmatrix}\n$$\n\npara cada $\\tau$ que le demos como argumento:\n\n\n```python\nh = 1\nf = lambda tau: (expm(L*tau)*(M + N*expm(L*h)).I*v).flatten().tolist()[0]\n```\n\nutilizamos $h = \\frac{1}{2}$ para probar nuestra funci\u00f3n: \n\n\n```python\n# Fijamos la precision de los datos mostrados a 3 cifras significativas\n# para facilitar la lectura\n\n%precision 3\n```\n\n\n\n\n    u'%.3f'\n\n\n\n\n```python\ntau = 0.5\nv1 = f(tau)\nv1\n```\n\n\n\n\n    [-0.309, -0.127, -0.750, 1.018, -0.309, -0.750, -0.127, 1.018]\n\n\n\ny para un incremento en el retardo de $\\frac{1}{10}$, tenemos:\n\n\n```python\nv2 = f(tau + 0.1)\nv2\n```\n\n\n\n\n    [-0.163, -0.051, -0.774, 1.009, -0.427, -0.713, -0.208, 1.035]\n\n\n\npor lo que solo queda declarar el dominio de definici\u00f3n de los retardos:\n\n$$\nT = [0, 1]\n$$\n\ny obtener el conjunto de soluciones para cada retardo en el dominio definido:\n\n$$\nV_{sol}= \\left\\{ f(t) \\mid t \\in T \\right\\} \n$$\n\n\n```python\nT = linspace(0, 1, 1000)\nvsol = [f(t) for t in T]\n```\n\n\n```python\nsol = zip(*vsol)\n```\n\nAhora solo queda graficar la soluci\u00f3nes contra los retardos del sistema.\n\n\n```python\n%matplotlib inline\nfrom matplotlib.pyplot import plot, figure, style, legend\nstyle.use(\"ggplot\")\n```\n\n\n```python\nfig = figure(figsize=(12, 6))\n\np1, = plot(T, sol[0])\np2, = plot(T, sol[1])\np3, = plot(T, sol[2])\np4, = plot(T, sol[3])\n\nax = fig.gca()\nax.set_ylabel(r\"$Y(\\tau)$\", fontsize=20)\nax.set_xlabel(r\"$\\tau$\", fontsize=20)\n\nlegend([p1, p2, p3, p4],\n       [r\"$y_{11}(\\tau)$\",\n        r\"$y_{21}(\\tau)$\",\n        r\"$y_{12}(\\tau)$\",\n        r\"$y_{22}(\\tau)$\"]);\n```\n\nPuedes acceder a este notebook a traves de la p\u00e1gina\n\nhttp://bit.ly/1CccnJ9\n\no escaneando el siguiente c\u00f3digo:\n\n\n\n\n```python\n# Codigo para generar codigo :)\nfrom qrcode import make\nimg = make(\"http://bit.ly/1CccnJ9\")\nimg.save(\"codigos/codigo6.jpg\")\n```\n", "meta": {"hexsha": "24616274415b0da85aa7573b59d3e9c97fdf3b89", "size": 57794, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "IPythonNotebooks/Sistemas con retardo en la entrada/Tarea 6.ipynb", "max_stars_repo_name": "robblack007/DCA", "max_stars_repo_head_hexsha": "0ea5f8b613e2dabe1127b857c7bfe9be64c52d20", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IPythonNotebooks/Sistemas con retardo en la entrada/Tarea 6.ipynb", "max_issues_repo_name": "robblack007/DCA", "max_issues_repo_head_hexsha": "0ea5f8b613e2dabe1127b857c7bfe9be64c52d20", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IPythonNotebooks/Sistemas con retardo en la entrada/Tarea 6.ipynb", "max_forks_repo_name": "robblack007/DCA", "max_forks_repo_head_hexsha": "0ea5f8b613e2dabe1127b857c7bfe9be64c52d20", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-20T12:44:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-20T12:44:13.000Z", "avg_line_length": 55.3052631579, "max_line_length": 31374, "alphanum_fraction": 0.7048482541, "converted": true, "num_tokens": 5727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30074559147595986, "lm_q2_score": 0.16451646904109268, "lm_q1q2_score": 0.04947760278929986}}
{"text": "# Equity Valuation\n## Valuation by Comparables\nPurpose of  fundamental analysis: identify stocks that are mispriced relative to some measure of \u201ctrue\u201d value that can be derived from observable financial data.\n\n$\\odot$  \nTrue value can only be estimated.$\\square$\n\nIn practice, stock analysts use models to estimate from **observable market data** and from the **financial statements of the firm and its *competitors***. \n\nThey look at the relationship between price and various determinants of value for similar firms and then extrapolate that relationship to the firm in question.\n***\nThe SEC requires all public companies (except foreign companies and companies with less than 10 million dollars in assets and 500 shareholders) to file registration statements.\n\n**market cap**: total market value or capitalization: $\\text{share price} \\times \\text{ number of shares }$.\n\n>**e.g.** figures to be referenced\n> \n1. General\n  1. Price per share\n  2. Common shares outstanding (billion)\n  3. Market Capitalization\n2. Last 12 months\n  1. Sales\n  2. EBITDA\n  3. Net income\n  4. Earning per share\n3. Valuation\n  1. Price/Book\n  2. Price/Sales\n  3. Price/Cash flow\n  4. PEG\n4. Profitability\n  1. ROE\n  2. ROA\n  3. Operating profit margin\n  4. Net profit margin\n\n**book value**: The net worth of common equity according to a firm\u2019s balance sheet.\n\nAnd market value over book value can be used to compare with the industry average to find wheather it is underpriced if the ratio is lower than the industry average.\n\n### Limitations of Book Value\nShareholders, the value of their stake is what is left over when the liabilities of the firm are subtracted from its assets. \n\nShareholders\u2019 equity is this net worth.\n\n***Limitation***: the values of both assets and liabilities recognized in financial statements base on **historical**, not **current values**.\n\nBook values are based on original cost, market values measure current values of assets and liabilities.\n\nThe market value of the shareholders\u2019 equity investment = *current values of all assets* - *liabilities*\u3002\n***\nFor a *floor value*, below which level the market price can never fall, **liquidation value** per share can be considered, that is: **Net amount that can be realized by selling the assets of a firm and paying off the debt.**\n\n1. Stock price goes below that\n2. A corporate raider would buy enough shares to gain control (as a takeover target \u88ab\u6536\u8d2d)\n3. Liquidate the firm\n  - because the liquidation value exceeds the value of the business as a going concern.\n\n***\nAnother measure is the **replacement cost (Cost to replace a firm\u2019s assets)** of assets less liabilities.\n1. The company's market value get far above the replacemet cost for long\n2. Competitors enter the market\n3. Competitive pressure would drive down the market value of all firms until they fell to replacement cost.\n\n**Tobin\u2019s q**: Ratio of market value of the firm to replacement cost.\n> In the long run, the ratio of market price to replacement cost will tend toward $1$, but the evidence is that this ratio can differ significantly from 1 for very long periods of time.\n\nFocusing on the balance sheet can give some useful information, but the analyst usually must turn to **expected future cash flows** for a *better* estimate.\n\n## Intrinsic Value Versus Market Price\n1. Assuming a one-year holding period\n2. Let the expected dividend per share be $E(D_1)$\n3. Let the current price of a share be $P_0$\n4. Let the expected price at the end of a year be $E(P_1)$\n\nThe expected holding-period return is:\n\n$$\\text{Expected HPR} = E(r) = \\frac{E(D_1) + [E(P_1) - P_0]} {P_0}$$\n\nHere, $E(P_1)$ is the expectation today of the stock price one year from now. $E(r)$ is the stock\u2019s expected holding-period return, which is the sum of the expected dividend yield, $E(D_1) /P_0$, and the expected rate of price appreciation, the capital gains yield, $[E(P_1) \u2013 P_0]/P_0$.\n***\n**Capital Asset Pricing Model (CAPM)**: when stock market prices are at *equilibrium levels*, the rate of return that investors can expect to earn on a security is\n\n$$r_f + \\beta[E(r_M) \u2013 r_f]:=k$$\n\nwhere $\\beta$ is the risk, $r_f$ and $E(r_M) \u2013 r_f$ are given, $r_f$ is the risk free rate, $r_M$ is the rate of return on the market portfolio. $k$ is called the required rate of return.\n\nIf a stock is priced correctly, then its *expected return* is its *required return*, $i.e.$, $\\text{Expected HPR} = k$.\n***\nAnother way to see this is to compare the intrinsic value of a share of stock to its market price.\n**Intrinsic Value**: The present value of a firm\u2019s expected future net cash flows discounted by the required rate of return.\n\n$\\odot$dividends and proceeds from the ultimate sale of the stock are included in the cash flow.$square$\n\n$$\\text{Intrinsic Value} = \\frac{E(D_1) + E(P_1)} {1 + k}:=V_0$$\n\n$E(D_1)$ and $E(P_1)$ are given and $k$ is the **discounted rate**, as an risk-adjusted interest rate.\n\n$\\odot$Whenever the intrinsic value, or the investor\u2019s own estimate of what the stock is really worth, exceeds the market price, the stock is considered undervalued and a good investment.$square$\n\n>**e.g.**\n>\n>For company ABC, $E(D_1)$, expected dividend per share is 4 dollar; $P_0$, current price of a share, is \\$48; $E(P_1)$, expected price at the end of a year, is \\$52, then we have\n>\n>$$\\text{Expected HPR} = E(r) = \\frac{E(D_1) + [E(P_1) - P_0]} {P_0} = \\frac{4+[52-48]} {48} = 16.7\\%$$\n>\n>After that we have $r_f = 6\\%$, $E(r_M) - r_f = 5\\%$, $\\beta = 1.2$, so that the required rate of return is\n>\n>$$k = 6\\% + 1.2 \\times 5\\% = 12\\%$$\n>\n>which indicates that the rate of return the investor expects exceeds the required rate based on ABC\u2019s risk by a margin of $16.7\\% - 12\\% = 4.7\\%$.\n>\n>And the intrinsic value is\n>\n>$$V_0 = \\frac{E(D_1) + E(P_1)} {1 + k} = \\frac{\\$4 + \\$52} {1.12} = \\$50$$\n>\n>In this situation, the *intrinsic value* is bigger than the *current stock value*, and the expected return is 12%. So it means there's a fair rate of return relative to its risk, it is a *positive-alpha* stock. And for investors following a *passive strategy*, they will hold more ABC's stock.\n***\n**Market capitalization rate**: The market-consensus estimate of the appropriate discount rate for a firm\u2019s cash flows.\n\n$\\odot$ In market equilibrium, the current market price will reflect the intrinsic value estimates of *all* market participants. This means:\n1. The individual investor whose $V_0$ estimate differs from the market price, $P_0$\n2. They must disagree with some or all of the **market-consensus estimates\u5e02\u573a\u4e00\u81f4\u9884\u671f** of $E(D_1)$, $E(P_1)$, or $k$.\n\nAnd $k$, the required rate of return, its market-consensus estimate is **market capitalization rate**.\n\n**Market capitalization rate**: The market-consensus estimate of the appropriate discount rate for a firm\u2019s cash flows.\n\n## Dividend Discount Models\n### General\nFirst we have:\n\n$$V_0 = \\frac{D_1 + P_1} {1 + k}$$\n\nHere we use simpler notation that still express the expected value, $i.e.$, $D_1$ stand for $E(D_1)$, and so is $P_1$.\n\nAnd this formula indicates that value today of a share of stock equals the the ratio of the quanity of the dividend in peiod one plus the sale price in period one all divided by the quantity one pluse the discount rate.\n\nBut $D_1$ is easily to predict given the historical data, not for $P_1$. So that we can use\n\n$$V_1 = \\frac{D_2 + P_2} {1 + k}$$\n\nThen we assume the stock will be selling for its intrinsic value next year, then $V_1 = P_1$, so that\n\n$$V_0 = \\frac{D_1} {1 + k} + \\frac{D_2 + P_2} {(1 + k)^2}$$\n\nGenerally if we hold this stock for $H$ years, then we have:\n\n$$V_0 = \\frac{D_1} {1 + k} + \\frac{D_2} {(1 + k)^2} + \\cdots + \\frac{D_H + P_H} {(1 + k)^H}$$\n\n$\\odot$ This formular is similar to that of bond valuation formula, since bonds have coupons just like dividends but keep a certain value. The key differences in the case of stocks are the uncertainty of dividends, the lack of a fixed maturity date, and the unknown sales price at the horizon date. $\\square$\n\n**Dividend discount model (DDM)**: A formula for the intrinsic value of a firm equal to the present value of all expected future dividends.\n\n$$V_0 = \\frac{D_1} {1 + k} + \\frac{D_2} {(1 + k)^2} + \\frac{D_3} {(1 + k)^3} + \\cdots$$\n### The Constant-Growth DDM\nassume that dividends are trending upward at a stable growth rate, $g$, then we have\n\n$$V_0 = \\frac{D_0(1+g)} {1 + k} + \\frac{D_0(1+g)^2} {(1 + k)^2} + \\frac{D_0(1+g)^3} {(1 + k)^3} + \\cdots$$\n\nThen to make it converge, we assume that  $|(1+g)/(1+k)|<1$ so that we have\n\n$$V_0 = \\frac{D_0(1+g)} {k - g} = \\frac{D_\\mathbf{1}} {k - g}$$\n\n**Constant-growth DDM**: A form of the dividend discount model that assumes dividends will grow at a constant rate.\n\nAlso known as the **Gordon model**.\n\n>**e.g.**\n>\n>Preferred stock that pays a **fixed dividend**, so that $g = 0$.\n\n$\\odot$ The constant-growth DDM is valid only when g is less than k. If an analyst derives an estimate of g that is greater than k, that growth rate must be *unsustainable* in the *long run*.$\\square$\n\n### Implications and limitations\nA stock\u2019s value will be greater \n1. The larger its expected dividend ($D_i$) per share.\n2. The lower the market capitalization rate, $k$.\n3. The higher the expected growth rate ($g$) of dividends.\n***\nAssume that stock is selling at its intrinsic value so that $P_i = V_i$, then\n\n$$P_0 = V_0, P_1 = \\frac{D_1 (1+g)} {k-g} = \\frac{D_1} {k-g} (1+g) = P_0 (1+g)$$\n\nTherefore, in the case of **constant expected growth of dividends**, the *expected rate of price appreciation* in any year will equal that *constant growth rate*, $g$. $\\odot$ The stock price is expected to grow at the same rate as dividends.$\\square$\n\nSo that for a stock whose market price equals its intrinsic value ($V_0 = P_0$), the expected holding-period return will be\n\n$$E(r) = \\text{Dividend yield} + \\text{Capital Gains yield} = \\frac{D_1} {P_0} + \\frac{P_1 - P_0} {P_0} = \\frac{D_1} {P_0} + g$$\n\n**Discounted cash flow (DCF)** formula: the above formula, for if the stock is selling at its intrinsic value, then $E(r) = k$, implying that $k = \\displaystyle \\frac{D_1} {P_0} + g$. So we can observe the dividend yield, $\\displaystyle \\frac{D_1} {P_0}$, and estimate the growth rate of dividends ,$g$, and finally compute $k$.\n***\nHowever this CONSTANT-GROWTH DDM  usually applies to the regulated public utilities.\n\n### Stock Prices and Investment Opportunities\nSuppose firm ABC originally has expected earnings in the coming year of 5 dollars per share, and in principle pay out all of these earnings as dividends. If the market capitalization rate were $k = 12.5\\%$, then it'll be valued at $D_1/k = \\$5/.125 = \\$40$ per share. Since all earnings paid out as dividends, no investment, and companies\u2019 capital stock and earnings capacity would remain unchanged over time; earnings and dividends would not grow.\n\nNow ABC engages in projects that generate a return on investment of $15\\%$, which is greater than the required rate of return, $k = 12.5\\%$.\n1. plows back some earnings into its highly profitable projects, it can earn a $15\\%$ rate of return for shareholders.\n2. pays out all earnings as dividends and forgoes the projects. Then shareholders invest the dividends in other opportunities at a fair market rate of only $12.5\\%$.\n\n**Dividend payout ratio**: Percentage of earnings paid out as dividends.\n\n**Plowback ratio or earnings retention ratio**: The proportion of the firm\u2019s earnings that is reinvested in the business (and not paid out as dividends)\n\n$$\\text{New dividends} = \\text{old dividends} \\times \\text{Dividend payout ratio}$$\n\nAnd even now the dividends are less, the stock price will still goes up. Although dividends initially fall under the earnings reinvestment policy, subsequent growth in the assets of the firm because of reinvested profits will generate growth in future dividends, which will be reflected in today\u2019s share price.\n\nWhen reinvestment, the increase in the stock price reflects the fact that planned investments provide an expected rate of return greater than the required rate. $i.e.$, the investment opportunities have **positive net present value** (**positive NPV**), also called **present value of growth opportunities (PVGO)**: Net present value of a firm\u2019s future investments.\n\n>**e.g.**\n>\n>Firm ABC starts with $100$ million. The *return on investment or equity (ROE)* is $15\\%$, so that total earnings are $15$ million. If there's 3 million shares totally, then the *earning per share* are $5$ dollars.\n>\n>Now ABC reinvest the earnings of $60\\%$. Then the *value of the firm\u2019s capital stock* is increased by $15 \\times 60\\% = 9$ million.\n>\n>Now endowed with $9\\%$ more capital, the company earns $9\\%$ more income and pays out $9\\%$ higher dividends. The growth rate of the dividends, therefore, is\n>\n>$$g = \\text{ROE} \\times b = 0.15 \\times 0.60 = 9\\%$$\n>\n>$b$ is the **plowback ratio**\n>\n>Then ff the **stock price** equals its **intrinsic value**, and this growth rate can be **sustained** ($i.e.$, if the ROE and payout ratios are consistent with the long-run capabilities of the firm), then the stock should sell at\n>\n>$$P_0 = \\frac{D_1} {k-g} = \\frac{\\$2} {0.125-0.09} = \\$57.14$$\n>\n>So now, $\\text{Price} = \\text{No-growth value per share} + \\text{PVGO}$ or $P_0 = \\displaystyle \\frac{E_1} {k} + \\text{PVGO}$, $i.e.$, $57.14 = 40+17.14$\n***\nDividend cuts are usually taken as bad news about the future prospects of the firm, and it is the new information about the firm\u2014not the reduced dividend yield per se\u2014that is responsible for the stock price decline.\n\nStock price declines in response to dividend cuts are really a response to the information conveyed by the cut.\n***\nBut reinvestment enhances company value only if $\\text{ROE} > k$.\n\nSo if say $\\text{ROE} = k$, then $b=0, k=0$, and stock value per share would be $\\displaystyle \\frac{E_1} {k}$.\n\n$\\dagger$  \n$$P_0 = \\frac{D_1} {k-g} = \\frac{D_0 (1-b)} {k-\\text{ROE}\\times b} = \\frac{D_0} {k}$$\n\n$\\dagger$  \nAnother way to estimate $g$ is using the average of the industry as a benchmark.\n\n### Life Cycles and Multistage Growth Models \n**two-stage DDM**: Dividend discount model in which dividend growth is assumed to level off only at some future date.\n>**e.g.** Dividend growth rate will be steady beyond 2012. Given: $\\text{ROE} = 11\\%$, $\\text{Dividend payout ratio} = 0.30$, $\\text{Risk-free rate} = 3.5\\%$, $\\text{Market return} = 11.5\\%$, $\\beta = 1.05$.\n>\n>$\\displaystyle V_{2008} = \\frac{D_{2009}} {1+k} + \\frac{D_{2010}} {(1+k)^2} + \\frac{D_{2011}} {(1+k)^3} + \\frac{D_{2012} + V_{2012}} {(1+k)^4}$\n>\n>And here $k = r_f + \\beta[r_M - r_f] = 11.9\\%$, and since it's now with constant growth, $\\displaystyle V_{2012} = \\frac{D_{2013}} {k-g} = \\frac{D_{2012} \\;\\times (1+g)} {k - g}$. Now $g$ is the only left.\n>\n>$g = \\text{ROE} \\times b = 11\\% \\times (1-0.3) = 7.7\\%$\n\n$\\dagger$  \nSometimes $b$ can be acquired by using $\\displaystyle \\frac{E_i - D_i} {E_i}$.\n\n## Price-Earning Ratios\n### The Price\u2013Earnings Ratio and Growth Opportunities\n**Price\u2013earnings multiple (P/E ratio)**: The ratio of a stock\u2019s price to its earnings per share.\n\nAnd using the product of this and earnings, we can estimate the stock price.\n\nOur first equation is \n\n$$\\frac{P_0} {E_1} = \\frac{1} {k} \\left[ 1 + \\frac{\\text{PVGO}} {E_1 / k} \\right]$$\n\nWhen $\\text{PVGO} = 0$, it's a nongrowing perpetuity and the P/E ratio is just $\\displaystyle \\frac{1} {k}$.\n\nAnd another one is, for a firm growing at a long-run sustainable pace,\n\n$$P_0 = \\frac{D_1} {k - (\\text{ROE} \\times b)} = \\frac{E_1(1-b)} {k - (\\text{ROE} \\times b)} \\Rightarrow \\text{P/E Ratio} = \\frac{1 - b} {k - \\text{ROE} \\times b}$$\n\n$\\odot$  \nP/E ratios commonly are taken as proxies for the expected growth in dividends or earnings.$\\square$\n\n$\\dagger$  \nWhen $\\text{ROE} > k$, higher $b$ makes higher $\\text{P/E Ratio}$.\n***\n**PEG ratio**: Ratio of P/E multiple to earnings growth rate.\n\nCommonly should be $1$. And as a rule of thumb\u7ecf\u9a8c\u6cd5\u5219, $\\text{P/E Ratio}$ are often taken as the proxies of growth rate $g$.\n\n>**e.g.** Given expected $\\text{ROE} = 12\\%$, expected earnings per share $\\$2$ dollars, expected dividends of $\\$1.5$, and market capitalization rate, $10\\%$ per year.\n>\n>Plowback Ratio $b=\\displaystyle \\frac{\\text{Earning} - \\text{Dividend}} {\\text{Earning}} = \\frac{2-1.5} {2} = 25\\%$\n>\n>Expected Dividend Growth Rate: $g = \\text{ROE}\\times b = 12\\% \\times 0.25 = 3\\%$\n>\n>Expected Price based on the constant-growth DDM: $P_0 =\\displaystyle \\frac{D_1} {k-g} = \\frac{\\$1.50} {0.10 - 0.03} = \\$21.43$\n>\n>$\\text{P/E Ratio} = \\displaystyle \\frac{\\$21.43} {\\$2} = 10.71$\n>\n>$\\text{PEG} = \\displaystyle \\frac{P_0/E_1} {g} = \\frac{10.71} {3} = 3.57$\n\n### P/E Ratios and Stock Risk\nRiskier stocks will have lower P/E multiples. Under constant-growth model, $\\displaystyle \\frac{P} {E} = \\frac{1-b} {k-g}$. Since riskier firms will have higher required rates of return, $k$, so the ratio get lower.\n\nThe market\u2019s assessment that earnings in high inflation periods are of \u201clower quality,\u201d artificially distorted by inflation, and warranting lower P/E ratios.\n\n**Earnings management**: The practice of using flexibility in accounting rules to manipulate the apparent profitability of the firm.\n\n### Combining P/E Analysis and the DDM\nWhen calculating the intrisinc value, we can use the P/E ratio to find the last price:\n\n$$V_{2014} = \\frac{D_{2009}} {1 + k} + \\frac{D_{2010}} {(1+k)^2} + \\frac{D_{2011} + P_{2011}} {(1+k)^3}$$\n\n### Other Comparative Valuation Ratios\n**PRICE-TO-BOOK RATIO**: The ratio of price per share divided by book value per share.\n\n**PRICE-TO-CASH-FLOW RATIO**: The ratio of price to cash flow per share. Cash flow, which tracks cash actually flowing into or out of the firm, is less affected by accounting decisions.\n\n**PRICE-TO-SALES RATIO**: The ratio of stock price to the annual sales per share, since many start-up firms have no earnings.\n\n## Free Cash Flow Valuation Approaches\n**Free Cash Flow**: cash flow available to the firm or the equityholders net of capital expenditures. And it's useful for firms that pay no dividends\n\n**Free Cash Flow for the Firm (FCFF)**:\n\n$$\\text{FCFF} = \\text{EBIT}(1 - t_c) + \\text{Depreciation} - \\text{Capital Expenditures} - \\text{Increase in NWC}$$\n\nwhere, $\\text{EBIT}$ is the **earnings before interest and taxes**, $t_c$ is the corporate tax rate, $\\text{NWC}$ is the net working capital.\n\nAnother one is **Free Cash Flow for the Equityholders (FCFE)**:\n\n$$\\text{FCFE} = \\text{FCFF} - \\text{Interest expense} \\times (1 - t_c) + \\text{Increases in net debt}$$\n\n**Firm Value**: \n\n$$\\text{Firm Value} = \\sum_{t = 1}^T \\left( \\frac{\\text{FCFF}} {(1 + \\text{WACC})^t}\\right) + \\frac{P_T} {(1 + \\text{ WACC })^T} $$\n\nwhere $\\displaystyle P_T = \\frac{\\text{FCFF}_{T+1}} {\\text{WACC} - g}$, assuming a constant-growth model, is the estimate of **terminal value** so that it can be approximately the Firm Value we want. And $\\text{WACC}$ is the weighted average cost of capital.\n\n$\\dagger$  \nSo how to calculate the $\\text{WACC}$? $\\text{WACC} = \\displaystyle \\frac{E}{V} R_e + \\frac{D}{V} R_d (1 - T_c)$, where:\n\n$R_e$: **cost of equity**  \n$R_d$: **cost of debt**  \n$E$: **market value of the firm's equity**  \n$D$: **market value of the firm's debt**  \n$V = E + D$: **total market value of the firm\u2019s financing (equity and debt)**  \n$E/V$: **percentage of financing that is equity**  \n$D/V$: **percentage of financing that is debt**  \n$T_c$: **corporate tax rate**  \n\n**Intrinsic value of equity**:\n\n$$\\text{Intrinsic value of equity} = \\sum_{t = 1}^T \\left( \\frac{\\text{FCFE}} {(1 + k_E)^t}\\right) + \\frac{P_T} {(1 + k_E)^T}$$\n\nwhere $\\displaystyle P_T = \\frac{\\text{FCFE}_{T+1}} {k_E - g}$, assuming a constant-growth model, is the estimate of terminal value. And $\\text{WACC}$ is the weighted average cost of capital.\n\n## Summary\n- One approach to firm valuation is to focus on the firm\u2019s book value, either as it appears on the balance sheet or adjusted to reflect the current replacement cost of assets or the liquidation value. Another approach is to focus on the present value of expected future dividends.\n- The dividend discount model holds that the price of a share of stock should equal the present value of all future dividends per share, discounted at an interest rate commensurate with the risk of the stock.\n- The constant-growth version of the DDM asserts that if dividends are expected to grow at a constant rate forever, then the intrinsic value of the stock is determined by the formula\n$$V_0 = \\frac{D_1} {k-g}$$\n- This version of the DDM is simplistic in its assumption of a constant value of g. There are more sophisticated multistage versions of the model for more complex environments. When the constant-growth assumption is reasonably satisfied, however, the formula can be inverted to infer the market capitalization rate for the stock:\n$$d = \\frac{D_1} {P_0} + g$$\n- Stock market analysts devote considerable attention to a company\u2019s price\u2013earnings ratio. The P/E ratio is a useful measure of the market\u2019s assessment of the firm\u2019s growth opportunities. Firms with no growth opportunities should have a P/E ratio that is just the reciprocal of the capitalization rate, k. As growth opportunities become a progressively more important component of the total value of the firm, the P/E ratio will increase.Page 432\n- Many analysts form their estimates of a stock\u2019s value by multiplying their forecast of next year\u2019s EPS by a predicted P/E multiple. Some analysts mix the P/E approach with the dividend discount model. They use an earnings multiplier to forecast the terminal value of shares at a future date and add the present value of that terminal value with the present value of all interim dividend payments.\n- The free cash flow approach is the one used most in corporate finance. The analyst first estimates the value of the firm as the present value of expected future free cash flows to the entire firm and then subtracts the value of all claims other than equity. Alternatively, the free cash flows to equity can be discounted at a discount rate appropriate to the risk of the stock.\n- The models presented in this chapter can be used to explain or to forecast the behavior of the aggregate stock market. The key macroeconomic variables that determine the level of stock prices in the aggregate are interest rates and corporate profits.\n\n## KEY TERMS\nbook value  \nconstant-growth DDM  \ndividend discount model (DDM)  \ndividend payout ratio  \nearnings management  \nearnings retention ratio  \nintrinsic value  \nliquidation value  \nmarket capitalization rate  \nPEG ratio  \nplowback ratio  \npresent value of growth opportunities (PVGO)  \nprice\u2013earnings multiple  \nreplacement cost  \nTobin\u2019s q  \ntwo-stage DDM  \n\n# Assignment\n1. The market capitalization rate on the stock of Aberdeen Wholesale Company is $11\\%$. Its expected ROE is $12\\%$, and its expected EPS is $8$ dollar. If the firm's plowback ratio is $65\\%$, its P/E ratio will be \n> $$\\begin{align}\n\\text{Dividend payout ratio} = 1 - b &= 1 \u2013 65\\% = 35\\% \\\\\n\\text{Expected dividend} = E[D_1] &= 35\\% \u00d7 \\$8 = \\$2.80 \\\\ \n\\text{Growth rate} = g = \\text{ROE} \\times b &= 12\\% \\times 65\\% = 7.80\\% \\\\\n\\text{Value} = \\frac{D_1} {k - g} &= \\$2.80/(0.11 \u2013 0.078) = \\$87.50 \\\\\n\\text{P/E Ratio} = \\frac{\\text{Market Value}} {\\text{EPS}}&= \\$87.50/\\$8 = 10.94\n\\end{align}$$\n2. Weyerhaeuser Incorporated has a balance sheet that lists $\\$99$ million in assets, $\\$59$ million in liabilities, and $40$ million in common shareholders' equity. It has $1$ million common shares outstanding. The replacement cost of its assets is $112$ million. Its share price in the market is $53$. Its book value per share is \n> $$\\text{BVPS} = \\frac{\\text{Common shareholder's equity}} {\\text{Common Outstanding Shares}} = \\frac{40,000,000} {1,000,000} = 40$$\n3. Sanders, Inc., paid a $5$ bucks dividend per share last year and is expected to continue to pay out $70\\%$ of its earnings as dividends for the foreseeable future. If the firm is expected to generate a $14\\%$ return on equity in the future, and if you require a $16\\%$ return on the stock, the value of the stock is\n> $$\\begin{align}\ng = \\text{ROE} \\times b &= (1 - 70\\%) \\times 14\\% = 4.2\\% \\\\\nD_1 &= \\$5 \\times (1 + 4.2\\%) = \\$5.210 \\\\ \n\\text{Intrinsic value} &= \\frac{\\$5.210} {16\\% - 4.2\\%} = \\$44.15 \\\\\n\\end{align}$$\n4. A firm has a stock price of $\\$68.00$ per share. The firm's earnings are $\\$85$ million, and the firm has $20$ million shares outstanding. The firm has an ROE of $12\\%$ and a plowback of $75\\%$. What is the firm's PEG ratio?\n> $$\\begin{align}\n\\text{EPS} = \\frac{\\text{Total Earnings}} {\\text{Outstanding shares}} &= \\frac{\\$85,000,000} {20,000,000} = \\$4.25 \\\\\n\\text{P/E Ratio} = \\frac{\\text{Market Value}} {\\text{EPS}}&= \\$68.00/\\$4.25 = 16 \\\\\ng = \\text{ROE} \\times b &= 12\\% \\times 75\\% = 9.00\\% \\\\\n\\text{PEG} = \\frac{\\text{P/E Ratio}} {100 \\cdot g}&= \\frac{16.00} {9.00} = 1.78\n\\end{align}$$\n5. If a firm increases its plowback ratio, the P/E ratio would?\n> The answer cannot be determined from the information given. Because only when $\\text{ROE}>k$ , higher $b$ makes higher $\\text{P/E Ratio}$.\n6. A firm has current assets that could be sold for their book value of $\\$10$ million. The book value of its fixed assets is $\\$60$ million, but they could be sold for $\\$95$ million today. The firm has total debt at a book value of $\\$40$ million, but interest rate changes have increased the value of the debt to a current market value of $\\$\\$50$ million. This firm's market-to-book ratio is  \n>$$\\begin{array}{l|c|c}\n\\hline\n& \\text{Book Values} & \\text{Market Values} \\\\ \\hline\n\\text{Current Assets} & \\$10 & \\$10 \\\\ \\hline\n\\text{Fixed Assets} & \\$60 & \\$95 \\\\ \\hline\n\\text{Total Assets} & \\$70 & \\$105 \\\\ \\hline\n &  &  \\\\ \\hline\n\\text{Debt} & \\$40 & \\$50 \\\\ \\hline\n\\text{Equity, the only one not given} & \\$30 & \\$55 \\\\ \\hline\n\\text{Total Debt \\& Equity} & \\$70 & \\$105 \\\\ \\hline\n\\end{array} \\\\\n\\text{Equity} = \\text{Total Assets} - \\text{Debt}\\\\\n\\frac{\\text{Market Value of the Firm}} {\\text{Book Value of the Firm}} = \\frac{\\$55} {\\$30} = 1.8333\n$$\n7. A firm is planning on paying its first dividend of $2$ dollars three years from today. After that, dividends are expected to grow at $6\\%$ per year indefinitely. The stock's required return is $14\\%$. What is the intrinsic value of a share today?\n> $$\\begin{align}\n\\text{Intrinsic value after two years} = \\frac{\\text{Dividend after three years}} {k - g} &= \\frac{\\$2} {14\\% - 6\\%} = \\$25 \\\\\n\\text{Intrinsic value today} &= \\frac{\\$25} {(1 + 14\\%)^2}= \\$19.24\n\\end{align}$$\n8. Interior Airline is expected to pay a dividend of $\\$\\$3$ in the upcoming year. Dividends are expected to grow at the rate of $10\\%$ per year. The risk-free rate of return is $4\\%$, and the expected return on the market portfolio is $13\\%$. The stock of Interior Airline has a beta of $4$. Using the constant-growth DDM, the intrinsic value of the stock is\n> $$\\begin{align}\ng &= 10\\% \\\\\nk = r_f + \\beta[E(r_M) \u2013 r_f] &= 4\\% + 4(13\\% \u2212 4\\%) = 40\\% \\\\\nV_0 = \\frac{D_1} {k - g} = &= \\frac{\\$3} {40\\% \u2212 10\\%} = \\$10\n\\end{align}$$\n9. A firm has a stock price of $\\$54.75$ per share. The firm's earnings are $\\$75$ million, and the firm has $20$ million shares outstanding. The firm has an ROE of $15\\%$ and a plowback of $65\\%$. What is the firm's PEG ratio?\n...\n10. A firm has a stock price of $\\$\\$55$ per share and a P/E ratio of 75. If you buy the stock at this P/E and earnings fail to grow at all, how long should you expect it to take to just recover the cost of your investment?\n> $$\\begin{align}\n\\text{EPS} = \\frac{\\text{Stock Price}} {\\text{P/E Ratio}} &= \\frac{\\$54.75} {75} = \\$0.73333 \\text{ per year} \\\\\n\\text{Payback period} = \\frac{\\text{Stock Price}} {\\text{EPS}}&= \\frac{\\$55} {\\$0.73333 \\text{ per year} } = 75 \\text{ \nyear}\n\\end{align}$$\n", "meta": {"hexsha": "1a08b2c4605bab9f76328978bbd1218ce338fb4a", "size": 33357, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "FinMath/Intermediate Investment/Note_Chap13.ipynb", "max_stars_repo_name": "XavierOwen/Notes", "max_stars_repo_head_hexsha": "d262a9103b29ee043aa198b475654aabd7a2818d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-11-27T10:31:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-20T03:11:58.000Z", "max_issues_repo_path": "FinMath/Intermediate Investment/Note_Chap13.ipynb", "max_issues_repo_name": "XavierOwen/Notes", "max_issues_repo_head_hexsha": "d262a9103b29ee043aa198b475654aabd7a2818d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FinMath/Intermediate Investment/Note_Chap13.ipynb", "max_forks_repo_name": "XavierOwen/Notes", "max_forks_repo_head_hexsha": "d262a9103b29ee043aa198b475654aabd7a2818d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-14T19:57:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-14T19:57:23.000Z", "avg_line_length": 67.1167002012, "max_line_length": 460, "alphanum_fraction": 0.6176814462, "converted": true, "num_tokens": 8227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668537353746, "lm_q2_score": 0.12252320931407354, "lm_q1q2_score": 0.049446306092441404}}
{"text": "```python\n!pip install coremltools\n```\n\n    Requirement already satisfied: coremltools in /opt/anaconda3/envs/u2net/lib/python3.7/site-packages (4.1)\n    Requirement already satisfied: tqdm in /opt/anaconda3/envs/u2net/lib/python3.7/site-packages (from coremltools) (4.60.0)\n    Requirement already satisfied: packaging in /opt/anaconda3/envs/u2net/lib/python3.7/site-packages (from coremltools) (20.9)\n    Requirement already satisfied: attrs in /opt/anaconda3/envs/u2net/lib/python3.7/site-packages (from coremltools) (20.3.0)\n    Requirement already satisfied: attr in /opt/anaconda3/envs/u2net/lib/python3.7/site-packages (from coremltools) (0.3.1)\n    Requirement already satisfied: numpy<1.20,>=1.14.5 in /opt/anaconda3/envs/u2net/lib/python3.7/site-packages (from coremltools) (1.19.5)\n    Requirement already satisfied: scipy in /opt/anaconda3/envs/u2net/lib/python3.7/site-packages (from coremltools) (1.4.1)\n    Requirement already satisfied: six>=1.10.0 in /opt/anaconda3/envs/u2net/lib/python3.7/site-packages (from coremltools) (1.15.0)\n    Requirement already satisfied: sympy in /opt/anaconda3/envs/u2net/lib/python3.7/site-packages (from coremltools) (1.7.1)\n    Requirement already satisfied: protobuf>=3.1.0 in /opt/anaconda3/envs/u2net/lib/python3.7/site-packages (from coremltools) (3.14.0)\n    Requirement already satisfied: pyparsing>=2.0.2 in /opt/anaconda3/envs/u2net/lib/python3.7/site-packages (from packaging->coremltools) (2.4.7)\n    Requirement already satisfied: mpmath>=0.19 in /opt/anaconda3/envs/u2net/lib/python3.7/site-packages (from sympy->coremltools) (1.2.1)\n\n\n\n```python\n# Initialise packages \nfrom model import U2NETP\nimport coremltools as ct\nfrom coremltools.proto import FeatureTypes_pb2 as ft\nimport torch\nimport torch.nn as nn   \nfrom torch.autograd import Variable\nimport os\nimport numpy as np\nfrom PIL import Image\nfrom torchvision import transforms\nfrom skimage import io, transform\n```\n\n    WARNING:root:scikit-learn version 0.22.1 is not supported. Minimum required version: 0.17. Maximum required version: 0.19.2. Disabling scikit-learn conversion API.\n\n\n\n```python\nfrom torchvision import transforms\n\ndef save_output(pred, image):\n    print(pred.shape)\n    predict = pred\n    predict = predict.squeeze()\n    print(predict.shape)\n    predict_np = predict.cpu().data.numpy()\n    im = Image.fromarray(predict_np * 255).convert('RGB')\n    imo = im.resize((image.size[0],image.size[1]),resample=Image.BILINEAR)\n    \n    display(imo)\n```\n\n\n```python\n# Pre-processing\n\ndef tensor_lab(sample):\n    image = sample\n\n    tmpImg = np.zeros((image.shape[0],image.shape[1],3))\n    image = image/np.max(image)\n    \n    tmpImg[:,:,0] = (image[:,:,0]-0.485)/0.229\n    tmpImg[:,:,1] = (image[:,:,1]-0.456)/0.224\n    tmpImg[:,:,2] = (image[:,:,2]-0.406)/0.225\n\n        # change the r,g,b to b,r,g from [0,255] to [0,1]\n    tmpImg = tmpImg.transpose((2, 0, 1))\n\n    return torch.from_numpy(tmpImg)\n\ndef input_test_image(image_name):\n    inputs_test = Image.open(image_name)\n    inputs_test = inputs_test.resize((320, 320))\n    inputs_test = np.asarray(inputs_test)\n    inputs_test = tensor_lab(inputs_test)\n    inputs_test = inputs_test.unsqueeze_(0)\n    inputs_test = inputs_test.type(torch.FloatTensor)\n\n    return inputs_test\n```\n\n\n```python\nimage_name = \"test_data/test_images/0002-01.jpg\"\ninput_image = input_test_image(image_name)\nnet = U2NETP(3,1)\ndevice = torch.device('cpu')\nnet.load_state_dict(torch.load(\"saved_models/u2netp/u2netp.pth\", map_location=device))\nnet.cpu()\nnet.eval()\nd1,d2,d3,d4,d5,d6,d7 = net(input_image)\n```\n\n\n```python\nsave_output(d1, Image.open(image_name))\n```\n\n\n```python\n# Initialise Baseline UNETP model.\nnet = U2NETP(3,1)\ndevice = torch.device('cpu')\nnet.load_state_dict(torch.load(\"saved_models/u2netp/u2netp.pth\", map_location=device))\nnet.cpu()\nnet.eval()\n```\n\n\n\n\n    U2NETP(\n      (stage1): RSU7(\n        (rebnconvin): REBNCONV(\n          (conv_s1): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1): REBNCONV(\n          (conv_s1): Conv2d(64, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv2): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv3): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool3): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv4): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv5): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool5): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv6): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv7): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(2, 2), dilation=(2, 2))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv6d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv5d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv4d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv3d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv2d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1d): REBNCONV(\n          (conv_s1): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n      )\n      (pool12): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n      (stage2): RSU6(\n        (rebnconvin): REBNCONV(\n          (conv_s1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1): REBNCONV(\n          (conv_s1): Conv2d(64, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv2): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv3): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool3): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv4): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv5): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv6): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(2, 2), dilation=(2, 2))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv5d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv4d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv3d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv2d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1d): REBNCONV(\n          (conv_s1): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n      )\n      (pool23): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n      (stage3): RSU5(\n        (rebnconvin): REBNCONV(\n          (conv_s1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1): REBNCONV(\n          (conv_s1): Conv2d(64, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv2): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv3): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool3): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv4): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv5): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(2, 2), dilation=(2, 2))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv4d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv3d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv2d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1d): REBNCONV(\n          (conv_s1): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n      )\n      (pool34): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n      (stage4): RSU4(\n        (rebnconvin): REBNCONV(\n          (conv_s1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1): REBNCONV(\n          (conv_s1): Conv2d(64, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv2): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv3): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv4): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(2, 2), dilation=(2, 2))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv3d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv2d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1d): REBNCONV(\n          (conv_s1): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n      )\n      (pool45): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n      (stage5): RSU4F(\n        (rebnconvin): REBNCONV(\n          (conv_s1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1): REBNCONV(\n          (conv_s1): Conv2d(64, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv2): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(2, 2), dilation=(2, 2))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv3): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(4, 4), dilation=(4, 4))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv4): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(8, 8), dilation=(8, 8))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv3d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(4, 4), dilation=(4, 4))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv2d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(2, 2), dilation=(2, 2))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1d): REBNCONV(\n          (conv_s1): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n      )\n      (pool56): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n      (stage6): RSU4F(\n        (rebnconvin): REBNCONV(\n          (conv_s1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1): REBNCONV(\n          (conv_s1): Conv2d(64, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv2): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(2, 2), dilation=(2, 2))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv3): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(4, 4), dilation=(4, 4))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv4): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(8, 8), dilation=(8, 8))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv3d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(4, 4), dilation=(4, 4))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv2d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(2, 2), dilation=(2, 2))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1d): REBNCONV(\n          (conv_s1): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n      )\n      (stage5d): RSU4F(\n        (rebnconvin): REBNCONV(\n          (conv_s1): Conv2d(128, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1): REBNCONV(\n          (conv_s1): Conv2d(64, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv2): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(2, 2), dilation=(2, 2))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv3): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(4, 4), dilation=(4, 4))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv4): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(8, 8), dilation=(8, 8))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv3d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(4, 4), dilation=(4, 4))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv2d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(2, 2), dilation=(2, 2))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1d): REBNCONV(\n          (conv_s1): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n      )\n      (stage4d): RSU4(\n        (rebnconvin): REBNCONV(\n          (conv_s1): Conv2d(128, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1): REBNCONV(\n          (conv_s1): Conv2d(64, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv2): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv3): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv4): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(2, 2), dilation=(2, 2))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv3d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv2d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1d): REBNCONV(\n          (conv_s1): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n      )\n      (stage3d): RSU5(\n        (rebnconvin): REBNCONV(\n          (conv_s1): Conv2d(128, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1): REBNCONV(\n          (conv_s1): Conv2d(64, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv2): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv3): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool3): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv4): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv5): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(2, 2), dilation=(2, 2))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv4d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv3d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv2d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1d): REBNCONV(\n          (conv_s1): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n      )\n      (stage2d): RSU6(\n        (rebnconvin): REBNCONV(\n          (conv_s1): Conv2d(128, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1): REBNCONV(\n          (conv_s1): Conv2d(64, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv2): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv3): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool3): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv4): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv5): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv6): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(2, 2), dilation=(2, 2))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv5d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv4d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv3d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv2d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1d): REBNCONV(\n          (conv_s1): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n      )\n      (stage1d): RSU7(\n        (rebnconvin): REBNCONV(\n          (conv_s1): Conv2d(128, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1): REBNCONV(\n          (conv_s1): Conv2d(64, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv2): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv3): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool3): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv4): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv5): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (pool5): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)\n        (rebnconv6): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv7): REBNCONV(\n          (conv_s1): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(2, 2), dilation=(2, 2))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv6d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv5d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv4d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv3d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv2d): REBNCONV(\n          (conv_s1): Conv2d(32, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n        (rebnconv1d): REBNCONV(\n          (conv_s1): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n          (bn_s1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu_s1): ReLU(inplace=True)\n        )\n      )\n      (side1): Conv2d(64, 1, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n      (side2): Conv2d(64, 1, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n      (side3): Conv2d(64, 1, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n      (side4): Conv2d(64, 1, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n      (side5): Conv2d(64, 1, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n      (side6): Conv2d(64, 1, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n      (outconv): Conv2d(6, 1, kernel_size=(1, 1), stride=(1, 1))\n    )\n\n\n\n\n```python\n# Trace the model.\ninput_image = input_test_image(image_name)\ntraced_model = torch.jit.trace(net, input_image)\n```\n\n\n```python\n# Convert the model\n_inputs = ct.ImageType(\n    name= \"input_1\", \n    shape= input_image.shape, \n    bias=[-0.456/0.224,\n          -0.406/0.225,\n          -0.485/0.229],\n    scale=1.0/255.0\n    )\nmodel = ct.convert(traced_model, inputs=[_inputs])\n```\n\n    WARNING:root:Tuple detected at graph output. This will be flattened in the converted model.\n    Converting Frontend ==> MIL Ops: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589| 2507/2509 [00:04<00:00, 569.62 ops/s]\n    Running MIL optimization passes: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 18/18 [00:00<00:00, 18.46 passes/s]\n    Translating MIL ==> MLModel Ops: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2224/2224 [00:00<00:00, 12881.33 ops/s]\n\n\n\n```python\n# Add metadata\nmodel.short_description = \"U2-Net: Going Deeper with Nested U-Structure for Salient Object Detection\"\nmodel.license = \"Apache 2.0\"\nmodel.author = \"Qin, Xuebin and Zhang, Zichen and Huang, Chenyang and Dehghan, Masood and Zaiane, Osmar and Jagersand, Martin\"\n```\n\n\n```python\n# Rename inputs\nspec = model.get_spec()\nct.utils.rename_feature(spec, \"input_1\", \"in_0\")\nct.utils.rename_feature(spec,\"2169\",\"out_a0\")\nct.utils.rename_feature(spec,\"2170\",\"out_a1\")\nct.utils.rename_feature(spec,\"2171\",\"out_a2\")\nct.utils.rename_feature(spec,\"2172\",\"out_a3\")\nct.utils.rename_feature(spec,\"2173\",\"out_a4\")\nct.utils.rename_feature(spec,\"2174\",\"out_a5\")\nct.utils.rename_feature(spec,\"2175\",\"out_a6\")\nmodel = ct.models.MLModel(spec)\nmodel.save(\"creating_models/u2netp_temp.mlmodel\")\n```\n\n\n```python\n# Re-open model for modification\nmodel = ct.models.MLModel(\"creating_models/u2netp_temp.mlmodel\")\n```\n\n\n```python\n# Get the model specifications\nspec = model.get_spec()\n```\n\n\n```python\n# Change model input and save\ninput = spec.description.input[0]\ninput.type.imageType.colorSpace = ft.ImageFeatureType.BGR\ninput.type.imageType.height = 320 \ninput.type.imageType.width = 320\n\nct.utils.save_spec(spec, \"creating_models/u2netp_temp_new_input.mlmodel\")\n```\n\n\n```python\n# Re-open model for modification\nmodel = ct.models.MLModel(\"creating_models/u2netp_temp_new_input.mlmodel\")\nspec = model.get_spec()\nspec_layers = getattr(spec, spec.WhichOneof(\"Type\")).layers\noutput_layers = spec_layers[476:] # Get only the last output layers, may change with full-size U^2net\n```\n\n\n```python\n# Append new layers\nnew_layers = []\nlayernum = 0;\nfor layer in output_layers:\n    new_layer = spec_layers.add()\n    new_layer.name = 'out_p' + str(layernum)\n    new_layers.append('out_p' + str(layernum))\n\n    new_layer.activation.linear.alpha = 255\n    new_layer.activation.linear.beta = 0\n\n    new_layer.input.append('out_a' + str(layernum))\n    new_layer.output.append('out_p' + str(layernum))\n    output_description = next(x for x in spec.description.output if x.name==output_layers[layernum].output[0])\n    output_description.name = new_layer.name\n\n    layernum = layernum + 1\n```\n\n\n```python\n# Specify the outputs as grayscale images.\nfor output in spec.description.output: \n    if output.name not in new_layers: \n        continue\n    if output.type.WhichOneof('Type') != 'multiArrayType': \n        raise ValueError(\"%s is not a multiarray type\" % output.name) \n\n    array_shape = tuple(output.type.multiArrayType.shape) \n    # print(array_shape)\n    # print(output.type)\n\n\n    output.type.imageType.colorSpace = ft.ImageFeatureType.ColorSpace.Value('GRAYSCALE')\n    output.type.imageType.width = 320 \n    output.type.imageType.height = 320\n```\n\n\n```python\nupdated_model = ct.models.MLModel(spec)\nmodel.short_description = \"U2-Net: Going Deeper with Nested U-Structure for Salient Object Detection\"\nmodel.license = \"Apache 2.0\"\nmodel.author = \"Qin, Xuebin and Zhang, Zichen and Huang, Chenyang and Dehghan, Masood and Zaiane, Osmar and Jagersand, Martin\"\n\nupdated_model.save(\"updated_model.mlmodel\")\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "61f7801e7205ce8d2f8dc6df56a112f51093d349", "size": 152457, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "CoreML_Conversion_U2NETP.ipynb", "max_stars_repo_name": "jb-apps/U-2-Net", "max_stars_repo_head_hexsha": "c8016e05202853b0203d32254f49e44de908ea60", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CoreML_Conversion_U2NETP.ipynb", "max_issues_repo_name": "jb-apps/U-2-Net", "max_issues_repo_head_hexsha": "c8016e05202853b0203d32254f49e44de908ea60", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CoreML_Conversion_U2NETP.ipynb", "max_forks_repo_name": "jb-apps/U-2-Net", "max_forks_repo_head_hexsha": "c8016e05202853b0203d32254f49e44de908ea60", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-19T03:46:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-19T03:46:00.000Z", "avg_line_length": 140.2548298068, "max_line_length": 99480, "alphanum_fraction": 0.8202903114, "converted": true, "num_tokens": 14542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233683016710835, "lm_q2_score": 0.12592276811536138, "lm_q1q2_score": 0.0494041396882487}}
{"text": "# Underwater Image Restoration By Blue-Green Channels Dehazing and Red Channel Correction\n\n## 1. The Challenge and Proposed Solution\nCapturing clear underwater images is challenging due to various reasons namely,  <br>\n  - Physical properties of underwater environment <br>\n  - Effects of absorption and scattering <br>\n  - Varying attenuation of light in different wavelengths <br>\n    \n<figure>\n<center> </center>\n<figcaption align = \"center\"><b>Fig.1 -This figure plots the differeing light intensities in water [4]</figcaption>\n</figure> \n                                  \nAn underwater image can be decomposed into the superposition of a *direct*, *forward-scattering* and a *back-scattering* component. The forward scattering causes blurring of the image while the back-scattering masks the details of the senarios.  \n<br>\nWith the help of Fig.1, we make the following obsevations: <br>\n - Red light is more easily absorbed than blue or green light\n - The shorter wavelengths of green and blue light scatter more than the long wavelength of red light\n<br>\n    \nIn [4], the following method is proposed for de-hazing of underwater images - using a modified version the Dark Channel Prior method to first de-haze the blue and green channels followed by the Red channel correction using the *Gray World Assumption theory*.\n\n### 1.1. Flowchart \n<figure>\n<center> </center>\n<figcaption align = \"center\"><b>Fig.2 -This figures depticts the flowchart for step-by-step implementation of the proposed method [4]</figcaption>\n</figure> \n           \n \n\n\n```python\nfrom IPython.display import HTML\nfrom IPython.display import display\n\ntag = HTML('''\nTo show/hide this cell's raw code input, click <a href=\"javascript:code_toggle()\">here</a>.''')\ndisplay(tag)\n```\n\n\n\nTo show/hide this cell's raw code input, click <a href=\"javascript:code_toggle()\">here</a>.\n\n\n\n```python\nimport os\nimport datetime\nimport numpy as np\nimport cv2\nimport natsort\nimport matplotlib.pyplot as plt\nimport io, os, sys, types\nfrom IPython import get_ipython\nfrom nbformat import read\nfrom IPython.core.interactiveshell import InteractiveShell\n\ndef find_notebook(fullname, path=None):\n    \"\"\"find a notebook, given its fully qualified name and an optional path\n    \n    This turns \"foo.bar\" into \"foo/bar.ipynb\"\n    and tries turning \"Foo_Bar\" into \"Foo Bar\" if Foo_Bar\n    does not exist.\n    \"\"\"\n    name = fullname.rsplit('.', 1)[-1]\n    if not path:\n        path = ['']\n    for d in path:\n        nb_path = os.path.join(d, name + \".ipynb\")\n        if os.path.isfile(nb_path):\n            return nb_path\n        # let import Notebook_Name find \"Notebook Name.ipynb\"\n        nb_path = nb_path.replace(\"_\", \" \")\n        if os.path.isfile(nb_path):\n            return nb_path\n            \nclass NotebookLoader(object):\n    \"\"\"Module Loader for Jupyter Notebooks\"\"\"\n    def __init__(self, path=None):\n        self.shell = InteractiveShell.instance()\n        self.path = path\n    \n    def load_module(self, fullname):\n        \"\"\"import a notebook as a module\"\"\"\n        path = find_notebook(fullname, self.path)\n        \n        print (\"importing Jupyter notebook from %s\" % path)\n                                       \n        # load the notebook object\n        with io.open(path, 'r', encoding='utf-8') as f:\n            nb = read(f, 4)\n\n        mod = types.ModuleType(fullname)\n        mod.__file__ = path\n        mod.__loader__ = self\n        mod.__dict__['get_ipython'] = get_ipython\n        sys.modules[fullname] = mod\n        \n        save_user_ns = self.shell.user_ns\n        self.shell.user_ns = mod.__dict__\n        \n        try:\n          for cell in nb.cells:\n            if cell.cell_type == 'code':\n                # transform the input to executable Python\n                code = self.shell.input_transformer_manager.transform_cell(cell.source)\n                # run the code in themodule\n                exec(code, mod.__dict__)\n        finally:\n            self.shell.user_ns = save_user_ns\n        return mod\n\nclass NotebookFinder(object):\n    \"\"\"Module finder that locates Jupyter Notebooks\"\"\"\n    def __init__(self):\n        self.loaders = {}\n    \n    def find_module(self, fullname, path=None):\n        nb_path = find_notebook(fullname, path)\n        if not nb_path:\n            return\n        \n        key = path\n        if path:\n            # lists aren't hashable\n            key = os.path.sep.join(path)\n        \n        if key not in self.loaders:\n            self.loaders[key] = NotebookLoader(path)\n        return self.loaders[key]\n\nsys.meta_path.append(NotebookFinder())\n\n# Importing the required libraries and supporting functions\nfrom extras.DetermineDepth import determineDepth\nfrom extras.TransmissionEstimation import getTransmission\nfrom extras.getAdaptiveSceneRadiance import AdaptiveSceneRadiance\nfrom extras.getAtomsphericLight import getAtomsphericLight\nfrom extras.sceneRadianceGb import sceneRadianceGB\nfrom extras.sceneRadianceR import sceneradiance\nfrom extras.GuidedFilter import GuidedFilter\nfrom extras.guidedfilter_he import guided_filter_he\n\n```\n\n    importing Jupyter notebook from C:\\Users\\Giridhar\\Downloads\\UnderwaterDeHaze_Lalitha\\extras\\DetermineDepth.ipynb\n    importing Jupyter notebook from C:\\Users\\Giridhar\\Downloads\\UnderwaterDeHaze_Lalitha\\extras\\TransmissionEstimation.ipynb\n    importing Jupyter notebook from C:\\Users\\Giridhar\\Downloads\\UnderwaterDeHaze_Lalitha\\extras\\getAdaptiveSceneRadiance.ipynb\n    importing Jupyter notebook from C:\\Users\\Giridhar\\Downloads\\UnderwaterDeHaze_Lalitha\\extras\\getAtomsphericLight.ipynb\n    importing Jupyter notebook from C:\\Users\\Giridhar\\Downloads\\UnderwaterDeHaze_Lalitha\\extras\\sceneRadianceGb.ipynb\n    importing Jupyter notebook from C:\\Users\\Giridhar\\Downloads\\UnderwaterDeHaze_Lalitha\\extras\\sceneRadianceR.ipynb\n    importing Jupyter notebook from C:\\Users\\Giridhar\\Downloads\\UnderwaterDeHaze_Lalitha\\extras\\GuidedFilter.ipynb\n    importing Jupyter notebook from C:\\Users\\Giridhar\\Downloads\\UnderwaterDeHaze_Lalitha\\extras\\guidedfilter_he.ipynb\n\n\n\n```python\ntag = HTML('''\nTo show/hide this cell's raw code input, click <a href=\"javascript:code_toggle()\">here</a>.''')\ndisplay(tag)\n\ndef  refinedtransmission(transmission, img):\n    # This function refines the transmission by using a guided filter to remove the halo effects\n    gimfiltR = 50  # The size of the radius when guiding the filter\n    eps = 10 ** -3  #The value of epsilon during bootstrap filtering\n\n    guided_filter = GuidedFilter(img, gimfiltR, eps)\n    transmission[:,:,0] = guided_filter.filter(transmission[:,:,0])\n    transmission[:,:,1] = guided_filter.filter(transmission[:,:,1])\n    transmission = np.clip(transmission, 0.1, 0.9)\n\n\n    return transmission\n```\n\n\n\nTo show/hide this cell's raw code input, click <a href=\"javascript:code_toggle()\">here</a>.\n\n\n\n```python\ntag = HTML('''\nTo show/hide this cell's raw code input, click <a href=\"javascript:code_toggle()\">here</a>.''')\ndisplay(tag)\n\ndef adapexpMap(img, sceneRadiance, Lambda, blockSize):\n    # Applied as the final step of the image correction process where the regions that are either too bright or too dark are\n    # adjusted accordingly to provide a balanced scene\n    minValue = 10 ** -2\n    img = np.uint8(img)\n    sceneRadiance = np.uint8(sceneRadiance)\n\n    yj_cr_cb = cv2.cvtColor(sceneRadiance, cv2.COLOR_BGR2YCrCb)\n    yi_cr_cb = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)\n    normyj_cr_cb = (yj_cr_cb - yj_cr_cb.min()) / (yj_cr_cb.max() - yj_cr_cb.min())\n    normyi_cr_cb = (yi_cr_cb - yi_cr_cb.min()) / (yi_cr_cb.max() - yi_cr_cb.min())\n    Yi = normyi_cr_cb[:, :, 0]\n    Yj = normyj_cr_cb[:, :, 0]\n    Yi = np.clip(Yi, minValue,1)\n    Yj = np.clip(Yj, minValue,1)\n\n    S = (Yj * Yi + 0.3 * Yi ** 2) / (Yj ** 2 + 0.3 * Yi ** 2)\n\n    filR = 50  # The size of the radius when guiding the filter\n    eps = 10 ** -3  # The value of epsilon during bootstrap filtering\n\n    guided_filter = GuidedFilter(yi_cr_cb, filR, eps)\n\n    refS = guided_filter.filter(S)\n\n    S_three = np.zeros(img.shape)\n    S_three[:, :, 0] = S_three[:, :, 1] = S_three[:, :, 2] = refS\n\n    return S_three\n```\n\n\n\nTo show/hide this cell's raw code input, click <a href=\"javascript:code_toggle()\">here</a>.\n\n\n## 2. Blue-Green Channels Dehazing \n\nNow, the attenuation of the blue and green channels result from scattering which is similar to the type of attenuation seen in tradionally terrestrial images. Based on this intuition, we can then describe the underwater imaging model described as  <br><br>\n$ \\begin{align}\nI^{c}(x) = J^{c}(x)t(x) + B^{c}(1-t(x)), c \\in \\{g,b\\}\n\\end{align} $ <br><br>\nHere, <br>\n    $I(x)$ : Observed image <br>\n    $J(x)$ : Restored image <br>\n    $B$ : Background light <br>\n    $t(x) \\in [0,1]$ is the medium transmission map based on camera parameters\n<br>\n<br>\nThe Background light *B* can be estimated from the knowledge that the Red channel attuates much faster than the green and blue channels underwater. First, the largest difference *D(x)* is computed by finding the difference between the maximum intensity of the red channel and the maximum intensity of the green and blue channels. <br><br>\n$ \\begin{align}\nD(x) = \\max_{ x \\in \\Omega,c \\in r } I^{c}(x) - \\max_{ x \\in \\Omega,c \\in \\{g,b\\} } I^{c}(x)\n\\end{align} $ <br><br>\n\nHere, $\\Omega$ corresponds to a local patch in the image. From this, *B* is estimated as:\n<br>\n<br>\n$ \\begin{align}\nB^{c} = avg(I^{c}(arg \\min_{x} D(x))), c \\in \\{g,b\\}\n\\end{align} $ <br><br>\n\n\n### 2.1. Transmission Map for Blue and Green Channels\nBased on the Rayleigh scattering theory the following assumptions are valid: \n - Blue and Green channels have equal attenuation underwater\n - Transmission map for a given patch is same for both channels \n \n<br>\nTo find the transmission map we minimise the imaging model equation over $c$ and simplify based on Dark Channel Prior theory. Rearranging the resulting equation we get: <br>\n$ \\begin{align}\nt(x) = 1 - \\min_{c \\in \\{g,b\\}}(\\min_{x\\in\\Omega}(\\frac{I^{c}(x)}{B^{c}}))\n\\end{align} $ <br>\n<figure>\n<center> </center>\n<figcaption align = \"center\"><b>Fig.3- Medium Transmission map (a) Original underwater image (b) Coarse transmission map (c) Refined medium transmission maps [4]</figcaption>\n</figure> \n\nFig.3(b) shows *halo* effects and block artifacts seen in the coarse tranmission map. This is because the coarse transmission map is a rough estimate over a patch of image. To fine-tune the transmission map, the coarse estimates are refined with the help of the guided filter which results in a more clear *t(x)* as seen in Fig.3(c).\n\n### 2.2. Restored haze-free Blue-Green Channels\nThe last step to the de-hazing process of the Blue-Green channels is restoring the respective channels after correction. This is done by a simple back-substitution of the estimated parameters into the original image equation as\n<br><br>\n$ \\begin{align}\nJ^{c}(x) = \\frac{I^{c}(x)-B^{c}}{t^{c}(x)}+B^{c}, c\\in\\{g,b\\}\n\\end{align} $ <br>\nwhere $J^{c}(x)$ represents the restored channel.\n\n## 3. Red Channel Correction\nIt is not straightforward to calculate the absorption rate for red light. Therefore the red light correction is done based on the Gray-World assumption theory which states that the average value of object color in an ideal image is gray. The following assumption forms the basis for the red channel correction process:\n<br><br>\n $ \\begin{align}\n(avgRr + avgBr +avgGr)/3 = 0.5\n\\end{align} $ <br>\n<br>\nHere, *avgR*,*avgB* and *avgG* are the normalized average values of the respective recorvered channels. \nThen, the average value of the recovered red channel is estimated as:<br><br>\n $ \\begin{align}\navgRr = 1.5 - avgBr - avgGr\n\\end{align} $ <br>\n<br>\nThe estimated *compensation coefficient*, $\\delta$ is \n<br>\n$ \\begin{align}\n\\delta = avgRr / avgR\n\\end{align} $ <br>\n<br>\nwhere, <br>\n$avgR$ : Normalised *average* value of original red channel\n<br><br>\nFinally, the recovered red channel is found as:<br>\n<br>\n$ \\begin{align}\nRrec = R .* \\delta\n\\end{align} $ <br>\n<br>\n\n## 4. Adaptive Exposure Map Estimation\nSome bright and dark parts of the image become too dark or bright after the dehazing and correction process. To restore the right amount of brightness/darkness an Adaptive Exposure Map is implemented on the image. This Adaptive Exposure Map $s(x)$ is obtained by solving an optimization problem. \n<br>\n<br>\n$ \\begin{align}\n\\min_{s}\\sum_{x}\\{[1-s(x)\\frac{Y_{J(x)}}{Y_{I(x)}}]^{2} + \\lambda[s(x) - 1]^{2}\\} + \\phi(s)\n\\end{align} $ <br>\n<br>\nHere, <br>\n$s(x)$: The adaptive exposure map <br>\n$Y_{J}$: Illumination intensity of restored image <br>\n$\\lambda$: A tuning hyperparameter set to $0.3$ <br>\n$\\phi(.)$: Smoothness regularization <br><br>\n\nThis optimization problem can be solved in two steps:\n - Solve $s(x)$ without the smoothness rgularization\n - Apply guided filter to smooth the solution\n<br><br>\n\nThe output after optimization can be obtained as: <br><br>\n$ \\begin{align}\nOutputExp = J^{c}(x).*s(x), c\\in\\{r,g,b\\}\n\\end{align} $ <br>\n<br>\n\n\n```python\nfrom IPython.display import HTML\nfrom IPython.display import display\n\ntag = HTML('''\nTo show/hide this cell's raw code input, click <a href=\"javascript:code_toggle()\">here</a>.''')\ndisplay(tag)\n\nif __name__ == '__main__':\n    pass\nstarttime = datetime.datetime.now() #Records the time taken to run the code \n\nfolder = (os.path.abspath(\".\"))\npath = folder + \"/Datasets\"\nfiles = os.listdir(path)\nfiles =  natsort.natsorted(files)\n\nfor i in range(len(files)):\n    file = files[i]\n    filepath = path + \"/\" + file\n    prefix = file.split('.')[0]\n    if os.path.isfile(filepath):\n        img1 = cv2.imread(folder +'/Datasets/' + file)\n        img = (img1 - img1.min()) / (img1.max() - img1.min()) * 255\n        blockSize = 9\n        largest_diff = determineDepth(img, blockSize)\n        #print(largest_diff)\n        AtomsphericLight, AtomsphericLightGB, AtomsphericLightRGB = getAtomsphericLight(largest_diff, img)\n       # print('AtomsphericLightRGB',AtomsphericLightRGB)\n        transmission = getTransmission(img, AtomsphericLightRGB, blockSize)\n        transmission = refinedtransmission(transmission, img)\n\n        sceneRadiance_GB = sceneRadianceGB(img, transmission, AtomsphericLightRGB)\n        sceneRadiance = sceneradiance(img, sceneRadiance_GB)\n\n        S_x = adapexpMap(img, sceneRadiance, Lambda=0.3, blockSize=blockSize)\n        sceneRadiance_adap = AdaptiveSceneRadiance(sceneRadiance, S_x)\n\n        sceneRadiance_adap = cv2.cvtColor(sceneRadiance_adap, cv2.COLOR_BGR2RGB)\n        img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)\n        plt.subplot(1, 2, 1)\n        plt.imshow(img1)\n        plt.gca().set_title('Original')\n        plt.subplot(1, 2, 2)\n        plt.imshow(sceneRadiance_adap)\n        plt.gca().set_title('Corrected')\n        plt.show()\n\nEndtime = datetime.datetime.now()\nTime = Endtime - starttime\nprint('Time', Time)\n```\n\n## 5. Comparison to Other Methods\nIn order to further highleten the requirement for the three color channels to be given the treatment as discussed above for underwater images we compare the results of the Green-Blue channel dehazing, Red channel correction method with the dehazing algorithms proposed for traditionally teresstrial images.\n<br>\n\n\n<br>\nHere, we see that the traditional method of Dark Channel Prior gives poor results when it comes to de-hazing and color correcting an underwater image. This once again affirms our observation that different datasets require different methods for de-hazing and color correction. \n\n\n```python\n\n```\n", "meta": {"hexsha": "0248a419a8b5cac32ab5f4629dc1956283583e56", "size": 789908, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "projects/Single_Image_dehazing/UnderwaterDehaze/main.ipynb", "max_stars_repo_name": "bioshape-lab/ece278a", "max_stars_repo_head_hexsha": "01edbee215b11b7dcd6b1889278f067effe31001", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2022-01-03T21:54:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T16:07:02.000Z", "max_issues_repo_path": "projects/Single_Image_dehazing/UnderwaterDehaze/main.ipynb", "max_issues_repo_name": "bioshape-lab/ece278a", "max_issues_repo_head_hexsha": "01edbee215b11b7dcd6b1889278f067effe31001", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2022-01-05T21:23:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T04:22:51.000Z", "max_forks_repo_path": "projects/Single_Image_dehazing/UnderwaterDehaze/main.ipynb", "max_forks_repo_name": "bioshape-lab/ece278a", "max_forks_repo_head_hexsha": "01edbee215b11b7dcd6b1889278f067effe31001", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2022-01-03T20:30:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T04:10:48.000Z", "avg_line_length": 1043.4715984148, "max_line_length": 138572, "alphanum_fraction": 0.9527501937, "converted": true, "num_tokens": 4052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.09947022055603118, "lm_q1q2_score": 0.04934656263395848}}
{"text": "# <center>Efficient multigrid methods for high-order nonlinear solid mechanics on emerging architectures</center>\n\n<br>\n<br>\n<br>\n\n## <center>Rezgar Shakeri<sup>1</sup>, \n<br>\n<center>Valeria Barra<sup>2</sup>, Natalie Beams<sup>3</sup>, Jed Brown<sup>4</sup>, Yohann Dudouit<sup>5</sup>, Karen Stengel<sup>4</sup>, Jeremy L. Thompson<sup>4</sup></center>  \n\n<br>\n  \n<center><sub><sup><sup>1</sup> Department of Civil Engineering, CU Boulder</sup></sub></center>  \n<center><sub><sup><sup>2</sup> Department of Environmental Science and Engineering, California Institute of Technology</sup></sub></center>\n<center><sub><sup><sup>3</sup> Innovative Computing Laboratory, University of Tennessee</sup></sub></center>  \n<center><sub><sup><sup>4</sup> Department of Computer Science, CU Boulder</sup></sub></center>  \n<center><sub><sup><sup>5</sup> Lawrence Livermore National Laboratory</sup></sub></center>  \n\n<br>\n<br>\n<br>\n\n<center>Copper-Iterative, 07 Apr 2022</center>\n\n\n```python\nfrom IPython.display import SVG, Video, HTML, IFrame\n```\n\n# Outline\n\n### Why Matrix Free ?\n\n### Model Equations\n\n* Neo-Hookean hyperelasticity at finite strain\n* Initial vs Current Configuration\n\n### Matrix Free FE\n\n* Math\n* libCEED\n\n### P-Multigrid\n\n### Results\n\n\n\n\n# Why Matrix Free ?\n\n\n\n* Modern hardware does 10 flops per byte.\n* Matrix-free methods store and move less data, compute faster.\n* The Jacobian of a non-linear operator rapidly loses the sparsity and the number of nonzero entries per dof grows with $p^d$ as the order $p$ of basis function increases in $d$ dimension\n\n# Model Equations\n\n* Strong form\n\\begin{equation}\n-\\nabla_X \\cdot \\boldsymbol{P} - \\rho_0 \\boldsymbol{g} = 0\n\\end{equation}\nwhere $\\boldsymbol{P}=\\boldsymbol{FS}$ and\n$$\n\\color{blue}{\n\\boldsymbol{S}=\\lambda \\, \\log J \\, \\boldsymbol{C}^{-1} + \\mu \\left( \\boldsymbol{I} - \\boldsymbol{C}^{-1} \\right).}\n$$\n\n* Variational form ($\\color{red}{\\text{Initial}}$ configuration)\n\\begin{equation}\n\\int_{\\Omega_0}{\\nabla_X \\boldsymbol{v} \\colon \\boldsymbol{FS}} \\, dV \n - \\int_{\\Omega_0}{\\boldsymbol{v} \\cdot \\rho_0 \\boldsymbol{g}} \\, dV\n = 0, \\quad \\forall \\boldsymbol v \\in \\mathcal V,\n\\end{equation}\n\n* Variational form ($\\color{red}{\\text{Current}}$ configuration)\n\\begin{equation}\n\\int_{\\Omega_0}{\\nabla_x \\boldsymbol{v} \\colon \\boldsymbol{\\tau}} \\, dV \n - \\int_{\\Omega_0}{\\boldsymbol{v} \\cdot \\rho_0 \\boldsymbol{g}} \\, dV\n = 0, \\quad \\forall \\boldsymbol v \\in \\mathcal V,\n\\end{equation}\nwhere\n$$\n\\color{teal}{\n\\boldsymbol{\\tau}=\\lambda \\, \\log J \\, \\boldsymbol{I} + \\, \\mu \\left( \\boldsymbol{b}-\\boldsymbol{I} \\right).}\n$$\n\n\n\n\n\n\n### Matrix-free Finite Element Formulation\n\n\\begin{gather*}\n    v^T F(u) \\sim \\int_\\Omega v \\cdot \\color{olive}{f_0(u, \\nabla u)} + \\nabla v \\!:\\! \\color{olive}{f_1(u, \\nabla u)} \\quad\n    v^T J du \\sim \\int_\\Omega \\begin{bmatrix} v \\\\ \\nabla v \\end{bmatrix}^T \\color{teal}{\\begin{bmatrix} f_{0,0} & f_{0,1} \\\\ f_{1,0} & f_{1,1} \\end{bmatrix}}\n    \\begin{bmatrix} du \\\\ \\nabla du \\end{bmatrix} \\\\\n\\end{gather*}\n\n\n\n### [libCEED](https://libceed.readthedocs.io): Efficient Extensible Discretization\n\n\n\n\n* <font color='red'>$\\mathcal P$</font>: Process decomposition,\n\n* $\\mathcal E$</font> : Element restriction/assembly operator\n\n* <font color='blue'>$B$</font> : Basis (DoFs-to-Qpts) evaluator, \n\n* <font color='green'>$D$</font> : Operator at quadrature point- Qfunction ($f_0, f_1, f_{0,0},...$)\n\n## [libCEED](https://libceed.readthedocs.io): fast algebra for finite elements\n\n* Single source vanilla C for QFunctions\n\n* Backend plugins with run-time selection\n    * e.g., `./bps -ceed /gpu/cuda`\n\n* Same source code can call multiple CEEDs with different backends\n\n* Open source (BSD-2 license) C library with Fortran, Python, Julia, and Rust interfaces\n\n* Available via MFEM, PETSc, Nek5000\n\n\n\n\n# P-Multigrid\n\n* h-multigrid vs p-multigrid\n\n\n\n\n* 2nd order Chebyshev/Jacobi iteration in the range $[0.1\\lambda_{max}, 1.1\\lambda_{max}]$\n* $\\lambda_{max}$ estimate eigenvalue of $\\left(\\text{diag}\\boldsymbol{A}_f \\right)^{-1}\\boldsymbol{A}_f$\n* AMG use only information of the matrix sparsity and its entries of the assembled operators\n\n\n\n# Results\n\n* Schwarz Primitive mesh, left wall fixed, thickness 0.2 and 0.05, $Q_1, Q_2, Q_3$ elements \n\n\n\n\n# Assembled vs Matrix-Free on Lassen machine\n\n\n\n* Matrix-free becomes more efficient as the order increases\n\n* Both are latency-limited for smaller problem size (left side of figure)\n\n* Even for linear element, efficiency of matrix-free grows as DoFs increases\n\n# Total nonlinear solve efficiency on different machines\n\n\n\n* $Q_3$ elements using matrix-free\n* Newton-Krylov with p-MG preconditioning and Boomer-AMG coarse solve\n* For example in 10 seconds total time, we can solve 0.6 MDoFs/s/GPU on Perlmutter, so the target problem would be scaled to about 6 MDoFs/GPU\n\n# Flame Graph\n\n\n```python\nIFrame(\"schwarz-q2-cuda-flame.svg\", width=\"2000\", height=\"200\")\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n# high-order FE in engineering problem\n\n* mesh A\n\n\n\n* mesh B\n\n\n\n\n\n\n\n\n\n\n# Future works\n\n## Buckling problem\n\n\n\n* implement arc-length method\n\n# ratel\n\n\n\n[https://gitlab.com/micromorph/ratel](https://gitlab.com/micromorph/ratel)\n\n\n", "meta": {"hexsha": "84898eddc51040ae0330cbaa95c4867bd171a44d", "size": 15914, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "copper-2022/copper-2022.ipynb", "max_stars_repo_name": "rezgarshakeri/talk", "max_stars_repo_head_hexsha": "8b9dd916b9b7adee7f8c1267739b19a08e8ed6ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "copper-2022/copper-2022.ipynb", "max_issues_repo_name": "rezgarshakeri/talk", "max_issues_repo_head_hexsha": "8b9dd916b9b7adee7f8c1267739b19a08e8ed6ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "copper-2022/copper-2022.ipynb", "max_forks_repo_name": "rezgarshakeri/talk", "max_forks_repo_head_hexsha": "8b9dd916b9b7adee7f8c1267739b19a08e8ed6ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4374079529, "max_line_length": 193, "alphanum_fraction": 0.5049013447, "converted": true, "num_tokens": 1613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.10521054021012236, "lm_q1q2_score": 0.04932171507278887}}
{"text": "# **CS224W - Colab 5**\n\nIn this Colab, we will shift our focus from homogenous graphs to heterogeneous graphs. Heterogeneous graphs extend the traditional homogenous graphs that we have been working with by incorperating different node and edge types. This additional information allows us to extend the graph neural nework models that we have worked with before. Namely, we can apply heterogenous message passing, where different message types now exist between different node and edge type relationships. \n\nIn this notebook, we will first learn how to transform NetworkX graphs into DeepSNAP representations. Then, we will dive deeper into how DeepSNAP stores and represents heterogeneous graphs as PyTorch Tensors.\n\nLastly, we will build our own heterogenous graph neural netowrk models using PyTorch Geometric and DeepSNAP. We will then apply our models for a node property prediction task; specifically, we will evaluate these models on the heterogeneous ACM node prediction dataset.\n\n**Note**: Make sure to **sequentially run all the cells in each section**, so that the intermediate variables / packages will carry over to the next cell\n\nHave fun and good luck on Colab 5 :)\n\n# Device\nYou might need to use GPU for this Colab.\n\nPlease click `Runtime` and then `Change runtime type`. Then set the `hardware accelerator` to **GPU**.\n\n# Installation\n\n\n```python\n# Install torch geometric\nimport os\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  !pip install torch-scatter -f https://data.pyg.org/whl/torch-1.10.0+cu111.html\n  !pip install torch-sparse -f https://data.pyg.org/whl/torch-1.10.0+cu111.html\n  !pip install torch-geometric\n  !pip install -q git+https://github.com/snap-stanford/deepsnap.git\n  !pip install -U -q PyDrive\n```\n\n\n```python\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  !nvcc --version\n  !python -c \"import torch; print(torch.version.cuda)\"\n```\n\n\n```python\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  import torch\n  print(torch.__version__)\n  import torch_geometric\n  print(torch_geometric.__version__)\n```\n\n# DeepSNAP Basics\n\nIn previous Colabs we used both of graph class (NetworkX) and tensor (PyG) representations of graphs separately. The graph class `nx.Graph` provides rich analysis and manipulation functionalities, such as the clustering coefficient and PageRank. To feed the graph into the model, we need to transform the graph into tensor representations including edge tensor `edge_index` and node attributes tensors `x` and `y`. But only using tensors (as the graphs formatted in PyG `datasets` and `data`) will make many graph manipulations and analysis less efficient and harder. So, in this Colab we will use DeepSNAP which combines both representations and offers a full pipeline for GNN training / validation / testing.\n\n\nIn general, [DeepSNAP](https://github.com/snap-stanford/deepsnap) is a Python library to assist efficient deep learning on graphs. DeepSNAP features in its support for flexible graph manipulation, standard pipeline, heterogeneous graphs and simple API.\n\n1. DeepSNAP is easy to be used for the sophisticated graph manipulations, such as feature computation, pretraining, subgraph extraction etc. during/before the training.\n2. In most frameworks, standard pipelines for node, edge, link, graph-level tasks under inductive or transductive settings are left to the user to code. In practice, there are additional design choices involved (such as how to split dataset for link prediction). DeepSNAP provides such a standard pipeline that greatly saves repetitive coding efforts, and enables fair comparision for models.\n3. Many real-world graphs are heterogeneous graphs. But packages support for heterogeneous graphs, including data storage and flexible message passing, is lacking. DeepSNAP provides an efficient and flexible heterogeneous graph that supports both the node and edge heterogeneity.\n\n[DeepSNAP](https://github.com/snap-stanford/deepsnap) is a newly released project and it is still under development. If you find any bugs or have any improvement ideas, feel free to raise issues or create pull requests on the GitHub directly :)\n\nIn this Colab, we will focus on learning using Heterogeneous Graphs. Not many libraries are able to handle heterogeneous graphs, but DeepSNAP handles them quite elegantly, which is why we're introducing it here!\n\n# 1) DeepSNAP Heterogeneous Graph\n\nFirst, we will explore how to transform a NetworkX graph into the format supported by DeepSNAP. \n\nIn DeepSNAP we have three levels of attributes. We can have **node level** attributes including `node_feature` and `node_label`. The other two levels of attributes are graph and edge attributes. The usage is similar to the node level one except that the feature becomes `edge_feature` or `graph_feature` and label becomes `edge_label` or `graph_label` etc.\n\nDeepSNAP extends its traditional graph representation to include heterogeneous graphs by including the following graph property features:  \n* `node_feature`: The feature of each node (`torch.tensor`)\n* `edge_feature`: The feature of each edge (`torch.tensor`)\n* `node_label`: The label of each node (`int`)\n* `node_type`: The node type of each node (`string`)\n* `edge_type`: The edge type of each edge (`string`)\n\nwhere the key **new** features we add are `node_type` and `edge_type`, which enables us to perform heterogenous message passing.\n\nFor this first question we will work with the familiar [karate club graph](https://networkx.github.io/documentation/stable/auto_examples/graph/plot_karate_club.html) seen in Colab 1. To start, since each node in the graph belongs to one of two clubs (club \"Mr. Hi\" or club \"Officer\"), we will treat the club as the `node_type`. The code below demonstrates how to differentiate the nodes in the NetworkX graph.\n\n\n\n```python\nimport networkx as nx\nfrom networkx.algorithms.community import greedy_modularity_communities\nimport matplotlib.pyplot as plt\nimport copy\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  from pylab import show\n  G = nx.karate_club_graph()\n  community_map = {}\n  for node in G.nodes(data=True):\n    if node[1][\"club\"] == \"Mr. Hi\":\n      community_map[node[0]] = 0\n    else:\n      community_map[node[0]] = 1\n  node_color = []\n  color_map = {0: 0, 1: 1}\n  node_color = [color_map[community_map[node]] for node in G.nodes()]\n  pos = nx.spring_layout(G)\n  plt.figure(figsize=(7, 7))\n  nx.draw(G, pos=pos, cmap=plt.get_cmap('coolwarm'), node_color=node_color)\n  show()\n```\n\n### Question 1.1: Assigning Node Type and Node Features \n\nUsing the `community_map` dictionary and graph `G` from above, add node attributes `node_type` and `node_label` to the graph G. Namely, for `node_type` assign nodes in the \"Mr. Hi\" club to a node type `n0` and nodes in club \"Officer\" a node type `n1`. Note: the node type should be a `string` property.\n\nThen for `node_label`, assign nodes in \"Mr. Hi\" club to a `node_label` `0` and nodes in club \"Officer\" a `node_label` of `1`.\n\nLastly, assign every node the *tensor* feature vector $[1, 1, 1, 1, 1]$. \n\n**Hint**: Look at the NetworkX function `nx.classes.function.set_node_attributes`.\n\n**Note**: This question is not specifically graded but is important for later questions.\n\n\n```python\nimport torch\n\ndef assign_node_types(G, community_map):\n  # TODO: Implement a function that takes in a NetworkX graph\n  # G and community map assignment (mapping node id --> 0/1 label)\n  # and adds 'node_type' as a node_attribute in G.\n\n  ############# Your code here ############\n  ## (~2 line of code)\n  ## Note\n  ## 1. Look up NetworkX `nx.classes.function.set_node_attributes`\n  ## 2. Look above for the two node type values!\n\n  pass\n\n  #########################################\n\ndef assign_node_labels(G, community_map):\n  # TODO: Implement a function that takes in a NetworkX graph\n  # G and community map assignment (mapping node id --> 0/1 label)\n  # and adds 'node_label' as a node_attribute in G.\n\n  ############# Your code here ############\n  ## (~2 line of code)\n  ## Note\n  ## 1. Look up NetworkX `nx.classes.function.set_node_attributes`\n\n  pass\n\n  #########################################\n\ndef assign_node_features(G):\n  # TODO: Implement a function that takes in a NetworkX graph\n  # G and adds 'node_feature' as a node_attribute in G. Each node\n  # in the graph has the same feature vector - a torchtensor with \n  # data [1., 1., 1., 1., 1.]\n\n  ############# Your code here ############\n  ## (~2 line of code)\n  ## Note\n  ## 1. Look up NetworkX `nx.classes.function.set_node_attributes`\n\n  pass\n\n  #########################################\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  assign_node_types(G, community_map)\n  assign_node_labels(G, community_map)\n  assign_node_features(G)\n\n  # Explore node properties for the node with id: 20\n  node_id = 20\n  print (f\"Node {node_id} has properties:\", G.nodes(data=True)[node_id])\n```\n\n### Question 1.2: Assigning Edge Types \n\nNext, we will assign three different `edge_types`: \n* Edges within club \"Mr. Hi\": `e0`\n* Edges within club \"Officer\": `e1`\n* Edges between the two clubs: `e2`\n\n**Hint**: Use the `community_map` from before and `nx.classes.function.set_edge_attributes`\n\n\n```python\ndef assign_edge_types(G, community_map):\n  # TODO: Implement a function that takes in a NetworkX graph\n  # G and community map assignment (mapping node id --> 0/1 label)\n  # and adds 'edge_type' as a edge_attribute in G.\n\n  ############# Your code here ############\n  ## (~5 line of code)\n  ## Note\n  ## 1. Create an edge assignment dict following rules above\n  ## 2. Look up NetworkX `nx.classes.function.set_edge_attributes`\n\n  pass\n\n  #########################################\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  assign_edge_types(G, community_map)\n\n  # Explore edge properties for a sampled edge and check the corresponding\n  # node types\n  edge_idx = 15\n  n1 = 0\n  n2 = 31\n  edge = list(G.edges(data=True))[edge_idx]\n  print (f\"Edge ({edge[0]}, {edge[1]}) has properties:\", edge[2])\n  print (f\"Node {n1} has properties:\", G.nodes(data=True)[n1])\n  print (f\"Node {n2} has properties:\", G.nodes(data=True)[n2])\n```\n\n## Heterogeneous Graph Visualization\n\nNow we can visualize the Heterogeneous Graph we have generated.\n\n\n```python\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  edge_color = {}\n  for edge in G.edges():\n    n1, n2 = edge\n    edge_color[edge] = community_map[n1] if community_map[n1] == community_map[n2] else 2\n    if community_map[n1] == community_map[n2] and community_map[n1] == 0:\n      edge_color[edge] = 'blue'\n    elif community_map[n1] == community_map[n2] and community_map[n1] == 1:\n      edge_color[edge] = 'red'\n    else:\n      edge_color[edge] = 'green'\n\n  G_orig = copy.deepcopy(G)\n  nx.classes.function.set_edge_attributes(G, edge_color, name='color')\n  colors = nx.get_edge_attributes(G,'color').values()\n  labels = nx.get_node_attributes(G, 'node_type')\n  plt.figure(figsize=(8, 8))\n  nx.draw(G, pos=pos, cmap=plt.get_cmap('coolwarm'), node_color=node_color, edge_color=colors, labels=labels, font_color='white')\n  show()\n```\n\nwhere we differentiate edges within each clubs (2 types) and edges between the two clubs (1 type). Different types of nodes and edges are visualized in different colors. The NetworkX object `G` in following code can be transformed into `deepsnap.hetero_graph.HeteroGraph` directly.\n\n## Transforming to DeepSNAP representation\n\nWe will now work through transforming the NetworkX object `G` into a `deepsnap.hetero_graph.HeteroGraph`.\n\n\n```python\nfrom deepsnap.hetero_graph import HeteroGraph\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  hete = HeteroGraph(G_orig)\n```\n\n## Question 1.3: How many nodes are of each type (10 Points)\n\n\n\n```python\ndef get_nodes_per_type(hete):\n  # TODO: Implement a function that takes a DeepSNAP dataset object\n  # and return the number of nodes per `node_type`.\n\n  num_nodes_n0 = 0\n  num_nodes_n1 = 0\n\n  ############# Your code here ############\n  ## (~2 line of code)\n  ## Note\n  ## 1. Colab autocomplete functionality might be useful.\n\n  pass\n\n  #########################################\n\n  return num_nodes_n0, num_nodes_n1\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  num_nodes_n0, num_nodes_n1 = get_nodes_per_type(hete)\n  print(\"Node type n0 has {} nodes\".format(num_nodes_n0))\n  print(\"Node type n1 has {} nodes\".format(num_nodes_n1))\n```\n\n## Question 1.4: Message Types - How many edges are of each message type (10 Points)\n\nWhen working with heterogenous graphs, as we have discussed before, we now work with heterogenous message types (i.e. different message types for the different `node_type` and `edge_type` combinations). For example, an edge of type `e0` connecting two nodes in club \"Mr. HI\" would have a message type of (`n0`, `e0`, `n0`). In this problem we will analyze how many edges in our graph are of each message type.\n\n**Hint**: If you want to learn more about what the different message types are try the call `hete.message_types`\n\n\n```python\ndef get_num_message_edges(hete):\n  # TODO: Implement this function that takes a DeepSNAP dataset object\n  # and return the number of edges for each message type. \n  # You should return a list of tuples as \n  # (message_type, num_edge)\n\n  message_type_edges = []\n\n  ############# Your code here ############\n  ## (~2 line of code)\n  ## Note\n  ## 1. Colab autocomplete functionality might be useful.\n\n  pass\n\n  #########################################\n\n  return message_type_edges\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  message_type_edges = get_num_message_edges(hete)\n  for (message_type, num_edges) in message_type_edges:\n    print(\"Message type {} has {} edges\".format(message_type, num_edges))\n```\n\n## Question 1.5: Dataset Splitting - How many nodes are in each dataset split? (10 Points)\n\nDeepSNAP has built in Dataset creation and splitting methods for heterogeneous graphs. Here we will create train, validation, and test datasets for a node prediction task and inspect the resulting subgraphs. Specifically, write a function that computes the number of nodes with a known label in each dataset split.\n\n\n\n```python\nfrom deepsnap.dataset import GraphDataset\n\ndef compute_dataset_split_counts(datasets):\n  # TODO: Implement a function that takes a dict of datasets in the form\n  # {'train': dataset_train, 'val': dataset_val, 'test': dataset_test}\n  # and returns a dict mapping dataset names to the number of labeled\n  # nodes used for supervision in that respective dataset.  \n  \n  data_set_splits = {}\n\n  ############# Your code here ############\n  ## (~3 line of code)\n  ## Note\n  ## 1. The DeepSNAP `node_label_index` dictionary will be helpful.\n  ## 2. Remember to count both node_types\n  ## 3. Remember each dataset only has one graph that we need to access \n  ##    (i.e. dataset[0])\n\n  pass\n\n\n  #########################################\n\n  return data_set_splits\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  dataset = GraphDataset([hete], task='node')\n  # Splitting the dataset\n  dataset_train, dataset_val, dataset_test = dataset.split(transductive=True, split_ratio=[0.4, 0.3, 0.3])\n  datasets = {'train': dataset_train, 'val': dataset_val, 'test': dataset_test}\n\n  data_set_splits = compute_dataset_split_counts(datasets)\n  for dataset_name, num_nodes in data_set_splits.items():\n    print(\"{} dataset has {} nodes\".format(dataset_name, num_nodes))\n```\n\n## DeepSNAP Dataset Visualization\n\nWe can now visualize the different nodes and edges used in each graph dataset split.\n\n\n```python\nfrom deepsnap.dataset import GraphDataset\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  dataset = GraphDataset([hete], task='node')\n  # Splitting the dataset\n  dataset_train, dataset_val, dataset_test = dataset.split(transductive=True, split_ratio=[0.4, 0.3, 0.3])\n  titles = ['Train', 'Validation', 'Test']\n\n  for i, dataset in enumerate([dataset_train, dataset_val, dataset_test]):\n    n0 = hete._convert_to_graph_index(dataset[0].node_label_index['n0'], 'n0').tolist()\n    n1 = hete._convert_to_graph_index(dataset[0].node_label_index['n1'], 'n1').tolist()\n\n    plt.figure(figsize=(7, 7))\n    plt.title(titles[i])\n    nx.draw(G_orig, pos=pos, node_color=\"grey\", edge_color=colors, labels=labels, font_color='white')\n    nx.draw_networkx_nodes(G_orig.subgraph(n0), pos=pos, node_color=\"blue\")\n    nx.draw_networkx_nodes(G_orig.subgraph(n1), pos=pos, node_color=\"red\")\n    show()\n```\n\n# 2) Heterogeneous Graph Node Property Prediction\n\nNow, we will use PyTorch Geometric and DeepSNAP to implement a GNN model for heterogeneous graph node property prediction (node classification). We will draw upon our understanding of heterogeneous graphs from lecture and previous work in implementing GNN layers using PyG (introduced in Colab 3).\n\nFirst let's take a look at the general structure of a heterogeneous GNN layer by working through an example:\n\nLet's assume we have a graph $G$, which contains two node types $a$ and $b$, and three message types $m_1=(a, r_1, a)$, $m_2=(a, r_2, b)$ and $m_3=(a, r_3, b)$. Note: during message passing we view each message as (src, relation, dst), where messages \"flow\" from src to dst node types. For example, during message passing, updating node type $b$ relies on two different message types $m_2$ and $m_3$.\n\nWhen applying message passing in heterogenous graphs, we seperately apply message passing over each message type. Therefore, for the graph $G$, a heterogeneous GNN layer contains three seperate Heterogeneous Message Passing layers (`HeteroGNNConv` in this Colab), where each `HeteroGNNConv` layer performs message passing and aggregation with respect to *only one message type*. Since a message type is viewed as (src, relation, dst) and messages \"flow\" from src to dst, each `HeteroGNNConv` layer only computes embeddings for the *dst* nodes of a given message type. For example, the `HeteroGNNConv` layer for message type $m_2$ outputs updated embedding representations *only* for node's with type b. \n\n---\n\nAn overview of the heterogeneous layer we will create is shown below:\n\n\n\nwhere we highlight the following notation:\n\n- $H_a^{(l)[m_1]}$ is the intermediate matrix of of node embeddings for node type $a$, generated by the $l$th `HeteroGNNConv` layer for message type $m_1$.\n- $H_a^{(l)}$ is the matrix with current embeddings for nodes of type $a$ after the $l$th layer of our Heterogeneous GNN model. Note that these embeddings can rely on one or more intermediate `HeteroGNNConv` layer embeddings(i.e. $H_b^{(l)}$ combines $H_b^{(l)[m_2]}$ and $H_b^{(l)[m_3]}$).\n\nSince each `HeteroGNNConv` is only applied over a single message type, we additionally define a Heterogeneous GNN Wrapper layer (`HeteroGNNWrapperConv`). This wrapper manages and combines the output of each `HeteroGNNConv` layer in order to generate the complete updated node embeddings for each node type in layer $l$ of our model. More specifically, the $l^{th}$ `HeteroGNNWrapperConv` layer takes as input the node embeddings computed for each message type and node type (e.g. $H_b^{(l)[m_2]}$ and $H_b^{(l)[m_3]}$) and aggregates across message types with the same $dst$ node type. The resulting output of the $l^{th}$ `HeteroGNNWrapperConv` layer is the updated embedding matrix $H_i^{(l)}$ for each node type i. \n\nContinuing on our example above, to compute the node embeddings $H_b^{(l)}$ the wrapper layer aggregates output embeddings from the `HeteroGNNConv` layers associated with message types $m_2$ and $m_3$ (i.e. $H_b^{(l)[m_2]}$ and $H_b^{(l)[m_3]}$). \n\n---\n\nWith the `HeteroGNNWrapperConv` module, we can now draw a \"simplified\" heterogeneous layer structure as follows:\n\n<br/>\n<center>\n\n</center>\n<br/>\n\n---\n**NOTE**: \nAs reference, it may be helpful to additionally read through PyG's introduciton to heterogeneous graph representations and buidling heterogeneous GNN models: https://pytorch-geometric.readthedocs.io/en/latest/notes/heterogeneous.html \n\n<font color='red'>Looking ahead, we recommend you implement the heterogeneous GNN model in following steps:</font>\n\n1. Implement `HeteroGNNConv`.\n2. Implement **just** `mean` aggregation within `HeteroGNNWrapperConv`.\n3. Implement `generate_convs`.\n4. Implement the `HeteroGNN` model and the `train` function.\n5. Train the model with `mean` aggregation and test your model to make sure your model has reasonable performance.\n6. Once you are confident in your mean aggregation model, implement `attn` aggregation in `HeteroGNNWrapperConv`.\n7. Train the model with `attn` aggregation and test your model to make sure your model has reasonable performance.\n\nNote: The key point of advice is to work completely through implementing the mean aggregation heterogeneous GNN model before diving into the more difficult attention based model.\n\n## Setup\n\n\n```python\nimport copy\nimport torch\nimport deepsnap\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch_geometric.nn as pyg_nn\n\nfrom sklearn.metrics import f1_score\nfrom deepsnap.hetero_gnn import forward_op\nfrom deepsnap.hetero_graph import HeteroGraph\nfrom torch_sparse import SparseTensor, matmul\n```\n\n## Dataset\n\nYou need to login to your Google account and enter the verification code below.\n\n\n```python\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  from pydrive.auth import GoogleAuth\n  from pydrive.drive import GoogleDrive\n  from google.colab import auth\n  from oauth2client.client import GoogleCredentials\n\n  # Authenticate and create the PyDrive client\n  auth.authenticate_user()\n  gauth = GoogleAuth()\n  gauth.credentials = GoogleCredentials.get_application_default()\n  drive = GoogleDrive(gauth)\n```\n\n\n```python\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  id='1ivlxd6lJMcZ9taS44TMGG72x2V1GeVvk'\n  downloaded = drive.CreateFile({'id': id})\n  downloaded.GetContentFile('acm.pkl')\n```\n\n## Implementing `HeteroGNNConv`\n\nNow let's start working on our own implementation of the heterogeneous message passing layer (`HeteroGNNConv`)! Just as in Colabs 3 and 4, we will implement the layer using PyTorch Geometric. \n\nAt a high level, the `HeteroGNNConv` layer is equivalent to the homogenous GNN layers we implemented in Colab 3, but now applied to an individual heterogeous message type. Moreover, our heterogeneous GNN layer draws directly from the **GraphSAGE** message passing model ([Hamilton et al. (2017)](https://arxiv.org/abs/1706.02216)).\n\nWe begin by defining the `HeteroGNNConv` layer with respect to message type $m$:\n\n\\begin{equation}\nm =(s, r, d)\n\\end{equation}\n\nwhere each message type is a tuple containing three elements: $s$ - the source node type, $r$ - the edge (relation) type, and $d$ - the destination node type. \n\nThe message passing update rule that we implement is very similar to that of GraphSAGE, except we now need to include the node types and the edge relation type. The update rule for message type $m$ is described below:\n\n\\begin{equation}\nh_v^{(l)[m]} = W^{(l)[m]} \\cdot \\text{CONCAT} \\Big( W_d^{(l)[m]} \\cdot h_v^{(l-1)}, W_s^{(l)[m]} \\cdot AGG(\\{h_u^{(l-1)}, \\forall u \\in N_{m}(v) \\})\\Big)\n\\end{equation}\n\nwhere we compute $h_v^{(l)[m]}$, the node embedding representation for node $v$ after `HeteroGNNConv` layer $l$ with respect message type $m$. Further unpacking the forumla we have:\n- $W_s^{(l)[m]}$ - linear transformation matrix for the messages of neighboring source nodes of type $s$ along message type $m$.\n- $W_d^{(l)[m]}$ - linear transformation matrix for the message from the node $v$ itself of type $d$.\n- $W^{(l)[m]}$ - linear transformation matrix for the concatenated messages from neighboring node's and the central node.\n- $h_u^{(l-1)}$ - the hidden embedding representation for node $u$ after the $(l-1)$th `HeteroGNNWrapperConv` layer. Note, that this embedding is not associated with a particular message type (see layer diagrams above). \n- $N_{m}(v)$ - the set of neighbor source nodes $s$ for the node v that we are embedding along message type $m = (s, r, d)$. \n\n**NOTE**: We emphasize that each weight matrix is associated with a specific message type $[m]$ and additionally, the weight matrices applied to node messages are differentiated by node type (i.e. $W_s$ and $W_d$).\n\nLastly, for simplicity, we use mean aggregations for $AGG$ where:\n\n\\begin{equation}\nAGG(\\{h_u^{(l-1)}, \\forall u \\in N_{m}(v) \\}) = \\frac{1}{|N_{m}(v)|} \\sum_{u\\in N_{m}(v)} h_u^{(l-1)}\n\\end{equation}\n\n\n```python\nclass HeteroGNNConv(pyg_nn.MessagePassing):\n    def __init__(self, in_channels_src, in_channels_dst, out_channels):\n        super(HeteroGNNConv, self).__init__(aggr=\"mean\")\n\n        self.in_channels_src = in_channels_src\n        self.in_channels_dst = in_channels_dst\n        self.out_channels = out_channels\n\n        # To simplify implementation, please initialize both self.lin_dst\n        # and self.lin_src out_features to out_channels\n        self.lin_dst = None\n        self.lin_src = None\n\n        self.lin_update = None\n\n        ############# Your code here #############\n        ## (~3 lines of code)\n        ## Note:\n        ## 1. Initialize the 3 linear layers.\n        ## 2. Think through the connection between the mathematical\n        ##    definition of the update rule and torch linear layers!\n\n        pass\n\n\n        ##########################################\n\n    def forward(\n        self,\n        node_feature_src,\n        node_feature_dst,\n        edge_index,\n        size=None\n    ):\n        ############# Your code here #############\n        ## (~1 line of code)\n        ## Note:\n        ## 1. Unlike Colabs 3 and 4, we just need to call self.propagate with \n        ## proper/custom arguments.\n\n        pass\n\n        ##########################################\n\n    def message_and_aggregate(self, edge_index, node_feature_src):\n\n        out = None\n        ############# Your code here #############\n        ## (~1 line of code)\n        ## Note:\n        ## 1. Different from what we implemented in Colabs 3 and 4, we use message_and_aggregate\n        ##    to combine the previously seperate message and aggregate functions. \n        ##    The benefit is that we can avoid materializing x_i and x_j\n        ##    to make the implementation more efficient.\n        ## 2. To implement efficiently, refer to PyG documentation for message_and_aggregate\n        ##    and sparse-matrix multiplication:\n        ##    https://pytorch-geometric.readthedocs.io/en/latest/notes/sparse_tensor.html\n        ## 3. Here edge_index is torch_sparse SparseTensor. Although interesting, you\n        ##    do not need to deeply understand SparseTensor represenations!\n        ## 4. Conceptually, think through how the message passing and aggregation\n        ##    expressed mathematically can be expressed through matrix multiplication.\n\n        pass\n\n\n        ##########################################\n\n        return out\n\n    def update(self, aggr_out, node_feature_dst):\n\n        ############# Your code here #############\n        ## (~4 lines of code)\n        ## Note:\n        ## 1. The update function is called after message_and_aggregate\n        ## 2. Think through the one-one connection between the mathematical update\n        ##    rule and the 3 linear layers defined in the constructor. \n\n       pass\n\n\n        ##########################################\n\n        return aggr_out\n```\n\n## Heterogeneous GNN Wrapper Layer\n\nAfter implementing the `HeteroGNNConv` layer for each message type, we need to manage and aggregate the node embedding results (with respect to each message types). Here we will implement two types of message type level aggregation.\n\nThe first one is simply mean aggregation over message types:\n\n\\begin{equation}\nh_v^{(l)} = \\frac{1}{M}\\sum_{m=1}^{M}h_v^{(l)[m]}\n\\end{equation}\n\nwhere node $v$ has node type $d$ and we sum over the $M$ message types that have destination node type $d$. From our original example, for a node v of type $b$ we aggregate v's `HeteroGNNConv` embeddings for message types $m_2$ and $m_3$ (i.e. $h_v^{(l)[m_2]}$ and $h_v^{(l)[m_3]}$).\n\nThe second method we implement is the semantic level attention introduced in **HAN** ([Wang et al. (2019)](https://arxiv.org/abs/1903.07293)). Instead of directly averaging on the message type aggregation results, we use attention to learn which message type result is more important, then aggregate across all the message types. Below are the equations for semantic level attention:\n\n\\begin{equation}\ne_{m} = \\frac{1}{|V_{d}|} \\sum_{v \\in V_{d}} q_{attn}^T \\cdot tanh \\Big( W_{attn}^{(l)} \\cdot h_v^{(l)[m]} + b \\Big)\n\\end{equation}\n\nwhere $m$ is the message type and $d$ refers to the destination node type for that message ($m = (s, r, d)$). Additionally, $V_{d}$ refers to the set of nodes v with type $d$. Lastly, the unormalized attention weight $e_m$ is a scaler computed for each message type $m$. \n\nNext, we can compute the normalized attention weights and update $h_v^{(l)}$:\n\n\\begin{equation}\n\\alpha_{m} = \\frac{\\exp(e_{m})}{\\sum_{m=1}^M \\exp(e_{m})}\n\\end{equation}\n\n\\begin{equation}\nh_v^{(l)} = \\sum_{m=1}^{M} \\alpha_{m} \\cdot h_v^{(l)[m]}\n\\end{equation}\n\n, where we emphasize that $M$ here is the number of message types associated with the destination node type $d$. \n\n**Note**: The implementation of the attention aggregation is tricky and nuanced. We strongly recommend working carefully through the math equations to undersatnd exactly what each notation refers to and how all the pieces fit together. If you can, try to connect the math to our original example, focusing on node type $b$, which depends on two different message types!\n\n**_We've implemented most of this for you but you'll need to initialize self.attn_proj in the initializer_**\n\n\n```python\nclass HeteroGNNWrapperConv(deepsnap.hetero_gnn.HeteroConv):\n    def __init__(self, convs, args, aggr=\"mean\"):\n        super(HeteroGNNWrapperConv, self).__init__(convs, None)\n        self.aggr = aggr\n\n        # Map the index and message type\n        self.mapping = {}\n\n        # A numpy array that stores the final attention probability\n        self.alpha = None\n\n        self.attn_proj = None\n\n        if self.aggr == \"attn\":\n            ############# Your code here #############\n            ## (~1 line of code)\n            ## Note:\n            ## 1. Initialize self.attn_proj, where self.attn_proj should include\n            ##    two linear layers. Note, make sure you understand\n            ##    which part of the equation self.attn_proj captures.\n            ## 2. You should use nn.Sequential for self.attn_proj\n            ## 3. nn.Linear and nn.Tanh are useful.\n            ## 4. You can model a weight vector (rather than matrix) by using:\n            ##    nn.Linear(some_size, 1, bias=False).\n            ## 5. The first linear layer should have out_features as args['attn_size']\n            ## 6. You can assume we only have one \"head\" for the attention.\n            ## 7. We recommend you to implement the mean aggregation first. After \n            ##    the mean aggregation works well in the training, then you can \n            ##    implement this part.\n\n            pass\n          \n            ##########################################\n    \n    def reset_parameters(self):\n        super(HeteroConvWrapper, self).reset_parameters()\n        if self.aggr == \"attn\":\n            for layer in self.attn_proj.children():\n                layer.reset_parameters()\n    \n    def forward(self, node_features, edge_indices):\n        message_type_emb = {}\n        for message_key, message_type in edge_indices.items():\n            src_type, edge_type, dst_type = message_key\n            node_feature_src = node_features[src_type]\n            node_feature_dst = node_features[dst_type]\n            edge_index = edge_indices[message_key]\n            message_type_emb[message_key] = (\n                self.convs[message_key](\n                    node_feature_src,\n                    node_feature_dst,\n                    edge_index,\n                )\n            )\n        node_emb = {dst: [] for _, _, dst in message_type_emb.keys()}\n        mapping = {}        \n        for (src, edge_type, dst), item in message_type_emb.items():\n            mapping[len(node_emb[dst])] = (src, edge_type, dst)\n            node_emb[dst].append(item)\n        self.mapping = mapping\n        for node_type, embs in node_emb.items():\n            if len(embs) == 1:\n                node_emb[node_type] = embs[0]\n            else:\n                node_emb[node_type] = self.aggregate(embs)\n        return node_emb\n    \n    def aggregate(self, xs):\n        # TODO: Implement this function that aggregates all message type results.\n        # Here, xs is a list of tensors (embeddings) with respect to message \n        # type aggregation results.\n\n        if self.aggr == \"mean\":\n\n            ############# Your code here #############\n            ## (~2 lines of code)\n            ## Note:\n            ## 1. Explore the function parameter `xs`! \n\n            pass\n\n            ##########################################\n\n        elif self.aggr == \"attn\":\n            N = xs[0].shape[0] # Number of nodes for that node type\n            M = len(xs) # Number of message types for that node type\n\n            x = torch.cat(xs, dim=0).view(M, N, -1) # M * N * D\n            z = self.attn_proj(x).view(M, N) # M * N * 1\n            z = z.mean(1) # M * 1\n            alpha = torch.softmax(z, dim=0) # M * 1\n\n            # Store the attention result to self.alpha as np array\n            self.alpha = alpha.view(-1).data.cpu().numpy()\n  \n            alpha = alpha.view(M, 1, 1)\n            x = x * alpha\n            return x.sum(dim=0)\n```\n\n## Initialize Heterogeneous GNN Layers\n\nNow let's put it all together and initialize the Heterogeneous GNN Layers. Different from the homogeneous graph case, heterogeneous graphs can be a little bit complex.\n\nIn general, we need to create a dictionary of `HeteroGNNConv` layers where the keys are message types.\n\n* To get all message types, `deepsnap.hetero_graph.HeteroGraph.message_types` is useful.\n* If we are initializing the first conv layers, we need to get the feature dimension of each node type. Using `deepsnap.hetero_graph.HeteroGraph.num_node_features(node_type)` will return the node feature dimension of `node_type`. In this function, we will set each `HeteroGNNConv` `out_channels` to be `hidden_size`.\n* If we are not initializing the first conv layers, all node types will have the smae embedding dimension `hidden_size` and we still set `HeteroGNNConv` `out_channels` to be `hidden_size` for simplicity.\n\n\n\n\n```python\ndef generate_convs(hetero_graph, conv, hidden_size, first_layer=False):\n    # TODO: Implement this function that returns a dictionary of `HeteroGNNConv` \n    # layers where the keys are message types. `hetero_graph` is deepsnap `HeteroGraph`\n    # object and the `conv` is the `HeteroGNNConv`.\n\n    convs = {}\n\n    ############# Your code here #############\n    ## (~9 lines of code)\n    ## Note:\n    ## 1. See the hints above!\n    ## 2. conv is of type `HeteroGNNConv`\n\n    pass\n\n\n    ##########################################\n    \n    return convs\n```\n\n## HeteroGNN\n\nNow we will make a simple HeteroGNN model which contains only two `HeteroGNNWrapperConv` layers.\n\nFor the forward function in `HeteroGNN`, the model is going to be run as following:\n\n$\\text{self.convs1} \\rightarrow \\text{self.bns1} \\rightarrow \\text{self.relus1} \\rightarrow \\text{self.convs2} \\rightarrow \\text{self.bns2} \\rightarrow \\text{self.relus2} \\rightarrow \\text{self.post_mps}$\n\n\n```python\nclass HeteroGNN(torch.nn.Module):\n    def __init__(self, hetero_graph, args, aggr=\"mean\"):\n        super(HeteroGNN, self).__init__()\n\n        self.aggr = aggr\n        self.hidden_size = args['hidden_size']\n\n        self.convs1 = None\n        self.convs2 = None\n\n        self.bns1 = nn.ModuleDict()\n        self.bns2 = nn.ModuleDict()\n        self.relus1 = nn.ModuleDict()\n        self.relus2 = nn.ModuleDict()\n        self.post_mps = nn.ModuleDict()\n\n        ############# Your code here #############\n        ## (~10 lines of code)\n        ## Note:\n        ## 1. For self.convs1 and self.convs2, call generate_convs at first and then\n        ##    pass the returned dictionary of `HeteroGNNConv` to `HeteroGNNWrapperConv`.\n        ## 2. For self.bns, self.relus and self.post_mps, the keys are node_types.\n        ##    `deepsnap.hetero_graph.HeteroGraph.node_types` will be helpful.\n        ## 3. Initialize all batchnorms to torch.nn.BatchNorm1d(hidden_size, eps=1).\n        ## 4. Initialize all relus to nn.LeakyReLU().\n        ## 5. For self.post_mps, each value in the ModuleDict is a linear layer \n        ##    where the `out_features` is the number of classes for that node type.\n        ##    `deepsnap.hetero_graph.HeteroGraph.num_node_labels(node_type)` will be\n        ##    useful.\n\n        pass\n\n      \n        ##########################################\n\n    def forward(self, node_feature, edge_index):\n        # TODO: Implement the forward function. Notice that `node_feature` is \n        # a dictionary of tensors where keys are node types and values are \n        # corresponding feature tensors. The `edge_index` is a dictionary of \n        # tensors where keys are message types and values are corresponding\n        # edge index tensors (with respect to each message type).\n\n        x = node_feature\n\n        ############# Your code here #############\n        ## (~7 lines of code)\n        ## Note:\n        ## 1. `deepsnap.hetero_gnn.forward_op` can be helpful.\n\n        pass\n\n\n        ##########################################\n        \n        return x\n\n    def loss(self, preds, y, indices):\n        \n        loss = 0\n        loss_func = F.cross_entropy\n\n        ############# Your code here #############\n        ## (~3 lines of code)\n        ## Note:\n        ## 1. For each node type in preds, accumulate computed loss to `loss`\n        ## 2. Loss need to be computed with respect to the given index\n        ## 3. preds is a dictionary of model predictions keyed by node_type.\n        ## 4. indeces is a dictionary of labeled supervision nodes keyed\n        ##    by node_type\n\n        pass\n\n\n        ##########################################\n\n        return loss\n```\n\n## Training and Testing\n\nHere we provide you with the functions to train and test. You only need to implement one line of code here.\n\n**Please do not modify other parts in `train` and `test` for grading purposes.**\n\n\n```python\nimport pandas as pd\n\ndef train(model, optimizer, hetero_graph, train_idx):\n    model.train()\n    optimizer.zero_grad()\n    preds = model(hetero_graph.node_feature, hetero_graph.edge_index)\n\n    loss = None\n\n    ############# Your code here #############\n    ## Note:\n    ## 1. Compute the loss here\n    ## 2. `deepsnap.hetero_graph.HeteroGraph.node_label` is useful\n\n    pass\n\n\n    ##########################################\n\n    loss.backward()\n    optimizer.step()\n    return loss.item()\n\ndef test(model, graph, indices, best_model=None, best_val=0, save_preds=False, agg_type=None):\n    model.eval()\n    accs = []\n    for i, index in enumerate(indices):\n        preds = model(graph.node_feature, graph.edge_index)\n        num_node_types = 0\n        micro = 0\n        macro = 0\n        for node_type in preds:\n            idx = index[node_type]\n            pred = preds[node_type][idx]\n            pred = pred.max(1)[1]\n            label_np = graph.node_label[node_type][idx].cpu().numpy()\n            pred_np = pred.cpu().numpy()\n            micro = f1_score(label_np, pred_np, average='micro')\n            macro = f1_score(label_np, pred_np, average='macro')\n            num_node_types += 1\n                  \n        # Averaging f1 score might not make sense, but in our example we only\n        # have one node type\n        micro /= num_node_types\n        macro /= num_node_types\n        accs.append((micro, macro))\n\n        # Only save the test set predictions and labels!\n        if save_preds and i == 2:\n          print (\"Saving Heterogeneous Node Prediction Model Predictions with Agg:\", agg_type)\n          print()\n\n          data = {}\n          data['pred'] = pred_np\n          data['label'] = label_np\n\n          df = pd.DataFrame(data=data)\n          # Save locally as csv\n          df.to_csv('ACM-Node-' + agg_type + 'Agg.csv', sep=',', index=False)\n\n    if accs[1][0] > best_val:\n        best_val = accs[1][0]\n        best_model = copy.deepcopy(model)\n    return accs, best_model, best_val\n```\n\n\n```python\n# Please do not change the following parameters\nargs = {\n    'device': torch.device('cuda' if torch.cuda.is_available() else 'cpu'),\n    'hidden_size': 64,\n    'epochs': 100,\n    'weight_decay': 1e-5,\n    'lr': 0.003,\n    'attn_size': 32,\n}\n```\n\n## Dataset and Preprocessing\n\nIn the next, we will load the data and create a tensor backend (without a NetworkX graph) `deepsnap.hetero_graph.HeteroGraph` object.\n\nWe will use the `ACM(3025)` dataset in our node property prediction task, which is proposed in **HAN** ([Wang et al. (2019)](https://arxiv.org/abs/1903.07293)) and our dataset is extracted from [DGL](https://www.dgl.ai/)'s [ACM.mat](https://data.dgl.ai/dataset/ACM.mat).\n\nThe original ACM dataset has three node types and two edge (relation) types. For simplicity, we simplify the heterogeneous graph to one node type and two edge types (shown below). This means that in our heterogeneous graph, we have one node type (paper) and two message types (paper, author, paper) and (paper, subject, paper).\n\n<br/>\n<center>\n\n</center>\n\n\n```python\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  print(\"Device: {}\".format(args['device']))\n\n  # Load the data\n  data = torch.load(\"acm.pkl\")\n\n  # Message types\n  message_type_1 = (\"paper\", \"author\", \"paper\")\n  message_type_2 = (\"paper\", \"subject\", \"paper\")\n\n  # Dictionary of edge indices\n  edge_index = {}\n  edge_index[message_type_1] = data['pap']\n  edge_index[message_type_2] = data['psp']\n\n  # Dictionary of node features\n  node_feature = {}\n  node_feature[\"paper\"] = data['feature']\n\n  # Dictionary of node labels\n  node_label = {}\n  node_label[\"paper\"] = data['label']\n\n  # Load the train, validation and test indices\n  train_idx = {\"paper\": data['train_idx'].to(args['device'])}\n  val_idx = {\"paper\": data['val_idx'].to(args['device'])}\n  test_idx = {\"paper\": data['test_idx'].to(args['device'])}\n\n  # Construct a deepsnap tensor backend HeteroGraph\n  hetero_graph = HeteroGraph(\n      node_feature=node_feature,\n      node_label=node_label,\n      edge_index=edge_index,\n      directed=True\n  )\n\n  print(f\"ACM heterogeneous graph: {hetero_graph.num_nodes()} nodes, {hetero_graph.num_edges()} edges\")\n\n  # Node feature and node label to device\n  for key in hetero_graph.node_feature:\n      hetero_graph.node_feature[key] = hetero_graph.node_feature[key].to(args['device'])\n  for key in hetero_graph.node_label:\n      hetero_graph.node_label[key] = hetero_graph.node_label[key].to(args['device'])\n\n  # Edge_index to sparse tensor and to device\n  for key in hetero_graph.edge_index:\n      edge_index = hetero_graph.edge_index[key]\n      adj = SparseTensor(row=edge_index[0], col=edge_index[1], sparse_sizes=(hetero_graph.num_nodes('paper'), hetero_graph.num_nodes('paper')))\n      hetero_graph.edge_index[key] = adj.t().to(args['device'])\n  print(hetero_graph.edge_index[message_type_1])\n  print(hetero_graph.edge_index[message_type_2])\n```\n\n## Start Training!\n\nNow lets start training!\n\n## Training the Mean Aggregation\n\n\n```python\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  best_model = None\n  best_val = 0\n\n  model = HeteroGNN(hetero_graph, args, aggr=\"mean\").to(args['device'])\n  optimizer = torch.optim.Adam(model.parameters(), lr=args['lr'], weight_decay=args['weight_decay'])\n\n  for epoch in range(args['epochs']):\n      loss = train(model, optimizer, hetero_graph, train_idx)\n      accs, best_model, best_val = test(model, hetero_graph, [train_idx, val_idx, test_idx], best_model, best_val)\n      print(\n          f\"Epoch {epoch + 1}: loss {round(loss, 5)}, \"\n          f\"train micro {round(accs[0][0] * 100, 2)}%, train macro {round(accs[0][1] * 100, 2)}%, \"\n          f\"valid micro {round(accs[1][0] * 100, 2)}%, valid macro {round(accs[1][1] * 100, 2)}%, \"\n          f\"test micro {round(accs[2][0] * 100, 2)}%, test macro {round(accs[2][1] * 100, 2)}%\"\n      )\n  best_accs, _, _ = test(best_model, hetero_graph, [train_idx, val_idx, test_idx], save_preds=True, agg_type=\"Mean\")\n  print(\n      f\"Best model: \"\n      f\"train micro {round(best_accs[0][0] * 100, 2)}%, train macro {round(best_accs[0][1] * 100, 2)}%, \"\n      f\"valid micro {round(best_accs[1][0] * 100, 2)}%, valid macro {round(best_accs[1][1] * 100, 2)}%, \"\n      f\"test micro {round(best_accs[2][0] * 100, 2)}%, test macro {round(best_accs[2][1] * 100, 2)}%\"\n  )\n```\n\n## Question 2.1: What is your maximum test set **micro** F1 score for the best_model when using mean aggregation? (10 points)\n\n\n## Question 2.2: What is your maximum test set **macro** F1 score for the best_model when using the mean aggregation? (10 points)\n\n\n## Training the Attention Aggregation\n\n\n```python\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  best_model = None\n  best_val = 0\n\n  output_size = hetero_graph.num_node_labels('paper')\n  model = HeteroGNN(hetero_graph, args, aggr=\"attn\").to(args['device'])\n  optimizer = torch.optim.Adam(model.parameters(), lr=args['lr'], weight_decay=args['weight_decay'])\n\n  for epoch in range(args['epochs']):\n      loss = train(model, optimizer, hetero_graph, train_idx)\n      accs, best_model, best_val = test(model, hetero_graph, [train_idx, val_idx, test_idx], best_model, best_val)\n      print(\n          f\"Epoch {epoch + 1}: loss {round(loss, 5)}, \"\n          f\"train micro {round(accs[0][0] * 100, 2)}%, train macro {round(accs[0][1] * 100, 2)}%, \"\n          f\"valid micro {round(accs[1][0] * 100, 2)}%, valid macro {round(accs[1][1] * 100, 2)}%, \"\n          f\"test micro {round(accs[2][0] * 100, 2)}%, test macro {round(accs[2][1] * 100, 2)}%\"\n      )\n  best_accs, _, _ = test(best_model, hetero_graph, [train_idx, val_idx, test_idx], save_preds=True, agg_type=\"Attention\")\n  print(\n      f\"Best model: \"\n      f\"train micro {round(best_accs[0][0] * 100, 2)}%, train macro {round(best_accs[0][1] * 100, 2)}%, \"\n      f\"valid micro {round(best_accs[1][0] * 100, 2)}%, valid macro {round(best_accs[1][1] * 100, 2)}%, \"\n      f\"test micro {round(best_accs[2][0] * 100, 2)}%, test macro {round(best_accs[2][1] * 100, 2)}%\"\n  )\n```\n\n## Question 2.3: What is your maximum test set **micro** F1 score for the best_model when using the attention aggregation? (4 points)\n\n\n## Question 2.4: What is your maximum test set **macro** F1 score for the best_model when using the attention aggregation? (4 points)\n\n\n## Attention for each Message Type\n\nThrough message type level attention we can learn which message type is more important to which layer.\n\nHere we will print out and show that each layer pay how much attention on each message type.\n\n\n```python\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  if model.convs1.alpha is not None and model.convs2.alpha is not None:\n      for idx, message_type in model.convs1.mapping.items():\n          print(f\"Layer 1 has attention {model.convs1.alpha[idx]} on message type {message_type}\")\n      for idx, message_type in model.convs2.mapping.items():\n          print(f\"Layer 2 has attention {model.convs2.alpha[idx]} on message type {message_type}\")\n```\n\n# Submission\n\nYou will need to submit three files on Gradescope to complete this notebook. \n\n1.   Your completed *CS224W_Colab5.ipynb*. From the \"File\" menu select \"Download .ipynb\" to save a local copy of your completed Colab. \n2.  *ACM-Node-MeanAgg.csv* \n3.  *ACM-Node-AttentionAgg.csv*\n\nDownload the csv files by selecting the *Folder* icon on the left panel. \n\nTo submit your work, zip the files downloaded in steps 1-3 above and submit to gradescope. **NOTE:** DO NOT rename any of the downloaded files. \n", "meta": {"hexsha": "518a9c83eed932aed9edbd96762ed269189d8fea", "size": 69878, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "labs/CS224W_Colab5.ipynb", "max_stars_repo_name": "kdha0727/CS224W", "max_stars_repo_head_hexsha": "095d61eb751b43d97ad8ca8b3a07266cc5006631", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "labs/CS224W_Colab5.ipynb", "max_issues_repo_name": "kdha0727/CS224W", "max_issues_repo_head_hexsha": "095d61eb751b43d97ad8ca8b3a07266cc5006631", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "labs/CS224W_Colab5.ipynb", "max_forks_repo_name": "kdha0727/CS224W", "max_forks_repo_head_hexsha": "095d61eb751b43d97ad8ca8b3a07266cc5006631", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.287103046, "max_line_length": 731, "alphanum_fraction": 0.5299235811, "converted": true, "num_tokens": 12222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2628418373713166, "lm_q2_score": 0.18713268669577832, "lm_q1q2_score": 0.049186299203349305}}
{"text": "```python\n#remove cell visibility\nfrom IPython.display import HTML\ntag = HTML('''\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.''')\ndisplay(tag)\n```\n\n\n\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.\n\n\n\n```python\n%matplotlib inline\nimport control\nimport numpy\nimport sympy as sym\nfrom IPython.display import display, Markdown\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\n\n\n#print a matrix latex-like\ndef bmatrix(a):\n     \"\"\"Returns a LaTeX bmatrix - by Damir Arbula (ICCT project)\n\n     :a: numpy array\n     :returns: LaTeX bmatrix as a string\n     \"\"\"\n     if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n     lines = str(a).replace('[', '').replace(']', '').splitlines()\n     rv = [r'\\begin{bmatrix}']\n     rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n     rv +=  [r'\\end{bmatrix}']\n     return '\\n'.join(rv)\n\n\n# Display formatted matrix: \ndef vmatrix(a):\n    if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n    lines = str(a).replace('[', '').replace(']', '').splitlines()\n    rv = [r'\\begin{vmatrix}']\n    rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n    rv +=  [r'\\end{vmatrix}']\n    return '\\n'.join(rv)\n\n\n#matrixWidget is a matrix looking widget built with a VBox of HBox(es) that returns a numPy array as value !\nclass matrixWidget(widgets.VBox):\n    def updateM(self,change):\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.M_[irow,icol] = self.children[irow].children[icol].value\n                #print(self.M_[irow,icol])\n        self.value = self.M_\n\n    def dummychangecallback(self,change):\n        pass\n    \n    \n    def __init__(self,n,m):\n        self.n = n\n        self.m = m\n        self.M_ = numpy.matrix(numpy.zeros((self.n,self.m)))\n        self.value = self.M_\n        widgets.VBox.__init__(self,\n                             children = [\n                                 widgets.HBox(children = \n                                              [widgets.FloatText(value=0.0, layout=widgets.Layout(width='90px')) for i in range(m)]\n                                             ) \n                                 for j in range(n)\n                             ])\n        \n        #fill in widgets and tell interact to call updateM each time a children changes value\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        #value = Unicode('example@example.com', help=\"The email value.\").tag(sync=True)\n        self.observe(self.updateM, names='value', type= 'All')\n        \n    def setM(self, newM):\n        #disable callbacks, change values, and reenable\n        self.unobserve(self.updateM, names='value', type= 'All')\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].unobserve(self.updateM, names='value')\n        self.M_ = newM\n        self.value = self.M_\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        self.observe(self.updateM, names='value', type= 'All')        \n\n                #self.children[irow].children[icol].observe(self.updateM, names='value')\n\n             \n#overlaod class for state space systems that DO NOT remove \"useless\" states (what \"professor\" of automatic control would do this?)\nclass sss(control.StateSpace):\n    def __init__(self,*args):\n        #call base class init constructor\n        control.StateSpace.__init__(self,*args)\n    #disable function below in base class\n    def _remove_useless_states(self):\n        pass\n```\n\n## Control of robotic arm with flexible joint\n\nA robotic arm link is driven by an electric motor via a flexible joint that behaves like a torsional spring. The system dynamics may be approximated with a third order linear time invariant system where the states are: \n- $x_1$ : the difference between motor and arm angles (not zero because of the joint flexibility),\n- $x_2$ : motor shaft angular speed,\n- $x_3$ : link angular speed.\nThe input $u$ is the motor torque. The dynamic equations are:\n\n\\begin{cases}\n\\dot{x} = \\begin{bmatrix} 0 & 1 & -1 \\\\ a-1 & -b_1 & b_1 \\\\ a & b_2 & -b_2 \\end{bmatrix}x + \\begin{bmatrix} 0 \\\\ b_3 \\\\ 0 \\end{bmatrix}u \\\\\ny = \\begin{bmatrix} 0 & 0 & 1 \\end{bmatrix}x\n\\end{cases}\n\nwith $a=0.1$, $b_1=0.09$, $b_2=0.01$ and $b_3=90$.\n\nThe goal of the control system design is to regulate the link angular speed in order to have dominant poles with damping equal to 0.7 and natural frequency equal to 0.5 rad/s and zero steady-state error in response to reference velocity step.\n\nThe transfer function of the system is:\n\n\n```python\nA = numpy.matrix('0 1 -1; -0.9 -0.09 0.09; 0.1 0.01 -0.01')\nB = numpy.matrix('0; 90; 0')\nC = numpy.matrix('0 0 1')\nD = numpy.matrix('0')\nsys_tf = control.tf(sss(A,B,C,D))\nprint(sys_tf)\n```\n\n    \n      3.886e-16 s^2 + 0.9 s + 9\n    -----------------------------\n    s^3 + 0.1 s^2 + s - 8.674e-19\n    \n\n\nwith poles\n\n\n```python\nimport warnings\n# In order to suppress the warning BadCoefficient\nwarnings.filterwarnings(\"ignore\")\nprint(numpy.round(sys_tf.pole(),3))\n```\n\n    [-0.05+0.999j -0.05-0.999j  0.  +0.j   ]\n\n\nand zeros\n\n\n```python\nprint(numpy.round(sys_tf.zero(),3),'.')\n```\n\n    [-2.31613695e+15 -1.00000000e+01] .\n\n\nFirst, we analyze the system in order to verify if it is controllable and observable. The controllability matrix $\\mathcal{C}$ is\n\n\n```python\nCtrb = control.ctrb(A,B)\ndisplay(Markdown(bmatrix(Ctrb)))\n# print(numpy.linalg.matrix_rank(Ctrb))\n```\n\n\n\\begin{bmatrix}\n  0. & 90. & -9.\\\\\n  90. & -8.1 & -80.19\\\\\n  0. & 0.9 & 8.91\\\\\n\\end{bmatrix}\n\n\nand has rank equal to 3 so the system is controllable. The observability matrix $\\mathcal{O}$ is\n\n\n```python\nObsv = control.obsv(A,C)\ndisplay(Markdown(bmatrix(Obsv)))\n# print(numpy.linalg.matrix_rank(Obsv))\n```\n\n\n\\begin{bmatrix}\n  0. & 0. & 1.\\\\\n  0.1 & 0.01 & -0.01\\\\\n  -0.01 & 0.099 & -0.099\\\\\n\\end{bmatrix}\n\n\nand has rank equal to 3 so the system is observable.\n\nThis could have been actually deduced from the fact that the denominator of the transfer function is of third order (equal to the state space vector dimension). \n\n### Regulator design\n#### Controller design\n\nDue to the requirements, we know that we have to place 2 poles in $\\zeta \\omega_n \\pm \\sqrt{1-\\zeta^2}\\omega_n = -0.35\\pm0.357i$ and place the remaining real pole at a frequency higher than that of the complex (dominant) poles. We can select to place the third pole at -3.5 rad/s. For the requirement of zero steady-state error we scale the reference signal with a  gain equal to the inverse of the closed-loop system gain.\n\n#### Design of the observer\n\nIn order to have an observer that quickly assists the controller we simply place the poles at about -10 rad/s.\n\n### How to use this notebook?\n- Verify if the closed-loop system performs well in a case of an initial state estimation error. Try to improve its performance.\n- Reduce the frequency of the real pole of the controlled closed-loop system and watch how the response differs from the reference response.\n\n\n```python\n# Preparatory cell\n\nX0 = numpy.matrix('0.0; 0.0; 0.0')\nK = numpy.matrix([8/15,-4.4,-4])\nL = numpy.matrix([[23],[66],[107/3]])\n\nAw = matrixWidget(3,3)\nAw.setM(A)\nBw = matrixWidget(3,1)\nBw.setM(B)\nCw = matrixWidget(1,3)\nCw.setM(C)\nX0w = matrixWidget(3,1)\nX0w.setM(X0)\nKw = matrixWidget(1,3)\nKw.setM(K)\nLw = matrixWidget(3,1)\nLw.setM(L)\n\n\neig1c = matrixWidget(1,1)\neig2c = matrixWidget(2,1)\neig3c = matrixWidget(1,1)\neig1c.setM(numpy.matrix([-3.5])) \neig2c.setM(numpy.matrix([[-0.35],[-0.357]]))\neig3c.setM(numpy.matrix([-3.5]))\n\neig1o = matrixWidget(1,1)\neig2o = matrixWidget(2,1)\neig3o = matrixWidget(1,1)\neig1o.setM(numpy.matrix([-10.])) \neig2o.setM(numpy.matrix([[-10.],[0.]]))\neig3o.setM(numpy.matrix([-10.]))\n```\n\n\n```python\n# Misc\n\n#create dummy widget \nDW = widgets.FloatText(layout=widgets.Layout(width='0px', height='0px'))\n\n#create button widget\nSTART = widgets.Button(\n    description='Test',\n    disabled=False,\n    button_style='', # 'success', 'info', 'warning', 'danger' or ''\n    tooltip='Test',\n    icon='check'\n)\n                       \ndef on_start_button_clicked(b):\n    #This is a workaround to have intreactive_output call the callback:\n    #   force the value of the dummy widget to change\n    if DW.value> 0 :\n        DW.value = -1\n    else: \n        DW.value = 1\n    pass\nSTART.on_click(on_start_button_clicked)\n\n# Define type of method \nselm = widgets.Dropdown(\n    options= ['Set K and L', 'Set the eigenvalues'],\n    value= 'Set the eigenvalues',\n    description='',\n    disabled=False\n)\n\n# Define the number of complex eigenvalues\nsele = widgets.Dropdown(\n    options= ['0 complex eigenvalues', '2 complex eigenvalues'],\n    value= '2 complex eigenvalues',\n    description='Complex eigenvalues:',\n    style = {'description_width': 'initial'},\n    disabled=False\n)\n\n#define type of ipout \nselu = widgets.Dropdown(\n    options=['impulse', 'step', 'sinusoid', 'square wave'],\n    value='step',\n    description='Type of reference:',\n    style = {'description_width': 'initial'},\n    disabled=False\n)\n# Define the values of the input\nu = widgets.FloatSlider(\n    value=1,\n    min=0,\n    max=3,\n    step=0.1,\n    description='Reference:',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.1f',\n)\nperiod = widgets.FloatSlider(\n    value=0.5,\n    min=0.001,\n    max=10,\n    step=0.001,\n    description='Period: ',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.2f',\n)\n\ngain_w2 = widgets.FloatText(\n    value=1.,\n    description='',\n    disabled=True\n)\n\nsimTime = widgets.FloatText(\n    value=20,\n    description='',\n    disabled=False\n)\n```\n\n\n```python\n# Support functions\n\ndef eigen_choice(sele):\n    if sele == '0 complex eigenvalues':\n        eig1c.children[0].children[0].disabled = False\n        eig2c.children[1].children[0].disabled = True\n        eig1o.children[0].children[0].disabled = False\n        eig2o.children[1].children[0].disabled = True\n        eig = 0\n    if sele == '2 complex eigenvalues':\n        eig1c.children[0].children[0].disabled = True\n        eig2c.children[1].children[0].disabled = False\n        eig1o.children[0].children[0].disabled = True\n        eig2o.children[1].children[0].disabled = False\n        eig = 2\n    return eig\n\ndef method_choice(selm):\n    if selm == 'Set K and L':\n        method = 1\n        sele.disabled = True\n    if selm == 'Set the eigenvalues':\n        method = 2\n        sele.disabled = False\n    return method\n```\n\n\n```python\ns = control.tf('s')\nGref = (0.5)**2/(s**2 + 2*0.7*0.5*s + (0.5)**2)\n\ndef main_callback2(Aw, Bw, X0w, K, L, eig1c, eig2c, eig3c, eig1o, eig2o, eig3o, u, period, selm, sele, selu, simTime, DW):\n    eige = eigen_choice(sele)\n    method = method_choice(selm)\n    \n    if method == 1:\n        solc = numpy.linalg.eig(A-B*K)\n        solo = numpy.linalg.eig(A-L*C)\n    if method == 2:\n        if eige == 0:\n            K = control.acker(A, B, [eig1c[0,0], eig2c[0,0], eig3c[0,0]])\n            Kw.setM(K)\n            L = control.acker(A.T, C.T, [eig1o[0,0], eig2o[0,0], eig3o[0,0]]).T\n            Lw.setM(L)\n        if eige == 2:\n            K = control.acker(A, B, [eig3c[0,0], \n                                     numpy.complex(eig2c[0,0],eig2c[1,0]), \n                                     numpy.complex(eig2c[0,0],-eig2c[1,0])])\n            Kw.setM(K)\n            L = control.acker(A.T, C.T, [eig3o[0,0], \n                                         numpy.complex(eig2o[0,0],eig2o[1,0]), \n                                         numpy.complex(eig2o[0,0],-eig2o[1,0])]).T\n            Lw.setM(L)\n            \n    \n    sys = control.ss(A,B,numpy.vstack((C,numpy.zeros((B.shape[1],C.shape[1])))),numpy.vstack((D,numpy.eye(B.shape[1]))))\n    sysC = control.ss(numpy.zeros((1,1)),\n                      numpy.zeros((1,numpy.shape(A)[0])),\n                      numpy.zeros((numpy.shape(B)[1],1)),\n                      -K)\n    \n    sysE = control.ss(A-L*C,\n                      numpy.hstack((L,B-L*D)),\n                      numpy.eye(numpy.shape(A)[0]),\n                      numpy.zeros((A.shape[0],C.shape[0]+B.shape[1])))\n    \n    sys_append = control.append(sys, sysE, sysC, control.ss(A,B,numpy.eye(A.shape[0]),numpy.zeros((A.shape[0],B.shape[1]))))\n    Q = []\n    # y in ingresso a sysE\n    for i in range(C.shape[0]):\n        Q.append([B.shape[1]+i+1, i+1])\n    # u in ingresso a sysE\n    for i in range(B.shape[1]):\n        Q.append([B.shape[1]+C.shape[0]+i+1, C.shape[0]+i+1])\n    # u in ingresso a sys\n    for i in range(B.shape[1]):\n        Q.append([i+1, C.shape[0]+B.shape[1]+A.shape[0]+i+1])\n    # u in ingresso al sistema che ha come uscite gli stati reali\n    for i in range(B.shape[1]):\n        Q.append([2*B.shape[1]+C.shape[0]+A.shape[0]+i+1, C.shape[0]+i+1])\n    # xe in ingresso a sysC\n    for i in range(A.shape[0]):\n        Q.append([2*B.shape[1]+C.shape[0]+i+1, C.shape[0]+B.shape[1]+i+1])\n        \n    inputv = [i+1 for i in range(B.shape[1])]\n    outputv = [i+1 for i in range(numpy.shape(sys_append.C)[0])]\n    sys_CL = control.connect(sys_append,\n                             Q,\n                             inputv,\n                             outputv)\n    \n    t = numpy.linspace(0, 100000, 2)\n    t, yout = control.step_response(sys_CL[0,0],T=t)\n    dcgain = yout[-1]\n    gain_w2.value = dcgain\n    if dcgain != 0:\n        u1 = u/gain_w2.value\n    else:\n        print('The feedforward gain setted is 0 and it is changed to 1')\n        u1 = u/1\n    print('The static gain of the closed-loop system (from the reference to the output) is: %.5f' %dcgain)\n    \n    X0w1 = numpy.zeros((A.shape[0],1))\n    for j in range(A.shape[0]):\n        X0w1 = numpy.vstack((X0w1,X0w[j]))\n    X0w1 = numpy.vstack((X0w1,numpy.zeros((A.shape[0],1))))\n    if simTime != 0:\n        T = numpy.linspace(0, simTime, 10000)\n    else:\n        T = numpy.linspace(0, 1, 10000)\n      \n    if selu == 'impulse': #selu\n        U = [0 for t in range(0,len(T))]\n        U[0] = u\n        U1 = [0 for t in range(0,len(T))]\n        U1[0] = u1\n        T, yout, xout = control.forced_response(sys_CL,T,U1,X0w1)\n        T, yout_ref, xout_ref = control.forced_response(Gref,T,U,[0, 0])\n    if selu == 'step':\n        U = [u for t in range(0,len(T))]\n        U1 = [u1 for t in range(0,len(T))]\n        T, yout, xout = control.forced_response(sys_CL,T,U1,X0w1)\n        T, yout_ref, xout_ref = control.forced_response(Gref,T,U,[0, 0])\n    if selu == 'sinusoid':\n        U = u*numpy.sin(2*numpy.pi/period*T)\n        U1 = u1*numpy.sin(2*numpy.pi/period*T)\n        T, yout, xout = control.forced_response(sys_CL,T,U1,X0w1)\n        T, yout_ref, xout_ref = control.forced_response(Gref,T,U,[0, 0])\n    if selu == 'square wave':\n        U = u*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n        U1 = u1*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n        T, yout, xout = control.forced_response(sys_CL,T,U1,X0w1)\n        T, yout_ref, xout_ref = control.forced_response(Gref,T,U,[0, 0])\n    # N.B. i primi 3 stati di xout sono quelli del sistema, mentre gli ultimi 3 sono quelli dell'osservatore\n    \n    step_info_dict = control.step_info(sys_CL[0,0],SettlingTimeThreshold=0.05,T=T)\n    print('Step info: \\n\\tRise time =',step_info_dict['RiseTime'],'\\n\\tSettling time (5%) =',step_info_dict['SettlingTime'],'\\n\\tOvershoot (%)=',step_info_dict['Overshoot'])\n    # print('Max x3 value (%)=', max(abs(yout[C.shape[0]+2*B.shape[1]+A.shape[0]+2]))/(numpy.pi/180*17)*100)\n    \n    fig = plt.figure(num='Simulation1', figsize=(14,12))\n    \n    fig.add_subplot(221)\n    plt.title('Output response')\n    plt.ylabel('Output')\n    plt.plot(T,yout[0],T,yout_ref,T,U,'r--')\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$y$','Second-order system reference','Reference'])\n    plt.grid()\n    \n    fig.add_subplot(222)\n    plt.title('Input')\n    plt.ylabel('$u$')\n    plt.plot(T,yout[C.shape[0]])\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(223)\n    plt.title('States response')\n    plt.ylabel('States')\n    plt.plot(T,yout[C.shape[0]+2*B.shape[1]+A.shape[0]],\n             T,yout[C.shape[0]+2*B.shape[1]+A.shape[0]+1],\n             T,yout[C.shape[0]+2*B.shape[1]+A.shape[0]+2])\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$x_{1}$','$x_{2}$','$x_{3}$'])\n    plt.grid()\n    \n    fig.add_subplot(224)\n    plt.title('Estimation errors')\n    plt.ylabel('Errors')\n    plt.plot(T,yout[C.shape[0]+2*B.shape[1]+A.shape[0]]-yout[C.shape[0]+B.shape[1]],\n             T,yout[C.shape[0]+2*B.shape[1]+A.shape[0]+1]-yout[C.shape[0]+B.shape[1]+1],\n             T,yout[C.shape[0]+2*B.shape[1]+A.shape[0]+2]-yout[C.shape[0]+B.shape[1]+2])\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$e_{1}$','$e_{2}$','$e_{3}$'])\n    plt.grid()\n    #plt.tight_layout()\n   \nalltogether2 = widgets.VBox([widgets.HBox([selm, \n                                          sele,\n                                          selu]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.Label('K:',border=3), Kw, \n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Eigenvalues:',border=3), \n                                          eig1c, \n                                          eig2c, \n                                          eig3c,\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('X0 est.:',border=3), X0w]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.Label('L:',border=3), Lw, \n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Eigenvalues:',border=3), \n                                          eig1o, \n                                          eig2o, \n                                          eig3o,\n                                          widgets.Label(' ',border=3),\n                                          widgets.VBox([widgets.Label('Inverse reference gain:',border=3),\n                                                        widgets.Label('Simulation time [s]:',border=3)]),\n                                          widgets.VBox([gain_w2,simTime])]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([u, \n                                          period, \n                                          START])])\nout2 = widgets.interactive_output(main_callback2, {'Aw':Aw, 'Bw':Bw, 'X0w':X0w, 'K':Kw, 'L':Lw,\n                                                 'eig1c':eig1c, 'eig2c':eig2c, 'eig3c':eig3c, 'eig1o':eig1o, 'eig2o':eig2o, 'eig3o':eig3o, \n                                                 'u':u, 'period':period, 'selm':selm, 'sele':sele, 'selu':selu, 'simTime':simTime, 'DW':DW})\nout2.layout.height = '860px'\ndisplay(out2, alltogether2)\n```\n\n\n    Output(layout=Layout(height='860px'))\n\n\n\n    VBox(children=(HBox(children=(Dropdown(index=1, options=('Set K and L', 'Set the eigenvalues'), value='Set the\u2026\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "6313c7d80200c2999e240dfbf6534f5e96c6ebf6", "size": 29260, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_en/examples/04/SS-40-Control_of_robotic_arm_with_flexible_joint.ipynb", "max_stars_repo_name": "ICCTerasmus/ICCT", "max_stars_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-22T18:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:10:22.000Z", "max_issues_repo_path": "ICCT/ENG/examples/04/SS-40-Control_of_robotic_arm_with_flexible_joint.ipynb", "max_issues_repo_name": "tuxsaurus/ICCT", "max_issues_repo_head_hexsha": "30d1aea4fb056c9736c9b4c5a0f50fff14fa6382", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICCT/ENG/examples/04/SS-40-Control_of_robotic_arm_with_flexible_joint.ipynb", "max_forks_repo_name": "tuxsaurus/ICCT", "max_forks_repo_head_hexsha": "30d1aea4fb056c9736c9b4c5a0f50fff14fa6382", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-24T11:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T16:36:18.000Z", "avg_line_length": 37.2264631043, "max_line_length": 439, "alphanum_fraction": 0.4761790841, "converted": true, "num_tokens": 5852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491213037224875, "lm_q2_score": 0.12765262698114574, "lm_q1q2_score": 0.04913504459892681}}
{"text": "```python\n%matplotlib inline\n```\n\n\nDCGAN Tutorial\n==============\n\n**Author**: `Nathan Inkawhich <https://github.com/inkawhich>`__\n\n\n\n\nIntroduction\n------------\n\nThis tutorial will give an introduction to DCGANs through an example. We\nwill train a generative adversarial network (GAN) to generate new\ncelebrities after showing it pictures of many real celebrities. Most of\nthe code here is from the dcgan implementation in\n`pytorch/examples <https://github.com/pytorch/examples>`__, and this\ndocument will give a thorough explanation of the implementation and shed\nlight on how and why this model works. But don\u2019t worry, no prior\nknowledge of GANs is required, but it may require a first-timer to spend\nsome time reasoning about what is actually happening under the hood.\nAlso, for the sake of time it will help to have a GPU, or two. Lets\nstart from the beginning.\n\nGenerative Adversarial Networks\n-------------------------------\n\nWhat is a GAN?\n~~~~~~~~~~~~~~\n\nGANs are a framework for teaching a DL model to capture the training\ndata\u2019s distribution so we can generate new data from that same\ndistribution. GANs were invented by Ian Goodfellow in 2014 and first\ndescribed in the paper `Generative Adversarial\nNets <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`__.\nThey are made of two distinct models, a *generator* and a\n*discriminator*. The job of the generator is to spawn \u2018fake\u2019 images that\nlook like the training images. The job of the discriminator is to look\nat an image and output whether or not it is a real training image or a\nfake image from the generator. During training, the generator is\nconstantly trying to outsmart the discriminator by generating better and\nbetter fakes, while the discriminator is working to become a better\ndetective and correctly classify the real and fake images. The\nequilibrium of this game is when the generator is generating perfect\nfakes that look as if they came directly from the training data, and the\ndiscriminator is left to always guess at 50% confidence that the\ngenerator output is real or fake.\n\nNow, lets define some notation to be used throughout tutorial starting\nwith the discriminator. Let $x$ be data representing an image.\n$D(x)$ is the discriminator network which outputs the (scalar)\nprobability that $x$ came from training data rather than the\ngenerator. Here, since we are dealing with images, the input to\n$D(x)$ is an image of CHW size 3x64x64. Intuitively, $D(x)$\nshould be HIGH when $x$ comes from training data and LOW when\n$x$ comes from the generator. $D(x)$ can also be thought of\nas a traditional binary classifier.\n\nFor the generator\u2019s notation, let $z$ be a latent space vector\nsampled from a standard normal distribution. $G(z)$ represents the\ngenerator function which maps the latent vector $z$ to data-space.\nThe goal of $G$ is to estimate the distribution that the training\ndata comes from ($p_{data}$) so it can generate fake samples from\nthat estimated distribution ($p_g$).\n\nSo, $D(G(z))$ is the probability (scalar) that the output of the\ngenerator $G$ is a real image. As described in `Goodfellow\u2019s\npaper <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`__,\n$D$ and $G$ play a minimax game in which $D$ tries to\nmaximize the probability it correctly classifies reals and fakes\n($logD(x)$), and $G$ tries to minimize the probability that\n$D$ will predict its outputs are fake ($log(1-D(G(z)))$).\nFrom the paper, the GAN loss function is\n\n\\begin{align}\\underset{G}{\\text{min}} \\underset{D}{\\text{max}}V(D,G) = \\mathbb{E}_{x\\sim p_{data}(x)}\\big[logD(x)\\big] + \\mathbb{E}_{z\\sim p_{z}(z)}\\big[log(1-D(G(z)))\\big]\\end{align}\n\nIn theory, the solution to this minimax game is where\n$p_g = p_{data}$, and the discriminator guesses randomly if the\ninputs are real or fake. However, the convergence theory of GANs is\nstill being actively researched and in reality models do not always\ntrain to this point.\n\nWhat is a DCGAN?\n~~~~~~~~~~~~~~~~\n\nA DCGAN is a direct extension of the GAN described above, except that it\nexplicitly uses convolutional and convolutional-transpose layers in the\ndiscriminator and generator, respectively. It was first described by\nRadford et. al.\u00a0in the paper `Unsupervised Representation Learning With\nDeep Convolutional Generative Adversarial\nNetworks <https://arxiv.org/pdf/1511.06434.pdf>`__. The discriminator\nis made up of strided\n`convolution <https://pytorch.org/docs/stable/nn.html#torch.nn.Conv2d>`__\nlayers, `batch\nnorm <https://pytorch.org/docs/stable/nn.html#torch.nn.BatchNorm2d>`__\nlayers, and\n`LeakyReLU <https://pytorch.org/docs/stable/nn.html#torch.nn.LeakyReLU>`__\nactivations. The input is a 3x64x64 input image and the output is a\nscalar probability that the input is from the real data distribution.\nThe generator is comprised of\n`convolutional-transpose <https://pytorch.org/docs/stable/nn.html#torch.nn.ConvTranspose2d>`__\nlayers, batch norm layers, and\n`ReLU <https://pytorch.org/docs/stable/nn.html#relu>`__ activations. The\ninput is a latent vector, $z$, that is drawn from a standard\nnormal distribution and the output is a 3x64x64 RGB image. The strided\nconv-transpose layers allow the latent vector to be transformed into a\nvolume with the same shape as an image. In the paper, the authors also\ngive some tips about how to setup the optimizers, how to calculate the\nloss functions, and how to initialize the model weights, all of which\nwill be explained in the coming sections.\n\n\n\n\n\n```python\nfrom __future__ import print_function\n#%matplotlib inline\nimport argparse\nimport os\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nimport torch.utils.data\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport torchvision.utils as vutils\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom IPython.display import HTML\n\n# Set random seed for reproducibility\nmanualSeed = 999\n#manualSeed = random.randint(1, 10000) # use if you want new results\nprint(\"Random Seed: \", manualSeed)\nrandom.seed(manualSeed)\ntorch.manual_seed(manualSeed)\n```\n\nInputs\n------\n\nLet\u2019s define some inputs for the run:\n\n-  **dataroot** - the path to the root of the dataset folder. We will\n   talk more about the dataset in the next section\n-  **workers** - the number of worker threads for loading the data with\n   the DataLoader\n-  **batch_size** - the batch size used in training. The DCGAN paper\n   uses a batch size of 128\n-  **image_size** - the spatial size of the images used for training.\n   This implementation defaults to 64x64. If another size is desired,\n   the structures of D and G must be changed. See\n   `here <https://github.com/pytorch/examples/issues/70>`__ for more\n   details\n-  **nc** - number of color channels in the input images. For color\n   images this is 3\n-  **nz** - length of latent vector\n-  **ngf** - relates to the depth of feature maps carried through the\n   generator\n-  **ndf** - sets the depth of feature maps propagated through the\n   discriminator\n-  **num_epochs** - number of training epochs to run. Training for\n   longer will probably lead to better results but will also take much\n   longer\n-  **lr** - learning rate for training. As described in the DCGAN paper,\n   this number should be 0.0002\n-  **beta1** - beta1 hyperparameter for Adam optimizers. As described in\n   paper, this number should be 0.5\n-  **ngpu** - number of GPUs available. If this is 0, code will run in\n   CPU mode. If this number is greater than 0 it will run on that number\n   of GPUs\n\n\n\n\n\n```python\n# Root directory for dataset\ndataroot = \"data/celeba\"\n\n# Number of workers for dataloader\nworkers = 2\n\n# Batch size during training\nbatch_size = 128\n\n# Spatial size of training images. All images will be resized to this\n#   size using a transformer.\nimage_size = 64\n\n# Number of channels in the training images. For color images this is 3\nnc = 3\n\n# Size of z latent vector (i.e. size of generator input)\nnz = 100\n\n# Size of feature maps in generator\nngf = 64\n\n# Size of feature maps in discriminator\nndf = 64\n\n# Number of training epochs\nnum_epochs = 5\n\n# Learning rate for optimizers\nlr = 0.0002\n\n# Beta1 hyperparam for Adam optimizers\nbeta1 = 0.5\n\n# Number of GPUs available. Use 0 for CPU mode.\nngpu = 1\n```\n\nData\n----\n\nIn this tutorial we will use the `Celeb-A Faces\ndataset <http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html>`__ which can\nbe downloaded at the linked site, or in `Google\nDrive <https://drive.google.com/drive/folders/0B7EVK8r0v71pTUZsaXdaSnZBZzg>`__.\nThe dataset will download as a file named *img_align_celeba.zip*. Once\ndownloaded, create a directory named *celeba* and extract the zip file\ninto that directory. Then, set the *dataroot* input for this notebook to\nthe *celeba* directory you just created. The resulting directory\nstructure should be:\n\n::\n\n   /path/to/celeba\n       -> img_align_celeba  \n           -> 188242.jpg\n           -> 173822.jpg\n           -> 284702.jpg\n           -> 537394.jpg\n              ...\n\nThis is an important step because we will be using the ImageFolder\ndataset class, which requires there to be subdirectories in the\ndataset\u2019s root folder. Now, we can create the dataset, create the\ndataloader, set the device to run on, and finally visualize some of the\ntraining data.\n\n\n\n\n\n```python\n# We can use an image folder dataset the way we have it setup.\n# Create the dataset\ndataset = dset.ImageFolder(root=dataroot,\n                           transform=transforms.Compose([\n                               transforms.Resize(image_size),\n                               transforms.CenterCrop(image_size),\n                               transforms.ToTensor(),\n                               transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n                           ]))\n# Create the dataloader\ndataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size,\n                                         shuffle=True, num_workers=workers)\n\n# Decide which device we want to run on\ndevice = torch.device(\"cuda:0\" if (torch.cuda.is_available() and ngpu > 0) else \"cpu\")\n\n# Plot some training images\nreal_batch = next(iter(dataloader))\nplt.figure(figsize=(8,8))\nplt.axis(\"off\")\nplt.title(\"Training Images\")\nplt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device)[:64], padding=2, normalize=True).cpu(),(1,2,0)))\n```\n\nImplementation\n--------------\n\nWith our input parameters set and the dataset prepared, we can now get\ninto the implementation. We will start with the weight initialization\nstrategy, then talk about the generator, discriminator, loss functions,\nand training loop in detail.\n\nWeight Initialization\n~~~~~~~~~~~~~~~~~~~~~\n\nFrom the DCGAN paper, the authors specify that all model weights shall\nbe randomly initialized from a Normal distribution with mean=0,\nstdev=0.02. The ``weights_init`` function takes an initialized model as\ninput and reinitializes all convolutional, convolutional-transpose, and\nbatch normalization layers to meet this criteria. This function is\napplied to the models immediately after initialization.\n\n\n\n\n\n```python\n# custom weights initialization called on netG and netD\ndef weights_init(m):\n    classname = m.__class__.__name__\n    if classname.find('Conv') != -1:\n        nn.init.normal_(m.weight.data, 0.0, 0.02)\n    elif classname.find('BatchNorm') != -1:\n        nn.init.normal_(m.weight.data, 1.0, 0.02)\n        nn.init.constant_(m.bias.data, 0)\n```\n\nGenerator\n~~~~~~~~~\n\nThe generator, $G$, is designed to map the latent space vector\n($z$) to data-space. Since our data are images, converting\n$z$ to data-space means ultimately creating a RGB image with the\nsame size as the training images (i.e.\u00a03x64x64). In practice, this is\naccomplished through a series of strided two dimensional convolutional\ntranspose layers, each paired with a 2d batch norm layer and a relu\nactivation. The output of the generator is fed through a tanh function\nto return it to the input data range of $[-1,1]$. It is worth\nnoting the existence of the batch norm functions after the\nconv-transpose layers, as this is a critical contribution of the DCGAN\npaper. These layers help with the flow of gradients during training. An\nimage of the generator from the DCGAN paper is shown below.\n\n.. figure:: /_static/img/dcgan_generator.png\n   :alt: dcgan_generator\n\nNotice, how the inputs we set in the input section (*nz*, *ngf*, and\n*nc*) influence the generator architecture in code. *nz* is the length\nof the z input vector, *ngf* relates to the size of the feature maps\nthat are propagated through the generator, and *nc* is the number of\nchannels in the output image (set to 3 for RGB images). Below is the\ncode for the generator.\n\n\n\n\n\n```python\n# Generator Code\n\nclass Generator(nn.Module):\n    def __init__(self, ngpu):\n        super(Generator, self).__init__()\n        self.ngpu = ngpu\n        self.main = nn.Sequential(\n            # input is Z, going into a convolution\n            nn.ConvTranspose2d( nz, ngf * 8, 4, 1, 0, bias=False),\n            nn.BatchNorm2d(ngf * 8),\n            nn.ReLU(True),\n            # state size. (ngf*8) x 4 x 4\n            nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False),\n            nn.BatchNorm2d(ngf * 4),\n            nn.ReLU(True),\n            # state size. (ngf*4) x 8 x 8\n            nn.ConvTranspose2d( ngf * 4, ngf * 2, 4, 2, 1, bias=False),\n            nn.BatchNorm2d(ngf * 2),\n            nn.ReLU(True),\n            # state size. (ngf*2) x 16 x 16\n            nn.ConvTranspose2d( ngf * 2, ngf, 4, 2, 1, bias=False),\n            nn.BatchNorm2d(ngf),\n            nn.ReLU(True),\n            # state size. (ngf) x 32 x 32\n            nn.ConvTranspose2d( ngf, nc, 4, 2, 1, bias=False),\n            nn.Tanh()\n            # state size. (nc) x 64 x 64\n        )\n\n    def forward(self, input):\n        return self.main(input)\n```\n\nNow, we can instantiate the generator and apply the ``weights_init``\nfunction. Check out the printed model to see how the generator object is\nstructured.\n\n\n\n\n\n```python\n# Create the generator\nnetG = Generator(ngpu).to(device)\n\n# Handle multi-gpu if desired\nif (device.type == 'cuda') and (ngpu > 1):\n    netG = nn.DataParallel(netG, list(range(ngpu)))\n\n# Apply the weights_init function to randomly initialize all weights\n#  to mean=0, stdev=0.02.\nnetG.apply(weights_init)\n\n# Print the model\nprint(netG)\n```\n\nDiscriminator\n~~~~~~~~~~~~~\n\nAs mentioned, the discriminator, $D$, is a binary classification\nnetwork that takes an image as input and outputs a scalar probability\nthat the input image is real (as opposed to fake). Here, $D$ takes\na 3x64x64 input image, processes it through a series of Conv2d,\nBatchNorm2d, and LeakyReLU layers, and outputs the final probability\nthrough a Sigmoid activation function. This architecture can be extended\nwith more layers if necessary for the problem, but there is significance\nto the use of the strided convolution, BatchNorm, and LeakyReLUs. The\nDCGAN paper mentions it is a good practice to use strided convolution\nrather than pooling to downsample because it lets the network learn its\nown pooling function. Also batch norm and leaky relu functions promote\nhealthy gradient flow which is critical for the learning process of both\n$G$ and $D$.\n\n\n\n\nDiscriminator Code\n\n\n\n\n```python\nclass Discriminator(nn.Module):\n    def __init__(self, ngpu):\n        super(Discriminator, self).__init__()\n        self.ngpu = ngpu\n        self.main = nn.Sequential(\n            # input is (nc) x 64 x 64\n            nn.Conv2d(nc, ndf, 4, 2, 1, bias=False),\n            nn.LeakyReLU(0.2, inplace=True),\n            # state size. (ndf) x 32 x 32\n            nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False),\n            nn.BatchNorm2d(ndf * 2),\n            nn.LeakyReLU(0.2, inplace=True),\n            # state size. (ndf*2) x 16 x 16\n            nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False),\n            nn.BatchNorm2d(ndf * 4),\n            nn.LeakyReLU(0.2, inplace=True),\n            # state size. (ndf*4) x 8 x 8\n            nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False),\n            nn.BatchNorm2d(ndf * 8),\n            nn.LeakyReLU(0.2, inplace=True),\n            # state size. (ndf*8) x 4 x 4\n            nn.Conv2d(ndf * 8, 1, 4, 1, 0, bias=False),\n            nn.Sigmoid()\n        )\n\n    def forward(self, input):\n        return self.main(input)\n```\n\nNow, as with the generator, we can create the discriminator, apply the\n``weights_init`` function, and print the model\u2019s structure.\n\n\n\n\n\n```python\n# Create the Discriminator\nnetD = Discriminator(ngpu).to(device)\n\n# Handle multi-gpu if desired\nif (device.type == 'cuda') and (ngpu > 1):\n    netD = nn.DataParallel(netD, list(range(ngpu)))\n    \n# Apply the weights_init function to randomly initialize all weights\n#  to mean=0, stdev=0.2.\nnetD.apply(weights_init)\n\n# Print the model\nprint(netD)\n```\n\nLoss Functions and Optimizers\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWith $D$ and $G$ setup, we can specify how they learn\nthrough the loss functions and optimizers. We will use the Binary Cross\nEntropy loss\n(`BCELoss <https://pytorch.org/docs/stable/nn.html#torch.nn.BCELoss>`__)\nfunction which is defined in PyTorch as:\n\n\\begin{align}\\ell(x, y) = L = \\{l_1,\\dots,l_N\\}^\\top, \\quad l_n = - \\left[ y_n \\cdot \\log x_n + (1 - y_n) \\cdot \\log (1 - x_n) \\right]\\end{align}\n\nNotice how this function provides the calculation of both log components\nin the objective function (i.e. $log(D(x))$ and\n$log(1-D(G(z)))$). We can specify what part of the BCE equation to\nuse with the $y$ input. This is accomplished in the training loop\nwhich is coming up soon, but it is important to understand how we can\nchoose which component we wish to calculate just by changing $y$\n(i.e.\u00a0GT labels).\n\nNext, we define our real label as 1 and the fake label as 0. These\nlabels will be used when calculating the losses of $D$ and\n$G$, and this is also the convention used in the original GAN\npaper. Finally, we set up two separate optimizers, one for $D$ and\none for $G$. As specified in the DCGAN paper, both are Adam\noptimizers with learning rate 0.0002 and Beta1 = 0.5. For keeping track\nof the generator\u2019s learning progression, we will generate a fixed batch\nof latent vectors that are drawn from a Gaussian distribution\n(i.e.\u00a0fixed_noise) . In the training loop, we will periodically input\nthis fixed_noise into $G$, and over the iterations we will see\nimages form out of the noise.\n\n\n\n\n\n```python\n# Initialize BCELoss function\ncriterion = nn.BCELoss()\n\n# Create batch of latent vectors that we will use to visualize\n#  the progression of the generator\nfixed_noise = torch.randn(64, nz, 1, 1, device=device)\n\n# Establish convention for real and fake labels during training\nreal_label = 1.\nfake_label = 0.\n\n# Setup Adam optimizers for both G and D\noptimizerD = optim.Adam(netD.parameters(), lr=lr, betas=(beta1, 0.999))\noptimizerG = optim.Adam(netG.parameters(), lr=lr, betas=(beta1, 0.999))\n```\n\nTraining\n~~~~~~~~\n\nFinally, now that we have all of the parts of the GAN framework defined,\nwe can train it. Be mindful that training GANs is somewhat of an art\nform, as incorrect hyperparameter settings lead to mode collapse with\nlittle explanation of what went wrong. Here, we will closely follow\nAlgorithm 1 from Goodfellow\u2019s paper, while abiding by some of the best\npractices shown in `ganhacks <https://github.com/soumith/ganhacks>`__.\nNamely, we will \u201cconstruct different mini-batches for real and fake\u201d\nimages, and also adjust G\u2019s objective function to maximize\n$logD(G(z))$. Training is split up into two main parts. Part 1\nupdates the Discriminator and Part 2 updates the Generator.\n\n**Part 1 - Train the Discriminator**\n\nRecall, the goal of training the discriminator is to maximize the\nprobability of correctly classifying a given input as real or fake. In\nterms of Goodfellow, we wish to \u201cupdate the discriminator by ascending\nits stochastic gradient\u201d. Practically, we want to maximize\n$log(D(x)) + log(1-D(G(z)))$. Due to the separate mini-batch\nsuggestion from ganhacks, we will calculate this in two steps. First, we\nwill construct a batch of real samples from the training set, forward\npass through $D$, calculate the loss ($log(D(x))$), then\ncalculate the gradients in a backward pass. Secondly, we will construct\na batch of fake samples with the current generator, forward pass this\nbatch through $D$, calculate the loss ($log(1-D(G(z)))$),\nand *accumulate* the gradients with a backward pass. Now, with the\ngradients accumulated from both the all-real and all-fake batches, we\ncall a step of the Discriminator\u2019s optimizer.\n\n**Part 2 - Train the Generator**\n\nAs stated in the original paper, we want to train the Generator by\nminimizing $log(1-D(G(z)))$ in an effort to generate better fakes.\nAs mentioned, this was shown by Goodfellow to not provide sufficient\ngradients, especially early in the learning process. As a fix, we\ninstead wish to maximize $log(D(G(z)))$. In the code we accomplish\nthis by: classifying the Generator output from Part 1 with the\nDiscriminator, computing G\u2019s loss *using real labels as GT*, computing\nG\u2019s gradients in a backward pass, and finally updating G\u2019s parameters\nwith an optimizer step. It may seem counter-intuitive to use the real\nlabels as GT labels for the loss function, but this allows us to use the\n$log(x)$ part of the BCELoss (rather than the $log(1-x)$\npart) which is exactly what we want.\n\nFinally, we will do some statistic reporting and at the end of each\nepoch we will push our fixed_noise batch through the generator to\nvisually track the progress of G\u2019s training. The training statistics\nreported are:\n\n-  **Loss_D** - discriminator loss calculated as the sum of losses for\n   the all real and all fake batches ($log(D(x)) + log(1 - D(G(z)))$).\n-  **Loss_G** - generator loss calculated as $log(D(G(z)))$\n-  **D(x)** - the average output (across the batch) of the discriminator\n   for the all real batch. This should start close to 1 then\n   theoretically converge to 0.5 when G gets better. Think about why\n   this is.\n-  **D(G(z))** - average discriminator outputs for the all fake batch.\n   The first number is before D is updated and the second number is\n   after D is updated. These numbers should start near 0 and converge to\n   0.5 as G gets better. Think about why this is.\n\n**Note:** This step might take a while, depending on how many epochs you\nrun and if you removed some data from the dataset.\n\n\n\n\n\n```python\n# Training Loop\n\n# Lists to keep track of progress\nimg_list = []\nG_losses = []\nD_losses = []\niters = 0\n\nprint(\"Starting Training Loop...\")\n# For each epoch\nfor epoch in range(num_epochs):\n    # For each batch in the dataloader\n    for i, data in enumerate(dataloader, 0):\n        \n        ############################\n        # (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))\n        ###########################\n        ## Train with all-real batch\n        netD.zero_grad()\n        # Format batch\n        real_cpu = data[0].to(device)\n        b_size = real_cpu.size(0)\n        label = torch.full((b_size,), real_label, dtype=torch.float, device=device)\n        # Forward pass real batch through D\n        output = netD(real_cpu).view(-1)\n        # Calculate loss on all-real batch\n        errD_real = criterion(output, label)\n        # Calculate gradients for D in backward pass\n        errD_real.backward()\n        D_x = output.mean().item()\n\n        ## Train with all-fake batch\n        # Generate batch of latent vectors\n        noise = torch.randn(b_size, nz, 1, 1, device=device)\n        # Generate fake image batch with G\n        fake = netG(noise)\n        label.fill_(fake_label)\n        # Classify all fake batch with D\n        output = netD(fake.detach()).view(-1)\n        # Calculate D's loss on the all-fake batch\n        errD_fake = criterion(output, label)\n        # Calculate the gradients for this batch, accumulated (summed) with previous gradients\n        errD_fake.backward()\n        D_G_z1 = output.mean().item()\n        # Compute error of D as sum over the fake and the real batches\n        errD = errD_real + errD_fake\n        # Update D\n        optimizerD.step()\n\n        ############################\n        # (2) Update G network: maximize log(D(G(z)))\n        ###########################\n        netG.zero_grad()\n        label.fill_(real_label)  # fake labels are real for generator cost\n        # Since we just updated D, perform another forward pass of all-fake batch through D\n        output = netD(fake).view(-1)\n        # Calculate G's loss based on this output\n        errG = criterion(output, label)\n        # Calculate gradients for G\n        errG.backward()\n        D_G_z2 = output.mean().item()\n        # Update G\n        optimizerG.step()\n        \n        # Output training stats\n        if i % 50 == 0:\n            print('[%d/%d][%d/%d]\\tLoss_D: %.4f\\tLoss_G: %.4f\\tD(x): %.4f\\tD(G(z)): %.4f / %.4f'\n                  % (epoch, num_epochs, i, len(dataloader),\n                     errD.item(), errG.item(), D_x, D_G_z1, D_G_z2))\n        \n        # Save Losses for plotting later\n        G_losses.append(errG.item())\n        D_losses.append(errD.item())\n        \n        # Check how the generator is doing by saving G's output on fixed_noise\n        if (iters % 500 == 0) or ((epoch == num_epochs-1) and (i == len(dataloader)-1)):\n            with torch.no_grad():\n                fake = netG(fixed_noise).detach().cpu()\n            img_list.append(vutils.make_grid(fake, padding=2, normalize=True))\n            \n        iters += 1\n```\n\nResults\n-------\n\nFinally, lets check out how we did. Here, we will look at three\ndifferent results. First, we will see how D and G\u2019s losses changed\nduring training. Second, we will visualize G\u2019s output on the fixed_noise\nbatch for every epoch. And third, we will look at a batch of real data\nnext to a batch of fake data from G.\n\n**Loss versus training iteration**\n\nBelow is a plot of D & G\u2019s losses versus training iterations.\n\n\n\n\n\n```python\nplt.figure(figsize=(10,5))\nplt.title(\"Generator and Discriminator Loss During Training\")\nplt.plot(G_losses,label=\"G\")\nplt.plot(D_losses,label=\"D\")\nplt.xlabel(\"iterations\")\nplt.ylabel(\"Loss\")\nplt.legend()\nplt.show()\n```\n\n**Visualization of G\u2019s progression**\n\nRemember how we saved the generator\u2019s output on the fixed_noise batch\nafter every epoch of training. Now, we can visualize the training\nprogression of G with an animation. Press the play button to start the\nanimation.\n\n\n\n\n\n```python\n#%%capture\nfig = plt.figure(figsize=(8,8))\nplt.axis(\"off\")\nims = [[plt.imshow(np.transpose(i,(1,2,0)), animated=True)] for i in img_list]\nani = animation.ArtistAnimation(fig, ims, interval=1000, repeat_delay=1000, blit=True)\n\nHTML(ani.to_jshtml())\n```\n\n**Real Images vs.\u00a0Fake Images**\n\nFinally, lets take a look at some real images and fake images side by\nside.\n\n\n\n\n\n```python\n# Grab a batch of real images from the dataloader\nreal_batch = next(iter(dataloader))\n\n# Plot the real images\nplt.figure(figsize=(15,15))\nplt.subplot(1,2,1)\nplt.axis(\"off\")\nplt.title(\"Real Images\")\nplt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device)[:64], padding=5, normalize=True).cpu(),(1,2,0)))\n\n# Plot the fake images from the last epoch\nplt.subplot(1,2,2)\nplt.axis(\"off\")\nplt.title(\"Fake Images\")\nplt.imshow(np.transpose(img_list[-1],(1,2,0)))\nplt.show()\n```\n\nWhere to Go Next\n----------------\n\nWe have reached the end of our journey, but there are several places you\ncould go from here. You could:\n\n-  Train for longer to see how good the results get\n-  Modify this model to take a different dataset and possibly change the\n   size of the images and the model architecture\n-  Check out some other cool GAN projects\n   `here <https://github.com/nashory/gans-awesome-applications>`__\n-  Create GANs that generate\n   `music <https://deepmind.com/blog/wavenet-generative-model-raw-audio/>`__\n\n\n\n", "meta": {"hexsha": "6d13c572a25946130fe259e32fe24bfbd2d3a88c", "size": 33207, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "dcgan_faces_tutorial.ipynb", "max_stars_repo_name": "makiit/PyTorch-VAE", "max_stars_repo_head_hexsha": "99312dfbc94055dde89a1058de314b410991391a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dcgan_faces_tutorial.ipynb", "max_issues_repo_name": "makiit/PyTorch-VAE", "max_issues_repo_head_hexsha": "99312dfbc94055dde89a1058de314b410991391a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dcgan_faces_tutorial.ipynb", "max_forks_repo_name": "makiit/PyTorch-VAE", "max_forks_repo_head_hexsha": "99312dfbc94055dde89a1058de314b410991391a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 114.1134020619, "max_line_length": 5479, "alphanum_fraction": 0.6605233836, "converted": true, "num_tokens": 7158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491214448393357, "lm_q2_score": 0.12765261536566067, "lm_q1q2_score": 0.049135041929379175}}
{"text": "```python\n#!pip3 install -U scikit-learn\n```\n\n    Collecting scikit-learn\n      Downloading scikit_learn-0.22.2.post1-cp37-cp37m-manylinux1_x86_64.whl (7.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 7.1 MB 1.5 MB/s eta 0:00:01     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b   | 6.3 MB 1.5 MB/s eta 0:00:01\n    \u001b[?25hRequirement already satisfied, skipping upgrade: scipy>=0.17.0 in /home/kodolamacz/anaconda3/lib/python3.7/site-packages (from scikit-learn) (1.1.0)\n    Collecting joblib>=0.11\n      Downloading joblib-0.14.1-py2.py3-none-any.whl (294 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 294 kB 264 kB/s eta 0:00:01\n    \u001b[?25hRequirement already satisfied, skipping upgrade: numpy>=1.11.0 in /home/kodolamacz/anaconda3/lib/python3.7/site-packages (from scikit-learn) (1.15.1)\n    Installing collected packages: joblib, scikit-learn\n      Attempting uninstall: scikit-learn\n        Found existing installation: scikit-learn 0.19.2\n        Uninstalling scikit-learn-0.19.2:\n          Successfully uninstalled scikit-learn-0.19.2\n    Successfully installed joblib-0.14.1 scikit-learn-0.22.2.post1\n\n\n\n```python\nimport sklearn\nsklearn.__version__\n\n# Jesli wersja nie jest przynajmnije 0.21 to:\n\n#!pip3 install -U sklearn\n#!pip3 install -U scikit-learn\n\n#i restart j\u0105dra\n```\n\n\n\n\n    '0.22.2.post1'\n\n\n\n# <center>Uczenie maszynowe</center>\n\n<br>\n\n<br>\n\n## <center>Proces rozwi\u0105zywania problem\u00f3w z zastosowaniem uczenia maszynowego</center>\n\n\n\u0179r\u00f3d\u0142o: https://upload.wikimedia.org/wikipedia/commons/thumb/b/b9/CRISP-DM_Process_Diagram.png/897px-CRISP-DM_Process_Diagram.png\n\n<br>\n\n<br>\n\n<br>\n\n<br>\n\n<br>\n\n\n\n\n <br>\n\n## Kilka fakt\u00f3w na temat uczenia maszynowego\n\n* ML to zar\u00f3wno nauka jak i sztuka.\n\n* Nie istnieje metoda \"najlepsza\" - ka\u017cdy problem wymaga indywidualnego podej\u015bcia.\n\n* Rozwi\u0105zanie problemu ML = reprezentacja danych + algorytm.\n\n  - w codziennej praktyce pierwszy czynnik cz\u0119sto niedoceniany. Przetworzenie danych jest r\u00f3wnie wa\u017cne jak same algorytmy, a nawet cz\u0119sto dane s\u0105 wa\u017cniejsze od algorytmu - wi\u0119kszy wp\u0142yw na wyniki ma posta\u0107 danych ni\u017c wyb\u00f3r konkretnego algorytmu.\n\n* Bardzo wa\u017cne jest zdefiniowanie celu jaki chcemy osi\u0105gn\u0105\u0107 i rozumienie jak dane i algorytmy z tym celem si\u0119\u00a0wi\u0105\u017c\u0105.\n\n\n <br>\n \n <br>\n \n <br>\n \n <br>\n \n <br>\n \n <br>\n \n <br>\n \n <br>\n \n ## Dwa g\u0142\u00f3wne nurty uczenia maszynowego:\n* uczenie nadzorowane (*supervised learning*)\n* uczenie nienadzorowane (*unsupervised learning*)\n\n  <br>\n \n <br>\n \n <br>\n \n <br>\n \n <br>\n \n <br>\n \n <br>\n \n## Uczenie nadzorowane\n\nDla znanych par (X,Y) szukamy zale\u017cno\u015bci mi\u0119dzy X a Y - budujemy model, kt\u00f3ry na podstawie X przewidzi Y.\n \n\n* regresja: Y jest zmienn\u0105\u00a0rzeczywist\u0105\n\n* klasyfikacja: Y jest zmienn\u0105 dyskretn\u0105 (np. binarn\u0105 - o warto\u015bciach 0 i 1)\n\n <br>\n \n <br>\n \n <br>\n \n <br>\n \n <br>\n \n <br>\n \n <br>\n \n## Zagadnienie klasyfikacji - przyk\u0142ady:\n- predykcja churnu - przewidywanie na podstawie cech klienta (opisuj\u0105cych m.in. jego zachowanie) czy klient odejdzie w najbli\u017cszym czasie (np. w ci\u0105gu miesi\u0105ca);\n- scoring kredytowy - na poziomie ostatecznej decyzji - da\u0107 czy nie da\u0107 kredyt;\n- rozpoznawanie choroby - rozpoznawanie na podstawie parametr\u00f3w medycznych czy pacjent zachoruje/jest chory;\n- klasyfikacja tematyczna tekstu;\n- klasyfikacja wyd\u017awi\u0119ku opini;\n- rozpoznawanie zawartosci obraz\u00f3w (dla okreslonej liczby typ\u00f3w obraz\u00f3w).\n\n# Regresja logistyczna\n\nRozwa\u017camy problem klasyfikacji binarnej: $X \\in \\mathbb{R}^p$, $Y \\in \\{0, 1\\}$.\n\nZa\u0142o\u017cenia modelu:\n\n$$\nY =\n\\begin{cases}\n1, \\text{ z prawdopodobie\u0144stwem } \\pi(x)\\\\\n0, \\text{ z prawdopodobie\u0144stwem } 1-\\pi(x).\\\\\n\\end{cases}$$\n\n, gdzie\n\n$\\pi(x)=P(Y=1 \\mid x)$.\n\nCzyli innymi s\u0142owy:\n\n$$\\large Y \\sim B(\\pi(x)),$$\n\n\nB($\\cdot$) - rozk\u0142ad dwupunktowy, \n\n\nModel:\n\n$$\\large \\pi(x) = \\frac{1}{1+e^{-\\beta x}},$$\n\n$\\beta = (\\beta_0,\\beta_1, \\ldots, \\beta_p),$   $\\beta x = \\beta_0 + \\beta_1 x_1 + \\ldots + \\beta_p x_p.$\n\n <br>\n \n <br>\n \nPredykcja warto\u015bci Y przy u\u017cyciu regresji logistycznej:\n\n$$\n\\hat{y} =\n\\begin{cases}\n1, \\text{ gdy } \\pi(x) > 0.5\\\\\n0, \\text{ gdy } \\pi(x) \\leq 0.5\\\\\n\\end{cases}\n$$\n \n <br>\n \n <br>\n \n <br>\n\nDopasowanie (uczenie) modelu = znalezienie optymalnych warto\u015bci wsp\u00f3\u0142czynnik\u00f3w wektora $\\beta$, czyli takich, kt\u00f3re najlepiej opisuj\u0105 zale\u017cno\u015b\u0107 $Y$ od $X$. \n\n <br>\n \n <br>\n \n <br>\n \nNajlepiej czyli jak?\n \n## Metoda najwi\u0119kszej wiarogodno\u015bci\n \nRozwa\u017cmy sytuacj\u0119 binarn\u0105. tzn. $y \\in \\{0,1\\}$. Logarytm funkcji wiarogodno\u015bci wygl\u0105da nast\u0119puj\u0105co (X zbi\u00f3r obserwacji, Y - zbi\u00f3r etykiet):\n\n$ \n\\begin{align}\nL(\\beta \\ | \\ X,Y) & = \\log \\prod\\limits_{i=1}^n P(Y_i=y_i \\ | \\ x_i) \\\\\n       & = \\log \\prod\\limits_{i=1}^n \\pi(x_i)^{y_i}(1-\\pi(x_i))^{1-y_i} \\\\\n       & = \\sum\\limits_{i=1}^n \\log\\big( \\pi(x_i)^{y_i}(1-\\pi(x_i))^{1-y_i}\\big) \\\\\n       & = \\sum\\limits_{i=1}^n y_i\\log(\\pi(x_i)) + (1-y_i)\\log(1-\\pi(x_i)) .\n\\end{align}\n$\n\nPrzyjmijmy oznaczenie: $h(\\pi(x),y) = y\\log{(\\pi(x))} + (1-y)\\log{(1-\\pi(x))}.$\nZauwa\u017cmy, \u017ce:\n\n$h(\\pi(x),1) = \\log{(\\pi(x))}$\n\n$h(\\pi(x),0) = \\log{(1-\\pi(x))}$\n\nJe\u017celi $y=1$ to model jest tym lepszy im $\\pi(x)$ jest wi\u0119ksze. Je\u017celi $y=0$, to model jest tym lepszy im $\\pi(x)$ jest mniejsze, czyli $1 - \\pi(x)$ wi\u0119ksze.\n\nDopasowywanie modelu regresji logistycznej polega na maksymalizacji funkcji wiarogodno\u015bci (technicznie - jej logarytmu) - szukamy (numerycznie) takiego wektora $\\beta$, dla kt\u00f3rego wiarogodno\u015b\u0107 jest najwi\u0119ksza.\n\n\n\n```python\nfrom warnings import filterwarnings\nfilterwarnings(\"ignore\")\n```\n\n\n```python\nfrom sklearn.datasets import load_breast_cancer\n```\n\n\n```python\n?load_breast_cancer\n```\n\n\n```python\ndata = load_breast_cancer()\n```\n\n\n```python\nX, y = data.data, data.target\n```\n\n\n```python\nX\n```\n\n\n\n\n    array([[1.799e+01, 1.038e+01, 1.228e+02, ..., 2.654e-01, 4.601e-01,\n            1.189e-01],\n           [2.057e+01, 1.777e+01, 1.329e+02, ..., 1.860e-01, 2.750e-01,\n            8.902e-02],\n           [1.969e+01, 2.125e+01, 1.300e+02, ..., 2.430e-01, 3.613e-01,\n            8.758e-02],\n           ...,\n           [1.660e+01, 2.808e+01, 1.083e+02, ..., 1.418e-01, 2.218e-01,\n            7.820e-02],\n           [2.060e+01, 2.933e+01, 1.401e+02, ..., 2.650e-01, 4.087e-01,\n            1.240e-01],\n           [7.760e+00, 2.454e+01, 4.792e+01, ..., 0.000e+00, 2.871e-01,\n            7.039e-02]])\n\n\n\n\n```python\nX.shape\n```\n\n\n\n\n    (569, 30)\n\n\n\n\n```python\ny\n```\n\n\n\n\n    array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,\n           0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,\n           0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0,\n           1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0,\n           1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1,\n           1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0,\n           0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1,\n           1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1,\n           1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0,\n           0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0,\n           1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1,\n           1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n           0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1,\n           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1,\n           1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0,\n           0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0,\n           0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0,\n           1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1,\n           1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0,\n           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1,\n           1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0,\n           1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1,\n           1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1,\n           1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1,\n           1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1])\n\n\n\n\n```python\ndata.feature_names\n```\n\n\n\n\n    array(['mean radius', 'mean texture', 'mean perimeter', 'mean area',\n           'mean smoothness', 'mean compactness', 'mean concavity',\n           'mean concave points', 'mean symmetry', 'mean fractal dimension',\n           'radius error', 'texture error', 'perimeter error', 'area error',\n           'smoothness error', 'compactness error', 'concavity error',\n           'concave points error', 'symmetry error',\n           'fractal dimension error', 'worst radius', 'worst texture',\n           'worst perimeter', 'worst area', 'worst smoothness',\n           'worst compactness', 'worst concavity', 'worst concave points',\n           'worst symmetry', 'worst fractal dimension'], dtype='<U23')\n\n\n\n\n```python\ny.mean()\n```\n\n\n\n\n    0.6274165202108963\n\n\n\n\n```python\nfrom sklearn.linear_model import LogisticRegression\n```\n\n\n```python\nmodel = LogisticRegression()\n```\n\n\n```python\nmodel.fit(X,y)\n```\n\n    /home/kodolamacz/anaconda3/lib/python3.7/site-packages/sklearn/linear_model/_logistic.py:940: ConvergenceWarning: lbfgs failed to converge (status=1):\n    STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n    \n    Increase the number of iterations (max_iter) or scale the data as shown in:\n        https://scikit-learn.org/stable/modules/preprocessing.html\n    Please also refer to the documentation for alternative solver options:\n        https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n      extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG)\n\n\n\n\n\n    LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,\n                       intercept_scaling=1, l1_ratio=None, max_iter=100,\n                       multi_class='auto', n_jobs=None, penalty='l2',\n                       random_state=None, solver='lbfgs', tol=0.0001, verbose=0,\n                       warm_start=False)\n\n\n\n\n```python\nmodel.intercept_, model.coef_\n```\n\n\n\n\n    (array([0.17602134]),\n     array([[ 0.94461853,  0.45691059,  0.2771816 , -0.01588461, -0.03513972,\n             -0.16555268, -0.23179226, -0.09762309, -0.0486746 , -0.00971057,\n              0.04103891,  0.3728471 ,  0.14478376, -0.10911838, -0.00317849,\n             -0.03559393, -0.0495699 , -0.01271195, -0.0117498 , -0.00330507,\n              1.00423304, -0.50341623, -0.24890017, -0.0136843 , -0.06375634,\n             -0.51630135, -0.642547  , -0.18784388, -0.15433358, -0.04961099]]))\n\n\n\n\n```python\nmodel.predict(X)\n```\n\n\n\n\n    array([0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1,\n           0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0,\n           1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0,\n           1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0,\n           1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1,\n           1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0,\n           0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n           1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1,\n           1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0,\n           0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0,\n           1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1,\n           1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,\n           0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1,\n           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1,\n           1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0,\n           0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0,\n           0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0,\n           1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1,\n           1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0,\n           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1,\n           1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0,\n           1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1,\n           1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1,\n           1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1,\n           1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1])\n\n\n\n\n```python\nmodel.predict_proba(X) #prawdopodobie\u0144stwa obliczone przez model\n```\n\n\n\n\n    array([[1.00000000e+00, 4.82487200e-15],\n           [9.99999965e-01, 3.48778573e-08],\n           [9.99999728e-01, 2.72381241e-07],\n           ...,\n           [9.92229755e-01, 7.77024500e-03],\n           [1.00000000e+00, 1.90741226e-10],\n           [2.51880451e-02, 9.74811955e-01]])\n\n\n\n\n```python\nmodel.predict_proba(X)[:10].round(2)\n```\n\n\n\n\n    array([[1.  , 0.  ],\n           [1.  , 0.  ],\n           [1.  , 0.  ],\n           [0.16, 0.84],\n           [1.  , 0.  ],\n           [0.73, 0.27],\n           [1.  , 0.  ],\n           [0.97, 0.03],\n           [0.69, 0.31],\n           [0.98, 0.02]])\n\n\n\n### Oceniamy klasyfikator - procent poprawnych klasyfikacji\n\n### Ocena dopasowania\n\n\n```python\nfrom sklearn.metrics import accuracy_score\n```\n\n\n```python\naccuracy_score(y, model.predict(X))\n```\n\n\n\n\n    0.9472759226713533\n\n\n\nO czym nam m\u00f3wi ta wartos\u0107? O **dopasowaniu**, a nie o tym jak dobrze model przewiduje!\n\n### Podzia\u0142 na cz\u0119\u015b\u0107 ucz\u0105c\u0105 i testow\u0105\n\n\n```python\nfrom sklearn.model_selection import train_test_split\n```\n\n\n```python\nX_train, X_test , y_train, y_test = train_test_split(X,y,test_size=0.33)\n```\n\n\n```python\nmodel.fit(X_train,y_train)\n```\n\n    /home/kodolamacz/anaconda3/lib/python3.7/site-packages/sklearn/linear_model/_logistic.py:940: ConvergenceWarning: lbfgs failed to converge (status=1):\n    STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n    \n    Increase the number of iterations (max_iter) or scale the data as shown in:\n        https://scikit-learn.org/stable/modules/preprocessing.html\n    Please also refer to the documentation for alternative solver options:\n        https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n      extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG)\n\n\n\n\n\n    LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,\n                       intercept_scaling=1, l1_ratio=None, max_iter=100,\n                       multi_class='auto', n_jobs=None, penalty='l2',\n                       random_state=None, solver='lbfgs', tol=0.0001, verbose=0,\n                       warm_start=False)\n\n\n\n\n```python\ny_pred = model.predict(X_test)\n```\n\n\n```python\naccuracy_score(y_pred,y_test)\n```\n\n\n\n\n    0.9574468085106383\n\n\n\n### Zadanie\n\nWypisz accuracy dla 10-ciu losowych podzia\u0142\u00f3w na cz\u0119\u015b\u0107 teningow\u0105 i testow\u0105.\n\n\n```python\nfor _ in range(10):\n    X_train, X_test , y_train, y_test = train_test_split(X,y,test_size=0.33)\n    model.fit(X_train,y_train)\n    y_pred = model.predict(X_test)\n    print(f'accuracy: {accuracy_score(y_pred,y_test)}')\n```\n\n    accuracy: 0.9468085106382979\n    accuracy: 0.9308510638297872\n    accuracy: 0.898936170212766\n    accuracy: 0.9627659574468085\n    accuracy: 0.9361702127659575\n    accuracy: 0.9414893617021277\n    accuracy: 0.9574468085106383\n    accuracy: 0.9468085106382979\n    accuracy: 0.9202127659574468\n    accuracy: 0.9414893617021277\n\n\n### Kroswalidacja - spos\u00f3b na zwi\u0119kszenie dok\u0142adno\u015bci oceny\n\n\n\u0179r\u00f3d\u0142o: http://ethen8181.github.io/machine-learning/model_selection/model_selection.html\n\n\n```python\nfrom sklearn.model_selection import cross_val_score\n```\n\n\n```python\n?cross_val_score\n```\n\n\n```python\ncv_scores = cross_val_score(LogisticRegression(), X,y, cv=10)\n```\n\n\n```python\ncv_scores\n```\n\n\n\n\n    array([0.92982456, 0.92982456, 0.92982456, 0.92982456, 0.94736842,\n           0.96491228, 0.92982456, 0.94736842, 0.92982456, 0.96428571])\n\n\n\n\n```python\ncv_scores.mean()\n```\n\n\n\n\n    0.9402882205513784\n\n\n\n# Regularyzacja\n\nRegularyzacja - zabezpieczenie przed przeuczeniem.\n\n\n### Regu\u0142a decyzyjna w regresji logistycznej\n\n$\n\\begin{equation}\n  \\begin{aligned}\n  \\hat{y_i} =  & 1, \\ \\ \\text{ gdy }\\frac{1}{1+e^{-\\beta x_i}} \\geq 0.5, \\\\\n  \\hat{y_i} = & 0, \\ \\ \\text{ gdy } \\frac{1}{1+e^{-\\beta x_i}} < 0.5,\n\\end{aligned}\n\\end{equation}\n$\n\nJest ona r\u00f3wnowa\u017cna regule:\n\n$\n\\begin{equation}\n  \\begin{aligned}\n  \\hat{y_i} =  & 1, \\ \\ \\text{ gdy } \\beta x_i \\geq 0, \\\\\n\\end{aligned}\n\\end{equation}\n$\n\nW przypadku danych o dw\u00f3ch zmiennych, regu\u0142a ma posta\u0107:\n\n$\n\\begin{equation}\n  \\begin{aligned}\n  \\hat{y_i} =  & 1, \\ \\ \\text{ gdy } \\beta_0 +\\beta_1x_1 + \\beta_2x_2 \\geq 0\n\\end{aligned}\n\\end{equation}\n$\n\nczyli\n\n$\n\\begin{equation}\n  \\begin{aligned}\n  \\hat{y_i} =  & 1, \\ \\ \\text{ gdy } x_2 \\geq \\frac{-\\beta_0}{\\beta_2} - \\frac{\\beta_1}{\\beta_2}x_1\n\\end{aligned}\n\\end{equation}\n$\n\nOznacza to, \u017ce decyzja jest podejmowana na podstawia po\u0142o\u017cenia wzgl\u0119dem pewnej prostej.\n\n### Stopnie dopasowania modelu\n\n\n\u0179r\u00f3d\u0142o: https://i.ytimg.com/vi/nmHNXsDPPFQ/maxresdefault.jpg\n\n\n## Regularyzacja w regresji logistycznej\n\nRegularyzacja w regresji logistycznej polega na dodaniu do celu optymalizacyjnego kary za wielko\u015bci wsp\u00f3\u0142czynnik\u00f3w w $\\beta$.\n\nPrzypomnijmy, \u017ce w regresji logistycznej estymator wektora $\\beta$ ma posta\u0107:\n\n$$\\hat{\\beta} = arg \\max\\limits_{\\beta} \\sum\\limits_{i=1}^n h(\\pi(x_i),y_i).$$\n\nW oczywisty spos\u00f3b jest to r\u00f3wnowa\u017cne rozwi\u0105zywaniu problemu:\n\n$$\\hat{\\beta} = arg \\min\\limits_{\\beta} -\\sum\\limits_{i=1}^n h(\\pi(x_i),y_i).$$\n\n### Regresja z regularyzacj\u0105 L2:\n\n$$\\hat{\\beta} = arg \\min\\limits_{\\beta} \\big( -\\sum\\limits_{i=1}^n h(\\pi(x_i),y_i) + \\lambda\\|\\beta\\|_2^2 \\big),$$\n\n$\\|\\beta\\|_2$ - norma l2 wektora $\\beta$: $\\sqrt{\\sum\\limits_{i=1}^p\\beta_i^2}$,\n\n$\\lambda$ - wsp\u00f3\u0142czynnik regularyzacji.\n\nSk\u0105d wzi\u0105\u0107 warto\u015b\u0107 $\\lambda$? Trzeba wyznaczy\u0107 sobie empirycznie - przetestowa\u0107 model  z r\u00f3\u017cnymi warto\u015bciami i wybra\u0107 t\u0119, dla kt\u00f3rej wyniki s\u0105 najlepsze.\n\n**W sklearnie za regularyzacj\u0119\u00a0odpowiada parametr C i jest on odwrotnosci\u0105\u00a0parametru $\\lambda$, tzn. $C = \\frac{1}{\\lambda}$. Zatem im mniejsze C, tym silniejsza regularyzacja.**\n\n\n### R\u00f3wnie cz\u0119sto stosowana jest norma l1: $\\sum\\limits_{i=1}^p|\\beta_i|$. \n\n#### Uwaga: Norma L1 zeruje wsp\u00f3\u0142czynniki! \n\n\nNa marginesie: w modelach w uczeniu maszynowym pojawiaj\u0105\u00a0sie\u00a0bardzo r\u00f3\u017cne formy regularyzacji, kt\u00f3rych cz\u0119sto nawet nie b\u0119dziemy \u015bwiadomi.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n\n```python\n?LogisticRegression\n```\n\n\n```python\nx = np.linspace(start=-1,stop=1,num=100)\nbeta = np.array([-0.5, 5])\n```\n\n\n```python\nprob = 1/(1+np.exp(-beta[0]-beta[1]*x))\ny = np.random.binomial(1,prob)\n```\n\n\n```python\nplt.plot(x,prob)\nplt.scatter(x,y)\nplt.show()\n```\n\n\n```python\n# X macierz, gdzie w pierwszej kolumnie jest siatka od -1 do 1, a w kolejny s\u0105 kolejne pot\u0119gi tej warto\u015bci\n\nX = np.vstack([x**p for p in range(1,20)]).T\nX\n```\n\n\n\n\n    array([[-1.        ,  1.        , -1.        , ..., -1.        ,\n             1.        , -1.        ],\n           [-0.97979798,  0.96000408, -0.94061006, ..., -0.70684009,\n             0.69256049, -0.67856937],\n           [-0.95959596,  0.92082441, -0.88361938, ..., -0.49602433,\n             0.47598295, -0.45675131],\n           ...,\n           [ 0.95959596,  0.92082441,  0.88361938, ...,  0.49602433,\n             0.47598295,  0.45675131],\n           [ 0.97979798,  0.96000408,  0.94061006, ...,  0.70684009,\n             0.69256049,  0.67856937],\n           [ 1.        ,  1.        ,  1.        , ...,  1.        ,\n             1.        ,  1.        ]])\n\n\n\nDopasujmy model \"bez regularyzacji\" (bardzo du\u017ce C) od x:\n\n\n```python\nmodel = LogisticRegression(C=10e8)\nmodel.fit(X[:,:1],y)\nmodel.intercept_, model.coef_\n```\n\n\n\n\n    (array([-0.18885914]), array([[4.58342835]]))\n\n\n\nTeraz z regularyzacj\u0105 nadal na podstawie samego x (bez pot\u0119g):\n\n\n```python\nmodel = LogisticRegression()\nmodel.fit(X[:,:1],y)\nmodel.intercept_, model.coef_\n```\n\n\n\n\n    (array([-0.1361186]), array([[3.08114871]]))\n\n\n\nCo sta\u0142o si\u0119 z wsp\u00f3\u0142czynnikami?\n\n---\n\nZobaczmy jaki to ma sens na przypadku, gdy mamy w modelu niepotrzebne zmienne.\n\n### Zadanie\n\nDopasuj model bez regularyzacji na wszystkich kolumnach i wypisz warto\u015bci wsp\u00f3\u0142czynnik\u00f3w:\n\n\n```python\nmodel = LogisticRegression(C=10e8)\nmodel.fit(X,y)\nmodel.intercept_, model.coef_\n```\n\n\n\n\n    (array([0.16410038]),\n     array([[   1.12524373,  -53.39250444,   13.1656258 ,  625.24798679,\n              372.83695518, -674.6263173 ,   63.87125265, -724.81825347,\n              -87.60181888, -471.28978197,  -48.6363041 , -192.91890479,\n               83.80986732,   50.47930471,  238.83405686,  247.97948136,\n              380.438508  ,  400.14952626,  494.3948719 ]]))\n\n\n\nCo obserwujesz?\n\n---\n\nDo poprzedniego wykresu dorysuj wykres prawpdopodobie\u0144stwa dla tego modelu:\n\n\n```python\nplt.plot(x,prob)\nplt.scatter(x,y)\n\nplt.plot(x, model.predict_proba(X)[:,1])\n\nplt.show()\n```\n\nPowt\u00f3rz powy\u017cszy punkt z modelem z regularyzacj\u0105:\n\n\n```python\nmodel = LogisticRegression()\nmodel.fit(X,y)\nmodel.intercept_, model.coef_\n\nplt.plot(x,prob)\nplt.scatter(x,y)\n\nplt.plot(x, model.predict_proba(X)[:,1])\n\nplt.show()\n```\n\n### Zadanie: \n\nNarysowa\u0107 wykresy krzywych prawdopodobie\u0144stwa w zale\u017cno\u015bci od C dla warto\u015bci $0.001, 0.01, 0.1, 1, 10, 100$.\n\n\n```python\nfor c in [0.001, 0.01, 0.1, 1, 10, 100]:\n    model = LogisticRegression(C=c)\n    model.fit(X,y)\n    plt.plot(x, model.predict_proba(X)[:,1], label=str(c))\n    \nplt.plot(x, prob, c='black')\nplt.scatter(x,y)\nplt.legend()\nplt.show()\n```\n\n### Jak stwierdzi\u0107 czy model jest dobrze dopasowany? Czy nie za s\u0142abo, ani za mocno?\n\n1. Gdy na zbiorze testowym niski procent poprawnych predykcji (np. 60%), a na treningowym model bardzo dobrze dopasowany (np. 90%) -> model przeuczony\n\n2. Gdy na zbiorze treningowym model bardzo nisko dopasowany (np. rz\u0119du pi\u0119\u0107dziesi\u0105t kilka procent) -> model s\u0142abo dopasowany.\n\nCo to jest niskie dopasowanie? -> zale\u017cy od danych...\n\nCo to jest du\u017ca r\u00f3\u017cnica? -> zale\u017cy od danych... (i ich wielko\u015bci - istotno\u015b\u0107 statystyczna!). Realnie, wyniki na testowym powinny by\u0107 troch\u0119 ni\u017csze od dopasowania na treningowym (idealnie, gdy s\u0105 takie same, ale to si\u0119 nigdy nie zdarza). Klasyfikator w oczywisty spos\u00f3b nie mo\u017ce dzia\u0142a\u0107 lepiej ni\u017c dopasowanie na zbiorze treningowym - bo dopasowanie pokazuje jak du\u017co zale\u017cno\u015bci wykry\u0142 w danych, na podstawie kt\u00f3rych b\u0119dzie klasyfikowa\u0142. Zatem je\u017celi mamy dopasowanie na zbiorze treningowym np. 90%, to maksymalna moc predykcyjna jakiej mo\u017cemy oczekiwa\u0107 to 90%.\n\n## Przygotowanie danych\n\nCzy warto\u015bci zmiennych maj\u0105 wp\u0142yw na wynik modelu?\n\nWyobra\u017amy sobie dwie zmienne, gdzie jedna ma wielko\u015bci rz\u0119du 1, a druga rz\u0119du 100, a rzeczywisty wsp\u00f3\u0142czynnik przy pierwszej wynosi 1, a przy drugiej 0.01.\n\nJak konsekwencje b\u0119dzie mia\u0142o zastosowanie regularyzacji?\n\n\n```python\nX_train, X_test , y_train, y_test = train_test_split(X,y,test_size=0.33)\n```\n\n\n```python\nfrom sklearn.preprocessing import StandardScaler\n```\n\n\n```python\nsc = StandardScaler()\nsc.fit(X_train)\n```\n\n\n\n\n    StandardScaler(copy=True, with_mean=True, with_std=True)\n\n\n\n\n```python\nX_tr = sc.transform(X_train)\nX_te = sc.transform(X_test)\n```\n\n## Pipeline\n\nW powy\u017cszym przyk\u0142adzie widzimy, \u017ce budowanie modelu sk\u0142ada si\u0119 w rzeczywisto\u015bci w dw\u00f3ch krok\u00f3w - transformacja zmiennych, a potem dopasowanie modelu. To s\u0105 tzw. pipeline'y.\n\n\n```python\nfrom sklearn.pipeline import Pipeline\n```\n\n\n```python\npipe = Pipeline([(\"scaler\", StandardScaler()),\n                 (\"model\", LogisticRegression())])\n```\n\n\n```python\npipe.fit(X_train,y_train)\n```\n\n\n\n\n    Pipeline(memory=None,\n             steps=[('scaler',\n                     StandardScaler(copy=True, with_mean=True, with_std=True)),\n                    ('model',\n                     LogisticRegression(C=1.0, class_weight=None, dual=False,\n                                        fit_intercept=True, intercept_scaling=1,\n                                        l1_ratio=None, max_iter=100,\n                                        multi_class='auto', n_jobs=None,\n                                        penalty='l2', random_state=None,\n                                        solver='lbfgs', tol=0.0001, verbose=0,\n                                        warm_start=False))],\n             verbose=False)\n\n\n\n\n```python\npipe.predict(X_test)\n```\n\n\n\n\n    array([1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,\n           1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0])\n\n\n\n\n```python\naccuracy_score(y_test, pipe.predict(X_test))\n```\n\n\n\n\n    0.8181818181818182\n\n\n\nAccuracy tego pipeline'a obliczone kroswalidacyjnie:\n\n\n```python\ncross_val_score(pipe, X,y, cv=10).mean()\n```\n\n\n\n\n    0.79\n\n\n\n# Optymalizacja parametr\u00f3w\n\nGridSearch\n\n\n```python\nfrom sklearn.model_selection import GridSearchCV\n```\n\n\n```python\nparam_grid = {\"penalty\":[\"l1\",\"l2\"],\n              \"C\":[1000,100,10,1,0.1,0.01]}\n\ngs = GridSearchCV(LogisticRegression(), param_grid, cv = 5, n_jobs=-1)\n```\n\n\n```python\ngs.fit(X_train, y_train)\n```\n\n\n\n\n    GridSearchCV(cv=5, error_score=nan,\n                 estimator=LogisticRegression(C=1.0, class_weight=None, dual=False,\n                                              fit_intercept=True,\n                                              intercept_scaling=1, l1_ratio=None,\n                                              max_iter=100, multi_class='auto',\n                                              n_jobs=None, penalty='l2',\n                                              random_state=None, solver='lbfgs',\n                                              tol=0.0001, verbose=0,\n                                              warm_start=False),\n                 iid='deprecated', n_jobs=-1,\n                 param_grid={'C': [1000, 100, 10, 1, 0.1, 0.01],\n                             'penalty': ['l1', 'l2']},\n                 pre_dispatch='2*n_jobs', refit=True, return_train_score=False,\n                 scoring=None, verbose=0)\n\n\n\n\n```python\ngs.cv_results_\n```\n\n\n\n\n    {'mean_fit_time': array([8.62598419e-05, 1.75650120e-02, 8.47339630e-05, 1.16497040e-02,\n            5.50270081e-05, 1.34493351e-02, 4.94480133e-05, 3.97257805e-03,\n            5.75542450e-05, 4.01840210e-03, 4.94003296e-05, 2.59928703e-03]),\n     'std_fit_time': array([3.84214777e-05, 5.13409779e-03, 2.83321536e-05, 2.20547575e-03,\n            7.98812545e-06, 5.69432346e-03, 5.66333212e-06, 1.16903002e-03,\n            2.02886226e-05, 1.22145559e-03, 8.18078038e-06, 3.14071081e-04]),\n     'mean_score_time': array([0.        , 0.00048571, 0.        , 0.00036645, 0.        ,\n            0.00035448, 0.        , 0.00047255, 0.        , 0.00044241,\n            0.        , 0.00030169]),\n     'std_score_time': array([0.00000000e+00, 9.10986627e-05, 0.00000000e+00, 4.95857915e-05,\n            0.00000000e+00, 7.67121773e-05, 0.00000000e+00, 2.56806893e-04,\n            0.00000000e+00, 2.29020752e-04, 0.00000000e+00, 1.11171595e-05]),\n     'param_C': masked_array(data=[1000, 1000, 100, 100, 10, 10, 1, 1, 0.1, 0.1, 0.01,\n                        0.01],\n                  mask=[False, False, False, False, False, False, False, False,\n                        False, False, False, False],\n            fill_value='?',\n                 dtype=object),\n     'param_penalty': masked_array(data=['l1', 'l2', 'l1', 'l2', 'l1', 'l2', 'l1', 'l2', 'l1',\n                        'l2', 'l1', 'l2'],\n                  mask=[False, False, False, False, False, False, False, False,\n                        False, False, False, False],\n            fill_value='?',\n                 dtype=object),\n     'params': [{'C': 1000, 'penalty': 'l1'},\n      {'C': 1000, 'penalty': 'l2'},\n      {'C': 100, 'penalty': 'l1'},\n      {'C': 100, 'penalty': 'l2'},\n      {'C': 10, 'penalty': 'l1'},\n      {'C': 10, 'penalty': 'l2'},\n      {'C': 1, 'penalty': 'l1'},\n      {'C': 1, 'penalty': 'l2'},\n      {'C': 0.1, 'penalty': 'l1'},\n      {'C': 0.1, 'penalty': 'l2'},\n      {'C': 0.01, 'penalty': 'l1'},\n      {'C': 0.01, 'penalty': 'l2'}],\n     'split0_test_score': array([       nan, 0.78571429,        nan, 0.78571429,        nan,\n            0.71428571,        nan, 0.71428571,        nan, 0.78571429,\n                   nan, 0.57142857]),\n     'split1_test_score': array([       nan, 0.92857143,        nan, 0.92857143,        nan,\n            0.92857143,        nan, 0.92857143,        nan, 0.92857143,\n                   nan, 0.78571429]),\n     'split2_test_score': array([       nan, 0.76923077,        nan, 0.76923077,        nan,\n            0.76923077,        nan, 0.76923077,        nan, 0.76923077,\n                   nan, 0.76923077]),\n     'split3_test_score': array([       nan, 0.84615385,        nan, 0.92307692,        nan,\n            0.84615385,        nan, 0.84615385,        nan, 0.92307692,\n                   nan, 0.84615385]),\n     'split4_test_score': array([       nan, 0.92307692,        nan, 0.92307692,        nan,\n            0.92307692,        nan, 0.92307692,        nan, 0.92307692,\n                   nan, 0.92307692]),\n     'mean_test_score': array([       nan, 0.85054945,        nan, 0.86593407,        nan,\n            0.83626374,        nan, 0.83626374,        nan, 0.86593407,\n                   nan, 0.77912088]),\n     'std_test_score': array([       nan, 0.06660827,        nan, 0.07244417,        nan,\n            0.08429367,        nan, 0.08429367,        nan, 0.07244417,\n                   nan, 0.117042  ]),\n     'rank_test_score': array([ 7,  3,  8,  1,  9,  4, 10,  4, 11,  1, 12,  6], dtype=int32)}\n\n\n\n\n```python\ngs.cv_results_['mean_test_score']\n```\n\n\n\n\n    array([       nan, 0.85054945,        nan, 0.86593407,        nan,\n           0.83626374,        nan, 0.83626374,        nan, 0.86593407,\n                  nan, 0.77912088])\n\n\n\n\n```python\ngs.best_params_\n\n# Uwaga: zwraca tylko parametey, kt\u00f3re optymalizowali\u015bmy, a nie wszystkie parametry modeleu\n```\n\n\n\n\n    {'C': 100, 'penalty': 'l2'}\n\n\n\n\n```python\ngs.best_estimator_\n```\n\n\n\n\n    LogisticRegression(C=100, class_weight=None, dual=False, fit_intercept=True,\n                       intercept_scaling=1, l1_ratio=None, max_iter=100,\n                       multi_class='auto', n_jobs=None, penalty='l2',\n                       random_state=None, solver='lbfgs', tol=0.0001, verbose=0,\n                       warm_start=False)\n\n\n\n\n```python\naccuracy_score(y_test, gs.best_estimator_.predict(X_test))\n```\n\n\n\n\n    0.8181818181818182\n\n\n\n\n```python\naccuracy_score(y_test, gs.predict(X_test))\n```\n\n\n\n\n    0.8181818181818182\n\n\n\n### Wersja z pipelinem:\n\n\n```python\npipe = Pipeline([(\"scaler\", StandardScaler()),\n                 (\"model\", LogisticRegression())])\n\nparam_grid = {\"scaler__with_std\": [True, False],\n              \"model__penalty\": [\"l1\",\"l2\"],\n              \"model__C\": [1000, 100, 10, 1, 0.1, 0.01]}\n\ngs = GridSearchCV(pipe, param_grid, cv = 10, n_jobs=-1)\n\ngs.fit(X_train, y_train)\n```\n\nCzyli do nazwy parametr\u00f3w doklejamy na pocz\u0105tku nazw\u0119 kroku, do kt\u00f3rego przekazujemy parametry.\n\n\n```python\naccuracy_score(y_test, gs.best_estimator_.predict(X_test))\n```\n\n### Zadanie.\n\nStw\u00f3rz pipeline ze zmiennymi wielomianowymi (sklearn.preprocessing -> PolynomialFeatures), zoptymalizuj go. Podaj najlepsze parametry i oce\u0144 najlepszy wariant.\n\n\n```python\nfrom sklearn.preprocessing import PolynomialFeatures\n\npipe = Pipeline([(\"poly\", PolynomialFeatures()),\n                 (\"scaler\", StandardScaler()),\n                 (\"model\", LogisticRegression())])\n\nparam_grid = {\"poly__degree\":[1,2],\n              \"scaler__with_std\": [True, False],\n              \"model__penalty\": [\"l1\",\"l2\"],\n              \"model__C\": [1000, 100, 10, 1, 0.1, 0.01]}\n\ngs = GridSearchCV(pipe, param_grid, cv = 10, n_jobs=-1)\n\ngs.fit(X_train, y_train)\n```\n\n\n```python\ngs.best_params_\n```\n\n\n\n\n    {'model__C': 10,\n     'model__penalty': 'l2',\n     'poly__degree': 2,\n     'scaler__with_std': False}\n\n\n\n\n```python\naccuracy_score(y_test, gs.predict(X_test))\n```\n\n\n\n\n    0.8181818181818182\n\n\n\n\n```python\npipe.fit(X_train,y_train)\n```\n\n\n\n\n    Pipeline(memory=None,\n             steps=[('scaler',\n                     StandardScaler(copy=True, with_mean=True, with_std=True)),\n                    ('model',\n                     DecisionTreeClassifier(ccp_alpha=0.0, class_weight=None,\n                                            criterion='gini', max_depth=None,\n                                            max_features=None, max_leaf_nodes=None,\n                                            min_impurity_decrease=0.0,\n                                            min_impurity_split=None,\n                                            min_samples_leaf=1, min_samples_split=2,\n                                            min_weight_fraction_leaf=0.0,\n                                            presort='deprecated', random_state=None,\n                                            splitter='best'))],\n             verbose=False)\n\n\n\n\n```python\npipe.predict(X)\n```\n\n# Drzewo decyzyjne\n\nZa\u0142\u00f3\u017cmy, \u017ce mamy dwie zmienne $X[0], X[1]$ i problem klasyfikacji binarnej ($Y \\in \\{0,1\\}$).\n\n\n\n\n\n## Jak ro\u015bnie drzewno?\n\nDrzewo ro\u015bnie od korzenia - tzn. budujemy model od g\u00f3ry. B\u0119d\u0105c w aktualnym w\u0119\u017ale szukamy najlepszego podzia\u0142u - rozpatrujemy wszystkie zmienne ze wszystkimi mo\u017cliwymi podzia\u0142ami i tworzymy rozga\u0142\u0119zienie wed\u0142ug najlepszej opcji.\n\nCo to znaczy najlpszy podzia\u0142? \n<br>\n\nRozwa\u017cmy klasyfikacj\u0119 binarn\u0105.\n\n<br>\n\n<br>\n\nOpcja nr 1: Gini impurity (Miara Gini'ego niesp\u00f3jno\u015bci w\u0119z\u0142a):\n- wybieramy podzia\u0142, kt\u00f3ry minimalizuje wa\u017con\u0105 miar\u0119 Giniego $g(p) = 2p(1-p)$:\n\n$$\\frac{n_1}{N}g(p_1) + \\frac{n_2}{N}g(p_2),$$\n\ngdzie $n_1, n_2$ liczno\u015bci w pierwszym i drugim dziecku, $N = n_1 + n_2$, $p_1, p_2$ - procent obserwacji, dla kt\u00f3rych $Y=1$ w dzieciach 1 i 2.\n\n\n\n<br>\n\nOpcja nr 2: Entropia.\n- wybieramy podzia\u0142, kt\u00f3ry daje najmniejsz\u0105\u00a0warto\u015b\u0107 wa\u017conej entropii $h(p) = -p\\log{(p)} - (1-p)\\log{(1-p)}$:\n\n$$\\frac{n_1}{N} h(p_1) + \\frac{n_2}{N}h(p_2),$$\n\ngdzie $p_1, p_2$ - procent obserwacji, dla kt\u00f3rych $Y=1$ w dzieciach 1 i 2.\n\n## Do kiedy tworzymy nowe podzia\u0142y? \n\nMo\u017cliwe s\u0105 r\u00f3\u017cne warunki stopu. Najpopularniejsze to:\n\n- maksymalna g\u0142\u0119boko\u015b\u0107 drzewa,\n- minimalna liczba obserwacji w li\u015bciu.\n\nCz\u0119sto stosowane w po\u0142\u0105czeniu.\n\n\n```python\nfrom sklearn.tree import DecisionTreeClassifier\n```\n\n\n```python\n?DecisionTreeClassifier\n```\n\nZwr\u00f3\u0107my uwag\u0119, \u017ce s\u0105 tu dost\u0119pne r\u00f3wnie\u017c inne warunki stopu ni\u017c wy\u017cej wymienione.\n\n#### Zadanie \n\nWczytaj zbi\u00f3r `zbi\u00f3r1.txt` (funkcja loadtxt w numpy) i podziel go na cz\u0119\u015b\u0107 ucz\u0105c\u0105 (200 obserwacji) i testow\u0105 (100). Dopasuj model regresji logistycznej na zbiorze ucz\u0105cym i oblicz accuracy na zbiorze testowym. Nast\u0119pnie oblicz procent poprawnych dopasowa\u0144 na zbiorze treningowym.\n\nSpr\u00f3buj zauwazy\u0107 jakie\u015b zalezno\u015bci mi\u0119dzy zmiennymi na podstawie analizy graficznej, np. narysuj\u0105c histogramy warto\u015bci cech w pozbiorach wyznaczonych przez warto\u015b\u0107 $Y$.\n\nNast\u0119pnie zbuduje drzewo klasyfikacyjne i policz dla niego accuracy.\n\n\n```python\nimport numpy as np\n```\n\n\n```python\ndane = np.loadtxt(\"Dane/zbior1.txt\")\n```\n\n\n```python\nX = dane[:,:2]\ny = dane[:,2]\n```\n\n\n```python\nX.shape\n```\n\n\n\n\n    (300, 2)\n\n\n\n\n```python\npipe = Pipeline([(\"scaler\", StandardScaler()),\n                 (\"model\", DecisionTreeClassifier())])\n```\n\n\n```python\nX_train, X_test , y_train, y_test = train_test_split(X,y,test_size=0.33)\n```\n\n\n```python\npipe.fit(X_train, y_train)\n```\n\n\n\n\n    Pipeline(memory=None,\n             steps=[('scaler',\n                     StandardScaler(copy=True, with_mean=True, with_std=True)),\n                    ('model',\n                     DecisionTreeClassifier(ccp_alpha=0.0, class_weight=None,\n                                            criterion='gini', max_depth=None,\n                                            max_features=None, max_leaf_nodes=None,\n                                            min_impurity_decrease=0.0,\n                                            min_impurity_split=None,\n                                            min_samples_leaf=1, min_samples_split=2,\n                                            min_weight_fraction_leaf=0.0,\n                                            presort='deprecated', random_state=None,\n                                            splitter='best'))],\n             verbose=False)\n\n\n\n\n```python\npipe.predict(X_test)\n```\n\n\n\n\n    array([0., 0., 1., 0., 0., 0., 1., 0., 1., 1., 0., 0., 0., 1., 0., 0., 1.,\n           0., 1., 1., 1., 1., 1., 1., 1., 0., 0., 1., 0., 1., 0., 0., 1., 1.,\n           1., 0., 0., 1., 1., 0., 1., 0., 1., 0., 0., 0., 1., 0., 0., 1., 0.,\n           1., 0., 0., 0., 1., 1., 1., 1., 0., 0., 1., 0., 1., 0., 1., 0., 1.,\n           1., 1., 0., 1., 0., 0., 0., 1., 1., 0., 1., 0., 0., 1., 0., 1., 0.,\n           0., 0., 0., 0., 1., 1., 1., 0., 1., 1., 0., 1., 1., 1.])\n\n\n\n\n```python\naccuracy_score(y_test, pipe.predict(X_test))\n```\n\n\n\n\n    1.0\n\n\n\n\n```python\ncross_val_score(pipe, X,y, cv=10).mean()\n```\n\n\n\n\n    0.9866666666666667\n\n\n\n### Bardzo wa\u017cna sprawa: wnioskowanie o zale\u017cno\u015bci zmiennych na podstawie analizy jednowymiarowej nie nie ma wi\u0119kszego sensu!\n\n- je\u015bli nie wida\u0107 zale\u017cno\u015bci, to nie znaczy, \u017ce jej nie ma,\n- je\u017celi wida\u0107 zale\u017cno\u015b\u0107, to wcale nie musi oznacza\u0107 zale\u017cno\u015bci przyczynowo-skutkowej (dana cecha mo\u017ce by\u0107 skorelowana z inn\u0105 cech\u0105, kt\u00f3ra faktycznie wp\u0142ywa na y).\n- zjawisko fa\u0142szywej korelacji - statystycznie rzecz bior\u0105c, regularnie zdarzaj\u0105 si\u0119 sytuacje, kiedy zmienne wygl\u0105daj\u0105 na zale\u017cne, a tak naprawd\u0119 nie s\u0105...\n\nNaturalnie analiza wielowymiarowa te\u017c mo\u017ce nie wykry\u0107 zale\u017cno\u015bci... Ale uczenie maszynowe polega w\u0142a\u015bnie na szukaniu tych zale\u017cno\u015bci.\n\n### Zadanie\n\nPrzetestuj drzewo na danych breast_cancer. Uwzgl\u0119dnij optymalizacj\u0119 minimalnej liczby obserwacji w li\u015bciach.\n\n\n```python\ndata = load_breast_cancer()\n```\n\n\n```python\nX, y = data.data, data.target\n```\n\n\n```python\npipe = Pipeline([(\"scaler\", StandardScaler()),\n                 (\"model\", DecisionTreeClassifier(min_samples_leaf=5))])\n```\n\n\n```python\nX_train, X_test , y_train, y_test = train_test_split(X,y,test_size=0.33)\n```\n\n\n```python\npipe.fit(X_train, y_train)\n```\n\n\n\n\n    Pipeline(memory=None,\n             steps=[('scaler',\n                     StandardScaler(copy=True, with_mean=True, with_std=True)),\n                    ('model',\n                     DecisionTreeClassifier(ccp_alpha=0.0, class_weight=None,\n                                            criterion='gini', max_depth=None,\n                                            max_features=None, max_leaf_nodes=None,\n                                            min_impurity_decrease=0.0,\n                                            min_impurity_split=None,\n                                            min_samples_leaf=5, min_samples_split=2,\n                                            min_weight_fraction_leaf=0.0,\n                                            presort='deprecated', random_state=None,\n                                            splitter='best'))],\n             verbose=False)\n\n\n\n\n```python\naccuracy_score(y_test, pipe.predict(X_test))\n```\n\n\n\n\n    0.9414893617021277\n\n\n\n\n```python\ncross_val_score(pipe, X,y, cv=10).mean()\n```\n\n\n\n\n    0.9333333333333332\n\n\n\n---\n\nDrzewo mo\u017cna sobie narysowa\u0107 (zapis do pliku):\n\n\n```python\n?plot_tree\n```\n\n\n```python\nfrom sklearn.tree import plot_tree\nplt.figure(figsize=(10,10))\nplot_tree(model)\nplt.show()\n# zapis do pliku:\n#import sklearn\n#sklearn.tree.export_graphviz(model,out_file='tree.dot') \n```\n\n# Klasyfikacja wieloklasowa\n\n## Regresja logistyczna\n\n\n\n\\begin{align}\n\\Pr(Y_i=1) &= \\frac{1}{Z} e^{\\boldsymbol\\beta_1 \\cdot \\mathbf{X}_i} \\, \\\\\n\\Pr(Y_i=2) &= \\frac{1}{Z} e^{\\boldsymbol\\beta_2 \\cdot \\mathbf{X}_i} \\, \\\\\n\\cdots & \\cdots \\\\\n\\Pr(Y_i=K-1) &= \\frac{1}{Z} e^{\\boldsymbol\\beta_{K-1} \\cdot \\mathbf{X}_i} \\, \\\\\n\\Pr(Y_i=K) &= \\frac{1}{Z} e^{\\boldsymbol\\beta_{K} \\cdot \\mathbf{X}_i}\\, \\\\\n\\end{align}\n\n\n$Z = \\sum_{k=1}^{K} e^{\\boldsymbol\\beta_k \\cdot \\mathbf{X}_i}$\n\nMo\u017cliwe s\u0105 r\u00f3wnie\u017c inne warianty. https://en.wikipedia.org/wiki/Multinomial_logistic_regression\n\n\nInny zapis powy\u017cszego:\n\n$$[P(Y=1), P(Y=2), \\ldots , P(Y=K)] = softmax([\\beta_1x, \\beta_2x, \\ldots , \\beta_Kx]) = $$\n$$[\\frac{e^{\\beta_1x}}{\\sum_{k=1}^{K}e^{\\beta_kx}}, \\frac{e^{\\beta_2x}}{\\sum_{k=1}^{K}e^{\\beta_kx}}, \\ldots, \\frac{e^{\\beta_Kx}}{\\sum_{k=1}^{K}e^{\\beta_k x}}]$$\n\nNa marginesie: w uczeniu maszynowym cz\u0119sto pojawia sie funkcja \"softmax\". \n\n$$softmax(\\mathbf{x}) = softmax([x_1, x_2, \\ldots , x_p])= [\\frac{e^{x_1}}{\\sum_{k=1}^{p}e^{x_k}}, \\frac{e^{x_2}}{\\sum_{k=1}^{p}e^{x_k}}, \\ldots, \\frac{e^{x_p}}{\\sum_{k=1}^{p}e^{x_k}}]$$\n\nW literaturze czasem mozna spotka\u0107 nazwanie regresji logistycznej dla klasyfikacji wieloklasowej klasyfikatorem softmax.\n\n## Drzewo decyzyjne\n\nPrzyjmujemy oznaczenie: $p = (p_1, p_2, \\ldots, p_K)$ - wektor prawdopodobie\u0144stw poszczeg\u00f3lnych klas (procent obserwacji danej klasy).\n\nOpcja nr 1: Gini impurity (Miara Gini'ego niesp\u00f3jno\u015bci w\u0119z\u0142a):\n- wybieramy podzia\u0142, kt\u00f3ry minimalizuje wa\u017con\u0105 miar\u0119\u00a0Gini'ego $g(p) = \\big( 1 - \\sum\\limits_{k=1}^K p_k^2 \\big)$:\n\n$$\\frac{n_1}{N} g(p_1) + \\frac{n_2}{N} g(p_2),$$\n\ngdzie $n_1, n_2$ liczno\u015bci w pierwszym i drugim dziecku, $p_1, p_2$ - rozk\u0142ady klas w dzieciach 9wektory z iformacj\u0105 ile procent jest jakiej klasy).\n\n<br>\n\nOpcja nr 2: Entropia.\n- wybieramy podzia\u0142, kt\u00f3ry daje najmniejsz\u0105 warto\u015b\u0107 wa\u017conej entropii $h(p) = -\\sum\\limits_{k=1}^K p_k\\log p_k$:\n\n$$\\frac{n_1}{n}\\sum\\limits_{i=1}^{n_1} h(p_1) + \\frac{n_2}{n}\\sum\\limits_{i=1}^{n_2} h(p_2)$$\n\n\n\n```python\nfrom sklearn import datasets\n\niris = datasets.load_iris()\nX, y = iris.data, iris.target\nprint(X.shape)\n\nm1 = LogisticRegression()\nm1.fit(X,y)\nm1.intercept_, m1.coef_\n```\n\n#### Zadanie\n\nWygenerowa\u0107 predykcje kroswalidacyjnie dla regresji logistycznej i drzewa decyzyjnego (u\u017cyj `cross_val_predict`), a nast\u0119pnie wypisz accuracy i przedstaw tablic\u0119 klasyfikacji (`confusion_matrix` z `sklearn.metrics`) dla obu modeli.\n\nRozwi\u0105zanie:\n\n\n```python\nfrom sklearn import datasets\nfrom sklearn.model_selection import cross_val_predict\n\niris = datasets.load_iris()\nX, y = iris.data, iris.target\nprint(X.shape)\n```\n\n    (150, 4)\n\n\n\n```python\nm1 = LogisticRegression()\nm1.fit(X,y)\nm1.intercept_, m1.coef_\n```\n\n\n\n\n    (array([  9.83921315,   2.21461011, -12.05382326]),\n     array([[-0.4181548 ,  0.9664131 , -2.52143371, -1.08402272],\n            [ 0.53103652, -0.31447171, -0.19924922, -0.94919241],\n            [-0.11288172, -0.65194139,  2.72068294,  2.03321513]]))\n\n\n\n\n```python\ncross_val_predict(m1, X,y, cv=10)\n```\n\n\n\n\n    array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n           0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n           0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n           1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1,\n           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2,\n           2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n           2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])\n\n\n\n\n```python\nm2 = DecisionTreeClassifier()\nm2.fit(X,y)\n```\n\n\n\n\n    DecisionTreeClassifier(ccp_alpha=0.0, class_weight=None, criterion='gini',\n                           max_depth=None, max_features=None, max_leaf_nodes=None,\n                           min_impurity_decrease=0.0, min_impurity_split=None,\n                           min_samples_leaf=1, min_samples_split=2,\n                           min_weight_fraction_leaf=0.0, presort='deprecated',\n                           random_state=None, splitter='best')\n\n\n\n\n```python\ncross_val_predict(m2, X,y, cv=10)\n```\n\n\n\n\n    array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n           0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n           0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n           1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1,\n           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2,\n           2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2,\n           2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])\n\n\n\n\n```python\nfrom sklearn.metrics import confusion_matrix\n\nconfusion_matrix(y, cross_val_predict(m1, X,y, cv=10))\n```\n\n\n\n\n    array([[50,  0,  0],\n           [ 0, 47,  3],\n           [ 0,  1, 49]])\n\n\n\n\n```python\nconfusion_matrix(y, cross_val_predict(m2, X,y, cv=10))\n```\n\n\n\n\n    array([[50,  0,  0],\n           [ 0, 47,  3],\n           [ 0,  3, 47]])\n\n\n\n# Naiwny klasyfikator Bayes'a\n\nRozwa\u017cmy klasyfikacj\u0119 wieloklasow\u0105 - $Y \\in \\{1, 2, \\ldots, K\\}$. \n\nNaiwny klasyfikator Bayesa klasyfikuje obserwacje na podstawie prawdopodobie\u0144stwa:\n\n$$p(Y = k \\mid x_1, \\dots, x_p)  = p(C_k \\mid x_1, \\dots, x_p).$$\n\nPredykcja klasyfikatora to najbardziej prawdopodobna klasa.\n\nSk\u0105d klasyfikator bierze to prawdopodobie\u0144stwo? Oblicza je przyjmuj\u0105c pewne za\u0142o\u017cenia...\n\nZ twierdzenia Bayesa:\n\n\n$$p(C_k \\mid \\mathbf{x}) = \\frac{p(C_k) \\ p(\\mathbf{x} \\mid C_k)}{p(\\mathbf{x})}.$$\n\nZauwa\u017cmy, \u017ce $p(\\mathbf{x})$, czyli rozk\u0142ad X, jest nieistotny dla klasyfikatora, zatem: \n\n$$p(C_k \\mid \\mathbf{x}) \\sim p(C_k) \\ p(\\mathbf{x} \\mid C_k).$$\n\n$p(C_k)$ - prawdopodobie\u015btwo a priori klasy $C_k$ - czyli procent obserwacji w danych, dla kt\u00f3rych $Y = k$.\n\n$p(\\mathbf{x} \\mid C_k) = p(x_1, x_2, \\ldots, x_p \\mid C_k)$ - rozk\u0142ad cech w pozbiorze danych, dla kt\u00f3rych $Y = C_k$.\n\n\n(**Naiwne**) za\u0142o\u017cenie modelu:\n\n$$p(x_1, x_2, \\ldots, x_p \\mid C_k) = p(x_1 \\mid C_k)\\cdot p(x_2\\mid C_k) \\cdot \\ldots \\cdot p(x_p \\mid C_k)$$\n\nZatem predykcja klasyfikatora ma posta\u0107:\n\n$$\\hat{y} = arg \\max\\limits_k  p(C_k \\mid \\mathbf{x}) = arg \\max\\limits_k p(C_k) \\prod\\limits_{i=1}^p p(x_i\\mid C_k)$$\n\nSk\u0105d bierzemy $p(x_i\\mid C_k)$?\n\nZ postaci danych:\n- je\u017celi zmienna $x_i$ jest binarna, to zak\u0142adamy, \u017ce rozk\u0142ad jest dwupunktowy - prawdopodobie\u0144stwo sukcesu model wylicza empirycznie z danych,\n- je\u017celi zmienna $x_i$ jest liczno\u015bci\u0105, to zak\u0142adamy, \u017ce rozk\u0142ad jest wielomianowy - prawdopodobie\u0144stwa poszczeg\u00f3lnych warto\u015bci model wylicza empirycznie z danych,\n- je\u017celi zmienna $x_i$ jest rzeczywista, to zak\u0142adamy, \u017ce rozk\u0142ad jest normalny - parametry (\u015bredni\u0105 i wariancj\u0119) model estymuje z danych.\n\nUwaga: ostatnia wersja w praktyce nieuzywana - nigdy nie daje dobrych wynik\u00f3w.\n\n\n```python\nfrom sklearn.naive_bayes import MultinomialNB # wersja wielomianowa\n```\n\n\n```python\n?MultinomialNB\n```\n\n# Case study\n\nDane\n\nhttp://www.ritchieng.com/machine-learning-multinomial-naive-bayes-vectorization/\n\n\n```python\nimport pandas as pd\n\nsms = pd.read_table('Dane/sms.tsv', header=None, names=['label', 'message'])\n\n#url = 'https://raw.githubusercontent.com/justmarkham/pycon-2016-tutorial/master/data/sms.tsv'\n#sms = pd.read_table(url, header=None, names=['label', 'message'])\n\nsms.shape\n```\n\n\n\n\n    (5572, 2)\n\n\n\n\n```python\nsms.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>label</th>\n      <th>message</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>ham</td>\n      <td>Go until jurong point, crazy.. Available only ...</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>ham</td>\n      <td>Ok lar... Joking wif u oni...</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>spam</td>\n      <td>Free entry in 2 a wkly comp to win FA Cup fina...</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>ham</td>\n      <td>U dun say so early hor... U c already then say...</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>ham</td>\n      <td>Nah I don't think he goes to usf, he lives aro...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nsms['label'] = sms.label.map({'ham':0, 'spam':1})\nsms.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>label</th>\n      <th>message</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0</td>\n      <td>Go until jurong point, crazy.. Available only ...</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0</td>\n      <td>Ok lar... Joking wif u oni...</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1</td>\n      <td>Free entry in 2 a wkly comp to win FA Cup fina...</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0</td>\n      <td>U dun say so early hor... U c already then say...</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0</td>\n      <td>Nah I don't think he goes to usf, he lives aro...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# examine the class distribution\nsms.label.value_counts(normalize=True)\n```\n\n\n\n\n    0    0.865937\n    1    0.134063\n    Name: label, dtype: float64\n\n\n\n\n```python\nfrom sklearn.feature_extraction.text import CountVectorizer\n```\n\n\n```python\nsms.message[:10]\n```\n\n\n\n\n    0    Go until jurong point, crazy.. Available only ...\n    1                        Ok lar... Joking wif u oni...\n    2    Free entry in 2 a wkly comp to win FA Cup fina...\n    3    U dun say so early hor... U c already then say...\n    4    Nah I don't think he goes to usf, he lives aro...\n    5    FreeMsg Hey there darling it's been 3 week's n...\n    6    Even my brother is not like to speak with me. ...\n    7    As per your request 'Melle Melle (Oru Minnamin...\n    8    WINNER!! As a valued network customer you have...\n    9    Had your mobile 11 months or more? U R entitle...\n    Name: message, dtype: object\n\n\n\n\n```python\nvectorizer = CountVectorizer(max_features=3000)\nvectorizer.fit(sms.message)\nx = vectorizer.transform(sms.message)\nx\n```\n\n\n\n\n    <5572x3000 sparse matrix of type '<class 'numpy.int64'>'\n    \twith 67227 stored elements in Compressed Sparse Row format>\n\n\n\n\n```python\nx[:10,:10].todense()\n```\n\n\n\n\n    matrix([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])\n\n\n\n\n```python\nvectorizer.vocabulary_ # przypisanie kolumn do slow\n```\n\n\n\n\n    {'go': 1134,\n     'until': 2754,\n     'point': 2009,\n     'crazy': 710,\n     'available': 356,\n     'only': 1866,\n     'in': 1319,\n     'bugis': 508,\n     'great': 1166,\n     'world': 2938,\n     'la': 1439,\n     'cine': 620,\n     'there': 2614,\n     'got': 1151,\n     'wat': 2848,\n     'ok': 1853,\n     'lar': 1448,\n     'joking': 1396,\n     'wif': 2898,\n     'oni': 1864,\n     'free': 1044,\n     'entry': 899,\n     'wkly': 2920,\n     'comp': 662,\n     'to': 2661,\n     'win': 2903,\n     'fa': 944,\n     'cup': 725,\n     'final': 997,\n     'tkts': 2656,\n     '21st': 82,\n     'may': 1641,\n     '2005': 79,\n     'text': 2591,\n     '87121': 182,\n     'receive': 2144,\n     'question': 2093,\n     'std': 2474,\n     'txt': 2722,\n     'rate': 2116,\n     'apply': 309,\n     'dun': 856,\n     'say': 2251,\n     'so': 2403,\n     'early': 862,\n     'already': 271,\n     'then': 2612,\n     'nah': 1773,\n     'don': 825,\n     'think': 2619,\n     'he': 1221,\n     'goes': 1138,\n     'usf': 2775,\n     'lives': 1519,\n     'around': 327,\n     'here': 1235,\n     'though': 2629,\n     'freemsg': 1046,\n     'hey': 1236,\n     'darling': 745,\n     'it': 1367,\n     'been': 400,\n     'week': 2865,\n     'now': 1829,\n     'and': 285,\n     'no': 1811,\n     'word': 2932,\n     'back': 371,\n     'like': 1497,\n     'some': 2410,\n     'fun': 1069,\n     'you': 2989,\n     'up': 2755,\n     'for': 1030,\n     'still': 2476,\n     'tb': 2561,\n     'xxx': 2964,\n     'send': 2289,\n     '50': 131,\n     'even': 913,\n     'my': 1770,\n     'brother': 498,\n     'is': 1359,\n     'not': 1825,\n     'speak': 2440,\n     'with': 2914,\n     'me': 1647,\n     'they': 2616,\n     'treat': 2698,\n     'as': 334,\n     'per': 1946,\n     'your': 2990,\n     'request': 2182,\n     'melle': 1663,\n     'oru': 1886,\n     'minnaminunginte': 1688,\n     'nurungu': 1836,\n     'vettam': 2794,\n     'has': 1211,\n     'set': 2302,\n     'callertune': 536,\n     'all': 266,\n     'callers': 535,\n     'press': 2042,\n     'copy': 691,\n     'friends': 1054,\n     'winner': 2905,\n     'valued': 2785,\n     'network': 1794,\n     'customer': 730,\n     'have': 1215,\n     'selected': 2282,\n     'receivea': 2145,\n     '900': 193,\n     'prize': 2050,\n     'reward': 2199,\n     'claim': 624,\n     'call': 530,\n     'code': 642,\n     'valid': 2781,\n     '12': 51,\n     'hours': 1276,\n     'had': 1185,\n     'mobile': 1714,\n     '11': 47,\n     'months': 1732,\n     'or': 1877,\n     'more': 1736,\n     'entitled': 898,\n     'update': 2756,\n     'the': 2607,\n     'latest': 1453,\n     'colour': 652,\n     'mobiles': 1715,\n     'camera': 543,\n     'co': 640,\n     'on': 1860,\n     'gonna': 1143,\n     'be': 393,\n     'home': 1259,\n     'soon': 2423,\n     'want': 2838,\n     'talk': 2553,\n     'about': 204,\n     'this': 2623,\n     'stuff': 2498,\n     'anymore': 297,\n     'tonight': 2676,\n     've': 2789,\n     'enough': 895,\n     'today': 2664,\n     'six': 2374,\n     'cash': 566,\n     'from': 1060,\n     '100': 40,\n     '20': 74,\n     '000': 1,\n     'pounds': 2028,\n     '87575': 185,\n     'cost': 695,\n     '150p': 63,\n     'day': 752,\n     '16': 67,\n     'reply': 2178,\n     'hl': 1248,\n     'info': 1331,\n     'urgent': 2764,\n     'won': 2926,\n     'membership': 1666,\n     'our': 1893,\n     'www': 2957,\n     'net': 1792,\n     'pobox': 2003,\n     'searching': 2268,\n     'right': 2202,\n     'words': 2933,\n     'thank': 2601,\n     'promise': 2063,\n     'wont': 2931,\n     'take': 2547,\n     'help': 1233,\n     'will': 2901,\n     'wonderful': 2928,\n     'at': 345,\n     'times': 2649,\n     'date': 748,\n     'sunday': 2518,\n     'use': 2772,\n     'credit': 713,\n     'click': 631,\n     'wap': 2842,\n     'link': 1507,\n     'next': 1802,\n     'message': 1671,\n     'http': 1284,\n     'com': 653,\n     'oh': 1851,\n     'watching': 2850,\n     'eh': 875,\n     'remember': 2169,\n     'how': 1278,\n     'spell': 2445,\n     'his': 1244,\n     'name': 1775,\n     'yes': 2978,\n     'did': 785,\n     'naughty': 1783,\n     'make': 1603,\n     'wet': 2879,\n     'fine': 1000,\n     'if': 1308,\n     'that': 2605,\n     'way': 2853,\n     'feel': 974,\n     'its': 1369,\n     'england': 891,\n     'dont': 827,\n     'miss': 1697,\n     'team': 2569,\n     'news': 1801,\n     'ur': 2761,\n     'national': 1780,\n     '87077': 181,\n     'eg': 872,\n     'try': 2707,\n     'wales': 2828,\n     'scotland': 2261,\n     'seriously': 2299,\n     'going': 1140,\n     'ha': 1184,\n     'pay': 1933,\n     'first': 1006,\n     'when': 2883,\n     'da': 736,\n     'stock': 2477,\n     'comin': 658,\n     'aft': 236,\n     'finish': 1002,\n     'lunch': 1577,\n     'str': 2487,\n     'down': 832,\n     'lor': 1540,\n     'ard': 317,\n     'smth': 2399,\n     'alright': 272,\n     'can': 545,\n     'meet': 1659,\n     'sooner': 2424,\n     'just': 1406,\n     'myself': 1771,\n     'eat': 866,\n     'really': 2134,\n     'hungry': 1289,\n     'tho': 2627,\n     'sucks': 2510,\n     'mark': 1621,\n     'getting': 1115,\n     'worried': 2939,\n     'knows': 1435,\n     'sick': 2349,\n     'turn': 2716,\n     'pizza': 1981,\n     'lol': 1530,\n     'always': 275,\n     'catch': 568,\n     'bus': 512,\n     'are': 318,\n     'frying': 1062,\n     'an': 284,\n     'egg': 873,\n     'tea': 2565,\n     'eating': 869,\n     'mom': 1722,\n     'left': 1472,\n     'over': 1898,\n     'dinner': 798,\n     'do': 812,\n     'love': 1554,\n     'amp': 282,\n     'we': 2855,\n     're': 2122,\n     'car': 552,\n     'll': 1521,\n     'let': 1482,\n     'know': 1433,\n     'room': 2217,\n     'work': 2934,\n     'what': 2880,\n     'does': 816,\n     'wait': 2823,\n     'clear': 629,\n     'were': 2878,\n     'sure': 2530,\n     'being': 408,\n     'why': 2896,\n     'doesn': 817,\n     'live': 1517,\n     'us': 2770,\n     'yeah': 2972,\n     'was': 2845,\n     'out': 1894,\n     'she': 2315,\n     'child': 608,\n     'caught': 570,\n     'till': 2647,\n     'but': 515,\n     'doing': 823,\n     'too': 2678,\n     'cheers': 604,\n     'tell': 2576,\n     'anything': 300,\n     'fear': 971,\n     'of': 1844,\n     'quick': 2096,\n     'thanks': 2602,\n     'subscription': 2507,\n     'ringtone': 2204,\n     'uk': 2733,\n     'charged': 591,\n     'month': 1730,\n     'please': 1994,\n     'confirm': 674,\n     'by': 522,\n     'replying': 2179,\n     'yup': 2998,\n     'look': 1535,\n     'msg': 1751,\n     'again': 240,\n     'xuhui': 2962,\n     'learn': 1465,\n     '2nd': 98,\n     'her': 1234,\n     'lesson': 1480,\n     'oops': 1869,\n     'roommate': 2218,\n     'done': 826,\n     'see': 2276,\n     'letter': 1484,\n     'decide': 763,\n     'hello': 1232,\n     'saturday': 2245,\n     'texting': 2594,\n     'decided': 764,\n     'tomo': 2672,\n     'trying': 2708,\n     'invite': 1350,\n     'pls': 1998,\n     'ahead': 248,\n     'wanted': 2839,\n     'weekend': 2866,\n     'abiola': 202,\n     'forget': 1035,\n     'need': 1788,\n     'crave': 709,\n     'most': 1740,\n     'sweet': 2535,\n     'yummy': 2995,\n     'tried': 2700,\n     'sms': 2398,\n     'nokia': 1815,\n     'camcorder': 541,\n     '08000930705': 11,\n     'delivery': 775,\n     'tomorrow': 2673,\n     'who': 2892,\n     'seeing': 2277,\n     'hope': 1266,\n     'man': 1610,\n     'well': 2873,\n     'am': 277,\n     'lt': 1572,\n     'gt': 1174,\n     'inches': 1322,\n     'calls': 539,\n     'messages': 1672,\n     'missed': 1698,\n     'didn': 786,\n     'get': 1112,\n     'nigeria': 1806,\n     'fair': 949,\n     'hopefully': 1267,\n     'tyler': 2727,\n     'could': 698,\n     'maybe': 1643,\n     'ask': 336,\n     'bit': 434,\n     'hospital': 1271,\n     'kept': 1417,\n     'telling': 2577,\n     'weak': 2856,\n     'time': 2648,\n     'saw': 2250,\n     'class': 626,\n     'gram': 1161,\n     'usually': 2778,\n     'runs': 2231,\n     'half': 1192,\n     'gets': 1113,\n     'almost': 268,\n     'whole': 2893,\n     'second': 2272,\n     'fyi': 1074,\n     'ride': 2201,\n     'morning': 1738,\n     'place': 1982,\n     'wow': 2947,\n     'never': 1798,\n     'realized': 2133,\n     'embarassed': 882,\n     'thought': 2630,\n     'liked': 1498,\n     'since': 2362,\n     'best': 414,\n     'seemed': 2279,\n     'happy': 1207,\n     'sorry': 2426,\n     'give': 1126,\n     'ac': 207,\n     'new': 1799,\n     'red': 2152,\n     'play': 1989,\n     'ice': 1301,\n     'correct': 693,\n     'end': 884,\n     'yesterday': 2980,\n     'find': 999,\n     'url': 2767,\n     'congrats': 676,\n     'year': 2973,\n     'special': 2441,\n     'cinema': 621,\n     'pass': 1925,\n     'yours': 2991,\n     '09061209465': 33,\n     'suprman': 2528,\n     'matrix3': 1635,\n     'starwars3': 2469,\n     'etc': 909,\n     'bx420': 521,\n     'ip4': 1355,\n     '5we': 143,\n     '150pm': 64,\n     'later': 1452,\n     'meeting': 1661,\n     'where': 2886,\n     'reached': 2124,\n     'series': 2297,\n     'pick': 1965,\n     'burger': 511,\n     'yourself': 2992,\n     'move': 1743,\n     'pain': 1908,\n     'good': 1144,\n     'joke': 1394,\n     'girls': 1124,\n     'situation': 2373,\n     'part': 1921,\n     'checking': 602,\n     'iq': 1357,\n     'roommates': 2219,\n     'took': 2679,\n     'forever': 1033,\n     'come': 655,\n     'double': 831,\n     'check': 600,\n     'hair': 1190,\n     'dresser': 839,\n     'said': 2237,\n     'wun': 2956,\n     'cut': 731,\n     'short': 2331,\n     'nice': 1804,\n     'pleased': 1995,\n     'advise': 232,\n     'following': 1024,\n     'recent': 2148,\n     'review': 2198,\n     'mob': 1713,\n     'awarded': 364,\n     '1500': 62,\n     'bonus': 458,\n     'song': 2419,\n     'which': 2889,\n     'valuable': 2783,\n     'frnds': 1058,\n     'rply': 2224,\n     'complimentary': 667,\n     'trip': 2701,\n     '1000': 41,\n     'dis': 803,\n     '18': 68,\n     '10': 39,\n     'ls1': 1570,\n     'hear': 1224,\n     'comes': 657,\n     'plane': 1985,\n     'wah': 2822,\n     'lucky': 1575,\n     'save': 2248,\n     'money': 1728,\n     'hee': 1228,\n     'finished': 1003,\n     'hi': 1238,\n     'babe': 368,\n     'im': 1313,\n     'wanna': 2837,\n     'something': 2415,\n     'xx': 2963,\n     'waiting': 2825,\n     'machan': 1591,\n     'once': 1861,\n     'thats': 2606,\n     'cool': 690,\n     'gentleman': 1107,\n     'dignity': 796,\n     'respect': 2185,\n     'very': 2793,\n     'much': 1760,\n     'shy': 2347,\n     'pa': 1901,\n     'after': 237,\n     'same': 2241,\n     'looking': 1538,\n     'job': 1390,\n     'ta': 2544,\n     'ah': 246,\n     'stop': 2481,\n     'urgnt': 2766,\n     'real': 2129,\n     'yo': 2985,\n     'tickets': 2644,\n     'one': 1862,\n     'used': 2773,\n     'started': 2466,\n     'requests': 2183,\n     'came': 542,\n     'bed': 398,\n     'coins': 644,\n     'gotta': 1153,\n     'kano': 1411,\n     'il': 1311,\n     'download': 833,\n     'wen': 2875,\n     'stand': 2461,\n     'close': 634,\n     'another': 288,\n     'night': 1807,\n     'spent': 2448,\n     'late': 1451,\n     'afternoon': 238,\n     'means': 1651,\n     'haven': 1216,\n     'any': 295,\n     'sheets': 2316,\n     'smile': 2392,\n     'pleasure': 1996,\n     'trouble': 2702,\n     'rain': 2105,\n     'sum1': 2515,\n     'hurts': 1293,\n     'becoz': 397,\n     'someone': 2413,\n     'loves': 1562,\n     'smiling': 2394,\n     'service': 2300,\n     'representative': 2181,\n     '0800': 9,\n     'between': 418,\n     '10am': 44,\n     '9pm': 197,\n     'guaranteed': 1175,\n     '5000': 133,\n     'havent': 1217,\n     'planning': 1987,\n     'buy': 517,\n     'lido': 1489,\n     '530': 137,\n     'show': 2340,\n     'collected': 648,\n     'simply': 2361,\n     'password': 1928,\n     'mix': 1705,\n     'verify': 2791,\n     'fml': 1021,\n     'po': 2002,\n     'box': 478,\n     'mk17': 1706,\n     'movie': 1745,\n     'abt': 205,\n     'loads': 1523,\n     'wk': 2918,\n     'hols': 1258,\n     'run': 2229,\n     'forgot': 1036,\n     'appointment': 310,\n     'four': 1040,\n     'shower': 2341,\n     'cause': 571,\n     'prob': 2051,\n     'coffee': 643,\n     'nothing': 1827,\n     'else': 878,\n     'okay': 1854,\n     'price': 2047,\n     'long': 1533,\n     'legal': 1473,\n     'them': 2610,\n     'ave': 358,\n     'gone': 1142,\n     'driving': 845,\n     'test': 2589,\n     'yet': 2981,\n     'mean': 1649,\n     'guess': 1178,\n     'gave': 1094,\n     'boston': 470,\n     'men': 1667,\n     'changed': 587,\n     'search': 2267,\n     'nyc': 1840,\n     'cuz': 734,\n     'page': 1905,\n     'says': 2253,\n     'umma': 2735,\n     'life': 1491,\n     'vava': 2788,\n     'lot': 1546,\n     'dear': 757,\n     'wishes': 2911,\n     'birthday': 432,\n     'making': 1606,\n     'truly': 2704,\n     'aight': 250,\n     'hit': 1246,\n     'would': 2945,\n     'address': 226,\n     'considering': 680,\n     'computer': 668,\n     'isn': 1363,\n     'old': 1857,\n     'people': 1945,\n     'better': 417,\n     'jokes': 1395,\n     'worry': 2941,\n     'busy': 514,\n     'research': 2184,\n     'cos': 694,\n     'things': 2618,\n     'scared': 2254,\n     'mah': 1598,\n     'loud': 1549,\n     'gent': 1105,\n     'contact': 682,\n     'last': 1450,\n     'weekends': 2867,\n     'draw': 835,\n     'shows': 2343,\n     'k52': 1408,\n     '12hrs': 55,\n     '150ppm': 66,\n     'wa': 2821,\n     'sentence': 2294,\n     'anyway': 302,\n     'juz': 1407,\n     'tt': 2712,\n     'eatin': 868,\n     'puttin': 2087,\n     'weight': 2870,\n     'haha': 1187,\n     'anythin': 299,\n     'happened': 1203,\n     'entered': 897,\n     'cabin': 524,\n     'boss': 469,\n     'felt': 981,\n     'askd': 337,\n     'invited': 1351,\n     'apartment': 305,\n     'went': 2876,\n     'specially': 2442,\n     'holiday': 1256,\n     'flights': 1017,\n     'inc': 1321,\n     'operator': 1871,\n     'min': 1683,\n     'must': 1768,\n     'friday': 1052,\n     'needed': 1789,\n     'hmm': 1249,\n     'uncle': 2739,\n     'informed': 1334,\n     'paying': 1934,\n     'school': 2258,\n     'directly': 801,\n     'food': 1026,\n     'private': 2049,\n     '2004': 78,\n     'account': 214,\n     'statement': 2470,\n     '786': 153,\n     'unredeemed': 2750,\n     'points': 2010,\n     'identifier': 1305,\n     '45239': 123,\n     'expires': 938,\n     '2000': 76,\n     'caller': 534,\n     '03': 4,\n     'landline': 1446,\n     'todays': 2665,\n     'voda': 2806,\n     'numbers': 1835,\n     'ending': 886,\n     '350': 108,\n     'award': 363,\n     'match': 1629,\n     '08712300220': 23,\n     'quoting': 2102,\n     'standard': 2462,\n     'rates': 2117,\n     'app': 307,\n     'mu': 1759,\n     'buying': 518,\n     'yetunde': 2982,\n     'hasn': 1212,\n     'sent': 2293,\n     'bother': 472,\n     'sending': 2291,\n     'shouldn': 2337,\n     'apologise': 306,\n     'girl': 1122,\n     'del': 770,\n     'bak': 376,\n     'answer': 291,\n     'sunshine': 2520,\n     'quiz': 2100,\n     'top': 2680,\n     'sony': 2421,\n     'dvd': 859,\n     'player': 1991,\n     'country': 700,\n     'ansr': 290,\n     '82277': 167,\n     'sp': 2437,\n     'tyrone': 2729,\n     'laid': 1444,\n     'dogging': 820,\n     'locations': 1526,\n     'direct': 800,\n     'join': 1392,\n     'largest': 1449,\n     'bt': 502,\n     'txting': 2725,\n     'nt': 1830,\n     'ec2a': 870,\n     'haf': 1186,\n     'yijue': 2983,\n     'him': 1241,\n     'rooms': 2220,\n     'befor': 402,\n     'activities': 219,\n     'msgs': 1754,\n     'chat': 595,\n     'hardcore': 1209,\n     'services': 2301,\n     'age': 242,\n     'yr': 2993,\n     'lazy': 1459,\n     'type': 2728,\n     'lect': 1470,\n     'sir': 2367,\n     'mail': 1600,\n     'swt': 2540,\n     'tired': 2651,\n     'little': 1516,\n     'lovable': 1553,\n     'persons': 1952,\n     'coz': 704,\n     'those': 2628,\n     'biggest': 425,\n     'their': 2609,\n     'gud': 1176,\n     'ni8': 1803,\n     'open': 1870,\n     'ya': 2967,\n     'dot': 830,\n     'whats': 2882,\n     'staff': 2459,\n     'taking': 2551,\n     'replied': 2177,\n     'sexy': 2308,\n     'female': 982,\n     'local': 1525,\n     'luv': 1578,\n     'netcollex': 1793,\n     'ltd': 1573,\n     'begin': 404,\n     'qatar': 2089,\n     'pray': 2036,\n     'hard': 1208,\n     'deleted': 771,\n     'birla': 430,\n     'soft': 2406,\n     'wine': 2904,\n     'thk': 2624,\n     'floor': 1019,\n     'shirt': 2323,\n     'sometimes': 2417,\n     'dream': 836,\n     'without': 2916,\n     'joy': 1399,\n     'lots': 1548,\n     'tv': 2718,\n     'become': 396,\n     'leaving': 1469,\n     'house': 1277,\n     'interview': 1347,\n     'boy': 482,\n     'missing': 1700,\n     'years': 2974,\n     'arrange': 328,\n     'keep': 1415,\n     'safe': 2236,\n     'because': 395,\n     'everyone': 918,\n     'parents': 1916,\n     'hand': 1195,\n     'each': 860,\n     'spend': 2446,\n     'inviting': 1352,\n     'friend': 1053,\n     '434': 121,\n     'frnd': 1057,\n     '62468': 145,\n     'order': 1881,\n     'should': 2336,\n     'content': 684,\n     'goto': 1152,\n     'internet': 1346,\n     'menu': 1669,\n     'wit': 2913,\n     'escape': 904,\n     'fancy': 954,\n     'needs': 1790,\n     'completely': 666,\n     'also': 274,\n     'waste': 2847,\n     'bank': 378,\n     'hmmm': 1250,\n     'hop': 1265,\n     'muz': 1769,\n     'discuss': 805,\n     'liao': 1486,\n     'coming': 659,\n     'bloody': 449,\n     'hell': 1230,\n     'cant': 550,\n     'believe': 409,\n     'mr': 1748,\n     'ill': 1312,\n     'spanish': 2439,\n     'bath': 384,\n     'carlos': 561,\n     'mall': 1609,\n     'turns': 2717,\n     'staying': 2473,\n     'til': 2646,\n     'smoke': 2395,\n     'worth': 2943,\n     'doesnt': 818,\n     'log': 1527,\n     'spoke': 2451,\n     'maneesha': 1616,\n     'satisfied': 2244,\n     'experience': 937,\n     'toll': 2669,\n     'offer': 1846,\n     'especially': 906,\n     'studying': 2497,\n     'anyways': 303,\n     'gr8': 1157,\n     'trust': 2705,\n     'guys': 1182,\n     'bye': 523,\n     'working': 2936,\n     'towards': 2689,\n     'mummy': 1762,\n     'boytoy': 485,\n     'awesome': 366,\n     'minute': 1690,\n     'freephone': 1047,\n     '0808': 15,\n     '145': 58,\n     '4742': 124,\n     '9am': 195,\n     '11pm': 50,\n     'xmas': 2961,\n     'radio': 2103,\n     'jus': 1405,\n     'bathe': 385,\n     'sis': 2368,\n     'using': 2776,\n     'finishes': 1004,\n     'unique': 2746,\n     'august': 353,\n     'joined': 1393,\n     'touch': 2685,\n     'deal': 756,\n     'personal': 1950,\n     'finally': 998,\n     'course': 702,\n     'itself': 1370,\n     'however': 1279,\n     'suggest': 2512,\n     'able': 203,\n     'every': 916,\n     'settled': 2305,\n     'mrng': 1749,\n     'hav': 1214,\n     'story': 2486,\n     'dead': 755,\n     'tmr': 2659,\n     'orchard': 1880,\n     'mrt': 1750,\n     'kate': 1413,\n     'evening': 914,\n     'found': 1039,\n     'bucks': 504,\n     'darlin': 744,\n     'ive': 1372,\n     'college': 651,\n     'successfully': 2509,\n     'decimal': 765,\n     'balance': 377,\n     'rs': 2225,\n     'transaction': 2694,\n     'id': 1302,\n     'goodmorning': 1145,\n     'sleeping': 2385,\n     'dat': 747,\n     'oso': 1888,\n     'cannot': 549,\n     'oredi': 1883,\n     'straight': 2488,\n     'connection': 679,\n     'before': 403,\n     'bill': 426,\n     'both': 471,\n     'shoot': 2328,\n     'big': 423,\n     'ready': 2128,\n     'break': 488,\n     'semester': 2287,\n     'study': 2496,\n     'noe': 1814,\n     'leh': 1475,\n     'sounds': 2433,\n     'slept': 2386,\n     'past': 1930,\n     'few': 985,\n     'nights': 1808,\n     'easy': 865,\n     'sen': 2288,\n     'exam': 925,\n     'march': 1619,\n     'atm': 348,\n     'register': 2159,\n     'os': 1887,\n     'called': 533,\n     'important': 1317,\n     'files': 992,\n     'system': 2543,\n     'shop': 2329,\n     'happen': 1201,\n     'romantic': 2215,\n     'nite': 1810,\n     '500': 132,\n     '89545': 189,\n     'collect': 647,\n     'tc': 2562,\n     'biz': 437,\n     '2optout': 100,\n     '087187262701': 29,\n     '50gbp': 134,\n     'mtmsg18': 1757,\n     'appreciate': 311,\n     'partner': 1922,\n     'career': 556,\n     'off': 1845,\n     'start': 2465,\n     'followed': 1023,\n     'sign': 2353,\n     'company': 663,\n     'than': 2599,\n     'teacher': 2567,\n     'bcoz': 390,\n     'teaches': 2568,\n     'lessons': 1481,\n     'walk': 2829,\n     'cross': 716,\n     ...}\n\n\n\n# Cel: zaimplementowa\u0107 w pe\u0142ni zautomatyzowane znajdowanie najlepszego modelu\n\nNa samym pocz\u0105tku wydzieli\u0107 1000 obserwacji na zbi\u00f3r testowy, na kt\u00f3rym na samym ko\u0144cu przetestujemy najlepszy model. Podczas szukania najlepszego modelu nie dotykamy tego zbioru!\n\nWej\u015bcie:\n- lista modeli w postaci og\u00f3lnie, kt\u00f3r\u0105\u00a0podaje si\u0119\u00a0do funkcji Pipeline lub lista pipelin\u00f3w,\n- lista siatek parametr\u00f3w, kt\u00f3re chcemy zbada\u0107, dla odpowiadaj\u0105ych modeli,\n\nWyj\u015bcie \n- accuracy na zbiorze testowym dla ka\u017cdego najlepszego wariantu danego modelu.\n\n\n```python\nX = sms.message\ny = sms.label\n```\n\n\n```python\n#wydzielenie zbiorow\nX_train, X_test , y_train, y_test = train_test_split(x,y,test_size=1000)\n```\n\n\n```python\nmodels = [LogisticRegression(),DecisionTreeClassifier(),MultinomialNB()]\n```\n\n\n```python\nfor model in models:\n    pipe = Pipeline([(\"scaler\", StandardScaler(with_mean=False)),\n                 (\"model\", model)])\n\n    param_grid = {\"scaler__with_std\": [True, False]}\n\n    gs = GridSearchCV(pipe, param_grid, cv = 10, n_jobs=-1)\n\n    gs.fit(X_train, y_train)\n    \n    #model.fit(X_train, y_train)\n    print(accuracy_score(y_test, gs.predict(X_test)))\n```\n\n    0.982\n    0.971\n    0.987\n\n\n\n```python\n# rozwiazanie prowadzacego\nX,y = sms.message, sms.label\nX_train, X_test , y_train, y_test = train_test_split(X,y,test_size=1000)\n```\n\n\n```python\npipelines = [Pipeline([\n    (\"vectorizer\", CountVectorizer()),\n    (\"scaler\", StandardScaler(with_mean=False)),\n    (\"model\", LogisticRegression())\n]),\n             Pipeline([\n    (\"vectorizer\", CountVectorizer()),\n    (\"model\", LogisticRegression())\n                 ]),\n             Pipeline([\n    (\"vectorizer\", CountVectorizer()),\n    (\"model\", DecisionTreeClassifier())\n\n]),\n             Pipeline([\n    (\"vectorizer\", CountVectorizer()),\n    (\"model\", MultinomialNB())\n\n])\n            ]\n\nparam_grids = [{\"model__penalty\": [\"l1\",\"l2\"],\n              \"model__C\": [0.01, 0.1, 1, 10, 100]},\n               {\"model__penalty\": [\"l1\",\"l2\"],\n              \"model__C\": [0.01, 0.1, 1, 10, 10e8]},\n               {\"model__min_samples_leaf\": [10,25,50,100],\n              \"model__max_deph\": [None, 10]},\n               {}\n              ]\n\nfor model, grid in zip(pipelines, param_grids):\n    gs = GridSearchCV(model, grid, cv=10)\n    gs.fit(X_train, y_train)\n    print(f' {model} accuracy - {accuracy_score(y_test, gs.predict(X_test))}')\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "2770e54dd4ecc56c8e3a1268d1cc222f69f187de", "size": 228719, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Machine Learning/ML1_materialy_do_zajec.ipynb", "max_stars_repo_name": "mrcngrcki/bootcamp", "max_stars_repo_head_hexsha": "b8634368eba7f4074290b11c4476b9d44ff93f4d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Machine Learning/ML1_materialy_do_zajec.ipynb", "max_issues_repo_name": "mrcngrcki/bootcamp", "max_issues_repo_head_hexsha": "b8634368eba7f4074290b11c4476b9d44ff93f4d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Machine Learning/ML1_materialy_do_zajec.ipynb", "max_forks_repo_name": "mrcngrcki/bootcamp", "max_forks_repo_head_hexsha": "b8634368eba7f4074290b11c4476b9d44ff93f4d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.9940982059, "max_line_length": 38336, "alphanum_fraction": 0.6653797892, "converted": true, "num_tokens": 28950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.15610489155639232, "lm_q1q2_score": 0.04902482626917201}}
{"text": "```python\nfrom IPython.core.display import HTML, Image\ncss_file = 'style.css'\nHTML(open(css_file, 'r').read())\n```\n\n\n\n\n<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:100,300,400,500,700,800,900,100italic,300italic,400italic,500italic,700italic,800italic,900italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Arvo:400,700,400italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=PT+Mono' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Shadows+Into+Light' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Philosopher:400,700,400italic,700italic' rel='stylesheet' type='text/css'>\n\n<style>\n\n@font-face {\n    font-family: \"Computer Modern\";\n    src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');\n}\n\n#notebook_panel { /* main background */\n    background: #ddd;\n    color: #000000;\n}\n\n\n\n/* Formatting for header cells */\n.text_cell_render h1 {\n    font-family: 'Philosopher', sans-serif;\n    font-weight: 400;\n    font-size: 2.2em;\n    line-height: 100%;\n    color: rgb(0, 80, 120);\n    margin-bottom: 0.1em;\n    margin-top: 0.1em;\n    display: block;\n}\t\n.text_cell_render h2 {\n    font-family: 'Philosopher', serif;\n    font-weight: 400;\n    font-size: 1.9em;\n    line-height: 100%;\n    color: rgb(200,100,0);\n    margin-bottom: 0.1em;\n    margin-top: 0.1em;\n    display: block;\n}\t\n\n.text_cell_render h3 {\n    font-family: 'Philosopher', serif;\n    margin-top:12px;\n    margin-bottom: 3px;\n    font-style: italic;\n    color: rgb(94,127,192);\n}\n\n.text_cell_render h4 {\n    font-family: 'Philosopher', serif;\n}\n\n.text_cell_render h5 {\n    font-family: 'Alegreya Sans', sans-serif;\n    font-weight: 300;\n    font-size: 16pt;\n    color: grey;\n    font-style: italic;\n    margin-bottom: .1em;\n    margin-top: 0.1em;\n    display: block;\n}\n\n.text_cell_render h6 {\n    font-family: 'PT Mono', sans-serif;\n    font-weight: 300;\n    font-size: 10pt;\n    color: grey;\n    margin-bottom: 1px;\n    margin-top: 1px;\n}\n\n.CodeMirror{\n        font-family: \"PT Mono\";\n        font-size: 100%;\n}\n\n</style>\n\n\n\n\n\n\n```python\nfrom sympy import init_printing, symbols, Matrix\nfrom warnings import filterwarnings\n```\n\n\n```python\ninit_printing(use_latex='mathjax')\nfilterwarnings('ignore')\n```\n\n# Exam review\n\n### Question 1\n\n* Consider three non-zero vectors in &#8477;<sup>7</sup>\n    * What is the dimension of the subspace that they can span?\n\n#### Solution 1\n\n* One, two, or three\n* They can't span a subspace of higher dimension as there are only three vectors\n* Zero cannot be an answer, because they are all non-zero vectors\n\n### Question 2\n\n* Part 1 \n    * Consider a 5&#215;3 matrix in echelon form with three pivots\n        * What's the nullspace\n*  Part 2 \n    * Consider a 10&#215;3 matrix of form the form below and calculate its rank and echelon form\n$$ \\begin{bmatrix} R \\\\ 2R \\end{bmatrix} $$\n* Part 3\n    * Give the row-reduced form of the matrix\n$$ \\begin{bmatrix} U & U \\\\ U & 0 \\end{bmatrix} $$\n\n#### Solution 2\n\n* Part 1\n    * The nullspace can only be the zero vector\n$$ \\begin{bmatrix} 0 \\\\ 0 \\\\ 0 \\end{bmatrix} $$\n    * With three columns all with pivots, we have *n* - *r* = 3 - 3 = 0\n\n* Part 2\n    * Row reduction will take us to\n$$ \\begin{bmatrix} R \\\\ 0 \\end{bmatrix} $$\n\n* Part 3\n$$ \\begin{bmatrix} U & U \\\\ 0 & -U \\end{bmatrix} $$\n    * In reduced row echelon form\n$$ \\begin{bmatrix} U & 0 \\\\ 0 & U \\end{bmatrix} $$\n\n### Question 3\n\n* Consider\n$$ {A} \\overline {x} = \\begin{bmatrix} 2 \\\\ 4 \\\\ 2 \\end{bmatrix} $$\n* With\n$$ {x} = \\begin{bmatrix} 2 \\\\ 0 \\\\ 0 \\end{bmatrix} + {c}\\begin{bmatrix} 1 \\\\ 1 \\\\ 0 \\end{bmatrix} + {d}\\begin{bmatrix} 0 \\\\ 0 \\\\ 1 \\end{bmatrix} $$\n* Part 1\n    * What is the dimension of the rowspace of A and the nullspace of A\n* Part 2\n    * For what values of **b** can A**x** = **b** be solved?\n\n#### Solution 3\n\n* Part 1\n    * Well, the size of the matrix must be 3&#215;3\n    * The dimension of the nullspace is 2 (because two non-pivot columns)\n    * With *n* - *r* = 2, we have *r* = 1, which must hold for the rowspace of A\n* Part 2\n    * Looking only at the particular solution we must have\n$$ 2\\begin{bmatrix} { a }_{ 11 } \\\\ { a }_{ 21 } \\\\ { a }_{ 31 } \\end{bmatrix}=\\begin{bmatrix} 2 \\\\ 4 \\\\ 2 \\end{bmatrix}\\\\ \\therefore \\quad \\begin{bmatrix} { a }_{ 11 } \\\\ { a }_{ 21 } \\\\ { a }_{ 31 } \\end{bmatrix}\\quad =\\quad \\begin{bmatrix} 1 \\\\ 2 \\\\ 1 \\end{bmatrix}\\\\ \\therefore \\quad \\begin{bmatrix} { a }_{ 11 } & { a }_{ 12 } & { a }_{ 13 } \\\\ { a }_{ 21 } & { a }_{ 22 } & { a }_{ 23 } \\\\ { a }_{ 31 } & { a }_{ 32 } & { a }_{ 33 } \\end{bmatrix}=\\begin{bmatrix} 1 & -1 & 0 \\\\ 2 & -2 & 0 \\\\ 1 & -1 & 0 \\end{bmatrix} $$\n* So, how did I get the last two columns?\n    * Well, they cannot be independent of the first column and the last column must have all zeros to set up the first variable solution fr *x*<sub>3</sub>, i.e. *x*<sub>3</sub> = *d*\n    * Adding column 2 to column 1 to get all zeros must result in what you seen for column 2\n\n\n```python\nA = Matrix([[1, -1, 0], [2, -2, 0], [1, -1, 0]])\nx_vect = Matrix([2, 0, 0])\nx_vect_null_1 = Matrix([1, 1, 0])\nx_vect_null_2 = Matrix([0, 0, 1])\nA * x_vect + A * x_vect_null_1 + A * x_vect_null_2\n```\n\n\n\n\n$$\\left[\\begin{matrix}2\\\\4\\\\2\\end{matrix}\\right]$$\n\n\n\n\n```python\nA.nullspace()\n```\n\n\n\n\n$$\\begin{bmatrix}\\left[\\begin{matrix}1\\\\1\\\\0\\end{matrix}\\right], & \\left[\\begin{matrix}0\\\\0\\\\1\\end{matrix}\\right]\\end{bmatrix}$$\n\n\n\n* It can only be solve for scalar multiples of\n$$ \\begin{bmatrix} 1 \\\\ 2 \\\\ 1 \\end{bmatrix} $$\n\n### Question and solution 4\n\n* If the nullspace of a square matrix is the zero vector only, does the nullspace of the transpose also only contain the zero vector\n    * Yes\n\n* Consider the matrix space of all 5&#215;5 matrices; do the invertible 5&#215;5 matrices form a subspace\n    * No, as the set of invertible matrices would not contain the zero matrix\n    * Also if I add two invertible matrices, I don't know if the resultant matrix is invertible\n    * The singular ones won't work either as adding two we also don't know if the resultant matrix is invertible\n\n* If B<sup>2</sup> = **0**, is B = **0**?\n    * No, i.e\n$$ {B} = \\begin{bmatrix} 0 & 1 \\\\ 0 & 0 \\end{bmatrix} $$\n\n\n```python\nB = Matrix([[0, 1], [0, 0]])\nB ** 2 # Could also use B * B\n```\n\n\n\n\n$$\\left[\\begin{matrix}0 & 0\\\\0 & 0\\end{matrix}\\right]$$\n\n\n\n\n```python\nB == B * B # Checking by Boolean statement\n```\n\n\n\n\n    False\n\n\n\n* A system of *n* unknowns in *n* equations is solvable for every **b** if the columns of the matrix of coefficients are independent?\n    * Yes\n\n### Question 5\n\n$$ B=\\begin{bmatrix} 1 & 1 & 0 \\\\ 0 & 1 & 0 \\\\ 1 & 0 & 1 \\end{bmatrix}\\begin{bmatrix} 1 & 0 & -1 & 2 \\\\ 0 & 1 & 1 & -1 \\\\ 0 & 0 & 0 & 0 \\end{bmatrix} $$\n* Calculate the basis of the nullspace of B\n\n#### Solution 5\n\n* B will have to be a 3&#215;4 matrix\n* The last row will be all zeros\n\n\n```python\nB1 = Matrix([[1, 1, 0], [0, 1, 0], [1, 0, 1]])\nB2 = Matrix([[1, 0, -1, 2], [0, 1, 1, -1], [0, 0, 0, 0]])\nB1, B2\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}1 & 1 & 0\\\\0 & 1 & 0\\\\1 & 0 & 1\\end{matrix}\\right], & \\left[\\begin{matrix}1 & 0 & -1 & 2\\\\0 & 1 & 1 & -1\\\\0 & 0 & 0 & 0\\end{matrix}\\right]\\end{pmatrix}$$\n\n\n\n* It is important to note that of we multiply an invertible matrix by another matrix (assuming multiplication is possible by the shape of the matrices), then the invertible one (B1 above), plays no part in the nullspace\n    * N(CD) = N(D) if C is invertible\n* We therefor only have to look at B2\n* It has 2 pivot columns, i.e. rank is *r* = 2\n* It will therefor have 2 independent variables, making the nullspace 2-dimensional\n\n\n```python\nB = B1 * B2\nB.nullspace()\n```\n\n\n\n\n$$\\begin{bmatrix}\\left[\\begin{matrix}1\\\\-1\\\\1\\\\0\\end{matrix}\\right], & \\left[\\begin{matrix}-2\\\\1\\\\0\\\\1\\end{matrix}\\right]\\end{bmatrix}$$\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "d245f989e72540e179419ef802af721fc0383103", "size": 15134, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_13_Quiz1_review.ipynb", "max_stars_repo_name": "okara83/Becoming-a-Data-Scientist", "max_stars_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_13_Quiz1_review.ipynb", "max_issues_repo_name": "okara83/Becoming-a-Data-Scientist", "max_issues_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_13_Quiz1_review.ipynb", "max_forks_repo_name": "okara83/Becoming-a-Data-Scientist", "max_forks_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-09T15:41:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T07:47:40.000Z", "avg_line_length": 27.4166666667, "max_line_length": 579, "alphanum_fraction": 0.4730408352, "converted": true, "num_tokens": 2714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245510940225, "lm_q2_score": 0.18010666408646392, "lm_q1q2_score": 0.048993434447162254}}
{"text": "# **CS224W - Colab 5**\n\nIn this Colab, we will shift our focus from homogenous graphs to heterogeneous graphs. Heterogeneous graphs extend the traditional homogenous graphs that we have been working with by incorperating different node and edge types. This additional information allows us to extend the graph neural nework models that we have worked with before. Namely, we can apply heterogenous message passing, where different message types now exist between different node and edge type relationships. \n\nIn this notebook, we will first learn how to transform NetworkX graphs into DeepSNAP representations. Then, we will dive deeper into how DeepSNAP stores and represents heterogeneous graphs as PyTorch Tensors.\n\nLastly, we will build our own heterogenous graph neural netowrk models using PyTorch Geometric and DeepSNAP. We will then apply our models for a node property prediction task; specifically, we will evaluate these models on the heterogeneous ACM node prediction dataset.\n\n**Note**: Make sure to **sequentially run all the cells in each section**, so that the intermediate variables / packages will carry over to the next cell\n\nHave fun and good luck on Colab 5 :)\n\n# Device\nYou might need to use GPU for this Colab.\n\nPlease click `Runtime` and then `Change runtime type`. Then set the `hardware accelerator` to **GPU**.\n\n# Installation\n\n\n```python\n# Install torch geometric\nimport os\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  !pip install torch-scatter -f https://data.pyg.org/whl/torch-1.10.0+cu111.html\n  !pip install torch-sparse -f https://data.pyg.org/whl/torch-1.10.0+cu111.html\n  !pip install torch-geometric\n  !pip install -q git+https://github.com/snap-stanford/deepsnap.git\n  !pip install -U -q PyDrive\n```\n\n    Looking in links: https://data.pyg.org/whl/torch-1.10.0+cu111.html\n    Collecting torch-scatter\n      Downloading https://data.pyg.org/whl/torch-1.10.0%2Bcu113/torch_scatter-2.0.9-cp37-cp37m-linux_x86_64.whl (7.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 7.9 MB 5.2 MB/s \n    \u001b[?25hInstalling collected packages: torch-scatter\n    Successfully installed torch-scatter-2.0.9\n    Looking in links: https://data.pyg.org/whl/torch-1.10.0+cu111.html\n    Collecting torch-sparse\n      Downloading https://data.pyg.org/whl/torch-1.10.0%2Bcu113/torch_sparse-0.6.12-cp37-cp37m-linux_x86_64.whl (3.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.5 MB 4.4 MB/s \n    \u001b[?25hRequirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from torch-sparse) (1.4.1)\n    Requirement already satisfied: numpy>=1.13.3 in /usr/local/lib/python3.7/dist-packages (from scipy->torch-sparse) (1.19.5)\n    Installing collected packages: torch-sparse\n    Successfully installed torch-sparse-0.6.12\n    Collecting torch-geometric\n      Downloading torch_geometric-2.0.3.tar.gz (370 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 370 kB 4.2 MB/s \n    \u001b[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (1.19.5)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (4.62.3)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (1.4.1)\n    Requirement already satisfied: networkx in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (2.6.3)\n    Requirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (1.0.2)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (2.23.0)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (1.1.5)\n    Collecting rdflib\n      Downloading rdflib-6.1.1-py3-none-any.whl (482 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 482 kB 50.2 MB/s \n    \u001b[?25hRequirement already satisfied: googledrivedownloader in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (0.4)\n    Requirement already satisfied: jinja2 in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (2.11.3)\n    Requirement already satisfied: pyparsing in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (3.0.6)\n    Collecting yacs\n      Downloading yacs-0.1.8-py3-none-any.whl (14 kB)\n    Requirement already satisfied: PyYAML in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (3.13)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2->torch-geometric) (2.0.1)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->torch-geometric) (2.8.2)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->torch-geometric) (2018.9)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas->torch-geometric) (1.15.0)\n    Requirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from rdflib->torch-geometric) (4.10.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from rdflib->torch-geometric) (57.4.0)\n    Collecting isodate\n      Downloading isodate-0.6.1-py2.py3-none-any.whl (41 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 41 kB 553 kB/s \n    \u001b[?25hRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->rdflib->torch-geometric) (3.7.0)\n    Requirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->rdflib->torch-geometric) (3.10.0.2)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->torch-geometric) (2021.10.8)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->torch-geometric) (2.10)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->torch-geometric) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->torch-geometric) (3.0.4)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->torch-geometric) (1.1.0)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->torch-geometric) (3.0.0)\n    Building wheels for collected packages: torch-geometric\n      Building wheel for torch-geometric (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for torch-geometric: filename=torch_geometric-2.0.3-py3-none-any.whl size=581968 sha256=c63ac66b814ba4e357e9d6ff9dce6849bf7b4b8c3b6ea929ff85a09fa80b0d9c\n      Stored in directory: /root/.cache/pip/wheels/c3/2a/58/87ce0508964d4def1aafb92750c4f3ac77038efd1b9a89dcf5\n    Successfully built torch-geometric\n    Installing collected packages: isodate, yacs, rdflib, torch-geometric\n    Successfully installed isodate-0.6.1 rdflib-6.1.1 torch-geometric-2.0.3 yacs-0.1.8\n      Building wheel for deepsnap (setup.py) ... \u001b[?25l\u001b[?25hdone\n\n\n\n```python\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  !nvcc --version\n  !python -c \"import torch; print(torch.version.cuda)\"\n```\n\n    nvcc: NVIDIA (R) Cuda compiler driver\n    Copyright (c) 2005-2020 NVIDIA Corporation\n    Built on Mon_Oct_12_20:09:46_PDT_2020\n    Cuda compilation tools, release 11.1, V11.1.105\n    Build cuda_11.1.TC455_06.29190527_0\n    11.1\n\n\n\n```python\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  import torch\n  print(torch.__version__)\n  import torch_geometric\n  print(torch_geometric.__version__)\n```\n\n    1.10.0+cu111\n    2.0.3\n\n\n# DeepSNAP Basics\n\nIn previous Colabs we used both of graph class (NetworkX) and tensor (PyG) representations of graphs separately. The graph class `nx.Graph` provides rich analysis and manipulation functionalities, such as the clustering coefficient and PageRank. To feed the graph into the model, we need to transform the graph into tensor representations including edge tensor `edge_index` and node attributes tensors `x` and `y`. But only using tensors (as the graphs formatted in PyG `datasets` and `data`) will make many graph manipulations and analysis less efficient and harder. So, in this Colab we will use DeepSNAP which combines both representations and offers a full pipeline for GNN training / validation / testing.\n\n\nIn general, [DeepSNAP](https://github.com/snap-stanford/deepsnap) is a Python library to assist efficient deep learning on graphs. DeepSNAP features in its support for flexible graph manipulation, standard pipeline, heterogeneous graphs and simple API.\n\n1. DeepSNAP is easy to be used for the sophisticated graph manipulations, such as feature computation, pretraining, subgraph extraction etc. during/before the training.\n2. In most frameworks, standard pipelines for node, edge, link, graph-level tasks under inductive or transductive settings are left to the user to code. In practice, there are additional design choices involved (such as how to split dataset for link prediction). DeepSNAP provides such a standard pipeline that greatly saves repetitive coding efforts, and enables fair comparision for models.\n3. Many real-world graphs are heterogeneous graphs. But packages support for heterogeneous graphs, including data storage and flexible message passing, is lacking. DeepSNAP provides an efficient and flexible heterogeneous graph that supports both the node and edge heterogeneity.\n\n[DeepSNAP](https://github.com/snap-stanford/deepsnap) is a newly released project and it is still under development. If you find any bugs or have any improvement ideas, feel free to raise issues or create pull requests on the GitHub directly :)\n\nIn this Colab, we will focus on learning using Heterogeneous Graphs. Not many libraries are able to handle heterogeneous graphs, but DeepSNAP handles them quite elegantly, which is why we're introducing it here!\n\n# 1) DeepSNAP Heterogeneous Graph\n\nFirst, we will explore how to transform a NetworkX graph into the format supported by DeepSNAP. \n\nIn DeepSNAP we have three levels of attributes. We can have **node level** attributes including `node_feature` and `node_label`. The other two levels of attributes are graph and edge attributes. The usage is similar to the node level one except that the feature becomes `edge_feature` or `graph_feature` and label becomes `edge_label` or `graph_label` etc.\n\nDeepSNAP extends its traditional graph representation to include heterogeneous graphs by including the following graph property features:  \n* `node_feature`: The feature of each node (`torch.tensor`)\n* `edge_feature`: The feature of each edge (`torch.tensor`)\n* `node_label`: The label of each node (`int`)\n* `node_type`: The node type of each node (`string`)\n* `edge_type`: The edge type of each edge (`string`)\n\nwhere the key **new** features we add are `node_type` and `edge_type`, which enables us to perform heterogenous message passing.\n\nFor this first question we will work with the familiar [karate club graph](https://networkx.github.io/documentation/stable/auto_examples/graph/plot_karate_club.html) seen in Colab 1. To start, since each node in the graph belongs to one of two clubs (club \"Mr. Hi\" or club \"Officer\"), we will treat the club as the `node_type`. The code below demonstrates how to differentiate the nodes in the NetworkX graph.\n\n\n\n```python\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport copy\n\nfrom networkx.algorithms.community import greedy_modularity_communities\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n\n  from pylab import show\n  \n  G = nx.karate_club_graph()\n\n  # Community map is a dict that associated the id of each node to one of the \n  # two classes/types\n  community_map = {}\n  for node in G.nodes(data=True):\n    if node[1][\"club\"] == \"Mr. Hi\":\n      community_map[node[0]] = 0\n    else:\n      community_map[node[0]] = 1\n\n  print(community_map)\n\n  # Create a list fo define color of nodes\n  node_color = []\n\n  # Create a color mapping function\n  color_map = {0: 0, 1: 1}\n\n  # Get the color of each node given its type\n  node_color = [color_map[community_map[node]] for node in G.nodes()]\n  \n  # Get position of Graph to obtain spring layout\n  pos = nx.spring_layout(G)\n\n  # Create a figure\n  plt.figure(figsize=(7, 7))\n  nx.draw(G, pos=pos, cmap=plt.get_cmap('coolwarm'), node_color=node_color)\n  show()\n\n```\n\n### Question 1.1: Assigning Node Type and Node Features \n\nUsing the `community_map` dictionary and graph `G` from above, add node attributes `node_type` and `node_label` to the graph G. Namely, for `node_type` assign nodes in the \"Mr. Hi\" club to a node type `n0` and nodes in club \"Officer\" a node type `n1`. Note: the node type should be a `string` property.\n\nThen for `node_label`, assign nodes in \"Mr. Hi\" club to a `node_label` `0` and nodes in club \"Officer\" a `node_label` of `1`.\n\nLastly, assign every node the *tensor* feature vector $[1, 1, 1, 1, 1]$. \n\n**Hint**: Look at the NetworkX function `nx.classes.function.set_node_attributes`.\n\n**Note**: This question is not specifically graded but is important for later questions.\n\n\n```python\nimport torch\n\ndef assign_node_types(G, community_map):\n  # TODO: Implement a function that takes in a NetworkX graph\n  # G and community map assignment (mapping node id --> 0/1 label)\n  # and adds 'node_type' as a node_attribute in G.\n\n  ############# Your code here ############\n  ## (~2 line of code)\n  ## Note\n  ## 1. Look up NetworkX `nx.classes.function.set_node_attributes`\n  ## 2. Look above for the two node type values!\n  renamed_community_map = {id: ('n0' if label == 0 else 'n1') for id, label in community_map.items()}\n  nx.set_node_attributes(G, renamed_community_map, name='node_type')\n  \n  #########################################\n\ndef assign_node_labels(G, community_map):\n  # TODO: Implement a function that takes in a NetworkX graph\n  # G and community map assignment (mapping node id --> 0/1 label)\n  # and adds 'node_label' as a node_attribute in G.\n\n  ############# Your code here ############\n  ## (~2 line of code)\n  ## Note\n  ## 1. Look up NetworkX `nx.classes.function.set_node_attributes`\n  nx.set_node_attributes(G, community_map, name='node_label')\n\n  #########################################\n\ndef assign_node_features(G):\n  # TODO: Implement a function that takes in a NetworkX graph\n  # G and adds 'node_feature' as a node_attribute in G. Each node\n  # in the graph has the same feature vector - a torchtensor with \n  # data [1., 1., 1., 1., 1.]\n\n  ############# Your code here ############\n  ## (~2 line of code)\n  ## Note\n  ## 1. Look up NetworkX `nx.classes.function.set_node_attributes`\n  nx.set_node_attributes(G, torch.ones(5), name='node_feature')\n\n  pass\n\n  #########################################\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  assign_node_types(G, community_map)\n  assign_node_labels(G, community_map)\n  assign_node_features(G)\n\n  # Explore node properties for the node with id: 20\n  node_id = 20\n  print (f\"Node {node_id} has properties:\", G.nodes(data=True)[node_id])\n\n  print(G.nodes(data=True))\n```\n\n    Node 20 has properties: {'club': 'Officer', 'node_type': 'n1', 'node_label': 1, 'node_feature': tensor([1., 1., 1., 1., 1.])}\n    [(0, {'club': 'Mr. Hi', 'node_type': 'n0', 'node_label': 0, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (1, {'club': 'Mr. Hi', 'node_type': 'n0', 'node_label': 0, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (2, {'club': 'Mr. Hi', 'node_type': 'n0', 'node_label': 0, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (3, {'club': 'Mr. Hi', 'node_type': 'n0', 'node_label': 0, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (4, {'club': 'Mr. Hi', 'node_type': 'n0', 'node_label': 0, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (5, {'club': 'Mr. Hi', 'node_type': 'n0', 'node_label': 0, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (6, {'club': 'Mr. Hi', 'node_type': 'n0', 'node_label': 0, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (7, {'club': 'Mr. Hi', 'node_type': 'n0', 'node_label': 0, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (8, {'club': 'Mr. Hi', 'node_type': 'n0', 'node_label': 0, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (9, {'club': 'Officer', 'node_type': 'n1', 'node_label': 1, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (10, {'club': 'Mr. Hi', 'node_type': 'n0', 'node_label': 0, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (11, {'club': 'Mr. Hi', 'node_type': 'n0', 'node_label': 0, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (12, {'club': 'Mr. Hi', 'node_type': 'n0', 'node_label': 0, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (13, {'club': 'Mr. Hi', 'node_type': 'n0', 'node_label': 0, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (14, {'club': 'Officer', 'node_type': 'n1', 'node_label': 1, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (15, {'club': 'Officer', 'node_type': 'n1', 'node_label': 1, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (16, {'club': 'Mr. Hi', 'node_type': 'n0', 'node_label': 0, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (17, {'club': 'Mr. Hi', 'node_type': 'n0', 'node_label': 0, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (18, {'club': 'Officer', 'node_type': 'n1', 'node_label': 1, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (19, {'club': 'Mr. Hi', 'node_type': 'n0', 'node_label': 0, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (20, {'club': 'Officer', 'node_type': 'n1', 'node_label': 1, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (21, {'club': 'Mr. Hi', 'node_type': 'n0', 'node_label': 0, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (22, {'club': 'Officer', 'node_type': 'n1', 'node_label': 1, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (23, {'club': 'Officer', 'node_type': 'n1', 'node_label': 1, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (24, {'club': 'Officer', 'node_type': 'n1', 'node_label': 1, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (25, {'club': 'Officer', 'node_type': 'n1', 'node_label': 1, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (26, {'club': 'Officer', 'node_type': 'n1', 'node_label': 1, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (27, {'club': 'Officer', 'node_type': 'n1', 'node_label': 1, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (28, {'club': 'Officer', 'node_type': 'n1', 'node_label': 1, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (29, {'club': 'Officer', 'node_type': 'n1', 'node_label': 1, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (30, {'club': 'Officer', 'node_type': 'n1', 'node_label': 1, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (31, {'club': 'Officer', 'node_type': 'n1', 'node_label': 1, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (32, {'club': 'Officer', 'node_type': 'n1', 'node_label': 1, 'node_feature': tensor([1., 1., 1., 1., 1.])}), (33, {'club': 'Officer', 'node_type': 'n1', 'node_label': 1, 'node_feature': tensor([1., 1., 1., 1., 1.])})]\n\n\n### Question 1.2: Assigning Edge Types \n\nNext, we will assign three different `edge_types`: \n* Edges within club \"Mr. Hi\": `e0`\n* Edges within club \"Officer\": `e1`\n* Edges between the two clubs: `e2`\n\n**Hint**: Use the `community_map` from before and `nx.classes.function.set_edge_attributes`\n\n\n```python\ndef assign_edge_types(G, community_map):\n  # TODO: Implement a function that takes in a NetworkX graph\n  # G and community map assignment (mapping node id --> 0/1 label)\n  # and adds 'edge_type' as a edge_attribute in G.\n\n  ############# Your code here ############\n  ## (~5 line of code)\n  ## Note\n  ## 1. Create an edge assignment dict following rules above\n  ## 2. Look up NetworkX `nx.classes.function.set_edge_attributes`\n\n  edge_map = {}\n\n  # Go through all the edges\n  for edge in G.edges():\n    if community_map[edge[0]] == community_map[edge[1]]:\n      edge_map[edge] = 'e0' if community_map[edge[0]] == 0 else 'e1'\n    else: \n      edge_map[edge] = 'e2'\n\n  nx.set_edge_attributes(G, edge_map, name='edge_type')\n\n  #########################################\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  assign_edge_types(G, community_map)\n\n  # Explore edge properties for a sampled edge and check the corresponding\n  # node types\n  edge_idx = 15\n  n1 = 0\n  n2 = 31\n  edge = list(G.edges(data=True))[edge_idx]\n  print (f\"Edge ({edge[0]}, {edge[1]}) has properties:\", edge[2])\n  print (f\"Node {n1} has properties:\", G.nodes(data=True)[n1])\n  print (f\"Node {n2} has properties:\", G.nodes(data=True)[n2])\n\n\n  #print(G.edges(data=True))\n```\n\n    Edge (0, 31) has properties: {'edge_type': 'e2'}\n    Node 0 has properties: {'club': 'Mr. Hi', 'node_type': 'n0', 'node_label': 0, 'node_feature': tensor([1., 1., 1., 1., 1.])}\n    Node 31 has properties: {'club': 'Officer', 'node_type': 'n1', 'node_label': 1, 'node_feature': tensor([1., 1., 1., 1., 1.])}\n\n\n## Heterogeneous Graph Visualization\n\nNow we can visualize the Heterogeneous Graph we have generated.\n\n\n```python\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  \n  # Prepare to save colors\n  edge_color = {}\n\n  for edge in G.edges():\n\n    # Unpacking nodes\n    n1, n2 = edge\n\n    # I commented this line is useless\n    #edge_color[edge] = community_map[n1] if community_map[n1] == community_map[n2] else 2\n    \n    if community_map[n1] == community_map[n2] and community_map[n1] == 0:\n      edge_color[edge] = 'blue'\n\n    elif community_map[n1] == community_map[n2] and community_map[n1] == 1:\n      edge_color[edge] = 'red'\n\n    else:\n      edge_color[edge] = 'green'\n  \n  # Create a copy \n  G_orig = copy.deepcopy(G)\n  \n  # Associate edge_color attribute\n  nx.classes.function.set_edge_attributes(G, edge_color, name='color')\n  \n  # Get the colors\n  colors = nx.get_edge_attributes(G,'color').values()\n  \n  # Get the labels\n  labels = nx.get_node_attributes(G, 'node_type')\n  \n  plt.figure(figsize=(8, 8))\n  nx.draw(G, pos=pos, cmap=plt.get_cmap('coolwarm'), node_color=node_color, edge_color=colors, labels=labels, font_color='white')\n  show()\n```\n\nwhere we differentiate edges within each clubs (2 types) and edges between the two clubs (1 type). Different types of nodes and edges are visualized in different colors. The NetworkX object `G` in following code can be transformed into `deepsnap.hetero_graph.HeteroGraph` directly.\n\n## Transforming to DeepSNAP representation\n\nWe will now work through transforming the NetworkX object `G` into a `deepsnap.hetero_graph.HeteroGraph`.\n\n\n```python\nfrom deepsnap.hetero_graph import HeteroGraph\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  hete = HeteroGraph(G_orig)  # done :) -- this is because we have created the necessary stuff: node_type, node_label, node_features, edge_type\n\n  print(type(hete))\n```\n\n    <class 'deepsnap.hetero_graph.HeteroGraph'>\n\n\n## Question 1.3: How many nodes are of each type (10 Points)\n\n\n\n```python\ndef get_nodes_per_type(hete):\n  # TODO: Implement a function that takes a DeepSNAP dataset object\n  # and return the number of nodes per `node_type`.\n\n  num_nodes_n0 = 0\n  num_nodes_n1 = 0\n\n  ############# Your code here ############\n  ## (~2 line of code)\n  ## Note\n  ## 1. Colab autocomplete functionality might be useful.\n  num_nodes_n0 = hete.num_nodes()['n0']\n  num_nodes_n1 = hete.num_nodes()['n1']\n  pass\n\n  #########################################\n\n  return num_nodes_n0, num_nodes_n1\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  num_nodes_n0, num_nodes_n1 = get_nodes_per_type(hete)\n  print(\"Node type n0 has {} nodes\".format(num_nodes_n0))\n  print(\"Node type n1 has {} nodes\".format(num_nodes_n1))\n```\n\n    Node type n0 has 17 nodes\n    Node type n1 has 17 nodes\n\n\n## Question 1.4: Message Types - How many edges are of each message type (10 Points)\n\nWhen working with heterogenous graphs, as we have discussed before, we now work with heterogenous message types (i.e. different message types for the different `node_type` and `edge_type` combinations). For example, an edge of type `e0` connecting two nodes in club \"Mr. HI\" would have a message type of (`n0`, `e0`, `n0`). In this problem we will analyze how many edges in our graph are of each message type.\n\n**Hint**: If you want to learn more about what the different message types are try the call `hete.message_types`\n\n\n```python\ndef get_num_message_edges(hete):\n  # TODO: Implement this function that takes a DeepSNAP dataset object\n  # and return the number of edges for each message type. \n  # You should return a list of tuples as \n  # (message_type, num_edge)\n\n  message_type_edges = []\n\n  ############# Your code here ############\n  ## (~2 line of code)\n  ## Note\n  ## 1. Colab autocomplete functionality might be useful.\n  message_type_edges = hete.num_edges().items()\n  \n  #########################################\n\n  return message_type_edges\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  message_type_edges = get_num_message_edges(hete)\n  for (message_type, num_edges) in message_type_edges:\n    print(\"Message type {} has {} edges\".format(message_type, num_edges))\n\n  print(hete.message_types)\n```\n\n    Message type ('n0', 'e0', 'n0') has 35 edges\n    Message type ('n0', 'e2', 'n1') has 11 edges\n    Message type ('n1', 'e1', 'n1') has 32 edges\n    [('n0', 'e0', 'n0'), ('n0', 'e2', 'n1'), ('n1', 'e1', 'n1')]\n\n\n## Question 1.5: Dataset Splitting - How many nodes are in each dataset split? (10 Points)\n\nDeepSNAP has built in Dataset creation and splitting methods for heterogeneous graphs. Here we will create train, validation, and test datasets for a node prediction task and inspect the resulting subgraphs. Specifically, write a function that computes the number of nodes with a known label in each dataset split.\n\n\n\n```python\nfrom deepsnap.dataset import GraphDataset\n\ndef compute_dataset_split_counts(datasets):\n  # TODO: Implement a function that takes a dict of datasets in the form\n  # {'train': dataset_train, 'val': dataset_val, 'test': dataset_test}\n  # and returns a dict mapping dataset names to the number of labeled\n  # nodes used for supervision in that respective dataset.  \n  \n  data_set_splits = {}\n\n  ############# Your code here ############\n  ## (~3 line of code)\n  ## Note\n  ## 1. The DeepSNAP `node_label_index` dictionary will be helpful.\n  ## 2. Remember to count both node_types\n  ## 3. Remember each dataset only has one graph that we need to access \n  ##    (i.e. dataset[0])\n  for phase, dataset in datasets.items():\n    \n    num_labels = 0\n\n    # Not pythonic, but..\n    for value in dataset[0].node_label_index.values():\n      num_labels += value.shape[0]\n      \n    data_set_splits[phase] = num_labels\n\n\n\n  #########################################\n\n  return data_set_splits\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n\n  # Create a Dataset from HeteroGraph\n  dataset = GraphDataset([hete], task='node')\n  \n  # Splitting the dataset\n  dataset_train, dataset_val, dataset_test = dataset.split(transductive=True, split_ratio=[0.4, 0.3, 0.3])\n  datasets = {'train': dataset_train, 'val': dataset_val, 'test': dataset_test}\n\n  data_set_splits = compute_dataset_split_counts(datasets)\n  for dataset_name, num_nodes in data_set_splits.items():\n    print(\"{} dataset has {} nodes\".format(dataset_name, num_nodes))\n```\n\n    train dataset has 12 nodes\n    val dataset has 10 nodes\n    test dataset has 12 nodes\n\n\n## DeepSNAP Dataset Visualization\n\nWe can now visualize the different nodes and edges used in each graph dataset split.\n\n\n```python\nfrom deepsnap.dataset import GraphDataset\n\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  dataset = GraphDataset([hete], task='node')\n\n  # Splitting the dataset\n  dataset_train, dataset_val, dataset_test = dataset.split(transductive=True, split_ratio=[0.4, 0.3, 0.3])\n  titles = ['Train', 'Validation', 'Test']\n\n  for i, dataset in enumerate([dataset_train, dataset_val, dataset_test]):\n\n    # We need to re-index the id of the nodes to the original graph, because\n    # the way that the ids of each node type is stored in HeteroGraph starts to \n    # count for each one of the types\n    n0 = hete._convert_to_graph_index(dataset[0].node_label_index['n0'], 'n0').tolist()\n    n1 = hete._convert_to_graph_index(dataset[0].node_label_index['n1'], 'n1').tolist()\n\n    #print(dataset[0].node_label_index['n0'])\n    #print(n0)\n\n    plt.figure(figsize=(7, 7))\n    plt.title(titles[i])\n    \n    nx.draw(G_orig, pos=pos, node_color=\"grey\", edge_color=colors, labels=labels, font_color='white')\n    nx.draw_networkx_nodes(G_orig.subgraph(n0), pos=pos, node_color=\"blue\")\n    nx.draw_networkx_nodes(G_orig.subgraph(n1), pos=pos, node_color=\"red\")\n\n    show()\n```\n\n# 2) Heterogeneous Graph Node Property Prediction\n\nNow, we will use PyTorch Geometric and DeepSNAP to implement a GNN model for heterogeneous graph node property prediction (node classification). We will draw upon our understanding of heterogeneous graphs from lecture and previous work in implementing GNN layers using PyG (introduced in Colab 3).\n\nFirst let's take a look at the general structure of a heterogeneous GNN layer by working through an example:\n\nLet's assume we have a graph $G$, which contains two node types $a$ and $b$, and three message types $m_1=(a, r_1, a)$, $m_2=(a, r_2, b)$ and $m_3=(a, r_3, b)$. Note: during message passing we view each message as (src, relation, dst), where messages \"flow\" from src to dst node types. For example, during message passing, updating node type $b$ relies on two different message types $m_2$ and $m_3$.\n\nWhen applying message passing in heterogenous graphs, we seperately apply message passing over each message type. Therefore, for the graph $G$, a heterogeneous GNN layer contains three seperate Heterogeneous Message Passing layers (`HeteroGNNConv` in this Colab), where each `HeteroGNNConv` layer performs message passing and aggregation with respect to *only one message type*. Since a message type is viewed as (src, relation, dst) and messages \"flow\" from src to dst, each `HeteroGNNConv` layer only computes embeddings for the *dst* nodes of a given message type. For example, the `HeteroGNNConv` layer for message type $m_2$ outputs updated embedding representations *only* for node's with type b. \n\n---\n\nAn overview of the heterogeneous layer we will create is shown below:\n\n\n\nwhere we highlight the following notation:\n\n- $H_a^{(l)[m_1]}$ is the intermediate matrix of of node embeddings for node type $a$, generated by the $l$th `HeteroGNNConv` layer for message type $m_1$.\n- $H_a^{(l)}$ is the matrix with current embeddings for nodes of type $a$ after the $l$th layer of our Heterogeneous GNN model. Note that these embeddings can rely on one or more intermediate `HeteroGNNConv` layer embeddings(i.e. $H_b^{(l)}$ combines $H_b^{(l)[m_2]}$ and $H_b^{(l)[m_3]}$).\n\nSince each `HeteroGNNConv` is only applied over a single message type, we additionally define a Heterogeneous GNN Wrapper layer (`HeteroGNNWrapperConv`). This wrapper manages and combines the output of each `HeteroGNNConv` layer in order to generate the complete updated node embeddings for each node type in layer $l$ of our model. More specifically, the $l^{th}$ `HeteroGNNWrapperConv` layer takes as input the node embeddings computed for each message type and node type (e.g. $H_b^{(l)[m_2]}$ and $H_b^{(l)[m_3]}$) and aggregates across message types with the same $dst$ node type. The resulting output of the $l^{th}$ `HeteroGNNWrapperConv` layer is the updated embedding matrix $H_i^{(l)}$ for each node type i. \n\nContinuing on our example above, to compute the node embeddings $H_b^{(l)}$ the wrapper layer aggregates output embeddings from the `HeteroGNNConv` layers associated with message types $m_2$ and $m_3$ (i.e. $H_b^{(l)[m_2]}$ and $H_b^{(l)[m_3]}$). \n\n---\n\nWith the `HeteroGNNWrapperConv` module, we can now draw a \"simplified\" heterogeneous layer structure as follows:\n\n<br/>\n<center>\n\n</center>\n<br/>\n\n---\n**NOTE**: \nAs reference, it may be helpful to additionally read through PyG's introduciton to heterogeneous graph representations and buidling heterogeneous GNN models: https://pytorch-geometric.readthedocs.io/en/latest/notes/heterogeneous.html \n\n<font color='red'>Looking ahead, we recommend you implement the heterogeneous GNN model in following steps:</font>\n\n1. Implement `HeteroGNNConv`.\n2. Implement **just** `mean` aggregation within `HeteroGNNWrapperConv`.\n3. Implement `generate_convs`.\n4. Implement the `HeteroGNN` model and the `train` function.\n5. Train the model with `mean` aggregation and test your model to make sure your model has reasonable performance.\n6. Once you are confident in your mean aggregation model, implement `attn` aggregation in `HeteroGNNWrapperConv`.\n7. Train the model with `attn` aggregation and test your model to make sure your model has reasonable performance.\n\nNote: The key point of advice is to work completely through implementing the mean aggregation heterogeneous GNN model before diving into the more difficult attention based model.\n\n## Setup\n\n\n```python\nimport copy\nimport torch\nimport deepsnap\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch_geometric.nn as pyg_nn\n\nfrom sklearn.metrics import f1_score\nfrom deepsnap.hetero_gnn import forward_op\nfrom deepsnap.hetero_graph import HeteroGraph\nfrom torch_sparse import SparseTensor, matmul\n```\n\n## Dataset\n\nYou need to login to your Google account and enter the verification code below.\n\n\n```python\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  from pydrive.auth import GoogleAuth\n  from pydrive.drive import GoogleDrive\n  from google.colab import auth\n  from oauth2client.client import GoogleCredentials\n\n  # Authenticate and create the PyDrive client\n  auth.authenticate_user()\n  gauth = GoogleAuth()\n  gauth.credentials = GoogleCredentials.get_application_default()\n  drive = GoogleDrive(gauth)\n```\n\n\n```python\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  id='1ivlxd6lJMcZ9taS44TMGG72x2V1GeVvk'\n  downloaded = drive.CreateFile({'id': id})\n  downloaded.GetContentFile('acm.pkl')\n```\n\n## Implementing `HeteroGNNConv`\n\nNow let's start working on our own implementation of the heterogeneous message passing layer (`HeteroGNNConv`)! Just as in Colabs 3 and 4, we will implement the layer using PyTorch Geometric. \n\nAt a high level, the `HeteroGNNConv` layer is equivalent to the homogenous GNN layers we implemented in Colab 3, but now applied to an individual heterogeous message type. Moreover, our heterogeneous GNN layer draws directly from the **GraphSAGE** message passing model ([Hamilton et al. (2017)](https://arxiv.org/abs/1706.02216)).\n\nWe begin by defining the `HeteroGNNConv` layer with respect to message type $m$:\n\n\\begin{equation}\nm =(s, r, d)\n\\end{equation}\n\nwhere each message type is a tuple containing three elements: $s$ - the source node type, $r$ - the edge (relation) type, and $d$ - the destination node type. \n\nThe message passing update rule that we implement is very similar to that of GraphSAGE, except we now need to include the node types and the edge relation type. The update rule for message type $m$ is described below:\n\n\\begin{equation}\nh_v^{(l)[m]} = W^{(l)[m]} \\cdot \\text{CONCAT} \\Big( W_d^{(l)[m]} \\cdot h_v^{(l-1)}, W_s^{(l)[m]} \\cdot AGG(\\{h_u^{(l-1)}, \\forall u \\in N_{m}(v) \\})\\Big)\n\\end{equation}\n\nwhere we compute $h_v^{(l)[m]}$, the node embedding representation for node $v$ after `HeteroGNNConv` layer $l$ with respect message type $m$. Further unpacking the forumla we have:\n- $W_s^{(l)[m]}$ - linear transformation matrix for the messages of neighboring source nodes of type $s$ along message type $m$.\n- $W_d^{(l)[m]}$ - linear transformation matrix for the message from the node $v$ itself of type $d$.\n- $W^{(l)[m]}$ - linear transformation matrix for the concatenated messages from neighboring node's and the central node.\n- $h_u^{(l-1)}$ - the hidden embedding representation for node $u$ after the $(l-1)$th `HeteroGNNWrapperConv` layer. Note, that this embedding is not associated with a particular message type (see layer diagrams above). \n- $N_{m}(v)$ - the set of neighbor source nodes $s$ for the node v that we are embedding along message type $m = (s, r, d)$. \n\n**NOTE**: We emphasize that each weight matrix is associated with a specific message type $[m]$ and additionally, the weight matrices applied to node messages are differentiated by node type (i.e. $W_s$ and $W_d$).\n\nLastly, for simplicity, we use mean aggregations for $AGG$ where:\n\n\\begin{equation}\nAGG(\\{h_u^{(l-1)}, \\forall u \\in N_{m}(v) \\}) = \\frac{1}{|N_{m}(v)|} \\sum_{u\\in N_{m}(v)} h_u^{(l-1)}\n\\end{equation}\n\n\n```python\nclass HeteroGNNConv(pyg_nn.MessagePassing):\n\n  def __init__(\n      self,\n      in_channels_src,\n      in_channels_dst,\n      out_channels\n  ):\n      \"\"\"Initializes a heterogeneous graph neural network. \n\n      Arguments\n      ---------\n\n      self : class HeteroGNNConv\n        Instantiation of HeteroGNNConv.\n\n      in_channels_src : int\n        Input dimension for source features.\n\n      in_channels_dsf : int\n        Input dimension for destination features.\n\n      out_channels : int\n        Final feature dimension after GNN layer.\n      \"\"\"  \n\n      # Parentazing\n      super(HeteroGNNConv, self).__init__(aggr=\"mean\")\n\n      # Storing\n      self.in_channels_src = in_channels_src\n      self.in_channels_dst = in_channels_dst\n      self.out_channels = out_channels\n\n      # To simplify implementation, please initialize both self.lin_dst\n      # and self.lin_src out_features to out_channels\n      self.lin_dst = None\n      self.lin_src = None\n\n      self.lin_update = None\n\n      ############# Your code here #############\n      ## (~3 lines of code)\n      ## Note:\n      ## 1. Initialize the 3 linear layers.\n      ## 2. Think through the connection between the mathematical\n      ##    definition of the update rule and torch linear layers!\n\n      # W_d and W_s in the formulation above\n      self.lin_dst = nn.Linear(self.in_channels_dst, self.out_channels)\n      self.lin_src = nn.Linear(self.in_channels_src, self.out_channels)\n\n      # Last linear layer muliply the concatenated vector [out_channels + \n      # out_channels]\n      self.lin_update = nn.Linear(2*self.out_channels, self.out_channels)\n\n      ##########################################\n\n  def forward(\n      self,\n      node_feature_src,\n      node_feature_dst,\n      edge_index,\n      size=None\n  ):\n\n    \"\"\"Implements a heterogeneous GNN layer.\n\n    Parameters\n    ----------\n\n    node_feature_src : tensor of shape (num_nodes_src_type, in_channels_src)\n      Features of source nodes.\n\n    node_feature_src : tensor of shape (num_nodes_dst_type, in_channels_dst)\n      Features of destination nodes.\n\n    edge_index : SparseTensor of shape (num_nodes_src_type, num_nodes_dst_type)\n      Stores adjacency matrix as a sparse matrix.\n\n    size : tuple with shape\n      See: https://github.com/pyg-team/pytorch_geometric/blob/master/torch_geometric/nn/conv/message_passing.py\n\n    Return\n    ------\n\n    out : tensor of shape (num_nodes_dst_type, out_channels)\n      Embedded features of destination nodes.\n\n    \"\"\"\n\n    ############# Your code here #############\n    ## (~1 line of code)\n    ## Note:\n    ## 1. Unlike Colabs 3 and 4, we just need to call self.propagate with \n    ## proper/custom arguments.\n    out = self.propagate(edge_index, node_feature_src=node_feature_src, \n                         node_feature_dst=node_feature_dst, size=size)\n\n    ##########################################\n    return out\n\n  def message_and_aggregate(self, edge_index, node_feature_src):\n    \"\"\"Implements message and aggregation steps of message passing together.\n\n    Parameters\n    ----------\n\n    edge_index : SparseTensor of shape (num_nodes_src_type, num_nodes_dst_type)\n      Stores adjacency matrix as a sparse matrix.\n\n    node_feature_src : tensor of shape (num_nodes_src_type, in_channels_src)\n      Features of source nodes.\n\n    Returns\n    -------\n\n    out : tensor of shape (num_nodes_dst_type, in_channels_src)\n      Aggregated source features (messages) for each destination node.\n\n    \"\"\"\n\n    out = None\n    ############# Your code here #############\n    ## (~1 line of code)\n    ## Note:\n    ## 1. Different from what we implemented in Colabs 3 and 4, we use message_and_aggregate\n    ##    to combine the previously seperate message and aggregate functions. \n    ##    The benefit is that we can avoid materializing x_i and x_j\n    ##    to make the implementation more efficient.\n    ## 2. To implement efficiently, refer to PyG documentation for message_and_aggregate\n    ##    and sparse-matrix multiplication:\n    ##    https://pytorch-geometric.readthedocs.io/en/latest/notes/sparse_tensor.html\n    ## 3. Here edge_index is torch_sparse SparseTensor. Although interesting, you\n    ##    do not need to deeply understand SparseTensor represenations!\n    ## 4. Conceptually, think through how the message passing and aggregation\n    ##    expressed mathematically can be expressed through matrix multiplication.\n    \n    # This is cool, we are multiplying a sparse stored version of the adjacency \n    # matrix directly with the feature vector.. meaning that we do not need to \n    # store the messages to do aggregation; we can do both together and just \n    # store the result of the aggregation\n    out = matmul(edge_index, node_feature_src, reduce='mean')\n\n    ##########################################\n\n    return out\n\n  def update(self, aggr_out, node_feature_dst):\n    \"\"\"Update step of message passing. \n\n    Parameters\n    ----------\n\n    aggr_out : tensor of shape (num_nodes_dst_type, in_channels_src)\n      Aggregated source features (messages) for each destination node.\n    \n    node_feature_src : tensor of shape (num_nodes_dst_type, in_channels_dst)\n      Features of destination nodes.\n    \n    Returns\n    -------\n\n    out : tensor of shape (num_nodes_dst_type, out_channels)\n      Updated features of destination nodes.\n  \n    \"\"\"\n\n\n    ############# Your code here #############\n    ## (~4 lines of code)\n    ## Note:\n    ## 1. The update function is called after message_and_aggregate\n    ## 2. Think through the one-one connection between the mathematical update\n    ##    rule and the 3 linear layers defined in the constructor. \n    \n    # Apply linear layer to self part\n    self_loop = self.lin_dst(node_feature_dst)\n\n    # Apply linear layer to aggr part\n    aggr_out = self.lin_src(aggr_out)\n\n    # Concatenate both vectors\n    cat = torch.cat((self_loop, aggr_out), dim=-1)\n    \n    # Aggregate them together via another linear layer\n    out = self.lin_update(cat) \n    ##########################################\n\n    return out\n```\n\n## Heterogeneous GNN Wrapper Layer\n\nAfter implementing the `HeteroGNNConv` layer for each message type, we need to manage and aggregate the node embedding results (with respect to each message types). Here we will implement two types of message type level aggregation.\n\nThe first one is simply mean aggregation over message types:\n\n\\begin{equation}\nh_v^{(l)} = \\frac{1}{M}\\sum_{m=1}^{M}h_v^{(l)[m]}\n\\end{equation}\n\nwhere node $v$ has node type $d$ and we sum over the $M$ message types that have destination node type $d$. From our original example, for a node v of type $b$ we aggregate v's `HeteroGNNConv` embeddings for message types $m_2$ and $m_3$ (i.e. $h_v^{(l)[m_2]}$ and $h_v^{(l)[m_3]}$).\n\nThe second method we implement is the semantic level attention introduced in **HAN** ([Wang et al. (2019)](https://arxiv.org/abs/1903.07293)). Instead of directly averaging on the message type aggregation results, we use attention to learn which message type result is more important, then aggregate across all the message types. Below are the equations for semantic level attention:\n\n\\begin{equation}\ne_{m} = \\frac{1}{|V_{d}|} \\sum_{v \\in V_{d}} q_{attn}^T \\cdot tanh \\Big( W_{attn}^{(l)} \\cdot h_v^{(l)[m]} + b \\Big)\n\\end{equation}\n\nwhere $m$ is the message type and $d$ refers to the destination node type for that message ($m = (s, r, d)$). Additionally, $V_{d}$ refers to the set of nodes v with type $d$. Lastly, the unormalized attention weight $e_m$ is a scaler computed for each message type $m$. \n\nNext, we can compute the normalized attention weights and update $h_v^{(l)}$:\n\n\\begin{equation}\n\\alpha_{m} = \\frac{\\exp(e_{m})}{\\sum_{m=1}^M \\exp(e_{m})}\n\\end{equation}\n\n\\begin{equation}\nh_v^{(l)} = \\sum_{m=1}^{M} \\alpha_{m} \\cdot h_v^{(l)[m]}\n\\end{equation}\n\n, where we emphasize that $M$ here is the number of message types associated with the destination node type $d$. \n\n**Note**: The implementation of the attention aggregation is tricky and nuanced. We strongly recommend working carefully through the math equations to undersatnd exactly what each notation refers to and how all the pieces fit together. If you can, try to connect the math to our original example, focusing on node type $b$, which depends on two different message types!\n\n**_We've implemented most of this for you but you'll need to initialize self.attn_proj in the initializer_**\n\n\n```python\nclass HeteroGNNWrapperConv(deepsnap.hetero_gnn.HeteroConv):\n\n\n    def __init__(\n        self,\n        convs,\n        args,\n        aggr=\"mean\"\n        ):\n      \n        \"\"\" \n        Initializes a heterogeneous GNN wrapper.\n\n        Parameters\n        ----------\n\n        convs : dict\n          Dictionary where keys are (src, msg, dst) and the values are \n          HeteroGNNConv layers.\n        \n        args : dict \n          Dictionary with additional configurations.\n\n        aggr : str \n          Choice on how to perform the aggreagation over different message types.\n\n        \"\"\"\n        super(HeteroGNNWrapperConv, self).__init__(convs, None)\n        \n        # Store aggregation\n        self.aggr = aggr\n\n        # Map the index and message type\n        self.mapping = {}\n\n        # A numpy array that stores the final attention probability\n\n        # Get required sizes from the args dictionary\n        self.hidden_size = args['hidden_size']\n        self.attn_size = args['attn_size']\n\n        self.alpha = None\n\n        self.attn_proj = None\n\n        if self.aggr == \"attn\":\n            ############# Your code here #############\n            ## (~1 line of code)\n            ## Note:\n            ## 1. Initialize self.attn_proj, where self.attn_proj should include\n            ##    two linear layers. Note, make sure you understand\n            ##    which part of the equation self.attn_proj captures.\n            ## 2. You should use nn.Sequential for self.attn_proj\n            ## 3. nn.Linear and nn.Tanh are useful.\n            ## 4. You can model a weight vector (rather than matrix) by using:\n            ##    nn.Linear(some_size, 1, bias=False).\n            ## 5. The first linear layer should have out_features as args['attn_size']\n            ## 6. You can assume we only have one \"head\" for the attention.\n            ## 7. We recommend you to implement the mean aggregation first. After \n            ##    the mean aggregation works well in the training, then you can \n            ##    implement this part.\n            self.attn_proj = nn.Sequential(\n                nn.Linear(self.hidden_size, self.attn_size, bias=True),  # this is for Wattn h + b\n                nn.Tanh(),  # this is for the non-linear part\n                nn.Linear(self.attn_size, 1, bias=False)  # this is for the qattnT \n            )\n\n            ##########################################\n    \n    def reset_parameters(self):\n        super(HeteroConvWrapper, self).reset_parameters()\n\n        if self.aggr == \"attn\":\n            for layer in self.attn_proj.children():\n                layer.reset_parameters()\n    \n    def forward(self, node_features, edge_indices):\n        \"\"\"Implements hetero GNN wrapper.\n\n        Parameters\n        ----------\n\n        node_features : dict\n          Dictionary where keys are 'node_types' and values are tensors of shape\n          (num_node_type, in_channels_node_type).\n\n        edge_indices : dict\n          Dictionary where keys are 'message types' (src, msg, dst) and values \n          are SparseTensors of shape (num_nodes_src_type, num_nodes_dst_type).\n\n        Returns\n        ------- \n\n        node_emb : dict\n          Dictionary where keys are 'node_types' and values are tensors of shape\n          (num_node_type, out_channels).\n\n        \"\"\"\n        # Prepare to store the embedding for each message type\n        message_type_emb = {}\n        \n        # Go through all message types and their adjacency matrices\n        for message_key, message_type in edge_indices.items():\n\n            # Extract current message type\n            src_type, edge_type, dst_type = message_key\n\n            # Get tensors with features according to the node type\n            node_feature_src = node_features[src_type]\n            node_feature_dst = node_features[dst_type]\n            \n            # Get current adjacency matrix\n            edge_index = edge_indices[message_key]\n\n            # Store embedding of the message after passing through a Hetero \n            # GNN layer for example\n            message_type_emb[message_key] = (\n                self.convs[message_key](\n                    node_feature_src,\n                    node_feature_dst,\n                    edge_index,\n                )\n            )\n\n        # We now need to aggregate the information through messages\n      \n        # Initialize a dictionary where keys are node types (strings) of \n        # destination nodes\n        node_emb = {dst: [] for _, _, dst in message_type_emb.keys()}\n      \n        # Initialize another dictionary to figure out mapping\n        mapping = {}        \n        \n        # Go through all message types \n        for (src, edge_type, dst), item in message_type_emb.items():\n\n            # Create an index 0, 1,.. based on the number of times that the \n            # particular node type was a destination node\n            mapping[len(node_emb[dst])] = (src, edge_type, dst)\n            \n            # Store in the node_emb disctionary a list of tensors with the \n            # embeddings\n            node_emb[dst].append(item)\n\n        # Store mapping\n        self.mapping = mapping\n        \n        # Perform aggregation. Recall that:\n        #   node_type is a dict where keys are node types and values are a list\n        #   of tensors containing the embeddings\n        #   embs is a list of tensors for each message where the node type was\n        #   the destination\n        for node_type, embs in node_emb.items():\n            if len(embs) == 1:\n                node_emb[node_type] = embs[0]\n            else:\n                node_emb[node_type] = self.aggregate(embs)\n        \n        return node_emb\n    \n    def aggregate(self, xs):\n        \"\"\"\n        Aggregate results of message passings occuring in parallel for a node \n        type that plays as a dst node more than once in (src, msg, dst) \n        combinations.\n\n        Parameters\n        ----------\n\n        xs : list   \n          List of tensors of shape [num_node_type, out_channels].\n\n        Returns\n        -------\n\n        out : tensor of shape (num_node_type, out_channels)\n          Aggregated embeddings.\n\n        \"\"\"\n\n        # TODO: Implement this function that aggregates all message type results.\n        # Here, xs is a list of tensors (embeddings) with respect to message \n        # type aggregation results.\n\n        if self.aggr == \"mean\":\n\n            ############# Your code here #############\n            ## (~2 lines of code)\n            ## Note:\n            ## 1. Explore the function parameter `xs`! \n            out = torch.mean(torch.cat(xs), dim=0)\n            \n            ##########################################\n\n            return out \n\n        elif self.aggr == \"attn\":\n\n            # Number of nodes for that node type\n            N = xs[0].shape[0] \n\n            # Number of message types for that node type\n            M = len(xs) \n\n            # Concatenate the list of tensors over M\n            x = torch.cat(xs, dim=0).view(M, N, -1) # shape of (M, N, D)\n            \n            # Apply attention layer over x\n            z = self.attn_proj(x).view(M, N) # shape of (M, N, 1)\n            \n            # Take the average over N -- all the nodes with same type\n            z = z.mean(1) # shape of (M, 1) -- this is in fact denoted as e_m above\n\n            # Normalize using softmax\n            alpha = torch.softmax(z, dim=0) # shape of (M, 1)\n\n            # Store the attention result to self.alpha as np array\n            self.alpha = alpha.view(-1).data.cpu().numpy()\n  \n            # Add a third dimension to perform multiplication with x\n            alpha = alpha.view(M, 1, 1)\n\n            # Compute weigthed version of the feature vector\n            x = x * alpha\n\n            # Weighted average\n            out = x.sum(dim=0)\n\n            return out\n```\n\n## Initialize Heterogeneous GNN Layers\n\nNow let's put it all together and initialize the Heterogeneous GNN Layers. Different from the homogeneous graph case, heterogeneous graphs can be a little bit complex.\n\nIn general, we need to create a dictionary of `HeteroGNNConv` layers where the keys are message types.\n\n* To get all message types, `deepsnap.hetero_graph.HeteroGraph.message_types` is useful.\n* If we are initializing the first conv layers, we need to get the feature dimension of each node type. Using `deepsnap.hetero_graph.HeteroGraph.num_node_features(node_type)` will return the node feature dimension of `node_type`. In this function, we will set each `HeteroGNNConv` `out_channels` to be `hidden_size`.\n* If we are not initializing the first conv layers, all node types will have the smae embedding dimension `hidden_size` and we still set `HeteroGNNConv` `out_channels` to be `hidden_size` for simplicity.\n\n\n\n\n```python\ndef generate_convs(hetero_graph, conv, hidden_size, first_layer=False):\n    \"\"\"\n    Creates a conv layer for each message type in the hetero_graph.\n\n    Parameters\n    ----------\n\n    hetero_graph : class HeteroGraph\n      Heterogeneous graph.\n\n    conv : class\n      Some layer that we want to apply over each message type. In our case, we\n      want to apply HeteroGNNConv.\n\n    hidden_size : int\n      Size of the hiddent layer.\n    \n    first_layer : bool\n      First layer needs to consider the input feature dimensions.\n\n    Returns\n    -------\n\n    convs : dictionary\n      A dictionary containing a conv layer for each message type in hetero_graph.\n\n    \"\"\"\n    # TODO: Implement this function that returns a dictionary of `HeteroGNNConv` \n    # layers where the keys are message types. `hetero_graph` is deepsnap `HeteroGraph`\n    # object and the `conv` is the `HeteroGNNConv`.\n\n    # Initialize the dictionary\n    convs = {}\n\n    ############# Your code here #############\n    ## (~9 lines of code)\n    ## Note:\n    ## 1. See the hints above!\n    ## 2. conv is of type `HeteroGNNConv`\n\n    # \"To get all message types, deepsnap.hetero_graph.HeteroGraph.message_types \n    # is useful.\"\"\n    message_types = hetero_graph.message_types\n\n    # Go through all message types\n    for (src, edge_type, dst) in message_types:\n\n      # \"If we are initializing the first conv layers, ...\"\n      if first_layer:\n\n        # Extracting feature dimensions\n        in_channels_src = hetero_graph.num_node_features(src)\n        in_channels_dst = hetero_graph.num_node_features(dst)\n\n      else: \n\n        # \"... all node types will have the smae embedding dimension hidden_size\n        # ...\"\n        in_channels_src = in_channels_dst = hidden_size\n\n      # Out_channels will always be the hidden_size\n      out_channels = hidden_size\n\n      # Now we just initialize the conv layer for the respective message type\n      convs[(src, edge_type, dst)] = conv(in_channels_src, in_channels_dst, out_channels)\n      \n    ##########################################\n    \n    return convs\n```\n\n## HeteroGNN\n\nNow we will make a simple HeteroGNN model which contains only two `HeteroGNNWrapperConv` layers.\n\nFor the forward function in `HeteroGNN`, the model is going to be run as following:\n\n$\\text{self.convs1} \\rightarrow \\text{self.bns1} \\rightarrow \\text{self.relus1} \\rightarrow \\text{self.convs2} \\rightarrow \\text{self.bns2} \\rightarrow \\text{self.relus2} \\rightarrow \\text{self.post_mps}$\n\n\n```python\nclass HeteroGNN(torch.nn.Module):\n\n  def __init__(self, hetero_graph, args, aggr=\"mean\"):\n    \"\"\"Initializes our HeteroGNN model.\n\n    Parameters\n    ----------\n\n    hetero_graph : class HeteroGraph\n      Heterogeneous graph.\n\n    args : dict \n      Dictionary with additional configurations.\n\n    aggr : str \n      Choice on how to perform the aggreagation over different message types.\n\n    \"\"\"\n    super(HeteroGNN, self).__init__()\n\n    self.aggr = aggr\n    self.hidden_size = args['hidden_size']\n\n    self.convs1 = None  # in_channels to hidden\n    self.convs2 = None  # hidden to hidden\n\n    self.bns1 = nn.ModuleDict() \n    self.bns2 = nn.ModuleDict() \n\n    self.relus1 = nn.ModuleDict() \n    self.relus2 = nn.ModuleDict() \n    \n    self.post_mps = nn.ModuleDict() \n\n    ############# Your code here #############\n    ## (~10 lines of code)\n    ## Note:\n    ## 1. For self.convs1 and self.convs2, call generate_convs at first and then\n    ##    pass the returned dictionary of `HeteroGNNConv` to `HeteroGNNWrapperConv`.\n    ## 2. For self.bns, self.relus and self.post_mps, the keys are node_types.\n    ##    `deepsnap.hetero_graph.HeteroGraph.node_types` will be helpful.\n    ## 3. Initialize all batchnorms to torch.nn.BatchNorm1d(hidden_size, eps=1).\n    ## 4. Initialize all relus to nn.LeakyReLU().\n    ## 5. For self.post_mps, each value in the ModuleDict is a linear layer \n    ##    where the `out_features` is the number of classes for that node type.\n    ##    `deepsnap.hetero_graph.HeteroGraph.num_node_labels(node_type)` will be\n    ##    useful.\n\n    # 1. For self.convs1 and self.convs2, call generate_convs at first and then\n    #    pass the returned dictionary of `HeteroGNNConv` to `HeteroGNNWrapperConv`.\n    convs1 = generate_convs(hetero_graph, HeteroGNNConv, self.hidden_size, first_layer=True)\n    convs2 = generate_convs(hetero_graph, HeteroGNNConv, self.hidden_size, first_layer=False)\n\n    self.convs1 = HeteroGNNWrapperConv(convs1, args, self.aggr)\n    self.convs2 = HeteroGNNWrapperConv(convs2, args, self.aggr)\n\n    # 2. For self.bns, self.relus and self.post_mps, the keys are node_types.\n    #   `deepsnap.hetero_graph.HeteroGraph.node_types` will be helpful.\n\n    # We need to create a dictionary (nn.ModuleDict) that contains a hidden \n    # layer of the chosen type for each node type\n    for node_type in hetero_graph.node_types:\n\n      # 3. Initialize all batchnorms to torch.nn.BatchNorm1d(hidden_size, eps=1).\n      self.bns1[node_type] = torch.nn.BatchNorm1d(self.hidden_size, eps=1)\n      self.bns2[node_type] = torch.nn.BatchNorm1d(self.hidden_size, eps=1)\n\n      # 4. Initialize all relus to nn.LeakyReLU().\n      self.relus1[node_type] = nn.LeakyReLU()\n      self.relus2[node_type] = nn.LeakyReLU()\n\n      # 5. For self.post_mps, each value in the ModuleDict is a linear layer \n      #    where the `out_features` is the number of classes for that node type.\n      #    `deepsnap.hetero_graph.HeteroGraph.num_node_labels(node_type)` will be\n      #    useful.\n      self.post_mps[node_type] = nn.Linear(in_features=self.hidden_size, out_features=hetero_graph.num_node_labels(node_type))\n\n        ##########################################\n\n  def forward(self, node_features, edge_indices):\n      \"\"\"Implements our HeteroGNN model.\n\n      Parameters\n      ----------\n        node_features : dict\n          Dictionary where keys are 'node_types' and values are tensors of shape\n          (num_node_type, in_channels_node_type). \n\n        edge_indices : dict\n          Dictionary where keys are 'message types' (src, msg, dst) and values \n          are SparseTensors of shape (num_nodes_src_type, num_nodes_dst_type).\n\n      Returns\n      -------\n        x : dict \n        Dictionary where keys are 'node_types' and values are tensors of shape\n        (num_node_type, out_channels). \n\n      \"\"\"\n      # TODO: Implement the forward function. Notice that `node_feature` is \n      # a dictionary of tensors where keys are node types and values are \n      # corresponding feature tensors. The `edge_index` is a dictionary of \n      # tensors where keys are message types and values are corresponding\n      # edge index tensors (with respect to each message type).\n\n      x = node_features\n\n      ############# Your code here #############\n      ## (~7 lines of code)\n      ## Note:\n      ## 1. `deepsnap.hetero_gnn.forward_op` can be helpful.\n\n      # See: https://snap.stanford.edu/deepsnap/modules/hetero_gnn.html?highlight=forward_op#deepsnap.hetero_gnn.forward_op\n      x = self.convs1(x, edge_indices)\n\n      # Since some layers are only dependent on the node type, irrespective \n      # of the message, we need to apply them over all possible messages. \n      # forward_op does that for us. If we did not had this function, we should \n      # a generate function as generate_convs for each layer.\n\n      x = forward_op(x, self.bns1)\n      x = forward_op(x, self.relus1)\n\n      x = self.convs2(x, edge_indices)\n\n      x = forward_op(x, self.bns2)\n      x = forward_op(x, self.relus2)\n\n      x = forward_op(x, self.post_mps)\n\n      ##########################################\n    \n      return x\n\n  def loss(self, preds, y, train_idx):\n    \"\"\"\n    Compute loss. \n\n    Parameters\n    ----------\n\n    self : HeteroGNN class\n      Instantiation of HeretoGNN.\n\n    preds : dict \n      Dictionary of predicted labels keyed by node type.\n              preds[node_type] = model_predictions\n      model_predictions has shape (num_nodes_node_type, num_node_labels_node_type)\n      because of the post_mps layer\n\n    y : dict\n      Dictionary of true labels keyed by node type.\n\n    train_idx : dict\n      Dictionary of indices keyed by node type, containing the mask of nodes\n      used for training.\n\n    Returns\n    -------\n\n    loss : float\n      Sum of the losses over all node types.\n\n    \"\"\"\n    loss = 0\n    loss_func = F.cross_entropy\n    \n    ############# Your code here #############\n    ## (~3 lines of code)\n    ## Note:\n    ## 1. For each node type in preds, accumulate computed loss to `loss`\n    ## 2. Loss need to be computed with respect to the given index\n    ## 3. preds is a dictionary of model predictions keyed by node_type.\n    ## 4. indeces is a dictionary of labeled supervision nodes keyed\n    ##    by node_type\n\n    # 1. For each node type in preds, accumulate computed loss to `loss`\n    for node_type in preds:\n        \n      # We need to get the training indexes of the nodes\n      idx = train_idx[node_type]\n\n      # Compute loss\n      loss += loss_func(preds[node_type][idx], y[node_type][idx])\n\n    ##########################################\n\n    return loss\n```\n\n## Training and Testing\n\nHere we provide you with the functions to train and test. You only need to implement one line of code here.\n\n**Please do not modify other parts in `train` and `test` for grading purposes.**\n\n\n```python\nimport pandas as pd\n\ndef train(model, optimizer, hetero_hetero_graph, train_idx):\n    \"\"\"Call training of the model. \n\n    Parameters\n    ----------\n\n    model : class torch.nn.Module\n      Our model.\n\n    optimizer : class torch.optim\n      Our optimizer.\n    \n    hetero_graph : class HeteroGraph\n      Our graph.\n\n    train_idx : dict\n      Dictionary keyed by node types containing the indexes of the nodes used for\n      training.\n\n    Return\n    ------\n    loss : float\n      Loss aggregated over all node types.\n\n    \"\"\"\n    \n    # Instantiate training\n    model.train()\n\n    # Zero grads\n    optimizer.zero_grad()\n    \n    # Training phase\n    preds = model(hetero_graph.node_feature, hetero_graph.edge_index)\n\n    # Initialize loss\n    loss = None\n\n    ############# Your code here #############\n    ## Note:\n    ## 1. Compute the loss here\n    ## 2. `deepsnap.hetero_graph.HeteroGraph.node_label` is useful\n    loss = model.loss(preds, hetero_graph.node_label, train_idx)\n\n    ##########################################\n\n    loss.backward()\n    optimizer.step()\n\n    return loss.item()\n\ndef test(model, hetero_graph, indices, best_model=None, best_val=0, save_preds=False, agg_type=None):\n    \"\"\"Test our model.\n\n    Parameters \n    ----------\n\n    model : class torch.nn.Module\n      Our model.\n    \n    hetero_graph : class HeteroGraph\n      Our hetero_graph.\n    \n    indices : list\n      List cointaing the indexes of each phase [train, validation, test]\n\n    best_model : class torch.nn.Module\n      Best model based on best validation.\n\n    best_val : float\n      Best validation metric.\n    \n    save_preds : bool\n      Save or not the predictions.\n    \n    agg_type : str\n      String with the aggreagation type used during wrapping.\n\n    Returns\n    -------\n\n    accs : list\n      List of tuples. 0, 1 ,2 stards for test, val, train; tuple is (micro, macro);\n\n    best_model : class torch.nn.Module\n      Best model based on best validation.\n\n    best_val : float\n      Best validation metric.\n\n    \"\"\"\n    model.eval()\n\n    # Get predictions\n    preds = model(hetero_graph.node_feature, hetero_graph.edge_index)\n\n    # Prepare to save accuracies\n    accs = []\n\n    # Go through each phase \n    for i, index in enumerate(indices):\n        \n        # preds = model(hetero_graph.node_feature, hetero_graph.edge_index) # I placed this outside, no reason why this is here\n\n        num_node_types = 0\n        micro = 0\n        macro = 0\n        \n        for node_type in preds:\n            idx = index[node_type]\n            pred = preds[node_type][idx]\n            pred = pred.max(1)[1]\n            label_np = hetero_graph.node_label[node_type][idx].cpu().numpy()\n            pred_np = pred.cpu().numpy()\n            micro = f1_score(label_np, pred_np, average='micro')\n            macro = f1_score(label_np, pred_np, average='macro')\n            num_node_types += 1\n                  \n        # Averaging f1 score might not make sense, but in our example we only\n        # have one node type\n        micro /= num_node_types\n        macro /= num_node_types\n        accs.append((micro, macro))\n\n        # Only save the test set predictions and labels!\n        if save_preds and i == 2:\n          print (\"Saving Heterogeneous Node Prediction Model Predictions with Agg:\", agg_type)\n          print()\n\n          data = {}\n          data['pred'] = pred_np\n          data['label'] = label_np\n\n          df = pd.DataFrame(data=data)\n          # Save locally as csv\n          df.to_csv('ACM-Node-' + agg_type + 'Agg.csv', sep=',', index=False)\n\n    if accs[1][0] > best_val:\n        best_val = accs[1][0]\n        best_model = copy.deepcopy(model)\n    return accs, best_model, best_val\n```\n\n\n```python\n# Please do not change the following parameters\nargs = {\n    'device': torch.device('cuda' if torch.cuda.is_available() else 'cpu'),\n    'hidden_size': 64,\n    'epochs': 500,\n    'weight_decay': 1e-5,\n    'lr': 0.003,\n    'attn_size': 32,\n}\n```\n\n## Dataset and Preprocessing\n\nIn the next, we will load the data and create a tensor backend (without a NetworkX graph) `deepsnap.hetero_graph.HeteroGraph` object.\n\nWe will use the `ACM(3025)` dataset in our node property prediction task, which is proposed in **HAN** ([Wang et al. (2019)](https://arxiv.org/abs/1903.07293)) and our dataset is extracted from [DGL](https://www.dgl.ai/)'s [ACM.mat](https://data.dgl.ai/dataset/ACM.mat).\n\nThe original ACM dataset has three node types and two edge (relation) types. For simplicity, we simplify the heterogeneous graph to one node type and two edge types (shown below). This means that in our heterogeneous graph, we have one node type (paper) and two message types (paper, author, paper) and (paper, subject, paper).\n\n<br/>\n<center>\n\n</center>\n\n\n```python\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n\n  print(\"Device: {}\".format(args['device']))\n\n  # Load the data\n  data = torch.load(\"acm.pkl\")\n\n  # Message types\n  message_type_1 = (\"paper\", \"author\", \"paper\")\n  message_type_2 = (\"paper\", \"subject\", \"paper\")\n\n  # Dictionary of edge indices\n  edge_index = {}\n  edge_index[message_type_1] = data['pap']\n  edge_index[message_type_2] = data['psp']\n\n  # Dictionary of node features\n  node_feature = {}\n  node_feature[\"paper\"] = data['feature']\n\n  # Dictionary of node labels\n  node_label = {}\n  node_label[\"paper\"] = data['label']\n\n  # Load the train, validation and test indices\n  train_idx = {\"paper\": data['train_idx'].to(args['device'])}\n  val_idx = {\"paper\": data['val_idx'].to(args['device'])}\n  test_idx = {\"paper\": data['test_idx'].to(args['device'])}\n\n  # Construct a deepsnap tensor backend HeteroGraph\n  hetero_graph = HeteroGraph(\n      node_feature=node_feature,\n      node_label=node_label,\n      edge_index=edge_index,\n      directed=True\n  )\n\n  print(f\"ACM heterogeneous graph: {hetero_graph.num_nodes()} nodes, {hetero_graph.num_edges()} edges\")\n\n  # Node feature and node label to device\n  for key in hetero_graph.node_feature:\n      hetero_graph.node_feature[key] = hetero_graph.node_feature[key].to(args['device'])\n  for key in hetero_graph.node_label:\n      hetero_graph.node_label[key] = hetero_graph.node_label[key].to(args['device'])\n\n  # Edge_index to sparse tensor and to device\n  for key in hetero_graph.edge_index:\n      edge_index = hetero_graph.edge_index[key]\n      adj = SparseTensor(row=edge_index[0], col=edge_index[1], sparse_sizes=(hetero_graph.num_nodes('paper'), hetero_graph.num_nodes('paper')))\n      hetero_graph.edge_index[key] = adj.t().to(args['device'])\n\n  print(\"Message Type 1:\")    \n  print(hetero_graph.edge_index[message_type_1])\n  print()\n  print(\"Message Type 2:\")\n  print(hetero_graph.edge_index[message_type_2])\n```\n\n    Device: cpu\n    ACM heterogeneous graph: {'paper': 3025} nodes, {('paper', 'author', 'paper'): 26256, ('paper', 'subject', 'paper'): 2207736} edges\n    Message Type 1:\n    SparseTensor(row=tensor([   0,    0,    0,  ..., 3024, 3024, 3024]),\n                 col=tensor([   8,   20,   51,  ..., 2948, 2983, 2991]),\n                 size=(3025, 3025), nnz=26256, density=0.29%)\n    \n    Message Type 2:\n    SparseTensor(row=tensor([   0,    0,    0,  ..., 3024, 3024, 3024]),\n                 col=tensor([  75,  434,  534,  ..., 3020, 3021, 3022]),\n                 size=(3025, 3025), nnz=2207736, density=24.13%)\n\n\n## Start Training!\n\nNow lets start training!\n\n## Training the Mean Aggregation\n\n\n```python\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  best_model = None\n  best_val = 0\n\n  model = HeteroGNN(hetero_graph, args, aggr=\"mean\").to(args['device'])\n  optimizer = torch.optim.Adam(model.parameters(), lr=args['lr'], weight_decay=args['weight_decay'])\n\n  for epoch in range(args['epochs']):\n      loss = train(model, optimizer, hetero_graph, train_idx)\n      accs, best_model, best_val = test(model, hetero_graph, [train_idx, val_idx, test_idx], best_model, best_val)\n      print(\n          f\"Epoch {epoch + 1}: loss {round(loss, 5)}, \"\n          f\"train micro {round(accs[0][0] * 100, 2)}%, train macro {round(accs[0][1] * 100, 2)}%, \"\n          f\"valid micro {round(accs[1][0] * 100, 2)}%, valid macro {round(accs[1][1] * 100, 2)}%, \"\n          f\"test micro {round(accs[2][0] * 100, 2)}%, test macro {round(accs[2][1] * 100, 2)}%\"\n      )\n  best_accs, _, _ = test(best_model, hetero_graph, [train_idx, val_idx, test_idx])\n  print(\n      f\"Best model: \"\n      f\"train micro {round(best_accs[0][0] * 100, 2)}%, train macro {round(best_accs[0][1] * 100, 2)}%, \"\n      f\"valid micro {round(best_accs[1][0] * 100, 2)}%, valid macro {round(best_accs[1][1] * 100, 2)}%, \"\n      f\"test micro {round(best_accs[2][0] * 100, 2)}%, test macro {round(best_accs[2][1] * 100, 2)}%\"\n  )\n```\n\n    Epoch 1: loss 1.09996, train micro 33.33%, train macro 16.67%, valid micro 33.33%, valid macro 16.67%, test micro 31.29%, test macro 15.89%\n    Epoch 2: loss 1.09203, train micro 57.83%, train macro 48.66%, valid micro 53.33%, valid macro 44.61%, test micro 50.59%, test macro 41.47%\n    Epoch 3: loss 1.06677, train micro 66.5%, train macro 53.62%, valid micro 65.67%, valid macro 52.71%, test micro 65.46%, test macro 53.44%\n    Epoch 4: loss 1.01573, train micro 66.67%, train macro 56.4%, valid micro 64.33%, valid macro 53.62%, test micro 64.28%, test macro 53.84%\n    Epoch 5: loss 0.92693, train micro 65.67%, train macro 56.13%, valid micro 64.0%, valid macro 54.07%, test micro 63.67%, test macro 53.48%\n    Epoch 6: loss 0.79406, train micro 66.5%, train macro 57.74%, valid micro 64.0%, valid macro 54.07%, test micro 63.86%, test macro 53.7%\n    Epoch 7: loss 0.62822, train micro 68.17%, train macro 59.61%, valid micro 65.0%, valid macro 55.74%, test micro 64.38%, test macro 54.07%\n    Epoch 8: loss 0.46084, train micro 69.33%, train macro 61.55%, valid micro 67.0%, valid macro 58.12%, test micro 64.85%, test macro 54.41%\n    Epoch 9: loss 0.32139, train micro 71.83%, train macro 65.76%, valid micro 70.33%, valid macro 63.38%, test micro 65.88%, test macro 55.49%\n    Epoch 10: loss 0.21974, train micro 76.83%, train macro 73.48%, valid micro 74.0%, valid macro 69.74%, test micro 66.64%, test macro 56.8%\n    Epoch 11: loss 0.15064, train micro 82.67%, train macro 81.11%, valid micro 82.33%, valid macro 81.0%, test micro 68.47%, test macro 60.2%\n    Epoch 12: loss 0.10394, train micro 90.83%, train macro 90.44%, valid micro 87.0%, valid macro 86.35%, test micro 71.01%, test macro 64.55%\n    Epoch 13: loss 0.07211, train micro 94.5%, train macro 94.37%, valid micro 89.67%, valid macro 89.18%, test micro 73.18%, test macro 68.0%\n    Epoch 14: loss 0.05103, train micro 95.67%, train macro 95.6%, valid micro 90.67%, valid macro 90.33%, test micro 74.45%, test macro 70.33%\n    Epoch 15: loss 0.0379, train micro 96.67%, train macro 96.64%, valid micro 91.67%, valid macro 91.47%, test micro 75.29%, test macro 71.91%\n    Epoch 16: loss 0.02955, train micro 97.83%, train macro 97.83%, valid micro 92.33%, valid macro 92.25%, test micro 75.72%, test macro 72.94%\n    Epoch 17: loss 0.024, train micro 98.67%, train macro 98.66%, valid micro 92.67%, valid macro 92.64%, test micro 75.91%, test macro 73.52%\n    Epoch 18: loss 0.02027, train micro 99.0%, train macro 99.0%, valid micro 93.33%, valid macro 93.32%, test micro 76.61%, test macro 74.55%\n    Epoch 19: loss 0.01751, train micro 99.0%, train macro 99.0%, valid micro 94.33%, valid macro 94.33%, test micro 77.46%, test macro 75.67%\n    Epoch 20: loss 0.01523, train micro 99.5%, train macro 99.5%, valid micro 95.0%, valid macro 95.0%, test micro 78.21%, test macro 76.54%\n    Epoch 21: loss 0.01327, train micro 99.67%, train macro 99.67%, valid micro 95.67%, valid macro 95.66%, test micro 78.96%, test macro 77.44%\n    Epoch 22: loss 0.01156, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.98%, test micro 79.76%, test macro 78.26%\n    Epoch 23: loss 0.01008, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.97%, test micro 80.47%, test macro 79.05%\n    Epoch 24: loss 0.00877, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.97%, test micro 81.22%, test macro 79.86%\n    Epoch 25: loss 0.00766, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.65%, test micro 81.6%, test macro 80.31%\n    Epoch 26: loss 0.00676, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.65%, test micro 81.79%, test macro 80.59%\n    Epoch 27: loss 0.006, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.32%, test micro 82.12%, test macro 81.04%\n    Epoch 28: loss 0.00525, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.32%, test micro 82.45%, test macro 81.5%\n    Epoch 29: loss 0.00452, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 96.98%, test micro 82.31%, test macro 81.36%\n    Epoch 30: loss 0.00388, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.32%, test micro 82.59%, test macro 81.7%\n    Epoch 31: loss 0.00333, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.32%, test micro 82.59%, test macro 81.7%\n    Epoch 32: loss 0.00287, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.32%, test micro 82.73%, test macro 81.92%\n    Epoch 33: loss 0.00249, train micro 100.0%, train macro 100.0%, valid micro 97.67%, valid macro 97.66%, test micro 82.73%, test macro 81.95%\n    Epoch 34: loss 0.00217, train micro 100.0%, train macro 100.0%, valid micro 97.67%, valid macro 97.67%, test micro 82.73%, test macro 81.98%\n    Epoch 35: loss 0.00191, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 82.87%, test macro 82.15%\n    Epoch 36: loss 0.0017, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 82.78%, test macro 82.05%\n    Epoch 37: loss 0.00152, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 82.87%, test macro 82.18%\n    Epoch 38: loss 0.00137, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 82.82%, test macro 82.15%\n    Epoch 39: loss 0.00125, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 82.87%, test macro 82.22%\n    Epoch 40: loss 0.00115, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 83.01%, test macro 82.41%\n    Epoch 41: loss 0.00106, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 82.92%, test macro 82.31%\n    Epoch 42: loss 0.00099, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 83.01%, test macro 82.42%\n    Epoch 43: loss 0.00093, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 82.96%, test macro 82.4%\n    Epoch 44: loss 0.00087, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 82.96%, test macro 82.43%\n    Epoch 45: loss 0.00082, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 83.06%, test macro 82.56%\n    Epoch 46: loss 0.00078, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 82.92%, test macro 82.43%\n    Epoch 47: loss 0.00075, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 83.06%, test macro 82.61%\n    Epoch 48: loss 0.00071, train micro 100.0%, train macro 100.0%, valid micro 97.67%, valid macro 97.67%, test micro 83.25%, test macro 82.84%\n    Epoch 49: loss 0.00068, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.33%, test micro 83.29%, test macro 82.9%\n    Epoch 50: loss 0.00066, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.33%, test micro 83.44%, test macro 83.07%\n    Epoch 51: loss 0.00063, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 83.25%, test macro 82.88%\n    Epoch 52: loss 0.00061, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 83.25%, test macro 82.88%\n    Epoch 53: loss 0.00059, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 83.29%, test macro 82.94%\n    Epoch 54: loss 0.00057, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 83.06%, test macro 82.72%\n    Epoch 55: loss 0.00056, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 83.01%, test macro 82.68%\n    Epoch 56: loss 0.00054, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 83.11%, test macro 82.79%\n    Epoch 57: loss 0.00053, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.67%, test micro 83.06%, test macro 82.74%\n    Epoch 58: loss 0.00051, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 83.11%, test macro 82.8%\n    Epoch 59: loss 0.0005, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 83.15%, test macro 82.85%\n    Epoch 60: loss 0.00049, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 83.15%, test macro 82.85%\n    Epoch 61: loss 0.00048, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 83.15%, test macro 82.86%\n    Epoch 62: loss 0.00047, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 83.11%, test macro 82.83%\n    Epoch 63: loss 0.00046, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 83.06%, test macro 82.78%\n    Epoch 64: loss 0.00045, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 83.06%, test macro 82.78%\n    Epoch 65: loss 0.00044, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.96%, test macro 82.7%\n    Epoch 66: loss 0.00043, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.92%, test macro 82.66%\n    Epoch 67: loss 0.00043, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.82%, test macro 82.58%\n    Epoch 68: loss 0.00042, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.78%, test macro 82.54%\n    Epoch 69: loss 0.00041, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.87%, test macro 82.64%\n    Epoch 70: loss 0.00041, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.82%, test macro 82.59%\n    Epoch 71: loss 0.0004, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.96%, test macro 82.74%\n    Epoch 72: loss 0.0004, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.66%, test micro 82.96%, test macro 82.74%\n    Epoch 73: loss 0.00039, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.66%, test micro 82.92%, test macro 82.7%\n    Epoch 74: loss 0.00038, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.82%, test macro 82.6%\n    Epoch 75: loss 0.00038, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.78%, test macro 82.56%\n    Epoch 76: loss 0.00037, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.73%, test macro 82.52%\n    Epoch 77: loss 0.00037, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.78%, test macro 82.57%\n    Epoch 78: loss 0.00037, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.68%, test macro 82.48%\n    Epoch 79: loss 0.00036, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.68%, test macro 82.48%\n    Epoch 80: loss 0.00036, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.73%, test macro 82.54%\n    Epoch 81: loss 0.00035, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.73%, test macro 82.53%\n    Epoch 82: loss 0.00035, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.73%, test macro 82.53%\n    Epoch 83: loss 0.00035, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.73%, test macro 82.53%\n    Epoch 84: loss 0.00034, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.68%, test macro 82.49%\n    Epoch 85: loss 0.00034, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.73%, test macro 82.54%\n    Epoch 86: loss 0.00033, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.73%, test macro 82.54%\n    Epoch 87: loss 0.00033, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.68%, test macro 82.49%\n    Epoch 88: loss 0.00033, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.68%, test macro 82.49%\n    Epoch 89: loss 0.00032, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.64%, test macro 82.44%\n    Epoch 90: loss 0.00032, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.64%, test macro 82.44%\n    Epoch 91: loss 0.00032, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.64%, test macro 82.44%\n    Epoch 92: loss 0.00032, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.59%, test macro 82.39%\n    Epoch 93: loss 0.00031, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.59%, test macro 82.4%\n    Epoch 94: loss 0.00031, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.59%, test macro 82.4%\n    Epoch 95: loss 0.00031, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.59%, test macro 82.41%\n    Epoch 96: loss 0.0003, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.54%, test macro 82.36%\n    Epoch 97: loss 0.0003, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.49%, test macro 82.31%\n    Epoch 98: loss 0.0003, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.49%, test macro 82.31%\n    Epoch 99: loss 0.0003, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.49%, test macro 82.31%\n    Epoch 100: loss 0.00029, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.4%, test macro 82.22%\n    Epoch 101: loss 0.00029, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.4%, test macro 82.22%\n    Epoch 102: loss 0.00029, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.35%, test macro 82.17%\n    Epoch 103: loss 0.00029, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.31%, test macro 82.12%\n    Epoch 104: loss 0.00028, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.31%, test macro 82.12%\n    Epoch 105: loss 0.00028, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.31%, test macro 82.12%\n    Epoch 106: loss 0.00028, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.31%, test macro 82.12%\n    Epoch 107: loss 0.00028, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.31%, test macro 82.12%\n    Epoch 108: loss 0.00027, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.31%, test macro 82.12%\n    Epoch 109: loss 0.00027, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.31%, test macro 82.12%\n    Epoch 110: loss 0.00027, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.31%, test macro 82.13%\n    Epoch 111: loss 0.00027, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.4%, test macro 82.23%\n    Epoch 112: loss 0.00027, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.4%, test macro 82.23%\n    Epoch 113: loss 0.00026, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.4%, test macro 82.23%\n    Epoch 114: loss 0.00026, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.4%, test macro 82.23%\n    Epoch 115: loss 0.00026, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.45%, test macro 82.28%\n    Epoch 116: loss 0.00026, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.45%, test macro 82.28%\n    Epoch 117: loss 0.00026, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.45%, test macro 82.28%\n    Epoch 118: loss 0.00025, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.45%, test macro 82.28%\n    Epoch 119: loss 0.00025, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.45%, test macro 82.28%\n    Epoch 120: loss 0.00025, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.35%, test macro 82.18%\n    Epoch 121: loss 0.00025, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.35%, test macro 82.18%\n    Epoch 122: loss 0.00025, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.35%, test macro 82.18%\n    Epoch 123: loss 0.00024, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.31%, test macro 82.14%\n    Epoch 124: loss 0.00024, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.26%, test macro 82.09%\n    Epoch 125: loss 0.00024, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.26%, test macro 82.09%\n    Epoch 126: loss 0.00024, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.21%, test macro 82.05%\n    Epoch 127: loss 0.00024, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.21%, test macro 82.05%\n    Epoch 128: loss 0.00024, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.16%, test macro 82.0%\n    Epoch 129: loss 0.00023, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.12%, test macro 81.95%\n    Epoch 130: loss 0.00023, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.16%, test macro 82.0%\n    Epoch 131: loss 0.00023, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.16%, test macro 82.0%\n    Epoch 132: loss 0.00023, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.16%, test macro 82.0%\n    Epoch 133: loss 0.00023, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.07%, test macro 81.91%\n    Epoch 134: loss 0.00023, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.07%, test macro 81.91%\n    Epoch 135: loss 0.00022, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.07%, test macro 81.91%\n    Epoch 136: loss 0.00022, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.02%, test macro 81.86%\n    Epoch 137: loss 0.00022, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.02%, test macro 81.86%\n    Epoch 138: loss 0.00022, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 81.88%, test macro 81.71%\n    Epoch 139: loss 0.00022, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 81.88%, test macro 81.71%\n    Epoch 140: loss 0.00022, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 81.88%, test macro 81.71%\n    Epoch 141: loss 0.00022, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 81.88%, test macro 81.71%\n    Epoch 142: loss 0.00021, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 81.88%, test macro 81.71%\n    Epoch 143: loss 0.00021, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 81.88%, test macro 81.71%\n    Epoch 144: loss 0.00021, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.88%, test macro 81.71%\n    Epoch 145: loss 0.00021, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.88%, test macro 81.71%\n    Epoch 146: loss 0.00021, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.88%, test macro 81.71%\n    Epoch 147: loss 0.00021, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.88%, test macro 81.71%\n    Epoch 148: loss 0.00021, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.88%, test macro 81.71%\n    Epoch 149: loss 0.0002, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.88%, test macro 81.71%\n    Epoch 150: loss 0.0002, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.88%, test macro 81.71%\n    Epoch 151: loss 0.0002, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.84%, test macro 81.66%\n    Epoch 152: loss 0.0002, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.88%, test macro 81.7%\n    Epoch 153: loss 0.0002, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.84%, test macro 81.65%\n    Epoch 154: loss 0.0002, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.84%, test macro 81.65%\n    Epoch 155: loss 0.0002, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.84%, test macro 81.65%\n    Epoch 156: loss 0.00019, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.79%, test macro 81.61%\n    Epoch 157: loss 0.00019, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.74%, test macro 81.57%\n    Epoch 158: loss 0.00019, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.69%, test macro 81.52%\n    Epoch 159: loss 0.00019, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.69%, test macro 81.52%\n    Epoch 160: loss 0.00019, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.69%, test macro 81.52%\n    Epoch 161: loss 0.00019, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.69%, test macro 81.52%\n    Epoch 162: loss 0.00019, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.69%, test macro 81.52%\n    Epoch 163: loss 0.00019, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.69%, test macro 81.52%\n    Epoch 164: loss 0.00018, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.69%, test macro 81.52%\n    Epoch 165: loss 0.00018, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.69%, test macro 81.52%\n    Epoch 166: loss 0.00018, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.69%, test macro 81.52%\n    Epoch 167: loss 0.00018, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.69%, test macro 81.51%\n    Epoch 168: loss 0.00018, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.65%, test macro 81.47%\n    Epoch 169: loss 0.00018, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.65%, test macro 81.47%\n    Epoch 170: loss 0.00018, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.65%, test macro 81.47%\n    Epoch 171: loss 0.00018, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.6%, test macro 81.42%\n    Epoch 172: loss 0.00018, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.65%, test macro 81.48%\n    Epoch 173: loss 0.00017, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.69%, test macro 81.52%\n    Epoch 174: loss 0.00017, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.51%, test macro 81.33%\n    Epoch 175: loss 0.00017, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.51%, test macro 81.33%\n    Epoch 176: loss 0.00017, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.55%, test macro 81.38%\n    Epoch 177: loss 0.00017, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.55%, test macro 81.38%\n    Epoch 178: loss 0.00017, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.55%, test macro 81.38%\n    Epoch 179: loss 0.00017, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.51%, test macro 81.34%\n    Epoch 180: loss 0.00017, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.46%, test macro 81.29%\n    Epoch 181: loss 0.00017, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.46%, test macro 81.29%\n    Epoch 182: loss 0.00017, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.46%, test macro 81.29%\n    Epoch 183: loss 0.00016, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.46%, test macro 81.29%\n    Epoch 184: loss 0.00016, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.51%, test macro 81.34%\n    Epoch 185: loss 0.00016, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.51%, test macro 81.34%\n    Epoch 186: loss 0.00016, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.51%, test macro 81.34%\n    Epoch 187: loss 0.00016, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.51%, test macro 81.34%\n    Epoch 188: loss 0.00016, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.51%, test macro 81.34%\n    Epoch 189: loss 0.00016, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.51%, test macro 81.34%\n    Epoch 190: loss 0.00016, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.51%, test macro 81.34%\n    Epoch 191: loss 0.00016, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.51%, test macro 81.34%\n    Epoch 192: loss 0.00016, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.51%, test macro 81.34%\n    Epoch 193: loss 0.00016, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.51%, test macro 81.34%\n    Epoch 194: loss 0.00015, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 81.51%, test macro 81.34%\n    Epoch 195: loss 0.00015, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.55%, test macro 81.39%\n    Epoch 196: loss 0.00015, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.55%, test macro 81.39%\n    Epoch 197: loss 0.00015, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.51%, test macro 81.34%\n    Epoch 198: loss 0.00015, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.51%, test macro 81.34%\n    Epoch 199: loss 0.00015, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.51%, test macro 81.34%\n    Epoch 200: loss 0.00015, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.41%, test macro 81.25%\n    Epoch 201: loss 0.00015, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.41%, test macro 81.26%\n    Epoch 202: loss 0.00015, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.36%, test macro 81.21%\n    Epoch 203: loss 0.00015, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.36%, test macro 81.22%\n    Epoch 204: loss 0.00015, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.36%, test macro 81.22%\n    Epoch 205: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.36%, test macro 81.22%\n    Epoch 206: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.36%, test macro 81.22%\n    Epoch 207: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.36%, test macro 81.22%\n    Epoch 208: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.36%, test macro 81.22%\n    Epoch 209: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.36%, test macro 81.22%\n    Epoch 210: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.36%, test macro 81.22%\n    Epoch 211: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.41%, test macro 81.27%\n    Epoch 212: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.41%, test macro 81.27%\n    Epoch 213: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.41%, test macro 81.27%\n    Epoch 214: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.36%, test macro 81.23%\n    Epoch 215: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.36%, test macro 81.23%\n    Epoch 216: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.36%, test macro 81.23%\n    Epoch 217: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.36%, test macro 81.23%\n    Epoch 218: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.36%, test macro 81.23%\n    Epoch 219: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.36%, test macro 81.23%\n    Epoch 220: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.27%, test macro 81.14%\n    Epoch 221: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.32%, test macro 81.19%\n    Epoch 222: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.27%, test macro 81.14%\n    Epoch 223: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.22%, test macro 81.09%\n    Epoch 224: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.22%, test macro 81.09%\n    Epoch 225: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.27%, test macro 81.14%\n    Epoch 226: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.27%, test macro 81.14%\n    Epoch 227: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.27%, test macro 81.15%\n    Epoch 228: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.27%, test macro 81.15%\n    Epoch 229: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.27%, test macro 81.15%\n    Epoch 230: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.27%, test macro 81.15%\n    Epoch 231: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.22%, test macro 81.1%\n    Epoch 232: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.18%, test macro 81.06%\n    Epoch 233: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.18%, test macro 81.06%\n    Epoch 234: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.18%, test macro 81.06%\n    Epoch 235: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.18%, test macro 81.06%\n    Epoch 236: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.13%, test macro 81.01%\n    Epoch 237: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.08%, test macro 80.96%\n    Epoch 238: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.04%, test macro 80.91%\n    Epoch 239: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.04%, test macro 80.91%\n    Epoch 240: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.04%, test macro 80.91%\n    Epoch 241: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 80.99%, test macro 80.87%\n    Epoch 242: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 80.99%, test macro 80.87%\n    Epoch 243: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 80.99%, test macro 80.87%\n    Epoch 244: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 80.99%, test macro 80.87%\n    Epoch 245: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 80.99%, test macro 80.87%\n    Epoch 246: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 80.99%, test macro 80.87%\n    Epoch 247: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 80.99%, test macro 80.87%\n    Epoch 248: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.04%, test macro 80.92%\n    Epoch 249: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.04%, test macro 80.92%\n    Epoch 250: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.08%, test macro 80.97%\n    Epoch 251: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.04%, test macro 80.92%\n    Epoch 252: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 81.04%, test macro 80.92%\n    Epoch 253: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 80.99%, test macro 80.88%\n    Epoch 254: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 80.99%, test macro 80.88%\n    Epoch 255: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 80.99%, test macro 80.88%\n    Epoch 256: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 80.99%, test macro 80.88%\n    Epoch 257: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 80.94%, test macro 80.83%\n    Epoch 258: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 80.94%, test macro 80.83%\n    Epoch 259: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.67%, test micro 80.94%, test macro 80.83%\n    Epoch 260: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 80.94%, test macro 80.83%\n    Epoch 261: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 80.94%, test macro 80.83%\n    Epoch 262: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 80.94%, test macro 80.83%\n    Epoch 263: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 80.94%, test macro 80.82%\n    Epoch 264: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 80.85%, test macro 80.73%\n    Epoch 265: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 80.75%, test macro 80.64%\n    Epoch 266: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 80.8%, test macro 80.68%\n    Epoch 267: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 80.8%, test macro 80.69%\n    Epoch 268: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 80.85%, test macro 80.73%\n    Epoch 269: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 80.8%, test macro 80.69%\n    Epoch 270: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 80.8%, test macro 80.69%\n    Epoch 271: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 80.8%, test macro 80.69%\n    Epoch 272: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 80.8%, test macro 80.69%\n    Epoch 273: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 80.8%, test macro 80.69%\n    Epoch 274: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 95.99%, test micro 80.8%, test macro 80.69%\n    Epoch 275: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.85%, test macro 80.73%\n    Epoch 276: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.85%, test macro 80.73%\n    Epoch 277: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.8%, test macro 80.69%\n    Epoch 278: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.8%, test macro 80.69%\n    Epoch 279: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.85%, test macro 80.74%\n    Epoch 280: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.89%, test macro 80.78%\n    Epoch 281: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.89%, test macro 80.78%\n    Epoch 282: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.89%, test macro 80.78%\n    Epoch 283: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.8%, test macro 80.7%\n    Epoch 284: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.85%, test macro 80.74%\n    Epoch 285: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.85%, test macro 80.74%\n    Epoch 286: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.85%, test macro 80.74%\n    Epoch 287: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.85%, test macro 80.74%\n    Epoch 288: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.85%, test macro 80.74%\n    Epoch 289: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.8%, test macro 80.69%\n    Epoch 290: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.8%, test macro 80.69%\n    Epoch 291: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.75%, test macro 80.64%\n    Epoch 292: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.75%, test macro 80.64%\n    Epoch 293: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.66%, test macro 80.54%\n    Epoch 294: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.71%, test macro 80.59%\n    Epoch 295: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.71%, test macro 80.59%\n    Epoch 296: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.71%, test macro 80.59%\n    Epoch 297: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.71%, test macro 80.59%\n    Epoch 298: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.66%, test macro 80.54%\n    Epoch 299: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.66%, test macro 80.54%\n    Epoch 300: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.61%, test macro 80.49%\n    Epoch 301: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.66%, test macro 80.53%\n    Epoch 302: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.66%, test macro 80.53%\n    Epoch 303: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.66%, test macro 80.53%\n    Epoch 304: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.66%, test macro 80.53%\n    Epoch 305: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.66%, test macro 80.53%\n    Epoch 306: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.66%, test macro 80.53%\n    Epoch 307: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.66%, test macro 80.53%\n    Epoch 308: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.61%, test macro 80.49%\n    Epoch 309: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.61%, test macro 80.49%\n    Epoch 310: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.56%, test macro 80.45%\n    Epoch 311: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.56%, test macro 80.45%\n    Epoch 312: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.56%, test macro 80.45%\n    Epoch 313: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.52%, test macro 80.41%\n    Epoch 314: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.52%, test macro 80.41%\n    Epoch 315: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.52%, test macro 80.41%\n    Epoch 316: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.52%, test macro 80.41%\n    Epoch 317: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.52%, test macro 80.41%\n    Epoch 318: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.52%, test macro 80.41%\n    Epoch 319: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.56%, test macro 80.45%\n    Epoch 320: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.56%, test macro 80.45%\n    Epoch 321: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.56%, test macro 80.45%\n    Epoch 322: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.56%, test macro 80.45%\n    Epoch 323: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.56%, test macro 80.45%\n    Epoch 324: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.61%, test macro 80.5%\n    Epoch 325: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.61%, test macro 80.5%\n    Epoch 326: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.61%, test macro 80.5%\n    Epoch 327: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.61%, test macro 80.5%\n    Epoch 328: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.61%, test macro 80.5%\n    Epoch 329: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.61%, test macro 80.5%\n    Epoch 330: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.56%, test macro 80.46%\n    Epoch 331: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.61%, test macro 80.5%\n    Epoch 332: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.61%, test macro 80.5%\n    Epoch 333: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.61%, test macro 80.5%\n    Epoch 334: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.61%, test macro 80.5%\n    Epoch 335: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.61%, test macro 80.5%\n    Epoch 336: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.66%, test macro 80.55%\n    Epoch 337: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.66%, test macro 80.55%\n    Epoch 338: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.66%, test macro 80.55%\n    Epoch 339: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.66%, test macro 80.55%\n    Epoch 340: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.71%, test macro 80.59%\n    Epoch 341: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.71%, test macro 80.59%\n    Epoch 342: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.71%, test macro 80.59%\n    Epoch 343: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.71%, test macro 80.58%\n    Epoch 344: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.66%, test micro 80.71%, test macro 80.58%\n    Epoch 345: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.71%, test macro 80.58%\n    Epoch 346: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.71%, test macro 80.58%\n    Epoch 347: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.66%, test macro 80.54%\n    Epoch 348: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.66%, test macro 80.54%\n    Epoch 349: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.66%, test macro 80.55%\n    Epoch 350: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.66%, test macro 80.55%\n    Epoch 351: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.66%, test macro 80.55%\n    Epoch 352: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.66%, test macro 80.55%\n    Epoch 353: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.66%, test macro 80.55%\n    Epoch 354: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.66%, test macro 80.55%\n    Epoch 355: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.66%, test macro 80.55%\n    Epoch 356: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.61%, test macro 80.49%\n    Epoch 357: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.61%, test macro 80.49%\n    Epoch 358: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.61%, test macro 80.49%\n    Epoch 359: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.61%, test macro 80.49%\n    Epoch 360: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.61%, test macro 80.49%\n    Epoch 361: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.66%, test macro 80.54%\n    Epoch 362: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.66%, test macro 80.54%\n    Epoch 363: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.66%, test macro 80.54%\n    Epoch 364: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.71%, test macro 80.59%\n    Epoch 365: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.71%, test macro 80.59%\n    Epoch 366: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.71%, test macro 80.59%\n    Epoch 367: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.66%, test macro 80.54%\n    Epoch 368: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.61%, test macro 80.49%\n    Epoch 369: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.61%, test macro 80.49%\n    Epoch 370: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.61%, test macro 80.49%\n    Epoch 371: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.61%, test macro 80.5%\n    Epoch 372: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.61%, test macro 80.5%\n    Epoch 373: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.61%, test macro 80.5%\n    Epoch 374: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.56%, test macro 80.46%\n    Epoch 375: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.56%, test macro 80.46%\n    Epoch 376: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.56%, test macro 80.46%\n    Epoch 377: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.56%, test macro 80.46%\n    Epoch 378: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.56%, test macro 80.46%\n    Epoch 379: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.56%, test macro 80.46%\n    Epoch 380: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.56%, test macro 80.46%\n    Epoch 381: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.52%, test macro 80.41%\n    Epoch 382: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.52%, test macro 80.41%\n    Epoch 383: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.52%, test macro 80.41%\n    Epoch 384: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.52%, test macro 80.41%\n    Epoch 385: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.56%, test macro 80.45%\n    Epoch 386: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.56%, test macro 80.45%\n    Epoch 387: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.47%, test macro 80.36%\n    Epoch 388: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.47%, test macro 80.36%\n    Epoch 389: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.47%, test macro 80.35%\n    Epoch 390: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.47%, test macro 80.35%\n    Epoch 391: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.42%, test macro 80.3%\n    Epoch 392: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.42%, test macro 80.3%\n    Epoch 393: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.38%, test macro 80.26%\n    Epoch 394: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.38%, test macro 80.26%\n    Epoch 395: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.38%, test macro 80.26%\n    Epoch 396: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.38%, test macro 80.26%\n    Epoch 397: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.38%, test macro 80.26%\n    Epoch 398: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.42%, test macro 80.3%\n    Epoch 399: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.42%, test macro 80.3%\n    Epoch 400: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.42%, test macro 80.3%\n    Epoch 401: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.42%, test macro 80.3%\n    Epoch 402: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.42%, test macro 80.3%\n    Epoch 403: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.42%, test macro 80.3%\n    Epoch 404: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.42%, test macro 80.3%\n    Epoch 405: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.33%, test micro 80.42%, test macro 80.3%\n    Epoch 406: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.0%, valid macro 94.99%, test micro 80.38%, test macro 80.26%\n    Epoch 407: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.0%, valid macro 94.99%, test micro 80.38%, test macro 80.26%\n    Epoch 408: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.0%, valid macro 94.99%, test micro 80.38%, test macro 80.26%\n    Epoch 409: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.0%, valid macro 94.99%, test micro 80.38%, test macro 80.26%\n    Epoch 410: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.0%, valid macro 94.99%, test micro 80.28%, test macro 80.16%\n    Epoch 411: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.0%, valid macro 94.99%, test micro 80.28%, test macro 80.16%\n    Epoch 412: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.0%, valid macro 94.99%, test micro 80.28%, test macro 80.16%\n    Epoch 413: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.0%, valid macro 94.99%, test micro 80.28%, test macro 80.16%\n    Epoch 414: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.0%, valid macro 94.99%, test micro 80.28%, test macro 80.16%\n    Epoch 415: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.0%, valid macro 94.99%, test micro 80.24%, test macro 80.11%\n    Epoch 416: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 95.0%, valid macro 94.99%, test micro 80.19%, test macro 80.06%\n    Epoch 417: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.24%, test macro 80.11%\n    Epoch 418: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.24%, test macro 80.11%\n    Epoch 419: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.24%, test macro 80.11%\n    Epoch 420: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.24%, test macro 80.11%\n    Epoch 421: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.24%, test macro 80.11%\n    Epoch 422: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.24%, test macro 80.11%\n    Epoch 423: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.19%, test macro 80.06%\n    Epoch 424: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.24%, test macro 80.11%\n    Epoch 425: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.19%, test macro 80.07%\n    Epoch 426: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.24%, test macro 80.11%\n    Epoch 427: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.19%, test macro 80.06%\n    Epoch 428: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.19%, test macro 80.06%\n    Epoch 429: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.14%, test macro 80.01%\n    Epoch 430: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.14%, test macro 80.01%\n    Epoch 431: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.14%, test macro 80.01%\n    Epoch 432: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.19%, test macro 80.06%\n    Epoch 433: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.19%, test macro 80.06%\n    Epoch 434: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.14%, test macro 80.01%\n    Epoch 435: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.14%, test macro 80.01%\n    Epoch 436: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.14%, test macro 80.01%\n    Epoch 437: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.14%, test macro 80.01%\n    Epoch 438: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.14%, test macro 80.01%\n    Epoch 439: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.14%, test macro 80.01%\n    Epoch 440: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.14%, test macro 80.01%\n    Epoch 441: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.14%, test macro 80.01%\n    Epoch 442: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.14%, test macro 80.01%\n    Epoch 443: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.09%, test macro 79.97%\n    Epoch 444: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.0%, test macro 79.88%\n    Epoch 445: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.0%, test macro 79.87%\n    Epoch 446: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.0%, test macro 79.87%\n    Epoch 447: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.0%, test macro 79.87%\n    Epoch 448: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.95%, test macro 79.82%\n    Epoch 449: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.0%, test macro 79.87%\n    Epoch 450: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.0%, test macro 79.87%\n    Epoch 451: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.0%, test macro 79.86%\n    Epoch 452: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.0%, test macro 79.86%\n    Epoch 453: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.0%, test macro 79.86%\n    Epoch 454: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 80.0%, test macro 79.86%\n    Epoch 455: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.95%, test macro 79.81%\n    Epoch 456: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.95%, test macro 79.81%\n    Epoch 457: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.91%, test macro 79.77%\n    Epoch 458: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.91%, test macro 79.77%\n    Epoch 459: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.91%, test macro 79.77%\n    Epoch 460: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.91%, test macro 79.77%\n    Epoch 461: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.86%, test macro 79.73%\n    Epoch 462: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.76%, test macro 79.62%\n    Epoch 463: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.81%, test macro 79.67%\n    Epoch 464: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.76%, test macro 79.62%\n    Epoch 465: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.72%, test macro 79.58%\n    Epoch 466: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.67%, test macro 79.52%\n    Epoch 467: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.67%, test macro 79.52%\n    Epoch 468: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.62%, test macro 79.47%\n    Epoch 469: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.62%, test macro 79.47%\n    Epoch 470: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.62%, test macro 79.47%\n    Epoch 471: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.58%, test macro 79.43%\n    Epoch 472: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.58%, test macro 79.43%\n    Epoch 473: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.58%, test macro 79.43%\n    Epoch 474: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.58%, test macro 79.43%\n    Epoch 475: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.58%, test macro 79.43%\n    Epoch 476: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.58%, test macro 79.43%\n    Epoch 477: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.58%, test macro 79.43%\n    Epoch 478: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.58%, test macro 79.42%\n    Epoch 479: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.62%, test macro 79.47%\n    Epoch 480: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.58%, test macro 79.42%\n    Epoch 481: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.48%, test macro 79.33%\n    Epoch 482: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.48%, test macro 79.33%\n    Epoch 483: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.53%, test macro 79.38%\n    Epoch 484: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.48%, test macro 79.34%\n    Epoch 485: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.44%, test macro 79.29%\n    Epoch 486: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.34%, test macro 79.2%\n    Epoch 487: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.34%, test macro 79.2%\n    Epoch 488: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.34%, test macro 79.2%\n    Epoch 489: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.29%, test macro 79.15%\n    Epoch 490: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.25%, test macro 79.1%\n    Epoch 491: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.2%, test macro 79.05%\n    Epoch 492: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.2%, test macro 79.05%\n    Epoch 493: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.2%, test macro 79.05%\n    Epoch 494: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.2%, test macro 79.05%\n    Epoch 495: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.2%, test macro 79.05%\n    Epoch 496: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.11%, test macro 78.96%\n    Epoch 497: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.01%, test macro 78.86%\n    Epoch 498: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.01%, test macro 78.86%\n    Epoch 499: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.01%, test macro 78.86%\n    Epoch 500: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 79.01%, test macro 78.86%\n    Best model: train micro 100.0%, train macro 100.0%, valid micro 97.67%, valid macro 97.66%, test micro 82.73%, test macro 81.95%\n\n\n## Question 2.1: What is your maximum test set **micro** F1 score for the best_model when using mean aggregation? (10 points)\n\n\n## Question 2.2: What is your maximum test set **macro** F1 score for the best_model when using the mean aggregation? (10 points)\n\n\n## Training the Attention Aggregation\n\n\n```python\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  best_model = None\n  best_val = 0\n\n  output_size = hetero_graph.num_node_labels('paper')\n  model = HeteroGNN(hetero_graph, args, aggr=\"attn\").to(args['device'])\n  optimizer = torch.optim.Adam(model.parameters(), lr=args['lr'], weight_decay=args['weight_decay'])\n\n  for epoch in range(args['epochs']):\n      loss = train(model, optimizer, hetero_graph, train_idx)\n      accs, best_model, best_val = test(model, hetero_graph, [train_idx, val_idx, test_idx], best_model, best_val)\n      print(\n          f\"Epoch {epoch + 1}: loss {round(loss, 5)}, \"\n          f\"train micro {round(accs[0][0] * 100, 2)}%, train macro {round(accs[0][1] * 100, 2)}%, \"\n          f\"valid micro {round(accs[1][0] * 100, 2)}%, valid macro {round(accs[1][1] * 100, 2)}%, \"\n          f\"test micro {round(accs[2][0] * 100, 2)}%, test macro {round(accs[2][1] * 100, 2)}%\"\n      )\n  best_accs, _, _ = test(best_model, hetero_graph, [train_idx, val_idx, test_idx], save_preds=True, agg_type=\"Attention\")\n  print(\n      f\"Best model: \"\n      f\"train micro {round(best_accs[0][0] * 100, 2)}%, train macro {round(best_accs[0][1] * 100, 2)}%, \"\n      f\"valid micro {round(best_accs[1][0] * 100, 2)}%, valid macro {round(best_accs[1][1] * 100, 2)}%, \"\n      f\"test micro {round(best_accs[2][0] * 100, 2)}%, test macro {round(best_accs[2][1] * 100, 2)}%\"\n  )\n```\n\n    Epoch 1: loss 1.09888, train micro 33.33%, train macro 16.67%, valid micro 33.33%, valid macro 16.67%, test micro 31.29%, test macro 15.89%\n    Epoch 2: loss 1.08958, train micro 33.33%, train macro 16.67%, valid micro 33.33%, valid macro 16.67%, test micro 31.29%, test macro 15.89%\n    Epoch 3: loss 1.05758, train micro 54.33%, train macro 44.95%, valid micro 55.33%, valid macro 46.27%, test micro 49.18%, test macro 39.67%\n    Epoch 4: loss 0.99157, train micro 66.17%, train macro 54.84%, valid micro 64.67%, valid macro 52.22%, test micro 62.73%, test macro 50.21%\n    Epoch 5: loss 0.87943, train micro 67.67%, train macro 56.55%, valid micro 66.0%, valid macro 53.41%, test micro 64.19%, test macro 51.81%\n    Epoch 6: loss 0.72531, train micro 68.33%, train macro 57.82%, valid micro 66.67%, valid macro 54.6%, test micro 64.47%, test macro 52.23%\n    Epoch 7: loss 0.56074, train micro 69.5%, train macro 60.56%, valid micro 67.0%, valid macro 55.78%, test micro 65.32%, test macro 53.33%\n    Epoch 8: loss 0.41621, train micro 70.83%, train macro 63.16%, valid micro 68.0%, valid macro 57.69%, test micro 65.55%, test macro 53.84%\n    Epoch 9: loss 0.30229, train micro 73.17%, train macro 67.37%, valid micro 69.33%, valid macro 60.54%, test micro 65.84%, test macro 54.55%\n    Epoch 10: loss 0.21979, train micro 78.0%, train macro 74.73%, valid micro 72.67%, valid macro 66.63%, test micro 66.54%, test macro 56.11%\n    Epoch 11: loss 0.16181, train micro 84.33%, train macro 83.0%, valid micro 80.33%, valid macro 77.96%, test micro 67.81%, test macro 58.66%\n    Epoch 12: loss 0.12026, train micro 90.83%, train macro 90.42%, valid micro 85.33%, valid macro 84.2%, test micro 70.21%, test macro 63.26%\n    Epoch 13: loss 0.08934, train micro 94.67%, train macro 94.54%, valid micro 87.67%, valid macro 86.9%, test micro 72.8%, test macro 67.59%\n    Epoch 14: loss 0.06547, train micro 97.0%, train macro 96.96%, valid micro 89.0%, valid macro 88.47%, test micro 74.12%, test macro 69.91%\n    Epoch 15: loss 0.0475, train micro 97.5%, train macro 97.48%, valid micro 89.0%, valid macro 88.54%, test micro 75.06%, test macro 71.49%\n    Epoch 16: loss 0.03503, train micro 98.0%, train macro 97.99%, valid micro 90.33%, valid macro 90.05%, test micro 75.53%, test macro 72.42%\n    Epoch 17: loss 0.02675, train micro 98.17%, train macro 98.16%, valid micro 90.33%, valid macro 90.15%, test micro 75.86%, test macro 73.08%\n    Epoch 18: loss 0.02102, train micro 98.83%, train macro 98.83%, valid micro 91.0%, valid macro 90.9%, test micro 75.95%, test macro 73.4%\n    Epoch 19: loss 0.01665, train micro 98.83%, train macro 98.83%, valid micro 91.0%, valid macro 90.9%, test micro 76.09%, test macro 73.73%\n    Epoch 20: loss 0.01322, train micro 99.17%, train macro 99.17%, valid micro 92.0%, valid macro 91.99%, test micro 76.47%, test macro 74.27%\n    Epoch 21: loss 0.01052, train micro 99.17%, train macro 99.17%, valid micro 93.33%, valid macro 93.36%, test micro 77.04%, test macro 74.96%\n    Epoch 22: loss 0.00845, train micro 99.5%, train macro 99.5%, valid micro 94.0%, valid macro 94.03%, test micro 77.55%, test macro 75.69%\n    Epoch 23: loss 0.00678, train micro 99.67%, train macro 99.67%, valid micro 94.0%, valid macro 94.03%, test micro 78.21%, test macro 76.48%\n    Epoch 24: loss 0.00538, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.68%, test micro 79.06%, test macro 77.48%\n    Epoch 25: loss 0.00426, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.68%, test micro 79.91%, test macro 78.5%\n    Epoch 26: loss 0.00339, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.68%, test micro 80.42%, test macro 79.12%\n    Epoch 27: loss 0.00273, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.68%, test micro 81.08%, test macro 79.88%\n    Epoch 28: loss 0.00225, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.0%, test micro 81.46%, test macro 80.31%\n    Epoch 29: loss 0.00189, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.0%, test micro 81.79%, test macro 80.69%\n    Epoch 30: loss 0.00162, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 81.93%, test macro 80.84%\n    Epoch 31: loss 0.00141, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.33%, test micro 82.4%, test macro 81.41%\n    Epoch 32: loss 0.00124, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.66%, test micro 82.45%, test macro 81.47%\n    Epoch 33: loss 0.00111, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 82.73%, test macro 81.8%\n    Epoch 34: loss 0.001, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 82.92%, test macro 82.02%\n    Epoch 35: loss 0.00091, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 82.87%, test macro 81.98%\n    Epoch 36: loss 0.00083, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.67%, test micro 83.06%, test macro 82.23%\n    Epoch 37: loss 0.00077, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 83.34%, test macro 82.59%\n    Epoch 38: loss 0.00071, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 96.99%, test micro 83.25%, test macro 82.54%\n    Epoch 39: loss 0.00066, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 96.99%, test micro 83.01%, test macro 82.31%\n    Epoch 40: loss 0.00062, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.66%, test micro 83.25%, test macro 82.59%\n    Epoch 41: loss 0.00058, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.32%, test micro 83.48%, test macro 82.85%\n    Epoch 42: loss 0.00055, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.32%, test micro 83.62%, test macro 83.02%\n    Epoch 43: loss 0.00052, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.32%, test micro 83.48%, test macro 82.9%\n    Epoch 44: loss 0.00049, train micro 100.0%, train macro 100.0%, valid micro 97.67%, valid macro 97.66%, test micro 83.34%, test macro 82.78%\n    Epoch 45: loss 0.00047, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.33%, test micro 83.44%, test macro 82.92%\n    Epoch 46: loss 0.00045, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.33%, test micro 83.48%, test macro 82.99%\n    Epoch 47: loss 0.00043, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.33%, test micro 83.48%, test macro 83.01%\n    Epoch 48: loss 0.00041, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.33%, test micro 83.2%, test macro 82.73%\n    Epoch 49: loss 0.00039, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.33%, test micro 83.29%, test macro 82.86%\n    Epoch 50: loss 0.00038, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.33%, test micro 83.25%, test macro 82.85%\n    Epoch 51: loss 0.00036, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.33%, test micro 83.25%, test macro 82.85%\n    Epoch 52: loss 0.00035, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.33%, test micro 83.06%, test macro 82.66%\n    Epoch 53: loss 0.00034, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 82.92%, test macro 82.53%\n    Epoch 54: loss 0.00033, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.67%, test micro 82.92%, test macro 82.55%\n    Epoch 55: loss 0.00032, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.67%, test micro 82.92%, test macro 82.58%\n    Epoch 56: loss 0.00031, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.67%, test micro 82.59%, test macro 82.26%\n    Epoch 57: loss 0.0003, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.67%, test micro 82.64%, test macro 82.32%\n    Epoch 58: loss 0.0003, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.67%, test micro 82.59%, test macro 82.28%\n    Epoch 59: loss 0.00029, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 82.45%, test macro 82.15%\n    Epoch 60: loss 0.00028, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 82.4%, test macro 82.11%\n    Epoch 61: loss 0.00028, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 82.26%, test macro 81.97%\n    Epoch 62: loss 0.00027, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 82.31%, test macro 82.02%\n    Epoch 63: loss 0.00027, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 82.31%, test macro 82.03%\n    Epoch 64: loss 0.00026, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 82.21%, test macro 81.94%\n    Epoch 65: loss 0.00026, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 82.12%, test macro 81.85%\n    Epoch 66: loss 0.00025, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 82.02%, test macro 81.79%\n    Epoch 67: loss 0.00025, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 81.93%, test macro 81.69%\n    Epoch 68: loss 0.00024, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 81.93%, test macro 81.7%\n    Epoch 69: loss 0.00024, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 81.93%, test macro 81.7%\n    Epoch 70: loss 0.00024, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.0%, test micro 81.88%, test macro 81.65%\n    Epoch 71: loss 0.00023, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.84%, test macro 81.6%\n    Epoch 72: loss 0.00023, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.79%, test macro 81.56%\n    Epoch 73: loss 0.00023, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.79%, test macro 81.56%\n    Epoch 74: loss 0.00022, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.79%, test macro 81.56%\n    Epoch 75: loss 0.00022, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.93%, test macro 81.72%\n    Epoch 76: loss 0.00022, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.93%, test macro 81.72%\n    Epoch 77: loss 0.00021, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.93%, test macro 81.74%\n    Epoch 78: loss 0.00021, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.93%, test macro 81.74%\n    Epoch 79: loss 0.00021, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.93%, test macro 81.74%\n    Epoch 80: loss 0.00021, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.93%, test macro 81.74%\n    Epoch 81: loss 0.0002, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.84%, test macro 81.66%\n    Epoch 82: loss 0.0002, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.84%, test macro 81.66%\n    Epoch 83: loss 0.0002, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.79%, test macro 81.61%\n    Epoch 84: loss 0.0002, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.74%, test macro 81.57%\n    Epoch 85: loss 0.0002, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.69%, test macro 81.52%\n    Epoch 86: loss 0.00019, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.79%, test macro 81.62%\n    Epoch 87: loss 0.00019, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.79%, test macro 81.61%\n    Epoch 88: loss 0.00019, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.84%, test macro 81.66%\n    Epoch 89: loss 0.00019, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.84%, test macro 81.66%\n    Epoch 90: loss 0.00019, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.79%, test macro 81.64%\n    Epoch 91: loss 0.00018, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.74%, test macro 81.59%\n    Epoch 92: loss 0.00018, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.69%, test macro 81.54%\n    Epoch 93: loss 0.00018, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.69%, test macro 81.54%\n    Epoch 94: loss 0.00018, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.65%, test macro 81.48%\n    Epoch 95: loss 0.00018, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.65%, test macro 81.48%\n    Epoch 96: loss 0.00018, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.55%, test macro 81.39%\n    Epoch 97: loss 0.00017, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.51%, test macro 81.34%\n    Epoch 98: loss 0.00017, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.51%, test macro 81.34%\n    Epoch 99: loss 0.00017, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.51%, test macro 81.34%\n    Epoch 100: loss 0.00017, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.51%, test macro 81.34%\n    Epoch 101: loss 0.00017, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.51%, test macro 81.34%\n    Epoch 102: loss 0.00017, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.51%, test macro 81.34%\n    Epoch 103: loss 0.00017, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.51%, test macro 81.35%\n    Epoch 104: loss 0.00016, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.51%, test macro 81.35%\n    Epoch 105: loss 0.00016, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.46%, test macro 81.3%\n    Epoch 106: loss 0.00016, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.51%, test macro 81.35%\n    Epoch 107: loss 0.00016, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.46%, test macro 81.3%\n    Epoch 108: loss 0.00016, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.41%, test macro 81.26%\n    Epoch 109: loss 0.00016, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.41%, test macro 81.26%\n    Epoch 110: loss 0.00016, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.32%, test macro 81.16%\n    Epoch 111: loss 0.00016, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.36%, test macro 81.22%\n    Epoch 112: loss 0.00015, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.46%, test macro 81.31%\n    Epoch 113: loss 0.00015, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.51%, test macro 81.36%\n    Epoch 114: loss 0.00015, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.55%, test macro 81.4%\n    Epoch 115: loss 0.00015, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.6%, test macro 81.44%\n    Epoch 116: loss 0.00015, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.51%, test macro 81.36%\n    Epoch 117: loss 0.00015, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.46%, test macro 81.31%\n    Epoch 118: loss 0.00015, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.46%, test macro 81.31%\n    Epoch 119: loss 0.00015, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.46%, test macro 81.31%\n    Epoch 120: loss 0.00015, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.41%, test macro 81.27%\n    Epoch 121: loss 0.00015, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.41%, test macro 81.27%\n    Epoch 122: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.36%, test macro 81.22%\n    Epoch 123: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.36%, test macro 81.22%\n    Epoch 124: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.36%, test macro 81.22%\n    Epoch 125: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.36%, test macro 81.22%\n    Epoch 126: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.36%, test macro 81.22%\n    Epoch 127: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.36%, test macro 81.22%\n    Epoch 128: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.36%, test macro 81.22%\n    Epoch 129: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.36%, test macro 81.22%\n    Epoch 130: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.27%, test macro 81.11%\n    Epoch 131: loss 0.00014, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.27%, test macro 81.11%\n    Epoch 132: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.27%, test macro 81.11%\n    Epoch 133: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.27%, test macro 81.11%\n    Epoch 134: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.32%, test macro 81.16%\n    Epoch 135: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.32%, test macro 81.16%\n    Epoch 136: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.32%, test macro 81.16%\n    Epoch 137: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.32%, test macro 81.16%\n    Epoch 138: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.32%, test macro 81.16%\n    Epoch 139: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.32%, test macro 81.16%\n    Epoch 140: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.32%, test macro 81.16%\n    Epoch 141: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.36%, test macro 81.21%\n    Epoch 142: loss 0.00013, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.36%, test macro 81.21%\n    Epoch 143: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.41%, test macro 81.26%\n    Epoch 144: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.41%, test macro 81.26%\n    Epoch 145: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.41%, test macro 81.26%\n    Epoch 146: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 97.33%, valid macro 97.34%, test micro 81.41%, test macro 81.26%\n    Epoch 147: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.01%, test micro 81.41%, test macro 81.26%\n    Epoch 148: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.01%, test micro 81.46%, test macro 81.31%\n    Epoch 149: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.01%, test micro 81.46%, test macro 81.31%\n    Epoch 150: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.01%, test micro 81.41%, test macro 81.26%\n    Epoch 151: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 97.0%, valid macro 97.01%, test micro 81.41%, test macro 81.26%\n    Epoch 152: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.68%, test micro 81.32%, test macro 81.17%\n    Epoch 153: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.68%, test micro 81.32%, test macro 81.17%\n    Epoch 154: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.68%, test micro 81.32%, test macro 81.17%\n    Epoch 155: loss 0.00012, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.68%, test micro 81.32%, test macro 81.17%\n    Epoch 156: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.68%, test micro 81.32%, test macro 81.17%\n    Epoch 157: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.68%, test micro 81.32%, test macro 81.17%\n    Epoch 158: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.68%, test micro 81.32%, test macro 81.17%\n    Epoch 159: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.68%, test micro 81.32%, test macro 81.17%\n    Epoch 160: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.68%, test micro 81.32%, test macro 81.17%\n    Epoch 161: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.68%, test micro 81.32%, test macro 81.17%\n    Epoch 162: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.68%, test micro 81.32%, test macro 81.17%\n    Epoch 163: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.68%, test micro 81.32%, test macro 81.17%\n    Epoch 164: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.67%, valid macro 96.68%, test micro 81.32%, test macro 81.17%\n    Epoch 165: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.32%, test macro 81.17%\n    Epoch 166: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.32%, test macro 81.17%\n    Epoch 167: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.27%, test macro 81.13%\n    Epoch 168: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.22%, test macro 81.08%\n    Epoch 169: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.27%, test macro 81.13%\n    Epoch 170: loss 0.00011, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.27%, test macro 81.14%\n    Epoch 171: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.27%, test macro 81.14%\n    Epoch 172: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.22%, test macro 81.1%\n    Epoch 173: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.22%, test macro 81.1%\n    Epoch 174: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.22%, test macro 81.1%\n    Epoch 175: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.22%, test macro 81.1%\n    Epoch 176: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.27%, test macro 81.15%\n    Epoch 177: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.27%, test macro 81.15%\n    Epoch 178: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.32%, test macro 81.2%\n    Epoch 179: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.27%, test macro 81.14%\n    Epoch 180: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.22%, test macro 81.09%\n    Epoch 181: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.22%, test macro 81.09%\n    Epoch 182: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.22%, test macro 81.09%\n    Epoch 183: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.22%, test macro 81.09%\n    Epoch 184: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.22%, test macro 81.09%\n    Epoch 185: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.22%, test macro 81.09%\n    Epoch 186: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.22%, test macro 81.09%\n    Epoch 187: loss 0.0001, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.22%, test macro 81.09%\n    Epoch 188: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.22%, test macro 81.09%\n    Epoch 189: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.18%, test macro 81.04%\n    Epoch 190: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.13%, test macro 81.0%\n    Epoch 191: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.13%, test macro 81.0%\n    Epoch 192: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.13%, test macro 81.0%\n    Epoch 193: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.13%, test macro 81.0%\n    Epoch 194: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.18%, test macro 81.04%\n    Epoch 195: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.13%, test macro 81.0%\n    Epoch 196: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.13%, test macro 81.0%\n    Epoch 197: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.13%, test macro 81.0%\n    Epoch 198: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.13%, test macro 81.0%\n    Epoch 199: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.13%, test macro 81.0%\n    Epoch 200: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.08%, test macro 80.96%\n    Epoch 201: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.08%, test macro 80.96%\n    Epoch 202: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.13%, test macro 81.01%\n    Epoch 203: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.22%, test macro 81.11%\n    Epoch 204: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.18%, test macro 81.05%\n    Epoch 205: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.18%, test macro 81.06%\n    Epoch 206: loss 9e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.22%, test macro 81.11%\n    Epoch 207: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.22%, test macro 81.11%\n    Epoch 208: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.18%, test macro 81.06%\n    Epoch 209: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.08%, test macro 80.98%\n    Epoch 210: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.04%, test macro 80.93%\n    Epoch 211: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.33%, valid macro 96.35%, test micro 81.04%, test macro 80.93%\n    Epoch 212: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 81.04%, test macro 80.93%\n    Epoch 213: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 81.04%, test macro 80.93%\n    Epoch 214: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 81.04%, test macro 80.93%\n    Epoch 215: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 81.04%, test macro 80.93%\n    Epoch 216: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.99%, test macro 80.89%\n    Epoch 217: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 81.04%, test macro 80.94%\n    Epoch 218: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 81.04%, test macro 80.94%\n    Epoch 219: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.94%, test macro 80.85%\n    Epoch 220: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.94%, test macro 80.85%\n    Epoch 221: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.89%, test macro 80.8%\n    Epoch 222: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.89%, test macro 80.8%\n    Epoch 223: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.89%, test macro 80.8%\n    Epoch 224: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.94%, test macro 80.84%\n    Epoch 225: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.89%, test macro 80.79%\n    Epoch 226: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.89%, test macro 80.79%\n    Epoch 227: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.89%, test macro 80.79%\n    Epoch 228: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.85%, test macro 80.75%\n    Epoch 229: loss 8e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.85%, test macro 80.75%\n    Epoch 230: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.89%, test macro 80.8%\n    Epoch 231: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.89%, test macro 80.8%\n    Epoch 232: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.85%, test macro 80.75%\n    Epoch 233: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.75%, test macro 80.65%\n    Epoch 234: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.75%, test macro 80.65%\n    Epoch 235: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.75%, test macro 80.65%\n    Epoch 236: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.75%, test macro 80.65%\n    Epoch 237: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.71%, test macro 80.6%\n    Epoch 238: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.71%, test macro 80.6%\n    Epoch 239: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.71%, test macro 80.6%\n    Epoch 240: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.61%, test macro 80.51%\n    Epoch 241: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.56%, test macro 80.46%\n    Epoch 242: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.56%, test macro 80.46%\n    Epoch 243: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.56%, test macro 80.46%\n    Epoch 244: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.42%, test macro 80.33%\n    Epoch 245: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.42%, test macro 80.33%\n    Epoch 246: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.47%, test macro 80.37%\n    Epoch 247: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.47%, test macro 80.37%\n    Epoch 248: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.42%, test macro 80.33%\n    Epoch 249: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.52%, test macro 80.42%\n    Epoch 250: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.52%, test macro 80.42%\n    Epoch 251: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.52%, test macro 80.42%\n    Epoch 252: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.52%, test macro 80.42%\n    Epoch 253: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.61%, test macro 80.52%\n    Epoch 254: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.71%, test macro 80.62%\n    Epoch 255: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.75%, test macro 80.67%\n    Epoch 256: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.75%, test macro 80.67%\n    Epoch 257: loss 7e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.61%, test macro 80.52%\n    Epoch 258: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.61%, test macro 80.52%\n    Epoch 259: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.61%, test macro 80.52%\n    Epoch 260: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.61%, test macro 80.52%\n    Epoch 261: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.66%, test macro 80.57%\n    Epoch 262: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.66%, test macro 80.57%\n    Epoch 263: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.66%, test macro 80.57%\n    Epoch 264: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.56%, test macro 80.48%\n    Epoch 265: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.52%, test macro 80.43%\n    Epoch 266: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.47%, test macro 80.39%\n    Epoch 267: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.47%, test macro 80.39%\n    Epoch 268: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.47%, test macro 80.39%\n    Epoch 269: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.47%, test macro 80.39%\n    Epoch 270: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.47%, test macro 80.39%\n    Epoch 271: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.47%, test macro 80.39%\n    Epoch 272: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.47%, test macro 80.39%\n    Epoch 273: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.38%, test macro 80.29%\n    Epoch 274: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.33%, test macro 80.25%\n    Epoch 275: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.28%, test macro 80.2%\n    Epoch 276: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.33%, test macro 80.24%\n    Epoch 277: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.28%, test macro 80.19%\n    Epoch 278: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.28%, test macro 80.19%\n    Epoch 279: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.24%, test macro 80.13%\n    Epoch 280: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.24%, test macro 80.13%\n    Epoch 281: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.24%, test macro 80.13%\n    Epoch 282: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.24%, test macro 80.13%\n    Epoch 283: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.28%, test macro 80.18%\n    Epoch 284: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.28%, test macro 80.18%\n    Epoch 285: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.33%, test macro 80.22%\n    Epoch 286: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.33%, test macro 80.22%\n    Epoch 287: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.33%, test macro 80.22%\n    Epoch 288: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.28%, test macro 80.18%\n    Epoch 289: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.24%, test macro 80.13%\n    Epoch 290: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.24%, test macro 80.13%\n    Epoch 291: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.14%, test macro 80.04%\n    Epoch 292: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.09%, test macro 79.99%\n    Epoch 293: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.09%, test macro 79.99%\n    Epoch 294: loss 6e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.09%, test macro 79.99%\n    Epoch 295: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 96.0%, valid macro 96.02%, test micro 80.09%, test macro 79.99%\n    Epoch 296: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.09%, test macro 79.99%\n    Epoch 297: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.09%, test macro 79.98%\n    Epoch 298: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.05%, test macro 79.93%\n    Epoch 299: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.0%, test macro 79.88%\n    Epoch 300: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.0%, test macro 79.88%\n    Epoch 301: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.0%, test macro 79.88%\n    Epoch 302: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.0%, test macro 79.89%\n    Epoch 303: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.0%, test macro 79.89%\n    Epoch 304: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.67%, valid macro 95.69%, test micro 80.0%, test macro 79.89%\n    Epoch 305: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.35%, test micro 79.95%, test macro 79.84%\n    Epoch 306: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.35%, test micro 79.91%, test macro 79.8%\n    Epoch 307: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.35%, test micro 79.86%, test macro 79.75%\n    Epoch 308: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.35%, test micro 79.86%, test macro 79.75%\n    Epoch 309: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.0%, valid macro 95.03%, test micro 79.95%, test macro 79.85%\n    Epoch 310: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.0%, valid macro 95.03%, test micro 79.86%, test macro 79.76%\n    Epoch 311: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.0%, valid macro 95.03%, test micro 79.86%, test macro 79.76%\n    Epoch 312: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.35%, test micro 79.91%, test macro 79.8%\n    Epoch 313: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.35%, test micro 79.86%, test macro 79.76%\n    Epoch 314: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.35%, test micro 79.81%, test macro 79.7%\n    Epoch 315: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.35%, test micro 79.81%, test macro 79.7%\n    Epoch 316: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.35%, test micro 79.81%, test macro 79.7%\n    Epoch 317: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.76%, test macro 79.65%\n    Epoch 318: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.76%, test macro 79.65%\n    Epoch 319: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.76%, test macro 79.65%\n    Epoch 320: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.76%, test macro 79.65%\n    Epoch 321: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.76%, test macro 79.65%\n    Epoch 322: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.76%, test macro 79.65%\n    Epoch 323: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.72%, test macro 79.6%\n    Epoch 324: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.72%, test macro 79.6%\n    Epoch 325: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.67%, test macro 79.55%\n    Epoch 326: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.62%, test macro 79.5%\n    Epoch 327: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.62%, test macro 79.5%\n    Epoch 328: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.58%, test macro 79.46%\n    Epoch 329: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.62%, test macro 79.5%\n    Epoch 330: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.62%, test macro 79.5%\n    Epoch 331: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.67%, test macro 79.55%\n    Epoch 332: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.72%, test macro 79.59%\n    Epoch 333: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.67%, test macro 79.54%\n    Epoch 334: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.67%, test macro 79.55%\n    Epoch 335: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.58%, test macro 79.46%\n    Epoch 336: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.53%, test macro 79.42%\n    Epoch 337: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.58%, test macro 79.47%\n    Epoch 338: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.58%, test macro 79.47%\n    Epoch 339: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.48%, test macro 79.37%\n    Epoch 340: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.44%, test macro 79.33%\n    Epoch 341: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.44%, test macro 79.33%\n    Epoch 342: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.39%, test macro 79.29%\n    Epoch 343: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.39%, test macro 79.29%\n    Epoch 344: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.39%, test macro 79.29%\n    Epoch 345: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.34%, test macro 79.24%\n    Epoch 346: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.25%, test macro 79.14%\n    Epoch 347: loss 5e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.29%, test macro 79.18%\n    Epoch 348: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.25%, test macro 79.14%\n    Epoch 349: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.25%, test macro 79.14%\n    Epoch 350: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.25%, test macro 79.14%\n    Epoch 351: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.2%, test macro 79.09%\n    Epoch 352: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.2%, test macro 79.09%\n    Epoch 353: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.11%, test macro 79.0%\n    Epoch 354: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.06%, test macro 78.96%\n    Epoch 355: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.06%, test macro 78.96%\n    Epoch 356: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.01%, test macro 78.9%\n    Epoch 357: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 95.33%, valid macro 95.34%, test micro 79.01%, test macro 78.9%\n    Epoch 358: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 95.0%, valid macro 95.01%, test micro 78.96%, test macro 78.85%\n    Epoch 359: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 95.0%, valid macro 95.01%, test micro 78.96%, test macro 78.85%\n    Epoch 360: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 78.92%, test macro 78.8%\n    Epoch 361: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 78.87%, test macro 78.75%\n    Epoch 362: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 78.92%, test macro 78.79%\n    Epoch 363: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 78.92%, test macro 78.79%\n    Epoch 364: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 78.92%, test macro 78.79%\n    Epoch 365: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 78.87%, test macro 78.74%\n    Epoch 366: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 78.87%, test macro 78.74%\n    Epoch 367: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 78.82%, test macro 78.69%\n    Epoch 368: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 78.78%, test macro 78.65%\n    Epoch 369: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 78.78%, test macro 78.65%\n    Epoch 370: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 78.73%, test macro 78.6%\n    Epoch 371: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 78.73%, test macro 78.6%\n    Epoch 372: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 78.73%, test macro 78.6%\n    Epoch 373: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 78.54%, test macro 78.41%\n    Epoch 374: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 78.54%, test macro 78.41%\n    Epoch 375: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.54%, test macro 78.41%\n    Epoch 376: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.54%, test macro 78.42%\n    Epoch 377: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.54%, test macro 78.42%\n    Epoch 378: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.49%, test macro 78.37%\n    Epoch 379: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.49%, test macro 78.37%\n    Epoch 380: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.49%, test macro 78.36%\n    Epoch 381: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.49%, test macro 78.36%\n    Epoch 382: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.59%, test macro 78.46%\n    Epoch 383: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.59%, test macro 78.46%\n    Epoch 384: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.54%, test macro 78.41%\n    Epoch 385: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.54%, test macro 78.41%\n    Epoch 386: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.59%, test macro 78.46%\n    Epoch 387: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.59%, test macro 78.46%\n    Epoch 388: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.54%, test macro 78.41%\n    Epoch 389: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.54%, test macro 78.41%\n    Epoch 390: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.54%, test macro 78.41%\n    Epoch 391: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.54%, test macro 78.41%\n    Epoch 392: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.54%, test macro 78.41%\n    Epoch 393: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.54%, test macro 78.41%\n    Epoch 394: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.54%, test macro 78.41%\n    Epoch 395: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.49%, test macro 78.37%\n    Epoch 396: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.45%, test macro 78.31%\n    Epoch 397: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.45%, test macro 78.31%\n    Epoch 398: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 78.45%, test macro 78.31%\n    Epoch 399: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.67%, valid macro 94.67%, test micro 78.4%, test macro 78.27%\n    Epoch 400: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.35%, test macro 78.23%\n    Epoch 401: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.31%, test macro 78.18%\n    Epoch 402: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.26%, test macro 78.14%\n    Epoch 403: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.16%, test macro 78.05%\n    Epoch 404: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.16%, test macro 78.04%\n    Epoch 405: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.16%, test macro 78.04%\n    Epoch 406: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.16%, test macro 78.04%\n    Epoch 407: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.02%, test macro 77.9%\n    Epoch 408: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 77.93%, test macro 77.8%\n    Epoch 409: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 77.98%, test macro 77.84%\n    Epoch 410: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 78.02%, test macro 77.89%\n    Epoch 411: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 77.98%, test macro 77.84%\n    Epoch 412: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 77.88%, test macro 77.74%\n    Epoch 413: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 77.84%, test macro 77.69%\n    Epoch 414: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 77.79%, test macro 77.64%\n    Epoch 415: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 77.74%, test macro 77.59%\n    Epoch 416: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 77.69%, test macro 77.55%\n    Epoch 417: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 77.69%, test macro 77.55%\n    Epoch 418: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 77.6%, test macro 77.45%\n    Epoch 419: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 77.6%, test macro 77.45%\n    Epoch 420: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 77.65%, test macro 77.51%\n    Epoch 421: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 77.65%, test macro 77.51%\n    Epoch 422: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 77.6%, test macro 77.46%\n    Epoch 423: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 77.6%, test macro 77.46%\n    Epoch 424: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.33%, valid macro 94.34%, test micro 77.55%, test macro 77.42%\n    Epoch 425: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 77.51%, test macro 77.38%\n    Epoch 426: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 77.51%, test macro 77.38%\n    Epoch 427: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 77.46%, test macro 77.33%\n    Epoch 428: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 77.46%, test macro 77.33%\n    Epoch 429: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 77.46%, test macro 77.33%\n    Epoch 430: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 77.41%, test macro 77.28%\n    Epoch 431: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 77.36%, test macro 77.23%\n    Epoch 432: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 77.36%, test macro 77.23%\n    Epoch 433: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 77.18%, test macro 77.02%\n    Epoch 434: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 77.18%, test macro 77.02%\n    Epoch 435: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 77.18%, test macro 77.02%\n    Epoch 436: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 77.13%, test macro 76.98%\n    Epoch 437: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 77.13%, test macro 76.98%\n    Epoch 438: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 77.13%, test macro 76.98%\n    Epoch 439: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 77.18%, test macro 77.02%\n    Epoch 440: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 77.18%, test macro 77.02%\n    Epoch 441: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 77.18%, test macro 77.02%\n    Epoch 442: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 77.04%, test macro 76.88%\n    Epoch 443: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 77.08%, test macro 76.93%\n    Epoch 444: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 77.08%, test macro 76.93%\n    Epoch 445: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 76.99%, test macro 76.85%\n    Epoch 446: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 76.99%, test macro 76.85%\n    Epoch 447: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 76.99%, test macro 76.85%\n    Epoch 448: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 76.99%, test macro 76.85%\n    Epoch 449: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 76.85%, test macro 76.71%\n    Epoch 450: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 76.85%, test macro 76.71%\n    Epoch 451: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 76.85%, test macro 76.71%\n    Epoch 452: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.67%, test micro 76.8%, test macro 76.65%\n    Epoch 453: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.67%, test micro 76.8%, test macro 76.65%\n    Epoch 454: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.67%, test micro 76.8%, test macro 76.65%\n    Epoch 455: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.67%, test micro 76.75%, test macro 76.6%\n    Epoch 456: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.67%, test micro 76.75%, test macro 76.6%\n    Epoch 457: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.67%, test micro 76.8%, test macro 76.65%\n    Epoch 458: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.67%, test micro 76.8%, test macro 76.65%\n    Epoch 459: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.67%, test micro 76.8%, test macro 76.65%\n    Epoch 460: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 76.8%, test macro 76.65%\n    Epoch 461: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 76.8%, test macro 76.65%\n    Epoch 462: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 76.8%, test macro 76.65%\n    Epoch 463: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 76.8%, test macro 76.65%\n    Epoch 464: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 76.8%, test macro 76.65%\n    Epoch 465: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 76.8%, test macro 76.65%\n    Epoch 466: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 76.85%, test macro 76.69%\n    Epoch 467: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 76.85%, test macro 76.69%\n    Epoch 468: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 76.75%, test macro 76.59%\n    Epoch 469: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 76.71%, test macro 76.54%\n    Epoch 470: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 76.66%, test macro 76.49%\n    Epoch 471: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 76.66%, test macro 76.49%\n    Epoch 472: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 94.0%, valid macro 94.0%, test micro 76.71%, test macro 76.53%\n    Epoch 473: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.67%, test micro 76.66%, test macro 76.49%\n    Epoch 474: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.67%, test micro 76.61%, test macro 76.44%\n    Epoch 475: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.67%, test micro 76.61%, test macro 76.43%\n    Epoch 476: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.67%, test micro 76.61%, test macro 76.43%\n    Epoch 477: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.67%, test micro 76.61%, test macro 76.43%\n    Epoch 478: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.66%, test micro 76.52%, test macro 76.34%\n    Epoch 479: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.66%, test micro 76.47%, test macro 76.29%\n    Epoch 480: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.66%, test micro 76.47%, test macro 76.29%\n    Epoch 481: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.66%, test micro 76.47%, test macro 76.29%\n    Epoch 482: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.66%, test micro 76.42%, test macro 76.25%\n    Epoch 483: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.66%, test micro 76.42%, test macro 76.25%\n    Epoch 484: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.66%, test micro 76.38%, test macro 76.21%\n    Epoch 485: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.66%, test micro 76.38%, test macro 76.21%\n    Epoch 486: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.66%, test micro 76.24%, test macro 76.07%\n    Epoch 487: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.66%, test micro 76.28%, test macro 76.11%\n    Epoch 488: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.66%, test micro 76.28%, test macro 76.11%\n    Epoch 489: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.66%, test micro 76.24%, test macro 76.06%\n    Epoch 490: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.67%, valid macro 93.66%, test micro 76.19%, test macro 76.02%\n    Epoch 491: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.33%, valid macro 93.32%, test micro 76.19%, test macro 76.02%\n    Epoch 492: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.33%, valid macro 93.32%, test micro 76.05%, test macro 75.89%\n    Epoch 493: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.33%, valid macro 93.32%, test micro 76.0%, test macro 75.84%\n    Epoch 494: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.33%, valid macro 93.32%, test micro 75.95%, test macro 75.8%\n    Epoch 495: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.33%, valid macro 93.32%, test micro 75.95%, test macro 75.8%\n    Epoch 496: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.33%, valid macro 93.32%, test micro 75.95%, test macro 75.8%\n    Epoch 497: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.33%, valid macro 93.32%, test micro 75.95%, test macro 75.8%\n    Epoch 498: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.33%, valid macro 93.32%, test micro 75.91%, test macro 75.74%\n    Epoch 499: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.33%, valid macro 93.32%, test micro 75.91%, test macro 75.74%\n    Epoch 500: loss 4e-05, train micro 100.0%, train macro 100.0%, valid micro 93.33%, valid macro 93.32%, test micro 75.91%, test macro 75.74%\n    Saving Heterogeneous Node Prediction Model Predictions with Agg: Attention\n    \n    Best model: train micro 100.0%, train macro 100.0%, valid micro 97.67%, valid macro 97.66%, test micro 83.34%, test macro 82.78%\n\n\n## Question 2.3: What is your maximum test set **micro** F1 score for the best_model when using the attention aggregation? (4 points)\n\n\n## Question 2.4: What is your maximum test set **macro** F1 score for the best_model when using the attention aggregation? (4 points)\n\n\n## Attention for each Message Type\n\nThrough message type level attention we can learn which message type is more important to which layer.\n\nHere we will print out and show that each layer pay how much attention on each message type.\n\n\n```python\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n  if model.convs1.alpha is not None and model.convs2.alpha is not None:\n      for idx, message_type in model.convs1.mapping.items():\n          print(f\"Layer 1 has attention {model.convs1.alpha[idx]} on message type {message_type}\")\n      for idx, message_type in model.convs2.mapping.items():\n          print(f\"Layer 2 has attention {model.convs2.alpha[idx]} on message type {message_type}\")\n```\n\n    Layer 1 has attention 0.032038453966379166 on message type ('paper', 'author', 'paper')\n    Layer 1 has attention 0.9679614901542664 on message type ('paper', 'subject', 'paper')\n    Layer 2 has attention 0.7597429752349854 on message type ('paper', 'author', 'paper')\n    Layer 2 has attention 0.24025702476501465 on message type ('paper', 'subject', 'paper')\n\n\n# Submission\n\nYou will need to submit three files on Gradescope to complete this notebook. \n\n1.   Your completed *CS224W_Colab5.ipynb*. From the \"File\" menu select \"Download .ipynb\" to save a local copy of your completed Colab. \n2.  *ACM-Node-MeanAgg.csv* \n3.  *ACM-Node-AttentionAgg.csv*\n\nDownload the csv files by selecting the *Folder* icon on the left panel. \n\nTo submit your work, zip the files downloaded in steps 1-3 above and submit to gradescope. **NOTE:** DO NOT rename any of the downloaded files. \n", "meta": {"hexsha": "9d58ae5dcd0461c5cb5f7d37315e7617e9e8f28a", "size": 589133, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Colab 5/CS224W - Colab5_victor.ipynb", "max_stars_repo_name": "victorcroisfelt/aau-cs224w-ml-with-graphs", "max_stars_repo_head_hexsha": "adb38651be8da98cc574f127763c785ed16dfb5a", "max_stars_repo_licenses": ["Unlicense", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Colab 5/CS224W - Colab5_victor.ipynb", "max_issues_repo_name": "victorcroisfelt/aau-cs224w-ml-with-graphs", "max_issues_repo_head_hexsha": "adb38651be8da98cc574f127763c785ed16dfb5a", "max_issues_repo_licenses": ["Unlicense", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Colab 5/CS224W - Colab5_victor.ipynb", "max_forks_repo_name": "victorcroisfelt/aau-cs224w-ml-with-graphs", "max_forks_repo_head_hexsha": "adb38651be8da98cc574f127763c785ed16dfb5a", "max_forks_repo_licenses": ["Unlicense", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 172.3114945891, "max_line_length": 86222, "alphanum_fraction": 0.7934812682, "converted": true, "num_tokens": 74355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567937024021, "lm_q2_score": 0.17553807362342932, "lm_q1q2_score": 0.048844661539151644}}
{"text": "```python\n%run ../../common/import_all.py\n\nfrom common.setup_notebook import set_css_style, config_ipython\nconfig_ipython()\nset_css_style()\n```\n\n\n\n\n<style>\n\n    /* DOWNLOAD COMPUTER MODERN FONT JUST IN CASE */\n    @font-face {\n        font-family: \"Computer Modern\";\n        src: url('http://9dbb143991406a7c655e-aa5fcb0a5a4ec34cff238a2d56ca4144.r56.cf5.rackcdn.com/cmunss.otf');\n    }\n    @font-face {\n        font-family: \"Computer Modern\";\n        font-weight: bold;\n        src: url('http://9dbb143991406a7c655e-aa5fcb0a5a4ec34cff238a2d56ca4144.r56.cf5.rackcdn.com/cmunsx.otf');\n    }\n    @font-face {\n        font-family: \"Computer Modern\";\n        font-style: oblique;\n        src: url('http://9dbb143991406a7c655e-aa5fcb0a5a4ec34cff238a2d56ca4144.r56.cf5.rackcdn.com/cmunsi.otf');\n    }\n    @font-face {\n        font-family: \"Computer Modern\";\n        font-weight: bold;\n        font-style: oblique;\n        src: url('http://9dbb143991406a7c655e-aa5fcb0a5a4ec34cff238a2d56ca4144.r56.cf5.rackcdn.com/cmunso.otf');\n    }\n\n    /* GLOBAL TEXT FONT */\n    div#notebook,\n    div.output_area pre,\n    div.output_wrapper,\n    div.prompt {\n      font-family: Times new Roman, monospace !important;\n    }\n\n    /* CENTER FIGURE */\n    .output_png {\n        display: table-cell;\n        text-align: center;\n        vertical-align: middle;\n    }\n\n    /* LINK */\n    a {\n        color: #FF8000;\n    }\n\n    /* H1 */\n    h1 {\n        font-size: 42px !important;\n        text-align: center;\n        color: #FF8000;\n    }\n\n    /* H2 */\n    h2 {\n        font-size: 32px !important;\n    }\n\n    /* H2 */\n    h3 {\n        font-size: 24px !important;\n    }\n\n    /* H2 */\n    h4 {\n        font-size: 20px !important;\n    }\n\n    /* PARAGRAPH */\n    p {\n        font-size: 16px !important;\n        text-align: center;\n    }\n\n    /* LIST ITEM */\n    li {\n        font-size: 16px !important;\n    }\n\n</style>\n\n\n\n\n\n# Probabilistic Latent Semantic Analysis\n\n## What is and how it works\n\nPLSA, also called PLSI (I for \"indexing\"), is a probabilistic version of LSA which models the co-occurrence of words and documents as a mixture decomposition; it came out in [[1]](#1). Note that in the following, we will use the words *concept* and *topic* interchangeably.\n\nGiven word $w$ and document $d$, the probability of co-occurrence (as, the probability that $w$ occurs in $d$) is given by a mixture of conditionally independent multinomial distributions. Given latent categories (topics) $c$, we write indeed:\n\n$$\n\\begin{align}\n    P(w, d) &= \\sum_c P(c) P(d | c) P(w | c) \\\\\n            &= P(d) \\sum_c P(c | d) P(w | c)\n\\end{align}\n$$\n\nIn the fist formulation, $w$ and $d$ are thought as generated from the latent class $c$ in similar ways by using the conditional probabilities $P(d|c)$ and $P(w|c)$. In the second formulation instead, $\\forall d$, a latent class is chosen conditionally to it according to the probability $P(c|d)$ and a word is generated from that class following $P(w|c)$. The number of parameters is $c(w+d)$, so it grows linearly with the number of documents. Said parameters are estimated using the [EM algorithm](../../prob-stats/methods/em.ipynb). \n\n## Concepts, documents, words and queries\n\nPLSA is an improved variation of LSA in the sense that \n\n* documents might not contain similar terms but still refer to the same concept\n* queries can contain words not present in a document and still be very relevant to the document\n\nThis is why is uses the probability of a word, or full query $q$ given the context ($r \\in \\{0, 1\\}$ is the relevance of the document):\n\n$$\n\\begin{align}\n    P(r=1 | q) &= \\frac{P(q | r=1) P(r=1)}{P(q)} \\\\\n               &\\propto P(q|r=1) P(r=1)\n\\end{align}\n$$\n\nwhere in the last writing we have $P(q|r=1)$, telling us given a document, how probable is the query, and $P(r=1)$, which can be uniform or dependent on the popularity of the document. \n\n$P(q | r=1)$ is calculated as:\n\n* $\\forall d$, compute the probability of each word $w$ to be relevant for it $P(w | r=1)$\n* compute the conditional probability of words in $q$\n\nThe model relies on the idea that each concept has a distribution over words, each document is a mixture of concepts and each word is drawn from the topics. We will have, according to the equation above, \n\n$$\n\\begin{align}\n    P(w, d) &= P(d) \\sum_c P(w | c) P(c | d) \\\\\n            &= \\sum_c P(d|c) P(c) P(w|c)\n\\end{align}\n$$\n\nand this is a factorisation of the original matrix into three matrices (hence the relation to LSA):\n\n* a matrix $U$ which maps documents to concepts\n* a matrix $\\Sigma$ which contains the concepts\n* a matrix $V$ which maps concepts to words\n\nBut, differently from an SVD factorisation used in LSA, here there is no orthonormality condition for $U$ and $V$ and their elements are non-negative because they are probabilities. \n\nNow, we need to find all parameters such that the probability of observing the corpus is maximised. Using a [MLE](../../prob-stats/methods/mle.ipynb) approach, we need to maximise the likelihood\n\n$$\n\\mathcal{L} = \\Pi_{i=1}^n \\Pi_{j=1}^m P(w_j, d_i)^{n(w_j, d_i)} \\ ,\n$$ \n\nwhere the exponent gives the multiplicity of $w_j$ in $d_i$, as in, their count. So, computing the log, \n\n$$\n\\begin{align}\n    \\log \\mathcal{L} &= \\sum_{i=1}^n \\sum_{j=1}^m n(w_j, d_i) \\log P(w_j, d_i) \\\\\n                     &= \\sum_{i=1}^n \\sum_{j=1}^m n(w_j, d_i) \\log \\left[ \\sum_{k=1}^K P(d_i) P(c_k|d_i) P(w_j|c_k) \\right] \\\\\n                     &= \\sum_{i=1}^n n(d_i) \\sum_{j=1}^m \\frac{n(w_j, d_i)}{n(d_i)} \\log \\left[\\sum_{k=1}^K P(d_i) P(c_k|d_i) P(w_j|c_k) \\right] \\\\\n                     &= \\sum_{i=1}^n n(d_i) \\sum_{j=1}^m \\frac{n(w_j, d_i)}{n(d_i)} \\left( \\log P(d_i) + \\log \\left[ \\sum_k P(c_k| d_i) P(w_j|c_k) \\right]  \\right) \\\\\n                     &= \\sum_{i=1}^n n(d_i) \\left[ \\sum_{j=1}^m \\frac{n(w_j, d_i)}{n(d_i)} \\log P(d_i) + \\sum_{j=1}^m \\frac{n(w_j, d_i)}{n(d_i)} \\log \\sum_k P(c_k | d_i) P(w_j | c_k) \\right] \\\\\n                     &= \\sum_{i=1}^n n(d_i) \\left( \\log P(d_i) + \\sum_{j=1}^m \\frac{n(w_j, d_i)}{n(d_i)} \\log \\left[ \\sum_k P(c_k | d_i) P(w_j | c_k) \\right] \\right)\n\\end{align} \\ ,\n$$\n\nthis because $n(w_j, d_i)$ is the count of $w_j$ in $d_i$ and $n(d_i)$ is the number of words in $d_i$, hence the semplification at the first addend, as $\\sum_j \\frac{n(w_j, d_i)}{n(d_i)} = \\sum_j P(w_j) = 1$.\n\nBecause of the coupling elements given by the $c_k$, this is a hard optimisation problem and the solution can be found via the EM algorithm:\n\n* *E step*: calculate the posterior using the current estimates of the parameters:\n\n$$\nP(c_k|d_i, w_j) = \\frac{P(w_j, c_k | d_i)}{P(w_j | d_i)} = \\frac{P(w_j|c_k, d_i) P(z_k|d_i)}{\\sum_k P(w_j|c_i, d_i) P(c_i, d_i)}\n$$\n\n* *M step*: maximise the logarithm of the likelihood from the posteriors \n\n## References\n\n1. <a name=\"2\"></a> T Hofmann [**Probabilistic latent semantic indexing**](http://www.csie.ntu.edu.tw/~b97020/DSP/p50-hofmann.pdf) *Proceedings of the 22nd annual international ACM SIGIR conference on Research and development in information retrieval, ACM* 1999\n2. <a name=\"wiki\"></a> [Wikipedia on PLSA](https://en.wikipedia.org/wiki/Probabilistic_latent_semantic_analysis)\n\n\n```python\n\n```\n", "meta": {"hexsha": "f391f48d9f5a5d0582d431b273c3b03a7784b241", "size": 10360, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "nlp/topic-modelling/plsa.ipynb", "max_stars_repo_name": "walkenho/tales-science-data", "max_stars_repo_head_hexsha": "4f271d78869870acf2b35ce54d40766af7dfa348", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-11T09:39:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-11T09:39:10.000Z", "max_issues_repo_path": "nlp/topic-modelling/plsa.ipynb", "max_issues_repo_name": "walkenho/tales-science-data", "max_issues_repo_head_hexsha": "4f271d78869870acf2b35ce54d40766af7dfa348", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nlp/topic-modelling/plsa.ipynb", "max_forks_repo_name": "walkenho/tales-science-data", "max_forks_repo_head_hexsha": "4f271d78869870acf2b35ce54d40766af7dfa348", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.391634981, "max_line_length": 544, "alphanum_fraction": 0.5207528958, "converted": true, "num_tokens": 2276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936415888237616, "lm_q2_score": 0.1347759139476672, "lm_q1q2_score": 0.04843363295340693}}
{"text": "# Word Embeddings: Ungraded Practice Notebook\n\nIn this ungraded notebook, you'll try out all the individual techniques that you learned about in the lecture. Practicing on small examples will prepare you for the graded assignment, where you will combine the techniques in more advanced ways to create word embeddings from a real-life corpus.\n\nThis notebook is made of two main parts: data preparation, and the continuous bag-of-words (CBOW) model.\n\nTo get started, import and initialize all the libraries you will need.\n\n\n```python\nimport sys\n!{sys.executable} -m pip install emoji\n```\n\n    Collecting emoji\n      Downloading emoji-0.5.4.tar.gz (43 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 43 kB 4.4 MB/s  eta 0:00:01\n    \u001b[?25hBuilding wheels for collected packages: emoji\n      Building wheel for emoji (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Created wheel for emoji: filename=emoji-0.5.4-py3-none-any.whl size=42174 sha256=87187bff9f854b89b65261248401ec79a0e0cc98c5556d1d3b1d2fea3eb19635\n      Stored in directory: /home/jovyan/.cache/pip/wheels/f6/65/82/d742fe456cd8aa21ffe6c4c1eaeedf3c2d430689811bf328e1\n    Successfully built emoji\n    Installing collected packages: emoji\n    Successfully installed emoji-0.5.4\n    \u001b[33mWARNING: You are using pip version 20.1; however, version 20.1.1 is available.\n    You should consider upgrading via the '/opt/conda/bin/python -m pip install --upgrade pip' command.\u001b[0m\n\n\n\n```python\nimport re\nimport nltk\nfrom nltk.tokenize import word_tokenize\nimport emoji\nimport numpy as np\n\nfrom utils2 import get_dict\n\nnltk.download('punkt')  # download pre-trained Punkt tokenizer for English\n```\n\n    [nltk_data] Downloading package punkt to /home/jovyan/nltk_data...\n    [nltk_data]   Unzipping tokenizers/punkt.zip.\n\n\n\n\n\n    True\n\n\n\n# Data preparation\n\nIn the data preparation phase, starting with a corpus of text, you will:\n\n- Clean and tokenize the corpus.\n\n- Extract the pairs of context words and center word that will make up the training data set for the CBOW model. The context words are the features that will be fed into the model, and the center words are the target values that the model will learn to predict.\n\n- Create simple vector representations of the context words (features) and center words (targets) that can be used by the neural network of the CBOW model.\n\n## Cleaning and tokenization\n\nTo demonstrate the cleaning and tokenization process, consider a corpus that contains emojis and various punctuation signs.\n\n\n```python\ncorpus = 'Who \u2764\ufe0f \"word embeddings\" in 2020? I do!!!'\n```\n\nFirst, replace all interrupting punctuation signs \u2014 such as commas and exclamation marks \u2014 with periods.\n\n\n```python\nprint(f'Corpus:  {corpus}')\ndata = re.sub(r'[,!?;-]+', '.', corpus)\nprint(f'After cleaning punctuation:  {data}')\n```\n\n    Corpus:  Who \u2764\ufe0f \"word embeddings\" in 2020? I do!!!\n    After cleaning punctuation:  Who \u2764\ufe0f \"word embeddings\" in 2020. I do.\n\n\nNext, use NLTK's tokenization engine to split the corpus into individual tokens.\n\n\n```python\nprint(f'Initial string:  {data}')\ndata = nltk.word_tokenize(data)\nprint(f'After tokenization:  {data}')\n```\n\n    Initial string:  Who \u2764\ufe0f \"word embeddings\" in 2020. I do.\n    After tokenization:  ['Who', '\u2764\ufe0f', '``', 'word', 'embeddings', \"''\", 'in', '2020', '.', 'I', 'do', '.']\n\n\nFinally, as you saw in the lecture, get rid of numbers and punctuation other than periods, and convert all the remaining tokens to lowercase.\n\n\n```python\nprint(f'Initial list of tokens:  {data}')\ndata = [ ch.lower() for ch in data\n         if ch.isalpha()\n         or ch == '.'\n         or emoji.get_emoji_regexp().search(ch)\n       ]\nprint(f'After cleaning:  {data}')\n```\n\n    Initial list of tokens:  ['Who', '\u2764\ufe0f', '``', 'word', 'embeddings', \"''\", 'in', '2020', '.', 'I', 'do', '.']\n    After cleaning:  ['who', '\u2764\ufe0f', 'word', 'embeddings', 'in', '.', 'i', 'do', '.']\n\n\nNote that the heart emoji is considered as a token just like any normal word.\n\nNow let's streamline the cleaning and tokenization process by wrapping the previous steps in a function.\n\n\n```python\ndef tokenize(corpus):\n    data = re.sub(r'[,!?;-]+', '.', corpus)\n    data = nltk.word_tokenize(data)  # tokenize string to words\n    data = [ ch.lower() for ch in data\n             if ch.isalpha()\n             or ch == '.'\n             or emoji.get_emoji_regexp().search(ch)\n           ]\n    return data\n```\n\nApply this function to the corpus that you'll be working on in the rest of this notebook: \"I am happy because I am learning\"\n\n\n```python\ncorpus = 'I am happy because I\u00a0am learning'\nprint(f'Corpus:  {corpus}')\nwords = tokenize(corpus)\nprint(f'Words (tokens):  {words}')\n```\n\n    Corpus:  I am happy because I\u00a0am learning\n    Words (tokens):  ['i', 'am', 'happy', 'because', 'i', 'am', 'learning']\n\n\n**Now try it out yourself with your own sentence.**\n\n\n```python\ntokenize(\"Now it's your turn: try with your own sentence!\")\n```\n\n\n\n\n    ['now', 'it', 'your', 'turn', 'try', 'with', 'your', 'own', 'sentence', '.']\n\n\n\n## Sliding window of words\n\nNow that you have transformed the corpus into a list of clean tokens, you can slide a window of words across this list. For each window you can extract a center word and the context words.\n\nThe `get_windows` function in the next cell was introduced in the lecture.\n\n\n```python\ndef get_windows(words, C):\n    i = C\n    while i < len(words) - C:\n        center_word = words[i]\n        context_words = words[(i - C):i] + words[(i+1):(i+C+1)]\n        yield context_words, center_word\n        i += 1\n```\n\nThe first argument of this function is a list of words (or tokens). The second argument, `C`, is the context half-size. Recall that for a given center word, the context words are made of `C` words to the left and `C` words to the right of the center word.\n\nHere is how you can use this function to extract context words and center words from a list of tokens. These context and center words will make up the training set that you will use to train the CBOW model.\n\n\n```python\nfor x, y in get_windows(\n            ['i', 'am', 'happy', 'because', 'i', 'am', 'learning'],\n            2\n        ):\n    print(f'{x}\\t{y}')\n```\n\n    ['i', 'am', 'because', 'i']\thappy\n    ['am', 'happy', 'i', 'am']\tbecause\n    ['happy', 'because', 'am', 'learning']\ti\n\n\nThe first example of the training set is made of:\n\n- the context words \"i\", \"am\", \"because\", \"i\",\n\n- and the center word to be predicted: \"happy\".\n\n**Now try it out yourself. In the next cell, you can change both the sentence and the context half-size.**\n\n\n```python\nfor x, y in get_windows(tokenize(\"Now it's your turn: try with your own sentence!\"), 1):\n    print(f'{x}\\t{y}')\n```\n\n    ['now', 'your']\tit\n    ['it', 'turn']\tyour\n    ['your', 'try']\tturn\n    ['turn', 'with']\ttry\n    ['try', 'your']\twith\n    ['with', 'own']\tyour\n    ['your', 'sentence']\town\n    ['own', '.']\tsentence\n\n\n## Transforming words into vectors for the training set\n\nTo finish preparing the training set, you need to transform the context words and center words into vectors.\n\n### Mapping words to indices and indices to words\n\nThe center words will be represented as one-hot vectors, and the vectors that represent context words are also based on one-hot vectors.\n\nTo create one-hot word vectors, you can start by mapping each unique word to a unique integer (or index). We have provided a helper function, `get_dict`, that creates a Python dictionary that maps words to integers and back.\n\n\n```python\nword2Ind, Ind2word = get_dict(words)\n```\n\nHere's the dictionary that maps words to numeric indices.\n\n\n```python\nword2Ind\n```\n\n\n\n\n    {'am': 0, 'because': 1, 'happy': 2, 'i': 3, 'learning': 4}\n\n\n\nYou can use this dictionary to get the index of a word.\n\n\n```python\nprint(\"Index of the word 'i':  \",word2Ind['i'])\n```\n\n    Index of the word 'i':   3\n\n\nAnd conversely, here's the dictionary that maps indices to words.\n\n\n```python\nInd2word\n```\n\n\n\n\n    {0: 'am', 1: 'because', 2: 'happy', 3: 'i', 4: 'learning'}\n\n\n\n\n```python\nprint(\"Word which has index 2:  \",Ind2word[2] )\n```\n\n    Word which has index 2:   happy\n\n\nFinally, get the length of either of these dictionaries to get the size of the vocabulary of your corpus, in other words the number of different words making up the corpus.\n\n\n```python\nV = len(word2Ind)\nprint(\"Size of vocabulary: \", V)\n```\n\n    Size of vocabulary:  5\n\n\n### Getting one-hot word vectors\n\nRecall from the lecture that you can easily convert an integer, $n$, into a one-hot vector.\n\nConsider the word \"happy\". First, retrieve its numeric index.\n\n\n```python\nn = word2Ind['happy']\nn\n```\n\n\n\n\n    2\n\n\n\nNow create a vector with the size of the vocabulary, and fill it with zeros.\n\n\n```python\ncenter_word_vector = np.zeros(V)\ncenter_word_vector\n```\n\n\n\n\n    array([0., 0., 0., 0., 0.])\n\n\n\nYou can confirm that the vector has the right size.\n\n\n```python\nlen(center_word_vector) == V\n```\n\n\n\n\n    True\n\n\n\nNext, replace the 0 of the $n$-th element with a 1.\n\n\n```python\ncenter_word_vector[n] = 1\n```\n\nAnd you have your one-hot word vector.\n\n\n```python\ncenter_word_vector\n```\n\n\n\n\n    array([0., 0., 1., 0., 0.])\n\n\n\n**You can now group all of these steps in a convenient function, which takes as parameters: a word to be encoded, a dictionary that maps words to indices, and the size of the vocabulary.**\n\n\n```python\ndef word_to_one_hot_vector(word, word2Ind, V):\n    # BEGIN your code here\n    one_hot_vector = np.zeros(V)\n    one_hot_vector[word2Ind[word]] = 1\n    # END your code here\n    return one_hot_vector\n```\n\nCheck that it works as intended.\n\n\n```python\nword_to_one_hot_vector('happy', word2Ind, V)\n```\n\n\n\n\n    array([0., 0., 1., 0., 0.])\n\n\n\n**What is the word vector for \"learning\"?**\n\n\n```python\n# BEGIN your code here\nword_to_one_hot_vector('learning', word2Ind, V)\n# END your code here\n```\n\n\n\n\n    array([0., 0., 0., 0., 1.])\n\n\n\nExpected output:\n\n    array([0., 0., 0., 0., 1.])\n\n### Getting context word vectors\n\nTo create the vectors that represent context words, you will calculate the average of the one-hot vectors representing the individual words.\n\nLet's start with a list of context words.\n\n\n```python\ncontext_words = ['i', 'am', 'because', 'i']\n```\n\nUsing Python's list comprehension construct and the `word_to_one_hot_vector` function that you created in the previous section, you can create a list of one-hot vectors representing each of the context words.\n\n\n```python\ncontext_words_vectors = [word_to_one_hot_vector(w, word2Ind, V) for w in context_words]\ncontext_words_vectors\n```\n\n\n\n\n    [array([0., 0., 0., 1., 0.]),\n     array([1., 0., 0., 0., 0.]),\n     array([0., 1., 0., 0., 0.]),\n     array([0., 0., 0., 1., 0.])]\n\n\n\nAnd you can now simply get the average of these vectors using numpy's `mean` function, to get the vector representation of the context words.\n\n\n```python\nnp.mean(context_words_vectors, axis=0)\n```\n\n\n\n\n    array([0.25, 0.25, 0.  , 0.5 , 0.  ])\n\n\n\nNote the `axis=0` parameter that tells `mean` to calculate the average of the rows (if you had wanted the average of the columns, you would have used `axis=1`).\n\n**Now create the `context_words_to_vector` function that takes in a list of context words, a word-to-index dictionary, and a vocabulary size, and outputs the vector representation of the context words.**\n\n\n```python\ndef context_words_to_vector(context_words, word2Ind, V):\n    # BEGIN your code here\n    context_words_vectors = [word_to_one_hot_vector(w, word2Ind, V) for w in context_words]\n    context_words_vectors = np.mean(context_words_vectors, axis=0)\n    # END your code here\n    return context_words_vectors\n```\n\nAnd check that you obtain the same output as the manual approach above.\n\n\n```python\ncontext_words_to_vector(['i', 'am', 'because', 'i'], word2Ind, V)\n```\n\n\n\n\n    array([0.25, 0.25, 0.  , 0.5 , 0.  ])\n\n\n\n**What is the vector representation of the context words \"am happy i am\"?**\n\n\n```python\n# BEGIN your code here\ncontext_words_to_vector(['am', 'happy', 'i', 'am'], word2Ind, V)\n# END your code here\n```\n\n\n\n\n    array([0.5 , 0.  , 0.25, 0.25, 0.  ])\n\n\n\nExpected output:\n\n    array([0.5 , 0.  , 0.25, 0.25, 0.  ])\n\n\n## Building the training set\n\nYou can now combine the functions that you created in the previous sections, to build a training set for the CBOW model, starting from the following tokenized corpus.\n\n\n```python\nwords\n```\n\n\n\n\n    ['i', 'am', 'happy', 'because', 'i', 'am', 'learning']\n\n\n\nTo do this you need to use the sliding window function (`get_windows`) to extract the context words and center words, and you then convert these sets of words into a basic vector representation using `word_to_one_hot_vector` and `context_words_to_vector`.\n\n\n```python\nfor context_words, center_word in get_windows(words, 2):  # reminder: 2 is the context half-size\n    print(f'Context words:  {context_words} -> {context_words_to_vector(context_words, word2Ind, V)}')\n    print(f'Center word:  {center_word} -> {word_to_one_hot_vector(center_word, word2Ind, V)}')\n    print()\n```\n\n    Context words:  ['i', 'am', 'because', 'i'] -> [0.25 0.25 0.   0.5  0.  ]\n    Center word:  happy -> [0. 0. 1. 0. 0.]\n    \n    Context words:  ['am', 'happy', 'i', 'am'] -> [0.5  0.   0.25 0.25 0.  ]\n    Center word:  because -> [0. 1. 0. 0. 0.]\n    \n    Context words:  ['happy', 'because', 'am', 'learning'] -> [0.25 0.25 0.25 0.   0.25]\n    Center word:  i -> [0. 0. 0. 1. 0.]\n    \n\n\nIn this practice notebook you'll be performing a single iteration of training using a single example, but in this week's assignment you'll train the CBOW model using several iterations and batches of example.\nHere is how you would use a Python generator function (remember the `yield` keyword from the lecture?) to make it easier to iterate over a set of examples.\n\n\n```python\ndef get_training_example(words, C, word2Ind, V):\n    for context_words, center_word in get_windows(words, C):\n        yield context_words_to_vector(context_words, word2Ind, V), word_to_one_hot_vector(center_word, word2Ind, V)\n```\n\nThe output of this function can be iterated on to get successive context word vectors and center word vectors, as demonstrated in the next cell.\n\n\n```python\nfor context_words_vector, center_word_vector in get_training_example(words, 2, word2Ind, V):\n    print(f'Context words vector:  {context_words_vector}')\n    print(f'Center word vector:  {center_word_vector}')\n    print()\n```\n\n    Context words vector:  [0.25 0.25 0.   0.5  0.  ]\n    Center word vector:  [0. 0. 1. 0. 0.]\n    \n    Context words vector:  [0.5  0.   0.25 0.25 0.  ]\n    Center word vector:  [0. 1. 0. 0. 0.]\n    \n    Context words vector:  [0.25 0.25 0.25 0.   0.25]\n    Center word vector:  [0. 0. 0. 1. 0.]\n    \n\n\nYour training set is ready, you can now move on to the CBOW model itself.\n\n# The continuous bag-of-words model\n\nThe CBOW model is based on a neural network, the architecture of which looks like the figure below, as you'll recall from the lecture.\n\n<div style=\"width:image width px; font-size:100%; text-align:center;\"> Figure 1 </div>\n\nThis part of the notebook will walk you through:\n\n- The two activation functions used in the neural network.\n\n- Forward propagation.\n\n- Cross-entropy loss.\n\n- Backpropagation.\n\n- Gradient descent.\n\n- Extracting the word embedding vectors from the weight matrices once the neural network has been trained.\n\n## Activation functions\n\nLet's start by implementing the activation functions, ReLU and softmax.\n\n### ReLU\n\nReLU is used to calculate the values of the hidden layer, in the following formulas:\n\n\\begin{align}\n \\mathbf{z_1} &= \\mathbf{W_1}\\mathbf{x} + \\mathbf{b_1}  \\tag{1} \\\\\n \\mathbf{h} &= \\mathrm{ReLU}(\\mathbf{z_1})  \\tag{2} \\\\\n\\end{align}\n\n\nLet's fix a value for $\\mathbf{z_1}$ as a working example.\n\n\n```python\nnp.random.seed(10)\nz_1 = 10*np.random.rand(5, 1)-5\nz_1\n```\n\n\n\n\n    array([[ 2.71320643],\n           [-4.79248051],\n           [ 1.33648235],\n           [ 2.48803883],\n           [-0.01492988]])\n\n\n\nTo get the ReLU of this vector, you want all the negative values to become zeros.\n\nFirst create a copy of this vector.\n\n\n```python\nh = z_1.copy()\n```\n\nNow determine which of its values are negative.\n\n\n```python\nh < 0\n```\n\n\n\n\n    array([[False],\n           [ True],\n           [False],\n           [False],\n           [ True]])\n\n\n\nYou can now simply set all of the values which are negative to 0.\n\n\n```python\nh[h < 0] = 0\n```\n\nAnd that's it: you have the ReLU of $\\mathbf{z_1}$!\n\n\n```python\nh\n```\n\n\n\n\n    array([[2.71320643],\n           [0.        ],\n           [1.33648235],\n           [2.48803883],\n           [0.        ]])\n\n\n\n**Now implement ReLU as a function.**\n\n\n```python\ndef relu(z):\n    # BEGIN your code here\n    result = z.copy()\n    result[result < 0] = 0\n    # END your code here\n    \n    return result\n```\n\n**And check that it's working.**\n\n\n```python\nz = np.array([[-1.25459881], [ 4.50714306], [ 2.31993942], [ 0.98658484], [-3.4398136 ]])\nrelu(z)\n```\n\n\n\n\n    array([[0.        ],\n           [4.50714306],\n           [2.31993942],\n           [0.98658484],\n           [0.        ]])\n\n\n\nExpected output:\n\n    array([[0.        ],\n           [4.50714306],\n           [2.31993942],\n           [0.98658484],\n           [0.        ]])\n\n### Softmax\n\nThe second activation function that you need is softmax. This function is used to calculate the values of the output layer of the neural network, using the following formulas:\n\n\\begin{align}\n \\mathbf{z_2} &= \\mathbf{W_2}\\mathbf{h} + \\mathbf{b_2}   \\tag{3} \\\\\n \\mathbf{\\hat y} &= \\mathrm{softmax}(\\mathbf{z_2})   \\tag{4} \\\\\n\\end{align}\n\nTo calculate softmax of a vector $\\mathbf{z}$, the $i$-th component of the resulting vector is given by:\n\n$$ \\textrm{softmax}(\\textbf{z})_i = \\frac{e^{z_i} }{\\sum\\limits_{j=1}^{V} e^{z_j} }  \\tag{5} $$\n\nLet's work through an example.\n\n\n```python\nz = np.array([9, 8, 11, 10, 8.5])\nz\n```\n\n\n\n\n    array([ 9. ,  8. , 11. , 10. ,  8.5])\n\n\n\nYou'll need to calculate the exponentials of each element, both for the numerator and for the denominator.\n\n\n```python\ne_z = np.exp(z)\ne_z\n```\n\n\n\n\n    array([ 8103.08392758,  2980.95798704, 59874.1417152 , 22026.46579481,\n            4914.7688403 ])\n\n\n\nThe denominator is equal to the sum of these exponentials.\n\n\n```python\nsum_e_z = np.sum(e_z)\nsum_e_z\n```\n\n\n\n\n    97899.41826492078\n\n\n\nAnd the value of the first element of $\\textrm{softmax}(\\textbf{z})$ is given by:\n\n\n```python\ne_z[0]/sum_e_z\n```\n\n\n\n\n    0.08276947985173956\n\n\n\nThis is for one element. You can use numpy's vectorized operations to calculate the values of all the elements of the $\\textrm{softmax}(\\textbf{z})$ vector in one go.\n\n**Implement the softmax function.**\n\n\n```python\ndef softmax(z):\n    # BEGIN your code here\n    e_z = np.exp(z)\n    sum_e_z = np.sum(e_z)\n    return e_z / sum_e_z\n    # END your code here\n```\n\n**Now check that it works.**\n\n\n```python\nsoftmax([9, 8, 11, 10, 8.5])\n```\n\n\n\n\n    array([0.08276948, 0.03044919, 0.61158833, 0.22499077, 0.05020223])\n\n\n\nExpected output:\n\n    array([0.08276948, 0.03044919, 0.61158833, 0.22499077, 0.05020223])\n\n## Dimensions: 1-D arrays vs 2-D column vectors\n\nBefore moving on to implement forward propagation, backpropagation, and gradient descent, let's have a look at the dimensions of the vectors you've been handling until now.\n\nCreate a vector of length $V$ filled with zeros.\n\n\n```python\nx_array = np.zeros(V)\nx_array\n```\n\n\n\n\n    array([0., 0., 0., 0., 0.])\n\n\n\nThis is a 1-dimensional array, as revealed by the `.shape` property of the array.\n\n\n```python\nx_array.shape\n```\n\n\n\n\n    (5,)\n\n\n\nTo perform matrix multiplication in the next steps, you actually need your column vectors to be represented as a matrix with one column. In numpy, this matrix is represented as a 2-dimensional array.\n\nThe easiest way to convert a 1D vector to a 2D column matrix is to set its `.shape` property to the number of rows and one column, as shown in the next cell.\n\n\n```python\nx_column_vector = x_array.copy()\nx_column_vector.shape = (V, 1)  # alternatively ... = (x_array.shape[0], 1)\nx_column_vector\n```\n\n\n\n\n    array([[0.],\n           [0.],\n           [0.],\n           [0.],\n           [0.]])\n\n\n\nThe shape of the resulting \"vector\" is:\n\n\n```python\nx_column_vector.shape\n```\n\n\n\n\n    (5, 1)\n\n\n\nSo you now have a 5x1 matrix that you can use to perform standard matrix multiplication.\n\n## Forward propagation\n\nLet's dive into the neural network itself, which is shown below with all the dimensions and formulas you'll need.\n\n<div style=\"width:image width px; font-size:100%; text-align:center;\"> Figure 2 </div>\n\nSet $N$ equal to 3. Remember that $N$ is a hyperparameter of the CBOW model that represents the size of the word embedding vectors, as well as the size of the hidden layer.\n\n\n```python\nN = 3\n```\n\n### Initialization of the weights and biases\n\nBefore you start training the neural network, you need to initialize the weight matrices and bias vectors with random values.\n\nIn the assignment you will implement a function to do this yourself using `numpy.random.rand`. In this notebook, we've pre-populated these matrices and vectors for you.\n\n\n```python\nW1 = np.array([[ 0.41687358,  0.08854191, -0.23495225,  0.28320538,  0.41800106],\n               [ 0.32735501,  0.22795148, -0.23951958,  0.4117634 , -0.23924344],\n               [ 0.26637602, -0.23846886, -0.37770863, -0.11399446,  0.34008124]])\n\nW2 = np.array([[-0.22182064, -0.43008631,  0.13310965],\n               [ 0.08476603,  0.08123194,  0.1772054 ],\n               [ 0.1871551 , -0.06107263, -0.1790735 ],\n               [ 0.07055222, -0.02015138,  0.36107434],\n               [ 0.33480474, -0.39423389, -0.43959196]])\n\nb1 = np.array([[ 0.09688219],\n               [ 0.29239497],\n               [-0.27364426]])\n\nb2 = np.array([[ 0.0352008 ],\n               [-0.36393384],\n               [-0.12775555],\n               [-0.34802326],\n               [-0.07017815]])\n```\n\n**Check that the dimensions of these matrices match those shown in the figure above.**\n\n\n```python\n# BEGIN your code here\nprint(f'V (vocabulary size): {V}')\nprint(f'N (embedding size / size of the hidden layer): {N}')\nprint(f'size of W1: {W1.shape} (NxV)')\nprint(f'size of b1: {b1.shape} (Nx1)')\nprint(f'size of W2: {W1.shape} (VxN)')\nprint(f'size of b2: {b2.shape} (Vx1)')\n# END your code here\n```\n\n    V (vocabulary size): 5\n    N (embedding size / size of the hidden layer): 3\n    size of W1: (3, 5) (NxV)\n    size of b1: (3, 1) (Nx1)\n    size of W2: (3, 5) (VxN)\n    size of b2: (5, 1) (Vx1)\n\n\n### Training example\n\nRun the next cells to get the first training example, made of the vector representing the context words \"i am because i\", and the target which is the one-hot vector representing the center word \"happy\".\n\n> You don't need to worry about the Python syntax, but there are some explanations below if you want to know what's happening behind the scenes.\n\n\n```python\ntraining_examples = get_training_example(words, 2, word2Ind, V)\n```\n\n> `get_training_examples`, which uses the `yield` keyword, is known as a generator. When run, it builds an iterator, which is a special type of object that... you can iterate on (using a `for` loop for instance), to retrieve the successive values that the function generates.\n>\n> In this case `get_training_examples` `yield`s training examples, and iterating on `training_examples` will return the successive training examples.\n\n\n```python\nx_array, y_array = next(training_examples)\n```\n\n> `next` is another special keyword, which gets the next available value from an iterator. Here, you'll get the very first value, which is the first training example. If you run this cell again, you'll get the next value, and so on until the iterator runs out of values to return.\n>\n> In this notebook `next` is used because you will only be performing one iteration of training. In this week's assignment with the full training over several iterations you'll use regular `for` loops with the iterator that supplies the training examples.\n\nThe vector representing the context words, which will be fed into the neural network, is:\n\n\n```python\nx_array\n```\n\n\n\n\n    array([0.25, 0.25, 0.  , 0.5 , 0.  ])\n\n\n\nThe one-hot vector representing the center word to be predicted is:\n\n\n```python\ny_array\n```\n\n\n\n\n    array([0., 0., 1., 0., 0.])\n\n\n\nNow convert these vectors into matrices (or 2D arrays) to be able to perform matrix multiplication on the right types of objects, as explained above.\n\n\n```python\nx = x_array.copy()\nx.shape = (V, 1)\nprint('x')\nprint(x)\nprint()\n\ny = y_array.copy()\ny.shape = (V, 1)\nprint('y')\nprint(y)\n```\n\n    x\n    [[0.25]\n     [0.25]\n     [0.  ]\n     [0.5 ]\n     [0.  ]]\n    \n    y\n    [[0.]\n     [0.]\n     [1.]\n     [0.]\n     [0.]]\n\n\n### Values of the hidden layer\n\nNow that you have initialized all the variables that you need for forward propagation, you can calculate the values of the hidden layer using the following formulas:\n\n\\begin{align}\n \\mathbf{z_1} = \\mathbf{W_1}\\mathbf{x} + \\mathbf{b_1}  \\tag{1} \\\\\n \\mathbf{h} = \\mathrm{ReLU}(\\mathbf{z_1})  \\tag{2} \\\\\n\\end{align}\n\nFirst, you can calculate the value of $\\mathbf{z_1}$.\n\n\n```python\nz1 = np.dot(W1, x) + b1\n```\n\n>\u00a0`np.dot` is numpy's function for matrix multiplication.\n\nAs expected you get an $N$ by 1 matrix, or column vector with $N$ elements, where $N$ is equal to the embedding size, which is 3 in this example.\n\n\n```python\nz1\n```\n\n\n\n\n    array([[ 0.36483875],\n           [ 0.63710329],\n           [-0.3236647 ]])\n\n\n\nYou can now take the ReLU of $\\mathbf{z_1}$ to get $\\mathbf{h}$, the vector with the values of the hidden layer.\n\n\n```python\nh = relu(z1)\nh\n```\n\n\n\n\n    array([[0.36483875],\n           [0.63710329],\n           [0.        ]])\n\n\n\nApplying ReLU means that the negative element of $\\mathbf{z_1}$ has been replaced with a zero.\n\n### Values of the output layer\n\nHere are the formulas you need to calculate the values of the output layer, represented by the vector $\\mathbf{\\hat y}$:\n\n\\begin{align}\n \\mathbf{z_2} &= \\mathbf{W_2}\\mathbf{h} + \\mathbf{b_2}   \\tag{3} \\\\\n \\mathbf{\\hat y} &= \\mathrm{softmax}(\\mathbf{z_2})   \\tag{4} \\\\\n\\end{align}\n\n**First, calculate $\\mathbf{z_2}$.**\n\n\n```python\n# BEGIN your code here\nz2 = np.dot(W2, h) + b2\n# END your code here\n\nz2\n```\n\n\n\n\n    array([[-0.31973737],\n           [-0.28125477],\n           [-0.09838369],\n           [-0.33512159],\n           [-0.19919612]])\n\n\n\nExpected output:\n\n    array([[-0.31973737],\n           [-0.28125477],\n           [-0.09838369],\n           [-0.33512159],\n           [-0.19919612]])\n\nThis is a $V$ by 1 matrix, where $V$ is the size of the vocabulary, which is 5 in this example.\n\n**Now calculate the value of $\\mathbf{\\hat y}$.**\n\n\n```python\n# BEGIN your code here\ny_hat = softmax(z2)\n# END your code here\n\ny_hat\n```\n\n\n\n\n    array([[0.18519074],\n           [0.19245626],\n           [0.23107446],\n           [0.18236353],\n           [0.20891502]])\n\n\n\nExpected output:\n\n    array([[0.18519074],\n           [0.19245626],\n           [0.23107446],\n           [0.18236353],\n           [0.20891502]])\n\nAs you've performed the calculations with random matrices and vectors (apart from the input vector), the output of the neural network is essentially random at this point. The learning process will adjust the weights and biases to match the actual targets better.\n\n**That being said, what word did the neural network predict?**\n\n<details>    \n<summary>\n    <font size=\"3\" color=\"darkgreen\"><b>Solution</b></font>\n</summary>\n<p>The neural network predicted the word \"happy\": the largest element of $\\mathbf{\\hat y}$ is the third one, and the third word of the vocabulary is \"happy\".</p>\n<p>Here's how you could implement this in Python:</p>\n<p><code>print(Ind2word[np.argmax(y_hat)])</code></p>\n\nWell done, you've completed the forward propagation phase!\n\n## Cross-entropy loss\n\nNow that you have the network's prediction, you can calculate the cross-entropy loss to determine how accurate the prediction was compared to the actual target.\n\n> Remember that you are working on a single training example, not on a batch of examples, which is why you are using *loss* and not *cost*, which is the generalized form of loss.\n\nFirst let's recall what the prediction was.\n\n\n```python\ny_hat\n```\n\n\n\n\n    array([[0.18519074],\n           [0.19245626],\n           [0.23107446],\n           [0.18236353],\n           [0.20891502]])\n\n\n\nAnd the actual target value is:\n\n\n```python\ny\n```\n\n\n\n\n    array([[0.],\n           [0.],\n           [1.],\n           [0.],\n           [0.]])\n\n\n\nThe formula for cross-entropy loss is:\n\n$$ J=-\\sum\\limits_{k=1}^{V}y_k\\log{\\hat{y}_k} \\tag{6}$$\n\n**Implement the cross-entropy loss function.**\n\nHere are a some hints if you're stuck.\n\n<details>    \n<summary>\n    <font size=\"3\" color=\"darkgreen\"><b>Hint 1</b></font>\n</summary>\n    <p>To multiply two numpy matrices (such as <code>y</code> and <code>y_hat</code>) element-wise, you can simply use the <code>*</code> operator.</p>\n\n<details>    \n<summary>\n    <font size=\"3\" color=\"darkgreen\"><b>Hint 2</b></font>\n</summary>\n<p>Once you have a vector equal to the element-wise multiplication of <code>y</code> and <code>y_hat</code>, you can use <code>np.sum</code> to calculate the sum of the elements of this vector.</p>\n\n\n```python\ndef cross_entropy_loss(y_predicted, y_actual):\n    # BEGIN your code here\n    loss = np.sum(-np.log(y_hat)*y)\n    # END your code here\n    return loss\n```\n\n**Now use this function to calculate the loss with the actual values of $\\mathbf{y}$ and $\\mathbf{\\hat y}$.**\n\n\n```python\ncross_entropy_loss(y_hat, y)\n```\n\n\n\n\n    1.4650152923611106\n\n\n\nExpected output:\n\n    1.4650152923611106\n\nThis value is neither good nor bad, which is expected as the neural network hasn't learned anything yet.\n\nThe actual learning will start during the next phase: backpropagation.\n\n## Backpropagation\n\nThe formulas that you will implement for backpropagation are the following.\n\n\\begin{align}\n \\frac{\\partial J}{\\partial \\mathbf{W_1}} &= \\rm{ReLU}\\left ( \\mathbf{W_2^\\top} (\\mathbf{\\hat{y}} - \\mathbf{y})\\right )\\mathbf{x}^\\top \\tag{7}\\\\\n \\frac{\\partial J}{\\partial \\mathbf{W_2}} &= (\\mathbf{\\hat{y}} - \\mathbf{y})\\mathbf{h^\\top} \\tag{8}\\\\\n \\frac{\\partial J}{\\partial \\mathbf{b_1}} &= \\rm{ReLU}\\left ( \\mathbf{W_2^\\top} (\\mathbf{\\hat{y}} - \\mathbf{y})\\right ) \\tag{9}\\\\\n \\frac{\\partial J}{\\partial \\mathbf{b_2}} &= \\mathbf{\\hat{y}} - \\mathbf{y} \\tag{10}\n\\end{align}\n\n> Note: these formulas are slightly simplified compared to the ones in the lecture as you're working on a single training example, whereas the lecture provided the formulas for a batch of examples. In the assignment you'll be implementing the latter.\n\nLet's start with an easy one.\n\n**Calculate the partial derivative of the loss function with respect to $\\mathbf{b_2}$, and store the result in `grad_b2`.**\n\n$$\\frac{\\partial J}{\\partial \\mathbf{b_2}} = \\mathbf{\\hat{y}} - \\mathbf{y} \\tag{10}$$\n\n\n```python\n# BEGIN your code here\ngrad_b2 = y_hat - y\n# END your code here\n\ngrad_b2\n```\n\n\n\n\n    array([[ 0.18519074],\n           [ 0.19245626],\n           [-0.76892554],\n           [ 0.18236353],\n           [ 0.20891502]])\n\n\n\nExpected output:\n\n    array([[ 0.18519074],\n           [ 0.19245626],\n           [-0.76892554],\n           [ 0.18236353],\n           [ 0.20891502]])\n\n**Next, calculate the partial derivative of the loss function with respect to $\\mathbf{W_2}$, and store the result in `grad_W2`.**\n\n$$\\frac{\\partial J}{\\partial \\mathbf{W_2}} = (\\mathbf{\\hat{y}} - \\mathbf{y})\\mathbf{h^\\top} \\tag{8}$$\n\n> Hint: use `.T` to get a transposed matrix, e.g. `h.T` returns $\\mathbf{h^\\top}$.\n\n\n```python\n# BEGIN your code here\ngrad_W2 = np.dot(y_hat - y, h.T)\n# END your code here\n\ngrad_W2\n```\n\n\n\n\n    array([[ 0.06756476,  0.11798563,  0.        ],\n           [ 0.0702155 ,  0.12261452,  0.        ],\n           [-0.28053384, -0.48988499,  0.        ],\n           [ 0.06653328,  0.1161844 ,  0.        ],\n           [ 0.07622029,  0.13310045,  0.        ]])\n\n\n\nExpected output:\n\n    array([[ 0.06756476,  0.11798563,  0.        ],\n           [ 0.0702155 ,  0.12261452,  0.        ],\n           [-0.28053384, -0.48988499,  0.        ],\n           [ 0.06653328,  0.1161844 ,  0.        ],\n           [ 0.07622029,  0.13310045,  0.        ]])\n\n**Now calculate the partial derivative with respect to $\\mathbf{b_1}$ and store the result in `grad_b1`.**\n\n$$\\frac{\\partial J}{\\partial \\mathbf{b_1}} = \\rm{ReLU}\\left ( \\mathbf{W_2^\\top} (\\mathbf{\\hat{y}} - \\mathbf{y})\\right ) \\tag{9}$$\n\n\n```python\n# BEGIN your code here\ngrad_b1 = relu(np.dot(W2.T, y_hat - y))\n# END your code here\n\ngrad_b1\n```\n\n\n\n\n    array([[0.        ],\n           [0.        ],\n           [0.17045858]])\n\n\n\nExpected output:\n\n    array([[0.        ],\n           [0.        ],\n           [0.17045858]])\n\n**Finally, calculate the partial derivative of the loss with respect to $\\mathbf{W_1}$, and store it in `grad_W1`.**\n\n$$\\frac{\\partial J}{\\partial \\mathbf{W_1}} = \\rm{ReLU}\\left ( \\mathbf{W_2^\\top} (\\mathbf{\\hat{y}} - \\mathbf{y})\\right )\\mathbf{x}^\\top \\tag{7}$$\n\n\n```python\n# BEGIN your code here\ngrad_W1 = np.dot(relu(np.dot(W2.T, y_hat - y)), x.T)\n# END your code here\n\ngrad_W1\n```\n\n\n\n\n    array([[0.        , 0.        , 0.        , 0.        , 0.        ],\n           [0.        , 0.        , 0.        , 0.        , 0.        ],\n           [0.04261464, 0.04261464, 0.        , 0.08522929, 0.        ]])\n\n\n\nExpected output:\n\n    array([[0.        , 0.        , 0.        , 0.        , 0.        ],\n           [0.        , 0.        , 0.        , 0.        , 0.        ],\n           [0.04261464, 0.04261464, 0.        , 0.08522929, 0.        ]])\n\nBefore moving on to gradient descent, double-check that all the matrices have the expected dimensions.\n\n\n```python\n# BEGIN your code here\nprint(f'V (vocabulary size): {V}')\nprint(f'N (embedding size / size of the hidden layer): {N}')\nprint(f'size of grad_W1: {grad_W1.shape} (NxV)')\nprint(f'size of grad_b1: {grad_b1.shape} (Nx1)')\nprint(f'size of grad_W2: {grad_W1.shape} (VxN)')\nprint(f'size of grad_b2: {grad_b2.shape} (Vx1)')\n# END your code here\n```\n\n    V (vocabulary size): 5\n    N (embedding size / size of the hidden layer): 3\n    size of grad_W1: (3, 5) (NxV)\n    size of grad_b1: (3, 1) (Nx1)\n    size of grad_W2: (3, 5) (VxN)\n    size of grad_b2: (5, 1) (Vx1)\n\n\n## Gradient descent\n\nDuring the gradient descent phase, you will update the weights and biases by subtracting $\\alpha$ times the gradient from the original matrices and vectors, using the following formulas.\n\n\\begin{align}\n \\mathbf{W_1} &:= \\mathbf{W_1} - \\alpha \\frac{\\partial J}{\\partial \\mathbf{W_1}} \\tag{11}\\\\\n \\mathbf{W_2} &:= \\mathbf{W_2} - \\alpha \\frac{\\partial J}{\\partial \\mathbf{W_2}} \\tag{12}\\\\\n \\mathbf{b_1} &:= \\mathbf{b_1} - \\alpha \\frac{\\partial J}{\\partial \\mathbf{b_1}} \\tag{13}\\\\\n \\mathbf{b_2} &:= \\mathbf{b_2} - \\alpha \\frac{\\partial J}{\\partial \\mathbf{b_2}} \\tag{14}\\\\\n\\end{align}\n\nFirst, let set a value for $\\alpha$.\n\n\n```python\nalpha = 0.03\n```\n\nThe updated weight matrix $\\mathbf{W_1}$ will be:\n\n\n```python\nW1_new = W1 - alpha * grad_W1\n```\n\nLet's compare the previous and new values of $\\mathbf{W_1}$:\n\n\n```python\nprint('old value of W1:')\nprint(W1)\nprint()\nprint('new value of W1:')\nprint(W1_new)\n```\n\n    old value of W1:\n    [[ 0.41687358  0.08854191 -0.23495225  0.28320538  0.41800106]\n     [ 0.32735501  0.22795148 -0.23951958  0.4117634  -0.23924344]\n     [ 0.26637602 -0.23846886 -0.37770863 -0.11399446  0.34008124]]\n    \n    new value of W1:\n    [[ 0.41687358  0.08854191 -0.23495225  0.28320538  0.41800106]\n     [ 0.32735501  0.22795148 -0.23951958  0.4117634  -0.23924344]\n     [ 0.26509758 -0.2397473  -0.37770863 -0.11655134  0.34008124]]\n\n\nThe difference is very subtle (hint: take a closer look at the last row), which is why it takes a fair amount of iterations to train the neural network until it reaches optimal weights and biases starting from random values.\n\n**Now calculate the new values of $\\mathbf{W_2}$ (to be stored in `W2_new`), $\\mathbf{b_1}$ (in `b1_new`), and $\\mathbf{b_2}$ (in `b2_new`).**\n\n\\begin{align}\n \\mathbf{W_2} &:= \\mathbf{W_2} - \\alpha \\frac{\\partial J}{\\partial \\mathbf{W_2}} \\tag{12}\\\\\n \\mathbf{b_1} &:= \\mathbf{b_1} - \\alpha \\frac{\\partial J}{\\partial \\mathbf{b_1}} \\tag{13}\\\\\n \\mathbf{b_2} &:= \\mathbf{b_2} - \\alpha \\frac{\\partial J}{\\partial \\mathbf{b_2}} \\tag{14}\\\\\n\\end{align}\n\n\n```python\n# BEGIN your code here\nW2_new = W2 - alpha * grad_W2\nb1_new = b1 - alpha * grad_b1\nb2_new = b2 - alpha * grad_b2\n# END your code here\n\nprint('W2_new')\nprint(W2_new)\nprint()\nprint('b1_new')\nprint(b1_new)\nprint()\nprint('b2_new')\nprint(b2_new)\n```\n\n    W2_new\n    [[-0.22384758 -0.43362588  0.13310965]\n     [ 0.08265956  0.0775535   0.1772054 ]\n     [ 0.19557112 -0.04637608 -0.1790735 ]\n     [ 0.06855622 -0.02363691  0.36107434]\n     [ 0.33251813 -0.3982269  -0.43959196]]\n    \n    b1_new\n    [[ 0.09688219]\n     [ 0.29239497]\n     [-0.27875802]]\n    \n    b2_new\n    [[ 0.02964508]\n     [-0.36970753]\n     [-0.10468778]\n     [-0.35349417]\n     [-0.0764456 ]]\n\n\nExpected output:\n\n    W2_new\n    [[-0.22384758 -0.43362588  0.13310965]\n     [ 0.08265956  0.0775535   0.1772054 ]\n     [ 0.19557112 -0.04637608 -0.1790735 ]\n     [ 0.06855622 -0.02363691  0.36107434]\n     [ 0.33251813 -0.3982269  -0.43959196]]\n\n    b1_new\n    [[ 0.09688219]\n     [ 0.29239497]\n     [-0.27875802]]\n\n    b2_new\n    [[ 0.02964508]\n     [-0.36970753]\n     [-0.10468778]\n     [-0.35349417]\n     [-0.0764456 ]]\n\nCongratulations, you have completed one iteration of training using one training example!\n\nYou'll need many more iterations to fully train the neural network, and you can optimize the learning process by training on batches of examples, as described in the lecture. You will get to do this during this week's assignment.\n\n## Extracting word embedding vectors\n\nOnce you have finished training the neural network, you have three options to get word embedding vectors for the words of your vocabulary, based on the weight matrices $\\mathbf{W_1}$ and/or $\\mathbf{W_2}$.\n\n### Option 1: extract embedding vectors from $\\mathbf{W_1}$\n\nThe first option is to take the columns of $\\mathbf{W_1}$ as the embedding vectors of the words of the vocabulary, using the same order of the words as for the input and output vectors.\n\n> Note: in this practice notebook the values of the word embedding vectors are meaningless after a single iteration with just one training example, but here's how you would proceed after the training process is complete.\n\nFor example $\\mathbf{W_1}$ is this matrix:\n\n\n```python\nW1\n```\n\n\n\n\n    array([[ 0.41687358,  0.08854191, -0.23495225,  0.28320538,  0.41800106],\n           [ 0.32735501,  0.22795148, -0.23951958,  0.4117634 , -0.23924344],\n           [ 0.26637602, -0.23846886, -0.37770863, -0.11399446,  0.34008124]])\n\n\n\nThe first column, which is a 3-element vector, is the embedding vector of the first word of your vocabulary. The second column is the word embedding vector for the second word, and so on.\n\nThe first, second, etc. words are ordered as follows.\n\n\n```python\nfor i in range(V):\n    print(Ind2word[i])\n```\n\n    am\n    because\n    happy\n    i\n    learning\n\n\nSo the word embedding vectors corresponding to each word are:\n\n\n```python\n# loop through each word of the vocabulary\nfor word in word2Ind:\n    # extract the column corresponding to the index of the word in the vocabulary\n    word_embedding_vector = W1[:, word2Ind[word]]\n    \n    print(f'{word}: {word_embedding_vector}')\n```\n\n    am: [0.41687358 0.32735501 0.26637602]\n    because: [ 0.08854191  0.22795148 -0.23846886]\n    happy: [-0.23495225 -0.23951958 -0.37770863]\n    i: [ 0.28320538  0.4117634  -0.11399446]\n    learning: [ 0.41800106 -0.23924344  0.34008124]\n\n\n### Option 2: extract embedding vectors from $\\mathbf{W_2}$\n\nThe second option is to take $\\mathbf{W_2}$ transposed, and take its columns as the word embedding vectors just like you did for $\\mathbf{W_1}$.\n\n\n```python\nW2.T\n```\n\n\n\n\n    array([[-0.22182064,  0.08476603,  0.1871551 ,  0.07055222,  0.33480474],\n           [-0.43008631,  0.08123194, -0.06107263, -0.02015138, -0.39423389],\n           [ 0.13310965,  0.1772054 , -0.1790735 ,  0.36107434, -0.43959196]])\n\n\n\n\n```python\n# loop through each word of the vocabulary\nfor word in word2Ind:\n    # extract the column corresponding to the index of the word in the vocabulary\n    word_embedding_vector = W2.T[:, word2Ind[word]]\n    \n    print(f'{word}: {word_embedding_vector}')\n```\n\n    am: [-0.22182064 -0.43008631  0.13310965]\n    because: [0.08476603 0.08123194 0.1772054 ]\n    happy: [ 0.1871551  -0.06107263 -0.1790735 ]\n    i: [ 0.07055222 -0.02015138  0.36107434]\n    learning: [ 0.33480474 -0.39423389 -0.43959196]\n\n\n### Option 3: extract embedding vectors from $\\mathbf{W_1}$ and $\\mathbf{W_2}$\n\nThe third option, which is the one you will use in this week's assignment, uses the average of $\\mathbf{W_1}$ and $\\mathbf{W_2^\\top}$.\n\n**Calculate the average of $\\mathbf{W_1}$ and $\\mathbf{W_2^\\top}$, and store the result in `W3`.**\n\n\n```python\n# BEGIN your code here\nW3 = (W1+W2.T)/2\n# END your code here\n\nW3\n```\n\n\n\n\n    array([[ 0.09752647,  0.08665397, -0.02389858,  0.1768788 ,  0.3764029 ],\n           [-0.05136565,  0.15459171, -0.15029611,  0.19580601, -0.31673866],\n           [ 0.19974284, -0.03063173, -0.27839106,  0.12353994, -0.04975536]])\n\n\n\nExpected output:\n\n    array([[ 0.09752647,  0.08665397, -0.02389858,  0.1768788 ,  0.3764029 ],\n           [-0.05136565,  0.15459171, -0.15029611,  0.19580601, -0.31673866],\n           [ 0.19974284, -0.03063173, -0.27839106,  0.12353994, -0.04975536]])\n\nExtracting the word embedding vectors works just like the two previous options, by taking the columns of the matrix you've just created.\n\n\n```python\n# loop through each word of the vocabulary\nfor word in word2Ind:\n    # extract the column corresponding to the index of the word in the vocabulary\n    word_embedding_vector = W3[:, word2Ind[word]]\n    \n    print(f'{word}: {word_embedding_vector}')\n```\n\n    am: [ 0.09752647 -0.05136565  0.19974284]\n    because: [ 0.08665397  0.15459171 -0.03063173]\n    happy: [-0.02389858 -0.15029611 -0.27839106]\n    i: [0.1768788  0.19580601 0.12353994]\n    learning: [ 0.3764029  -0.31673866 -0.04975536]\n\n\nYou're now ready to take on this week's assignment!\n\n### How this practice relates to and differs from the upcoming graded assignment\n\n- In the assignment, for each iteration of training you will use batches of examples instead of a single example. The formulas for forward propagation and backpropagation will be modified accordingly, and you will use cross-entropy cost instead of cross-entropy loss.\n- You will also complete several iterations of training, until you reach an acceptably low cross-entropy cost, at which point you can extract good word embeddings from the weight matrices.\n- After extracting the word embedding vectors, you will use principal component analysis (PCA) to visualize the vectors, which will enable you to perform an intrinsic evaluation of the quality of the vectors, as explained in the lecture.\n", "meta": {"hexsha": "07eb20a66f04d4e15815927a2be9985f35ba9713", "size": 77778, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Natural Language Processing/Course 2 - Natural Language Processing with Probabilistic Models/Assignments/Week 4/Word Embeddings.ipynb", "max_stars_repo_name": "atharvanaphade/deeplearning.ai-courses", "max_stars_repo_head_hexsha": "2c4280b58140b83259b605b515a50c2c871a324b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Natural Language Processing/Course 2 - Natural Language Processing with Probabilistic Models/Assignments/Week 4/Word Embeddings.ipynb", "max_issues_repo_name": "atharvanaphade/deeplearning.ai-courses", "max_issues_repo_head_hexsha": "2c4280b58140b83259b605b515a50c2c871a324b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Natural Language Processing/Course 2 - Natural Language Processing with Probabilistic Models/Assignments/Week 4/Word Embeddings.ipynb", "max_forks_repo_name": "atharvanaphade/deeplearning.ai-courses", "max_forks_repo_head_hexsha": "2c4280b58140b83259b605b515a50c2c871a324b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-06T21:13:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-10T21:31:57.000Z", "avg_line_length": 25.9692821369, "max_line_length": 303, "alphanum_fraction": 0.5174985214, "converted": true, "num_tokens": 13122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27202456289736326, "lm_q2_score": 0.1778108760134381, "lm_q1q2_score": 0.04836892582595275}}
{"text": "<a href=\"https://colab.research.google.com/github/JPA-BERT/jpa-bert.github.io/blob/master/notebooks/2020_0722advanced_tutorial.ipynb\" target=\"_parent\"></a>\n\n# PyTorch tutorial \u306e\u5185\u5bb9\u306b\u3064\u3044\u3066(5)\n\n- date: 2020-0722\n- author: \u6d45\u5ddd\u4f38\u4e00\n\n[https://github.com/pytorch/tutorials/tree/master/beginner_source/nlp](https://github.com/pytorch/tutorials/tree/master/beginner_source/nlp) \u3092\u898b\u308b\u3068\nPyTorch \u3067 \u81ea\u7136\u8a00\u8a9e\u51e6\u7406\u3092\u884c\u3046\u5834\u5408\u306e\u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb\u306f\u4ee5\u4e0b\u3068\u304a\u308a\u3067\u3042\u308b\n\n# Deep Learning for NLP with Pytorch\n\n1. [pytorch_tutorial.py](https://github.com/pytorch/tutorials/blob/master/beginner_source/nlp/pytorch_tutorial.py): \n\t[PyTorch \u5165\u9580 Introduction to PyTorch](https://pytorch.org/tutorials/beginner/nlp/pytorch_tutorial.html)\n\n2. [deep_learning_tutorial.py](https://github.com/pytorch/tutorials/blob/master/beginner_source/nlp/deep_learning_tutorial.py): \n\t[PyTorch \u306b\u3088\u308b\u6df1\u5c64\u5b66\u7fd2 Deep Learning with PyTorch](https://pytorch.org/tutorials/beginner/nlp/deep_learning_tutorial.html)\n\n3. [word_embeddings_tutorial.py](https://github.com/pytorch/tutorials/blob/master/beginner_source/nlp/word_embeddings_tutorial.py): \n\t[\u5358\u8a9e\u57cb\u3081\u8fbc\u307f:\u8a9e\u5f59\u7684\u610f\u5473\u306e\u7b26\u53f7\u5316 Word Embeddings: Encoding Lexical Semantics](https://pytorch.org/tutorials/beginner/nlp/word_embeddings_tutorial.html)\n\n4. [sequence_models_tutorial.py]((https://github.com/pytorch/tutorials/blob/master/beginner_source/nlp/sequence_models_tutorial.py): \n\t[\u7cfb\u5217\u30e2\u30c7\u30eb\u3068 LSTM Sequence Models and Long-Short Term Memory Networks](https://pytorch.org/tutorials/beginner/nlp/sequence_models_tutorial.html)\n\n5. [advanced_tutorial.py]((https://github.com/pytorch/tutorials/blob/master/beginner_source/nlp/advanced_tutorial.py): \n\t[\u52d5\u7684\u610f\u601d\u6c7a\u5b9a\u3068\u53cc\u65b9\u5411 LSTM \u6761\u4ef6\u4ed8\u304d\u78ba\u7387\u5834 Advanced: Making Dynamic Decisions and the Bi-LSTM CRF](https://pytorch.org/tutorials/beginner/nlp/advanced_tutorial.html)\n\n\n\u4ee5\u4e0b\u3067\u306f\uff0c\u3053\u306e\u3046\u3061\u306e 5 \u306b\u3064\u3044\u3066\u89e3\u8aac\u3057\u3066\u3044\u308b\u3002\n\n\n\n```python\n%matplotlib inline\n```\n\n\n# Advanced: Making Dynamic Decisions and the Bi-LSTM CRF\n\n## Dynamic versus Static Deep Learning Toolkits\n\nPytorch is a *dynamic* neural network kit. \nAnother example of a dynamic kit is `Dynet <https://github.com/clab/dynet>`__ (I mention this because working with Pytorch and Dynet is similar. \nIf you see an example in Dynet, it will probably help you implement it in Pytorch). \nThe opposite is the *static* tool kit, which includes Theano, Keras, TensorFlow, etc.\nThe core difference is the following:\n\n* In a static toolkit, you define  a computation graph once, compile it, and then stream instances to it.\n* In a dynamic toolkit, you define a computation graph *for each   instance*. It is never compiled and is executed on-the-fly\n\nWithout a lot of experience, it is difficult to appreciate the difference. One example is to suppose we want to build a deep constituent parser. \nSuppose our model involves roughly the following\nsteps:\n\n* We build the tree bottom up\n* Tag the root nodes (the words of the sentence)\n* From there, use a neural network and the embeddings\n  of the words to find combinations that form constituents. Whenever you\n  form a new constituent, use some sort of technique to get an embedding\n  of the constituent. In this case, our network architecture will depend\n  completely on the input sentence. In the sentence \"The green cat\n  scratched the wall\", at some point in the model, we will want to combine\n  the span $(i,j,r) = (1, 3, \\text{NP})$ (that is, an NP constituent\n  spans word 1 to word 3, in this case \"The green cat\").\n\nHowever, another sentence might be \"Somewhere, the big fat cat scratched the wall\". \nIn this sentence, we will want to form the constituent $(2, 4, NP)$ at some point. \nThe constituents we will want to form will depend on the instance. \nIf we just compile the computation graph once, as in a static toolkit, it will be exceptionally difficult or\nimpossible to program this logic. \nIn a dynamic toolkit though, there isn't just 1 pre-defined computation graph. There can be a new computation graph for each instance, so this problem goes away.\n\nDynamic toolkits also have the advantage of being easier to debug and the code more closely resembling the host language (by that I mean that Pytorch and Dynet look more like actual Python code than Keras or Theano).\n\n## Bi-LSTM Conditional Random Field Discussion\n\n\nFor this section, we will see a full, complicated example of a Bi-LSTM Conditional Random Field for named-entity recognition. \nThe LSTM tagger above is typically sufficient for part-of-speech tagging, but a sequence model like the CRF is really essential for strong performance on NER. \nFamiliarity with CRF's is assumed. Although this name sounds scary, all the model is is a CRF but where an LSTM provides the features. \nThis is an advanced model though, far more complicated than any earlier model in this tutorial. \nIf you want to skip it, that is fine. To see if you're ready, see if you can:\n\n-  Write the recurrence for the viterbi variable at step i for tag k.\n-  Modify the above recurrence to compute the forward variables instead.\n-  Modify again the above recurrence to compute the forward variables in log-space (hint: log-sum-exp)\n\nIf you can do those three things, you should be able to understand the code below. \nRecall that the CRF computes a conditional probability. \nLet $y$ be a tag sequence and $x$ an input sequence of words.\nThen we compute\n\n\\begin{align}P(y|x) = \\frac{\\exp{(\\text{Score}(x, y)})}{\\sum_{y'} \\exp{(\\text{Score}(x, y')})}\\end{align}\n\nWhere the score is determined by defining some log potentials $\\log \\psi_i(x,y)$ such that\n\n\\begin{align}\\text{Score}(x,y) = \\sum_i \\log \\psi_i(x,y)\\end{align}\n\nTo make the partition function tractable, the potentials must look only\nat local features.\n\nIn the Bi-LSTM CRF, we define two kinds of potentials: emission and transition. \nThe emission potential for the word at index $i$ comes from the hidden state of the Bi-LSTM at timestep $i$. \nThe transition scores are stored in a $|T|x|T|$ matrix $\\textbf{P}$, where $T$ is the tag set. \nIn my implementation, $\\textbf{P}_{j,k}$ is the score of transitioning to tag $j$ from tag $k$. So:\n\n\\begin{align}\\text{Score}(x,y) = \\sum_i \\log \\psi_\\text{EMIT}(y_i \\rightarrow x_i) + \\log \\psi_\\text{TRANS}(y_{i-1} \\rightarrow y_i)\\end{align}\n\n\\begin{align}= \\sum_i h_i[y_i] + \\textbf{P}_{y_i, y_{i-1}}\\end{align}\n\nwhere in this second expression, we think of the tags as being assigned unique non-negative indices.\n\nIf the above discussion was too brief, you can check out [`this`](http://www.cs.columbia.edu/%7Emcollins/crf.pdf) write up from Michael Collins on CRFs.\n\n## Implementation Notes\n\nThe example below implements the forward algorithm in log space to compute the partition function, and the viterbi algorithm to decode. \nBackpropagation will compute the gradients automatically for us. \nWe don't have to do anything by hand.\n\nThe implementation is not optimized. If you understand what is going on, you'll probably quickly see that iterating over the next tag in the forward algorithm could probably be done in one big operation. \nI wanted to code to be more readable. \nIf you want to make the relevant change, you could probably use this tagger for real tasks.\n\n\n\n\n```python\n# Author: Robert Guthrie\n\nimport torch\nimport torch.autograd as autograd\nimport torch.nn as nn\nimport torch.optim as optim\n\ntorch.manual_seed(1)\n```\n\nHelper functions to make the code more readable.\n\n\n\n\n```python\ndef argmax(vec):\n    # return the argmax as a python int\n    _, idx = torch.max(vec, 1)\n    return idx.item()\n\n\ndef prepare_sequence(seq, to_ix):\n    idxs = [to_ix[w] for w in seq]\n    return torch.tensor(idxs, dtype=torch.long)\n\n\n# Compute log sum exp in a numerically stable way for the forward algorithm\ndef log_sum_exp(vec):\n    max_score = vec[0, argmax(vec)]\n    max_score_broadcast = max_score.view(1, -1).expand(1, vec.size()[1])\n    return max_score + \\\n        torch.log(torch.sum(torch.exp(vec - max_score_broadcast)))\n```\n\nCreate model\n\n\n\n\n```python\nclass BiLSTM_CRF(nn.Module):\n\n    def __init__(self, vocab_size, tag_to_ix, embedding_dim, hidden_dim):\n        super(BiLSTM_CRF, self).__init__()\n        self.embedding_dim = embedding_dim\n        self.hidden_dim = hidden_dim\n        self.vocab_size = vocab_size\n        self.tag_to_ix = tag_to_ix\n        self.tagset_size = len(tag_to_ix)\n\n        self.word_embeds = nn.Embedding(vocab_size, embedding_dim)\n        self.lstm = nn.LSTM(embedding_dim, hidden_dim // 2,\n                            num_layers=1, bidirectional=True)\n\n        # Maps the output of the LSTM into tag space.\n        self.hidden2tag = nn.Linear(hidden_dim, self.tagset_size)\n\n        # Matrix of transition parameters.  Entry i,j is the score of\n        # transitioning *to* i *from* j.\n        self.transitions = nn.Parameter(\n            torch.randn(self.tagset_size, self.tagset_size))\n\n        # These two statements enforce the constraint that we never transfer\n        # to the start tag and we never transfer from the stop tag\n        self.transitions.data[tag_to_ix[START_TAG], :] = -10000\n        self.transitions.data[:, tag_to_ix[STOP_TAG]] = -10000\n\n        self.hidden = self.init_hidden()\n\n    def init_hidden(self):\n        return (torch.randn(2, 1, self.hidden_dim // 2),\n                torch.randn(2, 1, self.hidden_dim // 2))\n\n    def _forward_alg(self, feats):\n        # Do the forward algorithm to compute the partition function\n        init_alphas = torch.full((1, self.tagset_size), -10000.)\n        # START_TAG has all of the score.\n        init_alphas[0][self.tag_to_ix[START_TAG]] = 0.\n\n        # Wrap in a variable so that we will get automatic backprop\n        forward_var = init_alphas\n\n        # Iterate through the sentence\n        for feat in feats:\n            alphas_t = []  # The forward tensors at this timestep\n            for next_tag in range(self.tagset_size):\n                # broadcast the emission score: it is the same regardless of\n                # the previous tag\n                emit_score = feat[next_tag].view(\n                    1, -1).expand(1, self.tagset_size)\n                # the ith entry of trans_score is the score of transitioning to\n                # next_tag from i\n                trans_score = self.transitions[next_tag].view(1, -1)\n                # The ith entry of next_tag_var is the value for the\n                # edge (i -> next_tag) before we do log-sum-exp\n                next_tag_var = forward_var + trans_score + emit_score\n                # The forward variable for this tag is log-sum-exp of all the\n                # scores.\n                alphas_t.append(log_sum_exp(next_tag_var).view(1))\n            forward_var = torch.cat(alphas_t).view(1, -1)\n        terminal_var = forward_var + self.transitions[self.tag_to_ix[STOP_TAG]]\n        alpha = log_sum_exp(terminal_var)\n        return alpha\n\n    def _get_lstm_features(self, sentence):\n        self.hidden = self.init_hidden()\n        embeds = self.word_embeds(sentence).view(len(sentence), 1, -1)\n        lstm_out, self.hidden = self.lstm(embeds, self.hidden)\n        lstm_out = lstm_out.view(len(sentence), self.hidden_dim)\n        lstm_feats = self.hidden2tag(lstm_out)\n        return lstm_feats\n\n    def _score_sentence(self, feats, tags):\n        # Gives the score of a provided tag sequence\n        score = torch.zeros(1)\n        tags = torch.cat([torch.tensor([self.tag_to_ix[START_TAG]], dtype=torch.long), tags])\n        for i, feat in enumerate(feats):\n            score = score + \\\n                self.transitions[tags[i + 1], tags[i]] + feat[tags[i + 1]]\n        score = score + self.transitions[self.tag_to_ix[STOP_TAG], tags[-1]]\n        return score\n\n    def _viterbi_decode(self, feats):\n        backpointers = []\n\n        # Initialize the viterbi variables in log space\n        init_vvars = torch.full((1, self.tagset_size), -10000.)\n        init_vvars[0][self.tag_to_ix[START_TAG]] = 0\n\n        # forward_var at step i holds the viterbi variables for step i-1\n        forward_var = init_vvars\n        for feat in feats:\n            bptrs_t = []  # holds the backpointers for this step\n            viterbivars_t = []  # holds the viterbi variables for this step\n\n            for next_tag in range(self.tagset_size):\n                # next_tag_var[i] holds the viterbi variable for tag i at the\n                # previous step, plus the score of transitioning\n                # from tag i to next_tag.\n                # We don't include the emission scores here because the max\n                # does not depend on them (we add them in below)\n                next_tag_var = forward_var + self.transitions[next_tag]\n                best_tag_id = argmax(next_tag_var)\n                bptrs_t.append(best_tag_id)\n                viterbivars_t.append(next_tag_var[0][best_tag_id].view(1))\n            # Now add in the emission scores, and assign forward_var to the set\n            # of viterbi variables we just computed\n            forward_var = (torch.cat(viterbivars_t) + feat).view(1, -1)\n            backpointers.append(bptrs_t)\n\n        # Transition to STOP_TAG\n        terminal_var = forward_var + self.transitions[self.tag_to_ix[STOP_TAG]]\n        best_tag_id = argmax(terminal_var)\n        path_score = terminal_var[0][best_tag_id]\n\n        # Follow the back pointers to decode the best path.\n        best_path = [best_tag_id]\n        for bptrs_t in reversed(backpointers):\n            best_tag_id = bptrs_t[best_tag_id]\n            best_path.append(best_tag_id)\n        # Pop off the start tag (we dont want to return that to the caller)\n        start = best_path.pop()\n        assert start == self.tag_to_ix[START_TAG]  # Sanity check\n        best_path.reverse()\n        return path_score, best_path\n\n    def neg_log_likelihood(self, sentence, tags):\n        feats = self._get_lstm_features(sentence)\n        forward_score = self._forward_alg(feats)\n        gold_score = self._score_sentence(feats, tags)\n        return forward_score - gold_score\n\n    def forward(self, sentence):  # dont confuse this with _forward_alg above.\n        # Get the emission scores from the BiLSTM\n        lstm_feats = self._get_lstm_features(sentence)\n\n        # Find the best path, given the features.\n        score, tag_seq = self._viterbi_decode(lstm_feats)\n        return score, tag_seq\n```\n\nRun training\n\n\n\n\n```python\nSTART_TAG = \"<START>\"\nSTOP_TAG = \"<STOP>\"\nEMBEDDING_DIM = 5\nHIDDEN_DIM = 4\n\n# Make up some training data\ntraining_data = [(\n    \"the wall street journal reported today that apple corporation made money\".split(),\n    \"B I I I O O O B I O O\".split()\n), (\n    \"georgia tech is a university in georgia\".split(),\n    \"B I O O O O B\".split()\n)]\n\nword_to_ix = {}\nfor sentence, tags in training_data:\n    for word in sentence:\n        if word not in word_to_ix:\n            word_to_ix[word] = len(word_to_ix)\n\ntag_to_ix = {\"B\": 0, \"I\": 1, \"O\": 2, START_TAG: 3, STOP_TAG: 4}\n\nmodel = BiLSTM_CRF(len(word_to_ix), tag_to_ix, EMBEDDING_DIM, HIDDEN_DIM)\noptimizer = optim.SGD(model.parameters(), lr=0.01, weight_decay=1e-4)\n\n# Check predictions before training\nwith torch.no_grad():\n    precheck_sent = prepare_sequence(training_data[0][0], word_to_ix)\n    precheck_tags = torch.tensor([tag_to_ix[t] for t in training_data[0][1]], dtype=torch.long)\n    print(model(precheck_sent))\n\n# Make sure prepare_sequence from earlier in the LSTM section is loaded\nfor epoch in range(\n        300):  # again, normally you would NOT do 300 epochs, it is toy data\n    for sentence, tags in training_data:\n        # Step 1. Remember that Pytorch accumulates gradients.\n        # We need to clear them out before each instance\n        model.zero_grad()\n\n        # Step 2. Get our inputs ready for the network, that is,\n        # turn them into Tensors of word indices.\n        sentence_in = prepare_sequence(sentence, word_to_ix)\n        targets = torch.tensor([tag_to_ix[t] for t in tags], dtype=torch.long)\n\n        # Step 3. Run our forward pass.\n        loss = model.neg_log_likelihood(sentence_in, targets)\n\n        # Step 4. Compute the loss, gradients, and update the parameters by\n        # calling optimizer.step()\n        loss.backward()\n        optimizer.step()\n\n# Check predictions after training\nwith torch.no_grad():\n    precheck_sent = prepare_sequence(training_data[0][0], word_to_ix)\n    print(model(precheck_sent))\n# We got it!\n```\n\n## Exercise: A new loss function for discriminative tagging\n\nIt wasn't really necessary for us to create a computation graph when doing decoding, since we do not backpropagate from the viterbi path score. \nSince we have it anyway, try training the tagger where the loss function is the difference between the Viterbi path score and the score of the gold-standard path. \nIt should be clear that this function is non-negative and 0 when the predicted tag sequence is the correct tag sequence. This is essentially *structured perceptron*.\n\nThis modification should be short, since Viterbi and score\\_sentence are already implemented. \nThis is an example of the shape of the computation graph *depending on the training instance*. \nAlthough I haven't tried implementing this in a static toolkit, I imagine that it is possible but much less straightforward.\n\nPick up some real data and do a comparison!\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "ab0b39a185448e073ee5a55001203b6547b44d38", "size": 24909, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/05advanced_tutorial.ipynb", "max_stars_repo_name": "JPA-BERT/jpa-bert.github.io", "max_stars_repo_head_hexsha": "d0acda35703d876582b90b80298cfe0fa8590512", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/05advanced_tutorial.ipynb", "max_issues_repo_name": "JPA-BERT/jpa-bert.github.io", "max_issues_repo_head_hexsha": "d0acda35703d876582b90b80298cfe0fa8590512", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/05advanced_tutorial.ipynb", "max_forks_repo_name": "JPA-BERT/jpa-bert.github.io", "max_forks_repo_head_hexsha": "d0acda35703d876582b90b80298cfe0fa8590512", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.536259542, "max_line_length": 262, "alphanum_fraction": 0.5506443454, "converted": true, "num_tokens": 4272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.09807933006122667, "lm_q1q2_score": 0.04827348261557973}}
{"text": "# Exercise 1: Make a function class\n\n\n```python\nclass F:\n    def __init__(self, a, w):\n        self.a, self.w = a, w\n        \n    def __call__(self, x):\n        from math import exp, sin\n        return exp(-self.a * x) * sin(self.w * x)\n    \nf = F(a=1, w=0.1)\nfrom math import pi\nf(pi)\n```\n\n\n\n\n    0.01335383513703555\n\n\n\n\n```python\nf.a = 2\nf(pi)\n```\n\n\n\n\n    0.0005770715401197441\n\n\n\n# Exercise 2: Add a data attribute to a class\n\n\n```python\nclass Account(object):\n    def __init__(self, name, account_number, initial_amount):\n        self.name = name\n        self.no = account_number\n        self.balance = initial_amount\n        self.transactions = 0\n        \n    def deposit(self, amount):\n        self.balance += amount\n        self.transactions += 1\n        \n    def withdraw(self, amount):\n        self.balance -= amount\n        self.transactions += 1\n        \n    def dump(self):\n        print(\"%s, %s, balance: %s, transactions: %d\" % (self.name, self.no, self.balance, self.transactions))\n        \n    @staticmethod\n    def test():\n        a = Account(\"H.P.L.\", \"121344312\", 1000)\n        a.withdraw(3000)\n        a.deposit(20)\n        assert a.transactions == 2\n        \nAccount.test()\n```\n\n# Exercise 3: Add functionality to a class\n\n\n```python\nfrom datetime import datetime as dt\nimport dateutil.parser as dup\n\nclass Account(object):\n    def __init__(self, name, account_number, initial_amount):\n        self._name = name\n        self._no = account_number\n        self._transactions = {str(dt.utcnow()): initial_amount}\n        \n    def deposit(self, amount):\n        self._transactions[str(dt.utcnow())] = amount\n        \n    def withdraw(self, amount):\n        self._transactions[str(dt.utcnow())] = -amount\n        \n    def get_balance(self):\n        return sum(self._transactions.values())\n    \n    def print_transactions(self):\n        for time, amount in self._transactions.items():\n            print(f\"%s: %6.f\" % (dup.parse(time).ctime(), amount))\n        \n    def dump(self):\n        print(\"%s, %s, balance: %s\" % (self._name, self._no, self.get_balance()))\n```\n\n\n```python\nimport time\na = Account(\"Onno\", \"112312535\", 20)\na.deposit(333)\ntime.sleep(1)\na.withdraw(34)\ntime.sleep(1)\na.deposit(90)\ntime.sleep(1)\na.withdraw(100)\ntime.sleep(1)\na.print_transactions()\na.dump()\n```\n\n    Sun Mar 25 18:15:30 2018:     20\n    Sun Mar 25 18:15:30 2018:    333\n    Sun Mar 25 18:15:31 2018:    -34\n    Sun Mar 25 18:15:32 2018:     90\n    Sun Mar 25 18:15:33 2018:   -100\n    Onno, 112312535, balance: 309\n\n\n\n```python\n# time stuff\nimport time\ns = time.time()                                           # seconds since epoch\nprint(s)\nprint(time.ctime())                                       # print current time\nprint(time.ctime(2*s))                                    # print time t\nl = time.localtime(s)                                     # convert seconds to time_struct (local), s is optional\nprint(l)\nprint(time.gmtime(s))                                     # convert seconds to time_struct (adjust to gmt), s is optional\nprint(time.mktime(l))                                     # convert time_struct to seconde (local), s is optional\np = time.strftime(\"time: %a, %d %b %Y %H:%M:%S\", l)       # formatted string from time_struct, l is optional\nprint(p)\nprint(time.strptime(p, \"time: %a, %d %b %Y %H:%M:%S\"))    # make time_struct from formatted string\nprint(time.strptime(time.ctime()))                        # ctime format is default format for strptime\n\nfrom datetime import datetime as dt\nprint(dt.now())     # local datetime\nd = dt.utcnow()     # utc datetime\nprint(d)\nprint(d.ctime())    # print datetime (strftime works as well)\n\nimport dateutil.parser as dup\nd2 = dup.parse(str(d))    # parse datetime from iso string (datetime.strptime works as well)\nprint(d2.ctime())\nprint(d.tzinfo)\nprint(d2.tzinfo)\n```\n\n    1522001734.293254\n    Sun Mar 25 20:15:34 2018\n    Thu Jun 17 14:31:08 2066\n    time.struct_time(tm_year=2018, tm_mon=3, tm_mday=25, tm_hour=20, tm_min=15, tm_sec=34, tm_wday=6, tm_yday=84, tm_isdst=1)\n    time.struct_time(tm_year=2018, tm_mon=3, tm_mday=25, tm_hour=18, tm_min=15, tm_sec=34, tm_wday=6, tm_yday=84, tm_isdst=0)\n    1522001734.0\n    time: Sun, 25 Mar 2018 20:15:34\n    time.struct_time(tm_year=2018, tm_mon=3, tm_mday=25, tm_hour=20, tm_min=15, tm_sec=34, tm_wday=6, tm_yday=84, tm_isdst=-1)\n    time.struct_time(tm_year=2018, tm_mon=3, tm_mday=25, tm_hour=20, tm_min=15, tm_sec=34, tm_wday=6, tm_yday=84, tm_isdst=-1)\n    2018-03-25 20:15:34.301804\n    2018-03-25 18:15:34.301922\n    Sun Mar 25 18:15:34 2018\n    Sun Mar 25 18:15:34 2018\n    None\n    None\n\n\n# Exercise 7.4: Make classes for a rectangle and a triangle\n\n\n```python\nclass Rectangle:\n    def __init__(self, width, height, corner):\n        self.width, self.height, self.corner = width, height, corner\n        \n    def area(self):\n        return self.width * self.height\n    \n    def perimeter(self):\n        return 2*self.width + 2*self.height\n    \n    @staticmethod\n    def test():\n        r = Rectangle(2, 3, (0, 0))\n        import numpy as np\n        assert np.allclose((r.area(), r.perimeter()), (6, 10))\n        \nRectangle.test()\n```\n\n\n```python\nclass Triangle:\n    def __init__(self, vertices):\n        self.x = []; self.y = []\n        for x, y in vertices:\n            self.x.append(x)\n            self.y.append(y)\n            \n    def area(self):\n        x, y = self.x, self.y\n        return 1/2 * sum(abs(x[i - 1]*y[i] - y[i - 1]*x[i]) for i in range(3))\n    \n    def perimeter(self):\n        from math import sqrt\n        x, y = self.x, self.y\n        return sum(sqrt((x[i] - x[i - 1])**2 + (y[i] - y[i - 1])**2) for i in range(3))\n    \n    @staticmethod\n    def test():\n        import numpy as np\n        t = Triangle([(0, 0), (1, 0), (0, 1)])\n        assert np.allclose((t.area(), t.perimeter()), (0.5, 3.414213562373095))\n        \nTriangle.test()\n```\n\n# Exercise 7.5: Make a class for quadratic functions\n\n\n```python\nclass Quadratic:\n    def __init__(self, a, b, c):\n        self.a, self.b, self.c = a, b, c\n    \n    def __call__(self, x):\n        return (self.a * x**2) + self.b*x + self.c\n    \n    def table(self, l, r, n=10):\n        from numpy import linspace\n        print(\"          x |       f(x) \")\n        print(\"------------+------------\")\n        for x in linspace(l, r, n):\n            print(f\" {x:10.6f} | {self(x):10.6f} \")\n            \n    def roots(self):\n        from math import sqrt\n        a, b, c = self.a, self.b, self.c\n        d = -b / 2 / a; e = sqrt(b**2 - 4*a*c)\n        return a + e, a - e\n\nq = Quadratic(1, 2, -3)\nq.table(0, 10)\nprint(\"\\nroots:\", q.roots())\n```\n\n              x |       f(x) \n    ------------+------------\n       0.000000 |  -3.000000 \n       1.111111 |   0.456790 \n       2.222222 |   6.382716 \n       3.333333 |  14.777778 \n       4.444444 |  25.641975 \n       5.555556 |  38.975309 \n       6.666667 |  54.777778 \n       7.777778 |  73.049383 \n       8.888889 |  93.790123 \n      10.000000 | 117.000000 \n    \n    roots: (5.0, -3.0)\n\n\n# Exercise 7.6: Make a class for straight lines\n\n\n```python\nclass Line:\n    def __init__(self, p1, p2):\n        x0, y0 = p1; x1, y1 = p2\n        a = (y1 - y0) / (x1 - x0)\n        self.__class__.__call__ = lambda self, x: y0 + a*(x - x0)\n    \n    @staticmethod\n    def test():\n        import numpy as np\n        line = Line((0, -1), (2, 4))\n        assert np.allclose((line(0.5), line(0), line(1)), (0.25, -1, 1.5))\n        \nLine.test()\n```\n\n# Exercise 7.7: Flexible handling of function arguments\n\n\n```python\nclass Line:\n    def __init__(self, p1, p2):\n        if all(isinstance(p, tuple) for p in (p1, p2)):\n            x0, y0 = p1; x1, y1 = p2\n        elif isinstance(p1, tuple):\n            x0, y0 = p1\n            x1, y1 = x0 + 1, y0 + p2\n        elif isinstance(p2, tuple):\n            x0, y0 = p2\n            x1, y1 = x0 + 1, y0 + p1\n        else:\n            x0, y0 = 0, p1\n            x1, y1 = x0 + 1, y0 + p2\n        a = (y1 - y0) / (x1 - x0)\n        self.__class__.__call__ = lambda self, x: y0 + a*(x - x0)\n    \n    @staticmethod\n    def test():\n        import numpy as np\n        line = Line((0, -1), (2, 4))\n        assert np.allclose((line(0.5), line(0), line(1)), (0.25, -1, 1.5))\n        \n        line = Line((0, -1), 5/2)\n        assert np.allclose((line(0.5), line(0), line(1)), (0.25, -1, 1.5))\n        \n        line = Line(-1, 5/2)\n        assert np.allclose((line(0.5), line(0), line(1)), (0.25, -1, 1.5))\n        \nLine.test()\n```\n\n# Exercise 7.8: Wrap functions in a class\n\n\n```python\nclass LagrangeInterpolation:\n    def __init__(self, xp, yp):\n        self.xp, self.yp = xp, yp\n        \n    def __call__(self, x):\n        x = np.asarray(x)\n        k = arange(len(self.xp))\n        return sum(self.yp[k] * self.L_k(x, k), axis=1)\n\n    def L_k(self, x, k):\n        xp = self.xp\n        i = empty([len(k) - 1, len(k)], dtype=int)\n        for k_ in k:\n            i[:, k_] = np.delete(k, k_)\n        g = x.reshape(-1, 1, 1) - np.resize(xp[i], (x.size, xp[i].shape[0], xp[i].shape[1]))\n        return prod(g / (xp[k] - xp[i]), axis=1)\n    \n    def plot(self):\n        import matplotlib.pyplot as plt\n        xp = self.xp\n        plt.figure()\n        plt.scatter(xp, self.yp)\n        x = linspace(xp[0], xp[-1], 1001)\n        plt.plot(x, self(x))\n        plt.show()\n```\n\n\n```python\nimport numpy as np\nfrom numpy import arange, empty, prod, sum, linspace\nxp = np.linspace(0, 3*np.pi, 15)\nyp = np.sin(xp)\nf = LagrangeInterpolation(xp, yp)\nx = 1.2\nprint(\"p_L(%g)=%g\" % (x, f(x)))\nprint(\"sin(%g)=%g\" % (x, np.sin(x)))\nf.plot()\n```\n\n# Exercise 7.9: Flexible handling of function arguments\n\n\n```python\nclass LagrangeInterpolation:\n    def __init__(self, f, x, n=10):\n        self.xp = np.linspace(x[0], x[1], n)\n        self.yp = f(self.xp)\n        \n    def __call__(self, x):\n        x = np.asarray(x)\n        k = arange(len(self.xp))\n        return sum(self.yp[k] * self.L_k(x, k), axis=1)\n    \n    def L_k(self, x, k):\n        xp = self.xp\n        i = empty([len(k) - 1, len(k)], dtype=int)\n        for k_ in k:\n            i[:, k_] = np.delete(k, k_)\n        g = x.reshape(-1, 1, 1) - np.resize(xp[i], (x.size, xp[i].shape[0], xp[i].shape[1]))\n        return prod(g / (xp[k] - xp[i]), axis=1)\n    \n    def plot(self):\n        import matplotlib.pyplot as plt\n        xp = self.xp\n        plt.figure()\n        plt.scatter(xp, self.yp)\n        x = linspace(xp[0], xp[-1], 1001)\n        plt.plot(x, self(x))\n        plt.show()\n```\n\n\n```python\nfrom numpy import exp, sin, pi\n\ndef myfunction(x):\n    return exp(-x/2.0)*sin(x)\n\nf = LagrangeInterpolation(myfunction, x=[0, 2*pi], n=11)\nf.plot()\n```\n\n# Exercise 7.10: Deduce a class implementation\n\n\n```python\nclass Hello:\n    def __call__(self, x):\n        return f\"Hello, {x}!\"\n    \n    def __str__(self):\n        return \"Hello, World!\"\n    \na = Hello()\nprint(a(\"students\"))\nprint(a)\n```\n\n    Hello, students!\n    Hello, World!\n\n\n# Exercise 7.11: Implement special methods in a classm\n\n\n```python\nclass F:\n    def __init__(self, a, w):\n        self.a, self.w = a, w\n        \n    def __call__(self, x):\n        from math import exp, sin\n        return exp(-self.a * x) * sin(self.w * x)\n    \n    def __str__(self):\n        return \"exp(-self.a * x) * sin(self.w * x)\"\n    \nf = F(a=1, w=0.1)\nfrom math import pi\nf(pi)\n```\n\n\n\n\n    0.01335383513703555\n\n\n\n\n```python\nf.a = 2\nf(pi)\n```\n\n\n\n\n    0.0005770715401197441\n\n\n\n\n```python\nprint(f)\n```\n\n    exp(-self.a * x) * sin(self.w * x)\n\n\n# Exercise 7.12: Make a class for summation of series\n\n\n```python\ndef test_Sum():\n    term = lambda k, x: (-x)**k\n    x = 0.5\n    S = Sum(term, M=0, N=3)\n    \n    assert abs(S(x) - 5/8) < 1e-12\n    assert abs(S.term(k=4, x=x) - term(k=4, x=x)) < 1e-12\n```\n\n\n```python\nclass Sum():\n    def __init__(self, term, M, N):\n        self.term, self.M, self.N = term, M, N\n    \n    def __call__(self, x):\n        return sum(self.term(k, x) for k in range(self.M, self.N + 1))\n    \ntest_Sum()\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.special import factorial\nplt.figure()\nx = np.linspace(-10, 10, 100)\ny = Sum(lambda k, x: (-1)**k / factorial(2*k + 1) * x**(2*k + 1), 0, 10)(x)\nplt.plot(x, y)\nplt.show()\n```\n\n# Exercise 7.13: Apply a numerical differentitation class\n\n\n```python\npwd\n```\n\n\n\n\n    '/Users/onnoeberhard/Desktop/Scientific Python'\n\n\n\n\n```python\nfrom package.Y import Y\nfrom package.Derivative import Derivative\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ny = Y(20)\ndy = Derivative(y.value)\n\nt = np.linspace(0, y.v0/y.g)\nplt.figure()\nplt.plot(t, y.value(t))\nplt.plot(t, dy(t))\nplt.show()\n```\n\n# Exercise 7.14: Implement an addition operator\n\n\n```python\nclass Rope:\n    def __init__(self, knots):\n        self.knots = knots\n        \n    def __add__(self, other):\n        return Rope(self.knots + other.knots + 1)\n    \n    def __str__(self):\n        return str(self.knots)\n```\n\n\n```python\nr1 = Rope(2)\nr2 = Rope(2)\nr3 = r1 + r2\nprint(r3)\n```\n\n    5\n\n\n\n```python\ndef test_Rope():\n    r1 = Rope(2)\n    r2 = Rope(2)\n    r3 = r1 + r2\n    assert r3.knots == 5\n```\n\n# Exercise 7.15: Implement in-place += and -= operators\n\n\n```python\nfrom datetime import datetime as dt\nimport dateutil.parser as dup\n\nclass Account(object):\n    def __init__(self, name, account_number, initial_amount):\n        self._name = name\n        self._no = account_number\n        self._transactions = {str(dt.utcnow()): initial_amount}\n        \n    def __iadd__(self, amount):\n        self._transactions[str(dt.utcnow())] = amount\n        return self\n        \n    def __isub__(self, amount):\n        self._transactions[str(dt.utcnow())] = -amount\n        return self\n        \n    def get_balance(self):\n        return sum(v for v in self._transactions.values())\n    \n    def print_transactions(self):\n        for time, amount in self._transactions.items():\n            print(f\"%s: %6.f\" % (dup.parse(time).ctime(), amount))\n        \n    def __str__(self):\n        return \"%s, %s, balance: %s\" % (self._name, self._no, self.get_balance())\n        \n    def __repr__(self):\n        return f\"Account('{self._name}', {self._no}, {self.get_balance()})\"\n```\n\n\n```python\nimport time\na = Account(\"Onno\", \"112312535\", 20)\na += 333\ntime.sleep(1)\na -= 34\ntime.sleep(1)\na += 90\ntime.sleep(1)\na -= 100\ntime.sleep(1)\na.print_transactions()\nprint(a)\n```\n\n    Sun Mar 25 18:15:36 2018:     20\n    Sun Mar 25 18:15:36 2018:    333\n    Sun Mar 25 18:15:37 2018:    -34\n    Sun Mar 25 18:15:38 2018:     90\n    Sun Mar 25 18:15:39 2018:   -100\n    Onno, 112312535, balance: 309\n\n\n\n```python\nrepr(a)\n```\n\n\n\n\n    \"Account('Onno', 112312535, 309)\"\n\n\n\n\n```python\nb = eval(repr(a))\n```\n\n\n```python\nprint(a)\nprint(b)\n```\n\n    Onno, 112312535, balance: 309\n    Onno, 112312535, balance: 309\n\n\n\n```python\nb == a\n```\n\n\n\n\n    False\n\n\n\n# Exercise 7.16: Implement a class for numerical differentiation\n\n\n```python\ndef test_Central():\n    def f(x):\n        return 1/2 * x**2\n    \n    df = Central(f)\n    x = 2\n    print(df(x))\n    print(x)\n    assert abs(df(x) - x) < 1e-6\n```\n\n\n```python\nclass Central:\n    def __init__(self, f, h=1e-6):\n        self.f, self.h = f, h\n        \n    def __call__(self, x):\n        f, h = self.f, self.h\n        return (f(x + h) - f(x - h)) / 2/h\n```\n\n\n```python\ntest_Central()\n```\n\n    2.0000000000575113\n    2\n\n\n\n```python\nimport sympy as sp\n\ndef table(f, x, h=1e-6):\n    x_list = x\n    x = sp.Symbol('x')\n    df_exact = sp.lambdify(x, sp.diff(f))\n    df_numeric = Central(sp.lambdify(x, f), h=h)\n    print(\"         x |         Error \")\n    print(\"-----------+---------------\")\n    for x in x_list:\n        print(\" {:9.6f} | {:13.6e} \".format(x, df_exact(x) - df_numeric(x)))\n```\n\n\n```python\nx = sp.Symbol('x')\ntable(2*x*sp.cos(2*x) + sp.sin(2*x), np.linspace(-4, 4, 10))\n```\n\n             x |         Error \n    -----------+---------------\n     -4.000000 |  2.290324e-09 \n     -3.111111 | -5.667182e-10 \n     -2.222222 | -9.131380e-10 \n     -1.333333 | -3.966854e-10 \n     -0.444444 |  3.963496e-12 \n      0.444444 |  3.963496e-12 \n      1.333333 | -3.966871e-10 \n      2.222222 | -1.135199e-09 \n      3.111111 | -1.010797e-09 \n      4.000000 |  2.290324e-09 \n\n\n\n```python\nf = lambda x: 2*x*np.cos(2*x) + np.sin(2*x)\nx = np.linspace(-5, 5, 100)\nplt.figure()\nplt.plot(x, f(x))\nplt.show()\n```\n\n# Exercise 7.17: Examine a program\n\n\n```python\nfrom math import *\n\nclass Backward(object):\n    def __init__(self, f, h=1e-9):\n        self.f, self.h = f, h\n    \n    def __call__(self, x):\n        h, f = self.h, self.f\n        return (f(x) - f(x-h))/h    # finite difference\n\ndsin = Backward(sin)\ne = dsin(0) - cos(0); print(\"error:\", e)\ndexp = Backward(exp, h=1e-7)\ne = dexp(0) - exp(0); print(\"error:\", e)\n```\n\n    error: 0.0\n    error: -5.048639195592841e-08\n\n\n# Exercise 7.18: Modify a class for numerical differentiation\n\n\n```python\nclass Derivative(object):\n    def __init__(self, f, h=1E-5):\n        self._f = f\n        self._h = float(h)\n\n    def __call__(self, x):\n        f, h = self._f, self._h\n        return (f(x+h) - f(x))/h\n\n    def set_precision(self, h):\n        self._h = h\n    \n    def get_precision(self):\n        return self._h\n    \ndef test_Derivative():\n    d = Derivative(lambda x: x)\n    d.set_precision(1e-2)\n    assert d.get_precision() == 1e-2\n    \ntest_Derivative()\n```\n\n# Exercise 7.19: Make a class for the Heaviside function\n\n\n```python\nclass Heaviside():\n    import numpy as np\n    \n    def __init__(self, eps=None):\n        self.eps = eps\n    \n    def __call__(self, x):\n        eps = self.eps\n        \n        if eps:\n            from numpy import sin, pi\n            y = 0\n            y = np.where((-eps <= x) & (x < eps), (1 + x/eps + sin(pi * x / eps)/pi) / 2, y)\n            y = np.where(x >= eps, 1, y)\n        else:\n            y = 1 * (x >= 0)\n        \n        return y\n\n    def plot(self, xmin, xmax):\n        import matplotlib.pyplot as plt\n        \n        plt.figure()\n        x = np.linspace(xmin, xmax, 200)\n        plt.plot(x, self(x))\n        plt.show()\n```\n\n\n```python\nH = Heaviside()\nH(0.1)\n```\n\n\n\n\n    1\n\n\n\n\n```python\nH = Heaviside(eps=0.8)\nH(0.1)\n```\n\n\n\n\n    array(0.623405959900277)\n\n\n\n\n```python\nH = Heaviside()\nx = np.linspace(-1, 1, 11)\nH(x)\n```\n\n\n\n\n    array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1])\n\n\n\n\n```python\nH = Heaviside(eps=0.8)\nH(x)\n```\n\n\n\n\n    array([  0.00000000e+00,  -1.94908592e-17,   1.24604605e-02,\n             9.08450569e-02,   2.62460460e-01,   5.00000000e-01,\n             7.37539540e-01,   9.09154943e-01,   9.87539540e-01,\n             1.00000000e+00,   1.00000000e+00])\n\n\n\n\n```python\nH = Heaviside(eps=1)\nH.plot(xmin=-4, xmax=4)\n```\n\n# Exercise 7.20: Make a class for the indicator function\n\n\n```python\nclass Indicator():\n    import numpy as np\n    \n    def __init__(self, a, b, eps=None):\n        self.eps, self.a, self.b = eps, a, b\n    \n    def __call__(self, x):\n        H = Heaviside(self.eps)\n        y = H(x - self.a) * H(-(x - self.b))\n        return y\n\n    def plot(self, xmin, xmax):\n        import matplotlib.pyplot as plt\n        \n        plt.figure()\n        x = np.linspace(xmin, xmax, 200)\n        plt.plot(x, self(x))\n        plt.show()\n```\n\n\n```python\nI = Indicator(-2, 3, eps=1)\nI.plot(-5, 6)\n```\n\n# Exercise 7.21: Make a class for piecewise constant functions\n\n\n```python\nclass PiecewiseConstant():\n    import numpy as np\n    \n    def __init__(self, points, xmax):\n        self.points, self.xmax = points, xmax\n        \n    def __call__(self, x):\n        y = np.nan\n        for v, xi in self.points:\n            y = np.where((xi <= x) & (x < self.xmax), v, y)\n        return y\n    \n    def plot(self):\n        import matplotlib.pyplot as plt\n        \n        plt.figure()\n        x = np.linspace(self.points[0][1], self.xmax, 1000)\n        plt.plot(x, self(x))\n        plt.show()\n```\n\n\n```python\nf = PiecewiseConstant([(0.4, 1), (0.2, 1.5), (0.1, 3)], xmax=4)\nprint(f(1.5), f(1.75), f(4))\nx = np.linspace(0, 4, 21)\nprint(f(x))\n```\n\n    0.2 0.2 nan\n    [ nan  nan  nan  nan  nan  0.4  0.4  0.4  0.2  0.2  0.2  0.2  0.2  0.2  0.2\n      0.1  0.1  0.1  0.1  0.1  nan]\n\n\n\n```python\nf.plot()\n```\n\n# Exercise 7.22: Speed up repeated integral calculations\n\n\n```python\nclass Integral(object):\n    def __init__(self, f, a, n=100):\n        self.f, self.a, self.n = f, a, n\n    \n    def __call__(self, x):\n        if isinstance(x, np.ndarray):\n            nk = int(self.n / len(x))\n            I = [trapezoidal(self.f, self.a, x[0], nk)]\n            for i, xi in enumerate(x[1:]):\n                I.append(I[i] + trapezoidal(self.f, x[i], xi, nk))\n            return I\n        else:\n            return trapezoidal(self.f, self.a, x, self.n)\n\ndef trapezoidal(f, a, x, n):\n    dx = (x - a) / n\n    I = dx / 2 * sum(f(a + (k - 1)*dx) + f(a + k*dx) for k in range(n))\n    return I\n```\n\n\n```python\nfrom numpy import sin, pi\nI = Integral(sin, 0, n=1000)\nI(np.array([pi/2, pi, 3/2*pi, 2*pi]))\n```\n\n\n\n\n    [0.99369384775594749,\n     1.999953942101556,\n     1.0062600943456086,\n     -2.2204460492503131e-16]\n\n\n\n# Exercise 7.23: Apply a class for polynomials\n\n\n```python\nclass Polynomial(object):\n    def __init__(self, coefficients):\n        self.coeff = coefficients\n        \n    def __call__(self, x):\n        \"\"\"Evaluate the polynomial.\"\"\" \n        s = 0 \n        for i, c in enumerate(self.coeff):\n            s += c*x**i\n        return s\n    \n    def __add__(self, other):\n        \"\"\"Return self + other as Polynomial object.\"\"\" \n        \n        # Start with the longest list and add in the other\n        if len(self.coeff) > len(other.coeff):\n            result_coeff = self.coeff[:]  # copy!\n            for i in range(len(other.coeff)):\n                result_coeff[i] += other.coeff[i]\n        else:\n            result_coeff = other.coeff[:] # copy!\n            for i in range(len(self.coeff)):\n                result_coeff[i] += self.coeff[i]\n        \n        return Polynomial(result_coeff)\n```\n\n\n```python\ndef evaluate(x, N):\n    from math import factorial\n    coef = [1/factorial(k) for k in range(N + 1)]\n    p = Polynomial(coef)\n    print(f\"N: {N:2d}, p({x:05.2f}) = {p(x):f}\")\n```\n\n\n```python\nfrom math import exp\nfor x in [0.5, 3, 10]:\n    print(\"exact:\", exp(x))\n    for N in [2, 5, 10, 15, 20, 25]:\n        evaluate(x, N)\n```\n\n    exact: 1.6487212707001282\n    N:  2, p(00.50) = 1.625000\n    N:  5, p(00.50) = 1.648698\n    N: 10, p(00.50) = 1.648721\n    N: 15, p(00.50) = 1.648721\n    N: 20, p(00.50) = 1.648721\n    N: 25, p(00.50) = 1.648721\n    exact: 20.085536923187668\n    N:  2, p(03.00) = 8.500000\n    N:  5, p(03.00) = 18.400000\n    N: 10, p(03.00) = 20.079665\n    N: 15, p(03.00) = 20.085534\n    N: 20, p(03.00) = 20.085537\n    N: 25, p(03.00) = 20.085537\n    exact: 22026.465794806718\n    N:  2, p(10.00) = 61.000000\n    N:  5, p(10.00) = 1477.666667\n    N: 10, p(10.00) = 12842.305115\n    N: 15, p(10.00) = 20952.886969\n    N: 20, p(10.00) = 21991.482026\n    N: 25, p(10.00) = 22026.076361\n\n\n# Exercise 7.24: Find a bug in a class for polynomials\n\n\n```python\nclass Polynomial(object):\n    def __init__(self, coefficients):\n        self.coeff = coefficients\n        \n    def __call__(self, x):\n        return sum([c*x**i for i, c in enumerate(self.coeff)])\n    \n    def __add__(self, other):\n        maxlength = max(len(self.coeff), len(other.coeff))\n        # Extend both lists with zeros to this maxlength\n        self.coeff += [0]*(maxlength - len(self.coeff))\n        other.coeff += [0]*(maxlength - len(other.coeff))\n        result_coeff = self.coeff\n        for i in range(maxlength):\n            result_coeff[i] += other.coeff[i]\n        return Polynomial(result_coeff)\n```\n\n\n```python\np1 = Polynomial([1, 2, 3])\np2 = Polynomial([0, 4, 0])\n(p1 + p2)(3)\n```\n\n\n\n\n    46\n\n\n\n# Exercise 7.25: Implement subtraction of polynomials\n\n\n```python\nclass Polynomial(object):\n    def __init__(self, coefficients):\n        self.coeff = coefficients\n        \n    def __call__(self, x):\n        return sum([c*x**i for i, c in enumerate(self.coeff)])\n    \n    def __add__(self, other):\n        maxlength = max(len(self.coeff), len(other.coeff))\n        # Extend both lists with zeros to this maxlength\n        self.coeff += [0]*(maxlength - len(self.coeff))\n        other.coeff += [0]*(maxlength - len(other.coeff))\n        result_coeff = self.coeff\n        for i in range(maxlength):\n            result_coeff[i] += other.coeff[i]\n        return Polynomial(result_coeff)\n    \n    def __sub__(self, other):\n        from copy import copy\n        other_ = copy(other)\n        other_.coeff = [-c for c in other_.coeff]\n        return self.__add__(other_)\n    \n    def __str__(self):\n        s = \"\"\n        for i in range(0, len(self.coeff)):\n            if self.coeff[i] != 0:\n                s += \" + %g*x^%d\" % (self.coeff[i], i)\n        # Fix layout\n        s = s.replace(\"+ -\", \"- \")\n        s = s.replace(\"x^0\", \"1\")\n        s = s.replace(\" 1*\", \" \")\n        s = s.replace(\"x^1 \", \"x \")\n        if s[0:3] == \" + \":  # remove initial +\n            s = s[3:]\n        if s[0:3] == \" - \":  # fix spaces for initial -\n            s = \"-\" + s[3:]\n        return s\n```\n\n\n```python\np1 = Polynomial([1, 2, 3])\np2 = Polynomial([0, 4, 0])\n(p1 - p2).coeff\n```\n\n\n\n\n    [1, -2, 3]\n\n\n\n# Exercise 7.26: Test the functionality of pretty print of polynomials\n\n\n```python\nprint(p1 - p2)    # looks fine.\n```\n\n    1 - 6*x + 3*x^2\n\n\n# Exercise 7.27: Vectorize a class for polynomials\n\n\n```python\nclass Polynomial(object):\n    import numpy as np\n    \n    def __init__(self, coefficients):\n        self.coeff = np.asarray(coefficients)\n        \n    def __call__(self, x):\n        return self.coeff @ x**np.arange(len(self.coeff))\n    \n    def __add__(self, other):\n        coeffs = sorted([self.coeff, other.coeff], key=len)\n        r = coeffs[0] + coeffs[1][:len(coeffs[0])]\n        r = np.append(r, coeffs[1][len(r):])\n        return Polynomial(r)\n    \n    def __sub__(self, other):\n        from copy import copy\n        other_ = copy(other)\n        other_.coeff = [-c for c in other_.coeff]\n        return self.__add__(other_)\n    \n    def __str__(self):\n        s = \"\"\n        for i in range(0, len(self.coeff)):\n            if self.coeff[i] != 0:\n                s += \" + %g*x^%d\" % (self.coeff[i], i)\n        # Fix layout\n        s = s.replace(\"+ -\", \"- \")\n        s = s.replace(\"x^0\", \"1\")\n        s = s.replace(\" 1*\", \" \")\n        s = s.replace(\"x^1 \", \"x \")\n        if s[0:3] == \" + \":  # remove initial +\n            s = s[3:]\n        if s[0:3] == \" - \":  # fix spaces for initial -\n            s = \"-\" + s[3:]\n        return s\n```\n\n\n```python\np1 = Polynomial([1, 2, 3, 5, 7])\np2 = Polynomial([0, 4, 0, 1])\n(p1 + p2).coeff\n```\n\n\n\n\n    array([1, 6, 3, 6, 7])\n\n\n\n\n```python\n(p1 + p2)(2)\n```\n\n\n\n\n    185\n\n\n\n# Exercise 7.28: Use a dict to hold polynomial coefficients\n\n\n```python\nclass Polynomial:\n    import numpy as np\n    \n    def __init__(self, coefficients):\n        self.coeff = coefficients\n        \n    def __call__(self, x):\n        return sum(c * x**i for i, c in self.coeff.items())\n    \n    def __add__(self, other):\n        cs = self.coeff.copy()\n        for c in other.coeff:\n            if c in cs:\n                cs[c] += other.coeff[c]\n            else:\n                cs[c] = other.coeff[c]\n        return Polynomial(cs)\n    \n    def __sub__(self, other):\n        from copy import copy\n        other_ = copy(other)\n        other_.coeff = {k: -c for k, c in other_.coeff.items()}\n        return self.__add__(other_)\n    \n    def __mul__(self, other):\n        from collections import defaultdict\n        cs = defaultdict(float)\n        for i, c in self.coeff.items():\n            for ii, cc in other.coeff.items():\n                cs[i + ii] += c * cc\n        return Polynomial(dict(cs))\n    \n    @staticmethod\n    def test():\n        # test __call__\n        p1 = Polynomial({4: 1, 2: -2, 0: 3})\n        assert abs(p(2) - 11) < 1e-12\n        \n        # test __add__\n        p2 = Polynomial({0: 1, 3: 1})\n        p3 = p1 + p2\n        assert set(p3.coeff.keys()) == {0, 2, 3, 4}\n        assert np.allclose([p3.coeff[k] for k in sorted(p3.coeff)], [4, -2, 1, 1])\n        \n        # test __mul__\n        p4 = Polynomial({1: -2, 2: 3})\n        p5 = p2 * p4\n        assert set(p5.coeff.keys()) == {1, 2, 4, 5}\n        assert np.allclose([p5.coeff[k] for k in sorted(p5.coeff)], [-2, 3, -2, 3])\n```\n\n\n```python\np = Polynomial({4: 1, 2: -2, 0: 3})\np(2)\n```\n\n\n\n\n    11\n\n\n\n\n```python\np1 = Polynomial({0: 1, 3: 1})\np2 = Polynomial({1: -2, 2: 3})\n(p1 * p2).coeff\n```\n\n\n\n\n    {1: -2.0, 2: 3.0, 4: -2.0, 5: 3.0}\n\n\n\n\n```python\nPolynomial.test()\n```\n\n# Exercise 7.29: Extend class Vec2D to work with lists/tuples\n\n\n```python\nclass Vec2D:\n    def __init__(self, x, y):\n        self.x = x\n        self.y = y\n    \n    def __add__(self, other):\n        if isinstance(other, Vec2D):\n            return Vec2D(self.x + other.x, self.y + other.y)\n        else:\n            return Vec2D(self.x + other[0], self.y + other[1])\n        \n    def __radd__(self, other):\n        return self.__add__(other)\n    \n    def __sub__(self, other):\n        if isinstance(other, Vec2D):\n            return Vec2D(self.x - other.x, self.y - other.y)\n        else:\n            return Vec2D(self.x - other[0], self.y - other[1])\n        \n    def __rsub__(self, other):\n        if isinstance(other, Vec2D):\n            return Vec2D(other.x - self.x, other.y - self.y)\n        else:\n            return Vec2D(other[0] - self.x, other[1] - self.y)\n    \n    def __mul__(self, other):\n        return self.x*other.x + self.y*other.y\n    \n    def __abs__(self):\n        return math.sqrt(self.x**2 + self.y**2)\n    \n    def __eq__(self, other):\n        return self.x == other.x and self.y == other.y\n    \n    def __str__(self):\n        return \"(%g, %g)\" % (self.x, self.y)\n```\n\n\n```python\nu = Vec2D(-2, 4)\nv = u + (1, 1.5)\nw = [-3, 2] - v\n```\n\n# Exercise 7.30: Extend class Vec2D to 3D vectors\n\n\n```python\nclass Vec3D:\n    def __init__(self, x, y, z):\n        self.x = x\n        self.y = y\n        self.z = z\n    \n    def __add__(self, other):\n        return Vec3D(self.x + other.x, self.y + other.y, self.z + other.z)\n    \n    def __sub__(self, other):\n        return Vec3D(self.x - other.x, self.y - other.y, self.z - other.z)\n    \n    def __mul__(self, other):\n        return self.x*other.x + self.y*other.y + self.z*other.z\n    \n    def __abs__(self):\n        return math.sqrt(self.x**2 + self.y**2 + self.z**2)\n    \n    def __eq__(self, other):\n        return self.x == other.x and self.y == other.y and self.z == other.z\n    \n    def __str__(self):\n        return \"(%g, %g, %g)\" % (self.x, self.y, self.z)\n    \n    def cross(self, other):\n        return Vec3D(self.y*other.z - self.z*other.y, self.z*other.x - self.x*other.z, self.x*other.y - self.y*other.x)\n```\n\n\n```python\nprint(Vec3D(0, 1, 0).cross(Vec3D(1, 0, 0)))\n```\n\n    (0, 0, -1)\n\n\n# Exercise 7.31: Use NumPy arrays in class Vec2D\n\n\n```python\nclass Vec:\n    import math\n        \n    def __init__(self, *vec):\n        self.v = np.asarray(vec).flatten()\n    \n    def __add__(self, other):\n        return Vec(self.v + other.v)\n    \n    def __sub__(self, other):\n        return Vec(self.v - other.v)\n    \n    def __mul__(self, other):\n        return self.v @ other.v\n    \n    def __abs__(self):\n        return math.sqrt(sum(c**2 for c in self.v))\n    \n    def __eq__(self, other):\n        return (self.v == other.v).all()\n```\n\n\n```python\nv1 = v2 = Vec([1, 2, 3])\nv1 * v2\n```\n\n\n\n\n    14\n\n\n\n# Exercise 7.32: Impreciseness of interval arithmetics\n\n\n```python\nclass Interval(object):\n    def __init__(self, lower, upper):\n        self.lo = float(lower)\n        self.up = float(upper)\n    \n    def __add__(self, other):\n        if not isinstance(other, Interval):\n            other = Interval(other, other)\n        a, b, c, d = self.lo, self.up, other.lo, other.up\n        return Interval(a + c, b + d)\n    \n    def __radd__(self, other):\n        return self.__add__(other)\n    \n    def __sub__(self, other):\n        a, b, c, d = self.lo, self.up, other.lo, other.up\n        return Interval(a - d, b - c)\n    \n    def __mul__(self, other):\n        a, b, c, d = self.lo, self.up, other.lo, other.up\n        return Interval(min(a*c, a*d, b*c, b*d), max(a*c, a*d, b*c, b*d))\n    \n    def __truediv__(self, other):\n        a, b, c, d = self.lo, self.up, other.lo, other.up\n        if c * d <= 0: \n            raise ValueError(\"Interval %s cannot be denominator because it contains zero\" % other)\n        return Interval(min(a/c, a/d, b/c, b/d), max(a/c, a/d, b/c, b/d))\n    \n    def __str__(self):\n        return \"[%g, %g]\" % (self.lo, self.up)\n```\n\n\n```python\nx = Interval(1, 2)\nprint(x / (1 + x))\n```\n\n    [0.333333, 1]\n\n\n# Exercise 7.33: Make classes for students and courses\n\n\n```python\nclass Student:\n    def __init__(self, name, courses):\n        self.__dict__.update({k: v for k, v in locals().items() if k != 'self'})\n        \n    def __str__(self):\n        s = f\"Name: {self.name}\\n\"\n        for c in self.courses:\n            s += str(c) + \"\\n\"\n        return s\n\nclass Course:\n    def __init__(self, title, semester, credits, grade):\n        self.__dict__.update({k: v for k, v in locals().items() if k != 'self'})\n        \n    def __str__(self):\n        return f\"{self.title:30} {self.semester:11} {self.credits:2} {self.grade}\"\n```\n\n\n```python\nprint(Student(\"John Doe\", [Course(\"Astronomy\", \"2003 fall\", 10, \"A\"), \n                           Course(\"Quantum Mechanics II\", \"2005 spring\", 5, \"C\")]))\n```\n\n    Name: John Doe\n    Astronomy                      2003 fall   10 A\n    Quantum Mechanics II           2005 spring  5 C\n    \n\n\n# Exercise 7.34: Find local and global extrema of a function\n\n\n```python\nclass MinMax:\n    import numpy as np\n    \n    def __init__(self, f, a, b, n):\n        self.__dict__.update({k: v for k, v in locals().items() if k != 'self'})\n        self._find_extrema()\n        \n    def _find_extrema(self):\n        f, a, b = self.f, self.a, self.b\n        \n        self.Pmin, self.Pmax, self.Fmin, self.Fmax = Pmin, Pmax, Fmin, Fmax = [], [], [], []\n        \n        x = np.linspace(a, b, self.n)\n        for i, xi in enumerate(x[1:-1]):\n            if f(x[i]) < f(xi) > f(x[i + 2]):\n                Pmax.append(xi)\n                Fmax.append(f(xi))\n            elif f(x[i]) > f(xi) < f(x[i + 2]):\n                Pmin.append(xi)\n                Fmin.append(f(xi))\n                \n        if f(a) > f(x[1]):\n            Pmax.insert(1, a)\n            Fmax.insert(1, f(a))\n        elif f(a) < f(x[1]):\n            Pmin.insert(1, a)\n            Fmin.insert(1, f(a))\n        if f(b) > f(x[-2]):\n            Pmax.append(b)\n            Fmax.append(f(b))\n        elif f(b) < f(x[-2]):\n            Pmin.append(b)\n            Fmin.append(f(b))\n                    \n    def _refine_extrema(self):\n        f, a, b, n = self.f, self.a, self.b, self.n\n        Pmin, Pmax, Fmin, Fmax = self.Pmin, self.Pmax, self.Fmin, self.Fmax\n        for i, p in enumerate(Pmin):\n            if p != a and p != b:\n                df = Derivative(f, h= (b - a) / n**2 / 1000)\n                xmin, dfmin = p, df(p)\n                for x in np.linspace(p - (b - a)/n, p + (b - a)/n, n):    # just reuse `n` as precision basis\n                    if df(x) < dfmin:\n                        xmin, dfmin = x, df(x)\n                Pmin[i] = xmin\n                Fmin[i] = f(xmin)\n                \n        for i, p in enumerate(Pmax):\n            if p != a and p != b:\n                df = Derivative(f, h= (b - a) / n**2 / 1000)\n                xmax, dfmin = p, df(p)\n                for x in np.linspace(p - (b - a)/n, p + (b - a)/n, n):    # just reuse `n` as precision basis\n                    if df(x) < dfmin:\n                        xmax, dfmin = x, df(x)\n                Pmax[i] = xmax\n                Fmax[i] = f(xmax)\n                \n    \n    def get_global_minimum(self):\n        return min(self.get_all_minima(), key=lambda t: t[1])\n            \n    def get_global_maximum(self):\n        return max(self.get_all_maxima(), key=lambda t: t[1])\n    \n    def get_all_minima(self):\n        return [(x, y) for x, y in zip(self.Pmin, self.Fmin)]\n    \n    def get_all_maxima(self):\n        return [(x, y) for x, y in zip(self.Pmax, self.Fmax)]\n    \n    def __str__(self):\n        from textwrap import dedent as dd\n        return dd(f\"\"\"\n        All minima: {', '.join(f'{p:.4f}' for p, v in self.get_all_minima())}\n        All maxima: {', '.join(f'{p:.4f}' for p, v in self.get_all_maxima())}\n        Global minimum: {self.get_global_minimum()[0]}\n        Global maximum: {self.get_global_maximum()[0]}\n        \"\"\")\n```\n\n\n```python\nfrom math import exp, sin, pi\nmm = MinMax(f=lambda x: x**2 * exp(-0.2 * x) * sin(2 * pi * x), a=0, b=4, n=5001)\nprint(mm)\nmm._refine_extrema()\nprint(mm)\n```\n\n    \n    All minima: 0.8056, 0.0000, 1.7736, 2.7632, 3.7584\n    All maxima: 0.3616, 1.2840, 2.2672, 3.2608, 4.0000\n    Global minimum: 3.7584\n    Global maximum: 3.2608\n    \n    \n    All minima: 0.8048, 0.0000, 1.7728, 2.7624, 3.7576\n    All maxima: 0.3624, 1.2848, 2.2680, 3.2616, 4.0000\n    Global minimum: 3.7576001599680064\n    Global maximum: 3.2615998400319937\n    \n\n\n# Exercise 7.35: Find the optimal production for a company\n\n\n```python\nf = lambda x, y: 45*x + 14*y\nfa = lambda x, alpha: alpha/14 - 45*x/14\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nfrom numpy import linspace\nx = linspace(0, 20, 1000)\nplt.figure()\nplt.fill_between(x, 100 - 2*x, alpha=0.3)\nplt.fill_between(x, 80/3 - 5/3*x, alpha=0.3)\nplt.fill_between(x, 150/4, alpha=0.3)\nfor alpha in [1, 100, 1000, 500, 700]:\n    plt.plot(x, fa(x, alpha), label=f\"alpha = {alpha}\")\nplt.ylabel(\"y\")\nplt.xlabel(\"x\")\nplt.legend()\nplt.show()\n```\n\n\n```python\nf(x=16, y=0)    # optimal solution.\n```\n\n\n\n\n    720\n\n\n\n\n```python\nimport sympy as sp\nx, y = sp.symbols('x y')\n\nconditions = [\n    \"2*x +   y <= 100\",\n    \"5*x + 3*y <=  80\",\n    \"      4*y <= 150\",\n    \"  x       >=   0\",\n    \"        y >=   0\"\n]\n\n\n# Compute the intersections\nintersections = []\neqs = [\n    sp.Eq(eval(a), eval(b)) for a, b in \n        [e.split(\"=\") for e in \n            [c.replace(\"<=\", \"=\").replace(\">=\", \"=\") for c in conditions]\n]]\n\nfor e1 in eqs:\n    for e2 in eqs:\n        i = sp.solve([e1, e2])\n        if len(i) > 1 and i not in intersections:\n            intersections.append(i)\n        \n        \n# Check conditions on intersections\ncorners = []\n\nfor i in intersections:\n    corners.append(tuple(i.values()))\n    x, y = sp.symbols('x y')\n    x, y = i[x], i[y]\n    for c in conditions:\n        if not eval(c):\n            del corners[-1]\n            break\n```\n\n\n```python\ncorners\n```\n\n\n\n\n    [(0, 80/3), (16, 0), (0, 0)]\n\n\n\n\n```python\nf = lambda c: 45*c[0] + 14*c[1]\nx, y = max(corners, key=f)\nprint(x, y)    # yay!\n```\n\n    16 0\n\n", "meta": {"hexsha": "77d20c267e0e21f455aaf0dd884049f9b1e0608c", "size": 208688, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Exercises 7.ipynb", "max_stars_repo_name": "onnoeberhard/scipro-primer-notebooks", "max_stars_repo_head_hexsha": "e9cf1069d62f8c50549d9912403c640f08a99392", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2019-04-18T13:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T21:01:06.000Z", "max_issues_repo_path": "Exercises 7.ipynb", "max_issues_repo_name": "onnoeberhard/scipro-primer-notebooks", "max_issues_repo_head_hexsha": "e9cf1069d62f8c50549d9912403c640f08a99392", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-15T16:26:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-15T16:26:00.000Z", "max_forks_repo_path": "Exercises 7.ipynb", "max_forks_repo_name": "onnoeberhard/scipro-primer-notebooks", "max_forks_repo_head_hexsha": "e9cf1069d62f8c50549d9912403c640f08a99392", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2018-09-30T07:35:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-28T19:15:09.000Z", "avg_line_length": 78.1895841139, "max_line_length": 24666, "alphanum_fraction": 0.7852967109, "converted": true, "num_tokens": 12494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3007455789412415, "lm_q2_score": 0.16026603032235007, "lm_q1q2_score": 0.04819930007390973}}
{"text": "```javascript\n%%javascript\n    MathJax.Hub.Config({\n      TeX: { equationNumbers: { autoNumber: \"AMS\" } }\n    });\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n```python\nfrom IPython.display import HTML\n\nHTML('''\n<form action=\"javascript:code_toggle()\"><input type=\"submit\" value=\"Code Toggle\"></form>''')\n```\n\n\n\n\n\n<form action=\"javascript:code_toggle()\"><input type=\"submit\" value=\"Code Toggle\"></form>\n\n\n\n\n```python\nfrom IPython.display import HTML\n\nHTML('''\n<a href=\"https://github.com/usnistgov/pfhub/raw/master/benchmarks/benchmark8.ipynb\"\n   download>\n<button type=\"submit\">Download Notebook</button>\n</a>\n''')\n```\n\n\n\n\n\n<a href=\"https://github.com/usnistgov/pfhub/raw/master/benchmarks/benchmark8.ipynb\"\n   download>\n<button type=\"submit\">Download Notebook</button>\n</a>\n\n\n\n\n# Benchmark Problem 8: Homogeneous Nucleation\n\n\n```python\nfrom IPython.display import HTML\n\nHTML('''{% include jupyter_benchmark_table.html num=\"[8]\" revision=1 %}''')\n```\n\n\n\n\n{% include jupyter_benchmark_table.html num=\"[8]\" revision=1 %}\n\n\n\nSee the journal publication entitled [\"Phase Field Benchmark Problems for Nucleation\"][paper] for more details about the benchmark problems. Furthermore, read [the extended essay][benchmarks] for a discussion about the need for benchmark problems.\n\n[benchmarks]: ../\n[paper]: https://doi.org/10.1016/j.commatsci.2021.110371\n\n# Table of Contents\n\n* [Overview](#Overview)\n* [Model Formulation](#Model-Formulation)\n\t* [The phase field model in classical nucleation theory](#The-phase-field-model-in-classical-nucleation-theory)\n\t* [The properties of the classical nucleus](#The-properties-of-the-classical-nucleus)\n\t* [Avrami plots](#Avrami-plots)\n* [Benchmark 8 Specification](#Benchmark-8-Specification)\n\t* [Part (a): single seed](#Part-%28a%29:-single-seed)\n    * [Part (b): multiple initial seeds](#Part-%28b%29:-multiple-initial-seeds)\n    * [Part (c): multiple seeds at random times](#Part-%28c%29:-multiple-seeds-at-random-times)\n* [Submission Guidelines](#Submission-Guidelines)\n\t* [Part (a)](#Part-%28a%29)\n\t* [Part (b)](#Part-%28b%29)\n\t* [Part (c)](#Part-%28c%29)\n* [Results](#Results)\n* [References](#References)\n\n\n## Overview\n\nPhase field modeling of nucleation has a long history and is covered\nin a number of reviews (<a id=\"ref-1\" href=\"#cite-granasy2002nucleation\">Gr\u00e1n\u00e1sy 2002</a>,\n<a id=\"ref-2\" href=\"#cite-castro2003phase\">Castro 2003</a>,\n<a id=\"ref-3\" href=\"#cite-simmons2004microstructural\">Simmons 2004</a>,\n<a id=\"ref-4\" href=\"#cite-granasy2007phase\">Gr\u00e1n\u00e1sy 2007</a>,\n<a id=\"ref-5\" href=\"#cite-warren2009phase\">Warren 2009</a>,\n<a id=\"ref-6\" href=\"#cite-heo2014phase\">Heo 2014</a>,\n<a id=\"ref-7\" href=\"#cite-granasy2019\">Gr\u00e1n\u00e1sy 2019</a>). The problem formulation of crystallization of an ideal pure liquid cooled\nbelow its melting point starts with homogeneous nucleation, a process\nin which the internal fluctuations of the undercooled liquid lead to\nthe formation of crystal-like seeds able to grow to macroscopic\nsizes. The nucleation can be assisted by the presence of surfaces\n(container walls, foreign particles, etc.), in which case the process\nis termed heterogeneous nucleation. We note that homogeneous\nnucleation is an idealized formulation, and it is unlikely homogeneous\nnucleation occurs, due to impurities present in experimental\napparatus. However, creating benchmark problems for homogeneous\nnucleation is still needed since the focus in nucleation research\noften lies on the underlying homogeneous nucleation, as it is the\nbasis for advancing theoretical approaches to the much more complex\nphenomena governing heterogeneous nucleation. This benchmark\n(benchmark 8) targets homogeneous nucleation while benchmark 9\ntargets heterogeneous nucleation.\n\nThere are two main modeling approaches to introduce nuclei into a\nmetastable system: the Langevin noise method\n(<a id=\"ref-8\" href=\"#cite-kubo1966\">Kubo 1966</a>,\n<a id=\"ref-9\" href=\"#cite-granasy2002nucleation\">Gr\u00e1n\u00e1sy 2002</a>)\nand the explicit nucleation\nmethod\n(<a id=\"ref-10\" href=\"#cite-simmons2000phase\">Simmons 2000</a>,\n<a id=\"ref-11\" href=\"#cite-shi2019\">Shi 2019</a>)\n. We focus on the explicit\nmethod, where the critical nucleus size and the nucleation energy are\ndetermined by the classical nucleation theory. We break down our\nconsideration of homogeneous nucleation into three parts. Part (a)\nconsiders the simple case of single-seed homogeneous nucleation. We\nexplore how the particle size influences the evolution of the nucleus\nwhen the thermodynamic driving force is close to the critical value\nwhere we can observe whether the particle grows, dissolves or remains\nstationary. In parts (b) and (c) we consider multiple-seed homogeneous\nnucleation, with nuclei appearing at fixed time $t=0$ or at random\ntimes distributed uniformly, respectively, with the latter part\nillustrating a scenario with constant nucleation rate. The Benchmark\nProblem probes the differences between transformation kinetics of the\ntwo cases and summarizes them using the Avrami plots based on the\nJohnson-Mehl-Avrami-Kolmogorov (JMAK)\ntheory\n(<a id=\"ref-12\" href=\"#cite-johnson1939reaction\">Johnson 1939</a>,\n<a id=\"ref-13\" href=\"#cite-avrami1939kinetics\">Avrami 1939</a>,\n<a id=\"ref-14\" href=\"#cite-avrami1940kinetics\">Avrami 1940</a>,\n<a id=\"ref-15\" href=\"#cite-avrami1941granulation\">Avrami 1941</a>,\n<a id=\"ref-16\" href=\"#cite-kolmogorov1937izv\">Kolmogorov 1937</a>).\n\n## Model Formulation\n\n### The phase field model in classical nucleation theory\n\nFor this benchmark problems we use the simplest possible phase field model with a single non-conserved phase field $\\phi$, which describes an isothermal pure substance with one liquid ($\\phi=0$) and one solid ($\\phi=1$) phase. The free energy of this system is  \n\\begin{equation}\n    \\mathcal{F}(\\phi)=\\int \\left[\\frac{\\epsilon^2}{2}(\\nabla \\phi)^2+wg(\\phi)-\\Delta f p(\\phi) \\right] d{V},\n    \\label{eqn:Fphi}\n\\end{equation}\nset $g(\\phi)=\\phi^2(1-\\phi)^2$, a simple double well function with minima at $\\phi=0$ and $\\phi=1$, $ w$ controls the double-well barrier height, $\\epsilon^2$ is the gradient energy coefficient, let $p(\\phi)=\\phi^3(10-15\\phi+6\\phi^2)$, which ensures that $p(0)=p'(0)=p'(1)=0$ and $p(1)=1$, and $\\Delta f$ is the driving force for solidification at the simulation temperature ($\\Delta f$ is positive below the melting point). The time evolution of $\\phi$ is given by the Allen-Cahn equation (<a id=\"ref-17\" href=\"#cite-allen1979microscopic\">Allen 1979</a>)\n\\begin{equation}\n    \\frac{\\partial \\phi}{\\partial t}=-M\\frac{\\delta \\mathcal{F}}{\\delta \\phi}=M\\left[\\epsilon^2\\nabla^2\\phi-wg'(\\phi)+\\Delta fp'(\\phi)\\right]\n    \\label{eqn:dphidt}\n\\end{equation}\nwhere $M$ is the mobility parameter. We will restrict the problem to two dimensions (2D). For a planar interface, one can show that the equilibrium ($\\Delta f$=0) solid-liquid interface profile with the interface centered at $x=x_0$ is given by\n\\begin{equation}\n    \\phi(x)=\\frac{1}{2}\\left[1-\\tanh\\left(\\frac{x-x_0}{\\sqrt{2}\\ell}\\right)\\right],\n    \\label{eqn:phir}\n\\end{equation}\nwhere $x$ is the perpendicular distance from the interface.\nWe use this expression as the initial condition when we introduce a nucleus. We can also obtain the width $\\ell$ and the free energy of the interface, $\\gamma$, as\n\\begin{equation}\n    \\ell=\\sqrt{\\frac{\\epsilon^2}{w}}\n    \\label{eqn:l}\n\\end{equation}\nand\n\\begin{equation}\n    \\gamma=\\frac{\\sqrt{\\epsilon^2w}}{3\\sqrt{2}}.\n    \\label{eqn:gamma}\n\\end{equation}\n\nChoosing a characteristic length scale $\\xi=\\ell$ and a characteristic time scale $\\tau=1/(Mw)$, we can obtain a nondimensional form of the problem (the nondimensional quantities are denoted by tildes),\n\\begin{equation}\n    \\tilde{\\mathcal{F}}(\\phi)=\\int \\left[\\frac{1}{2}(\\tilde{\\nabla} \\phi)^2+g(\\phi)- \\tilde{\\Delta f} p(\\phi) \\right] d{\\tilde{V}}\n    \\label{eqn:tFphi}\n\\end{equation}\nand\n\\begin{equation}\n    \\frac{\\partial \\phi}{\\partial \\tilde{t}}=\\tilde{\\nabla}^2\\phi-g'(\\phi)+\\tilde{\\Delta f}p'(\\phi),\n    \\label{eqn:dphidtt}\n\\end{equation}\nwith $\\tilde{\\Delta f}=\\Delta f/w$.\n\n### The properties of the classical nucleus\n\nThe explicit nucleation method that we employ introduces nuclei into a metastable system, with their radii and nucleation barrier determined from classical nucleation theory. Classical nucleation theory views crystallite fluctuations appearing in the undercooled liquid as small spherical domains of the bulk crystalline phase bounded by a mathematically sharp solid-liquid interface. For a 2D system, the free energy of a circular solid particle of radius $r$ is \n\\begin{equation}\n    \\Delta G(r) = 2 \\pi r \\gamma - \\pi r^2 \\Delta f\n    \\label{eqn:deltaG}\n\\end{equation}\nwhere $\\Delta f$ is the nucleation driving force that is used in our phase field model, and $\\gamma$ is the free energy of the interface. The free energy of the particle is a balance between the energy cost in forming the solid-liquid interface, and the free energy from the driving force which is released when the crystalline particle forms. Once the rate of change of free energy with respect to particle size becomes negative, the particle can grow. Taking the derivative of $\\Delta G(r)$ we get the rate of change of free energy with respect to radius as\n\\begin{equation}\n    \\frac{d\\Delta G}{dr}=2\\pi \\gamma - 2\\pi r\\Delta f.\n    \\label{eqn:ddeltaGdr}\n\\end{equation}\nBy setting $d\\Delta G/dr$ to zero, we obtain the critical radius $r^*$ as\n\\begin{equation}\n    r^* = \\frac{\\gamma}{\\Delta f}.\n    \\label{eqn:rc}\n\\end{equation}\nThe corresponding critical nucleation free energy is\n\\begin{equation}\n    \\Delta G^* = \\frac{\\pi \\gamma^2}{\\Delta f}.\n    \\label{eqn:deltaGc}\n\\end{equation}\nUsing the same units as before, the nondimensional forms of these quantities are\n\\begin{equation}\n    \\tilde{r^*} = \\frac{1}{3\\sqrt{2}}\\frac{1}{\\tilde{\\Delta f}}\n    \\label{eqn:trc}\n\\end{equation}\nand\n\\begin{equation}\n    \\tilde{\\Delta G^*} = \\frac{\\pi}{18}\\frac{1}{\\tilde{\\Delta f}}\n    \\label{eqn:tdeltaGc},\n\\end{equation}\nrespectively.\n\n### Avrami plots\n\nAvrami plots describe how solids transform from one phase to another at constant temperature. In particular, they can describe the kinetics of nucleation. The Avrami plots come from the JMAK theory\n(<a id=\"ref-18\" href=\"#cite-johnson1939reaction\">Johnson 1939</a>,\n<a id=\"ref-19\" href=\"#cite-avrami1939kinetics\">Avrami 1939</a>,\n<a id=\"ref-20\" href=\"#cite-avrami1940kinetics\">Avrami 1940</a>,\n<a id=\"ref-21\" href=\"#cite-avrami1941granulation\">Avrami 1941</a>,\n<a id=\"ref-22\" href=\"#cite-kolmogorov1937izv\">Kolmogorov 1937</a>), which makes a number of \nassumptions and simplifications: (i)  nucleation occurs randomly and homogeneously over the entire un-transformed portion of the material, (ii) the growth rate is constant and does not depend on the extent of transformation, (iii) the particles have convex shape with the same orientation, and (iv) the size of the system is infinite (both in space and time).\n\nThe basis of the Avrami plots is the transformed fraction (solid fraction) $Y(t)$ vs. time. According to the JMAK theory,\n\\begin{equation}\n    Y(t)=1-\\exp (-Kt^n),\n    \\label{eqn:Xt}\n\\end{equation}\nwhere $K$ is a constant depending on the nucleation and growth rates, $n=d+1$ for continuous nucleation and $n=d$ if nucleation happens only at $t=0$, and $d$ is the number of spatial dimensions. If we plot $\\log(-\\log(1-Y))$ vs. $\\log(t)$, then for the JMAK kinetics (Eq. \\ref{eqn:Xt}) we get a straight line with slope $n$.\n\n## Benchmark 8 Specification\n\nFrom here on, we will use only the nondimensional forms of the phase field (Eqs. \\ref{eqn:tFphi}, \\ref{eqn:dphidtt}, and \\ref{eqn:phir}) and nucleation (Eqs. \\ref{eqn:trc} and \\ref{eqn:tdeltaGc}) equations, but we will drop the tildes.\n\n### Part (a): single seed\n\nIn this problem we examine the morphology change of the nucleus for different initial radii. We consider a 2D simulation domain of size $100 \\times 100$ units centered at $x=y=0$ with Neumann boundary conditions. The driving force is set to $\\Delta f = \\sqrt{2}/30$, which corresponds to a critical radius of $r^*=5$ (Eq. \\ref{eqn:trc}). Next, we place a circular seed at the center of the domain. \nIncorporating a nucleus into a diffuse interface phase field model leads to a small offset from a classical, sharp-interface model of a nucleus. To account for this,\nwe incorporate a diffuse-interface seed using the profile $\\phi(r)$ given by modifying Eq. \\ref{eqn:phir} to 2D where $r=\\sqrt{x^2+y^2}$, with a radius $r_0=r^*$. This seed is the diffuse-interface approximation of the classical sharp interface nucleus corresponding to the given $\\Delta f$, and therefore it should be fairly close to (an unstable) equilibrium. \nPart (a) is then defined by the Allen-Cahn equation\n\\begin{equation}\n    \\frac{\\partial \\phi}{\\partial {t}}={\\nabla}^2\\phi-g'(\\phi)+{\\Delta f}p'(\\phi)\n    \\label{eqn:dphidtt_2}\n\\end{equation}\nfor the phase field $\\phi$, and the three different initial conditions: in the first case with the seed radius $r_0$ corresponding exactly to the critical one (critical nucleus), and in the other two cases, slightly below and above the critical radius (subcritical and supercritical nuclei):\n\\begin{equation}\n    \\phi(r)=\\frac{1}{2}\\left[1-\\tanh\\left(\n    \\frac{r-r_0}{\\sqrt{2}}\n    \\right)\\right],\n    \\label{eqn:phitr_2}\n\\end{equation}\nwhere $r_0=\\{r^*, 0.99r^*, 1.01r^*\\}$. [Figure 1](#fig1) shows the computational domain with an initial seed of radius $r=r^*$. The time evolution of the system is then followed for times up to $t = 200$ units, and the solid fraction $Y$ and the total free energy $F$ are plotted as functions of time. Finally, the problem also includes a convergence test with respect to mesh (spatial resolution). The closer the initial radius $r$ is to the critical radius $r^*$, the more sensitive the numerical integration will be to round-off errors. Therefore, a convergence test is included for $r_0=1.01r^*$ using successive runs each halving the average spatial mesh size $\\Delta x$ between consecutive runs. At least 3 runs are required to estimate the rate of convergence based on the $L^2$ error with the finest mesh being used as a gold standard. The simulations should be run to $t=200$ and the final phase field (at $t=200$) for each successive run should be submitted.\n\nTo submit results to the PFHub website, see the [submission guidelines](#Part-%28a%29) below.\n\n<figure>\n    \n    <figcaption>\n        <center> Illustration of the $100 \\times 100$ computational domain in 2D. </center> \n    </figcaption>\n</figure>\n\n## Part (b): multiple initial seeds\n\nThe second part of the homogeneous nucleation benchmark problem focuses on the kinetics of nucleation using Avrami plots and compares them to JMAK theory. To obtain reasonable statistics for these two parts, the simulation volume needs to be larger so it can encompass a larger number of smaller nuclei. We therefore increase the domain size to $500 \\times 500$ units of length, and the driving force to $\\Delta f = 1/(3 \\sqrt{2})$, which corresponds to a critical radius of $r^*=1$. Random initial positions $\\mathbf{r}_i$ of 25 supercritical seeds $i, i=1,\\ldots,25$ are generated with $r_0=2.2r^*$ drawn from a uniform distribution on the $500\\times500$ domain. The distribution of the phase field $\\phi$ is the sum of the phase fields $\\phi_i$ with profiles\n\\begin{equation}\n    \\phi_i(r)=\\frac{1}{2}\\left[1-\\tanh\\left(\n    \\frac{|\\mathbf{r}-\\mathbf{r}_i|-2.2r^*}{\\sqrt{2}}\n    \\right)\\right].\n    \\label{eqn:phitr_3}\n\\end{equation}\nfrom the different seeds $i$. Overlaps between different seeds are managed by setting $\\phi=1$ in all regions where the sums of $\\phi_i >1$. After placing initial seeds and adjusting the initial phase field $\\phi$ so that $\\phi\\leq1$ everywhere, the simulation is run up to total time $t=200$, at which time the whole domain is transformed to a solid ($\\phi=1$).  This is repeated four times, each time with different random seeds, and the total free energy, time evolution of the solid fraction $Y$, discrete particle count $N$  (the number of disjoint regions with $\\phi=1$) are plotted for the five simulations, and Avrami plots are generated from the five simulations; from the Avrami plot the exponent $n$ is estimated and compared to the JMAK theory.\n\nBoth Part (b) and Part (c) involve a random number generator. Because different executions will in general generate different random numbers, specific individual solutions will in general not be reproduced. However, statistics such as the average slope of Avrami plots can be meaningfully compared.\n\nTo submit results to the PFHub website, see the [submission guidelines](#Part-%28b%29) below.\n\n## Part (c): multiple seeds at random times\n\nFor the third part of the homogeneous benchmark problem, the computational domain is first expanded to $1000 \\times1000$. Instead of inserting nuclei at fixed time $t = 0$ as in part two of the problem, in this case 100 random nucleation times $t_i$ are generated, $i=1,\\ldots,100$, drawn from a uniform distribution in the interval $t_i \\in [0, 600)$ with centers $\\mathbf{r}_i$ drawn from a uniform distribution on the $1000\\times1000$ domain.\nWe decrease the driving force to $\\Delta f=1/(6\\sqrt{2})$, which corresponds to a critical radius or $r^*=2$, but keep the initial radii of the inserted nuclei the same as those in the second part of the problem\n\\begin{equation}\n    \\phi_i(r)=\\frac{1}{2}\\left[1-\\tanh\\left(\n    \\frac{|\\mathbf{r}-\\mathbf{r}_i|-1.1r^*}{\\sqrt{2}}\n    \\right)\\right].\n\\end{equation}\n\nAgain, $\\phi$ is set to unity in regions of overlaps of nuclei. The simulations are run up to times $t=600$, and repeated for four more random initial conditions.  The total free energy plot the total free energy, the time evolution of the solid fraction $Y$ and the discrete particle count $N$, are plotted as functions of time, and an  Avrami plot is generated for the five runs.\n\nTo submit results to the PFHub website, see the [submission guidelines](#Part-%28c%29) below.\n\n## Submission Guidelines\n\nPlease use the [upload form]({{ site.baseurl }}/simulations/upload_form/) to upload your results.\n\nIn addition to that specified, further data to upload can include a Youtube video, images of the nuclei at different times, or the entire phase field variable at different times. This data can be uploaded directly to the website or stored at a secondary location and only the link to the data provided. This data is not required, but will help others view your work.\n\n### Part (a)\n\nPart (a) requires running three simulations with a single seed with different values of $r_0$ using the model formulation [defined above](#Part-%28a%29:-single-seed). Optionally, a further two simulations can be run to check convergence, but this is not required. The three required  simulations and two optional simulations are\n\n 1. $r_0 = 0.99 r^*$, ${\\Delta x} = {\\Delta x}_0$\n 1. $r_0 = r^*$, ${\\Delta x} = {\\Delta x}_0$\n 1. $r_0 = 1.01 r^*$, ${\\Delta x} = {\\Delta x}_0$\n 1. $r_0 = 1.01 r^*$, ${\\Delta x} = {\\Delta x}_1$ (optional)\n 1. $r_0 = 1.01 r^*$, ${\\Delta x} = {\\Delta x}_2$ (optional)\n \nwhere ${\\Delta x}_0, {\\Delta x}_1$ and ${\\Delta x}_2$ represent simulations at different mesh sizes. $\\Delta x$ refinement should be selected so that successively refined meshes have roughly $4\\times$ as many elements. When uploading the results, the $\\Delta x$ values should be provided in the datafile alongside the values for $\\phi$ at each location in the domain. Each simulation should be run to $t=200$ and the following data should be collected.\n\n - The solid fraction in the domain (the integral $\\int_V \\phi dV / \\int_V dV$) during the transient (not necessarily at every time step but for ~100 data points).\n \n - The free energy integrated over the whole domain, $\\mathcal{F}$, during the transient. \n \n - The phase field, $\\phi$, at each grid point in the domain at $t=200$. \n \n - The grid spacing, $\\Delta x$ at each grid point in the domain at $t=200$ if submitting the optional simulations.\n \nOne PFHub upload is required for all the simulations. The solid fraction and free energy data can be included in the same CSV file or in separate data files, but either way still require 2 entries in the \"Data Files\" section on the [upload form]({{ site.baseurl }}/simulations/upload_form/). The entries should be labeled as `solid_fraction_{i}` or `free_energy_{i}` depending on the simulation number (1 to 5). The CSV (JSON or TSV are also fine) files should have a format similar to the following.\n\n```\ntime,fraction,energy\n0.000000000000000000e+00,8.214174263100689974e-03,3.579809478015085311e+00\n1.000000000000000056e-01,8.205027223394931180e-03,3.577696619091880859e+00\n2.000000000000000111e-01,8.197361418448430651e-03,3.576379039721957032e+00\n...\n```\n\nThe names of the columns are arbitrary as long as they are given in \"Name of x-axis column\" and \"Name of y-axis column\" in the form. The phase field data should be named `phase_field_{i}` in the \"Short name of data\" entry and have the following format\n\n```\nx,y,phi,delta_x\n0.0,1.0,0.5,0.44\n0.0,1.5,0.49,0.44\n...\n```\n\nwhere `x` and `y` is a position in the domain and `phi` is the value at that position. `delta_x` is the nominal grid spacing in that region given by the coordinates. This may be constant across the domain for gridded data, but vary for adaptive meshing. `delta_x` is only a representative value of the grid spacing in that region. The \"3D\" radio button should be selected for the `phase_field_{i}` entry.\n\nThe grid spacing data should be named `grid_spacing_{i}` and have exactly the same data as above. Again the same file can be used, but two \"Data Files\" entries are required for both phase field and grid spacing. The \"3D\" radio button should be selected for the `grid_spacing_{i}` entry. \n\nThe `grid_spacing_{i}` entries are not required, but if included will show convergence data for simulations 3, 4 and 5.\n\n### Part (b)\n\nPart (b) requires running 5 simulations with multiple seeds randomly positioned at $t=0$, see the [defintion above](#Part-%28b%29:-multiple-initial-seeds). The simulations are run to $t=200$. The following data should be collected.\n\n - The solid fraction in the domain (the integral $\\int_V \\phi dV / \\int_V dV$) during the transient (not necessarily at every time step but for ~100 data points).\n \n - The free energy integrated over the whole domain, $\\mathcal{F}$, during the transient. \n \n - The discrete particle count, $N$, during the transient.\n \nOne PFHub upload is required with five data files, but with a total of 15 entries in the \"Data Files\" section. The solid fraction, free energy and particle count can be included in the same data file for each simulation. The entries should be labeled as `solid_fraction_{i}`, `free_energy_{i}` or `particle_count_{i}` depending on the simulation number (1 to 5). The CSV (JSON or TSV are also fine) files should have a format similar to the following.\n\n```\ntime,fraction,energy,particle_count\n0.000000000000000000e+00,8.214174263100689974e-03,3.579809478015085311e+00,24\n1.000000000000000056e-01,8.205027223394931180e-03,3.577696619091880859e+00,24\n2.000000000000000111e-01,8.197361418448430651e-03,3.576379039721957032e+00,23\n...\n```\n\n### Part (c)\n\nPart (c) requires running 5 simulations with seeds randomly appearing between $t=0$ and $t=600$, see the [definition above](#Part-%28c%29:-multiple-seeds-at-random-times). The simulations are run to $t=600$. The following data should be collected.\n\n - The solid fraction in the domain (the integral $\\int_V \\phi dV / \\int_V dV$) during the transient (not necessarily at every time step but for ~100 data points).\n \n - The free energy integrated over the whole domain, $\\mathcal{F}$, during the transient. \n \n - The discrete particle count, $N$, during the transient.\n \nOne PFHub upload is required with five data files, but with a total of 15 entries in the \"Data Files\" section. The solid fraction, free energy and particle count can be included in the same data file for each simulation. The entries should be labeled as `solid_fraction_{i}`, `free_energy_{i}` or `particle_count_{i}` depending on the simulation number (1 to 5). The CSV (JSON or TSV are also fine) files should have a format similar to the following.\n\n```\ntime,fraction,energy,particle_count\n0.000000000000000000e+00,8.214174263100689974e-03,3.579809478015085311e+00,0\n1.000000000000000056e-01,8.205027223394931180e-03,3.577696619091880859e+00,1\n2.000000000000000111e-01,8.197361418448430651e-03,3.576379039721957032e+00,1\n...\n```\n\nPlease use the [upload form]({{ site.baseurl }}/simulations/upload_form/) to upload your results.\n\n## Results\n\nResults from this benchmark problem are displayed on the [simulation result page]({{ site.baseurl }}/simulations/8a.1) for different codes.\n\n<!--\n... see https://jupyter.brynmawr.edu/services/public/dblank/jupyter.cs/Examples/Calico%20Document%20Tools%20and%20Bibtex.ipynb for details\n... also see https://jupyter.brynmawr.edu/services/public/dblank/Jupyter%20Notebook%20Users%20Manual.ipynb#5.-Bibliographic-Support\n... \n... to make this work (sometimes just doesn't work which is infuriating \n...\n...  \n...  - <!--bibtex needs to be at the very top of the cell it seems (very important)\n-->\n\n<!--bibtex\n\n@article{castro2003phase,\n  title = {Phase-field approach to heterogeneous nucleation},\n  author = {Castro, Mario},\n  journal = {Phys. Rev. B},\n  volume = {67},\n  issue = {3},\n  pages = {035412},\n  numpages = {8},\n  year = {2003},\n  month = {Jan},\n  publisher = {American Physical Society},\n  doi={10.1103/PhysRevB.67.035412},\n  URL=\"https://link.aps.org/doi/10.1103/PhysRevB.67.035412\"\n}\n\n\n@article{elliott1989second,\n  title={{A second order splitting method for the Cahn-Hilliard equation}},\n  author={Elliott, Charles M and French, Donald A and Milner, Fabio Augusto},\n  journal={Numerische Mathematik},\n  volume={54},\n  number={5},\n  pages={575--590},\n  year={1989},\n  publisher={Springer},\n  url=\"https://doi.org/10.1007/BF01396363\"\n}\n\n@article{gaston2014continuous,\n  title={Continuous integration for concurrent computational framework and application development},\n  author={Gaston, Derek and Peterson, John and Permann, Cody and Andrs, David and Slaughter, Andrew and Miller, Jason},\n  journal={Journal of Open Research Software},\n  volume={2},\n  number={1},\n  year={2014},\n  publisher={Ubiquity Press},\n  url=\"http://doi.org/10.5334/jors.as\"\n}\n\n@article{gaston2015physics,\n  title={Physics-based multiscale coupling for full core nuclear reactor simulation},\n  author={Gaston, Derek R and Permann, Cody J and Peterson, John W and Slaughter, Andrew E and Andr{\\v{s}}, David and Wang, Yaqi and Short, Michael P and Perez, Danielle M and Tonks, Michael R and Ortensi, Javier and others},\n  journal={Annals of Nuclear Energy},\n  volume={84},\n  pages={45--54},\n  year={2015},\n  publisher={Elsevier},\n  url=\"https://doi.org/10.1016/j.anucene.2014.09.060\"\n}\n\n@article{jokisaari2017spinodal,\n  title={Benchmark problems for numerical implementations of phase field models},\n  author={Jokisaari, A M and Voorhees, P W and Guyer, Jonathan E and Warren, J A and Heinonen, O G},\n  journal={Computational Materials Science},\n  volume={126},\n  pages={139--151},\n  year={2017},\n  publisher={Elsevier},\n  url=\"https://doi.org/10.1016/j.commatsci.2016.09.022\"\n}\n\n\n@article{jokisaari2017dendrite,\n  title={Phase field benchmark problems for dendritic growth and linear elasticity},\n  author={Jokisaari, A M and Voorhees, P W and Guyer, Jonathan E and Warren, J A and Heinonen, O G},\n  journal={Computational Materials Science},\n  volume={149},\n  pages={336},\n  year={2018},\n  publisher={Elsevier},\n  url=\"https://doi.org/10.1016/j.commatsci.2018.03.015\"\n}\n\n@article{jokisaari2020stokes,\n  title={Phase field benchmark problems targeting fluid flow and electrochemistry},\n  author={Jokisaari, A M and Wu, W and Voorhees, P W and Guyer, Jonathan E and Warren, J A and Heinonen, O G},\n  journal={Computational Materials Science},\n  volume={176},\n  pages={109548},\n  year={2020},\n  publisher={Elsevier},\n  url=\"https://doi.org/10.1016/j.commatsci.2020.109548\"\n}\n\n@article{kubo1966,\n  title={The fluctuation-dissipation theorem},\n  author={Kubo, R},\n  journal={Reports on Progess in Physics},\n  volume={29},\n  number = {1},\n  pages={255--284},\n  year={1966},\n  publisher={IOP Publishing},\n  url={https://doi.org/10.1088%2F0034-4885%2F29%2F1%2F306}\n}\n\n@article{granasy2002nucleation,\n title={Nucleation and bulk crystallization in binary phase field theory},\n author={Gr\u00e1n\u00e1sy, L and and B\u00f6rzs\u00f6nyi, T and Pusztai, T},\n journal={Physical Review Letters},\n volume={88},\n pages={206105},\n number={20},\n year={2002},\n publisher={American Physical Society},\n url={https://doi.org/10.1103/PhysRevLett.88.206105}\n}\n\n@article{granasy2007phase,\n title={Phase field theory of heterogeneous crystal nucleation},\n author={Gr\u00e1n\u00e1sy, L and T and Pusztai, T and Saylor, D and Warren, J A},\n journal={Physical Review Letters},\n volume={98},\n pages={035703},\n number={20},\n year={2007},\n publisher={American Physical Society},\n url={https://doi.org/10.1103/PhysRevLett.98.035703}\n}\n\n@article{granasy2019,\n title={Phase-field modeling of crystal nucleation in undercooled liquids -- A review},\n author={Gr\u00e1n\u00e1sy, L and T\u00f3th, G and Warren, J A and Podmaniczky, F and Tegze, G and R\u00e1tkai, L and Pusztai, T},\n journal={Progress in Materials Science},\n volume={106},\n pages={100569},\n year={2019},\n publisher={Elsevier},\n url={https://doi.org/10.1016/j.pmatsci.2019.05.002}\n}\n\n@article{heo2014phase,\n title={Phase-field modeling of nucleation in solid-state phase transformations},\n author={Heo, T W and Chen, L},\n journal={The journal of the minerals, metals \\& materials society},\n volume={66},\n pages={1520--1528},\n year={2014},\n publisher={TMS},\n url={https://doi.org/10.1007/s11837-014-1033-9}\n}\n\n@article{shi2019,\n title={Integrated simulation framework for additively manufactured Ti-6Al-4V: melt pool dynamics, microstructure, solid-state phase transformation, and microelastic response},\n author={Shi, R and Khairallah, S and Heo, T W and Rolchigo, M and McKeown, J T and Matthews, M J},\n journal={The journal of the minerals, metals \\& materials society},\n volume={71},\n pages={3640--3655},\n year={2019},\n publisher={TMS},\n url={https://doi.org/10.1007/s11837-019-03618-1}\n}\n\n@article{simmons2000phase,\n  title={Phase field modeling of simultaneous nucleation and growth by explicitly incorporating nucleation events},\n  author={Simmons, J P and Shen, C and Wang, Y},\n  journal={Scripta Materialia},\n  volume={43},\n  issues={10},\n  pages={935--942},\n  year={2000},\n  publisher={Elsevier},\n  url={https://doi.org/10.1016/S1359-6462&#40;00&#41;00517-0}\n}\n\n@article{simmons2004microstructural,\n  title={Microstructural development involving nucleation and growth phenomena simulated with the Phase Field method},\n  author={Simmons, J P and Wen, Y and Shen, C and Wang, Y},\n  journal={Materials Science and Engineering: A},\n  volume={365},\n  issues={1-2},\n  pages={136--143},\n  year={2004},\n  publisher={Elsevier},\n  url={https://doi.org/10.1016/j.msea.2003.09.019}\n}\n\n@article{warren2009phase,\n  title={Phase field approach to heterogeneous crystal nucleation in alloys},\n  author={Warren, J A and Pusztai, T and Gr\u00e1n\u00e1sy, L K and Gr\u00e1n\u00e1sy, L},\n  journal={Physical Revies B},\n  volume={79},\n  issues={1},\n  pages={014204},\n  year={2009},\n  publisher={American Physical Society},\n  url={https://doi.org/10.1103/PhysRevB.79.014204}\n}\n\n@incollection{elliott1989,\n  title={The Cahn-Hilliard model for the kinetics of phase separation},\n  author={Elliott, Charles M},\n  booktitle={Mathematical models for phase change problems},\n  pages={35--73},\n  year={1989},\n  publisher={Springer},\n  url={https://doi.org/10.1007/978-3-0348-9148-6_3}\n}\n\n@article{johnson1939reaction,\n  title={Reaction kinetics in processes of nucleation and growth},\n  author={Johnson, William A and Mehl, R F},\n  journal={Am. Inst. Min. Metal. Petro. Eng.},\n  volume={135},\n  pages={416--458},\n  year={1939},\n  url={https://doi.org/10.1007/s11663-010-9421-1}\n}\n\n@article{avrami1939kinetics,\n  title={Kinetics of phase change. I General theory},\n  author={Avrami, Melvin},\n  journal={The Journal of chemical physics},\n  volume={7},\n  number={12},\n  pages={1103--1112},\n  year={1939},\n  publisher={American Institute of Physics},\n  url={ https://doi.org/10.1063/1.1750380}\n}\n\n@article{avrami1940kinetics,\n  title={Kinetics of phase change. II transformation-time relations for random distribution of nuclei},\n  author={Avrami, Melvin},\n  journal={The Journal of chemical physics},\n  volume={8},\n  number={2},\n  pages={212--224},\n  year={1940},\n  publisher={American Institute of Physics},\n  url={https://doi.org/10.1063/1.1750631}\n}\n\n@article{avrami1941granulation,\n  title={Granulation, phase change, and microstructure kinetics of phase change. III},\n  author={Avrami, Melvin},\n  journal={The Journal of chemical physics},\n  volume={9},\n  number={2},\n  pages={177--184},\n  year={1941},\n  publisher={American Institute of Physics},\n  url={https://doi.org/10.1063/1.1750872}\n}\n\n@article{kolmogorov1937izv,\n  title={On the Statistical Theory of the Crystallization of Metals},\n  author={Kolmogorov, A N},\n  journal={Bulletin of the Acadamy of Sciences of the USSR},\n  series={Mathematical Series},\n  volume={1},\n  pages={355--359},\n  year={1937},\n  url={https://doi.org/10.1007/978-94-011-2260-3_22}\n}\n\n@article{quested2005athermal,\n  title={Athermal heterogeneous nucleation of solidification},\n  author={Quested, T E and Greer, A L},\n  journal={Acta Materialia},\n  volume={53},\n  number={9},\n  pages={2683--2692},\n  year={2005},\n  publisher={Elsevier},\n  url={https://doi.org/10.1016/j.actamat.2005.02.028}\n}\n\n@article{greer2000modelling,\n  title={Modelling of inoculation of metallic melts: application to grain refinement of aluminium by {A}l--{T}i--{B}},\n  author={Greer, A L and Bunn, A M and Tronche, A and Evans, P V and Bristow, D J},\n  journal={Acta materialia},\n  volume={48},\n  number={11},\n  pages={2823--2835},\n  year={2000},\n  publisher={Elsevier},\n  url={https://doi.org/10.1016/S1359-6454(00)00094-X}\n}\n\n@article{greer2016overview,\n  title={Overview: Application of heterogeneous nucleation in grain-refining of metals},\n  author={Greer, A L},\n  journal={The Journal of Chemical Physics},\n  volume={145},\n  number={21},\n  pages={211704},\n  year={2016},\n  publisher={AIP Publishing LLC},\n  url={https://doi.org/10.1063/1.4968846}\n}\n\n\n@article{dewitt2020prisms,\n  title={PRISMS-PF: A general framework for phase-field modeling with a matrix-free finite element method},\n  author={DeWitt, Stephen and Rudraraju, Shiva and Montiel, David and Andrews, W Beck and Thornton, Katsuyo},\n  journal={npj Computational Materials},\n  volume={6},\n  number={1},\n  pages={1--12},\n  year={2020},\n  publisher={Nature Publishing Group},\n  url={https://doi.org/10.1038/s41524-020-0298-5}\n}\n\n\n@article{guyer2009fipy,\n  title={FiPy: Partial differential equations with Python},\n  author={Guyer, Jonathan E and Wheeler, Daniel and Warren, James A},\n  journal={Computing in Science \\& Engineering},\n  volume={11},\n  number={3},\n  pages={6--15},\n  year={2009},\n  publisher={IEEE},\n  url={https://doi.org/10.1109/MCSE.2009.52}\n}\n\n@article{wheeler2019pfhub,\n  title={PFHub: The Phase-Field Community Hub},\n  author={Wheeler, Daniel and Keller, Trevor and DeWitt, Stephen J and Jokisaari, Andrea M and Schwen, Daniel and Guyer, Jonathan E and Aagesen, Larry K and Heinonen, Olle G and Tonks, Michael R and Voorhees, Peter W and others},\n  journal={Journal of Open Research Software},\n  volume={7},\n  number={1},\n  year={2019},\n  publisher={Ubiquity Press},\n  url={http://doi.org/10.5334/jors.276}\n}\n\n@article{allen1979microscopic,\n  title={A microscopic theory for antiphase boundary motion and its application to antiphase domain coarsening},\n  author={Allen, Samuel M and Cahn, John W},\n  journal={Acta Metallurgica},\n  volume={27},\n  issue = {6},\n  pages={1085--1095},\n  year={1979},\n  url={https://doi.org/10.1016/0001-6160(79)90196-2}\n}\n\n-->\n\n## References\n\n<a id=\"cite-granasy2002nucleation\"/><sup><a href=\"#ref-1\">[^]</a><a href=\"#ref-9\">[^]</a></sup>Gr\u00e1n\u00e1sy, L and and B\u00f6rzs\u00f6nyi, T and Pusztai, T. 2002. _Nucleation and bulk crystallization in binary phase field theory_. [URL](https://doi.org/10.1103/PhysRevLett.88.206105)\n\n<a id=\"cite-castro2003phase\"/><sup><a href=\"#ref-2\">[^]</a></sup>Castro, Mario. 2003. _Phase-field approach to heterogeneous nucleation_. [URL](https://link.aps.org/doi/10.1103/PhysRevB.67.035412)\n\n<a id=\"cite-simmons2004microstructural\"/><sup><a href=\"#ref-3\">[^]</a></sup>Simmons, J P and Wen, Y and Shen, C and Wang, Y. 2004. _Microstructural development involving nucleation and growth phenomena simulated with the Phase Field method_. [URL](https://doi.org/10.1016/j.msea.2003.09.019)\n\n<a id=\"cite-granasy2007phase\"/><sup><a href=\"#ref-4\">[^]</a></sup>Gr\u00e1n\u00e1sy, L and T and Pusztai, T and Saylor, D and Warren, J A. 2007. _Phase field theory of heterogeneous crystal nucleation_. [URL](https://doi.org/10.1103/PhysRevLett.98.035703)\n\n<a id=\"cite-warren2009phase\"/><sup><a href=\"#ref-5\">[^]</a></sup>Warren, J A and Pusztai, T and Gr\u00e1n\u00e1sy, L K and Gr\u00e1n\u00e1sy, L. 2009. _Phase field approach to heterogeneous crystal nucleation in alloys_. [URL](https://doi.org/10.1103/PhysRevB.79.014204)\n\n<a id=\"cite-heo2014phase\"/><sup><a href=\"#ref-6\">[^]</a></sup>Heo, T W and Chen, L. 2014. _Phase-field modeling of nucleation in solid-state phase transformations_. [URL](https://doi.org/10.1007/s11837-014-1033-9)\n\n<a id=\"cite-granasy2019\"/><sup><a href=\"#ref-7\">[^]</a></sup>Gr\u00e1n\u00e1sy, L and T\u00f3th, G and Warren, J A and Podmaniczky, F and Tegze, G and R\u00e1tkai, L and Pusztai, T. 2019. _Phase-field modeling of crystal nucleation in undercooled liquids -- A review_. [URL](https://doi.org/10.1016/j.pmatsci.2019.05.002)\n\n<a id=\"cite-kubo1966\"/><sup><a href=\"#ref-8\">[^]</a></sup>Kubo, R. 1966. _The fluctuation-dissipation theorem_. [URL](https://doi.org/10.1088%2F0034-4885%2F29%2F1%2F306)\n\n<a id=\"cite-simmons2000phase\"/><sup><a href=\"#ref-10\">[^]</a></sup>Simmons, J P and Shen, C and Wang, Y. 2000. _Phase field modeling of simultaneous nucleation and growth by explicitly incorporating nucleation events_. [URL][simmons_url]\n\n<a id=\"cite-shi2019\"/><sup><a href=\"#ref-11\">[^]</a></sup>Shi, R and Khairallah, S and Heo, T W and Rolchigo, M and McKeown, J T and Matthews, M J. 2019. _Integrated simulation framework for additively manufactured Ti-6Al-4V: melt pool dynamics, microstructure, solid-state phase transformation, and microelastic response_. [URL](https://doi.org/10.1007/s11837-019-03618-1)\n\n<a id=\"cite-johnson1939reaction\"/><sup><a href=\"#ref-12\">[^]</a><a href=\"#ref-18\">[^]</a></sup>Johnson, William A and Mehl, R F. 1939. _Reaction kinetics in processes of nucleation and growth_. [URL](https://doi.org/10.1007/s11663-010-9421-1)\n\n<a id=\"cite-avrami1939kinetics\"/><sup><a href=\"#ref-13\">[^]</a><a href=\"#ref-19\">[^]</a></sup>Avrami, Melvin. 1939. _Kinetics of phase change. I General theory_. [URL](https://doi.org/10.1063/1.1750380)\n\n<a id=\"cite-avrami1940kinetics\"/><sup><a href=\"#ref-14\">[^]</a><a href=\"#ref-20\">[^]</a></sup>Avrami, Melvin. 1940. _Kinetics of phase change. II transformation-time relations for random distribution of nuclei_. [URL](https://doi.org/10.1063/1.1750631)\n\n<a id=\"cite-avrami1941granulation\"/><sup><a href=\"#ref-15\">[^]</a><a href=\"#ref-21\">[^]</a></sup>Avrami, Melvin. 1941. _Granulation, phase change, and microstructure kinetics of phase change. III_. [URL](https://doi.org/10.1063/1.1750872)\n\n<a id=\"cite-kolmogorov1937izv\"/><sup><a href=\"#ref-16\">[^]</a><a href=\"#ref-22\">[^]</a></sup>Kolmogorov, A N. 1937. _On the Statistical Theory of the Crystallization of Metals_. [URL](https://doi.org/10.1007/978-94-011-2260-3_22)\n\n<a id=\"cite-allen1979microscopic\"/><sup><a href=\"#ref-17\">[^]</a></sup>Allen, Samuel M and Cahn, John W. 1979. _A microscopic theory for antiphase boundary motion and its application to antiphase domain coarsening_.\n[URL][allen_url]\n\n[allen_url]: https://doi.org/10.1016/0001-6160(79)90196-2\n[simmons_url]: https://doi.org/10.1016/S1359-6462(00)00517-0\n\n\n## Appendix\n\nThe following code is given as a resource for those implementing the benchmark to help count the particles in Part (b) and Part (c). One possibility as outlined here is to use [`scipy.ndimage.label`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.label.html#scipy.ndimage.label). This returns a tuple with a labeled array of unique features as the first item and a count of features as the second item. In the case of the phase field the values will require thresholding to 0 or 1 before using `scipy.ndimage.label`.\n\n```Python\nimport numpy as np\nimport scipy.ndimage\nimport matplotlib.pyplot as plt\n\ndef make_particles(shape, n_particles, max_radius, seed=99):\n    \"\"\"Make an array with random particles\n    \n    Args:\n      shape: shape of array\n      n_particles: number of particles in arrau\n      max_radius: maximum possible radius of particles\n      seed: random seed\n      \n    Returns: numpy array mask with particles\n    \"\"\"\n    np.random.seed(seed)\n        \n    def xy_grid(shape):\n        \"\"\"Generate a grid of x, y values in a single array\n        \n        The returned array has shape (len(shape),) + shape + (1,). The last axis is\n        for the operations with particles.\n        \"\"\"\n        linspace = lambda x: np.linspace(0, x - 1, x) + 0.5\n        return np.array(np.meshgrid(*map(linspace, shape), indexing=\"ij\"))[..., None]\n    \n    # first axis is dimensions\n    # second and third axes are shape of domain\n    # last axis is the number of particles. \n    centers = (np.random.random((len(shape), n_particles)) * np.array(shape)[:, None])[:, None, None]\n    radii = (np.random.random(n_particles) * max_radius)[None, None]\n    return numpy.any(((xy_grid(shape) - centers)**2).sum(0) < radii**2, axis=-1)\n\narr = make_particles((100, 200), 20, 10)\nplt.imshow(arr)\nprint('Actual number of particles:', scipy.ndimage.label(arr)[1])\n```\n\n\n```python\nimport numpy as np\nimport scipy.ndimage\nimport matplotlib.pyplot as plt\n\ndef make_particles(shape, n_particles, max_radius, seed=99):\n    \"\"\"Make an array with random particles\n    \n    Args:\n      shape: shape of array\n      n_particles: number of particles in arrau\n      max_radius: maximum possible radius of particles\n      seed: random seed\n      \n    Returns: numpy array mask with particles\n    \"\"\"\n    np.random.seed(seed)\n        \n    def xy_grid(shape):\n        \"\"\"Generate a grid of x, y values in a single array\n        \n        The returned array has shape (len(shape),) + shape + (1,). The last axis is\n        for the operations with particles.\n        \"\"\"\n        linspace = lambda x: np.linspace(0, x - 1, x) + 0.5\n        return np.array(np.meshgrid(*map(linspace, shape), indexing=\"ij\"))[..., None]\n    \n    # first axis is dimensions\n    # second and third axes are shape of domain\n    # last axis is the number of particles. \n    centers = (np.random.random((len(shape), n_particles)) * np.array(shape)[:, None])[:, None, None]\n    radii = (np.random.random(n_particles) * max_radius)[None, None]\n    return numpy.any(((xy_grid(shape) - centers)**2).sum(0) < radii**2, axis=-1)\n\narr = make_particles((100, 200), 20, 10)\nplt.imshow(arr)\nprint('Actual number of particles:', scipy.ndimage.label(arr)[1])\n```\n", "meta": {"hexsha": "613ffc7874f6cf351f5f2b365692e7faecc3ff78", "size": 63785, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "benchmarks/benchmark8.ipynb", "max_stars_repo_name": "wd15/chimad-phase-field", "max_stars_repo_head_hexsha": "b8ead2ef666201b500033052d0a4efb55796c2da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmarks/benchmark8.ipynb", "max_issues_repo_name": "wd15/chimad-phase-field", "max_issues_repo_head_hexsha": "b8ead2ef666201b500033052d0a4efb55796c2da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2015-02-06T16:45:52.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-12T17:39:56.000Z", "max_forks_repo_path": "benchmarks/benchmark8.ipynb", "max_forks_repo_name": "wd15/chimad-phase-field", "max_forks_repo_head_hexsha": "b8ead2ef666201b500033052d0a4efb55796c2da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.5109060403, "max_line_length": 5928, "alphanum_fraction": 0.6447910951, "converted": true, "num_tokens": 12620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.1311732203653401, "lm_q1q2_score": 0.04808675626625859}}
{"text": "This notebook contains my replication of the results from the following paper:\n\n    Bleakley, Hoyt, and Chin, Aimee. 2010. Age at arrival, English proficiency, and social assimilation among US immigrants. American Economic Journal: Applied Economics, 2(1), 165-92.\n\n\nDownloading and viewing this notebook:\n\n-The best way to view this notebook is by downloading it and the repository it is located in from //GitHub//. Other viewing options like MyBinder or NBViewer may have issues with displaying images or coloring of certain parts (missing images can be viewed in the folder //files// on GitHub). \n\n-The original paper, as well as the data and codes provided by the authors can be accessed here: https://www.aeaweb.org/articles?id=10.1257/app.2.1.165\n\n\n\n```python\n#importing packages\nimport numpy as np\nimport pandas as pd\nfrom statsmodels.formula.api import wls\nfrom auxiliary import *\nfrom auxiliary2 import *\n#setting up dataframes\ndf_ind1 = pd.read_csv( 'data/p00use_mf_indiv1.csv')\ndf_ind2 = pd.read_csv( 'data/p00use_mf_indiv2.csv')\ndf_ind = df_ind1.append(df_ind2)\ndf_mat = pd.read_csv( 'data/p00use_mf_matched_with_spouse.csv')\n\n```\n\n<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\">\n<ul class=\"toc-item\">\n    <li><span><a href=\"#1.-Introduction\" data-toc-modified-id=\"1.-Introduction-1\">1. Introduction</a></span></li>\n        <li><span><a href=\"#2.-Theoretical-Background-and-Data-Description\" data-toc-modified-id=\"##2.-Theoretical-Background-and-Data-Description-2\">2. Theoretical Background and Data Description</a></span><ul class=\"toc-item\">\n        <li><span><a href=\"#2.1-Theoretical-Background\" data-toc-modified-id=\"2.1-Theoretical-Background-2.1\">2.1 Theoretical Background</a></span></li>\n        <li><span><a href=\"#2.2-Data-Description\" data-toc-modified-id=\"2.2-Data-Description-2.2\">2.2 Data Description</a></span></li></ul></li>    \n    <li><span><a href=\"#3.-Identification-and-Empirical-Strategy\" data-toc-modified-id=\"3.-Identification-and-Empirical-Strategy-3\">3. Identification and Empirical Strategy</a></span></li>\n    <li><span><a href=\"#4.-Conceptual-issues-in-the-benchmark\" data-toc-modified-id=\"#4.-Conceptual-issues-in-the-benchmark-4\">4. Conceptual issues in the benchmark</a></span><ul class=\"toc-item\">\n        <li><span><a href=\"#4.1-Social-outcome-and-social-assimilation\" data-toc-modified-id=\"4.1-Social-outcome-and-social-assimilation-4.1\">4.1 Social outcome and social assimilation</a></span></li>\n    <li><span><a href=\"#4.2-Exogeneity-of-age-at-arrival\" data-toc-modified-id=\"4.2-Exogeneity-of-age-at-arrival-4.2\">4.2 Exogeneity of age at arrival</a></span></li>\n        <li><span><a href=\"#4.3-Cultural-connotations-in-language\" data-toc-modified-id=\"4.3-Cultural-connotations-in-language-4.3\">4.3 Cultural connotations in language</a></span></li></ul></li>\n\n<li><span><a href=\"#5.-Replication\" data-toc-modified-id=\"#5.-Replication-5\">5. Replication</a></span><ul class=\"toc-item\"><li><span><a href=\"#5.1-Main-result\" data-toc-modified-id=\"5.1-Main-result-5.1\">5.1 Main result</a></span></li><li><span><a href=\"#5.2-Robustness-checks-in-the-benchmark\" data-toc-modified-id=\"5.2-Robustness-checks-in-the-benchmark-5.2\">5.2 Robustness checks in the benchmark</a></span></li></ul></li>\n<li><span><a href=\"#6.-Robustness-checks-and-extensions\" data-toc-modified-id=\"#6.-Robustness-checks-and-extensions-6\">6. Robustness checks and extensions</a></span><ul class=\"toc-item\"><li><span><a href=\"#6.1-Durbin-Wu-Hausman-test\" data-toc-modified-id=\"6.1-Durbin-Wu-Hausman-test-6.1\">6.1 Durbin Wu Hausman test</a></span></li><li><span><a href=\"#6.2-Control-for-residence-location\" data-toc-modified-id=\"6.2-Control-for=residence-location-6.2\">6.2 Control for residence location</a></span></li><li><span><a href=\"#6.3-English-effect-on-outcome-gap-between-immigrants-and-spouses\" data-toc-modified-id=\"6.3-English-effect-on-outcome-gap-between-immigrants-and-spouses-6.3\">6.3 English effect on outcome gap between immigrants and spouses</a></span></li></ul></li>\n<li><span><a href=\"#7.-Conclusion\" data-toc-modified-id=\"7.-Conclusion-7\">7. Conclusion</a></span></li><li><span><a href=\"#8.-References\" data-toc-modified-id=\"8.-References-8\">8. References</a></span></li></ul></div>\n\n\n\n---\n# 1. Introduction \n---\nAmong numerous scholars, Beakley and Chin (2010) discuss the effect of English proficiency on social assimilation between immigrants in the US. While it is intuitive that immigrants with better English skills would be melt in the US society more thoroughly, competitive theories can be offered to explain the correlation between the two properties. A theory is that English skill lowers the difficulty, or, as economists put it, the cost of across group social interactions. As a result, interaction with the local increases when the immigrants have better English skills. On the other hand, it can also be argued that it is the people, who prefer the destination country\u2019s culture and society more, self-selected into immigrating into the US. And the higher English level of this group of people is another product of their endorsement towards the US culture. So the correlation is just driven by the cultural preference as a confounding factor, rather than causation. \n\nBeakley and Chin (2010) show evidential support for the theory that English proficiency causes social integrations using 2000 census data. The empirical strategy employed is to use the age of arrival as an instrumental variable. The justification of this practice is that the age of arrival correlates with the ability to acquire a second language and at the same time, does not affect other endogenous variables. They also exploite immigrants from Anglophone countries as a control group for non-linguistic effects of age at arrival. The IV esitmation confirms the causal effect of English proficiency on social outcome. English proficiency raises the probabilities of being divorced, having a more educated, higher earning, or US-born spouse, having fewer children. \n\nIn this notebook, we will replicate this study of Beakley and Chin. After that, a discussion of the conceptual framework and robustness checks will be offered. Our analysis explores some conceptual and econometrics issues in the original study.\n\nThis notebook is structured as follows. In the next section, we present the theoretical background that raises the authors' research interest. Following that we will give a brief data description. In Section 3, we analyze the instrumental variable strategy employed and the specification of the estimations. The main highlights of this notebook are sections 4 to 7. In Section 4, we will discuss some problems of the conceptual framework of the authors. Section 5 presents our replication of the results in the benchmark. Section 6 consists of various robustness checks adn extensions based on the benchmark. in Section 7 we sum up this paper.\n\n\n---\n# 2. Theoretical Background and Data Description\n---\n## 2.1 Theoretical Background\n\nResearchers are motivated to study the factors contributing to the social assimilation of immigrants. Previous studies, such as Gillian Stevens and Gray Swicegood (1987), Brian Duncan and Stephen J. Trejo (2007), Xin Meng and Robert G. Gregory (2005) have shown that English proficiency raises the probability of intermarriage. Duncan and Trejo (2007) particularly examine Mexican immigrants\u2019 marital outcomes. They investigate certain characteristics of Mexican Americans. It is revealed that Mexican Americans who are married to non-Mexicans \u201ctend to speak better English, be more educated, be more likely to work, and earn more compared to Mexican Americans married to either Mexican immigrants or US-born Mexicans\u201d. Similar evidence to support English proficiency relationships with fertility outcomes are given by Ann Marie Sorenson et al. (1988), and Swicegood et al. (1988). Apart from marital and fertility outcomes, English proficiency also correlated with residential location outcomes, as Edward Funkhouser and Fernando A. Ramos (1993) and Maude Toussaint-Comeau and Sherrie L. W. Rhine (2004) demonstrated. The relationship between the proficiency of the dominant language in the destination country and the level of social assimilation brings significant policy implications. If knowing the mainstream language helps immigrants integrating into their new home, then policies help improving language skills can certainly enhance social harmony.\n\nBut the nature of that correlation is still debatable. The \u201ccasual hypothesis\u201d claims that language proficiency lower the effort, or in an economics terminology - the \u201ccost\u201d of social interaction with the local residents. Under this partial equilibrium framework, lowering the cost of social interaction implies an increase in the consumption of it. Therefore the language proficiency causes social interaction. However, this hypothesis comes across challenges. The first one is that language proficiency is correlated with other variables that will affect the social outcome. For example, how well a person masters a second language is correlated with his ability such as IQ. It is possible that an immigrant is getting a well-paid simply because of his higher ability instead of language proficiency. Secondly, even if there is a direct relationship between language proficiency and social outcome, it still remains doubtful if it is the people have assimilated into the destination country, such as by having a spouse or a job in the destination country, can improve the English proficiency during their stay in the destination country. \n\n\n## 2.2 Data Description \n\nOur data is obtained from the 2000 US Census of Population and Housing. Measures including English level, a crucial variable for our computation of the instrumental variable, are self-reported by the respondent as a categorical variable. The census was conducted on household level. We can identify each respondent\u2019s and the cohabiting spouse\u2019s answer. Martial outcomes in social assimilation are therefore possible to be shown.\n\nWe subset the data to childhood immigrants currently aged from 25 to 55. A childhood immigrant is an immigrant who was under age 15 upon arrival in the US. A childhood immigrant typically did not choose to immigrate but just follow the parents\u2019 decision. Under our definition, a childhood immigrant spent at least 11 years and at most 55 years in the US. The minimum and maximum age of observations ensure enough years are given to expose to the English environment, at the same time avoid selection biases due to retired and deceased immigrants. \n\nWe further subset the data by their origins\u2019 English tie. A childhood immigrant who has a non-English-speaking country of birth belongs to the treatment group. A childhood immigrant whose countries of birth have English as 1) an official language and 2) predominant language, belongs to the control group\n\nOur descriptive statistics can be shown as follows. \n\n\n```python\nsumlist_ind = [\"eng\", \"age\", \"female\", \"white\" , \"black\" , \"asianpi\"  , \"other\",  \"multi\" , \"hispdum\" ,\"yrssch\", \"marriedpresent\" ,\"divorced\" ,\"evermarried\", \"nchild\", \"haskid\" ,\"singleparent\" ,\"nevermarried_haskid\", \"share_bpld_minusself\" ,\"abovemean_bpld2\" ,\"ancestpct_minusself\" ,\"abovemean_ancestry2\" ,\"nengdom\", \"young9\",\"perwt2\" ]\nsumlist_mat = [\"spouseeng\", \"marriednative\" ,\"couplesamebpld\", \"couplesameancestry1\", \"spouseage\", \"spouseyrssch\" ,\"yrssch\" ,\"spouselnwage\", \"spouseworkedly\" ,\"bothworked\" ,\"nchild\" ,\"haskid\", \"nengdom\", \"young9\",\"perwt2\"]\n\n#droppingh Null entry in english skills\ndf_ind['eng'].replace('  ', np.nan, inplace=True)\ndf_ind= df_ind.dropna(subset=['eng'])\n\ndf_ind[\"young9\"] = np.where(df_ind.agearr<=9,1,0)\n\ndfs_ind= df_ind[sumlist_ind]\n\ndfs_ind.loc[(dfs_ind[\"nengdom\"] ==1 ), 'English group'] = 'Treatment Group : Born in non-English-speaking country'\ndfs_ind.loc[(dfs_ind[\"nengdom\"] ==1 )&( dfs_ind[\"young9\"] == 1), 'Age group'] = 'Arrived Age 0-9'\ndfs_ind.loc[(dfs_ind[\"nengdom\"] ==1 )&( dfs_ind[\"young9\"] == 0), 'Age group'] = 'Arrived Age 10-14'\n\ndfs_ind.loc[(dfs_ind[\"nengdom\"] ==0 ), 'English group'] = 'Control Group: Born in English-speaking country'\ndfs_ind.loc[(dfs_ind[\"nengdom\"] ==0 )&( dfs_ind[\"young9\"] == 1), 'Age group'] = 'Arrived Age 0-9'\ndfs_ind.loc[(dfs_ind[\"nengdom\"] ==0 )&( dfs_ind[\"young9\"] == 0), 'Age group'] = 'Arrived Age 10-14'\n\ndfs_ind= dfs_ind.drop(['nengdom', 'young9'], axis=1)\n\n#droppingh Null entry in english skills\ndf_mat['eng'].replace('  ', np.nan, inplace=True)\ndf_mat= df_mat.dropna(subset=['eng'])\n\ndf_mat[\"young9\"] = df_mat[\"agearr\"] <=9\n\n# keeping useful variables\n\ndfs_mat= df_mat[sumlist_mat]\n\ndfs_mat.loc[(dfs_mat[\"nengdom\"] ==1 ), 'English group'] = 'Treatment Group : Born in non-English-speaking country'\ndfs_mat.loc[(dfs_mat[\"nengdom\"] ==1 )&( dfs_mat[\"young9\"] == 1), 'Age group'] = 'Arrived Age 0-9'\ndfs_mat.loc[(dfs_mat[\"nengdom\"] ==1 )&( dfs_mat[\"young9\"] == 0), 'Age group'] = 'Arrived Age 10-14'\n\ndfs_mat.loc[(dfs_mat[\"nengdom\"] ==0 ), 'English group'] = 'Control Group: Born in English-speaking country'\ndfs_mat.loc[(dfs_mat[\"nengdom\"] ==0 )&( dfs_mat[\"young9\"] == 1), 'Age group'] = 'Arrived Age 0-9'\ndfs_mat.loc[(dfs_mat[\"nengdom\"] ==0 )&( dfs_mat[\"young9\"] == 0), 'Age group'] = 'Arrived Age 10-14'\ndfs_mat = dfs_mat.rename(columns={'nchild': 'nchild_spouse', 'haskid': 'haskid_spouse'})\ndfs_mat= dfs_mat.drop(['nengdom', 'young9'], axis=1)\n\n# the observations is to be weighted by perwt2\nsumlist_ind.remove(\"nengdom\")\nsumlist_ind.remove(\"young9\")\nsumlist_ind.remove(\"perwt2\")\nsumlist_mat.remove(\"nengdom\")\nsumlist_mat.remove(\"young9\")\nsumlist_mat.remove(\"perwt2\")\n\n\ndfs_ind= dfs_ind.drop(['perwt2'], axis=1)\ndfs_mat= dfs_mat.drop(['perwt2'], axis=1)\nlist_table1 = list(dfs_ind.columns)\nlist_table1.remove(\"English group\")\nlist_table1.remove(\"Age group\")\nlist_table2 = list(dfs_mat.columns)\nlist_table2.remove(\"English group\")\nlist_table2.remove(\"Age group\")\n\n\nfor i in list_table1:\n    dfs_ind = dfs_ind.rename(columns={i: Dict_for_sumlist1[i]})\nfor i in list_table2:\n    dfs_mat = dfs_mat.rename(columns={i: Dict_for_sumlist1[i]})\n\n\n```\n\n    /Users/chingfungchow/opt/anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py:844: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      self.obj[key] = _infer_fill_value(value)\n    /Users/chingfungchow/opt/anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py:965: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      self.obj[item] = s\n\n\n\n```python\nprint(\"Table 1a: the mean and SD of variables for the control group and treatment group\")\nprint(\"This table refers to column (4) and (1) in Table 1 of the benchmark\" )\n\n\nprint(\"The mean of variables for control group and treatment group\")\nwith pd.option_context('display.max_rows', None, 'display.max_columns', None): \n    display(dfs_ind.groupby([\"English group\"]).mean(), dfs_mat.groupby([\"English group\"]).mean())\n\nprint(\"The standard deviation of variables for control group and treatment group\")\nwith pd.option_context('display.max_rows', None, 'display.max_columns', None): \n    display(dfs_ind.groupby([\"English group\"]).std(), dfs_mat.groupby([\"English group\"]).mean())\n\n```\n\n    Table 1a: the mean and SD of variables for the control group and treatment group\n    This table refers to column (4) and (1) in Table 1 of the benchmark\n    The mean of variables for control group and treatment group\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>English-speaking ability ordinal measure</th>\n      <th>Age</th>\n      <th>Female</th>\n      <th>White</th>\n      <th>Black</th>\n      <th>Asian/Pacific Islander</th>\n      <th>Other single race</th>\n      <th>Multiracial</th>\n      <th>Hispanic</th>\n      <th>Years of schooling</th>\n      <th>Is currently married with spouse present</th>\n      <th>Is currently divorced</th>\n      <th>Has ever married</th>\n      <th>Number of children living in same household</th>\n      <th>Has a child living in same household</th>\n      <th>Is a single parent</th>\n      <th>Is a never married, single parent</th>\n      <th>Fraction of PUMA population from same country of birth</th>\n      <th>Fraction from same country of birth is above national mean for the country of birth</th>\n      <th>Fraction of PUMA population with same primary ancestry</th>\n      <th>Fraction with same ancestry is above national mean for the primary ancestry</th>\n    </tr>\n    <tr>\n      <th>English group</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Control Group: Born in English-speaking country</th>\n      <td>2.980587</td>\n      <td>38.763566</td>\n      <td>0.529178</td>\n      <td>0.690274</td>\n      <td>0.225087</td>\n      <td>0.027673</td>\n      <td>0.018989</td>\n      <td>0.037978</td>\n      <td>0.012157</td>\n      <td>14.474017</td>\n      <td>0.571562</td>\n      <td>0.122183</td>\n      <td>0.748834</td>\n      <td>0.972250</td>\n      <td>0.509649</td>\n      <td>0.105012</td>\n      <td>0.034693</td>\n      <td>0.007964</td>\n      <td>0.356678</td>\n      <td>0.044566</td>\n      <td>0.368470</td>\n    </tr>\n    <tr>\n      <th>Treatment Group : Born in non-English-speaking country</th>\n      <td>2.714701</td>\n      <td>36.616986</td>\n      <td>0.501723</td>\n      <td>0.553140</td>\n      <td>0.028159</td>\n      <td>0.118414</td>\n      <td>0.247922</td>\n      <td>0.052365</td>\n      <td>0.521571</td>\n      <td>13.089313</td>\n      <td>0.605827</td>\n      <td>0.097178</td>\n      <td>0.771019</td>\n      <td>1.244415</td>\n      <td>0.584227</td>\n      <td>0.102999</td>\n      <td>0.029651</td>\n      <td>0.064826</td>\n      <td>0.343112</td>\n      <td>0.117402</td>\n      <td>0.369346</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Spouse English-speaking ability ordinal measure</th>\n      <th>Spouse is US-born</th>\n      <th>Spouse has the same country of birth</th>\n      <th>Spouse has the same ancestry</th>\n      <th>Spouse age</th>\n      <th>Spouse years of schooling</th>\n      <th>Years of schooling</th>\n      <th>Spouse log(wages last year)</th>\n      <th>Spouse worked last year</th>\n      <th>Both worked last year</th>\n      <th>Number of children living in same household, only individuals married spouse present</th>\n      <th>Has a child living in same household, only individuals married with spouse present</th>\n    </tr>\n    <tr>\n      <th>English group</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Control Group: Born in English-speaking country</th>\n      <td>2.978607</td>\n      <td>0.812874</td>\n      <td>0.089315</td>\n      <td>0.243836</td>\n      <td>40.771411</td>\n      <td>14.528200</td>\n      <td>14.597188</td>\n      <td>10.362746</td>\n      <td>0.881479</td>\n      <td>0.779933</td>\n      <td>1.397906</td>\n      <td>0.710372</td>\n    </tr>\n    <tr>\n      <th>Treatment Group : Born in non-English-speaking country</th>\n      <td>2.587381</td>\n      <td>0.499035</td>\n      <td>0.390376</td>\n      <td>0.543241</td>\n      <td>38.176907</td>\n      <td>12.965574</td>\n      <td>13.103995</td>\n      <td>10.191646</td>\n      <td>0.825765</td>\n      <td>0.701292</td>\n      <td>1.736242</td>\n      <td>0.797043</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    The standard deviation of variables for control group and treatment group\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>English-speaking ability ordinal measure</th>\n      <th>Age</th>\n      <th>Female</th>\n      <th>White</th>\n      <th>Black</th>\n      <th>Asian/Pacific Islander</th>\n      <th>Other single race</th>\n      <th>Multiracial</th>\n      <th>Hispanic</th>\n      <th>Years of schooling</th>\n      <th>Is currently married with spouse present</th>\n      <th>Is currently divorced</th>\n      <th>Has ever married</th>\n      <th>Number of children living in same household</th>\n      <th>Has a child living in same household</th>\n      <th>Is a single parent</th>\n      <th>Is a never married, single parent</th>\n      <th>Fraction of PUMA population from same country of birth</th>\n      <th>Fraction from same country of birth is above national mean for the country of birth</th>\n      <th>Fraction of PUMA population with same primary ancestry</th>\n      <th>Fraction with same ancestry is above national mean for the primary ancestry</th>\n    </tr>\n    <tr>\n      <th>English group</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Control Group: Born in English-speaking country</th>\n      <td>0.166150</td>\n      <td>8.440097</td>\n      <td>0.499158</td>\n      <td>0.462389</td>\n      <td>0.417648</td>\n      <td>0.164036</td>\n      <td>0.136488</td>\n      <td>0.191146</td>\n      <td>0.109591</td>\n      <td>2.469523</td>\n      <td>0.494862</td>\n      <td>0.327504</td>\n      <td>0.433692</td>\n      <td>1.171388</td>\n      <td>0.499917</td>\n      <td>0.306574</td>\n      <td>0.183005</td>\n      <td>0.018780</td>\n      <td>0.47903</td>\n      <td>0.061740</td>\n      <td>0.482402</td>\n    </tr>\n    <tr>\n      <th>Treatment Group : Born in non-English-speaking country</th>\n      <td>0.624551</td>\n      <td>8.295871</td>\n      <td>0.499999</td>\n      <td>0.497170</td>\n      <td>0.165428</td>\n      <td>0.323098</td>\n      <td>0.431808</td>\n      <td>0.222762</td>\n      <td>0.499536</td>\n      <td>3.476692</td>\n      <td>0.488674</td>\n      <td>0.296201</td>\n      <td>0.420178</td>\n      <td>1.335926</td>\n      <td>0.492856</td>\n      <td>0.303958</td>\n      <td>0.169623</td>\n      <td>0.105865</td>\n      <td>0.47475</td>\n      <td>0.156028</td>\n      <td>0.482630</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Spouse English-speaking ability ordinal measure</th>\n      <th>Spouse is US-born</th>\n      <th>Spouse has the same country of birth</th>\n      <th>Spouse has the same ancestry</th>\n      <th>Spouse age</th>\n      <th>Spouse years of schooling</th>\n      <th>Years of schooling</th>\n      <th>Spouse log(wages last year)</th>\n      <th>Spouse worked last year</th>\n      <th>Both worked last year</th>\n      <th>Number of children living in same household, only individuals married spouse present</th>\n      <th>Has a child living in same household, only individuals married with spouse present</th>\n    </tr>\n    <tr>\n      <th>English group</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Control Group: Born in English-speaking country</th>\n      <td>2.978607</td>\n      <td>0.812874</td>\n      <td>0.089315</td>\n      <td>0.243836</td>\n      <td>40.771411</td>\n      <td>14.528200</td>\n      <td>14.597188</td>\n      <td>10.362746</td>\n      <td>0.881479</td>\n      <td>0.779933</td>\n      <td>1.397906</td>\n      <td>0.710372</td>\n    </tr>\n    <tr>\n      <th>Treatment Group : Born in non-English-speaking country</th>\n      <td>2.587381</td>\n      <td>0.499035</td>\n      <td>0.390376</td>\n      <td>0.543241</td>\n      <td>38.176907</td>\n      <td>12.965574</td>\n      <td>13.103995</td>\n      <td>10.191646</td>\n      <td>0.825765</td>\n      <td>0.701292</td>\n      <td>1.736242</td>\n      <td>0.797043</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n```python\nprint(\"Table 1b: the mean and SD of variables for the age groups\")\nprint(\"This table refers to column (5), (6), (2) and (3) in Table 1 of the benchmark\" )\n\n\nprint(\"The mean of variables for age groups\")\nwith pd.option_context('display.max_rows', None, 'display.max_columns', None): \n    display(dfs_ind.groupby([\"English group\",\"Age group\"]).mean(), dfs_mat.groupby([\"English group\",\"Age group\"]).mean())\n\nprint(\"The standard deviation of variables for age groups\")\nwith pd.option_context('display.max_rows', None, 'display.max_columns', None): \n    display(dfs_ind.groupby([\"English group\",\"Age group\"]).std(), dfs_mat.groupby([\"English group\",\"Age group\"]).std())\n\n```\n\n    Table 1b: the mean and SD of variables for the age groups\n    This table refers to column (5), (6), (2) and (3) in Table 1 of the benchmark\n    The mean of variables for age groups\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>English-speaking ability ordinal measure</th>\n      <th>Age</th>\n      <th>Female</th>\n      <th>White</th>\n      <th>Black</th>\n      <th>Asian/Pacific Islander</th>\n      <th>Other single race</th>\n      <th>Multiracial</th>\n      <th>Hispanic</th>\n      <th>Years of schooling</th>\n      <th>Is currently married with spouse present</th>\n      <th>Is currently divorced</th>\n      <th>Has ever married</th>\n      <th>Number of children living in same household</th>\n      <th>Has a child living in same household</th>\n      <th>Is a single parent</th>\n      <th>Is a never married, single parent</th>\n      <th>Fraction of PUMA population from same country of birth</th>\n      <th>Fraction from same country of birth is above national mean for the country of birth</th>\n      <th>Fraction of PUMA population with same primary ancestry</th>\n      <th>Fraction with same ancestry is above national mean for the primary ancestry</th>\n    </tr>\n    <tr>\n      <th>English group</th>\n      <th>Age group</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">Control Group: Born in English-speaking country</th>\n      <th>Arrived Age 0-9</th>\n      <td>2.981686</td>\n      <td>39.253070</td>\n      <td>0.517638</td>\n      <td>0.784599</td>\n      <td>0.146098</td>\n      <td>0.023933</td>\n      <td>0.015765</td>\n      <td>0.029605</td>\n      <td>0.012383</td>\n      <td>14.530509</td>\n      <td>0.592591</td>\n      <td>0.125373</td>\n      <td>0.767568</td>\n      <td>0.968783</td>\n      <td>0.506243</td>\n      <td>0.093349</td>\n      <td>0.026529</td>\n      <td>0.006077</td>\n      <td>0.354117</td>\n      <td>0.047387</td>\n      <td>0.371457</td>\n    </tr>\n    <tr>\n      <th>Arrived Age 10-14</th>\n      <td>2.977429</td>\n      <td>37.357250</td>\n      <td>0.562332</td>\n      <td>0.419283</td>\n      <td>0.452018</td>\n      <td>0.038416</td>\n      <td>0.028251</td>\n      <td>0.062033</td>\n      <td>0.011510</td>\n      <td>14.310811</td>\n      <td>0.510937</td>\n      <td>0.112988</td>\n      <td>0.694826</td>\n      <td>0.982212</td>\n      <td>0.519432</td>\n      <td>0.138633</td>\n      <td>0.058229</td>\n      <td>0.013380</td>\n      <td>0.364026</td>\n      <td>0.036520</td>\n      <td>0.359955</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">Treatment Group : Born in non-English-speaking country</th>\n      <th>Arrived Age 0-9</th>\n      <td>2.871498</td>\n      <td>36.915149</td>\n      <td>0.514670</td>\n      <td>0.610062</td>\n      <td>0.028415</td>\n      <td>0.101546</td>\n      <td>0.207741</td>\n      <td>0.052237</td>\n      <td>0.450864</td>\n      <td>13.710728</td>\n      <td>0.591752</td>\n      <td>0.108141</td>\n      <td>0.761897</td>\n      <td>1.144813</td>\n      <td>0.559275</td>\n      <td>0.103195</td>\n      <td>0.027926</td>\n      <td>0.053551</td>\n      <td>0.318821</td>\n      <td>0.108715</td>\n      <td>0.357619</td>\n    </tr>\n    <tr>\n      <th>Arrived Age 10-14</th>\n      <td>2.429342</td>\n      <td>36.074351</td>\n      <td>0.478161</td>\n      <td>0.449547</td>\n      <td>0.027695</td>\n      <td>0.149111</td>\n      <td>0.321049</td>\n      <td>0.052598</td>\n      <td>0.650252</td>\n      <td>11.943063</td>\n      <td>0.631535</td>\n      <td>0.077152</td>\n      <td>0.787681</td>\n      <td>1.425683</td>\n      <td>0.629638</td>\n      <td>0.102640</td>\n      <td>0.032802</td>\n      <td>0.085421</td>\n      <td>0.387485</td>\n      <td>0.133040</td>\n      <td>0.390458</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>Spouse English-speaking ability ordinal measure</th>\n      <th>Spouse is US-born</th>\n      <th>Spouse has the same country of birth</th>\n      <th>Spouse has the same ancestry</th>\n      <th>Spouse age</th>\n      <th>Spouse years of schooling</th>\n      <th>Years of schooling</th>\n      <th>Spouse log(wages last year)</th>\n      <th>Spouse worked last year</th>\n      <th>Both worked last year</th>\n      <th>Number of children living in same household, only individuals married spouse present</th>\n      <th>Has a child living in same household, only individuals married with spouse present</th>\n    </tr>\n    <tr>\n      <th>English group</th>\n      <th>Age group</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">Control Group: Born in English-speaking country</th>\n      <th>Arrived Age 0-9</th>\n      <td>2.980906</td>\n      <td>0.865519</td>\n      <td>0.052804</td>\n      <td>0.218093</td>\n      <td>41.111965</td>\n      <td>14.588204</td>\n      <td>14.627805</td>\n      <td>10.362293</td>\n      <td>0.882938</td>\n      <td>0.782613</td>\n      <td>1.378366</td>\n      <td>0.698985</td>\n    </tr>\n    <tr>\n      <th>Arrived Age 10-14</th>\n      <td>2.970929</td>\n      <td>0.636847</td>\n      <td>0.211397</td>\n      <td>0.326992</td>\n      <td>39.632713</td>\n      <td>14.325539</td>\n      <td>14.494630</td>\n      <td>10.364303</td>\n      <td>0.876543</td>\n      <td>0.770866</td>\n      <td>1.463242</td>\n      <td>0.748450</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">Treatment Group : Born in non-English-speaking country</th>\n      <th>Arrived Age 0-9</th>\n      <td>2.758109</td>\n      <td>0.636782</td>\n      <td>0.263390</td>\n      <td>0.458948</td>\n      <td>38.582139</td>\n      <td>13.599222</td>\n      <td>13.820854</td>\n      <td>10.257401</td>\n      <td>0.848429</td>\n      <td>0.733346</td>\n      <td>1.618122</td>\n      <td>0.772752</td>\n    </tr>\n    <tr>\n      <th>Arrived Age 10-14</th>\n      <td>2.293690</td>\n      <td>0.263271</td>\n      <td>0.607723</td>\n      <td>0.682739</td>\n      <td>37.483322</td>\n      <td>11.861887</td>\n      <td>11.859057</td>\n      <td>10.065613</td>\n      <td>0.786248</td>\n      <td>0.644896</td>\n      <td>1.938413</td>\n      <td>0.838620</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    The standard deviation of variables for age groups\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>English-speaking ability ordinal measure</th>\n      <th>Age</th>\n      <th>Female</th>\n      <th>White</th>\n      <th>Black</th>\n      <th>Asian/Pacific Islander</th>\n      <th>Other single race</th>\n      <th>Multiracial</th>\n      <th>Hispanic</th>\n      <th>Years of schooling</th>\n      <th>Is currently married with spouse present</th>\n      <th>Is currently divorced</th>\n      <th>Has ever married</th>\n      <th>Number of children living in same household</th>\n      <th>Has a child living in same household</th>\n      <th>Is a single parent</th>\n      <th>Is a never married, single parent</th>\n      <th>Fraction of PUMA population from same country of birth</th>\n      <th>Fraction from same country of birth is above national mean for the country of birth</th>\n      <th>Fraction of PUMA population with same primary ancestry</th>\n      <th>Fraction with same ancestry is above national mean for the primary ancestry</th>\n    </tr>\n    <tr>\n      <th>English group</th>\n      <th>Age group</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">Control Group: Born in English-speaking country</th>\n      <th>Arrived Age 0-9</th>\n      <td>0.162508</td>\n      <td>8.435833</td>\n      <td>0.499702</td>\n      <td>0.411111</td>\n      <td>0.353213</td>\n      <td>0.152846</td>\n      <td>0.124568</td>\n      <td>0.169498</td>\n      <td>0.110590</td>\n      <td>2.458518</td>\n      <td>0.491365</td>\n      <td>0.331150</td>\n      <td>0.422394</td>\n      <td>1.170186</td>\n      <td>0.499974</td>\n      <td>0.290929</td>\n      <td>0.160707</td>\n      <td>0.014350</td>\n      <td>0.478260</td>\n      <td>0.062808</td>\n      <td>0.483210</td>\n    </tr>\n    <tr>\n      <th>Arrived Age 10-14</th>\n      <td>0.176167</td>\n      <td>8.293738</td>\n      <td>0.496137</td>\n      <td>0.493479</td>\n      <td>0.497730</td>\n      <td>0.192212</td>\n      <td>0.165702</td>\n      <td>0.241233</td>\n      <td>0.106672</td>\n      <td>2.494056</td>\n      <td>0.499918</td>\n      <td>0.316602</td>\n      <td>0.460516</td>\n      <td>1.174865</td>\n      <td>0.499660</td>\n      <td>0.345590</td>\n      <td>0.234194</td>\n      <td>0.027100</td>\n      <td>0.481199</td>\n      <td>0.057842</td>\n      <td>0.480032</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">Treatment Group : Born in non-English-speaking country</th>\n      <th>Arrived Age 0-9</th>\n      <td>0.421750</td>\n      <td>8.391007</td>\n      <td>0.499787</td>\n      <td>0.487738</td>\n      <td>0.166155</td>\n      <td>0.302052</td>\n      <td>0.405692</td>\n      <td>0.222505</td>\n      <td>0.497582</td>\n      <td>2.958999</td>\n      <td>0.491512</td>\n      <td>0.310560</td>\n      <td>0.425924</td>\n      <td>1.272928</td>\n      <td>0.496476</td>\n      <td>0.304215</td>\n      <td>0.164761</td>\n      <td>0.098546</td>\n      <td>0.466022</td>\n      <td>0.147841</td>\n      <td>0.479302</td>\n    </tr>\n    <tr>\n      <th>Arrived Age 10-14</th>\n      <td>0.806270</td>\n      <td>8.091798</td>\n      <td>0.499527</td>\n      <td>0.497452</td>\n      <td>0.164098</td>\n      <td>0.356201</td>\n      <td>0.466884</td>\n      <td>0.223231</td>\n      <td>0.476894</td>\n      <td>4.025796</td>\n      <td>0.482392</td>\n      <td>0.266835</td>\n      <td>0.408953</td>\n      <td>1.425808</td>\n      <td>0.482906</td>\n      <td>0.303491</td>\n      <td>0.178120</td>\n      <td>0.115257</td>\n      <td>0.487181</td>\n      <td>0.168651</td>\n      <td>0.487858</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>Spouse English-speaking ability ordinal measure</th>\n      <th>Spouse is US-born</th>\n      <th>Spouse has the same country of birth</th>\n      <th>Spouse has the same ancestry</th>\n      <th>Spouse age</th>\n      <th>Spouse years of schooling</th>\n      <th>Years of schooling</th>\n      <th>Spouse log(wages last year)</th>\n      <th>Spouse worked last year</th>\n      <th>Both worked last year</th>\n      <th>Number of children living in same household, only individuals married spouse present</th>\n      <th>Has a child living in same household, only individuals married with spouse present</th>\n    </tr>\n    <tr>\n      <th>English group</th>\n      <th>Age group</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">Control Group: Born in English-speaking country</th>\n      <th>Arrived Age 0-9</th>\n      <td>0.162387</td>\n      <td>0.341184</td>\n      <td>0.223651</td>\n      <td>0.412972</td>\n      <td>8.879019</td>\n      <td>2.547842</td>\n      <td>2.420732</td>\n      <td>1.048971</td>\n      <td>0.321509</td>\n      <td>0.412487</td>\n      <td>1.204742</td>\n      <td>0.458720</td>\n    </tr>\n    <tr>\n      <th>Arrived Age 10-14</th>\n      <td>0.197274</td>\n      <td>0.480979</td>\n      <td>0.408359</td>\n      <td>0.469191</td>\n      <td>9.004840</td>\n      <td>2.576121</td>\n      <td>2.462243</td>\n      <td>0.960799</td>\n      <td>0.329012</td>\n      <td>0.420341</td>\n      <td>1.191644</td>\n      <td>0.433968</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">Treatment Group : Born in non-English-speaking country</th>\n      <th>Arrived Age 0-9</th>\n      <td>0.599838</td>\n      <td>0.480931</td>\n      <td>0.440476</td>\n      <td>0.498316</td>\n      <td>9.119282</td>\n      <td>3.284479</td>\n      <td>2.904518</td>\n      <td>0.991118</td>\n      <td>0.358608</td>\n      <td>0.442214</td>\n      <td>1.255057</td>\n      <td>0.419058</td>\n    </tr>\n    <tr>\n      <th>Arrived Age 10-14</th>\n      <td>0.923215</td>\n      <td>0.440414</td>\n      <td>0.488265</td>\n      <td>0.465417</td>\n      <td>9.096449</td>\n      <td>4.176946</td>\n      <td>4.035474</td>\n      <td>0.986808</td>\n      <td>0.409960</td>\n      <td>0.478552</td>\n      <td>1.353711</td>\n      <td>0.367886</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\nOur descriptive statistics, althought slightly deviate from the benchmarks,give support to the age-language relationship picture we drawn. Late arrivers in treatment group and control group demonstrate a significant difference in English level, while earlier arrivers\u2019 English level are similar.\n\n\n---\n# 3. Identification and Empirical Strategy\n--- \n\nThe challenges require advanced econometrics techniques beyond ordinary least square estimation. The authors choose to use the method of instrumental variable to tackle the issues. What stands out the benchmark compared to other literature is that the authors sensibly make use of the fact that children acquire foreign languages with ease. This strategy is supported by research in physiological studies where researchers identified the physiological feature in the brain which is known as the \u201ccritical period of language acquisition\u201d (Eric H. Lenneberg 1967). \n\nThe social outcomes are assumed to be a function of age at arrival for non-Anglophone-origin immigrants. If a person coming from a non-English speaking country immigrates to the US at a younger age, one\u2019s English level is going to be closer to the native speakers. It is further assumed that there is no direct effect of age of arrival on the social assimilation. Therefore age-of-arrival will be suitable IV to control for the ability effect.\n\n\nOur instrumental variable is define as follows:\n\n\\begin{equation}\\tag{1}\n  k_{ija}= max (0, a-9) * I (j\\quad  is\\quad  a\\quad  non-English-speaking\\quad  country) \n\\end{equation}\n\nwhere *a* is age at arrival, *I*(\u00b7) is the indicator function, and *j* is country of birth\n\n\n\n\\begin{equation}\\tag{2}\nENG_{ija}= \\alpha_{1}+\\pi_{1}k_{ija}+\\delta_{1a}+\\gamma_{1j}+W_{ija}'\\rho_{1}+\\epsilon_{1ija}\n\\end{equation}\n\nfor individual *i*  born in country *j* arriving in the US at age *a*.  $ENG_{ija}$ is a measure of English language skills, $\u03b4_{1a}$ is a set of age-at-arrival dummies, $\u03b3_{1j}$  is a set of country-of-birth dummies, and $w_{ija}$  is a vector of exogenous explanatory variables (e.g., age, sex, race).\n\n\n\nThe OLS esitmation is given by \n\\begin{equation}\\tag{3}\ny_{ija}= \\alpha_{1}+ \\beta ENG_{ija} + \\delta_{a}+\\gamma_{j} + W_{ija}'\\rho + \\epsilon_{ija}\n\\end{equation}\n\nfor individual *i*  born in country *j* arriving in the US at age *a*. $y_{ija}$ is the outcome , $ENG_{ija}$ is a measure of English language skills (the endogenous regressor), $\u03b4_{a}$ is a set of age-at-arrival dummies, $\u03b3_{j}$  is a set of country-of-birth dummies, and $w_{ija}$  is a vector of exogenous explanatory variables (e.g., age, sex, race).\n\n\nThe OLS estimation of equation (3) will be biased because of endogeneity issue. The IV strategy we employed is to get \nthe first stage esitmate of $\\hat{ENG_{ija}}$ using equation (2). And then use $\\hat{ENG_{ija}}$ instead of  $ENG_{ija}$ in the second stage estimate, i.e. equation (4)\n\n\\begin{equation}\\tag{4}\ny_{ija}= \\alpha_{1}+ \\beta^{2SLS} \\hat{ENG_{ija}} + \\delta_{a}+\\gamma_{j} + W_{ija}'\\rho + \\epsilon_{ija}\n\\end{equation}\n\nThe estimation of ${\u03b2^{2SLS}}$ will be our target. \n\nOur model can be visualized by a causal graph.\n\nFigure 1. Causal graph\n\n\n---\n# 4. Conceptual issues in the benchmark\n---\n\n### 4.1 Social outcome and social assimilation\nIt seems to us that the authors are treating *social outcome* and *social assimilation* as a pair of synonymies when they are analyzing the statistics result. \n\nIt is not clear whether the variables measure the *wellness of the integration*. For example, why an immigrant having a child in the destination country implies that he or she better fitted into US society? Or why an immigrant and his or her spouse are both implies a higher level of social assimilation? We do not see any clear and strong intuition indicating the linkage between the proposed measures and our target concepts. Certainly, for some measures, a significantly low level indicates a potential integration problem. But we cannot tell if there is no problem by an increase in the level. \n\nA thought experiment can elaborate our point. Suppose there is a group of immigrant K from a specific country. If the mean wage of K-people (when fixing other variables) is very low, then it might indicate that they on margins in the labor market. But what if the mean-wage of K-people is very high? It would also mean that they process some systematic properties that the locals do not. These properties also differentiate K-people systematically from the locals. The high mean wage does not make them more integrated into the destination society, although they are absolutely better off in terms of living standards. \n\nAn initial guess to solve the problem is to compare the difference of the mean of these variables between the immigrants and the US. If the deviation is small, then it means an immigrant is on average not having a higher or lower outcome from the locals. \n\nHowever, this is not a solution neither. This issue is more complicated by the US liberal tradition. In principle, individuals are free to choose their own form of life.  What does it mean if the immigrants are losing their \u201chomeland features\u201d? If k-people, after observing the undesirable outcome of keeping their \u201chomeland features\u201d, decide to abandon those. And they finally have an outcome having no difference in those outcomes than the locals. Are they really integrating in the US society in terms of the outcome? Or they are just integrating into the US on the surface, but they are not embracing the liberal spirit of the US, which more fundamental than those measure outcomes? To settle this debate, we have to go deep into a philosophical discussion of politics and culture. But that will not be our focus in this short article. We will just be cautious about the conceptual insufficiency of the result about certain outcomes.  \n\n\n### 4.2 Exogeneity of age at arrival \n\nOne assumption for using instrumental variable is that the instrument is as good as randomly assign and have no correlation with Y through other uncontrolled variables. The authors justify the exogeneity of age at arrival by stating that for childhood immigrants \"age at arrival is not a choice variable since they did not time their own immigration, but merely come with their parents to the United State\". \n\nWe remain skeptical concerning the exogeneity assumption. Maybe the children are not the ones *making the final call* on the immigrate decision. However, we can reasonably think that the parents, if being responsible, will take *the children's ability to assimilate into considerations* when they are deciding to immigrate or not. If the parents know that their children will have a very rough time living in a new country, they have a higher cost and less probability to immigrate. This is more easily found in East Asian nations (which are non-English-speaking) where the offspring's future is weighted heavily. In addition, for the potentially-non-assimilating children who have already entered secondary school and are unwilling to move with their parents, the parents can just send the children to boarding school or leave the children to relatives in the origins, if they have a lower cost to do so.  So these non-assimilating children will not be included in the sample. This is more common in Asian or Middle-East countries (which are non-English-speaking) where family-collectivism is practiced. Siblings of the parents or grandparents have a larger moral responsibility to proxy the parents' role when the parents cannot take care of the children themselves.\n\nThese family characteristics, when being uncontrolled for, create self-selection bias where children that are expected to have higher social outcomes will be taking the treatment. This will lead to an overestimation of the treatment effect.\n\n\n### 4.3 Cultural connotations in language\n\n\nAs the authors remark in the paper, controlling the effect of mastering English (language effect) cannot exclude the effect of \u201cmelting\u201d into the US culture and institution. The authors\u2019 solution is to incorporate immigrants from the English speaking countries as the control group, so as to control for the non-language effect. They explain their decision:\n\n>*This is because, upon arrival in the United States, immigrants originating from English-speaking countries encounter everything that immigrants from non-English-speaking countries encounter except a new language. Thus, any difference in outcome between young and old arrivers from non-English-speaking countries that is over and above the difference from English-speaking countries can plausibly be attributed to language*. (Bleakley & Chin, 2010, p.169-170).\n\nSingling out the language effect on immigrants from non-anglophone countries certainly has a significant methodological merit, as anglophone immigrants barely come across any enormous language barrier. But it seems to us doubtful whether the authors can really separate the language effect and the culture effect.  Anglophone countries do not share the 100% same culture, however close they are.to each other. It is fairly possible that a British immigrant found the US metric system, jumbo-size Coca-Cola cups, and restaurant tipping manner very confusing. There can still be an influence of culture in the estimation of the parameters for the late-comers in treatment group. \n\nWe differ our understanding of the meaning of the parameters estimated from the authors\u2019. Instead of claiming that the difference in outcome is completely attributed to language, we can defend our thesis better by arguing that we have to take into account the embedded cultural effect in language, by looking at the nature of language. As Morris (1949) pointed out, a (natural) language is composed of three parts: semantics, syntax and pragmatics; Semantics refers to \u201cthe relations of signs to the objects to which the signs are applicable\u201d are; Syntax refers to \u201cthe formal relation of signs to one another\u201d; Pragmatics is \u201cthe relations of signs to interpreters\u201d. The authors\u2019 mistake, as it appears to us, is to assume language skill level has only the syntaxial aspect. While anglophone immigrants have not many obstacles in the syntax of English in America, they might have problems in the pragmatics of American English. For example, when a British says \u201cOoh, isn\u2019t it cold?\u201d, what he is doing (with his words) is to invite the listener to a conversation , but an American will just encode it as merely a question about weather.  \n\nFigure 2. Relationship between language, culture and pragmatics\n\n\nAs it is shown by Wittgenstein (1967), \u201cthe speaking of language is part of an activity, or of a life-form\u201d. Language is a social practice. When language users are interacting, the culture of the linguistic community is manifested. Culture is embedded in a language, through the pragmatics of it. Culture is instantiated in the language uses and culture-free language is not usable and empty. The language community, having their own culture, decide the rule of the \u201clanguage game\u201d, by which they determine who is a good speaker and who is not. In other words, to be a good language user, one has to know the culture of that linguistic community. \n\nIn our estimation, we could not separate the cultures in the pragmatics side of English in America. But a comprehensive understanding of languages implies that we do not have to so do. Rather, it accepts the cultural aspect being part of the estimator of language level. And it includes the understanding of culture when interpreting the estimation of parameters. \n\n---\n# 5. Replication\n---\n\n### 5.1 Main result \n\n\nWe first estimate equation (2') which is a modification of equation (2). In equation (2') the dependent variable is a social outcome rather than English proficiency. \n\n\\begin{equation}\\tag{2'}\nY_{ija}= \\alpha_{1}+\\pi_{1}k_{ija}+\\delta_{1a}+\\gamma_{1j}+W_{ija}'\\rho_{1}+\\epsilon_{1ija}\n\\end{equation}\n\nEquation (2') is a reduced-form equation that returns the effect of age at arrival on social outcomes for the treatment group in a regression setting. From Table 2, we can observe that age-at-arrival is significant to the majority of variables the authors are interested in, except for some fertility and all location outcomes. In the benchmark, the age-at-arrival effects are to be explained through language proficiency. If this hypothesis is right, further regressions, given by equation (4) should verify that. \n\n\n\n```python\ndf_ind['eng'].replace('  ', np.nan, inplace=True)\ndf_ind= df_ind.dropna(subset=['eng'])\ndf_ind[\"pwlinear\"] = np.where(df_ind.agearr>=9, df_ind[\"agearr\"]-9 ,0)\ndf_ind[\"pwlinear\"].describe()\ndf_ind[\"idvar\"] = df_ind[\"pwlinear\"]*df_ind[\"nengdom\"]\ndf_ind[\"idvar\"].describe() \ndf_ind = (df_ind[df_ind.perwt2 !=0])\n\ndf_mat['eng'].replace('  ', np.nan, inplace=True)\ndf_mat= df_mat.dropna(subset=['eng'])\ndf_mat[\"young9\"] = df_mat[\"agearr\"] <=9\ndf_mat['eng'].replace('  ', np.nan, inplace=True)\ndf_mat= df_mat.dropna(subset=['eng'])\ndf_mat[\"pwlinear\"] = np.where(df_mat.agearr>=9, df_mat[\"agearr\"]-9 ,0)\ndf_mat[\"pwlinear\"].describe()\ndf_mat[\"idvar\"] = df_mat[\"pwlinear\"]*df_mat[\"nengdom\"]\ndf_mat[\"nchild_spouse\"] = df_mat[\"nchild\"]\ndf_mat[\"haskid_spouse\"] = df_mat[\"haskid\"]\ndf_ind[\"eng1\"] = np.where(df_ind.eng>=1,1,0)\ndf_ind[\"eng2\"] = np.where(df_ind.eng>=2,1,0)\ndf_ind[\"eng3\"] = np.where(df_ind.eng>=3,1,0)\ndf_ind[\"tr9\"] = df_ind[\"pwlinear\"]*df_ind[\"nengdom\"]\ndf_mat[\"tr9\"] = df_mat[\"pwlinear\"]*df_mat[\"nengdom\"]\ndf_mat[\"nchild_spouse\"] = df_mat[\"nchild\"]\ndf_mat[\"haskid_spouse\"] = df_mat[\"haskid\"]\n\n\n```\n\n\n```python\nresult_t2_ind = pd.DataFrame({\"Dependent variable St\": list_table2_ind})\nfor dep in list_table2_ind:\n    get_table2_result(df_ind, dep, result_t2_ind)\nresult_t2_mat = pd.DataFrame({\"Dependent variable St\": list_table2_mat})\nfor dep in list_table2_mat:\n    temp = get_table2_result(df_mat, dep, result_t2_mat)\nresult_table2 = result_t2_ind.append(result_t2_mat)\n\n\nresult_table2 =get_variable_full_name_table2(result_table2)\nresult_table2 = result_table2.sort_index(ascending=True)\n\n\nget_asterisk(result_table2,\"P Value\", \"Coef\")\nresult_table2[\"Coefficient for identifying instrument variable\"] = (result_table2[\"Parameter\"].astype(str) + result_table2[\"Coef Sig. level\"])\n\n```\n\n    eng1\n    eng2\n    eng3\n    eng\n    marriedpresent\n    divorced\n    evermarried\n    nchild\n    haskid\n    singleparent\n    nevermarried_haskid\n    share_bpld_minusself\n    abovemean_bpld2\n    ancestpct_minusself\n    abovemean_ancestry2\n    spouseeng\n    marriednative\n    couplesamebpld\n    couplesameancestry1\n    spouseage\n    spouseyrssch\n    spouselnwage\n    spouseworkedly\n    bothworked\n    nchild_spouse\n    haskid_spouse\n\n\n\n```python\nresult_table2= result_table2[[\"Coefficient for identifying instrument variable\",\"SE\"]]\nprint(\"Table 2\u2014Reduced-Form Effects\")\nprint(\"This table refers to Table 2 in the benchmark\")\n\ndisplay(result_table2)\n\n\n```\n\n    Table 2\u2014Reduced-Form Effects\n    This table refers to Table 2 in the benchmark\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>Coefficient for identifying instrument variable</th>\n      <th>SE</th>\n    </tr>\n    <tr>\n      <th>Panel</th>\n      <th>Dependent variable</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"4\" valign=\"top\">Panel A. English proficiency measures</th>\n      <th>1. Speaks English not well or better</th>\n      <td>-0.006**</td>\n      <td>0.003</td>\n    </tr>\n    <tr>\n      <th>2. Speaks English well or better</th>\n      <td>-0.029**</td>\n      <td>0.012</td>\n    </tr>\n    <tr>\n      <th>3. Speaks English very well</th>\n      <td>-0.069***</td>\n      <td>0.013</td>\n    </tr>\n    <tr>\n      <th>4. English-speaking ability ordinal measure</th>\n      <td>-0.104***</td>\n      <td>0.029</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Panel B. Marital status</th>\n      <th>1. Is currently married with spouse present</th>\n      <td>0.011***</td>\n      <td>0.004</td>\n    </tr>\n    <tr>\n      <th>2. Is currently divorced</th>\n      <td>-0.005***</td>\n      <td>0.002</td>\n    </tr>\n    <tr>\n      <th>3. Has ever married</th>\n      <td>0.007***</td>\n      <td>0.003</td>\n    </tr>\n    <tr>\n      <th rowspan=\"4\" valign=\"top\">Panel C. Spouse\u2019s nativity and ethnicity</th>\n      <th>1. Spouse English-speaking ability ordinal measure</th>\n      <td>-0.086***</td>\n      <td>0.019</td>\n    </tr>\n    <tr>\n      <th>2. Spouse is US-born</th>\n      <td>-0.034***</td>\n      <td>0.011</td>\n    </tr>\n    <tr>\n      <th>3. Spouse has the same country of birth</th>\n      <td>0.037***</td>\n      <td>0.012</td>\n    </tr>\n    <tr>\n      <th>4. Spouse has the same ancestry</th>\n      <td>0.019*</td>\n      <td>0.011</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">Panel D. Spouse\u2019s age and education</th>\n      <th>1. Spouse age</th>\n      <td>0.096***</td>\n      <td>0.035</td>\n    </tr>\n    <tr>\n      <th>2. Spouse years of schooling</th>\n      <td>-0.249***</td>\n      <td>0.072</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Panel E. Spouse\u2019s labor market outcomes</th>\n      <th>1. Spouse log(wages last year)</th>\n      <td>-0.031***</td>\n      <td>0.012</td>\n    </tr>\n    <tr>\n      <th>2. Spouse worked last year</th>\n      <td>-0.008***</td>\n      <td>0.003</td>\n    </tr>\n    <tr>\n      <th>3. Both worked last year</th>\n      <td>-0.013**</td>\n      <td>0.005</td>\n    </tr>\n    <tr>\n      <th rowspan=\"6\" valign=\"top\">Panel F. Fertility</th>\n      <th>1. Number of children living in same household</th>\n      <td>0.046***</td>\n      <td>0.014</td>\n    </tr>\n    <tr>\n      <th>2. Has a child living in same household</th>\n      <td>0.008*</td>\n      <td>0.004</td>\n    </tr>\n    <tr>\n      <th>3. Number of children living in same household, only individuals married spouse present</th>\n      <td>0.043***</td>\n      <td>0.014</td>\n    </tr>\n    <tr>\n      <th>4. Has a child living in same household, only individuals married with spouse present</th>\n      <td>0.001</td>\n      <td>0.002</td>\n    </tr>\n    <tr>\n      <th>5. Is a single parent</th>\n      <td>-0.002</td>\n      <td>0.003</td>\n    </tr>\n    <tr>\n      <th>6. Is a never married, single parent</th>\n      <td>0.0</td>\n      <td>0.002</td>\n    </tr>\n    <tr>\n      <th rowspan=\"4\" valign=\"top\">Panel G. Residential location</th>\n      <th>1. Fraction of PUMA population from same country of birth</th>\n      <td>0.001</td>\n      <td>0.001</td>\n    </tr>\n    <tr>\n      <th>2. Fraction from same country of birth is above national mean for the country of birth</th>\n      <td>0.002</td>\n      <td>0.007</td>\n    </tr>\n    <tr>\n      <th>3. Fraction of PUMA population with same primary ancestry</th>\n      <td>0.002</td>\n      <td>0.001</td>\n    </tr>\n    <tr>\n      <th>4. Fraction with same ancestry is above national mean for the primary ancestry</th>\n      <td>0.002</td>\n      <td>0.006</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\nThe key results of the benchmark is replicated in table 3a, 3b and 3C, where we first look at the OLS and 2SLS results using equation (4) on the whole sample, male and female. English level, adjusted by the instrumental variable, affects most of the marital outcome. For example, the English skill level decreases the probability of being currently married. However, the effects on marital outcomes (that authors are interested in) do not tell a clear picture of the assimilation status of immigrants, which we explained earlier in the conceptual issues section. \n\n\n\n```python\n#plot table 3 \ndf_ind_t3 = get_1st_stage_result(df_ind)\ndf_mat_t3 = get_1st_stage_result(df_mat)\n\nresult_table3_ind = pd.DataFrame({\"Dependent variable St\": list_table3_ind})\nfor var in list_table3_ind:\n    get_ols_tsls_result(df_ind_t3, var, result_table3_ind)\n\n\nresult_table3_mat = pd.DataFrame({\"Dependent variable St\": list_table3_mat})\nfor var in list_table3_mat:\n    get_ols_tsls_result(df_mat_t3, var, result_table3_mat)\n\n\nresult_table3 = result_table3_ind.append(result_table3_mat)\nresult_table3 = get_variable_full_name_table3(result_table3)\nresult_table3 = result_table3.sort_index(ascending=True)\n\nget_asteris_and_coef(result_table3,\"OLS P Value\", \"OLS\", \"English effect(OLS)\") \nget_asteris_and_coef(result_table3,\"2SLS P Value\", \"2SLS\", \"English effect(2SLS)\") \n    \n\n```\n\n    marriedpresent\n    divorced\n    evermarried\n    nchild\n    haskid\n    singleparent\n    nevermarried_haskid\n    share_bpld_minusself\n    abovemean_bpld2\n    ancestpct_minusself\n    abovemean_ancestry2\n    spouseeng\n    marriednative\n    couplesamebpld\n    couplesameancestry1\n    spouseage\n    spouseyrssch\n    spouselnwage\n    spouseworkedly\n    bothworked\n    nchild_spouse\n    haskid_spouse\n\n\n\n```python\nprint(\"Table 3a \u2014Effect of English-Language Skills on Marriage Outcomes\")\nprint(\"This table refers to the column (1) and (2) in Table (3),(4),(5) in the benchmark\")\n\nresult_table3[[\"English effect(OLS)\", \"OLS SE\" , \"English effect(2SLS)\", \"2SLS SE\", \"2SLS Adj R sq\"]]\n```\n\n    Table 3a \u2014Effect of English-Language Skills on Marriage Outcomes\n    This table refers to the column (1) and (2) in Table (3),(4),(5) in the benchmark\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>English effect(OLS)</th>\n      <th>OLS SE</th>\n      <th>English effect(2SLS)</th>\n      <th>2SLS SE</th>\n      <th>2SLS Adj R sq</th>\n    </tr>\n    <tr>\n      <th>Panel</th>\n      <th>Dependent variable</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Panel A. Marital status</th>\n      <th>1. Is currently married with spouse present</th>\n      <td>0.008</td>\n      <td>0.009</td>\n      <td>-0.108***</td>\n      <td>0.039</td>\n      <td>0.072147</td>\n    </tr>\n    <tr>\n      <th>2. Is currently divorced</th>\n      <td>0.01***</td>\n      <td>0.003</td>\n      <td>0.052***</td>\n      <td>0.017</td>\n      <td>0.036220</td>\n    </tr>\n    <tr>\n      <th>3. Has ever married</th>\n      <td>-0.002</td>\n      <td>0.007</td>\n      <td>-0.071***</td>\n      <td>0.024</td>\n      <td>0.153013</td>\n    </tr>\n    <tr>\n      <th rowspan=\"4\" valign=\"top\">Panel B. Spouse\u2019s nativity and ethnicity</th>\n      <th>1. Spouse English-speaking ability ordinal measure</th>\n      <td>0.512***</td>\n      <td>0.016</td>\n      <td>0.809***</td>\n      <td>0.180</td>\n      <td>0.244451</td>\n    </tr>\n    <tr>\n      <th>2. Spouse is US-born</th>\n      <td>0.105***</td>\n      <td>0.009</td>\n      <td>0.322***</td>\n      <td>0.107</td>\n      <td>0.319407</td>\n    </tr>\n    <tr>\n      <th>3. Spouse has the same country of birth</th>\n      <td>-0.12***</td>\n      <td>0.007</td>\n      <td>-0.351***</td>\n      <td>0.115</td>\n      <td>0.326626</td>\n    </tr>\n    <tr>\n      <th>4. Spouse has the same ancestry</th>\n      <td>-0.076***</td>\n      <td>0.011</td>\n      <td>-0.18*</td>\n      <td>0.099</td>\n      <td>0.224261</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">Panel C. Spouse\u2019s age and education</th>\n      <th>1. Spouse age</th>\n      <td>-0.348***</td>\n      <td>0.035</td>\n      <td>-0.901***</td>\n      <td>0.334</td>\n      <td>0.727417</td>\n    </tr>\n    <tr>\n      <th>2. Spouse years of schooling</th>\n      <td>1.353***</td>\n      <td>0.034</td>\n      <td>2.35***</td>\n      <td>0.679</td>\n      <td>0.265225</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Panel D. Spouse\u2019s labor market outcomes</th>\n      <th>1. Spouse log(wages last year)</th>\n      <td>0.169***</td>\n      <td>0.006</td>\n      <td>0.296***</td>\n      <td>0.111</td>\n      <td>0.193737</td>\n    </tr>\n    <tr>\n      <th>2. Spouse worked last year</th>\n      <td>0.039***</td>\n      <td>0.003</td>\n      <td>0.078***</td>\n      <td>0.029</td>\n      <td>0.112868</td>\n    </tr>\n    <tr>\n      <th>3. Both worked last year</th>\n      <td>0.09***</td>\n      <td>0.004</td>\n      <td>0.12**</td>\n      <td>0.048</td>\n      <td>0.033702</td>\n    </tr>\n    <tr>\n      <th rowspan=\"6\" valign=\"top\">Panel E. Fertility</th>\n      <th>1. Number of children living in same household</th>\n      <td>-0.106***</td>\n      <td>0.021</td>\n      <td>-0.441***</td>\n      <td>0.136</td>\n      <td>0.150791</td>\n    </tr>\n    <tr>\n      <th>2. Has a child living in same household</th>\n      <td>-0.005</td>\n      <td>0.004</td>\n      <td>-0.073**</td>\n      <td>0.037</td>\n      <td>0.120078</td>\n    </tr>\n    <tr>\n      <th>3. Number of children living in same household, only individuals married spouse present</th>\n      <td>-0.177***</td>\n      <td>0.013</td>\n      <td>-0.41***</td>\n      <td>0.131</td>\n      <td>0.165262</td>\n    </tr>\n    <tr>\n      <th>4. Has a child living in same household, only individuals married with spouse present</th>\n      <td>-0.019***</td>\n      <td>0.004</td>\n      <td>-0.007</td>\n      <td>0.020</td>\n      <td>0.101348</td>\n    </tr>\n    <tr>\n      <th>5. Is a single parent</th>\n      <td>-0.001</td>\n      <td>0.004</td>\n      <td>0.021</td>\n      <td>0.026</td>\n      <td>0.061569</td>\n    </tr>\n    <tr>\n      <th>6. Is a never married, single parent</th>\n      <td>-0.003</td>\n      <td>0.002</td>\n      <td>-0.002</td>\n      <td>0.017</td>\n      <td>0.034528</td>\n    </tr>\n    <tr>\n      <th rowspan=\"4\" valign=\"top\">Panel F. Residential location</th>\n      <th>1. Fraction of PUMA population from same country of birth</th>\n      <td>-0.01***</td>\n      <td>0.001</td>\n      <td>-0.007</td>\n      <td>0.007</td>\n      <td>0.448813</td>\n    </tr>\n    <tr>\n      <th>2. Fraction from same country of birth is above national mean for the country of birth</th>\n      <td>-0.05***</td>\n      <td>0.007</td>\n      <td>-0.015</td>\n      <td>0.065</td>\n      <td>0.030742</td>\n    </tr>\n    <tr>\n      <th>3. Fraction of PUMA population with same primary ancestry</th>\n      <td>-0.013***</td>\n      <td>0.002</td>\n      <td>-0.018</td>\n      <td>0.013</td>\n      <td>0.357922</td>\n    </tr>\n    <tr>\n      <th>4. Fraction with same ancestry is above national mean for the primary ancestry</th>\n      <td>-0.041***</td>\n      <td>0.007</td>\n      <td>-0.022</td>\n      <td>0.057</td>\n      <td>0.024823</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# plot table 3 female sample \ndf_ind_t3_female = df_ind[df_ind[\"female\"] == 1]\ndf_mat_t3_female = df_mat[df_mat[\"female\"] == 1]\n\ndf_ind_t3_female = get_1st_stage_result(df_ind_t3_female)\ndf_mat_t3_female = get_1st_stage_result(df_mat_t3_female)\n\n\nresult_table3_female_ind = pd.DataFrame({\"Dependent variable St\": list_table3_ind})\nfor var in list_table3_ind:\n    (temp_ols, temp_2SLS) = get_ols_tsls_result(df_ind_t3_female, var, result_table3_female_ind)\n\n\nresult_table3_female_mat = pd.DataFrame({\"Dependent variable St\": list_table3_mat})\nfor var in list_table3_mat:\n    (temp_ols, temp_2SLS) = get_ols_tsls_result(df_mat_t3_female, var, result_table3_female_mat)\n\n\nresult_table3_female = result_table3_female_ind.append(result_table3_female_mat)\n\nresult_table3_female = get_variable_full_name_table3(result_table3_female)\nresult_table3_female = result_table3_female.sort_index(ascending=True, sort_remaining =False)\n\n\nget_asteris_and_coef(result_table3_female,\"OLS P Value\", \"OLS\", \"English effect(OLS)\") \nget_asteris_and_coef(result_table3_female,\"2SLS P Value\", \"2SLS\", \"English effect(2SLS)\") \n    \n\n```\n\n    /Users/chingfungchow/Documents/GitHub/Microeconometrics-Paper/auxiliary.py:22: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      data['eng_hat'] = fit_st1.predict(data)\n    /Users/chingfungchow/opt/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py:6746: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame\n    \n    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      self._update_inplace(new_data)\n\n\n    marriedpresent\n    divorced\n    evermarried\n    nchild\n    haskid\n    singleparent\n    nevermarried_haskid\n    share_bpld_minusself\n    abovemean_bpld2\n    ancestpct_minusself\n    abovemean_ancestry2\n    spouseeng\n    marriednative\n    couplesamebpld\n    couplesameancestry1\n    spouseage\n    spouseyrssch\n    spouselnwage\n    spouseworkedly\n    bothworked\n    nchild_spouse\n    haskid_spouse\n\n\n\n```python\nprint(\"Table 3b \u2014Effect of English-Language Skills on Marriage Outcomes, female sample\")\nprint(\"This table refers to the column (3) and (4) in Table (3),(4),(5) in the benchmark\")\nresult_table3_female[[\"English effect(OLS)\", \"OLS SE\" , \"English effect(2SLS)\", \"2SLS SE\", \"2SLS Adj R sq\"]]\n```\n\n    Table 3b \u2014Effect of English-Language Skills on Marriage Outcomes, female sample\n    This table refers to the column (3) and (4) in Table (3),(4),(5) in the benchmark\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>English effect(OLS)</th>\n      <th>OLS SE</th>\n      <th>English effect(2SLS)</th>\n      <th>2SLS SE</th>\n      <th>2SLS Adj R sq</th>\n    </tr>\n    <tr>\n      <th>Panel</th>\n      <th>Dependent variable</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Panel A. Marital status</th>\n      <th>1. Is currently married with spouse present</th>\n      <td>-0.004</td>\n      <td>0.009</td>\n      <td>-0.076**</td>\n      <td>0.033</td>\n      <td>0.062049</td>\n    </tr>\n    <tr>\n      <th>2. Is currently divorced</th>\n      <td>0.015***</td>\n      <td>0.003</td>\n      <td>0.064**</td>\n      <td>0.027</td>\n      <td>0.035673</td>\n    </tr>\n    <tr>\n      <th>3. Has ever married</th>\n      <td>-0.001</td>\n      <td>0.005</td>\n      <td>-0.015</td>\n      <td>0.027</td>\n      <td>0.136230</td>\n    </tr>\n    <tr>\n      <th rowspan=\"4\" valign=\"top\">Panel B. Spouse\u2019s nativity and ethnicity</th>\n      <th>1. Spouse English-speaking ability ordinal measure</th>\n      <td>0.474***</td>\n      <td>0.008</td>\n      <td>0.615***</td>\n      <td>0.109</td>\n      <td>0.232672</td>\n    </tr>\n    <tr>\n      <th>2. Spouse is US-born</th>\n      <td>0.101***</td>\n      <td>0.011</td>\n      <td>0.27**</td>\n      <td>0.118</td>\n      <td>0.340200</td>\n    </tr>\n    <tr>\n      <th>3. Spouse has the same country of birth</th>\n      <td>-0.118***</td>\n      <td>0.009</td>\n      <td>-0.285**</td>\n      <td>0.127</td>\n      <td>0.338575</td>\n    </tr>\n    <tr>\n      <th>4. Spouse has the same ancestry</th>\n      <td>-0.078***</td>\n      <td>0.013</td>\n      <td>-0.17</td>\n      <td>0.112</td>\n      <td>0.226091</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">Panel C. Spouse\u2019s age and education</th>\n      <th>1. Spouse age</th>\n      <td>-0.496***</td>\n      <td>0.055</td>\n      <td>-1.312***</td>\n      <td>0.461</td>\n      <td>0.707548</td>\n    </tr>\n    <tr>\n      <th>2. Spouse years of schooling</th>\n      <td>1.367***</td>\n      <td>0.036</td>\n      <td>2.188***</td>\n      <td>0.592</td>\n      <td>0.264124</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Panel D. Spouse\u2019s labor market outcomes</th>\n      <th>1. Spouse log(wages last year)</th>\n      <td>0.166***</td>\n      <td>0.006</td>\n      <td>0.233**</td>\n      <td>0.114</td>\n      <td>0.118192</td>\n    </tr>\n    <tr>\n      <th>2. Spouse worked last year</th>\n      <td>0.021***</td>\n      <td>0.005</td>\n      <td>0.022</td>\n      <td>0.019</td>\n      <td>0.027787</td>\n    </tr>\n    <tr>\n      <th>3. Both worked last year</th>\n      <td>0.106***</td>\n      <td>0.006</td>\n      <td>0.12***</td>\n      <td>0.042</td>\n      <td>0.027167</td>\n    </tr>\n    <tr>\n      <th rowspan=\"6\" valign=\"top\">Panel E. Fertility</th>\n      <th>1. Number of children living in same household</th>\n      <td>-0.162***</td>\n      <td>0.019</td>\n      <td>-0.472***</td>\n      <td>0.128</td>\n      <td>0.165340</td>\n    </tr>\n    <tr>\n      <th>2. Has a child living in same household</th>\n      <td>-0.019***</td>\n      <td>0.003</td>\n      <td>-0.041</td>\n      <td>0.034</td>\n      <td>0.116814</td>\n    </tr>\n    <tr>\n      <th>3. Number of children living in same household, only individuals married spouse present</th>\n      <td>-0.203***</td>\n      <td>0.017</td>\n      <td>-0.591***</td>\n      <td>0.140</td>\n      <td>0.193076</td>\n    </tr>\n    <tr>\n      <th>4. Has a child living in same household, only individuals married with spouse present</th>\n      <td>-0.024***</td>\n      <td>0.004</td>\n      <td>-0.02</td>\n      <td>0.021</td>\n      <td>0.123443</td>\n    </tr>\n    <tr>\n      <th>5. Is a single parent</th>\n      <td>-0.001</td>\n      <td>0.007</td>\n      <td>0.032</td>\n      <td>0.033</td>\n      <td>0.048728</td>\n    </tr>\n    <tr>\n      <th>6. Is a never married, single parent</th>\n      <td>-0.005</td>\n      <td>0.004</td>\n      <td>-0.005</td>\n      <td>0.026</td>\n      <td>0.046236</td>\n    </tr>\n    <tr>\n      <th rowspan=\"4\" valign=\"top\">Panel F. Residential location</th>\n      <th>1. Fraction of PUMA population from same country of birth</th>\n      <td>-0.012***</td>\n      <td>0.002</td>\n      <td>-0.014***</td>\n      <td>0.004</td>\n      <td>0.464532</td>\n    </tr>\n    <tr>\n      <th>2. Fraction from same country of birth is above national mean for the country of birth</th>\n      <td>-0.058***</td>\n      <td>0.006</td>\n      <td>-0.038</td>\n      <td>0.046</td>\n      <td>0.036516</td>\n    </tr>\n    <tr>\n      <th>3. Fraction of PUMA population with same primary ancestry</th>\n      <td>-0.017***</td>\n      <td>0.002</td>\n      <td>-0.033***</td>\n      <td>0.006</td>\n      <td>0.369076</td>\n    </tr>\n    <tr>\n      <th>4. Fraction with same ancestry is above national mean for the primary ancestry</th>\n      <td>-0.05***</td>\n      <td>0.007</td>\n      <td>-0.088**</td>\n      <td>0.041</td>\n      <td>0.030300</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# plot table 3 male sample \ndf_ind_t3_male = df_ind[df_ind[\"female\"] == 0]\ndf_mat_t3_male = df_mat[df_mat[\"female\"] == 0]\n\ndf_ind_t3_male = get_1st_stage_result(df_ind_t3_male)\ndf_mat_t3_male = get_1st_stage_result(df_mat_t3_male)\n\n\nresult_table3_male_ind = pd.DataFrame({\"Dependent variable St\": list_table3_ind})\nfor var in list_table3_ind:\n    (temp_ols, temp_2SLS) = get_ols_tsls_result(df_ind_t3_male, var, result_table3_male_ind)\n\n\nresult_table3_male_mat = pd.DataFrame({\"Dependent variable St\": list_table3_mat})\nfor var in list_table3_mat:\n    (temp_ols, temp_2SLS) = get_ols_tsls_result(df_mat_t3_male, var, result_table3_male_mat)\n\n\nresult_table3_male = result_table3_male_ind.append(result_table3_male_mat)\n\nresult_table3_male = get_variable_full_name_table3(result_table3_male)\nresult_table3_male = result_table3_male.sort_index(ascending=True, sort_remaining =False)\n\n\nget_asteris_and_coef(result_table3_male,\"OLS P Value\", \"OLS\", \"English effect(OLS)\") \nget_asteris_and_coef(result_table3_male,\"2SLS P Value\", \"2SLS\", \"English effect(2SLS)\") \n    \n\n```\n\n    /Users/chingfungchow/Documents/GitHub/Microeconometrics-Paper/auxiliary.py:22: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      data['eng_hat'] = fit_st1.predict(data)\n    /Users/chingfungchow/opt/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py:6746: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame\n    \n    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      self._update_inplace(new_data)\n\n\n    marriedpresent\n    divorced\n    evermarried\n    nchild\n    haskid\n    singleparent\n    nevermarried_haskid\n    share_bpld_minusself\n    abovemean_bpld2\n    ancestpct_minusself\n    abovemean_ancestry2\n    spouseeng\n    marriednative\n    couplesamebpld\n    couplesameancestry1\n    spouseage\n    spouseyrssch\n    spouselnwage\n    spouseworkedly\n    bothworked\n    nchild_spouse\n    haskid_spouse\n\n\n\n```python\nprint(\"Table 3c \u2014Effect of English-Language Skills on Marriage Outcomes, male sample\")\nprint(\"This table refers to the column (5) and (6) in Table (3),(4),(5) in the benchmark\")\nresult_table3_male[[\"English effect(OLS)\", \"OLS SE\" , \"English effect(2SLS)\", \"2SLS SE\", \"2SLS Adj R sq\"]]\n```\n\n    Table 3c \u2014Effect of English-Language Skills on Marriage Outcomes, male sample\n    This table refers to the column (5) and (6) in Table (3),(4),(5) in the benchmark\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>English effect(OLS)</th>\n      <th>OLS SE</th>\n      <th>English effect(2SLS)</th>\n      <th>2SLS SE</th>\n      <th>2SLS Adj R sq</th>\n    </tr>\n    <tr>\n      <th>Panel</th>\n      <th>Dependent variable</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Panel A. Marital status</th>\n      <th>1. Is currently married with spouse present</th>\n      <td>0.019*</td>\n      <td>0.011</td>\n      <td>-0.14***</td>\n      <td>0.048</td>\n      <td>0.092846</td>\n    </tr>\n    <tr>\n      <th>2. Is currently divorced</th>\n      <td>0.006*</td>\n      <td>0.004</td>\n      <td>0.038</td>\n      <td>0.023</td>\n      <td>0.031216</td>\n    </tr>\n    <tr>\n      <th>3. Has ever married</th>\n      <td>-0.004</td>\n      <td>0.009</td>\n      <td>-0.133***</td>\n      <td>0.046</td>\n      <td>0.164015</td>\n    </tr>\n    <tr>\n      <th rowspan=\"4\" valign=\"top\">Panel B. Spouse\u2019s nativity and ethnicity</th>\n      <th>1. Spouse English-speaking ability ordinal measure</th>\n      <td>0.56***</td>\n      <td>0.027</td>\n      <td>1.028***</td>\n      <td>0.271</td>\n      <td>0.259198</td>\n    </tr>\n    <tr>\n      <th>2. Spouse is US-born</th>\n      <td>0.109***</td>\n      <td>0.006</td>\n      <td>0.386***</td>\n      <td>0.110</td>\n      <td>0.310249</td>\n    </tr>\n    <tr>\n      <th>3. Spouse has the same country of birth</th>\n      <td>-0.122***</td>\n      <td>0.006</td>\n      <td>-0.434***</td>\n      <td>0.104</td>\n      <td>0.326044</td>\n    </tr>\n    <tr>\n      <th>4. Spouse has the same ancestry</th>\n      <td>-0.074***</td>\n      <td>0.009</td>\n      <td>-0.197**</td>\n      <td>0.089</td>\n      <td>0.229249</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">Panel C. Spouse\u2019s age and education</th>\n      <th>1. Spouse age</th>\n      <td>-0.147***</td>\n      <td>0.033</td>\n      <td>-0.382</td>\n      <td>0.648</td>\n      <td>0.727247</td>\n    </tr>\n    <tr>\n      <th>2. Spouse years of schooling</th>\n      <td>1.343***</td>\n      <td>0.043</td>\n      <td>2.582***</td>\n      <td>0.848</td>\n      <td>0.272656</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Panel D. Spouse\u2019s labor market outcomes</th>\n      <th>1. Spouse log(wages last year)</th>\n      <td>0.172***</td>\n      <td>0.012</td>\n      <td>0.395**</td>\n      <td>0.184</td>\n      <td>0.055268</td>\n    </tr>\n    <tr>\n      <th>2. Spouse worked last year</th>\n      <td>0.062***</td>\n      <td>0.004</td>\n      <td>0.141**</td>\n      <td>0.064</td>\n      <td>0.042286</td>\n    </tr>\n    <tr>\n      <th>3. Both worked last year</th>\n      <td>0.072***</td>\n      <td>0.004</td>\n      <td>0.115*</td>\n      <td>0.067</td>\n      <td>0.041955</td>\n    </tr>\n    <tr>\n      <th rowspan=\"6\" valign=\"top\">Panel E. Fertility</th>\n      <th>1. Number of children living in same household</th>\n      <td>-0.049*</td>\n      <td>0.026</td>\n      <td>-0.403**</td>\n      <td>0.165</td>\n      <td>0.133685</td>\n    </tr>\n    <tr>\n      <th>2. Has a child living in same household</th>\n      <td>0.009</td>\n      <td>0.007</td>\n      <td>-0.113**</td>\n      <td>0.049</td>\n      <td>0.107167</td>\n    </tr>\n    <tr>\n      <th>3. Number of children living in same household, only individuals married spouse present</th>\n      <td>-0.148***</td>\n      <td>0.013</td>\n      <td>-0.19</td>\n      <td>0.183</td>\n      <td>0.149393</td>\n    </tr>\n    <tr>\n      <th>4. Has a child living in same household, only individuals married with spouse present</th>\n      <td>-0.014***</td>\n      <td>0.004</td>\n      <td>0.008</td>\n      <td>0.035</td>\n      <td>0.087784</td>\n    </tr>\n    <tr>\n      <th>5. Is a single parent</th>\n      <td>-0.001</td>\n      <td>0.001</td>\n      <td>0.0</td>\n      <td>0.015</td>\n      <td>0.007007</td>\n    </tr>\n    <tr>\n      <th>6. Is a never married, single parent</th>\n      <td>-0.002**</td>\n      <td>0.001</td>\n      <td>-0.008</td>\n      <td>0.008</td>\n      <td>0.011830</td>\n    </tr>\n    <tr>\n      <th rowspan=\"4\" valign=\"top\">Panel F. Residential location</th>\n      <th>1. Fraction of PUMA population from same country of birth</th>\n      <td>-0.008***</td>\n      <td>0.001</td>\n      <td>-0.0</td>\n      <td>0.011</td>\n      <td>0.433569</td>\n    </tr>\n    <tr>\n      <th>2. Fraction from same country of birth is above national mean for the country of birth</th>\n      <td>-0.041***</td>\n      <td>0.009</td>\n      <td>0.007</td>\n      <td>0.091</td>\n      <td>0.026577</td>\n    </tr>\n    <tr>\n      <th>3. Fraction of PUMA population with same primary ancestry</th>\n      <td>-0.009***</td>\n      <td>0.001</td>\n      <td>-0.002</td>\n      <td>0.021</td>\n      <td>0.347328</td>\n    </tr>\n    <tr>\n      <th>4. Fraction with same ancestry is above national mean for the primary ancestry</th>\n      <td>-0.033***</td>\n      <td>0.008</td>\n      <td>0.056</td>\n      <td>0.084</td>\n      <td>0.020615</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThe coefficients for \u201cSpouse English-speaking ability\u201d, \u201cSpouse is US-born\u201d and \u201cSpouse has the same country of birth\u201d are more direct indicators to an immigrant\u2019s status: His or her English level moves in the same direction with the spouse English ability and the probability of the spouse being US-born, and it moves in the opposite direction with the probability of marrying someone from the same country of birth. These results imply that English level helps an immigrant to depart from the social circle of his or her countrypeople and be able to build relationships, in one most intimate form, with the US locals. Similarly, English also improves the spouse labor outcome, such as wage and employment status. It is worth noticing that for female immigrants, higher English level statistically significantly decreases the age of their spouses, while we do not observe a significant effect for male respondents.\n\nEnglish level does not bring significant effects to fertility outcomes, except for the decrease in the number of children. It might be caused by the fact that the mean age in the treatment group (36.54) is slightly less than that in the control group (38.403). In addition, English skills bear no demonstrative improvement in ethnic enclaving or resident location outcomes. The technicality issue is that due to data privacy, the lowest level of geographic aggregation measure \u201cpublic-use microdata area\u201d (PUMA), which is an area containing at least 100,000 people. As a result, our definition for a neighborhood becomes too big, leading to the unsatisfactory theoretical ground for our estimation.\n\nHowever, in the authors\u2019 analysis, the adjusted R-square of each estimation is not presented. As soon as we pay attention to the goodness-of-fit, we discover that equation (4) does a poor job in giving precise predictions. 2SLS estimations on an outcome such as \u201cis currently married with spouse present\u201d, \u201cis currently divorced\u201d, \u201chas a child living in the same household\u201d, \u201cis a single parent\u201d and \u201cspouse worked last year\u201d have an adjusted R-squared less than 0.04, which as a sign that there is just too much residual. The poor goodness-of-fit of the outcome with currently married (or divorced) might be consistent with our previous analysis. The effect of English on an immigrant\u2019s decision on marriage is ambiguous, as there are reasonable theories to predict the opposite results. \n\n### 5.2 Robustness checks in the benchmark  \n\n\nIt is possible that in table 3a,3b and 3c there are uncontrol features for the treatment group (childhood immigrants from non-English-speaking countries) that will be included in the 2SLS estimator. The authors consider alternative hypotheses for robustness check, in order to eliminate the non-language effect in the estimations. The robustness checks done by the authors are summarized in table 4a. The results in alternative specifications, as shown in table 4b, are similar to the baseline 2SLS analysis.  \n\nTable 4a \u2014 Summary of robustness check in the benchmark: Feature, movitivation and solution\n\n\n\n\n```python\n####################get baseline result (from table 3 )\n\nresult_table4_baseline = result_table3[[\"English effect(2SLS)\", \"2SLS SE\"]]\n# result_table4_baseline = result_table4_baseline.rename(columns={\"English effect(2SLS)\":\"Base results (1)\",\"2SLS SE\":\"2SLS SE\"},inplace = True)\n\n####################get result with control in origin's GDP\ndf_ind_GDP = df_ind\ndf_mat_GDP = df_mat\n\n\ndf_ind_GDP['lngdp'].replace('  ', np.nan, inplace=True)\ndf_ind_GDP= df_ind_GDP.dropna(subset=['lngdp'])\ndf_mat_GDP['lngdp'].replace('  ', np.nan, inplace=True)\ndf_mat_GDP= df_mat_GDP.dropna(subset=['lngdp'])\n\ndf_ind_GDP[\"pwxgdp\"]=(df_ind_GDP[\"pwlinear\"]*df_ind_GDP[\"lngdp\"])/100\ndf_mat_GDP[\"pwxgdp\"]=(df_mat_GDP[\"pwlinear\"]*df_mat_GDP[\"lngdp\"])/100\n\ndf_ind_GDP = get_first_stage_result_table4(df_ind_GDP ,\"pwxgdp\" )\ndf_mat_GDP = get_first_stage_result_table4(df_mat_GDP, \"pwxgdp\")\n\n\nresult_ind = pd.DataFrame({\"Dependent variable St\": list_table3_ind})\nfor var in list_table3_ind:\n    (temp_2SLS) = get_tsls_result_table4(df_ind_GDP, var, result_ind,\"pwxgdp\")\n\nresult_mat = pd.DataFrame({\"Dependent variable St\": list_table3_mat})\nfor var in list_table3_mat:\n    (temp_2SLS) = get_tsls_result_table4(df_mat_GDP, var, result_mat,\"pwxgdp\")\n\nresult_table4_control_GDP = result_ind.append(result_mat)\n\n\nresult_table4_control_GDP = get_variable_full_name_table3(result_table4_control_GDP)\nget_asteris_and_coef(result_table4_control_GDP,\"2SLS P Value\", \"2SLS\", \"Control for origin GDP \u00d7 age at arrival (2)\") \nresult_table4_control_GDP = result_table4_control_GDP[[\"Control for origin GDP \u00d7 age at arrival (2)\", \"2SLS SE\"]]\n\n\n####################get result with control in origin's fertility\ndf_ind_tfr = df_ind\ndf_mat_tfr = df_mat\n\ndf_ind_tfr['tfr82'].replace('  ', np.nan, inplace=True)\ndf_ind_tfr= df_ind_tfr.dropna(subset=['tfr82'])\n\ndf_mat_tfr['tfr82'].replace('  ', np.nan, inplace=True)\ndf_mat_tfr= df_mat_tfr.dropna(subset=['tfr82'])\n\ndf_ind_tfr[\"pwxtfr\"]=(df_ind_tfr[\"pwlinear\"]*df_ind_tfr[\"tfr82\"])\ndf_mat_tfr[\"pwxtfr\"]=(df_mat_tfr[\"pwlinear\"]*df_mat_tfr[\"tfr82\"])\n\ndf_ind_tfr = get_first_stage_result_table4(df_ind_tfr ,\"pwxtfr\" )\ndf_mat_tfr = get_first_stage_result_table4(df_mat_tfr, \"pwxtfr\")\n\n\nresult_ind = pd.DataFrame({\"Dependent variable St\": list_table3_ind})\nfor var in list_table3_ind:\n    (temp_2SLS) = get_tsls_result_table4(df_ind_tfr, var, result_ind,\"pwxtfr\")\n\nresult_mat = pd.DataFrame({\"Dependent variable St\": list_table3_mat})\nfor var in list_table3_mat:\n    (temp_2SLS) = get_tsls_result_table4(df_mat_tfr, var, result_mat,\"pwxtfr\")\n\nresult_table4_control_fertility = result_ind.append(result_mat)\nresult_table4_control_fertility = get_variable_full_name_table3(result_table4_control_fertility)\nget_asteris_and_coef(result_table4_control_fertility,\"2SLS P Value\", \"2SLS\", \"Control for origin fertility \u00d7 age at arrival (3)\") \nresult_table4_control_fertility = result_table4_control_fertility[[\"Control for origin fertility \u00d7 age at arrival (3)\", \"2SLS SE\"]]\n\n####################get result dropping immigrants from Canada\ndf_ind_no_CA = df_ind\n\ndf_mat_no_CA = df_mat\n\ndf_ind_no_CA = (df_ind_no_CA[df_ind_no_CA.bpld !=15000])\ndf_mat_no_CA = (df_mat_no_CA[df_mat_no_CA.bpld !=15000])\n\ndf_ind_no_CA = get_first_stage_result_table4(df_ind_no_CA  )\ndf_mat_no_CA = get_first_stage_result_table4(df_mat_no_CA)\n\n\nresult_ind = pd.DataFrame({\"Dependent variable St\": list_table3_ind})\nfor var in list_table3_ind:\n    (temp_2SLS) = get_tsls_result_table4(df_ind_no_CA, var, result_ind)\n\nresult_mat = pd.DataFrame({\"Dependent variable St\": list_table3_mat})\nfor var in list_table3_mat:\n    (temp_2SLS) = get_tsls_result_table4(df_mat_no_CA, var, result_mat)\n\nresult_table4_no_CA = result_ind.append(result_mat)\nresult_table4_no_CA = get_variable_full_name_table3(result_table4_no_CA)\nget_asteris_and_coef(result_table4_no_CA,\"2SLS P Value\", \"2SLS\", \"Drop Canada (4)\") \nresult_table4_no_CA = result_table4_no_CA[[\"Drop Canada (4)\", \"2SLS SE\"]]\n\n\n####################get result dropping immigrants from Mexico\ndf_ind_no_Mex = df_ind\n\ndf_mat_no_Mex = df_mat\n\ndf_ind_no_Mex = (df_ind_no_Mex[df_ind_no_Mex.bpld !=20000])\ndf_mat_no_Mex = (df_mat_no_Mex[df_mat_no_Mex.bpld !=20000])\ndf_ind_no_Mex = get_first_stage_result_table4(df_ind_no_Mex)\ndf_mat_no_Mex = get_first_stage_result_table4(df_mat_no_Mex)\n\nresult_ind = pd.DataFrame({\"Dependent variable St\": list_table3_ind})\nfor var in list_table3_ind:\n    (temp_2SLS) = get_tsls_result_table4(df_ind_no_Mex, var, result_ind)\n\nresult_mat = pd.DataFrame({\"Dependent variable St\": list_table3_mat})\nfor var in list_table3_mat:\n    (temp_2SLS) = get_tsls_result_table4(df_mat_no_Mex, var, result_mat)\n\nresult_table4_no_Mex = result_ind.append(result_mat)\n\nresult_table4_no_Mex = get_variable_full_name_table3(result_table4_no_Mex)\nget_asteris_and_coef(result_table4_no_Mex,\"2SLS P Value\", \"2SLS\", \"Drop Mexico (5)\") \nresult_table4_no_Mex = result_table4_no_Mex[[\"Drop Mexico (5)\", \"2SLS SE\"]]\nresult_table4_no_Mex\n\n\n\nresult_table4_baseline=result_table4_baseline.rename(columns={ \"English effect(2SLS)\":\"Base results (1)\", \"2SLS SE\": \"SE(1)\"})\nresult_table4_control_GDP=result_table4_control_GDP.rename(columns={\"2SLS SE\": \"SE(2)\"})\nresult_table4_control_fertility=result_table4_control_fertility.rename(columns={\"2SLS SE\": \"SE(3)\"})\nresult_table4_no_CA=result_table4_no_CA.rename(columns={\"2SLS SE\": \"SE(4)\"})\nresult_table4_no_Mex=result_table4_no_Mex.rename(columns={\"2SLS SE\": \"SE(5)\"})\n\n\nresult_table4 = pd.merge(result_table4_baseline, result_table4_control_GDP,\n                        left_on=[\"Panel\",'Dependent variable'], right_on = [\"Panel\",'Dependent variable'], how = 'left')\nresult_table4 = pd.merge(result_table4, result_table4_control_fertility,\n                       left_on=[\"Panel\",'Dependent variable'], right_on = [\"Panel\",'Dependent variable'], how = 'left')\nresult_table4 = pd.merge(result_table4, result_table4_no_CA,\n                       left_on=[\"Panel\",'Dependent variable'], right_on = [\"Panel\",'Dependent variable'], how = 'left')\nresult_table4 = pd.merge(result_table4, result_table4_no_Mex,\n                       left_on=[\"Panel\",'Dependent variable'], right_on = [\"Panel\",'Dependent variable'], how = 'left')\n\nresult_table4 = result_table4.sort_index(ascending=True, sort_remaining =False)\n\n```\n\n    /Users/chingfungchow/opt/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:16: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      app.launch_new_instance()\n    /Users/chingfungchow/opt/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:17: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n    /Users/chingfungchow/Documents/GitHub/Microeconometrics-Paper/auxiliary.py:164: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      data['eng_hat'] = fit_st1.predict(data)\n    /Users/chingfungchow/opt/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py:6746: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame\n    \n    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      self._update_inplace(new_data)\n\n\n    marriedpresent\n    divorced\n    evermarried\n    nchild\n    haskid\n    singleparent\n    nevermarried_haskid\n    share_bpld_minusself\n    abovemean_bpld2\n    ancestpct_minusself\n    abovemean_ancestry2\n    spouseeng\n    marriednative\n    couplesamebpld\n    couplesameancestry1\n    spouseage\n    spouseyrssch\n    spouselnwage\n    spouseworkedly\n    bothworked\n    nchild_spouse\n    haskid_spouse\n\n\n    /Users/chingfungchow/opt/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:49: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n    /Users/chingfungchow/opt/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:50: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n\n\n    marriedpresent\n    divorced\n    evermarried\n    nchild\n    haskid\n    singleparent\n    nevermarried_haskid\n    share_bpld_minusself\n    abovemean_bpld2\n    ancestpct_minusself\n    abovemean_ancestry2\n    spouseeng\n    marriednative\n    couplesamebpld\n    couplesameancestry1\n    spouseage\n    spouseyrssch\n    spouselnwage\n    spouseworkedly\n    bothworked\n    nchild_spouse\n    haskid_spouse\n\n\n    /Users/chingfungchow/Documents/GitHub/Microeconometrics-Paper/auxiliary.py:161: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      data['eng_hat'] = fit_st1.predict(data)\n\n\n    marriedpresent\n    divorced\n    evermarried\n    nchild\n    haskid\n    singleparent\n    nevermarried_haskid\n    share_bpld_minusself\n    abovemean_bpld2\n    ancestpct_minusself\n    abovemean_ancestry2\n    spouseeng\n    marriednative\n    couplesamebpld\n    couplesameancestry1\n    spouseage\n    spouseyrssch\n    spouselnwage\n    spouseworkedly\n    bothworked\n    nchild_spouse\n    haskid_spouse\n    marriedpresent\n    divorced\n    evermarried\n    nchild\n    haskid\n    singleparent\n    nevermarried_haskid\n    share_bpld_minusself\n    abovemean_bpld2\n    ancestpct_minusself\n    abovemean_ancestry2\n    spouseeng\n    marriednative\n    couplesamebpld\n    couplesameancestry1\n    spouseage\n    spouseyrssch\n    spouselnwage\n    spouseworkedly\n    bothworked\n    nchild_spouse\n    haskid_spouse\n\n\n\n```python\nprint(\"Table 4b \u2014 2SLS Effect of English Using Alternative Samples and Specifications\")\nprint(\"This table refers to Table (6) in the benchmark\")\nwith pd.option_context('display.max_rows', None, 'display.max_columns', None): \n    display(result_table4)\n\n```\n\n    Table 4b \u2014 2SLS Effect of English Using Alternative Samples and Specifications\n    This table refers to Table (6) in the benchmark\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>Base results (1)</th>\n      <th>SE(1)</th>\n      <th>Control for origin GDP \u00d7 age at arrival (2)</th>\n      <th>SE(2)</th>\n      <th>Control for origin fertility \u00d7 age at arrival (3)</th>\n      <th>SE(3)</th>\n      <th>Drop Canada (4)</th>\n      <th>SE(4)</th>\n      <th>Drop Mexico (5)</th>\n      <th>SE(5)</th>\n    </tr>\n    <tr>\n      <th>Panel</th>\n      <th>Dependent variable</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Panel A. Marital status</th>\n      <th>1. Is currently married with spouse present</th>\n      <td>-0.108***</td>\n      <td>0.039</td>\n      <td>-0.082**</td>\n      <td>0.037</td>\n      <td>-0.097**</td>\n      <td>0.043</td>\n      <td>-0.108**</td>\n      <td>0.047</td>\n      <td>-0.159**</td>\n      <td>0.069</td>\n    </tr>\n    <tr>\n      <th>2. Is currently divorced</th>\n      <td>0.052***</td>\n      <td>0.017</td>\n      <td>0.051***</td>\n      <td>0.017</td>\n      <td>0.053***</td>\n      <td>0.019</td>\n      <td>0.049**</td>\n      <td>0.021</td>\n      <td>0.071**</td>\n      <td>0.029</td>\n    </tr>\n    <tr>\n      <th>3. Has ever married</th>\n      <td>-0.071***</td>\n      <td>0.024</td>\n      <td>-0.043*</td>\n      <td>0.023</td>\n      <td>-0.057**</td>\n      <td>0.028</td>\n      <td>-0.071**</td>\n      <td>0.029</td>\n      <td>-0.115**</td>\n      <td>0.047</td>\n    </tr>\n    <tr>\n      <th rowspan=\"4\" valign=\"top\">Panel B. Spouse\u2019s nativity and ethnicity</th>\n      <th>1. Spouse English-speaking ability ordinal measure</th>\n      <td>0.809***</td>\n      <td>0.180</td>\n      <td>0.752***</td>\n      <td>0.194</td>\n      <td>0.817***</td>\n      <td>0.131</td>\n      <td>0.797***</td>\n      <td>0.178</td>\n      <td>1.023***</td>\n      <td>0.105</td>\n    </tr>\n    <tr>\n      <th>2. Spouse is US-born</th>\n      <td>0.322***</td>\n      <td>0.107</td>\n      <td>0.261***</td>\n      <td>0.074</td>\n      <td>0.368***</td>\n      <td>0.136</td>\n      <td>0.224**</td>\n      <td>0.096</td>\n      <td>0.593***</td>\n      <td>0.213</td>\n    </tr>\n    <tr>\n      <th>3. Spouse has the same country of birth</th>\n      <td>-0.351***</td>\n      <td>0.115</td>\n      <td>-0.285***</td>\n      <td>0.090</td>\n      <td>-0.389***</td>\n      <td>0.141</td>\n      <td>-0.278**</td>\n      <td>0.130</td>\n      <td>-0.591***</td>\n      <td>0.218</td>\n    </tr>\n    <tr>\n      <th>4. Spouse has the same ancestry</th>\n      <td>-0.18*</td>\n      <td>0.099</td>\n      <td>-0.091</td>\n      <td>0.057</td>\n      <td>-0.21</td>\n      <td>0.128</td>\n      <td>-0.144</td>\n      <td>0.122</td>\n      <td>-0.498***</td>\n      <td>0.193</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">Panel C. Spouse\u2019s age and education</th>\n      <th>1. Spouse age</th>\n      <td>-0.901***</td>\n      <td>0.334</td>\n      <td>-0.913***</td>\n      <td>0.289</td>\n      <td>-1.1**</td>\n      <td>0.451</td>\n      <td>-0.978**</td>\n      <td>0.439</td>\n      <td>-1.493**</td>\n      <td>0.678</td>\n    </tr>\n    <tr>\n      <th>2. Spouse years of schooling</th>\n      <td>2.35***</td>\n      <td>0.679</td>\n      <td>2.295***</td>\n      <td>0.722</td>\n      <td>2.424***</td>\n      <td>0.556</td>\n      <td>2.273***</td>\n      <td>0.725</td>\n      <td>2.745***</td>\n      <td>0.696</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Panel D. Spouse\u2019s labor market outcomes</th>\n      <th>1. Spouse log(wages last year)</th>\n      <td>0.296***</td>\n      <td>0.111</td>\n      <td>0.277**</td>\n      <td>0.108</td>\n      <td>0.336***</td>\n      <td>0.118</td>\n      <td>0.23**</td>\n      <td>0.112</td>\n      <td>0.374**</td>\n      <td>0.174</td>\n    </tr>\n    <tr>\n      <th>2. Spouse worked last year</th>\n      <td>0.078***</td>\n      <td>0.029</td>\n      <td>0.069**</td>\n      <td>0.029</td>\n      <td>0.062**</td>\n      <td>0.029</td>\n      <td>0.062*</td>\n      <td>0.032</td>\n      <td>0.088*</td>\n      <td>0.046</td>\n    </tr>\n    <tr>\n      <th>3. Both worked last year</th>\n      <td>0.12**</td>\n      <td>0.048</td>\n      <td>0.114**</td>\n      <td>0.049</td>\n      <td>0.102**</td>\n      <td>0.042</td>\n      <td>0.1**</td>\n      <td>0.048</td>\n      <td>0.111*</td>\n      <td>0.059</td>\n    </tr>\n    <tr>\n      <th rowspan=\"6\" valign=\"top\">Panel E. Fertility</th>\n      <th>1. Number of children living in same household</th>\n      <td>-0.441***</td>\n      <td>0.136</td>\n      <td>-0.399***</td>\n      <td>0.149</td>\n      <td>-0.349***</td>\n      <td>0.110</td>\n      <td>-0.414***</td>\n      <td>0.144</td>\n      <td>-0.476***</td>\n      <td>0.150</td>\n    </tr>\n    <tr>\n      <th>2. Has a child living in same household</th>\n      <td>-0.073**</td>\n      <td>0.037</td>\n      <td>-0.041</td>\n      <td>0.028</td>\n      <td>-0.058</td>\n      <td>0.042</td>\n      <td>-0.058</td>\n      <td>0.043</td>\n      <td>-0.113*</td>\n      <td>0.064</td>\n    </tr>\n    <tr>\n      <th>3. Number of children living in same household, only individuals married spouse present</th>\n      <td>-0.41***</td>\n      <td>0.131</td>\n      <td>-0.397***</td>\n      <td>0.134</td>\n      <td>-0.326***</td>\n      <td>0.116</td>\n      <td>-0.383***</td>\n      <td>0.136</td>\n      <td>-0.433***</td>\n      <td>0.143</td>\n    </tr>\n    <tr>\n      <th>4. Has a child living in same household, only individuals married with spouse present</th>\n      <td>-0.007</td>\n      <td>0.020</td>\n      <td>0.004</td>\n      <td>0.018</td>\n      <td>-0.003</td>\n      <td>0.032</td>\n      <td>0.011</td>\n      <td>0.018</td>\n      <td>-0.008</td>\n      <td>0.046</td>\n    </tr>\n    <tr>\n      <th>5. Is a single parent</th>\n      <td>0.021</td>\n      <td>0.026</td>\n      <td>0.034*</td>\n      <td>0.020</td>\n      <td>0.025</td>\n      <td>0.032</td>\n      <td>0.033</td>\n      <td>0.027</td>\n      <td>0.01</td>\n      <td>0.045</td>\n    </tr>\n    <tr>\n      <th>6. Is a never married, single parent</th>\n      <td>-0.002</td>\n      <td>0.017</td>\n      <td>0.008</td>\n      <td>0.014</td>\n      <td>0.001</td>\n      <td>0.021</td>\n      <td>0.005</td>\n      <td>0.020</td>\n      <td>-0.009</td>\n      <td>0.031</td>\n    </tr>\n    <tr>\n      <th rowspan=\"4\" valign=\"top\">Panel F. Residential location</th>\n      <th>1. Fraction of PUMA population from same country of birth</th>\n      <td>-0.007</td>\n      <td>0.007</td>\n      <td>0.0</td>\n      <td>0.003</td>\n      <td>-0.014</td>\n      <td>0.011</td>\n      <td>-0.005</td>\n      <td>0.007</td>\n      <td>-0.027**</td>\n      <td>0.012</td>\n    </tr>\n    <tr>\n      <th>2. Fraction from same country of birth is above national mean for the country of birth</th>\n      <td>-0.015</td>\n      <td>0.065</td>\n      <td>0.022</td>\n      <td>0.053</td>\n      <td>-0.035</td>\n      <td>0.062</td>\n      <td>0.018</td>\n      <td>0.060</td>\n      <td>-0.19***</td>\n      <td>0.067</td>\n    </tr>\n    <tr>\n      <th>3. Fraction of PUMA population with same primary ancestry</th>\n      <td>-0.018</td>\n      <td>0.013</td>\n      <td>-0.008</td>\n      <td>0.010</td>\n      <td>-0.032**</td>\n      <td>0.014</td>\n      <td>-0.016</td>\n      <td>0.013</td>\n      <td>-0.063***</td>\n      <td>0.013</td>\n    </tr>\n    <tr>\n      <th>4. Fraction with same ancestry is above national mean for the primary ancestry</th>\n      <td>-0.022</td>\n      <td>0.057</td>\n      <td>0.031</td>\n      <td>0.044</td>\n      <td>-0.032</td>\n      <td>0.057</td>\n      <td>-0.005</td>\n      <td>0.055</td>\n      <td>-0.184***</td>\n      <td>0.056</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n---\n# 6. Robustness checks and extensions \n---\n\n\n### 6.1 Durbin Wu Hausman test\n\nWe first examine the endogeneity of English proficiency, or in other words, whether employing IV add merits to our analysis. Although the benchmark authors test for endogeneity by comparing OLS and IV estimate, we can also test for endogeneity in a more formal way by running the Durbin\u2013Wu\u2013Hausman test on English proficiency.\n\nAs stated before, our equation (2) is: \n\\begin{equation}\\tag{2}\nENG_{ija}= \\alpha_{1}+\\pi_{1}k_{ija}+\\delta_{1a}+\\gamma_{1j}+W_{ija}'\\rho_{1}+\\epsilon_{1ija}\n\\end{equation}\n\nBy equation (2), we get the estimation of $\\epsilon_{1ija}$ ie. $\\hat{\\epsilon_{1ija}}$\n\n\nDurbin\u2013Wu\u2013Hausman test result given by \n\n\\begin{equation}\\tag{5}\ny_{ija}= \\alpha_{1}+ \\beta {ENG_{ija}}+ \\omega\\hat{\\epsilon_{ija}} + \\delta_{a}+\\gamma_{j}  + W_{ija}'\\rho + \\mu_{ija}\n\\end{equation}\n\nThe estimation of $\\omega$ will be our target. \n\n\n\n\n```python\n#DWH Test\n\nfit_st1 = wls( \"eng ~ idvar + C(agearr) + C(age) + C(bpld) + female + black + asianpi + other + multi + hispdum\", data=df_ind, weights=df_ind[\"perwt2\"] ).fit(cov_type='cluster', cov_kwds={'groups': df_ind['bpld']}, use_t=False)\ndf_ind['Epsilon']  = fit_st1.resid\ndf_ind['eng_hat'] = fit_st1.predict(df_ind)\n\n\nresult_DWH_ind = pd.DataFrame({\"Dependent variable St\": list_table3_ind})\nfor var in list_table3_ind:\n   get_Durbin_Wu_Hausman_result(df_ind, var,result_DWH_ind )\nfit_st1 = wls( \"eng ~ idvar + C(agearr) + C(age) + C(bpld) + female + black + asianpi + other + multi + hispdum\", data=df_mat, weights=df_mat[\"perwt2\"] ).fit(cov_type='cluster', cov_kwds={'groups': df_mat['bpld']}, use_t=False)\ndf_mat['Epsilon']  = fit_st1.resid\ndf_mat['eng_hat'] = fit_st1.predict(df_mat)\n\n\nresult_DWH_mat = pd.DataFrame({\"Dependent variable St\": list_table3_mat})\nfor var in list_table3_mat:\n   get_Durbin_Wu_Hausman_result(df_mat, var,result_DWH_mat )\nresult_DWH = result_DWH_ind.append(result_DWH_mat)\nresult_DWH = get_variable_full_name_table3(result_DWH)\nresult_DWH = result_DWH.sort_index(ascending=True, sort_remaining =False)\n\nget_asteris_and_coef(result_DWH,\"Epsilon P Value\", \"Epsilon\", \"Epsilon\") \n\nresult_DWH=result_DWH[[\"Epsilon\",\"Epsilon SE\"]]\n\n\n```\n\n    marriedpresent\n    divorced\n    evermarried\n    nchild\n    haskid\n    singleparent\n    nevermarried_haskid\n    share_bpld_minusself\n    abovemean_bpld2\n    ancestpct_minusself\n    abovemean_ancestry2\n    spouseeng\n    marriednative\n    couplesamebpld\n    couplesameancestry1\n    spouseage\n    spouseyrssch\n    spouselnwage\n    spouseworkedly\n    bothworked\n    nchild_spouse\n    haskid_spouse\n\n\n\n```python\nprint(\"Table 5 \u2014Durbin Wu Hausman test result\")\nresult_DWH\n```\n\n    Table 5 \u2014Durbin Wu Hausman test result\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>Epsilon</th>\n      <th>Epsilon SE</th>\n    </tr>\n    <tr>\n      <th>Panel</th>\n      <th>Dependent variable</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Panel A. Marital status</th>\n      <th>1. Is currently married with spouse present</th>\n      <td>0.117***</td>\n      <td>0.036</td>\n    </tr>\n    <tr>\n      <th>2. Is currently divorced</th>\n      <td>-0.043***</td>\n      <td>0.016</td>\n    </tr>\n    <tr>\n      <th>3. Has ever married</th>\n      <td>0.07***</td>\n      <td>0.023</td>\n    </tr>\n    <tr>\n      <th rowspan=\"4\" valign=\"top\">Panel B. Spouse\u2019s nativity and ethnicity</th>\n      <th>1. Spouse English-speaking ability ordinal measure</th>\n      <td>-0.303***</td>\n      <td>0.032</td>\n    </tr>\n    <tr>\n      <th>2. Spouse is US-born</th>\n      <td>-0.22**</td>\n      <td>0.104</td>\n    </tr>\n    <tr>\n      <th>3. Spouse has the same country of birth</th>\n      <td>0.234**</td>\n      <td>0.108</td>\n    </tr>\n    <tr>\n      <th>4. Spouse has the same ancestry</th>\n      <td>0.106</td>\n      <td>0.104</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">Panel C. Spouse\u2019s age and education</th>\n      <th>1. Spouse age</th>\n      <td>0.558*</td>\n      <td>0.329</td>\n    </tr>\n    <tr>\n      <th>2. Spouse years of schooling</th>\n      <td>-1.022***</td>\n      <td>0.348</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Panel D. Spouse\u2019s labor market outcomes</th>\n      <th>1. Spouse log(wages last year)</th>\n      <td>-0.131</td>\n      <td>0.086</td>\n    </tr>\n    <tr>\n      <th>2. Spouse worked last year</th>\n      <td>-0.04*</td>\n      <td>0.024</td>\n    </tr>\n    <tr>\n      <th>3. Both worked last year</th>\n      <td>-0.032</td>\n      <td>0.031</td>\n    </tr>\n    <tr>\n      <th rowspan=\"6\" valign=\"top\">Panel E. Fertility</th>\n      <th>1. Number of children living in same household</th>\n      <td>0.339***</td>\n      <td>0.100</td>\n    </tr>\n    <tr>\n      <th>2. Has a child living in same household</th>\n      <td>0.069*</td>\n      <td>0.036</td>\n    </tr>\n    <tr>\n      <th>3. Number of children living in same household, only individuals married spouse present</th>\n      <td>0.235***</td>\n      <td>0.081</td>\n    </tr>\n    <tr>\n      <th>4. Has a child living in same household, only individuals married with spouse present</th>\n      <td>-0.012</td>\n      <td>0.020</td>\n    </tr>\n    <tr>\n      <th>5. Is a single parent</th>\n      <td>-0.022</td>\n      <td>0.024</td>\n    </tr>\n    <tr>\n      <th>6. Is a never married, single parent</th>\n      <td>-0.001</td>\n      <td>0.017</td>\n    </tr>\n    <tr>\n      <th rowspan=\"4\" valign=\"top\">Panel F. Residential location</th>\n      <th>1. Fraction of PUMA population from same country of birth</th>\n      <td>-0.003</td>\n      <td>0.010</td>\n    </tr>\n    <tr>\n      <th>2. Fraction from same country of birth is above national mean for the country of birth</th>\n      <td>-0.035</td>\n      <td>0.072</td>\n    </tr>\n    <tr>\n      <th>3. Fraction of PUMA population with same primary ancestry</th>\n      <td>0.005</td>\n      <td>0.017</td>\n    </tr>\n    <tr>\n      <th>4. Fraction with same ancestry is above national mean for the primary ancestry</th>\n      <td>-0.02</td>\n      <td>0.062</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThe test evaluate the endogeneity of English proficiency by verifying the economic and statistics significance of the coefficient for epsilon hat. If $\\hat{\\omega}$ is significant, it is implied that that endogenous regressors' effects on the estimates are significant, and an IV strategy is needed. Vice versa, if residual is not statistically significantly different from zero, so conclude that there is no endogeneity bias in the OLS estimates. Using DWH test, we discovered that with regard to quite a lot of outcomes, we have no statistical reasons to use English proficiency as the instrument. The exceptions are \u201cSpouse English-speaking ability ordinal measure\u201d, \u201cSpouse years of schooling\u201d , \u201cSpouse age\u201d, \u201cNumber of children living in same household\u201d. \n\nHowever, although the DWH test result is not satisfactory, we might still defend using this IV approach by arguing an \"economics theory comes first\" attitude. The statistical failure is a result caused by the imperfectness of the data on hand and possibly committing variable biases. As long as the economics reasoning is backed by a strong economics theory and intuition, we should feel confident employing the current IV. \n\n\n### 6.2 Control for residence location\n\nIt is known that different states have different cultures and policies, and therefore different acceptance towards immigrants. Some states have an immigrant tradition such as Los Angeles and New York while some do not. It is possible that some locations of residence are more popular within non-English-speaking immigrants. For example, California has a lot of Asian immigrants because of the location and its immigrant heritage. Likewise, Mexican and South American immigrants are clustered in southern states such as Texas, New Mexico and Florida. States with a stronger immigrants heritage are easier for immigrants to assimilate. So the result might be biased. We therefore include a vector of dummy variables of state of residence and interaction between birthplace and state of residence into the model. \n\n\n```python\nresult_R2_ind = pd.DataFrame({\"Dependent variable St\": list_table3_ind})\nfit_st1 = wls( \"eng ~ idvar + C(agearr) + C(age) + C(bpld)+ C(statefip)*pwlinear + female + black + asianpi + other + multi + hispdum\", data=df_ind, weights=df_ind[\"perwt2\"] ).fit(cov_type='cluster', cov_kwds={'groups': df_ind['bpld']}, use_t=False)\ndf_ind['eng_hat'] = fit_st1.predict(df_ind)\n\nfor var in list_table3_ind:\n    get_ols_tsls_result_Robust2(df_ind, var, result_R2_ind)\n\nresult_R2_mat = pd.DataFrame({\"Dependent variable St\": list_table3_mat})\nfit_st1 = wls( \"eng ~ idvar + C(agearr) + C(age) + C(bpld)+ C(statefip)*pwlinear + female + black + asianpi + other + multi + hispdum\", data=df_mat, weights=df_mat[\"perwt2\"] ).fit(cov_type='cluster', cov_kwds={'groups': df_mat['bpld']}, use_t=False)\ndf_mat['eng_hat'] = fit_st1.predict(df_mat)\n\nfor var in list_table3_mat:\n    get_ols_tsls_result_Robust2(df_mat, var, result_R2_mat)\n\n\nresult_R2 = result_R2_ind.append(result_R2_mat)\nresult_R2 = get_variable_full_name_table3(result_R2)\nresult_R2 = result_R2.sort_index(ascending=True, sort_remaining =False)\nget_asteris_and_coef(result_R2,\"2SLS P Value\", \"2SLS\", \"English effect(2SLS)\") \n   \nresult_R2 = result_R2[[\"English effect(2SLS)\", \"2SLS SE\"]]\n\n\n```\n\n    marriedpresent\n    divorced\n    evermarried\n    nchild\n    haskid\n    singleparent\n    nevermarried_haskid\n    share_bpld_minusself\n    abovemean_bpld2\n    ancestpct_minusself\n    abovemean_ancestry2\n    spouseeng\n    marriednative\n    couplesamebpld\n    couplesameancestry1\n    spouseage\n    spouseyrssch\n    spouselnwage\n    spouseworkedly\n    bothworked\n    nchild_spouse\n    haskid_spouse\n\n\n\n```python\nprint(\"Table 6 \u2014 English effect with control on the residence location (state level)\")\nresult_R2\n```\n\n    Table 6 \u2014 English effect with control on the residence location (state level)\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>English effect(2SLS)</th>\n      <th>2SLS SE</th>\n    </tr>\n    <tr>\n      <th>Panel</th>\n      <th>Dependent variable</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Panel A. Marital status</th>\n      <th>1. Is currently married with spouse present</th>\n      <td>-0.096**</td>\n      <td>0.044</td>\n    </tr>\n    <tr>\n      <th>2. Is currently divorced</th>\n      <td>0.05**</td>\n      <td>0.020</td>\n    </tr>\n    <tr>\n      <th>3. Has ever married</th>\n      <td>-0.077***</td>\n      <td>0.028</td>\n    </tr>\n    <tr>\n      <th rowspan=\"4\" valign=\"top\">Panel B. Spouse\u2019s nativity and ethnicity</th>\n      <th>1. Spouse English-speaking ability ordinal measure</th>\n      <td>0.852***</td>\n      <td>0.140</td>\n    </tr>\n    <tr>\n      <th>2. Spouse is US-born</th>\n      <td>0.385***</td>\n      <td>0.117</td>\n    </tr>\n    <tr>\n      <th>3. Spouse has the same country of birth</th>\n      <td>-0.403***</td>\n      <td>0.131</td>\n    </tr>\n    <tr>\n      <th>4. Spouse has the same ancestry</th>\n      <td>-0.225**</td>\n      <td>0.114</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">Panel C. Spouse\u2019s age and education</th>\n      <th>1. Spouse age</th>\n      <td>-1.085***</td>\n      <td>0.421</td>\n    </tr>\n    <tr>\n      <th>2. Spouse years of schooling</th>\n      <td>2.514***</td>\n      <td>0.604</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Panel D. Spouse\u2019s labor market outcomes</th>\n      <th>1. Spouse log(wages last year)</th>\n      <td>0.321**</td>\n      <td>0.125</td>\n    </tr>\n    <tr>\n      <th>2. Spouse worked last year</th>\n      <td>0.078**</td>\n      <td>0.032</td>\n    </tr>\n    <tr>\n      <th>3. Both worked last year</th>\n      <td>0.113**</td>\n      <td>0.045</td>\n    </tr>\n    <tr>\n      <th rowspan=\"6\" valign=\"top\">Panel E. Fertility</th>\n      <th>1. Number of children living in same household</th>\n      <td>-0.39***</td>\n      <td>0.120</td>\n    </tr>\n    <tr>\n      <th>2. Has a child living in same household</th>\n      <td>-0.067</td>\n      <td>0.044</td>\n    </tr>\n    <tr>\n      <th>3. Number of children living in same household, only individuals married spouse present</th>\n      <td>-0.371***</td>\n      <td>0.104</td>\n    </tr>\n    <tr>\n      <th>4. Has a child living in same household, only individuals married with spouse present</th>\n      <td>0.007</td>\n      <td>0.027</td>\n    </tr>\n    <tr>\n      <th>5. Is a single parent</th>\n      <td>0.007</td>\n      <td>0.025</td>\n    </tr>\n    <tr>\n      <th>6. Is a never married, single parent</th>\n      <td>-0.005</td>\n      <td>0.018</td>\n    </tr>\n    <tr>\n      <th rowspan=\"4\" valign=\"top\">Panel F. Residential location</th>\n      <th>1. Fraction of PUMA population from same country of birth</th>\n      <td>0.0</td>\n      <td>0.013</td>\n    </tr>\n    <tr>\n      <th>2. Fraction from same country of birth is above national mean for the country of birth</th>\n      <td>-0.011</td>\n      <td>0.062</td>\n    </tr>\n    <tr>\n      <th>3. Fraction of PUMA population with same primary ancestry</th>\n      <td>-0.001</td>\n      <td>0.023</td>\n    </tr>\n    <tr>\n      <th>4. Fraction with same ancestry is above national mean for the primary ancestry</th>\n      <td>0.031</td>\n      <td>0.062</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThe result is displayed in table 6. We can observe similar outcomes from the baseline model presented in table 4_. One exception is the English effect on the variable \u201cspouse has the same primary ancestry\u201d. In the baseline model, the effect is -0.181 and insignificant at 10% level. When we control for the interaction term, effect is -0.225 and significant at 5% level. \n\n### 6.3 English effect on outcome gap between immigrants and spouses\n\nWe extend the authors' analysis to other outcomes that we are interested in. We use the baseline model to investigate the gap of age, years of schooling, and income between spouses. These three gaps can be seen as a proxy for age closeness, education closeness and economic closeness between a couple. Apart from the bassline model, we also add controls for the immigrants\u2019 level and their partners\u2019 level of the dependent variables and observe the effect. \n\n\n```python\ndf_mat_R3 = df_mat\ndf_mat_R3['age'].replace('  ', np.nan, inplace=True)\ndf_mat_R3= df_mat_R3.dropna(subset=['age'])\ndf_mat_R3['spouseage'].replace('  ', np.nan, inplace=True)\ndf_mat_R3= df_mat_R3.dropna(subset=['spouseage'])\ndf_mat_R3['yrssch'].replace('  ', np.nan, inplace=True)\ndf_mat_R3= df_mat_R3.dropna(subset=['yrssch'])\ndf_mat_R3['spouseyrssch'].replace('  ', np.nan, inplace=True)\ndf_mat_R3= df_mat_R3.dropna(subset=['spouseyrssch'])\ndf_mat_R3['lnwagely'].replace('  ', np.nan, inplace=True)\ndf_mat_R3= df_mat_R3.dropna(subset=['lnwagely'])\ndf_mat_R3['spouselnwage'].replace('  ', np.nan, inplace=True)\ndf_mat_R3= df_mat_R3.dropna(subset=['spouselnwage'])\n\n\ndf_mat_R3[\"Wage_difference\"] = abs(df_mat_R3[\"lnwagely\"] - df_mat_R3[\"spouselnwage\"])\ndf_mat_R3[\"Age_difference\"] = abs(df_mat_R3[\"age\"] - df_mat_R3[\"spouseage\"])\ndf_mat_R3[\"Education_difference\"] = abs(df_mat_R3[\"yrssch\"] - df_mat_R3[\"spouseyrssch\"])\n\nlist_mat_R3 = [\"Wage_difference\", \"Age_difference\", \"Education_difference\"    ]\n\nresult_mat_R3 = pd.DataFrame({\"Dependent variable St\": list_mat_R3})\n\nget_tsls_result_table4(df_mat_R3, \"Wage_difference\", result_mat_R3,\"lnwagely + spouselnwage\" )\nget_tsls_result_table4(df_mat_R3, \"Education_difference\", result_mat_R3, \"yrssch +spouseyrssch \")\nget_tsls_result_table4(df_mat_R3, \"Age_difference\", result_mat_R3,\"spouseage\" )\n\nget_asterisk(result_mat_R3,\"2SLS P Value\", \"2SLS\")\nresult_mat_R3[\"2SLS Parameter (Full Sample)\"] = (result_mat_R3[\"2SLS Parameter\"].astype(str) + result_mat_R3[\"2SLS Sig. level\"])\nresult_mat_R3=result_mat_R3.rename(columns={ \"Dependent variable St\":\"Dependent variable\", \"2SLS SE\": \"SE (Full Sample)\"})\nresult_mat_R3 = result_mat_R3.set_index('Dependent variable')\nresult_mat_R3= result_mat_R3[[\"2SLS Parameter (Full Sample)\", \"SE (Full Sample)\"]]\n\n\n# subset female sample \ndf_mat_R3_female = df_mat_R3[df_mat_R3[\"female\"] == 1]\nresult_mat_R3_female = pd.DataFrame({\"Dependent variable St\": list_mat_R3})\n\nget_tsls_result_table4(df_mat_R3_female, \"Wage_difference\", result_mat_R3_female,\"lnwagely + spouselnwage\" )\nget_tsls_result_table4(df_mat_R3_female, \"Education_difference\", result_mat_R3_female, \"yrssch +spouseyrssch \")\nget_tsls_result_table4(df_mat_R3_female, \"Age_difference\", result_mat_R3_female,\"spouseage\" )\n\nget_asterisk(result_mat_R3_female,\"2SLS P Value\", \"2SLS\")\nresult_mat_R3_female[\"2SLS Parameter (Female Sample)\"] = (result_mat_R3_female[\"2SLS Parameter\"].astype(str) + result_mat_R3_female[\"2SLS Sig. level\"])\nresult_mat_R3_female=result_mat_R3_female.rename(columns={ \"Dependent variable St\":\"Dependent variable\", \"2SLS SE\": \"SE (Female Sample)\"})\nresult_mat_R3_female = result_mat_R3_female.set_index('Dependent variable')\nresult_mat_R3_female= result_mat_R3_female[[\"2SLS Parameter (Female Sample)\", \"SE (Female Sample)\"]]\n\n\n# subset male sample \ndf_mat_R3_male = df_mat_R3[df_mat_R3[\"female\"] == 0]\nresult_mat_R3_male = pd.DataFrame({\"Dependent variable St\": list_mat_R3})\n\nget_tsls_result_table4(df_mat_R3_male, \"Wage_difference\", result_mat_R3_male,\"lnwagely + spouselnwage\" )\nget_tsls_result_table4(df_mat_R3_male, \"Education_difference\", result_mat_R3_male, \"yrssch +spouseyrssch \")\nget_tsls_result_table4(df_mat_R3_male, \"Age_difference\", result_mat_R3_male,\"spouseage\" )\n\nget_asterisk(result_mat_R3_male,\"2SLS P Value\", \"2SLS\")\nresult_mat_R3_male[\"2SLS Parameter (Male Sample)\"] = (result_mat_R3_male[\"2SLS Parameter\"].astype(str) + result_mat_R3_male[\"2SLS Sig. level\"])\nresult_mat_R3_male=result_mat_R3_male.rename(columns={ \"Dependent variable St\":\"Dependent variable\", \"2SLS SE\": \"SE (Male Sample)\"})\nresult_mat_R3_male = result_mat_R3_male.set_index('Dependent variable')\nresult_mat_R3_male= result_mat_R3_male[[\"2SLS Parameter (Male Sample)\", \"SE (Male Sample)\"]]\n\n\nresult_mat_R3 = pd.merge(result_mat_R3, result_mat_R3_female,\n                        left_on=['Dependent variable'], right_on = ['Dependent variable'], how = 'left')\nresult_mat_R3 = pd.merge(result_mat_R3, result_mat_R3_male,\n                        left_on=['Dependent variable'], right_on = ['Dependent variable'], how = 'left')\n\n\n```\n\n    Wage_difference\n    Education_difference\n    Age_difference\n\n\n    /Users/chingfungchow/opt/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py:6746: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame\n    \n    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      self._update_inplace(new_data)\n\n\n    Wage_difference\n    Education_difference\n    Age_difference\n    Wage_difference\n    Education_difference\n    Age_difference\n\n\n\n```python\nprint(\"Table 7 \u2014 English effect on the outcome gap with spouse\")\nresult_mat_R3\n```\n\n    Table 7 \u2014 English effect on the outcome gap with spouse\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>2SLS Parameter (Full Sample)</th>\n      <th>SE (Full Sample)</th>\n      <th>2SLS Parameter (Female Sample)</th>\n      <th>SE (Female Sample)</th>\n      <th>2SLS Parameter (Male Sample)</th>\n      <th>SE (Male Sample)</th>\n    </tr>\n    <tr>\n      <th>Dependent variable</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Wage_difference</th>\n      <td>0.199**</td>\n      <td>0.083</td>\n      <td>0.094</td>\n      <td>0.062</td>\n      <td>0.213***</td>\n      <td>0.060</td>\n    </tr>\n    <tr>\n      <th>Age_difference</th>\n      <td>0.216</td>\n      <td>0.269</td>\n      <td>0.247</td>\n      <td>0.273</td>\n      <td>0.142</td>\n      <td>0.205</td>\n    </tr>\n    <tr>\n      <th>Education_difference</th>\n      <td>-0.696***</td>\n      <td>0.130</td>\n      <td>-0.359*</td>\n      <td>0.202</td>\n      <td>-1.057***</td>\n      <td>0.213</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nFrom the results we know that English level does not inflict significant effects on age and economic closeness. But it affects education closeness significantly. A simple explanation can be offered: English skills have a significant effect on communications and consequently exchanges of ideas. The cost of communication decreases if one\u2019s English level is better. As a result, immigrants will consume more intelligence closeness.\n\n\nSuppose the three kinds of closeness are among the goods in deciding the utility of marriage (other goods will be, for example, the appearance of the partner). To consume education or intelligence closeness, one has to pay for the effort of communication. An increase in English level lowers the cost for communication, so the relative price of intelligence level closeness decrease. If intelligence closeness is not a Giffen good, then more of it will be consumed. However when it comes to age closeness or economic closeness, the increase of English level has no effect on the cost of these two goods. That explains why the English skill effects on the age gap and income gap are not significant. We can also observe that the magnitude of English effect is much stronger for male than for female immigrants. The differential can probably be explained by different utility curves of marriage between females and males. \n\n\n---\n# 7. Conclusion \n---\n\nThe benchmark investigates the relationships between English proficiency and some social aspects of an immigrants in the US. The authors choose the age of arrival as the instrument to control for omitted variables bias and reverse causality problems. Although some doubts call for attention regarding endogeneity issues (section 6.1), nevertheless we still have theoretical reasons to retain the IV approach proposed by the benchmark. The IV results pass a lot of robustness checks (section 5.2 & 6.2). It is clearly demonstrated that English proficiency causes increases in certain outcomes, especially some marital and fertility outcomes (section 5.1 & 6.3). However, we have seen the conceptual pitfalls of the benchmark. \n\nThe outcomes might not be satisfactory measurements for the level of social assimilation, despite being social outcomes. Some outcomes do not imply the degree of integration. That significantly limits the policy implications of the paper. We agree with most theses with the benchmark but differ in conceptual issues. As the aim of this replication paper is not to explore theories in immigration and population economics, we leave the project of defining good measurements for social assimilations to future researchers. \n\n---\n# 8. References\n---\n\n* **Bleakley, Hoyt, and Chin, Aimee**. 2010. Age at arrival, English proficiency, and social assimilation among US immigrants. *American Economic Journal: Applied Economics*, 2(1), 165-92.\n\n\n* **Duncan, Brian, and Stephen J. Trejo**. 2007. \u201cEthnic Identification, Intermarriage, and Unmeasured Progress by Mexican Americans.\u201d In *Mexican Immigration to the United States*, ed. George J. Borjas, 229\u201367. Chicago, IL: University of Chicago Press and National Bureau of Economic Research.\n\n\n* **Funkhouser, Edward, and Fernando A. Ramos**. 1993. \u201cThe Choice of Migration Destination: Dominican and Cuban Immigrants to the Mainland United States and Puerto Rico.\u201d *International Migration Review*, 27(3): 537\u201356.\n\n\n* **Lenneberg, Eric**. 1967. *Biological foundations of language*. New York (N.Y.): Wiley.\n\n\n* **Morris, Charles.**. 1967. *Foundations of the theory of signs* (International encyclopedia of unified science 1/2). University of Chicago press.\n\n\n* **Sorenson, Ann Marie**. 1988. \u201cThe Fertility and Language Characteristics of Mexican-American and Non-Hispanic Husbands and Wives.\u201d *Sociological Quarterly*, 29(1): 111\u201330.\n\n\n* **Stevens, Gillian, and Gray Swicegood**. 1987. \u201cThe Linguistic Context of Ethnic Endogamy.\u201d *American Sociological Review*, 52(1): 73\u201382.\n\n\n* **Swicegood, Gray, Frank D. Bean, Elizabeth Hervey Stephen, and Wolfgang Opitz**. 1988. \u201cLanguage Usage and Fertility in Mexican-Origin Population of the United States.\u201d *Demography*, 25(1): 17\u201333.\n\n\n* **Toussaint-Comeau, Maude, and Sherrie L. W. Rhine**. 2004. \u201cTenure Choice with Location Selection: The Case of Hispanic Neighborhoods in Chicago.\u201d *Contemporary Economic Policy*, 22(1): 95\u2013110.\n\n\n* **Wittgenstein, Ludwig**. 1968. *Philosophical investigations* (Repr. ed.). Oxford: Blackwell.\n\n\n\n", "meta": {"hexsha": "dffa8e526c68ddfeaa02c5b03e3bf0203d317812", "size": 348826, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Project.ipynb", "max_stars_repo_name": "Jackcfchow/Microeconometrics-Paper", "max_stars_repo_head_hexsha": "0e0324932d3029a2d8adf3a898e0b0754a31277c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-27T14:54:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T14:54:06.000Z", "max_issues_repo_path": "Project.ipynb", "max_issues_repo_name": "Jackcfchow/Microeconometrics-Paper", "max_issues_repo_head_hexsha": "0e0324932d3029a2d8adf3a898e0b0754a31277c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Project.ipynb", "max_forks_repo_name": "Jackcfchow/Microeconometrics-Paper", "max_forks_repo_head_hexsha": "0e0324932d3029a2d8adf3a898e0b0754a31277c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.2838205303, "max_line_length": 1465, "alphanum_fraction": 0.4108237345, "converted": true, "num_tokens": 40827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.10970577969958141, "lm_q1q2_score": 0.04803176834112251}}
{"text": "```\n# code cell\nname = \"Jonathan\"\n```\n\n\n```\n# code cell\nname = \"Jonathan\"\n```\n\n\n```\n# code cell\nname = \"Jonathan\"\n```\n\n\n```\n# Add this to python2 code to make life easier -- safe to use in python3 as well.\nfrom __future__ import absolute_import, division, print_function\n```\n\n\n```\nimport numpy as np\n# don't do:\n# from numpy import *\n```\n\n\n```\nmax('a')\n```\n\n\n```\nnp.max('a')\n```\n\n\n```\n%matplotlib inline\n%config InlineBackend.figure_format='retina'\n```\n\n\n```\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport os\nfrom sklearn.datasets import load_boston\nfrom pivottablejs import pivot_ui\nimport qgrid\nimport sys\nimport warnings\nwarnings.filterwarnings('ignore')\n```\n\n\n```\ndf = pd.read_csv(\"../data/mps.csv\", encoding=\"ISO-8859-1\")\n```\n\n\n```\n# recommend using .head()\ndf.head(10)\n```\n\n\n```\n# Province, Party, Average, Age, Heatmap\n```\n\n\n```\npivot_ui(df)\n```\n\n\n```\ndf_dict = load_boston()\nfeatures = pd.DataFrame(data=df_dict.data, columns = df_dict.feature_names)\ntarget = pd.DataFrame(data=df_dict.target, columns = ['MEDV'])\ndf = pd.concat([features, target], axis=1)\n```\n\n\n```\ndf['Zone'] = df['ZN'].astype('category')\ndf['CHAS'] = df['CHAS'].astype('category')\ndf.head()\n```\n\n\n```\nqgrid_widget = qgrid.show_grid(df[['CRIM',\n                                   'Zone',\n                                   'INDUS',\n                                   'CHAS',\n                                   'NOX',\n                                   'AGE',\n                                   'RAD',\n                                   'LSTAT',\n                                   'MEDV',\n                                  ]], show_toolbar=True)\n```\n\n\n```\nqgrid_widget\n```\n\n\n```\ndf2 = qgrid_widget.get_changed_df()\n```\n\n\n```\ndf2.head(7)\n```\n\n\n```\ndf.head(7)\n```\n\n\n```\nimport numpy as np\n```\n\n\n```\n# shift-tab right \u2193 more useful\nnp.linspace(start=50, endpoint=False, endpoint=100)\n```\n\n\n```\n# shift-tab right \u2193 more useful\nnp.linspace(start=50, endpoint=False, stop=100)\n```\n\n\n```\nnp.linspace?\n```\n\n\n```\n?np.linspace\n```\n\n\n```\nnp.linspace??\n```\n\n\n```\n!subl ~/miniconda3/envs/dspy3/lib/python3.6/site-packages/numpy/core/function_base.py\n```\n\n\n```\nimport textwrap\ndef example_function():\n    \"\"\"Docstring for example function\"\"\"\n    \n    print(textwrap.dedent(\"\"\"\n    This is a multi-lined string\n    that I want to write inside of a function.\n    Notice what happens when I print this.\n        And when something is indented more.\"\"\"))\n\n\nexample_function()\n```\n\n\n```\n# But first find and replace\ndef silly_function(xval):\n    \"\"\"Takes a value and returns the value.\"\"\"\n    xval_sq = xval ** 2.0\n    1 + 12\n    xval_abs = np.sqrt(xval_sq)\n    return xval_abs\n```\n\n\n```\nsilly_function?\n```\n\n\n```\nsilly_function??\n```\n\n\n```\nsilly_function??\n```\n\n\n```\n# But first find and replace\ndef silly_function(xval):\n    \"\"\"Takes a value and returns the value.\"\"\"\n    xval_sq = xval ** 2.0\n    1 + 10\n    xval_abs = np.sqrt(xval_sq)\n    return xval_abs\n```\n\n\n```\nsilly_function??\n```\n\n\n```\nimport textwrap\ndef example_function():\n    \"\"\"Docstring for example function\"\"\"\n    \n    print(textwrap.dedent(\"\"\"\n    This is a multi-lined string\n    that I want to write inside of a function.\n    Notice what happens when I print this.\n        And when something is indented more.\"\"\"))\n\n\nexample_function()\n```\n\n\n```\n!ls ../data/\n```\n\n\n```\ncoal_years = !ls ../data/coal_prod_20*.csv\n```\n\n\n```\ncoal_years\n```\n\n\n```\nexample_dict = {}\n\n# Indent/dedent/comment\nfor index in range(5):\n    example_dict[\"one\"] = 1\n    example_dict[\"two\"] = 2\n    example_dict[\"three\"] = 3\n    example_dict[\"four\"] = 4\n```\n\n\n```\nexample_dict[\"prepend_one_better_neat\"] = 1\nexample_dict[\"prepend_two_better_neat\"] = 2\nexample_dict[\"prepend_three_better_neat\"] = 3\nexample_dict[\"prepend_four_better_neat\"] = 4\n```\n\n\n```\nexample_dict[\"one_better_neat\"] = 1\nexample_dict[\"two_better_neat\"] = 2\nexample_dict[\"three_better_neat\"] = 3\nexample_dict[\"four_better_neat\"] = 4\n```\n\n\n```latex\n%%latex\n\nIf you want to get crazier$\\ldots$\n\n\\begin{equation}\n\\oint_S {E_n dA = \\frac{1}{{\\varepsilon _0 }}} Q_\\textrm{inside}\n\\end{equation}\n```\n\n\n```bash\n%%bash\nwget http://www.ast.cam.ac.uk/~rfc/vpfit11.1.tar.gz\nmkdir -p vpfit11\ncd vpfit11\ntar -xvzf ../vpfit11.1.tar.gz\n```\n\n\n```\nnormal_argument = 12.4\nsecond_argument = 98.4\n\narg_with_spaces = \"the secret to life\"\n```\n\n\n```bash\n%%bash -s {normal_argument} {second_argument}\necho \"This script knows the value of the argument: $1\"\necho \"It also has no trouble with the second argument: $2\"\n```\n\n\n```bash\n%%bash -s \"$arg_with_spaces\"\necho \"This bash script knows $1.\"\n```\n\n\n```\nls\n```\n\n\n```\n!ls\n```\n\n\n```\n%ls\n```\n\n\n```\ntailthing = \"*.ipynb\"\n```\n\n\n```\n!ls {tailthing}\n```\n\n\n```\noutput = !ls \n```\n\n\n```\noutput\n```\n\n\n```\n%env \n```\n\n\n```\n!pwd\n```\n\n\n```\na = 3\na\n```\n\n\n```\n_i56\n```\n\n\n```\n_56\n```\n\n\n```\n_\n```\n\n\n```\nb = 5\nb * 15\n```\n\n\n```\n_\n```\n\n\n```\nc = a * b \n```\n", "meta": {"hexsha": "906826760b101168d963ba70e3800463b6380cf4", "size": 12819, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/history.ipynb", "max_stars_repo_name": "ddeloss/jupyter-tips-and-tricks", "max_stars_repo_head_hexsha": "e47d5e5d07d2b9c9ba0b0f8101e8416ae7dd7cbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 260, "max_stars_repo_stars_event_min_datetime": "2015-09-11T15:57:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T23:42:13.000Z", "max_issues_repo_path": "notebooks/history.ipynb", "max_issues_repo_name": "ddeloss/jupyter-tips-and-tricks", "max_issues_repo_head_hexsha": "e47d5e5d07d2b9c9ba0b0f8101e8416ae7dd7cbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/history.ipynb", "max_forks_repo_name": "ddeloss/jupyter-tips-and-tricks", "max_forks_repo_head_hexsha": "e47d5e5d07d2b9c9ba0b0f8101e8416ae7dd7cbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 144, "max_forks_repo_forks_event_min_datetime": "2015-09-10T15:13:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T01:43:24.000Z", "avg_line_length": 19.3057228916, "max_line_length": 91, "alphanum_fraction": 0.4742179577, "converted": true, "num_tokens": 1420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.09807932874307332, "lm_q1q2_score": 0.04789050764700419}}
{"text": "# Bevezet\u00e9s\nSykora Henrik - BME-GPK M\u0171szaki Mechanikai Tansz\u00e9k (sykora@mm.bme.hu)\n### Python programoz\u00e1si nyelv\n\nA Python egy open-source (OS), interpret\u00e1lt, \u00e1ltal\u00e1nos c\u00e9l\u00fa programoz\u00e1si nyelv (vagy script-nyelv).\n\n**Tulajdons\u00e1gai:**\n- Objektum orient\u00e1lt\n- Interpret\u00e1lt\n    - Nem sz\u00fcks\u00e9ges ford\u00edtani (mint a pl a *C++*-t), el\u00e9g csak be\u00edrni a parancsot, \u00e9s m\u00e1r futtathat\u00f3 is a k\u00f3d\n    - Alkalmas teszi sz\u00e1m\u00edt\u00e1sok gyors-prototipiz\u00e1l\u00e1s\u00e1ra\n    - Cser\u00e9be lass\u00fa\n- Open-source:\n    - Ingyenes\n    - Folyamatosan karban tartott \n    - Sz\u00e9les k\u00f6rben felhaszn\u00e1lt iparban \u00e9s akad\u00e9mi\u00e1ban is\n    - Nagy \"Community\", sok seg\u00e9dlettel, f\u00f3rummal (pl.: [stackoverflow](https://stackoverflow.com/questions/tagged/python)) \n- Modul\u00e1ris:\n    - Rengetek feladatra l\u00e9tezik \"*package*\" (pl.: numerikus sz\u00e1m\u00edt\u00e1sokra *numpy*/*scipy*, szimbolikus sz\u00e1m\u00edt\u00e1sokra *sympy*, t\u00e1bl\u00e1zatf\u00e1jl-kezel\u00e9sre *CSV*)\n    - Csak azt kell beh\u00edvni, amire sz\u00fcks\u00e9g\u00fcnk van\n    - Ismerni kell a *package* ekosziszt\u00e9m\u00e1t, mik l\u00e9teznek, mi mire j\u00f3, stb...\n- Sok IDE (*Integrated Development Environment*) l\u00e9tezik:\n    - Alapvet\u0151en shell (termin\u00e1l) alap\u00fa\n    - Notebook: **_jupyter notebook_**, *jupyter lab*\n    - Sz\u00f6vegszerkeszt\u0151: *Spyder*, *VS Code* (ingyenes/open source - ezek tartalmaznak *Debugger*-t is)\n    - Fizet\u0151s sz\u00f6vegszerkesz\u0151k (lista nem teljes): *Visual Studio*, *PyCharm*, stb...\n    \n### Jupyter notebook m\u0171k\u00f6d\u00e9se (+ Python kernel):\n\nLegfontosabb tudnival\u00f3k:\n\n- Csak egy *front-end*, ami kommunik\u00e1l egy *kernel*-lel (ez a kernel men\u00fcben v\u00e1laszthat\u00f3).\n- K\u00e9t m\u00f3d l\u00e9tezik:\n    - Command mode (cellam\u0171veleteket lehet v\u00e9gezni)\n    - Edit mode (sz\u00f6vegbevitel cell\u00e1ba)\n- Command mode (`ESC` billenty\u0171 lenyom\u00e1s\u00e1val \u00e9rhet\u0151 el, k\u00e9k cs\u00edk a cella kijel\u00f6l\u00e9se eset\u00e9n):\n    - Notebook ment\u00e9se: `s`\n    - Cell\u00e1k hozz\u00e1ad\u00e1sa: `b` az aktu\u00e1lis cella al\u00e1, `a` az aktu\u00e1lis cella f\u00f6l\u00e9\n    - Cella t\u00f6rl\u00e9se: k\u00e9tszer egym\u00e1s ut\u00e1n a `d` billenty\u0171 lenyom\u00e1sa\n    - Cella t\u00f6rl\u00e9s\u00e9nek visszavon\u00e1sa: `z`\n    - Cella m\u00e1sol\u00e1s: `c`, kiv\u00e1g\u00e1s: `x`, beilleszt\u00e9s az aktu\u00e1lis cella al\u00e1: `v`\n    - Sz\u00e1moz\u00e1s bekapcsol\u00e1sa a cella soraira: `l` (kis L), vagy `Shift + l` az \u00f6sszes cell\u00e1ra\n    - Cellam\u00f3dok: futtatand\u00f3 k\u00f3d: `y`, nyers k\u00f3d (nem futtathat\u00f3): `r`, markdown (form\u00e1zott sz\u00f6veg): `m` \n- Edit mode (`Enter` billenyt\u0171 lenyom\u00e1s\u00e1val \u00e9rhet\u0151 el, z\u00f6ld sz\u00edn):\n    - Sor \"kikommentel\u00e9se\"/\"vissza\u00e1ll\u00edt\u00e1sa\": `Ctrl + /`\n    - T\u00f6bb kurzor lehelyez\u00e9se: `Ctrl + Bal eg\u00e9rgomb` \n    - T\u00e9glalap-szer\u0171 kijel\u00f6l\u00e9s (rectangular selection): `Alt + Bal eg\u00e9rgomb` \"h\u00faz\u00e1sa\" (dragging)\n- K\u00f6z\u00f6s\n    - Cella futtat\u00e1sa, majd cellal\u00e9ptet\u00e9s: `Shift + Enter` (ez l\u00e9trehoz egy \u00faj cell\u00e1t, ha nincs hova l\u00e9pnie)\n    - Cella futtat\u00e1sa cellal\u00e9ptet\u00e9s n\u00e9lk\u00fcl: `Ctrl + Enter` \n\n**Jupyter notebook help-j\u00e9nek el\u0151hoz\u00e1sa**: *Edit mode*-ban `h` lenyom\u00e1s\u00e1val  \n**Python help**: Kurzorral a f\u00fcggv\u00e9ny nev\u00e9n \u00e1llva `Shift + Tab` vagy egy cell\u00e1ba `?\"fv_n\u00e9v\"` be\u00edr\u00e1sa \u00e9s futtat\u00e1sa\n\n### A bevezet\u0151 fel\u00e9p\u00edt\u00e9se:\n- [Alapm\u0171veletek](#Alapmuveletek)\n- [\u00d6sszetett f\u00fcggv\u00e9nyek](#Osszetettfuggvenyek)\n- [Saj\u00e1t f\u00fcggv\u00e9nyek](#Sajatfuggvenyek)\n- [List\u00e1k \u00e9s vez\u00e9rl\u00e9si szerkezetek](#Vezerlesiszerkezetek)\n- [K\u00fcls\u0151 f\u00fcggv\u00e9nyk\u00f6nyvt\u00e1rak](#Kulsofuggvenykonyvtarak)\n    - [Szimbolikus matematikai m\u0171veletek](#Szimbolikus)\n    - [Deriv\u00e1l\u00e1s/Integr\u00e1l\u00e1s](#DerivalIntegral)\n    - [Vektor \u00e9s m\u00e1trixsz\u00e1m\u00edt\u00e1sok Sympy-ban](#SzimVektorMatrix)\n    - [Vektor \u00e9s m\u00e1trixsz\u00e1m\u00edt\u00e1sok Numpy-ban](#NumVektorMatrix)\n    - [Egyenletek megold\u00e1sa Scipy-ban](#Egyenletek)\n    - [Szimbolikus f\u00fcggv\u00e9nyekb\u0151l numerikus f\u00fcggv\u00e9nyek](#SymToNum)\n- [Egyszer\u0171 \u00e1br\u00e1k k\u00e9sz\u00edt\u00e9se](#Egyszeruabrak)\n- [+ Oszt\u00e1lyok](#Osztalyok)\n\n# Python bevezet\u0151 \n\n## Alapm\u0171veletek (Shift/Ctrl + Enter-rel futtassuk)<a id='Alapmuveletek'></a>\n\n\n```python\n17 + 7 #\u00d6sszead\u00e1s\n```\n\n\n\n\n    24\n\n\n\n\n```python\n1+1\n```\n\n\n\n\n    2\n\n\n\n\n```python\n333 - 7 #Kivon\u00e1s\n```\n\n\n\n\n    326\n\n\n\n\n```python\n11 * 22 #Szorz\u00e1s\n```\n\n\n\n\n    242\n\n\n\n\n```python\n9/7 #Oszt\u00e1s (ez nem eg\u00e9sz (int) lesz: k\u00fcl\u00f6n t\u00edpus float)\n```\n\n\n\n\n    1.2857142857142858\n\n\n\n\n```python\n9//7\n```\n\n\n\n\n    1\n\n\n\n\n```python\n0.3-0.1-0.2 # float: sz\u00e1m\u00e1br\u00e1zol\u00e1si hiba lehet!!\n```\n\n\n\n\n    -2.7755575615628914e-17\n\n\n\n\n```python\n9**2 # Hatv\u00e1nyoz\u00e1s (** \u00e9s NEM ^!)\n```\n\n\n\n\n    81\n\n\n\n\n```python\n2**(0.5) # Gy\u00f6kv\u00f6n\u00e1s hatv\u00e1nyoz\u00e1s seg\u00edts\u00e9g\u00e9vel\n```\n\n\n\n\n    1.4142135623730951\n\n\n\n\n```python\n5e-3 #norm\u00e1lalak e seg\u00edts\u00e9g\u00e9vel (vagy 5E-3)\n```\n\n\n\n\n    0.005\n\n\n\nN\u00e9h\u00e1ny alapm\u0171velet m\u0171k\u00f6dik sz\u00f6vegre is\n\n\n```python\n'str1_' + 'str2_' #\u00d6sszead\u00e1s\n```\n\n\n\n\n    'str1_str2_'\n\n\n\n\n```python\n2 * 'str2_' #Szorz\u00e1s\n```\n\n\n\n\n    'str2_str2_'\n\n\n\n## \u00d6sszetettebb f\u00fcggv\u00e9nyek <a id='Osszetettfuggvenyek'></a>\n\n\n```python\nsin(2) #szinusz\n```\n\n\u00d6sszetettebb f\u00fcggv\u00e9nyek m\u00e1r nincsenek a python alapnyelvben - ilyenkor sz\u00fcks\u00e9ges beh\u00edvni k\u00fcls\u0151 csomagokat, pl a **math** csomagot\n\n\n```python\nimport math\n```\n\n\n```python\nsin(2) # ez \u00edgy tov\u00e1bbra sem l\u00e9tezik\n```\n\n\n```python\nmath.sin(2)\n```\n\n\n```python\n# T\u00f6bb parancs egy\u00fcttes be\u00edr\u00e1sakor nem l\u00e1tszik, csak az utols\u00f3 sor kimenete: print f\u00fcggv\u00e9ny alkalmaz\u00e1sa!\nprint(math.sqrt(2))\nprint(math.tan(2))\nprint(math.atan(2))\n```\n\n    1.4142135623730951\n    -2.185039863261519\n    1.1071487177940904\n\n\n\n```python\n# Kimenet el is rejthet\u0151 a ; seg\u00edts\u00e9g\u00e9vel (\"suppress output\")\n1+1;\n```\n\nAmennyiben sz\u00fcks\u00e9ges, defini\u00e1lhatunk mi is saj\u00e1t v\u00e1ltoz\u00f3kat az `=` jellel.  \nMegjegyz\u00e9s: a `=` \u00e9rt\u00e9kad\u00f3 f\u00fcggv\u00e9nynek nincs kimenete\n\n\n```python\na=2\nb=3\nc=4.0 # automatikus t\u00edpusad\u00e1s\n```\n\n\n```python\n(a+b*c)**a # a leg\u00e1ltal\u00e1nosabb t\u00edpus lesz a kimenet (int < float)\n```\n# Fontos, hogy igyekezz\u00fck ker\u00fclni v\u00e9dett v\u00e1ltoz\u00f3 neveket! ILYET NE!\nmath.sqrt = 1\nmath.sqrt(2)\n\n# KERNEL RESTART SZ\u00dcKS\u00c9GES\n**Ha v\u00e9letlen\u00fcl ilyet tesz\u00fcnk, akkor \u00e9rdemes \u00fajraind\u00edtani a *kernel* a fent l\u00e1that\u00f3 k\u00f6rk\u00f6r\u00f6s ny\u00edllal, vagy a *Kernel* $\\rightarrow$ *Restart* seg\u00edts\u00e9g\u00e9vel**\n\n## Saj\u00e1t f\u00fcggv\u00e9nyek <a id='Sajatfuggvenyek'></a>\n\nSzerkezet:\n```python\ndef function(*arguments):\n    instruction1\n    instruction2\n    ...\n    return result\n```\n\nA f\u00fcggv\u00e9ny al\u00e1 tartoz\u00f3 utas\u00edt\u00e1sokat tabul\u00e1toros beh\u00faz\u00e1ssal (indent) kell be\u00edrni (nincs `{}` z\u00e1r\u00f3jel, vagy `end`). A f\u00fcggv\u00e9ny neve ut\u00e1n j\u00f6nnek az argumentumok majd kett\u0151sponttal `:` jelezz\u00fck, hogy hol kezd\u0151dik a f\u00fcggv\u00e9ny.\n\n\n```python\ndef foo(x):\n    return 3*x\n\ndef bar(x,y):\n    a = x+y**2\n    return 2*a + 4\n```\n\n\n```python\nprint(foo(3))\nprint(foo(3.))\nprint(foo('sz\u00f6veg_'))\n\nprint(bar(3,4.))\n```\n\n    9\n    9.0\n    sz\u00f6veg_sz\u00f6veg_sz\u00f6veg_\n    42.0\n\n\nLehets\u00e9ges \u00fagynevezett anonim f\u00fcggv\u00e9nyeket (*anonymous function* vagy *lambda function*) is l\u00e9trehozni, amely gyors m\u00f3dja az egyszer\u0171, egysoros f\u00fcggv\u00e9nyek l\u00e9trehoz\u00e1s\u00e1ra:\n\n```python\nlambda arguments: instruction\n```\n\nEz ak\u00e1r egy v\u00e1ltoz\u00f3hoz is hozz\u00e1rendelhet\u0151, mint egy sz\u00e1m vagy string.\n\n\n```python\ndouble = lambda x : x*2\nmultiply = lambda x,y : x*y\n```\n\n\n```python\nprint(double(3))\nprint(multiply(10,3))\n```\n\n    6\n    30\n\n\n## List\u00e1k \u00e9s vez\u00e9rl\u00e9si szerkezetek (Control Flow) - csak a legfontosabbak <a id='Vezerlesiszerkezetek'></a>\n\n### List\u00e1k\n\n\n```python\nlista = [1,2,3,4,\"valami\",[1.0,4]]\n```\n\n\n```python\nprint(lista[0]) # lista 1. eleme\nprint(lista[3]) # lista 4. eleme\nprint(lista[-1]) # negat\u00edv sz\u00e1mokkal h\u00e1tulr\u00f3l indexelj\u00fck a list\u00e1t, \u00e9s (-1)-t\u0151l indul\nprint(lista[-2]) # lista utols\u00f3 el\u0151tti eleme\n```\n\n    1\n    4\n    [1.0, 4]\n    valami\n\n\n\n```python\nprint(lista[1:-1]) # egyszerre t\u00f6bb elem [inkluz\u00edv:exkl\u00faz\u00edv m\u00f3don]\nprint(lista[1:2]) # egyszerre t\u00f6bb elem [inkluz\u00edv:exkl\u00faz\u00edv m\u00f3don]\nprint(lista[2:]) # lista utols\u00f3 elem\u00e9t is figyelembe vessz\u00fck\n```\n\n    [2, 3, 4, 'valami']\n    [2]\n    [3, 4, 'valami', [1.0, 4]]\n\n\n\n```python\nlista = [2,3,64,89,1,4,9,0,1]\n\nlista.sort()\nlista\n```\n\n### if-then-else\n\n```python\nif condition:\n    instruction1\nelif condition2:\n    instruction2\nelse:\n    intsturction3\n```\n\n\n```python\na=4\nif a<=3:\n    print('\"a\" nem nagyobb, mint 3')\nelif a>=10:\n    print('\"a\" nem kisebb, mint 10')\nelse:\n    print('\"a\" nagyobb mint 3, de kisebb mint 10')\n```\n\n    \"a\" nagyobb mint 3, de kisebb mint 10\n\n\n### for ciklus (for loop)\n```python\nfor i in array:\n    instruction\n```\n\n\n```python\nfor i in range(3):\n    print(i)\n    \nprint()\n\nfor (i,elem) in enumerate(lista):\n    print('lista ',i,'. eleme: ',elem,sep='') # t\u00f6bb elem printel\u00e9se egyszerr, szepar\u00e1tor = ''\n\n```\n\n    0\n    1\n    2\n    \n    lista 0. eleme: 0\n    lista 1. eleme: 1\n    lista 2. eleme: 1\n    lista 3. eleme: 2\n    lista 4. eleme: 3\n    lista 5. eleme: 4\n    lista 6. eleme: 9\n    lista 7. eleme: 64\n    lista 8. eleme: 89\n\n\n## List\u00e1k gyors l\u00e9trehoz\u00e1sa (List comprehension)\n\n\n```python\nlista2 = [3*i**2 for i in range(2,5)] # range: 2,3,4\nlista2\n```\n\n\n```python\nrange(10000)\n```\n\n\n\n\n    range(0, 10000)\n\n\n\n\n```python\nlista3 = list(range(10))\nlista3\n```\n\n\n```python\nmyfun = lambda x: 3*x**2\n\nlista4 = [myfun(i) for i in range(2,10) if i%3 != 0] # ha i nem oszthat\u00f3 3-al\nlista4\n```\n\n# K\u00fcls\u0151 f\u00fcggv\u00e9nyk\u00f6nyvt\u00e1rak: <a id='Kulsofuggvenykonyvtarak'></a>\n\nA m\u00e9rn\u00f6ki gyakorlatban el\u0151fordul\u00f3 alapsz\u00e1m\u00edt\u00e1sokhoz 2 f\u0151 csomag import\u00e1l\u00e1sa aj\u00e1nlott:\n- `sympy`: szimbolikus sz\u00e1m\u00edt\u00e1sokhoz\n- `scipy`/`numpy`: numerikus sz\u00e1m\u00edt\u00e1sokhoz (pl m\u00e1trix algebra)\n- `matplotlib.pyplot`: F\u00fcggv\u00e9nyek \u00e1br\u00e1zol\u00e1sa\nA `module`-ok h\u00edv\u00e1sa az al\u00e1bbi m\u00f3dokon t\u00f6rt\u00e9nhet\n- `import` *`modulename`* : import\u00e1lja az adott `module`-t. Ekkor a `module`-ban l\u00e9v\u0151 f\u00fcggv\u00e9nyek h\u00edv\u00e1sa a `module.functionname(arguments)` seg\u00edts\u00e9g\u00e9vel t\u00f6rt\u00e9nik (Az *1_Alapok.ipynb*-ben l\u00e1thattunk erre p\u00e9ld\u00e1t a `math` `module` eset\u00e9ben).  \n- `import` *`modulename`* `as` *`alias`* : hasonl\u00f3 az el\u0151z\u0151h\u00f6z, de megv\u00e1lasztjuk, hogy milyen *alias*-k\u00e9nt hivatkozunk a `module`-unkra\n- `from` *`modulename`* ` import` *`function1, function2, ...`* : csak bizonyos f\u00fcggv\u00e9nyek import\u00e1l\u00e1sa (nem sz\u00fcks\u00e9ges a `module`-ra hivatkozni a f\u00fcggv\u00e9nyek h\u00edv\u00e1sa sor\u00e1n)\n- `from` *`modulename`* ` import *` : a `module` \u00f6sszes f\u00fcggv\u00e9ny\u00e9nek import\u00e1l\u00e1sa (nem sz\u00fcks\u00e9ges a `module`-ra hivatkozni a f\u00fcggv\u00e9nyek h\u00edv\u00e1sa sor\u00e1n)\n\n\n## Szimbolikus matematikai m\u0171veletek <a id='Szimbolikus'></a>\n\n\n```python\nimport math\nimport sympy as sp\nimport scipy as sc\nsp.init_printing()\n```\n\n\n```python\nF, m, a, b, c, x = sp.symbols(\"F m a b c x\")\n```\n\n\n```python\nF=m*a\n```\n\n\n```python\n(a,7)\n```\n\n\n```python\nF.subs(a,7)\n```\n\n\n```python\nF.subs([(a,7),(m,1.1)])\n```\n\n\n```python\n((a+b)**3).expand()\n```\n\n\n```python\n((a+b)**7 - (b+2*a)**3).expand()\n```\n\n\n```python\n(a**2+b**2+2*a*b).factor()\n```\n\n\n```python\nsp.factor(a**2+b**2+2*a*b)\n```\n\n\n```python\nsp.factor(b**3 + 3*a*b**2 + 3*a**2*b + a**3)\n```\n\n\n```python\na/b+c/b+7/b\n```\n\n\n```python\nsp.ratsimp(a/b+c/b+7/b)\n```\n\n\n```python\n(a/b+c/b+7/b).ratsimp()\n```\n\n\n```python\n(sp.sin(x)**2 + sp.cos(x)**2).simplify().expand()\n```\n\n\n```python\n(sp.cos(2*x)).expand()\n```\n\n\n```python\nsp.expand_trig(sp.cos(2*x))\n```\n\n\n```python\nimport scipy.constants\n```\n\n\n```python\nsc.constants.golden\n```\n\n\n```python\nmath.sqrt(-1+0j) # A math csomagban nincsenek implement\u00e1lva a komplex sz\u00e1mok!\n```\n\n\n```python\nsc.sqrt(-1+0j)\n```\n\n\n```python\nsp.limit(sp.sin(x)/x,x,0)\n```\n\n\nTaylor-sor megad\u00e1sa. Els\u0151 param\u00e9ter a f\u00fcggv\u00e9ny, m\u00e1sodik a v\u00e1ltoz\u00f3, harmadik az \u00e9rt\u00e9k ami k\u00f6r\u00fcl akarjuk a sort kifejteni, negyedik pedig a foksz\u00e1m:\n\n$$f\\left(x\\right) \\approx \\sum\\limits_{i=0}^{N} \\dfrac{\\left(x - x_0\\right)^i}{i!} \\left.\\dfrac{\\mathrm{d}^i f}{\\mathrm{d} x^i}\\right|_{x = x_0}$$\n\n\n```python\nsp.series(sp.sin(x),x,0,20)\n```\n\n### Deriv\u00e1l\u00e1s/Integr\u00e1l\u00e1s <a id='DerivalIntegral'></a>\n\n\n```python\na,\u0394t,x = sp.symbols('a,\u0394t,x')\n```\n\nDeriv\u00e1l\u00e1s\n\n\n```python\nsp.diff(sp.sin(x**3),x)\n```\n\nT\u00f6bbsz\u00f6ri deriv\u00e1l\u00e1s\n\n\n```python\nsp.diff(sp.sin(x**3),x,3)\n```\n\nIntegr\u00e1l\u00e1s\n\n\n```python\nsp.integrate(1/(1+x),x)\n```\n\nHat\u00e1rozott integr\u00e1l\n\n\n```python\nsp.integrate(1/(1+x),(x,1,2))\n```\n\n\n```python\na = sp.Symbol('a')\n```\n\n\n```python\nsp.integrate(1/(x**2 + a),x)\n```\n\nL\u00e1ncszab\u00e1lyt is ismeri a szoftver\n\n\n```python\ny = sp.Symbol('y')\ndef f(x):\n    return x**2\ndef g(y):\n    return sp.sin(y)\n```\n\n\n```python\nf(g(y))\n```\n\n\n```python\nsp.diff(f(g(y)),y)\n```\n\n\n```python\nsp.diff(g(f(x)),x)\n```\n\nSok esetben nem l\u00e9tezik z\u00e1rt alak\u00fa kifejez\u00e9s a hat\u00e1rozatlan integr\u00e1lhoz. Ebben az esetben haszn\u00e1lhatjuk a [numerikus integr\u00e1l\u00e1st](https://en.wikipedia.org/wiki/Numerical_integration) a hat\u00e1rozott integr\u00e1l sz\u00e1m\u00edt\u00e1s\u00e1hoz:\n\n\n```python\nsp.integrate(sp.sin(sp.cos(x)),x)\n```\n\n[numerikus int\u00e1gr\u00e1ls SymPy-vel](https://docs.sympy.org/latest/modules/integrals/integrals.html#numeric-integrals)\n\nnem trivi\u00e1lis\n\n## Vektor- \u00e9s m\u00e1trixsz\u00e1m\u00edt\u00e1sok *sympy*-ban <a id='SzimVektorMatrix'></a>\nKisebb m\u00e9retek eset\u00e9n, amelyek ak\u00e1r szimbolikus sz\u00e1mokat is tartalmaznak\n\n\n```python\nv1= sp.Matrix([2.,3.,4.]) # oszlopvektor\nv2= sp.Matrix([[3.,-2.,-7.]]) # sorvektor (m\u00e9g 1 sz\u00f6gletes z\u00e1r\u00f3jel)\nmx1 = sp.Matrix([[1.,2.,3.],[2.,0.,4.],[3.,4.,1.]])\nmx2 = sp.Matrix([[1.,2.,3.],[4.,5.,6.],[7.,8.,9.]])\nEM = sp.eye(3) # egys\u00e9gm\u00e1trix\n```\n\n\n```python\nv1\n```\n\n\n```python\nv2\n```\n\n\n```python\nv2.multiply(v1)\n```\n\n\n```python\nmx2.multiply(v1)\n```\n\n\n```python\nv2.multiply(mx2)\n```\n\n\n```python\nEM\n```\n\n\n```python\nEVs=mx1.eigenvals() # saj\u00e1t\u00e9rt\u00e9kek \u00e9s multiplicit\u00e1suk (racion\u00e1lis sz\u00e1mokkal)\n```\n\n\n```python\nmx1.eigenvals(rational=False) # saj\u00e1t\u00e9rt\u00e9kek numerikusan\n```\n\n\n```python\nlist(mx1.eigenvals(rational=False)) # saj\u00e1t\u00e9rt\u00e9kek numerikusan, listak\u00e9nt (multiplicit\u00e1s n\u00e9lk\u00fcl)\n```\n\n\n```python\nmx1.det() # mx1 determin\u00e1nsa\n```\n\n\n```python\nIx,Iy,Ixy = sp.symbols('Ix,Iy,Ixy')\nmxSP=sp.Matrix([[Ix,-Ixy],[-Ixy,Iy]])\ndisplay(mxSP)\n\nprint('\\n Saj\u00e1t\u00e9rt\u00e9kek, vektorok: \\n')\nmxSP.eigenvects()\n```\n\n\n```python\nev=mxSP.eigenvals()\n```\n\n\n```python\nmxSP=sp.Matrix([[Ix,0,0],[0,Ix,0],[0,0,Iy]])\ndisplay(mxSP)\n\nprint('\\n Saj\u00e1t\u00e9rt\u00e9kek, vektorok: \\n')\nmxSP.eigenvects()\n```\n\n## Vektor- \u00e9s m\u00e1trixsz\u00e1m\u00edt\u00e1sok *numpy*-ban  <a id='NumVektorMatrix'></a>\nNagy m\u00e1trixok \u00e9s vektorok eset\u00e9n \u00e9rdemes ezt haszn\u00e1lni, vagy ha sok numerikus adattal dolgozik az ember. Tov\u00e1bb\u00e1 a saj\u00e1t\u00e9rt\u00e9k-saj\u00e1tvektor sz\u00e1m\u00edt\u00e1sok is jobban megoldott ebben a csomagban\n\n\n```python\nimport sympy as sp\nimport numpy as np\nimport numpy.linalg\n```\n\n\n```python\nv1= np.array([2.,3.,4.])\nv2= np.array([3.,-2.,-7.])\nmx1 = np.array([[1.,2.,3.],[2.,0.,4.],[3.,4.,1.]])\nmx2 = np.array([[1.,2.,3.],[4.,5.,6.],[7.,8.,9.]])\n```\n\n\n```python\nprint( np.dot(mx2,v1) )  # skal\u00e1r szorat mx2*v1\nprint( np.dot(v1,mx2) )  # skal\u00e1r szorat transpose(v1)*mx2\nprint( np.cross(v1,v2) ) # keresztszorzat v1\u00d7v2\n```\n\n    [20. 47. 74.]\n    [42. 51. 60.]\n    [-13.  26. -13.]\n\n\n\n```python\n(\u03bb,V) = np.linalg.eig(mx1) # M\u00e1trix saj\u00e1t\u00e9rt\u00e9kei, saj\u00e1tvektorai a \u03bb \u00e9s a V v\u00e1ltoz\u00f3kban\n\n# ki\u00edrat\u00e1s 2 \u00e9rt\u00e9kes tizedes jeggyel \u00e9s for ciklusra p\u00e9lda\nfor (i,v) in enumerate(V):\n    print(i+1, '. saj\u00e1t\u00e9rt\u00e9k \u00e9s -vektor:',sep='')\n    print('\u03bb = ', sp.N(\u03bb[i],3), '; v = ', [sp.N(e,3) for e in v], sep='', end='\\n\\n')\n```\n\n    1. saj\u00e1t\u00e9rt\u00e9k \u00e9s -vektor:\n    \u03bb = 6.76; v = [0.529, 0.834, -0.157]\n    \n    2. saj\u00e1t\u00e9rt\u00e9k \u00e9s -vektor:\n    \u03bb = -1.15; v = [0.543, -0.475, -0.693]\n    \n    3. saj\u00e1t\u00e9rt\u00e9k \u00e9s -vektor:\n    \u03bb = -3.61; v = [0.653, -0.281, 0.704]\n    \n\n\nFigyelj\u00fck meg, hogy a numpy a saj\u00e1tvektorokat 1 hossz\u00fare norm\u00e1lja!\n\n## Egyenletek megold\u00e1sa  <a id='Egyenletek'></a>\n\n\n```python\nx, y, z = sp.symbols(\"x y z\")\n```\n\n\n```python\negy1=77*x+6 - 160\n```\n\n\n```python\nsp.solve(egy1,x)\n```\n\n\n```python\nsp.solve(x**2 - 5, x)\n```\n\n\n```python\nx\n```\n\n\n```python\ne1 = 3*z + 2*y + 1*x - 7\ne2 = 4*z + 0*y + 2*x - 8\ne3 = 1*z + 4*y + 3*x - 9\n```\n\n\n```python\nsp.solve([e1,e2,e3],[x,y,z])\n```\n\n\n```python\ndef f(x):\n    return x**2 - 4\n```\n\n\n```python\n# Numerikus gy\u00f6kkeres\u00e9ssel scipy seg\u00edts\u00e9g\u00e9vel\nfrom scipy import optimize\n\ngyok = optimize.brentq(f,0,10)\nprint(gyok)\n```\n\n    2.0\n\n\n### Szimbolikus f\u00fcggv\u00e9nyekb\u0151l numerikus f\u00fcggv\u00e9nyek <a id='SymToNum'></a>\n\nEzt a legegyszer\u0171bben [*lambda function*](#Sajatfuggvenyek)-\u00f6k seg\u00edts\u00e9g\u00e9vel tehetj\u00fck meg, de van m\u00e1s m\u00f3d is r\u00e1: [l\u00e1sd ezt az \u00f6sszefoglal\u00f3t](https://docs.sympy.org/latest/modules/numeric-computation.html).\n\n\n```python\na,b,c,x = sp.symbols('a,b,c,x')\nadat = [(a, 3.0), (b,-2.), (c,1.0)]\n\nmasodfoku_x = a*x**2 + b*x + c\n\nmasodfoku_x\n```\n\n\n```python\nmasodfoku_num = sp.lambdify(x,masodfoku_x.subs(adat))\nmasodfoku_num(1.)\n```\n\n# Egyszer\u0171 \u00e1br\u00e1k k\u00e9sz\u00edt\u00e9se  <a id='Egyszeruabrak'></a>\n\n\n```python\nimport numpy as np # Ez egyszer\u0171s\u00edti a sok f\u00fcggv\u00e9nnyel val\u00f3 munk\u00e1t\nimport matplotlib.pyplot as plt # matplotlib csomag python rajzol\u00f3j\u00e1nak beh\u00edv\u00e1sa\n```\n\n## F\u00fcggv\u00e9nyek \u00e1br\u00e1zol\u00e1sa egyszer\u0171 diagramokon\n\n\n```python\ndef f(x):\n    return np.sin(x)*(1-4*np.exp(0.7*x)/(x**3))\n\nx1 = np.linspace(2,10,30)\ny1 = f(x1)\n```\n\n\n```python\nplt.figure(figsize=(20/2.54,12/2.54)) #inch-ben lehet megadni az \u00e1bra m\u00e9ret\u00e9t - nem k\u00f6telez\u0151 de \u00e9rdemes, ha dokument\u00e1ci\u00f3ba sz\u00e1njuk\n\n#plot objektum l\u00e9trehoz\u00e1sa\nplt.plot(x1,y1)\n\n# tengelyfeliratok\nplt.xlabel('x',fontsize=12)\nplt.ylabel('f(x)',fontsize=12)\n\n# r\u00e1csoz\u00e1s\nplt.grid()\n\n# \u00e1bra ment\u00e9s (m\u00e9g azel\u0151tt kell, miel\u0151tt kirajzolunk)\n# plt.savefig(\"abra1.png\", bbox_inches=\"tight\") \n# plt.savefig(\"abra1.pdf\", bbox_inches=\"tight\")\n\n# plot kirajzol\u00e1sa\n# plt.show()\n\n# plot ment\u00e9se\nplt.savefig('abra1.png')  # lehet .pdf, .svg form\u00e1tumokban is menteni\n```\n\n\n```python\nplt.plot(x1,y1,linewidth=3,color='k',linestyle='-.') # vonalvastags\u00e1g, -sz\u00edn, \u00e9s -st\u00edlus m\u00f3dos\u00edt\u00e1sa\nplt.xlabel('x')\nplt.ylabel('f(x)')\n# megjelen\u00edt\u00e9si hat\u00e1r\nplt.ylim(-0.5,0.5) #-0.5...0.5\nplt.xlim(None,8) # xmin...8\nplt.grid()\n \nplt.show()\n```\n\n\n```python\ndef g(x):\n    return np.sqrt(x)\ndef h(x):\n    return x**2\n\nx2 = np.linspace(0.,1.,100) \n\nplt.plot(x2,g(x2))\nplt.plot(x2,h(x2))\n\nplt.xlabel('x',fontsize=12)\n# felirat\nplt.legend((r'$\\sqrt{x}$',r'$x^2$'), fontsize=12, loc = 5) # loc: 1:jobbfenn, 2: balfent, 3:ballent,...10\nplt.grid()\n\n\nplt.show()\n```\n\n\n```python\nx3 = np.arange(1,14+1)\ny3 = np.exp(x3)/(1.4e4)\nplt.plot(x3, y3, linestyle = '', marker = 'o')\nplt.xlabel('szorgalmi h\u00e9t sorsz\u00e1ma')\nplt.ylabel('hallgat\u00f3k terhelts\u00e9ge [%]-ban')\nplt.grid()\nplt.show()\n```\n\n\n```python\nplt.plot(x3, y3, linestyle = '-', marker = 'o')\nplt.yscale('log')\nplt.xlabel('szorgalmi h\u00e9t sorsz\u00e1ma')\nplt.ylabel(r'hallgat\u00f3k terhelts\u00e9ge [%]-ban')\nplt.grid()\nplt.show()\n```\n\n## Parametrikus f\u00fcggv\u00e9ny\u00e1br\u00e1zol\u00e1s:\n\n\n```python\nt = np.linspace(0,2*sc.pi,100)\nx = np.sin(t)\ny = np.cos(t)\n\nplt.plot(x, y, linestyle = '--')\nplt.grid()\nplt.axis('equal')\nplt.show()\n```\n\n## 3D f\u00fcggv\u00e9ny\u00e1br\u00e1zol\u00e1s\n\n\n```python\nfrom mpl_toolkits.mplot3d import Axes3D\n```\n\n\n```python\ndef f(x, y):\n    return np.sin(np.exp( - x ** 2 - y ** 2))\n\nx = np.linspace(-2, 2, 30)\ny = np.linspace(-2, 2, 30)\n\nX, Y = np.meshgrid(x, y)\nZ = f(X, Y)\n```\n\n\n```python\nfig = plt.figure(figsize=(16/2.54,10/2.54)) # itt manu\u00e1lisan l\u00e9tre kell hozni a plot (figure) objektumot\nax = fig.add_subplot(111, projection='3d')\nax.plot_surface(X, Y, Z, cmap='viridis')\nplt.show()\n```\n\n## + Oszt\u00e1lyok <a id='Osztalyok'></a>\n\n\n```python\ndef foo(x):\n    return x**2\n\nclass MyClass:\n    def __init__(self,x,y,z):\n        self.square = foo(x)-z\n        self.cubic = y**3+foo(y)\n\n    @classmethod\n    def createfrom_x(cls,x):\n        return MyClass(x,x,x)\n    \n    def return_stuff(self):\n        return self.square+3*self.cubic\n```\n\n\n```python\nmcl=MyClass.createfrom_x(2)\n```\n", "meta": {"hexsha": "1d60e5e16aef2b2475d00d8efbd9af57ac349fbf", "size": 360076, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Python_Bevezeto.ipynb", "max_stars_repo_name": "HTSykora/Python_Bevezeto", "max_stars_repo_head_hexsha": "c1d7dde5001d6218d0b4f6e53f304fb928fa92db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-01T17:31:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-01T17:31:09.000Z", "max_issues_repo_path": "Python_Bevezeto.ipynb", "max_issues_repo_name": "HTSykora/Python_Bevezeto", "max_issues_repo_head_hexsha": "c1d7dde5001d6218d0b4f6e53f304fb928fa92db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python_Bevezeto.ipynb", "max_forks_repo_name": "HTSykora/Python_Bevezeto", "max_forks_repo_head_hexsha": "c1d7dde5001d6218d0b4f6e53f304fb928fa92db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 106.4998521148, "max_line_length": 73628, "alphanum_fraction": 0.8593630234, "converted": true, "num_tokens": 7555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297238231752, "lm_q2_score": 0.17328820379459514, "lm_q1q2_score": 0.04767673565182106}}
{"text": "# [Paris Saclay Center for Data Science](http://www.datascience-paris-saclay.fr)\n\n## [RAMP](https://www.ramp.studio/problems/sea_ice) on arctic sea ice prediction\n\n_Bal\u00e1zs K\u00e9gl (CNRS), Camille Marini (CNRS), Andy Rhines (UW), Jennifer Dy (NEU), Arindam Banerjee (UMN)_\n\n## Introduction\n\nArctic sea ice cover is one of the most variable features of Earth's climate. Its annual cycle peaks at around 15 million square kilometers in early spring, melting back to a minimum of about 6 million square kilometers in September. These seasonal swings are important for Earth's energy balance, as ice reflects the majority of sunlight while open water absorbs it. Changes in ice cover are also important for marine life and navigation for shipping.\n\n\n\nIn recent years, Arctic sea ice cover has declined rapidly, particularly during the September minimum. These changes have outpaced the predictions of climate models, and forecasting extent remains a formidable challenge. Typically, skillful predictions are limited to ~2-5 months in advance [Stroeve, et al. \"Improving Predictions of Arctic Sea Ice Extent\"](https://eos.org/features/improving-predictions-of-arctic-sea-ice-extent), while idealized experiments suggest that predictions up to two years in advance should be possible [Guemas et al., 2014](http://onlinelibrary.wiley.com/doi/10.1002/qj.2401/abstract).\n\n\n\nBetter tools to predict ice cover are critical for seasonal and regional climate prediction, and would thus address grand challenges in the study of climate change ([World Climate Research Programme: Grand Challenges, 2013](http://wcrp-climate.org/grand-challenges)).\n\n\n## The CCSM4 simulator\n\nAs a surrogate for observational data, we will use output from a 1300 year simulation using the NCAR [CCSM4.0](http://www.cesm.ucar.edu/models/ccsm4.0) climate model. The model was run in fully-coupled mode with interactive ocean, atmosphere, and sea ice. The simulation was also performed in an idealized \"Pre-Industrial\" mode, where greenhouse gas concentrations and other external forcings are held fixed to 1850 levels. This allows us to access a  stationary climate over a 1000+ year period, which makes the evaluation of the predictor more robust than if we used real measurements that are both non-stationary and limited to several decades.\n\n## The data\n\nThe data is a time series of \"images\" $z_t$, consisting of different physical variables on a regular grid on the Earth, indexed by lon(gitude) and lat(itude) coordinates. The variables we have made available are: \n* `ice_area`: the Northern Hemisphere sea ice area, in millions of squared kilometers.\n* `ts`: surface temperature, most important over the oceans which have a very high heat capacity.\n* `taux`: zonal (x-direction) surface wind stress. This is the frictional effect of winds on the sea surface and sea ice.\n* `tauy`: meridional (y-direction) surface wind stress.\n* `ps`: surface pressure.\n* `psl`: equivalent sea-level surface pressure. This corrects ps for the effects of topography, though the two should be very similar.\n* `shflx`: Surface sensible heat flux, the amount of heat transferred from the surface to the atmosphere.\n* `cldtot`: Total cloud cover (fractional), which has strong effects on radiative energy balance at the surface.\n\nThe fields are recorded every month for 1300 years, giving 15,600 time points. The goal is to predict the Northern Hemisphere sea ice area <span style=\"color:red\">4 months ahead</span>. \n\n## The prediction task\n\nThe pipeline will consists of a time series feature extractor and a predictor. Since the task is regression, the predictor will be a regressor, and the score (to minimize) will be the [root mean square error](http://en.wikipedia.org/wiki/Root-mean-square_deviation). The feature extractor will have access to the whole data. It will construct a \"classical\" feature matrix where each row corresponds to a time point. You should collect all information into these features that you find relevant to the regressor. The feature extractor can take <span style=\"color:red\">anything from the past</span>, that is, it will implement a function $x_t = g(z_1, \\ldots, z_t)$. Since you will have access to the full data, in theory you can cheat (even inadvertently) by using information from the future. We have implemented a randomized test to find such \"bugs\", but please do your best to avoid this since it would make the results irrelevant.\n\n## Domain-knowledge suggestions\n\nYou are of course free to explore any regression technique to improve the prediction. Since the input dimension is relatively large (2000+ dimensions per time point even after subsampling) sparse regression techniques (eg. LASSO) may be the best way to go, but this is just an a priori suggestion. The following list provides you other hints to start with, based on domain knowledge. \n* Some of the predictors will be very non-Gaussian.  \n* Teleconnections such as those associated with El Nino can be very important, so do not restrict your attention to variables in the Arctic.\n\n# Exploratory data analysis\n\nPackages to install:\n\nconda install xarray dask netCDF4 basemap<BR>\n\n\n```python\n%matplotlib inline\nfrom mpl_toolkits.basemap import Basemap\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\n```\n\nLet's start by reading the data into an xarray Dataset object. You can find all information on how to access and manipulate `Dataset` and `DataArray` objects at the [xarray site](http://xray.readthedocs.org/en/stable).\n\n\n```python\nX_ds = xr.open_dataset('data/train.nc')\ny_array = np.load('data/train.npy') \n```\n\n[`xarray`](http://xarray.pydata.org/en/stable/time-series.html) uses `datetime64[ns]` as a time type which means that dates must be between 1678 and 2262. We convert whatever time type we have into `datetime64[ns]` starting at 1700. This only works if the monthly time series has length less than 562 years, which is the case of all train and test times series, both in the starting kit and in the backend. This is important so that, e.g., grouping by month works correctly.\n\n\n```python\nX_ds['time'] = pd.date_range(\n    '1/1/1700', periods=X_ds['time'].shape[0], freq='M')\\\n    - np.timedelta64(15, 'D')\n```\n\nPrinting it, you can see that it contains all the data, indices, and other metadata.\n\n\n```python\nX_ds\n```\n\n\n\n\n    <xarray.Dataset>\n    Dimensions:   (lat: 39, lon: 58, time: 1800)\n    Coordinates:\n      * time      (time) datetime64[ns] 1700-01-16 1700-02-13 1700-03-16 ...\n      * lat       (lat) float64 -90.0 -85.29 -80.58 -75.86 -71.15 -66.44 -61.73 ...\n      * lon       (lon) float64 0.0 6.25 12.5 18.75 25.0 31.25 37.5 43.75 50.0 ...\n    Data variables:\n        ice_area  (time) float64 14.06 14.87 14.84 13.89 12.31 10.41 8.343 6.773 ...\n        ts        (time, lat, lon) float32 245.185 245.122 245.106 245.114 ...\n        taux      (time, lat, lon) float32 0.0119357 0.00967538 0.00755875 ...\n        tauy      (time, lat, lon) float32 0.0177472 0.0183095 0.0190735 ...\n        ps        (time, lat, lon) float32 69120.7 69120.7 69120.7 69120.7 ...\n        psl       (time, lat, lon) float32 100224.0 100224.0 100224.0 100224.0 ...\n        shflx     (time, lat, lon) float32 -1.9265 -2.07657 -2.13199 -2.11077 ...\n        cldtot    (time, lat, lon) float32 0.217556 0.217556 0.217556 0.217556 ...\n    Attributes:\n        n_burn_in:    120\n        n_lookahead:  4\n\n\n\n`y_array` on the disk is already shifted by `n_lookahead = 4` months. `n_burn_in = 120` (months) is the length of the prefix for which no prediction is required. If your feature extractor only uses these ten years of the past to extract features from, you don't need to worry about missing data in the beginning of the sequence. Otherwise you should take care of the issue \"manually\" (handling missing data in the beginning of the sequence).\n\n\n```python\ny_array, y_array.shape\n```\n\n\n\n\n    (array([ 12.31275082,  10.41492558,   8.34265137, ...,  15.05521202,\n             15.12392712,  14.23954105]), (1800,))\n\n\n\nPast ice area is also part of the input, here you should be extremely careful not using it in the future.\n\n\n```python\nX_ds['ice_area']\n```\n\n\n\n\n    <xarray.DataArray 'ice_area' (time: 1800)>\n    array([ 14.056189,  14.867679,  14.841535, ...,   8.755171,  10.52556 ,\n            12.80698 ])\n    Coordinates:\n      * time     (time) datetime64[ns] 1700-01-16 1700-02-13 1700-03-16 ...\n    Attributes:\n        units:      M km^2\n        long_name:  Northern hemisphere sea ice area\n\n\n\nLet's plot all spatiotemporal input at a certain time point. Time is measured in number of month after the first point which represents a January.\n\n\n```python\ndef plot_map(map_xr, time_index):\n\n    lons, lats = np.meshgrid(map_xr['lon'], map_xr['lat'])\n\n    fig = plt.figure()\n    ax = fig.add_axes([0.05, 0.05, 0.9,0.9])\n    map = Basemap(llcrnrlon=0, llcrnrlat=-89, urcrnrlon=360, urcrnrlat=89, projection='mill')\n    # draw coastlines, country boundaries, fill continents.\n    map.drawcoastlines(linewidth=0.25)\n    #map.drawcountries(linewidth=0.25)\n    #map.fillcontinents(color='coral',lake_color='aqua')\n    # draw the edge of the map projection region (the projection limb)\n    #map.drawmapboundary(fill_color='aqua')\n    ax.set_title(map_xr.attrs['long_name'] + ' at month ' + str(time_index))\n    im = map.pcolormesh(lons, lats, map_xr[time_index],\n                        shading='flat', cmap=plt.cm.jet, latlon=True)\n    cb = map.colorbar(im,\"bottom\", size=\"5%\", pad=\"2%\")\n\n    #plt.savefig(\"test_plot.pdf\")\n    plt.show()\n```\n\n\n```python\nt = 126\nplot_map(X_ds['ts'], t)\nplot_map(X_ds['taux'], t)\nplot_map(X_ds['tauy'], t)\nplot_map(X_ds['ps'], t)\nplot_map(X_ds['psl'], t)\nplot_map(X_ds['shflx'], t)\nplot_map(X_ds['cldtot'], t)\n```\n\n## The target.\n\nThe size of the Northern hemisphere sea ice area in million square kilometers, shifted by 4 months. Note that this variable is also part of the input (see above), shifted back so it is aligned with the other variables.\n\n\n```python\nfig = plt.figure(figsize=(16, 12))\nax = fig.add_subplot(2, 1, 1)\nax.set_xlabel('time [months]')\nax.set_ylabel('ice area [M km^2]')\nax.plot(X_ds['time'], y_array)\n\nax = fig.add_subplot(2, 1, 2)\nax.set_xlabel('time [months]')\nax.set_ylabel('ice area [M km^2]')\nax.plot(X_ds['time'][:120], y_array[:120])\n```\n\nYou can index xarray.DataArrays similarly to  <code>pandas</code> dataframes or <code>numpy</code> array. The result is always a <coda>DataArray</code>\n\n\n```python\nt = 123\nlat = 13\nlon = 29\n```\n\n\n```python\nX_ds['ice_area'][t]\n```\n\n\n\n\n    <xarray.DataArray 'ice_area' ()>\n    array(15.104208946228027)\n    Coordinates:\n        time     datetime64[ns] 1710-04-15\n    Attributes:\n        units:      M km^2\n        long_name:  Northern hemisphere sea ice area\n\n\n\n\n```python\nX_ds['ts'][t, lat]\n```\n\n\n\n\n    <xarray.DataArray 'ts' (lon: 58)>\n    array([ 295.595917,  295.077911,  294.459259,  294.784088,  288.778809,\n            291.563965,  298.488068,  297.634125,  297.555206,  297.538452,\n            296.985779,  296.336151,  295.854889,  295.928864,  295.802582,\n            295.874908,  295.745728,  295.77179 ,  296.79306 ,  292.079071,\n            291.610535,  292.217377,  293.144531,  293.365082,  291.763672,\n            297.667328,  296.720337,  296.548737,  296.528229,  296.442993,\n            296.600342,  296.626129,  296.825836,  296.636566,  296.6008  ,\n            296.299835,  296.133545,  296.138336,  296.254242,  296.246155,\n            296.207275,  296.272217,  296.061768,  295.639862,  294.837006,\n            293.281128,  292.998108,  291.669067,  295.59549 ,  293.546875,\n            298.870697,  298.631134,  298.164978,  297.651123,  297.691742,\n            297.313721,  296.688385,  296.033234], dtype=float32)\n    Coordinates:\n        time     datetime64[ns] 1710-04-15\n        lat      float64 -28.74\n      * lon      (lon) float64 0.0 6.25 12.5 18.75 25.0 31.25 37.5 43.75 50.0 ...\n    Attributes:\n        units:      K\n        long_name:  Surface temperature (radiative)\n\n\n\nYou can convert any of these objects into a <code>numpy</code> array.\n\n\n```python\nX_ds['taux'].values\n```\n\n\n\n\n    array([[[  1.19356960e-02,   9.67537798e-03,   7.55875325e-03, ...,\n               1.18619325e-02,   1.09429900e-02,   1.22338524e-02],\n            [  4.41878587e-02,   3.38704921e-02,   3.16834785e-02, ...,\n               6.33927882e-02,   5.51564693e-02,   4.85668816e-02],\n            [  1.48713449e-02,   9.71391704e-03,   4.09940118e-03, ...,\n               1.94972251e-02,   2.16817427e-02,   1.50534194e-02],\n            ..., \n            [  1.01837456e-01,   1.47577509e-01,   1.52642533e-01, ...,\n              -7.09521398e-02,   2.52995710e-03,   5.99600412e-02],\n            [  5.67872338e-02,   7.03624263e-02,   7.88953975e-02, ...,\n               1.72229647e-03,   2.38575265e-02,   4.71802503e-02],\n            [  7.66299218e-02,   7.68604428e-02,   7.69598857e-02, ...,\n               7.20449910e-02,   7.48636052e-02,   7.62343481e-02]],\n    \n           [[  1.01154828e-02,   7.53489835e-03,   5.28584421e-03, ...,\n               1.24596599e-02,   1.10400580e-02,   1.09038418e-02],\n            [  2.70372722e-02,   1.82139259e-02,   1.79223008e-02, ...,\n               5.91841228e-02,   4.45516631e-02,   3.35663259e-02],\n            [  4.56722127e-03,  -2.30912329e-03,  -9.04263649e-03, ...,\n               2.78667603e-02,   1.72966793e-02,   6.57241791e-03],\n            ..., \n            [  5.28127234e-03,   4.60262671e-02,   6.41433075e-02, ...,\n              -1.09132707e-01,  -5.37769273e-02,  -2.30879579e-02],\n            [ -8.29386618e-03,   1.45339733e-02,   3.09309326e-02, ...,\n              -8.90958011e-02,  -5.65651134e-02,  -2.34235488e-02],\n            [  3.85780595e-02,   4.43213768e-02,   4.99319695e-02, ...,\n               2.18626168e-02,   2.95717269e-02,   3.52127962e-02]],\n    \n           [[  2.55916659e-02,   1.99487675e-02,   1.43996347e-02, ...,\n               3.68869901e-02,   3.23505215e-02,   2.84630582e-02],\n            [  9.83300284e-02,   7.80353844e-02,   6.21962585e-02, ...,\n               1.62167504e-01,   1.39628366e-01,   1.13649629e-01],\n            [  3.45649421e-02,   2.15536896e-02,   1.08636040e-02, ...,\n               9.53203440e-02,   7.13457614e-02,   4.08168472e-02],\n            ..., \n            [ -2.83647515e-02,  -1.96722839e-02,  -1.37594007e-02, ...,\n              -5.89759722e-02,  -3.41217369e-02,  -3.00275870e-02],\n            [ -4.84686829e-02,  -3.73680145e-02,  -2.88465489e-02, ...,\n              -8.75075683e-02,  -7.00048655e-02,  -5.63468076e-02],\n            [  2.95577268e-03,   6.18538586e-03,   1.02356179e-02, ...,\n              -6.64883293e-03,  -1.62067183e-03,   1.17990072e-03]],\n    \n           ..., \n           [[  6.74928492e-03,   1.85473484e-03,  -3.03047406e-03, ...,\n               1.85889266e-02,   1.40439617e-02,   9.40556638e-03],\n            [  7.77858123e-02,   5.81281073e-02,   4.27184254e-02, ...,\n               1.29711390e-01,   1.13835961e-01,   9.15294886e-02],\n            [  1.81257632e-02,   3.50347464e-03,  -5.48585318e-03, ...,\n               8.80435035e-02,   6.43973425e-02,   2.94387899e-02],\n            ..., \n            [  5.72110247e-03,   1.25772152e-02,   1.85365826e-02, ...,\n              -4.72116061e-02,  -1.54972300e-02,  -2.24906858e-03],\n            [  4.66008624e-03,   9.28835198e-03,   1.21561177e-02, ...,\n              -1.80840958e-02,  -6.93337247e-03,   1.96989882e-03],\n            [ -8.21887702e-03,  -8.70553963e-03,  -9.42833349e-03, ...,\n              -6.50860276e-03,  -7.33792223e-03,  -7.90224969e-03]],\n    \n           [[  1.49074309e-02,   1.23018445e-02,   9.19409469e-03, ...,\n               2.05269847e-02,   1.87849980e-02,   1.59909595e-02],\n            [  5.99069074e-02,   4.49056588e-02,   3.19231674e-02, ...,\n               9.68916565e-02,   8.56958330e-02,   6.94289878e-02],\n            [  1.72058698e-02,   8.28679837e-03,   1.70873804e-03, ...,\n               4.67530489e-02,   3.46728042e-02,   2.23747306e-02],\n            ..., \n            [ -3.31579112e-02,  -2.11932342e-02,  -1.32686114e-02, ...,\n              -9.69535708e-02,  -4.63003963e-02,  -3.86148356e-02],\n            [ -3.58242914e-02,  -1.93917193e-02,  -4.02707374e-03, ...,\n              -1.03789270e-01,  -7.26778209e-02,  -4.67620790e-02],\n            [  1.71900429e-02,   2.53514275e-02,   3.41531821e-02, ...,\n              -3.92140355e-03,   5.31466538e-03,   1.26504060e-02]],\n    \n           [[  2.19966136e-02,   2.03868262e-02,   1.76709872e-02, ...,\n               2.41104197e-02,   2.40787510e-02,   2.15190146e-02],\n            [  3.91389951e-02,   3.04511730e-02,   2.07490362e-02, ...,\n               5.02797216e-02,   5.13844006e-02,   4.45303731e-02],\n            [ -1.92109519e-03,  -7.69918645e-03,  -1.27999941e-02, ...,\n               1.12321945e-02,   5.19877812e-03,  -3.84666018e-05],\n            ..., \n            [  5.34604490e-02,   8.14611837e-02,   1.08710922e-01, ...,\n              -2.82678455e-02,   1.20118940e-02,   3.67381312e-02],\n            [ -4.74150642e-04,   3.57131270e-04,   1.99886650e-04, ...,\n              -1.69663932e-02,  -8.53663310e-03,  -2.25929567e-03],\n            [  1.48056466e-02,   1.55802239e-02,   1.66975856e-02, ...,\n               1.25958174e-02,   1.38717657e-02,   1.44341793e-02]]], dtype=float32)\n\n\n\nYou can also use slices, and slice bounds don't even have to be in the index arrays.\n\n\n```python\nX_ds['tauy'][12].loc[10:50]\n```\n\n\n\n\n    <xarray.DataArray 'tauy' (lat: 8, lon: 58)>\n    array([[ 0.049768,  0.046843,  0.095759, ...,  0.038427,  0.029995,  0.046069],\n           [ 0.01939 ,  0.041139,  0.039579, ...,  0.032233,  0.034647,  0.035988],\n           [ 0.023434,  0.00317 ,  0.037727, ...,  0.027224,  0.010083,  0.036892],\n           ..., \n           [-0.016391, -0.008304,  0.000831, ..., -0.053041, -0.041311, -0.039617],\n           [-0.026566, -0.027404, -0.060934, ..., -0.098736, -0.113015, -0.319821],\n           [-0.25397 , -0.374775, -0.134166, ..., -0.09506 , -0.117772, -0.080058]], dtype=float32)\n    Coordinates:\n        time     datetime64[ns] 1701-01-16\n      * lat      (lat) float64 13.66 18.38 23.09 27.8 32.51 37.23 41.94 46.65\n      * lon      (lon) float64 0.0 6.25 12.5 18.75 25.0 31.25 37.5 43.75 50.0 ...\n    Attributes:\n        units:      N/m2\n        long_name:  Meridional surface stress\n\n\n\n\n```python\nX_ds.isel(time=t)\n```\n\n\n\n\n    <xarray.Dataset>\n    Dimensions:   (lat: 39, lon: 58)\n    Coordinates:\n        time      datetime64[ns] 1710-04-15\n      * lat       (lat) float64 -90.0 -85.29 -80.58 -75.86 -71.15 -66.44 -61.73 ...\n      * lon       (lon) float64 0.0 6.25 12.5 18.75 25.0 31.25 37.5 43.75 50.0 ...\n    Data variables:\n        ice_area  float64 15.1\n        ts        (lat, lon) float32 221.286 221.266 221.285 221.287 221.273 ...\n        taux      (lat, lon) float32 0.0259886 0.0205801 0.0151063 0.00936647 ...\n        tauy      (lat, lon) float32 0.0475492 0.0497843 0.0520096 0.0533593 ...\n        ps        (lat, lon) float32 68001.4 68001.4 68001.4 68001.4 68001.4 ...\n        psl       (lat, lon) float32 100270.0 100270.0 100270.0 100270.0 ...\n        shflx     (lat, lon) float32 -18.782 -18.8291 -18.7908 -18.7875 -18.8209 ...\n        cldtot    (lat, lon) float32 0.769741 0.769741 0.769741 0.769741 ...\n    Attributes:\n        n_burn_in:    120\n        n_lookahead:  4\n\n\n\n## The cross-validation object\n\nCross validating time-series predictors is tricky. We can't simply shuffle the observations $z_t =$ <code>X_ds['tas'][t]</code> since we would lose both causality and the correlation structure that follows natural order. \n\nTo formalize the issue, let us first define formally the predictor that we will produce in the RAMP. Let the time series be $z_1, \\ldots, z_T$ and the let target to predict at time $t$ be $y_t$. The target is usually (and in our case) a function of the future $z_{t+1}, \\ldots$, but it can be anything else. We want to learn a function that predicts $y$ from the past, that is\n\n\\begin{equation}\n\\hat{y}_t = f(z_1, ..., z_t) = f(Z_t)\n\\end{equation}\n\nwhere $Z_t = (z_1, ..., z_t)$ is the past. Now, the sample $(Z_t, y_t)$ is a regular (although none iid) sample from the point of view of shuffling, so we can train on $\\{Z_t, y_t\\}_{t \\in \\cal{I}_{\\text{train}}}$ and test on $(Z_t, y_t)_{t \\in \\cal{I}_{\\text{test}}}$, where $\\cal{I}_{\\text{train}}$ and $\\cal{I}_{\\text{test}}$ are arbitrary but disjunct train and test index sets, respectively (typically produced by sklearn's `ShuffleSplit`). Using shuffling would nevertheless allow a second order leakage from training points to test points that preceed them, by, e.g., aggregating the training set and adding the aggregate back as a feature. To avoid this, we use block-CV: on each fold, all $t \\in \\cal{I}_{\\text{test}}$ are larger than all $t \\in \\cal{I}_{\\text{train}}$. We also make sure that all training and test sets contain consecutive observations, so recurrent nets and similar predictors, which rely on this, may be trained.\n\nThe training algorithm thus maps $(Z_t, y_t)_{t \\in \\cal{I}_{\\text{train}}}$ to $f$. The point $Z_t$ contains the target for all training points $Z_{t'}$ for $t' \\le t - 4$, so it is technically possible to cheat: when you receive a test set $z_1, ..., z_T$, you could look up the target of $z_t$ in $z_{t+4}$. To detect this (often inadvertant) cheating, we will check that you feature extractor is invariant to the future. \n\nTo allow a reasonably long past before making the first prediction, we strip the first $b = 120$ months (burn-in). You can of course use a longer window in your feature extractor, but in this case you will have to handle the missing time points in the beginning of the sequence.\n\n## The pipeline\n\nWe have factorized the pipeline into two steps. The first feature extractor $g$ transforms the past into a classical feature vector $x_t = g(Z_t)$, and the classical regressor $h$ predicts the target from the feature vector $\\hat{y}_t = h(x_t)$. To summarize, the full predictor is a composition $f(Z_t) = h(g(Z_t))$. If you have a complex solution where this factorization does not make sense (e.g., RNNs), you can do all the work in the (optional) fit function of the feature extractor, send the prediction as a single feature $x_t$ to the regressor, and simply use an identity function in the regressor $\\hat{y}_t = x_t$.\n\n### The feature extractor\n\nThe feature extractor implements a single `transform` function. As we explained above, it receives the full `X_ds` including the burn-in period $b$ as an attribute. <font color='red'>It should produce a feature matrix of length $T - b$</font>, of type numpy array, representing the past vector $(Z_{t+b}, \\ldots, Z_{T})$. For constructing/computing $x_t$, it can only use the past $Z_t = (z_1, \\ldots, z_t) = $ `X_ds['tas'][:t]`.\n\nNote that the following code cells are *not* executed in the notebook. The notebook saves their contents in the file specified in the first line of the cell, so you can edit your submission before running the local test below and submitting it at the RAMP site.\n\n\n```python\n%%file submissions/starting_kit/ts_feature_extractor.py\nimport numpy as np\n\n\nclass FeatureExtractor(object):\n\n    def __init__(self):\n        pass\n\n    def transform(self, X_ds):\n        \"\"\"Compute the vector of input variables at time t.\n\n        Spatial variables will\n        be averaged along lat and lon coordinates.\n        \"\"\"\n        # This is the range for which features should be provided. Strip\n        # the burn-in from the beginning and the prediction look-ahead from\n        # the end.\n        valid_range = np.arange(X_ds.n_burn_in, len(X_ds['time']))\n        # We convert the Dataset into a 4D DataArray\n        X_xr = X_ds.to_array()\n        # We compute the mean over the lat and lon axes\n        mean_xr = np.mean(X_xr, axis=(2, 3))\n        # We convert it into numpy array, transpose, and slice the valid range\n        X_array = mean_xr.values.T[valid_range]\n        return X_array\n\n\n```\n\n    Overwriting submissions/starting_kit/ts_feature_extractor.py\n\n\n### The regressor\n\nThe regressor should implement a scikit-klearn-like regressor with fit and predict functions. The starting kit uses a linear model.\n\n\n```python\n%%file submissions/starting_kit/regressor.py\nfrom sklearn.base import BaseEstimator\nfrom sklearn import linear_model\n\n\nclass Regressor(BaseEstimator):\n    def __init__(self):\n        self.reg = linear_model.LinearRegression()\n\n    def fit(self, X, y):\n        self.reg.fit(X, y)\n\n    def predict(self, X):\n        return self.reg.predict(X)\n\n\n```\n\n    Overwriting submissions/starting_kit/regressor.py\n\n\n## Local testing (before submission)\n\nIt is <b><span style=\"color:red\">important that you test your submission files before submitting them</span></b>. For this we provide a unit test. Note that the test runs on your files in [`submissions/starting_kit`](/tree/submissions/starting_kit).\n\nFirst `pip install ramp-workflow` or install it from the [github repo](https://github.com/paris-saclay-cds/ramp-workflow). Make sure that the python files `ts_feature_extractor.py` and  `regressor.py` are in the  [`submissions/starting_kit`](/tree/submissions/starting_kit) folder, and the data `train.nc` and `test.nc` are in [`data`](/tree/data). Then run\n\n```ramp_test_submission```\n\nIf it runs and print training and test errors on each fold, then you can submit the code.\n\n\n```python\n!ramp_test_submission\n```\n\n    Testing Arctic sea ice forecast\n    Reading train and test files from ./data ...\n    Reading cv ...\n    length of common block: 912 months = 76 years\n    length of validation block: 768 months = 64 years\n    length of each cv block: 96 months = 8 years\n    Training ./submissions/starting_kit ...\n    CV fold 0\n    \ttrain rmse = 0.904\n    \tvalid rmse = 0.876\n    \ttest rmse = 0.996\n    CV fold 1\n    \ttrain rmse = 0.902\n    \tvalid rmse = 0.862\n    \ttest rmse = 0.978\n    CV fold 2\n    \ttrain rmse = 0.909\n    \tvalid rmse = 0.828\n    \ttest rmse = 0.962\n    CV fold 3\n    \ttrain rmse = 0.902\n    \tvalid rmse = 0.81\n    \ttest rmse = 0.964\n    CV fold 4\n    \ttrain rmse = 0.889\n    \tvalid rmse = 0.821\n    \ttest rmse = 0.964\n    CV fold 5\n    \ttrain rmse = 0.886\n    \tvalid rmse = 0.815\n    \ttest rmse = 0.969\n    CV fold 6\n    \ttrain rmse = 0.893\n    \tvalid rmse = 0.703\n    \ttest rmse = 0.964\n    CV fold 7\n    \ttrain rmse = 0.881\n    \tvalid rmse = 0.674\n    \ttest rmse = 0.958\n    ----------------------------\n    train rmse = 0.896 \u00b1 0.0093\n    valid rmse = 0.799 \u00b1 0.0675\n    test rmse = 0.97 \u00b1 0.0115\n    ----------------------------\n    Testing if the notebook can be converted to html\n    [NbConvertApp] Converting notebook ./sea_ice_starting_kit.ipynb to html\n    [NbConvertApp] Writing 866271 bytes to ./sea_ice_starting_kit.html\n\n\nAlternatively, load and execute `rampwf.utils.testing.py`, and call `assert_submission`. This may be useful if you would like to understand how we instantiate the workflow, the scores, the data connectors, and the cross validation scheme defined in [`problem.py`](problem.py), and how we insert and train/test your submission.\n\n\n```python\n# %load https://raw.githubusercontent.com/paris-saclay-cds/ramp-workflow/master/rampwf/utils/testing.py\n\n\"\"\"The :mod:`rampwf.utils.testing` submodule provide utils to test ramp-kits\"\"\"\nfrom __future__ import print_function\n\nimport imp\nfrom os.path import join, abspath\nfrom os import system\n\nimport numpy as np\n\n\ndef assert_read_problem(ramp_kit_dir='.'):\n    problem = imp.load_source('', join(ramp_kit_dir, 'problem.py'))\n    return problem\n\n\ndef assert_title(ramp_kit_dir='.'):\n    problem = assert_read_problem(ramp_kit_dir)\n    print('Testing {}'.format(problem.problem_title))\n\n\ndef assert_data(ramp_kit_dir='.', ramp_data_dir='.'):\n    problem = assert_read_problem(ramp_kit_dir)\n    print('Reading train and test files from {}/data ...'.format(\n        ramp_data_dir))\n    X_train, y_train = problem.get_train_data(path=ramp_data_dir)\n    X_test, y_test = problem.get_test_data(path=ramp_data_dir)\n    return X_train, y_train, X_test, y_test\n\n\ndef assert_cv(ramp_kit_dir='.', ramp_data_dir='.'):\n    problem = assert_read_problem(ramp_kit_dir)\n    X_train, y_train = problem.get_train_data(path=ramp_data_dir)\n    print('Reading cv ...')\n    cv = list(problem.get_cv(X_train, y_train))\n    return cv\n\n\ndef assert_score_types(ramp_kit_dir='.'):\n    problem = assert_read_problem(ramp_kit_dir)\n    score_types = problem.score_types\n    return score_types\n\n\ndef assert_submission(ramp_kit_dir='.', ramp_data_dir='.',\n                      submission='starting_kit'):\n    \"\"\"Helper to test a submission from a ramp-kit.\n\n    Parameters\n    ----------\n    ramp_kit_dir : str, (default='.')\n        The directory of the ramp-kit to be tested for submission.\n\n    ramp_data_dir : str, (default='.')\n        The directory of the data\n\n    submission_name : str, (default='starting_kit')\n        The name of the submission to be tested.\n\n    Returns\n    -------\n    None\n\n    \"\"\"\n    problem = assert_read_problem(ramp_kit_dir)\n    assert_title(ramp_kit_dir)\n    X_train, y_train, X_test, y_test = assert_data(ramp_kit_dir, ramp_data_dir)\n    cv = assert_cv(ramp_kit_dir, ramp_data_dir)\n    score_types = assert_score_types(ramp_kit_dir)\n    print('Training {}/submissions/{} ...'.format(\n        ramp_kit_dir, submission))\n    module_path = join(ramp_kit_dir, 'submissions', submission)\n    train_train_scoress = np.empty((len(cv), len(score_types)))\n    train_valid_scoress = np.empty((len(cv), len(score_types)))\n    test_scoress = np.empty((len(cv), len(score_types)))\n    for fold_i, (train_is, valid_is) in enumerate(cv):\n        trained_workflow = problem.workflow.train_submission(\n            module_path, X_train, y_train, train_is=train_is)\n\n        y_pred_train = problem.workflow.test_submission(\n            trained_workflow, X_train)\n        predictions_train_train = problem.Predictions(\n            y_pred=y_pred_train[train_is])\n        ground_truth_train_train = problem.Predictions(\n            y_true=y_train[train_is])\n        predictions_train_valid = problem.Predictions(\n            y_pred=y_pred_train[valid_is])\n        ground_truth_train_valid = problem.Predictions(\n            y_true=y_train[valid_is])\n\n        y_pred_test = problem.workflow.test_submission(\n            trained_workflow, X_test)\n        predictions_test = problem.Predictions(y_pred=y_pred_test)\n        ground_truth_test = problem.Predictions(y_true=y_test)\n\n        print('CV fold {}'.format(fold_i))\n        for score_type_i, score_type in enumerate(score_types):\n            score = score_type.score_function(\n                ground_truth_train_train, predictions_train_train)\n            train_train_scoress[fold_i, score_type_i] = score\n            print('\\ttrain {} = {}'.format(\n                score_type.name, round(score, score_type.precision)))\n\n            score = score_type.score_function(\n                ground_truth_train_valid, predictions_train_valid)\n            train_valid_scoress[fold_i, score_type_i] = score\n            print('\\tvalid {} = {}'.format(\n                score_type.name, round(score, score_type.precision)))\n\n            score = score_type.score_function(\n                ground_truth_test, predictions_test)\n            test_scoress[fold_i, score_type_i] = score\n            print('\\ttest {} = {}'.format(\n                score_type.name, round(score, score_type.precision)))\n\n    print('----------------------------')\n    means = train_train_scoress.mean(axis=0)\n    stds = train_train_scoress.std(axis=0)\n    for mean, std, score_type in zip(means, stds, score_types):\n        print('train {} = {} \u00b1 {}'.format(\n            score_type.name, round(mean, score_type.precision),\n            round(std, score_type.precision + 1)))\n\n    means = train_valid_scoress.mean(axis=0)\n    stds = train_valid_scoress.std(axis=0)\n    for mean, std, score_type in zip(means, stds, score_types):\n        print('valid {} = {} \u00b1 {}'.format(\n            score_type.name, round(mean, score_type.precision),\n            round(std, score_type.precision + 1)))\n\n    means = test_scoress.mean(axis=0)\n    stds = test_scoress.std(axis=0)\n    for mean, std, score_type in zip(means, stds, score_types):\n        print('test {} = {} \u00b1 {}'.format(\n            score_type.name, round(mean, score_type.precision),\n            round(std, score_type.precision + 1)))\n\n    print('----------------------------')\n    problem_name = abspath(ramp_kit_dir).split('/')[-1]\n    print('Testing if the notebook can be converted to html')\n    system('jupyter nbconvert --to html {}/{}_starting_kit.ipynb'.format(\n        ramp_kit_dir, problem_name))\n\n```\n\n\n```python\n# assert_submission()\n```\n\n## Submitting to [ramp.studio](http://ramp.studio)\n\nOnce you found a good model, you can submit it to [ramp.studio](http://www.ramp.studio). First, if it is your first time using RAMP, [sign up](http://www.ramp.studio/sign_up), otherwise [log in](http://www.ramp.studio/login). Then find an open event on the particular problem, for example, the event [sea ice colorado](https://www.ramp.studio/events/sea_ice_colorado) for this RAMP. Sign up for the event. Both signups are controled by RAMP administrators, so there **can be a delay between asking for signup and being able to submit**.\n\nOnce your signup request is accepted, you can go to your [sandbox](http://www.ramp.studio/events/sea_ice_colorado/sandbox) and copy-paste (or upload) [`ts_feature_extractor.py`](/edit/submissions/starting_kit/ts_feature_extractor.py) and [`regressor.py`](/edit/submissions/starting_kit/regressor.py) from `submissions/starting_kit`. Save it, rename it, then submit it. The submission is trained and tested on our backend in the same way as `ramp_test_submission` does it locally. While your submission is waiting in the queue and being trained, you can find it in the \"New submissions (pending training)\" table in [my submissions](http://www.ramp.studio/events/sea_ice_colorado/my_submissions). Once it is trained, you get a mail, and your submission shows up on the [public leaderboard](http://www.ramp.studio/events/sea_ice_colorado/leaderboard). \nIf there is an error (despite having tested your submission locally with `ramp_test_submission`), it will show up in the \"Failed submissions\" table in [my submissions](http://www.ramp.studio/events/sea_ice_colorado/my_submissions). You can click on the error to see part of the trace.\n\nAfter submission, do not forget to give credits to the previous submissions you reused or integrated into your submission.\n\nThe data set we use at the backend is usually different from what you find in the starting kit, so the score may be different.\n\nThe usual way to work with RAMP is to explore solutions, add feature transformations, select models, perhaps do some AutoML/hyperopt, etc., _locally_, and checking them with `ramp_test_submission`. The script prints mean cross-validation scores \n```\n----------------------------\ntrain rmse = 0.896 \u00b1 0.0093\nvalid rmse = 0.799 \u00b1 0.0675\ntest rmse = 0.97 \u00b1 0.0115\n```\nThe official score in this RAMP (the first score column after \"historical contributivity\" on the [leaderboard](http://www.ramp.studio/events/sea_ice_colorado/leaderboard)) is root mean squared error (\"rmse\"), so the line that is relevant in the output of `ramp_test_submission` is `valid rmse = 0.799 \u00b1 0.0675`. When the score is good enough, you can submit it at the RAMP.\n\n## Other models in the starting kit\n\nTo get you started, we made several other example submissions.\n\nThis one uses the whole set of fields at time $t$ as the feature vector. We also modify the regressor because of the large dimensional input.\n\n\n```python\n%%file submissions/whole_fields/ts_feature_extractor.py\nimport numpy as np\n\n\nclass FeatureExtractor(object):\n\n    def __init__(self):\n        pass\n\n    def transform(self, X_ds):\n        \"\"\"Compute the vector of input variables at time t.\n\n        Spatial variables will be concatenated.\n        \"\"\"\n        # This is the range for which features should be provided. Strip\n        # the burn-in from the beginning and the prediction look-ahead from\n        # the end.\n        valid_range = np.arange(X_ds.n_burn_in, len(X_ds['time']))\n        # We convert the Dataset into a 4D DataArray\n        X_xr = X_ds.to_array()\n        # We convert it into np array, put the t axis first\n        X_array_t_first = np.swapaxes(X_xr.values, 0, 1)\n        shape = X_array_t_first.shape\n        # We reshape it to create one vector per time step, and slice the\n        # valid range\n        X_array = X_array_t_first.reshape(\n            shape[0], shape[1] * shape[2] * shape[3])[valid_range]\n        return X_array\n\n\n```\n\n    Overwriting submissions/whole_fields/ts_feature_extractor.py\n\n\n\n```python\n%%file submissions/whole_fields/regressor.py\nfrom sklearn.base import BaseEstimator\nfrom sklearn import linear_model\n\n\nclass Regressor(BaseEstimator):\n    def __init__(self):\n        self.reg = linear_model.Lasso()\n\n    def fit(self, X, y):\n        self.reg.fit(X, y)\n\n    def predict(self, X):\n        return self.reg.predict(X)\n\n\n```\n\n    Overwriting submissions/whole_fields/regressor.py\n\n\nYou can test this by\n\n\n```python\n!ramp_test_submission --submission whole_fields\n```\n\n    Testing Arctic sea ice forecast\n    Reading train and test files from ./data ...\n    Reading cv ...\n    length of common block: 912 months = 76 years\n    length of validation block: 768 months = 64 years\n    length of each cv block: 96 months = 8 years\n    Training ./submissions/whole_fields ...\n    /Users/kegl/anaconda/lib/python2.7/site-packages/sklearn/linear_model/coordinate_descent.py:484: ConvergenceWarning: Objective did not converge. You might want to increase the number of iterations. Fitting data with very small alpha may cause precision problems.\n      ConvergenceWarning)\n    CV fold 0\n    \ttrain rmse = 0.441\n    \tvalid rmse = 0.59\n    \ttest rmse = 0.63\n    CV fold 1\n    \ttrain rmse = 0.429\n    \tvalid rmse = 0.541\n    \ttest rmse = 0.587\n    CV fold 2\n    \ttrain rmse = 0.416\n    \tvalid rmse = 0.512\n    \ttest rmse = 0.563\n    CV fold 3\n    \ttrain rmse = 0.407\n    \tvalid rmse = 0.509\n    \ttest rmse = 0.551\n    CV fold 4\n    \ttrain rmse = 0.404\n    \tvalid rmse = 0.529\n    \ttest rmse = 0.558\n    CV fold 5\n    \ttrain rmse = 0.396\n    \tvalid rmse = 0.532\n    \ttest rmse = 0.538\n    CV fold 6\n    \ttrain rmse = 0.407\n    \tvalid rmse = 0.501\n    \ttest rmse = 0.532\n    CV fold 7\n    \ttrain rmse = 0.391\n    \tvalid rmse = 0.466\n    \ttest rmse = 0.515\n    ----------------------------\n    train rmse = 0.411 \u00b1 0.0158\n    valid rmse = 0.522 \u00b1 0.0335\n    test rmse = 0.559 \u00b1 0.0336\n    ----------------------------\n    Testing if the notebook can be converted to html\n    [NbConvertApp] Converting notebook ./sea_ice_starting_kit.ipynb to html\n    [NbConvertApp] Writing 866712 bytes to ./sea_ice_starting_kit.html\n\n\nThis one computes the vector of input variables at times `[t, t-1, ... t-window_size+1]` then concatenate. Spatial variables are averaged along lat and lon coordinates. We use this with a random forest regressor.\n\n\n```python\n%%file submissions/mean_ten/ts_feature_extractor.py\nimport numpy as np\n\n\nclass FeatureExtractor(object):\n\n    def __init__(self):\n        self.window_size = 10\n\n    def transform(self, X_ds):\n        \"\"\"Compute the vector of input variables in window of a given size.\n\n        Compute the vector of input variables at times\n        [t, t-1, ... t-window_size+1] then concatenate. Spatial variables\n        will be averaged along lat and lon coordinates.\n        \"\"\"\n        # This is the range for which features should be provided. Strip\n        # the burn-in from the beginning and the prediction look-ahead from\n        # the end.\n        valid_range = np.arange(X_ds.attrs['n_burn_in'], len(X_ds['time']))\n        # We convert the Dataset into a 4D DataArray\n        X_xr = X_ds.to_array()\n        # We compute the mean over the lat and lon axes\n        mean_xr = np.mean(X_xr, axis=(2, 3))\n        mean_array_transposed = mean_xr.values.T\n        # We concatenate the past window_size means\n        mean_array_c = np.concatenate(\n            [np.roll(mean_array_transposed, i)\n             for i in range(self.window_size)], axis=1)\n        # We slice the valid range\n        X_array = mean_array_c[valid_range]\n        return X_array\n\n\n```\n\n    Overwriting submissions/mean_ten/ts_feature_extractor.py\n\n\n\n```python\n%%file submissions/mean_ten/regressor.py\nfrom sklearn.base import BaseEstimator\nfrom sklearn.ensemble import RandomForestRegressor\n\n\nclass Regressor(BaseEstimator):\n    def __init__(self):\n        self.reg = RandomForestRegressor(n_estimators=10, max_leaf_nodes=500)\n\n    def fit(self, X, y):\n        self.reg.fit(X, y)\n\n    def predict(self, X):\n        return self.reg.predict(X)\n\n\n```\n\n    Overwriting submissions/mean_ten/regressor.py\n\n\n\n```python\n!ramp_test_submission --submission mean_ten\n```\n\n    Testing Arctic sea ice forecast\n    Reading train and test files from ./data ...\n    Reading cv ...\n    length of common block: 912 months = 76 years\n    length of validation block: 768 months = 64 years\n    length of each cv block: 96 months = 8 years\n    Training ./submissions/mean_ten ...\n    CV fold 0\n    \ttrain rmse = 0.459\n    \tvalid rmse = 0.606\n    \ttest rmse = 0.713\n    CV fold 1\n    \ttrain rmse = 0.454\n    \tvalid rmse = 0.594\n    \ttest rmse = 0.673\n    CV fold 2\n    \ttrain rmse = 0.46\n    \tvalid rmse = 0.525\n    \ttest rmse = 0.683\n    CV fold 3\n    \ttrain rmse = 0.415\n    \tvalid rmse = 0.548\n    \ttest rmse = 0.586\n    CV fold 4\n    \ttrain rmse = 0.385\n    \tvalid rmse = 0.512\n    \ttest rmse = 0.609\n    CV fold 5\n    \ttrain rmse = 0.382\n    \tvalid rmse = 0.565\n    \ttest rmse = 0.622\n    CV fold 6\n    \ttrain rmse = 0.379\n    \tvalid rmse = 0.527\n    \ttest rmse = 0.602\n    CV fold 7\n    \ttrain rmse = 0.358\n    \tvalid rmse = 0.547\n    \ttest rmse = 0.601\n    ----------------------------\n    train rmse = 0.411 \u00b1 0.0386\n    valid rmse = 0.553 \u00b1 0.0312\n    test rmse = 0.636 \u00b1 0.0438\n    ----------------------------\n    Testing if the notebook can be converted to html\n    [NbConvertApp] Converting notebook ./sea_ice_starting_kit.ipynb to html\n    [NbConvertApp] Writing 867447 bytes to ./sea_ice_starting_kit.html\n\n\n\n```python\n%%file submissions/monthly_means/ts_feature_extractor.py\nimport numpy as np\n\n\nclass FeatureExtractor(object):\n\n    def __init__(self):\n        pass\n\n    def transform(self, X_ds):\n        \"\"\"Compute the monthly averages of the ice_area.\n\n        Corresponding to the month to predict.\n        The code could be simplified but in this way it is general, can be\n        used for the other variables as well.\n        \"\"\"\n        # This is the range for which features should be provided. Strip\n        # the burn-in from the beginning and the prediction look-ahead from\n        # the end.\n        valid_range = np.arange(X_ds.attrs['n_burn_in'], len(X_ds['time']))\n        # We convert the Dataset into a 4D DataArray\n        X_xr = X_ds.to_array()\n        # We compute the mean over the lat and lon axes\n        mean_array = np.mean(X_xr, axis=(2, 3)).values\n        # We group the 8 monthly series into 8 x 12 monthly groups of series\n        monthly_groups = mean_array.reshape(\n            (mean_array.shape[0], 12, -1), order='F')\n        # We compute cumulative means in each group\n        monthly_means = np.cumsum(monthly_groups, axis=2)\\\n            / (1. + np.arange(monthly_groups.shape[2]))\n        # We repeat each mean 12 times\n        monthly_means_per_month = np.repeat(monthly_means, 12, axis=2)\n        # We pad m 0s to the series corresponding to month m, no single-line\n        # operation for this\n        for j in range(monthly_means_per_month.shape[0]):\n            for m in range(12):\n                monthly_means_per_month[j, m] = np.roll(\n                    monthly_means_per_month[j, m], m)\n                monthly_means_per_month[j, m, :m] = 0\n        # We reshape and transpose it into one vector per month\n        monthly_ice_area_mean = monthly_means_per_month[0]\n        # At each month t we use the running mean correponting to month t - 8\n        X_array = np.array(\n            [monthly_ice_area_mean[(t + X_ds.n_lookahead - 12) % 12][t]\n             for t in range(monthly_ice_area_mean.shape[1])])\n        # We slice the valid range\n        X_array = X_array[valid_range].reshape(-1, 1)\n        return X_array\n\n\n```\n\n    Overwriting submissions/monthly_means/ts_feature_extractor.py\n\n\n\n```python\n!ramp_test_submission --submission monthly_means\n```\n\n    Testing Arctic sea ice forecast\n    Reading train and test files from ./data ...\n    Reading cv ...\n    length of common block: 912 months = 76 years\n    length of validation block: 768 months = 64 years\n    length of each cv block: 96 months = 8 years\n    Training ./submissions/monthly_means ...\n    CV fold 0\n    \ttrain rmse = 0.332\n    \tvalid rmse = 0.342\n    \ttest rmse = 0.37\n    CV fold 1\n    \ttrain rmse = 0.336\n    \tvalid rmse = 0.334\n    \ttest rmse = 0.368\n    CV fold 2\n    \ttrain rmse = 0.342\n    \tvalid rmse = 0.319\n    \ttest rmse = 0.369\n    CV fold 3\n    \ttrain rmse = 0.341\n    \tvalid rmse = 0.318\n    \ttest rmse = 0.367\n    CV fold 4\n    \ttrain rmse = 0.336\n    \tvalid rmse = 0.329\n    \ttest rmse = 0.368\n    CV fold 5\n    \ttrain rmse = 0.333\n    \tvalid rmse = 0.342\n    \ttest rmse = 0.367\n    CV fold 6\n    \ttrain rmse = 0.339\n    \tvalid rmse = 0.299\n    \ttest rmse = 0.366\n    CV fold 7\n    \ttrain rmse = 0.337\n    \tvalid rmse = 0.284\n    \ttest rmse = 0.367\n    ----------------------------\n    train rmse = 0.337 \u00b1 0.0034\n    valid rmse = 0.321 \u00b1 0.0192\n    test rmse = 0.368 \u00b1 0.0012\n    ----------------------------\n    Testing if the notebook can be converted to html\n    [NbConvertApp] Converting notebook ./sea_ice_starting_kit.ipynb to html\n    [NbConvertApp] Writing 862869 bytes to ./sea_ice_starting_kit.html\n\n\nThe following feature extractor \"cheats\": it rolls the feature array backwards, making the future part of the features. Check what happens when the unit test is run.\n\n\n```python\n%%file submissions/illegal_lookahead/ts_feature_extractor.py\nimport numpy as np\n\n\nclass FeatureExtractor(object):\n\n    def __init__(self):\n        pass\n\n    def transform(self, X_ds):\n        \"\"\"Compute the vector of input variables at time t. Spatial variables will\n        be averaged along lat and lon coordinates.\"\"\"\n        # This is the range for which features should be provided. Strip\n        # the burn-in from the beginning and the prediction look-ahead from\n        # the end.\n        valid_range = np.arange(X_ds.attrs['n_burn_in'], len(X_ds['time']))\n        # We convert the Dataset into a 4D DataArray\n        X_xr = X_ds.to_array()\n        # We compute the mean over the lat and lon axes\n        mean_xr = np.mean(X_xr, axis=(2, 3))\n        # We convert it into numpy array, transpose, and slice the valid range\n        # We roll it backwards to see what happens when the feature extractor\n        # attempts to look into the future.\n        X_array = mean_xr.values.T[np.roll(valid_range, -2)]\n        return X_array\n\n\n```\n\n    Overwriting submissions/illegal_lookahead/ts_feature_extractor.py\n\n\n\n```python\n!ramp_test_submission --submission illegal_lookahead\n```\n\n    Testing Arctic sea ice forecast\n    Reading train and test files from ./data ...\n    Reading cv ...\n    length of common block: 912 months = 76 years\n    length of validation block: 768 months = 64 years\n    length of each cv block: 96 months = 8 years\n    Training ./submissions/illegal_lookahead ...\n    Traceback (most recent call last):\n      File \"/Users/kegl/anaconda/bin/ramp_test_submission\", line 11, in <module>\n        load_entry_point('ramp-workflow', 'console_scripts', 'ramp_test_submission')()\n      File \"/Users/kegl/Research/RAMP/ramp-workflow/rampwf/utils/command_line.py\", line 51, in ramp_test_submission\n        submission=sub)\n      File \"/Users/kegl/Research/RAMP/ramp-workflow/rampwf/utils/testing.py\", line 79, in assert_submission\n        module_path, X_train, y_train, train_is=train_is)\n      File \"/Users/kegl/Research/RAMP/ramp-workflow/rampwf/workflows/el_nino.py\", line 59, in train_submission\n        ts_fe, X_train_ds)\n      File \"/Users/kegl/Research/RAMP/ramp-workflow/rampwf/workflows/ts_feature_extractor.py\", line 125, in test_submission\n        raise AssertionError(message)\n    AssertionError: The feature extractor looks into the future by at least 2 time steps\n\n\n## Working in the notebook\n\nWhen you are developing and debugging your submission, you may want to stay in the notebook and execute the workflow step by step. You can import `problem.py` and call the ingredients directly, or even deconstruct the code from [ramp-workflow](https://github.com/paris-saclay-cds/ramp-workflow).\n\n\n```python\nimport imp\nproblem = imp.load_source('', 'problem.py')\n```\n\nGet the training data.\n\n\n```python\nX_train, y_train = problem.get_train_data()\n```\n\nGet the first cv fold, creating training and validation indices.\n\n\n```python\ntrain_is, test_is = list(problem.get_cv(X_train, y_train))[0]\n```\n\n    length of common block: 708 months = 59 years\n    length of validation block: 672 months = 56 years\n    length of each cv block: 84 months = 7 years\n\n\nTrain your starting kit.\n\n\n```python\nts_fe, reg = problem.workflow.train_submission(\n    'submissions/starting_kit', X_train, y_train, train_is)\n```\n\nGet the full prediction (train and validation).\n\n\n```python\ny_pred = problem.workflow.test_submission((ts_fe, reg), X_train)\n```\n\nPrint the training and validation scores.\n\n\n```python\nscore_function = problem.score_types[0]\n```\n\n\n```python\nscore_train = score_function(y_train[train_is], y_pred[train_is])\nprint(score_train)\n```\n\n    0.914748857316\n\n\n\n```python\nscore_valid = score_function(y_train[test_is], y_pred[test_is])\nprint(score_valid)\n```\n\n    0.922932338866\n\n\nGet the independent test data.\n\n\n```python\nX_test, y_test = problem.get_test_data()\n```\n\nTest the submission on it.\n\n\n```python\ny_test_pred = problem.workflow.test_submission((ts_fe, reg), X_test)\n```\n\nPrint the test score.\n\n\n```python\nscore_test = score_function(y_test, y_test_pred)\nprint(score_test)\n```\n\n    0.970616143599\n\n\nIf you want to execute training step by step, go to the [`el_nino`](https://github.com/paris-saclay-cds/ramp-workflow/blob/master/rampwf/workflows/el_nino.py), [`ts_feature_extractor`](https://github.com/paris-saclay-cds/ramp-workflow/blob/master/rampwf/workflows/ts_feature_extractor.py), and [`regressor`](https://github.com/paris-saclay-cds/ramp-workflow/blob/master/rampwf/workflows/regressor.py) workflows and deconstruct them.\n\n\n```python\nts_feature_extractor = imp.load_source(\n    '', 'submissions/starting_kit/ts_feature_extractor.py')\nts_fe = ts_feature_extractor.FeatureExtractor()\nregressor = imp.load_source(\n    '', 'submissions/starting_kit/regressor.py')\nreg = regressor.Regressor()\n```\n\n\n```python\nn_burn_in = X_ds.n_burn_in\n# X_ds contains burn-in so it needs to be extended by n_burn_in\n# timesteps. This assumes that train_is is a block of consecutive\n# time points.\nburn_in_range = np.arange(train_is[-1], train_is[-1] + n_burn_in)\nextended_train_is = np.concatenate((train_is, burn_in_range))\nX_train_ds = X_ds.isel(time=extended_train_is)\nX_train_array = ts_fe.transform(X_train_ds)\nprint(X_train_array)\nreg.fit(X_train_array[train_is], y_train[train_is])\n```\n\n    [[  1.48342934e+01   2.75403087e+02  -9.99870661e-03 ...,   1.00945582e+05\n        1.04329444e+01   4.36368580e-01]\n     [  1.57851725e+01   2.74862356e+02  -4.93761828e-03 ...,   1.01028900e+05\n        1.00348801e+01   4.46457947e-01]\n     [  1.58088322e+01   2.74467664e+02  -6.26856377e-03 ...,   1.00970414e+05\n        1.02867818e+01   4.46326237e-01]\n     ..., \n     [  7.11175919e+00   2.77646321e+02  -1.24813862e-02 ...,   1.00744758e+05\n        1.12947455e+01   4.81643986e-01]\n     [  8.72921658e+00   2.76421950e+02  -1.22162999e-02 ...,   1.00820864e+05\n        1.00709387e+01   4.62528035e-01]\n     [  1.07231407e+01   2.75346836e+02  -1.20509273e-02 ...,   1.00832401e+05\n        1.00267506e+01   4.40711749e-01]]\n\n\n\n```python\nX_train_array = ts_fe.transform(X_train)\ny_pred = reg.predict(X_train_array)\n```\n\n\n```python\nX_test_array = ts_fe.transform(X_test)\ny_test_pred = reg.predict(X_test_array)\n```\n\n## More information\n\nYou can find more information in the [README](https://github.com/paris-saclay-cds/ramp-workflow/blob/master/README.md) of the [ramp-workflow library](https://github.com/paris-saclay-cds/ramp-workflow).\n\n## Contact\n\nDon't hesitate to [contact us](mailto:admin@ramp.studio?subject=sea ice notebook).\n", "meta": {"hexsha": "83e9bbb6973da51295509c4299462e57c195be81", "size": 610935, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "sea_ice/sea_ice_starting_kit.ipynb", "max_stars_repo_name": "bgroenks96/csci-5622-project", "max_stars_repo_head_hexsha": "c13ff6ac27853ba74457d668280ea07dc6601a5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sea_ice/sea_ice_starting_kit.ipynb", "max_issues_repo_name": "bgroenks96/csci-5622-project", "max_issues_repo_head_hexsha": "c13ff6ac27853ba74457d668280ea07dc6601a5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sea_ice/sea_ice_starting_kit.ipynb", "max_forks_repo_name": "bgroenks96/csci-5622-project", "max_forks_repo_head_hexsha": "c13ff6ac27853ba74457d668280ea07dc6601a5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 315.2399380805, "max_line_length": 146884, "alphanum_fraction": 0.9076153764, "converted": true, "num_tokens": 15888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.09670578874026685, "lm_q1q2_score": 0.04759744187348104}}
{"text": "# PyTorch Assignment: Reinforcement Learning (RL)\n\n**[Duke Community Standard](http://integrity.duke.edu/standard.html): By typing your name below, you are certifying that you have adhered to the Duke Community Standard in completing this assignment.**\n\nName: \n\n### Short answer\n\n1\\. One of the fundamental challenges of reinforcement learning is balancing *exploration* versus *exploitation*. What do these two terms mean, and why do they present a challenge?\n\n`[Your answer here]`\n\n2\\. Another fundamental reinforcement learning challenge is what is known as the *credit assignment problem*, especially when rewards are sparse. What do we mean by the phrase, and why does it make learning especially difficult?\n\n`[Your answer here]`\n\n### Deep SARSA Cart Pole\n\n[SARSA (state-action-reward-state-action)](https://en.wikipedia.org/wiki/State\u2013action\u2013reward\u2013state\u2013action) is another Q value algorithm that resembles Q-learning quite closely:\n\nQ-learning update rule:\n\\begin{equation}\nQ_\\pi (s_t, a_t) \\leftarrow (1 - \\alpha) \\cdot Q_\\pi(s_t, a_t) + \\alpha \\cdot \\big(r_t + \\gamma \\max_a Q_\\pi(s_{t+1}, a)\\big)\n\\end{equation}\n\nSARSA update rule:\n\\begin{equation}\nQ_\\pi (s_t, a_t) \\leftarrow (1 - \\alpha) \\cdot Q_\\pi(s_t, a_t) + \\alpha \\cdot \\big(r_t + \\gamma Q_\\pi(s_{t+1}, a_{t+1})\\big)\n\\end{equation}\n\nUnlike Q-learning, which is considered an *off-policy* network, SARSA is an *on-policy* algorithm. \nWhen Q-learning calculates the estimated future reward, it must \"guess\" the future, starting with the next action the agent will take. In Q-learning, we assume the agent will take the best possible action: $\\max_a Q_\\pi(s_{t+1}, a)$. SARSA, on the other hand, uses the action that was actually taken next in the episode we are learning from: $Q_\\pi(s_{t+1}, a_{t+1})$. In other words, SARSA learns from the next action he actually took (on policy), as opposed to what the max possible Q value for the next state was (off policy).\n\nBuild an RL agent that uses SARSA to solve the Cart Pole problem. \n\n*Hint: You can and should reuse the Q-Learning agent we went over earlier. In fact, if you know what you're doing, it's possible to finish this assignment in about 30 seconds.*\n\n\n```python\n### YOUR CODE HERE ###\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n```\n", "meta": {"hexsha": "48fb413007c02db432b83ee6508f4f2398643f9c", "size": 3781, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Duke_DL/notebook/5B_Reinforcement_Learning_Assignment.ipynb", "max_stars_repo_name": "sudhirln92/Udemy_Courses_ML", "max_stars_repo_head_hexsha": "2226177430a54e75541c4ac1e76e9eb2620cdae4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Duke_DL/notebook/5B_Reinforcement_Learning_Assignment.ipynb", "max_issues_repo_name": "sudhirln92/Udemy_Courses_ML", "max_issues_repo_head_hexsha": "2226177430a54e75541c4ac1e76e9eb2620cdae4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Duke_DL/notebook/5B_Reinforcement_Learning_Assignment.ipynb", "max_forks_repo_name": "sudhirln92/Udemy_Courses_ML", "max_forks_repo_head_hexsha": "2226177430a54e75541c4ac1e76e9eb2620cdae4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-02-18T14:49:44.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-18T14:49:44.000Z", "avg_line_length": 29.7716535433, "max_line_length": 543, "alphanum_fraction": 0.5829145729, "converted": true, "num_tokens": 585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.10230469899740588, "lm_q1q2_score": 0.04756161532277551}}
{"text": "```\n# @title Copyright 2022 The Cirq Developers\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# Classical control\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n  <td>\n    <a target=\"_blank\" href=\"https://quantumai.google/cirq/classical_control\">View on QuantumAI</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/Cirq/blob/master/docs/classical_control.ipynb\">Run in Google Colab</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://github.com/quantumlib/Cirq/blob/master/docs/classical_control.ipynb\">View source on GitHub</a>\n  </td>\n  <td>\n    <a href=\"https://storage.googleapis.com/tensorflow_docs/Cirq/docs/classical_control.ipynb\">Download notebook</a>\n  </td>\n</table>\n\n\n```\ntry:\n    import cirq\nexcept ImportError:\n    print(\"installing cirq...\")\n    !pip install --quiet cirq\n    import cirq\n\n    print(\"installed cirq.\")\n```\n\nWhile some quantum algorithms can be defined entirely at the quantum level, there are many others (notably including [teleportation](/cirq/tutorials/educators/textbook_algorithms#quantum_teleportation) and [error correction](https://www.nature.com/articles/s41586-021-03588-y)) which rely on classical measurement results from one part of the algorithm to control operations in a later section.\n\nTo represent this, Cirq provides the `ClassicallyControlledOperation`. Following the pattern of controlled operations, a classically-controlled version of any `Operation` can be constructed by calling its `with_classical_controls` method with the control condition(s).\n\n## Basic conditions\n\nIn the example below, `H` will only be applied to `q1` if the previous measurement \"a\" returns a 1. More generally, providing some string `\"cond\"` to `with_classical_controls` creates a `cirq.ClassicallyControlledOperation` with a `cirq.KeyCondition` whose key is `\"cond\"`. A `KeyCondition` will only trigger, and apply the operation it controls, if a preceding measurement with the same key measured **one or more** qubits in the $|1\\rangle$ state.\n\n\n```\nq0, q1 = cirq.LineQubit.range(2)\ncircuit = cirq.Circuit(\n    cirq.H(q0),\n    cirq.measure(q0, key='a'),\n    cirq.H(q1).with_classical_controls('a'),\n    cirq.measure(q1, key='b'),\n)\nprint(circuit)\nprint(cirq.Simulator().run(circuit, repetitions=1000).histogram(key='b'))\n```\n\nThe results from running the circuit on the simulator match expectation. `H` applied to qubit `q0` means that qubit will be $|1\\rangle$ half of the time on average. When `H` is then applied to qubit `q1`, (half of the time), `q1` will measure $|1\\rangle$ a quarter of the time and $|0\\rangle$ three-quarters of the time.\n\nUsing just these conditions, we can construct the [quantum teleportation](/cirq/tutorials/educators/textbook_algorithms#quantum_teleportation) circuit:\n\n\n```\n# Teleports `_message` from Alice to Bob.\nalice = cirq.NamedQubit('alice')\nbob = cirq.NamedQubit('bob')\nmessage = cirq.NamedQubit('_message')\n\nmessage_circuit = cirq.Circuit(\n    # Create the message.\n    cirq.X(message) ** 0.371,\n    cirq.Y(message) ** 0.882,\n)\n\nteleport_circuit = cirq.Circuit(\n    # Create Bell state to be shared between Alice and Bob.\n    cirq.H(alice),\n    cirq.CNOT(alice, bob),\n    # Prepare message circuit\n    message_circuit,\n    # Bell measurement of the message and Alice's entangled qubit.\n    cirq.CNOT(message, alice),\n    cirq.H(message),\n    cirq.measure(message, key='M'),\n    cirq.measure(alice, key='A'),\n    # Uses the two classical bits from the Bell measurement to recover the\n    # original quantum message on Bob's entangled qubit.\n    cirq.X(bob).with_classical_controls('A'),\n    cirq.Z(bob).with_classical_controls('M'),\n)\nprint(circuit)\n\n# Simulate the message and teleport circuits for Bloch vectors to compare\n#     the state of the teleported qubit before and after teleportation.\nsim = cirq.Simulator()\nmessage_bloch_vector = cirq.bloch_vector_from_state_vector(\n    sim.simulate(message_circuit).final_state_vector, index=0\n)\nteleport_bloch_vector = cirq.bloch_vector_from_state_vector(\n    sim.simulate(teleport_circuit).final_state_vector, index=2\n)\nprint(f\"Message Qubit State: {message_bloch_vector}\")\nprint(f\"Teleported Bob's Qubit state: {teleport_bloch_vector}\")\n```\n\nThis example separately simulated the message qubit after its construction, and Bob's qubit after teleportation of the message. The fact that the Bloch vectors of each respective qubit are the same indicate that the circuit successfully teleported the message qubit's state onto Bob's qubit. \n\n## Sympy conditions\n\nCirq also supports more complex control conditions: providing some `sympy` expression `\"expr\"` to `with_classical_controls` creates a `ClassicallyControlledOperation` with a `SympyCondition`. That condition will only trigger if `\"expr\"` evaluates to a \"truthy\" value (`bool(expr) == True`), and uses measurement results to resolve any variables in the expression.\n\nIn this example, `X` will only be applied to `q2` if `a == b`; in other words, $|q_0q_1\\rangle$ must be either $|00\\rangle$ or $|11\\rangle$. This is verifiable with the simulated result data, where the `c` measurement key for qubit `q2` is always `1` when `a` and `b` are `00` or `11`, and `0` otherwise.\n\n\n```\nimport sympy\n\nq0, q1, q2 = cirq.LineQubit.range(3)\na, b = sympy.symbols('a b')\nsympy_cond = sympy.Eq(a, b)\ncircuit = cirq.Circuit(\n    cirq.H.on_each(q0, q1),\n    cirq.measure(q0, key='a'),\n    cirq.measure(q1, key='b'),\n    cirq.X(q2).with_classical_controls(sympy_cond),\n    cirq.measure(q2, key='c'),\n)\nprint(circuit)\nresults = cirq.Simulator(seed=2).run(circuit, repetitions=8)\nprint(results.data)\n```\n\n## Combining conditions\n\nMultiple conditions of either type can be specified to `with_classical_controls`, in which case the resulting `ClassicallyControlledOperation` will only trigger if _all_ conditions trigger. Similarly, calling `with_classical_controls` on an existing `ClassicallyControlledOperation` will require all new and pre-existing conditions to trigger for the operation to trigger.\n\n\n```\nq0, q1, q2, q3, q4 = cirq.LineQubit.range(5)\na = sympy.symbols('a')\nsympy_cond = sympy.Eq(a, 0)\ncircuit = cirq.Circuit(\n    cirq.H.on_each(q0, q1, q2),\n    cirq.measure(q0, q1, key='a'),\n    cirq.measure(q2, key='b'),\n    cirq.X(q3).with_classical_controls('b', sympy_cond),\n    cirq.X(q4).with_classical_controls('b').with_classical_controls(sympy_cond),\n    cirq.measure(q3, key='c'),\n    cirq.measure(q4, key='d'),\n)\nprint(circuit)\nresults = cirq.Simulator(seed=1).run(circuit, repetitions=8)\nprint(results.data)\n```\n\nFirst, remember that the value of a measurement key for multiple qubits will be an integer representative of the bit string of those qubits' measurements. You can see this in the data for `a`, the measurement key for both `q0` and `q1`, which has values in the range `[0, 3]`. The sympy condition `Eq(a, 0)` will then only trigger when both of those qubits individually measure `0`. \n\nThis means that `X(q3).with_classical_controls('b', sympy_cond)` only triggers when `b`'s qubit `q2` measures `1` and `a = 0` is true (`q0` and `q1` measure `0`). This is consistent with the simulated results, for both `c` (`q3`'s key) and `d` (`q4`'s key).\n\nFinally, the fact that `c` and `d` are always identical serves as a reminder that chaining multiple calls of `with_classical_controls()` together is equivalent to calling it once with multiple arguments.\n\n## Variable scope\n\nWhen used with `cirq.CircuitOperation`, classically controlled operations will be resolved using local repetition IDs, if any. This is the only way to create a non-global variable scope within a circuit. A simple example of this is shown below, where the controls inside and outside a subcircuit rely on measurements in their respective scopes:\n\n\n```\nq0 = cirq.LineQubit(0)\nsubcircuit = cirq.FrozenCircuit(cirq.measure(q0, key='a'), cirq.X(q0).with_classical_controls('a'))\ncircuit = cirq.Circuit(\n    cirq.measure(q0, key='a'),\n    cirq.CircuitOperation(subcircuit, repetitions=2),\n    cirq.X(q0).with_classical_controls('a'),\n)\nprint(\"Original Circuit\")\nprint(circuit)\nprint(\"Circuit with nested circuit unrolled.\")\nprint(cirq.CircuitOperation(cirq.FrozenCircuit(circuit)).mapped_circuit(deep=True))\n```\n\nThe measurement key `a` is present both in the outer circuit and the `FrozenCircuit` nested within it, but these two keys are different due to their different scopes. After unrolling the inner circuit twice, these inner `a`s get prefixed by the repetition number and becomes new, separate measurement keys, `0:a` and `1:a`, that don't interact with each other or the original `a`. \n\nMore complex scoping behavior is described in the [classically controlled operation tests](https://github.com/quantumlib/Cirq/blob/master/cirq-core/cirq/ops/classically_controlled_operation_test.py).\n\n## Using with transformers\n\nCirq [transformers](transformers.ipynb) are aware of classical control and will avoid changes which move a control before its corresponding measurement. Additionally, for some simple cases the [`defer_measurements` transformer](https://github.com/quantumlib/Cirq/blob/6e0e164e8ac1c2f28a1f3389370fffb50a4d2a4f/cirq-core/cirq/transformers/measurement_transformers.py#L58) can convert a classically-controlled circuit into a purely-quantum circuit:\n\n\n```\nq0 = cirq.LineQubit(0)\ncircuit = cirq.Circuit(\n    cirq.measure(q0, key='a'), cirq.X(q1).with_classical_controls('a'), cirq.measure(q1, key='b')\n)\ndeferred = cirq.defer_measurements(circuit)\nprint(\"Original circuit:\")\nprint(circuit)\nprint(\"Measurement deferred:\")\nprint(deferred)\n```\n\n## Compatibility\n\nThe Cirq built-in simulators provide support for classical control, but caution should be exercised when exporting these circuits to other environments. `ClassicallyControlledOperation` is fundamentally different from other operations in that it requires access to the measurement results, and simulators or hardware that do not explicitly support this will not be able to run `ClassicallyControlledOperation`s.\n", "meta": {"hexsha": "aa6364a8a43f6d913dbb5470080f71b9ae43720e", "size": 15039, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/classical_control.ipynb", "max_stars_repo_name": "Nexuscompute/Cirq", "max_stars_repo_head_hexsha": "640ef8f82d6a56ec95361388ce7976e096cca906", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/classical_control.ipynb", "max_issues_repo_name": "Nexuscompute/Cirq", "max_issues_repo_head_hexsha": "640ef8f82d6a56ec95361388ce7976e096cca906", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2022-01-16T14:12:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T03:58:46.000Z", "max_forks_repo_path": "docs/classical_control.ipynb", "max_forks_repo_name": "Nexuscompute/Cirq", "max_forks_repo_head_hexsha": "640ef8f82d6a56ec95361388ce7976e096cca906", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6459459459, "max_line_length": 462, "alphanum_fraction": 0.6364784893, "converted": true, "num_tokens": 2750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215779698935, "lm_q2_score": 0.11124121387367901, "lm_q1q2_score": 0.047424529833913244}}
{"text": "# Tutorial 1: EasyVVUQ\n\nThe Role of Uncertainty in Mathematical Modelling of Pandemics - Session 2: Wider Applications of VVUQ Methods - 9th February 2022\n\n\n* Forward uncertainty propagation: computing the output distribution of a computational model, given *assumed* probability density functions for the input parameters of the model (see image below). \n\n* [EasyVVUQ](https://github.com/UCL-CCS/EasyVVUQ) is VECMA's forward uncertainty propagation toolkit.\n\n\n\nAuthor: Wouter Edeling, CWI Scientific Computing Group (Wouter.Edeling@CWI.nl)\n\n## Installation\n\n* EasyVVUQ: via git clone or by eceuting the command below\n\nYou will also need seaborn installed for some of the plots. Uncomment the install line below if need be.\n\n\n```python\n!pip install easyvvuq\n#!pip install seaborn\n```\n\n    Defaulting to user installation because normal site-packages is not writeable\n    Requirement already satisfied: easyvvuq in /home/wouter/.local/lib/python3.8/site-packages/easyvvuq-0.7.3.1+75.g8a46b49.dirty-py3.8.egg (0.7.3.1+75.g8a46b49.dirty)\n    Requirement already satisfied: numpy in /home/wouter/.local/lib/python3.8/site-packages (from easyvvuq) (1.19.0)\n    Requirement already satisfied: pandas in /home/wouter/.local/lib/python3.8/site-packages (from easyvvuq) (1.2.1)\n    Requirement already satisfied: scipy in /home/wouter/.local/lib/python3.8/site-packages (from easyvvuq) (1.5.0)\n    Requirement already satisfied: wheel in /home/wouter/.local/lib/python3.8/site-packages (from easyvvuq) (0.35.1)\n    Requirement already satisfied: chaospy==3.3.6 in /home/wouter/.local/lib/python3.8/site-packages (from easyvvuq) (3.3.6)\n    Requirement already satisfied: SALib in /home/wouter/.local/lib/python3.8/site-packages (from easyvvuq) (1.3.12)\n    Requirement already satisfied: pytest in /home/wouter/.local/lib/python3.8/site-packages (from easyvvuq) (6.2.2)\n    Requirement already satisfied: pytest-pep8 in /usr/local/lib/python3.8/dist-packages/pytest_pep8-1.0.6-py3.8.egg (from easyvvuq) (1.0.6)\n    Requirement already satisfied: SQLAlchemy in /usr/lib/python3/dist-packages (from easyvvuq) (1.3.12)\n    Requirement already satisfied: jsonpickle in /home/wouter/.local/lib/python3.8/site-packages (from easyvvuq) (1.5.1)\n    Requirement already satisfied: cerberus in /home/wouter/.local/lib/python3.8/site-packages (from easyvvuq) (1.3.2)\n    Requirement already satisfied: dask[complete] in /home/wouter/.local/lib/python3.8/site-packages (from easyvvuq) (2021.1.1)\n    Requirement already satisfied: dask_jobqueue in /usr/local/lib/python3.8/dist-packages/dask_jobqueue-0.7.2-py3.8.egg (from easyvvuq) (0.7.2)\n    Requirement already satisfied: cloudpickle in /home/wouter/.local/lib/python3.8/site-packages/cloudpickle-1.6.0-py3.8.egg (from easyvvuq) (1.6.0)\n    Requirement already satisfied: scikit-learn in /usr/local/lib/python3.8/dist-packages/scikit_learn-0.23.2-py3.8-linux-x86_64.egg (from easyvvuq) (0.23.2)\n    Requirement already satisfied: jinja2 in /usr/local/lib/python3.8/dist-packages/Jinja2-3.0.0a1-py3.8.egg (from easyvvuq) (3.0.0a1)\n    Requirement already satisfied: kubernetes in /usr/local/lib/python3.8/dist-packages/kubernetes-17.14.0a1-py3.8.egg (from easyvvuq) (17.14.0a1)\n    Requirement already satisfied: autopep8 in /home/wouter/.local/lib/python3.8/site-packages (from easyvvuq) (1.5.4)\n    Requirement already satisfied: numpoly==1.0.5 in /home/wouter/.local/lib/python3.8/site-packages (from chaospy==3.3.6->easyvvuq) (1.0.5)\n    Requirement already satisfied: six in /usr/lib/python3/dist-packages (from numpoly==1.0.5->chaospy==3.3.6->easyvvuq) (1.14.0)\n    Requirement already satisfied: pycodestyle>=2.6.0 in /home/wouter/.local/lib/python3.8/site-packages (from autopep8->easyvvuq) (2.6.0)\n    Requirement already satisfied: toml in /home/wouter/.local/lib/python3.8/site-packages (from autopep8->easyvvuq) (0.10.1)\n    Requirement already satisfied: setuptools in /home/wouter/.local/lib/python3.8/site-packages (from cerberus->easyvvuq) (50.3.0)\n    Requirement already satisfied: distributed>=2.19 in /home/wouter/.local/lib/python3.8/site-packages/distributed-2021.1.1-py3.8.egg (from dask_jobqueue->easyvvuq) (2021.1.1)\n    Requirement already satisfied: pyyaml in /usr/lib/python3/dist-packages (from dask[complete]->easyvvuq) (5.3.1)\n    Requirement already satisfied: click>=6.6 in /usr/lib/python3/dist-packages (from distributed>=2.19->dask_jobqueue->easyvvuq) (7.0)\n    Requirement already satisfied: msgpack>=0.6.0 in /home/wouter/.local/lib/python3.8/site-packages (from distributed>=2.19->dask_jobqueue->easyvvuq) (1.0.0)\n    Requirement already satisfied: psutil>=5.0 in /home/wouter/.local/lib/python3.8/site-packages/psutil-5.8.0-py3.8-linux-x86_64.egg (from distributed>=2.19->dask_jobqueue->easyvvuq) (5.8.0)\n    Requirement already satisfied: sortedcontainers!=2.0.0,!=2.0.1 in /home/wouter/.local/lib/python3.8/site-packages/sortedcontainers-2.3.0-py3.8.egg (from distributed>=2.19->dask_jobqueue->easyvvuq) (2.3.0)\n    Requirement already satisfied: tblib>=1.6.0 in /home/wouter/.local/lib/python3.8/site-packages/tblib-1.7.0-py3.8.egg (from distributed>=2.19->dask_jobqueue->easyvvuq) (1.7.0)\n    Requirement already satisfied: toolz>=0.8.2 in /home/wouter/.local/lib/python3.8/site-packages/toolz-0.11.1-py3.8.egg (from distributed>=2.19->dask_jobqueue->easyvvuq) (0.11.1)\n    Requirement already satisfied: tornado>=6.0.3 in /home/wouter/.local/lib/python3.8/site-packages/tornado-6.1-py3.8-linux-x86_64.egg (from distributed>=2.19->dask_jobqueue->easyvvuq) (6.1)\n    Requirement already satisfied: zict>=0.1.3 in /home/wouter/.local/lib/python3.8/site-packages/zict-2.0.0-py3.8.egg (from distributed>=2.19->dask_jobqueue->easyvvuq) (2.0.0)\n    Requirement already satisfied: heapdict in /home/wouter/.local/lib/python3.8/site-packages/HeapDict-1.0.1-py3.8.egg (from zict>=0.1.3->distributed>=2.19->dask_jobqueue->easyvvuq) (1.0.1)\n    Requirement already satisfied: partd>=0.3.10 in /home/wouter/.local/lib/python3.8/site-packages/partd-1.1.0-py3.8.egg (from dask[complete]->easyvvuq) (1.1.0)\n    Requirement already satisfied: fsspec>=0.6.0 in /home/wouter/.local/lib/python3.8/site-packages/fsspec-0.8.5-py3.8.egg (from dask[complete]->easyvvuq) (0.8.5)\n    Requirement already satisfied: bokeh!=2.0.0,>=1.0.0 in /home/wouter/.local/lib/python3.8/site-packages/bokeh-2.3.0.dev12-py3.8.egg (from dask[complete]->easyvvuq) (2.3.0.dev12)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/lib/python3/dist-packages (from bokeh!=2.0.0,>=1.0.0->dask[complete]->easyvvuq) (2.7.3)\n    Requirement already satisfied: pillow>=7.1.0 in /home/wouter/.local/lib/python3.8/site-packages/Pillow-8.1.0-py3.8-linux-x86_64.egg (from bokeh!=2.0.0,>=1.0.0->dask[complete]->easyvvuq) (8.1.0)\n    Requirement already satisfied: packaging>=16.8 in /home/wouter/.local/lib/python3.8/site-packages (from bokeh!=2.0.0,>=1.0.0->dask[complete]->easyvvuq) (20.9)\n    Requirement already satisfied: typing_extensions>=3.7.4 in /home/wouter/.local/lib/python3.8/site-packages (from bokeh!=2.0.0,>=1.0.0->dask[complete]->easyvvuq) (3.7.4.3)\n    Requirement already satisfied: MarkupSafe>=1.1 in /usr/lib/python3/dist-packages (from jinja2->easyvvuq) (1.1.0)\n    Requirement already satisfied: pyparsing>=2.0.2 in /home/wouter/.local/lib/python3.8/site-packages (from packaging>=16.8->bokeh!=2.0.0,>=1.0.0->dask[complete]->easyvvuq) (2.4.7)\n    Requirement already satisfied: pytz>=2017.3 in /usr/lib/python3/dist-packages (from pandas->easyvvuq) (2019.3)\n    Requirement already satisfied: locket in /home/wouter/.local/lib/python3.8/site-packages/locket-0.2.1-py3.8.egg (from partd>=0.3.10->dask[complete]->easyvvuq) (0.2.1)\n    Requirement already satisfied: certifi>=14.05.14 in /home/wouter/.local/lib/python3.8/site-packages (from kubernetes->easyvvuq) (2020.6.20)\n    Requirement already satisfied: google-auth>=1.0.1 in /usr/lib/python3/dist-packages (from kubernetes->easyvvuq) (1.5.1)\n    Requirement already satisfied: requests in /usr/lib/python3/dist-packages (from kubernetes->easyvvuq) (2.22.0)\n    Requirement already satisfied: requests-oauthlib in /home/wouter/.local/lib/python3.8/site-packages/requests_oauthlib-1.3.0-py3.8.egg (from kubernetes->easyvvuq) (1.3.0)\n    Requirement already satisfied: urllib3>=1.24.2 in /usr/lib/python3/dist-packages (from kubernetes->easyvvuq) (1.25.8)\n    Requirement already satisfied: websocket-client!=0.40.0,!=0.41.*,!=0.42.*,>=0.32.0 in /home/wouter/.local/lib/python3.8/site-packages/websocket_client-0.57.0-py3.8.egg (from kubernetes->easyvvuq) (0.57.0)\n    Requirement already satisfied: attrs>=19.2.0 in /home/wouter/.local/lib/python3.8/site-packages (from pytest->easyvvuq) (20.3.0)\n    Requirement already satisfied: pluggy<1.0.0a1,>=0.12 in /home/wouter/.local/lib/python3.8/site-packages (from pytest->easyvvuq) (0.13.1)\n    Requirement already satisfied: iniconfig in /home/wouter/.local/lib/python3.8/site-packages (from pytest->easyvvuq) (1.1.1)\n    Requirement already satisfied: py>=1.8.2 in /home/wouter/.local/lib/python3.8/site-packages (from pytest->easyvvuq) (1.10.0)\n    Requirement already satisfied: pep8>=1.3 in /home/wouter/.local/lib/python3.8/site-packages/pep8-1.7.1-py3.8.egg (from pytest-pep8->easyvvuq) (1.7.1)\n    Requirement already satisfied: pytest-cache in /home/wouter/.local/lib/python3.8/site-packages/pytest_cache-1.0-py3.8.egg (from pytest-pep8->easyvvuq) (1.0)\n    Requirement already satisfied: execnet>=1.1.dev1 in /home/wouter/.local/lib/python3.8/site-packages/execnet-1.8.0-py3.8.egg (from pytest-cache->pytest-pep8->easyvvuq) (1.8.0)\n    Requirement already satisfied: apipkg>=1.4 in /home/wouter/.local/lib/python3.8/site-packages/apipkg-1.5-py3.8.egg (from execnet>=1.1.dev1->pytest-cache->pytest-pep8->easyvvuq) (1.5)\n    Requirement already satisfied: oauthlib>=3.0.0 in /usr/lib/python3/dist-packages (from requests-oauthlib->kubernetes->easyvvuq) (3.1.0)\n    Requirement already satisfied: matplotlib in /home/wouter/.local/lib/python3.8/site-packages (from SALib->easyvvuq) (3.3.2)\n    Requirement already satisfied: cycler>=0.10 in /home/wouter/.local/lib/python3.8/site-packages (from matplotlib->SALib->easyvvuq) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /home/wouter/.local/lib/python3.8/site-packages (from matplotlib->SALib->easyvvuq) (1.2.0)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.8/dist-packages/joblib-0.16.0-py3.8.egg (from scikit-learn->easyvvuq) (0.16.0)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.8/dist-packages/threadpoolctl-2.1.0-py3.8.egg (from scikit-learn->easyvvuq) (2.1.0)\n    \u001b[33mWARNING: You are using pip version 21.0.1; however, version 22.0.2 is available.\n    You should consider upgrading via the '/usr/bin/python3 -m pip install --upgrade pip' command.\u001b[0m\n\n\n## Sparse-grid forward UQ in theory\n\n### Making a interpolation-based surrogate with 1 uncertain input parameter\n\n\nLet $f^{(1)}(x)$ be a one-dimensional function. We aim to create an interpolation of $f^{(1)}$, denoted by\n\n\\begin{align}\n I^{(l)}f^{(1)}(x) = \\sum_{i=1}^{m_l} f(x_{i}^{(l)})a^{(l)}_i(x).\n \\label{eq:sc1d}\n\\end{align}\n\nHere, $l$ is the so-called *level* of the interpolant. It is an index which links to a **one-dimensional** set of collocation points $\\{x^{l}_i\\}$, for $i=1,\\cdots, m_l$. We can select these points from different families, typically they'll be the abscissas of some quadrature rule. For instance, a Clenshaw-Curtis (CC) rule can generate different collocation points in $[0,1]$ such that\n\n* Level 1: $x^{(1)}_i \\in \\{0.5\\}$,\n* Level 2: $x^{(2)}_i \\in \\{0.0, 0.5, 1.0\\}$,\n* Level 3: $x^{(3)}_i \\in \\{0.0, 0.146, 0.5, 0.854, 1.0\\}$.\n\nNote that here, the higher level collocation point sets include all points from previous levels. When this is the case, we say that the quadrature rule is **nested**. This leads to efficient sampling plans in higher dimensions, but nestedness is not a strict requirement for sparse grid interpolation or integration. This does (often) lead to 1D quadrature rules which increase exponentially, such that the number of points is given by\n\n\\begin{align}\n m_l = \n \\begin{cases}\n  2^{l-1} + 1 & l > 1 \\\\\n  1 & l = 1\n \\end{cases}  \n\\end{align}\n\nFinally, the $a^{(l)}_i(x)$ are the basis functions used for interpolation. In the case of the **Stochastic Collocation** (SC) method, these are often (although not necessarily) the Lagrange interpolation polynomials, given by\n\n\\begin{align}\na^{(l)}_i(x) = \\prod_{\\substack{1\\leq j \\leq m_l \\\\ j \\neq i}} \\frac{x - x_j}{x_i - x_j}\n\\end{align}\n\nA property of the Lagrange polynomial associated with the i-th collocation point is that $a^{(l)}_i(x_i) = 1$ at this point, and $a^{(l)}_i(x_j) = 0$ at all other collocation points $x_j$. The interpolation $I^{(l)}f^{(1)}$ will therefore exactly reproduce the code outputs $f^{(1)}(x_i)$ at the collocation points $x_i$.\n\n### Refinement\n\nLet us define the following difference formulas for interpolation in 1D:\n\n\\begin{align}\n \\Delta^{(l)} f^{(1)} := I^{(l)}f^{(1)} - I^{(l-1)}f^{(1)}\\quad\\mathrm{where}\\quad\n I^{(0)}f^{(1)}:=0.\n \\label{eq:Delta1d}\n\\end{align}\n\nThat is, $ \\Delta^{(l)} f^{(1)}$ is just the difference between the interpolations at successive levels. These difference formulas are often used in both sparse-grid interpolation (and quadrature), see the figure below.\n\n\n\n\nWhen interpolating a level $l-1$ interpolant using a level $l$ interpolating we retrieve the former, i.e.\n\n\\begin{align}\n I^{(l)}\\left(I^{(l-1)}f^{(l)}\\right) = I^{(l-1)}f^{(l)}.\n\\end{align}\n\n\nThus, a lower level interpolant can be exactly interpolated by a higher level interpolant (which is true for both nested and non-nested collocation points), see Figure below:\n\n\n*The blue solid line is the exact 1D function $f^{(1)}$. The red striped line is a (non-nested) level $l$ interpolant. The green striped line is a lower-level $l-1$ counterpart, constructed from function evaluations at  the green star symbols.. If we evaluate the level $l-1$ interpolant at the level $l$ collocation, we obtain the blue squares. Clearly, if these function values are used to construct a level $l$ interpolant of $I^{(l-1)}f^{(1)}$, which would be $I^{(l)}\\left(I^{(l-1)}f^{(1)}\\right)$, we just retrieve $I^{(l-1)}f^{(1)}$.*\n\nWe can therefore write the difference formula as\n\n\\begin{align}\n \\Delta^{(l)}f^{(1)} = I^{(l)}f^{(1)} - I^{(l-1)}f^{(1)} =  I^{(l)}f^{(1)} - I^{(l)}\\left(I^{(l-1)}f^{(1)}\\right) = \\sum_{i = 1}^{m_l}f(x^{(l)}_i)a^{(l)}_i - \\sum_{i=1}^{m_l}I^{(l-1)}f^{(1)}(x^{(l)}_i)a^{(l)}_i = \\nonumber\\\\\n \\sum_{i=1}^{m_l}\\left[f(x^{(l)}_i) - I^{(l-1)}f^{(1)}(x^{(l)}_i)\\right]a^{(l)}_i = \\sum_{i=1}^{m_l}w^{(l)}_ia^{(l)}_i.\n \\label{eq:diff0}\n\\end{align}\n\nHere, $w^{(l)}_i:=f(x^{(l)}_i) - I^{(l-1)}f^{(1)}(x^{(l)}_i)$ is the **hierarchical surplus**, defined as the difference between the code output at a collocation point $x^{(l)}_i$ at level $l$, minus the level $l-1$ polynomial approximation of the code output at the same location. This can be thought of as a local measure of the accuracy of the interpolation. Furthermore, we can also write the interpolation $I^{(l)}f^{(1)}(x)$ in terms of the difference formulas, in which case the $a^{l}_i$ basis function will form a hierarchical basis as\n\n\\begin{align}\n I^{(L)}f^{(1)} = \\sum_{l=1}^L \\Delta^{(l)}f^{(1)} = \\sum_{l=1}^L\\sum_{i=1}^{m_l}w^{(l)}_i a^{(l)}_i\n \\label{eq:diff1}\n\\end{align}\n\nHence, to obtain a level $L$ interpolant, we can just create a telescopic sum of the difference formulas, which is the first equality above. The second equality is obtained by simply plugging in the formula for $\\Delta^{(l)}f^{(1)}$, and it shows that the $a^{(l)}_i$ form a hierarchical basis due to summation over $l$, which increases the number collocation point $m_l$ at every new level. This is also sketched in the Figure below, which assumes linear basis functions for simplicity.\n\n\n*Top left is a standard linear (finite-element) basis, with below it a corresponding linear interpolant. Top right displays a linear hierarchical basis. Below it we show a series of 3 hierarchical interpolants ($L=1,2$ and $3$) and the hierarchical surplus coefficients $w^{(l)}_i$ used in their construction. Figure recreated from [3]*\n\n**Why should we care?**\n\nThe formula above is the same as $I^{(l)}f^{(1)}$ in the beginning, as both are 1D interpolation formulas, only written differently, so why should we complicate things with a hierarchical notation? \n\nOne advantage of adopting the hierarchical notation is that it naturally allows for **refinement**, i.e. adding more points to an existing sampling plan, by adding another level. If we select a nested quadrature rule, adding another level means we only have to evaluate the (expensive) code at a relatively small number of *new* points, the other points are quaranteed to be present in one or more of the previous levels, see the CC example at the beginning of this section.\n\nIn the case more than one uncertain input, sampling plans are create using **tensor products of 1D collocation points**. Here, **a hierarchical construction leads to a sparse sampling plan**, with much less code evaluations compared to \"standard\" sampling plans.\n\n\n\n## Sparse grid UQ on an HIV model\n\nHere we will look at a HIV model [1], taken from the [Active Subspace data set repository](https://github.com/paulcon/as-data-sets). It models the T-cell count during different stages of the disease, and has 27 input parameters spread out over 7 coupled ODEs.\n\n### HIV model\n\nFrom [here](https://github.com/paulcon/as-data-sets/blob/master/HIV/HIV.ipynb) we find the following description of the model, see also [4]. The 7 coupled ordinary differential equations are given by:\n\n$$\n\\begin{align}\n\\frac{dT}{dt} &= s_1 + \\frac{p_1}{C_1+V}TV - \\delta_1T - (K_1V + K_2M_I)T,\\\\\n\\frac{dT_I}{dt} &= \\psi(K_1V + K_2M_I)T + \\alpha_1T_L-\\delta_2T_I-K_3T_ICTL,\\\\\n\\frac{dT_L}{dt} &= (1-\\psi)(K_1V+K_2M_I)T-\\alpha_1T_L-\\delta_3T_L,\\\\\n\\frac{dM}{dt} &= s_2+K_4MV-K_5MV-\\delta_4M,\\\\\n\\frac{dM_I}{dt} &= K_5MV-\\delta_5M_I-K_6M_ICTL,\\\\\n\\frac{dCTL}{dt} &= s_3 + (K_7T_I+K_8M_I)CTL-\\delta_6CTL,\\\\\n\\frac{dV}{dt} &= K_9T_I+K_{10}M_I-K_{11}TV-(K_{12}+K_{13})MV-\\delta_7V,\n\\end{align}\n$$\n\nwhere $T(t)$ is the CD4$^+$ T-cell population, $T_I$ is the actively infected T-cell population, $T_L$ represents latently-infected T-cells, $M$ is macrophages, $M_I$ is infected macrophages, $CTL$ is cytotoxic lymphocytes, and $V$ is virions. The model's 27 parameters are summarized in the table below.\n\nParameter|Nominal Value|Distribution (U(min, max))\n:-------:|:-----------:|:-------------:\n$s_1$|  10 |  U(9.75, 10.25)\n$s_2$|   .15 |  U(.14625, .15375)\n$s_3$|   5  | U(4.875, 5.125)\n$p_1$|   .2 |  U(.195, .205)\n$C_1$|   55.6  | U(54.21, 56.99)\n$K_1$|   3.87e-3 |  U(3.77325e-3, 3.96675e-3)\n$K_2$|   1e-6  | U(.975e-6, 1.025e-6)\n$K_3$|   4.5e-4 |  U(4.3875e-4, 4.6125e-4)\n$K_4$|   7.45e-4 |  U(7.26375e-4, 7.63625e-4)\n$K_5$|   5.22e-4 |  U(5.0895e-4, 5.3505e-4)\n$K_6$|   3e-6  | U(2.925e-6, 3.075e-6)\n$K_7$|   3.3e-4  | U(3.2175e-4, 3.3825e-4)\n$K_8$|   6e-9  | U(5.85e-9, 6.15e-9)\n$K_9$|   .537 |  U(.523575, .550425)\n$K_{10}$|   .285 |  U(.277875, .292125)\n$K_{11}$|   7.79e-6 |  U(7.59525e-6, 7.98475e-6)\n$K_{12}$|   1e-6  | U(.975e-6, 1.025e-6)\n$K_{13}$|   4e-5   |U(3.9e-5, 4.1e-5)\n$\\delta_1$|   .01 |  U(.00975, .01025)\n$\\delta_2$|   .28  | U(.273, .287)\n$\\delta_3$|   .05  | U(.04875, .05125)\n$\\delta_4$|   .005  | U(.004875, .005125)\n$\\delta_5$|   .005 |  U(.004875, .005125)\n$\\delta_6$|   .015 |  U(.014625, .015375)\n$\\delta_7$|   2.39 |  U(2.33025, 2.44975)\n$\\alpha_1$|   3e-4 |  U(2.925e-4, 3.075e-4)\n$\\psi$|   .97 |  U(.94575, .99425)\n\nThe limits on the uniform distributions are 2.5% above and below the nominal values. \n\n\n\n```python\nimport os\nimport numpy as np\nimport easyvvuq as uq\nimport chaospy as cp\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom easyvvuq.actions import CreateRunDirectory, Encode, Decode, ExecuteLocal, Actions\n```\n\n### Setting up an EasyVVUQ campaign\n\nWe first set up the `params` dictionary, in which we specify the name, type and default value of each input:\n\n\n```python\n# default values\nnominal = np.array([10, .15, 5, .2, 55.6, 3.87e-3, 1e-6, 4.5e-4, 7.45e-4, 5.22e-4, 3e-6,\\\n    3.3e-4, 6e-9, .537, .285, 7.79e-6, 1e-6, 4e-5, .01, .28, .05, .005, .005, .015, 2.39,\\\n    3e-4, .97])\n\n# parameter names\nparam_names = ['s_1', 's_2', 's_3', 'p_1', 'C_1', 'K_1', 'K_2', 'K_3', 'K_4', 'K_5', 'K_6',\n               'K_7', 'K_8', 'K_9', 'K_10', 'K_11', 'K_12', 'K_13', 'delta_1', 'delta_2', 'delta_3',\n               'delta_4', 'delta_5', 'delta_6', 'delta_7', 'alpha_1', 'psi']\n# params dict\nparams = {}\nfor idx, name in enumerate(param_names):\n    params[name] = {'type': 'float', 'default': nominal[idx]}\n\nparams\n```\n\n\n\n\n    {'s_1': {'type': 'float', 'default': 10.0},\n     's_2': {'type': 'float', 'default': 0.15},\n     's_3': {'type': 'float', 'default': 5.0},\n     'p_1': {'type': 'float', 'default': 0.2},\n     'C_1': {'type': 'float', 'default': 55.6},\n     'K_1': {'type': 'float', 'default': 0.00387},\n     'K_2': {'type': 'float', 'default': 1e-06},\n     'K_3': {'type': 'float', 'default': 0.00045},\n     'K_4': {'type': 'float', 'default': 0.000745},\n     'K_5': {'type': 'float', 'default': 0.000522},\n     'K_6': {'type': 'float', 'default': 3e-06},\n     'K_7': {'type': 'float', 'default': 0.00033},\n     'K_8': {'type': 'float', 'default': 6e-09},\n     'K_9': {'type': 'float', 'default': 0.537},\n     'K_10': {'type': 'float', 'default': 0.285},\n     'K_11': {'type': 'float', 'default': 7.79e-06},\n     'K_12': {'type': 'float', 'default': 1e-06},\n     'K_13': {'type': 'float', 'default': 4e-05},\n     'delta_1': {'type': 'float', 'default': 0.01},\n     'delta_2': {'type': 'float', 'default': 0.28},\n     'delta_3': {'type': 'float', 'default': 0.05},\n     'delta_4': {'type': 'float', 'default': 0.005},\n     'delta_5': {'type': 'float', 'default': 0.005},\n     'delta_6': {'type': 'float', 'default': 0.015},\n     'delta_7': {'type': 'float', 'default': 2.39},\n     'alpha_1': {'type': 'float', 'default': 0.0003},\n     'psi': {'type': 'float', 'default': 0.97}}\n\n\n\nNext we'll set up the **encoder**, which will create the input files for the HIV model using an input template. In this case the input file is just a comma-separated file of values. To create an EasyVVUQ input template each value is replaced by `$param_name`:\n\n`$s_1,$s_2,$s_3,$p_1,$C_1,$K_1,$K_2,$K_3,$K_4,$K_5,$K_6,$K_7,$K_8,$K_9,$K_10,$K_11,$K_12,$K_13,$delta_1,$delta_2,$delta_3,$delta_4,$delta_5,$delta_6,$delta_7,$alpha_1,$psi`\n\nThe encoder will swap out the `$param_name` flags for values drawn from the specified input distribution.\n\n\n```python\n# input file encoder\nencoder = uq.encoders.GenericEncoder(template_fname='HIV.template', delimiter='$', target_filename='input.csv')\n```\n\nThe HIV model writes a CSV file containing the predicted T-cell count. The **decoder** will read this file and store its contents within the EasyVVUQ database. \n\n\n```python\n# Quantity of Interest, also the column name of the output CSV file\nQOI = 'T_cell_count'\n# CSV output file decoder\ndecoder = uq.decoders.SimpleCSV(target_filename='output.csv', output_columns=[QOI])\n```\n\nWe'll run the HIV ensemble locally. However, in many cases of practical interest the model will be too expensive for local execution. In this case the VECMA tools [QCG-PilotJob](https://github.com/vecma-project/QCG-PilotJob) or [FabSim3](https://github.com/djgroen/FabSim3) can be used in combination with EasyVVUQ to submit the ensemble to HPC resources.\n\n\n```python\n# local execution of HIV_model.py\nexecute = ExecuteLocal('{}/HIV_model.py'.format(os.getcwd()))\n```\n\nNow we are combine all actions we want to execute into an `Actions` object.\n\n\n```python\n# location where the run directories are stored\nWORK_DIR = '/tmp'\n# actions to be undertaken: make rundirs, encode input files, execute local model ensemble, decode output files\nactions = Actions(CreateRunDirectory(root=WORK_DIR, flatten=True), Encode(encoder), execute, \n                  Decode(decoder))\n```\n\nThe central object in the UQ analysis is a so-called Campaign. This is created as:\n\n\n```python\ncampaign = uq.Campaign(name='HIV_SC', params=params, actions=actions)\n```\n\n### Input specification\n\nNext we specify a probability density function for each input parameter in the `vary` dict. Each input in the vary dict will be considered as random, and therefore part of the UQ campaign. We could select only a subset of the parameters defined in the `params` dict above. The remaining inputs will then be fixed to their default values ( also defined in the `params` dict). Here we'll just include 2 inputs to visualize the full sampling plan, and specify a uniform input distribution with bounds at $\\pm 2.5 \\%$ from their default value:\n\n\n```python\nvary = {}\n#Lower and upper parameter limits\nxl = .975*nominal; xu = 1.025*nominal\nincluded_params = ['K_4', 'delta_7']\nfor name in included_params:\n    # input distributions are specified using Chaospy\n    idx = param_names.index(name)\n    vary[name] = cp.Uniform(xl[idx], xu[idx])\nvary\n```\n\n\n\n\n    {'K_4': Uniform(lower=0.000726375, upper=0.000763625),\n     'delta_7': Uniform(lower=2.33025, upper=2.44975)}\n\n\n\n### Sampler\nTo generate the sampling plan we select the (sparse) Stochastic Collocation sampler. The `polynomial_order` of the sampler object should be interpreted as the level (defined above) in the case of `sparse=True`. Furthermore;\n\n* `quadrature_rule='C'`: select the Clenshaw Curtis (CC) quadrature rule\n* `growth=True`: selects an exponential growth rule, making CC *nested*. This is *not* possible for every quadrature rule, see [Chaospy documentation](https://chaospy.readthedocs.io/en/master/reference/quadrature/index.html).\n\n\n\n\n```python\nsampler = uq.sampling.SCSampler(vary=vary, polynomial_order=1, sparse = True, quadrature_rule='C', \n                                growth=True, dimension_adaptive=False)\ncampaign.set_sampler(sampler)\n```\n\nSetting `polynomial_order=1` will create a level 1 sparse grid, with just a single point:\n\n\n```python\ndef plot_sampling_plan():\n    \"\"\"\n    Plot the sampling plan of the (first) two input dimensions\n    \"\"\"\n    fig = plt.figure()\n    ax = fig.add_subplot(111, xlabel='x_1', ylabel='x_2')\n    # the xi_d array contains the N x d sampling points, with N being the number of points and d the number of inputs\n    ax.plot(sampler.xi_d[:,0], sampler.xi_d[:, 1], 'ro')\n    # print the number of points to screen\n    print(\"Number of sampling points = %d\" % sampler.n_samples)\n```\n\n\n```python\nplot_sampling_plan()\n```\n\nWe can refine the grid to the next level via `next_level_sparse_grid`, only evaluating the code at the *new* sampling points. We do this a number of times, plotting the 2D sampling plan each time. \n\n\n```python\nn_adaptations = 6\nfig_means = plt.figure()\nfor i in range(n_adaptations):\n    sampler.next_level_sparse_grid()\n    plot_sampling_plan()\n    # this command executes the actions\n    campaign.execute().collate(progress_bar=True)\n```\n\n## Dimension-adaptive sparse grids\n\nThe sparse grids shown above are **isotropic**, in the sense that both inputs are treated the same. While isotropic sparse grids contains less points compared to the standard SC method, they will not scale very well when we have 27 inputs. \n\nIn this case we can opt to apply the dimension-adaptive version of the SC sampler, in order to create an **anisotropic** sparse grid. This process is iterative in nature, usually staring from a single point. Unlike the isotropic case, only a certain (combination of) parameters will get refined. \n\nAt each iteration, the code is evaluated at certain (so-called *admissible*) refinements, the `x` symbols in the cartoon below. Refinement means adding another tensor product where the quadrature order of one or more inputs is increased by one. Only one of the admissible refinements will get accepted, creating an anisotropic sampling plan.\n\n\n\nTo determine which of the admissible refinement gets accepted, an error measure is computed for every refinement. The one with the highest error is accepted. Here we will use *hierarchical surplus*, defined above. For more information see [2,3].\n\nWe will create a new campaign, the `params` dict and the `actions` do no need to redefined.\n\n\n```python\ncampaign = uq.Campaign(name='HIV_SC_adaptive', params=params, actions=actions)\n```\n\nWe do redefine `vary`, as we will include all 27 inputs in the uncertainty analysis this time.\n\n\n```python\nvary = {}\n#Lower and upper parameter limits\nxl = .975*nominal; xu = 1.025*nominal\nfor i in range(27):\n    vary[param_names[i]] = cp.Uniform(xl[i], xu[i])\n```\n\nSome changes must be made in the sampler as well, as now we set `dimension_adaptive = True`.\n\n\n```python\nsampler = uq.sampling.SCSampler(vary=vary, polynomial_order=1, quadrature_rule='C', sparse=True,\n                                growth=True, dimension_adaptive=True)\ncampaign.set_sampler(sampler)\n```\n\nRun the first ensemble, which consists of just a single sample:\n\n\n```python\ncampaign.execute().collate(progress_bar=True)\n\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.61it/s]\n\n\nTo analyse the results (and execute the dimension adaptivity), we need an `SCAnalysis` object:\n\n\n```python\nanalysis = uq.analysis.SCAnalysis(sampler=sampler, qoi_cols=[QOI])\n# perform analysis (basically estimates moments, Sobol analysis, and updates internal state of analysis)\ncampaign.apply_analysis(analysis)\n```\n\n    /home/wouter/.local/lib/python3.7/site-packages/easyvvuq-1.1.1-py3.7.egg/easyvvuq/analysis/sc_analysis.py:1097: RuntimeWarning: invalid value encountered in true_divide\n      S_u[u] = D_u[u] / D\n\n\nNow we'll refine the grid several times in an anisotropic fashion. Here\n\n* `look_ahead`: determines the new admissible candidate refinements.\n* `campaign.get_collation_result()`: get the data frame with all code samples.\n* `adapt_dimension`: compute the hierarchical surplus at all candidate refinements, and accept the one with the highest surplus.\n\n\n```python\nnumber_of_adaptations = 15\nfor i in range(number_of_adaptations):\n    # compute candidate refinements\n    sampler.look_ahead(analysis.l_norm)\n    # run ensemble (at new locations only)\n    campaign.execute().collate(progress_bar=True)\n    # get data frame\n    data_frame = campaign.get_collation_result()\n    # adapt the sampling plan\n    analysis.adapt_dimension(QOI, data_frame)\n    # we must apply the analysis to update its internal state\n    campaign.apply_analysis(analysis)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 54/54 [00:06<00:00,  8.72it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00,  3.23it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6/6 [00:01<00:00,  5.78it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 10/10 [00:01<00:00,  6.65it/s]\n    0it [00:00, ?it/s]\n    0it [00:00, ?it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 8/8 [00:01<00:00,  6.42it/s]\n    0it [00:00, ?it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 14/14 [00:02<00:00,  6.87it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 18/18 [00:02<00:00,  7.82it/s]\n    0it [00:00, ?it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 8/8 [00:01<00:00,  6.20it/s]\n    0it [00:00, ?it/s]\n    0it [00:00, ?it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 8/8 [00:01<00:00,  6.27it/s]\n\n\nThis command retrieves the result after all refinements:\n\n\n```python\nresults = campaign.get_last_analysis()\n```\n\nThe `adaptation_table` shows a plot of that visualizes which inputs got refined. Again, each refinement is another tensor product of 1D quadrature points, where the quadrature order of at least 1 input is increased. Note that the algorithm will focus on a subset of inputs.\n\n\n```python\nanalysis.adaptation_table()\n```\n\nHere we will compute confidence intervals:\n\n\n```python\ndef get_confidence_intervals(samples, conf=0.9):\n    \"\"\"\n    Compute the confidence intervals given an array of samples\n\n    Parameters\n    ----------\n    samples : array\n        Samples on which to compute the intervals.\n    conf : float, optional, must be in [0, 1].\n        The confidence interval percentage. The default is 0.9.\n\n    Returns\n    -------\n    lower : array\n        The lower confidence bound..\n    upper : array\n        The upper confidence bound.\n\n    \"\"\"\n\n    # ake sure conf is in [0, 1]\n    if conf < 0.0 or conf > 1.0:\n        print('conf must be specified within [0, 1]')\n        return\n\n    # lower bound = alpha, upper bound = 1 - alpha\n    alpha = 0.5 * (1.0 - conf)\n\n    # arrays for lower and upper bound of the interval\n    n_samples = samples.shape[0]\n    N_qoi = samples.shape[1]\n    lower = np.zeros(N_qoi)\n    upper = np.zeros(N_qoi)\n\n    # the probabilities of the ecdf\n    prob = np.linspace(0, 1, n_samples)\n    # the closest locations in prob that correspond to the interval bounds\n    idx0 = np.where(prob <= alpha)[0][-1]\n    idx1 = np.where(prob <= 1.0 - alpha)[0][-1]\n\n    # for every location of qoi compute the ecdf-based confidence interval\n    for i in range(N_qoi):\n        # the sorted surrogate samples at the current location\n        samples_sorted = np.sort(samples[:, i])\n        # the corresponding confidence interval\n        lower[i] = samples_sorted[idx0]\n        upper[i] = samples_sorted[idx1]\n\n    return lower, upper\n```\n\n\n```python\nfrom matplotlib import gridspec\n\nx = range(analysis.N_qoi)\n\ncode_samples = analysis.get_sample_array(QOI)\nn_samples = code_samples.shape[0]\n\n#confidence bounds\nlower1, upper1 = get_confidence_intervals(code_samples, conf=0.63)\nlower2, upper2 = get_confidence_intervals(code_samples, conf=0.95)\n\nfig = plt.figure(figsize=(10,5))\nspec = gridspec.GridSpec(ncols=2, nrows=1,\n                          width_ratios=[3, 1])\n\nax1 = fig.add_subplot(spec[0])\nax2 = fig.add_subplot(spec[1], sharey=ax1)\nax2.get_xaxis().set_ticks([])\nfig.subplots_adjust(wspace=0)\nplt.setp(ax2.get_yticklabels(), visible=False)\n\nax1.fill_between(x, lower2, upper2, color='#aa99cc', label='95% CI', alpha=0.5)\nax1.fill_between(x, lower1, upper1, color='#aa99cc', label='68% CI')\n\nmean = results.describe(QOI, 'mean')\nax1.plot(x, mean, label='Mean')\n\nax1.legend(loc=0, frameon=False)\n\nax1.set_xlabel('Days')\nax1.set_ylabel('T cell count')\nax2.axis('off')\nsns.despine(top=True)\nax2.hist(code_samples[:, -1], orientation='horizontal', color='#aa99cc')\n\nplt.tight_layout()\n```\n\nFinally, we will create a plot with all first-order Sobol indices `S_i`, which shows the fraction of the output variance (vs time here), that each input variable is responsible for *by itself*. To also estimate higher-order effects (the fraction of variance obtained by simultaneously varying 2 or more inputs together), we sum all first-order indices. Where this sum is close to one, there is (almost) no higher-order effect.\n\n\n```python\nfrom itertools import cycle\n\n# color = cycle(['b', 'r', 'g', 'm', 'c', 'k'])\nmarker = cycle(['o', 'v', '^', '<', '>', 's', '*', 'p', 'd', 'P', 'X', \n                '1', '2', '3', '4', 'x', 'D', '|', '_'])\nskip = 100\nx = range(0, analysis.N_qoi, skip)\n\nfig = plt.figure(figsize=[10, 5])\nax = fig.add_subplot(121, title=r'First-order Sobol indices',\n                      xlabel=\"days\", ylim=[0,1])\nax.set_ylabel(r'$S_i$', fontsize=14)\nsobols_first = results.sobols_first(QOI)\n\nfirst_order_contribution = 0\n\nfor param in sobols_first.keys():\n    ax.plot(x, sobols_first[param][0:-1:skip], label=param, marker=next(marker))\n    first_order_contribution += sobols_first[param][0:-1:skip]\n    \nax.plot(x, first_order_contribution, 'b*', label=r'First-order contribution all 27 parameters')\n\n# place legend on empty axes on the right\nhandles, labels = ax.get_legend_handles_labels()    # ax1 legend\nax2 = fig.add_subplot(122)                          # ax2\nax2.axis('off')                                     # make ax2 empty\nax2.legend(handles, labels, ncol=2)                 # place ax1 legend on ax1\nplt.tight_layout()\n```\n\n## References\n\n[1] T. Loudon and S. Pankavich. _Mathematical Analysis and Dynamic Active Subspaces for a Long term model of HIV_. arXiv:1604.04588, 2016\n\n[2] Edeling, W., Arabnejad, H., Sinclair, R., Suleimenova, D., Gopalakrishnan, K., Bosak, B., ... & Coveney, P. V. (2021). The impact of uncertainty on predictions of the CovidSim epidemiological code. Nature Computational Science, 1(2), 128-135.\n\n[3] Ma, X., & Zabaras, N. (2009). An adaptive hierarchical sparse grid collocation algorithm for the solution of stochastic differential equations. Journal of Computational Physics, 228(8), 3084-3113.\n", "meta": {"hexsha": "bad6e32585a39e9f915487bce08b755cd8d2704f", "size": 232853, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "easyvvuq_tutorial.ipynb", "max_stars_repo_name": "chmielar/INI_tutorial", "max_stars_repo_head_hexsha": "9ba97284f86298f70db99dc0f31119049ebb19e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-17T19:52:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T20:57:14.000Z", "max_issues_repo_path": "easyvvuq_tutorial.ipynb", "max_issues_repo_name": "chmielar/INI_tutorial", "max_issues_repo_head_hexsha": "9ba97284f86298f70db99dc0f31119049ebb19e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "easyvvuq_tutorial.ipynb", "max_forks_repo_name": "chmielar/INI_tutorial", "max_forks_repo_head_hexsha": "9ba97284f86298f70db99dc0f31119049ebb19e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-09T11:48:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T11:48:19.000Z", "avg_line_length": 187.1808681672, "max_line_length": 58592, "alphanum_fraction": 0.8729928324, "converted": true, "num_tokens": 12050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234844434674, "lm_q2_score": 0.10818894449799439, "lm_q1q2_score": 0.04736766065837281}}
{"text": "# Hello, world!\n\nThis is our hello world notebook!\n\n\n```\nprint(\"Hello world!\")\n```\n\n    Hello world!\n\n\nHere we continue with some formula\n\n\\begin{align}\nf(x) = \\sin(\\pi x),\n\\end{align}\n\nwhich we would like to plot\n\n\n```\n%matplotlib inline\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\n```\n\n\n```\nx = np.linspace(0., 2.) \nplt.plot(x, np.sin(np.pi * x))\nplt.show()\n```\n\nThis is the end of the file.\n\n\n", "meta": {"hexsha": "5386663dd01c8ee03107f37958a7d9e3639d9582", "size": 12972, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/test.ipynb", "max_stars_repo_name": "andsor/notebooks", "max_stars_repo_head_hexsha": "7c4c6695cd48655b4cf6f158cbafd27649c78df8", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-12-13T14:50:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-11T00:35:32.000Z", "max_issues_repo_path": "notebooks/test.ipynb", "max_issues_repo_name": "andsor/notebooks", "max_issues_repo_head_hexsha": "7c4c6695cd48655b4cf6f158cbafd27649c78df8", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/test.ipynb", "max_forks_repo_name": "andsor/notebooks", "max_forks_repo_head_hexsha": "7c4c6695cd48655b4cf6f158cbafd27649c78df8", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 135.125, "max_line_length": 11185, "alphanum_fraction": 0.8758865248, "converted": true, "num_tokens": 120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.096705803058668, "lm_q1q2_score": 0.04721983786229673}}
{"text": "```python\n# This cell is for the Google Colaboratory\n# https://stackoverflow.com/a/63519730\nif 'google.colab' in str(get_ipython()):\n  # https://colab.research.google.com/notebooks/io.ipynb\n  import google.colab.drive as gcdrive\n  # may need to visit a link for the Google Colab authorization code\n  gcdrive.mount(\"/content/drive/\")\n  import sys\n  sys.path.insert(0,\"/content/drive/My Drive/Colab Notebooks/nmisp/10_root_finding\")\n\n```\n\n\n```python\n# \uadf8\ub798\ud504, \uc218\ud559 \uae30\ub2a5 \ucd94\uac00\n# Add graph and math features\nimport pylab as py\n\n\n```\n\n# \uc21c\ucc28\ubc95<br>Sequential Method\n\n\n\n10\uc758 \uc81c\uacf1\uadfc\uc744 \uad6c\ud55c\ub2e4\uace0 \uc0dd\uac01\ud574 \ubcf4\uc790.<br>Let's try to find the square root of 10.\n\n\n\n$$\nx=\\sqrt{10} = 10 ^ \\frac{1}{2} = 10 ^ {0.5}\n$$\n\n\n\n\uacc4\uc0b0\uae30\ub77c\uba74 \uc774\ub7f0 \uc2dd\uc73c\ub85c \uad6c\ud560 \uc218 \uc788\uc744 \uac83\uc774\ub2e4.<br>With a calcuator, an engineer can find it as follows.\n\n\n\n\n```python\nprint('sqrt(10) =', 10 ** 0.5)\n\n\n```\n\n\uc870\uae08 \ub2e4\ub978 \ubc29\uc2dd\uc73c\ub85c \ud574 \ubcf4\uc790.<br>Let's try a different way.\n\n\n\n\uc591\ubcc0\uc744 \uc81c\uacf1\ud574 \ubcf4\uc790.<br>Let's square both sides.\n\n\n\n$$\n\\begin{align}\nx &= 10 ^ {0.5} \\\\\nx^2 &= \\left(10 ^ {0.5}\\right)^2 \\\\\nx^2 &= 10\n\\end{align}\n$$\n\n\n\n\uc774 \uad00\uacc4\ub97c \uadf8\ub798\ud504\ub85c \ud45c\ud604\ud574 \ubcf4\uba74 \ub2e4\uc74c\uacfc \uac19\uc744 \uac83\uc774\ub2e4.<br>An engineer can visualize this relationship as follows.\n\n\n\n\n```python\n# x \uc758 \ubc94\uc704\uc640 \uac04\uaca9\uc744 \uc9c0\uc815 \n# Specify range and interval of x\nx = py.arange(-5, 5+0.1, 0.2)\n\n\n```\n\n\uc704 `py.arange(-5, 5+0.1, 0.2)`\uc740 -5 \ubd80\ud130 5\uae4c\uc9c0\uc758 \ubc30\uc5f4\uc744 0.2 \uac04\uaca9\uc73c\ub85c \uc0dd\uc131\ud55c\ub2e4.<br>\nThe `py.arange(-5, 5+0.1, 0.2)` above would generate an array starting from -5 to 5 with interval of 0.2.\n\n\n\n`x`\uc758 \ud589\uacfc \uc5f4\uc758 \uac2f\uc218:<br>\nNumber of rows and columns of `x`:\n\n\n\n\n```python\nx.shape\n\n\n```\n\n`(50, 0)` \uc774\ub77c\uba74 1\ucc28\uc6d0 \ubc30\uc5f4\uc774\uace0 \uae38\uc774\ub294 50 \uc774\ub2e4.<br>\n`(50, 0)` means it is a 1-D array with length of 50.\n\n\n\n`x`\uc758 \uccab \ud56d\ubaa9<br>The first item of the `x`\n\n\n\n\n```python\nx[0]\n\n\n```\n\n\ucc98\uc74c \ub2e4\uc12f \ud56d\ubaa9<br>\nFirst five items of `x`\n\n\n\n\n```python\nx[:5]\n\n\n```\n\n\ub9c8\uc9c0\ub9c9 \ub2e4\uc12f \ud56d\ubaa9<br>\nLast five items of `x`\n\n\n\n\n```python\nx[-5:]\n\n\n```\n\n\ub9c8\uc9c0\ub9c9 \ud56d\ubaa9<br>\nLast item\n\n\n\n\n```python\nx[-1]\n\n\n```\n\n\uc704 \uac01 `x` \uc810\uc5d0 \ub300\ud574 \uc704 \ub4f1\uc2dd\uc744 \ud45c\uc2dc\ud574 \ubcf4\uc790.<br>\nLet's represent the equation above for each point of `x`.\n\n\n\n\n```python\n# y = x^2\npy.plot(x, x**2, 'k.')\n# y = 10\npy.plot(x, 10*py.ones_like(x), 'r.')\n# \ubaa8\ub208 \ud45c\uc2dc\n# Indicate grid\npy.grid()\n\n\n```\n\n`py.ones_like(x)` \ub294 `x`\uc640 \ud589, \uc5f4\uc758 \ud06c\uae30\uac00 \uac19\uc740 \ubc30\uc5f4\uc744 \ub9cc\ub4e4\uace0 1\ub85c \ucc44\uc6b4\ub2e4.<br>\n`py.ones_like(x)` would create an array with same number of rows and columns and fill it with ones.\n\n\n\n\ud55c\ubc88 \ud574\ub2f9 \ud568\uc218\ub97c \uc0ac\uc6a9\ud574 \ubcf4\uc790.<br>\nLet's try using the function.\n\n\n\n\n```python\nx.shape\n\n\n```\n\n\n```python\nn = py.ones_like(x)\nn.shape\n\n\n```\n\n\uccab\ubc88\uc9f8 \uadf8\ub9ac\uace0 \ub9c8\uc9c0\ub9c9 5 \ud56d\ubaa9<br>\nFirst and last items\n\n\n\n\n```python\nn[:5], n[-5:]\n\n\n```\n\n\ucd5c\uc18c\uac12\uacfc \ucd5c\ub300\uac12<br>\nMinimum and maximum values\n\n\n\n\n```python\nn.min(), n.max()\n\n\n```\n\n`py.zeros_like(x)` \ub294 `x`\uc640 \ud589, \uc5f4\uc758 \ud06c\uae30\uac00 \uac19\uc740 \ubc30\uc5f4\uc744 \ub9cc\ub4e4\uace0 0\uc73c\ub85c \ucc44\uc6b4\ub2e4.<br>\n`py.zeros_like(x)` would create an array with same number of rows and columns and fill it with zeros.\n\n\n\n\n```python\nz = py.zeros_like(x)\nz.shape\n\n\n```\n\n\n```python\nz[:5], z[-5:]\n\n\n```\n\n\uc774\uc81c \uc591\ubcc0\uc5d0\uc11c 10\uc744 \ube7c \ubcf4\uc790.<br>\nNow let's subtract 10 from both sides.\n\n\n\n$$\n\\begin{align}\nx^2-10 &= 10-10\\\\\nx^2-10 &= 0\n\\end{align}\n$$\n\n\n\n\uc774 \uad00\uacc4\ub3c4 \uadf8\ub824\ubcf4\uc790.<br>Let's plot this, too.\n\n\n\n\n```python\n# x \uc758 \ubc94\uc704\uc640 \uac04\uaca9\uc744 \uc9c0\uc815 \n# Specify range and interval of x\nx = py.arange(-5, 5, 0.2)\n# y = x^2\npy.plot(x, x**2 - 10, 'k.')\n# y = 0\npy.plot(x, py.zeros_like(x), 'r.')\n# \ubaa8\ub208 \ud45c\uc2dc\n# Indicate grid\npy.grid()\n\n\n```\n\n\uc704 \ubc29\uc815\uc2dd\uc744 \ub9cc\uc871\ud558\ub294 $x$ \ub294 10\uc758 \uc81c\uacf1\uadfc\uc77c \uac83\uc774\ub2e4.<br>$x$ satisfying the equation above would be the square root of 10.\n\n\n\n\uc774\ub7ec\ud55c $x$\ub97c \uc704 \ubc29\uc815\uc2dd\uc758 **\uadfc** \uc774\ub77c\uace0 \ubd80\ub978\ub2e4.<br>We call such $x$ a **root** of the equation above.\n\n\n\n\uadf8\ub9ac\uace0 \uadf8\ub7ec\ud55c x\ub294 \uc544\ub798\uc640 \uac19\uc740 \ud568\uc218\ub97c 0\uc73c\ub85c \ub9cc\ub4e4 \uac83\uc774\ub2e4.<br>And such $x$ would make following function zero.\n\n\n\n$$\nf(x) = x^2 - 10=0\n$$\n\n\n\n\n```python\n# \uc774 \ud568\uc218\ub97c 0\uc73c\ub85c \ub9cc\ub4dc\ub294 x \ub97c \ucc3e\uace0\uc790 \ud568\n# Intend to find x making the function below zero\ndef f(x):\n    return x ** 2 - 10\n\n\n```\n\n\ucef4\ud4e8\ud130\uc758 \uc5f0\uc0b0\ub2a5\ub825\uc744 \uc774\uc6a9\ud558\uc5ec \uadfc\uc744 \ucc3e\uc544 \ubcf4\ub3c4\ub85d \ud558\uc790.<br>Let's try to find the root using the computer's computation capability.\n\n\n\n\uc5ec\ub7ec \uac00\ub2a5\ud55c \ubc29\ubc95 \uac00\uc6b4\ub370 \ud558\ub098\ub294 $x$\ub97c \uc5b4\ub5a4 *\ucd08\uae30\uac12*\uc73c\ub85c\ubd80\ud130 \uc2dc\uc791\ud558\uc5ec \uc77c\uc815 *\uac04\uaca9* \uc73c\ub85c \uc99d\uac00\uc2dc\ud0a4\uba74\uc11c $f(x)=x^2-10$\uc744 \uacc4\uc0b0\ud574 \ubcf4\ub294 \uac83\uc774\ub2e4.<br>\nOne of the possible ways is to evaluate $f(x)=x^2-10$ starting from an *initial value* of $x$, increasing by a constant *interval*.\n\n\n\n\uadf8\ub807\uac8c \ubc18\ubcf5\ud558\ub2e4\uac00 $\\left|f(x)\\right|=\\left|x^2-10\\right|$ \uc774 \uc5b4\ub5a4 *\ub9cc\uc871\uc2a4\ub7ec\uc6b4 \uc218\uc900* \uc774\ud558\uac00 \ub418\uba74, \uadf8 \ub54c\uc758 $x$ \uac12\uc774 $\\sqrt{10}$\uc758 *\uadfc\uc0ac\uac12*\uc774 \ub420 \uac83\uc774\ub2e4.<br>\nDuring the iteration, the $x$ making $\\left|f(x)\\right|=\\left|x^2-10\\right|$ below a certain *satisfactory level* would be the *approximation* of $\\sqrt{10}.$\n\n\n\n$$\n\\left(\\left|x^2-10\\right|<\\epsilon \\right) \\equiv \\left(\\left|x^2-10\\right|\\approx 0 \\right) \n$$\n\n\n\n$$\n\\left(\\left|f(x)\\right|<\\epsilon \\right) \\equiv \\left(\\left|f(x)\\right|\\approx 0 \\right) \n$$\n\n\n\n\uc5ec\uae30\uc11c $\\epsilon$ \uac12\uc758 \uc758\ubbf8\ub294, \uc608\ub97c \ub4e4\uc5b4 $\\left|y\\right| < \\epsilon$ \uc774\uba74 $y \\approx 0$ \uc774\ub77c\uace0 \ubcf4\ub294 \uac83\uc774\ub2e4.<br>\nHere, $\\epsilon$ means that if $\\left|y\\right| < \\epsilon$ then $y \\approx 0$.\n\n\n\n## \uc65c $\\epsilon$ \uc774 \ud544\uc694\ud55c\uac00?<br>Why do we need $\\epsilon$?\n\n\n\n\uc704\uc758 \uadf8\ub798\ud504\uc758 \uc77c\ubd80\ub97c \ud655\ub300\ud574\ubcf4\uc790.<br>Let's zoom into the plot above. \n\n\n\n\n```python\n# x \uc758 \ubc94\uc704\uc640 \uac04\uaca9\uc744 \uc9c0\uc815 \n# Specify range and interval of x\nx = py.arange(2.8, 3.5, 0.2)\n# y = f(x) = x * x - 10\npy.plot(x, f(x), 'ko')\n# y = 0\npy.plot(x, py.zeros_like(x), 'ro')\n# x \ucd95 \uc774\ub984\ud45c\n# x axis label\npy.xlabel('x')\n# \ubaa8\ub208 \ud45c\uc2dc\n# Indicate grid\npy.grid()\n\n\n```\n\n\uc704 \uadf8\ub9bc\uc5d0\uc11c $|x^2-10|$\uc774 $x=3.0$\uacfc $x=3.2$ \uc0ac\uc774 \uc5b4\ub518\uac00\uc5d0\uc11c 0\uc774 \ub420 \uac83\uc784\uc744 \uc9d0\uc791\ud560 \uc218 \uc788\ub2e4.<br>\nWe can see that $|x^2-10|$ will be zero somewhere between $x=3.0$ and $x=3.2$.\n\n\n\n\uadf8 \uac12\uc744 \ub354 \uc815\ud655\ud788 \uc54c\uace0 \uc2f6\ub2e4\uba74 \uc810\uc744 \uadf8\ub9ac\ub294 \uac04\uaca9\uc744 \uc904\uc774\uba74 \ub420 \uac83\uc774\ub2e4.<br>\nTo find more precise value, we can reduce the interval of the dots.\n\n\n\n\n```python\n# x \uc758 \ubc94\uc704\uc640 \uac04\uaca9\uc744 \uc9c0\uc815 \n# Specify range and interval of x\nx = py.arange(2.8, 3.5, 0.05)\n# y = f(x) = x * x - 10\npy.plot(x, f(x), 'ko')\n# y = 0\npy.plot(x, py.zeros_like(x), 'ro')\n# x \ucd95 \uc774\ub984\ud45c\n# x axis label\npy.xlabel('x')\n# \ubaa8\ub208 \ud45c\uc2dc\n# Indicate grid\npy.grid()\n\n\n```\n\n\uc0ac\ub78c\uc758 \uacbd\uc6b0\ub294 \uadf8 \uac04\uaca9\uc744 \ubb34\ud55c\ud788 \uc904\uc5ec\uc11c \uc810\uc774 **\uc5f0\uc18d\uc801**\uc774 \ub418\ub294 \uac83\uc744 \uc0dd\uac01\ud560 \uc218 \uc788\uc9c0\ub9cc, \ucef4\ud4e8\ud130\ub294 **\uc774\uc0b0\uc801**\uc778 \uadf8\ub798\ud504\uae4c\uc9c0\ub9cc \uadf8\ub9b4 \uc218 \uc788\ub2e4.<br>\nA person may think infinitely small interval so that the dots become **continuous**, however, computer plots can only be **discrete**.\n\n\n\n\ucef4\ud4e8\ud130\ub294 **\uc815\ubc00\ub3c4**\ub77c\ub294 \uc5b4\ub5a4 \uc218\uc900 \uc774\ud558\ub85c \uc810\uc744 \uadf8\ub9ac\ub294 \uac04\uaca9\uc744 \uc904\uc77c \uc218 \uc5c6\uae30 \ub54c\ubb38\uc774\ub2e4.<br>Because computers are unable to make the interval of the dots smaller than a certain level called **precision**.\n\n\n\n\uc0ac\ub78c\uc740 $x^2-10$ \uc744 0\uc73c\ub85c \ub9cc\ub4e4 \uc218 \uc788\ub294 $x$ \ub97c \uc0dd\uac01\ud560 \uc218 \uc788\uc9c0\ub9cc, \ucef4\ud4e8\ud130\uac00 \ucc3e\uc544 \ub0bc \uc218 \uc788\ub294 \ucd5c\uc120\uc758 $\\sqrt{10}$\uc758 \uadfc\uc0ac\uac12\uc73c\ub85c\ub3c4 $x^2-10$ \uc774 \uc815\ud655\ud788 0\uc774 \ub418\uc9c0 \uc54a\uc744 \uc218 \uc788\ub294 \uac83\uc774\ub2e4.<br>\nWhile a person may think about $x$ making $x^2-10$ exact zero, even computer's best approximation of $\\sqrt{10}$ may not exactly make $x^2-10$ zero.\n\n\n\n\uadf8\ub798\uc11c \ucef4\ud4e8\ud130\uc758 \uacc4\uc0b0 \uacb0\uacfc \uc808\ub300\uac12\uc774 **$\\epsilon$** \uac12\ubcf4\ub2e4 \uc791\uc73c\uba74, \uadf8 \uacb0\uacfc\ub294 0\uacfc \uac19\uc740 \uac83\uc73c\ub85c \uc0dd\uac01\ud560 \uac83\uc774\ub2e4.<br>\nHence, if a computation result has absolute value smaller then **$\\epsilon$**, we would regard that the result is the same as zero.\n\n\n\n\n```python\nimport plot_root_finding\n\n\nx_start = 2.8\nx_end = 3.5\nx_interval = 0.05\n\nplot_root_finding.plot(f, x_start, x_end, x_interval);\n\n\n```\n\n## \uc21c\ucc28\ubc95 \uad6c\ud604<br>Implementing Sequantial Method\n\n\n\n\uc544\ub798 python \ud504\ub85c\uadf8\ub7a8\uc740 \uc21c\ucc28\ubc95\uc73c\ub85c $\\sqrt{10}$\uc744 \uacc4\uc0b0\ud55c\ub2e4<br>Following python script calculates $\\sqrt{10}$ using sequential method.\n\n\n\n### \uc2e4\ud589\uc744 \uc704\ud55c \uc900\ube44<br>Prepare to run\n\n\n\n\uc785\uc2e4\ub860 \uac12 : `y_i` \uc758 \uc808\ub300\uac12\uc774 \uc774 \uac12 \ubcf4\ub2e4 \uc791\uc73c\uba74 `y_i == 0`\uc778 \uac83\uc73c\ub85c \ubd04<br>\nepsilon : if absolute value of `y_i` is smaller than this, we would think that `y_i == 0`.\n\n\n\n\n```python\nepsilon = 1e-3\n\n\n```\n\n`sqrt_10` \uc758 \ucd08\uae30\uac12<br>Initial value for `sqrt_10`\n\n\n\n\n```python\nsqrt_10 = 'Not Found'\n\n\n```\n\n`x_i` \uc758 \ucd08\uae30\uac12<br>Initial value of `x_i`\n\n\n\n\n```python\nx_init = 0\n\n\n```\n\n`x_i` \uc758 \ub9c8\uc9c0\ub9c9 \uac12<br>Final value of `x_i`\n\n\n\n\n```python\nx_final = 4\n\n\n```\n\n`i` \ubc88\uc9f8 `x` \uac12\uacfc `i+1` \ubc88\uc9f8 `x` \uac12 \uc0ac\uc774\uc758 \uac04\uaca9<br>The interval between `i`'th and `(i+1)`'st `x`s\n\n\n\n\n```python\nx_interval = 1e-5\n\n\n```\n\n\uc77c\ub828\uc758 `x_i` \uac12\uc744 \ubbf8\ub9ac \uc900\ube44<br>Prepare a sequence of `x_i` values in advance\n\n\n\n\n```python\nx_array = py.arange(x_init, x_final+x_interval*0.5, x_interval)\n\n\n```\n\n\uba87 \ubc88 \ubc18\ubcf5\ud588\ub294\uc9c0 \uce21\uc815\ud558\ub294 \ubcc0\uc218 \uc120\uc5b8<br>\nLet's declare a variable to count the number of iterations\n\n\n\n\n```python\ncounter = 0\n\n\n```\n\n### \uc21c\ucc28\ubc95\uc744 \uc704\ud55c `for` \ubc18\ubcf5\ubb38<br>The `for` loop for the sequential method\n\n\n\n\n```python\n# x_i \uc5d0 \uad00\ud55c \ubc18\ubcf5\ubb38\n# x_i loop\nfor x_i in x_array:\n\n    # \uadfc\uc744 \ucc3e\uace0\uc790 \ud558\ub294 \ud568\uc218\ub97c \uacc4\uc0b0\n    # Evaluate the function whose root we are looking for\n\n    y_i = x_i ** 2 - 10\n    \n    # \ud55c\ubc88 \ubc18\ubcf5\ud560 \ub54c \ub9c8\ub2e4 1\uc529 \uc99d\uac00\n    # Increase counter variable by one\n    counter += 1\n\n    # \uc808\ub300\uac12\uc774 \uc785\uc2e4\ub860 \uac12 \ubcf4\ub2e4 \uc791\uc740\uc9c0 \ud655\uc778\n    # Check if absolute value is smaller than epsilon\n\n    if abs(y_i) < epsilon:\n\n        # \uc704 \uc870\uac74\ubb38\uc774 \ucc38\uc774\uba74 \uadfc\uc744 \ucc3e\uc740 \uac83\uc784\n        # if true, we found the root\n\n        sqrt_10 = x_i\n        break\n\n\n```\n\n\uc544\ub798 \uc140\uc740 `isinstance(sqrt_10, float)` \ud568\uc218\uc758 \uacb0\uacfc\uac12\uc774 \ucc38\uc778\uc9c0 \ud655\uc778\ud55c\ub2e4.  \uac70\uc9d3\uc774\ub77c\uba74 `sqrt_10` \uac12\uc744 \ud654\uba74\uc5d0 \ud45c\uc2dc\ud558\uace0 \uc2e4\ud589\uc744 \uc911\ub2e8\uc2dc\ud0ac \uac83\uc774\ub2e4.<br>\nFollowing cell tests whether the returned result of `isinstance(sqrt_10, float)` is `True`.  If not, it will present the value of `sqrt_10` and stop execution by raising an exception.\n\n\n\n\n```python\nassert isinstance(sqrt_10, float), sqrt_10\n\n\n```\n\n### \ud6c4\ucc98\ub9ac<br>Postprocessing\n\n\n\n\uc21c\ucc28\ubc95\uc73c\ub85c \ucc3e\uc740 10\uc758 \uc81c\uacf1\uadfc<br>The square root of 10 that we just found using the sequential method\n\n\n\n\n```python\nprint('sqrt_10 =', sqrt_10)\n\n\n```\n\n\uc704 \uacb0\uacfc\ub97c \uc81c\uacf1\ud574\ubcf4\uc790<br>What is the square of the value above?\n\n\n\n\n```python\nprint('sqrt_10**2 =', sqrt_10**2)\n\n\n```\n\n\uc544\ub798 \uc5f0\uc0b0\uc758 \uacb0\uacfc\ub294 0\uc778\uac00?<br>Is the result of the following calculation zero?\n\n\n\n\n```python\nprint('sqrt_10 ** 2 - 10 =', sqrt_10 ** 2 - 10)\n\n\n```\n\n\uc704 \uacb0\uacfc\uc758 \uc758\ubbf8\ub294 \ubb34\uc5c7\uc778\uac00?<br>What would be the result above?\n\n\n\n\ubc18\ubcf5 \ud69f\uc218\ub294 \uba87 \ubc88\uc774\uc5c8\ub294\uac00?<br>Number of iterations?\n\n\n\n\n```python\nprint('counter =', counter)\n\n\n```\n\n`epsilon`, `x_init`, `x_interval` \ub4f1 \ub9e4\uac1c \ubcc0\uc218\ub97c \ubc14\uafb8\uc5b4 \ubcf4\uba74\uc11c \uacb0\uacfc\uac00 \uc5b4\ub5bb\uac8c \ub2ec\ub77c\uc9c0\ub294\uc9c0 \ud655\uc778 \ud574 \ubcf4\ub77c.<br>\nSee how the results change as you change parameters such as `epsilon`, `x_init`, and `x_interval`.\n\n\n\n## \uc21c\ucc28\ubc95\uc744 \ud568\uc218\ub85c \uad6c\ud604<br>Implementing Sequantial Method in a Function\n\n\n\n\uc704 \ud504\ub85c\uadf8\ub7a8\uc73c\ub85c \uc5b4\ub5a4 \uc218\uc758 \uc81c\uacf1\uadfc\uc744 \uad6c\ud560 \uc218 \uc788\uc5c8\ub2e4. \ub2e4\ub978 \ud568\uc218\uc758 \uadfc\uc744 \uad6c\ud558\uae30\uc5d0 \ub354 \ud3b8\ub9ac\ud55c \ud615\ud0dc\ub85c \ubc14\uafb8\uba74 \ub354 \uc88b\uc744 \uac83\uc774\ub2e4.<br>\nWe could the sqare root of a number.  It would be even better modify so that we can easily find roots of other functions.\n\n\n\n\n```python\ndef sequential(f, x_init, x_interval, epsilon, x_final, b_print_counter=True):\n    # result \uc758 \ucd08\uae30\uac12\n    # Initial value for sqrt_10\n    result = 'Not Found'\n\n    # \uc77c\ub828\uc758 x_i \uac12\uc744 \ubbf8\ub9ac \uc900\ube44\ud55c\ub2e4\n    # Prepare a series of x_i values in advance\n    x_array = py.arange(x_init, x_final+x_interval*0.5, x_interval)\n\n    # \uba87\ubc88 \ubc18\ubcf5\ud588\ub294\uc9c0 \uce21\uc815\ud558\ub294 \ubcc0\uc218\ub97c \uc120\uc5b8\n    # Declare a variable to count the number of iterations\n    counter = 0\n\n    # x_i \uc5d0 \uad00\ud55c \ubc18\ubcf5\ubb38\n    # x_i loop\n    for x_i in x_array:\n        # x = x_i \uc5d0\uc11c\uc758 \ud568\uc218 f(x)\uac12\uc744 \uacc4\uc0b0\ud558\uc5ec y_i\uc5d0 \uc800\uc7a5\n        # Evaluate the function f(x) at x = x_i and store in y_i\n        y_i = f(x_i)\n\n        # counter \ubcc0\uc218 1 \uc99d\uac00\n        # Increase the counter by one\n        counter += 1\n\n        # y_i \uc758 \uc808\ub300\uac12\uc774 epsilon \ubcf4\ub2e4 \uc791\uc740\uc9c0 \ud655\uc778\n        # Check if absolute value is smaller than epsilon\n        if abs(y_i) < epsilon:\n            # y_i\uc758 \uc808\ub300\uac12\uc774 epsilon \ubcf4\ub2e4 \uc791\ub2e4\uba74 \uadfc\uc744 \ucc3e\uc740 \uac83\uc784\n            # if the absolute value of y_i is smaller than epsilon\n            # we found the root\n            result = x_i\n\n            # \uadfc\uc744 \ucc3e\uc558\uc73c\ubbc0\ub85c for \ubc18\ubcf5\ubb38\uc744 \uc911\ub2e8\ud568\n            # As we found a root, break out of the for loop\n            break\n\n    # \ubc18\ubcf5 \ud69f\uc218\n    # Number of iterations\n    if b_print_counter:\n        print('counter =', counter)\n\n    # f(x)\uc758 \uc808\ub300\uac12\uc744 epsilon \ubcf4\ub2e4 \uc791\uac8c \ub9cc\ub4dc\ub294 \uacb0\uacfc\uac12\uc744 \ubc18\ud658\n    # return the result that would make \n    # the absolute value of f(x) smaller than epsilon\n    return result\n\n\n```\n\n### \uc801\uc6a9\uc0ac\ub840<br>Application example\n\n\n\n#### 10\uc758 \uc81c\uacf1\uadfc<br>square root of 10\n\n\n\n\uc6b0\ub9ac\ub294 \uc544\ub798 \ud568\uc218\ub97c 0\uc73c\ub85c \ub9cc\ub4dc\ub294 $x$\ub97c \ucc3e\uace0\uc790 \ud55c\ub2e4.<br>We want to find $x$ that makes the following function zero.\n\n\n\n\n```python\ndef find_sqrt_10(x):\n    return (x ** 2) - 10\n\n\n```\n\n\n```python\nsqrt_10_function = sequential(find_sqrt_10, x_init, x_interval, epsilon, x_final)\n\n\n```\n\n\uacb0\uacfc\uac12<br>Result\n\n\n\n\n```python\nsqrt_10_function\n\n\n```\n\n\uc544\ub798 \uc140\uc740 \ud568\uc218\ub85c \uad6c\ud55c \uacb0\uacfc\uc640 \uc774\uc804\uc5d0 \uad6c\ud55c \uacb0\uacfc\ub97c \ube44\uad50<br>Following cell compares results from function with the previous one.\n\n\n\n\n```python\nassert abs(sqrt_10_function - sqrt_10) < epsilon, f\"previous = {sqrt_10}, new = {sqrt_10_function}\"\n\n\n```\n\n\uacc4\uc0b0 \uc2dc\uac04:<br>Computation time.\n\n\n\n\n```python\n%timeit sqrt_10_function = sequential(find_sqrt_10, x_init, x_interval, epsilon, x_final, b_print_counter=False)\n\n\n```\n\n#### 5\uc758 \uc81c\uacf1\uadfc<br>square root of 5\n\n\n\n\uc6b0\ub9ac\ub294 \uc544\ub798 \ud568\uc218\ub97c 0\uc73c\ub85c \ub9cc\ub4dc\ub294 $x$\ub97c \ucc3e\uace0\uc790 \ud55c\ub2e4.<br>We want to find $x$ that makes the following function zero.\n\n\n\n\n```python\ndef find_sqrt_5(x):\n    return (x ** 2) - 5\n\n\n```\n\n\ub9e4\uac1c\ubcc0\uc218\ub294 \ub2e4\uc74c\uacfc \uac19\ub2e4.<br>\nParameters are as follows.\n\n\n\n\n```python\n# y_i \uc758 \uc808\ub300\uac12\uc774 \uc774 \uac12 \ubcf4\ub2e4 \uc791\uc73c\uba74 y_i = 0\uc73c\ub85c \ubcf8\ub2e4\n# If absolute value of y_i is smaller than this, we would think y_i = 0.\nepsilon = 1e-3\n# \uc21c\ucc28\ubc95\uc758 \ub9e4\uac1c\ubcc0\uc218\n# Parameters of the Sequantial Method\n# x_i \uc758 \ucd08\uae30\uac12\n# Initial value of x_i\nx_init = 0\n# x_i \uc758 \ub9c8\uc9c0\ub9c9 \uac12\n# Final value of x_i\nx_final = 4\n# i \ubc88\uc9f8 x \uac12\uacfc i+1 \ubc88\uc9f8 x \uac12 \uc0ac\uc774\uc758 \uac04\uaca9\n# The interval between i'th and (i+1)'th x's\nx_interval = 1.0 / (2**12)\n\n\n```\n\n\uc81c\uacf1\uadfc\uc744 \uad6c\ud558\uae30 \uc704\ud574 \uc21c\ucc28\ubc95 \ud568\uc218\ub294 \ub2e4\uc74c\uacfc \uac19\uc774 \ud638\ucd9c\ud560 \uc218 \uc788\ub2e4.<br>To find the square root of five, we can call the function of the sequential method as follows.\n\n\n\n\n```python\nsqrt_5 = sequential(find_sqrt_5, x_init, x_interval, epsilon, x_final)\n\n\n```\n\n\uc21c\ucc28\ubc95\uc73c\ub85c \ucc3e\uc740 5\uc758 \uc81c\uacf1\uadfc<br>\nSquare root of 5 that we just found using the sequential method\n\n\n\n\n```python\nprint('sqrt_5 =', sqrt_5)\n\n\n```\n\n\uc544\ub798 \uc5f0\uc0b0\uc758 \uacb0\uacfc\ub294 0\uc778\uac00?<br>\nIs the result of the following calculation zero?\n\n\n\n\n```python\nprint('sqrt_5 ** 2 - 5 =', find_sqrt_5(sqrt_5))\n\n\n```\n\n$\\epsilon$ \uac12\uacfc \ube44\uad50<br>Check with the $\\epsilon$\n\n\n\n\n```python\nassert abs(find_sqrt_5(sqrt_5)) < epsilon\n\n\n```\n\n\uacc4\uc0b0 \uc2dc\uac04<br>Computatin time\n\n\n\n\n```python\n%timeit sqrt_5 = sequential(find_sqrt_5, x_init, x_interval, epsilon, x_final, b_print_counter=False)\n\n\n```\n\n## \uc5f0\uc2b5 \ubb38\uc81c<br>Exercises\n\n\n\n\ub3c4\uc804 \uacfc\uc81c 1: \ub2e4\uc74c \ub9e4\uac1c \ubcc0\uc218\uac12\uc744 \ud558\ub098\uc529 \ubc14\uafb8\uc5b4 \ubcf4\uace0 \uadf8 \uc601\ud5a5\uc5d0 \ub300\ud55c \uc758\uacac\uc744 \uc801\uc73c\uc2dc\uc624.<br>Try this 1: Change one parameter value at a time and write down your opinion on its influence.\n\n\n\n|\ub9e4\uac1c\ubcc0\uc218<br>Parameter | \ud604\uc7ac\uac12<br>Current value | \ubc14\uafb8\uc5b4 \ubcf8 \uac12<br>New value | \uc601\ud5a5<br>Influence |\n|:------:|:------:|:----------:|:----------:|\n|`epsilon` | `1e-3` |   ?   |   ?   |\n|`x_init` | `0` |   ?   |   ?   |\n|`x_interval` | `1.0 / (2**12)` |   ?   |   ?   |\n\n\n\n\ub3c4\uc804 \uacfc\uc81c 2: $sin^2(\\theta)=0.5$ \uc778 $\\theta$(\ub3c4)\ub97c \uc21c\ucc28\ubc95\uc73c\ub85c \uad6c\ud574 \ubcf4\uc2dc\uc624.<br>Try this 2: Find $\\theta$(degree) satisfying $sin^2(\\theta)=0.5$ using the sequential method.\n\n\n\n\ub3c4\uc804 \uacfc\uc81c 3: \uad00\uc2ec \uc788\ub294 $f(x)=0$ \ubb38\uc81c\ub97c \uc815\ud558\uc5ec \uadf8 \uadfc\uc744 \uc21c\ucc28\ubc95\uc73c\ub85c \uad6c\ud574 \ubcf4\uc2dc\uc624.<br>Try this 3: Find a root of a $f(x)=0$ problem of your choice using the sequential method.\n\n\n\n## Final Bell<br>\ub9c8\uc9c0\ub9c9 \uc885\n\n\n\n\uba54\ub274\uc758 Cell/Run All \uba85\ub839\uc744 \uc2e4\ud589\uc2dc\ucf30\uc744 \ub54c \ubb38\uc11c\uc758 \ubaa8\ub4e0 \uc140\uc774 \uc2e4\ud589\ub418\uc5c8\uc73c\uba74 \uc885\uc18c\ub9ac\ub97c \ub0c4<br>When all cells executed by Cell/Run All command of the menu, generate the bell sound.\n\n\n\n\n```python\n# stackoverfow.com/a/24634221\nimport os\nos.system(\"printf '\\a'\");\n\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "d6e62ec5247d65884326e7cf8acc708e2bf98a36", "size": 38866, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "10_root_finding/10_sequential.ipynb", "max_stars_repo_name": "kangwonlee/2109eca-nmisp-template", "max_stars_repo_head_hexsha": "2e078870757fa06222df62d0ff8f4f4f288af51a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "10_root_finding/10_sequential.ipynb", "max_issues_repo_name": "kangwonlee/2109eca-nmisp-template", "max_issues_repo_head_hexsha": "2e078870757fa06222df62d0ff8f4f4f288af51a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "10_root_finding/10_sequential.ipynb", "max_forks_repo_name": "kangwonlee/2109eca-nmisp-template", "max_forks_repo_head_hexsha": "2e078870757fa06222df62d0ff8f4f4f288af51a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.441495778, "max_line_length": 196, "alphanum_fraction": 0.4215766994, "converted": true, "num_tokens": 5644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.1066906024668249, "lm_q1q2_score": 0.04712235906769227}}
{"text": "```python\n# This cell is for the Google Colaboratory\n# https://stackoverflow.com/a/63519730\nif 'google.colab' in str(get_ipython()):\n  # https://colab.research.google.com/notebooks/io.ipynb\n  import google.colab.drive as gcdrive\n  # may need to visit a link for the Google Colab authorization code\n  gcdrive.mount(\"/content/drive/\")\n  import sys\n  sys.path.insert(0,\"/content/drive/My Drive/Colab Notebooks/nmisp/10_root_finding\")\n\n```\n\n\n```python\n# \uadf8\ub798\ud504, \uc218\ud559 \uae30\ub2a5 \ucd94\uac00\n# Add graph and math features\nimport pylab as py\n\n\n```\n\n# \uc21c\ucc28\ubc95<br>Sequential Method\n\n\n\n10\uc758 \uc81c\uacf1\uadfc\uc744 \uad6c\ud55c\ub2e4\uace0 \uc0dd\uac01\ud574 \ubcf4\uc790.<br>Let's try to find the square root of 10.\n\n\n\n$$\nx=\\sqrt{10} = 10 ^ \\frac{1}{2} = 10 ^ {0.5}\n$$\n\n\n\n\uacc4\uc0b0\uae30\ub77c\uba74 \uc774\ub7f0 \uc2dd\uc73c\ub85c \uad6c\ud560 \uc218 \uc788\uc744 \uac83\uc774\ub2e4.<br>With a calcuator, an engineer can find it as follows.\n\n\n\n\n```python\nprint('sqrt(10) =', 10 ** 0.5)\n\n\n```\n\n\uc870\uae08 \ub2e4\ub978 \ubc29\uc2dd\uc73c\ub85c \ud574 \ubcf4\uc790.<br>Let's try a different way.\n\n\n\n\uc591\ubcc0\uc744 \uc81c\uacf1\ud574 \ubcf4\uc790.<br>Let's square both sides.\n\n\n\n$$\n\\begin{align}\nx &= 10 ^ {0.5} \\\\\nx^2 &= \\left(10 ^ {0.5}\\right)^2 \\\\\nx^2 &= 10\n\\end{align}\n$$\n\n\n\n\uc774 \uad00\uacc4\ub97c \uadf8\ub798\ud504\ub85c \ud45c\ud604\ud574 \ubcf4\uba74 \ub2e4\uc74c\uacfc \uac19\uc744 \uac83\uc774\ub2e4.<br>An engineer can visualize this relationship as follows.\n\n\n\n\n```python\n# x \uc758 \ubc94\uc704\uc640 \uac04\uaca9\uc744 \uc9c0\uc815 \n# Specify range and interval of x\nx = py.arange(-5, 5+0.1, 0.2)\n\n\n```\n\n\uc704 `py.arange(-5, 5+0.1, 0.2)`\uc740 -5 \ubd80\ud130 5\uae4c\uc9c0\uc758 \ubc30\uc5f4\uc744 0.2 \uac04\uaca9\uc73c\ub85c \uc0dd\uc131\ud55c\ub2e4.<br>\nThe `py.arange(-5, 5+0.1, 0.2)` above would generate an array starting from -5 to 5 with interval of 0.2.\n\n\n\n`x`\uc758 \ud589\uacfc \uc5f4\uc758 \uac2f\uc218:<br>\nNumber of rows and columns of `x`:\n\n\n\n\n```python\nx.shape\n\n\n```\n\n`(50, 0)` \uc774\ub77c\uba74 1\ucc28\uc6d0 \ubc30\uc5f4\uc774\uace0 \uae38\uc774\ub294 50 \uc774\ub2e4.<br>\n`(50, 0)` means it is a 1-D array with length of 50.\n\n\n\n`x`\uc758 \uccab \ud56d\ubaa9<br>The first item of the `x`\n\n\n\n\n```python\nx[0]\n\n\n```\n\n\ucc98\uc74c \ub2e4\uc12f \ud56d\ubaa9<br>\nFirst five items of `x`\n\n\n\n\n```python\nx[:5]\n\n\n```\n\n\ub9c8\uc9c0\ub9c9 \ub2e4\uc12f \ud56d\ubaa9<br>\nLast five items of `x`\n\n\n\n\n```python\nx[-5:]\n\n\n```\n\n\ub9c8\uc9c0\ub9c9 \ud56d\ubaa9<br>\nLast item\n\n\n\n\n```python\nx[-1]\n\n\n```\n\n\uc704 \uac01 `x` \uc810\uc5d0 \ub300\ud574 \uc704 \ub4f1\uc2dd\uc744 \ud45c\uc2dc\ud574 \ubcf4\uc790.<br>\nLet's represent the equation above for each point of `x`.\n\n\n\n\n```python\n# y = x^2\npy.plot(x, x**2, 'k.')\n# y = 10\npy.plot(x, 10*py.ones_like(x), 'r.')\n# \ubaa8\ub208 \ud45c\uc2dc\n# Indicate grid\npy.grid()\n\n\n```\n\n`py.ones_like(x)` \ub294 `x`\uc640 \ud589, \uc5f4\uc758 \ud06c\uae30\uac00 \uac19\uc740 \ubc30\uc5f4\uc744 \ub9cc\ub4e4\uace0 1\ub85c \ucc44\uc6b4\ub2e4.<br>\n`py.ones_like(x)` would create an array with same number of rows and columns and fill it with ones.\n\n\n\n\ud55c\ubc88 \ud574\ub2f9 \ud568\uc218\ub97c \uc0ac\uc6a9\ud574 \ubcf4\uc790.<br>\nLet's try using the function.\n\n\n\n\n```python\nx.shape\n\n\n```\n\n\n```python\nn = py.ones_like(x)\nn.shape\n\n\n```\n\n\uccab\ubc88\uc9f8 \uadf8\ub9ac\uace0 \ub9c8\uc9c0\ub9c9 5 \ud56d\ubaa9<br>\nFirst and last items\n\n\n\n\n```python\nn[:5], n[-5:]\n\n\n```\n\n\ucd5c\uc18c\uac12\uacfc \ucd5c\ub300\uac12<br>\nMinimum and maximum values\n\n\n\n\n```python\nn.min(), n.max()\n\n\n```\n\n`py.zeros_like(x)` \ub294 `x`\uc640 \ud589, \uc5f4\uc758 \ud06c\uae30\uac00 \uac19\uc740 \ubc30\uc5f4\uc744 \ub9cc\ub4e4\uace0 0\uc73c\ub85c \ucc44\uc6b4\ub2e4.<br>\n`py.zeros_like(x)` would create an array with same number of rows and columns and fill it with zeros.\n\n\n\n\n```python\nz = py.zeros_like(x)\nz.shape\n\n\n```\n\n\n```python\nz[:5], z[-5:]\n\n\n```\n\n\uc774\uc81c \uc591\ubcc0\uc5d0\uc11c 10\uc744 \ube7c \ubcf4\uc790.<br>\nNow let's subtract 10 from both sides.\n\n\n\n$$\n\\begin{align}\nx^2-10 &= 10-10\\\\\nx^2-10 &= 0\n\\end{align}\n$$\n\n\n\n\uc774 \uad00\uacc4\ub3c4 \uadf8\ub824\ubcf4\uc790.<br>Let's plot this, too.\n\n\n\n\n```python\n# x \uc758 \ubc94\uc704\uc640 \uac04\uaca9\uc744 \uc9c0\uc815 \n# Specify range and interval of x\nx = py.arange(-5, 5, 0.2)\n# y = x^2\npy.plot(x, x**2 - 10, 'k.')\n# y = 0\npy.plot(x, py.zeros_like(x), 'r.')\n# \ubaa8\ub208 \ud45c\uc2dc\n# Indicate grid\npy.grid()\n\n\n```\n\n\uc704 \ubc29\uc815\uc2dd\uc744 \ub9cc\uc871\ud558\ub294 $x$ \ub294 10\uc758 \uc81c\uacf1\uadfc\uc77c \uac83\uc774\ub2e4.<br>$x$ satisfying the equation above would be the square root of 10.\n\n\n\n\uc774\ub7ec\ud55c $x$\ub97c \uc704 \ubc29\uc815\uc2dd\uc758 **\uadfc** \uc774\ub77c\uace0 \ubd80\ub978\ub2e4.<br>We call such $x$ a **root** of the equation above.\n\n\n\n\uadf8\ub9ac\uace0 \uadf8\ub7ec\ud55c x\ub294 \uc544\ub798\uc640 \uac19\uc740 \ud568\uc218\ub97c 0\uc73c\ub85c \ub9cc\ub4e4 \uac83\uc774\ub2e4.<br>And such $x$ would make following function zero.\n\n\n\n$$\nf(x) = x^2 - 10=0\n$$\n\n\n\n\n```python\n# \uc774 \ud568\uc218\ub97c 0\uc73c\ub85c \ub9cc\ub4dc\ub294 x \ub97c \ucc3e\uace0\uc790 \ud568\n# Intend to find x making the function below zero\ndef f(x):\n    return x ** 2 - 10\n\n\n```\n\n\ucef4\ud4e8\ud130\uc758 \uc5f0\uc0b0\ub2a5\ub825\uc744 \uc774\uc6a9\ud558\uc5ec \uadfc\uc744 \ucc3e\uc544 \ubcf4\ub3c4\ub85d \ud558\uc790.<br>Let's try to find the root using the computer's computation capability.\n\n\n\n\uc5ec\ub7ec \uac00\ub2a5\ud55c \ubc29\ubc95 \uac00\uc6b4\ub370 \ud558\ub098\ub294 $x$\ub97c \uc5b4\ub5a4 *\ucd08\uae30\uac12*\uc73c\ub85c\ubd80\ud130 \uc2dc\uc791\ud558\uc5ec \uc77c\uc815 *\uac04\uaca9* \uc73c\ub85c \uc99d\uac00\uc2dc\ud0a4\uba74\uc11c $f(x)=x^2-10$\uc744 \uacc4\uc0b0\ud574 \ubcf4\ub294 \uac83\uc774\ub2e4.<br>\nOne of the possible ways is to evaluate $f(x)=x^2-10$ starting from an *initial value* of $x$, increasing by a constant *interval*.\n\n\n\n\uadf8\ub807\uac8c \ubc18\ubcf5\ud558\ub2e4\uac00 $\\left|f(x)\\right|=\\left|x^2-10\\right|$ \uc774 \uc5b4\ub5a4 *\ub9cc\uc871\uc2a4\ub7ec\uc6b4 \uc218\uc900* \uc774\ud558\uac00 \ub418\uba74, \uadf8 \ub54c\uc758 $x$ \uac12\uc774 $\\sqrt{10}$\uc758 *\uadfc\uc0ac\uac12*\uc774 \ub420 \uac83\uc774\ub2e4.<br>\nDuring the iteration, the $x$ making $\\left|f(x)\\right|=\\left|x^2-10\\right|$ below a certain *satisfactory level* would be the *approximation* of $\\sqrt{10}.$\n\n\n\n$$\n\\left(\\left|x^2-10\\right|<\\epsilon \\right) \\equiv \\left(\\left|x^2-10\\right|\\approx 0 \\right) \n$$\n\n\n\n$$\n\\left(\\left|f(x)\\right|<\\epsilon \\right) \\equiv \\left(\\left|f(x)\\right|\\approx 0 \\right) \n$$\n\n\n\n\uc5ec\uae30\uc11c $\\epsilon$ \uac12\uc758 \uc758\ubbf8\ub294, \uc608\ub97c \ub4e4\uc5b4 $\\left|y\\right| < \\epsilon$ \uc774\uba74 $y \\approx 0$ \uc774\ub77c\uace0 \ubcf4\ub294 \uac83\uc774\ub2e4.<br>\nHere, $\\epsilon$ means that if $\\left|y\\right| < \\epsilon$ then $y \\approx 0$.\n\n\n\n## \uc65c $\\epsilon$ \uc774 \ud544\uc694\ud55c\uac00?<br>Why do we need $\\epsilon$?\n\n\n\n\uc704\uc758 \uadf8\ub798\ud504\uc758 \uc77c\ubd80\ub97c \ud655\ub300\ud574\ubcf4\uc790.<br>Let's zoom into the plot above. \n\n\n\n\n```python\n# x \uc758 \ubc94\uc704\uc640 \uac04\uaca9\uc744 \uc9c0\uc815 \n# Specify range and interval of x\nx = py.arange(2.8, 3.5, 0.2)\n# y = f(x) = x * x - 10\npy.plot(x, f(x), 'ko')\n# y = 0\npy.plot(x, py.zeros_like(x), 'ro')\n# x \ucd95 \uc774\ub984\ud45c\n# x axis label\npy.xlabel('x')\n# \ubaa8\ub208 \ud45c\uc2dc\n# Indicate grid\npy.grid()\n\n\n```\n\n\uc704 \uadf8\ub9bc\uc5d0\uc11c $|x^2-10|$\uc774 $x=3.0$\uacfc $x=3.2$ \uc0ac\uc774 \uc5b4\ub518\uac00\uc5d0\uc11c 0\uc774 \ub420 \uac83\uc784\uc744 \uc9d0\uc791\ud560 \uc218 \uc788\ub2e4.<br>\nWe can see that $|x^2-10|$ will be zero somewhere between $x=3.0$ and $x=3.2$.\n\n\n\n\uadf8 \uac12\uc744 \ub354 \uc815\ud655\ud788 \uc54c\uace0 \uc2f6\ub2e4\uba74 \uc810\uc744 \uadf8\ub9ac\ub294 \uac04\uaca9\uc744 \uc904\uc774\uba74 \ub420 \uac83\uc774\ub2e4.<br>\nTo find more precise value, we can reduce the interval of the dots.\n\n\n\n\n```python\n# x \uc758 \ubc94\uc704\uc640 \uac04\uaca9\uc744 \uc9c0\uc815 \n# Specify range and interval of x\nx = py.arange(2.8, 3.5, 0.05)\n# y = f(x) = x * x - 10\npy.plot(x, f(x), 'ko')\n# y = 0\npy.plot(x, py.zeros_like(x), 'ro')\n# x \ucd95 \uc774\ub984\ud45c\n# x axis label\npy.xlabel('x')\n# \ubaa8\ub208 \ud45c\uc2dc\n# Indicate grid\npy.grid()\n\n\n```\n\n\uc0ac\ub78c\uc758 \uacbd\uc6b0\ub294 \uadf8 \uac04\uaca9\uc744 \ubb34\ud55c\ud788 \uc904\uc5ec\uc11c \uc810\uc774 **\uc5f0\uc18d\uc801**\uc774 \ub418\ub294 \uac83\uc744 \uc0dd\uac01\ud560 \uc218 \uc788\uc9c0\ub9cc, \ucef4\ud4e8\ud130\ub294 **\uc774\uc0b0\uc801**\uc778 \uadf8\ub798\ud504\uae4c\uc9c0\ub9cc \uadf8\ub9b4 \uc218 \uc788\ub2e4.<br>\nA person may think infinitely small interval so that the dots become **continuous**, however, computer plots can only be **discrete**.\n\n\n\n\ucef4\ud4e8\ud130\ub294 **\uc815\ubc00\ub3c4**\ub77c\ub294 \uc5b4\ub5a4 \uc218\uc900 \uc774\ud558\ub85c \uc810\uc744 \uadf8\ub9ac\ub294 \uac04\uaca9\uc744 \uc904\uc77c \uc218 \uc5c6\uae30 \ub54c\ubb38\uc774\ub2e4.<br>Because computers are unable to make the interval of the dots smaller than a certain level called **precision**.\n\n\n\n\uc0ac\ub78c\uc740 $x^2-10$ \uc744 0\uc73c\ub85c \ub9cc\ub4e4 \uc218 \uc788\ub294 $x$ \ub97c \uc0dd\uac01\ud560 \uc218 \uc788\uc9c0\ub9cc, \ucef4\ud4e8\ud130\uac00 \ucc3e\uc544 \ub0bc \uc218 \uc788\ub294 \ucd5c\uc120\uc758 $\\sqrt{10}$\uc758 \uadfc\uc0ac\uac12\uc73c\ub85c\ub3c4 $x^2-10$ \uc774 \uc815\ud655\ud788 0\uc774 \ub418\uc9c0 \uc54a\uc744 \uc218 \uc788\ub294 \uac83\uc774\ub2e4.<br>\nWhile a person may think about $x$ making $x^2-10$ exact zero, even computer's best approximation of $\\sqrt{10}$ may not exactly make $x^2-10$ zero.\n\n\n\n\uadf8\ub798\uc11c \ucef4\ud4e8\ud130\uc758 \uacc4\uc0b0 \uacb0\uacfc \uc808\ub300\uac12\uc774 **$\\epsilon$** \uac12\ubcf4\ub2e4 \uc791\uc73c\uba74, \uadf8 \uacb0\uacfc\ub294 0\uacfc \uac19\uc740 \uac83\uc73c\ub85c \uc0dd\uac01\ud560 \uac83\uc774\ub2e4.<br>\nHence, if a computation result has absolute value smaller then **$\\epsilon$**, we would regard that the result is the same as zero.\n\n\n\n\n```python\nimport plot_root_finding\n\n\nx_start = 2.8\nx_end = 3.5\nx_interval = 0.05\n\nplot_root_finding.plot(f, x_start, x_end, x_interval);\n\n\n```\n\n## \uc21c\ucc28\ubc95 \uad6c\ud604<br>Implementing Sequantial Method\n\n\n\n\uc544\ub798 python \ud504\ub85c\uadf8\ub7a8\uc740 \uc21c\ucc28\ubc95\uc73c\ub85c $\\sqrt{10}$\uc744 \uacc4\uc0b0\ud55c\ub2e4<br>Following python script calculates $\\sqrt{10}$ using sequential method.\n\n\n\n### \uc2e4\ud589\uc744 \uc704\ud55c \uc900\ube44<br>Prepare to run\n\n\n\n\uc785\uc2e4\ub860 \uac12 : `y_i` \uc758 \uc808\ub300\uac12\uc774 \uc774 \uac12 \ubcf4\ub2e4 \uc791\uc73c\uba74 `y_i == 0`\uc778 \uac83\uc73c\ub85c \ubd04<br>\nepsilon : if absolute value of `y_i` is smaller than this, we would think that `y_i == 0`.\n\n\n\n\n```python\nepsilon = 1e-3\n\n\n```\n\n`sqrt_10` \uc758 \ucd08\uae30\uac12<br>Initial value for `sqrt_10`\n\n\n\n\n```python\nsqrt_10 = 'Not Found'\n\n\n```\n\n`x_i` \uc758 \ucd08\uae30\uac12<br>Initial value of `x_i`\n\n\n\n\n```python\nx_init = 0\n\n\n```\n\n`x_i` \uc758 \ub9c8\uc9c0\ub9c9 \uac12<br>Final value of `x_i`\n\n\n\n\n```python\nx_final = 4\n\n\n```\n\n`i` \ubc88\uc9f8 `x` \uac12\uacfc `i+1` \ubc88\uc9f8 `x` \uac12 \uc0ac\uc774\uc758 \uac04\uaca9<br>The interval between `i`'th and `(i+1)`'st `x`s\n\n\n\n\n```python\nx_interval = 1e-5\n\n\n```\n\n\uc77c\ub828\uc758 `x_i` \uac12\uc744 \ubbf8\ub9ac \uc900\ube44<br>Prepare a sequence of `x_i` values in advance\n\n\n\n\n```python\nx_array = py.arange(x_init, x_final+x_interval*0.5, x_interval)\n\n\n```\n\n\uba87 \ubc88 \ubc18\ubcf5\ud588\ub294\uc9c0 \uce21\uc815\ud558\ub294 \ubcc0\uc218 \uc120\uc5b8<br>\nLet's declare a variable to count the number of iterations\n\n\n\n\n```python\ncounter = 0\n\n\n```\n\n### \uc21c\ucc28\ubc95\uc744 \uc704\ud55c `for` \ubc18\ubcf5\ubb38<br>The `for` loop for the sequential method\n\n\n\n\n```python\n# x_i \uc5d0 \uad00\ud55c \ubc18\ubcf5\ubb38\n# x_i loop\nfor x_i in x_array:\n\n    # \uadfc\uc744 \ucc3e\uace0\uc790 \ud558\ub294 \ud568\uc218\ub97c \uacc4\uc0b0\n    # Evaluate the function whose root we are looking for\n\n    y_i = x_i ** 2 - 10\n    \n    # \ud55c\ubc88 \ubc18\ubcf5\ud560 \ub54c \ub9c8\ub2e4 1\uc529 \uc99d\uac00\n    # Increase counter variable by one\n    counter += 1\n\n    # \uc808\ub300\uac12\uc774 \uc785\uc2e4\ub860 \uac12 \ubcf4\ub2e4 \uc791\uc740\uc9c0 \ud655\uc778\n    # Check if absolute value is smaller than epsilon\n\n    if abs(y_i) < epsilon:\n\n        # \uc704 \uc870\uac74\ubb38\uc774 \ucc38\uc774\uba74 \uadfc\uc744 \ucc3e\uc740 \uac83\uc784\n        # if true, we found the root\n\n        sqrt_10 = x_i\n        break\n\n\n```\n\n\uc544\ub798 \uc140\uc740 `isinstance(sqrt_10, float)` \ud568\uc218\uc758 \uacb0\uacfc\uac12\uc774 \ucc38\uc778\uc9c0 \ud655\uc778\ud55c\ub2e4.  \uac70\uc9d3\uc774\ub77c\uba74 `sqrt_10` \uac12\uc744 \ud654\uba74\uc5d0 \ud45c\uc2dc\ud558\uace0 \uc2e4\ud589\uc744 \uc911\ub2e8\uc2dc\ud0ac \uac83\uc774\ub2e4.<br>\nFollowing cell tests whether the returned result of `isinstance(sqrt_10, float)` is `True`.  If not, it will present the value of `sqrt_10` and stop execution by raising an exception.\n\n\n\n\n```python\nassert isinstance(sqrt_10, float), sqrt_10\n\n\n```\n\n### \ud6c4\ucc98\ub9ac<br>Postprocessing\n\n\n\n\uc21c\ucc28\ubc95\uc73c\ub85c \ucc3e\uc740 10\uc758 \uc81c\uacf1\uadfc<br>The square root of 10 that we just found using the sequential method\n\n\n\n\n```python\nprint('sqrt_10 =', sqrt_10)\n\n\n```\n\n\uc704 \uacb0\uacfc\ub97c \uc81c\uacf1\ud574\ubcf4\uc790<br>What is the square of the value above?\n\n\n\n\n```python\nprint('sqrt_10**2 =', sqrt_10**2)\n\n\n```\n\n\uc544\ub798 \uc5f0\uc0b0\uc758 \uacb0\uacfc\ub294 0\uc778\uac00?<br>Is the result of the following calculation zero?\n\n\n\n\n```python\nprint('sqrt_10 ** 2 - 10 =', sqrt_10 ** 2 - 10)\n\n\n```\n\n\uc704 \uacb0\uacfc\uc758 \uc758\ubbf8\ub294 \ubb34\uc5c7\uc778\uac00?<br>What would be the result above?\n\n\n\n\ubc18\ubcf5 \ud69f\uc218\ub294 \uba87 \ubc88\uc774\uc5c8\ub294\uac00?<br>Number of iterations?\n\n\n\n\n```python\nprint('counter =', counter)\n\n\n```\n\n`epsilon`, `x_init`, `x_interval` \ub4f1 \ub9e4\uac1c \ubcc0\uc218\ub97c \ubc14\uafb8\uc5b4 \ubcf4\uba74\uc11c \uacb0\uacfc\uac00 \uc5b4\ub5bb\uac8c \ub2ec\ub77c\uc9c0\ub294\uc9c0 \ud655\uc778 \ud574 \ubcf4\ub77c.<br>\nSee how the results change as you change parameters such as `epsilon`, `x_init`, and `x_interval`.\n\n\n\n## \uc21c\ucc28\ubc95\uc744 \ud568\uc218\ub85c \uad6c\ud604<br>Implementing Sequantial Method in a Function\n\n\n\n\uc704 \ud504\ub85c\uadf8\ub7a8\uc73c\ub85c \uc5b4\ub5a4 \uc218\uc758 \uc81c\uacf1\uadfc\uc744 \uad6c\ud560 \uc218 \uc788\uc5c8\ub2e4. \ub2e4\ub978 \ud568\uc218\uc758 \uadfc\uc744 \uad6c\ud558\uae30\uc5d0 \ub354 \ud3b8\ub9ac\ud55c \ud615\ud0dc\ub85c \ubc14\uafb8\uba74 \ub354 \uc88b\uc744 \uac83\uc774\ub2e4.<br>\nWe could the sqare root of a number.  It would be even better modify so that we can easily find roots of other functions.\n\n\n\n\n```python\ndef sequential(f, x_init, x_interval, epsilon, x_final, b_print_counter=True):\n    # result \uc758 \ucd08\uae30\uac12\n    # Initial value for sqrt_10\n    result = 'Not Found'\n\n    # \uc77c\ub828\uc758 x_i \uac12\uc744 \ubbf8\ub9ac \uc900\ube44\ud55c\ub2e4\n    # Prepare a series of x_i values in advance\n    x_array = py.arange(x_init, x_final+x_interval*0.5, x_interval)\n\n    # \uba87\ubc88 \ubc18\ubcf5\ud588\ub294\uc9c0 \uce21\uc815\ud558\ub294 \ubcc0\uc218\ub97c \uc120\uc5b8\n    # Declare a variable to count the number of iterations\n    counter = 0\n\n    # x_i \uc5d0 \uad00\ud55c \ubc18\ubcf5\ubb38\n    # x_i loop\n    for x_i in x_array:\n        # x = x_i \uc5d0\uc11c\uc758 \ud568\uc218 f(x)\uac12\uc744 \uacc4\uc0b0\ud558\uc5ec y_i\uc5d0 \uc800\uc7a5\n        # Evaluate the function f(x) at x = x_i and store in y_i\n        y_i = f(x_i)\n\n        # counter \ubcc0\uc218 1 \uc99d\uac00\n        # Increase the counter by one\n        counter += 1\n\n        # y_i \uc758 \uc808\ub300\uac12\uc774 epsilon \ubcf4\ub2e4 \uc791\uc740\uc9c0 \ud655\uc778\n        # Check if absolute value is smaller than epsilon\n        if abs(y_i) < epsilon:\n            # y_i\uc758 \uc808\ub300\uac12\uc774 epsilon \ubcf4\ub2e4 \uc791\ub2e4\uba74 \uadfc\uc744 \ucc3e\uc740 \uac83\uc784\n            # if the absolute value of y_i is smaller than epsilon\n            # we found the root\n            result = x_i\n\n            # \uadfc\uc744 \ucc3e\uc558\uc73c\ubbc0\ub85c for \ubc18\ubcf5\ubb38\uc744 \uc911\ub2e8\ud568\n            # As we found a root, break out of the for loop\n            break\n\n    # \ubc18\ubcf5 \ud69f\uc218\n    # Number of iterations\n    if b_print_counter:\n        print('counter =', counter)\n\n    # f(x)\uc758 \uc808\ub300\uac12\uc744 epsilon \ubcf4\ub2e4 \uc791\uac8c \ub9cc\ub4dc\ub294 \uacb0\uacfc\uac12\uc744 \ubc18\ud658\n    # return the result that would make \n    # the absolute value of f(x) smaller than epsilon\n    return result\n\n\n```\n\n### \uc801\uc6a9\uc0ac\ub840<br>Application example\n\n\n\n#### 10\uc758 \uc81c\uacf1\uadfc<br>square root of 10\n\n\n\n\uc6b0\ub9ac\ub294 \uc544\ub798 \ud568\uc218\ub97c 0\uc73c\ub85c \ub9cc\ub4dc\ub294 $x$\ub97c \ucc3e\uace0\uc790 \ud55c\ub2e4.<br>We want to find $x$ that makes the following function zero.\n\n\n\n\n```python\ndef find_sqrt_10(x):\n    return (x ** 2) - 10\n\n\n```\n\n\n```python\nsqrt_10_function = sequential(find_sqrt_10, x_init, x_interval, epsilon, x_final)\n\n\n```\n\n\uacb0\uacfc\uac12<br>Result\n\n\n\n\n```python\nsqrt_10_function\n\n\n```\n\n\uc544\ub798 \uc140\uc740 \ud568\uc218\ub85c \uad6c\ud55c \uacb0\uacfc\uc640 \uc774\uc804\uc5d0 \uad6c\ud55c \uacb0\uacfc\ub97c \ube44\uad50<br>Following cell compares results from function with the previous one.\n\n\n\n\n```python\nassert abs(sqrt_10_function - sqrt_10) < epsilon, f\"previous = {sqrt_10}, new = {sqrt_10_function}\"\n\n\n```\n\n\uacc4\uc0b0 \uc2dc\uac04:<br>Computation time.\n\n\n\n\n```python\n%timeit sqrt_10_function = sequential(find_sqrt_10, x_init, x_interval, epsilon, x_final, b_print_counter=False)\n\n\n```\n\n#### 5\uc758 \uc81c\uacf1\uadfc<br>square root of 5\n\n\n\n\uc6b0\ub9ac\ub294 \uc544\ub798 \ud568\uc218\ub97c 0\uc73c\ub85c \ub9cc\ub4dc\ub294 $x$\ub97c \ucc3e\uace0\uc790 \ud55c\ub2e4.<br>We want to find $x$ that makes the following function zero.\n\n\n\n\n```python\ndef find_sqrt_5(x):\n    return (x ** 2) - 5\n\n\n```\n\n\ub9e4\uac1c\ubcc0\uc218\ub294 \ub2e4\uc74c\uacfc \uac19\ub2e4.<br>\nParameters are as follows.\n\n\n\n\n```python\n# y_i \uc758 \uc808\ub300\uac12\uc774 \uc774 \uac12 \ubcf4\ub2e4 \uc791\uc73c\uba74 y_i = 0\uc73c\ub85c \ubcf8\ub2e4\n# If absolute value of y_i is smaller than this, we would think y_i = 0.\nepsilon = 1e-3\n# \uc21c\ucc28\ubc95\uc758 \ub9e4\uac1c\ubcc0\uc218\n# Parameters of the Sequantial Method\n# x_i \uc758 \ucd08\uae30\uac12\n# Initial value of x_i\nx_init = 0\n# x_i \uc758 \ub9c8\uc9c0\ub9c9 \uac12\n# Final value of x_i\nx_final = 4\n# i \ubc88\uc9f8 x \uac12\uacfc i+1 \ubc88\uc9f8 x \uac12 \uc0ac\uc774\uc758 \uac04\uaca9\n# The interval between i'th and (i+1)'th x's\nx_interval = 1.0 / (2**12)\n\n\n```\n\n\uc81c\uacf1\uadfc\uc744 \uad6c\ud558\uae30 \uc704\ud574 \uc21c\ucc28\ubc95 \ud568\uc218\ub294 \ub2e4\uc74c\uacfc \uac19\uc774 \ud638\ucd9c\ud560 \uc218 \uc788\ub2e4.<br>To find the square root of five, we can call the function of the sequential method as follows.\n\n\n\n\n```python\nsqrt_5 = sequential(find_sqrt_5, x_init, x_interval, epsilon, x_final)\n\n\n```\n\n\uc21c\ucc28\ubc95\uc73c\ub85c \ucc3e\uc740 5\uc758 \uc81c\uacf1\uadfc<br>\nSquare root of 5 that we just found using the sequential method\n\n\n\n\n```python\nprint('sqrt_5 =', sqrt_5)\n\n\n```\n\n\uc544\ub798 \uc5f0\uc0b0\uc758 \uacb0\uacfc\ub294 0\uc778\uac00?<br>\nIs the result of the following calculation zero?\n\n\n\n\n```python\nprint('sqrt_5 ** 2 - 5 =', find_sqrt_5(sqrt_5))\n\n\n```\n\n$\\epsilon$ \uac12\uacfc \ube44\uad50<br>Check with the $\\epsilon$\n\n\n\n\n```python\nassert abs(find_sqrt_5(sqrt_5)) < epsilon\n\n\n```\n\n\uacc4\uc0b0 \uc2dc\uac04<br>Computatin time\n\n\n\n\n```python\n%timeit sqrt_5 = sequential(find_sqrt_5, x_init, x_interval, epsilon, x_final, b_print_counter=False)\n\n\n```\n\n## \uc5f0\uc2b5 \ubb38\uc81c<br>Exercises\n\n\n\n\ub3c4\uc804 \uacfc\uc81c 1: \ub2e4\uc74c \ub9e4\uac1c \ubcc0\uc218\uac12\uc744 \ud558\ub098\uc529 \ubc14\uafb8\uc5b4 \ubcf4\uace0 \uadf8 \uc601\ud5a5\uc5d0 \ub300\ud55c \uc758\uacac\uc744 \uc801\uc73c\uc2dc\uc624.<br>Try this 1: Change one parameter value at a time and write down your opinion on its influence.\n\n\n\n|\ub9e4\uac1c\ubcc0\uc218<br>Parameter | \ud604\uc7ac\uac12<br>Current value | \ubc14\uafb8\uc5b4 \ubcf8 \uac12<br>New value | \uc601\ud5a5<br>Influence |\n|:------:|:------:|:----------:|:----------:|\n|`epsilon` | `1e-3` |   ?   |   ?   |\n|`x_init` | `0` |   ?   |   ?   |\n|`x_interval` | `1.0 / (2**12)` |   ?   |   ?   |\n\n\n\n\ub3c4\uc804 \uacfc\uc81c 2: $sin^2(\\theta)=0.5$ \uc778 $\\theta$(\ub3c4)\ub97c \uc21c\ucc28\ubc95\uc73c\ub85c \uad6c\ud574 \ubcf4\uc2dc\uc624.<br>Try this 2: Find $\\theta$(degree) satisfying $sin^2(\\theta)=0.5$ using the sequential method.\n\n\n\n\ub3c4\uc804 \uacfc\uc81c 3: \uad00\uc2ec \uc788\ub294 $f(x)=0$ \ubb38\uc81c\ub97c \uc815\ud558\uc5ec \uadf8 \uadfc\uc744 \uc21c\ucc28\ubc95\uc73c\ub85c \uad6c\ud574 \ubcf4\uc2dc\uc624.<br>Try this 3: Find a root of a $f(x)=0$ problem of your choice using the sequential method.\n\n\n\n## Final Bell<br>\ub9c8\uc9c0\ub9c9 \uc885\n\n\n\n\uba54\ub274\uc758 Cell/Run All \uba85\ub839\uc744 \uc2e4\ud589\uc2dc\ucf30\uc744 \ub54c \ubb38\uc11c\uc758 \ubaa8\ub4e0 \uc140\uc774 \uc2e4\ud589\ub418\uc5c8\uc73c\uba74 \uc885\uc18c\ub9ac\ub97c \ub0c4<br>When all cells executed by Cell/Run All command of the menu, generate the bell sound.\n\n\n\n\n```python\n# stackoverfow.com/a/24634221\nimport os\nos.system(\"printf '\\a'\");\n\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "e4006aa4bd0f09003638cf0645b4b7fcdba794fc", "size": 29551, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "10_root_finding/10_sequential.ipynb", "max_stars_repo_name": "kangwon-naver/nmisp", "max_stars_repo_head_hexsha": "141f8148b3ce783d3df27ee0c9986f530cada8fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-05-14T11:00:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-27T01:04:29.000Z", "max_issues_repo_path": "10_root_finding/10_sequential.ipynb", "max_issues_repo_name": "kangwon-naver/nmisp", "max_issues_repo_head_hexsha": "141f8148b3ce783d3df27ee0c9986f530cada8fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 170, "max_issues_repo_issues_event_min_datetime": "2018-07-12T06:06:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T09:06:55.000Z", "max_forks_repo_path": "10_root_finding/10_sequential.ipynb", "max_forks_repo_name": "kangwon-naver/nmisp", "max_forks_repo_head_hexsha": "141f8148b3ce783d3df27ee0c9986f530cada8fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 57, "max_forks_repo_forks_event_min_datetime": "2018-08-28T08:38:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-02T03:40:47.000Z", "avg_line_length": 21.3827785818, "max_line_length": 192, "alphanum_fraction": 0.4889513045, "converted": true, "num_tokens": 5644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.11436851410729884, "lm_q1q2_score": 0.047018139247443094}}
{"text": "Project for the course of Microeconometrics _ Summer 2020, M.Sc. Economics, Bonn University _ [Solmaz Ahmadi](https://github.com/solmazahmadi).\n\n---\n\n __A replication of Bronzini, R., & Lachini, E. (2014).__\n\nIn this notebook, we replicate the key results of the following paper:\n\n>  ***Bronzini, R., & Lachini, E. (2014). Are incentives for R&D effective? Evidence from a regression discontinuity approach. American Economic Journal: Economic Policy, 6(4), 100-134.***\n\n\n__Downloading and viewing this notebook:__\n\n- The best way to view this notebook is by downloading it and the repository it is located in from [GitHub](https://github.com/solmazahmadi/microeconometrics-course-project-solmazahmadi). Other viewing options like *MyBinder*  or *NBViewer* may have issues with displaying images or coloring of certain parts (missing images can be viewed in the folder [files]() on GitHub).\n\n- The original paper, as well as the data and code provided by the authors can be accessed [here](https://www.aeaweb.org/articles?id=10.1257/pol.6.4.100).\n\n__Information about replication and individual contributions:__\n\n- for the ease of camparision, we preserve the paper's original structure. All sections are titled the same and tables and figures are named and labeled as they appear in Bronzini, R., & Iachini, E. (2014).\n\n- The tables in my replication appear transposed compared to the original tables to suit my workflow in Python.\n\n- For transparency, all sections in the replication that constitute independent contributions by me and are not part of results presented (or include deviations from the methods used) in the paper are marked as extensions.\n\n<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><ul class=\"toc-item\"><li><span><a href=\"#Replication-of-Bronzini,-R.,-&amp;-Iachini,-E.-(2014).\" data-toc-modified-id=\"Replication-of-Bronzini,-R.,-&amp;-Iachini,-E.-(2014).-0.1\"><span class=\"toc-item-num\">0.1&nbsp;&nbsp;</span><strong>Replication of Bronzini, R., &amp; Iachini, E. (2014).</strong></a></span></li></ul></li><li><span><a href=\"#Table-of-Contents\" data-toc-modified-id=\"Table-of-Contents-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span><strong>Table of Contents</strong></a></span></li></ul></div>\n\n# 1. Introduction\n\nBronzini and Lachini (2014) study the effects of a unique R&D subsidy program executed in northern Italy on investment expenditures of firms. The public R&D funding is a government policy that aims to trigger marginal projects, those that would not be carried out without the subventions. The economic rationale behind the R&D subsidies is firstly to conquer market failure of knowledge as a public good the positive externalities of which cannot be fully internalized by the firm. secondly, the government grants aid to overcome the firm's liquidity constraints. Firms were asked to present a proposal for their new projects and an independent technical committee scores them. Only firms whose scores were exceeded a specific threshold were awarded public grants. To estimate the causal impact of subsidies, Bronzini and Lachini (2014) apply a sharp regression discontinuity design (RDD) comparing the private investment spending of funded and nonfunded firms with scores close to the threshold. Among nonexperimental econometric methods, the regression discontinuity controls preferably for the endogeneity of treatment since it can be shown as a randomized experiment by arguing that the agents had been randomly drawn just below or just above the cutoff. The paper finds for the whole sample of firms, the investment expenditures do not increase significantly. since the overall impact hides the considerable heterogeneity in the program\u2019s effect, Bronzini and Lachini (2014)  divide the sample by small and large firms and demonstrate that although the subsidy did not affect large enterprises' investment spending, small companies raised their investments\u2014by roughly the amount of the grant they gained.\n\n\nMain variables for the sample as a whole are presented in the table 1.1:\n\n| main variables   |            main outcome variables            |      main covriates    |  \n|----------------- |----------------------------------------------|----------------------- |\n| treatment effect | investment (total, tangible, and intangible) |      score             |   \n|        -         |              labor costs                     |       ROA              |   \n|        -         |             employmentand                    | Net worth assets/Debts |   \n|        -         |                 wages                        |   Cash flow/Sales      |   \n|        -         |            service costs                     |  Interest costs/Debts  |   \n\n\n(((\n By letting the outcome variable be a function of the score, the average treatment\neffect of the program is assessed through the estimated value of the discontinuity at\nthe threshold. ))))\n\nThe rest of notbook is structured as follows. In the second section, we review the theoretical framework for the paper. Sectin 3 describes the identification strategy utilized by the authors to unravel causal effects of gorment subsidy program on investment expenditure of companies. Section 4 discusses the paper emprical method used for the estimation. In section 5, we replicate the key results of the paper by Bronzini and Lachini (2014) and discuss it in detail. Section 6 conducts and evaluates the results using multiple robustness checks. finaly, last section colcludes remarks.\n\n# add from 13.06\n\n\n```python\nimport numpy as np\nimport pandas as pd\nimport scipy\nimport pandas.io.formats.style\nimport seaborn as sns\nimport statsmodels as sm\nimport statsmodels.formula.api as smf\nimport statsmodels.formula.api as smf\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\nfrom IPython.display import HTML\nfrom statsmodels.formula.api import ols\nfrom statsmodels.formula.api import ols\nfrom statsmodels.sandbox.regression.predstd import wls_prediction_std\n```\n\n\n```python\nimport econtools.metrics as mt\n```\n\n\n```python\nfrom auxiliary_get_key_varaibles import get_key_variables\n```\n\n\n```python\ndf = get_key_variables()\n```\n\n\n```python\ndf\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>K</th>\n      <th>KT</th>\n      <th>KINT</th>\n      <th>SALES</th>\n      <th>ASSETS</th>\n      <th>INV</th>\n      <th>INVT</th>\n      <th>INVINT</th>\n      <th>LINV</th>\n      <th>LINVT</th>\n      <th>...</th>\n      <th>AGE</th>\n      <th>WAGE</th>\n      <th>LEMPL</th>\n      <th>LWAGE</th>\n      <th>SIZE</th>\n      <th>score</th>\n      <th>treatment</th>\n      <th>T</th>\n      <th>s</th>\n      <th>streat</th>\n    </tr>\n    <tr>\n      <th>Firm</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>21237</td>\n      <td>19339</td>\n      <td>1898</td>\n      <td>80721</td>\n      <td>159591</td>\n      <td>9707</td>\n      <td>9318</td>\n      <td>389</td>\n      <td>11.640</td>\n      <td>10.875</td>\n      <td>...</td>\n      <td>1974.1232</td>\n      <td>49.900</td>\n      <td>7.424</td>\n      <td>3.910</td>\n      <td>large</td>\n      <td>85</td>\n      <td>treated</td>\n      <td>1.0</td>\n      <td>10</td>\n      <td>10.0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1646</td>\n      <td>1487</td>\n      <td>159</td>\n      <td>3707</td>\n      <td>3381</td>\n      <td>373</td>\n      <td>75</td>\n      <td>298</td>\n      <td>11.554</td>\n      <td>10.682</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>small</td>\n      <td>82</td>\n      <td>treated</td>\n      <td>1.0</td>\n      <td>7</td>\n      <td>7.0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>6931</td>\n      <td>6728</td>\n      <td>203</td>\n      <td>25301</td>\n      <td>21127</td>\n      <td>1545</td>\n      <td>1216</td>\n      <td>329</td>\n      <td>11.566</td>\n      <td>10.708</td>\n      <td>...</td>\n      <td>1967.1016</td>\n      <td>38.683</td>\n      <td>5.293</td>\n      <td>3.655</td>\n      <td>large</td>\n      <td>89</td>\n      <td>treated</td>\n      <td>1.0</td>\n      <td>14</td>\n      <td>14.0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1131</td>\n      <td>1115</td>\n      <td>16</td>\n      <td>12143</td>\n      <td>10842</td>\n      <td>-114</td>\n      <td>-114</td>\n      <td>0</td>\n      <td>11.550</td>\n      <td>10.678</td>\n      <td>...</td>\n      <td>1966.1020</td>\n      <td>37.397</td>\n      <td>5.242</td>\n      <td>3.622</td>\n      <td>large</td>\n      <td>70</td>\n      <td>untreated</td>\n      <td>0.0</td>\n      <td>-5</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1691</td>\n      <td>1649</td>\n      <td>42</td>\n      <td>5263</td>\n      <td>7688</td>\n      <td>235</td>\n      <td>219</td>\n      <td>16</td>\n      <td>11.553</td>\n      <td>10.686</td>\n      <td>...</td>\n      <td>1969.1120</td>\n      <td>23.836</td>\n      <td>4.804</td>\n      <td>3.171</td>\n      <td>small</td>\n      <td>85</td>\n      <td>treated</td>\n      <td>1.0</td>\n      <td>10</td>\n      <td>10.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>352</th>\n      <td>1126</td>\n      <td>985</td>\n      <td>141</td>\n      <td>30938</td>\n      <td>22915</td>\n      <td>-63</td>\n      <td>-49</td>\n      <td>-14</td>\n      <td>11.550</td>\n      <td>10.680</td>\n      <td>...</td>\n      <td>1995.0107</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>large</td>\n      <td>77</td>\n      <td>treated</td>\n      <td>1.0</td>\n      <td>2</td>\n      <td>2.0</td>\n    </tr>\n    <tr>\n      <th>353</th>\n      <td>494378</td>\n      <td>185503</td>\n      <td>308875</td>\n      <td>773040</td>\n      <td>1123660</td>\n      <td>-103863</td>\n      <td>14641</td>\n      <td>-118504</td>\n      <td>0.000</td>\n      <td>10.971</td>\n      <td>...</td>\n      <td>1995.0316</td>\n      <td>65.707</td>\n      <td>8.153</td>\n      <td>4.185</td>\n      <td>large</td>\n      <td>88</td>\n      <td>treated</td>\n      <td>1.0</td>\n      <td>13</td>\n      <td>13.0</td>\n    </tr>\n    <tr>\n      <th>354</th>\n      <td>41568</td>\n      <td>40187</td>\n      <td>1381</td>\n      <td>161396</td>\n      <td>272656</td>\n      <td>-10065</td>\n      <td>-10486</td>\n      <td>421</td>\n      <td>11.449</td>\n      <td>10.405</td>\n      <td>...</td>\n      <td>1995.0718</td>\n      <td>41.551</td>\n      <td>7.762</td>\n      <td>3.727</td>\n      <td>large</td>\n      <td>84</td>\n      <td>treated</td>\n      <td>1.0</td>\n      <td>9</td>\n      <td>9.0</td>\n    </tr>\n    <tr>\n      <th>355</th>\n      <td>16316</td>\n      <td>9654</td>\n      <td>6662</td>\n      <td>73186</td>\n      <td>76299</td>\n      <td>1351</td>\n      <td>2865</td>\n      <td>-1514</td>\n      <td>11.564</td>\n      <td>10.744</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>46.806</td>\n      <td>7.192</td>\n      <td>3.846</td>\n      <td>large</td>\n      <td>72</td>\n      <td>untreated</td>\n      <td>0.0</td>\n      <td>-3</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>356</th>\n      <td>499</td>\n      <td>225</td>\n      <td>274</td>\n      <td>2581</td>\n      <td>1689</td>\n      <td>78</td>\n      <td>224</td>\n      <td>-146</td>\n      <td>11.552</td>\n      <td>10.686</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>large</td>\n      <td>90</td>\n      <td>treated</td>\n      <td>1.0</td>\n      <td>15</td>\n      <td>15.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>357 rows \u00d7 37 columns</p>\n</div>\n\n\n\n\n```python\n\n```\n\n\n```python\nols_pol0 = ols(\"INVSALES ~ T\", data= df).fit()\nols_pol0_coeff = ols_pol0.params.copy()\n\nols_pol0_coeff[1].round(3)\n```\n\n\n\n\n    0.012\n\n\n\n\n```python\nols_pol1 = ols(\"INVSALES ~ T + s +streat\", data= df).fit()\nols_pol1_coeff = ols_pol1.params.copy()\n\nols_pol1_coeff.round(3)\n```\n\n\n\n\n    Intercept    0.021\n    T            0.040\n    s           -0.001\n    streat      -0.001\n    dtype: float64\n\n\n\n\n```python\n#ols_pol1 = ols(\"INVSALES ~ T + treatment\", data= df).fit()\n#ols_pol1_coeff = ols_pol1.params.copy()\n\n#ols_pol1_coeff[1].round(3)\n```\n\n\n```python\nols_pol1 = ols(\"INVSALES ~ T + s +streat\", data= df).fit().summary()\nols_pol1\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVSALES</td>     <th>  R-squared:         </th> <td>   0.013</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.005</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.563</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.198</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:27</td>     <th>  Log-Likelihood:    </th> <td>  303.35</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>  -598.7</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   353</td>      <th>  BIC:               </th> <td>  -583.2</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0205</td> <td>    0.015</td> <td>    1.382</td> <td> 0.168</td> <td>   -0.009</td> <td>    0.050</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0401</td> <td>    0.019</td> <td>    2.102</td> <td> 0.036</td> <td>    0.003</td> <td>    0.078</td>\n</tr>\n<tr>\n  <th>s</th>         <td>   -0.0009</td> <td>    0.001</td> <td>   -1.192</td> <td> 0.234</td> <td>   -0.002</td> <td>    0.001</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0007</td> <td>    0.001</td> <td>   -0.541</td> <td> 0.589</td> <td>   -0.003</td> <td>    0.002</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>63.335</td> <th>  Durbin-Watson:     </th> <td>   1.817</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 101.929</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.057</td> <th>  Prob(JB):          </th> <td>7.35e-23</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 4.545</td> <th>  Cond. No.          </th> <td>    64.1</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\ndf[\"NT\"]  = 1-df[\"T\"]\n```\n\n\n```python\n\n```\n\n\n```python\ndf[\"s2\"]= df[\"s\"].pow(2)\ndf[\"s3\"]= df[\"s\"].pow(3)\ndf[\"streat\"] = df[\"s\"]* df[\"T\"]\ndf[\"s2treat\"] = df[\"s2\"]* df[\"T\"]\ndf[\"s3treat\"] = df[\"s3\"]* df[\"T\"]\ndf[\"snotreat\"] = df[\"s\"]* df[\"NT\"]\ndf[\"s2notreat\"] = df[\"s2\"]* df[\"NT\"]\ndf[\"s3notreat\"] = df[\"s3\"]* df[\"NT\"]\n#ols_pol2 = ols(\"INVSALES ~ T + s +streat + s2treat\", data= df).fit().summary()\n#ols_pol2\n```\n\n\n```python\nols_pol0 =ols(\"INVSALES ~ C(T) \", data= df).fit().summary()\n\nols_pol1 = ols(\"INVSALES ~ C(T) + streat + snotreat \", data= df).fit().summary()\n\nols_pol2 = ols(\"INVSALES ~ T + streat + snotreat + s2treat + s2notreat\", data= df).fit().summary()\n\nols_pol3 = ols(\"INVSALES ~ T + streat + snotreat + s2treat + s2notreat + s3treat + s3notreat\", data= df).fit().summary()\n```\n\n\n```python\nols_pol00 = ols(\"INVTSALES ~ T \", data= df).fit().summary()\n\nols_pol11 = ols(\"INVTSALES ~ T + streat+ snotreat \", data= df).fit().summary()\n\nols_pol22 = ols(\"INVTSALES ~ T + streat + snotreat + s2treat + s2notreat\", data= df).fit().summary()\n\nols_pol33 =ols(\"INVTSALES ~ T + streat + snotreat + s2treat + s2notreat + s3treat + s3notreat\", data= df).fit().summary()\n```\n\n\n```python\nols_pol0\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVSALES</td>     <th>  R-squared:         </th> <td>   0.003</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.000</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.003</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.317</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:27</td>     <th>  Log-Likelihood:    </th> <td>  301.50</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>  -599.0</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   355</td>      <th>  BIC:               </th> <td>  -591.2</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n       <td></td>          <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th>   <td>    0.0333</td> <td>    0.010</td> <td>    3.244</td> <td> 0.001</td> <td>    0.013</td> <td>    0.054</td>\n</tr>\n<tr>\n  <th>C(T)[T.1.0]</th> <td>    0.0122</td> <td>    0.012</td> <td>    1.002</td> <td> 0.317</td> <td>   -0.012</td> <td>    0.036</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>63.908</td> <th>  Durbin-Watson:     </th> <td>   1.825</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 103.114</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.064</td> <th>  Prob(JB):          </th> <td>4.07e-23</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 4.550</td> <th>  Cond. No.          </th> <td>    3.49</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nols_pol1\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVSALES</td>     <th>  R-squared:         </th> <td>   0.013</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.005</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.563</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.198</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:27</td>     <th>  Log-Likelihood:    </th> <td>  303.35</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>  -598.7</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   353</td>      <th>  BIC:               </th> <td>  -583.2</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n       <td></td>          <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th>   <td>    0.0205</td> <td>    0.015</td> <td>    1.382</td> <td> 0.168</td> <td>   -0.009</td> <td>    0.050</td>\n</tr>\n<tr>\n  <th>C(T)[T.1.0]</th> <td>    0.0401</td> <td>    0.019</td> <td>    2.102</td> <td> 0.036</td> <td>    0.003</td> <td>    0.078</td>\n</tr>\n<tr>\n  <th>streat</th>      <td>   -0.0016</td> <td>    0.001</td> <td>   -1.503</td> <td> 0.134</td> <td>   -0.004</td> <td>    0.001</td>\n</tr>\n<tr>\n  <th>snotreat</th>    <td>   -0.0009</td> <td>    0.001</td> <td>   -1.192</td> <td> 0.234</td> <td>   -0.002</td> <td>    0.001</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>63.335</td> <th>  Durbin-Watson:     </th> <td>   1.817</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 101.929</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.057</td> <th>  Prob(JB):          </th> <td>7.35e-23</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 4.545</td> <th>  Cond. No.          </th> <td>    42.9</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nols_pol2\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVSALES</td>     <th>  R-squared:         </th> <td>   0.016</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.002</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.165</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.326</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:27</td>     <th>  Log-Likelihood:    </th> <td>  303.93</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>  -595.9</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   351</td>      <th>  BIC:               </th> <td>  -572.6</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     5</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0063</td> <td>    0.023</td> <td>    0.269</td> <td> 0.788</td> <td>   -0.040</td> <td>    0.052</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0459</td> <td>    0.029</td> <td>    1.601</td> <td> 0.110</td> <td>   -0.010</td> <td>    0.102</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>    0.0011</td> <td>    0.004</td> <td>    0.273</td> <td> 0.785</td> <td>   -0.007</td> <td>    0.009</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0035</td> <td>    0.003</td> <td>   -1.049</td> <td> 0.295</td> <td>   -0.010</td> <td>    0.003</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>   -0.0001</td> <td>    0.000</td> <td>   -0.724</td> <td> 0.470</td> <td>   -0.001</td> <td>    0.000</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>-5.681e-05</td> <td> 7.18e-05</td> <td>   -0.791</td> <td> 0.429</td> <td>   -0.000</td> <td> 8.44e-05</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>62.091</td> <th>  Durbin-Watson:     </th> <td>   1.814</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td>  98.726</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.045</td> <th>  Prob(JB):          </th> <td>3.65e-22</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 4.507</td> <th>  Cond. No.          </th> <td>2.45e+03</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.<br/>[2] The condition number is large, 2.45e+03. This might indicate that there are<br/>strong multicollinearity or other numerical problems.\n\n\n\n\n```python\nols_pol3\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVSALES</td>     <th>  R-squared:         </th> <td>   0.019</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.001</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>  0.9476</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.470</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:27</td>     <th>  Log-Likelihood:    </th> <td>  304.35</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>  -592.7</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   349</td>      <th>  BIC:               </th> <td>  -561.7</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     7</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>   -0.0010</td> <td>    0.036</td> <td>   -0.029</td> <td> 0.977</td> <td>   -0.072</td> <td>    0.069</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0647</td> <td>    0.042</td> <td>    1.552</td> <td> 0.122</td> <td>   -0.017</td> <td>    0.147</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0061</td> <td>    0.009</td> <td>   -0.668</td> <td> 0.505</td> <td>   -0.024</td> <td>    0.012</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0055</td> <td>    0.008</td> <td>   -0.659</td> <td> 0.511</td> <td>   -0.022</td> <td>    0.011</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>    0.0007</td> <td>    0.001</td> <td>    0.717</td> <td> 0.474</td> <td>   -0.001</td> <td>    0.003</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>   -0.0002</td> <td>    0.000</td> <td>   -0.388</td> <td> 0.698</td> <td>   -0.001</td> <td>    0.001</td>\n</tr>\n<tr>\n  <th>s3treat</th>   <td>-2.763e-05</td> <td> 3.19e-05</td> <td>   -0.868</td> <td> 0.386</td> <td>-9.03e-05</td> <td>  3.5e-05</td>\n</tr>\n<tr>\n  <th>s3notreat</th> <td>-1.855e-06</td> <td> 6.89e-06</td> <td>   -0.269</td> <td> 0.788</td> <td>-1.54e-05</td> <td> 1.17e-05</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>61.047</td> <th>  Durbin-Watson:     </th> <td>   1.813</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td>  95.790</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.037</td> <th>  Prob(JB):          </th> <td>1.58e-21</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 4.462</td> <th>  Cond. No.          </th> <td>1.53e+05</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.<br/>[2] The condition number is large, 1.53e+05. This might indicate that there are<br/>strong multicollinearity or other numerical problems.\n\n\n\n\n```python\nols_pol00 = ols(\"INVTSALES ~ T \", data= df).fit().summary()\n\nols_pol11 = ols(\"INVTSALES ~ T + streat+ snotreat \", data= df).fit().summary()\n\nols_pol22 = ols(\"INVTSALES ~ T + streat + snotreat + s2treat + s2notreat\", data= df).fit().summary()\n\nols_pol33 =ols(\"INVTSALES ~ T + streat + snotreat + s2treat + s2notreat + s3treat + s3notreat\", data= df).fit().summary()\n\n```\n\n\n```python\nols_pol00\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVTSALES</td>    <th>  R-squared:         </th> <td>   0.002</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.001</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>  0.5741</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.449</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:27</td>     <th>  Log-Likelihood:    </th> <td>  357.34</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>  -710.7</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   355</td>      <th>  BIC:               </th> <td>  -702.9</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0211</td> <td>    0.009</td> <td>    2.404</td> <td> 0.017</td> <td>    0.004</td> <td>    0.038</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0079</td> <td>    0.010</td> <td>    0.758</td> <td> 0.449</td> <td>   -0.013</td> <td>    0.028</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>87.252</td> <th>  Durbin-Watson:     </th> <td>   1.942</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 426.189</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 0.933</td> <th>  Prob(JB):          </th> <td>2.85e-93</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 8.017</td> <th>  Cond. No.          </th> <td>    3.49</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nols_pol11\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVTSALES</td>    <th>  R-squared:         </th> <td>   0.007</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.002</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>  0.7992</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.495</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:27</td>     <th>  Log-Likelihood:    </th> <td>  358.26</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>  -708.5</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   353</td>      <th>  BIC:               </th> <td>  -693.0</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0098</td> <td>    0.013</td> <td>    0.772</td> <td> 0.440</td> <td>   -0.015</td> <td>    0.035</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0241</td> <td>    0.016</td> <td>    1.471</td> <td> 0.142</td> <td>   -0.008</td> <td>    0.056</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0005</td> <td>    0.001</td> <td>   -0.566</td> <td> 0.571</td> <td>   -0.002</td> <td>    0.001</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0008</td> <td>    0.001</td> <td>   -1.226</td> <td> 0.221</td> <td>   -0.002</td> <td>    0.000</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>86.985</td> <th>  Durbin-Watson:     </th> <td>   1.938</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 417.404</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 0.936</td> <th>  Prob(JB):          </th> <td>2.30e-91</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 7.956</td> <th>  Cond. No.          </th> <td>    42.9</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nols_pol22\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVTSALES</td>    <th>  R-squared:         </th> <td>   0.007</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.007</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>  0.4801</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.791</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:27</td>     <th>  Log-Likelihood:    </th> <td>  358.27</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>  -704.5</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   351</td>      <th>  BIC:               </th> <td>  -681.3</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     5</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0114</td> <td>    0.020</td> <td>    0.568</td> <td> 0.570</td> <td>   -0.028</td> <td>    0.051</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0217</td> <td>    0.025</td> <td>    0.882</td> <td> 0.378</td> <td>   -0.027</td> <td>    0.070</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0003</td> <td>    0.003</td> <td>   -0.083</td> <td> 0.934</td> <td>   -0.007</td> <td>    0.006</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0005</td> <td>    0.003</td> <td>   -0.190</td> <td> 0.849</td> <td>   -0.006</td> <td>    0.005</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>-1.289e-05</td> <td>    0.000</td> <td>   -0.079</td> <td> 0.937</td> <td>   -0.000</td> <td>    0.000</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td> 6.183e-06</td> <td> 6.17e-05</td> <td>    0.100</td> <td> 0.920</td> <td>   -0.000</td> <td>    0.000</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>86.779</td> <th>  Durbin-Watson:     </th> <td>   1.939</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 417.829</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 0.932</td> <th>  Prob(JB):          </th> <td>1.86e-91</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 7.961</td> <th>  Cond. No.          </th> <td>2.45e+03</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.<br/>[2] The condition number is large, 2.45e+03. This might indicate that there are<br/>strong multicollinearity or other numerical problems.\n\n\n\n\n```python\nols_pol33 \n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVTSALES</td>    <th>  R-squared:         </th> <td>   0.007</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.013</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>  0.3513</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.929</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:27</td>     <th>  Log-Likelihood:    </th> <td>  358.30</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>  -700.6</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   349</td>      <th>  BIC:               </th> <td>  -669.6</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     7</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0111</td> <td>    0.031</td> <td>    0.359</td> <td> 0.720</td> <td>   -0.050</td> <td>    0.072</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0251</td> <td>    0.036</td> <td>    0.700</td> <td> 0.484</td> <td>   -0.045</td> <td>    0.096</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0022</td> <td>    0.008</td> <td>   -0.278</td> <td> 0.781</td> <td>   -0.018</td> <td>    0.013</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0006</td> <td>    0.007</td> <td>   -0.087</td> <td> 0.931</td> <td>   -0.015</td> <td>    0.014</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>    0.0002</td> <td>    0.001</td> <td>    0.249</td> <td> 0.804</td> <td>   -0.002</td> <td>    0.002</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td> 6.942e-07</td> <td>    0.000</td> <td>    0.002</td> <td> 0.999</td> <td>   -0.001</td> <td>    0.001</td>\n</tr>\n<tr>\n  <th>s3treat</th>   <td>-7.339e-06</td> <td> 2.74e-05</td> <td>   -0.268</td> <td> 0.789</td> <td>-6.12e-05</td> <td> 4.65e-05</td>\n</tr>\n<tr>\n  <th>s3notreat</th> <td>-8.222e-08</td> <td> 5.92e-06</td> <td>   -0.014</td> <td> 0.989</td> <td>-1.17e-05</td> <td> 1.16e-05</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>86.523</td> <th>  Durbin-Watson:     </th> <td>   1.939</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 419.134</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 0.927</td> <th>  Prob(JB):          </th> <td>9.69e-92</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 7.974</td> <th>  Cond. No.          </th> <td>1.53e+05</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.<br/>[2] The condition number is large, 1.53e+05. This might indicate that there are<br/>strong multicollinearity or other numerical problems.\n\n\n\n\n```python\nols_pol000 = ols(\"INVINTSALES ~ T \", data= df).fit().summary()\n\nols_pol111 = ols(\"INVINTSALES ~ T + streat+ snotreat \", data= df).fit().summary()\n\nols_pol222 = ols(\"INVINTSALES ~ T + streat + snotreat + s2treat + s2notreat\", data= df).fit().summary()\n\nols_pol333 =ols(\"INVINTSALES ~ T + streat + snotreat + s2treat + s2notreat + s3treat + s3notreat\", data= df).fit().summary()\n```\n\n\n```python\nols_pol000\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>       <td>INVINTSALES</td>   <th>  R-squared:         </th> <td>   0.001</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.002</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>  0.3569</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.551</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:27</td>     <th>  Log-Likelihood:    </th> <td>  491.83</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>  -979.7</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   355</td>      <th>  BIC:               </th> <td>  -971.9</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0122</td> <td>    0.006</td> <td>    2.023</td> <td> 0.044</td> <td>    0.000</td> <td>    0.024</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0043</td> <td>    0.007</td> <td>    0.597</td> <td> 0.551</td> <td>   -0.010</td> <td>    0.018</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>173.982</td> <th>  Durbin-Watson:     </th> <td>   1.785</td> \n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>1109.843</td> \n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.968</td>  <th>  Prob(JB):          </th> <td>1.00e-241</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>10.689</td>  <th>  Cond. No.          </th> <td>    3.49</td> \n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nols_pol111\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>       <td>INVINTSALES</td>   <th>  R-squared:         </th> <td>   0.010</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.001</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.131</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.336</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:27</td>     <th>  Log-Likelihood:    </th> <td>  493.36</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>  -978.7</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   353</td>      <th>  BIC:               </th> <td>  -963.2</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0108</td> <td>    0.009</td> <td>    1.234</td> <td> 0.218</td> <td>   -0.006</td> <td>    0.028</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0159</td> <td>    0.011</td> <td>    1.417</td> <td> 0.157</td> <td>   -0.006</td> <td>    0.038</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0011</td> <td>    0.001</td> <td>   -1.728</td> <td> 0.085</td> <td>   -0.002</td> <td>    0.000</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0001</td> <td>    0.000</td> <td>   -0.227</td> <td> 0.821</td> <td>   -0.001</td> <td>    0.001</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>172.293</td> <th>  Durbin-Watson:     </th> <td>   1.762</td> \n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>1086.302</td> \n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.949</td>  <th>  Prob(JB):          </th> <td>1.30e-236</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>10.605</td>  <th>  Cond. No.          </th> <td>    42.9</td> \n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nols_pol222\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>       <td>INVINTSALES</td>   <th>  R-squared:         </th> <td>   0.019</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.005</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.378</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.232</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:27</td>     <th>  Log-Likelihood:    </th> <td>  495.12</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>  -978.2</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   351</td>      <th>  BIC:               </th> <td>  -955.0</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     5</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>   -0.0050</td> <td>    0.014</td> <td>   -0.367</td> <td> 0.714</td> <td>   -0.032</td> <td>    0.022</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0241</td> <td>    0.017</td> <td>    1.436</td> <td> 0.152</td> <td>   -0.009</td> <td>    0.057</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>    0.0013</td> <td>    0.002</td> <td>    0.581</td> <td> 0.562</td> <td>   -0.003</td> <td>    0.006</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0029</td> <td>    0.002</td> <td>   -1.510</td> <td> 0.132</td> <td>   -0.007</td> <td>    0.001</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>   -0.0001</td> <td>    0.000</td> <td>   -1.112</td> <td> 0.267</td> <td>   -0.000</td> <td> 9.55e-05</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>  -6.3e-05</td> <td>  4.2e-05</td> <td>   -1.499</td> <td> 0.135</td> <td>   -0.000</td> <td> 1.97e-05</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>171.283</td> <th>  Durbin-Watson:     </th> <td>   1.734</td> \n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>1085.343</td> \n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.932</td>  <th>  Prob(JB):          </th> <td>2.09e-236</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>10.618</td>  <th>  Cond. No.          </th> <td>2.45e+03</td> \n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.<br/>[2] The condition number is large, 2.45e+03. This might indicate that there are<br/>strong multicollinearity or other numerical problems.\n\n\n\n\n```python\nols_pol333\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>       <td>INVINTSALES</td>   <th>  R-squared:         </th> <td>   0.023</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.004</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.182</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.313</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:27</td>     <th>  Log-Likelihood:    </th> <td>  495.83</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>  -975.7</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   349</td>      <th>  BIC:               </th> <td>  -944.6</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     7</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>   -0.0121</td> <td>    0.021</td> <td>   -0.575</td> <td> 0.566</td> <td>   -0.053</td> <td>    0.029</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0396</td> <td>    0.024</td> <td>    1.624</td> <td> 0.105</td> <td>   -0.008</td> <td>    0.088</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0040</td> <td>    0.005</td> <td>   -0.740</td> <td> 0.460</td> <td>   -0.014</td> <td>    0.007</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0049</td> <td>    0.005</td> <td>   -0.999</td> <td> 0.318</td> <td>   -0.015</td> <td>    0.005</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>    0.0005</td> <td>    0.001</td> <td>    0.866</td> <td> 0.387</td> <td>   -0.001</td> <td>    0.002</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>   -0.0002</td> <td>    0.000</td> <td>   -0.669</td> <td> 0.504</td> <td>   -0.001</td> <td>    0.000</td>\n</tr>\n<tr>\n  <th>s3treat</th>   <td>-2.037e-05</td> <td> 1.86e-05</td> <td>   -1.093</td> <td> 0.275</td> <td> -5.7e-05</td> <td> 1.63e-05</td>\n</tr>\n<tr>\n  <th>s3notreat</th> <td>-1.785e-06</td> <td> 4.03e-06</td> <td>   -0.443</td> <td> 0.658</td> <td>-9.71e-06</td> <td> 6.14e-06</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>170.192</td> <th>  Durbin-Watson:     </th> <td>   1.733</td> \n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>1063.238</td> \n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.923</td>  <th>  Prob(JB):          </th> <td>1.32e-231</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>10.529</td>  <th>  Cond. No.          </th> <td>1.53e+05</td> \n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.<br/>[2] The condition number is large, 1.53e+05. This might indicate that there are<br/>strong multicollinearity or other numerical problems.\n\n\n\n\n```python\ndf_wide_wind = df.loc[(52 <= df.score) & (df.score <= 80), :]\ndf_wide_wind \n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>K</th>\n      <th>KT</th>\n      <th>KINT</th>\n      <th>SALES</th>\n      <th>ASSETS</th>\n      <th>INV</th>\n      <th>INVT</th>\n      <th>INVINT</th>\n      <th>LINV</th>\n      <th>LINVT</th>\n      <th>...</th>\n      <th>s</th>\n      <th>streat</th>\n      <th>NT</th>\n      <th>s2</th>\n      <th>s3</th>\n      <th>s2treat</th>\n      <th>s3treat</th>\n      <th>snotreat</th>\n      <th>s2notreat</th>\n      <th>s3notreat</th>\n    </tr>\n    <tr>\n      <th>Firm</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>3</th>\n      <td>1131</td>\n      <td>1115</td>\n      <td>16</td>\n      <td>12143</td>\n      <td>10842</td>\n      <td>-114</td>\n      <td>-114</td>\n      <td>0</td>\n      <td>11.550</td>\n      <td>10.678</td>\n      <td>...</td>\n      <td>-5</td>\n      <td>-0.0</td>\n      <td>1.0</td>\n      <td>25</td>\n      <td>-125</td>\n      <td>0.0</td>\n      <td>-0.0</td>\n      <td>-5.0</td>\n      <td>25.0</td>\n      <td>-125.0</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>3788</td>\n      <td>3788</td>\n      <td>0</td>\n      <td>12071</td>\n      <td>14032</td>\n      <td>987</td>\n      <td>677</td>\n      <td>310</td>\n      <td>11.560</td>\n      <td>10.696</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>2070</td>\n      <td>1321</td>\n      <td>749</td>\n      <td>10718</td>\n      <td>11990</td>\n      <td>2770</td>\n      <td>3156</td>\n      <td>-386</td>\n      <td>11.577</td>\n      <td>10.751</td>\n      <td>...</td>\n      <td>1</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>17152</td>\n      <td>17049</td>\n      <td>103</td>\n      <td>30226</td>\n      <td>54628</td>\n      <td>2275</td>\n      <td>1805</td>\n      <td>470</td>\n      <td>11.573</td>\n      <td>10.721</td>\n      <td>...</td>\n      <td>2</td>\n      <td>2.0</td>\n      <td>0.0</td>\n      <td>4</td>\n      <td>8</td>\n      <td>4.0</td>\n      <td>8.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>18017</td>\n      <td>15318</td>\n      <td>2699</td>\n      <td>341343</td>\n      <td>282072</td>\n      <td>-203</td>\n      <td>-1760</td>\n      <td>1557</td>\n      <td>11.549</td>\n      <td>10.639</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>344</th>\n      <td>298</td>\n      <td>252</td>\n      <td>46</td>\n      <td>1034</td>\n      <td>1189</td>\n      <td>353</td>\n      <td>-36</td>\n      <td>389</td>\n      <td>11.554</td>\n      <td>10.680</td>\n      <td>...</td>\n      <td>1</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>345</th>\n      <td>48</td>\n      <td>28</td>\n      <td>20</td>\n      <td>11796</td>\n      <td>12094</td>\n      <td>453</td>\n      <td>158</td>\n      <td>295</td>\n      <td>11.555</td>\n      <td>10.684</td>\n      <td>...</td>\n      <td>-7</td>\n      <td>-0.0</td>\n      <td>1.0</td>\n      <td>49</td>\n      <td>-343</td>\n      <td>0.0</td>\n      <td>-0.0</td>\n      <td>-7.0</td>\n      <td>49.0</td>\n      <td>-343.0</td>\n    </tr>\n    <tr>\n      <th>350</th>\n      <td>11161</td>\n      <td>10510</td>\n      <td>651</td>\n      <td>73763</td>\n      <td>75434</td>\n      <td>1549</td>\n      <td>2057</td>\n      <td>-508</td>\n      <td>11.566</td>\n      <td>10.727</td>\n      <td>...</td>\n      <td>5</td>\n      <td>5.0</td>\n      <td>0.0</td>\n      <td>25</td>\n      <td>125</td>\n      <td>25.0</td>\n      <td>125.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>352</th>\n      <td>1126</td>\n      <td>985</td>\n      <td>141</td>\n      <td>30938</td>\n      <td>22915</td>\n      <td>-63</td>\n      <td>-49</td>\n      <td>-14</td>\n      <td>11.550</td>\n      <td>10.680</td>\n      <td>...</td>\n      <td>2</td>\n      <td>2.0</td>\n      <td>0.0</td>\n      <td>4</td>\n      <td>8</td>\n      <td>4.0</td>\n      <td>8.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>355</th>\n      <td>16316</td>\n      <td>9654</td>\n      <td>6662</td>\n      <td>73186</td>\n      <td>76299</td>\n      <td>1351</td>\n      <td>2865</td>\n      <td>-1514</td>\n      <td>11.564</td>\n      <td>10.744</td>\n      <td>...</td>\n      <td>-3</td>\n      <td>-0.0</td>\n      <td>1.0</td>\n      <td>9</td>\n      <td>-27</td>\n      <td>0.0</td>\n      <td>-0.0</td>\n      <td>-3.0</td>\n      <td>9.0</td>\n      <td>-27.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>171 rows \u00d7 45 columns</p>\n</div>\n\n\n\n\n```python\nww_pol0 = ols(\"INVSALES ~ C(T) \", data = df_wide_wind).fit().summary()\n\nww_pol1 = ols(\"INVSALES ~ C(T) + streat + snotreat \", data = df_wide_wind).fit().summary()\n\nww_pol2 = ols(\"INVSALES ~ T + streat + snotreat + s2treat + s2notreat\", data = df_wide_wind).fit().summary()\n\n\n```\n\n\n```python\nww_pol0\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVSALES</td>     <th>  R-squared:         </th> <td>   0.016</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.010</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   2.688</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.103</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:28</td>     <th>  Log-Likelihood:    </th> <td>  140.52</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   171</td>      <th>  AIC:               </th> <td>  -277.0</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   169</td>      <th>  BIC:               </th> <td>  -270.8</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n       <td></td>          <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th>   <td>    0.0280</td> <td>    0.012</td> <td>    2.354</td> <td> 0.020</td> <td>    0.005</td> <td>    0.051</td>\n</tr>\n<tr>\n  <th>C(T)[T.1.0]</th> <td>    0.0269</td> <td>    0.016</td> <td>    1.639</td> <td> 0.103</td> <td>   -0.005</td> <td>    0.059</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>34.917</td> <th>  Durbin-Watson:     </th> <td>   1.876</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td>  54.944</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.070</td> <th>  Prob(JB):          </th> <td>1.17e-12</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 4.770</td> <th>  Cond. No.          </th> <td>    2.68</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nww_pol1\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVSALES</td>     <th>  R-squared:         </th> <td>   0.020</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.002</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.126</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.340</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:28</td>     <th>  Log-Likelihood:    </th> <td>  140.89</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   171</td>      <th>  AIC:               </th> <td>  -273.8</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   167</td>      <th>  BIC:               </th> <td>  -261.2</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n       <td></td>          <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th>   <td>    0.0127</td> <td>    0.022</td> <td>    0.584</td> <td> 0.560</td> <td>   -0.030</td> <td>    0.056</td>\n</tr>\n<tr>\n  <th>C(T)[T.1.0]</th> <td>    0.0417</td> <td>    0.031</td> <td>    1.365</td> <td> 0.174</td> <td>   -0.019</td> <td>    0.102</td>\n</tr>\n<tr>\n  <th>streat</th>      <td>    0.0002</td> <td>    0.007</td> <td>    0.025</td> <td> 0.980</td> <td>   -0.013</td> <td>    0.014</td>\n</tr>\n<tr>\n  <th>snotreat</th>    <td>   -0.0020</td> <td>    0.002</td> <td>   -0.843</td> <td> 0.401</td> <td>   -0.007</td> <td>    0.003</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>33.970</td> <th>  Durbin-Watson:     </th> <td>   1.879</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td>  52.151</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.058</td> <th>  Prob(JB):          </th> <td>4.74e-12</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 4.686</td> <th>  Cond. No.          </th> <td>    27.1</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nww_pol2\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVSALES</td>     <th>  R-squared:         </th> <td>   0.048</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.019</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.653</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.149</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:28</td>     <th>  Log-Likelihood:    </th> <td>  143.36</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   171</td>      <th>  AIC:               </th> <td>  -274.7</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   165</td>      <th>  BIC:               </th> <td>  -255.9</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     5</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>   -0.0219</td> <td>    0.039</td> <td>   -0.564</td> <td> 0.573</td> <td>   -0.098</td> <td>    0.055</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.1102</td> <td>    0.048</td> <td>    2.313</td> <td> 0.022</td> <td>    0.016</td> <td>    0.204</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0447</td> <td>    0.024</td> <td>   -1.835</td> <td> 0.068</td> <td>   -0.093</td> <td>    0.003</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0115</td> <td>    0.009</td> <td>   -1.256</td> <td> 0.211</td> <td>   -0.030</td> <td>    0.007</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>    0.0087</td> <td>    0.005</td> <td>    1.918</td> <td> 0.057</td> <td>   -0.000</td> <td>    0.018</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>   -0.0005</td> <td>    0.000</td> <td>   -1.073</td> <td> 0.285</td> <td>   -0.001</td> <td>    0.000</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>30.908</td> <th>  Durbin-Watson:     </th> <td>   1.880</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td>  43.900</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.020</td> <th>  Prob(JB):          </th> <td>2.93e-10</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 4.415</td> <th>  Cond. No.          </th> <td>    692.</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nww_pol00 = ols(\"INVTSALES ~ T \", data = df_wide_wind).fit().summary()\n\nww_pol11 = ols(\"INVTSALES ~ T + streat+ snotreat \", data = df_wide_wind).fit().summary()\n\nww_pol22 = ols(\"INVTSALES ~ T + streat + snotreat + s2treat + s2notreat\", data = df_wide_wind).fit().summary()\n\n\n```\n\n\n```python\nww_pol00\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVTSALES</td>    <th>  R-squared:         </th> <td>   0.013</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.007</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   2.175</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.142</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:28</td>     <th>  Log-Likelihood:    </th> <td>  178.92</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   171</td>      <th>  AIC:               </th> <td>  -353.8</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   169</td>      <th>  BIC:               </th> <td>  -347.6</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0157</td> <td>    0.009</td> <td>    1.651</td> <td> 0.101</td> <td>   -0.003</td> <td>    0.034</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0193</td> <td>    0.013</td> <td>    1.475</td> <td> 0.142</td> <td>   -0.007</td> <td>    0.045</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>74.009</td> <th>  Durbin-Watson:     </th> <td>   2.036</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 274.311</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.680</td> <th>  Prob(JB):          </th> <td>2.72e-60</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 8.216</td> <th>  Cond. No.          </th> <td>    2.68</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nols_pol11\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVTSALES</td>    <th>  R-squared:         </th> <td>   0.007</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.002</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>  0.7992</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.495</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:27</td>     <th>  Log-Likelihood:    </th> <td>  358.26</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>  -708.5</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   353</td>      <th>  BIC:               </th> <td>  -693.0</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0098</td> <td>    0.013</td> <td>    0.772</td> <td> 0.440</td> <td>   -0.015</td> <td>    0.035</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0241</td> <td>    0.016</td> <td>    1.471</td> <td> 0.142</td> <td>   -0.008</td> <td>    0.056</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0005</td> <td>    0.001</td> <td>   -0.566</td> <td> 0.571</td> <td>   -0.002</td> <td>    0.001</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0008</td> <td>    0.001</td> <td>   -1.226</td> <td> 0.221</td> <td>   -0.002</td> <td>    0.000</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>86.985</td> <th>  Durbin-Watson:     </th> <td>   1.938</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 417.404</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 0.936</td> <th>  Prob(JB):          </th> <td>2.30e-91</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 7.956</td> <th>  Cond. No.          </th> <td>    42.9</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nols_pol22\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVTSALES</td>    <th>  R-squared:         </th> <td>   0.007</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.007</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>  0.4801</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.791</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:27</td>     <th>  Log-Likelihood:    </th> <td>  358.27</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>  -704.5</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   351</td>      <th>  BIC:               </th> <td>  -681.3</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     5</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0114</td> <td>    0.020</td> <td>    0.568</td> <td> 0.570</td> <td>   -0.028</td> <td>    0.051</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0217</td> <td>    0.025</td> <td>    0.882</td> <td> 0.378</td> <td>   -0.027</td> <td>    0.070</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0003</td> <td>    0.003</td> <td>   -0.083</td> <td> 0.934</td> <td>   -0.007</td> <td>    0.006</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0005</td> <td>    0.003</td> <td>   -0.190</td> <td> 0.849</td> <td>   -0.006</td> <td>    0.005</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>-1.289e-05</td> <td>    0.000</td> <td>   -0.079</td> <td> 0.937</td> <td>   -0.000</td> <td>    0.000</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td> 6.183e-06</td> <td> 6.17e-05</td> <td>    0.100</td> <td> 0.920</td> <td>   -0.000</td> <td>    0.000</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>86.779</td> <th>  Durbin-Watson:     </th> <td>   1.939</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 417.829</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 0.932</td> <th>  Prob(JB):          </th> <td>1.86e-91</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 7.961</td> <th>  Cond. No.          </th> <td>2.45e+03</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.<br/>[2] The condition number is large, 2.45e+03. This might indicate that there are<br/>strong multicollinearity or other numerical problems.\n\n\n\n\n```python\nww_pol000 = ols(\"INVINTSALES ~ T \", data = df_wide_wind).fit().summary()\n\nww_pol111 = ols(\"INVINTSALES ~ T + streat + snotreat \", data = df_wide_wind).fit().summary()\n\nww_pol222 = ols(\"INVINTSALES ~ T +  +streat + snotreat + s2treat + s2notreat\", data = df_wide_wind).fit().summary()\n\n\n```\n\n\n```python\nww_pol000\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>       <td>INVINTSALES</td>   <th>  R-squared:         </th> <td>   0.004</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.002</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>  0.6169</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.433</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:28</td>     <th>  Log-Likelihood:    </th> <td>  233.69</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   171</td>      <th>  AIC:               </th> <td>  -463.4</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   169</td>      <th>  BIC:               </th> <td>  -457.1</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0123</td> <td>    0.007</td> <td>    1.790</td> <td> 0.075</td> <td>   -0.001</td> <td>    0.026</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0075</td> <td>    0.010</td> <td>    0.785</td> <td> 0.433</td> <td>   -0.011</td> <td>    0.026</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>81.703</td> <th>  Durbin-Watson:     </th> <td>   1.664</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 433.646</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.716</td> <th>  Prob(JB):          </th> <td>6.84e-95</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>10.006</td> <th>  Cond. No.          </th> <td>    2.68</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nww_pol111\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>       <td>INVINTSALES</td>   <th>  R-squared:         </th> <td>   0.012</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.005</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>  0.6942</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.557</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:28</td>     <th>  Log-Likelihood:    </th> <td>  234.44</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   171</td>      <th>  AIC:               </th> <td>  -460.9</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   167</td>      <th>  BIC:               </th> <td>  -448.3</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0012</td> <td>    0.013</td> <td>    0.092</td> <td> 0.926</td> <td>   -0.024</td> <td>    0.026</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0248</td> <td>    0.018</td> <td>    1.401</td> <td> 0.163</td> <td>   -0.010</td> <td>    0.060</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0023</td> <td>    0.004</td> <td>   -0.579</td> <td> 0.563</td> <td>   -0.010</td> <td>    0.006</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0015</td> <td>    0.001</td> <td>   -1.064</td> <td> 0.289</td> <td>   -0.004</td> <td>    0.001</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>79.630</td> <th>  Durbin-Watson:     </th> <td>   1.645</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 406.793</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.678</td> <th>  Prob(JB):          </th> <td>4.63e-89</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 9.770</td> <th>  Cond. No.          </th> <td>    27.1</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nww_pol222\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>       <td>INVINTSALES</td>   <th>  R-squared:         </th> <td>   0.045</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.016</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.570</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.171</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:28</td>     <th>  Log-Likelihood:    </th> <td>  237.36</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   171</td>      <th>  AIC:               </th> <td>  -462.7</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   165</td>      <th>  BIC:               </th> <td>  -443.9</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     5</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>   -0.0304</td> <td>    0.022</td> <td>   -1.358</td> <td> 0.176</td> <td>   -0.075</td> <td>    0.014</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0735</td> <td>    0.027</td> <td>    2.674</td> <td> 0.008</td> <td>    0.019</td> <td>    0.128</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0250</td> <td>    0.014</td> <td>   -1.782</td> <td> 0.077</td> <td>   -0.053</td> <td>    0.003</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0101</td> <td>    0.005</td> <td>   -1.917</td> <td> 0.057</td> <td>   -0.021</td> <td>    0.000</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>    0.0044</td> <td>    0.003</td> <td>    1.686</td> <td> 0.094</td> <td>   -0.001</td> <td>    0.010</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>   -0.0004</td> <td>    0.000</td> <td>   -1.697</td> <td> 0.092</td> <td>   -0.001</td> <td> 6.77e-05</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>81.323</td> <th>  Durbin-Watson:     </th> <td>   1.624</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 442.428</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.695</td> <th>  Prob(JB):          </th> <td>8.47e-97</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>10.114</td> <th>  Cond. No.          </th> <td>    692.</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\ndf_narr_wind = df.loc[(66 <= df.score) & (df.score <= 78), :]\n```\n\n\n```python\ndf_narr_wind\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>K</th>\n      <th>KT</th>\n      <th>KINT</th>\n      <th>SALES</th>\n      <th>ASSETS</th>\n      <th>INV</th>\n      <th>INVT</th>\n      <th>INVINT</th>\n      <th>LINV</th>\n      <th>LINVT</th>\n      <th>...</th>\n      <th>s</th>\n      <th>streat</th>\n      <th>NT</th>\n      <th>s2</th>\n      <th>s3</th>\n      <th>s2treat</th>\n      <th>s3treat</th>\n      <th>snotreat</th>\n      <th>s2notreat</th>\n      <th>s3notreat</th>\n    </tr>\n    <tr>\n      <th>Firm</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>3</th>\n      <td>1131</td>\n      <td>1115</td>\n      <td>16</td>\n      <td>12143</td>\n      <td>10842</td>\n      <td>-114</td>\n      <td>-114</td>\n      <td>0</td>\n      <td>11.550</td>\n      <td>10.678</td>\n      <td>...</td>\n      <td>-5</td>\n      <td>-0.0</td>\n      <td>1.0</td>\n      <td>25</td>\n      <td>-125</td>\n      <td>0.0</td>\n      <td>-0.0</td>\n      <td>-5.0</td>\n      <td>25.0</td>\n      <td>-125.0</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>3788</td>\n      <td>3788</td>\n      <td>0</td>\n      <td>12071</td>\n      <td>14032</td>\n      <td>987</td>\n      <td>677</td>\n      <td>310</td>\n      <td>11.560</td>\n      <td>10.696</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>2070</td>\n      <td>1321</td>\n      <td>749</td>\n      <td>10718</td>\n      <td>11990</td>\n      <td>2770</td>\n      <td>3156</td>\n      <td>-386</td>\n      <td>11.577</td>\n      <td>10.751</td>\n      <td>...</td>\n      <td>1</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>17152</td>\n      <td>17049</td>\n      <td>103</td>\n      <td>30226</td>\n      <td>54628</td>\n      <td>2275</td>\n      <td>1805</td>\n      <td>470</td>\n      <td>11.573</td>\n      <td>10.721</td>\n      <td>...</td>\n      <td>2</td>\n      <td>2.0</td>\n      <td>0.0</td>\n      <td>4</td>\n      <td>8</td>\n      <td>4.0</td>\n      <td>8.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>18017</td>\n      <td>15318</td>\n      <td>2699</td>\n      <td>341343</td>\n      <td>282072</td>\n      <td>-203</td>\n      <td>-1760</td>\n      <td>1557</td>\n      <td>11.549</td>\n      <td>10.639</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>339</th>\n      <td>129</td>\n      <td>104</td>\n      <td>25</td>\n      <td>2398</td>\n      <td>1475</td>\n      <td>67</td>\n      <td>82</td>\n      <td>-15</td>\n      <td>11.551</td>\n      <td>10.683</td>\n      <td>...</td>\n      <td>-8</td>\n      <td>-0.0</td>\n      <td>1.0</td>\n      <td>64</td>\n      <td>-512</td>\n      <td>0.0</td>\n      <td>-0.0</td>\n      <td>-8.0</td>\n      <td>64.0</td>\n      <td>-512.0</td>\n    </tr>\n    <tr>\n      <th>344</th>\n      <td>298</td>\n      <td>252</td>\n      <td>46</td>\n      <td>1034</td>\n      <td>1189</td>\n      <td>353</td>\n      <td>-36</td>\n      <td>389</td>\n      <td>11.554</td>\n      <td>10.680</td>\n      <td>...</td>\n      <td>1</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>345</th>\n      <td>48</td>\n      <td>28</td>\n      <td>20</td>\n      <td>11796</td>\n      <td>12094</td>\n      <td>453</td>\n      <td>158</td>\n      <td>295</td>\n      <td>11.555</td>\n      <td>10.684</td>\n      <td>...</td>\n      <td>-7</td>\n      <td>-0.0</td>\n      <td>1.0</td>\n      <td>49</td>\n      <td>-343</td>\n      <td>0.0</td>\n      <td>-0.0</td>\n      <td>-7.0</td>\n      <td>49.0</td>\n      <td>-343.0</td>\n    </tr>\n    <tr>\n      <th>352</th>\n      <td>1126</td>\n      <td>985</td>\n      <td>141</td>\n      <td>30938</td>\n      <td>22915</td>\n      <td>-63</td>\n      <td>-49</td>\n      <td>-14</td>\n      <td>11.550</td>\n      <td>10.680</td>\n      <td>...</td>\n      <td>2</td>\n      <td>2.0</td>\n      <td>0.0</td>\n      <td>4</td>\n      <td>8</td>\n      <td>4.0</td>\n      <td>8.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>355</th>\n      <td>16316</td>\n      <td>9654</td>\n      <td>6662</td>\n      <td>73186</td>\n      <td>76299</td>\n      <td>1351</td>\n      <td>2865</td>\n      <td>-1514</td>\n      <td>11.564</td>\n      <td>10.744</td>\n      <td>...</td>\n      <td>-3</td>\n      <td>-0.0</td>\n      <td>1.0</td>\n      <td>9</td>\n      <td>-27</td>\n      <td>0.0</td>\n      <td>-0.0</td>\n      <td>-3.0</td>\n      <td>9.0</td>\n      <td>-27.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>115 rows \u00d7 45 columns</p>\n</div>\n\n\n\n\n```python\nnw_pol0 = ols(\"INVSALES ~ C(T) \", data = df_narr_wind).fit().summary()\n\nnw_pol1 = ols(\"INVSALES ~ C(T) + streat + snotreat \", data = df_narr_wind).fit().summary()\n\nnw_pol2 = ols(\"INVSALES ~ T + streat + s2treat + snotreat +s2notreat \", data = df_narr_wind).fit().summary()\n```\n\n\n```python\nnw_pol0\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVSALES</td>     <th>  R-squared:         </th> <td>   0.027</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.018</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   3.112</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td>0.0804</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:28</td>     <th>  Log-Likelihood:    </th> <td>  102.17</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   115</td>      <th>  AIC:               </th> <td>  -200.3</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   113</td>      <th>  BIC:               </th> <td>  -194.9</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n       <td></td>          <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th>   <td>    0.0167</td> <td>    0.013</td> <td>    1.266</td> <td> 0.208</td> <td>   -0.009</td> <td>    0.043</td>\n</tr>\n<tr>\n  <th>C(T)[T.1.0]</th> <td>    0.0330</td> <td>    0.019</td> <td>    1.764</td> <td> 0.080</td> <td>   -0.004</td> <td>    0.070</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>14.142</td> <th>  Durbin-Watson:     </th> <td>   1.942</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.001</td> <th>  Jarque-Bera (JB):  </th> <td>  16.256</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 0.741</td> <th>  Prob(JB):          </th> <td>0.000295</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 4.095</td> <th>  Cond. No.          </th> <td>    2.61</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nnw_pol1\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVSALES</td>     <th>  R-squared:         </th> <td>   0.048</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.022</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.846</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.143</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:28</td>     <th>  Log-Likelihood:    </th> <td>  103.41</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   115</td>      <th>  AIC:               </th> <td>  -198.8</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   111</td>      <th>  BIC:               </th> <td>  -187.8</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n       <td></td>          <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th>   <td>    0.0126</td> <td>    0.035</td> <td>    0.361</td> <td> 0.719</td> <td>   -0.056</td> <td>    0.082</td>\n</tr>\n<tr>\n  <th>C(T)[T.1.0]</th> <td>    0.0681</td> <td>    0.042</td> <td>    1.611</td> <td> 0.110</td> <td>   -0.016</td> <td>    0.152</td>\n</tr>\n<tr>\n  <th>streat</th>      <td>   -0.0192</td> <td>    0.012</td> <td>   -1.549</td> <td> 0.124</td> <td>   -0.044</td> <td>    0.005</td>\n</tr>\n<tr>\n  <th>snotreat</th>    <td>   -0.0008</td> <td>    0.007</td> <td>   -0.128</td> <td> 0.898</td> <td>   -0.014</td> <td>    0.012</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>12.394</td> <th>  Durbin-Watson:     </th> <td>   1.960</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.002</td> <th>  Jarque-Bera (JB):  </th> <td>  13.475</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 0.697</td> <th>  Prob(JB):          </th> <td> 0.00119</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 3.933</td> <th>  Cond. No.          </th> <td>    21.8</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nnw_pol2\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVSALES</td>     <th>  R-squared:         </th> <td>   0.088</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.046</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   2.099</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td>0.0709</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:28</td>     <th>  Log-Likelihood:    </th> <td>  105.90</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   115</td>      <th>  AIC:               </th> <td>  -199.8</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   109</td>      <th>  BIC:               </th> <td>  -183.3</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     5</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.1559</td> <td>    0.074</td> <td>    2.100</td> <td> 0.038</td> <td>    0.009</td> <td>    0.303</td>\n</tr>\n<tr>\n  <th>T</th>         <td>   -0.0791</td> <td>    0.079</td> <td>   -0.999</td> <td> 0.320</td> <td>   -0.236</td> <td>    0.078</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0085</td> <td>    0.041</td> <td>   -0.205</td> <td> 0.838</td> <td>   -0.090</td> <td>    0.073</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>   -0.0036</td> <td>    0.013</td> <td>   -0.271</td> <td> 0.787</td> <td>   -0.030</td> <td>    0.023</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>    0.0645</td> <td>    0.031</td> <td>    2.102</td> <td> 0.038</td> <td>    0.004</td> <td>    0.125</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>    0.0063</td> <td>    0.003</td> <td>    2.178</td> <td> 0.032</td> <td>    0.001</td> <td>    0.012</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>11.922</td> <th>  Durbin-Watson:     </th> <td>   1.966</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.003</td> <th>  Jarque-Bera (JB):  </th> <td>  12.651</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 0.695</td> <th>  Prob(JB):          </th> <td> 0.00179</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 3.840</td> <th>  Cond. No.          </th> <td>    308.</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nnw_pol00 = ols(\"INVTSALES ~ C(T) \", data = df_narr_wind).fit().summary()\n\nnw_pol11 = ols(\"INVTSALES ~ C(T) + streat + snotreat \", data = df_narr_wind).fit().summary()\n\nnw_pol22 = ols(\"INVTSALES ~ T + streat + snotreat + s2treat + s2notreat\", data = df_narr_wind).fit().summary()\n```\n\n\n```python\nnw_pol00\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVTSALES</td>    <th>  R-squared:         </th> <td>   0.022</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.013</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   2.540</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.114</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:28</td>     <th>  Log-Likelihood:    </th> <td>  135.44</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   115</td>      <th>  AIC:               </th> <td>  -266.9</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   113</td>      <th>  BIC:               </th> <td>  -261.4</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n       <td></td>          <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th>   <td>    0.0106</td> <td>    0.010</td> <td>    1.074</td> <td> 0.285</td> <td>   -0.009</td> <td>    0.030</td>\n</tr>\n<tr>\n  <th>C(T)[T.1.0]</th> <td>    0.0223</td> <td>    0.014</td> <td>    1.594</td> <td> 0.114</td> <td>   -0.005</td> <td>    0.050</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>24.839</td> <th>  Durbin-Watson:     </th> <td>   1.956</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td>  43.550</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 0.942</td> <th>  Prob(JB):          </th> <td>3.49e-10</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 5.354</td> <th>  Cond. No.          </th> <td>    2.61</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nnw_pol11\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVTSALES</td>    <th>  R-squared:         </th> <td>   0.028</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.002</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.070</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.365</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:29</td>     <th>  Log-Likelihood:    </th> <td>  135.80</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   115</td>      <th>  AIC:               </th> <td>  -263.6</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   111</td>      <th>  BIC:               </th> <td>  -252.6</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n       <td></td>          <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th>   <td>    0.0289</td> <td>    0.026</td> <td>    1.102</td> <td> 0.273</td> <td>   -0.023</td> <td>    0.081</td>\n</tr>\n<tr>\n  <th>C(T)[T.1.0]</th> <td>    0.0095</td> <td>    0.032</td> <td>    0.297</td> <td> 0.767</td> <td>   -0.054</td> <td>    0.073</td>\n</tr>\n<tr>\n  <th>streat</th>      <td>   -0.0034</td> <td>    0.009</td> <td>   -0.361</td> <td> 0.719</td> <td>   -0.022</td> <td>    0.015</td>\n</tr>\n<tr>\n  <th>snotreat</th>    <td>    0.0037</td> <td>    0.005</td> <td>    0.754</td> <td> 0.453</td> <td>   -0.006</td> <td>    0.013</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>25.510</td> <th>  Durbin-Watson:     </th> <td>   2.005</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td>  47.309</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 0.939</td> <th>  Prob(JB):          </th> <td>5.33e-11</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 5.519</td> <th>  Cond. No.          </th> <td>    21.8</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nnw_pol22 \n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVTSALES</td>    <th>  R-squared:         </th> <td>   0.054</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.010</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.239</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.296</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:29</td>     <th>  Log-Likelihood:    </th> <td>  137.34</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   115</td>      <th>  AIC:               </th> <td>  -262.7</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   109</td>      <th>  BIC:               </th> <td>  -246.2</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     5</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.1134</td> <td>    0.056</td> <td>    2.008</td> <td> 0.047</td> <td>    0.001</td> <td>    0.225</td>\n</tr>\n<tr>\n  <th>T</th>         <td>   -0.0787</td> <td>    0.060</td> <td>   -1.305</td> <td> 0.195</td> <td>   -0.198</td> <td>    0.041</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>    0.0067</td> <td>    0.031</td> <td>    0.212</td> <td> 0.833</td> <td>   -0.056</td> <td>    0.069</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>    0.0422</td> <td>    0.023</td> <td>    1.809</td> <td> 0.073</td> <td>   -0.004</td> <td>    0.089</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>   -0.0033</td> <td>    0.010</td> <td>   -0.334</td> <td> 0.739</td> <td>   -0.023</td> <td>    0.016</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>    0.0037</td> <td>    0.002</td> <td>    1.688</td> <td> 0.094</td> <td>   -0.001</td> <td>    0.008</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>24.095</td> <th>  Durbin-Watson:     </th> <td>   2.030</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td>  40.794</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 0.931</td> <th>  Prob(JB):          </th> <td>1.39e-09</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 5.247</td> <th>  Cond. No.          </th> <td>    308.</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nnw_pol000 = ols(\"INVINTSALES ~ C(T) \", data = df_narr_wind).fit().summary()\n\nnw_pol111 = ols(\"INVINTSALES ~  C(T) + streat + snotreat \", data = df_narr_wind).fit().summary()\n\nnw_pol222 = ols(\"INVINTSALES ~ T + streat + snotreat + s2treat + s2notreat\", data = df_narr_wind).fit().summary()\n\n#nw_pol222 = ols(\"INVINTSALES ~ T + streat + snotreat + s2treat + s2notreat\", data = df_narr_wind).fit(cov_type='cluster').summary()\n```\n\n\n```python\nnw_pol000\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>       <td>INVINTSALES</td>   <th>  R-squared:         </th> <td>   0.007</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.002</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>  0.8056</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.371</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:29</td>     <th>  Log-Likelihood:    </th> <td>  154.81</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   115</td>      <th>  AIC:               </th> <td>  -305.6</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   113</td>      <th>  BIC:               </th> <td>  -300.1</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n       <td></td>          <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th>   <td>    0.0061</td> <td>    0.008</td> <td>    0.734</td> <td> 0.465</td> <td>   -0.010</td> <td>    0.023</td>\n</tr>\n<tr>\n  <th>C(T)[T.1.0]</th> <td>    0.0106</td> <td>    0.012</td> <td>    0.898</td> <td> 0.371</td> <td>   -0.013</td> <td>    0.034</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>67.299</td> <th>  Durbin-Watson:     </th> <td>   1.797</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 416.888</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.865</td> <th>  Prob(JB):          </th> <td>2.98e-91</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>11.549</td> <th>  Cond. No.          </th> <td>    2.61</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nnw_pol111\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>       <td>INVINTSALES</td>   <th>  R-squared:         </th> <td>   0.053</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.028</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   2.089</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.106</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:29</td>     <th>  Log-Likelihood:    </th> <td>  157.56</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   115</td>      <th>  AIC:               </th> <td>  -307.1</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   111</td>      <th>  BIC:               </th> <td>  -296.1</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n       <td></td>          <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th>   <td>   -0.0163</td> <td>    0.022</td> <td>   -0.750</td> <td> 0.455</td> <td>   -0.059</td> <td>    0.027</td>\n</tr>\n<tr>\n  <th>C(T)[T.1.0]</th> <td>    0.0586</td> <td>    0.026</td> <td>    2.221</td> <td> 0.028</td> <td>    0.006</td> <td>    0.111</td>\n</tr>\n<tr>\n  <th>streat</th>      <td>   -0.0158</td> <td>    0.008</td> <td>   -2.048</td> <td> 0.043</td> <td>   -0.031</td> <td>   -0.001</td>\n</tr>\n<tr>\n  <th>snotreat</th>    <td>   -0.0045</td> <td>    0.004</td> <td>   -1.115</td> <td> 0.267</td> <td>   -0.013</td> <td>    0.004</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>65.518</td> <th>  Durbin-Watson:     </th> <td>   1.766</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 400.467</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.806</td> <th>  Prob(JB):          </th> <td>1.10e-87</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>11.398</td> <th>  Cond. No.          </th> <td>    21.8</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nnw_pol222\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>       <td>INVINTSALES</td>   <th>  R-squared:         </th> <td>   0.071</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.028</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.656</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.151</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:29</td>     <th>  Log-Likelihood:    </th> <td>  158.61</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   115</td>      <th>  AIC:               </th> <td>  -305.2</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   109</td>      <th>  BIC:               </th> <td>  -288.8</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     5</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0427</td> <td>    0.047</td> <td>    0.910</td> <td> 0.365</td> <td>   -0.050</td> <td>    0.136</td>\n</tr>\n<tr>\n  <th>T</th>         <td>   -0.0006</td> <td>    0.050</td> <td>   -0.012</td> <td> 0.991</td> <td>   -0.100</td> <td>    0.099</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0153</td> <td>    0.026</td> <td>   -0.585</td> <td> 0.560</td> <td>   -0.067</td> <td>    0.037</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>    0.0224</td> <td>    0.019</td> <td>    1.153</td> <td> 0.251</td> <td>   -0.016</td> <td>    0.061</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>   -0.0002</td> <td>    0.008</td> <td>   -0.021</td> <td> 0.983</td> <td>   -0.017</td> <td>    0.016</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>    0.0026</td> <td>    0.002</td> <td>    1.418</td> <td> 0.159</td> <td>   -0.001</td> <td>    0.006</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>66.755</td> <th>  Durbin-Watson:     </th> <td>   1.742</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 427.866</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.829</td> <th>  Prob(JB):          </th> <td>1.23e-93</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>11.713</td> <th>  Cond. No.          </th> <td>    308.</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nIK_pol0 = ols(\"INVK ~ T \", data = df).fit().summary()\n\nIK_pol1 = ols(\"INVK ~ T + streat + snotreat \", data = df).fit().summary()\n\nIK_pol2 = ols(\"INVK ~ T +  +streat + snotreat + s2treat + s2notreat\", data = df).fit().summary()\n\nIK_pol3 = ols(\"INVK ~ T +  +streat + snotreat + s2treat + s2notreat + s3treat +s3notreat\", data = df).fit().summary()\n\n```\n\n\n```python\nIK_pol0\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>          <td>INVK</td>       <th>  R-squared:         </th> <td>   0.005</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.002</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.623</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.204</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:29</td>     <th>  Log-Likelihood:    </th> <td> -597.78</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>   1200.</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   355</td>      <th>  BIC:               </th> <td>   1207.</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.3540</td> <td>    0.128</td> <td>    2.775</td> <td> 0.006</td> <td>    0.103</td> <td>    0.605</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.1927</td> <td>    0.151</td> <td>    1.274</td> <td> 0.204</td> <td>   -0.105</td> <td>    0.490</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>351.340</td> <th>  Durbin-Watson:     </th> <td>   2.056</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>9611.151</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 4.296</td>  <th>  Prob(JB):          </th> <td>    0.00</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>26.923</td>  <th>  Cond. No.          </th> <td>    3.49</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nIK_pol1\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>          <td>INVK</td>       <th>  R-squared:         </th> <td>   0.021</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.013</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   2.539</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td>0.0564</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:29</td>     <th>  Log-Likelihood:    </th> <td> -594.78</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>   1198.</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   353</td>      <th>  BIC:               </th> <td>   1213.</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.3790</td> <td>    0.184</td> <td>    2.062</td> <td> 0.040</td> <td>    0.018</td> <td>    0.740</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.4700</td> <td>    0.236</td> <td>    1.992</td> <td> 0.047</td> <td>    0.006</td> <td>    0.934</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0331</td> <td>    0.014</td> <td>   -2.437</td> <td> 0.015</td> <td>   -0.060</td> <td>   -0.006</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>    0.0018</td> <td>    0.010</td> <td>    0.188</td> <td> 0.851</td> <td>   -0.017</td> <td>    0.021</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>345.841</td> <th>  Durbin-Watson:     </th> <td>   2.052</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>9045.158</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 4.208</td>  <th>  Prob(JB):          </th> <td>    0.00</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>26.179</td>  <th>  Cond. No.          </th> <td>    42.9</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nIK_pol2\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>          <td>INVK</td>       <th>  R-squared:         </th> <td>   0.024</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.010</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.705</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.133</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:29</td>     <th>  Log-Likelihood:    </th> <td> -594.31</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>   1201.</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   351</td>      <th>  BIC:               </th> <td>   1224.</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     5</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.1672</td> <td>    0.289</td> <td>    0.579</td> <td> 0.563</td> <td>   -0.401</td> <td>    0.735</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.6584</td> <td>    0.355</td> <td>    1.854</td> <td> 0.065</td> <td>   -0.040</td> <td>    1.357</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0255</td> <td>    0.048</td> <td>   -0.527</td> <td> 0.599</td> <td>   -0.121</td> <td>    0.070</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0359</td> <td>    0.041</td> <td>   -0.880</td> <td> 0.379</td> <td>   -0.116</td> <td>    0.044</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>   -0.0004</td> <td>    0.002</td> <td>   -0.164</td> <td> 0.870</td> <td>   -0.005</td> <td>    0.004</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>   -0.0008</td> <td>    0.001</td> <td>   -0.951</td> <td> 0.342</td> <td>   -0.003</td> <td>    0.001</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>346.778</td> <th>  Durbin-Watson:     </th> <td>   2.045</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>9166.885</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 4.221</td>  <th>  Prob(JB):          </th> <td>    0.00</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>26.345</td>  <th>  Cond. No.          </th> <td>2.45e+03</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.<br/>[2] The condition number is large, 2.45e+03. This might indicate that there are<br/>strong multicollinearity or other numerical problems.\n\n\n\n\n```python\nIK_pol3\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>          <td>INVK</td>       <th>  R-squared:         </th> <td>   0.028</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.009</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.447</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.185</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:29</td>     <th>  Log-Likelihood:    </th> <td> -593.49</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>   1203.</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   349</td>      <th>  BIC:               </th> <td>   1234.</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     7</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>   -0.0932</td> <td>    0.443</td> <td>   -0.210</td> <td> 0.834</td> <td>   -0.965</td> <td>    0.778</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    1.0831</td> <td>    0.515</td> <td>    2.101</td> <td> 0.036</td> <td>    0.069</td> <td>    2.097</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.1284</td> <td>    0.113</td> <td>   -1.135</td> <td> 0.257</td> <td>   -0.351</td> <td>    0.094</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.1100</td> <td>    0.104</td> <td>   -1.058</td> <td> 0.291</td> <td>   -0.315</td> <td>    0.095</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>    0.0121</td> <td>    0.013</td> <td>    0.958</td> <td> 0.339</td> <td>   -0.013</td> <td>    0.037</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>   -0.0053</td> <td>    0.006</td> <td>   -0.913</td> <td> 0.362</td> <td>   -0.017</td> <td>    0.006</td>\n</tr>\n<tr>\n  <th>s3treat</th>   <td>   -0.0004</td> <td>    0.000</td> <td>   -1.006</td> <td> 0.315</td> <td>   -0.001</td> <td>    0.000</td>\n</tr>\n<tr>\n  <th>s3notreat</th> <td>-6.602e-05</td> <td> 8.52e-05</td> <td>   -0.775</td> <td> 0.439</td> <td>   -0.000</td> <td>    0.000</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>343.742</td> <th>  Durbin-Watson:     </th> <td>   2.053</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>8820.883</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 4.176</td>  <th>  Prob(JB):          </th> <td>    0.00</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>25.875</td>  <th>  Cond. No.          </th> <td>1.53e+05</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.<br/>[2] The condition number is large, 1.53e+05. This might indicate that there are<br/>strong multicollinearity or other numerical problems.\n\n\n\n\n```python\nIA_pol0 = ols(\"INVA ~ T \", data = df).fit().summary()\n\nIA_pol1 = ols(\"INVA  ~ T + streat + snotreat \", data = df).fit().summary()\n\nIA_pol2 = ols(\"INVA  ~ T +  +streat + snotreat + s2treat + s2notreat\", data = df).fit().summary()\n\nIA_pol3 = ols(\"INVA  ~ T +  +streat + snotreat + s2treat + s2notreat + s3treat +s3notreat\", data = df).fit().summary()\n```\n\n\n```python\nIA_pol0\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>          <td>INVA</td>       <th>  R-squared:         </th> <td>   0.006</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.003</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   2.025</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.156</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:29</td>     <th>  Log-Likelihood:    </th> <td>  261.45</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>  -518.9</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   355</td>      <th>  BIC:               </th> <td>  -511.2</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0331</td> <td>    0.011</td> <td>    2.877</td> <td> 0.004</td> <td>    0.010</td> <td>    0.056</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0194</td> <td>    0.014</td> <td>    1.423</td> <td> 0.156</td> <td>   -0.007</td> <td>    0.046</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>100.857</td> <th>  Durbin-Watson:     </th> <td>   1.854</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td> 253.045</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.365</td>  <th>  Prob(JB):          </th> <td>1.13e-55</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 6.092</td>  <th>  Cond. No.          </th> <td>    3.49</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nIA_pol1\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>          <td>INVA</td>       <th>  R-squared:         </th> <td>   0.012</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.004</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.484</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.219</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:29</td>     <th>  Log-Likelihood:    </th> <td>  262.68</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>  -517.4</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   353</td>      <th>  BIC:               </th> <td>  -501.8</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0232</td> <td>    0.017</td> <td>    1.395</td> <td> 0.164</td> <td>   -0.010</td> <td>    0.056</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0441</td> <td>    0.021</td> <td>    2.065</td> <td> 0.040</td> <td>    0.002</td> <td>    0.086</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0016</td> <td>    0.001</td> <td>   -1.324</td> <td> 0.186</td> <td>   -0.004</td> <td>    0.001</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0007</td> <td>    0.001</td> <td>   -0.819</td> <td> 0.413</td> <td>   -0.002</td> <td>    0.001</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>102.214</td> <th>  Durbin-Watson:     </th> <td>   1.843</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td> 262.307</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.373</td>  <th>  Prob(JB):          </th> <td>1.10e-57</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 6.178</td>  <th>  Cond. No.          </th> <td>    42.9</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nIA_pol2\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>          <td>INVA</td>       <th>  R-squared:         </th> <td>   0.021</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.007</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.538</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.177</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:29</td>     <th>  Log-Likelihood:    </th> <td>  264.31</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>  -516.6</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   351</td>      <th>  BIC:               </th> <td>  -493.3</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     5</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>   -0.0072</td> <td>    0.026</td> <td>   -0.276</td> <td> 0.782</td> <td>   -0.058</td> <td>    0.044</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0620</td> <td>    0.032</td> <td>    1.935</td> <td> 0.054</td> <td>   -0.001</td> <td>    0.125</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>    0.0024</td> <td>    0.004</td> <td>    0.554</td> <td> 0.580</td> <td>   -0.006</td> <td>    0.011</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0061</td> <td>    0.004</td> <td>   -1.664</td> <td> 0.097</td> <td>   -0.013</td> <td>    0.001</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>   -0.0002</td> <td>    0.000</td> <td>   -0.966</td> <td> 0.335</td> <td>   -0.001</td> <td>    0.000</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>   -0.0001</td> <td> 8.02e-05</td> <td>   -1.513</td> <td> 0.131</td> <td>   -0.000</td> <td> 3.64e-05</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>97.410</td> <th>  Durbin-Watson:     </th> <td>   1.834</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 240.737</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.323</td> <th>  Prob(JB):          </th> <td>5.30e-53</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 6.030</td> <th>  Cond. No.          </th> <td>2.45e+03</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.<br/>[2] The condition number is large, 2.45e+03. This might indicate that there are<br/>strong multicollinearity or other numerical problems.\n\n\n\n\n```python\nIA_pol3\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>          <td>INVA</td>       <th>  R-squared:         </th> <td>   0.026</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.006</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.327</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.237</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:29</td>     <th>  Log-Likelihood:    </th> <td>  265.13</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>  -514.3</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   349</td>      <th>  BIC:               </th> <td>  -483.2</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     7</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>   -0.0317</td> <td>    0.040</td> <td>   -0.793</td> <td> 0.428</td> <td>   -0.110</td> <td>    0.047</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.1009</td> <td>    0.047</td> <td>    2.169</td> <td> 0.031</td> <td>    0.009</td> <td>    0.192</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0066</td> <td>    0.010</td> <td>   -0.645</td> <td> 0.519</td> <td>   -0.027</td> <td>    0.013</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0131</td> <td>    0.009</td> <td>   -1.396</td> <td> 0.164</td> <td>   -0.032</td> <td>    0.005</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>    0.0009</td> <td>    0.001</td> <td>    0.778</td> <td> 0.437</td> <td>   -0.001</td> <td>    0.003</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>   -0.0005</td> <td>    0.001</td> <td>   -1.032</td> <td> 0.303</td> <td>   -0.002</td> <td>    0.000</td>\n</tr>\n<tr>\n  <th>s3treat</th>   <td>-3.471e-05</td> <td> 3.55e-05</td> <td>   -0.976</td> <td> 0.330</td> <td>   -0.000</td> <td> 3.52e-05</td>\n</tr>\n<tr>\n  <th>s3notreat</th> <td>-6.215e-06</td> <td> 7.69e-06</td> <td>   -0.808</td> <td> 0.419</td> <td>-2.13e-05</td> <td> 8.91e-06</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>95.670</td> <th>  Durbin-Watson:     </th> <td>   1.836</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 231.086</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.310</td> <th>  Prob(JB):          </th> <td>6.61e-51</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 5.945</td> <th>  Cond. No.          </th> <td>1.53e+05</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.<br/>[2] The condition number is large, 1.53e+05. This might indicate that there are<br/>strong multicollinearity or other numerical problems.\n\n\n\n\n```python\nLC_pol0 = ols(\"LCSALES ~ T \", data = df).fit().summary()\n\nLC_pol1 = ols(\"LCSALES  ~ T + streat + snotreat \", data = df).fit().summary()\n\nLC_pol2 = ols(\"LCSALES  ~ T +  +streat + snotreat + s2treat + s2notreat\", data = df).fit().summary()\n\nLC_pol3 = ols(\"LCSALES  ~ T +  +streat + snotreat + s2treat + s2notreat + s3treat +s3notreat\", data = df).fit().summary()\n```\n\n\n```python\nLC_pol0\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>         <td>LCSALES</td>     <th>  R-squared:         </th> <td>   0.005</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.002</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.644</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.201</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:29</td>     <th>  Log-Likelihood:    </th> <td> -120.10</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>   244.2</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   355</td>      <th>  BIC:               </th> <td>   252.0</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.7346</td> <td>    0.033</td> <td>   21.947</td> <td> 0.000</td> <td>    0.669</td> <td>    0.800</td>\n</tr>\n<tr>\n  <th>T</th>         <td>   -0.0509</td> <td>    0.040</td> <td>   -1.282</td> <td> 0.201</td> <td>   -0.129</td> <td>    0.027</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>87.034</td> <th>  Durbin-Watson:     </th> <td>   2.022</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 212.560</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.185</td> <th>  Prob(JB):          </th> <td>6.97e-47</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 5.945</td> <th>  Cond. No.          </th> <td>    3.49</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nLC_pol1\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>         <td>LCSALES</td>     <th>  R-squared:         </th> <td>   0.007</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.002</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>  0.7904</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.500</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:29</td>     <th>  Log-Likelihood:    </th> <td> -119.73</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>   247.5</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   353</td>      <th>  BIC:               </th> <td>   263.0</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.7572</td> <td>    0.049</td> <td>   15.589</td> <td> 0.000</td> <td>    0.662</td> <td>    0.853</td>\n</tr>\n<tr>\n  <th>T</th>         <td>   -0.0549</td> <td>    0.062</td> <td>   -0.881</td> <td> 0.379</td> <td>   -0.178</td> <td>    0.068</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0020</td> <td>    0.004</td> <td>   -0.565</td> <td> 0.572</td> <td>   -0.009</td> <td>    0.005</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>    0.0016</td> <td>    0.003</td> <td>    0.643</td> <td> 0.520</td> <td>   -0.003</td> <td>    0.007</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>88.805</td> <th>  Durbin-Watson:     </th> <td>   2.011</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 222.457</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.198</td> <th>  Prob(JB):          </th> <td>4.94e-49</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 6.036</td> <th>  Cond. No.          </th> <td>    42.9</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nLC_pol2\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>         <td>LCSALES</td>     <th>  R-squared:         </th> <td>   0.014</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.000</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>  0.9662</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.438</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:29</td>     <th>  Log-Likelihood:    </th> <td> -118.48</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>   249.0</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   351</td>      <th>  BIC:               </th> <td>   272.2</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     5</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.8486</td> <td>    0.076</td> <td>   11.138</td> <td> 0.000</td> <td>    0.699</td> <td>    0.998</td>\n</tr>\n<tr>\n  <th>T</th>         <td>   -0.1535</td> <td>    0.094</td> <td>   -1.639</td> <td> 0.102</td> <td>   -0.338</td> <td>    0.031</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>    0.0003</td> <td>    0.013</td> <td>    0.022</td> <td> 0.983</td> <td>   -0.025</td> <td>    0.025</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>    0.0179</td> <td>    0.011</td> <td>    1.664</td> <td> 0.097</td> <td>   -0.003</td> <td>    0.039</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>   -0.0001</td> <td>    0.001</td> <td>   -0.188</td> <td> 0.851</td> <td>   -0.001</td> <td>    0.001</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>    0.0004</td> <td>    0.000</td> <td>    1.556</td> <td> 0.121</td> <td>-9.63e-05</td> <td>    0.001</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>89.659</td> <th>  Durbin-Watson:     </th> <td>   2.002</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 226.454</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.206</td> <th>  Prob(JB):          </th> <td>6.70e-50</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 6.067</td> <th>  Cond. No.          </th> <td>2.45e+03</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.<br/>[2] The condition number is large, 2.45e+03. This might indicate that there are<br/>strong multicollinearity or other numerical problems.\n\n\n\n\n```python\nLC_pol3\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>         <td>LCSALES</td>     <th>  R-squared:         </th> <td>   0.031</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.012</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.603</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.133</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:29</td>     <th>  Log-Likelihood:    </th> <td> -115.27</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>   246.5</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   349</td>      <th>  BIC:               </th> <td>   277.6</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     7</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    1.0569</td> <td>    0.116</td> <td>    9.104</td> <td> 0.000</td> <td>    0.829</td> <td>    1.285</td>\n</tr>\n<tr>\n  <th>T</th>         <td>   -0.3983</td> <td>    0.135</td> <td>   -2.950</td> <td> 0.003</td> <td>   -0.664</td> <td>   -0.133</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>    0.0231</td> <td>    0.030</td> <td>    0.780</td> <td> 0.436</td> <td>   -0.035</td> <td>    0.081</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>    0.0772</td> <td>    0.027</td> <td>    2.835</td> <td> 0.005</td> <td>    0.024</td> <td>    0.131</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>   -0.0029</td> <td>    0.003</td> <td>   -0.874</td> <td> 0.383</td> <td>   -0.009</td> <td>    0.004</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>    0.0039</td> <td>    0.002</td> <td>    2.581</td> <td> 0.010</td> <td>    0.001</td> <td>    0.007</td>\n</tr>\n<tr>\n  <th>s3treat</th>   <td> 8.802e-05</td> <td>    0.000</td> <td>    0.853</td> <td> 0.394</td> <td>   -0.000</td> <td>    0.000</td>\n</tr>\n<tr>\n  <th>s3notreat</th> <td> 5.284e-05</td> <td> 2.23e-05</td> <td>    2.368</td> <td> 0.018</td> <td> 8.95e-06</td> <td> 9.67e-05</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>82.310</td> <th>  Durbin-Watson:     </th> <td>   2.018</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 184.538</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.158</td> <th>  Prob(JB):          </th> <td>8.47e-41</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 5.653</td> <th>  Cond. No.          </th> <td>1.53e+05</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.<br/>[2] The condition number is large, 1.53e+05. This might indicate that there are<br/>strong multicollinearity or other numerical problems.\n\n\n\n\n```python\nSC_pol0 = ols(\"SCSALES ~ T \", data = df).fit().summary()\n\nSC_pol1 = ols(\"SCSALES  ~ T + streat + snotreat \", data = df).fit().summary()\n\nSC_pol2 = ols(\"SCSALES  ~ T +  +streat + snotreat + s2treat + s2notreat\", data = df).fit().summary()\n\nSC_pol3 = ols(\"SCSALES  ~ T +  +streat + snotreat + s2treat + s2notreat + s3treat +s3notreat\", data = df).fit().summary()\n```\n\n\n```python\nSC_pol0\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>         <td>SCSALES</td>     <th>  R-squared:         </th> <td>   0.006</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.003</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   2.243</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.135</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:30</td>     <th>  Log-Likelihood:    </th> <td> -271.08</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>   546.2</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   355</td>      <th>  BIC:               </th> <td>   553.9</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    1.0532</td> <td>    0.051</td> <td>   20.615</td> <td> 0.000</td> <td>    0.953</td> <td>    1.154</td>\n</tr>\n<tr>\n  <th>T</th>         <td>   -0.0907</td> <td>    0.061</td> <td>   -1.498</td> <td> 0.135</td> <td>   -0.210</td> <td>    0.028</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>177.828</td> <th>  Durbin-Watson:     </th> <td>   1.742</td> \n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>1112.630</td> \n</tr>\n<tr>\n  <th>Skew:</th>          <td> 2.032</td>  <th>  Prob(JB):          </th> <td>2.49e-242</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>10.635</td>  <th>  Cond. No.          </th> <td>    3.49</td> \n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nSC_pol1\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>         <td>SCSALES</td>     <th>  R-squared:         </th> <td>   0.015</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.007</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.780</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.151</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:30</td>     <th>  Log-Likelihood:    </th> <td> -269.52</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>   547.0</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   353</td>      <th>  BIC:               </th> <td>   562.6</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.9697</td> <td>    0.074</td> <td>   13.123</td> <td> 0.000</td> <td>    0.824</td> <td>    1.115</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0330</td> <td>    0.095</td> <td>    0.347</td> <td> 0.729</td> <td>   -0.154</td> <td>    0.220</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0044</td> <td>    0.005</td> <td>   -0.805</td> <td> 0.422</td> <td>   -0.015</td> <td>    0.006</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0060</td> <td>    0.004</td> <td>   -1.562</td> <td> 0.119</td> <td>   -0.014</td> <td>    0.002</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>177.686</td> <th>  Durbin-Watson:     </th> <td>   1.749</td> \n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>1161.972</td> \n</tr>\n<tr>\n  <th>Skew:</th>          <td> 2.010</td>  <th>  Prob(JB):          </th> <td>4.80e-253</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>10.871</td>  <th>  Cond. No.          </th> <td>    42.9</td> \n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nSC_pol2\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>         <td>SCSALES</td>     <th>  R-squared:         </th> <td>   0.016</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.002</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.139</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.339</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:30</td>     <th>  Log-Likelihood:    </th> <td> -269.33</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>   550.7</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   351</td>      <th>  BIC:               </th> <td>   573.9</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     5</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    1.0220</td> <td>    0.116</td> <td>    8.791</td> <td> 0.000</td> <td>    0.793</td> <td>    1.251</td>\n</tr>\n<tr>\n  <th>T</th>         <td>   -0.0080</td> <td>    0.143</td> <td>   -0.056</td> <td> 0.955</td> <td>   -0.289</td> <td>    0.273</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0081</td> <td>    0.019</td> <td>   -0.414</td> <td> 0.679</td> <td>   -0.046</td> <td>    0.030</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>    0.0033</td> <td>    0.016</td> <td>    0.200</td> <td> 0.841</td> <td>   -0.029</td> <td>    0.036</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>    0.0002</td> <td>    0.001</td> <td>    0.196</td> <td> 0.845</td> <td>   -0.002</td> <td>    0.002</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>    0.0002</td> <td>    0.000</td> <td>    0.584</td> <td> 0.560</td> <td>   -0.000</td> <td>    0.001</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>177.746</td> <th>  Durbin-Watson:     </th> <td>   1.749</td> \n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>1166.751</td> \n</tr>\n<tr>\n  <th>Skew:</th>          <td> 2.009</td>  <th>  Prob(JB):          </th> <td>4.40e-254</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>10.892</td>  <th>  Cond. No.          </th> <td>2.45e+03</td> \n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.<br/>[2] The condition number is large, 2.45e+03. This might indicate that there are<br/>strong multicollinearity or other numerical problems.\n\n\n\n\n```python\nSC_pol3\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>         <td>SCSALES</td>     <th>  R-squared:         </th> <td>   0.017</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.003</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>  0.8606</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.538</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:30</td>     <th>  Log-Likelihood:    </th> <td> -269.15</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>   554.3</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   349</td>      <th>  BIC:               </th> <td>   585.3</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     7</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    1.0576</td> <td>    0.179</td> <td>    5.920</td> <td> 0.000</td> <td>    0.706</td> <td>    1.409</td>\n</tr>\n<tr>\n  <th>T</th>         <td>   -0.0789</td> <td>    0.208</td> <td>   -0.380</td> <td> 0.704</td> <td>   -0.488</td> <td>    0.330</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>    0.0140</td> <td>    0.046</td> <td>    0.308</td> <td> 0.758</td> <td>   -0.076</td> <td>    0.104</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>    0.0134</td> <td>    0.042</td> <td>    0.320</td> <td> 0.749</td> <td>   -0.069</td> <td>    0.096</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>   -0.0025</td> <td>    0.005</td> <td>   -0.490</td> <td> 0.624</td> <td>   -0.012</td> <td>    0.008</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>    0.0008</td> <td>    0.002</td> <td>    0.350</td> <td> 0.727</td> <td>   -0.004</td> <td>    0.005</td>\n</tr>\n<tr>\n  <th>s3treat</th>   <td> 8.514e-05</td> <td>    0.000</td> <td>    0.536</td> <td> 0.592</td> <td>   -0.000</td> <td>    0.000</td>\n</tr>\n<tr>\n  <th>s3notreat</th> <td> 9.036e-06</td> <td> 3.43e-05</td> <td>    0.263</td> <td> 0.793</td> <td>-5.85e-05</td> <td> 7.66e-05</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>179.227</td> <th>  Durbin-Watson:     </th> <td>   1.747</td> \n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>1199.353</td> \n</tr>\n<tr>\n  <th>Skew:</th>          <td> 2.022</td>  <th>  Prob(JB):          </th> <td>3.66e-261</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>11.017</td>  <th>  Cond. No.          </th> <td>1.53e+05</td> \n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.<br/>[2] The condition number is large, 1.53e+05. This might indicate that there are<br/>strong multicollinearity or other numerical problems.\n\n\n\n\n```python\nIK_pol0 = ols(\"INVK ~ T \", data = df_wide_wind).fit().summary()\n\nIK_pol1 = ols(\"INVK  ~ T + streat + snotreat \", data =  df_wide_wind).fit().summary()\n\nIK_pol2 = ols(\"INVK  ~ T +  +streat + snotreat + s2treat + s2notreat\", data =  df_wide_wind).fit().summary()\n\n\n```\n\n\n```python\nIK_pol0\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>          <td>INVK</td>       <th>  R-squared:         </th> <td>   0.019</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.013</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   3.210</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td>0.0750</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:30</td>     <th>  Log-Likelihood:    </th> <td> -318.19</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   171</td>      <th>  AIC:               </th> <td>   640.4</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   169</td>      <th>  BIC:               </th> <td>   646.7</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.3792</td> <td>    0.174</td> <td>    2.181</td> <td> 0.031</td> <td>    0.036</td> <td>    0.722</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.4293</td> <td>    0.240</td> <td>    1.792</td> <td> 0.075</td> <td>   -0.044</td> <td>    0.902</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>174.192</td> <th>  Durbin-Watson:     </th> <td>   1.927</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>2985.047</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 4.003</td>  <th>  Prob(JB):          </th> <td>    0.00</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>21.838</td>  <th>  Cond. No.          </th> <td>    2.68</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nIK_pol1\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>          <td>INVK</td>       <th>  R-squared:         </th> <td>   0.020</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.003</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.153</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.329</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:30</td>     <th>  Log-Likelihood:    </th> <td> -318.05</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   171</td>      <th>  AIC:               </th> <td>   644.1</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   167</td>      <th>  BIC:               </th> <td>   656.7</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.2382</td> <td>    0.318</td> <td>    0.749</td> <td> 0.455</td> <td>   -0.390</td> <td>    0.866</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.5628</td> <td>    0.447</td> <td>    1.258</td> <td> 0.210</td> <td>   -0.321</td> <td>    1.446</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>    0.0028</td> <td>    0.100</td> <td>    0.028</td> <td> 0.978</td> <td>   -0.195</td> <td>    0.201</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0185</td> <td>    0.035</td> <td>   -0.530</td> <td> 0.597</td> <td>   -0.087</td> <td>    0.050</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>174.642</td> <th>  Durbin-Watson:     </th> <td>   1.930</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>3019.506</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 4.014</td>  <th>  Prob(JB):          </th> <td>    0.00</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>21.956</td>  <th>  Cond. No.          </th> <td>    27.1</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nIK_pol2\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>          <td>INVK</td>       <th>  R-squared:         </th> <td>   0.041</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.012</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.425</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.218</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:30</td>     <th>  Log-Likelihood:    </th> <td> -316.19</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   171</td>      <th>  AIC:               </th> <td>   644.4</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   165</td>      <th>  BIC:               </th> <td>   663.2</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     5</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>   -0.3108</td> <td>    0.569</td> <td>   -0.546</td> <td> 0.586</td> <td>   -1.435</td> <td>    0.813</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    1.5043</td> <td>    0.700</td> <td>    2.150</td> <td> 0.033</td> <td>    0.123</td> <td>    2.886</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.5164</td> <td>    0.358</td> <td>   -1.443</td> <td> 0.151</td> <td>   -1.223</td> <td>    0.190</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.1691</td> <td>    0.134</td> <td>   -1.259</td> <td> 0.210</td> <td>   -0.434</td> <td>    0.096</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>    0.1008</td> <td>    0.067</td> <td>    1.511</td> <td> 0.133</td> <td>   -0.031</td> <td>    0.232</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>   -0.0072</td> <td>    0.006</td> <td>   -1.161</td> <td> 0.247</td> <td>   -0.019</td> <td>    0.005</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>172.746</td> <th>  Durbin-Watson:     </th> <td>   1.968</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>2874.651</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 3.966</td>  <th>  Prob(JB):          </th> <td>    0.00</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>21.454</td>  <th>  Cond. No.          </th> <td>    692.</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\n\n```\n\n\n```python\nIA_pol0 = ols(\"INVA ~ T \", data = df_wide_wind).fit().summary()\n\nIA_pol1 = ols(\"INVA  ~ T + streat + snotreat \", data =  df_wide_wind).fit().summary()\n\nIA_pol2 = ols(\"INVA  ~ T +  +streat + snotreat + s2treat + s2notreat\", data =  df_wide_wind).fit().summary()\n\n```\n\n\n```python\nLC_pol0 = ols(\"LCSALES ~ T \", data = df_wide_wind).fit().summary()\n\nLC_pol1 = ols(\"LCSALES  ~ T + streat + snotreat \", data =  df_wide_wind).fit().summary()\n\nLC_pol2 = ols(\"LCSALES  ~ T +  +streat + snotreat + s2treat + s2notreat\", data =  df_wide_wind).fit().summary()\n```\n\n\n```python\nLC_pol0\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>         <td>LCSALES</td>     <th>  R-squared:         </th> <td>   0.000</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.006</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>0.009312</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.923</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:30</td>     <th>  Log-Likelihood:    </th> <td> -63.978</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   171</td>      <th>  AIC:               </th> <td>   132.0</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   169</td>      <th>  BIC:               </th> <td>   138.2</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.7196</td> <td>    0.039</td> <td>   18.304</td> <td> 0.000</td> <td>    0.642</td> <td>    0.797</td>\n</tr>\n<tr>\n  <th>T</th>         <td>   -0.0052</td> <td>    0.054</td> <td>   -0.097</td> <td> 0.923</td> <td>   -0.112</td> <td>    0.102</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>46.911</td> <th>  Durbin-Watson:     </th> <td>   2.234</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td>  95.416</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.259</td> <th>  Prob(JB):          </th> <td>1.91e-21</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 5.655</td> <th>  Cond. No.          </th> <td>    2.68</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nLC_pol1\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>         <td>LCSALES</td>     <th>  R-squared:         </th> <td>   0.079</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.063</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   4.803</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td>0.00310</td>\n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:30</td>     <th>  Log-Likelihood:    </th> <td> -56.907</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   171</td>      <th>  AIC:               </th> <td>   121.8</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   167</td>      <th>  BIC:               </th> <td>   134.4</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.9128</td> <td>    0.069</td> <td>   13.210</td> <td> 0.000</td> <td>    0.776</td> <td>    1.049</td>\n</tr>\n<tr>\n  <th>T</th>         <td>   -0.3024</td> <td>    0.097</td> <td>   -3.112</td> <td> 0.002</td> <td>   -0.494</td> <td>   -0.111</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>    0.0390</td> <td>    0.022</td> <td>    1.790</td> <td> 0.075</td> <td>   -0.004</td> <td>    0.082</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>    0.0253</td> <td>    0.008</td> <td>    3.346</td> <td> 0.001</td> <td>    0.010</td> <td>    0.040</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>48.488</td> <th>  Durbin-Watson:     </th> <td>   2.231</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 102.069</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.284</td> <th>  Prob(JB):          </th> <td>6.85e-23</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 5.781</td> <th>  Cond. No.          </th> <td>    27.1</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nLC_pol2\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>         <td>LCSALES</td>     <th>  R-squared:         </th> <td>   0.095</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.068</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   3.479</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td>0.00513</td>\n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:30</td>     <th>  Log-Likelihood:    </th> <td> -55.413</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   171</td>      <th>  AIC:               </th> <td>   122.8</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   165</td>      <th>  BIC:               </th> <td>   141.7</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     5</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.8467</td> <td>    0.124</td> <td>    6.835</td> <td> 0.000</td> <td>    0.602</td> <td>    1.091</td>\n</tr>\n<tr>\n  <th>T</th>         <td>   -0.1470</td> <td>    0.152</td> <td>   -0.965</td> <td> 0.336</td> <td>   -0.448</td> <td>    0.154</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0792</td> <td>    0.078</td> <td>   -1.017</td> <td> 0.311</td> <td>   -0.233</td> <td>    0.075</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>    0.0071</td> <td>    0.029</td> <td>    0.244</td> <td> 0.807</td> <td>   -0.051</td> <td>    0.065</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>    0.0229</td> <td>    0.015</td> <td>    1.580</td> <td> 0.116</td> <td>   -0.006</td> <td>    0.052</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>   -0.0009</td> <td>    0.001</td> <td>   -0.642</td> <td> 0.522</td> <td>   -0.004</td> <td>    0.002</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>46.049</td> <th>  Durbin-Watson:     </th> <td>   2.266</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td>  93.182</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.238</td> <th>  Prob(JB):          </th> <td>5.83e-21</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 5.636</td> <th>  Cond. No.          </th> <td>    692.</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nSC_pol0 = ols(\"SCSALES ~ T \", data = df_wide_wind).fit().summary()\n\nSC_pol1 = ols(\"SCSALES  ~ T + streat + snotreat \", data =  df_wide_wind).fit().summary()\n\nSC_pol2 = ols(\"SCSALES  ~ T +  +streat + snotreat + s2treat + s2notreat\", data =  df_wide_wind).fit().summary()\n```\n\n\n```python\nSC_pol0\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>         <td>SCSALES</td>     <th>  R-squared:         </th> <td>   0.000</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.006</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>0.008981</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.925</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:30</td>     <th>  Log-Likelihood:    </th> <td> -131.42</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   171</td>      <th>  AIC:               </th> <td>   266.8</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   169</td>      <th>  BIC:               </th> <td>   273.1</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.9997</td> <td>    0.058</td> <td>   17.141</td> <td> 0.000</td> <td>    0.885</td> <td>    1.115</td>\n</tr>\n<tr>\n  <th>T</th>         <td>   -0.0076</td> <td>    0.080</td> <td>   -0.095</td> <td> 0.925</td> <td>   -0.166</td> <td>    0.151</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>133.535</td> <th>  Durbin-Watson:     </th> <td>   1.987</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>1566.584</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 2.816</td>  <th>  Prob(JB):          </th> <td>    0.00</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>16.717</td>  <th>  Cond. No.          </th> <td>    2.68</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nSC_pol1\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>         <td>SCSALES</td>     <th>  R-squared:         </th> <td>   0.004</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.014</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>  0.2100</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.889</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:30</td>     <th>  Log-Likelihood:    </th> <td> -131.10</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   171</td>      <th>  AIC:               </th> <td>   270.2</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   167</td>      <th>  BIC:               </th> <td>   282.8</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    1.0700</td> <td>    0.107</td> <td>   10.033</td> <td> 0.000</td> <td>    0.859</td> <td>    1.281</td>\n</tr>\n<tr>\n  <th>T</th>         <td>   -0.0770</td> <td>    0.150</td> <td>   -0.513</td> <td> 0.608</td> <td>   -0.373</td> <td>    0.219</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0003</td> <td>    0.034</td> <td>   -0.010</td> <td> 0.992</td> <td>   -0.067</td> <td>    0.066</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>    0.0092</td> <td>    0.012</td> <td>    0.788</td> <td> 0.432</td> <td>   -0.014</td> <td>    0.032</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>133.915</td> <th>  Durbin-Watson:     </th> <td>   1.980</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>1577.546</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 2.826</td>  <th>  Prob(JB):          </th> <td>    0.00</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>16.765</td>  <th>  Cond. No.          </th> <td>    27.1</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nSC_pol2\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>         <td>SCSALES</td>     <th>  R-squared:         </th> <td>   0.018</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.012</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>  0.6011</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.699</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:30</td>     <th>  Log-Likelihood:    </th> <td> -129.88</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   171</td>      <th>  AIC:               </th> <td>   271.8</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   165</td>      <th>  BIC:               </th> <td>   290.6</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     5</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.8824</td> <td>    0.191</td> <td>    4.608</td> <td> 0.000</td> <td>    0.504</td> <td>    1.260</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.1973</td> <td>    0.235</td> <td>    0.838</td> <td> 0.403</td> <td>   -0.267</td> <td>    0.662</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.1150</td> <td>    0.120</td> <td>   -0.955</td> <td> 0.341</td> <td>   -0.353</td> <td>    0.123</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0423</td> <td>    0.045</td> <td>   -0.936</td> <td> 0.351</td> <td>   -0.131</td> <td>    0.047</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>    0.0223</td> <td>    0.022</td> <td>    0.992</td> <td> 0.323</td> <td>   -0.022</td> <td>    0.067</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>   -0.0025</td> <td>    0.002</td> <td>   -1.179</td> <td> 0.240</td> <td>   -0.007</td> <td>    0.002</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>132.591</td> <th>  Durbin-Watson:     </th> <td>   2.011</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>1519.453</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 2.798</td>  <th>  Prob(JB):          </th> <td>    0.00</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>16.488</td>  <th>  Cond. No.          </th> <td>    692.</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nIK_pol0 = ols(\"INVK ~ T \", data = df_narr_wind).fit().summary()\n\nIK_pol1 = ols(\"INVK  ~ T + streat + snotreat \", data =  df_narr_wind).fit().summary()\n\nIK_pol2 = ols(\"INVK  ~ T +  +streat + snotreat + s2treat + s2notreat\", data =  df_narr_wind).fit().summary()\n```\n\n\n```python\nIK_pol0\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>          <td>INVK</td>       <th>  R-squared:         </th> <td>   0.012</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.003</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.362</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.246</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:31</td>     <th>  Log-Likelihood:    </th> <td> -212.03</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   115</td>      <th>  AIC:               </th> <td>   428.1</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   113</td>      <th>  BIC:               </th> <td>   433.5</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.3309</td> <td>    0.203</td> <td>    1.634</td> <td> 0.105</td> <td>   -0.070</td> <td>    0.732</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.3358</td> <td>    0.288</td> <td>    1.167</td> <td> 0.246</td> <td>   -0.234</td> <td>    0.906</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>143.552</td> <th>  Durbin-Watson:     </th> <td>   2.028</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>3197.795</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 4.595</td>  <th>  Prob(JB):          </th> <td>    0.00</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>27.143</td>  <th>  Cond. No.          </th> <td>    2.61</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nIK_pol1\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>          <td>INVK</td>       <th>  R-squared:         </th> <td>   0.040</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.014</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.550</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.206</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:31</td>     <th>  Log-Likelihood:    </th> <td> -210.36</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   115</td>      <th>  AIC:               </th> <td>   428.7</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   111</td>      <th>  BIC:               </th> <td>   439.7</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>   -0.1590</td> <td>    0.533</td> <td>   -0.298</td> <td> 0.766</td> <td>   -1.215</td> <td>    0.897</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    1.2882</td> <td>    0.647</td> <td>    1.991</td> <td> 0.049</td> <td>    0.006</td> <td>    2.571</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.2866</td> <td>    0.190</td> <td>   -1.512</td> <td> 0.133</td> <td>   -0.662</td> <td>    0.089</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0990</td> <td>    0.100</td> <td>   -0.993</td> <td> 0.323</td> <td>   -0.297</td> <td>    0.099</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>138.304</td> <th>  Durbin-Watson:     </th> <td>   2.043</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>2744.380</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 4.384</td>  <th>  Prob(JB):          </th> <td>    0.00</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>25.268</td>  <th>  Cond. No.          </th> <td>    21.8</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\nIK_pol2\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>          <td>INVK</td>       <th>  R-squared:         </th> <td>   0.055</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.012</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.269</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.282</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:31</td>     <th>  Log-Likelihood:    </th> <td> -209.46</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   115</td>      <th>  AIC:               </th> <td>   430.9</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   109</td>      <th>  BIC:               </th> <td>   447.4</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     5</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0861</td> <td>    1.153</td> <td>    0.075</td> <td> 0.941</td> <td>   -2.199</td> <td>    2.371</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    1.3292</td> <td>    1.230</td> <td>    1.080</td> <td> 0.282</td> <td>   -1.109</td> <td>    3.767</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -1.0745</td> <td>    0.642</td> <td>   -1.675</td> <td> 0.097</td> <td>   -2.346</td> <td>    0.197</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>    0.0128</td> <td>    0.477</td> <td>    0.027</td> <td> 0.979</td> <td>   -0.932</td> <td>    0.957</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>    0.2626</td> <td>    0.204</td> <td>    1.285</td> <td> 0.201</td> <td>   -0.142</td> <td>    0.667</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>    0.0108</td> <td>    0.045</td> <td>    0.240</td> <td> 0.811</td> <td>   -0.078</td> <td>    0.100</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>137.018</td> <th>  Durbin-Watson:     </th> <td>   2.050</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>2648.312</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 4.331</td>  <th>  Prob(JB):          </th> <td>    0.00</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>24.855</td>  <th>  Cond. No.          </th> <td>    308.</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\n\n```python\n\n```\n\n\n```python\nIA_pol0 = ols(\"INVA ~ T \", data = df_narr_wind).fit().summary()\n\nIA_pol1 = ols(\"INVA   ~ T + streat + snotreat \", data =  df_narr_wind).fit().summary()\n\nIA_pol2 = ols(\"INVA   ~ T +  +streat + snotreat + s2treat + s2notreat\", data =  df_narr_wind).fit().summary()\n```\n\n\n```python\nLC_pol0 = ols(\"LCSALES ~ T \", data = df_narr_wind).fit().summary()\n\nLC_pol1 = ols(\"LCSALES   ~ T + streat + snotreat \", data =  df_narr_wind).fit().summary()\n\nLC_pol2 = ols(\"LCSALES   ~ T +  +streat + snotreat + s2treat + s2notreat\", data =  df_narr_wind).fit().summary()\n```\n\n\n```python\nSC_pol0 = ols(\"SCSALES ~ T \", data = df_narr_wind).fit().summary()\n\nSC_pol1 = ols(\"SCSALES   ~ T + streat + snotreat \", data =  df_narr_wind).fit().summary()\n\nSC_pol2 = ols(\"SCSALES   ~ T +  +streat + snotreat + s2treat + s2notreat\", data =  df_narr_wind)\n```\n\n\n```python\n#from lmfit import Model\n```\n\n##                                           I. Conceptual Framework and Empirical Evidence\n\nAlthough theoritically government R&D  subsidies leads to a decline in the capital cost, an increase in investment profitability and subsequently expansion of firms\u2019 R&D investment, the type of project which is funded determines the grant's effectiveness. The policy would be effective if the grant triggers the marginal projects, which would not have been profitable without public funding. However, the program would be ineffective if the grant finances the inframarginal projects, which would have been undertaken even in the absence of public grant because of their profitability. Under these conditions, the substitution of private for public funding to exploit the lower capital cost of public subsidies will happen without any positive impact on R&D investment. \n\n\nTo assess the program\u2019s effectiveness, we take three considerations. First, Ceteris paribus, the sucess of program might be affected by subsidizing the projects which were regonized as privately financed unprofitable by their companies because the firms face asymmetric information and problems in accessing markets of capital.\n\nSecond, firms are less willing to finance  since the risk of R&D investments is higher and the importance of  R&D is less clear for companies. Moreover, the asymmetric information and the fear of leaks of their idea to rival agents keep them from sharing their knowledge with financial intermediaries. from another angle, the intermediaries may be eager to reward the tangible investments to keep the chance of being colleteral  rather than intagible ones ????whose profits come in futur???????.\n\n\n\n\n\n\neffective, ineffective\nubsidy,grant, incentive\nreward, subsidize,privately financed\nundertaken, made, triggered, activate\nrecipient firms\nR&D spending, \n\nThird, even the professional public committee might not be able to differentiate between marginal and inframarginal projects due to lack of all necessary information , which decreases the effectiveness of program. Furthermore, government institutions might be applead to funding inframarginal since the probability of their success is higher and they can convince publict opiniion about the effectiveness of the policy.\nBesides the abovementioned directs impacts, there are several positive indirect effects producing the crowding in to increase the potential outcome. the assignment of grant may demonstrate the projects profitabilita reducing the as info and cost of capital . In addition, bz means of the public funds fidms could upgrade their eqipments and hire wellskilled researched which benefit current and subsequent projects leading to an increase in future  profit streams. \n\non the other side of negetive indirect effects  generate the crowding out.In presence of price inelasiticiz of r and d input supplz. the dmand shift for input would onlz raise the cost of projrcts. \nConsidering abovementioned arguments, the effectiveness of grant would be an emprical question to answer.\n\n\n##          A. Empirical Evidence\n\nThe  review  of  the  eprical literature on the effects of R&D subsidies shows the major challenge  in evaluation of policy is that that the firms in treatment and control groups are not randomly chosen. That is, there are crucial unobservable characteristics in correlation with outcome variable which differentiate the fundend companies from non-funded ones, therefore, the identifying feature for subsidy assignment is enfogenout. the paper argues that recent researches addressed the enfogenity problem through the matching or instrumenta variable methods and the results are usually sensentive to the selection of methodology.\n\nThe endogeneity problem has been addressed in recent analyses mainly through matching methods or instrumental variable estimates. \nHowever, irrespective of the strategy adopted, the conclusions of earlier studies are mixed. Surveying firm-level analyses conducted in the previous three decades, David, Hall, and Toole (2000) observe that almost one-half (9 out of 19) of the policies were not found to trigger additional investment while for the other half the opposite\nwas true. More recent evidence is similarly inconclusive. In the case of the Small Business Innovation Research program in the United States, two studies reach opposite conclusions. Matching subsidized and unsubsidized firms by industry and size, Lerner (1999) finds that the policy increased the sales and employment of subsidized firms. By contrast, Wallsten (2000), using the amount of public funds available for each type of R&D investment in each year as an instrument for the subsidy, shows that grants did not lead to an increase in employment and that the public\nsubsidy crowded out firm-financed R&D dollar for dollar. The evidence available for other countries is also mixed. For Israel, Lach (2002) finds that grants createdadditional R&D investment for small firms but, since the greatest share of the subsidies was given to large firms that did not make additional investment, the overall impact was null. He compared the performance of subsidized and nonsubsidized firms using difference-in-differences (DID) estimates and controlling for severalobservables. Almus and Czarnitzki (2003) use matching strategies to study R&D subsidies in Eastern Germany, finding an overall positive and significant effect oninvestment. Gonz\u00e1lez, Jaumandreu, and Paz\u00f3 (2005) examine the effects of R&Dpolicies in Spain, estimating simultaneously the probability of obtaining a subsidy,\nassuming a set of firms\u2019 observables as predetermined (e.g., size, age, industry, location, capital growth), and the impact of the grant on investment. They find a positive,albeit very small, effect on private investment that turns out to be significantly largerfor small firms. Combining the matching method with DID estimations, G\u00f6rg and Strobl (2007) find that in Ireland only small grants had additional effects on private R&D investment, while large grants crowded out private investment. Hussinger(2008) uses two-step selection models to show that in Germany public subsidies\nwere effective in promoting firms\u2019 R&D investment. Finally, Jacob and Lefgren (2011) use a similar method to ours to estimate the impact of public grants on US researchers\u2019 output measured by the number of published articles and citations, and find a limited impact of public support. Meanwhile Takalo, Tanayama, and Toivanen\n(2013), using a structural model estimated on firm-level data from Finland, find positive general equilibrium effects of the subsidies on expected welfare\u2014i.e., the expected benefits of the program net of its costs\u2014although the expected effects of the incentives are highly heterogeneous.\n\n\n\n\nThe geographic area covered by the policy isdescribed in Figure A1 in the Appendix.\n\n## II. The Program\n\n\nIn 2003, the inauguration of the \u201cRegional Program for Industrial Research, Innovation and Technological Transfer,\u201d by the govenrment of Emilia-Romagna leads to implementation of the public financing R&D program  according to the Article 4 of Regional Law 7/2002. The goal of program is to get behind the enterprises' research in the region and help them with the precompetitive development activities _the activity necessary to convert the output of research\ninto a plan, project, or design for the realization of new products or processes or\nthe improvement of existing ones(Bronzinin and lachini)_. The plan requie the regional\ngovernment to funds eligible firms for their R&D expenditures. The subsidy is planned to cover the expenses of research projects up to 50 percent and precompetitive development projects up to 25 percent; there might be an extention of 10 percent for precompetitive develoment activities for small- or medium-sized enterprises. the maximum fund woudl be \u20ac250,000. the program period  is from 1 to 2 years but extendable. the subsidy transfer could be done in two ways: one payment at the end of project or in two installments the first at the halfway of project and the second at the time of completion.\nthe projects which are eligible to be subsidized are as follow: (i) costs\nfor machinery and equipment; (ii) software; (iii) purchase and registration of\npatents and licenses; (iv) employment of researchers; (v) the use of laboratories;\n(vi) contracts with research centers; (vii) consulting; (viii) feasibility studies; and\n(ix) external costs for the realization of prototypes.(Bronzinin and lachini) \n\n\nOne critical issue is that whether the effect of regional program could be mixed with other kinds of public subsidies.However, this problem would be addressed bz the fact that each project could onlz receive one tzpe of public grant. In addition, the probability of subsiidy assignment is independent from the amount of demanded fund.  The regional government designates a committe of independent professionals to assign a score for each of aspects mentioned below: \n(i) technological and scientific (max. 45 points); (ii) financial and economic (max.\n20 points); (iii) managerial (max. 20 points); and (iv) regional impact (max.\n15 points).7 Only projects deemed sufficient in each category and which obtain a\ntotal score of at least 75 points receive the grants (the maximum score is 100). For\nthe evaluation process, both the committee and the independent evaluators must\ncomply with the general principles for the evaluation of research specified by the\nMinistry of Education, University and Research of the Italian Government, and the\ngeneral principles of the European Commission.\nthere were two rounds of applications, deadlines and evaluation process.the size of grants for industrial firms which are used for the estimation of their paper was \u20ac182,000 on average.\n\n\n##                               III. Empirical Strategy and Data\n\n###                                 A. Empirical Strategy\n\n As described before, the difficulty of the program's evaluation is the endogenity of characteristic which identifies the recipient firms since the difference of treated and untreated agents are related to unobserved features correlated with the response variable. Bronzini and lachini utilized the mechanism of the funds\u2019 assignment to address the endogenity problem. That is, the committee graded each project and only thosereceiving a score greater than or equal to a threshold of 75 points out of 100  won subsidies.\n\nFor performance comparison of subsidized and nonsubsidized enterprises with scores nearby the threshold, the paper applies a sharp regression discontinuity (RD) design. Their reason to apply sharp RDD is that the the treatment status ( $T_{i}$ ) is deterministic and discontinuous function of the paper's running variable which is score with discontinuity at the cutoff score(75 point).\n\n \n\\begin{equation}\n T_{i} = \\begin{cases}\n       1 & \\text{if score $\\geq$ 75}  \\\\\n       0  & \\text{if score < 75}  \n     \\end{cases}\n\\end{equation}\n\nThe outcome variable is set to be a function of the score. In this way, the program's average treatment effect (ATE) is evaluated through the value of the discontinuity estimated at the cutoff point.\n\nReasoning that the utilization of RDD is growing in quasi-experimental studies in economics after ( Angrist and Lavy (1999);\nBlack (1999); and van der Klaauw (2002)), Bronzini and lachini arque that the RD method performs better to contril the treatment endogeneity rather than other nonexperimental strategies. Their reason is that under satisfied conditions, is is likely to demonstrate that there is a randomized experiment around the cutoff point. knowing that  the score (running variable) is not fully manipulatable around th ethreshold. The randomness aroung the threshold could be detected by looking at the densitz of the score (McCrary 2008). In addition, they test the randomization assuption by checking whether  the subsidized and non subsidiezed firms around the thereshold are similar enough or in another way of saying by verifying if observable differences of two groups become negligble. The similarity of the two groups is a consequence of randomization and\nnot vice versa (Lee 2008).\n\nIn absence of a direct way of testing the validity of the continiuty hypothesis claiming that covariates,  they refer to Lee (2008) arguing formally that  the continuity assumption is satisfied if the treatment relies on whether a running variable surpasses a certain threshold and that running variable is not under the control of the agent. under these conditins, the treatment's variation is randomized around the cutoff meaning that the agents are randomly drawn just above and just below the threshold and the effect of program could be identified by the discontinuity of the outcome variable at the cutoff point (Hahn, Todd,and van der Klaauw 2001). However, they present an indirec way for the robustness check of continiuty assumption in Section V by assessing whether observable and unobservable variables  correlated with the outcome variable or outcome variable in the absence of program are continuious across the RD threshold. In their case they test that the firms close to cutoff point have the same identical potential outcome in a qeivalent subsidy experience.\n\n\n\nRegarding the susebtibility of RDD model to the choice of the functional form or the threshold interva in the local regressions, they check the robustness of their model by using different functional forms and econometric models. By refering to (see, amongst others: Imbens and Lemieux 2008; Lee and Lemieux 2010)they utilize the several test for the threshold discontinuity.\n\n\nThey use both parametric and nonparametric models.\nIn try of parametric models, first, They estimate different polynomial models form zero to third ordered ones over the full sample:\n\n\\begin{equation}\n(1) Y_{i} = \\alpha + \\beta T_{i} + (1 \u2212 T_{i}) \\sum_{i = 1}^{3} \\gamma_{i} (S_{i})^p + T_{i}\\sum_{i = 1}^{3}\\gamma_{i}' (S_{i})^p + \\epsilon_{i}\n\\end{equation}\n\nwhere the outcome variable is denoted by $Y_{i}$; $T_{i} = 1$ if company is funded because of being scored above or equal to 75 and $T_{i} = 0$ otherwise; S_{i} = Score_{i} \u2212 75; the parameters of grade's function are denoted by \u03b3_{p} and \u03b3_{i}\u2032 on both sides of the threshold with possible different value to address the function heterogeneity across the cuttoff point; \n; and \u03b5i is the error term. They run the polynomial of order zero to check the mean difference between treated and untreated enterprises. \nSecond, two different sample windows are considered to estimate the equation (1) by local regressions aaround threshold. The wide window contains half of the baseline sample (scores in the 52 to 80 range); the narrow window consists of 35 percent of the full sample (companies with scores between 66 and 78). The reason of chosen ranges is to almaost balance the number of companies above and below of threshold. the number of observations in the neigbourhood of cutoff point is relativelz low  ( 171 firms in wide window  and 115 in narrow widnow )which leads to imprecised estimation of higher-order polynomial models(see Lee and Lemieux 2010), to deal wit this issue thez estmate up to 2nd order of  the polznomila for the\nlocal regressions around the cutoff.\nThird, they use the nonparametric techniques named the Epanechnikov kernel regressions  with two bandwidths of 30 and 15  to estimate the discontinuity (the results are presented and discussed in Section V).\n\n\nthe correct specification of equation 1 leads to estmation of parameter Beta trhrough OLS model, the beta is measuring the amount of the function\u00c4s discontinuitz  at the threshold which is correspond to the unbiased estimate of program\u00e4s causal effect.however, the random error might be correlated within the group not unlike the cases discussed by Moulton 1990)dbecause of discrete  forcing variable \n meaning that the grade could be \n only integer value.\n \n since the groups close the dutoff receive the same score. the standard errors are underestimated(downward-biased) and might significanebut spurius siginifance occure. to deal with that thez clustere the the heteroskesadticitz robust standard errors bz the normalize score S\nIn our study, the groups are represented by firms that received the same score. moreover , in kernel regressions thez cluster and bootstrap the standard errors.\n\n\n\n\n\n### B. outcome Variables and Data\n\n   the usual suspect for the outcome variable is the amount of firm's R&D investment. However, due to the unavailability of data of R&D since expenditure, they construct their analysis based on the data of almost all Italian corporation's balance-sheets gathered by Cerved group.\n    \n   They take the reimbursable outlays as outcome variables. Their aim is to observe whether a significant raise in at least one of mentioned outcome variables for subsidized firms happen, comparing to nonsubsidized companies. The noticable increase in those item could  demonstrate that the program made some outlays possible that would not have been made withut public fund.\n\n\nThe main reimbursable expenditures are tangible or intangible assets, such as costs for machinery and quipment, software, patents, and licenses. So they take the net tangible investment as their frist and foremost outcome variable. They argue that the net intangible investment would be another outcome variable because in Italy 40 percen of innovation projects are included in tangible assets(Istituto Nazionale di Statistica 2010). The net investment is annual diffrence in tangible or intangible assets net of amortization, which drived from the balance sheet. \n\n\nThe paper builds the evaluation only on total amount of intangible and tangible assets for three reasons. The first reason is inconsistency of different firms' financial reports. Only some large firms provide the Italian Civil Code with the detailed financial statment and  other firms usually smaller ones merely report the total amount of financial items. Furthermore, the information on total items are more precise than detailed ones. Also, based on a sample of five firms, it was shown that eligible expenditures for subsidies(R&D, patents, software and other intellectual property rights, licences, trademark, and ongoing intangible assets) consist of 66 percent of the total intangible assets and goodwill which is not covered by subsidy occupies 22 percent of intangible assests; therefore, despite being aware of a second-\norder bias by goodwill, the reason that the total intangible  and tangible investments are reasonable outcome variables\n \n\nMoreove, knowing that employment of researches are included in other reimbursable outlays, they consider other three outcome variables: labor costs, level of employment, and wages. From theory point of view , the program leads to substitution of researches (high skilled employees) for low-skilled workers and subsequently an increase in labor costs. Labor costs divided by the number of employees gives the wages. if wages increases the demand for higher_skilled employees goes up and program benefited the employees as shown by Goolsbee (1998).\n\nIN addtion,  the firm buys some servises or pays for laboratories, contracts with\nresearch centers, consulting, feasibility studies, and external costs for the realization\nof prototypes for R&D projects. for this reason , service costs are considered as another outcome variable. With this strategy thez study the effect of program on different kinds of r and d spendings.\n\nWrap it up, they evaluate the program's effect on the following outcome variables: investment (total, tangible, and intangible), labor costs, employment, wages and service costs. \n\nThe expected period of project's realization is three years( the year of assignment plus two next years) to detect all potential changes. Also, to avoid the potential endogeneity, all outcome variables are scaled pre-program sales(the first year before te program). The employment and wages are used as log form. Finally, to prevent the outliers to drive the results because of volatility of investment during the time and unevenness of variables across the firms , they trimmeds the sample trimmed\nthe sample according to the fifth and ninety-fifth percentile of the distribution of Total investmenti/Pre-programsalesi \n(Bronyini lachini, 2014). 1,2046 compnaies submitted their proposals and 557 were chosen to be treatd  and 689 to be untreated. but amon 689 untreated firms 411 of them were excluded in the second year because their projects were inefficient. the paper claims that their exclusion does not affect on the study since even if they recieved the score, they would have been far from the cutoff point whose discontinuity matters to be tested. therefore, their ommision does not make any bias. they also omit the statups and very small enterprises which are underrepresented. after cleaning the sample, the full sample with major share of grants becomes 357 industrial firms (254 treated and 103 untreated) and 111 service firms\n(of which 61 were treated).\n  Because of considerable heterpgeneity of industrial and service firms which might generate nhuge noise, they concentreated on industrial firms ( the vast majority was manufacturing and construction)which compares homogenous enterprises\n\nthe number of subsidized firms are almost doubled that of nonsubsideyed because nonscored firms in the second round were excluded. However, the within sector 's proportion is balanced.\n \n\n(((((From the balance sheets we take as outcome variables those items that are associated with the expenditures reimbursable by the program listed in Section II.))))\n\nIn Figure 1 the density function of the sample by score is shown. The density is\nhigher on the right-hand side of the threshold because of the cited exclusion of nonscored untreated firms in the second round and increases substantially around the\ncutoff point. We observe, however, that just below the cutoff (score = 74) it is lower\nthan at slightly more distant values.\nWe do not interpret this drop as the signal that firms just below the threshold\nwere able to manipulate their score. Rather, we believe that the committee of experts\navoided assigning a score just below the threshold for understandable reasons. A\nsimilar outcome could have been perceived as particularly annoying by unsuccessful applicant firms and would potentially have left more room for appeals against the\ndecision. If anything, this evidence shows that the committee enjoys a certain degree\nof discretion in assigning the score, a characteristic of the assessment that does not\ninvalidate our design.\nIV. Results\nA. Baseline Results\nWe first present the estimations of the coefficient \u03b2 of model (1) using total, tangible, and intangible investment scaled by pre-program sales as outcome variables.\nSince we do not observe privately financed investment separately from that financed\nby public incentive, we shall now briefly discuss how to interpret the results. A coefficient \u03b2 equal to zero would signal complete crowding-out of private investment\nby public grants: firms reduced private expenditure by the amount of the subsidies\nreceived and the investment turned out to be unaffected by the program. On the other\nhand, a positive coefficient would show that overall treated firms invested more than\nuntreated firms, plausibly thanks to the program, and that total crowding-out did not\n\noccur. However, it is still possible that firms partially substituted public for privately\nfinanced R&D outlays. In order to evaluate if partial crowding-out, or on the contrary,\neven crowding-in, occurred\u2014that is if public subsidies triggered privately financed\ninvestment\u2014we have to compare the change in total investment with the grants.\nBefore showing the econometric results let us present the scatterplot of the (averaged by score) outcome variables against the score (Figure 2). As expected, the\nfigure shows rather dispersed points, given that investment is usually greatly uneven\nacross firms. The interpolation lines appear almost flat, showing a weak dependence\nof the overall outcome on the score. As a matter of fact, no remarkable jumps of the\noutcome variables at the threshold emerge from the figures; however, if anything,\nthe impact seems somewhat positive.\nThis perception is confirmed by the econometric estimates of the coefficient \u03b2\nfor total, tangible, and intangible investment shown in Table 3. Akaike Information\nCriterion (AIC) suggests a preference for more parsimonious models, namely simple\nmean differences, rather than a higher order of polynomials in all cases but one. The\nsign of the coefficient is almost always positive. Using the full sample as a benchmark, the jump turns out to be equal to about one-third of the mean of the outcome\nvariable of the untreated firms. Due to the sample variance, however, the discontinuity\nis almost never statistically significant (the coefficient is weakly significant in just 4\nout of 30 models). Local estimates generate similar results to those of the full sample.\nIt is possible that we were unable to detect any effect because, for example, firms\nhad used the grants for hiring researchers or for consulting contracts. To check for\nthis eventuality we test for discontinuity of labor and service costs, using these as\nadditional outcome variables. Furthermore, we change the scale variable for investment using capital and total assets (calculated in the pre-program year) to check the\nsensitiveness of our previous findings on investment. Both are taken from firms\u2019\nbalance sheets. Capital is defined as the sum of tangible and intangible assets (fixed\nassets). Total assets are the sum of fixed, current, and other assets. The results of\nthese exercises are reported in Table 4.\nLabor costs almost always have a negative sign, but only rarely is the coefficient\nstatistically significant. With regard to service costs, the discontinuity is never significant and the sign is not stable across the model\u2019s specifications. The previous\nresults do not even appear affected by the variable used to scale investment, although\nin some models the coefficient now turns out to be statistically significant. Finally,\nwe estimated the effect of the incentives on the (log of) employment and wages for\na subsample of firms that reported information on employment (263 out of 357).19\nThe former aims to ascertain the effect of the policy on firms\u2019 employment; the latter to verify whether the benefits of the program went mainly to employees through\nhigher wages, as shown for the United States by Goolsbee (1998). Table B2 in\nthe online Appendix displays the results (in the local regressions we use only the\nwide-window because of the narrower sample size). Overall it seems that neither\nthe level of employment nor that of wages changed thanks to the program: the coefficients are almost never statistically significant.\n\noccur. However, it is still possible that firms partially substituted public for privately\nfinanced R&D outlays. In order to evaluate if partial crowding-out, or on the contrary,\neven crowding-in, occurred\u2014that is if public subsidies triggered privately financed\ninvestment\u2014we have to compare the change in total investment with the grants.\nBefore showing the econometric results let us present the scatterplot of the (averaged by score) outcome variables against the score (Figure 2). As expected, the\nfigure shows rather dispersed points, given that investment is usually greatly uneven\nacross firms. The interpolation lines appear almost flat, showing a weak dependence\nof the overall outcome on the score. As a matter of fact, no remarkable jumps of the\noutcome variables at the threshold emerge from the figures; however, if anything,\nthe impact seems somewhat positive.\nThis perception is confirmed by the econometric estimates of the coefficient \u03b2\nfor total, tangible, and intangible investment shown in Table 3. Akaike Information\nCriterion (AIC) suggests a preference for more parsimonious models, namely simple\nmean differences, rather than a higher order of polynomials in all cases but one. The\nsign of the coefficient is almost always positive. Using the full sample as a benchmark, the jump turns out to be equal to about one-third of the mean of the outcome\nvariable of the untreated firms. Due to the sample variance, however, the discontinuity\nis almost never statistically significant (the coefficient is weakly significant in just 4\nout of 30 models). Local estimates generate similar results to those of the full sample.\nIt is possible that we were unable to detect any effect because, for example, firms\nhad used the grants for hiring researchers or for consulting contracts. To check for\nthis eventuality we test for discontinuity of labor and service costs, using these as\nadditional outcome variables. Furthermore, we change the scale variable for investment using capital and total assets (calculated in the pre-program year) to check the\nsensitiveness of our previous findings on investment. Both are taken from firms\u2019\nbalance sheets. Capital is defined as the sum of tangible and intangible assets (fixed\nassets). Total assets are the sum of fixed, current, and other assets. The results of\nthese exercises are reported in Table 4.\nLabor costs almost always have a negative sign, but only rarely is the coefficient\nstatistically significant. With regard to service costs, the discontinuity is never significant and the sign is not stable across the model\u2019s specifications. The previous\nresults do not even appear affected by the variable used to scale investment, although\nin some models the coefficient now turns out to be statistically significant. Finally,\nwe estimated the effect of the incentives on the (log of) employment and wages for\na subsample of firms that reported information on employment (263 out of 357).19\nThe former aims to ascertain the effect of the policy on firms\u2019 employment; the latter to verify whether the benefits of the program went mainly to employees through\nhigher wages, as shown for the United States by Goolsbee (1998). Table B2 in\nthe online Appendix displays the results (in the local regressions we use only the\nwide-window because of the narrower sample size). Overall it seems that neither\nthe level of employment nor that of wages changed thanks to the program: the coefficients are almost never statistically significant.\n\n\n```python\nSC_pol0 = ols(\"SCSALES ~ T \", data = df_narr_wind).fit(cov_type='cluster', cov_kwds={'groups': df_narr_wind[\"score\"]}).summary()\n```\n\n\n```python\nSC_pol0\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>         <td>SCSALES</td>     <th>  R-squared:         </th> <td>   0.001</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.008</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td> 0.05725</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.815</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:31</td>     <th>  Log-Likelihood:    </th> <td> -97.448</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   115</td>      <th>  AIC:               </th> <td>   198.9</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   113</td>      <th>  BIC:               </th> <td>   204.4</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>       <td>cluster</td>     <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>z</th>      <th>P>|z|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    1.0086</td> <td>    0.057</td> <td>   17.580</td> <td> 0.000</td> <td>    0.896</td> <td>    1.121</td>\n</tr>\n<tr>\n  <th>T</th>         <td>   -0.0254</td> <td>    0.106</td> <td>   -0.239</td> <td> 0.811</td> <td>   -0.233</td> <td>    0.182</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>105.205</td> <th>  Durbin-Watson:     </th> <td>   2.056</td> \n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>1164.822</td> \n</tr>\n<tr>\n  <th>Skew:</th>          <td> 3.104</td>  <th>  Prob(JB):          </th> <td>1.15e-253</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>17.302</td>  <th>  Cond. No.          </th> <td>    2.61</td> \n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors are robust to cluster correlation (cluster)\n\n\n\n\n```python\nols_pol0 = ols(\"INVSALES ~ T\", data= df).fit(cov_type='cluster', cov_kwds={'groups': df[\"score\"]}).summary()\n```\n\n\n```python\nols_pol0 \n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVSALES</td>     <th>  R-squared:         </th> <td>   0.003</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.000</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>  0.8927</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.349</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:31</td>     <th>  Log-Likelihood:    </th> <td>  301.50</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>  -599.0</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   355</td>      <th>  BIC:               </th> <td>  -591.2</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>       <td>cluster</td>     <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>z</th>      <th>P>|z|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0333</td> <td>    0.011</td> <td>    3.111</td> <td> 0.002</td> <td>    0.012</td> <td>    0.054</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0122</td> <td>    0.013</td> <td>    0.945</td> <td> 0.345</td> <td>   -0.013</td> <td>    0.038</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>63.908</td> <th>  Durbin-Watson:     </th> <td>   1.825</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 103.114</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.064</td> <th>  Prob(JB):          </th> <td>4.07e-23</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 4.550</td> <th>  Cond. No.          </th> <td>    3.49</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors are robust to cluster correlation (cluster)\n\n\n\n\n```python\nols_pol0 = ols(\"INVSALES ~ T \", data= df).fit(cov_type='cluster', cov_kwds={'groups': df[\"score\"]}).summary()\n```\n\n\n```python\nww_pol222 = ols(\"INVINTSALES ~ T +  +streat + snotreat + s2treat + s2notreat\", data = df_wide_wind).fit(cov_type='cluster', cov_kwds={'groups': df_wide_wind[\"score\"]}).summary()\n\n```\n\n\n```python\nww_pol222\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>       <td>INVINTSALES</td>   <th>  R-squared:         </th> <td>   0.045</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.016</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   3.776</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td>0.0115</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>21:34:31</td>     <th>  Log-Likelihood:    </th> <td>  237.36</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   171</td>      <th>  AIC:               </th> <td>  -462.7</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   165</td>      <th>  BIC:               </th> <td>  -443.9</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     5</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>       <td>cluster</td>     <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>z</th>      <th>P>|z|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>   -0.0304</td> <td>    0.017</td> <td>   -1.808</td> <td> 0.071</td> <td>   -0.063</td> <td>    0.003</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0735</td> <td>    0.024</td> <td>    3.035</td> <td> 0.002</td> <td>    0.026</td> <td>    0.121</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0250</td> <td>    0.012</td> <td>   -2.046</td> <td> 0.041</td> <td>   -0.049</td> <td>   -0.001</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>   -0.0101</td> <td>    0.005</td> <td>   -1.973</td> <td> 0.049</td> <td>   -0.020</td> <td>-6.49e-05</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>    0.0044</td> <td>    0.002</td> <td>    1.901</td> <td> 0.057</td> <td>   -0.000</td> <td>    0.009</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>   -0.0004</td> <td>    0.000</td> <td>   -1.837</td> <td> 0.066</td> <td>   -0.001</td> <td> 2.78e-05</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>81.323</td> <th>  Durbin-Watson:     </th> <td>   1.624</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 442.428</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.695</td> <th>  Prob(JB):          </th> <td>8.47e-97</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>10.114</td> <th>  Cond. No.          </th> <td>    692.</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors are robust to cluster correlation (cluster)\n\n\n\n\n```python\n\n```\n\n\n\n\n    Firm\n    0      1.0\n    1      0.0\n    2      1.0\n    3      1.0\n    4      0.0\n          ... \n    352    1.0\n    353    1.0\n    354    1.0\n    355    1.0\n    356    1.0\n    Name: LF, Length: 357, dtype: float64\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\nISF_pol0\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVSALES</td>     <th>  R-squared:         </th> <td>   0.003</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.000</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>  0.8927</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.349</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>22:09:16</td>     <th>  Log-Likelihood:    </th> <td>  301.50</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   357</td>      <th>  AIC:               </th> <td>  -599.0</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   355</td>      <th>  BIC:               </th> <td>  -591.2</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>       <td>cluster</td>     <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>z</th>      <th>P>|z|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0333</td> <td>    0.011</td> <td>    3.111</td> <td> 0.002</td> <td>    0.012</td> <td>    0.054</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0122</td> <td>    0.013</td> <td>    0.945</td> <td> 0.345</td> <td>   -0.013</td> <td>    0.038</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>63.908</td> <th>  Durbin-Watson:     </th> <td>   1.825</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td> 103.114</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.064</td> <th>  Prob(JB):          </th> <td>4.07e-23</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 4.550</td> <th>  Cond. No.          </th> <td>    3.49</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors are robust to cluster correlation (cluster)\n\n\n\n\n```python\n\n```\n\n\n```python\n\ndf_large = df.loc[df[\"SIZE\"]==\"large\", :]\n#df_large\n\ndf_small = df.loc[ df[\"SIZE\"] == \"small\" , : ]\n#df_small[\"s\"]\n```\n\n\n```python\n\n```\n\n\n```python\nISS_pol0 = ols(\"INVSALES ~ T\", data = df_small).fit(cov_type='cluster', cov_kwds={'groups': df_small[\"score\"]}).summary()\nISS_pol1 = ols(\"INVSALES ~ T + streat + snotreat \", data =  df_small).fit(cov_type='cluster', cov_kwds={'groups': df_small[\"score\"]}).summary()\nISS_pol2 = ols(\"INVSALES ~ T +  +streat + snotreat + s2treat + s2notreat\", data =  df_small).fit(cov_type='cluster', cov_kwds={'groups': df_small[\"score\"]}).summary()\nISS_pol3 = ols(\"INVSALES ~ T +  +streat + snotreat + s2treat + s2notreat + s3treat + s3notreat\", data =  df_small).fit(cov_type='cluster', cov_kwds={'groups': df_small[\"score\"]}).summary()\n\n\nISL_pol0 = ols(\"INVSALES ~ T\", data = df_large).fit(cov_type='cluster', cov_kwds={'groups': df_large[\"score\"]}).summary()\nISL_pol1 = ols(\"INVSALES ~ T + streat + snotreat \", data =  df_large).fit(cov_type='cluster', cov_kwds={'groups': df_large[\"score\"]}).summary()\nISL_pol2 = ols(\"INVSALES ~ T +  +streat + snotreat + s2treat + s2notreat\", data =  df_large).fit(cov_type='cluster', cov_kwds={'groups': df_large[\"score\"]}).summary()\nISL_pol3 = ols(\"INVSALES ~ T +  +streat + snotreat + s2treat + s2notreat + s3treat + s3notreat\", data =  df_large).fit(cov_type='cluster', cov_kwds={'groups': df_large[\"score\"]}).summary()\n```\n\n\n```python\n#ISS_pol0\n#ISS_pol1\n#ISS_pol2\n#ISS_pol3\n```\n\n\n```python\nISS_pol0\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVSALES</td>     <th>  R-squared:         </th> <td>   0.037</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.032</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   6.028</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td>0.0179</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>22:13:31</td>     <th>  Log-Likelihood:    </th> <td>  142.59</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   178</td>      <th>  AIC:               </th> <td>  -281.2</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   176</td>      <th>  BIC:               </th> <td>  -274.8</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>       <td>cluster</td>     <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>z</th>      <th>P>|z|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0229</td> <td>    0.014</td> <td>    1.612</td> <td> 0.107</td> <td>   -0.005</td> <td>    0.051</td>\n</tr>\n<tr>\n  <th>T</th>         <td>    0.0452</td> <td>    0.018</td> <td>    2.455</td> <td> 0.014</td> <td>    0.009</td> <td>    0.081</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>32.420</td> <th>  Durbin-Watson:     </th> <td>   1.845</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td>  45.239</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.058</td> <th>  Prob(JB):          </th> <td>1.50e-10</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 4.274</td> <th>  Cond. No.          </th> <td>    3.24</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors are robust to cluster correlation (cluster)\n\n\n\n\n```python\nISL_pol0\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVSALES</td>     <th>  R-squared:         </th> <td>   0.009</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.004</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.166</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.286</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>22:13:31</td>     <th>  Log-Likelihood:    </th> <td>  166.46</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   179</td>      <th>  AIC:               </th> <td>  -328.9</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   177</td>      <th>  BIC:               </th> <td>  -322.5</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     1</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>       <td>cluster</td>     <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>z</th>      <th>P>|z|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0473</td> <td>    0.018</td> <td>    2.561</td> <td> 0.010</td> <td>    0.011</td> <td>    0.084</td>\n</tr>\n<tr>\n  <th>T</th>         <td>   -0.0217</td> <td>    0.020</td> <td>   -1.080</td> <td> 0.280</td> <td>   -0.061</td> <td>    0.018</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>31.899</td> <th>  Durbin-Watson:     </th> <td>   2.344</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td>  49.023</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 0.962</td> <th>  Prob(JB):          </th> <td>2.26e-11</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 4.695</td> <th>  Cond. No.          </th> <td>    3.81</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors are robust to cluster correlation (cluster)\n\n\n\n\n```python\nISL_pol2\n```\n\n\n```python\nISL_pol3\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>        <td>INVSALES</td>     <th>  R-squared:         </th> <td>   0.034</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.005</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.780</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Tue, 23 Jun 2020</td> <th>  Prob (F-statistic):</th>  <td> 0.115</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>22:13:31</td>     <th>  Log-Likelihood:    </th> <td>  168.74</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   179</td>      <th>  AIC:               </th> <td>  -321.5</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   171</td>      <th>  BIC:               </th> <td>  -296.0</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     7</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>       <td>cluster</td>     <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>z</th>      <th>P>|z|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.0939</td> <td>    0.058</td> <td>    1.630</td> <td> 0.103</td> <td>   -0.019</td> <td>    0.207</td>\n</tr>\n<tr>\n  <th>T</th>         <td>   -0.0302</td> <td>    0.064</td> <td>   -0.476</td> <td> 0.634</td> <td>   -0.155</td> <td>    0.094</td>\n</tr>\n<tr>\n  <th>streat</th>    <td>   -0.0166</td> <td>    0.011</td> <td>   -1.521</td> <td> 0.128</td> <td>   -0.038</td> <td>    0.005</td>\n</tr>\n<tr>\n  <th>snotreat</th>  <td>    0.0140</td> <td>    0.016</td> <td>    0.864</td> <td> 0.387</td> <td>   -0.018</td> <td>    0.046</td>\n</tr>\n<tr>\n  <th>s2treat</th>   <td>    0.0018</td> <td>    0.001</td> <td>    1.449</td> <td> 0.147</td> <td>   -0.001</td> <td>    0.004</td>\n</tr>\n<tr>\n  <th>s2notreat</th> <td>    0.0009</td> <td>    0.001</td> <td>    1.000</td> <td> 0.317</td> <td>   -0.001</td> <td>    0.003</td>\n</tr>\n<tr>\n  <th>s3treat</th>   <td>-5.882e-05</td> <td> 4.03e-05</td> <td>   -1.460</td> <td> 0.144</td> <td>   -0.000</td> <td> 2.02e-05</td>\n</tr>\n<tr>\n  <th>s3notreat</th> <td> 1.318e-05</td> <td> 1.18e-05</td> <td>    1.118</td> <td> 0.264</td> <td>-9.93e-06</td> <td> 3.63e-05</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>30.795</td> <th>  Durbin-Watson:     </th> <td>   2.341</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td> <th>  Jarque-Bera (JB):  </th> <td>  48.637</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 0.915</td> <th>  Prob(JB):          </th> <td>2.75e-11</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 4.782</td> <th>  Cond. No.          </th> <td>1.14e+05</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors are robust to cluster correlation (cluster)<br/>[2] The condition number is large, 1.14e+05. This might indicate that there are<br/>strong multicollinearity or other numerical problems.\n\n\n\n\n```python\n# tangible investment/presales program by firm's size\nITS_pol0 = ols(\"INVTSALES ~ T\", data = df_small).fit(cov_type='cluster', cov_kwds={'groups': df_small[\"score\"]}).summary()\nITS_pol1 = ols(\"INVTSALES ~ T + streat + snotreat \", data =  df_small).fit(cov_type='cluster', cov_kwds={'groups': df_small[\"score\"]}).summary()\nITS_pol2 = ols(\"INVTSALES ~ T +  +streat + snotreat + s2treat + s2notreat\", data =  df_small).fit(cov_type='cluster', cov_kwds={'groups': df_small[\"score\"]}).summary()\nITS_pol3 = ols(\"INVTSALES ~ T +  +streat + snotreat + s2treat + s2notreat + s3treat + s3notreat\", data =  df_small).fit(cov_type='cluster', cov_kwds={'groups': df_small[\"score\"]}).summary()\n\n\nITL_pol0 = ols(\"INVTSALES ~ T\", data = df_large).fit(cov_type='cluster', cov_kwds={'groups': df_large[\"score\"]}).summary()\nITL_pol1 = ols(\"INVTSALES ~ T + streat + snotreat \", data =  df_large).fit(cov_type='cluster', cov_kwds={'groups': df_large[\"score\"]}).summary()\nITL_pol2 = ols(\"INVTSALES ~ T +  +streat + snotreat + s2treat + s2notreat\", data =  df_large).fit(cov_type='cluster', cov_kwds={'groups': df_large[\"score\"]}).summary()\nITL_pol3 = ols(\"INVTSALES ~ T +  +streat + snotreat + s2treat + s2notreat + s3treat + s3notreat\", data =  df_large).fit(cov_type='cluster', cov_kwds={'groups': df_large[\"score\"]}).summary()\n```\n\n\n```python\nITS_pol0\n```\n\n\n```python\nITS_pol1\n```\n\n\n```python\nITS_pol2\n```\n\n\n```python\nITS_pol3\n```\n\n\n```python\nITL_pol0\n```\n\n\n```python\nITL_pol1\n```\n\n\n```python\nITL_pol2\n```\n\n\n```python\nITL_pol3\n```\n\n\n```python\ndf_narr_small = df.loc[(66 <=df.score) & (df.score <= 78) & (df.SIZE == \"small\") , :]\ndf_narr_large = df.loc[(66 <=df[\"score\"]) & (df[\"score\"] <= 78) & (df[\"SIZE\"] == \"large\") , :]\n\ndf_wide_small = df.loc[(52 <=df.score) & (df.score <= 80) & (df.SIZE == \"small\") , :]\ndf_wide_large = df.loc[(52 <=df[\"score\"]) & (df[\"score\"] <= 80) & (df[\"SIZE\"] == \"large\") , :]\n\n```\n\n\n```python\n\n\n```\n\n\n```python\n# total investment/pre-sales program by firm's size\nITSW_pol0 = ols(\"INVSALES ~ T\", data = df_wide_small).fit(cov_type='cluster', cov_kwds={'groups': df_wide_small[\"score\"]}).summary()\nITSW_pol1 = ols(\"INVSALES ~ T + streat + snotreat \", data = df_wide_small).fit(cov_type='cluster', cov_kwds={'groups': df_wide_small[\"score\"]}).summary()\nITSW_pol2 = ols(\"INVSALES ~ T +  +streat + snotreat + s2treat + s2notreat\", data = df_wide_small).fit(cov_type='cluster', cov_kwds={'groups': df_wide_small[\"score\"]}).summary()\n\n\n\n```\n\n\n```python\nITSW_pol0 \n```\n\n\n```python\nITSW_pol1\n```\n\n\n```python\nITSW_pol2\n```\n\n\n```python\n\n```\n\n\n```python\nITLW_pol0 = ols(\"INVSALES ~ T\", data = df_wide_large).fit(cov_type='cluster', cov_kwds={'groups': df_wide_large[\"score\"]}).summary()\nITLW_pol1 = ols(\"INVSALES ~ T + streat + snotreat \", data =  df_wide_large).fit(cov_type='cluster', cov_kwds={'groups': df_wide_large[\"score\"]}).summary()\nITLW_pol2 = ols(\"INVSALES ~ T +  +streat + snotreat + s2treat + s2notreat\", data =  df_wide_large).fit(cov_type='cluster', cov_kwds={'groups': df_wide_large[\"score\"]}).summary()\n\n```\n\n\n```python\n\n```\n\n\n```python\nITLW_pol0\n```\n\n\n```python\nITLW_pol1\n```\n\n\n```python\nITLW_pol2\n```\n\n\n```python\n# tangible investment/presales program by firm's size\nITS_pol0 = ols(\"INVTSALES ~ T\", data = df_narr_small).fit(cov_type='cluster', cov_kwds={'groups': df_narr_small[\"score\"]}).summary()\nITS_pol1 = ols(\"INVTSALES ~ T + streat + snotreat \", data =  df_narr_small).fit(cov_type='cluster', cov_kwds={'groups': df_narr_small[\"score\"]}).summary()\nITS_pol2 = ols(\"INVTSALES ~ T +  +streat + snotreat + s2treat + s2notreat\", data =  df_narr_small).fit(cov_type='cluster', cov_kwds={'groups': df_narr_small[\"score\"]}).summary()\n\n\nITL_pol0 = ols(\"INVTSALES ~ T\", data = df_narr_large).fit(cov_type='cluster', cov_kwds={'groups': df_narr_large[\"score\"]}).summary()\nITL_pol1 = ols(\"INVTSALES ~ T + streat + snotreat \", data =  df_narr_large).fit(cov_type='cluster', cov_kwds={'groups': df_narr_large[\"score\"]}).summary()\nITL_pol2 = ols(\"INVTSALES ~ T +  +streat + snotreat + s2treat + s2notreat\", data =  df_narr_large).fit(cov_type='cluster', cov_kwds={'groups': df_narr_large[\"score\"]}).summary()\n\n```\n\n\n```python\nITS_pol0\n```\n\n\n```python\nITS_pol1\n```\n\n\n```python\nITS_pol2\n```\n\n\n```python\n#Intangible investment/pre-program sales in narrow window sample\nIINTS_pol0 = ols(\"INVINTSALES ~ T\", data = df_narr_small).fit(cov_type='cluster', cov_kwds={'groups': df_narr_small[\"score\"]}).summary()\nIINTS_pol1 = ols(\"INVINTSALES ~ T + streat + snotreat \", data =  df_narr_small).fit(cov_type='cluster', cov_kwds={'groups': df_narr_small[\"score\"]}).summary()\nIINTS_pol2 = ols(\"INVINTSALES ~ T +  +streat + snotreat + s2treat + s2notreat\", data =  df_narr_small).fit(cov_type='cluster', cov_kwds={'groups': df_narr_small[\"score\"]}).summary()\n\n\nIINTL_pol0 = ols(\"INVINTSALES ~ T\", data = df_narr_large).fit(cov_type='cluster', cov_kwds={'groups': df_narr_large[\"score\"]}).summary()\nIINTL_pol1 = ols(\"INVINTSALES ~ T + streat + snotreat \", data =  df_narr_large).fit(cov_type='cluster', cov_kwds={'groups': df_narr_large[\"score\"]}).summary()\nIINTL_pol2 = ols(\"INVINTSALES ~ T +streat + snotreat + s2treat + s2notreat\", data =  df_narr_large).fit(cov_type='cluster', cov_kwds={'groups': df_narr_large[\"score\"]}).summary()\n\n```\n\n\n```python\nITS_pol0\n```\n\n\n```python\nIINTS_pol1\n```\n\n\n```python\nIINTS_pol2\n```\n\n\n```python\nIINTL_pol0\n```\n\n\n```python\nIINTL_pol1\n```\n\n\n```python\nIINTL_pol2\n```\n\n\n```python\n# investment full sample\nIS_pol0 = ols(\"INV ~ T\", data = df_small).fit(cov_type='cluster', cov_kwds={'groups': df_small[\"score\"]}).summary()\nIS_pol1 = ols(\"INV ~ T + streat + snotreat \", data =  df_small).fit(cov_type='cluster', cov_kwds={'groups': df_small[\"score\"]}).summary()\nIS_pol2 = ols(\"INV ~ T +  +streat + snotreat + s2treat + s2notreat\", data =  df_small).fit(cov_type='cluster', cov_kwds={'groups': df_small[\"score\"]}).summary()\n\n\n# investment full sample\nISF_pol0 = ols(\"INV ~ T\", data = df_small).fit(cov_type='cluster', cov_kwds={'groups': df_small[\"score\"]}).summary()\nISF_pol1 = ols(\"INV ~ T + streat + snotreat \", data =  df_small).fit(cov_type='cluster', cov_kwds={'groups': df_small[\"score\"]}).summary()\nISF_pol2 = ols(\"INV ~ T +streat + snotreat + s2treat + s2notreat\", data =  df_small).fit(cov_type='cluster', cov_kwds={'groups': df_small[\"score\"]}).summary()\nISF_pol2 = ols(\"INV ~ T +streat + snotreat + s2treat + s2notreat + s3treat + s3notreat\", data =  df_small).fit(cov_type='cluster', cov_kwds={'groups': df_small[\"score\"]}).summary()\n\n# investment full sample\nILF_pol0 = ols(\"INV ~ T\", data = df_large).fit(cov_type='cluster', cov_kwds={'groups': df_large[\"score\"]}).summary()\nILF_pol1 = ols(\"INV ~ T + streat + snotreat \", data = df_large).fit(cov_type='cluster', cov_kwds={'groups': df_large[\"score\"]}).summary()\nILF_pol2 = ols(\"INV ~ T +streat + snotreat + s2treat + s2notreat\", data = df_large).fit(cov_type='cluster', cov_kwds={'groups': df_large[\"score\"]}).summary()\nISF_pol2 = ols(\"INV ~ T +streat + snotreat + s2treat + s2notreat + s3treat + s3notreat\", data =  df_small).fit(cov_type='cluster', cov_kwds={'groups': df_small[\"score\"]}).summary()\n\n#investment in narrow window sample\nIS_pol0 = ols(\"INV ~ T\", data = df_narr_small).fit(cov_type='cluster', cov_kwds={'groups': df_narr_small[\"score\"]}).summary()\nIS_pol1 = ols(\"INV ~ T + streat + snotreat \", data =  df_narr_small).fit(cov_type='cluster', cov_kwds={'groups': df_narr_small[\"score\"]}).summary()\nIS_pol2 = ols(\"INV ~ T +streat + snotreat + s2treat + s2notreat\", data =  df_narr_small).fit(cov_type='cluster', cov_kwds={'groups': df_narr_small[\"score\"]}).summary()\n\n#investment in wide window sample\nIL_pol0 = ols(\"INV ~ T\", data = df_narr_large).fit(cov_type='cluster', cov_kwds={'groups': df_narr_large[\"score\"]}).summary()\nIL_pol1 = ols(\"INV ~ T + streat + snotreat \", data =  df_narr_large).fit(cov_type='cluster', cov_kwds={'groups': df_narr_large[\"score\"]}).summary()\nIL_pol2 = ols(\"INV ~ T +streat + snotreat + s2treat + s2notreat\", data =  df_narr_large).fit(cov_type='cluster', cov_kwds={'groups': df_narr_large[\"score\"]}).summary()\n\n```\n\n\n```python\nIS_pol1\n```\n\n\n```python\ndf[\"sizem\"] = np.nan\ndf.loc[df[\"SIZE\"] == \"small\", \"sizem\"] = 1\ndf.loc[df[\"SIZE\"] == \"large\", \"sizem\"] = 0\n\ndf[\"SF\"] = df[\"sizem\"]\ndf[\"LF\"] = 1 - df[\"sizem\"]\n#df_small = df.loc[df[\"sizem\"] == 1 , : ]\n#df_small[\"SF\"] = df\n\n```\n\n\n```python\ndf[\"largem\"]  = np.nan\ndf[\"slarge\"]  = np.nan\ndf[\"s2large\"] = np.nan\ndf[\"s3large\"] = np.nan\n\ndf[\"largem\"]  = df[\"LF\"]\ndf[\"slarge\"]  = df[\"s\"] * df[\"largem\"]\ndf[\"s2large\"] = df[\"s\"].pow(2) * df[\"largem\"]\ndf[\"s3large\"] = df[\"s\"].pow(3) * df[\"largem\"]\n```\n\n\n```python\ndf[\"smallem\"]  = np.nan\ndf[\"ssmallem\"]  = np.nan\ndf[\"s2smallem\"] = np.nan\ndf[\"s3smallem\"] = np.nan\n\ndf[\"smallem\"]  = df[\"SF\"]\ndf[\"ssmallem\"]  = df[\"s\"] * df[\"smallem\"]\ndf[\"s2smallem\"] = df[\"s\"].pow(2) * df[\"smallem\"]\ndf[\"s3smallem\"] = df[\"s\"].pow(3) * df[\"smallem\"]\n```\n\n\n```python\n# total investment/pre-sales program by firm's size\nISF_pol0 = ols(\"INVSALES ~ T\", data = df).fit(cov_type='cluster', cov_kwds={'groups': df[\"score\"]}).summary()\nISF_pol1 = ols(\"INVSALES ~ T + ssmallem + slarge\", data = df).fit(cov_type='cluster', cov_kwds={'groups': df[\"score\"]}).summary()\nISF_pol2 = ols(\"INVSALES ~ T +ssmallem + slarge + s2smallem + s2large\", data = df).fit(cov_type='cluster', cov_kwds={'groups': df[\"score\"]}).summary()\nISF_pol2 = ols(\"INVSALES ~ T +ssmallem + slarge + s2smallem + s2large + s3smallem + s3large\", data = df).fit(cov_type='cluster', cov_kwds={'groups': df[\"score\"]}).summary()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "7d897fad6bc7c132a2448c784b674bb3bfb81c2d", "size": 515240, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "20.06.ipynb", "max_stars_repo_name": "solmazahmadi/microeconometrics-course-project-solmazahmadi", "max_stars_repo_head_hexsha": "6bb1c76a7b126275effe7572df7d266a5aa4ff4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "20.06.ipynb", "max_issues_repo_name": "solmazahmadi/microeconometrics-course-project-solmazahmadi", "max_issues_repo_head_hexsha": "6bb1c76a7b126275effe7572df7d266a5aa4ff4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "20.06.ipynb", "max_forks_repo_name": "solmazahmadi/microeconometrics-course-project-solmazahmadi", "max_forks_repo_head_hexsha": "6bb1c76a7b126275effe7572df7d266a5aa4ff4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.2036441586, "max_line_length": 1718, "alphanum_fraction": 0.3721896592, "converted": true, "num_tokens": 96865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864512179822543, "lm_q2_score": 0.13477592784882603, "lm_q1q2_score": 0.04698896978032279}}
{"text": "# Getting started with **RuNNer**\n## Constructing a HDNNP for Bulk Copper\n\nThis Jupyter Notebook is written for the RuNNer tutorial at the workshop \"WORKFLOWS FOR ATOMISTIC SIMULATION\" from 10-12 March, 2021 by **Marius Herbold** (marius.herbold@chemie.uni-goettingen.de, Georg-August-Universit\u00e4t G\u00f6ttingen, Institut f\u00fcr Physikalische Chemie, Theoretische Chemie).\n\nIt is written in text form for an easier understanding, if participants will get back later to this notebook. Anyhow, during the tutorial, we will\nnot explicitly go through the text.\n\nFor this tutorial it is intended to use the RuNNer release version 1.2.\nRuNNer is hosted at www.gitlab.com. The most recent version can only be found in this repository.\nFor access please contact Prof. J\u00f6rg Behler (joerg.behler@uni-goettingen.de).\n\n\n```python\n### Import python modules\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport ase\nfrom pyiron import Project\n\n### Import Marius Class and functions\nimport functions as fc\n\n### Varibales form RuNNer UC\nBohr2Ang = 0.5291772109030   # CODATA 2018\nAng2Bohr = 1/Bohr2Ang\nEh2eV    = 27.211386245988   # CODATA 2018\neV2Eh    = 1/Eh2eV\nf_conversion = eV2Eh/Ang2Bohr\n```\n\n# About RuNNer\n**RuNNer** is a stand-alone Fortran program for the construction of high-dimensional neural network potentials (HDNNP), written mainly by J\u00f6rg Behler. It relates the local environment of an atom to its atomic energy $E_\\mathrm{s}$, which contributes to the sum of all $N$ atomic energies, resulting in the total energy of the system $E_\\mathrm{s}$\n\n\\begin{equation}\n    E_\\mathrm{s} = \\sum_{a}^{N}E_\\mathrm{a}.\n\\end{equation}\n\nThe atomic energy is described by an atomic neural network (NN), which is element specific. This gives the oppurtunity to describe different numbers of atoms with the same NN, which would be not the case, if there is only one NN for the whole system. To feed information to the NN, the local environment up to a certain cutoff radius $R_\\mathrm{c}$ is described by so-called symmetry functions (SF) (more details are shown in a few moments) forming the SF vector $G$, which forms the input layer of the NN. In the next layers of the NN - the hidden layers - this information will be processed and in the final layer - the output layer - the atomic NN will provide the atomic energy $E_\\mathrm{a}$. In each layer, there are a certain number of nodes $y$ which are connected by the weights $a$ and can be biased by the biases $b$. For the NN training the wheights and biases are optimized to represent best the data in the training data set.\n\n\n\nIn general **RuNNer** can be separated into three different stages - so-called modes, in which different steps are performed.\n- mode 1: SF calculation, data set splitting in training and test set\n- mode 2: training of the NN to construct the NNP\n- mode 3: prediction of energy, forces, stress, charges\n\nAll these steps are performed consecutively beginning with mode 1. Needed input files are:\n* ``input.nn``: \n  - main control file needed in all modes\n  - contains all control parameters (NN architecture, symmetry functios, ...)\n* ``input.data``:\n  - needed in mode 1 and 3\n  - contains structural information (lattice vectors, atomic positions, forces, charges, total energy)\n  - output of electronic structure code must be converted to ``input.data`` format\n  - RuNNer repository provides the RuNNerUC (universial converter) to convert from several formats (FHI-aims, VASP, xyz, LAMMPS) to input.data format and vice-versa\n\n# Getting the First Data Set\n\nBefore we are gettinger deeper into **RuNNer**, we will go one step back. At the beginning of each NNP, there is your data set. For sure, the data set does not have to be good/perfect/large, because you can increase your data set step by step and train different generations of your NN, ending up with an accurate potential. For getting your first data set, there are several ways like:\n- small random displacements,\n- thermal displacements by a simple potential - like force fields - in MD,\n- experimental structures.\n\nThe question \"What is a good data set?\" is not that simple to answer and it strongly depends on the purpose of your potential. But one important point is for sure the distribution of your data over the configurational space you like to handle with your potential. If some configurations are missing, the NNP will provide inaccurate results, because you make the NNP predict energies and forces for an unknown configuration. In **RuNNer**, this is called an ``extrapolation``, that means the NNP is not trained to such a configuration.\n\nHere in the workshop, we are dealing with bulk-Cu. So, a first application of your NNP could be to predict the equilibrium lattice constant of bulk-Cu and you will calculate the energy of a bulk-Cu unit cell with different lattice constants to give an energy-volume curve, which provides the equilibrium lattice constant at its minimum. Thus, your data set should contain information of different cell volumes.\n\n\n```python\n# Read in workshop's data set in pandas data frame\ndata_pr = Project(\"../../datasets\")\nif len(data_pr.job_table()) == 0:\n    data_pr.unpack(\"Cu_training_archive\")\ndata_job = data_pr.load('df4_2_5eV_25A3_8K')\ndata = data_job.to_pandas()\nfig1 = fc.PlotData(data)\n```\n\nAs already mentioned, your data needs to be stored in the ``input.data`` file. This file is used for ``mode 1`` to generate all the needed files for the NN training in ``mode 2``. In this case the ``input.data`` stores all the information of the electronic structure code like the total energy and charge, the structure (lattice constants, atomic positions), atomic forces and may the atomic charges. If used in ``mode 3``, only the structural paramteres are necessary, since ``mode 3`` is the prediction mode and we may do not know the outcome of an electronic structure calculation.\n\nThe ``input.data`` follows a certain format with certain keywords. Each structure is embedded between the keywords ``begin`` and ``end``, to separate different structures from each other. For periodic structures the three lattice vectors are introduced by the keyword ``lattice``, for non-periodic structures this keyword is just missing. Information about the atoms is given line by line, thus each atom in one line, beginning with the ``atom`` keyword, followed by the Cartesian coordinates (x, y and z), the element, the atomic charge, an unused column and the atomic force components (fx, fy and fz). The ``energy`` keyword is followed by the total energy of the current structure, equivalent, the overall charge is marked by the ``charge`` keyword. Comments can also be added with the ``comment`` keyword. Important aspect: the data is given in special units. A length is given in ``bohr``, an energy in ``Hartree``, thus forces in ``Hartree/bohr`` and charges in the elementary charge ``e``. In general, periodic and non-periodic structures can be mixed, as well as different numbers of atoms per structure can be combined. Information can be given in a free format (number of digits), but it is recommended to use at least six digits and the order of the keywords is arbitrary in general.\nbegin\nlattice   2.34735543   -4.06574009    0.00000000\nlattice   2.34735543    4.06574009    0.00000000\nlattice   0.00000000    0.00000000   13.45504276\ncomment x             y             z         element atomic charge   unused      fx            fy               fz\natom    0.00000000    0.00000000    0.00000000   Cu    0.00000000   0.00000000   -0.00000000   -0.00000000    0.00000002\natom    2.34735543    1.35524733   10.09128112   Cu    0.00000000   0.00000000   -0.00000000    0.00000134   -0.00000002\natom    0.00000000    0.00000000    6.72752138   Cu    0.00000000   0.00000000    0.00000000    0.00000000   -0.00000004\natom    2.34735543   -1.35524733    3.36375974   Cu    0.00000000   0.00000000    0.00000000   -0.00000134    0.00000003\nenergy -0.4746414926841609\ncharge 0.0\nend\n# The RuNNer Workflow\n\nWe discussed the ``input.data`` and will have a look at the next steps. Here, the ``input.nn`` is explained. Keywords can be given in an arbitrary order, but grouping keywords by the modes is useful for the general structure. The units are the same as for the ``input.data``, see above. If a keyword is not specified, **RuNNer** uses default values, if possible. A summary in the output files give more detailed information in the specific case. Most keywords can only be specified ones, to avoid contradictions, otherwise an error will be printed. Also comments can be added to the file, which are indicated by a hash ``#``. In principle, it is possible to change the ``input.nn`` for every mode, however it is highly recommended not to do that. Anyway here, you will not have the opportunity to explicitly change the ``input.nn``, since **RuNNer** is called via the pyiron environment. At the moment, the implementation of **RuNNer** to pyiron is on a very early stage, thus no changes are possible for the input.\n\nIn the following we will discuss a subset, but the most important keywords. Beginning with some general keywords of the ``input.nn``. I think the first keywords are self-explanatory together with the given comments. The data set splitting in ``mode 1`` and the initial weights in ``mode 2`` rely on random numbers. For the reproducibility, a random number seed (keyword ``random_seed``) has to be defined, which will give the same results, if the run is repeated later. Together with this, the generator for the random numbers can also be defined (keyword ``random_number_type``). The second group of keywords describe the architecture of the NN and the activation functions of the nodes via the keywords ``global_...``. Usually, we use 2-3 hidden layers with 10-40 nodes each.\n### general keywords\nnn_type_short 1                           # 1=Behler-Parrinello energy is a sum of atomic energies\nrunner_mode 1                             # 1=calculate symmetry functions, 2=fitting mode, 3=predicition mode\nnumber_of_elements 1                      # number of elements\nelements Cu                               # specification of elements\nrandom_seed 20                            # integer seed for random number generator\nrandom_number_type 6                      # 6 recommended\n\n\n### NN structure of the short-range NN\nuse_short_nn                              # use NN for short range interactions\nglobal_hidden_layers_short 2              # number of hidden layers\nglobal_nodes_short 15 15                  # number of nodes in hidden layers\nglobal_activation_short t t l             # activation functions  (t = hyperbolic tangent, l = linear)\n# Pyiron RuNNer Fit\n\nHere, you will not have the opportunity to explicitly change the ``input.nn``, since **RuNNer** is called via the pyiron environment. At the moment, the implementation of **RuNNer** to pyiron is on a very early stage, thus no changes are possible for the input.\n\n\n```python\npr = Project(\"runner_fit\")\n```\n\n\n```python\ndata_pr.job_table()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>id</th>\n      <th>status</th>\n      <th>chemicalformula</th>\n      <th>job</th>\n      <th>subjob</th>\n      <th>projectpath</th>\n      <th>project</th>\n      <th>timestart</th>\n      <th>timestop</th>\n      <th>totalcputime</th>\n      <th>computer</th>\n      <th>hamilton</th>\n      <th>hamversion</th>\n      <th>parentid</th>\n      <th>masterid</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>finished</td>\n      <td>None</td>\n      <td>df1_A1_A2_A3_EV_elast_phon</td>\n      <td>/df1_A1_A2_A3_EV_elast_phon</td>\n      <td>/home/pyiron/</td>\n      <td>datasets/Cu_database/</td>\n      <td>2021-02-18 19:49:53.061360</td>\n      <td>None</td>\n      <td>None</td>\n      <td>zora@cmti001#1</td>\n      <td>TrainingContainer</td>\n      <td>0.4</td>\n      <td>None</td>\n      <td>None</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2</td>\n      <td>finished</td>\n      <td>None</td>\n      <td>df3_10k</td>\n      <td>/df3_10k</td>\n      <td>/home/pyiron/</td>\n      <td>datasets/Cu_database/</td>\n      <td>2021-02-18 19:49:55.496691</td>\n      <td>None</td>\n      <td>None</td>\n      <td>zora@cmti001#1</td>\n      <td>TrainingContainer</td>\n      <td>0.4</td>\n      <td>None</td>\n      <td>None</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>3</td>\n      <td>finished</td>\n      <td>None</td>\n      <td>df2_1k</td>\n      <td>/df2_1k</td>\n      <td>/home/pyiron/</td>\n      <td>datasets/Cu_database/</td>\n      <td>2021-02-18 19:49:56.101883</td>\n      <td>None</td>\n      <td>None</td>\n      <td>zora@cmti001#1</td>\n      <td>TrainingContainer</td>\n      <td>0.4</td>\n      <td>None</td>\n      <td>None</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>4</td>\n      <td>finished</td>\n      <td>None</td>\n      <td>df4_2_5eV_25A3_8K</td>\n      <td>/df4_2_5eV_25A3_8K</td>\n      <td>/home/pyiron/</td>\n      <td>datasets/Cu_database/</td>\n      <td>2021-02-18 19:49:57.547918</td>\n      <td>None</td>\n      <td>None</td>\n      <td>zora@cmti001#1</td>\n      <td>TrainingContainer</td>\n      <td>0.4</td>\n      <td>None</td>\n      <td>None</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nj = pr.create.job.RunnerFit('fit', delete_existing_job=False)\n```\n\n\n```python\n# Be aware of fitting a larger data set, since it will run some time, roughly six hours!\nj.add_job_to_fitting(data_pr.load('df1_A1_A2_A3_EV_elast_phon'))\n```\n\n\n```python\nj.run()\n```\n\n    The job fit was saved and received the ID: 68\n\n\n\n```python\nj.lammps_potential\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Name</th>\n      <th>Filename</th>\n      <th>Model</th>\n      <th>Species</th>\n      <th>Config</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>RuNNer-Cu</td>\n      <td>[/home/pyiron/day_2/02-runner/runner_fit/fit_hdf5/fit/input.nn, /home/pyiron/day_2/02-runner/runner_fit/fit_hdf5/fit/weights.029.data, /home/pyiron/day_2/02-runner/runner_fit/fit_hdf5/fit/scaling....</td>\n      <td>RuNNer</td>\n      <td>[Cu]</td>\n      <td>[pair_style nnp dir \"./\" showew no showewsum 0 resetew no maxew 100 cflength 1.8897261328 cfenergy 0.0367493254 emap \"1:Cu\"\\n, pair_coeff * * 12\\n]</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThe data set, you will fit is a strongly reduced subset of the data shown above. For comparison, the same plot is shown here.\n\n**Be aware of fitting a larger data set, since it will run some time, roughly six hours!**\n\n\n```python\ndf1_job = data_pr.load('df1_A1_A2_A3_EV_elast_phon')\ndf1 = df1_job.to_pandas()\nfig1 = fc.PlotData(df1)\n```\n\n## RuNNer Mode 1\n\nIn **RuNNer**'s mode 1 the following steps are performed:\n- calculation of SF values,\n- splitting of data set in train and test data set.\n\nThe amount of test structures is defined by the keyword ``test_fraction``. Here, ``test_fraction 0.10`` means 10% of the data set will be used for testing and is not part of the training data. ``use_short_forces`` keyword states to use also the atomic forces for the fitting process in ``mode 2``, but it is recommended to use it also in ``mode 1`` to create the necessary force files.\n### symmetry function generation ( mode 1):\ntest_fraction 0.10000                     # threshold for splitting between fitting and test set\nuse_short_forces                          # use forces and prepare the files in mode 1 for fitting in mode 2\nIn the next group of keywords, the SFs are defined. There are two different types of SFs: the radial SFs ``symfunction_short XX type XX ...`` to describe the atomic distances and angular SFs ``symfunction_short XX type XX XX ...`` to describe the spatial distribution of the neighboring atoms. ``cutoff_type`` keyword describes the cutoff function type. All mentioned SF types are shown in the next section.\n### symmetry function definitions (all modes):\ncutoff_type 1\nsymfunction_short Cu  2 Cu     0.000000      0.000000     12.000000\nsymfunction_short Cu  2 Cu     0.006000      0.000000     12.000000\nsymfunction_short Cu  2 Cu     0.016000      0.000000     12.000000\nsymfunction_short Cu  2 Cu     0.040000      0.000000     12.000000\nsymfunction_short Cu  2 Cu     0.109000      0.000000     12.000000\n\nsymfunction_short Cu  3 Cu Cu     0.00000       1.000000      1.000000     12.000000\nsymfunction_short Cu  3 Cu Cu     0.00000       1.000000      2.000000     12.000000\nsymfunction_short Cu  3 Cu Cu     0.00000       1.000000      4.000000     12.000000\nsymfunction_short Cu  3 Cu Cu     0.00000       1.000000     16.000000     12.000000\nsymfunction_short Cu  3 Cu Cu     0.00000      -1.000000      1.000000     12.000000\nsymfunction_short Cu  3 Cu Cu     0.00000      -1.000000      2.000000     12.000000\nsymfunction_short Cu  3 Cu Cu     0.00000      -1.000000      4.000000     12.000000\nsymfunction_short Cu  3 Cu Cu     0.00000      -1.000000     16.000000     12.000000\n### Definition of the Symmetry Functions (SFs)\n\nDifferent types of SFs for the radial and angular SFs are implemented in **RuNNer**, but only the most common types are shown here. SFs provide the input for the NN and describe the local atomic environment of each atom and are rotationally and translationally invariant. So, SFs describe the relative positions of the atoms to each other. In contrast, Cartesian coordinates describe the absolute positions to each other and change with a translation or a rotation. That means the numerical input will change with translation or rotation, but not the energy of the system. However, different numerical inputs belonging to the same energy leads to problems in fitting.\n\n### The Cutoff Function\n\nAnother kind of symmetry function is the cutoff function, which is included in the radial and angular SFs. The cutoff radius $R_\\mathrm{c}$ (usually $12\\,\\mathrm{bohr}$) defines how much of the local atomic environment is considered. All SFs will decrease to zero, if the atomic distance is larger than $R_\\mathrm{c}$. A decrease to exact zero is necessary for numerical reasons. There are several cutoff funtions defined in **RuNNer** and we will use here\n\n\\begin{equation}\n    f_{c}(R_{ij}) = \n    \\begin{cases}\n    1& ~ \\text{for $R_{ij} \\leq R_{inner,c}$}\\\\\n    0.5 * [cos(\\pi x) + 1]& ~ \\text{for $R_{inner,c} \\leq R_{ij} \\leq R_\\mathrm{c}$},\\\\\n    0& ~ \\text{for $R_\\mathrm{c} < R_{ij}$}\n    \\end{cases}\n\\end{equation}\n\nwith the atomic distance $R_{ij}$, the cutoff radius $R_\\mathrm{c}$, the inner cutoff $R_{inner,c}$ (here $=0$) and $x = \\frac{R_{ij} - R_{inner,c}}{R_\\mathrm{c} - R_{inner,c}}$.\n\n\n```python\ndistances = np.arange(0,15.1,0.1)\ncfct = np.array([fc.cutofffct(i) for i in distances])\nplt.plot(distances, cfct);\n```\n\n### The Radial Symmetry Functions\n\nTo define the parameters for the radial SFs, it is important to know which are the shortest bonds in your data set. Usually, 5-6 radial SF are used for each element pair, with different $\\eta$ values to increase the resolution for structure description. It is possible to shift the maximum of the radial SF $G^2$ by $R_{s}$\n\n\\begin{equation}\n    G_{i}^{2} = \\sum_{j}^{}e^{\\eta (R_{ij} - R_{s})^2} \\cdot f_{c}(R_{ij}).\n\\end{equation}\n\nBelow, the defintion of a radial SF in ``input.nn``, again ``symfunction_short`` calls to define a SF, ``Cu`` defines the specific element, ``2`` the SF type, the second ``Cu`` defines the neighboring atom, and the last three parameters define $\\eta$, $R_{s}$ and $R_\\mathrm{c}$. The gaussian exponent $\\eta$ for the radial SF are chosen to equally distribute the radial SF turning points, whereas the turning point of radial SF with $\\eta = 0$ is set to the specific minimum bond in your data set. There is no need to define element specific SF, also global SF are possible, which are used for every element combination. It is also possible to define for each SF a different $R_\\mathrm{c}$, but it is recommended to use only one $R_\\mathrm{c}$ for all SFs.   \nsymfunction_short Cu  2 Cu     0.000000      0.000000     12.000000\nHere, different radial parts of radial SFs with different $\\eta$ are plotted. Feel free and play around with the parameters.\n\n\n```python\nrsf1 = np.array([fc.radialSF(i, 0.1) for i in distances])\nrsf2 = np.array([fc.radialSF(i, 0.05) for i in distances])\nrsf3 = np.array([fc.radialSF(i, 0.025) for i in distances])\nplt.plot(distances, rsf1[:,1], label='');\nplt.plot(distances, rsf2[:,1], label='');\nplt.plot(distances, rsf3[:,1], label='');\n```\n\n### The Angular Symmetry Functions\n\nFor the angular SF it is quite similar as for the radial SF. But here, three atomic positions are included.\n\n\\begin{equation}\n    G_{i}^{3} = 2^{\\zeta - 1}\\sum_{j}^{} \\sum_{k}^{} \\left[( 1 + \\lambda \\cdot cos \\theta_{ijk})^{\\zeta} \\cdot e^{\\eta (R_{ij}^2 + R_{ik}^2 + R_{jk}^2)} \\cdot f_{c}(R_{ij}) \\cdot f_{c}(R_{ik}) \\cdot f_{c}(R_{jk}) \\right],\n\\end{equation}\n\nthe angle $\\theta_{ijk} = \\frac{\\mathbf{R}_{ij} \\cdot \\mathbf{R}_{ik}}{R_{ij} \\cdot R_{ik}}$ is centered at atom $i$ and the atomic distance vector is defined as $\\mathbf{R}_{ij} = \\mathbf{R}_{i} - \\mathbf{R}_{j}$. Mostly used for the angular exponent $\\zeta = 1, 2, 4 ,16$, gaussian exponent $\\eta = 0$ and for $\\lambda$ only $+1$ or $-1$ is possible. If many atoms of each element are present, angular SFs are usually not critical and a default set of SFs can be used.\n\nHere a definition of an angular SF is given, which is similar to the definition of a radial SF. ``3`` defines the used type of SF, which needs the following parameters: ``Cu Cu`` to describe the neighboring atoms included in the angle, followed by $\\eta$, $\\lambda$, $\\zeta$ and $R_\\mathrm{c}$.\nsymfunction_short Cu  3 Cu Cu     0.00000       1.000000      1.000000     12.000000\nBelow, you find different angular parts for angular SF with different $\\zeta$ and $\\lambda$ values. Fell free and play around.\n\n\n```python\nangles = range(0,361)\nasf1 = np.array([fc.angularSF(i,1,1,1,0.0,1.0,1.0) for i in angles])\nasf2 = np.array([fc.angularSF(i,1,1,1,0.0,1.0,2.0) for i in angles])\nasf3 = np.array([fc.angularSF(i,1,1,1,0.0,1.0,4.0) for i in angles])\nasf4 = np.array([fc.angularSF(i,1,1,1,0.0,-1.0,1.0) for i in angles])\nasf5 = np.array([fc.angularSF(i,1,1,1,0.0,-1.0,2.0) for i in angles])\nasf6 = np.array([fc.angularSF(i,1,1,1,0.0,-1.0,4.0) for i in angles])\nplt.plot(angles, asf1[:,1]);\nplt.plot(angles, asf2[:,1]);\nplt.plot(angles, asf3[:,1]);\nplt.plot(angles, asf4[:,1]);\nplt.plot(angles, asf5[:,1]);\nplt.plot(angles, asf6[:,1]);\n```\n\n### Output Mode 1\n\nAs said, the data set splitting and the calculation of the symmetry function values takes place here. Among general information of your data set and your SFs, you find explicitly how the data set is splitted. As shown in the example below, it is written what happens to each structure (called ``Point``) and if it goes to the training or test set and which number it has there. ``mode 1`` will prepare the necessary files for ``mode 2``:\n* training data\n - function.data: SF values for each atom in each structure\n - trainstruct.data: structural information\n - trainforces.data: force information (if force fitting is used)\n \n\n* test data\n - testing.data: SF values for each atom in each structure\n - teststruct.data: structural information\n - testforces.data: force information (if force fitting is used)\n -------------------------------------------------------------\n Maximum number of atoms:          128\n -------------------------------------------------------------\n Calculating Symmetry Functions\n for         8073  structures\n -------------------------------------------------------------\n           1  Point is used for training            1\n           2  Point is used for training            2\n           3  Point is used for training            3\n           4  Point is used for testing            1\n           5  Point is used for training            4\n           6  Point is used for training            5\n**RuNNer** ends without any problems, if at the end of the ouput file the following lines are written:\n Normal termination of RuNNer\n -------------------------------------------------------------\n### Short quick example of SF calculation\n\nTo clarify how the SFs represent the atomic environment for an atom. Let's have a look at this simple structure with three Cu atoms below:\nbegin\natom    0.00000000    0.00000000    0.00000000   Cu    0.00000000   0.00000000   -0.00000000   -0.00000000    0.00000002\natom    0.00000000    0.00000000    6.72752138   Cu    0.00000000   0.00000000    0.00000000    0.00000000   -0.00000004\natom    2.34735543   -1.35524733    3.36375974   Cu    0.00000000   0.00000000    0.00000000   -0.00000134    0.00000003\nenergy -0.4746414926841609\ncharge 0.0\nend\nHere we define the atomic positions as vectors, calculate  the distances and angles for the SFs. Finally, we will end up with the SFs vector for the first Cu atom. We use the 13 SFs, which were introduced in the section above \"RuNNer Mode 1\".\n\n\n```python\n# Define atomic positions as vectors\nd1 = np.array([0.0, 0.0, 0.0])\nd2 = np.array([0.0, 0.0, 6.72752138])\nd3 = np.array([2.34735543, 1.35524733, 3.36375974])\n\n# Define distance vectors\nd12 = d1 - d2\nd13 = d1 - d3\nd23 = d2 - d3\n\n# Define angles\na123 = np.dot(d12, d13) / (np.linalg.norm(d12) * np.linalg.norm(d13))\na213 = np.dot(d12, d23) / (np.linalg.norm(d12) * np.linalg.norm(d23))\na312 = np.dot(d13, d23) / (np.linalg.norm(d13) * np.linalg.norm(d23))\n\n# Calculate radial symmetry function values\nfor eta in [0.000, 0.006, 0.016, 0.040, 0.109]:\n    value_sf = 0\n    for d in [d12, d13]:\n        d = np.linalg.norm(d)\n        value_sf += fc.radialSF(d, eta)[0]\n    print(value_sf)\n\n# Calculate angular symmetry function values\nfor Lambda in [1, -1]:\n    for zeta in [1, 2, 4, 16]:\n        for a in [a123]:\n            value_sf = fc.angularSF(a, np.linalg.norm(d12), np.linalg.norm(d13), np.linalg.norm(d23), 0.0, Lambda, zeta)[0]\n        print(value_sf)\n        \n```\n\n    1.1182423115740479\n    0.9463318326255568\n    0.7253600030997174\n    0.40425285668735783\n    0.09616369636385737\n    0.411992195819298\n    0.4119731729121053\n    0.41193512973271224\n    0.41170694441910877\n    1.9023785577599554e-05\n    8.78384860610243e-10\n    1.872667361071411e-18\n    1.7583909381106493e-70\n\n\n## RuNNer Mode 2\n\nIn ``mode 2``, the magic happens and your data will be fitted. The part below of the ``input.nn`` defines how the fitting in ``mode 2`` has to take place. ``epochs`` define how often **RuNNer** will loop over the training data to optimize the weights and biases of the NN, ``fitting_unit`` defines in which unit the output will be presented in ``mode 2``, all other files and units will stay in ``bohr`` and ``Hartree``. ``precondition_weights`` effects the initial weights and biases of the NN. In the second part, there are some parameters for the Kalman-Filter, ``repeated_energy_update`` repeats the energy update after a force component update, to increase the impact of the energies. This is slower in general, but might be necessary, since there a many more force components than energies. ``mix_all_points`` mixes the order of the training points for each epoch to improve the training. Often, the ranges of the symmetry functions are rather different in their order of magnitude and thus a rescaling of SFs can be advantageous numerically stated by ``scale_symmetry_functions`` keyword. Together with that, a centering of the SF average value to zero is performed for numerical reasons, since zero is the non-linear center of most activations  functions. ``short_force_fraction`` defines how much of the force components is randomly used for training the NN. The last part, defines to write certain files for each epoch, to analyze it in a later stage. There are many other keywords and options to present. However, you got an idea how **RuNNer** works and what to do to fit your first NNP. In the next part, first steps for analyzing the fit are presented.\n### fitting (mode 2):general inputs for short range AND electrostatic part:\n\nepochs 10                                 # number of epochs\nfitting_unit eV                           # unit for error output in mode 2 (eV or Ha)\nprecondition_weights                      # optional precondition initial weights\n\n\n### fitting options ( mode 2): short range part only:\n\nshort_energy_error_threshold 0.10000      # threshold of adaptive Kalman filter short E\nshort_force_error_threshold 1.00000       # threshold of adaptive Kalman filter short F\nkalman_lambda_short 0.98000               # Kalman parameter short E/F, do not change\nkalman_nue_short 0.99870                  # Kalman parameter short E/F, do not change\nuse_short_forces                          # use forces for fitting\nrepeated_energy_update                    # optional: repeat energy update for each force update\nmix_all_points                            # do not change\nscale_symmetry_functions                  # optional\ncenter_symmetry_functions                 # optional\nshort_force_fraction 0.01                 #\n\n\n### output options for mode 2 (fitting):\nwrite_trainpoints                         # write trainpoints.out and testpoints.out files\nwrite_trainforces\nDuring the fitting process of the NN, the error function $\\Gamma$ is minimized, which is defined as \n\\begin{equation}\n    \\Gamma = \\frac{1}{N_\\mathrm{struct}} \\sum_{i}^{N_\\mathrm{struct}} (E_{NN}^{i} - E_{Ref}^{i})^2 = RMSE(E),\n\\end{equation}\nif only energy fitting is used, which defines simultaneously the root-mean squared error of the energies $RMSE(E)$. This defines the differences of the reference data and the NNP predictions. During the epochs, the error decreases as you can see in the part of ``mode2`` output.\n -------------------------------------------------------------------------------\n RMSEs (energies: eV/atom, forces: eV/Bohr):\n                      --- E_short: ---    - time -\n                          /atom              min\n        epoch         train         test\n ENERGY     0      0.486020     0.481254    9.86\n FORCES     0      0.543702     0.502894\n -------------------------------------------------------------------------------\n ENERGY     1      0.039459     0.039840   19.05\n FORCES     1      0.201312     0.174885\n INFORMATION USED FOR UPDATE (E,F)     1      1998        45\n -------------------------------------------------------------------------------\n ENERGY     2      0.024635     0.026306   19.14\n FORCES     2      0.132738     0.123616\n INFORMATION USED FOR UPDATE (E,F)     2      5565       112\n -------------------------------------------------------------------------------\n ENERGY     3      0.022316     0.024581   19.13\n FORCES     3      0.120274     0.111427\n INFORMATION USED FOR UPDATE (E,F)     3      6033       131\n -------------------------------------------------------------------------------\n ENERGY     4      0.021333     0.023145   19.16\n FORCES     4      0.113496     0.105447\n INFORMATION USED FOR UPDATE (E,F)     4      6132       142\n -------------------------------------------------------------------------------\n ENERGY     5      0.022327     0.023597   19.13\n FORCES     5      0.113152     0.102596\n INFORMATION USED FOR UPDATE (E,F)     5      6064       137\n-------------------------------------------------------------------------------\n ENERGY     6      0.021007     0.022555   19.15\n FORCES     6      0.102685     0.094464\n INFORMATION USED FOR UPDATE (E,F)     6      6094       168\n -------------------------------------------------------------------------------\n ENERGY     7      0.021018     0.022213   19.15\n FORCES     7      0.098023     0.097181\n INFORMATION USED FOR UPDATE (E,F)     7      6226       158\n -------------------------------------------------------------------------------\n ENERGY     8      0.020692     0.022248   19.15\n FORCES     8      0.095995     0.097202\n INFORMATION USED FOR UPDATE (E,F)     8      6186       183\n -------------------------------------------------------------------------------\n ENERGY     9      0.020880     0.022219   19.16\n FORCES     9      0.094960     0.095833\n INFORMATION USED FOR UPDATE (E,F)     9      6122       176\n -------------------------------------------------------------------------------\n ENERGY    10      0.021217     0.022457   19.41\n FORCES    10      0.097554     0.094895\n INFORMATION USED FOR UPDATE (E,F)    10      6226       203\n =============================================================\n Best short range fit has been obtained in epoch     7\n                    --- E_short: ---          --- F_short: ---\n                   train         test        train         test\n OPTSHORT        0.021018     0.022213     0.098023     0.097181\n -------------------------------------------------------------\n max Eshort error in last epoch (train set):       0.281291  eV/atom (structure      788 )\n max Eshort error in last epoch (test set) :       0.261851  eV/atom (structure      253 )\n -------------------------------------------------------------\n Total runtime (s)  :      12095.013\n Total runtime (min):        201.584\n Total runtime (h)  :          3.360\n Normal termination of RuNNer\n -------------------------------------------------------------\nA first and simple plot to anlyze the progress of the fitting procedure, is to show the RMSEs over the epochs. Here, you can easily identify overfitting, if the training $RMSE$ is much lower than the test $RMSE$, for example.\nAnyhow, the $RMSE$ is a rather strong reduction of the really complex potential energy surface (PES) and can only be understood as a rule of thumb for the quality of the NNP fit.\n\n\n```python\n# Load here an example fit\n# Use results of the workshop participants\nfit2 = fc.RuNFit('runner_fit/fit_hdf5/fit', 9)\n#fit2 = fc.RuNFit('MH-df4-2', 7)\nfigRMSE = fit2.plot_rmse()\n```\n\nFor a more detailed analyze, you could have a look at the predicted energies and forces per structure. This is quite useful to identify inaccurately described structures. The training data set may has a specific order of different structures (bulk, slab, cluster, ...) and you can identify, if some parts of the data set are described inaccurately in general. The second plot shows the atomic energy prediction of the NNP over the reference values. For a perfect fit, all points will be on the blue line, but as we can see this is not the case. In this plot, we can identify, if some energies ranges are not well described in our data set. This is related to our first data set analysis above.\n\n\n```python\nfigE1, figE2, figF3 = fit2.plot_points()\n```\n\nThe same plot can also be done for the atomic forces.\n\n\n```python\nfigF1, figF2, figF3 = fit2.plot_forces()\n```\n\nThe ``mode 2`` output gives further information about the parameters of the fitting procedure, about the fitting data and it gives information about the defined SFs and the SFs ranges. These ranges define the known configuration space of your NNP and are used to identify the already mentioned ``extrapolations``. If the NNP is made to predict energies, forces or stress, it first calculates the SF vectors and compares these values to the trainings range shown below. If a SF value occurs, which is not in the range, **RuNNer** will give an ``extrapolation warning`` and tell the user, but you will still get your wanted energy, force or stress. Another usage of these ranges is to increase the data set and the known configuration space.\n =============================================================\n Short range symmetry function values for element Cu\n Training set:  min           max       average         range        stddev      range/stddev\n   1     6.72393532   25.25447208   14.00001115   18.53053676    4.02011080    4.60945921\n   2     5.03976308   19.37796546   10.59714429   14.33820238    3.11321693    4.60559053\n   3     3.25577537   13.11073890    6.98744718    9.85496353    2.14525332    4.59384607\n   4     1.25883453    6.21227127    3.05195579    4.95343674    1.07630994    4.60224009\n   5     0.06568766    1.53442885    0.48718005    1.46874120    0.26713619    5.49809898\n   6     2.42989188   42.06637435   12.30898440   39.63648248    7.96564228    4.97593051\n   7     6.59284339  109.34982696   33.28285935  102.75698358   21.03610544    4.88479124\n   8     0.78142670   19.11390444    5.22756080   18.33247774    3.61016236    5.07802030\n   9     5.20079617   86.39735705   26.20143575   81.19656088   16.68008353    4.86787495\n  10     0.15497639    7.72411752    1.91198556    7.56914113    1.46079520    5.18152107\n  11     3.59136462   60.38094318   17.95854981   56.78957856   11.72399989    4.84387403\n  12     0.00059457    1.66933490    0.34750355    1.66874033    0.32743124    5.09646040\n  13     0.52030958   18.24849080    4.70826264   17.72818122    3.59567219    4.93042198\n -------------------------------------------------------------\nDuring ``mode 2`` several files will be printed by **RuNNer** and some are printed every epoch:\n- scaling.data: information about the SFs if ``scale_symmetry_functions`` is used\n- xxxxxx.XXX.out: weights and biases of the specific epoch xxxxxx for atomic NN of element XXX\n- optweights.XXX.out: weights and biases of the epoch with lowest RMSE defined by **RuNNer** for element XXX\n- trainpoints.xxxxxx.out, testpoints.xxxxxx.out: optional, giving information about training and test energies of epoch xxxxxx\n- trainforces.xxxxxx.out, testforces.xxxxxx.out: optional, giving information about training and test forces of epoch xxxxxx\n\n## RuNNer Mode 3\n\n**RuNNer** ``mode 3`` is the prediction mode and brings the NNP to application. Via N2P2, NNP can also be used in LAMMPS. For ``mode 3``, the ``input.nn``, ``scaling.data`` (if scaling is used), ``weights.XXX.data`` and the ``input.data``, contaning the structures to predict, are needed. A first application of the NNP in the Cu case is to predict the correct energy-volume behaviour.\n\n\n```python\npr_ev = pr.create_group(\"E_V_curve\") # Creating a new sub-project within the main project\na_list = np.linspace(3.4, 4.0, 7)\nfor a in a_list:\n    job_name = \"job_a_{:.4}\".format(a).replace(\".\", \"_\")\n    job = pr_ev.create.job.Lammps(job_name, delete_existing_job=False)\n    job.structure = pr_ev.create_ase_bulk(\"Cu\", a=a)\n    #job.potential = '2012--Mendelev-M-I--Cu--LAMMPS--ipr1'\n    job.potential = j.lammps_potential\n    job.calc_minimize()\n    job.run()\n```\n\n    The job job_a_3_4 was saved and received the ID: 69\n    The job job_a_3_5 was saved and received the ID: 70\n    The job job_a_3_6 was saved and received the ID: 71\n    The job job_a_3_7 was saved and received the ID: 72\n    The job job_a_3_8 was saved and received the ID: 73\n    The job job_a_3_9 was saved and received the ID: 74\n    The job job_a_4_0 was saved and received the ID: 75\n\n\n\n```python\npr_ev.job_table()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>id</th>\n      <th>status</th>\n      <th>chemicalformula</th>\n      <th>job</th>\n      <th>subjob</th>\n      <th>projectpath</th>\n      <th>project</th>\n      <th>timestart</th>\n      <th>timestop</th>\n      <th>totalcputime</th>\n      <th>computer</th>\n      <th>hamilton</th>\n      <th>hamversion</th>\n      <th>parentid</th>\n      <th>masterid</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>69</td>\n      <td>finished</td>\n      <td>Cu</td>\n      <td>job_a_3_4</td>\n      <td>/job_a_3_4</td>\n      <td>/home/pyiron/</td>\n      <td>day_2/02-runner/runner_fit/E_V_curve/</td>\n      <td>2021-03-09 09:12:11.908333</td>\n      <td>2021-03-09 09:12:12.233260</td>\n      <td>0.0</td>\n      <td>pyiron@jupyter-janssen#1</td>\n      <td>Lammps</td>\n      <td>0.1</td>\n      <td>None</td>\n      <td>None</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>70</td>\n      <td>finished</td>\n      <td>Cu</td>\n      <td>job_a_3_5</td>\n      <td>/job_a_3_5</td>\n      <td>/home/pyiron/</td>\n      <td>day_2/02-runner/runner_fit/E_V_curve/</td>\n      <td>2021-03-09 09:12:12.600059</td>\n      <td>2021-03-09 09:12:12.930932</td>\n      <td>0.0</td>\n      <td>pyiron@jupyter-janssen#1</td>\n      <td>Lammps</td>\n      <td>0.1</td>\n      <td>None</td>\n      <td>None</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>71</td>\n      <td>finished</td>\n      <td>Cu</td>\n      <td>job_a_3_6</td>\n      <td>/job_a_3_6</td>\n      <td>/home/pyiron/</td>\n      <td>day_2/02-runner/runner_fit/E_V_curve/</td>\n      <td>2021-03-09 09:12:13.308590</td>\n      <td>2021-03-09 09:12:13.628758</td>\n      <td>0.0</td>\n      <td>pyiron@jupyter-janssen#1</td>\n      <td>Lammps</td>\n      <td>0.1</td>\n      <td>None</td>\n      <td>None</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>72</td>\n      <td>finished</td>\n      <td>Cu</td>\n      <td>job_a_3_7</td>\n      <td>/job_a_3_7</td>\n      <td>/home/pyiron/</td>\n      <td>day_2/02-runner/runner_fit/E_V_curve/</td>\n      <td>2021-03-09 09:12:14.004092</td>\n      <td>2021-03-09 09:12:14.332162</td>\n      <td>0.0</td>\n      <td>pyiron@jupyter-janssen#1</td>\n      <td>Lammps</td>\n      <td>0.1</td>\n      <td>None</td>\n      <td>None</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>73</td>\n      <td>finished</td>\n      <td>Cu</td>\n      <td>job_a_3_8</td>\n      <td>/job_a_3_8</td>\n      <td>/home/pyiron/</td>\n      <td>day_2/02-runner/runner_fit/E_V_curve/</td>\n      <td>2021-03-09 09:12:14.709127</td>\n      <td>2021-03-09 09:12:15.039564</td>\n      <td>0.0</td>\n      <td>pyiron@jupyter-janssen#1</td>\n      <td>Lammps</td>\n      <td>0.1</td>\n      <td>None</td>\n      <td>None</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>74</td>\n      <td>finished</td>\n      <td>Cu</td>\n      <td>job_a_3_9</td>\n      <td>/job_a_3_9</td>\n      <td>/home/pyiron/</td>\n      <td>day_2/02-runner/runner_fit/E_V_curve/</td>\n      <td>2021-03-09 09:12:15.413618</td>\n      <td>2021-03-09 09:12:15.737637</td>\n      <td>0.0</td>\n      <td>pyiron@jupyter-janssen#1</td>\n      <td>Lammps</td>\n      <td>0.1</td>\n      <td>None</td>\n      <td>None</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>75</td>\n      <td>finished</td>\n      <td>Cu</td>\n      <td>job_a_4_0</td>\n      <td>/job_a_4_0</td>\n      <td>/home/pyiron/</td>\n      <td>day_2/02-runner/runner_fit/E_V_curve/</td>\n      <td>2021-03-09 09:12:16.124528</td>\n      <td>2021-03-09 09:12:16.435324</td>\n      <td>0.0</td>\n      <td>pyiron@jupyter-janssen#1</td>\n      <td>Lammps</td>\n      <td>0.1</td>\n      <td>None</td>\n      <td>None</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndef get_volume(job):\n    return job[\"output/generic/volume\"][-1]\ndef get_energy(job):\n    return job[\"output/generic/energy_tot\"][-1]\n```\n\n\n```python\n# Analysing the data\nvol_list = list()\nenergy_list = list()\n\nfor job in pr[\"E_V_curve\"].iter_jobs(status=\"finished\"):\n    vol_list.append(get_volume(job))\n    energy_list.append(get_energy(job))\n\nargs = np.argsort(vol_list)\nvol_list = np.array(vol_list)\nenergy_list = np.array(energy_list)\nplt.plot(vol_list[args], energy_list[args], \"-x\")\nplt.xlabel(\"Volume [$\\mathrm{\\AA^3}$]\")\nplt.ylabel(\"Energy [eV]\");\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "0c29dcbc362cece354ef04d3ea0992ed3446bfc8", "size": 804016, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "day_2/02-runner/Workflow-RuNNer.ipynb", "max_stars_repo_name": "pyiron/pyiron_potentialf", "max_stars_repo_head_hexsha": "1134125e327c011812a42db31a73f8f23088c25d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-03-12T09:03:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T23:51:45.000Z", "max_issues_repo_path": "day_2/02-runner/Workflow-RuNNer.ipynb", "max_issues_repo_name": "pyiron/pyiron_potentialf", "max_issues_repo_head_hexsha": "1134125e327c011812a42db31a73f8f23088c25d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 39, "max_issues_repo_issues_event_min_datetime": "2021-02-28T09:45:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-09T10:56:54.000Z", "max_forks_repo_path": "day_2/02-runner/Workflow-RuNNer.ipynb", "max_forks_repo_name": "pyiron/pyiron_potentialfit", "max_forks_repo_head_hexsha": "1134125e327c011812a42db31a73f8f23088c25d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-10T11:51:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-10T11:51:34.000Z", "avg_line_length": 533.8751660027, "max_line_length": 427800, "alphanum_fraction": 0.9302650694, "converted": true, "num_tokens": 12965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.10818895240548258, "lm_q1q2_score": 0.04695200004053059}}
{"text": "```python\n# This cell installs VESICal. You can comment out with a #\n!pip install VESIcal\n```\n\n    Collecting VESIcal\n      Using cached VESIcal-0.9.12-py3-none-any.whl (111 kB)\n    Requirement already satisfied: cycler in /opt/conda/lib/python3.8/site-packages (from VESIcal) (0.10.0)\n    Requirement already satisfied: pandas in /opt/conda/lib/python3.8/site-packages (from VESIcal) (1.2.4)\n    Requirement already satisfied: sympy in /opt/conda/lib/python3.8/site-packages (from VESIcal) (1.7.1)\n    Requirement already satisfied: matplotlib in /opt/conda/lib/python3.8/site-packages (from VESIcal) (3.4.1)\n    Requirement already satisfied: scipy in /opt/conda/lib/python3.8/site-packages (from VESIcal) (1.6.2)\n    Requirement already satisfied: numpy in /opt/conda/lib/python3.8/site-packages (from VESIcal) (1.20.2)\n    Requirement already satisfied: six in /opt/conda/lib/python3.8/site-packages (from cycler->VESIcal) (1.15.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /opt/conda/lib/python3.8/site-packages (from matplotlib->VESIcal) (1.3.1)\n    Requirement already satisfied: pyparsing>=2.2.1 in /opt/conda/lib/python3.8/site-packages (from matplotlib->VESIcal) (2.4.7)\n    Requirement already satisfied: python-dateutil>=2.7 in /opt/conda/lib/python3.8/site-packages (from matplotlib->VESIcal) (2.8.1)\n    Requirement already satisfied: pillow>=6.2.0 in /opt/conda/lib/python3.8/site-packages (from matplotlib->VESIcal) (8.1.2)\n    Requirement already satisfied: pytz>=2017.3 in /opt/conda/lib/python3.8/site-packages (from pandas->VESIcal) (2021.1)\n    Requirement already satisfied: mpmath>=0.19 in /opt/conda/lib/python3.8/site-packages (from sympy->VESIcal) (1.2.1)\n    Installing collected packages: VESIcal\n    Successfully installed VESIcal-0.9.12\n\n\n\n```python\nimport VESIcal as v\n```\n\n\n```python\n# Importing matplotlib (python's plotting thing), pandas (pythons nice table formats) and numpy (python paths)\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n```\n\n    /opt/conda/lib/python3.8/site-packages/ipykernel/ipkernel.py:283: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.\n      and should_run_async(code)\n\n\n\n```python\n# Load in melt inclusion data\nmyfile= v.BatchFile('Cassidy2015_AndesiteMI_YouTubeDemo.xlsx', sheet_name='Sheet1',  input_type='wtpercent')\n```\n\n    /opt/conda/lib/python3.8/site-packages/ipykernel/ipkernel.py:283: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.\n      and should_run_async(code)\n\n\n\n```python\n# Allows you to inspect data, and check VESIcal has read column headings correctly (e.g., non zero values for oxides)\nmyfile.get_data()\n```\n\n    /opt/conda/lib/python3.8/site-packages/ipykernel/ipkernel.py:283: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.\n      and should_run_async(code)\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>SiO2</th>\n      <th>TiO2</th>\n      <th>Al2O3</th>\n      <th>Fe2O3</th>\n      <th>FeO</th>\n      <th>MnO</th>\n      <th>MgO</th>\n      <th>CaO</th>\n      <th>Na2O</th>\n      <th>K2O</th>\n      <th>H2O</th>\n      <th>CO2</th>\n      <th>Cr2O3</th>\n      <th>NiO</th>\n      <th>CoO</th>\n      <th>P2O5</th>\n      <th>Phase</th>\n      <th>Temp</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>SSH4_1</th>\n      <td>64.6</td>\n      <td>0.86</td>\n      <td>16.4</td>\n      <td>0.663327</td>\n      <td>3.3830</td>\n      <td>0.0</td>\n      <td>0.87</td>\n      <td>4.53</td>\n      <td>4.08</td>\n      <td>1.05</td>\n      <td>5.06</td>\n      <td>0.0105</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Pyx</td>\n      <td>1050</td>\n    </tr>\n    <tr>\n      <th>SSH4_2</th>\n      <td>63.6</td>\n      <td>0.59</td>\n      <td>16.5</td>\n      <td>0.573328</td>\n      <td>2.9240</td>\n      <td>0.0</td>\n      <td>0.78</td>\n      <td>4.24</td>\n      <td>4.31</td>\n      <td>0.97</td>\n      <td>5.08</td>\n      <td>0.0071</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Pyx</td>\n      <td>1050</td>\n    </tr>\n    <tr>\n      <th>SSH10_1</th>\n      <td>58.7</td>\n      <td>0.68</td>\n      <td>15.0</td>\n      <td>0.928324</td>\n      <td>4.7345</td>\n      <td>0.0</td>\n      <td>2.36</td>\n      <td>5.70</td>\n      <td>2.13</td>\n      <td>2.22</td>\n      <td>5.62</td>\n      <td>0.0313</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Ol</td>\n      <td>1050</td>\n    </tr>\n    <tr>\n      <th>SSH5B_1</th>\n      <td>67.6</td>\n      <td>0.48</td>\n      <td>17.0</td>\n      <td>0.079999</td>\n      <td>0.4080</td>\n      <td>0.0</td>\n      <td>0.02</td>\n      <td>3.14</td>\n      <td>4.51</td>\n      <td>1.58</td>\n      <td>6.19</td>\n      <td>0.0043</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Pyx_2</td>\n      <td>1050</td>\n    </tr>\n    <tr>\n      <th>SSH5B_2</th>\n      <td>67.2</td>\n      <td>0.70</td>\n      <td>16.9</td>\n      <td>0.076666</td>\n      <td>0.3910</td>\n      <td>0.0</td>\n      <td>0.02</td>\n      <td>3.31</td>\n      <td>4.49</td>\n      <td>1.60</td>\n      <td>5.48</td>\n      <td>0.0052</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Pyx</td>\n      <td>1050</td>\n    </tr>\n    <tr>\n      <th>SSH10</th>\n      <td>60.3</td>\n      <td>0.81</td>\n      <td>15.8</td>\n      <td>0.914991</td>\n      <td>4.6665</td>\n      <td>0.0</td>\n      <td>2.80</td>\n      <td>6.56</td>\n      <td>1.94</td>\n      <td>0.32</td>\n      <td>5.20</td>\n      <td>0.0250</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Ol</td>\n      <td>1050</td>\n    </tr>\n    <tr>\n      <th>SSH5B</th>\n      <td>68.0</td>\n      <td>0.41</td>\n      <td>16.2</td>\n      <td>0.233331</td>\n      <td>1.1900</td>\n      <td>0.0</td>\n      <td>0.60</td>\n      <td>4.20</td>\n      <td>4.20</td>\n      <td>1.60</td>\n      <td>5.70</td>\n      <td>0.0180</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Pyx</td>\n      <td>1050</td>\n    </tr>\n    <tr>\n      <th>SSH4_3</th>\n      <td>63.0</td>\n      <td>0.62</td>\n      <td>16.0</td>\n      <td>0.699993</td>\n      <td>3.5700</td>\n      <td>0.0</td>\n      <td>1.10</td>\n      <td>4.30</td>\n      <td>3.30</td>\n      <td>0.90</td>\n      <td>5.10</td>\n      <td>0.0140</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Pyx</td>\n      <td>1050</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nSat_P_MagmaSat=myfile.calculate_saturation_pressure(temperature=\"Temp\")\n```\n\n    [==                  ] 12%  Working on sample SSH4_1                            \n\n    /opt/conda/lib/python3.8/site-packages/ipykernel/ipkernel.py:283: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.\n      and should_run_async(code)\n\n\n    [====================] 100%  Working on sample SSH4_3                            \n\n\n\n```python\n# Inspecting saturation pressures\nSat_P_MagmaSat['SaturationP_bars_VESIcal']\n```\n\n\n\n\n    SSH4_1     1760\n    SSH4_2     1740\n    SSH10_1    2560\n    SSH5B_1    2170\n    SSH5B_2    1850\n    SSH10      2210\n    SSH5B      2090\n    SSH4_3     1930\n    Name: SaturationP_bars_VESIcal, dtype: int64\n\n\n\n\n```python\n# Doing same, but using IaconoMarziano\nSat_P_IaconoMarziano=myfile.calculate_saturation_pressure(temperature=\"Temp\", model='IaconoMarziano')\n```\n\n    /opt/conda/lib/python3.8/site-packages/VESIcal/model_classes.py:365: RuntimeWarning: Saturation pressure not found.\n      xx0 = model.calculate_saturation_pressure(sample=sample,**kwargs)\n\n\n\n```python\n# Calculating saturation pressures using the simplification of Dixon 1997 implemented in VolatileCalc\nSat_P_Dixon=myfile.calculate_saturation_pressure(temperature=\"Temp\", model='Dixon')\n```\n\n\n```python\n# Comparing different models\n```\n\n\n```python\nfig, ((ax1, ax2)) = plt.subplots(1, 2, figsize = (12,5))\nax1.plot(Sat_P_MagmaSat['SaturationP_bars_VESIcal'], Sat_P_Dixon['SaturationP_bars_VESIcal'], 'ok')\nax1.plot([1800, 3500], [1800, 3500], '-r')\nax1.set_xlabel('Sat P MagmaSat')\nax1.set_ylabel('Sat P VolatileCalc Basalt')\n\nax2.plot(Sat_P_MagmaSat['H2O'], Sat_P_MagmaSat['SaturationP_bars_VESIcal'], 'ok')\nax2.set_ylabel('Sat P MagmaSat')\nax2.set_xlabel('H2O (wt%)')\n```\n\n\n```python\n# Plotting as histograms (obviously this is a very small dataset, but that is to allow fast computation in this example!)\nfig, ((ax1, ax2)) = plt.subplots(1, 2, figsize = (12,5), sharex=True)\nax1.hist(Sat_P_Dixon['SaturationP_bars_VESIcal'], color='cornflowerblue')\nax2.hist(Sat_P_MagmaSat['SaturationP_bars_VESIcal'], color='grey')\nax1.set_xlabel('Saturation pressure (bars)')\nax2.set_xlabel('Saturation pressure (bars)')\nax1.set_ylabel('# of measurements')\nax1.locator_params(axis=\"both\", integer=True, tight=True)\nax2.locator_params(axis=\"both\", integer=True, tight=True)\n\nfig.savefig('Andesitic_MIs_Histogram.svg', transparent=True)\n```\n\n\n```python\n# Save calculations to excel for future reference\nmyfile.save_excel(filename = 'Andesite_MI_SatPs.xlsx', calculations=[Sat_P_MagmaSat, Sat_P_Dixon], sheet_names=['Magmasat', 'Dixon'])\n```\n\n    Saved Andesite_MI_SatPs.xlsx\n\n\n\n```python\n# Or just save a single set of calculations using Pandas\nSat_P_IaconoMarziano.to_excel('SatP_IaconoMarziano.xlsx')\n```\n", "meta": {"hexsha": "26377dfb56a8beacfbfe55af9ca1a568a9c980c9", "size": 71264, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "You Tube Examples/Saturation_pressure_example.ipynb", "max_stars_repo_name": "bobmyhill/VESIcal", "max_stars_repo_head_hexsha": "f401226b55bdb6c8e6f1838aba78927664c89706", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2020-06-22T09:07:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T13:42:12.000Z", "max_issues_repo_path": "You Tube Examples/Saturation_pressure_example.ipynb", "max_issues_repo_name": "bobmyhill/VESIcal", "max_issues_repo_head_hexsha": "f401226b55bdb6c8e6f1838aba78927664c89706", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 136, "max_issues_repo_issues_event_min_datetime": "2020-05-22T21:43:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T22:06:33.000Z", "max_forks_repo_path": "You Tube Examples/Saturation_pressure_example.ipynb", "max_forks_repo_name": "bobmyhill/VESIcal", "max_forks_repo_head_hexsha": "f401226b55bdb6c8e6f1838aba78927664c89706", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-05-18T08:21:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T01:08:10.000Z", "avg_line_length": 122.2367066895, "max_line_length": 38448, "alphanum_fraction": 0.8344185002, "converted": true, "num_tokens": 3704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.0953494738965146, "lm_q1q2_score": 0.04692987979908419}}
{"text": "# Data structures and algorithms for spell checking and correction\n\nBy Robin William Hundt, University of G\u00f6ttingen  \nInspired by John Bentleys article \"A spelling checker\" [1]  \n<br>\nGit: https://gitlab.gwdg.de/robinwilliam.hundt/programming-pearls-spelling-checker\n\n# Table of contents\n\n1. [Introduction](#intro)\n2. [Spell checking](#spell-checking)\n    1. [Original spell program and Python implementation](#spell)\n    2. [Testing the implementation](#testing-spell)\n    3. [Trie data structure](#trie-data-structure)\n    4. [Testing of trie and benchmarks](#testing-trie)\n    5. [Spell checking: conclusion](#checking-conclusion)\n3. [Spelling correction](#spell-correcting)\n    1. [Distance of strings](#string-distance)\n    2. [Frequency of strings and fast corrector](#freq-fast-corrector)\n    3. [Symmetric delete spelling correction (SymSpell)](#sym-spell)\n    4. [SymSpell benchmarks](#testing-sym-spell)\n    5. [Corrector accuracy](#corrector-accuracy)\n    6. [Spelling correction: conclusion](#correcting-conclusion)\n4. [References](#references)\n    1. [Data sources](#data-sources)\n    2. [Libraries](#libraries)\n\n# Introduction <a name=\"intro\"/>\n\nThis notebook is a technical preparation about data structures and algorithms for spell checking and correction.  \nIt has been developed for the *Programming pearls* seminar at the university of Goettingen (May - June 2018) and is inspired by John Bentleys article *A spelling checker* which was part of his *programming pearls* article series[1].  \n  \nAll relevant data sources are included in the repository.\n\n### Dependencies\nTo install the necessary dependencies simply execute within a cell or a terminal (here without the !)\n```bash\n!pip install --user -r requirements.txt\n```\n\n**Note:** Since this notebook contains a number of different benchmarks, running all cells takes several minutes.\n\n\n```python\n# just some boring imports\nfrom io import StringIO\nfrom time import sleep\nfrom typing import Set, Tuple, Iterable, Callable, List, Dict\nfrom types import MethodType\nfrom functools import partial\nimport re\nimport timeit\nimport gc\n\nimport marisa_trie\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pympler.asizeof import asizeof\nfrom IPython.core.interactiveshell import InteractiveShell\n\nInteractiveShell.ast_node_interactivity = \"all\"\n\n%load_ext memory_profiler\n%matplotlib inline\n\n# small decorator to split class definitions over several slides\ndef add_to_class(cls):\n    def decorator(fn):\n        setattr(cls, fn.__name__, fn)\n        return fn\n    return decorator\n```\n\n# Spell checking <a name=\"spell-checking\"/>\n## Original spell program and Python implementation <a name=\"spell\"/>\n\nIn 1975 Steve Johnson wrote the first version of the `spell` program[1]. The improved version by Douglas McIlroy would later become the standard english language spell checker on Unix (introduced in v7 [2]).  \nThe original version is particularly interesting for it's simplicity and clever combination of already existing porgrams with highly specific functions into a new program that has a clearly defined functionality:\n\n\n\nReconstructed version of Steve Johnsons spell (Kernighan and Bauer, Software Tools in Pascal)\n\n``` bash\nprepare filename |                 # remove formatting commands\n    translit A-Z a-z |             # map upper to lower case\n        translit ^a-z @n |         # remove punctuation\n            sort |                 # put words in alphabetical order\n                unique |           # remove duplicate words\n                    common -2 dict # report words not in dictionary\n```\n*source: [1]*\n\nThe shell pipeline operator `|` is used to *pipe* the output of the program on the left side to the program on the right side as its input. Using this, several porgrams can be chained together in a clear and concise way.\n  \nUnfortunately there is no *pipe* operator in Python, but by utilizing the comprehensive standard libraries we can implement nearly the same functionality that the original `spell` offered in a few lines of code.\n\n\n```python\ndef spell(filename: str, word_dict: str) -> Set[str]:\n    w = set(word_dict.lower().split('\\n'))\n    with open(filename) as f:\n        return set(re.sub(r\"[^a-z]\", \"\\n\", f.read().lower()).split('\\n')) - w\n```\n\nThis version however has, some of the same shortcomings as Steve Johnsons, e.g. `isn't` is converted to `isn` and `t` which aren't english words, but `isn't` is.\n\n## Testing the implementation <a name=\"testing-spell\"/>\nIn order to test the function we need two things:  \n1. A text file with a big amount of english text\n2. A dictionary where we look up the words of the input text  \n\nAs a text file we can use the `big.txt` file provided by [Peter Norvig](http://norvig.com/) [D1] which is a concatination of public domain book excerpts from [Project Gutenberg](http://www.gutenberg.org/wiki/Main_Page)(inaccessible with a german IP) and lists of most frequent english words.  \nFollowing is the number of words inside that fille and a small excerpt.\n\n\n```python\n!echo word count: $(wc -w big.txt) '\\n'\n!head -n 5000 big.txt | tail -n 1\n```\n\n    word count: 1095695 big.txt \n    \n    \"You can easily imagine, Mr. Holmes, how curious I became as to what the meaning of this extraordinary performance could possibly be. They were always very careful, I observed, to turn my face away from the window, so that I became consumed with the desire to see what was going on behind my back. At first it seemed to be impossible, but I soon devised a means. My hand-mirror had been broken, so a happy thought seized me, and I concealed a piece of the glass in my handkerchief. On the next occasion, in the midst of my laughter, I put my handkerchief up to my eyes, and was able with a little management to see all that there was behind me. I confess that I was disappointed. There was nothing. At least that was my first impression. At the second glance, however, I perceived that there was a man standing in the Southampton Road, a small bearded man in a grey suit, who seemed to be looking in my direction. The road is an important highway, and there are usually people there. This man, however, was leaning against the railings which bordered our field and was looking earnestly up. I lowered my handkerchief and glanced at Mrs. Rucastle to find her eyes fixed upon me with a most searching gaze. She said nothing, but I am convinced that she had divined that I had a mirror in my hand and had seen what was behind me. She rose at once.\n\n\nSo we have our big text file of english text, now we need a dictionary.\nLuckily on most Unix and Unix-like systems there is a comprehensive newline delimeted dictionary text file available. The file usually resides under `/usr/share/dict/words` od `/usr/dict/words`. To ensure portability the file is also available inside the repository as `american-english`.\n\n\n```python\n!echo word count: $(wc -w american-english) '\\n'\n!head -n 5000 american-english | tail\n```\n\n    word count: 99171 american-english \n    \n    Eula\n    Eula's\n    Euler\n    Eumenides\n    Eumenides's\n    Eunice\n    Eunice's\n    Euphrates\n    Euphrates's\n    Eurasia\n\n\nWe read in the dictionary file as a single string to be passed to our Python version of `spell`.\n\n\n```python\nwith open('american-english') as w:\n    words_file = w.read()\n```\n\nNow that we have the necessary files requiered to assess the quality of our implementation we must ask ourselves: What do we actually want to test?  \nThree things come to mind:  \n1. The number of unique false positives\n2. The memory consumption of the function\n3. The execution time of the function\n  \n### False positives\nIn the following cell we first calculate the number of unique words in the `big.txt` file, then pass it to the spell checking function and output the number of unique misspelled words as well as a slice of the error set.\n\n\n```python\nwith open('big.txt') as f:\n    num_unique_words = len(set(f.read().split()))\nf\"Number of individual words in big.txt: {num_unique_words}\" \nerrors = spell('big.txt', words_file)\nf\"Number of individual misspelled words: {len(errors)}\"\nlist(errors)[:10]\n```\n\n\n\n\n    'Number of individual words in big.txt: 81397'\n\n\n\n\n\n\n    'Number of individual misspelled words: 5065'\n\n\n\n\n\n\n    ['tsaritsin',\n     'coquetry',\n     'phlegmon',\n     'afebrile',\n     'federative',\n     'mcduffie',\n     'cauterisation',\n     'dishonourable',\n     'diplococcus',\n     'hyoscin']\n\n\n\nAround five thousand unique words of the original eigthy thousand unique words are declared as misspelled by our `spell` version. However when we look at some of the words that are declared as wrong we see that they contain a lot of (medical) technical terms like iodides, leucocytes, hyperostosis or names like Shrewsbury and Newtown.  \nApparently writing a minimal spelling checker is an easy task, however to use it productively, great care has to be put into the dictionary that is used as the basis. \n  \nSince the quality of a spelling checker in terms of false-positives largely depends on the dictionary used, we'll mainly look at the other two metrics, memory consumption and execution time.\n\n### Rough estimate of memory consumption\n\n\n\nSince doing an analytical analysis of the memory consuption of an algorithm is a difficult task when using many library functions, we instead try to assess the memory footprint empirical.  \nIn order to do this we change the first version of spell to handle file like objects that have a `read()` method instead of file names or paths. \n\n\n```python\n# this version excpects a file object instead of a file name\ndef spell2(file, word_dict: str) -> Set[str]:\n    w = set(word_dict.lower().split('\\n'))\n    return set(re.sub(r\"[^a-z]\", \"\\n\", file.read().lower()).split('\\n')) - w\n```\n\nUsing the adapted version and the [memory_profiler](https://pypi.org/project/memory_profiler/) package we can get an idea of the memory requierements during the execution of the algorithm.\nIt should be noted however, that the output of the `%memit` magic command at times seems highly erratic. It is very likely to produce different results on different runs.\n\n\n```python\nwith open('big.txt') as f:\n    text = f.read()\n\nout_mem = []\ngc.disable()\nfor i in range(1, 16):\n    char_count = (len(text) // 15) * i\n    unique_word_count = len(set(text[:char_count].split()))\n    text_io = StringIO(text[:char_count])\n    tmp = %memit -o -q spell2(text_io, words_file)\n    tmp = (unique_word_count, tmp.mem_usage[0] - tmp.baseline)\n    text_io.close()\n    out_mem.append(tmp)\ngc.enable()\n```\n\nAlthough the actual MB numbers should be taken with a grain of salt, the data suggest that we have a polynomial relationship between the number of unique words in the input and the amount of memory allocated during the execution.\n\n\n```python\nuniq_word_counts, memory = list(zip(*out_mem))\nplt.figure(dpi=100, figsize=(8,8));\nplt.title(\"Approximate memory consumption of spell function relative to unique word count\")\nplt.xlabel(\"Amount of unique words in input\")\nplt.ylabel(\"Approx. amount of memory in MB allocated during execution\")\nplt.plot(uniq_word_counts, memory);\n```\n\n### Benchmark of execution time\n\nThe last metric and also the most important one is the execution time.  \nWe again use the adapted version of the spell function in order to execute the function on partitons of the original file that are linearly increasing in size.\n\n\n```python\ndef time_spell_func(text, spell_func, num_partitions=15, runs_per_partition=20):\n    \"\"\" This function time the execution of one of the spell like functions by partitioning the passed text \n        into num_partitions chunks where each chunk is len(text)//num_partitions bigger than the \n        previous one (the chunk sizes are are increasing linearly).\n        This function deliberately sets -n 1 -r 1 for the %timeit magic command to prevent caching issues.\n    \"\"\"\n    timing_data = []\n    gc.disable()\n    for i in range(1, num_partitions+1):\n        char_count = (len(text) // num_partitions) * i\n        run_times = []\n        for _ in range(runs_per_partition):\n            text_io = StringIO(text[:char_count])  # provide file like object of partition of orginal file\n            tmp = %timeit -q -o -n 1 -r 1 spell_func(text_io) # timeit magic command is used to collect timings\n            run_times.append(tmp.best)\n            text_io.close()\n        timing_data.append((char_count, run_times))\n    gc.enable()\n    return timing_data\n```\n\nLooking at the plotted data, we can clearly see that there is a linear relationship between the execution time and the amount of characters in the input file. \n\n\n```python\nchar_counts, time_spell = list(zip(*time_spell_func(text, partial(spell2, word_dict=words_file))))\nplt.figure(dpi=100, figsize=(16,8));\nplt.title(\"Execution time of spell function relative to char count\")\nplt.xlabel(\"Amount of characters in input, increasing by 1/15th of original size\")\nplt.ylabel(\"Execution time in seconds\")\nplt.boxplot(time_spell, labels=char_counts);\n```\n\n### That is quite fast for a 1 million words file!\n\nThe speed is actually quite good, compared to the already optimized version of `spell` by Doug McIlroy (written in 1978). That version managed to check a 5,000 word document in **under 30 seconds** (on a VAX-11/750 with 3.125 MHz)[1]. The dramatic decrease in spell checking time (30 seconds for 5,000 words compared to ~0.6-1.0 seconds for nearly 1,000,000 words) can be partly attributed to a tremendous increase in computing power but is also due to the `spell2` version not actually loading the file to be checked from disk, but using a StringIO object that is already loaded into memory and has thus considerably lower access times.\n\n### But can we do better?\n\n\n## Trie data structure <a name=\"trie-data-structure\"/>\n\n<div>\n    \n    <a href=\"https://de.wikipedia.org/wiki/Trie#/media/File:Trie.svg\">Trie.svg</a> created by <a href=\"https://de.wikipedia.org/wiki/Benutzer:Nd\">nd</a> (<a href=\"https://creativecommons.org/licenses/by-sa/3.0/\">CC BY-SA 3.0</a>)\n</div>\n\n\nWe can use a **Trie** or \"prefix-tree\", which is an ordered tree data structure, to efficiently store all the words from our dictionary.  \nThe nodes themselves don't carry information about the key they're storing, instead the key is solely encoded in the position of the node and the information associated with the edges inside it.\nIn theory, this structure allows us to look up words in $O(length(word))$ while saving the strings in a compressed way, but will it actually be better than using standard Python sets?\n\nSimple Node object that solely stores information about neighbouring nodes and which letter the the connecting edges represent. Edge information is saved inside Python dictionaries to ensure fast $O(1)$ access.\n\n\n```python\nclass IllegalTrieEdge(Exception):\n    pass\n\nclass Node:\n    def __init__(self):\n        self.edges = {}\n        self.end_of_word = False  # note that not only leaves can be valid words, but also intermediate nodes\n        \n    def add_edge(self, ch: str):\n        if len(ch) != 1:\n            raise IllegalTrieEdge('Edges can only consist of one character')\n        if ch not in self.edges:\n            self.edges[ch] = Node()\n        return self.edges[ch]\n    \n    def get_edge(self, ch: str):\n        return self.edges.get(ch)\n    \n    def __contains__(self, edge: str):\n        return edge in self.edges\n```\n\nBasis of the Trie class with helper method `_find_last_prefix_node()` method.\n\n\n```python\nclass Trie:\n    def __init__(self, words=[]):\n        self.root = Node()\n        self._build_trie(words)\n        \n        \n    def _find_last_prefix_node(self, word: str) -> Tuple[str, Node]:\n        \"\"\" Helper method that, given a word, returns a tuple consisting of the prefix \n            of the word that is contained in the trie and the Node within the trie representing \n            the end of the prefix. Should the word not be saved in the trie, an empty string\n            and the root is returned. If the trie contains the full word then prefix == word.\n        \"\"\"\n        v = self.root\n        prefix = ''\n        while len(word) > 0 and word[0] in v:\n            prefix += word[0]\n            v = v.get_edge(word[0])\n            word = word[1:]\n        return prefix, v\n```\n\nThe `_find_last_prefix_node()` method can be used to easily implement the addition of words as well as the `__contains__()` [magic method](https://rszalski.github.io/magicmethods/).\n\n\n```python\n@add_to_class(Trie)\ndef _add_word(self, word: str):\n    \"\"\" Helper method that adds a single word to the trie.\n    \"\"\"\n    prefix, node = self._find_last_prefix_node(word)\n    if prefix == word:\n        node.end_of_word = True\n    word = word[len(prefix):]\n    while len(word) > 0:\n        node = node.add_edge(word[0])\n        word = word[1:]\n    node.end_of_word = True\n```\n\nBuild up a trie by repeatedly calling `_add_word()` with the contents of the passed Iterable `words`.\n\n\n```python\n@add_to_class(Trie)\ndef _build_trie(self, words: Iterable[str]):\n    for word in words:\n        self._add_word(word)\n```\n\nImplementing the `__contains_()` magic method allows us to use the `in` operator to test for membership.\n\n\n```python\n@add_to_class(Trie)\ndef __contains__(self, word: str) -> bool:\n    prefix, node = self._find_last_prefix_node(word)\n    return prefix == word and node.end_of_word\n```\n\n## So lets test it, shall we?  <a name=\"testing-trie\"/>\nAs the dictionary to store inside the trie we'll again use the standard english words file on unix systems, splitted at newlines.\n\n\n```python\nwith open('american-english') as w:\n    words_file = w.read()  \n    words = [word for word in words_file.split('\\n') if len(word) > 0]\n```\n\n### Quick test of our implementation\nIn order to quickly test our implementation we can use a list comprehension that should output all the words from our dictionary file for which the Trie membership test returns false. To verify that the `__contains__()` method doesn't just always output `True` we also test for membership of two words that are **not** in the dictionary.\n\n\n```python\ntrie = Trie(words)\n```\n\n\n```python\n[word for word in words if word not in trie]\n'adasedadwa'  in trie\n'Hallo' in trie\n```\n\n\n\n\n    []\n\n\n\n\n\n\n    False\n\n\n\n\n\n\n    False\n\n\n\n### Memory decrease by using a prefix tree (trie)....\nDid we accomplish a reduction of memory used by the dictionary by utilizing this, in theory efficient datastructure?  \nIn order to test this we can use the [pympler](https://pypi.org/project/Pympler/) python package that is able to recursively estimate the size of Python objects.\n\n\n```python\nsize_words_file = asizeof(words_file)\nsize_words = asizeof(words)\nsize_trie = asizeof(trie)\nf\"Size read file: {size_words_file} B; size word list: {size_words} B; size of trie: {size_trie} B\"\nf\"Increase in size by factor {size_trie/size_words_file}\"\n```\n\n\n\n\n    'Size read file: 938664 B; size word list: 6884128 B; size of trie: 93362984 B'\n\n\n\n\n\n\n    'Increase in size by factor 99.46368881729778'\n\n\n\n### An increase by a factor of ~ 100 ?! \n\nPython is a highly dynamic language where **everything** is an object, even simple things like an integer or character. This adds an immense overhead, which results in this dramatic increase in size.  \nSo saving space by using a prefix tree implemented in native Python is not possible, due to the limitations of the language.  \n\n### But maybe it is at least fast?  \n\nWe adapt the `spell` function from earlier to calculate $A \\backslash B$ where $A = \\{w | w$ in file$\\}$ and \n$B = \\{w | w$ in dictionary$\\}$ and $B$ is a Python object implementing the `__contains__()` method.\n\n\n```python\ndef spell_G(file, word_dict) -> Set[str]:\n    return {\n        word for word in\n        # read the file to check -> convert to lower -> split at newlines \n        # -> remove punctuation -> remove double occurences (conv. to set)\n        set(re.sub(r\"[^a-z']\", \"\\n\", file.read().lower()).split('\\n'))\n        if word not in word_dict\n    }\n```\n\n\n```python\nchar_counts, time_spell_trie = list(zip(*time_spell_func(text, partial(spell_G, word_dict=trie))))\n```\n\n\n```python\nplt.figure(dpi=100, figsize=(16,8));\nplt.title(\"Execution time of spell function relative to char count\")\nplt.xlabel(\"Amount of characters in input\")\nplt.ylabel(\"Execution time in seconds\")\nplt.boxplot(time_spell_trie, labels=char_counts);\n```\n\n#### Quite underwhelming\nIt seems that it's not only not possible to save memory by implementing a trie datastructure in Python but that there is also no reduction of execution time.\n\nNevertheless maybe we can finally gain something by further utilizing the vast Python ecosysytem and instead of using a pure Python implementation of a trie, we use a wrapper for a c++ implementation.  \nThe package of choice is [marisa-trie](https://pypi.org/project/marisa-trie/)\n\n\n```python\ntrie_efficient = marisa_trie.Trie(words)\n```\n\n\n```python\nchar_counts, time_spell_marisa = list(zip(*time_spell_func(text, partial(spell_G, word_dict=trie_efficient))))\n```\n\n\n```python\nplt.figure(dpi=100, figsize=(16,8));\nplt.title(\"Execution time of spell function relative to char count\")\nplt.xlabel(\"Amount of characters in input\")\nplt.ylabel(\"Execution time in seconds\")\nplt.boxplot(time_spell_marisa, labels=char_counts);\n```\n\n\n```python\ndata = [time_spell[-1], time_spell_trie[-1], time_spell_marisa[-1]]\nplt.figure(dpi=110, figsize=(6,4));\nplt.boxplot(data, labels=['spell2', 'spell_G (trie)', 'spell_G (marisa_trie)']);\n```\n\n## Spell checking: Conclusion <a name=\"checking-conclusion\"/>\n\nImplementing a usable spelling checker in Python only takes a couple of minutes and a few lines of code. The quality of the spelling checker in terms of false positives is mainly dependant on the dictionary that is used as the basis. Trying to further increase the performance and memory efficiency by implementing a trie in pure Python code proves difficult, due to the nature of Python, a highly dynamic language without static typing.  \nEven using a c++ implementation of a trie, we were only able to slightly reduce the runtime of the spell checking.\n\n<br/><br/><br/>\n<hr/>\n<br/><br/><br/>\n# Spelling correction <a name=\"spell-correcting\"/>\nIdentifying words that are not part of a dictionary as part of spell checking is very useful, but surely there must be a way to also give sensible suggestions as to what actual word might have been meant by the misspelling.  \nAchieving spelling correction that is not only performant (again in pure Python) by using clever algorithms, but also actually makes helpful suggestions is the topic of this second part.\n  \nIn order to achieve this goal we need two things:  \n1. A measure of how similar two words are\n2. A language model in order to estimate the probability of a word\n\n## *Distance* of strings <a name=\"string-distance\"/>\nTo determine how similar words are, we have a look at two string distances (metrics) and their implementations: Levenshtein distance and an extension of the first, the Damerau-Levenshtein distance.\n### Levenshtein distance (edit distance)\n\nThe Levenshtein distance is defined as the minimal number of single-character edits (insertion, deletion, substitution) needed to change word $a$ into word $b$.\n\nMathematically it can be expressed like this:\n\n\\begin{equation}\n\\qquad\\operatorname{lev}_{a,b}(i,j) = \\begin{cases}\n  \\max(i,j) & \\text{ if} \\min(i,j)=0, \\\\\n  \\min \\begin{cases}\n          \\operatorname{lev}_{a,b}(i-1,j) + 1 \\\\\n          \\operatorname{lev}_{a,b}(i,j-1) + 1 \\\\\n          \\operatorname{lev}_{a,b}(i-1,j-1) + 1_{(a_i \\neq b_j)}\n       \\end{cases} & \\text{ otherwise.}\n\\end{cases}\n\\end{equation}  \n\nwhere:  \n\n- $1_{(a_i \\neq b_j)}$ is an indicator function equal to 0 when $a_i = b_j$ and equal to 1 otherwise  \n- $\\operatorname{lev}_{a,b}(i,j)$ is the distance of the first $i$ characters of $a$ and the first $j$ characters of $b$\n\n#### Example:\n$\\qquad\\operatorname{lev}_{\\text{kitten},\\text{sitting}}(6,7) = 3$  \n$\\qquad$**k**itten $\\rightarrow$ *s*itt**e**n $\\rightarrow$ sitt*i*n $\\rightarrow$ sittin*g* \n\n### Recursive implementation with exponential runtime\n\nTaking the mathematical definition we can easily implement the distance function as a recursive Python function.\n\n\n```python\ndef levenshtein_distance(s: str, t: str):\n    if min(len(s), len(t)) == 0:\n        return max(len(s),len(t))\n    \n    cost = 0 if s[-1] == t[-1] else 1  # corresponds to the indicator function\n    \n    return min(levenshtein_distance(s[:-1], t) +1,\n               levenshtein_distance(s, t[:-1]) +1,\n               levenshtein_distance(s[:-1], t[:-1]) + cost\n              )\n```\n\nIn order to test different implementations of distance functions we define a function that takes a string, a list of words, a callable distance function and a maximal distance.  \nThe function simply returns all words within in the passed list that are within the specified maximal distance from the passed string.\n\n\n```python\ndef close_strings(s: str, words: Iterable[str],\n                  distace_func: Callable[[str, str], int],\n                  max_distance: int = 2):\n    return [word for word in words if 0 <= distace_func(s, word) <= max_distance]\n```\n\nRunning the function with the word 'hel' and a max edit distance of 2 returns quiete a big list of potential corrections, the first 10 shown below. \n\n\n```python\nclose_strings('hel', words, levenshtein_distance, 2)[:10]\n```\n\n\n\n\n    ['Abel', 'Al', 'Be', 'Bela', 'Bell', 'Ben', 'Cal', 'Celt', 'Che', 'Chen']\n\n\n\nLooking at the recursive implementation of the levenshtein distance and the fact that we iterate over a whole dictionary within `close_strings()` it becomes evident, that this approach will likely not be performant enough to be used as an actual spelling suggestor.  \nA quick (or actually not so quick) call to `%timeit` confirms this.\n\n\n```python\ntime_lev = %timeit -q -o -r 1 -n 1 close_strings('hel', words, levenshtein_distance, 2)\nf\"Best: {time_lev.best} s\"\n```\n\n\n\n\n    'Best: 181.64795927796513 s'\n\n\n\n### Utilize dynamic programming  \n\nBy using a dynamic programming approach we can reduce the complexity of the original recursive function (exponential to the power of 3) to just $O(nm)$.  \nThis is achieved by storing the distances of prefixes of the input words in a 2-dimensional matrix instead of recalculating them.\n\n\n```python\ndef levenshtein_dp(s: str, t: str):\n    n = len(s) + 1\n    m = len(t) + 1\n    d = np.zeros((n, m))\n    d[:, 0] = range(n)\n    d[0, :] = range(m)\n    \n    for j in range(1, m):\n        for i in range(1, n):\n            cost = 0 if s[i-1] == t[j-1] else 1\n            d[i, j] = min(d[i-1, j] + 1,\n                          d[i, j-1] + 1,\n                          d[i-1, j-1] + cost\n                         )\n    return d[n-1,m-1]\n```\n\nRunning the `%timeit` command on the improved version reveals the enourmous difference between a quadratic algorithm and an exponential one.\n\n\n```python\ntime_lev_dp = %timeit -q -o -r 3 -n 1 close_strings('hallo', words, levenshtein_dp, 2)\nf\"Best: {time_lev_dp.best} s\"\n```\n\n\n\n\n    'Best: 9.363651401014067 s'\n\n\n\n### Damerau-Levenshtein distance\n\nBefore we begin to consider the language model and the implementation of a **fast** spelling corrector we implement another version of the levenshtein distance called the *Damerau-Levenshtein distance*. The only difference compared to the usual one is, that it also counts transpositions between succesive elements as a single character edit.  \nThis is especially useful since swapping two successive characters within a word is a common mistake made by humans typing on keyboards.\n\n\\begin{equation}\nd_{a,b}(i,j) = \\begin{cases}\n  \\max(i,j) & \\text{ if} \\min(i,j)=0, \\\\\n\\min \\begin{cases}\n          d_{a,b}(i-1,j) + 1 \\\\\n          d_{a,b}(i,j-1) + 1 \\\\\n          d_{a,b}(i-1,j-1) + 1_{(a_i \\neq b_j)} \\\\\n          d_{a,b}(i-2,j-2) + 1\n       \\end{cases} & \\text{ if } i,j > 1 \\text{ and } a_i = b_{j-1} \\text{ and } a_{i-1} = b_j \\\\\n  \\min \\begin{cases}\n          d_{a,b}(i-1,j) + 1 \\\\\n          d_{a,b}(i,j-1) + 1 \\\\\n          d_{a,b}(i-1,j-1) + 1_{(a_i \\neq b_j)}\n       \\end{cases} & \\text{ otherwise.}\n\\end{cases}\n\\end{equation}\n\n\n```python\ndef damerau_levenshtein(s: str, t: str):\n    n = len(s) + 1\n    m = len(t) + 1\n    d = np.zeros((n, m))\n    d[:, 0] = range(n)\n    d[0, :] = range(m)\n    \n    for j in range(1, m):\n        for i in range(1, n):\n            cost = 0 if s[i-1] == t[j-1] else 1\n            d[i, j] = min(d[i-1, j] + 1,\n                          d[i, j-1] + 1,\n                          d[i-1, j-1] + cost\n                         )\n            if i > 1 and j > 1 and s[i-1] == t[j-2] and s[i-2] == t[j-1]:\n                d[i,j] = min(d[i,j], d[i-2, j-2] + cost)\n    return d[n-1,m-1]\n```\n\n## Frequency of strings and *fast* corrector <a name=\"freq-fast-corrector\"/>\n\nIn order to write an actually useful corrector we need a language model which gives us an estimate of the probability of a word within texts of that language.  \nTake for example the word `hellp`, the words `help, hello, hell` are all within an edit distance of one. However the word `help` occurs much more frequent in english text than the other two und thus, we treat it as the most likely correction (approach inspired by Peter Norvig [4]). This is obviously a very simplified model of language since we completely ignore the context that the word appears in. Nonetheless even this simple model can be used to achieve useful corrections as we see later. \n  \nTo estimate the probabilities of words in the english language we use the word frequency file by wolfgarbe: [GitHub SymSpell](https://github.com/wolfgarbe/SymSpell/blob/master/SymSpell/frequency_dictionary_en_82_765.txt) [D2]\n\n\n```python\n!echo word count: $(wc -l frequency_dictionary_en_82_765.txt) '\\n'\n!head -n 5000 frequency_dictionary_en_82_765.txt | tail\n```\n\n    word count: 82765 frequency_dictionary_en_82_765.txt \n    \n    mrs 12206596\n    restoration 12202668\n    convenience 12201623\n    returning 12197026\n    ralph 12190683\n    opposition 12183104\n    container 12181942\n    defendant 12169689\n    warner 12165874\n    confirmation 12157725\n\n\nWe read in the frequency file which consists of lines containig an english word and an absolute number of occurences collected from various texts.\n\n\n```python\nwith open('frequency_dictionary_en_82_765.txt') as freq:\n    freq = {word: int(cnt) for word, cnt in [line.split() for line in freq.read().split('\\n') if line]}\n```\n\n### Distribution of ten most and least common words\n\n\n```python\nsorted_freq_tuples = sorted([(w, c) for w,c in freq.items()], key=lambda t: -t[1])\n\nwords, counts = zip(*sorted_freq_tuples)\n\nplt.figure(figsize=(8,4), dpi=100)\nplt.subplot(121)\nplt.bar(words[:10], counts[:10])\nplt.xticks(rotation='vertical')\nplt.ylabel('word frequency')\nplt.subplot(122)\nplt.bar(words[-10:], counts[-10:])\nplt.xticks(rotation='vertical')\nplt.ylabel('word frequency')\nplt.tight_layout()\nplt.savefig('word-freqs.svg');\n```\n\n## Symmetric delete spelling correction ([SymSpell](https://towardsdatascience.com/symspell-vs-bk-tree-100x-faster-fuzzy-string-search-spell-checking-c4f10d80a078)) <a name=\"sym-spell\"/>\n\nSo now have everything needed for a corrector don't we?  \nAs we've seen earlier, although the dynamic programming version of the edit distance implementation is orders of magnitudes faster than the recursive implementation, it still takes several seconds to provide suggestions for a word since we're computing the distance for the word in question to every other word within the dictionary. This is obviously too inefficient and takes too long to be usable.  \n  \nLuckily there is a solution to this problem, an algorithm called SymSpell which was developed [Wolf Garbe](https://medium.com/@wolfgarbe), founder of SeekStorm (Search-as-a-Service), FAROO (P2P Search).\n\n### Idea: Reduce candidates to calc. edit distance for\n- pre-calculate possible strings by deleting at most n chars\n- store deletes in dictionary with candidate correction terms\n- calc. deletes for search term and look them up in dictionary\n- only calc. edit distance for terms stored as candidate corrections\n- sort by edit dist. and frequency\n\nObviously this approach does trade memory for performance, but as the benchmarks show, it's worth the tradeoff.\n\n\n```python\ndef splits(s: str) -> List[str]:\n    \"\"\" Helper function that given a string will return a list of tuples of possible splits of this word.\n        E.g. splits('abc') -> [('', 'abc'), ('a', 'bc'), ('ab', 'c'), ('abc', '')]\n    \"\"\"\n    return [(s[:i], s[i:]) for i in range(len(s)+1)]\n\ndef possible_deletions(s: str, max_edit_dist: int = 1) -> Set[str]:\n    \"\"\" Helper function that, given a string and a maximal edit dist. returns a set of strings where at most\n        max_edit_dist many characters have been deleted from the original string.\n        E.g. possible_deletions('abc') -> {'bc', 'ac', 'ab'}\n    \"\"\"\n    deletions = {s}\n    for i in range(max_edit_dist):\n        i_deletions = set()\n        for word in deletions:\n            split_words = splits(word)\n            i_deletions |= {a+b[1:] for a,b in split_words}\n        deletions |= i_deletions\n    return deletions\n```\n\n\n```python\nclass SpellingCorrector:\n    \"\"\" This is the class that will offer the correction suggestion functionality and is responsible\n        for preprocessing the word frequency input data and storing the resulting dictionary of partially\n        deleted words and their possible corrections.\n    \"\"\"\n    def __init__(self, filename, max_edit_dist=2):\n        self._dictionary = {}\n        self.max_edit_dist = max_edit_dist\n        self._init_dict_with_freq_file(filename)\n        \n    \n    def _create_dict_entry(self, word, cnt):\n        \"\"\" Helper method that takes a word and it's associated count. The word and it's corresponding frequency\n            is added to the dictionary. Then all possible deletions of the original word are generated. \n            Every partially deleted word is looked up in the internal dictionary.\n            If it's already present, we add the original word as a possible correction to the partial word.\n            If not, we create e new dictionary entry with the original word as possible correction and \n            a frequency of 0.\n        \"\"\"\n        self._dictionary[word] = ([], int(cnt))                # initialize with no corrections and freq.\n        deletes = possible_deletions(word, self.max_edit_dist) # generate all possible deletes within max_edit_dist \n        for part_word in deletes:\n            if part_word in self._dictionary:\n                self._dictionary[part_word][0].append(word)    # append orig. word as possible correction\n            else:\n                self._dictionary[part_word] = ([word], 0)      # create new entry with word as correction and freq\n                                                               # set to 0\n```\n\n\n```python\n@add_to_class(SpellingCorrector)\ndef _init_dict_with_freq_file(self, filename):\n    \"\"\" Helper method that reads in frequency file and \n        calls `_create_dict_entry()` on all word, freq. tuples\n    \"\"\"\n    with open(filename) as f:\n        word_cnt_tuples = [line.split() for line in f.read().split('\\n') if line]\n        for word, cnt in word_cnt_tuples:\n            self._create_dict_entry(word, cnt)\n```\n\n\n```python\nclass InvalidMaxEditDist(Exception):\n    pass\n\n@add_to_class(SpellingCorrector)\ndef _suggestion_candidates(self, word, max_edit_dist=2,\n                           edit_dist_func=damerau_levenshtein,\n                           verbose=False\n                          ):\n    \"\"\" Function that, given a word, a maximal edit distance < 0 and <= than the max_edit_dist specified at\n        instantiation and a distance function, returns a dictionary containing all possible corrections of the \n        given word as keys and tuples of their distance to the passed word and their absolute frequency.\n    \"\"\"\n    if not (0 < max_edit_dist <= self.max_edit_dist):\n        raise InvalidMaxEditDist(f\"max_edit_dist must be in range (0,{self.max_edit_dist}]\")\n    deletes = possible_deletions(word, max_edit_dist)\n    # dictionary containing corrections as keys and their corresponding distance \n    # to the passed word and freq as value \n    suggestion_dict = {}                  \n    # set where each word is stored for which the dist. has already been calculated\n    tried_corrections = set()\n    dist_func_counter = 0\n    for part_word in deletes:\n        # get all possible corrections that were precomputed during initialization\n        corrections = self._dictionary.get(part_word, ([], 0))[0]    \n        for correction in corrections:\n            # avoid unnecessary computations of distance func \n            if correction not in tried_corrections:\n                tried_corrections.add(correction)\n                dist = edit_dist_func(correction, word)\n                dist_func_counter += 1\n                if  dist <= max_edit_dist:\n                    # _dictionary[correction] tuple contains freq of word at second tuple position\n                    suggestion_dict[correction] = (dist, self._dictionary[correction][1])\n    if verbose:\n        print(f\"Called {edit_dist_func.__name__}() {dist_func_counter} many times.\")\n    return suggestion_dict\n\n```\n\n\n```python\n@add_to_class(SpellingCorrector)\ndef suggestions(self, word: str, verbose=False, **kwargs):\n    \"\"\" Function that given a word, generates possible corrections and orders them first by their distance\n        to the original string and second by their frequency.\n        If verbose is True the list of words with their corresponding distances and frequencies is returned,\n        otherwise just the sorted list.\n    \"\"\"\n    word = word.lower()\n    candidates = self._suggestion_candidates(word, verbose=verbose, **kwargs)\n    # sort candidates first by their dsitance to words, then by their frequency\n    sorted_candidates = sorted(candidates.items(), key=lambda tup: (tup[1][0], -tup[1][1]))\n    if verbose:\n        return sorted_candidates\n    return [word for word, _ in sorted_candidates]\n```\n\n\n```python\ncorr = SpellingCorrector('frequency_dictionary_en_82_765.txt', max_edit_dist=2)\n```\n\n### Small slice of the underlying dictionary structure  \n  \nAt the heart of the algorithm is the precomputing step where we take all words from our dictionary, delete at most `max_edit_dist` characters from them and then save the original string as a possible correction of the partially deleted one.  \nFollowing is a small slice of the dictionary that is the reusult of this precomputing step.\nAs we can also see, there is a lot of room for improvement memory efficiency wise (we save possible corrections even for already correctly spelled words), but since improving memory efficiency of datastructures in Python is a lost cause, we don't concern ourselves with this.\n\n\n```python\n[(k, (data[0][:3]+['...'], data[1])) for k, data in list(corr._dictionary.items())[:5]]\n```\n\n\n\n\n    [('the', (['the', 'other', 'they', '...'], 23135851162)),\n     ('e', (['the', 'be', 'are', '...'], 0)),\n     ('he', (['he', 'when', 'here', '...'], 842847219)),\n     ('th', (['the', 'that', 'this', '...'], 0)),\n     ('te', (['the', 'time', 'they', '...'], 0))]\n\n\n\n## So lets benchmark it! <a name=\"testing-sym-spell\"/>\n\n\n```python\ntime_corr = %timeit -q -o corr.suggestions(\"hellp\", max_edit_dist=2)\nf\"Best: {time_corr.best} s\"\ncorr.suggestions(\"hellp\", verbose=True)[:5]\n```\n\n\n\n\n    'Best: 0.005804701360175386 s'\n\n\n\n    Called damerau_levenshtein() 86 many times.\n\n\n\n\n\n    [('help', (1.0, 611054034)),\n     ('hello', (1.0, 32960381)),\n     ('hell', (1.0, 22791884)),\n     ('hells', (1.0, 480906)),\n     ('helle', (1.0, 143349))]\n\n\n\n### That's a speed increase of *several* orders of magnitude!  \n  \nAs we can see when passing `verbose=True` our distance function is only called **86 times** for the word 'hellp'. We have effectively reduced the number of candidates for which to compute the distance from ~80 thousand (size of dictionary) to 80.  \n\n## But is the corrector actually any good? <a name=\"corrector-accuracy\"/>\nWe verified that the SymSpell algorithm indeed allows us to do spelling correction blazingly fast, even in Python. \nBut can the simplistic language model of looking at words independantly from their context and simply ranking them by their distance and frequency produce useful results?  \n  \nIn order to assess this we need some test data containing words and their misspelled versions[D3].\n### Misspell data  \n<br>\nWe're using spelling error data formatted by [Roger Mitton](http://www.dcs.bbk.ac.uk/~ROGER/) to test the corrector.  \n`aspell.dat`\n> The aspell file contains 531 misspellings of 450 words. It is derived from one assembled by Atkinson [(click here)](http://aspell.net/test/batch0.tab) for testing the [GNU Aspell spellchecker](http://aspell.net/). \n\n`wikipedia.dat`\n> The wikipedia file contains 2,455 misspellings of 1,922 words. It is a list of misspellings made by Wikipedia editors [(click here)](http://en.wikipedia.org/wiki/Wikipedia:List_of_common_misspellings). \n\n\n```python\n!echo \"Aspell file:\\n\"\n!head aspell.dat\n!echo \"\\nWikipedia file:\\n\"\n!head wikipedia.dat\n```\n\n    Aspell file:\n    \n    $Nevada\n    nevade\n    $Presbyterian\n    presbyterian\n    $RSX\n    rsx\n    $Stephen\n    Steffen\n    $Susan\n    susan\n    \n    Wikipedia file:\n    \n    $Apennines\n    Apenines\n    Appenines\n    $Athenian\n    Athenean\n    $Athenians\n    Atheneans\n    $Bernoulli\n    Bernouilli\n    $Blitzkrieg\n\n\n\n```python\ndef parse_misspell_data(filename):\n    \"\"\" Methods that takes a misspel data filename and parses the data into a dictionary that contains \n        correct words as keys and a list of misspelled version as values.\n        The method expects a file with exactly one word per line. Words that are prefixed by $ are correctly\n        spelled and all following words until the next $ are misspelled versions.\n    \"\"\"\n    with open(filename) as f:\n        lines = [line for line in f.read().split('\\n') if line]\n        misspell_data = {}\n        misspelled_words_cnt = 0\n        cursor = ''\n        for line in lines:\n            if line.startswith('$'):\n                cursor = line[1:]\n                misspell_data[cursor] = []\n                continue\n            misspell_data[cursor].append(line)\n            misspelled_words_cnt += 1\n        return misspell_data, misspelled_words_cnt\n```\n\nIn order to test and compare our correcter on the dataset we need some way of measuring it's performance. The most straightforward way is to simply take the dataset and generate for every misspelled word the correction suggestions. Then we look up if the correct word is within the first `consider_corrections_count` corrections and increment a score counter if that is the case. This serves the purpose of emulating the `Did you mean: [list of words]` feature that most (non-auto) correctors offer. \n\n\n```python\ndef score(misspell_data: Dict[str, List[str]] ,\n          corrector_func: Callable[[str], Iterable[str]] ,\n          consider_corrections_count=5):\n    \"\"\" Method that computes a score for a given misspell dataset, a corrector function, and \n        the consider_corrections_count which specifies how many corrections should be considered when\n        determining the score.\n    \"\"\"\n    score = 0\n    for word, misspells in misspell_data.items():\n        for ms_word in misspells:\n            corrections = corrector_func(ms_word)\n            score += 1 if word in corrections[:consider_corrections_count] else 0\n    return score\n```\n\n\n```python\ndef test_with_spell_data_and_create_graph(filename, corrector, max_edit_dist=2, max_lookup=5, verbose=False):\n    \"\"\" Small helper method that simply takes the filename of misspell data with the format specified\n        in `parse_misspell_data`, computes the relative score for different edit distances and maximal lookups\n        and plots the results.\n    \"\"\"\n    misspell_data, misspelled_words_cnt = parse_misspell_data(filename)\n    plot_cols = max_edit_dist\n    plt.figure(figsize=(4*plot_cols, 4), dpi=100)\n    for edit_dist in range(1, max_edit_dist+1):\n        corrector_fixed_dist = partial(corrector, max_edit_dist=edit_dist)\n        score_data = [score(misspell_data, corrector_fixed_dist, lookup)/misspelled_words_cnt \n                      for lookup in range(1, max_lookup+1)]\n        if verbose:\n            print(f\"Score data for {filename} with max edit dist {edit_dist}: {score_data}\")\n        plt.subplot(1, plot_cols, edit_dist);\n        plt.gca().set_ylim([0, 1.0]);\n        plt.bar(range(1, max_lookup+1), score_data);\n        plt.title(f\"Max edit dist: {edit_dist}\");\n        plt.ylabel('score in %');\n        plt.xlabel('max lookup');\n    plt.tight_layout();\n    plt.savefig(f'{filename}-score-graph.svg');\n```\n\n\n```python\ntest_with_spell_data_and_create_graph('aspell.dat', corr.suggestions, max_lookup=10, verbose=True);\ntest_with_spell_data_and_create_graph('wikipedia.dat', corr.suggestions, max_lookup=10, verbose=True);\n```\n\nLooking at the results from benchmarking the corrector it is suprisingly effective. On the aspell data set the correct word is contained within in the 5 highest ranked suggestions nearly 72% of the time (using a max edit distance of 2). Increasing the maximal lookup to 10 items increases the accuracy to ~73.3%.\nEven better are the results on the wikipedia dataset where the accuracy is 88.9% for a lookup of 5 items. Increasing the lookup to 10 items results in an accuracy of 90.2%.\nThe difference in the datasets are due to the aspell dataset containing more serious spelling mistakes than the wikipedia dataset.\n\n## Spelling correction: Conclusion <a name=\"correcting-conclusion\"/>\n\nUtilizing the SymSpell algorithm and a carefully composed word frequency file it is possible to achieve both accurate and performant spelling correction.  \nThe accuracy of the correction could be further increased by weighing the distance between words and their respective frequencys differently. When ranking the correction suggestions it might bebeneficial to rank a word, that has a distance of 2 from the originial and a very high freqeuency, higher than a word that has a distance of 1 but is only very rarely used within the language.  \nAnother measure that would likely increase performance is using n-gram (contigous sequence of n words) data, in order to consider the context that words appear in.  \nThe run time and memory efficiency could be further optimized by using a fast compiled language and using datastructures that are able to store strings efficiently, a trie or directed acyclic word graph could be used.\n\n# References  <a name=\"references\"/>\n\n1. Bentley, John (1985): programming pearls, A spelling checker. In: Communications of the ACM, Volume 28 Number 5\n2. Garbe, Wolf (2012): 1000x Faster Spelling Correction algorithm, Wolf, [online] [medium.com](https://medium.com/@wolfgarbe/1000x-faster-spelling-correction-algorithm-2012-8701fcd87a5f) [accessed 16.06.2018]\n3. McIlroy, Malcolm Douglas (1971-1986): A research UNIX Reader: Annotated Excerpts from the Programmer\u2019s Manual, [online] [cs.dartmouth.edu](http://www.cs.dartmouth.edu/~doug/reader.pdf) [accessed 12.06.2018]\n4. Norvig, Peter (2007-2016): How to Write a Spelling Corrector, [online] [norvig.com](http://norvig.com/spell-correct.html) [accessed 16.06.2018]  \n\n## Data sources <a name=\"data-sources\"/>\n1. `big.txt`, Peter Norvig, [norvig.com](http://norvig.com/big.txt), [accessed 16.06.2018]\n2. `frequency_dictionary_en_82_765.txt`, Wolf Garbe, [github.com](https://github.com/wolfgarbe/SymSpell/blob/master/SymSpell/frequency_dictionary_en_82_765.txt), [accessed 16.06.2018]\n3. `aspell.dat` and `wikipedia.dat`, Roger Mitton, [dcs.bbk.ac.uk](http://www.dcs.bbk.ac.uk/~ROGER/corpora.html), [accessed 16.06.2018]\n\n## Libraries <a name=\"libraries\"/>\n- [marisa_trie](https://github.com/pytries/marisa-trie) (MIT license)  \n- [matplotlib](https://github.com/matplotlib/matplotlib)  \n- [memory-profiler](https://github.com/pythonprofilers/memory_profiler) (BSD-new license)\n- [numpy](https://github.com/numpy/numpy) (BSD-new license)  \n- [pympler](https://github.com/pympler/pympler) (Apache-2.0)\n\n\n```python\n\n```\n", "meta": {"hexsha": "6206b3cea9b5c6843887c04d90a43800238c167e", "size": 336677, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "spell-checking-correction.ipynb", "max_stars_repo_name": "robinhundt/programming-pearls-spelling-checker", "max_stars_repo_head_hexsha": "7c04d1f1d186f104366c89c8e06f36d69d052a52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spell-checking-correction.ipynb", "max_issues_repo_name": "robinhundt/programming-pearls-spelling-checker", "max_issues_repo_head_hexsha": "7c04d1f1d186f104366c89c8e06f36d69d052a52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spell-checking-correction.ipynb", "max_forks_repo_name": "robinhundt/programming-pearls-spelling-checker", "max_forks_repo_head_hexsha": "7c04d1f1d186f104366c89c8e06f36d69d052a52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 157.6203183521, "max_line_length": 51636, "alphanum_fraction": 0.8818006576, "converted": true, "num_tokens": 11893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3208213008246071, "lm_q2_score": 0.14608725262486594, "lm_q1q2_score": 0.046867902421002486}}
{"text": "<p style=\"font-size:40px;text-align:center;color:yellow\"> <b>Taxi demand prediction in New York City</b> </p>\n\n\n\n```python\n# \n```\n\n# - Objectives \n- Our end-user is an `Taxi-Driver`, who is probably going to use this on his smartphone.\n- So our primary Objective is to `Predict the number of pickups as accurately as possible for aech region in next 10mins (in 10mins interval)`.\n- So according to the objective we need to divide the NYC into various regions. \n- For our model, at any time input will be :\n> 1) Current location of the taxi, hence we will get the region (pre-defined by us) in which the TaxiDriver is present. <br>\n> 2) Current time. So for eg. say we get current time as 2:00 pm, then we need to do the estimation for next 10 min interval i.e 2:00 - 2:10 pm\n- So our output would be - 'output is specified as our primary objective'\n\n# - Constraints\n1) Latency : We have decent Latency requirements. It is not as low as in miliseconds as required for internet applicarions, but it should not be as high as in minutes. Ideal waiting time would be some seconds, 15-45 seconds as per me. <br>\n2) Intrepretability : Is not important, as long as you provide with correct predictions no TaxiDriver is keen on knowing 'on what basis we obtained that number'. It is not as in medical applications where doctors need to know thw reasons behind the predictions. <br>\n3) Relative Errors : Say in some A case we predicted 'no of pickups' as 100 and in reality there were 102. So our absolute error is 2. Now consider case B where we predicted 10 and there were 8. So here the absolute error is 2. Now in both the cases the absolute error is 2. But the same error makes lage difference in case B as compared to case A.\n>So here we wil introduce relative error, which is percentage error. Then the relative percentage error for Case A is 2% but that for case B is 20%. So if we say that our relative percentage error is about 10%, then the TaxiDriver will know how to percieve the predictions provided by us. For eg.if the prediction says 250 the TaxiDriver will percieve it as between 225-275.\n\n# - Data Information\n\n<p>\nGe the data from : http://www.nyc.gov/html/tlc/html/about/trip_record_data.shtml \n(2016 data)\nThe data used in the attached datasets were collected and provided to the NYC Taxi and Limousine Commission (TLC) \n</p>\n\n* ## Information on taxis:\n\n<h5> Yellow Taxi: Yellow Medallion Taxicabs</h5>\n<p> These are the famous NYC yellow taxis that provide transportation exclusively through street-hails. The number of taxicabs is limited by a finite number of medallions issued by the TLC. You access this mode of transportation by standing in the street and hailing an available taxi with your hand. The pickups are not pre-arranged.</p>\n\n<h5> For Hire Vehicles (FHVs) </h5>\n<p> FHV transportation is accessed by a pre-arrangement with a dispatcher or limo company. These FHVs are not permitted to pick up passengers via street hails, as those rides are not considered pre-arranged. </p>\n\n<h5> Green Taxi: Street Hail Livery (SHL) </h5>\n<p>  The SHL program will allow livery vehicle owners to license and outfit their vehicles with green borough taxi branding, meters, credit card machines, and ultimately the right to accept street hails in addition to pre-arranged rides. </p>\n<p> Credits: Quora</p>\n\n<h5>Footnote:</h5>\nIn the given notebook we are considering only the yellow taxis for the time period between Jan - Mar 2015 & Jan - Mar 2016\n\n# - Data Collection\nWe Have collected all yellow taxi trips data from jan-2015 to dec-2016(Will be using only 2015 data)\n<table border=\"1\">\n<tr>\n<th> file name </th>\n<th> file name size</th>\n<th> number of records </th>\n<th> number of features </th>\n</tr>\n<tr>\n<td> yellow_tripdata_2016-01 </td>\n<td> 1. 59G </td>\n<td> 10906858 </td>\n<td> 19 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2016-02 </td>\n<td> 1. 66G </td>\n<td> 11382049 </td>\n<td> 19 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2016-03 </td>\n<td> 1. 78G </td>\n<td> 12210952 </td>\n<td> 19 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2016-04 </td>\n<td> 1. 74G </td>\n<td> 11934338 </td>\n<td> 19 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2016-05 </td>\n<td> 1. 73G </td>\n<td> 11836853 </td>\n<td> 19 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2016-06 </td>\n<td> 1. 62G </td>\n<td> 11135470 </td>\n<td> 19 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2016-07 </td>\n<td> 884Mb </td>\n<td> 10294080 </td>\n<td> 17 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2016-08 </td>\n<td> 854Mb </td>\n<td> 9942263 </td>\n<td> 17 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2016-09 </td>\n<td> 870Mb </td>\n<td> 10116018 </td>\n<td> 17 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2016-10 </td>\n<td> 933Mb </td>\n<td> 10854626 </td>\n<td> 17 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2016-11 </td>\n<td> 868Mb </td>\n<td> 10102128 </td>\n<td> 17 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2016-12 </td>\n<td> 897Mb </td>\n<td> 10449408 </td>\n<td> 17 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2015-01 </td>\n<td> 1.84Gb </td>\n<td> 12748986 </td>\n<td> 19 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2015-02 </td>\n<td> 1.81Gb </td>\n<td> 12450521 </td>\n<td> 19 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2015-03 </td>\n<td> 1.94Gb </td>\n<td> 13351609 </td>\n<td> 19 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2015-04 </td>\n<td> 1.90Gb </td>\n<td> 13071789 </td>\n<td> 19 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2015-05 </td>\n<td> 1.91Gb </td>\n<td> 13158262 </td>\n<td> 19 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2015-06 </td>\n<td> 1.79Gb </td>\n<td> 12324935 </td>\n<td> 19 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2015-07 </td>\n<td> 1.68Gb </td>\n<td> 11562783 </td>\n<td> 19 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2015-08 </td>\n<td> 1.62Gb </td>\n<td> 11130304 </td>\n<td> 19 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2015-09 </td>\n<td> 1.63Gb </td>\n<td> 11225063 </td>\n<td> 19 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2015-10 </td>\n<td> 1.79Gb </td>\n<td> 12315488 </td>\n<td> 19 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2015-11 </td>\n<td> 1.65Gb </td>\n<td> 11312676 </td>\n<td> 19 </td>\n</tr>\n<tr>\n<td> yellow_tripdata_2015-12 </td>\n<td> 1.67Gb </td>\n<td> 11460573 </td>\n<td> 19 </td>\n</tr>\n</table>\n\n## `As you can see the size of each csv is tremendous between 1.5-2gb. So using Pandas is not an option as such an large amount of data will not fit in our RAM (2*4 = 8 gb). Hence we are expoiting other libraries. But in our case we can load 8gb data into Ram as we have 24gb of it. So basically we can use pandas`\n\n\n```python\nimport os\nimport math\nimport time\nimport pickle\nfrom datetime import datetime\n\nimport scipy\nimport numpy as np\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pylab as plt\nfrom matplotlib import rcParams\n%matplotlib inline\n# matplotlib.use('nbagg')\nimport seaborn as sns\n\nimport gpxpy.geo\nimport dask.dataframe as dd\nimport folium\n\nimport xgboost as xgb\nfrom sklearn.metrics import mean_absolute_percentage_error\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.cluster import MiniBatchKMeans, KMeans\nfrom sklearn.linear_model import LinearRegression\n\n# mingw_path = 'C:\\\\Program Files (x86)\\\\mingw-w64\\\\i686-8.1.0-posix-dwarf-rt_v6-rev0\\\\mingw32\\\\bin'\n# os.environ['PATH'] = mingw_path + ';' + os.environ['PATH']\n```\n\n\n```python\n#Looking at the features\n# dask dataframe  : # https://github.com/dask/dask-tutorial/blob/master/07_dataframe.ipynb\nmonth = dd.read_csv('data/raw/yellow_tripdata_2016-03.csv')\nprint(month.columns)\n```\n\n    Index(['VendorID', 'tpep_pickup_datetime', 'tpep_dropoff_datetime',\n           'passenger_count', 'trip_distance', 'pickup_longitude',\n           'pickup_latitude', 'RatecodeID', 'store_and_fwd_flag',\n           'dropoff_longitude', 'dropoff_latitude', 'payment_type', 'fare_amount',\n           'extra', 'mta_tax', 'tip_amount', 'tolls_amount',\n           'improvement_surcharge', 'total_amount'],\n          dtype='object')\n\n\n\n```python\n# However unlike Pandas, operations on dask.dataframes don't trigger immediate computation, \n# instead they add key-value pairs to an underlying Dask graph. Recall that in the diagram below, \n# circles are operations and rectangles are results.\n\n# to see the visulaization you need to install graphviz\n# pip3 install graphviz if this doesnt work please check the install_graphviz.jpg in the drive\n\n# os.environ[\"PATH\"] += os.pathsep + 'C:\\\\Users\\\\magic\\\\anaconda3\\\\envs\\\\ml1\\\\Library\\\\bin\\\\graphviz' # run this if graphviz shows error\nmonth.visualize(filename='images/viz/one.svg');\n```\n\n\n```python\nmonth.fare_amount.sum().visualize(filename='images/viz/two.svg');\n```\n\n* ## Features in the dataset:\n<table border=\"1\">\n\t<tr>\n\t\t<th>Field Name</th>\n\t\t<th>Description</th>\n\t</tr>\n\t<tr>\n\t\t<td>VendorID</td>\n\t\t<td>\n\t\tA code indicating the TPEP provider that provided the record.\n\t\t<ol>\n\t\t\t<li>Creative Mobile Technologies</li>\n\t\t\t<li>VeriFone Inc.</li>\n\t\t</ol>\n\t\t</td>\n\t</tr>\n\t<tr>\n\t\t<td>tpep_pickup_datetime</td>\n\t\t<td>The date and time when the meter was engaged.</td>\n\t</tr>\n\t<tr>\n\t\t<td>tpep_dropoff_datetime</td>\n\t\t<td>The date and time when the meter was disengaged.</td>\n\t</tr>\n\t<tr>\n\t\t<td>Passenger_count</td>\n\t\t<td>The number of passengers in the vehicle. This is a driver-entered value.</td>\n\t</tr>\n\t<tr>\n\t\t<td>Trip_distance</td>\n\t\t<td>The elapsed trip distance in miles reported by the taximeter.</td>\n\t</tr>\n\t<tr>\n\t\t<td>Pickup_longitude</td>\n\t\t<td>Longitude where the meter was engaged.</td>\n\t</tr>\n\t<tr>\n\t\t<td>Pickup_latitude</td>\n\t\t<td>Latitude where the meter was engaged.</td>\n\t</tr>\n\t<tr>\n\t\t<td>RateCodeID</td>\n\t\t<td>The final rate code in effect at the end of the trip.\n\t\t<ol>\n\t\t\t<li> Standard rate </li>\n\t\t\t<li> JFK </li>\n\t\t\t<li> Newark </li>\n\t\t\t<li> Nassau or Westchester</li>\n\t\t\t<li> Negotiated fare </li>\n\t\t\t<li> Group ride</li>\n\t\t</ol>\n\t\t</td>\n\t</tr>\n\t<tr>\n\t\t<td>Store_and_fwd_flag</td>\n\t\t<td>This flag indicates whether the trip record was held in vehicle memory before sending to the vendor,<br\\> aka \u201cstore and forward,\u201d because the vehicle did not have a connection to the server.\n\t\t<br\\>Y= store and forward trip\n\t\t<br\\>N= not a store and forward trip\n\t\t</td>\n\t</tr>\n\t<tr>\n\t\t<td>Dropoff_longitude</td>\n\t\t<td>Longitude where the meter was disengaged.</td>\n\t</tr>\n\t<tr>\n\t\t<td>Dropoff_ latitude</td>\n\t\t<td>Latitude where the meter was disengaged.</td>\n\t</tr>\n\t<tr>\n\t\t<td>Payment_type</td>\n\t\t<td>A numeric code signifying how the passenger paid for the trip.\n\t\t<ol>\n\t\t\t<li> Credit card </li>\n\t\t\t<li> Cash </li>\n\t\t\t<li> No charge </li>\n\t\t\t<li> Dispute</li>\n\t\t\t<li> Unknown </li>\n\t\t\t<li> Voided trip</li>\n\t\t</ol>\n\t\t</td>\n\t</tr>\n\t<tr>\n\t\t<td>Fare_amount</td>\n\t\t<td>The time-and-distance fare calculated by the meter.</td>\n\t</tr>\n\t<tr>\n\t\t<td>Extra</td>\n\t\t<td>Miscellaneous extras and surcharges. Currently, this only includes. the $0.50 and $1 rush hour and overnight charges.</td>\n\t</tr>\n\t<tr>\n\t\t<td>MTA_tax</td>\n\t\t<td>0.50 MTA tax that is automatically triggered based on the metered rate in use.</td>\n\t</tr>\n\t<tr>\n\t\t<td>Improvement_surcharge</td>\n\t\t<td>0.30 improvement surcharge assessed trips at the flag drop. the improvement surcharge began being levied in 2015.</td>\n\t</tr>\n\t<tr>\n\t\t<td>Tip_amount</td>\n\t\t<td>Tip amount \u2013 This field is automatically populated for credit card tips.Cash tips are not included.</td>\n\t</tr>\n\t<tr>\n\t\t<td>Tolls_amount</td>\n\t\t<td>Total amount of all tolls paid in trip.</td>\n\t</tr>\n\t<tr>\n\t\t<td>Total_amount</td>\n\t\t<td>The total amount charged to passengers. Does not include cash tips.</td>\n\t</tr>\n</table>\n\n # - ML Problem Formulation\n<p><b> Time-series forecasting and Regression</b></p>\n<br>\n-<i> To find number of pickups, given location cordinates(latitude and longitude) and time, in the query reigion and surrounding regions.</i>\n<p> \nTo solve the above we would be using data collected in Jan - Mar 2015 to predict the pickups in Jan - Mar 2016.\n</p>\n\n# - Performance metrics\n1. Mean Absolute percentage error.\n2. Mean Squared error.\n\n\n----\n\n# - Data Cleaning\n\nIn this section we will be doing univariate analysis and removing outlier/illegitimate values which may be caused due to some error\n\n\n```python\nmonth.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>VendorID</th>\n      <th>tpep_pickup_datetime</th>\n      <th>tpep_dropoff_datetime</th>\n      <th>passenger_count</th>\n      <th>trip_distance</th>\n      <th>pickup_longitude</th>\n      <th>pickup_latitude</th>\n      <th>RatecodeID</th>\n      <th>store_and_fwd_flag</th>\n      <th>dropoff_longitude</th>\n      <th>dropoff_latitude</th>\n      <th>payment_type</th>\n      <th>fare_amount</th>\n      <th>extra</th>\n      <th>mta_tax</th>\n      <th>tip_amount</th>\n      <th>tolls_amount</th>\n      <th>improvement_surcharge</th>\n      <th>total_amount</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:07:55</td>\n      <td>1</td>\n      <td>2.50</td>\n      <td>-73.976746</td>\n      <td>40.765152</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-74.004265</td>\n      <td>40.746128</td>\n      <td>1</td>\n      <td>9.0</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>2.05</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>12.35</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:11:06</td>\n      <td>1</td>\n      <td>2.90</td>\n      <td>-73.983482</td>\n      <td>40.767925</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-74.005943</td>\n      <td>40.733166</td>\n      <td>1</td>\n      <td>11.0</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>3.05</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>15.35</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:31:06</td>\n      <td>2</td>\n      <td>19.98</td>\n      <td>-73.782021</td>\n      <td>40.644810</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-73.974541</td>\n      <td>40.675770</td>\n      <td>1</td>\n      <td>54.5</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>8.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>63.80</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>2</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>3</td>\n      <td>10.78</td>\n      <td>-73.863419</td>\n      <td>40.769814</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-73.969650</td>\n      <td>40.757767</td>\n      <td>1</td>\n      <td>31.5</td>\n      <td>0.0</td>\n      <td>0.5</td>\n      <td>3.78</td>\n      <td>5.54</td>\n      <td>0.3</td>\n      <td>41.62</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>2</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>5</td>\n      <td>30.43</td>\n      <td>-73.971741</td>\n      <td>40.792183</td>\n      <td>3</td>\n      <td>N</td>\n      <td>-74.177170</td>\n      <td>40.695053</td>\n      <td>1</td>\n      <td>98.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.00</td>\n      <td>15.50</td>\n      <td>0.3</td>\n      <td>113.80</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nlen(month)\n```\n\n\n\n\n    12210952\n\n\n\n\n```python\n# other way\nmonth.shape[0].compute(),month.shape[1]\n```\n\n\n\n\n    (12210952, 19)\n\n\n\n### 1. Pickup Latitude and Pickup Longitude\n\nIt is inferred from the source https://www.flickr.com/places/info/2459115 that New York is bounded by the location cordinates(lat,long) - (40.5774, -74.15) & (40.9176,-73.7004) so hence any cordinates not within these cordinates are not considered by us as we are only concerned with pickups which originate within New York.\n\n\n```python\n# This is the dataframe without pickup outliers\nmonth[month['pickup_longitude'].between(-74.15,-73.7004) | month['pickup_latitude'].between(40.5774,40.9176)].head(10)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>VendorID</th>\n      <th>tpep_pickup_datetime</th>\n      <th>tpep_dropoff_datetime</th>\n      <th>passenger_count</th>\n      <th>trip_distance</th>\n      <th>pickup_longitude</th>\n      <th>pickup_latitude</th>\n      <th>RatecodeID</th>\n      <th>store_and_fwd_flag</th>\n      <th>dropoff_longitude</th>\n      <th>dropoff_latitude</th>\n      <th>payment_type</th>\n      <th>fare_amount</th>\n      <th>extra</th>\n      <th>mta_tax</th>\n      <th>tip_amount</th>\n      <th>tolls_amount</th>\n      <th>improvement_surcharge</th>\n      <th>total_amount</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:07:55</td>\n      <td>1</td>\n      <td>2.50</td>\n      <td>-73.976746</td>\n      <td>40.765152</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-74.004265</td>\n      <td>40.746128</td>\n      <td>1</td>\n      <td>9.0</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>2.05</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>12.35</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:11:06</td>\n      <td>1</td>\n      <td>2.90</td>\n      <td>-73.983482</td>\n      <td>40.767925</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-74.005943</td>\n      <td>40.733166</td>\n      <td>1</td>\n      <td>11.0</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>3.05</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>15.35</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:31:06</td>\n      <td>2</td>\n      <td>19.98</td>\n      <td>-73.782021</td>\n      <td>40.644810</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-73.974541</td>\n      <td>40.675770</td>\n      <td>1</td>\n      <td>54.5</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>8.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>63.80</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>2</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>3</td>\n      <td>10.78</td>\n      <td>-73.863419</td>\n      <td>40.769814</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-73.969650</td>\n      <td>40.757767</td>\n      <td>1</td>\n      <td>31.5</td>\n      <td>0.0</td>\n      <td>0.5</td>\n      <td>3.78</td>\n      <td>5.54</td>\n      <td>0.3</td>\n      <td>41.62</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>2</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>5</td>\n      <td>30.43</td>\n      <td>-73.971741</td>\n      <td>40.792183</td>\n      <td>3</td>\n      <td>N</td>\n      <td>-74.177170</td>\n      <td>40.695053</td>\n      <td>1</td>\n      <td>98.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.00</td>\n      <td>15.50</td>\n      <td>0.3</td>\n      <td>113.80</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>2</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>5</td>\n      <td>5.92</td>\n      <td>-74.017197</td>\n      <td>40.705383</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-73.978073</td>\n      <td>40.755787</td>\n      <td>1</td>\n      <td>23.5</td>\n      <td>1.0</td>\n      <td>0.5</td>\n      <td>5.06</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>30.36</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>2</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>6</td>\n      <td>5.72</td>\n      <td>-73.994583</td>\n      <td>40.727848</td>\n      <td>1</td>\n      <td>N</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>2</td>\n      <td>23.0</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>24.30</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>1</td>\n      <td>2016-03-01 00:00:01</td>\n      <td>2016-03-01 00:16:04</td>\n      <td>1</td>\n      <td>6.20</td>\n      <td>-73.788773</td>\n      <td>40.647758</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-73.829208</td>\n      <td>40.712345</td>\n      <td>3</td>\n      <td>20.5</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>21.80</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>1</td>\n      <td>2016-03-01 00:00:01</td>\n      <td>2016-03-01 00:05:00</td>\n      <td>1</td>\n      <td>0.70</td>\n      <td>-73.958221</td>\n      <td>40.764641</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-73.967896</td>\n      <td>40.762901</td>\n      <td>1</td>\n      <td>5.5</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>8.80</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>2</td>\n      <td>2016-03-01 00:00:01</td>\n      <td>2016-03-01 00:24:06</td>\n      <td>3</td>\n      <td>7.18</td>\n      <td>-73.985779</td>\n      <td>40.741192</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-73.946350</td>\n      <td>40.797878</td>\n      <td>1</td>\n      <td>23.5</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>3.20</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>28.00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nmonth[month['pickup_longitude'].between(-74.15,-73.7004) | month['pickup_latitude'].between(40.5774,40.9176)].shape[0].compute()\n```\n\n\n\n\n    12028245\n\n\n\n#### ` Here i am trying to avoid to create temporary variables so as to not store junk in ram, as the dat we are playing with is tremendiously large in size`\n\n\n```python\n# This is the Dataframe with the outliers\nmonth[~month['pickup_longitude'].between(-74.15,-73.7004) | ~month['pickup_latitude'].between(40.5774,40.9176)].head(10)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>VendorID</th>\n      <th>tpep_pickup_datetime</th>\n      <th>tpep_dropoff_datetime</th>\n      <th>passenger_count</th>\n      <th>trip_distance</th>\n      <th>pickup_longitude</th>\n      <th>pickup_latitude</th>\n      <th>RatecodeID</th>\n      <th>store_and_fwd_flag</th>\n      <th>dropoff_longitude</th>\n      <th>dropoff_latitude</th>\n      <th>payment_type</th>\n      <th>fare_amount</th>\n      <th>extra</th>\n      <th>mta_tax</th>\n      <th>tip_amount</th>\n      <th>tolls_amount</th>\n      <th>improvement_surcharge</th>\n      <th>total_amount</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>95</th>\n      <td>2</td>\n      <td>2016-03-01 00:00:31</td>\n      <td>2016-03-01 00:09:06</td>\n      <td>1</td>\n      <td>0.73</td>\n      <td>-74.651306</td>\n      <td>40.609261</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-74.651306</td>\n      <td>40.609261</td>\n      <td>1</td>\n      <td>6.5</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>8.80</td>\n    </tr>\n    <tr>\n      <th>116</th>\n      <td>2</td>\n      <td>2016-03-01 00:00:41</td>\n      <td>2016-03-01 00:11:39</td>\n      <td>1</td>\n      <td>2.91</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1</td>\n      <td>N</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1</td>\n      <td>12.0</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>3.32</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>16.62</td>\n    </tr>\n    <tr>\n      <th>365</th>\n      <td>2</td>\n      <td>2016-03-10 07:08:29</td>\n      <td>2016-03-10 07:32:55</td>\n      <td>2</td>\n      <td>8.81</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1</td>\n      <td>N</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1</td>\n      <td>28.0</td>\n      <td>0.0</td>\n      <td>0.5</td>\n      <td>10.30</td>\n      <td>5.54</td>\n      <td>0.3</td>\n      <td>44.64</td>\n    </tr>\n    <tr>\n      <th>434</th>\n      <td>2</td>\n      <td>2016-03-10 07:08:57</td>\n      <td>2016-03-10 07:09:03</td>\n      <td>6</td>\n      <td>0.02</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-73.972359</td>\n      <td>40.794121</td>\n      <td>2</td>\n      <td>2.5</td>\n      <td>0.0</td>\n      <td>0.5</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>3.30</td>\n    </tr>\n    <tr>\n      <th>478</th>\n      <td>2</td>\n      <td>2016-03-10 07:09:15</td>\n      <td>2016-03-10 07:40:06</td>\n      <td>1</td>\n      <td>18.05</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>3</td>\n      <td>N</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1</td>\n      <td>66.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>16.36</td>\n      <td>15.50</td>\n      <td>0.3</td>\n      <td>98.16</td>\n    </tr>\n    <tr>\n      <th>491</th>\n      <td>2</td>\n      <td>2016-03-10 07:09:20</td>\n      <td>2016-03-10 07:17:52</td>\n      <td>5</td>\n      <td>1.73</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1</td>\n      <td>N</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1</td>\n      <td>8.0</td>\n      <td>0.0</td>\n      <td>0.5</td>\n      <td>1.76</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>10.56</td>\n    </tr>\n    <tr>\n      <th>646</th>\n      <td>2</td>\n      <td>2016-03-10 07:10:28</td>\n      <td>2016-03-10 07:21:24</td>\n      <td>1</td>\n      <td>2.86</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1</td>\n      <td>N</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1</td>\n      <td>11.0</td>\n      <td>0.0</td>\n      <td>0.5</td>\n      <td>2.36</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>14.16</td>\n    </tr>\n    <tr>\n      <th>866</th>\n      <td>2</td>\n      <td>2016-03-10 07:11:51</td>\n      <td>2016-03-10 07:17:30</td>\n      <td>1</td>\n      <td>0.91</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1</td>\n      <td>N</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1</td>\n      <td>6.0</td>\n      <td>0.0</td>\n      <td>0.5</td>\n      <td>2.04</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>8.84</td>\n    </tr>\n    <tr>\n      <th>984</th>\n      <td>2</td>\n      <td>2016-03-10 07:12:35</td>\n      <td>2016-03-10 07:24:55</td>\n      <td>1</td>\n      <td>1.71</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1</td>\n      <td>N</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>2</td>\n      <td>10.0</td>\n      <td>0.0</td>\n      <td>0.5</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>10.80</td>\n    </tr>\n    <tr>\n      <th>1407</th>\n      <td>2</td>\n      <td>2016-03-10 07:15:16</td>\n      <td>2016-03-10 07:31:35</td>\n      <td>2</td>\n      <td>2.89</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1</td>\n      <td>N</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>2</td>\n      <td>13.5</td>\n      <td>0.0</td>\n      <td>0.5</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>14.30</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nmonth[~month['pickup_longitude'].between(-74.15,-73.7004) | ~month['pickup_latitude'].between(40.5774,40.9176)].shape[0].compute()\n```\n\n\n\n\n    185746\n\n\n\n\n```python\n# Summing up the length of dataframe without outliers and an dataframe of outliers. This should equal to 12210952, the original shape of the complete dataframe\n12028245 + 185746\n```\n\n\n\n\n    12213991\n\n\n\n\n```python\n12213991-12210952\n```\n\n\n\n\n    3039\n\n\n\n\n```python\nmonth[(~month['pickup_longitude'].between(-74.15,-73.7004) & ~month['pickup_latitude'].between(40.5774,40.9176))==(month['pickup_longitude'].between(-74.15,-73.7004) & month['pickup_latitude'].between(40.5774,40.9176))].shape[0].compute()\n```\n\n\n\n\n    3039\n\n\n\n\n```python\nmonth[((~month['pickup_longitude'].between(-74.15,-73.7004)) & (~month['pickup_latitude'].between(40.5774,40.9176)))==(month['pickup_longitude'].between(-74.15,-73.7004) & month['pickup_latitude'].between(40.5774,40.9176))].head(20)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>VendorID</th>\n      <th>tpep_pickup_datetime</th>\n      <th>tpep_dropoff_datetime</th>\n      <th>passenger_count</th>\n      <th>trip_distance</th>\n      <th>pickup_longitude</th>\n      <th>pickup_latitude</th>\n      <th>RatecodeID</th>\n      <th>store_and_fwd_flag</th>\n      <th>dropoff_longitude</th>\n      <th>dropoff_latitude</th>\n      <th>payment_type</th>\n      <th>fare_amount</th>\n      <th>extra</th>\n      <th>mta_tax</th>\n      <th>tip_amount</th>\n      <th>tolls_amount</th>\n      <th>improvement_surcharge</th>\n      <th>total_amount</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>95</th>\n      <td>2</td>\n      <td>2016-03-01 00:00:31</td>\n      <td>2016-03-01 00:09:06</td>\n      <td>1</td>\n      <td>0.73</td>\n      <td>-74.651306</td>\n      <td>40.609261</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-74.651306</td>\n      <td>40.609261</td>\n      <td>1</td>\n      <td>6.50</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>8.80</td>\n    </tr>\n    <tr>\n      <th>9922</th>\n      <td>2</td>\n      <td>2016-03-10 08:00:55</td>\n      <td>2016-03-10 08:03:20</td>\n      <td>1</td>\n      <td>1.51</td>\n      <td>-74.186760</td>\n      <td>40.697449</td>\n      <td>5</td>\n      <td>N</td>\n      <td>-74.177338</td>\n      <td>40.695122</td>\n      <td>1</td>\n      <td>100.00</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.01</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>100.31</td>\n    </tr>\n    <tr>\n      <th>10181</th>\n      <td>2</td>\n      <td>2016-03-10 08:02:13</td>\n      <td>2016-03-10 08:09:02</td>\n      <td>1</td>\n      <td>1.00</td>\n      <td>-74.184555</td>\n      <td>40.668911</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-74.003365</td>\n      <td>40.748787</td>\n      <td>1</td>\n      <td>6.50</td>\n      <td>0.0</td>\n      <td>0.5</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>8.30</td>\n    </tr>\n    <tr>\n      <th>20882</th>\n      <td>2</td>\n      <td>2016-03-10 08:57:02</td>\n      <td>2016-03-10 08:57:07</td>\n      <td>2</td>\n      <td>0.00</td>\n      <td>-74.406517</td>\n      <td>40.859928</td>\n      <td>5</td>\n      <td>N</td>\n      <td>-74.406517</td>\n      <td>40.859928</td>\n      <td>1</td>\n      <td>180.00</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>45.08</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>225.38</td>\n    </tr>\n    <tr>\n      <th>29620</th>\n      <td>2</td>\n      <td>2016-03-10 09:45:10</td>\n      <td>2016-03-10 09:45:12</td>\n      <td>2</td>\n      <td>0.00</td>\n      <td>-73.693176</td>\n      <td>40.638042</td>\n      <td>5</td>\n      <td>N</td>\n      <td>-73.693169</td>\n      <td>40.638031</td>\n      <td>1</td>\n      <td>84.00</td>\n      <td>0.0</td>\n      <td>0.5</td>\n      <td>16.96</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>101.76</td>\n    </tr>\n    <tr>\n      <th>34528</th>\n      <td>2</td>\n      <td>2016-03-10 10:14:27</td>\n      <td>2016-03-10 10:26:26</td>\n      <td>1</td>\n      <td>4.49</td>\n      <td>-74.192940</td>\n      <td>40.682598</td>\n      <td>5</td>\n      <td>N</td>\n      <td>-74.216331</td>\n      <td>40.647751</td>\n      <td>2</td>\n      <td>93.00</td>\n      <td>0.0</td>\n      <td>0.5</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>93.80</td>\n    </tr>\n    <tr>\n      <th>38597</th>\n      <td>2</td>\n      <td>2016-03-10 10:40:24</td>\n      <td>2016-03-10 10:42:41</td>\n      <td>1</td>\n      <td>0.68</td>\n      <td>-74.229523</td>\n      <td>40.732571</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-74.226830</td>\n      <td>40.737019</td>\n      <td>2</td>\n      <td>4.00</td>\n      <td>0.0</td>\n      <td>0.5</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>4.80</td>\n    </tr>\n    <tr>\n      <th>38829</th>\n      <td>2</td>\n      <td>2016-03-10 10:41:47</td>\n      <td>2016-03-10 10:47:55</td>\n      <td>3</td>\n      <td>0.63</td>\n      <td>-7.587607</td>\n      <td>40.760498</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-73.979378</td>\n      <td>40.761581</td>\n      <td>1</td>\n      <td>5.50</td>\n      <td>0.0</td>\n      <td>0.5</td>\n      <td>1.26</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>7.56</td>\n    </tr>\n    <tr>\n      <th>40469</th>\n      <td>2</td>\n      <td>2016-03-10 10:51:42</td>\n      <td>2016-03-10 10:54:05</td>\n      <td>1</td>\n      <td>0.00</td>\n      <td>-73.805061</td>\n      <td>40.971306</td>\n      <td>5</td>\n      <td>N</td>\n      <td>-73.805061</td>\n      <td>40.971302</td>\n      <td>1</td>\n      <td>104.00</td>\n      <td>0.0</td>\n      <td>0.5</td>\n      <td>10.00</td>\n      <td>2.54</td>\n      <td>0.3</td>\n      <td>117.34</td>\n    </tr>\n    <tr>\n      <th>54389</th>\n      <td>2</td>\n      <td>2016-03-10 12:18:20</td>\n      <td>2016-03-10 12:21:49</td>\n      <td>1</td>\n      <td>1.47</td>\n      <td>-74.177849</td>\n      <td>40.828911</td>\n      <td>5</td>\n      <td>N</td>\n      <td>-74.197487</td>\n      <td>40.820438</td>\n      <td>1</td>\n      <td>130.75</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>36.90</td>\n      <td>16.54</td>\n      <td>0.3</td>\n      <td>184.49</td>\n    </tr>\n    <tr>\n      <th>66038</th>\n      <td>1</td>\n      <td>2016-03-01 00:10:03</td>\n      <td>2016-03-01 00:10:37</td>\n      <td>1</td>\n      <td>0.00</td>\n      <td>-73.832832</td>\n      <td>41.059826</td>\n      <td>5</td>\n      <td>N</td>\n      <td>-73.832832</td>\n      <td>41.059826</td>\n      <td>4</td>\n      <td>170.00</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>170.30</td>\n    </tr>\n    <tr>\n      <th>67377</th>\n      <td>2</td>\n      <td>2016-03-10 13:20:52</td>\n      <td>2016-03-10 13:21:59</td>\n      <td>3</td>\n      <td>0.00</td>\n      <td>-74.073082</td>\n      <td>41.034771</td>\n      <td>5</td>\n      <td>N</td>\n      <td>-74.073242</td>\n      <td>41.034740</td>\n      <td>1</td>\n      <td>118.75</td>\n      <td>0.0</td>\n      <td>0.5</td>\n      <td>32.51</td>\n      <td>10.50</td>\n      <td>0.3</td>\n      <td>162.56</td>\n    </tr>\n    <tr>\n      <th>70983</th>\n      <td>2</td>\n      <td>2016-03-01 00:18:36</td>\n      <td>2016-03-01 00:24:34</td>\n      <td>1</td>\n      <td>1.15</td>\n      <td>-74.651306</td>\n      <td>40.609261</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-74.501564</td>\n      <td>40.711903</td>\n      <td>2</td>\n      <td>6.00</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>7.30</td>\n    </tr>\n    <tr>\n      <th>71193</th>\n      <td>1</td>\n      <td>2016-03-01 00:20:09</td>\n      <td>2016-03-01 00:20:38</td>\n      <td>1</td>\n      <td>1.00</td>\n      <td>-73.812035</td>\n      <td>40.982334</td>\n      <td>5</td>\n      <td>N</td>\n      <td>-73.812035</td>\n      <td>40.982334</td>\n      <td>1</td>\n      <td>104.00</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>10.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>114.30</td>\n    </tr>\n    <tr>\n      <th>72570</th>\n      <td>2</td>\n      <td>2016-03-01 00:32:05</td>\n      <td>2016-03-01 00:46:10</td>\n      <td>1</td>\n      <td>3.97</td>\n      <td>-74.501564</td>\n      <td>40.711903</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-74.501564</td>\n      <td>40.711903</td>\n      <td>1</td>\n      <td>14.00</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>3.06</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>18.36</td>\n    </tr>\n    <tr>\n      <th>80189</th>\n      <td>1</td>\n      <td>2016-03-01 01:25:18</td>\n      <td>2016-03-01 01:26:16</td>\n      <td>1</td>\n      <td>28.50</td>\n      <td>-74.110451</td>\n      <td>41.002087</td>\n      <td>5</td>\n      <td>N</td>\n      <td>-74.110451</td>\n      <td>41.002087</td>\n      <td>1</td>\n      <td>102.00</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.01</td>\n      <td>10.50</td>\n      <td>0.3</td>\n      <td>112.81</td>\n    </tr>\n    <tr>\n      <th>80695</th>\n      <td>1</td>\n      <td>2016-03-01 01:32:49</td>\n      <td>2016-03-01 01:33:04</td>\n      <td>1</td>\n      <td>4.30</td>\n      <td>-73.619354</td>\n      <td>40.664433</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-73.619362</td>\n      <td>40.664433</td>\n      <td>4</td>\n      <td>2.50</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>3.80</td>\n    </tr>\n    <tr>\n      <th>80879</th>\n      <td>1</td>\n      <td>2016-03-01 01:35:25</td>\n      <td>2016-03-01 01:37:11</td>\n      <td>1</td>\n      <td>4.30</td>\n      <td>-73.619339</td>\n      <td>40.664448</td>\n      <td>5</td>\n      <td>N</td>\n      <td>-73.619347</td>\n      <td>40.664429</td>\n      <td>1</td>\n      <td>150.00</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>150.30</td>\n    </tr>\n    <tr>\n      <th>84917</th>\n      <td>2</td>\n      <td>2016-03-01 03:00:13</td>\n      <td>2016-03-01 03:28:17</td>\n      <td>2</td>\n      <td>23.70</td>\n      <td>-74.000130</td>\n      <td>40.577213</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-73.873192</td>\n      <td>40.774254</td>\n      <td>2</td>\n      <td>62.50</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>63.80</td>\n    </tr>\n    <tr>\n      <th>85463</th>\n      <td>2</td>\n      <td>2016-03-01 03:16:00</td>\n      <td>2016-03-01 03:16:09</td>\n      <td>1</td>\n      <td>0.00</td>\n      <td>-73.526367</td>\n      <td>40.766811</td>\n      <td>5</td>\n      <td>N</td>\n      <td>-73.526367</td>\n      <td>40.766811</td>\n      <td>1</td>\n      <td>80.00</td>\n      <td>0.0</td>\n      <td>0.5</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>80.80</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n`But we do not get the results as expected, seems like some data points are getting included in both the dataframes. I tried to find out the solution but couldnt find it. So this remains mystery.`\n\n\n```python\n# Plotting pickup cordinates which are outside the bounding box of New-York \n# we will collect all the points outside the bounding box of newyork city to outlier_locations\noutlier_locations = month[((month.pickup_longitude <= -74.15) | (month.pickup_latitude <= 40.5774)| \\\n                   (month.pickup_longitude >= -73.7004) | (month.pickup_latitude >= 40.9176))]\nprint(outlier_locations.shape[0].compute())\n# creating a map with the a base location\n# read more about the folium here: http://folium.readthedocs.io/en/latest/quickstart.html\n\n# note: you dont need to remember any of these, you dont need indeepth knowledge on these maps and plots\n\nmap_osm = folium.Map(location=[40.734695, -73.990372], tiles='Stamen Toner')\n\n# we will spot only first 100 outliers on the map, plotting all the outliers will take more time\nsample_locations = outlier_locations.head(10000)\nfor i,j in sample_locations.iterrows():\n    if int(j['pickup_latitude']) != 0:\n        folium.Marker(list((j['pickup_latitude'],j['pickup_longitude']))).add_to(map_osm)\nmap_osm;\n```\n\n    185746\n\n\n<b>Observation:-</b> `As you can see above that there are some points just outside the boundary but there are a few that are in either South america, Mexico or Canada`\n\n### 2. Dropoff Latitude & Dropoff Longitude\n\nIt is inferred from the source https://www.flickr.com/places/info/2459115 that New York is bounded by the location cordinates(lat,long) - (40.5774, -74.15) & (40.9176,-73.7004) so hence any cordinates not within these cordinates are not considered by us as we are only concerned with dropoffs which are within New York.\n\n\n```python\n# Plotting dropoff cordinates which are outside the bounding box of New-York \n# we will collect all the points outside the bounding box of newyork city to outlier_locations\noutlier_locations = month[((month.dropoff_longitude <= -74.15) | (month.dropoff_latitude <= 40.5774)| \\\n                   (month.dropoff_longitude >= -73.7004) | (month.dropoff_latitude >= 40.9176))]\nprint(outlier_locations.shape[0].compute())\n# creating a map with the a base location\n# read more about the folium here: http://folium.readthedocs.io/en/latest/quickstart.html\n\n# note: you dont need to remember any of these, you dont need indeepth knowledge on these maps and plots\n\nmap_osm = folium.Map(location=[40.734695, -73.990372], tiles='Stamen Toner')\n\n# we will spot only first 100 outliers on the map, plotting all the outliers will take more time\nsample_locations = outlier_locations.head(10000)\nfor i,j in sample_locations.iterrows():\n    if int(j['pickup_latitude']) != 0:\n        folium.Marker(list((j['dropoff_latitude'],j['dropoff_longitude']))).add_to(map_osm)\nmap_osm;\n```\n\n    204783\n\n\n<b>Observation:-</b> `The observations here are similar to those obtained while analysing pickup latitude and longitude`\n\n## 3. Trip Durations:\n\n<p style=\"font-size:18px\">According to NYC Taxi &amp; Limousine Commision Regulations <b style= \"color:blue\">the maximum allowed trip duration in a 24 hour interval is 12 hours.</b> </p>\n\n\n```python\ndef dura_cal(x):\n    try:\n        return (datetime.strptime(x['tpep_dropoff_datetime'], '%Y-%m-%d %H:%M:%S')-datetime.strptime(x['tpep_pickup_datetime'], '%Y-%m-%d %H:%M:%S')).seconds/60\n    except:\n        return 0\n```\n\n\n```python\ndef dura_cal1(x):\n    return (datetime.strptime(x['tpep_dropoff_datetime'].iloc[0], '%Y-%m-%d %H:%M:%S')-datetime.strptime(x['tpep_pickup_datetime'].iloc[0], '%Y-%m-%d %H:%M:%S')).seconds/60\n   \n```\n\n\n```python\nmonth.get_partition(0).loc[0].compute()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>VendorID</th>\n      <th>tpep_pickup_datetime</th>\n      <th>tpep_dropoff_datetime</th>\n      <th>passenger_count</th>\n      <th>trip_distance</th>\n      <th>pickup_longitude</th>\n      <th>pickup_latitude</th>\n      <th>RatecodeID</th>\n      <th>store_and_fwd_flag</th>\n      <th>dropoff_longitude</th>\n      <th>dropoff_latitude</th>\n      <th>payment_type</th>\n      <th>fare_amount</th>\n      <th>extra</th>\n      <th>mta_tax</th>\n      <th>tip_amount</th>\n      <th>tolls_amount</th>\n      <th>improvement_surcharge</th>\n      <th>total_amount</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:07:55</td>\n      <td>1</td>\n      <td>2.5</td>\n      <td>-73.976746</td>\n      <td>40.765152</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-74.004265</td>\n      <td>40.746128</td>\n      <td>1</td>\n      <td>9.0</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>2.05</td>\n      <td>0.0</td>\n      <td>0.3</td>\n      <td>12.35</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nmonth.get_partition(0).loc[20].compute()['tpep_dropoff_datetime'].iloc[0]\n```\n\n\n\n\n    '2016-03-01 00:06:11'\n\n\n\n\n```python\ndura_cal(month.get_partition(0).loc[20].compute())\n```\n\n    2016-03-01 00:06:11\n\n\n\n\n\n    6.116666666666666\n\n\n\n\n```python\n# month['duration'] = month.apply(lambda x: dura_cal(x),axis=1).compute()\n# month.head(25)\n```\n\n\n```python\ndf = pd.read_csv('data/yellow_tripdata_2016-03.csv')\n```\n\n\n```python\ndf.head(10)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>VendorID</th>\n      <th>tpep_pickup_datetime</th>\n      <th>tpep_dropoff_datetime</th>\n      <th>passenger_count</th>\n      <th>trip_distance</th>\n      <th>pickup_longitude</th>\n      <th>pickup_latitude</th>\n      <th>RatecodeID</th>\n      <th>store_and_fwd_flag</th>\n      <th>dropoff_longitude</th>\n      <th>dropoff_latitude</th>\n      <th>payment_type</th>\n      <th>fare_amount</th>\n      <th>extra</th>\n      <th>mta_tax</th>\n      <th>tip_amount</th>\n      <th>tolls_amount</th>\n      <th>improvement_surcharge</th>\n      <th>total_amount</th>\n      <th>duration</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:07:55</td>\n      <td>1</td>\n      <td>2.50</td>\n      <td>-73.976746</td>\n      <td>40.765152</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-74.004265</td>\n      <td>40.746128</td>\n      <td>1</td>\n      <td>9.0</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>2.05</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>12.35</td>\n      <td>7.916667</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:11:06</td>\n      <td>1</td>\n      <td>2.90</td>\n      <td>-73.983482</td>\n      <td>40.767925</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-74.005943</td>\n      <td>40.733166</td>\n      <td>1</td>\n      <td>11.0</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>3.05</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>15.35</td>\n      <td>11.100000</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:31:06</td>\n      <td>2</td>\n      <td>19.98</td>\n      <td>-73.782021</td>\n      <td>40.644810</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-73.974541</td>\n      <td>40.675770</td>\n      <td>1</td>\n      <td>54.5</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>8.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>63.80</td>\n      <td>31.100000</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>2</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>3</td>\n      <td>10.78</td>\n      <td>-73.863419</td>\n      <td>40.769814</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-73.969650</td>\n      <td>40.757767</td>\n      <td>1</td>\n      <td>31.5</td>\n      <td>0.0</td>\n      <td>0.5</td>\n      <td>3.78</td>\n      <td>5.54</td>\n      <td>0.3</td>\n      <td>41.62</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>2</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>5</td>\n      <td>30.43</td>\n      <td>-73.971741</td>\n      <td>40.792183</td>\n      <td>3</td>\n      <td>N</td>\n      <td>-74.177170</td>\n      <td>40.695053</td>\n      <td>1</td>\n      <td>98.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.00</td>\n      <td>15.50</td>\n      <td>0.3</td>\n      <td>113.80</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>2</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>5</td>\n      <td>5.92</td>\n      <td>-74.017197</td>\n      <td>40.705383</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-73.978073</td>\n      <td>40.755787</td>\n      <td>1</td>\n      <td>23.5</td>\n      <td>1.0</td>\n      <td>0.5</td>\n      <td>5.06</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>30.36</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>2</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>6</td>\n      <td>5.72</td>\n      <td>-73.994583</td>\n      <td>40.727848</td>\n      <td>1</td>\n      <td>N</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>2</td>\n      <td>23.0</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>24.30</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>1</td>\n      <td>2016-03-01 00:00:01</td>\n      <td>2016-03-01 00:16:04</td>\n      <td>1</td>\n      <td>6.20</td>\n      <td>-73.788773</td>\n      <td>40.647758</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-73.829208</td>\n      <td>40.712345</td>\n      <td>3</td>\n      <td>20.5</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>21.80</td>\n      <td>16.050000</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>1</td>\n      <td>2016-03-01 00:00:01</td>\n      <td>2016-03-01 00:05:00</td>\n      <td>1</td>\n      <td>0.70</td>\n      <td>-73.958221</td>\n      <td>40.764641</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-73.967896</td>\n      <td>40.762901</td>\n      <td>1</td>\n      <td>5.5</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>8.80</td>\n      <td>4.983333</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>2</td>\n      <td>2016-03-01 00:00:01</td>\n      <td>2016-03-01 00:24:06</td>\n      <td>3</td>\n      <td>7.18</td>\n      <td>-73.985779</td>\n      <td>40.741192</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-73.946350</td>\n      <td>40.797878</td>\n      <td>1</td>\n      <td>23.5</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>3.20</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>28.00</td>\n      <td>24.083333</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf['duration'] = df.apply(dura_cal,axis=1)\ndf.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>VendorID</th>\n      <th>tpep_pickup_datetime</th>\n      <th>tpep_dropoff_datetime</th>\n      <th>passenger_count</th>\n      <th>trip_distance</th>\n      <th>pickup_longitude</th>\n      <th>pickup_latitude</th>\n      <th>RatecodeID</th>\n      <th>store_and_fwd_flag</th>\n      <th>dropoff_longitude</th>\n      <th>dropoff_latitude</th>\n      <th>payment_type</th>\n      <th>fare_amount</th>\n      <th>extra</th>\n      <th>mta_tax</th>\n      <th>tip_amount</th>\n      <th>tolls_amount</th>\n      <th>improvement_surcharge</th>\n      <th>total_amount</th>\n      <th>duration</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:07:55</td>\n      <td>1</td>\n      <td>2.50</td>\n      <td>-73.976746</td>\n      <td>40.765152</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-74.004265</td>\n      <td>40.746128</td>\n      <td>1</td>\n      <td>9.0</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>2.05</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>12.35</td>\n      <td>7.916667</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:11:06</td>\n      <td>1</td>\n      <td>2.90</td>\n      <td>-73.983482</td>\n      <td>40.767925</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-74.005943</td>\n      <td>40.733166</td>\n      <td>1</td>\n      <td>11.0</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>3.05</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>15.35</td>\n      <td>11.100000</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:31:06</td>\n      <td>2</td>\n      <td>19.98</td>\n      <td>-73.782021</td>\n      <td>40.644810</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-73.974541</td>\n      <td>40.675770</td>\n      <td>1</td>\n      <td>54.5</td>\n      <td>0.5</td>\n      <td>0.5</td>\n      <td>8.00</td>\n      <td>0.00</td>\n      <td>0.3</td>\n      <td>63.80</td>\n      <td>31.100000</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>2</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>3</td>\n      <td>10.78</td>\n      <td>-73.863419</td>\n      <td>40.769814</td>\n      <td>1</td>\n      <td>N</td>\n      <td>-73.969650</td>\n      <td>40.757767</td>\n      <td>1</td>\n      <td>31.5</td>\n      <td>0.0</td>\n      <td>0.5</td>\n      <td>3.78</td>\n      <td>5.54</td>\n      <td>0.3</td>\n      <td>41.62</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>2</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>5</td>\n      <td>30.43</td>\n      <td>-73.971741</td>\n      <td>40.792183</td>\n      <td>3</td>\n      <td>N</td>\n      <td>-74.177170</td>\n      <td>40.695053</td>\n      <td>1</td>\n      <td>98.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.00</td>\n      <td>15.50</td>\n      <td>0.3</td>\n      <td>113.80</td>\n      <td>0.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndef speed_cal(x):\n    try:\n        return df['trip_distance'] /(df['duration']/60)\n    except:\n        return 0 \n    \ndf['speed'] = df.apply(speed_cal,axis=1)\n```\n\n\n```python\ndfd = df[['passenger_count','trip_distance','duration','speed','tpep_pickup_datetime','pickup_longitude','pickup_latitude','dropoff_longitude','dropoff_latitude','total_amount']].copy(False)\n```\n\n`I tried to compute the duration using the pandas methodology but, here we are being unsuccessful, it i staking either an tremendious amount of time or always crashing.. So we need to appreach this differently.`\n\n\n```python\ndatime = month[['tpep_pickup_datetime','tpep_dropoff_datetime','trip_distance']].compute()\n```\n\n\n```python\nduration = datime.apply(dura_cal,axis=1)\n```\n\n\n```python\ndf = month[['passenger_count','trip_distance','tpep_pickup_datetime','pickup_longitude','pickup_latitude','dropoff_longitude','dropoff_latitude','total_amount']].compute()\n```\n\n\n```python\ndf['duration'] = duration\n```\n\n\n```python\nspeed = 60*(df['trip_distance']/duration)\n```\n\n\n```python\ndf['speed'] = speed\n```\n\n\n```python\ndf\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>passenger_count</th>\n      <th>trip_distance</th>\n      <th>tpep_pickup_datetime</th>\n      <th>pickup_longitude</th>\n      <th>pickup_latitude</th>\n      <th>dropoff_longitude</th>\n      <th>dropoff_latitude</th>\n      <th>total_amount</th>\n      <th>duration</th>\n      <th>speed</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>2.50</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>-73.976746</td>\n      <td>40.765152</td>\n      <td>-74.004265</td>\n      <td>40.746128</td>\n      <td>12.35</td>\n      <td>7.916667</td>\n      <td>18.947368</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>2.90</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>-73.983482</td>\n      <td>40.767925</td>\n      <td>-74.005943</td>\n      <td>40.733166</td>\n      <td>15.35</td>\n      <td>11.100000</td>\n      <td>15.675676</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2</td>\n      <td>19.98</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>-73.782021</td>\n      <td>40.644810</td>\n      <td>-73.974541</td>\n      <td>40.675770</td>\n      <td>63.80</td>\n      <td>31.100000</td>\n      <td>38.546624</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>3</td>\n      <td>10.78</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>-73.863419</td>\n      <td>40.769814</td>\n      <td>-73.969650</td>\n      <td>40.757767</td>\n      <td>41.62</td>\n      <td>0.000000</td>\n      <td>inf</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>5</td>\n      <td>30.43</td>\n      <td>2016-03-01 00:00:00</td>\n      <td>-73.971741</td>\n      <td>40.792183</td>\n      <td>-74.177170</td>\n      <td>40.695053</td>\n      <td>113.80</td>\n      <td>0.000000</td>\n      <td>inf</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>13037</th>\n      <td>1</td>\n      <td>0.00</td>\n      <td>2016-03-31 16:34:36</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>20.80</td>\n      <td>0.000000</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>13038</th>\n      <td>1</td>\n      <td>0.40</td>\n      <td>2016-03-26 03:02:32</td>\n      <td>-73.977356</td>\n      <td>40.774471</td>\n      <td>-73.982536</td>\n      <td>40.772408</td>\n      <td>7.50</td>\n      <td>945.383333</td>\n      <td>0.025387</td>\n    </tr>\n    <tr>\n      <th>13039</th>\n      <td>1</td>\n      <td>20.20</td>\n      <td>2016-03-20 08:43:59</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>-74.008614</td>\n      <td>40.710987</td>\n      <td>64.34</td>\n      <td>381.033333</td>\n      <td>3.180824</td>\n    </tr>\n    <tr>\n      <th>13040</th>\n      <td>1</td>\n      <td>15.40</td>\n      <td>2016-03-20 08:49:47</td>\n      <td>-73.790077</td>\n      <td>40.647377</td>\n      <td>-73.971756</td>\n      <td>40.578457</td>\n      <td>49.30</td>\n      <td>621.666667</td>\n      <td>1.486327</td>\n    </tr>\n    <tr>\n      <th>13041</th>\n      <td>1</td>\n      <td>17.50</td>\n      <td>2016-03-20 08:50:24</td>\n      <td>-73.798485</td>\n      <td>40.645096</td>\n      <td>-73.993111</td>\n      <td>40.725880</td>\n      <td>66.00</td>\n      <td>427.866667</td>\n      <td>2.454036</td>\n    </tr>\n  </tbody>\n</table>\n<p>12210952 rows \u00d7 10 columns</p>\n</div>\n\n\n\n\n```python\ndf.to_csv('data/step1data.csv')\n```\n\n\n```python\nsns.boxplot(y=df['duration'])\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n\n\n\n    <AxesSubplot:ylabel='duration'>\n\n\n\n\n```python\nfor i in range(0,101,10):\n    print('The {}th percentile of duration attribute is :{}'.format(i,np.percentile(df['duration'],i)))\n```\n\n    The 0th percentile of duration attribute is :0.0\n    The 10th percentile of duration attribute is :4.016666666666667\n    The 20th percentile of duration attribute is :5.733333333333333\n    The 30th percentile of duration attribute is :7.35\n    The 40th percentile of duration attribute is :9.016666666666667\n    The 50th percentile of duration attribute is :10.883333333333333\n    The 60th percentile of duration attribute is :13.083333333333334\n    The 70th percentile of duration attribute is :15.850000000000001\n    The 80th percentile of duration attribute is :19.716666666666665\n    The 90th percentile of duration attribute is :26.466666666666665\n    The 100th percentile of duration attribute is :1439.9666666666667\n\n\n\n```python\nfor i in range(90,101,1):\n    print('The {}th percentile of duration attribute is :{}'.format(i,np.percentile(df['duration'],i)))\n```\n\n    The 90th percentile of duration attribute is :26.466666666666665\n    The 91th percentile of duration attribute is :27.53333333333333\n    The 92th percentile of duration attribute is :28.75\n    The 93th percentile of duration attribute is :30.15\n    The 94th percentile of duration attribute is :31.816666666666666\n    The 95th percentile of duration attribute is :33.86666666666667\n    The 96th percentile of duration attribute is :36.483333333333334\n    The 97th percentile of duration attribute is :40.05\n    The 98th percentile of duration attribute is :45.3\n    The 99th percentile of duration attribute is :54.85\n    The 100th percentile of duration attribute is :1439.9666666666667\n\n\n\n```python\ndf.shape\n```\n\n\n\n\n    (12210952, 10)\n\n\n\n\n```python\n#removing data based on our analysis and TLC regulations\n# i.e. duration should be between 1 and 720mins(12hrs)\ndf = df[(df.duration>1) & (df.duration<720)]\n```\n\n\n```python\ndf.shape\n```\n\n\n\n\n    (12093193, 10)\n\n\n\n\n```python\n#box-plot after removal of outliers\nsns.boxplot(y=df['duration'])\n```\n\n\n```python\n# fig, ax = plt.Figure(figsize=(40,6))\nrcParams['figure.figsize'] = 20,10\nsns.histplot(df['duration'],kde=True)\n```\n\nAs we can see it is an right skewed graph\n\n#### This graph might represent Log-Normal so we will log() the values and check if the distribution is normal/gaussian.\n\n\n```python\nsns.histplot(np.log(df['duration']),kde=True)\n```\n\n#### This is almost normal dist, with some right skew.\n\n\n```python\nnp.log(df['duration'])\n```\n\n\n\n\n    0        2.068970\n    1        2.406945\n    2        3.437208\n    7        2.775709\n    8        1.606099\n               ...   \n    13035    5.638058\n    13036    4.776880\n    13039    5.942887\n    13040    6.432404\n    13041    6.058812\n    Name: duration, Length: 12093193, dtype: float64\n\n\n\n\n```python\nax = plt.subplot(111)\nscipy.stats.probplot(np.log(df['duration']),plot=ax)\nplt.show()\n```\n\n### So it is little off from normal dist at the ends. \n\n## 4. Speed\n\n\n```python\nrcParams['figure.figsize'] = 5,10\nsns.boxplot(y=df['speed'])\n```\n\n\n```python\nfor i in range(0,90,10):\n    print('The {}th percentile of duration attribute is :{}'.format(i,np.percentile(df['speed'],i)))\nfor i in range(90,99,1):\n    print('The {}th percentile of duration attribute is :{}'.format(i,np.percentile(df['speed'],i)))\nfor i in np.linspace(99.0,100.0,11):\n    print('The {}th percentile of duration attribute is :{}'.format(i,np.percentile(df['speed'],i)))\n```\n\n    The 0th percentile of duration attribute is :0.0\n    The 10th percentile of duration attribute is :5.915492957746478\n    The 20th percentile of duration attribute is :7.285714285714286\n    The 30th percentile of duration attribute is :8.392156862745098\n    The 40th percentile of duration attribute is :9.444866920152089\n    The 50th percentile of duration attribute is :10.542056074766355\n    The 60th percentile of duration attribute is :11.779141104294478\n    The 70th percentile of duration attribute is :13.317567567567567\n    The 80th percentile of duration attribute is :15.524999999999999\n    The 90th percentile of duration attribute is :19.726027397260275\n    The 91th percentile of duration attribute is :20.417910447761194\n    The 92th percentile of duration attribute is :21.19935170178282\n    The 93th percentile of duration attribute is :22.10232558139535\n    The 94th percentile of duration attribute is :23.13847158897581\n    The 95th percentile of duration attribute is :24.36\n    The 96th percentile of duration attribute is :25.827232796486093\n    The 97th percentile of duration attribute is :27.671840354767184\n    The 98th percentile of duration attribute is :30.21221864951768\n    The 99.0th percentile of duration attribute is :34.225352112676056\n    The 99.1th percentile of duration attribute is :34.79063244888023\n    The 99.2th percentile of duration attribute is :35.41841680129241\n    The 99.3th percentile of duration attribute is :36.114285714285714\n    The 99.4th percentile of duration attribute is :36.8944099378882\n    The 99.5th percentile of duration attribute is :37.804055901003466\n    The 99.6th percentile of duration attribute is :38.87323943661972\n    The 99.7th percentile of duration attribute is :40.17403346666368\n    The 99.8th percentile of duration attribute is :41.86461937638487\n    The 99.9th percentile of duration attribute is :44.53771860911574\n    The 100.0th percentile of duration attribute is :61801497.46174618\n\n\n\n```python\ndf.shape\n```\n\n\n\n\n    (12093193, 10)\n\n\n\n\n```python\n#removing further outliers based on the 99.9th percentile value\ndf=df[(df.speed>0) & (df.speed<44.54)]\n```\n\n\n```python\ndf.shape\n```\n\n\n\n\n    (12068027, 10)\n\n\n\n\n```python\n#avg.speed of cabs in New-York\ndf.speed.mean()\n```\n\n\n\n\n    11.916955185455928\n\n\n\n<b style='font-size:16px'>The avg speed in Newyork speed is 11.92miles/hr, so a cab driver can travel <font color='blue'> 2 miles per 10min on avg.</font> </b>\n\n## 4. Trip Distance\n\n\n```python\nrcParams['figure.figsize'] = 5,10\nsns.boxplot(y=df['trip_distance'])\n```\n\n\n```python\nfor i in range(0,90,10):\n    print('The {}th percentile of duration attribute is :{}'.format(i,np.percentile(df['trip_distance'],i)))\nfor i in range(90,99,1):\n    print('The {}th percentile of duration attribute is :{}'.format(i,np.percentile(df['trip_distance'],i)))\nfor i in np.linspace(99.0,100.0,11):\n    print('The {}th percentile of duration attribute is :{}'.format(i,np.percentile(df['trip_distance'],i)))\n```\n\n    The 0th percentile of duration attribute is :0.01\n    The 10th percentile of duration attribute is :0.69\n    The 20th percentile of duration attribute is :0.9\n    The 30th percentile of duration attribute is :1.13\n    The 40th percentile of duration attribute is :1.4\n    The 50th percentile of duration attribute is :1.7\n    The 60th percentile of duration attribute is :2.1\n    The 70th percentile of duration attribute is :2.72\n    The 80th percentile of duration attribute is :3.8\n    The 90th percentile of duration attribute is :6.7\n    The 91th percentile of duration attribute is :7.35\n    The 92th percentile of duration attribute is :8.1\n    The 93th percentile of duration attribute is :8.89\n    The 94th percentile of duration attribute is :9.6\n    The 95th percentile of duration attribute is :10.4\n    The 96th percentile of duration attribute is :11.46\n    The 97th percentile of duration attribute is :13.57\n    The 98th percentile of duration attribute is :16.91\n    The 99.0th percentile of duration attribute is :18.51\n    The 99.1th percentile of duration attribute is :18.73\n    The 99.2th percentile of duration attribute is :19.0\n    The 99.3th percentile of duration attribute is :19.25\n    The 99.4th percentile of duration attribute is :19.59\n    The 99.5th percentile of duration attribute is :19.99\n    The 99.6th percentile of duration attribute is :20.43\n    The 99.7th percentile of duration attribute is :21.0\n    The 99.8th percentile of duration attribute is :21.7\n    The 99.9th percentile of duration attribute is :23.5\n    The 100.0th percentile of duration attribute is :222.2\n\n\n\n```python\nrcParams['figure.figsize'] = 20,10\nsns.histplot(df['trip_distance'],kde=True)\n```\n\n\n```python\ndf.shape\n```\n\n\n\n\n    (12068027, 10)\n\n\n\n\n```python\n#removing further outliers based on the 99.9th percentile value\ndf=df[(df.trip_distance>0) & (df.trip_distance<24)]\n```\n\n\n```python\ndf.shape\n```\n\n\n\n\n    (12057201, 10)\n\n\n\n\n```python\nrcParams['figure.figsize'] = 5,7\nsns.boxplot(y=df['trip_distance'])\n```\n\n## 5. Total Fare\n\n\n```python\nrcParams['figure.figsize'] = 5,7\nsns.boxplot(y=df['total_amount'])\n```\n\n\n```python\nfor i in range(0,90,10):\n    print('The {}th percentile of duration attribute is :{}'.format(i,np.percentile(df['total_amount'],i)))\nfor i in range(90,99,1):\n    print('The {}th percentile of duration attribute is :{}'.format(i,np.percentile(df['total_amount'],i)))\nfor i in np.linspace(99.0,100.0,11):\n    print('The {}th percentile of duration attribute is :{}'.format(i,np.percentile(df['total_amount'],i)))\n```\n\n    The 0th percentile of duration attribute is :-300.8\n    The 10th percentile of duration attribute is :6.8\n    The 20th percentile of duration attribute is :8.1\n    The 30th percentile of duration attribute is :9.3\n    The 40th percentile of duration attribute is :10.38\n    The 50th percentile of duration attribute is :11.8\n    The 60th percentile of duration attribute is :13.56\n    The 70th percentile of duration attribute is :15.96\n    The 80th percentile of duration attribute is :19.8\n    The 90th percentile of duration attribute is :28.8\n    The 91th percentile of duration attribute is :30.84\n    The 92th percentile of duration attribute is :33.34\n    The 93th percentile of duration attribute is :36.34\n    The 94th percentile of duration attribute is :39.41\n    The 95th percentile of duration attribute is :42.99\n    The 96th percentile of duration attribute is :47.21\n    The 97th percentile of duration attribute is :52.8\n    The 98th percentile of duration attribute is :59.34\n    The 99.0th percentile of duration attribute is :69.99\n    The 99.1th percentile of duration attribute is :69.99\n    The 99.2th percentile of duration attribute is :70.01\n    The 99.3th percentile of duration attribute is :70.01\n    The 99.4th percentile of duration attribute is :70.2\n    The 99.5th percentile of duration attribute is :72.89\n    The 99.6th percentile of duration attribute is :73.59\n    The 99.7th percentile of duration attribute is :75.41\n    The 99.8th percentile of duration attribute is :80.16\n    The 99.9th percentile of duration attribute is :94.55\n    The 100.0th percentile of duration attribute is :1463.12\n\n\n\n```python\ndf['total_amount'].sort_values()[-8400:-8398]\n```\n\n\n\n\n    156072    100.0\n    36528     100.0\n    Name: total_amount, dtype: float64\n\n\n\n\n```python\nrcParams['figure.figsize'] = 20,10\nplt.subplot(131)\nplt.plot(list(df['total_amount'].sort_values()[-10000:]))\nplt.subplot(132)\nplt.plot(list(df['total_amount'].sort_values()[-700:]))\nplt.subplot(133)\nplt.plot(list(df['total_amount'].sort_values()[-100:]))\nplt.show()\n```\n\n#### As we can see an sharp increase in the 'total_amount' near the end i.e after 200 fare amount. So we will consider 200 as out outlier bound.\n\n\n```python\ndf.shape\n```\n\n\n\n\n    (12057201, 10)\n\n\n\n\n```python\ndf = df[(df.total_amount <200) & (df.total_amount >0)]\n```\n\n\n```python\ndf.shape\n```\n\n\n\n\n    (12054486, 10)\n\n\n\n\n```python\ndf.to_csv('data/step2data.csv')\n```\n\n### Summing every outlier removal step in one function:\n\n\n```python\n#removing all outliers based on our univariate analysis above\ndef dura_cal(x):\n    try:\n        return (datetime.strptime(x['tpep_dropoff_datetime'], '%Y-%m-%d %H:%M:%S')-datetime.strptime(x['tpep_pickup_datetime'], '%Y-%m-%d %H:%M:%S')).seconds/60\n    except:\n        return 0\n        \ndef remove_outliers(df):\n\n    df = df[['passenger_count','trip_distance','tpep_pickup_datetime','tpep_dropoff_datetime',\\\n                 'pickup_longitude','pickup_latitude','dropoff_longitude','dropoff_latitude','total_amount']].compute()\n    \n    df['duration'] = df.apply(dura_cal,axis=1)\n    df['speed'] = 60*(df['trip_distance']/df['duration'])\n    \n    a = df.shape[0]\n    print (\"Number of pickup records = \",a)\n    t_df = df[((df.dropoff_longitude >= -74.15) & (df.dropoff_longitude <= -73.7004) &\\\n                       (df.dropoff_latitude >= 40.5774) & (df.dropoff_latitude <= 40.9176)) & \\\n                       ((df.pickup_longitude >= -74.15) & (df.pickup_latitude >= 40.5774)& \\\n                       (df.pickup_longitude <= -73.7004) & (df.pickup_latitude <= 40.9176))]\n    b = t_df.shape[0]\n    print (\"Number of outlier coordinates lying outside NY boundaries:\",(a-b))\n\n    \n    t_df = df[(df.duration > 0) & (df.duration < 720)]\n    c = t_df.shape[0]\n    print (\"Number of outliers from trip duration analysis:\",(a-c))\n    \n    # we are rounding off our bounds as the bounds will be not presisely same for each dataset.\n    t_df = df[(df.trip_distance > 0) & (df.trip_distance < 25)]\n    d = t_df.shape[0]\n    print (\"Number of outliers from trip distance analysis:\",(a-d))\n    \n    t_df = df[(df.speed <= 60) & (df.speed >= 0)]\n    e = t_df.shape[0]\n    print (\"Number of outliers from speed analysis:\",(a-e))\n    \n    # for total_amount i am going to take middle ground as AAi thinks 1000 should t=be the bond and i think 200 should be the bond. so 600\n    t_df = df[(df.total_amount <600) & (df.total_amount >0)]\n    f = t_df.shape[0]\n    print (\"Number of outliers from fare analysis:\",(a-f))\n    \n    \n    df = df[((df.dropoff_longitude >= -74.15) & (df.dropoff_longitude <= -73.7004) &\\\n                       (df.dropoff_latitude >= 40.5774) & (df.dropoff_latitude <= 40.9176)) & \\\n                       ((df.pickup_longitude >= -74.15) & (df.pickup_latitude >= 40.5774)& \\\n                       (df.pickup_longitude <= -73.7004) & (df.pickup_latitude <= 40.9176))]\n    \n    df = df[(df.duration > 0) & (df.duration < 720)]\n    df = df[(df.trip_distance > 0) & (df.trip_distance < 25)]\n    df = df[(df.speed < 60) & (df.speed > 0)]\n    df = df[(df.total_amount <600) & (df.total_amount >0)]\n    print (\"---\")\n    print (\"Total data before :\",a)\n    print (\"Total data after removal of outliers :\",df.shape[0])\n    print (\"Total outliers removed :\",a - df.shape[0])\n    print (\"---\")\n    return df\n```\n\n\n```python\nndf = remove_outliers(month)\n```\n\n    Number of pickup records =  12210952\n    Number of outlier coordinates lying outside NY boundaries: 232444\n    Number of outliers from trip duration analysis: 30837\n    Number of outliers from trip distance analysis: 82156\n    Number of outliers from speed analysis: 23987\n    Number of outliers from fare analysis: 5887\n    ---\n    Total data before : 12210952\n    Total data after removal of outliers : 11896583\n    Total outliers removed : 314369\n    ---\n\n\n# - Data-preperation\n## Clustering/Segmentation\n\n\n```python\ndef clusterization(data,k):\n    clu = MiniBatchKMeans(n_clusters=k,batch_size=10000,random_state=99).fit(data[['pickup_latitude', 'pickup_longitude']])\n    centers = clu.cluster_centers_\n    \n    min_dist = 999\n    for i in range(k):\n        dists = list()\n        for j in range(k):\n            if j!=i:\n                dist = gpxpy.geo.haversine_distance(centers[i][0], centers[i][1],centers[j][0], centers[j][1])\n                dists.append(dist/(1.60934*1000)) \n            \n        min_dist = min(min_dist,min(dists))\n        lt2 = sum(np.array(dists)<=2)\n        gt2 = len(dists)-lt2\n    \n    print('No. of Clusters: ',k)\n    print('No. of Clusters within 2 mile: ',lt2)\n    print('No. of Clusters further than 2 mile: ',gt2)\n    print('Avg. of Min Distances: ',min_dist)\n        \n```\n\n\n```python\nfor i in range(10,101,10):\n    \n    clusterization(ndf,i)\n    print('='*30)\n    \n```\n\n    No. of Clusters:  10\n    No. of Clusters within 2 mile:  0\n    No. of Clusters further than 2 mile:  9\n    Avg. of Min Distances:  0.8054068944707957\n    ==============================\n    No. of Clusters:  20\n    No. of Clusters within 2 mile:  4\n    No. of Clusters further than 2 mile:  15\n    Avg. of Min Distances:  0.7001785521327114\n    ==============================\n    No. of Clusters:  30\n    No. of Clusters within 2 mile:  14\n    No. of Clusters further than 2 mile:  15\n    Avg. of Min Distances:  0.4570133713392362\n    ==============================\n    No. of Clusters:  40\n    No. of Clusters within 2 mile:  7\n    No. of Clusters further than 2 mile:  32\n    Avg. of Min Distances:  0.35635440360862947\n    ==============================\n    No. of Clusters:  50\n    No. of Clusters within 2 mile:  17\n    No. of Clusters further than 2 mile:  32\n    Avg. of Min Distances:  0.18762600803268542\n    ==============================\n    No. of Clusters:  60\n    No. of Clusters within 2 mile:  28\n    No. of Clusters further than 2 mile:  31\n    Avg. of Min Distances:  0.23235748388749222\n    ==============================\n    No. of Clusters:  70\n    No. of Clusters within 2 mile:  32\n    No. of Clusters further than 2 mile:  37\n    Avg. of Min Distances:  0.1759123967325982\n    ==============================\n    No. of Clusters:  80\n    No. of Clusters within 2 mile:  12\n    No. of Clusters further than 2 mile:  67\n    Avg. of Min Distances:  0.20785701717708638\n    ==============================\n    No. of Clusters:  90\n    No. of Clusters within 2 mile:  31\n    No. of Clusters further than 2 mile:  58\n    Avg. of Min Distances:  0.18256625007491076\n    ==============================\n    No. of Clusters:  100\n    No. of Clusters within 2 mile:  33\n    No. of Clusters further than 2 mile:  66\n    Avg. of Min Distances:  0.1346901859283083\n    ==============================\n\n\n\n```python\n### k=30 looks good for random_state=99\n```\n\n\n```python\n# Plotting the cluster centers on OSM\nclu = MiniBatchKMeans(n_clusters=30,batch_size=10000,random_state=99).fit(ndf[['pickup_latitude', 'pickup_longitude']])\n#     centers = clu.cluster_centers_\ncluster_centers = clu.cluster_centers_\ncluster_len = len(cluster_centers)\nmap_osm = folium.Map(location=[40.734695, -73.990372], tiles='Stamen Toner')\nfor i in range(cluster_len):\n    folium.Marker(list((cluster_centers[i][0],cluster_centers[i][1])), popup=(str(cluster_centers[i][0])+str(cluster_centers[i][1]))).add_to(map_osm)\nmap_osm;\n```\n\n\n```python\n# Getting 30 clusters using the kmeans \nndf['cluster'] = clu.predict(ndf[['pickup_latitude', 'pickup_longitude']])\n```\n\n\n```python\n#Visualising the clusters on a map\ndef plot_clusters(df):\n    city_long_border = (-74.03, -73.75)\n    city_lat_border = (40.63, 40.85)\n    fig, ax = plt.subplots(ncols=1, nrows=1)\n    ax.scatter(df.pickup_longitude.values, df.pickup_latitude.values, s=10, lw=0,\n               c=df.cluster.values, cmap='tab20', alpha=0.2)\n    ax.set_xlim(city_long_border)\n    ax.set_ylim(city_lat_border)\n    ax.set_xlabel('Longitude')\n    ax.set_ylabel('Latitude')\n    plt.close()\n    # plt.show()\n\nplot_clusters(ndf)\n```\n\n\n```python\nndf.to_csv('data/ndf.csv')\n```\n\n---- \nCheckpoint\n\n----\n\n\n```python\nndf = pd.read_csv('data/ndf.csv',index_col=0)\n```\n\n\n```python\nndf.reset_index(drop=True,inplace=True)\n```\n\n\n```python\ndt = datetime(2015, 3, 1)\ntime.mktime(datetime(2015, 3, 1).timetuple())+19800\n```\n\n\n\n\n    1425168000.0\n\n\n\n\n```python\ndef convert_to_unix(s):\n    return time.mktime(datetime.datetime.strptime(s, \"%Y-%m-%d %H:%M:%S\").timetuple())\n```\n\n\n```python\n(1420070400-1420050600)\n```\n\n\n\n\n    19800\n\n\n\n\n```python\ndef time_binning(df,y,m):\n    # unix_pickup_times=[i for i in df['pickup_times'].values]\n    # unix_times = [[1420070400,1422748800,1425168000,1427846400,1430438400,1433116800],\\\n    #                 [1451606400,1454284800,1456790400,1459468800,1462060800,1464739200]]\n    # start_pickup_unix=unix_times[year-2015][month-1]\n    \n    df['unix_pickup'] = df.tpep_pickup_datetime.apply(lambda x: time.mktime(datetime.strptime(x, \"%Y-%m-%d %H:%M:%S\").timetuple()))\n    std_unix = time.mktime(datetime(y,m,1).timetuple())+19800\n    # https://www.timeanddate.com/time/zones/est\n    # (int((i-start_pickup_unix)/600)+33) : our unix time is in gmt to we are converting it to est\n    bins=[int(((i+19800)-std_unix)/600) for i in df['unix_pickup'].values] # this can aslo be thought as  [(i+19800) - std_unix]/600 similar to what we did while computing std_unix\n    df['pickup_bins'] = np.array(bins)\n    return df\n```\n\n\n```python\nndf = time_binning(ndf,2016,3)\n```\n\n\n```python\nndf_gb = ndf[['cluster','pickup_bins','trip_distance']].groupby(['cluster','pickup_bins']).count()\n```\n\n\n```python\nndf_gb\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>trip_distance</th>\n    </tr>\n    <tr>\n      <th>cluster</th>\n      <th>pickup_bins</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">0</th>\n      <th>0</th>\n      <td>40</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>36</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>35</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>34</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>22</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <th>...</th>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">29</th>\n      <th>4459</th>\n      <td>174</td>\n    </tr>\n    <tr>\n      <th>4460</th>\n      <td>168</td>\n    </tr>\n    <tr>\n      <th>4461</th>\n      <td>167</td>\n    </tr>\n    <tr>\n      <th>4462</th>\n      <td>140</td>\n    </tr>\n    <tr>\n      <th>4463</th>\n      <td>147</td>\n    </tr>\n  </tbody>\n</table>\n<p>132635 rows \u00d7 1 columns</p>\n</div>\n\n\n\n* ### Data Preparation Function\n\n\n```python\n# upto now we cleaned data and prepared data for the month 2016,\n\n# now do the same operations for months Jan, Feb, March of 2015\n# 1. get the dataframe which inlcudes only required colums\n# 2. adding trip times, speed, unix time stamp of pickup_time\n# 4. remove the outliers based on trip_times, speed, trip_duration, total_amount\n# 5. add pickup_cluster to each data point\n# 6. add pickup_bin (index of 10min intravel to which that trip belongs to)\n# 7. group by data, based on 'pickup_cluster' and 'pickuo_bin'\n\n# Data Preparation for the months of Jan,Feb and March 2015\ndef data_preparation(df,kmeans,y,m):\n\n    print (\"Claculating 'duration' and 'speed' & Remove outliers..\")\n    df = remove_outliers(df)\n    \n    print (\"Estimating clusters..\")\n    df['cluster'] = kmeans.predict(df[['pickup_latitude', 'pickup_longitude']])\n\n    print (\"Final groupbying..\")\n    df = time_binning(df,y,m)\n    df_gb = df[['cluster','pickup_bins','trip_distance']].groupby(['cluster','pickup_bins']).count()\n    print('Completed')\n    return df,df_gb    \n\n```\n\n\n```python\njan_2015 = dd.read_csv('data/raw/yellow_tripdata_2015-01.csv')\nfeb_2015 = dd.read_csv('data/raw/yellow_tripdata_2015-02.csv')\nmar_2015 = dd.read_csv('data/raw/yellow_tripdata_2015-03.csv')\n\ndf_1501,dfgb_1501 = data_preparation(jan_2015,clu,2015,1)\ndf_1502,dfgb_1502 = data_preparation(feb_2015,clu,2015,2)\ndf_1503,dfgb_1503 = data_preparation(mar_2015,clu,2015,3)\n```\n\n\n```python\njan_2016 = dd.read_csv('data/raw/yellow_tripdata_2016-01.csv')\ndf_1601,dfgb_1601 = data_preparation(jan_2016,clu,2016,1)\n```\n\n\n```python\nclu_tbins = list()\nfor i in range(30):\n    clu_tbins.append(set(dfgb_1601.loc[i].index))\n```\n\n    4375\n    4390\n    4285\n    4355\n    4394\n    4383\n    4264\n    4372\n    4394\n    4394\n    4378\n    4379\n    4380\n    4397\n    4382\n    4388\n    4254\n    4385\n    4372\n    4356\n    4392\n    4385\n    3660\n    4387\n    4382\n    4363\n    4385\n    4388\n    4391\n    4394\n\n\n## - Smoothing\n\n\n```python\n# Gets the unique bins where pickup values are present for each each reigion\n\n# for each cluster region we will collect all the indices of 10min intravels in which the pickups are happened\n# we got an observation that there are some pickpbins that doesnt have any pickups\n\n#AAi method\ndef return_unq_pickup_bins(frame):\n    values = []\n    for i in range(0,40):\n        new = frame[frame['cluster'] == i]\n        list_unq = list(set(new['pickup_bins']))\n        list_unq.sort()\n        values.append(list_unq)\n    return values\n\n# Alternat - My method\ndef unique_cluster_time_bins(df):\n    clu_tbins = list()\n    for i in range(30):\n        clu_tbins.append(set(df.loc[i].index))\n    return clu_tbins\n```\n\n\n```python\ndfgb_1603 = ndf_gb\ndf_1603 = ndf\nuni_clu_tbins_1501 = unique_cluster_time_bins(dfgb_1501)\nuni_clu_tbins_1502 = unique_cluster_time_bins(dfgb_1502)\nuni_clu_tbins_1503 = unique_cluster_time_bins(dfgb_1503)\nuni_clu_tbins_1601 = unique_cluster_time_bins(dfgb_1601)\nuni_clu_tbins_1603 = unique_cluster_time_bins(dfgb_1603)\n```\n\n#### We have been doing all the first shot processing on the 2016/03 data hence will continue to do so using db_1603 and dfgb_1603\n\n\n```python\nlen(df_1603.pickup_bins.unique())\n```\n\n\n\n\n    4464\n\n\n\n\n```python\n# for each cluster number of 10min intravels with 0 pickups\nfor i in range(30):\n    print(\"for the \",i,\"th cluster number of 10min intervals with zero pickups: \",4464 - len(uni_clu_tbins_1603[i]))\n    print('-'*60)\n```\n\n    for the  0 th cluster number of 10min intervals with zero pickups:  6\n    ------------------------------------------------------------\n    for the  1 th cluster number of 10min intervals with zero pickups:  6\n    ------------------------------------------------------------\n    for the  2 th cluster number of 10min intervals with zero pickups:  107\n    ------------------------------------------------------------\n    for the  3 th cluster number of 10min intervals with zero pickups:  16\n    ------------------------------------------------------------\n    for the  4 th cluster number of 10min intervals with zero pickups:  5\n    ------------------------------------------------------------\n    for the  5 th cluster number of 10min intervals with zero pickups:  5\n    ------------------------------------------------------------\n    for the  6 th cluster number of 10min intervals with zero pickups:  138\n    ------------------------------------------------------------\n    for the  7 th cluster number of 10min intervals with zero pickups:  6\n    ------------------------------------------------------------\n    for the  8 th cluster number of 10min intervals with zero pickups:  5\n    ------------------------------------------------------------\n    for the  9 th cluster number of 10min intervals with zero pickups:  5\n    ------------------------------------------------------------\n    for the  10 th cluster number of 10min intervals with zero pickups:  6\n    ------------------------------------------------------------\n    for the  11 th cluster number of 10min intervals with zero pickups:  9\n    ------------------------------------------------------------\n    for the  12 th cluster number of 10min intervals with zero pickups:  5\n    ------------------------------------------------------------\n    for the  13 th cluster number of 10min intervals with zero pickups:  4\n    ------------------------------------------------------------\n    for the  14 th cluster number of 10min intervals with zero pickups:  6\n    ------------------------------------------------------------\n    for the  15 th cluster number of 10min intervals with zero pickups:  6\n    ------------------------------------------------------------\n    for the  16 th cluster number of 10min intervals with zero pickups:  74\n    ------------------------------------------------------------\n    for the  17 th cluster number of 10min intervals with zero pickups:  3\n    ------------------------------------------------------------\n    for the  18 th cluster number of 10min intervals with zero pickups:  7\n    ------------------------------------------------------------\n    for the  19 th cluster number of 10min intervals with zero pickups:  30\n    ------------------------------------------------------------\n    for the  20 th cluster number of 10min intervals with zero pickups:  4\n    ------------------------------------------------------------\n    for the  21 th cluster number of 10min intervals with zero pickups:  6\n    ------------------------------------------------------------\n    for the  22 th cluster number of 10min intervals with zero pickups:  787\n    ------------------------------------------------------------\n    for the  23 th cluster number of 10min intervals with zero pickups:  7\n    ------------------------------------------------------------\n    for the  24 th cluster number of 10min intervals with zero pickups:  4\n    ------------------------------------------------------------\n    for the  25 th cluster number of 10min intervals with zero pickups:  9\n    ------------------------------------------------------------\n    for the  26 th cluster number of 10min intervals with zero pickups:  8\n    ------------------------------------------------------------\n    for the  27 th cluster number of 10min intervals with zero pickups:  1\n    ------------------------------------------------------------\n    for the  28 th cluster number of 10min intervals with zero pickups:  5\n    ------------------------------------------------------------\n    for the  29 th cluster number of 10min intervals with zero pickups:  5\n    ------------------------------------------------------------\n\n\n\n```python\n# AAI method\n\n# Fills a value of zero for every bin where no pickup data is present \n# the count_values: number pickps that are happened in each region for each 10min intravel\n# there wont be any value if there are no picksups.\n# values: number of unique bins\n\n# for every 10min intravel(pickup_bin) we will check it is there in our unique bin,\n# if it is there we will add the count_values[index] to smoothed data\n# if not we add 0 to the smoothed data\n# we finally return smoothed data\n\n\ndef fill_missing(count_values,values):\n    smoothed_regions=[]\n    ind=0\n    for r in range(0,30):\n        smoothed_bins=[]\n        for i in range(4464):\n            if i in values[r]:\n                smoothed_bins.append(count_values[ind])\n                ind+=1\n            else:\n                smoothed_bins.append(0)\n        smoothed_regions.extend(smoothed_bins)\n    return smoothed_regions\n```\n\n#### My method\n\n\n```python\nw0_dfgb_1603 = dfgb_1603.unstack(fill_value=0)\nw0_dfgb_1603\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n\n    .dataframe thead tr:last-of-type th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th colspan=\"21\" halign=\"left\">trip_distance</th>\n    </tr>\n    <tr>\n      <th>pickup_bins</th>\n      <th>0</th>\n      <th>1</th>\n      <th>2</th>\n      <th>3</th>\n      <th>4</th>\n      <th>5</th>\n      <th>6</th>\n      <th>7</th>\n      <th>8</th>\n      <th>9</th>\n      <th>...</th>\n      <th>4454</th>\n      <th>4455</th>\n      <th>4456</th>\n      <th>4457</th>\n      <th>4458</th>\n      <th>4459</th>\n      <th>4460</th>\n      <th>4461</th>\n      <th>4462</th>\n      <th>4463</th>\n    </tr>\n    <tr>\n      <th>cluster</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>40</td>\n      <td>36</td>\n      <td>35</td>\n      <td>34</td>\n      <td>22</td>\n      <td>21</td>\n      <td>16</td>\n      <td>29</td>\n      <td>15</td>\n      <td>9</td>\n      <td>...</td>\n      <td>131</td>\n      <td>130</td>\n      <td>129</td>\n      <td>126</td>\n      <td>129</td>\n      <td>138</td>\n      <td>123</td>\n      <td>129</td>\n      <td>108</td>\n      <td>88</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>106</td>\n      <td>90</td>\n      <td>93</td>\n      <td>82</td>\n      <td>85</td>\n      <td>64</td>\n      <td>58</td>\n      <td>48</td>\n      <td>62</td>\n      <td>52</td>\n      <td>...</td>\n      <td>383</td>\n      <td>333</td>\n      <td>289</td>\n      <td>307</td>\n      <td>287</td>\n      <td>308</td>\n      <td>273</td>\n      <td>282</td>\n      <td>229</td>\n      <td>221</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>77</td>\n      <td>59</td>\n      <td>45</td>\n      <td>48</td>\n      <td>42</td>\n      <td>51</td>\n      <td>51</td>\n      <td>37</td>\n      <td>21</td>\n      <td>5</td>\n      <td>...</td>\n      <td>80</td>\n      <td>87</td>\n      <td>82</td>\n      <td>79</td>\n      <td>78</td>\n      <td>84</td>\n      <td>78</td>\n      <td>49</td>\n      <td>67</td>\n      <td>65</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>40</td>\n      <td>22</td>\n      <td>11</td>\n      <td>27</td>\n      <td>33</td>\n      <td>9</td>\n      <td>2</td>\n      <td>7</td>\n      <td>6</td>\n      <td>4</td>\n      <td>...</td>\n      <td>140</td>\n      <td>138</td>\n      <td>131</td>\n      <td>144</td>\n      <td>147</td>\n      <td>138</td>\n      <td>129</td>\n      <td>145</td>\n      <td>82</td>\n      <td>71</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>39</td>\n      <td>31</td>\n      <td>13</td>\n      <td>26</td>\n      <td>19</td>\n      <td>12</td>\n      <td>15</td>\n      <td>20</td>\n      <td>19</td>\n      <td>17</td>\n      <td>...</td>\n      <td>122</td>\n      <td>89</td>\n      <td>112</td>\n      <td>108</td>\n      <td>101</td>\n      <td>104</td>\n      <td>82</td>\n      <td>84</td>\n      <td>69</td>\n      <td>65</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>45</td>\n      <td>55</td>\n      <td>45</td>\n      <td>28</td>\n      <td>29</td>\n      <td>29</td>\n      <td>30</td>\n      <td>30</td>\n      <td>29</td>\n      <td>14</td>\n      <td>...</td>\n      <td>189</td>\n      <td>215</td>\n      <td>172</td>\n      <td>187</td>\n      <td>160</td>\n      <td>148</td>\n      <td>142</td>\n      <td>152</td>\n      <td>141</td>\n      <td>114</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>9</td>\n      <td>11</td>\n      <td>9</td>\n      <td>11</td>\n      <td>5</td>\n      <td>10</td>\n      <td>9</td>\n      <td>10</td>\n      <td>8</td>\n      <td>4</td>\n      <td>...</td>\n      <td>15</td>\n      <td>20</td>\n      <td>19</td>\n      <td>18</td>\n      <td>19</td>\n      <td>14</td>\n      <td>20</td>\n      <td>16</td>\n      <td>20</td>\n      <td>22</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>19</td>\n      <td>21</td>\n      <td>30</td>\n      <td>20</td>\n      <td>18</td>\n      <td>19</td>\n      <td>23</td>\n      <td>10</td>\n      <td>13</td>\n      <td>18</td>\n      <td>...</td>\n      <td>44</td>\n      <td>63</td>\n      <td>51</td>\n      <td>43</td>\n      <td>49</td>\n      <td>48</td>\n      <td>48</td>\n      <td>48</td>\n      <td>42</td>\n      <td>49</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>47</td>\n      <td>53</td>\n      <td>45</td>\n      <td>43</td>\n      <td>34</td>\n      <td>24</td>\n      <td>30</td>\n      <td>20</td>\n      <td>20</td>\n      <td>12</td>\n      <td>...</td>\n      <td>119</td>\n      <td>154</td>\n      <td>148</td>\n      <td>141</td>\n      <td>112</td>\n      <td>113</td>\n      <td>90</td>\n      <td>88</td>\n      <td>76</td>\n      <td>84</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>60</td>\n      <td>57</td>\n      <td>47</td>\n      <td>55</td>\n      <td>45</td>\n      <td>57</td>\n      <td>50</td>\n      <td>41</td>\n      <td>37</td>\n      <td>34</td>\n      <td>...</td>\n      <td>215</td>\n      <td>204</td>\n      <td>215</td>\n      <td>211</td>\n      <td>228</td>\n      <td>221</td>\n      <td>208</td>\n      <td>228</td>\n      <td>197</td>\n      <td>185</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>61</td>\n      <td>64</td>\n      <td>35</td>\n      <td>53</td>\n      <td>44</td>\n      <td>34</td>\n      <td>27</td>\n      <td>36</td>\n      <td>33</td>\n      <td>20</td>\n      <td>...</td>\n      <td>185</td>\n      <td>151</td>\n      <td>171</td>\n      <td>157</td>\n      <td>166</td>\n      <td>206</td>\n      <td>162</td>\n      <td>186</td>\n      <td>164</td>\n      <td>171</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>15</td>\n      <td>14</td>\n      <td>8</td>\n      <td>6</td>\n      <td>14</td>\n      <td>17</td>\n      <td>16</td>\n      <td>9</td>\n      <td>3</td>\n      <td>9</td>\n      <td>...</td>\n      <td>90</td>\n      <td>79</td>\n      <td>91</td>\n      <td>75</td>\n      <td>68</td>\n      <td>64</td>\n      <td>76</td>\n      <td>43</td>\n      <td>40</td>\n      <td>44</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>75</td>\n      <td>73</td>\n      <td>60</td>\n      <td>47</td>\n      <td>34</td>\n      <td>46</td>\n      <td>41</td>\n      <td>37</td>\n      <td>26</td>\n      <td>46</td>\n      <td>...</td>\n      <td>226</td>\n      <td>214</td>\n      <td>216</td>\n      <td>234</td>\n      <td>210</td>\n      <td>240</td>\n      <td>196</td>\n      <td>223</td>\n      <td>206</td>\n      <td>239</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>21</td>\n      <td>18</td>\n      <td>18</td>\n      <td>7</td>\n      <td>14</td>\n      <td>20</td>\n      <td>14</td>\n      <td>25</td>\n      <td>17</td>\n      <td>11</td>\n      <td>...</td>\n      <td>12</td>\n      <td>12</td>\n      <td>22</td>\n      <td>15</td>\n      <td>18</td>\n      <td>11</td>\n      <td>21</td>\n      <td>20</td>\n      <td>13</td>\n      <td>16</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>14</td>\n      <td>14</td>\n      <td>17</td>\n      <td>22</td>\n      <td>16</td>\n      <td>16</td>\n      <td>11</td>\n      <td>7</td>\n      <td>14</td>\n      <td>9</td>\n      <td>...</td>\n      <td>14</td>\n      <td>23</td>\n      <td>19</td>\n      <td>13</td>\n      <td>21</td>\n      <td>21</td>\n      <td>20</td>\n      <td>19</td>\n      <td>29</td>\n      <td>14</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>89</td>\n      <td>52</td>\n      <td>62</td>\n      <td>50</td>\n      <td>39</td>\n      <td>53</td>\n      <td>27</td>\n      <td>37</td>\n      <td>32</td>\n      <td>44</td>\n      <td>...</td>\n      <td>204</td>\n      <td>196</td>\n      <td>224</td>\n      <td>199</td>\n      <td>197</td>\n      <td>199</td>\n      <td>157</td>\n      <td>159</td>\n      <td>148</td>\n      <td>126</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>27</td>\n      <td>36</td>\n      <td>34</td>\n      <td>30</td>\n      <td>26</td>\n      <td>26</td>\n      <td>23</td>\n      <td>25</td>\n      <td>33</td>\n      <td>27</td>\n      <td>...</td>\n      <td>26</td>\n      <td>25</td>\n      <td>37</td>\n      <td>34</td>\n      <td>44</td>\n      <td>47</td>\n      <td>57</td>\n      <td>50</td>\n      <td>42</td>\n      <td>43</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>85</td>\n      <td>73</td>\n      <td>83</td>\n      <td>64</td>\n      <td>62</td>\n      <td>53</td>\n      <td>49</td>\n      <td>33</td>\n      <td>36</td>\n      <td>34</td>\n      <td>...</td>\n      <td>206</td>\n      <td>220</td>\n      <td>217</td>\n      <td>221</td>\n      <td>255</td>\n      <td>235</td>\n      <td>219</td>\n      <td>225</td>\n      <td>238</td>\n      <td>226</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>36</td>\n      <td>38</td>\n      <td>42</td>\n      <td>20</td>\n      <td>27</td>\n      <td>23</td>\n      <td>25</td>\n      <td>19</td>\n      <td>20</td>\n      <td>24</td>\n      <td>...</td>\n      <td>164</td>\n      <td>145</td>\n      <td>139</td>\n      <td>128</td>\n      <td>142</td>\n      <td>119</td>\n      <td>121</td>\n      <td>96</td>\n      <td>100</td>\n      <td>81</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>18</td>\n      <td>15</td>\n      <td>10</td>\n      <td>5</td>\n      <td>3</td>\n      <td>6</td>\n      <td>2</td>\n      <td>14</td>\n      <td>10</td>\n      <td>4</td>\n      <td>...</td>\n      <td>9</td>\n      <td>14</td>\n      <td>16</td>\n      <td>13</td>\n      <td>8</td>\n      <td>18</td>\n      <td>15</td>\n      <td>17</td>\n      <td>18</td>\n      <td>11</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>121</td>\n      <td>83</td>\n      <td>70</td>\n      <td>86</td>\n      <td>87</td>\n      <td>66</td>\n      <td>66</td>\n      <td>55</td>\n      <td>51</td>\n      <td>54</td>\n      <td>...</td>\n      <td>245</td>\n      <td>230</td>\n      <td>219</td>\n      <td>217</td>\n      <td>234</td>\n      <td>241</td>\n      <td>207</td>\n      <td>216</td>\n      <td>222</td>\n      <td>209</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>51</td>\n      <td>72</td>\n      <td>36</td>\n      <td>52</td>\n      <td>53</td>\n      <td>37</td>\n      <td>40</td>\n      <td>49</td>\n      <td>39</td>\n      <td>27</td>\n      <td>...</td>\n      <td>193</td>\n      <td>144</td>\n      <td>153</td>\n      <td>184</td>\n      <td>150</td>\n      <td>179</td>\n      <td>190</td>\n      <td>182</td>\n      <td>167</td>\n      <td>178</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>3</td>\n      <td>0</td>\n      <td>0</td>\n      <td>4</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>...</td>\n      <td>0</td>\n      <td>2</td>\n      <td>2</td>\n      <td>1</td>\n      <td>2</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>84</td>\n      <td>81</td>\n      <td>43</td>\n      <td>55</td>\n      <td>54</td>\n      <td>32</td>\n      <td>32</td>\n      <td>35</td>\n      <td>26</td>\n      <td>32</td>\n      <td>...</td>\n      <td>201</td>\n      <td>229</td>\n      <td>220</td>\n      <td>223</td>\n      <td>187</td>\n      <td>192</td>\n      <td>153</td>\n      <td>156</td>\n      <td>171</td>\n      <td>148</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>53</td>\n      <td>44</td>\n      <td>33</td>\n      <td>27</td>\n      <td>33</td>\n      <td>33</td>\n      <td>25</td>\n      <td>13</td>\n      <td>21</td>\n      <td>13</td>\n      <td>...</td>\n      <td>276</td>\n      <td>324</td>\n      <td>202</td>\n      <td>133</td>\n      <td>142</td>\n      <td>142</td>\n      <td>128</td>\n      <td>101</td>\n      <td>101</td>\n      <td>101</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>27</td>\n      <td>20</td>\n      <td>15</td>\n      <td>23</td>\n      <td>18</td>\n      <td>13</td>\n      <td>12</td>\n      <td>17</td>\n      <td>25</td>\n      <td>14</td>\n      <td>...</td>\n      <td>35</td>\n      <td>35</td>\n      <td>61</td>\n      <td>45</td>\n      <td>46</td>\n      <td>68</td>\n      <td>35</td>\n      <td>42</td>\n      <td>34</td>\n      <td>35</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>26</td>\n      <td>19</td>\n      <td>17</td>\n      <td>14</td>\n      <td>15</td>\n      <td>8</td>\n      <td>17</td>\n      <td>18</td>\n      <td>14</td>\n      <td>14</td>\n      <td>...</td>\n      <td>109</td>\n      <td>95</td>\n      <td>93</td>\n      <td>91</td>\n      <td>68</td>\n      <td>93</td>\n      <td>78</td>\n      <td>73</td>\n      <td>67</td>\n      <td>53</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>75</td>\n      <td>65</td>\n      <td>82</td>\n      <td>71</td>\n      <td>68</td>\n      <td>67</td>\n      <td>74</td>\n      <td>41</td>\n      <td>37</td>\n      <td>33</td>\n      <td>...</td>\n      <td>177</td>\n      <td>211</td>\n      <td>218</td>\n      <td>231</td>\n      <td>223</td>\n      <td>249</td>\n      <td>238</td>\n      <td>244</td>\n      <td>209</td>\n      <td>219</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>45</td>\n      <td>25</td>\n      <td>24</td>\n      <td>30</td>\n      <td>25</td>\n      <td>21</td>\n      <td>21</td>\n      <td>18</td>\n      <td>10</td>\n      <td>14</td>\n      <td>...</td>\n      <td>119</td>\n      <td>126</td>\n      <td>110</td>\n      <td>118</td>\n      <td>111</td>\n      <td>120</td>\n      <td>104</td>\n      <td>83</td>\n      <td>76</td>\n      <td>79</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>51</td>\n      <td>52</td>\n      <td>41</td>\n      <td>36</td>\n      <td>19</td>\n      <td>34</td>\n      <td>18</td>\n      <td>30</td>\n      <td>17</td>\n      <td>17</td>\n      <td>...</td>\n      <td>192</td>\n      <td>205</td>\n      <td>199</td>\n      <td>167</td>\n      <td>164</td>\n      <td>174</td>\n      <td>168</td>\n      <td>167</td>\n      <td>140</td>\n      <td>147</td>\n    </tr>\n  </tbody>\n</table>\n<p>30 rows \u00d7 4464 columns</p>\n</div>\n\n\n\n\n```python\nw0_dfgb_1603.shape[1]==(6*24*31) # is the all possible 10 min time intervals in the month of March i.e 4464 \n```\n\n\n\n\n    True\n\n\n\n#### Checking our method vs AAI method provide us with the same output\n\n\n```python\nlist(w0_dfgb_1603.stack().trip_distance.values);\n```\n\n\n```python\ntemp_tbins = fill_missing(dfgb_1603.trip_distance.values,uni_clu_tbins_1603)\n```\n\n\n```python\ntemp_tbins;\n```\n\n\n```python\nlist(w0_dfgb_1603.stack().trip_distance.values)==temp_tbins\n```\n\n\n\n\n    True\n\n\n\n#### Hence we can see our output are totallt same\n\nthere are two ways to fill up these values\n<ul>\n<li> Fill the missing value with 0's</li>\n<li> Fill the missing values with the avg values\n<ul>\n<li> Case 1:(values missing at the start)  <br>Ex1: \\_ \\_ \\_ x =>ceil(x/4), ceil(x/4), ceil(x/4), ceil(x/4) <br> Ex2: \\_ \\_ x => ceil(x/3), ceil(x/3), ceil(x/3) </li>\n<li> Case 2:(values missing in middle) <br>Ex1: x \\_ \\_ y => ceil((x+y)/4), ceil((x+y)/4), ceil((x+y)/4), ceil((x+y)/4) <br> Ex2: x \\_ \\_ \\_ y => ceil((x+y)/5), ceil((x+y)/5), ceil((x+y)/5), ceil((x+y)/5), ceil((x+y)/5) </li>\n<li> Case 3:(values missing at the end)  <br>Ex1: x \\_ \\_ \\_  => ceil(x/4), ceil(x/4), ceil(x/4), ceil(x/4) <br> Ex2: x \\_  => ceil(x/2), ceil(x/2) </li>\n</ul>\n</li>\n</ul>\n\n\n```python\n# Fills a value of zero for every bin where no pickup data is present \n# the count_values: number pickps that are happened in each region for each 10min intravel\n# there wont be any value if there are no picksups.\n# values: number of unique bins\n\n# for every 10min intravel(pickup_bin) we will check it is there in our unique bin,\n# if it is there we will add the count_values[index] to smoothed data\n# if not we add smoothed data (which is calculated based on the methods that are discussed in the above markdown cell)\n# we finally return smoothed data\ndef smoothing(count_values,values):\n    smoothed_regions=[] # stores list of final smoothed values of each reigion\n    ind=0\n    repeat=0 \n    smoothed_value=0\n    for r in range(0,30):\n        smoothed_bins=[] #stores the final smoothed values\n        repeat=0\n        for i in range(4464):\n            if repeat!=0: # prevents iteration for a value which is already visited/resolved\n                repeat-=1\n                continue\n            if i in values[r]: #checks if the pickup-bin exists \n                smoothed_bins.append(count_values[ind]) # appends the value of the pickup bin if it exists\n            else:\n                if i!=0:\n                    right_hand_limit=0\n                    for j in range(i,4464):\n                        if  j not in values[r]: #searches for the left-limit or the pickup-bin value which has a pickup value\n                            continue\n                        else:\n                            right_hand_limit=j\n                            break\n                    if right_hand_limit==0:\n                    #Case 1: When we have the last/last few values are found to be missing,hence we have no right-limit here\n                        smoothed_value=count_values[ind-1]*1.0/((4463-i)+2)*1.0                               \n                        for j in range(i,4464):                              \n                            smoothed_bins.append(math.ceil(smoothed_value))\n                        smoothed_bins[i-1] = math.ceil(smoothed_value)\n                        repeat=(4463-i)\n                        ind-=1\n                    else:\n                    #Case 2: When we have the missing values between two known values\n                        smoothed_value=(count_values[ind-1]+count_values[ind])*1.0/((right_hand_limit-i)+2)*1.0             \n                        for j in range(i,right_hand_limit+1):\n                            smoothed_bins.append(math.ceil(smoothed_value))\n                        smoothed_bins[i-1] = math.ceil(smoothed_value)\n                        repeat=(right_hand_limit-i)\n                else:\n                    #Case 3: When we have the first/first few values are found to be missing,hence we have no left-limit here\n                    right_hand_limit=0\n                    for j in range(i,4464):\n                        if  j not in values[r]:\n                            continue\n                        else:\n                            right_hand_limit=j\n                            break\n                    smoothed_value=count_values[ind]*1.0/((right_hand_limit-i)+1)*1.0\n                    for j in range(i,right_hand_limit+1):\n                            smoothed_bins.append(math.ceil(smoothed_value))\n                    repeat=(right_hand_limit-i)\n            ind+=1\n        smoothed_regions.extend(smoothed_bins)\n    return smoothed_regions\n\n```\n\n\n```python\nsmth_dfgb_1603 = smoothing(dfgb_1603.trip_distance.values,uni_clu_tbins_1603)\n```\n\n\n```python\nlen(smth_dfgb_1603) == 30*4464 # No of clusers * No of time bins in march month\n```\n\n\n\n\n    True\n\n\n\n\n```python\nprint(len(w0_dfgb_1603.stack().trip_distance.values)) \nprint(len(temp_tbins))\nprint(len(smth_dfgb_1603))\nprint(30*4464)\n```\n\n    133920\n    133920\n    133920\n    133920\n\n\n\n```python\n# Smoothing vs Filling\n# sample plot that shows two variations of filling missing values\n# we have taken the number of pickups for cluster region 2\nplt.figure(figsize=(10,10),frameon=False)\nplt.plot(temp_tbins[4464:8920], label=\"zero filled values\",c='y')\nplt.plot(smth_dfgb_1603[4464:8920], label=\"filled with avg values\",c='r' )\n# plt.legend()\nplt.show()\n```\n\n\n```python\nnp.array(temp_tbins[4464:8920])\n```\n\n\n\n\n    array([106,  90,  93, ..., 300, 383, 333], dtype=int64)\n\n\n\n\n```python\n# Mar-2016 data is smoothed, Jan,Feb & March 2015 data missing values are filled with zero\n# smth_dfgb_1603 = smoothing(dfgb_1603.trip_distance.values,uni_clu_tbins_1603)\n\n\nw0_cnt_1501=list(dfgb_1501.unstack(fill_value=0).stack().trip_distance.values)\nw0_cnt_1502=list(dfgb_1502.unstack(fill_value=0).stack().trip_distance.values)\nw0_cnt_1503=list(dfgb_1503.unstack(fill_value=0).stack().trip_distance.values)\n\n\n```\n\n\n```python\n# df_1501,dfgb_1501 \n# df_1502,dfgb_1502\n# df_1503,dfgb_1503\n# df_1601,dfgb_1601\n# df_1603,dfgb_1603\n\n# uni_clu_tbins_1501\n# uni_clu_tbins_1502\n# uni_clu_tbins_1503\n# uni_clu_tbins_1601\n# uni_clu_tbins_1603\n\n# w0_dfgb_1603\n# smth_dfgb_1603\n# w0_cnt_1501\n# w0_cnt_1502\n# w0_cnt_1503\n\nwith open(\"data/chkpt1.pickle\",\"wb\") as f:\n    # pickle.dump(df_1501, f)\n    # pickle.dump(df_1502, f)\n    # pickle.dump(df_1503, f)\n    # pickle.dump(df_1601, f)\n    # pickle.dump(df_1603, f)\n    # pickle.dump(dfgb_1501, f)\n    # pickle.dump(dfgb_1502, f)\n    # pickle.dump(dfgb_1503, f)\n    # pickle.dump(dfgb_1601, f)\n    # pickle.dump(dfgb_1603, f)\n    pickle.dump(uni_clu_tbins_1501, f)\n    pickle.dump(uni_clu_tbins_1502, f)\n    pickle.dump(uni_clu_tbins_1503, f)\n    pickle.dump(uni_clu_tbins_1601, f)\n    pickle.dump(uni_clu_tbins_1603, f)\n    pickle.dump(w0_dfgb_1603, f)\n    pickle.dump(smth_dfgb_1603, f)\n    pickle.dump(w0_cnt_1501, f)\n    pickle.dump(w0_cnt_1502, f)\n    pickle.dump(w0_cnt_1503, f)\n\n# len(df_1501),len(df_1502),len(df_1503),len(df_1601),len(df_1603),len(dfgb_1501),len(dfgb_1502),len(dfgb_1503),len(dfgb_1601),len(dfgb_1603),len(uni_clu_tbins_1501),len(uni_clu_tbins_1502),len(uni_clu_tbins_1503),len(uni_clu_tbins_1601),len(uni_clu_tbins_1603),len(w0_dfgb_1603),len(smth_dfgb_1603),len(w0_cnt_1501),len(w0_cnt_1502),len(w0_cnt_1503)\n```\n\n\n```python\nwith open(\"data/chkpt1.pickle\", \"rb\") as f:\n    # df_1501 = pickle.load(f)\n    # df_1502 = pickle.load(f)\n    # df_1503 = pickle.load(f)\n    # df_1601 = pickle.load(f)\n    # df_1603 = pickle.load(f)\n    # dfgb_1501 = pickle.load(f)\n    # dfgb_1502 = pickle.load(f)\n    # dfgb_1503 = pickle.load(f)\n    # dfgb_1601 = pickle.load(f)\n    # dfgb_1603 = pickle.load(f)\n    uni_clu_tbins_1501 = pickle.load(f)\n    uni_clu_tbins_1502 = pickle.load(f)\n    uni_clu_tbins_1503 = pickle.load(f)\n    uni_clu_tbins_1601 = pickle.load(f)\n    uni_clu_tbins_1603 = pickle.load(f)\n    w0_dfgb_1603 = pickle.load(f)\n    smth_dfgb_1603 = pickle.load(f)\n    w0_cnt_1501 = pickle.load(f)\n    w0_cnt_1502 = pickle.load(f)\n    w0_cnt_1503 = pickle.load(f)\n\n# len(df_1501),len(df_1502),len(df_1503),len(df_1601),len(df_1603),len(dfgb_1501),len(dfgb_1502),len(dfgb_1503),len(dfgb_1601),len(dfgb_1603),len(uni_clu_tbins_1501),len(uni_clu_tbins_1502),len(uni_clu_tbins_1503),len(uni_clu_tbins_1601),len(uni_clu_tbins_1603),len(w0_dfgb_1603),len(smth_dfgb_1603),len(w0_cnt_1501),len(w0_cnt_1502),len(w0_cnt_1503)\n```\n\n\n```python\n# Making list of all the values of pickup data in every bin for a period of 3 months and storing them region-wise \nregions_cum = []\n\n# a =[1,2,3]\n# b = [2,3,4]\n# a+b = [1, 2, 3, 2, 3, 4]\n\n# number of 10min indices for march 2016= 24*31*60/10 = 4464\n# number of 10min indices for jan 2015 = 24*31*60/10 = 4464\n# number of 10min indices for feb 2015 = 24*28*60/10 = 4032\n# number of 10min indices for march 2015 = 24*31*60/10 = 4464\n# regions_cum: it will contain 40 lists, each list will contain 4464+4032+4464 values which represents the number of pickups \n# that are happened for three months in 2016 data\n\nfor i in range(0,30):\n    regions_cum.append(w0_cnt_1501[4464*i:4464*(i+1)]+w0_cnt_1502[4032*i:4032*(i+1)]+w0_cnt_1503[4464*i:4464*(i+1)])\n```\n\n\n```python\nlen(regions_cum)\n```\n\n\n\n\n    30\n\n\n\n\n```python\n# 4464+4032+4464 = 12960\nfor i in range(30):\n    print(len(regions_cum[i]))\n```\n\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n    12960\n\n\n* ## Time series and Fourier Transforms\n\n\n```python\ndef uniqueish_color():\n    \"\"\"There're better ways to generate unique colors, but this isn't awful.\"\"\"\n    return plt.cm.gist_ncar(np.random.random())\nfirst_x = list(range(0,4464))\nsecond_x = list(range(4464,8496))\nthird_x = list(range(8496,12960))\nfor i in range(30):\n    plt.figure(figsize=(10,4))\n    plt.plot(first_x,regions_cum[i][:4464], color=uniqueish_color(), label='2016 Jan month data')\n    plt.plot(second_x,regions_cum[i][4464:8496], color=uniqueish_color(), label='2016 feb month data')\n    plt.plot(third_x,regions_cum[i][8496:], color=uniqueish_color(), label='2016 march month data')\n    plt.title('Graph for {}th cluster'.format(i+1))\n    plt.legend()\n    # plt.show()\n    plt.close()\n```\n\n\n```python\n# getting peaks: https://blog.ytotech.com/2015/11/01/findpeaks-in-python/\n# read more about fft function : https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fft.html\nY    = np.fft.fft(np.array(smth_dfgb_1603)[0:4464]) # using data of march 2016 of cluster 1\n# read more about the fftfreq: https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fftfreq.html  \nfreq = np.fft.fftfreq(4460, 1)\nn = len(freq)\nplt.figure(figsize=(20,7))\nplt.plot( freq[:int(n/2)], np.abs(Y)[:int(n/2)] )\nplt.xlabel(\"Frequency\")\nplt.ylabel(\"Amplitude\")\nplt.show()\n```\n\n\n```python\n#Preparing the Dataframe only with x(i) values as march-2016 data and y(i) values as march-2015\nratios_march = pd.DataFrame()\nratios_march['Given']=smth_dfgb_1603\nratios_march['Prediction']=w0_cnt_1503\nratios_march['Ratios']=ratios_march['Prediction']*1.0/ratios_march['Given']*1.0\n```\n\n\n```python\nratios_march\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Given</th>\n      <th>Prediction</th>\n      <th>Ratios</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>40</td>\n      <td>169</td>\n      <td>4.225000</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>36</td>\n      <td>182</td>\n      <td>5.055556</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>35</td>\n      <td>180</td>\n      <td>5.142857</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>34</td>\n      <td>169</td>\n      <td>4.970588</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>22</td>\n      <td>196</td>\n      <td>8.909091</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>133915</th>\n      <td>174</td>\n      <td>133</td>\n      <td>0.764368</td>\n    </tr>\n    <tr>\n      <th>133916</th>\n      <td>168</td>\n      <td>107</td>\n      <td>0.636905</td>\n    </tr>\n    <tr>\n      <th>133917</th>\n      <td>167</td>\n      <td>85</td>\n      <td>0.508982</td>\n    </tr>\n    <tr>\n      <th>133918</th>\n      <td>140</td>\n      <td>87</td>\n      <td>0.621429</td>\n    </tr>\n    <tr>\n      <th>133919</th>\n      <td>147</td>\n      <td>100</td>\n      <td>0.680272</td>\n    </tr>\n  </tbody>\n</table>\n<p>133920 rows \u00d7 3 columns</p>\n</div>\n\n\n\n## Modelling: Baseline Models\n\nNow we get into modelling in order to forecast the pickup densities for the months of Jan, Feb and March of 2016 for which we are using multiple models with two variations \n\n1. Using Ratios of the 2016 data to the 2015 data i.e $\\begin{align} R_{t} = P^{2016}_{t} / P^{2015}_{t} \\end{align}$\n\n2. Using Previous known values of the 2016 data itself to predict the future values\n\n### Simple Moving Averages\nThe First Model used is the Moving Averages Model which uses the previous n values in order to predict the next value <br> \n\n### Using Ratio Values - $\\begin{align}R_{t} = ( R_{t-1} + R_{t-2} + R_{t-3} .... R_{t-n} )/n \\end{align}$\n\n\n```python\n# one cluster\n24*6*31\n```\n\n\n\n\n    4464\n\n\n\n\n```python\n# smth_dfgb_1603[0:4464]\n# w0_cnt_1503[0:4464]\n\n# df1 = smth_dfgb_1603 # train data\n# df2 = w0_cnt_1503# test data\n\ndef sim_mov_avg(df1,df2,n):\n    preds = list()\n    preds.append(df2[0])\n    error = list()\n    error.append(0)\n    # error1 = list()\n    # error1.append(0)\n    for i in range(1,133920):\n        indx = max(i-n,0)\n        ratio = sum([i/j for i,j in zip(df2[indx:i],df1[indx:i])])/(i-indx)\n        pred_i = ratio*df1[i]\n        preds.append(pred_i)\n        # error1.append(abs(df2[i]-pred_i)/max(1,abs(df2[i])))\n        error.append(abs(math.pow(df2[i]-int(pred_i),1)))\n\n    y = np.array(w0_cnt_1503)\n    y_pred = np.array(preds)\n\n    # mape = sum(error1)/len(error1)\n    mape_err = (sum(error)/len(error))/(sum(y)/len(y))\n    mse_err = sum([e**2 for e in error])/len(error)\n    print('For n= {} \\n MAPE: {} \\n MSE: {}'.format(n,mape_err,mse_err))\n    return mape_err,mse_err \n```\n\n\n```python\nfor i in range(1,8):\n    sim_mov_avg(smth_dfgb_1603,w0_cnt_1503,i)\n```\n\n    For n= 1 \n     MAPE: 0.1881094398330249 \n     MSE: 26497.781145459976\n    For n= 2 \n     MAPE: 0.1787257273869427 \n     MSE: 23346.68452060932\n    For n= 3 \n     MAPE: 0.18161743718902607 \n     MSE: 33323.029577359615\n    For n= 4 \n     MAPE: 0.18882249586113622 \n     MSE: 45495.081907108724\n    For n= 5 \n     MAPE: 0.1980599107422901 \n     MSE: 61449.9875\n    For n= 6 \n     MAPE: 0.2081186588161095 \n     MSE: 79404.03341547192\n    For n= 7 \n     MAPE: 0.2181241937535027 \n     MSE: 81232.17676224612\n\n\nFor the above the Hyperparameter is the window-size (n) which is tuned manually and it is found that the window-size of 2 is optimal for getting the best results using Moving Averages using previous Ratio values therefore we get $\\begin{align}R_{t} = ( R_{t-1} + R_{t-2})/2 \\end{align}$\n\nNext we use the Moving averages of the 2015  values itself to predict the future value using $\\begin{align}P_{t} = ( P_{t-1} + P_{t-2} + P_{t-3} .... P_{t-n} )/n \\end{align}$\n\n\n```python\ndef sim_mov_avg_direct(df1,n):\n    preds = list()\n    preds.append(df1[0])\n    error = list()\n    error.append(0)\n    for i in range(1,133920):\n        indx = max(i-n,0)\n        sumoflast_nvalues_byn = sum(df1[indx:i])/(i-indx)\n        preds.append(sumoflast_nvalues_byn)\n        error.append(abs(math.pow(df1[i]-int(sumoflast_nvalues_byn),1)))\n\n    mape_err = (sum(error)/len(error))/(sum(df1)/len(df1))\n    mse_err = sum([e**2 for e in error])/len(error)\n    print('For n= {} \\n MAPE: {} \\n MSE: {}'.format(n,mape_err,mse_err))\n    return mape_err,mse_err \n```\n\n\n```python\nfor i in range(1,8):\n    sim_mov_avg_direct(w0_cnt_1503,i)\n```\n\n    For n= 1 \n     MAPE: 0.11792100440489088 \n     MSE: 286.1540397252091\n    For n= 2 \n     MAPE: 0.11598736241994219 \n     MSE: 286.3942502986858\n    For n= 3 \n     MAPE: 0.12204000964623057 \n     MSE: 321.11155167264036\n    For n= 4 \n     MAPE: 0.1309588397932153 \n     MSE: 371.52221475507764\n    For n= 5 \n     MAPE: 0.14103864176014247 \n     MSE: 430.10135155316607\n    For n= 6 \n     MAPE: 0.15162126930605366 \n     MSE: 495.95253136200716\n    For n= 7 \n     MAPE: 0.16290870098790572 \n     MSE: 569.7561827956989\n\n\nFor the above the Hyperparameter is the window-size (n) which is tuned manually and it is found that the window-size of 1 is optimal for getting the best results using Moving Averages using previous 2016 values therefore we get $\\begin{align}P_{t} = P_{t-1} \\end{align}$\n\nHere i was actually confused between n=1 or 2, but i went with 1 as it made more sense looking at the time series graph and even AAi preferred 1 and MSE also says 1.\n\n### Weighted Moving Averages\nThe Moving Avergaes Model used gave equal importance to all the values in the window used, but we know intuitively that the future is more likely to be similar to the latest values and less similar to the older values. Weighted Averages converts this analogy into a mathematical relationship giving the highest weight while computing the averages to the latest previous value and decreasing weights to the subsequent older ones<br>\n\nWeighted Moving Averages using Ratio Values - $\\begin{align}R_{t} = ( N*R_{t-1} + (N-1)*R_{t-2} + (N-2)*R_{t-3} .... 1*R_{t-n} )/(N*(N+1)/2) \\end{align}$\n\n\n```python\ndef weigh_mov_avg(df1,df2,n):\n    preds = list()\n    preds.append(df2[0])\n    error = list()\n    error.append(0)\n    for i in range(1,133920):\n        indx = max(i-n,0)\n        n_dash = i-indx\n        meta = list()\n        for x in range(n_dash):\n            ind = indx+x\n            meta.append((df2[ind]/df1[ind])*(x+1))\n        deno = n_dash*((n_dash+1)/2)\n        ratio = sum(meta)/deno\n        # ratio = sum([i/j for i,j in zip(df2[indx:i],df1[indx:i])])/(i-indx)\n        pred_i = ratio*df1[i]\n        preds.append(pred_i)\n        error.append(abs(math.pow(df2[i]-int(pred_i),1)))\n\n    y = np.array(w0_cnt_1503)\n    y_pred = np.array(preds)\n\n    mape_err = (sum(error)/len(error))/(sum(y)/len(y))\n    mse_err = sum([e**2 for e in error])/len(error)\n    print('For n= {} \\n MAPE: {} \\n MSE: {}'.format(n,mape_err,mse_err))\n    return mape_err,mse_err \n```\n\n\n```python\nfor i in range(1,8):\n    weigh_mov_avg(smth_dfgb_1603,w0_cnt_1503,i)\n```\n\n    For n= 1 \n     MAPE: 0.1881094398330249 \n     MSE: 26497.781145459976\n    For n= 2 \n     MAPE: 0.17666275434433204 \n     MSE: 23040.646542712067\n    For n= 3 \n     MAPE: 0.17578334942452306 \n     MSE: 27307.041562126644\n    For n= 4 \n     MAPE: 0.1785392500479882 \n     MSE: 33440.78162335723\n    For n= 5 \n     MAPE: 0.18306637690957073 \n     MSE: 41252.30884856631\n    For n= 6 \n     MAPE: 0.18860432200178873 \n     MSE: 50268.393443847075\n    For n= 7 \n     MAPE: 0.19462588967158473 \n     MSE: 56169.983363201914\n\n\nFor the above the Hyperparameter is the window-size (n) which is tuned manually and it is found that the window-size of 3 is optimal for getting the best results using Weighted Moving Averages using previous Ratio values therefore we get $\\begin{align} R_{t} = (3*R_{t-1} + 2*R_{t-2} + R_{t-3} )/6 \\end{align}$\n\nWeighted Moving Averages using Previous 2015 Values - $\\begin{align}P_{t} = ( N*P_{t-1} + (N-1)*P_{t-2} + (N-2)*P_{t-3} .... 1*P_{t-n} )/(N*(N+1)/2) \\end{align}$\n\n\n```python\ndef weigh_mov_avg_direct(df1,n):\n    preds = list()\n    preds.append(df1[0])\n    error = list()\n    error.append(0)\n    for i in range(1,133920):\n        indx = max(i-n,0)\n        n2 = i-indx\n        meta = [df1[indx+x]*(x+1) for x in range(n2)]\n        deno = n2*((n2+1)/2)\n        pred_i = sum(meta)/deno\n        preds.append(pred_i)\n        error.append(abs(math.pow(df1[i]-int(pred_i),1)))\n\n    mape_err = (sum(error)/len(error))/(sum(df1)/len(df1))\n    mse_err = sum([e**2 for e in error])/len(error)\n    print('For n= {} \\n MAPE: {} \\n MSE: {}'.format(n,mape_err,mse_err))\n    return mape_err,mse_err \n```\n\n\n```python\nfor i in range(1,8):\n    weigh_mov_avg_direct(w0_cnt_1503,i)\n```\n\n    For n= 1 \n     MAPE: 0.11792100440489088 \n     MSE: 286.1540397252091\n    For n= 2 \n     MAPE: 0.11336835066192129 \n     MSE: 270.5185334528077\n    For n= 3 \n     MAPE: 0.11548145202145522 \n     MSE: 283.9622759856631\n    For n= 4 \n     MAPE: 0.11995837344562692 \n     MSE: 308.40602598566306\n    For n= 5 \n     MAPE: 0.1255433620352652 \n     MSE: 338.5740740740741\n    For n= 6 \n     MAPE: 0.13180060991508802 \n     MSE: 373.1146505376344\n    For n= 7 \n     MAPE: 0.1385443338305291 \n     MSE: 411.47962962962964\n\n\nFor the above the Hyperparameter is the window-size (n) which is tuned manually and it is found that the window-size of 2 is optimal for getting the best results using Weighted Moving Averages using previous 2016 values therefore we get $\\begin{align} P_{t} = ( 2*P_{t-1} + P_{t-2} )/3 \\end{align}$\n\n### Exponential  Weighted Moving Averages\n https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average\nThrough weighted averaged we have satisfied the analogy of giving higher weights to the latest value and decreasing weights to the subsequent ones but we still do not know which is the correct weighting scheme as there are infinetly many possibilities in which we can assign weights in a non-increasing order and tune the the hyperparameter window-size. To simplify this process we use Exponential Moving Averages which is a more logical way towards assigning weights and at the same time also using an optimal window-size.\n\nIn exponential moving averages we use a single hyperparameter alpha $\\begin{align}(\\alpha)\\end{align}$ which is a value between 0 & 1 and based on the value of the hyperparameter alpha the weights and the window sizes are configured.<br>\nFor eg. If $\\begin{align}\\alpha=0.9\\end{align}$ then the number of days on which the value of the current iteration is based is~$\\begin{align}1/(1-\\alpha)=10\\end{align}$ i.e. we consider values 10 days prior before we predict the value for the current iteration. Also the weights are assigned using $\\begin{align}2/(N+1)=0.18\\end{align}$ ,where N = number of prior values being considered, hence from this it is implied that the first or latest value is assigned a weight of 0.18 which keeps exponentially decreasing for the subsequent values.\n\n$\\begin{align}R^{'}_{t} = \\alpha*R_{t-1} + (1-\\alpha)*R^{'}_{t-1}  \\end{align}$\n\n\n```python\ndef exp_weigh_mov_avg(df1,df2,alpha):\n    preds = list()\n    preds.append(df2[0])\n    error = list()\n    error.append(0)\n    ratio = df2[0]/df1[0]\n\n    for i in range(1,133920):\n        rat_prev = df2[i-1]/df1[i-1]\n        ratio = (alpha*rat_prev)+((1-alpha)*ratio) \n        pred_i = ratio*df1[i]\n        preds.append(pred_i)\n        error.append(abs(math.pow(df2[i]-int(pred_i),1)))\n\n    y = np.array(w0_cnt_1503)\n    y_pred = np.array(preds)\n\n    mape_err = (sum(error)/len(error))/(sum(y)/len(y))\n    mse_err = sum([e**2 for e in error])/len(error)\n    print('For alpha= {} \\n MAPE: {} \\n MSE: {}'.format(alpha,mape_err,mse_err))\n    return mape_err,mse_err \n```\n\n\n```python\nfor i in range(1,10):\n    exp_weigh_mov_avg(smth_dfgb_1603,w0_cnt_1503,(i/10))\n```\n\n    For alpha= 0.1 \n     MAPE: 0.30025859270688515 \n     MSE: 31411.968593189966\n    For alpha= 0.2 \n     MAPE: 0.22423537542985994 \n     MSE: 43377.78929211469\n    For alpha= 0.3 \n     MAPE: 0.19622236088485887 \n     MSE: 42335.36694295102\n    For alpha= 0.4 \n     MAPE: 0.1835037271946042 \n     MSE: 37220.816293309435\n    For alpha= 0.5 \n     MAPE: 0.17768730002175567 \n     MSE: 32080.327822580646\n    For alpha= 0.6 \n     MAPE: 0.17568687169456768 \n     MSE: 28247.5194369773\n    For alpha= 0.7 \n     MAPE: 0.17614928613806277 \n     MSE: 25927.889717741935\n    For alpha= 0.8 \n     MAPE: 0.17846945600673353 \n     MSE: 24970.822401433692\n    For alpha= 0.9 \n     MAPE: 0.18240977307836373 \n     MSE: 25191.71634557945\n\n\n#### alpha = 0.6 looks good to us\n\n- $\\begin{align}P^{'}_{t} = \\alpha*P_{t-1} + (1-\\alpha)*P^{'}_{t-1}  \\end{align}$\n\n\n```python\ndef exp_weigh_mov_avg_direct(df1,alpha):\n    preds = list()\n    preds.append(df1[0])\n    error = list()\n    error.append(0)\n    p=df1[0]\n\n    for i in range(1,133920):\n        # indx = max(i-n,0)\n        p = (alpha*df1[i-1])+((1-alpha)*p)\n        # sumoflast_nvalues_byn = sum(df1[indx:i])/(i-indx)\n        preds.append(p)\n        error.append(abs(math.pow(df1[i]-int(p),1)))\n\n    mape_err = (sum(error)/len(error))/(sum(df1)/len(df1))\n    mse_err = sum([e**2 for e in error])/len(error)\n    print('For alpha= {} \\n MAPE: {} \\n MSE: {}'.format(alpha,mape_err,mse_err))\n    return mape_err,mse_err \n```\n\n\n```python\nfor i in range(1,10):\n    exp_weigh_mov_avg_direct(w0_cnt_1503,(i/10))\n```\n\n    For alpha= 0.1 \n     MAPE: 0.25018888735419115 \n     MSE: 1251.7970579450418\n    For alpha= 0.2 \n     MAPE: 0.17275999495015046 \n     MSE: 616.867689665472\n    For alpha= 0.3 \n     MAPE: 0.14155704567761646 \n     MSE: 420.9728718637993\n    For alpha= 0.4 \n     MAPE: 0.12638682880786456 \n     MSE: 337.93738799283153\n    For alpha= 0.5 \n     MAPE: 0.1186260399022945 \n     MSE: 297.67070639187574\n    For alpha= 0.6 \n     MAPE: 0.11485531078284004 \n     MSE: 277.8523521505376\n    For alpha= 0.7 \n     MAPE: 0.11344994413777483 \n     MSE: 269.66850358422937\n    For alpha= 0.8 \n     MAPE: 0.11370860625309878 \n     MSE: 269.25571983273596\n    For alpha= 0.9 \n     MAPE: 0.11523991065437272 \n     MSE: 275.0391875746715\n\n\n#### alpha = 0.7 looks good to us\n\n## Comparison between baseline models\nWe have chosen our error metric for comparison between models as <b>MAPE (Mean Absolute Percentage Error)</b> so that we can know that on an average how good is our model with predictions and <b>MSE (Mean Squared Error)</b> is also used so that we have a clearer understanding as to how well our forecasting model performs with outliers so that we make sure that there is not much of a error margin between our prediction and the actual value\n\n\n```python\nmean_err=[0]*10\nmedian_err=[0]*10\nmean_err[0],median_err[0]=sim_mov_avg(smth_dfgb_1603,w0_cnt_1503,2)\nmean_err[1],median_err[1]=sim_mov_avg_direct(w0_cnt_1503,1)\nmean_err[2],median_err[2]=weigh_mov_avg(smth_dfgb_1603,w0_cnt_1503,3)\nmean_err[3],median_err[3]=weigh_mov_avg_direct(w0_cnt_1503,2)\nmean_err[4],median_err[4]=exp_weigh_mov_avg(smth_dfgb_1603,w0_cnt_1503,0.6)\nmean_err[5],median_err[5]=exp_weigh_mov_avg_direct(w0_cnt_1503,0.7)\n```\n\n    For n= 2 \n     MAPE: 0.1787257273869427 \n     MSE: 23346.68452060932\n    For n= 1 \n     MAPE: 0.11792100440489088 \n     MSE: 286.1540397252091\n    For n= 3 \n     MAPE: 0.17578334942452306 \n     MSE: 27307.041562126644\n    For n= 2 \n     MAPE: 0.11336835066192129 \n     MSE: 270.5185334528077\n    For alpha= 0.6 \n     MAPE: 0.17568687169456768 \n     MSE: 28247.5194369773\n    For alpha= 0.7 \n     MAPE: 0.11344994413777483 \n     MSE: 269.66850358422937\n\n\n\n```python\nprint (\"Error Metric Matrix (Forecasting Methods) - MAPE & MSE\")\nprint (\"--------------------------------------------------------------------------------------------------------\")\nprint (\"Moving Averages (Ratios) -                             MAPE: \",mean_err[0],\"      MSE: \",median_err[0])\nprint (\"Moving Averages (2015 Values) -                        MAPE: \",mean_err[1],\"       MSE: \",median_err[1])\nprint (\"--------------------------------------------------------------------------------------------------------\")\nprint (\"Weighted Moving Averages (Ratios) -                    MAPE: \",mean_err[2],\"      MSE: \",median_err[2])\nprint (\"Weighted Moving Averages (2015 Values) -               MAPE: \",mean_err[3],\"      MSE: \",median_err[3])\nprint (\"--------------------------------------------------------------------------------------------------------\")\nprint (\"Exponential Moving Averages (Ratios) -              MAPE: \",mean_err[4],\"      MSE: \",median_err[4])\nprint (\"Exponential Moving Averages (2015 Values) -         MAPE: \",mean_err[5],\"      MSE: \",median_err[5])\n```\n\n    Error Metric Matrix (Forecasting Methods) - MAPE & MSE\n    --------------------------------------------------------------------------------------------------------\n    Moving Averages (Ratios) -                             MAPE:  0.1787257273869427       MSE:  23346.68452060932\n    Moving Averages (2015 Values) -                        MAPE:  0.11792100440489088        MSE:  286.1540397252091\n    --------------------------------------------------------------------------------------------------------\n    Weighted Moving Averages (Ratios) -                    MAPE:  0.17578334942452306       MSE:  27307.041562126644\n    Weighted Moving Averages (2015 Values) -               MAPE:  0.11336835066192129       MSE:  270.5185334528077\n    --------------------------------------------------------------------------------------------------------\n    Exponential Moving Averages (Ratios) -              MAPE:  0.17568687169456768       MSE:  28247.5194369773\n    Exponential Moving Averages (2015 Values) -         MAPE:  0.11344994413777483       MSE:  269.66850358422937\n\n\n\n```python\n<b>Plese Note:-</b> The above comparisons are made using March 2015 and March 2016 only\n```\n\n# - Regression Models\n\n- ### Train-Test Split\nBefore we start predictions using the tree based regression models we take 3 months of 2016 pickup data and split it such that for every region we have 70% data in train and 30% in test, ordered date-wise for every region\n\n\n```python\njan_2016 = dd.read_csv('data/raw/yellow_tripdata_2016-01.csv')\nfeb_2016 = dd.read_csv('data/raw/yellow_tripdata_2016-02.csv')\nmar_2016 = dd.read_csv('data/raw/yellow_tripdata_2016-03.csv')\n\ndf_1601,dfgb_1601 = data_preparation(jan_2016,clu,2016,1)\ndf_1602,dfgb_1602 = data_preparation(feb_2016,clu,2016,2)\ndf_1603,dfgb_1603 = data_preparation(mar_2016,clu,2016,3)\n\nw0_dfgb_1601 = dfgb_1601.unstack(fill_value=0)\nw0_dfgb_1602 = dfgb_1602.unstack(fill_value=0)\nw0_dfgb_1603 = dfgb_1603.unstack(fill_value=0)\n```\n\n    Claculating 'duration' and 'speed' & Remove outliers..\n    Number of pickup records =  10906858\n    Number of outlier coordinates lying outside NY boundaries: 214677\n    Number of outliers from trip duration analysis: 27182\n    Number of outliers from trip distance analysis: 74842\n    Number of outliers from speed analysis: 21203\n    Number of outliers from fare analysis: 5031\n    ---\n    Total data before : 10906858\n    Total data after removal of outliers : 10619847\n    Total outliers removed : 287011\n    ---\n    Estimating clusters..\n    Final groupbying..\n    Completed\n\n\n\n```python\nwith open(\"data/chkpt2.pickle\",\"wb\") as f:\n    pickle.dump(w0_dfgb_1601, f)\n    pickle.dump(w0_dfgb_1602, f)\n    pickle.dump(w0_dfgb_1603, f)\n```\n\n\n```python\nwith open(\"data/chkpt2.pickle\", \"rb\") as f:\n    w0_dfgb_1601 = pickle.load(f)\n    w0_dfgb_1602 = pickle.load(f)\n    w0_dfgb_1603 = pickle.load(f)    \n```\n\n\n```python\nlen(w0_dfgb_1601.stack())\n```\n\n\n\n\n    133620\n\n\n\nWhile checking the things out i found out that the length of w0_dfgb_1601 to be 133620, whereas it should have been 133920 = 6*24*31*30, so after digging in the issue\n\n`temp = [x for (y,x) in w0_dfgb_1601.columns]` \n\n`set(range(4464)).difference(set(temp))`\n\nwe found that these columns are missing\n\n`{3287, 3290, 3293, 3296, 3305, 3308, 3322, 3324, 3331, 3334}`\n\nthen we checked the original dataset and, yes we do not have any data for those timebins across any cluster. So we need to add 0 in those places\n\n\n\n```python\ntemp = [x for (y,x) in w0_dfgb_1601.columns]\nset(range(4464)).difference(set(temp))\n```\n\n\n\n\n    {3287, 3290, 3293, 3296, 3305, 3308, 3322, 3324, 3331, 3334}\n\n\n\n\n```python\ntemp_df = pd.DataFrame(np.zeros(300,dtype=np.int8).reshape(30,10),columns=[3287, 3290, 3293, 3296, 3305, 3308, 3322, 3324, 3331, 3334])\ntotal_w0_1601 = pd.concat([w0_dfgb_1601['trip_distance'], temp_df], axis=1)\ntotal_w0_1601.columns;\n```\n\n\n```python\ntotal_w0_1601=total_w0_1601[list(range(4464))]\ntotal_w0_1601.columns;\n```\n\n\n```python\n(total_w0_1601.columns == list(range(4464))).any()\n```\n\n\n\n\n    True\n\n\n\n\n```python\ncount_1601 = list(total_w0_1601.stack())\nlen(count_1601)\n```\n\n\n\n\n    133920\n\n\n\n\n```python\ncount_1603 = list(w0_dfgb_1603['trip_distance'].stack())\nlen(count_1603)\n```\n\n\n\n\n    133920\n\n\n\n\n```python\ncount_1602 = list(w0_dfgb_1602['trip_distance'].stack())\nlen(count_1602)\n```\n\n\n\n\n    125280\n\n\n\n\n```python\n# Preparing data to be split into train and test, The below prepares data in cumulative form which will be later split into test and train\n# number of 10min indices for jan 2015= 24*31*60/10 = 4464\n# number of 10min indices for jan 2016 = 24*31*60/10 = 4464\n# number of 10min indices for feb 2016 = 24*29*60/10 = 4176\n# number of 10min indices for march 2016 = 24*31*60/10 = 4464\n# regions_cum: it will contain 40 lists, each list will contain 4464+4176+4464 values which represents the number of pickups \n# that are happened for three months in 2016 data\nregions_cum=list()\nfor i in range(0,30):\n    regions_cum.append(count_1601[4464*i:4464*(i+1)]+count_1602[4176*i:4176*(i+1)]+count_1603[4464*i:4464*(i+1)])\n\n\n# print(len(regions_cum))\n# 30\n# print(len(regions_cum[0]))\n# 13104\n```\n\n\n```python\n# we take number of pickups that are happened in last 5 10min intravels\nnumber_of_time_stamps = 5\n\n# output varaible\n# it is list of lists\n# it will contain number of pickups 13099 for each cluster\noutput = []\n\n\n# tsne_lat will contain 13104-5=13099 times lattitude of cluster center for every cluster\n# Ex: [[cent_lat 13099times],[cent_lat 13099times], [cent_lat 13099times].... 40 lists]\n# it is list of lists\ntsne_lat = []\n\n\n# tsne_lon will contain 13104-5=13099 times logitude of cluster center for every cluster\n# Ex: [[cent_long 13099times],[cent_long 13099times], [cent_long 13099times].... 40 lists]\n# it is list of lists\ntsne_lon = []\n\n# we will code each day \n# sunday = 0, monday=1, tue = 2, wed=3, thur=4, fri=5,sat=6\n# for every cluster we will be adding 13099 values, each value represent to which day of the week that pickup bin belongs to\n# it is list of lists\ntsne_weekday = []\n\n# its an numbpy array, of shape (523960, 5)\n# each row corresponds to an entry in out data\n# for the first row we will have [f0,f1,f2,f3,f4] fi=number of pickups happened in i+1th 10min intravel(bin)\n# the second row will have [f1,f2,f3,f4,f5]\n# the third row will have [f2,f3,f4,f5,f6]\n# and so on...\ntsne_feature = []\n\n\ntsne_feature = [0]*number_of_time_stamps\nfor i in range(0,30):\n    tsne_lat.append([clu.cluster_centers_[i][0]]*13099)\n    tsne_lon.append([clu.cluster_centers_[i][1]]*13099)\n    # jan 1st 2016 is thursday, so we start our day from 4: \"(int(k/144))%7+4\"\n    # our prediction start from 5th 10min intravel since we need to have number of pickups that are happened in last 5 pickup bins\n    tsne_weekday.append([int(((int(k/144))%7+4)%7) for k in range(5,4464+4176+4464)])\n    # regions_cum is a list of lists [[x1,x2,x3..x13104], [x1,x2,x3..x13104], [x1,x2,x3..x13104], [x1,x2,x3..x13104], [x1,x2,x3..x13104], .. 40 lsits]\n    tsne_feature = np.vstack((tsne_feature, [regions_cum[i][r:r+number_of_time_stamps] for r in range(0,len(regions_cum[i])-number_of_time_stamps)]))\n    output.append(regions_cum[i][5:])\ntsne_feature = tsne_feature[1:]\n```\n\n\n```python\nlen(tsne_lat[0])*len(tsne_lat) == tsne_feature.shape[0] == len(tsne_weekday)*len(tsne_weekday[0]) == 30*13099 == len(output)*len(output[0])\n```\n\n\n\n\n    True\n\n\n\n\n```python\n# Getting the predictions of exponential moving averages to be used as a feature in cumulative form\n\n# upto now we computed 8 features for every data point that starts from 50th min of the day\n# 1. cluster center lattitude\n# 2. cluster center longitude\n# 3. day of the week \n# 4. f_t_1: number of pickups that are happened previous t-1th 10min intravel\n# 5. f_t_2: number of pickups that are happened previous t-2th 10min intravel\n# 6. f_t_3: number of pickups that are happened previous t-3th 10min intravel\n# 7. f_t_4: number of pickups that are happened previous t-4th 10min intravel\n# 8. f_t_5: number of pickups that are happened previous t-5th 10min intravel\n\n# from the baseline models we said the exponential weighted moving avarage gives us the best error\n# we will try to add the same exponential weighted moving avarage at t as a feature to our data\n# exponential weighted moving avarage => p'(t) = alpha*p'(t-1) + (1-alpha)*P(t-1) \nalpha=0.3\n\n# it is a temporary array that store exponential weighted moving avarage for each 10min intravel, \n# for each cluster it will get reset\n# for every cluster it contains 13104 values\npredicted_values=[]\n\n# it is similar like tsne_lat\n# it is list of lists\n# predict_list is a list of lists [[x5,x6,x7..x13104], [x5,x6,x7..x13104], [x5,x6,x7..x13104], [x5,x6,x7..x13104], [x5,x6,x7..x13104], .. 40 lsits]\npredict_list = []\ntsne_flat_exp_avg = []\nfor r in range(0,30):\n    for i in range(0,13104):\n        if i==0:\n            predicted_value= regions_cum[r][0]\n            predicted_values.append(0)\n            continue\n        predicted_values.append(predicted_value)\n        predicted_value =int((alpha*predicted_value) + (1-alpha)*(regions_cum[r][i]))\n    predict_list.append(predicted_values[5:])\n    predicted_values=[]\n```\n\n\n```python\n# train, test split : 70% 30% split\n# Before we start predictions using the tree based regression models we take 3 months of 2016 pickup data \n# and split it such that for every region we have 70% data in train and 30% in test,\n# ordered date-wise for every region\nprint(\"size of train data :\", int(13099*0.7))\nprint(\"size of test data :\", int(13099*0.3))\n```\n\n    size of train data : 9169\n    size of test data : 3929\n\n\n\n```python\n# extracting first 9169 timestamp values i.e 70% of 13099 (total timestamps) for our training data\ntrain_features =  [tsne_feature[i*13099:(13099*i+9169)] for i in range(0,30)]\n# temp = [0]*(12955 - 9068)\ntest_features = [tsne_feature[(13099*(i))+9169:13099*(i+1)] for i in range(0,30)]\n```\n\n\n```python\nprint(\"Number of data clusters\",len(train_features), \"Number of data points in trian data\", len(train_features[0]), \"Each data point contains\", len(train_features[0][0]),\"features\")\nprint(\"Number of data clusters\",len(train_features), \"Number of data points in test data\", len(test_features[0]), \"Each data point contains\", len(test_features[0][0]),\"features\")\n```\n\n    Number of data clusters 30 Number of data points in trian data 9169 Each data point contains 5 features\n    Number of data clusters 30 Number of data points in test data 3930 Each data point contains 5 features\n\n\n\n```python\n# extracting first 9169 timestamp values i.e 70% of 13099 (total timestamps) for our training data\ntsne_train_flat_lat = [i[:9169] for i in tsne_lat]\ntsne_train_flat_lon = [i[:9169] for i in tsne_lon]\ntsne_train_flat_weekday = [i[:9169] for i in tsne_weekday]\ntsne_train_flat_output = [i[:9169] for i in output]\ntsne_train_flat_exp_avg = [i[:9169] for i in predict_list]\n```\n\n\n```python\n# extracting the rest of the timestamp values i.e 30% of 12956 (total timestamps) for our test data\ntsne_test_flat_lat = [i[9169:] for i in tsne_lat]\ntsne_test_flat_lon = [i[9169:] for i in tsne_lon]\ntsne_test_flat_weekday = [i[9169:] for i in tsne_weekday]\ntsne_test_flat_output = [i[9169:] for i in output]\ntsne_test_flat_exp_avg = [i[9169:] for i in predict_list]\n```\n\n\n```python\n# the above contains values in the form of list of lists (i.e. list of values of each region), here we make all of them in one list\ntrain_new_features = []\nfor i in range(0,30):\n    train_new_features.extend(train_features[i])\ntest_new_features = []\nfor i in range(0,30):\n    test_new_features.extend(test_features[i])\n```\n\n\n```python\n# converting lists of lists into sinle list i.e flatten\n# a  = [[1,2,3,4],[4,6,7,8]]\n# print(sum(a,[]))\n# [1, 2, 3, 4, 4, 6, 7, 8]\n\ntsne_train_lat = sum(tsne_train_flat_lat, [])\ntsne_train_lon = sum(tsne_train_flat_lon, [])\ntsne_train_weekday = sum(tsne_train_flat_weekday, [])\ntsne_train_output = sum(tsne_train_flat_output, [])\ntsne_train_exp_avg = sum(tsne_train_flat_exp_avg,[])\n```\n\n\n```python\n# converting lists of lists into sinle list i.e flatten\n# a  = [[1,2,3,4],[4,6,7,8]]\n# print(sum(a,[]))\n# [1, 2, 3, 4, 4, 6, 7, 8]\n\ntsne_test_lat = sum(tsne_test_flat_lat, [])\ntsne_test_lon = sum(tsne_test_flat_lon, [])\ntsne_test_weekday = sum(tsne_test_flat_weekday, [])\ntsne_test_output = sum(tsne_test_flat_output, [])\ntsne_test_exp_avg = sum(tsne_test_flat_exp_avg,[])\n```\n\n\n```python\n# Preparing the data frame for our train data\ncolumns = ['ft_5','ft_4','ft_3','ft_2','ft_1']\ndf_train = pd.DataFrame(data=train_new_features, columns=columns) \ndf_train['lat'] = tsne_train_lat\ndf_train['lon'] = tsne_train_lon\ndf_train['weekday'] = tsne_train_weekday\ndf_train['exp_avg'] = tsne_train_exp_avg\n\nprint(df_train.shape)\n```\n\n    (275070, 9)\n\n\n\n```python\n# Preparing the data frame for our train data\ndf_test = pd.DataFrame(data=test_new_features, columns=columns) \ndf_test['lat'] = tsne_test_lat\ndf_test['lon'] = tsne_test_lon\ndf_test['weekday'] = tsne_test_weekday\ndf_test['exp_avg'] = tsne_test_exp_avg\nprint(df_test.shape)\n```\n\n    (117900, 9)\n\n\n\n```python\ndf_test.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>ft_5</th>\n      <th>ft_4</th>\n      <th>ft_3</th>\n      <th>ft_2</th>\n      <th>ft_1</th>\n      <th>lat</th>\n      <th>lon</th>\n      <th>weekday</th>\n      <th>exp_avg</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>76</td>\n      <td>66</td>\n      <td>62</td>\n      <td>81</td>\n      <td>72</td>\n      <td>40.749332</td>\n      <td>-73.991686</td>\n      <td>4</td>\n      <td>72</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>66</td>\n      <td>62</td>\n      <td>81</td>\n      <td>72</td>\n      <td>95</td>\n      <td>40.749332</td>\n      <td>-73.991686</td>\n      <td>4</td>\n      <td>88</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>62</td>\n      <td>81</td>\n      <td>72</td>\n      <td>95</td>\n      <td>76</td>\n      <td>40.749332</td>\n      <td>-73.991686</td>\n      <td>4</td>\n      <td>79</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>81</td>\n      <td>72</td>\n      <td>95</td>\n      <td>76</td>\n      <td>69</td>\n      <td>40.749332</td>\n      <td>-73.991686</td>\n      <td>4</td>\n      <td>72</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>72</td>\n      <td>95</td>\n      <td>76</td>\n      <td>69</td>\n      <td>98</td>\n      <td>40.749332</td>\n      <td>-73.991686</td>\n      <td>4</td>\n      <td>90</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## - Using Linear Regression\n\n\n```python\nlr_reg=LinearRegression().fit(df_train, tsne_train_output)\n\ny_pred = lr_reg.predict(df_test)\nlr_test_predictions = [round(value) for value in y_pred]\ny_pred = lr_reg.predict(df_train)\nlr_train_predictions = [round(value) for value in y_pred]\n```\n\n## - Using Random Forest Regressor\n\n\n```python\nregr1 = RandomForestRegressor(max_features='sqrt',min_samples_leaf=4,min_samples_split=3,n_estimators=40, n_jobs=-1)\nregr1.fit(df_train, tsne_train_output)\n```\n\n\n\n\n    RandomForestRegressor(max_features='sqrt', min_samples_leaf=4,\n                          min_samples_split=3, n_estimators=40, n_jobs=-1)\n\n\n\n\n```python\n# Predicting on test data using our trained random forest model \n\n# the models regr1 is already hyper parameter tuned\n# the parameters that we got above are found using grid search\n\ny_pred = regr1.predict(df_test)\nrndf_test_predictions = [round(value) for value in y_pred]\ny_pred = regr1.predict(df_train)\nrndf_train_predictions = [round(value) for value in y_pred]\n```\n\n\n```python\n#feature importances based on analysis using random forest\nprint (df_train.columns)\nprint (regr1.feature_importances_)\n```\n\n    Index(['ft_5', 'ft_4', 'ft_3', 'ft_2', 'ft_1', 'lat', 'lon', 'weekday',\n           'exp_avg'],\n          dtype='object')\n    [0.01231967 0.04130586 0.2294651  0.1977369  0.21806498 0.00241721\n     0.00192689 0.00163166 0.29513174]\n\n\n## - Using XgBoost Regressor\n\n\n```python\n# Training a hyper-parameter tuned Xg-Boost regressor on our train data\n\n# find more about XGBRegressor function here http://xgboost.readthedocs.io/en/latest/python/python_api.html?#module-xgboost.sklearn\n# -------------------------\n# default paramters\n# xgboost.XGBRegressor(max_depth=3, learning_rate=0.1, n_estimators=100, silent=True, objective='reg:linear', \n# booster='gbtree', n_jobs=1, nthread=None, gamma=0, min_child_weight=1, max_delta_step=0, subsample=1, colsample_bytree=1, \n# colsample_bylevel=1, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, base_score=0.5, random_state=0, seed=None, \n# missing=None, **kwargs)\n\n# some of methods of RandomForestRegressor()\n# fit(X, y, sample_weight=None, eval_set=None, eval_metric=None, early_stopping_rounds=None, verbose=True, xgb_model=None)\n# get_params([deep])\tGet parameters for this estimator.\n# predict(data, output_margin=False, ntree_limit=0) : Predict with data. NOTE: This function is not thread safe.\n# get_score(importance_type='weight') -> get the feature importance\n\nx_model = xgb.XGBRegressor(\n learning_rate =0.1,\n n_estimators=1000,\n max_depth=3,\n min_child_weight=3,\n gamma=0,\n subsample=0.8,\n reg_alpha=200, reg_lambda=200,\n colsample_bytree=0.8,nthread=4)\nx_model.fit(df_train, tsne_train_output)\n```\n\n\n\n\n    XGBRegressor(base_score=0.5, booster='gbtree', colsample_bylevel=1,\n                 colsample_bynode=1, colsample_bytree=0.8, gamma=0, gpu_id=-1,\n                 importance_type='gain', interaction_constraints='',\n                 learning_rate=0.1, max_delta_step=0, max_depth=3,\n                 min_child_weight=3, missing=nan, monotone_constraints='()',\n                 n_estimators=1000, n_jobs=4, nthread=4, num_parallel_tree=1,\n                 random_state=0, reg_alpha=200, reg_lambda=200, scale_pos_weight=1,\n                 subsample=0.8, tree_method='exact', validate_parameters=1,\n                 verbosity=None)\n\n\n\n\n```python\n#predicting with our trained Xg-Boost regressor\n# the models x_model is already hyper parameter tuned\n# the parameters that we got above are found using grid search\n\ny_pred = x_model.predict(df_test)\nxgb_test_predictions = [round(value) for value in y_pred]\ny_pred = x_model.predict(df_train)\nxgb_train_predictions = [round(value) for value in y_pred]\n```\n\n\n```python\n#feature importances\nx_model.get_booster().get_score(importance_type='weight')\n```\n\n\n\n\n    {'ft_1': 1108,\n     'exp_avg': 792,\n     'ft_2': 863,\n     'ft_3': 749,\n     'ft_4': 594,\n     'lat': 768,\n     'weekday': 311,\n     'lon': 427,\n     'ft_5': 1062}\n\n\n\n\n```python\ntrain_mape=[]\ntest_mape=[]\n\ntrain_mape.append((mean_absolute_error(tsne_train_output,df_train['ft_1'].values))/(sum(tsne_train_output)/len(tsne_train_output)))\ntrain_mape.append((mean_absolute_error(tsne_train_output,df_train['exp_avg'].values))/(sum(tsne_train_output)/len(tsne_train_output)))\ntrain_mape.append((mean_absolute_error(tsne_train_output,rndf_train_predictions))/(sum(tsne_train_output)/len(tsne_train_output)))\ntrain_mape.append((mean_absolute_error(tsne_train_output, xgb_train_predictions))/(sum(tsne_train_output)/len(tsne_train_output)))\ntrain_mape.append((mean_absolute_error(tsne_train_output, lr_train_predictions))/(sum(tsne_train_output)/len(tsne_train_output)))\n\ntest_mape.append((mean_absolute_error(tsne_test_output, df_test['ft_1'].values))/(sum(tsne_test_output)/len(tsne_test_output)))\ntest_mape.append((mean_absolute_error(tsne_test_output, df_test['exp_avg'].values))/(sum(tsne_test_output)/len(tsne_test_output)))\ntest_mape.append((mean_absolute_error(tsne_test_output, rndf_test_predictions))/(sum(tsne_test_output)/len(tsne_test_output)))\ntest_mape.append((mean_absolute_error(tsne_test_output, xgb_test_predictions))/(sum(tsne_test_output)/len(tsne_test_output)))\ntest_mape.append((mean_absolute_error(tsne_test_output, lr_test_predictions))/(sum(tsne_test_output)/len(tsne_test_output)))\n```\n\n\n```python\nprint (\"Error Metric Matrix (Tree Based Regression Methods) -  MAPE\")\nprint (\"--------------------------------------------------------------------------------------------------------\")\nprint (\"Baseline Model -                             Train: \",train_mape[0],\"      Test: \",test_mape[0])\nprint (\"Exponential Averages Forecasting -           Train: \",train_mape[1],\"      Test: \",test_mape[1])\nprint (\"Linear Regression -                         Train: \",train_mape[3],\"      Test: \",test_mape[3])\nprint (\"Random Forest Regression -                   Train: \",train_mape[2],\"     Test: \",test_mape[2])\n```\n\n    Error Metric Matrix (Tree Based Regression Methods) -  MAPE\n    --------------------------------------------------------------------------------------------------------\n    Baseline Model -                             Train:  0.12653812243978038       Test:  0.1236194754070999\n    Exponential Averages Forecasting -           Train:  0.12098454722999152       Test:  0.11810668675911908\n    Linear Regression -                         Train:  0.1167186415469483       Test:  0.11496267373734606\n    Random Forest Regression -                   Train:  0.08243746428940353      Test:  0.11458312346670046\n\n\n\n```python\nprint (\"Error Metric Matrix (Tree Based Regression Methods) -  MAPE\")\nprint (\"--------------------------------------------------------------------------------------------------------\")\nprint (\"Baseline Model -                             Train: \",train_mape[0],\"      Test: \",test_mape[0])\nprint (\"Exponential Averages Forecasting -           Train: \",train_mape[1],\"      Test: \",test_mape[1])\nprint (\"Linear Regression -                         Train: \",train_mape[4],\"      Test: \",test_mape[4])\nprint (\"Random Forest Regression -                   Train: \",train_mape[2],\"     Test: \",test_mape[2])\nprint (\"XgBoost Regression -                         Train: \",train_mape[3],\"      Test: \",test_mape[3])\nprint (\"--------------------------------------------------------------------------------------------------------\")\n```\n\n    Error Metric Matrix (Tree Based Regression Methods) -  MAPE\n    --------------------------------------------------------------------------------------------------------\n    Baseline Model -                             Train:  0.12653812243978038       Test:  0.1236194754070999\n    Exponential Averages Forecasting -           Train:  0.12098454722999152       Test:  0.11810668675911908\n    Linear Regression -                         Train:  0.12075609461928105       Test:  0.11778022578419144\n    Random Forest Regression -                   Train:  0.08243746428940353      Test:  0.11458312346670046\n    XgBoost Regression -                         Train:  0.1167186415469483       Test:  0.11496267373734606\n    --------------------------------------------------------------------------------------------------------\n\n\n<p style=\"font-size:17px\">Assessment : <br>\n1) We can see that even the basic models like 'simple moving averages of values'(and not ratios) or 'weighted','exponential' models presented with very good accuracy with MAPE around 13-14, when compared with the MAPE of other complex models as above, provide us with MAPE of about 11-12. So comparing the complexity of the models the complex models do not improve the results drastically. <br>\n2) As per the Shrikant Cheturi's experience working in Amazon, the features like the previous values (moving averages) play the important part in prediction in the Time-Series data every time. <br>\n3) Comparing the results of Random Forest Regression and XgBoost Regression we can observe that the test MAPE are similar around 11.4%, but there is an noticeable difference in the MAPE of train data. We can see that the difference in the errors is less in GBDT than in RF, stating that the GBDT is more stable model and RF seems to have overfitted.\n\n\n```python\n\n```\n", "meta": {"hexsha": "1bfd8e6e9eeb45e5d5a72a0c499cfea17d9f5eb8", "size": 921277, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Taxi-Prediction.ipynb", "max_stars_repo_name": "Sahil-Chavan/Taxi_Prediction-CaseStudy", "max_stars_repo_head_hexsha": "db0c2a87fcf5acaa9a6b57ecdb14ac4352195e78", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Taxi-Prediction.ipynb", "max_issues_repo_name": "Sahil-Chavan/Taxi_Prediction-CaseStudy", "max_issues_repo_head_hexsha": "db0c2a87fcf5acaa9a6b57ecdb14ac4352195e78", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Taxi-Prediction.ipynb", "max_forks_repo_name": "Sahil-Chavan/Taxi_Prediction-CaseStudy", "max_forks_repo_head_hexsha": "db0c2a87fcf5acaa9a6b57ecdb14ac4352195e78", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 115.1164563289, "max_line_length": 192774, "alphanum_fraction": 0.7204022243, "converted": true, "num_tokens": 54162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.09670578808943049, "lm_q1q2_score": 0.04684235778483053}}
{"text": "```python\n# Erasmus+ ICCT project (2018-1-SI01-KA203-047081)\n\n# Toggle cell visibility\n\nfrom IPython.display import HTML\ntag = HTML('''\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.''')\ndisplay(tag)\n\n# Hide the code completely\n\n# from IPython.display import HTML\n# tag = HTML('''<style>\n# div.input {\n#     display:none;\n# }\n# </style>''')\n# display(tag)\n```\n\n\n\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.\n\n\n\n```python\n%matplotlib notebook\n\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport numpy as np\nimport sympy as sym\n\nfrom ipywidgets import widgets, Layout\nfrom ipywidgets import interact\n\nfrom IPython.display import Latex, display, Markdown # For displaying Markdown and LaTeX code\n\nfrom matplotlib import patches\n```\n\n    Traceback (most recent call last):\n      File \"C:\\Users\\Uporabnik\\Anaconda3\\envs\\icct2\\lib\\site-packages\\matplotlib\\cbook\\__init__.py\", line 216, in process\n        func(*args, **kwargs)\n      File \"C:\\Users\\Uporabnik\\Anaconda3\\envs\\icct2\\lib\\site-packages\\matplotlib\\animation.py\", line 1465, in _stop\n        self.event_source.remove_callback(self._loop_delay)\n    AttributeError: 'NoneType' object has no attribute 'remove_callback'\n\n\n## Sistem za krmiljenje polo\u017eaja antene\n\nShematski primer enostavnega sistema za krmiljenje polo\u017eaja antene je shematsko prikazan na levi sliki spodaj. Cilj sistema za krmiljenje je vzdr\u017eevanje referen\u010dnega (zahtevanega) polo\u017eaja antene, ki ga dolo\u010dimo z nastavitvijo zahtevanega kota antene $\\theta_{ref}$ na referen\u010dnem potenciometru (RP). Vstopni signal v blokovni diagram sistema (prikazan na sliki desno spodaj) je tako $\\theta_{ref}$, ki se nato pretvori v napetostni signal $U_1$, od katerega se od\u0161teje napetostni signal $U_2$, ki predstavlja izstopni signal za merilnega potenciometra (MP). $U_2$ nosi informacijo o dejanskem polo\u017eajnem kotu antene. Razlika napetostnih signalov $U_1-U_2$ predstavlja odstopek, ki nam pove, koliko dejanski polo\u017eajni kot odstopa od zahtevanega. Glede na ta odstopek, sistem za krmiljenje deluje na elektromotor, kateri zavrti anteno na na\u010din, da se zmanj\u0161a odstopek. $d_w$ predstavlja motnjo zaradi vetra, ki naklju\u010dno rotira anteno.\n\n<br>\n<br>\n\n<table>\n    <tr>\n        <th>Shematski prikaz sistema za krmiljenje polo\u017eaja antene</th>\n        <th>Blokovni diagram sistema za krmiljenje polo\u017eaja antene</th>\n    </tr>\n    <tr>\n        <td></td>\n        <td></td>\n    </tr>\n    <tr>\n        <td></td>\n        <td>Legend: RP-referen\u010dni potenciometer, MP-merilni potenciometer, d<sub>w</sub>-motnja zaradi vetra.</td>\n    </tr>    \n</table>\n\n---\n\n### Kako upravljati s tem interaktivnim primerom?\n\n- Z uporabo drsnikov spreminjamo vrednosti zahtevanega polo\u017eaja antene ($\\theta_{ref}$), motnje zaradi vetra ($d_w$), ter koeficientov proporcionalnega ($K_p$), integracijskega ($K_i$) in diferencirnega ($K_d$) objekta.\n\n- S preklopnimi gumbi izbiramo med proporcionalnim (P), proporcionalno-integrirnim (PI) in proporcionalno-integrirno-diferencirnim (PID) tipom krmilnika.\n\n---\n\n### Opombe\n\n- Velikost rde\u010de pu\u0161\u010dice ozna\u010dene na shematskem prikazu sistema za krmiljenje polo\u017eaja antene je proporcionalno z magnitudo motnje zaradi vetra ($d_w$), medtem ko smer te pu\u0161\u010dice ka\u017ee smer motnje.\n- \u010crtkana modra \u010drta na shematskem prikazu sistema za krmiljenje polo\u017eaja antene ozna\u010duje dejanski polo\u017eaj antene.\n- \u010crtkana zelena \u010drta na shematskem prikazu sistema za krmiljenje polo\u017eaja antene ozna\u010duje zahtevani polo\u017eaj antene.\n- Rde\u010da \u010drta iz pik in \u010drtic na shematskem prikazu sistema za krmiljenje polo\u017eaja antene predstavlja predhodni polo\u017eaj antene.\n\nIzbira\u0161 lahko med dvema na\u010dinoma za prikaz rezultatov:\n1. Ponastavi shematski prikaz sistema ob spremembi tipa krmilnika.\n2. Ponastavi graf polo\u017eaja antene v odvisnosti od \u010dasa ob spremembi tipa krmilnika.\n\n\n<!-- An example of a simple antenna azimuth position control system is shown schematically in the left figure below. The goal of this control system is to maintain the reference (desired) position of the antenna by setting the desired angle $\\theta_{ref}$ with the reference potentiometer (RP). Block diagram of this system (shown in the right figure below) therefore starts with the signal $\\theta_{ref}$, which is converted to voltage $U_1$. Voltage $U_2$ is then subtracted from $U_1$. $U_2$ is the output from the measuring potentiometer (MP), which provides the information about the actual angle. Voltage difference $U_1-U_2$ represents the error that tells us how much the actual angle differs from the desired one. Based on this error the controller affects the electromotor, which (by means of gearing) rotates the antenna in the way in which the error is reduced. $d_w$ is a disturbance due to the wind, which randomly rotates the antenna.\n\n<br>\n<br>\n\n<table>\n    <tr>\n        <th>Schematic representation of the antenna azimuth position control system</th>\n        <th>Block diagram of the antenna azimuth position control system</th>\n    </tr>\n    <tr>\n        <td></td>\n        <td></td>\n    </tr>\n    <tr>\n        <td></td>\n        <td>Legend: RP-reference potentiometer, MP-measuring potentiometer, d<sub>w</sub>-disturbance due to the wind.</td>\n    </tr>    \n</table>\n\n---\n\n### How to use this notebook?\n\n- Move the sliders to change the values of the desired antenna azimuth angle ($\\theta_{ref}$), disturbance due to the wind ($d_w$), and proportional ($K_p$), integral ($K_i$) and derivative ($K_d$) tuning coefficients.\n\n- Press the buttons to toggle between proportional (P), proportional-integral (PI) and proportional-integral-derivative (PID) controller type.\n\n---\n\n### Notes\n\n- Size of the red arrow on the schematic representation of the antenna is proportional to the magnitude of the disturbance due to the wind ($d_w$), whereas the direction of the arrow indicates the direction of the disturbance.\n- Dashed blue line on the schematic representation of an antenna denotes the actual angle of the atenna.\n- Dashed green line on the schematic representation of an antenna denotes the desired angle of the atenna.\n- Dash-dot red line on the schematic representation of an antenna indicates the previous actual angle of the antenna.\n\nYou can select between two different options for displaying the results:\n1. Reset the schematic representation when the controller type is changed.\n2. Reset the plot when the controller type is changed. -->\n\n\n```python\n# define system constants\n_Kpot = 0.318\n\n_K1 = 100\n_a = 100\n_Km = 2.083\n_am = 1.71\n_Kg = 0.1\n_R = 8\n_Kt = 0.5\n_Tv = 200 #in milliseconds\n\n#set current theta and theta reference:\nth = [0,0,0,0,0,0]\nthref = [0,0,0,0,0,0]\n# disturbance:\nm = [0,0,0,0,0,0]\n#joined together (first theta reference, second disturbance, then theta measured):\nvariables = [thref, m, th]\n\n# variables of controller:\n_K = 1\n_taui = 1\n_taud = 1\n\n```\n\n\n```python\n# symbolic calculus:\ntaui, taud, K, s, z = sym.symbols('taui, taud, K, s, z')\n\n_alpha=0.1\n#controller:\nP = K\nI = K/(taui*s)\nD = K*taud*s/(_alpha*taud*s+1)\n\ndef make_model(controller):\n    if controller == 'P':\n        C = P\n    elif controller == 'PI':\n        C = P+I\n    elif controller == 'PID':\n        C = P+I+D\n    else:\n        print('Controller type not in library')\n    \n    tf_s = C*_K1*_Km*_Kg*_Kpot/(s*(s+_a)*(s+_am)+C*_K1*_Km*_Kg*_Kpot)\n    tf_s = tf_s.simplify()\n\n    tf_z = tf_s.subs(s,2/(_Tv/1000)*(z-1)/(z+1))\n    tf_z = tf_z.simplify()\n    \n    num = [sym.fraction(tf_z.factor())[0].expand().coeff(z, i) for i in reversed(range(1+sym.degree(sym.fraction(tf_z.factor())[0], gen=z)))]\n    den = [sym.fraction(tf_z.factor())[1].expand().coeff(z, i) for i in reversed(range(1+sym.degree(sym.fraction(tf_z.factor())[1], gen=z)))]\n    #print(num)\n    #print(den)\n\n    tf_sM = _Km*_Kg*_R*(s+_a)/(s*(s+_a)*(s+_am)*_Kt+C*_K1*_Km*_Kg*_Kpot*_Kt)\n    \n    tf_zM = tf_sM.subs(s,2/(_Tv/1000)*(z-1)/(z+1))\n    tf_zM = tf_zM.simplify()\n    num_M = [sym.fraction(tf_zM.factor())[0].expand().coeff(z, i) for i in reversed(range(1+sym.degree(sym.fraction(tf_zM.factor())[0], gen=z)))]\n    #print(num_M)\n    #print(den_M)\n    \n    #print('\\n........finished........')\n    return sym.lambdify((K, taui, taud), [np.array(num), -np.array(num_M), -np.array(den)])\n\nz_transform_p = make_model('P')\nz_transform_pi = make_model('PI')\nz_transform_pid = make_model('PID')\n```\n\n\n```python\ndef calculate_next(z_transform):\n    variables[-1][0] = 0 # set current to zero\n    z_transform = z_transform(_K, _taui, _taud)\n    \n    temp = 0\n    for i in range(len(z_transform)): # for every polynomial\n        for j in range(len(z_transform[i])): # for every term in polynomial\n            temp += z_transform[i][j] * variables[i][j]\n\n    return temp / z_transform[-1][0]*(-1)\n```\n\n\n```python\nfig = plt.figure(figsize=(9.8, 4),num='Antenna azimuth position control system')\n# add axes\nax = fig.add_subplot(121)\ngraph = fig.add_subplot(122)\n    \n#set current theta and theta reference:\nth = [0,0,0,0,0,0]\nthref = [1,0,0,0,0,0]\n# disturbance:\nm = [.1,0,0,0,0,0]\n#joined together (first theta reference, second disturbance, then theta measured):\nvariables = [thref, m, th]\n\n# variables of controller:\n_K = 20\n_taui = 10\n_taud = 1\n\nnew_flag_value = [True, 0] # flag for displaying old value of th, before th_ref was changed [flag, angle]\n\n#slider widgets:\nth_ref_widget = widgets.FloatSlider(value=variables[0][0],min=0.0,max=2*np.pi,step=.01,description=r'\\(\\theta_{ref} \\) [rad]',\n                    disabled=False,continuous_update=True,orientation='horizontal',readout=True,readout_format='.2f')\nm_widget = widgets.FloatSlider(value=variables[1][0],min=-.3,max=.3,step=.01,description=r'\\(d_{w} \\)',\n                    disabled=False,continuous_update=True,orientation='horizontal',readout=True,readout_format='.2f')\nK_widget = widgets.FloatSlider(value=_K,min=0.0,max=40,step=.1,description=r'\\(K_p \\)',\n                    disabled=False,continuous_update=True,orientation='horizontal',readout=True,readout_format='.1f')\ntaui_widget = widgets.FloatSlider(value=_taui,min=0.01,max=60,step=.01,description=r'\\(K_i \\)',\n                    disabled=False,continuous_update=True,orientation='horizontal',readout=True,readout_format='.2f')\ntaud_widget = widgets.FloatSlider(value=_taud,min=0.0,max=5,step=.1,description=r'\\(K_d \\)',\n                    disabled=False,continuous_update=True,orientation='horizontal',readout=True,readout_format='.2f')\n#interact(set_coefficients, setK=K_widget, setthref=th_ref_widget, setm=m_widget, settaui=taui_widget, settaud=taud_widget)\n\n#checkboxes\n#checkbox_reset_antenna = widgets.Checkbox(value=False, description='Reset schematic representation of antenna when type of controller is changed', disabled=False)\n#checkbox_reset_graph = widgets.Checkbox(value=False, description='Reset graph when type of controller is changed', disabled=False)\n\ncheckbox_reset_antenna = widgets.Checkbox(value=False, disabled=False, layout=Layout(width='100px'))\nlabel_scheme = widgets.Label('Ponastavi shematski prikaz sistema ob spremembi tipa krmilnika', layout=Layout(width='500px'))\nbox1 = widgets.HBox([checkbox_reset_antenna, label_scheme])\n                             \ncheckbox_reset_graph = widgets.Checkbox(value=False, disabled=False, layout=Layout(width='100px'))\nlabel_graph = widgets.Label('Ponastavi graf polo\u017eaja antene v odvisnosti od \u010dasa ob spremembi tipa krmilnika', layout=Layout(width='500px'))\nbox2 = widgets.HBox([checkbox_reset_graph, label_graph])\n\nstyle = {'description_width': 'initial'}\n\n#buttons:\ndef buttons_clicked(event):\n    global controller_type, equation, list_th, list_th_ref, list_time\n    controller_type = buttons.options[buttons.index]\n    if controller_type =='P':\n        taui_widget.disabled=True\n        taud_widget.disabled=True\n        equation = '$Kp$'\n    if controller_type =='PI':\n        taui_widget.disabled=False\n        taud_widget.disabled=True\n        equation = '$Kp\\,(1+\\dfrac{1}{T_{i}\\,s})$'\n    if controller_type =='PID':\n        taui_widget.disabled=False\n        taud_widget.disabled=False\n        equation = '$Kp\\,(1+\\dfrac{1}{T_{i}\\,s}+\\dfrac{T_{d}\\,s}{a\\,T_{d}\\,s+1})$'\n    if checkbox_reset_antenna.value:\n        #reset values to zero:\n        for i in range(len(variables)):\n            for j in range(1, len(variables[i])):\n                variables[i][j] = 0\n        variables[-1][0] = 0\n    if checkbox_reset_graph.value:\n        list_th = []\n        list_th_ref = []\n        list_time = []\n        \nbuttons = widgets.ToggleButtons(\n    options=['P', 'PI', 'PID'],\n    description='Izberi tip krmilnika:',\n    disabled=False,\n    style=style)\nbuttons.observe(buttons_clicked)\n\n\n#updating values\ndef set_values(event):\n    global _K, _taui, _taud\n    if event['name'] != 'value':\n        return\n    if th_ref_widget.value != variables[0][0] and not new_flag_value[0]:\n        new_flag_value[0] = True\n        new_flag_value[1] = variables[-1][0]\n        \n    variables[0][0] = th_ref_widget.value\n    variables[1][0] = m_widget.value\n    _K = K_widget.value\n    _taui = taui_widget.value\n    _taud = taud_widget.value\nth_ref_widget.observe(set_values)\nm_widget.observe(set_values)\nK_widget.observe(set_values)\ntaui_widget.observe(set_values)\ntaud_widget.observe(set_values)\n\n#displaying widgets:\ndisplay(buttons)\nvbox1 = widgets.VBox([th_ref_widget, m_widget, K_widget, taui_widget, taud_widget])\nvbox2 = widgets.VBox([box1, box2])\nhbox = widgets.HBox([vbox1, vbox2])\ndisplay(hbox)\n\n#setting at start:\ncontroller_type = 'P'\ntaui_widget.disabled=True\ntaud_widget.disabled=True\nequation = '$Kp$'\nset_values({'name':'value'})\n\n#lists for graph in time:\nlist_time = []\nlist_th = []\nlist_th_ref = []\n\n#previous th before change of th_ref:\nprev_th = 0\n\ncycles_flag = True\n\ndef update_figure(i_time):\n    global cycles_flag, variables, _K, controller_type, equation\n    \n    if cycles_flag == True:\n        cycles_flag = False\n        return\n    \n    if controller_type == 'P':\n        th = calculate_next(z_transform_p)\n    elif controller_type == 'PI':\n        th = calculate_next(z_transform_pi)\n    elif controller_type == 'PID':\n        th = calculate_next(z_transform_pid)\n    variables[-1][0] = th\n    \n    # save variables for next time step:\n    for i in range(len(variables)):\n        for j in reversed(range(len(variables[i])-1)):\n            variables[i][j+1] = variables[i][j]\n\n    list_time.append((i_time+1)*_Tv/1000)\n    list_th.append(th)\n    list_th_ref.append(variables[0][0])\n    \n    #plot:\n    ax.clear()\n    ax.plot([-1.5, 1.5, 1.5, -1.5], [-1.5, -1.5, 1.5, 1.5], ',', color='b')\n    \n    #plot line:\n    ax.plot([np.cos(th)*-.5, np.cos(th)*1.5], [np.sin(th)*-.5, np.sin(th)*1.5], 'b--', linewidth=.7, alpha=.7)\n    \n    #plot antenna:\n    center1 = 1\n    center2 = 3\n    d1 = 2.2\n    d2 = 5.5\n    x1 = center1*np.cos(th)\n    y1 = center1*np.sin(th)\n    x2 = center2*np.cos(th)\n    y2 = center2*np.sin(th)\n    arc1 = patches.Arc((x1, y1), d1, d1,\n                 angle=th/np.pi*180+180, theta1=-58, theta2=58, linewidth=2, color='black', alpha=.7)\n    arc2 = patches.Arc((x2, y2), d2, d2,\n                 angle=th/np.pi*180+180, theta1=-20, theta2=20, linewidth=2, color='black', alpha=.7)\n    ax.add_patch(arc1)\n    ax.add_patch(arc2)\n    if m_widget.value > 0:\n        ax.plot(0, 0, 'r', alpha=.1, marker=r'$\\circlearrowright$',ms=150*m_widget.value)\n    elif m_widget.value < 0:\n        ax.plot(0, 0, 'r', alpha=.1, marker=r'$\\circlearrowleft$',ms=-150*m_widget.value)\n    ax.set_title('Shematski prikaz sistema')\n\n    \n    #plot direction of antenna before thref change\n    if abs(variables[0][0] - th) < 0.03:\n        new_flag_value[0] = False\n    if new_flag_value[0]:\n        ax.plot([0,np.cos(new_flag_value[1])], [0, np.sin(new_flag_value[1])], 'r-.', alpha=.3, linewidth=0.5)\n    #plot desired direction of antenna\n    ax.plot([0,np.cos(variables[0][0])], [0, np.sin(variables[0][0])], 'g-.', alpha=.7, linewidth=0.7)\n    \n    ax.text(-1, 1.3, 'dejanski kot: %.2f rad' %th)\n    ax.text(-1, -1.3, 'tip krmilnika:')\n    ax.text(-1, -1.6, equation)\n    \n    ax.set_aspect('equal', adjustable='datalim')\n    ax.set_xlim(-1.5,1.5)\n    ax.set_ylim(-1.5,1.5)\n    ax.axis('off')\n    \n    graph.clear()\n    graph.plot(list_time, list_th_ref, 'g', label='zahtevani polo\u017eaj')\n    graph.plot(list_time, list_th, 'b', label='dejanski polo\u017eaj')    \n    graph.set_xlabel('$t$ [s]')\n    graph.set_ylabel('$\\\\theta$ [rad]')\n    graph.legend(loc=4, fontsize=8)\n    graph.set_title('Polo\u017eaj antene v odvisnosti od \u010dasa')\n    \n    plt.show()\n\nani = animation.FuncAnimation(fig, update_figure, interval=_Tv)\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n\n    ToggleButtons(description='Izberi tip krmilnika:', options=('P', 'PI', 'PID'), style=ToggleButtonsStyle(descri\u2026\n\n\n\n    HBox(children=(VBox(children=(FloatSlider(value=1.0, description='\\\\(\\\\theta_{ref} \\\\) [rad]', max=6.283185307\u2026\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "66e87881e910bc0cf0ee1dcc13a1146adea2fbb0", "size": 140777, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_si/examples/02/TD-02-Sistem_za_krmiljenje_polozaja_antene.ipynb", "max_stars_repo_name": "ICCTerasmus/ICCT", "max_stars_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-22T18:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:10:22.000Z", "max_issues_repo_path": "ICCT_si/examples/02/.ipynb_checkpoints/TD-02-Sistem_za_krmiljenje_polozaja_antene-checkpoint.ipynb", "max_issues_repo_name": "ICCTerasmus/ICCT", "max_issues_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICCT_si/examples/02/.ipynb_checkpoints/TD-02-Sistem_za_krmiljenje_polozaja_antene-checkpoint.ipynb", "max_forks_repo_name": "ICCTerasmus/ICCT", "max_forks_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-24T11:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T16:36:18.000Z", "avg_line_length": 102.6071428571, "max_line_length": 82163, "alphanum_fraction": 0.777477855, "converted": true, "num_tokens": 5078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22541661583507672, "lm_q2_score": 0.20689405859634893, "lm_q1q2_score": 0.04663735852517304}}
{"text": "<font size = \"5\"> **Chapter 4: [Spectroscopy](CH4-Spectroscopy.ipynb)** </font>\n\n<hr style=\"height:1px;border-top:4px solid #FF8200\" />\n\n\n\n# Introduction to Core-Loss Spectroscopy\n<font size = \"5\">Working with X-Sections</font>\n\n[Download](https://raw.githubusercontent.com/gduscher/MSE672-Introduction-to-TEM/main/Spectroscopy/CH4_07-Introduction_Core_Loss.ipynb)\n \n[](\n    https://colab.research.google.com/github/gduscher/MSE672-Introduction-to-TEM/blob/main/Spectroscopy/CH4_07-Introduction_Core_Loss.ipynb)\n\n\npart of \n\n<font size = \"5\"> **[MSE672:  Introduction to Transmission Electron Microscopy](../_MSE672_Intro_TEM.ipynb)**</font>\n\nby Gerd Duscher, Spring 2021\n\nMicroscopy Facilities<br>\nJoint Institute of Advanced Materials<br>\nMaterials Science & Engineering<br>\nThe University of Tennessee, Knoxville\n\nBackground and methods to analysis and quantification of data acquired with transmission electron microscopes.\n\n## Core --Loss Spectroscopy\n\nAs we can see in figure below the energies of the core shells are well defined and can be viewed as delta functions, unlike in the low loss region where the broad valence bands are the initial state. In both cases, however, we excite electrons into the conduction band.\n\n\n*Excitation from a core-shell state up into the conduction band above the Fermi level.*\n\nIf we look at the transition between two states $< \\Phi_f | H | \\Phi_i >$ the transition should be quite sharp. In the case of the low-loss spectrum, we have many initial (the valence) states and many final (the conduction) states. The spectrum will be a convolution of these states. \n\nThe features of the core--loss edges are, therefore, much sharper than any details in the low--loss region. Because only the final states contribute to the features. These sharp features enable a wide variety of analysis to determine the chemical compositions and chemical bonding, probing the local conduction band of the sample.\n\n\n\n### Chemical Composition\n\nIn this chapter we use the area under the ionization edge to determine the chemical composition of a (small) sample volume. \nThe equation used to determine the number of atoms per unit volume $N$ (also called areal density) is:\n\\begin{equation}\nI_{edge}(\\beta, \\Delta E) = N I_{0}(\\beta) \\sigma_{edge}(\\beta, \\Delta E)\n\\end{equation}\n\n$I_0$ is the number of electrons hitting the sample, and so directly comparable to the beam current.\n\nThe equation can be approximated assuming that the spectrum has not been corrected for single scattering:\n\\begin{equation} \nI_{edge}(\\beta, \\Delta E) = N I_{low-loss}(\\beta,\\Delta E) \\sigma_{edge}(\\beta, \\Delta E)\n\\end{equation}\nwhere $\\beta$ is the collection angle and $\\sigma_{edge}$ is the **partial** cross--section (for energy window $\\Delta E$) for the core--loss excitation.\n\n\n> \n> It is this cross-section $ \\sigma_{edge}$ that we want to explorein this notebook.\n>\nWe will do the chemical composition in the [next notebook](CH4_08-Chemical_Composition.ipynb)\n\n\n\n## Load important packages\n\n### Check Installed Packages\n\n\n\n```python\nimport sys\nfrom pkg_resources import get_distribution, DistributionNotFound\n\ndef test_package(package_name):\n    \"\"\"Test if package exists and returns version or -1\"\"\"\n    try:\n        version = get_distribution(package_name).version\n    except (DistributionNotFound, ImportError) as err:\n        version = '-1'\n    return version\n\n# Colab setup ------------------\nif 'google.colab' in sys.modules:\n    !pip install pyTEMlib -q\n# pyTEMlib setup ------------------\nelse:\n    if test_package('sidpy') < '0.0.5':\n        print('installing sidpy')\n        !{sys.executable} -m pip install  --upgrade pyTEMlib -q\n    if test_package('pyTEMlib') < '0.2021.4.20':\n        print('installing pyTEMlib')\n        !{sys.executable} -m pip install  --upgrade pyTEMlib -q\n# ------------------------------\nprint('done')\n```\n\n    done\n\n\n### Import all relevant libraries\n\nPlease note that the EELS_tools package from pyTEMlib is essential.\n\n\n```python\nimport sys\nif 'google.colab' in sys.modules:\n    %pylab --no-import-all inline\nelse:    \n    %pylab --no-import-all notebook\n    %gui qt\n    \nimport warnings\nwarnings.filterwarnings('ignore')\n\n## We need to import a few important additional function from matplotlib, \n## because we want to demonstrate a few more hidden functionalities of the EELS_tools of pytTEMlib.\nfrom matplotlib.widgets import Cursor\nfrom matplotlib.patches import Rectangle\nfrom matplotlib.widgets import SpanSelector\n\n## import the configuration files of pyTEMlib (we need access to the data folder)\nimport pyTEMlib\nimport pyTEMlib.eels_tools as eels\nimport pyTEMlib.interactive_eels as ieels\n\n# For archiving reasons it is a good idea to print the version numbers out at this point\nprint('pyTEM version: ',pyTEMlib.__version__)\n```\n\n    Populating the interactive namespace from numpy and matplotlib\n    pyTEM version:  0.2021.04.20\n\n\n## Load Cross-Sections\n\n\nThe form factors are from:\nX-Ray Form Factor, Attenuation, and Scattering Tables\nNIST Standard Reference Database 66\n\n DOI: https://dx.doi.org/10.18434/T4HS32\n\nDetailed Tabulation of Atomic Form Factors, Photoelectric Absorption and Scattering Cross Section, and Mass Attenuation Coefficients for Z = 1-92 from E = 1-10 eV to E = 0.4-1.0 MeV\nC.T. Chantler,1 K. Olsen, R.A. Dragoset, J. Chang, A.R. Kishore, S.A. Kotochigova, and D.S. Zucker\nNIST, Physical Measurement Laboratory\n\nThe cross sections are part of the pyTEMlib package and are stored as a pickled dictionary in the package data directory.\n\nBelow are the lines for accessing the cross sections with eels_tools of pyTEMlib.\n\n\n```python\nXsections = eels.get_x_sections()\n```\n\n## Plot Cross Sections\n\nPlease add your favourite element ot the list of atomic numbers.\n\nWith the code cell above we made the whole database of cross secitons available for this notebook.\n\n\n```python\n# -----Input ------------ #\natomic_numbers = [16, 42]\n# ----------------------- #\nfig, ax = plt.subplots()\nfor Z in atomic_numbers:\n    ax.plot(Xsections[str(Z)]['ene'], Xsections[str(Z)]['dat'], label = Xsections[str(Z)]['name'])\n\nax.set_xlim(0,600)\nax.set_ylim(0,2.5e17)\nplt.legend();\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n### List All Edges of an Element \n\n\n```python\nelement = str(42)\nfor key in Xsections[element]:\n    if isinstance(Xsections[element][key], dict):\n        if 'onset' in Xsections[element][key]:\n            print(f\"{Xsections[element]['name']}-{key}: {Xsections[element][key]['onset']:8.1f} eV \")\n            \n\n```\n\n    Mo-N3:     34.8 eV \n    Mo-M5:    227.0 eV \n    Mo-N5:      1.8 eV \n    Mo-M4:    230.3 eV \n    Mo-N2:     34.8 eV \n    Mo-N1:     61.8 eV \n    Mo-L3:   2520.2 eV \n    Mo-M1:    504.6 eV \n    Mo-L2:   2625.1 eV \n    Mo-L1:   2865.5 eV \n    Mo-K1:  19999.5 eV \n    Mo-N4:      1.8 eV \n    Mo-M3:    392.3 eV \n    Mo-M2:    409.7 eV \n\n\nOr ordered\n\n\n```python\nmajor_edges = ['K1', 'L3', 'M5', 'N5']\nall_edges = ['K1','L1','L2','L3','M1','M2','M3','M4','M5','N1', 'N2','N3','N4','N5','N6','N7','O1','O2','O3','O4','O5','O6','O7', 'P1', 'P2', 'P3']\nfirst_close_edges = ['K1', 'L3', 'M5', 'M3', 'N5', 'N3']\n\nelement = str(42)\n\ndef list_all_edges(Z):\n    element = str(Z)\n    print('All edges')\n    for key in all_edges:\n        if key in Xsections[element]:\n            if 'onset' in Xsections[element][key]:\n                print(f\" {Xsections[element]['name']}-{key}: {Xsections[element][key]['onset']:8.1f} eV \")\n\ndef list_major_edges(Z):\n    element = str(Z)\n    print('Major edges')\n    for key in major_edges:\n        if key in Xsections[element]:\n            if 'onset' in Xsections[element][key]:\n                print(f\" {Xsections[element]['name']}-{key}: {Xsections[element][key]['onset']:8.1f} eV \")                      \n## Here with the function of the EELS_tools package                      \nlist_all_edges(element)\nlist_major_edges(element)\n```\n\n    All edges\n     Mo-K1:  19999.5 eV \n     Mo-L1:   2865.5 eV \n     Mo-L2:   2625.1 eV \n     Mo-L3:   2520.2 eV \n     Mo-M1:    504.6 eV \n     Mo-M2:    409.7 eV \n     Mo-M3:    392.3 eV \n     Mo-M4:    230.3 eV \n     Mo-M5:    227.0 eV \n     Mo-N1:     61.8 eV \n     Mo-N2:     34.8 eV \n     Mo-N3:     34.8 eV \n     Mo-N4:      1.8 eV \n     Mo-N5:      1.8 eV \n    Major edges\n     Mo-K1:  19999.5 eV \n     Mo-L3:   2520.2 eV \n     Mo-M5:    227.0 eV \n     Mo-N5:      1.8 eV \n\n\n### Plotting all edges of an element in view\n\nNow, let's do it graphically\n\n\n```python\nmajor_edges = ['K1', 'L3', 'M5', 'N5']\nall_edges = ['K1','L1','L2','L3','M1','M2','M3','M4','M5','N1', 'N2','N3','N4','N5','N6','N7','O1','O2','O3','O4','O5','O6','O7', 'P1', 'P2', 'P3']\nfirst_close_edges = ['K1', 'L3', 'M5', 'M3', 'N5', 'N3']\n\ndef get_Z(Z):\n    \"\"\"\n    returns the atomic number independent of input as a string or number\n    \n    input:\n    Z: atomic number of chemical symbol (0 if not valid)\n    \"\"\"\n    Xsections = eels.get_x_sections()\n    \n    Z_out = 0\n    if str(Z).isdigit(): \n        Z_out = Z\n    elif isinstance(Z, str):\n        for key in Xsections:\n            if Xsections[key]['name'].lower() == Z.lower(): ## Well one really should know how to write elemental \n                Z_out = int(key)\n    return Z_out\n\n\nclass ElementalEdges(object):\n    def __init__(self, ax, Z):\n        self.ax = ax\n        self.labels = None\n        self.lines = None\n        \n        self.Z = get_Z(Z)\n        self.color = 'black'\n        self.Xsections = eels.get_x_sections()\n        self.cid = ax.figure.canvas.mpl_connect('draw_event', self.onresize)\n        \n        #self.update()\n    def set_edge(self,Z):\n        self.Z = get_Z(Z)\n        \n            \n        self.update()\n    def onresize(self, event):\n        self.update()\n        \n    def update(self):\n        \n        if self.labels != None:\n            for label in self.labels:\n                label.remove()\n        if self.lines != None:\n            for line in self.lines:\n                line.remove()\n        if self.Z>0:\n            self.labels = [] ; self.lines =[] \n            x_min, x_max = self.ax.get_xlim()\n            y_min, y_max = self.ax.get_ylim()\n            x_bounds = ax.get_xlim()\n            element = str(self.Z)\n            Xsections = self.Xsections\n            for key in all_edges:\n                if key in Xsections[element]:\n                    if 'onset' in Xsections[element][key]:\n                        x = Xsections[element][key]['onset']\n                        if x > x_min and x < x_max:\n                            if key in first_close_edges:\n                                label2 = self.ax.text(x, y_max,f\"{Xsections[element]['name']}-{key}\",\n                                                      verticalalignment='top', rotation = 0, color = self.color)\n                            else:\n                                label2 = self.ax.text(x, y_max,f\"\\n{Xsections[element]['name']}-{key}\",\n                                                      verticalalignment='top', color = self.color)\n                            line2 = self.ax.axvline(x,ymin = 0,ymax = 1,color=self.color)\n\n                            self.labels.append(label2)\n\n                            self.lines.append(line2)\n                    \n        \n    def disconnect(self):\n        if self.labels != None:\n            for label in self.labels:\n                label.remove()\n        if self.lines != None:\n            for line in self.lines:\n                line.remove()\n        self.labels = None\n        self.lines = None\n        self.ax.figure.canvas.mpl_disconnect(self.cid)\n    def reconnect(self):    \n        self.cid = ax.figure.canvas.mpl_connect('draw_event', self.onresize)\n        ax.figure.canvas.draw_idle()\n        \nfig, ax_Xsec = plt.subplots()                \nfor Z in atomic_numbers:\n    ax_Xsec.plot(Xsections[str(Z)]['ene'], Xsections[str(Z)]['dat'], label = Xsections[str(Z)]['name'])\nax_Xsec.set_xlim(100,550)\nax_Xsec.set_ylim(0,1e17)\nplt.legend();   \nZ = 42\nedges = ieels.ElementalEdges(ax_Xsec, 'Mo')\n\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\nLet's make the lines disappear\n\n\n```python\nedges.disconnect()\n```\n\nand reappear in the plot above\n\n\n```python\nedges.set_edge(Z)\n```\n\nLet's set another edge\n\n\n```python\nedges.set_edge(16)\n```\n\n### Find Edges Listed in Xsection Dictionary\n\nplease note that the two functions below are as ususal available in the EELS_tools of pyTEMlib\n\n\n```python\ndef find_major_edges(edge_onset, maximal_chemical_shift = 5):\n    text = ''\n    for element in Xsections:\n        for key in Xsections[element]:\n            \n            #if isinstance(Xsections[element][key], dict):\n            if key in major_edges:\n                \n                #if 'onset' in Xsections[element][key]:\n                #print(key, Xsections[element][key])\n                if abs(Xsections[element][key]['onset'] - edge_onset) < maximal_chemical_shift:\n                    #print(element, Xsections[element]['name'], key, Xsections[element][key]['onset'])\n                    text = text+ f\"\\n {Xsections[element]['name']:2s}-{key}: {Xsections[element][key]['onset']:8.1f} eV \"\n                    \n    return text\ndef find_all_edges(edge_onset, maximal_chemical_shift = 5):\n    text = ''\n    for element in Xsections:\n        for key in Xsections[element]:\n            \n            if isinstance(Xsections[element][key], dict):\n            \n                \n                if 'onset' in Xsections[element][key]:\n                \n                    if abs(Xsections[element][key]['onset'] - edge_onset) < maximal_chemical_shift:\n                        #print(element, Xsections[element]['name'], key, Xsections[element][key]['onset'])\n                        text = text+ f\"\\n {Xsections[element]['name']:2s}-{key}: {Xsections[element][key]['onset']:8.1f} eV \"\n                    \n    return text\n\n\nedge_onset = 284\nmaximal_chemical_shift = 7\nprint(f'Major Edges within {maximal_chemical_shift:.1f} eV of {edge_onset:.1f}')\nprint(eels.find_major_edges(edge_onset, maximal_chemical_shift))\nprint(f'\\nAll Edges within {maximal_chemical_shift:.1f} eV of {edge_onset:.1f}')\nprint(eels.find_all_edges(edge_onset, maximal_chemical_shift))\n```\n\n    Major Edges within 7.0 eV of 284.0\n    \n     C -K1:    283.8 eV \n     Ru-M5:    279.4 eV \n    \n    All Edges within 7.0 eV of 284.0\n    \n     C -K1:    283.8 eV \n     Gd-N2:    288.5 eV \n     Ce-N1:    289.6 eV \n     Kr-M1:    288.3 eV \n     Tb-N3:    285.0 eV \n     Os-N4:    289.4 eV \n     Sr-M2:    279.8 eV \n     Eu-N2:    283.9 eV \n     Ru-M5:    279.4 eV \n     Ru-M4:    283.6 eV \n\n\n### Find Edges Depending on Cursor Postion\n\n\n```python\n# We are using \n# from matplotlib.widgets import Cursor\n\n\nmaximal_chemical_shift = 5\nfig, ax = plt.subplots()\nplt.title(f'Click with left for major and right mouse button for all \\n ionization edges within {maximal_chemical_shift:.1f} eV of cursor')\nmaximal_chemical_shift = 5\ncursor = ieels.EdgesAtCursor(ax, Xsections['42']['ene'], Xsections['42']['dat'],maximal_chemical_shift)\ncursor.maximal_chemical_shift =maximal_chemical_shift\ncid =  plt.connect('motion_notify_event', cursor.mouse_move)\n\nax.plot(Xsections['16']['ene'], Xsections['16']['dat']*2, label = 'S')\nax.plot(Xsections['42']['ene'], Xsections['42']['dat'], 'r', label = 'Mo')\nax.set_xlim(0,500)\nax.set_ylim(0,2.5e17);\n\n\n\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n## EELS cross sections\n### Determine Effective Collection Angle\n\nEELS cross sections are dependent on the momentum transfer (angle dependence), while photons cannot transfer any momentum. The angle dependence is given by the experimental set-up and can be calculated by the convolution of collection and convergence angle.\n\nHere we use the method of [Pierre Trebbia, Ultramicroscopy **24** (1988) pp.399-408](https://doi.org/10.1016/0304-3991(88)90130-1)\n\n\n\n```python\ndef effective_collection_angle(ene,  alpha, beta, beamkV):\n    \"\"\" effective collection angle for convergent beam setup\n    \n    \n    \n    Original abstract of function y = effbeta(ene,  alpha, beta, beamkV)\n    # \n    #       This program computes etha(alpha,beta), that is the collection\n    #       efficiency associated to the following geometry :\n    #\n    #       alpha = half angle of illumination  (0 -> pi/2)\n    #       beta  = half angle of collection    (0 -> pi/2)\n    #                                           (pi/2 = 1570.795 mrad)\n    #\n    #           A constant angular distribution of incident electrons is assumed\n    #       for any incident angle (-alpha,alpha). These electrons impige the\n    #       target and a single energy loss event occurs, with a characteristic\n    #       angle theta-e (relativistic). The angular distribution of the\n    #       electrons after the target is analytically derived.\n    #           This program integrates this distribution from theta=0 up to\n    #       theta=beta with an adjustable angular step.\n    #           This program also computes beta* which is the theoretical\n    #       collection angle which would give the same value of etha(alpha,beta)\n    #       with a parallel incident beam.\n    #\n    #       subroutines and function subprograms required\n    #       ---------------------------------------------\n    #       none\n    #\n    #       comments\n    #       --------\n    #\n    #       The following parameters are asked as input :\n    #        accelerating voltage (kV), energy loss range (eV) for the study,\n    #        energy loss step (eV) in this range, alpha (mrad), beta (mrad).\n    #       The program returns for each energy loss step :\n    #        alpha (mrad), beta (mrad), theta-e (relativistic) (mrad),\n    #        energy loss (eV), etha (#), beta * (mrad)\n    #\n    #       author :\n    #       --------\n    #       Pierre TREBBIA\n    #       US 41 : \"Microscopie Electronique Analytique Quantitative\"\n    #       Laboratoire de Physique des Solides, Bat. 510\n    #       Universite Paris-Sud, F91405 ORSAY Cedex\n    #       Phone : (33-1) 69 41 53 68\n    #\n    #       \n    \"\"\"\n        \n       \n    z1 = beamkV*1000.  ;   # eV\n    z2 = ene[0];\n    z3 = ene[-1]\n    z4 = 100.0\n    z5 = alpha*0.001   # rad\n    z6 = beta*0.001    # rad\n    z7 = 500          # number of integration steps to be modified at will\n\n    # main loop on energy loss\n    \n    for  zx in range(int(z2),int(z3),int(z4)): #! zx = current energy loss\n        eta=0.0;\n        x0=float(zx)*(z1+511060.)/(z1*(z1+1022120.));  # x0 = relativistic theta-e\n        x1 = np.pi/(2.*x0);\n        x2=x0*x0+z5*z5;\n        x3=z5/x0*z5/x0;\n        x4=0.1*np.sqrt(x2);\n        dtheta=(z6-x4)/z7;\n    #\n    # calculation of the analytical expression\n    #\n    for zi in range(1, int(z7)):\n        theta=x4+dtheta*float(zi);\n        x5=theta*theta;\n        x6=4.*x5*x0*x0;\n        x7=x2-x5;\n        x8=np.sqrt(x7*x7+x6);\n        x9=(x8+x7)/(2.*x0*x0);\n        x10=2.*theta*dtheta*np.log(x9);\n        eta=eta+x10;\n\n          \n\n    eta=eta+x2/100.*np.log(1.+x3)   ;  # addition of the central contribution\n    x4=z5*z5*np.log(1.+x1*x1);         # normalisation\n    eta=eta/x4;\n    #\n    #        correction by geometrical factor (beta/alpha)**2\n    #\n    if (z6<z5):\n        x5=z5/z6;\n        eta=eta*x5*x5;\n\n    etha2=eta*100.;\n    #\n    #        calculation of beta *\n    #\n    x6=np.power((1.+x1*x1),eta);\n    x7=x0*np.sqrt(x6-1.);\n    y=x7*1000.;\n\n    \n    return y\n\n    \n```\n\n\n```python\nenergy_scale = np.linspace(100,500,1000)\nalpha=30 \nbeta=33\neff_beta = eels.effective_collection_angle(energy_scale,  alpha=alpha, beta=beta, beam_kv=200000)\nprint(f'Convergence angle  {alpha:.2f} mrad and collection angle {beta:.2f} mrad \\n '\n      f'results in effective collection angle of is {eff_beta:.2f} mrad')\n```\n\n    Convergence angle  30.00 mrad and collection angle 33.00 mrad \n     results in effective collection angle of is 24.05 mrad\n\n\n### Calculating EELS Cross Section\n\nEELS cross sections are dependent on the momentum transfer (angle dependence), while photons cannot transfer any momentum. The angle dependence of the cross-section is aproximated by the equation 4 in:\n[Egerton Ultramicroscopy 50 (1993) 13-28](https://doi.org/10.1016/0304-3991(93)90087-E)\n\nThe units of atom density in  electron microscopy is atoms per nm$^2$.\nCross sections are normally given in barns (a neutron scattering joke).\n\nA barn is 10$^{-28}$ m$^2$ which is then 1 barn = 10$^{-10}$ nm$^2$\n\nTherefore, to get a probability per nm$^2$ we have to divide the cross-section in barns by 10$^{10}$\n\n\ud835\udc3c\ud835\udc52\ud835\udc51\ud835\udc54\ud835\udc52(\ud835\udefd,\u0394\ud835\udc38)=\ud835\udc41\ud835\udc3c\ud835\udc59\ud835\udc5c\ud835\udc64\u2212\ud835\udc59\ud835\udc5c\ud835\udc60\ud835\udc60(\ud835\udefd,\u0394\ud835\udc38)\ud835\udf0e\ud835\udc52\ud835\udc51\ud835\udc54\ud835\udc52(\ud835\udefd,\u0394\ud835\udc38)\n\n\n\n```python\n\nfrom scipy.interpolate import splev,splrep,splint\n#from scipy.integrate import quad\nfrom scipy.interpolate import interp1d\nfrom scipy.optimize import leastsq\n\ndef xsec_xrpa(energy_scale, E0, Z, beta, shift=0 ):\n    \"\"\"\n    Calculate momentum-integrated cross-section for EELS from X-ray photoaborption  cross-sections.\n    \n    Input:\n    ------\n    energy_scale: energyscale of spectrum to be analyzed\n    E0: acceleration voltage in keV\n    Z: atomic number of element\n    beta: effective collection angle in mrad\n    shift: chemical shift of edge in eV\n    \"\"\"\n \n    beta = beta * 0.001;     #% collection half angle theta [rad]\n    #thetamax = self.parent.spec[0].convAngle * 0.001;  #% collection half angle theta [rad]\n    dispersion = energy_scale[1]-energy_scale[0]\n    \n    Xsections = eels.get_Xsections(Z)\n    enexs = Xsections['ene']\n    datxs = Xsections['dat']\n        \n    #####\n    ## Cross Section according to Egerton Ultramicroscopy 50 (1993) 13-28 equation (4)\n    #####\n\n    # Relativistic correction factors\n    T = 511060.0*(1.0-1.0/(1.0+E0/(511.06))**2)/2.0;\n    gamma=1+E0/511.06;\n    A = 6.5#e-14 *10**14\n    b = beta\n\n    thetaE = enexs/(2*gamma*T)\n\n    G = 2*np.log(gamma)-np.log((b**2+thetaE**2)/(b**2+thetaE**2/gamma**2))-(gamma-1)*b**2/(b**2+thetaE**2/gamma**2)\n    datxs = datxs*(A/enexs/T)*(np.log(1+b**2/thetaE**2)+G)/1e8\n\n    datxs = datxs * dispersion # from per eV to per dispersion\n    coeff = splrep(enexs,datxs,s=0) # now in areal density atoms / m^2\n    xsec = np.zeros(len(energy_scale ))\n    #shift = 0# int(ek -onsetXRPS)#/dispersion\n    lin = interp1d(enexs,datxs,kind='linear') # Linear instead of spline interpolation to avoid oscillations.\n    xsec = lin(energy_scale-shift)\n    \n    return xsec\nenergy_scale = np.arange(100,600)\nB_Xsection = eels.xsec_xrpa(energy_scale, 200, 5,  10. )/1e10  \nN_Xsection = eels.xsec_xrpa(energy_scale, 200, 7,  10. )/1e10       #  xsec  is in barns = 10^28 m2 = 10^10 nm2\n\n```\n\n### Plotting of Cross Sections\nplease note that spectrum and cross sections are not on the same scale\n\n\n```python\nS_Xsection  = eels.xsec_xrpa(energy_scale, 200, 16, 10. )/1e10  \nMo_Xsection = eels.xsec_xrpa(energy_scale, 200, 42, 10. ,shift=0)/1e10       #  xsec  is in barns = 10^28 m2 = 10^10 nm2\n\nfig, ax1 = plt.subplots()\n\nax1.plot(energy_scale, S_Xsection, label='S X-section' )\nax1.plot(energy_scale, Mo_Xsection, label='Mo X-section' )\nax1.set_xlabel('energy_loss [eV]')\nax1.set_ylabel('probability [atoms/nm$^{2}$]')\n\n\nplt.legend();\nfig.tight_layout();\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n## Summary\n\nThe cross section is key to determine the chemical composition of an EELS spectrum. \nThese cross sections are dependent on:\n- acceleration voltage\n- effective collection angle\n- element\n\nSo these experimental parameters have to be provided for a calculations of cross sections.\n\nWe will use these cross sections in the [chemical compostions notebook](CH4_08-Chemical_Composition.ipynb)\n\n## Navigation\n- <font size = \"3\">  **Up Chapter 4: [Imaging](CH4_00-Spectroscopy.ipynb)** </font>\n- <font size = \"3\">  **Back: [Dielectric Function](CH4_03-Drude.ipynb)** </font>\n- <font size = \"3\">  **Next: [Chemical Composition](CH4_08-Chemical_Composition.ipynb)** </font>\n- <font size = \"3\">  **List of Content: [Front](../_MSE672_Intro_TEM.ipynb)** </font>\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "0851ae0dee7e377150e86ba261ec39c58ffc53bf", "size": 585397, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Spectroscopy/CH4_07-Introduction_Core_Loss.ipynb", "max_stars_repo_name": "ahoust17/MSE672-Introduction-to-TEM", "max_stars_repo_head_hexsha": "6b412a3ad07ee273428a95a7158aa09058d7e2ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-01-22T18:09:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T20:17:34.000Z", "max_issues_repo_path": "Spectroscopy/CH4_07-Introduction_Core_Loss.ipynb", "max_issues_repo_name": "ahoust17/MSE672-Introduction-to-TEM", "max_issues_repo_head_hexsha": "6b412a3ad07ee273428a95a7158aa09058d7e2ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Spectroscopy/CH4_07-Introduction_Core_Loss.ipynb", "max_forks_repo_name": "ahoust17/MSE672-Introduction-to-TEM", "max_forks_repo_head_hexsha": "6b412a3ad07ee273428a95a7158aa09058d7e2ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2021-01-26T16:10:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T14:53:16.000Z", "avg_line_length": 118.5974473258, "max_line_length": 109175, "alphanum_fraction": 0.7840559484, "converted": true, "num_tokens": 6839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.12421301321508335, "lm_q1q2_score": 0.046440242514740916}}
{"text": "```python\n#\n```\n\n\n```python\nimport numpy as np\nimport pandas as pd\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\n%matplotlib inline\n```\n\n # Seminario: Optimizaci\u00f3n con Pyomo\n \n _Jose Angel Velasco (javelascor@indra.es)_ \n \n _Indra Digital Labs | IA_\n \n _26 Marzo de 2021_\n\n\n## Motivaci\u00f3n\n\n\n## Introducci\u00f3n a la optimizacion\n* La __optimizaci\u00f3n__ consiste en la toma de la mejor decisi\u00f3n posible (de un conjunto de soluciones factibles) en base a un objetivo concreto (funcion objetivo) y sujeto a ciertos requisitos (restricciones)\n\n* Mediante __programaci\u00f3n matem\u00e1tica__ se puede formular dicha funcion objetivo y restricciones utilizando un lenguaje algebraico\n\n* Alternativa a programaci\u00f3n matem\u00e1tica: _m\u00e9todos heuristicos_\n\n* El soporte a la toma de decisiones mediante optimizaci\u00f3n con programaci\u00f3n matem\u00e1tica es a menudo desconocida o bien descartada por falta de tiempo y/o recursos. \n\n* En este seminario se realizar\u00e1 un breve repaso a conceptos de optimizaci\u00f3n y se\npresentar\u00e1 Pyomo para la resoluci\u00f3n de diferentes problemas tipo.\n\n\n\n\n\n##### Ejemplos\n\n* Problemas Lineales\n    * __Problemas del transporte__\n    * Problema de la planificaci\u00f3n de la producci\u00f3n\n    * Problema de la dieta\n    * __Problema del flujo en una red__\n    * __Problema de la cartera de valores__\n    * Problema del despacho economico de centrales el\u00e9ctricas\n* Problemas lineal entero-mixto\n    * __Optimizaci\u00f3n de rutas__\n    * Problema de la mochila\n    * Problema de Identificaci\u00f3n de sintomas relevantes\n    * Problema de la academia de ingenieria\n    * Problema del horario\n    * __Problema de localizaci\u00f3n de plantas logisticas__\n    * __Problema de programaci\u00f3n de centrales eletricas (t\u00e9rmica)__\n    * Problema de coordinaci\u00f3n de centrales electricas (termica e hidrot\u00e9rmica)\n    \n\n* Problemas no-lineales\n    * __Problema de estimaci\u00f3n de estado de sensores (state estimation)__\n    * Problema del reparto \u00f3ptimo de carga en redes electricas (Optimal power flow)\n    * __Problema de la asignaci\u00f3n de trafico__\n    * Problemas de regresi\u00f3n (m\u00ednimos cuadrados)\n    * Aplicaciones de inteligencia artificial (ej: redes neuronales RMSE como objetivo) \n    * Control \u00f3ptimo para el alcance de un blanco\n\n### Programacion matematica \n* La programaci\u00f3n matem\u00e1tica tiene su origen en 1947 cuando George B. Dantzig public\u00f3 el algoritmo [Simplex](https://en.wikipedia.org/wiki/Simplex_algorithm) (Programaci\u00f3n lineal)\n\n\n\n* En la p\u00e1ctica, un problema de optimizaci\u00f3n consiste minimizar (o maximizar) una funci\u00f3n objetivo __convexa__ y real $f(x)$ eligiendo sistem\u00e1ticamente valores de entrada (tomados de un conjunto permitido) y calculando el valor de la funci\u00f3n sujeto a ciertas restricciones de igualdad y desigualdad. \n\n\\begin{array}{ll}\n\\min & f(x) = c^{T} x\\\\\ns.t. & g(x) = b\\\\\n     & h(x) \\leq c\\\\\n     & x \\geq 0 \n\\end{array}\n\n   * $x$ es la variable de decision\n\n   * $f(x)$ es la funcion objetivo (minimizar costes, retrasos, riesgos, etc...)\n   \n   * $g(x)$ y $h(x)$ son restricciones y definen limitaciones, realidades de negocio, etc.\n\n### Forma standard\n   * minimizacion\n   * restricciones de igualdad ( si las hay, existen tecnicas para convertir a igualdad)\n   * $x>0$\n   * $b>0$\n* Si la funci\u00f3n objetivo o las restricciones tienen elementos no lineales ($x^2, sin(x), ...$), el problema es NLP (Non-Linear Programming)\n\n* Si existen variables enteras $x \\in (0,1)$ el problema es MIP (Mixed-Integer Programming)\n\n* Una soluci\u00f3n $\\tilde{x} = (x_1 , x_2 , \\ldots , x_n )$ que satisface todas las restricciones  se denomina _solucion factible_. El conjunto de todas esas soluciones es la _region de factibilidad_ \n* Un punto factible $\\tilde{x}^{*}$ tal que $f(\\tilde{x}^{*}) \\leq f(\\tilde{x})$ para cualquier otro punto factible $\\tilde{x}$ se denomina una _solucion optima_ del problema.\n\n### Dualidad\nEs una relacion simetrica, esto es, si el problema D es\nel dual del problema P, entonces P es el dual de D.\n\nDado el problema de programacion lineal denominado problema _primal_,\n\n\\begin{array}{ll}\n\\min & f(x) = c^{T} x\\\\\ns.t. & Ax \\ge  b\\\\\n     & x \\geq 0 \n\\end{array}\n\nsu problema _dual_ es maximizar:\n\n\\begin{array}{ll}\n\\max & f^{'}(y) = b^{T} y\\\\\ns.t. & A^{T} y \\leq  c\\\\\n     & y \\geq 0 \n\\end{array}\n\n$y$ es __variable dual__\n\nBajo ciertas hipotesis, los problemas _primal_ y _dual_ dan lugar al mismo valor optimo de la funcion objetivo, y por tanto se puede resolver indirectamente el problema primal resolviendo el problema dual.\n\n### Programacion Lineal\n\n\n\n* Funcion objetivo y restricciones lineales\n* Algoritmo:\n    * simplex\n    * Punto interior\n\n* Ejemplo: \n\n\\begin{array}{ll}\n\\min & 2x + 3y \\\\\ns.t. & 3x + 4y \\geq 1\\\\\n     & x,y \\geq 0 \n\\end{array}\n\n\n\n```python\nx = np.linspace(0, 1)\ny = np.linspace(0, 1)\nxx, yy = np.meshgrid(x, y)\n\nplt.figure(figsize=(8,6))\nplt.contour(xx, yy, 2 * xx + 3 * yy, colors='k')\nplt.contourf(xx, yy, 3 * xx + 4 * yy, cmap=plt.cm.viridis)\nplt.colorbar()\nplt.xlabel('x', fontsize=18)\nplt.ylabel('y',fontsize=18)\nplt.show()\n```\n\n\n```python\n#we will use numpy functions in order to work with numpy arrays\ndef function(x,y):\n    z  = 2 * x + 3 * y\n    #z  = 3 * x + 4 * y\n    return z\n\nn = 200\nx = np.random.uniform(0, 1, n)\ny = np.random.uniform(0, 1, n)\nz = function(x, y)\n\n#we create two 1D arrays of the desired lengths:\nx_1d = np.linspace(min(x), max(x), n)\ny_1d = np.linspace(min(y), max(y), n)\n\n#And we use the meshgrid function to create the X and Y matrices!\nX, Y = np.meshgrid(x_1d, y_1d)\n\n#Using Numpy arrays, calculating the function value at the points is easy!\nZ = function(X,Y)\n\nfig = plt.figure(figsize=(16,10))\nax = fig.add_subplot(111, projection='3d')\n\nsurf = ax.plot_surface(X, Y, Z,\n                       rstride=2,\n                       cstride=2,\n                       alpha=0.6,\n                       cmap=plt.cm.viridis, #cm.jet, # coolwarm\n                       linewidth=0, antialiased=False)\n# Customize the z axis.\n#ax.set_zlim(-120, 120)\nax.zaxis.set_major_locator(LinearLocator(10))\nax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\n\n# add contour \ncset = ax.contour(X, Y, Z, zdir='y', cmap=cm.coolwarm)\n\nax.set_xlabel('X')\n#ax.set_xlim(-8, 8)\nax.set_ylabel('Y')\n#ax.set_ylim(-8, 8)\nax.set_zlabel('Z')\n#ax.set_zlim(-2, 2)\n\n# Add a color bar which maps values to colors.\nfig.colorbar(surf, shrink=0.4, aspect=5)\nplt.show()\n```\n\n### Programaci\u00f3n Lineal Entera-Mixta (MILP)\n\n\n\n* Funcion objetivo y restricciones lineales\n* Incluye toma de decisiones logicas con variables binarias\n* Algoritmos:\n    * Ramificaci\u00f3n y acotamiento (branch & bound)\n    * Cortes de gomory\n\n* Ejemplo: Seleci\u00f3n de la mejor ruta de producci\u00f3n \n\n\\begin{array}{ll}\n\\min & c^T + d^Ty \\\\\ns.t. & Ax + By \\leq 1\\\\\n     & x \\geq 0  \\\\\n     & y \\in (0,1) \n\\end{array}\n\n### Programaci\u00f3n No-Lineal (NLP)\n\n* Funcion objetivo y/o restricciones no-lineales\n* Algoritmos:\n    * Condiciones de optimalidad de Karush-Kuhn-Tucker\n\n* Ejemplo: Flujo de carga \u00f3ptimo en red de energ\u00eda el\u00e9ctrica\n\n\\begin{array}{ll}\n\\min & z = f(x) \\\\\ns.t. & h(x)=0\\\\\n     & g(x)\\le 0  \\\\\n     & x \\le 0 \n\\end{array}\n\n* Ejemplo de funciones no lineales: Funci\u00f3n de Rosenbrock\n\n$$ f(x, y) = (a - x)^2 + b (y - x^2)^2 $$\n\n$$a=1$$\n$$b=100$$\n\n\n```python\n#we will use numpy functions in order to work with numpy arrays\ndef rosembrock(x,y):\n    z  = (1-x)**2+100*(y-x**2)**2\n    return z \n\nn = 150\nx = np.random.uniform(-1, 1, n)\ny = np.random.uniform(-1, 1, n)\nz = rosembrock(x, y)\n\n#we create two 1D arrays of the desired lengths:\nx_1d = np.linspace(min(x), max(x), n)\ny_1d = np.linspace(min(y), max(y), n)\n\n#And we use the meshgrid function to create the X and Y matrices!\nX, Y = np.meshgrid(x_1d, y_1d)\n\n#Using Numpy arrays, calculating the function value at the points is easy!\nZ = rosembrock(X,Y)\n\nfig = plt.figure(figsize=(16,10))\nax = fig.add_subplot(111, projection='3d')\n\nsurf = ax.plot_surface(X, Y, Z,\n                       rstride=2,\n                       cstride=2,\n                       alpha=0.6,\n                       cmap=cm.jet,\n                       linewidth=0,\n                       antialiased=False)\n# Customize the z axis.\n#ax.set_zlim(-120, 120)\nax.zaxis.set_major_locator(LinearLocator(10))\nax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\n\n# add contour \ncset = ax.contour(X, Y, Z, zdir='y', cmap=cm.coolwarm)\n\nax.set_xlabel('X')\n#ax.set_xlim(-8, 8)\nax.set_ylabel('Y')\n#ax.set_ylim(-8, 8)\nax.set_zlabel('Z')\n#ax.set_zlim(-2, 2)\n\nax.view_init(30, 20)\n\n# Add a color bar which maps values to colors.\nfig.colorbar(surf, shrink=0.4, aspect=5)\nplt.show()\n```\n\n### Programaci\u00f3n No Lineal Entero Mixta (MINLP)\n\n\n\n* Funcion objetivo y/o restricciones no-lineales\n* Incluye toma de decisiones logicas con variables binarias\n* Algoritmos:\n    * Aproximaciones Exteriores\n\n* Ejemplo: Planificaci\u00f3n de la expansi\u00f3n de la red el\u00e9ctrica\n\n\\begin{array}{ll}\n\\min & z = f(x) + d^T y \\\\\ns.t. & h(x) + By=0\\\\\n     & g(x) + Dy \\le 0  \\\\\n     & x \\le 0 \\\\\n     & y \\in (0,1)  \n\\end{array}\n\n\n\n\n\n# Pyomo\n\n* Dos de los lenguajes de modelado comerciales m\u00e1s utilizados para resolver este tipo de problemas matem\u00e1ticos son [GAMS](https://www.gams.com) y [AMPL](https://ampl.com). \n\n* Como alternativa libre y gratuita existe [Pyomo](pyomo.org) que es un lenguaje de modelado algebraico basado en __Python__\n\n* Otras alternativas: [JuMP (julia)](https://jump.dev), __SciPy__, __CVXopt__, __PuLP__\n\n* Pyomo es un un lenguaje de modelado algebraico compatible con una amplia gama de tipos de problemas de optimizaci\u00f3n tipo:\n\n    * [LP](https://www.analyticsvidhya.com/blog/2017/02/lintroductory-guide-on-linear-programming-explained-in-simple-english/) (Linear Prograaming)\n    * [NLP](https://en.wikipedia.org/wiki/Nonlinear_programming) (Non-Linear Programming)\n    * [MIP](https://en.wikipedia.org/wiki/Integer_programming) (Mixed-Integer Programming)\n    * [MINLP](https://neos-guide.org/content/mixed-integer-nonlinear-programming) (Mixed-Integer Non-Linear Programming)\n\n* Deseable optimizaci\u00f3n convexa\n\n* Pyomo se comunica con los principales solvers comerciales, gratuitos y/o libres:\n\n    * [GLPK (GNU Linear Programming Kit)](https://www.gnu.org/software/glpk/) (libre, LP/MIP)\n    * [IPOPT](https://coin-or.github.io/Ipopt/) (libre, LP/NLP)\n    * [CONOPT](http://www.conopt.com) (gratuito, NLP)\n    * [CPLEX](https://www.ibm.com/es-es/analytics/cplex-optimizer) (comercial, LP/MIP)\n    * [GUROBI](https://www.gurobi.com/products/gurobi-optimizer/) (comercial, LP/MIP)\n    * [BARON (Branch-and-Reduce Optimization Navigator)](https://minlp.com/baron) (comercial MIP/MINLP)\n    * [CBC (Coin-or branch and cut)](https://projects.coin-or.org/Cbc)(libre, MIP)\n    * [MindtPy (Mixed-Integer Nonlinear Decomposition Toolbox in Pyomo)](https://pyomo.readthedocs.io/en/stable/contributed_packages/mindtpy.html) (libre, MINLP)\n    \n    \n| Solver        | LP   | MIP | NLP   |MINLP  |\n| :-----------: |:----:| :--:|:-----:|:-----:|\n| GLPK          | X    | X   |   -    |   -    |\n| IPOPT         |    -  | -    | X     |   -    |\n| CONOPT        | -     | -    | X     |   -    |\n| CBC           | -     | X    | -     |   -    |\n| BARON         | -     | X    | X     |   X    |\n| GUROBI        | X    | X   |    -   |   -    |\n| CPLEX         | X    | X   |   -    |   -    |\n| MindtPy       |    -  | -    |   -    | X     |\n\n\n\n## Instalaci\u00f3n\nCrear entorno de python con version 3.6 o 3.7 con una ventana de comandos\n\n```\nconda create -n pyomo36 python=3.6 numpy pandas matplotlib plotly scipy jupyter ipython\n```\nComprobar entorno \n\n```\nconda env list\n```\n\nActivar entorno\n\n```\nconda activate pyomo36\n```\n\nInstalar pyomo \n\n```\nconda install pyomo -c conda-forge\n```\n\nComprobar que se ha instalado correctamente\n\n```\npyomo\n```\n\nInstalar extras: [NEOS server](https://neos-server.org/neos/)\n\n```\nconda install pyomo.extras --channel conda-forge\n```\n\nInstalar solver GLPK\n\n```\nconda install glpk -c conda-forge\n```\n\nInstalar solvers IPOPT\n\n```\nconda install -c cachemeorg ipopt_bin\n```\n\nDetectar solvers instalados\n\n```\npyomo help -s\n```\n\nAyuda sobre componentes\n```\npyomo help --components\n```\n\nAyuda sobre pyomo en general\n\n```\npyomo help -a\n```\n\n## Modelado\n* El modelado es un proceso fundamental en muchos aspectos de la investigaci\u00f3n, ingenier\u00eda y los negocios. El modelado involucra la formulaci\u00f3n de una representaci\u00f3n simplificada de una sistema o de un objecto del mundo real. \n\n* Un modelo matem\u00e1tico incluye los siquientes componentes:\n    * __Variables__: Representan incognitas dentro del modelo y el objetivo es determinar su valor. Los valores que toman las variables corresponden con la soluci\u00f3n del problema y proporcionan la decisi\u00f3n a tomar \u00f3ptima ya que son el resultado de un proceso de optimizaci\u00f3n.\n    * __Par\u00e1metros__: Representan los datos conocidos sobre el problema de optimizaci\u00f3n. Pueden ser vectores o matrices.\n    * __Funci\u00f3n objectivo__: Ecuaci\u00f3n a minimizar o maximizar que relaciona las variables con los par\u00e1metros del modelo.\n    * __Restricciones__: Ecuaciones de igualdad o desigualdad que imponen ciertos comportamientos a las variables.\n\n## Proceso \n* Pyomo soporta un dise\u00f1o orientado a objectos para la modelizaci\u00f3n. Los pasos a seguir son los siguientes\n\n    * Definir modelo y componentes\n    * Instanciar modelo\n    * Aplicar solver\n    * Consultar resultados\n    \n\n## Componentes\nUn modelo de pyomo consiste en un conjunto de componentes de lenguaje algebraico definidos a traves de clases de pyomo:\n   * Indices\n   * conjuntos\n   * variables de decisi\u00f3n\n   * par\u00e1metros\n   * funci\u00f3n objetivo\n   * restricciones. \n   * expresiones\n\n\n## Tipos de modelos\n\n### Concreto\n   * Paramteros del modelo directos\n        \n        \n\\begin{array}{ll}\n\\min & z= 2x_1 + 3x_2\\\\\ns.t. & 3x_1 + 4x_2 \\geq 1\\\\\n     & x_1,x_2 \\geq 0 \n\\end{array}\n\n### Abstracto\n   * Par\u00e1metros del modelo \n   * Independecia modelo y datos\n    \n\\begin{array}{lll}\n\\min & z=  \\sum_{j=1}^n c_j x_j & \\\\\ns.t. & \\sum_{j=1}^n a_{i,j} \\cdot x_j \\geq b_i & \\forall i = 1 \\ldots m\\\\\n     & x_j \\geq 0 & \\forall j = 1 \\ldots n\n\\end{array}\n\n\n\n## Ejemplo Modelo Abstracto: Problema del transporte\n\n* Original problem formulation:\n  - Dantzig, G B, Chapter 3.3. In Linear Programming and Extensions. Princeton University Press, Princeton, New Jersey, 1963.\n  \n\n\n\n\\begin{equation}\n\\begin{array}{lll}\n\\min & z =  \\sum_{j=1}^n c_{i,j} x_{i,j}  & (1a) & \\\\\ns.t. & \\sum_{j=1}^n x_{i,j} \\leq u_i & ,\\forall i \\in (1, \\ldots, m) & (1b) \\\\\n     & \\sum_{i=1}^m x_{i,j} = d_j & ,\\forall i \\in (1, \\ldots, n)& (1c)  \\\\\n     & x_{i,j} \\geq 0 & ,\\forall j \\in (1 ,\\ldots, n) & (1d)\n\\end{array}\n\\end{equation}\n\n__Datos__\n* $m$ Numero de origenes\n* $n$ Numero de destinos\n* $u_i$ Stock de producto en origen $i$\n* $d_j$ Demanda de producto en destino $j$\n* $c_{i,j}$ coste unitario de envio de producto desde origen $i$ a destino $j$ (\u20ac/ud)  \n\n\n\n\n__Variable objetivo (o de decisi\u00f3n)__\n* $x_{i,j}$ Cantidad de producto que va del origen $i$ al destino $j$ \n\n__Restricci\u00f3nes__ \n* __1b__: Limitaci\u00f3n stock \n\n* __1c__: garantizar suministro demanda\n\n* __1d__: Cantidades positivas. _Esto implica que la direccion de env\u0131o del producto esta prefijada desde los distintos or\u0131genes hasta los destinos. No obstante, otras hipotesis podr\u0131an tenerse en cuenta. Por ejemplo, podr\u0131a no limitarse el signo de las variables , si no se quiere predeterminar cuales son los puntos de partida y llegada_\n\n\n\n\n\n### importar libreria pyomo\n\n\n```python\nimport pyomo.environ as pyo\n```\n\n### Iniciar modelo abstracto\n\n\n```python\nmodel = pyo.AbstractModel()\n```\n\n### Definir conjuntos (Sets) [opcion a]\n\n\n```python\nmodel.origen = pyo.Set() # origenes i in (1,...,m)\nmodel.destino = pyo.Set() # destinos j in (1,...,n)\n```\n\n### Definir conjuntos (Sets) [opcion b]\n\n\n```python\n# Crear primero un parametro que marca la dimension del indice\nmodel.m = pyo.Param(within='NonNegativeIntegers') # 'PositiveReals' Si incluimos el 0\nmodel.n = pyo.Param(within='NonNegativeIntegers')\n\n# Definir luego los sets como un rango de valores entre 1 y la dimension del indice\nmodel.I = pyo.RangeSet(1, model.m)\nmodel.J = pyo.RangeSet(1, model.n)\n```\n\n### Definir parametros (datos conocidos)\n\n\n```python\nmodel.stock = pyo.Param(model.origen) # stock en origen i\nmodel.demanda = pyo.Param(model.destino) # demanda en destino j\nmodel.coste = pyo.Param(model.origen, model.destino) # coste de envio unitario de origen i a destino J\n```\n\n### definir variable de decision \n\n\n```python\nmodel.x = pyo.Var(model.origen, model.destino, domain=pyo.NonNegativeReals)\n```\n\n### Definir funcion objetivo\n\n\n```python\n### primero definir expresion que define la funcion objetivo\ndef pyomo_of(model):\n    return sum(model.c[i,j] * model.x[i,j] for i in model.origen for j in model.destino) \n\n### despues definir el component de la funcion objetivo\nmodel.total_cost = pyo.Objective(rule=pyomo_of)\n```\n\n### Definir restricciones\n\n\n```python\n# Definir restriccion stock\ndef pyomo_constraint_stock(model, i):\n    # devuelve la expression de la restriccion para el valor de i\n    return sum(model.x[i,j] for j in model.destino) <= model.stock[i]\n\n# definir entidad de la restriccion para indice I\nmodel.const_stock = pyo.Constraint(model.origen, rule=pyomo_constraint_stock)\n```\n\n\n```python\n# Definir restriccion demanda\ndef pyomo_constraint_demand(model, j):\n    # devuelve la expression de la restriccion para el valor de i\n    return sum(model.x[i,j] for i in model.origen) == model.demanda[j]\n\n# definir entidad de la restriccion para indice I\nmodel.const_demand = pyo.Constraint(model.destino, rule=pyomo_constraint_demand)\n```\n\n### Definir funcion que genera el modelo\n\n\n```python\ndef dl_ia_opt_build_model():\n    \"\"\" Builds an abstract pyomo model for the transport problem based\n    :return: abstract pyomo model\n    \"\"\"\n    \n    import pyomo.environ as pyo\n    \n    model = pyo.AbstractModel()\n    \n    # Sets\n    model.origen = pyo.Set() #  origenes (1,...,m)\n    model.destino = pyo.Set() # destinos (1,...,n)\n    \n    # Parametros\n    model.stock = pyo.Param(model.origen, domain=pyo.NonNegativeReals) # stock en origen i\n    model.demanda = pyo.Param(model.destino, domain=pyo.NonNegativeReals) # demanda en destino j\n    model.coste = pyo.Param(model.origen, model.destino, domain=pyo.NonNegativeReals) # coste de envio unitario de origen i a destino J\n    \n    # variable objetivo\n    model.x = pyo.Var(model.origen, model.destino, domain=pyo.NonNegativeReals)\n\n    ### primero definir expresion que define la funcion objetivo\n    def of_expression(model):\n        return sum(model.coste[i,j] * model.x[i,j] for i in model.origen for j in model.destino) \n\n    ### despues definir el component de la funcion objetivo\n    model.total_cost = pyo.Objective(rule=of_expression)\n\n    # Definir restriccion stock\n    def pyomo_constraint_stock(model, i):\n        # devuelve la expression de la restriccion para el valor de i\n        return sum(model.x[i,j] for j in model.destino) <= model.stock[i]\n\n    # definir entidad de la restriccion para indice I\n    model.const_stock = pyo.Constraint(model.origen, rule=pyomo_constraint_stock)\n    \n    # Definir restriccion demanda\n    def pyomo_constraint_demand(model, j):\n        # devuelve la expression de la restriccion para el valor de i\n        return sum(model.x[i,j] for i in model.origen) == model.demanda[j]\n\n    # definir entidad de la restriccion para indice I\n    model.const_demand = pyo.Constraint(model.destino, rule=pyomo_constraint_demand)\n \n    \n    return model\n```\n\n\n```python\nmodel = dl_ia_opt_build_model()\n```\n\n### Datos\n\n\n\n\n```python\ndf_data = pd.DataFrame({ 'origen':['Barcelona'   , 'Barcelona'   , 'Barcelona'   ,'Valencia'   ,'Valencia'   ,'Valencia'   ,'Bilbao'    ,'Bilbao'    ,'Bilbao'   ],\n                         'destino':['Madrid' ,'Sevilla' ,'Malaga'  ,'Madrid' ,'Sevilla'  ,'Malaga' ,'Madrid' ,'Sevilla'  ,'Malaga'  ],\n                         'coste':[0.682,0.995 ,0.976 ,0.562, 0.756, 0.720, 0.402 ,0.861 ,0.922],\n                         'stock':[174  ,174   ,174   ,36  ,36  ,36  ,57   ,57   ,57  ] ,\n                         'demanda':[54  ,45   ,23   ,54  ,45  ,23  ,54   ,45   ,23  ],\n                   })\n\ndf_data\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>origen</th>\n      <th>destino</th>\n      <th>coste</th>\n      <th>stock</th>\n      <th>demanda</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Barcelona</td>\n      <td>Madrid</td>\n      <td>0.682</td>\n      <td>174</td>\n      <td>54</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Barcelona</td>\n      <td>Sevilla</td>\n      <td>0.995</td>\n      <td>174</td>\n      <td>45</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Barcelona</td>\n      <td>Malaga</td>\n      <td>0.976</td>\n      <td>174</td>\n      <td>23</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Valencia</td>\n      <td>Madrid</td>\n      <td>0.562</td>\n      <td>36</td>\n      <td>54</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Valencia</td>\n      <td>Sevilla</td>\n      <td>0.756</td>\n      <td>36</td>\n      <td>45</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>Valencia</td>\n      <td>Malaga</td>\n      <td>0.720</td>\n      <td>36</td>\n      <td>23</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Bilbao</td>\n      <td>Madrid</td>\n      <td>0.402</td>\n      <td>57</td>\n      <td>54</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Bilbao</td>\n      <td>Sevilla</td>\n      <td>0.861</td>\n      <td>57</td>\n      <td>45</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Bilbao</td>\n      <td>Malaga</td>\n      <td>0.922</td>\n      <td>57</td>\n      <td>23</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n#### Visualizar datos entrada\n\n##### Stock y demanda\n\n\n```python\n# Plot stocks\ndf_aux = df_data[['origen','stock']].drop_duplicates()\n\nfig = px.bar(df_aux,\n             x=\"origen\",\n             y=\"stock\",\n             title=\"Stocks\")\nfig.update_yaxes(title_text='Stocks (ud)')\nfig.update_xaxes(title_text='Origenes')\nfig.update_layout(font=dict(family=\"Courier New, monospace\", size=18, color=\"#7f7f7f\"))\nfig.show()\n\n# Plot demanda\ndf_aux = df_data[['destino','demanda']].drop_duplicates()\n\nfig = px.bar(df_aux,\n             x=\"destino\",\n             y=\"demanda\",\n             title=\"Demanda\")\nfig.update_yaxes(title_text='Demanda (ud)')\nfig.update_xaxes(title_text='Destinos')\nfig.update_layout(font=dict(family=\"Courier New, monospace\", size=18, color=\"#7f7f7f\"))\nfig.show()\n```\n\n\n<div>                            <div id=\"b27a33cb-d9f2-4263-bf0e-11112e267fcc\" class=\"plotly-graph-div\" style=\"height:525px; width:100%;\"></div>                    </div>\n\n\n\n<div>                            <div id=\"8fe8d9d1-8bf9-4491-ba73-021aaacb39c9\" class=\"plotly-graph-div\" style=\"height:525px; width:100%;\"></div>                    </div>\n\n\n##### Costes\n\n\n```python\ndf_aux = df_data[['origen','destino','coste']].drop_duplicates().pivot(index='destino',values='coste', columns='origen').fillna(0)\n\nfig = go.Figure(data=go.Heatmap(\n                   z=df_aux.values,\n                   y=df_data['origen'].unique().tolist(),\n                   x=df_data['destino'].unique().tolist(),\n                   hoverongaps = False))\nfig.update_yaxes(title_text='origen')\nfig.update_xaxes(title_text='destino')\nfig.update_layout(title='Costes de envio')\nfig.update_layout(font=dict(family=\"Courier New, monospace\", size=18, color=\"#7f7f7f\"))\nfig.show()\n```\n\n\n<div>                            <div id=\"fe746e74-18c0-47c5-9a64-31a772552333\" class=\"plotly-graph-div\" style=\"height:525px; width:100%;\"></div>                    </div>\n\n\n### Guardar datos en formato adecuado\n\n\n```python\ndf_data[['origen', 'stock']].drop_duplicates()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>origen</th>\n      <th>stock</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Barcelona</td>\n      <td>174</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Valencia</td>\n      <td>36</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Bilbao</td>\n      <td>57</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf_data[['origen', 'stock']].drop_duplicates()['origen'].to_csv('data/set_origen.tab', index=False, sep=' ')\ndf_data[['destino', 'demanda']].drop_duplicates()['destino'].to_csv('data/set_destino.tab', index=False, sep=' ')\n\ndf_data[['origen', 'stock']].drop_duplicates().to_csv('data/param_stock.tab', index=False, sep=' ')\ndf_data[['destino', 'demanda']].drop_duplicates().to_csv('data/param_demand.tab', index=False, sep=' ')\n\ndf_data[['origen', 'destino', 'coste']].to_csv('data/param_coste.tab', index=False, sep=' ')\n```\n\n### Crear instancia de datos\n\n\n```python\ndata = pyo.DataPortal(model=model)\n\ndata.load(filename='data/set_origen.tab', set=\"origen\", format=\"set\")\ndata.load(filename='data/set_destino.tab', set=\"destino\", format=\"set\")\n\ndata.load(filename='data/param_stock.tab', param=model.stock)\ndata.load(filename='data/param_demand.tab', param=model.demanda)\n\ndata.load(filename='data/param_coste.tab', param=model.coste)\n```\n\n\n```python\ndata.data()\n```\n\n\n\n\n    {'origen': {None: ['Barcelona', 'Valencia', 'Bilbao']},\n     'destino': {None: ['Madrid', 'Sevilla', 'Malaga']},\n     'stock': {'Barcelona': 174, 'Valencia': 36, 'Bilbao': 57},\n     'demanda': {'Madrid': 54, 'Sevilla': 45, 'Malaga': 23},\n     'coste': {('Barcelona', 'Madrid'): 0.682,\n      ('Barcelona', 'Sevilla'): 0.995,\n      ('Barcelona', 'Malaga'): 0.976,\n      ('Valencia', 'Madrid'): 0.562,\n      ('Valencia', 'Sevilla'): 0.756,\n      ('Valencia', 'Malaga'): 0.72,\n      ('Bilbao', 'Madrid'): 0.402,\n      ('Bilbao', 'Sevilla'): 0.861,\n      ('Bilbao', 'Malaga'): 0.922}}\n\n\n\n### Instanciar modelo con datos\n\n\n```python\ninstance = model.create_instance(data)\n\n### comprobar instancia creada\ninstance.pprint()\n```\n\n    4 Set Declarations\n        coste_index : Size=1, Index=None, Ordered=True\n            Key  : Dimen : Domain         : Size : Members\n            None :     2 : origen*destino :    9 : {('Barcelona', 'Madrid'), ('Barcelona', 'Sevilla'), ('Barcelona', 'Malaga'), ('Valencia', 'Madrid'), ('Valencia', 'Sevilla'), ('Valencia', 'Malaga'), ('Bilbao', 'Madrid'), ('Bilbao', 'Sevilla'), ('Bilbao', 'Malaga')}\n        destino : Size=1, Index=None, Ordered=Insertion\n            Key  : Dimen : Domain : Size : Members\n            None :     1 :    Any :    3 : {'Madrid', 'Sevilla', 'Malaga'}\n        origen : Size=1, Index=None, Ordered=Insertion\n            Key  : Dimen : Domain : Size : Members\n            None :     1 :    Any :    3 : {'Barcelona', 'Valencia', 'Bilbao'}\n        x_index : Size=1, Index=None, Ordered=True\n            Key  : Dimen : Domain         : Size : Members\n            None :     2 : origen*destino :    9 : {('Barcelona', 'Madrid'), ('Barcelona', 'Sevilla'), ('Barcelona', 'Malaga'), ('Valencia', 'Madrid'), ('Valencia', 'Sevilla'), ('Valencia', 'Malaga'), ('Bilbao', 'Madrid'), ('Bilbao', 'Sevilla'), ('Bilbao', 'Malaga')}\n    \n    3 Param Declarations\n        coste : Size=9, Index=coste_index, Domain=NonNegativeReals, Default=None, Mutable=False\n            Key                      : Value\n             ('Barcelona', 'Madrid') : 0.682\n             ('Barcelona', 'Malaga') : 0.976\n            ('Barcelona', 'Sevilla') : 0.995\n                ('Bilbao', 'Madrid') : 0.402\n                ('Bilbao', 'Malaga') : 0.922\n               ('Bilbao', 'Sevilla') : 0.861\n              ('Valencia', 'Madrid') : 0.562\n              ('Valencia', 'Malaga') :  0.72\n             ('Valencia', 'Sevilla') : 0.756\n        demanda : Size=3, Index=destino, Domain=NonNegativeReals, Default=None, Mutable=False\n            Key     : Value\n             Madrid :    54\n             Malaga :    23\n            Sevilla :    45\n        stock : Size=3, Index=origen, Domain=NonNegativeReals, Default=None, Mutable=False\n            Key       : Value\n            Barcelona :   174\n               Bilbao :    57\n             Valencia :    36\n    \n    1 Var Declarations\n        x : Size=9, Index=x_index\n            Key                      : Lower : Value : Upper : Fixed : Stale : Domain\n             ('Barcelona', 'Madrid') :     0 :  None :  None : False :  True : NonNegativeReals\n             ('Barcelona', 'Malaga') :     0 :  None :  None : False :  True : NonNegativeReals\n            ('Barcelona', 'Sevilla') :     0 :  None :  None : False :  True : NonNegativeReals\n                ('Bilbao', 'Madrid') :     0 :  None :  None : False :  True : NonNegativeReals\n                ('Bilbao', 'Malaga') :     0 :  None :  None : False :  True : NonNegativeReals\n               ('Bilbao', 'Sevilla') :     0 :  None :  None : False :  True : NonNegativeReals\n              ('Valencia', 'Madrid') :     0 :  None :  None : False :  True : NonNegativeReals\n              ('Valencia', 'Malaga') :     0 :  None :  None : False :  True : NonNegativeReals\n             ('Valencia', 'Sevilla') :     0 :  None :  None : False :  True : NonNegativeReals\n    \n    1 Objective Declarations\n        total_cost : Size=1, Index=None, Active=True\n            Key  : Active : Sense    : Expression\n            None :   True : minimize : 0.682*x[Barcelona,Madrid] + 0.995*x[Barcelona,Sevilla] + 0.976*x[Barcelona,Malaga] + 0.562*x[Valencia,Madrid] + 0.756*x[Valencia,Sevilla] + 0.72*x[Valencia,Malaga] + 0.402*x[Bilbao,Madrid] + 0.861*x[Bilbao,Sevilla] + 0.922*x[Bilbao,Malaga]\n    \n    2 Constraint Declarations\n        const_demand : Size=3, Index=destino, Active=True\n            Key     : Lower : Body                                                           : Upper : Active\n             Madrid :  54.0 :    x[Barcelona,Madrid] + x[Valencia,Madrid] + x[Bilbao,Madrid] :  54.0 :   True\n             Malaga :  23.0 :    x[Barcelona,Malaga] + x[Valencia,Malaga] + x[Bilbao,Malaga] :  23.0 :   True\n            Sevilla :  45.0 : x[Barcelona,Sevilla] + x[Valencia,Sevilla] + x[Bilbao,Sevilla] :  45.0 :   True\n        const_stock : Size=3, Index=origen, Active=True\n            Key       : Lower : Body                                                             : Upper : Active\n            Barcelona :  -Inf : x[Barcelona,Madrid] + x[Barcelona,Sevilla] + x[Barcelona,Malaga] : 174.0 :   True\n               Bilbao :  -Inf :          x[Bilbao,Madrid] + x[Bilbao,Sevilla] + x[Bilbao,Malaga] :  57.0 :   True\n             Valencia :  -Inf :    x[Valencia,Madrid] + x[Valencia,Sevilla] + x[Valencia,Malaga] :  36.0 :   True\n    \n    11 Declarations: origen destino stock demanda coste_index coste x_index x total_cost const_stock const_demand\n\n\n### Definir Solver\n\n\n\n```python\n# Definimos Solver\nfrom pyomo.opt import SolverFactory\nopt = SolverFactory(\"glpk\")\n```\n\n### Resolver problema de optimizaci\u00f3n\nAl resolver el modelo se dar\u00e1 una de las siguientes situaciones:\n*  __El problema es no factible__: No existe ninguna soluci\u00f3n que cumpla simult\u00e1neamente todas las restricciones\n*  __El problema es no acotado__: Funcion no convexa (z=infinito)\n* __Tiene una \u00fanica soluci\u00f3n__: El problema tiene soluci\u00f3n factible, es acotado y existe un \u00f3ptimo y es \u00fanico\n*  __Tiene m\u00faltiples soluciones__: El problema tiene soluci\u00f3n factible, es acotado y existen varios \u00f3ptimos. Todos los \u00f3ptimos ser\u00e1n equivalentes, esto es, proporcionan el mismo valor de z\n\n\n\n```python\nresults = opt.solve(instance, tee=False) # tee is a option to plot process\n\n#send results to stdout\n#results.write()\n#!cat results.yml\n\nprint('--- Problem Results ---')\nprint(results.Problem())\nprint('--- Solver Results ---')\nprint(results.Solver())\n\nprint('--- Restriccion Stock ---')\nprint(instance.const_stock.display())\nprint('--- Restriccion Demanda ---')\nprint(instance.const_demand.display())\nprint('--- Coste Total ---')\nprint(instance.total_cost.display())\n```\n\n    --- Problem Results ---\n    \n    Name: unknown\n    Lower bound: 79.534\n    Upper bound: 79.534\n    Number of objectives: 1\n    Number of constraints: 7\n    Number of variables: 10\n    Number of nonzeros: 19\n    Sense: minimize\n    \n    --- Solver Results ---\n    \n    Status: ok\n    Termination condition: optimal\n    Statistics: \n      Branch and bound: \n        Number of bounded subproblems: 0\n        Number of created subproblems: 0\n    Error rc: 0\n    Time: 0.022034168243408203\n    \n    --- Restriccion Stock ---\n    const_stock : Size=3\n        Key       : Lower : Body : Upper\n        Barcelona :  None : 29.0 : 174.0\n           Bilbao :  None : 57.0 :  57.0\n         Valencia :  None : 36.0 :  36.0\n    None\n    --- Restriccion Demanda ---\n    const_demand : Size=3\n        Key     : Lower : Body : Upper\n         Madrid :  54.0 : 54.0 :  54.0\n         Malaga :  23.0 : 23.0 :  23.0\n        Sevilla :  45.0 : 45.0 :  45.0\n    None\n    --- Coste Total ---\n    total_cost : Size=1, Index=None, Active=True\n        Key  : Active : Value\n        None :   True : 79.53399999999999\n    None\n\n\n### Explorar Resultados\n\n\n```python\ndef dl_ia_opt_get_results(instance):\n    \"\"\" Funtion to check resutls \n        :param results: optimization resutls\n        :return: dataframe with resutls\n    \"\"\"\n    \n    import pandas as pd\n    try:\n        origen = []\n        destino = []\n        cantidad = []\n        for i in instance.origen:\n            for j in instance.destino:\n                origen.append(i)\n                destino.append(j)\n                cantidad.append(instance.x[(i, j)].value)\n\n        df_out = pd.DataFrame({'origen':origen, 'destino':destino, 'cantidad':cantidad})\n        df_out['origen'] = df_out['origen'].astype(str)\n        df_out['destino'] = df_out['destino'].astype(str)\n        df_out['cantidad'] = df_out['cantidad'].astype(int)\n        \n        \n        return df_out\n        \n        \n    except Exception as exception_msg:\n        print('(!) Error in dl_ia_opt_get_results: {}'.format(str(exception_msg)))\n```\n\n\n```python\ndf_results = dl_ia_opt_get_results(instance)\nprint('Coste total: {} euros'.format(instance.total_cost.expr()))\nprint('Tiempo de ejecuci\u00f3n: {} s'.format(round(results.Solver.Time,4)))\nprint('Suministro: {} lotes'.format(df_results['cantidad'].sum()))\ndf_results\n```\n\n    Coste total: 79.53399999999999 euros\n    Tiempo de ejecuci\u00f3n: 0.022 s\n    Suministro: 122 lotes\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>origen</th>\n      <th>destino</th>\n      <th>cantidad</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Barcelona</td>\n      <td>Madrid</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Barcelona</td>\n      <td>Sevilla</td>\n      <td>29</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Barcelona</td>\n      <td>Malaga</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Valencia</td>\n      <td>Madrid</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Valencia</td>\n      <td>Sevilla</td>\n      <td>13</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>Valencia</td>\n      <td>Malaga</td>\n      <td>23</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Bilbao</td>\n      <td>Madrid</td>\n      <td>54</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Bilbao</td>\n      <td>Sevilla</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Bilbao</td>\n      <td>Malaga</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf_aux = df_results[['origen','destino','cantidad']].drop_duplicates().pivot(index='destino',values='cantidad', columns='origen').fillna(0)\n\nfig = go.Figure(data=go.Heatmap(\n                   z=df_aux.values,\n                   y=df_results['origen'].unique().tolist(),\n                   x=df_results['destino'].unique().tolist(),\n                   hoverongaps = False))\nfig.update_yaxes(title_text='origen')\nfig.update_xaxes(title_text='destino')\nfig.update_layout(title='Cantidad de producto')\nfig.update_layout(font=dict(family=\"Courier New, monospace\", size=18, color=\"#7f7f7f\"))\nfig.show()\n```\n\n\n<div>\n\n\n            <div id=\"991ffe09-bcdd-4c7f-ab04-bf67ce2c3cb5\" class=\"plotly-graph-div\" style=\"height:525px; width:100%;\"></div>\n            \n        </div>\n\n\n### Mejoras\n\n   * __\u00bfY si existe stock minimo?__\n       * _Restriccion stock minimo_\n   * __\u00bfY si hay mas de un producto?__\n       * _costes por origen, destino y producto_\n   * __\u00bfY si hay diferentes modos de transporte?__\n       * _costes origen, destino, modo_\n   * __\u00bfY si los productos se pueden agrupar?__\n       * _A\u00f1adir caracterisitcas del producto: peso, volumen, precio, reglas de agrupamiento_\n   * __\u00bfY si no hay suficiente stock?__\n       * _Introducir preferencias en destinos_\n   * __\u00bfY si hay productos alternativos?__\n       * _Introducir preferencia por original, suministrar alternativo en caso de no stock_\n   * __\u00bfY si es multiperiodo?__\n       * _Programaci\u00f3n din\u00e1mica, introducir demanda y stock por horizonte temporal_\n   * __\u00bfY que pasa si hay nodos intermedios?__\n       * _Definir mediante expresiones ecuaciones auxiliares_\n\n# Proximamente\n\n* Optimizaci\u00f3n multi-objetivo \n* Comparativa de tiempos de ejecui\u00f3n y esfuerzo computacional\n* Mas ejemplos con aplicaci\u00f3n a sensores, transporte, flujos, cartera de valores, etc..\n\n# Referencias\n* [pyomo repository](https://github.com/Pyomo)\n* [Pyomo Modelling Components](https://pyomo.readthedocs.io/en/stable/pyomo_modeling_components/index.html)\n* [Pyomo Documentation](https://pyomo.readthedocs.io/en/latest/)\n* [Expressions pyomo](https://pyomo.readthedocs.io/en/stable/pyomo_modeling_components/Expressions.html)\n* [Gallery](https://github.com/Pyomo/PyomoGallery/wiki)\n* [Accessing Pyomo variable values and objective function value](http://hselab.org/pyomo-get-variable-values.html)\n* [latex symbols](https://oeis.org/wiki/List_of_LaTeX_mathematical_symbols)\n* [latex math](https://www.overleaf.com/learn/latex/Matrices)\n* [Gams solvers](https://www.gams.com/latest/docs/S_MAIN.html)\n* [IBM optimization](https://www.ibm.com/analytics/optimization-solver)\n* [Solvers comparative](https://www.researchgate.net/publication/314750497_A_Comparative_Analysis_of_Optimization_Solvers)\n* [More about optimization solvers](https://cran.r-project.org/web/views/Optimization.html)\n* [Book optimization UCLM](http://www.dia.fi.upm.es/~jafernan/teaching/operational-research/LibroCompleto.pdf)\n* [Pareto Frontier Method](https://www.researchgate.net/publication/265600679_On_Epsilon-Constraint_Based_Methods_for_the_Generation_of_Pareto_Frontiers)\n* [(Udemy) Complete Pyomo Bootcamp: Python Optimization Beginners](https://www.udemy.com/share/103zuUAEAYdlhWTXQB/)\n\n\n```python\n\n```\n", "meta": {"hexsha": "d7546b333e2edf5919df535427821378da5b8b85", "size": 727921, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/seminario_optimizacion_con_pyomo.ipynb", "max_stars_repo_name": "joanvelro/pyomo-seminario", "max_stars_repo_head_hexsha": "0669874b4e707d31e453f85549d6fb317a373814", "max_stars_repo_licenses": ["ADSL"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-26T03:59:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T03:59:06.000Z", "max_issues_repo_path": "notebooks/seminario_optimizacion_con_pyomo.ipynb", "max_issues_repo_name": "joanvelro/pyomo-seminario", "max_issues_repo_head_hexsha": "0669874b4e707d31e453f85549d6fb317a373814", "max_issues_repo_licenses": ["ADSL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/seminario_optimizacion_con_pyomo.ipynb", "max_forks_repo_name": "joanvelro/pyomo-seminario", "max_forks_repo_head_hexsha": "0669874b4e707d31e453f85549d6fb317a373814", "max_forks_repo_licenses": ["ADSL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 126.9482036972, "max_line_length": 260944, "alphanum_fraction": 0.8237253768, "converted": true, "num_tokens": 12031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814055953761019, "lm_q2_score": 0.16451646289656316, "lm_q1q2_score": 0.04629585319057773}}
{"text": "```python\n#remove cell visibility\nfrom IPython.display import HTML\ntag = HTML('''\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.''')\ndisplay(tag)\n```\n\n\n\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.\n\n\n\n```python\n%matplotlib inline\nimport control\nimport numpy\nimport sympy as sym\nfrom IPython.display import display, Markdown\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\n\n\n#print a matrix latex-like\ndef bmatrix(a):\n     \"\"\"Returns a LaTeX bmatrix - by Damir Arbula (ICCT project)\n\n     :a: numpy array\n     :returns: LaTeX bmatrix as a string\n     \"\"\"\n     if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n     lines = str(a).replace('[', '').replace(']', '').splitlines()\n     rv = [r'\\begin{bmatrix}']\n     rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n     rv +=  [r'\\end{bmatrix}']\n     return '\\n'.join(rv)\n\n\n# Display formatted matrix: \ndef vmatrix(a):\n    if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n    lines = str(a).replace('[', '').replace(']', '').splitlines()\n    rv = [r'\\begin{vmatrix}']\n    rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n    rv +=  [r'\\end{vmatrix}']\n    return '\\n'.join(rv)\n\n\n#matrixWidget is a matrix looking widget built with a VBox of HBox(es) that returns a numPy array as value !\nclass matrixWidget(widgets.VBox):\n    def updateM(self,change):\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.M_[irow,icol] = self.children[irow].children[icol].value\n                #print(self.M_[irow,icol])\n        self.value = self.M_\n\n    def dummychangecallback(self,change):\n        pass\n    \n    \n    def __init__(self,n,m):\n        self.n = n\n        self.m = m\n        self.M_ = numpy.matrix(numpy.zeros((self.n,self.m)))\n        self.value = self.M_\n        widgets.VBox.__init__(self,\n                             children = [\n                                 widgets.HBox(children = \n                                              [widgets.FloatText(value=0.0, layout=widgets.Layout(width='90px')) for i in range(m)]\n                                             ) \n                                 for j in range(n)\n                             ])\n        \n        #fill in widgets and tell interact to call updateM each time a children changes value\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        #value = Unicode('example@example.com', help=\"The email value.\").tag(sync=True)\n        self.observe(self.updateM, names='value', type= 'All')\n        \n    def setM(self, newM):\n        #disable callbacks, change values, and reenable\n        self.unobserve(self.updateM, names='value', type= 'All')\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].unobserve(self.updateM, names='value')\n        self.M_ = newM\n        self.value = self.M_\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        self.observe(self.updateM, names='value', type= 'All')        \n\n                #self.children[irow].children[icol].observe(self.updateM, names='value')\n\n             \n#overlaod class for state space systems that DO NOT remove \"useless\" states (what \"professor\" of automatic control would do this?)\nclass sss(control.StateSpace):\n    def __init__(self,*args):\n        #call base class init constructor\n        control.StateSpace.__init__(self,*args)\n    #disable function below in base class\n    def _remove_useless_states(self):\n        pass\n```\n\n## Quadrotor longitudinal velocity control\n\n\n\nThe quadrotor (or quadcopter) longitudinal velocity $v$ may be controlled by tilting the vehicle by the pitch angle. The angle $\\theta$ is controlled by applying the torque $T$ using the propellers. The vehicle moment of inertia is $J= 1.3e-2$. When the vehicle is tilted by the angle $\\theta$, the propellers produce a forward force approximately equal to $F_v = F\\theta = mg\\theta$ and the aerodynamic drag is $F_c=-cv=-0.9v$, where $m=2000$ g is vehicle mass, and $g = 9.81$ m/s^2 gravity acceleration. Maximum torque equals $5000$ mNm. Pitch angle $\\theta$ must be limited to $\\pm30$ degrees during all operations and maximum velocity to 2 m/s. The pitch angle is estimated by an appropriate sensor and velocity is measured with GPS. \n\nThe design procedure follows the following two-step procedure:\n1. Write the system equations in state space form for the rotational dynamics (torque $T$ to pitch angle $\\theta$) and the longitudinal dynamics (pitch angle to forward velocity $v$).\n2. Design a regulator for $v$ in order to satisfy the following specifications:\n    - Settling time for 5% tolerance band of less than 2.5 seconds.\n    - No Overshoot.\n    - No steady-state error in response to a step velocity request.\n\n### System equations\n\nThe system equations are equal to:\n\n\\begin{cases}\n    m\\dot{v} = F_v + F_c = mg\\theta -cv \\\\\n    J\\ddot{\\theta} = T.\n\\end{cases}\n\nBy defining the state vector as $x = \\begin{bmatrix} x_1 & x_2 & x_3 \\end{bmatrix}^T = \\begin{bmatrix} v & \\theta & \\dot{\\theta} \\end{bmatrix}^T$ and the input $u=T$, system equations in state space form become:\n\n\\begin{cases}\n\\dot{x} = \\begin{bmatrix} -c/m & g & 0 \\\\ 0 & 0 & 1 \\\\ 0 & 0 & 0 \\end{bmatrix}x + \\begin{bmatrix} 0 \\\\ 0 \\\\ 1/J \\end{bmatrix}u \\\\\ny = \\begin{bmatrix} y_1 \\\\ y_2 \\end{bmatrix} = \\begin{bmatrix} 1 & 0 & 0 \\\\ 0 & 1 & 0 \\end{bmatrix}x\n\\end{cases}\n\nThe dynamics from $u$ to $\\theta$ is a double integrator while that from $\\theta$ to $v$ is a first order dynamics with a pole in $-c/m$. The system has two outputs: velocity and tilt angle. \n\nThe controllability matrix $\\mathcal{C}$ is\n\n\n```python\nA = numpy.matrix('-0.45 9.81 0; 0 0 1; 0 0 0')\nB = numpy.matrix([[0],[0],[1/1.3E-02]])\nC = numpy.matrix('1 0 0; 0 1 0')\nD = numpy.matrix('0; 0')\n\nCM = control.ctrb(A,B)\ndisplay(Markdown(bmatrix(CM)))\n# print(numpy.linalg.matrix_rank(CM))\n```\n\n\n\\begin{bmatrix}\n  0. & 0. & 754.61538462\\\\\n  0. & 76.92307692 & 0.\\\\\n  76.92307692 & 0. & 0.\\\\\n\\end{bmatrix}\n\n\nand has rank equal to 3 so the system is controllable.\nThe observability matrix $\\mathcal{O}$ is\n\n\n```python\nOM = control.obsv(A,C)\ndisplay(Markdown(bmatrix(OM)))\n# print(numpy.linalg.matrix_rank(OM))\n```\n\n\n\\begin{bmatrix}\n  1. & 0. & 0.\\\\\n  0. & 1. & 0.\\\\\n  -0.45 & 9.81 & 0.\\\\\n  0. & 0. & 1.\\\\\n  0.2025 & -4.4145 & 9.81\\\\\n  0. & 0. & 0.\\\\\n\\end{bmatrix}\n\n\nand has rank equal to 3 so the system is observable.\n\n### Regulator design\n#### Observer design\nSince we have the direct measurements of $x_1$ and $x_2$ we are only interested in estimating $x_3$. If we look at the subsystem $(x_2, \\, x_3)$ we note that it is observable, so it is possible to design an observer by considering only this subsystem. The structure of our estimator is therefore:\n\n$$\n\\begin{bmatrix} \\dot{\\hat{x}_2} \\\\ \\dot{\\hat{x}_3} \\end{bmatrix} = \\begin{bmatrix} 0 & 1 \\\\ 0 & 0 \\end{bmatrix}\\begin{bmatrix} \\hat{x}_2 \\\\ \\hat{x}_3 \\end{bmatrix} + \\begin{bmatrix} 0 \\\\ 1/J \\end{bmatrix}u + \\begin{bmatrix} l_1 \\\\ l_2 \\end{bmatrix}\\left( y - C\\begin{bmatrix} \\hat{x}_2 \\\\ \\hat{x}_3 \\end{bmatrix} \\right) = \\begin{bmatrix} -l_1 & 1 \\\\ -l_2 & 0 \\end{bmatrix}\\begin{bmatrix} \\hat{x}_2 \\\\ \\hat{x}_3 \\end{bmatrix} + \\begin{bmatrix} 0 \\\\ 1/J \\end{bmatrix}u + \\begin{bmatrix} l_1 \\\\ l_2 \\end{bmatrix}y\n$$\n\napplying the Laplace transform and solving for $\\hat{x}_3(s)$ we arrive at\n\n$$\n\\hat{x}_3(s) = \\frac{l_2s}{s^2+l_1s+l_2}y_2(s) + \\frac{s+l_1}{s^2+l_1s+l_2}\\frac{u(s)}{J}.\n$$\n\nWe now have a simple linear estimator for $x_3$ that is asymptotically stable for any $l_1>0$ and $l_2>0$. It is interesting to note that if $l_2\\rightarrow \\infty$, the estimator transfer function simplifies to $\\hat{x}_3(s) = s y_2(s)$ and the result equals $\\hat{x}_3 = \\dot{\\theta}$; it is obtained by differentiating the measured $y_2 = \\theta$.\n\nSelecting $l_1 = 20$ and $l_2 = 100$ places both observer eigenvalues in $-10$.\n\n#### Controller design\nFor the requirement on settling time, the frequency of the poles must be greater than $3/T_S$ for real poles and greater than $3/\\zeta Ts$ for complex poles, where $T_s$ is the settling time (5%) and $\\zeta$ the damping. Good poles locations, in terms of response and input energy, for a double integrator system, should lay within a range of $\\pm 45\u00b0$ w.r.t. the real negative axis. By first considering these facts and then proceeding iteratively, dominant poles were chosen in $-2.8\\pm1.0i$, whereas the third pole was chosen at much higher frequency: $-15$.\nFor the requirement of zero steady-state error the reference input is scaled by a gain equal to the inverse of the steady-state gain of the closed-loop system, yielding total closed-loop gain of $1.0$.\n\n### How to use this notebook?\n- Verify the requested specifications in case of initial error in the estimate of $x_3$ for both positive and negative error.\n- Watch the changed response and, by having a physical system in your mind, try to understand why it changed the way it did.\n\n\n```python\n# Preparatory cell\n\nX0 = 0.0\nK = numpy.matrix([8/15,-4.4,-4])\nL = numpy.matrix([[66],[107/3]])\n\nAw = matrixWidget(3,3)\nAw.setM(A)\nBw = matrixWidget(3,1)\nBw.setM(B)\nCw = matrixWidget(1,3)\nCw.setM(C)\nX0w = widgets.FloatText(\n    value=X0,\n    description='',\n    disabled=False\n)\nKw = matrixWidget(1,3)\nKw.setM(K)\nLw = matrixWidget(2,1)\nLw.setM(L)\n\n\neig1c = matrixWidget(1,1)\neig2c = matrixWidget(2,1)\neig3c = matrixWidget(1,1)\neig1c.setM(numpy.matrix([-15.])) \neig2c.setM(numpy.matrix([[-2.8],[-1.0]]))\neig3c.setM(numpy.matrix([-15.]))\n\neig2o = matrixWidget(2,1)\neig3o = matrixWidget(1,1)\neig2o.setM(numpy.matrix([[-10.],[0.]]))\neig3o.setM(numpy.matrix([-10.]))\n```\n\n\n```python\n# Misc\n\n#create dummy widget \nDW = widgets.FloatText(layout=widgets.Layout(width='0px', height='0px'))\n\n#create button widget\nSTART = widgets.Button(\n    description='Test',\n    disabled=False,\n    button_style='', # 'success', 'info', 'warning', 'danger' or ''\n    tooltip='Test',\n    icon='check'\n)\n                       \ndef on_start_button_clicked(b):\n    #This is a workaround to have intreactive_output call the callback:\n    #   force the value of the dummy widget to change\n    if DW.value> 0 :\n        DW.value = -1\n    else: \n        DW.value = 1\n    pass\nSTART.on_click(on_start_button_clicked)\n\n# Define type of method \nselm = widgets.Dropdown(\n    options= ['Set K and L', 'Set the eigenvalues'],\n    value= 'Set the eigenvalues',\n    description='',\n    disabled=False\n)\n\n# Define the number of complex eigenvalues\nsele = widgets.Dropdown(\n    options= ['0 complex eigenvalues', '2 complex eigenvalues'],\n    value= '2 complex eigenvalues',\n    description='Complex eigenvalues:',\n    style = {'description_width': 'initial'},\n    disabled=False\n)\n\n#define type of ipout \nselu = widgets.Dropdown(\n    options=['impulse', 'step', 'sinusoid', 'square wave'],\n    value='step',\n    description='Type of reference:',\n    style = {'description_width': 'initial'},\n    disabled=False\n)\n# Define the values of the input\nu = widgets.FloatSlider(\n    value=2,\n    min=0,\n    max=4,\n    step=0.1,\n    description='Reference:',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.1f',\n)\nperiod = widgets.FloatSlider(\n    value=0.5,\n    min=0.001,\n    max=10,\n    step=0.001,\n    description='Period: ',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.2f',\n)\n\ngain_w2 = widgets.FloatText(\n    value=1.,\n    description='',\n    disabled=True\n)\n\nsimTime = widgets.FloatText(\n    value=3,\n    description='',\n    disabled=False\n)\n```\n\n\n```python\n# Support functions\n\ndef eigen_choice(sele):\n    if sele == '0 complex eigenvalues':\n        eig1c.children[0].children[0].disabled = False\n        eig2c.children[1].children[0].disabled = True\n        eig2o.children[1].children[0].disabled = True\n        eig = 0\n    if sele == '2 complex eigenvalues':\n        eig1c.children[0].children[0].disabled = True\n        eig2c.children[1].children[0].disabled = False\n        eig2o.children[1].children[0].disabled = False\n        eig = 2\n    return eig\n\ndef method_choice(selm):\n    if selm == 'Set K and L':\n        method = 1\n        sele.disabled = True\n    if selm == 'Set the eigenvalues':\n        method = 2\n        sele.disabled = False\n    return method\n```\n\n\n```python\n# Reduced system\nAr = numpy.matrix('0 1; 0 0')\nBr = numpy.matrix([[0],[1/1.3E-02]])\nCr = numpy.matrix('1 0')\nDr = numpy.matrix('0')\n\ndef main_callback2(Aw, Bw, X0w, K, L, eig1c, eig2c, eig3c, eig2o, eig3o, u, period, selm, sele, selu, simTime, DW):\n    eige = eigen_choice(sele)\n    method = method_choice(selm)\n    \n    if method == 1:\n        solc = numpy.linalg.eig(A-B*K)\n        solo = numpy.linalg.eig(Ar-L*Cr)\n    if method == 2:\n        if eige == 0:\n            K = control.acker(A, B, [eig1c[0,0], eig2c[0,0], eig3c[0,0]])\n            Kw.setM(K)\n            \n            L = control.acker(Ar.T, Cr.T, [eig2o[0,0], eig3o[0,0]]).T\n            Lw.setM(L)\n        if eige == 2:\n            K = control.acker(A, B, [eig3c[0,0], \n                                     numpy.complex(eig2c[0,0],eig2c[1,0]), \n                                     numpy.complex(eig2c[0,0],-eig2c[1,0])])\n            Kw.setM(K)\n            \n            L = control.acker(Ar.T, Cr.T, [numpy.complex(eig2o[0,0],eig2o[1,0]), \n                                           numpy.complex(eig2o[0,0],-eig2o[1,0])]).T\n            Lw.setM(L)\n            \n    \n    sys = control.ss(A,B,numpy.vstack((C,numpy.zeros((B.shape[1],C.shape[1])))),numpy.vstack((D,numpy.eye(B.shape[1]))))\n    sysC = control.ss(numpy.zeros((1,1)),\n                      numpy.zeros((1,numpy.shape(A)[0])),\n                      numpy.zeros((numpy.shape(B)[1],1)),\n                      -K)\n    \n    sysE = control.ss(Ar-L*Cr,\n                      numpy.hstack((L,Br-L*Dr)),\n                      numpy.matrix('0 1'),\n                      numpy.zeros((1,2)))\n    \n    sys_append = control.append(sys, sysE, sysC, control.ss(A,B,numpy.eye(A.shape[0]),numpy.zeros((A.shape[0],B.shape[1]))))\n    Q = []\n    # y in ingresso a sysE\n    for i in range(1):\n        Q.append([B.shape[1]+i+1, i+2])\n    # u in ingresso a sysE\n    for i in range(B.shape[1]):\n        Q.append([B.shape[1]+1+i+1, C.shape[0]+i+1])\n    # u in ingresso a sys\n    for i in range(B.shape[1]):\n        Q.append([i+1, C.shape[0]+B.shape[1]+1+i+1])\n    # u in ingresso al sistema che ha come uscite gli stati reali\n    for i in range(B.shape[1]):\n        Q.append([2*B.shape[1]+1+A.shape[0]+i+1, C.shape[0]+i+1])\n    # xe in ingresso a sysC\n    Q.append([2*B.shape[1]+1+1, 1])\n    Q.append([2*B.shape[1]+1+1+1, 1+1])\n    Q.append([2*B.shape[1]+1+2+1, C.shape[0]+B.shape[1]+1])\n        \n    inputv = [i+1 for i in range(B.shape[1])]\n    outputv = [i+1 for i in range(numpy.shape(sys_append.C)[0])]\n    sys_CL = control.connect(sys_append,\n                             Q,\n                             inputv,\n                             outputv)\n    \n    t = numpy.linspace(0, 100000, 2)\n    t, yout = control.step_response(sys_CL[0,0],T=t)\n    dcgain = yout[-1]\n    gain_w2.value = dcgain\n    if dcgain != 0:\n        u1 = u/gain_w2.value\n    else:\n        print('The feedforward gain is set to 0 and it changed to 1.')\n        u1 = u/1\n    print('The static gain of the closed-loop system (from the reference to the output) is: %.5f' %dcgain)\n    \n    X0w1 = numpy.zeros((2*A.shape[0]+2,1))\n    X0w1[A.shape[0]+1,0] = X0w\n    if simTime != 0:\n        T = numpy.linspace(0, simTime, 10000)\n    else:\n        T = numpy.linspace(0, 1, 10000)\n      \n    if selu == 'impulse': #selu\n        U = [0 for t in range(0,len(T))]\n        U[0] = u\n        U1 = [0 for t in range(0,len(T))]\n        U1[0] = u1\n        T, yout, xout = control.forced_response(sys_CL,T,U1,X0w1)\n    if selu == 'step':\n        U = [u for t in range(0,len(T))]\n        U1 = [u1 for t in range(0,len(T))]\n        T, yout, xout = control.forced_response(sys_CL,T,U1,X0w1)\n    if selu == 'sinusoid':\n        U = u*numpy.sin(2*numpy.pi/period*T)\n        U1 = u1*numpy.sin(2*numpy.pi/period*T)\n        T, yout, xout = control.forced_response(sys_CL,T,U1,X0w1)\n    if selu == 'square wave':\n        U = u*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n        U1 = u1*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n        T, yout, xout = control.forced_response(sys_CL,T,U1,X0w1)\n    # N.B. i primi 3 stati di xout sono quelli del sistema, mentre gli ultimi 3 sono quelli dell'osservatore\n    \n    step_info_dict = control.step_info(sys_CL[0,0],SettlingTimeThreshold=0.05,T=T)\n    print('Step info: \\n\\tRise time =',step_info_dict['RiseTime'],'\\n\\tSettling time (5%) =',step_info_dict['SettlingTime'],'\\n\\tOvershoot (%)=',step_info_dict['Overshoot'])\n    print('Max x2 value (%)=', max(abs(yout[C.shape[0]+2*B.shape[1]+1+1]))/(numpy.pi/180*30)*100)\n    \n    fig = plt.figure(num='Simulation1', figsize=(14,12))\n    \n    fig.add_subplot(221)\n    plt.title('Output response')\n    plt.ylabel('Output')\n    plt.plot(T,yout[0],T,U,'r--')\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$y$','Reference'])\n    plt.grid()\n    \n    fig.add_subplot(222)\n    plt.title('Input')\n    plt.ylabel('$u$')\n    plt.plot(T,yout[C.shape[0]])\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(223)\n    plt.title('States response')\n    plt.ylabel('States')\n    plt.plot(T,yout[C.shape[0]+2*B.shape[1]+1],\n             T,yout[C.shape[0]+2*B.shape[1]+1+1],\n             T,yout[C.shape[0]+2*B.shape[1]+1+2],\n             T,[numpy.pi/180*30 for i in range(len(T))],'r--',\n             T,[-numpy.pi/180*30 for i in range(len(T))],'r--')\n    plt.xlabel('$t$ [s]')\n    plt.legend(['$x_{1}$','$x_{2}$','$x_{3}$','limit +$x_{2}$','limit -$x_{2}$'])\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(224)\n    plt.title('Estimation error')\n    plt.ylabel('Error')\n    plt.plot(T,yout[C.shape[0]+2*B.shape[1]+1+2]-yout[C.shape[0]+B.shape[1]])\n    plt.xlabel('$t$ [s]')\n    plt.legend(['$e_{3}$'])\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    #plt.tight_layout()\n   \nalltogether2 = widgets.VBox([widgets.HBox([selm, \n                                          sele,\n                                          selu]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.Label('K:',border=3), Kw, \n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Eigenvalues:',border=3),\n                                          eig1c, \n                                          eig2c, \n                                          eig3c,\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3)]),\n                            widgets.Label('X0 est.:',border=3), X0w,\n                            widgets.Label(' ',border=3), \n                            widgets.HBox([widgets.Label('L:',border=3), Lw, \n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Eigenvalues:',border=3), \n                                          eig2o, \n                                          eig3o,\n                                          widgets.Label(' ',border=3),\n                                          widgets.VBox([widgets.Label('Inverse reference gain:',border=3),\n                                                        widgets.Label('Simulation time (s):',border=3)]),\n                                          widgets.VBox([gain_w2,simTime])]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([u, \n                                          period, \n                                          START])])\nout2 = widgets.interactive_output(main_callback2, {'Aw':Aw, 'Bw':Bw, 'X0w':X0w, 'K':Kw, 'L':Lw,\n                                                 'eig1c':eig1c, 'eig2c':eig2c, 'eig3c':eig3c, 'eig2o':eig2o, 'eig3o':eig3o, \n                                                 'u':u, 'period':period, 'selm':selm, 'sele':sele, 'selu':selu, 'simTime':simTime, 'DW':DW})\nout2.layout.height = '870px'\ndisplay(out2, alltogether2)\n```\n\n\n    Output(layout=Layout(height='870px'))\n\n\n\n    VBox(children=(HBox(children=(Dropdown(index=1, options=('Set K and L', 'Set the eigenvalues'), value='Set the\u2026\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "99c74954cf1da74c2bd1f9393fd2a50c39d64759", "size": 29870, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_en/examples/04/SS-37-Quadrotor_longitudinal_velocity_control.ipynb", "max_stars_repo_name": "ICCTerasmus/ICCT", "max_stars_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-22T18:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:10:22.000Z", "max_issues_repo_path": "ICCT/ENG/examples/04/SS-37-Quadrotor_longitudinal_velocity_control.ipynb", "max_issues_repo_name": "tuxsaurus/ICCT", "max_issues_repo_head_hexsha": "30d1aea4fb056c9736c9b4c5a0f50fff14fa6382", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICCT/ENG/examples/04/SS-37-Quadrotor_longitudinal_velocity_control.ipynb", "max_forks_repo_name": "tuxsaurus/ICCT", "max_forks_repo_head_hexsha": "30d1aea4fb056c9736c9b4c5a0f50fff14fa6382", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-24T11:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T16:36:18.000Z", "avg_line_length": 41.1432506887, "max_line_length": 753, "alphanum_fraction": 0.4874455976, "converted": true, "num_tokens": 6288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.320821300824607, "lm_q2_score": 0.14414885303274058, "lm_q1q2_score": 0.046246022542338935}}
{"text": "#### \u203b \ubb38\uc81c190 \ub9ac\ubdf0\n\n\n```python\nimport csv\nimport pandas as pd\n\nemp11=pd.read_csv('k:/Itwill/2. Python/\uc790\ub8cc/emp11.csv')\nrs2=emp11['email']\nfor i in rs2:\n    print(i.find('@'))\n```\n\n    12\n    10\n    8\n    7\n    9\n    9\n    9\n    7\n    11\n    7\n    12\n    6\n    12\n    8\n    12\n    9\n    7\n    9\n    10\n    10\n    8\n    9\n    10\n    6\n    8\n    6\n    6\n    8\n    11\n    9\n\n\n\n```python\n\nfile = open('k:/Itwill/2. Python/\uc790\ub8cc/emp11.csv','r',encoding='UTF-8')\nemp_csv=csv.reader(file)\nfor i in emp_csv:\n    data = i[7]\n    a = data.find('@')\n    b = data.find('.')\n    print(data[a+1:b],data[a+1:-b+2])\n```\n\n    emai ema\n    naver \n    naver \n    gmail \n    gmail \n    gmail \n    gmail \n    hanmail \n    naver \n    gmail \n    naver \n    naver \n    hanmail \n     gmail\n    gmail \n    gmail \n    naver \n    naver \n    naver \n    hanmai \n    naver \n    naver \n    naver \n    naver \n    naver \n    icloud \n    gmail \n    naver \n    naver \n    naver \n    gmail \n\n\n\n```python\nfor i in rs2:\n    print(i[i.find('@')+1:i.rfind('.')])\n```\n\n    naver\n    naver\n    gmail\n    gmail\n    gmail\n    gmail\n    hanmail\n    naver\n    gmail\n    naver\n    naver\n    hanmail\n    gmail\n    gmail\n    gmail\n    naver\n    naver\n    naver\n    hanmai\n    naver\n    naver\n    naver\n    naver\n    naver\n    icloud\n    gmail\n    naver\n    naver\n    naver\n    gmail\n\n\n### \u25a0 \uc608\uc81c91. \ubb38\uc790\uc5f4\uc744 \ud2b9\uc815 \ubb38\uc790(\uc5f4)\ub85c \ubd84\ub9ac\ud558\uae30(split)\n#### \ucf54\ub4dc\ub97c \uc791\uc131\ud560 \ub54c \uac00\uc7a5 \ub9ce\uc774 \uc811\ud558\uac8c \ub418\ub294 \uacbd\uc6b0\uac00 \uad6c\ubd84\uc790(separator)\ub85c \uad6c\ubd84\ub418\uc5b4 \uc788\ub294 \ubb38\uc790\uc5f4 \ud30c\uc2f1(parsing)\ud558\ub294 \uc77c\n#### \uc774\ub54c \ubb38\uc790\uc5f4 \uac1d\uccb4\uc758 split()\uc744 \ud65c\uc6a9\ud558\uba74 \uad6c\ubd84\uc790\ub97c \uae30\uc900\uc73c\ub85c \ubb38\uc790\uc5f4\uc744 \uc27d\uac8c \ubd84\ub9ac\ud558\uc5ec \ud30c\uc2f1\n\n\n```python\n# \uc608\uc81c\nurl='http://www.naver.com/news/today=20191204'\nresult=url.split('/') # \ubb38\uc790\uc5f4\uc5d0\uc11c /\ub85c \uad6c\ubd84\ud574\uc11c \ubb38\uc790\ub97c \ub9ac\uc2a4\ud2b8\ud654\nresult\n```\n\n\n\n\n    ['http:', '', 'www.naver.com', 'news', 'today=20191204']\n\n\n\n### \u203b \ubb38\uc81c191. \uc6f9\ub85c\uadf8\uc640 \uac19\uc740 log \ub370\uc774\ud130\ub97c \ub370\uc774\ud130 \ubd84\uc11d\uac00\ub4e4\uc774 \ubd84\uc11d\ud560 \uc77c\uc774 \ub9ce\uc774 \uc788\ub294\ub370 \uc544\ub798\uc758 log \ub370\uc774\ud130\uc5d0\uc11c \uc544\ub798\uc758 \ub370\uc774\ud130\ub97c \ucd94\ucd9c\ud558\uc2dc\uc624\n```\nlog='name:\ud64d\uae38\ub3d9 age:17 major:\uacbd\uc601\ud559 nation:\ud55c\uad6d' \n\uacb0\uacfc: ['name:\ud64d\uae38\ub3d9','...']\n```\n\n\n```python\nlog='name:\ud64d\uae38\ub3d9 age:17 major:\uacbd\uc601\ud559 nation:\ud55c\uad6d' # \uacb0\uacfc: ['name:\ud64d\uae38\ub3d9','...']\nlog.split(' ')\n```\n\n\n\n\n    ['name:\ud64d\uae38\ub3d9', 'age:17', 'major:\uacbd\uc601\ud559', 'nation:\ud55c\uad6d']\n\n\n\n### \u203b \ubb38\uc81c192. \uc544\ub798\uc758 log \ubb38\uc790\uc5f4\uc5d0\uc11c \uc544\ub798\uc758 \ub370\uc774\ud130\ub9cc \ucd94\ucd9c\ud558\uc2dc\uc624\n```\nlog='name:\ud64d\uae38\ub3d9 age:17 major:\uacbd\uc601\ud559 nation:\ud55c\uad6d' \n\uacb0\uacfc: ['\ud64d\uae38\ub3d9','17',...]\n```\n\n\n```python\nrs=log.split()\nls=[j[1] for j in [i.split(':') for i in rs]]\nls\n```\n\n\n\n\n    ['\ud64d\uae38\ub3d9', '17', '\uacbd\uc601\ud559', '\ud55c\uad6d']\n\n\n\n### \u25a0 \uc608\uc81c92. \ubb38\uc790\uc5f4\uc744 \ud2b9\uc815 \ubb38\uc790(\uc5f4)\ub85c \uacb0\ud569\ud558\uae30 (join)\n#### \ubb38\uc790\uc5f4 \uac1d\uccb4\uc758 join() \uba54\uc18c\ub4dc\ub294 split()\uacfc\ub294 \ubc18\ub300\ub85c \ubb38\uc790\uc5f4\uc774 \uc694\uc18c\uc778 \ub9ac\uc2a4\ud2b8\ub97c \uc778\uc790\ub85c \ubc1b\uc544 \ub9ac\uc2a4\ud2b8 \ubaa8\ub4e0 \uc694\uc18c\ub97c \ud2b9\uc815 \ubb38\uc790\uc5f4\ub85c \uc5f0\uacb0\ud558\uc5ec \uc0c8\ub85c\uc6b4 \ubb38\uc790\uc5f4\ub85c \ub9cc\ub4e4\uc5b4 \ub9ac\ud134\n\n\n```python\n# \uc608\uc81c\nloglist=['2020/05/22','200','ok','\uc774\uc900\ud638']\nbond=':'\nlog=bond.join(loglist)\nlog\n```\n\n\n\n\n    '2020/05/22:200:ok:\uc774\uc900\ud638'\n\n\n\n### \u203b \ubb38\uc81c193. \uc704\uc5d0\uc11c \ubc30\uc6b4 join\uc744 \uc774\uc6a9\ud574\uc11c \uc6b0\ub9ac\ubc18 \ub370\uc774\ud130(emp11.csv)\uc758 \ub370\uc774\ud130 \uc911 \uc774\ub984\uc744 \uc544\ub798\uc640 \uac19\uc774 \ucd9c\ub825\ud558\uc2dc\uc624(\uc131\uc528\ub85c \uc815\ub82c\ud574\uc11c)\n```\n\ud78c\ud2b8 : a.sort()\n\uac15\ud61c\ub9ac,\uad8c\ubbfc\uc900,\uae40\uba85\ud658,\uae40\uc11c\uc900,\uae40\uc18c\uc560,\uae40\uc720\uc9c4,\uae40\uc740\uc8fc,\uae40\uc9c0\uc11d,....\n```\n\n\n```python\nfile=open('k:/Itwill/2. Python/\uc790\ub8cc/emp11_2.csv','r',encoding='UTF-8')\nname=csv.reader(file)\nls=[]\nfor i in name:\n    ls.append(i[1]) # ls\uc5d0 \uc774\ub984\uc744 \ucd94\uac00\nls.sort() # \uc815\ub82c\nbond=',' \nrs=bond.join(ls) # ls\uc758 \uc694\uc18c\ub97c bond\uc548\uc758 \uac12\uc73c\ub85c join\nrs\n```\n\n\n\n\n    '\uac15\ud61c\ub9ac,\uad8c\ubbfc\uc900,\uae40\uba85\ud658,\uae40\uc11c\uc900,\uae40\uc18c\uc560,\uae40\uc720\uc9c4,\uae40\uc740\uc8fc,\uae40\uc9c0\uc11d,\uae40\ud0dc\ud658,\uae40\ud604\uc218,\ubc15\ubbfc\ud638,\ubc15\uc0c1\ud76c,\ubc15\uc9c0\uc131,\uc11c\ub3d9\ud601,\uc548\ud0dc\ud615,\uc591\uc120\uc885,\uc704\uc8fc\ud76c,\uc774\uc11c\uc9c0,\uc774\uc2b9\ud601,\uc774\uc608\ub77c,\uc774\uc900\ud638,\uc774\ud0dc\ud658,\uc804\uc9c0\uc5f0,\uc815\uc8fc\ud76c,\uc870\uc131\uc6d0,\uc870\uc6d0\uae30,\ucd5c\ubbfc\ud601,\ucd5c\uc720\ub9ac,\ud55c\ud0dc\ud604,\ud64d\uc2b9\ud76c'\n\n\n\n\n```python\nfile=open('k:/Itwill/2. Python/\uc790\ub8cc/emp11_2.csv','r',encoding='UTF-8')\nname=csv.reader(file)\nprint(','.join(sorted([i[1] for i in name])))\n```\n\n    \uac15\ud61c\ub9ac,\uad8c\ubbfc\uc900,\uae40\uba85\ud658,\uae40\uc11c\uc900,\uae40\uc18c\uc560,\uae40\uc720\uc9c4,\uae40\uc740\uc8fc,\uae40\uc9c0\uc11d,\uae40\ud0dc\ud658,\uae40\ud604\uc218,\ubc15\ubbfc\ud638,\ubc15\uc0c1\ud76c,\ubc15\uc9c0\uc131,\uc11c\ub3d9\ud601,\uc548\ud0dc\ud615,\uc591\uc120\uc885,\uc704\uc8fc\ud76c,\uc774\uc11c\uc9c0,\uc774\uc2b9\ud601,\uc774\uc608\ub77c,\uc774\uc900\ud638,\uc774\ud0dc\ud658,\uc804\uc9c0\uc5f0,\uc815\uc8fc\ud76c,\uc870\uc131\uc6d0,\uc870\uc6d0\uae30,\ucd5c\ubbfc\ud601,\ucd5c\uc720\ub9ac,\ud55c\ud0dc\ud604,\ud64d\uc2b9\ud76c\n\n\n### \u25a0 \uc608\uc81c93. \ubb38\uc790\uc5f4\uc5d0\uc11c \ud2b9\uc815 \ubb38\uc790(\uc5f4)\uc744 \ub2e4\ub978 \ubb38\uc790(\uc5f4)\ub85c \ubc14\uafb8\uae30 (replace)\n#### \ubb38\uc790\uc5f4 \uac1d\uccb4\uc758 replace() \uba54\uc18c\ub4dc\ub294 \ubb38\uc790\uc5f4\uc5d0\uc11c \ud2b9\uc815 \ubb38\uc790\ub098 \ubb38\uc790\uc5f4\uc744 \ub2e4\ub978 \ubb38\uc790\ub098 \ubb38\uc790\uc5f4\ub85c \ubcc0\uacbd\n\n\n```python\n# \uc608\uc81c\ntxt='My password is 1234'\nrs=txt.replace('1','0') # \ubb38\uc790\uc5f4 \ubcc0\uc218 txt\uc758 \ubb38\uc790\uc911 1\uc744 0\uc73c\ub85c \ubc14\uafc8\nrs\n```\n\n\n\n\n    'My password is 0234'\n\n\n\n### \u203b \ubb38\uc81c194. \uc544\ub798\uc758 \ub9ac\uc2a4\ud2b8\uc758 \uacb0\uacfc\ub97c \uc544\ub798\uc640 \uac19\uc774 \ucd9c\ub825\ud558\uc2dc\uc624\n```\nresult=['name:\ud64d\uae38\ub3d9 age:17 major:\uacbd\uc601\ud559 nation:\ud55c\uad6d']\n\uacb0\uacfc: \nname ---> \ud64d\uae38\ub3d9\nage ---> 17\nmajor ---> \uacbd\uc601\ud559\nnation ---> \ud55c\uad6d\n```\n\n\n```python\nresult=['name:\ud64d\uae38\ub3d9', 'age:17', 'major:\uacbd\uc601\ud559', 'nation:\ud55c\uad6d']\nfor i in result:\n    print(i.replace(':',' ---> '))\n\n```\n\n    name ---> \ud64d\uae38\ub3d9\n    age ---> 17\n    major ---> \uacbd\uc601\ud559\n    nation ---> \ud55c\uad6d\n\n\n\n```python\nprint('\\n'.join([i.replace(':',' ---> ') for i in result]))\n```\n\n    name ---> \ud64d\uae38\ub3d9\n    age ---> 17\n    major ---> \uacbd\uc601\ud559\n    nation ---> \ud55c\uad6d\n\n\n### \u25a0 \uc608\uc81c94. \ubb38\uc790\uc5f4\uc744 \ubc14\uc774\ud2b8 \uac1d\uccb4\ub85c \ubc14\uafb8\uae30 (encode)\n#### \uc778\ucf54\ub529(encoding)\uc774\ub780?\n```\n\uc0ac\ub78c\uc774 \uc778\uc9c0\ud560 \uc218 \uc788\ub294 \ud615\ud0dc\uc758 \ub370\uc774\ud130\ub97c \uc57d\uc18d\ub41c \uaddc\uce59\uc5d0 \uc758\ud574 \ucef4\ud4e8\ud130\uac00 \uc0ac\uc6a9\ud558\ub294 0\uacfc 1\ub85c \ubcc0\ud658\ud558\ub294 \uacfc\uc815.\n\ucef4\ud4e8\ud130\uc758 \ubc1c\uba85, \ubc1c\uc804\uc774 \ubbf8\uad6d\uc758 \ud559\uacc4\uc640 \uae30\uc5c5\uc744 \uc911\uc2ec\uc73c\ub85c \uc774\ub8e8\uc5b4\uc9c0\ub2e4\ubcf4\ub2c8 \ubb38\uc790 \uc9d1\ud569\ub3c4 \ubbf8\uad6d\uc744 \uae30\uc900\uc73c\ub85c \uc81c\uc815.\n\ubbf8\uad6d\uc5d0\uc11c\ub294 \uc81c\uc815\ub41c ASCII(\ubbf8\uad6d \uc815\ubcf4 \uad50\ud658 \ud45c\uc900 \ubd80\ud638)\ub294 1960\ub144\ub300\uc5d0 \uc81c\uc815\ub41c \ubb38\uc790 \uc9d1\ud569\uc73c\ub85c \uc774\ud6c4 \uac1c\ubc1c\ub41c \ubb38\uc790 \uc9d1\ud569\uc758 \ud1a0\ub300\ub97c \uc774\ub8e8\uace0 \uc788\ub2e4.\nASCII\ub294 7\ube44\ud2b8\ub9cc\uc744 \uc774\uc6a9\ud574\uc11c \uc74c\uc774 \uc544\ub2cc \uc218(0~127)\uc758 \ubb38\uc790 \uc9d1\ud569\ub0b4\uc758 \ubb38\uc790 \ud560\ub2f9 \uc57d\uc18d\n```\n```\n\uc0ac\ub78c\uc774 \uc54c\uc544 \ubcfc \uc218 \uc788\ub294 \uc5b8\uc5b4 --(\ubcc0\uacbd)--> \ucef4\ud4e8\ud130\uac00 \uc54c\uc544\ubcfc \uc218 \uc788\ub294 \uc22b\uc790\n```\n\n\n### \u203b \ubb38\uc81c195. chr\uc744 \uc774\uc6a9\ud574\uc11c \uc22b\uc790 65\ubd80\ud130 127\uae4c\uc9c0 \uc5b4\ub5a4 \ubb38\uc790\uc778\uc9c0 \ucd9c\ub825\ud558\uc2dc\uc624\n\n\n```python\n# \uc608\uc81c: A\ub294 \uc22b\uc790 65. a\ub294 \uc22b\uc790 97\nfor i in range(65,128):\n    print(i,'-->',chr(i))\n```\n\n    65 --> A\n    66 --> B\n    67 --> C\n    68 --> D\n    69 --> E\n    70 --> F\n    71 --> G\n    72 --> H\n    73 --> I\n    74 --> J\n    75 --> K\n    76 --> L\n    77 --> M\n    78 --> N\n    79 --> O\n    80 --> P\n    81 --> Q\n    82 --> R\n    83 --> S\n    84 --> T\n    85 --> U\n    86 --> V\n    87 --> W\n    88 --> X\n    89 --> Y\n    90 --> Z\n    91 --> [\n    92 --> \\\n    93 --> ]\n    94 --> ^\n    95 --> _\n    96 --> `\n    97 --> a\n    98 --> b\n    99 --> c\n    100 --> d\n    101 --> e\n    102 --> f\n    103 --> g\n    104 --> h\n    105 --> i\n    106 --> j\n    107 --> k\n    108 --> l\n    109 --> m\n    110 --> n\n    111 --> o\n    112 --> p\n    113 --> q\n    114 --> r\n    115 --> s\n    116 --> t\n    117 --> u\n    118 --> v\n    119 --> w\n    120 --> x\n    121 --> y\n    122 --> z\n    123 --> {\n    124 --> |\n    125 --> }\n    126 --> ~\n    127 --> \u007f\n\n\n#### ASCII \ucf54\ub4dc\ud45c -> \ubbf8\uad6d \uc5d4\uc9c0\ub2c8\uc5b4\ub4e4\uc740 \ud3b8\ud558\uac8c \uc0ac\uc6a9 but \ub2e4\ub978 \ub098\ub77c\ub294 \ubd88\ud3b8\n```\n1. \uc11c\uc720\ub7fd \n    - \ub3c5\uc77c\uc5b4\uc758 \uc6c0\ub77c\uc6b0\ud2b8, \uc2a4\ud398\uc778\uc5b4\uc758 \ubb3c\uacb0\ud45c, \ud130\ud0a4\uc5b4\uc758 \uc2dc\ub51c\ub7ec, \ud504\ub791\uc2a4\uc5b4\uc758 \uc545\uc13c\ud2b8\ub294 7\ube44\ud2b8\ub85c\ub294 \ud45c\ud604 \ubd88\uac00\n    - \ubbf8\uad6d \ud45c\uc900\uc744 \ubcf4\uc644\ud55c \uc0c8\ub85c\uc6b4 \uad6d\uc81c \ud45c\uc900\uc774 \ub4f1\uc7a5\n    - \ubbf8\uad6d \ud45c\uc900\uc778 0~127 \uc601\uc5ed\uc740 \uadf8\ub300\ub85c \uc720\uc9c0\ud558\uace0 128~255 \uc601\uc5ed\uc758 \uc11c\uc720\ub7fd\uc5b4\uc5d0 \ud544\uc694\ud55c \ubb38\uc790\ub97c \ucd94\uac00\n    - 129\uc5d0 256\uc778 8\ube44\ud2b8\ub85c \ud45c\ud604\ud558\ub294 \ubb38\uc790 \uc9d1\ud569\uc744 \ucd94\uac00\ud574\uc11c \uc11c\uc720\ub7fd\uc5b4\ub3c4 \ucef4\ud4e8\ud130\ub85c \uad6c\ud604\uac00\ub2a5\ud558\uac8c \ub428\n```\n```\n2. \uc544\uc2dc\uc544\n    - \ud55c\uc790, \uc77c\ubcf8\uc5b4, \ud55c\uae00\uc774 8\ube44\ud2b8\uc5d0 \ub4e4\uc5b4\ub9de\uc9c0 \uc54a\uc74c\n    - \uc544\uc2dc\uc544\ub97c \uc704\ud574\uc11c \ub354\ube14 \uce90\ub9ad\ud130 \uc14b 16\ube44\ud2b8\ub85c\ub41c \ubb38\uc790 \uc9d1\ud569\uc744 \uc81c\uacf5\ud574\uc11c \ud574\uacb0\n    - 65536\uc758 \ubb38\uc790\ub97c \ud560\ub2f9\ud560 \uc218 \uc788\uac8c \ud568\n    - EUC-KR, CP949\uac00 \uc5ec\uae30\uc5d0 \ud574\ub2f9\n        - \ud3ec\uc2a4\ucf54 \ub354 \uc0fe \uc544\ud30c\ud2b8\uac00 \uc624\ub77c\ud074 DB\uc5d0 insert\ub418\uba74 ??\ub85c \ubcf4\uc774\uac8c \ub41c\ub2e4\n    - \uc774 \ubb38\uc81c\ub97c \ud574\uacb0\ud558\uae30 \uc704\ud574 \ub098\uc628 \uac83\uc774 \uc720\ub2c8\ucf54\ub4dc\n        - UTF-7, UTF-8, UTF-6, UTF-32 \uc774 \uc911 UTF-8\uc744 \uac00\uc7a5 \ub9ce\uc774 \uc0ac\uc6a9  \n```  \n##### \ud30c\uc774\uc36c\uc5d0\uc11c \ud55c\uae00\uc774 ??\ub85c \ucd9c\ub825 \uc548\ub418\ub824\uba74 \uc778\ucf54\ub529 UTF-8\ub85c \ub9de\ucdb0\uc918\uc57c \ud55c\ub2e4\n    \n\n### \u25a0 \uc608\uc81c95. \ubc14\uc774\ud2b8 \uac1d\uccb4\ub97c \ubb38\uc790\uc5f4\ub85c \ubc14\uafb8\uae30(decode)\n#### \ub514\ucf54\ub529(decoding)\n```\n\ucef4\ud4e8\ud130\uac00 \uc54c\uc544\ubcfc \uc218 \uc788\ub294 \uc5b8\uc5b4 ------------> \uc0ac\ub78c\uc774 \uc54c\uc544\ubcfc \uc218 \uc788\ub294 \uc5b8\uc5b4\n```\n\n\n```python\n# \uc608\uc81c\nu_txt='A'\nb_txt=u_txt.encode()\nprint(u_txt)\nprint(b_txt) # b'A' : binary 'A'\nc_txt=b_txt.decode()\nprint(c_txt)\n```\n\n    A\n    b'A'\n    A\n\n\n### \u25a0 \uc608\uc81c96. \uc21c\ucc28\uc801\uc778 \uc815\uc218 \ub9ac\uc2a4\ud2b8 \ub9cc\ub4e4\uae30(range)\n#### [0,1,2,3]\uc774\ub098 [100,101,102,103]\uacfc \uac19\uc774 \uc21c\ucc28\uc801\uc778 \uc815\uc218 \ub9ac\uc2a4\ud2b8\ub97c \ub9cc\ub4dc\ub294 \uac00\uc7a5 \uac04\ub2e8\ud55c \ubc29\ubc95\uc740 \ud30c\uc774\uc36c \ub0b4\uc7a5\ud568\uc218 range()\ub97c \uc774\uc6a9\n\n\n```python\n# \uc608\uc81c\nfor i in range(1,11):\n    print(i)\n```\n\n    1\n    2\n    3\n    4\n    5\n    6\n    7\n    8\n    9\n    10\n\n\n### \u203b \ubb38\uc81c196. \uc544\ub798\uc758 \uacb0\uacfc\ub97c \ucd9c\ub825\ud558\uc2dc\uc624\n```\n[2,4,6,8,10,12,14,16,18]\n```\n\n\n```python\n[i for i in range(2,20,2)]        \n```\n\n\n\n\n    [2, 4, 6, 8, 10, 12, 14, 16, 18]\n\n\n\n\n```python\nlist(range(2,20,2))\n```\n\n\n\n\n    [2, 4, 6, 8, 10, 12, 14, 16, 18]\n\n\n\n### \u25a0 \uc608\uc81c97. \ub9ac\uc2a4\ud2b8\uc5d0\uc11c \ud2b9\uc815 \uc694\uc18c \uc5bb\uae30\n#### \ub9ac\uc2a4\ud2b8\uc758 \ud2b9\uc815 \uc704\uce58\uc5d0 \uc788\ub294 \uc694\uc18c\uac12\uc744 \uad6c\ud558\ub824\uba74 \uc778\ub371\uc2f1\uc744 \uc774\uc6a9\n#### \uc778\ub371\uc2a4\ub294 0\ubd80\ud130 \uc2dc\uc791\n\n\n```python\na=[1,2,'a','b','c',[4,5,6]]\na[1]\n```\n\n\n\n\n    2\n\n\n\n### \u203b \ubb38\uc81c197. \uc704\uc758 a \ub9ac\uc2a4\ud2b8\uc5d0\uc11c \uc22b\uc790 4\ub97c \ucd9c\ub825\ud558\uc2dc\uc624\n\n\n```python\na[5][0]\n```\n\n\n\n\n    4\n\n\n\n### \u203b \ubb38\uc81c198. \uc544\ub798\uc758 \ub9ac\uc2a4\ud2b8\uc5d0\uc11c \uc22b\uc790 7\uc744 \ucd9c\ub825\ud558\uc2dc\uc624\n\n\n```python\nb=[2,3,4,[5,6,[7,8],9],10]\nb[3][2][0]\n```\n\n\n\n\n    7\n\n\n\n### \u203b \ubb38\uc81c199. \uc8fc\uba38\ub2c8\uc18d\uc5d0 \ub178\ub780\uacf5 6\uac1c\uc640 \ud30c\ub780\uacf5 4\uac1c \ucd1d 10\uac1c\uc758 \uacf5\uc774 \ub4e4\uc5b4\uc788\ub294 \ub9ac\uc2a4\ud2b8\ub97c \ub9cc\ub4dc\uc2dc\uc624\n\n\n```python\nls=['y']*6+['b']*4\nls\n```\n\n\n\n\n    ['y', 'y', 'y', 'y', 'y', 'y', 'b', 'b', 'b', 'b']\n\n\n\n### \u203b \ubb38\uc81c200. \uc704\uc758 \uc8fc\uba38\ub2c8\uc5d0\uc11c \uacf5\uc744 \ud558\ub098 \uc784\uc758\ub85c \uaebc\ub0b4\ubcf4\uc2dc\uc624\n\n\n```python\nimport random\nprint(random.sample(ls,1)) # random.sample : \ub9ac\uc2a4\ud2b8\ub85c \ucd9c\ub825\n```\n\n    ['b']\n\n\n### \u203b \ubb38\uc81c201. \uc704\uc758 \uc8fc\uba38\ub2c8\uc5d0\uc11c \uc784\uc758\ub85c 3\uac1c\uc758 \uacf5\uc744 \uaebc\ub0bc \uacbd\uc6b0 \uc774 \uc911\uc5d0 2\uac1c\uc758 \uacf5\uc774 \ud30c\ub780\uacf5\uc77c \ud655\ub960\uc744 \uad6c\ud558\uc2dc\uc624(\ube44\ubcf5\uc6d0)\n\n\n```python\ncnt=0\nfor _ in range(100000):\n    ls=['y']*6+['b']*4\n    pick=[]\n    for i in range(3):\n        pick.append(ls.pop(ls.index(random.choice(ls))))\n    if pick.count('b')==2:\n        cnt += 1\nprint(cnt/100000)\n```\n\n    0.30088\n\n\n\n```python\nls=['y']*6+['b']*4\ncnt=0\nfor i in range(100000):\n    pick=random.sample(ls,3)\n    if pick.count('b')==2:\n        cnt += 1\nprint(cnt/100000)\n```\n\n    0.30035\n\n\n\n```python\nsum([random.sample(ls,3).count('b')==2 for i in range(100000)])/100000\n```\n\n\n\n\n    0.3007\n\n\n\n### \u203b \ubb38\uc81c202. \uc544\ub798\uc758 a \ub9ac\uc2a4\ud2b8\uc5d0\uc11c \ub79c\ub364\uc73c\ub85c \ucd94\ucd9c\ub418\ub294 3\uac1c\uc758 \uc22b\uc790\uac12\uc758 \ud3c9\uade0\uac12\uc744 \ucd9c\ub825\ud558\uc2dc\uc624\n\n\n```python\na=[1,2,3,4,5,6,7]\nb=random.sample(a,3)\nprint(sum(b)/len(b))\n```\n\n    4.666666666666667\n\n\n### \u203b \ubb38\uc81c203. \uc704\uc758 \ucf54\ub4dc\ub97c numpy\ub85c \uad6c\ud604\ud558\uc2dc\uc624\n\n\n```python\nnp.random.choice(a,3).mean()\n```\n\n\n\n\n    5.333333333333333\n\n\n\n\n```python\nnp.mean(random.sample(a,3))\n```\n\n\n\n\n    5.0\n\n\n\n### \u203b \ubb38\uc81c204. \uc544\ub798\uc640 \uac19\uc774 \ucd08\ub4f1\ud559\uc0dd \uc2ed\ub9cc\uba85\uc744 \uad6c\uc131\ud558\ub294\ub370 \ud3c9\uade0\ud0a4\ub97c 148.5\ub85c \ud558\uace0 \ud45c\uc900\ud3b8\ucc28\ub97c 7.8\ub85c \ud574\uc11c \uad6c\uc131\ud558\uace0 \uc774 \ucd08\ub4f1\ud559\uc0dd\ub4e4 \uc911 \ub79c\ub364\uc73c\ub85c 100\uba85\uc744 \ucd94\ucd9c\ud574\uc11c \ud3c9\uade0\ud0a4\ub97c \ucd9c\ub825\ud558\uc2dc\uc624\n\n\n```python\navg=148.5\nstd=7.8\nN=100000\nheight=np.random.randn(N)*std+avg\nnp.random.choice(height,100).mean()\n```\n\n\n\n\n    148.54899892360692\n\n\n\n### \u25a0 \uac00\uc124\uac80\uc815\uc774\ub780?\n#### \uac00\uc124\uc774\ub780 \ub450 \uac1c \uc774\uc0c1\uc758 \ubcc0\uc218 \ub610\ub294 \ud604\uc0c1\uac04\uc758 \uad00\uacc4\ub97c \uac80\uc815 \uac00\ub2a5\ud55c \ud615\ud0dc\ub85c \uc11c\uc220\ud55c \ubb38\uc7a5\uc73c\ub85c \uacfc\ud559\uc801 \uc870\uc0ac\uc5d0 \uc758\ud558\uc5ec \uac80\uc815\uc774 \uac00\ub2a5\ud55c \uc0ac\uc2e4\uc744 \ub9d0\ud55c\ub2e4.\n```\n\uac00\uc124\uc5d0\ub294 \uc5f0\uad6c\uc790\uac00 \uc0c8\ub85c\uc774 \uc8fc\uc7a5\ud558\uc5ec \uac80\uc815\ud558\uace0\uc790 \ud558\ub294 \uc5f0\uad6c\uac00\uc124(\ub300\ub9bd\uac00\uc124)\uacfc \uc774\uc5d0 \ubc18\ud558\uc5ec \uae30\uc874\uc5d0 \uc77c\ubc18\uc801\uc778 \uc0ac\uc2e4\ub85c \ubc1b\uc544\ub4e4\uc5ec\uc9c0\uace0 \uc788\ub294 \ub0b4\uc6a9\uc744 \ub098\ud0c0\ub0b4\ub294 \uadc0\ubb34\uac00\uc124\uc774 \uc788\ub2e4.\n```\n#### \uc77c\ubc18\uc801\uc73c\ub85c \uadc0\ubb34\uac00\uc124\uc740 $H_0$\uc73c\ub85c \ud45c\uae30\ud558\uace0 \uc5f0\uad6c\uac00\uc124\uc740 $H_1$\ub85c \ud45c\uae30\ud55c\ub2e4.\n```\n\ud1b5\uc0c1\uc801\uc73c\ub85c \uc5f0\uad6c\uac00\uc124\uc774 \uba3c\uc800 \uc124\uc815\ub418\uba74, \uadc0\ubb34\uac00\uc124\uc740 \uc5f0\uad6c\uac00\uc124\uc5d0\uc11c \uc8fc\uc7a5\ud558\ub294 \ub0b4\uc6a9\uacfc \ubc18\ub300\ub418\ub294 \ubaa8\ub4e0 \ub0b4\uc6a9\uc744 \ud3ec\ud568\ud558\ub294 \uac83\uc774 \ub41c\ub2e4.\n```\n#### \uc77c\ubc18\uc801\uc73c\ub85c \uc0c8\ub85c\uc6b4 \uc8fc\uc7a5(\uc5f0\uad6c\uac00\uc124)\uc740 \uadf8\uac83\uc774 \uac1d\uad00\uc801\uc73c\ub85c \uba85\ubc31\ud558\uac8c \uc785\uc99d\ub418\uc9c0 \uc54a\uc73c\uba74 \uc27d\uac8c \ubc1b\uc544\ub4e4\uc5ec\uc9c0\uc9c0 \uc54a\ub294\ub2e4.\n#### \ub530\ub77c\uc11c \uadc0\ubb34\uac00\uc124\uc744 \uae30\uac01\ud558\uace0 \uc5f0\uad6c\uac00\uc124\uc774 \ucc44\ud0dd\ub418\ub294 \uc704\ud574\uc11c\ub294 \uae30\uc874 \uc9c0\uc2dd\uc744 \ub098\ud0c0\ub0b4\ub294 \uadc0\ubb34\uac00\uc124\uc774 \ubd84\uba85\ud558\uac8c \uc798\ubabb\ub418\uc5c8\uc74c\uc744 \uc785\uc99d\ud574\uc57c \ud55c\ub2e4\n\n### \u25a0 \uac00\uc124\uac80\uc815\uc758 \uc911\uc694\ud55c \uc6a9\uc5b4 4\uac1c\n1. \uc720\uc758\uc218\uc900($\\alpha$) : \uadc0\ubb34\uac00\uc124\uc774 \uc633\ub2e4\ub294 \uc804\uc81c\ud558\uc5d0 \uc5b4\ub290\uc815\ub3c4 \uadf9\ub2e8\uc801\uc778 \ud45c\ubcf8 \ud1b5\uacc4\ub7c9\uac12\uc774 \ub098\uc624\uba74 \uadc0\ubb34\uac00\uc124\uc774 \uc798\ubabb\ub418\uc5c8\ub2e4\uace0 \ud310\ub2e8\ud558\uc5ec \uadc0\ubb34\uac00\uc124\uc744 \uae30\uac01\ud560 \ucd5c\ub300\uc758 \ud655\ub960  \n2. \uc784\uacc4\uce58 : \uac80\uc815\uc758 \uc885\ub958(\uc591\uce21/\ub2e8\uce21)\uc640 \uc720\uc758\uc218\uc900\uc744 \uace0\ub824\ud574\uc11c \uc0b0\ucd9c\ud55c \uac12\uc73c\ub85c \uac00\uc124\uc758 \ucc44\ud0dd \uc5ec\ubd80\ub97c \uacb0\uc815\uc9d3\ub294 \uacbd\uacc4\uac12  \n3. \uac80\uc815\ud1b5\uacc4\ub7c9 : \ud45c\ubcf8\uc73c\ub85c\ubd80\ud130 \ucd94\ucd9c\ud55c \ud1b5\uacc4\ub7c9\uc774\ub098 \uac80\uc815\uc5d0 \uc0ac\uc6a9\ud560 \ubd84\ud3ec\uc5d0 \ub530\ub77c \uadf8\uc5d0 \ub9de\ub294 \uac12\uc73c\ub85c \uce58\ud658\ud55c \ud1b5\uacc4\ub7c9  \n4. $p$-Value : \ud45c\ubcf8\uc73c\ub85c\ubd80\ud130 \uc5bb\uc740 \ud1b5\uacc4\ub7c9 \ud639\uc740 \uc774\ub97c \uce58\ud658\ud55c \uac80\uc815 \ud1b5\uacc4\ub7c9\uc758 \uc808\ub313\uac12\ubcf4\ub2e4 \ub354 \ud070 \uc808\ub313\uac12\uc744 \ub610\ub2e4\ub978 \ud45c\ubcf8\uc73c\ub85c\ubd80\ud130 \uc5bb\uc744 \uc218 \uc788\ub294 \ud655\ub960\n\n### \u203b (\uc624\ub298\uc758 \ub9c8\uc9c0\ub9c9 \ubb38\uc81c)(\ud30c\uc774\uc36c \uc54c\uace0\ub9ac\uc998 \ubb38\uc81c 34\ubc88)\n```\n2000 \ub144 \ucd08\ub4f1\ud559\uad50 5\ud559\ub144 \uc5b4\ub9b0\uc774\ub4e4\uc758 \uc804\uad6d \ud3c9\uade0\ud0a4\ub294 148.5cm , \ud45c\uc900\uc624\ucc28\ub294 7.8 \uc774\uc600\uc2b5\ub2c8\ub2e4.\n\uc2dd\uc0dd\ud65c\uc758 \ubcc0\ud654\ub85c \uc778\ud574 \uc5b4\ub9b0\uc774\ub4e4\uc758 \uc131\uc7a5\uc5d0 \ubcc0\ud654\uac00 \uc77c\uc5b4\ub0ac\ub2e4\uace0 \uc0dd\uac01\ub429\ub2c8\ub2e4. \uadf8\ub798\uc11c \ud604\ub300\uc758 \ucd08\ub4f1\ud559\uad50 5\ud559\ub144 \uc5b4\ub9b0\uc774\ub4e4\uc744 100\uba85\uc744\n\ubb34\uc791\uc704\ub85c \ucd94\ucd9c\ud574 \uc870\uc0ac\ud588\ub354\ub2c8 \uadf8 \ud3c9\uade0\ud0a4\uac00 150cm \uc600\uc2b5\ub2c8\ub2e4. \ucd08\ub4f1\ud559\uad50 5\ud559\ub144 \uc5b4\ub9b0\uc774\ub4e4\uc758 \ud3c9\uade0 \ud0a4\uac00 \ub298\uc5b4\ub0ac\ub2e4\ub294 \uac83\uc744\n\uc720\uc758\uc218\uc900 5%\ub85c \uac80\uc815\ud574\ubcf4\uc138\uc694 ~ ( \ub2e8\uce21\uac80\uc815)\n```\n\n```python\navg=148.5\nstd=7.8\nN=100000\nheight=np.random.randn(N)*std+avg\nnp.random.choice(height,100).mean()\n```\n\n\n```python\navg5=150\nstd5=7.8\nN5=100000\nheight5=np.random.randn(N)*std+avg5\nsample_avg=np.random.choice(height5,100).mean()\nsample_avg\n```\n\n\n\n\n    149.1947234602117\n\n\n\n#### tall_pvalue()\ub97c \uc0dd\uc131\ud558\uace0 \ud3c9\uade0\ud0a4 \uac12\uc744 \ub123\uc5c8\uc744 \ub54c p-value\uac12\uc774 \ucd9c\ub825\ub418\uac8c \ud558\uc2dc\uc624\n\n\n```python\ndef tall_pvalue(n):\n    from sympy import exp, sqrt, pi, Integral, Symbol, S\n    import numpy as np\n        \n    avg=148.5\n    std=7.8\n    N=100000\n    height=np.random.randn(N)*std+avg\n       \n    s_std=np.array([np.random.choice(height,100).mean() for _ in range(100000)]).std()\n        \n    data=n\n            \n    x = Symbol('x')\n    f = exp(-(x-avg)**2/(2*s_std**2))/(s_std*sqrt(2*pi))\n    \n    return f'{round(n_pvalue,1)}%'\n```\n\n\n```python\ntall_pvalue(150)\n```\n\n\n\n\n    '2.7%'\n\n\n", "meta": {"hexsha": "78072e3bc52b0008a4c48522282713cf12b5ea09", "size": 28227, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "09-2. Python ch.91 ~ Q. ~204 (200522).ipynb", "max_stars_repo_name": "Adrian123K/python_class", "max_stars_repo_head_hexsha": "11fb52d3ca3a84ee582ec9da68b463fac0f485fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "09-2. Python ch.91 ~ Q. ~204 (200522).ipynb", "max_issues_repo_name": "Adrian123K/python_class", "max_issues_repo_head_hexsha": "11fb52d3ca3a84ee582ec9da68b463fac0f485fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "09-2. Python ch.91 ~ Q. ~204 (200522).ipynb", "max_forks_repo_name": "Adrian123K/python_class", "max_forks_repo_head_hexsha": "11fb52d3ca3a84ee582ec9da68b463fac0f485fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7857142857, "max_line_length": 130, "alphanum_fraction": 0.4561589967, "converted": true, "num_tokens": 5870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.15203224546424318, "lm_q1q2_score": 0.046224138559873784}}
{"text": "```python\n%pylab inline\n```\n\n    Populating the interactive namespace from numpy and matplotlib\n\n\n## Notebook magic\n\n\n```python\nfrom IPython.core.magic import Magics, magics_class, line_cell_magic\nfrom IPython.core.magic import cell_magic, register_cell_magic, register_line_magic\nfrom IPython.core.magic_arguments import argument, magic_arguments, parse_argstring\nimport subprocess\nimport os\n```\n\n\n```python\n@magics_class\nclass PyboardMagic(Magics):\n    @cell_magic\n    @magic_arguments()\n    @argument('-skip')\n    @argument('-unix')\n    @argument('-pyboard')\n    @argument('-file')\n    @argument('-data')\n    @argument('-time')\n    @argument('-memory')\n    def micropython(self, line='', cell=None):\n        args = parse_argstring(self.micropython, line)\n        if args.skip: # doesn't care about the cell's content\n            print('skipped execution')\n            return None # do not parse the rest\n        if args.unix: # tests the code on the unix port. Note that this works on unix only\n            with open('/dev/shm/micropython.py', 'w') as fout:\n                fout.write(cell)\n            proc = subprocess.Popen([\"../../micropython/ports/unix/micropython\", \"/dev/shm/micropython.py\"], \n                                    stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n            print(proc.stdout.read().decode(\"utf-8\"))\n            print(proc.stderr.read().decode(\"utf-8\"))\n            return None\n        if args.file: # can be used to copy the cell content onto the pyboard's flash\n            spaces = \"    \"\n            try:\n                with open(args.file, 'w') as fout:\n                    fout.write(cell.replace('\\t', spaces))\n                    printf('written cell to {}'.format(args.file))\n            except:\n                print('Failed to write to disc!')\n            return None # do not parse the rest\n        if args.data: # can be used to load data from the pyboard directly into kernel space\n            message = pyb.exec(cell)\n            if len(message) == 0:\n                print('pyboard >>>')\n            else:\n                print(message.decode('utf-8'))\n                # register new variable in user namespace\n                self.shell.user_ns[args.data] = string_to_matrix(message.decode(\"utf-8\"))\n        \n        if args.time: # measures the time of executions\n            pyb.exec('import utime')\n            message = pyb.exec('t = utime.ticks_us()\\n' + cell + '\\ndelta = utime.ticks_diff(utime.ticks_us(), t)' + \n                               \"\\nprint('execution time: {:d} us'.format(delta))\")\n            print(message.decode('utf-8'))\n        \n        if args.memory: # prints out memory information \n            message = pyb.exec('from micropython import mem_info\\nprint(mem_info())\\n')\n            print(\"memory before execution:\\n========================\\n\", message.decode('utf-8'))\n            message = pyb.exec(cell)\n            print(\">>> \", message.decode('utf-8'))\n            message = pyb.exec('print(mem_info())')\n            print(\"memory after execution:\\n========================\\n\", message.decode('utf-8'))\n\n        if args.pyboard:\n            message = pyb.exec(cell)\n            print(message.decode('utf-8'))\n\nip = get_ipython()\nip.register_magics(PyboardMagic)\n```\n\n## pyboard\n\n\n```python\nimport pyboard\npyb = pyboard.Pyboard('/dev/ttyACM0')\npyb.enter_raw_repl()\n```\n\n\n```python\npyb.exit_raw_repl()\npyb.close()\n```\n\n\n```python\n%%micropython -pyboard 1\n\nimport utime\nimport ulab as np\n\ndef timeit(n=1000):\n    def wrapper(f, *args, **kwargs):\n        func_name = str(f).split(' ')[1]\n        def new_func(*args, **kwargs):\n            run_times = np.zeros(n, dtype=np.uint16)\n            for i in range(n):\n                t = utime.ticks_us()\n                result = f(*args, **kwargs)\n                run_times[i] = utime.ticks_diff(utime.ticks_us(), t)\n            print('{}() execution times based on {} cycles'.format(func_name, n, (delta2-delta1)/n))\n            print('\\tbest: %d us'%np.min(run_times))\n            print('\\tworst: %d us'%np.max(run_times))\n            print('\\taverage: %d us'%np.mean(run_times))\n            print('\\tdeviation: +/-%.3f us'%np.std(run_times))            \n            return result\n        return new_func\n    return wrapper\n\ndef timeit(f, *args, **kwargs):\n    func_name = str(f).split(' ')[1]\n    def new_func(*args, **kwargs):\n        t = utime.ticks_us()\n        result = f(*args, **kwargs)\n        print('execution time: ', utime.ticks_diff(utime.ticks_us(), t), ' us')\n        return result\n    return new_func\n```\n\n    \n\n\n__END_OF_DEFS__\n\n# scipy.linalg\n\n`scipy`'s `linalg` module contains two functions, `solve_triangular`, and `cho_solve`. The functions can be called by prepending them by `scipy.linalg.`.\n\n1. [scipy.linalg.solve_cho](#cho_solve)\n2. [scipy.linalg.solve_triangular](#solve_triangular)\n\n## cho_solve\n\n`scipy`: https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.cho_solve.html\n\nSolve the linear equations \n\n\n\\begin{equation}\n\\mathbf{A}\\cdot\\mathbf{x} = \\mathbf{b}\n\\end{equation}\n\ngiven the Cholesky factorization of $\\mathbf{A}$. As opposed to `scipy`, the function simply takes the Cholesky-factorised matrix, $\\mathbf{A}$, and $\\mathbf{b}$ as inputs.\n\n\n```python\n%%micropython -unix 1\n\nfrom ulab import numpy as np\nfrom ulab import scipy as spy\n\nA = np.array([[3, 0, 0, 0], [2, 1, 0, 0], [1, 0, 1, 0], [1, 2, 1, 8]])\nb = np.array([4, 2, 4, 2])\n\nprint(spy.linalg.cho_solve(A, b))\n```\n\n    array([-0.01388888888888906, -0.6458333333333331, 2.677083333333333, -0.01041666666666667], dtype=float64)\n    \n    \n\n\n## solve_triangular\n\n`scipy`: https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.solve_triangular.html \n\nSolve the linear equation \n\n\\begin{equation}\n\\mathbf{a}\\cdot\\mathbf{x} = \\mathbf{b}\n\\end{equation}\n\nwith the assumption that $\\mathbf{a}$ is a triangular matrix. The two position arguments are $\\mathbf{a}$, and $\\mathbf{b}$, and the optional keyword argument is `lower` with a default value of `False`. `lower` determines, whether data are taken from the lower, or upper triangle of $\\mathbf{a}$. \n\nNote that $\\mathbf{a}$ itself does not have to be a triangular matrix: if it is not, then the values are simply taken to be 0 in the upper or lower triangle, as dictated by `lower`. However, $\\mathbf{a}\\cdot\\mathbf{x}$ will yield $\\mathbf{b}$ only, when $\\mathbf{a}$ is triangular. You should keep this in mind, when trying to establish the validity of the solution by back substitution.\n\n\n```python\n%%micropython -unix 1\n\nfrom ulab import numpy as np\nfrom ulab import scipy as spy\n\na = np.array([[3, 0, 0, 0], [2, 1, 0, 0], [1, 0, 1, 0], [1, 2, 1, 8]])\nb = np.array([4, 2, 4, 2])\n\nprint('a:\\n')\nprint(a)\nprint('\\nb: ', b)\n\nx = spy.linalg.solve_triangular(a, b, lower=True)\n\nprint('='*20)\nprint('x: ', x)\nprint('\\ndot(a, x): ', np.dot(a, x))\n```\n\n    a:\n    \n    array([[3.0, 0.0, 0.0, 0.0],\n           [2.0, 1.0, 0.0, 0.0],\n           [1.0, 0.0, 1.0, 0.0],\n           [1.0, 2.0, 1.0, 8.0]], dtype=float64)\n    \n    b:  array([4.0, 2.0, 4.0, 2.0], dtype=float64)\n    ====================\n    x:  array([1.333333333333333, -0.6666666666666665, 2.666666666666667, -0.08333333333333337], dtype=float64)\n    \n    dot(a, x):  array([4.0, 2.0, 4.0, 2.0], dtype=float64)\n    \n    \n\n\nWith get the same solution, $\\mathbf{x}$, with the following matrix, but the dot product of $\\mathbf{a}$, and $\\mathbf{x}$ is no longer $\\mathbf{b}$:\n\n\n```python\n%%micropython -unix 1\n\nfrom ulab import numpy as np\nfrom ulab import scipy as spy\n\na = np.array([[3, 2, 1, 0], [2, 1, 0, 1], [1, 0, 1, 4], [1, 2, 1, 8]])\nb = np.array([4, 2, 4, 2])\n\nprint('a:\\n')\nprint(a)\nprint('\\nb: ', b)\n\nx = spy.linalg.solve_triangular(a, b, lower=True)\n\nprint('='*20)\nprint('x: ', x)\nprint('\\ndot(a, x): ', np.dot(a, x))\n```\n\n    a:\n    \n    array([[3.0, 2.0, 1.0, 0.0],\n           [2.0, 1.0, 0.0, 1.0],\n           [1.0, 0.0, 1.0, 4.0],\n           [1.0, 2.0, 1.0, 8.0]], dtype=float64)\n    \n    b:  array([4.0, 2.0, 4.0, 2.0], dtype=float64)\n    ====================\n    x:  array([1.333333333333333, -0.6666666666666665, 2.666666666666667, -0.08333333333333337], dtype=float64)\n    \n    dot(a, x):  array([5.333333333333334, 1.916666666666666, 3.666666666666667, 2.0], dtype=float64)\n    \n    \n\n", "meta": {"hexsha": "6adaa11b691d5ff288087bdef8c1124090bfc105", "size": 14473, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/scipy-linalg.ipynb", "max_stars_repo_name": "oojBuffalo/micropython-ulab", "max_stars_repo_head_hexsha": "4407bec88c3a7585ffbdfdd98e72bed12329ff3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 232, "max_stars_repo_stars_event_min_datetime": "2019-10-30T02:47:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:35:42.000Z", "max_issues_repo_path": "docs/scipy-linalg.ipynb", "max_issues_repo_name": "oojBuffalo/micropython-ulab", "max_issues_repo_head_hexsha": "4407bec88c3a7585ffbdfdd98e72bed12329ff3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 325, "max_issues_repo_issues_event_min_datetime": "2019-10-25T00:27:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T19:47:45.000Z", "max_forks_repo_path": "docs/scipy-linalg.ipynb", "max_forks_repo_name": "oojBuffalo/micropython-ulab", "max_forks_repo_head_hexsha": "4407bec88c3a7585ffbdfdd98e72bed12329ff3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 73, "max_forks_repo_forks_event_min_datetime": "2019-11-04T19:31:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T03:11:41.000Z", "avg_line_length": 30.5337552743, "max_line_length": 399, "alphanum_fraction": 0.5015546189, "converted": true, "num_tokens": 2473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771374883919, "lm_q2_score": 0.136608397056381, "lm_q1q2_score": 0.04618417583369895}}
{"text": "[](https://colab.research.google.com/github/QuCAI-Lab/qhack2022-hackeinberg-project/blob/dev/presentation.ipynb)\n[](https://github.com/QuCAI-Lab/qhack2022-hackeinberg-project/blob/dev/LICENSE.md)\n\n[](https://github.com/QuCAI-Lab/qhack2022-hackeinberg-project/graphs/commit-activity)\n[](https://github.com/QuCAI-Lab/qhack2022-hackeinberg-project/actions/workflows/tests.yml)\n[](https://github.com/QuCAI-Lab/qhack2022-hackeinberg-project/releases)\n[](https://github.com/QuCAI-Lab/qhack2022-hackeinberg-project/commits)\n[](https://github.com/QuCAI-Lab/qhack2022-hackeinberg-project/fork)\n\n<div align=\"center\">\n  <h1> <a href=\"https://qhack.ai/events#hackathon-challenges\"> QHack2022 Open Hackaton </a> - Hackeinberg Team Project </h1>\n  <h2> Extending Adaptive Methods for Finding an Optimal Circuit Ansatze in VQE Optimization</h2>\n</div>\n<br>\n\n<div align=\"center\">\n  <b>Developer: <a target=\"_blank\" href=\"https://github.com/camponogaraviera\">\u00b9Lucas Camponogara Viera</a></b>\n  <br>\n  <b>Auditor: <a target=\"_blank\" href=\"https://github.com/zemarchezi\">\u00b2Jos\u00e9 Paulo Marchezi</a></b>\n<br>\n<b><a target=\"_blank\" href=\"https://en.ntnu.edu.tw/\">\u00b9National Taiwan Normal University - NTNU, Taipei, Taiwan</a></b>.\n<br>\n<b><a target=\"_blank\" href=\"https://www.gov.br/inpe/pt-br\">\u00b2National Institute for Space Research - INPE, S\u00e3o Jos\u00e9 dos Campos, SP, Brazil.</a></b>.\n<br>\n<b><a target=\"_blank\" href=\"http://english.nssc.cas.cn/\">\u00b2State  Key  Laboratory  of  Space  Weather,  National  Space  Science  Center, Chinese  Academy  of  Sciences, China</a></b>.\n</div>\n\n<br>\n\n[comment]: <> ()\n<table class=\"tfo-notebook-buttons\" align=\"head\">\n  <td>\n    <a target=\"_blank\" href=\"https://github.com/QuCAI-Lab/qhack2022-hackeinberg-project\"></a>\n  </td>\n</table>\n\n<center><a href=\"https://github.com/QuCAI-Lab/qhack2022-hackeinberg-project\"><b>View source on GitHub.</b></a></center>\n\n    \n\n\n\n```\n%autosave 30\n```\n\n\n\n    Autosaving every 30 seconds\n\n\n---\n\nIn this jupyter notebook, the author describe a step-by-step implementation of a hybrid quantum-classical optimization approach to find the optimal gate arrangement of a problem-specific ansatze (quantum circuit). Here is demonstrated the Variational Quantum Eigensolver (VQE) algorithm approach to find the ground state of the LiH molecule (the minimum eigenvalue of its Hamiltonian) considering only single and double excitations.\n\n---\n\n# &nbsp; <a href=\"#\"></a> **Project Description**\n\n\n## Background and Motivation\n\nMost widely considered hardware-efficient and Chemistry-inspired ansatze, although generic, suffer from either barren plateaus [[1](https://www.nature.com/articles/s41467-018-07090-4)] or inconsistency under low-order trotterization steps [[2](https://pubs.acs.org/doi/abs/10.1021/acs.jctc.9b01083)], respectively. To circumvent this drawback, different algorithms for optimization of variational quantum circuits (VQA), the so-called adaptive circuits, have already been proposed in the literature [[4](https://pennylane.ai/qml/demos/tutorial_adaptive_circuits.html)]. One example is the Adaptive Derivative-Assembled Pseudo-Trotter ansatz Variational Quantum Eigensolver (ADAPT-VQE) [[3](https://www.nature.com/articles/s41467-019-10988-2)]. In a nutshell, the ADAPT-VQE approach is to grow the ansatz by adding fermionic operators one-at-a-time so to preserve the amount of correlation energy. This approach can also be regarded as a particular optimization procedure for Full Configuration Interaction (FCI) VQE.\n\nIn this work, we combine some of the existing methods applied to the hybrid quantum-classical VQE [[5](https://doi.org/10.1038/ncomms5213)] algorithm for the particular case of the ground state of the LiH molecule. We prioritize the minimization of the circuit depth (the longest sequence of gates acting on a qubit register) at the cost of increasing parameter count (the number of parameters to be optimized) given the tradeoff between difficulty in implementation on NISQ devices vs difficulty in optimization on classical computers, respectively. The baseline approach took into consideration the following features for a good ansatz:\n\n1. Coherence friendly: the circuit must be shallow, i.e, have a small number of layers in order to be computed during a time window smaller than the decoherence time.\n2. Hardware friendly (qubit routing): gate coupling allowed only between nearest-neighbor qubits to avoid SWAP gates during qubit routing (mapping from the circuit diagram to a hardware topology).\n3. Small number of hyperparameters: we seek the minimum amount of angles to be optimized in order to avoid classical optimization overhead (when classical computation becomes too expensive).\n\nIn the early stages of the project, the goal is to find a quasi-optimal ansatz by restricting the VQE simulation to single and double order excitations only. For the future, the plan is to frame the problem as a deep reinforcement learning approach to learn an optimal circuit ansatz considering higher excitation orders, and perform the simulation on a real quantum hardware unsing the [Qamuy SDK](https://qamuy.qunasys.com/docs/en/).\n\n\n\n\n## Algorithm outline\n\n1. With the spin orbitals of the molecule of interest, compute its second-quantized electronic Hamiltonian in the STO-3G basis.\n\n2. Map the fermionic Hamiltonian given in terms of its fermionic operators into a spin qubit-equivalent Hamiltonian using either Bravyi-Kitaev or the inverted Jordan\u2013Wigner transformation. This is required to perform gate-based quantum computation. The Hamiltonian will be used to compute the cost function that evaluates the expectation value of the Hamiltonian, while the number of qubits is required to obtain the electronic excitations and to set up the quantum circuit.\n\n3. Obtain the single and double electronic excitations by acting with the electron annihilation and creation operators on the Hartree-Fock reference state.\n\n4. Define a set with all unique single and double excitations to create the correspondent SO(2) unitary qubit gates (the particular Givens rotations) to each electronic excitation operator in order to build a quantum circuit ansatz of particle-conserving unitary qubit gates.\n\n5. Initialize the qubit state to a reference Hartree-Fock state.\n\n6. Initialize the parameter values of each gate in the ansatz to zero, i.e, initialize the ansatz to the identity matrix in order to compute the gradients with respect to the Hartree-Fock state.\n\n7. Prepare the trial estate with the current ansatz.\n\n8. Define the cost function as the expectation value of the qubit Hamiltonian. Define an optimizer (e.g. SGD).\n\n9. Use the parameter shift rule to compute the gradient of the cost function with respect to its tunable parameters.\n\n10. Identify the operators (gates) with the maximum and minimum gradient in magnitude. Add to the ansatz the gate whose gradient is at maximum magnitude. Remove from the set the gate with the gradient at minimum magnitude if it is smaller than a predefined threshold. Here, we add one gate per iteration while deleting a single gate if it satisfies the above condition.\n\n11.\u00a0 Use the optimizer to update the circuit parameters according to a VQE experiment.\n\n12. Define convergence as the difference between the ground truth and the expected value for the current optimization step. If the convergence tolerance is less than or equal to a pre-defined threshold $\\epsilon$, exit the optimization loop and evaluate the cost metric of the final optimized circuit by measuring its circuit depth.\n\n13. Repeat step 9.\n\n# &nbsp; <a href=\"https://creativecommons.org/licenses/by/4.0/\"></a> License\n\n\n```\n#@title Copyright 2022.\n# This code is part of qhack2022-hackeinberg-project.\n#\n# (C) Copyright NTNU QuCAI-Lab, 2022.\n#\n# This code is licensed under the Creative Commons Zero v1.0 Universal License. \n# You may obtain a copy of the License at https://github.com/QuCAI-Lab/qhack2022-hackeinberg-project/blob/dev/LICENSE.md.\n```\n\n# &nbsp; <a href=\"https://cloud.google.com/tpu/\"></a> Colab's memory card \n\n\"Executing a code cell within a GPU or TPU runtime does not mean that GPU or TPU is being used.\" \n\n[For more information about GPU usage on Colab](https://research.google.com/colaboratory/faq.html#gpu-availability).\n\n## CPU\n\n1. Click on the tab `Runtime -> Change runtime type`.\n1. Click on `Hardware accelerator`.\n1. Select `None` from the drop-down menu and click `Save`.\n1. Click `Connect` in the upper right corner and select `Connect to hosted runtime` (if not automatically).\n\n\n```\n!free -h    # Show CPU Memory.\n              # 'free' = wasted memory (not being used).\n              # 'available' = memory for allocation.\n              # 'buff/cache' used memory for cache (Data has been read) and buffer (data is being written).\n              # 'free' + 'buff/cache' = 'available'.\n\nprint('')\n!lscpu      # Show CPU Architecture.\n```\n\n                  total        used        free      shared  buff/cache   available\n    Mem:            12G        834M         10G        1.1M        1.8G         11G\n    Swap:            0B          0B          0B\n    \n    Architecture:        x86_64\n    CPU op-mode(s):      32-bit, 64-bit\n    Byte Order:          Little Endian\n    CPU(s):              2\n    On-line CPU(s) list: 0,1\n    Thread(s) per core:  2\n    Core(s) per socket:  1\n    Socket(s):           1\n    NUMA node(s):        1\n    Vendor ID:           GenuineIntel\n    CPU family:          6\n    Model:               79\n    Model name:          Intel(R) Xeon(R) CPU @ 2.20GHz\n    Stepping:            0\n    CPU MHz:             2199.998\n    BogoMIPS:            4399.99\n    Hypervisor vendor:   KVM\n    Virtualization type: full\n    L1d cache:           32K\n    L1i cache:           32K\n    L2 cache:            256K\n    L3 cache:            56320K\n    NUMA node0 CPU(s):   0,1\n    Flags:               fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm rdseed adx smap xsaveopt arat md_clear arch_capabilities\n\n\n## GPU\n\n1. Click on the tab `Runtime -> Change runtime type`.\n1. Click on `Hardware accelerator`.\n1. Select `GPU` from the drop-down menu and click `Save`.\n1. Click `Connect` in the upper right corner and select `Connect to hosted runtime` (if not automatically).\n\n\n```\n!nvidia-smi #Show GPU Card\n```\n\n    NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver. Make sure that the latest NVIDIA driver is installed and running.\n    \n\n\n# &nbsp; <a href=\"https://colab.research.google.com/\"></a> Pip Install\n\n* **Run this cell only if you are running this Jupyter notebook outside the [hackeinberg_project environment](https://github.com/QuCAI-Lab/qhack2022-hackeinberg-project/blob/dev/environment.yml).**\n\nInstalling `Qamuy`, `PennyLane`, `pennylane-qchem`, `pyscf`, `openfermionpyscf`, `matplotlib`, and `pylatexenc`.\n\n\n\n```\n'''\n# Installing a non-default library\n\n!python3 -m pip install <library_name>\n\n# Alternative \n\n!apt-get -qq install -y <library_name> && python3 -m pip install -U <library_name> \n\n# Upgrading an installed library\n\n!python3 -m pip install -U --upgrade <library_name> \n'''\n```\n\n\n\n\n    '\\n# Installing a non-default library\\n\\n!python3 -m pip install <library_name>\\n\\n# Alternative \\n\\n!apt-get -qq install -y <library_name> && python3 -m pip install -U <library_name> \\n\\n# Upgrading an installed library\\n\\n!python3 -m pip install -U --upgrade <library_name> \\n'\n\n\n\n\n```\ntry:\n  import pkg_resources\n  pkg_resources.require(\"pip>=22.0.4\")\n  import pip\n  print(pip.__version__)\nexcept:\n  import subprocess, sys\n  cmd = \"apt install python3-pip && python3 -m pip install --upgrade pip\"\n  process = subprocess.Popen(cmd,shell=True,bufsize=1,stdout=subprocess.PIPE,\n                             stderr=subprocess.STDOUT,encoding='utf-8',errors='replace') \n  while True:\n    out = process.stdout.readline()\n    if out == '' and process.poll() is not None:\n      break\n    if out:\n      print(out.strip(), flush=False)\n      sys.stdout.flush()\n  raise\n```\n\n    22.0.4\n\n\n\n```\n#!python3 -m pip install pip==version_number # To downgrade pip.\n!pip --version\n```\n\n    pip 22.0.4 from /usr/local/lib/python3.7/dist-packages/pip (python 3.7)\n\n\n**Qamuy:**\n\n\n```\n#!python3 -m pip install qamuy-client --extra-index-url https://download.qamuy.qunasys.com/simple/\n```\n\n**PennyLane:**\n\n\n```\n!python3 -m pip install PennyLane==0.21.0\n```\n\n    Requirement already satisfied: PennyLane==0.21.0 in /usr/local/lib/python3.7/dist-packages (0.21.0)\n    Requirement already satisfied: autograd in /usr/local/lib/python3.7/dist-packages (from PennyLane==0.21.0) (1.3)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from PennyLane==0.21.0) (1.21.5)\n    Requirement already satisfied: autoray in /usr/local/lib/python3.7/dist-packages (from PennyLane==0.21.0) (0.2.5)\n    Requirement already satisfied: pennylane-lightning>=0.21 in /usr/local/lib/python3.7/dist-packages (from PennyLane==0.21.0) (0.22.1)\n    Requirement already satisfied: cachetools in /usr/local/lib/python3.7/dist-packages (from PennyLane==0.21.0) (4.2.4)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from PennyLane==0.21.0) (1.4.1)\n    Requirement already satisfied: networkx in /usr/local/lib/python3.7/dist-packages (from PennyLane==0.21.0) (2.6.3)\n    Requirement already satisfied: appdirs in /usr/local/lib/python3.7/dist-packages (from PennyLane==0.21.0) (1.4.4)\n    Requirement already satisfied: semantic-version==2.6 in /usr/local/lib/python3.7/dist-packages (from PennyLane==0.21.0) (2.6.0)\n    Requirement already satisfied: retworkx in /usr/local/lib/python3.7/dist-packages (from PennyLane==0.21.0) (0.11.0)\n    Requirement already satisfied: toml in /usr/local/lib/python3.7/dist-packages (from PennyLane==0.21.0) (0.10.2)\n    Requirement already satisfied: ninja in /usr/local/lib/python3.7/dist-packages (from pennylane-lightning>=0.21->PennyLane==0.21.0) (1.10.2.3)\n    Requirement already satisfied: future>=0.15.2 in /usr/local/lib/python3.7/dist-packages (from autograd->PennyLane==0.21.0) (0.16.0)\n    \u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n    \u001b[0m\n\n**pennylane-qchem:**\n\n\n```\n!python3 -m pip install pennylane-qchem==0.21.0\n```\n\n    Requirement already satisfied: pennylane-qchem==0.21.0 in /usr/local/lib/python3.7/dist-packages (0.21.0)\n    Requirement already satisfied: pyscf<2.0,>=1.7.2 in /usr/local/lib/python3.7/dist-packages (from pennylane-qchem==0.21.0) (1.7.6.post1)\n    Requirement already satisfied: openfermionpsi4>=0.5 in /usr/local/lib/python3.7/dist-packages (from pennylane-qchem==0.21.0) (0.5)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from pennylane-qchem==0.21.0) (1.4.1)\n    Requirement already satisfied: openfermionpyscf>=0.5 in /usr/local/lib/python3.7/dist-packages (from pennylane-qchem==0.21.0) (0.5)\n    Requirement already satisfied: openfermion>=1.0 in /usr/local/lib/python3.7/dist-packages (from pennylane-qchem==0.21.0) (1.3.0)\n    Requirement already satisfied: pennylane>=0.13 in /usr/local/lib/python3.7/dist-packages (from pennylane-qchem==0.21.0) (0.21.0)\n    Requirement already satisfied: h5py<=3.2.1 in /usr/local/lib/python3.7/dist-packages (from pennylane-qchem==0.21.0) (3.1.0)\n    Requirement already satisfied: numpy>=1.14.5 in /usr/local/lib/python3.7/dist-packages (from h5py<=3.2.1->pennylane-qchem==0.21.0) (1.21.5)\n    Requirement already satisfied: cached-property in /usr/local/lib/python3.7/dist-packages (from h5py<=3.2.1->pennylane-qchem==0.21.0) (1.5.2)\n    Requirement already satisfied: networkx in /usr/local/lib/python3.7/dist-packages (from openfermion>=1.0->pennylane-qchem==0.21.0) (2.6.3)\n    Requirement already satisfied: cirq-core>=0.12.0 in /usr/local/lib/python3.7/dist-packages (from openfermion>=1.0->pennylane-qchem==0.21.0) (0.14.0)\n    Requirement already satisfied: cirq-google>=0.12.0 in /usr/local/lib/python3.7/dist-packages (from openfermion>=1.0->pennylane-qchem==0.21.0) (0.14.0)\n    Requirement already satisfied: requests>=2.18 in /usr/local/lib/python3.7/dist-packages (from openfermion>=1.0->pennylane-qchem==0.21.0) (2.23.0)\n    Requirement already satisfied: pubchempy in /usr/local/lib/python3.7/dist-packages (from openfermion>=1.0->pennylane-qchem==0.21.0) (1.0.4)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from openfermion>=1.0->pennylane-qchem==0.21.0) (1.7.1)\n    Requirement already satisfied: deprecation in /usr/local/lib/python3.7/dist-packages (from openfermion>=1.0->pennylane-qchem==0.21.0) (2.1.0)\n    Requirement already satisfied: pytest in /usr/local/lib/python3.7/dist-packages (from openfermionpyscf>=0.5->pennylane-qchem==0.21.0) (3.6.4)\n    Requirement already satisfied: pennylane-lightning>=0.21 in /usr/local/lib/python3.7/dist-packages (from pennylane>=0.13->pennylane-qchem==0.21.0) (0.22.1)\n    Requirement already satisfied: cachetools in /usr/local/lib/python3.7/dist-packages (from pennylane>=0.13->pennylane-qchem==0.21.0) (4.2.4)\n    Requirement already satisfied: semantic-version==2.6 in /usr/local/lib/python3.7/dist-packages (from pennylane>=0.13->pennylane-qchem==0.21.0) (2.6.0)\n    Requirement already satisfied: toml in /usr/local/lib/python3.7/dist-packages (from pennylane>=0.13->pennylane-qchem==0.21.0) (0.10.2)\n    Requirement already satisfied: autoray in /usr/local/lib/python3.7/dist-packages (from pennylane>=0.13->pennylane-qchem==0.21.0) (0.2.5)\n    Requirement already satisfied: retworkx in /usr/local/lib/python3.7/dist-packages (from pennylane>=0.13->pennylane-qchem==0.21.0) (0.11.0)\n    Requirement already satisfied: appdirs in /usr/local/lib/python3.7/dist-packages (from pennylane>=0.13->pennylane-qchem==0.21.0) (1.4.4)\n    Requirement already satisfied: autograd in /usr/local/lib/python3.7/dist-packages (from pennylane>=0.13->pennylane-qchem==0.21.0) (1.3)\n    Requirement already satisfied: duet~=0.2.0 in /usr/local/lib/python3.7/dist-packages (from cirq-core>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (0.2.5)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from cirq-core>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (4.63.0)\n    Requirement already satisfied: backports.cached-property~=1.0.1 in /usr/local/lib/python3.7/dist-packages (from cirq-core>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (1.0.1)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from cirq-core>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (3.10.0.0)\n    Requirement already satisfied: matplotlib~=3.0 in /usr/local/lib/python3.7/dist-packages (from cirq-core>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (3.5.1)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from cirq-core>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (1.3.5)\n    Requirement already satisfied: sortedcontainers~=2.0 in /usr/local/lib/python3.7/dist-packages (from cirq-core>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (2.4.0)\n    Requirement already satisfied: google-api-core[grpc]<2.0.0dev,>=1.14.0 in /usr/local/lib/python3.7/dist-packages (from cirq-google>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (1.26.3)\n    Requirement already satisfied: protobuf>=3.13.0 in /usr/local/lib/python3.7/dist-packages (from cirq-google>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (3.17.3)\n    Requirement already satisfied: ninja in /usr/local/lib/python3.7/dist-packages (from pennylane-lightning>=0.21->pennylane>=0.13->pennylane-qchem==0.21.0) (1.10.2.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.18->openfermion>=1.0->pennylane-qchem==0.21.0) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.18->openfermion>=1.0->pennylane-qchem==0.21.0) (2021.10.8)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests>=2.18->openfermion>=1.0->pennylane-qchem==0.21.0) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.18->openfermion>=1.0->pennylane-qchem==0.21.0) (3.0.4)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->openfermion>=1.0->pennylane-qchem==0.21.0) (1.2.1)\n    Requirement already satisfied: future>=0.15.2 in /usr/local/lib/python3.7/dist-packages (from autograd->pennylane>=0.13->pennylane-qchem==0.21.0) (0.16.0)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from deprecation->openfermion>=1.0->pennylane-qchem==0.21.0) (21.3)\n    Requirement already satisfied: attrs>=17.4.0 in /usr/local/lib/python3.7/dist-packages (from pytest->openfermionpyscf>=0.5->pennylane-qchem==0.21.0) (21.4.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from pytest->openfermionpyscf>=0.5->pennylane-qchem==0.21.0) (57.4.0)\n    Requirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.7/dist-packages (from pytest->openfermionpyscf>=0.5->pennylane-qchem==0.21.0) (1.15.0)\n    Requirement already satisfied: more-itertools>=4.0.0 in /usr/local/lib/python3.7/dist-packages (from pytest->openfermionpyscf>=0.5->pennylane-qchem==0.21.0) (8.12.0)\n    Requirement already satisfied: pluggy<0.8,>=0.5 in /usr/local/lib/python3.7/dist-packages (from pytest->openfermionpyscf>=0.5->pennylane-qchem==0.21.0) (0.7.1)\n    Requirement already satisfied: atomicwrites>=1.0 in /usr/local/lib/python3.7/dist-packages (from pytest->openfermionpyscf>=0.5->pennylane-qchem==0.21.0) (1.4.0)\n    Requirement already satisfied: py>=1.5.0 in /usr/local/lib/python3.7/dist-packages (from pytest->openfermionpyscf>=0.5->pennylane-qchem==0.21.0) (1.11.0)\n    Requirement already satisfied: google-auth<2.0dev,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (1.35.0)\n    Requirement already satisfied: googleapis-common-protos<2.0dev,>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (1.56.0)\n    Requirement already satisfied: pytz in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (2018.9)\n    Requirement already satisfied: grpcio<2.0dev,>=1.29.0 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (1.44.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (1.4.0)\n    Requirement already satisfied: pyparsing>=2.2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (3.0.7)\n    Requirement already satisfied: pillow>=6.2.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (7.1.2)\n    Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (4.32.0)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (0.11.0)\n    Requirement already satisfied: python-dateutil>=2.7 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (2.8.2)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (0.2.8)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (4.8)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google>=0.12.0->openfermion>=1.0->pennylane-qchem==0.21.0) (0.4.8)\n    \u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n    \u001b[0m\n\n**pyscf**:\n\n\n```\n!python3 -m pip install pyscf --user\n```\n\n    Requirement already satisfied: pyscf in /usr/local/lib/python3.7/dist-packages (1.7.6.post1)\n    Requirement already satisfied: numpy!=1.16,!=1.17,>1.8 in /usr/local/lib/python3.7/dist-packages (from pyscf) (1.21.5)\n    Requirement already satisfied: h5py>2.2 in /usr/local/lib/python3.7/dist-packages (from pyscf) (3.1.0)\n    Requirement already satisfied: scipy!=1.5.0,!=1.5.1 in /usr/local/lib/python3.7/dist-packages (from pyscf) (1.4.1)\n    Requirement already satisfied: cached-property in /usr/local/lib/python3.7/dist-packages (from h5py>2.2->pyscf) (1.5.2)\n    \u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n    \u001b[0m\n\n**Open Fermion**:\n\n\n```\n!python3 -m pip install openfermionpyscf==0.5\n```\n\n    Requirement already satisfied: openfermionpyscf==0.5 in /usr/local/lib/python3.7/dist-packages (0.5)\n    Requirement already satisfied: pyscf in /usr/local/lib/python3.7/dist-packages (from openfermionpyscf==0.5) (1.7.6.post1)\n    Requirement already satisfied: pytest in /usr/local/lib/python3.7/dist-packages (from openfermionpyscf==0.5) (3.6.4)\n    Requirement already satisfied: openfermion>=0.5 in /usr/local/lib/python3.7/dist-packages (from openfermionpyscf==0.5) (1.3.0)\n    Requirement already satisfied: requests>=2.18 in /usr/local/lib/python3.7/dist-packages (from openfermion>=0.5->openfermionpyscf==0.5) (2.23.0)\n    Requirement already satisfied: numpy>=1.11.0 in /usr/local/lib/python3.7/dist-packages (from openfermion>=0.5->openfermionpyscf==0.5) (1.21.5)\n    Requirement already satisfied: cirq-google>=0.12.0 in /usr/local/lib/python3.7/dist-packages (from openfermion>=0.5->openfermionpyscf==0.5) (0.14.0)\n    Requirement already satisfied: scipy>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from openfermion>=0.5->openfermionpyscf==0.5) (1.4.1)\n    Requirement already satisfied: deprecation in /usr/local/lib/python3.7/dist-packages (from openfermion>=0.5->openfermionpyscf==0.5) (2.1.0)\n    Requirement already satisfied: h5py>=2.8 in /usr/local/lib/python3.7/dist-packages (from openfermion>=0.5->openfermionpyscf==0.5) (3.1.0)\n    Requirement already satisfied: cirq-core>=0.12.0 in /usr/local/lib/python3.7/dist-packages (from openfermion>=0.5->openfermionpyscf==0.5) (0.14.0)\n    Requirement already satisfied: networkx in /usr/local/lib/python3.7/dist-packages (from openfermion>=0.5->openfermionpyscf==0.5) (2.6.3)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from openfermion>=0.5->openfermionpyscf==0.5) (1.7.1)\n    Requirement already satisfied: pubchempy in /usr/local/lib/python3.7/dist-packages (from openfermion>=0.5->openfermionpyscf==0.5) (1.0.4)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from pytest->openfermionpyscf==0.5) (57.4.0)\n    Requirement already satisfied: attrs>=17.4.0 in /usr/local/lib/python3.7/dist-packages (from pytest->openfermionpyscf==0.5) (21.4.0)\n    Requirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.7/dist-packages (from pytest->openfermionpyscf==0.5) (1.15.0)\n    Requirement already satisfied: atomicwrites>=1.0 in /usr/local/lib/python3.7/dist-packages (from pytest->openfermionpyscf==0.5) (1.4.0)\n    Requirement already satisfied: py>=1.5.0 in /usr/local/lib/python3.7/dist-packages (from pytest->openfermionpyscf==0.5) (1.11.0)\n    Requirement already satisfied: more-itertools>=4.0.0 in /usr/local/lib/python3.7/dist-packages (from pytest->openfermionpyscf==0.5) (8.12.0)\n    Requirement already satisfied: pluggy<0.8,>=0.5 in /usr/local/lib/python3.7/dist-packages (from pytest->openfermionpyscf==0.5) (0.7.1)\n    Requirement already satisfied: duet~=0.2.0 in /usr/local/lib/python3.7/dist-packages (from cirq-core>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (0.2.5)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from cirq-core>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (4.63.0)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from cirq-core>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (3.10.0.0)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from cirq-core>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (1.3.5)\n    Requirement already satisfied: backports.cached-property~=1.0.1 in /usr/local/lib/python3.7/dist-packages (from cirq-core>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (1.0.1)\n    Requirement already satisfied: matplotlib~=3.0 in /usr/local/lib/python3.7/dist-packages (from cirq-core>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (3.5.1)\n    Requirement already satisfied: sortedcontainers~=2.0 in /usr/local/lib/python3.7/dist-packages (from cirq-core>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (2.4.0)\n    Requirement already satisfied: protobuf>=3.13.0 in /usr/local/lib/python3.7/dist-packages (from cirq-google>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (3.17.3)\n    Requirement already satisfied: google-api-core[grpc]<2.0.0dev,>=1.14.0 in /usr/local/lib/python3.7/dist-packages (from cirq-google>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (1.26.3)\n    Requirement already satisfied: cached-property in /usr/local/lib/python3.7/dist-packages (from h5py>=2.8->openfermion>=0.5->openfermionpyscf==0.5) (1.5.2)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.18->openfermion>=0.5->openfermionpyscf==0.5) (3.0.4)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests>=2.18->openfermion>=0.5->openfermionpyscf==0.5) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.18->openfermion>=0.5->openfermionpyscf==0.5) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.18->openfermion>=0.5->openfermionpyscf==0.5) (2021.10.8)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->openfermion>=0.5->openfermionpyscf==0.5) (1.2.1)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from deprecation->openfermion>=0.5->openfermionpyscf==0.5) (21.3)\n    Requirement already satisfied: googleapis-common-protos<2.0dev,>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (1.56.0)\n    Requirement already satisfied: pytz in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (2018.9)\n    Requirement already satisfied: google-auth<2.0dev,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (1.35.0)\n    Requirement already satisfied: grpcio<2.0dev,>=1.29.0 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (1.44.0)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (0.11.0)\n    Requirement already satisfied: pyparsing>=2.2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (3.0.7)\n    Requirement already satisfied: pillow>=6.2.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (7.1.2)\n    Requirement already satisfied: python-dateutil>=2.7 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (2.8.2)\n    Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (4.32.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (1.4.0)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (4.8)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (0.2.8)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (4.2.4)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google>=0.12.0->openfermion>=0.5->openfermionpyscf==0.5) (0.4.8)\n    \u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n    \u001b[0m\n\n**Native numpy:**\n\nNote: `This notebook uses the Pennylane wrapped NumPy instead of the native one.`\n\n\n```\n#!python3 -m pip install numpy==1.20.3\n```\n\n**Matplotlib:**\n\nNote: `Matplotlib is already included in Google Colab.`\n\n\n```\n# !python3 -m pip install -U matplotlib==3.5.1\n```\n\n**pylatexenc**:\n\n\n```\n!python3 -m pip install pylatexenc\n```\n\n    Requirement already satisfied: pylatexenc in /usr/local/lib/python3.7/dist-packages (2.10)\n    \u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n    \u001b[0m\n\n# &nbsp; <a href=\"#\"></a> Importing dependencies\n\nAlternatively, you may resort to the `requirements.txt` file from the official [GitHub repo](https://github.com/QuCAI-Lab/qhack2022-hackeinberg-project/blob/dev/requirements.txt).\n\n\n\n```\n'''\nIf using Google Colab, one needs to restart Colab Runtime after the previous package installation.\n'''\n\nimport sys, subprocess\nimport IPython\nimport time\n\n#import qamuy.chemistry as qy\n#from qamuy.client import Client\n\nimport pennylane as qml\nfrom pennylane import qchem\nfrom pennylane import numpy as np\nimport matplotlib\n\ntry:\n  import pkg_resources\n  pkg_resources.require(\"watermark>=2.3.0\") # Force watermark version.\n  import watermark\n  print(watermark.__version__)\nexcept:\n  import subprocess, sys\n  if \"google.colab\" in sys.modules:\n    cmd = \"python3 -m pip install --upgrade watermark\" # Upgrade watermak.\n\n    process = subprocess.Popen(cmd,shell=True,bufsize=1,stdout=subprocess.PIPE, \\\n                              stderr=subprocess.STDOUT,encoding='utf-8',errors='replace') \n    while True: \n      out = process.stdout.readline() # The first line of the file.\n      if out == '' and process.poll() is not None: # Run the loop until condition is True.\n        break \n      if out:\n        print(out.strip(), flush=False) # Removes leading and trailing empty spaces. \n        sys.stdout.flush()\n    raise # To raise the import error. Upgrade will be successful regardless.\n```\n\n    2.3.0\n\n\n\n```\n# If you get hit by the error \"No module named watermark\", run this cell twice!\n\n%load_ext watermark\n%watermark -a 'Lucas Camponogara Viera' -gu 'camponogaraviera' -ws 'https://qucai-lab.github.io/' -w -u -d -v -m -iv -r -b\n```\n\n    The watermark extension is already loaded. To reload it, use:\n      %reload_ext watermark\n    Author: Lucas Camponogara Viera\n    \n    Github username: camponogaraviera\n    \n    Website: https://qucai-lab.github.io/\n    \n    Last updated: 2022-04-10\n    \n    Python implementation: CPython\n    Python version       : 3.7.13\n    IPython version      : 5.5.0\n    \n    Compiler    : GCC 7.5.0\n    OS          : Linux\n    Release     : 5.4.144+\n    Machine     : x86_64\n    Processor   : x86_64\n    CPU cores   : 2\n    Architecture: 64bit\n    \n    Git repo: \n    \n    Git branch: \n    \n    watermark      : 2.3.0\n    sys            : 3.7.13 (default, Mar 16 2022, 17:37:17) \n    [GCC 7.5.0]\n    pennylane      : 0.21.0\n    pennylane_qchem: 0.21.0\n    IPython        : 5.5.0\n    matplotlib     : 3.5.1\n    \n    Watermark: 2.3.0\n    \n\n\n\n```\n#%watermark?\n```\n\n\n```\nqml.about()\n```\n\n    WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.\n    Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.\n    To avoid this problem you can invoke Python with '-m pip' instead of running pip directly.\n\n\n    Name: PennyLane\n    Version: 0.21.0\n    Summary: PennyLane is a Python quantum machine learning library by Xanadu Inc.\n    Home-page: https://github.com/XanaduAI/pennylane\n    Author: None\n    Author-email: None\n    License: Apache License 2.0\n    Location: /usr/local/lib/python3.7/dist-packages\n    Requires: cachetools, networkx, autoray, numpy, autograd, appdirs, pennylane-lightning, toml, retworkx, semantic-version, scipy\n    Required-by: PennyLane-Qchem, PennyLane-Lightning\n    Platform info:           Linux-5.4.144+-x86_64-with-Ubuntu-18.04-bionic\n    Python version:          3.7.13\n    Numpy version:           1.21.5\n    Scipy version:           1.4.1\n    Installed devices:\n    - default.gaussian (PennyLane-0.21.0)\n    - default.mixed (PennyLane-0.21.0)\n    - default.qubit (PennyLane-0.21.0)\n    - default.qubit.autograd (PennyLane-0.21.0)\n    - default.qubit.jax (PennyLane-0.21.0)\n    - default.qubit.tf (PennyLane-0.21.0)\n    - default.qubit.torch (PennyLane-0.21.0)\n    - lightning.qubit (PennyLane-Lightning-0.22.1)\n\n\n\n```\nprint(IPython.sys_info())\n```\n\n    {'commit_hash': 'b467d487e',\n     'commit_source': 'installation',\n     'default_encoding': 'UTF-8',\n     'ipython_path': '/usr/local/lib/python3.7/dist-packages/IPython',\n     'ipython_version': '5.5.0',\n     'os_name': 'posix',\n     'platform': 'Linux-5.4.144+-x86_64-with-Ubuntu-18.04-bionic',\n     'sys_executable': '/usr/bin/python3',\n     'sys_platform': 'linux',\n     'sys_version': '3.7.13 (default, Mar 16 2022, 17:37:17) \\n[GCC 7.5.0]'}\n\n\n# &nbsp; <a href=\"#\"></a> Implementation\n\n**Definitions:**\n\n\n\n- symbols: a list of strings labeling the atoms of the molecule.\n- geometry: a 1D numpy tensor defining the orbital coordinates of the molecule.\n- H: the molecular Hamiltonian of the system in the qubit representation.\n- qubits: the number of qubits (int).\n- electrons: the number of active electrons for simulation (int).\n- singles: a list of 8 elements where each element is another list with 2 indices of the spin orbitals.\n- doubles: a list of 16 elements where each element is another list with 4 indices of the spin orbitals.\n- sets: a list containing the total spin orbital indices used to build the Givens rotations a.k.a particle-preserving operators (qubit gates).\n- HF:  a numpy.ndarray of shape ((10,) representing the Hartree-Fock state vector.\n- params: a numpy tensor containing the angles to be optimized.\n- energy: a list containing the optimized expected values of the Hamiltonian.\n- opt: the optimizer (e.g., SGD, Adam, Adagrad, etc.).\n- dev: the PennyLane Python module defining the simulator type.\n- cost(): a function that returns the expectation value of the Hamiltonian according to $\\langle \\psi_{HF}|U^{\\dagger}HU|\\psi_{HF}\\rangle$.\n- ansatz(): a function defining the quantum circuit and parametrized gates to be optimized.\n\n- grads: a <class 'numpy.ndarray'> of shape sets.shape containing the gradient of the cost function w.r.t the angle of each gate.\n\n\n\n\n## <a href=\"https://pennylane.ai/\"></a> Pennylane\n\n**Algorithm**\n\n- Steps 1 and 2 are implemented with the qchem.molecular_hamiltonian() function that returns both the fermionic-to-qubit transformed Hamiltonian and the number of qubits.\n\n- Step 3 is implemented using the qchem.excitations() function.\n\n- Step 4 is implemented with the SingleExcitation() and DoubleExcitation() classes, respectively, by passing the return of the qchem.excitations() function, i.e, the lists with the indices of the spin orbitals.\n\n- Step 5 is implemented with the qml.BasisState class provided the HF state is obtained with the function qchem.hf_state function.\n\n- Step 6 is a simple numpy tensor.\n\n- At step 8, the cost function can be implemented either with the built-in ExpvalCost() class or as a custom function returning the expectation value of the circuit using the expval() class. The primary optimizer of choice is SGD defined by the GradientDescentOptimizer(stepsize=float) class.\n\n- Step 9 is implemented with the grad() class. \n\n- Step 11 is computed using the GradientDescentOptimizer.step() method.\n\n### The algorithm as described in the outline\n\nBy using all gates available in the initial ansatz, we see the presence of [Barren Plateaus](https://www.tensorflow.org/quantum/tutorials/barren_plateaus) (gradients that vanish exponentially with increasing number of qubits). Barren Plateaus can appear only by adding a single layer of single-qubit rotation gates, one rotation of a single parameter (all gates with the same angle of rotation) per qubit.\n\n\n```\n#! /usr/bin/python3\n\nimport pennylane as qml\nfrom pennylane import numpy as np\nfrom pennylane import qchem\nimport time\n\ndef penny_simulation(params, H, HF, sets, qubits, conv_tol, threshold):\n  \"\"\"Main function to run the optimization loop.\n\n  Args:\n      - params (tensor): the parameters to be optimized in the ansatz.\n      - H: the molecular Hamiltonian of the system in the qubit representation.\n      - HF (numpy.ndarray): the Hartree-Fock state vector.\n      - sets (list): total spin orbital indices used to build the Givens rotations a.k.a particle-preserving operators (qubit gates).\n      - qubits (int): the number of qubits used to build the circuit.\n      - conv_tol (float): convergence tolerance to stop training.\n      - threshold (float): threshold for the smallest gradient.\n\n  Returns:\n      - energy (list): a list of expected values of each iteration.\n      - sets (list): a list of excitations corresponding to the gates used in the final circuit.\n      - params (list): a list of optimized parameters.\n      - n (int): number of epochs.\n  \"\"\"\n\n  # Step 7\n  def ansatz(params, wires, to_gates):\n    \"\"\"Function that defines the adaptive circuit to be optimized.\"\"\"\n    qml.BasisState(HF, wires=wires) # The reference Hartree-Fock state.\n    for i, elem in enumerate(to_gates):\n      if len(elem) == 4:\n        qml.DoubleExcitation(params[i], wires=elem)\n      else:\n        qml.SingleExcitation(params[i], wires=elem)\n  \n  # Step 8.\n  opt = qml.GradientDescentOptimizer(stepsize=0.4)  \n  dev = qml.device(\"default.qubit\", wires=qubits)\n  cost = qml.ExpvalCost(ansatz, H, dev, optimize=True)\n  circuit_gradient = qml.grad(cost, argnum=0)\n  epochs = 20\n  energy = [cost(params, to_gates=sets)]\n  print(f\"Epoch = 0,  Energy = {energy[-1]:.8f} Ha, t = 0s\")\n  print(\"Number of gates = {}\\n\".format(len(sets)))\n\n  for n in range(epochs):\n    t1 = time.time()\n    grads = circuit_gradient(params,to_gates=sets) # Step 9.\n    \n    maxpos = np.argmax(abs(grads)) # Beginning of Step 10.\n    minpos = np.argmin(abs(grads)) \n    gatemax=sets[maxpos]\n    gatemin=sets[minpos]\n    paramsmax=params[maxpos]\n    if np.amin(abs(grads)) < threshold:\n      sets.remove(gatemin)\n      params=np.delete(params, minpos)\n    sets.append(gatemax)\n    params=np.append(params, paramsmax) # End of step 10.\n\n    params, prev_energy = opt.step_and_cost(cost, params, to_gates=sets) # Step 11.\n    energy.append(cost(params, to_gates=sets))\n    conv = np.abs(-7.8825378193 - prev_energy) # Step 12.\n    t2 = time.time()\n    print(f\"Epoch = {n+1}, Energy = {energy[-1]:.8f} Ha, t = {t2-t1:.2f}s\")\n    print(\"Number of gates = {}\\n\".format(len(sets)))\n    if conv <= conv_tol:\n      break\n\n  return energy, sets, params, n\n\nif __name__ == \"__main__\":\n  symbols = [\"Li\", \"H\"] # Beginning of step 1.\n  geometry = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 2.969280527], dtype=float)\n  H, qubits = qml.qchem.molecular_hamiltonian(symbols, geometry, active_electrons=2, active_orbitals=5) # End of step 2.\n  electrons = 2\n  singles, doubles = qchem.excitations(electrons, qubits) # Step 3.\n  sets = singles+doubles # Step 4.\n  HF = qml.qchem.hf_state(electrons, qubits) # Step 5.\n  params = np.zeros(len(sets), requires_grad=True) # Beginning of step 6.\n  energy, sets, angles, n = penny_simulation(params, H, HF, sets, qubits, conv_tol=1e-04, threshold=1.0e-5) # Beginning of the optimization loop.\n  print(\"Expected ground-state energy: -7.8825378193.\")\n  print(f\"Simulation = {energy[-1]:.8f} Ha\")\n```\n\n    Epoch = 0,  Energy = -7.86266587 Ha, t = 0s\n    Number of gates = 24\n    \n    Epoch = 1, Energy = -7.87363768 Ha, t = 21.97s\n    Number of gates = 24\n    \n    Epoch = 2, Energy = -7.87905425 Ha, t = 20.32s\n    Number of gates = 24\n    \n    Epoch = 3, Energy = -7.88049351 Ha, t = 19.40s\n    Number of gates = 24\n    \n    Epoch = 4, Energy = -7.88141879 Ha, t = 19.17s\n    Number of gates = 24\n    \n    Epoch = 5, Energy = -7.88174212 Ha, t = 19.41s\n    Number of gates = 24\n    \n    Epoch = 6, Energy = -7.88192486 Ha, t = 20.26s\n    Number of gates = 24\n    \n    Epoch = 7, Energy = -7.88201640 Ha, t = 19.97s\n    Number of gates = 24\n    \n    Epoch = 8, Energy = -7.88208517 Ha, t = 19.45s\n    Number of gates = 24\n    \n    Epoch = 9, Energy = -7.88215322 Ha, t = 18.80s\n    Number of gates = 24\n    \n    Epoch = 10, Energy = -7.88221599 Ha, t = 18.57s\n    Number of gates = 24\n    \n    Epoch = 11, Energy = -7.88227532 Ha, t = 17.29s\n    Number of gates = 24\n    \n    Epoch = 12, Energy = -7.88232331 Ha, t = 17.22s\n    Number of gates = 24\n    \n    Epoch = 13, Energy = -7.88236396 Ha, t = 17.49s\n    Number of gates = 24\n    \n    Epoch = 14, Energy = -7.88228489 Ha, t = 17.53s\n    Number of gates = 24\n    \n    Epoch = 15, Energy = -7.88227914 Ha, t = 18.10s\n    Number of gates = 25\n    \n    Epoch = 16, Energy = -7.88237565 Ha, t = 19.68s\n    Number of gates = 26\n    \n    Epoch = 17, Energy = -7.88241752 Ha, t = 19.94s\n    Number of gates = 27\n    \n    Epoch = 18, Energy = -7.88242400 Ha, t = 21.12s\n    Number of gates = 28\n    \n    Epoch = 19, Energy = -7.88230579 Ha, t = 22.18s\n    Number of gates = 29\n    \n    Epoch = 20, Energy = -7.88229159 Ha, t = 23.04s\n    Number of gates = 30\n    \n    Expected ground-state energy: -7.8825378193.\n    Simulation = -7.88229159 Ha\n\n\n\n```\nimport matplotlib.pyplot as plt\n\nE_fci = -7.8825378193\nfig=plt.figure()\nfig.set_figheight(6)\nfig.set_figwidth(10)\nplt.plot(range(n + 2), energy, \"go\", label=r\"$E_\\mathrm{HF}$\", ls=\"dashed\")\nplt.plot(range(n + 2), np.full(n + 2, E_fci), label=r\"$E_\\mathrm{FCI}$\", color=\"red\")\nplt.title('VQE optimization for the LiH Molecule')\nplt.legend(loc='upper right')\nplt.xlabel('Optimization step')\nplt.ylabel('Energy (Hartree)')\nplt.show()\n```\n\n**Final Ansatz Visualization:**\n\n\n```\nconv_tol=1e-04\nprint(\"Expected ground-state energy: -7.8825378193.\")\nprint(f\"Simulation = {energy[-1]:.8f} Ha\")\nprint(f\"Convergence = {conv_tol:.4f} Ha\")\n```\n\n    Expected ground-state energy: -7.8825378193.\n    Simulation = -7.88229159 Ha\n    Convergence = 0.0001 Ha\n\n\n\n```\nangles.shape, len(sets)\n```\n\n\n\n\n    ((30,), 30)\n\n\n\n\n```\ndev = qml.device(\"default.qubit\", wires=qubits)\n@qml.qnode(dev)\ndef ansatz(params, wires, to_gates=sets):\n  \"\"\"Function that defines the circuit to be optimized.\"\"\"\n  qml.BasisState(HF, wires=wires) # Reference Hartree-Fock state.\n  for i, elem in enumerate(to_gates):\n    if len(elem) == 4:\n      qml.DoubleExcitation(angles[i], wires=elem)\n    else:\n      qml.SingleExcitation(angles[i], wires=elem)\n  return qml.expval(H)\n\nfig, ax = qml.draw_mpl(ansatz, decimals=6)(params, wires=qubits)\n```\n\n\n```\nsets\n```\n\n\n\n\n    [[0, 2],\n     [0, 8],\n     [1, 3],\n     [1, 9],\n     [0, 1, 2, 3],\n     [0, 1, 2, 9],\n     [0, 1, 3, 8],\n     [0, 1, 4, 5],\n     [0, 1, 6, 7],\n     [0, 1, 8, 9],\n     [0, 1, 8, 9],\n     [0, 1, 8, 9],\n     [0, 1, 3, 8],\n     [0, 1, 2, 9],\n     [0, 1, 2, 3],\n     [0, 1, 6, 7],\n     [0, 1, 4, 5],\n     [0, 2],\n     [1, 3],\n     [0, 2],\n     [1, 3],\n     [0, 2],\n     [1, 3],\n     [0, 1, 3, 8],\n     [0, 1, 3, 8],\n     [0, 1, 3, 8],\n     [0, 1, 3, 8],\n     [0, 1, 3, 8],\n     [0, 1, 2, 9],\n     [0, 1, 2, 9]]\n\n\n\n### Adding one gate per iteration without deleting gates with vanishing gradients\n\nFrom the performance of the following algorithm, we see that the algorithm described in the outline achieves better results with fewer number of gates and epochs.\n\n\n```\n#! /usr/bin/python3\n\nimport pennylane as qml\nfrom pennylane import numpy as np\nfrom pennylane import qchem\nimport time\n\ndef penny_simulation(params, H, HF, sets, qubits, conv_tol, threshold):\n  \"\"\"Main function to run the optimization loop.\n\n  Args:\n      - params (tensor): the parameters to be optimized in the ansatz.\n      - H: the molecular Hamiltonian of the system in the qubit representation.\n      - HF (numpy.ndarray): the Hartree-Fock state vector.\n      - sets (list): total spin orbital indices used to build the Givens rotations a.k.a particle-preserving operators (qubit gates).\n      - qubits (int): the number of qubits used to build the circuit.\n      - conv_tol (float): convergence tolerance to stop training.\n      - threshold (float): threshold for the smallest gradient.\n\n  Returns:\n      - energy (list): a list of expected values of each iteration.\n      - sets (list): a list of excitations corresponding to the gates used in the final circuit.\n      - params (list): a list of optimized parameters.\n      - n (int): number of epochs.\n  \"\"\"\n\n  def ansatz(params, wires, to_gates):\n    \"\"\"Function that defines the circuit to be optimized.\"\"\"\n    qml.BasisState(HF, wires=wires) # The reference Hartree-Fock state.\n    for i, elem in enumerate(to_gates):\n      if len(elem) == 4:\n        qml.DoubleExcitation(params[i], wires=elem)\n      else:\n        qml.SingleExcitation(params[i], wires=elem)\n  \n  # Step 8.\n  opt = qml.GradientDescentOptimizer(stepsize=0.4)  \n  dev = qml.device(\"default.qubit\", wires=qubits)\n  cost = qml.ExpvalCost(ansatz, H, dev, optimize=True)\n  circuit_gradient = qml.grad(cost, argnum=0)\n  epochs = 20\n  energy = [cost(params, to_gates=sets)]\n  print(f\"Epoch = 0,  Energy = {energy[-1]:.8f} Ha, t = 0s\")\n  print(\"Number of gates = {}\\n\".format(len(sets)))\n\n  for n in range(epochs):\n    t1 = time.time()\n    grads = circuit_gradient(params,to_gates=sets) # Step 9.\n\n    maxpos = np.argmax(grads) # Beginning of Step 10.\n    max=sets[maxpos]\n    sets.append(max)\n    params=np.append(params, 0) # End of step 10.\n    \n    params, prev_energy = opt.step_and_cost(cost, params, to_gates=sets) # Step 11.\n    energy.append(cost(params, to_gates=sets))\n    conv = np.abs(-7.8825378193 - prev_energy) # Step 12.\n    t2 = time.time()\n    print(f\"Epoch = {n+1}, Energy = {energy[-1]:.8f} Ha, t = {t2-t1:.2f}s\")\n    print(\"Number of gates = {}\\n\".format(len(sets)))\n    if conv <= conv_tol:\n      break\n\n  return energy, sets, params, n\n\nif __name__ == \"__main__\":\n  symbols = [\"Li\", \"H\"] # Beginning of step 1.\n  geometry = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 2.969280527], dtype=float)\n  H, qubits = qml.qchem.molecular_hamiltonian(symbols, geometry, active_electrons=2, active_orbitals=5) # End of step 2.\n  electrons = 2\n  singles, doubles = qchem.excitations(electrons, qubits) # Step 3.\n  sets = singles+doubles # Step 4.\n  HF = qml.qchem.hf_state(electrons, qubits) # Step 5.\n  params = np.zeros(len(sets), requires_grad=True) # Beginning of step 6.\n  energy, sets, angles, n = penny_simulation(params, H, HF, sets, qubits, conv_tol=1e-04, threshold=1.0e-4) # Beginning of the optimization loop.\n  print(\"Expected ground-state energy: -7.8825378193.\")\n  print(f\"Simulation = {energy[-1]:.8f} Ha\")\n```\n\n    Epoch = 0,  Energy = -7.86266587 Ha, t = 0s\n    Number of gates = 24\n    \n    Epoch = 1, Energy = -7.86985383 Ha, t = 19.90s\n    Number of gates = 25\n    \n    Epoch = 2, Energy = -7.87450290 Ha, t = 21.14s\n    Number of gates = 26\n    \n    Epoch = 3, Energy = -7.87733380 Ha, t = 22.61s\n    Number of gates = 27\n    \n    Epoch = 4, Energy = -7.87904365 Ha, t = 23.29s\n    Number of gates = 28\n    \n    Epoch = 5, Energy = -7.88011206 Ha, t = 23.46s\n    Number of gates = 29\n    \n    Epoch = 6, Energy = -7.88079852 Ha, t = 23.94s\n    Number of gates = 30\n    \n    Epoch = 7, Energy = -7.88124764 Ha, t = 24.37s\n    Number of gates = 31\n    \n    Epoch = 8, Energy = -7.88154767 Ha, t = 24.48s\n    Number of gates = 32\n    \n    Epoch = 9, Energy = -7.88175335 Ha, t = 24.75s\n    Number of gates = 33\n    \n    Epoch = 10, Energy = -7.88189845 Ha, t = 24.85s\n    Number of gates = 34\n    \n    Epoch = 11, Energy = -7.88200372 Ha, t = 25.17s\n    Number of gates = 35\n    \n    Epoch = 12, Energy = -7.88208206 Ha, t = 25.43s\n    Number of gates = 36\n    \n    Epoch = 13, Energy = -7.88214162 Ha, t = 26.04s\n    Number of gates = 37\n    \n    Epoch = 14, Energy = -7.88218776 Ha, t = 25.80s\n    Number of gates = 38\n    \n    Epoch = 15, Energy = -7.88222409 Ha, t = 26.59s\n    Number of gates = 39\n    \n    Epoch = 16, Energy = -7.88225316 Ha, t = 26.68s\n    Number of gates = 40\n    \n    Epoch = 17, Energy = -7.88227674 Ha, t = 27.09s\n    Number of gates = 41\n    \n    Epoch = 18, Energy = -7.88229613 Ha, t = 27.06s\n    Number of gates = 42\n    \n    Epoch = 19, Energy = -7.88231225 Ha, t = 26.49s\n    Number of gates = 43\n    \n    Epoch = 20, Energy = -7.88232581 Ha, t = 27.53s\n    Number of gates = 44\n    \n    Expected ground-state energy: -7.8825378193.\n    Simulation = -7.88232581 Ha\n\n\n\n```\nimport matplotlib.pyplot as plt\n\nE_fci = -7.8825378193\nfig=plt.figure()\nfig.set_figheight(6)\nfig.set_figwidth(10)\nplt.plot(range(n + 2), energy, \"go\", label=r\"$E_\\mathrm{HF}$\", ls=\"dashed\")\nplt.plot(range(n + 2), np.full(n + 2, E_fci), label=r\"$E_\\mathrm{FCI}$\", color=\"red\")\nplt.title('VQE optimization for the LiH Molecule')\nplt.legend(loc='upper right')\nplt.xlabel('Optimization step')\nplt.ylabel('Energy (Hartree)')\nplt.show()\n```\n\n### Comparing optimization for a fixed ansatz\n\nThe same can be said here. A variational circuit outperforms a fixed ansatz. While the first algorithm achieves -7.882 at epoch no.7 with 24 gates, the following algorihm with a fixed ansatz achineves -7.882 at epoch no. 14.\n\n\n```\n#! /usr/bin/python3\n\nimport pennylane as qml\nfrom pennylane import numpy as np\nfrom pennylane import qchem\nimport time\n\ndef penny_simulation(params, H, HF, sets, qubits, conv_tol, threshold):\n  \"\"\"Main function to run the optimization loop.\n\n  Args:\n      - params (tensor): the parameters to be optimized in the ansatz.\n      - H: the molecular Hamiltonian of the system in the qubit representation.\n      - HF (numpy.ndarray): the Hartree-Fock state vector.\n      - sets (list): total spin orbital indices used to build the Givens rotations a.k.a particle-preserving operators (qubit gates).\n      - qubits (int): the number of qubits used to build the circuit.\n      - conv_tol (float): convergence tolerance to stop training.\n      - threshold (float): threshold for the smallest gradient.\n\n  Returns:\n      - energy (list): a list of expected values of each iteration.\n      - sets (list): a list of excitations corresponding to the gates used in the final circuit.\n      - params (list): a list of optimized parameters.\n      - n (int): number of epochs.\n  \"\"\"\n\n  def ansatz(params, wires, to_gates):\n    \"\"\"Function that defines the circuit to be optimized.\"\"\"\n    qml.BasisState(HF, wires=wires) # The reference Hartree-Fock state.\n    for i, elem in enumerate(to_gates):\n      if len(elem) == 4:\n        qml.DoubleExcitation(params[i], wires=elem)\n      else:\n        qml.SingleExcitation(params[i], wires=elem)\n  \n  # Step 8.\n  opt = qml.GradientDescentOptimizer(stepsize=0.4)  \n  dev = qml.device(\"default.qubit\", wires=qubits)\n  cost = qml.ExpvalCost(ansatz, H, dev, optimize=True)\n  circuit_gradient = qml.grad(cost, argnum=0)\n  epochs = 20\n  energy = [cost(params, to_gates=sets)]\n  print(f\"Epoch = 0,  Energy = {energy[-1]:.8f} Ha, t = 0s\")\n  print(\"Number of gates = {}\\n\".format(len(sets)))\n\n  for n in range(epochs):\n    t1 = time.time()\n    grads = circuit_gradient(params,to_gates=sets) # Step 9. From now on we skip step 10.\n    params, prev_energy = opt.step_and_cost(cost, params, to_gates=sets) # Step 11.\n    energy.append(cost(params, to_gates=sets))\n    conv = np.abs(-7.8825378193 - prev_energy) # Step 12.\n    t2 = time.time()\n    print(f\"Epoch = {n+1}, Energy = {energy[-1]:.8f} Ha, t = {t2-t1:.2f}s\")\n    print(\"Number of gates = {}\\n\".format(len(sets)))\n    if conv <= conv_tol:\n      break\n\n  return energy, sets, params, n\n\nif __name__ == \"__main__\":\n  symbols = [\"Li\", \"H\"] # Beginning of step 1.\n  geometry = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 2.969280527], dtype=float)\n  H, qubits = qml.qchem.molecular_hamiltonian(symbols, geometry, active_electrons=2, active_orbitals=5) # End of step 2.\n  electrons = 2\n  singles, doubles = qchem.excitations(electrons, qubits) # Step 3.\n  sets = singles+doubles # Step 4.\n  HF = qml.qchem.hf_state(electrons, qubits) # Step 5.\n  params = np.zeros(len(sets), requires_grad=True) # Beginning of step 6.\n  energy, sets, angles, n = penny_simulation(params, H, HF, sets, qubits, conv_tol=1e-04, threshold=1.0e-4) # Beginning of the optimization loop.\n  print(\"Expected ground-state energy: -7.8825378193.\")\n  print(f\"Simulation = {energy[-1]:.8f} Ha\")\n```\n\n    Epoch = 0,  Energy = -7.86266587 Ha, t = 0s\n    Number of gates = 24\n    \n    Epoch = 1, Energy = -7.86947865 Ha, t = 19.14s\n    Number of gates = 24\n    \n    Epoch = 2, Energy = -7.87385844 Ha, t = 19.82s\n    Number of gates = 24\n    \n    Epoch = 3, Energy = -7.87667722 Ha, t = 19.51s\n    Number of gates = 24\n    \n    Epoch = 4, Energy = -7.87849872 Ha, t = 19.59s\n    Number of gates = 24\n    \n    Epoch = 5, Energy = -7.87968343 Ha, t = 19.79s\n    Number of gates = 24\n    \n    Epoch = 6, Energy = -7.88046071 Ha, t = 19.69s\n    Number of gates = 24\n    \n    Epoch = 7, Energy = -7.88097626 Ha, t = 22.16s\n    Number of gates = 24\n    \n    Epoch = 8, Energy = -7.88132277 Ha, t = 19.82s\n    Number of gates = 24\n    \n    Epoch = 9, Energy = -7.88155938 Ha, t = 19.53s\n    Number of gates = 24\n    \n    Epoch = 10, Energy = -7.88172397 Ha, t = 19.62s\n    Number of gates = 24\n    \n    Epoch = 11, Energy = -7.88184092 Ha, t = 19.22s\n    Number of gates = 24\n    \n    Epoch = 12, Energy = -7.88192606 Ha, t = 19.49s\n    Number of gates = 24\n    \n    Epoch = 13, Energy = -7.88198970 Ha, t = 19.13s\n    Number of gates = 24\n    \n    Epoch = 14, Energy = -7.88203861 Ha, t = 20.39s\n    Number of gates = 24\n    \n    Epoch = 15, Energy = -7.88207727 Ha, t = 28.93s\n    Number of gates = 24\n    \n    Epoch = 16, Energy = -7.88210870 Ha, t = 19.29s\n    Number of gates = 24\n    \n    Epoch = 17, Energy = -7.88213491 Ha, t = 19.46s\n    Number of gates = 24\n    \n    Epoch = 18, Energy = -7.88215728 Ha, t = 19.81s\n    Number of gates = 24\n    \n    Epoch = 19, Energy = -7.88217677 Ha, t = 19.67s\n    Number of gates = 24\n    \n    Epoch = 20, Energy = -7.88219404 Ha, t = 21.36s\n    Number of gates = 24\n    \n    Expected ground-state energy: -7.8825378193.\n    Simulation = -7.88219404 Ha\n\n\n\n```\nimport matplotlib.pyplot as plt\n\nE_fci = -7.8825378193\nfig=plt.figure()\nfig.set_figheight(6)\nfig.set_figwidth(10)\nplt.plot(range(n + 2), energy, \"go\", label=r\"$E_\\mathrm{HF}$\", ls=\"dashed\")\nplt.plot(range(n + 2), np.full(n + 2, E_fci), label=r\"$E_\\mathrm{FCI}$\", color=\"red\")\nplt.title('VQE optimization for the LiH Molecule')\nplt.legend(loc='upper right')\nplt.xlabel('Optimization step')\nplt.ylabel('Energy (Hartree)')\nplt.show()\n```\n\n## <a href=\"https://qamuy.qunasys.com/docs/en/\"></a> Qamuy\n\n\n```\nimport qamuy.chemistry as qy\nimport qamuy.plot\n```\n\n\n```\nemail_address = \"email_address\" #@param\npassword = \"password\" #@param\n```\n\n\n```\n!qamuy reset-password\n```\n\n\n```\n!qamuy login\n```\n\n\n```\nqclient = Client(email_address=email_address, password=password)\n```\n\n\n```\nsetting = qy.QamuyChemistryInput()\n```\n\n# &nbsp; <a href=\"#\"></a> References\n\n\n\\[1] McClean, J.R., Boixo, S., Smelyanskiy, V.N. et al. Barren plateaus in quantum neural network training landscapes. [Nat Commun 9, 4812 (2018)](https://www.nature.com/articles/s41467-018-07090-4). \n\n\\[2] Grimsley, H. R.; Claudino, D.; Economou, S. E.; Barnes, E.; Mayhall, N. J. Is the trotterized uccsd ansatz chemically well-defined? [J. Chem. Theory Comput. 2020, 16, 1](https://pubs.acs.org/doi/abs/10.1021/acs.jctc.9b01083).\n\n[3] Harper R. Grimsley, Sophia E. Economou, Edwin Barnes, Nicholas J. Mayhall, \u201cAn adaptive variational algorithm for exact molecular simulations on a quantum computer\u201d. [Nat. Commun. 2019, 10, 3007](https://www.nature.com/articles/s41467-019-10988-2).\n\n[4] PennyLane dev team, \"Adaptive circuits for quantum chemistry\". [PennyLane, 13 September 2021](https://pennylane.ai/qml/demos/tutorial_adaptive_circuits.html).\n\n[5] Peruzzo, A., McClean, J., Shadbolt, P. et al. A variational eigenvalue solver on a photonic quantum processor. [Nat Commun 5, 4213 (2014)](https://doi.org/10.1038/ncomms5213).\n", "meta": {"hexsha": "fe077a39603d996d90b9df0b34b62342592c9053", "size": 287021, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "presentation.ipynb", "max_stars_repo_name": "zemarchezi/qhack2022-hackeinberg-project", "max_stars_repo_head_hexsha": "49ac97997fa18b5ef4b21ffd48b723099949afe0", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-03-02T20:50:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:20:49.000Z", "max_issues_repo_path": "presentation.ipynb", "max_issues_repo_name": "zemarchezi/qhack2022-hackeinberg-project", "max_issues_repo_head_hexsha": "49ac97997fa18b5ef4b21ffd48b723099949afe0", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "presentation.ipynb", "max_forks_repo_name": "zemarchezi/qhack2022-hackeinberg-project", "max_forks_repo_head_hexsha": "49ac97997fa18b5ef4b21ffd48b723099949afe0", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2022-02-24T01:41:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T20:03:19.000Z", "avg_line_length": 287021.0, "max_line_length": 287021, "alphanum_fraction": 0.8823988489, "converted": true, "num_tokens": 20179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.10818895743752079, "lm_q1q2_score": 0.04612328863081651}}
{"text": "```python\nx = 1\nif x == 1:\n    # indented four spaces\n    print(\"x is 1.\")\n\n\nprint('Hello j\\'ai bien ex\u00e9cut\u00e9 votre commande mon ma\u00eetre ;)')\n\n\n```\n\n    x is 1.\n    Hello j'ai bien ex\u00e9cut\u00e9 votre commande mon ma\u00eetre ;)\n\n\n\n```python\nimport sympy\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nnormalize=False\n\npi = sympy.pi.evalf(400)\n\ndigits = (d for d in str(pi)[2:])\n\nfreqs = np.zeros(10, dtype='i4')\n\nfor d in digits:\n\n    freqs[int(d)] += 1\n\nif normalize:\n\n    freqs = freqs/freqs.sum()\n    \n\nax = plt.plot(freqs,'bo-')\n\nplt.title('Single digit counts in pi')\n\nplt.xlabel('Digit')\n\nplt.ylabel('Count')\n```\n", "meta": {"hexsha": "fbf86b4cf41e7dbf751d70141b91ef387c0bbb3a", "size": 18259, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "test_notebook.ipynb", "max_stars_repo_name": "vertingo/Anaconda_Videos_Tutos", "max_stars_repo_head_hexsha": "f30f2a0549a7b81c17f4d5d249edc59eb3c05458", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test_notebook.ipynb", "max_issues_repo_name": "vertingo/Anaconda_Videos_Tutos", "max_issues_repo_head_hexsha": "f30f2a0549a7b81c17f4d5d249edc59eb3c05458", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test_notebook.ipynb", "max_forks_repo_name": "vertingo/Anaconda_Videos_Tutos", "max_forks_repo_head_hexsha": "f30f2a0549a7b81c17f4d5d249edc59eb3c05458", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 165.9909090909, "max_line_length": 16188, "alphanum_fraction": 0.9053617394, "converted": true, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749485, "lm_q2_score": 0.10087861394487134, "lm_q1q2_score": 0.046115318376866825}}
{"text": "## You don't know what to choose between Matlab and Python :\n\n# Try Julia !\n\n<center></center>\n\n\n## Why a talk on programming language ?\n\n- [Better Software, Better Research](https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=6886129&tag=1) (Goble, C. (2014). IEEE Internet Computing)\n\n>  Of  2,000  scientists surveyed  online, **91%** said  **using**  scientific  software  is  important  for  their own research, **84%** said **developing** scientific  software  is  important  for  their  own  research [...] and **38% spend at least one  fifth  of  their  time  developing  software**.  \n\n>   \u201cYou  can download our code from the URL supplied. Good luck downloading the only \n> postdoc who can get it to run, though\u201d (Ian  Holmes)\n    \n- Big Data -> Big Software\n- Loi pour une r\u00e9publique num\u00e9rique (2017) $\\rightarrow$ new codes must (more or less) be open source (cf https://scinfolex.com/2017/12/08/les-logiciels-produits-par-les-administrations-sont-passes-en-open-source-par-defaut-et-voici-pourquoi/)\n\n# Play with the slides \n\nhttps://tinyurl.com/introjuliagipsa \n\nor https://mybinder.org/v2/gh/raphbacher/julia-intro/master?filepath=presentation_julia.ipynb\n\nSources:\n\nhttps://github.com/raphbacher/julia-intro\n\n# Outline\n\n- State of the art : the two language problem\n- What is Julia\n- Why Julia is fast\n- Julia Ecosystem & interop \n- (Parallelism)\n\n## State of the art : Matlab\n\nPros :\n- Polished product with support\n- Simulink\n- High level syntax\n\nCons :\n- Closed : not everyone has access to it, impossible to put a demonstrator online.\n- Slow loops (better since 2015) : not everything is pretty once vectorized\n- Not fast per se (Fortran bindings), memory management is difficult\n- Not a generalist language (cumbersome to put a demo on the web e.g.)\n- 12 000\u20ac each year for the lab\n\n\n\n\n## State of the art : Python\n \nPros :\n- Free and open-source, generalist, widly used outside scientific community\n- Lot of scientific communities are embracing it\n- Lots of efforts to make it fast (numba, ...)\n\nCons :\n- Scientific computing is not native : \n    - all fallback to C/Fortran black-boxes -> limit flexibility \n- Object Oriented paradigm can be cumbersome for scientific code\n\n## Science and the two languages problem\n\nScientists need to easily explore new ideas :\n\n- Need for mathematical abstractions\n- Need for customizations (avoid black boxes, try variations)\n\n- But also need for performance (intrinsic goal or to allow re-use)\n\nWhat is done now (when you need to go further than using existing packages, for e.g. data analysis)\n\n1) Prototyping in R/Python/Matlab\n\n2) Rewriting whole or parts (if money/man power) to a performant low-level language as C/Fortran\n\n\n# Yet another language\n\n<center></center>\n\n# Here comes Julia :\n\n* innovative open-source generalist programming language with scientific computing at its core\n* **easy as Matlab, fast as Fortran, flexible as Python, deep as LISP**\n* leverages (for now...) major C/Fortran science packages, e.g. LAPACK, MPI, FFTW... \n* 5th language to run at 1 petaflops (Celeste project), after assembly, Fortran, C, C++ \n* State of the art packages in Optimization (JUMP), Differential Equations (DifEq), ... Well positioned for ML (Flux, Knet, autodiff...)\n* solves the \"two-language problem\"\n\n\n# Background\n\n* origins at MIT, UCSB applied math & computer science, 2010     \n* founders Viral Shah, Jeff Bezanson, Stefan Karpinsky (now at Julia Computing LLC), Alan Edelman (MIT)\n* ~10-person core language team, ~600 contributors, ~1500 registered packages \n* support from Intel, Microsoft, Wall St., Moore Foundation, NumFocus\n* julia-0.1 released in 2012, julia-1.0 in August 2018\n\n\n**Its goal : Solve the languages problem by having a dynamic, high level language with good mathematical expressivity able to be as fast as C/Fortran.**\n\n# Disclaimer\n\n- I am not a Julia expert : I've been following the language for ~ one year and started porting Python codes a few months ago.\n- Julia (like Python...) is not a drop-in replacement for Matlab, it is an alternative.\n- Don't fix that ain't broken : \n    - if Matlab/R/Python/C is good for you, no need to change\n    - but if you are sometimes faced with some limitations of these languages, give Julia a try\n\n# Julia: expressive as Matlab\n\nJulia can as expressive as Matlab for interactive calculations with built-in numerical libraries and plotting. A few examples...\n\n### Arrays\n\n\n```julia\nusing LinearAlgebra\nA = randn(4,4)       # 4 x 4 matrix of normally distributed random numbers\n```\n\n\n```julia\nA[:,1]                # familiar colon syntax --extract first column of A\n```\n\n## Linear Algebra\n\n\n```julia\nb = randn(4)          \nx = A\\b               # solve Ax=b for x using backslash operator\nnorm(A*x-b)\n```\n\n\n```julia\nU, \u03c3, V = svd(A);     # singular value decomposition --note unicode variable name \u03c3\n```\n\n\n```julia\n\u03a3 = diagm(0 => \u03c3)\nnorm(A - U*\u03a3*V')      # compute error of SVD factorization A = U \u03a3 V'\n```\n\n# Fast as Fortran\n\n\n\n```julia\nfunction loop()\n    a=0 \n    for i in 1:1_000_000\n        a+=1;\n    end\nend\n@time loop # compile time\n@time loop # now fast\n```\n\n## Compare with Matlab (R2018) \n\n    function [] = loop()\n        a=0;\n        for i=1:1000000\n            a=i+1;\n        end\n    end\n    \n    f = @() loop();\n    \n    timeit(f) => 0.0018s\n\n**2000x slower !**\n\n### Benchmarks on common code pattterns\n\nTakeaway: Julia timings are clustered around C timing, Matlab/Python/R orders of magnitude slower.\n\n<center></center>\n\n### KS-CNAB2 benchmark: CPU time of identical algorithm in six languages. \n\nTakeaway: Julia is nearly as fast as C and Fortran, within a few percent. Codes: [ks.py](https://github.com/johnfgibson/whyjulia/tree/master/ks-codes/ksbenchmark.py#48)\n [ks.m](https://github.com/johnfgibson/whyjulia/tree/master/ks-codes/ksbenchmark.m#46) \n [ks.jl](https://github.com/johnfgibson/whyjulia/tree/master/ks-codes/ksbenchmark.jl#L129) [ks.c](https://github.com/johnfgibson/whyjulia/tree/master/ks-codes/ksbenchmark.c#L82) [ks.cpp](https://github.com/johnfgibson/whyjulia/tree/master/ks-codes/ksbenchmark.cpp#L87) [ks.f90](https://github.com/johnfgibson/whyjulia/tree/master/ks-codes/ksbenchmark.f90#L84) \n\n<center></center>\n\n### KS-CNAB2 benchmark: CPU time versus lines of code \n\nTakeaway: The Julia PDE code is almost as compact as Matlab/Python, almost as fast as C/Fortran.\n<center></center>\n\n\n## Julia: easy, dynamic, and fast. How? \n\n\n * **Just-in-time compilation** (JIT)\n    - user-level code is compiled to machine code on-the-fly  \n    \n    \n * **Meticulous type system**\n    - designed to maximize impact of JIT\n    - type inference: compiler determines types of variables\n    \n    \n * **Multiple dispatch**\n    - functions are compiled for each set of argument types\n    - function dispatch determined at compile time when possible, run time when not\n \n\n### Just-in-time compilation\n\nFunctions are compiled to machine code when first run. Subsequent runs are as fast as compiled C, C++, Fortran.\n\n\n# Caveats\n\n- It's a marathon not a sprint : Julia can be slow at first\n- It's an open-source language with lots of good willing contributors, it's not a product (see JuliaPro...)\n- If you directly translate from Matlab to Julia you will not always see an improvement, you have exploit Julia strengths (loops to avoid allocations, type stability, ...)\n\n# A julia type\n\nLike a Python object but without methods\n\n```julia\nstruct Spaceship\n           speed::Float64\n           Position::Array{Float64,2}\n   end\n```\n\n## Multiple dispatch\n\n```julia\ncollide(a::Asteroid, s::Spaceship) # a first method of the function collide\ncollide(s1::Spaceship, s2::Spaceship) # another method of the function collide\n```\n\n#### Logistic map example \n$$f(x) = 4\\, x\\, (1-x)$$\n\n\n```julia\nf(x) = 4x*(1-x)     # define logistic map\n@time f(0.3);       # first run is slow\n@time f(0.4);       # second run is a thousand times faster\n```\n\n#### Observe the compilation of $f(x)$ by stages\n\nuser Julia -> generic Julia expression -> typed Julia expression -> intermediate compiler language -> machine code\n\n\n```julia\ninclude(\"macros.jl\");\n```\n\n\n```julia\n@code_lowered f(0.3)  # show f(x) as generic Julia expression\n```\n\n\n```julia\n@code_typed f(0.3)    # show f(x) as Julia expr with inferred types, based on the arg types\n```\n\n## Type inference and dispatch\n\nWe can see that if we call f on an Integer we get a code specialised for integer (i64)\n\n\n```julia\n@code_llvm_nocomment f(0.3)    # show f(x) in intermediate compiler language (LLVM)\n```\n\n\n```julia\n@code_native_nocomment f(0.3) # show f(x) in IA-64 assembly language\n```\n\n\n```julia\n@code_llvm_nocomment f(3)    # show f(x) in intermediate compiler language (LLVM)\n```\n\n# Type stability\n\nNo need to declare type but need to be type stable...\n\n\n```julia\nfunction g1(a,n)\n  x = 0\n  for i in 1:n\n    x += a\n  end\nend\n\n@code_warntype g1(2.0,10) # see the Union{Float64, Int64}\n# @code_llvm_nocomment g1(2.0,10)\n```\n\n\n```julia\nfunction g2(a,n)\n  x = zero(a) # get the zero of the type of a\n  for i in 1:n\n    x += a\n  end\nend\n\n@code_warntype g2(2.0,10) # the type stable version is shorter thus faster\n#@code_llvm_nocomment g2(2.0,10)\n```\n\n### Millionth iterate of logistic map: comparison of Julia, C, Matlab\n\nGiven $f(x) = 4\\,x \\, (1-x)$, \n\nlet $~~f^N(x) = f(\\,f(\\,...(\\,f(\\,f(x)))))$ be the millionth iterate of $f$, with $N=10^6$.\n\n#### $f^N$ in Julia: run-time code generation & compilation!\n\n\n```julia\n# define function that, given function g(x), \n# returns iterated function g\u1d3a(x) = g(g(...(g(g(x)))))\nfunction iterator(g, N)\n    \n    # construct g\u1d3a, the Nth iterate of g\n    function g\u1d3a(x)\n       for i \u2208 1:N             \n          x = g(x)\n       end        \n       return x\n    end    \n    \n    return g\u1d3a\nend\n\n\nf\u1d3a = iterator(f, 10^6);  # generate millionth iterate funcion f\u1d3a(x) for f(x) = 4x(1-x)\n\nf\u1d3a(0.67)                 # run f\u1d3a(x) once to compile it\n```\n\n**$f^N$ in C++, compiled**\n\n\n```julia\n; cat codes/fN.cpp \n```\n\n### Compare execution time of $f^N$ in Julia, C++, Matlab\n\n#### Julia\n\n\n```julia\nprint(\"t=\");\n@time x = f\u1d3a(0.67);         # run the Julia f\u1d3a on x = 0.67\n@show x;\n```\n\n#### C++\n\n\n```julia\n; g++ -O3 -o fN codes/fN.cpp -lm \n```\n\n\n```julia\n; ./fN 0.67 \n```\n\nJulia and C++ get the same result `x` in roughly same execution time `t`. Sometimes Julia is faster, sometimes C++.\n\n#### Matlab\n```\n>> tic(); x=fN(0.67); t=toc();\n>> t, x\nt = 0.048889000000000\nx = 0.101168853345475\n```\nMatlab gets the same result $x$, but ten to twenty times slower than Julia or C++.\n\n# A short break\n\n<center></center>\n\n## An ecosystem of packages\n\n- Most of packages are available on Github (ease collaboration)\n- Main fields are grouped in Github Organizations (see https://julialang.org/community/)\n- Julia comes with a powerful package/envrionment manager\n\n\n\n```julia\nusing Pkg #load the Pkg stdlib\nPkg.activate(\".\") #activate the local environment\n```\n\n### Singular values of Hilbert matrix and arbitrary precision\n\nThe Hilbert matrix $A_{ij} = (i+j-1)^{-1}$ is notoriously ill-conditioned. \n\n\n```julia\nusing LinearAlgebra #load stdlib\n\n#install package : no need online, needed on your computer\n#Pkg.add(PackageSpec(name=\"GenericSVD\",rev=\"master\")); \n\nusing GenericSVD #load package\n```\n\n\n```julia\nm = 8\nA = [1//(i+j-1) for i=1:m, j=1:m]    # 8 x 8 Hilbert matrix of Rationals\n```\n\n\n```julia\n# 16 x 16 Hilbert is too ill-conditioned for 64-bit arithmetic \nm = 16 ; A = [1/(i+j-1) for i=1:m, j=1:m]    # 16 x 16 Hilbert matrix of Float64s\n@show cond(A)\n@show eps(Float64);\n```\n\n\n```julia\n\u03c3 = svdvals(A)\n\u03c3[end-5:end] # last 5 values\n```\n\n\n```julia\n# Make 32 x 32 Hilbert matrix of 256-bit BigFloats and show a few elements\nsetprecision(256)\nm = 32\nA = [BigFloat(1//(i+j-1)) for i=1:m, j=1:m]; \n@show A[1,1]\n@show A[2,1]\n@show A[3,1]\n;\n```\n\n\n```julia\n# Compute singular values of 32 x 32 Hilbert matrix in 256-bit arithmetic\n\u03c3 = svdvals!(A);\n\u03c3[end-5:end] # last 5 values\n```\n\n## User-defined type: Galois field GF(p)\n\nFinite scalar field GF(p) is $\\mathbb{Z}/p$, the integers modulo p, where p is prime. Example by Andreas Noack, Julia Computing.\n\n\n```julia\n# Type definition: Galois fields GF(p), where p is prime modulus, T is integer type\nstruct GF{p,T} <: Number where {p,T<:Integer}\n    rep::T  # representative integer which holds the value of a GF(p) variable\n    function GF{p,T}(x::Integer) where {p,T<:Integer}\n        return new(mod(x, p))\n    end\nend\nGF{p}(x::T) where {p,T<:Integer} = GF{p,T}(x)\n\n\n# Define some basic methods for GF(p) that all Julia Numbers must have\nimport Base: convert, inv, one, promote_rule, show, zero\n\nfunction call(::Type{GF{p}}, x::Integer) where {p}\n    if !isprime(p)\n        throw(ArgumentError(\"p must be prime\"))\n    end\n    return GF{p,typeof(x)}(mod(x, p))\nend\n\nconvert(::Type{GF{p,T}}, x::Integer) where {p,T} = GF{p}(x)\nconvert(::Type{GF{p}}, x::Integer) where {p} = GF{p}(x)\nconvert(::Type{GF{p,T}}, x::GF{p}) where {p,T} = GF{p,T}(x.rep)\npromote_rule(::Type{GF{p,T1}}, ::Type{T2}) where {p,T1,T2<:Integer} = GF{p,promote_type(T1,T2)}\nshow(io::IO, x::GF) = show(io, x.rep);\n\n\n\n```\n\n\n```julia\n# Define arithmetic operations on GF(p)\nimport Base: +, -, *, /,conj\n\nfor op in (:+, :-, :*)   # loop over ops, defining each in terms of integer ops mod p\n    @eval begin\n        ($op)(x::GF{p,T}, y::GF{p,T}) where {p,T} = GF{p,T}($(op)(x.rep, y.rep))\n    end\nend\n\n\n# Define inverse and \u00f7. Requires more care than +, -, * because dividing by zero throws error\nfunction inv(x::GF{p,T}) where {p,T}\n    if x == zero(x)\n        throw(DivideError())\n    end\n    r, u, v = gcdx(x.rep, p)\n    GF{p,T}(u)\nend\n\nfunction conj(x::GF{p,T}) where {p,T}\n    u = conj(x.rep)\n    GF{p,T}(u)\nend\n\n\n(/)(x::GF{p}, y::GF{p}) where {p}= x*inv(y);\n```\n\n\n```julia\n# Create some GF(7) variables and do arithmetic\n\nx = GF{7}(9)   # x =  9 mod 7 = 2\ny = GF{7}(12)  # y = 12 mod 7 = 5\n@show x\n@show y\n@show x + y     # 2 + 5 mod 7 = 0\n@show x - y     # 2 - 5 mod 7 = 4\n@show x * y     # 2 * 5 mod 7 = 3\n@show x / y     # 2 \u00f7 5 mod 7 = 6, because 2 = 6*5 mod 7\n;\n```\n\n### Linear algebra over Galois field\n\n\n```julia\nimport Random: seed!\nseed!(1234)\nA = [GF{7}(rand(0:6)) for i = 1:4, j = 1:4]; # matrix of random GF(7) elems\n```\n\n\n```julia\nb = [GF{7}(rand(0:6)) for i = 1:4];         # random vector b for Ax=b problem\n```\n\n\n```julia\nx = A\\b;   # solve Ax=b over GF(p)!\n```\n\n\n```julia\nA*x - b   # check that x satisfies Ax=b\n```\n\n**Whoa! Built-in backslash operator on matrix of GF(p) worked!** \n\nJulia generated and compiled a GF(p)-specific version of its generic LU decomp function. All it needs is definitions of $+, -, \\times, \\div$.\n\n# Solving Differential Equations\n\n Solve the Lorenz equations:\n \n\n$$\n\\begin{align}\n\\frac{dx}{dt} &= \u03c3(y-x) \\\\\n\\frac{dy}{dt} &= x(\u03c1-z) - y \\\\\n\\frac{dz}{dt} &= xy - \u03b2z \\\\\n\\end{align}\n$$\n\n<div style=\"padding: 20px;background-color: #f44336;color: white; margin-bottom: 15px;\">\nFair Warning \u26a0 : the next cell is gonna take some time. Like really. You can go grab a coffee.\n\nThis compilation time only occurs the first time you load this version of this package on your machine. \nIf you are trying this online on Mybinder, remember that each time you connect, you are on a fresh julia install \njust built for you, so this precompilation time occurs. And Plots and DifferentialEquations are pretty big libraries (DifEq regroups a lot of solvers).\n</div>\n\n\n```julia\n#Pkg.add(\"DifferentialEquations\") # add the Differential equation suite\nusing DifferentialEquations # first time is very slow (precompilation)\nusing Plots\n```\n\n\n```julia\nfunction lorenz(du,u,p,t)\n du[1] = 10.0*(u[2]-u[1])\n du[2] = u[1]*(28.0-u[3]) - u[2]\n du[3] = u[1]*u[2] - (8/3)*u[3]\nend\n\nu0 = [1.0;0.0;0.0] ; tspan = (0.0,100.0);\nprob = ODEProblem(lorenz,u0,tspan)\nsol = solve(prob)\nPlots.plot(sol,vars=(1,2,3))\n```\n\n### Add a bit of interaction\n\n<center></center>\n\n\n```julia\n#Pkg.add(\"IJulia\") \n#Pkg.add(\"Interact\") \n#Pkg.add(\"Plots\") \n\nusing Interact #load library\nusing Plots\nusing IJulia\n```\n\n\n```julia\nx = y = 0:0.1:30\n\nfreqs = OrderedDict(zip([\"pi/4\", \"\u03c0/2\", \"3\u03c0/4\", \"\u03c0\"], [\u03c0/4, \u03c0/2, 3\u03c0/4, \u03c0]))\n\nmp = @manipulate for freq1 in freqs, freq2 in slider(0.01:0.1:4\u03c0; label=\"freq2\")\n    y = @. sin(freq1*x) * sin(freq2*x)\n    plot(x, y)\nend\n\ndisplay(mp) # do not work online on mybinder for now.\n\n```\n\n## Automatic differentiation\n\n\n\n\n```julia\n#Pkg.add(\"ForwardDiff\")\nusing ForwardDiff\n\nf(x::Vector) = sum(sin, x) + prod(tan, x) * sum(sqrt, x);\n\nx = rand(5) # small size for example's sake\n\ng = x -> ForwardDiff.gradient(f, x); # g = \u2207f\n\n@show g(x)\n\n@show ForwardDiff.hessian(f, x)\n```\n\n# Interop\n\nInterop possible avec Python, Matlab, R, Java, C/Fortran,...\n\n\n```julia\n#Pkg.add(\"PyCall\") # add python binding package\n\nusing PyCall \n@pyimport math\nmath.sin(math.pi / 4) - sin(pi / 4) # python - julia = 0\n```\n\n### Macros: code that transforms code\n\n\n```julia\n# @time macro inserts timing and memory profiling into expression, then evaluates, and prints\n@time f(2//3)\n```\n\n\n```julia\n# @which macro determines which function is called, provides link to source code on GitHub\n@which exp(\u03c0)\n```\n\n\n```julia\n@which exp(\u03c0*im)\n```\n\nMacros enable run-time code generation and transformation. \n\nApplications :\n\n  * generation and execution of boilerplate code\n  * run-time generation and optimization of algorithms, e.g. FFTW, ATLAS\n  * symbolic mathematics, automatic differentiation\n  * *all written like high-level Python, running like compiled C !!!*\n\n## Parallelism in Julia: just change the array type\n\nSome very trivial examples of Julia's built-in parallelism\n\n\n```julia\nusing Distributed\n#Pkg.add(\"DistributedArrays\")\n\naddprocs(2);\n```\n\n\n```julia\n; cat codes/count_heads.jl\n```\n\n\n```julia\n@everywhere include(\"codes/count_heads.jl\")\n\na = @spawn count_heads(10000000)\nb = @spawn count_heads(10000000)\nfetch(a)+fetch(b)\n```\n\n### Parallel loops with reduction\n\n\n```julia\nnheads = @distributed (+) for i=1:200000000\n  Int(rand(Bool))\nend\n```\n\nAnd more :\n- Distributed arrays\n- GPUArrays\n- TPUArrays ...\n\nJust changing the behavior of the underlying structure can bring new hardware support for all packages\n\n# Helpful materials\n\n- Main site https://julialang.org/\n- Docs https://docs.julialang.org/en/v1/\n- Forum https://discourse.julialang.org/\n- Book https://benlauwens.github.io/ThinkJulia.jl/latest/book.html\n- Blog http://www.stochasticlifestyle.com/\n- All-in-one package : https://juliacomputing.com/products/juliapro.html\n- Try online (not yet 1.0) : https://juliabox.com/\n\n<center> </center>\n\n# Code as a first-class citizen product of research\n\n- The (new version) Julia package manager has reproductibility at its core (each code project is linked to a deterministic set of dependencies)\n- Creating a Julia package comes with tools for documentation, unit testing, continuous integration\n- New scientific collaborations can be based on software (see the Github organizations such as JuliaDiff, JuliaStats, etc...)\n\n\n\n# Food for thoughts\n\n- Cost and open source\n    - Matlab licences cost 12000\u20ac each year to the lab \n    - Julia (and Python and R) come for free but development is not free\n    - A part of Matlab costs could go to financing open source software that is critical for science (see e.g. https://bitbucket.org/paugier/etude-asso-pynumfr/src/default/etude_asso_python_sciences_fr.rst?fileviewer=file-view-default)\n- The combo C(++) low-level libraries and high level bindings (as Tensorflow, Keras...) lead to black box workflows...\n\n# Conclusions\n\nJulia\n* **Easy as Matlab, fast as Fortran, flexible as Python, deep as Lisp**\n*  Scientific computing, from interactive exploration to HPC\n*  Paradigms (multiple dispatch) that enforce collaboration\n\nNot covered\n* large-scale programming, development ecosystem, environments, debuggers, etc.\n* Abstract Types, compositions, ...\n* rough edges: plotting, static compilation  (not quite there), package loading times, young 1.0\n\n*Thanks* : the Julia communityfor most of the examples, xkcd\n\n  \nJulia website: http://www.julialang.org, this talk: https://github.com/raphbacher/julia-intro\n\n", "meta": {"hexsha": "54ae916f3d4b34e5ac2cc3476a06a69e309d4515", "size": 39914, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "presentation_julia.ipynb", "max_stars_repo_name": "raphbacher/julia-intro-bio", "max_stars_repo_head_hexsha": "d4897b1d3e5a6447a3e634d0b9d30fa319956765", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "presentation_julia.ipynb", "max_issues_repo_name": "raphbacher/julia-intro-bio", "max_issues_repo_head_hexsha": "d4897b1d3e5a6447a3e634d0b9d30fa319956765", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "presentation_julia.ipynb", "max_forks_repo_name": "raphbacher/julia-intro-bio", "max_forks_repo_head_hexsha": "d4897b1d3e5a6447a3e634d0b9d30fa319956765", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1172205438, "max_line_length": 369, "alphanum_fraction": 0.5237761187, "converted": true, "num_tokens": 5966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934934732271168, "lm_q2_score": 0.19193279106941585, "lm_q1q2_score": 0.04593898827229107}}
{"text": "```python\n! pip3 install matplotlib\n```\n\n\n```python\nimport sys\n!{sys.executable} -m pip install matplotlib\n```\n\n    Collecting matplotlib\n      Using cached https://files.pythonhosted.org/packages/c3/8b/af9e0984f5c0df06d3fab0bf396eb09cbf05f8452de4e9502b182f59c33b/matplotlib-3.1.1-cp37-cp37m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl\n    Collecting kiwisolver>=1.0.1 (from matplotlib)\n      Using cached https://files.pythonhosted.org/packages/df/93/8bc9b52a8846be2b9572aa0a7c881930939b06e4abe1162da6a0430b794f/kiwisolver-1.1.0-cp37-cp37m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl\n    Collecting cycler>=0.10 (from matplotlib)\n      Using cached https://files.pythonhosted.org/packages/f7/d2/e07d3ebb2bd7af696440ce7e754c59dd546ffe1bbe732c8ab68b9c834e61/cycler-0.10.0-py2.py3-none-any.whl\n    Collecting numpy>=1.11 (from matplotlib)\n      Using cached https://files.pythonhosted.org/packages/c1/4b/78119133136c20e5ad2e01bf72b0633241defd619939908223cd394a9c32/numpy-1.17.0-cp37-cp37m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from matplotlib) (2.8.0)\n    Collecting pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 (from matplotlib)\n      Using cached https://files.pythonhosted.org/packages/11/fa/0160cd525c62d7abd076a070ff02b2b94de589f1a9789774f17d7c54058e/pyparsing-2.4.2-py2.py3-none-any.whl\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/site-packages (from kiwisolver>=1.0.1->matplotlib) (41.0.1)\n    Requirement already satisfied: six in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from cycler>=0.10->matplotlib) (1.12.0)\n    Installing collected packages: kiwisolver, cycler, numpy, pyparsing, matplotlib\n    Successfully installed cycler-0.10.0 kiwisolver-1.1.0 matplotlib-3.1.1 numpy-1.17.0 pyparsing-2.4.2\n\n\n\n```python\nimport matplotlib.pyplot as plt\n```\n\n\n```python\nplt.plot(range(100))\n```\n\n\n```python\n%time range(100)\n```\n\n    CPU times: user 3 \u00b5s, sys: 0 ns, total: 3 \u00b5s\n    Wall time: 5.96 \u00b5s\n\n\n\n\n\n    range(0, 100)\n\n\n\n\n```python\n%time x=range(1000000)\n```\n\n    CPU times: user 5 \u00b5s, sys: 1e+03 ns, total: 6 \u00b5s\n    Wall time: 8.11 \u00b5s\n\n\n\n```python\n%%timeit x=range(1000000)\nmax(x)\n```\n\n    28.6 ms \u00b1 370 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 10 loops each)\n\n\n\n```python\n%%writefile test.txt\nthis is written from jupyter\nnotebook\n```\n\n    Writing test.txt\n\n\n\n```python\n%pwd\n```\n\n\n\n\n    '/Users/mildo/MyDocuments/datascienceWithPython/module2'\n\n\n\n\n```python\n%cat test.txt\n```\n\n    this is written from jupyter\r\n    notebook\r\n\n\n\n```python\npwd\n```\n\n\n\n\n    '/Users/mildo/MyDocuments/datascienceWithPython/module2'\n\n\n\n\n```python\n%pwd\n```\n\n\n\n\n    '/Users/mildo/MyDocuments/datascienceWithPython/module2'\n\n\n\n\n```python\n%%HTML\n<i> hola ale </i>\n```\n\n\n<i> hola ale </i>\n\n\n\n\n```latex\n%%latex\n\\begin{equation}\nGradient: \\nabla J = - 2H^T(Y-HW)\n\\end{equation}\n```\n\n\n\\begin{equation}\nGradient: \\nabla J = - 2H^T(Y-HW)\n\\end{equation}\n\n\n\n\n\n```latex\n%%latex\nThe equation environment creates numbered formulas you can\nlabel and refer to elsewhere:\n    \n\\begin{equation}\\label{eq:pythagoras}\na^2 + b^2 = c^2 .\n\\end{equation}\nEquation \\ref{eq:pythagoras} is the heart of the Pythagorean theorem.\n\nUse the \\eqref macro to put parentheses around equation\nreferences: \\eqref{eq:pythagoras}.\n\n```\n\n\nThe equation environment creates numbered formulas you can\nlabel and refer to elsewhere:\n    \n\\begin{equation}\\label{eq:pythagoras}\na^2 + b^2 = c^2 .\n\\end{equation}\nEquation \\ref{eq:pythagoras} is the heart of the Pythagorean theorem.\n\nUse the \\eqref macro to put parentheses around equation\nreferences: \\eqref{eq:pythagoras}.\n\n\n\n\n```latex\n%%latex\n\nFor equations with no numbers, use \\verb|equation*|:\n\n\\begin{equation*}\n2 + 2 = 4 .\n\\end{equation*}\n```\n\n\n\nUse the \\verb|\\eqref| macro to put parentheses around equation\nreferences: \\eqref{eq:pythagoras}.\n\nFor equations with no numbers, use \\verb|equation*|:\n\n\\begin{equation*}\n2 + 2 = 4 .\n\\end{equation*}\n\n\n\n\n```python\n!pip install ipython-sql\n```\n\n    Collecting ipython-sql\n      Downloading https://files.pythonhosted.org/packages/ab/df/427e7cf05ffc67e78672ad57dce2436c1e825129033effe6fcaf804d0c60/ipython_sql-0.3.9-py2.py3-none-any.whl\n    Requirement already satisfied: ipython>=1.0 in /usr/local/Cellar/ipython/7.7.0/libexec/lib/python3.7/site-packages (from ipython-sql) (7.7.0)\n    Collecting prettytable (from ipython-sql)\n      Downloading https://files.pythonhosted.org/packages/ef/30/4b0746848746ed5941f052479e7c23d2b56d174b82f4fd34a25e389831f5/prettytable-0.7.2.tar.bz2\n    Collecting sqlalchemy>=0.6.7 (from ipython-sql)\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/c2/75/6217c626fa22ad56ae5ccb1a36e7c4f17f5ca31543887e00179468d10464/SQLAlchemy-1.3.7.tar.gz (5.9MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5.9MB 3.0MB/s eta 0:00:01\n    \u001b[?25hRequirement already satisfied: ipython-genutils>=0.1.0 in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython-sql) (0.2.0)\n    Requirement already satisfied: six in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython-sql) (1.12.0)\n    Collecting sqlparse (from ipython-sql)\n      Downloading https://files.pythonhosted.org/packages/ef/53/900f7d2a54557c6a37886585a91336520e5539e3ae2423ff1102daf4f3a7/sqlparse-0.3.0-py2.py3-none-any.whl\n    Requirement already satisfied: setuptools>=18.5 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from ipython>=1.0->ipython-sql) (40.8.0)\n    Requirement already satisfied: jedi>=0.10 in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython>=1.0->ipython-sql) (0.14.1)\n    Requirement already satisfied: decorator in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython>=1.0->ipython-sql) (4.4.0)\n    Requirement already satisfied: pickleshare in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython>=1.0->ipython-sql) (0.7.5)\n    Requirement already satisfied: traitlets>=4.2 in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython>=1.0->ipython-sql) (4.3.2)\n    Requirement already satisfied: prompt_toolkit<2.1.0,>=2.0.0 in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython>=1.0->ipython-sql) (2.0.9)\n    Requirement already satisfied: pygments in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython>=1.0->ipython-sql) (2.4.2)\n    Requirement already satisfied: backcall in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython>=1.0->ipython-sql) (0.1.0)\n    Requirement already satisfied: appnope in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython>=1.0->ipython-sql) (0.1.0)\n    Requirement already satisfied: pexpect in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython>=1.0->ipython-sql) (4.7.0)\n    Requirement already satisfied: parso>=0.5.0 in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from jedi>=0.10->ipython>=1.0->ipython-sql) (0.5.1)\n    Requirement already satisfied: wcwidth in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from prompt_toolkit<2.1.0,>=2.0.0->ipython>=1.0->ipython-sql) (0.1.7)\n    Requirement already satisfied: ptyprocess>=0.5 in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from pexpect->ipython>=1.0->ipython-sql) (0.6.0)\n    Installing collected packages: prettytable, sqlalchemy, sqlparse, ipython-sql\n      Running setup.py install for prettytable ... \u001b[?25ldone\n    \u001b[?25h  Running setup.py install for sqlalchemy ... \u001b[?25ldone\n    \u001b[?25hSuccessfully installed ipython-sql-0.3.9 prettytable-0.7.2 sqlalchemy-1.3.7 sqlparse-0.3.0\n\n\n\n```python\nimport sys\n!{sys.executable} -m pip install ipython-sql\n```\n\n    Collecting ipython-sql\n      Using cached https://files.pythonhosted.org/packages/ab/df/427e7cf05ffc67e78672ad57dce2436c1e825129033effe6fcaf804d0c60/ipython_sql-0.3.9-py2.py3-none-any.whl\n    Collecting prettytable (from ipython-sql)\n      Using cached https://files.pythonhosted.org/packages/ef/30/4b0746848746ed5941f052479e7c23d2b56d174b82f4fd34a25e389831f5/prettytable-0.7.2.tar.bz2\n    Requirement already satisfied: ipython-genutils>=0.1.0 in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython-sql) (0.2.0)\n    Collecting sqlalchemy>=0.6.7 (from ipython-sql)\n      Using cached https://files.pythonhosted.org/packages/c2/75/6217c626fa22ad56ae5ccb1a36e7c4f17f5ca31543887e00179468d10464/SQLAlchemy-1.3.7.tar.gz\n    Collecting sqlparse (from ipython-sql)\n      Using cached https://files.pythonhosted.org/packages/ef/53/900f7d2a54557c6a37886585a91336520e5539e3ae2423ff1102daf4f3a7/sqlparse-0.3.0-py2.py3-none-any.whl\n    Requirement already satisfied: ipython>=1.0 in /usr/local/Cellar/ipython/7.7.0/libexec/lib/python3.7/site-packages (from ipython-sql) (7.7.0)\n    Requirement already satisfied: six in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython-sql) (1.12.0)\n    Requirement already satisfied: setuptools>=18.5 in /usr/local/lib/python3.7/site-packages (from ipython>=1.0->ipython-sql) (41.0.1)\n    Requirement already satisfied: jedi>=0.10 in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython>=1.0->ipython-sql) (0.14.1)\n    Requirement already satisfied: decorator in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython>=1.0->ipython-sql) (4.4.0)\n    Requirement already satisfied: pickleshare in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython>=1.0->ipython-sql) (0.7.5)\n    Requirement already satisfied: traitlets>=4.2 in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython>=1.0->ipython-sql) (4.3.2)\n    Requirement already satisfied: prompt_toolkit<2.1.0,>=2.0.0 in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython>=1.0->ipython-sql) (2.0.9)\n    Requirement already satisfied: pygments in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython>=1.0->ipython-sql) (2.4.2)\n    Requirement already satisfied: backcall in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython>=1.0->ipython-sql) (0.1.0)\n    Requirement already satisfied: appnope in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython>=1.0->ipython-sql) (0.1.0)\n    Requirement already satisfied: pexpect in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from ipython>=1.0->ipython-sql) (4.7.0)\n    Requirement already satisfied: parso>=0.5.0 in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from jedi>=0.10->ipython>=1.0->ipython-sql) (0.5.1)\n    Requirement already satisfied: wcwidth in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from prompt_toolkit<2.1.0,>=2.0.0->ipython>=1.0->ipython-sql) (0.1.7)\n    Requirement already satisfied: ptyprocess>=0.5 in /usr/local/Cellar/ipython/7.7.0/libexec/vendor/lib/python3.7/site-packages (from pexpect->ipython>=1.0->ipython-sql) (0.6.0)\n    Building wheels for collected packages: prettytable, sqlalchemy\n      Building wheel for prettytable (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Stored in directory: /Users/mildo/Library/Caches/pip/wheels/80/34/1c/3967380d9676d162cb59513bd9dc862d0584e045a162095606\n      Building wheel for sqlalchemy (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Stored in directory: /Users/mildo/Library/Caches/pip/wheels/80/e0/68/3d11cc7209b5bd2c7d55cbb56c6bda843cc82f77c8387468ea\n    Successfully built prettytable sqlalchemy\n    Installing collected packages: prettytable, sqlalchemy, sqlparse, ipython-sql\n    Successfully installed ipython-sql-0.3.9 prettytable-0.7.2 sqlalchemy-1.3.7 sqlparse-0.3.0\n\n\n\n```python\n%load_ext sql\n```\n\n    The sql extension is already loaded. To reload it, use:\n      %reload_ext sql\n\n\n\n```python\n%sql sqlite://\n```\n\n\n\n\n    'Connected: @None'\n\n\n\n\n```sql\n%%sql\nCREATE TABLE classroom (name, age, totalmarks);\ninsert into classroom values ('raj',10,10);\ninsert into classroom values ('ale',30,30);\ninsert into classroom values ('ser',20,20);\n```\n\n     * sqlite://\n    Done.\n    1 rows affected.\n    1 rows affected.\n    1 rows affected.\n\n\n\n\n\n    []\n\n\n\n\n```python\n%sql select * from classroom\n```\n\n     * sqlite://\n    Done.\n\n\n\n\n\n<table>\n    <tr>\n        <th>name</th>\n        <th>age</th>\n        <th>totalmarks</th>\n    </tr>\n    <tr>\n        <td>raj</td>\n        <td>10</td>\n        <td>10</td>\n    </tr>\n    <tr>\n        <td>ale</td>\n        <td>30</td>\n        <td>30</td>\n    </tr>\n    <tr>\n        <td>ser</td>\n        <td>20</td>\n        <td>20</td>\n    </tr>\n</table>\n\n\n\n\n```python\n%lsmagic\n```\n\n\n\n\n    Available line magics:\n    %alias  %alias_magic  %autoawait  %autocall  %automagic  %autosave  %bookmark  %cat  %cd  %clear  %colors  %conda  %config  %connect_info  %cp  %debug  %dhist  %dirs  %doctest_mode  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %less  %lf  %lk  %ll  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %lx  %macro  %magic  %man  %matplotlib  %mkdir  %more  %mv  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %pip  %popd  %pprint  %precision  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %rep  %rerun  %reset  %reset_selective  %rm  %rmdir  %run  %save  %sc  %set_env  %sql  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode\n    \n    Available cell magics:\n    %%!  %%HTML  %%SVG  %%bash  %%capture  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%markdown  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%sql  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile\n    \n    Automagic is ON, % prefix IS NOT needed for line magics.\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "f02751d9b95a61c3cd4bf32711d0f12c45d12285", "size": 38247, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "titanic-ds-python/notebooks/ploting in notebook.ipynb", "max_stars_repo_name": "MildoCentaur/titanic-ds-python", "max_stars_repo_head_hexsha": "e0b6bbcb5b2e0267f55baaf0d64fbe37e2b108de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-23T16:59:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-23T16:59:11.000Z", "max_issues_repo_path": "titanic-ds-python/notebooks/ploting in notebook.ipynb", "max_issues_repo_name": "MildoCentaur/titanic-ds-python", "max_issues_repo_head_hexsha": "e0b6bbcb5b2e0267f55baaf0d64fbe37e2b108de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "titanic-ds-python/notebooks/ploting in notebook.ipynb", "max_forks_repo_name": "MildoCentaur/titanic-ds-python", "max_forks_repo_head_hexsha": "e0b6bbcb5b2e0267f55baaf0d64fbe37e2b108de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.9718309859, "max_line_length": 11632, "alphanum_fraction": 0.6960807384, "converted": true, "num_tokens": 5114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.11124121092722457, "lm_q1q2_score": 0.045732470918730235}}
{"text": "```python\nfrom IPython.core.display import HTML\ndef css_styling():\n    styles = open(\"./styles/custom.css\", \"r\").read()\n    return HTML(styles)\ncss_styling()\n```\n\n\n\n\n<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:100,300,400,500,700,800,900,100italic,300italic,400italic,500italic,700italic,800italic,900italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Arvo:400,700,400italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=PT+Mono' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Shadows+Into+Light' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Philosopher:400,700,400italic,700italic' rel='stylesheet' type='text/css'>\n\n<style>\n\n@font-face {\n    font-family: \"Computer Modern\";\n    src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');\n}\n\n#notebook_panel { /* main background */\n    background: #888;\n    color: #f6f6f6;\n}\n\ndiv #notebook { /* centre the content */\n    background: #fff;\n    color: #333;\n    width: 1200px;\n    margin: auto;\n    padding-left: 0em;\n}\n\n#notebook li { /* More space between bullet points */\nmargin-top:0.8em;\n}\n\ndiv.cell { /* set cell width to about 80 chars */\n    width: 1000px;\n}\n\ndiv.cell.border-box-sizing.code_cell.running {\n    /* draw border around running cells */\n    border: 3px solid #111;\n}\n\n\nh1 {\n    font-family: 'Philosopher', sans-serif;\n}\nh2 {\n    font-family: 'Philosopher', serif;\n}\nh3{\n    font-family: 'Philosopher', serif;\n    font-style: 'italic';\n    margin-top:12px;\n    margin-bottom: 3px;\n}\nh4{\n    font-family: 'Philosopher', serif;\n}\nh5 {\n    font-family: 'Alegreya Sans', sans-serif;\n}\nh6 {\n    font-family: 'PT Mono', sans-serif;\n}\n\ndiv.text_cell_render{\n    font-family: 'Arvo' sans-serif;\n    line-height: 130%;\n    font-size: 115%;\n    width:900px;\n    margin-left:auto;\n    margin-right:auto;\n}\n\n.CodeMirror{\n        font-family: \"PT Mono\";\n                    font-size: 100%;\n            }\n\n.text_cell_render h1 {\n    font-weight: 400;\n    font-size: 64pt;\n    line-height: 100%;\n    color: rgb(12,85,97);\n    margin-bottom: 0.1em;\n    margin-top: 0.1em;\n    display: block;\n}\n.text_cell_render h2 {\n    font-weight: 700;\n    font-size: 24pt;\n    line-height: 100%;\n    color: rgb(171,165,131);\n    margin-bottom: 0.1em;\n    margin-top: 0.1em;\n    display: block;\n}\n\n.text_cell_render h3 {\n    font-style: italic;\n    color: rgb(95,92,72);\n}\n\n.text_cell_render h5 {\n    font-weight: 300;\n    font-size: 16pt;\n    color: grey;\n    font-style: italic;\n    margin-bottom: .1em;\n    margin-top: 0.1em;\n    display: block;\n}\n\n.text_cell_render h6 {\n    font-weight: 300;\n    font-size: 10pt;\n    color: grey;\n    margin-bottom: 1px;\n    margin-top: 1px;\n}\ndiv.cell.code_cell {  /* Group area containing both code and output */\nbackground-color: rgba(171,165,131,0.3);\nborder-radius: 10px; /* rounded borders */\npadding: 1em;\n}\n\n</style>\n\n\n\n\n\n\n# Characteristics and scalar problems\n\nBased on earlier lessons **add explicit links** we expect that the solution of the Riemann problem obeys certain key rules.\n\n1. The solution can be written as ${\\bf q}(\\xi)$ where $\\xi = x/t$ is the self-similarity coordinate.\n2. This means that, in regions where the solution is smooth, it must obey\n\n$$\n  \\left( \\frac{\\partial {\\bf f}}{\\partial {\\bf q}} - \\xi \\textrm{Id} \\right) \\partial_{\\xi} {\\bf q} = 0.\n$$\n\n3. This means that the self-similarity coordinate matches an eigenvalue $\\lambda^{(p)}$ of the Jacobian matrix $\\partial {\\bf f} / \\partial {\\bf q}$, and that $\\partial_{\\xi} {\\bf q}$ is an eigenvector.\n4. When the solution is not continuous, the solution (if it exists) must obey the Rankine-Hugoniot condition\n\n$$\n  {\\bf f}({\\bf q}_r) - {\\bf f}({\\bf q}_l) = s \\left( {\\bf q}_r - {\\bf q}_l \\right)\n$$\nwhere $s$ is the speed of the shock, which is a constant.\n\n## Scalar case\n\nIf we consider the key conditions in the scalar case, we see that the Jacobian is simply $f'(q)$. For example, given Burgers' equation\n$$\n  \\partial_t q + \\partial_x \\left( \\tfrac{1}{2} q^2 \\right) = 0\n$$\nwe have $f'(q) = q$, and so the characteristic speed is given by the value of the data itself.\n\nWe know that the solution is constant along characteristic lines. Let us plot those lines and see where the solution is determined.\n\n\n```python\n%matplotlib inline\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n```\n\n\n```python\ndef df_burgers(q):\n    \"\"\"The derivative of the flux function, here defined for Burger's equation.\"\"\"\n    \n    return q\n```\n\n\n```python\ndef plot_characteristics(df, ql, qr):\n    \"\"\"Plot the characteristic lines for the initial data of a scalar Riemann problem.\"\"\"\n    \n    fig = plt.figure(figsize=(12,6))\n    ax1 = fig.add_subplot(121)\n\n    dq = np.max([abs(qr-ql), 0.1])\n    qmin = np.min([ql, qr])\n    qmax = np.max([ql, qr])\n    ax1.plot([-1.0, 0.0], [ql, ql], 'b-')\n    ax1.plot([0.0, 1.0], [qr, qr], 'g-')\n    ax1.set_xbound(-1.0, 1.0)\n    ax1.set_ybound(qmin - 0.1*dq, qmax + 0.1*dq)\n    ax1.set_xlabel(r\"$x$\")\n    ax1.set_ylabel(r\"$q(x, t=0)$\")\n    \n    ax2 = fig.add_subplot(122)\n    \n    slope_l = df(ql)\n    slope_r = df(qr)\n    left_edge = np.min([-1.0, -1.0 - slope_l])\n    right_edge = np.max([1.0, 1.0 - slope_r])\n    x_start_points_l = np.linspace(left_edge, 0.0, 20)\n    x_start_points_r = np.linspace(0.0, right_edge, 20) \n    x_end_points_l = x_start_points_l + slope_l\n    x_end_points_r = x_start_points_r + slope_r\n    \n    for xs, xe in zip(x_start_points_l, x_end_points_l):\n        ax2.plot([xs, xe], [0.0, 1.0], 'b-')\n    for xs, xe in zip(x_start_points_r, x_end_points_r):\n        ax2.plot([xs, xe], [0.0, 1.0], 'g-')\n        \n    x_fill = [x_end_points_l[-1], x_start_points_l[-1], x_end_points_r[0]]\n    t_fill = [1.0, 0.0, 1.0]\n    ax2.fill_between(x_fill, t_fill, 1.0, facecolor = 'red', alpha = 0.5)\n        \n    ax2.set_xbound(-1.0, 1.0)\n    ax2.set_ybound(0.0, 1.0)\n    ax2.set_xlabel(r\"$x$\")\n    ax2.set_ylabel(r\"$t$\")\n    \n    fig.tight_layout()\n```\n\n\n```python\nplot_characteristics(df_burgers, 0.1, -0.2)\n```\n\nIn the red shaded area the characteristics cross - there is characteristic focusing. The solution is not determined here as it could take the value of the initial data either from the left or from the right, which would give different values.\n\n\n```python\nplot_characteristics(df_burgers, -0.1, 0.2)\n```\n\nAlternatively the characteristics could separate. In this case the red shaded region is not determined by the initial data at all.\n\nTry modifying the initial data and see what the results are.\n\n\n```python\nfrom ipywidgets import interactive, FloatSlider\ndef interactive_characteristics(ql, qr):\n    return plot_characteristics(df_burgers, ql, qr)\ninteractive(interactive_characteristics, \n            ql = FloatSlider(min=-2.0, max=2.0, step=0.1, value=-0.1), \n            qr = FloatSlider(min=-2.0, max=2.0, step=0.1, value=0.2))\n```\n\n### Exercise\n\nTry repeating this characteristic analysis using different scalar problems, such as the LWR traffic equation\n\n\\begin{equation}\n  \\partial_t q + \\partial_x \\left( q (1 - q) \\right) = 0.\n\\end{equation}\n\n## Shocks\n\nWhen the characteristics cross, we have to find a weak solution that gives a unique self-similar solution. A shock satisfying the Rankine-Hugoniot conditions is such a solution.\n\nFor Burger's equation we can solve this explicitly. We have\n$$\n\\begin{align}\n  && {\\bf f}({\\bf q}_r) - {\\bf f}({\\bf q}_l) & = s \\left( {\\bf q}_r - {\\bf q}_l \\right) \\\\\n  \\implies && \\frac{1}{2} \\left( q_r^2 - q_l^2 \\right) & = s \\left( q_r - q_l \\right) \\\\\n  \\implies && s & = \\frac{1}{2} \\frac{ q_r^2 - q_l^2 }{ q_r - q_l } \\\\\n  && & = \\frac{q_r + q_l}{2}.\n\\end{align}\n$$\nGiven the shock speed, we then have the explicit solution to the Riemann problem for Burger's equation in the case of a shock, and when it occurs:\n$$\n  q_l > q_r \\quad \\implies \\quad q(x, t) = \\begin{cases} q_l & x < s t \\\\ q_r & x > s t \\end{cases}\n$$\nwhere $s = (q_r + q_l) / 2$.\n\n\n```python\ndef plot_shock_burgers(ql, qr):\n    \"\"\"Plot the characteristic lines for the shock solution to Burger's equation.\"\"\"\n    \n    assert(ql > qr)\n    \n    fig = plt.figure(figsize=(12,6))\n    ax1 = fig.add_subplot(121)\n\n    dq = np.max([abs(qr-ql), 0.1])\n    qmin = np.min([ql, qr])\n    qmax = np.max([ql, qr])\n    ax1.plot([-1.0, 0.0], [ql, ql], 'b-')\n    ax1.plot([0.0, 1.0], [qr, qr], 'g-')\n    ax1.set_xbound(-1.0, 1.0)\n    ax1.set_ybound(qmin - 0.1*dq, qmax + 0.1*dq)\n    ax1.set_xlabel(r\"$x$\")\n    ax1.set_ylabel(r\"$q(x, t=0)$\")\n    \n    ax2 = fig.add_subplot(122)\n    \n    slope_l = ql\n    slope_r = qr\n    s = 0.5 * (qr + ql)\n    ax2.plot([0.0, s], [0.0, 1.0], 'k-', linewidth=3)\n    \n    left_edge = np.min([-1.0, -1.0 - slope_l])\n    right_edge = np.max([1.0, 1.0 - slope_r])\n    x_start_points_l = np.linspace(left_edge, 0.0, 20)\n    x_start_points_r = np.linspace(0.0, right_edge, 20) \n    t_end_points_l = np.ones_like(x_start_points_l)\n    t_end_points_r = np.ones_like(x_start_points_r)\n    \n    # Look for intersections\n    t_end_points_l = np.minimum(t_end_points_l, x_start_points_l / (s - slope_l))\n    t_end_points_r = np.minimum(t_end_points_r, x_start_points_r / (s - slope_r))\n    x_end_points_l = x_start_points_l + slope_l * t_end_points_l\n    x_end_points_r = x_start_points_r + slope_r * t_end_points_r\n    \n    for xs, xe, te in zip(x_start_points_l, x_end_points_l, t_end_points_l):\n        ax2.plot([xs, xe], [0.0, te], 'b-')\n    for xs, xe, te in zip(x_start_points_r, x_end_points_r, t_end_points_r):\n        ax2.plot([xs, xe], [0.0, te], 'g-')\n    \n        \n    ax2.set_xbound(-1.0, 1.0)\n    ax2.set_ybound(0.0, 1.0)\n    ax2.set_xlabel(r\"$x$\")\n    ax2.set_ylabel(r\"$t$\")\n    \n    fig.tight_layout()\n```\n\n\n```python\ninteractive(plot_shock_burgers, \n            ql = FloatSlider(min=-2.0, max=2.0, step=0.1, value=0.1), \n            qr = FloatSlider(min=-2.0, max=2.0, step=0.1, value=-0.2))\n```\n\n### Exercise\n\nAgain, repeat this calculation for the LWR traffic equation.\n\n## Rarefactions\n\nWhen the characteristics do not cross, we have a rarefaction. Again, for Burger's equation we can solve for this explicitly.\n\nWe must have that $\\xi = x/t$ is an eigenvalue of the Jacobian $\\partial {\\bf f} / \\partial {\\bf q}$. For Burger's equation, that simply means that $\\xi = q$.\n\nThis holds true within the rarefaction wave - the gap in the $x-t$ plane where the characteristics do not reach. Therefore, we can write the solution in the rarefaction case, and when it holds, as:\n$$\n  q_l < q_r \\quad \\implies \\quad q(x, t) = \\begin{cases} q_l & x < \\xi_l t \\\\ \\frac{x}{t} & \\xi_l t < x < \\xi_r t \\\\ q_r & x > \\xi_r t \\end{cases}\n$$\nwhere the edges of the rarefaction wave (sometimes known as the *head* and *tail* of the rarefaction) are given by the characteristic speed there, which for Burger's equation means that $\\xi_l = q_l$ and $\\xi_r = q_r$.\n\n\n```python\ndef plot_rarefaction_burgers(ql, qr):\n    \"\"\"Plot the characteristic lines for the rarefaction solution to Burger's equation.\"\"\"\n    \n    assert(ql < qr)\n    \n    fig = plt.figure(figsize=(12,6))\n    ax1 = fig.add_subplot(121)\n\n    dq = np.max([abs(qr-ql), 0.1])\n    qmin = np.min([ql, qr])\n    qmax = np.max([ql, qr])\n    ax1.plot([-1.0, 0.0], [ql, ql], 'b-')\n    ax1.plot([0.0, 1.0], [qr, qr], 'g-')\n    ax1.set_xbound(-1.0, 1.0)\n    ax1.set_ybound(qmin - 0.1*dq, qmax + 0.1*dq)\n    ax1.set_xlabel(r\"$x$\")\n    ax1.set_ylabel(r\"$q(x, t=0)$\")\n    \n    ax2 = fig.add_subplot(122)\n    \n    slope_l = ql\n    slope_r = qr\n    \n    left_edge = np.min([-1.0, -1.0 - slope_l])\n    right_edge = np.max([1.0, 1.0 - slope_r])\n    x_start_points_l = np.linspace(left_edge, 0.0, 20)\n    x_start_points_r = np.linspace(0.0, right_edge, 20)\n    x_end_points_l = x_start_points_l + slope_l\n    x_end_points_r = x_start_points_r + slope_r\n    \n    # Rarefaction wave\n    xi_l = ql\n    xi_r = qr\n    xi = np.linspace(xi_l, xi_r, 7)\n    x_end_rarefaction = xi\n    \n    for xs, xe in zip(x_start_points_l, x_end_points_l):\n        ax2.plot([xs, xe], [0.0, 1.0], 'b-')\n    for xs, xe in zip(x_start_points_r, x_end_points_r):\n        ax2.plot([xs, xe], [0.0, 1.0], 'g-')\n    for xe in x_end_rarefaction:\n        ax2.plot([0.0, xe], [0.0, 1.0], 'r--')\n    \n        \n    ax2.set_xbound(-1.0, 1.0)\n    ax2.set_ybound(0.0, 1.0)\n    ax2.set_xlabel(r\"$x$\")\n    ax2.set_ylabel(r\"$t$\")\n    \n    fig.tight_layout()\n```\n\n\n```python\ninteractive(plot_rarefaction_burgers, \n            ql = FloatSlider(min=-2.0, max=2.0, step=0.1, value=-0.1), \n            qr = FloatSlider(min=-2.0, max=2.0, step=0.1, value=0.2))\n```\n\n### Exercise\n\nAgain, repeat this calculation for the LWR traffic equation.\n\n## Solution to the Riemann Problem\n\nFor Burger's equation, these two cases are sufficient for a complete solution of the Riemann problem. If $q_l < q_r$ then we have a rarefaction. If $q_l > q_r$ then we have a shock. If $q_l = q_r$ then the solution is trivial (although care should be taken in the code!).\n\n\n```python\ndef plot_solution_burgers(ql, qr):\n    \"\"\"Plot the characteristic lines for the full solution to Burger's equation.\"\"\"\n    \n    fig = plt.figure(figsize=(12,6))\n    ax1 = fig.add_subplot(121)\n\n    dq = np.max([abs(qr-ql), 0.1])\n    qmin = np.min([ql, qr])\n    qmax = np.max([ql, qr])\n    ax1.plot([-1.0, 0.0], [ql, ql], 'b-')\n    ax1.plot([0.0, 1.0], [qr, qr], 'g-')\n    ax1.set_xbound(-1.0, 1.0)\n    ax1.set_ybound(qmin - 0.1*dq, qmax + 0.1*dq)\n    ax1.set_xlabel(r\"$x$\")\n    ax1.set_ylabel(r\"$q(x, t=0)$\")\n    \n    ax2 = fig.add_subplot(122)\n    \n    slope_l = ql\n    slope_r = qr\n    \n    if (ql <= qr):\n        # Rarefaction case\n        \n        left_edge = np.min([-1.0, -1.0 - slope_l])\n        right_edge = np.max([1.0, 1.0 - slope_r])\n        x_start_points_l = np.linspace(left_edge, 0.0, 20)\n        x_start_points_r = np.linspace(0.0, right_edge, 20)\n        x_end_points_l = x_start_points_l + slope_l\n        x_end_points_r = x_start_points_r + slope_r\n    \n        # Rarefaction wave\n        xi_l = ql\n        xi_r = qr\n        xi = np.linspace(xi_l, xi_r, 7)\n        x_end_rarefaction = xi\n    \n        for xs, xe in zip(x_start_points_l, x_end_points_l):\n            ax2.plot([xs, xe], [0.0, 1.0], 'b-')\n        for xs, xe in zip(x_start_points_r, x_end_points_r):\n            ax2.plot([xs, xe], [0.0, 1.0], 'g-')\n        for xe in x_end_rarefaction:\n            ax2.plot([0.0, xe], [0.0, 1.0], 'r--')\n    \n    else:\n        # Shock case\n        s = 0.5 * (qr + ql)\n        ax2.plot([0.0, s], [0.0, 1.0], 'k-', linewidth=3)\n    \n        left_edge = np.min([-1.0, -1.0 - slope_l])\n        right_edge = np.max([1.0, 1.0 - slope_r])\n        x_start_points_l = np.linspace(left_edge, 0.0, 20)\n        x_start_points_r = np.linspace(0.0, right_edge, 20) \n        t_end_points_l = np.ones_like(x_start_points_l)\n        t_end_points_r = np.ones_like(x_start_points_r)\n    \n        # Look for intersections\n        t_end_points_l = np.minimum(t_end_points_l, x_start_points_l / (s - slope_l))\n        t_end_points_r = np.minimum(t_end_points_r, x_start_points_r / (s - slope_r))\n        x_end_points_l = x_start_points_l + slope_l * t_end_points_l\n        x_end_points_r = x_start_points_r + slope_r * t_end_points_r\n    \n        for xs, xe, te in zip(x_start_points_l, x_end_points_l, t_end_points_l):\n            ax2.plot([xs, xe], [0.0, te], 'b-')\n        for xs, xe, te in zip(x_start_points_r, x_end_points_r, t_end_points_r):\n            ax2.plot([xs, xe], [0.0, te], 'g-')\n        \n    ax2.set_xbound(-1.0, 1.0)\n    ax2.set_ybound(0.0, 1.0)\n    ax2.set_xlabel(r\"$x$\")\n    ax2.set_ylabel(r\"$t$\")\n    \n    fig.tight_layout()\n```\n\n\n```python\ninteractive(plot_solution_burgers, \n            ql = FloatSlider(min=-2.0, max=2.0, step=0.1, value=-0.1), \n            qr = FloatSlider(min=-2.0, max=2.0, step=0.1, value=0.2))\n```\n\n### Exercise\n\nAgain, repeat this exercise for the LWR traffic equation.\n\n## Going further\n\nFor many nonlinear problems this type of construction is sufficient. However, there are cases where it fails.\n\nConsider the *Buckley-Leverett* equation with flux\n$$\n  f(q) = \\frac{q^2}{q^2 + a (1 - q)^2}\n$$\nwhere $a \\in (0, 1)$ is a constant. We know that to solve within a rarefaction wave we need the derivative, which is\n$$\n  f'(q) = \\frac{2 a q (1 - q)}{ \\left[ q^2 + a (1 - q)^2 \\right]}.\n$$\nAs $q$ varies from $0$ to $1$ we see that the derivative has a maximum:\n\n\n```python\na = 0.5\nq = np.linspace(0.0, 1.0)\nf = q**2 / (q**2 + a * (1.0 - q)**2)\ndf = 2.0 * a * q * (1.0 - q) / (q**2 + a * (1.0 - q)**2)\nfig = plt.figure(figsize=(12,6))\nax1 = fig.add_subplot(121)\nax1.plot(q, f)\nax1.set_xlabel(r\"$q$\")\nax1.set_ylabel(r\"$f$\")\nax2 = fig.add_subplot(122)\nax2.plot(q, df)\nax2.set_xlabel(r\"$q$\")\nax2.set_ylabel(r\"$\\partial f / \\partial q$\")\nfig.tight_layout()\nplt.show()\n```\n\nThis is a problem, as within a rarefaction wave we have to solve $\\xi = f'(q)$. More formally we invert the derivative so that, given the characteristic coordinate $\\xi$ we have the solution\n\n\\begin{equation}\n  q = \\left( f' \\right)^{-1} (\\xi)\n\\end{equation}\n\nBut clearly here there are two possible solutions!\n\nThis will be a problem for any nonlinear problem where the second derivative, $f''$, vanishes. For problems such as these, we need to look again at the characteristic structure to see what an allowable solution should be.\n\n### Compound waves\n\nWe'll consider the Riemann problem for the Buckley-Leverett problem with $q_l = 1$ and $q_r = 0$.\n\nFirst let's look at the characteristic speeds of the left and right states. Given $f'$ as above we see that $\\xi_l = 0 = \\xi_r$. So the characteristics are parallel. At first glance we would not expect either a shock or a rarefaction, but a linear discontinuity. However, such a discontinuity would satisfy the Rankine-Hugoniot conditions with the same speed as the neighbouring characteristics - here 0. Let us check:\n$$\n\\begin{align}\n  && f_r - f_l & = s \\left( q_r - q_l \\right) \\\\\n  \\implies && s & = \\frac{0 - 1}{0 - 1} \\\\\n  && & = 1.\n\\end{align}\n$$\n\nThis cannot be right. If the left and right states were separated by a single discontinuity then it would have to travel to the right with speed 1, and points in the $x-t$ plane with $0 < x < t$ would therefore not be determined.\n\nHowever, neither can we have a single rarefaction. The left and right characteristics speeds would give the boundaries of such a rarefaction, and here they are both $0$.\n\nThe alternative is a *compound wave*: one that is made up of more than one piece, separating rarefactions with discontinuities satisfying the Rankine-Hugoniot conditions.\n\nTo construct a solution, let us start from the left state $q_l = 1$. We know that we want to connect to the state at $q_r = 0$, so we want $q$ to decrease as we move along the wave curve.\n\nRecall the behaviour of the flux and the characteristic speed $\\xi = f'(q)$:\n\n\n```python\na = 0.5\nq = np.linspace(0.0, 1.0)\nf = q**2 / (q**2 + a * (1.0 - q)**2)\ndf = 2.0 * a * q * (1.0 - q) / (q**2 + a * (1.0 - q)**2)\nfig = plt.figure(figsize=(12,6))\nax1 = fig.add_subplot(121)\nax1.plot(q, f)\nax1.set_xlabel(r\"$q$\")\nax1.set_ylabel(r\"$f$\")\nax2 = fig.add_subplot(122)\nax2.plot(q, df)\nax2.set_xlabel(r\"$q$\")\nax2.set_ylabel(r\"$\\partial f / \\partial q$\")\nfig.tight_layout()\nplt.show()\n```\n\nAs we move from the left state $q_l = 1$ to *smaller* values of $q$ we see that the characteristic coordinate $\\xi = f'(q)$ increases, as it should. Therefore the first section of the compound wave could be a rarefaction. However, we cannot get all the way to $q_r = 0$, as after the maximum in $f'$ the characteristic coordinate would start to decrease again.\n\nSo, at some point $q_*$ the wave must stop being a rarefaction and join to a discontinuity. In order for the characteristics to make sense, they must *join*, not intersect (as at a shock). That is, the shock speed must match the characteristic speed at $q_*$.\n\nSo our first attempt at a solution must try to find a state $q_*$ such that, when connected to the right state $q_r = 0$ using a discontinuity satisfying the Rankine-Hugoniot conditions, the shock speed is $s = f'(q_*)$. This requires that\n$$\n\\begin{align}\n  && \\frac{q_r^2}{q_r^2 + a (1 - q_r)^2} - \\frac{q_*^2}{q_*^2 + a (1 - q_*)^2} & = \\frac{2 a q_* (1 - q_*)}{\\left[ q_*^2 + a (1 - q_*)^2 \\right]^2} \\left( q_r - q_* \\right) \\\\\n  \\implies && \\frac{q_*^2}{q_*^2 + a (1 - q_*)^2} & = \\frac{2 a q_*^2 (1 - q_*)}{\\left[ q_*^2 + a (1 - q_*)^2 \\right]^2} \\\\\n  \\implies && q_*^2 + a (1 - q_*)^2 & = 2 a  (1 - q_*) \\\\\n  \\implies && q_* & = \\pm \\sqrt{\\frac{a}{1+a}}.\n\\end{align}\n$$\n\nThe characteristic picture for this shows a rarefaction attached to a *non-classical* shock. The shock is not the standard shock, as the characteristics only converge on it from one side.\n\n\n```python\ndef flux_buckley_leverett(q):\n    return q**2 / (q**2 + a * (1.0 - q)**2)\n\ndef df_buckley_leverett(q):\n    return 2.0 * a * q * (1.0 - q) / (q**2 + a * (1.0 - q)**2)\n\nfig = plt.figure(figsize=(12,6))\nax = fig.add_subplot(111)\n\na = 0.5\nql = 1.0\nqr = 0.0\nqs = np.sqrt(a / (1.0 + a))\ns = df_buckley_leverett(qs) # Shock speed matches characteristic speed on left!\n\nslope_l = df_buckley_leverett(ql)\nslope_r = df_buckley_leverett(qr)\n    \nleft_edge = np.min([-1.0, -1.0 - slope_l])\nright_edge = np.max([1.0, 1.0 - slope_r])\nx_start_points_l = np.linspace(left_edge, 0.0, 20)\nx_start_points_r = np.linspace(0.0, right_edge, 20)\nx_end_points_l = x_start_points_l + slope_l\nx_end_points_r = x_start_points_r + slope_r\n    \n# Rarefaction wave\nxi_l = df_buckley_leverett(ql)\nxi_r = df_buckley_leverett(qs)\nxi = np.linspace(xi_l, xi_r, 7)\nx_end_rarefaction = xi\n\n# Shock intersections\nt_end_points_r = np.ones_like(x_start_points_r)\nt_end_points_r = np.minimum(t_end_points_r, x_start_points_r / (s - slope_r))\n\nfor xs, xe in zip(x_start_points_l, x_end_points_l):\n    ax.plot([xs, xe], [0.0, 1.0], 'b-')\nfor xs, xe, te in zip(x_start_points_r, x_end_points_r, t_end_points_r):\n    ax.plot([xs, xe], [0.0, te], 'g-')\nfor xe in x_end_rarefaction:\n    ax.plot([0.0, xe], [0.0, 1.0], 'r--')\n# Shock\nax.plot([0.0, s], [0.0, 1.0], 'k-', linewidth=3)\n    \nax.set_xbound(-1.0, 1.0)\nax.set_ybound(0.0, 1.0)\nax.set_xlabel(r\"$x$\")\nax.set_ylabel(r\"$t$\")\n    \nfig.tight_layout()\n```\n\nWhilst this approach can be generalised (see e.g. the [thesis by Voss](http://134.130.184.8/opus/volltexte/2005/1210/)), we usually hope that the system is simple enough (i.e., $f''(q) \\ne 0$, or the equivalent for a system) that we only have to deal with shocks or rarefactions.\n", "meta": {"hexsha": "26edd7d9ca1bcda0aab8e2d139c5569780a7ce69", "size": 270843, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lesson_03_Characteristics.ipynb", "max_stars_repo_name": "IanHawke/RiemannPython", "max_stars_repo_head_hexsha": "57d6e372861a9c89b15755fb1d6ff9ea8116f6e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2015-08-24T01:24:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T18:26:24.000Z", "max_issues_repo_path": "Lesson_03_Characteristics.ipynb", "max_issues_repo_name": "IanHawke/RiemannPython", "max_issues_repo_head_hexsha": "57d6e372861a9c89b15755fb1d6ff9ea8116f6e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lesson_03_Characteristics.ipynb", "max_forks_repo_name": "IanHawke/RiemannPython", "max_forks_repo_head_hexsha": "57d6e372861a9c89b15755fb1d6ff9ea8116f6e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-07-31T17:41:21.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-11T13:50:22.000Z", "avg_line_length": 255.9952741021, "max_line_length": 65276, "alphanum_fraction": 0.9084229609, "converted": true, "num_tokens": 7315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20689404881588808, "lm_q2_score": 0.22000709463169618, "lm_q1q2_score": 0.045518158576571856}}
{"text": "```python\nfrom qiskit import IBMQ\nimport qiskit\nqiskit.__qiskit_version__\n```\n\n\n\n\n    {'qiskit-terra': '0.13.0',\n     'qiskit-aer': '0.5.0',\n     'qiskit-ignis': '0.3.0',\n     'qiskit-ibmq-provider': '0.6.0',\n     'qiskit-aqua': '0.6.5',\n     'qiskit': '0.18.0'}\n\n\n\n\n```python\nprovider = IBMQ.load_account()\nprovider = IBMQ.get_provider(hub='ibm-q-ncsu', group='nc-state', project='on-boarding')\n#provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')\nprovider.backends()\n```\n\n\n\n\n    [<IBMQSimulator('ibmq_qasm_simulator') from IBMQ(hub='ibm-q-ncsu', group='nc-state', project='on-boarding')>,\n     <IBMQBackend('ibmq_poughkeepsie') from IBMQ(hub='ibm-q-ncsu', group='nc-state', project='on-boarding')>,\n     <IBMQBackend('ibmq_vigo') from IBMQ(hub='ibm-q-ncsu', group='nc-state', project='on-boarding')>,\n     <IBMQBackend('ibmq_ourense') from IBMQ(hub='ibm-q-ncsu', group='nc-state', project='on-boarding')>,\n     <IBMQBackend('ibmq_valencia') from IBMQ(hub='ibm-q-ncsu', group='nc-state', project='on-boarding')>,\n     <IBMQBackend('ibmq_london') from IBMQ(hub='ibm-q-ncsu', group='nc-state', project='on-boarding')>,\n     <IBMQBackend('ibmq_burlington') from IBMQ(hub='ibm-q-ncsu', group='nc-state', project='on-boarding')>,\n     <IBMQBackend('ibmq_almaden') from IBMQ(hub='ibm-q-ncsu', group='nc-state', project='on-boarding')>,\n     <IBMQBackend('ibmq_rochester') from IBMQ(hub='ibm-q-ncsu', group='nc-state', project='on-boarding')>,\n     <IBMQBackend('ibmq_essex') from IBMQ(hub='ibm-q-ncsu', group='nc-state', project='on-boarding')>,\n     <IBMQBackend('ibmq_paris') from IBMQ(hub='ibm-q-ncsu', group='nc-state', project='on-boarding')>]\n\n\n\n\n```python\nimport math\nimport numpy as np\nimport random\nimport re\nimport qiskit.tools.jupyter\n\nfrom qiskit import *\nfrom qiskit.compiler import transpile\nfrom qiskit.visualization import plot_histogram\nfrom qiskit.tools.monitor import job_monitor\n\nfrom qiskit.transpiler import PassManager\nfrom qiskit.transpiler import CouplingMap, Layout\nfrom qiskit.transpiler.passes import StochasticSwap, BasicSwap\n\nfrom qiskit.tools.monitor import job_monitor, backend_monitor, backend_overview\n%matplotlib inline\n```\n\n\n```python\nfrom qiskit.transpiler import PassManagerConfig\nfrom qiskit.transpiler.coupling import CouplingMap\nfrom statistics import mean\nfrom passmanager import level_3_with_contant_pure\nfrom benchmark.suites.qpe import QPE\n```\n\n\n```python\ndevice = provider.get_backend('ibmq_almaden')\nbackend_monitor(device)\ndevice\n```\n\n    ibmq_almaden\n    ============\n    Configuration\n    -------------\n        n_qubits: 20\n        operational: True\n        status_msg: active\n        pending_jobs: 1\n        backend_version: 1.4.6\n        basis_gates: ['u1', 'u2', 'u3', 'cx', 'id']\n        local: False\n        simulator: False\n        dt: 3.5555555555555554e-09\n        conditional: False\n        coupling_map: [[0, 1], [1, 0], [1, 2], [1, 6], [2, 1], [2, 3], [3, 2], [3, 4], [3, 8], [4, 3], [5, 6], [5, 10], [6, 1], [6, 5], [6, 7], [7, 6], [7, 8], [7, 12], [8, 3], [8, 7], [8, 9], [9, 8], [9, 14], [10, 5], [10, 11], [11, 10], [11, 12], [11, 16], [12, 7], [12, 11], [12, 13], [13, 12], [13, 14], [13, 18], [14, 9], [14, 13], [15, 16], [16, 11], [16, 15], [16, 17], [17, 16], [17, 18], [18, 13], [18, 17], [18, 19], [19, 18]]\n        max_shots: 8192\n        online_date: 2019-09-13T04:00:00+00:00\n        u_channel_lo: [[{'q': 1, 'scale': [1.0, 0.0]}], [{'q': 0, 'scale': [1.0, 0.0]}], [{'q': 2, 'scale': [1.0, 0.0]}], [{'q': 6, 'scale': [1.0, 0.0]}], [{'q': 1, 'scale': [1.0, 0.0]}], [{'q': 3, 'scale': [1.0, 0.0]}], [{'q': 2, 'scale': [1.0, 0.0]}], [{'q': 4, 'scale': [1.0, 0.0]}], [{'q': 8, 'scale': [1.0, 0.0]}], [{'q': 3, 'scale': [1.0, 0.0]}], [{'q': 6, 'scale': [1.0, 0.0]}], [{'q': 10, 'scale': [1.0, 0.0]}], [{'q': 1, 'scale': [1.0, 0.0]}], [{'q': 5, 'scale': [1.0, 0.0]}], [{'q': 7, 'scale': [1.0, 0.0]}], [{'q': 6, 'scale': [1.0, 0.0]}], [{'q': 8, 'scale': [1.0, 0.0]}], [{'q': 12, 'scale': [1.0, 0.0]}], [{'q': 3, 'scale': [1.0, 0.0]}], [{'q': 7, 'scale': [1.0, 0.0]}], [{'q': 9, 'scale': [1.0, 0.0]}], [{'q': 8, 'scale': [1.0, 0.0]}], [{'q': 14, 'scale': [1.0, 0.0]}], [{'q': 5, 'scale': [1.0, 0.0]}], [{'q': 11, 'scale': [1.0, 0.0]}], [{'q': 10, 'scale': [1.0, 0.0]}], [{'q': 12, 'scale': [1.0, 0.0]}], [{'q': 16, 'scale': [1.0, 0.0]}], [{'q': 7, 'scale': [1.0, 0.0]}], [{'q': 11, 'scale': [1.0, 0.0]}], [{'q': 13, 'scale': [1.0, 0.0]}], [{'q': 12, 'scale': [1.0, 0.0]}], [{'q': 14, 'scale': [1.0, 0.0]}], [{'q': 18, 'scale': [1.0, 0.0]}], [{'q': 9, 'scale': [1.0, 0.0]}], [{'q': 13, 'scale': [1.0, 0.0]}], [{'q': 16, 'scale': [1.0, 0.0]}], [{'q': 11, 'scale': [1.0, 0.0]}], [{'q': 15, 'scale': [1.0, 0.0]}], [{'q': 17, 'scale': [1.0, 0.0]}], [{'q': 16, 'scale': [1.0, 0.0]}], [{'q': 18, 'scale': [1.0, 0.0]}], [{'q': 13, 'scale': [1.0, 0.0]}], [{'q': 17, 'scale': [1.0, 0.0]}], [{'q': 19, 'scale': [1.0, 0.0]}], [{'q': 18, 'scale': [1.0, 0.0]}]]\n        url: None\n        uchannels_enabled: True\n        dtm: 3.5555555555555554e-09\n        n_registers: 1\n        rep_times: [0]\n        allow_q_circuit: False\n        meas_lo_range: [[6764856891.0, 7764856891.0], [6570226896.0, 7570226896.0], [6722414155.0, 7722414155.0], [6630569974.0, 7630569974.0], [6715856761.0, 7715856761.0], [6479389665.0, 7479389665.0], [6640246272.0, 7640246272.0], [6534825806.0, 7534825806.0], [6797209412.0, 7797209412.0], [6597757684.0, 7597757684.0], [6786899984.0, 7786899984.0], [6554657786.0, 7554657786.0], [6703657122.0, 7703657122.0], [6653318307.0, 7653318307.0], [6682410566.0, 7682410566.0], [6475843032.0, 7475843032.0], [6633222076.0, 7633222076.0], [6518386448.0, 7518386448.0], [6807007960.0, 7807007960.0], [6604129811.0, 7604129811.0]]\n        n_uchannels: 46\n        allow_object_storage: True\n        open_pulse: True\n        meas_map: [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]]\n        credits_required: True\n        qubit_lo_range: [[4357152165.037528, 5357152165.037528], [4471766555.388986, 5471766555.388986], [4571111439.9388, 5571111439.9388], [4426983341.092592, 5426983341.092592], [4219733314.5663195, 5219733314.566319], [4275034867.93258, 5275034867.93258], [4413664104.357497, 5413664104.357497], [4289295570.149339, 5289295570.14934], [4357610541.397088, 5357610541.397088], [4159205763.5126843, 5159205763.512684], [4479225971.88113, 5479225971.88113], [4422131122.694569, 5422131122.694569], [4334019900.794435, 5334019900.794435], [4443847604.774473, 5443847604.774473], [4250449580.438109, 5250449580.438108], [4156964331.284013, 5156964331.284013], [4349296297.171849, 5349296297.171849], [4285018344.010058, 5285018344.010057], [4326325747.532302, 5326325747.532302], [4213149144.2146716, 5213149144.214672]]\n        backend_name: ibmq_almaden\n        hamiltonian: {'description': 'Qubits are modelled as a two level system. Qubits are coupled through resonator buses. The provided Hamiltonian has been projected into the zero excitation subspace of the resonator buses leading to an effective qubit-qubit flip-flop interaction. The qubit resonance frequencies in the Hamiltonian are the cavity dressed frequencies and not exactly what is returned by the backend defaults, which also includes the dressing due to the qubit-qubit interactions.\\nWarning: Currently not all system Hamiltonian information is available to the public, missing values have been replaced with 0.\\n', 'h_latex': '\\\\begin{align} \\\\mathcal{H}/\\\\hbar = & \\\\sum_{i=0}^{19}\\\\left(\\\\frac{\\\\omega_{q,i}}{2} (\\\\mathbb{1}_i-\\\\sigma_i^{z})+ \\\\Omega_{d,i}D_i(t)\\\\sigma_i^{X}\\\\right) \\\\\\\\ & + J_{11,16}(\\\\sigma_{11}^{+}\\\\sigma_{16}^{-}+\\\\sigma_{11}^{-}\\\\sigma_{16}^{+}) + J_{10,11}(\\\\sigma_{10}^{+}\\\\sigma_{11}^{-}+\\\\sigma_{10}^{-}\\\\sigma_{11}^{+}) + J_{7,12}(\\\\sigma_{7}^{+}\\\\sigma_{12}^{-}+\\\\sigma_{7}^{-}\\\\sigma_{12}^{+}) + J_{5,6}(\\\\sigma_{5}^{+}\\\\sigma_{6}^{-}+\\\\sigma_{5}^{-}\\\\sigma_{6}^{+}) \\\\\\\\ & + J_{8,9}(\\\\sigma_{8}^{+}\\\\sigma_{9}^{-}+\\\\sigma_{8}^{-}\\\\sigma_{9}^{+}) + J_{15,16}(\\\\sigma_{15}^{+}\\\\sigma_{16}^{-}+\\\\sigma_{15}^{-}\\\\sigma_{16}^{+}) + J_{1,6}(\\\\sigma_{1}^{+}\\\\sigma_{6}^{-}+\\\\sigma_{1}^{-}\\\\sigma_{6}^{+}) + J_{18,19}(\\\\sigma_{18}^{+}\\\\sigma_{19}^{-}+\\\\sigma_{18}^{-}\\\\sigma_{19}^{+}) \\\\\\\\ & + J_{1,2}(\\\\sigma_{1}^{+}\\\\sigma_{2}^{-}+\\\\sigma_{1}^{-}\\\\sigma_{2}^{+}) + J_{16,17}(\\\\sigma_{16}^{+}\\\\sigma_{17}^{-}+\\\\sigma_{16}^{-}\\\\sigma_{17}^{+}) + J_{6,7}(\\\\sigma_{6}^{+}\\\\sigma_{7}^{-}+\\\\sigma_{6}^{-}\\\\sigma_{7}^{+}) + J_{12,13}(\\\\sigma_{12}^{+}\\\\sigma_{13}^{-}+\\\\sigma_{12}^{-}\\\\sigma_{13}^{+}) \\\\\\\\ & + J_{3,4}(\\\\sigma_{3}^{+}\\\\sigma_{4}^{-}+\\\\sigma_{3}^{-}\\\\sigma_{4}^{+}) + J_{9,14}(\\\\sigma_{9}^{+}\\\\sigma_{14}^{-}+\\\\sigma_{9}^{-}\\\\sigma_{14}^{+}) + J_{2,3}(\\\\sigma_{2}^{+}\\\\sigma_{3}^{-}+\\\\sigma_{2}^{-}\\\\sigma_{3}^{+}) + J_{11,12}(\\\\sigma_{11}^{+}\\\\sigma_{12}^{-}+\\\\sigma_{11}^{-}\\\\sigma_{12}^{+}) \\\\\\\\ & + J_{17,18}(\\\\sigma_{17}^{+}\\\\sigma_{18}^{-}+\\\\sigma_{17}^{-}\\\\sigma_{18}^{+}) + J_{0,1}(\\\\sigma_{0}^{+}\\\\sigma_{1}^{-}+\\\\sigma_{0}^{-}\\\\sigma_{1}^{+}) + J_{5,10}(\\\\sigma_{5}^{+}\\\\sigma_{10}^{-}+\\\\sigma_{5}^{-}\\\\sigma_{10}^{+}) + J_{13,14}(\\\\sigma_{13}^{+}\\\\sigma_{14}^{-}+\\\\sigma_{13}^{-}\\\\sigma_{14}^{+}) \\\\\\\\ & + J_{3,8}(\\\\sigma_{3}^{+}\\\\sigma_{8}^{-}+\\\\sigma_{3}^{-}\\\\sigma_{8}^{+}) + J_{13,18}(\\\\sigma_{13}^{+}\\\\sigma_{18}^{-}+\\\\sigma_{13}^{-}\\\\sigma_{18}^{+}) + J_{7,8}(\\\\sigma_{7}^{+}\\\\sigma_{8}^{-}+\\\\sigma_{7}^{-}\\\\sigma_{8}^{+}) \\\\\\\\ & + \\\\Omega_{d,0}(U_{0}^{(0,1)}(t))\\\\sigma_{0}^{X} + \\\\Omega_{d,1}(U_{1}^{(1,0)}(t)+U_{3}^{(1,6)}(t)+U_{2}^{(1,2)}(t))\\\\sigma_{1}^{X} \\\\\\\\ & + \\\\Omega_{d,2}(U_{4}^{(2,1)}(t)+U_{5}^{(2,3)}(t))\\\\sigma_{2}^{X} + \\\\Omega_{d,3}(U_{7}^{(3,4)}(t)+U_{6}^{(3,2)}(t)+U_{8}^{(3,8)}(t))\\\\sigma_{3}^{X} \\\\\\\\ & + \\\\Omega_{d,4}(U_{9}^{(4,3)}(t))\\\\sigma_{4}^{X} + \\\\Omega_{d,5}(U_{11}^{(5,10)}(t)+U_{10}^{(5,6)}(t))\\\\sigma_{5}^{X} \\\\\\\\ & + \\\\Omega_{d,6}(U_{14}^{(6,7)}(t)+U_{12}^{(6,1)}(t)+U_{13}^{(6,5)}(t))\\\\sigma_{6}^{X} + \\\\Omega_{d,7}(U_{15}^{(7,6)}(t)+U_{16}^{(7,8)}(t)+U_{17}^{(7,12)}(t))\\\\sigma_{7}^{X} \\\\\\\\ & + \\\\Omega_{d,8}(U_{19}^{(8,7)}(t)+U_{18}^{(8,3)}(t)+U_{20}^{(8,9)}(t))\\\\sigma_{8}^{X} + \\\\Omega_{d,9}(U_{21}^{(9,8)}(t)+U_{22}^{(9,14)}(t))\\\\sigma_{9}^{X} \\\\\\\\ & + \\\\Omega_{d,10}(U_{24}^{(10,11)}(t)+U_{23}^{(10,5)}(t))\\\\sigma_{10}^{X} + \\\\Omega_{d,11}(U_{25}^{(11,10)}(t)+U_{26}^{(11,12)}(t)+U_{27}^{(11,16)}(t))\\\\sigma_{11}^{X} \\\\\\\\ & + \\\\Omega_{d,12}(U_{28}^{(12,7)}(t)+U_{30}^{(12,13)}(t)+U_{29}^{(12,11)}(t))\\\\sigma_{12}^{X} + \\\\Omega_{d,13}(U_{31}^{(13,12)}(t)+U_{32}^{(13,14)}(t)+U_{33}^{(13,18)}(t))\\\\sigma_{13}^{X} \\\\\\\\ & + \\\\Omega_{d,14}(U_{34}^{(14,9)}(t)+U_{35}^{(14,13)}(t))\\\\sigma_{14}^{X} + \\\\Omega_{d,15}(U_{36}^{(15,16)}(t))\\\\sigma_{15}^{X} \\\\\\\\ & + \\\\Omega_{d,16}(U_{38}^{(16,15)}(t)+U_{39}^{(16,17)}(t)+U_{37}^{(16,11)}(t))\\\\sigma_{16}^{X} + \\\\Omega_{d,17}(U_{41}^{(17,18)}(t)+U_{40}^{(17,16)}(t))\\\\sigma_{17}^{X} \\\\\\\\ & + \\\\Omega_{d,18}(U_{42}^{(18,13)}(t)+U_{43}^{(18,17)}(t)+U_{44}^{(18,19)}(t))\\\\sigma_{18}^{X} + \\\\Omega_{d,19}(U_{45}^{(19,18)}(t))\\\\sigma_{19}^{X} \\\\\\\\ \\\\end{align}', 'h_str': ['_SUM[i,0,19,wq{i}/2*(I{i}-Z{i})]', '_SUM[i,0,19,omegad{i}*X{i}||D{i}]', 'jq11q16*Sp11*Sm16', 'jq11q16*Sm11*Sp16', 'jq10q11*Sp10*Sm11', 'jq10q11*Sm10*Sp11', 'jq7q12*Sp7*Sm12', 'jq7q12*Sm7*Sp12', 'jq5q6*Sp5*Sm6', 'jq5q6*Sm5*Sp6', 'jq8q9*Sp8*Sm9', 'jq8q9*Sm8*Sp9', 'jq15q16*Sp15*Sm16', 'jq15q16*Sm15*Sp16', 'jq1q6*Sp1*Sm6', 'jq1q6*Sm1*Sp6', 'jq18q19*Sp18*Sm19', 'jq18q19*Sm18*Sp19', 'jq1q2*Sp1*Sm2', 'jq1q2*Sm1*Sp2', 'jq16q17*Sp16*Sm17', 'jq16q17*Sm16*Sp17', 'jq6q7*Sp6*Sm7', 'jq6q7*Sm6*Sp7', 'jq12q13*Sp12*Sm13', 'jq12q13*Sm12*Sp13', 'jq3q4*Sp3*Sm4', 'jq3q4*Sm3*Sp4', 'jq9q14*Sp9*Sm14', 'jq9q14*Sm9*Sp14', 'jq2q3*Sp2*Sm3', 'jq2q3*Sm2*Sp3', 'jq11q12*Sp11*Sm12', 'jq11q12*Sm11*Sp12', 'jq17q18*Sp17*Sm18', 'jq17q18*Sm17*Sp18', 'jq0q1*Sp0*Sm1', 'jq0q1*Sm0*Sp1', 'jq5q10*Sp5*Sm10', 'jq5q10*Sm5*Sp10', 'jq13q14*Sp13*Sm14', 'jq13q14*Sm13*Sp14', 'jq3q8*Sp3*Sm8', 'jq3q8*Sm3*Sp8', 'jq13q18*Sp13*Sm18', 'jq13q18*Sm13*Sp18', 'jq7q8*Sp7*Sm8', 'jq7q8*Sm7*Sp8', 'omegad1*X0||U0', 'omegad0*X1||U1', 'omegad6*X1||U3', 'omegad2*X1||U2', 'omegad1*X2||U4', 'omegad3*X2||U5', 'omegad4*X3||U7', 'omegad2*X3||U6', 'omegad8*X3||U8', 'omegad3*X4||U9', 'omegad10*X5||U11', 'omegad6*X5||U10', 'omegad7*X6||U14', 'omegad1*X6||U12', 'omegad5*X6||U13', 'omegad6*X7||U15', 'omegad8*X7||U16', 'omegad12*X7||U17', 'omegad7*X8||U19', 'omegad3*X8||U18', 'omegad9*X8||U20', 'omegad8*X9||U21', 'omegad14*X9||U22', 'omegad11*X10||U24', 'omegad5*X10||U23', 'omegad10*X11||U25', 'omegad12*X11||U26', 'omegad16*X11||U27', 'omegad7*X12||U28', 'omegad13*X12||U30', 'omegad11*X12||U29', 'omegad12*X13||U31', 'omegad14*X13||U32', 'omegad18*X13||U33', 'omegad9*X14||U34', 'omegad13*X14||U35', 'omegad16*X15||U36', 'omegad15*X16||U38', 'omegad17*X16||U39', 'omegad11*X16||U37', 'omegad18*X17||U41', 'omegad16*X17||U40', 'omegad13*X18||U42', 'omegad17*X18||U43', 'omegad19*X18||U44', 'omegad18*X19||U45'], 'osc': {}, 'qub': {'0': 2, '1': 2, '2': 2, '3': 2, '4': 2, '5': 2, '6': 2, '7': 2, '8': 2, '9': 2, '10': 2, '11': 2, '12': 2, '13': 2, '14': 2, '15': 2, '16': 2, '17': 2, '18': 2, '19': 2}, 'vars': {'jq0q1': 0, 'jq10q11': 0, 'jq11q12': 0, 'jq11q16': 0, 'jq12q13': 0, 'jq13q14': 0, 'jq13q18': 0, 'jq15q16': 0, 'jq16q17': 0, 'jq17q18': 0, 'jq18q19': 0, 'jq1q2': 0, 'jq1q6': 0, 'jq2q3': 0, 'jq3q4': 0, 'jq3q8': 0, 'jq5q10': 0, 'jq5q6': 0, 'jq6q7': 0, 'jq7q12': 0, 'jq7q8': 0, 'jq8q9': 0, 'jq9q14': 0, 'omegad0': 0, 'omegad1': 0, 'omegad10': 0, 'omegad11': 0, 'omegad12': 0, 'omegad13': 0, 'omegad14': 0, 'omegad15': 0, 'omegad16': 0, 'omegad17': 0, 'omegad18': 0, 'omegad19': 0, 'omegad2': 0, 'omegad3': 0, 'omegad4': 0, 'omegad5': 0, 'omegad6': 0, 'omegad7': 0, 'omegad8': 0, 'omegad9': 0, 'wq0': 30.518387118099312, 'wq1': 31.23853057154694, 'wq10': 31.285399467650514, 'wq11': 30.926661950125876, 'wq12': 30.373042815285313, 'wq13': 31.063110631253963, 'wq14': 29.847955006306155, 'wq15': 29.260569862383118, 'wq16': 30.46902724455054, 'wq17': 30.06515695366879, 'wq18': 30.324699024557493, 'wq19': 29.613589453475672, 'wq2': 31.862732890493785, 'wq3': 30.957149337471563, 'wq4': 29.65495901588911, 'wq5': 30.002428923464205, 'wq6': 30.87346210491477, 'wq7': 30.09203155810261, 'wq8': 30.52126718170686, 'wq9': 29.27465319642934}}\n        memory: True\n        acquisition_latency: []\n        allow_q_object: True\n        description: 20 qubit device Almaden\n        discriminators: ['linear_discriminator', 'quadratic_discriminator']\n        meas_kernels: ['boxcar']\n        quantum_volume: 8\n        max_experiments: 900\n        meas_levels: [1, 2]\n        conditional_latency: []\n        sample_name: HexV2\n    \n    Qubits [Name / Freq / T1 / T2 / U1 err / U2 err / U3 err / Readout err]\n    -----------------------------------------------------------------------\n        Q0 / 4.85715 GHz / 72.63238 \u00b5s / 102.04211 \u00b5s / 0.0 / 0.00068 / 0.00137 / 0.03667\n        Q1 / 4.97177 GHz / 83.68511 \u00b5s / 20.15841 \u00b5s / 0.0 / 0.00055 / 0.0011 / 0.045\n        Q2 / 5.07111 GHz / 96.78522 \u00b5s / 19.83045 \u00b5s / 0.0 / 0.00047 / 0.00094 / 0.12833\n        Q3 / 4.92698 GHz / 93.15195 \u00b5s / 138.82031 \u00b5s / 0.0 / 0.00036 / 0.00073 / 0.015\n        Q4 / 4.71973 GHz / 131.55839 \u00b5s / 162.34797 \u00b5s / 0.0 / 0.00026 / 0.00052 / 0.01667\n        Q5 / 4.77503 GHz / 115.38173 \u00b5s / 119.84606 \u00b5s / 0.0 / 0.00066 / 0.00132 / 0.08167\n        Q6 / 4.91366 GHz / 69.34857 \u00b5s / 35.02859 \u00b5s / 0.0 / 0.00061 / 0.00122 / 0.05667\n        Q7 / 4.7893 GHz / 21.41658 \u00b5s / 14.68001 \u00b5s / 0.0 / 0.00095 / 0.00189 / 0.04833\n        Q8 / 4.85761 GHz / 112.82705 \u00b5s / 96.60506 \u00b5s / 0.0 / 0.00028 / 0.00057 / 0.02833\n        Q9 / 4.65921 GHz / 106.30635 \u00b5s / 127.34094 \u00b5s / 0.0 / 0.0004 / 0.00079 / 0.02833\n        Q10 / 4.97923 GHz / 131.83902 \u00b5s / 13.37327 \u00b5s / 0.0 / 0.00049 / 0.00098 / 0.03667\n        Q11 / 4.92213 GHz / 56.03556 \u00b5s / 84.2544 \u00b5s / 0.0 / 0.00066 / 0.00132 / 0.00833\n        Q12 / 4.83402 GHz / 112.74639 \u00b5s / 37.51677 \u00b5s / 0.0 / 0.00084 / 0.00167 / 0.01667\n        Q13 / 4.94385 GHz / 143.49342 \u00b5s / 13.9653 \u00b5s / 0.0 / 0.00088 / 0.00176 / 0.025\n        Q14 / 4.75045 GHz / 124.95256 \u00b5s / 16.51211 \u00b5s / 0.0 / 0.0007 / 0.0014 / 0.01833\n        Q15 / 4.65696 GHz / 117.64104 \u00b5s / 151.27719 \u00b5s / 0.0 / 0.00037 / 0.00075 / 0.015\n        Q16 / 4.8493 GHz / 86.06115 \u00b5s / 111.01472 \u00b5s / 0.0 / 0.00037 / 0.00074 / 0.03\n        Q17 / 4.78502 GHz / 115.56301 \u00b5s / 108.73886 \u00b5s / 0.0 / 0.00057 / 0.00114 / 0.025\n        Q18 / 4.82633 GHz / 95.36256 \u00b5s / 12.55396 \u00b5s / 0.0 / 0.00164 / 0.00329 / 0.06\n        Q19 / 4.71315 GHz / 143.72866 \u00b5s / 195.37614 \u00b5s / 0.0 / 0.00084 / 0.00169 / 0.06667\n    \n    Multi-Qubit Gates [Name / Type / Gate Error]\n    --------------------------------------------\n        cx0_1 / cx / 0.00997\n        cx1_0 / cx / 0.00997\n        cx1_2 / cx / 0.0123\n        cx1_6 / cx / 0.01653\n        cx2_1 / cx / 0.0123\n        cx2_3 / cx / 0.0155\n        cx3_2 / cx / 0.0155\n        cx3_4 / cx / 0.01163\n        cx3_8 / cx / 0.01085\n        cx4_3 / cx / 0.01163\n        cx5_6 / cx / 0.01164\n        cx5_10 / cx / 0.00818\n        cx6_1 / cx / 0.01653\n        cx6_5 / cx / 0.01164\n        cx6_7 / cx / 0.03835\n        cx7_6 / cx / 0.03835\n        cx7_8 / cx / 0.01683\n        cx7_12 / cx / 0.02122\n        cx8_3 / cx / 0.01085\n        cx8_7 / cx / 0.01683\n        cx8_9 / cx / 0.01919\n        cx9_8 / cx / 0.01919\n        cx9_14 / cx / 0.01158\n        cx10_5 / cx / 0.00818\n        cx10_11 / cx / 0.01402\n        cx11_10 / cx / 0.01402\n        cx11_12 / cx / 0.01117\n        cx11_16 / cx / 0.01005\n        cx12_7 / cx / 0.02122\n        cx12_11 / cx / 0.01117\n        cx12_13 / cx / 0.01909\n        cx13_12 / cx / 0.01909\n        cx13_14 / cx / 0.0105\n        cx13_18 / cx / 0.02128\n        cx14_9 / cx / 0.01158\n        cx14_13 / cx / 0.0105\n        cx15_16 / cx / 0.01165\n        cx16_11 / cx / 0.01005\n        cx16_15 / cx / 0.01165\n        cx16_17 / cx / 0.0093\n        cx17_16 / cx / 0.0093\n        cx17_18 / cx / 0.01675\n        cx18_13 / cx / 0.02128\n        cx18_17 / cx / 0.01675\n        cx18_19 / cx / 0.01621\n        cx19_18 / cx / 0.01621\n\n\n\n    VBox(children=(HTML(value=\"<h1 style='color:#ffffff;background-color:#000000;padding-top: 1%;padding-bottom: 1\u2026\n\n\n\n\n\n    <IBMQBackend('ibmq_almaden') from IBMQ(hub='ibm-q-ncsu', group='nc-state', project='on-boarding')>\n\n\n\n\n```python\nsimulator = provider.get_backend('ibmq_qasm_simulator')\n```\n\n\n```python\nseed = 0\npmconfig = PassManagerConfig(\n            initial_layout=None,\n            basis_gates=['u1', 'u2', 'u3', 'cx', 'id'],\n            coupling_map=CouplingMap(device.configuration().coupling_map),\n            backend_properties=device.properties(),\n            seed_transpiler=seed)\n```\n\n\n```python\npm = level_3_with_contant_pure(pmconfig)\n```\n\n\n```python\nQCList = []\nfor i in range(3, 7):\n    QCList.append(transpile(QPE(nbits = i),device, optimization_level = 3))\n    QCList.append(pm.run(QPE(nbits = i)))\n```\n\n\n```python\nQCList[0].count_ops()\n```\n\n\n\n\n    OrderedDict([('cx', 28),\n                 ('u2', 13),\n                 ('u1', 11),\n                 ('u3', 3),\n                 ('measure', 3),\n                 ('barrier', 1)])\n\n\n\n\n```python\nQCList[1].count_ops()\n```\n\n\n\n\n    OrderedDict([('cx', 20),\n                 ('u1', 15),\n                 ('u2', 8),\n                 ('measure', 3),\n                 ('barrier', 1)])\n\n\n\n\n```python\nfrom qiskit.qobj.utils import MeasLevel, MeasReturnType\nfrom qiskit.pulse import Schedule\nfrom qiskit.exceptions import QiskitError\n```\n\n\n```python\nqobj = assemble(QCList,\n            qobj_id=None, qobj_header=None,\n            shots=8192,\n            memory=False, max_credits=10, seed_simulator=None,\n            default_qubit_los=None, default_meas_los=None,  # schedule run options\n            schedule_los=None, meas_level=MeasLevel.CLASSIFIED,\n            meas_return=MeasReturnType.AVERAGE,\n            memory_slots=None, memory_slot_size=100, rep_time=None, parameter_binds=None,\n            backend=device,\n            )\n```\n\n\n```python\njob2 = device.run(qobj)\njob_monitor(job2)\nres2 = job2.result()\n```\n\n    Job Status: job has successfully run\n\n\n\n```python\nplot_histogram(res2.get_counts()[0])\n```\n\n\n```python\nplot_histogram(res2.get_counts()[1])\n```\n\n\n```python\nplot_histogram(res2.get_counts()[1]).savefig('almadenour.pdf')\n```\n\n\n```python\nplot_histogram(res2.get_counts()[0]).savefig('almadenlevel3.pdf')\n```\n\n\n```python\n#level3 result\nres2.get_counts()[0]\n```\n\n\n\n\n    {'111': 1089,\n     '000': 655,\n     '101': 621,\n     '100': 550,\n     '001': 960,\n     '110': 699,\n     '010': 1160,\n     '011': 2458}\n\n\n\n\n```python\n#our result\nres2.get_counts()[1]\n```\n\n\n\n\n    {'111': 2935,\n     '000': 532,\n     '101': 1138,\n     '100': 746,\n     '001': 683,\n     '110': 1025,\n     '010': 360,\n     '011': 773}\n\n\n", "meta": {"hexsha": "a062a26aaafb0146f0fbd2d20acb7fae126fd3f1", "size": 63485, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "QPE_almaden.ipynb", "max_stars_repo_name": "revilooliver/rp", "max_stars_repo_head_hexsha": "9618b640039f911e98e0fa0f5766951bac7e16af", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-12-16T07:58:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T16:41:49.000Z", "max_issues_repo_path": "QPE_almaden.ipynb", "max_issues_repo_name": "revilooliver/rp", "max_issues_repo_head_hexsha": "9618b640039f911e98e0fa0f5766951bac7e16af", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QPE_almaden.ipynb", "max_forks_repo_name": "revilooliver/rp", "max_forks_repo_head_hexsha": "9618b640039f911e98e0fa0f5766951bac7e16af", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-19T17:31:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-19T17:31:49.000Z", "avg_line_length": 117.5648148148, "max_line_length": 18528, "alphanum_fraction": 0.7720406395, "converted": true, "num_tokens": 9430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.1037486296375442, "lm_q1q2_score": 0.04542358805621299}}
{"text": "\n\n# Summary on the Deep Learning Study, Week 1\n\n- Date: January 15th, 2018\n- Lectures Covered\n    - \uc218\uc5c5\uc5d0 \uc0ac\uc6a9\ud558\ub294 \ucf54\ub4dc https://github.com/hunkim/DeepLearningZeroToAll\n    - \uc218\uc5c5\uc758 \uac1c\uc694\n    - \uba38\uc2e0\ub7ec\ub2dd\uc758 \uac1c\ub150\uacfc \uc6a9\uc5b4\n    - Linear Regression \uc758 \uac1c\ub150\n    - Linear Regression cost \ud568\uc218 \ucd5c\uc18c\ud654\n    - \uc5ec\ub7ec \uac1c\uc758 \uc785\ub825(feature)\uc758 Linear Regression\n\n\n\n```python\nimport sys\nsys.version  # Current version of Python\n```\n\n\n\n\n    '3.6.4 |Anaconda custom (64-bit)| (default, Dec 21 2017, 15:39:08) \\n[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]'\n\n\n\n\n```python\nimport os\n\n# Set an environment variable TF_CPP_MIN_LOG_LEVEL as '2'.\n# With the setting, you can ignore tensorflow logs except for error-level logs.\n# https://stackoverflow.com/questions/35869137/avoid-tensorflow-print-on-standard-error\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n```\n\n# Environment Setup\n\n## Anaconda\n\n\n> With over 4.5 million users, the open source Anaconda Distribution is the easiest way to do Python data science and machine learning. It includes hundreds of popular data science packages and the conda package and virtual environment manager for Windows, Linux, and MacOS. Conda makes it quick and easy to install, run, and upgrade complex data science and machine learning environments like scikit-learn, TensorFlow, and SciPy. Anaconda Distribution is the foundation of millions of data science projects as well as Amazon Web Services' Machine Learning AMIs and Anaconda for Microsoft on Azure and Windows.\n>\n> &mdash; [What is Anaconda? :: Anaconda](https://www.anaconda.com/what-is-anaconda/)\n\n- [Downloads :: Anaconda](https://www.anaconda.com/download/)\n- [Installation \u2014 Conda documentation](https://conda.io/docs/user-guide/install/index.html)\n\n### Install (Windows)\n\nJust download graphical installer and run it! :)\n\n### Install (macOS)\n\n#### Install with the official bash file\n\n```bash\nwget https://repo.continuum.io/archive/Anaconda3-5.0.1-MacOSX-x86_64.sh\nbash Anaconda3-5.0.1-MacOSX-x86_64.sh\nrm Anaconda3-5.0.1-MacOSX-x86_64.sh\n\n# You should add the bin directory of anaconda to the PATH environment variable.\n# You can do it by adding a line as below to ~/.bashrc or ~/.zshrc\n#\n#   export PATH=/path/to/your/anaconda/bin:$PATH\n#\n# The exact path of the anaconda directory can vary.\n```\n\n#### Install with Homebrew\n\n- [Homebrew \u2014 The missing package manager for macOS](https://brew.sh/)\n\n```bash\n# If you already installed homebrew, just running this line will work!\nbrew cask install anaconda\n\n# You should add the bin directory of anaconda to the PATH environment variable.\n# You can do it by adding a line as below to ~/.bashrc or ~/.zshrc\n#\n#   export PATH=/path/to/your/anaconda/bin:$PATH\n#\n# The exact path of the anaconda directory can vary.\n```\n\n### Install (Linux)\n\n```bash\nwget https://repo.continuum.io/archive/Anaconda3-5.0.1-Linux-x86_64.sh\nbash Anaconda3-5.0.1-Linux-x86_64.sh\nrm Anaconda3-5.0.1-Linux-x86_64.sh\n\n# You should add the bin directory of anaconda to the PATH environment variable.\n# You can do it by adding a line as below to ~/.bashrc or ~/.zshrc\n#\n#   export PATH=/path/to/your/anaconda/bin:$PATH\n#\n# The exact path of the anaconda directory can vary.\n```\n\n## Conda\n\n> Conda is an open source package management system and environment management system that runs on Windows, macOS and Linux. Conda quickly installs, runs and updates packages and their dependencies. Conda easily creates, saves, loads and switches between environments on your local computer. It was created for Python programs, but it can package and distribute software for any language.\n>\n> &mdash; [Conda documentation page](https://conda.io/docs/)\n\n- [Getting started \u2014 Conda documentation](https://conda.io/docs/user-guide/getting-started.html)\n- [Cheat sheet \u2014 Conda documentation](https://conda.io/docs/user-guide/cheatsheet.html)\n\n### Update all the packages\n```bash\n# Update all the packages in the base environment of anaconda\nconda update --all\n```\n\n### Use a virtual environment for TensorFlow\n\n- [Managing environments \u2014 Conda documentation](https://conda.io/docs/user-guide/tasks/manage-environments.html)\n\n```bash\n# Create new environment, tf, with python 3.6 and anaconda packages\nconda create -n tf python=3.6 anaconda\n\n# Activate tf environment\nsource activate tf\n\n# Install Tensorflow from PyPI\npip install tensorflow\n\n# Deactivate tf environment\nsource deactivate\n```\n\n### (Optional) Use conda-forge instead of PyPI\n\n- [conda-forge | community driven packaging for conda](https://conda-forge.org/)\n- [conda-forge :: Anaconda Cloud](https://anaconda.org/conda-forge)\n\n```bash\n# Install tensorflow distributed on conda-forge\nconda install -c conda-forge tensorflow\n```\n\n## Jupyter Notebook\n\n\n\n> The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. Uses include: data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more.\n>\n> &mdash; [Project Jupyter | Home](http://jupyter.org/)\n\n- [Project Jupyter | Install](http://jupyter.org/install)\n- [nacyot\uc758 \ud504\ub85c\uadf8\ub798\ubc0d \uc774\uc57c\uae30 :: \uc8fc\ud53c\ud130(Jupyter, IPython >= 3)\uc758 \ub2e4\uc911 \ucee4\ub110 \uac1c\ub150 \uc774\ud574\ud558\uae30 - \ud30c\uc774\uc36c2\uc640 \ud30c\uc774\uc36c3 \ub3d9\uc2dc\uc5d0 \uc0ac\uc6a9\ud558\uae30](http://blog.nacyot.com/articles/2015-05-08-jupyter-multiple-pythons/)\n- [Jupyter notebook \uc774\ud574\ud558\uae30](https://www.slideshare.net/dahlmoon/jupyter-notebok-20160815)\n\n### Run\n\n```bash\ncd <working-directory>\njupyter notebook\n```\n\n## JupyterLab\n\n\n\n> An extensible environment for interactive and reproducible computing, based on the Jupyter Notebook and Architecture.\n>\n> JupyterLab is the next generation user interface for Project Jupyter. It offers all the familiar building blocks of the classic Jupyter Notebook (notebook, terminal, text editor, file browser, rich outputs, etc.) in a flexible and powerful user inteface that can be extended through third party extensions that access our public APIs. Eventually, JupyterLab will replace the classic Jupyter Notebook.\n>\n> &mdash; [jupyterlab README](https://github.com/jupyterlab/jupyterlab)\n\n- [jupyterlab/jupyterlab: JupyterLab computational environment.](https://github.com/jupyterlab/jupyterlab)\n\n### Run\n\n```bash\ncd <working-directory>\njupyter lab\n```\n\n# Tensorflow\n\n\n```python\nimport tensorflow as tf\ntf.__version__\n```\n\n    /usr/local/anaconda3/envs/tf/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: compiletime version 3.5 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.6\n      return f(*args, **kwds)\n    /usr/local/anaconda3/envs/tf/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n      from ._conv import register_converters as _register_converters\n\n\n\n\n\n    '1.4.1'\n\n\n\n\n```python\nhello = tf.constant(\"Hello, Tensorflow!\")\n\nsess = tf.Session()\nprint(sess.run(hello))\nsess.close()\n```\n\n    b'Hello, Tensorflow!'\n\n\n\n```python\na = tf.constant(5.)\nb = tf.constant(6.)\nc = a * b\n\nwith tf.Session() as sess:\n    print(sess.run(c))\n```\n\n    30.0\n\n\n# Datasets\n\n- [Red Wine Quality | Kaggle](https://www.kaggle.com/uciml/red-wine-quality-cortez-et-al-2009)\n\n> **Input variables (based on physicochemical tests)**: \n1. fixed acidity \n2. volatile acidity \n3. citric acid \n4. residual sugar \n5. chlorides \n6. free sulfur dioxide \n7. total sulfur dioxide \n8. density \n9. pH \n10. sulphates \n11. alcohol \n\n> **Output variable (based on sensory data)**:\n1. quality (score between 0 and 10)\n\n> **Relevant Papers**:\n>\n> - P. Cortez, A. Cerdeira, F. Almeida, T. Matos and J. Reis. Modeling wine preferences by data mining from physicochemical properties. \nIn Decision Support Systems, Elsevier, 47(4):547-553, 2009. \n\n- Cf. [hunkim/KaggleZeroToAll: Kaggle problem solving](https://github.com/hunkim/KaggleZeroToAll)\n\n\n```python\nDIM_INPUTS = 11\nDIM_OUTPUTS = 1\n```\n\n## Read datasets\n\n### Using NumPy\n\n- [numpy.loadtxt \u2014 NumPy v1.13 Manual](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.loadtxt.html)\n- [numpy.genfromtxt \u2014 NumPy v1.13 Manual](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.genfromtxt.html)\n\n\n```python\nimport numpy as np\n\ndat = np.genfromtxt('datasets/winequality-red.csv', delimiter=',', skip_header=1)\n```\n\n\n```python\ndat\n```\n\n\n\n\n    array([[ 7.4  ,  0.7  ,  0.   , ...,  0.56 ,  9.4  ,  5.   ],\n           [ 7.8  ,  0.88 ,  0.   , ...,  0.68 ,  9.8  ,  5.   ],\n           [ 7.8  ,  0.76 ,  0.04 , ...,  0.65 ,  9.8  ,  5.   ],\n           ...,\n           [ 6.3  ,  0.51 ,  0.13 , ...,  0.75 , 11.   ,  6.   ],\n           [ 5.9  ,  0.645,  0.12 , ...,  0.71 , 10.2  ,  5.   ],\n           [ 6.   ,  0.31 ,  0.47 , ...,  0.66 , 11.   ,  6.   ]])\n\n\n\n\n```python\ndat.shape\n```\n\n\n\n\n    (1599, 12)\n\n\n\n### Using Pandas\n\n- [pandas.read_csv \u2014 pandas 0.22.0 documentation](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html)\n\n\n```python\nimport pandas as pd\n\ndat = pd.read_csv('datasets/winequality-red.csv')\n```\n\n\n```python\ntype(dat)\n```\n\n\n\n\n    pandas.core.frame.DataFrame\n\n\n\n\n```python\ndat.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fixed acidity</th>\n      <th>volatile acidity</th>\n      <th>citric acid</th>\n      <th>residual sugar</th>\n      <th>chlorides</th>\n      <th>free sulfur dioxide</th>\n      <th>total sulfur dioxide</th>\n      <th>density</th>\n      <th>pH</th>\n      <th>sulphates</th>\n      <th>alcohol</th>\n      <th>quality</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>7.4</td>\n      <td>0.70</td>\n      <td>0.00</td>\n      <td>1.9</td>\n      <td>0.076</td>\n      <td>11.0</td>\n      <td>34.0</td>\n      <td>0.9978</td>\n      <td>3.51</td>\n      <td>0.56</td>\n      <td>9.4</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>7.8</td>\n      <td>0.88</td>\n      <td>0.00</td>\n      <td>2.6</td>\n      <td>0.098</td>\n      <td>25.0</td>\n      <td>67.0</td>\n      <td>0.9968</td>\n      <td>3.20</td>\n      <td>0.68</td>\n      <td>9.8</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>7.8</td>\n      <td>0.76</td>\n      <td>0.04</td>\n      <td>2.3</td>\n      <td>0.092</td>\n      <td>15.0</td>\n      <td>54.0</td>\n      <td>0.9970</td>\n      <td>3.26</td>\n      <td>0.65</td>\n      <td>9.8</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>11.2</td>\n      <td>0.28</td>\n      <td>0.56</td>\n      <td>1.9</td>\n      <td>0.075</td>\n      <td>17.0</td>\n      <td>60.0</td>\n      <td>0.9980</td>\n      <td>3.16</td>\n      <td>0.58</td>\n      <td>9.8</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>7.4</td>\n      <td>0.70</td>\n      <td>0.00</td>\n      <td>1.9</td>\n      <td>0.076</td>\n      <td>11.0</td>\n      <td>34.0</td>\n      <td>0.9978</td>\n      <td>3.51</td>\n      <td>0.56</td>\n      <td>9.4</td>\n      <td>5</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndat.values\n```\n\n\n\n\n    array([[ 7.4  ,  0.7  ,  0.   , ...,  0.56 ,  9.4  ,  5.   ],\n           [ 7.8  ,  0.88 ,  0.   , ...,  0.68 ,  9.8  ,  5.   ],\n           [ 7.8  ,  0.76 ,  0.04 , ...,  0.65 ,  9.8  ,  5.   ],\n           ...,\n           [ 6.3  ,  0.51 ,  0.13 , ...,  0.75 , 11.   ,  6.   ],\n           [ 5.9  ,  0.645,  0.12 , ...,  0.71 , 10.2  ,  5.   ],\n           [ 6.   ,  0.31 ,  0.47 , ...,  0.66 , 11.   ,  6.   ]])\n\n\n\n\n```python\ndat.shape\n```\n\n\n\n\n    (1599, 12)\n\n\n\n\n```python\ndat.describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fixed acidity</th>\n      <th>volatile acidity</th>\n      <th>citric acid</th>\n      <th>residual sugar</th>\n      <th>chlorides</th>\n      <th>free sulfur dioxide</th>\n      <th>total sulfur dioxide</th>\n      <th>density</th>\n      <th>pH</th>\n      <th>sulphates</th>\n      <th>alcohol</th>\n      <th>quality</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>1599.000000</td>\n      <td>1599.000000</td>\n      <td>1599.000000</td>\n      <td>1599.000000</td>\n      <td>1599.000000</td>\n      <td>1599.000000</td>\n      <td>1599.000000</td>\n      <td>1599.000000</td>\n      <td>1599.000000</td>\n      <td>1599.000000</td>\n      <td>1599.000000</td>\n      <td>1599.000000</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>8.319637</td>\n      <td>0.527821</td>\n      <td>0.270976</td>\n      <td>2.538806</td>\n      <td>0.087467</td>\n      <td>15.874922</td>\n      <td>46.467792</td>\n      <td>0.996747</td>\n      <td>3.311113</td>\n      <td>0.658149</td>\n      <td>10.422983</td>\n      <td>5.636023</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>1.741096</td>\n      <td>0.179060</td>\n      <td>0.194801</td>\n      <td>1.409928</td>\n      <td>0.047065</td>\n      <td>10.460157</td>\n      <td>32.895324</td>\n      <td>0.001887</td>\n      <td>0.154386</td>\n      <td>0.169507</td>\n      <td>1.065668</td>\n      <td>0.807569</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>4.600000</td>\n      <td>0.120000</td>\n      <td>0.000000</td>\n      <td>0.900000</td>\n      <td>0.012000</td>\n      <td>1.000000</td>\n      <td>6.000000</td>\n      <td>0.990070</td>\n      <td>2.740000</td>\n      <td>0.330000</td>\n      <td>8.400000</td>\n      <td>3.000000</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>7.100000</td>\n      <td>0.390000</td>\n      <td>0.090000</td>\n      <td>1.900000</td>\n      <td>0.070000</td>\n      <td>7.000000</td>\n      <td>22.000000</td>\n      <td>0.995600</td>\n      <td>3.210000</td>\n      <td>0.550000</td>\n      <td>9.500000</td>\n      <td>5.000000</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>7.900000</td>\n      <td>0.520000</td>\n      <td>0.260000</td>\n      <td>2.200000</td>\n      <td>0.079000</td>\n      <td>14.000000</td>\n      <td>38.000000</td>\n      <td>0.996750</td>\n      <td>3.310000</td>\n      <td>0.620000</td>\n      <td>10.200000</td>\n      <td>6.000000</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>9.200000</td>\n      <td>0.640000</td>\n      <td>0.420000</td>\n      <td>2.600000</td>\n      <td>0.090000</td>\n      <td>21.000000</td>\n      <td>62.000000</td>\n      <td>0.997835</td>\n      <td>3.400000</td>\n      <td>0.730000</td>\n      <td>11.100000</td>\n      <td>6.000000</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>15.900000</td>\n      <td>1.580000</td>\n      <td>1.000000</td>\n      <td>15.500000</td>\n      <td>0.611000</td>\n      <td>72.000000</td>\n      <td>289.000000</td>\n      <td>1.003690</td>\n      <td>4.010000</td>\n      <td>2.000000</td>\n      <td>14.900000</td>\n      <td>8.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### Using TensorFlow\n\n- [Importing Data \u00a0|\u00a0 TensorFlow](https://www.tensorflow.org/programmers_guide/datasets)\n\n## Make X & Y\n\n\n```python\nX_total = dat.values[:, 0:-1]\nY_total = dat.values[:, [-1]]\n```\n\n## Split Training/Test datasets\n\n### Using NumPy\n\n\n```python\n# This way of choosing train datasets cannot make fixed rate of train-test split.\n# The number of True on the mask vector is distributed around 0.8.\nmask = np.random.rand(len(X_total)) < 0.8\n```\n\n\n```python\nX_train = X_total[mask]\nY_train = Y_total[mask]\nX_test = X_total[~mask]\nY_test = Y_total[~mask]\n```\n\n\n```python\n# Formatted String on Python 3.6\nprint(f'X_train: {X_train.shape}\\nX_test: {X_test.shape}')\nprint(f'Y_train: {Y_train.shape}\\nY_test: {Y_test.shape}')\n```\n\n    X_train: (1261, 11)\n    X_test: (338, 11)\n    Y_train: (1261, 1)\n    Y_test: (338, 1)\n\n\n- Cf. [PyFormat: Using % and .format() for great good!](https://pyformat.info/)\n\n### Using Pandas\n\n\n```python\ndat_train = dat.sample(frac=0.8)\ndat_test = dat.drop(dat_train.index)\n```\n\n\n```python\nX_train, Y_train = dat_train.values[:, 0:-1], dat_train.values[:, [-1]]\nX_test, Y_test = dat_test.values[:, 0:-1], dat_test.values[:, [-1]]\n```\n\n\n```python\nprint(f'X_train: {X_train.shape}\\nX_test: {X_test.shape}')\nprint(f'Y_train: {Y_train.shape}\\nY_test: {Y_test.shape}')\n```\n\n    X_train: (1279, 11)\n    X_test: (320, 11)\n    Y_train: (1279, 1)\n    Y_test: (320, 1)\n\n\n### Using Scikit-Learn\n\n- [sklearn.model_selection.train_test_split \u2014 scikit-learn 0.19.1 documentation](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html)\n\n\n```python\nfrom sklearn.model_selection import train_test_split\n```\n\n\n```python\nX_train, X_test, Y_train, Y_test = train_test_split(X_total, Y_total, test_size=0.2)\n```\n\n\n```python\nprint(f'X_train: {X_train.shape}\\nX_test: {X_test.shape}')\nprint(f'Y_train: {Y_train.shape}\\nY_test: {Y_test.shape}')\n```\n\n    X_train: (1279, 11)\n    X_test: (320, 11)\n    Y_train: (1279, 1)\n    Y_test: (320, 1)\n\n\n# Linear Regression\n\n\\begin{align}\n    H(X)\n    &= X W + b \\\\\n    &= \\underbrace{\\begin{bmatrix}\n        x_{11} & \\cdots & x_{1m} \\\\\n        \\vdots & \\ddots & \\vdots \\\\\n        x_{n1} & \\cdots & x_{nm}\n    \\end{bmatrix}}_{n \\times m} \\cdot \\underbrace{\\begin{bmatrix}\n        w_{11} & \\cdots & w_{1k} \\\\\n        \\vdots & \\ddots & \\vdots \\\\\n        w_{m1} & \\cdots & w_{mk}\n    \\end{bmatrix}}_{m \\times k} + \\underbrace{\\begin{bmatrix}\n        b_1 \\\\\n        \\vdots \\\\\n        b_k \\\\\n    \\end{bmatrix}}_{k} \\\\\n    &= \\begin{bmatrix}\n        (\\sum_i x_{1i} w_{i1}) + b_1 & (\\sum_i x_{1i} w_{i2}) + b_2 & \\cdots & (\\sum_i x_{1i} w_{ik}) + b_k \\\\\n        (\\sum_i x_{2i} w_{i1}) + b_1 & (\\sum_i x_{2i} w_{i2}) + b_2 & \\cdots & (\\sum_i x_{2i} w_{ik}) + b_k \\\\\n        \\vdots & \\vdots & \\ddots & \\vdots \\\\\n        (\\sum_i x_{ni} w_{i1}) + b_1 & (\\sum_i x_{ni} w_{i2}) + b_2 & \\cdots & (\\sum_i x_{ni} w_{ik}) + b_k \\\\\n    \\end{bmatrix} \\\\\n    &= \\begin{bmatrix}\n        h_{11} & h_{12} & \\cdots & h_{1k} \\\\\n        h_{21} & h_{22} & \\cdots & h_{2k} \\\\\n        \\vdots & \\vdots & \\ddots & \\vdots \\\\\n        h_{n1} & h_{n2} & \\cdots & h_{nk}\n    \\end{bmatrix} \\\\\n\\end{align}\n\nwhere $n$ = the number of records, $m$ = the number of input variables (aka features, regressors, predictors), $k$ = the number of output variables.\n\n## Model\n\n\n```python\n# Input & Target\nX = tf.placeholder(tf.float32, shape=[None, DIM_INPUTS], name='Input')\nY = tf.placeholder(tf.float32, shape=[None, DIM_OUTPUTS], name='Target')\n\n# Weight & Bias\nW = tf.Variable(tf.random_normal([DIM_INPUTS, DIM_OUTPUTS]), name='Weight')\nb = tf.Variable(tf.random_normal([DIM_OUTPUTS]), name='Bias')\n```\n\n\n```python\n# Hypothesis with the linear regression model\nH = tf.matmul(X, W) + b\n\n# Cost/Loss function (Mean Squared Error)\ncost = tf.reduce_mean(tf.square(H - Y))\n```\n\n## Optimization\n\n\n```python\n# Gradient Descent Optimizer provided by TensorFlow\noptimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-4)\n\n# Train operation to minimize the cost function\ntrain = optimizer.minimize(cost)\n```\n\n\n```python\n# Manually computed gradient\ngradient = tf.reduce_mean((H - Y) * X) * 2\n\n# Gradients computed by the optimizer\ngvs = optimizer.compute_gradients(cost, [W])\n\n# Apply computed gradients back to optimizer\napply_gradients = optimizer.apply_gradients(gvs)\n```\n\n## Start a session\n\n\n```python\n# Launch the graph in a session.\nsess = tf.Session()\n# Initializes global variables in the graph.\nsess.run(tf.global_variables_initializer())\n```\n\n## Train\n\n\n```python\ncosts = []\nfor step in range(2001):\n    val_cost, _ = sess.run([cost, train], feed_dict={X: X_train, Y: Y_train})\n    # val_cost, _ = sess.run([cost, apply_gradients], feed_dict={X: X_train, Y: Y_train})\n    costs.append(val_cost)\n```\n\n\n```python\nfor i in range(0, 2001, 100):\n    print(f'Step {i:4d} {costs[i]:.4f}')\n```\n\n    Step    0 4731.5576\n    Step  100 23.9495\n    Step  200 12.0473\n    Step  300 9.3886\n    Step  400 8.3725\n    Step  500 7.6884\n    Step  600 7.1054\n    Step  700 6.5798\n    Step  800 6.1007\n    Step  900 5.6630\n    Step 1000 5.2628\n    Step 1100 4.8969\n    Step 1200 4.5622\n    Step 1300 4.2561\n    Step 1400 3.9761\n    Step 1500 3.7200\n    Step 1600 3.4855\n    Step 1700 3.2710\n    Step 1800 3.0746\n    Step 1900 2.8949\n    Step 2000 2.7302\n\n\n\n```python\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(costs)\nplt.xlabel('Steps')\nplt.ylabel('MSE cost')\nplt.show()\n```\n\n## Test\n\n\n```python\nval_cost = sess.run([cost], feed_dict={X: X_test, Y: Y_test})\nval_cost\n```\n\n\n\n\n    [2.6323833]\n\n\n\n## Close the session\n\n\n```python\nsess.close()\n```\n\n# Using multiple datasets\n\n\n```python\nfilename_queue = tf.train.string_input_producer(\n    ['datasets/winequality-red.csv'], shuffle=False, name='filename_queue')\nreader = tf.TextLineReader(skip_header_lines=1)\nkey, value = reader.read(filename_queue)\n\nrecord_defaults = [[0.]] * 12\nxy = tf.decode_csv(value, record_defaults=record_defaults)\n\ntrain_x_batch, train_y_batch = tf.train.batch([xy[0:-1], xy[-1:]], batch_size=10)\n```\n\n## Abstraction with functions\n\n- [Reading data \u00a0|\u00a0 TensorFlow](https://www.tensorflow.org/api_guides/python/reading_data)\n- [Importing Data \u00a0|\u00a0 TensorFlow](https://www.tensorflow.org/programmers_guide/datasets)\n- [Threading and Queues \u00a0|\u00a0 TensorFlow](https://www.tensorflow.org/versions/r0.12/how_tos/threading_and_queues/)\n- [\uc4f0\ub808\ub4dc\uc640 \ud050 \u00b7 \ud150\uc11c\ud50c\ub85c\uc6b0 \ubb38\uc11c \ud55c\uae00 \ubc88\uc5ed\ubcf8](https://tensorflowkorea.gitbooks.io/tensorflow-kr/content/g3doc/how_tos/threading_and_queues/)\n\n\n```python\ndef read_data_format(filename_queue):\n    reader = tf.TextLineReader(skip_header_lines=1)\n    key, value = reader.read(filename_queue)\n    \n    record_defaults = [[0.]] * 12\n    xy = tf.decode_csv(value, record_defaults=record_defaults)\n    \n    features = xy[0:-1]\n    labels = xy[-1:]\n    \n    return features, labels\n```\n\n\n```python\ndef input_pipeline(filenames, batch_size, num_epochs=None):\n    filename_queue = tf.train.string_input_producer(\n        filenames, num_epochs=num_epochs, shuffle=True)\n    \n    features, labels = read_data_format(filename_queue)\n    \n    min_after_dequeue = 10000\n    capacity = min_after_dequeue + 3 * batch_size\n\n    feature_batch, label_batch = tf.train.shuffle_batch(\n        [features, labels],\n        batch_size=batch_size,\n        capacity=capacity,\n        min_after_dequeue=min_after_dequeue)\n    \n    return feature_batch, label_batch\n```\n\n\n```python\ntrain_x_batch, train_y_batch = input_pipeline(['datasets/winequality-red.csv'], 100)\n```\n\n\n```python\n# Launch the graph in a session.\nsess = tf.Session()\n# Initializes global variables in the graph.\nsess.run(tf.global_variables_initializer())\n```\n\n\n```python\n# Start populating the filename queue.\ncoord = tf.train.Coordinator()\nthreads = tf.train.start_queue_runners(sess=sess, coord=coord)\n\ncosts = []\nfor step in range(2001):\n    # Evaluate X_batch & Y_batch\n    X_batch, Y_batch = sess.run([train_x_batch, train_y_batch])\n    \n    # Train the regression model and evaluate the cost\n    _, val_cost = sess.run([train, cost], feed_dict={X: X_batch, Y: Y_batch})\n    \n    # Append it to the list of costs\n    costs.append(val_cost)\n\ncoord.request_stop()\ncoord.join(threads)\n```\n\n\n```python\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(costs)\nplt.xlabel('Steps')\nplt.ylabel('MSE cost')\nplt.show()\n```\n\n\n```python\nsess.close()\n```\n\n# Useful Resources\n\n- [aicodes/tf-bestpractice: Tensorflow Best Practices](https://github.com/aicodes/tf-bestpractice)\n- [aymericdamien/TensorFlow-Examples: TensorFlow Tutorial and Examples for Beginners with Latest APIs](https://github.com/aymericdamien/TensorFlow-Examples)\n- [nlintz/TensorFlow-Tutorials: Simple tutorials using Google's TensorFlow Framework](https://github.com/nlintz/TensorFlow-Tutorials)\n- [sjchoi86/Tensorflow-101: TensorFlow Tutorials](https://github.com/sjchoi86/Tensorflow-101): Useful tutorial for TensorFlow by Sungjoon Choi in SNU\n", "meta": {"hexsha": "cf43b27ddfa40a6fc09d510fa7281e7c56766df3", "size": 63490, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "week-1/index.ipynb", "max_stars_repo_name": "CCS-Lab/DeepLearning2017winter", "max_stars_repo_head_hexsha": "0a7c932c6b60009161a98c59010d666a4b687247", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "week-1/index.ipynb", "max_issues_repo_name": "CCS-Lab/DeepLearning2017winter", "max_issues_repo_head_hexsha": "0a7c932c6b60009161a98c59010d666a4b687247", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week-1/index.ipynb", "max_forks_repo_name": "CCS-Lab/DeepLearning2017winter", "max_forks_repo_head_hexsha": "0a7c932c6b60009161a98c59010d666a4b687247", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-01-21T08:35:27.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-19T05:31:52.000Z", "avg_line_length": 41.0407239819, "max_line_length": 9996, "alphanum_fraction": 0.6206174201, "converted": true, "num_tokens": 7945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26284183737131667, "lm_q2_score": 0.17106118745263715, "lm_q1q2_score": 0.04496203681297037}}
{"text": "```python\n#remove cell visibility\nfrom IPython.display import HTML\ntag = HTML('''\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.''')\ndisplay(tag)\n```\n\n\n\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.\n\n\n\n```python\n%matplotlib inline\nimport control\nimport numpy\nimport sympy as sym\nfrom IPython.display import display, Markdown\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\n\n\n#print a matrix latex-like\ndef bmatrix(a):\n     \"\"\"Returns a LaTeX bmatrix - by Damir Arbula (ICCT project)\n\n     :a: numpy array\n     :returns: LaTeX bmatrix as a string\n     \"\"\"\n     if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n     lines = str(a).replace('[', '').replace(']', '').splitlines()\n     rv = [r'\\begin{bmatrix}']\n     rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n     rv +=  [r'\\end{bmatrix}']\n     return '\\n'.join(rv)\n\n\n# Display formatted matrix: \ndef vmatrix(a):\n    if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n    lines = str(a).replace('[', '').replace(']', '').splitlines()\n    rv = [r'\\begin{vmatrix}']\n    rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n    rv +=  [r'\\end{vmatrix}']\n    return '\\n'.join(rv)\n\n\n#matrixWidget is a matrix looking widget built with a VBox of HBox(es) that returns a numPy array as value !\nclass matrixWidget(widgets.VBox):\n    def updateM(self,change):\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.M_[irow,icol] = self.children[irow].children[icol].value\n                #print(self.M_[irow,icol])\n        self.value = self.M_\n\n    def dummychangecallback(self,change):\n        pass\n    \n    \n    def __init__(self,n,m):\n        self.n = n\n        self.m = m\n        self.M_ = numpy.matrix(numpy.zeros((self.n,self.m)))\n        self.value = self.M_\n        widgets.VBox.__init__(self,\n                             children = [\n                                 widgets.HBox(children = \n                                              [widgets.FloatText(value=0.0, layout=widgets.Layout(width='90px')) for i in range(m)]\n                                             ) \n                                 for j in range(n)\n                             ])\n        \n        #fill in widgets and tell interact to call updateM each time a children changes value\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        #value = Unicode('example@example.com', help=\"The email value.\").tag(sync=True)\n        self.observe(self.updateM, names='value', type= 'All')\n        \n    def setM(self, newM):\n        #disable callbacks, change values, and reenable\n        self.unobserve(self.updateM, names='value', type= 'All')\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].unobserve(self.updateM, names='value')\n        self.M_ = newM\n        self.value = self.M_\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        self.observe(self.updateM, names='value', type= 'All')        \n\n                #self.children[irow].children[icol].observe(self.updateM, names='value')\n\n             \n#overlaod class for state space systems that DO NOT remove \"useless\" states (what \"professor\" of automatic control would do this?)\nclass sss(control.StateSpace):\n    def __init__(self,*args):\n        #call base class init constructor\n        control.StateSpace.__init__(self,*args)\n    #disable function below in base class\n    def _remove_useless_states(self):\n        pass\n```\n\n## Missile attitude control\n\nMissile guidance is usually achieved by means of acceleration commands. The dynamic model of the missile of interest is given by the following equations obtained by system identification:\n\n\\begin{cases}\n\\dot{\\textbf{X}}=\\begin{bmatrix}\\dot{x_1} \\\\ \\dot{x_2} \\\\ \\dot{x_3}\\end{bmatrix} =\\begin{bmatrix}-1.364 & \u221292.82 & \u2212128.46 \\\\ 1 & \u22124.68 & \u22120.087 \\\\ 0 & 0 & -190 \\end{bmatrix} \\begin{bmatrix} x_1 \\\\x_2 \\\\ x_3 \\end{bmatrix}+\\begin{bmatrix}0 \\\\0 \\\\190\\end{bmatrix}u \\\\\na=\\begin{bmatrix}1.36 & \u2212184.26 & 76.43\\end{bmatrix}\\textbf{X},\n\\end{cases}\n\nwhere $x_1$ is pitch rate in rad/s, $x_2$ is angle of attack in rad, $x_3$ is rudder angle in rad, $u$ is rudder command in rad/s, and the output is lateral acceleration $a$ in m/$\\text{s}^2$. Aim is to design a flight control system that regulates missile acceleration to the desired value $a_d$. The maximum rudder deflection is $\\pm$17 degrees.\n\nThe aim is to design a regulator that controls the missile acceleration by acting on rudder angle according to the following specifications:\n- steady-state error (in response to a desired acceleration step input equal to $3 G \\simeq 30$ $\\text{m/s}^2$) is less than 1%,\n- max overshoot: 5%, \n- settling time for 5% tolerance band is less than 0.1 seconds.\n\n### Regulator design\n#### Controller design\nThe system's controllability matrix $\\mathcal{C}$ is:\n\n\n```python\nA = numpy.matrix('-1.364 -92.82 -128.46; 1 -4.68 -0.087; 0 0 -190')\nB = numpy.matrix('0; 0; 190')\nC = numpy.matrix('1.36 -184.26 76.43')\nD = numpy.matrix('0')\nCtrb = control.ctrb(A,B)\ndisplay(Markdown(bmatrix(Ctrb)))\n# print(numpy.linalg.matrix_rank(Ctrb))\n```\n\n\n\\begin{bmatrix}\n  0.00000000e+00 & -2.44074000e+04 & 4.67223201e+06\\\\\n  0.00000000e+00 & -1.65300000e+01 & -2.11893396e+04\\\\\n  1.90000000e+02 & -3.61000000e+04 & 6.85900000e+06\\\\\n\\end{bmatrix}\n\n\nthat has rank equal to 3, so the system is controllable.\n\nThe transfer function of the system is\n\n\n```python\nsys = sss(A,B,C,0)\nprint(control.ss2tf(sys))\n```\n\n    \n    1.452e+04 s^2 + 5.762e+04 s + 5.789e+06\n    ---------------------------------------\n      s^3 + 196 s^2 + 1248 s + 1.885e+04\n    \n\n\nand the poles and zeros are\n\n\n```python\nprint('Poles: ', sys.pole())\nprint('Zeros: ', sys.zero())\n```\n\n    Poles:  [  -3.022+9.49057617j   -3.022-9.49057617j -190.   +0.j        ]\n    Zeros:  [-1.98395879+19.86693768j -1.98395879-19.86693768j]\n\n\nWe find that placing 2 imaginary poles near the zeros results in a good response, so the poles that we choose are $-2+19.1i$, $-2-19.1i$ and $-45$.\n\n#### Observer design\nThe system's observability matrix $\\mathcal{O}$ is:\n\n\n```python\nObsv = control.obsv(A,C) \ndisplay(Markdown(bmatrix(Obsv)))\n# print(numpy.linalg.matrix_rank(Obsv))\n```\n\n\n\\begin{bmatrix}\n  1.36000000e+00 & -1.84260000e+02 & 7.64300000e+01\\\\\n  -1.86115040e+02 & 7.36101600e+02 & -1.46803750e+04\\\\\n  9.89962515e+02 & 1.38302425e+04 & 2.81311554e+06\\\\\n\\end{bmatrix}\n\n\nthat has rank equal to 3, so the system is observable.\n\nThe only requirement that we have for the observer is that the error dynamics converges in approximately less than 0.1 s. A good choice for the observer poles is $-50$, $-50$, and $-50$.\n\n### How to use this notebook?\nTry to achieve the performance requirements with other locations of the poles and with errors in the initial state of the observer.\n\n\n```python\n# Preparatory cell\n\nX0 = numpy.matrix('0.0; 0.0; 0.0')\nK = numpy.matrix([8/15,-4.4,-4])\nL = numpy.matrix([[23],[66],[107/3]])\n\nAw = matrixWidget(3,3)\nAw.setM(A)\nBw = matrixWidget(3,1)\nBw.setM(B)\nCw = matrixWidget(1,3)\nCw.setM(C)\nX0w = matrixWidget(3,1)\nX0w.setM(X0)\nKw = matrixWidget(1,3)\nKw.setM(K)\nLw = matrixWidget(3,1)\nLw.setM(L)\n\n\neig1c = matrixWidget(1,1)\neig2c = matrixWidget(2,1)\neig3c = matrixWidget(1,1)\neig1c.setM(numpy.matrix([-60.])) \neig2c.setM(numpy.matrix([[-2.],[-19.1]]))\neig3c.setM(numpy.matrix([-45.]))\n\neig1o = matrixWidget(1,1)\neig2o = matrixWidget(2,1)\neig3o = matrixWidget(1,1)\neig1o.setM(numpy.matrix([-50.])) \neig2o.setM(numpy.matrix([[-50.],[0.]]))\neig3o.setM(numpy.matrix([-50.]))\n```\n\n\n```python\n# Misc\n\n#create dummy widget \nDW = widgets.FloatText(layout=widgets.Layout(width='0px', height='0px'))\n\n#create button widget\nSTART = widgets.Button(\n    description='Test',\n    disabled=False,\n    button_style='', # 'success', 'info', 'warning', 'danger' or ''\n    tooltip='Test',\n    icon='check'\n)\n                       \ndef on_start_button_clicked(b):\n    #This is a workaround to have intreactive_output call the callback:\n    #   force the value of the dummy widget to change\n    if DW.value> 0 :\n        DW.value = -1\n    else: \n        DW.value = 1\n    pass\nSTART.on_click(on_start_button_clicked)\n\n# Define type of method \nselm = widgets.Dropdown(\n    options= ['Set K and L', 'Set the eigenvalues'],\n    value= 'Set the eigenvalues',\n    description='',\n    disabled=False\n)\n\n# Define the number of complex eigenvalues\nsele = widgets.Dropdown(\n    options= ['0 complex eigenvalues', '2 complex eigenvalues'],\n    value= '2 complex eigenvalues',\n    description='Complex eigenvalues:',\n    style = {'description_width': 'initial'},\n    disabled=False\n)\n\n#define type of ipout \nselu = widgets.Dropdown(\n    options=['impulse', 'step', 'sinusoid', 'square wave'],\n    value='step',\n    description='Type of reference:',\n    style = {'description_width': 'initial'},\n    disabled=False\n)\n# Define the values of the input\nu = widgets.FloatSlider(\n    value=9.81*3,\n    min=0,\n    max=9.81*10,\n    step=0.1,\n    description='Reference:',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.1f',\n)\nperiod = widgets.FloatSlider(\n    value=0.5,\n    min=0.001,\n    max=10,\n    step=0.001,\n    description='Period: ',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.2f',\n)\n\ngain_w2 = widgets.FloatText(\n    value=1.,\n    description='',\n    disabled=True\n)\n\nsimTime = widgets.FloatText(\n    value=1.5,\n    description='',\n    disabled=False\n)\n```\n\n\n```python\n# Support functions\n\ndef eigen_choice(sele):\n    if sele == '0 complex eigenvalues':\n        eig1c.children[0].children[0].disabled = False\n        eig2c.children[1].children[0].disabled = True\n        eig1o.children[0].children[0].disabled = False\n        eig2o.children[1].children[0].disabled = True\n        eig = 0\n    if sele == '2 complex eigenvalues':\n        eig1c.children[0].children[0].disabled = True\n        eig2c.children[1].children[0].disabled = False\n        eig1o.children[0].children[0].disabled = True\n        eig2o.children[1].children[0].disabled = False\n        eig = 2\n    return eig\n\ndef method_choice(selm):\n    if selm == 'Set K and L':\n        method = 1\n        sele.disabled = True\n    if selm == 'Set the eigenvalues':\n        method = 2\n        sele.disabled = False\n    return method\n```\n\n\n```python\ndef main_callback2(Aw, Bw, X0w, K, L, eig1c, eig2c, eig3c, eig1o, eig2o, eig3o, u, period, selm, sele, selu, simTime, DW):\n    eige = eigen_choice(sele)\n    method = method_choice(selm)\n    \n    if method == 1:\n        solc = numpy.linalg.eig(A-B*K)\n        solo = numpy.linalg.eig(A-L*C)\n    if method == 2:\n        if eige == 0:\n            K = control.acker(A, B, [eig1c[0,0], eig2c[0,0], eig3c[0,0]])\n            Kw.setM(K)\n            L = control.acker(A.T, C.T, [eig1o[0,0], eig2o[0,0], eig3o[0,0]]).T\n            Lw.setM(L)\n        if eige == 2:\n            K = control.acker(A, B, [eig3c[0,0], \n                                     numpy.complex(eig2c[0,0],eig2c[1,0]), \n                                     numpy.complex(eig2c[0,0],-eig2c[1,0])])\n            Kw.setM(K)\n            L = control.acker(A.T, C.T, [eig3o[0,0], \n                                         numpy.complex(eig2o[0,0],eig2o[1,0]), \n                                         numpy.complex(eig2o[0,0],-eig2o[1,0])]).T\n            Lw.setM(L)\n            \n    \n    sys = control.ss(A,B,numpy.vstack((C,numpy.zeros((B.shape[1],C.shape[1])))),numpy.vstack((D,numpy.eye(B.shape[1]))))\n    sysC = control.ss(numpy.zeros((1,1)),\n                      numpy.zeros((1,numpy.shape(A)[0])),\n                      numpy.zeros((numpy.shape(B)[1],1)),\n                      -K)\n    \n    sysE = control.ss(A-L*C,\n                      numpy.hstack((L,B-L*D)),\n                      numpy.eye(numpy.shape(A)[0]),\n                      numpy.zeros((A.shape[0],C.shape[0]+B.shape[1])))\n    \n    sys_append = control.append(sys, sysE, sysC, control.ss(A,B,numpy.eye(A.shape[0]),numpy.zeros((A.shape[0],B.shape[1]))))\n    Q = []\n    # y in ingresso a sysE\n    for i in range(C.shape[0]):\n        Q.append([B.shape[1]+i+1, i+1])\n    # u in ingresso a sysE\n    for i in range(B.shape[1]):\n        Q.append([B.shape[1]+C.shape[0]+i+1, C.shape[0]+i+1])\n    # u in ingresso a sys\n    for i in range(B.shape[1]):\n        Q.append([i+1, C.shape[0]+B.shape[1]+A.shape[0]+i+1])\n    # u in ingresso al sistema che ha come uscite gli stati reali\n    for i in range(B.shape[1]):\n        Q.append([2*B.shape[1]+C.shape[0]+A.shape[0]+i+1, C.shape[0]+i+1])\n    # xe in ingresso a sysC\n    for i in range(A.shape[0]):\n        Q.append([2*B.shape[1]+C.shape[0]+i+1, C.shape[0]+B.shape[1]+i+1])\n        \n    inputv = [i+1 for i in range(B.shape[1])]\n    outputv = [i+1 for i in range(numpy.shape(sys_append.C)[0])]\n    sys_CL = control.connect(sys_append,\n                             Q,\n                             inputv,\n                             outputv)\n    \n    dcgain = control.dcgain(sys_CL[0,0])\n    gain_w2.value = dcgain\n    if dcgain != 0:\n        u1 = u/gain_w2.value\n    else:\n        print('The feedforward gain setted is 0 and it is changed to 1')\n        u1 = u/1\n    print('The static gain of the closed loop system (from the reference to the output) is: %.5f' %dcgain)\n    \n    X0w1 = numpy.zeros((A.shape[0],1))\n    for j in range(A.shape[0]):\n        X0w1 = numpy.vstack((X0w1,X0w[j]))\n    X0w1 = numpy.vstack((X0w1,numpy.zeros((A.shape[0],1))))\n    if simTime != 0:\n        T = numpy.linspace(0, simTime, 10000)\n    else:\n        T = numpy.linspace(0, 1, 10000)\n      \n    if selu == 'impulse': #selu\n        U = [0 for t in range(0,len(T))]\n        U[0] = u\n        U1 = [0 for t in range(0,len(T))]\n        U1[0] = u1\n        T, yout, xout = control.forced_response(sys_CL,T,U1,X0w1)\n    if selu == 'step':\n        U = [u for t in range(0,len(T))]\n        U1 = [u1 for t in range(0,len(T))]\n        T, yout, xout = control.forced_response(sys_CL,T,U1,X0w1)\n    if selu == 'sinusoid':\n        U = u*numpy.sin(2*numpy.pi/period*T)\n        U1 = u1*numpy.sin(2*numpy.pi/period*T)\n        T, yout, xout = control.forced_response(sys_CL,T,U1,X0w1)\n    if selu == 'square wave':\n        U = u*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n        U1 = u1*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n        T, yout, xout = control.forced_response(sys_CL,T,U1,X0w1)\n    # N.B. i primi 3 stati di xout sono quelli del sistema, mentre gli ultimi 3 sono quelli dell'osservatore\n    \n    step_info_dict = control.step_info(sys_CL[0,0],SettlingTimeThreshold=0.05,T=T)\n    print('Step info: \\n\\tRise time =',step_info_dict['RiseTime'],'\\n\\tSettling time (5%) =',step_info_dict['SettlingTime'],'\\n\\tOvershoot (%)=',step_info_dict['Overshoot'])\n    print('Max x3 value (%)=', max(abs(yout[C.shape[0]+2*B.shape[1]+A.shape[0]+2]))/(numpy.pi/180*17)*100)\n    \n    fig = plt.figure(num='Simulation1', figsize=(14,12))\n    \n    fig.add_subplot(221)\n    plt.title('Output response')\n    plt.ylabel('Output')\n    plt.plot(T,yout[0],T,U,'r--')\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$y$','Reference'])\n    plt.grid()\n    \n    fig.add_subplot(222)\n    plt.title('Input')\n    plt.ylabel('$u$')\n    plt.plot(T,yout[C.shape[0]])\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(223)\n    plt.title('States response')\n    plt.ylabel('States')\n    plt.plot(T,yout[C.shape[0]+2*B.shape[1]+A.shape[0]],\n             T,yout[C.shape[0]+2*B.shape[1]+A.shape[0]+1],\n             T,yout[C.shape[0]+2*B.shape[1]+A.shape[0]+2],\n             T,[numpy.pi/180*17 for i in range(len(T))],'r--',\n             T,[-numpy.pi/180*17 for i in range(len(T))],'r--')\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$x_{1}$','$x_{2}$','$x_{3}$','limit +$x_{3}$','limit -$x_{3}$'])\n    plt.grid()\n    \n    fig.add_subplot(224)\n    plt.title('Estimation errors')\n    plt.ylabel('Errors')\n    plt.plot(T,yout[C.shape[0]+2*B.shape[1]+A.shape[0]]-yout[C.shape[0]+B.shape[1]],\n             T,yout[C.shape[0]+2*B.shape[1]+A.shape[0]+1]-yout[C.shape[0]+B.shape[1]+1],\n             T,yout[C.shape[0]+2*B.shape[1]+A.shape[0]+2]-yout[C.shape[0]+B.shape[1]+2])\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$e_{1}$','$e_{2}$','$e_{3}$'])\n    plt.grid()\n    #plt.tight_layout()\n   \nalltogether2 = widgets.VBox([widgets.HBox([selm, \n                                          sele,\n                                          selu]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.Label('K:',border=3), Kw, \n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Eigenvalues:',border=3), \n                                          eig1c, \n                                          eig2c, \n                                          eig3c,\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('X0 est.:',border=3), X0w]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.Label('L:',border=3), Lw, \n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Eigenvalues:',border=3), \n                                          eig1o, \n                                          eig2o, \n                                          eig3o,\n                                          widgets.Label(' ',border=3),\n                                          widgets.VBox([widgets.Label('Inverse reference gain:',border=3),\n                                                        widgets.Label('Simulation time [s]:',border=3)]),\n                                          widgets.VBox([gain_w2,simTime])]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([u, \n                                          period, \n                                          START])])\nout2 = widgets.interactive_output(main_callback2, {'Aw':Aw, 'Bw':Bw, 'X0w':X0w, 'K':Kw, 'L':Lw,\n                                                 'eig1c':eig1c, 'eig2c':eig2c, 'eig3c':eig3c, 'eig1o':eig1o, 'eig2o':eig2o, 'eig3o':eig3o, \n                                                 'u':u, 'period':period, 'selm':selm, 'sele':sele, 'selu':selu, 'simTime':simTime, 'DW':DW})\nout2.layout.height = '860px'\ndisplay(out2, alltogether2)\n```\n\n\n    Output(layout=Layout(height='860px'))\n\n\n\n    VBox(children=(HBox(children=(Dropdown(index=1, options=('Set K and L', 'Set the eigenvalues'), value='Set the\u2026\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "ed23c07d1b893184fbda0e14b2762c04ceb1fdb0", "size": 28460, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_en/examples/04/.ipynb_checkpoints/SS-42-Missile_attitude_control-checkpoint.ipynb", "max_stars_repo_name": "ICCTerasmus/ICCT", "max_stars_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-22T18:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:10:22.000Z", "max_issues_repo_path": "ICCT/ENG/examples/04/SS-42-Missile_attitude_control.ipynb", "max_issues_repo_name": "tuxsaurus/ICCT", "max_issues_repo_head_hexsha": "30d1aea4fb056c9736c9b4c5a0f50fff14fa6382", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICCT/ENG/examples/04/SS-42-Missile_attitude_control.ipynb", "max_forks_repo_name": "tuxsaurus/ICCT", "max_forks_repo_head_hexsha": "30d1aea4fb056c9736c9b4c5a0f50fff14fa6382", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-24T11:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T16:36:18.000Z", "avg_line_length": 37.7954847278, "max_line_length": 358, "alphanum_fraction": 0.4738931834, "converted": true, "num_tokens": 5819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807711081161995, "lm_q2_score": 0.13296424706933604, "lm_q1q2_score": 0.044952168490443534}}
{"text": "##### Copyright 2020 The Cirq Developers\n\n\n```\n#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# Operators and observables\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n  <td>\n    <a target=\"_blank\" href=\"https://quantumai.google/cirq/operators_and_observables\">View on QuantumAI</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/Cirq/blob/master/docs/operators_and_observables.ipynb\">Run in Google Colab</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://github.com/quantumlib/Cirq/blob/master/docs/operators_and_observables.ipynb\">View source on GitHub</a>\n  </td>\n  <td>\n    <a href=\"https://storage.googleapis.com/tensorflow_docs/Cirq/docs/operators_and_observables.ipynb\">Download notebook</a>\n  </td>\n</table>\n\n\n```\ntry:\n    import cirq\nexcept ImportError:\n    print(\"installing cirq...\")\n    !pip install --quiet cirq\n    print(\"installed cirq.\")\n    import cirq\n    \nimport numpy as np\nimport sympy.parsing.sympy_parser as sympy_parser\n```\n\nThis guide is directed at those already familiar with quantum operations (operators) and observables who want to know how to use them in Cirq. The following table shows an overview of operators.\n\n| Operator | Cirq representation | Guides | Examples | \n|-----|-------|--------|-----|\n| Unitary operators | Any class implementing the `_unitary_` protocol | [Protocols](protocols.ipynb), [Gates and operations](gates.ipynb), [Custom gates](custom_gates.ipynb) | `cirq.Gate` <br> `cirq.X(qubit)` <br> `cirq.CNOT(q0, q1)` <br> `cirq.MatrixGate.on(qubit)` <br> `cirq.Circuit` (if it only contains unitary operations)  |\n| Measurements | `cirq.measure` and `cirq.MeasurementGate`  | [Gates and operations](gates.ipynb) | `cirq.measure(cirq.LineQubit(0))` |  \n| Quantum channels | <ul> <li>Kraus operators (any class implementing the `_kraus_` protocol)</li><li>Pauli basis (cirq.PauliSum)</li> </ul> | [Protocols](protocols.ipynb) | `cirq.DepolarizingChannel(p=0.2)(q0)` <br> `cirq.X.with_probability(0.5)`|\n\nCirq also supports observables on qubits that can be used to calculate expectation values on a given state.\n\n* You can use `cirq.PauliString` to express them,\n* Or you can use `cirq.PauliSum` with real coefficients.\n\n## Operators\n\nQuantum operations (or just *operators*) include unitary gates, measurements, and noisy channels. Operators that act on a given set of qubits implement `cirq.Operation` which supports the Kraus operator representation\n\n$$\n\\rho \\mapsto \\sum_{k} A_k \\rho A_k^\\dagger .\n$$\n\nHere, $\\sum_{k} A_k^\\dagger A_k = I$ and $\\rho$ is a quantum state. Operators are defined in the `cirq.ops` module.\n\n### Unitary operators\n\nStandard unitary operators used in quantum information can be found in `cirq.ops`, for example Pauli-$X$ as shown below.\n\n\n```\nqubit = cirq.LineQubit(0)\nunitary_operation = cirq.ops.X.on(qubit)  # cirq.X can also be used for cirq.ops.X\nprint(unitary_operation)\n```\n\nCirq makes a distinction between gates (independent of qubits) and operations (gates acting on qubits). Thus `cirq.X` is a gate where `cirq.X.on(qubit)` is an operation. See the [guide on gates](gates.ipynb) for more details and additional common unitaries defined in Cirq.\n\n> **Note**: The method `cirq.X.on_each` is a utility to apply `cirq.X` to multiple qubits. Similarly for other operations.\n\nEvery `cirq.Operation` supports the `cirq.channel` protocol which returns its Kraus operators. (Read more about [protocols](protocols.ipynb) in Cirq.)\n\n\n```\nkraus_ops = cirq.kraus(unitary_operation)\nprint(f\"Kraus operators of {unitary_operation.gate} are:\", *kraus_ops, sep=\"\\n\")\n```\n\nUnitary operators also support the `cirq.unitary` protocol.\n\n\n```\nunitary = cirq.unitary(cirq.ops.X)\nprint(f\"Unitary of {unitary_operation.gate} is:\\n\", unitary)\n```\n\nUnitary gates can be raised to powers, for example to implement a $\\sqrt{X}$ operation.\n\n\n```\nsqrt_not = cirq.X ** (1 / 2)\nprint(cirq.unitary(sqrt_not))\n```\n\nAny gate can be controlled via `cirq.ControlledGate` as follows.\n\n\n```\ncontrolled_hadamard = cirq.ControlledGate(sub_gate=cirq.H, num_controls=1)\nprint(cirq.unitary(controlled_hadamard).round(3))\n```\n\nCustom gates can be defined as described in [this guide](custom_gates.ipynb). Some common subroutines which consist of several operations are pre-defined - e.g., `cirq.qft` returns the operations to implement the quantum Fourier transform.\n\n### Measurements\n\nCirq supports measurements in the computational basis.\n\n\n```\nmeasurement = cirq.MeasurementGate(num_qubits=1, key=\"key\")\nprint(\"Measurement:\", measurement)\n```\n\nThe `key` can be used to identify results of measurements when [simulating circuits](simulation.ipynb). A measurement gate acting on a qubit forms an operation.\n\n\n```\nmeasurement_operation = measurement.on(qubit)\nprint(measurement_operation)\n```\n\n> **Note**: The function `cirq.measure` is a utility to measure a single qubit, and the function `cirq.measure_each` is a utility to measure multiple qubits.\n\nAgain measurement operations implement `cirq.Operation` so the `cirq.channel` protocol can be used to get the Kraus operators.\n\n\n```\nkraus_ops = cirq.kraus(measurement)\nprint(f\"Kraus operators of {measurement} are:\", *kraus_ops, sep=\"\\n\\n\")\n```\n\nThe functions `cirq.measure_state_vector` and `cirq.measure_density_matrix` can be used to perform computational basis measurements on state vectors and density matrices, respectively, represented by NumPy arrays.\n\n\n```\npsi = np.ones(shape=(2,)) / np.sqrt(2)\nprint(\"Wavefunction:\\n\", psi.round(3))\n```\n\n\n```\nresults, psi_prime = cirq.measure_state_vector(psi, indices=[0])\n\nprint(\"Measured:\", results[0])\nprint(\"Resultant state:\\n\", psi_prime)\n```\n\n\n```\nrho = np.ones(shape=(2, 2)) / 2.0\nprint(\"State:\\n\", rho)\n```\n\n\n```\nmeasurements, rho_prime = cirq.measure_density_matrix(rho, indices=[0])\n\nprint(\"Measured:\", measurements[0])\nprint(\"Resultant state:\\n\", rho_prime)\n```\n\nThese functions do not modify the input state (`psi` or `rho`) unless the optional argument `out` is provided as the input state.\n\n### Noisy channels\n\nLike common unitary gates, Cirq defines many common noisy channels, for example the depolarizing channel below.\n\n\n```\ndepo_channel = cirq.DepolarizingChannel(p=0.01, n_qubits=1)\nprint(depo_channel)\n```\n\nJust like unitary gates and measurements, noisy channels implement `cirq.Operation`, and we can always use `cirq.channel` to get the Kraus operators.\n\n\n```\nkraus_ops = cirq.kraus(depo_channel)\nprint(f\"Kraus operators of {depo_channel} are:\", *[op.round(2) for op in kraus_ops], sep=\"\\n\\n\")\n```\n\nSome channels can be written\n\n$$\n\\rho \\mapsto \\sum_k p_k U_k \\rho U_k ^\\dagger\n$$\n\nwhere real numbers $p_k$ form a probability distribution and $U_k$ are unitary. Such a *probabilistic mixture* of unitaries supports the `cirq.mixture` protocol which returns $p_k$ and $U_k$. An example is shown below for the bit-flip channel $\\rho \\mapsto (1 - p) \\rho + p X \\rho X$.\n\n\n```\nbit_flip = cirq.bit_flip(p=0.05)\nprobs, unitaries = cirq.mixture(bit_flip)\n\nfor prob, unitary in cirq.mixture(bit_flip):\n    print(f\"With probability {prob}, apply \\n{unitary}\\n\")\n```\n\n> **Note**: Any unitary gate/operation supports `cirq.mixture` because it can be interpreted as applying a single unitary with probability one.\n\nCustom noisy channels can be defined as described in [this guide](noise.ipynb).\n\n### In circuits\n\nAny `cirq.Operation` (pre-defined or user-defined) can be placed in a `cirq.Circuit`. An example with a unitary, noisy channel, and measurement is shown below.\n\n\n```\ncircuit = cirq.Circuit(\n    cirq.H(qubit),\n    cirq.depolarize(p=0.01).on(qubit),\n    cirq.measure(qubit)\n)\nprint(circuit)\n```\n\nThe general input to the circuit constructor is a `cirq.OP_TREE`, i.e., an operation or nested collection of operations. Circuits can be manipulated as described in the [circuits guide](circuits.ipynb) and simulated as described in the [simulation guide](simulation.ipynb).\n\n## Observables\n\nCirq supports observables which are Pauli strings or linear combinations of Pauli strings. Such objects can be used to compute expectation values.\n\n### Pauli strings\n\nPauli products or strings are supported via `cirq.PauliString`. For example, the Pauli string $Z_0 Z_1$ (where subscripts denote qubit indices) can be represented as follows.\n\n\n```\n# Qubit register\nqreg = cirq.NamedQubit.range(2, prefix=\"q\")\n\n# PauliString Z_0 Z_1\nzz = cirq.PauliString(cirq.Z(q) for q in qreg)\nprint(zz)\n```\n\nThe matrix of a Pauli string can be returned via:\n\n\n```\nzz.matrix()\n```\n\nPauli strings can also have arbitrary coefficients.\n\n\n```\nnew = (1.0 - 0.1j) * zz\nprint(new)\n```\n\n### Pauli sums\n\nA `cirq.PauliSum` is a linear combination of `cirq.PauliString`s and represents a Hamiltonian (or general observable) in the Pauli basis. To represent the observable $O = 1.5 Z_0 Z_1 - 0.7 X_0 X_1$, we can first define the $X_0 X_1$ Pauli string:\n\n\n```\nxx = cirq.PauliString(cirq.X(q) for q in qreg)\nprint(xx)\n```\n\nThen form the linear combination.\n\n\n```\npsum = 1.5 * zz - 0.7 * xx\nprint(psum)\n```\n\nLike Pauli strings, we can get the matrix of a `cirq.PauliSum`:\n\n\n```\npsum.matrix()\n```\n\nA Pauli sum can also be constructed from a `Sympy` Boolean expression. This is based on \"On the representation of Boolean and real functions as Hamiltonians for quantum computing\" by Stuart Hadfield (https://arxiv.org/abs/1804.09130)\n\n\n```\npsum = cirq.PauliSum.from_boolean_expression(\n    sympy_parser.parse_expr('x0 ^ x1'),\n    {'x0': cirq.NamedQubit('q0'), 'x1': cirq.NamedQubit('q1')})\n```\n\n### Expectation values\n\nGiven a state $\\rho$ that is prepared by a circuit, expectation values $\\text{Tr} [ \\rho O ]$ where $O$ is an observable can be computed as follows. First, an example circuit:\n\n\n```\ncircuit = cirq.Circuit(cirq.ops.H.on_each(qreg))\nprint(circuit)\n```\n\nThe pattern for computing $\\text{Tr} [ \\rho O ]$ is shown below.\n\n\n```\n!pip install nest-asyncio\n# for running collector under jupyter environment\nimport nest_asyncio\nnest_asyncio.apply()   \n```\n\n**Warning: If you run this notebook in a colab environment with \"Run all\", the cell below may hang forever or you may encounter crash. Please manually run this cell either by pressing the play button to the left of the code, or by using the keyboard shortcut \"Command/Ctrl+Enter\".**\n\n\n```\n# Define a PauliSumCollector.\ncollector = cirq.PauliSumCollector(circuit, psum, samples_per_term=10_000)\n\n# Provide a sampler. See also: collector.collect(...).\ncollector.collect(sampler=cirq.Simulator())\n\n# Estimate the observable.\nenergy = collector.estimated_energy()\nprint(\"Energy:\", energy)\n```\n\nNote that this method uses sampling with a number of samples given by `samples_per_term`. \n\nExpectation values can also be computed from NumPy array representations of quantum states. For example, given a state vector we can do the following.\n\n\n```\n# Get the state vector.\npsi = circuit.final_state_vector()\n\n# Compute the expectation value.\nenergy = psum.expectation_from_state_vector(\n    state_vector=psi, qubit_map={q: i for i, q in enumerate(qreg)}\n)\nprint(\"Energy:\", energy.real)\n```\n\nAnd given a density matrix, we can compute the expectation via:\n\n\n```\n# Get the density matrix.\ndsim = cirq.DensityMatrixSimulator()\nrho = dsim.simulate(circuit).final_density_matrix\n\n# Compute the expectation value.\nenergy = psum.expectation_from_density_matrix(\n    state=rho, qubit_map={q: i for i, q in enumerate(qreg)}\n)\nprint(\"Energy:\", energy.real)\n```\n\n### Pauli expansions\n\nThe function `cirq.pauli_expansion` can return Pauli basis representations of certain objects. For example, given the circuit $H \\otimes H$ from above:\n\n\n```\ncircuit\n```\n\nThe Pauli expansion can be obtained via:\n\n\n```\npsum = cirq.pauli_expansion(circuit)\nprint(psum)\n```\n\nGenerally, the argument to `cirq.pauli_expansion` must define the `_pauli_expansion_` method or have a small unitary representation. The argument `default` can be provided to return a default value if no expansion can be computed.\n", "meta": {"hexsha": "80787deab78f2c673f4af3cb2cfb5f8c18d1b5a2", "size": 24773, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/operators_and_observables.ipynb", "max_stars_repo_name": "Saibaba-Alapati/Cirq", "max_stars_repo_head_hexsha": "782efcd04c3bbf73a0d630306a3d1cfd9966521d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/operators_and_observables.ipynb", "max_issues_repo_name": "Saibaba-Alapati/Cirq", "max_issues_repo_head_hexsha": "782efcd04c3bbf73a0d630306a3d1cfd9966521d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/operators_and_observables.ipynb", "max_forks_repo_name": "Saibaba-Alapati/Cirq", "max_forks_repo_head_hexsha": "782efcd04c3bbf73a0d630306a3d1cfd9966521d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3302658487, "max_line_length": 339, "alphanum_fraction": 0.5763532879, "converted": true, "num_tokens": 3339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.12252320931407357, "lm_q1q2_score": 0.04491575099579103}}
{"text": "# Hello World! \n\n\nThe **Jupyter Notebook** is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. Uses include: data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more.\n\nThere two types of cells in the Jupyter Notebook:\n - Markdowns\n - Code cells\n\n## Changing cell types\n\nDouble click this cell, and change its type to `Code` using the dropdown menu in the toolbar.\n\n\n\nHit `crtl+enter` or `cmd+enter` (OSX) and try to run this cell as a Python code block. Python will throw you an error, given that this cell does not follow its syntax at all :)\n\nSwitch the type of this cell back to `Markdown` and run it again (`crtl+enter` or `cmd+enter` (OSX)) to restore its initial state. \n\n## Markdown cells\n\n**This is a Markdown cell aka text cell**\n\nThis is a table in Markdown\n\n| <b><b> | a | b  | c  | d  |\n|----|----|----|----|----|\n| row1 | 1 | 2  | 3  | 4  |\n| row2 | 5 | 6  | 7  | 8  |\n| row3 | 9 | 10 | 11 | 12 |\n\nTo style your markdown cells you can use HTML and CSS\n\n<div style=\"background-color:cyan\">\n    <p style=\"text-align:center; font-family: Andale Mono; font-size:20px\">\n        This part uses HTML tags and it is styled with css\n    </p>\n<div>\n\nYou can write LaTex in the markdown cells (see the example below)\n\\begin{definition} \\label{def:FT}\nLet $x[n]$ be a sequence of length $N$. Then, its **Fourier transform** is given by\n\\begin{equation}\n\\label{eq:FT}\nX[k]= \\frac{1}{N} \\sum_{n=0}^{N-1} x[n] e^{-j2\\pi \\frac{kn}{N}}\n\\end{equation}\n\\end{definition}\n\n## Code cells\n\n\n```python\n# This is a code cell. This notebook uses a Python3 kernel (see upper right of the notebook). \n# So, we should be coding in Python! \n\n# Run the following line by ctrl+enter or cmd+enter. Feel free to change Hello World text with something else.\n\nprint('Hello World!')\n```\n\n    Hello World!\n\n\n## Some useful keyboard shortcuts to work with JN\n\nFind more on [this website](https://www.cheatography.com/weidadeyue/cheat-sheets/jupyter-notebook/).\n\n## Defining Python functions in JN\n\nFunction definitions follows the traditional Python syntax. \n\nBefore calling a function defined in the notebook, make sure that the cell containing the function definition is executed.\n\n\n```python\n# In this cell, we define the function. \n# You have to run this cell before executing the next one. \n# Otherwise function wont be recognized in the scope of the following cells. \ndef HelloFunction():\n    print('Hello World from the function')\n    print('test')\n    print('test 2')\n        \n```\n\n\n```python\n# Call HelloFunction\n\nHelloFunction()\n```\n\n    Hello World from the function\n    test\n    test 2\n\n\nYou can also save the function to a file using the magic command `%%file`\n\n\n```python\n%%file func1.py\n\n#We are going to save the function above to a file called func.py\n\ndef testFunction():\n    print('Hello World from the function')\n    print('test')\n    print('test 2')\n        \n```\n\n    Writing func1.py\n\n\n## Using your custom Python scripts (*.py) in JN\n\nYou need to make sure that the `*.py` file is in the same directory with your notebook. \n\nI know you had enough of the `Hello World` in this tutorial. Let's have different flavors of them from the `Hello.py` script. \n\n\n```python\n# First we need to use magic command %run followed by the name of the python script we'd like to use\n%run Hello.py\n```\n\n\n```python\nfrom Hello import HelloAdele\nfrom Hello import HelloLionelRichie\nfrom Hello import WhatKindaWorld\n```\n\n\n```python\n# Listen to your favorite Hello song on YouTube by calling the corresponding function. \n# If you wonder to what kind of world we've been keep saying hello, run WhatKindaWorld().\n\n\nWhatKindaWorld()\n```\n\n## Using widgets \n\nTo use the jupyter widgets we first need to install them either using pip or conda (see the commands bellow).\n\n`pip install ipywidgets`\n\n`jupyter nbextension enable --py widgetsnbextension`\n\nor \n\n`conda install -c conda-forge ipywidgets`\n\nSome fun.\n\n\n```python\nimport ipywidgets as widgets\nfrom IPython.display import display, clear_output\nfrom IPython.display import IFrame\n\nddown = widgets.Dropdown(\n    options=['Select your song','Adele', 'Lionel Richie', 'World is'],\n    value='Select your song',\n    disabled=False,\n)\n\n\ndef on_change(change):\n    if change['type'] == 'change' and change['name'] == 'value':\n        if change['new'] == 'Adele':\n            lnk = HelloAdele(1)\n            clear_output(wait=True)\n            display(ddown)\n            display(IFrame(src=lnk, width=420, height=315))\n        elif change['new'] == 'Lionel Richie':\n            lnk = HelloLionelRichie(1)\n            clear_output(wait=True)\n            display(ddown)\n            display(IFrame(src=lnk, width=420, height=315))\n        elif change['new'] == 'World is':\n            lnk = WhatKindaWorld(1)\n            clear_output(wait=True)\n            display(ddown)\n            display(IFrame(src=lnk, width=420, height=315))   \n        if change['new'] == 'Select your song':  \n            clear_output(wait=True)\n            display(ddown)\n\nddown.observe(on_change)\n\ndisplay(ddown)\n```\n\n\n    Dropdown(index=1, options=('Select your song', 'Adele', 'Lionel Richie', 'World is'), value='Adele')\n\n\n\n\n\n\n\n\n## Let's see some more Python code\n\nYour anaconda installation comes with more than 720 Python packages. You can do much more than printing text and opening YouTube videos. In this section, we will use some of them for demonstration. \n\n### Use pandas to create a DataFrame\n\nPandas is one of the most famous Python libraries for data manipulation. Pandas tidy dataframe is commonly used by Python community to analyze and visualize data. In the following cell, you will see how to create a simple dataframe and display it as a table. \n\n\n```python\n# This is how you import a python module\nimport pandas as pd\n\n# From this point on, you can access pandas by the proxy name pd \n\n# Variable raw_data has the type Dictionary. To find more about \n# Dictionaries in Python you can visit this link:\n# https://realpython.com/python-dicts/\n\nraw_data = {'first_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], \n        'last_name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze'], \n        'age': [42, 52, 36, 24, 73], \n        'preTestScore': [4, 24, 31, 2, 3],\n        'postTestScore': [25, 94, 57, 62, 70]}\n\n# Once you have a dictionary variable, you can easily convert it to a dataframe \n# by telling Pandas column names:\n\ndf = pd.DataFrame(raw_data, columns = ['first_name', 'last_name', 'age', 'preTestScore', 'postTestScore'])\n\n# Let's see how our dataframe looks like\ndf\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>first_name</th>\n      <th>last_name</th>\n      <th>age</th>\n      <th>preTestScore</th>\n      <th>postTestScore</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Jason</td>\n      <td>Miller</td>\n      <td>42</td>\n      <td>4</td>\n      <td>25</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Molly</td>\n      <td>Jacobson</td>\n      <td>52</td>\n      <td>24</td>\n      <td>94</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Tina</td>\n      <td>Ali</td>\n      <td>36</td>\n      <td>31</td>\n      <td>57</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Jake</td>\n      <td>Milner</td>\n      <td>24</td>\n      <td>2</td>\n      <td>62</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Amy</td>\n      <td>Cooze</td>\n      <td>73</td>\n      <td>3</td>\n      <td>70</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### Read a data from a csv file into a DataFrame\n\nIn the directory at which this notebook is present, you will find `iris.csv` which belongs to the [Iris flower dataset](https://en.wikipedia.org/wiki/Iris_flower_data_set).\n\nIn the following cell, we will read this `csv` file into a `pandas` dataframe by simply calling `read_csv` method. Then we will show first five data entries in the dataset by calling the `head` method. \n\n\n```python\niris = pd.read_csv('iris.csv')\niris.head()\n\n# Hint: run iris? to see its type\n# Hint: Change iris.head() with iris.tail() above to see last 5 entries instead. \n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>sepal.length</th>\n      <th>sepal.width</th>\n      <th>petal.length</th>\n      <th>petal.width</th>\n      <th>variety</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>5.1</td>\n      <td>3.5</td>\n      <td>1.4</td>\n      <td>0.2</td>\n      <td>Setosa</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>4.9</td>\n      <td>3.0</td>\n      <td>1.4</td>\n      <td>0.2</td>\n      <td>Setosa</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>4.7</td>\n      <td>3.2</td>\n      <td>1.3</td>\n      <td>0.2</td>\n      <td>Setosa</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>4.6</td>\n      <td>3.1</td>\n      <td>1.5</td>\n      <td>0.2</td>\n      <td>Setosa</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>5.0</td>\n      <td>3.6</td>\n      <td>1.4</td>\n      <td>0.2</td>\n      <td>Setosa</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nYou can easily see a statistical summary of your dataset by evoking `describe()` method. \n\n\n```python\niris.describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>sepal.length</th>\n      <th>sepal.width</th>\n      <th>petal.length</th>\n      <th>petal.width</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>150.000000</td>\n      <td>150.000000</td>\n      <td>150.000000</td>\n      <td>150.000000</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>5.843333</td>\n      <td>3.057333</td>\n      <td>3.758000</td>\n      <td>1.199333</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>0.828066</td>\n      <td>0.435866</td>\n      <td>1.765298</td>\n      <td>0.762238</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>4.300000</td>\n      <td>2.000000</td>\n      <td>1.000000</td>\n      <td>0.100000</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>5.100000</td>\n      <td>2.800000</td>\n      <td>1.600000</td>\n      <td>0.300000</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>5.800000</td>\n      <td>3.000000</td>\n      <td>4.350000</td>\n      <td>1.300000</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>6.400000</td>\n      <td>3.300000</td>\n      <td>5.100000</td>\n      <td>1.800000</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>7.900000</td>\n      <td>4.400000</td>\n      <td>6.900000</td>\n      <td>2.500000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### Some basic visualizations using Iris dataset\n\nLooking at tables and their statistical summaries are useful, but they can't beat data visualization. In the following code cell, we use matplotlib to see the correlations between `width` and `height` of the iris flower for its sepal and petal regions. \n\nHint: Petal length-width correlation is higher than that of sepal length-width.\n\n\n\n\n```python\n# Import matplotlib. Use plt as proxy to access package modules\nimport matplotlib.pyplot as plt\n%matplotlib inline  \n# Create a figure \nplt.figure()\n\n# Split figure into subplots 1 row, 2 columns \nfig,ax=plt.subplots(1,2,figsize=(17, 9))\n\n# Use iris.plot() method to create scatter plots. Remember that \n# iris is an pandas object. To see the full reference of \n# pandas.DataFrame.plot visit: \n# https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.plot.html\n\niris.plot(x=\"sepal.length\",y=\"sepal.width\",kind=\"scatter\",ax=ax[0],sharex=False,sharey=False,label=\"sepal\",color='r')\niris.plot(x=\"petal.length\",y=\"petal.width\",kind=\"scatter\",ax=ax[1],sharex=False,sharey=False,label=\"petal\",color='b')\n\n# Set axes labels for subplots. \nax[0].set(title='Sepal comparison ', ylabel='sepal-width')\nax[1].set(title='Petal comparison',  ylabel='petal-width')\nax[0].legend()\nax[1].legend()\n\n# Show the plots\nplt.show()\n```\n", "meta": {"hexsha": "ad94ef03ea5648bf198e79dfff0bba5cdc218ee6", "size": 60082, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "NB01/HelloWorld.ipynb", "max_stars_repo_name": "zelenkastiot/notebooks19", "max_stars_repo_head_hexsha": "bc4a02135ebab00292abb808cf0a36cda424e217", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-09-18T21:50:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-28T09:24:09.000Z", "max_issues_repo_path": "NB01/HelloWorld.ipynb", "max_issues_repo_name": "zelenkastiot/notebooks19", "max_issues_repo_head_hexsha": "bc4a02135ebab00292abb808cf0a36cda424e217", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-09-19T12:28:04.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-25T20:09:49.000Z", "max_forks_repo_path": "NB01/HelloWorld.ipynb", "max_forks_repo_name": "zelenkastiot/notebooks19", "max_forks_repo_head_hexsha": "bc4a02135ebab00292abb808cf0a36cda424e217", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-09-18T19:28:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-03T01:45:27.000Z", "avg_line_length": 63.9850905218, "max_line_length": 33104, "alphanum_fraction": 0.745214873, "converted": true, "num_tokens": 3816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24220562872535947, "lm_q2_score": 0.1847675196261571, "lm_q1q2_score": 0.04475173325907857}}
{"text": "# Neutron Balance and Criticality\n\n## Learning Objectives\n\nAt the end of this lesson, the student should be able to:\n\n- Define the basic components of a reactor (fuel, coolant, moderator, reflector, etc.)\n- Classify conventional reactors based on their components\n- Outline the life cycle of a neutron in a reactor\n- Explain the 6 factors, conceptually: $\\eta$, $\\epsilon$, $p$, $f$, $P_{NL}^{th}$, and $P_{NL}^f$\n- State the 2, 4, and 6 factor formulas\n- Define the terms in the 2, 4, and 6 factor formulas\n- Associate the 2, 4, and 6 factor formulas with their corresponding assumptions\n- Predict the impact of reactor designs on each of the 6 factors\n- Calculate criticality based on the 2, 4, and 6 factor formulas\n\n\n## Reactor basics\n\nReactors have a number of components:\n\n- fuel (uranium, plutonium, various enrichments, fertile isotopes, mixed isotopes, ... )\n- moderator (scattering medium: water, heavy water, graphite, floride or chloride salts, lithium salts, ...)\n- coolant (water, heavy water, helium, carbon dioxide, salts, liquid metals, ...)\n- reflector (graphite, beryllium, ...)\n\nA really good summary of various types of reactors, with images, can be found [here](http://www.theiet.org/factfiles/energy/nuc-reac-page.cfm?type=pdf).\n\n### CANDU\n\n- natural uranium\n- heavy water ($D_2O$)\n- online refuelling\n- each bundle: 50 cm long 10 cm diameter\n\n\n\n\n\n\n\n\n\n\n### PWR \n\n- $UO_2$ fuel\n- Zircalloy cladding (typically)\n- Height: 4.1m\n- Hardware mostly Zircaloy (Zr with Sn, Fe, Cr)\n- Grid spacers: Zircaloy, Inconel, stainless steel\n- End pieces: Stainless steel, Inconel\n- 200-250 fuel assemblies per core\n- Each Assembly: \n  - 14 x 14 to 17 x 17 fuel elements\n  - 21cm x 21cm\n  - Fuel element size: 1 cm diameter, \n  - Fuel element height: 3.9m\n  - Assembly weight: 1400lb\n  - Enrichment: 3-5%\n  - May have separate burnable poison rods\n\n\n<a title=\"By U.S.NRC. [Public domain], via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File:PressurizedWaterReactor.gif\"></a>\n  \n  \n \n \n \n \n\n\n```python\nrod = 400 # pellets per rod\nassembly = 17*17 - 5*5 # assembly array minus control rod tubes\ncore = 193 # typical number of assemblies per core\nprint(\"Total pellets in a core\", core*assembly*rod)\nprint(\"Total rods in a core\", core*assembly)\n```\n\n    Total pellets in a core 20380800\n    Total rods in a core 50952\n\n\n### BWR\n\nA BWR has about 600-800 fuel assemblies per core. Each assembly:\n\n- 14ft (4.5m) tall\n- Zircalloy channel around the assembly\n- Hardware mostly Zircaloy (Zr with Sn, Fe, Cr)\n- Grid spacers: Zircaloy\n- Channel (aka shroud): Zircaloy\n- End pieces: Stainless steel\n- Each assembly\n  - 700lb\n  - 5.5x5.5 inches (14 cm x 14 cm) square assembly\n  - Fuel element array: 8 x 8 or 10 x 10\n  - Fuel element size: 1.25 cm diameter, height = 4.1m\n  - Enrichment: 2.5-4.5%\n  - May have Gd in some rods and variable enrichment in 3D\n  \n<a title=\"By U.S.NRC. [Public domain], via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File:BoilingWaterReactor.gif\"></a>\n\n\n\n### Reaction Rates\n\n- The microscopic cross section is just the likelihood of the event per unit area. \n- The macroscopic cross section is just the likelihood of the event per unit area of a certain density of target isotopes.\n- The reaction rate is the macroscopic cross section times the flux of incident neutrons.\n\n\\begin{align}\nR_{i,j}(\\vec{r}) &= N_j(\\vec{r})\\int dE \\phi(\\vec{r},E)\\sigma_{i,j}(E)\\\\\nR_{i,j}(\\vec{r}) &= \\mbox{reactions of type i involving isotope j } [reactions/cm^3s]\\\\\nN_j(\\vec{r}) &= \\mbox{number of nuclei participating in the reactions } [\\#/cm^3]\\\\\nE &= \\mbox{energy} [MeV]\\\\\n\\phi(\\vec{r},E)&= \\mbox{flux of neutrons with energy E at position i } [\\#/cm^2s]\\\\\n\\sigma_{i,j}(E)&= \\mbox{cross section } [cm^2]\\\\\n\\end{align}\n\n\nThis can be written more simply as $R_x = \\Sigma_x I N$, where I is intensity of the neutron flux.\n\n### Neutron Life Cycle\n\nLet's observe the life cycle of a neutron:\n\n\n\nWe can be more explicit about this with some descriptions of the losses.\n\n\n\n### Two Factor Formula\n\nThe source of neutrons in a reactor are the neutrons from fission. \n\n\\begin{align}\ns &=\\nu \\Sigma_f \\phi\n\\end{align}\n\nwhere\n\n\\begin{align}\ns &= \\mbox{neutrons available for next generation of fissions}\\\\\n\\nu &= \\mbox{the number born per fission}\\\\\n\\Sigma_f &= \\mbox{the number of fissions in the material}\\\\\n\\phi &= \\mbox{initial neutron flux}\n\\end{align}\n\nThis can also be written as:\n\n\\begin{align}\ns &= \\nu\\Sigma_f\\phi\\\\\n  &= \\nu\\frac{\\Sigma_f}{\\Sigma_{a,fuel}}\\frac{\\Sigma_{a,fuel}}{\\Sigma_a}{\\Sigma_a} \\phi\\\\\n  &= \\eta f {\\Sigma_a} \\phi\\\\\n\\eta &= \\frac{\\nu\\Sigma_f}{\\Sigma_{a,fuel}} \\\\\n      &= \\mbox{number of neutrons produced per neutron absorbed by the fuel, \"neutron reproduction factor\"}\\\\\nf &= \\frac{\\Sigma_{a,fuel}}{\\Sigma_a} \\\\\n   &= \\mbox{number of neutrons absorbed in the fuel per neutron absorbed anywhere, \"fuel utilization factor\"}\\\\\n\\end{align}\n\nThis absorption and flux term at the end seeks to capture the fact that some of the neutrons escape. However, if we assume an infinite reactor, we know that all the neutrons are eventually absorbed in either the fuel or the coolant, so we can normalize by $\\Sigma_a\\phi$ and therefore:\n\n\n\\begin{align}\nk_\\infty &= \\frac{\\eta f \\Sigma_a\\phi}{\\Sigma_a \\phi}\\\\\n&= \\eta f\n\\end{align}\n\n### Four Factor Formula\n\nSo, then, if we consider the impact of neutron energy on the likelihood of absorption, we can break the neutrons up into a thermal and a fast group. \n\n\nSo, we can say more explicitly:\n\n\n\\begin{align}\nk_\\infty =& \\epsilon p \\eta f\\\\\n\\epsilon =& \\mbox{ fast fission factor}\\\\\n         =& \\frac{\\mbox{neutrons produced by all fissions}}{\\mbox{neutrons produced by thermal fissions}}\\\\\np =& \\mbox{ resonance escape probability}\\\\\n         =& \\frac{\\mbox{neutrons that reach thermal energies}}{\\mbox{number of fast neutrons that start to slow down}}\n\\end{align}\n\n### Six Factor Formula\n\nIf we consider the non-infinite nature of most reactors, we have to add two more factors to the formula:\n\n\\begin{align}\nk_{eff} =& P_{fnl} P_{tnl}\\epsilon p \\eta f\\\\\nP_{NL}^{f} =& \\mbox{ fast neutron non leakage probability}\\\\\n         =& \\frac{\\mbox{fast neutrons that do not leak from the reactor}}{\\mbox{fast neutrons produced by thermal fissions}}\\\\\nP_{NL}^{th} =& \\mbox{ thermal neutron non leakage probability}\\\\\n         =& \\frac{\\mbox{thermal neutrons that do not leak from the reactor}}{\\mbox{neutrons that reach thermal energies}}\\\\\n\\end{align}\n\n### Criticality and the full life cycle\n\n\nIf criticality, $k$ is the ratio :\n\n\\begin{align}\nk = \\frac{\\mbox{neutrons in generation N}}{\\mbox{neutrons in generation N-1}}\n\\end{align}\n\nThen we can use the life cycle diagram to plug in our six factors to arrive at $k = \\frac{n'}{n}$:\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "f5952292bc1681bcd3245e5f1936059c5057ccdb", "size": 12188, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "reactor-physics/neutron-balance.ipynb", "max_stars_repo_name": "katyhuff/npr247", "max_stars_repo_head_hexsha": "0bc7abf483247ba1a705516393f49703d8263458", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-12-17T06:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T17:14:51.000Z", "max_issues_repo_path": "reactor-physics/neutron-balance.ipynb", "max_issues_repo_name": "katyhuff/npr247", "max_issues_repo_head_hexsha": "0bc7abf483247ba1a705516393f49703d8263458", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-08-29T17:27:24.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-29T17:46:50.000Z", "max_forks_repo_path": "reactor-physics/neutron-balance.ipynb", "max_forks_repo_name": "katyhuff/npr247", "max_forks_repo_head_hexsha": "0bc7abf483247ba1a705516393f49703d8263458", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-08-25T20:00:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T03:05:26.000Z", "avg_line_length": 37.5015384615, "max_line_length": 296, "alphanum_fraction": 0.5886937972, "converted": true, "num_tokens": 1999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24508502416032485, "lm_q2_score": 0.18242552825126704, "lm_q1q2_score": 0.044709764998921805}}
{"text": "```python\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nfrom torch import optim\nimport torch.nn.functional as F\nimport os\nfrom torch.utils.data import DataLoader, sampler\n# load modules\nfrom pytorchtools import EarlyStopping #, Encoder, Decoder\n\ntorch.manual_seed(1)\n```\n\n\n\n\n    <torch._C.Generator at 0x11fc28390>\n\n\n\n\n```python\nUSE_CUDA = torch.cuda.is_available()\ndevice = torch.device(\"cuda\" if USE_CUDA else \"cpu\")\nprint(device)\n```\n\n    cpu\n\n\n# Data Processing\n\n\n```python\nPAD_TOKEN = 0\nSOS_TOKEN = 1\nEOS_TOKEN = 2\n\nclass BuildVocab:\n    def __init__(self):\n        self.word2index = {'<PAD>': PAD_TOKEN, '<SOS>': SOS_TOKEN, '<EOS>': EOS_TOKEN}\n        self.word2count = {}\n        self.index2word = {PAD_TOKEN:'<PAD>', SOS_TOKEN: '<SOS>', EOS_TOKEN: '<EOS>'}\n        self.num_words = 3\n    \n    def fromCorpus(self, corpus):\n        for line in corpus:\n            self.fromSentence(line)\n    \n    def fromSentence(self, line):\n        for word in line:\n            self.toVocab(word)\n    \n    def toVocab(self, word):\n        if word not in self.word2index:\n            self.word2index[word] = self.num_words\n            self.word2count[word] = 1\n            self.index2word[self.num_words] = word\n            self.num_words += 1\n        else:\n            self.word2count[word] += 1\n```\n\n\n```python\ndf = pd.read_csv(\"protein_seq.csv\", index_col=0)\ndf.drop_duplicates(inplace=True)\nprint(\"Trimming sentence from: \", df.shape)\n\n# chop off the sequence length\n# keep sentence length <= a threshhold\nmask = (df[\"meso_seq\"].str.len()<=100)&(df[\"thermal_seq\"].str.len()<=100) ########\ndf = df.loc[mask].reset_index(drop=True)\nprint(\"To: \", df.shape)\n\ninput_seq = df[\"meso_seq\"].tolist()\ntarget_seq = df[\"thermal_seq\"].tolist()\n\nvoc = BuildVocab()\nvoc.fromCorpus(input_seq + target_seq)\nprint(\"Word Count: \", len(voc.word2index))\n```\n\n    Trimming sentence from:  (401885, 4)\n    To:  (1686, 4)\n    Word Count:  24\n\n\n\n```python\n# mapping character to index for all sentences\ndef map_character(voc, line):\n    return [voc.word2index[word] for word in line] + [EOS_TOKEN] # EOS token\n\ndef sequence_padding(ctx, max_len):\n    for index, seq in enumerate(ctx):\n        pad_to_seq = [PAD_TOKEN]*(max_len - len(seq))\n        ctx[index] = [*seq, *pad_to_seq]\n    return ctx\n\ndef target_binary_mask(ctx):\n    for i, line in enumerate(ctx):\n        for j, index in enumerate(line):\n            if index != 0:\n                ctx[i][j] = 1\n    return ctx\n```\n\n\n```python\n# input and output batch shape should be (max_length, batch_size)\ndef input_init(input_batch, voc):\n    mapped_batch = [map_character(voc, line) for line in input_batch]\n    lengths = [len(seq_len) for seq_len in mapped_batch]\n    length_t = torch.tensor(lengths)\n    max_input_len = max(lengths)\n    padded_batch = sequence_padding(mapped_batch, max_input_len)\n    padded_batch_t = torch.LongTensor(padded_batch).t()\n    return padded_batch_t, length_t\n\ndef target_init(target_batch, voc):\n    mapped_batch = [map_character(voc, line) for line in target_batch]\n    max_target_len = max(len(seq_len) for seq_len in mapped_batch)\n    padded_batch = sequence_padding(mapped_batch, max_target_len)\n    padded_batch_t = torch.LongTensor(padded_batch).t()\n    target_mask = target_binary_mask(padded_batch)\n    target_mask_t = torch.ByteTensor(target_mask).t()\n    return max_target_len, padded_batch_t, target_mask_t\n\ndef batch_inp_out(loader):\n    batches = []\n    for input_batch, target_batch in loader:\n        # sort lengths to pack_padded_sequence later\n        input_batch, target_batch = zip(*sorted(zip(input_batch, target_batch),\n                                                key=lambda x:len(x[0]),\n                                                reverse=True))\n        input_batch = list(input_batch)\n        target_batch = list(target_batch)\n        input_t, lengths = input_init(input_batch, voc)\n        max_target_len, target_t, mask_t = target_init(target_batch, voc)\n        batches.append((input_t, lengths, max_target_len, target_t, mask_t))\n    return batches\n\ndef train_val_split(input_seq, target_seq, batch_size):\n    num_train = len(input_seq)\n    indices = list(range(num_train))\n    np.random.shuffle(indices)\n    split = int(np.floor(0.1 * num_train)) # validate on 10% of data\n    train_indx, val_indx = indices[split:], indices[:split]\n    \n    data = list(zip(input_seq, target_seq))\n    train_sampler = sampler.SubsetRandomSampler(train_indx)\n    val_sampler = sampler.SubsetRandomSampler(val_indx)\n    \n    train_loader = DataLoader(data, batch_size=batch_size, sampler=train_sampler, drop_last=True)\n    val_loader = DataLoader(data, batch_size=batch_size, sampler=val_sampler, drop_last=True)\n    \n    train_batches = batch_inp_out(train_loader)\n    val_batches = batch_inp_out(val_loader)\n    return train_batches, val_batches\n```\n\n\n```python\n### test\ntrain_batches, val_batches = train_val_split(input_seq, target_seq, 64)\n# input_t, lengths, max_target_len, target_t, mask_t = train_batches[-1]\ninput_t, lengths, max_target_len, target_t, mask_t = val_batches[-1]\nprint(\"input sequences tensor: \", input_t.shape)\nprint(\"input length tensor: \", len(lengths))\nprint(\"max target length: \", max_target_len)\nprint(\"target sequences tensor: \", target_t.shape)\nprint(\"target binary mask: \", mask_t.shape)\n```\n\n    input sequences tensor:  torch.Size([101, 64])\n    input length tensor:  64\n    max target length:  101\n    target sequences tensor:  torch.Size([101, 64])\n    target binary mask:  torch.Size([101, 64])\n\n\n# Build Neural Network\n## Part I: Encoder\n\n\n```python\n### comment this part if import modules above\n# network inherit from nn.Module (container) and override forward() method\nclass Encoder(nn.Module):\n    def __init__(self, hidden_dim, embedding, layer_dim, dropout=0):\n        super(Encoder, self).__init__()\n        self.layer_dim, self.hidden_dim, self.embedding = layer_dim, hidden_dim, embedding\n        # nn.GRU(input_dim, hidden_dim, layer_dim)\n        self.gru = nn.GRU(hidden_dim, hidden_dim, layer_dim, dropout=dropout, bidirectional=True)\n    \n    # input_seq: (max_length, b atch_size)\n    # input_length: (batch_size)\n    def forward(self, input_seq, input_length):\n        \n        # for each batch_size add a random feature with shape of embedding_dim\n        # embeddings: (max_length, batch_size, embedding_dim=hidden_dim)\n        embeddings = self.embedding(input_seq)\n        \n        # tensor will be concated in time axis\n        # basically, it will again concat the first column (seq), second, ....\n        # pack: (sum_seq_len, num_directions * hidden_size)\n        pack = torch.nn.utils.rnn.pack_padded_sequence(embeddings, input_length)\n        \n        # hidden: (n_layers * num_directions, batch_size, hidden_size)\n        outputs, hidden = self.gru(pack)\n        \n        # unpack outputs: (max_length, batch_size, num_direction * hidden_size)\n        outputs, _ = torch.nn.utils.rnn.pad_packed_sequence(outputs)\n        \n        # sum bidirectional outputs\n        outputs = outputs[:, :, :self.hidden_dim] + outputs[:, :, self.hidden_dim:]\n        return outputs, hidden\n```\n\n\n```python\n## dimension test\nrnn = nn.GRU(6, 20, 2, bidirectional=True)  # (input_size = features, hidden_size, n_layers)\ninputs = torch.randn(5, 3, 6)  # (max_length, batch_size, input_size)\nh0 = torch.randn(2*2, 3, 20)  # (n_layers * num_direction, batch_size, hidden_size)\noutput, hn = rnn(inputs, h0)\nprint(\"Output shape: \", output.shape)  # (max_length, batch_size, hidden_size)\nprint(\"hidden shape:\", hn.shape)  # (n_layers * num_direction, batch_size, hidden_size)\noutput = output[:, :, :20] + output[:, :, 20:]\nprint(\"output shape: \", output.shape)\n```\n\n    Output shape:  torch.Size([5, 3, 40])\n    hidden shape: torch.Size([4, 3, 20])\n    output shape:  torch.Size([5, 3, 20])\n\n\n\n```python\n## something about pack_padded_sequence...\n# (batch_size, max_length)\na = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 0, 0], [9, 10, 0, 0, 0]])\nlength = [5, 3, 2]\ntargets = nn.utils.rnn.pack_padded_sequence(a, length, batch_first=True)\nprint(targets[0]) # concat first element of every batch, second element of every batch...\nprint(targets[1]) # different batch size for each timestep\n```\n\n    tensor([ 1,  6,  9,  2,  7, 10,  3,  8,  4,  5])\n    tensor([3, 3, 2, 1, 1])\n\n\n## Part II. Decoder: token by token until EOS\nUse current hidden state of the decoder and output of encoder.\nGlobal attention's score function:\n                      \n$$\n\\begin{equation}\nScores = \n\\begin{cases}\n    h_t^T h_s & \\text{dot}\\\\\n    h_t W_a h_s & \\text{general}\\\\\n    v_a^T \\tanh(W_a[h_t;h_s]) & \\text{concat}\n\\end{cases}\n\\end{equation}\\\\\n$$\nNote: $h_t$ is the current target decoder state and $h_s$ is all encoder states (= encoder output). $W_a$ is the weight from linear layer.\n\n\n```python\n### comment this part if modules loaded from above\nclass Attn(torch.nn.Module):\n    def __init__(self, method, hidden_size):\n        super(Attn, self).__init__()\n        self.method = method\n        self.hidden_size = hidden_size\n    \n    # current decoder state (ht): (1, batch_size, hidden_size) \n    # encoder output (hs): (max_length, batch_size, hidden_size)\n    # return: (max_length, batch_size)\n    def attn_dot(self, ht, hs):\n        return torch.sum(ht * hs, dim=2) # sum across hidden_size\n    \n    # return: (batch_size, 1, max_length)\n    def forward(self, ht, hs):\n        # (batch_size, max_length)\n        score = self.attn_dot(ht, hs).t()\n        # normalize across each row so that the sum of each col in a row will be 1\n        # and add one dimension\n        return F.softmax(score, dim=1).unsqueeze(1)\n```\n\n\n```python\n## Test Attn\natt = Attn('dot', 20)\nht = torch.randn(1, 5, 20)\nhs = torch.randn(10, 5, 20)\natt.forward(ht, hs).shape\n```\n\n\n\n\n    torch.Size([5, 1, 10])\n\n\n\n\n```python\n### comment this part if modules loaded above\nclass Decoder(nn.Module):\n    # note: input_size=feature size, output_size = vocabulary size\n    def __init__(self, method, embedding, hidden_size, output_size, n_layer=1, dropout=0):\n        super(Decoder, self).__init__()\n        self.method, self.hidden_size, self.output_size, self.n_layer = method, hidden_size, output_size, n_layer\n        self.embedding = embedding\n        self.embedding_dropout = nn.Dropout(dropout)\n        # embed_size = hidden_size here\n        self.gru = nn.GRU(hidden_size, hidden_size, n_layer, dropout=dropout)\n        self.concat = nn.Linear(hidden_size*2, hidden_size)\n        self.out = nn.Linear(hidden_size, output_size) \n        self.attn = Attn(method, hidden_size)\n    \n    # decoder_input: (1, batch_size) one batch of words at a time\n    # decoder_hidden: (n_layer * num_directional, batch_size, hidden_size)\n    # encoder_output: (max_length, batch_size, hidden_size)\n    def forward(self, decoder_input, decoder_hidden, encoder_output):\n        # embeds: (1, batch_size, embed_size=hidden_size)\n        embeds = self.embedding_dropout(self.embedding(decoder_input))\n\n        # only one word, no need to pack padded sequence...\n        \n        # decoder_output: (1, batch_size, hidden_size)\n        # hidden: (n_layers * num_directions, batch_size, hidden_size)\n        decoder_output, hidden = self.gru(embeds, decoder_hidden)\n        # calculate attention weight\n        # score: (batch_size, 1, max_length)\n        score = self.attn(decoder_output, encoder_output)\n        # context: (batch_size, hidden_size)\n        context = score.bmm(encoder_output.transpose(0, 1)).squeeze(1)\n        # decoder_output: (batch_size, hidden_size)\n        decoder_output = decoder_output.squeeze(0)\n        # concat into (batch_size, hidden_size*2)\n        linear_input = torch.cat((decoder_output, context), 1)\n        concat_output = torch.tanh(self.concat(linear_input))\n        # predict next word: (batch_size, vocab_size)\n        output = F.softmax(self.out(concat_output), dim=1)\n        return output, hidden\n```\n\n\n```python\n## test\nlinear_input_t = torch.randn(3, 8)  # (batch_size, hidden_size)\nconcat = nn.Linear(8, 4)\nconcat_output_t = torch.tanh(concat(linear_input_t))\nout = nn.Linear(4, 5) \noutput = F.softmax(out(concat_output_t), dim=1)\nprint(output.shape)\nprint(output)\nf, t = output.topk(1) # torch.max(decoder_output, dim=1)\nprint(f)\nprint(t)\n```\n\n    torch.Size([3, 5])\n    tensor([[0.1057, 0.1441, 0.1823, 0.4148, 0.1531],\n            [0.1375, 0.1852, 0.1354, 0.2544, 0.2876],\n            [0.1331, 0.1758, 0.1664, 0.2730, 0.2516]], grad_fn=<SoftmaxBackward>)\n    tensor([[0.4148],\n            [0.2876],\n            [0.2730]], grad_fn=<TopkBackward>)\n    tensor([[3],\n            [4],\n            [3]])\n\n\n\n```python\n# calculate loss and ignore padded part\n# dec_out: (batch_size, vocab_size)\ndef loss_func(dec_out, target, mask):\n    # (batch_size, 1)\n    target = target.view(-1, 1)\n    # negative log likelihood\n    crossEntropy = -torch.log(torch.gather(dec_out, 1, target).squeeze(1))\n    # select non-zero elements and calculate the mean\n    loss = crossEntropy.masked_select(mask).mean()\n    loss = loss.to(device)\n    return loss, mask.sum().item()\n```\n\n\n```python\n## test loss_func\ndec_out = torch.randn(5, 7)\ndec_out = F.softmax(dec_out, dim=1)\ntarget = torch.LongTensor([3, 5, 4, 1, 2])\nmask = torch.tensor([1, 1, 0, 0, 1], dtype=torch.uint8)\nloss_func(dec_out, target, mask)\n# print(\"Dec_out:\", dec_out)\n# target = target.view(-1, 1)\n# print(\"target:\", target)\n# gather = torch.gather(dec_out, 1, target).squeeze(1)\n# print(\"gather:\", gather)\n# crossEntropy = -torch.log(gather)\n# print(\"crossEntropy:\", crossEntropy)\n# loss = crossEntropy.masked_select(mask)\n# print(\"loss:\", loss)\n```\n\n\n\n\n    (tensor(2.1858), 3)\n\n\n\n## Part III. Training Process\n\n\n```python\ndef loss_calulation(encoder, decoder, batch, batch_size, teacher_forcing_r):\n    \n    input_t, lengths, max_target_len, target_t, mask_t = batch\n    \n    input_t = input_t.to(device)\n    lengths = lengths.to(device)\n    target_t = target_t.to(device)\n    mask_t = mask_t.to(device)\n    \n    encoder_output, encoder_hidden = encoder(input_t, lengths)\n    decoder_input = torch.LongTensor([[SOS_TOKEN for _ in range(batch_size)]])\n    decoder_input = decoder_input.to(device)\n    # set initial decoder hidden state to the encoder's final state\n    decoder_hidden = encoder_hidden[:decoder.n_layer]\n    \n    loss = 0\n    print_loss = []\n    nTotals = 0\n    if np.random.random() < teacher_forcing_r:\n        for step in range(max_target_len):\n            decoder_output, decoder_hidden = decoder(decoder_input, decoder_hidden, encoder_output)\n            # teacher forcing: next input is current target\n            decoder_input = target_t[step].view(1, -1)\n            mask_loss, nTotal = loss_func(decoder_output, target_t[step], mask_t[step])\n            loss += mask_loss\n            print_loss.append(mask_loss.item()*nTotal)\n            nTotals += nTotal\n    else:\n        for step in range(max_target_len):\n            decoder_output, decoder_hidden = decoder(decoder_input, decoder_hidden, encoder_output)\n            # non teacher forcing: next input is current decoder output\n            # choose the index of word with highest possibility\n            _, indx = torch.max(decoder_output, dim=1) \n            decoder_input = torch.LongTensor([[indx[i] for i in range(batch_size)]])\n            decoder_input.to(device)\n            mask_loss, nTotal = loss_func(decoder_output, target_t[step], mask_t[step])\n            loss += mask_loss\n            print_loss.append(mask_loss.item()*nTotal)\n            nTotals += nTotal\n    \n    return print_loss, loss, nTotals\n```\n\n\n```python\n# train for a fixed iterations\ndef train(input_seq, target_seq, batch_size, epochs, hidden_dim, embedding, encoder, decoder,\n          encoder_opt, decoder_opt, teacher_forcing_r, epoch_from, folder, early_stopping_flag,\n          patience=20):\n    \n    avg_train_loss = []\n    avg_val_loss = []\n    \n    train_batches, val_batches = train_val_split(input_seq, target_seq, batch_size)\n    \n    print(encoder)\n    print(decoder)\n    \n    if early_stopping_flag:\n        early_stopping = EarlyStopping(patience=patience)\n    \n    for epoch in range(epoch_from, epochs):\n        ############\n        # Training #\n        ############\n        encoder.train()\n        decoder.train()\n        train_loss = []\n        for train_batch in train_batches:\n            # initialize and move the model to GPU/CPU\n            # set training mode\n            encoder_opt.zero_grad()\n            decoder_opt.zero_grad()\n\n            print_loss, loss, nTotals = loss_calulation(encoder, decoder, train_batch, batch_size, teacher_forcing_r)\n\n            loss.backward()\n\n            _ = torch.nn.utils.clip_grad_norm_(encoder.parameters(), 1.0)\n            _ = torch.nn.utils.clip_grad_norm_(decoder.parameters(), 1.0)\n\n            encoder_opt.step()  # update weights\n            decoder_opt.step()\n            \n            train_loss.append(sum(print_loss) / nTotals)\n        \n        print(\"train_finished!\")\n        ##############\n        # validation #\n        ##############\n        encoder.eval()\n        decoder.eval()\n        val_loss = []\n        for val_batch in val_batches:\n            print_loss, _, nTotals = loss_calulation(encoder, decoder, val_batch, batch_size, teacher_forcing_r)\n            \n            val_loss.append(sum(print_loss) / nTotals)  # loss for batches\n\n        avg_train_loss.append(np.average(train_loss))  # loss for epochs\n        avg_val_loss.append(np.average(val_loss))\n        print(\"Epoch: {}; train loss: {:.4}; val loss: {:.4}\".format(epoch + 1, avg_train_loss[-1], avg_val_loss[-1]))\n        \n        model_states = (\n            epoch,\n            encoder.state_dict(),\n            decoder.state_dict(),\n            encoder_opt.state_dict(),\n            decoder_opt.state_dict(),\n            voc.__dict__,\n            embedding.state_dict())\n        \n        if early_stopping_flag:\n            early_stopping(avg_val_loss[-1], model_states, folder)\n\n            if early_stopping.early_stop:\n                print('EarlyStopping ...')\n                break\n        \n    return avg_train_loss, avg_val_loss\n```\n\n## Part IV. Run the Model\n\n\n```python\n# hyperparameters\nhidden_dim = 300\nenc_layer_dim = 2\ndec_layer_dim = 2\ndropout = 0.1\nattn_method = \"dot\"\nlr = 0.0001\nteacher_forcing_r = 0.5\nbatch_size = 64\nepochs = 2000\n```\n\n\n```python\ndef run(folder, loadMode, early_stopping_flag):\n    if not os.path.exists(folder):\n        os.makedirs(folder)\n\n    if loadMode:\n        checkpoint = torch.load(loadMode)\n        enc_chp = checkpoint[\"enc\"]\n        dec_chp = checkpoint[\"dec\"]\n        enc_opt_chp = checkpoint[\"enc_opt\"]\n        dec_opt_chp = checkpoint[\"dec_opt\"]\n        voc.__dict__ = checkpoint[\"voc_dict\"]\n        embedding_chp = checkpoint[\"embedding\"]\n\n    embedding = nn.Embedding(voc.num_words, hidden_dim)\n    if loadMode:\n        embedding.load_state_dict(embedding_chp)\n\n    encoder = Encoder(hidden_dim, embedding, enc_layer_dim, dropout)\n    decoder = Decoder(attn_method, embedding, hidden_dim, voc.num_words, dec_layer_dim, dropout)\n    if loadMode:\n        encoder.load_state_dict(enc_chp)\n        decoder.load_state_dict(dec_chp)\n\n    encoder = encoder.to(device)\n    decoder = decoder.to(device)\n\n    encoder_opt = optim.Adam(encoder.parameters(), lr=lr)\n    decoder_opt = optim.Adam(decoder.parameters(), lr=lr)\n\n    epoch_from = 0\n    if loadMode:\n        encoder_opt.load_state_dict(enc_opt_chp)\n        decoder_opt.load_state_dict(dec_opt_chp)\n        epoch_from = checkpoint['epoch'] + 1\n\n    train_loss, val_loss = train(input_seq, target_seq, batch_size, epochs, hidden_dim, embedding,\n                                 encoder, decoder, encoder_opt, decoder_opt, teacher_forcing_r,\n                                 epoch_from, folder, early_stopping_flag)\n    \n    with open(os.path.join(folder, 'loss.txt'), 'w') as f:\n        for loss1, loss2 in list(zip(train_loss, val_loss)):\n            f.write(\"{}\\t{}\\n\".format(loss1, loss2))\n```\n\n\n```python\n## training process\nfolder = os.path.join(\"checkpoints\", \"{}_{}_{}\".format(enc_layer_dim, dec_layer_dim, hidden_dim))\nloadMode = None\nearly_stopping_flag = False\n\nrun(folder, loadMode, early_stopping_flag)\n```\n\n    Encoder(\n      (embedding): Embedding(24, 300)\n      (gru): GRU(300, 300, num_layers=2, dropout=0.1, bidirectional=True)\n    )\n    Decoder(\n      (embedding): Embedding(24, 300)\n      (embedding_dropout): Dropout(p=0.1)\n      (gru): GRU(300, 300, num_layers=2, dropout=0.1)\n      (concat): Linear(in_features=600, out_features=300, bias=True)\n      (out): Linear(in_features=300, out_features=24, bias=True)\n      (attn): Attn()\n    )\n    train_finished!\n    Epoch: 1; train loss: 3.035; val loss: 2.93\n    train_finished!\n    Epoch: 2; train loss: 2.916; val loss: 2.89\n    train_finished!\n    Epoch: 3; train loss: 2.884; val loss: 2.868\n    train_finished!\n    Epoch: 4; train loss: 2.871; val loss: 2.866\n    train_finished!\n    Epoch: 5; train loss: 2.863; val loss: 2.861\n    train_finished!\n    Epoch: 6; train loss: 2.859; val loss: 2.86\n    train_finished!\n    Epoch: 7; train loss: 2.854; val loss: 2.854\n    train_finished!\n    Epoch: 8; train loss: 2.85; val loss: 2.853\n    train_finished!\n    Epoch: 9; train loss: 2.847; val loss: 2.849\n    train_finished!\n    Epoch: 10; train loss: 2.843; val loss: 2.829\n    train_finished!\n    Epoch: 11; train loss: 2.838; val loss: 2.825\n    train_finished!\n    Epoch: 12; train loss: 2.829; val loss: 2.816\n    train_finished!\n    Epoch: 13; train loss: 2.815; val loss: 2.801\n    train_finished!\n    Epoch: 14; train loss: 2.814; val loss: 2.799\n    train_finished!\n    Epoch: 15; train loss: 2.808; val loss: 2.81\n    train_finished!\n    Epoch: 16; train loss: 2.805; val loss: 2.795\n    train_finished!\n    Epoch: 17; train loss: 2.801; val loss: 2.8\n    train_finished!\n    Epoch: 18; train loss: 2.799; val loss: 2.792\n    train_finished!\n    Epoch: 19; train loss: 2.799; val loss: 2.81\n    train_finished!\n    Epoch: 20; train loss: 2.793; val loss: 2.804\n    train_finished!\n    Epoch: 21; train loss: 2.791; val loss: 2.801\n    train_finished!\n    Epoch: 22; train loss: 2.786; val loss: 2.795\n    train_finished!\n    Epoch: 23; train loss: 2.786; val loss: 2.782\n    train_finished!\n    Epoch: 24; train loss: 2.786; val loss: 2.808\n    train_finished!\n    Epoch: 25; train loss: 2.78; val loss: 2.783\n    train_finished!\n    Epoch: 26; train loss: 2.779; val loss: 2.776\n    train_finished!\n    Epoch: 27; train loss: 2.774; val loss: 2.774\n    train_finished!\n    Epoch: 28; train loss: 2.772; val loss: 2.808\n    train_finished!\n    Epoch: 29; train loss: 2.783; val loss: 2.807\n    train_finished!\n    Epoch: 30; train loss: 2.764; val loss: 2.772\n    train_finished!\n    Epoch: 31; train loss: 2.763; val loss: 2.772\n    train_finished!\n    Epoch: 32; train loss: 2.763; val loss: 2.792\n    train_finished!\n    Epoch: 33; train loss: 2.769; val loss: 2.791\n    train_finished!\n    Epoch: 34; train loss: 2.755; val loss: 2.768\n    train_finished!\n    Epoch: 35; train loss: 2.759; val loss: 2.781\n    train_finished!\n    Epoch: 36; train loss: 2.76; val loss: 2.779\n    train_finished!\n    Epoch: 37; train loss: 2.756; val loss: 2.779\n    train_finished!\n    Epoch: 38; train loss: 2.753; val loss: 2.763\n    train_finished!\n    Epoch: 39; train loss: 2.748; val loss: 2.787\n    train_finished!\n    Epoch: 40; train loss: 2.759; val loss: 2.785\n    train_finished!\n    Epoch: 41; train loss: 2.745; val loss: 2.779\n    train_finished!\n    Epoch: 42; train loss: 2.749; val loss: 2.797\n    train_finished!\n    Epoch: 43; train loss: 2.74; val loss: 2.776\n    train_finished!\n    Epoch: 44; train loss: 2.735; val loss: 2.786\n    train_finished!\n    Epoch: 45; train loss: 2.735; val loss: 2.781\n    train_finished!\n    Epoch: 46; train loss: 2.742; val loss: 2.783\n    train_finished!\n    Epoch: 47; train loss: 2.732; val loss: 2.771\n    train_finished!\n    Epoch: 48; train loss: 2.734; val loss: 2.783\n    train_finished!\n    Epoch: 49; train loss: 2.731; val loss: 2.804\n    train_finished!\n    Epoch: 50; train loss: 2.741; val loss: 2.775\n    train_finished!\n    Epoch: 51; train loss: 2.743; val loss: 2.775\n    train_finished!\n    Epoch: 52; train loss: 2.731; val loss: 2.775\n    train_finished!\n    Epoch: 53; train loss: 2.732; val loss: 2.78\n    train_finished!\n    Epoch: 54; train loss: 2.73; val loss: 2.754\n    train_finished!\n    Epoch: 55; train loss: 2.716; val loss: 2.782\n    train_finished!\n    Epoch: 56; train loss: 2.729; val loss: 2.803\n    train_finished!\n    Epoch: 57; train loss: 2.722; val loss: 2.755\n    train_finished!\n    Epoch: 58; train loss: 2.719; val loss: 2.802\n    train_finished!\n    Epoch: 59; train loss: 2.706; val loss: 2.75\n    train_finished!\n    Epoch: 60; train loss: 2.714; val loss: 2.771\n    train_finished!\n    Epoch: 61; train loss: 2.719; val loss: 2.774\n    train_finished!\n    Epoch: 62; train loss: 2.713; val loss: 2.756\n    train_finished!\n    Epoch: 63; train loss: 2.717; val loss: 2.801\n    train_finished!\n    Epoch: 64; train loss: 2.698; val loss: 2.806\n    train_finished!\n    Epoch: 65; train loss: 2.717; val loss: 2.804\n    train_finished!\n    Epoch: 66; train loss: 2.706; val loss: 2.776\n    train_finished!\n    Epoch: 67; train loss: 2.723; val loss: 2.787\n    train_finished!\n    Epoch: 68; train loss: 2.702; val loss: 2.773\n    train_finished!\n    Epoch: 69; train loss: 2.692; val loss: 2.757\n    train_finished!\n    Epoch: 70; train loss: 2.7; val loss: 2.752\n    train_finished!\n    Epoch: 71; train loss: 2.71; val loss: 2.781\n    train_finished!\n    Epoch: 72; train loss: 2.698; val loss: 2.769\n    train_finished!\n    Epoch: 73; train loss: 2.683; val loss: 2.785\n    train_finished!\n    Epoch: 74; train loss: 2.675; val loss: 2.784\n    train_finished!\n    Epoch: 75; train loss: 2.681; val loss: 2.752\n    train_finished!\n    Epoch: 76; train loss: 2.681; val loss: 2.809\n    train_finished!\n    Epoch: 77; train loss: 2.68; val loss: 2.807\n    train_finished!\n    Epoch: 78; train loss: 2.672; val loss: 2.78\n    train_finished!\n    Epoch: 79; train loss: 2.662; val loss: 2.771\n    EarlyStopping ...\n\n\n## Part V. Inference Process\n\n\n```python\n# Inference shares the same encoder/decoder structure as training process\nclass InferenceDecoder(nn.Module):\n    def __init__(self, encoder, decoder):\n        super(InferenceDecoder, self).__init__()\n        self.encoder = encoder\n        self.decoder = decoder\n    \n    def forward(self, input_t, lengths, max_target_len):\n        encoder_output, encoder_hidden = encoder(input_t, lengths)\n        decoder_input = torch.LongTensor([[SOS_TOKEN]])\n        decoder_hidden = encoder_hidden[:decoder.n_layer]\n        \n        preds = torch.LongTensor()\n        probs = torch.zeros([0])\n        \n        decoder_input = decoder_input.to(device)\n        preds = preds.to(device)\n        probs = probs.to(device)\n        \n        for _ in range(max_target_len):\n            decoder_output, decoder_hidden = self.decoder(decoder_input, decoder_hidden, encoder_output)\n            prob, indx = torch.max(decoder_output, dim=1)\n            # non teacher forcing\n            decoder_input = torch.LongTensor([[indx]])\n            preds = torch.cat((preds, indx), dim=0)\n            probs = torch.cat((probs, prob), dim=0)\n            if preds[-1] == EOS_TOKEN:\n                break\n        \n        return preds, probs\n```\n\n\n```python\n# one test_seq at a time\ndef evaluation(inference, voc, test_seq):    \n    # word2index\n    mapped_batch = [map_character(voc, test_seq)]\n    lengths = torch.tensor([len(mapped_batch[0])])\n    input_batch = torch.LongTensor(mapped_batch).t()\n    input_batch = input_batch.to(device)\n    lengths = lengths.to(device)\n    preds, probs = inference(input_batch, lengths, 100)\n    decoded_words = [voc.index2word[indx.item()] for indx in preds]\n    return decoded_words\n```\n\n\n```python\ndef translate(loadMode, rand_indx):\n    checkpoint = torch.load(loadMode)\n    enc_chp = checkpoint[\"enc\"]\n    dec_chp = checkpoint[\"dec\"]\n    voc.__dict__ = checkpoint[\"voc_dict\"]\n    embedding_chp = checkpoint[\"embedding\"]\n\n    embedding = nn.Embedding(voc.num_words, hidden_dim)\n    embedding.load_state_dict(embedding_chp)\n\n    encoder = Encoder(hidden_dim, embedding, enc_layer_dim, dropout)\n    decoder = Decoder(attn_method, embedding, hidden_dim, voc.num_words, dec_layer_dim, dropout)\n    encoder.load_state_dict(enc_chp)\n    decoder.load_state_dict(dec_chp)\n\n    encoder = encoder.to(device)\n    decoder = decoder.to(device)\n    \n    encoder.eval()\n    decoder.eval()\n\n    test_seq = input_seq[rand_indx]\n    test_tar = target_seq[rand_indx]\n    inference = InferenceDecoder(encoder, decoder)\n    decoded_words = evaluation(inference, voc, test_seq)\n    print(\"Input: \", test_seq)\n    print(\"Target: \", test_tar)\n    print(\"Prediction:\", ''.join(decoded_words))\n```\n\n\n```python\n## translation process\nseq_indx = np.random.choice(range(len(input_seq)))\nloadMode = os.path.join(folder, \"checkpoint.tar\")\ntranslate(loadMode, seq_indx)\n```\n\n    Input:  MQINYPINPDWTTDELIEVVEFYNVVAQANEGGVEREVFLDSYRAFKRIVTSKSEEKQLNAVHDEQTGYSTYRTVQAAMKSSSKMIKL\n    Target:  MKFYTIKLPRFLGGIVRAVLNAFKKG\n    Prediction: MKIPPPPPVPDDDERRRRRRRRRRRRRRRLLLKKLKKLKKLKLKKLKLKLKLKELKEEELKEEEELKEEEEEEELEEEEEEEEEEEEE<EOS>\n\n\n## Part VI. Plot Result\n\n\n```python\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\n\n```python\n# visualize the loss as the network trained\nfig = plt.figure(figsize=(10,8))\nplt.plot(range(1,len(train_loss)+1),train_loss, label='Training Loss')\nplt.plot(range(1,len(val_loss)+1),val_loss,label='Validation Loss')\n\n# find position of lowest validation loss\nminposs = val_loss.index(min(val_loss))+1 \nplt.axvline(minposs, linestyle='--', color='r',label='Early Stopping Checkpoint')\n\nplt.xlabel('epochs')\nplt.ylabel('loss')\nplt.xlim(0, len(train_loss)+1) # consistent scale\nplt.grid(True)\nplt.legend()\nplt.tight_layout()\nplt.show()\nfig.savefig('loss_plot.png', bbox_inches='tight')\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "fc9dcf3f2f8eaf9a963914bb41cf38feac654f50", "size": 102312, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Seq2Seq_in_Pytorch.ipynb", "max_stars_repo_name": "Lenaxiao/thermalizer", "max_stars_repo_head_hexsha": "1ffa6cbc60a51e59062829daee7449d90b11254d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Seq2Seq_in_Pytorch.ipynb", "max_issues_repo_name": "Lenaxiao/thermalizer", "max_issues_repo_head_hexsha": "1ffa6cbc60a51e59062829daee7449d90b11254d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Seq2Seq_in_Pytorch.ipynb", "max_forks_repo_name": "Lenaxiao/thermalizer", "max_forks_repo_head_hexsha": "1ffa6cbc60a51e59062829daee7449d90b11254d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-02-22T19:05:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-02T11:26:09.000Z", "avg_line_length": 87.595890411, "max_line_length": 60528, "alphanum_fraction": 0.7947650324, "converted": true, "num_tokens": 8336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.09009299335118119, "lm_q1q2_score": 0.04469457808008556}}
{"text": "<!-- Note on the Springer T2 style: here we use the modifications -->\n<!-- introduced in t2do.sty and svmonodo.sty (both are bundled with DocOnce). -->\n\n# Nuclear Many-body Physics; a Computational Approach\n**May 4, 2015**\n\n# Preface\n<div id=\"ch:preface\"></div>\n\n\nNearly all of physics is many-body physics at the most  \nmicroscopic level of understanding.\nA theoretical understanding of the behavior of quantum mechanical systems with many interacting particles,\naccompanied with experiments and simulations,   \nis a  great challenge and provides fundamental insights into systems governed by quantum mechanical principles.\n\nMany-body physics  applications range from condensed matter physics\n(for example antiferromagnets, quantum liquids and solids, plasmas, metals,\nsuperconductors), nuclear and high energy physics (for example nuclear matter, finite\nnuclei, quark-gluon plasmas), dense matter astrophysics (for example  neutron\nstars, white dwarfs), atoms and molecules (for example electron correlations,\nreactions, quantum chemistry), and elementary particles\n(for example quantum field theory, lattice gauge field models). \n\nMicroscopic many-body methodologies have attained a high degree of\nsophistication in the last decades, from both theoretical and\napplicative  points of view. These developments have allowed\nresearchers to adapt these technologies to a much wider range of physical\nsystems, and to obtain quantitative descriptions of many \nobservables. \n\nSeveral of these methods have been developed independently of each other.\nIn some  cases the same methods have been applied and studied in different\nfields of research with little overlap and exchange of knowledge. \nA classic example is the development of coupled-cluster approaches,\nwhich originated from the nuclear many-body problem in the late fifties.\nThese methods were adapted and refined \nto extremely high precision and predicability by quantum chemists over \nthe next four decades. The developments comprised, and still do,  \nboth methodological innovations and the usage of advances in high-performance computing.    \nAs time elapsed,   \nthe overlap with the original nuclear many-body problem vanished gradually, \ndwindling almost to a non-vanishing exchange of knowledge and methodologies. \nThese methods were however revived in nuclear physics towards the turn of the last century and offer now a viable approach\nto *ab initio* We would like to come with a warning here, since it is our feeling that the \nlabelling *ab initio* attached to many titles of scientific articles nowadays, has reached an inflationary stage. \nWith *ab initio* we will mean solving Schroedinger's or Dirac's many-particle equations starting with the presumably best \ninter-particle Hamiltonian, making no approximations. The particles that make up the many-body problem will be approximated \nas the constituent ones. \nIn the nuclear many-body problem\nthese are various baryons such as protons, neutrons, isobars and hyperons and low-mass mesons. All many-body approaches discussed in this text involve\nsome approximations, and only few of them, if any,  can reach the glorious stage of being truely *ab initio*.\nTruely *ab initio* in nuclear physics means to solve the many-body problem starting with quarks and gluons.\nnuclear structure  studies of nuclei,   spanning the whole range of stable closed-shell and several open-shell nuclei. \n\n\nMany of the developments are also not \nalways readily accessible to a larger community of\nresearchers and especially to the young and uninitiated ones. A notorious exception is \nagain the quantum chemistry community, where highly effecient codes and methods are made available.  \nNumerical packages like\nGamess, Dalton and Gaussian provide a reliable computational \nplatform for many  chemical applications and studies.\nIn other fields this is not always the case.     \n\nNuclear physics, where we have our basic research experience, is such a field.\nThis book aims therefore at giving you an overview \nof widely used quantum mechanical  many-body methods. We want also to provide you with computational tools in order to enable you\nto perform studies of realistic systems  in nuclear physics. \nThe methods we discuss are however not limited to applications\nin nuclear physics, rather, with  minor  changes one can apply them to other fields, from quantum chemistry, via studies of atoms and\nmolecules to materials science and solid state devices such as quantum dots.  \n\nTypical methods we will discuss are \nconfiguration interaction and large-scale diagonalization.methods (shell-model in nuclear physics), perturbative many-body methods, \ncoupled cluster theory, Green's function approaches, various Monte Carlo methods, extensions to weakly  bound systems and links\nfrom *ab initio* methods to  density functional and mean field theories. \nThe methods we have chosen are those which enjoy a great degree of popularity in low and intermediate energy nuclear physics, \nbut due to both our limited knowledge\nand due to space considerations, some of these will be treated in rather cavalier way.\n\nFocussing on methods and tools only is however not necessarily a recipe for success, as we all know a \na bad workman quarrels with his tools. Our aim is to provide \nyou with a didactical description\nof some of these  powerful methods and tools with the purpose of allowing you to\ngain further insights and a possible working experience in modern many-body methods.\nThere are several textbooks on the market which cover specific \nmany-body methods and/or applications, but almost none of them\npresents an updated and comparative description of various many-body methods. The reason for choosing such an approach\nis that we want you, the reader, to gain the experience and form your own opinion on the suitability and applicability\nof specific methods. Too often you may have met many-body practitioners\nclaiming 'my method is better than your method because...'.  We wish to avoid such a pitfal, although ours, as any other approach,\nis tainted by our biases, preferences and obviously ignorance about all possible details. \n\nWe also  want  to shed light, in a hopefully unbiased way, on possible interplays and\ndifferences between the various many-body methods with a focus\non the physics content. \nWe have therefore selected several physical systems,\nfrom simple models to realistic cases,  whose properties can be\ndescribed within the theoretical frameworks presented here.\nIn this text we will expose you to problems which tour many nuclear physics applications, \nfrom the basic forces which bind nucleons together to compact objects such as neutron stars.  \nOur hope is that the material we have provided   allows an eventual reader to  assess \nby himself/herself the pro and cons of the methods discussed.\n\nMoreover,  the text can be used and read as a large project. Each chapter ends with a specific project. The code you end up developing \nfor that particular project, can in turn be  reused in the next chapter and its pertaining project.  To give you an example,\nin chapter xx you will end up constructing your own nucleon-nucleon interaction and solve its Schr\\\"odinger equation using the Lippman-Schwinger\nequation.  This solution results in the so-called $T$-matrix  which in turn can be related to the experimental phase shifts.\nThe Lippman-Schwinger equation can easily be modified to account for a given nuclear medium, resulting in the \nso-called $G$-matrix.  In chapter xx you end up computing such an effective interaction, using similarity transformations as well.\nWith these codes, you are in turn in the position where you can define effective interactions for say coupled-cluster calculations\n(the topic of chapter xx) or shell-model effective interactions (topics for chapter xx and xx).\n\nOur hope is that this will enable  you to assess at a much deeper level the pros and cons of the various methods.  \nWe believe firmly that knowledge of the strengths and weaknesses of a given method allows you to realize where\nimprovements can be made.   The text has also a strong focus on computational issues, from how to build up large many-body codes \nto parallelization and high-performance computing topics.\n\n\n\nThis texts spans some four hundred pages, and with the promised wide scope we aim at, \nthere have to be topics which will not be dealt with properly.\nIn particular we will not cover  reaction theories.  \nFor reaction theories we provide all the inputs needed to compute\nonebody densities, spectroscopic factors and optical potentials. \nFor density functional theories we discuss how one can constrain the exchange correlations based on *ab initio* methods.\nFurthermore, when it comes to the underlying nuclear forces, we will assume that various baryons and mesons are the \neffective degrees of freedom, limiting ourselves to low and intermediate energy nuclear physics.  A discussion of recent \nadvances in lattice quantumchromodynamics (QCD) and its link to effective field theories is also outside the scope\nof this book, although we will refer to advances in these fields as well and link the construction of nuclear forces to\nundergoing research in effective field theory and lattice QCD.  \nThe material on infinite matter can be extended to finite temperatures, but we do not \nadventure into the realm of heavy-ion collisions and the search of the holy grail of quark-gluon plasma. \nWe will throughout pay loyalty to a physical world governed by the degrees of freedom of baryons and mesons.\nWe apologize for these shortcomings, which are mainly due to\nour lack of detailed research knowledge in the above fields. To be a jack of all trades leads normally to mastering none.\n\nA final warning however.\nThis text is not a text on many-body theories, rather it is\na text on applications and implementations of many-body theories. This applies also to many of the algoritms  we discuss.  We do not go into\ndetails about for example Gaussian quadrature or the mathematical foundations of random walks and the Metropolis algorithm.  We will often simply state results, but add \nenough references to tutorial texts so that you can look up the missing wonders of numerical mathematics yourself.\nSimilarly,  handling of angular momenta and their recouplings via $3j$, $6j$ or $9j$ symbols should  not  come as a bolt out from the blue. But again, don't despair,\nwe'll guide you safely to the appropriate literature.\n\nWe have therefore taken the liberty to have  certain expectations about you, the potential reader.  \nWe assume that you are at least a graduate student who is embarking on studies in \nnuclear physics and that\nyou have some familiarity with basic nuclear physics, angular momentum theory and many-body theory, \ntypically at the level of texts like those of Talmi, Fetter and Walecka, Blaizot and Ripka, Dickhoff and Van Neck or similar monographs (add refs later). \nWe will obviously state and repeat the basic rules and theorems, but will not go into derivations.  \nSome of the derivations will however be left to you via various exercises interspersed througout the text.\n\n\nFriends/colleagues bla bla  and sponsors bla bla. also add that errors, misunderstandings etc are mainly due to ourselves!!\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# Experimental data and definitions of the many-body problem\n<div id=\"ch:spdata\"></div>\n\n## Introduction\n\nTo understand why matter is stable, and thereby shed light on the limits of \nnuclear stability, is one of the \noverarching aims and intellectual challenges \nof basic research in nuclear physics. To relate the stability of matter\nto the underlying fundamental forces and particles of nature as manifested in nuclear matter, is central\nto present and planned rare isotope facilities. \nImportant properties of nuclear systems which can reveal information about these topics \nare for example masses, and thereby binding energies, and density distributions of nuclei.  \nThese are quantities which convey important information on \nthe shell structure of nuclei, with their \npertinent magic numbers and shell closures or the  eventual disappearence of the latter \naway from  the valley of stability.\n\nNeutron-rich nuclei are particularly interesting for the above endeavour. As a particular chain\nof isotopes becomes more and more neutron rich, one reaches finally the limit of stability, the so-called\ndripline, where one additional neutron makes the next isotopes unstable with respect \nto the previous ones. The appearence or not of magic numbers and shell structures,\nthe formation of neutron skins and halos\ncan thence be probed via investigations of quantities like  the binding energy\nor the charge radii and neutron rms radii of neutron-rich nuclei. \nThese quantities have in turn important \nconsequences for theoretical models of nuclear structure and their application in astrophysics.\nFor example, the neutron radius of $\\,{}^{208}\\mbox{Pb}$, recently extracted from the PREX \nexperiment at Jefferson Laboratory  can be used to constrain the equation of state of \nneutron matter. A related quantity to the\nneutron rms radius $r_n^{\\mathrm{rms}}=\\langle r^2\\rangle_n^{1/2}$ is the neutron skin \n$r_{\\mathrm{skin}}=r_n^{\\mathrm{rms}}-r_p^{\\mathrm{rms}}$,\nwhere $r_p^{\\mathrm{rms}}$ is the corresponding proton rms radius.  \nThere are several properties which relate the thickness of the neutron skin to quantities in nuclei and \nnuclear matter, such as the symmetry energy at the saturation point for nuclear matter, the slope\nof the equation of state for neutron matter\nor the low-energy electric dipole strength due to the pigmy dipole resonance. \nSee Ref. <http://iopscience.iop.org/1402-4896/2013/T152> for several interesting discussions of these topics. \n\n\nHaving access to precise measurements of masses, radii, and\nelectromagnetic moments for a wide range of nuclei allows to study\ntrends with varying neutron excess. A quantitative description of\nvarious experimental data with quantified uncertainty still remains a\nmajor challenge for nuclear structure theory.  Global theoretical\nstudies of isotopic chains, such as the Ca chain shown in the figure below here, make it possible to test systematic\nproperties of effective interactions between nucleons. Such calculations also\nprovide critical tests of limitations of many-body methods. As one\napproaches the particle emission thresholds, it becomes increasingly\nimportant to describe correctly the coupling to the continuum of\ndecays and scattering channels. While the\nfull treatment of antisymmetrization and short-range correlations has\nbecome routine in first principle  approaches (to be defined later) to nuclear bound states, the\nmany-body problem becomes more difficult when long-range correlations\nand continuum effects are considered.\n\n\n<p>Expected experimental information on the calcium isotopes that can be obtained at FRIB. The limits for detailed spectroscopic information are around $A\\sim 60$.</p>\n\n\n\n\n\nThe aim of this first section is to present some of the experimental data which can be used to extract \ninformation about correlations in nuclear systems. In particular, we will start with a theoretical analysis of a quantity called the separation energy for neutrons or protons. This quantity, to be discussed below, is defined as the difference between two binding energies (masses) of neighboring nuclei. As we will see from various figures below and exercises as well, the separation energies display a varying behavior as function of the number of neutrons or protons. These variations from one nucleus to another one, laid the foundation for the introduction of so-called magic numbers and a mean-field picture in order to describe nuclei theoretically.\n\n\n\nWith a mean- or average-field picture we mean that a given nucleon (either a proton or a neutron) moves in an average potential field which is set up by all other nucleons in the system. Consider for example a nucleus like $\\,{}^{17}\\mbox{O}$ with nine neutrons and eight protons. Many properties  of this nucleus can be interpreted in terms of a picture where we can view it as\none neutron on top of $\\,{}^{16}\\mbox{O}$. We infer from data and our theoretical interpretations that this additional neutron behaves almost as an individual neutron which *sees* an average interaction set up by the remaining 16 nucleons in   $\\,{}^{16}\\mbox{O}$. A nucleus like $\\,{}^{16}\\mbox{O}$ is an example of what we in this course will denote as a good closed-shell nucleus. We will come back to what this means later.\n\nSince we want to develop a theory capable of interpreting data in terms of our laws of motion and the pertinent forces,\nwe can think of this neutron as a particle which moves in a potential field. We can hence attempt at solving our equations of motion (Schroedinger's equation in our case) for this system along the same lines as we did in atomic physics when we solved Schroedinger's equation for the hydrogen atom. We just need to define a model for our effective single-particle potential. \n\nA simple potential model which enjoys quite some popularity in nuclear physics, is the three-dimensional harmonic oscillator. This potential model captures some of the physics of deeply bound single-particle states but fails in reproducing \nthe less bound single-particle states. A parametrized, and more realistic,  potential model which is widely used in nuclear physics, is the so-called Woods-Saxon potential. Both the harmonic oscillator and the Woods-Saxon potential models define computational problems that can easily be solved (see below), resulting (with the appropriate parameters) in a rather good reproduction of experiment for nuclei which can be approximated as one nucleon on top (or one nucleon removed) of a so-called closed-shell system.\n\n\n\nTo be able to interpret a nucleus in such  a way requires at least that we are capable of parametrizing the abovementioned\ninteractions in order to reproduce say the excitation spectrum of a nucleus like $\\,{}^{17}\\mbox{O}$. \n\nWith such a parametrized interaction we are able to solve Schroedinger's equation for the motion of one nucleon in a given field. A nucleus is however a true and complicated many-nucleon system, with extremely many degrees of freedom and complicated correlations, rendering the ideal solution of the many-nucleon Schroedinger equation an impossible enterprise. It is much easier to solve a single-particle problem with say a Woods-Saxon potential. Using such a potential hides however many of the complicated correlations and interactions which we see in nuclei. Such an effective single-nucleon potential is for example not capable of \ndescribing properties like the binding energy or the rms radius of a given nucleus. \n\nAn improvement to these simpler single-nucleon potentials is given by the Hartree-Fock method, where the variational principle is used to define a mean-field which the nucleons move in. There are many different classes of mean-field methods.\nAn important difference between these methods and the simpler parametrized mean-field potentials like the harmonic oscillator and the Woods-Saxon potentials, is that the resulting equations contain information about the nuclear forces present in our models for solving Schroedinger's equation. Hartree-Fock and other mean-field methods like density functional theory form core topics in later lectures.\n\n\n\nThe aim of this section is to present some of the experimental data we will confront theory with. In particular, we will focus on separation and shell-gap energies and use these to build a picture of nuclei in terms of (from a philosophical stand we would call this  a reductionist approach) a single-particle picture. The harmonic oscillator will serve as an excellent starting point in building nuclei from the bottom and up. Here we will neglect nuclear forces, these are introduced in the next section when we discuss the Hartree-Fock method. \n\nThe aim of this course is to develop our physics intuition of nuclear systems using  a theoretical approach  where we describe data in terms of \nthe motion of individual nucleons and their mutual interactions. \n\n**How our theoretical pictures and models can be used to interpret data is in essence what this course is about**. Our narrative will lead us along a path where we start with single-particle models and end with the theory of the nuclear shell-model. The latter will be used to understand and analyze excitation spectra and decay patterns of nuclei, linking our theoretical understanding with interpretations of experiment. The way we build up our theoretical descriptions and interpretations follows what we may call a standard reductionistic approach, that is we start with what we believe are our effective degrees of freedom (nucleons in our case) and interactions amongst these and solve thereafter the underlying equations of motions. This defines the nuclear many-body problem, and mean-field approaches like Hartree-Fock theory and the nuclear shell-model represent different approaches to our solutions of Schroedinger's equation. \n\n\n\nWe start our tour of experimental data and our interpretations by considering the chain of oxygen isotopes. In the exercises below you will be asked to perform similar analyses for other chains of isotopes.\n\nThe oxygen isotopes are the heaviest isotopes for which the drip line is well established.  The drip line is defined as the point where adding one more nucleon leads to an unbound nucleus. Below we will see that we can define the dripline by studying the separation energy. Where the neutron (proton) separation energy changes sign as a function of the number of neutrons (protons) defines the neutron (proton) drip line.\n\nThe oxygen isotopes are simple enough to be described by some few selected single-particle degrees of freedom.  \n\n* Two out of four stable even-even isotopes exhibit a doubly magic nature, namely $\\,{}^{22}\\mbox{O}$ ($Z=8$, $N=14$) and $\\,{}^{24}\\mbox{O}$ ($Z=8$, $N=16$).\n\n* The structure of $\\,{}^{22}\\mbox{O}$ and $\\,{}^{24}\\mbox{O}$ is assumed to be governed by the evolution of the $1s_{1/2}$ and $0d_{5/2}$  one-quasiparticle states.\n\n* The isotopes $\\,{}^{25}\\mbox{O}$, $\\,{}^{26}\\mbox{O}$, $\\,{}^{27}\\mbox{O}$ and $\\,{}^{28}\\mbox{O}$ are outside the drip line, since the $0d_{3/2}$ orbit is not bound.\n\n Many experiments worldwide!\nThese isotopes have been studied in series of recent experiments. Some of these experiments and theoretical interpretations are discussed in the following articles:\n\n* $\\,{}^{24}\\mbox{O}$ and lighter:  C. R. Hoffman *et al.*, Phys. Lett. B **672**, 17 (2009); R. Kanungo *et al*., Phys. Rev. Lett.~**102**, 152501 (2009); C. R. Hoffman *et al*., Phys. Rev. C **83**, 031303(R) (2011); Stanoiu *et al*., Phys. Rev. C **69**, 034312 (2004)\n\n* $\\,{}^{25}\\mbox{O}$: C. R. Hoffman *et al*., Phys. Rev. Lett. **102**,152501  (2009). \n\n* $\\,{}^{26}\\mbox{O}$: E. Lunderberg *et al*., Phys. Rev. Lett. **108**, 142503 (2012). \n\n* $\\,{}^{26}\\mbox{O}$: Z. Kohley  *et al*., Study of two-neutron radioactivity in the decay of 26O, Phys. Rev. Lett., **110**, 152501 (2013). \n\n* Theory: Oxygen isotopes with three-body forces,  Otsuka *et al*., Phys. Rev. Lett. **105**, 032501  (2010).  Hagen *et al.*, Phys. Rev. Lett., **108**, 242501 (2012). \n\n## Masses and Binding energies\nOur first approach in analyzing data theoretically, is to see if we can use experimental information to \n\n* Extract information about a *so-called* single-particle  behavior\n\n* And interpret such a behavior in terms of the underlying forces and microscopic physics\n\nThe next step is to see if we could use these interpretations to say something about shell closures and magic numbers. Since we focus on single-particle properties, a quantity we can extract from experiment is the separation energy for protons and neutrons. Before we proceed, we need to define quantities like masses and binding energies.   Two excellent reviews on \nrecent trends in the determination of nuclear masses can be found in <http://journals.aps.org/rmp/abstract/10.1103/RevModPhys.75.1021> and in <http://iopscience.iop.org/1402-4896/2013/T152/014017/>\n\n\nA basic quantity which can be measured for the ground states of nuclei is the atomic mass $M(N, Z)$ of the neutral atom with atomic mass number $A$ and charge $Z$. The number of neutrons is $N$.\n\nAtomic masses are usually tabulated in terms of the mass excess defined by\n\n$$\n\\Delta M(N, Z) =  M(N, Z) - uA,\n$$\n\nwhere $u$ is the Atomic Mass Unit\n\n$$\nu = M(^{12}\\mathrm{C})/12 = 931.49386 \\hspace{0.1cm} \\mathrm{MeV}/c^2.\n$$\n\nIn this course we will mainly use \ndata from the 2003 compilation of Audi, Wapstra and Thibault, see <http://www.sciencedirect.com/science/journal/03759474/729/1>.\n\n\nThe nucleon masses are\n\n$$\nm_p = 938.27203(8)\\hspace{0.1cm} \\mathrm{MeV}/c^2 = 1.00727646688(13)u,\n$$\n\nand\n\n$$\nm_n = 939.56536(8)\\hspace{0.1cm} \\mathrm{MeV}/c^2 = 1.0086649156(6)u.\n$$\n\nIn the 2003 mass evaluation there are 2127 nuclei measured with an accuracy of 0.2\nMeV or better, and 101 nuclei measured with an accuracy of greater than 0.2 MeV. For\nheavy nuclei one observes several chains of nuclei with a constant $N-Z$ value whose masses are obtained from the energy released in $\\alpha$-decay.\n\n\nThe nuclear binding energy is defined as the energy required to break up a given nucleus\ninto its constituent parts of $N$ neutrons and $Z$ protons. In terms of the atomic masses $M(N, Z)$ the binding energy is defined by\n\n$$\nBE(N, Z) = ZM_H c^2 + Nm_n c^2 - M(N, Z)c^2 ,\n$$\n\nwhere $M_H$ is the mass of the hydrogen atom and $m_n$ is the mass of the neutron.\nIn terms of the mass excess the binding energy is given by\n\n$$\nBE(N, Z) = Z\\Delta_H c^2 + N\\Delta_n c^2 -\\Delta(N, Z)c^2 ,\n$$\n\nwhere $\\Delta_H c^2 = 7.2890$ MeV and $\\Delta_n c^2 = 8.0713$ MeV.\n\n\nThe following python program reads in the experimental data on binding energies and, stored in the file bindingenergies.dat,  plots them as function of the mass number $A$. One notices clearly a saturation of the binding energy per nucleon at $A\\approx 56$.\n\n\n```\n%matplotlib inline\n\nimport numpy as np\nfrom  matplotlib import pyplot as plt\n# Load in data file\ndata = np.loadtxt(\"datafiles/bindingenergies.dat\")\n# Make arrays containing x-axis and binding energies as function of A\nx = data[:,2]\nbexpt = data[:,3]\nplt.plot(x, bexpt ,'ro')\nplt.axis([0,270,-1, 10.0])\nplt.xlabel(r'$A$')\nplt.ylabel(r'Binding energies in [MeV]')\nplt.legend(('Experiment'), loc='upper right')\nplt.title(r'Binding energies from experiment')\nplt.savefig('expbindingenergies.pdf')\nplt.savefig('expbindingenergies.png')\nplt.show()\n\n```\n\nA popular and physically intuitive model which can be used to parametrize \nthe experimental binding energies as function of $A$, is the so-called \nthe liquid drop model. The ansatz is based on the following expression\n\n$$\nBE(N,Z) = a_1A-a_2A^{2/3}-a_3\\frac{Z^2}{A^{1/3}}-a_4\\frac{(N-Z)^2}{A},\n$$\n\nwhere $A$ stands for the number of nucleons and the $a_i$s are parameters which are determined by a fit \nto the experimental data.  \n\nTo arrive at the above expression we have assumed that we can make the following assumptions:\n\n * There is a volume term $a_1A$ proportional with the number of nucleons (the energy is also an extensive quantity). When an assembly of nucleons of the same size is packed together into the smallest volume, each interior nucleon has a certain number of other nucleons in contact with it. This contribution is proportional to the volume.\n\n * There is a surface energy term $a_2A^{2/3}$. The assumption here is that a nucleon at the surface of a nucleus interacts with fewer other nucleons than one in the interior of the nucleus and hence its binding energy is less. This surface energy term takes that into account and is therefore negative and is proportional to the surface area.\n\n * There is a Coulomb energy term $a_3\\frac{Z^2}{A^{1/3}}$. The electric repulsion between each pair of protons in a nucleus yields less binding. \n\n * There is an asymmetry term $a_4\\frac{(N-Z)^2}{A}$. This term is associated with the Pauli exclusion principle and reflectd the fact that the proton-neutron interaction is more attractive on the average than the neutron-neutron and proton-proton interactions.\n\nWe could also add a so-called pairing term, which is a correction term that\narises from the tendency of proton pairs and neutron pairs to\noccur. An even number of particles is more stable than an odd number. \nPerforming a least-square fit to data, we obtain the following numerical values for the various constants\n* $a_1=15.49$ MeV\n\n* $a_2=17.23$ MeV\n\n* $a_3=0.697$ MeV\n\n* $a_4=22.6$ MeV\n\nThe python below here allows you to perform a fit of teh above parameters using nonlinear least squares curvefitting.\n\n\nThe following python program reads now in the experimental data on binding energies as well as the results from the above liquid drop model and plots these energies as function of the mass number $A$. One sees that for larger values of $A$, there is a better agreement with data.\n\n\n```\nimport numpy as np\nfrom  matplotlib import pyplot as plt\n# Load in data file\ndata = np.loadtxt(\"datafiles/bindingenergies.dat\")\n# Make arrays containing x-axis and binding energies as function of\nx = data[:,2]\nbexpt = data[:,3]\nliquiddrop = data[:,4]\nplt.plot(x, bexpt ,'b-o', x, liquiddrop, 'r-o')\nplt.axis([0,270,-1, 10.0])\nplt.xlabel(r'$A$')\nplt.ylabel(r'Binding energies in [MeV]')\nplt.legend(('Experiment','Liquid Drop'), loc='upper right')\nplt.title(r'Binding energies from experiment and liquid drop')\nplt.savefig('bindingenergies.pdf')\nplt.savefig('bindingenergies.png')\nplt.show()\n\n```\n\nThis  python program reads now in the experimental data on binding energies and performs a nonlinear least square fitting of the data. In the example here we use only the parameters $a_1$ and $a_2$, leaving it as an exercise to the reader to perform the fit for all four paramters. The results are plotted and compared with the experimental values.  To read more about non-linear least square methods, see for example the text of M.J. Box, D. Davies and W.H. Swann, Non-Linear optimisation Techniques, Oliver & Boyd, 1969.\n\n\n```\nimport numpy as np\nfrom scipy.optimize import curve_fit\nfrom  matplotlib import pyplot as plt\n# Load in data file\ndata = np.loadtxt(\"datafiles/bindingenergies.dat\")\n# Make arrays containing A on x-axis and binding energies\nA = data[:,2]\nbexpt = data[:,3]\n# The function we want to fit to, only two terms here\ndef func(A,a1, a2):\n    return a1*A-a2*(A**(2.0/3.0))\n# function to perform nonlinear least square with guess for a1 and a2\npopt, pcov = curve_fit(func, A, bexpt, p0 = (16.0, 18.0))\na1  = popt[0]\na2 = popt[1]\nliquiddrop = a1*A-a2*(A**(2.0/3.0))\n\nplt.plot(A, bexpt ,'bo', A, liquiddrop, 'ro')\nplt.axis([0,270,-1, 10.0])\nplt.xlabel(r'$A$')\nplt.ylabel(r'Binding energies in [MeV]')\nplt.legend(('Experiment','Liquid Drop'), loc='upper right')\nplt.title(r'Binding energies from experiment and liquid drop')\nplt.savefig('bindingenergies.pdf')\nplt.savefig('bindingenergies.png')\nplt.show()\n\n```\n\nWe are now interested in interpreting experimental binding energies  in terms of a single-particle picture.\nIn order to do so, we  consider first energy conservation for nuclear transformations that include, for\nexample, the fusion of two nuclei $a$ and $b$ into the combined system $c$\n\n$$\n{^{N_a+Z_a}}a+ {^{N_b+Z_b}}b\\rightarrow {^{N_c+Z_c}}c\n$$\n\nor the decay of nucleus $c$ into two other nuclei $a$ and $b$\n\n$$\n^{N_c+Z_c}c \\rightarrow  ^{N_a+Z_a}a+ ^{N_b+Z_b}b\n$$\n\nIn general we have the reactions\n\n$$\n\\sum_i {^{N_i+Z_i}}i \\rightarrow  \\sum_f {^{N_f+Z_f}}f\n$$\n\nWe require also that the number of protons and neutrons (the total number of nucleons) is conserved in the initial stage and final stage, unless we have processes which violate baryon conservation,\n\n$$\n\\sum_iN_i = \\sum_f N_f \\hspace{0.2cm}\\mathrm{and} \\hspace{0.2cm}\\sum_iZ_i = \\sum_f Z_f.\n$$\n\n## $Q$-values and separation energies\n\nThe above processes can be characterized by an energy difference called the $Q$ value, defined as\n\n$$\nQ=\\sum_i M(N_i, Z_i)c^2-\\sum_f M(N_f, Z_f)c^2=\\sum_i BE(N_f, Z_f)-\\sum_i BE(N_i, Z_i)\n$$\n\nSpontaneous decay involves a single initial nuclear state and is allowed if $Q > 0$. In the decay, energy is released in the form of the kinetic energy of the final products. Reactions involving two initial nuclei are called endothermic (a net loss of energy) if $Q < 0$. The reactions are exothermic (a net release of energy) if $Q > 0$.\n\n\nLet us study the Q values associated with the removal of one or two nucleons from\na nucleus. These are conventionally defined in terms of the one-nucleon and two-nucleon\nseparation energies. The neutron separation energy is defined as\n\n$$\nS_n= -Q_n= BE(N,Z)-BE(N-1,Z),\n$$\n\nand the proton separation energy reads\n\n$$\nS_p= -Q_p= BE(N,Z)-BE(N,Z-1).\n$$\n\nThe two-neutron separation energy is defined as\n\n$$\nS_{2n}= -Q_{2n}= BE(N,Z)-BE(N-2,Z),\n$$\n\nand  the two-proton separation energy is given by\n\n$$\nS_{2p}= -Q_{2p}= BE(N,Z)-BE(N,Z-2),\n$$\n\nUsing say the neutron separation energies (alternatively the proton separation energies)\n\n$$\nS_n= -Q_n= BE(N,Z)-BE(N-1,Z),\n$$\n\nwe can define the so-called energy gap for neutrons (or protons) as\n\n$$\n\\Delta S_n= BE(N,Z)-BE(N-1,Z)-\\left(BE(N+1,Z)-BE(N,Z)\\right),\n$$\n\nor\n\n$$\n\\Delta S_n= 2BE(N,Z)-BE(N-1,Z)-BE(N+1,Z).\n$$\n\nThis quantity can in turn be used to determine which nuclei are magic or not. \nFor protons we would have\n\n$$\n\\Delta S_p= 2BE(N,Z)-BE(N,Z-1)-BE(N,Z+1).\n$$\n\nWe leave it as an exercise to the reader to define and interpret the two-neutron or two-proton gaps. \n\n\nThe following python programs can now be used to plot the separation energies and the energy gaps for the oxygen isotopes.  The following python code reads the separation energies from file for all oxygen isotopes from $A=13$ to $A=25$, The data are taken from the file *snox.dat*.  This files contains the separation energies and the shell gap energies.\n\n\n```\n\nimport numpy as np\nfrom  matplotlib import pyplot as plt\n# Load in data file\ndata = np.loadtxt(\"datafiles/snox.dat\")\n# Make arrays containing x-axis and binding energies as function of\nx = data[:,1]\ny = data[:,2]\n\nplt.plot(x, y,'b-+',markersize=6)\nplt.axis([4,18,-1, 25.0])\nplt.xlabel(r'Number of neutrons $N$',fontsize=20)\nplt.ylabel(r'$S_n$ [MeV]',fontsize=20)\nplt.legend(('Separation energies for oxygen isotpes'), loc='upper right')\nplt.title(r'Separation energy for the oxygen isotopes')\nplt.savefig('snoxygen.pdf')\nplt.savefig('snoxygen.png')\nplt.show()\n\n```\n\nHere we display the python program for plotting the corresponding results for shell gaps for the oyxgen isotopes.\n\n\n```\n\nimport numpy as np\nfrom  matplotlib import pyplot as plt\n# Load in data file\ndata = np.loadtxt(\"datafiles/snox.dat\")\n# Make arrays containing x-axis and binding energies as function of\nx = data[:,1]\ny = data[:,3]\n\nplt.plot(x, y,'b-+',markersize=6)\nplt.axis([4,18,-7, 12.0])\nplt.xlabel(r'Number of neutrons $N$',fontsize=20)\nplt.ylabel(r'$\\Delta S_n$ [MeV]',fontsize=20)\nplt.legend(('Shell gap energies for oxygen isotpes'), loc='upper right')\nplt.title(r'Shell gap energies for the oxygen isotopes')\nplt.savefig('gapoxygen.pdf')\nplt.savefig('gapoxygen.png')\nplt.show()\n\n```\n\nSince we will focus in the beginning on single-particle degrees of freedom and mean-field approaches before we\nstart with nuclear forces and many-body approaches like the nuclear shell-model, there are some features to be noted\n\n* In the discussion of the liquid drop model and binding energies, we note that the total binding energy is not that different from the sum of the individual neutron and proton masses. \n\nOne may thus infer that intrinsic properties of nucleons in a nucleus are close to those of free nucleons.\n* In the discussion of the neutron separation energies for the oxygen isotopes, we note  a clear staggering effect between odd and even isotopes with the even ones being more bound (larger separation energies). We will later link this to strong pairing correlations in nuclei.\n\n* The neutron separation energy becomes negative at $\\,{}^{25}\\mbox{O}$, making this nucleus unstable with respect to the emission of one neutron. A nucleus like $\\,{}^{24}\\mbox{O}$ is thus the last stable oxygen isotopes which has been observed. Oyxgen-26 has been found to be unbound with respect to $\\,{}^{24}\\mbox{O}$, see <ournals.aps.org/prl/abstract/10.1103/PhysRevLett.108.142503> .\n\n* We note also that there are large shell-gaps for some nuclei, meaning that more energy is needed to remove one nucleon. These gaps are used to define so-called magic numbers. For the oxygen isotopes we see a clear gap for $\\,{}^{16}\\mbox{O}$. We will interpret this gap as one of several experimental properties that define so-called magic numbers. In our discussion below we will make a first interpretation using  single-particle states from the harmonic oscillator and the Woods-Saxon potential. \n\nIn the exercises below you will be asked to perform a similar analysis for other chains of isotopes and interpret the results. \n\n\n\n## Radii\n\nThe root-mean-square (rms) charge radius has been measured for the ground states of many\nnuclei. For a spherical charge density, $\\rho(\\boldsymbol{r})$, the mean-square radius is defined by\n\n$$\n\\langle r^2\\rangle = \\frac{ \\int  d \\boldsymbol{r} \\rho(\\boldsymbol{r}) r^2}{ \\int  d \\boldsymbol{r} \\rho(\\boldsymbol{r})},\n$$\n\nand the rms radius is the square root of this quantity denoted by\n\n$$\nR =\\sqrt{ \\langle r^2\\rangle}.\n$$\n\nRadii for most stable\nnuclei have been deduced from electron scattering form\nfactors and/or from the x-ray transition energies of muonic atoms. \nThe relative radii for a\nseries of isotopes can be extracted from the isotope shifts of atomic x-ray transitions.\nThe rms radius for the nuclear point-proton density, $R_p$ is obtained from the rms charge radius by:\n\n$$\nR_p = \\sqrt{R^2_{\\mathrm{ch}}- R^2_{\\mathrm{corr}}},\n$$\n\nwhere\n\n$$\nR^2_{\\mathrm{corr}}= R^2_{\\mathrm{op}}+(N/Z)R^2_{\\mathrm{on}}+R^2_{\\mathrm{rel}},\n$$\n\nwhere\n\n$$\nR_{\\mathrm{op}}= 0.875(7) \\mathrm{fm}.\n$$\n\nis the rms radius of the proton, $R^2_{\\mathrm{on}} = 0.116(2)$ $\\mbox{fm}^{2}$ is the\nmean-square radius of the neutron and $R^2_{\\mathrm{rel}} = 0.033$ $\\mbox{fm}^{2}$ is the relativistic Darwin-Foldy correction. There are also smaller nucleus-dependent relativistic spin-orbit and\nmesonic-exchange corrections that should be included.\n\n\n\n\n## Definitions\n\nWe will now introduce the potential models we have discussex above, namely the harmonic oscillator and the Woods-Saxon potentials.  In order to proceed, we need some definitions.\n\nWe define an operator as $\\hat{O}$ throughout. Unless otherwise specified the total number of nucleons is\nalways $A$ and $d$ is the dimension of the system.  In nuclear physics\nwe normally define the total number of particles to be $A=N+Z$, where\n$N$ is total number of neutrons and $Z$ the total number of\nprotons. In case of other baryons such as isobars $\\Delta$ or various\nhyperons such as $\\Lambda$ or $\\Sigma$, one needs to add their\ndefinitions.  When we refer to a single neutron we will use the label $n$ and when we refer to a single proton we will use the label $p$. Unless otherwise specified, we will simply call these particles for nucleons.\n\n\nThe quantum numbers of a single-particle state in coordinate space are\ndefined by the variables\n\n$$\nx=(\\boldsymbol{r},\\sigma),\n$$\n\nwhere\n\n$$\n\\boldsymbol{r}\\in {\\mathbb{R}}^{d},\n$$\n\nwith $d=1,2,3$ represents the spatial coordinates and $\\sigma$ is the eigenspin of the particle. For fermions with eigenspin $1/2$ this means that\n\n$$\nx\\in {\\mathbb{R}}^{d}\\oplus (\\frac{1}{2}),\n$$\n\nand the integral\n\n$$\n\\int dx = \\sum_{\\sigma}\\int d^dr = \\sum_{\\sigma}\\int d\\boldsymbol{r},\n$$\n\nand\n\n$$\n\\int d^Ax= \\int dx_1\\int dx_2\\dots\\int dx_A.\n$$\n\nSince we are dealing with protons and neutrons we need to add isospin as a new degree of freedom.\n\n\n\nIncluding isospin $\\tau$ we have\n\n$$\nx=(\\boldsymbol{r},\\sigma,\\tau),\n$$\n\nwhere\n\n$$\n\\boldsymbol{r}\\in {\\mathbb{R}}^{3},\n$$\n\nFor nucleons, which are fermions with eigenspin $1/2$ and isospin $1/2$ this means that\n\n$$\nx\\in {\\mathbb{R}}^{d}\\oplus (\\frac{1}{2})\\oplus (\\frac{1}{2}),\n$$\n\nand the integral\n\n$$\n\\int dx = \\sum_{\\sigma\\tau}\\int d\\boldsymbol{r},\n$$\n\nand\n\n$$\n\\int d^Ax= \\int dx_1\\int dx_2\\dots\\int dx_A.\n$$\n\nWe will use the standard nuclear physics definition of isospin, resulting in $\\tau_z=-1/2$ for protons and $\\tau_z=1/2$ for neutrons.\n\n\n\nThe quantum mechanical wave function of a given state with quantum numbers $\\lambda$ (encompassing all quantum numbers needed to specify the system), ignoring time, is\n\n$$\n\\Psi_{\\lambda}=\\Psi_{\\lambda}(x_1,x_2,\\dots,x_A),\n$$\n\nwith $x_i=(\\boldsymbol{r}_i,\\sigma_i,\\tau_i)$ and the projections of $\\sigma_i$ and $\\tau_i$ take the values\n$\\{-1/2,+1/2\\}$. \nWe will hereafter always refer to $\\Psi_{\\lambda}$ as the exact wave function, and if the ground state is not degenerate we label it as\n\n$$\n\\Psi_0=\\Psi_0(x_1,x_2,\\dots,x_A).\n$$\n\nSince the solution $\\Psi_{\\lambda}$ seldomly can be found in closed form, approximations are sought. In this text we define an approximative wave function or an ansatz to the exact wave function as\n\n$$\n\\Phi_{\\lambda}=\\Phi_{\\lambda}(x_1,x_2,\\dots,x_A),\n$$\n\nwith\n\n$$\n\\Phi_{0}=\\Phi_{0}(x_{1},x_{2},\\dots,x_{A}),\n$$\n\nbeing the ansatz for the ground state.  \n\n\nThe wave function $\\Psi_{\\lambda}$ is sought in the Hilbert space of either symmetric or anti-symmetric $N$-body functions, namely\n\n$$\n\\Psi_{\\lambda}\\in {\\cal H}_A:= {\\cal H}_1\\oplus{\\cal H}_1\\oplus\\dots\\oplus{\\cal H}_1,\n$$\n\nwhere the single-particle Hilbert space $\\hat{H}_1$ is the space of square integrable functions over $\\in {\\mathbb{R}}^{d}\\oplus (\\sigma)\\oplus (\\tau)$ resulting in\n\n$$\n{\\cal H}_1:= L^2(\\mathbb{R}^{d}\\oplus (\\sigma)\\oplus (\\tau)).\n$$\n\nOur Hamiltonian is invariant under the permutation (interchange) of two particles.\nSince we deal with fermions however, the total wave function is antisymmetric.\nLet $\\hat{P}$ be an operator which interchanges two particles.\nDue to the symmetries we have ascribed to our Hamiltonian, this operator commutes with the total Hamiltonian,\n\n$$\n[\\hat{H},\\hat{P}] = 0,\n$$\n\nmeaning that $\\Psi_{\\lambda}(x_1, x_2, \\dots , x_A)$ is an eigenfunction of \n$\\hat{P}$ as well, that is\n\n$$\n\\hat{P}_{ij}\\Psi_{\\lambda}(x_1, x_2, \\dots,x_i,\\dots,x_j,\\dots,x_A)=\n\\beta\\Psi_{\\lambda}(x_1, x_2, \\dots,x_j,\\dots,x_i,\\dots,x_A),\n$$\n\nwhere $\\beta$ is the eigenvalue of $\\hat{P}$. We have introduced the suffix $ij$ in order to indicate that we permute particles $i$ and $j$.\nThe Pauli principle tells us that the total wave function for a system of fermions\nhas to be antisymmetric, resulting in the eigenvalue $\\beta = -1$.   \n\n\n\nThe Schrodinger equation reads\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:basicSE1\"></div>\n\n$$\n\\begin{equation}\n\\hat{H}(x_1, x_2, \\dots , x_A) \\Psi_{\\lambda}(x_1, x_2, \\dots , x_A) = \nE_\\lambda  \\Psi_\\lambda(x_1, x_2, \\dots , x_A), \\label{eq:basicSE1} \\tag{1}\n\\end{equation}\n$$\n\nwhere the vector $x_i$ represents the coordinates (spatial, spin and isospin) of particle $i$, $\\lambda$ stands  for all the quantum\nnumbers needed to classify a given $A$-particle state and $\\Psi_{\\lambda}$ is the pertaining eigenfunction.  Throughout this course,\n$\\Psi$ refers to the exact eigenfunction, unless otherwise stated.\n\n\nWe write the Hamilton operator, or Hamiltonian,  in a generic way\n\n$$\n\\hat{H} = \\hat{T} + \\hat{V}\n$$\n\nwhere $\\hat{T}$  represents the kinetic energy of the system\n\n$$\n\\hat{T} = \\sum_{i=1}^A \\frac{\\mathbf{p}_i^2}{2m_i} = \\sum_{i=1}^A \\left( -\\frac{\\hbar^2}{2m_i} \\mathbf{\\nabla_i}^2 \\right) =\n\t\t\\sum_{i=1}^A t(x_i)\n$$\n\nwhile the operator $\\hat{V}$ for the potential energy is given by\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:firstv\"></div>\n\n$$\n\\begin{equation}\n\t\\hat{V} = \\sum_{i=1}^A \\hat{u}_{\\mathrm{ext}}(x_i) + \\sum_{ji=1}^A v(x_i,x_j)+\\sum_{ijk=1}^Av(x_i,x_j,x_k)+\\dots\n\\label{eq:firstv} \\tag{2}\n\\end{equation}\n$$\n\nHereafter we use natural units, viz. $\\hbar=c=e=1$, with $e$ the elementary charge and $c$ the speed of light. This means that momenta and masses\nhave dimension energy. \n\n\nThe potential energy part includes also an external potential $\\hat{u}_{\\mathrm{ext}}(x_i)$.\n\nIn a non-relativistic approach to atomic  physics, this external potential is given by the attraction an electron feels from the atomic nucleus. The latter being much heavier than the involved electrons, is often used to define a natural center of mass. In nuclear physics there is no such external potential. It is the nuclear force which results in binding in nuclear systems. In a non-relativistic framework, the nuclear force contains two-body, three-body and more complicated degrees of freedom. The potential energy reads then\n\n$$\n\\hat{V} = \\sum_{ij}^A v(x_i,x_j)+\\sum_{ijk}^Av(x_i,x_j,x_k)+\\dots\n$$\n\nThree-body and more  complicated forces arise since we are dealing with protons and neutrons as effective degrees of freedom. We will come back to this topic later. Furthermore, in large parts of these lectures we will assume that the potential energy can be approximated by a two-body interaction only. Our Hamiltonian reads then\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:firstH\"></div>\n\n$$\n\\begin{equation}\n\t\\hat{H} = \\sum_{i=1}^A \\frac{\\mathbf{p}_i^2}{2m_i}+\\sum_{ij}^A v(x_i,x_j).\n\\label{eq:firstH} \\tag{3}\n\\end{equation}\n$$\n\n## A modified Hamiltonian\n\nIt is however, from a computational point of view, convenient to introduce an external potential $\\hat{u}_{\\mathrm{ext}}(x_i)$ by adding and substracting it to the original Hamiltonian. \nThis means that our Hamiltonian can be rewritten as\n\n$$\n\\hat{H} = \\hat{H}_0 + \\hat{H}_I \n    = \\sum_{i=1}^A \\hat{h}_0(x_i) + \\sum_{i < j=1}^A \\hat{v}(x_{ij})-\\sum_{i=1}^A\\hat{u}_{\\mathrm{ext}}(x_i),\n$$\n\nwith\n\n$$\n\\hat{H}_0=\\sum_{i=1}^A \\hat{h}_0(x_i) =  \\sum_{i=1}^A\\left(\\hat{t}(x_i) + \\hat{u}_{\\mathrm{ext}}(x_i)\\right).\n$$\n\nThe interaction (or potential energy term) reads now\n\n$$\n\\hat{H}_I=  \\sum_{i < j=1}^A \\hat{v}(x_{ij})-\\sum_{i=1}^A\\hat{u}_{\\mathrm{ext}}(x_i).\n$$\n\nIn nuclear physics the one-body part $u_{\\mathrm{ext}}(x_i)$ is often approximated by a harmonic oscillator potential or a\nWoods-Saxon potential. However, this is not fully correct, because as we have discussed, nuclei are self-bound systems and there is no external confining potential. As we will see later, *the $\\hat{H}_0$ part of the hamiltonian cannot be used to compute the binding energy of a nucleus since it is not based on a model for the nuclear forces*. That is, the binding energy is not the sum of the individual single-particle energies. \n\n\nWhy do we introduce the  Hamiltonian  in the form\n\n$$\n\\hat{H} = \\hat{H}_0 + \\hat{H}_I?\n$$\n\nThere are many reasons for this. Let us look at some of them, using the harmonic oscillator in three dimensions as our starting point. For the harmonic oscillator we know that\n\n$$\n\\hat{h}_0(x_i)\\psi_{\\alpha}(x_i)=\\varepsilon_{\\alpha}\\psi_{\\alpha}(x_i),\n$$\n\nwhere the eigenvalues are $\\varepsilon_{\\alpha}$ and the eigenfunctions are $\\psi_{\\alpha}(x_i)$. The subscript $\\alpha$ represents quantum numbers like the orbital angular momentum $l_{\\alpha}$, its projection $m_{l_{\\alpha}}$ and the   \nprincipal quantum number $n_{\\alpha}=0,1,2,\\dots$. \n\nThe eigenvalues are\n\n$$\n\\varepsilon_{\\alpha} = \\hbar\\omega \\left(2n_{\\alpha}+l_{\\alpha}+\\frac{3}{2}\\right).\n$$\n\nThe following mathematical properties of the  harmonic oscillator are handy. \n * First of all we have a complete basis of orthogonal eigenvectors. These have well-know expressions and can be easily be encoded. \n\n * With a complete basis $\\psi_{\\alpha}(x_i)$, we can construct a new basis $\\phi_{\\tau}(x_i)$ by expanding in terms of a harmonic oscillator basis, that is\n\n$$\n\\phi_{\\tau}(x_i)=\\sum_{\\alpha} C_{\\tau\\alpha}\\psi_{\\alpha}(x_i),\n$$\n\nwhere $C_{\\tau\\alpha}$ represents the overlap between the two basis sets. \n * As we will see later, the harmonic oscillator basis allows us to compute in an expedient way matrix elements of the interactions between two nucleons.  Using the above expansion we can in turn represent nuclear forces in terms of new basis, for example the  Woods-Saxon basis  to be discussed later here.\n\nThe harmonic oscillator (a shifted one by a negative constant) provides also a very good approximation to most bound single-particle states. Furthermore, it serves as a starting point in building up our picture of nuclei, in particular how we define magic numbers and systems with one nucleon added to (or removed from) a closed-shell core nucleus. The figure here shows \nthe various harmonic oscillator states, with those obtained with a Woods-Saxon potential as well, including a spin-orbit splitting (to be discussed below).\n\n<p>Single-particle spectrum and quantum numbers for a harmonic oscillator potential and a Woods-Saxon potential with and without a spin-orbit force.</p>\n\n\n\n\n\n\n\n\n\n\nIn nuclear physics the one-body part $u_{\\mathrm{ext}}(x_i)$ is often \napproximated by a harmonic oscillator potential. However,  as we also noted with the Woods-Saxon potential there is no \nexternal confining potential in nuclei. \n\nWhat many people do then, is to add and subtract a harmonic oscillator potential,\nwith\n\n$$\n\\hat{u}_{\\mathrm{ext}}(x_i)=\\hat{u}_{\\mathrm{ho}}(x_i)= \\frac{1}{2}m\\omega^2 r_i^2,\n$$\n\nwhere $\\omega$ is the oscillator frequency. This leads to\n\n$$\n\\hat{H} = \\hat{H_0} + \\hat{H_I} \n    = \\sum_{i=1}^A \\hat{h}_0(x_i) + \\sum_{i < j=1}^A \\hat{v}(x_{ij})-\\sum_{i=1}^A\\hat{u}_{\\mathrm{ho}}(x_i),\n$$\n\nwith\n\n$$\nH_0=\\sum_{i=1}^A \\hat{h}_0(x_i) =  \\sum_{i=1}^A\\left(\\hat{t}(x_i) + \\hat{u}_{\\mathrm{ho}}(x_i)\\right).\n$$\n\nMany practitioners use this as the standard Hamiltonian when doing nuclear structure calculations. \nThis is ok if the number of nucleons is large, but still with this Hamiltonian, we do not obey translational invariance.  How can we cure this?\n\n\n In setting up a translationally invariant Hamiltonian  \n the following expressions are helpful.\n The center-of-mass (CoM)  momentum is\n\n$$\nP=\\sum_{i=1}^A\\boldsymbol{p}_i,\n$$\n\nand we have that\n\n$$\n\\sum_{i=1}^A\\boldsymbol{p}_i^2 =\n \\frac{1}{A}\\left[\\boldsymbol{P}^2+\\sum_{i < j}(\\boldsymbol{p}_i-\\boldsymbol{p}_j)^2\\right]\n$$\n\nmeaning that\n\n$$\n\\left[\\sum_{i=1}^A\\frac{\\boldsymbol{p}_i^2}{2m} -\\frac{\\boldsymbol{P}^2}{2mA}\\right]\n =\\frac{1}{2mA}\\sum_{i < j}(\\boldsymbol{p}_i-\\boldsymbol{p}_j)^2.\n$$\n\nIn a similar fashion we can define the CoM coordinate\n\n$$\n\\boldsymbol{R}=\\frac{1}{A}\\sum_{i=1}^{A}\\boldsymbol{r}_i,\n$$\n\nwhich yields\n\n$$\n\\sum_{i=1}^A\\boldsymbol{r}_i^2 =\n \\frac{1}{A}\\left[A^2\\boldsymbol{R}^2+\\sum_{i < j}(\\boldsymbol{r}_i-\\boldsymbol{r}_j)^2\\right].\n$$\n\nIf we then introduce the harmonic oscillator one-body Hamiltonian\n\n$$\nH_0= \\sum_{i=1}^A\\left(\\frac{\\boldsymbol{p}_i^2}{2m}+\n\t   \\frac{1}{2}m\\omega^2\\boldsymbol{r}_i^2\\right),\n$$\n\nwith $\\omega$ the oscillator frequency,\n we can rewrite the latter as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:obho\"></div>\n\n$$\nH_{\\mathrm{HO}}= \\frac{\\boldsymbol{P}^2}{2mA}+\\frac{mA\\omega^2\\boldsymbol{R}^2}{2}\n\t    +\\frac{1}{2mA}\\sum_{i < j}(\\boldsymbol{p}_i-\\boldsymbol{p}_j)^2\n\t    +\\frac{m\\omega^2}{2A}\\sum_{i < j}(\\boldsymbol{r}_i-\\boldsymbol{r}_j)^2.\n     \\label{eq:obho} \\tag{4}\n$$\n\nAlternatively, we could write it as\n\n$$\nH_{\\mathrm{HO}}= H_{\\mathrm{CoM}}+\\frac{1}{2mA}\\sum_{i < j}(\\boldsymbol{p}_i-\\boldsymbol{p}_j)^2\n\t    +\\frac{m\\omega^2}{2A}\\sum_{i < j}(\\boldsymbol{r}_i-\\boldsymbol{r}_j)^2,\n$$\n\nThe center-of-mass term is defined as\n\n$$\nH_{\\mathrm{CoM}}= \\frac{\\boldsymbol{P}^2}{2mA}+\\frac{mA\\omega^2\\boldsymbol{R}^2}{2}.\n$$\n\nThe translationally invariant one- and two-body  Hamiltonian reads for an A-nucleon system,\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:ham\"></div>\n\n$$\n\\label{eq:ham} \\tag{5}\n\\hat{H}=\\left[\\sum_{i=1}^A\\frac{\\boldsymbol{p}_i^2}{2m} -\\frac{\\boldsymbol{P}^2}{2mA}\\right] +\\sum_{i < j}^A V_{ij} \\; ,\n$$\n\nwhere $V_{ij}$ is the nucleon-nucleon interaction. Adding zero as here\n\n$$\n\\sum_{i=1}^A\\frac{1}{2}m\\omega^2\\boldsymbol{r}_i^2-\n \\frac{m\\omega^2}{2A}\\left[\\boldsymbol{R}^2+\\sum_{i < j}(\\boldsymbol{r}_i-\\boldsymbol{r}_j)^2\\right]=0.\n$$\n\nwe can then rewrite the Hamiltonian as\n\n$$\n\\hat{H}=\\sum_{i=1}^A \\left[ \\frac{\\boldsymbol{p}_i^2}{2m}\n +\\frac{1}{2}m\\omega^2 \\boldsymbol{r}^2_i\n \\right] + \\sum_{i < j}^A \\left[ V_{ij}-\\frac{m\\omega^2}{2A}\n (\\boldsymbol{r}_i-\\boldsymbol{r}_j)^2\n \\right]-H_{\\mathrm{CoM}}.\n$$\n\nThe Woods-Saxon potential is a mean field potential for the nucleons (protons and neutrons) \ninside an atomic nucleus. It represent an average potential that a given nucleon feels from  the forces applied on each nucleon. \nThe parametrization is\n\n$$\n\\hat{u}_{\\mathrm{ext}}(r)=-\\frac{V_0}{1+\\exp{(r-R)/a}},\n$$\n\nwith $V_0\\approx 50$ MeV representing the potential well depth, $a\\approx 0.5$ fm \nlength representing the \"surface thickness\" of the nucleus and $R=r_0A^{1/3}$, with $r_0=1.25$ fm and $A$ the number of nucleons.\nThe value for $r_0$ can be extracted from a fit to data, see for example M. Kirson, <http://www.sciencedirect.com/science/article/pii/S037594740600769X>.\n\nThe following python code produces a plot of the Woods-Saxon potential with the above parameters.\n\n\n```\nimport numpy as np\nfrom  matplotlib import pyplot as plt\nfrom matplotlib import rc, rcParams\nimport matplotlib.units as units\nimport matplotlib.ticker as ticker\nrc('text',usetex=True)\nrc('font',**{'family':'serif','serif':['Woods-Saxon potential']})\nfont = {'family' : 'serif',\n        'color'  : 'darkred',\n        'weight' : 'normal',\n        'size'   : 16,\n        }\nv0 = 50\nA = 100\na = 0.5\nr0 = 1.25\nR = r0*A**(0.3333)\nx = np.linspace(0.0, 10.0)\ny = -v0/(1+np.exp((x-R)/a))\n\nplt.plot(x, y, 'b-')\nplt.title(r'{\\bf Woods-Saxon potential}', fontsize=20)     \nplt.text(3, -40, r'Parameters: $A=20$, $V_0=50$ [MeV]', fontdict=font)\nplt.text(3, -44, r'$a=0.5$ [fm], $r_0=1.25$ [fm]', fontdict=font)\nplt.xlabel(r'$r$ [fm]',fontsize=20)\nplt.ylabel(r'$V(r)$ [MeV]',fontsize=20)\n\n# Tweak spacing to prevent clipping of ylabel\nplt.subplots_adjust(left=0.15)\nplt.savefig('woodsaxon.pdf', format='pdf')\n\n```\n\nFrom the plot we notice that the potential\n* rapidly approaches zero as $r$ goes to infinity, reflecting the short-distance nature of the strong nuclear force.\n\n* For large $A$, it is approximately flat in the center.\n\n* Nucleons near the surface of the nucleus experience a large force towards the center.\n\nWe have introduced a single-particle Hamiltonian\n\n$$\nH_0=\\sum_{i=1}^A \\hat{h}_0(x_i) =  \\sum_{i=1}^A\\left(\\hat{t}(x_i) + \\hat{u}_{\\mathrm{ext}}(x_i)\\right),\n$$\n\nwith an external and central symmetric potential $u_{\\mathrm{ext}}(x_i)$, which is often \napproximated by a harmonic oscillator potential or a Woods-Saxon potential. Being central symmetric leads to a degeneracy \nin energy which is not observed experimentally. We see this from for example our discussion of separation energies and magic numbers. There are, in addition to the assumed magic numbers from a harmonic oscillator basis of $2,8,20,40,70\\dots$ magic numbers like $28$, $50$, $82$ and $126$. \n\nTo produce these additional numbers, we need to add a phenomenological spin-orbit force which lifts the degeneracy, that is\n\n$$\n\\hat{h}(x_i) =  \\hat{t}(x_i) + \\hat{u}_{\\mathrm{ext}}(x_i) +\\xi(\\boldsymbol{r})\\boldsymbol{ls}=\\hat{h}_0(x_i)+\\xi(\\boldsymbol{r})\\boldsymbol{ls}.\n$$\n\nWe have introduced a modified single-particle Hamiltonian\n\n$$\n\\hat{h}(x_i) =  \\hat{t}(x_i) + \\hat{u}_{\\mathrm{ext}}(x_i) +\\xi(\\boldsymbol{r})\\boldsymbol{ls}=\\hat{h}_0(x_i)+\\xi(\\boldsymbol{r})\\boldsymbol{ls}.\n$$\n\nWe can calculate the expectation value of the latter using the fact that\n\n$$\n\\xi(\\boldsymbol{r})\\boldsymbol{ls}=\\frac{1}{2}\\xi(\\boldsymbol{r})\\left(\\boldsymbol{j}^2-\\boldsymbol{l}^2-\\boldsymbol{s}^2\\right).\n$$\n\nFor a single-particle state with quantum numbers $nlj$ (we suppress $s$ and $m_j$), with $s=1/2$, we obtain the single-particle energies\n\n$$\n\\varepsilon_{nlj} = \\varepsilon_{nlj}^{(0)}+\\Delta\\varepsilon_{nlj},\n$$\n\nwith $\\varepsilon_{nlj}^{(0)}$ being the single-particle energy obtained with $\\hat{h}_0(x)$ and\n\n$$\n\\Delta\\varepsilon_{nlj}=\\frac{C}{2}\\left(j(j+1)-l(l+1)-\\frac{3}{4}\\right).\n$$\n\nThe spin-orbit force gives thus an additional contribution to the energy\n\n$$\n\\Delta\\varepsilon_{nlj}=\\frac{C}{2}\\left(j(j+1)-l(l+1)-\\frac{3}{4}\\right),\n$$\n\nwhich lifts the degeneracy we have seen before in the harmonic oscillator or Woods-Saxon potentials. The value $C$ is the radial\nintegral involving $\\xi(\\boldsymbol{r})$. Depending on the value of $j=l\\pm 1/2$, we obtain\n\n$$\n\\Delta\\varepsilon_{nlj=l-1/2}=\\frac{C}{2}l,\n$$\n\nor\n\n$$\n\\Delta\\varepsilon_{nlj=l+1/2}=-\\frac{C}{2}(l+1),\n$$\n\nclearly lifting the degeneracy. Note well that till now we have simply postulated the spin-orbit force in *ad hoc* way.\nLater, we will see how this term arises from the two-nucleon force in a natural way. \n\n\nWith the spin-orbit force, we can modify our Woods-Saxon potential to\n\n$$\n\\hat{u}_{\\mathrm{ext}}(r)=-\\frac{V_0}{1+\\exp{(r-R)/a}}+V_{so}(r)\\boldsymbol{ls},\n$$\n\nwith\n\n$$\nV_{so}(r) = V_{so}\\frac{1}{r}\\frac{d f_{so}(r)}{dr},\n$$\n\nwhere we have\n\n$$\nf_{so}(r) = \\frac{1}{1+\\exp{(r-R_{so})/a_{so}}}.\n$$\n\nWe can also add, in case of proton, a Coulomb potential. The Woods-Saxon potential has been widely used in parametrizations of\neffective single-particle potentials. **However, as was the case with the harmonic oscillator, none of these potentials are linked directly to the nuclear forces**. Our next step is to build a mean field based on the nucleon-nucleon interaction.\nThis will lead us to our first and simplest many-body theory, Hartree-Fock theory.  \n\n\nThe Woods-Saxon potential does allow for closed-form or analytical solutions of the eigenvalue problem\n\n$$\n\\hat{h}_0(x_i)\\psi_{\\alpha}(x_i)=\\varepsilon_{\\alpha}\\psi_{\\alpha}(x_i).\n$$\n\nFor the harmonic oscillator in three dimensions we have closed-form expressions for the energies and analytical solutions for the eigenstates,\nwith the latter given by either Hermite polynomials (cartesian coordinates) or Laguerre polynomials (spherical coordinates).\n\nTo solve the above equation is however rather straightforward numerically. \n\n\n\n## Numerical solution of the single-particle Schroedinger equation\n\nWe will illustrate the numerical solution of Schroedinger's equation by solving it for the harmonic oscillator in three dimensions.\nIt is straightforward to change the harmonic oscillator potential with a Woods-Saxon potential, or any other type of potentials. \n\nWe are interested in the solution of the radial part of Schroedinger's equation for one nucleon. \nThe angular momentum part  is given by the so-called Spherical harmonics. \n\nThe radial equation reads\n\n$$\n-\\frac{\\hbar^2}{2 m} \\left ( \\frac{1}{r^2} \\frac{d}{dr} r^2\n  \\frac{d}{dr} - \\frac{l (l + 1)}{r^2} \\right )R(r) \n     + V(r) R(r) = E R(r).\n$$\n\nIn our case $V(r)$ is the harmonic oscillator potential $(1/2)kr^2$ with\n$k=m\\omega^2$ and $E$ is\nthe energy of the harmonic oscillator in three dimensions.\nThe oscillator frequency is $\\omega$ and the energies are\n\n$$\nE_{nl}=  \\hbar \\omega \\left(2n+l+\\frac{3}{2}\\right),\n$$\n\nwith $n=0,1,2,\\dots$ and $l=0,1,2,\\dots$.\n\n\n\nSince we have made a transformation to spherical coordinates it means that \n$r\\in [0,\\infty)$.  \nThe quantum number\n$l$ is the orbital momentum of the nucleon.   Then we substitute $R(r) = (1/r) u(r)$ and obtain\n\n$$\n-\\frac{\\hbar^2}{2 m} \\frac{d^2}{dr^2} u(r) \n       + \\left ( V(r) + \\frac{l (l + 1)}{r^2}\\frac{\\hbar^2}{2 m}\n                                    \\right ) u(r)  = E u(r) .\n$$\n\nThe boundary conditions are $u(0)=0$ and $u(\\infty)=0$.\n\n\n\n\nWe introduce a dimensionless variable $\\rho = (1/\\alpha) r$\nwhere $\\alpha$ is a constant with dimension length and get\n\n$$\n-\\frac{\\hbar^2}{2 m \\alpha^2} \\frac{d^2}{d\\rho^2} u(\\rho) \n       + \\left ( V(\\rho) + \\frac{l (l + 1)}{\\rho^2}\n         \\frac{\\hbar^2}{2 m\\alpha^2} \\right ) u(\\rho)  = E u(\\rho) .\n$$\n\nLet us specialize to $l=0$. \nInserting $V(\\rho) = (1/2) k \\alpha^2\\rho^2$ we end up with\n\n$$\n-\\frac{\\hbar^2}{2 m \\alpha^2} \\frac{d^2}{d\\rho^2} u(\\rho) \n       + \\frac{k}{2} \\alpha^2\\rho^2u(\\rho)  = E u(\\rho) .\n$$\n\nWe multiply thereafter with $2m\\alpha^2/\\hbar^2$ on both sides and obtain\n\n$$\n-\\frac{d^2}{d\\rho^2} u(\\rho) \n       + \\frac{mk}{\\hbar^2} \\alpha^4\\rho^2u(\\rho)  = \\frac{2m\\alpha^2}{\\hbar^2}E u(\\rho) .\n$$\n\nWe have thus\n\n$$\n-\\frac{d^2}{d\\rho^2} u(\\rho) \n       + \\frac{mk}{\\hbar^2} \\alpha^4\\rho^2u(\\rho)  = \\frac{2m\\alpha^2}{\\hbar^2}E u(\\rho) .\n$$\n\nThe constant $\\alpha$ can now be fixed\nso that\n\n$$\n\\frac{mk}{\\hbar^2} \\alpha^4 = 1,\n$$\n\nor\n\n$$\n\\alpha = \\left(\\frac{\\hbar^2}{mk}\\right)^{1/4}.\n$$\n\nDefining\n\n$$\n\\lambda = \\frac{2m\\alpha^2}{\\hbar^2}E,\n$$\n\nwe can rewrite Schroedinger's equation as\n\n$$\n-\\frac{d^2}{d\\rho^2} u(\\rho) + \\rho^2u(\\rho)  = \\lambda u(\\rho) .\n$$\n\nThis is the first equation to solve numerically. In three dimensions \nthe eigenvalues for $l=0$ are \n$\\lambda_0=3,\\lambda_1=7,\\lambda_2=11,\\dots .$\n\n\nWe use the standard\nexpression for the second derivative of a function $u$\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:diffoperation\"></div>\n\n$$\n\\begin{equation}\n    u''=\\frac{u(\\rho+h) -2u(\\rho) +u(\\rho-h)}{h^2} +O(h^2),\n    \\label{eq:diffoperation} \\tag{6}\n\\end{equation}\n$$\n\nwhere $h$ is our step.\nNext we define minimum and maximum values for the variable $\\rho$,\n$\\rho_{\\mathrm{min}}=0$  and $\\rho_{\\mathrm{max}}$, respectively.\nYou need to check your results for the energies against different values\n$\\rho_{\\mathrm{max}}$, since we cannot set\n$\\rho_{\\mathrm{max}}=\\infty$. \n\n\nWith a given number of steps, $n_{\\mathrm{step}}$, we then \ndefine the step $h$ as\n\n$$\nh=\\frac{\\rho_{\\mathrm{max}}-\\rho_{\\mathrm{min}} }{n_{\\mathrm{step}}}.\n$$\n\nDefine an arbitrary value of $\\rho$ as\n\n$$\n\\rho_i= \\rho_{\\mathrm{min}} + ih \\hspace{1cm} i=0,1,2,\\dots , n_{\\mathrm{step}}\n$$\n\nwe can rewrite the Schroedinger equation for $\\rho_i$ as\n\n$$\n-\\frac{u(\\rho_i+h) -2u(\\rho_i) +u(\\rho_i-h)}{h^2}+\\rho_i^2u(\\rho_i)  = \\lambda u(\\rho_i),\n$$\n\nor in  a more compact way\n\n$$\n-\\frac{u_{i+1} -2u_i +u_{i-1}}{h^2}+\\rho_i^2u_i=-\\frac{u_{i+1} -2u_i +u_{i-1} }{h^2}+V_iu_i  = \\lambda u_i,\n$$\n\nwhere $V_i=\\rho_i^2$ is the harmonic oscillator potential.\n\n\nDefine first the diagonal matrix element\n\n$$\nd_i=\\frac{2}{h^2}+V_i,\n$$\n\nand the non-diagonal matrix element\n\n$$\ne_i=-\\frac{1}{h^2}.\n$$\n\nIn this case the non-diagonal matrix elements are given by a mere constant. *All non-diagonal matrix elements are equal*.\n\nWith these definitions the Schroedinger equation takes the following form\n\n$$\nd_iu_i+e_{i-1}u_{i-1}+e_{i+1}u_{i+1}  = \\lambda u_i,\n$$\n\nwhere $u_i$ is unknown. We can write the \nlatter equation as a matrix eigenvalue problem\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:sematrix\"></div>\n\n$$\n\\begin{equation}\n    \\left( \\begin{array}{ccccccc} d_1 & e_1 & 0   & 0    & \\dots  &0     & 0 \\\\\n                                e_1 & d_2 & e_2 & 0    & \\dots  &0     &0 \\\\\n                                0   & e_2 & d_3 & e_3  &0       &\\dots & 0\\\\\n                                \\dots  & \\dots & \\dots & \\dots  &\\dots      &\\dots & \\dots\\\\\n                                0   & \\dots & \\dots & \\dots  &\\dots       &d_{n_{\\mathrm{step}}-2} & e_{n_{\\mathrm{step}}-1}\\\\\n                                0   & \\dots & \\dots & \\dots  &\\dots       &e_{n_{\\mathrm{step}}-1} & d_{n_{\\mathrm{step}}-1}\n\n             \\end{array} \\right)      \\left( \\begin{array}{c} u_{1} \\\\\n                                                              u_{2} \\\\\n                                                              \\dots\\\\ \\dots\\\\ \\dots\\\\\n                                                              u_{n_{\\mathrm{step}}-1}\n             \\end{array} \\right)=\\lambda \\left( \\begin{array}{c} u_{1} \\\\\n                                                              u_{2} \\\\\n                                                              \\dots\\\\ \\dots\\\\ \\dots\\\\\n                                                              u_{n_{\\mathrm{step}}-1}\n             \\end{array} \\right) \n      \\label{eq:sematrix} \\tag{7}\n\\end{equation}\n$$\n\nor if we wish to be more detailed, we can write the tridiagonal matrix as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:matrixse\"></div>\n\n$$\n\\begin{equation}\n    \\left( \\begin{array}{ccccccc} \\frac{2}{h^2}+V_1 & -\\frac{1}{h^2} & 0   & 0    & \\dots  &0     & 0 \\\\\n                                -\\frac{1}{h^2} & \\frac{2}{h^2}+V_2 & -\\frac{1}{h^2} & 0    & \\dots  &0     &0 \\\\\n                                0   & -\\frac{1}{h^2} & \\frac{2}{h^2}+V_3 & -\\frac{1}{h^2}  &0       &\\dots & 0\\\\\n                                \\dots  & \\dots & \\dots & \\dots  &\\dots      &\\dots & \\dots\\\\\n                                0   & \\dots & \\dots & \\dots  &\\dots       &\\frac{2}{h^2}+V_{n_{\\mathrm{step}}-2} & -\\frac{1}{h^2}\\\\\n                                0   & \\dots & \\dots & \\dots  &\\dots       &-\\frac{1}{h^2} & \\frac{2}{h^2}+V_{n_{\\mathrm{step}}-1}\n\n             \\end{array} \\right)  \n\\label{eq:matrixse} \\tag{8} \n\\end{equation}\n$$\n\nRecall that the solutions are known via the boundary conditions at\n$i=n_{\\mathrm{step}}$ and at the other end point, that is for  $\\rho_0$.\nThe solution is zero in both cases.\n\n\n\nThe following python program is an example of how one can obtain the eigenvalues for a single-nucleon moving in a harmonic oscillator potential. It is rather easy to change the onebody-potential with ones like a Woods-Saxon potential. \n\n\n* The c++ and Fortran versions of this program can be found at <https://github.com/NuclearStructure/PHY981/tree/master/doc/pub/spdata/programs>. \n\n* The c++  program uses the c++ library armadillo, see <http://arma.sourceforge.net/>. \n\n* To install armadillo see the guidelines at <http://www.uio.no/studier/emner/matnat/fys/FYS4411/v14/guides/installing-armadillo/>. \n\n* For mac users I recommend using *brew*, see <http://brew.sh/>.\n\n* If you use ipython notebook, you can run c++ programs following the instructions at <http://nbviewer.ipython.org/github/dragly/cppmagic/blob/master/example.ipynb>\n\nThe code sets up the Hamiltonian matrix by defining the the minimun and maximum values of $r$ with a\nmaximum value of integration points.  These are set in the initialization function. It plots the \neigenfunctions of the three lowest eigenstates.\n\n\n```\n#Program which solves the one-particle Schrodinger equation \n#for a potential specified in function\n#potential(). This example is for the harmonic oscillator in 3d\n\nfrom  matplotlib import pyplot as plt\nimport numpy as np\n#Function for initialization of parameters\ndef initialize():\n    RMin = 0.0\n    RMax = 10.0\n    lOrbital = 0\n    Dim = 400\n    return RMin, RMax, lOrbital, Dim\n# Here we set up the harmonic oscillator potential\ndef potential(r):\n    return r*r\n\n#Get the boundary, orbital momentum and number of integration points\nRMin, RMax, lOrbital, Dim = initialize()\n\n#Initialize constants\nStep    = RMax/(Dim+1)\nDiagConst = 2.0 / (Step*Step)\nNondiagConst =  -1.0 / (Step*Step)\nOrbitalFactor = lOrbital * (lOrbital + 1.0)\n\n#Calculate array of potential values\nv = np.zeros(Dim)\nr = np.linspace(RMin,RMax,Dim)\nfor i in xrange(Dim):\n    r[i] = RMin + (i+1) * Step;\n    v[i] = potential(r[i]) + OrbitalFactor/(r[i]*r[i]);\n\n#Setting up tridiagonal matrix and find eigenvectors and eigenvalues\nHamiltonian = np.zeros((Dim,Dim))\nHamiltonian[0,0] = DiagConst + v[0];\nHamiltonian[0,1] = NondiagConst;\nfor i in xrange(1,Dim-1):\n    Hamiltonian[i,i-1]  = NondiagConst;\n    Hamiltonian[i,i]    = DiagConst + v[i];\n    Hamiltonian[i,i+1]  = NondiagConst;\nHamiltonian[Dim-1,Dim-2] = NondiagConst;\nHamiltonian[Dim-1,Dim-1] = DiagConst + v[Dim-1];\n# diagonalize and obtain eigenvalues, not necessarily sorted\nEigValues, EigVectors = np.linalg.eig(Hamiltonian)\n# sort eigenvectors and eigenvalues\npermute = EigValues.argsort()\nEigValues = EigValues[permute]\nEigVectors = EigVectors[:,permute]\n# now plot the results for the three lowest lying eigenstates\nfor i in xrange(3):\n    print EigValues[i]\nFirstEigvector = EigVectors[:,0]\nSecondEigvector = EigVectors[:,1]\nThirdEigvector = EigVectors[:,2]\nplt.plot(r, FirstEigvector**2 ,'b-',r, SecondEigvector**2 ,'g-',r, ThirdEigvector**2 ,'r-')\nplt.axis([0,4.6,0.0, 0.025])\nplt.xlabel(r'$r$')\nplt.ylabel(r'Radial probability $r^2|R(r)|^2$')\nplt.title(r'Radial probability distributions for three lowest-lying states')\nplt.savefig('eigenvector.pdf')\nplt.savefig('eigenvector.png')\nplt.show()\n\n\n```\n\n<!-- --- begin exercise --- -->\n\n### Exercise 1: Masses and binding energies\n\nThe data on binding energies can be found in the file bedata.dat at the github address of the course, see\n<https://github.com/NuclearStructure/PHY981/tree/master/doc/pub/spdata/programs>\n\n\n**a)**\nWrite a small program which reads in the proton and neutron numbers and the binding energies \nand make a plot of all neutron separation energies for the chain of oxygen (O), calcium (Ca), nickel (Ni), tin (Sn) and lead (Pb) isotopes, that is you need to plot\n\n$$\nS_n= BE(N,Z)-BE(N-1,Z).\n$$\n\nComment your results.\n\n**b)**\nIn the same figures, you should also include the liquid drop model results of Eq. (2.17) of Alex Brown's text, namely\n\n$$\nBE(N,Z)= \\alpha_1A-\\alpha_2A^{2/3}-\\alpha_3\\frac{Z^2}{A^{1/3}}-\\alpha_4\\frac{(N-Z)^2}{A},\n$$\n\nwith $\\alpha_1=15.49$ MeV, $\\alpha_2=17.23$ MeV, $\\alpha_3=0.697$ MeV and $\\alpha_4=22.6$ MeV.\nAgain, comment your results.\n\n**c)**\nMake also a plot of the binding energies as function of $A$ using the data in the file on binding energies and the above liquid drop model.  Make a figure similar to figure 2.5 of Alex Brown where you set the various parameters $\\alpha_i=0$. Comment your results.\n\n**d)**\nUse the liquid drop model to find the neutron drip lines   for Z values up to 120.\nAnalyze then the fluorine isotopes and find, where available the corresponding experimental data, and compare the liquid drop model predicition with experiment. \nComment your results.\nA program example in C++ and the input data file *bedata.dat* can be found found at the github repository for the [course](https://github.com/NuclearStructure/PHY981/tree/master/doc/pub/spdata/programs)\n\n\n\n<!-- --- end exercise --- -->\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 2: Eigenvalues and eigenvectors for various single-particle potentials\n\nThe program for finding the eigenvalues of the harmonic oscillator are in the github folder\n<https://github.com/NuclearStructure/PHY981/tree/master/doc/pub/spdata/programs>.\n\nYou can use this program to solve the exercises below, or write your own using your preferred programming language, be it python, fortran or c++ or other languages. Here I will mainly provide fortran, python and c++.\n\n\n**a)**\nCompute the eigenvalues of the five lowest states with a given orbital momentum and oscillator frequency $\\omega$. Study these results as functions of the the maximum value of $r$ and the number of integration points $n$, starting with  $r_{\\mathrm{max}}=10$. Compare the computed ones with the exact values and comment your results.\n\n**b)**\nPlot thereafter the eigenfunctions as functions of $r$ for the lowest-lying state with a given orbital momentum $l$.\n\n**c)**\nReplace thereafter the harmonic oscillator potential with a Woods-Saxon potential using the parameters discussed above. Compute the lowest five eigenvalues and plot the eigenfunction of the lowest-lying state. How does this compare with the harmonic oscillator? Comment your results and possible implications for nuclear physics studies.\n\n<!-- --- end exercise --- -->\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 3: Operators and Slater determinants\n\nConsider the Slater determinant\n\n$$\n\\Phi_{\\lambda}^{AS}(x_{1}x_{2}\\dots x_{N};\\alpha_{1}\\alpha_{2}\\dots\\alpha_{N})\n=\\frac{1}{\\sqrt{N!}}\\sum_{p}(-)^{p}P\\prod_{i=1}^{N}\\psi_{\\alpha_{i}}(x_{i}).\n$$\n\nwhere $P$ is an operator which permutes the coordinates of two particles. We have assumed here that the \nnumber of particles is the same as the number of available single-particle states, represented by the\ngreek letters $\\alpha_{1}\\alpha_{2}\\dots\\alpha_{N}$.\n\n\n**a)**\nWrite  out $\\Phi^{AS}$ for $N=3$.\n\n**b)**\nShow that\n\n$$\n\\int dx_{1}dx_{2}\\dots dx_{N}\\left\\vert\n\\Phi_{\\lambda}^{AS}(x_{1}x_{2}\\dots x_{N};\\alpha_{1}\\alpha_{2}\\dots\\alpha_{N})\n\\right\\vert^{2} = 1.\n$$\n\n**c)**\nDefine a general onebody operator $\\hat{F} = \\sum_{i}^N\\hat{f}(x_{i})$ and a general  twobody operator $\\hat{G}=\\sum_{i>j}^N\\hat{g}(x_{i},x_{j})$ with $g$ being invariant under the interchange of the coordinates of particles $i$ and $j$. Calculate the matrix elements for a two-particle Slater determinant\n\n$$\n\\langle\\Phi_{\\alpha_{1}\\alpha_{2}}^{AS}|\\hat{F}|\\Phi_{\\alpha_{1}\\alpha_{2}}^{AS}\\rangle,\n$$\n\nand\n\n$$\n\\langle\\Phi_{\\alpha_{1}\\alpha_{2}}^{AS}|\\hat{G}|\\Phi_{\\alpha_{1}\\alpha_{2}}^{AS}\\rangle.\n$$\n\nExplain the short-hand notation for the Slater determinant.\nWhich properties do you expect these operators to have in addition to an eventual permutation\nsymmetry?\n\n\n<!-- --- end exercise --- -->\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 4: First simple shell-model calculation\n\nWe will now consider a simple three-level problem, depicted in the figure below. This is our first and very simple model of a possible many-nucleon (or just fermion) problem and the shell-model.\nThe single-particle states are labelled by the quantum number $p$ and can accomodate up to two single particles,  viz., every single-particle state  is doubly degenerate (you could think of this as one state having spin up and the other spin down). \nWe let the spacing between the doubly degenerate single-particle states be constant, with value $d$.  The first state\nhas energy $d$. There are only three available single-particle states, $p=1$, $p=2$ and $p=3$, as illustrated\nin the figure.\n\n\n**a)**\nHow many two-particle Slater determinants can we construct in this space? \n\nWe limit ourselves to a system with only the two lowest single-particle orbits and two particles, $p=1$ and $p=2$. We assume that we can write the Hamiltonian as\n\n$$\n\\hat{H}=\\hat{H}_0+\\hat{H}_I,\n$$\n\nand that the onebody part of the Hamiltonian with single-particle operator $\\hat{h}_0$ has the property\n\n$$\n\\hat{h}_0\\psi_{p\\sigma} = p\\times d \\psi_{p\\sigma},\n$$\n\nwhere we have added a spin quantum number $\\sigma$. \nWe assume also that the only two-particle states that can exist are those where two particles are in the \nsame state $p$, as shown by the two possibilities to the left in the figure.\nThe two-particle matrix elements of $\\hat{H}_I$ have all a constant value, $-g$.\n\n**b)**\nShow then that the Hamiltonian matrix can be written as\n\n$$\n\\left(\\begin{array}{cc}2d-g &-g \\\\\n-g &4d-g \\end{array}\\right),\n$$\n\n**c)**\nFind the eigenvalues and eigenvectors.  What is mixing of the state with two particles in $p=2$  to the wave function with two-particles in $p=1$? Discuss your results in terms of a linear combination of Slater determinants.\n\n**d)**\nAdd the possibility that the two particles can be in the state with $p=3$ as well and find the Hamiltonian matrix, the eigenvalues and the eigenvectors. We still insist that we only have two-particle states composed of two particles being in the same level $p$. You can diagonalize numerically your $3\\times 3$ matrix.\nThis simple model catches several birds with a stone. It demonstrates how we can build linear combinations\nof Slater determinants and interpret these as different admixtures to a given state. It represents also the way we are going to interpret these contributions.  The two-particle states above $p=1$ will be interpreted as \nexcitations from the ground state configuration, $p=1$ here.  The reliability of this ansatz for the ground state, \nwith two particles in $p=1$,\ndepends on the strength of the interaction $g$ and the single-particle spacing $d$.\nFinally, this model is a simple schematic ansatz for studies of pairing correlations and thereby superfluidity/superconductivity  \nin fermionic systems. \n\n\n<p>Schematic plot of the possible single-particle levels with double degeneracy. The filled circles indicate occupied particle states. The spacing between each level $p$ is constant in this picture. We show some possible two-particle states.</p>\n\n\n\n\n\n\n<!-- --- end exercise --- -->\n\n\n# Mean-field approaches\n<div id=\"ch:meanfield\"></div>\n\n## Derivation of Hartree-Fock equations in coordinate space\n\nHartree-Fock (HF) theory is an algorithm for finding an approximative expression for the ground state of a given Hamiltonian. The basic ingredients are\n  * Define a single-particle basis $\\{\\psi_{\\alpha}\\}$ so that\n\n$$\n\\hat{h}^{\\mathrm{HF}}\\psi_{\\alpha} = \\varepsilon_{\\alpha}\\psi_{\\alpha}\n$$\n\nwith the Hartree-Fock Hamiltonian defined as\n\n$$\n\\hat{h}^{\\mathrm{HF}}=\\hat{t}+\\hat{u}_{\\mathrm{ext}}+\\hat{u}^{\\mathrm{HF}}\n$$\n\n* The term  $\\hat{u}^{\\mathrm{HF}}$ is a single-particle potential to be determined by the HF algorithm.\n\n  * The HF algorithm means to choose $\\hat{u}^{\\mathrm{HF}}$ in order to have\n\n$$\n\\langle \\hat{H} \\rangle = E^{\\mathrm{HF}}= \\langle \\Phi_0 | \\hat{H}|\\Phi_0 \\rangle\n$$\n\nthat is to find a local minimum with a Slater determinant $\\Phi_0$ being the ansatz for the ground state. \n  * The variational principle ensures that $E^{\\mathrm{HF}} \\ge E_0$, with $E_0$ the exact ground state energy.\n\nWe will show that the Hartree-Fock Hamiltonian $\\hat{h}^{\\mathrm{HF}}$ equals our definition of the operator $\\hat{f}$ discussed in connection with the new definition of the normal-ordered Hamiltonian (see later lectures), that is we have, for a specific matrix element\n\n$$\n\\langle p |\\hat{h}^{\\mathrm{HF}}| q \\rangle =\\langle p |\\hat{f}| q \\rangle=\\langle p|\\hat{t}+\\hat{u}_{\\mathrm{ext}}|q \\rangle +\\sum_{i\\le F} \\langle pi | \\hat{V} | qi\\rangle_{AS},\n$$\n\nmeaning that\n\n$$\n\\langle p|\\hat{u}^{\\mathrm{HF}}|q\\rangle = \\sum_{i\\le F} \\langle pi | \\hat{V} | qi\\rangle_{AS}.\n$$\n\nThe so-called Hartree-Fock potential $\\hat{u}^{\\mathrm{HF}}$ brings an explicit medium dependence due to the summation over all single-particle states below the Fermi level $F$. It brings also in an explicit dependence on the two-body interaction (in nuclear physics we can also have complicated three- or higher-body forces). The two-body interaction, with its contribution from the other bystanding fermions, creates an effective mean field in which a given fermion moves, in addition to the external potential $\\hat{u}_{\\mathrm{ext}}$ which confines the motion of the fermion. For systems like nuclei, there is no external confining potential. Nuclei are examples of self-bound systems, where the binding arises due to the intrinsic nature of the strong force. For nuclear systems thus, there would be no external one-body potential in the Hartree-Fock Hamiltonian. \n\n\nThe calculus of variations involves \nproblems where the quantity to be minimized or maximized is an integral. \n\nIn the general case we have an integral of the type\n\n$$\nE[\\Phi]= \\int_a^b f(\\Phi(x),\\frac{\\partial \\Phi}{\\partial x},x)dx,\n$$\n\nwhere $E$ is the quantity which is sought minimized or maximized.\nThe problem is that although $f$ is a function of the variables $\\Phi$, $\\partial \\Phi/\\partial x$ and $x$, the exact dependence of\n$\\Phi$ on $x$ is not known.  This means again that even though the integral has fixed limits $a$ and $b$, the path of integration is\nnot known. In our case the unknown quantities are the single-particle wave functions and we wish to choose an integration path which makes\nthe functional $E[\\Phi]$ stationary. This means that we want to find minima, or maxima or saddle points. In physics we search normally for minima.\nOur task is therefore to find the minimum of $E[\\Phi]$ so that its variation $\\delta E$ is zero  subject to specific\nconstraints. In our case the constraints appear as the integral which expresses the orthogonality of the  single-particle wave functions.\nThe constraints can be treated via the technique of Lagrangian multipliers\n\n\n\nLet us specialize to the expectation value of the energy for one particle in three-dimensions.\nThis expectation value reads\n\n$$\nE=\\int dxdydz \\psi^*(x,y,z) \\hat{H} \\psi(x,y,z),\n$$\n\nwith the constraint\n\n$$\n\\int dxdydz \\psi^*(x,y,z) \\psi(x,y,z)=1,\n$$\n\nand a Hamiltonian\n\n$$\n\\hat{H}=-\\frac{1}{2}\\nabla^2+V(x,y,z).\n$$\n\nWe will, for the sake of notational convenience,  skip the variables $x,y,z$ below, and write for example $V(x,y,z)=V$.\n\n\n\nThe integral involving the kinetic energy can be written as, with the function $\\psi$ vanishing\nstrongly for large values of $x,y,z$ (given here by the limits $a$ and $b$),\n\n$$\n\\int_a^b dxdydz \\psi^* \\left(-\\frac{1}{2}\\nabla^2\\right) \\psi dxdydz = \\psi^*\\nabla\\psi|_a^b+\\int_a^b dxdydz\\frac{1}{2}\\nabla\\psi^*\\nabla\\psi.\n$$\n\nWe will drop the limits $a$ and $b$ in the remaining discussion. \nInserting this expression into the expectation value for the energy and taking the variational minimum  we obtain\n\n$$\n\\delta E = \\delta \\left\\{\\int dxdydz\\left( \\frac{1}{2}\\nabla\\psi^*\\nabla\\psi+V\\psi^*\\psi\\right)\\right\\} = 0.\n$$\n\nThe constraint appears in integral form as\n\n$$\n\\int dxdydz \\psi^* \\psi=\\mathrm{constant},\n$$\n\nand multiplying with a Lagrangian multiplier $\\lambda$ and taking the variational minimum we obtain the final variational equation\n\n$$\n\\delta \\left\\{\\int dxdydz\\left( \\frac{1}{2}\\nabla\\psi^*\\nabla\\psi+V\\psi^*\\psi-\\lambda\\psi^*\\psi\\right)\\right\\} = 0.\n$$\n\nWe introduce the function  $f$\n\n$$\nf =  \\frac{1}{2}\\nabla\\psi^*\\nabla\\psi+V\\psi^*\\psi-\\lambda\\psi^*\\psi=\n\\frac{1}{2}(\\psi^*_x\\psi_x+\\psi^*_y\\psi_y+\\psi^*_z\\psi_z)+V\\psi^*\\psi-\\lambda\\psi^*\\psi,\n$$\n\nwhere we have skipped the dependence on $x,y,z$ and introduced the shorthand $\\psi_x$, $\\psi_y$ and $\\psi_z$  for the various derivatives.\n\n\n\n\nFor $\\psi^*$ the Euler-Lagrange  equations yield\n\n$$\n\\frac{\\partial f}{\\partial \\psi^*}- \\frac{\\partial }{\\partial x}\\frac{\\partial f}{\\partial \\psi^*_x}-\\frac{\\partial }{\\partial y}\\frac{\\partial f}{\\partial \\psi^*_y}-\\frac{\\partial }{\\partial z}\\frac{\\partial f}{\\partial \\psi^*_z}=0,\n$$\n\nwhich results in\n\n$$\n-\\frac{1}{2}(\\psi_{xx}+\\psi_{yy}+\\psi_{zz})+V\\psi=\\lambda \\psi.\n$$\n\nWe can then identify the  Lagrangian multiplier as the energy of the system. The last equation is \nnothing but the standard \nSchroedinger equation and the variational  approach discussed here provides \na powerful method for obtaining approximate solutions of the wave function.\n\n\n\n\n\n\n## Definitions and notations\n\nBefore we proceed we need some definitions.\nWe will assume that the interacting part of the Hamiltonian\ncan be approximated by a two-body interaction.\nThis means that our Hamiltonian is written as the sum of some onebody part and a twobody part\n\n<!-- Equation labels as ordinary links -->\n<div id=\"Hnuclei\"></div>\n\n$$\n\\begin{equation}\n    \\hat{H} = \\hat{H}_0 + \\hat{H}_I \n    = \\sum_{i=1}^A \\hat{h}_0(x_i) + \\sum_{i < j}^A \\hat{v}(r_{ij}),\n\\label{Hnuclei} \\tag{9}\n\\end{equation}\n$$\n\nwith\n\n<!-- Equation labels as ordinary links -->\n<div id=\"hinuclei\"></div>\n\n$$\n\\begin{equation}\n  H_0=\\sum_{i=1}^A \\hat{h}_0(x_i).\n\\label{hinuclei} \\tag{10}\n\\end{equation}\n$$\n\nThe onebody part $u_{\\mathrm{ext}}(x_i)$ is normally approximated by a harmonic oscillator potential or the Coulomb interaction an electron feels from the nucleus. However, other potentials are fully possible, such as \none derived from the self-consistent solution of the Hartree-Fock equations to be discussed here.\n\n\n\n\nOur Hamiltonian is invariant under the permutation (interchange) of two particles.\nSince we deal with fermions however, the total wave function is antisymmetric.\nLet $\\hat{P}$ be an operator which interchanges two particles.\nDue to the symmetries we have ascribed to our Hamiltonian, this operator commutes with the total Hamiltonian,\n\n$$\n[\\hat{H},\\hat{P}] = 0,\n$$\n\nmeaning that $\\Psi_{\\lambda}(x_1, x_2, \\dots , x_A)$ is an eigenfunction of \n$\\hat{P}$ as well, that is\n\n$$\n\\hat{P}_{ij}\\Psi_{\\lambda}(x_1, x_2, \\dots,x_i,\\dots,x_j,\\dots,x_A)=\n\\beta\\Psi_{\\lambda}(x_1, x_2, \\dots,x_i,\\dots,x_j,\\dots,x_A),\n$$\n\nwhere $\\beta$ is the eigenvalue of $\\hat{P}$. We have introduced the suffix $ij$ in order to indicate that we permute particles $i$ and $j$.\nThe Pauli principle tells us that the total wave function for a system of fermions\nhas to be antisymmetric, resulting in the eigenvalue $\\beta = -1$.   \n\n\n\nIn our case we assume that  we can approximate the exact eigenfunction with a Slater determinant\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:HartreeFockDet\"></div>\n\n$$\n\\begin{equation}\n   \\Phi(x_1, x_2,\\dots ,x_A,\\alpha,\\beta,\\dots, \\sigma)=\\frac{1}{\\sqrt{A!}}\n\\left| \\begin{array}{ccccc} \\psi_{\\alpha}(x_1)& \\psi_{\\alpha}(x_2)& \\dots & \\dots & \\psi_{\\alpha}(x_A)\\\\\n                            \\psi_{\\beta}(x_1)&\\psi_{\\beta}(x_2)& \\dots & \\dots & \\psi_{\\beta}(x_A)\\\\  \n                            \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n                            \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n                     \\psi_{\\sigma}(x_1)&\\psi_{\\sigma}(x_2)& \\dots & \\dots & \\psi_{\\sigma}(x_A)\\end{array} \\right|, \\label{eq:HartreeFockDet} \\tag{11}\n\\end{equation}\n$$\n\nwhere  $x_i$  stand for the coordinates and spin values of a particle $i$ and $\\alpha,\\beta,\\dots, \\gamma$ \nare quantum numbers needed to describe remaining quantum numbers.  \n\n\n\nThe single-particle function $\\psi_{\\alpha}(x_i)$  are eigenfunctions of the onebody\nHamiltonian $h_i$, that is\n\n$$\n\\hat{h}_0(x_i)=\\hat{t}(x_i) + \\hat{u}_{\\mathrm{ext}}(x_i),\n$$\n\nwith eigenvalues\n\n$$\n\\hat{h}_0(x_i) \\psi_{\\alpha}(x_i)=\\left(\\hat{t}(x_i) + \\hat{u}_{\\mathrm{ext}}(x_i)\\right)\\psi_{\\alpha}(x_i)=\\varepsilon_{\\alpha}\\psi_{\\alpha}(x_i).\n$$\n\nThe energies $\\varepsilon_{\\alpha}$ are the so-called non-interacting single-particle energies, or unperturbed energies. \nThe total energy is in this case the sum over all  single-particle energies, if no two-body or more complicated\nmany-body interactions are present.\n\n\n\nLet us denote the ground state energy by $E_0$. According to the\nvariational principle we have\n\n$$\nE_0 \\le E[\\Phi] = \\int \\Phi^*\\hat{H}\\Phi d\\mathbf{\\tau}\n$$\n\nwhere $\\Phi$ is a trial function which we assume to be normalized\n\n$$\n\\int \\Phi^*\\Phi d\\mathbf{\\tau} = 1,\n$$\n\nwhere we have used the shorthand $d\\mathbf{\\tau}=dx_1dr_2\\dots dr_A$.\n\n\n\nIn the Hartree-Fock method the trial function is the Slater\ndeterminant of Eq. [(11)](#eq:HartreeFockDet) which can be rewritten as\n\n$$\n\\Phi(x_1,x_2,\\dots,x_A,\\alpha,\\beta,\\dots,\\nu) = \\frac{1}{\\sqrt{A!}}\\sum_{P} (-)^P\\hat{P}\\psi_{\\alpha}(x_1)\n    \\psi_{\\beta}(x_2)\\dots\\psi_{\\nu}(x_A)=\\sqrt{A!}\\hat{A}\\Phi_H,\n$$\n\nwhere we have introduced the antisymmetrization operator $\\hat{A}$ defined by the \nsummation over all possible permutations of two particles.\n\n\nIt is defined as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"antiSymmetryOperator\"></div>\n\n$$\n\\begin{equation}\n  \\hat{A} = \\frac{1}{A!}\\sum_{p} (-)^p\\hat{P},\n\\label{antiSymmetryOperator} \\tag{12}\n\\end{equation}\n$$\n\nwith $p$ standing for the number of permutations. We have introduced for later use the so-called\nHartree-function, defined by the simple product of all possible single-particle functions\n\n$$\n\\Phi_H(x_1,x_2,\\dots,x_A,\\alpha,\\beta,\\dots,\\nu) =\n  \\psi_{\\alpha}(x_1)\n    \\psi_{\\beta}(x_2)\\dots\\psi_{\\nu}(x_A).\n$$\n\nBoth $\\hat{H}_0$ and $\\hat{H}_I$ are invariant under all possible permutations of any two particles\nand hence commute with $\\hat{A}$\n\n<!-- Equation labels as ordinary links -->\n<div id=\"commutionAntiSym\"></div>\n\n$$\n\\begin{equation}\n  [H_0,\\hat{A}] = [H_I,\\hat{A}] = 0. \\label{commutionAntiSym} \\tag{13}\n\\end{equation}\n$$\n\nFurthermore, $\\hat{A}$ satisfies\n\n<!-- Equation labels as ordinary links -->\n<div id=\"AntiSymSquared\"></div>\n\n$$\n\\begin{equation}\n  \\hat{A}^2 = \\hat{A},  \\label{AntiSymSquared} \\tag{14}\n\\end{equation}\n$$\n\nsince every permutation of the Slater\ndeterminant reproduces it. \n\n\n\n\nThe expectation value of $\\hat{H}_0$\n\n$$\n\\int \\Phi^*\\hat{H}_0\\Phi d\\mathbf{\\tau} \n  = A! \\int \\Phi_H^*\\hat{A}\\hat{H}_0\\hat{A}\\Phi_H d\\mathbf{\\tau}\n$$\n\nis readily reduced to\n\n$$\n\\int \\Phi^*\\hat{H}_0\\Phi d\\mathbf{\\tau} \n  = A! \\int \\Phi_H^*\\hat{H}_0\\hat{A}\\Phi_H d\\mathbf{\\tau},\n$$\n\nwhere we have used Eqs. [(13)](#commutionAntiSym) and\n[(14)](#AntiSymSquared). The next step is to replace the antisymmetrization\noperator by its definition and to\nreplace $\\hat{H}_0$ with the sum of one-body operators\n\n$$\n\\int \\Phi^*\\hat{H}_0\\Phi  d\\mathbf{\\tau}\n  = \\sum_{i=1}^A \\sum_{p} (-)^p\\int \n  \\Phi_H^*\\hat{h}_0\\hat{P}\\Phi_H d\\mathbf{\\tau}.\n$$\n\nThe integral vanishes if two or more particles are permuted in only one\nof the Hartree-functions $\\Phi_H$ because the individual single-particle wave functions are\northogonal. We obtain then\n\n$$\n\\int \\Phi^*\\hat{H}_0\\Phi  d\\mathbf{\\tau}= \\sum_{i=1}^A \\int \\Phi_H^*\\hat{h}_0\\Phi_H  d\\mathbf{\\tau}.\n$$\n\nOrthogonality of the single-particle functions allows us to further simplify the integral, and we\narrive at the following expression for the expectation values of the\nsum of one-body Hamiltonians\n\n<!-- Equation labels as ordinary links -->\n<div id=\"H1Expectation\"></div>\n\n$$\n\\begin{equation}\n  \\int \\Phi^*\\hat{H}_0\\Phi  d\\mathbf{\\tau}\n  = \\sum_{\\mu=1}^A \\int \\psi_{\\mu}^*(x)\\hat{h}_0\\psi_{\\mu}(x)dx\n  d\\mathbf{r}.\n  \\label{H1Expectation} \\tag{15}\n\\end{equation}\n$$\n\nWe introduce the following shorthand for the above integral\n\n$$\n\\langle \\mu | \\hat{h}_0 | \\mu \\rangle = \\int \\psi_{\\mu}^*(x)\\hat{h}_0\\psi_{\\mu}(x)dx,\n$$\n\nand rewrite Eq. [(15)](#H1Expectation) as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"H1Expectation1\"></div>\n\n$$\n\\begin{equation}\n  \\int \\Phi^*\\hat{H}_0\\Phi  d\\tau\n  = \\sum_{\\mu=1}^A \\langle \\mu | \\hat{h}_0 | \\mu \\rangle.\n  \\label{H1Expectation1} \\tag{16}\n\\end{equation}\n$$\n\nThe expectation value of the two-body part of the Hamiltonian is obtained in a\nsimilar manner. We have\n\n$$\n\\int \\Phi^*\\hat{H}_I\\Phi d\\mathbf{\\tau} \n  = A! \\int \\Phi_H^*\\hat{A}\\hat{H}_I\\hat{A}\\Phi_H d\\mathbf{\\tau},\n$$\n\nwhich reduces to\n\n$$\n\\int \\Phi^*\\hat{H}_I\\Phi d\\mathbf{\\tau} \n  = \\sum_{i\\le j=1}^A \\sum_{p} (-)^p\\int \n  \\Phi_H^*\\hat{v}(r_{ij})\\hat{P}\\Phi_H d\\mathbf{\\tau},\n$$\n\nby following the same arguments as for the one-body\nHamiltonian. \n\n\n\nBecause of the dependence on the inter-particle distance $r_{ij}$,  permutations of\nany two particles no longer vanish, and we get\n\n$$\n\\int \\Phi^*\\hat{H}_I\\Phi d\\mathbf{\\tau} \n  = \\sum_{i < j=1}^A \\int  \n  \\Phi_H^*\\hat{v}(r_{ij})(1-P_{ij})\\Phi_H d\\mathbf{\\tau}.\n$$\n\nwhere $P_{ij}$ is the permutation operator that interchanges\nparticle $i$ and particle $j$. Again we use the assumption that the single-particle wave functions\nare orthogonal. \n\n\n\n\n\nWe obtain\n\n<!-- Equation labels as ordinary links -->\n<div id=\"H2Expectation\"></div>\n\n$$\n\\begin{equation}\n\\begin{split}\n  \\int \\Phi^*\\hat{H}_I\\Phi d\\mathbf{\\tau} \n  = \\frac{1}{2}\\sum_{\\mu=1}^A\\sum_{\\nu=1}^A\n    &\\left[ \\int \\psi_{\\mu}^*(x_i)\\psi_{\\nu}^*(x_j)\\hat{v}(r_{ij})\\psi_{\\mu}(x_i)\\psi_{\\nu}(x_j)\n    dx_idx_j \\right.\\\\\n  &\\left.\n  - \\int \\psi_{\\mu}^*(x_i)\\psi_{\\nu}^*(x_j)\n  \\hat{v}(r_{ij})\\psi_{\\nu}(x_i)\\psi_{\\mu}(x_j)\n  dx_idx_j\n  \\right]. \\label{H2Expectation} \\tag{17}\n\\end{split}\n\\end{equation}\n$$\n\nThe first term is the so-called direct term. It is frequently also called the  Hartree term, \nwhile the second is due to the Pauli principle and is called\nthe exchange term or just the Fock term.\nThe factor  $1/2$ is introduced because we now run over\nall pairs twice. \n\n\n\nThe last equation allows us to  introduce some further definitions.  \nThe single-particle wave functions $\\psi_{\\mu}(x)$, defined by the quantum numbers $\\mu$ and $x$\nare defined as the overlap\n\n$$\n\\psi_{\\alpha}(x)  = \\langle x | \\alpha \\rangle .\n$$\n\nWe introduce the following shorthands for the above two integrals\n\n$$\n\\langle \\mu\\nu|\\hat{v}|\\mu\\nu\\rangle =  \\int \\psi_{\\mu}^*(x_i)\\psi_{\\nu}^*(x_j)\\hat{v}(r_{ij})\\psi_{\\mu}(x_i)\\psi_{\\nu}(x_j)\n    dx_idx_j,\n$$\n\nand\n\n$$\n\\langle \\mu\\nu|\\hat{v}|\\nu\\mu\\rangle = \\int \\psi_{\\mu}^*(x_i)\\psi_{\\nu}^*(x_j)\n  \\hat{v}(r_{ij})\\psi_{\\nu}(x_i)\\psi_{\\mu}(x_j)\n  dx_idx_j.\n$$\n\n## Derivation of Hartree-Fock equations in coordinate space\n\nLet us denote the ground state energy by $E_0$. According to the\nvariational principle we have\n\n$$\nE_0 \\le E[\\Phi] = \\int \\Phi^*\\hat{H}\\Phi d\\mathbf{\\tau}\n$$\n\nwhere $\\Phi$ is a trial function which we assume to be normalized\n\n$$\n\\int \\Phi^*\\Phi d\\mathbf{\\tau} = 1,\n$$\n\nwhere we have used the shorthand $d\\mathbf{\\tau}=dx_1dx_2\\dots dx_A$.\n\n\n\n\n\nIn the Hartree-Fock method the trial function is a Slater\ndeterminant which can be rewritten as\n\n$$\n\\Psi(x_1,x_2,\\dots,x_A,\\alpha,\\beta,\\dots,\\nu) = \\frac{1}{\\sqrt{A!}}\\sum_{P} (-)^PP\\psi_{\\alpha}(x_1)\n    \\psi_{\\beta}(x_2)\\dots\\psi_{\\nu}(x_A)=\\sqrt{A!}\\hat{A}\\Phi_H,\n$$\n\nwhere we have introduced the anti-symmetrization operator $\\hat{A}$ defined by the \nsummation over all possible permutations *p* of two fermions.\nIt is defined as\n\n$$\n\\hat{A} = \\frac{1}{A!}\\sum_{p} (-)^p\\hat{P},\n$$\n\nwith the the Hartree-function given by the simple product of all possible single-particle function\n\n$$\n\\Phi_H(x_1,x_2,\\dots,x_A,\\alpha,\\beta,\\dots,\\nu) =\n  \\psi_{\\alpha}(x_1)\n    \\psi_{\\beta}(x_2)\\dots\\psi_{\\nu}(x_A).\n$$\n\nOur functional is written as\n\n$$\nE[\\Phi] = \\sum_{\\mu=1}^A \\int \\psi_{\\mu}^*(x_i)\\hat{h}_0(x_i)\\psi_{\\mu}(x_i) dx_i \n  + \\frac{1}{2}\\sum_{\\mu=1}^A\\sum_{\\nu=1}^A\n   \\left[ \\int \\psi_{\\mu}^*(x_i)\\psi_{\\nu}^*(x_j)\\hat{v}(r_{ij})\\psi_{\\mu}(x_i)\\psi_{\\nu}(x_j)dx_idx_j- \\int \\psi_{\\mu}^*(x_i)\\psi_{\\nu}^*(x_j)\n \\hat{v}(r_{ij})\\psi_{\\nu}(x_i)\\psi_{\\mu}(x_j)dx_idx_j\\right]\n$$\n\nThe more compact version reads\n\n$$\nE[\\Phi] \n  = \\sum_{\\mu}^A \\langle \\mu | \\hat{h}_0 | \\mu\\rangle+ \\frac{1}{2}\\sum_{\\mu\\nu}^A\\left[\\langle \\mu\\nu |\\hat{v}|\\mu\\nu\\rangle-\\langle \\nu\\mu |\\hat{v}|\\mu\\nu\\rangle\\right].\n$$\n\nSince the interaction is invariant under the interchange of two particles it means for example that we have\n\n$$\n\\langle \\mu\\nu|\\hat{v}|\\mu\\nu\\rangle =  \\langle \\nu\\mu|\\hat{v}|\\nu\\mu\\rangle,\n$$\n\nor in the more general case\n\n$$\n\\langle \\mu\\nu|\\hat{v}|\\sigma\\tau\\rangle =  \\langle \\nu\\mu|\\hat{v}|\\tau\\sigma\\rangle.\n$$\n\nThe direct and exchange matrix elements can be  brought together if we define the antisymmetrized matrix element\n\n$$\n\\langle \\mu\\nu|\\hat{v}|\\mu\\nu\\rangle_{AS}= \\langle \\mu\\nu|\\hat{v}|\\mu\\nu\\rangle-\\langle \\mu\\nu|\\hat{v}|\\nu\\mu\\rangle,\n$$\n\nor for a general matrix element\n\n$$\n\\langle \\mu\\nu|\\hat{v}|\\sigma\\tau\\rangle_{AS}= \\langle \\mu\\nu|\\hat{v}|\\sigma\\tau\\rangle-\\langle \\mu\\nu|\\hat{v}|\\tau\\sigma\\rangle.\n$$\n\nIt has the symmetry property\n\n$$\n\\langle \\mu\\nu|\\hat{v}|\\sigma\\tau\\rangle_{AS}= -\\langle \\mu\\nu|\\hat{v}|\\tau\\sigma\\rangle_{AS}=-\\langle \\nu\\mu|\\hat{v}|\\sigma\\tau\\rangle_{AS}.\n$$\n\nThe antisymmetric matrix element is also hermitian, implying\n\n$$\n\\langle \\mu\\nu|\\hat{v}|\\sigma\\tau\\rangle_{AS}= \\langle \\sigma\\tau|\\hat{v}|\\mu\\nu\\rangle_{AS}.\n$$\n\nWith these notations we rewrite the Hartree-Fock functional as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"H2Expectation2\"></div>\n\n$$\n\\begin{equation}\n  \\int \\Phi^*\\hat{H_I}\\Phi d\\mathbf{\\tau} \n  = \\frac{1}{2}\\sum_{\\mu=1}^A\\sum_{\\nu=1}^A \\langle \\mu\\nu|\\hat{v}|\\mu\\nu\\rangle_{AS}. \\label{H2Expectation2} \\tag{18}\n\\end{equation}\n$$\n\nAdding the contribution from the one-body operator $\\hat{H}_0$ to\n[(18)](#H2Expectation2) we obtain the energy functional\n\n<!-- Equation labels as ordinary links -->\n<div id=\"FunctionalEPhi\"></div>\n\n$$\n\\begin{equation}\n  E[\\Phi] \n  = \\sum_{\\mu=1}^A \\langle \\mu | h | \\mu \\rangle +\n  \\frac{1}{2}\\sum_{{\\mu}=1}^A\\sum_{{\\nu}=1}^A \\langle \\mu\\nu|\\hat{v}|\\mu\\nu\\rangle_{AS}. \\label{FunctionalEPhi} \\tag{19}\n\\end{equation}\n$$\n\nIn our coordinate space derivations below we will spell out the Hartree-Fock equations in terms of their integrals.\n\n\n\n\nIf we generalize the Euler-Lagrange equations to more variables \nand introduce $N^2$ Lagrange multipliers which we denote by \n$\\epsilon_{\\mu\\nu}$, we can write the variational equation for the functional of $E$\n\n$$\n\\delta E - \\sum_{\\mu\\nu}^A \\epsilon_{\\mu\\nu} \\delta\n  \\int \\psi_{\\mu}^* \\psi_{\\nu} = 0.\n$$\n\nFor the orthogonal wave functions $\\psi_{i}$ this reduces to\n\n$$\n\\delta E - \\sum_{\\mu=1}^A \\epsilon_{\\mu} \\delta\n  \\int \\psi_{\\mu}^* \\psi_{\\mu} = 0.\n$$\n\nVariation with respect to the single-particle wave functions $\\psi_{\\mu}$ yields then\n\n1\n7\n6\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\sum_{\\mu=1}^A \\int \\psi_{\\mu}^*\\hat{h_0}(x_i)\\delta\\psi_{\\mu}\n  dx_i \n  + \\frac{1}{2}\\sum_{{\\mu}=1}^A\\sum_{{\\nu}=1}^A \\left[ \\int\n  \\psi_{\\mu}^*\\psi_{\\nu}^*\\hat{v}(r_{ij})\\delta\\psi_{\\mu}\\psi_{\\nu} dx_idx_j- \\int\n  \\psi_{\\mu}^*\\psi_{\\nu}^*\\hat{v}(r_{ij})\\psi_{\\nu}\\delta\\psi_{\\mu}\n  dx_idx_j \\right]-  \\sum_{{\\mu}=1}^A E_{\\mu} \\int \\delta\\psi_{\\mu}^*\n  \\psi_{\\mu}dx_i\n  -  \\sum_{{\\mu}=1}^A E_{\\mu} \\int \\psi_{\\mu}^*\n  \\delta\\psi_{\\mu}dx_i = 0.\n$$\n\nAlthough the variations $\\delta\\psi$ and $\\delta\\psi^*$ are not\nindependent, they may in fact be treated as such, so that the \nterms dependent on either $\\delta\\psi$ and $\\delta\\psi^*$ individually \nmay be set equal to zero. To see this, simply \nreplace the arbitrary variation $\\delta\\psi$ by $i\\delta\\psi$, so that\n$\\delta\\psi^*$ is replaced by $-i\\delta\\psi^*$, and combine the two\nequations. We thus arrive at the Hartree-Fock equations\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:hartreefockcoordinatespace\"></div>\n\n$$\n\\begin{equation}\n\\left[ -\\frac{1}{2}\\nabla_i^2+ \\sum_{\\nu=1}^A\\int \\psi_{\\nu}^*(x_j)\\hat{v}(r_{ij})\\psi_{\\nu}(x_j)dx_j \\right]\\psi_{\\mu}(x_i) - \\left[ \\sum_{{\\nu}=1}^A \\int\\psi_{\\nu}^*(x_j)\\hat{v}(r_{ij})\\psi_{\\mu}(x_j) dx_j\\right] \\psi_{\\nu}(x_i) = \\epsilon_{\\mu} \\psi_{\\mu}(x_i).  \\label{eq:hartreefockcoordinatespace} \\tag{20}\n\\end{equation}\n$$\n\nNotice that the integration $\\int dx_j$ implies an\nintegration over the spatial coordinates $\\mathbf{r_j}$ and a summation\nover the spin-coordinate of fermion $j$. We note that the factor of $1/2$ in front of the sum involving the two-body interaction, has been removed. This is due to the fact that we need to vary both $\\delta\\psi_{\\mu}^*$ and\n$\\delta\\psi_{\\nu}^*$. Using the symmetry properties of the two-body interaction and interchanging $\\mu$ and $\\nu$\nas summation indices, we obtain two identical terms. \n\n\n\n\nThe two first terms in the last equation are the one-body kinetic energy and the\nelectron-nucleus potential. The third or *direct* term is the averaged electronic repulsion of the other\nelectrons. As written, the\nterm includes the *self-interaction* of \nelectrons when $\\mu=\\nu$. The self-interaction is cancelled in the fourth\nterm, or the *exchange* term. The exchange term results from our\ninclusion of the Pauli principle and the assumed determinantal form of\nthe wave-function. Equation [(20)](#eq:hartreefockcoordinatespace), in addition to the kinetic energy and the attraction from the atomic nucleus that confines the motion of a single electron,   represents now the motion of a single-particle modified by the two-body interaction. The additional contribution to the Schroedinger equation due to the two-body interaction, represents a mean field set up by all the other bystanding electrons, the latter given by the sum over all single-particle states occupied by $N$ electrons. \n\nThe Hartree-Fock equation is an example of an integro-differential equation. These equations involve repeated calculations of integrals, in addition to the solution of a set of coupled differential equations. \nThe Hartree-Fock equations can also be rewritten in terms of an eigenvalue problem. The solution of an eigenvalue problem represents often a more practical algorithm and the  solution of  coupled  integro-differential equations.\nThis alternative derivation of the Hartree-Fock equations is given below.\n\n\n\n\n## Analysis of Hartree-Fock equations in coordinate space\n\n  A theoretically convenient form of the\nHartree-Fock equation is to regard the direct and exchange operator\ndefined through\n\n$$\nV_{\\mu}^{d}(x_i) = \\int \\psi_{\\mu}^*(x_j) \n \\hat{v}(r_{ij})\\psi_{\\mu}(x_j) dx_j\n$$\n\nand\n\n$$\nV_{\\mu}^{ex}(x_i) g(x_i) \n  = \\left(\\int \\psi_{\\mu}^*(x_j) \n \\hat{v}(r_{ij})g(x_j) dx_j\n  \\right)\\psi_{\\mu}(x_i),\n$$\n\nrespectively. \n\n\n\nThe function $g(x_i)$ is an arbitrary function,\nand by the substitution $g(x_i) = \\psi_{\\nu}(x_i)$\nwe get\n\n$$\nV_{\\mu}^{ex}(x_i) \\psi_{\\nu}(x_i) \n  = \\left(\\int \\psi_{\\mu}^*(x_j) \n \\hat{v}(r_{ij})\\psi_{\\nu}(x_j)\n  dx_j\\right)\\psi_{\\mu}(x_i).\n$$\n\nWe may then rewrite the Hartree-Fock equations as\n\n$$\n\\hat{h}^{HF}(x_i) \\psi_{\\nu}(x_i) = \\epsilon_{\\nu}\\psi_{\\nu}(x_i),\n$$\n\nwith\n\n$$\n\\hat{h}^{HF}(x_i)= \\hat{h}_0(x_i) + \\sum_{\\mu=1}^AV_{\\mu}^{d}(x_i) -\n  \\sum_{\\mu=1}^AV_{\\mu}^{ex}(x_i),\n$$\n\nand where $\\hat{h}_0(i)$ is the one-body part. The latter is normally chosen as a part which yields solutions in closed form. The harmonic oscilltor is a classical problem thereof.\nWe normally rewrite the last equation as\n\n$$\n\\hat{h}^{HF}(x_i)= \\hat{h}_0(x_i) + \\hat{u}^{HF}(x_i).\n$$\n\n## Hartree-Fock by varying the coefficients of a wave function expansion\n\nAnother possibility is to expand the single-particle functions in a known basis  and vary the coefficients, \nthat is, the new single-particle wave function is written as a linear expansion\nin terms of a fixed chosen orthogonal basis (for example the well-known harmonic oscillator functions or the hydrogen-like functions etc).\nWe define our new Hartree-Fock single-particle basis by performing a unitary transformation \non our previous basis (labelled with greek indices) as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:newbasis\"></div>\n\n$$\n\\begin{equation}\n\\psi_p^{HF}  = \\sum_{\\lambda} C_{p\\lambda}\\phi_{\\lambda}. \\label{eq:newbasis} \\tag{21}\n\\end{equation}\n$$\n\nIn this case we vary the coefficients $C_{p\\lambda}$. If the basis has infinitely many solutions, we need\nto truncate the above sum.  We assume that the basis $\\phi_{\\lambda}$ is orthogonal. A unitary transformation keeps the orthogonality, as discussed in exercise 1 below.  \n\n\nIt is normal to choose a single-particle basis defined as the eigenfunctions\nof parts of the full Hamiltonian. The typical situation consists of the solutions of the one-body part of the Hamiltonian, that is we have\n\n$$\n\\hat{h}_0\\phi_{\\lambda}=\\epsilon_{\\lambda}\\phi_{\\lambda}.\n$$\n\nThe single-particle wave functions $\\phi_{\\lambda}({\\bf r})$, defined by the quantum numbers $\\lambda$ and ${\\bf r}$\nare defined as the overlap\n\n$$\n\\phi_{\\lambda}({\\bf r})  = \\langle {\\bf r} | \\lambda \\rangle .\n$$\n\nIn our discussions hereafter we will use our definitions of single-particle states above and below the Fermi ($F$) level given by the labels\n$ijkl\\dots \\le F$ for so-called single-hole states and $abcd\\dots > F$ for so-called particle states.\nFor general single-particle states we employ the labels $pqrs\\dots$. \n\n\n\n\nIn Eq. [(19)](#FunctionalEPhi), restated here\n\n$$\nE[\\Phi] \n  = \\sum_{\\mu=1}^A \\langle \\mu | h | \\mu \\rangle +\n  \\frac{1}{2}\\sum_{{\\mu}=1}^A\\sum_{{\\nu}=1}^A \\langle \\mu\\nu|\\hat{v}|\\mu\\nu\\rangle_{AS},\n$$\n\nwe found the expression for the energy functional in terms of the basis function $\\phi_{\\lambda}({\\bf r})$. We then  varied the above energy functional with respect to the basis functions $|\\mu \\rangle$. \nNow we are interested in defining a new basis defined in terms of\na chosen basis as defined in Eq. [(21)](#eq:newbasis). We can then rewrite the energy functional as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"FunctionalEPhi2\"></div>\n\n$$\n\\begin{equation}\n  E[\\Phi^{HF}] \n  = \\sum_{i=1}^A \\langle i | h | i \\rangle +\n  \\frac{1}{2}\\sum_{ij=1}^A\\langle ij|\\hat{v}|ij\\rangle_{AS}, \\label{FunctionalEPhi2} \\tag{22}\n\\end{equation}\n$$\n\nwhere $\\Phi^{HF}$ is the new Slater determinant defined by the new basis of Eq. [(21)](#eq:newbasis). \n\n\nUsing Eq. [(21)](#eq:newbasis) we can rewrite Eq. [(22)](#FunctionalEPhi2) as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"FunctionalEPhi3\"></div>\n\n$$\n\\begin{equation}\n  E[\\Psi] \n  = \\sum_{i=1}^A \\sum_{\\alpha\\beta} C^*_{i\\alpha}C_{i\\beta}\\langle \\alpha | h | \\beta \\rangle +\n  \\frac{1}{2}\\sum_{ij=1}^A\\sum_{{\\alpha\\beta\\gamma\\delta}} C^*_{i\\alpha}C^*_{j\\beta}C_{i\\gamma}C_{j\\delta}\\langle \\alpha\\beta|\\hat{v}|\\gamma\\delta\\rangle_{AS}. \\label{FunctionalEPhi3} \\tag{23}\n\\end{equation}\n$$\n\nWe wish now to minimize the above functional. We introduce again a set of Lagrange multipliers, noting that\nsince $\\langle i | j \\rangle = \\delta_{i,j}$ and $\\langle \\alpha | \\beta \\rangle = \\delta_{\\alpha,\\beta}$, \nthe coefficients $C_{i\\gamma}$ obey the relation\n\n$$\n\\langle i | j \\rangle=\\delta_{i,j}=\\sum_{\\alpha\\beta} C^*_{i\\alpha}C_{i\\beta}\\langle \\alpha | \\beta \\rangle=\n\\sum_{\\alpha} C^*_{i\\alpha}C_{i\\alpha},\n$$\n\nwhich allows us to define a functional to be minimized that reads\n\n$$\n\\begin{equation}\n  F[\\Phi^{HF}]=E[\\Phi^{HF}] - \\sum_{i=1}^A\\epsilon_i\\sum_{\\alpha} C^*_{i\\alpha}C_{i\\alpha}.\n\\end{equation}\n$$\n\nMinimizing with respect to $C^*_{i\\alpha}$, remembering that the equations for $C^*_{i\\alpha}$ and $C_{i\\alpha}$\ncan be written as two  independent equations, we obtain\n\n$$\n\\frac{d}{dC^*_{i\\alpha}}\\left[  E[\\Phi^{HF}] - \\sum_{j}\\epsilon_j\\sum_{\\alpha} C^*_{j\\alpha}C_{j\\alpha}\\right]=0,\n$$\n\nwhich yields for every single-particle state $i$ and index $\\alpha$ (recalling that the coefficients $C_{i\\alpha}$ are matrix elements of a unitary (or orthogonal for a real symmetric matrix) matrix)\nthe following Hartree-Fock equations\n\n$$\n\\sum_{\\beta} C_{i\\beta}\\langle \\alpha | h | \\beta \\rangle+\n\\sum_{j=1}^A\\sum_{\\beta\\gamma\\delta} C^*_{j\\beta}C_{j\\delta}C_{i\\gamma}\\langle \\alpha\\beta|\\hat{v}|\\gamma\\delta\\rangle_{AS}=\\epsilon_i^{HF}C_{i\\alpha}.\n$$\n\nWe can rewrite this equation as (changing dummy variables)\n\n$$\n\\sum_{\\beta} \\left\\{\\langle \\alpha | h | \\beta \\rangle+\n\\sum_{j}^A\\sum_{\\gamma\\delta} C^*_{j\\gamma}C_{j\\delta}\\langle \\alpha\\gamma|\\hat{v}|\\beta\\delta\\rangle_{AS}\\right\\}C_{i\\beta}=\\epsilon_i^{HF}C_{i\\alpha}.\n$$\n\nNote that the sums over greek indices run over the number of basis set functions (in principle an infinite number).\n\nDefining\n\n$$\nh_{\\alpha\\beta}^{HF}=\\langle \\alpha | h | \\beta \\rangle+\n\\sum_{j=1}^A\\sum_{\\gamma\\delta} C^*_{j\\gamma}C_{j\\delta}\\langle \\alpha\\gamma|\\hat{v}|\\beta\\delta\\rangle_{AS},\n$$\n\nwe can rewrite the new equations as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:newhf\"></div>\n\n$$\n\\begin{equation}\n\\sum_{\\gamma}h_{\\alpha\\beta}^{HF}C_{i\\beta}=\\epsilon_i^{HF}C_{i\\alpha}. \\label{eq:newhf} \\tag{24}\n\\end{equation}\n$$\n\nThe latter is nothing but a standard eigenvalue problem. Compared with Eq. [(20)](#eq:hartreefockcoordinatespace),\nwe see that we do not need to compute any integrals in an iterative procedure for solving the equations.\nIt suffices to tabulate the matrix elements $\\langle \\alpha | h | \\beta \\rangle$ and $\\langle \\alpha\\gamma|\\hat{v}|\\beta\\delta\\rangle_{AS}$ once and for all. Successive iterations require thus only a look-up in tables over one-body and two-body matrix elements. These details will be discussed below when we solve the Hartree-Fock equations numerical. \n\n\n\nOur Hartree-Fock matrix  is thus\n\n$$\n\\hat{h}_{\\alpha\\beta}^{HF}=\\langle \\alpha | \\hat{h}_0 | \\beta \\rangle+\n\\sum_{j=1}^A\\sum_{\\gamma\\delta} C^*_{j\\gamma}C_{j\\delta}\\langle \\alpha\\gamma|\\hat{v}|\\beta\\delta\\rangle_{AS}.\n$$\n\nThe Hartree-Fock equations are solved in an iterative waym starting with a guess for the coefficients $C_{j\\gamma}=\\delta_{j,\\gamma}$ and solving the equations by diagonalization till the new single-particle energies\n$\\epsilon_i^{\\mathrm{HF}}$ do not change anymore by a prefixed quantity. \n\n\n\nNormally we assume that the single-particle basis $|\\beta\\rangle$ forms an eigenbasis for the operator\n$\\hat{h}_0$, meaning that the Hartree-Fock matrix becomes\n\n$$\n\\hat{h}_{\\alpha\\beta}^{HF}=\\epsilon_{\\alpha}\\delta_{\\alpha,\\beta}+\n\\sum_{j=1}^A\\sum_{\\gamma\\delta} C^*_{j\\gamma}C_{j\\delta}\\langle \\alpha\\gamma|\\hat{v}|\\beta\\delta\\rangle_{AS}.\n$$\n\nThe Hartree-Fock eigenvalue problem\n\n$$\n\\sum_{\\beta}\\hat{h}_{\\alpha\\beta}^{HF}C_{i\\beta}=\\epsilon_i^{\\mathrm{HF}}C_{i\\alpha},\n$$\n\ncan be written out in a more compact form as\n\n$$\n\\hat{h}^{HF}\\hat{C}=\\epsilon^{\\mathrm{HF}}\\hat{C}.\n$$\n\n## Hartree-Fock algorithm\n\nThe Hartree-Fock equations are, in their simplest form, solved in an iterative way, starting with a guess for the\ncoefficients $C_{i\\alpha}$. We label the coefficients as $C_{i\\alpha}^{(n)}$, where the subscript $n$ stands for iteration $n$.\nTo set up the algorithm we can proceed as follows:\n\n * We start with a guess $C_{i\\alpha}^{(0)}=\\delta_{i,\\alpha}$. Alternatively, we could have used random starting values as long as the vectors are normalized. Another possibility is to give states below the Fermi level a larger weight.\n\n * The Hartree-Fock matrix simplifies then to (assuming that the coefficients $C_{i\\alpha} $  are real)\n\n$$\n\\hat{h}_{\\alpha\\beta}^{HF}=\\epsilon_{\\alpha}\\delta_{\\alpha,\\beta}+\n\\sum_{j = 1}^A\\sum_{\\gamma\\delta} C_{j\\gamma}^{(0)}C_{j\\delta}^{(0)}\\langle \\alpha\\gamma|\\hat{v}|\\beta\\delta\\rangle_{AS}.\n$$\n\nSolving the Hartree-Fock eigenvalue problem yields then new eigenvectors $C_{i\\alpha}^{(1)}$ and eigenvalues\n$\\epsilon_i^{HF(1)}$. \n * With the new eigenvalues we can set up a new Hartree-Fock potential\n\n$$\n\\sum_{j = 1}^A\\sum_{\\gamma\\delta} C_{j\\gamma}^{(1)}C_{j\\delta}^{(1)}\\langle \\alpha\\gamma|\\hat{v}|\\beta\\delta\\rangle_{AS}.\n$$\n\nThe diagonalization with the new Hartree-Fock potential yields new eigenvectors and eigenvalues.\nThis process is continued till for example\n\n$$\n\\frac{\\sum_{p} |\\epsilon_i^{(n)}-\\epsilon_i^{(n-1)}|}{m} \\le \\lambda,\n$$\n\nwhere $\\lambda$ is a user prefixed quantity ($\\lambda \\sim 10^{-8}$ or smaller) and $p$ runs over all calculated single-particle\nenergies and $m$ is the number of single-particle states.\n\n\n\n## Analysis of Hartree-Fock equations and Koopman's theorem\n\nWe can rewrite the ground state energy by adding and subtracting $\\hat{u}^{HF}(x_i)$\n\n$$\nE_0^{HF} =\\langle \\Phi_0 | \\hat{H} | \\Phi_0\\rangle = \n\\sum_{i\\le F}^A \\langle i | \\hat{h}_0 +\\hat{u}^{HF}| j\\rangle+ \\frac{1}{2}\\sum_{i\\le F}^A\\sum_{j \\le F}^A\\left[\\langle ij |\\hat{v}|ij \\rangle-\\langle ij|\\hat{v}|ji\\rangle\\right]-\\sum_{i\\le F}^A \\langle i |\\hat{u}^{HF}| i\\rangle,\n$$\n\nwhich results in\n\n$$\nE_0^{HF}\n  = \\sum_{i\\le F}^A \\varepsilon_i^{HF} + \\frac{1}{2}\\sum_{i\\le F}^A\\sum_{j \\le F}^A\\left[\\langle ij |\\hat{v}|ij \\rangle-\\langle ij|\\hat{v}|ji\\rangle\\right]-\\sum_{i\\le F}^A \\langle i |\\hat{u}^{HF}| i\\rangle.\n$$\n\nOur single-particle states $ijk\\dots$ are now single-particle states obtained from the solution of the Hartree-Fock equations.\n\n\nUsing our definition of the Hartree-Fock single-particle energies we obtain then the following expression for the total ground-state energy\n\n$$\nE_0^{HF}\n  = \\sum_{i\\le F}^A \\varepsilon_i - \\frac{1}{2}\\sum_{i\\le F}^A\\sum_{j \\le F}^A\\left[\\langle ij |\\hat{v}|ij \\rangle-\\langle ij|\\hat{v}|ji\\rangle\\right].\n$$\n\nThis form will be used in our discussion of Koopman's theorem.\n\n\nWe have\n\n$$\nE[\\Phi^{\\mathrm{HF}}(N)] \n  = \\sum_{i=1}^H \\langle i | \\hat{h}_0 | i \\rangle +\n  \\frac{1}{2}\\sum_{ij=1}^N\\langle ij|\\hat{v}|ij\\rangle_{AS},\n$$\n\nwhere $\\Phi^{\\mathrm{HF}}(N)$ is the new Slater determinant defined by the new basis of Eq. [(21)](#eq:newbasis)\nfor $N$ electrons (same $Z$).  If we assume that the single-particle wave functions in the new basis do not change \nwhen we remove one electron or add one electron, we can then define the corresponding energy for the $N-1$ systems as\n\n$$\nE[\\Phi^{\\mathrm{HF}}(N-1)] \n  = \\sum_{i=1; i\\ne k}^N \\langle i | \\hat{h}_0 | i \\rangle +\n  \\frac{1}{2}\\sum_{ij=1;i,j\\ne k}^N\\langle ij|\\hat{v}|ij\\rangle_{AS},\n$$\n\nwhere we have removed a single-particle state $k\\le F$, that is a state below the Fermi level.  \n\n\nCalculating the difference\n\n$$\nE[\\Phi^{\\mathrm{HF}}(N)]-   E[\\Phi^{\\mathrm{HF}}(N-1)] = \\langle k | \\hat{h}_0 | k \\rangle +\n  \\frac{1}{2}\\sum_{i=1;i\\ne k}^N\\langle ik|\\hat{v}|ik\\rangle_{AS}  \\frac{1}{2}\\sum_{j=1;j\\ne k}^N\\langle kj|\\hat{v}|kj\\rangle_{AS},\n$$\n\nwe obtain\n\n$$\nE[\\Phi^{\\mathrm{HF}}(N)]-   E[\\Phi^{\\mathrm{HF}}(N-1)] = \\langle k | \\hat{h}_0 | k \\rangle +\n  \\frac{1}{2}\\sum_{j=1}^N\\langle kj|\\hat{v}|kj\\rangle_{AS}\n$$\n\nwhich is just our definition of the Hartree-Fock single-particle energy\n\n$$\nE[\\Phi^{\\mathrm{HF}}(N)]-   E[\\Phi^{\\mathrm{HF}}(N-1)] = \\epsilon_k^{\\mathrm{HF}}\n$$\n\nSimilarly, we can now compute the difference (we label the single-particle states above the Fermi level as $abcd > F$)\n\n$$\nE[\\Phi^{\\mathrm{HF}}(N+1)]-   E[\\Phi^{\\mathrm{HF}}(N)]= \\epsilon_a^{\\mathrm{HF}}.\n$$\n\nThese two equations can thus be used to the electron affinity or ionization energies, respectively. \nKoopman's theorem states that for example the ionization energy of a closed-shell system is given by the energy of the highest occupied single-particle state.  If we assume that changing the number of electrons from $N$ to $N+1$ does not change the Hartree-Fock single-particle energies and eigenfunctions, then Koopman's theorem simply states that the ionization energy of an atom is given by the single-particle energy of the last bound state. In a similar way, we can also define the electron affinities. \n\n\n\nAs an example, consider a simple model for atomic sodium, Na. Neutral sodium has eleven electrons, \nwith the weakest bound one being confined the $3s$ single-particle quantum numbers. The energy needed to remove an electron from neutral sodium is rather small, 5.1391 eV, a feature which pertains to all alkali metals.\nHaving performed a  Hartree-Fock calculation for neutral sodium would then allows us to compute the\nionization energy by using the single-particle energy for the $3s$ states, namely $\\epsilon_{3s}^{\\mathrm{HF}}$. \n\nFrom these considerations, we see that Hartree-Fock theory allows us to make a connection between experimental \nobservables (here ionization and affinity energies) and the underlying interactions between particles.  \nIn this sense, we are now linking the dynamics and structure of a many-body system with the laws of motion which govern the system. Our approach is a reductionistic one, meaning that we want to understand the laws of motion \nin terms of the particles or degrees of freedom which we believe are the fundamental ones. Our Slater determinant, being constructed as the product of various single-particle functions, follows this philosophy.\n\n\nWith similar arguments as in atomic physics, we can now use Hartree-Fock theory to make a link\nbetween nuclear forces and separation energies. Changing to nuclear system, we define\n\n$$\nE[\\Phi^{\\mathrm{HF}}(A)] \n  = \\sum_{i=1}^A \\langle i | \\hat{h}_0 | i \\rangle +\n  \\frac{1}{2}\\sum_{ij=1}^A\\langle ij|\\hat{v}|ij\\rangle_{AS},\n$$\n\nwhere $\\Phi^{\\mathrm{HF}}(A)$ is the new Slater determinant defined by the new basis of Eq. [(21)](#eq:newbasis)\nfor $A$ nucleons, where $A=N+Z$, with $N$ now being the number of neutrons and $Z$ th enumber of protons.  If we assume again that the single-particle wave functions in the new basis do not change from a nucleus with $A$ nucleons to a nucleus with $A-1$  nucleons, we can then define the corresponding energy for the $A-1$ systems as\n\n$$\nE[\\Phi^{\\mathrm{HF}}(A-1)] \n  = \\sum_{i=1; i\\ne k}^A \\langle i | \\hat{h}_0 | i \\rangle +\n  \\frac{1}{2}\\sum_{ij=1;i,j\\ne k}^A\\langle ij|\\hat{v}|ij\\rangle_{AS},\n$$\n\nwhere we have removed a single-particle state $k\\le F$, that is a state below the Fermi level.  \n\n\nCalculating the difference\n\n$$\nE[\\Phi^{\\mathrm{HF}}(A)]-   E[\\Phi^{\\mathrm{HF}}(A-1)] \n  = \\langle k | \\hat{h}_0 | k \\rangle +\n  \\frac{1}{2}\\sum_{i=1;i\\ne k}^A\\langle ik|\\hat{v}|ik\\rangle_{AS}  \\frac{1}{2}\\sum_{j=1;j\\ne k}^A\\langle kj|\\hat{v}|kj\\rangle_{AS},\n$$\n\nwhich becomes\n\n$$\nE[\\Phi^{\\mathrm{HF}}(A)]-   E[\\Phi^{\\mathrm{HF}}(A-1)] \n  = \\langle k | \\hat{h}_0 | k \\rangle +\n  \\frac{1}{2}\\sum_{j=1}^A\\langle kj|\\hat{v}|kj\\rangle_{AS}\n$$\n\nwhich is just our definition of the Hartree-Fock single-particle energy\n\n$$\nE[\\Phi^{\\mathrm{HF}}(A)]-   E[\\Phi^{\\mathrm{HF}}(A-1)] \n  = \\epsilon_k^{\\mathrm{HF}}\n$$\n\nSimilarly, we can now compute the difference (recall that the single-particle states $abcd > F$)\n\n$$\nE[\\Phi^{\\mathrm{HF}}(A+1)]-   E[\\Phi^{\\mathrm{HF}}(A)]= \\epsilon_a^{\\mathrm{HF}}.\n$$\n\nIf we then recall that the binding energy differences\n\n$$\nBE(A)-BE(A-1) \\hspace{0.5cm} \\mathrm{and} \\hspace{0.5cm} BE(A+1)-BE(A),\n$$\n\ndefine the separation energies, we see that the Hartree-Fock single-particle energies can be used to\ndefine separation energies. We have thus our first link between nuclear forces (included in the potential energy term) and an observable quantity defined by differences in binding energies. \n\n\nWe have thus the following interpretations (if the single-particle field do not change)\n\n$$\nBE(A)-BE(A-1)\\approx  E[\\Phi^{\\mathrm{HF}}(A)]-   E[\\Phi^{\\mathrm{HF}}(A-1)] \n  = \\epsilon_k^{\\mathrm{HF}},\n$$\n\nand\n\n$$\nBE(A+1)-BE(A)\\approx  E[\\Phi^{\\mathrm{HF}}(A+1)]-   E[\\Phi^{\\mathrm{HF}}(A)] =  \\epsilon_a^{\\mathrm{HF}}.\n$$\n\nIf  we use ${}^{16}\\mbox{O}$ as our closed-shell nucleus, we could then interpret the separation energy\n\n$$\nBE(^{16}\\mathrm{O})-BE(^{15}\\mathrm{O})\\approx \\epsilon_{0p^{\\nu}_{1/2}}^{\\mathrm{HF}},\n$$\n\nand\n\n$$\nBE(^{16}\\mathrm{O})-BE(^{15}\\mathrm{N})\\approx \\epsilon_{0p^{\\pi}_{1/2}}^{\\mathrm{HF}}.\n$$\n\nSimilalry, we could interpret\n\n$$\nBE(^{17}\\mathrm{O})-BE(^{16}\\mathrm{O})\\approx \\epsilon_{0d^{\\nu}_{5/2}}^{\\mathrm{HF}},\n$$\n\nand\n\n$$\nBE(^{17}\\mathrm{F})-BE(^{16}\\mathrm{O})\\approx\\epsilon_{0d^{\\pi}_{5/2}}^{\\mathrm{HF}}.\n$$\n\nWe can continue like this for all $A\\pm 1$ nuclei where $A$ is a good closed-shell (or subshell closure)\nnucleus. Examples are ${}^{22}\\mbox{O}$, ${}^{24}\\mbox{O}$, ${}^{40}\\mbox{Ca}$, ${}^{48}\\mbox{Ca}$, ${}^{52}\\mbox{Ca}$, ${}^{54}\\mbox{Ca}$, ${}^{56}\\mbox{Ni}$, \n${}^{68}\\mbox{Ni}$, ${}^{78}\\mbox{Ni}$, ${}^{90}\\mbox{Zr}$, ${}^{88}\\mbox{Sr}$, ${}^{100}\\mbox{Sn}$, ${}^{132}\\mbox{Sn}$ and ${}^{208}\\mbox{Pb}$, to mention some possile cases.\n\n\nWe can thus make our first interpretation of the separation energies in terms of the simplest\npossible many-body theory. \nIf we also recall that the so-called energy gap for neutrons (or protons) is defined as\n\n$$\n\\Delta S_n= 2BE(N,Z)-BE(N-1,Z)-BE(N+1,Z),\n$$\n\nfor neutrons and the corresponding gap for protons\n\n$$\n\\Delta S_p= 2BE(N,Z)-BE(N,Z-1)-BE(N,Z+1),\n$$\n\nwe can define the neutron and proton energy gaps for ${}^{16}\\mbox{O}$ as\n\n$$\n\\Delta S_{\\nu}=\\epsilon_{0d^{\\nu}_{5/2}}^{\\mathrm{HF}}-\\epsilon_{0p^{\\nu}_{1/2}}^{\\mathrm{HF}},\n$$\n\nand\n\n$$\n\\Delta S_{\\pi}=\\epsilon_{0d^{\\pi}_{5/2}}^{\\mathrm{HF}}-\\epsilon_{0p^{\\pi}_{1/2}}^{\\mathrm{HF}}.\n$$\n\n<!-- --- begin exercise --- -->\n\n### Exercise 5: Derivation of Hartree-Fock equations\n\nConsider a Slater determinant built up of single-particle orbitals $\\psi_{\\lambda}$, \nwith $\\lambda = 1,2,\\dots,N$.\n\nThe unitary transformation\n\n$$\n\\psi_a  = \\sum_{\\lambda} C_{a\\lambda}\\phi_{\\lambda},\n$$\n\nbrings us into the new basis.  \nThe new basis has quantum numbers $a=1,2,\\dots,N$.\n\n\n**a)**\nShow that the new basis is orthonormal.\n\n**b)**\nShow that the new Slater determinant constructed from the new single-particle wave functions can be\nwritten as the determinant based on the previous basis and the determinant of the matrix $C$.\n\n**c)**\nShow that the old and the new Slater determinants are equal up to a complex constant with absolute value unity.\n\n<!-- --- begin hint in exercise --- -->\n\n**Hint.**\nHint, $C$ is a unitary matrix.\n\n<!-- --- end hint in exercise --- -->\n\n\n\n<!-- --- end exercise --- -->\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 6: Derivation of Hartree-Fock equations\n\nConsider the  Slater  determinant\n\n$$\n\\Phi_{0}=\\frac{1}{\\sqrt{n!}}\\sum_{p}(-)^{p}P\n\\prod_{i=1}^{n}\\psi_{\\alpha_{i}}(x_{i}).\n$$\n\nA small variation in this function is given by\n\n$$\n\\delta\\Phi_{0}=\\frac{1}{\\sqrt{n!}}\\sum_{p}(-)^{p}P\n\\psi_{\\alpha_{1}}(x_{1})\\psi_{\\alpha_{2}}(x_{2})\\dots\n\\psi_{\\alpha_{i-1}}(x_{i-1})(\\delta\\psi_{\\alpha_{i}}(x_{i}))\n\\psi_{\\alpha_{i+1}}(x_{i+1})\\dots\\psi_{\\alpha_{n}}(x_{n}).\n$$\n\n**a)**\nShow that\n\n$$\n\\langle \\delta\\Phi_{0}|\\sum_{i=1}^{n}\\left\\{t(x_{i})+u(x_{i})\n\\right\\}+\\frac{1}{2}\n\\sum_{i\\neq j=1}^{n}v(x_{i},x_{j})|\\Phi_{0}\\rangle  =\\sum_{i=1}^{n}\\langle \\delta\\psi_{\\alpha_{i}}|\\hat{t}+\\hat{u}\n|\\phi_{\\alpha_{i}}\\rangle\n$$\n\n$$\n+\\sum_{i\\neq j=1}^{n}\\left\\{\\langle\\delta\\psi_{\\alpha_{i}}\n\\psi_{\\alpha_{j}}|\\hat{v}|\\psi_{\\alpha_{i}}\\psi_{\\alpha_{j}}\\rangle-\n\\langle\\delta\\psi_{\\alpha_{i}}\\psi_{\\alpha_{j}}|\\hat{v}\n|\\psi_{\\alpha_{j}}\\psi_{\\alpha_{i}}\\rangle\\right\\}\n$$\n\n<!-- --- end exercise --- -->\n\n\n# Second quantization\n<div id=\"ch:squant\"></div>\n\n\n## Second quantization\n* Second quantization and operators, two-body operator with examples \n\n* Wick's theorem (missing in html and ipython notebook but in pdf files)\n\n* Thouless' theorem and analysis of the Hartree-Fock equations using second quantization\n\n* Examples on how to use bit representations for Slater determinants\n\n* TO DO: add material about Wick's theorem and diagrammatic representation\n\n* TO DO: Link determinantal analysis with Thouless' theorem\n\nWe introduce the time-independent  operators\n$a_\\alpha^{\\dagger}$ and $a_\\alpha$   which create and annihilate, respectively, a particle \nin the single-particle state \n$\\varphi_\\alpha$. \nWe define the fermion creation operator\n$a_\\alpha^{\\dagger}$\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-1a\"></div>\n\n$$\n\\begin{equation}\n\ta_\\alpha^{\\dagger}|0\\rangle \\equiv  |\\alpha\\rangle  \\label{eq:2-1a} \\tag{25},\n\\end{equation}\n$$\n\nand\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-1b\"></div>\n\n$$\n\\begin{equation}\n\ta_\\alpha^{\\dagger}|\\alpha_1\\dots \\alpha_n\\rangle_{\\mathrm{AS}} \\equiv  |\\alpha\\alpha_1\\dots \\alpha_n\\rangle_{\\mathrm{AS}} \\label{eq:2-1b} \\tag{26}\n\\end{equation}\n$$\n\nIn Eq. [(25)](#eq:2-1a) \nthe operator  $a_\\alpha^{\\dagger}$  acts on the vacuum state \n$|0\\rangle$, which does not contain any particles. Alternatively, we could define  a closed-shell nucleus or atom as our new vacuum, but then\nwe need to introduce the particle-hole  formalism, see the discussion to come. \n\nIn Eq. [(26)](#eq:2-1b) $a_\\alpha^{\\dagger}$ acts on an antisymmetric $n$-particle state and \ncreates an antisymmetric $(n+1)$-particle state, where the one-body state \n$\\varphi_\\alpha$ is occupied, under the condition that\n$\\alpha \\ne \\alpha_1, \\alpha_2, \\dots, \\alpha_n$. \nIt follows that we can express an antisymmetric state as the product of the creation\noperators acting on the vacuum state.\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-2\"></div>\n\n$$\n\\begin{equation}\n\t|\\alpha_1\\dots \\alpha_n\\rangle_{\\mathrm{AS}} = a_{\\alpha_1}^{\\dagger} a_{\\alpha_2}^{\\dagger} \\dots a_{\\alpha_n}^{\\dagger} |0\\rangle \\label{eq:2-2} \\tag{27}\n\\end{equation}\n$$\n\nIt is easy to derive the commutation and anticommutation rules  for the fermionic creation operators \n$a_\\alpha^{\\dagger}$. Using the antisymmetry of the states \n[(27)](#eq:2-2)\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-3a\"></div>\n\n$$\n\\begin{equation}\n\t|\\alpha_1\\dots \\alpha_i\\dots \\alpha_k\\dots \\alpha_n\\rangle_{\\mathrm{AS}} = \n\t\t- |\\alpha_1\\dots \\alpha_k\\dots \\alpha_i\\dots \\alpha_n\\rangle_{\\mathrm{AS}} \\label{eq:2-3a} \\tag{28}\n\\end{equation}\n$$\n\nwe obtain\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-3b\"></div>\n\n$$\n\\begin{equation}\n\t a_{\\alpha_i}^{\\dagger}  a_{\\alpha_k}^{\\dagger} = - a_{\\alpha_k}^{\\dagger} a_{\\alpha_i}^{\\dagger} \\label{eq:2-3b} \\tag{29}\n\\end{equation}\n$$\n\nUsing the Pauli principle\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-4a\"></div>\n\n$$\n\\begin{equation}\n\t|\\alpha_1\\dots \\alpha_i\\dots \\alpha_i\\dots \\alpha_n\\rangle_{\\mathrm{AS}} = 0 \\label{eq:2-4a} \\tag{30}\n\\end{equation}\n$$\n\nit follows that\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-4b\"></div>\n\n$$\n\\begin{equation}\n\ta_{\\alpha_i}^{\\dagger}  a_{\\alpha_i}^{\\dagger} = 0. \\label{eq:2-4b} \\tag{31}\n\\end{equation}\n$$\n\nIf we combine Eqs. [(29)](#eq:2-3b) and [(31)](#eq:2-4b), we obtain the well-known anti-commutation rule\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-5\"></div>\n\n$$\n\\begin{equation}\n\ta_{\\alpha}^{\\dagger}  a_{\\beta}^{\\dagger} + a_{\\beta}^{\\dagger}  a_{\\alpha}^{\\dagger} \\equiv \n\t\t\\{a_{\\alpha}^{\\dagger},a_{\\beta}^{\\dagger}\\} = 0 \\label{eq:2-5} \\tag{32}\n\\end{equation}\n$$\n\nThe hermitian conjugate  of $a_\\alpha^{\\dagger}$ is\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-6\"></div>\n\n$$\n\\begin{equation}\n\ta_{\\alpha} = ( a_{\\alpha}^{\\dagger} )^{\\dagger} \\label{eq:2-6} \\tag{33}\n\\end{equation}\n$$\n\nIf we take the hermitian conjugate of Eq. [(32)](#eq:2-5), we arrive at\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-7\"></div>\n\n$$\n\\begin{equation}\n\t\\{a_{\\alpha},a_{\\beta}\\} = 0 \\label{eq:2-7} \\tag{34}\n\\end{equation}\n$$\n\nWhat is the physical interpretation of the operator $a_\\alpha$ and what is the effect of \n$a_\\alpha$ on a given state $|\\alpha_1\\alpha_2\\dots\\alpha_n\\rangle_{\\mathrm{AS}}$? \nConsider the following matrix element\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-8\"></div>\n\n$$\n\\begin{equation}\n\t\\langle\\alpha_1\\alpha_2 \\dots \\alpha_n|a_\\alpha|\\alpha_1'\\alpha_2' \\dots \\alpha_m'\\rangle \\label{eq:2-8} \\tag{35}\n\\end{equation}\n$$\n\nwhere both sides are antisymmetric. We  distinguish between two cases. The first (1) is when\n$\\alpha \\in \\{\\alpha_i\\}$. Using the Pauli principle of Eq. [(30)](#eq:2-4a) it follows\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-9a\"></div>\n\n$$\n\\begin{equation}\n\t\t\\langle\\alpha_1\\alpha_2 \\dots \\alpha_n|a_\\alpha = 0 \\label{eq:2-9a} \\tag{36}\n\\end{equation}\n$$\n\nThe second (2) case is when $\\alpha \\notin \\{\\alpha_i\\}$. It follows that an hermitian conjugation\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-9b\"></div>\n\n$$\n\\begin{equation}\n\t\t\\langle \\alpha_1\\alpha_2 \\dots \\alpha_n|a_\\alpha = \\langle\\alpha\\alpha_1\\alpha_2 \\dots \\alpha_n|  \\label{eq:2-9b} \\tag{37}\n\\end{equation}\n$$\n\nEq. [(37)](#eq:2-9b) holds for case (1) since the lefthand side is zero due to the Pauli principle. We write\nEq. [(35)](#eq:2-8) as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-10\"></div>\n\n$$\n\\begin{equation}\n\t\\langle\\alpha_1\\alpha_2 \\dots \\alpha_n|a_\\alpha|\\alpha_1'\\alpha_2' \\dots \\alpha_m'\\rangle = \n\t\\langle \\alpha_1\\alpha_2 \\dots \\alpha_n|\\alpha\\alpha_1'\\alpha_2' \\dots \\alpha_m'\\rangle \\label{eq:2-10} \\tag{38}\n\\end{equation}\n$$\n\nHere we must have $m = n+1$ if Eq. [(38)](#eq:2-10) has to be trivially different from zero.\n\n\n\nFor the last case, the minus and plus signs apply when the sequence \n$\\alpha ,\\alpha_1, \\alpha_2, \\dots, \\alpha_n$ and \n$\\alpha_1', \\alpha_2', \\dots, \\alpha_{n+1}'$ are related to each other via even and odd permutations.\nIf we assume that  $\\alpha \\notin \\{\\alpha_i\\}$ we obtain\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-12\"></div>\n\n$$\n\\begin{equation}\n\t\\langle\\alpha_1\\alpha_2 \\dots \\alpha_n|a_\\alpha|\\alpha_1'\\alpha_2' \\dots \\alpha_{n+1}'\\rangle = 0 \\label{eq:2-12} \\tag{39}\n\\end{equation}\n$$\n\nwhen $\\alpha \\in \\{\\alpha_i'\\}$. If $\\alpha \\notin \\{\\alpha_i'\\}$, we obtain\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-13a\"></div>\n\n$$\n\\begin{equation}\n\ta_\\alpha\\underbrace{|\\alpha_1'\\alpha_2' \\dots \\alpha_{n+1}'}\\rangle_{\\neq \\alpha} = 0 \\label{eq:2-13a} \\tag{40}\n\\end{equation}\n$$\n\nand in particular\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-13b\"></div>\n\n$$\n\\begin{equation}\n\ta_\\alpha |0\\rangle = 0 \\label{eq:2-13b} \\tag{41}\n\\end{equation}\n$$\n\nIf $\\{\\alpha\\alpha_i\\} = \\{\\alpha_i'\\}$, performing the right permutations, the sequence\n$\\alpha ,\\alpha_1, \\alpha_2, \\dots, \\alpha_n$ is identical with the sequence\n$\\alpha_1', \\alpha_2', \\dots, \\alpha_{n+1}'$. This results in\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-14\"></div>\n\n$$\n\\begin{equation}\n\t\\langle\\alpha_1\\alpha_2 \\dots \\alpha_n|a_\\alpha|\\alpha\\alpha_1\\alpha_2 \\dots \\alpha_{n}\\rangle = 1 \\label{eq:2-14} \\tag{42}\n\\end{equation}\n$$\n\nand thus\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-15\"></div>\n\n$$\n\\begin{equation}\n\ta_\\alpha |\\alpha\\alpha_1\\alpha_2 \\dots \\alpha_{n}\\rangle = |\\alpha_1\\alpha_2 \\dots \\alpha_{n}\\rangle \\label{eq:2-15} \\tag{43}\n\\end{equation}\n$$\n\nThe action of the operator \n$a_\\alpha$ from the left on a state vector  is to to remove  one particle in the state\n$\\alpha$. \nIf the state vector does not contain the single-particle state $\\alpha$, the outcome of the operation is zero.\nThe operator  $a_\\alpha$ is normally called for a destruction or annihilation operator.\n\nThe next step is to establish the  commutator algebra of $a_\\alpha^{\\dagger}$ and\n$a_\\beta$. \n\n\n\nThe action of the anti-commutator \n$\\{a_\\alpha^{\\dagger}$,$a_\\alpha\\}$ on a given $n$-particle state is\n\n$$\n\\begin{equation}\n\ta_\\alpha^{\\dagger} a_\\alpha \\underbrace{|\\alpha_1\\alpha_2 \\dots \\alpha_{n}\\rangle}_{\\neq \\alpha} = 0 \\nonumber \n\\end{equation}\n$$\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-16a\"></div>\n\n$$\n\\begin{equation} \n\ta_\\alpha a_\\alpha^{\\dagger} \\underbrace{|\\alpha_1\\alpha_2 \\dots \\alpha_{n}\\rangle}_{\\neq \\alpha} =\n\ta_\\alpha \\underbrace{|\\alpha \\alpha_1\\alpha_2 \\dots \\alpha_{n}\\rangle}_{\\neq \\alpha} = \n\t\\underbrace{|\\alpha_1\\alpha_2 \\dots \\alpha_{n}\\rangle}_{\\neq \\alpha} \\label{eq:2-16a} \\tag{44}\n\\end{equation}\n$$\n\nif the single-particle state $\\alpha$ is not contained in the state.\n\n\n\n\n If it is present\nwe arrive at\n\n$$\n\\begin{equation}\n\ta_\\alpha^{\\dagger} a_\\alpha |\\alpha_1\\alpha_2 \\dots \\alpha_{k}\\alpha \\alpha_{k+1} \\dots \\alpha_{n-1}\\rangle =\n\ta_\\alpha^{\\dagger} a_\\alpha (-1)^k |\\alpha \\alpha_1\\alpha_2 \\dots \\alpha_{n-1}\\rangle \\nonumber \n\\end{equation}\n$$\n\n$$\n\\begin{equation} \n\t= (-1)^k |\\alpha \\alpha_1\\alpha_2 \\dots \\alpha_{n-1}\\rangle =\n\t|\\alpha_1\\alpha_2 \\dots \\alpha_{k}\\alpha \\alpha_{k+1} \\dots \\alpha_{n-1}\\rangle \\nonumber \n\\end{equation}\n$$\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-16b\"></div>\n\n$$\n\\begin{equation} \n\ta_\\alpha a_\\alpha^{\\dagger}|\\alpha_1\\alpha_2 \\dots \\alpha_{k}\\alpha \\alpha_{k+1} \\dots \\alpha_{n-1}\\rangle = 0 \\label{eq:2-16b} \\tag{45}\n\\end{equation}\n$$\n\nFrom Eqs. [(44)](#eq:2-16a) and  [(45)](#eq:2-16b) we arrive at\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-17\"></div>\n\n$$\n\\begin{equation}\n\t\\{a_\\alpha^{\\dagger} , a_\\alpha \\} = a_\\alpha^{\\dagger} a_\\alpha + a_\\alpha a_\\alpha^{\\dagger} = 1 \\label{eq:2-17} \\tag{46}\n\\end{equation}\n$$\n\nThe action of $\\left\\{a_\\alpha^{\\dagger}, a_\\beta\\right\\}$, with \n$\\alpha \\ne \\beta$ on a given state yields three possibilities. \nThe first case is a state vector which contains both $\\alpha$ and $\\beta$, then either \n$\\alpha$ or $\\beta$ and finally none of them.\n\n\n\nThe first case results in\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-18a\"></div>\n\n$$\n\\begin{eqnarray}\n\ta_\\alpha^{\\dagger} a_\\beta |\\alpha\\beta\\alpha_1\\alpha_2 \\dots \\alpha_{n-2}\\rangle = 0 \\nonumber \\\\\n\ta_\\beta a_\\alpha^{\\dagger} |\\alpha\\beta\\alpha_1\\alpha_2 \\dots \\alpha_{n-2}\\rangle = 0 \\label{eq:2-18a} \\tag{47}\n\\end{eqnarray}\n$$\n\nwhile the second case gives\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-18b\"></div>\n\n$$\n\\begin{eqnarray}\n\t a_\\alpha^{\\dagger} a_\\beta |\\beta \\underbrace{\\alpha_1\\alpha_2 \\dots \\alpha_{n-1}}_{\\neq \\alpha}\\rangle &=& \n\t \t|\\alpha \\underbrace{\\alpha_1\\alpha_2 \\dots \\alpha_{n-1}}_{\\neq  \\alpha}\\rangle \\nonumber \\\\\n\ta_\\beta a_\\alpha^{\\dagger} |\\beta \\underbrace{\\alpha_1\\alpha_2 \\dots \\alpha_{n-1}}_{\\neq \\alpha}\\rangle &=&\n\t\ta_\\beta |\\alpha\\beta\\underbrace{\\beta \\alpha_1\\alpha_2 \\dots \\alpha_{n-1}}_{\\neq \\alpha}\\rangle \\nonumber \\\\\n\t&=& - |\\alpha\\underbrace{\\alpha_1\\alpha_2 \\dots \\alpha_{n-1}}_{\\neq \\alpha}\\rangle \\label{eq:2-18b} \\tag{48}\n\\end{eqnarray}\n$$\n\nFinally if the state vector does not contain $\\alpha$ and $\\beta$\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-18c\"></div>\n\n$$\n\\begin{eqnarray}\n\ta_\\alpha^{\\dagger} a_\\beta |\\underbrace{\\alpha_1\\alpha_2 \\dots \\alpha_{n}}_{\\neq \\alpha,\\beta}\\rangle &=& 0 \\nonumber \\\\\n\ta_\\beta a_\\alpha^{\\dagger} |\\underbrace{\\alpha_1\\alpha_2 \\dots \\alpha_{n}}_{\\neq \\alpha,\\beta}\\rangle &=& \n\t\ta_\\beta |\\alpha \\underbrace{\\alpha_1\\alpha_2 \\dots \\alpha_{n}}_{\\neq \\alpha,\\beta}\\rangle = 0 \\label{eq:2-18c} \\tag{49}\n\\end{eqnarray}\n$$\n\nFor all three cases we have\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-19\"></div>\n\n$$\n\\begin{equation}\n\t\\{a_\\alpha^{\\dagger},a_\\beta \\} = a_\\alpha^{\\dagger} a_\\beta + a_\\beta a_\\alpha^{\\dagger} = 0, \\quad \\alpha \\neq \\beta \\label{eq:2-19} \\tag{50}\n\\end{equation}\n$$\n\nWe can summarize  our findings in Eqs. [(46)](#eq:2-17) and [(50)](#eq:2-19) as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-20\"></div>\n\n$$\n\\begin{equation}\n\t\\{a_\\alpha^{\\dagger},a_\\beta \\} = \\delta_{\\alpha\\beta} \\label{eq:2-20} \\tag{51}\n\\end{equation}\n$$\n\nwith  $\\delta_{\\alpha\\beta}$ is the Kroenecker $\\delta$-symbol.\n\nThe properties of the creation and annihilation operators can be summarized as (for fermions)\n\n$$\na_\\alpha^{\\dagger}|0\\rangle \\equiv  |\\alpha\\rangle,\n$$\n\nand\n\n$$\na_\\alpha^{\\dagger}|\\alpha_1\\dots \\alpha_n\\rangle_{\\mathrm{AS}} \\equiv  |\\alpha\\alpha_1\\dots \\alpha_n\\rangle_{\\mathrm{AS}}.\n$$\n\nfrom which follows\n\n$$\n|\\alpha_1\\dots \\alpha_n\\rangle_{\\mathrm{AS}} = a_{\\alpha_1}^{\\dagger} a_{\\alpha_2}^{\\dagger} \\dots a_{\\alpha_n}^{\\dagger} |0\\rangle.\n$$\n\nThe hermitian conjugate has the folowing properties\n\n$$\na_{\\alpha} = ( a_{\\alpha}^{\\dagger} )^{\\dagger}.\n$$\n\nFinally we found\n\n$$\na_\\alpha\\underbrace{|\\alpha_1'\\alpha_2' \\dots \\alpha_{n+1}'}\\rangle_{\\neq \\alpha} = 0, \\quad\n\t\t\\textrm{in particular } a_\\alpha |0\\rangle = 0,\n$$\n\nand\n\n$$\na_\\alpha |\\alpha\\alpha_1\\alpha_2 \\dots \\alpha_{n}\\rangle = |\\alpha_1\\alpha_2 \\dots \\alpha_{n}\\rangle,\n$$\n\nand the corresponding commutator algebra\n\n$$\n\\{a_{\\alpha}^{\\dagger},a_{\\beta}^{\\dagger}\\} = \\{a_{\\alpha},a_{\\beta}\\} = 0 \\hspace{0.5cm} \n\\{a_\\alpha^{\\dagger},a_\\beta \\} = \\delta_{\\alpha\\beta}.\n$$\n\n## One-body operators in second quantization\n\nA very useful operator is the so-called number-operator.  Most physics cases  we will\nstudy in this text conserve the total number of particles.  The number operator is therefore\na useful quantity which allows us to test that our many-body formalism  conserves the number of particles.\nIn for example $(d,p)$ or $(p,d)$ reactions it is important to be able to describe quantum mechanical states\nwhere particles get added or removed.\nA creation operator $a_\\alpha^{\\dagger}$ adds one particle to the single-particle state\n$\\alpha$ of a give many-body state vector, while an annihilation operator $a_\\alpha$ \nremoves a particle from a single-particle\nstate $\\alpha$. \n\n\n\n\n\nLet us consider an operator proportional with $a_\\alpha^{\\dagger} a_\\beta$ and \n$\\alpha=\\beta$. It acts on an $n$-particle state \nresulting in\n\n$$\n\\begin{equation}\n\ta_\\alpha^{\\dagger} a_\\alpha |\\alpha_1\\alpha_2 \\dots \\alpha_{n}\\rangle = \n\t\\begin{cases}\n\t\t0  &\\alpha \\notin \\{\\alpha_i\\} \\\\\n\t\t\\\\\n\t\t|\\alpha_1\\alpha_2 \\dots \\alpha_{n}\\rangle & \\alpha \\in \\{\\alpha_i\\}\n\t\\end{cases}\n\\end{equation}\n$$\n\nSumming over all possible one-particle states we arrive at\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-21\"></div>\n\n$$\n\\begin{equation}\n\t\\left( \\sum_\\alpha a_\\alpha^{\\dagger} a_\\alpha \\right) |\\alpha_1\\alpha_2 \\dots \\alpha_{n}\\rangle = \n\tn |\\alpha_1\\alpha_2 \\dots \\alpha_{n}\\rangle \\label{eq:2-21} \\tag{52}\n\\end{equation}\n$$\n\nThe operator\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-22\"></div>\n\n$$\n\\begin{equation}\n\t\\hat{N} = \\sum_\\alpha a_\\alpha^{\\dagger} a_\\alpha \\label{eq:2-22} \\tag{53}\n\\end{equation}\n$$\n\nis called the number operator since it counts the number of particles in a give state vector when it acts \non the different single-particle states.  It acts on one single-particle state at the time and falls \ntherefore under category one-body operators.\nNext we look at another important one-body operator, namely $\\hat{H}_0$ and study its operator form in the \noccupation number representation.\n\n\n\n\nWe want to obtain an expression for a one-body operator which conserves the number of particles.\nHere we study the one-body operator for the kinetic energy plus an eventual external one-body potential.\nThe action of this operator on a particular $n$-body state with its pertinent expectation value has already\nbeen studied in coordinate  space.\nIn coordinate space the operator reads\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-23\"></div>\n\n$$\n\\begin{equation}\n\t\\hat{H}_0 = \\sum_i \\hat{h}_0(x_i) \\label{eq:2-23} \\tag{54}\n\\end{equation}\n$$\n\nand the anti-symmetric $n$-particle Slater determinant is defined as\n\n$$\n\\Phi(x_1, x_2,\\dots ,x_n,\\alpha_1,\\alpha_2,\\dots, \\alpha_n)= \\frac{1}{\\sqrt{n!}} \\sum_p (-1)^p\\hat{P}\\psi_{\\alpha_1}(x_1)\\psi_{\\alpha_2}(x_2) \\dots \\psi_{\\alpha_n}(x_n).\n$$\n\nDefining\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-25\"></div>\n\n$$\n\\begin{equation}\n\t\\hat{h}_0(x_i) \\psi_{\\alpha_i}(x_i) = \\sum_{\\alpha_k'} \\psi_{\\alpha_k'}(x_i) \\langle\\alpha_k'|\\hat{h}_0|\\alpha_k\\rangle \\label{eq:2-25} \\tag{55}\n\\end{equation}\n$$\n\nwe can easily  evaluate the action of $\\hat{H}_0$ on each product of one-particle functions in Slater determinant.\nFrom Eq. [(55)](#eq:2-25)  we obtain the following result without  permuting any particle pair\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-26\"></div>\n\n$$\n\\begin{eqnarray}\n\t&& \\left( \\sum_i \\hat{h}_0(x_i) \\right) \\psi_{\\alpha_1}(x_1)\\psi_{\\alpha_2}(x_2) \\dots \\psi_{\\alpha_n}(x_n) \\nonumber \\\\\n\t& =&\\sum_{\\alpha_1'} \\langle \\alpha_1'|\\hat{h}_0|\\alpha_1\\rangle \n\t\t\\psi_{\\alpha_1'}(x_1)\\psi_{\\alpha_2}(x_2) \\dots \\psi_{\\alpha_n}(x_n) \\nonumber \\\\\n\t&+&\\sum_{\\alpha_2'} \\langle \\alpha_2'|\\hat{h}_0|\\alpha_2\\rangle\n\t\t\\psi_{\\alpha_1}(x_1)\\psi_{\\alpha_2'}(x_2) \\dots \\psi_{\\alpha_n}(x_n) \\nonumber \\\\\n\t&+& \\dots \\nonumber \\\\\n\t&+&\\sum_{\\alpha_n'} \\langle \\alpha_n'|\\hat{h}_0|\\alpha_n\\rangle\n\t\t\\psi_{\\alpha_1}(x_1)\\psi_{\\alpha_2}(x_2) \\dots \\psi_{\\alpha_n'}(x_n) \\label{eq:2-26} \\tag{56}\n\\end{eqnarray}\n$$\n\nIf we interchange particles $1$ and $2$  we obtain\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-27\"></div>\n\n$$\n\\begin{eqnarray}\n\t&& \\left( \\sum_i \\hat{h}_0(x_i) \\right) \\psi_{\\alpha_1}(x_2)\\psi_{\\alpha_1}(x_2) \\dots \\psi_{\\alpha_n}(x_n) \\nonumber \\\\\n\t& =&\\sum_{\\alpha_2'} \\langle \\alpha_2'|\\hat{h}_0|\\alpha_2\\rangle \n\t\t\\psi_{\\alpha_1}(x_2)\\psi_{\\alpha_2'}(x_1) \\dots \\psi_{\\alpha_n}(x_n) \\nonumber \\\\\n\t&+&\\sum_{\\alpha_1'} \\langle \\alpha_1'|\\hat{h}_0|\\alpha_1\\rangle\n\t\t\\psi_{\\alpha_1'}(x_2)\\psi_{\\alpha_2}(x_1) \\dots \\psi_{\\alpha_n}(x_n) \\nonumber \\\\\n\t&+& \\dots \\nonumber \\\\\n\t&+&\\sum_{\\alpha_n'} \\langle \\alpha_n'|\\hat{h}_0|\\alpha_n\\rangle\n\t\t\\psi_{\\alpha_1}(x_2)\\psi_{\\alpha_1}(x_2) \\dots \\psi_{\\alpha_n'}(x_n) \\label{eq:2-27} \\tag{57}\n\\end{eqnarray}\n$$\n\nWe can continue by computing all possible permutations. \nWe rewrite also our Slater determinant in its second quantized form and skip the dependence on the quantum numbers $x_i.$\nSumming up all contributions and taking care of all phases\n$(-1)^p$ we arrive at\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-28\"></div>\n\n$$\n\\begin{eqnarray}\n\t\\hat{H}_0|\\alpha_1,\\alpha_2,\\dots, \\alpha_n\\rangle &=& \\sum_{\\alpha_1'}\\langle \\alpha_1'|\\hat{h}_0|\\alpha_1\\rangle\n\t\t|\\alpha_1'\\alpha_2 \\dots \\alpha_{n}\\rangle \\nonumber \\\\\n\t&+& \\sum_{\\alpha_2'} \\langle \\alpha_2'|\\hat{h}_0|\\alpha_2\\rangle\n\t\t|\\alpha_1\\alpha_2' \\dots \\alpha_{n}\\rangle \\nonumber \\\\\n\t&+& \\dots \\nonumber \\\\\n\t&+& \\sum_{\\alpha_n'} \\langle \\alpha_n'|\\hat{h}_0|\\alpha_n\\rangle\n\t\t|\\alpha_1\\alpha_2 \\dots \\alpha_{n}'\\rangle \\label{eq:2-28} \\tag{58}\n\\end{eqnarray}\n$$\n\nIn Eq. [(58)](#eq:2-28) \nwe have expressed the action of the one-body operator\nof Eq. [(54)](#eq:2-23) on the  $n$-body state in its second quantized form.\nThis equation can be further manipulated if we use the properties of the creation and annihilation operator\non each primed quantum number, that is\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-29\"></div>\n\n$$\n\\begin{equation}\n\t|\\alpha_1\\alpha_2 \\dots \\alpha_k' \\dots \\alpha_{n}\\rangle = \n\t\ta_{\\alpha_k'}^{\\dagger}  a_{\\alpha_k} |\\alpha_1\\alpha_2 \\dots \\alpha_k \\dots \\alpha_{n}\\rangle \\label{eq:2-29} \\tag{59}\n\\end{equation}\n$$\n\nInserting this in the right-hand side of Eq. [(58)](#eq:2-28) results in\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-30a\"></div>\n\n$$\n\\begin{eqnarray}\n\t\\hat{H}_0|\\alpha_1\\alpha_2 \\dots \\alpha_{n}\\rangle &=& \\sum_{\\alpha_1'}\\langle \\alpha_1'|\\hat{h}_0|\\alpha_1\\rangle\n\t\ta_{\\alpha_1'}^{\\dagger}  a_{\\alpha_1} |\\alpha_1\\alpha_2 \\dots \\alpha_{n}\\rangle \\nonumber \\\\\n\t&+& \\sum_{\\alpha_2'} \\langle \\alpha_2'|\\hat{h}_0|\\alpha_2\\rangle\n\t\ta_{\\alpha_2'}^{\\dagger}  a_{\\alpha_2} |\\alpha_1\\alpha_2 \\dots \\alpha_{n}\\rangle \\nonumber \\\\\n\t&+& \\dots \\nonumber \\\\\n\t&+& \\sum_{\\alpha_n'} \\langle \\alpha_n'|\\hat{h}_0|\\alpha_n\\rangle\n\t\ta_{\\alpha_n'}^{\\dagger}  a_{\\alpha_n} |\\alpha_1\\alpha_2 \\dots \\alpha_{n}\\rangle \\nonumber \\\\\n\t&=& \\sum_{\\alpha, \\beta} \\langle \\alpha|\\hat{h}_0|\\beta\\rangle a_\\alpha^{\\dagger} a_\\beta \n\t\t|\\alpha_1\\alpha_2 \\dots \\alpha_{n}\\rangle \\label{eq:2-30a} \\tag{60}\n\\end{eqnarray}\n$$\n\nIn the number occupation representation or second quantization we get the following expression for a one-body \noperator which conserves the number of particles\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-30b\"></div>\n\n$$\n\\begin{equation}\n\t\\hat{H}_0 = \\sum_{\\alpha\\beta} \\langle \\alpha|\\hat{h}_0|\\beta\\rangle a_\\alpha^{\\dagger} a_\\beta \\label{eq:2-30b} \\tag{61}\n\\end{equation}\n$$\n\nObviously, $\\hat{H}_0$ can be replaced by any other one-body  operator which preserved the number\nof particles. The stucture of the operator is therefore not limited to say the kinetic or single-particle energy only.\n\nThe opearator $\\hat{H}_0$ takes a particle from the single-particle state $\\beta$  to the single-particle state $\\alpha$ \nwith a probability for the transition given by the expectation value $\\langle \\alpha|\\hat{h}_0|\\beta\\rangle$.\n\n\n\n\n\nIt is instructive to verify Eq. [(61)](#eq:2-30b) by computing the expectation value of $\\hat{H}_0$ \nbetween two single-particle states\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-30c\"></div>\n\n$$\n\\begin{equation}\n\t\\langle \\alpha_1|\\hat{h}_0|\\alpha_2\\rangle = \\sum_{\\alpha\\beta} \\langle \\alpha|\\hat{h}_0|\\beta\\rangle\n\t\t\\langle 0|a_{\\alpha_1}a_\\alpha^{\\dagger} a_\\beta a_{\\alpha_2}^{\\dagger}|0\\rangle \\label{eq:2-30c} \\tag{62}\n\\end{equation}\n$$\n\nUsing the commutation relations for the creation and annihilation operators we have\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-30d\"></div>\n\n$$\n\\begin{equation}\na_{\\alpha_1}a_\\alpha^{\\dagger} a_\\beta a_{\\alpha_2}^{\\dagger} = (\\delta_{\\alpha \\alpha_1} - a_\\alpha^{\\dagger} a_{\\alpha_1} )(\\delta_{\\beta \\alpha_2} - a_{\\alpha_2}^{\\dagger} a_{\\beta} ), \\label{eq:2-30d} \\tag{63}\n\\end{equation}\n$$\n\nwhich results in\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-30e\"></div>\n\n$$\n\\begin{equation}\n\\langle 0|a_{\\alpha_1}a_\\alpha^{\\dagger} a_\\beta a_{\\alpha_2}^{\\dagger}|0\\rangle = \\delta_{\\alpha \\alpha_1} \\delta_{\\beta \\alpha_2} \\label{eq:2-30e} \\tag{64}\n\\end{equation}\n$$\n\nand\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-30f\"></div>\n\n$$\n\\begin{equation}\n\\langle \\alpha_1|\\hat{h}_0|\\alpha_2\\rangle = \\sum_{\\alpha\\beta} \\langle \\alpha|\\hat{h}_0|\\beta\\rangle\\delta_{\\alpha \\alpha_1} \\delta_{\\beta \\alpha_2} = \\langle \\alpha_1|\\hat{h}_0|\\alpha_2\\rangle \\label{eq:2-30f} \\tag{65}\n\\end{equation}\n$$\n\n## Two-body operators in second quantization\n\nLet us now derive the expression for our two-body interaction part, which also conserves the number of particles.\nWe can proceed in exactly the same way as for the one-body operator. In the coordinate representation our\ntwo-body interaction part takes the following expression\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-31\"></div>\n\n$$\n\\begin{equation}\n\t\\hat{H}_I = \\sum_{i < j} V(x_i,x_j) \\label{eq:2-31} \\tag{66}\n\\end{equation}\n$$\n\nwhere the summation runs over distinct pairs. The term $V$ can be an interaction model for the nucleon-nucleon interaction\nor the interaction between two electrons. It can also include additional two-body interaction terms. \n\nThe action of this operator on a product of \ntwo single-particle functions is defined as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-32\"></div>\n\n$$\n\\begin{equation}\n\tV(x_i,x_j) \\psi_{\\alpha_k}(x_i) \\psi_{\\alpha_l}(x_j) = \\sum_{\\alpha_k'\\alpha_l'} \n\t\t\\psi_{\\alpha_k}'(x_i)\\psi_{\\alpha_l}'(x_j) \n\t\t\\langle \\alpha_k'\\alpha_l'|\\hat{v}|\\alpha_k\\alpha_l\\rangle \\label{eq:2-32} \\tag{67}\n\\end{equation}\n$$\n\nWe can now let $\\hat{H}_I$ act on all terms in the linear combination for $|\\alpha_1\\alpha_2\\dots\\alpha_n\\rangle$. Without any permutations we have\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-33\"></div>\n\n$$\n\\begin{eqnarray}\n\t&& \\left( \\sum_{i < j} V(x_i,x_j) \\right) \\psi_{\\alpha_1}(x_1)\\psi_{\\alpha_2}(x_2)\\dots \\psi_{\\alpha_n}(x_n) \\nonumber \\\\\n\t&=& \\sum_{\\alpha_1'\\alpha_2'} \\langle \\alpha_1'\\alpha_2'|\\hat{v}|\\alpha_1\\alpha_2\\rangle\n\t\t\\psi_{\\alpha_1}'(x_1)\\psi_{\\alpha_2}'(x_2)\\dots \\psi_{\\alpha_n}(x_n) \\nonumber \\\\\n\t& +& \\dots \\nonumber \\\\\n\t&+& \\sum_{\\alpha_1'\\alpha_n'} \\langle \\alpha_1'\\alpha_n'|\\hat{v}|\\alpha_1\\alpha_n\\rangle\n\t\t\\psi_{\\alpha_1}'(x_1)\\psi_{\\alpha_2}(x_2)\\dots \\psi_{\\alpha_n}'(x_n) \\nonumber \\\\\n\t& +& \\dots \\nonumber \\\\\n\t&+& \\sum_{\\alpha_2'\\alpha_n'} \\langle \\alpha_2'\\alpha_n'|\\hat{v}|\\alpha_2\\alpha_n\\rangle\n\t\t\\psi_{\\alpha_1}(x_1)\\psi_{\\alpha_2}'(x_2)\\dots \\psi_{\\alpha_n}'(x_n) \\nonumber \\\\\n\t & +& \\dots \\label{eq:2-33} \\tag{68}\n\\end{eqnarray}\n$$\n\nwhere on the rhs we have a term for each distinct pairs. \n\n\n\n\nFor the other terms on the rhs we obtain similar expressions  and summing over all terms we obtain\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-34\"></div>\n\n$$\n\\begin{eqnarray}\n\tH_I |\\alpha_1\\alpha_2\\dots\\alpha_n\\rangle &=& \\sum_{\\alpha_1', \\alpha_2'} \\langle \\alpha_1'\\alpha_2'|\\hat{v}|\\alpha_1\\alpha_2\\rangle\n\t\t|\\alpha_1'\\alpha_2'\\dots\\alpha_n\\rangle \\nonumber \\\\\n\t&+& \\dots \\nonumber \\\\\n\t&+& \\sum_{\\alpha_1', \\alpha_n'} \\langle \\alpha_1'\\alpha_n'|\\hat{v}|\\alpha_1\\alpha_n\\rangle\n\t\t|\\alpha_1'\\alpha_2\\dots\\alpha_n'\\rangle \\nonumber \\\\\n\t&+& \\dots \\nonumber \\\\\n\t&+& \\sum_{\\alpha_2', \\alpha_n'} \\langle \\alpha_2'\\alpha_n'|\\hat{v}|\\alpha_2\\alpha_n\\rangle\n\t\t|\\alpha_1\\alpha_2'\\dots\\alpha_n'\\rangle \\nonumber \\\\\n\t &+& \\dots \\label{eq:2-34} \\tag{69}\n\\end{eqnarray}\n$$\n\nWe introduce second quantization via the relation\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-35\"></div>\n\n$$\n\\begin{eqnarray}\n\t&& a_{\\alpha_k'}^{\\dagger} a_{\\alpha_l'}^{\\dagger} a_{\\alpha_l} a_{\\alpha_k} \n\t\t|\\alpha_1\\alpha_2\\dots\\alpha_k\\dots\\alpha_l\\dots\\alpha_n\\rangle \\nonumber \\\\\n\t&=& (-1)^{k-1} (-1)^{l-2} a_{\\alpha_k'}^{\\dagger} a_{\\alpha_l'}^{\\dagger} a_{\\alpha_l} a_{\\alpha_k}\n\t\t|\\alpha_k\\alpha_l \\underbrace{\\alpha_1\\alpha_2\\dots\\alpha_n}_{\\neq \\alpha_k,\\alpha_l}\\rangle \\nonumber \\\\\n\t&=& (-1)^{k-1} (-1)^{l-2} \n\t|\\alpha_k'\\alpha_l' \\underbrace{\\alpha_1\\alpha_2\\dots\\alpha_n}_{\\neq \\alpha_k',\\alpha_l'}\\rangle \\nonumber \\\\\n\t&=& |\\alpha_1\\alpha_2\\dots\\alpha_k'\\dots\\alpha_l'\\dots\\alpha_n\\rangle \\label{eq:2-35} \\tag{70}\n\\end{eqnarray}\n$$\n\nInserting this in [(69)](#eq:2-34) gives\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-36\"></div>\n\n$$\n\\begin{eqnarray}\n\tH_I |\\alpha_1\\alpha_2\\dots\\alpha_n\\rangle\n\t&=& \\sum_{\\alpha_1', \\alpha_2'} \\langle \\alpha_1'\\alpha_2'|\\hat{v}|\\alpha_1\\alpha_2\\rangle\n\t\ta_{\\alpha_1'}^{\\dagger} a_{\\alpha_2'}^{\\dagger} a_{\\alpha_2} a_{\\alpha_1}\n\t\t|\\alpha_1\\alpha_2\\dots\\alpha_n\\rangle \\nonumber \\\\\n\t&+& \\dots \\nonumber \\\\\n\t&=& \\sum_{\\alpha_1', \\alpha_n'} \\langle \\alpha_1'\\alpha_n'|\\hat{v}|\\alpha_1\\alpha_n\\rangle\n\t\ta_{\\alpha_1'}^{\\dagger} a_{\\alpha_n'}^{\\dagger} a_{\\alpha_n} a_{\\alpha_1}\n\t\t|\\alpha_1\\alpha_2\\dots\\alpha_n\\rangle \\nonumber \\\\\n\t&+& \\dots \\nonumber \\\\\n\t&=& \\sum_{\\alpha_2', \\alpha_n'} \\langle \\alpha_2'\\alpha_n'|\\hat{v}|\\alpha_2\\alpha_n\\rangle\n\t\ta_{\\alpha_2'}^{\\dagger} a_{\\alpha_n'}^{\\dagger} a_{\\alpha_n} a_{\\alpha_2}\n\t\t|\\alpha_1\\alpha_2\\dots\\alpha_n\\rangle \\nonumber \\\\\n\t&+& \\dots \\nonumber \\\\\n\t&=& \\sum_{\\alpha, \\beta, \\gamma, \\delta} ' \\langle \\alpha\\beta|\\hat{v}|\\gamma\\delta\\rangle\n\t\ta^{\\dagger}_\\alpha a^{\\dagger}_\\beta a_\\delta a_\\gamma\n\t\t|\\alpha_1\\alpha_2\\dots\\alpha_n\\rangle \\label{eq:2-36} \\tag{71}\n\\end{eqnarray}\n$$\n\nHere we let $\\sum'$ indicate that the sums running over $\\alpha$ and $\\beta$ run over all\nsingle-particle states, while the summations  $\\gamma$ and $\\delta$ \nrun over all pairs of single-particle states. We wish to remove this restriction and since\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-37\"></div>\n\n$$\n\\begin{equation}\n\t\\langle \\alpha\\beta|\\hat{v}|\\gamma\\delta\\rangle = \\langle \\beta\\alpha|\\hat{v}|\\delta\\gamma\\rangle \\label{eq:2-37} \\tag{72}\n\\end{equation}\n$$\n\nwe get\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-38a\"></div> <div id=\"eq:2-38b\"></div>\n\n$$\n\\begin{eqnarray}\n\t\\sum_{\\alpha\\beta} \\langle \\alpha\\beta|\\hat{v}|\\gamma\\delta\\rangle a^{\\dagger}_\\alpha a^{\\dagger}_\\beta a_\\delta a_\\gamma &=& \n\t\t\\sum_{\\alpha\\beta} \\langle \\beta\\alpha|\\hat{v}|\\delta\\gamma\\rangle \n\t\ta^{\\dagger}_\\alpha a^{\\dagger}_\\beta a_\\delta a_\\gamma \\label{eq:2-38a} \\tag{73} \\\\\n\t&=& \\sum_{\\alpha\\beta}\\langle \\beta\\alpha|\\hat{v}|\\delta\\gamma\\rangle\n\t\ta^{\\dagger}_\\beta a^{\\dagger}_\\alpha a_\\gamma a_\\delta \\label{eq:2-38b} \\tag{74}\n\\end{eqnarray}\n$$\n\nwhere we  have used the anti-commutation rules.\n\n\n\n\nChanging the summation indices \n$\\alpha$ and $\\beta$ in [(74)](#eq:2-38b) we obtain\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-38c\"></div>\n\n$$\n\\begin{equation}\n\t\\sum_{\\alpha\\beta} \\langle \\alpha\\beta|\\hat{v}|\\gamma\\delta\\rangle a^{\\dagger}_\\alpha a^{\\dagger}_\\beta a_\\delta a_\\gamma =\n\t\t \\sum_{\\alpha\\beta} \\langle \\alpha\\beta|\\hat{v}|\\delta\\gamma\\rangle \n\t\t  a^{\\dagger}_\\alpha a^{\\dagger}_\\beta  a_\\gamma a_\\delta \\label{eq:2-38c} \\tag{75}\n\\end{equation}\n$$\n\nFrom this it follows that the restriction on the summation over $\\gamma$ and $\\delta$ can be removed if we multiply with a factor $\\frac{1}{2}$, resulting in\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-39\"></div>\n\n$$\n\\begin{equation}\n\t\\hat{H}_I = \\frac{1}{2} \\sum_{\\alpha\\beta\\gamma\\delta} \\langle \\alpha\\beta|\\hat{v}|\\gamma\\delta\\rangle\n\t\ta^{\\dagger}_\\alpha a^{\\dagger}_\\beta a_\\delta a_\\gamma \\label{eq:2-39} \\tag{76}\n\\end{equation}\n$$\n\nwhere we sum freely over all single-particle states $\\alpha$, \n$\\beta$, $\\gamma$ og $\\delta$.\n\n\n\n\n\n\nWith this expression we can now verify that the second quantization form of $\\hat{H}_I$ in Eq. [(76)](#eq:2-39) \nresults in the same matrix between two anti-symmetrized two-particle states as its corresponding coordinate\nspace representation. We have\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-40\"></div>\n\n$$\n\\begin{equation}\n\t\\langle \\alpha_1 \\alpha_2|\\hat{H}_I|\\beta_1 \\beta_2\\rangle =\n\t\t\\frac{1}{2} \\sum_{\\alpha\\beta\\gamma\\delta}\n\t\t\t\\langle \\alpha\\beta|\\hat{v}|\\gamma\\delta\\rangle \\langle 0|a_{\\alpha_2} a_{\\alpha_1} \n\t\t\t a^{\\dagger}_\\alpha a^{\\dagger}_\\beta a_\\delta a_\\gamma \n\t\t\t a_{\\beta_1}^{\\dagger} a_{\\beta_2}^{\\dagger}|0\\rangle. \\label{eq:2-40} \\tag{77}\n\\end{equation}\n$$\n\nUsing the commutation relations we get\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-41\"></div>\n\n$$\n\\begin{eqnarray}\n\t&& a_{\\alpha_2} a_{\\alpha_1}a^{\\dagger}_\\alpha a^{\\dagger}_\\beta \n\t\ta_\\delta a_\\gamma a_{\\beta_1}^{\\dagger} a_{\\beta_2}^{\\dagger} \\nonumber \\\\\n\t&=& a_{\\alpha_2} a_{\\alpha_1}a^{\\dagger}_\\alpha a^{\\dagger}_\\beta \n\t\t( a_\\delta \\delta_{\\gamma \\beta_1} a_{\\beta_2}^{\\dagger} - \n\t\ta_\\delta  a_{\\beta_1}^{\\dagger} a_\\gamma a_{\\beta_2}^{\\dagger} ) \\nonumber \\\\\n\t&=& a_{\\alpha_2} a_{\\alpha_1}a^{\\dagger}_\\alpha a^{\\dagger}_\\beta \n\t\t(\\delta_{\\gamma \\beta_1} \\delta_{\\delta \\beta_2} - \\delta_{\\gamma \\beta_1} a_{\\beta_2}^{\\dagger} a_\\delta -\n\t\ta_\\delta a_{\\beta_1}^{\\dagger}\\delta_{\\gamma \\beta_2} +\n\t\ta_\\delta a_{\\beta_1}^{\\dagger} a_{\\beta_2}^{\\dagger} a_\\gamma ) \\nonumber \\\\\n\t&=& a_{\\alpha_2} a_{\\alpha_1}a^{\\dagger}_\\alpha a^{\\dagger}_\\beta \n\t\t(\\delta_{\\gamma \\beta_1} \\delta_{\\delta \\beta_2} - \\delta_{\\gamma \\beta_1} a_{\\beta_2}^{\\dagger} a_\\delta \\nonumber \\\\\n\t\t&& \\qquad - \\delta_{\\delta \\beta_1} \\delta_{\\gamma \\beta_2} + \\delta_{\\gamma \\beta_2} a_{\\beta_1}^{\\dagger} a_\\delta\n\t\t+ a_\\delta a_{\\beta_1}^{\\dagger} a_{\\beta_2}^{\\dagger} a_\\gamma ) \\label{eq:2-41} \\tag{78}\n\\end{eqnarray}\n$$\n\nThe vacuum expectation value of this product of operators becomes\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-42b\"></div>\n\n$$\n\\begin{eqnarray}\n\t&& \\langle 0|a_{\\alpha_2} a_{\\alpha_1} a^{\\dagger}_\\alpha a^{\\dagger}_\\beta a_\\delta a_\\gamma \n\t\ta_{\\beta_1}^{\\dagger} a_{\\beta_2}^{\\dagger}|0\\rangle \\nonumber \\\\\n\t&=& (\\delta_{\\gamma \\beta_1} \\delta_{\\delta \\beta_2} -\n\t\t\\delta_{\\delta \\beta_1} \\delta_{\\gamma \\beta_2} ) \n\t\t\\langle 0|a_{\\alpha_2} a_{\\alpha_1}a^{\\dagger}_\\alpha a^{\\dagger}_\\beta|0\\rangle \\nonumber \\\\\n\t&=& (\\delta_{\\gamma \\beta_1} \\delta_{\\delta \\beta_2} -\\delta_{\\delta \\beta_1} \\delta_{\\gamma \\beta_2} )\n\t(\\delta_{\\alpha \\alpha_1} \\delta_{\\beta \\alpha_2} -\\delta_{\\beta \\alpha_1} \\delta_{\\alpha \\alpha_2} ) \\label{eq:2-42b} \\tag{79}\n\\end{eqnarray}\n$$\n\nInsertion of \nEq. [(79)](#eq:2-42b) in Eq. [(77)](#eq:2-40) results in\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-43b\"></div>\n\n$$\n\\begin{eqnarray}\n\t\\langle \\alpha_1\\alpha_2|\\hat{H}_I|\\beta_1\\beta_2\\rangle &=& \\frac{1}{2} \\big[ \n\t\t\\langle \\alpha_1\\alpha_2|\\hat{v}|\\beta_1\\beta_2\\rangle- \\langle \\alpha_1\\alpha_2|\\hat{v}|\\beta_2\\beta_1\\rangle \\nonumber \\\\\n\t\t&& - \\langle \\alpha_2\\alpha_1|\\hat{v}|\\beta_1\\beta_2\\rangle + \\langle \\alpha_2\\alpha_1|\\hat{v}|\\beta_2\\beta_1\\rangle \\big] \\nonumber \\\\\n\t&=& \\langle \\alpha_1\\alpha_2|\\hat{v}|\\beta_1\\beta_2\\rangle - \\langle \\alpha_1\\alpha_2|\\hat{v}|\\beta_2\\beta_1\\rangle \\nonumber \\\\\n\t&=& \\langle \\alpha_1\\alpha_2|\\hat{v}|\\beta_1\\beta_2\\rangle_{\\mathrm{AS}}. \\label{eq:2-43b} \\tag{80}\n\\end{eqnarray}\n$$\n\nThe two-body operator can also be expressed in terms of the anti-symmetrized matrix elements we discussed previously as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-45\"></div>\n\n$$\n\\begin{eqnarray}\n\t\\hat{H}_I &=& \\frac{1}{2} \\sum_{\\alpha\\beta\\gamma\\delta}  \\langle \\alpha \\beta|\\hat{v}|\\gamma \\delta\\rangle\n\t\ta_\\alpha^{\\dagger} a_\\beta^{\\dagger} a_\\delta a_\\gamma \\nonumber \\\\\n\t&=& \\frac{1}{4} \\sum_{\\alpha\\beta\\gamma\\delta} \\left[ \\langle \\alpha \\beta|\\hat{v}|\\gamma \\delta\\rangle -\n\t\t\\langle \\alpha \\beta|\\hat{v}|\\delta\\gamma \\rangle \\right] \n\t\ta_\\alpha^{\\dagger} a_\\beta^{\\dagger} a_\\delta a_\\gamma \\nonumber \\\\\n\t&=& \\frac{1}{4} \\sum_{\\alpha\\beta\\gamma\\delta} \\langle \\alpha \\beta|\\hat{v}|\\gamma \\delta\\rangle_{\\mathrm{AS}}\n\t\ta_\\alpha^{\\dagger} a_\\beta^{\\dagger} a_\\delta a_\\gamma \\label{eq:2-45} \\tag{81}\n\\end{eqnarray}\n$$\n\nThe factors in front of the operator, either  $\\frac{1}{4}$ or \n$\\frac{1}{2}$ tells whether we use antisymmetrized matrix elements or not. \n\nWe can now express the Hamiltonian operator for a many-fermion system  in the occupation basis representation\nas\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-46b\"></div>\n\n$$\n\\begin{equation}\n\tH = \\sum_{\\alpha, \\beta} \\langle \\alpha|\\hat{t}+\\hat{u}_{\\mathrm{ext}}|\\beta\\rangle a_\\alpha^{\\dagger} a_\\beta + \\frac{1}{4} \\sum_{\\alpha\\beta\\gamma\\delta}\n\t\t\\langle \\alpha \\beta|\\hat{v}|\\gamma \\delta\\rangle a_\\alpha^{\\dagger} a_\\beta^{\\dagger} a_\\delta a_\\gamma. \\label{eq:2-46b} \\tag{82}\n\\end{equation}\n$$\n\nThis is the form we will use in the rest of these lectures, assuming that we work with anti-symmetrized two-body matrix elements.\n\n\n\n\n\n## Particle-hole formalism\n\nSecond quantization is a useful and elegant formalism  for constructing many-body  states and \nquantum mechanical operators. One can express and translate many physical processes\ninto simple pictures such as Feynman diagrams. Expecation values of many-body states are also easily calculated.\nHowever, although the equations are seemingly easy to set up, from  a practical point of view, that is\nthe solution of Schroedinger's equation, there is no particular gain.\nThe many-body equation is equally hard to solve, irrespective of representation. \nThe cliche that \nthere is no free lunch brings us down to earth again.  \nNote however that a transformation to a particular\nbasis, for cases where the interaction obeys specific symmetries, can ease the solution of Schroedinger's equation. \n\nBut there is at least one important case where second quantization comes to our rescue.\nIt is namely easy to introduce another reference state than the pure vacuum $|0\\rangle $, where all single-particle states are active.\nWith many particles present it is often useful to introduce another reference state  than the vacuum state$|0\\rangle $. We will label this state $|c\\rangle$ ($c$ for core) and as we will see it can reduce \nconsiderably the complexity and thereby the dimensionality of the many-body problem. It allows us to sum up to infinite order specific many-body correlations.  The particle-hole representation is one of these handy representations. \n\n\n\n\n\nIn the original particle representation these states are products of the creation operators  $a_{\\alpha_i}^\\dagger$ acting on the true vacuum $|0\\rangle $.\nFollowing Eq. [(27)](#eq:2-2) we have\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-47a\"></div> <div id=\"eq:2-47b\"></div> <div id=\"eq:2-47c\"></div>\n\n$$\n\\begin{eqnarray}\n |\\alpha_1\\alpha_2\\dots\\alpha_{n-1}\\alpha_n\\rangle &=& a_{\\alpha_1}^\\dagger a_{\\alpha_2}^\\dagger \\dots\n\t\t\t\t\ta_{\\alpha_{n-1}}^\\dagger a_{\\alpha_n}^\\dagger |0\\rangle  \\label{eq:2-47a} \\tag{83} \\\\\n\t|\\alpha_1\\alpha_2\\dots\\alpha_{n-1}\\alpha_n\\alpha_{n+1}\\rangle &=&\n\t\ta_{\\alpha_1}^\\dagger a_{\\alpha_2}^\\dagger \\dots a_{\\alpha_{n-1}}^\\dagger a_{\\alpha_n}^\\dagger\n\t\ta_{\\alpha_{n+1}}^\\dagger |0\\rangle  \\label{eq:2-47b} \\tag{84} \\\\\n\t|\\alpha_1\\alpha_2\\dots\\alpha_{n-1}\\rangle &=& a_{\\alpha_1}^\\dagger a_{\\alpha_2}^\\dagger \\dots\n\t\ta_{\\alpha_{n-1}}^\\dagger |0\\rangle  \\label{eq:2-47c} \\tag{85}\n\\end{eqnarray}\n$$\n\nIf we use Eq. [(83)](#eq:2-47a) as our new reference state, we can simplify considerably the representation of \nthis state\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-48a\"></div>\n\n$$\n\\begin{equation}\n\t|c\\rangle  \\equiv |\\alpha_1\\alpha_2\\dots\\alpha_{n-1}\\alpha_n\\rangle =\n\t\ta_{\\alpha_1}^\\dagger a_{\\alpha_2}^\\dagger \\dots a_{\\alpha_{n-1}}^\\dagger a_{\\alpha_n}^\\dagger |0\\rangle  \\label{eq:2-48a} \\tag{86}\n\\end{equation}\n$$\n\nThe new reference states for the $n+1$ and $n-1$ states can then be written as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-48b\"></div> <div id=\"eq:2-48c\"></div>\n\n$$\n\\begin{eqnarray}\n\t|\\alpha_1\\alpha_2\\dots\\alpha_{n-1}\\alpha_n\\alpha_{n+1}\\rangle &=& (-1)^n a_{\\alpha_{n+1}}^\\dagger |c\\rangle \n\t\t\\equiv (-1)^n |\\alpha_{n+1}\\rangle_c \\label{eq:2-48b} \\tag{87} \\\\\n\t|\\alpha_1\\alpha_2\\dots\\alpha_{n-1}\\rangle &=& (-1)^{n-1} a_{\\alpha_n} |c\\rangle  \n\t\t\\equiv (-1)^{n-1} |\\alpha_{n-1}\\rangle_c \\label{eq:2-48c} \\tag{88} \n\\end{eqnarray}\n$$\n\nThe first state has one additional particle with respect to the new vacuum state\n$|c\\rangle $  and is normally referred to as a one-particle state or one particle added to the \nmany-body reference state. \nThe second state has one particle less than the reference vacuum state  $|c\\rangle $ and is referred to as\na one-hole state. \nWhen dealing with a new reference state it is often convenient to introduce \nnew creation and annihilation operators since we have \nfrom Eq. [(88)](#eq:2-48c)\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-49\"></div>\n\n$$\n\\begin{equation}\n\ta_\\alpha |c\\rangle  \\neq 0 \\label{eq:2-49} \\tag{89}\n\\end{equation}\n$$\n\nsince  $\\alpha$ is contained  in $|c\\rangle $, while for the true vacuum we have \n$a_\\alpha |0\\rangle  = 0$ for all $\\alpha$.\n\nThe new reference state leads to the definition of new creation and annihilation operators\nwhich satisfy the following relations\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-50a\"></div> <div id=\"eq:2-50c\"></div>\n\n$$\n\\begin{eqnarray}\n\tb_\\alpha |c\\rangle  &=& 0 \\label{eq:2-50a} \\tag{90} \\\\\n\t\\{b_\\alpha^\\dagger , b_\\beta^\\dagger \\} = \\{b_\\alpha , b_\\beta \\} &=& 0 \\nonumber  \\\\\n\t\\{b_\\alpha^\\dagger , b_\\beta \\} &=& \\delta_{\\alpha \\beta} \\label{eq:2-50c} \\tag{91}\n\\end{eqnarray}\n$$\n\nWe assume also that the new reference state is properly normalized\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-51\"></div>\n\n$$\n\\begin{equation}\n\t\\langle c | c \\rangle = 1 \\label{eq:2-51} \\tag{92}\n\\end{equation}\n$$\n\nThe physical interpretation of these new operators is that of so-called quasiparticle states.\nThis means that a state defined by the addition of one extra particle to a reference state $|c\\rangle $ may not necesseraly be interpreted as one particle coupled to a core.\nWe define now new creation operators that act on a state $\\alpha$ creating a new quasiparticle state\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-52\"></div>\n\n$$\n\\begin{equation}\n\tb_\\alpha^\\dagger|c\\rangle  = \\Bigg\\{ \\begin{array}{ll}\n\t\ta_\\alpha^\\dagger |c\\rangle  = |\\alpha\\rangle, & \\alpha > F \\\\\n\t\t\\\\\n\t\ta_\\alpha |c\\rangle  = |\\alpha^{-1}\\rangle, & \\alpha \\leq F\n\t\\end{array} \\label{eq:2-52} \\tag{93}\n\\end{equation}\n$$\n\nwhere $F$ is the Fermi level representing the last  occupied single-particle orbit \nof the new reference state $|c\\rangle $. \n\n\nThe annihilation is the hermitian conjugate of the creation operator\n\n$$\nb_\\alpha = (b_\\alpha^\\dagger)^\\dagger,\n$$\n\nresulting in\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-54\"></div>\n\n$$\n\\begin{equation}\n\tb_\\alpha^\\dagger = \\Bigg\\{ \\begin{array}{ll}\n\t\ta_\\alpha^\\dagger & \\alpha > F \\\\\n\t\t\\\\\n\t\ta_\\alpha & \\alpha \\leq F\n\t\\end{array} \\qquad \n\tb_\\alpha = \\Bigg\\{ \\begin{array}{ll}\n\t\ta_\\alpha & \\alpha > F \\\\\n\t\t\\\\\n\t\t a_\\alpha^\\dagger & \\alpha \\leq F\n\t\\end{array} \\label{eq:2-54} \\tag{94}\n\\end{equation}\n$$\n\nWith the new creation and annihilation operator  we can now construct \nmany-body quasiparticle states, with one-particle-one-hole states, two-particle-two-hole\nstates etc in the same fashion as we previously constructed many-particle states. \nWe can write a general particle-hole state as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-56\"></div>\n\n$$\n\\begin{equation}\n\t|\\beta_1\\beta_2\\dots \\beta_{n_p} \\gamma_1^{-1} \\gamma_2^{-1} \\dots \\gamma_{n_h}^{-1}\\rangle \\equiv\n\t\t\\underbrace{b_{\\beta_1}^\\dagger b_{\\beta_2}^\\dagger \\dots b_{\\beta_{n_p}}^\\dagger}_{>F}\n\t\t\\underbrace{b_{\\gamma_1}^\\dagger b_{\\gamma_2}^\\dagger \\dots b_{\\gamma_{n_h}}^\\dagger}_{\\leq F} |c\\rangle \\label{eq:2-56} \\tag{95}\n\\end{equation}\n$$\n\nWe can now rewrite our one-body and two-body operators in terms of the new creation and annihilation operators.\nThe number operator becomes\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-57b\"></div>\n\n$$\n\\begin{equation}\n\t\\hat{N} = \\sum_\\alpha a_\\alpha^\\dagger a_\\alpha= \n\\sum_{\\alpha > F} b_\\alpha^\\dagger b_\\alpha + n_c - \\sum_{\\alpha \\leq F} b_\\alpha^\\dagger b_\\alpha \\label{eq:2-57b} \\tag{96}\n\\end{equation}\n$$\n\nwhere $n_c$ is the number of particle in the new vacuum state $|c\\rangle $.  \nThe action of $\\hat{N}$ on a many-body state results in\n\n<!-- Equation labels as ordinary links -->\n<div id=\"2-59\"></div>\n\n$$\n\\begin{equation}\n\tN |\\beta_1\\beta_2\\dots \\beta_{n_p} \\gamma_1^{-1} \\gamma_2^{-1} \\dots \\gamma_{n_h}^{-1}\\rangle = (n_p + n_c - n_h) |\\beta_1\\beta_2\\dots \\beta_{n_p} \\gamma_1^{-1} \\gamma_2^{-1} \\dots \\gamma_{n_h}^{-1}\\rangle \\label{2-59} \\tag{97}\n\\end{equation}\n$$\n\nHere  $n=n_p +n_c - n_h$ is the total number of particles in the quasi-particle state of \nEq. [(95)](#eq:2-56). Note that  $\\hat{N}$ counts the total number of particles  present\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-60\"></div>\n\n$$\n\\begin{equation}\n\tN_{qp} = \\sum_\\alpha b_\\alpha^\\dagger b_\\alpha, \\label{eq:2-60} \\tag{98}\n\\end{equation}\n$$\n\ngives us the number of quasi-particles as can be seen by computing\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-61\"></div>\n\n$$\n\\begin{equation}\n\tN_{qp}= |\\beta_1\\beta_2\\dots \\beta_{n_p} \\gamma_1^{-1} \\gamma_2^{-1} \\dots \\gamma_{n_h}^{-1}\\rangle\n\t\t= (n_p + n_h)|\\beta_1\\beta_2\\dots \\beta_{n_p} \\gamma_1^{-1} \\gamma_2^{-1} \\dots \\gamma_{n_h}^{-1}\\rangle \\label{eq:2-61} \\tag{99}\n\\end{equation}\n$$\n\nwhere $n_{qp} = n_p + n_h$ is the total number of quasi-particles.\n\n\n\n\nWe express the one-body operator $\\hat{H}_0$ in terms of the quasi-particle creation and annihilation operators, resulting in\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-63b\"></div>\n\n$$\n\\begin{eqnarray}\n\t\\hat{H}_0 &=& \\sum_{\\alpha\\beta > F} \\langle \\alpha|\\hat{h}_0|\\beta\\rangle  b_\\alpha^\\dagger b_\\beta +\n\t\t\\sum_{\\begin{array}{c} \\alpha > F \\\\ \\beta \\leq F \\end{array}} \\left[\n\t\t\\langle \\alpha|\\hat{h}_0|\\beta\\rangle b_\\alpha^\\dagger b_\\beta^\\dagger + \n\t\t\\langle \\beta|\\hat{h}_0|\\alpha\\rangle b_\\beta  b_\\alpha \\right] \\nonumber \\\\\n\t&+& \\sum_{\\alpha \\leq F} \\langle \\alpha|\\hat{h}_0|\\alpha\\rangle - \n\t\t\\sum_{\\alpha\\beta \\leq F} \\langle \\beta|\\hat{h}_0|\\alpha\\rangle\n\t\tb_\\alpha^\\dagger b_\\beta \\label{eq:2-63b} \\tag{100}\n\\end{eqnarray}\n$$\n\nThe first term  gives contribution only for particle states, while the last one\ncontributes only for holestates. The second term can create or destroy a set of\nquasi-particles and \nthe third term is the contribution  from the vacuum state $|c\\rangle$.\n\n\n\n\n\nBefore we continue with the expressions for the two-body operator, we introduce a nomenclature we will use for the rest of this\ntext. It is inspired by the notation used in quantum chemistry.\nWe reserve the labels $i,j,k,\\dots$ for hole states and $a,b,c,\\dots$ for states above $F$, viz. particle states.\nThis means also that we will skip the constraint $\\leq F$ or $> F$ in the summation symbols. \nOur operator $\\hat{H}_0$  reads now\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-63b\"></div>\n\n$$\n\\begin{eqnarray}\n\t\\hat{H}_0 &=& \\sum_{ab} \\langle a|\\hat{h}|b\\rangle b_a^\\dagger b_b +\n\t\t\\sum_{ai} \\left[\n\t\t\\langle a|\\hat{h}|i\\rangle b_a^\\dagger b_i^\\dagger + \n\t\t\\langle i|\\hat{h}|a\\rangle b_i  b_a \\right] \\nonumber \\\\\n\t&+& \\sum_{i} \\langle i|\\hat{h}|i\\rangle - \n\t\t\\sum_{ij} \\langle j|\\hat{h}|i\\rangle\n\t\tb_i^\\dagger b_j \\label{eq:2-63b} \\tag{101}\n\\end{eqnarray}\n$$\n\nThe two-particle operator in the particle-hole formalism  is more complicated since we have\nto translate four indices $\\alpha\\beta\\gamma\\delta$ to the possible combinations of particle and hole\nstates.  When performing the commutator algebra we can regroup the operator in five different terms\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-65\"></div>\n\n$$\n\\begin{equation}\n\t\\hat{H}_I = \\hat{H}_I^{(a)} + \\hat{H}_I^{(b)} + \\hat{H}_I^{(c)} + \\hat{H}_I^{(d)} + \\hat{H}_I^{(e)} \\label{eq:2-65} \\tag{102}\n\\end{equation}\n$$\n\nUsing anti-symmetrized  matrix elements, \nbthe term  $\\hat{H}_I^{(a)}$ is\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-66\"></div>\n\n$$\n\\begin{equation}\n\t\\hat{H}_I^{(a)} = \\frac{1}{4}\n\t\\sum_{abcd} \\langle ab|\\hat{V}|cd\\rangle \n\t\tb_a^\\dagger b_b^\\dagger b_d b_c \\label{eq:2-66} \\tag{103}\n\\end{equation}\n$$\n\nThe next term $\\hat{H}_I^{(b)}$  reads\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-67b\"></div>\n\n$$\n\\begin{equation}\n\t \\hat{H}_I^{(b)} = \\frac{1}{4} \\sum_{abci}\\left(\\langle ab|\\hat{V}|ci\\rangle b_a^\\dagger b_b^\\dagger b_i^\\dagger b_c +\\langle ai|\\hat{V}|cb\\rangle b_a^\\dagger b_i b_b b_c\\right) \\label{eq:2-67b} \\tag{104}\n\\end{equation}\n$$\n\nThis term conserves the number of quasiparticles but creates or removes a \nthree-particle-one-hole  state. \nFor $\\hat{H}_I^{(c)}$  we have\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-68c\"></div>\n\n$$\n\\begin{eqnarray}\n\t\\hat{H}_I^{(c)}& =& \\frac{1}{4}\n\t\t\\sum_{abij}\\left(\\langle ab|\\hat{V}|ij\\rangle b_a^\\dagger b_b^\\dagger b_j^\\dagger b_i^\\dagger +\n\t\t\\langle ij|\\hat{V}|ab\\rangle b_a  b_b b_j b_i \\right)+  \\nonumber \\\\\n\t&&\t\\frac{1}{2}\\sum_{abij}\\langle ai|\\hat{V}|bj\\rangle b_a^\\dagger b_j^\\dagger b_b b_i + \n\t\t\\frac{1}{2}\\sum_{abi}\\langle ai|\\hat{V}|bi\\rangle b_a^\\dagger b_b. \\label{eq:2-68c} \\tag{105}\n\\end{eqnarray}\n$$\n\nThe first line stands for the creation of a two-particle-two-hole state, while the second line represents\nthe creation to two one-particle-one-hole pairs\nwhile the last term represents a contribution to the particle single-particle energy\nfrom the hole states, that is an interaction between the particle states and the hole states\nwithin the new vacuum  state.\nThe fourth term reads\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-69d\"></div>\n\n$$\n\\begin{eqnarray}\n\t \\hat{H}_I^{(d)}& = &\\frac{1}{4} \n\t \t\\sum_{aijk}\\left(\\langle ai|\\hat{V}|jk\\rangle b_a^\\dagger b_k^\\dagger b_j^\\dagger b_i+\n\\langle ji|\\hat{V}|ak\\rangle b_k^\\dagger b_j b_i b_a\\right)+\\nonumber \\\\\n&&\\frac{1}{4}\\sum_{aij}\\left(\\langle ai|\\hat{V}|ji\\rangle b_a^\\dagger b_j^\\dagger+\n\\langle ji|\\hat{V}|ai\\rangle - \\langle ji|\\hat{V}|ia\\rangle b_j b_a \\right). \\label{eq:2-69d} \\tag{106} \n\\end{eqnarray}\n$$\n\nThe terms in the first line  stand for the creation of a particle-hole state \ninteracting with hole states, we will label this as a two-hole-one-particle contribution. \nThe remaining terms are a particle-hole state interacting with the holes in the vacuum state. \nFinally we have\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:2-70d\"></div>\n\n$$\n\\begin{equation}\n\t\\hat{H}_I^{(e)} = \\frac{1}{4}\n\t\t \\sum_{ijkl}\n\t\t \\langle kl|\\hat{V}|ij\\rangle b_i^\\dagger b_j^\\dagger b_l b_k+\n\t        \\frac{1}{2}\\sum_{ijk}\\langle ij|\\hat{V}|kj\\rangle b_k^\\dagger b_i\n\t        +\\frac{1}{2}\\sum_{ij}\\langle ij|\\hat{V}|ij\\rangle \\label{eq:2-70d} \\tag{107}\n\\end{equation}\n$$\n\nThe first terms represents the \ninteraction between two holes while the second stands for the interaction between a hole and the remaining holes in the vacuum state.\nIt represents a contribution to single-hole energy  to first order.\nThe last term collects all contributions to the energy of the ground state of a closed-shell system arising\nfrom hole-hole correlations.\n\n\n\n\n## Summarizing and defining a normal-ordered Hamiltonian\n\n$$\n\\Phi_{AS}(\\alpha_1, \\dots, \\alpha_A; x_1, \\dots x_A)=\n            \\frac{1}{\\sqrt{A}} \\sum_{\\hat{P}} (-1)^P \\hat{P} \\prod_{i=1}^A \\psi_{\\alpha_i}(x_i),\n$$\n\nwhich is equivalent with $|\\alpha_1 \\dots \\alpha_A\\rangle= a_{\\alpha_1}^{\\dagger} \\dots a_{\\alpha_A}^{\\dagger} |0\\rangle$. We have also\n\n3\n2\n8\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\delta_{pq} = \\left\\{a_p, a_q^\\dagger \\right\\},\n$$\n\nand\n\n3\n3\n0\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n|\\Phi_0\\rangle = |\\alpha_1 \\dots \\alpha_A\\rangle, \\quad \\alpha_1, \\dots, \\alpha_A \\leq \\alpha_F\n$$\n\n3\n3\n2\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\left\\{a_p, a_q^\\dagger \\right\\} = \\delta_{pq}, p, q > \\alpha_F\n$$\n\nwith         $i,j,\\ldots \\leq \\alpha_F, \\quad a,b,\\ldots > \\alpha_F, \\quad p,q, \\ldots - \\textrm{any}$\n\n$$\na_i|\\Phi_0\\rangle = |\\Phi_i\\rangle, \\hspace{0.5cm} a_a^\\dagger|\\Phi_0\\rangle = |\\Phi^a\\rangle\n$$\n\nand\n\n$$\na_i^\\dagger|\\Phi_0\\rangle = 0 \\hspace{0.5cm}  a_a|\\Phi_0\\rangle = 0\n$$\n\nThe one-body operator is defined as\n\n$$\n\\hat{F} = \\sum_{pq} \\langle p|\\hat{f}|q\\rangle a_p^\\dagger a_q\n$$\n\nwhile the two-body opreator is defined as\n\n$$\n\\hat{V} = \\frac{1}{4} \\sum_{pqrs} \\langle pq|\\hat{v}|rs\\rangle_{AS} a_p^\\dagger a_q^\\dagger a_s a_r\n$$\n\nwhere we have defined the antisymmetric matrix elements\n\n$$\n\\langle pq|\\hat{v}|rs\\rangle_{AS} = \\langle pq|\\hat{v}|rs\\rangle - \\langle pq|\\hat{v}|sr\\rangle.\n$$\n\nWe can also define a three-body operator\n\n$$\n\\hat{V}_3 = \\frac{1}{36} \\sum_{pqrstu} \\langle pqr|\\hat{v}_3|stu\\rangle_{AS} \n                a_p^\\dagger a_q^\\dagger a_r^\\dagger a_u a_t a_s\n$$\n\nwith the antisymmetrized matrix element\n\n$$\n\\begin{equation}\n            \\langle pqr|\\hat{v}_3|stu\\rangle_{AS} = \\langle pqr|\\hat{v}_3|stu\\rangle + \\langle pqr|\\hat{v}_3|tus\\rangle + \\langle pqr|\\hat{v}_3|ust\\rangle- \\langle pqr|\\hat{v}_3|sut\\rangle - \\langle pqr|\\hat{v}_3|tsu\\rangle - \\langle pqr|\\hat{v}_3|uts\\rangle.\n\\end{equation}\n$$\n\n## Hartree-Fock in second quantization and stability of HF solution\n\nWe wish now to derive the Hartree-Fock equations using our second-quantized formalism and study the stability of the equations. \nOur ansatz for the ground state of the system is approximated as (this is our representation of a Slater determinant in second quantization)\n\n$$\n|\\Phi_0\\rangle = |c\\rangle = a^{\\dagger}_i a^{\\dagger}_j \\dots a^{\\dagger}_l|0\\rangle.\n$$\n\nWe wish to determine $\\hat{u}^{HF}$ so that \n$E_0^{HF}= \\langle c|\\hat{H}| c\\rangle$ becomes a local minimum. \n\nIn our analysis here we will need Thouless' theorem, which states that\nan arbitrary Slater determinant $|c'\\rangle$ which is not orthogonal to a determinant\n$| c\\rangle ={\\displaystyle\\prod_{i=1}^{n}}\na_{\\alpha_{i}}^{\\dagger}|0\\rangle$, can be written as\n\n$$\n|c'\\rangle=exp\\left\\{\\sum_{a>F}\\sum_{i\\le F}C_{ai}a_{a}^{\\dagger}a_{i}\\right\\}| c\\rangle\n$$\n\nLet us give a simple proof of Thouless' theorem. The theorem states that we can make a linear combination av particle-hole excitations  with respect to a given reference state $\\vert c\\rangle$. With this linear combination, we can make a new Slater determinant $\\vert c'\\rangle $ which is not orthogonal to \n$\\vert c\\rangle$, that is\n\n$$\n\\langle c|c'\\rangle \\ne 0.\n$$\n\nTo show this we need some intermediate steps. The exponential product of two operators  $\\exp{\\hat{A}}\\times\\exp{\\hat{B}}$ is equal to $\\exp{(\\hat{A}+\\hat{B})}$ only if the two operators commute, that is\n\n$$\n[\\hat{A},\\hat{B}] = 0.\n$$\n\n### Thouless' theorem\n\n\nIf the operators do not commute, we need to resort to the [Baker-Campbell-Hauersdorf](http://www.encyclopediaofmath.org/index.php/Campbell%E2%80%93Hausdorff_formula). This relation states that\n\n$$\n\\exp{\\hat{C}}=\\exp{\\hat{A}}\\exp{\\hat{B}},\n$$\n\nwith\n\n$$\n\\hat{C}=\\hat{A}+\\hat{B}+\\frac{1}{2}[\\hat{A},\\hat{B}]+\\frac{1}{12}[[\\hat{A},\\hat{B}],\\hat{B}]-\\frac{1}{12}[[\\hat{A},\\hat{B}],\\hat{A}]+\\dots\n$$\n\nFrom these relations, we note that \nin our expression  for $|c'\\rangle$ we have commutators of the type\n\n$$\n[a_{a}^{\\dagger}a_{i},a_{b}^{\\dagger}a_{j}],\n$$\n\nand it is easy to convince oneself that these commutators, or higher powers thereof, are all zero. This means that we can write out our new representation of a Slater determinant as\n\n$$\n|c'\\rangle=exp\\left\\{\\sum_{a>F}\\sum_{i\\le F}C_{ai}a_{a}^{\\dagger}a_{i}\\right\\}| c\\rangle=\\prod_{i}\\left\\{1+\\sum_{a>F}C_{ai}a_{a}^{\\dagger}a_{i}+\\left(\\sum_{a>F}C_{ai}a_{a}^{\\dagger}a_{i}\\right)^2+\\dots\\right\\}| c\\rangle\n$$\n\nWe note that\n\n$$\n\\prod_{i}\\sum_{a>F}C_{ai}a_{a}^{\\dagger}a_{i}\\sum_{b>F}C_{bi}a_{b}^{\\dagger}a_{i}| c\\rangle =0,\n$$\n\nand all higher-order powers of these combinations of creation and annihilation operators disappear \ndue to the fact that $(a_i)^n| c\\rangle =0$ when $n > 1$. This allows us to rewrite the expression for $|c'\\rangle $ as\n\n$$\n|c'\\rangle=\\prod_{i}\\left\\{1+\\sum_{a>F}C_{ai}a_{a}^{\\dagger}a_{i}\\right\\}| c\\rangle,\n$$\n\nwhich we can rewrite as\n\n$$\n|c'\\rangle=\\prod_{i}\\left\\{1+\\sum_{a>F}C_{ai}a_{a}^{\\dagger}a_{i}\\right\\}| a^{\\dagger}_{i_1} a^{\\dagger}_{i_2} \\dots a^{\\dagger}_{i_n}|0\\rangle.\n$$\n\nThe last equation can be written as\n\n$$\n\\begin{equation}\n|c'\\rangle=\\prod_{i}\\left\\{1+\\sum_{a>F}C_{ai}a_{a}^{\\dagger}a_{i}\\right\\}| a^{\\dagger}_{i_1} a^{\\dagger}_{i_2} \\dots a^{\\dagger}_{i_n}|0\\rangle=\\left(1+\\sum_{a>F}C_{ai_1}a_{a}^{\\dagger}a_{i_1}\\right)a^{\\dagger}_{i_1} \n\\end{equation}\n$$\n\n$$\n\\begin{equation} \n \\times\\left(1+\\sum_{a>F}C_{ai_2}a_{a}^{\\dagger}a_{i_2}\\right)a^{\\dagger}_{i_2} \\dots |0\\rangle=\\prod_{i}\\left(a^{\\dagger}_{i}+\\sum_{a>F}C_{ai}a_{a}^{\\dagger}\\right)|0\\rangle.\n\\end{equation}\n$$\n\n### New operators\n\n\nIf we define a new creation operator\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:newb\"></div>\n\n$$\n\\begin{equation}\nb^{\\dagger}_{i}=a^{\\dagger}_{i}+\\sum_{a>F}C_{ai}a_{a}^{\\dagger}, \\label{eq:newb} \\tag{108}\n\\end{equation}\n$$\n\nwe have\n\n$$\n|c'\\rangle=\\prod_{i}b^{\\dagger}_{i}|0\\rangle=\\prod_{i}\\left(a^{\\dagger}_{i}+\\sum_{a>F}C_{ai}a_{a}^{\\dagger}\\right)|0\\rangle,\n$$\n\nmeaning that the new representation of the Slater determinant in second quantization, $|c'\\rangle$, looks like our previous ones. However, this representation is not general enough since we have a restriction on the sum over single-particle states in Eq. [(108)](#eq:newb). The single-particle states have all to be above the Fermi level.\nThe question then is whether we can construct a general representation of a Slater determinant with a creation operator\n\n$$\n\\tilde{b}^{\\dagger}_{i}=\\sum_{p}f_{ip}a_{p}^{\\dagger},\n$$\n\nwhere $f_{ip}$ is a matrix element of a unitary matrix which transforms our creation and annihilation operators\n$a^{\\dagger}$ and $a$ to $\\tilde{b}^{\\dagger}$ and $\\tilde{b}$. These new operators define a new representation of a Slater determinant as\n\n$$\n|\\tilde{c}\\rangle=\\prod_{i}\\tilde{b}^{\\dagger}_{i}|0\\rangle.\n$$\n\n### Showing that $|\\tilde{c}\\rangle= |c'\\rangle$\n\n\n\nWe need to show that $|\\tilde{c}\\rangle= |c'\\rangle$. We need also to assume that the new state\nis not orthogonal to $|c\\rangle$, that is $\\langle c| \\tilde{c}\\rangle \\ne 0$. From this it follows that\n\n$$\n\\langle c| \\tilde{c}\\rangle=\\langle 0| a_{i_n}\\dots a_{i_1}\\left(\\sum_{p=i_1}^{i_n}f_{i_1p}a_{p}^{\\dagger} \\right)\\left(\\sum_{q=i_1}^{i_n}f_{i_2q}a_{q}^{\\dagger} \\right)\\dots \\left(\\sum_{t=i_1}^{i_n}f_{i_nt}a_{t}^{\\dagger} \\right)|0\\rangle,\n$$\n\nwhich is nothing but the determinant $det(f_{ip})$ which we can, using the intermediate normalization condition, \nnormalize to one, that is\n\n$$\ndet(f_{ip})=1,\n$$\n\nmeaning that $f$ has an inverse defined as (since we are dealing with orthogonal, and in our case unitary as well, transformations)\n\n$$\n\\sum_{k} f_{ik}f^{-1}_{kj} = \\delta_{ij},\n$$\n\nand\n\n$$\n\\sum_{j} f^{-1}_{ij}f_{jk} = \\delta_{ik}.\n$$\n\nUsing these relations we can then define the linear combination of creation (and annihilation as well) \noperators as\n\n$$\n\\sum_{i}f^{-1}_{ki}\\tilde{b}^{\\dagger}_{i}=\\sum_{i}f^{-1}_{ki}\\sum_{p=i_1}^{\\infty}f_{ip}a_{p}^{\\dagger}=a_{k}^{\\dagger}+\\sum_{i}\\sum_{p=i_{n+1}}^{\\infty}f^{-1}_{ki}f_{ip}a_{p}^{\\dagger}.\n$$\n\nDefining\n\n$$\nc_{kp}=\\sum_{i \\le F}f^{-1}_{ki}f_{ip},\n$$\n\nwe can redefine\n\n$$\na_{k}^{\\dagger}+\\sum_{i}\\sum_{p=i_{n+1}}^{\\infty}f^{-1}_{ki}f_{ip}a_{p}^{\\dagger}=a_{k}^{\\dagger}+\\sum_{p=i_{n+1}}^{\\infty}c_{kp}a_{p}^{\\dagger}=b_k^{\\dagger},\n$$\n\nour starting point. We have shown that our general representation of a Slater determinant\n\n$$\n|\\tilde{c}\\rangle=\\prod_{i}\\tilde{b}^{\\dagger}_{i}|0\\rangle=|c'\\rangle=\\prod_{i}b^{\\dagger}_{i}|0\\rangle,\n$$\n\nwith\n\n$$\nb_k^{\\dagger}=a_{k}^{\\dagger}+\\sum_{p=i_{n+1}}^{\\infty}c_{kp}a_{p}^{\\dagger}.\n$$\n\nThis means that we can actually write an ansatz for the ground state of the system as a linear combination of\nterms which contain the ansatz itself $|c\\rangle$ with  an admixture from an infinity of one-particle-one-hole states. The latter has important consequences when we wish to interpret the Hartree-Fock equations and their stability. We can rewrite the new representation as\n\n$$\n|c'\\rangle = |c\\rangle+|\\delta c\\rangle,\n$$\n\nwhere $|\\delta c\\rangle$ can now be interpreted as a small variation. If we approximate this term with \ncontributions from one-particle-one-hole (*1p-1h*) states only, we arrive at\n\n$$\n|c'\\rangle = \\left(1+\\sum_{ai}\\delta C_{ai}a_{a}^{\\dagger}a_i\\right)|c\\rangle.\n$$\n\nIn our derivation of the Hartree-Fock equations we have shown that\n\n$$\n\\langle \\delta c| \\hat{H} | c\\rangle =0,\n$$\n\nwhich means that we have to satisfy\n\n$$\n\\langle c|\\sum_{ai}\\delta C_{ai}\\left\\{a_{a}^{\\dagger}a_i\\right\\} \\hat{H} | c\\rangle =0.\n$$\n\nWith this as a background, we are now ready to study the stability of the Hartree-Fock equations.\n\n\n\n### Hartree-Fock in second quantization and stability of HF solution\n\nThe variational condition for deriving the Hartree-Fock equations guarantees only that the expectation value $\\langle c | \\hat{H} | c \\rangle$ has an extreme value, not necessarily a minimum. To figure out whether the extreme value we have found  is a minimum, we can use second quantization to analyze our results and find a criterion \nfor the above expectation value to a local minimum. We will use Thouless' theorem and show that\n\n$$\n\\frac{\\langle c' |\\hat{H} | c'\\rangle}{\\langle c' |c'\\rangle} \\ge \\langle c |\\hat{H} | c\\rangle= E_0,\n$$\n\nwith\n\n$$\n{|c'\\rangle} = {|c\\rangle + |\\delta c\\rangle}.\n$$\n\nUsing Thouless' theorem we can write out ${|c'\\rangle}$ as\n\n$$\n\\begin{equation}\n {|c'\\rangle}=\\exp\\left\\{\\sum_{a > F}\\sum_{i \\le F}\\delta C_{ai}a_{a}^{\\dagger}a_{i}\\right\\}| c\\rangle\n\\end{equation}\n$$\n\n$$\n\\begin{equation}  \n=\\left\\{1+\\sum_{a > F}\\sum_{i \\le F}\\delta C_{ai}a_{a}^{\\dagger}\na_{i}+\\frac{1}{2!}\\sum_{ab > F}\\sum_{ij \\le F}\\delta C_{ai}\\delta C_{bj}a_{a}^{\\dagger}a_{i}a_{b}^{\\dagger}a_{j}+\\dots\\right\\}\n\\end{equation}\n$$\n\nwhere the amplitudes $\\delta C$ are small.\n\n\nThe norm of $|c'\\rangle$ is given by (using the intermediate normalization condition $\\langle c' |c\\rangle=1$)\n\n$$\n\\langle c' | c'\\rangle = 1+\\sum_{a>F}\n\\sum_{i\\le F}|\\delta C_{ai}|^2+O(\\delta C_{ai}^3).\n$$\n\nThe expectation value for the energy is now given by (using the Hartree-Fock condition)\n\n3\n7\n6\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\frac{1}{2!}\\sum_{ab>F}\n\\sum_{ij\\le F}\\delta C_{ai}\\delta C_{bj}\\langle c |\\hat{H}a_{a}^{\\dagger}a_{i}a_{b}^{\\dagger}a_{j}|c\\rangle+\\frac{1}{2!}\\sum_{ab>F}\n\\sum_{ij\\le F}\\delta C_{ai}^*\\delta C_{bj}^*\\langle c|a_{j}^{\\dagger}a_{b}a_{i}^{\\dagger}a_{a}\\hat{H}|c\\rangle\n+\\dots\n$$\n\nWe have already calculated the second term on the right-hand side of the previous equation\n\n$$\n\\begin{equation}\n\\langle c | \\left(\\{a^\\dagger_i a_a\\} \\hat{H} \\{a^\\dagger_b a_j\\} \\right) | c\\rangle=\\sum_{pq} \\sum_{ijab}\\delta C_{ai}^*\\delta C_{bj} \\langle p|\\hat{h}_0 |q\\rangle \n            \\langle c | \\left(\\{a^{\\dagger}_i a_a\\}\\{a^{\\dagger}_pa_q\\} \n             \\{a^{\\dagger}_b a_j\\} \\right)| c\\rangle\n\\end{equation}\n$$\n\n$$\n\\begin{equation} \n +\\frac{1}{4} \\sum_{pqrs} \\sum_{ijab}\\delta C_{ai}^*\\delta C_{bj} \\langle pq| \\hat{v}|rs\\rangle \n            \\langle c | \\left(\\{a^\\dagger_i a_a\\}\\{a^{\\dagger}_p a^{\\dagger}_q a_s  a_r\\} \\{a^{\\dagger}_b a_j\\} \\right)| c\\rangle ,\n\\end{equation}\n$$\n\nresulting in\n\n$$\nE_0\\sum_{ai}|\\delta C_{ai}|^2+\\sum_{ai}|\\delta C_{ai}|^2(\\varepsilon_a-\\varepsilon_i)-\\sum_{ijab} \\langle aj|\\hat{v}| bi\\rangle \\delta C_{ai}^*\\delta C_{bj}.\n$$\n\n$$\n\\frac{1}{2!}\\langle c |\\left(\\{a^\\dagger_j a_b\\} \\{a^\\dagger_i a_a\\} \\hat{V}_N  \\right) | c\\rangle  = \n\\frac{1}{2!}\\langle c |\\left( \\hat{V}_N \\{a^\\dagger_a a_i\\} \\{a^\\dagger_b a_j\\} \\right)^{\\dagger} | c\\rangle\n$$\n\nwhich is nothing but\n\n$$\n\\frac{1}{2!}\\langle c |  \\left( \\hat{V}_N \\{a^\\dagger_a a_i\\} \\{a^\\dagger_b a_j\\} \\right) | c\\rangle^*\n=\\frac{1}{2} \\sum_{ijab} (\\langle ij|\\hat{v}|ab\\rangle)^*\\delta C_{ai}^*\\delta C_{bj}^*\n$$\n\nor\n\n$$\n\\frac{1}{2} \\sum_{ijab} (\\langle ab|\\hat{v}|ij\\rangle)\\delta C_{ai}^*\\delta C_{bj}^*\n$$\n\nwhere we have used the relation\n\n$$\n\\langle a |\\hat{A} | b\\rangle =  (\\langle b |\\hat{A}^{\\dagger} | a\\rangle)^*\n$$\n\ndue to the hermiticity of $\\hat{H}$ and $\\hat{V}$.\n\n\nWe define two matrix elements\n\n$$\nA_{ai,bj}=-\\langle aj|\\hat{v} bi\\rangle\n$$\n\nand\n\n$$\nB_{ai,bj}=\\langle ab|\\hat{v}|ij\\rangle\n$$\n\nboth being anti-symmetrized.\n\n\n\nWith these definitions we write out the energy as\n\n$$\n\\begin{equation}\n\\langle c'|H|c'\\rangle = \\left(1+\\sum_{ai}|\\delta C_{ai}|^2\\right)\\langle c |H|c\\rangle+\\sum_{ai}|\\delta C_{ai}|^2(\\varepsilon_a^{HF}-\\varepsilon_i^{HF})+\\sum_{ijab}A_{ai,bj}\\delta C_{ai}^*\\delta C_{bj}+\n\\end{equation}\n$$\n\n$$\n\\begin{equation} \n\\frac{1}{2} \\sum_{ijab} B_{ai,bj}^*\\delta C_{ai}\\delta C_{bj}+\\frac{1}{2} \\sum_{ijab} B_{ai,bj}\\delta C_{ai}^*\\delta C_{bj}^*\n+O(\\delta C_{ai}^3),\n\\end{equation}\n$$\n\nwhich can be rewritten as\n\n$$\n\\langle c'|H|c'\\rangle = \\left(1+\\sum_{ai}|\\delta C_{ai}|^2\\right)\\langle c |H|c\\rangle+\\Delta E+O(\\delta C_{ai}^3),\n$$\n\nand skipping higher-order terms we arrived\n\n$$\n\\frac{\\langle c' |\\hat{H} | c'\\rangle}{\\langle c' |c'\\rangle} =E_0+\\frac{\\Delta E}{\\left(1+\\sum_{ai}|\\delta C_{ai}|^2\\right)}.\n$$\n\nWe have defined\n\n$$\n\\Delta E = \\frac{1}{2} \\langle \\chi | \\hat{M}| \\chi \\rangle\n$$\n\nwith the vectors\n\n$$\n\\chi = \\left[ \\delta C\\hspace{0.2cm} \\delta C^*\\right]^T\n$$\n\nand the matrix\n\n$$\n\\hat{M}=\\left(\\begin{array}{cc} \\Delta + A & B \\\\ B^* & \\Delta + A^*\\end{array}\\right),\n$$\n\nwith $\\Delta_{ai,bj} = (\\varepsilon_a-\\varepsilon_i)\\delta_{ab}\\delta_{ij}$.\n\n\n\nThe condition\n\n$$\n\\Delta E = \\frac{1}{2} \\langle \\chi | \\hat{M}| \\chi \\rangle \\ge 0\n$$\n\nfor an arbitrary  vector\n\n$$\n\\chi = \\left[ \\delta C\\hspace{0.2cm} \\delta C^*\\right]^T\n$$\n\nmeans that all eigenvalues of the matrix have to be larger than or equal zero. \nA necessary (but no sufficient) condition is that the matrix elements (for all $ai$ )\n\n$$\n(\\varepsilon_a-\\varepsilon_i)\\delta_{ab}\\delta_{ij}+A_{ai,bj} \\ge 0.\n$$\n\nThis equation can be used as a first test of the stability of the Hartree-Fock equation.\n\n\n\n\n\n\n\n## Operators in second quantization\n\nIn the build-up of a shell-model or FCI code that is meant to tackle large dimensionalities\nis the action of the Hamiltonian $\\hat{H}$ on a\nSlater determinant represented in second quantization as\n\n$$\n|\\alpha_1\\dots \\alpha_n\\rangle = a_{\\alpha_1}^{\\dagger} a_{\\alpha_2}^{\\dagger} \\dots a_{\\alpha_n}^{\\dagger} |0\\rangle.\n$$\n\nThe time consuming part stems from the action of the Hamiltonian\non the above determinant,\n\n$$\n\\left(\\sum_{\\alpha\\beta} \\langle \\alpha|t+u|\\beta\\rangle a_\\alpha^{\\dagger} a_\\beta + \\frac{1}{4} \\sum_{\\alpha\\beta\\gamma\\delta}\n                \\langle \\alpha \\beta|\\hat{v}|\\gamma \\delta\\rangle a_\\alpha^{\\dagger} a_\\beta^{\\dagger} a_\\delta a_\\gamma\\right)a_{\\alpha_1}^{\\dagger} a_{\\alpha_2}^{\\dagger} \\dots a_{\\alpha_n}^{\\dagger} |0\\rangle.\n$$\n\nA practically useful way to implement this action is to encode a Slater determinant as a bit pattern.\n\n\n\nAssume that we have at our disposal $n$ different single-particle orbits\n$\\alpha_0,\\alpha_2,\\dots,\\alpha_{n-1}$ and that we can distribute  among these orbits $N\\le n$ particles.\n\nA Slater  determinant can then be coded as an integer of $n$ bits. As an example, if we have $n=16$ single-particle states\n$\\alpha_0,\\alpha_1,\\dots,\\alpha_{15}$ and $N=4$ fermions occupying the states $\\alpha_3$, $\\alpha_6$, $\\alpha_{10}$ and $\\alpha_{13}$\nwe could write this Slater determinant as\n\n$$\n\\Phi_{\\Lambda} = a_{\\alpha_3}^{\\dagger} a_{\\alpha_6}^{\\dagger} a_{\\alpha_{10}}^{\\dagger} a_{\\alpha_{13}}^{\\dagger} |0\\rangle.\n$$\n\nThe unoccupied single-particle states have bit value $0$ while the occupied ones are represented by bit state $1$. \nIn the binary notation we would write this   16 bits long integer as\n\n$$\n\\begin{array}{cccccccccccccccc}\n{\\alpha_0}&{\\alpha_1}&{\\alpha_2}&{\\alpha_3}&{\\alpha_4}&{\\alpha_5}&{\\alpha_6}&{\\alpha_7} & {\\alpha_8} &{\\alpha_9} & {\\alpha_{10}} &{\\alpha_{11}} &{\\alpha_{12}} &{\\alpha_{13}} &{\\alpha_{14}} & {\\alpha_{15}} \\\\\n{0} & {0} &{0} &{1} &{0} &{0} &{1} &{0} &{0} &{0} &{1} &{0} &{0} &{1} &{0} & {0} \\\\\n\\end{array}\n$$\n\nwhich translates into the decimal number\n\n$$\n2^3+2^6+2^{10}+2^{13}=9288.\n$$\n\nWe can thus encode a Slater determinant as a bit pattern.\n\n\n\nWith $N$ particles that can be distributed over $n$ single-particle states, the total number of Slater determinats (and defining thereby the dimensionality of the system) is\n\n$$\n\\mathrm{dim}(\\mathcal{H}) = \\left(\\begin{array}{c} n \\\\N\\end{array}\\right).\n$$\n\nThe total number of bit patterns is $2^n$. \n\n\nWe assume again that we have at our disposal $n$ different single-particle orbits\n$\\alpha_0,\\alpha_2,\\dots,\\alpha_{n-1}$ and that we can distribute  among these orbits $N\\le n$ particles.\nThe ordering among these states is important as it defines the order of the creation operators.\nWe will write the determinant\n\n$$\n\\Phi_{\\Lambda} = a_{\\alpha_3}^{\\dagger} a_{\\alpha_6}^{\\dagger} a_{\\alpha_{10}}^{\\dagger} a_{\\alpha_{13}}^{\\dagger} |0\\rangle,\n$$\n\nin a more compact way as\n\n$$\n\\Phi_{3,6,10,13} = |0001001000100100\\rangle.\n$$\n\nThe action of a creation operator is thus\n\n$$\na^{\\dagger}_{\\alpha_4}\\Phi_{3,6,10,13} = a^{\\dagger}_{\\alpha_4}|0001001000100100\\rangle=a^{\\dagger}_{\\alpha_4}a_{\\alpha_3}^{\\dagger} a_{\\alpha_6}^{\\dagger} a_{\\alpha_{10}}^{\\dagger} a_{\\alpha_{13}}^{\\dagger} |0\\rangle,\n$$\n\nwhich becomes\n\n$$\n-a_{\\alpha_3}^{\\dagger} a^{\\dagger}_{\\alpha_4} a_{\\alpha_6}^{\\dagger} a_{\\alpha_{10}}^{\\dagger} a_{\\alpha_{13}}^{\\dagger} |0\\rangle=-|0001101000100100\\rangle.\n$$\n\nSimilarly\n\n$$\na^{\\dagger}_{\\alpha_6}\\Phi_{3,6,10,13} = a^{\\dagger}_{\\alpha_6}|0001001000100100\\rangle=a^{\\dagger}_{\\alpha_6}a_{\\alpha_3}^{\\dagger} a_{\\alpha_6}^{\\dagger} a_{\\alpha_{10}}^{\\dagger} a_{\\alpha_{13}}^{\\dagger} |0\\rangle,\n$$\n\nwhich becomes\n\n$$\n-a^{\\dagger}_{\\alpha_4} (a_{\\alpha_6}^{\\dagger})^ 2 a_{\\alpha_{10}}^{\\dagger} a_{\\alpha_{13}}^{\\dagger} |0\\rangle=0!\n$$\n\nThis gives a simple recipe:  \n* If one of the bits $b_j$ is $1$ and we act with a creation operator on this bit, we return a null vector\n\n* If $b_j=0$, we set it to $1$ and return a sign factor $(-1)^l$, where $l$ is the number of bits set before bit $j$.\n\nConsider the action of $a^{\\dagger}_{\\alpha_2}$ on various slater determinants:\n\n$$\n\\begin{array}{ccc}\na^{\\dagger}_{\\alpha_2}\\Phi_{00111}& = a^{\\dagger}_{\\alpha_2}|00111\\rangle&=0\\times |00111\\rangle\\\\\na^{\\dagger}_{\\alpha_2}\\Phi_{01011}& = a^{\\dagger}_{\\alpha_2}|01011\\rangle&=(-1)\\times |01111\\rangle\\\\\na^{\\dagger}_{\\alpha_2}\\Phi_{01101}& = a^{\\dagger}_{\\alpha_2}|01101\\rangle&=0\\times |01101\\rangle\\\\\na^{\\dagger}_{\\alpha_2}\\Phi_{01110}& = a^{\\dagger}_{\\alpha_2}|01110\\rangle&=0\\times |01110\\rangle\\\\\na^{\\dagger}_{\\alpha_2}\\Phi_{10011}& = a^{\\dagger}_{\\alpha_2}|10011\\rangle&=(-1)\\times |10111\\rangle\\\\\na^{\\dagger}_{\\alpha_2}\\Phi_{10101}& = a^{\\dagger}_{\\alpha_2}|10101\\rangle&=0\\times |10101\\rangle\\\\\na^{\\dagger}_{\\alpha_2}\\Phi_{10110}& = a^{\\dagger}_{\\alpha_2}|10110\\rangle&=0\\times |10110\\rangle\\\\\na^{\\dagger}_{\\alpha_2}\\Phi_{11001}& = a^{\\dagger}_{\\alpha_2}|11001\\rangle&=(+1)\\times |11101\\rangle\\\\\na^{\\dagger}_{\\alpha_2}\\Phi_{11010}& = a^{\\dagger}_{\\alpha_2}|11010\\rangle&=(+1)\\times |11110\\rangle\\\\\n\\end{array}\n$$\n\nWhat is the simplest way to obtain the phase when we act with one annihilation(creation) operator\non the given Slater determinant representation?\n\n\n\n\nWe have an SD representation\n\n$$\n\\Phi_{\\Lambda} = a_{\\alpha_0}^{\\dagger} a_{\\alpha_3}^{\\dagger} a_{\\alpha_6}^{\\dagger} a_{\\alpha_{10}}^{\\dagger} a_{\\alpha_{13}}^{\\dagger} |0\\rangle,\n$$\n\nin a more compact way as\n\n$$\n\\Phi_{0,3,6,10,13} = |1001001000100100\\rangle.\n$$\n\nThe action of\n\n$$\na^{\\dagger}_{\\alpha_4}a_{\\alpha_0}\\Phi_{0,3,6,10,13} = a^{\\dagger}_{\\alpha_4}|0001001000100100\\rangle=a^{\\dagger}_{\\alpha_4}a_{\\alpha_3}^{\\dagger} a_{\\alpha_6}^{\\dagger} a_{\\alpha_{10}}^{\\dagger} a_{\\alpha_{13}}^{\\dagger} |0\\rangle,\n$$\n\nwhich becomes\n\n$$\n-a_{\\alpha_3}^{\\dagger} a^{\\dagger}_{\\alpha_4} a_{\\alpha_6}^{\\dagger} a_{\\alpha_{10}}^{\\dagger} a_{\\alpha_{13}}^{\\dagger} |0\\rangle=-|0001101000100100\\rangle.\n$$\n\nThe action\n\n$$\na_{\\alpha_0}\\Phi_{0,3,6,10,13} = |0001001000100100\\rangle,\n$$\n\ncan be obtained by subtracting the logical sum (AND operation) of $\\Phi_{0,3,6,10,13}$ and \na word which represents only $\\alpha_0$, that is\n\n$$\n|1000000000000000\\rangle,\n$$\n\nfrom $\\Phi_{0,3,6,10,13}= |1001001000100100\\rangle$.\n\nThis operation gives $|0001001000100100\\rangle$. \n\nSimilarly, we can form $a^{\\dagger}_{\\alpha_4}a_{\\alpha_0}\\Phi_{0,3,6,10,13}$, say, by adding \n$|0000100000000000\\rangle$ to $a_{\\alpha_0}\\Phi_{0,3,6,10,13}$, first checking that their logical sum\nis zero in order to make sure that orbital $\\alpha_4$ is not already occupied. \n\n\n\n\n\n\n\nIt is trickier however to get the phase $(-1)^l$. \nOne possibility is as follows\n* Let $S_1$ be a word that represents the $1-$bit to be removed and all others set to zero.\n\nIn the previous example $S_1=|1000000000000000\\rangle$\n* Define $S_2$ as the similar word that represents the bit to be added, that is in our case\n\n$S_2=|0000100000000000\\rangle$.\n* Compute then $S=S_1-S_2$, which here becomes\n\n$$\nS=|0111000000000000\\rangle\n$$\n\n* Perform then the logical AND operation of $S$ with the word containing\n\n$$\n\\Phi_{0,3,6,10,13} = |1001001000100100\\rangle,\n$$\n\nwhich results in $|0001000000000000\\rangle$. Counting the number of $1-$bits gives the phase.  Here you need however an algorithm for bitcounting. Several efficient ones available. \n\n\n\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 7: Relation between basis functions\n\nThis exercise serves to convince you about the relation between\ntwo different single-particle bases, where one could be our new Hartree-Fock basis and the other a harmonic oscillator basis.\n\nConsider a Slater determinant built up of single-particle orbitals $\\psi_{\\lambda}$, \nwith $\\lambda = 1,2,\\dots,A$. The unitary transformation\n\n$$\n\\psi_a  = \\sum_{\\lambda} C_{a\\lambda}\\phi_{\\lambda},\n$$\n\nbrings us into the new basis.  \nThe new basis has quantum numbers $a=1,2,\\dots,A$.\nShow that the new basis is orthonormal.\nShow that the new Slater determinant constructed from the new single-particle wave functions can be\nwritten as the determinant based on the previous basis and the determinant of the matrix $C$.\nShow that the old and the new Slater determinants are equal up to a complex constant with absolute value unity.\n(Hint, $C$ is a unitary matrix). \n\nStarting with the second quantization representation of the Slater determinant\n\n$$\n\\Phi_{0}=\\prod_{i=1}^{n}a_{\\alpha_{i}}^{\\dagger}|0\\rangle,\n$$\n\nuse Wick's theorem to compute the normalization integral\n$\\langle\\Phi_{0}|\\Phi_{0}\\rangle$.\n\n<!-- --- end exercise --- -->\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 8: Matrix elements\n\nCalculate the matrix elements\n\n$$\n\\langle \\alpha_{1}\\alpha_{2}|\\hat{F}|\\alpha_{1}\\alpha_{2}\\rangle\n$$\n\nand\n\n$$\n\\langle \\alpha_{1}\\alpha_{2}|\\hat{G}|\\alpha_{1}\\alpha_{2}\\rangle\n$$\n\nwith\n\n4\n2\n2\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n4\n2\n3\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n4\n2\n4\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\hat{G} = \\frac{1}{2}\\sum_{\\alpha\\beta\\gamma\\delta}\n\\langle \\alpha\\beta |\\hat{g}|\\gamma\\delta\\rangle\na_{\\alpha}^{\\dagger}a_{\\beta}^{\\dagger}a_{\\delta}a_{\\gamma} ,\n$$\n\nand\n\n$$\n\\langle \\alpha\\beta |\\hat{g}|\\gamma\\delta\\rangle=\n\\int\\int \\psi_{\\alpha}^{*}(x_{1})\\psi_{\\beta}^{*}(x_{2})g(x_{1},\nx_{2})\\psi_{\\gamma}(x_{1})\\psi_{\\delta}(x_{2})dx_{1}dx_{2}\n$$\n\nCompare these results with those from exercise 3c).\n\n<!-- --- end exercise --- -->\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 9: Normal-ordered one-body operator\n\nShow that the onebody part of the Hamiltonian\n\n$$\n\\hat{H}_0 = \\sum_{pq} \\langle p|\\hat{h}_0|q\\rangle a^{\\dagger}_p a_q,\n$$\n\ncan be written, using standard annihilation and creation operators, in normal-ordered form as\n\n$$\n\\hat{H}_0 = \\sum_{pq} \\langle p|\\hat{h}_0|q\\rangle \\left\\{a^\\dagger_p a_q\\right\\} +\n             \\sum_i \\langle i|\\hat{h}_0|i\\rangle.\n$$\n\nExplain the meaning of the various symbols. Which reference \nvacuum has been used?\n\n<!-- --- end exercise --- -->\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 10: Normal-ordered two-body operator\n\nShow that the twobody part of the Hamiltonian\n\n$$\n\\hat{H}_I = \\frac{1}{4} \\sum_{pqrs} \\langle pq|\\hat{v}|rs\\rangle a^\\dagger_p a^\\dagger_q a_s  a_r,\n$$\n\ncan be written, using standard annihilation and creation operators, in normal-ordered form as\n\n$$\n\\hat{H}_I =\\frac{1}{4} \\sum_{pqrs} \\langle pq|\\hat{v}|rs\\rangle \\left\\{a^\\dagger_p a^\\dagger_q a_s  a_r\\right\\}\n            + \\sum_{pqi} \\langle pi|\\hat{v}|qi\\rangle \\left\\{a^\\dagger_p a_q\\right\\} \n            + \\frac{1}{2} \\sum_{ij}\\langle ij|\\hat{v}|ij\\rangle.\n$$\n\nExplain again the meaning of the various symbols.\n\nThis exercise is optional: Derive the normal-ordered form of the threebody part of the Hamiltonian.\n\n$$\n\\hat{H}_3 = \\frac{1}{36} \\sum_{\\substack{pqr \\\\ stu}}\n                 \\langle pqr|\\hat{v}_3|stu\\rangle a^\\dagger_p a^\\dagger_q a^\\dagger_r a_u a_t a_s,\n$$\n\nand specify the contributions to the twobody, onebody and the scalar part.\n\n<!-- --- end exercise --- -->\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 11: Matrix elements using the Slater-Condon rule\n\nThe aim of this exercise is to set up specific matrix elements that will turn useful when we start our discussions of the nuclear shell model. In particular you will notice, depending on the character of the operator, that many matrix elements will actually be zero.\n\nConsider three $N$-particle  Slater determinants  $|\\Phi_0$, $|\\Phi_i^a\\rangle$ and $|\\Phi_{ij}^{ab}\\rangle$, where the notation means that \nSlater determinant $|\\Phi_i^a\\rangle$ differs from $|\\Phi_0\\rangle$ by one single-particle state, that is a single-particle\nstate $\\psi_i$ is replaced by a single-particle state $\\psi_a$. \nIt is often interpreted as a so-called one-particle-one-hole excitation.\nSimilarly, the Slater determinant $|\\Phi_{ij}^{ab}\\rangle$\ndiffers by two single-particle states from $|\\Phi_0\\rangle$ and is normally thought of as a two-particle-two-hole excitation.\nWe assume also that $|\\Phi_0\\rangle$ represents our new vacuum reference state\nand the labels $ijk\\dots$ represent single-particle states below the Fermi level and $abc\\dots$ represent states above the Fermi level, so-called particle states.\nWe define thereafter a general onebody normal-ordered (with respect to the new vacuum state) operator \nas\n\n$$\n\\hat{F}_N=\\sum_{pq}\\langle p |f |\\beta\\rangle \\left\\{a_{p}^{\\dagger}a_{q}\\right\\}  ,\n$$\n\nwith\n\n$$\n\\langle p |f| q\\rangle=\\int \\psi_{p}^{*}(x)f(x)\\psi_{q}(x)dx ,\n$$\n\nand a general normal-ordered two-body operator\n\n$$\n\\hat{G}_N = \\frac{1}{4}\\sum_{pqrs}\n\\langle pq |g| rs\\rangle_{AS} \\left\\{a_{p}^{\\dagger}a_{q}^{\\dagger}a_{s}a_{r}\\right\\} ,\n$$\n\nwith for example the direct matrix element given as\n\n$$\n\\langle pq |g| rs\\rangle=\n\\int\\int \\psi_{p}^{*}(x_{1})\\psi_{q}^{*}(x_{2})g(x_{1}, x_{2})\\psi_{r}(x_{1})\\psi_{s}(x_{2})dx_{1}dx_{2}\n$$\n\nwith $g$ being invariant under the interchange of the coordinates of two particles.\nThe single-particle states $\\psi_i$ are not necessarily eigenstates of $\\hat{f}$.  The curly brackets mean that the operators are normal-ordered with respect to the new vacuum reference state. \n\nHow would you write the above Slater determinants in a second quantization formalism, utilizing the fact that we have defined a new reference state? \n\nUse thereafter Wick's theorem to find the expectation values of\n\n$$\n\\langle \\Phi_0 \\vert\\hat{F}_N\\vert\\Phi_0\\rangle,\n$$\n\nand\n\n$$\n\\langle \\Phi_0\\hat{G}_N|\\Phi_0\\rangle.\n$$\n\nFind thereafter\n\n$$\n\\langle \\Phi_0 |\\hat{F}_N|\\Phi_i^a\\rangle,\n$$\n\nand\n\n$$\n\\langle \\Phi_0|\\hat{G}_N|\\Phi_i^a\\rangle,\n$$\n\nFinally, find\n\n$$\n\\langle \\Phi_0 |\\hat{F}_N|\\Phi_{ij}^{ab}\\rangle,\n$$\n\nand\n\n$$\n\\langle \\Phi_0|\\hat{G}_N|\\Phi_{ij}^{ab}\\rangle.\n$$\n\nWhat happens with the two-body operator if we have a transition probability  of the type\n\n$$\n\\langle \\Phi_0|\\hat{G}_N|\\Phi_{ijk}^{abc}\\rangle,\n$$\n\nwhere the Slater determinant to the right of the operator differs by more than two single-particle states?\n\n<!-- --- end exercise --- -->\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 12: Program to set up Slater determinants\n\nWrite a program which sets up all possible Slater determinants given $N=4$ eletrons which can occupy\nthe atomic single-particle states defined by the $1s$, $2s2p$ and $3s3p3d$ shells. How many single-particle\nstates $n$ are there in total?  Include the spin degrees of freedom as well.\n\n<!-- --- end exercise --- -->\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 13: Using sympy to compute matrix elements\n\nCompute the matrix element\n\n$$\n\\langle\\alpha_{1}\\alpha_{2}\\alpha_{3}|\\hat{G}|\\alpha_{1}'\\alpha_{2}'\\alpha_{3}'\\rangle,\n$$\n\nusing Wick's theorem and express the two-body operator\n$G$ in the occupation number (second quantization) \nrepresentation.\n\n<!-- --- end exercise --- -->\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 14: Using sympy to compute matrix elements\n\nThe last exercise can be solved using the symbolic Python package called *SymPy*. SymPy is a Python \npackage for general purpose symbolic algebra. There is a physics module with several interesting submodules.\nAmong these, the submodule called *secondquant*, contains several  functionalities that allow us to test\nour algebraic manipulations using Wick's theorem and operators for second quantization.\n\n\n```\nfrom sympy import *\nfrom sympy.physics.secondquant import *\n\ni, j = symbols('i,j', below_fermi=True)\na, b = symbols('a,b', above_fermi=True)\np, q = symbols('p,q')\nprint simplify(wicks(Fd(i)*F(a)*Fd(p)*F(q)*Fd(b)*F(j), keep_only_fully_contracted=True))\n\n```\n\nThe code defines single-particle states above and below the Fermi level, in addition to the genereal symbols\n$pq$ which can refer to any type of state below or above the Fermi level. Wick's theorem is implemented between \nthe creation and annihilation operators *Fd* and *F*, respectively. Using the simplify option, one can lump together several Kronecker-$\\delta$ functions.\n\n<!-- --- end exercise --- -->\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 15: Using sympy to compute matrix elements\n\nWe can expand the above Python code by defining one-body and two-body operators using  the following SymPy code\n\n\n```\n# This code sets up a two-body Hamiltonian for fermions\nfrom sympy import symbols, latex, WildFunction, collect, Rational\nfrom sympy.physics.secondquant import F, Fd, wicks, AntiSymmetricTensor, substitute_dummies, NO\n\n# setup hamiltonian\np,q,r,s = symbols('p q r s',dummy=True)\nf = AntiSymmetricTensor('f',(p,),(q,))\npr = NO((Fd(p)*F(q)))\nv = AntiSymmetricTensor('v',(p,q),(r,s))\npqsr = NO(Fd(p)*Fd(q)*F(s)*F(r))\nHamiltonian=f*pr + Rational(1)/Rational(4)*v*pqsr\nprint \"Hamiltonian defined as:\", latex(Hamiltonian)\n\n```\n\nHere we have used the *AntiSymmetricTensor* functionality, together with normal-ordering defined by the *NO* function. \nUsing the *latex* option, this program produces the following output\n\n$$\nf^{p}_{q} \\left\\{a^\\dagger_{p} a_{q}\\right\\} - \\frac{1}{4} v^{qp}_{sr} \\left\\{a^\\dagger_{p} a^\\dagger_{q} a_{r} a_{s}\\right\\}\n$$\n\n<!-- --- end exercise --- -->\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 16: Using sympy to compute matrix elements\n\nWe can now use this code to compute the matrix elements between two two-body Slater determinants using Wick's theorem.\n\n\n```\nfrom sympy import symbols, latex, WildFunction, collect, Rational, simplify\nfrom sympy.physics.secondquant import F, Fd, wicks, AntiSymmetricTensor, substitute_dummies, NO, evaluate_deltas\n# setup hamiltonian\np,q,r,s = symbols('p q r s',dummy=True)\nf = AntiSymmetricTensor('f',(p,),(q,))\npr = NO((Fd(p)*F(q)))\nv = AntiSymmetricTensor('v',(p,q),(r,s))\npqsr = NO(Fd(p)*Fd(q)*F(s)*F(r))\nHamiltonian=f*pr + Rational(1)/Rational(4)*v*pqsr\nc,d = symbols('c, d',above_fermi=True)\na,b = symbols('a, b',above_fermi=True)\n\nexpression = wicks(F(b)*F(a)*Hamiltonian*Fd(c)*Fd(d),keep_only_fully_contracted=True, simplify_kronecker_deltas=True)\nexpression = evaluate_deltas(expression)\nexpression = simplify(expression)\nprint \"Hamiltonian defined as:\", latex(expression)\n\n```\n\nThe result is as expected,\n\n$$\n\\delta_{a c} f^{b}_{d} - \\delta_{a d} f^{b}_{c} - \\delta_{b c} f^{a}_{d} + \\delta_{b d} f^{a}_{c} + v^{ab}_{cd}.\n$$\n\n<!-- --- end exercise --- -->\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 17: Using sympy to compute matrix elements\n\nWe can continue along these lines and define a normal-ordered Hamiltonian with respect to a given reference state.\nIn our first step we just define the Hamiltonian\n\n\n```\nfrom sympy import symbols, latex, WildFunction, collect, Rational, simplify\nfrom sympy.physics.secondquant import F, Fd, wicks, AntiSymmetricTensor, substitute_dummies, NO, evaluate_deltas\n# setup hamiltonian\np,q,r,s = symbols('p q r s',dummy=True)\nf = AntiSymmetricTensor('f',(p,),(q,))\npr = Fd(p)*F(q)\nv = AntiSymmetricTensor('v',(p,q),(r,s))\npqsr = Fd(p)*Fd(q)*F(s)*F(r)\n#define the Hamiltonian\nHamiltonian = f*pr + Rational(1)/Rational(4)*v*pqsr\n#define indices for states above and below the Fermi level\nindex_rule = {\n     'below':  'kl',\n     'above':  'cd',\n     'general': 'pqrs'\n     }\nHnormal = substitute_dummies(Hamiltonian,new_indices=True, pretty_indices=index_rule)\nprint \"Hamiltonian defined as:\", latex(Hnormal)\n\n```\n\nwhich results in\n\n$$\nf^{q}_{p} a^\\dagger_{q} a_{p} + \\frac{1}{4} v^{sr}_{qp} a^\\dagger_{s} a^\\dagger_{r} a_{p} a_{q}\n$$\n\n<!-- --- end exercise --- -->\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 18: Using sympy to compute matrix elements\n\nIn our next step we define the reference energy $E_0$ and redefine the Hamiltonian by subtracting the reference energy and collecting the coefficients for all normal-ordered products (given by the *NO* function).\n\n\n```\nfrom sympy import symbols, latex, WildFunction, collect, Rational, simplify\nfrom sympy.physics.secondquant import F, Fd, wicks, AntiSymmetricTensor, substitute_dummies, NO, evaluate_deltas\n# setup hamiltonian\np,q,r,s = symbols('p q r s',dummy=True)\nf = AntiSymmetricTensor('f',(p,),(q,))\npr = Fd(p)*F(q)\nv = AntiSymmetricTensor('v',(p,q),(r,s))\npqsr = Fd(p)*Fd(q)*F(s)*F(r)\n#define the Hamiltonian\nHamiltonian=f*pr + Rational(1)/Rational(4)*v*pqsr\n#define indices for states above and below the Fermi level\nindex_rule = {\n     'below':  'kl',\n     'above':  'cd',\n     'general': 'pqrs'\n     }\nHnormal = substitute_dummies(Hamiltonian,new_indices=True, pretty_indices=index_rule)\nE0 = wicks(Hnormal,keep_only_fully_contracted=True)\nHnormal = Hnormal-E0\nw = WildFunction('w')\nHnormal = collect(Hnormal, NO(w))\nHnormal = evaluate_deltas(Hnormal)\nprint latex(Hnormal)\n\n```\n\nwhich gives us\n\n$$\n- f^{i}_{i} + f^{q}_{p} a^\\dagger_{q} a_{p} - \\frac{1}{4} v^{ii}_{ii} - \\frac{1}{4} v^{ii}_{ii} + \\frac{1}{4} v^{sr}_{qp} a^\\dagger_{r} a^\\dagger_{s} a_{q} a_{p},\n$$\n\nagain as expected, with the reference energy to be subtracted.\n\n<!-- --- end exercise --- -->\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 19: Using sympy to compute matrix elements\n\nWe can now go back to exercise 7 and define the Hamiltonian and the second-quantized representation of a  three-body Slater determinant.\n\n\n```\nfrom sympy import symbols, latex, WildFunction, collect, Rational, simplify\nfrom sympy.physics.secondquant import F, Fd, wicks, AntiSymmetricTensor, substitute_dummies, NO, evaluate_deltas\n# setup hamiltonian\np,q,r,s = symbols('p q r s',dummy=True)\n\nv = AntiSymmetricTensor('v',(p,q),(r,s))\npqsr = NO(Fd(p)*Fd(q)*F(s)*F(r))\nHamiltonian=Rational(1)/Rational(4)*v*pqsr\na,b,c,d,e,f = symbols('a,b, c, d, e, f',above_fermi=True)\n\nexpression = wicks(F(c)*F(b)*F(a)*Hamiltonian*Fd(d)*Fd(e)*Fd(f),keep_only_fully_contracted=True, simplify_kronecker_deltas=True)\nexpression = evaluate_deltas(expression)\nexpression = simplify(expression)\nprint latex(expression)\n\n```\n\nresulting in nine terms (as expected),\n\n$$\n- \\delta_{a d} v^{cb}_{ef} - \\delta_{a e} v^{cb}_{fd} + \\delta_{a f} v^{cb}_{ed} - \\delta_{b d} v^{ac}_{ef} - \\delta_{b e} v^{ac}_{fd} + \\delta_{b f} v^{ac}_{ed} + \\delta_{c d} v^{ab}_{ef} + \\delta_{c e} v^{ab}_{fd} - \\delta_{c f} v^{ab}_{ed}\n$$\n\n<!-- --- end exercise --- -->\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 20: Diagrammatic representation of Hartree-Fock equations\n\nWhat is the diagrammatic representation of the HF equation?\n\n$$\n-\\langle\\alpha_{k}|u^{HF}|\\alpha_{i}\\rangle+\\sum_{j=1}^{n}\n\\left[\\langle\\alpha_{k}\\alpha_{j}|\\hat{v}|\\alpha_{i}\\alpha_{j}\\rangle-\n\\langle\\alpha_{k}\\alpha_{j}|v|\\alpha_{j}\\alpha_{i}\\rangle\\right]=0\n$$\n\n(Represent $(-u^{HF})$ by the symbol $---$X .)\n\n<!-- --- end exercise --- -->\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 21: Derivation of Hartree-Fock equations\n\nConsider the ground state $|\\Phi\\rangle$ \nof a bound many-particle system of fermions. Assume that we remove one particle\nfrom the single-particle state $\\lambda$ and that our system ends in a new state\n$|\\Phi_{n}\\rangle$. \nDefine the energy needed to remove this particle as\n\n$$\nE_{\\lambda}=\\sum_{n}\\vert\\langle\\Phi_{n}|a_{\\lambda}|\\Phi\\rangle\\vert^{2}(E_{0}-E_{n}),\n$$\n\nwhere $E_{0}$ and $E_{n}$  are the ground state energies of the states\n$|\\Phi\\rangle$  and  $|\\Phi_{n}\\rangle$, respectively.\n * Show that\n\n$$\nE_{\\lambda}=\\langle\\Phi|a_{\\lambda}^{\\dagger}\\left[\na_{\\lambda},H \\right]|\\Phi\\rangle,\n$$\n\nwhere $H$ is the Hamiltonian of this system.\n * If we assume that $\\Phi$ is the  Hartree-Fock result, find the \n\nrelation between $E_{\\lambda}$ and the single-particle energy\n$\\varepsilon_{\\lambda}$\nfor states $\\lambda \\leq F$ and $\\lambda >F$, with\n\n$$\n\\varepsilon_{\\lambda}=\\langle\\lambda|\\hat{t}+\\hat{u}|\\lambda\\rangle,\n$$\n\nand\n\n$$\n\\langle\\lambda|\\hat{u}|\\lambda\\rangle=\\sum_{\\beta \\leq F}\n\\langle\\lambda\\beta|\\hat{v}|\\lambda\\beta\\rangle.\n$$\n\nWe have assumed an antisymmetrized matrix element here.\nDiscuss the result.\n\nThe Hamiltonian operator is defined as\n\n$$\nH=\\sum_{\\alpha\\beta}\\langle\\alpha|\\hat{t}|\\beta\\rangle a_{\\alpha}^{\\dagger}a_{\\beta}+\n\\frac{1}{2}\\sum_{\\alpha\\beta\\gamma\\delta}\\langle\\alpha\\beta|\\hat{v}|\\gamma\\delta\\rangle a_{\\alpha}^{\\dagger}a_{\\beta}^{\\dagger}a_{\\delta}a_{\\gamma}.\n$$\n\n<!-- --- end exercise --- -->\n\n\n# Nuclear forces\n<div id=\"ch:forces\"></div>\n\n## Introduction\n\n* Discussion of single-particle and two-particle quantum numbers, uncoupled and coupled schemes\n\n* Discussion of nuclear forces and models thereof (this material will not be covered in depth this spring)\n\n## Single-particle and two-particle quantum numbers\nIn order to understand the basics of the nucleon-nucleon interaction, we need to define the relevant quantum numbers and how we build up a single-particle state and a two-body state. \n\n* For the single-particle states, due to the fact that we have the spin-orbit force, the quantum numbers for the projection of orbital momentum $l$, that is $m_l$, and for spin $s$, that is $m_s$, are no longer so-called good quantum numbers. The total angular momentum $j$ and its projection $m_j$ are then  so-called *good quantum numbers*.\n\n* This means that the operator $\\hat{J}^2$ does not commute with $\\hat{L}_z$  or $\\hat{S}_z$.  \n\n* We also start normally with single-particle state functions defined using say the harmonic oscillator. For these functions, we have no explicit dependence on $j$. How can we introduce single-particle wave functions which have $j$ and its projection $m_j$ as quantum numbers? \n\nWe have that the operators for the orbital momentum are given by\n\n4\n5\n5\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n4\n5\n6\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\nL_z=-i\\hbar(x\\frac{\\partial }{\\partial y}-y\\frac{\\partial }{\\partial x})=xp_y-yp_x.\n$$\n\nSince we have a spin orbit force which is strong, it is easy to show that \nthe total angular momentum operator\n\n$$\n\\hat{J}=\\hat{L}+\\hat{S}\n$$\n\ndoes not commute with $\\hat{L}_z$ and $\\hat{S}_z$. To see this, we calculate for example\n\n$$\n\\begin{eqnarray} \n   [\\hat{L}_z,\\hat{J}^2]&=&[\\hat{L}_z,(\\hat{L}+\\hat{S})^2] \\\\ \\nonumber\n   &=&[\\hat{L}_z,\\hat{L}^2+\\hat{S}^2+2\\hat{L}\\hat{S}]\\\\ \\nonumber \n   &=& [\\hat{L}_z,\\hat{L}\\hat{S}]=[\\hat{L}_z,\\hat{L}_x\\hat{S}_x+\\hat{L}_y\\hat{S}_y+\\hat{L}_z\\hat{S}_z]\\ne 0, \n\\end{eqnarray}\n$$\n\nsince we have that $[\\hat{L}_z,\\hat{L}_x]=i\\hbar\\hat{L}_y$ and $[\\hat{L}_z,\\hat{L}_y]=i\\hbar\\hat{L}_x$. \n\nWe have also\n\n$$\n|\\hat{J}|=\\hbar\\sqrt{J(J+1)},\n$$\n\nwith the the following degeneracy\n\n$$\nM_J=-J, -J+1, \\dots, J-1, J.\n$$\n\nWith a given value of  $L$ and $S$ we can then determine the possible values of \n $J$ by studying the $z$ component of  $\\hat{J}$. \nIt is given by\n\n$$\n\\hat{J}_z=\\hat{L}_z+\\hat{S}_z.\n$$\n\nThe operators $\\hat{L}_z$ and $\\hat{S}_z$ have the quantum numbers\n$L_z=M_L\\hbar$ and $S_z=M_S\\hbar$, respectively, meaning that\n\n$$\nM_J\\hbar=M_L\\hbar +M_S\\hbar,\n$$\n\nor\n\n$$\nM_J=M_L +M_S.\n$$\n\nSince the max value of  $M_L$ is $L$ and for  $M_S$ is $S$\nwe obtain\n\n$$\n(M_J)_{\\mathrm{maks}}=L+S.\n$$\n\nFor nucleons we have that the maximum value of $M_S=m_s=1/2$, yielding\n\n$$\n(m_j)_{\\mathrm{max}}=l+\\frac{1}{2}.\n$$\n\nUsing this and the fact that the maximum value of  $M_J=m_j$ is $j$ we have\n\n$$\nj=l+\\frac{1}{2}, l-\\frac{1}{2}, l-\\frac{3}{2}, l-\\frac{5}{2}, \\dots\n$$\n\nTo decide where this series terminates, we use the vector inequality\n\n$$\n|\\hat{L}+\\hat{S}| \\ge \\left| |\\hat{L}|-|\\hat{S}|\\right|.\n$$\n\nUsing $\\hat{J}=\\hat{L}+\\hat{S}$ we get\n\n$$\n|\\hat{J}| \\ge |\\hat{L}|-|\\hat{S}|,\n$$\n\nor\n\n$$\n|\\hat{J}|=\\hbar\\sqrt{J(J+1)}\\ge |\\hbar\\sqrt{L(L+1)}-\n   \\hbar\\sqrt{S(S+1)}|.\n$$\n\nIf we limit ourselves to nucleons only with $s=1/2$ we find that\n\n$$\n|\\hat{J}|=\\hbar\\sqrt{j(j+1)}\\ge |\\hbar\\sqrt{l(l+1)}-\n   \\hbar\\sqrt{\\frac{1}{2}(\\frac{1}{2}+1)}|.\n$$\n\nIt is then easy to show that for nucleons there are only two possible values of\n$j$ which satisfy the inequality, namely\n\n$$\nj=l+\\frac{1}{2}\\hspace{0.1cm} \\mathrm{or} \\hspace{0.1cm}j=l-\\frac{1}{2},\n$$\n\nand with $l=0$ we get\n\n$$\nj=\\frac{1}{2}.\n$$\n\nLet us study some selected examples. We need also to keep in mind that parity is conserved.\nThe strong and electromagnetic Hamiltonians conserve parity. Thus the eigenstates can be\nbroken down into two classes of states labeled by their parity $\\pi= +1$ or $\\pi=-1$.\nThe nuclear interactions do not mix states with different parity.\n\nFor nuclear structure the total parity originates\nfrom the intrinsic parity of the nucleon which is $\\pi_{\\mathrm{intrinsic}}=+1$ \nand the parities associated with\nthe orbital angular momenta $\\pi_l=(-1)^l$ . The total parity is the product over all nucleons\n$\\pi = \\prod_i \\pi_{\\mathrm{intrinsic}}(i)\\pi_l(i) = \\prod_i (-1)^{l_i}$\n\nThe basis states we deal with are constructed so that they conserve parity and have thus a definite parity. \n\nNote that we do have parity violating processes, more on this later although our focus will be mainly on non-parity viloating processes\n\nConsider now the single-particle orbits of the $1s0d$ shell. \nFor a $0d$ state we have the quantum numbers $l=2$, $m_l=-2,-1,0,1,2$, $s+1/2$, $m_s=\\pm 1/2$,\n$n=0$ (the number of nodes of the wave function).   This means that we have positive parity and\n\n$$\nj=\\frac{3}{2}=l-s\\hspace{1cm} m_j=-\\frac{3}{2},-\\frac{1}{2},\\frac{1}{2},\\frac{3}{2}.\n$$\n\nand\n\n$$\nj=\\frac{5}{2}=l+s\\hspace{1cm} m_j=-\\frac{5}{2},-\\frac{3}{2},-\\frac{1}{2},\\frac{1}{2},\\frac{3}{2},\\frac{5}{2}.\n$$\n\nOur single-particle wave functions, if we use the harmonic oscillator, do however not contain the quantum numbers $j$ and $m_j$.\nNormally what we have is an eigenfunction for the one-body problem defined as\n\n$$\n\\phi_{nlm_lsm_s}(r,\\theta,\\phi)=R_{nl}(r)Y_{lm_l}(\\theta,\\phi)\\xi_{sm_s},\n$$\n\nwhere we have used spherical coordinates (with a spherically symmetric potential) and the spherical harmonics\n\n$$\nY_{lm_l}(\\theta,\\phi)=P(\\theta)F(\\phi)=\\sqrt{\\frac{(2l+1)(l-m_l)!}{4\\pi (l+m_l)!}}\n                      P_l^{m_l}(cos(\\theta))\\exp{(im_l\\phi)},\n$$\n\nwith $P_l^{m_l}$ being the so-called associated Legendre polynomials. \n\nExamples are\n\n$$\nY_{00}=\\sqrt{\\frac{1}{4\\pi}},\n$$\n\nfor $l=m_l=0$,\n\n$$\nY_{10}=\\sqrt{\\frac{3}{4\\pi}}cos(\\theta),\n$$\n\nfor $l=1$ and $m_l=0$,\n\n$$\nY_{1\\pm 1}=\\sqrt{\\frac{3}{8\\pi}}sin(\\theta)exp(\\pm i\\phi),\n$$\n\nfor  $l=1$ and $m_l=\\pm 1$,\n\n$$\nY_{20}=\\sqrt{\\frac{5}{16\\pi}}(3cos^2(\\theta)-1)\n$$\n\nfor $l=2$ and $m_l=0$ etc. \n\nHow can we get a function in terms of $j$ and $m_j$?\nDefine now\n\n$$\n\\phi_{nlm_lsm_s}(r,\\theta,\\phi)=R_{nl}(r)Y_{lm_l}(\\theta,\\phi)\\xi_{sm_s},\n$$\n\nand\n\n$$\n\\psi_{njm_j;lm_lsm_s}(r,\\theta,\\phi),\n$$\n\nas the state with quantum numbers $jm_j$.\nOperating with\n\n$$\n\\hat{j}^2=(\\hat{l}+\\hat{s})^2=\\hat{l}^2+\\hat{s}^2+2\\hat{l}_z\\hat{s}_z+\\hat{l}_+\\hat{s}_{-}+\\hat{l}_{-}\\hat{s}_{+},\n$$\n\non the latter state we will obtain admixtures from possible $\\phi_{nlm_lsm_s}(r,\\theta,\\phi)$ states.\n\nTo see this, we consider the following example and fix\n\n$$\nj=\\frac{3}{2}=l-s\\hspace{1cm} m_j=\\frac{3}{2}.\n$$\n\nand\n\n$$\nj=\\frac{5}{2}=l+s\\hspace{1cm} m_j=\\frac{3}{2}.\n$$\n\nIt means we can have, with $l=2$ and $s=1/2$ being fixed, in order to have $m_j=3/2$ either $m_l=1$ and $m_s=1/2$ or\n$m_l=2$ and $m_s=-1/2$. The two states\n\n$$\n\\psi_{n=0j=5/2m_j=3/2;l=2s=1/2}\n$$\n\nand\n\n$$\n\\psi_{n=0j=3/2m_j=3/2;l=2s=1/2}\n$$\n\nwill have admixtures from $\\phi_{n=0l=2m_l=2s=1/2m_s=-1/2}$ and $\\phi_{n=0l=2m_l=1s=1/2m_s=1/2}$. \nHow do we find these admixtures? Note that we don't specify the values of $m_l$ and $m_s$ \nin the functions $\\psi$ since    \n$\\hat{j}^2$ does not commute with $\\hat{L}_z$ and $\\hat{S}_z$. \n\nWe operate with\n\n$$\n\\hat{j}^2=(\\hat{l}+\\hat{s})^2=\\hat{l}^2+\\hat{s}^2+2\\hat{l}_z\\hat{s}_z+\\hat{l}_+\\hat{s}_{-}+\\hat{l}_{-}\\hat{s}_{+}\n$$\n\non the two $jm_j$ states, that is\n\n4\n9\n0\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\beta\\hbar^2\\sqrt{l(l+1)-m_l(m_l-1)}\\phi_{n=0l=2m_l=1s=1/2m_s=1/2},\n$$\n\nand\n\n4\n9\n2\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\beta\\hbar^2\\sqrt{l(l+1)-m_l(m_l+1)}\\phi_{n=0l=2m_l=2s=1/2m_s=-1/2}.\n$$\n\nThis means that the eigenvectors $\\phi_{n=0l=2m_l=2s=1/2m_s=-1/2}$ etc are not eigenvectors of $\\hat{j}^2$. The above problems gives a $2\\times2$ matrix that mixes the vectors $\\psi_{n=0j=5/2m_j3/2;l=2m_ls=1/2m_s}$ and $\\psi_{n=0j=3/2m_j3/2;l=2m_ls=1/2m_s}$ with the states  $\\phi_{n=0l=2m_l=2s=1/2m_s=-1/2}$ and\n$\\phi_{n=0l=2m_l=1s=1/2m_s=1/2}$. The unknown coefficients $\\alpha$ and $\\beta$ results from eigenvectors of this matrix. That is, inserting all values $m_l,l,m_s,s$ we obtain the matrix\n\n$$\n\\left[ \\begin{array} {cc} 19/4 & 2 \\\\ 2 & 31/4 \\end{array} \\right]\n$$\n\nwhose eigenvectors are the columns of\n\n$$\n\\left[ \\begin{array} {cc} 2/\\sqrt{5} &1/\\sqrt{5}  \\\\ 1/\\sqrt{5} & -2/\\sqrt{5} \\end{array}\\right]\n$$\n\nThese numbers define the so-called Clebsch-Gordan coupling coefficients  (the overlaps between the two basis sets). We can thus write\n\n$$\n\\psi_{njm_j;ls}=\\sum_{m_lm_s}\\langle lm_lsm_s|jm_j\\rangle\\phi_{nlm_lsm_s},\n$$\n\nwhere the coefficients $\\langle lm_lsm_s|jm_j\\rangle$ are the so-called Clebsch-Gordan coeffficients.\n\n\n\n### Clebsch-Gordan coefficients\n\nThe Clebsch-Gordan coeffficients $\\langle lm_lsm_s|jm_j\\rangle$ have some interesting properties for us, like the following  orthogonality relations\n\n4\n9\n7\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n4\n9\n8\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\langle j_1m_1j_2m_2|JM\\rangle=(-1)^{j_1+j_2-J}\\langle j_2m_2j_1m_1|JM\\rangle,\n$$\n\nand many others. The latter will turn extremely useful when we are going to define two-body states and interactions in a coupled basis.\n\n\n\n### Quantum numbers and the Schroeodinger equation in relative and CM coordinates\n\nSumming up, for \nfor the single-particle case, we have the following eigenfunctions\n\n$$\n\\psi_{njm_j;ls}=\\sum_{m_lm_s}\\langle lm_lsm_s|jm_j\\rangle\\phi_{nlm_lsm_s},\n$$\n\nwhere the coefficients $\\langle lm_lsm_s|jm_j\\rangle$ are the so-called Clebsch-Gordan coeffficients.\nThe relevant quantum numbers are $n$ (related to the principal quantum number and the number of nodes of the wave function) and\n\n5\n0\n1\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n5\n0\n2\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n5\n0\n3\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\hat{s}^2\\psi_{njm_j;ls}=\\hbar^2s(s+1)\\psi_{njm_j;ls},\n$$\n\nbut $s_z$ and $l_z$ do not result in good quantum numbers in a basis where we\nuse the angular momentum $j$.\n\n\nFor a two-body state where we couple two angular momenta $j_1$ and $j_2$ to a final\nangular momentum $J$ with projection $M_J$, we can define a similar transformation in terms\nof the Clebsch-Gordan coeffficients\n\n$$\n\\psi_{(j_1j_2)JM_J}=\\sum_{m_{j_1}m_{j_2}}\\langle j_1m_{j_1}j_2m_{j_2}|JM_J\\rangle\\psi_{n_1j_1m_{j_1};l_1s_1}\\psi_{n_2j_2m_{j_2};l_2s_2}.\n$$\n\nWe will write these functions in a more compact form hereafter, namely,\n\n$$\n|(j_1j_2)JM_J\\rangle=\\psi_{(j_1j_2)JM_J},\n$$\n\nand\n\n$$\n|j_im_{j_i}\\rangle=\\psi_{n_ij_im_{j_i};l_is_i},\n$$\n\nwhere we have skipped the explicit reference to $l$, $s$ and $n$. The spin of a nucleon is always $1/2$ while the value of $l$ can be deduced from the parity of the state.\nIt is thus normal to label a state with a given total angular momentum as \n$j^{\\pi}$, where $\\pi=\\pm 1$. \n\n\n\nOur two-body state can thus be written as\n\n$$\n|(j_1j_2)JM_J\\rangle=\\sum_{m_{j_1}m_{j_2}}\\langle j_1m_{j_1}j_2m_{j_2}|JM_J\\rangle|j_1m_{j_1}\\rangle|j_2m_{j_2}\\rangle.\n$$\n\nDue to the coupling order of the Clebsch-Gordan coefficient it reads as \n$j_1$ coupled to $j_2$ to yield a final angular momentum $J$. If we invert the order of coupling we would have\n\n$$\n|(j_2j_1)JM_J\\rangle=\\sum_{m_{j_1}m_{j_2}}\\langle j_2m_{j_2}j_1m_{j_1}|JM_J\\rangle|j_1m_{j_1}\\rangle|j_2m_{j_2}\\rangle,\n$$\n\nand due to the symmetry properties of the Clebsch-Gordan coefficient we have\n\n$$\n|(j_2j_1)JM_J\\rangle=(-1)^{j_1+j_2-J}\\sum_{m_{j_1}m_{j_2}}\\langle j_1m_{j_1}j_2m_{j_2}|JM_J\\rangle|j_1m_{j_1}\\rangle|j_2m_{j_2}\\rangle=(-1)^{j_1+j_2-J}|(j_1j_2)JM_J\\rangle.\n$$\n\nWe call the basis $|(j_1j_2)JM_J\\rangle$ for the **coupled basis**, or just $j$-coupled basis/scheme. The basis formed by the simple product of single-particle eigenstates \n$|j_1m_{j_1}\\rangle|j_2m_{j_2}\\rangle$ is called the **uncoupled-basis**, or just the $m$-scheme basis. \n\n\n\nWe have thus the coupled basis\n\n$$\n|(j_1j_2)JM_J\\rangle=\\sum_{m_{j_1}m_{j_2}}\\langle j_1m_{j_1}j_2m_{j_2}|JM_J\\rangle|j_1m_{j_1}\\rangle|j_2m_{j_2}\\rangle.\n$$\n\nand the uncoupled basis\n\n$$\n|j_1m_{j_1}\\rangle|j_2m_{j_2}\\rangle.\n$$\n\nThe latter can easily be generalized to many single-particle states whereas the first \nneeds specific coupling coefficients and definitions of coupling orders. \nThe $m$-scheme basis is easy to implement numerically and is used in most standard shell-model codes. \nOur coupled basis obeys also the following relations\n\n5\n1\n3\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\hat{J}_z|(j_1j_2)JM_J\\rangle=\\hbar M_J|(j_1j_2)JM_J\\rangle,\n$$\n\n## Components of the force and isospin\n\n The nuclear forces are almost charge independent. If we assume they are, \nwe can introduce a new quantum number which is conserved. For nucleons only, that is a proton and neutron, we can limit ourselves\nto two possible values which allow us to distinguish between the two particles. If we assign an isospin value of $\\tau=1/2$ for protons\nand neutrons (they belong to an isospin doublet, in the same way as we discussed the spin $1/2$ multiplet), we can define \nthe neutron to have isospin projection $\\tau_z=+1/2$ and a proton to have $\\tau_z=-1/2$. These assignements are the standard choices in low-energy nuclear physics.\n\n\n\n### Isospin\n\nThis leads to the introduction of an additional quantum number called isospin.\nWe can define a single-nucleon\nstate function in terms of the quantum numbers $n$, $j$, $m_j$, $l$, $s$, $\\tau$ and $\\tau_z$. Using our definitions in terms of an uncoupled basis, we had\n\n$$\n\\psi_{njm_j;ls}=\\sum_{m_lm_s}\\langle lm_lsm_s|jm_j\\rangle\\phi_{nlm_lsm_s},\n$$\n\nwhich we can now extend to\n\n$$\n\\psi_{njm_j;ls}\\xi_{\\tau\\tau_z}=\\sum_{m_lm_s}\\langle lm_lsm_s|jm_j\\rangle\\phi_{nlm_lsm_s}\\xi_{\\tau\\tau_z},\n$$\n\nwith the isospin spinors defined as\n\n$$\n\\xi_{\\tau=1/2\\tau_z=+1/2}=\\left(\\begin{array}{c} 1  \\\\ 0\\end{array}\\right),\n$$\n\nand\n\n$$\n\\xi_{\\tau=1/2\\tau_z=-1/2}=\\left(\\begin{array}{c} 0  \\\\ 1\\end{array}\\right).\n$$\n\nWe can then define the proton state function as\n\n$$\n\\psi^p(\\mathbf{r})  =\\psi_{njm_j;ls}(\\mathbf{r})\\left(\\begin{array}{c} 0  \\\\ 1\\end{array}\\right),\n$$\n\nand similarly for neutrons as\n\n$$\n\\psi^n(\\mathbf{r})  =\\psi_{njm_j;ls}(\\mathbf{r})\\left(\\begin{array}{c} 1  \\\\ 0\\end{array}\\right).\n$$\n\nWe can in turn define the isospin Pauli matrices (in the same as we define the spin matrices) as\n\n5\n2\n1\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\hat{\\tau}_y =\\left(\\begin{array}{cc} 0 & -\\imath \\\\ \\imath & 0 \\end{array}\\right),\n$$\n\nand\n\n$$\n\\hat{\\tau}_z =\\left(\\begin{array}{cc} 1 & 0 \\\\ 0 & -1 \\end{array}\\right),\n$$\n\nand operating with $\\hat{\\tau}_z$ on the proton state function we have\n\n$$\n\\hat{\\tau}_z\\psi^p(\\mathbf{r})=-\\frac{1}{2}\\psi^p(\\mathbf{r}),\n$$\n\nand for neutrons we have\n\n$$\n\\hat{\\tau}\\psi^n(\\mathbf{r})=\\frac{1}{2}\\psi^n(\\mathbf{r}).\n$$\n\nWe can now define the so-called charge operator as\n\n$$\n\\frac{\\hat{Q}}{e} = \\frac{1}{2}\\left(1-\\hat{\\tau}_z\\right)=\\begin{Bmatrix} 0 & 0 \\\\ 0 & 1 \\end{Bmatrix},\n$$\n\nwhich results in\n\n$$\n\\frac{\\hat{Q}}{e}\\psi^p(\\mathbf{r})=\\psi^p(\\mathbf{r}),\n$$\n\nand\n\n$$\n\\frac{\\hat{Q}}{e}\\psi^n(\\mathbf{r})=0,\n$$\n\nas it should be. \n\nThe total isospin is defined as\n\n$$\n\\hat{T}=\\sum_{i=1}^A\\hat{\\tau}_i,\n$$\n\nand its corresponding isospin projection as\n\n$$\n\\hat{T}_z=\\sum_{i=1}^A\\hat{\\tau}_{z_i},\n$$\n\nwith eigenvalues $T(T+1)$ for $\\hat{T}$ and $1/2(N-Z)$ for $\\hat{T}_z$, where $N$ is the number of neutrons and $Z$ the number of protons. \n\nIf charge is conserved, the Hamiltonian $\\hat{H}$ commutes with $\\hat{T}_z$ and all members of a given isospin multiplet\n(that is the same value of $T$) have the same energy and there is no $T_z$ dependence and we say that $\\hat{H}$ is a scalar in isospin space.\n\n\n\n\n## Two-body matrix elements\n\nTill now we have not said anything about the explicit calculation of two-body matrix elements. It is time to amend this deficiency.\nWe have till now seen the following definitions of a two-body matrix elements. In $m$-scheme\nwith quantum numbers $p=j_pm_p$ etc we have a two-body state defined as\n\n$$\n|(pq)M\\rangle  = a^{\\dagger}_pa^{\\dagger}_q|\\Phi_0\\rangle,\n$$\n\nwhere $|\\Phi_0\\rangle$ is a chosen reference state, say for example the Slater determinant which approximates ${}^{16}\\mbox{O}$ with the $0s$ and the $0p$ shells being filled, and $M=m_p+m_q$. Recall that we label single-particle states above the Fermi level as $abcd\\dots$ and states below the Fermi level for $ijkl\\dots$.  \nIn case of two-particles in the single-particle states $a$ and $b$ outside ${}^{16}\\mbox{O}$ as a closed shell core, say ${}^{18}\\mbox{O}$, \nwe would write the representation of the Slater determinant as\n\n$$\n|^{18}\\mathrm{O}\\rangle =|(ab)M\\rangle  = a^{\\dagger}_aa^{\\dagger}_b|^{16}\\mathrm{O}\\rangle=|\\Phi^{ab}\\rangle.\n$$\n\nIn case of two-particles removed from say ${}^{16}\\mbox{O}$, for example two neutrons in the single-particle states $i$ and $j$, we would write this as\n\n$$\n|^{14}\\mathrm{O}\\rangle =|(ij)M\\rangle  = a_ja_i|^{16}\\mathrm{O}\\rangle=|\\Phi_{ij}\\rangle.\n$$\n\nFor a one-hole-one-particle state we have\n\n$$\n|^{16}\\mathrm{O}\\rangle_{1p1h} =|(ai)M\\rangle  = a_a^{\\dagger}a_i|^{16}\\mathrm{O}\\rangle=|\\Phi_{i}^a\\rangle,\n$$\n\nand finally for a two-particle-two-hole state we\n\n$$\n|^{16}\\mathrm{O}\\rangle_{2p2h} =|(abij)M\\rangle  = a_a^{\\dagger}a_b^{\\dagger}a_ja_i|^{16}\\mathrm{O}\\rangle=|\\Phi_{ij}^{ab}\\rangle.\n$$\n\nLet us go back to the case of two-particles in the single-particle states $a$ and $b$ outside ${}^{16}\\mbox{O}$ as a closed shell core, say ${}^{18}\\mbox{O}$.\nThe representation of the Slater determinant is\n\n$$\n|^{18}\\mathrm{O}\\rangle =|(ab)M\\rangle  = a^{\\dagger}_aa^{\\dagger}_b|^{16}\\mathrm{O}\\rangle=|\\Phi^{ab}\\rangle.\n$$\n\nThe anti-symmetrized matrix element is detailed as\n\n$$\n\\langle (ab) M | \\hat{V} | (cd) M \\rangle = \\langle (j_am_aj_bm_b)M=m_a+m_b |  \\hat{V} | (j_cm_cj_dm_d)M=m_a+m_b \\rangle,\n$$\n\nand note that anti-symmetrization means\n\n5\n3\n8\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\langle (ab) M | \\hat{V} | (cd) M \\rangle =-\\langle (ab) M | \\hat{V} | (dc) M \\rangle.\n$$\n\nThis matrix element is the expectation value of\n\n$$\n\\langle ^{16}\\mathrm{O}|a_ba_a\\frac{1}{4}\\sum_{pqrs}\\langle (pq) M | \\hat{V} | (rs) M' \\rangle a^{\\dagger}_pa^{\\dagger}_qa_sa_r a^{\\dagger}_ca^{\\dagger}_c|^{16}\\mathrm{O}\\rangle.\n$$\n\nWe have also defined matrix elements in the coupled basis, the so-called $J$-coupled scheme.\nIn this case the two-body wave function for two neutrons outside ${}^{16}\\mbox{O}$ is written as\n\n$$\n|^{18}\\mathrm{O}\\rangle_J =|(ab)JM\\rangle  = \\left\\{a^{\\dagger}_aa^{\\dagger}_b\\right\\}^J_M|^{16}\\mathrm{O}\\rangle=N_{ab}\\sum_{m_am_b}\\langle j_am_aj_bm_b|JM\\rangle|\\Phi^{ab}\\rangle,\n$$\n\nwith\n\n$$\n|\\Phi^{ab}\\rangle=a^{\\dagger}_aa^{\\dagger}_b|^{16}\\mathrm{O}\\rangle.\n$$\n\nWe have now an explicit coupling order, where the angular momentum $j_a$ is coupled to the angular momentum $j_b$ to yield a final two-body angular momentum $J$. \nThe normalization factor (to be derived below) is\n\n$$\nN_{ab}=\\frac{\\sqrt{1+\\delta_{ab}\\times (-1)^J}}{1+\\delta_{ab}}.\n$$\n\nThe implementation of the Pauli principle looks different in the $J$-scheme compared with the $m$-scheme. In the latter, no two fermions or more can have the same set of quantum numbers. In the $J$-scheme, when we write a state with the shorthand\n\n$$\n|^{18}\\mathrm{O}\\rangle_J =|(ab)JM\\rangle,\n$$\n\nwe do refer to the angular momenta only. This means that another way of writing the last state is\n\n$$\n|^{18}\\mathrm{O}\\rangle_J =|(j_aj_b)JM\\rangle.\n$$\n\nWe will use this notation throughout when we refer to a two-body state in $J$-scheme. The Kronecker $\\delta$ function in the normalization factor \nrefers thus to the values of $j_a$ and $j_b$. If two identical particles are in a state with the same $j$-value, then only even values of the total angular momentum apply.\n\n\n\n\nNote also that, using the anti-commuting properties of the creation operators, we obtain\n\n$$\nN_{ab}\\sum_{m_am_b}\\langle j_am_aj_bm_b|JM>|\\Phi^{ab}\\rangle=-N_{ab}\\sum_{m_am_b}\\langle j_am_aj_bm_b|JM\\rangle|\\Phi^{ba}\\rangle.\n$$\n\nFurthermore, using the property of the Clebsch-Gordan coefficient\n\n$$\n\\langle j_am_aj_bm_b|JM>=(-1)^{j_a+j_b-J}\\langle j_bm_bj_am_a|JM\\rangle,\n$$\n\nwhich can be used to show that\n\n$$\n|(j_bj_a)JM\\rangle  = \\left\\{a^{\\dagger}_ba^{\\dagger}_a\\right\\}^J_M|^{16}\\mathrm{O}\\rangle=N_{ab}\\sum_{m_am_b}\\langle j_bm_bj_am_a|JM\\rangle|\\Phi^{ba}\\rangle,\n$$\n\nis equal to\n\n$$\n|(j_bj_a)JM\\rangle=(-1)^{j_a+j_b-J+1}|(j_aj_b)JM\\rangle.\n$$\n\nThis relation is important since we will need it when using anti-symmetrized matrix elements in $J$-scheme.\n\n\n\nThe two-body matrix element is a scalar and since it obeys rotational symmetry, it is diagonal in $J$, \nmeaning that the corresponding matrix element in $J$-scheme is\n\n5\n5\n0\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\times \\langle j_cm_cj_dm_d|JM\\rangle\\langle (j_am_aj_bm_b)M |  \\hat{V} | (j_cm_cj_dm_d)M \\rangle,\n$$\n\nand note that of the four $m$-values in the above sum, only three are independent due to the constraint $m_a+m_b=M=m_c+m_d$.\nSince\n\n$$\n|(j_bj_a)JM\\rangle=(-1)^{j_a+j_b-J+1}|(j_aj_b)JM\\rangle,\n$$\n\nthe anti-symmetrized matrix elements need now to obey the following relations\n\n5\n5\n3\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n5\n5\n4\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\langle (j_aj_b) JM | \\hat{V} | (j_cj_d) JM \\rangle = (-1)^{j_a+j_b+j_c+j_d}\\langle (j_bj_a) JM | \\hat{V} | (j_dj_c) JM \\rangle=\\langle (j_bj_a) JM | \\hat{V} | (j_dj_c) JM \\rangle,\n$$\n\nwhere the last relations follows from the fact that $J$ is an integer and $2J$ is always an even number.\n\n\n\n\nUsing the orthogonality properties of the Clebsch-Gordan coefficients,\n\n$$\n\\sum_{m_am_b}\\langle j_am_aj_bm_b|JM\\rangle\\langle j_am_aj_bm_b|J'M'\\rangle=\\delta_{JJ'}\\delta_{MM'},\n$$\n\nand\n\n$$\n\\sum_{JM}\\langle j_am_aj_bm_b|JM\\rangle\\langle j_am_a'j_bm_b'|JM\\rangle=\\delta_{m_am_a'}\\delta_{m_bm_b'},\n$$\n\nwe can also express the two-body matrix element in $m$-scheme in terms of that in $J$-scheme, that is, if we multiply with\n\n$$\n\\sum_{JMJ'M'}\\langle j_am_a'j_bm_b'|JM\\rangle\\langle j_cm_c'j_dm_d'|J'M'\\rangle\n$$\n\nfrom left in\n\n5\n5\n9\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\times \\langle (j_am_aj_bm_b)M|  \\hat{V} | (j_cm_cj_dm_d)M\\rangle,\n$$\n\nwe obtain\n\n\n\nwe obtain\n\n5\n6\n1\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\times \\langle (j_aj_b) JM | \\hat{V} | (j_cj_d) JM \\rangle.\n$$\n\n## Phenomenology of nuclear forces: From Yukawa to Lattice QCD and Effective Field Theory\n\n\n* Chadwick (1932) discovers the neutron and Heisenberg (1932) proposes the first Phenomenology (Isospin).  \n\n* Yukawa (1935) and his Meson Hypothesis       \n\n* Discovery of the pion in cosmic ray (1947) and in the Berkeley Cyclotron Lab (1948).\n\n* Nobelprize awarded to Yukawa (1949).  Rabi (1948) measures quadrupole moment of the deuteron.\n\n* Taketani, Nakamura, Sasaki (1951): 3 ranges.      One-Pion-Exchange (OPE): o.k.\n\n* Multi-pion exchanges: Problems!   Taketani, Machida, Onuma (1952);\n\n* *Pion Theories* Brueckner, Watson (1953).\n\n* Many pions = multi-pion resonances: $\\sigma(600)$,  $\\rho(770)$,  $\\omega(782)$ etc. One-Boson-Exchange Model.\n\n* Refined Meson Theories\n\n* Sophisticated models for two-pion exchange:\n\n      * Paris Potential (Lacombe et al., Phys. Rev. C **21**, 861 (1980))\n\n      * Bonn potential (Machleidt et al., Phys. Rep. **149**, 1 (1987))\n\n\n* Quark cluster models. Begin of effective field theory studies.\n\n* 1990's\n\n  * 1993-2001: High-precision NN potentials: Nijmegen I, II, '93, Reid93 (Stoks et al. 1994), \n\n  * Argonne V18 (Wiringa et al, 1995), CD-Bonn (Machleidt et al. 1996 and 2001. \n\n  * Advances in effective field theory: Weinberg (1990); Ordonez, Ray, van Kolck and many more.\n\n\n* 3rd Millenium\n\n  * Another \"pion theory\"; but now right: constrained by chiral symmetry. Three-body and higher-body forces appear naturally at a given order of the chiral expansion. \n\n\nNucleon-nucleon interaction from Lattice QCD, final confirmation of meson hypothesis of Yukawa?  See for example Ishii *et al*, PRL 2007\n\nThe aim is to give you an overview over central features of the nucleon-nucleon interaction and how it is constructed, with both technical and theoretical approaches. \n\n* The existence of the deuteron with $J^{\\pi}=1^+$ indicates that the force between protons and neutrons is attractive at least for the $^3S_1$ partial wave. Interference between Coulomb and nuclear scattering for the proton-proton partial wave $^1S_0$ shows that  the NN force is attractive at least for the $^1S_0$ partial wave. \n\n* It has a short range and strong intermediate attraction.\n\n* Spin dependent, scattering lengths for triplet and singlet states are different,\n\n* Spin-orbit force. Observation of large polarizations of scattered nucleons perpendicular to the plane of scattering.\n\n* Strongly repulsive core. The $s$-wave phase shift becomes negative at $\\approx 250$ MeV implying that the singlet $S$ has a hard core with range $0.4-0.5$ fm. \n\n* Charge independence (almost). Two nucleons in a given two-body state always (almost) experience the same force. Modern interactions break charge and isospin symmetry lightly. That means that the pp, neutron-neutron and pn parts of the interaction will be different for the same quantum numbers. \n\n* Non-central. There is a tensor force. First indications from the quadrupole moment of the deuteron pointing to an admixture in the ground state of both $l=2$ ($^3D_1$) and $l=0$ ($^3S_1$) orbital momenta.\n\nComparison of the binding energies of\n${}^2\\mbox{H}$ (deuteron), ${}^3\\mbox{H}$ (triton), ${}^4\\mbox{He}$ (alpha - particle) show that the nuclear force is of finite range ($1-2$ fm) and very strong within that range.\n\nFor nuclei with $A>4$, the energy saturates: Volume and binding energies of nuclei are proportional to the mass number $A$ (as we saw from exercise 1).\n\nNuclei are also bound. The average distance\nbetween nucleons in nuclei is about $2$ fm which\nmust roughly correspond to the range of the\nattractive part.\n\n\n### Phenomenology of nuclear forces: Charge Dependence\n\n\n * After correcting for the electromagnetic interaction, the forces between nucleons (pp, nn, or np) in the same state are almost the same.\n\n * *Almost the same*: Charge-independence is slightly broken.\n\n * Equality between the pp and nn forces: Charge symmetry.\n\n * Equality between pp/nn force and np force: Charge independence.\n\n * Better notation: Isospin symmetry, invariance under rotations in isospin\n\nCharge-symmetry breaking (CSB), after electromagnetic effects\nhave been removed:\n* $a_{pp}=  -17.3 \\pm 0.4 \\hspace{0.cm} \\mathrm{fm}$\n\n* $a_{nn}=-18.8 \\pm 0.5 \\hspace{0.cm} \\mathrm{fm}$. Note however discrepancy from $nd$ breakup reactions resulting in  $a_{nn}=-18.72 \\pm 0.13 \\pm 0.65 \\hspace{0.cm} \\mathrm{fm}$ and $\\pi^- + d \\rightarrow \\gamma + 2n$ reactions giving  $a_{nn}=-18.93 \\pm 0.27 \\pm 0.3 \\hspace{0.cm} \\mathrm{fm}$.\n\nCharge-independence breaking (CIB)\n* $a_{pn}=  -23.74 \\pm 0.02 \\hspace{0.cm} \\mathrm{fm}$ \n\n## Symmetries of the Nucleon-Nucleon (NN) Force\n\n* Translation invariance\n\n* Galilean invariance\n\n* Rotation invariance in space\n\n* Space reflection invariance\n\n* Time reversal invariance\n\n* Invariance under the interchange of particle $1$ and $2$\n\n* Almost isospin symmetry\n\nHere we display a typical way to parametrize (non-relativistic expression) the nuclear two-body force\nin terms of some operators, the central part, the spin-spin part and the central force.\n\n5\n6\n3\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\left. + C_{SL} \\left( {1\\over m_\\alpha r} + {1\\over \\left( m_\\alpha r\\right)^2}\n\\right) \\mathbf{L}\\cdot \\mathbf{S}\n\\right\\} \\frac{e^{-m_\\alpha r}}{m_\\alpha r}\n$$\n\nHow do we derive such terms?  (Note: no isospin dependence and that the above is an approximation)\n\nTo derive the above famous form of the nuclear force using field theoretical concepts, we will need some \nelements from relativistic quantum mechanics. These derivations will be given below. \nThe material here gives some background to this.\nI know that many of you have not taken a course in quantum field theory. I hope however that you can see the basic ideas leading to the famous non-relativistic expressions for the nuclear force. \n\n**Furthermore, when we analyze nuclear data, we will actually try to explain properties like spectra, single-particle energies etc in terms of the various terms of the nuclear force. Moreover, many of you will hear about these terms at various talks, workshops, seminars etc. Then, it is good to have an idea of what people actually mean!!**\n\n\n\n### Dramatis Personae\n\n\n<table border=\"1\">\n<thead>\n<tr><th align=\"center\"> Baryons </th> <th align=\"center\">Mass (MeV)</th> <th align=\"center\">   Mesons  </th> <th align=\"center\">   Mass (MeV)  </th> </tr>\n</thead>\n<tbody>\n<tr><td align=\"center\">   $p,n$        </td> <td align=\"center\">   938.926       </td> <td align=\"center\">   $\\pi$          </td> <td align=\"center\">   138.03             </td> </tr>\n<tr><td align=\"center\">   $\\Lambda$    </td> <td align=\"center\">   1116.0        </td> <td align=\"center\">   $\\eta$         </td> <td align=\"center\">   548.8              </td> </tr>\n<tr><td align=\"center\">   $\\Sigma$     </td> <td align=\"center\">   1197.3        </td> <td align=\"center\">   $\\sigma$       </td> <td align=\"center\">   $\\approx 550.0$    </td> </tr>\n<tr><td align=\"center\">   $\\Delta$     </td> <td align=\"center\">   1232.0        </td> <td align=\"center\">   $\\rho$         </td> <td align=\"center\">   770                </td> </tr>\n<tr><td align=\"center\">                </td> <td align=\"center\">                 </td> <td align=\"center\">   $\\omega$       </td> <td align=\"center\">   782.6              </td> </tr>\n<tr><td align=\"center\">                </td> <td align=\"center\">                 </td> <td align=\"center\">   $\\delta$       </td> <td align=\"center\">   983.0              </td> </tr>\n<tr><td align=\"center\">                </td> <td align=\"center\">                 </td> <td align=\"center\">   $K$            </td> <td align=\"center\">   495.8              </td> </tr>\n<tr><td align=\"center\">                </td> <td align=\"center\">                 </td> <td align=\"center\">   $K^{\\star}$    </td> <td align=\"center\">   895.0              </td> </tr>\n</tbody>\n</table>\n\n\n\n\n### Components of the force and quantum numbers\n\nBut before we proceed, we will look into specific quantum numbers of the relative system and study \nexpectation vaues of the various terms of\n\n5\n6\n5\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\left. + C_{SL} \\left( {1\\over m_\\alpha r} + {1\\over \\left( m_\\alpha r\\right)^2}\n\\right) \\mathbf{L}\\cdot \\mathbf{S}\n\\right\\} \\frac{e^{-m_\\alpha r}}{m_\\alpha r}\n$$\n\n### Relative and CoM system, quantum numbers\n\n\nWhen solving the scattering equation or solving the two-nucleon problem, it is convenient to rewrite the Schroedinger equation, due to\nthe spherical symmetry of the Hamiltonian, in relative and center-of-mass coordinates. This will also define the quantum numbers of the relative and center-of-mass system and will aid us later in solving\nthe so-called Lippman-Schwinger equation for the scattering problem. \n\nWe define the center-of-mass (CoM)  momentum as\n\n$$\n\\mathbf{K}=\\sum_{i=1}^A\\mathbf{k}_i,\n$$\n\nwith $\\hbar=c=1$ the wave number $k_i=p_i$, with $p_i$ the pertinent momentum of a single-particle state. \nWe have also the relative momentum\n\n$$\n\\mathbf{k}_{ij}=\\frac{1}{2}(\\mathbf{k}_i-\\mathbf{k}_j).\n$$\n\nWe will below skip the indices $ij$ and simply write $\\mathbf{k}$\n\n\n\n\nIn a similar fashion we can define the CoM coordinate\n\n$$\n\\mathbf{R}=\\frac{1}{A}\\sum_{i=1}^{A}\\mathbf{r}_i,\n$$\n\nand the relative distance\n\n$$\n\\mathbf{r}_{ij}=(\\mathbf{r}_i-\\mathbf{r}_j).\n$$\n\nWith the definitions\n\n$$\n\\mathbf{K}=\\sum_{i=1}^A\\mathbf{k}_i,\n$$\n\nand\n\n$$\n\\mathbf{k}_{ij}=\\frac{1}{2}(\\mathbf{k}_i-\\mathbf{k}_j).\n$$\n\nwe can rewrite the two-particle kinetic energy (note that we use $\\hbar=c=1$ as\n\n$$\n\\frac{\\mathbf{k}_1^2}{2m_n}+\\frac{\\mathbf{k}_2^2}{2m_n}=\\frac{\\mathbf{k}^2}{m_n}+\\frac{\\mathbf{K}^2}{4m_n},\n$$\n\nwhere $m_n$ is the average of the proton and the neutron masses. \n\n\n\nSince the two-nucleon interaction depends only on the relative distance, this means that we can separate Schroedinger's equation in an equation for the center-of-mass motion and one for the relative motion.\n\nWith an equation for the relative motion only and a separate one for the center-of-mass motion we need to redefine the two-body quantum numbers.\n\nPreviously we had a two-body state vector defined as $|(j_1j_2)JM_J\\rangle$ in a coupled basis. \nWe will now define the quantum numbers for the relative motion. Here we need to define new orbital momenta (since these are the quantum numbers which change). \nWe define\n\n$$\n\\hat{l}_1+\\hat{l}_2=\\hat{\\lambda}=\\hat{l}+\\hat{L},\n$$\n\nwhere $\\hat{l}$ is the orbital momentum associated with the relative motion and\n$\\hat{L}$ the corresponding one linked with the CoM. The total spin $S$ is unchanged since it acts in a different space. We have thus that\n\n$$\n\\hat{J}=\\hat{l}+\\hat{L}+\\hat{S},\n$$\n\nwhich allows us to define the angular momentum of the relative motion\n\n$$\n{ \\cal J} =  \\hat{l}+\\hat{S},\n$$\n\nwhere ${ \\cal J}$ is the total angular momentum of the relative motion.\n\n\n\nThe total two-nucleon state function has to be anti-symmetric. The total function contains a spatial part, a spin part and an isospin part. If isospin is conserved, this leads to in case we have an $s$-wave with spin $S=0$ to an isospin \ntwo-body state with $T=1$ since the spatial part is symmetric and the spin part is anti-symmetric. \n\nSince the projections for $T$ are $T_z=-1,0,1$, we can have a $pp$, an $nn$ and a $pn$ state.\n\nFor $l=0$ and $S=1$, a so-called triplet state, $^3S_1$, we must have $T=0$, meaning that we have only one state, a $pn$ state. For other partial waves, the following table lists states up to $f$ waves.\nWe can systemize this in a table as follows, recalling that $|\\mathbf{l}-\\mathbf{S}| \\le |\\mathbf{J}| \\le |\\mathbf{l}+\\mathbf{S}|$,  \n\n<table border=\"1\">\n<thead>\n<tr><th align=\"center\">$^{2S+1}l_J$</th> <th align=\"center\">$J$</th> <th align=\"center\">$l$</th> <th align=\"center\">$S$</th> <th align=\"center\">$T$</th> <th align=\"center\">$\\vert pp\\rangle$</th> <th align=\"center\">$\\vert pn\\rangle$</th> <th align=\"center\">$\\vert nn\\rangle$</th> </tr>\n</thead>\n<tbody>\n<tr><td align=\"center\">   $^{1}S_0$       </td> <td align=\"center\">   0      </td> <td align=\"center\">   0      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1      </td> <td align=\"center\">   yes                  </td> <td align=\"center\">   yes                  </td> <td align=\"center\">   yes                  </td> </tr>\n<tr><td align=\"center\">   $^{3}S_1$       </td> <td align=\"center\">   1      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1      </td> <td align=\"center\">   0      </td> <td align=\"center\">   no                   </td> <td align=\"center\">   yes                  </td> <td align=\"center\">   no                   </td> </tr>\n<tr><td align=\"center\">   $^{3}P_0$       </td> <td align=\"center\">   0      </td> <td align=\"center\">   1      </td> <td align=\"center\">   1      </td> <td align=\"center\">   1      </td> <td align=\"center\">   yes                  </td> <td align=\"center\">   yes                  </td> <td align=\"center\">   yes                  </td> </tr>\n<tr><td align=\"center\">   $^{1}P_1$       </td> <td align=\"center\">   1      </td> <td align=\"center\">   1      </td> <td align=\"center\">   0      </td> <td align=\"center\">   0      </td> <td align=\"center\">   no                   </td> <td align=\"center\">   yes                  </td> <td align=\"center\">   no                   </td> </tr>\n<tr><td align=\"center\">   $^{3}P_1$       </td> <td align=\"center\">   1      </td> <td align=\"center\">   1      </td> <td align=\"center\">   1      </td> <td align=\"center\">   1      </td> <td align=\"center\">   yes                  </td> <td align=\"center\">   yes                  </td> <td align=\"center\">   yes                  </td> </tr>\n<tr><td align=\"center\">   $^{3}P_2$       </td> <td align=\"center\">   2      </td> <td align=\"center\">   1      </td> <td align=\"center\">   1      </td> <td align=\"center\">   1      </td> <td align=\"center\">   yes                  </td> <td align=\"center\">   yes                  </td> <td align=\"center\">   yes                  </td> </tr>\n<tr><td align=\"center\">   $^{3}D_1$       </td> <td align=\"center\">   1      </td> <td align=\"center\">   2      </td> <td align=\"center\">   1      </td> <td align=\"center\">   0      </td> <td align=\"center\">   no                   </td> <td align=\"center\">   yes                  </td> <td align=\"center\">   no                   </td> </tr>\n<tr><td align=\"center\">   $^{3}F_2$       </td> <td align=\"center\">   2      </td> <td align=\"center\">   3      </td> <td align=\"center\">   1      </td> <td align=\"center\">   1      </td> <td align=\"center\">   yes                  </td> <td align=\"center\">   yes                  </td> <td align=\"center\">   yes                  </td> </tr>\n</tbody>\n</table>\n\n\n\n\n\n### Components of the force and quantum numbers\n\nThe tensor force is given by\n\n$$\nS_{12} (\\hat r) = \\frac{3}{r^2}\\left(\\mathbf{\\sigma}_1\\cdot \\mathbf{r}\\right) \\left(\\mathbf{\\sigma}_2\\cdot \\mathbf{r}\\right) -\\mathbf{\\sigma}_1\\cdot\\mathbf{\\sigma}_2\n$$\n\nwhere the Pauli matrices are defined as\n\n5\n7\n8\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\sigma_y =\\begin{Bmatrix} 0 & -\\imath \\\\ \\imath & 0 \\end{Bmatrix},\n$$\n\nand\n\n$$\n\\sigma_z =\\begin{Bmatrix} 1 & 0 \\\\ 0 & -1 \\end{Bmatrix},\n$$\n\nwith the properties $\\sigma = 2\\mathbf{S}$ (the spin of the system, being $1/2$ for nucleons), \n$\\sigma^2_x=\\sigma^2_y=\\sigma_z=\\mathbf{1}$ and\nobeying the commutation and anti-commutation relations $\\{\\sigma_x,\\sigma_y\\} =0$\n$[\\sigma_x,\\sigma_y] =\\imath\\sigma_z$ etc.\n\n\nWhen we look at the expectation value of \n$\\langle \\mathbf{\\sigma}_1\\cdot\\mathbf{\\sigma}_2\\rangle$, we can rewrite this expression in terms of the\nspin $\\mathbf{S}=\\mathbf{s}_1+\\mathbf{s}_2$, resulting in\n\n$$\n\\langle\\mathbf{\\sigma}_1\\cdot\\mathbf{\\sigma}_2\\rangle=2(S^2-s_1^2-s_2^2)=2S(S+1)-3,\n$$\n\nwhere we $s_1=s_2=1/2$ leading to\n\n$$\n\\left\\{ \\begin{array}{cc} \\langle\\mathbf{\\sigma}_1\\cdot\\mathbf{\\sigma}_2\\rangle=1 &  \\mathrm{if} \\hspace{0.2cm} S=1\\\\\n\\langle\\mathbf{\\sigma}_1\\cdot\\mathbf{\\sigma}_2\\rangle=-3 & \\mathrm{if} \\hspace{0.2cm} S=0\\\\\\end{array}\\right.\n$$\n\nSimilarly, the expectation value of the spin-orbit term is\n\n$$\n\\langle \\mathbf{l}\\mathbf{S} \\rangle = \\frac{1}{2}\\left( J(J+1)-l(l+1)-S(S+1)\\right),\n$$\n\nwhich means that for $s$-waves with either $S=0$ and thereby $J=0$ or $S=1$ and $J=1$, \nthe expectation value for the\nspin-orbit force is zero. With the above phenomenological model, the\nonly contributions to the expectation value of the potential energy for $s$-waves\nstem  from the central and the spin-spin components since the\nexpectation value of the tensor force is also zero.\n\n\n For $s=1/2$ spin values only for two nucleons, the expectation value of the tensor force operator is \n\n<table border=\"1\">\n<thead>\n<tr><th align=\"center\">     </th> <th align=\"center\">             $l'$            </th> <th align=\"center\">   </th> <th align=\"center\">                             </th> </tr>\n</thead>\n<tbody>\n<tr><td align=\"center\">   $l$      </td> <td align=\"center\">   $J+1$                            </td> <td align=\"center\">   $J$    </td> <td align=\"center\">   $J-1$                            </td> </tr>\n<tr><td align=\"center\">            </td> <td align=\"center\">                                    </td> <td align=\"center\">          </td> <td align=\"center\">                                    </td> </tr>\n<tr><td align=\"center\">   $J+1$    </td> <td align=\"center\">   $-\\frac{2J(J+2)}{2J+1}$          </td> <td align=\"center\">   0      </td> <td align=\"center\">   $\\frac{6\\sqrt{J(J+1)}}{2J+1}$    </td> </tr>\n<tr><td align=\"center\">            </td> <td align=\"center\">                                    </td> <td align=\"center\">          </td> <td align=\"center\">                                    </td> </tr>\n<tr><td align=\"center\">   $J$      </td> <td align=\"center\">   0                                </td> <td align=\"center\">   2      </td> <td align=\"center\">   0                                </td> </tr>\n<tr><td align=\"center\">            </td> <td align=\"center\">                                    </td> <td align=\"center\">          </td> <td align=\"center\">                                    </td> </tr>\n<tr><td align=\"center\">   $J-1$    </td> <td align=\"center\">   $\\frac{6\\sqrt{J(J+1)}}{2J+1}$    </td> <td align=\"center\">   0      </td> <td align=\"center\">   $-\\frac{2(2J+1)}{2J+1}$          </td> </tr>\n<tr><td align=\"center\">            </td> <td align=\"center\">                                    </td> <td align=\"center\">          </td> <td align=\"center\">                                    </td> </tr>\n</tbody>\n</table>\nWe will derive these expressions after we have discussed the Wigner-Eckart theorem. \n\n\n\n\nIf we now add isospin to our simple $V_4$ interaction model, we end up with $8$ operators, popularly dubbed $V_8$ interaction model. The explicit form reads\n\n5\n8\n4\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n5\n8\n5\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n5\n8\n6\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\left. + C_{SL\\tau} \\left( {1\\over m_\\alpha r} + {1\\over \\left( m_\\alpha r\\right)^2}\n\\right) \\mathbf{L}\\cdot \\mathbf{S}\n\\right\\}\\mathbf{\\tau}_1\\cdot\\mathbf{\\tau}_2 \\frac{e^{-m_\\alpha r}}{m_\\alpha r}\n$$\n\nFrom 1950 till approximately 2000: One-Boson-Exchange (OBE) models dominate. These are models which typically include several low-mass mesons, that is with masses below 1 GeV.   Potentials which are based upon the standard non-relativistic operator structure\n are called \"Phenomenological Potentials\" Some historically important examples are   \n* Gammel-Thaler potential ( Phys. Rev. **107**, 291, 1339 (1957) and the \n\n* Hamada-Johnston potential, Nucl. Phys. **34**, 382 (1962)), both with a hard core.\n\n* Reid potential (Ann. Phys. (N.Y.) **50**, 411 (1968)), soft core.\n\n* Argonne $V_{14}$ potential (Wiringa et al., Phys. Rev. C **29**, 1207 (1984)) with 14 operators and  the  Argonne $V_{18}$ potential (Wiringa et al., Phys. Rev. C **51**, 38 (1995)), uses 18 operators\n\n* A good historical reference: R. Machleidt, Adv. Nucl. Phys.  **19**, 189 (1989).\n\nNow: models based on chiral perturbation theory. These are effective models with nucleons and pions as degrees of freedom only. The other mesons which appeared in standard one-boson model appear as multi-pion resonances. \n\n\n\n\nThe total two-nucleon state function has to be anti-symmetric. The total function contains a spatial part, a spin part and an isospin part. If isospin is conserved, this leads to in case we have an $s$-wave with spin $S=0$ to an isospin \ntwo-body state with $T=1$ since the spatial part is symmetric and the spin part is anti-symmetric. \n\nSince the projections for $T$ are $T_z=-1,0,1$, we can have a $pp$, an $nn$ and a $pn$ state.\n\nFor $l=0$ and $S=1$, a so-called triplet state, $^3S_1$, we must have $T=0$, meaning that we have only one state, a $pn$ state. For other partial waves, see exercises below. \n\n\n\n### Phenomenology of one-pion exchange\n\nThe one-pion exchange contribution (see derivation below), can be written as\n\n$$\nV_{\\pi}(\\mathbf{r})= -\\frac{f_{\\pi}^{2}}{4\\pi m_{\\pi}^{2}}\\mathbf{ \\tau}_1\\cdot\\mathbf{\\tau}_2\n\\frac{1}{3}\\left\\{\\mathbf{ \\sigma}_1\\cdot\\mathbf{ \\sigma}_2+\\left( 1 + {3\\over m_\\pi r} + {3\\over\\left(m_\\pi r\\right)^2}\\right) S_{12} (\\hat r)\\right\\} \\frac{e^{-m_\\pi r}}{m_\\pi r}.\n$$\n\nHere the constant $f_{\\pi}^{2}/4\\pi\\approx 0.08$ and the mass of the pion is $m_\\pi\\approx 140$ MeV/$\\mbox{c}^2$.  \n\nLet us look closer at specific partial waves for which one-pion exchange is applicable. If we have $S=0$ and $T=0$, the \norbital momentum has to be an odd number in order for the total anti-symmetry to be obeyed. For $S=0$, the tensor force component is zero, meaning that \nthe only contribution is\n\n$$\nV_{\\pi}(\\mathbf{r})=\\frac{3f_{\\pi}^{2}}{4\\pi m_{\\pi}^{2}}\\frac{e^{-m_\\pi r}}{m_\\pi r},\n$$\n\nsince $\\langle\\mathbf{ \\sigma}_1\\cdot\\mathbf{ \\sigma}_2\\rangle=-3$, that is we obtain a repulsive contribution to partial waves like \n$^1P_0$.\n\nSince $S=0$ yields always a zero tensor force contribution, for the combination of $T=1$ and then even $l$ values, we get an attractive contribution\n\n$$\nV_{\\pi}(\\mathbf{r})=-\\frac{f_{\\pi}^{2}}{4\\pi m_{\\pi}^{2}}\\frac{e^{-m_\\pi r}}{m_\\pi r}.\n$$\n\nWith $S=1$ and $T=0$, $l$ can only take even values in order to obey the anti-symmetry requirements and we get\n\n$$\nV_{\\pi}(\\mathbf{r})= -\\frac{f_{\\pi}^{2}}{4\\pi m_{\\pi}^{2}}\n\\left(1+( 1 + {3\\over m_\\pi r} + {3\\over\\left(m_\\pi r\\right))^2}) S_{12} (\\hat r)\\right) \\frac{e^{-m_\\pi r}}{m_\\pi r},\n$$\n\nwhile for $S=1$ and $T=1$, $l$ can only take odd values, resulting in a repulsive contribution\n\n$$\nV_{\\pi}(\\mathbf{r})= \\frac{1}{3}\\frac{f_{\\pi}^{2}}{4\\pi m_{\\pi}^{2}}\\left(1+( 1 + {3\\over m_\\pi r} + {3\\over\\left(m_\\pi r\\right)^2}) S_{12} (\\hat r)\\right) \\frac{e^{-m_\\pi r}}{m_\\pi r}.\n$$\n\nThe central part of one-pion exchange interaction, arising from the spin-spin term,  \nis thus attractive for $s$-waves and all even $l$ values. For $p$-waves and all other odd values\nit is repulsive. However, its overall strength is weak. This is discussed further in one of exercises below.\n\n\n\n\n\n\n## Models for nuclear forces and derivation of non-relativistic expressions\n\nTo describe the interaction between the various baryons and mesons of the previous\ntable we choose the following phenomenological\nlagrangians\nfor spin $1/2$ baryons\n\n5\n9\n3\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n{\\cal L}_{s} =g^{s}\\overline{\\Psi}\\Psi\\phi^{(s)},\n$$\n\nand\n\n$$\n{\\cal L}_{v} =g^{v}\\overline{\\Psi}\\gamma_{\\mu}\\Psi\\phi_{\\mu}^{(v)}\n   +g^{t}\\overline{\\Psi}\\sigma^{\\mu\\nu}\\Psi\\left\n   (\\partial_{\\mu}\\phi_{\\nu}^{(v)}\n   -\\partial_{\\nu}\\phi_{\\mu}^{(v)}\\right),\n$$\n\nfor pseudoscalar (ps), scalar (s) and vector (v) coupling, respectively.\nThe factors $g^{v}$ and $g^{t}$ are the vector\nand tensor coupling constants, respectively.\n\nFor spin $1/2$ baryons, the fields $\\Psi$ are expanded\nin terms of the Dirac spinors (positive energy\nsolution shown here with $\\overline{u}u=1$)\n\n$$\nu(k\\sigma)=\\sqrt{\\frac{E(k)+m}{2m}}\n\t  \\left(\\begin{array}{c} \\chi\\\\ \\\\\n\t  \\frac{\\mathbf{\\sigma}\\mathbf{k}}{E(k)+m}\\chi\n\t  \\end{array}\\right),\n$$\n\nwith $\\chi$ the familiar Pauli spinor and $E(k) =\\sqrt{m^2 +|\\mathbf{k}|^2}$. \nThe positive energy part of the field $\\Psi$ reads\n\n$$\n\\Psi (x)={\\displaystyle \\frac{1}{(2\\pi )^{3/2}}\n        \\sum_{\\mathbf{k}\\mathbf{\\sigma}}u(k\\mathbf{\\sigma})\\exp{-(ikx)}a_{\\mathbf{k}\\mathbf{\\sigma}}},\n$$\n\nwith $a$ being a fermion annihilation operator.\n\nExpanding the free Dirac spinors\nin terms of $1/m$ ($m$ is here the mass of the relevant baryon) \nresults, to lowest order, in the familiar non-relativistic\nexpressions for baryon-baryon potentials.\nThe configuration space version of the interaction can be approximated as\n\n5\n9\n8\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n+ C_{SL}\\left. \\left( {1\\over m_\\alpha r} + {1\\over \\left( m_\\alpha r\\right)^2}\n\\right) \\mathbf{L}\\cdot \\mathbf{S}\n\\right\\} \\frac{\\exp{-(m_\\alpha r)}}{m_\\alpha r},\n$$\n\nwhere $m_{\\alpha}$ is the mass of the relevant meson and\n$S_{12}$ is the familiar tensor term.\n\n\nWe derive now the non-relativistic one-pion exchange interaction.\n\nHere $p_{1}$, $p_{1}'$, $p_{2}$, $p_{2}'$ and $k=p_{1}-p_{1}'$ denote \nfour-momenta.  \nThe vertices are \ngiven by the pseudovector Lagrangian\n\n$$\n{\\cal L}_{pv}=\\frac{f_{\\pi}}{m_{\\pi}}\\overline{\\psi}\\gamma_{5}\\gamma_{\\mu}\n\\psi\\partial^{\\mu}\\phi_{\\pi}.\n$$\n\nFrom the Feynman diagram rules we can write the two-body interaction as\n\n$$\nV^{pv}=\\frac{f_{\\pi}^{2}}{m_{\\pi}^{2}}\\frac{\\overline{u}(p_{1}')\\gamma_{5}\n\\gamma_{\\mu}(p_{1}-p_{1}')^{\\mu}u(p_{1})\\overline{u}(p_{2}')\\gamma_{5}\n\\gamma_{\\nu}(p_{2}'-p_{2})^{\\nu}u(p_{2})}{(p_{1}-p_{1}')^{2}-m_{\\pi}^{2}}.\n$$\n\nThe factors $p_{1}-p_{1}'=p_{2}'-p_{2}$ are both the four-momentum of the \nexchanged meson and come from the derivative of the meson field in \nthe interaction Lagrangian. \nThe Dirac spinors obey\n\n$$\n\\begin{eqnarray*}\n\\gamma_{\\mu}p^{\\mu}u(p)&=&mu(p) \\nonumber \\\\\n\\overline{u}(p)\\gamma_{\\mu}p^{\\mu}&=&m\\overline{u}(p). \\nonumber\n\\end{eqnarray*}\n$$\n\nUsing these relations, together with $\\{\\gamma_{5},\\gamma_{\\mu}\\}=0$, we find\n\n$$\n\\begin{eqnarray*}\n\\overline{u}(p_{1}')\\gamma_{5}\\gamma_{\\mu}(p_{1}-p_{1}')^{\\mu}u(p_{1})\n&=&m\\overline{u}(p_{1}')\\gamma_{5}u(p_{1})+\\overline{u}(p_{1}')\\gamma_{\\mu}\np_{1}'^{\\mu}\\gamma_{5}u(p_{1}) \\nonumber \\\\\n &=&2m\\overline{u}(p_{1}')\\gamma_{5}u(p_{1}) \\nonumber\n\\end{eqnarray*}\n$$\n\nand\n\n$$\n\\overline{u}(p_{2}')\\gamma_{5}\\gamma_{\\mu}(p_{2}'-p_{2})^{\\mu}=\n-2m\\overline{u}(p_{2}')\\gamma_{5}u(p_{1}).\n$$\n\nWe get\n\n$$\nV^{pv}=-\\frac{f_{\\pi}^{2}}{m_{\\pi}^{2}}4m^{2}\\frac{\\overline{u}(p_{1}')\n\\gamma_{5}u(p_{1})\\overline{u}(p_{2}')\\gamma_{5}u(p_{2})}{(p_{1}-p_{1}')\n^{2}-m_{\\pi}^{2}}.\n$$\n\nBy inserting expressions for the Dirac spinors, we find\n\n$$\n\\begin{eqnarray*}\n\\overline{u}(p_{1}')\\gamma_{5}u(p_{1})&=&\\sqrt{\\frac{(E_{1}'+m)(E_{1}+m)}\n{4m^{2}}}\\left(\\begin{array}{cc}\\chi^{\\dagger}&-\\frac{\\sigma_{1}\\cdot{\n\\bf p_{1}}}{E_{1}'\n+m}\\chi^{\\dagger}\\end{array}\\right)\\left(\\begin{array}{cc}0&1\\\\1&0\\end{array}\n\\right)\\nonumber \\\\\n &&\\times \\left(\\begin{array}{c}\\chi\\\\ \\frac{\\sigma_{1}\\cdot\\mathbf{p_{1}}}{E_{1}+m}\\chi\n\\end{array}\\right) \n\\nonumber \\\\\n &=&\\sqrt{\\frac{(E_{1}'+m)(E_{1}+m)}{4m^{2}}}\\left(\\frac{\\sigma_{1}\\cdot\n\\mathbf{p_{1}}}{E_{1}+m}-\\frac{\\sigma_{1}\\cdot\\mathbf{p_{1}'}}{E_{1}'+m}\\right) \n\\nonumber \n\\end{eqnarray*}\n$$\n\nSimilarly\n\n$$\n\\overline{u}(p_{2}')\\gamma_{5}u(p_{2})=\\sqrt{\\frac{(E_{2}'+m)(E_{2}+m)}\n{4m^{2}}}\\left(\\frac{\\sigma_{2}\\cdot \\mathbf{p}_{2}}{E_{2}+m}-\n\\frac{\\sigma_{2}\\cdot\\mathbf{p'}_{2}}{E_{2}'+m}\\right).\n$$\n\nIn the CM system we have $\\mathbf{p}_{2}=-\\mathbf{p}_{1}$, $\\mathbf{p'}_{2}=\n-\\mathbf{p'}_{1}$ and so $E_{2}=E_{1}$, $E_{2}'=E_{1}'$.  \nWe can then write down the relativistic contribution \nto the NN potential in the CM system:\n\n$$\n\\begin{eqnarray}\nV^{pv}&=&-\\frac{f_{\\pi}^{2}}{m_{\\pi}^{2}}4m^{2}\\frac{1}{(p_{1}-p_{1}')^{2}-\nm_{\\pi}^{2}}\\frac{(E_{1}+m)(E_{1}'+m)}{4m^{2}} \\nonumber \\\\ \n &\\times&\\left(\\frac{\\sigma_{1}\\cdot\\mathbf{p}_{1}}{E_{1}+m}-\\frac{\\sigma_{1}\n\\cdot\\mathbf{p'}_{1}}{E_{1}'+m}\\right)\\left(\\frac{\\sigma_{2}\\cdot\\mathbf{p}_{1}}\n{E_{1}+m}-\\frac{\\sigma_{2}\\cdot\\mathbf{p'}_{1}}{E_{1}'+m}\\right). \\nonumber\n\\end{eqnarray}\n$$\n\nIn the non-relativistic limit we have to lowest order\n\n$$\nE_{1}=\\sqrt{\\mathbf{p}_{1}^{2}+m^{2}}\\approx m \\approx E_{1}'\n$$\n\nand then $(p_{1}-p_{1}')^{2}=-\\mathbf{k}^{2}$, so we get \nfor the contribution to the NN potential\n\n$$\n\\begin{eqnarray}\nV^{pv}&=&-\\frac{f_{\\pi}^{2}}{m_{\\pi}^{2}}4m^{2}\\frac{1}{\\mathbf{k}^{2}+m^{2}}\n\\frac{2m\\cdot 2m}{4m^{2}}\\frac{\\sigma_{1}}{2m}\\cdot(\\mathbf{p}_{1}-\\mathbf{p'}_{1})\n\\frac{\\sigma_{2}}{2m}\\cdot (\\mathbf{p}_{1}-\\mathbf{p'}_{1}) \\nonumber \\\\ \n &=&-\\frac{f_{\\pi}^{2}}{m_{\\pi}^{2}}\n\\frac{(\\sigma_{1}\\cdot\\mathbf{k})(\\sigma_{2}\\cdot\\mathbf{k})}{\\mathbf{k}^{2}+m_{\\pi}^{2}}.\n\\nonumber\n\\end{eqnarray}\n$$\n\nWe have omitted exchange terms and the isospin term $\\mathbf{\\tau}_1\\cdot\\mathbf{\\tau}_2$.\n\n\nWe have\n\n$$\nV^{pv}(k)=-\\frac{f_{\\pi}^{2}}{m_{\\pi}^{2}}\n\\frac{(\\sigma_{1}\\cdot\\mathbf{k})(\\sigma_{2}\\cdot\\mathbf{k})}{\\mathbf{k}^{2}+m_{\\pi}^{2}}.\n$$\n\nIn coordinate space we have\n\n$$\nV^{pv}(r)=\\int\\frac{d^3k}{(2\\pi)^3}e^{i\\mathbf{kr}}V^{pv}(k)\n$$\n\nresulting in\n\n$$\nV^{pv}(r)=-\\frac{f_{\\pi}^{2}}{m_{\\pi}^{2}}\n\\sigma_{1}\\cdot{\\nabla}\\sigma_{2}\\cdot{\\nabla}\n\\int\\frac{d^3k}{(2\\pi)^3}e^{i\\mathbf{kr}}\\frac{1}{\\mathbf{k}^{2}+m_{\\pi}^{2}}.\n$$\n\nWe obtain\n\n$$\nV^{pv}(r)=-\\frac{f_{\\pi}^{2}}{m_{\\pi}^{2}}\\sigma_{1}\\cdot{\\nabla}\\sigma_{2}\\cdot{\\nabla}\\frac{e^{-m_{\\pi}r}}{r}.\n$$\n\nCarrying out the differentation of\n\n$$\nV^{pv}(r)=-\\frac{f_{\\pi}^{2}}{m_{\\pi}^{2}}\\sigma_{1}\\cdot{\\nabla}\\sigma_{2}\\cdot{\\nabla}\\frac{e^{-m_{\\pi}r}}{r}.\n$$\n\nwe arrive at the famous one-pion exchange potential with central and tensor parts\n\n$$\nV(\\mathbf{r})= -\\frac{f_{\\pi}^{2}}{m_{\\pi}^{2}}\\left\\{C_{\\sigma}\\mathbf{\\sigma}_1\\cdot\\mathbf{\\sigma}_2+ C_T \\left( 1 + \\frac{3}{m_\\alpha r} + \\frac{3}{\\left(m_\\alpha r\\right)^2}\\right) S_{12}(\\hat r)\\right\\}\\frac{\\exp{-m_\\pi r}}{m_\\pi r}.\n$$\n\nFor the full potential add the exchange part and the $\\mathbf{\\tau}_1\\cdot\\mathbf{\\tau}_2$ term as well. (Subtle point: there is a divergence which gets cancelled by using cutoffs) This leads to coefficients $C_{\\sigma}$ and $C_T$ which are fitted to data.\n\n\nWhen we perform similar non-relativistic expansions for scalar and vector mesons we obtain\nfor the $\\sigma$ meson\n\n$$\nV^{\\sigma}= g_{\\sigma NN}^{2}\\frac{1}{\\mathbf{k}^{2}+m_{\\sigma}^{2}}\\left (-1+\\frac{\\mathbf{q}^{2}}{2M_N^2}\n-\\frac{\\mathbf{k}^{2}}{8M_N^2}-\\frac{\\mathbf{LS}}{2M_N^2}\\right).\n$$\n\nWe note an attractive central force and spin-orbit force. This term has an intermediate range.\nWe have defined $1/2(p_{1}+p_{1}')=\\mathbf{q}$.\nFor the full potential add the exchange part and the isospin dependence as well.\n\n\n\nWe obtain\nfor the $\\omega$ meson\n\n$$\nV^{\\omega}= g_{\\omega NN}^{2}\\frac{1}{\\mathbf{k}^{2}+m_{\\omega}^{2}}\\left (1-3\\frac{\\mathbf{LS}}{2M_N^2}\\right).\n$$\n\nWe note a repulsive central force and an attractive spin-orbit force. This term has  short range.\nFor the full potential add the exchange part and the isospin dependence as well.\n\n\nFinally \nfor the $\\rho$ meson\n\n$$\nV^{\\rho}= g_{\\rho NN}^{2}\\frac{\\mathbf{k}^{2}}{\\mathbf{k}^{2}+m_{\\rho}^{2}}\\left (\n-2\\sigma_{1}\\sigma_{2}+S_{12}(\\hat{k})\\right)\\tau_{1}\\tau_{2}.\n$$\n\nWe note a tensor force with sign opposite to that of the pion. This term has  short range. For the full potential add the exchange part and the isospin dependence as well.\n\n\n\n\n\n* Can use a one-boson exchange picture to construct a nucleon-nucleon interaction a la QED\n\n* Non-relativistic approximation yields amongst other things a spin-orbit force which is much stronger than in atoms.\n\n* At large intermediate distances pion exchange dominates while  pion resonances (other mesons) dominate at intermediate and short range \n\n * Potentials are parameterized to fit selected two-nucleon data, binding energies and scattering phase shifts.\n\n\n* Nowaydays, chiral perturbation theory gives an effective theory that allows a systematic expansion in terms of contrallable parameters. Good basis for many-body physics\n\n## The Lippman-Schwinger equation for two-nucleon scattering\n\nWhat follows now is a more technical discussion on how we can solve the two-nucleon problem.\nThis will lead us to the so-called Lippman-Schwinger equation for the scattering problem and a rewrite of Schroedinger's equation in relative and center-of-mass coordinates. \n\n\nBefore we break down the Schroedinger equation into a partial wave decomposition, we derive now the so-called Lippman-Schwinger equation. We will do this in an operator form first.\nThereafter, we rewrite it in terms of various quantum numbers such as relative momenta, orbital momenta etc. \nThe Schroedinger equation in abstract vector representation is\n\n$$\n\\left( \\hat{H}_0 + \\hat{V} \\right) \\vert \\psi_n \\rangle = E_n \\vert\\psi_n \\rangle.\n$$\n\nIn our case for the two-body problem $\\hat{H}_0$ is just the kinetic energy. \nWe rewrite it as\n\n$$\n\\left( \\hat{H}_0 -E_n \\right)\\vert\\psi_n \\rangle =-\\hat{V}\\vert \\psi_n \\rangle .\n$$\n\nWe assume that the invers of $\\left( \\hat{H}_0 -E_n\\right)$ exists and rewrite this equation as\n\n$$\n\\vert\\psi_n \\rangle =\\frac{1}{\\left( E_n -\\hat{H}_0\\right)}\\hat{V}\\vert \\psi_n \\rangle .\n$$\n\nThe equation\n\n$$\n\\vert \\psi_n \\rangle =\\frac{1}{\\left( E_n -\\hat{H}_0\\right)}\\hat{V}\\vert \\psi_n \\rangle,\n$$\n\nis normally solved in an iterative fashion. \nWe assume first that\n\n$$\n\\vert\\psi_n \\rangle = \\vert\\phi_n \\rangle,\n$$\n\nwhere $\\vert\\phi_n \\rangle$ are the eigenfunctions of\n\n$$\n\\hat{H}_0\\vert \\phi_n \\rangle=\\omega_n\\vert \\phi_n \\rangle\n$$\n\nthe so-called unperturbed problem. In our case, these will simply be the kinetic energies of the relative motion. \n\n\n\nInserting  $\\vert\\phi_n \\rangle$  on the right-hand side of\n\n$$\n\\vert \\psi_n \\rangle =\\frac{1}{( E_n -\\hat{H}_0)}\\hat{V}\\vert \\psi_n \\rangle,\n$$\n\nyields\n\n$$\n\\vert \\psi_n \\rangle =\\vert\\phi_n \\rangle+\\frac{1}{\\left( E_n -\\hat{H}_0\\right)}\\hat{V}\\vert \\phi_n \\rangle,\n$$\n\nas our first iteration. \nReinserting again gives\n\n$$\n\\vert \\psi_n \\rangle =\\vert\\phi_n \\rangle+\\frac{1}{\\left( E_n -\\hat{H}_0\\right)}\\hat{V}\\vert \\phi_n \\rangle+\\frac{1}{( E_n -\\hat{H}_0)}\\hat{V}\\frac{1}{\\left( E_n -\\hat{H}_0\\right)}\\hat{V}\\vert \\phi_n \\rangle,\n$$\n\nand continuing we obtain\n\n$$\n\\vert \\psi_n \\rangle =\\sum_{i=0}^{\\infty}\\left[\\frac{1}{( E_n -\\hat{H}_0)}\\hat{V}\\right]^i\\vert \\phi_n \\rangle.\n$$\n\nIt is easy to see that\n\n$$\n\\vert \\psi_n \\rangle =\\sum_{i=0}^{\\infty}\\left[\\frac{1}{(E_n -\\hat{H}_0)}\\hat{V}\\right]^i\\vert \\phi_n \\rangle,\n$$\n\ncan be rewritten as\n\n$$\n\\vert \\psi_n \\rangle =\\vert\\phi_n \\rangle+\\frac{1}{( E_n -\\hat{H}_0)}\n\\hat{V}\\left(1+ \\frac{1}{(E_n -\\hat{H}_0)}\\hat{V}+\\frac{1}{(E_n -\\hat{H}_0)}\\hat{V}\\frac{1}{(E_n -\\hat{H}_0)}\\hat{V}+\\dots\\right]\\vert \\phi_n \\rangle,\n$$\n\nwhich we rewrite as\n\n$$\n\\vert \\psi_n \\rangle =\\vert\\phi_n \\rangle+\\frac{1}{(E_n -\\hat{H}_0)}\\hat{V}\\vert \\psi_n \\rangle.\n$$\n\nIn operator form we have thus\n\n$$\n\\vert \\psi_n \\rangle =\\vert\\phi_n \\rangle+\\frac{1}{(E_n -\\hat{H}_0)}\\hat{V}\\vert \\psi_n \\rangle.\n$$\n\nWe multiply from the left with $\\hat{V}$ and $\\langle \\phi_m \\vert$ and obtain\n\n$$\n\\langle \\phi_m \\vert\\hat{V}\\vert \\psi_n \\rangle =\\langle \\phi_m \\vert\\hat{V}\\vert\\phi_n \\rangle+\\langle \\phi_m \\vert\\hat{V}\\frac{1}{(E_n -\\hat{H}_0)}\\hat{V}\\vert \\psi_n \\rangle.\n$$\n\nWe define thereafter the so-called $T$-matrix as\n\n$$\n\\langle \\phi_m \\vert\\hat{T}\\vert \\phi_n \\rangle=\\langle \\phi_m \\vert\\hat{V}\\vert \\psi_n \\rangle.\n$$\n\nWe can rewrite our equation as\n\n$$\n\\langle \\phi_m \\vert\\hat{T}\\vert \\phi_n \\rangle =\\langle \\phi_m \\vert\\hat{V}\\vert\\phi_n \\rangle+\\langle \\phi_m \\vert\\hat{V}\\frac{1}{(E_n -\\hat{H}_0)}\\hat{T}\\vert \\phi_n \\rangle.\n$$\n\nThe equation\n\n$$\n\\langle \\phi_m \\vert\\hat{T}\\vert \\phi_n \\rangle =\\langle \\phi_m \\vert\\hat{V}\\vert\\phi_n \\rangle+\\langle \\phi_m \\vert\\hat{V}\\frac{1}{(E_n -\\hat{H}_0)}\\hat{T}\\vert \\phi_n \\rangle,\n$$\n\nis called the Lippman-Schwinger equation. Inserting the completeness relation\n\n$$\n\\mathbf{1} = \\sum_n \\vert \\phi_n\\rangle\\langle \\phi_n \\vert, \\:\\: \\langle \\phi_n\\vert \\phi_{n'} \\rangle = \\delta_{n,n'}\n$$\n\nwe have\n\n$$\n\\langle \\phi_m \\vert\\hat{T}\\vert \\phi_n \\rangle =\\langle \\phi_m \\vert\\hat{V}\\vert\\phi_n \\rangle+\\sum_k \\langle \\phi_m \\vert\\hat{V}\\vert \\phi_k\\rangle\\frac{1}{(E_n -\\omega_k)}\\langle \\phi_k \\vert\\hat{T}\\vert \\phi_n \\rangle,\n$$\n\nwhich is (when we specify the state $\\vert\\phi_n \\rangle$) an integral equation that can actually be solved by matrix inversion easily! The unknown quantity is the $T$-matrix.\n\n\nNow we wish to introduce a partial wave decomposition in order to solve the Lippman-Schwinger equation. With a partial wave decomposition we can reduce a three-dimensional integral equation to a one-dimensional one. \n\nLet us continue with our Schroedinger equation in the abstract vector representation\n\n$$\n\\left(T + V\\right)\\vert\\psi_n\\rangle = E_n\\vert\\psi_n \\rangle\n$$\n\nHere $T$ is the kinetic energy operator and $V$ is the potential operator. \nThe eigenstates form a complete orthonormal set according to\n\n$$\n\\mathbf{1}=\\sum_n\\vert\\psi_n\\rangle\\langle\\psi_n\\vert, \\:\\: \\langle\\psi_n\\vert\\psi_{n'}\\rangle =\\delta_{n,n'}\n$$\n\nThe most commonly used representations are the coordinate and\nthe momentum space representations. They define the completeness relations\n\n$$\n\\begin{eqnarray*}\n \\mathbf{1}&=&  \\int d\\mathbf{r} \\:\\vert\\mathbf{r} \\rangle \\langle \\mathbf{r}\\vert, \\:\\: \\langle  \\mathbf{r}\\vert  \\mathbf{r'} \\rangle = \\delta ( \\mathbf{r}-\\mathbf{r'}) \\\\\n\\mathbf{1} &=& \\int d\\mathbf{k} \\:\\vert  \\mathbf{k}\\rangle \\langle \\mathbf{k}\\vert, \\:\\: \\langle\\mathbf{k}\\vert  \\mathbf{k'} \\rangle = \\delta ( \\mathbf{k}-\\mathbf{k'}) \n\\end{eqnarray*}\n$$\n\nHere the basis states in  both $\\mathbf{r}$- and $\\mathbf{k}$-space are dirac-delta \nfunction normalized. From this it follows that the plane-wave states are given by,\n\n$$\n\\langle\\mathbf{r}\\vert\\mathbf{k} \\rangle =\\left(\\frac{1}{2\\pi}\\right)^{3/2}\\exp\\left(i\\mathbf{k\\cdot r} \\right)\n$$\n\nwhich is a transformation function defining the mapping from the abstract \n$\\vert\\mathbf{k}\\rangle$ to the abstract $\\vert\\mathbf{r}\\rangle $ space.\n\n\nThat the $\\mathbf{r}$-space basis states are \ndelta-function normalized follows from\n\n$$\n\\delta ( \\mathbf{r}-\\mathbf{r'}) = \\langle \\mathbf{r} \\vert \\mathbf{r}'\\rangle = \\langle \\mathbf{r} \\vert \\mathbf{1} \\vert \\mathbf{r}'\\rangle = \\int d\\mathbf{k} \\langle \\mathbf{r}\\vert \\mathbf{k} \\rangle \\langle \\mathbf{k}\\vert \\mathbf{r}' \\rangle =\\left( {1\\over 2\\pi}\\right)^3 \\int d\\mathbf{k} e^{i \\mathbf{k}(\\mathbf{r} - \\mathbf{r}')}\n$$\n\nand the same for the momentum space basis states,\n\n$$\n\\delta ( \\mathbf{k}-\\mathbf{k'}) = \\langle \\mathbf{k} \\vert \\mathbf{k}'\\rangle = \\langle \\mathbf{k} \\vert \\mathbf{1} \\vert \\mathbf{k}'\\rangle =\\int d\\mathbf{r} \\langle \\mathbf{k}\\vert \\mathbf{r} \\rangle \\langle \\mathbf{r}\\vert \\mathbf{k}' \\rangle = \\left( {1\\over 2\\pi}\\right)^3 \\int d\\mathbf{r} e^{i \\mathbf{r}(\\mathbf{k} - \\mathbf{k}')}\n$$\n\nProjecting  on momentum states, we obtain the momentum space Schroedinger equation as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:momspace1\"></div>\n\n$$\n\\begin{equation}\n\\frac{\\hbar^2}{2\\mu}k^2\\psi_n(\\mathbf{k})+\\int d\\mathbf{k'}V(\\mathbf{k}, \\mathbf{k'}) \\psi_n(\\mathbf{k'})=E_n \\psi_n(\\mathbf{k})\n\\label{eq:momspace1} \\tag{109}\n\\end{equation}\n$$\n\nHere the notation $\\psi_n(\\mathbf{k}) =\\langle\\mathbf{k}\\vert\\psi_n\\rangle $ and \n$\\langle\\mathbf{k}\\vert V\\vert\\mathbf{k}' \\rangle =V(\\mathbf{k}, \\mathbf{k'})$ has been introduced.\nThe potential in momentum space is given by a double Fourier-transform \nof the potential in coordinate space, i.e.\n\n$$\nV(\\mathbf{k},\\mathbf{k'}) = \\left( \\frac{1}{2\\pi}\\right)^3\\int d\\mathbf{r}\\int d\\mathbf{r}'\\exp{-i\\mathbf{kr}}V(\\mathbf{r},\\mathbf{r}')\\exp{i\\mathbf{k}'\\mathbf{r}'}\n$$\n\nHere it is assumed that the potential interaction does not contain any spin dependence. \nInstead of a differential equation in coordinate space, the Schroedinger\nequation becomes an integral equation in momentum space. This has \nmany tractable features. Firstly, most realistic \nnucleon-nucleon interactions derived from field-theory are given \nexplicitly in momentum space. Secondly, the boundary conditions imposed\non the differential equation in coordinate space are automatically built into the\nintegral equation. And last, but not least, integral equations are easy to numerically \nimplement, and convergence is obtained by just increasing the number of integration\npoints.\nInstead of solving the three-dimensional integral equation, an \ninfinite set of 1-dimensional equations can be obtained via a  partial wave\nexpansion. \n\n\nThe wave function $\\psi_n(\\mathbf{k})$ can be expanded in a complete set of spherical harmonics, that is\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:part_wave1\"></div>\n\n$$\n\\begin{equation}\n  \\psi_n(\\mathbf{k}) = \\sum _{lm} \\psi_{nlm}(k)Y_{lm}(\\hat{k}) \\hspace{1cm} \\psi_{nlm}(k) = \\int d\\hat{k} Y_{lm}^*(\\hat{k})\\psi_n(\\mathbf{k}).   , \n  \\label{eq:part_wave1} \\tag{110}\n\\end{equation}\n$$\n\nBy inserting equation [(110)](#eq:part_wave1) in equation [(109)](#eq:momspace1), and projecting from the left\n$Y_{lm}(\\hat{k})$, the three-dimensional Schroedinger equation [(109)](#eq:momspace1) is reduced\nto an infinite set of  1-dimensional angular momentum coupled integral equations,\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:part_wave2\"></div>\n\n$$\n\\begin{equation}\n  \\left( \\frac{\\hbar^2}{2\\mu} k^2-E_{nlm}\\right)\\psi_{nlm}(k) = -\\sum_{l'm'}\\int_{0}^\\infty dk' {k'}^2 V_{lm, l'm'}(k,k') \\psi_{nl'm'}(k') \n  \\label{eq:part_wave2} \\tag{111}\n\\end{equation}\n$$\n\nwhere the angular momentum projected potential takes the form,\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:pot1\"></div>\n\n$$\n\\begin{equation}\n  V_{lm, l'm'}(k,k') = \\int d{\\hat{k}} \\int d{\\hat{k}'}Y_{lm}^*(\\hat{k})V(\\mathbf{k}\\mathbf{k'})Y_{l'm'}(\\hat{k}')\n  \\label{eq:pot1} \\tag{112}\n\\end{equation}\n$$\n\nhere $d\\hat{k} = d\\theta\\sin(\\theta)d\\varphi$.\nNote that we discuss only the orbital momentum, we will include angular momentum and spin later. \n\n\n\nThe potential is often given in position space. It is then convenient to establish \nthe connection between $V_{lm, l'm'}(k,k')$ and $V_{lm, l'm'}(r,r')$. Inserting \nthe completeness relation for the position quantum numbers in equation [(112)](#eq:pot1) results in\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:pot2\"></div>\n\n$$\n\\begin{equation}\nV =\\int d\\mathbf{r}\\int d\\mathbf{r}'\\left\\{\\int d{\\hat{k}}Y_{lm}^*(\\hat{k})\\langle \\mathbf{k}\\vert \\mathbf{r}\\rangle\\right\\}\\langle\\mathbf{r}\\vert V\\vert\\mathbf{r}'\\rangle\\left\\{\\int d\\hat{k}'Y_{lm}(\\hat{k}')\\langle\\mathbf{r'}\\vert\\mathbf{k}'\\rangle\\right\\}\n\\label{eq:pot2} \\tag{113}\n\\end{equation}\n$$\n\nSince the plane waves depend only on the absolute values of position and momentum, $\\vert\\mathbf{k}\\vert$ and \n$\\vert\\mathbf{r}\\vert$,\nand the angle between them, $\\theta_{kr}$, they may be expanded in terms of bipolar harmonics of \nzero rank, i.e.\n\n$$\n\\exp{(i \\mathbf{k}\\cdot \\mathbf{r})} = 4\\pi\\sum_{l=0}^{\\infty} i^l j_l(kr)\\left( Y_l(\\hat{k}) \\cdot Y_l(\\hat{r}) \\right)= \\sum_{l=0}^{\\infty} (2l+1)i^l j_l(kr) P_l(\\cos \\theta_{kr})\n$$\n\nwhere the addition theorem for spherical harmonics has been used in order to write\nthe expansion in terms of Legendre polynomials. The spherical Bessel functions, $j_l(z)$,  \nare given in terms of Bessel functions of the first kind with half integer orders,\n\n$$\nj_l(z) = \\sqrt{\\pi \\over 2 z} J_{l+1/2}(z).\n$$\n\nInserting the plane-wave expansion\ninto the brackets of equation [(113)](#eq:pot2) yields,\n\n$$\n\\begin{eqnarray*}\n  \\nonumber\n  \\int d{\\hat{k}}  Y_{lm}^*(\\hat{k})\\langle \\mathbf{k}\\vert \\mathbf{r} \\rangle & = &  \n  \\left( {1\\over 2\\pi} \\right) ^{3/2}4\\pi i^{-l} j_l(kr) Y_{lm}^*(\\hat{r}), \\\\  \n  \\nonumber\n  \\int d{\\hat{k}'}\\:   Y_{lm}(\\hat{k}') \\langle \\mathbf{r'}\\vert \\mathbf{k}' \\rangle & = &  \n  \\left( {1\\over 2\\pi} \\right) ^{3/2}4\\pi i^{l'} j_{l'}(k'r') Y_{l'm'}(\\hat{r}). \n\\end{eqnarray*}\n$$\n\nThe connection between the momentum- and position space angular momentum \nprojected potentials are then given,\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:pot3\"></div>\n\n$$\nV_{lm, l'm'}(k,k')=\\frac{2}{\\pi}i^{l'-l}\\int_0^\\infty drr^2 \\int_0^\\infty dr'{r'}^2j_l(kr) V_{lm,l'm'}(r,r') j_{l'}(k'r')\n  \\label{eq:pot3} \\tag{114}\n$$\n\nwhich is known as a double Fourier-Bessel transform. The position space angular \nmomentum projected potential is given by\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:pot4\"></div>\n\n$$\nV_{lm, l'm'}(r,r') = \\int d{\\hat{r}} \\int d{\\hat{r}'}Y_{lm}^*(\\hat{r})V(\\mathbf{r}, \\mathbf{r'})Y_{l'm'}(\\hat{r}').\n  \\label{eq:pot4} \\tag{115}\n$$\n\nNo assumptions of locality/non-locality and deformation of the interaction has so far been made, \nand the result in equation [(114)](#eq:pot3) is general. In position space the Schroedinger equation \ntakes form of an integro-differential equation in case of a non-local interaction, \nin momentum space the Schroedinger equation is an ordinary integral equation of the Fredholm type, \nsee equation [(111)](#eq:part_wave2). This is a further advantage of the momentum space approach as compared to \nthe standard position space approach.  \nIf we assume that the \ninteraction is of local character, i.e.\n\n$$\n\\langle \\mathbf{r}\\vert V \\vert \\mathbf{r'}\\rangle = V(\\mathbf{r}) \\delta( \\mathbf{r}-\\mathbf{r}' ) = \n  V(\\mathbf{r}) {\\delta( { r}-{r}' ) \\over r^2} \\delta ( \\cos \\theta - \\cos \\theta' ) \\delta (\\varphi-\\varphi'),\n$$\n\nthen equation [(115)](#eq:pot4) reduces to\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:pot5\"></div>\n\n$$\n\\begin{equation}\n  V_{lm, l'm'}(r,r') = \\frac{\\delta({r}-{r}')}{r^2}\\int d{\\hat{r}}\\:\n  Y_{lm}^*(\\hat{r})V(\\mathbf{r})Y_{l'm'}(\\hat{r}),\n  \\label{eq:pot5} \\tag{116}\n\\end{equation}\n$$\n\nand equation [(114)](#eq:pot3) reduces to\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:pot6\"></div>\n\n$$\n\\begin{equation}\n  V_{lm, l'm'}(k,k') = \\frac{2}{\\pi}i^{l' -l}\\int_0^\\infty drr^2j_l(kr) V_{lm,l'm'}(r) j_{l'}(k'r)\n  \\label{eq:pot6} \\tag{117}\n\\end{equation}\n$$\n\nwhere\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:pot10\"></div>\n\n$$\n\\begin{equation}\n  V_{lm, l'm'}(r) = \\int d{\\hat{r}}Y_{lm}^*(\\hat{r})V(\\mathbf{r})Y_{l'm'}(\\hat{r}),\n  \\label{eq:pot10} \\tag{118}\n\\end{equation}\n$$\n\nIn the case that the interaction is central, $V(\\mathbf{r}) = V(r)$, then\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:pot7\"></div>\n\n$$\n\\begin{equation}\n  V_{lm, l'm'}(r) = V(r) \\int d{\\hat{r}}Y_{lm}^*(\\hat{r})Y_{l'm'}(\\hat{r}) = V(r) \\delta_{l,l'}\\delta_{m,m'},\n  \\label{eq:pot7} \\tag{119}\n\\end{equation}\n$$\n\nand\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:pot8\"></div>\n\n$$\n\\begin{equation}\n  V_{lm, l'm'}(k,k') = \\frac{2}{\\pi} \\int_0^\\infty drr^2j_l(kr) V(r) j_{l'}(k'r)\\delta_{l,l'}\\delta_{m,m'} = V_l(k,k') \\delta_{l,l'}\\delta_{m,m'}\n  \\label{eq:pot8} \\tag{120}\n\\end{equation}\n$$\n\nwhere the momentum space representation of the interaction finally reads,\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:pot9\"></div>\n\n$$\n\\begin{equation}\n  V_{l}(k,k') = {2 \\over \\pi} \\int_0^\\infty dr\\: r^2 \\:\n  j_l(kr) V(r) j_{l}(k'r).\n  \\label{eq:pot9} \\tag{121}\n\\end{equation}\n$$\n\nFor a local and spherical symmetric potential, \nthe coupled momentum space Schroedinger equations given in equation [(111)](#eq:part_wave2)\ndecouples in angular momentum, \ngiving\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:momentum_space\"></div>\n\n$$\n\\begin{equation}\n\\frac{\\hbar^2}{2\\mu} k^2 \\psi_{n l}(k) +\\int_{0}^\\infty dk' {k'}^2 V_{l}(k,k') \\psi_{n l }(k')=E_{n l} \\psi_{n l}(k) \n  \\label{eq:momentum_space} \\tag{122}\n\\end{equation}\n$$\n\nWhere we have written $\\psi_{n l }(k)=\\psi_{nlm}(k)$, since the \nequation becomes independent of the projection $m$ for spherical symmetric interactions. \nThe momentum space wave functions $\\psi_{n l}(k)$ defines a complete orthogonal set \nof functions, which spans the space of functions with a positive finite Euclidean norm \n (also called $l^2$-norm), $\\sqrt{\\langle\\psi_n\\vert\\psi_n\\rangle}$, which \nis a Hilbert space. The corresponding normalized wave function in coordinate space\nis given by the Fourier-Bessel transform\n\n$$\n\\phi_{n l}(r)  = \\sqrt{\\frac{2}{\\pi}}\\int dk k^2 j_l(kr) \\psi_{n l}(k)\n$$\n\nWe will thus assume that the interaction is spherically symmetric and use\nthe partial wave expansion of the plane waves in\nterms of spherical harmonics.\nThis means that we can separate the radial part of the wave function from its\nangular dependence. The wave function of the relative motion is described\nin terms of plane waves as\n\n$$\n\\exp{(\\imath \\mathbf{kr})}=\\langle\\mathbf{r}\\vert\\mathbf{k}\\rangle=4\\pi\\sum_{lm}\\imath^{l}j_{l}(kr)Y_{lm}^{*}(\\mathbf{\\hat{k}})Y_{lm}(\\mathbf{\\hat{r}}),\n$$\n\nwhere $j_l$ is a spherical Bessel function and $Y_{lm}$ the\nspherical harmonics.\n\n\n\nIn terms of the relative and center-of-mass momenta $\\mathbf{k}$ and\n$\\mathbf{K}$, the potential in momentum space is related to the nonlocal operator\n$V(\\mathbf{r},\\mathbf{r}')$ by\n\n$$\n\\langle\\mathbf{k'K'}\\vert V \\vert \\mathbf{kK}\\rangle =\\int d\\mathbf{r}d \\mathbf{r'}\n        \\exp{-(\\imath \\mathbf{k'r'})}V(\\mathbf{r'},\\mathbf{r})\\exp{\\imath \\mathbf{kr}}\\delta(\\mathbf{K},\\mathbf{K'}).\n$$\n\nWe will assume that the interaction is spherically symmetric.\nCan separate the radial part of the wave function from its\nangular dependence. The wave function of the relative motion is described\nin terms of plane waves as\n\n$$\n\\exp{(\\imath \\mathbf{kr})} =\\langle\\mathbf{r}\\vert\\mathbf{k}\\rangle= 4\\pi\\sum_{lm}\\imath^{l}j_{l}(kr)Y_{lm}^{*}(\\mathbf{\\hat{k}})Y_{lm}(\\mathbf{\\hat{r}}),\n$$\n\nwhere $j_l$ is a spherical Bessel function and $Y_{lm}$ the\nspherical harmonic.\n\n\n\nThis partial wave basis is useful for defining the operator for\nthe nucleon-nucleon interaction, which\nis symmetric with respect to rotations, parity and\nisospin transformations. These symmetries imply that the interaction is\ndiagonal with respect to the quantum numbers of total relative angular\nmomentum ${\\cal J}$, spin $S$ and isospin $T$ (we skip isospin for the moment). Using the above plane wave expansion,\nand coupling to final ${\\cal J}$ and $S$ and $T$ we get\n\n6\n6\n9\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\langle lm_lSm_S|{\\cal J}M\\rangle \\langle l'm_{l'}Sm_S|{\\cal J}M\\rangle\\langle k'l'S{\\cal J}M\\vert V \\vert klS{\\cal J}M\\rangle,\n$$\n\nwhere we have defined\n\n$$\n\\langle k'l'S{\\cal J}M\\vert V \\vert klS{\\cal J}M\\rangle=\\int j_{l'}(k'r')\\langle l'S{\\cal J}M\\vert V(r',r)\\vert lS{\\cal J}M\\rangle j_l(kr) {r'}^2 dr' r^2 dr.\n$$\n\nWe have omitted the momentum of the center-of-mass motion $\\mathbf{K}$ and the \ncorresponding orbital momentum $L$, since the interaction is diagonal\nin these variables.\n\n\n\nWe wrote the Lippman-Schwinger equation as\n\n$$\n\\langle \\phi_m \\vert\\hat{T}\\vert \\phi_n \\rangle =\\langle \\phi_m \\vert\\hat{V}\\vert\\phi_n \\rangle+\\sum_k \\langle \\phi_m \\vert\\hat{V}\\vert \\phi_k\\rangle\\frac{1}{(E_n -\\omega_k)}\\langle \\phi_k \\vert\\hat{T}\\vert \\phi_n \\rangle.\n$$\n\nHow do we rewrite it in a partial wave expansion with momenta $k$?\n\n\n\nThe general structure of the $T$-matrix in partial waves is\n\n6\n7\n3\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:bspartial\"></div>\n\n$$\n\\begin{equation}\n   +{\\displaystyle \\frac{2}{\\pi}\\sum_{l''m_{l''}M_S}\\int_{0}^{\\infty} d \\mathbf{q}\n   (\\langle l''m_{l''}Sm_S|{\\cal J}M\\rangle)^2\n   \\frac{Y_{l''m_{l''}}^*(\\hat{\\mathbf{q}})\n   Y_{l''m_{l''}}(\\hat{\\mathbf{q}}) V_{ll''}^{\\alpha}(kq)\n   T_{l''l'}^{\\alpha}(qk'K\\omega)}\n   {\\omega -H_0}},\n   \\label{eq:bspartial} \\tag{123}\n\\end{equation}\n$$\n\nThe  shorthand notation\n\n$$\nT_{ll'}^{\\alpha}(kk'K\\omega)=\n   \\langle kKlL{\\cal J}S\\vert T(\\omega)\\vert k'Kl'L{\\cal J}S\\rangle,\n$$\n\ndenotes the $T$-matrix\nwith momenta $k$ and $k'$ and orbital momenta $l$ and $l'$\nof the relative motion, and\n$K$ is the corresponding momentum of\nthe center-of-mass motion. Further, $L$, ${\\cal J}$, $S$ and $T$\nare the orbital momentum of the center-of-mass motion, the\ntotal angular momentum,\nspin and isospin, respectively. \nDue to the nuclear tensor force, the interaction is not diagonal in $ll'$.\n\n\nUsing the orthogonality\nproperties of the Clebsch-Gordan coefficients and the spherical harmonics,\nwe obtain the well-known\none-dimensional angle independent\nintegral equation\n\n$$\nT_{ll'}^{\\alpha}(kk'K\\omega)=V_{ll'}^{\\alpha}(kk')\n   +\\frac{2}{\\pi}\\sum_{l''}\\int_{0}^{\\infty} dqq^2\n   \\frac{V_{ll''}^{\\alpha}(kq)\n   T_{l''l'}^{\\alpha}(qk'K\\omega)}\n   {\\omega -H_0}.\n$$\n\nInserting the denominator we arrive at\n\n$$\n\\hat{T}_{ll'}^{\\alpha}(kk'K)=\\hat{V}_{ll'}^{\\alpha}(kk')\n   +\\frac{2}{\\pi}\\sum_{l''}\\int_{0}^{\\infty} dqq^2\n   \\hat{V}_{ll''}^{\\alpha}(kq)\n   \\frac{1}{k^2-q^2 +i\\epsilon}\n   \\hat{T}_{l''l'}^{\\alpha}(qk'K).\n$$\n\nTo parameterize the nucleon-nucleon interaction we solve the Lippman-Scwhinger\nequation\n\n$$\nT_{ll'}^{\\alpha}(kk'K)=V_{ll'}^{\\alpha}(kk')\n   +\\frac{2}{\\pi}\\sum_{l''}\\int_{0}^{\\infty} dqq^2\n   V_{ll''}^{\\alpha}(kq)\n   \\frac{1}{k^2-q^2 +i\\epsilon}\n   T_{l''l'}^{\\alpha}(qk'K).\n$$\n\nThe  shorthand notation\n\n$$\nT(\\hat{V})_{ll'}^{\\alpha}(kk'K\\omega)=\\langle kKlL{\\cal J}S\\vert T(\\omega)\\vert k'Kl'L{\\cal J}S\\rangle,\n$$\n\ndenotes the $T(V)$-matrix\nwith momenta $k$ and $k'$ and orbital momenta $l$ and $l'$\nof the relative motion, and\n$K$ is the corresponding momentum of\nthe center-of-mass motion. Further, $L$, ${\\cal J}$, and $S$\nare the orbital momentum of the center-of-mass motion, the\ntotal angular momentum and\nspin, respectively. We skip for the moment isospin.\n\n\nFor scattering states, the energy is positive, $E>0$. \nThe Lippman-Schwinger equation (a rewrite of the Schroedinger equation)\nis an integral equation\nwhere we have to deal with the amplitude \n$R(k,k')$ (reaction matrix, which is the real part of  the full\ncomplex $T$-matrix)\ndefined through the integral equation for one partial wave (no coupled-channels)\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:ls1\"></div>\n\n$$\n\\begin{equation}\n    R_l(k,k') = V_l(k,k') +\\frac{2}{\\pi}{\\cal P}\n                \\int_0^{\\infty}dqq^2V_l(k,q)\\frac{1}{E-q^2/m}R_l(q,k').\n   \\label{eq:ls1} \\tag{124}\n\\end{equation}\n$$\n\nFor negative energies (bound states) and intermediate states scattering states blocked\nby  occupied states below the Fermi level.\n\n\nThe symbol ${\\cal P}$ in the previous slide indicates that Cauchy's principal-value prescription\nis used in order to avoid the singularity arising from the zero of the denominator.\n\n\nThe total kinetic energy of the two \nincoming particles in the center-of-mass system\nis\n\n$$\nE=\\frac{k_0^2}{m_n}.\n$$\n\nThe matrix $R_l(k,k')$ relates to the \nthe  phase shifts through its diagonal elements as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:shifts\"></div>\n\n$$\n\\begin{equation}\n     R_l(k_0,k_0)=-\\frac{tan\\delta_l}{mk_0}.\n     \\label{eq:shifts} \\tag{125}\n\\end{equation}\n$$\n\nFrom now on we will drop the subscript $l$ in all equations.\nIn order to solve the Lippman-Schwinger equation \nin momentum space, we need first to write \na function which sets up the mesh points. \nWe need to do that since we are going to approximate an integral\nthrough\n\n$$\n\\int_a^bf(x)dx\\approx\\sum_{i=1}^Nw_if(x_i),\n$$\n\nwhere we have fixed $N$ lattice points through the corresponding weights\n$w_i$ and points $x_i$. Typically obtained via methods like Gaussian quadrature.\n\n\nIf you use Gauss-Legendre the points are determined for the interval $x_i\\in [-1,1]$\nYou map these points over to the limits in your integral. You can then\nuse the following mapping\n\n$$\nk_i=const\\times tan\\left\\{\\frac{\\pi}{4}(1+x_i)\\right\\},\n$$\n\nand\n\n$$\n\\omega_i= const\\frac{\\pi}{4}\\frac{w_i}{cos^2\\left(\\frac{\\pi}{4}(1+x_i)\\right)}.\n$$\n\nIf you choose units fm$^{-1}$ for $k$, set $const=1$. If you choose to work\nwith MeV, set $const\\sim 200$ ($\\hbar c=197$ MeVfm).\n\n\n\nThe principal value integral is rather tricky\nto evaluate numerically, mainly since computers have limited\nprecision. We will here use a subtraction trick often used\nwhen dealing with singular integrals in numerical calculations.\nWe introduce first the calculus relation\n\n$$\n\\int_{-\\infty}^{\\infty} \\frac{dk}{k-k_0} =0.\n$$\n\nIt means that the curve $1/(k-k_0)$ has equal and opposite\nareas on both sides of the singular point $k_0$. If we break\nthe integral into one over positive $k$ and one over \nnegative $k$, a change of variable $k\\rightarrow -k$ \nallows us to rewrite the last equation as\n\n$$\n\\int_{0}^{\\infty} \\frac{dk}{k^2-k_0^2} =0.\n$$\n\nWe can then express a principal values integral\nas\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:trick\"></div>\n\n$$\n\\begin{equation}\n  {\\cal P}\\int_{0}^{\\infty} \\frac{f(k)dk}{k^2-k_0^2} =\n  \\int_{0}^{\\infty} \\frac{(f(k)-f(k_0))dk}{k^2-k_0^2},\n   \\label{eq:trick} \\tag{126}\n\\end{equation}\n$$\n\nwhere the right-hand side is no longer singular at \n$k=k_0$, it is proportional to the derivative $df/dk$,\nand can be evaluated numerically as any other integral.\n\n\n\nWe can then use this trick to obtain\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:ls2\"></div>\n\n$$\n\\begin{equation}\n    R(k,k') = V(k,k') +\\frac{2}{\\pi}\n                \\int_0^{\\infty}dq\n                \\frac{q^2V(k,q)R(q,k')-k_0^2V(k,k_0)R(k_0,k')  }\n                     {(k_0^2-q^2)/m}.\n   \\label{eq:ls2} \\tag{127}\n\\end{equation}\n$$\n\nThis is the equation to solve numerically in order\nto calculate the phase shifts. We are interested in obtaining\n$R(k_0,k_0)$.\n\n\n\nHow do we proceed?\n\nUsing the mesh points $k_j$ and the weights $\\omega_j$,\n         we reach\n\n$$\nR(k,k') = V(k,k') +\\frac{2}{\\pi}\n          \\sum_{j=1}^N\\frac{\\omega_jk_j^2V(k,k_j)R(k_j,k')}\n                           {(k_0^2-k_j^2)/m}\n           -\\frac{2}{\\pi}k_0^2V(k,k_0)R(k_0,k')\n          \\sum_{n=1}^N\\frac{\\omega_n}\n                           {(k_0^2-k_n^2)/m}.\n$$\n\nThis equation contains now the unknowns $R(k_i,k_j)$\n(with dimension $N\\times N$) and $R(k_0,k_0)$.\n\nWe can turn it into an equation\nwith dimension $(N+1)\\times (N+1)$ with  a mesh\nwhich contains the original mesh points $k_j$ for $j=1,N$\nand the point which corresponds to the energy $k_0$.\nConsider the latter as the 'observable' point.\nThe mesh points become then $k_j$ for $j=1,n$ and\n$k_{N+1}=k_0$. \n\nWith these new mesh points we define the matrix\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:aeq\"></div>\n\n$$\n\\begin{equation}\n      A_{i,j}=\\delta_{i,j}-V(k_i,k_j)u_j,\n      \\label{eq:aeq} \\tag{128}\n\\end{equation}\n$$\n\nwhere $\\delta$ is the Kronecker $\\delta$\nand\n\n$$\nu_j=\\frac{2}{\\pi}\\frac{\\omega_jk_j^2}{(k_0^2-k_j^2)/m}\\hspace{1cm} j=1,N\n$$\n\nand\n\n$$\nu_{N+1}=-\\frac{2}{\\pi}\\sum_{j=1}^N\\frac{k_0^2\\omega_j}{(k_0^2-k_j^2)/m}.\n$$\n\nThe first task is then to \nset up the matrix $A$ for a given $k_0$. This is an\n$(N+1)\\times (N+1)$ matrix. It can be convenient\nto have an outer loop which runs over the chosen\nobservable values for the energy $k_0^2/m$.\n{\\em Note that all mesh points $k_j$ for $j=1,N$ must be\ndifferent from $k_0$. Note also that\n$V(k_i,k_j)$ is an\n$(N+1)\\times (N+1)$ matrix}. \n\nWith the matrix $A$ we can rewrite the problem as a matrix problem of dimension $(N+1)\\times (N+1)$.\nAll matrices $R$, $A$ and $V$ have this dimension and we get\n\n$$\nA_{i,l}R_{l,j}=V_{i,j},\n$$\n\nor just\n\n$$\nAR=V.\n$$\n\nSince you already have defined $A$ and $V$\n(these are stored as $(N+1)\\times (N+1)$ matrices) \nThe final equation involves only the unknown\n$R$. We obtain it by matrix inversion, i.e.,\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:final2\"></div>\n\n$$\n\\begin{equation}\n    R=A^{-1}V.\n    \\label{eq:final2} \\tag{129}\n\\end{equation}\n$$\n\nThus, to obtain $R$, you will need to set up the matrices\n$A$ and $V$ and invert the matrix $A$. \nWith the inverse $A^{-1}$, perform\na matrix multiplication with $V$ results in $R$.\n\n\n\nWith $R$ you can then evaluate the phase shifts\nby noting that\n\n$$\nR(k_{N+1},k_{N+1})=R(k_0,k_0)=-\\frac{tan\\delta}{mk_0},\n$$\n\nwhere $\\delta$ are the phase shifts.\n\n\n\nFor elastic scattering, the scattering potential can only change the outgoing spherical wave function up to a phase. In the asymptotic limit, far away from the scattering potential, we get for the spherical bessel function\n\n$$\nj_l(kr) \\xrightarrow[]{ r \\gg 1} \\frac{\\sin(kr -l\\pi/2)}{kr} =  \\frac{1}{2ik}\\left( \\frac{e^{i(kr-l\\pi/2)}}{r} - \\frac{e^{-i(kr-l\\pi/2)}}{r}\\right)\n$$\n\nThe outgoing wave will change by a phase shift $\\delta_l$, from which we can define the S-matrix $S_l(k) = e^{2i\\delta_l(k)}$. Thus, we have\n\n$$\n\\frac{e^{i(kr-l\\pi/2)}}{r} \\xrightarrow[]{\\mathrm{phase change}}  \\frac{S_l(k)e^{i(kr-l\\pi/2)}}{r}\n$$\n\nThe solution to the Schrodinger equation for a spherically symmetric potential, will have the form\n\n$$\n\\psi_k(r) = e^{ikr} + f(\\theta)\\frac{e^{ikr}}{r}\n$$\n\nwhere $f(\\theta)$ is the scattering amplitude, and related to the differential cross section as\n\n$$\n\\frac{d\\sigma}{d\\Omega} = |f(\\theta)|^2\n$$\n\nUsing the expansion of a plane wave in spherical waves, we can relate the scattering amplitude $f(\\theta)$ with the partial wave phase shifts $\\delta_l$ by identifying the outgoing wave\n\n$$\n\\psi_k(r) = e^{ikr} + \\left[\\frac{1}{2ik}\\sum_l i^l (2l+1) (S_l(k)-1)P_l(\\cos(\\theta))e^{-il\\pi/2}\\right] \\frac{e^{ikr}}{r}\n$$\n\nwhich can be simplified further by cancelling $i^l$ with $e^{-il\\pi/2}$ \n\n\n\nWe have\n\n$$\n\\psi_k(r) = e^{ikr} + f(\\theta) \\frac{e^{ikr}}{r}\n$$\n\nwith\n\n$$\nf(\\theta) = \\sum_l (2l+1)f_l(\\theta) P_l(\\cos(\\theta))\n$$\n\nwhere the partial wave scattering amplitude is given by\n\n$$\nf_l(\\theta) = \\frac{1}{k}\\frac{(S_l(k)-1)}{2i} = \\frac{1}{k}\\sin\\delta_l(k) e^{i\\delta_l(k)}\n$$\n\nWith Eulers formula for the cotangent, this can also be written as\n\n$$\nf_l(\\theta) = \\frac{1}{k}\\frac{1}{\\cot \\delta_l(k) - i}.\n$$\n\n<p>Examples of negative and positive phase shifts for repulsive and attractive potentials, respectively.</p>\n\n\n\n\n\nThe integrated cross section is given by\n\\[\n\\sigma = 2\\pi \\int_0^{\\pi} |f(\\theta)|^2 \\sin \\theta d\\theta \n\\]\n\\[\n=2\\pi \\sum_l |\\frac{(2l+1)}{k} \\sin(\\delta_l)|^2 \\int_0^{\\pi} (P_l(\\cos(\\theta)))^2 \\sin(\\theta) d\\theta\\]\n\\[ \n= \\frac{4\\pi}{k^2} \\sum_l (2l+1) \\sin^2\\delta_l(k) = 4\\pi \\sum_l (2l+1)|f_l(\\theta)|^2, \n\\]\nwhere the orthogonality of the Legendre polynomials was used to evaluate the last integral\n\\[\n\\int_0^{\\pi} P_l(\\cos \\theta)^2 \\sin \\theta d\\theta = \\frac{2}{2l+1}.\n\\]\nThus, the **total** cross section is the sum of the partial-wave cross sections. Note that the differential cross section contains cross-terms from different partial waves. The integral over the full sphere enables the use of the legendre orthogonality, and this kills the cross-terms.\n\n\n\n\nAt low energy, $k \\rightarrow 0$, S-waves are most important. In this region we can define the scattering length $a$ and the effective range $r$. The $S-$wave scattering amplitude is given by\n\\[\nf_l(\\theta) = \\frac{1}{k}\\frac{1}{\\cot \\delta_l(k) - i}.\n\\]\nTaking the limit $k \\rightarrow 0$, gives us the expansion\n\\[\nk \\cot \\delta_0 = -\\frac{1}{a} + \\frac{1}{2}r_0 k^2 + \\ldots\n\\]\nThus the low energy cross section is given by\n\\[\n\\sigma = 4\\pi a^2.\n\\]\nIf the system contains a bound state, the scattering length will become positive (neutron-proton in $^3S_1$). For the $^1S_0$ wave, the scattering length is negative and large. This indicates that the wave function of the system is at the verge of turning over to get a node, but cannot create a bound state in this wave.\n\n\n\n\n<p>Examples of scattering lengths.</p>\n\n\n\n\n\nIt is important to realize that the phase shifts themselves are not\nobservables. The measurable scattering quantity is the cross section,\nor the differential cross section. The partial wave phase shifts can\nbe thought of as a parameterization of the (experimental) cross\nsections. The phase shifts provide insights into the physics of\npartial wave projected nuclear interactions, and are thus important\nquantities to know.\n\nThe nucleon-nucleon differential cross section\nhave been measured at almost all energies up to the pion production\nthreshold (290 MeV in the Lab frame), and this experimental data base\nis what provides us with the constraints on our nuclear interaction\nmodels. In order to pin down the unknown coupling constants of the\ntheory, a statistical optimization with respect to cross sections need\nto be carried out. This is how we constrain the nucleon-nucleon\ninteraction in practice!\n\n\n\n\n\n\n<p>Nijmegen phase shifts for selected partial waves.</p>\n\n\n\n\nThe $pp$-data is more accurate than the $np$-data, and for $nn$ there is no data. The quality of a potential is gauged by the $\\chi^2$/datum with respect to the scattering data base\n\n\n\n<table border=\"1\">\n<thead>\n<tr><th align=\"center\">$T_{\\mathrm{lab}}$ bin (MeV)</th> <th align=\"center\">    N3LO$^1$   </th> <th align=\"center\">   NNLO$^2$  </th> <th align=\"center\">   NLO$^2$   </th> <th align=\"center\">    AV18$^3$   </th> </tr>\n</thead>\n<tbody>\n<tr><td align=\"center\">                                   </td> <td align=\"center\">                      </td> <td align=\"center\">                    </td> <td align=\"center\">                    </td> <td align=\"center\">                      </td> </tr>\n<tr><td align=\"center\">   0-100                           </td> <td align=\"center\">   1.05               </td> <td align=\"center\">   1.7              </td> <td align=\"center\">   4.5              </td> <td align=\"center\">   0.95               </td> </tr>\n<tr><td align=\"center\">   100-190                         </td> <td align=\"center\">   1.08               </td> <td align=\"center\">   22               </td> <td align=\"center\">   100              </td> <td align=\"center\">   1.10               </td> </tr>\n<tr><td align=\"center\">   190-290                         </td> <td align=\"center\">   1.15               </td> <td align=\"center\">   47               </td> <td align=\"center\">   180              </td> <td align=\"center\">   1.11               </td> </tr>\n<tr><td align=\"center\">   $\\mathbf{0-290}$                </td> <td align=\"center\">   $\\mathbf{1.10}$    </td> <td align=\"center\">   $\\mathbf{20}$    </td> <td align=\"center\">   $\\mathbf{86}$    </td> <td align=\"center\">   $\\mathbf{1.04}$    </td> </tr>\n</tbody>\n</table>\n* R. Machleidt et al., Phys. Rev. C68, 041001(R) (2003)\n\n* E. Epelbaum et al., Eur. Phys. J. A19, 401 (2004)\n\n* R. B. Wiringa et al., Phys. Rev. C5, 38 (1995)\n\nAn example: chiral twobody interactions\n\n$$\n\\mathcal{L_{\\mathrm{eff}}} = \\mathcal{L}_{\\pi \\pi}(f_\\pi,m_{\\pi}) + \\mathcal{L}_{\\pi N}(f_{\\pi},M_{N},g_A,c_i,d_i,...) + \\mathcal{L}_{NN}(C_{i},\\tilde{C}_{i},D_{i},...) + \\ldots\n$$\n\n* R. Machleidt, D. R. Entem, Phys. Rep. 503, 1 (2011)\n\n* E. Epelbaum, H.-W. Hammer, Ulf-G. Mei\\ss{}ner, Rev. Mod. Phys. 81, 1773 (2009)\n\nProton-neutron $^1S_0$ phase shift\nNote that the Nijm93 PWA phase shift becomes negative at T$_{\\mathrm{lab}}> 250$MeV. This indicates that the nucleon-nucleon potential is repulsive at short distances \n\n<p>Proton-neutron $^1S_0$ phase shift.</p>\n\n\n\n\n Differential cross section\n\n<p>Proton-neutron $^1S_0$ phase shift.</p>\n\n\n\n\n\n\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 22: Find all possible two-body quantum numbers\n\nList all **allowed** according to the Pauli principle partial waves with isospin $T$, their \nprojection $T_z$, spin $S$, orbital angular momentum $l$ and total spin $J$ for $J\\le 3$.\nUse the standard spectroscopic notation $^{2S+1}L_J$ to label different partial waves. A proton-proton state\nhas $T_Z=-1$, a proton-neutron state has $T_z=0$ and a neutron-neutron state has $T_z=1$.\n\n<!-- --- end exercise --- -->\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 23: Expressions for the various operators\n\n\n**a)**\nFind the closed form expression for the spin-orbit force. Show that the spin-orbit force {\\bf LS} gives a zero\ncontribution for $S$-waves (orbital angular momentum $l=0$).   What is the value of the spin-orbit force for spin-singlet states ($S=0$)?\n\n**b)**\nFind thereafter the expectation value of $\\mathbf{\\sigma}_1\\cdot\\mathbf{\\sigma}_2$, where $\\mathbf{\\sigma}_i$ are so-called Pauli matrices. \n1. Add thereafter isospin and find the expectation value of $\\mathbf{\\sigma}_1\\cdot\\mathbf{\\sigma}_2\\mathbf{\\tau}_1\\cdot\\mathbf{\\tau}_2$, where $\\mathbf{\\tau}_i$ are also so-called Pauli matrices. List all the cases with $S=0,1$ and $T=0,1$.\n\n<!-- --- end exercise --- -->\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 24: One-pion exchange\n\nA simple parametrization of the nucleon-nucleon force is given by what is called the $V_8$ potential model,\nwhere we have kept eight different operators. These operators contain a central force, a spin-orbit force,\na spin-spin force and a tensor force. Several features of the nuclei can be explained in terms of these four components. Without the Pauli matrices for isospin the final form of such an interaction model results in the following form:\n\n7\n0\n8\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\left. + C_{SL} \\left( {1\\over m_\\alpha r} + {1\\over \\left( m_\\alpha r\\right)^2}\n\\right) \\mathbf{L}\\cdot \\mathbf{S}\n\\right\\} \\frac{e^{-m_\\alpha r}}{m_\\alpha r}\n$$\n\nwhere $m_{\\alpha}$ is the mass of the relevant meson and\n$S_{12}$ is the familiar tensor term. The various coefficients $C_i$ are normally fitted so that the potential reproduces experimental scattering cross sections. By adding terms which include the isospin Pauli matrices \nresults in an interaction model with eight operators.\n\nThe expectaction value of the tensor operator is non-zero only for $S=1$. We will show this in a forthcoming lecture, after that we have derived the Wigner-Eckart theorem. \nHere it suffices to know that the expectaction value of the tensor force for different partial values is  (with $l$ the orbital angular momentum and ${\\cal J}$ the total angular momentum in the relative and center-of-mass frame of motion)\n\n7\n1\n0\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n7\n1\n1\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n7\n1\n2\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n7\n1\n3\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\langle l {\\cal J}S=1| S_{12} | l' {\\cal J}S=1\\rangle = 2 \\hspace{0.5cm} l= {\\cal J} \\hspace{0.1cm}\\mathrm{and} \\hspace{0.1cm} l'={\\cal J},\n$$\n\nand zero else.   \n\nIn this exercise we will focus only on the one-pion exchange term of the nuclear force, namely\n\n$$\nV_{\\pi}(\\mathbf{r})= -\\frac{f_{\\pi}^{2}}{4\\pi m_{\\pi}^{2}}\\mathbf{ \\tau}_1\\cdot\\mathbf{\\tau}_2\n\\frac{1}{3}\\left\\{\\mathbf{ \\sigma}_1\\cdot\\mathbf{ \\sigma}_2+\\left( 1 + {3\\over m_\\pi r} + {3\\over\\left(m_\\pi r\\right)^2}\\right) S_{12} (\\hat r)\\right\\} \\frac{e^{-m_\\pi r}}{m_\\pi r}.\n$$\n\nHere the constant $f_{\\pi}^{2}/4\\pi\\approx 0.08$ and the mass of the pion is $m_\\pi\\approx 140$ MeV/c${}^{2}$.\n\n\n**a)**\nCompute the expectation value of the tensor force and the spin-spin  and isospin operators for the one-pion exchange potential for all partial waves you found in exercise 9. Comment your results. How does the one-pion exchange part behave as function of different $l$, ${\\cal J}$ and $S$ values? Do you see some patterns?\n\n**b)**\nFor the binding energy of the deuteron, with the ground state defined by the quantum numbers $l=0$, $S=1$ and ${\\cal J}=1$, the tensor force plays an important role due to the admixture from the $l=2$ state. Use the expectation values of the different operators of the one-pion exchange potential and plot the ratio of the tensor force component over the spin-spin component of the one-pion exchange part as function of $x=m_\\pi r$ for the $l=2$ state (that is the case $l,l'={\\cal J}+1$). Comment your results.\n\n\n\n\n\n<!-- --- end exercise --- -->\n\n\n# Configuration interaction theory\n<div id=\"ch:fci\"></div>\n\n## Introduction\n\nThe simplest possible choice for many-body wavefunctions are **product** wavefunctions.\nThat is\n\n$$\n\\Psi(x_1, x_2, x_3, \\ldots, x_A) \\approx \\phi_1(x_1) \\phi_2(x_2) \\phi_3(x_3) \\ldots\n$$\n\nbecause we are really only good  at thinking about one particle at a time. Such \nproduct wavefunctions, without correlations, are easy to \nwork with; for example, if the single-particle states $\\phi_i(x)$ are orthonormal, then \nthe product wavefunctions are easy to orthonormalize.   \n\nSimilarly, computing matrix elements of operators are relatively easy, because the \nintegrals factorize.\n\n\nThe price we pay is the lack of correlations, which we must build up by using many, many product \nwavefunctions. (Thus we have a trade-off: compact representation of correlations but \ndifficult integrals versus easy integrals but many states required.) \n\n\nBecause we have fermions, we are required to have antisymmetric wavefunctions, e.g.\n\n$$\n\\Psi(x_1, x_2, x_3, \\ldots, x_A) = - \\Psi(x_2, x_1, x_3, \\ldots, x_A)\n$$\n\netc. This is accomplished formally by using the determinantal formalism\n\n$$\n\\Psi(x_1, x_2, \\ldots, x_A) \n= \\frac{1}{\\sqrt{A!}} \n\\det \\left | \n\\begin{array}{cccc}\n\\phi_1(x_1) & \\phi_1(x_2) & \\ldots & \\phi_1(x_A) \\\\\n\\phi_2(x_1) & \\phi_2(x_2) & \\ldots & \\phi_2(x_A) \\\\\n \\vdots & & &  \\\\\n\\phi_A(x_1) & \\phi_A(x_2) & \\ldots & \\phi_A(x_A) \n\\end{array}\n\\right |\n$$\n\nProduct wavefunction + antisymmetry = Slater determinant.\n\n$$\n\\Psi(x_1, x_2, \\ldots, x_A) \n= \\frac{1}{\\sqrt{N!}} \n\\det \\left | \n\\begin{array}{cccc}\n\\phi_1(x_1) & \\phi_1(x_2) & \\ldots & \\phi_1(x_A) \\\\\n\\phi_2(x_1) & \\phi_2(x_2) & \\ldots & \\phi_2(x_A) \\\\\n \\vdots & & &  \\\\\n\\phi_A(x_1) & \\phi_A(x_2) & \\ldots & \\phi_A(x_A) \n\\end{array}\n\\right |\n$$\n\nProperties of the determinant (interchange of any two rows or \nany two columns yields a change in sign; thus no two rows and no \ntwo columns can be the same) lead to the Pauli principle:\n\n* No two particles can be at the same place (two columns the same); and\n\n* No two particles can be in the same state (two rows the same).\n\nAs a practical matter, however, Slater determinants beyond $N=4$ quickly become \nunwieldy. Thus we turn to the **occupation representation** or **second quantization** to simplify calculations. \n\nThe occupation representation, using fermion **creation** and **annihilation** \noperators, is compact and efficient. It is also abstract and, at first encounter, not easy to \ninternalize. It is inspired by other operator formalism, such as the ladder operators for \nthe harmonic oscillator or for angular momentum, but unlike those cases, the operators **do not have coordinate space representations**.\n\nInstead, one can think of fermion creation/annihilation operators as a game of symbols that \ncompactly reproduces what one would do, albeit clumsily, with full coordinate-space Slater \ndeterminants. \n\n\nWe start with a set of orthonormal single-particle states $\\{ \\phi_i(x) \\}$. \n(Note: this requirement, and others, can be relaxed, but leads to a \nmore involved formalism.) **Any** orthonormal set will do. \n\nTo each single-particle state $\\phi_i(x)$ we associate a creation operator \n$\\hat{a}^\\dagger_i$ and an annihilation operator $\\hat{a}_i$. \n\nWhen acting on the vacuum state $| 0 \\rangle$, the creation operator $\\hat{a}^\\dagger_i$ causes \na particle to occupy the single-particle state $\\phi_i(x)$:\n\n$$\n\\phi_i(x) \\rightarrow \\hat{a}^\\dagger_i |0 \\rangle\n$$\n\nBut with multiple creation operators we can occupy multiple states:\n\n$$\n\\phi_i(x) \\phi_j(x^\\prime) \\phi_k(x^{\\prime \\prime}) \n\\rightarrow \\hat{a}^\\dagger_i \\hat{a}^\\dagger_j \\hat{a}^\\dagger_k |0 \\rangle.\n$$\n\nNow we impose antisymmetry, by having the fermion operators satisfy  **anticommutation relations**:\n\n$$\n\\hat{a}^\\dagger_i \\hat{a}^\\dagger_j + \\hat{a}^\\dagger_j \\hat{a}^\\dagger_i\n= [ \\hat{a}^\\dagger_i ,\\hat{a}^\\dagger_j ]_+ \n= \\{ \\hat{a}^\\dagger_i ,\\hat{a}^\\dagger_j \\} = 0\n$$\n\nso that\n\n$$\n\\hat{a}^\\dagger_i \\hat{a}^\\dagger_j = - \\hat{a}^\\dagger_j \\hat{a}^\\dagger_i\n$$\n\nBecause of this property, automatically $\\hat{a}^\\dagger_i \\hat{a}^\\dagger_i = 0$, \nenforcing the Pauli exclusion principle.  Thus when writing a Slater determinant \nusing creation operators,\n\n$$\n\\hat{a}^\\dagger_i \\hat{a}^\\dagger_j \\hat{a}^\\dagger_k \\ldots |0 \\rangle\n$$\n\neach index $i,j,k, \\ldots$ must be unique.\n\n\n\n\n## Full Configuration Interaction Theory\n\nWe have defined the ansatz for the ground state as\n\n$$\n|\\Phi_0\\rangle = \\left(\\prod_{i\\le F}\\hat{a}_{i}^{\\dagger}\\right)|0\\rangle,\n$$\n\nwhere the index $i$ defines different single-particle states up to the Fermi level. We have assumed that we have $N$ fermions. \nA given one-particle-one-hole ($1p1h$) state can be written as\n\n$$\n|\\Phi_i^a\\rangle = \\hat{a}_{a}^{\\dagger}\\hat{a}_i|\\Phi_0\\rangle,\n$$\n\nwhile a $2p2h$ state can be written as\n\n$$\n|\\Phi_{ij}^{ab}\\rangle = \\hat{a}_{a}^{\\dagger}\\hat{a}_{b}^{\\dagger}\\hat{a}_j\\hat{a}_i|\\Phi_0\\rangle,\n$$\n\nand a general $NpNh$ state as\n\n$$\n|\\Phi_{ijk\\dots}^{abc\\dots}\\rangle = \\hat{a}_{a}^{\\dagger}\\hat{a}_{b}^{\\dagger}\\hat{a}_{c}^{\\dagger}\\dots\\hat{a}_k\\hat{a}_j\\hat{a}_i|\\Phi_0\\rangle.\n$$\n\nWe can then expand our exact state function for the ground state \nas\n\n$$\n|\\Psi_0\\rangle=C_0|\\Phi_0\\rangle+\\sum_{ai}C_i^a|\\Phi_i^a\\rangle+\\sum_{abij}C_{ij}^{ab}|\\Phi_{ij}^{ab}\\rangle+\\dots\n=(C_0+\\hat{C})|\\Phi_0\\rangle,\n$$\n\nwhere we have introduced the so-called correlation operator\n\n$$\n\\hat{C}=\\sum_{ai}C_i^a\\hat{a}_{a}^{\\dagger}\\hat{a}_i  +\\sum_{abij}C_{ij}^{ab}\\hat{a}_{a}^{\\dagger}\\hat{a}_{b}^{\\dagger}\\hat{a}_j\\hat{a}_i+\\dots\n$$\n\nSince the normalization of $\\Psi_0$ is at our disposal and since $C_0$ is by hypothesis non-zero, we may arbitrarily set $C_0=1$ with \ncorresponding proportional changes in all other coefficients. Using this so-called intermediate normalization we have\n\n$$\n\\langle \\Psi_0 | \\Phi_0 \\rangle = \\langle \\Phi_0 | \\Phi_0 \\rangle = 1,\n$$\n\nresulting in\n\n$$\n|\\Psi_0\\rangle=(1+\\hat{C})|\\Phi_0\\rangle.\n$$\n\nWe rewrite\n\n$$\n|\\Psi_0\\rangle=C_0|\\Phi_0\\rangle+\\sum_{ai}C_i^a|\\Phi_i^a\\rangle+\\sum_{abij}C_{ij}^{ab}|\\Phi_{ij}^{ab}\\rangle+\\dots,\n$$\n\nin a more compact form as\n\n$$\n|\\Psi_0\\rangle=\\sum_{PH}C_H^P\\Phi_H^P=\\left(\\sum_{PH}C_H^P\\hat{A}_H^P\\right)|\\Phi_0\\rangle,\n$$\n\nwhere $H$ stands for $0,1,\\dots,n$ hole states and $P$ for $0,1,\\dots,n$ particle states. \nOur requirement of unit normalization gives\n\n$$\n\\langle \\Psi_0 | \\Phi_0 \\rangle = \\sum_{PH}|C_H^P|^2= 1,\n$$\n\nand the energy can be written as\n\n$$\nE= \\langle \\Psi_0 | \\hat{H} |\\Phi_0 \\rangle= \\sum_{PP'HH'}C_H^{*P}\\langle \\Phi_H^P | \\hat{H} |\\Phi_{H'}^{P'} \\rangle C_{H'}^{P'}.\n$$\n\n### Full Configuration Interaction Theory\n\nNormally\n\n$$\nE= \\langle \\Psi_0 | \\hat{H} |\\Phi_0 \\rangle= \\sum_{PP'HH'}C_H^{*P}\\langle \\Phi_H^P | \\hat{H} |\\Phi_{H'}^{P'} \\rangle C_{H'}^{P'},\n$$\n\nis solved by diagonalization setting up the Hamiltonian matrix defined by the basis of all possible Slater determinants. A diagonalization\n<!-- to do: add text about Rayleigh-Ritz -->\nis equivalent to finding the variational minimum   of\n\n$$\n\\langle \\Psi_0 | \\hat{H} |\\Phi_0 \\rangle-\\lambda \\langle \\Psi_0 |\\Phi_0 \\rangle,\n$$\n\nwhere $\\lambda$ is a variational multiplier to be identified with the energy of the system.\nThe minimization process results in\n\n7\n3\n9\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\sum_{P'H'}\\left\\{\\delta[C_H^{*P}]\\langle \\Phi_H^P | \\hat{H} |\\Phi_{H'}^{P'} \\rangle C_{H'}^{P'}+\nC_H^{*P}\\langle \\Phi_H^P | \\hat{H} |\\Phi_{H'}^{P'} \\rangle \\delta[C_{H'}^{P'}]-\n\\lambda( \\delta[C_H^{*P}]C_{H'}^{P'}+C_H^{*P}\\delta[C_{H'}^{P'}]\\right\\} = 0.\n$$\n\nSince the coefficients $\\delta[C_H^{*P}]$ and $\\delta[C_{H'}^{P'}]$ are complex conjugates it is necessary and sufficient to require the quantities that multiply with $\\delta[C_H^{*P}]$ to vanish.  \n\nThis leads to\n\n$$\n\\sum_{P'H'}\\langle \\Phi_H^P | \\hat{H} |\\Phi_{H'}^{P'} \\rangle C_{H'}^{P'}-\\lambda C_H^{P}=0,\n$$\n\nfor all sets of $P$ and $H$.\n\nIf we then multiply by the corresponding $C_H^{*P}$ and sum over $PH$ we obtain\n\n$$\n\\sum_{PP'HH'}C_H^{*P}\\langle \\Phi_H^P | \\hat{H} |\\Phi_{H'}^{P'} \\rangle C_{H'}^{P'}-\\lambda\\sum_{PH}|C_H^P|^2=0,\n$$\n\nleading to the identification $\\lambda = E$. This means that we have for all $PH$ sets\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:fullci\"></div>\n\n$$\n\\begin{equation}\n\\sum_{P'H'}\\langle \\Phi_H^P | \\hat{H} -E|\\Phi_{H'}^{P'} \\rangle = 0. \\label{eq:fullci} \\tag{130}\n\\end{equation}\n$$\n\nAn alternative way to derive the last equation is to start from\n\n$$\n(\\hat{H} -E)|\\Psi_0\\rangle = (\\hat{H} -E)\\sum_{P'H'}C_{H'}^{P'}|\\Phi_{H'}^{P'} \\rangle=0,\n$$\n\nand if this equation is successively projected against all $\\Phi_H^P$ in the expansion of $\\Psi$, then the last equation on the previous slide\nresults.   As stated previously, one solves this equation normally by diagonalization. If we are able to solve this equation exactly (that is\nnumerically exactly) in a large Hilbert space (it will be truncated in terms of the number of single-particle states included in the definition\nof Slater determinants), it can then serve as a benchmark for other many-body methods which approximate the correlation operator\n$\\hat{C}$.  \n\n\nFor reasons to come (links with Coupled-Cluster theory and Many-Body perturbation theory), \nwe will rewrite Eq. ( ref{eq:fullci}) as a set of coupled non-linear equations in terms of the unknown coefficients $C_H^P$. \n\nTo see this, we look at the contributions arising from\n\n$$\n\\langle \\Phi_H^P | = \\langle \\Phi_0|\n$$\n\nin  Eq. [(130)](#eq:fullci), that is we multiply with $\\langle \\Phi_0 |$\nfrom the left in\n\n$$\n(\\hat{H} -E)\\sum_{P'H'}C_{H'}^{P'}|\\Phi_{H'}^{P'} \\rangle=0.\n$$\n\nIf we assume that we have a two-body operator at most, Slater's rule gives then an equation for the \ncorrelation energy in terms of $C_i^a$ and $C_{ij}^{ab}$ only.  We get then\n\n$$\n\\langle \\Phi_0 | \\hat{H} -E| \\Phi_0\\rangle + \\sum_{ai}\\langle \\Phi_0 | \\hat{H} -E|\\Phi_{i}^{a} \\rangle C_{i}^{a}+\n\\sum_{abij}\\langle \\Phi_0 | \\hat{H} -E|\\Phi_{ij}^{ab} \\rangle C_{ij}^{ab}=0,\n$$\n\nor\n\n$$\nE-E_0 =\\Delta E=\\sum_{ai}\\langle \\Phi_0 | \\hat{H}|\\Phi_{i}^{a} \\rangle C_{i}^{a}+\n\\sum_{abij}\\langle \\Phi_0 | \\hat{H}|\\Phi_{ij}^{ab} \\rangle C_{ij}^{ab},\n$$\n\nwhere the energy $E_0$ is the reference energy and $\\Delta E$ defines the so-called correlation energy.\nThe single-particle basis functions  could be the results of a Hartree-Fock calculation or just the eigenstates of the non-interacting part of the Hamiltonian. \n\nIn our chapter on Hartree-Fock calculations, \nwe have already computed the matrix $\\langle \\Phi_0 | \\hat{H}|\\Phi_{i}^{a}\\rangle $ and $\\langle \\Phi_0 | \\hat{H}|\\Phi_{ij}^{ab}\\rangle$.  If we are using a Hartree-Fock basis, then the matrix elements\n$\\langle \\Phi_0 | \\hat{H}|\\Phi_{i}^{a}\\rangle $ and we are left with a correlation energy given by\n\n$$\nE-E_0 =\\Delta E^{HF}=\\sum_{abij}\\langle \\Phi_0 | \\hat{H}|\\Phi_{ij}^{ab} \\rangle C_{ij}^{ab}.\n$$\n\nInserting the various matrix elements we can rewrite the previous equation as\n\n$$\n\\Delta E=\\sum_{ai}\\langle i| \\hat{f}|a \\rangle C_{i}^{a}+\n\\sum_{abij}\\langle ij | \\hat{v}| ab \\rangle C_{ij}^{ab}.\n$$\n\nThis equation determines the correlation energy but not the coefficients $C$. \nWe need more equations. Our next step is to set up\n\n$$\n\\langle \\Phi_i^a | \\hat{H} -E| \\Phi_0\\rangle + \\sum_{bj}\\langle \\Phi_i^a | \\hat{H} -E|\\Phi_{j}^{b} \\rangle C_{j}^{b}+\n\\sum_{bcjk}\\langle \\Phi_i^a | \\hat{H} -E|\\Phi_{jk}^{bc} \\rangle C_{jk}^{bc}+\n\\sum_{bcdjkl}\\langle \\Phi_i^a | \\hat{H} -E|\\Phi_{jkl}^{bcd} \\rangle C_{jkl}^{bcd}=0,\n$$\n\nas this equation will allow us to find an expression for the coefficents $C_i^a$ since we can rewrite this equation as\n\n$$\n\\langle i | \\hat{f}| a\\rangle +\\langle \\Phi_i^a | \\hat{H}|\\Phi_{i}^{a} \\rangle C_{i}^{a}+ \\sum_{bj\\ne ai}\\langle \\Phi_i^a | \\hat{H}|\\Phi_{j}^{b} \\rangle C_{j}^{b}+\n\\sum_{bcjk}\\langle \\Phi_i^a | \\hat{H}|\\Phi_{jk}^{bc} \\rangle C_{jk}^{bc}+\n\\sum_{bcdjkl}\\langle \\Phi_i^a | \\hat{H}|\\Phi_{jkl}^{bcd} \\rangle C_{jkl}^{bcd}=0.\n$$\n\nWe rewrite this equation as\n\n7\n5\n3\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\times\\left(\\langle i | \\hat{f}| a\\rangle+ \\sum_{bj\\ne ai}\\langle \\Phi_i^a | \\hat{H}|\\Phi_{j}^{b} \\rangle C_{j}^{b}+\\sum_{bcjk}\\langle \\Phi_i^a | \\hat{H}|\\Phi_{jk}^{bc} \\rangle C_{jk}^{bc}+\n\\sum_{bcdjkl}\\langle \\Phi_i^a | \\hat{H}|\\Phi_{jkl}^{bcd} \\rangle C_{jkl}^{bcd}\\right).\n$$\n\nSince these equations are solved iteratively ( that is we can start with a guess for the coefficients $C_i^a$), it is common to start the  iteration \nby setting\n\n$$\nC_{i}^{a}=-\\frac{\\langle i | \\hat{f}| a\\rangle}{\\langle \\Phi_i^a | \\hat{H}|\\Phi_{i}^{a}\\rangle},\n$$\n\nand the denominator can be written as\n\n$$\nC_{i}^{a}=\\frac{\\langle i | \\hat{f}| a\\rangle}{\\langle i | \\hat{f}| i\\rangle-\\langle a | \\hat{f}| a\\rangle+\\langle ai | \\hat{v}| ai\\rangle}.\n$$\n\nThe observant reader will however see that we need an equation for $C_{jk}^{bc}$ and $C_{jkl}^{bcd}$ as well.\nTo find equations for these coefficients we need then to continue our multiplications from the left with the various\n$\\Phi_{H}^P$ terms. \n\n\n\nFor $C_{jk}^{bc}$ we need then\n\n7\n5\n7\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\sum_{cdkl}\\langle \\Phi_{ij}^{ab} | \\hat{H} -E|\\Phi_{kl}^{cd} \\rangle C_{kl}^{cd}+\\sum_{cdeklm}\\langle \\Phi_{ij}^{ab} | \\hat{H} -E|\\Phi_{klm}^{cde} \\rangle C_{klm}^{cde}+\\sum_{cdefklmn}\\langle \\Phi_{ij}^{ab} | \\hat{H} -E|\\Phi_{klmn}^{cdef} \\rangle C_{klmn}^{cdef}=0,\n$$\n\nand we can isolate the coefficients $C_{kl}^{cd}$ in a similar way as we did for the coefficients $C_{i}^{a}$. \nAt the end we can rewrite our solution of the Schr\\\"odinger equation in terms of $n$ coupled equations for the coefficients $C_H^P$.\nThis is a very cumbersome way of solving the equation. However, by using this iterative scheme we can illustrate how we can compute the\nvarious terms in the wave operator or correlation operator $\\hat{C}$. We will later identify the calculation of the various terms $C_H^P$\nas parts of different many-body approximations to full CI. In particular, ww can  relate this non-linear scheme with Coupled Cluster theory and\nmany-body perturbation theory. These theories will not be discussed in this course.\n\n\nIf we use a Hartree-Fock basis, we simplify this equation\n\n$$\n\\Delta E=\\sum_{ai}\\langle i| \\hat{f}|a \\rangle C_{i}^{a}+\n\\sum_{abij}\\langle ij | \\hat{v}| ab \\rangle C_{ij}^{ab}.\n$$\n\nWhat about\n\n$$\n\\langle \\Phi_i^a | \\hat{H} -E| \\Phi_0\\rangle + \\sum_{bj}\\langle \\Phi_i^a | \\hat{H} -E|\\Phi_{j}^{b} \\rangle C_{j}^{b}+\n\\sum_{bcjk}\\langle \\Phi_i^a | \\hat{H} -E|\\Phi_{jk}^{bc} \\rangle C_{jk}^{bc}+\n\\sum_{bcdjkl}\\langle \\Phi_i^a | \\hat{H} -E|\\Phi_{jkl}^{bcd} \\rangle C_{jkl}^{bcd}=0,\n$$\n\nand\n\n7\n6\n1\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\sum_{cdeklm}\\langle \\Phi_{ij}^{ab} | \\hat{H} -E|\\Phi_{klm}^{cde} \\rangle C_{klm}^{cde}+\\sum_{cdefklmn}\\langle \\Phi_{ij}^{ab} | \\hat{H} -E|\\Phi_{klmn}^{cdef} \\rangle C_{klmn}^{cdef}=0?\n$$\n\n## Building a many-body basis\n\n\nIn project 1 the plan  is to construct a working code that constructs the \nmany-body Hamiltonian matrix in a basis of Slater determinants and to find the low-lying eigenenergies. \nThis is referred to as the configuration-interaction method or shell-model diagonalization \n(or the interacting shell model). \n\nThe first step in such codes--and in your project--is to construct the many-body basis.  \n\nWhile the formalism is independent of the choice of basis, the **effectiveness** of a calculation \nwill certainly be basis dependent. \n\nFurthermore there are common conventions useful to know.\n\n\nFirst, the single-particle basis has angular momentum as a good quantum number.  You can \nimagine the single-particle wavefunctions being generated by a one-body Hamiltonian, \nfor example a harmonic oscillator.  Modifications include harmonic oscillator plus \nspin-orbit splitting, or self-consistent mean-field potentials, or the Woods-Saxon potential which mocks \nup the self-consistent mean-field. \n\n\nFor nuclei, the harmonic oscillator, modified by spin-orbit splitting, provides a useful language \nfor describing single-particle states.\n\n\nEach single-particle state is labeled by the following quantum numbers: \n\n* Orbital angular momentum $l$\n\n* Intrinsic spin $s$ = 1/2 for protons and neutrons\n\n* Angular momentum $j = l \\pm 1/2$\n\n* $z$-component $j_z$ (or $m$)\n\n* Some labeling of the radial wavefunction, typically $n$ the number of nodes in  the radial wavefunction, but in the case of harmonic oscillator one can also use the principal quantum number $N$, where the harmonic oscillator energy is $(N+3/2)\\hbar \\omega$. \n\nIn this format one labels states by $n(l)_j$, with $(l)$ replaced by a letter:\n$s$ for $l=0$, $p$ for $l=1$, $d$ for $l=2$, $f$ for $l=3$, and thenceforth alphabetical.\n\n\n In practice the single-particle space has to be severely truncated.  This truncation is \ntypically based upon the single-particle energies, which is the effective energy \nfrom a mean-field potential. \n\nSometimes we freeze the core and only consider a valence space. For example, one \nmay assume a frozen ${}^{4}\\mbox{He}$ core, with two protons and two neutrons in the $0s_{1/2}$ \nshell, and then only allow active particles in the $0p_{1/2}$ and $0p_{3/2}$ orbits. \n\n\nAnother example is a frozen ${}^{16}\\mbox{O}$ core, with eight protons and eight neutrons filling the \n$0s_{1/2}$,  $0p_{1/2}$ and $0p_{3/2}$ orbits, with valence particles in the \n$0d_{5/2}, 1s_{1/2}$ and $0d_{3/2}$ orbits.\n\n\nSometimes we refer to nuclei by the valence space where their last nucleons go.  \nSo, for example, we call ${}^{12}\\mbox{C}$ a $p$-shell nucleus, while ${}^{26}\\mbox{Al}$ is an \n$sd$-shell nucleus and ${}^{56}\\mbox{Fe}$ is a $pf$-shell nucleus.\n\n\n\nThere are different kinds of truncations.\n\n* For example, one can start with `filled' orbits (almost always the lowest), and then  allow one, two, three... particles excited out of those filled orbits. These are called  1p-1h, 2p-2h, 3p-3h excitations. \n\n* Alternately, one can state a maximal orbit and allow all possible configurations with  particles occupying states up to that maximum. This is called *full configuration*.\n\n* Finally, for particular use in nuclear physics, there is the *energy* truncation, also  called the $N\\hbar\\Omega$ or $N_{max}$ truncation. \n\n Here one works in a harmonic oscillator basis, with each major oscillator shell assigned \na principal quantum number $N=0,1,2,3,...$. \n\nThe $N\\hbar\\Omega$ or $N_{max}$ truncation: Any configuration is given an noninteracting energy, which is the sum \nof the single-particle harmonic oscillator energies. (Thus this ignores \nspin-orbit splitting.)\n\n\n\n\nExcited state are labeled relative to the lowest configuration by the \nnumber of harmonic oscillator quanta.\n\nThis truncation is useful because: if one includes *all* configuration up to \nsome $N_{max}$, and has a translationally invariant interaction, then the intrinsic \nmotion and the center-of-mass motion factor. In other words, we can know exactly \nthe center-of-mass wavefunction. \n\n\n\n\n\nIn almost all cases, the many-body Hamiltonian is rotationally invariant. This means \nit commutes with the operators $\\hat{J}^2, \\hat{J}_z$ and so eigenstates will have \ngood $J,M$. Furthermore, the eigenenergies do not depend upon the orientation $M$. \n\n\nTherefore we can choose to construct a many-body basis which has fixed $M$; this is \ncalled an $M$-scheme basis. \n\n\nAlternately, one can construct a many-body basis which has fixed $J$, or a $J$-scheme \nbasis. \n\nThe Hamiltonian matrix will have smaller dimensions (a factor of 10 or more)\n in the $J$-scheme than in the $M$-scheme. \nOn the other hand, as we'll show in the next slide, the $M$-scheme is very easy to \nconstruct with Slater determinants, while the $J$-scheme basis states, and thus the \nmatrix elements, are more complicated, almost always being linear combinations of \n$M$-scheme states. $J$-scheme bases are important and useful, but we'll focus on the \nsimpler $M$-scheme.\n\n\n\nThe quantum number $m$ is additive (because the underlying group is Abelian): \nif a Slater determinant $\\hat{a}_i^\\dagger \\hat{a}^\\dagger_j \\hat{a}^\\dagger_k \\ldots | 0 \\rangle$ \nis built from single-particle states all with good $m$, then the total\n\n$$\nM = m_i + m_j + m_k + \\ldots\n$$\n\nThis is *not* true of $J$, because the angular momentum group SU(2) is not Abelian.\n\nThe upshot is that \n* It is easy to construct a Slater determinant with good total $M$;\n\n* It is trivial to calculate $M$ for each Slater determinant;\n\n* So it is easy to construct an $M$-scheme basis with fixed total $M$.\n\nNote that the individual $M$-scheme basis states will *not*, in general, \nhave good total $J$. \nBecause the Hamiltonian is rotationally invariant, however, the eigenstates will \nhave good $J$. (The situation is muddied when one has states of different $J$ that are \nnonetheless degenerate.) \n\n\nExample: two $j=1/2$ orbits\n\n<table border=\"1\">\n<thead>\n<tr><th align=\"center\">Index</th> <th align=\"center\">$n$</th> <th align=\"center\">$l$</th> <th align=\"center\">$j$</th> <th align=\"center\">$m_j$</th> </tr>\n</thead>\n<tbody>\n<tr><td align=\"center\">   1        </td> <td align=\"center\">   0      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   -1/2     </td> </tr>\n<tr><td align=\"center\">   2        </td> <td align=\"center\">   0      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   1/2      </td> </tr>\n<tr><td align=\"center\">   3        </td> <td align=\"center\">   1      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   -1/2     </td> </tr>\n<tr><td align=\"center\">   4        </td> <td align=\"center\">   1      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   1/2      </td> </tr>\n</tbody>\n</table>\nNote: the order is arbitrary.\nThere are $\\left ( \\begin{array}{c} 4 \\\\ 2 \\end{array} \\right) = 6$ two-particle states, \nwhich we list with the total $M$:\n\n<table border=\"1\">\n<thead>\n<tr><th align=\"center\">Occupied</th> <th align=\"center\">$M$</th> </tr>\n</thead>\n<tbody>\n<tr><td align=\"center\">   1,2         </td> <td align=\"center\">   0      </td> </tr>\n<tr><td align=\"center\">   1,3         </td> <td align=\"center\">   -1     </td> </tr>\n<tr><td align=\"center\">   1,4         </td> <td align=\"center\">   0      </td> </tr>\n<tr><td align=\"center\">   2,3         </td> <td align=\"center\">   0      </td> </tr>\n<tr><td align=\"center\">   2,4         </td> <td align=\"center\">   1      </td> </tr>\n<tr><td align=\"center\">   3,4         </td> <td align=\"center\">   0      </td> </tr>\n</tbody>\n</table>\nand 1 each with $M = \\pm 1$.\n\n\nExample: consider using only single particle states from the $0d_{5/2}$ space. \nThey have the following quantum numbers\n\n<table border=\"1\">\n<thead>\n<tr><th align=\"center\">Index</th> <th align=\"center\">$n$</th> <th align=\"center\">$l$</th> <th align=\"center\">$j$</th> <th align=\"center\">$m_j$</th> </tr>\n</thead>\n<tbody>\n<tr><td align=\"center\">   1        </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   5/2    </td> <td align=\"center\">   -5/2     </td> </tr>\n<tr><td align=\"center\">   2        </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   5/2    </td> <td align=\"center\">   -3/2     </td> </tr>\n<tr><td align=\"center\">   3        </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   5/2    </td> <td align=\"center\">   -1/2     </td> </tr>\n<tr><td align=\"center\">   4        </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   5/2    </td> <td align=\"center\">   1/2      </td> </tr>\n<tr><td align=\"center\">   5        </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   5/2    </td> <td align=\"center\">   3/2      </td> </tr>\n<tr><td align=\"center\">   6        </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   5/2    </td> <td align=\"center\">   5/2      </td> </tr>\n</tbody>\n</table>\nThere are $\\left ( \\begin{array}{c} 6 \\\\ 2 \\end{array} \\right) = 15$ two-particle states, \nwhich we list with the total $M$:\n\n<table border=\"1\">\n<thead>\n<tr><th align=\"center\">Occupied</th> <th align=\"center\">$M$</th> <th align=\"center\">Occupied</th> <th align=\"center\">$M$</th> <th align=\"center\">Occupied</th> <th align=\"center\">$M$</th> </tr>\n</thead>\n<tbody>\n<tr><td align=\"center\">   1,2         </td> <td align=\"center\">   -4     </td> <td align=\"center\">   2,3         </td> <td align=\"center\">   -2     </td> <td align=\"center\">   3,5         </td> <td align=\"center\">   1      </td> </tr>\n<tr><td align=\"center\">   1,3         </td> <td align=\"center\">   -3     </td> <td align=\"center\">   2,4         </td> <td align=\"center\">   -1     </td> <td align=\"center\">   3,6         </td> <td align=\"center\">   2      </td> </tr>\n<tr><td align=\"center\">   1,4         </td> <td align=\"center\">   -2     </td> <td align=\"center\">   2,5         </td> <td align=\"center\">   0      </td> <td align=\"center\">   4,5         </td> <td align=\"center\">   2      </td> </tr>\n<tr><td align=\"center\">   1,5         </td> <td align=\"center\">   -1     </td> <td align=\"center\">   2,6         </td> <td align=\"center\">   1      </td> <td align=\"center\">   4,6         </td> <td align=\"center\">   3      </td> </tr>\n<tr><td align=\"center\">   1,6         </td> <td align=\"center\">   0      </td> <td align=\"center\">   3,4         </td> <td align=\"center\">   0      </td> <td align=\"center\">   5,6         </td> <td align=\"center\">   4      </td> </tr>\n</tbody>\n</table>\n\n### Basic steps in a building an FCI code\n\nThe basic goal of the project is for you to build your own configuration-interaction  shell-model \ncode. The code will be fairly basic; it will assume that we have \na single species of particles, e.g. only neutrons, \nand you could, if you wish to,  read in uncoupled two-body matrix elements.  Furthermore the pieces of the code will not \nbe the most efficient.  Nonetheless it will be usable; most importantly, you will gain a good idea of what goes into a many-body shell-model code.\n\nThe first step  is to construct the $M$-scheme basis of Slater determinants.\nHere $M$-scheme means the total $J_z$ of the many-body states is fixed.\n\nThe steps could be:\n\n* Read in a user-supplied file of single-particle states (examples can be given) or just code these internally;\n\n* Ask for the total $M$ of the system and the number of particles $N$;\n\n* Construct all the $N$-particle states with given $M$.  You will validate the code by  comparing both the number of states and specific states.\n\nThe format of a possible input  file could be\n<table border=\"1\">\n<thead>\n<tr><th align=\"center\">Index</th> <th align=\"center\">$n$</th> <th align=\"center\">$l$</th> <th align=\"center\">$2j$</th> <th align=\"center\">$2m_j$</th> </tr>\n</thead>\n<tbody>\n<tr><td align=\"center\">   1        </td> <td align=\"center\">   1      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1       </td> <td align=\"center\">   -1        </td> </tr>\n<tr><td align=\"center\">   2        </td> <td align=\"center\">   1      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1       </td> <td align=\"center\">   1         </td> </tr>\n<tr><td align=\"center\">   3        </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   3       </td> <td align=\"center\">   -3        </td> </tr>\n<tr><td align=\"center\">   4        </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   3       </td> <td align=\"center\">   -1        </td> </tr>\n<tr><td align=\"center\">   5        </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   3       </td> <td align=\"center\">   1         </td> </tr>\n<tr><td align=\"center\">   6        </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   3       </td> <td align=\"center\">   3         </td> </tr>\n<tr><td align=\"center\">   7        </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   5       </td> <td align=\"center\">   -5        </td> </tr>\n<tr><td align=\"center\">   8        </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   5       </td> <td align=\"center\">   -3        </td> </tr>\n<tr><td align=\"center\">   9        </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   5       </td> <td align=\"center\">   -1        </td> </tr>\n<tr><td align=\"center\">   10       </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   5       </td> <td align=\"center\">   1         </td> </tr>\n<tr><td align=\"center\">   11       </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   5       </td> <td align=\"center\">   3         </td> </tr>\n<tr><td align=\"center\">   12       </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   5       </td> <td align=\"center\">   5         </td> </tr>\n</tbody>\n</table>\nThis represents the $1s_{1/2}0d_{3/2}0d_{5/2}$ valence space, or just the $sd$-space.  There are \ntwelve single-particle states, labeled by an overall index, and which have associated quantum \nnumbers the number of radial nodes, the orbital angular momentum $l$, and the \nangular momentum $j$ and third component $j_z$.  To keep everything as integers, we could store $2 \\times j$ and \n$2 \\times j_z$. \n\n\nTo read in the single-particle states you need to:\n* Open the file \n\n * Read the number of single-particle states (in the above example, 12);  allocate memory; all you need is a single array storing $2\\times j_z$ for each state, labeled by the index.\n\n\n* Read in the quantum numbers and store $2 \\times j_z$ (and anything else you happen to want).\n\nThe next step is to read in the number of particles $N$ and the fixed total $M$ (or, actually, $2 \\times M$). \nFor this project we assume only a single species of particles, say neutrons, although this can be \nrelaxed. **Note**: Although it is often a good idea to try to write a more general code, given the \nshort time alloted we would suggest you keep your ambition in check, at least in the initial phases of the \nproject.  \n\n\nYou should probably write an error trap to make sure $N$ and $M$ are congruent; if $N$ is even, then \n$2 \\times M$ should be even, and if $N$ is odd then $2\\times M$ should be odd. \n\n\nThe final step is to generate the set of $N$-particle Slater determinants with fixed $M$. \nThe Slater determinants will be stored in occupation representation.  Although in many codes\nthis representation is done compactly in bit notation with ones and zeros, but for \ngreater transparency and simplicity we will list the occupied single particle states.\n\n Hence we can \nstore the Slater determinant basis states as $sd(i,j)$, that is an \narray of dimension $N_{SD}$, the number of Slater determinants, by $N$, the number of occupied \nstate. So if for the 7th Slater determinant the 2nd, 3rd, and 9th single-particle states are occupied, \nthen $sd(7,1) = 2$, $sd(7,2) = 3$, and $sd(7,3) = 9$.\n\n\nWe can construct an occupation representation of Slater determinants by the *odometer*\nmethod.  Consider $N_{sp} = 12$ and $N=4$. \nStart with the first 4 states occupied, that is:\n\n* $sd(1,:)= 1,2,3,4$ (also written as $|1,2,3,4 \\rangle$)\n\nNow increase the last occupancy recursively:\n* $sd(2,:)= 1,2,3,5$\n\n* $sd(3,:)= 1,2,3,6$\n\n* $sd(4,:)= 1,2,3,7$\n\n* $\\ldots$\n\n* $sd(9,:)= 1,2,3,12$\n\nThen start over with \n* $sd(10,:)= 1,2,4,5$\n\nand again increase the rightmost digit\n\n* $sd(11,:)= 1,2,4,6$\n\n* $sd(12,:)= 1,2,4,7$\n\n* $\\ldots$\n\n* $sd(17,:)= 1,2,4,12$\n\nWhen we restrict ourselves to an $M$-scheme basis, we could choose two paths. \nThe first is simplest (and simplest is often best, at \nleast in the first draft of a code): generate all possible Slater determinants, \nand then extract from this initial list a list of those Slater determinants with a given \n$M$. (You will need to write a short function or routine that computes $M$ for any \ngiven occupation.)  \n\n\nAlternately, and not too difficult, is to run the odometer routine twice: each time, as \nas a Slater determinant is calculated, compute $M$, but do not store the Slater determinants \nexcept the current one. You can then count up the number of Slater determinants with a \nchosen $M$.  Then allocated storage for the Slater determinants, and run the odometer \nalgorithm again, this time storing Slater determinants with the desired $M$ (this can be \ndone with a simple logical flag). \n\n\n\n*Some example solutions*:  Let's begin with a simple case, the $0d_{5/2}$ space containing six single-particle states\n\n<table border=\"1\">\n<thead>\n<tr><th align=\"center\">Index</th> <th align=\"center\">$n$</th> <th align=\"center\">$l$</th> <th align=\"center\">$j$</th> <th align=\"center\">$m_j$</th> </tr>\n</thead>\n<tbody>\n<tr><td align=\"center\">   1        </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   5/2    </td> <td align=\"center\">   -5/2     </td> </tr>\n<tr><td align=\"center\">   2        </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   5/2    </td> <td align=\"center\">   -3/2     </td> </tr>\n<tr><td align=\"center\">   3        </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   5/2    </td> <td align=\"center\">   -1/2     </td> </tr>\n<tr><td align=\"center\">   4        </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   5/2    </td> <td align=\"center\">   1/2      </td> </tr>\n<tr><td align=\"center\">   5        </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   5/2    </td> <td align=\"center\">   3/2      </td> </tr>\n<tr><td align=\"center\">   6        </td> <td align=\"center\">   0      </td> <td align=\"center\">   2      </td> <td align=\"center\">   5/2    </td> <td align=\"center\">   5/2      </td> </tr>\n</tbody>\n</table>\nFor two particles, there are a total of 15 states, which we list here with the total $M$:\n* $| 1,2 \\rangle$, $M= -4$,  $| 1,3 \\rangle$, $M= -3$\n\n* $| 1,4 \\rangle$, $M= -2$, $| 1,5 \\rangle$, $M= -1$\n\n* $| 1,5 \\rangle$, $M= 0$, $| 2,3 \\rangle$, $M= -2$\n\n* $| 2,4 \\rangle$, $M= -1$, $| 2,5 \\rangle$, $M= 0$\n\n* $| 2,6 \\rangle$, $M= 1$, $| 3,4 \\rangle$, $M= 0$\n\n* $| 3,5 \\rangle$, $M= 1$, $| 3,6 \\rangle$, $M= 2$\n\n* $| 4,5 \\rangle$, $M= 2$, $ | 4,6 \\rangle$, $M= 3$\n\n* $| 5,6 \\rangle$, $M= 4$\n\nOf these, there are only 3 states with $M=0$. \n\n*You should try* by hand to show that in this same single-particle space, that for \n$N=3$ there are 3 states with $M=1/2$ and for $N= 4$ there are also only 3 states with $M=0$. \n\n*To test your code*, confirm the above. \n\nAlso, \nfor the $sd$-space given above, for $N=2$ there are 14 states with $M=0$, for $N=3$ there are 37 \nstates with $M=1/2$, for $N=4$ there are 81 states with $M=0$.\n\n\nFor our project, we will only consider the pairing model.\nA simple space is the $(1/2)^2$ space with four single-particle states\n\n<table border=\"1\">\n<thead>\n<tr><th align=\"center\">Index</th> <th align=\"center\">$n$</th> <th align=\"center\">$l$</th> <th align=\"center\">$s$</th> <th align=\"center\">$m_s$</th> </tr>\n</thead>\n<tbody>\n<tr><td align=\"center\">   1        </td> <td align=\"center\">   0      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   -1/2     </td> </tr>\n<tr><td align=\"center\">   2        </td> <td align=\"center\">   0      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   1/2      </td> </tr>\n<tr><td align=\"center\">   3        </td> <td align=\"center\">   1      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   -1/2     </td> </tr>\n<tr><td align=\"center\">   4        </td> <td align=\"center\">   1      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   1/2      </td> </tr>\n</tbody>\n</table>\nFor $N=2$ there are 4 states with $M=0$; show this by hand and confirm your code reproduces it. \n\n\nAnother, slightly more challenging space is the $(1/2)^4$ space, that is, \nwith eight  single-particle states we have\n\n<table border=\"1\">\n<thead>\n<tr><th align=\"center\">Index</th> <th align=\"center\">$n$</th> <th align=\"center\">$l$</th> <th align=\"center\">$s$</th> <th align=\"center\">$m_s$</th> </tr>\n</thead>\n<tbody>\n<tr><td align=\"center\">   1        </td> <td align=\"center\">   0      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   -1/2     </td> </tr>\n<tr><td align=\"center\">   2        </td> <td align=\"center\">   0      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   1/2      </td> </tr>\n<tr><td align=\"center\">   3        </td> <td align=\"center\">   1      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   -1/2     </td> </tr>\n<tr><td align=\"center\">   4        </td> <td align=\"center\">   1      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   1/2      </td> </tr>\n<tr><td align=\"center\">   5        </td> <td align=\"center\">   2      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   -1/2     </td> </tr>\n<tr><td align=\"center\">   6        </td> <td align=\"center\">   2      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   1/2      </td> </tr>\n<tr><td align=\"center\">   7        </td> <td align=\"center\">   3      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   -1/2     </td> </tr>\n<tr><td align=\"center\">   8        </td> <td align=\"center\">   3      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   1/2      </td> </tr>\n</tbody>\n</table>\nFor $N=2$ there are 16 states with $M=0$; for $N=3$ there are 24 states with $M=1/2$, and for \n$N=4$ there are 36 states with $M=0$. \n\n\nIn the shell-model context we can interpret this as 4 $s_{1/2}$ levels, with $m = \\pm 1/2$, we can also think of these are simple four pairs,  $\\pm k, k = 1,2,3,4$. Later on we will \nassign single-particle energies,  depending on the radial quantum number $n$, that is, \n$\\epsilon_k = |k| \\delta$ so that they are equally spaced.\n\n\nFor application in the pairing model we can go further and consider only states with \nno \"broken pairs,\" that is, if $+k$ is filled (or $m = +1/2$, so is $-k$ ($m=-1/2$). \nIf you want, you can write your code to accept only these, and obtain the following \nsix states:\n\n* $|           1,           2 ,          3         ,       4  \\rangle , $\n\n* $|            1      ,     2        ,        5         ,       6 \\rangle , $\n\n* $|            1         ,       2     ,           7         ,       8  \\rangle , $\n\n* $|            3        ,        4      ,          5          ,      6  \\rangle , $\n\n* $|            3        ,        4      ,          7         ,       8  \\rangle , $\n\n* $|            5        ,        6     ,           7     ,           8  \\rangle $\n\n* Write small modules (routines/functions) ; avoid big functions  that do everything. (But not too small.)\n\n* Write lots of error traps, even for things that are `obvious.'\n\n* Document as you go along.  For each function write a header that includes: \n\n1. Main purpose of function\n\n2. names and  brief explanation of input variables, if any \n\n3. names and brief explanation of output variables, if any\n\n4. functions called by this function\n\n5. called by which functions\n\n\nHints for coding\n\n* When debugging, print out intermediate values. It's almost impossible to debug a  code by looking at it--the code will almost always win a `staring contest.'\n\n* Validate code with SIMPLE CASES. Validate early and often.   \n\nThe number one mistake is using a too complex a system to test. For example ,\nif you are computing particles in a potential in a box, try removing the potential--you should get \nparticles in a box. And start with one particle, then two, then three... Don't start with \neight particles.\n\n\nOur recommended occupation representation, e.g. $| 1,2,4,8 \\rangle$, is \neasy to code, but numerically inefficient when one has hundreds of \nmillions of Slater determinants.\n\n\nIn state-of-the-art shell-model codes, one generally uses bit \nrepresentation, i.e. $|1101000100... \\rangle$ where one stores \nthe Slater determinant as a single (or a small number of) integer.\n\n\nThis is much more compact, but more intricate to code with considerable \nmore overhead. There exist \nbit-manipulation functions. \nThis is left as a challenge for those of you who would like to study this topic further for the final project to be presented for the oral examination.\n\n\n### Example case: pairing Hamiltonian\n\nWe consider a space with $2\\Omega$ single-particle states, with each \nstate labeled by \n$k = 1, 2, 3, \\Omega$ and $m = \\pm 1/2$. The convention is that \nthe state with $k>0$ has $m = + 1/2$ while $-k$ has $m = -1/2$.\n\n\nThe Hamiltonian we consider is\n\n$$\n\\hat{H} = -G \\hat{P}_+ \\hat{P}_-,\n$$\n\nwhere\n\n$$\n\\hat{P}_+ = \\sum_{k > 0} \\hat{a}^\\dagger_k \\hat{a}^\\dagger_{-{k}}.\n$$\n\nand $\\hat{P}_- = ( \\hat{P}_+)^\\dagger$.\n\nThis problem can be solved using what is called the quasi-spin formalism to obtain the \nexact results. Thereafter we will try again using the explicit Slater determinant formalism.\n\n\nOne can show (and this is part of the project) that\n\n$$\n\\left [ \\hat{P}_+, \\hat{P}_- \\right ] = \\sum_{k> 0} \\left( \\hat{a}^\\dagger_k \\hat{a}_k \n+ \\hat{a}^\\dagger_{-{k}} \\hat{a}_{-{k}} - 1 \\right) = \\hat{N} - \\Omega.\n$$\n\nNow define\n\n$$\n\\hat{P}_z = \\frac{1}{2} ( \\hat{N} -\\Omega).\n$$\n\nFinally you can show\n\n$$\n\\left [ \\hat{P}_z , \\hat{P}_\\pm \\right ] = \\pm \\hat{P}_\\pm.\n$$\n\nThis means the operators $\\hat{P}_\\pm, \\hat{P}_z$ form a so-called  $SU(2)$ algebra, and we can \nuse all our insights about angular momentum, even though there is no actual \nangular momentum involved (this is similar to project 1).\n\nSo we rewrite the Hamiltonian to make this explicit:\n\n$$\n\\hat{H} = -G \\hat{P}_+ \\hat{P}_- \n= -G \\left( \\hat{P}^2 - \\hat{P}_z^2 + \\hat{P}_z\\right)\n$$\n\nBecause of the SU(2) algebra, we know that the eigenvalues of \n$\\hat{P}^2$ must be of the form $p(p+1)$, with $p$ either integer or half-integer, and the eigenvalues of $\\hat{P}_z$ \nare $m_p$ with $p \\geq | m_p|$, with $m_p$ also integer or half-integer. \n\n\nBut because $\\hat{P}_z = (1/2)(\\hat{N}-\\Omega)$, we know that for $N$ particles \nthe value $m_p = (N-\\Omega)/2$. Furthermore, the values of $m_p$ range from \n$-\\Omega/2$ (for $N=0$) to $+\\Omega/2$ (for $N=2\\Omega$, with all states filled). \n\nWe deduce the maximal $p = \\Omega/2$ and for a given $n$ the \nvalues range of $p$ range from $|N-\\Omega|/2$ to $\\Omega/2$ in steps of 1 \n(for an even number of particles) \n\n\nFollowing Racah we introduce the notation\n$p = (\\Omega - v)/2$\nwhere $v = 0, 2, 4,..., \\Omega - |N-\\Omega|$ \nWith this it is easy to deduce that the eigenvalues of the pairing Hamiltonian are\n\n$$\n-G(N-v)(2\\Omega +2-N-v)/4\n$$\n\nThis also works for $N$ odd, with $v= 1,3,5, \\dots$.\n\n\n\nLet's take a specific example: $\\Omega = 3$ so there are 6 single-particle states, \nand $N = 3$, with $v= 1,3$. Therefore there are two distinct eigenvalues,\n\n$$\nE = -2G, 0\n$$\n\nNow let's work this out explicitly. The single particle degrees of freedom are defined as\n\n<table border=\"1\">\n<thead>\n<tr><th align=\"center\">Index</th> <th align=\"center\">$k$</th> <th align=\"center\">$m$ </th> </tr>\n</thead>\n<tbody>\n<tr><td align=\"center\">   1        </td> <td align=\"center\">   1      </td> <td align=\"center\">   -1/2    </td> </tr>\n<tr><td align=\"center\">   2        </td> <td align=\"center\">   -1     </td> <td align=\"center\">   1/2     </td> </tr>\n<tr><td align=\"center\">   3        </td> <td align=\"center\">   2      </td> <td align=\"center\">   -1/2    </td> </tr>\n<tr><td align=\"center\">   4        </td> <td align=\"center\">   -2     </td> <td align=\"center\">   1/2     </td> </tr>\n<tr><td align=\"center\">   5        </td> <td align=\"center\">   3      </td> <td align=\"center\">   -1/2    </td> </tr>\n<tr><td align=\"center\">   6        </td> <td align=\"center\">   -3     </td> <td align=\"center\">   1/2     </td> </tr>\n</tbody>\n</table>\n There are  $\\left( \\begin{array}{c}6 \\\\ 3 \\end{array} \\right) = 20$ three-particle states, but there \nare 9 states with $M = +1/2$, namely\n$| 1,2,3 \\rangle, |1,2,5\\rangle, | 1,4,6 \\rangle, | 2,3,4 \\rangle, |2,3,6 \\rangle, | 2,4,5 \\rangle, | 2, 5, 6 \\rangle, |3,4,6 \\rangle, | 4,5,6 \\rangle$.\n\n\n\n\n\n\n\n\n\n\n\nIn this basis, the operator\n\n$$\n\\hat{P}_+\n= \\hat{a}^\\dagger_1 \\hat{a}^\\dagger_2 + \\hat{a}^\\dagger_3 \\hat{a}^\\dagger_4 +\n\\hat{a}^\\dagger_5 \\hat{a}^\\dagger_6\n$$\n\nFrom this we can determine that\n\n$$\n\\hat{P}_- | 1, 4, 6 \\rangle = \\hat{P}_- | 2, 3, 6 \\rangle\n= \\hat{P}_- | 2, 4, 5 \\rangle = 0\n$$\n\nso those states all have eigenvalue 0.\n\n\nNow for further example,\n\n$$\n\\hat{P}_- | 1,2,3 \\rangle = | 3 \\rangle\n$$\n\nso\n\n$$\n\\hat{P}_+ \\hat{P}_- | 1,2,3\\rangle = | 1,2,3\\rangle+ | 3,4,3\\rangle + | 5,6,3\\rangle\n$$\n\nThe second term vanishes because state 3 is occupied twice, and reordering the last \nterm we\nget\n\n$$\n\\hat{P}_+ \\hat{P}_- | 1,2,3\\rangle = | 1,2,3\\rangle+ |3, 5,6\\rangle\n$$\n\nwithout picking up a phase.\n\n\n\nContinuing in this fashion, with the previous ordering of the many-body states\n(  $| 1,2,3 \\rangle, |1,2,5\\rangle, | 1,4,6 \\rangle, | 2,3,4 \\rangle, |2,3,6 \\rangle, | 2,4,5 \\rangle, | 2, 5, 6 \\rangle, |3,4,6 \\rangle, | 4,5,6 \\rangle$) the \nHamiltonian matrix of this system is\n\n$$\nH = -G\\left( \n\\begin{array}{ccccccccc}\n1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1  \\\\\n0 & 1 & 0 & 0 & 0 & 0 & 0 & 1 & 0  \\\\\n0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0  \\\\\n0 & 0 & 0 & 1 & 0 & 0 & 1 & 0 & 0  \\\\\n0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0  \\\\\n0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0  \\\\\n0 & 0 & 0 & 1 & 0 & 0 & 1 & 0 & 0  \\\\\n0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0  \\\\\n0 & 1 & 0 & 0 & 0 & 0 & 0 & 1 & 0  \\\\\n1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1  \n\\end{array} \\right )\n$$\n\nThis is useful for our project.  One can by hand confirm \nthat there are 3 eigenvalues $-2G$ and 6 with value zero.\n\n\n\nAnother example\nUsing the $(1/2)^4$ single-particle space, resulting in eight single-particle states\n\n<table border=\"1\">\n<thead>\n<tr><th align=\"center\">Index</th> <th align=\"center\">$n$</th> <th align=\"center\">$l$</th> <th align=\"center\">$s$</th> <th align=\"center\">$m_s$</th> </tr>\n</thead>\n<tbody>\n<tr><td align=\"center\">   1        </td> <td align=\"center\">   0      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   -1/2     </td> </tr>\n<tr><td align=\"center\">   2        </td> <td align=\"center\">   0      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   1/2      </td> </tr>\n<tr><td align=\"center\">   3        </td> <td align=\"center\">   1      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   -1/2     </td> </tr>\n<tr><td align=\"center\">   4        </td> <td align=\"center\">   1      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   1/2      </td> </tr>\n<tr><td align=\"center\">   5        </td> <td align=\"center\">   2      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   -1/2     </td> </tr>\n<tr><td align=\"center\">   6        </td> <td align=\"center\">   2      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   1/2      </td> </tr>\n<tr><td align=\"center\">   7        </td> <td align=\"center\">   3      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   -1/2     </td> </tr>\n<tr><td align=\"center\">   8        </td> <td align=\"center\">   3      </td> <td align=\"center\">   0      </td> <td align=\"center\">   1/2    </td> <td align=\"center\">   1/2      </td> </tr>\n</tbody>\n</table>\nand then taking only 4-particle, $M=0$ states that have no `broken pairs', there are six basis Slater \ndeterminants:\n\n* $|           1,           2 ,          3         ,       4  \\rangle , $\n\n* $|            1      ,     2        ,        5         ,       6 \\rangle , $\n\n* $|            1         ,       2     ,           7         ,       8  \\rangle , $\n\n* $|            3        ,        4      ,          5          ,      6  \\rangle , $\n\n* $|            3        ,        4      ,          7         ,       8  \\rangle , $\n\n* $|            5        ,        6     ,           7     ,           8  \\rangle $\n\nNow we take the following Hamiltonian\n\n$$\n\\hat{H} = \\sum_n n \\delta \\hat{N}_n  - G \\hat{P}^\\dagger \\hat{P}\n$$\n\nwhere\n\n$$\n\\hat{N}_n = \\hat{a}^\\dagger_{n, m=+1/2} \\hat{a}_{n, m=+1/2} +\n\\hat{a}^\\dagger_{n, m=-1/2} \\hat{a}_{n, m=-1/2}\n$$\n\nand\n\n$$\n\\hat{P}^\\dagger = \\sum_{n} \\hat{a}^\\dagger_{n, m=+1/2} \\hat{a}^\\dagger_{n, m=-1/2}\n$$\n\nWe can write down the $ 6 \\times 6$  Hamiltonian in the basis from the prior slide:\n\n$$\nH = \\left ( \n\\begin{array}{cccccc}\n2\\delta -2G & -G & -G & -G & -G & 0 \\\\\n -G & 4\\delta -2G & -G & -G & -0 & -G \\\\\n-G & -G & 6\\delta -2G & 0 & -G & -G \\\\\n -G & -G & 0 & 6\\delta-2G & -G & -G \\\\\n -G & 0 & -G & -G & 8\\delta-2G & -G \\\\\n0 & -G & -G & -G & -G & 10\\delta -2G \n\\end{array} \\right )\n$$\n\n(You should check by hand that this is correct.) \n\nFor $\\delta = 0$ we have the closed form solution of  the g.s. energy given by $-6G$.\n\n\n\n\n\n\n\n\n\n\n### Angular momentum algebra, Wigner-Eckart theorem\n\n* We need to define the so-called $6j$ and $9j$ symbols\n\n* The Wigner-Eckart theorem\n\n* We will also study  some specific examples, like the calculation of the tensor force.\n\nWe define an irreducible  spherical tensor $T^{\\lambda}_{\\mu}$ of rank $\\lambda$ as an operator with $2\\lambda+1$ components $\\mu$ \nthat satisfies the commutation relations ($\\hbar=1$)\n\n$$\n[J_{\\pm}, T^{\\lambda}_{\\mu}]= \\sqrt{(\\lambda\\mp \\mu)(\\lambda\\pm \\mu+1)}T^{\\lambda}_{\\mu\\pm 1},\n$$\n\nand\n\n$$\n[J_{z}, T^{\\lambda}_{\\mu}]=\\mu T^{\\lambda}_{\\mu}.\n$$\n\nOur angular momentum coupled two-body wave function obeys clearly this definition, namely\n\n$$\n|(ab)JM\\rangle  = \\left\\{a^{\\dagger}_aa^{\\dagger}_b\\right\\}^J_M|\\Phi_0\\rangle=N_{ab}\\sum_{m_am_b}\\langle j_am_aj_bm_b|JM\\rangle|\\Phi^{ab}\\rangle,\n$$\n\nis a tensor of rank $J$ with $M$ components. Another well-known example is given by the spherical harmonics (see examples during today's lecture). \n\nThe product of two irreducible tensor operators\n\n$$\nT^{\\lambda_3}_{\\mu_3}=\\sum_{\\mu_1\\mu_2}\\langle \\lambda_1\\mu_1\\lambda_2\\mu_2|\\lambda_3\\mu_3\\rangle T^{\\lambda_1}_{\\mu_1}T^{\\lambda_2}_{\\mu_2}\n$$\n\nis also a tensor operator of rank $\\lambda_3$. \n\n\nWe wish to apply the above definitions to the computations of a matrix element\n\n$$\n\\langle \\Phi^J_M|T^{\\lambda}_{\\mu}|\\Phi^{J'}_{M'}\\rangle,\n$$\n\nwhere we have skipped a reference to specific single-particle states. This is the expectation value for two specific states, labelled by angular momenta $J'$ and $J$. These states form an orthonormal basis.\nUsing the properties of the Clebsch-Gordan coefficients we can write\n\n$$\nT^{\\lambda}_{\\mu}|\\Phi^{J'}_{M'}\\rangle=\\sum_{J''M''}\\langle \\lambda \\mu J'M'|J''M''\\rangle|\\Psi^{J''}_{M''}\\rangle,\n$$\n\nand assuming that states with different $J$ and $M$ are orthonormal we arrive at\n\n$$\n\\langle \\Phi^J_M|T^{\\lambda}_{\\mu}|\\Phi^{J'}_{M'}\\rangle= \\langle \\lambda \\mu J'M'|JM\\rangle \\langle \\Phi^J_M|\\Psi^{J}_{M}\\rangle.\n$$\n\nWe need to show that\n\n$$\n\\langle \\Phi^J_M|\\Psi^{J}_{M}\\rangle,\n$$\n\nis independent of $M$.\nTo show that\n\n$$\n\\langle \\Phi^J_M|\\Psi^{J}_{M}\\rangle,\n$$\n\nis independent of $M$, we use the ladder operators for angular momentum.\n\n\n We have that\n\n$$\n\\langle \\Phi^J_{M+1}|\\Psi^{J}_{M+1}\\rangle=\\left((J-M)(J+M+1)\\right)^{-1/2}\\langle \\hat{J}_{+}\\Phi^J_{M}|\\Psi^{J}_{M+1}\\rangle,\n$$\n\nbut this is also equal to\n\n$$\n\\langle \\Phi^J_{M+1}|\\Psi^{J}_{M+1}\\rangle=\\left((J-M)(J+M+1)\\right)^{-1/2}\\langle \\Phi^J_{M}|\\hat{J}_{-}\\Psi^{J}_{M+1}\\rangle,\n$$\n\nmeaning that\n\n$$\n\\langle \\Phi^J_{M+1}|\\Psi^{J}_{M+1}\\rangle=\\langle \\Phi^J_M|\\Psi^{J}_{M}\\rangle\\equiv\\langle \\Phi^J_{M}||T^{\\lambda}||\\Phi^{J'}_{M'}\\rangle.\n$$\n\nThe double bars indicate that this expectation value is independent of the projection $M$.\n\n\nThe Wigner-Eckart theorem for an expectation value can then be written as\n\n$$\n\\langle \\Phi^J_M|T^{\\lambda}_{\\mu}|\\Phi^{J'}_{M'}\\rangle\\equiv\\langle \\lambda \\mu J'M'|JM\\rangle\\langle \\Phi^J||T^{\\lambda}||\\Phi^{J'}\\rangle.\n$$\n\nThe double bars indicate that this expectation value is independent of the projection $M$.\nWe can manipulate the Clebsch-Gordan coefficients using the relations\n\n$$\n\\langle \\lambda \\mu J'M'|JM\\rangle= (-1)^{\\lambda+J'-J}\\langle J'M'\\lambda \\mu |JM\\rangle\n$$\n\nand\n\n$$\n\\langle J'M'\\lambda \\mu |JM\\rangle =(-1)^{J'-M'}\\frac{\\sqrt{2J+1}}{\\sqrt{2\\lambda+1}}\\langle J'M'J-M |\\lambda-\\mu\\rangle,\n$$\n\ntogether with the so-called $3j$ symbols.\nIt is then normal to encounter the Wigner-Eckart theorem in the form\n\n$$\n\\langle \\Phi^J_M|T^{\\lambda}_{\\mu}|\\Phi^{J'}_{M'}\\rangle\\equiv(-1)^{J-M}\\left(\\begin{array}{ccc}  J & \\lambda & J' \\\\ -M & \\mu & M'\\end{array}\\right)\\langle \\Phi^J||T^{\\lambda}||\\Phi^{J'}\\rangle,\n$$\n\nwith the condition $\\mu+M'-M=0$.\n\nThe $3j$ symbols obey the symmetry relation\n\n$$\n\\left(\\begin{array}{ccc}  j_1 & j_2 & j_3 \\\\ m_1 & m_2 & m_3\\end{array}\\right)=(-1)^{p}\\left(\\begin{array}{ccc}  j_a & j_b & j_c \\\\ m_a & m_b & m_c\\end{array}\\right),\n$$\n\nwith $(-1)^p=1$ when the columns $a,b, c$ are even permutations of the columns $1,2,3$, $p=j_1+j_2+j_3$ when the columns $a,b,c$ are odd permtations of the\ncolumns $1,2,3$ and $p=j_1+j_2+j_3$ when all the magnetic quantum numbers $m_i$ change sign. Their orthogonality is given by\n\n$$\n\\sum_{j_3m_3}(2j_3+1)\\left(\\begin{array}{ccc}  j_1 & j_2 & j_3 \\\\ m_1 & m_2 & m_3\\end{array}\\right)\\left(\\begin{array}{ccc}  j_1 & j_2 & j_3 \\\\ m_{1'} & m_{2'} & m_3\\end{array}\\right)=\\delta_{m_1m_{1'}}\\delta_{m_2m_{2'}},\n$$\n\nand\n\n$$\n\\sum_{m_1m_2}\\left(\\begin{array}{ccc}  j_1 & j_2 & j_3 \\\\ m_1 & m_2 & m_3\\end{array}\\right)\\left(\\begin{array}{ccc}  j_1 & j_2 & j_{3'} \\\\ m_{1} & m_{2} & m_{3'}\\end{array}\\right)=\\frac{1}{(2j_3+1)}\\delta_{j_3j_{3'}}\\delta_{m_3m_{3'}}.\n$$\n\nFor later use, the following special cases for the Clebsch-Gordan and $3j$ symbols are rather useful\n\\[\n\\langle JM J'M' |00\\rangle =\\frac{(-1)^{J-M}}{\\sqrt{2J+1}}\\delta_{JJ'}\\delta_{MM'}.\n\\] \nand \n\\[\n\\left(\\begin{array}{ccc}  J & 1 & J \\\\ -M & 0 & M'\\end{array}\\right)=(-1)^{J-M}\\frac{M}{\\sqrt{(2J+1)(J+1)}}\\delta_{MM'}.\n\\]\n\nUsing $3j$ symbols we rewrote the Wigner-Eckart theorem as\n\n$$\n\\langle \\Phi^J_M|T^{\\lambda}_{\\mu}|\\Phi^{J'}_{M'}\\rangle\\equiv(-1)^{J-M}\\left(\\begin{array}{ccc}  J & \\lambda & J' \\\\ -M & \\mu & M'\\end{array}\\right)\\langle \\Phi^J||T^{\\lambda}||\\Phi^{J'}\\rangle.\n$$\n\nMultiplying from the left with the same $3j$ symbol and summing over $M,\\mu,M'$ we obtain the equivalent relation\n\n$$\n\\langle \\Phi^J||T^{\\lambda}||\\Phi^{J'}\\rangle\\equiv\\sum_{M,\\mu,M'}(-1)^{J-M}\\left(\\begin{array}{ccc}  J & \\lambda & J' \\\\ -M & \\mu & M'\\end{array}\\right)\\langle \\Phi^J_M|T^{\\lambda}_{\\mu}|\\Phi^{J'}_{M'}\\rangle,\n$$\n\nwhere we used the orthogonality properties of the $3j$ symbols from the previous page.\n\nThis relation can in turn be used to compute the expectation value of some simple reduced matrix elements like\n\n$$\n\\langle \\Phi^J||{\\bf 1}||\\Phi^{J'}\\rangle=\\sum_{M,M'}(-1)^{J-M}\\left(\\begin{array}{ccc}  J & 0 & J' \\\\ -M & 0 & M'\\end{array}\\right)\\langle \\Phi^J_M|1|\\Phi^{J'}_{M'}\\rangle=\\sqrt{2J+1}\\delta_{JJ'}\\delta_{MM'},\n$$\n\nwhere we used\n\n$$\n\\langle JM J'M' |00\\rangle =\\frac{(-1)^{J-M}}{\\sqrt{2J+1}}\\delta_{JJ'}\\delta_{MM'}.\n$$\n\nSimilarly, using\n\n$$\n\\left(\\begin{array}{ccc}  J & 1 & J \\\\ -M & 0 & M'\\end{array}\\right)=(-1)^{J-M}\\frac{M}{\\sqrt{(2J+1)(J+1)}}\\delta_{MM'},\n$$\n\nwe have that\n\n$$\n\\langle \\Phi^J||{\\bf J}||\\Phi^{J}\\rangle=\\sum_{M,M'}(-1)^{J-M}\\left(\\begin{array}{ccc}  J & 1 & J' \\\\ -M & 0 & M'\\end{array}\\right)\\langle \\Phi^J_M|j_Z|\\Phi^{J'}_{M'}\\rangle=\\sqrt{J(J+1)(2J+1)}\n$$\n\nWith the Pauli spin matrices $\\sigma$ and a state with $J=1/2$, the reduced matrix element\n\n$$\n\\langle \\frac{1}{2}||{\\bf \\sigma}||\\frac{1}{2}\\rangle=\\sqrt{6}.\n$$\n\nBefore we proceed with further examples, we need some other properties of the Wigner-Eckart theorem plus some additional angular momenta relations.\n\n\nThe Wigner-Eckart theorem states that the  expectation value for an irreducible spherical tensor can be written as\n\n$$\n\\langle \\Phi^J_M|T^{\\lambda}_{\\mu}|\\Phi^{J'}_{M'}\\rangle\\equiv\\langle \\lambda \\mu J'M'|JM\\rangle\\langle \\Phi^J||T^{\\lambda}||\\Phi^{J'}\\rangle.\n$$\n\nSince the Clebsch-Gordan coefficients themselves are easy to evaluate, the interesting quantity is the reduced matrix element. Note also that \nthe Clebsch-Gordan coefficients limit via the triangular relation among $\\lambda$, $J$ and $J'$ the possible non-zero values.\n\nFrom the theorem we see also that\n\n$$\n\\langle \\Phi^J_M|T^{\\lambda}_{\\mu}|\\Phi^{J'}_{M'}\\rangle=\\frac{\\langle \\lambda \\mu J'M'|JM\\rangle\\langle }{\\langle \\lambda \\mu_0 J'M'_0|JM_0\\rangle\\langle }\\langle \\Phi^J_{M_0}|T^{\\lambda}_{\\mu_0}|\\Phi^{J'}_{M'_0}\\rangle,\n$$\n\nmeaning that if we know the matrix elements for say some $\\mu=\\mu_0$, $M'=M'_0$ and $M=M_0$ we can calculate all other. \n\n\n\nIf we look at the hermitian adjoint of the operator $T^{\\lambda}_{\\mu}$, \nwe see via the commutation relations that $(T^{\\lambda}_{\\mu})^{\\dagger}$ is not an irreducible tensor, that is\n\n$$\n[J_{\\pm}, (T^{\\lambda}_{\\mu})^{\\dagger}]= -\\sqrt{(\\lambda\\pm \\mu)(\\lambda\\mp \\mu+1)}(T^{\\lambda}_{\\mu\\mp 1})^{\\dagger},\n$$\n\nand\n\n$$\n[J_{z}, (T^{\\lambda}_{\\mu})^{\\dagger}]=-\\mu (T^{\\lambda}_{\\mu})^{\\dagger}.\n$$\n\nThe hermitian adjoint $(T^{\\lambda}_{\\mu})^{\\dagger}$ is not an irreducible tensor. As an example, consider the spherical harmonics for \n$l=1$ and $m_l=\\pm 1$. These functions are\n\n$$\nY^{l=1}_{m_l=1}(\\theta,\\phi)=-\\sqrt{\\frac{3}{8\\pi}}\\sin{(\\theta)}\\exp{\\imath\\phi},\n$$\n\nand\n\n$$\nY^{l=1}_{m_l=-1}(\\theta,\\phi)=\\sqrt{\\frac{3}{8\\pi}}\\sin{(\\theta)}\\exp{-\\imath\\phi},\n$$\n\nIt is easy to see that the Hermitian adjoint of these two functions\n\n$$\n\\left[Y^{l=1}_{m_l=1}(\\theta,\\phi)\\right]^{\\dagger}=-\\sqrt{\\frac{3}{8\\pi}}\\sin{(\\theta)}\\exp{-\\imath\\phi},\n$$\n\nand\n\n$$\n\\left[Y^{l=1}_{m_l=-1}(\\theta,\\phi)\\right]^{\\dagger}=\\sqrt{\\frac{3}{8\\pi}}\\sin{(\\theta)}\\exp{\\imath\\phi},\n$$\n\ndo not behave as a spherical tensor. However, the modified quantity\n\n$$\n\\tilde{T}^{\\lambda}_{\\mu}=(-1)^{\\lambda+\\mu}(T^{\\lambda}_{-\\mu})^{\\dagger},\n$$\n\ndoes satisfy the above commutation relations.\n\n\n\n\n\nWith the modified quantity\n\n$$\n\\tilde{T}^{\\lambda}_{\\mu}=(-1)^{\\lambda+\\mu}(T^{\\lambda}_{-\\mu})^{\\dagger},\n$$\n\nwe can then define the expectation value\n\n$$\n\\langle \\Phi^J_M|T^{\\lambda}_{\\mu}|\\Phi^{J'}_{M'}\\rangle^{\\dagger} = \\langle \\lambda \\mu J'M'|JM\\rangle\\langle \\Phi^J||T^{\\lambda}||\\Phi^{J'}\\rangle^*,\n$$\n\nsince the Clebsch-Gordan coefficients are real. The rhs is equivalent with\n\n$$\n\\langle \\lambda \\mu J'M'|JM\\rangle\\langle \\Phi^J||T^{\\lambda}||\\Phi^{J'}\\rangle^*=\\langle \\Phi^{J'}_{M'}|(T^{\\lambda}_{\\mu})^{\\dagger}|\\Phi^{J}_{M}\\rangle,\n$$\n\nwhich is equal to\n\n$$\n\\langle \\Phi^{J'}_{M'}|(T^{\\lambda}_{\\mu})^{\\dagger}|\\Phi^{J}_{M}\\rangle=(-1)^{-\\lambda+\\mu}\\langle \\lambda -\\mu JM|J'M'\\rangle\\langle \\Phi^{J'}||\\tilde{T}^{\\lambda}||\\Phi^{J}\\rangle.\n$$\n\nWe have till now seen the following definitions of a two-body matrix elements \nwith quantum numbers $p=j_pm_p$ etc we have a two-body state defined as\n\n$$\n|(pq)M\\rangle  = a^{\\dagger}_pa^{\\dagger}_q|\\Phi_0\\rangle,\n$$\n\nwhere $|\\Phi_0\\rangle$ is a chosen reference state, say for example the Slater determinant which approximates \n${}^{16}\\mbox{O}$ with the $0s$ and the $0p$ shells being filled, and $M=m_p+m_q$. Recall that we label single-particle states above the Fermi level as $abcd\\dots$ and states below the Fermi level for $ijkl\\dots$.  \nIn case of two-particles in the single-particle states $a$ and $b$ outside ${}^{16}\\mbox{O}$ as a closed shell core, say ${}^{18}\\mbox{O}$, \nwe would write the representation of the Slater determinant as\n\n$$\n|^{18}\\mathrm{O}\\rangle =|(ab)M\\rangle  = a^{\\dagger}_aa^{\\dagger}_b|^{16}\\mathrm{O}\\rangle=|\\Phi^{ab}\\rangle.\n$$\n\nIn case of two-particles removed from say ${}^{16}\\mbox{O}$, for example two neutrons in the single-particle states $i$ and $j$, we would write this as\n\n$$\n|^{14}\\mathrm{O}\\rangle =|(ij)M\\rangle  = a_ja_i|^{16}\\mathrm{O}\\rangle=|\\Phi_{ij}\\rangle.\n$$\n\nFor a one-hole-one-particle state we have\n\n$$\n|^{16}\\mathrm{O}\\rangle_{1p1h} =|(ai)M\\rangle  = a_a^{\\dagger}a_i|^{16}\\mathrm{O}\\rangle=|\\Phi_{i}^a\\rangle,\n$$\n\nand finally for a two-particle-two-hole state we\n\n$$\n|^{16}\\mathrm{O}\\rangle_{2p2h} =|(abij)M\\rangle  = a_a^{\\dagger}a_b^{\\dagger}a_ja_i|^{16}\\mathrm{O}\\rangle=|\\Phi_{ij}^{ab}\\rangle.\n$$\n\nLet us go back to the case of two-particles in the single-particle states $a$ and $b$ outside ${}^{16}\\mbox{O}$ as a closed shell core, say ${}^{18}\\mbox{O}$.\nThe representation of the Slater determinant is\n\n$$\n|^{18}\\mathrm{O}\\rangle =|(ab)M\\rangle  = a^{\\dagger}_aa^{\\dagger}_b|^{16}\\mathrm{O}\\rangle=|\\Phi^{ab}\\rangle.\n$$\n\nThe anti-symmetrized matrix element is detailed as\n\n$$\n\\langle (ab) M | \\hat{V} | (cd) M \\rangle = \\langle (j_am_aj_bm_b)M=m_a+m_b |  \\hat{V} | (j_cm_cj_dm_d)M=m_a+m_b \\rangle,\n$$\n\nand note that anti-symmetrization means\n\n8\n2\n8\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\langle (ab) M | \\hat{V} | (cd) M \\rangle =-\\langle (ab) M | \\hat{V} | (dc) M \\rangle.\n$$\n\nThis matrix element is the expectation value of\n\n$$\n\\langle ^{16}\\mathrm{O}|a_ba_a\\frac{1}{4}\\sum_{pqrs}\\langle (pq) M | \\hat{V} | (rs) M' \\rangle a^{\\dagger}_pa^{\\dagger}_qa_sa_r a^{\\dagger}_ca^{\\dagger}_c|^{16}\\mathrm{O}\\rangle.\n$$\n\nWe have also defined matrix elements in the coupled basis, the so-called $J$-coupled scheme.\nIn this case the two-body wave function for two neutrons outside ${}^{16}\\mbox{O}$ is written as\n\n$$\n|^{18}\\mathrm{O}\\rangle_J =|(ab)JM\\rangle  = \\left\\{a^{\\dagger}_aa^{\\dagger}_b\\right\\}^J_M|^{16}\\mathrm{O}\\rangle=N_{ab}\\sum_{m_am_b}\\langle j_am_aj_bm_b|JM\\rangle|\\Phi^{ab}\\rangle,\n$$\n\nwith\n\n$$\n|\\Phi^{ab}\\rangle=a^{\\dagger}_aa^{\\dagger}_b|^{16}\\mathrm{O}\\rangle.\n$$\n\nWe have now an explicit coupling order, where the angular momentum $j_a$ is coupled to the angular momentum $j_b$ to yield a final two-body angular momentum $J$. \nThe normalization factor is\n\n$$\nN_{ab}=\\frac{\\sqrt{1+\\delta_{ab}\\times (-1)^J}}{1+\\delta_{ab}}.\n$$\n\nThe implementation of the Pauli principle looks different in the $J$-scheme compared with the $m$-scheme. In the latter, no two fermions or more can have the same set of quantum numbers. In the $J$-scheme, when we write a state with the shorthand\n\n$$\n|^{18}\\mathrm{O}\\rangle_J =|(ab)JM\\rangle,\n$$\n\nwe do refer to the angular momenta only. This means that another way of writing the last state is\n\n$$\n|^{18}\\mathrm{O}\\rangle_J =|(j_aj_b)JM\\rangle.\n$$\n\nWe will use this notation throughout when we refer to a two-body state in $J$-scheme. The Kronecker $\\delta$ function in the normalization factor \nrefers thus to the values of $j_a$ and $j_b$. If two identical particles are in a state with the same $j$-value, then only even values of the total angular momentum apply.\n\n\n\nNote also that, using the anti-commuting \nproperties of the creation operators, we obtain\n\n$$\nN_{ab}\\sum_{m_am_b}\\langle j_am_aj_bm_b|JM>|\\Phi^{ab}\\rangle=-N_{ab}\\sum_{m_am_b}\\langle j_am_aj_bm_b|JM\\rangle|\\Phi^{ba}\\rangle.\n$$\n\nFurthermore, using the property of the Clebsch-Gordan coefficient\n\n$$\n\\langle j_am_aj_bm_b|JM>=(-1)^{j_a+j_b-J}\\langle j_bm_bj_am_a|JM\\rangle,\n$$\n\nwhich can be used to show that\n\n$$\n|(j_bj_a)JM\\rangle  = \\left\\{a^{\\dagger}_ba^{\\dagger}_a\\right\\}^J_M|^{16}\\mathrm{O}\\rangle=N_{ab}\\sum_{m_am_b}\\langle j_bm_bj_am_a|JM\\rangle|\\Phi^{ba}\\rangle,\n$$\n\nis equal to\n\n$$\n|(j_bj_a)JM\\rangle=(-1)^{j_a+j_b-J+1}|(j_aj_b)JM\\rangle.\n$$\n\nThe two-body matrix element is a scalar and since it obeys rotational symmetry, it is diagonal in $J$, \nmeaning that the corresponding matrix element in $J$-scheme is\n\n8\n4\n0\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\times \\langle j_cm_cj_dm_d|JM\\rangle\\langle (j_am_aj_bm_b)M |  \\hat{V} | (j_cm_cj_dm_d)M \\rangle,\n$$\n\nand note that of the four $m$-values in the above sum, only three are independent due to the constraint $m_a+m_b=M=m_c+m_d$.\n\nSince\n\n$$\n|(j_bj_a)JM\\rangle=(-1)^{j_a+j_b-J+1}|(j_aj_b)JM\\rangle,\n$$\n\nthe anti-symmetrized matrix elements need now to obey the following relations\n\n8\n4\n3\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n8\n4\n4\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\langle (j_aj_b) JM | \\hat{V} | (j_cj_d) JM \\rangle = (-1)^{j_a+j_b+j_c+j_d}\\langle (j_bj_a) JM | \\hat{V} | (j_dj_c) JM \\rangle=\\langle (j_bj_a) JM | \\hat{V} | (j_dj_c) JM \\rangle,\n$$\n\nwhere the last relations follows from the fact that $J$ is an integer and $2J$ is always an even number.\n\n\nUsing the orthogonality properties of the Clebsch-Gordan coefficients,\n\n$$\n\\sum_{m_am_b}\\langle j_am_aj_bm_b|JM\\rangle\\langle j_am_aj_bm_b|J'M'\\rangle=\\delta_{JJ'}\\delta_{MM'},\n$$\n\nand\n\n$$\n\\sum_{JM}\\langle j_am_aj_bm_b|JM\\rangle\\langle j_am_a'j_bm_b'|JM\\rangle=\\delta_{m_am_a'}\\delta_{m_bm_b'},\n$$\n\nwe can also express the two-body matrix element in $m$-scheme in terms of that in $J$-scheme, that is, if we multiply with\n\n$$\n\\sum_{JMJ'M'}\\langle j_am_a'j_bm_b'|JM\\rangle\\langle j_cm_c'j_dm_d'|J'M'\\rangle\n$$\n\nfrom left in\n\n8\n4\n9\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\times \\langle (j_am_aj_bm_b)M|  \\hat{V} | (j_cm_cj_dm_d)M\\rangle,\n$$\n\nwe obtain\n\n8\n5\n1\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\times \\langle (j_aj_b) JM | \\hat{V} | (j_cj_d) JM \\rangle.\n$$\n\nLet us now apply the theorem to some selected expectation values.\nIn several of the expectation values we will meet when evaluating explicit matrix elements, we will have to deal with expectation values involving spherical harmonics. A general central interaction can be expanded in a complete set of functions like the Legendre polynomials, that is, we have an interaction, with $r_{ij}=|{\\bf r}_i-{\\bf r}_j|$,\n\n$$\nv(r_{ij})=\\sum_{\\nu=0}^{\\infty}v_{\\nu}(r_{ij})P_{\\nu}(\\cos{(\\theta_{ij})},\n$$\n\nwith $P_{\\nu}$ being a Legendre polynomials\n\n$$\nP_{\\nu}(\\cos{(\\theta_{ij})}=\\sum_{\\mu}\\frac{4\\pi}{2\\mu+1}Y_{\\mu}^{\\nu *}(\\Omega_{i})Y_{\\mu}^{\\nu}(\\Omega_{j}).\n$$\n\nWe will come back later to how we split the above into a contribution that involves only one of the coordinates.\n\n\n\nThis means that we will need matrix elements of the type\n\n$$\n\\langle Y^{l'}||Y^{\\lambda}|| Y^{l}\\rangle.\n$$\n\nWe can rewrite the Wigner-Eckart theorem as\n\n$$\n\\langle Y^{l'}||Y^{\\lambda}|| Y^{l}\\rangle=\\sum_{m\\mu}\\langle \\lambda\\mu lm|l'm'\\rangle Y^{\\lambda}_{\\mu}Y^l_m,\n$$\n\nThis equation is true for all values of $\\theta$ and $\\phi$. It must also hold for $\\theta=0$.\n\n\nWe have\n\n$$\n\\langle Y^{l'}||Y^{\\lambda}|| Y^{l}\\rangle=\\sum_{m\\mu}\\langle \\lambda\\mu lm|l'm'\\rangle Y^{\\lambda}_{\\mu}Y^l_m,\n$$\n\nand for $\\theta=0$, the spherical harmonic\n\n$$\nY_m^l(\\theta=0,\\phi)=\\sqrt{\\frac{2l+1}{4\\pi}}\\delta_{m0},\n$$\n\nwhich results in\n\n$$\n\\langle Y^{l'}||Y^{\\lambda}|| Y^{l}\\rangle=\\left\\{\\frac{(2l+1)(2\\lambda+1)}{4\\pi(2l'+1)}\\right\\}^{1/2}\\langle \\lambda0 l0|l'0\\rangle.\n$$\n\nTill now we have mainly been concerned with the coupling of two angular momenta $j_aj_b$to a final angular momentum $J$.\nIf we wish to describe a three-body state with a final angular momentum $J$, we need to couple three angular momenta, say \nthe two momenta $j_a,j_b$ to a third one $j_c$. The coupling order is important and leads to a less trivial implementation of the \nPauli principle. With three angular momenta there are obviously $3!$ ways by which we can combine the angular momenta. \nIn $m$-scheme a three-body Slater determinant is represented as (say for the case of $^{19}$O, three neutrons outside the core of $^{16}$O),\n\n$$\n|^{19}\\mathrm{O}\\rangle =|(abc)M\\rangle  = a^{\\dagger}_aa^{\\dagger}_ba^{\\dagger}_c|^{16}\\mathrm{O}\\rangle=|\\Phi^{abc}\\rangle.\n$$\n\nThe Pauli principle is automagically implemented via the anti-commutation relations. \n\n\n\nHowever, when we deal the same state in an angular momentum coupled basis, we need to be a little bit more careful. We can namely couple the states\nas follows\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:fabc\"></div>\n\n$$\n| ([j_a\\rightarrow j_b]J_{ab}\\rightarrow j_c) J\\rangle= \\sum_{m_am_bm_c}\\langle j_am_aj_bm_b|J_{ab}M_{ab}\\rangle \\langle J_{ab}M_{ab}j_cm_c|JM\\rangle|j_am_a\\rangle\\otimes |j_bm_b\\rangle \\otimes |j_cm_c\\rangle \\ , \n\\label{eq:fabc} \\tag{131}\n$$\n\nthat is, we couple first $j_a$ to $j_b$ to yield an intermediate angular momentum $J_{ab}$, then to $j_c$ yielding the final angular momentum $J$.\n\n\n\nNow, nothing hinders us from recoupling this state by coupling $j_b$ to $j_c$, yielding an intermediate angular momentum $J_{bc}$ and then couple this angular momentum to $j_a$, resulting in the final angular momentum $J'$. \n\nThat is, we can have\n\n$$\n| (j_a\\rightarrow [j_b\\rightarrow j_c]J_{bc}) J\\rangle = \\sum_{m_a'm_b'm_c'}\\langle j_bm_b'j_cm_c'|J_{bc}M_{bc}\\rangle \\langle j_am_a'J_{bc}M_{bc}|J'M'\\rangle|\\Phi^{abc}\\rangle .\n$$\n\nWe will always assume that we work with orthornormal states, this means that when we compute the overlap betweem these two possible ways of coupling angular momenta, we get\n\n$$\n\\begin{eqnarray}\n\\nonumber\n\\lefteqn{ \\langle (j_a\\rightarrow [j_b\\rightarrow j_c]J_{bc}) J'M'| ([j_a\\rightarrow j_b]J_{ab}\\rightarrow j_c) JM\\rangle = } \\\\\n\\nonumber\n& & \\delta_{JJ'}\\delta_{MM'}\\sum_{m_am_bm_c}\\langle j_am_aj_bm_b|J_{ab}M_{ab}\\rangle \\langle J_{ab}M_{ab}j_cm_c|JM\\rangle \\\\\n& & \\times \\langle j_bm_bj_cm_c|J_{bc}M_{bc}\\rangle \\langle j_am_aJ_{bc}M_{bc}|JM\\rangle . \\nonumber\n\\end{eqnarray}\n$$\n\nWe use then the latter equation to define the so-called $6j$-symbols\n\n$$\n\\begin{eqnarray}\n\\nonumber\n\\lefteqn{ \\langle (j_a\\rightarrow [j_b\\rightarrow j_c]J_{bc}) J'M'| ([j_a\\rightarrow j_b]J_{ab}\\rightarrow j_c) JM\\rangle } \\\\ \\nonumber\n&= & \\delta_{JJ'}\\delta_{MM'}\\sum_{m_am_bm_c}\\langle j_am_aj_bm_b|J_{ab}M_{ab}\\rangle \\langle J_{ab}M_{ab}j_cm_c|JM\\rangle \\\\ \\nonumber\n& &  \\times \\langle j_bm_bj_cm_c|J_{bc}M_{bc}\\rangle \\langle j_am_aJ_{bc}M_{bc}|JM\\rangle  \\\\ \\nonumber\n&= & (-1)^{j_a+j_b+j_c+J}\\sqrt{(2J_{ab}+1)(2J_{bc}+1)}\\left\\{\\begin{array}{ccc} j_a & j_b& J_{ab} \\\\ j_c & J & J_{bc} \\end{array}\\right\\}\n, \\nonumber\n\\end{eqnarray}\n$$\n\nwhere the symbol in curly brackets $\\{\\}$ is the $6j$ symbol. \nA specific coupling order has to be respected in the symbol, that is, the so-called triangular relations between three angular momenta needs to be respected, that is\n\n$$\n\\left\\{\\begin{array}{ccc} x & x& x \\\\  &  &  \\end{array}\\right\\}\\hspace{0.1cm}\\left\\{\\begin{array}{ccc}  & & x \\\\  x& x &  \\end{array}\\right\\}\\hspace{0.1cm}\\left\\{\\begin{array}{ccc}  & x&  \\\\ x &  &x  \\end{array}\\right\\}\\hspace{0.1cm}\\left\\{\\begin{array}{ccc} x & &  \\\\  & x &x  \\end{array}\\right\\}\\hspace{0.1cm}\n$$\n\nThe $6j$ symbol is invariant under the permutation of any two columns\n\n$$\n\\begin{Bmatrix} j_1 & j_2 & j_3\\\\ j_4 & j_5 & j_6 \\end{Bmatrix} = \\begin{Bmatrix} j_2 & j_1 & j_3\\\\ j_5 & j_4 & j_6 \\end{Bmatrix} = \\begin{Bmatrix} j_1 & j_3 & j_2\\\\ j_4 & j_6 & j_5 \\end{Bmatrix} = \\begin{Bmatrix} j_3 & j_2 & j_1\\\\ j_6 & j_5 & j_4 \\end{Bmatrix}.\n$$\n\nThe $6j$ symbol is also invariant if upper and lower arguments are interchanged in any two columns\n\n$$\n\\begin{Bmatrix} j_1 & j_2 & j_3\\\\ j_4 & j_5 & j_6 \\end{Bmatrix} = \\begin{Bmatrix} j_4 & j_5 & j_3\\\\ j_1 & j_2 & j_6 \\end{Bmatrix} = \\begin{Bmatrix} j_1 & j_5 & j_6\\\\ j_4 & j_2 & j_3 \\end{Bmatrix} = \\begin{Bmatrix} j_4 & j_2 & j_6\\\\ j_1 & j_5 & j_3 \\end{Bmatrix}.\n$$\n\nThe $6j$ symbols satisfy this orthogonality relation\n\n$$\n\\sum_{j_3} (2j_3+1) \\begin{Bmatrix} j_1 & j_2 & j_3\\\\ j_4 & j_5 & j_6 \\end{Bmatrix} \\begin{Bmatrix} j_1 & j_2 & j_3\\\\ j_4 & j_5 & j_6' \\end{Bmatrix} = \\frac{\\delta_{j_6^{}j_6'}}{2j_6+1} \\{j_1,j_5,j_6\\} \\{j_4,j_2,j_6\\}.\n$$\n\nThe symbol $\\{j_1j_2j_3\\}$ (called the triangular delta) is equal to one if the triad $(j_1j_2j_3)$ satisfies the triangular conditions and zero otherwise.\nA useful value is given when say one of the angular momenta are zero, say $J_{bc}=0$, then we have\n\n$$\n\\left\\{\\begin{array}{ccc} j_a & j_b& J_{ab} \\\\ j_c & J & 0 \\end{array}\\right\\}=\\frac{(-1)^{j_a+j_b+J_{ab}}\\delta_{Jj_a}\\delta_{j_cj_b} }{\\sqrt{(2j_{a}+1)(2j_{b}+1)}}\n$$\n\nWith the $6j$ symbol defined, we can go back and and rewrite the overlap between the two ways of recoupling angular momenta in terms of the $6j$ symbol.\nThat is, we can have\n\n$$\n\\begin{eqnarray}\n\\nonumber\n\\lefteqn{| (j_a\\rightarrow [j_b\\rightarrow j_c]J_{bc}) JM\\rangle = } \\\\\n\\nonumber\n& &\\sum_{J_{ab}}(-1)^{j_a+j_b+j_c+J}\\sqrt{(2J_{ab}+1)(2J_{bc}+1)}\\left\\{\\begin{array}{ccc} j_a & j_b& J_{ab} \\\\ j_c & J & J_{bc} \\end{array}\\right\\}| ([j_a\\rightarrow j_b]J_{ab}\\rightarrow j_c) JM\\rangle\n. \\nonumber\n\\end{eqnarray}\n$$\n\nCan you find the inverse relation?  \nThese relations can in turn be used to write out the fully anti-symmetrized three-body wave function in a $J$-scheme coupled basis. \nIf you opt then for a specific coupling order, say $| ([j_a\\rightarrow j_b]J_{ab}\\rightarrow j_c) JM\\rangle$, you need to express this representation in terms of the other coupling possibilities. \n\n\n\n\n\nNote that the two-body intermediate state is assumed to be antisymmetric but\nnot normalized, that is, the state which involves the quantum numbers \n$j_a$ and $j_b$. Assume that the intermediate \ntwo-body state is antisymmetric. With this coupling order, we can \nrewrite ( in a schematic way) the general three-particle Slater determinant as\n\n$$\n\\Phi(a,b,c) = {\\cal A} | ([j_a\\rightarrow j_b]J_{ab}\\rightarrow j_c) J\\rangle,\n$$\n\nwith an implicit sum over $J_{ab}$.  The antisymmetrization operator ${\\cal A}$ is used here to indicate that we need to antisymmetrize the state. **Challenge**: Use the definition of the $6j$ symbol and find an explicit \nexpression for the above three-body state using the coupling order $| ([j_a\\rightarrow j_b]J_{ab}\\rightarrow j_c) J\\rangle$.\n\n\n\n\n\n\nWe can also coupled together four angular momenta. Consider two four-body states, with single-particle angular momenta $j_a$, $j_b$, $j_c$ and $j_d$ we can have a state with final $J$\n\n$$\n|\\Phi(a,b,c,d)\\rangle_1 = | ([j_a\\rightarrow j_b]J_{ab}\\times [j_c\\rightarrow j_d]J_{cd}) JM\\rangle,\n$$\n\nwhere we read the coupling order as $j_a$ couples with $j_b$ to given and intermediate angular momentum $J_{ab}$. \nMoreover, $j_c$ couples with $j_d$ to given and intermediate angular momentum $J_{cd}$.  The two intermediate angular momenta $J_{ab}$ and $J_{cd}$\nare in turn coupled to a final $J$.  These operations involved three Clebsch-Gordan coefficients. \n\nAlternatively, we could couple in the following order\n\n$$\n|\\Phi(a,b,c,d)\\rangle_2 = | ([j_a\\rightarrow j_c]J_{ac}\\times [j_b\\rightarrow j_d]J_{bd}) JM\\rangle,\n$$\n\nThe overlap between these two states\n\n$$\n\\langle([j_a\\rightarrow j_c]J_{ac}\\times [j_b\\rightarrow j_d]J_{bd}) JM| ([j_a\\rightarrow j_b]J_{ab}\\times [j_c\\rightarrow j_d]J_{cd}) JM\\rangle,\n$$\n\nis equal to\n\n$$\n\\begin{eqnarray}\n\\nonumber\n& & \\sum_{m_iM_{ij}}\\langle j_am_aj_bm_b|J_{ab}M_{ab}\\rangle \\langle j_cm_cj_dm_d|J_{cd}M_{cd}\\rangle \\langle J_{ab}M_{ab}J_{cd}M_{cd}|JM\\rangle \\\\\n& & \\times\\langle j_am_aj_cm_c|J_{ac}M_{ac}\\rangle \\langle j_bm_bj_dm_d|J_{cd}M_{bd}\\rangle \\langle J_{ac}M_{ac}J_{bd}M_{bd}|JM\\rangle \\\\  \\nonumber\n&= & \\sqrt{(2J_{ab}+1)(2J_{cd}+1)(2J_{ac}+1)(2J_{bd}+1)}\\left\\{\\begin{array}{ccc} j_a & j_b& J_{ab} \\\\ j_c & j_d& J_{cd} \\\\J_{ac} & J_{bd}& J\\end{array}\\right\\}\n, \\nonumber\n\\end{eqnarray}\n$$\n\nwith the symbol in curly brackets $\\{\\}$ being the $9j$-symbol. We see  that a $6j$ symbol  involves four Clebsch-Gordan coefficients, while the $9j$ symbol\ninvolves six.\n\n\n\n\nA $9j$ symbol is invariant under reflection in either diagonal\n\n$$\n\\begin{Bmatrix} j_1 & j_2 & j_3\\\\ j_4 & j_5 & j_6\\\\ j_7 & j_8 & j_9 \\end{Bmatrix} = \\begin{Bmatrix} j_1 & j_4 & j_7\\\\ j_2 & j_5 & j_8\\\\ j_3 & j_6 & j_9 \\end{Bmatrix} = \\begin{Bmatrix} j_9 & j_6 & j_3\\\\ j_8 & j_5 & j_2\\\\ j_7 & j_4 & j_1 \\end{Bmatrix}.\n$$\n\nThe permutation of any two rows or any two columns yields a phase factor $(-1)^S$, where\n\n$$\nS=\\sum_{i=1}^9 j_i.\n$$\n\nAs an  example we have\n\n$$\n\\begin{Bmatrix} j_1 & j_2 & j_3\\\\ j_4 & j_5 & j_6\\\\ j_7 & j_8 & j_9 \\end{Bmatrix} = (-1)^S \\begin{Bmatrix} j_4 & j_5 & j_6\\\\ j_1 & j_2 & j_3\\\\ j_7 & j_8 & j_9 \\end{Bmatrix} = (-1)^S \\begin{Bmatrix} j_2 & j_1 & j_3\\\\ j_5 & j_4 & j_6\\\\ j_8 & j_7 & j_9 \\end{Bmatrix}.\n$$\n\nA useful case is when say $J=0$ in\n\n$$\n\\left\\{\\begin{array}{ccc} j_a & j_b& J_{ab} \\\\ j_c & j_d & J_{cd} \\\\ J_{ac} & J_{bd}& 0\\end{array}\\right\\}=\\frac{\\delta_{J_{ab}J_{cd}} \\delta_{J_{ac}J_{bd}}}{\\sqrt{(2J_{ab}+1)(2J_{ac}+1)}} (-1)^{j_b+J_{ab}+j_c+J_{ac}} \\begin{Bmatrix} j_a & j_b & J_{ab}\\\\ j_d & j_c & J_{ac} \\end{Bmatrix}.\n$$\n\nThe tensor operator in the nucleon-nucleon potential\nis given by\n\n$$\n\\begin{array}{ll}\n&\\\\\n\\langle lSJ\\vert S_{12}\\vert l'S'J\\rangle =&\n(-)^{S+J}\\sqrt{30(2l+1)(2l'+1)(2S+1)(2S'+1)}\\\\\n&\\times\\left\\{\\begin{array}{ccc}J&S'&l'\\\\2&l&S\\end{array}\\right\\}\n\\left(\\begin{array}{ccc}l'&2&l\\\\0&0&0\\end{array}\\right)\n\\left\\{\\begin{array}{ccc}s_{1}&s_{2}&S\\\\s_{3}&s_{4}&S'\\\\\n1&1&2\\end{array}\n\\right\\}\\\\\n&\\times\\langle s_{1}\\vert\\vert \\sigma_{1}\\vert\\vert s_{3}\\rangle\n\\langle s_{2}\\vert\\vert \\sigma_{2}\\vert \\vert s_{4}\\rangle,\n\\end{array}\n$$\n\nand it is zero for the $^1S_0$ wave. \n\nHow do we get here?\n\n\nTo derive the expectation value of the nuclear tensor force, we recall that \nthe product of two irreducible tensor operators is\n\n$$\nW^{r}_{m_r}=\\sum_{m_pm_q}\\langle pm_pqm_q|rm_r\\rangle T^{p}_{m_p}U^{q}_{m_q},\n$$\n\nand using the orthogonality properties of the Clebsch-Gordan coefficients we can rewrite the above as\n\n$$\nT^{p}_{m_p}U^{q}_{m_q}=\\sum_{m_pm_q}\\langle pm_pqm_q|rm_r\\rangle W^{r}_{m_r}.\n$$\n\nAssume now that the operators $T$ and $U$ act on different parts of say a wave function. The operator $T$ could act on the spatial part only while the operator $U$ acts only on the spin part. This means also that these operators commute.\nThe reduced matrix element of this operator is thus, using the Wigner-Eckart theorem,\n\n8\n8\n3\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\times\\langle (j_aj_bJM|\\left[ T^{p}_{m_p}U^{q}_{m_q} \\right]^{r}_{m_r}|(j_cj_d)J'M'\\rangle.\n$$\n\nStarting with\n\n8\n8\n5\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\times\\langle (j_aj_bJM|\\left[ T^{p}_{m_p}U^{q}_{m_q} \\right]^{r}_{m_r}|(j_cj_d)J'M'\\rangle,\n$$\n\nwe assume now that $T$ acts only on $j_a$ and $j_c$ and that $U$ acts only on $j_b$ and $j_d$. \nThe matrix element $\\langle (j_aj_bJM|\\left[ T^{p}_{m_p}U^{q}_{m_q} \\right]^{r}_{m_r}|(j_cj_d)J'M'\\rangle$ can be written out,\nwhen we insert a complete set of states $|j_im_ij_jm_j\\rangle\\langle j_im_ij_jm_j|$ between $T$ and $U$ as\n\n8\n8\n7\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\times \\langle (j_am_aj_bm_b|\\left[ T^{p}_{m_p}\\right]^{r}_{m_r}|(j_cm_cj_bm_b)\\rangle\\langle (j_cm_cj_bm_b|\\left[ U^{q}_{m_q}\\right]^{r}_{m_r}|(j_cm_cj_dm_d)\\rangle.\n$$\n\nThe complete set of states that was inserted between $T$ and $U$ reduces to $|j_cm_cj_bm_b\\rangle\\langle j_cm_cj_bm_b|$\ndue to orthogonality of the states. \n\n\n\n\nCombining the last two equations from the previous slide and \nand applying the Wigner-Eckart theorem, we arrive at (rearranging phase factors)\n\n8\n8\n9\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n8\n9\n0\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\times\\left(\\begin{array}{ccc} j_a  &j_c  &p  \\\\ m_a &-m_c &-m_p \\end{array}\\right)\\left(\\begin{array}{ccc} j_b  &j_d  &q  \\\\ m_b &-m_d &-m_q \\end{array}\\right)\\langle j_a||T^p||j_c\\rangle \\times \\langle j_b||U^q||j_d\\rangle\n$$\n\nwhich can be rewritten in terms of a $9j$ symbol as\n\n$$\n\\langle (j_aj_b)J||W^{r}||(j_cj_d)J'\\rangle=\\sqrt{(2J+1)(2r+1)(2J'+1)}\\langle j_a||T^p||j_c\\rangle  \\langle j_b||U^q||j_d\\rangle\\left\\{\\begin{array}{ccc} j_a & j_b& J \\\\ j_c & j_d & J' \\\\ p & q& r\\end{array}\\right\\}.\n$$\n\nFrom this expression we can in turn compute for example the spin-spin operator of the tensor force.\n\n\nIn case $r=0$, that is we two tensor operators coupled to a scalar, we can use (with $p=q$)\n\n$$\n\\left\\{\\begin{array}{ccc} j_a & j_b& J \\\\ j_c & j_d & J' \\\\ p &p & 0\\end{array}\\right\\}=\\frac{\\delta_{JJ'} \\delta_{pq}}{\\sqrt{(2J+1)(2J+1)}} (-1)^{j_b+j_c+2J} \\begin{Bmatrix} j_a & j_b & J\\\\ j_d & j_c & p \\end{Bmatrix},\n$$\n\nand obtain\n\n$$\n\\langle (j_aj_b)J||W^{0}||(j_cj_d)J'\\rangle=(-1)^{j_b+j_c+2J}\\langle j_a||T^p||j_c\\rangle\\langle j_b||U^p||j_d\\rangle \\begin{Bmatrix} j_a & j_b & J\\\\ j_d & j_c & p \\end{Bmatrix}.\n$$\n\nAnother very useful expression is the case where the operators act in just one space. We state here without \nshowing that the reduced matrix element\n\n8\n9\n5\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\times \\langle j_a||T^p||j_c\\rangle \\langle j_c||T^q||j_b\\rangle.\n$$\n\nThe tensor operator in \nthe nucleon-nucleon potential can be written as\n\n$$\nV=\\frac{3}{r^{2}}\\left[ \\left[ {\\bf \\sigma}_1 \\otimes {\\bf \\sigma}_2\\right]^\n{(2)} \\otimes\\left[{\\bf r} \\otimes {\\bf r} \\right]^{(2)}\\right]^{(0)}_0\n$$\n\nSince the irreducible tensor  \n$\\left[{\\bf r} \\otimes {\\bf r} \\right]^{(2)}$\noperates  only on the angular quantum numbers and\n$\\left[{\\bf \\sigma}_1 \\otimes {\\bf \\sigma}_2\\right]^{(2)}$ \noperates  only on \nthe spin states we can write the matrix element\n\n$$\n\\begin{eqnarray*}\n\\langle lSJ\\vert V\\vert lSJ\\rangle & = &\n\\langle lSJ \\vert\\left[ \\left[{\\bf \\sigma}_1 \\otimes {\\bf \\sigma}_2\\right]^{(2)} \\otimes\n\\left[{\\bf r} \\otimes {\\bf r} \\right]^{(2)}\\right]^{(0)}_0\\vert l'S'J\\rangle \\\\\n&  = &\n(-1)^{J+l+S}\n\\left\\{\\begin{array}{ccc} l&S&J \\\\ l'&S'&2\\end{array}\\right\\}\n\\langle l \\vert\\vert\\left[{\\bf r} \\otimes {\\bf r} \\right]^{(2)} \\vert \\vert l'\\rangle\\\\\n& &\n\\times \\langle S\\vert\\vert\\left[{\\bf \\sigma}_1 \\otimes {\\bf \\sigma}_2\\right]^{(2)} \\vert\\vert S'\\rangle\n\\end{eqnarray*}\n$$\n\nWe need that\nthe coordinate vector ${\\bf r}$ can be written in terms of spherical \ncomponents as\n\n$$\n{\\bf r}_\\alpha = r\\sqrt{\\frac{4\\pi}{3}} Y_{1\\alpha}\n$$\n\nUsing this expression we get\n\n$$\n\\begin{eqnarray*}\n\\left[{\\bf r} \\otimes {\\bf r} \\right]^{(2)}_\\mu &=& \\frac{4\\pi}{3}r^2\n\\sum_{\\alpha ,\\beta}\\langle 1\\alpha 1\\beta\\vert 2\\mu \\rangle Y_{1\\alpha} Y_{1\\beta}\n\\end{eqnarray*}\n$$\n\nThe product of two spherical harmonics can be written\nas\n\n9\n0\n1\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\times \\left(\\begin{array}{ccc} l_1&l_2&l \\\\ 0  &0  &0\\end{array}\\right)\nY_{l-m}(-1)^m.\n$$\n\nUsing this relation we get\n\n$$\n\\begin{eqnarray*}\n\\left[{\\bf r} \\otimes {\\bf r} \\right]^{(2)}_\\mu &=& \n\\sqrt{4\\pi}r^2\n\\sum_{lm}\n\\sum_{\\alpha ,\\beta}   \\langle 1\\alpha 1\\beta\\vert 2\\mu \\rangle \\\\\n&&\\times \\langle 1\\alpha 1\\beta\\vert l-m \\rangle\n\\frac{(-1)^{1-1-m}}{\\sqrt{2l+1}} \n\\left(\\begin{array}{ccc} 1&1&l \\\\ 0  &0  &0\\end{array}\\right)Y_{l-m}(-1)^m\\\\\n&=& \\sqrt{4\\pi}r^2\n\\left(\\begin{array}{ccc} 1&1&2 \\\\ 0  &0  &0\\end{array}\\right)\nY_{2-\\mu}\\\\\n&=& \\sqrt{4\\pi}r^2 \\sqrt{\\frac{2}{15}}Y_{2-\\mu}\n\\end{eqnarray*}\n$$\n\nWe can then  use this relation to rewrite the reduced matrix element containing the \nposition vector as\n\n$$\n\\begin{eqnarray*}\n\\langle l \\vert\\vert\\left[{\\bf r} \\otimes {\\bf r} \\right]^{(2)} \\vert \\vert l'\\rangle\n& = & \n\\sqrt{4\\pi}\\sqrt{ \\frac{2}{15}}r^2 \\langle l \\vert\\vert Y_2 \\vert \\vert l'\\rangle \\\\\n& = &\\sqrt{4\\pi}\\sqrt{ \\frac{2}{15}}  r^2 (-1)^l\n\\sqrt{\\frac{(2l+1)5(2l'+1)}{4\\pi}}\n\\left(\\begin{array}{ccc} l&2&l' \\\\ 0&0&0\\end{array}\\right)\n\\end{eqnarray*}\n$$\n\nUsing the  reduced matrix element of the spin \noperators defined as\n\n$$\n\\begin{eqnarray*}\n\\langle S\\vert \\vert\\left[{\\bf \\sigma}_1 \\otimes {\\bf \\sigma}_2\\right]^{(2)} \\vert \\vert S' \\rangle\n& = & \n\\sqrt{(2S+1)(2S'+1)5}\n\\left\\{\\begin{array}{ccc} s_1&s_2&S \\\\s_3&s_4&S' \\\\ 1&1&2\\end{array}\\right\\}\\\\\n&\\times& \n\\langle s_1 \\vert \\vert {\\bf \\sigma}_1 \\vert \\vert s_3\\rangle\n\\langle s_2 \\vert\\vert {\\bf \\sigma}_2 \\vert \\vert s_4\\rangle\n\\end{eqnarray*}\n$$\n\nand inserting  these expressions for the two reduced matrix elements we get\n\n$$\n\\begin{array}{ll}\n&\\\\\n\\langle lSJ\\vert V\\vert l'S'J\\rangle =&(-1)^{S+J}\\sqrt{30(2l+1)(2l'+1)(2S+1)(2S'+1)}\\\\\n&\\times\\left\\{\\begin{array}{ccc}l&S &J \\\\l'&S&2\\end{array}\\right\\}\n\\left(\\begin{array}{ccc}l&2&l'\\\\0&0&0\\end{array}\\right)\n\\left\\{\\begin{array}{ccc}s_{1}&s_{2}&S\\\\s_{3}&s_{4}&S'\\\\\n1&1&2\\end{array}\n\\right\\}\\\\\n&\\times\\langle s_{1}\\vert\\vert \\sigma_{1}\\vert\\vert s_{3}\\rangle\n\\langle s_{2}\\vert\\vert \\sigma_{2}\\vert \\vert s_{4}\\rangle.\n\\end{array}\n$$\n\nNormally, we start we a nucleon-nucleon interaction fitted to reproduce scattering data.\nIt is common then to represent this interaction in terms relative momenta $k$, the center-of-mass momentum $K$\nand various partial wave quantum numbers like the spin $S$, the total relative angular  momentum ${\\cal J}$, isospin $T$ and relative orbital momentum $l$ and finally the corresponding center-of-mass $L$.  \nWe can then write the  free interaction matrix $V$ as\n\n$$\n\\langle kKlL{\\cal J}ST\\vert\\hat{V}\\vert k'Kl'L{\\cal J}S'T\\rangle.\n$$\n\nTransformations from the relative and center-of-mass motion\nsystem to the lab system will be discussed\nbelow.\n\n\n\n\nTo obtain a $V$-matrix in a h.o. basis, we need  \nthe transformation\n\n$$\n\\langle nNlL{\\cal J}ST\\vert\\hat{V}\\vert n'N'l'L'{\\cal J}S'T\\rangle,\n$$\n\nwith $n$ and $N$ the principal quantum numbers of the relative and\ncenter-of-mass motion, respectively.\n\n$$\n\\vert nlNL{\\cal J}ST\\rangle= \\int k^{2}K^{2}dkdKR_{nl}(\\sqrt{2}\\alpha k)\nR_{NL}(\\sqrt{1/2}\\alpha K)\n\\vert klKL{\\cal J}ST\\rangle.\n$$\n\nThe parameter $\\alpha$ is the chosen oscillator length.\n\n\n\nThe most commonly employed sp basis is the harmonic oscillator, which\nin turn means that\na two-particle wave function with total angular momentum $J$\nand isospin $T$\ncan be expressed as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:hoho\"></div>\n\n$$\n\\begin{array}{ll}\n\\vert (n_{a}l_{a}j_{a})(n_{b}l_{b}j_{b})JT\\rangle =&\n{\\displaystyle\n\\frac{1}{\\sqrt{(1+\\delta_{12})}}\n\\sum_{\\lambda S{\\cal J}}\\sum_{nNlL}}\nF\\times \\langle ab|\\lambda SJ \\rangle\\\\\n&\\times (-1)^{\\lambda +{\\cal J}-L-S}\\hat{\\lambda}\n\\left\\{\\begin{array}{ccc}L&l&\\lambda\\\\S&J&{\\cal J}\n\\end{array}\\right\\}\\\\\n&\\times \\left\\langle nlNL| n_al_an_bl_b\\right\\rangle\n\\vert nlNL{\\cal J}ST\\rangle ,\\end{array}\n\\label{eq:hoho} \\tag{132}\n$$\n\nwhere the term\n$\\left\\langle nlNL| n_al_an_bl_b\\right\\rangle$\nis the so-called Moshinsky-Talmi transformation coefficient (see chapter 18 of Alex Brown's notes).\n\n\n\nThe term $\\langle ab|LSJ \\rangle $ is a shorthand\nfor the $LS-jj$ transformation coefficient,\n\n$$\n\\langle ab|\\lambda SJ \\rangle = \\hat{j_{a}}\\hat{j_{b}}\n     \\hat{\\lambda}\\hat{S}\n     \\left\\{\n    \\begin{array}{ccc}\n       l_{a}&s_a&j_{a}\\\\\n       l_{b}&s_b&j_{b}\\\\\n       \\lambda    &S          &J\n    \\end{array}\n    \\right\\}.\n$$\n\nHere\nwe use $\\hat{x} = \\sqrt{2x +1}$.\nThe factor $F$ is defined as $F=\\frac{1-(-1)^{l+S+T}}{\\sqrt{2}}$ if\n$s_a = s_b$ and we .\n\n\n\nThe $\\hat{V}$-matrix in terms of harmonic oscillator wave functions reads\n\n9\n1\n2\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n9\n1\n3\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n9\n1\n4\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\times\\langle nNlL{\\cal J}ST\\vert\\hat{V}\\vert n'N'l'L'{\\cal J}S'T\\rangle.\n$$\n\nThe label $a$ represents here all the single particle quantum numbers  \n$n_{a}l_{a}j_{a}$.\n\n\n\n# Many-body perturbation theory\n<div id=\"ch:mbpt\"></div>\n\n## Many-body perturbation theory\n\nWe assume here that we are only interested in the ground state of the system and \nexpand the exact wave function in term of a series of Slater determinants\n\n$$\n\\vert \\Psi_0\\rangle = \\vert \\Phi_0\\rangle + \\sum_{m=1}^{\\infty}C_m\\vert \\Phi_m\\rangle,\n$$\n\nwhere we have assumed that the true ground state is dominated by the \nsolution of the unperturbed problem, that is\n\n$$\n\\hat{H}_0\\vert \\Phi_0\\rangle= W_0\\vert \\Phi_0\\rangle.\n$$\n\nThe state $\\vert \\Psi_0\\rangle$ is not normalized, rather we have used an intermediate \nnormalization $\\langle \\Phi_0 \\vert \\Psi_0\\rangle=1$ since we have $\\langle \\Phi_0\\vert \\Phi_0\\rangle=1$. \n\n\n\nThe Schroedinger equation is\n\n$$\n\\hat{H}\\vert \\Psi_0\\rangle = E\\vert \\Psi_0\\rangle,\n$$\n\nand multiplying the latter from the left with $\\langle \\Phi_0\\vert $ gives\n\n$$\n\\langle \\Phi_0\\vert \\hat{H}\\vert \\Psi_0\\rangle = E\\langle \\Phi_0\\vert \\Psi_0\\rangle=E,\n$$\n\nand subtracting from this equation\n\n$$\n\\langle \\Psi_0\\vert \\hat{H}_0\\vert \\Phi_0\\rangle= W_0\\langle \\Psi_0\\vert \\Phi_0\\rangle=W_0,\n$$\n\nand using the fact that the both operators $\\hat{H}$ and $\\hat{H}_0$ are hermitian \nresults in\n\n$$\n\\Delta E=E-W_0=\\langle \\Phi_0\\vert \\hat{H}_I\\vert \\Psi_0\\rangle,\n$$\n\nwhich is an exact result. We call this quantity the correlation energy.\n\n\n\nThis equation forms the starting point for all perturbative derivations. However,\nas it stands it represents nothing but a mere formal rewriting of Schroedinger's equation and is not of much practical use. The exact wave function $\\vert \\Psi_0\\rangle$ is unknown. In order to obtain a perturbative expansion, we need to expand the exact wave function in terms of the interaction $\\hat{H}_I$. \n\nHere we have assumed that our model space defined by the operator $\\hat{P}$ is one-dimensional, meaning that\n\n$$\n\\hat{P}= \\vert \\Phi_0\\rangle \\langle \\Phi_0\\vert ,\n$$\n\nand\n\n$$\n\\hat{Q}=\\sum_{m=1}^{\\infty}\\vert \\Phi_m\\rangle \\langle \\Phi_m\\vert .\n$$\n\nWe can thus rewrite the exact wave function as\n\n$$\n\\vert \\Psi_0\\rangle= (\\hat{P}+\\hat{Q})\\vert \\Psi_0\\rangle=\\vert \\Phi_0\\rangle+\\hat{Q}\\vert \\Psi_0\\rangle.\n$$\n\nGoing back to the Schr\\\"odinger equation, we can rewrite it as, adding and a subtracting a term $\\omega \\vert \\Psi_0\\rangle$ as\n\n$$\n\\left(\\omega-\\hat{H}_0\\right)\\vert \\Psi_0\\rangle=\\left(\\omega-E+\\hat{H}_I\\right)\\vert \\Psi_0\\rangle,\n$$\n\nwhere $\\omega$ is an energy variable to be specified later. \n\n\nWe assume also that the resolvent of $\\left(\\omega-\\hat{H}_0\\right)$ exits, that is\nit has an inverse which defined the unperturbed Green's function as\n\n$$\n\\left(\\omega-\\hat{H}_0\\right)^{-1}=\\frac{1}{\\left(\\omega-\\hat{H}_0\\right)}.\n$$\n\nWe can rewrite Schroedinger's equation as\n\n$$\n\\vert \\Psi_0\\rangle=\\frac{1}{\\omega-\\hat{H}_0}\\left(\\omega-E+\\hat{H}_I\\right)\\vert \\Psi_0\\rangle,\n$$\n\nand multiplying from the left with $\\hat{Q}$ results in\n\n$$\n\\hat{Q}\\vert \\Psi_0\\rangle=\\frac{\\hat{Q}}{\\omega-\\hat{H}_0}\\left(\\omega-E+\\hat{H}_I\\right)\\vert \\Psi_0\\rangle,\n$$\n\nwhich is possible since we have defined the operator $\\hat{Q}$ in terms of the eigenfunctions of $\\hat{H}$.\n\n\n\n\nThese operators commute meaning that\n\n$$\n\\hat{Q}\\frac{1}{\\left(\\omega-\\hat{H}_0\\right)}\\hat{Q}=\\hat{Q}\\frac{1}{\\left(\\omega-\\hat{H}_0\\right)}=\\frac{\\hat{Q}}{\\left(\\omega-\\hat{H}_0\\right)}.\n$$\n\nWith these definitions we can in turn define the wave function as\n\n$$\n\\vert \\Psi_0\\rangle=\\vert \\Phi_0\\rangle+\\frac{\\hat{Q}}{\\omega-\\hat{H}_0}\\left(\\omega-E+\\hat{H}_I\\right)\\vert \\Psi_0\\rangle.\n$$\n\nThis equation is again nothing but a formal rewrite of Schr\\\"odinger's equation\nand does not represent a practical calculational scheme.  \nIt is a non-linear equation in two unknown quantities, the energy $E$ and the exact\nwave function $\\vert \\Psi_0\\rangle$. We can however start with a guess for $\\vert \\Psi_0\\rangle$ on the right hand side of the last equation.\n\n\n\n The most common choice is to start with the function which is expected to exhibit the largest overlap with the wave function we are searching after, namely $\\vert \\Phi_0\\rangle$. This can again be inserted in the solution for $\\vert \\Psi_0\\rangle$ in an iterative fashion and if we continue along these lines we end up with\n\n$$\n\\vert \\Psi_0\\rangle=\\sum_{i=0}^{\\infty}\\left\\{\\frac{\\hat{Q}}{\\omega-\\hat{H}_0}\\left(\\omega-E+\\hat{H}_I\\right)\\right\\}^i\\vert \\Phi_0\\rangle,\n$$\n\nfor the wave function and\n\n$$\n\\Delta E=\\sum_{i=0}^{\\infty}\\langle \\Phi_0\\vert \\hat{H}_I\\left\\{\\frac{\\hat{Q}}{\\omega-\\hat{H}_0}\\left(\\omega-E+\\hat{H}_I\\right)\\right\\}^i\\vert \\Phi_0\\rangle,\n$$\n\nwhich is now  a perturbative expansion of the exact energy in terms of the interaction\n$\\hat{H}_I$ and the unperturbed wave function $\\vert \\Psi_0\\rangle$.\n\n\n\nIn our equations for $\\vert \\Psi_0\\rangle$ and $\\Delta E$ in terms of the unperturbed\nsolutions $\\vert \\Phi_i\\rangle$  we have still an undetermined parameter $\\omega$\nand a dependecy on the exact energy $E$. Not much has been gained thus from a practical computational point of view. \n\nIn Brilluoin-Wigner perturbation theory it is customary to set $\\omega=E$. This results in the following perturbative expansion for the energy $\\Delta E$\n\n9\n3\n3\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\langle \\Phi_0\\vert \\left(\\hat{H}_I+\\hat{H}_I\\frac{\\hat{Q}}{E-\\hat{H}_0}\\hat{H}_I+\n\\hat{H}_I\\frac{\\hat{Q}}{E-\\hat{H}_0}\\hat{H}_I\\frac{\\hat{Q}}{E-\\hat{H}_0}\\hat{H}_I+\\dots\\right)\\vert \\Phi_0\\rangle.\n$$\n\n9\n3\n5\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\langle \\Phi_0\\vert \\left(\\hat{H}_I+\\hat{H}_I\\frac{\\hat{Q}}{E-\\hat{H}_0}\\hat{H}_I+\n\\hat{H}_I\\frac{\\hat{Q}}{E-\\hat{H}_0}\\hat{H}_I\\frac{\\hat{Q}}{E-\\hat{H}_0}\\hat{H}_I+\\dots\\right)\\vert \\Phi_0\\rangle.\n$$\n\nThis expression depends however on the exact energy $E$ and is again not very convenient from a practical point of view. It can obviously be solved iteratively, by starting with a guess for  $E$ and then solve till some kind of self-consistency criterion has been reached. \n\nActually, the above expression is nothing but a rewrite again of the full Schr\\\"odinger equation. \n\nDefining $e=E-\\hat{H}_0$ and recalling that $\\hat{H}_0$ commutes with \n$\\hat{Q}$ by construction and that $\\hat{Q}$ is an idempotent operator\n$\\hat{Q}^2=\\hat{Q}$. \nUsing this equation in the above expansion for $\\Delta E$ we can write the denominator\n\n9\n3\n7\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\hat{Q}\\left[\\frac{1}{\\hat{e}}+\\frac{1}{\\hat{e}}\\hat{Q}\\hat{H}_I\\hat{Q}\n\\frac{1}{\\hat{e}}+\\frac{1}{\\hat{e}}\\hat{Q}\\hat{H}_I\\hat{Q}\n\\frac{1}{\\hat{e}}\\hat{Q}\\hat{H}_I\\hat{Q}\\frac{1}{\\hat{e}}+\\dots\\right]\\hat{Q}.\n$$\n\nInserted in the expression for $\\Delta E$ leads to\n\n$$\n\\Delta E=\n\\langle \\Phi_0\\vert \\hat{H}_I+\\hat{H}_I\\hat{Q}\\frac{1}{E-\\hat{H}_0-\\hat{Q}\\hat{H}_I\\hat{Q}}\\hat{Q}\\hat{H}_I\\vert \\Phi_0\\rangle.\n$$\n\nIn RS perturbation theory we set $\\omega = W_0$ and obtain the following expression for the energy difference\n\n9\n4\n0\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\langle \\Phi_0\\vert \\left(\\hat{H}_I+\\hat{H}_I\\frac{\\hat{Q}}{W_0-\\hat{H}_0}(\\hat{H}_I-\\Delta E)+\n\\hat{H}_I\\frac{\\hat{Q}}{W_0-\\hat{H}_0}(\\hat{H}_I-\\Delta E)\\frac{\\hat{Q}}{W_0-\\hat{H}_0}(\\hat{H}_I-\\Delta E)+\\dots\\right)\\vert \\Phi_0\\rangle.\n$$\n\nRecalling that $\\hat{Q}$ commutes with $\\hat{H_0}$ and since $\\Delta E$ is a constant we obtain that\n\n$$\n\\hat{Q}\\Delta E\\vert \\Phi_0\\rangle = \\hat{Q}\\Delta E\\vert \\hat{Q}\\Phi_0\\rangle = 0.\n$$\n\nInserting this results in the expression for the energy results in\n\n$$\n\\Delta E=\\langle \\Phi_0\\vert \\left(\\hat{H}_I+\\hat{H}_I\\frac{\\hat{Q}}{W_0-\\hat{H}_0}\\hat{H}_I+\n\\hat{H}_I\\frac{\\hat{Q}}{W_0-\\hat{H}_0}(\\hat{H}_I-\\Delta E)\\frac{\\hat{Q}}{W_0-\\hat{H}_0}\\hat{H}_I+\\dots\\right)\\vert \\Phi_0\\rangle.\n$$\n\nWe can now this expression in terms of a perturbative expression in terms\nof $\\hat{H}_I$ where we iterate the last expression in terms of $\\Delta E$\n\n$$\n\\Delta E=\\sum_{i=1}^{\\infty}\\Delta E^{(i)}.\n$$\n\nWe get the following expression for $\\Delta E^{(i)}$\n\n$$\n\\Delta E^{(1)}=\\langle \\Phi_0\\vert \\hat{H}_I\\vert \\Phi_0\\rangle,\n$$\n\nwhich is just the contribution to first order in perturbation theory,\n\n$$\n\\Delta E^{(2)}=\\langle\\Phi_0\\vert \\hat{H}_I\\frac{\\hat{Q}}{W_0-\\hat{H}_0}\\hat{H}_I\\vert \\Phi_0\\rangle,\n$$\n\nwhich is the contribution to second order.\n\n$$\n\\Delta E^{(3)}=\\langle \\Phi_0\\vert \\hat{H}_I\\frac{\\hat{Q}}{W_0-\\hat{H}_0}\\hat{H}_I\\frac{\\hat{Q}}{W_0-\\hat{H}_0}\\hat{H}_I\\Phi_0\\rangle-\n\\langle\\Phi_0\\vert \\hat{H}_I\\frac{\\hat{Q}}{W_0-\\hat{H}_0}\\langle \\Phi_0\\vert \\hat{H}_I\\vert \\Phi_0\\rangle\\frac{\\hat{Q}}{W_0-\\hat{H}_0}\\hat{H}_I\\vert \\Phi_0\\rangle,\n$$\n\nbeing the third-order contribution. \n\n\n\nLet us analyse a given contribution to first first order in perturbation, that is, the contribution includes (more material to come)\n\n\n\n\n# Coupled cluster theory\n<div id=\"ch:cc\"></div>\n\n\n\n\n# Infinite matter\n<div id=\"ch:infmatter\"></div>\n\n\n## Introduction to studies of infinite matter\n\n\nStudies of infinite nuclear matter play an important role  in nuclear physics. The aim of this part of the lectures is to provide the necessary ingredients for perfoming studies of neutron star matter (or matter in $\\beta$-equilibrium) and symmetric nuclear matter. We start however with the electron gas in two and three dimensions for both historical and pedagogical reasons. Since there are several benchmark calculations for the electron gas, this small detour will allow us to establish the necessary formalism. Thereafter we will study infinite nuclear matter \n* at the Hartree-Fock with realistic nuclear forces and\n\n* using many-body methods like coupled-cluster theory or in-medium SRG as discussed in our previous sections.\n\n### The infinite electron gas\n\nThe electron gas is perhaps the only realistic model of a \nsystem of many interacting particles that allows for a solution\nof the Hartree-Fock equations on a closed form. Furthermore, to first order in the interaction, one can also\ncompute on a closed form the total energy and several other properties of a many-particle systems. \nThe model gives a very good approximation to the properties of valence electrons in metals.\nThe assumptions are\n\n * System of electrons that is not influenced by external forces except by an attraction provided by a uniform background of ions. These ions give rise to a uniform background charge. The ions are stationary.\n\n * The system as a whole is neutral.\n\n * We assume we have $N_e$ electrons in a cubic box of length $L$ and volume $\\Omega=L^3$. This volume contains also a uniform distribution of positive charge with density $N_ee/\\Omega$. \n\nThe homogeneous electron gas is one of the few examples of a system of many\ninteracting particles that allows for a solution of the mean-field\nHartree-Fock equations on a closed form.  To first order in the\nelectron-electron interaction, this applies to ground state properties\nlike the energy and its pertinent equation of state as well.  The\nhomogeneus electron gas is a system of electrons that is not\ninfluenced by external forces except by an attraction provided by a\nuniform background of ions. These ions give rise to a uniform\nbackground charge.  The ions are stationary and the system as a whole\nis neutral.\nIrrespective of this simplicity, this system, in both two and\nthree-dimensions, has eluded a proper description of correlations in\nterms of various first principle methods, except perhaps for quantum\nMonte Carlo methods. In particular, the diffusion Monte Carlo\ncalculations of [Ceperley](http://journals.aps.org/prl/abstract/10.1103/PhysRevLett.45.566) \nand [Ceperley and Tanatar](http://journals.aps.org/prb/abstract/10.1103/PhysRevB.39.5005) \nare presently still considered as the\nbest possible benchmarks for the two- and three-dimensional electron\ngas. \n\n\n\nThe electron gas, in \ntwo or three dimensions is thus interesting as a test-bed for \nelectron-electron correlations. The three-dimensional \nelectron gas is particularly important as a cornerstone \nof the local-density approximation in density-functional \ntheory. In the physical world, systems \nsimilar to the three-dimensional electron gas can be \nfound in, for example, alkali metals and doped \nsemiconductors. Two-dimensional electron fluids are \nobserved on metal and liquid-helium surfaces, as well as \nat metal-oxide-semiconductor interfaces. However, the Coulomb \ninteraction has an infinite range, and therefore \nlong-range correlations play an essential role in the\nelectron gas. \n\n\n\n\nAt low densities, the electrons become \nlocalized and form a lattice. This so-called Wigner \ncrystallization is a direct consequence \nof the long-ranged repulsive interaction. At higher\ndensities, the electron gas is better described as a\nliquid.\nWhen using, for example, Monte Carlo methods the electron gas must be approximated \nby a finite system. The long-range Coulomb interaction \nin the electron gas causes additional finite-size effects  that are not\npresent in other infinite systems like nuclear matter or neutron star matter.\nThis poses additional challenges to many-body methods when applied \nto the electron gas.\n\n\n\n\n\n### The infinite electron gas as a homogenous system\n\nThis is a homogeneous system and the one-particle wave functions are given by plane wave functions normalized to a volume $\\Omega$ \nfor a box with length $L$ (the limit $L\\rightarrow \\infty$ is to be taken after we have computed various expectation values)\n\n$$\n\\psi_{\\mathbf{k}\\sigma}(\\mathbf{r})= \\frac{1}{\\sqrt{\\Omega}}\\exp{(i\\mathbf{kr})}\\xi_{\\sigma}\n$$\n\nwhere $\\mathbf{k}$ is the wave number and  $\\xi_{\\sigma}$ is a spin function for either spin up or down\n\n$$\n\\xi_{\\sigma=+1/2}=\\left(\\begin{array}{c} 1 \\\\ 0 \\end{array}\\right) \\hspace{0.5cm}\n\\xi_{\\sigma=-1/2}=\\left(\\begin{array}{c} 0 \\\\ 1 \\end{array}\\right).\n$$\n\n### Periodic boundary conditions\n\n\nWe assume that we have periodic boundary conditions which limit the allowed wave numbers to\n\n$$\nk_i=\\frac{2\\pi n_i}{L}\\hspace{0.5cm} i=x,y,z \\hspace{0.5cm} n_i=0,\\pm 1,\\pm 2, \\dots\n$$\n\nWe assume first that the electrons interact via a central, symmetric and translationally invariant\ninteraction  $V(r_{12})$ with\n$r_{12}=|\\mathbf{r}_1-\\mathbf{r}_2|$.  The interaction is spin independent.\n\nThe total Hamiltonian consists then of kinetic and potential energy\n\n$$\n\\hat{H} = \\hat{T}+\\hat{V}.\n$$\n\nThe operator for the kinetic energy can be written as\n\n$$\n\\hat{T}=\\sum_{\\mathbf{k}\\sigma}\\frac{\\hbar^2k^2}{2m}a_{\\mathbf{k}\\sigma}^{\\dagger}a_{\\mathbf{k}\\sigma}.\n$$\n\n### Defining the Hamiltonian operator\n\nThe Hamiltonian operator is given by\n\n$$\n\\hat{H}=\\hat{H}_{el}+\\hat{H}_{b}+\\hat{H}_{el-b},\n$$\n\nwith the electronic part\n\n$$\n\\hat{H}_{el}=\\sum_{i=1}^N\\frac{p_i^2}{2m}+\\frac{e^2}{2}\\sum_{i\\ne j}\\frac{e^{-\\mu |\\mathbf{r}_i-\\mathbf{r}_j|}}{|\\mathbf{r}_i-\\mathbf{r}_j|},\n$$\n\nwhere we have introduced an explicit convergence factor\n(the limit $\\mu\\rightarrow 0$ is performed after having calculated the various integrals).\nCorrespondingly, we have\n\n$$\n\\hat{H}_{b}=\\frac{e^2}{2}\\int\\int d\\mathbf{r}d\\mathbf{r}'\\frac{n(\\mathbf{r})n(\\mathbf{r}')e^{-\\mu |\\mathbf{r}-\\mathbf{r}'|}}{|\\mathbf{r}-\\mathbf{r}'|},\n$$\n\nwhich is the energy contribution from the positive background charge with density\n$n(\\mathbf{r})=N/\\Omega$. Finally,\n\n$$\n\\hat{H}_{el-b}=-\\frac{e^2}{2}\\sum_{i=1}^N\\int d\\mathbf{r}\\frac{n(\\mathbf{r})e^{-\\mu |\\mathbf{r}-\\mathbf{x}_i|}}{|\\mathbf{r}-\\mathbf{x}_i|},\n$$\n\nis the interaction between the electrons and the positive background.\n\n\n\n### Single-particle Hartree-Fock energy\n\nIn the first exercise below we show that the Hartree-Fock energy can be written as\n\n$$\n\\varepsilon_{k}^{HF}=\\frac{\\hbar^{2}k^{2}}{2m_e}-\\frac{e^{2}}\n{\\Omega^{2}}\\sum_{k'\\leq\nk_{F}}\\int d\\mathbf{r}e^{i(\\mathbf{k}'-\\mathbf{k})\\mathbf{r}}\\int\nd\\mathbf{r'}\\frac{e^{i(\\mathbf{k}-\\mathbf{k}')\\mathbf{r}'}}\n{\\vert\\mathbf{r}-\\mathbf{r}'\\vert}\n$$\n\nresulting in\n\n$$\n\\varepsilon_{k}^{HF}=\\frac{\\hbar^{2}k^{2}}{2m_e}-\\frac{e^{2}\nk_{F}}{2\\pi}\n\\left[\n2+\\frac{k_{F}^{2}-k^{2}}{kk_{F}}ln\\left\\vert\\frac{k+k_{F}}\n{k-k_{F}}\\right\\vert\n\\right]\n$$\n\nThe previous result can be rewritten in terms of the density\n\n$$\nn= \\frac{k_F^3}{3\\pi^2}=\\frac{3}{4\\pi r_s^3},\n$$\n\nwhere $n=N_e/\\Omega$, $N_e$ being the number of electrons, and $r_s$ is the radius of a sphere which represents the volum per conducting electron.  \nIt can be convenient to use the Bohr radius $a_0=\\hbar^2/e^2m_e$.\nFor most metals we have a relation $r_s/a_0\\sim 2-6$.  The quantity $r_s$ is dimensionless.\n\n\nIn the second exercise below  we find that\nthe total energy\n$E_0/N_e=\\langle\\Phi_{0}|\\hat{H}|\\Phi_{0}\\rangle/N_e$ for\nfor this system to first order in the interaction is given as\n\n$$\nE_0/N_e=\\frac{e^2}{2a_0}\\left[\\frac{2.21}{r_s^2}-\\frac{0.916}{r_s}\\right].\n$$\n\n<!-- --- begin exercise --- -->\n\n### Exercise 25: Hartree-Fock single-particle solution for the electron gas\n\nThe electron gas model allows closed form solutions for quantities like the \nsingle-particle Hartree-Fock energy.  The latter quantity is given by the following expression\n\n$$\n\\varepsilon_{k}^{HF}=\\frac{\\hbar^{2}k^{2}}{2m}-\\frac{e^{2}}\n{V^{2}}\\sum_{k'\\leq\nk_{F}}\\int d\\mathbf{r}e^{i(\\mathbf{k'}-\\mathbf{k})\\mathbf{r}}\\int\nd\\mathbf{r}'\\frac{e^{i(\\mathbf{k}-\\mathbf{k'})\\mathbf{r}'}}\n{\\vert\\mathbf{r}-\\mathbf{r'}\\vert}\n$$\n\n**a)**\nShow first that\n\n$$\n\\varepsilon_{k}^{HF}=\\frac{\\hbar^{2}k^{2}}{2m}-\\frac{e^{2}\nk_{F}}{2\\pi}\n\\left[\n2+\\frac{k_{F}^{2}-k^{2}}{kk_{F}}ln\\left\\vert\\frac{k+k_{F}}\n{k-k_{F}}\\right\\vert\n\\right]\n$$\n\n<!-- --- begin hint in exercise --- -->\n\n**Hint.**\nHint: Introduce the convergence factor \n$e^{-\\mu\\vert\\mathbf{r}-\\mathbf{r}'\\vert}$\nin the potential and use  $\\sum_{\\mathbf{k}}\\rightarrow\n\\frac{V}{(2\\pi)^{3}}\\int d\\mathbf{k}$\n\n<!-- --- end hint in exercise --- -->\n\n**b)**\nRewrite the above result as a function of the density\n\n$$\nn= \\frac{k_F^3}{3\\pi^2}=\\frac{3}{4\\pi r_s^3},\n$$\n\nwhere $n=N/V$, $N$ being the number of particles, and $r_s$ is the radius of a sphere which represents the volum per conducting electron.\n\nIt can be convenient to use the Bohr radius $a_0=\\hbar^2/e^2m$.\nFor most metals we have a relation $r_s/a_0\\sim 2-6$.\n**c)**\nMake a plot of the free electron energy and the Hartree-Fock energy and discuss the behavior around the Fermi surface. Extract also   the Hartree-Fock band width $\\Delta\\varepsilon^{HF}$ defined as\n\n$$\n\\Delta\\varepsilon^{HF}=\\varepsilon_{k_{F}}^{HF}-\n\\varepsilon_{0}^{HF}.\n$$\n\nCompare this results with the corresponding one for a free electron and comment your results. How large is the contribution due to the exchange term in the Hartree-Fock equation?\nWe will now define a quantity called the effective mass.\nFor $\\vert\\mathbf{k}\\vert$ near $k_{F}$, we can Taylor expand the Hartree-Fock energy as\n\n$$\n\\varepsilon_{k}^{HF}=\\varepsilon_{k_{F}}^{HF}+\n\\left(\\frac{\\partial\\varepsilon_{k}^{HF}}{\\partial k}\\right)_{k_{F}}(k-k_{F})+\\dots\n$$\n\nIf we compare the latter with the corresponding expressiyon for the non-interacting system\n\n$$\n\\varepsilon_{k}^{(0)}=\\frac{\\hbar^{2}k^{2}_{F}}{2m}+\n\\frac{\\hbar^{2}k_{F}}{m}\\left(k-k_{F}\\right)+\\dots ,\n$$\n\nwe can define the so-called effective Hartree-Fock mass as\n\n$$\nm_{HF}^{*}\\equiv\\hbar^{2}k_{F}\\left(\n\\frac{\\partial\\varepsilon_{k}^{HF}}\n{\\partial k}\\right)_{k_{F}}^{-1}\n$$\n\n**d)**\nCompute $m_{HF}^{*}$ and comment your results.\n\n**e)**\nShow that the level density (the number of single-electron states per unit energy) can be written as\n\n$$\nn(\\varepsilon)=\\frac{Vk^{2}}{2\\pi^{2}}\\left(\n\\frac{\\partial\\varepsilon}{\\partial k}\\right)^{-1}\n$$\n\nCalculate $n(\\varepsilon_{F}^{HF})$ and comment the results.\n\nWe want to show that, given the Hartree-Fock equation for the electron gas\n\n$$\n\\varepsilon_{k}^{HF}=\\frac{\\hbar^{2}k^{2}}{2m}-\\frac{e^{2}}\n{V^{2}}\\sum_{p\\leq\nk_{F}}\\int d\\mathbf{r}\\exp{(i(\\mathbf{p}-\\mathbf{k})\\mathbf{r})}\\int\nd\\mathbf{r}'\\frac{\\exp{(i(\\mathbf{k}-\\mathbf{p})\\mathbf{r}'})}\n{\\vert\\mathbf{r}-\\mathbf{r'}\\vert}\n$$\n\nthe single-particle energy can be written as\n\n$$\n\\varepsilon_{k}^{HF}=\\frac{\\hbar^{2}k^{2}}{2m}-\\frac{e^{2}\nk_{F}}{2\\pi}\n\\left[\n2+\\frac{k_{F}^{2}-k^{2}}{kk_{F}}ln\\left\\vert\\frac{k+k_{F}}\n{k-k_{F}}\\right\\vert\n\\right].\n$$\n\nWe introduce the convergence factor \n$e^{-\\mu\\vert\\mathbf{r}-\\mathbf{r}'\\vert}$\nin the potential and use  $\\sum_{\\mathbf{k}}\\rightarrow\n\\frac{V}{(2\\pi)^{3}}\\int d\\mathbf{k}$. We can then rewrite the integral as\n\n$$\n\\begin{equation}\n\\frac{e^{2}}\n{V^{2}}\\sum_{k'\\leq\nk_{F}}\\int d\\mathbf{r}\\exp{(i(\\mathbf{k'}-\\mathbf{k})\\mathbf{r})}\\int\nd\\mathbf{r}'\\frac{\\exp{(i(\\mathbf{k}-\\mathbf{p})\\mathbf{r}'})}\n{\\vert\\mathbf{r}-\\mathbf{r'}\\vert}=  \n\\end{equation}\n$$\n\n$$\n\\begin{equation} \n\\frac{e^{2}}{V (2\\pi)^3}  \\int d\\mathbf{r}\\int\n\\frac{d\\mathbf{r}'}{\\vert\\mathbf{r}-\\mathbf{r'}\\vert}\\exp{(-i\\mathbf{k}(\\mathbf{r}-\\mathbf{r}'))}\\int d\\mathbf{p}\\exp{(i\\mathbf{p}(\\mathbf{r}-\\mathbf{r}'))},\n\\end{equation}\n$$\n\nand introducing the abovementioned convergence factor we have\n\n$$\n\\begin{equation}\n\\lim_{\\mu \\to 0}\\frac{e^{2}}{V (2\\pi)^3}  \\int d\\mathbf{r}\\int d\\mathbf{r}'\\frac{\\exp{(-\\mu\\vert\\mathbf{r}-\\mathbf{r}'\\vert})}{\\vert\\mathbf{r}-\\mathbf{r'}\\vert}\\int d\\mathbf{p}\\exp{(i(\\mathbf{p}-\\mathbf{k})(\\mathbf{r}-\\mathbf{r}'))}.\n\\end{equation}\n$$\n\nWith a change variables to $\\mathbf{x} = \\mathbf{r}-\\mathbf{r}'$ and $\\mathbf{y}=\\mathbf{r}'$ we rewrite the last integral as\n\n$$\n\\lim_{\\mu \\to 0}\\frac{e^{2}}{V (2\\pi)^3}  \\int d\\mathbf{p}\\int d\\mathbf{y}\\int d\\mathbf{x}\\exp{(i(\\mathbf{p}-\\mathbf{k})\\mathbf{x})}\\frac{\\exp{(-\\mu\\vert\\mathbf{x}\\vert})}{\\vert\\mathbf{x}\\vert}.\n$$\n\nThe integration over $\\mathbf{x}$ can be performed using spherical coordinates, resulting in (with $x=\\vert \\mathbf{x}\\vert$)\n\n$$\n\\int d\\mathbf{x}\\exp{(i(\\mathbf{p}-\\mathbf{k})\\mathbf{x})}\\frac{\\exp{(-\\mu\\vert\\mathbf{x}\\vert})}{\\vert\\mathbf{x}\\vert}=\\int x^2 dx d\\phi d\\cos{(\\theta)}\\exp{(i(\\mathbf{p}-\\mathbf{k})x\\cos{(\\theta))}}\\frac{\\exp{(-\\mu x)}}{x}.\n$$\n\nWe obtain\n\n$$\n\\begin{equation}\n4\\pi \\int dx \\frac{ \\sin{(\\vert \\mathbf{p}-\\mathbf{k}\\vert)x} }{\\vert \\mathbf{p}-\\mathbf{k}\\vert}{\\exp{(-\\mu x)}}= \\frac{4\\pi}{\\mu^2+\\vert \\mathbf{p}-\\mathbf{k}\\vert^2}.\n\\end{equation}\n$$\n\nThis results gives us\n\n$$\n\\begin{equation}\n\\lim_{\\mu \\to 0}\\frac{e^{2}}{V (2\\pi)^3}  \\int d\\mathbf{p}\\int d\\mathbf{y}\\frac{4\\pi}{\\mu^2+\\vert \\mathbf{p}-\\mathbf{k}\\vert^2}=\\lim_{\\mu \\to 0}\\frac{e^{2}}{ 2\\pi^2}  \\int d\\mathbf{p}\\frac{1}{\\mu^2+\\vert \\mathbf{p}-\\mathbf{k}\\vert^2},\n\\end{equation}\n$$\n\nwhere we have used that the integrand on the left-hand side does not depend on $\\mathbf{y}$ and that $\\int d\\mathbf{y}=V$.\n\nIntroducing spherical coordinates we can rewrite the integral as\n\n$$\n\\begin{equation}\n\\lim_{\\mu \\to 0}\\frac{e^{2}}{ 2\\pi^2}  \\int d\\mathbf{p}\\frac{1}{\\mu^2+\\vert \\mathbf{p}-\\mathbf{k}\\vert^2}=\\frac{e^{2}}{ 2\\pi^2}  \\int d\\mathbf{p}\\frac{1}{\\vert \\mathbf{p}-\\mathbf{k}\\vert^2}= \n\\end{equation}\n$$\n\n$$\n\\begin{equation} \n\\frac{e^{2}}{\\pi}  \\int_0^{k_F} p^2dp\\int_0^{\\pi} d\\theta\\cos{(\\theta)}\\frac{1}{p^2+k^2-2pk\\cos{(\\theta)}},\n\\end{equation}\n$$\n\nand with the change of variables $\\cos{(\\theta)}=u$ we have\n\n$$\n\\frac{e^{2}}{\\pi}  \\int_0^{k_F} p^2dp\\int_{0}^{\\pi} d\\theta\\cos{(\\theta)}\\frac{1}{p^2+k^2-2pk\\cos{(\\theta)}}=\\frac{e^{2}}{\\pi}  \\int_0^{k_F} p^2dp\\int_{-1}^{1} du\\frac{1}{p^2+k^2-2pku},\n$$\n\nwhich gives\n\n$$\n\\frac{e^{2}}{k\\pi}  \\int_0^{k_F} pdp\\left\\{ln(\\vert p+k\\vert)-ln(\\vert p-k\\vert)\\right\\}.\n$$\n\nIntroducing new variables $x=p+k$ and $y=p-k$, we obtain after some straightforward reordering of the integral\n\n$$\n\\frac{e^{2}}{k\\pi}\\left[\nkk_F+\\frac{k_{F}^{2}-k^{2}}{kk_{F}}ln\\left\\vert\\frac{k+k_{F}}\n{k-k_{F}}\\right\\vert\n\\right],\n$$\n\nwhich gives the abovementioned expression for the single-particle energy.\n\n\nIntroducing the dimensionless quantity $x=k/k_F$ and the function\n\n$$\nF(x) = \\frac{1}{2}+\\frac{1-x^2}{4x}\\ln{\\left\\vert \\frac{1+x}{1-x}\\right\\vert},\n$$\n\nwe can rewrite the single-particle Hartree-Fock energy as\n\n$$\n\\varepsilon_{k}^{HF}=\\frac{\\hbar^{2}k^{2}}{2m}-\\frac{2e^{2}\nk_{F}}{\\pi}F(k/k_F),\n$$\n\nand dividing by the non-interacting contribution at the Fermi level,\n\n$$\n\\varepsilon_{0}^{F}=\\frac{\\hbar^{2}k_F^{2}}{2m},\n$$\n\nwe have\n\n$$\n\\frac{\\varepsilon_{k}^{HF} }{\\varepsilon_{0}^{F}}=x^2-\\frac{e^2m}{\\hbar^2 k_F\\pi}F(x)=x^2-\\frac{4}{\\pi k_Fa_0}F(x),\n$$\n\nwhere $a_0=0.0529$ nm is the Bohr radius, setting thereby a natural length scale. \n\n\nBy introducing the radius $r_s$ of a sphere whose volume is the volume occupied by each electron, we can rewrite the previous equation in terms of $r_s$ using that the electron density $n=N/V$\n\n$$\nn=\\frac{k_F^3}{3\\pi^2} = \\frac{3}{4\\pi r_s^3},\n$$\n\nwe have (with $k_F=1.92/r_s$,\n\n$$\n\\frac{\\varepsilon_{k}^{HF} }{\\varepsilon_{0}^{F}}=x^2-\\frac{e^2m}{\\hbar^2 k_F\\pi}F(x)=x^2-\\frac{r_s}{a_0}0.663F(x),\n$$\n\nwith $r_s \\sim 2-6$ for most metals. \n\n\nWe can now define the so-called band gap, that is the scatter between the maximal and the minimal value of the electrons in the conductance band of a metal (up to the Fermi level). \nFor $x=1$ and $r_s/a_0=4$ we have\n\n$$\n\\frac{\\varepsilon_{k=k_F}^{HF} }{\\varepsilon_{0}^{F}} = -0.326,\n$$\n\nand for $x=0$ we have\n\n$$\n\\frac{\\varepsilon_{k=0}^{HF} }{\\varepsilon_{0}^{F}} = -2.652,\n$$\n\nwhich results in a gap at the Fermi level of\n\n$$\n\\Delta \\varepsilon^{HF} = \\frac{\\varepsilon_{k=k_F}^{HF} }{\\varepsilon_{0}^{F}}-\\frac{\\varepsilon_{k=0}^{HF} }{\\varepsilon_{0}^{F}} = 2.326.\n$$\n\nThis quantity measures the deviation from the $k=0$ single-particle energy and the energy at the Fermi level.\nThe general result is\n\n$$\n\\Delta \\varepsilon^{HF} = 1+\\frac{r_s}{a_0}0.663.\n$$\n\n<!-- --- end exercise --- -->\n\n\n### Plot of the Hartree-Fock single-particle energy for the three-dimensional electron gas\n\nThe following python code produces a plot of the electron energy for a free electron (only kinetic energy) and \nfor the Hartree-Fock solution. We have chosen here a ratio $r_s/a_0=4$ and the equations are plotted as funtions\nof $k/f_F$.\n\n\n```\nimport numpy as np\nfrom math import log\nfrom  matplotlib import pyplot as plt\nfrom matplotlib import rc, rcParams\nimport matplotlib.units as units\nimport matplotlib.ticker as ticker\nrc('text',usetex=True)\nrc('font',**{'family':'serif','serif':['Hartree-Fock energy']})\nfont = {'family' : 'serif',\n        'color'  : 'darkred',\n        'weight' : 'normal',\n        'size'   : 16,\n        }\n\nN = 100\nx = np.linspace(0.0, 2.0,N)\nF = 0.5+np.log(abs((1.0+x)/(1.0-x)))*(1.0-x*x)*0.25/x\ny = x*x -4.0*0.663*F\n\nplt.plot(x, y, 'b-')\nplt.plot(x, x*x, 'r-')\nplt.title(r'{\\bf Hartree-Fock single-particle energy for electron gas}', fontsize=20)     \nplt.text(3, -40, r'Parameters: $r_s/a_0=4$', fontdict=font)\nplt.xlabel(r'$k/k_F$',fontsize=20)\nplt.ylabel(r'$\\varepsilon_k^{HF}/\\varepsilon_0^F$',fontsize=20)\n# Tweak spacing to prevent clipping of ylabel\nplt.subplots_adjust(left=0.15)\nplt.savefig('hartreefockspelgas.pdf', format='pdf')\nplt.show()\n\n```\n\nFrom the plot we notice that the exchange term increases considerably the band gap\ncompared with the non-interacting gas of electrons.\n\n\n\n\n\n\n\n\n\n\n<!-- --- begin exercise --- -->\n\n### Exercise 26: Hartree-Fock ground state energy for the  electron gas in three dimensions\n\nWe consider a system of electrons in infinite matter, the so-called electron gas. This is a homogeneous system and the one-particle states are given by plane wave function normalized to a volume $\\Omega$ \nfor a box with length $L$ (the limit $L\\rightarrow \\infty$ is to be taken after we have computed various expectation values)\n\n$$\n\\psi_{\\mathbf{k}\\sigma}(\\mathbf{r})= \\frac{1}{\\sqrt{\\Omega}}\\exp{(i\\mathbf{kr})}\\xi_{\\sigma}\n$$\n\nwhere $\\mathbf{k}$ is the wave number and  $\\xi_{\\sigma}$ is a spin function for either spin up or down\n\n$$\n\\xi_{\\sigma=+1/2}=\\left(\\begin{array}{c} 1 \\\\ 0 \\end{array}\\right) \\hspace{0.5cm}\n\\xi_{\\sigma=-1/2}=\\left(\\begin{array}{c} 0 \\\\ 1 \\end{array}\\right).\n$$\n\nWe assume that we have periodic boundary conditions which limit the allowed wave numbers to\n\n$$\nk_i=\\frac{2\\pi n_i}{L}\\hspace{0.5cm} i=x,y,z \\hspace{0.5cm} n_i=0,\\pm 1,\\pm 2, \\dots\n$$\n\nWe assume first that the particles interact via a central, symmetric and translationally invariant\ninteraction  $V(r_{12})$ with\n$r_{12}=|\\mathbf{r}_1-\\mathbf{r}_2|$.  The interaction is spin independent.\n\nThe total Hamiltonian consists then of kinetic and potential energy\n\n$$\n\\hat{H} = \\hat{T}+\\hat{V}.\n$$\n\n**a)**\nShow that the operator for the kinetic energy can be written as\n\n$$\n\\hat{T}=\\sum_{\\mathbf{k}\\sigma}\\frac{\\hbar^2k^2}{2m}a_{\\mathbf{k}\\sigma}^{\\dagger}a_{\\mathbf{k}\\sigma}.\n$$\n\nFind also the number operator $\\hat{N}$ and find a corresponding expression for the interaction\n$\\hat{V}$ expressed with creation and annihilation operators.   The expression for the interaction\nhas to be written in  $k$ space, even though $V$ depends only on the relative distance. It means that you ned to set up the Fourier transform $\\langle \\mathbf{k}_i\\mathbf{k}_j| V | \\mathbf{k}_m\\mathbf{k}_n\\rangle$.\n\nThe Hamiltonian operator is given by\n\n$$\n\\hat{H}=\\hat{H}_{el}+\\hat{H}_{b}+\\hat{H}_{el-b},\n$$\n\nwith the electronic part\n\n$$\n\\hat{H}_{el}=\\sum_{i=1}^N\\frac{p_i^2}{2m}+\\frac{e^2}{2}\\sum_{i\\ne j}\\frac{e^{-\\mu |\\mathbf{r}_i-\\mathbf{r}_j|}}{|\\mathbf{r}_i-\\mathbf{r}_j|},\n$$\n\nwhere we have introduced an explicit convergence factor\n(the limit $\\mu\\rightarrow 0$ is performed after having calculated the various integrals).\nCorrespondingly, we have\n\n$$\n\\hat{H}_{b}=\\frac{e^2}{2}\\int\\int d\\mathbf{r}d\\mathbf{r}'\\frac{n(\\mathbf{r})n(\\mathbf{r}')e^{-\\mu |\\mathbf{r}-\\mathbf{r}'|}}{|\\mathbf{r}-\\mathbf{r}'|},\n$$\n\nwhich is the energy contribution from the positive background charge with density\n$n(\\mathbf{r})=N/\\Omega$. Finally,\n\n$$\n\\hat{H}_{el-b}=-\\frac{e^2}{2}\\sum_{i=1}^N\\int d\\mathbf{r}\\frac{n(\\mathbf{r})e^{-\\mu |\\mathbf{r}-\\mathbf{x}_i|}}{|\\mathbf{r}-\\mathbf{x}_i|},\n$$\n\nis the interaction between the electrons and the positive background.\n**b)**\nShow that\n\n$$\n\\hat{H}_{b}=\\frac{e^2}{2}\\frac{N^2}{\\Omega}\\frac{4\\pi}{\\mu^2},\n$$\n\nand\n\n$$\n\\hat{H}_{el-b}=-e^2\\frac{N^2}{\\Omega}\\frac{4\\pi}{\\mu^2}.\n$$\n\n**c)**\nShow thereafter that the final Hamiltonian can be written as\n\n$$\nH=H_{0}+H_{I},\n$$\n\nwith\n\n$$\nH_{0}={\\displaystyle\\sum_{\\mathbf{k}\\sigma}}\n\\frac{\\hbar^{2}k^{2}}{2m}a_{\\mathbf{k}\\sigma}^{\\dagger}\na_{\\mathbf{k}\\sigma},\n$$\n\nand\n\n$$\nH_{I}=\\frac{e^{2}}{2\\Omega}{\\displaystyle\\sum_{\\sigma_{1}\\sigma_{2}}}{\\displaystyle\\sum_{\\mathbf{q}\\neq 0,\\mathbf{k},\\mathbf{p}}}\\frac{4\\pi}{q^{2}}\na_{\\mathbf{k}+\\mathbf{q},\\sigma_{1}}^{\\dagger}\na_{\\mathbf{p}-\\mathbf{q},\\sigma_{2}}^{\\dagger}\na_{\\mathbf{p}\\sigma_{2}}a_{\\mathbf{k}\\sigma_{1}}.\n$$\n\n**d)**\nCalculate $E_0/N=\\langle \\Phi_{0}\\vert H\\vert \\Phi_{0}\\rangle/N$ for for this system to first order in the interaction. Show that, by using\n\n$$\n\\rho= \\frac{k_F^3}{3\\pi^2}=\\frac{3}{4\\pi r_0^3},\n$$\n\nwith $\\rho=N/\\Omega$, $r_0$\nbeing the radius of a sphere representing the volume an electron occupies \nand the Bohr radius $a_0=\\hbar^2/e^2m$, \nthat the energy per electron can be written as\n\n$$\nE_0/N=\\frac{e^2}{2a_0}\\left[\\frac{2.21}{r_s^2}-\\frac{0.916}{r_s}\\right].\n$$\n\nHere we have defined\n$r_s=r_0/a_0$ to be a dimensionless quantity.\n\n**e)**\nPlot your results. Why is this system stable?\nCalculate thermodynamical quantities like the pressure, given by\n\n$$\nP=-\\left(\\frac{\\partial E}{\\partial \\Omega}\\right)_N,\n$$\n\nand the bulk modulus\n\n$$\nB=-\\Omega\\left(\\frac{\\partial P}{\\partial \\Omega}\\right)_N,\n$$\n\nand comment your results.\n\nWe have to show first  that\n\n$$\n\\hat{H}_{b}=\\frac{e^2}{2}\\frac{N_e^2}{\\Omega}\\frac{4\\pi}{\\mu^2},\n$$\n\nand\n\n$$\n\\hat{H}_{el-b}=-e^2\\frac{N_e^2}{\\Omega}\\frac{4\\pi}{\\mu^2}.\n$$\n\nAnd then that the final Hamiltonian can be written as\n\n$$\nH=H_{0}+H_{I},\n$$\n\nwith\n\n$$\nH_{0}={\\displaystyle\\sum_{\\mathbf{k}\\sigma}}\n\\frac{\\hbar^{2}k^{2}}{2m_e}a_{\\mathbf{k}\\sigma}^{\\dagger}\na_{\\mathbf{k}\\sigma},\n$$\n\nand\n\n$$\nH_{I}=\\frac{e^{2}}{2\\Omega}{\\displaystyle\\sum_{\\sigma_{1}\n\\sigma_{2}}}{\\displaystyle\n\\sum_{\\mathbf{q}\\neq 0,\\mathbf{k},\\mathbf{p}}}\\frac{4\\pi}{q^{2}}\na_{\\mathbf{k}+\\mathbf{q},\\sigma_{1}}^{\\dagger}\na_{\\mathbf{p}-\\mathbf{q},\\sigma_{2}}^{\\dagger}\na_{\\mathbf{p}\\sigma_{2}}a_{\\mathbf{k}\\sigma_{1}}.\n$$\n\nLet us now calculate the following part of the Hamiltonian\n\n$$\n\\hat H_b = \\frac{e^2}{2} \\iint \\frac{n(\\mathbf{r}) n(\\mathbf{r}')e^{-\\mu|\\mathbf{r} - \\mathbf{r}'|}}{|\\mathbf{r} - \\mathbf{r}'|} d\\mathbf{r} d\\mathbf{r}' ,\n$$\n\nwhere $n(\\mathbf{r}) = N_e/\\Omega$, the density of the positive background charge. We define $\\mathbf{r}_{12} = \\mathbf{r} - \\mathbf{r}'$, resulting in $d\\mathbf{r}_{12} = d\\mathbf{r}$, and allowing us to rewrite the integral as\n\n$$\n\\hat H_b = \\frac{e^2 N_e^2}{2\\Omega^2} \\iint \\frac{e^{-\\mu |\\mathbf{r}_{12}|}}{|\\mathbf{r}_{12}|} d\\mathbf{r}_{12} d\\mathbf{r}' = \\frac{e^2 N_e^2}{2\\Omega} \\int \\frac{e^{-\\mu |\\mathbf{r}_{12}|}}{|\\mathbf{r}_{12}|} d\\mathbf{r}_{12} .\n$$\n\nHere we have used that $\\int \\! \\mathbf{r} = \\Omega$. We change to spherical coordinates and the lack of angle \ndependencies yields a factor $4\\pi$, resulting in\n\n$$\n\\hat H_b = \\frac{4\\pi e^2 N_e^2}{2\\Omega} \\int_0^\\infty re^{-\\mu r} \\, \\mathrm{d} r .\n$$\n\nSolving by partial integration\n\n$$\n\\int_0^\\infty re^{-\\mu r} \\, \\mathrm{d} r = \\left[ -\\frac{r}{\\mu} e^{-\\mu r} \\right]_0^\\infty + \\frac{1}{\\mu} \\int_0^\\infty e^{-\\mu r} \\, \\mathrm{d} r\n= \\frac{1}{\\mu} \\left[ - \\frac{1}{\\mu} e^{-\\mu r} \\right]_0^\\infty = \\frac{1}{\\mu^2},\n$$\n\ngives\n\n$$\n\\hat{H}_b = \\frac{e^2}{2} \\frac{N_e^2}{\\Omega} \\frac{4\\pi}{\\mu^2} .\n$$\n\nThe next term is\n\n$$\n\\hat H_{el-b} = -e^2 \\sum_{i = 1}^N \\int \\frac{n(\\mathbf{r}) e^{-\\mu |\\mathbf{r} - \\mathbf{x}_i|}}{|\\mathbf{r} - \\mathbf{x}_i|} \\mathbf{r} .\n$$\n\nInserting  $n(\\mathbf{r})$ and changing variables in the same way as in the previous integral $\\mathbf{y} = \\mathbf{r} - \\mathbf{x}_i$, we get $\\mathrm{d}^3 \\mathbf{y} = \\mathrm{d}^3 \\mathbf{r}$. This gives\n\n$$\n\\begin{equation}\n\\hat H_{el-b} = -\\frac{e^2 N_e}{\\Omega} \\sum_{i = 1^N} \\int \\frac{e^{-\\mu |\\mathbf{y}|}}{|\\mathbf{y}|} \\, \\mathrm{d}^3 \\mathbf{y}\n=  -\\frac{4\\pi e^2 N_e}{\\Omega} \\sum_{i = 1}^N \\int_0^\\infty y e^{-\\mu y} \\mathrm{d} y. \n\\end{equation}\n$$\n\nWe have already seen this  type of integral. The answer is\n\n$$\n\\hat H_{el-b} = -\\frac{4\\pi e^2 N_e}{\\Omega} \\sum_{i = 1}^N \\frac{1}{\\mu^2},\n$$\n\nwhich gives\n\n$$\n\\hat H_{el-b} = -e^2 \\frac{N_e^2}{\\Omega} \\frac{4\\pi}{\\mu^2} .\n$$\n\nFinally, we need to evaluate $\\hat H_{el}$. This term reads\n\n$$\n\\hat H_{el} = \\sum_{i=1}^{N_e} \\frac{\\hat{\\vec p}_i^2}{2m_e} + \\frac{e^2}{2} \\sum_{i \\neq j} \\frac{e^{-\\mu |\\mathbf{r}_i - \\mathbf{r}_j|}}{\\mathbf{r}_i - \\mathbf{r}_j} .\n$$\n\nThe last term represents the repulsion between two electrons. It is a central symmetric interaction\nand is translationally invariant. The potential is given by the expression\n\n$$\nv(|\\mathbf{r}|) = e^2 \\frac{e^{\\mu|\\mathbf{r}|}}{|\\mathbf{r}|},\n$$\n\nwhich we derived in connection with the single-particle Hartree-Fock derivation.\n\nMore material will be added here!\n\n\n\n\n\n<!-- --- end exercise --- -->\n\n\n### Preparing the ground for numerical calculations; kinetic energy and Ewald term\n\nThe kinetic energy operator is\n\n$$\n\\begin{equation}\n  \\hat{H}_{\\text{kin}} = -\\frac{\\hbar^{2}}{2m}\\sum_{i=1}^{N}\\nabla_{i}^{2},\n\\end{equation}\n$$\n\nwhere the sum is taken over all particles in the finite\nbox. The Ewald electron-electron interaction operator \ncan be written as\n\n$$\n\\begin{equation}\n  \\hat{H}_{ee} = \\sum_{i < j}^{N} v_{E}\\left( \\mathbf{r}_{i}-\\mathbf{r}_{j}\\right)\n  + \\frac{1}{2}Nv_{0},\n\\end{equation}\n$$\n\nwhere $v_{E}(\\mathbf{r})$ is the effective two-body \ninteraction and $v_{0}$ is the self-interaction, defined \nas $v_{0} = \\lim_{\\mathbf{r} \\rightarrow 0} \\left\\{ v_{E}(\\mathbf{r}) - 1/r\\right\\} $. \n\nThe negative \nelectron charges are neutralized by a positive, homogeneous \nbackground charge. Fraser *et al.* explain how the\nelectron-background and background-background terms, \n$\\hat{H}_{eb}$ and $\\hat{H}_{bb}$, vanish\nwhen using Ewald's interaction for the three-dimensional\nelectron gas. Using the same arguments, one can show that\nthese terms are also zero in the corresponding \ntwo-dimensional system. \n\n\n\n\n### Ewald correction term\n\nIn the three-dimensional electron gas, the Ewald \ninteraction is\n\n$$\n\\begin{equation}\n  v_{E}(\\mathbf{r}) = \\sum_{\\mathbf{k} \\neq \\mathbf{0}}\n  \\frac{4\\pi }{L^{3}k^{2}}e^{i\\mathbf{k}\\cdot \\mathbf{r}}\n  e^{-\\eta^{2}k^{2}/4} \\nonumber \n\\end{equation}\n$$\n\n$$\n\\begin{equation} \n  + \\sum_{\\mathbf{R}}\\frac{1}{\\left| \\mathbf{r}\n    -\\mathbf{R}\\right| } \\mathrm{erfc} \\left( \\frac{\\left| \n    \\mathbf{r}-\\mathbf{R}\\right|}{\\eta }\\right)\n  - \\frac{\\pi \\eta^{2}}{L^{3}},\n\\end{equation}\n$$\n\nwhere $L$ is the box side length, $\\mathrm{erfc}(x)$ is the \ncomplementary error function, and $\\eta $ is a free\nparameter that can take any value in the interval \n$(0, \\infty )$.\n\n\n\n### Interaction in momentum space\n\nThe translational vector\n\n$$\n\\begin{equation}\n  \\mathbf{R} = L\\left(n_{x}\\mathbf{u}_{x} + n_{y}\n  \\mathbf{u}_{y} + n_{z}\\mathbf{u}_{z}\\right) ,\n\\end{equation}\n$$\n\nwhere $\\mathbf{u}_{i}$ is the unit vector for dimension $i$,\nis defined for all integers $n_{x}$, $n_{y}$, and \n$n_{z}$. These vectors are used to obtain all image\ncells in the entire real space. \nThe parameter $\\eta $ decides how \nthe Coulomb interaction is divided into a short-ranged\nand long-ranged part, and does not alter the total\nfunction. However, the number of operations needed\nto calculate the Ewald interaction with a desired \naccuracy depends on $\\eta $, and $\\eta $ is therefore \noften chosen to optimize the convergence as a function\nof the simulation-cell size. In\nour calculations, we choose $\\eta $ to be an infinitesimally\nsmall positive number, similarly as was done by [Shepherd *et al.*](https://journals.aps.org/prb/abstract/10.1103/PhysRevB.86.035111) and [Roggero *et al.*](https://journals.aps.org/prb/abstract/10.1103/PhysRevB.88.115138).\n\nThis gives an interaction that is evaluated only in\nFourier space. \n\nWhen studying the two-dimensional electron gas, we\nuse an Ewald interaction that is quasi two-dimensional.\nThe interaction is derived in three dimensions, with \nFourier discretization in only two dimensions. The Ewald effective\ninteraction has the form\n\n$$\n\\begin{equation}\n  v_{E}(\\mathbf{r}) = \\sum_{\\mathbf{k} \\neq \\mathbf{0}} \n  \\frac{\\pi }{L^{2}k}\\left\\{ e^{-kz} \\mathrm{erfc} \\left(\n  \\frac{\\eta k}{2} - \\frac{z}{\\eta }\\right)+ \\right. \\nonumber \n\\end{equation}\n$$\n\n$$\n\\begin{equation} \n   \\left. e^{kz}\\mathrm{erfc} \\left( \\frac{\\eta k}{2} + \\frac{z}{\\eta }\n  \\right) \\right\\} e^{i\\mathbf{k}\\cdot \\mathbf{r}_{xy}} \n  \\nonumber \n\\end{equation}\n$$\n\n$$\n\\begin{equation} \n   + \\sum_{\\mathbf{R}}\\frac{1}{\\left| \\mathbf{r}-\\mathbf{R}\n    \\right| } \\mathrm{erfc} \\left( \\frac{\\left| \\mathbf{r}-\\mathbf{R}\n    \\right|}{\\eta }\\right) \\nonumber \n\\end{equation}\n$$\n\n$$\n\\begin{equation} \n   - \\frac{2\\pi}{L^{2}}\\left\\{ z\\mathrm{erf} \\left( \\frac{z}{\\eta }\n  \\right) + \\frac{\\eta }{\\sqrt{\\pi }}e^{-z^{2}/\\eta^{2}}\\right\\},\n\\end{equation}\n$$\n\nwhere the Fourier vectors $\\mathbf{k}$ and the position vector\n$\\mathbf{r}_{xy}$ are defined in the $(x,y)$ plane. When\napplying the interaction $v_{E}(\\mathbf{r})$ to two-dimensional\nsystems, we set $z$ to zero. \n\n\nSimilarly as in the \nthree-dimensional case, also here we \nchoose $\\eta $ to approach zero from above. The resulting \nFourier-transformed interaction is\n\n$$\n\\begin{equation}\n  v_{E}^{\\eta = 0, z = 0}(\\mathbf{r}) = \\sum_{\\mathbf{k} \\neq \\mathbf{0}} \n  \\frac{2\\pi }{L^{2}k}e^{i\\mathbf{k}\\cdot \\mathbf{r}_{xy}}. \n\\end{equation}\n$$\n\nThe self-interaction $v_{0}$ is a constant that can be \nincluded in the reference energy.\n\n\n\n\n### Antisymmetrized matrix elements in three dimensions\n\nIn the three-dimensional electron gas, the antisymmetrized\nmatrix elements are\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:vmat_3dheg\"></div>\n\n$$\n\\begin{equation} \\label{eq:vmat_3dheg} \\tag{133}\n   \\langle \\mathbf{k}_{p}m_{s_{p}}\\mathbf{k}_{q}m_{s_{q}}\n  |\\tilde{v}|\\mathbf{k}_{r}m_{s_{r}}\\mathbf{k}_{s}m_{s_{s}}\\rangle_{AS} \n  \\nonumber \n\\end{equation}\n$$\n\n$$\n\\begin{equation} \n   = \\frac{4\\pi }{L^{3}}\\delta_{\\mathbf{k}_{p}+\\mathbf{k}_{q},\n    \\mathbf{k}_{r}+\\mathbf{k}_{s}}\\left\\{ \n  \\delta_{m_{s_{p}}m_{s_{r}}}\\delta_{m_{s_{q}}m_{s_{s}}}\n  \\left( 1 - \\delta_{\\mathbf{k}_{p}\\mathbf{k}_{r}}\\right) \n  \\frac{1}{|\\mathbf{k}_{r}-\\mathbf{k}_{p}|^{2}}\n  \\right. \\nonumber \n\\end{equation}\n$$\n\n$$\n\\begin{equation} \n   \\left. - \\delta_{m_{s_{p}}m_{s_{s}}}\\delta_{m_{s_{q}}m_{s_{r}}}\n  \\left( 1 - \\delta_{\\mathbf{k}_{p}\\mathbf{k}_{s}} \\right)\n  \\frac{1}{|\\mathbf{k}_{s}-\\mathbf{k}_{p}|^{2}} \n  \\right\\} ,\n\\end{equation}\n$$\n\nwhere the Kronecker delta functions \n$\\delta_{\\mathbf{k}_{p}\\mathbf{k}_{r}}$ and\n$\\delta_{\\mathbf{k}_{p}\\mathbf{k}_{s}}$ ensure that the \ncontribution with zero momentum transfer vanishes.\n\n\nSimilarly, the matrix elements for the two-dimensional\nelectron gas are\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:vmat_2dheg\"></div>\n\n$$\n\\begin{equation} \\label{eq:vmat_2dheg} \\tag{134}\n   \\langle \\mathbf{k}_{p}m_{s_{p}}\\mathbf{k}_{q}m_{s_{q}}\n  |v|\\mathbf{k}_{r}m_{s_{r}}\\mathbf{k}_{s}m_{s_{s}}\\rangle_{AS} \n  \\nonumber \n\\end{equation}\n$$\n\n$$\n\\begin{equation} \n   = \\frac{2\\pi }{L^{2}}\n  \\delta_{\\mathbf{k}_{p}+\\mathbf{k}_{q},\\mathbf{k}_{r}+\\mathbf{k}_{s}}\n  \\left\\{ \\delta_{m_{s_{p}}m_{s_{r}}}\\delta_{m_{s_{q}}m_{s_{s}}} \n  \\left( 1 - \\delta_{\\mathbf{k}_{p}\\mathbf{k}_{r}}\\right)\n  \\frac{1}{\n    |\\mathbf{k}_{r}-\\mathbf{k}_{p}|} \\right.\n  \\nonumber \n\\end{equation}\n$$\n\n$$\n\\begin{equation} \n   - \\left. \\delta_{m_{s_{p}}m_{s_{s}}}\\delta_{m_{s_{q}}m_{s_{r}}}\n  \\left( 1 - \\delta_{\\mathbf{k}_{p}\\mathbf{k}_{s}}\\right)\n  \\frac{1}{ \n    |\\mathbf{k}_{s}-\\mathbf{k}_{p}|}\n  \\right\\} ,\n\\end{equation}\n$$\n\nwhere the single-particle momentum vectors $\\mathbf{k}_{p,q,r,s}$\nare now defined in two dimensions.\n\n\n\n### Fock operator\n\nIn the calculations, the \nself-interaction constant is included in the reference \nenergy. We therefore get the \nFock-operator matrix elements\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:fock_heg\"></div>\n\n$$\n\\begin{equation}\n  \\langle \\mathbf{k}_{p}|f|\\mathbf{k}_{q} \\rangle\n  = \\frac{\\hbar^{2}k_{p}^{2}}{2m}\\delta_{\\mathbf{k}_{p},\n  \\mathbf{k}_{q}} + \\sum_{\\mathbf{k}_{i}}\\langle \n  \\mathbf{k}_{p}\\mathbf{k}_{i}|v|\\mathbf{k}_{q}\n  \\mathbf{k}_{i}\\rangle_{AS}.\n  \\label{eq:fock_heg} \\tag{135}\n\\end{equation}\n$$\n\nIn work of Shepherd *et al.* the matrix elements were \ndefined with the self-interaction constant included in the\ntwo-body interaction. This gives Fock-operator matrix \nelements with a gap constant.\n\n\n\n### Periodic boundary conditions and single-particle states\n\nWhen using periodic boundary conditions, the \ndiscrete-momentum single-particle basis functions\n\n$$\n\\phi_{\\mathbf{k}}(\\mathbf{r}) =\ne^{i\\mathbf{k}\\cdot \\mathbf{r}}/L^{d/2}\n$$\n\nare associated with \nthe single-particle energy\n\n$$\n\\begin{equation}\n  \\varepsilon_{n_{x}, n_{y}} = \\frac{\\hbar^{2}}{2m} \\left( \\frac{2\\pi }{L}\\right)^{2}\\left( n_{x}^{2} + n_{y}^{2}\\right)\n\\end{equation}\n$$\n\nfor two-dimensional sytems and\n\n$$\n\\begin{equation}\n  \\varepsilon_{n_{x}, n_{y}, n_{z}} = \\frac{\\hbar^{2}}{2m}\n  \\left( \\frac{2\\pi }{L}\\right)^{2}\n  \\left( n_{x}^{2} + n_{y}^{2} + n_{z}^{2}\\right)\n\\end{equation}\n$$\n\nfor three-dimensional systems.\n\n\nWe choose  the single-particle basis such that both the occupied and \nunoccupied single-particle spaces have a closed-shell \nstructure. This means that all single-particle states \ncorresponding to energies below a chosen cutoff are\nincluded in the basis. We study only the unpolarized spin\nphase, in which all orbitals are occupied with one spin-up \nand one spin-down electron. \n\n\nThe table illustrates  how single-particle energies\n    fill energy shells in a two-dimensional electron box.\n  Here $n_{x}$ and $n_{y}$ are the momentum quantum numbers,\n  $n_{x}^{2} + n_{y}^{2}$ determines the single-particle \n  energy level, $N_{\\uparrow \\downarrow }$ represents the \n  cumulated number of spin-orbitals in an unpolarized spin\n  phase, and $N_{\\uparrow \\uparrow }$ stands for the\n  cumulated number of spin-orbitals in a spin-polarized\n  system.\n\n\n\n\n### Magic number for the two-dimensional electron gas\n\n\n<table border=\"1\">\n<thead>\n<tr><th align=\"center\">$n_{x}^{2}+n_{y}^{2}$</th> <th align=\"center\">$n_{x}$</th> <th align=\"center\">$n_{y}$</th> <th align=\"center\">$N_{\\uparrow \\downarrow }$</th> <th align=\"center\">$N_{\\uparrow \\uparrow }$</th> </tr>\n</thead>\n<tbody>\n<tr><td align=\"center\">   0                        </td> <td align=\"center\">   0          </td> <td align=\"center\">   0          </td> <td align=\"center\">   2                             </td> <td align=\"center\">   1                           </td> </tr>\n<tr><td align=\"center\">   1                        </td> <td align=\"center\">   -1         </td> <td align=\"center\">   0          </td> <td align=\"center\">                                 </td> <td align=\"center\">                               </td> </tr>\n<tr><td align=\"center\">                            </td> <td align=\"center\">   1          </td> <td align=\"center\">   0          </td> <td align=\"center\">                                 </td> <td align=\"center\">                               </td> </tr>\n<tr><td align=\"center\">                            </td> <td align=\"center\">   0          </td> <td align=\"center\">   -1         </td> <td align=\"center\">                                 </td> <td align=\"center\">                               </td> </tr>\n<tr><td align=\"center\">                            </td> <td align=\"center\">   0          </td> <td align=\"center\">   1          </td> <td align=\"center\">   10                            </td> <td align=\"center\">   5                           </td> </tr>\n<tr><td align=\"center\">   2                        </td> <td align=\"center\">   -1         </td> <td align=\"center\">   -1         </td> <td align=\"center\">                                 </td> <td align=\"center\">                               </td> </tr>\n<tr><td align=\"center\">                            </td> <td align=\"center\">   -1         </td> <td align=\"center\">   1          </td> <td align=\"center\">                                 </td> <td align=\"center\">                               </td> </tr>\n<tr><td align=\"center\">                            </td> <td align=\"center\">   1          </td> <td align=\"center\">   -1         </td> <td align=\"center\">                                 </td> <td align=\"center\">                               </td> </tr>\n<tr><td align=\"center\">                            </td> <td align=\"center\">   1          </td> <td align=\"center\">   1          </td> <td align=\"center\">   18                            </td> <td align=\"center\">   9                           </td> </tr>\n<tr><td align=\"center\">   4                        </td> <td align=\"center\">   -2         </td> <td align=\"center\">   0          </td> <td align=\"center\">                                 </td> <td align=\"center\">                               </td> </tr>\n<tr><td align=\"center\">                            </td> <td align=\"center\">   2          </td> <td align=\"center\">   0          </td> <td align=\"center\">                                 </td> <td align=\"center\">                               </td> </tr>\n<tr><td align=\"center\">                            </td> <td align=\"center\">   0          </td> <td align=\"center\">   -2         </td> <td align=\"center\">                                 </td> <td align=\"center\">                               </td> </tr>\n<tr><td align=\"center\">                            </td> <td align=\"center\">   0          </td> <td align=\"center\">   2          </td> <td align=\"center\">   26                            </td> <td align=\"center\">   13                          </td> </tr>\n<tr><td align=\"center\">   5                        </td> <td align=\"center\">   -2         </td> <td align=\"center\">   -1         </td> <td align=\"center\">                                 </td> <td align=\"center\">                               </td> </tr>\n<tr><td align=\"center\">                            </td> <td align=\"center\">   2          </td> <td align=\"center\">   -1         </td> <td align=\"center\">                                 </td> <td align=\"center\">                               </td> </tr>\n<tr><td align=\"center\">                            </td> <td align=\"center\">   -2         </td> <td align=\"center\">   1          </td> <td align=\"center\">                                 </td> <td align=\"center\">                               </td> </tr>\n<tr><td align=\"center\">                            </td> <td align=\"center\">   2          </td> <td align=\"center\">   1          </td> <td align=\"center\">                                 </td> <td align=\"center\">                               </td> </tr>\n<tr><td align=\"center\">                            </td> <td align=\"center\">   -1         </td> <td align=\"center\">   -2         </td> <td align=\"center\">                                 </td> <td align=\"center\">                               </td> </tr>\n<tr><td align=\"center\">                            </td> <td align=\"center\">   -1         </td> <td align=\"center\">   2          </td> <td align=\"center\">                                 </td> <td align=\"center\">                               </td> </tr>\n<tr><td align=\"center\">                            </td> <td align=\"center\">   1          </td> <td align=\"center\">   -2         </td> <td align=\"center\">                                 </td> <td align=\"center\">                               </td> </tr>\n<tr><td align=\"center\">                            </td> <td align=\"center\">   1          </td> <td align=\"center\">   2          </td> <td align=\"center\">   42                            </td> <td align=\"center\">   21                          </td> </tr>\n</tbody>\n</table>\n### Hartree-Fock energies\n\nFinally, a useful benchmark for our calculations is the expression for\nthe reference energy $E_0$ per particle.\nDefining the $T=0$ density $\\rho_0$, we can in turn determine in three\ndimensions the radius $r_0$ of a sphere representing the volume an\nelectron occupies (the classical electron radius) as\n\n$$\nr_0= \\left(\\frac{3}{4\\pi \\rho}\\right)^{1/3}.\n$$\n\nIn two dimensions the corresponding quantity is\n\n$$\nr_0= \\left(\\frac{1}{\\pi \\rho}\\right)^{1/2}.\n$$\n\nOne can then express the reference energy per electron in terms of the\ndimensionless quantity $r_s=r_0/a_0$, where we have introduced the\nBohr radius $a_0=\\hbar^2/e^2m$. The energy per electron computed with\nthe reference Slater determinant can then be written as\n(using hereafter only atomic units, meaning that $\\hbar = m = e = 1$)\n\n$$\nE_0/N=\\frac{1}{2}\\left[\\frac{2.21}{r_s^2}-\\frac{0.916}{r_s}\\right],\n$$\n\nfor the three-dimensional electron gas.  For the two-dimensional gas\nthe corresponding expression is (show this)\n\n$$\nE_0/N=\\frac{1}{r_s^2}-\\frac{8\\sqrt{2}}{3\\pi r_s}.\n$$\n\nFor an infinite homogeneous system, there are some particular\nsimplications due to the conservation of the total momentum of the\nparticles.  By symmetry considerations, the total momentum of the\nsystem has to be zero. Both the kinetic energy operator and the\ntotal Hamiltonian $\\hat{H}$ are assumed to be diagonal in the total\nmomentum $\\mathbf{K}$. Hence, both the reference state $\\Phi_{0}$ and\nthe correlated ground state $\\Psi$ must be eigenfunctions of the\noperator $\\mathbf{\\hat{K}}$ with the corresponding eigenvalue\n$\\mathbf{K} = \\mathbf{0}$.  This leads to important\nsimplications to our different many-body methods. In coupled cluster\ntheory for example, all\nterms that involve single particle-hole excitations vanish. \n\n\n\n\n\n\n\n\n\n\n\n# Decays\n<div id=\"ch:decay\"></div>\n\n## Electromagnetic multipole moments and transitions\nThe reduced\ntransition probability $B$ is defined in terms of reduced matrix\nelements of a one-body operator by\n\n$$\nB(i \\rightarrow f)= \\frac{\\langle J_{f}||{\\cal O}(\\lambda )||J_{i}\\rangle^{2}}{(2J_{i}+1)}.\n$$\n\nWith our definition of the reduced matrix element,\n\n$$\n\\langle J_{f}||{\\cal O}(\\lambda )||J_{i}\\rangle^{2} =\\langle J_{i}||{\\cal O}(\\lambda )||J_{f}\\rangle^{2},\n$$\n\nthe transition probability $B$ depends upon the direction of the transition by the factor\nof $(2J_{i}+1)$. For electromagnetic\ntransitions $J_{i}$ is that for the higher-energy initial state. But in\nCoulomb excitation the initial state is usually\ntaken as the ground state, and it is normal to use the notation $B(\\uparrow)$ for transitions from the ground state.\n\nThe one-body operators $  {\\cal O}(\\lambda )  $ represent a sum over\nthe operators for the individual nucleon degrees of freedom  $  i  $\n\n$$\n{\\cal O}(\\lambda ) = \\sum_{i} O(\\lambda ,i).\n$$\n\nThe electric transition operator is given by\n\n$$\nO(E\\lambda ) = r^{\\lambda } \\; Y^{\\lambda }_{\\mu }(\\hat{r}) \\; e_{q} e,\n$$\n\nwere $Y^{\\lambda }_{\\mu }$ are the spherical harmonics\nand $q$ stands for proton $q=p$ or neutron $q=n$.\n\n\nGamma transitions\nwith $\\lambda=0$ are forbidden because the photon must carry off\nat least one unit of angular momentum. The $e_{q}$\nare the electric charges for the proton and neutron in units of $  e  $.\nFor the free-nucleon\ncharge we would take $e_{p}=1$ and $e_{n}=0$, for the\nproton and neutron, respectively.\nAlthough the bare operator acts upon the protons,\nwe will keep the general expression in terms of $e_{q}$ in order\nto incorporate the **effective charges** for the proton and\nneutron, which represent the center-of-mass corrections and the\naverage effects of the renormalization from wavefunction\nadmixtures outside the model space.\n\n\n\nThe magnetic transition operator is given by:\n\n1\n0\n5\n5\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n= \\sqrt{\\lambda (2\\lambda +1)}\\left[[Y^{\\lambda -1}(\\hat{r})\\otimes \\mathbf{l}\\,]^{\\lambda }_{\\mu }\\frac{2g^{l}_{q}}{(\\lambda +1)}\n+ [Y^{\\lambda -1}(\\hat{r})\\otimes \\mathbf{s}\\,]^{\\lambda }_{\\mu }g^{s}_{q}\\right]r^{\\lambda -1}\\mu _{N},\n$$\n\nwhere $\\mu_{N}$ is the nuclear magneton,\n\n$$\n\\mu _{N}=\\frac{e\\hbar }{2m_{p}c} = 0.105 \\; e {\\rm fm},\n$$\n\nand where $m_{p}$ is the mass of the proton.\n\n\nThe g-factors $g^{l}_{q}$ and $g^{s}_{q}$\nare the orbital and spin g-factors\nfor the proton and neutron, respectively.\nThe\nfree-nucleon values for the g-factors are $g^{l}_{p}=1$, $g^{l}_{n}=0$,\n$g^{s}_{p}=5.586$ and $g^{s}_{n}=-3.826$. We may use effective values\nfor these g-factors to take into account the truncation of the model\nspace.\n\n\nThe most common types of transitions are $E1$, $E2$ and $M1$.\nThe $E1$ transition operator is given by $\\lambda$=1:\n\n$$\nO(E1) = rY^{(1)}_{\\mu }(\\hat{r})e_{q} e= \\sqrt{\\frac{3}{4\\pi }}\\mathbf{r}e_{q} e.\n$$\n\nThe $E2$ transition operator with $\\lambda$=2:\n\n$$\nO(E2) = r^{2}Y^{(2)}_{\\mu }(\\hat{r})e_{q} e,\n$$\n\nThe $M1$ transition operator with $\\lambda=1$ and with\n\n$$\nY^{0}=1/\\sqrt{4\\pi },\n$$\n\nwe have\n\n$$\nO(M1)=\\sqrt{\\frac{3}{4\\pi }}[\\mathbf{l}g^{l }_{q}+\\mathbf{s} \\; g^{s}_{q}]\\mu _{N}.\n$$\n\nThe selection rules are given by the triangle condition for the\nangular momenta, $  \\Delta (J_{i},J_{f},\\lambda )  $. The electromagnetic\ninteraction conserves parity, and the elements of the\noperators for $  E\\lambda   $ and $  M\\lambda   $\ncan be classified according to their transformation under parity\nchange\n\n$$\n\\hat{P}\\hat{O}\\hat{P}^{-1}=\\pi_{O}\\hat{O},\n$$\n\nwhere we have $\\pi _{O}=(-1)^{\\lambda }$ for $Y^{\\lambda }$,\n$\\pi _{O}=-1$ for the vectors\n$\\mathbf{r}$, $\\mathbf{\\nabla}$ and $\\mathbf{p}$, and $  \\pi _{O}=+1  $ for the \npseudo vectors\n$\\mathbf{l}=\\mathbf{r}\\times\\mathbf{p}$ and $\\mathbf{\\sigma}$. For a given matrix element we have:\n\n$$\n\\langle\\Psi _{f}\\vert {\\cal O}\\vert \\Psi _{i}\\rangle =\\langle\\Psi _{f}\\vert P^{-1}P{\\cal O}P^{-1}P\\vert \\Psi _{i}\\rangle=\\pi _{i}\\pi _{f}\\pi _{O} \\langle\\Psi _{f}\\vert {\\cal O}\\vert \\Psi _{i}\\rangle.\n$$\n\nThe matrix element will vanish unless  $\\pi _{i}\\pi _{f}\\pi _{O}=+1$.\n\n\n\nThe transitions are divided into two classes, those\nwhich do not change parity change $\\pi _{i}\\pi _{f}=+1$ which go by the\noperators with $\\pi _{O}=+1$:\n\n$$\n\\pi _{i}\\pi _{f}=+1 \\; \\mathrm{for} \\; M1, E2, M3, E4 \\dots,\n$$\n\nand the ones which do change parity change $\\pi _{i}\\pi _{f}=-1$\nwhich go by the operators with $\\pi _{O}=-1$:\n\n$$\n\\pi _{i}\\pi _{f}=-1 \\; \\mathrm{for} \\; E1, M2, E3, M4 \\dots.\n$$\n\nThe \nelectromagnetic moment operator can be expressed in terms of the\nelectromagnetic transition operators.\nBy the parity selection rule of the moments are nonzero\nonly for $M1$, $E2$, $M3$, $E4,\\ldots$.\nThe most common are:\n\n$$\n\\mu =\\sqrt{\\frac{4\\pi }{3}}\\langle J,M=J\\vert {\\cal O}(M1)\\vert J,M=J\\rangle= \\sqrt{\\frac{4\\pi }{3}}\\left\\{\\begin{array}{ccc} J & 1 &J \\\\  -J &  0 &  J \\end{array}\\right\\}\n\\langle J\\vert \\vert {\\cal O}(M1)\\vert \\vert J\\rangle,\n$$\n\nand\n\n$$\nQ = \\sqrt{\\frac{16\\pi }{5}}\\langle J,M=J\\vert {\\cal O}(E2)\\vert J,M=J\\rangle= \\sqrt{\\frac{16\\pi }{5}}\\,\n  \\left(\\begin{array}{ccc}  {J}&  {2} & {J}\\\\  {-J} & {0}&  {J}\\end{array}\\right)\\langle J\\vert\\vert {\\cal O}(E2)\\vert\\vert J\\rangle.\n$$\n\nElectromagnetic transitions and moments depend upon the reduced nuclear\nmatrix elements $\\langle f\\vert\\vert {\\cal O}(\\lambda )\\vert\\vert i\\rangle$. These can be expressed as a sum over one-body transition\ndensities (OBTD) times single-particle matrix elements\n\n$$\n\\langle f\\vert\\vert {\\cal O}(\\lambda )\\vert\\vert i\\rangle\n=\\sum _{k_{\\alpha } k_{\\beta }}\\mathrm{OBTD}(f i k_{\\alpha } k_{\\beta } \\lambda )\n \\langle k_{\\alpha }\\vert\\vert O(\\lambda )\\vert\\vert k_{\\beta }\\rangle,\n$$\n\nwhere the OBTD is given by\n\n$$\n\\mathrm{OBTD}(f i k_{\\alpha} k_{\\beta}\\lambda)= \\frac{\\langle f\\vert\\vert [a^{+}_{k_{\\alpha }}\\otimes \\tilde{a}_{k_{\\beta }}]^{\\lambda }\\vert\\vert i\\rangle}{\\sqrt{(2\\lambda +1)}}.\n$$\n\nThe labels $i$ and $f$ are a short-hand notation for the initial\nand final state quantum numbers $(n \\omega _{i}J_{i})$ and $(n\\omega_{f}J_{f})$,\nrespectively. Thus the problem is divided into two parts, one\ninvolving the nuclear structure dependent one-body transition\ndensities OBTD, and the other involving the reduced\nsingle-particle matrix\nelements (SPME).\n\n\n\n\nThe SPME for the $  E\\lambda   $ operator is given by:\n\n1\n0\n7\n0\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\times\\sqrt{ {(2j_{a}+1)(2\\lambda +1)(2j_{b}+1)\\over4\\pi }}\\left(\\begin{array}{ccc}  {j_{a}}&  {\\lambda} &  {j_{b}}\\\\  {1/2} & {0}&  {-1/2}\\end{array}\\right)\\langle k_{a}\\vert r^{\\lambda }\\vert k_{b}\\rangle e_{q} e.\n$$\n\nThe SPME for the spin part of the magnetic operator is\n\n1\n0\n7\n2\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n1\n0\n7\n3\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n1\n0\n7\n4\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\times \\langle l _{a}\\vert\\vert Y^{\\lambda -1}(\\hat{r})\\vert\\vert l _{b}\\rangle\\langle\\vert\\vert \\mathbf{s}\\vert\\vert s\\rangle\\langle k_{a}\\vert r^{\\lambda -1}\\vert k_{b}\\rangle g^{s}_{q}\\mu _{N},\n$$\n\nwhere\n\n$$\n\\langle\\vert\\vert \\mathbf{s}\\vert\\vert s\\rangle = \\sqrt{3/2}.\n$$\n\nThe SPME for the orbital part of the magnetic operator is:\n\n1\n0\n7\n7\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n1\n0\n7\n8\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n1\n0\n7\n9\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\times\\left\\{\\begin{array}{ccc}  {l _{a}} &  {l _{b}} & {\\lambda} \\\\  {j_{b}}&  {j_{a}}&  {1/2}\\end{array}\\right\\}\n\\langle l _{a}\\vert\\vert [Y^{\\lambda -1}(\\hat{r})\\otimes\\mathbf{l}\\,]^{\\lambda }\\vert\\vert l _{b}\\rangle\n\\langle k_{a}\\vert r^{\\lambda -1}\\vert k_{b}\\rangle g^{l }_{q}\\mu _{N},\n$$\n\nwhere we have defined\n\n1\n0\n8\n1\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\times\\left\\{\\begin{array}{ccc}  {\\lambda -1} & {1}&  {\\lambda}\\\\   {l _{b}}&  {l _{a}} &  {l _{b}} \\end{array}\\right\\}\n\\langle l _{a}\\vert\\vert Y^{\\lambda -1}(\\hat{r})\\vert\\vert l _{b}\\rangle,\n$$\n\nwith\n\n$$\n\\langle l _{a}\\vert\\vert Y^{\\lambda -1}(\\hat{r})\\vert\\vert l _{b}\\rangle=(-1)^{l _{a}} \\sqrt{\\frac{(2l _{a}+1)(2l _{b}+1)(2\\lambda -1)}{4\\pi }}\\left(\\begin{array}{ccc}  {l _{a}} & {\\lambda -1} & {l _{b}}\\\\  {0} & {0}&  {0}\\end{array}\\right)\n.\n$$\n\nFor the $M1$ operator the radial matrix element is\n\n$$\n<k_{a}\\vert r^{0}\\vert k_{b}>\\, = \\delta _{n_{a},n_{b}},\n$$\n\nand the SPME simplify to:\n\n1\n0\n8\n5\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n1\n0\n8\n6\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\times\\langle s\\vert\\vert \\mathbf{s}\\vert\\vert s\\rangle \\delta _{l _{a},l _{b}} \\delta _{n_{a},n_{b}}g^{s}_{q}\\mu _{N},\n$$\n\nwhere we have\n\n$$\n<s\\vert\\vert \\mathbf{s}\\,\\vert\\vert s>\\, = \\sqrt{3/2}\\, ,\n$$\n\nand\n\n1\n0\n8\n9\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n1\n0\n9\n0\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\times\\langle l _{a}\\vert\\vert \\mathbf{l}\\,\\vert\\vert l _{b}\\rangle \\delta _{n_{a},n_{b}}g^{l }_{q}\\mu _{N} ,\n$$\n\nwhere\n\n$$\n\\langle l _{a}\\vert\\vert \\mathbf{l}\\,\\vert\\vert l _{b}\\rangle = \\delta _{l _{a},l _{b}} \\sqrt{l _{a}(l_{a}+1)(2l _{a}+1)}.\n$$\n\nThus the $M1$ operator connects only\nthose orbitals which have the same $n$ and $l$ values.\n\n\n\n## $\\beta$-decay\n\nWe will now focus on  allowed $\\beta$-decay.  \nThe allowed beta decay rate $W$ between a specific set of\ninitial and final states is given by\n\n$$\nW_{i,f} = (f/K_{o}) \\left[ g_{V}^{2} \\; B_{i,f}(F_{\\pm})+ g_{A}^{2}B_{i,f}(GT_{\\pm})\\right],\n$$\n\nwhere $f$ is dimensionless three-body\nphase-space factor which depends upon the\nbeta-decay $Q$ value,\nand $K_{o}$ is a specific combination of fundamental constants\n\n$$\nK_{o}=\\frac{2\\pi^{3}\\hbar^{7}}{ m_{e}^{5} c^{4}}= 1.8844 \\times 10^{-94}\\mathrm{erg}^{2}\\mathrm{cm}^{6}\\mathrm{s}.\n$$\n\nThe $\\pm$ signrefer to $\\beta_{\\pm}$ decay of nucleus\n$(A_{i},Z_{i})$ into nucleus $(A_{i},Z_{i} \\mp 1)  $.\nThe weak-interaction vector ($V$) and axial-vector ($A$) coupling\nconstants for the decay of neutron into a proton are denoted by $g_{V}$\nand $g_{A}$, respectively.\n\nThe total decay rate for a given\ninitial state is obtained by summing the partial rates over all\nfinal states\n\n$$\nW = \\displaystyle\\sum _{f} W_{if},\n$$\n\nwith the branching fraction to a specific final state given by\n\n$$\nb_{if} = \\frac{W_{if}}{W}.\n$$\n\nBeta decay lifetime are usually given in terms of the half-life with\na total half-life of\n\n$$\nT_{1/2} = \\frac{{\\rm ln}(2)}{W}.\n$$\n\nThe partial half-life for a particular final state will be\ndenoted by $  t_{1/2}  $\n\n$$\nt_{1/2} = \\frac{T_{1/2}}{b_{if}}.\n$$\n\nHistorically\none combines the partial half-life for a particular decay\nwith the calculated\nphase-space factor $f$ to obtain  an **ft** value given by\n\n$$\nf t_{1/2}=\\frac{C }{\\left[B(F_{\\pm})+(g_{A}/g_{V})^{2} B(GT_{\\pm}) \\right] }\n$$\n\nwhere\n\n$$\nC = \\frac{{\\rm ln}(2)K_{o}}{(g_{V})^{2}}.\n$$\n\nOne often compiles the allowed beta decay in terms of a **logft**\nwhich stands for log$_{10}$ of the $ft_{1/2}$ value.\n\n     The values of the coupling constants for Fermi decay,\n$g_{V}$, and Gamow-Teller decay, $g_{A}$ are obtained as follows.\nFor a $0^{+} \\rightarrow  0^{+}$ nuclear transition $B(GT)=0$, and for a\ntransition between $  T=1  $ analogue states with $B(F)=2$ we find\n\n$$\nC = 2 t_{1/2} f.\n$$\n\nThe partial half-lives and $Q$ values for several $0^{+} \\rightarrow  0^{+}$ analogue\ntransitions have been measured to an accuracy of about one part in\n10000. With  phase space factors one obtains\n\n$$\nC = 6170(4)\n$$\n\nThis result, together with the value of $K_{o}$ can be used to obtain $g_{V}$.\n\n\nAt the quark level $g_{V}=-g_{A}$.\nBut for nuclear structure we use the value obtained from the\nneutron to proton beta decay\n\n$$\n\\vert g_{A}/g_{V}\\vert  = 1.261(8).\n$$\n\nThe operator for Fermi beta decay in terms of sums\nover the nucleons is\n\n$$\n{\\cal O}(F_{\\pm}) =  \\displaystyle\\sum _{k} t_{k\\pm}.\n$$\n\nThe matrix element is\n\n$$\nB(F) =\\, \\vert \\langle f\\vert  T_{\\pm} \\vert i\\rangle\\vert ^{2},\n$$\n\nwhere\n\n$$\nT_{\\pm} = \\sum _{k} t_{\\pm}\n$$\n\nis the total isospin raising and lowering operator for total\nisospin constructed out of the\nbasic nucleon isospin raising and lowering operators\n\n$$\nt_{-}\\vert n\\rangle=\\vert p\\rangle \\hspace{1cm} t_{-}\\vert p\\rangle= 0,\n$$\n\nand\n\n$$\nt_{+}\\vert p\\rangle=\\vert n\\rangle, \\;\\; t_{+}\\vert n\\rangle= 0.\n$$\n\nThe matrix elements obey the triangle\nconditions $J_{f}=J_{i}$ ($\\Delta J=0$). The Fermi operator has\n$\\pi _{O}=+1$, and thus the\ninitial and final nuclear states must have $\\pi _{i}\\pi _{f}=+1$ for\nthe matrix element to be\nnonzero under the parity transform.\n\nWhen isospin is conserved\nthe Fermi matrix element must obey the isospin triangle condition\n$T_{f}=T_{i}$ $(\\Delta T=0)$, and the Fermi operator can only connect\nisobaric analogue states.\n\n\n\nFor $\\beta_{-}$ decay\n\n1\n1\n0\n9\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n= \\sqrt{(T_{i}(T_{i}+1)-T_{zi}(T_{zi}-1)}\\vert \\omega _{i},J_{i},M_{i},T_{i},T_{zi}-1\\rangle,\n$$\n\nand\n\n1\n1\n1\n1\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n= [T_{i}(T_{i}+1)-T_{zi}(T_{zi}-1)]\n\\delta _{\\omega _{f},\\omega }\\;\\delta _{J_{i},J_{f}}\\;\\delta _{M_{i},M_{f}}\\;\\delta _{T_{i},T_{f}}.\n$$\n\nFor $\\beta_{ + }$ we have\n\n1\n1\n1\n3\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n= [T_{i}(T_{i}+1)-T_{zi}(T_{zi}+1)]\n\\delta _{\\omega _{f},\\omega }\\;\\delta _{J_{i},J_{f}}\\delta _{M_{i},M_{f}}\\delta _{T_{i},T_{f}}.\n$$\n\nFor neutron-rich nuclei ($N_{i}> Z_{i}$) we have $T_{i}=T_{zi}$ and thus\n\n$$\nB(F_{-})(N_{i}> Z_{i}) = 2T_{zi} = (N_{i}-Z_{i})\\delta _{\\omega _{f},\\omega }\\delta _{J_{i},J_{f}}\\;\\delta _{M_{i},M_{f}}\\;\\delta _{T_{i},T_{f}},\n$$\n\nand\n\n$$\nB(F_{+})(N_{i}> Z_{i}) = 0.\n$$\n\nThe reduced single-particle\nmatrix elements are given by\n\n$$\n\\langle k_{a},p\\vert\\vert \\sigma  t_{-}\\vert\\vert k_{b},n\\rangle=\\langle k_{a},n\\vert\\vert \\sigma  t_{+}\\vert\\vert k_{b},p\\rangle= 2\\langle k_{a}\\vert\\vert \\mathbf{s}\\vert\\vert k_{b}\\rangle,\n$$\n\nwhere the matrix elements of $\\mathbf{s}$ are given by\n\n1\n1\n1\n8\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n=(-1)^{l_{a}+j_{a}+3/2}\n\\sqrt{(2j_{a}+1)(2j_{b}+1)}\\left\\{\\begin{array}{ccc}  {1/2}&  {1/2}&  {1} \\\\ {j_{b}}&  {j_{a}}&  {l_{a}}\\end{array}\\right\\}\n\\langle s\\vert\\vert \\mathbf{s}\\,\\vert\\vert s\\rangle \\delta _{\\ell _{a},\\ell _{b}} \\delta_{n_{a},n_{b}}\n,\n$$\n\nwith\n\n$$\n\\langle s\\vert\\vert \\mathbf{s}\\vert\\vert s\\rangle= \\sqrt{3/2}.\n$$\n\nThe matrix elements of $\\mathbf{s}$ has the selection rules $\\delta_{ \\ell_{a} , \\ell_{b} }$\nand $\\delta_{n _{a} ,n _{b} }$. Thus the orbits which are connected by the GT operator\nare very selective; they are those in the same major oscillator shell\nwith the same $\\ell$ value. The matrix elements such as\n$1s_{1/2}-0d_{3/2}$ which have the allowed $\\Delta j$ coupling but\nare zero due to the $\\Delta\\ell$ coupling are called $\\ell$-**forbidden** matrix\nelements.\n\n\nSum rules for Fermi and Gamow-Teller matrix elements can be obtained easily.\n\nThe sum rule for Fermi is obtained from the sum\n\n$$\n\\sum _{f} \\left[ B_{fi}(F_{-}) - B_{fi}(F_{+}) \\right]\n=\\sum _{f} \\left[ \\vert \\langle f\\vert  T_{-} \\vert i\\rangle\\vert ^{2} -  \\vert \\langle f\\vert  T_{+} \\vert \ni\\rangle\\vert ^{2} \\right]\n$$\n\nThe final states $f$ in the $T_{-}$ matrix element go\nwith the $Z_{f}=Z_{i}+1$ nucleus and those in the $T_{+}$ matrix element\nto with the $Z_{f}=Z_{i}-1$ nucleus. One can explicitly sum over the\nfinal states to obtain\n\n1\n1\n2\n2\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n= \\langle i\\vert  T_{+} T_{-} -  T_{-} T_{+}\\vert i\\rangle =\\langle i\\vert  2T_{z}\\vert i\\rangle  = (N_{i}-Z_{i}).\n$$\n\nThe sum rule for Gamow-Teller is obtained as follows\n\n1\n1\n2\n4\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n1\n1\n2\n5\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n1\n1\n2\n6\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n1\n1\n2\n7\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n1\n1\n2\n8\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n=   3\\langle i\\vert  T_{+} T_{-} -  T_{-} T_{+}\\vert i\\rangle= 3\\langle i\\vert  2T_{z}\\vert i\\rangle  = 3(N_{i}-Z_{i}).\n$$\n\nWe have used the fact that $\\sigma ^{2}_{x} = \\sigma ^{2}_{y}=\\sigma ^{2}_{z}=1$.\nWhen $k \\neq k'$ the operators commute and cancel.\nThus\n\n$$\n\\sum_{f} \\left[B_{fi}(F_{-}) - B_{fi}(F_{+}) \\right] = (N_{i}-Z_{i}),\n$$\n\nand\n\n$$\n\\sum_{f} \\left[ B_{fi}(GT_{-}) - B_{fi}(GT_{+}) \\right] = 3(N_{i}-Z_{i}).\n$$\n\nThe sum-rule for the Fermi matrix elements applies even\nwhen isospin is not conserved.\n\n\nFor $N > Z$ we usually have\n$T_{i}=T_{zi}$ which means that $B(F_{+})=0$.\n\nFor $N=Z (T_{zi}=0)$ and $T_{i}=0$ we get \n$B(F_{+})=B(F_{-})=0$, and for $T_{i}=1$ we\nhave $B(F_{+}) = B(F_{-}) = 2$. Fermi transitions which would be zero\nif isospin is conserved are called isospin-forbidden Fermi transitions.\n\nWhen $N > Z$ there are some situations where one has $B(GT_{+})=0$,\nand then we obtain $B(GT_{-}) = 3(N_{i}-Z_{i})$. In particular\nfor the $\\beta_{-}$ decay of the neutron we have $B(F_{-})=1$\nand $B(GT_{-})=3$.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n## References\n\n<!-- BIBFILE: ../chapters/papers.pub -->\n", "meta": {"hexsha": "210432c41e5fda4ff99f22b3ec10e875c9fc78ec", "size": 788753, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/src/book/book.ipynb", "max_stars_repo_name": "ManyBodyPhysics/CQMech", "max_stars_repo_head_hexsha": "8395f082392844a0e2831649aab4108324c86312", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-06-18T14:34:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T14:44:41.000Z", "max_issues_repo_path": "doc/src/book/book.ipynb", "max_issues_repo_name": "ManyBodyPhysics/QuantumPhysics", "max_issues_repo_head_hexsha": "ab8c7a01cd4456af2a68311ccf1ded1272642040", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/src/book/book.ipynb", "max_forks_repo_name": "ManyBodyPhysics/QuantumPhysics", "max_forks_repo_head_hexsha": "ab8c7a01cd4456af2a68311ccf1ded1272642040", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-02-18T15:21:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-18T15:21:45.000Z", "avg_line_length": 31.4846319655, "max_line_length": 950, "alphanum_fraction": 0.4869534569, "converted": true, "num_tokens": 153932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733341443526055, "lm_q2_score": 0.10970577533337339, "lm_q1q2_score": 0.04468682804981057}}
{"text": "--- \nProject for the course in Microeconometrics | Summer 2019, M.Sc. Economics, Bonn University | [Annica Gehlen](https://github.com/amageh)\n\n# Replication of Jason M. Lindo, Nicholas J.  Sanders & Philip Oreopoulos  (2010) <a class=\"tocSkip\">   \n---\n\nThis notebook contains my replication of the results from the following paper:\n\n> Lindo, J. M., Sanders, N. J., & Oreopoulos, P. (2010). Ability, gender, and performance standards: Evidence from academic probation. American Economic Journal: Applied Economics, 2(2), 95-117.\n\n##### Downloading and viewing this notebook:\n\n* The best way to view this notebook is by downloading it and the repository it is located in from [GitHub](https://github.com/HumanCapitalAnalysis/template-course-project). Other viewing options like _MyBinder_ or _NBViewer_ may have issues with displaying images or coloring of certain parts (missing images can be viewed in the folder [files](https://github.com/HumanCapitalAnalysis/template-course-project/tree/master/files) on GitHub).\n\n\n* The original paper, as well as the data and code provided by the authors can be accessed [here](https://www.aeaweb.org/articles?id=10.1257/app.2.2.95).\n\n##### Information about replication and individual contributions:\n\n* For the replication, I try to remain true to the original structure of the paper so readers can easily follow along and compare. All tables and figures are named and labeled as they appear in Lindo et al. (2010).\n\n\n* The tables in my replication appear transposed compared to the original tables to suit my workflow in Python.\n\n\n* For transparency, all sections in the replication that constitute independent contributions by me and are not part of results presented (or include deviations from the methods used) in the paper are marked as _extensions_. \n\n<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#1.-Introduction\" data-toc-modified-id=\"1.-Introduction-1\">1. Introduction</a></span></li><li><span><a href=\"#2.-Theoretical-Background\" data-toc-modified-id=\"2.-Theoretical-Background-2\">2. Theoretical Background</a></span></li><li><span><a href=\"#3.-Identification\" data-toc-modified-id=\"3.-Identification-3\">3. Identification</a></span></li><li><span><a href=\"#4.-Empirical-Strategy\" data-toc-modified-id=\"4.-Empirical-Strategy-4\">4. Empirical Strategy</a></span></li><li><span><a href=\"#5.-Replication-of-Lindo-et-al.-(2010)\" data-toc-modified-id=\"5.-Replication-of-Lindo-et-al.-(2010)-5\">5. Replication of Lindo et al. (2010)</a></span><ul class=\"toc-item\"><li><span><a href=\"#5.1.-Data-&amp;-Descriptive-Statistics\" data-toc-modified-id=\"5.1.-Data-&amp;-Descriptive-Statistics-5.1\">5.1. Data &amp; Descriptive Statistics</a></span></li><li><span><a href=\"#5.2.-Results\" data-toc-modified-id=\"5.2.-Results-5.2\">5.2. Results</a></span><ul class=\"toc-item\"><li><span><a href=\"#5.2.1.-Tests-of-the-Validity-of-the-RD-Approach\" data-toc-modified-id=\"5.2.1.-Tests-of-the-Validity-of-the-RD-Approach-5.2.1\">5.2.1. Tests of the Validity of the RD Approach</a></span></li><li><span><a href=\"#i.--Extension:-Visual-Validity-Check\" data-toc-modified-id=\"i.--Extension:-Visual-Validity-Check-5.2.2\">i.  Extension: Visual Validity Check</a></span></li><li><span><a href=\"#ii.-Advanced-Validity-Check\" data-toc-modified-id=\"ii.-Advanced-Validity-Check-5.2.3\">ii. Advanced Validity Check</a></span></li><li><span><a href=\"#5.2.2.-First-Year-GPAs-and-Academic-Probation\" data-toc-modified-id=\"5.2.2.-First-Year-GPAs-and-Academic-Probation-5.2.4\">5.2.2. First Year GPAs and Academic Probation</a></span></li><li><span><a href=\"#5.2.3.-The-Immediate-Response-to-Academic-Probation\" data-toc-modified-id=\"5.2.3.-The-Immediate-Response-to-Academic-Probation-5.2.5\">5.2.3. The Immediate Response to Academic Probation</a></span></li><li><span><a href=\"#5.2.4.-The-Impact-onSubsequent-Performance\" data-toc-modified-id=\"5.2.4.-The-Impact-onSubsequent-Performance-5.2.6\">5.2.4. The Impact onSubsequent Performance</a></span></li><li><span><a href=\"#i.-Main-Results-for-Impact-on-GPA-&amp;-Probability-of-Placing-Above-Cutoff-in-the-Next-Term\" data-toc-modified-id=\"i.-Main-Results-for-Impact-on-GPA-&amp;-Probability-of-Placing-Above-Cutoff-in-the-Next-Term-5.2.7\">i. Main Results for Impact on GPA &amp; Probability of Placing Above Cutoff in the Next Term</a></span></li><li><span><a href=\"#ii.-Formal-Bound-Analysis-on-Subsequent-GPA-(partial-extension)\" data-toc-modified-id=\"ii.-Formal-Bound-Analysis-on-Subsequent-GPA-(partial-extension)-5.2.8\">ii. Formal Bound Analysis on Subsequent GPA (partial extension)</a></span></li><li><span><a href=\"#5.2.5.-The-Impacts-on-Graduation\" data-toc-modified-id=\"5.2.5.-The-Impacts-on-Graduation-5.2.9\">5.2.5. The Impacts on Graduation</a></span></li></ul></li></ul></li><li><span><a href=\"#6.-Extension:-Robustness-Checks\" data-toc-modified-id=\"6.-Extension:-Robustness-Checks-6\">6. Extension: Robustness Checks</a></span><ul class=\"toc-item\"><li><span><a href=\"#6.1.--A-Closer-Look-at-Students'-Subsequent-Performance.\" data-toc-modified-id=\"6.1.--A-Closer-Look-at-Students'-Subsequent-Performance.-6.1\">6.1.  A Closer Look at Students' Subsequent Performance.</a></span><ul class=\"toc-item\"><li><span><a href=\"#6.1.1.-Subsequent-Performance-and-Total-Credits-in-Year-2\" data-toc-modified-id=\"6.1.1.-Subsequent-Performance-and-Total-Credits-in-Year-2-6.1.1\">6.1.1. Subsequent Performance and Total Credits in Year 2</a></span></li><li><span><a href=\"#6.1.2.-Subsequent-Cumulative-Grade-Point-Average-(CGPA)\" data-toc-modified-id=\"6.1.2.-Subsequent-Cumulative-Grade-Point-Average-(CGPA)-6.1.2\">6.1.2. Subsequent Cumulative Grade Point Average (CGPA)</a></span></li></ul></li><li><span><a href=\"#6.2.-Bandwidth-Sensitivity\" data-toc-modified-id=\"6.2.-Bandwidth-Sensitivity-6.2\">6.2. Bandwidth Sensitivity</a></span></li></ul></li><li><span><a href=\"#7.-Conclusion\" data-toc-modified-id=\"7.-Conclusion-7\">7. Conclusion</a></span></li><li><span><a href=\"#8.-References\" data-toc-modified-id=\"8.-References-8\">8. References</a></span></li></ul></div>\n\n\n```python\n%matplotlib inline\nimport numpy as np\nimport pandas as pd\nimport pandas.io.formats.style\nimport seaborn as sns\nimport statsmodels as sm\nimport statsmodels.formula.api as smf\nimport statsmodels.api as sm_api\nimport matplotlib as plt\nfrom IPython.display import HTML\n```\n\n\n```python\nfrom auxiliary.example_project_auxiliary_predictions import *\nfrom auxiliary.example_project_auxiliary_plots import *\nfrom auxiliary.example_project_auxiliary_tables import *\n```\n\n---\n# 1. Introduction \n---\n\nLindo et al. (2010) examine the effects of academic probation on student outcomes using data from Canada. Academic probation is a university policy that aims to improve the performance of the lowest- scoring students. If a student's Grade Point Average (GPA) drops below a certain threshold, the student is placed on academic probation. The probation status serves as a warning and does not entail immediate consequences, however, if students fail to improve their grades during the following term, they face the threat of being suspended from the university. In a more general sense, academic probation may offer insights into how agents respond to negative incentives and the threat of punishment in a real-world context with high stakes. \n\nTo estimate the causal impact of being placed on probation, Lindo et al. (2010) apply a **regression discontinuity design (RDD)** to data retrieved from three campuses at a large Canadian university. The RDD is motivated by the idea that the students who score just above the threshold for being put on academic probation provide a good counterfactual to the 'treatment group' that scores just below the threshold. In line with the performance standard model that serves as the theoretical framework for the paper, Lindo et al. (2010) find that being placed on probation induces students to drop out but increases the grades of the students who remain in school. The authors also find large heterogeneities in the way different groups of students react to academic probation.\n\n**Main variables** \n\n| **Treatment**     | **Main outcomes**       | **Main Covariates**    |\n|-------------------|-------------------------|------------------------|\n| Academic probation| Drop-out rates          | Gender                 |\n| .                 | Subsequent performance  | HS grades              |                         \n| .                 | Graduation rates        | Native language        |\n\n \nIn this notebook, I replicate the results presented in the paper by Lindo et al. (2010). Furthermore, I discuss in detail the identification strategy used by the authors and evaluate the results using multiple robustness checks. My analysis offers general support for the findings of Lindo et al. (2010) and points out some factors which may enable a deeper understanding of the causal relationship explored in the paper. \n\nThis notebook is structured as follows. In the next section, I present the performance standard model that lays down the theoretical framework for the paper (Section 2). In Section 3, I analyze the identification strategy that Lindo et al. (2010) use to unravel the causal effects of academic probation on student outcomes and Section 4 briefly discusses the empirical strategy the authors use for estimation. Section 5 and Section 6 constitute the core of this notebook. Section 5 shows my replication of the results in the paper and discussion thereof. In Section 6 I conduct various robustness checks and discuss some limitations of the paper. Section 7 offers some concluding remarks. \n\n\n---\n# 2. Theoretical Background\n---\nThe underlying framework used for the analysis is a model developed by B\u00e9nabou and Tirole (2000) which models agent's responses to a performance standard. While B\u00e9nabou and Tirole (2000) model a game between a principal and an agent, Lindo et al. (2010) focus only on the agent to relate the model to the example of academic probation. \n\nIn the performance standard model, the agents face a choice between three options:\n 1. **Option 1**: Incurs cost $c_1$ and grants benefit $V_1$ if successful.\n 2. **Option 2**: Incurs cost $c_2$ and grants benefit $V_2$ if successful.\n 3. **Neither** option: Incurs 0 cost and 0 benefit.\n \nOption 1 has a lower cost and a lower benefit than option 2 such that:\n\n\\begin{equation}\n    0 < c_1 < c_2 ,  0 < V_1 < V_2.\n\\end{equation}\n\nAbility, denoted by $\\theta$, translates to the probability of successfully completing either option. Assuming agents have perfect information about their ability, they solve the maximizing problem\n\n\\begin{equation}\nmax\\{0, \\theta V_1-c_1, \\theta V_2-c_2\\}.\n\\end{equation}\n  \nLet $\\underline{\\theta}$ be the ability level where the agent is indifferent between neither and option two and let $\\bar{\\theta}$ be the ability level at which the agent is indifferent between option 1 and option 2. Assuming that\n\n\\begin{equation}\n\\underline{\\theta} \\equiv \\frac{c_1}{V_1} < \\bar{\\theta} \\equiv \\frac{c_2-c_1}{V_2-V1} < 1\n\\end{equation}\n\nensures that both options are optimal for at least some $\\theta$.\n\nIt can be shown that \n* the lowest ability types ($\\theta < \\underline{\\theta}$) choose neither option,\n* the highest ability types ($\\bar{\\theta} < \\theta$) choose the difficult option,\n* the individuals in between the high and low type $\\underline{\\theta}< \\theta < \\bar{\\theta} $) choose the easier option.\n\nIf the principal now removes option 1 or makes choosing this option much more costly, then the agent will choose option 2 if and only if\n\n\\begin{equation}\n\\theta \\ge \\frac{c_2}{V_2} \\equiv \\theta^*\n\\end{equation}\n\n\nand choose neither option otherwise. The agents who would have chosen option 1 now split according to ability. Agents with high ability (specifically those with $\\theta \\in [\\theta^*,\\bar{\\theta}]$) work harder, thereby choosing option 2, while low ability types (those with $\\theta \\in [\\underline{\\theta}, \\theta^*]$) do not pursue option 2 (and thus choose neither option).\n\nIn the context of academic probation students face a similar decision and possible courses of action. Students whose GPA is just above the probation cutoff face the full set of options for the next year:\n\n1. **Option 1**: Return to school and exhibit low effort and leading to a low GPA\n2. **Option 2**: Return to school and exhibit high effort with the intent of achieving a high GPA\n3. **Neither** option: Drop out of university\n\nStudents who score below the probation cutoff face a restricted set of options as the university administration essentially eliminates option 1 by suspending students if they do not improve their grades. \n\nLindo et al. (2010) formulate three testable implications of this theoretical framework: \n\n  * _Forbidding option 1 will **increase the overall probability of students dropping out**._\n  * _Forbidding option 1 will **increase the performance of those who return**._\n  * _Forbidding option 1 will cause **relatively low-ability students to drop out** and **relatively high-ability students to return and work harder**._\n\n---\n# 3. Identification\n--- \nLindo et al. (2010) in their paper aim to evaluate how academic probation affects students, specifically their probability of dropping out of university and whether it motivates those who remain to improve their grades. Students are placed on probation if their Grade Point Average (GPA) drops below a certain threshold and face the threat of suspension if they fail to improve their GPA in the next term. Students are thus clearly separated into a treated group (who is put on probation) and an untreated group based on their GPA. \n\nThe causal graph below illustrates the relationship between the assignment variable $X$, treatment $D$ and outcome $Y$. While $X$ (the GPA) directly assigns students to treatment, it may also be linked to student outcomes. Additionally, there may be observables $W$ and unobservables $U$ also affecting $X$,$D$, and $Y$. There are thus multiple backdoor paths that need to be closed in order to isolate the effect of academic probation. Simply controlling for the variables in question, in this case, does not suffice since there are unobservables that we cannot condition on. A randomized experiment, on the other hand, could eliminate selection bias in treatment by randomly assigning probation to students. The research question evaluated in the paper constitutes a classic policy evaluation problem in economics where we try to understand the causal implications of a policy without being able to observe the counterfactual world where the policy is not administered. However, as with many questions in economics, implementing a randomize experiment directly is not a feasible option, especially since we are examing the effect of a penalty whose consequences may affect students for the rest of their lives.\n\n\n\nSince it is not possible to randomize assignment to treatment, another method is needed to isolate the effects of academic probation on student outcomes. Lindo et al. (2010) apply a regression discontinuity design (RDD) to the problem at hand, a method pioneered by Thistlethwaite and Campbell (1960) in their analysis of the effects of scholarships on student outcomes. In fact, the identification problem in Lindo et al. (2010) is quite similar to that of Thistlethwaite and Campbell (1960) as both papers evaluate the causal effects of an academic policy on student outcomes. However, while the scholarship administered to high performing students in Thistlethwaite and Campbell (1960) constitutes a positive reinforcement for these students, Lindo et al. (2010) examine the effects of a negative reinforcement or penalty on low performing students. This means that, in contrast to Thistlethwaite and Campbell (1960) and many other applications of RD, our treatment group lies _below_ the cutoff and not above it. This does not change the causal inference of this model but it might be confusing to readers familiar with RD designs and should thus be kept in mind. \n\nThe regression discontinuity design relies on the assumption of local randomization, i.e. the idea that students who score just above the cutoff do not systematically differ from those who score below the cutoff and thus pose an appropriate control group for the students who are placed on probation. This identification strategy relies on the assumption that students are unable to precisely manipulate their grades to score just above or below the probation threshold. Within the neighborhood around the discontinuity threshold, the RDD thus in a sense mimics a randomized experiment. \n\nTo explain how the use of regression discontinuity allows Lindo et al. (2010) to identify treatment effects, I draw on material provided in Lee and Lemieux (2010) and their discussion on the RDD in the potential outcomes framework. As mentioned above, for each student $i$ we can image a potential outcome where they are placed on probation $Y_i(1)$ and where they are not $Y_i(0)$ but we can never simultaneously observe both outcomes for each student. Since it is impossible to observe treatment effects at the individual level, researchers thus estimate average effects using treatment and control groups. \n\nFor the RDD this potential outcomes framework translates by imagining there are two underlying relationships between the average student outcome and the assignment variable $X$ (the students' GPA), which are represented by $E[Y_i(1)|X]$ and $E[Y_i(0)|X]$. Since all students who score below the cutoff $c$ are placed on probation, we only observe $E[Y_i(1)|X]$ for those below the cutoff and $E[Y_i(0)|X]$ for those above the cutoff. \n\nWe can estimate the average treatment effects by taking the difference of the conditional expectations at the cutoff if these underlying functions are continuous throughout the cutoff:\n\n\\begin{equation}\nlim_{\\epsilon \\downarrow 0}E[Y_i|X_i=c+\\epsilon] - lim_{\\epsilon \\uparrow 0} E[Y_i|X_i=c+\\epsilon] \n    = E[Y_i(1)-Y_i(0)|X=c].\n\\end{equation}\n\nAs explained above, this _continuity assumption_ is fulfilled by the RDD because we can assume that students have _imprecise control_ over the assignment variable, their GPA. We can clearly identify the average treatment effects because there is a natural sharp cutoff at the threshold. The treatment administered to students is being confronted with the information that they are placed on probation and the subsequent threat of suspension. Being put on probation does not involve any actions by the students, in fact being assigned to the treatment group already constitutes the treatment in itself. Non-compliers thus do not pose a concern for this research design. \n\nAs the theoretical framework discussed in the prior section illustrates, students on probation face the decision of dropping out or trying to improve their performance in the next term. While the estimation on effects on dropping out using the regression discontinuity design is relatively straight forward, the estimation of effects for subsequent performance adds additional challenges.\n\n\n\nThe extended causal graph above illustrates how the subsequent performance of students is also affected by whether a student drops out or not. This factor adds additional complexity to the estimation problem because we cannot observe the subsequent GPA for students who drop out after being placed on probation. This factor puts into question the comparability of the treatment and control group in subsequent periods. I address these concerns and possible solutions in later sections of this notebook.\n\nAside from the two main outcomes, Lindo et al. (2010) also examine the effects of academic probation on graduation rates of students. However, since information about student's academic progress over the whole course of their studies is limited in the available data, only very simple analysis is possible. \n\n---\n# 4. Empirical Strategy\n---\nThe authors examine the impact of being put on probation after the first year in university. The probation status after the first year is a deterministic function of student's GPA, formally\n\n\\begin{equation}\nPROB^{year1}_{IC} = 1(GPANORM^{year1}_{IC} < 0),\n\\end{equation}\n\nwhere $PROB^{year1}_{IC}$ represents the probation status of student $i$ at campus $c$ and $GPANORM^{year1}_{IC}$ is the distance between student $i$'s first-year GPA and the probationary cutoff at their respective campus. The distance of first-year GPA from the threshold thus constitutes the *running variable* in this RD design. Normalizing the running variable in this way makes sense because the three campuses have different GPA thresholds for putting students on probation  (the threshold at campus 1 and 2 is 1.5, at campus 3 the threshold is 1.6), using the distance from the cutoff as the running variable instead allows Lindo et al. (2010) to pool the data from all three campuses.\n\nApplying the regression discontinuity design, the treatment effect for students near the threshold is obtained by comparing the outcomes of students just below the threshold to those just above the threshold.\n\nThe following equation can be used to estimate the effects of academic probation on subsequent student outcomes:\n\n\\begin{equation}\nY_{ic} = m(GPANORM_{ic}^{year1}) + \\delta1(GPANORM_{ic}^{year1}<0) + u_{ic} \n\\end{equation}\n\n* $Y_{ic}$ denotes the outcome for student $i$ at campus $c$, \n* $m(GPANORM_{ic}^{year1})$ is a continuous function of students' standardized first year GPAs,\n* $1(GPANORM_{ic}^{year1}<0)$ is an indicator function equal to 1 if the student's GPA is below the probation cutoff,\n* $u_{ic} $ is the error term,\n* $\\delta$ is the coefficient for the estimated impact of being placed on academic probation after the first year.\n\nFor the regression analysis, Lindo et al. (2010) extend the above equation by an interaction term and a constant:\n\n\\begin{equation}\nY_{ic} = \\alpha + \\delta1(GPANORM_{ic}^{year1}<0) + \\beta(GPANORM_{ic}^{year1}) \n                + \\gamma(GPANORM_{ic}^{year1})x 1(GPANORM_{ic}^{year1}<0) + u_{ic} \n\\end{equation}\n\n\nThis regression equation does not include covariates because Lindo et al. (2010) implement a split sample analysis for the covariates in the analysis. \n\n---\n# 5. Replication of Lindo et al. (2010)\n---\n\n## 5.1. Data & Descriptive Statistics\n\n\nLindo et al. (2010) filter the data to meet the following requirements:\n* Students high school grade measure is not missing,\n* Students entered university before the year 2004 ( to ensure they can be observed over a 2-year period),\n* Students are between 17 and 21 years of age at time of entry.\n* Distance from cutoff is maximally 0.6 (or 1.2).\n\nThe first three requirements are already fulfilled in the provided data. It should be noted that the high school measure is a student's average GPA in courses that are universally taken by high school students in the province. Thus all students that remain in the sample (84 % of the original data) attended high school in the province. This has the advantage that the high school measurement for all students is very comparable. An additional implication that should be taken note of for later interpretations is that this also implies that all students assessed in the study attended high school in the province. The group of 'nonnative' English speakers thus, for example, does not include students that moved to Canada after completing high school. \n\n\n```python\ndata_1 = pd.read_stata('data/data-performance-standards-1.dta')\ndata_2 = pd.read_stata('data/data-performance-standards-2.dta')\n```\n\n\n```python\ndata = pd.concat([data_1, data_2], axis=1)\ndata = prepare_data(data)\n```\n\n---\n<span style=\"color:orange\">**NOTE**:</span> The original data provided by the authors can be found [here](https://www.aeaweb.org/articles?id=10.1257/app.2.2.95). For this replication the data is split into two .dta-files due to size constraints.\n\n---\n\nAs shown in the graph below, the distance from the cutoff for university GPA in the provided dataset still spans from values of -1.6 to 2.8 as can be seen below. Lindo et al. (2010) use a bandwidth of *(-0.6, 0.6)* for regression results and a bandwidth of *(-1.2, 1.2)* for graphical analysis. \n\n\n```python\nplot_hist_GPA(data)\n```\n\n\n```python\n# Reduce sample to students within 1.2 points from cutoff.\nsample12 = data[abs(data['dist_from_cut']) < 1.2]\nsample12.reset_index(inplace=True)\nprint(\"A sample of students within 1.2 points from the cuttoff consits of\", len(sample12), \"observations.\")\n```\n\n    A sample of students within 1.2 points from the cuttoff consits of 25389 observations.\n\n\n\n```python\n# Reduce sample to students within 0.6 points from cutoff.\nsample06 = data[abs(data['dist_from_cut']) < 0.6]\nsample06.reset_index(inplace=True)\nprint(\"The final sample includes\", len(sample06), \"observations.\")\n```\n\n    The final sample includes 12530 observations.\n\n\nTable 1 shows the descriptive statistics of the main student characteristics and outcomes in the restricted sample with a bandwidth of 0.6 from the cutoff. The majority of students are female (62%) and native English speakers (72%). Students in the reduced sample on average placed in the 33rd percentile in high school. It should also be noted that quite a large number of students (35%) are placed on probation after the fist year. An additional 11% are placed on probation after the first year.\n\n#### Table 1- Summary statistics\n\n\n```python\ncreate_table1(sample06)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Mean</th>\n      <th>Standard Deviation</th>\n      <th>Description</th>\n      <th>Type</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>hsgrade_pct</td>\n      <td>33.33</td>\n      <td>23.29</td>\n      <td>High School Grade Percentile</td>\n      <td>Characteristics</td>\n    </tr>\n    <tr>\n      <td>totcredits_year1</td>\n      <td>4.43</td>\n      <td>0.53</td>\n      <td>Credits attempted first year</td>\n      <td>Characteristics</td>\n    </tr>\n    <tr>\n      <td>age_at_entry</td>\n      <td>18.72</td>\n      <td>0.74</td>\n      <td>Age at entry</td>\n      <td>Characteristics</td>\n    </tr>\n    <tr>\n      <td>male</td>\n      <td>0.38</td>\n      <td>0.48</td>\n      <td>Male</td>\n      <td>Characteristics</td>\n    </tr>\n    <tr>\n      <td>english</td>\n      <td>0.72</td>\n      <td>0.45</td>\n      <td>English is first language</td>\n      <td>Characteristics</td>\n    </tr>\n    <tr>\n      <td>bpl_north_america</td>\n      <td>0.87</td>\n      <td>0.34</td>\n      <td>Born in North America</td>\n      <td>Characteristics</td>\n    </tr>\n    <tr>\n      <td>loc_campus1</td>\n      <td>0.48</td>\n      <td>0.50</td>\n      <td>At Campus 1</td>\n      <td>Characteristics</td>\n    </tr>\n    <tr>\n      <td>loc_campus2</td>\n      <td>0.21</td>\n      <td>0.41</td>\n      <td>At Campus 2</td>\n      <td>Characteristics</td>\n    </tr>\n    <tr>\n      <td>loc_campus3</td>\n      <td>0.31</td>\n      <td>0.46</td>\n      <td>At Campus 3</td>\n      <td>Characteristics</td>\n    </tr>\n    <tr>\n      <td>dist_from_cut</td>\n      <td>0.11</td>\n      <td>0.33</td>\n      <td>Distance from cutoff in first year</td>\n      <td>Outcomes</td>\n    </tr>\n    <tr>\n      <td>probation_year1</td>\n      <td>0.35</td>\n      <td>0.48</td>\n      <td>On probation after first year</td>\n      <td>Outcomes</td>\n    </tr>\n    <tr>\n      <td>probation_ever</td>\n      <td>0.46</td>\n      <td>0.50</td>\n      <td>Ever on acad. probation</td>\n      <td>Outcomes</td>\n    </tr>\n    <tr>\n      <td>left_school</td>\n      <td>0.05</td>\n      <td>0.22</td>\n      <td>Left Uni after 1st evaluation</td>\n      <td>Outcomes</td>\n    </tr>\n    <tr>\n      <td>nextGPA</td>\n      <td>0.47</td>\n      <td>0.81</td>\n      <td>Distance from cutoff at next evaluation</td>\n      <td>Outcomes</td>\n    </tr>\n    <tr>\n      <td>suspended_ever</td>\n      <td>0.16</td>\n      <td>0.36</td>\n      <td>Ever suspended</td>\n      <td>Outcomes</td>\n    </tr>\n    <tr>\n      <td>gradin4</td>\n      <td>0.29</td>\n      <td>0.45</td>\n      <td>Graduated by year  4</td>\n      <td>Outcomes</td>\n    </tr>\n    <tr>\n      <td>gradin5</td>\n      <td>0.56</td>\n      <td>0.50</td>\n      <td>Graduated by year  5</td>\n      <td>Outcomes</td>\n    </tr>\n    <tr>\n      <td>gradin6</td>\n      <td>0.66</td>\n      <td>0.47</td>\n      <td>Graduated by year  6</td>\n      <td>Outcomes</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n##  5.2. Results\n\n### 5.2.1. Tests of the Validity of the RD Approach\n\nThe core motivation in the application of RD approaches is the idea, that the variation in treatment near the cutoff is random if subjects are unable to control the selection into treatment (Lee & Lemieux, 2010). This condition, if fulfilled, means the RDD can closely emulate a randomized experiment and allows researchers to identify the causal effects of treatment. \n\nFor evaluating the effects of academic probation on subsequent student outcomes, the RDD is thus a valid approach only if students are not able to precisely manipulate whether they score above or below the cutoff. Lindo et al. (2010) offer multiple arguments to address concerns about nonrandom sorting: \n\n1. The study focuses on first-year students, assuming this group of students is likely to be less familiar with the probation policy on campus. To verify their conjecture, the authors also conducted a survey in an introductory economics course which revealed that around 50 % of students were unsure of the probation cutoff at their campus. They also claim that this analysis showed no relationship between knowledge of probation cutoffs and students' grades. \n\n\n2. The authors also point out that most first-year courses span the entire year and most of the evaluation takes place at the end of the term which would make it difficult for students to purposely aim for performances slightly above the cutoff for academic probation.\n\n\n3. Finally, and most importantly, the implication of local randomization is testable. If nonrandom sorting were to be a problem, there should be a discontinuity in the distribution of grades at the cutoff with a disproportionate number of students scoring just above the cutoff. Additionally, all the covariates should be continuous throughout the cutoff to ensure that the group above the probation cutoff constitutes a realistic counterfactual for the treated group.\n\nIn the following section, I first conduct a brief visual and descriptive check of validity before presenting my replication of the validity checks conducted in Lindo et al. (2010).\n\n###  i.  Extension: Visual Validity Check\n\nTo check for discontinuities in the covariates and the distribution of students around the cutoff Lindo et al. (2010) use local linear regression analysis. Before implementing the rather extensive validity check conducted by Lindo et al. (2010) I show in this section that a rather simple descriptive and graphical analysis of the distribution of covariates already supports the assumption they are continuous throughout the threshold.\n\n#### Extension | Table - Descriptive Statistics of Treated and Untreated Group Close to the Cutoff\nThe table below shows the means of the different covariates at the limits of the cutoff from both sides (here within a bandwidth of 0.1 grade points). We can see that the means of the groups below and above the probation cutoff are very similar, even equal for some of the variables.\n\n\n```python\ncov_descriptives = describe_covariates_at_cutoff(sample06,bandwidth=0.1)\ncov_descriptives\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th colspan=\"2\" halign=\"left\">Below cutoff</th>\n      <th colspan=\"2\" halign=\"left\">Above cutoff</th>\n      <th>Description</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>Mean</th>\n      <th>Std.</th>\n      <th>Mean</th>\n      <th>Std.</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>hsgrade_pct</td>\n      <td>30.94</td>\n      <td>22.61</td>\n      <td>31.76</td>\n      <td>22.65</td>\n      <td>High School Grade Percentile</td>\n    </tr>\n    <tr>\n      <td>totcredits_year1</td>\n      <td>4.42</td>\n      <td>0.55</td>\n      <td>4.37</td>\n      <td>0.54</td>\n      <td>Credits attempted first year</td>\n    </tr>\n    <tr>\n      <td>age_at_entry</td>\n      <td>18.73</td>\n      <td>0.76</td>\n      <td>18.72</td>\n      <td>0.75</td>\n      <td>Age at entry</td>\n    </tr>\n    <tr>\n      <td>male</td>\n      <td>0.38</td>\n      <td>0.49</td>\n      <td>0.38</td>\n      <td>0.49</td>\n      <td>Male</td>\n    </tr>\n    <tr>\n      <td>english</td>\n      <td>0.70</td>\n      <td>0.46</td>\n      <td>0.72</td>\n      <td>0.45</td>\n      <td>English is first language</td>\n    </tr>\n    <tr>\n      <td>bpl_north_america</td>\n      <td>0.88</td>\n      <td>0.33</td>\n      <td>0.87</td>\n      <td>0.34</td>\n      <td>Born in North America</td>\n    </tr>\n    <tr>\n      <td>loc_campus1</td>\n      <td>0.44</td>\n      <td>0.50</td>\n      <td>0.45</td>\n      <td>0.50</td>\n      <td>At Campus 1</td>\n    </tr>\n    <tr>\n      <td>loc_campus2</td>\n      <td>0.22</td>\n      <td>0.42</td>\n      <td>0.21</td>\n      <td>0.41</td>\n      <td>At Campus 2</td>\n    </tr>\n    <tr>\n      <td>loc_campus3</td>\n      <td>0.34</td>\n      <td>0.47</td>\n      <td>0.34</td>\n      <td>0.47</td>\n      <td>At Campus 3</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n#### Extension | Figure - Distribution of Covariates throughout the Probation Cutoff\nThe figure below shows the means of the nine covariates in bins of size 0.5 (grade points). Similar to the descriptive table shown above, this visualization shows that there seem to be no apparent discontinuities in the distribution of students for any of the observable characteristics (graphs with bins of size 0.1 or 0.025 suggest the same).\n\n\n```python\nplot_covariates(data=data, descriptive_table=cov_descriptives,bins = 'dist_from_cut_med05')\n```\n\n### ii. Advanced Validity Check\n(as conducted by Lindo et al. (2010))\n\n#### Figure 1 | Distribution of Student Grades Relative to their Cutoff\n\nTo test the assumption of local randomization, Lindo et al. (2010) run a local linear regression on the distribution of students throughout the cutoff. As mentioned above, these should be continuous as a jump in the distribution of students around the cutoff would indicate that students can in some way manipulate their GPA to place above the cutoff. \n\nFor the analysis, the data (containing all observations within 1.2 GPA points from the cutoff) is sorted into bins of size 0.1. The bins contain their lower limit but not their upper limit. To replicate the result from Lindo et al. (2010), I calculate the frequency of each bin and then run a local linear regression with a bandwidth of 0.6 on the size of the bins. Figure 1 shows the bins and the predicted frequency for each bin. The results show that the distribution of grades seems to be continuous around the cutoff, suggesting that we can assume local randomization. \n\nThis method of testing the validity is especially useful because it could capture the effects of unobservables, whose influence we cannot otherwise test like we test for discontinuities in observable characteristics in the parts above and below. If all observable characteristics would show to be continuous throughout the cutoff but we could still observe a jump in the distribution of students above the cutoff, this would suggest that some unobservable characteristic distinguishes students above and below the probation threshold. Fortunately, the results shown below indicate that this is not the case supporting the RDD as a valid identification strategy.\n\n\n```python\nbin_frequency_fig1 = calculate_bin_frequency(sample12, \"dist_from_cut_med10\")\npredictions_fig1 = create_bin_frequency_predictions(bin_frequency_fig1, bin_frequency_fig1.bins.unique().round(4), 0.6)\nplot_figure1(bin_frequency_fig1, bin_frequency_fig1.bins.unique().round(4), predictions_fig1)\n```\n\n#### Table 2 - Estimated Discontinuities in Observable Characteristics \n\nTable 2 shows the results of local linear regression (using a bandwidth of 0.6) for a range of observable characteristics that are related to student outcomes. Significant discontinuities would indicate that students with certain characteristics might be able to manipulate their grades to score above the probation cutoff. Similar to the descriptive validity checks on covariates in the section, these results additionally support the validity of the RDD. Table 2 shows that the coefficient for scoring below the cutoff is insignificant at the 10% level for all covariates. \n\n\n```python\ntable2_variables = ('hsgrade_pct', 'totcredits_year1', 'age_at_entry', 'male', 'english', \n                    'bpl_north_america','loc_campus1', 'loc_campus2')\nregressors = ['const', 'gpalscutoff', 'gpaXgpalscutoff', 'gpaXgpagrcutoff']\n```\n\n\n```python\ntable2 = estimate_RDD_multiple_outcomes(sample06, table2_variables, regressors)\ntable2.style.applymap(color_pvalues, subset=['P-Value (1)', 'P-Value (0)'])\n```\n\n\n\n\n<style  type=\"text/css\" >\n    #T_5f87578a_83e5_11ea_95c3_bb23d54d891crow0_col1 {\n            color:  black;\n        }    #T_5f87578a_83e5_11ea_95c3_bb23d54d891crow0_col4 {\n            color:  darkorange;\n        }    #T_5f87578a_83e5_11ea_95c3_bb23d54d891crow1_col1 {\n            color:  black;\n        }    #T_5f87578a_83e5_11ea_95c3_bb23d54d891crow1_col4 {\n            color:  darkorange;\n        }    #T_5f87578a_83e5_11ea_95c3_bb23d54d891crow2_col1 {\n            color:  black;\n        }    #T_5f87578a_83e5_11ea_95c3_bb23d54d891crow2_col4 {\n            color:  darkorange;\n        }    #T_5f87578a_83e5_11ea_95c3_bb23d54d891crow3_col1 {\n            color:  black;\n        }    #T_5f87578a_83e5_11ea_95c3_bb23d54d891crow3_col4 {\n            color:  darkorange;\n        }    #T_5f87578a_83e5_11ea_95c3_bb23d54d891crow4_col1 {\n            color:  black;\n        }    #T_5f87578a_83e5_11ea_95c3_bb23d54d891crow4_col4 {\n            color:  darkorange;\n        }    #T_5f87578a_83e5_11ea_95c3_bb23d54d891crow5_col1 {\n            color:  black;\n        }    #T_5f87578a_83e5_11ea_95c3_bb23d54d891crow5_col4 {\n            color:  darkorange;\n        }    #T_5f87578a_83e5_11ea_95c3_bb23d54d891crow6_col1 {\n            color:  black;\n        }    #T_5f87578a_83e5_11ea_95c3_bb23d54d891crow6_col4 {\n            color:  darkorange;\n        }    #T_5f87578a_83e5_11ea_95c3_bb23d54d891crow7_col1 {\n            color:  black;\n        }    #T_5f87578a_83e5_11ea_95c3_bb23d54d891crow7_col4 {\n            color:  darkorange;\n        }</style><table id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891c\" ><thead>    <tr>        <th class=\"blank level0\" ></th>        <th class=\"col_heading level0 col0\" >GPA below cutoff (1)</th>        <th class=\"col_heading level0 col1\" >P-Value (1)</th>        <th class=\"col_heading level0 col2\" >Std.err (1)</th>        <th class=\"col_heading level0 col3\" >Intercept (0)</th>        <th class=\"col_heading level0 col4\" >P-Value (0)</th>        <th class=\"col_heading level0 col5\" >Std.err (0)</th>        <th class=\"col_heading level0 col6\" >Observations</th>    </tr>    <tr>        <th class=\"index_name level0\" >outcomes</th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>    </tr></thead><tbody>\n                <tr>\n                        <th id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891clevel0_row0\" class=\"row_heading level0 row0\" >hsgrade_pct</th>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow0_col0\" class=\"data row0 col0\" >0.45</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow0_col1\" class=\"data row0 col1\" >0.72</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow0_col2\" class=\"data row0 col2\" >1.259</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow0_col3\" class=\"data row0 col3\" >30.991</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow0_col4\" class=\"data row0 col4\" >0</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow0_col5\" class=\"data row0 col5\" >0.745</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow0_col6\" class=\"data row0 col6\" >12530</td>\n            </tr>\n            <tr>\n                        <th id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891clevel0_row1\" class=\"row_heading level0 row1\" >totcredits_year1</th>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow1_col0\" class=\"data row1 col0\" >0.024</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow1_col1\" class=\"data row1 col1\" >0.749</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow1_col2\" class=\"data row1 col2\" >0.076</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow1_col3\" class=\"data row1 col3\" >4.386</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow1_col4\" class=\"data row1 col4\" >0</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow1_col5\" class=\"data row1 col5\" >0.046</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow1_col6\" class=\"data row1 col6\" >12530</td>\n            </tr>\n            <tr>\n                        <th id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891clevel0_row2\" class=\"row_heading level0 row2\" >age_at_entry</th>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow2_col0\" class=\"data row2 col0\" >0.015</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow2_col1\" class=\"data row2 col1\" >0.641</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow2_col2\" class=\"data row2 col2\" >0.032</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow2_col3\" class=\"data row2 col3\" >18.719</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow2_col4\" class=\"data row2 col4\" >0</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow2_col5\" class=\"data row2 col5\" >0.021</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow2_col6\" class=\"data row2 col6\" >12530</td>\n            </tr>\n            <tr>\n                        <th id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891clevel0_row3\" class=\"row_heading level0 row3\" >male</th>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow3_col0\" class=\"data row3 col0\" >0</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow3_col1\" class=\"data row3 col1\" >0.989</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow3_col2\" class=\"data row3 col2\" >0.024</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow3_col3\" class=\"data row3 col3\" >0.374</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow3_col4\" class=\"data row3 col4\" >0</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow3_col5\" class=\"data row3 col5\" >0.012</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow3_col6\" class=\"data row3 col6\" >12530</td>\n            </tr>\n            <tr>\n                        <th id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891clevel0_row4\" class=\"row_heading level0 row4\" >english</th>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow4_col0\" class=\"data row4 col0\" >-0.037</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow4_col1\" class=\"data row4 col1\" >0.124</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow4_col2\" class=\"data row4 col2\" >0.024</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow4_col3\" class=\"data row4 col3\" >0.729</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow4_col4\" class=\"data row4 col4\" >0</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow4_col5\" class=\"data row4 col5\" >0.015</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow4_col6\" class=\"data row4 col6\" >12530</td>\n            </tr>\n            <tr>\n                        <th id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891clevel0_row5\" class=\"row_heading level0 row5\" >bpl_north_america</th>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow5_col0\" class=\"data row5 col0\" >0.017</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow5_col1\" class=\"data row5 col1\" >0.173</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow5_col2\" class=\"data row5 col2\" >0.013</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow5_col3\" class=\"data row5 col3\" >0.864</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow5_col4\" class=\"data row5 col4\" >0</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow5_col5\" class=\"data row5 col5\" >0.008</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow5_col6\" class=\"data row5 col6\" >12530</td>\n            </tr>\n            <tr>\n                        <th id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891clevel0_row6\" class=\"row_heading level0 row6\" >loc_campus1</th>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow6_col0\" class=\"data row6 col0\" >0.012</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow6_col1\" class=\"data row6 col1\" >0.724</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow6_col2\" class=\"data row6 col2\" >0.034</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow6_col3\" class=\"data row6 col3\" >0.444</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow6_col4\" class=\"data row6 col4\" >0</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow6_col5\" class=\"data row6 col5\" >0.022</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow6_col6\" class=\"data row6 col6\" >12530</td>\n            </tr>\n            <tr>\n                        <th id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891clevel0_row7\" class=\"row_heading level0 row7\" >loc_campus2</th>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow7_col0\" class=\"data row7 col0\" >-0.01</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow7_col1\" class=\"data row7 col1\" >0.719</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow7_col2\" class=\"data row7 col2\" >0.027</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow7_col3\" class=\"data row7 col3\" >0.217</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow7_col4\" class=\"data row7 col4\" >0</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow7_col5\" class=\"data row7 col5\" >0.018</td>\n                        <td id=\"T_5f87578a_83e5_11ea_95c3_bb23d54d891crow7_col6\" class=\"data row7 col6\" >12530</td>\n            </tr>\n    </tbody></table>\n\n\n\n---\n<span style=\"color:orange\">**NOTE**:</span> My results for 'Male' and 'Age at entry' are switched compared to the table presented in Lindo et al. (2010). Since the results are identical otherwise, I assume this difference stems from an error in the table formatting of the published paper.\n\n<span style=\"color:orange\">**NOTE**:</span> The p-values in all regression tables are color-coded to enhance readability:\n\n* P-values at the <span style=\"color:magenta\">10% level</span> are magenta,\n* P-values at the <span style=\"color:red\">5 % level</span> are red,\n* P-values at the <span style=\"color:orange\">1 % level</span> are orange.\n\nThe color-coding may not be visible in all viewing options for Jupyter Notebooks (e.g. MyBinder).\n\n---\n\n### 5.2.2. First Year GPAs and Academic Probation\n\nFigure 2 and Table 3 show the estimated discontinuity in probation status. Figure 2 and the first part of Table 3 show the estimated discontinuity for the probation status after the _first year_. The second part of Table 3 presents the results for the estimated effects of scoring below the cutoff on the probability of _ever_ being placed on academic probation.\n\nFigure 2 and part 1 of Table 3 verify that the discontinuity at the cutoff is **sharp**, i.e. all students whose GPA falls below the cutoff are placed on probation. For students below the cutoff, the probability of being placed on probation is 1, for students above the cutoff it is 0.\n\nIt should be noted that the estimated discontinuity at the cutoff is only approximately equal to 1 for all of the different subgroups, as the results in Part 1 of Table 3 show. The authors attribute this fact to administrative errors in the data reportage. \n\n#### Figure 2 - Porbation Status at the End of First Year\n\n\n```python\npredictions_fig2 = create_predictions(sample12, 'probation_year1', regressors, 0.6)\nplot_figure2(sample12, predictions_fig2)\n```\n\n#### Table 3 - Estimated Discontinuity in Probation Status\n\nTo estimate the discontinuity in probation status, the authors again use a bandwidth of 0.6 from the cutoff. In addition to the whole sample, they also estimate the discontinuities for certain subgroups within the selected bandwidth:\n\n* **high school grades below** and **above the median** (here, median refers to the median of the entire dataset (median: *50*) and not the median of the subset of students with a GPA within 0.6 grade points of the probation cutoff (the median for this set would be *28*))\n* **male** and **female** students\n* **english** native speakers and students with a different native language (**nonenglish**) \n\n\n```python\nsample_treat06 = sample06[sample06['dist_from_cut'] < 0]\nsample_untreat06 = sample06[sample06['dist_from_cut'] >= 0]\nsample06 = pd.concat([sample_untreat06, sample_treat06])\ngroups_dict_keys = ['All', 'HS Grades < median', 'HS Grades > median', 'Male', 'Female',\n                    'Native English', 'Nonnative English']\ngroups_dict_columns = ['const', 'lowHS', 'highHS','male', 'female', 'english', 'noenglish']\ngroups_dict_06 = create_groups_dict(sample06, groups_dict_keys, groups_dict_columns)\n```\n\n**Table 3 | Part 1 - Estimated Discontinuity in Probation Status for Year 1**\n\n\n\n```python\ntable3_1 = estimate_RDD_multiple_datasets(groups_dict_06, groups_dict_keys, 'probation_year1', regressors)\ntable3_1.style.applymap(color_pvalues, subset=['P-Value (1)', 'P-Value (0)'])\n```\n\n\n\n\n<style  type=\"text/css\" >\n    #T_6060aada_83e5_11ea_95c3_bb23d54d891crow0_col1 {\n            color:  darkorange;\n        }    #T_6060aada_83e5_11ea_95c3_bb23d54d891crow0_col4 {\n            color:  black;\n        }    #T_6060aada_83e5_11ea_95c3_bb23d54d891crow1_col1 {\n            color:  darkorange;\n        }    #T_6060aada_83e5_11ea_95c3_bb23d54d891crow1_col4 {\n            color:  black;\n        }    #T_6060aada_83e5_11ea_95c3_bb23d54d891crow2_col1 {\n            color:  darkorange;\n        }    #T_6060aada_83e5_11ea_95c3_bb23d54d891crow2_col4 {\n            color:  black;\n        }    #T_6060aada_83e5_11ea_95c3_bb23d54d891crow3_col1 {\n            color:  darkorange;\n        }    #T_6060aada_83e5_11ea_95c3_bb23d54d891crow3_col4 {\n            color:  black;\n        }    #T_6060aada_83e5_11ea_95c3_bb23d54d891crow4_col1 {\n            color:  darkorange;\n        }    #T_6060aada_83e5_11ea_95c3_bb23d54d891crow4_col4 {\n            color:  black;\n        }    #T_6060aada_83e5_11ea_95c3_bb23d54d891crow5_col1 {\n            color:  darkorange;\n        }    #T_6060aada_83e5_11ea_95c3_bb23d54d891crow5_col4 {\n            color:  black;\n        }    #T_6060aada_83e5_11ea_95c3_bb23d54d891crow6_col1 {\n            color:  darkorange;\n        }    #T_6060aada_83e5_11ea_95c3_bb23d54d891crow6_col4 {\n            color:  darkorange;\n        }</style><table id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891c\" ><thead>    <tr>        <th class=\"blank level0\" ></th>        <th class=\"col_heading level0 col0\" >GPA below cutoff (1)</th>        <th class=\"col_heading level0 col1\" >P-Value (1)</th>        <th class=\"col_heading level0 col2\" >Std.err (1)</th>        <th class=\"col_heading level0 col3\" >Intercept (0)</th>        <th class=\"col_heading level0 col4\" >P-Value (0)</th>        <th class=\"col_heading level0 col5\" >Std.err (0)</th>        <th class=\"col_heading level0 col6\" >Observations</th>    </tr>    <tr>        <th class=\"index_name level0\" >groups</th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>    </tr></thead><tbody>\n                <tr>\n                        <th id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891clevel0_row0\" class=\"row_heading level0 row0\" >All</th>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow0_col0\" class=\"data row0 col0\" >0.994</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow0_col1\" class=\"data row0 col1\" >0</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow0_col2\" class=\"data row0 col2\" >0.002</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow0_col3\" class=\"data row0 col3\" >0.001</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow0_col4\" class=\"data row0 col4\" >0.157</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow0_col5\" class=\"data row0 col5\" >0.001</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow0_col6\" class=\"data row0 col6\" >12530</td>\n            </tr>\n            <tr>\n                        <th id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891clevel0_row1\" class=\"row_heading level0 row1\" >HS Grades < median</th>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow1_col0\" class=\"data row1 col0\" >0.995</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow1_col1\" class=\"data row1 col1\" >0</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow1_col2\" class=\"data row1 col2\" >0.002</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow1_col3\" class=\"data row1 col3\" >0.001</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow1_col4\" class=\"data row1 col4\" >0.183</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow1_col5\" class=\"data row1 col5\" >0.001</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow1_col6\" class=\"data row1 col6\" >9473</td>\n            </tr>\n            <tr>\n                        <th id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891clevel0_row2\" class=\"row_heading level0 row2\" >HS Grades > median</th>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow2_col0\" class=\"data row2 col0\" >0.99</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow2_col1\" class=\"data row2 col1\" >0</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow2_col2\" class=\"data row2 col2\" >0.006</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow2_col3\" class=\"data row2 col3\" >0.001</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow2_col4\" class=\"data row2 col4\" >0.317</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow2_col5\" class=\"data row2 col5\" >0.001</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow2_col6\" class=\"data row2 col6\" >3057</td>\n            </tr>\n            <tr>\n                        <th id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891clevel0_row3\" class=\"row_heading level0 row3\" >Male</th>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow3_col0\" class=\"data row3 col0\" >0.99</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow3_col1\" class=\"data row3 col1\" >0</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow3_col2\" class=\"data row3 col2\" >0.005</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow3_col3\" class=\"data row3 col3\" >0.001</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow3_col4\" class=\"data row3 col4\" >0.319</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow3_col5\" class=\"data row3 col5\" >0.001</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow3_col6\" class=\"data row3 col6\" >4701</td>\n            </tr>\n            <tr>\n                        <th id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891clevel0_row4\" class=\"row_heading level0 row4\" >Female</th>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow4_col0\" class=\"data row4 col0\" >0.996</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow4_col1\" class=\"data row4 col1\" >0</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow4_col2\" class=\"data row4 col2\" >0.002</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow4_col3\" class=\"data row4 col3\" >0.001</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow4_col4\" class=\"data row4 col4\" >0.179</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow4_col5\" class=\"data row4 col5\" >0.001</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow4_col6\" class=\"data row4 col6\" >7829</td>\n            </tr>\n            <tr>\n                        <th id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891clevel0_row5\" class=\"row_heading level0 row5\" >Native English</th>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow5_col0\" class=\"data row5 col0\" >0.993</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow5_col1\" class=\"data row5 col1\" >0</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow5_col2\" class=\"data row5 col2\" >0.002</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow5_col3\" class=\"data row5 col3\" >0.001</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow5_col4\" class=\"data row5 col4\" >0.16</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow5_col5\" class=\"data row5 col5\" >0.001</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow5_col6\" class=\"data row5 col6\" >9006</td>\n            </tr>\n            <tr>\n                        <th id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891clevel0_row6\" class=\"row_heading level0 row6\" >Nonnative English</th>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow6_col0\" class=\"data row6 col0\" >0.997</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow6_col1\" class=\"data row6 col1\" >0</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow6_col2\" class=\"data row6 col2\" >0.003</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow6_col3\" class=\"data row6 col3\" >0</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow6_col4\" class=\"data row6 col4\" >0</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow6_col5\" class=\"data row6 col5\" >0</td>\n                        <td id=\"T_6060aada_83e5_11ea_95c3_bb23d54d891crow6_col6\" class=\"data row6 col6\" >3524</td>\n            </tr>\n    </tbody></table>\n\n\n\n**Table 3 | Part 2 - Estimated Discontinuity in Probabtion Status Ever**\n\nPart 2 of Table 3 presents the estimated effect of scoring below the cutoff in the first year for _ever_ being placed on probation. The results show that even of those who score slightly above the probation cutoff in year 1, 33 % are placed on probation at some other point in time during their studies. \n\nFor the different subgroups of students this value varies from 29% (for students with high school grades above the median) up to 36.7% (for the group of males). These results already indicate that we can expect heterogeneities in the way different students react to being placed on academic probation.\n\nThe fact that it is not unlikely for low performing students just slightly above the cutoff to fall below it later on also underlines these student's fitness as a control group for the purpose of the analysis. Lindo et al. (2010) argue that the controls can be thought of as receiving a much weaker form of treatment than the group that is placed on probation, as scoring just above the cutoff in year 1 does not save students from falling below the cutoff and being placed on probation in subsequent terms. \n\n\n```python\ntable3_1 = estimate_RDD_multiple_datasets(groups_dict_06, groups_dict_keys,'probation_ever',regressors)\ntable3_1.style.applymap(color_pvalues, subset=['P-Value (1)', 'P-Value (0)'])\n```\n\n\n\n\n<style  type=\"text/css\" >\n    #T_60794234_83e5_11ea_95c3_bb23d54d891crow0_col1 {\n            color:  darkorange;\n        }    #T_60794234_83e5_11ea_95c3_bb23d54d891crow0_col4 {\n            color:  darkorange;\n        }    #T_60794234_83e5_11ea_95c3_bb23d54d891crow1_col1 {\n            color:  darkorange;\n        }    #T_60794234_83e5_11ea_95c3_bb23d54d891crow1_col4 {\n            color:  darkorange;\n        }    #T_60794234_83e5_11ea_95c3_bb23d54d891crow2_col1 {\n            color:  darkorange;\n        }    #T_60794234_83e5_11ea_95c3_bb23d54d891crow2_col4 {\n            color:  darkorange;\n        }    #T_60794234_83e5_11ea_95c3_bb23d54d891crow3_col1 {\n            color:  darkorange;\n        }    #T_60794234_83e5_11ea_95c3_bb23d54d891crow3_col4 {\n            color:  darkorange;\n        }    #T_60794234_83e5_11ea_95c3_bb23d54d891crow4_col1 {\n            color:  darkorange;\n        }    #T_60794234_83e5_11ea_95c3_bb23d54d891crow4_col4 {\n            color:  darkorange;\n        }    #T_60794234_83e5_11ea_95c3_bb23d54d891crow5_col1 {\n            color:  darkorange;\n        }    #T_60794234_83e5_11ea_95c3_bb23d54d891crow5_col4 {\n            color:  darkorange;\n        }    #T_60794234_83e5_11ea_95c3_bb23d54d891crow6_col1 {\n            color:  darkorange;\n        }    #T_60794234_83e5_11ea_95c3_bb23d54d891crow6_col4 {\n            color:  darkorange;\n        }</style><table id=\"T_60794234_83e5_11ea_95c3_bb23d54d891c\" ><thead>    <tr>        <th class=\"blank level0\" ></th>        <th class=\"col_heading level0 col0\" >GPA below cutoff (1)</th>        <th class=\"col_heading level0 col1\" >P-Value (1)</th>        <th class=\"col_heading level0 col2\" >Std.err (1)</th>        <th class=\"col_heading level0 col3\" >Intercept (0)</th>        <th class=\"col_heading level0 col4\" >P-Value (0)</th>        <th class=\"col_heading level0 col5\" >Std.err (0)</th>        <th class=\"col_heading level0 col6\" >Observations</th>    </tr>    <tr>        <th class=\"index_name level0\" >groups</th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>    </tr></thead><tbody>\n                <tr>\n                        <th id=\"T_60794234_83e5_11ea_95c3_bb23d54d891clevel0_row0\" class=\"row_heading level0 row0\" >All</th>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow0_col0\" class=\"data row0 col0\" >0.665</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow0_col1\" class=\"data row0 col1\" >0</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow0_col2\" class=\"data row0 col2\" >0.014</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow0_col3\" class=\"data row0 col3\" >0.33</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow0_col4\" class=\"data row0 col4\" >0</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow0_col5\" class=\"data row0 col5\" >0.014</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow0_col6\" class=\"data row0 col6\" >12530</td>\n            </tr>\n            <tr>\n                        <th id=\"T_60794234_83e5_11ea_95c3_bb23d54d891clevel0_row1\" class=\"row_heading level0 row1\" >HS Grades < median</th>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow1_col0\" class=\"data row1 col0\" >0.653</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow1_col1\" class=\"data row1 col1\" >0</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow1_col2\" class=\"data row1 col2\" >0.014</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow1_col3\" class=\"data row1 col3\" >0.343</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow1_col4\" class=\"data row1 col4\" >0</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow1_col5\" class=\"data row1 col5\" >0.014</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow1_col6\" class=\"data row1 col6\" >9473</td>\n            </tr>\n            <tr>\n                        <th id=\"T_60794234_83e5_11ea_95c3_bb23d54d891clevel0_row2\" class=\"row_heading level0 row2\" >HS Grades > median</th>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow2_col0\" class=\"data row2 col0\" >0.705</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow2_col1\" class=\"data row2 col1\" >0</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow2_col2\" class=\"data row2 col2\" >0.023</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow2_col3\" class=\"data row2 col3\" >0.286</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow2_col4\" class=\"data row2 col4\" >0</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow2_col5\" class=\"data row2 col5\" >0.022</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow2_col6\" class=\"data row2 col6\" >3057</td>\n            </tr>\n            <tr>\n                        <th id=\"T_60794234_83e5_11ea_95c3_bb23d54d891clevel0_row3\" class=\"row_heading level0 row3\" >Male</th>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow3_col0\" class=\"data row3 col0\" >0.625</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow3_col1\" class=\"data row3 col1\" >0</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow3_col2\" class=\"data row3 col2\" >0.016</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow3_col3\" class=\"data row3 col3\" >0.366</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow3_col4\" class=\"data row3 col4\" >0</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow3_col5\" class=\"data row3 col5\" >0.015</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow3_col6\" class=\"data row3 col6\" >4701</td>\n            </tr>\n            <tr>\n                        <th id=\"T_60794234_83e5_11ea_95c3_bb23d54d891clevel0_row4\" class=\"row_heading level0 row4\" >Female</th>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow4_col0\" class=\"data row4 col0\" >0.69</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow4_col1\" class=\"data row4 col1\" >0</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow4_col2\" class=\"data row4 col2\" >0.017</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow4_col3\" class=\"data row4 col3\" >0.308</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow4_col4\" class=\"data row4 col4\" >0</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow4_col5\" class=\"data row4 col5\" >0.017</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow4_col6\" class=\"data row4 col6\" >7829</td>\n            </tr>\n            <tr>\n                        <th id=\"T_60794234_83e5_11ea_95c3_bb23d54d891clevel0_row5\" class=\"row_heading level0 row5\" >Native English</th>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow5_col0\" class=\"data row5 col0\" >0.677</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow5_col1\" class=\"data row5 col1\" >0</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow5_col2\" class=\"data row5 col2\" >0.016</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow5_col3\" class=\"data row5 col3\" >0.317</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow5_col4\" class=\"data row5 col4\" >0</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow5_col5\" class=\"data row5 col5\" >0.016</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow5_col6\" class=\"data row5 col6\" >9006</td>\n            </tr>\n            <tr>\n                        <th id=\"T_60794234_83e5_11ea_95c3_bb23d54d891clevel0_row6\" class=\"row_heading level0 row6\" >Nonnative English</th>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow6_col0\" class=\"data row6 col0\" >0.635</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow6_col1\" class=\"data row6 col1\" >0</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow6_col2\" class=\"data row6 col2\" >0.023</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow6_col3\" class=\"data row6 col3\" >0.362</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow6_col4\" class=\"data row6 col4\" >0</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow6_col5\" class=\"data row6 col5\" >0.022</td>\n                        <td id=\"T_60794234_83e5_11ea_95c3_bb23d54d891crow6_col6\" class=\"data row6 col6\" >3524</td>\n            </tr>\n    </tbody></table>\n\n\n\n### 5.2.3. The Immediate Response to Academic Probation \n\nStudents who have been placed on academic probation enter their next term at university with the threat of suspension in case they fail to improve their grades. Recalling the theoretical framework presented in prior sections, students face the following set of options after each term:\n\n1. **Option 1**: Return to school, exhibit low effort and achieving a low GPA,\n2. **Option 2**: Return to school, exhibit high effort with the intent of achieving a high GPA,\n3. **Neither** option: Drop out of university.\n\nStudents on probation face a different set of choices than the students that were not placed on probation as the threat of suspension essentially eliminates option 1. Of course, students could enter the next term, exhibit low effort, and receive low grades, but this would result in suspension. Since both option 1 and option 3 result in the student not continuing school (at least for a certain period of time), students who cannot meet the performance standard (thus leading to suspension) are much better off dropping out and saving themselves the cost of attending university for another term.\n\n#### Table 4 - Estimated Effect on the Decision to Leave after the First Evaluation\n\n\n```python\ntable4 = estimate_RDD_multiple_datasets(groups_dict_06, groups_dict_keys, 'left_school', regressors)\ntable4.style.applymap(color_pvalues, subset=['P-Value (1)', 'P-Value (0)'])\n```\n\n\n\n\n<style  type=\"text/css\" >\n    #T_6092a792_83e5_11ea_95c3_bb23d54d891crow0_col1 {\n            color:  red;\n        }    #T_6092a792_83e5_11ea_95c3_bb23d54d891crow0_col4 {\n            color:  darkorange;\n        }    #T_6092a792_83e5_11ea_95c3_bb23d54d891crow1_col1 {\n            color:  black;\n        }    #T_6092a792_83e5_11ea_95c3_bb23d54d891crow1_col4 {\n            color:  darkorange;\n        }    #T_6092a792_83e5_11ea_95c3_bb23d54d891crow2_col1 {\n            color:  magenta;\n        }    #T_6092a792_83e5_11ea_95c3_bb23d54d891crow2_col4 {\n            color:  darkorange;\n        }    #T_6092a792_83e5_11ea_95c3_bb23d54d891crow3_col1 {\n            color:  red;\n        }    #T_6092a792_83e5_11ea_95c3_bb23d54d891crow3_col4 {\n            color:  darkorange;\n        }    #T_6092a792_83e5_11ea_95c3_bb23d54d891crow4_col1 {\n            color:  black;\n        }    #T_6092a792_83e5_11ea_95c3_bb23d54d891crow4_col4 {\n            color:  darkorange;\n        }    #T_6092a792_83e5_11ea_95c3_bb23d54d891crow5_col1 {\n            color:  darkorange;\n        }    #T_6092a792_83e5_11ea_95c3_bb23d54d891crow5_col4 {\n            color:  darkorange;\n        }    #T_6092a792_83e5_11ea_95c3_bb23d54d891crow6_col1 {\n            color:  black;\n        }    #T_6092a792_83e5_11ea_95c3_bb23d54d891crow6_col4 {\n            color:  darkorange;\n        }</style><table id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891c\" ><thead>    <tr>        <th class=\"blank level0\" ></th>        <th class=\"col_heading level0 col0\" >GPA below cutoff (1)</th>        <th class=\"col_heading level0 col1\" >P-Value (1)</th>        <th class=\"col_heading level0 col2\" >Std.err (1)</th>        <th class=\"col_heading level0 col3\" >Intercept (0)</th>        <th class=\"col_heading level0 col4\" >P-Value (0)</th>        <th class=\"col_heading level0 col5\" >Std.err (0)</th>        <th class=\"col_heading level0 col6\" >Observations</th>    </tr>    <tr>        <th class=\"index_name level0\" >groups</th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>    </tr></thead><tbody>\n                <tr>\n                        <th id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891clevel0_row0\" class=\"row_heading level0 row0\" >All</th>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow0_col0\" class=\"data row0 col0\" >0.018</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow0_col1\" class=\"data row0 col1\" >0.01</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow0_col2\" class=\"data row0 col2\" >0.007</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow0_col3\" class=\"data row0 col3\" >0.041</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow0_col4\" class=\"data row0 col4\" >0</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow0_col5\" class=\"data row0 col5\" >0.004</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow0_col6\" class=\"data row0 col6\" >12530</td>\n            </tr>\n            <tr>\n                        <th id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891clevel0_row1\" class=\"row_heading level0 row1\" >HS Grades < median</th>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow1_col0\" class=\"data row1 col0\" >0.013</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow1_col1\" class=\"data row1 col1\" >0.107</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow1_col2\" class=\"data row1 col2\" >0.008</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow1_col3\" class=\"data row1 col3\" >0.045</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow1_col4\" class=\"data row1 col4\" >0</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow1_col5\" class=\"data row1 col5\" >0.005</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow1_col6\" class=\"data row1 col6\" >9473</td>\n            </tr>\n            <tr>\n                        <th id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891clevel0_row2\" class=\"row_heading level0 row2\" >HS Grades > median</th>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow2_col0\" class=\"data row2 col0\" >0.032</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow2_col1\" class=\"data row2 col1\" >0.058</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow2_col2\" class=\"data row2 col2\" >0.017</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow2_col3\" class=\"data row2 col3\" >0.026</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow2_col4\" class=\"data row2 col4\" >0</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow2_col5\" class=\"data row2 col5\" >0.007</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow2_col6\" class=\"data row2 col6\" >3057</td>\n            </tr>\n            <tr>\n                        <th id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891clevel0_row3\" class=\"row_heading level0 row3\" >Male</th>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow3_col0\" class=\"data row3 col0\" >0.037</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow3_col1\" class=\"data row3 col1\" >0.014</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow3_col2\" class=\"data row3 col2\" >0.015</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow3_col3\" class=\"data row3 col3\" >0.038</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow3_col4\" class=\"data row3 col4\" >0</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow3_col5\" class=\"data row3 col5\" >0.007</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow3_col6\" class=\"data row3 col6\" >4701</td>\n            </tr>\n            <tr>\n                        <th id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891clevel0_row4\" class=\"row_heading level0 row4\" >Female</th>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow4_col0\" class=\"data row4 col0\" >0.006</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow4_col1\" class=\"data row4 col1\" >0.53</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow4_col2\" class=\"data row4 col2\" >0.009</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow4_col3\" class=\"data row4 col3\" >0.043</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow4_col4\" class=\"data row4 col4\" >0</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow4_col5\" class=\"data row4 col5\" >0.004</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow4_col6\" class=\"data row4 col6\" >7829</td>\n            </tr>\n            <tr>\n                        <th id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891clevel0_row5\" class=\"row_heading level0 row5\" >Native English</th>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow5_col0\" class=\"data row5 col0\" >0.028</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow5_col1\" class=\"data row5 col1\" >0.003</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow5_col2\" class=\"data row5 col2\" >0.01</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow5_col3\" class=\"data row5 col3\" >0.047</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow5_col4\" class=\"data row5 col4\" >0</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow5_col5\" class=\"data row5 col5\" >0.005</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow5_col6\" class=\"data row5 col6\" >9006</td>\n            </tr>\n            <tr>\n                        <th id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891clevel0_row6\" class=\"row_heading level0 row6\" >Nonnative English</th>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow6_col0\" class=\"data row6 col0\" >-0.004</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow6_col1\" class=\"data row6 col1\" >0.713</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow6_col2\" class=\"data row6 col2\" >0.011</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow6_col3\" class=\"data row6 col3\" >0.025</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow6_col4\" class=\"data row6 col4\" >0</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow6_col5\" class=\"data row6 col5\" >0.007</td>\n                        <td id=\"T_6092a792_83e5_11ea_95c3_bb23d54d891crow6_col6\" class=\"data row6 col6\" >3524</td>\n            </tr>\n    </tbody></table>\n\n\n\nThe results presented in Table 4 and and Figure 3 show the effects of being placed on probation on the probability to drop out of school after the first evaluation. The first row of Table 4 shows the average effect of academic probation on this outcome. The results indicate that, on average, being placed on probation increases the probability of leaving university by 1.8 percentage points. A student on academic probation is thus 44% more likely to drop out than their control group counterpart.\n\nThe results presented in the rest of Table 4 and and Figure 3 show that the average effect of being placed on probation is also characterized by large heterogeneities between the different subgroups of students. For males and native English speakers, the results, which are significant at the 5% level, show an increase of 3.7 and 2.8 percentage points respectively in the probability of leaving university after being placed on probation after the first evaluation. The results show no significant effects for these group's counterparts, the subgroups of females and nonnative English speakers. \n\nAside from gender and native language, the results also indicate that high school performance seems to play a role in how students react on being placed on probation. For the group of students who scored above the median in high school academic probation roughly doubles the probability of leaving school compared to the control group while there is no such effect for students who scored below the median in high school. Lindo et al. (2010) contribute this finding to a discouragement effect for those students who are placed on probation, which seems to be larger for students who did well in high school.\n\n#### Figure 3 - Stratified Results for Voluntarily Leaving School at the End of the First year\n\n\n```python\ngroups_dict_12 = create_groups_dict(sample12, groups_dict_keys, groups_dict_columns)\npredictions_groups_dict = create_fig3_predictions(groups_dict_12, regressors, 0.6)\nplot_figure3(groups_dict_12, predictions_groups_dict, groups_dict_keys)\n```\n\n### 5.2.4. The Impact onSubsequent Performance\n\n### i. Main Results for Impact on GPA & Probability of Placing Above Cutoff in the Next Term\n\nThe next outcome Lindo et al. (2010) analyze is the performance of students who stayed at university for the next term. The theoretical framework presented in Section 2 predicts that those students on probation who stay at university will try to improve their GPA. Indeed, if they do not manage to improve, they will be suspended and could have saved themselves the effort by dropping out.\n\nThe results presented in Figure 4 and Table 5 show the estimated discontinuity in subsequent GPA. Lindo et al. (2010) find significant results (at the 5% level) for all subgroups, which is an even bigger effect than that of probation on drop out rates, where only some subgroups were affected. \n\n#### Figure 4 - GPA in the Next Enrolled Term\n\n\n```python\npredictions_fig4 = create_predictions(sample12, 'nextGPA', regressors, 0.6)\nplot_figure4(sample12, predictions_fig4)\n```\n\nAs part A of Table 5 shows, the average treatment effect on the GPA in the next term is positive for all groups of students. The average student on probation has a GPA increase of 0.23 grade points which is 74% of the control group. \n\nThe increase is greatest for students who have high school grades below the median. These students increase their GPA by 0.25 grade points on average, 90% more than their control group. This is an interesting finding because the counterpart, students who scored above the median in high school, are especially likely to drop out. Thus high school grades seem to have a large effect on whether students perceive academic probation as discouragement or as an incentive to improve their performance. \n\nIt should be noted here, that the '*next term*' may not be the next year for all students because some students take summer classes. If students fail to improve their grades during summer classes, they are already suspended after summer and will not enter the second year. Only using grades from the second year would thus omit students who were suspended before even entering the second year. The existence of summer classes may complicate the comparability of students after being put on probation. However, in a footnote Lindo et al. (2010) mention that they find no statistically significant impact of academic probation on the probability that a student enrolls in summer classes and the estimates for subsequent GPA are nearly identical when controlling for whether a student's next term was attending a summer class.\n\n---\n<span style=\"color:orange\">**NOTE**:</span> Lindo et al. (2010) in this call this the '*improvement*' of students' GPA, however, this phrasing in my opinion could be misleading, as the dependent variable in this analysis is the distance from cutoff in the next term. The results thus capture the increase in subsequent GPA in general and not relative to the GPA in the prior term.\n\n---\n\n#### Table 5 - Estimated Discontinuites in Subsequent GPA | Part A - Next Term GPA\n\n\n```python\ntable5 = estimate_RDD_multiple_datasets(groups_dict_06, groups_dict_keys, 'nextGPA', regressors)\ntable5.style.applymap(color_pvalues, subset=['P-Value (1)', 'P-Value (0)'])\n```\n\n\n\n\n<style  type=\"text/css\" >\n    #T_665f8776_83e5_11ea_95c3_bb23d54d891crow0_col1 {\n            color:  darkorange;\n        }    #T_665f8776_83e5_11ea_95c3_bb23d54d891crow0_col4 {\n            color:  darkorange;\n        }    #T_665f8776_83e5_11ea_95c3_bb23d54d891crow1_col1 {\n            color:  darkorange;\n        }    #T_665f8776_83e5_11ea_95c3_bb23d54d891crow1_col4 {\n            color:  darkorange;\n        }    #T_665f8776_83e5_11ea_95c3_bb23d54d891crow2_col1 {\n            color:  red;\n        }    #T_665f8776_83e5_11ea_95c3_bb23d54d891crow2_col4 {\n            color:  darkorange;\n        }    #T_665f8776_83e5_11ea_95c3_bb23d54d891crow3_col1 {\n            color:  darkorange;\n        }    #T_665f8776_83e5_11ea_95c3_bb23d54d891crow3_col4 {\n            color:  darkorange;\n        }    #T_665f8776_83e5_11ea_95c3_bb23d54d891crow4_col1 {\n            color:  darkorange;\n        }    #T_665f8776_83e5_11ea_95c3_bb23d54d891crow4_col4 {\n            color:  darkorange;\n        }    #T_665f8776_83e5_11ea_95c3_bb23d54d891crow5_col1 {\n            color:  darkorange;\n        }    #T_665f8776_83e5_11ea_95c3_bb23d54d891crow5_col4 {\n            color:  darkorange;\n        }    #T_665f8776_83e5_11ea_95c3_bb23d54d891crow6_col1 {\n            color:  darkorange;\n        }    #T_665f8776_83e5_11ea_95c3_bb23d54d891crow6_col4 {\n            color:  darkorange;\n        }</style><table id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891c\" ><thead>    <tr>        <th class=\"blank level0\" ></th>        <th class=\"col_heading level0 col0\" >GPA below cutoff (1)</th>        <th class=\"col_heading level0 col1\" >P-Value (1)</th>        <th class=\"col_heading level0 col2\" >Std.err (1)</th>        <th class=\"col_heading level0 col3\" >Intercept (0)</th>        <th class=\"col_heading level0 col4\" >P-Value (0)</th>        <th class=\"col_heading level0 col5\" >Std.err (0)</th>        <th class=\"col_heading level0 col6\" >Observations</th>    </tr>    <tr>        <th class=\"index_name level0\" >groups</th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>    </tr></thead><tbody>\n                <tr>\n                        <th id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891clevel0_row0\" class=\"row_heading level0 row0\" >All</th>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow0_col0\" class=\"data row0 col0\" >0.233</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow0_col1\" class=\"data row0 col1\" >0</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow0_col2\" class=\"data row0 col2\" >0.026</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow0_col3\" class=\"data row0 col3\" >0.312</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow0_col4\" class=\"data row0 col4\" >0</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow0_col5\" class=\"data row0 col5\" >0.018</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow0_col6\" class=\"data row0 col6\" >11258</td>\n            </tr>\n            <tr>\n                        <th id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891clevel0_row1\" class=\"row_heading level0 row1\" >HS Grades < median</th>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow1_col0\" class=\"data row1 col0\" >0.247</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow1_col1\" class=\"data row1 col1\" >0</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow1_col2\" class=\"data row1 col2\" >0.029</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow1_col3\" class=\"data row1 col3\" >0.275</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow1_col4\" class=\"data row1 col4\" >0</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow1_col5\" class=\"data row1 col5\" >0.02</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow1_col6\" class=\"data row1 col6\" >8457</td>\n            </tr>\n            <tr>\n                        <th id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891clevel0_row2\" class=\"row_heading level0 row2\" >HS Grades > median</th>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow2_col0\" class=\"data row2 col0\" >0.179</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow2_col1\" class=\"data row2 col1\" >0.028</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow2_col2\" class=\"data row2 col2\" >0.081</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow2_col3\" class=\"data row2 col3\" >0.443</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow2_col4\" class=\"data row2 col4\" >0</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow2_col5\" class=\"data row2 col5\" >0.044</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow2_col6\" class=\"data row2 col6\" >2801</td>\n            </tr>\n            <tr>\n                        <th id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891clevel0_row3\" class=\"row_heading level0 row3\" >Male</th>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow3_col0\" class=\"data row3 col0\" >0.207</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow3_col1\" class=\"data row3 col1\" >0</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow3_col2\" class=\"data row3 col2\" >0.044</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow3_col3\" class=\"data row3 col3\" >0.281</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow3_col4\" class=\"data row3 col4\" >0</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow3_col5\" class=\"data row3 col5\" >0.027</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow3_col6\" class=\"data row3 col6\" >4166</td>\n            </tr>\n            <tr>\n                        <th id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891clevel0_row4\" class=\"row_heading level0 row4\" >Female</th>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow4_col0\" class=\"data row4 col0\" >0.246</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow4_col1\" class=\"data row4 col1\" >0</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow4_col2\" class=\"data row4 col2\" >0.036</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow4_col3\" class=\"data row4 col3\" >0.33</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow4_col4\" class=\"data row4 col4\" >0</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow4_col5\" class=\"data row4 col5\" >0.024</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow4_col6\" class=\"data row4 col6\" >7092</td>\n            </tr>\n            <tr>\n                        <th id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891clevel0_row5\" class=\"row_heading level0 row5\" >Native English</th>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow5_col0\" class=\"data row5 col0\" >0.229</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow5_col1\" class=\"data row5 col1\" >0</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow5_col2\" class=\"data row5 col2\" >0.036</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow5_col3\" class=\"data row5 col3\" >0.309</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow5_col4\" class=\"data row5 col4\" >0</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow5_col5\" class=\"data row5 col5\" >0.02</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow5_col6\" class=\"data row5 col6\" >8012</td>\n            </tr>\n            <tr>\n                        <th id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891clevel0_row6\" class=\"row_heading level0 row6\" >Nonnative English</th>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow6_col0\" class=\"data row6 col0\" >0.24</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow6_col1\" class=\"data row6 col1\" >0</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow6_col2\" class=\"data row6 col2\" >0.055</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow6_col3\" class=\"data row6 col3\" >0.318</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow6_col4\" class=\"data row6 col4\" >0</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow6_col5\" class=\"data row6 col5\" >0.035</td>\n                        <td id=\"T_665f8776_83e5_11ea_95c3_bb23d54d891crow6_col6\" class=\"data row6 col6\" >3246</td>\n            </tr>\n    </tbody></table>\n\n\n\n#### Table 5 - Estimated Discontinuites in Subsequent GPA | Part B - Probability of Placing Above the Cutoff in Next Term\n\nPanel B of Table 5 shows the probability of scoring above the cutoff in the next term. This statistic is very important because it decides whether students on academic probation are suspended after the subsequent term. It is therefore important for students who scored below the cutoff in the first year to not only improve their GPA, but improve it enough to score above the cutoff in the next term. Again academic probation increases the probability of students scoring above the cutoff in the next term for all subgroups.\n\n\n```python\ntable5 = estimate_RDD_multiple_datasets(groups_dict_06, groups_dict_keys,'nextGPA_above_cutoff', regressors)\ntable5.style.applymap(color_pvalues, subset=['P-Value (1)', 'P-Value (0)'])\n```\n\n\n\n\n<style  type=\"text/css\" >\n    #T_667bc260_83e5_11ea_95c3_bb23d54d891crow0_col1 {\n            color:  darkorange;\n        }    #T_667bc260_83e5_11ea_95c3_bb23d54d891crow0_col4 {\n            color:  darkorange;\n        }    #T_667bc260_83e5_11ea_95c3_bb23d54d891crow1_col1 {\n            color:  darkorange;\n        }    #T_667bc260_83e5_11ea_95c3_bb23d54d891crow1_col4 {\n            color:  darkorange;\n        }    #T_667bc260_83e5_11ea_95c3_bb23d54d891crow2_col1 {\n            color:  magenta;\n        }    #T_667bc260_83e5_11ea_95c3_bb23d54d891crow2_col4 {\n            color:  darkorange;\n        }    #T_667bc260_83e5_11ea_95c3_bb23d54d891crow3_col1 {\n            color:  darkorange;\n        }    #T_667bc260_83e5_11ea_95c3_bb23d54d891crow3_col4 {\n            color:  darkorange;\n        }    #T_667bc260_83e5_11ea_95c3_bb23d54d891crow4_col1 {\n            color:  darkorange;\n        }    #T_667bc260_83e5_11ea_95c3_bb23d54d891crow4_col4 {\n            color:  darkorange;\n        }    #T_667bc260_83e5_11ea_95c3_bb23d54d891crow5_col1 {\n            color:  darkorange;\n        }    #T_667bc260_83e5_11ea_95c3_bb23d54d891crow5_col4 {\n            color:  darkorange;\n        }    #T_667bc260_83e5_11ea_95c3_bb23d54d891crow6_col1 {\n            color:  darkorange;\n        }    #T_667bc260_83e5_11ea_95c3_bb23d54d891crow6_col4 {\n            color:  darkorange;\n        }</style><table id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891c\" ><thead>    <tr>        <th class=\"blank level0\" ></th>        <th class=\"col_heading level0 col0\" >GPA below cutoff (1)</th>        <th class=\"col_heading level0 col1\" >P-Value (1)</th>        <th class=\"col_heading level0 col2\" >Std.err (1)</th>        <th class=\"col_heading level0 col3\" >Intercept (0)</th>        <th class=\"col_heading level0 col4\" >P-Value (0)</th>        <th class=\"col_heading level0 col5\" >Std.err (0)</th>        <th class=\"col_heading level0 col6\" >Observations</th>    </tr>    <tr>        <th class=\"index_name level0\" >groups</th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>    </tr></thead><tbody>\n                <tr>\n                        <th id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891clevel0_row0\" class=\"row_heading level0 row0\" >All</th>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow0_col0\" class=\"data row0 col0\" >0.099</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow0_col1\" class=\"data row0 col1\" >0</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow0_col2\" class=\"data row0 col2\" >0.014</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow0_col3\" class=\"data row0 col3\" >0.693</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow0_col4\" class=\"data row0 col4\" >0</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow0_col5\" class=\"data row0 col5\" >0.009</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow0_col6\" class=\"data row0 col6\" >11258</td>\n            </tr>\n            <tr>\n                        <th id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891clevel0_row1\" class=\"row_heading level0 row1\" >HS Grades < median</th>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow1_col0\" class=\"data row1 col0\" >0.109</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow1_col1\" class=\"data row1 col1\" >0</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow1_col2\" class=\"data row1 col2\" >0.017</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow1_col3\" class=\"data row1 col3\" >0.68</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow1_col4\" class=\"data row1 col4\" >0</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow1_col5\" class=\"data row1 col5\" >0.011</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow1_col6\" class=\"data row1 col6\" >8457</td>\n            </tr>\n            <tr>\n                        <th id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891clevel0_row2\" class=\"row_heading level0 row2\" >HS Grades > median</th>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow2_col0\" class=\"data row2 col0\" >0.061</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow2_col1\" class=\"data row2 col1\" >0.073</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow2_col2\" class=\"data row2 col2\" >0.034</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow2_col3\" class=\"data row2 col3\" >0.737</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow2_col4\" class=\"data row2 col4\" >0</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow2_col5\" class=\"data row2 col5\" >0.02</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow2_col6\" class=\"data row2 col6\" >2801</td>\n            </tr>\n            <tr>\n                        <th id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891clevel0_row3\" class=\"row_heading level0 row3\" >Male</th>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow3_col0\" class=\"data row3 col0\" >0.075</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow3_col1\" class=\"data row3 col1\" >0.001</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow3_col2\" class=\"data row3 col2\" >0.022</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow3_col3\" class=\"data row3 col3\" >0.68</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow3_col4\" class=\"data row3 col4\" >0</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow3_col5\" class=\"data row3 col5\" >0.013</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow3_col6\" class=\"data row3 col6\" >4166</td>\n            </tr>\n            <tr>\n                        <th id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891clevel0_row4\" class=\"row_heading level0 row4\" >Female</th>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow4_col0\" class=\"data row4 col0\" >0.111</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow4_col1\" class=\"data row4 col1\" >0</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow4_col2\" class=\"data row4 col2\" >0.022</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow4_col3\" class=\"data row4 col3\" >0.7</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow4_col4\" class=\"data row4 col4\" >0</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow4_col5\" class=\"data row4 col5\" >0.014</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow4_col6\" class=\"data row4 col6\" >7092</td>\n            </tr>\n            <tr>\n                        <th id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891clevel0_row5\" class=\"row_heading level0 row5\" >Native English</th>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow5_col0\" class=\"data row5 col0\" >0.112</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow5_col1\" class=\"data row5 col1\" >0</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow5_col2\" class=\"data row5 col2\" >0.02</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow5_col3\" class=\"data row5 col3\" >0.691</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow5_col4\" class=\"data row5 col4\" >0</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow5_col5\" class=\"data row5 col5\" >0.011</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow5_col6\" class=\"data row5 col6\" >8012</td>\n            </tr>\n            <tr>\n                        <th id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891clevel0_row6\" class=\"row_heading level0 row6\" >Nonnative English</th>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow6_col0\" class=\"data row6 col0\" >0.07</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow6_col1\" class=\"data row6 col1\" >0.004</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow6_col2\" class=\"data row6 col2\" >0.024</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow6_col3\" class=\"data row6 col3\" >0.697</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow6_col4\" class=\"data row6 col4\" >0</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow6_col5\" class=\"data row6 col5\" >0.019</td>\n                        <td id=\"T_667bc260_83e5_11ea_95c3_bb23d54d891crow6_col6\" class=\"data row6 col6\" >3246</td>\n            </tr>\n    </tbody></table>\n\n\n\n### ii. Formal Bound Analysis on Subsequent GPA (partial extension)\n\nAs already mentioned in the section on the identification strategy, analyzing outcomes that occur after the immediate reaction to probation (the decision whether to drop out or not) becomes more challenging if we find that students are significantly more or less likely to drop out if they have been placed on academic probation. As discussed in the preceding section, this is the case because some groups of students indeed are more likely to drop out if they have been placed on probation.\n\nFor the analysis of subsequent GPA, this means that the results become less reliable because there is a group of students (those who dropped out) whose subsequent performance cannot be observed. This can cause the results to be biased. For example, if academic probation causes students with relatively low ability to drop out (which the performance model would predict) then we would find a positive impact on subsequent GPA being solely driven by the fact that the low performers in the treatment group dropped out. If, on the other hand, high ability students were more likely to drop out, the estimates for the impact on subsequent performance would be downward biased.\n\nIn short, the control group might not be comparable anymore. To test whether the results on subsequent GPA are robust to these concerns, Lindo et al. (2010) use formal bound analysis for the results on subsequent GPA which I present below.\n\nIn addition to this formal bound analysis, I plot confidence intervals for the results on subsequent GPA. Confidence intervals are a useful way to support the graphical analysis of RDDs and ensure the discontinuity at the threshold does not disappear when new population samples are drawn. The graph below shows the estimates from before including a bootstrap 95% percent confidence interval. The confidence interval around the cutoff shows to be quite small, and the fall in subsequent GPA between the treatment and control group persists even at the borders of the confidence interval. \n\n#### Subsequent Performance with 95% Confidence Interval\n\n\n```python\nbootstrap_pred = bootstrap_predictions(n=100, data=sample12, outcome='nextGPA', regressors=regressors, bandwidth=0.6)\nCI = get_confidence_interval(data=bootstrap_pred, lbound=2.5, ubound=97.5, index_var='dist_from_cut')\npredictions_fig4_CI = pd.concat([predictions_fig4, CI[['upper_bound', 'lower_bound']]], axis=1)\nplot_figure4_with_CI(data=sample12, pred=predictions_fig4_CI)\n```\n\n---\n<span style=\"color:orange\">**NOTE**:</span> The confidence intervals presented here are the product of only 100 resampling iterations of the bootstrap because increasing the number of times the data is resampled significantly increases the runtime of this notebook. However, I have tested the bootstrap for up to 1000 iterations and the results do not diverge very much from the version shown here. \n\n---\n\nThis type of confidence interval, however, does not correct for potential biases in the treatment or control group discussed above because the bootstrap only resamples the original data and therefore can at best achieve the estimate resulting from the original sample. \n\nTo test the sensitivity to possible nonrandom attrition through specific students dropping out of university, Lindo et al. (2010) perform a formal bound analysis using a trimming procedure proposed by Lee (2009)*. The reasoning for this approach is based on the concerns described above. To find a lower bound of the estimate, Lindo et al. (2010) assume that academic probation causes students who would have performed worse in the next term to drop out. The control group is thus made comparable by dropping the lowest-performing students (in the next term) from the sample, assuming these students would have dropped out had they been placed on probation. To calculate the upper bound estimate, the same share of students is dropped from the upper part of the grade distribution instead. \n\nThe share of students who need to be dropped is given by the estimated impact of probation on leaving school. For example, in the entire sample students on probation are 1.8 percentage points more likely to drop out, which is 44% of the control mean. Thus, to make the groups comparable again we presumably need to drop 44% more students from the control group than actually dropped out. \n\nFor groups of students where the estimated impact of probation on leaving school is negative, students from the control group need to be dropped instead (i.e. here the lower bound is given by dropping the top students in the treatment group and the upper bound is given by dropping the bottom students). \n\nWhile all results I have presented in this replication so far are exactly identical to the results from Lindo et al. (2010), I, unfortunately, cannot replicate the results from the formal bound analysis precisely. The description in the paper is brief and the provided STATA code from the authors does not include the formal bound analysis. While referring to methods presented in Lee (2009) has been helpful to understand the trimming procedure, I am unable to replicate the exact numbers presented in Lindo et al. (2010).\n\nThe table pictured below shows the results of the formal bound analysis presented in Lindo et al. (2010). The authors conclude that the positive effects of academic probation on students' subsequent GPA are too great to be explained by the attrition caused by dropouts. \n\n---\n<span style=\"color:orange\">**NOTE**:</span> In their paper Lindo et al. (2010) quote _'Lee (2008)'_ which could also refer to a different paper by Lee and Card from 2008 listed in the references. However, since this paper in contrast to the 2009 paper by Lee does not mention formal bound analysis and since Lee (2009) is not mentioned anywhere else in the paper, I am certain this is a citation error.\n\n---\n\n#### Formal Bound Analysis from Lindo et al. (2010) (p.110)\n\n\n\nThe table below shows my results using the proposed trimming procedure (table is again transposed compared to the original). The overall results are quite similar to the ones presented in Lindo et al. (2010), all estimates presented in Table 5 still lie between the lower and upper bound. It should be noted that in my replication the lower bound estimate for students with high school grades above the median was not significant at the 10% level while the results for all other groups were.\n\n#### Replication of Formal Bound Analysis\n\n\n```python\ntable4['add_leavers'] = round(table4['GPA below cutoff (1)']/table4['Intercept (0)'],2)\nadd_leavers = table4['add_leavers']\n```\n\n\n```python\nlb_trimmed_dict_06 = trim_data(groups_dict_06, add_leavers, True, False)\nlower_bound = estimate_RDD_multiple_datasets(lb_trimmed_dict_06, groups_dict_keys, 'nextGPA', regressors)\n```\n\n\n```python\nub_trimmed_dict_06 = trim_data(groups_dict_06, add_leavers, False, True)\nupper_bound = estimate_RDD_multiple_datasets(ub_trimmed_dict_06, groups_dict_keys, 'nextGPA', regressors)\n```\n\n\n```python\nbounds = pd.concat([lower_bound.iloc[:,[0,2]],upper_bound.iloc[:,[0,2]]], axis=1)\nbounds.columns = pd.MultiIndex.from_product([['Lower Bound Estimate','Upper Bound Estimate',],\n                                             ['GPA below cutoff (1)', 'Std.err (1)']])\nbounds\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n\n    .dataframe thead tr:last-of-type th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th colspan=\"2\" halign=\"left\">Lower Bound Estimate</th>\n      <th colspan=\"2\" halign=\"left\">Upper Bound Estimate</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>GPA below cutoff (1)</th>\n      <th>Std.err (1)</th>\n      <th>GPA below cutoff (1)</th>\n      <th>Std.err (1)</th>\n    </tr>\n    <tr>\n      <th>groups</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>All</td>\n      <td>0.175</td>\n      <td>0.025</td>\n      <td>0.259</td>\n      <td>0.026</td>\n    </tr>\n    <tr>\n      <td>HS Grades &lt; median</td>\n      <td>0.211</td>\n      <td>0.028</td>\n      <td>0.267</td>\n      <td>0.029</td>\n    </tr>\n    <tr>\n      <td>HS Grades &gt; median</td>\n      <td>0.036</td>\n      <td>0.082</td>\n      <td>0.215</td>\n      <td>0.079</td>\n    </tr>\n    <tr>\n      <td>Male</td>\n      <td>0.108</td>\n      <td>0.043</td>\n      <td>0.261</td>\n      <td>0.042</td>\n    </tr>\n    <tr>\n      <td>Female</td>\n      <td>0.229</td>\n      <td>0.036</td>\n      <td>0.248</td>\n      <td>0.036</td>\n    </tr>\n    <tr>\n      <td>Native English</td>\n      <td>0.140</td>\n      <td>0.035</td>\n      <td>0.261</td>\n      <td>0.035</td>\n    </tr>\n    <tr>\n      <td>Nonnative English</td>\n      <td>0.215</td>\n      <td>0.053</td>\n      <td>0.256</td>\n      <td>0.056</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### 5.2.5. The Impacts on Graduation\n\nAs a third outcome, Lindo et al. (2010) examine the effects of academic probation on students' graduation rates. As already discussed in the previous section, the outcomes that are realized later in time are more complex to examine because of all the different choices a student has made until she or he reaches that outcome. Graduation rates are the product of a dynamic decision-making process that spans throughout the students' time at university. While the study focuses mainly on the effects of being put on probation after the first year, the decision problem described in the theoretical framework can be faced by students at different points during their academic career as students can be placed on probation each term or for multiple terms in a row. There are different ways in which academic probation could affect graduation rates. On the one hand, it could reduce the probability of graduating because probation increases the probability of dropping out and some students who fail to increase their grades are suspended. On the other hand, these students might have graduated either way and thus do not have an effect. Additionally, probation could increase graduation rates because those students who remain improve their performance. \n\n#### Figure 5 - Graduation Rates\n\nFigure 5 and Table 6 show the estimated impacts of academic probation after the first year on whether a student has graduated in four, five or six years. The effects are negative for all three options, suggesting that the negative effects discussed above overweigh potential positive effects on graduation rates.\n\n\n```python\nplot_figure5(sample12, \n             create_predictions(sample12,'gradin4', regressors, 0.6), \n             create_predictions(sample12,'gradin5', regressors, 0.6), \n             create_predictions(sample12,'gradin6', regressors, 0.6))\n```\n\n#### Table 6 - Estimated Effects on Graduation\n\nThe effects on graduation rates are insignificant for most subgroups, the group of students with high school grades above the median stands out as being especially negatively affected by being placed on probation in the first year. This group of students sees their probability of graduation within six years reduced by 14.5 percent. Lindo et al. (2010) attribute these results to the fact that this group of students is especially likely to drop out after being put on probation and also on average does not do much better than their counterpart if they continue to attend university.\n\nOverall the results on graduation rates are rather limited. This likely stems from the more complex nature in which probation in the first year can affect this outcome later down the line. Unfortunately, most of the data in the provided dataset focus on the first two years of students' time at university (e.g. we only now the GPA of the first two years). Much more information would be needed to uncover the mechanisms in which probation may affect students' probability of graduating within specific timeframes.\n\n---\n<span style=\"color:orange\">**NOTE**:</span> Below I only show the sections of Table 6 that are discussed above as the entire table is quite extensive. The other results presented in Table 6 of the paper can be viewed by uncommenting the code at the end of this section.\n\n---\n\n#### Graduated after 6 years\n\n\n```python\ntable6 = create_table6(groups_dict_06, groups_dict_keys, regressors)\ntable6.loc[['All','HS Grades > median' ], \n           'Graduated after 6 years'].style.applymap(color_pvalues, subset=['P-Value (1)', 'P-Value (0)'])\n```\n\n\n\n\n<style  type=\"text/css\" >\n    #T_9a6b03d8_83e5_11ea_95c3_bb23d54d891crow0_col1 {\n            color:  black;\n        }    #T_9a6b03d8_83e5_11ea_95c3_bb23d54d891crow0_col4 {\n            color:  darkorange;\n        }    #T_9a6b03d8_83e5_11ea_95c3_bb23d54d891crow1_col1 {\n            color:  darkorange;\n        }    #T_9a6b03d8_83e5_11ea_95c3_bb23d54d891crow1_col4 {\n            color:  darkorange;\n        }</style><table id=\"T_9a6b03d8_83e5_11ea_95c3_bb23d54d891c\" ><thead>    <tr>        <th class=\"blank level0\" ></th>        <th class=\"col_heading level0 col0\" >GPA below cutoff (1)</th>        <th class=\"col_heading level0 col1\" >P-Value (1)</th>        <th class=\"col_heading level0 col2\" >Std.err (1)</th>        <th class=\"col_heading level0 col3\" >Intercept (0)</th>        <th class=\"col_heading level0 col4\" >P-Value (0)</th>        <th class=\"col_heading level0 col5\" >Std.err (0)</th>        <th class=\"col_heading level0 col6\" >Observations</th>    </tr>    <tr>        <th class=\"index_name level0\" >groups</th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>    </tr></thead><tbody>\n                <tr>\n                        <th id=\"T_9a6b03d8_83e5_11ea_95c3_bb23d54d891clevel0_row0\" class=\"row_heading level0 row0\" >All</th>\n                        <td id=\"T_9a6b03d8_83e5_11ea_95c3_bb23d54d891crow0_col0\" class=\"data row0 col0\" >-0.024</td>\n                        <td id=\"T_9a6b03d8_83e5_11ea_95c3_bb23d54d891crow0_col1\" class=\"data row0 col1\" >0.316</td>\n                        <td id=\"T_9a6b03d8_83e5_11ea_95c3_bb23d54d891crow0_col2\" class=\"data row0 col2\" >0.024</td>\n                        <td id=\"T_9a6b03d8_83e5_11ea_95c3_bb23d54d891crow0_col3\" class=\"data row0 col3\" >0.674</td>\n                        <td id=\"T_9a6b03d8_83e5_11ea_95c3_bb23d54d891crow0_col4\" class=\"data row0 col4\" >0</td>\n                        <td id=\"T_9a6b03d8_83e5_11ea_95c3_bb23d54d891crow0_col5\" class=\"data row0 col5\" >0.018</td>\n                        <td id=\"T_9a6b03d8_83e5_11ea_95c3_bb23d54d891crow0_col6\" class=\"data row0 col6\" >6005</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9a6b03d8_83e5_11ea_95c3_bb23d54d891clevel0_row1\" class=\"row_heading level0 row1\" >HS Grades > median</th>\n                        <td id=\"T_9a6b03d8_83e5_11ea_95c3_bb23d54d891crow1_col0\" class=\"data row1 col0\" >-0.145</td>\n                        <td id=\"T_9a6b03d8_83e5_11ea_95c3_bb23d54d891crow1_col1\" class=\"data row1 col1\" >0.006</td>\n                        <td id=\"T_9a6b03d8_83e5_11ea_95c3_bb23d54d891crow1_col2\" class=\"data row1 col2\" >0.053</td>\n                        <td id=\"T_9a6b03d8_83e5_11ea_95c3_bb23d54d891crow1_col3\" class=\"data row1 col3\" >0.76</td>\n                        <td id=\"T_9a6b03d8_83e5_11ea_95c3_bb23d54d891crow1_col4\" class=\"data row1 col4\" >0</td>\n                        <td id=\"T_9a6b03d8_83e5_11ea_95c3_bb23d54d891crow1_col5\" class=\"data row1 col5\" >0.022</td>\n                        <td id=\"T_9a6b03d8_83e5_11ea_95c3_bb23d54d891crow1_col6\" class=\"data row1 col6\" >1356</td>\n            </tr>\n    </tbody></table>\n\n\n\n**Code for complete Table 6:**\n\n\n```python\n# table6.loc[:, 'Graduated after 4 years'].style.applymap(color_pvalues, subset=['P-Value (1)', 'P-Value (0)'])\n```\n\n\n```python\n# table6.loc[:, 'Graduated after 5 years'].style.applymap(color_pvalues, subset=['P-Value (1)', 'P-Value (0)'])\n```\n\n\n```python\n# table6.loc[:, 'Graduated after 6 years'].style.applymap(color_pvalues, subset=['P-Value (1)', 'P-Value (0)'])\n```\n\n---\n# 6. Extension: Robustness Checks \n---\n\nAs discussed in my replication of Lindo et al. (2010) above, the authors use a variety of validity and robustness checks to analyze the reliability of their results. Aside from some smaller independent contributions that I already discuss in the replication part for better context, I in this section further analyze subsequent performance and check the bandwidth sensitivity of the results in drop out rates and subsequent GPA.\n\n## 6.1.  A Closer Look at Students' Subsequent Performance. \n\n### 6.1.1. Subsequent Performance and Total Credits in Year 2\n\nThe results from Lindo et al. (2010) presented above show that students are more likely to drop out after being placed on academic probation but those who remain in school tend to improve their GPA above the cutoff in the next term. These results are generally in line with the theoretical framework presented in the paper which predicts that students either drop out or improve their GPA if the cost of not improving in the next term increases. The performance standard model explains these results through students self-selecting between increasing effort and dropping out based on their abilities (which are defined as the probability of meeting the performance standard). Students who are less likely to improve their GPA should thus be more likely to drop out. Unfortunately, it is not possible to test this prediction, as Lindo et al. (2010) emphasize in the paper because the probability of meeting the performance standard is not observed for students who leave school. \n\nHowever, examining the students who remain in school may give some further insights. While Lindo et al. (2010) observe that  students have been placed on probation on average improve their performance, it is not clear under which circumstances this is happening. A look at the amount of credits students are taking in their second year may give some insights. The results presented below show that being placed on probation after the first year has a negative effect on the amount of credits students take in the second year for all of the examined subgroups except the group of nonnative English speakers. This is a stark contrast to the first year where both the treatment and control group take almost the same amount of credits (as shown in the section on the validity of the RD Approach).\n\n\n```python\npredictions_credits_year2 = create_predictions(sample12, 'total_credits_year2', regressors, 0.6)\nplot_figure_credits_year2(sample12, predictions_credits_year2)\n```\n\nThe results indicate that being placed on probation decreases the total credits taken by the average student in year two by 0.33, around 8% of the control mean. As the table below shows, the results are most prominent for males, native English speakers, and students with high school grades above the median. Interestingly, these are the same groups of students that are most likely to drop out, suggesting that the discouragement effect persists throughout these groups and even those who re-enroll for the next term proceed with caution by taking fewer credits.\n\n\n```python\ntable_total_credits_year2 = estimate_RDD_multiple_datasets(groups_dict_06, groups_dict_keys, \n                                                           'total_credits_year2',regressors)\ntable_total_credits_year2.style.applymap(color_pvalues, subset=['P-Value (1)', 'P-Value (0)'])\n```\n\n\n\n\n<style  type=\"text/css\" >\n    #T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow0_col1 {\n            color:  darkorange;\n        }    #T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow0_col4 {\n            color:  darkorange;\n        }    #T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow1_col1 {\n            color:  darkorange;\n        }    #T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow1_col4 {\n            color:  darkorange;\n        }    #T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow2_col1 {\n            color:  darkorange;\n        }    #T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow2_col4 {\n            color:  darkorange;\n        }    #T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow3_col1 {\n            color:  darkorange;\n        }    #T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow3_col4 {\n            color:  darkorange;\n        }    #T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow4_col1 {\n            color:  darkorange;\n        }    #T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow4_col4 {\n            color:  darkorange;\n        }    #T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow5_col1 {\n            color:  darkorange;\n        }    #T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow5_col4 {\n            color:  darkorange;\n        }    #T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow6_col1 {\n            color:  darkorange;\n        }    #T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow6_col4 {\n            color:  darkorange;\n        }</style><table id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891c\" ><thead>    <tr>        <th class=\"blank level0\" ></th>        <th class=\"col_heading level0 col0\" >GPA below cutoff (1)</th>        <th class=\"col_heading level0 col1\" >P-Value (1)</th>        <th class=\"col_heading level0 col2\" >Std.err (1)</th>        <th class=\"col_heading level0 col3\" >Intercept (0)</th>        <th class=\"col_heading level0 col4\" >P-Value (0)</th>        <th class=\"col_heading level0 col5\" >Std.err (0)</th>        <th class=\"col_heading level0 col6\" >Observations</th>    </tr>    <tr>        <th class=\"index_name level0\" >groups</th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>    </tr></thead><tbody>\n                <tr>\n                        <th id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891clevel0_row0\" class=\"row_heading level0 row0\" >All</th>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow0_col0\" class=\"data row0 col0\" >-0.326</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow0_col1\" class=\"data row0 col1\" >0</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow0_col2\" class=\"data row0 col2\" >0.06</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow0_col3\" class=\"data row0 col3\" >3.953</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow0_col4\" class=\"data row0 col4\" >0</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow0_col5\" class=\"data row0 col5\" >0.036</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow0_col6\" class=\"data row0 col6\" >11126</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891clevel0_row1\" class=\"row_heading level0 row1\" >HS Grades < median</th>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow1_col0\" class=\"data row1 col0\" >-0.29</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow1_col1\" class=\"data row1 col1\" >0</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow1_col2\" class=\"data row1 col2\" >0.069</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow1_col3\" class=\"data row1 col3\" >3.906</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow1_col4\" class=\"data row1 col4\" >0</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow1_col5\" class=\"data row1 col5\" >0.04</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow1_col6\" class=\"data row1 col6\" >8349</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891clevel0_row2\" class=\"row_heading level0 row2\" >HS Grades > median</th>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow2_col0\" class=\"data row2 col0\" >-0.453</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow2_col1\" class=\"data row2 col1\" >0</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow2_col2\" class=\"data row2 col2\" >0.112</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow2_col3\" class=\"data row2 col3\" >4.115</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow2_col4\" class=\"data row2 col4\" >0</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow2_col5\" class=\"data row2 col5\" >0.041</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow2_col6\" class=\"data row2 col6\" >2777</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891clevel0_row3\" class=\"row_heading level0 row3\" >Male</th>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow3_col0\" class=\"data row3 col0\" >-0.38</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow3_col1\" class=\"data row3 col1\" >0</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow3_col2\" class=\"data row3 col2\" >0.084</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow3_col3\" class=\"data row3 col3\" >3.839</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow3_col4\" class=\"data row3 col4\" >0</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow3_col5\" class=\"data row3 col5\" >0.049</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow3_col6\" class=\"data row3 col6\" >4109</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891clevel0_row4\" class=\"row_heading level0 row4\" >Female</th>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow4_col0\" class=\"data row4 col0\" >-0.301</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow4_col1\" class=\"data row4 col1\" >0</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow4_col2\" class=\"data row4 col2\" >0.067</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow4_col3\" class=\"data row4 col3\" >4.021</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow4_col4\" class=\"data row4 col4\" >0</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow4_col5\" class=\"data row4 col5\" >0.043</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow4_col6\" class=\"data row4 col6\" >7017</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891clevel0_row5\" class=\"row_heading level0 row5\" >Native English</th>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow5_col0\" class=\"data row5 col0\" >-0.283</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow5_col1\" class=\"data row5 col1\" >0</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow5_col2\" class=\"data row5 col2\" >0.054</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow5_col3\" class=\"data row5 col3\" >4.029</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow5_col4\" class=\"data row5 col4\" >0</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow5_col5\" class=\"data row5 col5\" >0.032</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow5_col6\" class=\"data row5 col6\" >7928</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891clevel0_row6\" class=\"row_heading level0 row6\" >Nonnative English</th>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow6_col0\" class=\"data row6 col0\" >-0.374</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow6_col1\" class=\"data row6 col1\" >0.004</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow6_col2\" class=\"data row6 col2\" >0.13</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow6_col3\" class=\"data row6 col3\" >3.756</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow6_col4\" class=\"data row6 col4\" >0</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow6_col5\" class=\"data row6 col5\" >0.067</td>\n                        <td id=\"T_9b1e024e_83e5_11ea_95c3_bb23d54d891crow6_col6\" class=\"data row6 col6\" >3198</td>\n            </tr>\n    </tbody></table>\n\n\n\nWhen interpreting these results it should be kept in mind that some students' next evaluation takes place during summer classes. Students who have taken summer classes enter their second year already having either passed the next evaluation or not. Those who fell below the cutoff will have been suspended and thus are missing from the data for the second year and those who have passed the threshold in the summer classes are likely not on probation anymore. Estimating the effects of probation on credits taken in the second year separately for both groups shows that those who did not take classes in the summer are more affected than those who did. For the students who took summer classes, the results are only significant for males, students with high school grades above the median and native English speakers.\n\n#### No summer classes\n\n\n```python\nsample06_nosummer = sample06[sample06.summerreg_year1 == 0]\ngroups_dict_06_nosummer = create_groups_dict(data=sample06_nosummer, keys=groups_dict_keys,columns=groups_dict_columns)\ntable_totcred_y2_nosummer = estimate_RDD_multiple_datasets(groups_dict_06_nosummer,groups_dict_keys,\n                                                           'total_credits_year2',regressors)\ntable_totcred_y2_nosummer.style.applymap(color_pvalues, subset=['P-Value (1)', 'P-Value (0)'])\n```\n\n\n\n\n<style  type=\"text/css\" >\n    #T_9b372abc_83e5_11ea_95c3_bb23d54d891crow0_col1 {\n            color:  darkorange;\n        }    #T_9b372abc_83e5_11ea_95c3_bb23d54d891crow0_col4 {\n            color:  darkorange;\n        }    #T_9b372abc_83e5_11ea_95c3_bb23d54d891crow1_col1 {\n            color:  darkorange;\n        }    #T_9b372abc_83e5_11ea_95c3_bb23d54d891crow1_col4 {\n            color:  darkorange;\n        }    #T_9b372abc_83e5_11ea_95c3_bb23d54d891crow2_col1 {\n            color:  magenta;\n        }    #T_9b372abc_83e5_11ea_95c3_bb23d54d891crow2_col4 {\n            color:  darkorange;\n        }    #T_9b372abc_83e5_11ea_95c3_bb23d54d891crow3_col1 {\n            color:  red;\n        }    #T_9b372abc_83e5_11ea_95c3_bb23d54d891crow3_col4 {\n            color:  darkorange;\n        }    #T_9b372abc_83e5_11ea_95c3_bb23d54d891crow4_col1 {\n            color:  darkorange;\n        }    #T_9b372abc_83e5_11ea_95c3_bb23d54d891crow4_col4 {\n            color:  darkorange;\n        }    #T_9b372abc_83e5_11ea_95c3_bb23d54d891crow5_col1 {\n            color:  darkorange;\n        }    #T_9b372abc_83e5_11ea_95c3_bb23d54d891crow5_col4 {\n            color:  darkorange;\n        }    #T_9b372abc_83e5_11ea_95c3_bb23d54d891crow6_col1 {\n            color:  red;\n        }    #T_9b372abc_83e5_11ea_95c3_bb23d54d891crow6_col4 {\n            color:  darkorange;\n        }</style><table id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891c\" ><thead>    <tr>        <th class=\"blank level0\" ></th>        <th class=\"col_heading level0 col0\" >GPA below cutoff (1)</th>        <th class=\"col_heading level0 col1\" >P-Value (1)</th>        <th class=\"col_heading level0 col2\" >Std.err (1)</th>        <th class=\"col_heading level0 col3\" >Intercept (0)</th>        <th class=\"col_heading level0 col4\" >P-Value (0)</th>        <th class=\"col_heading level0 col5\" >Std.err (0)</th>        <th class=\"col_heading level0 col6\" >Observations</th>    </tr>    <tr>        <th class=\"index_name level0\" >groups</th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>    </tr></thead><tbody>\n                <tr>\n                        <th id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891clevel0_row0\" class=\"row_heading level0 row0\" >All</th>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow0_col0\" class=\"data row0 col0\" >-0.187</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow0_col1\" class=\"data row0 col1\" >0</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow0_col2\" class=\"data row0 col2\" >0.048</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow0_col3\" class=\"data row0 col3\" >4.112</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow0_col4\" class=\"data row0 col4\" >0</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow0_col5\" class=\"data row0 col5\" >0.03</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow0_col6\" class=\"data row0 col6\" >6820</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891clevel0_row1\" class=\"row_heading level0 row1\" >HS Grades < median</th>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow1_col0\" class=\"data row1 col0\" >-0.192</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow1_col1\" class=\"data row1 col1\" >0.002</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow1_col2\" class=\"data row1 col2\" >0.062</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow1_col3\" class=\"data row1 col3\" >4.088</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow1_col4\" class=\"data row1 col4\" >0</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow1_col5\" class=\"data row1 col5\" >0.034</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow1_col6\" class=\"data row1 col6\" >5137</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891clevel0_row2\" class=\"row_heading level0 row2\" >HS Grades > median</th>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow2_col0\" class=\"data row2 col0\" >-0.173</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow2_col1\" class=\"data row2 col1\" >0.058</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow2_col2\" class=\"data row2 col2\" >0.091</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow2_col3\" class=\"data row2 col3\" >4.204</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow2_col4\" class=\"data row2 col4\" >0</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow2_col5\" class=\"data row2 col5\" >0.045</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow2_col6\" class=\"data row2 col6\" >1683</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891clevel0_row3\" class=\"row_heading level0 row3\" >Male</th>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow3_col0\" class=\"data row3 col0\" >-0.155</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow3_col1\" class=\"data row3 col1\" >0.042</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow3_col2\" class=\"data row3 col2\" >0.076</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow3_col3\" class=\"data row3 col3\" >3.988</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow3_col4\" class=\"data row3 col4\" >0</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow3_col5\" class=\"data row3 col5\" >0.049</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow3_col6\" class=\"data row3 col6\" >2653</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891clevel0_row4\" class=\"row_heading level0 row4\" >Female</th>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow4_col0\" class=\"data row4 col0\" >-0.22</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow4_col1\" class=\"data row4 col1\" >0</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow4_col2\" class=\"data row4 col2\" >0.058</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow4_col3\" class=\"data row4 col3\" >4.197</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow4_col4\" class=\"data row4 col4\" >0</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow4_col5\" class=\"data row4 col5\" >0.042</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow4_col6\" class=\"data row4 col6\" >4167</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891clevel0_row5\" class=\"row_heading level0 row5\" >Native English</th>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow5_col0\" class=\"data row5 col0\" >-0.183</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow5_col1\" class=\"data row5 col1\" >0.001</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow5_col2\" class=\"data row5 col2\" >0.053</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow5_col3\" class=\"data row5 col3\" >4.143</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow5_col4\" class=\"data row5 col4\" >0</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow5_col5\" class=\"data row5 col5\" >0.032</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow5_col6\" class=\"data row5 col6\" >5333</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891clevel0_row6\" class=\"row_heading level0 row6\" >Nonnative English</th>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow6_col0\" class=\"data row6 col0\" >-0.173</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow6_col1\" class=\"data row6 col1\" >0.044</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow6_col2\" class=\"data row6 col2\" >0.086</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow6_col3\" class=\"data row6 col3\" >3.99</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow6_col4\" class=\"data row6 col4\" >0</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow6_col5\" class=\"data row6 col5\" >0.062</td>\n                        <td id=\"T_9b372abc_83e5_11ea_95c3_bb23d54d891crow6_col6\" class=\"data row6 col6\" >1487</td>\n            </tr>\n    </tbody></table>\n\n\n\n#### Summer classes\n\n\n```python\nsample06_summer = sample06[sample06.summerreg_year1 == 1]\ngroups_dict_06_summer = create_groups_dict(sample06_summer,groups_dict_keys,groups_dict_columns)\ntable_totcred_y2_summer = estimate_RDD_multiple_datasets(groups_dict_06_summer,groups_dict_keys,\n                                                         'total_credits_year2',regressors)\ntable_totcred_y2_summer.style.applymap(color_pvalues, subset=['P-Value (1)', 'P-Value (0)'])\n```\n\n\n\n\n<style  type=\"text/css\" >\n    #T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow0_col1 {\n            color:  darkorange;\n        }    #T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow0_col4 {\n            color:  darkorange;\n        }    #T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow1_col1 {\n            color:  darkorange;\n        }    #T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow1_col4 {\n            color:  darkorange;\n        }    #T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow2_col1 {\n            color:  darkorange;\n        }    #T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow2_col4 {\n            color:  darkorange;\n        }    #T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow3_col1 {\n            color:  darkorange;\n        }    #T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow3_col4 {\n            color:  darkorange;\n        }    #T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow4_col1 {\n            color:  darkorange;\n        }    #T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow4_col4 {\n            color:  darkorange;\n        }    #T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow5_col1 {\n            color:  darkorange;\n        }    #T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow5_col4 {\n            color:  darkorange;\n        }    #T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow6_col1 {\n            color:  darkorange;\n        }    #T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow6_col4 {\n            color:  darkorange;\n        }</style><table id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891c\" ><thead>    <tr>        <th class=\"blank level0\" ></th>        <th class=\"col_heading level0 col0\" >GPA below cutoff (1)</th>        <th class=\"col_heading level0 col1\" >P-Value (1)</th>        <th class=\"col_heading level0 col2\" >Std.err (1)</th>        <th class=\"col_heading level0 col3\" >Intercept (0)</th>        <th class=\"col_heading level0 col4\" >P-Value (0)</th>        <th class=\"col_heading level0 col5\" >Std.err (0)</th>        <th class=\"col_heading level0 col6\" >Observations</th>    </tr>    <tr>        <th class=\"index_name level0\" >groups</th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>    </tr></thead><tbody>\n                <tr>\n                        <th id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891clevel0_row0\" class=\"row_heading level0 row0\" >All</th>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow0_col0\" class=\"data row0 col0\" >-0.552</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow0_col1\" class=\"data row0 col1\" >0</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow0_col2\" class=\"data row0 col2\" >0.095</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow0_col3\" class=\"data row0 col3\" >3.725</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow0_col4\" class=\"data row0 col4\" >0</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow0_col5\" class=\"data row0 col5\" >0.058</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow0_col6\" class=\"data row0 col6\" >4306</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891clevel0_row1\" class=\"row_heading level0 row1\" >HS Grades < median</th>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow1_col0\" class=\"data row1 col0\" >-0.452</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow1_col1\" class=\"data row1 col1\" >0</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow1_col2\" class=\"data row1 col2\" >0.117</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow1_col3\" class=\"data row1 col3\" >3.646</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow1_col4\" class=\"data row1 col4\" >0</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow1_col5\" class=\"data row1 col5\" >0.061</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow1_col6\" class=\"data row1 col6\" >3212</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891clevel0_row2\" class=\"row_heading level0 row2\" >HS Grades > median</th>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow2_col0\" class=\"data row2 col0\" >-0.898</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow2_col1\" class=\"data row2 col1\" >0</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow2_col2\" class=\"data row2 col2\" >0.201</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow2_col3\" class=\"data row2 col3\" >3.989</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow2_col4\" class=\"data row2 col4\" >0</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow2_col5\" class=\"data row2 col5\" >0.096</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow2_col6\" class=\"data row2 col6\" >1094</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891clevel0_row3\" class=\"row_heading level0 row3\" >Male</th>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow3_col0\" class=\"data row3 col0\" >-0.75</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow3_col1\" class=\"data row3 col1\" >0</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow3_col2\" class=\"data row3 col2\" >0.151</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow3_col3\" class=\"data row3 col3\" >3.577</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow3_col4\" class=\"data row3 col4\" >0</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow3_col5\" class=\"data row3 col5\" >0.072</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow3_col6\" class=\"data row3 col6\" >1456</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891clevel0_row4\" class=\"row_heading level0 row4\" >Female</th>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow4_col0\" class=\"data row4 col0\" >-0.448</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow4_col1\" class=\"data row4 col1\" >0</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow4_col2\" class=\"data row4 col2\" >0.105</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow4_col3\" class=\"data row4 col3\" >3.798</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow4_col4\" class=\"data row4 col4\" >0</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow4_col5\" class=\"data row4 col5\" >0.07</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow4_col6\" class=\"data row4 col6\" >2850</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891clevel0_row5\" class=\"row_heading level0 row5\" >Native English</th>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow5_col0\" class=\"data row5 col0\" >-0.518</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow5_col1\" class=\"data row5 col1\" >0</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow5_col2\" class=\"data row5 col2\" >0.13</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow5_col3\" class=\"data row5 col3\" >3.818</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow5_col4\" class=\"data row5 col4\" >0</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow5_col5\" class=\"data row5 col5\" >0.058</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow5_col6\" class=\"data row5 col6\" >2595</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891clevel0_row6\" class=\"row_heading level0 row6\" >Nonnative English</th>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow6_col0\" class=\"data row6 col0\" >-0.56</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow6_col1\" class=\"data row6 col1\" >0.003</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow6_col2\" class=\"data row6 col2\" >0.188</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow6_col3\" class=\"data row6 col3\" >3.577</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow6_col4\" class=\"data row6 col4\" >0</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow6_col5\" class=\"data row6 col5\" >0.093</td>\n                        <td id=\"T_9b4c2c78_83e5_11ea_95c3_bb23d54d891crow6_col6\" class=\"data row6 col6\" >1711</td>\n            </tr>\n    </tbody></table>\n\n\n\nThese findings are useful for interpreting the subsequent performance of students because more credits likely signify a larger workload for the student. Instead of increasing their effort, students may just decrease their workload by completing fewer credits in the next term. Unfortunately, we cannot test this in detail because the data doesn't show how many credits students completed in which term. \n\nReducing the sample for the analysis of the subsequent GPA to students who did not attend summer classes and completed 4 credits in the second year (the most frequent amount of credits takeen by this group of students) shows that the effect of scoring below the cutoff in year 1 becomes insignificant for the students who have above-median high school grades and nonnative English speakers. The improvement decreases a bit for some groups like females or students with high school grades below the median but increases for others like males and native english speakers. Overall the results are still highly significant though considering the small window of observations to which the data is reduced in this case. This suggests that while students on probation do seem to take fewer credits in the next year, the improvements to subsequent performance is too great to just be attributed to students decreasing their workload. \n\n\n```python\nsample06_many_credits = sample06_nosummer[(sample06_nosummer.total_credits_year2 == 4)]\ngroups_dict_06_manycredits = create_groups_dict(sample06_many_credits,groups_dict_keys,groups_dict_columns)\ntable_manycredits = estimate_RDD_multiple_datasets(groups_dict_06_manycredits,groups_dict_keys,\n                                                         'nextGPA',regressors)\ntable_manycredits.style.applymap(color_pvalues, subset=['P-Value (1)', 'P-Value (0)'])\n```\n\n\n\n\n<style  type=\"text/css\" >\n    #T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow0_col1 {\n            color:  darkorange;\n        }    #T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow0_col4 {\n            color:  darkorange;\n        }    #T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow1_col1 {\n            color:  darkorange;\n        }    #T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow1_col4 {\n            color:  darkorange;\n        }    #T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow2_col1 {\n            color:  black;\n        }    #T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow2_col4 {\n            color:  darkorange;\n        }    #T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow3_col1 {\n            color:  darkorange;\n        }    #T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow3_col4 {\n            color:  darkorange;\n        }    #T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow4_col1 {\n            color:  red;\n        }    #T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow4_col4 {\n            color:  darkorange;\n        }    #T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow5_col1 {\n            color:  darkorange;\n        }    #T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow5_col4 {\n            color:  darkorange;\n        }    #T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow6_col1 {\n            color:  black;\n        }    #T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow6_col4 {\n            color:  darkorange;\n        }</style><table id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891c\" ><thead>    <tr>        <th class=\"blank level0\" ></th>        <th class=\"col_heading level0 col0\" >GPA below cutoff (1)</th>        <th class=\"col_heading level0 col1\" >P-Value (1)</th>        <th class=\"col_heading level0 col2\" >Std.err (1)</th>        <th class=\"col_heading level0 col3\" >Intercept (0)</th>        <th class=\"col_heading level0 col4\" >P-Value (0)</th>        <th class=\"col_heading level0 col5\" >Std.err (0)</th>        <th class=\"col_heading level0 col6\" >Observations</th>    </tr>    <tr>        <th class=\"index_name level0\" >groups</th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>    </tr></thead><tbody>\n                <tr>\n                        <th id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891clevel0_row0\" class=\"row_heading level0 row0\" >All</th>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow0_col0\" class=\"data row0 col0\" >0.188</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow0_col1\" class=\"data row0 col1\" >0</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow0_col2\" class=\"data row0 col2\" >0.047</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow0_col3\" class=\"data row0 col3\" >0.314</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow0_col4\" class=\"data row0 col4\" >0</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow0_col5\" class=\"data row0 col5\" >0.027</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow0_col6\" class=\"data row0 col6\" >2003</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891clevel0_row1\" class=\"row_heading level0 row1\" >HS Grades < median</th>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow1_col0\" class=\"data row1 col0\" >0.22</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow1_col1\" class=\"data row1 col1\" >0</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow1_col2\" class=\"data row1 col2\" >0.052</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow1_col3\" class=\"data row1 col3\" >0.265</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow1_col4\" class=\"data row1 col4\" >0</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow1_col5\" class=\"data row1 col5\" >0.035</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow1_col6\" class=\"data row1 col6\" >1524</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891clevel0_row2\" class=\"row_heading level0 row2\" >HS Grades > median</th>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow2_col0\" class=\"data row2 col0\" >0.072</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow2_col1\" class=\"data row2 col1\" >0.586</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow2_col2\" class=\"data row2 col2\" >0.132</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow2_col3\" class=\"data row2 col3\" >0.476</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow2_col4\" class=\"data row2 col4\" >0</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow2_col5\" class=\"data row2 col5\" >0.073</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow2_col6\" class=\"data row2 col6\" >479</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891clevel0_row3\" class=\"row_heading level0 row3\" >Male</th>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow3_col0\" class=\"data row3 col0\" >0.273</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow3_col1\" class=\"data row3 col1\" >0.001</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow3_col2\" class=\"data row3 col2\" >0.082</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow3_col3\" class=\"data row3 col3\" >0.289</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow3_col4\" class=\"data row3 col4\" >0</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow3_col5\" class=\"data row3 col5\" >0.046</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow3_col6\" class=\"data row3 col6\" >748</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891clevel0_row4\" class=\"row_heading level0 row4\" >Female</th>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow4_col0\" class=\"data row4 col0\" >0.144</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow4_col1\" class=\"data row4 col1\" >0.031</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow4_col2\" class=\"data row4 col2\" >0.067</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow4_col3\" class=\"data row4 col3\" >0.331</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow4_col4\" class=\"data row4 col4\" >0</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow4_col5\" class=\"data row4 col5\" >0.04</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow4_col6\" class=\"data row4 col6\" >1255</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891clevel0_row5\" class=\"row_heading level0 row5\" >Native English</th>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow5_col0\" class=\"data row5 col0\" >0.252</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow5_col1\" class=\"data row5 col1\" >0</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow5_col2\" class=\"data row5 col2\" >0.055</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow5_col3\" class=\"data row5 col3\" >0.272</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow5_col4\" class=\"data row5 col4\" >0</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow5_col5\" class=\"data row5 col5\" >0.032</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow5_col6\" class=\"data row5 col6\" >1578</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891clevel0_row6\" class=\"row_heading level0 row6\" >Nonnative English</th>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow6_col0\" class=\"data row6 col0\" >-0.051</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow6_col1\" class=\"data row6 col1\" >0.609</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow6_col2\" class=\"data row6 col2\" >0.1</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow6_col3\" class=\"data row6 col3\" >0.473</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow6_col4\" class=\"data row6 col4\" >0</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow6_col5\" class=\"data row6 col5\" >0.062</td>\n                        <td id=\"T_9b5feb00_83e5_11ea_95c3_bb23d54d891crow6_col6\" class=\"data row6 col6\" >425</td>\n            </tr>\n    </tbody></table>\n\n\n\n### 6.1.2. Subsequent Cumulative Grade Point Average (CGPA) \n\nAn additional factor that might be important for the analysis of subsequent performance is the Cumulative Grade Point Average (CGPA). Lindo et al. (2010) focus their analysis of subsequent performance solely on the grades achieved in the next term. However, in the section on the institutional background in the paper the authors write:\n\n>*At all campuses, students on probation can avoid suspension and return to good academic standing by bringing their cumulative GPA up to the cutoff.* (Lindo et al., 2010, p.98).\n\nTo avoid suspension in the long term, students on probation thus are required to not only score above the cutoff in the next term but to score high enough to bring their CGPA above the probation threshold. Students who score above the threshold in the next term but still have a CGPA below the cutoff remain on probation. Students who fail to bring their GPA above the cutoff (and thus also their CGPA since their first-year GPA and first-year CGPA are the same) are suspended. \n\nAs the figure and table below show, the positive effects of probation on subsequent performance carry over to students' CGPA as well. Being placed on probation on average increases students' CGPA by 0.07 grade points or 63% of the control mean although the difference is rather difficult to spot visually.\n\n\n```python\npredictions_nextCGPA = create_predictions(sample12, 'nextCGPA', regressors, 0.6)\nplot_nextCGPA(sample12, predictions_nextCGPA)\n```\n\n#### Effect of Academic Probation on Subsequent CGPA\n\n\n```python\ntable_nextCGPA = estimate_RDD_multiple_datasets(groups_dict_06, groups_dict_keys, 'nextCGPA', regressors)\ntable_nextCGPA.style.applymap(color_pvalues, subset=['P-Value (1)', 'P-Value (0)'])\n```\n\n\n\n\n<style  type=\"text/css\" >\n    #T_9c220988_83e5_11ea_95c3_bb23d54d891crow0_col1 {\n            color:  darkorange;\n        }    #T_9c220988_83e5_11ea_95c3_bb23d54d891crow0_col4 {\n            color:  darkorange;\n        }    #T_9c220988_83e5_11ea_95c3_bb23d54d891crow1_col1 {\n            color:  darkorange;\n        }    #T_9c220988_83e5_11ea_95c3_bb23d54d891crow1_col4 {\n            color:  darkorange;\n        }    #T_9c220988_83e5_11ea_95c3_bb23d54d891crow2_col1 {\n            color:  black;\n        }    #T_9c220988_83e5_11ea_95c3_bb23d54d891crow2_col4 {\n            color:  darkorange;\n        }    #T_9c220988_83e5_11ea_95c3_bb23d54d891crow3_col1 {\n            color:  darkorange;\n        }    #T_9c220988_83e5_11ea_95c3_bb23d54d891crow3_col4 {\n            color:  darkorange;\n        }    #T_9c220988_83e5_11ea_95c3_bb23d54d891crow4_col1 {\n            color:  darkorange;\n        }    #T_9c220988_83e5_11ea_95c3_bb23d54d891crow4_col4 {\n            color:  darkorange;\n        }    #T_9c220988_83e5_11ea_95c3_bb23d54d891crow5_col1 {\n            color:  darkorange;\n        }    #T_9c220988_83e5_11ea_95c3_bb23d54d891crow5_col4 {\n            color:  darkorange;\n        }    #T_9c220988_83e5_11ea_95c3_bb23d54d891crow6_col1 {\n            color:  darkorange;\n        }    #T_9c220988_83e5_11ea_95c3_bb23d54d891crow6_col4 {\n            color:  darkorange;\n        }</style><table id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891c\" ><thead>    <tr>        <th class=\"blank level0\" ></th>        <th class=\"col_heading level0 col0\" >GPA below cutoff (1)</th>        <th class=\"col_heading level0 col1\" >P-Value (1)</th>        <th class=\"col_heading level0 col2\" >Std.err (1)</th>        <th class=\"col_heading level0 col3\" >Intercept (0)</th>        <th class=\"col_heading level0 col4\" >P-Value (0)</th>        <th class=\"col_heading level0 col5\" >Std.err (0)</th>        <th class=\"col_heading level0 col6\" >Observations</th>    </tr>    <tr>        <th class=\"index_name level0\" >groups</th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>    </tr></thead><tbody>\n                <tr>\n                        <th id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891clevel0_row0\" class=\"row_heading level0 row0\" >All</th>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow0_col0\" class=\"data row0 col0\" >0.07</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow0_col1\" class=\"data row0 col1\" >0</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow0_col2\" class=\"data row0 col2\" >0.01</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow0_col3\" class=\"data row0 col3\" >0.111</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow0_col4\" class=\"data row0 col4\" >0</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow0_col5\" class=\"data row0 col5\" >0.007</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow0_col6\" class=\"data row0 col6\" >11258</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891clevel0_row1\" class=\"row_heading level0 row1\" >HS Grades < median</th>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow1_col0\" class=\"data row1 col0\" >0.08</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow1_col1\" class=\"data row1 col1\" >0</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow1_col2\" class=\"data row1 col2\" >0.01</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow1_col3\" class=\"data row1 col3\" >0.094</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow1_col4\" class=\"data row1 col4\" >0</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow1_col5\" class=\"data row1 col5\" >0.007</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow1_col6\" class=\"data row1 col6\" >8457</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891clevel0_row2\" class=\"row_heading level0 row2\" >HS Grades > median</th>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow2_col0\" class=\"data row2 col0\" >0.031</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow2_col1\" class=\"data row2 col1\" >0.267</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow2_col2\" class=\"data row2 col2\" >0.028</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow2_col3\" class=\"data row2 col3\" >0.167</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow2_col4\" class=\"data row2 col4\" >0</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow2_col5\" class=\"data row2 col5\" >0.016</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow2_col6\" class=\"data row2 col6\" >2801</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891clevel0_row3\" class=\"row_heading level0 row3\" >Male</th>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow3_col0\" class=\"data row3 col0\" >0.059</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow3_col1\" class=\"data row3 col1\" >0</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow3_col2\" class=\"data row3 col2\" >0.016</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow3_col3\" class=\"data row3 col3\" >0.102</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow3_col4\" class=\"data row3 col4\" >0</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow3_col5\" class=\"data row3 col5\" >0.011</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow3_col6\" class=\"data row3 col6\" >4166</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891clevel0_row4\" class=\"row_heading level0 row4\" >Female</th>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow4_col0\" class=\"data row4 col0\" >0.075</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow4_col1\" class=\"data row4 col1\" >0</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow4_col2\" class=\"data row4 col2\" >0.013</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow4_col3\" class=\"data row4 col3\" >0.116</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow4_col4\" class=\"data row4 col4\" >0</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow4_col5\" class=\"data row4 col5\" >0.008</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow4_col6\" class=\"data row4 col6\" >7092</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891clevel0_row5\" class=\"row_heading level0 row5\" >Native English</th>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow5_col0\" class=\"data row5 col0\" >0.077</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow5_col1\" class=\"data row5 col1\" >0</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow5_col2\" class=\"data row5 col2\" >0.012</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow5_col3\" class=\"data row5 col3\" >0.115</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow5_col4\" class=\"data row5 col4\" >0</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow5_col5\" class=\"data row5 col5\" >0.007</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow5_col6\" class=\"data row5 col6\" >8012</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891clevel0_row6\" class=\"row_heading level0 row6\" >Nonnative English</th>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow6_col0\" class=\"data row6 col0\" >0.057</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow6_col1\" class=\"data row6 col1\" >0.001</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow6_col2\" class=\"data row6 col2\" >0.017</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow6_col3\" class=\"data row6 col3\" >0.1</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow6_col4\" class=\"data row6 col4\" >0</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow6_col5\" class=\"data row6 col5\" >0.012</td>\n                        <td id=\"T_9c220988_83e5_11ea_95c3_bb23d54d891crow6_col6\" class=\"data row6 col6\" >3246</td>\n            </tr>\n    </tbody></table>\n\n\n\nHowever, in contrast to the probability of improving the next term GPA above the cutoff, academic probation has no significant effect on the probability of improving the CGPA above the cutoff in the next term except for the group of nonnative English speakers where the probability is actually negative. Indeed, out of all students on probation (within 0.6 grade points of the cutoff), only around 37% improve their next term CGPA above the cutoff. Around 23% improve their GPA above the cutoff but not their CGPA and remain on probation. The other students dropped out or are suspended after the next term. This suggests that the effects of probation span much longer than just the subsequent term for many students, not only indirectly because they have had the experience of being placed on probation but also directly because many of them remain on probation for multiple subsequent terms. These factors underline the points made in previous sections about the complexity of the way academic probation can affect a student's academic career. After being placed on probation a student can take a multitude of different paths, many more than the theoretical framework introduced in Section 2 leads on. A more dynamic approach to estimating the effects of academic probation could likely offer more insights into how students react to this university policy.\n\n#### Effect of Academic Probation on the Probability of Achieving a CGPA Above the Cutoff in the Next Term\n\n\n```python\ntable_nextCGPA_above_cutoff = estimate_RDD_multiple_datasets(groups_dict_06, groups_dict_keys,'nextCGPA_above_cutoff', \n                                                             regressors)\ntable_nextCGPA_above_cutoff.style.applymap(color_pvalues, subset=['P-Value (1)', 'P-Value (0)'])\n```\n\n\n\n\n<style  type=\"text/css\" >\n    #T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow0_col1 {\n            color:  black;\n        }    #T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow0_col4 {\n            color:  darkorange;\n        }    #T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow1_col1 {\n            color:  black;\n        }    #T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow1_col4 {\n            color:  darkorange;\n        }    #T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow2_col1 {\n            color:  black;\n        }    #T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow2_col4 {\n            color:  darkorange;\n        }    #T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow3_col1 {\n            color:  black;\n        }    #T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow3_col4 {\n            color:  darkorange;\n        }    #T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow4_col1 {\n            color:  black;\n        }    #T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow4_col4 {\n            color:  darkorange;\n        }    #T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow5_col1 {\n            color:  black;\n        }    #T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow5_col4 {\n            color:  darkorange;\n        }    #T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow6_col1 {\n            color:  red;\n        }    #T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow6_col4 {\n            color:  darkorange;\n        }</style><table id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891c\" ><thead>    <tr>        <th class=\"blank level0\" ></th>        <th class=\"col_heading level0 col0\" >GPA below cutoff (1)</th>        <th class=\"col_heading level0 col1\" >P-Value (1)</th>        <th class=\"col_heading level0 col2\" >Std.err (1)</th>        <th class=\"col_heading level0 col3\" >Intercept (0)</th>        <th class=\"col_heading level0 col4\" >P-Value (0)</th>        <th class=\"col_heading level0 col5\" >Std.err (0)</th>        <th class=\"col_heading level0 col6\" >Observations</th>    </tr>    <tr>        <th class=\"index_name level0\" >groups</th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>        <th class=\"blank\" ></th>    </tr></thead><tbody>\n                <tr>\n                        <th id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891clevel0_row0\" class=\"row_heading level0 row0\" >All</th>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow0_col0\" class=\"data row0 col0\" >-0.014</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow0_col1\" class=\"data row0 col1\" >0.505</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow0_col2\" class=\"data row0 col2\" >0.021</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow0_col3\" class=\"data row0 col3\" >0.758</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow0_col4\" class=\"data row0 col4\" >0</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow0_col5\" class=\"data row0 col5\" >0.013</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow0_col6\" class=\"data row0 col6\" >11258</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891clevel0_row1\" class=\"row_heading level0 row1\" >HS Grades < median</th>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow1_col0\" class=\"data row1 col0\" >-0.009</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow1_col1\" class=\"data row1 col1\" >0.685</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow1_col2\" class=\"data row1 col2\" >0.023</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow1_col3\" class=\"data row1 col3\" >0.745</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow1_col4\" class=\"data row1 col4\" >0</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow1_col5\" class=\"data row1 col5\" >0.014</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow1_col6\" class=\"data row1 col6\" >8457</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891clevel0_row2\" class=\"row_heading level0 row2\" >HS Grades > median</th>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow2_col0\" class=\"data row2 col0\" >-0.028</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow2_col1\" class=\"data row2 col1\" >0.513</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow2_col2\" class=\"data row2 col2\" >0.042</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow2_col3\" class=\"data row2 col3\" >0.798</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow2_col4\" class=\"data row2 col4\" >0</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow2_col5\" class=\"data row2 col5\" >0.021</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow2_col6\" class=\"data row2 col6\" >2801</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891clevel0_row3\" class=\"row_heading level0 row3\" >Male</th>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow3_col0\" class=\"data row3 col0\" >-0.025</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow3_col1\" class=\"data row3 col1\" >0.219</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow3_col2\" class=\"data row3 col2\" >0.02</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow3_col3\" class=\"data row3 col3\" >0.741</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow3_col4\" class=\"data row3 col4\" >0</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow3_col5\" class=\"data row3 col5\" >0.012</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow3_col6\" class=\"data row3 col6\" >4166</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891clevel0_row4\" class=\"row_heading level0 row4\" >Female</th>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow4_col0\" class=\"data row4 col0\" >-0.009</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow4_col1\" class=\"data row4 col1\" >0.755</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow4_col2\" class=\"data row4 col2\" >0.027</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow4_col3\" class=\"data row4 col3\" >0.768</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow4_col4\" class=\"data row4 col4\" >0</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow4_col5\" class=\"data row4 col5\" >0.017</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow4_col6\" class=\"data row4 col6\" >7092</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891clevel0_row5\" class=\"row_heading level0 row5\" >Native English</th>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow5_col0\" class=\"data row5 col0\" >0.013</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow5_col1\" class=\"data row5 col1\" >0.542</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow5_col2\" class=\"data row5 col2\" >0.021</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow5_col3\" class=\"data row5 col3\" >0.755</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow5_col4\" class=\"data row5 col4\" >0</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow5_col5\" class=\"data row5 col5\" >0.016</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow5_col6\" class=\"data row5 col6\" >8012</td>\n            </tr>\n            <tr>\n                        <th id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891clevel0_row6\" class=\"row_heading level0 row6\" >Nonnative English</th>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow6_col0\" class=\"data row6 col0\" >-0.071</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow6_col1\" class=\"data row6 col1\" >0.026</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow6_col2\" class=\"data row6 col2\" >0.032</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow6_col3\" class=\"data row6 col3\" >0.766</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow6_col4\" class=\"data row6 col4\" >0</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow6_col5\" class=\"data row6 col5\" >0.018</td>\n                        <td id=\"T_9c35fdc6_83e5_11ea_95c3_bb23d54d891crow6_col6\" class=\"data row6 col6\" >3246</td>\n            </tr>\n    </tbody></table>\n\n\n\n## 6.2. Bandwidth Sensitivity \n\nAs a final robustness check, I evaluate the model at different bandwidths to ensure that results are not limited to one specific sample of students within a particular bandwidth. Lindo et al. (2010) use a distance from the threshold of 0.6 for the main regression analysis and 1.2 for graphical analysis (although the estimated curve at each point relies on a local linear regression with a bandwidth of 0.6 as well). The chosen bandwidth around the cutoff thus captures around 25% of the total range of grades (the GPA values observed in the first year span from 0 to 4.3). \n\nLindo et al. (2010) do not discuss the reasoning behind their choice of bandwidth in detail and do not apply optimal bandwidth selection methods like some other applications of regression discontinuity (Imbens & Lemieux, 2008; Lee & Lemieux, 2010). However, from a heuristic standpoint, this bandwidth choice seems reasonable. Since the cutoff lies at a GPA of 1.5 (1.6 at Campus 3), this bandwidth includes students whose GPA falls roughly between 0.9 and 2.1 grade points, so a range of around one average grade point including the edges. A much larger bandwidth would not make sense because it would include students that are failing every class and students who are achieving passable grades and are thus not very comparable to students who pass or fall below the threshold by a small margin.\n\nI evaluate bandwidths of length 0.2 (0.1 distance from cutoff on each side) up to 2.4 (1.2 distance from cutoff on both sides). As Lindo et al. (2010), I choose a maximum bandwidth of 1.2 the reasons explained in the paragraph above.\n\n#### Bandwidth sensitivity of the effect of probation on the probability of leaving school\n\nThe table below shows the estimated effect of probation on the probability to leave school after the first year using local linear regression (same specification as before) for all bandwidths between 0.1 and 1.2. The bandwidths are on the vertical axis, and the different subgroups are on the horizontal axis of the table. An *x* in the table indicates that the estimate was insignificant at the 10% level and is thus not shown for readability. \n\nThe table shows that the results for the effects on leaving school are relatively sensitive to bandwidth selection. Estimates of students within only 0.2 grade points of the probation threshold are not significant for any of the groups considered. Results for students with high school grades below the median are only significant for bandwidths between 0.3 and 0.5 while estimates for students with high school grades above the median are only significant between values of 0.5 and 0.7. The results for the other subgroups, on the other hand, seem to be quite robust to bandwidth selection.  \n\nThe findings reported in this table suggest that some results presented in the previous sections should be interpreted carefully. Especially the estimates of students based on high school grades might be driven by some underlying factors that are not observed in this study. These could explain the sensitivity of the results to bandwidth selection.\n\n\n```python\nbandwidths = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,1.1,1.2]\nsummary_left_school = bandwidth_sensitivity_summary(data, 'left_school',groups_dict_keys, groups_dict_columns, regressors)\nsummary_left_school.loc[(bandwidths,'probation'),:]\n#summary_left_school  #<- uncommenting this code will reveal the table including pvalues\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>All</th>\n      <th>HS Grades &lt; median</th>\n      <th>HS Grades &gt; median</th>\n      <th>Male</th>\n      <th>Female</th>\n      <th>Native English</th>\n      <th>Nonnative English</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0.1</td>\n      <td>probation</td>\n      <td>x</td>\n      <td>x</td>\n      <td>x</td>\n      <td>x</td>\n      <td>x</td>\n      <td>x</td>\n      <td>x</td>\n    </tr>\n    <tr>\n      <td>0.2</td>\n      <td>probation</td>\n      <td>x</td>\n      <td>x</td>\n      <td>x</td>\n      <td>x</td>\n      <td>x</td>\n      <td>x</td>\n      <td>x</td>\n    </tr>\n    <tr>\n      <td>0.3</td>\n      <td>probation</td>\n      <td>0.021</td>\n      <td>0.019</td>\n      <td>x</td>\n      <td>0.046</td>\n      <td>x</td>\n      <td>0.031</td>\n      <td>x</td>\n    </tr>\n    <tr>\n      <td>0.4</td>\n      <td>probation</td>\n      <td>0.024</td>\n      <td>0.022</td>\n      <td>x</td>\n      <td>0.063</td>\n      <td>x</td>\n      <td>0.037</td>\n      <td>x</td>\n    </tr>\n    <tr>\n      <td>0.5</td>\n      <td>probation</td>\n      <td>0.021</td>\n      <td>0.016</td>\n      <td>0.038</td>\n      <td>0.05</td>\n      <td>x</td>\n      <td>0.032</td>\n      <td>x</td>\n    </tr>\n    <tr>\n      <td>0.6</td>\n      <td>probation</td>\n      <td>0.018</td>\n      <td>x</td>\n      <td>0.032</td>\n      <td>0.037</td>\n      <td>x</td>\n      <td>0.028</td>\n      <td>x</td>\n    </tr>\n    <tr>\n      <td>0.7</td>\n      <td>probation</td>\n      <td>0.017</td>\n      <td>x</td>\n      <td>0.032</td>\n      <td>0.038</td>\n      <td>x</td>\n      <td>0.028</td>\n      <td>x</td>\n    </tr>\n    <tr>\n      <td>0.8</td>\n      <td>probation</td>\n      <td>0.014</td>\n      <td>x</td>\n      <td>x</td>\n      <td>0.036</td>\n      <td>x</td>\n      <td>0.022</td>\n      <td>x</td>\n    </tr>\n    <tr>\n      <td>0.9</td>\n      <td>probation</td>\n      <td>x</td>\n      <td>x</td>\n      <td>x</td>\n      <td>0.037</td>\n      <td>x</td>\n      <td>x</td>\n      <td>x</td>\n    </tr>\n    <tr>\n      <td>1.0</td>\n      <td>probation</td>\n      <td>x</td>\n      <td>x</td>\n      <td>x</td>\n      <td>0.03</td>\n      <td>x</td>\n      <td>x</td>\n      <td>x</td>\n    </tr>\n    <tr>\n      <td>1.1</td>\n      <td>probation</td>\n      <td>0.01</td>\n      <td>x</td>\n      <td>x</td>\n      <td>0.028</td>\n      <td>x</td>\n      <td>0.015</td>\n      <td>x</td>\n    </tr>\n    <tr>\n      <td>1.2</td>\n      <td>probation</td>\n      <td>0.013</td>\n      <td>x</td>\n      <td>x</td>\n      <td>0.029</td>\n      <td>x</td>\n      <td>0.018</td>\n      <td>x</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n#### Bandwidth sensitivity of the effect of probation on subsequent GPA\n\nThe results for the effects of academic probation on subsequent performance, on the other hand, seem to be quite robust to bandwidth selection. The estimated effects are the highest for most subgroups around the threshold of 0.6 chosen by Lindo et al. (2010) but the effects do not change sign for any subgroup and still remain quite similar.\n\nAgain, the group of students with high school grades above the median does not show significant results for bandwidths between 0.1 and 0.4 and thus seems to be the most sensitive to bandwidth selection. \n\n\n```python\nsummary_nextGPA = bandwidth_sensitivity_summary(data, 'nextGPA', groups_dict_keys, groups_dict_columns, regressors)\nsummary_nextGPA.loc[(bandwidths,'probation'),:]\n# summary_nextGPA    #<- uncommenting this code will reveal the table including pvalues\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>All</th>\n      <th>HS Grades &lt; median</th>\n      <th>HS Grades &gt; median</th>\n      <th>Male</th>\n      <th>Female</th>\n      <th>Native English</th>\n      <th>Nonnative English</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0.1</td>\n      <td>probation</td>\n      <td>0.191</td>\n      <td>0.19</td>\n      <td>x</td>\n      <td>0.163</td>\n      <td>0.208</td>\n      <td>0.134</td>\n      <td>0.311</td>\n    </tr>\n    <tr>\n      <td>0.2</td>\n      <td>probation</td>\n      <td>0.172</td>\n      <td>0.222</td>\n      <td>x</td>\n      <td>0.131</td>\n      <td>0.201</td>\n      <td>0.154</td>\n      <td>0.207</td>\n    </tr>\n    <tr>\n      <td>0.3</td>\n      <td>probation</td>\n      <td>0.233</td>\n      <td>0.258</td>\n      <td>x</td>\n      <td>0.203</td>\n      <td>0.247</td>\n      <td>0.221</td>\n      <td>0.258</td>\n    </tr>\n    <tr>\n      <td>0.4</td>\n      <td>probation</td>\n      <td>0.241</td>\n      <td>0.257</td>\n      <td>x</td>\n      <td>0.21</td>\n      <td>0.25</td>\n      <td>0.237</td>\n      <td>0.247</td>\n    </tr>\n    <tr>\n      <td>0.5</td>\n      <td>probation</td>\n      <td>0.227</td>\n      <td>0.247</td>\n      <td>0.141</td>\n      <td>0.183</td>\n      <td>0.246</td>\n      <td>0.221</td>\n      <td>0.237</td>\n    </tr>\n    <tr>\n      <td>0.6</td>\n      <td>probation</td>\n      <td>0.233</td>\n      <td>0.247</td>\n      <td>0.179</td>\n      <td>0.207</td>\n      <td>0.246</td>\n      <td>0.229</td>\n      <td>0.24</td>\n    </tr>\n    <tr>\n      <td>0.7</td>\n      <td>probation</td>\n      <td>0.246</td>\n      <td>0.255</td>\n      <td>0.216</td>\n      <td>0.197</td>\n      <td>0.273</td>\n      <td>0.238</td>\n      <td>0.264</td>\n    </tr>\n    <tr>\n      <td>0.8</td>\n      <td>probation</td>\n      <td>0.232</td>\n      <td>0.237</td>\n      <td>0.198</td>\n      <td>0.181</td>\n      <td>0.26</td>\n      <td>0.229</td>\n      <td>0.237</td>\n    </tr>\n    <tr>\n      <td>0.9</td>\n      <td>probation</td>\n      <td>0.215</td>\n      <td>0.221</td>\n      <td>0.178</td>\n      <td>0.164</td>\n      <td>0.242</td>\n      <td>0.213</td>\n      <td>0.219</td>\n    </tr>\n    <tr>\n      <td>1.0</td>\n      <td>probation</td>\n      <td>0.218</td>\n      <td>0.22</td>\n      <td>0.189</td>\n      <td>0.157</td>\n      <td>0.251</td>\n      <td>0.211</td>\n      <td>0.234</td>\n    </tr>\n    <tr>\n      <td>1.1</td>\n      <td>probation</td>\n      <td>0.224</td>\n      <td>0.226</td>\n      <td>0.197</td>\n      <td>0.183</td>\n      <td>0.247</td>\n      <td>0.214</td>\n      <td>0.249</td>\n    </tr>\n    <tr>\n      <td>1.2</td>\n      <td>probation</td>\n      <td>0.233</td>\n      <td>0.233</td>\n      <td>0.203</td>\n      <td>0.201</td>\n      <td>0.249</td>\n      <td>0.23</td>\n      <td>0.243</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n---\n# 7. Conclusion\n---\n\nOverall, the results in this notebook support the findings reported by Lindo et al. (2010) in their paper. The transparent research methods and STATA code provided by the authors allowed me to reproduce the results precisely for almost all tables and figures except for the formal bound analysis presented in Section 5.2.4. for which I could only produce similar results. In addition to the replication of the main results from Lindo et al. (2010), I discuss the identification strategy used in the paper and evaluate the robustness of the results, especially in the context of the performance standard model used in the paper. The results presented in Lindo et al. (2010) and my additional evaluation offer overall support for the performance standard model by B\u00e9nabou and Tirole (2000) which predicts that students who are put on probation will be more likely to drop out of university or improve their performance if they remain in school. However, one core feature of the model, the idea that students make their choices based on their ability to meet the performance standard, could not be tested due to the fact that the subsequent performance of students who left school cannot be observed.\n\nLindo et al. (2010) find large heterogeneities in the way students react to probation based on a set of covariates, however, the underlying sources of these heterogeneities are not evaluated. Further analysis of performance standards like academic probation using a larger set of information on student characteristics like personality traits, patience or socioeconomic background may thus be helpful to reveal the reasons why different students react to this negative incentive in certain ways. \n\nAdditionally, the study focused only on the effects of academic probation in the first year and relatively short term outcomes while long term outcomes were not assessed in detail. As already discussed in the section on the effects of academic probation on graduation rates, analyzing long term outcomes is much more difficult because of the multitude of different choices a student can make before reaching a specific outcome. Being placed on probation in the first year already expands the types of paths students may follow greatly. However, students can be placed on probation, suspended or leave school each term. To analyze the long term effects of academic probation in detail, there are too many questions that the data used in this study cannot answer. \n\nOverall the findings from Lindo et al. (2010) offer quite robust results on the effects of academic probation on low performing students. They contribute important insights into how students or individuals in general may react to negative incentives with the threat of severe real-world penalties if they fail to adjust their behavior.\n\n---\n# 8. References\n---\n\n* **B\u00e9nabou, R., & Tirole, J. (2000)**. *Self-Confidence and Social Interactions* (No. w7585). National bureau of economic research.\n\n\n* **Imbens, G. W., & Lemieux, T. (2008)**. Regression discontinuity designs: A guide to practice. *Journal of Econometrics*, 142(2), 615-635.\n\n\n* **Lee, D. S. (2009)**. Training, Wages, and Sample Selection: Estimating Sharp Bounds on Treatment Effects. *The Review of Economic Studies*, 76(3), 1071-1102.\n\n\n* **Lee, D. S., & Lemieux, T. (2010)**. Regression Discontinuity Designs in Economics. *Journal of Economic Literature*, 48(2), 281-355.\n\n\n* **Lindo, J. M., Sanders, N. J., & Oreopoulos, P. (2010)**. Ability, Gender, and Performance Standards: Evidence from Academic Probation. *American Economic Journal: Applied Economics*, 2(2), 95-117.\n\n\n* **Thistlethwaite, D. L., & Campbell, D. T. (1960)**. Regression-discontinuity analysis: An alternative to the ex post facto experiment. *Journal of Educational Psychology*, 51(6), 309.\n\n\n\n-------\nNotebook by Annica Gehlen | Find me on GitHub at https://github.com/amageh.\n\n---\n", "meta": {"hexsha": "5909c62b33cbf72eb07ddc4770f2ee86189ef088", "size": 665506, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "~old/example_project.ipynb", "max_stars_repo_name": "timmens/test", "max_stars_repo_head_hexsha": "8d35255a2cdb63748566e5d4c59aefa928ffe9c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "~old/example_project.ipynb", "max_issues_repo_name": "timmens/test", "max_issues_repo_head_hexsha": "8d35255a2cdb63748566e5d4c59aefa928ffe9c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "~old/example_project.ipynb", "max_forks_repo_name": "timmens/test", "max_forks_repo_head_hexsha": "8d35255a2cdb63748566e5d4c59aefa928ffe9c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 168.9530337649, "max_line_length": 114752, "alphanum_fraction": 0.8100197444, "converted": true, "num_tokens": 67097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3593641451601019, "lm_q2_score": 0.12421301483609337, "lm_q1q2_score": 0.04463770389433175}}
{"text": "# Exercise 4a\n\nGroup Members: Luis Pazos Clemens, Robert Freund, Eugen Dizer\n\nDeadline: 12.01.2021, 16:00.\n\n\n```python\n#Load standard libraries\nimport numpy as np   \nimport matplotlib.pyplot as plt   \n%matplotlib inline\n\nimport pandas as pd\nimport os\n```\n\n## 2 Red Cards Study\n\nDownload the dataset from https://osf.io/gvm2z/ (`1. Crowdsourcing Dataset July 01, 2014 Incl.Ref Country.zip` contains the dataset, `README.txt` a detailed description of the data and `2._Crowdstorming_Pictures_Skin_Color_Ratings.zip` the images of the players). Feel free to look at `Crowdsourcing Analytics - Final Manuscript.pdf` for a more detailed description of the experiment, its features, and the different methods participants applied to tackle the question.\n\n### 2.1 Loading and Cleaning the Data\n\nThe first step consists of loading the `.csv` file and preparing the data for the experiment. One participant of the official experiment provided a nice jupyter notebook demonstrating how the python library\n`pandas` can be utilized to achieve this: http://nbviewer.ipython.org/github/mathewzilla/redcard/blob/master/Crowdstorming_visualisation.ipynb. You should get inspiration from this example, but still choose your own data preparation steps.\n\n\n```python\n# Import original data and get it in displayable form.\nfile = os.path.join('data','CrowdstormingDataJuly1st.csv') \ndf = pd.read_csv(file)\n```\n\nBy default the data is in a rather counter-intuitive format: referee-player dyads.\n\nA referee-player dyad describes the interactions between a particular ref and one player. This means that each row in the dataset is of a unique player-ref combination, listing all of the games by a given player with a particular referee at any point in his career. Let's look at the first few rows of the dataset as an example:\n\n\n```python\n# Display the first 10 rows of the dataset. Only 13 columns for space reasons\ndf.iloc[:10,:13]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>playerShort</th>\n      <th>player</th>\n      <th>club</th>\n      <th>leagueCountry</th>\n      <th>birthday</th>\n      <th>height</th>\n      <th>weight</th>\n      <th>position</th>\n      <th>games</th>\n      <th>victories</th>\n      <th>ties</th>\n      <th>defeats</th>\n      <th>goals</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>lucas-wilchez</td>\n      <td>Lucas Wilchez</td>\n      <td>Real Zaragoza</td>\n      <td>Spain</td>\n      <td>31.08.1983</td>\n      <td>177.0</td>\n      <td>72.0</td>\n      <td>Attacking Midfielder</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>john-utaka</td>\n      <td>John Utaka</td>\n      <td>Montpellier HSC</td>\n      <td>France</td>\n      <td>08.01.1982</td>\n      <td>179.0</td>\n      <td>82.0</td>\n      <td>Right Winger</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>abdon-prats</td>\n      <td>Abd\u00f3n Prats</td>\n      <td>RCD Mallorca</td>\n      <td>Spain</td>\n      <td>17.12.1992</td>\n      <td>181.0</td>\n      <td>79.0</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>pablo-mari</td>\n      <td>Pablo Mar\u00ed</td>\n      <td>RCD Mallorca</td>\n      <td>Spain</td>\n      <td>31.08.1993</td>\n      <td>191.0</td>\n      <td>87.0</td>\n      <td>Center Back</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>ruben-pena</td>\n      <td>Rub\u00e9n Pe\u00f1a</td>\n      <td>Real Valladolid</td>\n      <td>Spain</td>\n      <td>18.07.1991</td>\n      <td>172.0</td>\n      <td>70.0</td>\n      <td>Right Midfielder</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>aaron-hughes</td>\n      <td>Aaron Hughes</td>\n      <td>Fulham FC</td>\n      <td>England</td>\n      <td>08.11.1979</td>\n      <td>182.0</td>\n      <td>71.0</td>\n      <td>Center Back</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>aleksandar-kolarov</td>\n      <td>Aleksandar Kolarov</td>\n      <td>Manchester City</td>\n      <td>England</td>\n      <td>10.11.1985</td>\n      <td>187.0</td>\n      <td>80.0</td>\n      <td>Left Fullback</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>alexander-tettey</td>\n      <td>Alexander Tettey</td>\n      <td>Norwich City</td>\n      <td>England</td>\n      <td>04.04.1986</td>\n      <td>180.0</td>\n      <td>68.0</td>\n      <td>Defensive Midfielder</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>anders-lindegaard</td>\n      <td>Anders Lindegaard</td>\n      <td>Manchester United</td>\n      <td>England</td>\n      <td>13.04.1984</td>\n      <td>193.0</td>\n      <td>80.0</td>\n      <td>Goalkeeper</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>andreas-beck</td>\n      <td>Andreas Beck</td>\n      <td>1899 Hoffenheim</td>\n      <td>Germany</td>\n      <td>13.03.1987</td>\n      <td>180.0</td>\n      <td>70.0</td>\n      <td>Right Fullback</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# Display the other columns too\ndf.iloc[:10,13:28]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>yellowCards</th>\n      <th>yellowReds</th>\n      <th>redCards</th>\n      <th>photoID</th>\n      <th>rater1</th>\n      <th>rater2</th>\n      <th>refNum</th>\n      <th>refCountry</th>\n      <th>Alpha_3</th>\n      <th>meanIAT</th>\n      <th>nIAT</th>\n      <th>seIAT</th>\n      <th>meanExp</th>\n      <th>nExp</th>\n      <th>seExp</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>95212.jpg</td>\n      <td>0.25</td>\n      <td>0.50</td>\n      <td>1</td>\n      <td>1</td>\n      <td>GRC</td>\n      <td>0.326391</td>\n      <td>712.0</td>\n      <td>0.000564</td>\n      <td>0.396000</td>\n      <td>750.0</td>\n      <td>0.002696</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1663.jpg</td>\n      <td>0.75</td>\n      <td>0.75</td>\n      <td>2</td>\n      <td>2</td>\n      <td>ZMB</td>\n      <td>0.203375</td>\n      <td>40.0</td>\n      <td>0.010875</td>\n      <td>-0.204082</td>\n      <td>49.0</td>\n      <td>0.061504</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>3</td>\n      <td>3</td>\n      <td>ESP</td>\n      <td>0.369894</td>\n      <td>1785.0</td>\n      <td>0.000229</td>\n      <td>0.588297</td>\n      <td>1897.0</td>\n      <td>0.001002</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>3</td>\n      <td>3</td>\n      <td>ESP</td>\n      <td>0.369894</td>\n      <td>1785.0</td>\n      <td>0.000229</td>\n      <td>0.588297</td>\n      <td>1897.0</td>\n      <td>0.001002</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>3</td>\n      <td>3</td>\n      <td>ESP</td>\n      <td>0.369894</td>\n      <td>1785.0</td>\n      <td>0.000229</td>\n      <td>0.588297</td>\n      <td>1897.0</td>\n      <td>0.001002</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3868.jpg</td>\n      <td>0.25</td>\n      <td>0.00</td>\n      <td>4</td>\n      <td>4</td>\n      <td>LUX</td>\n      <td>0.325185</td>\n      <td>127.0</td>\n      <td>0.003297</td>\n      <td>0.538462</td>\n      <td>130.0</td>\n      <td>0.013752</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>47704.jpg</td>\n      <td>0.00</td>\n      <td>0.25</td>\n      <td>4</td>\n      <td>4</td>\n      <td>LUX</td>\n      <td>0.325185</td>\n      <td>127.0</td>\n      <td>0.003297</td>\n      <td>0.538462</td>\n      <td>130.0</td>\n      <td>0.013752</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>22356.jpg</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>4</td>\n      <td>4</td>\n      <td>LUX</td>\n      <td>0.325185</td>\n      <td>127.0</td>\n      <td>0.003297</td>\n      <td>0.538462</td>\n      <td>130.0</td>\n      <td>0.013752</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>16528.jpg</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>4</td>\n      <td>4</td>\n      <td>LUX</td>\n      <td>0.325185</td>\n      <td>127.0</td>\n      <td>0.003297</td>\n      <td>0.538462</td>\n      <td>130.0</td>\n      <td>0.013752</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>36499.jpg</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>4</td>\n      <td>4</td>\n      <td>LUX</td>\n      <td>0.325185</td>\n      <td>127.0</td>\n      <td>0.003297</td>\n      <td>0.538462</td>\n      <td>130.0</td>\n      <td>0.013752</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nWe already see some strange things in the data. Some refs officiated very few games. The two raters disagree about player skintone quite often. For some players there isn't a photo, so their skin tone couldn't be rated. Most dyads don't feature cards at all. In general, it's difficult to get an intuition for what the population looks like from inspecting small samples of the data. This is particularly difficult in the dyad format, as each player or ref's cards are spread un-evenly across the dataset.\n\n#### Data Preparation Steps\n\nThe following questions may guide\nyou:\n\n- What do the feature names (e.g. `column games`) stand for?\n  - There is a list (`README.md`) that explains all the names.\n- Which irrelevant features might be dropped?\n  - We dropped the name of the players but kept the short code to distinguish the players.\n  - Also the players characteristics like weight, height, etc. are not important.\n  - The club and league is not important.\n- What relevant features might be missing, but can be computed? E.g., you can obtain the age of a player (which might be relevant) from his birthday, or create entirely new features by non-linear combinations of existing ones.\n  - We combined yellowReds and redCards into total number of red cards ('reds')\n  - We don't think that there are more relevant features.\n- Are there missing data values (e.g. missing skin color ratings), and how should they be dealt with (see https://en.wikipedia.org/wiki/Missing_data)?\n  - Yes, there are missing data values. We just drop them from our data set and don't use them for training.\n- How good are the skin color ratings? Do the raters agree?\n  - The ratings disagree quite often but are not too different. That's why we just take the mean of the two ratings (reported as the new 'skin' column). A simple chart shows this disagreement below in the code.\n- Should referees with very few appearances be excluded from the dataset?\n  - No, they should not. We take every referee into account.\n- Should features be normalized and/or centralized?\n  - For each unique player, we calculate an average probability of getting a red card from all his encounters with different referees.\n\nCategorical features (e.g. `league`) should be transformed to a one-hot  ncoding (see https://en.wikipedia.org/wiki/One-hot). In case of league, you can also repreat the experiment independently for the different leagues to check if there are differences between countries. Provide a detailed description and justification of your data preparation.\n\n\n```python\n### Cleaning the data:\n\ndf2 = df.dropna(subset=['photoID'])  #drop all dyads without photo\n\ndf2 = df2.assign(skin=df.loc[:, [\"rater1\", \"rater2\"]].mean(axis=1))   #create skin feature (mean of the 2 raters)\n\ndf2 = df2.assign(reds=df.loc[:, [\"yellowReds\", \"redCards\"]].sum(axis=1))   # create new column summing both types of red cards\n\n### simple chart to show disagreement in skin colour evaluation:\ndf3 = df2.groupby([\"playerShort\",'rater1', 'rater2'], as_index=False).sum()  \nrate_diff = abs(df3['rater1'] - df3['rater2']).value_counts()\nprint('Raters Disgreement (absolute difference between the 2 skin rates | percentaage of players): \\n', rate_diff/len(df3['rater1'])*100 )\n###\n\nDATA = df2.groupby([\"playerShort\",'skin'], as_index=False).sum()  #group dyads by player; now number of rows = number of players\n\nDATA[\"reds/N\"] = DATA[\"reds\"]/DATA[\"games\"]   # create new column with the label corresponding to each player\n\nDATA = DATA.loc[:,[\"skin\",\"reds/N\",\"refNum\"]]   #display final DATA; just skin (1D feature) and red cards/games played (labels)\nDATA\n\n#DATA = DATA.loc[:,[\"playerShort\",\"games\",\"reds\",\"skin\",\"reds/N\"]]   #we could show other columns too\n#DATA = DATA.groupby(\"skin\", as_index=False).mean()  \n```\n\n    Raters Disgreement (absolute difference between the 2 skin rates | percentaage of players): \n     0.00    76.088328\n    0.25    23.785489\n    0.50     0.126183\n    dtype: float64\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>skin</th>\n      <th>reds/N</th>\n      <th>refNum</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.125</td>\n      <td>0.000000</td>\n      <td>267701</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.125</td>\n      <td>0.002976</td>\n      <td>164589</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.250</td>\n      <td>0.000000</td>\n      <td>161486</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.000</td>\n      <td>0.003846</td>\n      <td>173524</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.250</td>\n      <td>0.048387</td>\n      <td>59603</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>1580</th>\n      <td>0.250</td>\n      <td>0.005102</td>\n      <td>220384</td>\n    </tr>\n    <tr>\n      <th>1581</th>\n      <td>0.000</td>\n      <td>0.000000</td>\n      <td>79202</td>\n    </tr>\n    <tr>\n      <th>1582</th>\n      <td>0.875</td>\n      <td>0.020253</td>\n      <td>140649</td>\n    </tr>\n    <tr>\n      <th>1583</th>\n      <td>0.000</td>\n      <td>0.042553</td>\n      <td>34125</td>\n    </tr>\n    <tr>\n      <th>1584</th>\n      <td>0.000</td>\n      <td>0.000000</td>\n      <td>46935</td>\n    </tr>\n  </tbody>\n</table>\n<p>1585 rows \u00d7 3 columns</p>\n</div>\n\n\n\n### 2.2 Model Creation\n\n#### Linear Regression\n\nLinear regression determines a weighted sum of the features $\\hat{Y}_i = X_i \\hat{\\beta} + \\hat{b}$, where optimal weights\nand intercept minimize the squared error:\n\n\\begin{equation}\n\\hat{\\beta}, \\, \\hat{b} = \\text{arg min}_{\\beta, b} \\sum_i (X_i \\beta + b - Y_i^*)^2 \\,.\n\\end{equation}\n\nDifferentiating with respect to $\\beta$ and $b$ and finding the minimum yields:\n\\begin{equation}\n\\hat{\\beta} = \\frac{\\sum_i X_i Y_i^* - N \\bar{X}\\bar{Y}^*}{\\sum_i X_i^2 - N \\bar{X}^2} \\,, \\,\n\\hat{b} = \\bar{Y}^* - \\hat{\\beta} \\bar{X} \\,,\n\\end{equation}\nwhere $N$ is the total number of players and $\\bar{X}$, $\\bar{Y}^*$ are the averages of $X_i$ and $Y_i^*$.\n\n\n```python\nclass LinearRegression:\n    def __init__(self):\n        self.beta = None\n        self.b = None\n      \n    def train(self, data, labels):\n        '''\n        data: the feature matrix (N, D)\n        labels: the corresponding ground-truth responses (N)\n        '''\n        N, D = data.shape # N: number of players, D: feature dimension\n        labels = labels.reshape((N, 1))\n\n        # Average feature and label vector\n        X = np.mean(data, axis=0)\n        Y = np.mean(labels, axis=0)\n\n        self.beta = ( np.mean(data * labels, axis=0) - X * Y ) / ( np.mean(np.sum(data**2, axis=1), axis=0) - np.dot(X, X) )\n        self.b = Y - np.dot(self.beta, X)\n\n        return self.beta, self.b\n\n\n    def predict(self, data):\n        # Compute Y = beta * X + b\n        return np.matmul(data, self.beta) + self.b\n```\n\n\n```python\n# Short visualization of how the Linear Regression works\n\ndata = np.atleast_2d(DATA[[\"skin\",\"refNum\"]])\nlabels = np.atleast_2d(DATA[\"reds/N\"])\n\na = LinearRegression()\na.train(data, labels)\npredictions = a.predict(data)\n\nprint('Predictions: ', predictions)\n\nN = np.linspace(0, 1584, 1585)\nplt.plot(N, labels.reshape((1585)), color='green', label='Data')\nplt.plot(N, predictions.reshape((1585)), color='red', label='Prediction')\nplt.xlim(0, 200)\nplt.ylim(0, 0.08)\nplt.legend()\nplt.show()\n```\n\n#### Regression Forest\n\n\n```python\n# Base classes\nclass Node:\n    pass\n\nclass Tree:\n    def __init__(self):\n        self.root = Node()\n    \n    def find_leaf(self, x):\n        node = self.root\n        while hasattr(node, \"feature\"):\n            j = node.feature\n            if x[j] <= node.threshold:\n                node = node.left\n            else:\n                node = node.right\n        return node\n```\n\n\n```python\nclass RegressionTree(Tree):\n    def __init__(self):\n        super(RegressionTree, self).__init__()\n\n    def train(self, data, labels, n_min=10):\n        '''\n        data: the feature matrix\n        labels: the corresponding ground-truth responses\n        n_min: termination criterion (don't split if a node contains fewer instances)\n        '''\n        N, D = data.shape\n        D_try = int(np.sqrt(D)) # how many features to consider for each split decision\n\n        # initialize the root node\n        self.root.data = data\n        self.root.labels = labels\n        \n        #put root in stack\n        stack = [self.root]\n        while len(stack):\n            node = stack.pop()\n            n = node.data.shape[0] # number of instances in present node\n            if n >= n_min:\n                # Call 'make_decision_split_node()' with 'D_try' randomly selected \n                # feature indices. This turns 'node' into a split node\n                # and returns the two children, which must be placed on the 'stack'.\n                perm = np.random.permutation(D)   # permute D indices\n                left, right = make_decision_split_node(node, perm[:D_try]) #select :D_try of permuted indices\n                                                       #for 'make_decision_split_node()'\n                # put children in stack\n                stack.append(left)\n                stack.append(right)\n            else:\n                # Call 'make_decision_leaf_node()' to turn 'node' into a leaf node.\n                make_decision_leaf_node(node)\n                \n    def predict(self, x):\n        leaf = self.find_leaf(x)\n        # compute p(y | x)\n        return leaf.response \n```\n\n\n```python\ndef make_decision_split_node(node, feature_indices):\n    '''\n    node: the node to be split\n    feature_indices: a numpy array of length 'D_try', containing the feature \n                     indices to be considered in the present split\n    '''\n    n, D = node.data.shape\n\n    # find best feature j (among 'feature_indices') and best threshold t for the split\n    e_min = 1e100\n    j_min, t_min = 0, 0\n    for j in feature_indices:\n        # remove duplicate features\n        dj = np.sort(np.unique(node.data[:,j]))\n        # compute candidate thresholds in the middle between consecutive feature values\n        tj = 0.5 * (dj[1:] + dj[:-1]) \n        # each candidate threshold we need to compute squared errors of the resulting children node\n        for t in tj:\n            left_indices = node.data[:,j] <= t\n            ll = node.labels[left_indices]\n            el = np.sum(np.square(ll - np.mean(ll)))\n            lr = node.labels[node.data[:,j] > t]\n            er = np.sum(np.square(lr - np.mean(lr)))\n            # choose the the best threshold that minimizes sum of squared errors\n            if el + er < e_min:\n                e_min = el + er\n                j_min = j\n                t_min = t\n\n    # create children\n    left = Node()\n    right = Node()\n    \n    # initialize 'left' and 'right' with the data subsets and labels\n    # according to the optimal split found above\n    left.data = node.data[node.data[:,j_min] <= t_min, :]\n    left.labels = node.labels[node.data[:,j_min] <= t_min]\n    right.data = node.data[node.data[:,j_min] > t_min, :]\n    right.labels = node.labels[node.data[:,j_min] > t_min]\n\n    # turn the current 'node' into a split node\n    # (store children and split condition)\n    node.left = left\n    node.right = right\n    node.feature = j_min\n    node.threshold = t_min\n\n    # return the children (to be placed on the stack)\n    return left, right    \n```\n\n\n```python\ndef make_decision_leaf_node(node):\n    '''\n    node: the node to become a leaf\n    '''\n    node.N = node.labels.shape[0]\n    node.response = np.mean(node.labels)\n```\n\n\n```python\nclass RegressionForest():\n    def __init__(self, n_trees=10):\n        # create ensemble\n        self.trees = [RegressionTree() for i in range(n_trees)]\n    \n    def train(self, data, labels, n_min=10):\n        for tree in self.trees:\n            # train each tree, using a bootstrap sample of the data\n            bootstrap = np.random.choice(len(data), size=len(data))\n            tree.train(data[bootstrap], labels[bootstrap], n_min)\n\n    def predict(self, x):\n        # compute the ensemble prediction\n        return np.mean([tree.predict(x) for tree in self.trees], axis=0)\n```\n\n\n```python\n# Short visualization of how the Regression Forest works\n\ndata = np.atleast_2d(DATA[[\"skin\",\"refNum\"]])\nlabels = np.atleast_2d(DATA[\"reds/N\"]).reshape((len(data)))\n\nb = RegressionForest()\nb.train(data, labels)\n\npredictions = np.zeros(len(data[:,0]))\n\nfor i in range(len(data[:,0])):\n    predictions[i] = b.predict(data[i,:])\n\nprint('Predictions: ', predictions)\n\nN = np.linspace(0, 1584, 1585)\nplt.plot(N,labels.reshape((1585)), color='green', label='Data')\nplt.plot(N,predictions.reshape((1585)), color='red', label='Prediction')\nplt.xlim(0, 200)\nplt.ylim(0, 0.08)\nplt.legend()\nplt.show()\n```\n\nWe see that the Regression Forest is much more flexible and fits the data better.\n\n#### Cross-Validation\n\n\n```python\ndef cross_validate(n_folds, data, labels):\n    N, D = data.shape\n    linear_regression = LinearRegression()\n    regression_forest = RegressionForest()\n\n    results = []\n    error_rates_linear = []; error_rates_forest = []\n\n    perm = range(N)\n    X_folds = np.array_split(data[perm], n_folds)\n    y_folds = np.array_split(labels[perm], n_folds)\n\n    for n in range(n_folds):\n        # construct train and test set from folds\n        X_train_f = np.concatenate([X_folds[i] for i in range(n_folds) if i != n])\n        X_test_f = X_folds[n]\n        y_train_f = np.concatenate([y_folds[i] for i in range(n_folds) if i != n])\n        y_test_f = y_folds[n]\n\n        # run linear regression\n        beta, b = linear_regression.train(X_train_f, y_train_f)\n        results_linear = linear_regression.predict(X_test_f)\n        error_rates_linear.append(np.sum(np.square(results_linear - y_test_f)))\n\n        # run regression forest\n        regression_forest.train(X_train_f, y_train_f)\n        results_forest = np.zeros(len(X_test_f[:,0]))\n        for i in range(len(X_test_f[:,0])):\n            results_forest[i] = regression_forest.predict(X_test_f[i,:])\n        error_rates_forest.append(np.sum(np.square((results_forest - y_test_f)[np.isfinite(results_forest)]))) # filter out nan\n\n\n    results.append(np.array(\n            [[np.mean(error_rates_linear), np.std(error_rates_linear)],\n              [np.mean(error_rates_forest), np.std(error_rates_forest)]]\n        ))\n\n    return results[0]\n```\n\n\n```python\n# Perform cross-validation for 10 folds\n\nerrors = cross_validate(10, data, labels)\n```\n\n    C:\\Users\\Eugen\\anaconda3\\lib\\site-packages\\numpy\\core\\fromnumeric.py:3334: RuntimeWarning: Mean of empty slice.\n      return _methods._mean(a, axis=axis, dtype=dtype,\n    C:\\Users\\Eugen\\anaconda3\\lib\\site-packages\\numpy\\core\\_methods.py:161: RuntimeWarning: invalid value encountered in double_scalars\n      ret = ret.dtype.type(ret / rcount)\n\n\n\n```python\nprint('Linear Regression Error: {:2.2%} +- {:2.2%}.'.format(errors[0][0], errors[0][1]))\nprint('Regression Forest Error: {:2.2%} +- {:2.2%}.'.format(errors[1][0], errors[1][1]))\n```\n\n    Linear Regression Error: 1.74% +- 0.55%.\n    Regression Forest Error: 2.17% +- 0.64%.\n\n\n\n```python\n# Dependence on the n-folds\n\nerrors_linear = []\nerrors_forest = []\nstds_linear = []\nstds_forest = []\n\nfor i in range(2,11):\n    errors = cross_validate(i, data, labels)\n    errors_linear.append(errors[0][0])\n    errors_forest.append(errors[1][0])\n    stds_linear.append(errors[0][1])\n    stds_forest.append(errors[1][1])\n```\n\n\n```python\nn = np.linspace(2, 10, 9)\nplt.errorbar(n, errors_linear, yerr=stds_linear, label='Linear Regression', capsize=2)\nplt.errorbar(n, errors_forest, yerr=stds_forest, label='Regression Forest', capsize=2)\nplt.xlabel('n-folds')\nplt.ylabel('Cross-Validation Mean Squared Error')\nplt.legend()\nplt.show()\n```\n\nWe can follow that the error of the Regression Forest is slightly higher than that of the Linear Regression. It seems like the Regression Forest fits the training data very well but doesn't generalize so well for unseen data.\n\n### 2.3 Answering the research question\n\n\n```python\n# Produce 19 different test sets with shuffled skin color variable\n\ndef permutation_test(n_folds, data, labels, n_permutations):\n    # produce some array to fit the data in\n    performation_data = np.full((n_permutations, len(data), len(data[0])), data)\n    skin_var = data[:,0] # skin has to be at first position in data\n\n    for i in range(n_permutations):\n        # shuffle skin data and then write it into the data set\n        np.random.shuffle(skin_var)\n        performation_data[i,:,0] = skin_var\n    \n    # calculate the cross validation error for each data set\n    performation_test_error = np.zeros((n_permutations, 2, 2))\n    for i in range(n_permutations):\n        performation_test_error[i] = cross_validate(n_folds, performation_data[i], labels)\n    \n    return performation_test_error\n```\n\n\n```python\n# Get the error for all permutations seperately\n\nerror_with_perm = permutation_test(4, data, labels, 19)\n```\n\n\n```python\nerror_no_perm = cross_validate(4, data, labels)\n```\n\nWe produced N_permutations data sets with differently shuffeled skin variable among the players. Then we calculate the error by cross-validation. If the error of the shuffeled datasets is always larger than the original dataset, we can state thatthere is a bias. The following graph should show wether the error is above or below the original datset for the several shuffeled datasets.\n\n\n```python\nn = np.arange(19) #number of permutations\n\nplt.errorbar(n, error_with_perm[:,0,0], yerr=error_with_perm[:,0,1], label=\"linear regression\", capsize=3)\nplt.plot(n, np.full(len(n),error_no_perm[0,0]), \"g\", label=\"linear regression without permutation\")\nplt.plot(n, np.full(len(n),error_no_perm[0,0])+np.full(len(n),error_no_perm[0,1]), \":\", color=\"g\")\nplt.plot(n, np.full(len(n),error_no_perm[0,0])-np.full(len(n),error_no_perm[0,1]), \":\", color=\"g\")\n\nplt.ylabel(\"error\")\nplt.xlabel(\"number of permutations\")\nplt.xlim(0,18)\nplt.ylim(0.034,0.055)\nplt.legend(bbox_to_anchor=(1, 0.5))\nplt.show()\n```\n\n\n```python\nplt.errorbar(n, error_with_perm[:,1,0], yerr=error_with_perm[:,1,1], label=\"regression forest\", capsize=3)\nplt.plot(n, np.full(len(n),error_no_perm[1,0]), \"r\", label=\"regression forest without permutation\")\nplt.plot(n, np.full(len(n),error_no_perm[1,0])+np.full(len(n),error_no_perm[1,1]), \":\", color=\"r\")\nplt.plot(n, np.full(len(n),error_no_perm[1,0])-np.full(len(n),error_no_perm[1,1]), \":\", color=\"r\")\n\nplt.ylabel(\"error\")\nplt.xlabel(\"number of permutations\")\nplt.xlim(0,18)\nplt.ylim(0.04,0.069)\nplt.legend(bbox_to_anchor=(1, 0.5))\nplt.show()\n```\n\nSince the absolute error of the Regression Forest with permutations is not significantly larger than the absolute error of the Regression Forest without permutations (we have the same behavior for the Linear Regression model), this gives rise to no bias!\nWe thus think that there is no correspondence between the skin color of a player and the number of red cards.\n\n\n```python\n\n```\n", "meta": {"hexsha": "41b311edd3cd1fa2c05e3982c6676322320b517f", "size": 210654, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "04a_red-cards.ipynb", "max_stars_repo_name": "Spektralzerleger/FML", "max_stars_repo_head_hexsha": "3e6dbb961d259f4b9ee4f7331bff8580a8fe8a60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-25T14:13:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T20:53:15.000Z", "max_issues_repo_path": "04a_red-cards.ipynb", "max_issues_repo_name": "Spektralzerleger/FML", "max_issues_repo_head_hexsha": "3e6dbb961d259f4b9ee4f7331bff8580a8fe8a60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "04a_red-cards.ipynb", "max_forks_repo_name": "Spektralzerleger/FML", "max_forks_repo_head_hexsha": "3e6dbb961d259f4b9ee4f7331bff8580a8fe8a60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-13T21:01:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-16T13:13:43.000Z", "avg_line_length": 135.8181818182, "max_line_length": 45068, "alphanum_fraction": 0.8406771293, "converted": true, "num_tokens": 9049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.13477592263589133, "lm_q1q2_score": 0.04462696841145343}}
{"text": "```python\n# %load /Users/facai/Study/book_notes/preconfig.py\n%matplotlib inline\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(color_codes=True)\n#sns.set(font='SimHei', font_scale=2.5)\n#plt.rcParams['axes.grid'] = False\n\nimport numpy as np\n\nimport pandas as pd\n#pd.options.display.max_rows = 20\n\n#import sklearn\n\n#import itertools\n\n#import logging\n#logger = logging.getLogger()\n\n#from IPython.display import SVG\nfrom IPython.display import Image\n```\n\nChapter 3: Finite Markov Decision Processes \n==========\n\nMDP(Markov Decision Processes): actions influence not just immediate rewards, but also subsequential situations.\n\n### 3.1 The Agent-Environment Interface\n\n\n```python\nImage('./res/fig3_1.png')\n```\n\n*finite* MDP: the sets of states, actions and rewards all have a finite number of elements.\n\n\\begin{align}\n    & p(s', r \\mid s, a) \\doteq \\operatorname{Pr} \\{ S_t = s', R_t = r \\mid S_{t-1} = s, A_{t-1} = a \\} \\\\\n    & \\displaystyle \\sum_{s' \\in \\mathcal{S}} \\sum_{r \\in \\mathcal{R}} p(s', r \\mid s, a) = 1 \\quad \\text{, for all $s \\in \\mathcal{S}$, $a \\in \\mathcal{A}(s)$}\n\\end{align}\n\n\n+ state-transition probabilities:\n\n\\begin{align*}\n    p(s' \\mid s, a) & \\doteq \\operatorname{Pr} \\{ S_t = s' \\mid S_{t-1} = s, A_{t-1} = a \\} \\\\\n                    & = \\sum_{r \\in \\mathcal{R}} p(s', r \\mid s, a)\n\\end{align*}\n\n+ expected rewards for state-action paris:\n\n\\begin{align*}\n    r(s, a) & \\doteq \\mathbb{E} \\left [ R_t \\mid S_{t-1} = s, A_{t-1} = a \\right ] \\\\\n            & = \\sum_{r \\in \\mathcal{R}} \\left ( r \\sum_{s' \\in \\mathcal{S}} p(s', r \\mid s, a) \\right )\n\\end{align*}\n\n+ expected rewards for state-action-next-state triples:\n\n\\begin{align*}\n    r(s, a, s') & \\doteq \\mathbb{E} \\left [ R_t \\mid S_{t-1} = s, A_{t-1} = a, S_t = s' \\right ] \\\\\n            & = \\sum_{r \\in \\mathcal{R}} r \\frac{p(s', r \\mid s, a)}{p(s' \\mid s, a)}\n\\end{align*}\n\nagent-environment boundary represents the limit of the agent's *absolute control*, not of its knowledge.\n\n\n```python\n# Transition Graph\nImage('./res/ex3_3.png')\n```\n\n##### Exercise 3.4\n\n$r(S_t, a) \\; \\pi(a \\mid S_t)$\n\n\n\n### 3.2 Goals and Rewards\n\ngoal: to maximize the total amount of reward it receives.\n\nIn particular, the reward signal is not the place to impart to the agent prior knowledge about *how* to achieve what it to do.\n\n### 3.3 Returns and Episodes\n\n+ episodic tasks: $G_t \\doteq R_{t+1} + R_{t+2} + R_{t+3} + \\cdots + R_T$, $\\quad G_t$ is *expected return*.\n+ continuing tasks: $G_t \\doteq R_{t+1} + \\gamma R_{t+2} + \\gamma^2 R_{t+3} + \\cdots = \\displaystyle \\sum_{k=0}^\\infty \\gamma^k R_{t+k+1} = R_{t+1} + \\gamma G_{t+1}$    \n  - $\\gamma$ is called *discount rate*, and $0 \\leq \\gamma \\leq 1$    \n  - $G_T = 0$ often makes it easy to compute returns from reward sequences.\n  \n  \n##### exercise 3.8\n\n0 for escaping from the maze and -1 at all other times\n\n##### exercise 3.10\n\n$G_1 = \\frac{7}{1 - r} = 70$\n\n$G_0 = R_1 + 0.9 G_1 = 65$\n\n##### exercise 3.11\n\n\\begin{align}\n    G_t &= \\sum_{k=0}^\\infty r^k \\\\\n        &= 1 + r \\sum_{k=0}^\\infty r^k \\\\\n        &= 1 + r G_t \\\\\n        &= \\frac1{1 - r}\n\\end{align}\n\n### 3.4 Unified Notation for Episodic and Continuing Tasks\n\n$G_t \\doteq \\sum_{k=t+1}^T \\gamma^{k-t-1} R_k$, including the possibility that $T = \\infty$ or $\\gamma = 1$.\n\n### 3.5 Policies and Value Functions\n\n+ value functions: estimate *how good* it is for the agent to be in a given state.\n+ policy $\\pi$: a mapping from states to probabilities of selecting each possible action.\n+ The *value* of a state $s$ under a policy $\\pi$, denoted $v_\\pi(s)$, is the expected return when starting in $s$ and following $\\pi$ thereafter:     \n  $v_\\pi(s) \\doteq \\mathbb{E}_\\pi [ G_t \\mid S_t = s ]$\n  - $v_\\pi$: state-value function for policy $\\pi$\n+ $q_\\pi$: action-value function for policy $\\pi$, $q_\\pi(s, a) \\doteq \\mathbb{E}_\\pi [ G_t \\mid S_t = s, A_t = a]$\n\nBellman equation for $v_\\pi$:\n\n\\begin{equation}\n    v_\\pi(s) \\doteq \\displaystyle \\sum_a \\pi(a \\mid s) \\sum_{s', r} p(s', r \\mid s, a) \\left [ r + \\gamma v_\\pi(s') \\right ] \\quad \\text{, for all $s \\in \\mathcal{S}$}\n\\end{equation}\n\nThe value functions $v_\\pi$ and $q_\\pi$ can be estimated from experience, say Monte Carlo methods (average).\n\n\n```python\n# Example 3.5\nfrom scipy.signal import convolve2d\n\nreward_matrix = np.zeros((5, 5))\n# kernel\nkernel = np.array([[0, 1, 0],\n                   [1, 0, 1],\n                   [0, 1, 0]])\n\niteration_nums = 100\n\nfor _ in range(iteration_nums):\n    reward = convolve2d(reward_matrix, kernel, mode='same', boundary='fill', fillvalue=-1)\n    reward /= 4.0\n    # A -> A'\n    reward[0, 1] = 10 + reward[-1, 1]\n    # B -> B'\n    reward[0, -2] = 5 + reward[2, -2]\n    reward_matrix = reward\n \npd.DataFrame(reward_matrix)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>0</th>\n      <th>1</th>\n      <th>2</th>\n      <th>3</th>\n      <th>4</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>2.253150</td>\n      <td>9.592586</td>\n      <td>4.524364</td>\n      <td>6.244556</td>\n      <td>1.271214</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1.420013</td>\n      <td>3.970976</td>\n      <td>3.260312</td>\n      <td>2.897431</td>\n      <td>0.840299</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.455929</td>\n      <td>1.610993</td>\n      <td>1.648482</td>\n      <td>1.244556</td>\n      <td>0.192553</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>-0.207290</td>\n      <td>0.368589</td>\n      <td>0.478065</td>\n      <td>0.239763</td>\n      <td>-0.314645</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>-0.653676</td>\n      <td>-0.407414</td>\n      <td>-0.344568</td>\n      <td>-0.448925</td>\n      <td>-0.690892</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n##### exercise 3.12\n\n(2.3 + 0.4 - 0.4 + 0.7) / 4 = 0.75\n\n\n##### exercise 3.13\n\n\n##### exercise 3.14\n\n$\\sum_{k=0}^\\infty \\gamma^k C = \\frac{C}{1 - r}$ = constant offset\n\n### 3.6 Optimal Policies and Optimal Value Functions\n\noptimal policy: \n\n\\begin{align}\n    v_\\ast(s) & \\doteq \\displaystyle \\max_\\pi v_\\pi(s) \\quad \\text{ for all } s \\in \\mathcal{S} \\\\\n              & = \\max_a \\sum_{s', r} p(s', r \\mid s, a) \\left [ r + \\gamma v_\\ast(s') \\right ] \\\\\n\\end{align}\n\nAny policy that is *greedy* with respect to the optimal evaluation function $v_\\ast$ is an optimal policy.\n\noptimal action-value function: \n\n\\begin{align}\n    q_\\ast(s, a) & \\doteq \\max_\\pi q_\\pi(s, a) \\quad \\text{ for all $s \\in \\mathcal{S}$ and $a \\in \\mathcal{A}(s)$} \\\\\n                 & = \\mathbb{E} [ R_{t+1} + \\gamma v_\\ast(S_{t+1}) \\mid S_t = s, A_t = a ] \\\\\n                 & = \\sum_{s', r} p(s', r \\mid s, a) \\left [ r + \\gamma \\max_{a'} q_\\ast (s', a') \\right ] \\\\\n\\end{align}\n\n\nExplicitly solving the Bellman optimality equation relies on at least three assumptions that are rarely true in practice:\n\n1. we accurately know the dynamics of the environment;\n2. we have enough computational resources;\n3. the Markov property.\n\n### 3.7 Optimality and Approximation\n\nextreme computational cost, memory => approximations\n\nput more effort into learning to make good decisions for frequently encountered states, at the expense of less effort for infrequently encountered states.\n\n\n```python\n\n```\n", "meta": {"hexsha": "f4ae161deb16db4432714fc57a88196d110bd4ba", "size": 97571, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Reinforcement_Learing_An_Introduction/Finite_Markov_Decision_Processes/note.ipynb", "max_stars_repo_name": "ningchi/book_notes", "max_stars_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-12-31T12:10:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T15:49:34.000Z", "max_issues_repo_path": "Reinforcement_Learing_An_Introduction/Finite_Markov_Decision_Processes/note.ipynb", "max_issues_repo_name": "ningchi/book_notes", "max_issues_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-12-05T13:04:14.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-07T16:24:50.000Z", "max_forks_repo_path": "Reinforcement_Learing_An_Introduction/Finite_Markov_Decision_Processes/note.ipynb", "max_forks_repo_name": "ningchi/book_notes", "max_forks_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-06-27T07:19:28.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-19T08:57:35.000Z", "avg_line_length": 230.6643026005, "max_line_length": 52624, "alphanum_fraction": 0.8909717027, "converted": true, "num_tokens": 2623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981165504266236, "lm_q2_score": 0.1112411991414075, "lm_q1q2_score": 0.04447552793765652}}
{"text": "<a href=\"https://colab.research.google.com/github/wiatrak2/BScThesis/blob/master/BackwardFunctions.ipynb\" target=\"_parent\"></a>\n\n# Load data\n\n\n```\nfrom google.colab import drive\ndrive.mount('/content/drive')\nimport sys\nsys.path.append('BScThesis/')\n```\n\n    Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&scope=email%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdocs.test%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.photos.readonly%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fpeopleapi.readonly&response_type=code\n    \n    Enter your authorization code:\n    \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\n    Mounted at /content/drive\n\n\n\n```\n!pip3 install torch torchvision\n```\n\n    Collecting torch\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/7e/60/66415660aa46b23b5e1b72bc762e816736ce8d7260213e22365af51e8f9c/torch-1.0.0-cp36-cp36m-manylinux1_x86_64.whl (591.8MB)\n    \u001b[K    100% |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 591.8MB 26kB/s \n    tcmalloc: large alloc 1073750016 bytes == 0x62826000 @  0x7fda7e9502a4 0x591a07 0x5b5d56 0x502e9a 0x506859 0x502209 0x502f3d 0x506859 0x504c28 0x502540 0x502f3d 0x506859 0x504c28 0x502540 0x502f3d 0x506859 0x504c28 0x502540 0x502f3d 0x507641 0x502209 0x502f3d 0x506859 0x504c28 0x502540 0x502f3d 0x507641 0x504c28 0x502540 0x502f3d 0x507641\n    \u001b[?25hCollecting torchvision\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/ca/0d/f00b2885711e08bd71242ebe7b96561e6f6d01fdb4b9dcf4d37e2e13c5e1/torchvision-0.2.1-py2.py3-none-any.whl (54kB)\n    \u001b[K    100% |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 61kB 21.1MB/s \n    \u001b[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from torchvision) (1.14.6)\n    Collecting pillow>=4.1.1 (from torchvision)\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/85/5e/e91792f198bbc5a0d7d3055ad552bc4062942d27eaf75c3e2783cf64eae5/Pillow-5.4.1-cp36-cp36m-manylinux1_x86_64.whl (2.0MB)\n    \u001b[K    100% |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.0MB 6.6MB/s \n    \u001b[?25hRequirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from torchvision) (1.11.0)\n    Installing collected packages: torch, pillow, torchvision\n      Found existing installation: Pillow 4.0.0\n        Uninstalling Pillow-4.0.0:\n          Successfully uninstalled Pillow-4.0.0\n    Successfully installed pillow-5.4.1 torch-1.0.0 torchvision-0.2.1\n\n\n\n```\n!git clone https://github.com/wiatrak2/BScThesis\n```\n\n    Cloning into 'BScThesis'...\n    remote: Enumerating objects: 14, done.\u001b[K\n    remote: Counting objects: 100% (14/14), done.\u001b[K\n    remote: Compressing objects: 100% (11/11), done.\u001b[K\n    remote: Total 364 (delta 5), reused 9 (delta 3), pack-reused 350\u001b[K\n    Receiving objects: 100% (364/364), 56.72 MiB | 10.07 MiB/s, done.\n    Resolving deltas: 100% (209/209), done.\n\n\n\n```\nfrom importlib import reload \n```\n\n\n```\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n```\n\n\n```\nimport torchvision\nimport torchvision.transforms as transforms\n```\n\n\n```\nimport matplotlib.pyplot as plt\nimport pickle\nimport sympy\nfrom collections import defaultdict, namedtuple\nimport copy\n```\n\n\n```\nfrom mnist_m import Mnist_M\nfrom random_dataset import RandomDataset\nimport datasets_merge\nimport models\nimport svhn_models\nimport trainer\nimport domain_trainer\nfrom test_model import test_model\nimport plots\nimport test\nimport plotly_plots\n```\n\n\n```\nimport backward_functions\n```\n\n\n```\nimport plotly\nfrom plotly import tools\nfrom plotly.offline import init_notebook_mode, iplot\nimport plotly.graph_objs as go\n```\n\n\n```\ndef convertMnist(img):\n  img = img.squeeze().numpy()\n  return torch.from_numpy(np.tile(img, (3,1,1)))\n```\n\n\n```\nbatch_size=128\nnum_workers=1\n```\n\n\n```\nmnist_transform=transforms.Compose([\n                           transforms.ToTensor(),\n                           transforms.Normalize((0.1307, 0.1307, 0.1307), (0.3081, 0.3081, 0.3081)),\n                           transforms.Lambda(convertMnist)\n                       ])\n\nmnist_train_set = torchvision.datasets.MNIST(root='./data', train=True, download=True,\n                                     transform=mnist_transform)\nmnist_train_loader = torch.utils.data.DataLoader(mnist_train_set, batch_size=batch_size,\n                                         shuffle=True, num_workers=num_workers)\n\nmnist_test_set = torchvision.datasets.MNIST(root='./data', train=False, download=True,\n                                     transform=mnist_transform)\nmnist_test_loader = torch.utils.data.DataLoader(mnist_test_set, batch_size=batch_size,\n                                         shuffle=False, num_workers=num_workers)\n\n\n```\n\n    Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\n    Downloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz\n    Downloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz\n    Downloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz\n    Processing...\n    Done!\n\n\n\n```\nmnist_m_transform = transforms.Compose([\n                           transforms.Normalize((0.1307, 0.1307, 0.1307), (0.3081, 0.3081, 0.3081)),\n                       ])\nmnist_m_train_set = Mnist_M('drive/My Drive/BScThesis/keras_mnistm.pkl',\n                        transform=mnist_m_transform)\nmnist_m_test_set = Mnist_M('drive/My Drive/BScThesis/keras_mnistm.pkl',train=False,\n                     transform=mnist_m_transform)\nmnist_m_train_loader = torch.utils.data.DataLoader(mnist_m_train_set, \n                                                   batch_size=batch_size,\n                                         shuffle=True, num_workers=num_workers)\nmnist_m_test_loader = torch.utils.data.DataLoader(mnist_m_test_set,\n                                                  batch_size=batch_size,\n                                         shuffle=False, num_workers=num_workers)\n```\n\n\n```\nmerge_train_set = datasets_merge.Merge_Datasets([mnist_train_set, mnist_m_train_set], get_labels=False)\nmerge_test_set = datasets_merge.Merge_Datasets([mnist_test_set, mnist_m_test_set], get_labels=False)\nmerge_train_loader = torch.utils.data.DataLoader(merge_train_set, \n                                                   batch_size=batch_size,\n                                         shuffle=True, num_workers=num_workers)\nmerge_test_loader = torch.utils.data.DataLoader(merge_test_set, \n                                                   batch_size=batch_size,\n                                         shuffle=True, num_workers=num_workers)\n```\n\n\n```\nlog_interval = 100\n```\n\n\n```\nuse_cuda = True\nuse_cuda = use_cuda and torch.cuda.is_available()\ndevice = torch.device(\"cuda\" if use_cuda else \"cpu\")\n```\n\n\n```\nlr = 0.01\nmomentum=0.9\n```\n\n\n```\nModels = namedtuple('Models', ['model_f', 'model_c', 'model_d'])\nOptims = namedtuple('Optims', ['optim_f', 'optim_c', 'optim_d'])\nCriterions = namedtuple('Criterions', ['criterion', 'criterion_domain'])\nLoaders = namedtuple('Loaders', ['train_loader', 'train_loader_domain',\n                                'source_test_loader', 'target_test_loader',\n                                'merged_test_loader'])\n```\n\n\n```\nloaders = Loaders(mnist_train_loader, mnist_m_train_loader,\n                 mnist_test_loader, mnist_m_test_loader, merge_test_loader)\n```\n\n\n```\ncriterion = F.nll_loss\ncriterion_domain = F.nll_loss\n```\n\n\n```\ncriterions = Criterions(criterion, criterion_domain)\n```\n\n\n```\nepochs=10\n```\n\n# Testing functions\n\n\n```\ndef test_grad_function(grad_function, epochs=4):\n  model_f = models.MnistFeatureExtractor().to(device)\n  model_c = models.MnistClassPredictor().to(device)\n  model_d = models.MnistDomain(grad_func = grad_function).to(device)\n  \n  optim_f = optim.SGD(model_f.parameters(), lr=lr, momentum=momentum, nesterov=True)\n  optim_c = optim.SGD(model_c.parameters(), lr=lr, momentum=momentum, nesterov=True)\n  optim_d = optim.SGD(model_d.parameters(), lr=lr, momentum=momentum, nesterov=True)\n  \n  train_models = Models(model_f, model_c, model_d)\n  optims = Optims(optim_f, optim_c, optim_d)\n  \n  model_trainer = trainer.Trainer(train_models, optims, criterions, device,\n                                train_domain=True, tune_lr=True)\n  \n  test_history = defaultdict(lambda:[])\n  model_trainer.train(4, loaders, test_history=test_history)\n```\n\n\n```\ngrad_log = []\ndef grlog(x, lambd):\n  return backward_functions.GRLog(lambd, grad_log)(x)\n```\n\n\n```\ngrad_log = []\ndef grinv(x, lambd):\n  return backward_functions.GRInv(-1, lambd, grad_log)(x)\n```\n\n\n```\ntest_grad_function(grlog)\n```\n\n    Train Epoch: \t\t\t\t\t1 [0/60000 (0%)]\tLoss: 2.302571, lr: 0.01000 lambd: 0.00000\n    Train Epoch: \t\t\t\t\t1 [12800/60000 (21%)]\tLoss: 0.632978, lr: 0.00726 lambd: 0.26052\n    Train Epoch: \t\t\t\t\t1 [25600/60000 (43%)]\tLoss: 0.591048, lr: 0.00580 lambd: 0.48792\n    Train Epoch: \t\t\t\t\t1 [38400/60000 (64%)]\tLoss: 0.404582, lr: 0.00488 lambd: 0.66404\n    Train Epoch: \t\t\t\t\t1 [51200/60000 (85%)]\tLoss: 0.264745, lr: 0.00425 lambd: 0.78820\n    \n    Target Domain Test set: Average loss: 1.2978, Accuracy: 6271/10000 (63%)\n    Source Domain Test set: Average loss: 0.1211, Accuracy: 9614/10000 (96%)\n    Domains predictor:  Accuracy: 14577/20000 (73%)\n    \n    Train Epoch: \t\t\t\t\t2 [0/60000 (0%)]\tLoss: 0.295873, lr: 0.00391 lambd: 0.84828\n    Train Epoch: \t\t\t\t\t2 [12800/60000 (21%)]\tLoss: 0.283074, lr: 0.00351 lambd: 0.90812\n    Train Epoch: \t\t\t\t\t2 [25600/60000 (43%)]\tLoss: 0.267564, lr: 0.00320 lambd: 0.94505\n    Train Epoch: \t\t\t\t\t2 [38400/60000 (64%)]\tLoss: 0.297445, lr: 0.00295 lambd: 0.96740\n    Train Epoch: \t\t\t\t\t2 [51200/60000 (85%)]\tLoss: 0.162265, lr: 0.00273 lambd: 0.98074\n    \n    Target Domain Test set: Average loss: 1.1145, Accuracy: 7147/10000 (71%)\n    Source Domain Test set: Average loss: 0.0864, Accuracy: 9736/10000 (97%)\n    Domains predictor:  Accuracy: 13037/20000 (65%)\n    \n    Train Epoch: \t\t\t\t\t3 [0/60000 (0%)]\tLoss: 0.189036, lr: 0.00261 lambd: 0.98661\n    Train Epoch: \t\t\t\t\t3 [12800/60000 (21%)]\tLoss: 0.161942, lr: 0.00245 lambd: 0.99213\n    Train Epoch: \t\t\t\t\t3 [25600/60000 (43%)]\tLoss: 0.078210, lr: 0.00231 lambd: 0.99537\n    Train Epoch: \t\t\t\t\t3 [38400/60000 (64%)]\tLoss: 0.164317, lr: 0.00218 lambd: 0.99728\n    Train Epoch: \t\t\t\t\t3 [51200/60000 (85%)]\tLoss: 0.218790, lr: 0.00208 lambd: 0.99841\n    \n    Target Domain Test set: Average loss: 0.9194, Accuracy: 7466/10000 (75%)\n    Source Domain Test set: Average loss: 0.0728, Accuracy: 9761/10000 (98%)\n    Domains predictor:  Accuracy: 13804/20000 (69%)\n    \n    Train Epoch: \t\t\t\t\t4 [0/60000 (0%)]\tLoss: 0.184848, lr: 0.00201 lambd: 0.99889\n    Train Epoch: \t\t\t\t\t4 [12800/60000 (21%)]\tLoss: 0.241879, lr: 0.00192 lambd: 0.99935\n    Train Epoch: \t\t\t\t\t4 [25600/60000 (43%)]\tLoss: 0.165163, lr: 0.00184 lambd: 0.99962\n\n\n\n```\ntest_grad_function(grinv)\n```\n\n    Train Epoch: \t\t\t\t\t1 [0/60000 (0%)]\tLoss: 2.318720, lr: 0.01000 lambd: 0.00000\n    Train Epoch: \t\t\t\t\t1 [12800/60000 (21%)]\tLoss: 0.810656, lr: 0.00726 lambd: 0.26052\n    Train Epoch: \t\t\t\t\t1 [25600/60000 (43%)]\tLoss: 0.549511, lr: 0.00580 lambd: 0.48792\n    Train Epoch: \t\t\t\t\t1 [38400/60000 (64%)]\tLoss: 0.457427, lr: 0.00488 lambd: 0.66404\n    Train Epoch: \t\t\t\t\t1 [51200/60000 (85%)]\tLoss: 0.222553, lr: 0.00425 lambd: 0.78820\n    \n    Target Domain Test set: Average loss: 1.7708, Accuracy: 6613/10000 (66%)\n    Source Domain Test set: Average loss: 0.1464, Accuracy: 9558/10000 (96%)\n    Domains predictor:  Accuracy: 10350/20000 (52%)\n    \n    Train Epoch: \t\t\t\t\t2 [0/60000 (0%)]\tLoss: 0.371020, lr: 0.00391 lambd: 0.84828\n    Train Epoch: \t\t\t\t\t2 [12800/60000 (21%)]\tLoss: 0.264524, lr: 0.00351 lambd: 0.90812\n    Train Epoch: \t\t\t\t\t2 [25600/60000 (43%)]\tLoss: 0.335705, lr: 0.00320 lambd: 0.94505\n    Train Epoch: \t\t\t\t\t2 [38400/60000 (64%)]\tLoss: 0.398240, lr: 0.00295 lambd: 0.96740\n    Train Epoch: \t\t\t\t\t2 [51200/60000 (85%)]\tLoss: 0.152408, lr: 0.00273 lambd: 0.98074\n    \n    Target Domain Test set: Average loss: 1.3885, Accuracy: 6716/10000 (67%)\n    Source Domain Test set: Average loss: 0.1081, Accuracy: 9662/10000 (97%)\n    Domains predictor:  Accuracy: 13639/20000 (68%)\n    \n    Train Epoch: \t\t\t\t\t3 [0/60000 (0%)]\tLoss: 0.273087, lr: 0.00261 lambd: 0.98661\n    Train Epoch: \t\t\t\t\t3 [12800/60000 (21%)]\tLoss: 0.390106, lr: 0.00245 lambd: 0.99213\n    Train Epoch: \t\t\t\t\t3 [25600/60000 (43%)]\tLoss: 0.130011, lr: 0.00231 lambd: 0.99537\n    Train Epoch: \t\t\t\t\t3 [38400/60000 (64%)]\tLoss: 0.231334, lr: 0.00218 lambd: 0.99728\n    Train Epoch: \t\t\t\t\t3 [51200/60000 (85%)]\tLoss: 0.475967, lr: 0.00208 lambd: 0.99841\n    \n    Target Domain Test set: Average loss: 1.0248, Accuracy: 7316/10000 (73%)\n    Source Domain Test set: Average loss: 0.0907, Accuracy: 9712/10000 (97%)\n    Domains predictor:  Accuracy: 12666/20000 (63%)\n    \n    Train Epoch: \t\t\t\t\t4 [0/60000 (0%)]\tLoss: 0.357871, lr: 0.00201 lambd: 0.99889\n    Train Epoch: \t\t\t\t\t4 [12800/60000 (21%)]\tLoss: 0.313296, lr: 0.00192 lambd: 0.99935\n    Train Epoch: \t\t\t\t\t4 [25600/60000 (43%)]\tLoss: 0.105079, lr: 0.00184 lambd: 0.99962\n    Train Epoch: \t\t\t\t\t4 [38400/60000 (64%)]\tLoss: 0.172043, lr: 0.00177 lambd: 0.99978\n    Train Epoch: \t\t\t\t\t4 [51200/60000 (85%)]\tLoss: 0.175342, lr: 0.00170 lambd: 0.99987\n    \n    Target Domain Test set: Average loss: 0.9377, Accuracy: 7331/10000 (73%)\n    Source Domain Test set: Average loss: 0.0753, Accuracy: 9746/10000 (97%)\n    Domains predictor:  Accuracy: 14138/20000 (71%)\n    \n\n\n\n```\ngrad_log = []\ndef grinv2(x, lambd):\n  return backward_functions.GRInv(1., lambd, grad_log)(x)\n```\n\n\n```\ntest_grad_function(grinv2)\n```\n\n    Train Epoch: \t\t\t\t\t1 [0/60000 (0%)]\tLoss: 2.327919, lr: 0.01000 lambd: 0.00000\n    Train Epoch: \t\t\t\t\t1 [12800/60000 (21%)]\tLoss: 0.745220, lr: 0.00726 lambd: 0.26052\n    Train Epoch: \t\t\t\t\t1 [25600/60000 (43%)]\tLoss: 0.533236, lr: 0.00580 lambd: 0.48792\n    Train Epoch: \t\t\t\t\t1 [38400/60000 (64%)]\tLoss: 0.456913, lr: 0.00488 lambd: 0.66404\n    Train Epoch: \t\t\t\t\t1 [51200/60000 (85%)]\tLoss: 0.288192, lr: 0.00425 lambd: 0.78820\n    \n    Target Domain Test set: Average loss: 2.3159, Accuracy: 3049/10000 (30%)\n    Source Domain Test set: Average loss: 0.0995, Accuracy: 9698/10000 (97%)\n    Domains predictor:  Accuracy: 19797/20000 (99%)\n    \n    Train Epoch: \t\t\t\t\t2 [0/60000 (0%)]\tLoss: 0.233389, lr: 0.00391 lambd: 0.84828\n    Train Epoch: \t\t\t\t\t2 [12800/60000 (21%)]\tLoss: 0.372094, lr: 0.00351 lambd: 0.90812\n    Train Epoch: \t\t\t\t\t2 [25600/60000 (43%)]\tLoss: 0.303700, lr: 0.00320 lambd: 0.94505\n    Train Epoch: \t\t\t\t\t2 [38400/60000 (64%)]\tLoss: 0.326173, lr: 0.00295 lambd: 0.96740\n    Train Epoch: \t\t\t\t\t2 [51200/60000 (85%)]\tLoss: 0.291125, lr: 0.00273 lambd: 0.98074\n    \n    Target Domain Test set: Average loss: 2.3855, Accuracy: 2562/10000 (26%)\n    Source Domain Test set: Average loss: 0.0701, Accuracy: 9779/10000 (98%)\n    Domains predictor:  Accuracy: 19952/20000 (100%)\n    \n    Train Epoch: \t\t\t\t\t3 [0/60000 (0%)]\tLoss: 0.210821, lr: 0.00261 lambd: 0.98661\n    Train Epoch: \t\t\t\t\t3 [12800/60000 (21%)]\tLoss: 0.246365, lr: 0.00245 lambd: 0.99213\n    Train Epoch: \t\t\t\t\t3 [25600/60000 (43%)]\tLoss: 0.287860, lr: 0.00231 lambd: 0.99537\n    Train Epoch: \t\t\t\t\t3 [38400/60000 (64%)]\tLoss: 0.165999, lr: 0.00218 lambd: 0.99728\n    Train Epoch: \t\t\t\t\t3 [51200/60000 (85%)]\tLoss: 0.073122, lr: 0.00208 lambd: 0.99841\n    \n    Target Domain Test set: Average loss: 2.6827, Accuracy: 2394/10000 (24%)\n    Source Domain Test set: Average loss: 0.0575, Accuracy: 9818/10000 (98%)\n    Domains predictor:  Accuracy: 19988/20000 (100%)\n    \n    Train Epoch: \t\t\t\t\t4 [0/60000 (0%)]\tLoss: 0.164869, lr: 0.00201 lambd: 0.99889\n    Train Epoch: \t\t\t\t\t4 [12800/60000 (21%)]\tLoss: 0.075003, lr: 0.00192 lambd: 0.99935\n    Train Epoch: \t\t\t\t\t4 [25600/60000 (43%)]\tLoss: 0.145272, lr: 0.00184 lambd: 0.99962\n    Train Epoch: \t\t\t\t\t4 [38400/60000 (64%)]\tLoss: 0.138908, lr: 0.00177 lambd: 0.99978\n    Train Epoch: \t\t\t\t\t4 [51200/60000 (85%)]\tLoss: 0.106489, lr: 0.00170 lambd: 0.99987\n    \n    Target Domain Test set: Average loss: 2.9522, Accuracy: 2196/10000 (22%)\n    Source Domain Test set: Average loss: 0.0562, Accuracy: 9821/10000 (98%)\n    Domains predictor:  Accuracy: 19993/20000 (100%)\n    \n\n\n\n```\ngrad_log = []\ndef grandmult(x, lambd):\n  return backward_functions.GRandMult(1, lambd, grad_log)(x)\n```\n\n\n```\ntest_grad_function(grandmult)\n```\n\n    Train Epoch: \t\t\t\t\t1 [0/60000 (0%)]\tLoss: 2.356206, lr: 0.01000 lambd: 0.00000\n    Train Epoch: \t\t\t\t\t1 [12800/60000 (21%)]\tLoss: 0.634399, lr: 0.00726 lambd: 0.26052\n    Train Epoch: \t\t\t\t\t1 [25600/60000 (43%)]\tLoss: 0.509887, lr: 0.00580 lambd: 0.48792\n    Train Epoch: \t\t\t\t\t1 [38400/60000 (64%)]\tLoss: 0.173120, lr: 0.00488 lambd: 0.66404\n    Train Epoch: \t\t\t\t\t1 [51200/60000 (85%)]\tLoss: 0.351211, lr: 0.00425 lambd: 0.78820\n    \n    Target Domain Test set: Average loss: 1.9298, Accuracy: 3438/10000 (34%)\n    Source Domain Test set: Average loss: 0.1113, Accuracy: 9651/10000 (97%)\n    Domains predictor:  Accuracy: 19679/20000 (98%)\n    \n    Train Epoch: \t\t\t\t\t2 [0/60000 (0%)]\tLoss: 0.223685, lr: 0.00391 lambd: 0.84828\n    Train Epoch: \t\t\t\t\t2 [12800/60000 (21%)]\tLoss: 0.170962, lr: 0.00351 lambd: 0.90812\n    Train Epoch: \t\t\t\t\t2 [25600/60000 (43%)]\tLoss: 0.182587, lr: 0.00320 lambd: 0.94505\n    Train Epoch: \t\t\t\t\t2 [38400/60000 (64%)]\tLoss: 0.096928, lr: 0.00295 lambd: 0.96740\n    Train Epoch: \t\t\t\t\t2 [51200/60000 (85%)]\tLoss: 0.161787, lr: 0.00273 lambd: 0.98074\n    \n    Target Domain Test set: Average loss: 2.1723, Accuracy: 2546/10000 (25%)\n    Source Domain Test set: Average loss: 0.0742, Accuracy: 9770/10000 (98%)\n    Domains predictor:  Accuracy: 19886/20000 (99%)\n    \n    Train Epoch: \t\t\t\t\t3 [0/60000 (0%)]\tLoss: 0.254556, lr: 0.00261 lambd: 0.98661\n    Train Epoch: \t\t\t\t\t3 [12800/60000 (21%)]\tLoss: 0.233278, lr: 0.00245 lambd: 0.99213\n    Train Epoch: \t\t\t\t\t3 [25600/60000 (43%)]\tLoss: 0.178423, lr: 0.00231 lambd: 0.99537\n    Train Epoch: \t\t\t\t\t3 [38400/60000 (64%)]\tLoss: 0.196384, lr: 0.00218 lambd: 0.99728\n    Train Epoch: \t\t\t\t\t3 [51200/60000 (85%)]\tLoss: 0.183332, lr: 0.00208 lambd: 0.99841\n    \n    Target Domain Test set: Average loss: 2.0319, Accuracy: 2830/10000 (28%)\n    Source Domain Test set: Average loss: 0.0538, Accuracy: 9836/10000 (98%)\n    Domains predictor:  Accuracy: 19911/20000 (100%)\n    \n    Train Epoch: \t\t\t\t\t4 [0/60000 (0%)]\tLoss: 0.116799, lr: 0.00201 lambd: 0.99889\n    Train Epoch: \t\t\t\t\t4 [12800/60000 (21%)]\tLoss: 0.159713, lr: 0.00192 lambd: 0.99935\n    Train Epoch: \t\t\t\t\t4 [25600/60000 (43%)]\tLoss: 0.168556, lr: 0.00184 lambd: 0.99962\n    Train Epoch: \t\t\t\t\t4 [38400/60000 (64%)]\tLoss: 0.187594, lr: 0.00177 lambd: 0.99978\n    Train Epoch: \t\t\t\t\t4 [51200/60000 (85%)]\tLoss: 0.108288, lr: 0.00170 lambd: 0.99987\n    \n    Target Domain Test set: Average loss: 2.2315, Accuracy: 2308/10000 (23%)\n    Source Domain Test set: Average loss: 0.0509, Accuracy: 9838/10000 (98%)\n    Domains predictor:  Accuracy: 19960/20000 (100%)\n    \n\n\n\n```\ngrad_log = []\ndef grandmult(x, lambd):\n  return backward_functions.GRandMult(1e-1, lambd, grad_log)(x)\n```\n\n\n```\ntest_grad_function(grandmult)\n```\n\n    Train Epoch: \t\t\t\t\t1 [0/60000 (0%)]\tLoss: 2.312164, lr: 0.01000 lambd: 0.00000\n    Train Epoch: \t\t\t\t\t1 [12800/60000 (21%)]\tLoss: 0.551612, lr: 0.00726 lambd: 0.26052\n    Train Epoch: \t\t\t\t\t1 [25600/60000 (43%)]\tLoss: 0.499983, lr: 0.00580 lambd: 0.48792\n    Train Epoch: \t\t\t\t\t1 [38400/60000 (64%)]\tLoss: 0.353211, lr: 0.00488 lambd: 0.66404\n    Train Epoch: \t\t\t\t\t1 [51200/60000 (85%)]\tLoss: 0.277616, lr: 0.00425 lambd: 0.78820\n    \n    Target Domain Test set: Average loss: 1.5431, Accuracy: 4493/10000 (45%)\n    Source Domain Test set: Average loss: 0.1045, Accuracy: 9670/10000 (97%)\n    Domains predictor:  Accuracy: 19372/20000 (97%)\n    \n    Train Epoch: \t\t\t\t\t2 [0/60000 (0%)]\tLoss: 0.343850, lr: 0.00391 lambd: 0.84828\n    Train Epoch: \t\t\t\t\t2 [12800/60000 (21%)]\tLoss: 0.236943, lr: 0.00351 lambd: 0.90812\n    Train Epoch: \t\t\t\t\t2 [25600/60000 (43%)]\tLoss: 0.216584, lr: 0.00320 lambd: 0.94505\n    Train Epoch: \t\t\t\t\t2 [38400/60000 (64%)]\tLoss: 0.133211, lr: 0.00295 lambd: 0.96740\n    Train Epoch: \t\t\t\t\t2 [51200/60000 (85%)]\tLoss: 0.202780, lr: 0.00273 lambd: 0.98074\n    \n    Target Domain Test set: Average loss: 1.4694, Accuracy: 4692/10000 (47%)\n    Source Domain Test set: Average loss: 0.0734, Accuracy: 9756/10000 (98%)\n    Domains predictor:  Accuracy: 19642/20000 (98%)\n    \n    Train Epoch: \t\t\t\t\t3 [0/60000 (0%)]\tLoss: 0.237773, lr: 0.00261 lambd: 0.98661\n    Train Epoch: \t\t\t\t\t3 [12800/60000 (21%)]\tLoss: 0.107190, lr: 0.00245 lambd: 0.99213\n    Train Epoch: \t\t\t\t\t3 [25600/60000 (43%)]\tLoss: 0.184812, lr: 0.00231 lambd: 0.99537\n    Train Epoch: \t\t\t\t\t3 [38400/60000 (64%)]\tLoss: 0.199738, lr: 0.00218 lambd: 0.99728\n    Train Epoch: \t\t\t\t\t3 [51200/60000 (85%)]\tLoss: 0.153193, lr: 0.00208 lambd: 0.99841\n    \n    Target Domain Test set: Average loss: 1.5249, Accuracy: 4696/10000 (47%)\n    Source Domain Test set: Average loss: 0.0575, Accuracy: 9820/10000 (98%)\n    Domains predictor:  Accuracy: 19755/20000 (99%)\n    \n    Train Epoch: \t\t\t\t\t4 [0/60000 (0%)]\tLoss: 0.079153, lr: 0.00201 lambd: 0.99889\n    Train Epoch: \t\t\t\t\t4 [12800/60000 (21%)]\tLoss: 0.149514, lr: 0.00192 lambd: 0.99935\n    Train Epoch: \t\t\t\t\t4 [25600/60000 (43%)]\tLoss: 0.103344, lr: 0.00184 lambd: 0.99962\n    Train Epoch: \t\t\t\t\t4 [38400/60000 (64%)]\tLoss: 0.132674, lr: 0.00177 lambd: 0.99978\n    Train Epoch: \t\t\t\t\t4 [51200/60000 (85%)]\tLoss: 0.108807, lr: 0.00170 lambd: 0.99987\n    \n    Target Domain Test set: Average loss: 1.5512, Accuracy: 4521/10000 (45%)\n    Source Domain Test set: Average loss: 0.0498, Accuracy: 9843/10000 (98%)\n    Domains predictor:  Accuracy: 19818/20000 (99%)\n    \n\n\n\n```\ngrad_log = []\ndef grand(x, lambd):\n  return backward_functions.GRand(1e-3, lambd, grad_log)(x)\n```\n\n\n```\ntest_grad_function(grand)\n```\n\n    Exception ignored in: <bound method _DataLoaderIter.__del__ of <torch.utils.data.dataloader._DataLoaderIter object at 0x7f1853807358>>\n    Traceback (most recent call last):\n      File \"/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py\", line 717, in __del__\n        self._shutdown_workers()\n      File \"/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py\", line 713, in _shutdown_workers\n        w.join()\n      File \"/usr/lib/python3.6/multiprocessing/process.py\", line 122, in join\n        assert self._parent_pid == os.getpid(), 'can only join a child process'\n    AssertionError: can only join a child process\n    Exception ignored in: <bound method _DataLoaderIter.__del__ of <torch.utils.data.dataloader._DataLoaderIter object at 0x7f185046d3c8>>\n    Traceback (most recent call last):\n      File \"/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py\", line 717, in __del__\n        self._shutdown_workers()\n      File \"/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py\", line 713, in _shutdown_workers\n        w.join()\n      File \"/usr/lib/python3.6/multiprocessing/process.py\", line 122, in join\n        assert self._parent_pid == os.getpid(), 'can only join a child process'\n    AssertionError: can only join a child process\n    Exception ignored in: <bound method _DataLoaderIter.__del__ of <torch.utils.data.dataloader._DataLoaderIter object at 0x7f1853738c50>>\n    Traceback (most recent call last):\n      File \"/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py\", line 717, in __del__\n        self._shutdown_workers()\n      File \"/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py\", line 713, in _shutdown_workers\n        w.join()\n      File \"/usr/lib/python3.6/multiprocessing/process.py\", line 122, in join\n        assert self._parent_pid == os.getpid(), 'can only join a child process'\n    AssertionError: can only join a child process\n    Exception ignored in: <bound method _DataLoaderIter.__del__ of <torch.utils.data.dataloader._DataLoaderIter object at 0x7f1853807358>>\n    Traceback (most recent call last):\n      File \"/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py\", line 717, in __del__\n        self._shutdown_workers()\n      File \"/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py\", line 713, in _shutdown_workers\n        w.join()\n      File \"/usr/lib/python3.6/multiprocessing/process.py\", line 122, in join\n        assert self._parent_pid == os.getpid(), 'can only join a child process'\n    AssertionError: can only join a child process\n    Exception ignored in: <bound method _DataLoaderIter.__del__ of <torch.utils.data.dataloader._DataLoaderIter object at 0x7f185046d3c8>>\n\n\n    Train Epoch: \t\t\t\t\t1 [0/60000 (0%)]\tLoss: 2.317810, lr: 0.01000 lambd: 0.00000\n\n\n    Traceback (most recent call last):\n      File \"/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py\", line 717, in __del__\n        self._shutdown_workers()\n      File \"/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py\", line 713, in _shutdown_workers\n        w.join()\n      File \"/usr/lib/python3.6/multiprocessing/process.py\", line 122, in join\n        assert self._parent_pid == os.getpid(), 'can only join a child process'\n    AssertionError: can only join a child process\n    Exception ignored in: <bound method _DataLoaderIter.__del__ of <torch.utils.data.dataloader._DataLoaderIter object at 0x7f1853738c50>>\n    Traceback (most recent call last):\n      File \"/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py\", line 717, in __del__\n        self._shutdown_workers()\n      File \"/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py\", line 713, in _shutdown_workers\n        w.join()\n      File \"/usr/lib/python3.6/multiprocessing/process.py\", line 122, in join\n        assert self._parent_pid == os.getpid(), 'can only join a child process'\n    AssertionError: can only join a child process\n\n\n    Train Epoch: \t\t\t\t\t1 [12800/60000 (21%)]\tLoss: 0.712805, lr: 0.00726 lambd: 0.26052\n    Train Epoch: \t\t\t\t\t1 [25600/60000 (43%)]\tLoss: 0.296397, lr: 0.00580 lambd: 0.48792\n    Train Epoch: \t\t\t\t\t1 [38400/60000 (64%)]\tLoss: 0.255301, lr: 0.00488 lambd: 0.66404\n    Train Epoch: \t\t\t\t\t1 [51200/60000 (85%)]\tLoss: 0.488634, lr: 0.00425 lambd: 0.78820\n    \n    Target Domain Test set: Average loss: 1.4624, Accuracy: 5065/10000 (51%)\n    Source Domain Test set: Average loss: 0.1266, Accuracy: 9597/10000 (96%)\n    Domains predictor:  Accuracy: 19248/20000 (96%)\n    \n    Train Epoch: \t\t\t\t\t2 [0/60000 (0%)]\tLoss: 0.316768, lr: 0.00391 lambd: 0.84828\n    Train Epoch: \t\t\t\t\t2 [12800/60000 (21%)]\tLoss: 0.188924, lr: 0.00351 lambd: 0.90812\n    Train Epoch: \t\t\t\t\t2 [25600/60000 (43%)]\tLoss: 0.195166, lr: 0.00320 lambd: 0.94505\n    Train Epoch: \t\t\t\t\t2 [38400/60000 (64%)]\tLoss: 0.286140, lr: 0.00295 lambd: 0.96740\n    Train Epoch: \t\t\t\t\t2 [51200/60000 (85%)]\tLoss: 0.112674, lr: 0.00273 lambd: 0.98074\n    \n    Target Domain Test set: Average loss: 1.5594, Accuracy: 4544/10000 (45%)\n    Source Domain Test set: Average loss: 0.1062, Accuracy: 9645/10000 (96%)\n    Domains predictor:  Accuracy: 18857/20000 (94%)\n    \n    Train Epoch: \t\t\t\t\t3 [0/60000 (0%)]\tLoss: 0.336886, lr: 0.00261 lambd: 0.98661\n    Train Epoch: \t\t\t\t\t3 [12800/60000 (21%)]\tLoss: 0.251837, lr: 0.00245 lambd: 0.99213\n    Train Epoch: \t\t\t\t\t3 [25600/60000 (43%)]\tLoss: 0.221007, lr: 0.00231 lambd: 0.99537\n    Train Epoch: \t\t\t\t\t3 [38400/60000 (64%)]\tLoss: 0.228762, lr: 0.00218 lambd: 0.99728\n    Train Epoch: \t\t\t\t\t3 [51200/60000 (85%)]\tLoss: 0.464130, lr: 0.00208 lambd: 0.99841\n    \n    Target Domain Test set: Average loss: 1.6057, Accuracy: 4844/10000 (48%)\n    Source Domain Test set: Average loss: 0.0963, Accuracy: 9720/10000 (97%)\n    Domains predictor:  Accuracy: 18671/20000 (93%)\n    \n    Train Epoch: \t\t\t\t\t4 [0/60000 (0%)]\tLoss: 0.212811, lr: 0.00201 lambd: 0.99889\n    Train Epoch: \t\t\t\t\t4 [12800/60000 (21%)]\tLoss: 0.214758, lr: 0.00192 lambd: 0.99935\n    Train Epoch: \t\t\t\t\t4 [25600/60000 (43%)]\tLoss: 0.165383, lr: 0.00184 lambd: 0.99962\n    Train Epoch: \t\t\t\t\t4 [38400/60000 (64%)]\tLoss: 0.199856, lr: 0.00177 lambd: 0.99978\n    Train Epoch: \t\t\t\t\t4 [51200/60000 (85%)]\tLoss: 0.125342, lr: 0.00170 lambd: 0.99987\n    \n    Target Domain Test set: Average loss: 1.5942, Accuracy: 4788/10000 (48%)\n    Source Domain Test set: Average loss: 0.0893, Accuracy: 9712/10000 (97%)\n    Domains predictor:  Accuracy: 18776/20000 (94%)\n    \n\n\n# Gradient Inverse Layer test\n\n\n```\ndef grinv(x, lambd):\n  return backward_functions.GRInv(-1, lambd)(x)\n```\n\n\n```\nmodel_f = models.MnistFeatureExtractor().to(device)\nmodel_c = models.MnistClassPredictor().to(device)\nmodel_d = models.MnistDomain(grad_func=grinv).to(device)\noptim_f = optim.SGD(model_f.parameters(), lr=lr, momentum=momentum, nesterov=True)\noptim_c = optim.SGD(model_c.parameters(), lr=lr, momentum=momentum, nesterov=True)\noptim_d = optim.SGD(model_d.parameters(), lr=lr, momentum=momentum, nesterov=True)\n\ntrain_models = Models(model_f, model_c, model_d)\noptims = Optims(optim_f, optim_c, optim_d)\n```\n\n\n```\nmodel_trainer = trainer.Trainer(train_models, optims, criterions, device,\n                                tune_lr=True)\n```\n\n\n```\ntest_history = defaultdict(lambda:[])\nmodel_trainer.train(epochs, loaders, test_history=test_history)\n```\n\n    Train Epoch: \t\t\t\t\t1 [0/60000 (0%)]\tLoss: 2.312509, lr: 0.01000 lambd: 0.00000\n    Train Epoch: \t\t\t\t\t1 [12800/60000 (21%)]\tLoss: 0.470715, lr: 0.00865 lambd: 0.10626\n    Train Epoch: \t\t\t\t\t1 [25600/60000 (43%)]\tLoss: 0.401973, lr: 0.00766 lambd: 0.21015\n    Train Epoch: \t\t\t\t\t1 [38400/60000 (64%)]\tLoss: 0.208745, lr: 0.00690 lambd: 0.30951\n    Train Epoch: \t\t\t\t\t1 [51200/60000 (85%)]\tLoss: 0.331025, lr: 0.00630 lambd: 0.40253\n    \n    Target Domain Test set: Average loss: 1.2261, Accuracy: 6299/10000 (63%)\n    Source Domain Test set: Average loss: 0.1081, Accuracy: 9680/10000 (97%)\n    Domains predictor:  Accuracy: 14677/20000 (73%)\n    \n    Train Epoch: \t\t\t\t\t2 [0/60000 (0%)]\tLoss: 0.371136, lr: 0.00595 lambd: 0.46212\n    Train Epoch: \t\t\t\t\t2 [12800/60000 (21%)]\tLoss: 0.307323, lr: 0.00551 lambd: 0.54178\n    Train Epoch: \t\t\t\t\t2 [25600/60000 (43%)]\tLoss: 0.395909, lr: 0.00514 lambd: 0.61276\n    Train Epoch: \t\t\t\t\t2 [38400/60000 (64%)]\tLoss: 0.271887, lr: 0.00483 lambd: 0.67507\n    Train Epoch: \t\t\t\t\t2 [51200/60000 (85%)]\tLoss: 0.285515, lr: 0.00455 lambd: 0.72904\n    \n    Target Domain Test set: Average loss: 1.2675, Accuracy: 7115/10000 (71%)\n    Source Domain Test set: Average loss: 0.0991, Accuracy: 9695/10000 (97%)\n    Domains predictor:  Accuracy: 13576/20000 (68%)\n    \n    Train Epoch: \t\t\t\t\t3 [0/60000 (0%)]\tLoss: 0.158411, lr: 0.00439 lambd: 0.76159\n    Train Epoch: \t\t\t\t\t3 [12800/60000 (21%)]\tLoss: 0.225826, lr: 0.00417 lambd: 0.80288\n    Train Epoch: \t\t\t\t\t3 [25600/60000 (43%)]\tLoss: 0.284502, lr: 0.00397 lambd: 0.83768\n    Train Epoch: \t\t\t\t\t3 [38400/60000 (64%)]\tLoss: 0.182873, lr: 0.00379 lambd: 0.86678\n    Train Epoch: \t\t\t\t\t3 [51200/60000 (85%)]\tLoss: 0.272523, lr: 0.00364 lambd: 0.89098\n    \n    Target Domain Test set: Average loss: 0.9923, Accuracy: 7328/10000 (73%)\n    Source Domain Test set: Average loss: 0.0817, Accuracy: 9736/10000 (97%)\n    Domains predictor:  Accuracy: 12820/20000 (64%)\n    \n    Train Epoch: \t\t\t\t\t4 [0/60000 (0%)]\tLoss: 0.145459, lr: 0.00354 lambd: 0.90515\n    Train Epoch: \t\t\t\t\t4 [12800/60000 (21%)]\tLoss: 0.103794, lr: 0.00340 lambd: 0.92267\n    Train Epoch: \t\t\t\t\t4 [25600/60000 (43%)]\tLoss: 0.321543, lr: 0.00328 lambd: 0.93706\n    Train Epoch: \t\t\t\t\t4 [38400/60000 (64%)]\tLoss: 0.179386, lr: 0.00316 lambd: 0.94884\n    Train Epoch: \t\t\t\t\t4 [51200/60000 (85%)]\tLoss: 0.218501, lr: 0.00306 lambd: 0.95846\n    \n    Target Domain Test set: Average loss: 1.0416, Accuracy: 7215/10000 (72%)\n    Source Domain Test set: Average loss: 0.0614, Accuracy: 9807/10000 (98%)\n    Domains predictor:  Accuracy: 13779/20000 (69%)\n    \n    Train Epoch: \t\t\t\t\t5 [0/60000 (0%)]\tLoss: 0.169267, lr: 0.00299 lambd: 0.96403\n    Train Epoch: \t\t\t\t\t5 [12800/60000 (21%)]\tLoss: 0.177790, lr: 0.00290 lambd: 0.97084\n    Train Epoch: \t\t\t\t\t5 [25600/60000 (43%)]\tLoss: 0.220318, lr: 0.00281 lambd: 0.97637\n    Train Epoch: \t\t\t\t\t5 [38400/60000 (64%)]\tLoss: 0.137977, lr: 0.00273 lambd: 0.98087\n    Train Epoch: \t\t\t\t\t5 [51200/60000 (85%)]\tLoss: 0.232367, lr: 0.00266 lambd: 0.98452\n    \n    Target Domain Test set: Average loss: 0.9560, Accuracy: 7393/10000 (74%)\n    Source Domain Test set: Average loss: 0.0687, Accuracy: 9778/10000 (98%)\n    Domains predictor:  Accuracy: 14327/20000 (72%)\n    \n    Train Epoch: \t\t\t\t\t6 [0/60000 (0%)]\tLoss: 0.200763, lr: 0.00261 lambd: 0.98661\n    Train Epoch: \t\t\t\t\t6 [12800/60000 (21%)]\tLoss: 0.173522, lr: 0.00254 lambd: 0.98917\n    Train Epoch: \t\t\t\t\t6 [25600/60000 (43%)]\tLoss: 0.108857, lr: 0.00248 lambd: 0.99124\n    Train Epoch: \t\t\t\t\t6 [38400/60000 (64%)]\tLoss: 0.126563, lr: 0.00242 lambd: 0.99292\n    Train Epoch: \t\t\t\t\t6 [51200/60000 (85%)]\tLoss: 0.141906, lr: 0.00236 lambd: 0.99428\n    \n    Target Domain Test set: Average loss: 0.8650, Accuracy: 7519/10000 (75%)\n    Source Domain Test set: Average loss: 0.0599, Accuracy: 9809/10000 (98%)\n    Domains predictor:  Accuracy: 12617/20000 (63%)\n    \n    Train Epoch: \t\t\t\t\t7 [0/60000 (0%)]\tLoss: 0.182191, lr: 0.00232 lambd: 0.99505\n    Train Epoch: \t\t\t\t\t7 [12800/60000 (21%)]\tLoss: 0.201400, lr: 0.00227 lambd: 0.99600\n    Train Epoch: \t\t\t\t\t7 [25600/60000 (43%)]\tLoss: 0.115925, lr: 0.00222 lambd: 0.99677\n    Train Epoch: \t\t\t\t\t7 [38400/60000 (64%)]\tLoss: 0.166766, lr: 0.00218 lambd: 0.99739\n    Train Epoch: \t\t\t\t\t7 [51200/60000 (85%)]\tLoss: 0.189622, lr: 0.00213 lambd: 0.99789\n    \n    Target Domain Test set: Average loss: 0.8678, Accuracy: 7332/10000 (73%)\n    Source Domain Test set: Average loss: 0.0636, Accuracy: 9796/10000 (98%)\n    Domains predictor:  Accuracy: 13513/20000 (68%)\n    \n    Train Epoch: \t\t\t\t\t8 [0/60000 (0%)]\tLoss: 0.107886, lr: 0.00210 lambd: 0.99818\n    Train Epoch: \t\t\t\t\t8 [12800/60000 (21%)]\tLoss: 0.134360, lr: 0.00206 lambd: 0.99853\n    Train Epoch: \t\t\t\t\t8 [25600/60000 (43%)]\tLoss: 0.202102, lr: 0.00202 lambd: 0.99881\n    Train Epoch: \t\t\t\t\t8 [38400/60000 (64%)]\tLoss: 0.237934, lr: 0.00198 lambd: 0.99904\n    Train Epoch: \t\t\t\t\t8 [51200/60000 (85%)]\tLoss: 0.116310, lr: 0.00195 lambd: 0.99922\n    \n    Target Domain Test set: Average loss: 0.8703, Accuracy: 7438/10000 (74%)\n    Source Domain Test set: Average loss: 0.0566, Accuracy: 9810/10000 (98%)\n    Domains predictor:  Accuracy: 13463/20000 (67%)\n    \n    Train Epoch: \t\t\t\t\t9 [0/60000 (0%)]\tLoss: 0.117980, lr: 0.00192 lambd: 0.99933\n    Train Epoch: \t\t\t\t\t9 [12800/60000 (21%)]\tLoss: 0.236234, lr: 0.00189 lambd: 0.99946\n    Train Epoch: \t\t\t\t\t9 [25600/60000 (43%)]\tLoss: 0.235230, lr: 0.00186 lambd: 0.99956\n    Train Epoch: \t\t\t\t\t9 [38400/60000 (64%)]\tLoss: 0.136297, lr: 0.00183 lambd: 0.99965\n    Train Epoch: \t\t\t\t\t9 [51200/60000 (85%)]\tLoss: 0.181172, lr: 0.00180 lambd: 0.99971\n    \n    Target Domain Test set: Average loss: 0.7648, Accuracy: 7665/10000 (77%)\n    Source Domain Test set: Average loss: 0.0642, Accuracy: 9814/10000 (98%)\n    Domains predictor:  Accuracy: 13079/20000 (65%)\n    \n    Train Epoch: \t\t\t\t\t10 [0/60000 (0%)]\tLoss: 0.093681, lr: 0.00178 lambd: 0.99975\n    Train Epoch: \t\t\t\t\t10 [12800/60000 (21%)]\tLoss: 0.141431, lr: 0.00175 lambd: 0.99980\n    Train Epoch: \t\t\t\t\t10 [25600/60000 (43%)]\tLoss: 0.117273, lr: 0.00172 lambd: 0.99984\n    Train Epoch: \t\t\t\t\t10 [38400/60000 (64%)]\tLoss: 0.232385, lr: 0.00170 lambd: 0.99987\n    Train Epoch: \t\t\t\t\t10 [51200/60000 (85%)]\tLoss: 0.148965, lr: 0.00167 lambd: 0.99989\n    \n    Target Domain Test set: Average loss: 0.7481, Accuracy: 7762/10000 (78%)\n    Source Domain Test set: Average loss: 0.0525, Accuracy: 9838/10000 (98%)\n    Domains predictor:  Accuracy: 13521/20000 (68%)\n    \n\n\n\n```\n\n```\n", "meta": {"hexsha": "71fbbbe05961f9b0fcfc58a8fa0c587c97e05f76", "size": 57297, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "BackwardFunctions.ipynb", "max_stars_repo_name": "wiatrak2/BScThesis", "max_stars_repo_head_hexsha": "e5dd012fd9052e7088d8464b409dc055dbfcf840", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BackwardFunctions.ipynb", "max_issues_repo_name": "wiatrak2/BScThesis", "max_issues_repo_head_hexsha": "e5dd012fd9052e7088d8464b409dc055dbfcf840", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BackwardFunctions.ipynb", "max_forks_repo_name": "wiatrak2/BScThesis", "max_forks_repo_head_hexsha": "e5dd012fd9052e7088d8464b409dc055dbfcf840", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.3299050633, "max_line_length": 483, "alphanum_fraction": 0.5236225282, "converted": true, "num_tokens": 13383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.09807933072030336, "lm_q1q2_score": 0.04445561869439693}}
{"text": "\n\n<style type=\"text/css\">\n  div#preloader { position: fixed;\n      left: 0;\n      top: 0;\n      z-index: 999;\n      width: 100%;\n      height: 100%;\n      overflow: visible;\n      background: #fff url('http://preloaders.net/preloaders/720/Moving%20line.gif') no-repeat center center;\n  }\n\n</style>\n\n<div id=\"preloader\"></div>\n\n<table width=60% >\n    <tr style=\"background-color: white;\">\n        <td></td>\n<!--         <td></td> -->\n    </tr>\n</table>\n\n---\n\n\n\n---\n\n<br>\n\n<center> <h1> Quantum teleportation </h1></center>\n\n<div class=\"alert alert-info\">\n\u201cA trick that quantum magicians use to produce phenomena that cannot be imitated by classical magicians.\u201d - A. Peres\n</div>\n\nTo get a feel for how Strawberry Fields works, let's walk through an example of quantum teleportation.\n\n\n## Background info\nQuantum teleportation is the reliable transfer of an unknown quantum state across spatially separated qubits or qumodes, through the use of a classical transmission channel and quantum entanglement. Considered a fundamental quantum information protocol, it has applications ranging from quantum communication to enabling distributed information processing in quantum computation.\n\nIn general, all quantum teleportation circuits work on the same basic principle. Two distant observers, Alice and Bob, share a maximally entangled quantum state (in discrete variables, any one of the four Bell states; or in CV, a maximally entangled state for a fixed energy), and have access to a classical communication channel. Alice, in possession of an unknown state which she wishes to transport to Bob, makes a joint measurement of the unknown state and her half of the entangled state, by projecting onto the Bell basis. By transmitting the results of her measurement to Bob, Bob is then able to transform his half of the entangled state to an accurate replica of the original unknown state, by performing a conditional phase flip (for qubits) or displacement (for qumodes).\n\n## The teleportation circuit\n\n\n\n$$\\newcommand{ket}[1]{\\left|#1\\right\\rangle}$$\n\n* Here, qumodes $q_1$ and $q_2$ are initially prepared as highly squeezed vacuum states in momentum and position space respectively. We do this by highly squeezing these two qumodes in the phase space:\n\n\\begin{align}\n&\\ket{0}_x \\approx S(2)\\ket{0}\\\\\n&\\ket{0}_p \\approx S(-2) \\ket{0}\n\\end{align}\n\n\n* They are then maximally entangled by a 50-50 beamsplitter. This is a beamsplitter with parameters $\\theta=\\pi/4$, $\\phi=0$.\n\n\n\n* These two qumodes are now spatially separated, with $\\ket{q_1}$ held by Alice, and $\\ket{q_2}$ held by Bob, with the two connected via the classical communication channels $c_0$ and $c_1$.\n\n\n* To teleport her unknown state $\\ket{\\psi}$ to Bob, Alice now performs a projective measurement of her entire system onto the maximally entangled basis states. This is done by entangling $\\ket{\\psi}$ and $\\ket{q_1}$ via another 50-50 beamsplitter, before performing two homodyne measurements, in the $x$ and $p$ quadratures respectively. The two resulting measurements are referred to as $m_1$ and $m_2$.\n\n\n* The results of these measurements are then transmitted to Bob, who performs both a position displacement (conditional on the $x$ measurement) using a $X$ gate, and a momentum displacement (conditional on the $p$ measurement) using a $Z$ gate, to recover exactly the transmitted state $\\ket{\\psi}$. In particular, Bob has to make the following displacements:\n\n\\begin{align}\nZ\\left(-\\sqrt{2}m_2\\right)X\\left(\\sqrt{2}m_1\\right)\\ket{q_2}\n\\end{align}\n\n## Importing Strawberry Fields\n\nWe import the Strawberry Fields, as well as all quantum operations, using the following commands:\n\n\n```python\nimport strawberryfields as sf\nfrom strawberryfields.ops import *\n```\n\nThe first import statement imports Strawberry Fields as sf, allowing us to access the engine and backends. The second import statement imports all available CV gates into the global namespace.\n\nIn addition, we will also need some utilities from the `utils` subpackage, a module containing Strawberry Fields utilities and extensions. Finally, we import $\\pi$ and the square root from NumPy so that we can pass angle parameters to gates such as beamsplitters, and perform some custom classical processing.\n\n\n```python\nfrom strawberryfields.utils import scale\nfrom numpy import pi, sqrt\n```\n\n\n<div class=\"alert alert-success\" style=\"border: 0px; border-left: 3px solid #119a68; color: black; background-color: #daf0e9\">\n<p style=\"color: #119a68;\">**Available CV gates**</p>\n\nCheck out our <a href=\"https://strawberryfields.readthedocs.io/en/stable/op_conventions.html\">documentation</a> to see the available CV gates, states, measurements, and other operations available in Strawberry Fields.\n</div>\n\n\n## Engine initialization\n\nWe can now initialise our chosen backend, engine, and quantum register, using the \n`sf.Engine()` function, which has the following syntax:\n\n    eng, q = sf.Engine(num_subsystems)\n\nwhere\n\n* `num_subsystems` (*int*) is the number of modes we want to initialise in our quantum register\n\nreturning\n\n* `eng` is the resulting engine; we use this engine object to manipulate our engine/circuit.\n* `q` (*tuple*) contains the **qumodes** in our quantum circuit. They are accessed by indexing; for example `q[0]` for the first qumode, `q[1]` for the second qumode, etc.\n\n<div class=\"alert alert-info\" style=\"border: 0px; border-left: 3px solid #31708f; color: black; background-color: #d9edf7\">\n<p style=\"color: #31708f;\">**Exercise**</p>\n\nInitialise an engine below, using the correct number of modes for quantum teleportation as per the circuit above.\n\n</div>\n\n\n```python\neng, q = sf.Engine(3)\n```\n\n## Circuit construction\n\nNow that we have created the engine and qumodes, we can start to construct our circuit. In Strawberry Fields, circuit construction *always* occurs within a `with eng:` context. Inside this context, operations are applied using the syntax\n\n```python3\nwith eng:\n    Operation(arguments) | (sequence of qumodes)\n```\n\nFor example, to apply prepare a squeezed state, followed by a beamsplitter, we can write\n\n```python3\nwith eng:\n    Squeezed(0.5) | q[0]\n    BSgate(pi/4, 0) | (q[0], q[1])\n```\n\nSome operations in Strawberry Fields apply to one mode, and some apply to two. Be sure to check the documentation to double check the operation arguments, and to see how many qumodes they act on.\n\n<div class=\"alert alert-info\" style=\"border: 0px; border-left: 3px solid #31708f; color: black; background-color: #d9edf7\">\n<p style=\"color: #31708f;\">**Exercise**</p>\n\nThe cell below corresponding to the teleportation circuit is partially complete. Using the above, and referring to the docs, fill in the cell below to finish constructing the teleportation circuit.\n</div>\n\n\n\n\n```python\nwith eng:\n    # prepare the initial states\n    Coherent(1+0.5j) | q[0]  # This is the state we will teleport\n    Sgate(-2) | q[1]\n    Sgate(2) | q[2]\n    \n    # apply the gates\n    BSgate(pi/4, 0) | (q[1], q[2])  # a 50-50 beamsplitter\n    BSgate(pi/4, 0) | (q[0], q[1])  # a 50-50 beamsplitter\n    \n    # perform the homodyne measurements\n    MeasureX | q[0]\n    MeasureP | q[1]    \n    \n    # displacement gates conditioned on the measurements\n    Xgate(scale(q[0], sqrt(2))) | q[2]\n    Zgate(scale(q[1], sqrt(2))) | q[2]\n```\n\nA couple of things to note:\n\n* **Operations must be applied in temporal order.** Different operation orderings can result in the same quantum circuit, providing the operations do not apply sequentially to the same mode.\n\n\n* **Gates are standard Python objects, and can be treated as such.** In this case, since both beamsplitters use the same parameters, a single instance can be created and stored under variable BS.\n\n\n* **The results of measured modes are passed to gates simply by passing the measured mode as an argument.** In order to perform additional classical processing to the measured mode, we can use the basic classical processing functions available in `strawberryfields.utils`; here we used the `scale()` function.\n\n\n## Running the engine\n\nOnce the circuit is constructed, you can run the engine via the `eng.run()` method:\n\n```python3\n    state = eng.run(backend, return_state=True, modes=None, *args, **kwargs)\n```\n\nThe eng.run method accepts the arguments\n\n* `backend`: a string representing the Strawberry Fields backend we wish to use; we have the choice of two Fock basis backends, the NumPy based (`'fock'`) and Tensorflow (`'tf'`), and one Gaussian representation backend (`'gaussian'`).\n\n    This is required the first time running the engine, but optional for subsequent runs - if not provided, the previously used backend will continue to be used.\n\nand returns\n\n* `state`: an object representing the quantum state after the circuit simulation.\n\n    Depending on backend used, the state returned might be a BaseFockState, which represents the state using the Fock/number basis, or might be a BaseGaussianState, which represents the state using Gaussian representation, as a vector of means and a covariance matrix. Many methods are provided for state manipulation, see Quantum states API for more details.\n\nFor more details on the technical differences between the backends, see the [Backend API](https://strawberryfields.readthedocs.io/en/stable/code/backend.html) in the documentation.\n\n### How do we choose a backend?\n\n\n* **Fock backends** are backends which represent the quantum state and operations via the Fock basis. <br>These can represent all possible continuous-variable states and operations, but also introduce numerical error due to truncation of the Fock space, and can consume more memory.\n\n\n* The **gaussian backend**, due to its ability to represent states and operations as gaussian objects/transforms in the phase space, can be less computationally intensive then the Fock backends. <br>However, it cannot represent non-gaussian operations and states (such as the cubic phase gate, fock measurements, and fock states, amongst others).</li>\n\nIn the Fock backends, due to the infinite Hilbert space, we must specify a **cutoff dimension**. For example, choosing `cutoff_dim=5`, a state $|\\psi\\rangle$ has approximation\n\n$$|{\\psi}\\rangle = \\sum_{n=0}^\\infty c_n|{n}\\rangle \\approx\\sum_{n=0}^{5-1} c_n|{n}\\rangle$$\n\nin our truncated Fock basis - i.e. all information of quantum amplitudes of Fock states $|n\\rangle$, with $n\\geq 5$, is discarded.\n\n<div class=\"alert\" style=\"border: 0px; border-left: 3px solid #F0AD4E; color: black; background-color: #FFF1E3\">\n<p style=\"color: #9B5831;\">**Warning**</p>\nTo avoid significant numerical error when working with the Fock backend, we generally need to ensure that all initial states and gates we apply result in negligible amplitude in the Fock basis for Fock states $|{n}\\rangle, ~~n\\geq \\texttt{cutoff_dim}$.\n<br><br>\n\nFor example, to prepare a squeezed vacuum state in the $x$ quadrature with `cutoff_dim=10`, a squeezing factor of $r=1$ provides an acceptable approximation, since $\\left|\\left\\langle{n}\\middle|{\\xi}\\right\\rangle\\right|^2<0.02$ for $n\\geq 10$.\n</div>\n\n<div class=\"alert alert-success\" style=\"border: 0px; border-left: 3px solid #119a68; color: black; background-color: #daf0e9\">\n<p style=\"color: #119a68;\">**Scaling**</p>\nAs we are performing a classical simualation of a quantum system, we still need to consider how the simulation scales. Using the Fock backends, memory usage and computational time will scale like $\\sim D^N$, where $N$ is the number of modes and $D$ the cutoff dimension.\n<br><br>\nIdeally, we would like to choose a cutoff large enough that minimises truncation error, but small enough to reduce classical computational resources!\n</div>\n\n\n<div class=\"alert alert-info\" style=\"border: 0px; border-left: 3px solid #31708f; color: black; background-color: #d9edf7\">\n<p style=\"color: #31708f;\">**Exercise**</p>\n\nRun the engine using the Gaussian or the Fock backend.\n\n</div>\n\n\n```python\nstate = eng.run('fock', cutoff_dim=15)\n```\n\n## Results and visualization\nOnce the engine has been run, we can extract results of measurements and the quantum state from the circuit. Any measurements performed on a mode are stored in the mode attribute `val`:\n\n\n```python\nq[0].val\n```\n\n\n\n\n    -1.0993109931099312\n\n\n\n\n```python\nq[1].val\n```\n\n\n\n\n    -0.038300383003829097\n\n\n\nThe returned `state` object stores the resulting state of the circuit after the engine run, and also contains some convenient functions for state manipulation.\n\n<div class=\"alert alert-info\" style=\"border: 0px; border-left: 3px solid #31708f; color: black; background-color: #d9edf7\">\n<p style=\"color: #31708f;\">**Exercise**</p>\n\nPrint the state object below to see some info about the state.\n\n</div>\n\n\n```python\nprint(state)\n```\n\n    <FockState: num_modes=3, cutoff=15, pure=False, hbar=2>\n\n\nThe actual state representation can also be returned; in the Fock backends, the state vector in the truncated Fock basis is available via `state.ket()`, while the density matrix is given by `state.dm()`. In the Gaussian backend, the vector of means and covariance matrix are accessible via `state.means()` and `state.cov()` respectively.\n\n### Fock backend example\nTo return the density matrix representing the Fock state, we can use the method state.dm(). In this case, the density matrix has dimension\n\n\n```python\nstate.dm().shape\n```\n\n\n\n\n    (15, 15, 15, 15, 15, 15)\n\n\n\nHere, we use the convention that every pair of consecutive dimensions corresponds to a subsystem; i.e.,\n\n$$\\rho_{\\underbrace{ij}_{q[0]}\\underbrace{kl}_{q[1]}\\underbrace{mn}_{q[2]}}$$\n\nThus we can calculate the reduced density matrix for mode `q[2]`, $\\rho_2$:\n\n\n```python\nimport numpy as np\nrho2 = np.einsum('kkllij->ij', state.dm())\nrho2.shape\n```\n\n<div class=\"alert alert-success\" style=\"border: 0px; border-left: 3px solid #119a68; color: black; background-color: #daf0e9\">\n<p style=\"color: #119a68;\">**Note**</p>\nThe Fock state also provides the method `reduced_dm()` for extracting the reduced density matrix automatically.\n</div>\n\n\n```python\nstate.reduced_dm([2])\n```\n\n\n\n\n    array([[  5.20017225e-01 -1.73472348e-17j,\n              2.62001634e-01 -8.69150141e-02j,\n              2.80055494e-01 +2.94986447e-02j,\n              1.67123169e-01 -7.90550672e-02j,\n              1.22974690e-01 +4.66482169e-03j,\n              8.70370392e-02 -5.99165249e-02j,\n              6.12599236e-02 -7.23598638e-04j,\n              5.03755666e-02 -4.24049729e-02j,\n              4.56986981e-02 +4.90277701e-03j,\n              3.27242806e-02 -1.95025911e-02j,\n              3.94015196e-02 +1.75404805e-02j,\n              1.02001102e-02 +1.03391172e-02j,\n              8.68933695e-03 +1.84366657e-02j,\n             -1.62624603e-02 +1.79535624e-03j,\n              2.02890892e-03 -1.94914994e-02j],\n           [  2.62001634e-01 +8.69150141e-02j,\n              1.46531831e-01 -3.90312782e-18j,\n              1.36170724e-01 +6.16704962e-02j,\n              9.74152648e-02 -1.18977678e-02j,\n              6.11789861e-02 +2.29041217e-02j,\n              5.38664697e-02 -1.56406395e-02j,\n              3.09856883e-02 +9.87433272e-03j,\n              3.24683660e-02 -1.29453002e-02j,\n              2.22050503e-02 +1.01082009e-02j,\n              1.97471977e-02 -4.35654686e-03j,\n              1.69200768e-02 +1.54229856e-02j,\n              3.41108128e-03 +6.91401776e-03j,\n              1.29649055e-03 +1.07413180e-02j,\n             -8.49363133e-03 -1.81352782e-03j,\n              4.28001476e-03 -9.48134370e-03j],\n           [  2.80055494e-01 -2.94986447e-02j,\n              1.36170724e-01 -6.16704962e-02j,\n              1.52497352e-01 +4.33680869e-18j,\n              8.55197524e-02 -5.20554158e-02j,\n              6.64926885e-02 -4.46365547e-03j,\n              4.34749920e-02 -3.72053573e-02j,\n              3.29505104e-02 -3.86474216e-03j,\n              2.47243059e-02 -2.56948345e-02j,\n              2.48891693e-02 +4.80752896e-05j,\n              1.65173655e-02 -1.23594554e-02j,\n              2.22147111e-02 +7.21133132e-03j,\n              6.07977332e-03 +4.98952155e-03j,\n              5.72548958e-03 +9.43616022e-03j,\n             -8.65631093e-03 +1.88939879e-03j,\n             -1.30105816e-05 -1.06122476e-02j],\n           [  1.67123169e-01 +7.90550672e-02j,\n              9.74152648e-02 +1.18977678e-02j,\n              8.55197524e-02 +5.20554158e-02j,\n              6.57283175e-02 +1.82145965e-17j,\n              3.88124491e-02 +2.01942775e-02j,\n              3.70807154e-02 -6.02426302e-03j,\n              1.97977225e-02 +9.08042475e-03j,\n              2.26362739e-02 -5.96982079e-03j,\n              1.39413111e-02 +8.52295091e-03j,\n              1.34817921e-02 -1.29286990e-03j,\n              9.99628993e-03 +1.16271350e-02j,\n              1.70631874e-03 +4.87344709e-03j,\n             -1.02348873e-05 +7.24616404e-03j,\n             -5.49936768e-03 -1.89529159e-03j,\n              3.61522540e-03 -5.95573660e-03j],\n           [  1.22974690e-01 -4.66482169e-03j,\n              6.11789861e-02 -2.29041217e-02j,\n              6.64926885e-02 +4.46365547e-03j,\n              3.88124491e-02 -2.01942775e-02j,\n              2.91231408e-02 -8.67361738e-18j,\n              2.00452071e-02 -1.49499439e-02j,\n              1.44803754e-02 -7.20651010e-04j,\n              1.15325180e-02 -1.04799056e-02j,\n              1.08508979e-02 +7.49477487e-04j,\n              7.56375358e-03 -4.90556446e-03j,\n              9.47509547e-03 +3.79455523e-03j,\n              2.50488919e-03 +2.35351442e-03j,\n              2.22025775e-03 +4.28199092e-03j,\n             -3.82967314e-03 +5.70451977e-04j,\n              3.04951581e-04 -4.62758823e-03j],\n           [  8.70370392e-02 +5.99165249e-02j,\n              5.38664697e-02 +1.56406395e-02j,\n              4.34749920e-02 +3.72053573e-02j,\n              3.70807154e-02 +6.02426302e-03j,\n              2.00452071e-02 +1.49499439e-02j,\n              2.14712813e-02 -1.42572586e-17j,\n              1.03366535e-02 +6.93727377e-03j,\n              1.33174411e-02 -1.29317715e-03j,\n              7.08384615e-03 +6.08601067e-03j,\n              7.72426717e-03 +5.06285910e-04j,\n              4.57374650e-03 +7.47566316e-03j,\n              5.15951020e-04 +2.90575242e-03j,\n             -6.69913922e-04 +4.08699475e-03j,\n             -2.92876434e-03 -1.57327023e-03j,\n              2.58540115e-03 -3.02858665e-03j],\n           [  6.12599236e-02 +7.23598638e-04j,\n              3.09856883e-02 -9.87433272e-03j,\n              3.29505104e-02 +3.86474216e-03j,\n              1.97977225e-02 -9.08042475e-03j,\n              1.44803754e-02 +7.20651010e-04j,\n              1.03366535e-02 -6.93727377e-03j,\n              7.21764906e-03 -3.68628739e-18j,\n              5.99343135e-03 -4.92536320e-03j,\n              5.37665096e-03 +6.41154263e-04j,\n              3.88217713e-03 -2.25194078e-03j,\n              4.61723515e-03 +2.12115931e-03j,\n              1.18722337e-03 +1.23217902e-03j,\n              9.97981117e-04 +2.18399751e-03j,\n             -1.91827529e-03 +1.88870459e-04j,\n              2.66135083e-04 -2.29334643e-03j],\n           [  5.03755666e-02 +4.24049729e-02j,\n              3.24683660e-02 +1.29453002e-02j,\n              2.47243059e-02 +2.56948345e-02j,\n              2.26362739e-02 +5.96982079e-03j,\n              1.15325180e-02 +1.04799056e-02j,\n              1.33174411e-02 +1.29317715e-03j,\n              5.99343135e-03 +4.92536320e-03j,\n              8.33795348e-03 -4.01154804e-18j,\n              4.02716599e-03 +4.20146125e-03j,\n              4.76044043e-03 +7.79239875e-04j,\n              2.38659455e-03 +4.91220653e-03j,\n              1.45007401e-04 +1.83335136e-03j,\n             -6.61662767e-04 +2.49458771e-03j,\n             -1.72179429e-03 -1.15220626e-03j,\n              1.78598688e-03 -1.72274966e-03j],\n           [  4.56986981e-02 -4.90277701e-03j,\n              2.22050503e-02 -1.01082009e-02j,\n              2.48891693e-02 -4.80752896e-05j,\n              1.39413111e-02 -8.52295091e-03j,\n              1.08508979e-02 -7.49477487e-04j,\n              7.08384615e-03 -6.08601067e-03j,\n              5.37665096e-03 -6.41154263e-04j,\n              4.02716599e-03 -4.20146125e-03j,\n              4.06218896e-03 +1.08420217e-18j,\n              2.69191115e-03 -2.02240007e-03j,\n              3.62794754e-03 +1.16996174e-03j,\n              9.93855816e-04 +8.12425648e-04j,\n              9.37434806e-04 +1.53827546e-03j,\n             -1.41220521e-03 +3.11098655e-04j,\n             -5.46900937e-06 -1.73202615e-03j],\n           [  3.27242806e-02 +1.95025911e-02j,\n              1.97471977e-02 +4.35654686e-03j,\n              1.65173655e-02 +1.23594554e-02j,\n              1.34817921e-02 +1.29286990e-03j,\n              7.56375358e-03 +4.90556446e-03j,\n              7.72426717e-03 -5.06285910e-04j,\n              3.88217713e-03 +2.25194078e-03j,\n              4.76044043e-03 -7.79239875e-04j,\n              2.69191115e-03 +2.02240007e-03j,\n              2.79073371e-03 +3.02831219e-17j,\n              1.82167344e-03 +2.58151320e-03j,\n              2.54129455e-04 +1.03317491e-03j,\n             -1.44630691e-04 +1.48608771e-03j,\n             -1.09071659e-03 -4.96922717e-04j,\n              8.58681799e-04 -1.15049327e-03j],\n           [  3.94015196e-02 -1.75404805e-02j,\n              1.69200768e-02 -1.54229856e-02j,\n              2.22147111e-02 -7.21133132e-03j,\n              9.99628993e-03 -1.16271350e-02j,\n              9.47509547e-03 -3.79455523e-03j,\n              4.57374650e-03 -7.47566316e-03j,\n              4.61723515e-03 -2.12115931e-03j,\n              2.38659455e-03 -4.91220653e-03j,\n              3.62794754e-03 -1.16996174e-03j,\n              1.82167344e-03 -2.58151320e-03j,\n              3.57708958e-03 +2.88397778e-17j,\n              1.12160309e-03 +4.39335630e-04j,\n              1.28026731e-03 +1.10384324e-03j,\n             -1.17164242e-03 +6.84575654e-04j,\n             -5.03729795e-04 -1.54530022e-03j],\n           [  1.02001102e-02 -1.03391172e-02j,\n              3.41108128e-03 -6.91401776e-03j,\n              6.07977332e-03 -4.98952155e-03j,\n              1.70631874e-03 -4.87344709e-03j,\n              2.50488919e-03 -2.35351442e-03j,\n              5.15951020e-04 -2.90575242e-03j,\n              1.18722337e-03 -1.23217902e-03j,\n              1.45007401e-04 -1.83335136e-03j,\n              9.93855816e-04 -8.12425648e-04j,\n              2.54129455e-04 -1.03317491e-03j,\n              1.12160309e-03 -4.39335630e-04j,\n              4.05639627e-04 +3.08997619e-18j,\n              5.37003447e-04 +1.88870568e-04j,\n             -2.83291557e-04 +3.58550268e-04j,\n             -3.47738101e-04 -4.22664017e-04j],\n           [  8.68933695e-03 -1.84366657e-02j,\n              1.29649055e-03 -1.07413180e-02j,\n              5.72548958e-03 -9.43616022e-03j,\n             -1.02348873e-05 -7.24616404e-03j,\n              2.22025775e-03 -4.28199092e-03j,\n             -6.69913922e-04 -4.08699475e-03j,\n              9.97981117e-04 -2.18399751e-03j,\n             -6.61662767e-04 -2.49458771e-03j,\n              9.37434806e-04 -1.53827546e-03j,\n             -1.44630691e-04 -1.48608771e-03j,\n              1.28026731e-03 -1.10384324e-03j,\n              5.37003447e-04 -1.88870568e-04j,\n              7.98848958e-04 -8.78203760e-18j,\n             -2.08088520e-04 +6.06568369e-04j,\n             -6.57148203e-04 -3.97630139e-04j],\n           [ -1.62624603e-02 -1.79535624e-03j,\n             -8.49363133e-03 +1.81352782e-03j,\n             -8.65631093e-03 -1.88939879e-03j,\n             -5.49936768e-03 +1.89529159e-03j,\n             -3.82967314e-03 -5.70451977e-04j,\n             -2.92876434e-03 +1.57327023e-03j,\n             -1.91827529e-03 -1.88870459e-04j,\n             -1.72179429e-03 +1.15220626e-03j,\n             -1.41220521e-03 -3.11098655e-04j,\n             -1.09071659e-03 +4.96922717e-04j,\n             -1.17164242e-03 -6.84575654e-04j,\n             -2.83291557e-04 -3.58550268e-04j,\n             -2.08088520e-04 -6.06568369e-04j,\n              5.14773180e-04 -1.31188463e-17j,\n             -1.30744199e-04 +6.02551428e-04j],\n           [  2.02890892e-03 +1.94914994e-02j,\n              4.28001476e-03 +9.48134370e-03j,\n             -1.30105816e-05 +1.06122476e-02j,\n              3.61522540e-03 +5.95573660e-03j,\n              3.04951581e-04 +4.62758823e-03j,\n              2.58540115e-03 +3.02858665e-03j,\n              2.66135083e-04 +2.29334643e-03j,\n              1.78598688e-03 +1.72274966e-03j,\n             -5.46900937e-06 +1.73202615e-03j,\n              8.58681799e-04 +1.15049327e-03j,\n             -5.03729795e-04 +1.54530022e-03j,\n             -3.47738101e-04 +4.22664017e-04j,\n             -6.57148203e-04 +3.97630139e-04j,\n             -1.30744199e-04 -6.02551428e-04j,\n              7.38504422e-04 +1.40946282e-18j]])\n\n\n\nThe diagonal values of the reduced density matrix contain the marginal Fock state probabilities $\\left|\\left\\langle{i}\\mid{\\rho_2}\\right\\rangle\\right|^2,~~ 0\\leq i< cutoff$:\n\n\n```python\nnp.real_if_close(np.diag(state.reduced_dm([2])))\n```\n\n\n\n\n    array([  3.30124234e-01,   3.66661916e-01,   2.02037477e-01,\n             6.96202751e-02,   1.39445869e-02,   1.68472510e-03,\n             3.31591938e-03,   5.00648663e-03,   1.49447948e-03,\n             1.08845772e-04,   1.21982477e-03,   5.89777516e-04,\n             1.06575755e-03,   1.65544901e-04,   5.62370962e-05])\n\n\n\nThis can also be returned via the state method `all_fock_probs`.\n\n### Plotting the Wigner function\n\n<div class=\"alert alert-info\" style=\"border: 0px; border-left: 3px solid #31708f; color: black; background-color: #d9edf7\">\n<p style=\"color: #31708f;\">**Exercise**</p>\n\nUsing the `state.wigner` function, plot the wigner function of the input state and the resulting teleported state.\n\n</div>\n\n\n```python\nimport matplotlib.pyplot as plt\n```\n\n\n```python\nx = np.arange(-5, 5, 0.1)\np = np.arange(-5, 5, 0.1)\n```\n\n\n```python\nW = state.wigner(2, x, p)\n```\n\n\n```python\nW.shape\n```\n\n\n\n\n    (100, 100)\n\n\n\n\n```python\nX, P = np.meshgrid(x, p)\nplt.contourf(X, P, W)\n```\n\n<div class=\"alert alert-info\" style=\"border: 0px; border-left: 3px solid #31708f; color: black; background-color: #d9edf7\">\n<p style=\"color: #31708f;\">**Exercise**</p>\n\nRepeat this notebook, but using the `'gaussian'` backend instead. How does the teleportation fidelity compare to the fock backend?\n\n</div>\n\n\n```python\n\n```\n", "meta": {"hexsha": "f3abe0afcbf5f863fec0bfca2673e099b0b16454", "size": 45497, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/QuantumTeleportation.ipynb", "max_stars_repo_name": "ziofil/strawberryfields", "max_stars_repo_head_hexsha": "2c3241c1831f396ade208a3d4b8ff5786f3cf806", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-20T03:12:39.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-20T03:12:39.000Z", "max_issues_repo_path": "examples/QuantumTeleportation.ipynb", "max_issues_repo_name": "ziofil/strawberryfields", "max_issues_repo_head_hexsha": "2c3241c1831f396ade208a3d4b8ff5786f3cf806", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/QuantumTeleportation.ipynb", "max_forks_repo_name": "ziofil/strawberryfields", "max_forks_repo_head_hexsha": "2c3241c1831f396ade208a3d4b8ff5786f3cf806", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.1859459459, "max_line_length": 8740, "alphanum_fraction": 0.6353166143, "converted": true, "num_tokens": 8857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.09807932940215, "lm_q1q2_score": 0.0444556180969283}}
{"text": "```python\nfrom IPython.core.display import HTML, Image, Markdown\nimport sys\nimport json\nsys.path.append(\"microTC\")\nfrom microtc.textmodel import TextModel\nfrom itertools import combinations\n\n\nfrom graphviz import Digraph\ndot = Digraph(comment='microtc pipeline', format=\"png\")\n# dot.engine = 'circo'\ndot.graph_attr['rankdir'] = 'LR'\ndot.node('i', '', style=\"invis\")\ndot.node('n', 'Normalizaci\u00f3n')\ndot.node('t', 'Tokenizaci\u00f3n')\ndot.node('w', 'Pesado')\ndot.node('c', 'Clasificaci\u00f3n')\ndot.node('o', '', style=\"invis\")\n\ndot.edge('i', 'n', label=\"texto entrada\")\ndot.edge('n', 't', label=\"texto normalizado\")\ndot.edge('t', 'w', label=\"bolsa de palabras\")\ndot.edge('w', 'c', label=\"vector con pesos\")\ndot.edge('c', 'o', label=\"clase\")\n\npipeline = dot.render(\"fig-pipeline\", view=False)\n\n```\n\n# Clasificaci\u00f3n de texto #\n## Un enfoque basado en $\\mu TC$ ##\n\n\n**Seminario de la Sociedad Matem\u00e1tica Mexicana SMM 2016**\n\n\n<div>\n    Eric Sadit T\u00e9llez Avila INFOTEC \n    <estellezav@conacyt.mx> <br/>\n       CONACyT -- INFOTEC\n</div>\n\n# Agenda #\n- \u00bfQu\u00e9 es $\\mu TC$\n- \u00bfEn qu\u00e9 consiste la tarea de clasificaci\u00f3n de texto?\n- \u00bfC\u00f3mo esta compuesto $\\mu TC$?\n- Estado del arte\n- C\u00f3mo se compara $\\mu TC$ con el estado del arte\n- Qu\u00e9 falta en $\\mu TC$\n- Ejemplos\n\n\n## Categorizaci\u00f3n de texto ##\nEl problema consiste en, dado un texto $d$, determinar la(s) categor\u00eda(s) a la que pertenece en un conjunto $C$ de categorias, previamente conocido.\n\nM\u00e1s formalmente:\n\nDado un conjunto de categorias $\\cal{C} = \\{c_1, ..., c_m\\}$, determinar el subconjunto de categorias\n$C_d \\in \\wp(\\cal{C})$ a las que pertenece $d$. \n\nNotese que $C_t$ puede ser vacio o $\\cal{C}$.\n\n\n\n## Clasificaci\u00f3n de texto ##\nLa _clasificaci\u00f3n_ de texto es una especializaci\u00f3n del problema de categorizaci\u00f3n, donde $|C_d| = 1$, esto es $d$ solo puede ser asignado a una categor\u00eda.\n\nEs un problema de inter\u00e9s en la industria y la ac\u00e1demia, con aplicaciones variadas a distintas \u00e1reas del conocimiento.\n\n- An\u00e1lisis de sentimiento\n- Determinaci\u00f3n de autor\u00eda, e.g., g\u00e9nero, edad, estilo, etc.\n- Detecci\u00f3n de spam\n- Categorizaci\u00f3n de noticias\n- Clasificaci\u00f3n de idioma\n\n# Procesamiento de Lenguaje Natural #\n\n\nUn documento $d=s_1\\cdots s_n$ es simplemente la concatenaci\u00f3n de s\u00edmbolos $s \\in \\Sigma$. Donde, $\\Sigma$ es un _alfabeto_ de tama\u00f1o $\\sigma = |\\Sigma|$\n\nNotese qu\u00e9 el n\u00famero de textos posibles de tama\u00f1o $n$ es $\\sigma^n$, por ejemplo, limitados a texto en ingl\u00e9s en Twitter se tienen\n    $$ 26^{140} \\simeq 1.248 \\times 10^{198} $$\n\nSin emabargo, en lenguaje natural, este n\u00famero no suele ser tan grande:\n  - existen reglas sobre que s\u00edmbolos se pueden unir\n  - m\u00e1s a\u00fan, hay noci\u00f3n de _terminos_ o _palabras_, i.e., _morfolog\u00eda_\n  - tambi\u00e9n, hay reglas sobre como las palabras se pueden combinar, i.e., _sintaxis y gram\u00e1tica_\n\nSin embargo, es un problema sumamente complicado, hay muchas reglas, variantes, excepciones, errores, etc.\n\nY por si fuera poco, aunque los conceptos existen en esencia, aparecen de manera diferente en todos los lenguajes\n\n\nAdem\u00e1s, esta el problema sem\u00e1ntico:\n\n- un t\u00e9rmino $s_i$ tiene significados diferentes (ant\u00f3nimos)\n- lo contrario tambi\u00e9n existe, $s_i \\not= s_j$ pero que son id\u00e9nticos en significado (sin\u00f3nimos)\n- en ambos casos, el significado preciso depende del contexto\n- tambi\u00e9n hay casos _aproximados_ de todo lo anterior\n- ironias, sarcamos, etc.\n\n... hay much\u00edsimos problemas abiertos. **NLP** es complicado, de hecho es _AI-complete_\n\n\n# Nuestro Enfoque #\nPor su complejidad, trabajar en NLP tiene una gran cantidad de problemas abiertos, en particular nosotros nos enfocamos en la clasificaci\u00f3n de texto escrito de manera informal (e.g., Twitter).\n\nPara esto se utiliza un _pipeline_ est\u00e1ndar\n\n\n\nNo es la \u00fanica opci\u00f3n, pero fijar el pipeline es \u00fatil como ya se expondr\u00e1.\n\n\nEl enfoque te\u00f3rico suele ser muy complicado, y en realidad poco efectivo en la pr\u00e1ctica, dadas las simplificaciones necesarias para hacerlo manejable\n\n- L\u00f3gica\n- Ling\u00fcistica\n- Sem\u00e1ntica\n\nEl enfoque pr\u00e1ctico supone muchas cosas, en particular es un tanto casu\u00edstico:\n    \n- Se fija el lenguaje\n- Se fija el problema\n- Y la ra\u00edz de todos los males, muchas veces se supone que entre m\u00e1s t\u00e9cnicas sof\u00edsticadas se usen, mejores resultados se tendr\u00e1n\n\nEn ambos enfoques se suele suponer que ausencia de errores de diferentes fuentes, sin embargo, es la regla cuando el texto que se analiza fue generado por usuarios de una red social, e.g. Twitter.\n\n# \u00bfQu\u00e9 es $\\mu TC$? #\nmicro TC o $\\mu TC$ es un clasificador de texto desarrollado en\nel _Laboratorio de An\u00e1lisis Computacional de Grandes C\u00famulos de Informaci\u00f3n_\n(o _Laboratorio de BigDATA_) de INFOTEC, sede Aguascalientes.\n\nEsta disponible para ser clonado en [https://github.com/INGEOTEC/microTC](https://github.com/INGEOTEC/microTC). Esta escrito en Python 3.5 para sacar ventaja de unicode. Tambi\u00e9n se puede instalar utilizando `pip` y `conda`.\n\n\nEn particular, nuestro enfoque se basa en _aprendizaje computacional_ y _optimizaci\u00f3n combinatoria_. Hemos probado que este esquema es muy competitivo en la pr\u00e1ctica. Adem\u00e1s, con la adecuada selecci\u00f3n de las funciones podemos lograr que \n$\\mu TC$ se independiente del lenguaje y robusto a errores.\n\nEsta compuesto por:\n- una serie de funciones de transformaci\u00f3n de texto\n- una serie de tokenizadores\n- filtros de palabras y\n- algoritmos de pesado de t\u00e9rminos\n\nTodo esto orquestado mediante un algoritmo de optimizaci\u00f3n combinatoria\n\n\n## Lista de parametros ##\n\n### Normalizadores multilenguaje ###\n\n|   nombre  | valores             |        descripci\u00f3n                   |\n|-----------|---------------------|--------------------------------------|\n|\tdel-punc | yes, no | Determina si las puntuaciones deben removerse |\n|\tdel-d1   | yes, no | Determina si se deben borrar letras repetidas |\n|\tdel-diac | yes, no | Determina si los simbolos que no ocupan espacios deben ser removidos |\n|\tlc       | yes, no | Determina si los s\u00edmbolos deben ser normalizados en min\u00fasculas |\n|\temo      | remove, group, none | Controla como deben tratarse los emoticones |\n|\tnum      | remove, group, none | `........................` n\u00fameros |\n|\turl      | remove, group, none | `........................` urls |\n|\tusr      | remove, group, none | `........................` usuarios |\n\nconfiguraciones: 1296\n\n\n\n### Normalizadores dependientes del lenguaje ###\n\n|   nombre  | valores             |        descripci\u00f3n                   |\n|-----------|---------------------|--------------------------------------|\n|\tstem   | yes, no | Determina si a las palabras se les aplica _stemming_. |\n|\tneg    | yes, no | Determina si los operadores de negaci\u00f3n son manejados de manera especial |\n|\tsw | remove, group, none | Controla como los _stopwords_ son manejados |\n\nconfiguraciones: 12\n\n\n### Tokenizadores ###\nLos tokenizadores son en realidad una lista de tokenizadores, y est\u00e1n definidos tokenizer un elemento en $\\wp{(\\text{n-words} \\cup \\text{q-grams} \\cup \\text{skip-grams})} \\setminus \\{\\emptyset\\}$\n\n|   nombre  | valores             |        descripci\u00f3n                   |\n|-----------|---------------------|--------------------------------------|\n|\tn-words    | $\\{1,2,3\\}$      | Longitud de n-gramas de palabras (n-words) |\n|\tq-grams  | $\\{1,2,3,4,5,6,7\\}$ | Longitud de q-gramas de caracteres) |\n|\tskip-grams  | $\\{(2,1), (3, 1), (2, 2), (3, 2)\\}$ | Lista de skip-grams|\n\nconfiguraciones: 16383\n\n### Parametros para pesado ###\n|   nombre  | valores             |        descripci\u00f3n                   |\n|-----------|---------------------|--------------------------------------|\n|token_min_filter | $\\{0.01, 0.03, 0.1, 0.30, -1, -5, -10\\}$ | Filtro de frequencias bajas |\n|token_max_filter | $\\{0.9, 99, 1.0\\}$ | Filtro de frequencias altas |\n|\ttfidf    | yes, no | Determina si se debe realizar un pesado TFIDF de terminos |\n\nconfiguraciones = 42\n\n\n```python\nconf = 42 * 16383 * 12 * 1292\ntime = conf * 10 / 60 / 24 / 365.25\nprint(conf, time)\n```\n\n    10668085344 202830.73511293635\n\n\nCon esto tenemos un total de $10,668,085,344$ configuraciones. Dependiendo del tama\u00f1o de cada colecci\u00f3n, cada configuraci\u00f3n se evalua en tiempo diferente.\n\nUna tarea t\u00edpica de an\u00e1lisis de sentimientos tiene un costo por configuraci\u00f3n de cerca de 10 min. en una computadora de relativamente nueva, i.e., Intel(R) Xeon(R) CPU E5-2640 v3 @ 2.60GHz.\n\nEsto da un total de $202,830.74$ a\u00f1os de tiempo de c\u00f3mputo.\n\nUn enfoque _na\u00efve_ requiere una cantidad enorme de computadoras para parallelizar y distribuir este proceso, por esta raz\u00f3n, es mejor utilizar algoritmos eficientes para optimizar la b\u00fasqueda de la mejor configuraci\u00f3n\n\n\n\n```python\nfrom sympy import symbols, sin, cos, exp, tan, sqrt\nfrom sympy.plotting import plot, plot3d\nfrom matplotlib import pyplot\nx, y = symbols('x y')\nplot(-x**2+200, axis=False, show=False).save(\"opt-1a.png\")\nplot(sin(x)*sin(1/(x*x)), axis=False, show=False).save('opt-1b.png')\nplot3d((-x**2 - y**2, (x, -5, 5), (y, -5, 5)), axis=False, show=False).save('opt-2a.png')\nplot3d(sin(x*y), axis=False, show=False).save('opt-2b.png')\n```\n\n# Optimizaci\u00f3n combinatoria #\nPara tener algo pr\u00e1ctico utilizamos una aproximaci\u00f3n a encontrar la configuraci\u00f3n \u00f3ptima, en a lo m\u00e1s unas cuantas horas.\n\nPara esto necesitamos un espacio de b\u00fasqueda (dominio) y una funci\u00f3n de aptitud.\n\nEl espacio de b\u00fasqueda son todas las configuraciones.\n\nLa funci\u00f3n de aptitud es una m\u00e9dida de _que tan atinado_ es nuestro clasificador. Deseamos seleccionar la configuraci\u00f3n que maximice la funci\u00f3n de aptitud.\n\n\n\nNotes\u00e9 que:\n\n- El espacio de configuraci\u00f3n no esta en $\\mathbb{R}^n$\n- En la configuraci\u00f3n/par\u00e1metros son una mezcla de reales y categ\u00f3ricos\n- No hay coordenadas como tal\n\nAfortunadamente\n\n- Se pueden definir vecindades entre configuraciones\n- Se puede construir una gr\u00e1fica\n- Se puede samplear el espacio\n- Se puede definir una funci\u00f3n de aptitud de nodos\n\n\n## Maximizando un objetivo (ejemplo) ##\n\n|f\u00e1cil|un poco m\u00e1s complicado|\n|-|-|\n|||\n|||\n\n\n# Resultados Experimentales #\n\n\n\n\n\n\n\n\n# Gracias por su atenci\u00f3n #\n\n## \u00bfComentarios y preguntas? ##\n\n\n- Para m\u00e1s informaci\u00f3n sobre el _Posgrado en Ciencias en Ciencia de Datos_ aqu\u00ed en Aguascalientes: <eric.tellez@infotec.mx>\n- Esta presentaci\u00f3n la puedes obtener en: <https://github.com/INGEOTEC/pres-MSA-SMM2016>\n- $\\mu TC$ lo puedes conseguir en: <https://github.com/INGEOTEC/microTC>\n- P\u00e1gina de INFOTEC <https://www.infotec.mx/>\n\n# Slides de soporte #\n\n## Sobre el pesado ##\nEl pesado de tokens esta fijo a TFIDF. Su nombre viene de la formulaci\u00f3n $tf \\times idf$\n\n$tf$ es _term frequency_; es una medida de importancia **local** del t\u00e9rmino $t$ en el documento $d$, de manera normalizada esta definida como:\n    $$tf(t,d) = \\frac{freq(t, d)}{\\max_{w \\in d}{freq(w, d)}}$$\nentre m\u00e1s veces aparece en el documento $d$, $t$ es m\u00e1s importante\n\n$idf$ quiere decir _inverse document frequency_; es una medida **global** a la colecci\u00f3n $D$, esta definida como:\n$$ idf(t,d) = log{\\frac{|D|}{1+|{d \\in D: t \\in d}|}} $$\nentre m\u00e1s veces aparece $t$ en la colecci\u00f3n, el t\u00e9rmino es m\u00e1s com\u00fan y menos discriminante; por lo tanto, menos importante\n\n## Sobre el clasificador ##\nEl clasificador es un algoritmo de aprendizaje computacional que dado un objeto, decide finalmente la etiqueta o clase de ese objeto. Tiene dos etapas bien definidas\n\n- **Entrenamiento.** Dado un conjunto de ejemplos en un espacio vectorial, con etiquetas, el algoritmo intenta _aprender_ las caracter\u00edsticas que definen cada clase\n- **Predicci\u00f3n.** La idea es que una vez entrenado, el algoritmo puede recibir objetos no vistos durante la etapa de entrenamiento y asignales la clase adecuada\n\nEn particular, esta fijo como un _Support Vector Machine_ (SVM) con kernel lineal\n\n\n\n\n# \u00bfPor qu\u00e9 es robusto a errores?\n\nConsidere los siguientes textos $T=I\\_like\\_vanilla$, $T' = I\\_lik3\\_vanila$\n\nPara fijar ideas pongamos que se usar el coeficiente de Jaccard como medida de similitud, i.e.\n\n\n$$\\frac{|\\{{I, like, vanilla}\\} \\cap \\{{I, lik3, vanila}\\}|}{|\\{{I, like, vanilla}\\} \\cup \\{{I, lik3, vanila}\\}|} = 0.2$$\n\n\n$$Q^T_3 = \\{ I\\_l, \\_li, lik, ike, ke\\_, e\\_v, \\_va, van, ani, nil, ill, lla \\}$$\n$$Q^{T'}_3 = \\{ I\\_l, \\_li, lik, ik3, k3\\_, 3\\_v, \\_va, van, ani, nil, ila \\}$$\n\nBajo la misma medida\n$$\\frac{|Q^T_3 \\cap Q^{T'}_3|}{|Q^T_3 \\cup Q^{T'}_3|} = 0.448.$$\n\nSe puede ver que estos conjuntos son m\u00e1s similares que los tokenizados por palabra\n\nLa idea es que un algoritmo de aprendizaje tenga un poco m\u00e1s de soporte para determinar que $T$ es parecido a $T'$\n\n\n\n```python\ndef emoformat(A, emo):\n    s = \"  \".join([a[0] for a in A if a[1] == emo])\n    return s[:1000] + \"...\"\n    \nwith open('microTC/microtc/resources/emoticons.json') as f:\n    A = list(json.load(f).items())\n    A.sort()\n    S = dict(\n        pos=emoformat(A, '_pos'),\n        neg=emoformat(A, '_neg'),\n        neu=emoformat(A, '_neu'),\n        none=emoformat(A, '_none'),\n    )\n\noutput = [\"## Emoticones y emojis clasificados por sentimiento ##\"]\nfor k, v in S.items():\n    output.append(\"## Clase `{0}` ##\".format(k.upper()))\n    output.append(v)\n\nMarkdown(\"\\n\".join(output))\n```\n\n\n\n\n## Emoticones y emojis clasificados por sentimiento ##\n## Clase `NONE` ##\n'~'U  ^( \\\\\\'-\\\\\\' )^  \u03c0  \u03df  \u0ca0~\u0ca0  \u2037\u0317\u2182\u51f8\u2182\u2034  \u203c  \u2042  \u2049  \u204e  \u2051  \u2139  \u21b6  \u21b7  \u2228  \u2229  \u222a  \u2234  \u2295  \u2297  \u229a  \u229b  \u229c  \u22a5  \u2306  \u2318  \u2325  \u232b  \u2388  \u238b  \u238c  \u23ce  \u23cf  \u257d  \u257f  \u25c9  \u25cf  \u25d0  \u25d1  \u25d2  \u25d3  \u25d4  \u25d5  \u25d6  \u25d7  \u2604  \u2607  \u2608  \u2609  \u260a  \u260c  \u260d  \u260e  \u260f  \u261b  \u261d  \u261e  \u2624  \u2627  \u2628  \u2629  \u262a  \u262b  \u262c  \u262d  \u2638  \u263f  \u264a  \u264b  \u264c  \u264d  \u264e  \u264f  \u2650  \u2651  \u2652  \u2653  \u2664  \u2668  \u266d  \u266e  \u266f  \u267f  \u2692  \u2693  \u2694  \u2695  \u2698  \u269a  \u269c  \u26aa  \u26ab  \u2706  \u2707  \u270a  \u2711  \u2720  \u2721  \u2722  \u2723  \u2724  \u2725  \u2726  \u2727  \u2756  \u2757  \u2766  \u2767  \u2796  \u2797  \u27b0  \u27b7  \u27ba  \u27bf  \u3065  \u309e  \u30ac  \u30ae  \u30b0  \u30b2  \u30b4  \u30b6  \u30ba  \u30bc  \u30d0  \u30d3  \u30f7  \u30f9  \u30fa  \u328a  \u328b  \u328c  \u328d  \u328e  \u328f  \u3290  \uc720  \ufe62  \ufe63  \ufe64  \ufe65  \ud83c\udc04...\n## Clase `POS` ##\n(^L^)  (^\u203f^)  (\u00b0\u2323\u00b0)  (\u2022\u203f\u2022)  (\uff61\u25d5\u203f\u25d5\uff61)  *-*  :)  :*  :-)  :-*  :-D  :3  :B  :D  :]  :p  ;)  ;-)  ;D  < (^^,) >  <3  <\u3010\u262f\u3011\u203f\u3010\u262f\u3011>  =)  =D  =^.^=  D:  Dx  XP  ^( \\\\\\'\u203f\\\\\\' )^  ^.^  ^^  ^_^  ^o^  ^\u203f^  n_n  q(\u2742\u203f\u2742)p  xD  {\u25d5 \u25e1 \u25d5}  |\u25d4\u25e1\u25c9|  \u00a2\u203f\u00a2  \u00dc  \u00f1.\u00f1  \u00f1__\u00f1  \u00f1_\u00f1  \u00f3\u203f\u00f3  \u062a  \u0669(-\u032e\u032e\u0303-\u0303)\u06f6  \u0669(-\u032e\u032e\u0303\u2022\u0303)  \u0669(^\u203f^)\u06f6  \u0669(\u0361\u0e4f\u032e\u0361\u0e4f)\u06f6  \u0669\u25d4\u203f\u25d4\u06f6  \u0ca0\u25e1\u0ca0  \u0f3a\u203f\u0f3b  \u10e6  \u1d54\u1d25\u1d54  \u200d\ud83d\udc68\u2764\u200d\ufe0f\u200d\ud83d\udc8b\ud83d\udc68  \u200d\ud83d\udc69\u2764\u200d\ufe0f\u200d\ud83d\udc8b\ud83d\udc68  \u200d\ud83d\udc69\u2764\u200d\ufe0f\u200d\ud83d\udc8b\ud83d\udc69  \u2020  \u21e7  \u21ea  \u221a  \u2267\u25e1\u2266  \u2282\u25c9\u203f\u25c9\u3064  \u2299\u2583\u2299  \u22c6  \u235f  \u250c(\u0ca0\u203f\u0ca0)\u2518  \u2573  \u25cf\u203f\u25cf  \u25d5\u203f\u25d5\u0669(\u25cf\u032e\u032e\u0303\u2022\u0303)\u06f6  \u25d9\u203f\u25d9  \u2600  \u2603  \u2605  \u2606  \u260b  \u2611  \u2615  \u2618  \u261a  \u261c  \u2625  \u2626  \u262e  \u262f  \u263a  \u263b  \u263c  \u263d  \u263e  \u2649  \u2654  \u2655  \u2656  \u265a  \u265b  \u2661  \u2663  \u2665  \u2665\u203f\u2665  \u2667  \u2669  \u266a  \u266b  \u266c  \u267b  \u2696  \u269b  \u26f9  \u26f9\ud83c\udffb  \u26f9\ud83c\udffc  \u26f9\ud83c\udffd  \u26f9\ud83c\udffe  \u26f9\ud83c\udfff  \u2705  \u2708  \u2709  \u270c  \u270c\ud83c\udffb  \u270c\ud83c\udffc  \u270c\ud83c\udffd  \u270c\ud83c\udffe  \u270c\ud83c\udfff  \u2713  \u2714  \u2719  \u271a  \u271b  \u271c  \u271d  \u271e  \u271f  \u2728  \u2729  \u272a  \u272b  \u272c  \u272d  \u272e  \u272f  \u2730  \u2731  \u2732  \u2733  \u2734  \u2735  \u2736  \u2737  \u2738  \u2739  \u273a  \u273b  \u273c  \u273d  \u273e  \u273f  \u2740  \u2740\u203f\u2740  \u2741  \u2742  \u2743  \u2747  \u2748  \u2749  \u274a  \u274b  \u2755  \u2763  \u2764  \u2764\ufe0f  \u2764\ufe0f\u203f\u2764\ufe0f  \u2765  \u2795  \u27b3  \u27b5  \u27b8  \u27b9  \u27bb  \u27bc  \u27bd  \u2b50  \u30b7  \u30b8  \u30be  \u30c3  \u30c4  \u30c5  \u32e1  \u4e42\u25dc\u25ec\u25dd\u4e42  \uc6c3  \ud83c\udf04  \ud83c\udf05  \ud83c\udf37  \ud83c\udf39  \ud83c\udf3a  \ud83c\udf3b  \ud83c\udf3c  \ud83c\udf40  \ud83c\udf7b  \ud83c\udf7e  \ud83c\udf82  \ud83c\udf84  \ud83c\udf86  \ud83c\udf87  \ud83c\udf88  \ud83c\udf89  \ud83c\udf8a  \ud83c\udf91  \ud83c\udf96  \ud83c\udf9f  \ud83c\udfa7  \ud83c\udfab  \ud83c\udfb5  \ud83c\udfb6  \ud83c\udfbc  \ud83c\udfc5  \ud83c\udfc6  \ud83c\udfe9  \ud83c\udff5  \ud83d\udc2d  \ud83d\udc2e  \ud83d\udc31  \ud83d\udc35  \ud83d\udc4b  \ud83d\udc4b\ud83c\udffb  \ud83d\udc4b\ud83c\udffc  \ud83d\udc4b\ud83c\udffd  \ud83d\udc4b\ud83c\udffe  \ud83d\udc4b\ud83c\udfff  \ud83d\udc4c  \ud83d\udc4c\ud83c\udffb  \ud83d\udc4c\ud83c\udffc  \ud83d\udc4c\ud83c\udffd  \ud83d\udc4c\ud83c\udffe  \ud83d\udc4c\ud83c\udfff  \ud83d\udc4d  \ud83d\udc4d\ud83c\udffb  \ud83d\udc4d\ud83c\udffc  \ud83d\udc4d\ud83c\udffd  \ud83d\udc4d\ud83c\udffe  \ud83d\udc4d\ud83c\udfff  \ud83d\udc4e  \ud83d\udc4e\ud83c\udffb  \ud83d\udc4e\ud83c\udffc  \ud83d\udc4e\ud83c\udffd  \ud83d\udc4e\ud83c\udffe  \ud83d\udc4e\ud83c\udfff  \ud83d\udc4f...\n## Clase `NEU` ##\n#\u20e3  $_$  &  (-\\\\\\'\\\\\\'-)  (\u2022\u032a\u25cf)  *\u20e3  -.-  -_-  ._.  0\u20e3  1\u20e3  2\u20e3  3\u20e3  4\u20e3  5\u20e3  6\u20e3  7\u20e3  8-|  8\u20e3  9\u20e3  :-|  >:-o  @_@  U_U  n__n  u.u  u_u  v( \u2018.\u2019 )v  {\u2022\u0303\u033e_\u2022\u0303\u033e}  |\u02da\u2013\u02da|  \u00a9  \u00ac\u00ac  \u00ae  \u0c20_\u0c20  \u0cb0_\u0cb0  \u200d\ud83d\udc68\u2764\u200d\ufe0f\ud83d\udc68  \u200d\ud83d\udc69\u2764\u200d\ufe0f\ud83d\udc68  \u200d\ud83d\udc69\u2764\u200d\ufe0f\ud83d\udc69  \u2122  \u2194  \u2195  \u2196  \u2197  \u2198  \u2199  \u21a9  \u21aa  \u21ce_\u21ce  \u231a  \u2328  \u23e9  \u23ea  \u23eb  \u23ec  \u23ed  \u23ee  \u23ef  \u23f0  \u23f1  \u23f2  \u23f3  \u23f8  \u23f9  \u23fa  \u24c2  \u25aa  \u25ab  \u25b6  \u25c0  \u25d0.\u0303\u25d0  \u25d1.\u25d1  \u25d4_\u25d4  \u25fb  \u25fc  \u25fd  \u25fe  \u2601  \u261d\ud83c\udffb  \u261d\ud83c\udffc  \u261d\ud83c\udffd  \u261d\ud83c\udffe  \u261d\ud83c\udfff  \u2640  \u2641  \u2642  \u2648  \u2657  \u2658  \u2659  \u265c  \u265d  \u265e  \u265f  \u2660  \u2662  \u2666  \u2697  \u2699  \u26b0  \u26b1  \u26bd  \u26be  \u26c4  \u26c5  \u26c8  \u26ce  \u26cf  \u26d1  \u26d3  \u26e9  \u26ea  \u26f0  \u26f1  \u26f2  \u26f3  \u26f4  \u26f5  \u26f7  \u26f8  \u26fa  \u26fd  \u270b\ud83c\udffb  \u270b\ud83c\udffc  \u270b\ud83c\udffd  \u270b\ud83c\udffe  \u270b\ud83c\udfff  \u270d  \u270d\ud83c\udffb  \u270d\ud83c\udffc  \u270d\ud83c\udffd  \u270d\ud83c\udffe  \u270d\ud83c\udfff  \u270e  \u270f  \u2712  \u2744  \u2745  \u2746  \u2753  \u2754  \u27a1  \u2934  \u2935  \u2b05  \u2b06  \u2b07  \u2b1b  \u2b1c  \u2b55  \u3010\u2022\u3011_\u3010\u2022\u3011  \u3030  \u303d  \u3297  \u3299  \ud83c\udccf  \ud83c\udd70  \ud83c\udd71  \ud83c\udd7e  \ud83c\udd7f  \ud83c\udd8e  \ud83c\udd91  \ud83c\udd92  \ud83c\udd93  \ud83c\udd94  \ud83c\udd95  \ud83c\udd96  \ud83c\udd97  \ud83c\udd98  \ud83c\udd99  \ud83c\udd9a  \ud83c\udde6\ud83c\udde8  \ud83c\udde6\ud83c\udde9  \ud83c\udde6\ud83c\uddea  \ud83c\udde6\ud83c\uddeb  \ud83c\udde6\ud83c\uddec  \ud83c\udde6\ud83c\uddee  \ud83c\udde6\ud83c\uddf1  \ud83c\udde6\ud83c\uddf2  \ud83c\udde6\ud83c\uddf4  \ud83c\udde6\ud83c\uddf6  \ud83c\udde6\ud83c\uddf7  \ud83c\udde6\ud83c\uddf8  \ud83c\udde6\ud83c\uddf9  \ud83c\udde6\ud83c\uddfa  \ud83c\udde6\ud83c\uddfc  \ud83c\udde6\ud83c\uddfd  \ud83c\udde6\ud83c\uddff  \ud83c\udde7\ud83c\udde6  \ud83c\udde7\ud83c\udde7  \ud83c\udde7\ud83c\udde9  \ud83c\udde7\ud83c\uddea  \ud83c\udde7\ud83c\uddeb  \ud83c\udde7\ud83c\uddec  \ud83c\udde7\ud83c\udded  \ud83c\udde7\ud83c\uddee  \ud83c\udde7\ud83c\uddef  \ud83c\udde7\ud83c\uddf1  \ud83c\udde7\ud83c\uddf2  \ud83c\udde7\ud83c\uddf3  \ud83c\udde7\ud83c\uddf4  \ud83c\udde7\ud83c\uddf6  \ud83c\udde7\ud83c\uddf7  \ud83c\udde7\ud83c\uddf8  \ud83c\udde7\ud83c\uddf9  \ud83c\udde7\ud83c\uddfb  \ud83c\udde7\ud83c\uddfc  \ud83c\udde7\ud83c\uddfe  \ud83c\udde7\ud83c\uddff  \ud83c\udde8\ud83c\udde6  \ud83c\udde8\ud83c\udde8  \ud83c\udde8\ud83c\udde9  \ud83c\udde8\ud83c\uddeb  \ud83c\udde8\ud83c\uddec  \ud83c\udde8\ud83c\udded  \ud83c\udde8\ud83c\uddee  \ud83c\udde8\ud83c\uddf0  \ud83c\udde8\ud83c\uddf1  \ud83c\udde8\ud83c\uddf2  \ud83c\udde8\ud83c\uddf3  \ud83c\udde8\ud83c\uddf4  \ud83c\udde8\ud83c\uddf5  \ud83c\udde8\ud83c\uddf7  \ud83c\udde8\ud83c\uddfa  \ud83c\udde8\ud83c\uddfb  \ud83c\udde8\ud83c\uddfc  \ud83c\udde8\ud83c\uddfd  \ud83c\udde8\ud83c\uddfe  \ud83c\udde8\ud83c\uddff  \ud83c\udde9\ud83c\uddea  \ud83c\udde9\ud83c\uddec  \ud83c\udde9\ud83c\uddef  \ud83c\udde9\ud83c\uddf0  \ud83c\udde9\ud83c\uddf2  \ud83c\udde9\ud83c\uddf4  \ud83c\udde9\ud83c\uddff  \ud83c\uddea\ud83c\udde6  \ud83c\uddea\ud83c\udde8  \ud83c\uddea\ud83c\uddea  \ud83c\uddea\ud83c\uddec  \ud83c\uddea\ud83c\udded  \ud83c\uddea\ud83c\uddf7  \ud83c\uddea\ud83c\uddf8  \ud83c\uddea\ud83c\uddf9  \ud83c\uddea\ud83c\uddfa  \ud83c\uddeb\ud83c\uddee  \ud83c\uddeb\ud83c\uddef  \ud83c\uddeb\ud83c\uddf0  \ud83c\uddeb\ud83c\uddf2  \ud83c\uddeb\ud83c\uddf4  \ud83c\uddeb\ud83c\uddf7  \ud83c\uddec\ud83c\udde6  \ud83c\uddec\ud83c\udde7  \ud83c\uddec\ud83c\udde9  \ud83c\uddec\ud83c\uddea  \ud83c\uddec\ud83c\uddeb  \ud83c\uddec\ud83c\uddec  \ud83c\uddec\ud83c\udded  \ud83c\uddec\ud83c\uddee  \ud83c\uddec\ud83c\uddf1  \ud83c\uddec\ud83c\uddf2  \ud83c\uddec\ud83c\uddf3  \ud83c\uddec\ud83c\uddf5 ...\n## Clase `NEG` ##\n'n'  (>.<)  (O.O)  (\u2299\u0303.o \u2299.\u25ce)  )-:  ):  ):-/  .l.  /:  :\"(  :'(  :(  :-(  :-/  :-\\  :-o  :-x  :/  :S  :[  :\\  :c  :o  ='(  =(  =S  >.<  >:-(  >:o  ><  >_<  O.o  O.\u00f3  TT  XC  X_X  \\\\\\\\m/(>.<)\\\\\\\\m/  o.\u00d3  o\u0303.O  x_x  \u00ac \u00ac  \u00ac \u00ac*  \u00ac\u00ac*  \u00bb.\u00ab  \u00f2_\u00f3  \u0953_\u0954  \u0e4f_\u0e4f  \u229d  \u231b  \u2324  \u2602  \u2612  \u2614  \u261f  \u2620  \u2622  \u2623  \u2639  \u26a0  \u26a1  \u26d4  \u2702  \u270a\ud83c\udffb  \u270a\ud83c\udffc  \u270a\ud83c\udffd  \u270a\ud83c\udffe  \u270a\ud83c\udfff  \u270b  \u2715  \u2716  \u2717  \u2718  \u274c  \u274e  \u3034\u22cb_\u22cc\u3035  \u534d  \u5350  \ud83c\udf01  \ud83c\udf97  \ud83d\udc79  \ud83d\udc7a  \ud83d\udc7b  \ud83d\udc7d  \ud83d\udc7e  \ud83d\udc7f  \ud83d\udc80  \ud83d\udc94  \ud83d\udca2  \ud83d\udca3  \ud83d\udca6  \ud83d\udca8  \ud83d\udca9  \ud83d\udcab  \ud83d\udcc9  \ud83d\udd95  \ud83d\udd95\ud83c\udffb  \ud83d\udd95\ud83c\udffc  \ud83d\udd95\ud83c\udffd  \ud83d\udd95\ud83c\udffe  \ud83d\udd95\ud83c\udfff  \ud83d\uddef  \ud83d\ude13  \ud83d\ude14  \ud83d\ude16  \ud83d\ude1e  \ud83d\ude1f  \ud83d\ude20  \ud83d\ude21  \ud83d\ude22  \ud83d\ude23  \ud83d\ude25  \ud83d\ude26  \ud83d\ude27  \ud83d\ude28  \ud83d\ude29  \ud83d\ude2a  \ud83d\ude2b  \ud83d\ude2c  \ud83d\ude2d  \ud83d\ude2e  \ud83d\ude2f  \ud83d\ude30  \ud83d\ude31  \ud83d\ude32  \ud83d\ude33  \ud83d\ude35  \ud83d\ude37  \ud83d\ude3e  \ud83d\ude3f  \ud83d\ude40  \ud83d\ude41  \ud83d\ude43  \ud83d\ude45  \ud83d\ude45\ud83c\udffb  \ud83d\ude45\ud83c\udffc  \ud83d\ude45\ud83c\udffd  \ud83d\ude45\ud83c\udffe  \ud83d\ude45\ud83c\udfff  \ud83d\ude48  \ud83d\ude49  \ud83d\ude4a  \ud83d\ude4e  \ud83d\ude4e\ud83c\udffb  \ud83d\ude4e\ud83c\udffc  \ud83d\ude4e\ud83c\udffd  \ud83d\ude4e\ud83c\udffe  \ud83d\ude4e\ud83c\udfff  \ud83d\udeab  \ud83d\udeb3  \ud83e\udd12  \ud83e\udd15  \ud83e\udd18  \ud83e\udd18\ud83c\udffb  \ud83e\udd18\ud83c\udffc  \ud83e\udd18\ud83c\udffd  \ud83e\udd18\ud83c\udffe  \ud83e\udd18\ud83c\udfff...\n\n\n\n\n```python\nfrom itertools import combinations\ntext = \"qu\u00e9 buena esta la pl\u00e1tica\"\ntokenizers = [1, 2, 3, -1, -2, (2,1), (2,2)]\n\nnum = 1\noutput = [\"\"\"\n\n## Tokenizadores Ejemplos ##\nLa codificaci\u00f3n es:\n\n- entero positivo: q-grama de caracter\n- entero engativo: w-word (n-grama de palabra)\n- tupla: skip-gram (tama\u00f1o, salto)\n\n\"\"\"]\nfor ltokens in range(len(tokenizers)):\n    output.append('## Combinaciones de tama\u00f1o {0} ##'.format(ltokens+1))\n    output.append('|id|combinaci\u00f3n|tokens|')\n    output.append('|--|-----------|------|')\n    for comb in combinations(tokenizers, ltokens+1):\n        model = TextModel([], token_list=comb)\n        output.append(\"|{0}|{1}|{2}|\".format(num, comb, \", \".join(model.tokenize(text))))\n        num += 1\n\nMarkdown(\"\\n\".join(output))\n```\n\n\n\n\n\n\n## Tokenizadores Ejemplos ##\nLa codificaci\u00f3n es:\n\n- entero positivo: q-grama de caracter\n- entero engativo: w-word (n-grama de palabra)\n- tupla: skip-gram (tama\u00f1o, salto)\n\n\n## Combinaciones de tama\u00f1o 1 ##\n|id|combinaci\u00f3n|tokens|\n|--|-----------|------|\n|1|(1,)|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~|\n|2|(2,)|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~|\n|3|(3,)|~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~|\n|4|(-1,)|que, buena, esta, la, platica|\n|5|(-2,)|que~buena, buena~esta, esta~la, la~platica|\n|6|((2, 1),)|que~esta, buena~la, esta~platica|\n|7|((2, 2),)|que~la, buena~platica|\n## Combinaciones de tama\u00f1o 2 ##\n|id|combinaci\u00f3n|tokens|\n|--|-----------|------|\n|8|(1, 2)|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~|\n|9|(1, 3)|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~|\n|10|(1, -1)|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, que, buena, esta, la, platica|\n|11|(1, -2)|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, que~buena, buena~esta, esta~la, la~platica|\n|12|(1, (2, 1))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, que~esta, buena~la, esta~platica|\n|13|(1, (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, que~la, buena~platica|\n|14|(2, 3)|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~|\n|15|(2, -1)|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que, buena, esta, la, platica|\n|16|(2, -2)|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que~buena, buena~esta, esta~la, la~platica|\n|17|(2, (2, 1))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que~esta, buena~la, esta~platica|\n|18|(2, (2, 2))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que~la, buena~platica|\n|19|(3, -1)|~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica|\n|20|(3, -2)|~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~buena, buena~esta, esta~la, la~platica|\n|21|(3, (2, 1))|~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~esta, buena~la, esta~platica|\n|22|(3, (2, 2))|~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~la, buena~platica|\n|23|(-1, -2)|que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica|\n|24|(-1, (2, 1))|que, buena, esta, la, platica, que~esta, buena~la, esta~platica|\n|25|(-1, (2, 2))|que, buena, esta, la, platica, que~la, buena~platica|\n|26|(-2, (2, 1))|que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica|\n|27|(-2, (2, 2))|que~buena, buena~esta, esta~la, la~platica, que~la, buena~platica|\n|28|((2, 1), (2, 2))|que~esta, buena~la, esta~platica, que~la, buena~platica|\n## Combinaciones de tama\u00f1o 3 ##\n|id|combinaci\u00f3n|tokens|\n|--|-----------|------|\n|29|(1, 2, 3)|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~|\n|30|(1, 2, -1)|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que, buena, esta, la, platica|\n|31|(1, 2, -2)|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que~buena, buena~esta, esta~la, la~platica|\n|32|(1, 2, (2, 1))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que~esta, buena~la, esta~platica|\n|33|(1, 2, (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que~la, buena~platica|\n|34|(1, 3, -1)|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica|\n|35|(1, 3, -2)|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~buena, buena~esta, esta~la, la~platica|\n|36|(1, 3, (2, 1))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~esta, buena~la, esta~platica|\n|37|(1, 3, (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~la, buena~platica|\n|38|(1, -1, -2)|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica|\n|39|(1, -1, (2, 1))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, que, buena, esta, la, platica, que~esta, buena~la, esta~platica|\n|40|(1, -1, (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, que, buena, esta, la, platica, que~la, buena~platica|\n|41|(1, -2, (2, 1))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica|\n|42|(1, -2, (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, que~buena, buena~esta, esta~la, la~platica, que~la, buena~platica|\n|43|(1, (2, 1), (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|44|(2, 3, -1)|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica|\n|45|(2, 3, -2)|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~buena, buena~esta, esta~la, la~platica|\n|46|(2, 3, (2, 1))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~esta, buena~la, esta~platica|\n|47|(2, 3, (2, 2))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~la, buena~platica|\n|48|(2, -1, -2)|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica|\n|49|(2, -1, (2, 1))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que, buena, esta, la, platica, que~esta, buena~la, esta~platica|\n|50|(2, -1, (2, 2))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que, buena, esta, la, platica, que~la, buena~platica|\n|51|(2, -2, (2, 1))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica|\n|52|(2, -2, (2, 2))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que~buena, buena~esta, esta~la, la~platica, que~la, buena~platica|\n|53|(2, (2, 1), (2, 2))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|54|(3, -1, -2)|~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica|\n|55|(3, -1, (2, 1))|~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~esta, buena~la, esta~platica|\n|56|(3, -1, (2, 2))|~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~la, buena~platica|\n|57|(3, -2, (2, 1))|~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica|\n|58|(3, -2, (2, 2))|~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~buena, buena~esta, esta~la, la~platica, que~la, buena~platica|\n|59|(3, (2, 1), (2, 2))|~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|60|(-1, -2, (2, 1))|que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica|\n|61|(-1, -2, (2, 2))|que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~la, buena~platica|\n|62|(-1, (2, 1), (2, 2))|que, buena, esta, la, platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|63|(-2, (2, 1), (2, 2))|que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n## Combinaciones de tama\u00f1o 4 ##\n|id|combinaci\u00f3n|tokens|\n|--|-----------|------|\n|64|(1, 2, 3, -1)|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica|\n|65|(1, 2, 3, -2)|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~buena, buena~esta, esta~la, la~platica|\n|66|(1, 2, 3, (2, 1))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~esta, buena~la, esta~platica|\n|67|(1, 2, 3, (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~la, buena~platica|\n|68|(1, 2, -1, -2)|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica|\n|69|(1, 2, -1, (2, 1))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que, buena, esta, la, platica, que~esta, buena~la, esta~platica|\n|70|(1, 2, -1, (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que, buena, esta, la, platica, que~la, buena~platica|\n|71|(1, 2, -2, (2, 1))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica|\n|72|(1, 2, -2, (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que~buena, buena~esta, esta~la, la~platica, que~la, buena~platica|\n|73|(1, 2, (2, 1), (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|74|(1, 3, -1, -2)|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica|\n|75|(1, 3, -1, (2, 1))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~esta, buena~la, esta~platica|\n|76|(1, 3, -1, (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~la, buena~platica|\n|77|(1, 3, -2, (2, 1))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica|\n|78|(1, 3, -2, (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~buena, buena~esta, esta~la, la~platica, que~la, buena~platica|\n|79|(1, 3, (2, 1), (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|80|(1, -1, -2, (2, 1))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica|\n|81|(1, -1, -2, (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~la, buena~platica|\n|82|(1, -1, (2, 1), (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, que, buena, esta, la, platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|83|(1, -2, (2, 1), (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|84|(2, 3, -1, -2)|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica|\n|85|(2, 3, -1, (2, 1))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~esta, buena~la, esta~platica|\n|86|(2, 3, -1, (2, 2))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~la, buena~platica|\n|87|(2, 3, -2, (2, 1))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica|\n|88|(2, 3, -2, (2, 2))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~buena, buena~esta, esta~la, la~platica, que~la, buena~platica|\n|89|(2, 3, (2, 1), (2, 2))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|90|(2, -1, -2, (2, 1))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica|\n|91|(2, -1, -2, (2, 2))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~la, buena~platica|\n|92|(2, -1, (2, 1), (2, 2))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que, buena, esta, la, platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|93|(2, -2, (2, 1), (2, 2))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|94|(3, -1, -2, (2, 1))|~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica|\n|95|(3, -1, -2, (2, 2))|~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~la, buena~platica|\n|96|(3, -1, (2, 1), (2, 2))|~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|97|(3, -2, (2, 1), (2, 2))|~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|98|(-1, -2, (2, 1), (2, 2))|que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n## Combinaciones de tama\u00f1o 5 ##\n|id|combinaci\u00f3n|tokens|\n|--|-----------|------|\n|99|(1, 2, 3, -1, -2)|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica|\n|100|(1, 2, 3, -1, (2, 1))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~esta, buena~la, esta~platica|\n|101|(1, 2, 3, -1, (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~la, buena~platica|\n|102|(1, 2, 3, -2, (2, 1))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica|\n|103|(1, 2, 3, -2, (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~buena, buena~esta, esta~la, la~platica, que~la, buena~platica|\n|104|(1, 2, 3, (2, 1), (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|105|(1, 2, -1, -2, (2, 1))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica|\n|106|(1, 2, -1, -2, (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~la, buena~platica|\n|107|(1, 2, -1, (2, 1), (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que, buena, esta, la, platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|108|(1, 2, -2, (2, 1), (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|109|(1, 3, -1, -2, (2, 1))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica|\n|110|(1, 3, -1, -2, (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~la, buena~platica|\n|111|(1, 3, -1, (2, 1), (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|112|(1, 3, -2, (2, 1), (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|113|(1, -1, -2, (2, 1), (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|114|(2, 3, -1, -2, (2, 1))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica|\n|115|(2, 3, -1, -2, (2, 2))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~la, buena~platica|\n|116|(2, 3, -1, (2, 1), (2, 2))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|117|(2, 3, -2, (2, 1), (2, 2))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|118|(2, -1, -2, (2, 1), (2, 2))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|119|(3, -1, -2, (2, 1), (2, 2))|~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n## Combinaciones de tama\u00f1o 6 ##\n|id|combinaci\u00f3n|tokens|\n|--|-----------|------|\n|120|(1, 2, 3, -1, -2, (2, 1))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica|\n|121|(1, 2, 3, -1, -2, (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~la, buena~platica|\n|122|(1, 2, 3, -1, (2, 1), (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|123|(1, 2, 3, -2, (2, 1), (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|124|(1, 2, -1, -2, (2, 1), (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|125|(1, 3, -1, -2, (2, 1), (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n|126|(2, 3, -1, -2, (2, 1), (2, 2))|~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n## Combinaciones de tama\u00f1o 7 ##\n|id|combinaci\u00f3n|tokens|\n|--|-----------|------|\n|127|(1, 2, 3, -1, -2, (2, 1), (2, 2))|~, q, u, e, ~, b, u, e, n, a, ~, e, s, t, a, ~, l, a, ~, p, l, a, t, i, c, a, ~, ~q, qu, ue, e~, ~b, bu, ue, en, na, a~, ~e, es, st, ta, a~, ~l, la, a~, ~p, pl, la, at, ti, ic, ca, a~, ~qu, que, ue~, e~b, ~bu, bue, uen, ena, na~, a~e, ~es, est, sta, ta~, a~l, ~la, la~, a~p, ~pl, pla, lat, ati, tic, ica, ca~, que, buena, esta, la, platica, que~buena, buena~esta, esta~la, la~platica, que~esta, buena~la, esta~platica, que~la, buena~platica|\n\n\n", "meta": {"hexsha": "f0f42383818be62bffb915a3fb9165b85a52a9da", "size": 62989, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "smm2016.ipynb", "max_stars_repo_name": "INGEOTEC/pres-MSA-SMM2016", "max_stars_repo_head_hexsha": "a3fbade30332e5649c24f294de682c59a1d496b0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "smm2016.ipynb", "max_issues_repo_name": "INGEOTEC/pres-MSA-SMM2016", "max_issues_repo_head_hexsha": "a3fbade30332e5649c24f294de682c59a1d496b0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "smm2016.ipynb", "max_forks_repo_name": "INGEOTEC/pres-MSA-SMM2016", "max_forks_repo_head_hexsha": "a3fbade30332e5649c24f294de682c59a1d496b0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.0950533463, "max_line_length": 1021, "alphanum_fraction": 0.4709869977, "converted": true, "num_tokens": 24750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814794452761, "lm_q2_score": 0.10230470652415342, "lm_q1q2_score": 0.044398347891566894}}
{"text": "```python\n#remove cell visibility\nfrom IPython.display import HTML\ntag = HTML('''\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.''')\ndisplay(tag)\n```\n\n\n\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.\n\n\n\n```python\n%matplotlib inline\nimport control\nimport numpy\nimport sympy as sym\nfrom IPython.display import display, Markdown\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\n\n\n#print a matrix latex-like\ndef bmatrix(a):\n     \"\"\"Returns a LaTeX bmatrix - by Damir Arbula (ICCT project)\n\n     :a: numpy array\n     :returns: LaTeX bmatrix as a string\n     \"\"\"\n     if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n     lines = str(a).replace('[', '').replace(']', '').splitlines()\n     rv = [r'\\begin{bmatrix}']\n     rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n     rv +=  [r'\\end{bmatrix}']\n     return '\\n'.join(rv)\n\n\n# Display formatted matrix: \ndef vmatrix(a):\n    if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n    lines = str(a).replace('[', '').replace(']', '').splitlines()\n    rv = [r'\\begin{vmatrix}']\n    rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n    rv +=  [r'\\end{vmatrix}']\n    return '\\n'.join(rv)\n\n\n#matrixWidget is a matrix looking widget built with a VBox of HBox(es) that returns a numPy array as value !\nclass matrixWidget(widgets.VBox):\n    def updateM(self,change):\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.M_[irow,icol] = self.children[irow].children[icol].value\n                #print(self.M_[irow,icol])\n        self.value = self.M_\n\n    def dummychangecallback(self,change):\n        pass\n    \n    \n    def __init__(self,n,m):\n        self.n = n\n        self.m = m\n        self.M_ = numpy.matrix(numpy.zeros((self.n,self.m)))\n        self.value = self.M_\n        widgets.VBox.__init__(self,\n                             children = [\n                                 widgets.HBox(children = \n                                              [widgets.FloatText(value=0.0, layout=widgets.Layout(width='90px')) for i in range(m)]\n                                             ) \n                                 for j in range(n)\n                             ])\n        \n        #fill in widgets and tell interact to call updateM each time a children changes value\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        #value = Unicode('example@example.com', help=\"The email value.\").tag(sync=True)\n        self.observe(self.updateM, names='value', type= 'All')\n        \n    def setM(self, newM):\n        #disable callbacks, change values, and reenable\n        self.unobserve(self.updateM, names='value', type= 'All')\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].unobserve(self.updateM, names='value')\n        self.M_ = newM\n        self.value = self.M_\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        self.observe(self.updateM, names='value', type= 'All')        \n\n                #self.children[irow].children[icol].observe(self.updateM, names='value')\n\n             \n#overlaod class for state space systems that DO NOT remove \"useless\" states (what \"professor\" of automatic control would do this?)\nclass sss(control.StateSpace):\n    def __init__(self,*args):\n        #call base class init constructor\n        control.StateSpace.__init__(self,*args)\n    #disable function below in base class\n    def _remove_useless_states(self):\n        pass\n```\n\n## Krmiljenje longitudinalne hitrosti kvadrotorja\n\n\n\nLongitudinalno hitrost kvadrotorja (ali kvadrokopterja) lahko krmilimo z nagibom kvadrotorja prek njegovega kota okoli pre\u010dne osi. Kot $\\theta$ krmilimo prek navora $T$ z uporabo propelerjev. Vztrajnostni moment vozila je $J= 1.3e-2$. Ko je vozilo nagnjeno za kot $\\theta$, producirajo propelerji vle\u010dno silo, ki je pribli\u017eno enaka $F_v = F\\theta = mg\\theta$, zra\u010dni upor je $F_c=-cv=-0.9v$, $m=2000$ g je masa vozila, $g = 9.81$ m/s<sup>2</sup> pa te\u017enostni pospe\u0161ek. Maksimalen navor zna\u0161a $5000$ mNm. Kot vozila okoli pre\u010dne osi $\\theta$ mora biti omejen na $\\pm30$ stopinj skozi celotno delovanje kvadrotorja, maksimalna hitrost pa na 2 m/s. Kot vozila okoli pre\u010dne osi je ocenjen na podlagi ustreznega senzorja in hitrosti, merjene z uporabo GPS.\n\nPostopek na\u010drtovanja krmiljenja sestoji iz dveh korakov:\n1. Zapis ena\u010db sistema v obliki prostora stanj za rotacijsko dinamiko (navor $T$ in kot vozila okoli pre\u010dne osi $\\theta$) ter longitudinalno dinamiko (od kota vozila okoli pre\u010dne osi do naprej usmerjene hitrosti $v$).\n2. Na\u010drtovanje regulatorja za $v$ ob upo\u0161tevanju naslednjih zahtev:\n    - \u010cas ustalitve kraj\u0161i od 2.5 s (dose\u017eena vrednost izhoda naj se razlikuje od tiste v stacionarnem stanju za 5%).\n    - Brez prenihaja.\n    - Brez odstopka v stacionarnem stanju v odzivu na vhodno kora\u010dno funkcijo hitrosti.\n\n### Ena\u010dbe sistema\n\nEna\u010dbi sistema sta:\n\n\\begin{cases}\n    m\\dot{v} = F_v + F_c = mg\\theta -cv \\\\\n    J\\ddot{\\theta} = T.\n\\end{cases}\n\nOb upo\u0161tevanju vektorja stanj $x = \\begin{bmatrix} x_1 & x_2 & x_3 \\end{bmatrix}^T = \\begin{bmatrix} v & \\theta & \\dot{\\theta} \\end{bmatrix}^T$ ter vhoda $u=T$, lahko zapi\u0161emo ena\u010dbe sistema v obliki prostora stanj:\n\n\\begin{cases}\n\\dot{x} = \\begin{bmatrix} -c/m & g & 0 \\\\ 0 & 0 & 1 \\\\ 0 & 0 & 0 \\end{bmatrix}x + \\begin{bmatrix} 0 \\\\ 0 \\\\ 1/J \\end{bmatrix}u \\\\\ny = \\begin{bmatrix} y_1 \\\\ y_2 \\end{bmatrix} = \\begin{bmatrix} 1 & 0 & 0 \\\\ 0 & 1 & 0 \\end{bmatrix}x\n\\end{cases}\n\nDinamika od $u$ do $\\theta$ je dvojni integrator, medtem ko je tista od $\\theta$ do $v$ dinamika prvega reda s polom v $-c/m$. Sistem ima dva izhoda: hitrost in kot nagiba vozila. \n\nVodljivostna matrika $\\mathcal{C}$ je\n\n\n```python\nA = numpy.matrix('-0.45 9.81 0; 0 0 1; 0 0 0')\nB = numpy.matrix([[0],[0],[1/1.3E-02]])\nC = numpy.matrix('1 0 0; 0 1 0')\nD = numpy.matrix('0; 0')\n\nCM = control.ctrb(A,B)\ndisplay(Markdown(bmatrix(CM)))\n# print(numpy.linalg.matrix_rank(CM))\n```\n\n\n\\begin{bmatrix}\n  0. & 0. & 754.61538462\\\\\n  0. & 76.92307692 & 0.\\\\\n  76.92307692 & 0. & 0.\\\\\n\\end{bmatrix}\n\n\nin ima rang enak 3, kar pomeni, da je sistem vodljiv.\nSpoznavnostna matrija $\\mathcal{O}$ je\n\n\n```python\nOM = control.obsv(A,C)\ndisplay(Markdown(bmatrix(OM)))\n# print(numpy.linalg.matrix_rank(OM))\n```\n\n\n\\begin{bmatrix}\n  1. & 0. & 0.\\\\\n  0. & 1. & 0.\\\\\n  -0.45 & 9.81 & 0.\\\\\n  0. & 0. & 1.\\\\\n  0.2025 & -4.4145 & 9.81\\\\\n  0. & 0. & 0.\\\\\n\\end{bmatrix}\n\n\nin ima rang enak 3, kar pomeni da je sistem spoznaven.\n\n### Na\u010drovanje regulatorja\n#### Na\u010drtovanje spoznavalnika\nKer neposredno merimo $x_1$ in $x_2$, nas zanima le ocena stanja $x_3$. \u010ce pogledamo podsistem $(x_2, \\, x_3)$, opazimo, da je spoznaven, tako da je mo\u017eno na\u010drtovati spoznavalnik zgolj za ta podsistem. Zgradba spoznavalnika je tako: \n\n$$\n\\begin{bmatrix} \\dot{\\hat{x}_2} \\\\ \\dot{\\hat{x}_3} \\end{bmatrix} = \\begin{bmatrix} 0 & 1 \\\\ 0 & 0 \\end{bmatrix}\\begin{bmatrix} \\hat{x}_2 \\\\ \\hat{x}_3 \\end{bmatrix} + \\begin{bmatrix} 0 \\\\ 1/J \\end{bmatrix}u + \\begin{bmatrix} l_1 \\\\ l_2 \\end{bmatrix}\\left( y - C\\begin{bmatrix} \\hat{x}_2 \\\\ \\hat{x}_3 \\end{bmatrix} \\right) = \\begin{bmatrix} -l_1 & 1 \\\\ -l_2 & 0 \\end{bmatrix}\\begin{bmatrix} \\hat{x}_2 \\\\ \\hat{x}_3 \\end{bmatrix} + \\begin{bmatrix} 0 \\\\ 1/J \\end{bmatrix}u + \\begin{bmatrix} l_1 \\\\ l_2 \\end{bmatrix}y\n$$\n\nz uporabo Laplaceove transformacije in re\u0161itvijo za $\\hat{x}_3(s)$, dobimo\n\n$$\n\\hat{x}_3(s) = \\frac{l_2s}{s^2+l_1s+l_2}y_2(s) + \\frac{s+l_1}{s^2+l_1s+l_2}\\frac{u(s)}{J}.\n$$\n\nDobili smo enostaven linearen spoznavalnik za $x_3$, ki je asimptoti\u010dno stabilen za vsak $l_1>0$ in $l_2>0$. Zanimivo je, da \u010de velja $l_2\\rightarrow \\infty$, se prenosna funkcija spoznavalnika poenostavi v $\\hat{x}_3(s) = s y_2(s)$, rezultat pa je enak $\\hat{x}_3 = \\dot{\\theta}$; slednjega dobimo z odvodom izmerjene spremenljivke $y_2 = \\theta$.\n\nZ izbiro $l_1 = 20$ in $l_2 = 100$ sta obe lastni vrednosti spoznavalnika enaki $-10$.\n\n#### Na\u010drtovanje krmilnika\nZa izpolnitev zahteve glede \u010dasa ustalitve, mora biti frekvenca polov ve\u010dja kot $3/T_S$ (v primeru realnih polov) oz. $3/\\zeta Ts$ (v primeru kompleksnih polov), pri \u010demer sta $T_s$ \u010das ustalitve, $\\zeta$ pa razmernik du\u0161enja. Dobre lokacije polov (v smislu odziva in vhodne energije) za sistem z dvojnim integratorjem, so v obmo\u010dju $\\pm 45\u00b0$ glede na negativno realno os. Z upo\u0161tevanjem teh dejstvem, izberemo dominantna pola v $-2.8\\pm1.0i$, medtem ko je tretji pol razporedimo v $-15$.\nZa izpolnitev zahteve glede odstopka v stacionarnem stanju, moramo vhod skalirati z oja\u010danjem, ki je enak inverzu oja\u010danja zaprtozan\u010dnega sistema v stacionarnem stanju, da dose\u017eemo, da je vrednost celotnega zaprtozan\u010dnega oja\u010danja enako $1.0$.\n\n### Kako upravljati s tem interaktivnim primerom?\n- Preveri izpolnjevanje danih zahtev v primeru za\u010detne napake ocene stanja $x_3$ (tako za pozitivne kot negativne vrednosti napake).\n- Opazuj spremembe odziva sistema in, ob upo\u0161tevanju fizi\u010dnega sistema, poizkusi razumeti, zakaj se odziv spremeni na tak na\u010din, kot se.\n\n\n```python\n# Preparatory cell\n\nX0 = 0.0\nK = numpy.matrix([8/15,-4.4,-4])\nL = numpy.matrix([[66],[107/3]])\n\nAw = matrixWidget(3,3)\nAw.setM(A)\nBw = matrixWidget(3,1)\nBw.setM(B)\nCw = matrixWidget(1,3)\nCw.setM(C)\nX0w = widgets.FloatText(\n    value=X0,\n    description='',\n    disabled=False\n)\nKw = matrixWidget(1,3)\nKw.setM(K)\nLw = matrixWidget(2,1)\nLw.setM(L)\n\n\neig1c = matrixWidget(1,1)\neig2c = matrixWidget(2,1)\neig3c = matrixWidget(1,1)\neig1c.setM(numpy.matrix([-15.])) \neig2c.setM(numpy.matrix([[-2.8],[-1.0]]))\neig3c.setM(numpy.matrix([-15.]))\n\neig2o = matrixWidget(2,1)\neig3o = matrixWidget(1,1)\neig2o.setM(numpy.matrix([[-10.],[0.]]))\neig3o.setM(numpy.matrix([-10.]))\n```\n\n\n```python\n# Misc\n\n#create dummy widget \nDW = widgets.FloatText(layout=widgets.Layout(width='0px', height='0px'))\n\n#create button widget\nSTART = widgets.Button(\n    description='Test',\n    disabled=False,\n    button_style='', # 'success', 'info', 'warning', 'danger' or ''\n    tooltip='Test',\n    icon='check'\n)\n                       \ndef on_start_button_clicked(b):\n    #This is a workaround to have intreactive_output call the callback:\n    #   force the value of the dummy widget to change\n    if DW.value> 0 :\n        DW.value = -1\n    else: \n        DW.value = 1\n    pass\nSTART.on_click(on_start_button_clicked)\n\n# Define type of method \nselm = widgets.Dropdown(\n    options= ['Nastavi K in L', 'Nastavi lastne vrednosti'],\n    value= 'Nastavi lastne vrednosti',\n    description='',\n    disabled=False\n)\n\n# Define the number of complex eigenvalues\nsele = widgets.Dropdown(\n    options= ['brez kompleksnih lastnih vrednosti', 'dve kompleksni lastni vrednosti'],\n    value= 'dve kompleksni lastni vrednosti',\n    description='Kompleksne lastne vrednosti:',\n    style = {'description_width': 'initial'},\n    disabled=False\n)\n\n#define type of ipout \nselu = widgets.Dropdown(\n    options=['impulzna funkcija', 'kora\u010dna funkcija', 'sinusoidna funkcija', 'kvadratni val'],\n    value='kora\u010dna funkcija',\n    description='Vhod:',\n    style = {'description_width': 'initial'},\n    disabled=False\n)\n# Define the values of the input\nu = widgets.FloatSlider(\n    value=2,\n    min=0,\n    max=4,\n    step=0.1,\n    description='Vhod:',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.1f',\n)\nperiod = widgets.FloatSlider(\n    value=0.5,\n    min=0.001,\n    max=10,\n    step=0.001,\n    description='Perioda: ',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.2f',\n)\n\ngain_w2 = widgets.FloatText(\n    value=1.,\n    description='',\n    disabled=True\n)\n\nsimTime = widgets.FloatText(\n    value=3,\n    description='',\n    disabled=False\n)\n```\n\n\n```python\n# Support functions\n\ndef eigen_choice(sele):\n    if sele == 'brez kompleksnih lastnih vrednosti':\n        eig1c.children[0].children[0].disabled = False\n        eig2c.children[1].children[0].disabled = True\n        eig2o.children[1].children[0].disabled = True\n        eig = 0\n    if sele == 'dve kompleksni lastni vrednosti':\n        eig1c.children[0].children[0].disabled = True\n        eig2c.children[1].children[0].disabled = False\n        eig2o.children[1].children[0].disabled = False\n        eig = 2\n    return eig\n\ndef method_choice(selm):\n    if selm == 'Nastavi K in L':\n        method = 1\n        sele.disabled = True\n    if selm == 'Nastavi lastne vrednosti':\n        method = 2\n        sele.disabled = False\n    return method\n```\n\n\n```python\n# Reduced system\nAr = numpy.matrix('0 1; 0 0')\nBr = numpy.matrix([[0],[1/1.3E-02]])\nCr = numpy.matrix('1 0')\nDr = numpy.matrix('0')\n\ndef main_callback2(Aw, Bw, X0w, K, L, eig1c, eig2c, eig3c, eig2o, eig3o, u, period, selm, sele, selu, simTime, DW):\n    eige = eigen_choice(sele)\n    method = method_choice(selm)\n    \n    if method == 1:\n        solc = numpy.linalg.eig(A-B*K)\n        solo = numpy.linalg.eig(Ar-L*Cr)\n    if method == 2:\n        if eige == 0:\n            K = control.acker(A, B, [eig1c[0,0], eig2c[0,0], eig3c[0,0]])\n            Kw.setM(K)\n            \n            L = control.acker(Ar.T, Cr.T, [eig2o[0,0], eig3o[0,0]]).T\n            Lw.setM(L)\n        if eige == 2:\n            K = control.acker(A, B, [eig3c[0,0], \n                                     numpy.complex(eig2c[0,0],eig2c[1,0]), \n                                     numpy.complex(eig2c[0,0],-eig2c[1,0])])\n            Kw.setM(K)\n            \n            L = control.acker(Ar.T, Cr.T, [numpy.complex(eig2o[0,0],eig2o[1,0]), \n                                           numpy.complex(eig2o[0,0],-eig2o[1,0])]).T\n            Lw.setM(L)\n            \n    \n    sys = control.ss(A,B,numpy.vstack((C,numpy.zeros((B.shape[1],C.shape[1])))),numpy.vstack((D,numpy.eye(B.shape[1]))))\n    sysC = control.ss(numpy.zeros((1,1)),\n                      numpy.zeros((1,numpy.shape(A)[0])),\n                      numpy.zeros((numpy.shape(B)[1],1)),\n                      -K)\n    \n    sysE = control.ss(Ar-L*Cr,\n                      numpy.hstack((L,Br-L*Dr)),\n                      numpy.matrix('0 1'),\n                      numpy.zeros((1,2)))\n    \n    sys_append = control.append(sys, sysE, sysC, control.ss(A,B,numpy.eye(A.shape[0]),numpy.zeros((A.shape[0],B.shape[1]))))\n    Q = []\n    # y in ingresso a sysE\n    for i in range(1):\n        Q.append([B.shape[1]+i+1, i+2])\n    # u in ingresso a sysE\n    for i in range(B.shape[1]):\n        Q.append([B.shape[1]+1+i+1, C.shape[0]+i+1])\n    # u in ingresso a sys\n    for i in range(B.shape[1]):\n        Q.append([i+1, C.shape[0]+B.shape[1]+1+i+1])\n    # u in ingresso al sistema che ha come uscite gli stati reali\n    for i in range(B.shape[1]):\n        Q.append([2*B.shape[1]+1+A.shape[0]+i+1, C.shape[0]+i+1])\n    # xe in ingresso a sysC\n    Q.append([2*B.shape[1]+1+1, 1])\n    Q.append([2*B.shape[1]+1+1+1, 1+1])\n    Q.append([2*B.shape[1]+1+2+1, C.shape[0]+B.shape[1]+1])\n        \n    inputv = [i+1 for i in range(B.shape[1])]\n    outputv = [i+1 for i in range(numpy.shape(sys_append.C)[0])]\n    sys_CL = control.connect(sys_append,\n                             Q,\n                             inputv,\n                             outputv)\n    \n    t = numpy.linspace(0, 100000, 2)\n    t, yout = control.step_response(sys_CL[0,0],T=t)\n    dcgain = yout[-1]\n    gain_w2.value = dcgain\n    if dcgain != 0:\n        u1 = u/gain_w2.value\n    else:\n        print('Nastavljena vrednost inverza oja\u010danja je enaka 0 in je bila spremenjena na vrednost 1')\n        u1 = u/1\n    print('Stati\u010dno oja\u010danje zaprtozan\u010dnega sistema (od vhoda do izhoda) je: %.5f' %dcgain)\n    \n    X0w1 = numpy.zeros((2*A.shape[0]+2,1))\n    X0w1[A.shape[0]+1,0] = X0w\n    if simTime != 0:\n        T = numpy.linspace(0, simTime, 10000)\n    else:\n        T = numpy.linspace(0, 1, 10000)\n      \n    if selu == 'impulzna funkcija': #selu\n        U = [0 for t in range(0,len(T))]\n        U[0] = u\n        U1 = [0 for t in range(0,len(T))]\n        U1[0] = u1\n        T, yout, xout = control.forced_response(sys_CL,T,U1,X0w1)\n    if selu == 'kora\u010dna funkcija':\n        U = [u for t in range(0,len(T))]\n        U1 = [u1 for t in range(0,len(T))]\n        T, yout, xout = control.forced_response(sys_CL,T,U1,X0w1)\n    if selu == 'sinusoidna funkcija':\n        U = u*numpy.sin(2*numpy.pi/period*T)\n        U1 = u1*numpy.sin(2*numpy.pi/period*T)\n        T, yout, xout = control.forced_response(sys_CL,T,U1,X0w1)\n    if selu == 'kvadratni val':\n        U = u*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n        U1 = u1*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n        T, yout, xout = control.forced_response(sys_CL,T,U1,X0w1)\n    # N.B. i primi 3 stati di xout sono quelli del sistema, mentre gli ultimi 3 sono quelli dell'osservatore\n    \n    step_info_dict = control.step_info(sys_CL[0,0],SettlingTimeThreshold=0.05,T=T)\n    print('Informacija o odzivu: \\n\\t\u010cas vzpona [s] =',step_info_dict['RiseTime'],'\\n\\t\u010cas ustalitve [s] =',step_info_dict['SettlingTime'],'\\n\\tPrenihaj [%]=',step_info_dict['Overshoot'])\n    print('Maksimalna vrednost x2 (%)=', max(abs(yout[C.shape[0]+2*B.shape[1]+1+1]))/(numpy.pi/180*30)*100)\n    \n    fig = plt.figure(num='Simulacija 1', figsize=(14,12))\n    \n    fig.add_subplot(221)\n    plt.title('Odziv sistema')\n    plt.ylabel('Izhod')\n    plt.plot(T,yout[0],T,U,'r--')\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$y$','referenca'])\n    plt.grid()\n    \n    fig.add_subplot(222)\n    plt.title('Vhod')\n    plt.ylabel('$u$')\n    plt.plot(T,yout[C.shape[0]])\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(223)\n    plt.title('Odzive stanj')\n    plt.ylabel('Stanja')\n    plt.plot(T,yout[C.shape[0]+2*B.shape[1]+1],\n             T,yout[C.shape[0]+2*B.shape[1]+1+1],\n             T,yout[C.shape[0]+2*B.shape[1]+1+2],\n             T,[numpy.pi/180*30 for i in range(len(T))],'r--',\n             T,[-numpy.pi/180*30 for i in range(len(T))],'r--')\n    plt.xlabel('$t$ [s]')\n    plt.legend(['$x_{1}$','$x_{2}$','$x_{3}$','limit +$x_{2}$','limit -$x_{2}$'])\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(224)\n    plt.title('Ocena napake stanj')\n    plt.ylabel('Ocena napake stanj')\n    plt.plot(T,yout[C.shape[0]+2*B.shape[1]+1+2]-yout[C.shape[0]+B.shape[1]])\n    plt.xlabel('$t$ [s]')\n    plt.legend(['$e_{3}$'])\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    #plt.tight_layout()\n   \nalltogether2 = widgets.VBox([widgets.HBox([selm, \n                                          sele,\n                                          selu]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.Label('K:',border=3), Kw, \n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Lastne vrednosti:',border=3),\n                                          eig1c, \n                                          eig2c, \n                                          eig3c,\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3)]),\n                            widgets.Label('X0 est.:',border=3), X0w,\n                            widgets.Label(' ',border=3), \n                            widgets.HBox([widgets.Label('L:',border=3), Lw, \n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Lastne vrednosti:',border=3), \n                                          eig2o, \n                                          eig3o,\n                                          widgets.Label(' ',border=3),\n                                          widgets.VBox([widgets.Label('Inverzno oja\u010danje vhoda:',border=3),\n                                                        widgets.Label('Simulacijski \u010das (s):',border=3)]),\n                                          widgets.VBox([gain_w2,simTime])]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([u, \n                                          period, \n                                          START])])\nout2 = widgets.interactive_output(main_callback2, {'Aw':Aw, 'Bw':Bw, 'X0w':X0w, 'K':Kw, 'L':Lw,\n                                                 'eig1c':eig1c, 'eig2c':eig2c, 'eig3c':eig3c, 'eig2o':eig2o, 'eig3o':eig3o, \n                                                 'u':u, 'period':period, 'selm':selm, 'sele':sele, 'selu':selu, 'simTime':simTime, 'DW':DW})\nout2.layout.height = '870px'\ndisplay(out2, alltogether2)\n```\n\n\n    Output(layout=Layout(height='870px'))\n\n\n\n    VBox(children=(HBox(children=(Dropdown(index=1, options=('Nastavi K in L', 'Nastavi lastne vrednosti'), value=\u2026\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "ef9ed1147bb47445279bb374c19a64210fe2d622", "size": 30128, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_si/examples/04/SS-37-Krmiljenje_longitudinalne_hitrosti_kvadrotorja.ipynb", "max_stars_repo_name": "ICCTerasmus/ICCT", "max_stars_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-22T18:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:10:22.000Z", "max_issues_repo_path": "ICCT_si/examples/04/SS-37-Krmiljenje_longitudinalne_hitrosti_kvadrotorja.ipynb", "max_issues_repo_name": "ICCTerasmus/ICCT", "max_issues_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICCT_si/examples/04/SS-37-Krmiljenje_longitudinalne_hitrosti_kvadrotorja.ipynb", "max_forks_repo_name": "ICCTerasmus/ICCT", "max_forks_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-24T11:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T16:36:18.000Z", "avg_line_length": 41.4986225895, "max_line_length": 766, "alphanum_fraction": 0.4924322889, "converted": true, "num_tokens": 7047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.1037486192456777, "lm_q1q2_score": 0.04423027658142052}}
{"text": "```python\n# Erasmus+ ICCT project (2018-1-SI01-KA203-047081)\n\n# Toggle cell visibility\n\nfrom IPython.display import HTML\ntag = HTML('''\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.''')\ndisplay(tag)\n\n# Hide the code completely\n\n# from IPython.display import HTML\n# tag = HTML('''<style>\n# div.input {\n#     display:none;\n# }\n# </style>''')\n# display(tag)\n\n```\n\n\n\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.\n\n\n## Notranja stabilnost\n\nKoncept notranje stabilnosti je vezan na odziv sistema, ki ga odklonimo iz ravnote\u017enega stanja; opisuje ali se stanje sistema po motnji razlikuje od stanja sistema pred motnjo (tj. v ravnote\u017eju).\n\n### Definicija\nZa \u010dasovno nespremenljiv dinami\u010dni sistem, ki ga popisujejo vektor stanja $x(t)\\in \\mathbb{R}^n$, ravnote\u017ena to\u010dka $x_e$, za\u010detno stanje $x_0$ ter za\u010detni \u010das $t_0$, mora veljati: \n\n$$\n\\forall \\, \\epsilon \\in \\mathbb{R}, \\, \\epsilon > 0 \\quad \\exists \\delta \\in \\mathbb{R}, \\, \\delta > 0 : \\quad ||x_0-x_e|| < \\delta \\, \\Rightarrow  \\, ||x(t)-x_e|| < \\epsilon \\quad \\forall t \\ge t_0.\n$$\n\nZgornji zapis lahko preberemo na naslednji na\u010din: \u010de obstaja dovolj majhna motnja $\\delta$, ki odkloni sistem iz ravnote\u017ene to\u010dke in povzro\u010di, da se odziv $x(t)$ ne razlikuje dovolj od ravnote\u017ene to\u010dke (tj. za ne ve\u010d kot $\\epsilon$), potem re\u010demo, da je ravnote\u017ena to\u010dka stabilna.\n\nDodatno, \u010de velja $\\lim_{t\\to\\infty}||x(t)-x_e|| = 0$, lahko to preberemo kot: \u010de se sistem vrne nazaj v ravnote\u017eno to\u010dko, potem re\u010demo, da je ravnote\u017eje asimptoti\u010dno stabilno.\n\nV primeru linearnega \u010dasovno nespremenljivega sistema:\n\n\\begin{cases}\n\\dot{x} = Ax +Bu \\\\\ny = Cx + Du,\n\\end{cases}\n\nlahko doka\u017eemo, da stabilnost ene ravnote\u017ene to\u010dke sistema nakazuje tudi stabilnost preostalih ravnote\u017enih to\u010dk; tako lahko govorimo o stabilnosti sistema (v splo\u0161nem) tudi kadar imamo na voljo informacijo o stabilnosti zgolj posamezne ravnote\u017ene to\u010dke. Ta posebnost linearnih sistemov je posledica dejstva, da je odziv teh sistemov strogo povezan z lastnimi vrednostmi dinami\u010dne matrike $A$, ki so rotacijsko, translacijsko, \u010dasovno, in z ozirom na za\u010detne pogoje nespremenljive.\n\nV interaktivnem primeru [Modalna analiza](SS-02-Modalna_analiza.ipynb) je navedeno:\n\n> Re\u0161itev diferencialne ena\u010dbe na podlagi za\u010detnega \u010dasa $t_0$ in za\u010detnih pogojev $x(t_0)$ je: \n$$\nx(t) = e^{A(t-t_0)}x(t_0).\n$$ Matrika $e^{A(t-t_0)}x(t_0)$ je linearna kombinacija \u010dasovnih funkcij $t$, od katerih je vsaka posamezna oblike $$e^{\\lambda t},$$ kjer $\\lambda$ ozna\u010duje lastne vrednosti matrike $A$; te funkcija imenujemo modalne oblike sistema.\n\nIz tega sledi:\n- linearni dinami\u010dni sistem je stabilen \u010de in samo \u010de vse njegove modalne oblike niso konvergentne,\n- linearni dinami\u010dni sistem je stabilen \u010de in samo \u010de so vse njegove modalne oblike konvergentne,\n- linearni dinami\u010dni sistem je nestabilen, \u010de ima vsaj eno divergentno modalno obliko.\n\nZ ozirom na lastne vrednosti dinami\u010dne matrike lahko zgornje pogoje zapi\u0161emo kot:\n- Vse lastne vrednosti matrike $A$ le\u017eijo v zaprti levi polovici kompleksne ravnine (tj. imajo realni del negativen ali enak 0) in je v primeru ni\u010delnega realnega dela njihova algebrai\u010dna ve\u010dkratnost enaka geometri\u010dni oz. so elementi Jordanovih blokov skalarji.\n- Vse lastne vrednosti pripadajo odprti levi polovici kompleksne ravnine, kar pomeni da imajo negativen realni del.\n- Najmanj ena lastna vrednost ima pozitiven realni del, ali pa imajo lastne vrednosti ni\u010delni realni del in Jordanove bloke, katerih elementi niso skalarji.\n\nTa interaktivni primer prikazuje dinami\u010dno matriko $A$, ki prikazuje njen prosti odziv ter pripadajo\u010de lastne vrednosti.\n\n### Kako upravljati s tem interaktivnim primerom?\n- Opazuj odziv sistema ob spremembah lastnih vrednosti in za\u010detnih pogojev $x_0$.\n\n\n```python\n%matplotlib inline\n#%matplotlib notebook \nimport control as control\nimport numpy\nimport sympy as sym\nfrom IPython.display import display, Markdown\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\n\n\n#print a matrix latex-like\ndef bmatrix(a):\n     \"\"\"Returns a LaTeX bmatrix - by Damir Arbula (ICCT project)\n\n     :a: numpy array\n     :returns: LaTeX bmatrix as a string\n     \"\"\"\n     if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n     lines = str(a).replace('[', '').replace(']', '').splitlines()\n     rv = [r'\\begin{bmatrix}']\n     rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n     rv +=  [r'\\end{bmatrix}']\n     return '\\n'.join(rv)\n\n\n# Display formatted matrix: \ndef vmatrix(a):\n    if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n    lines = str(a).replace('[', '').replace(']', '').splitlines()\n    rv = [r'\\begin{vmatrix}']\n    rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n    rv +=  [r'\\end{vmatrix}']\n    return '\\n'.join(rv)\n\n\n#matrixWidget is a matrix looking widget built with a VBox of HBox(es) that returns a numPy array as value !\nclass matrixWidget(widgets.VBox):\n    def updateM(self,change):\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.M_[irow,icol] = self.children[irow].children[icol].value\n                #print(self.M_[irow,icol])\n        self.value = self.M_\n\n    def dummychangecallback(self,change):\n        pass\n    \n    \n    def __init__(self,n,m):\n        self.n = n\n        self.m = m\n        self.M_ = numpy.matrix(numpy.zeros((self.n,self.m)))\n        self.value = self.M_\n        widgets.VBox.__init__(self,\n                             children = [\n                                 widgets.HBox(children = \n                                              [widgets.FloatText(value=0.0, layout=widgets.Layout(width='90px')) for i in range(m)]\n                                             ) \n                                 for j in range(n)\n                             ])\n        \n        #fill in widgets and tell interact to call updateM each time a children changes value\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        #value = Unicode('example@example.com', help=\"The email value.\").tag(sync=True)\n        self.observe(self.updateM, names='value', type= 'All')\n        \n    def setM(self, newM):\n        #disable callbacks, change values, and reenable\n        self.unobserve(self.updateM, names='value', type= 'All')\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].unobserve(self.updateM, names='value')\n        self.M_ = newM\n        self.value = self.M_\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        self.observe(self.updateM, names='value', type= 'All')        \n\n                #self.children[irow].children[icol].observe(self.updateM, names='value')\n\n             \n#overlaod class for state space systems that DO NOT remove \"useless\" states (what \"professor\" of automatic control would do this?)\nclass sss(control.StateSpace):\n    def __init__(self,*args):\n        #call base class init constructor\n        control.StateSpace.__init__(self,*args)\n    #disable function below in base class\n    def _remove_useless_states(self):\n        pass\n```\n\n\n```python\n# Preparatory cell\n\nA = numpy.matrix([[0,1],[-2/5,-1/5]])\nX0 = numpy.matrix('5; 3')\n\nAw = matrixWidget(2,2)\nAw.setM(A)\nX0w = matrixWidget(2,1)\nX0w.setM(X0)\n```\n\n\n```python\n# Misc\n\n#create dummy widget \nDW = widgets.FloatText(layout=widgets.Layout(width='0px', height='0px'))\n\n#create button widget\nSTART = widgets.Button(\n    description='Test',\n    disabled=False,\n    button_style='', # 'success', 'info', 'warning', 'danger' or ''\n    tooltip='Test',\n    icon='check'\n)\n                       \ndef on_start_button_clicked(b):\n    #This is a workaround to have intreactive_output call the callback:\n    #   force the value of the dummy widget to change\n    if DW.value> 0 :\n        DW.value = -1\n    else: \n        DW.value = 1\n    pass\nSTART.on_click(on_start_button_clicked)\n```\n\n\n```python\n# Main cell\n\ndef main_callback(A, X0, DW):\n    sols = numpy.linalg.eig(A)\n    sys = sss(A,[[1],[0]],[0,1],0)\n    pole = control.pole(sys)\n    if numpy.real(pole[0]) != 0:\n        p1r = abs(numpy.real(pole[0]))\n    else:\n        p1r = 1\n    if numpy.real(pole[1]) != 0:\n        p2r = abs(numpy.real(pole[1]))\n    else:\n        p2r = 1\n    if numpy.imag(pole[0]) != 0:\n        p1i = abs(numpy.imag(pole[0]))\n    else:\n        p1i = 1\n    if numpy.imag(pole[1]) != 0:\n        p2i = abs(numpy.imag(pole[1]))\n    else:\n        p2i = 1\n    \n    print('Lastni vrednosti matrike A sta:',round(sols[0][0],4),'in',round(sols[0][1],4))\n    \n    #T = numpy.linspace(0, 60, 1000)\n    T, yout, xout = control.initial_response(sys,X0=X0,return_x=True)\n    \n    fig = plt.figure(\"Lastni vrednosti matrike A sta:\", figsize=(16,16))\n    ax = fig.add_subplot(311,title='Poli (realni vs imaginarni)')\n    #plt.axis(True)\n    # Move left y-axis and bottim x-axis to centre, passing through (0,0)\n    # Eliminate upper and right axes\n    ax.spines['left'].set_position(('data',0.0))\n    ax.spines['bottom'].set_position(('data',0.0))\n    ax.spines['right'].set_color('none')\n    ax.spines['top'].set_color('none')\n    ax.set_xlim(-max([p1r+p1r/3,p2r+p2r/3]),\n                max([p1r+p1r/3,p2r+p2r/3]))\n    ax.set_ylim(-max([p1i+p1i/3,p2i+p2i/3]),\n                max([p1i+p1i/3,p2i+p2i/3]))\n    \n    plt.plot([numpy.real(pole[0]),numpy.real(pole[1])],[numpy.imag(pole[0]),numpy.imag(pole[1])],'o')\n    plt.grid()\n\n    ax1 = fig.add_subplot(312,title='Prosti odziv')\n    plt.plot(T,xout[0])\n    plt.grid()\n    ax1.set_xlabel('\u010das [s]')\n    ax1.set_ylabel('$x_1$')\n    ax1.axvline(x=0,color='black',linewidth='0.8')\n    ax1.axhline(y=0,color='black',linewidth='0.8')\n    ax2 = fig.add_subplot(313)\n    plt.plot(T,xout[1])\n    plt.grid()\n    ax2.set_xlabel('\u010das [s]')\n    ax2.set_ylabel('$x_2$')\n    ax2.axvline(x=0,color='black',linewidth='0.8')\n    ax2.axhline(y=0,color='black',linewidth='0.8')\n    \n    #plt.show()\n    \n\n    \nalltogether = widgets.HBox([widgets.VBox([widgets.Label('$A$:',border=3),\n                                          Aw]),\n                                          widgets.Label('   ',border=3),\n                            widgets.VBox([widgets.Label('$X_0$:',border=3),\n                                          X0w]),\n                                          START])\nout = widgets.interactive_output(main_callback, {'A':Aw, 'X0':X0w, 'DW':DW})\nout.layout.height = '1000px'\ndisplay(out, alltogether)\n```\n\n\n    Output(layout=Layout(height='1000px'))\n\n\n\n    HBox(children=(VBox(children=(Label(value='$A$:'), matrixWidget(children=(HBox(children=(FloatText(value=0.0, \u2026\n\n", "meta": {"hexsha": "b30e48e29d4990efdd85177d9e9c1d4e226d5af2", "size": 16034, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_si/examples/04/SS-17-Notranja_stabilnost.ipynb", "max_stars_repo_name": "ICCTerasmus/ICCT", "max_stars_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-22T18:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:10:22.000Z", "max_issues_repo_path": "ICCT_si/examples/04/SS-17-Notranja_stabilnost.ipynb", "max_issues_repo_name": "ICCTerasmus/ICCT", "max_issues_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICCT_si/examples/04/SS-17-Notranja_stabilnost.ipynb", "max_forks_repo_name": "ICCTerasmus/ICCT", "max_forks_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-24T11:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T16:36:18.000Z", "avg_line_length": 39.7866004963, "max_line_length": 489, "alphanum_fraction": 0.5268803792, "converted": true, "num_tokens": 3412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798742624020276, "lm_q2_score": 0.177810865121124, "lm_q1q2_score": 0.04409485879893138}}
{"text": "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Evaluating-Imbalanced-Datasets\" data-toc-modified-id=\"Evaluating-Imbalanced-Datasets-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Evaluating Imbalanced Datasets</a></span><ul class=\"toc-item\"><li><span><a href=\"#Dataset\" data-toc-modified-id=\"Dataset-1.1\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;</span>Dataset</a></span></li><li><span><a href=\"#Class-Weighting\" data-toc-modified-id=\"Class-Weighting-1.2\"><span class=\"toc-item-num\">1.2&nbsp;&nbsp;</span>Class Weighting</a></span></li><li><span><a href=\"#F1-Score\" data-toc-modified-id=\"F1-Score-1.3\"><span class=\"toc-item-num\">1.3&nbsp;&nbsp;</span>F1 Score</a></span></li><li><span><a href=\"#Conclusion\" data-toc-modified-id=\"Conclusion-1.4\"><span class=\"toc-item-num\">1.4&nbsp;&nbsp;</span>Conclusion</a></span></li></ul></li><li><span><a href=\"#Reference\" data-toc-modified-id=\"Reference-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Reference</a></span></li></ul></div>\n\n\n```python\n# code for loading the format for the notebook\nimport os\n\n# path : store the current path to convert back to it later\npath = os.getcwd()\nos.chdir(os.path.join('..', '..', 'notebook_format'))\n\nfrom formats import load_style\nload_style(plot_style=False)\n```\n\n\n\n\n<style>\n@import url('http://fonts.googleapis.com/css?family=Source+Code+Pro');\n@import url('http://fonts.googleapis.com/css?family=Vollkorn');\n@import url('http://fonts.googleapis.com/css?family=Arimo');\n@import url('http://fonts.googleapis.com/css?family=Fira_sans');\n\n    div.cell {\n        width: 1000px;\n        margin-left: 0% !important;\n        margin-right: auto;\n    }\n    div.text_cell code {\n        background: transparent;\n        color: #000000;\n        font-weight: 600;\n        font-size: 12pt;\n        font-style: bold;\n        font-family:  'Source Code Pro', Consolas, monocco, monospace;\n    }\n    h1 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n\t}\n\n    div.input_area {\n        background: #F6F6F9;\n        border: 1px solid #586e75;\n    }\n\n    .text_cell_render h1 {\n        font-weight: 200;\n        font-size: 30pt;\n        line-height: 100%;\n        color:#c76c0c;\n        margin-bottom: 0.5em;\n        margin-top: 1em;\n        display: block;\n        white-space: wrap;\n        text-align: left;\n    } \n    h2 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n        text-align: left;\n    }\n    .text_cell_render h2 {\n        font-weight: 200;\n        font-size: 16pt;\n        font-style: italic;\n        line-height: 100%;\n        color:#c76c0c;\n        margin-bottom: 0.5em;\n        margin-top: 1.5em;\n        display: block;\n        white-space: wrap;\n        text-align: left;\n    } \n    h3 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n    }\n    .text_cell_render h3 {\n        font-weight: 200;\n        font-size: 14pt;\n        line-height: 100%;\n        color:#d77c0c;\n        margin-bottom: 0.5em;\n        margin-top: 2em;\n        display: block;\n        white-space: wrap;\n        text-align: left;\n    }\n    h4 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n    }\n    .text_cell_render h4 {\n        font-weight: 100;\n        font-size: 14pt;\n        color:#d77c0c;\n        margin-bottom: 0.5em;\n        margin-top: 0.5em;\n        display: block;\n        white-space: nowrap;\n    }\n    h5 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n    }\n    .text_cell_render h5 {\n        font-weight: 200;\n        font-style: normal;\n        color: #1d3b84;\n        font-size: 16pt;\n        margin-bottom: 0em;\n        margin-top: 0.5em;\n        display: block;\n        white-space: nowrap;\n    }\n    div.text_cell_render{\n        font-family: 'Fira sans', verdana,arial,sans-serif;\n        line-height: 125%;\n        font-size: 115%;\n        text-align:justify;\n        text-justify:inter-word;\n    }\n    div.output_wrapper{\n        margin-top:0.2em;\n        margin-bottom:0.2em;\n    }\n\n    code{\n      font-size: 70%;\n    }\n    .rendered_html code{\n    background-color: transparent;\n    }\n    ul{\n        margin: 2em;\n    }\n    ul li{\n        padding-left: 0.5em; \n        margin-bottom: 0.5em; \n        margin-top: 0.5em; \n    }\n    ul li li{\n        padding-left: 0.2em; \n        margin-bottom: 0.2em; \n        margin-top: 0.2em; \n    }\n    ol{\n        margin: 2em;\n    }\n    ol li{\n        padding-left: 0.5em; \n        margin-bottom: 0.5em; \n        margin-top: 0.5em; \n    }\n    ul li{\n        padding-left: 0.5em; \n        margin-bottom: 0.5em; \n        margin-top: 0.2em; \n    }\n    a:link{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:visited{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:hover{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:focus{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:active{\n       font-weight: bold;\n       color:#447adb;\n    }\n    .rendered_html :link {\n       text-decoration: underline; \n    }\n    .rendered_html :hover {\n       text-decoration: none; \n    }\n    .rendered_html :visited {\n      text-decoration: none;\n    }\n    .rendered_html :focus {\n      text-decoration: none;\n    }\n    .rendered_html :active {\n      text-decoration: none;\n    }\n    .warning{\n        color: rgb( 240, 20, 20 )\n    } \n    hr {\n      color: #f3f3f3;\n      background-color: #f3f3f3;\n      height: 1px;\n    }\n    blockquote{\n      display:block;\n      background: #fcfcfc;\n      border-left: 5px solid #c76c0c;\n      font-family: 'Open sans',verdana,arial,sans-serif;\n      width:680px;\n      padding: 10px 10px 10px 10px;\n      text-align:justify;\n      text-justify:inter-word;\n      }\n      blockquote p {\n        margin-bottom: 0;\n        line-height: 125%;\n        font-size: 100%;\n      }\n</style>\n\n\n\n\n\n\n```python\nos.chdir(path)\n\n# 1. magic for inline plot\n# 2. magic to print version\n# 3. magic so that the notebook will reload external python modules\n# 4. magic to enable retina (high resolution) plots\n# https://gist.github.com/minrk/3301035\n%matplotlib inline\n%load_ext watermark\n%load_ext autoreload\n%autoreload 2\n%config InlineBackend.figure_format='retina'\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import precision_recall_curve, roc_curve\nfrom sklearn.metrics import precision_score, recall_score, f1_score\n\n%watermark -a 'Ethen' -d -t -v -p numpy,pandas,sklearn,matplotlib\n```\n\n    Ethen 2019-12-16 11:30:05 \n    \n    CPython 3.6.4\n    IPython 7.9.0\n    \n    numpy 1.16.5\n    pandas 0.25.0\n    sklearn 0.21.2\n    matplotlib 3.1.1\n\n\n# Evaluating Imbalanced Datasets\n\nThis documentation illustrates the trade off between True Positive Rate and False Positive Rate using ROC and Precision/Recall (PR) curves. In the end, we will take a look at why, for binary classification problem, apart from solely using the popular evaluation metric ROC curve we should also look at other evaluation metric such as precision and recall especially when working with highly imbalanced dataset.\n\n## Dataset\n\nThe dataset we'll be using today can be downloaded from the [Kaggle website](https://www.kaggle.com/mlg-ulb/creditcardfraud).\n\n\n```python\nfilepath = os.path.join('data', 'creditcard.csv')\ndf = pd.read_csv(filepath)\nprint('dimension: ', df.shape)\ndf.head()\n```\n\n    dimension:  (284807, 31)\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Time</th>\n      <th>V1</th>\n      <th>V2</th>\n      <th>V3</th>\n      <th>V4</th>\n      <th>V5</th>\n      <th>V6</th>\n      <th>V7</th>\n      <th>V8</th>\n      <th>V9</th>\n      <th>...</th>\n      <th>V21</th>\n      <th>V22</th>\n      <th>V23</th>\n      <th>V24</th>\n      <th>V25</th>\n      <th>V26</th>\n      <th>V27</th>\n      <th>V28</th>\n      <th>Amount</th>\n      <th>Class</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.0</td>\n      <td>-1.359807</td>\n      <td>-0.072781</td>\n      <td>2.536347</td>\n      <td>1.378155</td>\n      <td>-0.338321</td>\n      <td>0.462388</td>\n      <td>0.239599</td>\n      <td>0.098698</td>\n      <td>0.363787</td>\n      <td>...</td>\n      <td>-0.018307</td>\n      <td>0.277838</td>\n      <td>-0.110474</td>\n      <td>0.066928</td>\n      <td>0.128539</td>\n      <td>-0.189115</td>\n      <td>0.133558</td>\n      <td>-0.021053</td>\n      <td>149.62</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.0</td>\n      <td>1.191857</td>\n      <td>0.266151</td>\n      <td>0.166480</td>\n      <td>0.448154</td>\n      <td>0.060018</td>\n      <td>-0.082361</td>\n      <td>-0.078803</td>\n      <td>0.085102</td>\n      <td>-0.255425</td>\n      <td>...</td>\n      <td>-0.225775</td>\n      <td>-0.638672</td>\n      <td>0.101288</td>\n      <td>-0.339846</td>\n      <td>0.167170</td>\n      <td>0.125895</td>\n      <td>-0.008983</td>\n      <td>0.014724</td>\n      <td>2.69</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1.0</td>\n      <td>-1.358354</td>\n      <td>-1.340163</td>\n      <td>1.773209</td>\n      <td>0.379780</td>\n      <td>-0.503198</td>\n      <td>1.800499</td>\n      <td>0.791461</td>\n      <td>0.247676</td>\n      <td>-1.514654</td>\n      <td>...</td>\n      <td>0.247998</td>\n      <td>0.771679</td>\n      <td>0.909412</td>\n      <td>-0.689281</td>\n      <td>-0.327642</td>\n      <td>-0.139097</td>\n      <td>-0.055353</td>\n      <td>-0.059752</td>\n      <td>378.66</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1.0</td>\n      <td>-0.966272</td>\n      <td>-0.185226</td>\n      <td>1.792993</td>\n      <td>-0.863291</td>\n      <td>-0.010309</td>\n      <td>1.247203</td>\n      <td>0.237609</td>\n      <td>0.377436</td>\n      <td>-1.387024</td>\n      <td>...</td>\n      <td>-0.108300</td>\n      <td>0.005274</td>\n      <td>-0.190321</td>\n      <td>-1.175575</td>\n      <td>0.647376</td>\n      <td>-0.221929</td>\n      <td>0.062723</td>\n      <td>0.061458</td>\n      <td>123.50</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>2.0</td>\n      <td>-1.158233</td>\n      <td>0.877737</td>\n      <td>1.548718</td>\n      <td>0.403034</td>\n      <td>-0.407193</td>\n      <td>0.095921</td>\n      <td>0.592941</td>\n      <td>-0.270533</td>\n      <td>0.817739</td>\n      <td>...</td>\n      <td>-0.009431</td>\n      <td>0.798278</td>\n      <td>-0.137458</td>\n      <td>0.141267</td>\n      <td>-0.206010</td>\n      <td>0.502292</td>\n      <td>0.219422</td>\n      <td>0.215153</td>\n      <td>69.99</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 31 columns</p>\n</div>\n\n\n\nA brief description of the dataset based on the data overview section from the download source.\n\n> The datasets contains transactions made by credit cards in September 2013 by european cardholders. This dataset presents transactions that occurred in two days, where we have 492 frauds out of 284,807 transactions.\n> Unfortunately, due to confidentiality issues, we cannot provide the original features and more background information about the data. Features V1, V2, ... V28 are the principal components obtained with PCA, the only features which have not been transformed with PCA are 'Time' and 'Amount'. Feature 'Time' contains the seconds elapsed between each transaction and the first transaction in the dataset. The feature 'Amount' is the transaction amount. Feature 'Class' is the response variable and it takes value 1 in case of fraud and 0 otherwise.\n\nThe only feature-engineering that we'll be doing for now is to convert the feature \"Time\" (seconds from which the very first data observation took place) to hours of a day. While we're at it, let's take a look at a breakdown of our legit vs fraud transactions via a pivot table and a plot of fraud transactions' count over time for a quick exploratory data analysis.\n\n\n```python\ndf['hour'] = np.ceil(df['Time'].values / 3600) % 24\nfraud_over_hour = df.pivot_table(values='Amount', index='hour', columns='Class', aggfunc='count')\nfraud_over_hour\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Class</th>\n      <th>0</th>\n      <th>1</th>\n    </tr>\n    <tr>\n      <th>hour</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0.0</th>\n      <td>10919</td>\n      <td>21</td>\n    </tr>\n    <tr>\n      <th>1.0</th>\n      <td>7687</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>2.0</th>\n      <td>4212</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>3.0</th>\n      <td>3269</td>\n      <td>57</td>\n    </tr>\n    <tr>\n      <th>4.0</th>\n      <td>3476</td>\n      <td>17</td>\n    </tr>\n    <tr>\n      <th>5.0</th>\n      <td>2185</td>\n      <td>23</td>\n    </tr>\n    <tr>\n      <th>6.0</th>\n      <td>2979</td>\n      <td>11</td>\n    </tr>\n    <tr>\n      <th>7.0</th>\n      <td>4093</td>\n      <td>9</td>\n    </tr>\n    <tr>\n      <th>8.0</th>\n      <td>7219</td>\n      <td>23</td>\n    </tr>\n    <tr>\n      <th>9.0</th>\n      <td>10266</td>\n      <td>9</td>\n    </tr>\n    <tr>\n      <th>10.0</th>\n      <td>15824</td>\n      <td>16</td>\n    </tr>\n    <tr>\n      <th>11.0</th>\n      <td>16593</td>\n      <td>8</td>\n    </tr>\n    <tr>\n      <th>12.0</th>\n      <td>16804</td>\n      <td>53</td>\n    </tr>\n    <tr>\n      <th>13.0</th>\n      <td>15400</td>\n      <td>17</td>\n    </tr>\n    <tr>\n      <th>14.0</th>\n      <td>15350</td>\n      <td>17</td>\n    </tr>\n    <tr>\n      <th>15.0</th>\n      <td>16545</td>\n      <td>23</td>\n    </tr>\n    <tr>\n      <th>16.0</th>\n      <td>16434</td>\n      <td>26</td>\n    </tr>\n    <tr>\n      <th>17.0</th>\n      <td>16435</td>\n      <td>22</td>\n    </tr>\n    <tr>\n      <th>18.0</th>\n      <td>16135</td>\n      <td>29</td>\n    </tr>\n    <tr>\n      <th>19.0</th>\n      <td>17003</td>\n      <td>33</td>\n    </tr>\n    <tr>\n      <th>20.0</th>\n      <td>15632</td>\n      <td>19</td>\n    </tr>\n    <tr>\n      <th>21.0</th>\n      <td>16739</td>\n      <td>18</td>\n    </tr>\n    <tr>\n      <th>22.0</th>\n      <td>17692</td>\n      <td>16</td>\n    </tr>\n    <tr>\n      <th>23.0</th>\n      <td>15424</td>\n      <td>9</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nplt.rcParams['font.size'] = 12\nplt.rcParams['figure.figsize'] = 8, 6\n\n\nplt.plot(fraud_over_hour[1])\nplt.title('Fraudulent Transaction over Hour')\nplt.ylabel('Fraudulent Count')\nplt.xlabel('Hour')\nplt.show()\n```\n\n\n```python\n# prepare the dataset for modeling;\n# extract the features and labels, perform a quick train/test split\nlabel = df['Class']\npca_cols = [col for col in df.columns if col.startswith('V')]\ninput_cols = ['hour', 'Amount'] + pca_cols\ndf = df[input_cols]\n\ndf_train, df_test, y_train, y_test = train_test_split(\n    df, label, stratify=label, test_size=0.35, random_state=1)\n\nprint('training data dimension:', df_train.shape)\ndf_train.head()\n```\n\n    training data dimension: (185124, 30)\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>hour</th>\n      <th>Amount</th>\n      <th>V1</th>\n      <th>V2</th>\n      <th>V3</th>\n      <th>V4</th>\n      <th>V5</th>\n      <th>V6</th>\n      <th>V7</th>\n      <th>V8</th>\n      <th>...</th>\n      <th>V19</th>\n      <th>V20</th>\n      <th>V21</th>\n      <th>V22</th>\n      <th>V23</th>\n      <th>V24</th>\n      <th>V25</th>\n      <th>V26</th>\n      <th>V27</th>\n      <th>V28</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>183716</th>\n      <td>11.0</td>\n      <td>0.76</td>\n      <td>2.089242</td>\n      <td>0.629632</td>\n      <td>-3.364200</td>\n      <td>0.489395</td>\n      <td>1.553483</td>\n      <td>-0.986382</td>\n      <td>0.698731</td>\n      <td>-0.284807</td>\n      <td>...</td>\n      <td>0.084549</td>\n      <td>-0.107484</td>\n      <td>-0.041904</td>\n      <td>0.058986</td>\n      <td>-0.103786</td>\n      <td>0.050964</td>\n      <td>0.416364</td>\n      <td>0.694420</td>\n      <td>-0.082845</td>\n      <td>-0.028126</td>\n    </tr>\n    <tr>\n      <th>145898</th>\n      <td>1.0</td>\n      <td>0.49</td>\n      <td>-0.914450</td>\n      <td>2.361973</td>\n      <td>0.335526</td>\n      <td>4.114377</td>\n      <td>0.557196</td>\n      <td>0.874183</td>\n      <td>0.332492</td>\n      <td>0.540016</td>\n      <td>...</td>\n      <td>1.614699</td>\n      <td>0.352808</td>\n      <td>-0.159933</td>\n      <td>-0.261357</td>\n      <td>0.186308</td>\n      <td>0.718244</td>\n      <td>-0.911284</td>\n      <td>-0.093219</td>\n      <td>-0.282263</td>\n      <td>-0.229368</td>\n    </tr>\n    <tr>\n      <th>247003</th>\n      <td>19.0</td>\n      <td>2.69</td>\n      <td>2.070918</td>\n      <td>-0.062049</td>\n      <td>-1.128898</td>\n      <td>0.383220</td>\n      <td>-0.079241</td>\n      <td>-1.130912</td>\n      <td>0.177956</td>\n      <td>-0.321792</td>\n      <td>...</td>\n      <td>0.201919</td>\n      <td>-0.222333</td>\n      <td>-0.299237</td>\n      <td>-0.732516</td>\n      <td>0.322038</td>\n      <td>-0.112259</td>\n      <td>-0.281414</td>\n      <td>0.205225</td>\n      <td>-0.071557</td>\n      <td>-0.061429</td>\n    </tr>\n    <tr>\n      <th>56024</th>\n      <td>14.0</td>\n      <td>159.95</td>\n      <td>0.929003</td>\n      <td>-0.262584</td>\n      <td>-0.026089</td>\n      <td>0.596927</td>\n      <td>-0.469012</td>\n      <td>-1.022218</td>\n      <td>0.463968</td>\n      <td>-0.176288</td>\n      <td>...</td>\n      <td>0.278433</td>\n      <td>0.152181</td>\n      <td>-0.236715</td>\n      <td>-1.149710</td>\n      <td>0.035834</td>\n      <td>0.504788</td>\n      <td>0.139781</td>\n      <td>0.095334</td>\n      <td>-0.102652</td>\n      <td>0.025986</td>\n    </tr>\n    <tr>\n      <th>217153</th>\n      <td>16.0</td>\n      <td>44.22</td>\n      <td>1.831384</td>\n      <td>-0.814800</td>\n      <td>-0.727692</td>\n      <td>-0.075094</td>\n      <td>0.028202</td>\n      <td>1.380668</td>\n      <td>-0.941283</td>\n      <td>0.502667</td>\n      <td>...</td>\n      <td>-1.051171</td>\n      <td>-0.240155</td>\n      <td>0.242974</td>\n      <td>0.905053</td>\n      <td>0.189693</td>\n      <td>-0.540499</td>\n      <td>-0.358400</td>\n      <td>0.202675</td>\n      <td>0.048368</td>\n      <td>-0.044683</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 30 columns</p>\n</div>\n\n\n\n\n```python\n# we'll be using linear models later, hence\n# we standardize our features to ensure they are\n# all at the same scale\nstandardize = StandardScaler()\nX_train = standardize.fit_transform(df_train)\nX_test = standardize.transform(df_test)\n\nlabel_distribution = np.bincount(label) / label.size\nprint('labels distribution:', label_distribution)\nprint('Fraud is {}% of our data'.format(label_distribution[1] * 100))\n```\n\n    labels distribution: [0.99827251 0.00172749]\n    Fraud is 0.1727485630620034% of our data\n\n\n## Class Weighting\n\nWith scikit-learn, we can give higher weights to the minority class (the model will be penalized more when misclassifying a minority class) by modifying the `class_weight` argument during model initialization. Let's see what affect will this have with our model. The following code chunk manually selects a range of weights to boost the minority class and tracks various metrics to see the model's performance across different class weighting values.\n\nNote that the following section assumes knowledge of model performance metric such as precision, recall and AUC. The following link contains resources into those concepts if needed. [Notebook: AUC (Area under the ROC curve and precision/recall curve) from scratch](http://nbviewer.jupyter.org/github/ethen8181/machine-learning/blob/master/model_selection/auc/auc.ipynb)\n\n\n```python\nfig = plt.figure(figsize=(15, 8))\nax1 = fig.add_subplot(1, 2, 1)\nax1.set_xlim([-0.05, 1.05])\nax1.set_ylim([-0.05, 1.05])\nax1.set_xlabel('Recall')\nax1.set_ylabel('Precision')\nax1.set_title('PR Curve')\n\nax2 = fig.add_subplot(1, 2, 2)\nax2.set_xlim([-0.05, 1.05])\nax2.set_ylim([-0.05, 1.05])\nax2.set_xlabel('False Positive Rate')\nax2.set_ylabel('True Positive Rate')\nax2.set_title('ROC Curve')\n\nf1_scores = []\nrecall_scores = []\nprecision_scores = []\npos_weights = [1, 10, 25, 50, 100, 10000]\nfor pos_weight in pos_weights:\n    lr_model = LogisticRegression(class_weight={0: 1, 1: pos_weight})\n    lr_model.fit(X_train, y_train)\n\n    # plot the precision-recall curve and AUC curve\n    pred_prob = lr_model.predict_proba(X_test)[:, 1]\n    precision, recall, _ = precision_recall_curve(y_test, pred_prob)\n    tpr, fpr, _ = roc_curve(y_test, pred_prob)\n\n    ax1.plot(recall, precision, label=pos_weight)\n    ax2.plot(tpr, fpr, label=pos_weight)\n\n    # track the precision, recall and f1 score\n    pred = lr_model.predict(X_test)\n    f1_test = f1_score(y_test, pred)\n    recall_test = recall_score(y_test, pred)\n    precision_test = precision_score(y_test, pred)\n    f1_scores.append(f1_test)\n    recall_scores.append(recall_test)\n    precision_scores.append(precision_test)\n\nax1.legend(loc='lower left')    \nax2.legend(loc='lower right')\n\nplt.show()\n```\n\nA good classifier would have a PR (Precision/Recall) curve closer to the upper-right corner and a ROC curve to the upper-left corner. Based on the plot above, we can see that while both curves uses the same underlying data, i.e. the real class labels and the predicted probability, the two charts can tell different stories, with some weights seem to perform better based on the precision/recall curve's chart.\n\nTo be explicit, different settings of the `class_weight` argument all seem to perform pretty well for ROC curve, but some poorly for PR curve. This is due to the fact that for ROC curve, one of the axis shows the false positive rate (number of false positives / total number of negatives), and this ratio won't change much when the total number of negatives is extremely large. Whereas for PR curve, one of the axis, precision (number of true positives / total number of predicted positives), is less affected by this.\n\nAnother way to visualize the model's performance metric is to use a bar-plot to visualize the precision/recall/f1 score at different class weighting values.\n\n\n```python\ndef score_barplot(precision_scores, recall_scores, f1_scores, pos_weights, figsize=(8, 6)):\n    \"\"\"Visualize precision/recall/f1 score at different class weighting values.\"\"\"\n    width = 0.3\n    ind = np.arange(len(precision_scores))      \n    fig = plt.figure(figsize=figsize)\n    ax = fig.add_subplot(111)\n    b1 = ax.bar(ind, precision_scores, width, color='lightskyblue')\n    b2 = ax.bar(ind + width, recall_scores, width, color='lightcoral')\n    b3 = ax.bar(ind + (2 * width), f1_scores, width, color='gold')\n\n    ax.set_xticks(ind + width)\n    ax.set_xticklabels(pos_weights)\n    ax.set_ylabel('score')\n    ax.set_xlabel('positive weights')\n    ax.set_ylim(0, 1.3)\n    ax.legend(handles=[b1, b2, b3], labels=['precision', 'recall', 'f1'])\n    plt.tight_layout()\n    plt.show()\n\n\nscore_barplot(precision_scores, recall_scores, f1_scores, pos_weights)\n```\n\nJudging from the plot above, the can see that when the weight's value is set at 10, we seem to have strike a good balance between precision and recall (this setting has the highest f1 score, we'll have a deeper discussion on f1 score in the next section), where our model can detect 80% of the fraudulent transaction, while not annoying a bunch of customers with false positives. Another observation is that if we were to set the class weighting value to 10,000 we would be able to increase our recall score at the expense of more mis-classified legit cases (as depicted by the low precision score).\n\n\n```python\n# this code chunk shows the same idea applies when using tree-based models\nf1_scores = []\nrecall_scores = []\nprecision_scores = []\npos_weights = [1, 10, 100, 10000]\nfor pos_weight in pos_weights:\n    rf_model = RandomForestClassifier(n_estimators=50, max_depth=6, n_jobs=-1,\n                                      class_weight={0: 1, 1: pos_weight})\n    rf_model.fit(df_train, y_train)\n\n    # track the precision, recall and f1 score\n    pred = rf_model.predict(df_test)\n    f1_test = f1_score(y_test, pred)\n    recall_test = recall_score(y_test, pred)\n    precision_test = precision_score(y_test, pred)\n    f1_scores.append(f1_test)\n    recall_scores.append(recall_test)\n    precision_scores.append(precision_test)\n\nscore_barplot(precision_scores, recall_scores, f1_scores, pos_weights)\n```\n\n## F1 Score\n\nThe formula for F1 score is:\n\n\\begin{align}\nF1 &= 2 * \\frac{\\text{precision} * \\text{recall}}{\\text{precision} + \\text{recall}}\n\\end{align}\n\nF1 score can be interpreted as a weighted average or harmonic mean of precision and recall, where the relative contribution of precision and recall to the F1 score are equal. F1 score reaches its best value at 1 and worst score at 0.\n\nWhen we create a classifier, often times we need to make a compromise between the recall and precision, it is kind of hard to compare a model with high recall and low precision versus a model with high precision but low recall. F1 score merge these two metrics into a single measure that we can use to compare two models. This is not to say that a model with higher F1 score is always better as it depends on the use case, more on this in the conclusion section.\n\nTo understand the rationale behind harmonic means, let's digress from machine learning evaluation metrics and take a look at a canonical example of using harmonic means. Consider a trip to the grocery store & back:\n\n- On the way there we drove 30 mph the entire way.\n- On the way back traffic was crawling, so we instead drove 10 mph the entire way.\n- We took the same route and covered the same amount of ground (5 miles) each way.\n\nWhat was our average speed across this entire trip's duration? When prompted to calculate the average of something, we might naively turn to arithmetic mean to 30 mph and 10 mph and proudly declare that the average speed for the whole trip was 20 mph. But if we step back and think about it for a moment, we'll realize that because we traveled faster on our way there, we covered the 5 miles quicker & spent less time overall traveling at that speed, thus our average speed across our entire trip should be closer to 10 mph because we spent longer traveling at that speed. In order to calculate the arithmetic mean correctly here, we have to first calculate the amount of time spent traveling at each rate, then weight our mean calculation accordingly.\n\n- Trip There: (at 30 mph)\n    - 30 miles per 60 minutes = 1 mile every 2 minutes = 1/2 mile every minute\n    - 5 miles at 1/2 mile per minute = 5 / 1/2 = 10 minutes\n    - Trip There time = 10 minutes\n- Trip Back: (at 10 mph)\n    - 10 miles per 60 minutes = 1 mile every 6 minutes = 1/6 miles every minute\n    - 5 miles at 1/6 mile per minute = 5 / 1/6 = 30 minutes\n    - Trip Back time = 30 minutes\n- Total trip time = 10 + 30 = 40 minutes\n    - Trip there / total trip = 10 / 40 minutes = .25\n    - Trip back / total trip = 30 / 40 minutes = .75\n- Weighted Arithmetic Mean = (30 mph x .25) + (10 mph x .75) = 7.5 + 7.5 = 15 \n\nWe now get an average speed of 15 mph, which matches the intuition that the number should be lower than our unweighted arithmetic mean of 20 mph. Now let's look at the same problem from a harmonic mean perspective. The harmonic mean can be described in words as: the reciprocal of the arithmetic mean of the reciprocals of the dataset. That's a lot of reciprocal flips there ..., the notation for the computation is:\n\n\\begin{align}\n\\text{Harmonic mean} &= \\big( \\frac{\\sum_{i=1}^n x_i^{-1}}{n} \\big)^{-1}\n\\end{align}\n\nNow back our original example, the harmonic mean of 30 mph and 10 mph:\n\n- Arithmetic mean of reciprocals = 1/30 + 1/10 = 4/30 / 2 = 4/60 = 1/15\n- Reciprocal of arithmetic mean = 1 / 1/15 = 15/1 = 15\n\nOur true average rate of travel, automagically adjusted for time spent traveling in each direction = 15 mph! In this example, using harmonic mean helps us find relationship with datasets of rates/ratios/fractions over different length/periods. By using reciprocals, it already accounts for the proportion of time that was implicit in the rates.\n\nWith this knowledge in mind, let's turn our heads back to F1 score's calculation. Precision and recall both have true positives in the numerator, but they have different denominators. In order for an average to be valid, we need the values to be in the same scaled units. In our traveling distance example miles per hour need to be compared over the same number of hours. Thus, to take the average of precision and recall really only makes sense to average their reciprocals (adjusts for scale), thus the harmonic mean.\n\nIf the business case warrants it, we may want to put more weight on recall than precision or vice-versa. In that case a more general version of the F score called F beta score could be useful. \n\n\\begin{align}\nF_{\\beta}&= (1+\\beta^2) * \\frac{\\text{precision} * \\text{recall}}{\\beta^2*\\text{precision} + \\text{recall}}\n\\end{align}\n\nWith $\\beta>1$ you focus more on recall, with $0<\\beta<1$ you put more weight on precision.\nFor example, commonly used F2 score puts 2x more weight on recall than precision. You can find more information on the subject here [Blog: 24 Evaluation Metrics for Binary Classification (And When to Use Them)](https://neptune.ml/blog/evaluation-metrics-binary-classification) \n\n## Conclusion\n\nTo sum it up, when using model-based metrics to evaluate a imbalanced classification problem, it is often times recommended to look at the precision and recall score to fully evaluate the overall effectiveness of a model.\n\nA model with high recall but low precision score returns many positive results, but most of its predicted labels are incorrect when compared to the ground truth. On the other hand, a model with high precision but low recall score returns very few results, but most of its predicted labels are correct when compared to the ground-truth. An ideal scenario would be a model with high precision and high recall, meaning it will return many results, with all results labeled correctly. Unfortunately, in most cases, precision and recall are often in tension. That is, improving precision typically reduces recall and vice versa.\n\nSo how do we know if we should sacrifice our precision for more recall, i.e. catching fraud? That is business decisions come into play. If the cost of missing a fraud highly outweighs the cost of canceling a bunch of legit customer transactions, i.e. false positives, then perhaps we can choose a weight that gives us a higher recall rate. Or maybe catching 80% of fraud is good enough for the business, in that case, we can also minimize the \"user friction\" by keeping our precision high.\n\n# Reference\n\n- [Notes: The Harmonic Mean](http://jwilson.coe.uga.edu/EMT725/HM/HM.html)\n- [Blog: \nClassification: Precision and Recall](https://developers.google.com/machine-learning/crash-course/classification/precision-and-recall)\n- [Blog: 24 Evaluation Metrics for Binary Classification (And When to Use Them)](https://neptune.ml/blog/evaluation-metrics-binary-classification)\n- [Blog: On Average, You\u2019re Using the Wrong Average: Geometric & Harmonic Means in Data Analysis](https://towardsdatascience.com/on-average-youre-using-the-wrong-average-geometric-harmonic-means-in-data-analysis-2a703e21ea0)\n- [Kaggle Kernel: Imbalanced data & why you should NOT use ROC curve](https://www.kaggle.com/lct14558/imbalanced-data-why-you-should-not-use-roc-curve)\n- [Stackoverflow: what is f1-score and what its value indicates?](https://stackoverflow.com/questions/45963174/what-is-f1-score-and-what-its-value-indicates)\n- [Stackoverflow: Why is the F-Measure a harmonic mean and not an arithmetic mean of the Precision and Recall measures?](https://stackoverflow.com/questions/26355942/why-is-the-f-measure-a-harmonic-mean-and-not-an-arithmetic-mean-of-the-precision)\n", "meta": {"hexsha": "e35b508b4084129e2582f84544f233ddb5bd07f5", "size": 298589, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "model_selection/imbalanced/imbalanced_metrics.ipynb", "max_stars_repo_name": "certara-ShengnanHuang/machine-learning", "max_stars_repo_head_hexsha": "d21dfbeabf2876ffe49fcef444ca4516c4d36df0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2104, "max_stars_repo_stars_event_min_datetime": "2016-04-15T13:35:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T10:39:51.000Z", "max_issues_repo_path": "model_selection/imbalanced/imbalanced_metrics.ipynb", "max_issues_repo_name": "certara-ShengnanHuang/machine-learning", "max_issues_repo_head_hexsha": "d21dfbeabf2876ffe49fcef444ca4516c4d36df0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-04-07T14:25:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-18T03:16:15.000Z", "max_forks_repo_path": "model_selection/imbalanced/imbalanced_metrics.ipynb", "max_forks_repo_name": "certara-ShengnanHuang/machine-learning", "max_forks_repo_head_hexsha": "d21dfbeabf2876ffe49fcef444ca4516c4d36df0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 539, "max_forks_repo_forks_event_min_datetime": "2015-12-10T04:23:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:15:28.000Z", "avg_line_length": 210.5705218618, "max_line_length": 108848, "alphanum_fraction": 0.877155555, "converted": true, "num_tokens": 9981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262438, "lm_q2_score": 0.09401018596240077, "lm_q1q2_score": 0.044071093986563566}}
{"text": "\n\n# Course title\n# Lecture XX - Lecture title\n\n**Aur\u00e9lien Nioche**\n\nAalto University\n\n## Preamble\n\n<!--\n\n-->\n\n<div class=\"alert alert-block alert-success\">\n<h2>&nbsp;Learning objectives</h2>\n    <br>Learn to:\n    <ul>\n        <li>Learn (see <a href=\"#1.-Part-1\" class=\"alert-link\">Section 1</a>);\n    </ul>\n</div>\n\n## Course Overview\n\n\n&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"font-size:2rem; font-weight:bold\"><a href=\"#1.-Part-1\">1. Section 1</a></span>\n\n<a href=\"#1.1-Subsection-1.1\">1.1 Subsection 1.1</a>\n\n<span style=\"font-size:2rem; font-weight:bold\"><a href=\"#Conclusive-Remarks-and-a-Few-Take-Aways\">Conclusive Remarks and a Few Take Aways</a></span>\n\n<span style=\"font-size:2rem; font-weight:bold\"><a href=\"#Additional-material\">Additional material</a></span>\n\n## 1. Section 1\n<a href=\"#Course-Overview\">Course Overview</a>\n\n\n\n<div class=\"alert alert-block alert-success\">\n<h3>&nbsp;Section Goal</h3>\n<ul>\n    <li>How to XXX.\n    </ul>\n</div>\n\n&nbsp;<b>How to do it?</b>\n\nLet's take as example:\n<b><a href=\"https://en.wikipedia.org/wiki/Goal_orientation\">Goal orientation</a></b>\n\n\n```python\na = 1 + 2\nb = 3\na == b\n```\n\n\n\n\n    True\n\n\n\n\\begin{equation}\n\\forall i: \\sum_{i}^N x_i = x_1 + x_2 + \\cdots + x_n\n\\end{equation}\n\n*Note: For more info, see the <a href=\"#Additional-material\">supplementary section</a>.*\n\n---\n\nThis an another paragraph.\n\n<div class=\"alert alert-block alert-danger\">\n<h2>&nbsp;Warning</h2>\n    <br>You should look to the <a href=\"#Additional-material\" class=\"alert-link\">supplementary</a> for that.</div>\n\n## Conclusive Remarks and a Few Takeaways\n<a href=\"#Course-Overview\">Course Overview</a>\n\n<div class=\"alert alert-block alert-success\">\n<h2>&nbsp;Learning objectives</h2>\n    <br>Learn by a basic example the elementary rules of decision making modeling, including:\n    <ul>\n        <li>How to ... (see <a href=\"#1.-Section-1\" class=\"alert-link\">Section 1</a>)\n    </ul>\n</div>\n\n\n## Additional material\n<a href=\"#Course-Overview\">Course Overview</a>\n", "meta": {"hexsha": "11b37d629c02105a50c1c5b0673b4ec4f0768347", "size": 5226, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": ".template.ipynb", "max_stars_repo_name": "AurelienNioche/NormalizingFlowsTutorial", "max_stars_repo_head_hexsha": "a03d426218cca83b41307ad00d0e2178fb575bbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-10T14:13:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-10T14:13:17.000Z", "max_issues_repo_path": ".template.ipynb", "max_issues_repo_name": "AurelienNioche/NormalizingFlowsTutorial", "max_issues_repo_head_hexsha": "a03d426218cca83b41307ad00d0e2178fb575bbb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": ".template.ipynb", "max_forks_repo_name": "AurelienNioche/NormalizingFlowsTutorial", "max_forks_repo_head_hexsha": "a03d426218cca83b41307ad00d0e2178fb575bbb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0829493088, "max_line_length": 184, "alphanum_fraction": 0.5066972828, "converted": true, "num_tokens": 595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510528442897664, "lm_q2_score": 0.12765261868437058, "lm_q1q2_score": 0.04405359327917341}}
{"text": "## Jupyter Notebook\n\n> Notebook documents contains the inputs and outputs of a interactive session as well as additional text that accompanies the code but is not meant for execution. In this way, notebook files can serve as a complete computational record of a session, interleaving executable code with explanatory text, mathematics, and rich representations of resulting objects. These documents are internally JSON files and are saved with the .ipynb extension.\n\nRef : http://jupyter-notebook.readthedocs.io/en/latest/notebook.html#notebook-documents\n\n> The notebook consists of a sequence of cells. A cell is a multiline text input field, and its contents can be executed by using Shift-Enter, or by clicking either the \u201cPlay\u201d button the toolbar, or Cell | Run in the menu bar. The execution behavior of a cell is determined the cell\u2019s type. There are four types of cells: code cells, markdown cells, raw cells and heading cells. Every cell starts off being a code cell, but its type can be changed by using a drop-down on the toolbar (which will be \u201cCode\u201d, initially), or via keyboard shortcuts.\n\nRef : http://jupyter-notebook.readthedocs.io/en/latest/notebook.html#structure-of-a-notebook-document\n\n> When a cell is in edit mode, the Cell Mode Indicator will change to reflect the cell\u2019s state. This state is indicated by a small pencil icon on the top right of the interface. When the cell is in command mode, there is no icon in that location.\n\nThe user can enter the Edit mode of an executed cell by pressing `Enter` and escape the edit mode by pressing `Esc`\n\nRef : http://jupyter-notebook.readthedocs.io/en/latest/ui_components.html#edit-mode-and-notebook-editor\n\n## A Code cell\n\n> A code cell allows you to edit and write new code, with full syntax highlighting and tab completion. By default, the language associated to a code cell is Python. When a code cell is executed, code that it contains is sent to the kernel associated with the notebook. The results that are returned from this computation are then displayed in the notebook as the cell\u2019s output. The output is not limited to text, with many other possible forms of output are also possible, including matplotlib figures and HTML tables (as used, for example, in the pandas data analysis package). This is known as IPython\u2019s rich display capability.\n\nRef : http://jupyter-notebook.readthedocs.io/en/latest/notebook.html#code-cells\n\n\n```python\nfrom __future__ import print_function\n\nx = 4\nprint(x)\n```\n\n    4\n\n\n## A Markdown cell\n\n> You can document the computational process in a literate way, alternating descriptive text with code, using rich text. In IPython this is accomplished by marking up text with the Markdown language. The corresponding cells are called Markdown cells. The Markdown language provides a simple way to perform this text markup, that is, to specify which parts of the text should be emphasized (italics), bold, form lists, etc. \n\n> When a Markdown cell is executed, the Markdown code is converted into the corresponding formatted rich text. Markdown allows arbitrary HTML code for formatting.\n\n> Within Markdown cells, you can also include mathematics in a straightforward way, using standard LaTeX notation: ``$...$`` for inline mathematics and ``$$...$$`` for displayed mathematics. When the Markdown cell is executed, the LaTeX portions are automatically rendered in the HTML output as equations with high quality typography. This is made possible by MathJax, which supports a large subset of LaTeX functionality\n\n> Standard mathematics environments defined by LaTeX and AMS-LaTeX (the amsmath package) also work, such as ``\\begin{equation}...\\end{equation}``, and ``\\begin{align}...\\end{align}``. New LaTeX macros may be defined using standard methods, such as \\newcommand, by placing them anywhere between math delimiters in a Markdown cell. These definitions are then available throughout the rest of the IPython session.\n\nRef : http://jupyter-notebook.readthedocs.io/en/latest/notebook.html#markdown-cells\n\nLists can be rendered in Markdown, such as\n\n- list\n- of\n- items\n\nand math equations can be rendered, such as\n\n$\\alpha^2 + \\beta_2 = \\gamma_2$\n\n## Output Cell with Embedded plot\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\nplt.plot(range(-5, 5), range(10))\n```\n\n## Running Shell commands\n\n\n```python\n!ls ~\n```\n\n    \u001b[34mApplications\u001b[m\u001b[m       \u001b[34mLibrary\u001b[m\u001b[m            Untitled1.ipynb    \u001b[34mnltk_data\u001b[m\u001b[m\r\n    \u001b[34mApr_IITM_Python\u001b[m\u001b[m    \u001b[34mMovies\u001b[m\u001b[m             \u001b[34mVirtualBox VMs\u001b[m\u001b[m     rodeo.log\r\n    \u001b[34mClionProjects\u001b[m\u001b[m      \u001b[34mMusic\u001b[m\u001b[m              \u001b[34m__pycache__\u001b[m\u001b[m        \u001b[30m\u001b[43mscipy.in\u001b[m\u001b[m\r\n    \u001b[34mDesktop\u001b[m\u001b[m            \u001b[34mPictures\u001b[m\u001b[m           \u001b[34mdata_import_tool\u001b[m\u001b[m   v162 by months.png\r\n    \u001b[34mDocuments\u001b[m\u001b[m          \u001b[34mPublic\u001b[m\u001b[m             dtrace.txt\r\n    \u001b[34mDownloads\u001b[m\u001b[m          \u001b[34mPycharmProjects\u001b[m\u001b[m    \u001b[34menthought\u001b[m\u001b[m\r\n    \u001b[34mGithub\u001b[m\u001b[m             Untitled.ipynb     installers\r\n\n\n## Jupyter Magics\n\nA few commonly used Jupyter commands, referred to as line and cell magics, are\n\n- `%matplotlib inline`\n- `%pprint`\n- `%precision`\n- `%reset`\n- `%timeit`\n- `%%cython`, if the cython library is installed\n\n## Further reading\n\n- https://ipython.readthedocs.io/en/stable/\n- http://jupyter-notebook.readthedocs.io/en/latest/\n- https://ipython.readthedocs.io/en/stable/interactive/magics.html\n", "meta": {"hexsha": "b1bb1bd071dbe0b619c4cc7fa1fa1b812110adfb", "size": 19419, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "scientific_computing_101/jupyter_notebook.ipynb", "max_stars_repo_name": "rahulporuri/talks", "max_stars_repo_head_hexsha": "693e159b40c1cff9d798ca67838fa3f723915129", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-01T15:18:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-01T15:18:44.000Z", "max_issues_repo_path": "scientific_computing_101/jupyter_notebook.ipynb", "max_issues_repo_name": "rahulporuri/talks", "max_issues_repo_head_hexsha": "693e159b40c1cff9d798ca67838fa3f723915129", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-06-25T06:41:10.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-12T15:34:53.000Z", "max_forks_repo_path": "scientific_computing_101/jupyter_notebook.ipynb", "max_forks_repo_name": "rahulporuri/talks", "max_forks_repo_head_hexsha": "693e159b40c1cff9d798ca67838fa3f723915129", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 79.9135802469, "max_line_length": 10582, "alphanum_fraction": 0.8087440136, "converted": true, "num_tokens": 1309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814056194821861, "lm_q2_score": 0.15610489940847916, "lm_q1q2_score": 0.043928795922247424}}
{"text": "# Replication Baskaran & Hessami (2018)<a class=\"tocSkip\">\n\nThis notebook contains a replication of [Baskaran, T., & Hessami, Z. (2018) Does the Election of a Female Leader Clear the Way for More Women in Politics? *American Economic Journal: Economic Policy*, 10(3): 91-121](https://www.aeaweb.org/articles?id=10.1257/pol.20170045).\n\nFor this purpose, first, I present an executive summary on the article, including the research hypothesis, analyzed data and the used method. Nonetheless, I strongly recommend that one reads the original article prior to reading this notebook. Second, descriptive and graphical data analyses are presented. This is useful for understanding and making sense of the data that is used for the empirical analysis and serves as a preparation for the third part of this notebook: A replication of the key results of the paper. Besides the baseline results of the main model this includes econometric analyses regarding the internal validity of the used method as well as the robustness tests presented in the article. Subsequently, the fourth section of this notebook presents an investigation on the internal validity of the regression discontinuitiy design (henceforth RD design) which goes beyond what is presented in the article. Finally, section 5 concludes the results of this exercise.\n\nNaturally, throughout this replication I draw heavily from the original article. Unless stated otherwise, the reader should, therefore, assume that the ideas presented within this notebook are reproductions of the contents of Baskaran & Hessami (2018). \n\nOverall, the results presented by Baskeran & Hessami (2018) can successfully be replicated. Particularly, the baseline results of the main estimation model, the test results for internal validity of the econometric method, and the results for robustness tests yield the same results in this replication as in the article. \n\n\n<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#1.-Excecutive-summary-of-the-paper\" data-toc-modified-id=\"1.-Excecutive-summary-of-the-paper-1\">1. Excecutive summary of the paper</a></span></li><li><span><a href=\"#2.-Descriptive-and-Graphical-Analyses\" data-toc-modified-id=\"2.-Descriptive-and-Graphical-Analyses-2\">2. Descriptive and Graphical Analyses</a></span><ul class=\"toc-item\"><li><span><a href=\"#2.1.-Description-of-the-Dataset\" data-toc-modified-id=\"2.1.-Description-of-the-Dataset-2.1\">2.1. Description of the Dataset</a></span></li><li><span><a href=\"#2.2.-Discontinuity-in-Distribution-of-Observations\" data-toc-modified-id=\"2.2.-Discontinuity-in-Distribution-of-Observations-2.2\">2.2. Discontinuity in Distribution of Observations</a></span></li><li><span><a href=\"#2.3.-Discontinuity-at-the-Critical-Value-of-the-Margin-of-Victory\" data-toc-modified-id=\"2.3.-Discontinuity-at-the-Critical-Value-of-the-Margin-of-Victory-2.3\">2.3. Discontinuity at the Critical Value of the Margin of Victory</a></span></li></ul></li><li><span><a href=\"#3.-Replication-and-Critical-Review\" data-toc-modified-id=\"3.-Replication-and-Critical-Review-3\">3. Replication and Critical Review</a></span><ul class=\"toc-item\"><li><span><a href=\"#3.1-Graphical-Evidence:-RDD-Plot\" data-toc-modified-id=\"3.1-Graphical-Evidence:-RDD-Plot-3.1\">3.1 Graphical Evidence: RDD Plot</a></span></li><li><span><a href=\"#3.2-Main-Results\" data-toc-modified-id=\"3.2-Main-Results-3.2\">3.2 Main Results</a></span><ul class=\"toc-item\"><li><span><a href=\"#3.2.1-Regression-Results\" data-toc-modified-id=\"3.2.1-Regression-Results-3.2.1\">3.2.1 Regression Results</a></span></li><li><span><a href=\"#3.2.2-Robustness\" data-toc-modified-id=\"3.2.2-Robustness-3.2.2\">3.2.2 Robustness</a></span><ul class=\"toc-item\"><li><span><a href=\"#3.2.2.1-Placebo-Test\" data-toc-modified-id=\"3.2.2.1-Placebo-Test-3.2.2.1\">3.2.2.1 Placebo Test</a></span></li><li><span><a href=\"#3.2.2.2-Scaling-of-the-Outcome-Variable\" data-toc-modified-id=\"3.2.2.2-Scaling-of-the-Outcome-Variable-3.2.2.2\">3.2.2.2 Scaling of the Outcome Variable</a></span></li></ul></li></ul></li><li><span><a href=\"#3.3-Internal-Validity-of-the-RD-Design\" data-toc-modified-id=\"3.3-Internal-Validity-of-the-RD-Design-3.3\">3.3 Internal Validity of the RD Design</a></span><ul class=\"toc-item\"><li><span><a href=\"#3.3.1-Pretreatment-Municipality-Characteristics\" data-toc-modified-id=\"3.3.1-Pretreatment-Municipality-Characteristics-3.3.1\">3.3.1 Pretreatment Municipality Characteristics</a></span></li><li><span><a href=\"#3.3.2-Discontinuity-in-Density\" data-toc-modified-id=\"3.3.2-Discontinuity-in-Density-3.3.2\">3.3.2 Discontinuity in Density</a></span></li><li><span><a href=\"#3.3.3.-Confoundness-with-Mayor-Ideology\" data-toc-modified-id=\"3.3.3.-Confoundness-with-Mayor-Ideology-3.3.3\">3.3.3. Confoundness with Mayor Ideology</a></span></li></ul></li></ul></li><li><span><a href=\"#4.-Independent-Contribution:-On-Internal-Validity-of-the-RD-Design\" data-toc-modified-id=\"4.-Independent-Contribution:-On-Internal-Validity-of-the-RD-Design-4\">4. Independent Contribution: On Internal Validity of the RD Design</a></span></li><li><span><a href=\"#5.-Conclusions\" data-toc-modified-id=\"5.-Conclusions-5\">5. Conclusions</a></span></li><li><span><a href=\"#References\" data-toc-modified-id=\"References-6\">References</a></span></li></ul></div>\n\n## 1. Excecutive summary of the paper\n* **Theoretical Framework:** *Anti-female voter bias* results in underrepresentation of females in politics.\n\n\n* **Research Hypothesis:** Exposure to a female mayor deminishes *anti-female biases* of voters.\n\n**Figure 1: Causal Graph**\n\n\n* **Identification problems:**\n\n    * Other potential drivers of the underrepresentation of femeales in politics:\n        - Political parties influence election outcomes. Thus, underrepresentation might be caused by *anti-female party biases*.\n        - Parties might *anticipate anti-female voter bias* and, therefore, are less willing to field female candidates in competitive races.\n        - Women who expect discrimination might be reluctand to run for election/ pursue a career in politics in the first place. \n\n    * Isolating *anti-female voter bias*: Rule out alternative explanations:\n        - (a) Initial rank of female candidates does not impact their rank advancements.\n        - (b) Characteristics of women on party's list chage only little in case there is a female mayor in office.\n        - (c) Number of female candidates on list remains unchanged.\n        - (a), (b), and (c) indicate little *anti-female party bias*.\n        \n\n* **Data:**\n\n    * Data on local council election in the German state of Hesse:\n        - Open-list electoral system (parties specify order of candidates; voters can distribute preferential votes to individual candidates).\n        - Includes gender, list ranks, personal characteristics among other information for ~109.017 candidates who competed in 2001, 2006, 2011, or 2016 elections.\n    \n    * Data on mayor elections for all 426 municipalities in Hesse\n        - Including the elected mayor's gender and the margin the election was won by.\n        - Including characteristics of each municipality.\n    \n    \n* **Method:**\n\n    * Authors use a RD design to study the causal effects of female mayors on subsequent council election results.\n    \n    * The discontinuity is provided by close mixed-gender mayor elections. Authors compare \"candidate's rank improvement of women in municipalities where a woman barely won against a man with outcomes in municipalities where a man barely won against a woman\".\n    \n    * Estimated model equation: \n     \\begin{align} \n     rank \\, improvement_{k, i, t} = \\alpha + \\beta female \\, mayor_{i, t} + f(vote \\, margin)_{i, t} + female \\, mayor_{i, t} \\times  g(vote \\, margin)_{i, t} + \\epsilon_{k, i, t} \\tag{1}\n     \\end{align}\n     \n     Where \n         - $rank \\, improvement_{k, i, t}$ is the normalized rank improvement of candidate $k$ in municipality $i$ and local election year $t$.\n         - $vote \\, margin_{i, t}$ is the margin of victory of the female candidate in the preceeding mayoral election (negative values, thus, denote a loss of the female candidate).\n         - $female \\, mayor_{i, t}$ is a dummy that takes value 1 if a female candiate has won the mayoral election preceeding the council election $(female \\, mayor_{i, t} = 1 \\Leftrightarrow vote \\, margin_{i, t} > 0)$.\n\n\n\n\n\n* **Results:**\n    * A female candidate winning a close mixed-gender mayoral election causes:\n        \n        - Voters to give preferential votes to female council candidates.\n    \n        - A 4 percentage points higher share of female council members.\n        \n        - Positive spillover effects on female council candidates in neighboring municipalities.\n       \n\n\n```python\n# Import packages and auxiliary functions\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport statsmodels.api as sm\n\nfrom scipy.stats import ttest_ind\n\nfrom auxiliary.localreg import *\nfrom auxiliary.auxiliary_functions import * \nfrom auxiliary.plots_and_figures import *\n\n# General notebooks settings\npd.options.display.max_columns = None\n\n# Settings for matlibplot package\nplt.rc('axes', axisbelow=True)\n\n# Import auxiliary datasets\ndf_mayor_election_data = pd.read_stata('data/mayor_election_data.dta')\ndf_municipality_characteristics = pd.read_stata('data/municipality_characteristics_data.dta')\ndf_mayor_election_data = pd.read_stata('data/mayor_election_data.dta')\ndf_placebo = pd.read_stata('data/dataset_with_lagged_rank_improvments.dta')\n\n# Import main dataset and print a few randomly seleted rows for illustration\ndf_main_dataset = pd.read_stata('data/main_dataset.dta')\ndf_main_dataset.sample(5)\n\n\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>gkz</th>\n      <th>jahr</th>\n      <th>gkz_jahr</th>\n      <th>rdd_sample</th>\n      <th>female</th>\n      <th>elected</th>\n      <th>gewinn_norm</th>\n      <th>gewinn</th>\n      <th>gewinn_dummy</th>\n      <th>listenplatz_norm</th>\n      <th>joint_party</th>\n      <th>age</th>\n      <th>non_university_phd</th>\n      <th>university</th>\n      <th>phd</th>\n      <th>architect</th>\n      <th>businessmanwoman</th>\n      <th>engineer</th>\n      <th>lawyer</th>\n      <th>civil_administration</th>\n      <th>teacher</th>\n      <th>employed</th>\n      <th>selfemployed</th>\n      <th>student</th>\n      <th>retired</th>\n      <th>housewifehusband</th>\n      <th>incumbent_council</th>\n      <th>wahlbet</th>\n      <th>party</th>\n      <th>female_mayor</th>\n      <th>margin_1</th>\n      <th>inter_1</th>\n      <th>margin_2</th>\n      <th>inter_2</th>\n      <th>female_mayor_full_sample</th>\n      <th>sum_years_as_mayor</th>\n      <th>mayor_age</th>\n      <th>mayor_university</th>\n      <th>mayor_employment</th>\n      <th>log_bevoelkerung</th>\n      <th>log_flaeche</th>\n      <th>log_debt_pc</th>\n      <th>log_tottaxrev_pc</th>\n      <th>log_gemeinde_beschaef_pc</th>\n      <th>log_female_sh_gem_besch</th>\n      <th>log_tot_beschaeft_pc</th>\n      <th>log_female_share_totbesch</th>\n      <th>log_prod_share_tot</th>\n      <th>log_female_share_prod</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>33708</th>\n      <td>436004</td>\n      <td>2011.0</td>\n      <td>4360042011</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>8.108109</td>\n      <td>3.0</td>\n      <td>1.0</td>\n      <td>72.972977</td>\n      <td>1.0</td>\n      <td>51.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>47.5</td>\n      <td>spd</td>\n      <td>0.0</td>\n      <td>-12.3</td>\n      <td>0.0</td>\n      <td>151.290009</td>\n      <td>0.00000</td>\n      <td>0.0</td>\n      <td>4.0</td>\n      <td>56.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>9.920246</td>\n      <td>3.133318</td>\n      <td>-0.121231</td>\n      <td>-0.156653</td>\n      <td>-5.091933</td>\n      <td>-0.820981</td>\n      <td>-1.721057</td>\n      <td>-0.828959</td>\n      <td>-1.353310</td>\n      <td>-0.962557</td>\n    </tr>\n    <tr>\n      <th>12539</th>\n      <td>432003</td>\n      <td>2001.0</td>\n      <td>4320032001</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>12.000000</td>\n      <td>3.0</td>\n      <td>1.0</td>\n      <td>20.000000</td>\n      <td>0.0</td>\n      <td>54.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>57.3</td>\n      <td>fdp</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>8.574329</td>\n      <td>2.225704</td>\n      <td>-0.585786</td>\n      <td>-0.040672</td>\n      <td>-5.483287</td>\n      <td>-0.893818</td>\n      <td>-2.000649</td>\n      <td>-0.715747</td>\n      <td>-1.105620</td>\n      <td>-1.177601</td>\n    </tr>\n    <tr>\n      <th>333</th>\n      <td>411000</td>\n      <td>2001.0</td>\n      <td>4110002001</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-12.676056</td>\n      <td>-9.0</td>\n      <td>0.0</td>\n      <td>47.887325</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>49.5</td>\n      <td>fdp</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>11.836761</td>\n      <td>4.805904</td>\n      <td>0.732735</td>\n      <td>-0.134298</td>\n      <td>-3.653085</td>\n      <td>-0.719740</td>\n      <td>-0.456145</td>\n      <td>-0.820801</td>\n      <td>-1.224465</td>\n      <td>-1.244217</td>\n    </tr>\n    <tr>\n      <th>89078</th>\n      <td>633001</td>\n      <td>2001.0</td>\n      <td>6330012001</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>22.580645</td>\n      <td>7.0</td>\n      <td>1.0</td>\n      <td>58.064518</td>\n      <td>1.0</td>\n      <td>22.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>59.2</td>\n      <td>spd</td>\n      <td>1.0</td>\n      <td>24.9</td>\n      <td>24.9</td>\n      <td>620.010010</td>\n      <td>620.01001</td>\n      <td>1.0</td>\n      <td>4.0</td>\n      <td>43.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>9.025455</td>\n      <td>2.892037</td>\n      <td>-0.455480</td>\n      <td>-0.564198</td>\n      <td>-5.387869</td>\n      <td>-1.335001</td>\n      <td>-2.531702</td>\n      <td>-0.719202</td>\n      <td>-1.190449</td>\n      <td>-1.589733</td>\n    </tr>\n    <tr>\n      <th>41061</th>\n      <td>438001</td>\n      <td>2006.0</td>\n      <td>4380012006</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>2.222222</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>22.222221</td>\n      <td>0.0</td>\n      <td>71.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>43.2</td>\n      <td>rep</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>10.415203</td>\n      <td>3.075929</td>\n      <td>0.347201</td>\n      <td>-0.105884</td>\n      <td>-4.791185</td>\n      <td>-0.620071</td>\n      <td>-1.165065</td>\n      <td>-0.896876</td>\n      <td>-1.526133</td>\n      <td>-1.257860</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## 2. Descriptive and Graphical Analyses\nThis section presents a descriptive summary of the data set which is provided by the authors. First, the coverage of the data set is described, i.e., how many council and mayor elections are observed for what number of municipalities and other rather superficial properties. We will have a look at the compositions of this data set, particularly in relation to the subsample of female council candidates which will be of increased interest throughout article and, hence, for this replication.\n\nSecond, we will try to make sense of observable discontinuities in observations. When inspecting the data set, in particular the observations for margin of victory and rank improvement combinations, noticeable discontinuities in both dimensions can be seen. This is especially interesting, because these discontinuities lead to stacked observations in a scatter plot which, in term, make it hard to judge if there is a discontinuity around the cutoff value of margin of victory.\n\nThis section concludes with a summary of the insights that can be gained from this very top level descriptive approach as well as the finding, that a discontinuity around the cutoff yet needs to be identified.\n\n### 2.1. Description of the Dataset\nThe data set contains observations on 1721 mayor elections. This includes the margin of victory as well as the gender of the mayoral candidates. Out of these 1721 elections, 268 are classified as a *mixed gender election*. The term *mixed gender election* is defined by the authors as \"mayor elections \\[where\\] the top two candidates were of opposite gender\".\n\nAt the same time, observations on the election results of 109.017 council candidates are provided. When only those council candidates are kept in the sample which ran at an election that was preceded by a mixed gender mayor election, a total of 23.169 council candidates is observed. For each of these candidate's individual characteristics like gender, education and occupation as well as their success in the council election is observed. Success in a council election is measured by the normalized rank improvement, which will be looked at in more detail in subsection 2.2.\n\n\n\n```python\n# Count of mayor elections\ndescriptive_dict = {}\ndescriptive_dict[\"mayor_election_count\"] = df_mayor_election_data[\"mayor_election_year\"].count()\n\n# Count of mixed gender elections\ndescriptive_dict[\"mixed_gender_elections_count\"] = df_mayor_election_data[\"rdd_sample\"].sum()\n\n# Count of council candidates\ndescriptive_dict[\"council_candidates_count\"] = df_main_dataset.gkz_jahr.count().astype(str)\n\n# Count of council candidates in mixed gender election municipality\ndescriptive_dict[\"relevant_council_candidates_count\"] = df_main_dataset.rdd_sample.count()\n\n# print results\nfor k in descriptive_dict.keys():\n    print(k, \":\", descriptive_dict[k], \"\\n\")\n```\n\n    mayor_election_count : 1721 \n    \n    mixed_gender_elections_count : 268.0 \n    \n    council_candidates_count : 109017 \n    \n    relevant_council_candidates_count : 23169 \n    \n\n\n\n```python\n# Generate a Barchart presenting the number of municipalities for which observations are available and for the\n# number of candidates per gender.\nplot_observations_municipalities_candidates(df_main_dataset)\n\n# Calculate the total number of Municipalities \nmuni_count = df_mayor_election_data.gkz.nunique()\nprint(\"In total there is data on characteristics available for\", \n      \"{} different Hessian Municipalities\".format(muni_count)\n     )\n```\n\n    In total there is data on characteristics available for 426 different Hessian Municipalities\n\n\n\n    <Figure size 432x360 with 0 Axes>\n\n\nAvailability of administrative data on municipalities (i.e. their population, per capita tax revenues and employment among others) is worse in early years. It is available for all 426 municipalities in 2016, however, for in 2001 it is available for 199 municipalities, only (figure 2, left side). While data for 2016 was provided by The Statistical Office of Hesse, data for previous years come \"from varying internet sources such as municipalities' websites as well as e-mail communication with the mayors, their administrative assistants, and high-ranking officials in the local administration.\" The quality of this information, thus, cannot be verified.\n\nA similar pattern in availability can be seen for the number of candidates observed in each year. The share of female candidates seems to be relatively stable at approximately 25 % in each year (figure 2, right side). \n\n**Figure 2: Number of observations on municipalities (left) and candidates per year (right)**\n\n\nData on the characteristics of council candidates varies slightly in availability. The data set provided by the authors contains information on educational attainment for 48.729 candidates. The occupation is provided for 49.399 individuals and age is known for 54.676 candidates (see table below for summary statistics). Differences in characteristics of council candidates are analyzed in the context section 5 of the article, where this information is used to assess the mechanisms that potentially drive the results of the main model. These mechanisms, however, are beyond the scope of this replication. \n\n\n```python\n# Calculate a descriptive summary table using a function stored in the auxiliary/plots_and_f\u00edgures file\nsummary_stats(df_main_dataset)\n```\n\n    C:\\ProgramData\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:2: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame\n    \n    See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n      \n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th colspan=\"5\" halign=\"left\">All candidates</th>\n      <th colspan=\"5\" halign=\"left\">Female candidates</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>Count</th>\n      <th>Mean</th>\n      <th>SD</th>\n      <th>Min</th>\n      <th>Max</th>\n      <th>Count</th>\n      <th>Mean</th>\n      <th>SD</th>\n      <th>Min</th>\n      <th>Max</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>gewinn_norm</th>\n      <td>109017</td>\n      <td>0.0666775</td>\n      <td>13.2524</td>\n      <td>-89.1892</td>\n      <td>97.2973</td>\n      <td>28480</td>\n      <td>-0.458681</td>\n      <td>11.9338</td>\n      <td>-89.1892</td>\n      <td>97.2973</td>\n    </tr>\n    <tr>\n      <th>age</th>\n      <td>54676</td>\n      <td>51.5807</td>\n      <td>13.7804</td>\n      <td>18</td>\n      <td>102</td>\n      <td>13923</td>\n      <td>51.035</td>\n      <td>13.6026</td>\n      <td>18</td>\n      <td>96</td>\n    </tr>\n    <tr>\n      <th>non_university_phd</th>\n      <td>48729</td>\n      <td>0.650578</td>\n      <td>0.476758</td>\n      <td>0</td>\n      <td>1</td>\n      <td>11734</td>\n      <td>0.671723</td>\n      <td>0.469591</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>university</th>\n      <td>48729</td>\n      <td>0.281598</td>\n      <td>0.449675</td>\n      <td>0</td>\n      <td>1</td>\n      <td>11734</td>\n      <td>0.277399</td>\n      <td>0.447711</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>phd</th>\n      <td>48729</td>\n      <td>0.0678241</td>\n      <td>0.25149</td>\n      <td>0</td>\n      <td>1</td>\n      <td>11734</td>\n      <td>0.0508778</td>\n      <td>0.219755</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>architect</th>\n      <td>49399</td>\n      <td>0.00860341</td>\n      <td>0.092334</td>\n      <td>0</td>\n      <td>1</td>\n      <td>11832</td>\n      <td>0.00693036</td>\n      <td>0.0829653</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>businessmanwoman</th>\n      <td>49399</td>\n      <td>0.0758922</td>\n      <td>0.264901</td>\n      <td>0</td>\n      <td>1</td>\n      <td>11832</td>\n      <td>0.0641481</td>\n      <td>0.245015</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>engineer</th>\n      <td>49399</td>\n      <td>0.0553048</td>\n      <td>0.228622</td>\n      <td>0</td>\n      <td>1</td>\n      <td>11832</td>\n      <td>0.0138607</td>\n      <td>0.116922</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>lawyer</th>\n      <td>49399</td>\n      <td>0.0313772</td>\n      <td>0.174319</td>\n      <td>0</td>\n      <td>1</td>\n      <td>11832</td>\n      <td>0.0351589</td>\n      <td>0.184205</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>civil_administration</th>\n      <td>49399</td>\n      <td>0.0773093</td>\n      <td>0.26701</td>\n      <td>0</td>\n      <td>1</td>\n      <td>11832</td>\n      <td>0.0581474</td>\n      <td>0.23403</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>teacher</th>\n      <td>49399</td>\n      <td>0.051661</td>\n      <td>0.221369</td>\n      <td>0</td>\n      <td>1</td>\n      <td>11832</td>\n      <td>0.0781778</td>\n      <td>0.268453</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>employed</th>\n      <td>55416</td>\n      <td>0.714721</td>\n      <td>0.451489</td>\n      <td>0</td>\n      <td>1</td>\n      <td>14043</td>\n      <td>0.697501</td>\n      <td>0.459378</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>selfemployed</th>\n      <td>55416</td>\n      <td>0.0584669</td>\n      <td>0.234624</td>\n      <td>0</td>\n      <td>1</td>\n      <td>14043</td>\n      <td>0.0361746</td>\n      <td>0.186739</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>student</th>\n      <td>55416</td>\n      <td>0.0443915</td>\n      <td>0.205934</td>\n      <td>0</td>\n      <td>1</td>\n      <td>14043</td>\n      <td>0.0516271</td>\n      <td>0.221288</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>retired</th>\n      <td>55416</td>\n      <td>0.14393</td>\n      <td>0.350939</td>\n      <td>0</td>\n      <td>1</td>\n      <td>14043</td>\n      <td>0.112868</td>\n      <td>0.316428</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>housewifehusband</th>\n      <td>55416</td>\n      <td>0.0228995</td>\n      <td>0.149591</td>\n      <td>0</td>\n      <td>1</td>\n      <td>14043</td>\n      <td>0.0880154</td>\n      <td>0.283326</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThis table compares characteristics of council candidates and their success in the council election between the whole sample and the female subsample. There are noticeable differences in the first row \"gewinn_norm\" which provides data on the normalized rank improvement of a candidate. By showing a lower (even negative) rank improvement on average, females appear to be less successful in council elections than male candidates. \n\nWhile most of the candidates' characteristics seem to be quite similar in both groups, there is some noticeable differences when it comes to the candidates' occupations: While the share of engineers is six times higher in the whole sample then among females, more than four times as many women than men reported domestic work as their occupation (category \"housewifehusband\").Furthermore, there is smaller but still noticeable differences, e.g. in occupations \"selfemployed\" and \"retired\" (both taking higher shares for male candidates) as well as \"teacher\" and \"civil_administration\" (both higher for female candidates).\n\nOverall, especially with respect to age and education of the candidates, there seems to be relatively little differences as seen from this descriptive level of inspection.\n\n### 2.2. Discontinuity in Distribution of Observations\nTaking a step beyond the content of the article, this section presents a brief investigation of the observations that are provided on the margin of victory (MoV) of a female in a mixed-gender mayor election and the rank improvements of female council candidates. This will help to get a feeling for the data on this main interrelation, prior to the econometric analyses that will be presented in subsequent sections of this notebook.\n\nThe relationship between the MoV of the female mayor (abscissa) and the rank improvements of female candidates in the subsequent council election (ordinate) is illustrated in firgure 2 below. For this exercise, only data on council elections that is subsequent to mixed-gender mayor elections will be used. In addition, only rank improvements of female council candidates are of interest for this analysis and, therefore, are included in the illustration below. \n\nNote that for easier interpretability *rank improvements* in the council elections are provided in a normalized form, facilitating comparability of changes in ranks of candidates between councils of different sizes. This conversion follows equation (2) of the article: \n\n\\begin{align}\n    rank \\, improvement = (\\frac{initial \\, rank - final \\, rank}{council \\, size}) \\times 100 \\label{eq2} \\tag{2}\n\\end{align}\n\n\n```python\n# Create a dataset that only contains observations on (a) on rank improvements of female council candidates and \n# (b) mixed gender mayor elections.\nrdd_data = df_main_dataset.loc[(df_main_dataset.female == 1) & \n                               (df_main_dataset.rdd_sample == 1)\n                              ]\n\n# Create a scatter plot that shows all combinations of the margin of victory of a female in a mixed\n# gender mayor lection and the rank improvements of female candidates in subsequent council elections.\n# Function is stored in auxiliary/plots_and_figures\nplot_observations(df=rdd_data, s=0.1)\n\n\n## Auxiliary addition: Find the reason for the discrete changes in gewinn_norm. \n# This would make sense, if the council sizes are small and many councils have same sizes. \n# Thus, create a plot showing the distribution of council sizes\n\n# Deduce the councile size using previously introduced conversion to normalizesd rank improvements. \ncouncil_sizes = rdd_data[['gkz_jahr', 'gewinn_norm', 'gewinn', 'listenplatz_norm']].copy()\ncouncil_sizes.loc[:,'council_size'] = council_sizes.loc[:,'gewinn'] / council_sizes.loc[:,'gewinn_norm'] * 100\n\n# drop rows where gewinn = 0 since we cannot deduct on council sizes in these cases. \ncouncil_sizes.drop(labels=council_sizes.loc[council_sizes.loc[:, 'gewinn']==0,:].index,\n                   axis=0,\n                   inplace=True\n                  )\n\n# Calculate the 95% percentile of council sizes as well as the number of councils that were voted for. \nN_councils = len(council_sizes.drop_duplicates(subset=['gkz_jahr'])['council_size'])\npercentile = int(np.percentile(a=council_sizes.drop_duplicates(subset=['gkz_jahr'])['council_size'],\n                               q=95, interpolation='lower'\n                              ))\n\n\n# plot a histogram for the council sizes\nbins = int((council_sizes['council_size']).max() - (council_sizes['council_size']).min())\n\nhist_council_sizes(df=council_sizes, bins=bins)\nprint('The number of council elections that we have observations for is '+\n      '{}. \\nThe 95 % percentile of council sizes is {}.'.format(N_councils, percentile))\n```\n\n    The number of council elections that we have observations for is 214. \n    The 95 % percentile of council sizes is 45.\n\n\nFigure 3 displays the rank improvement of a female council candidate and the MoV of a female mayor in the preceding mixed-gender mayor election. Since a lot of observations are stacked on top of each other and to prevent the figure from being too cluttered, a random sample of 10% of all available observations is plotted. Looking at the distributions of observed combinations, a pattern of horizontally as well as vertically aligned data points is revealed. \n\nFirst, since the authors work with a data set that contains rank improvements of each female council candidate for a given result of the preceding mayor election, discrete changes in the horizontal dimension, i.e. for mayor election results, are no surprising considering the limited number of observed mayor elections. \n\nSecond, the discrete distribution of values in the vertical dimension can be explained when a closer look is taken at the distribution of council sizes: As previously described, rank improvements are normalized using the respective size of the council. While the authors do not provide data on the council sizes, this value can easily be deduced from the given values for absolute and relative gains in list ranks for the candidates. As presented in figure 4, sizes of the 214 observed councils are distributed over relatively few values and are clustered at certain values. In addition, 95% if all councils have not more than 45 seats. \n\nConcluding, it seems plausible to observe a discrete distribution of normalized rank improvements, given the discussed distribution of council sizes which will cause the denominator for the value on the ordinate to be the same for a large number of observations.\n\n**Figure 3: Sample observations on normalized rank improvements and margin of victory**\n\n\n**Figure 4: Distribution of council sizes**\n\n\n\n### 2.3. Discontinuity at the Critical Value of the Margin of Victory\nConsidering figure 3, it is not very obvious if there is a discontinuity around the critical value of margin of victory (i.e. a margin of 0). A jump in values on the ordinate, however, might not be visible in this graphical representation. As discussed previously, observations are not distributed continuously but instead show strong discontinuities. This might result in a lot of observations being stacked on top of each other, hence not being represented in above plot. However, this problem should be mitigated by plotting only a small fraction of 10% of all observations.\n\nSummarizing, a discontinuity around the cutoff can still not be ruled out. Hence, in another approach we will have a look at binned data. By plotting data tuples of the mean values of both, the margin of victory as well as the rank improvement, a discontinuity should be revealed (if there is any). This is because stacked observations will still have an impact of equal size on the mean values within each bin. In the next section, this approach of plotting binned data will be pursued further.\n\n## 3. Replication and Critical Review\n### 3.1 Graphical Evidence: RDD Plot\n\nAs seen in previous section, a clear discontinuity around the cutoff value of the margin of victory of 0 is hard - if at all - to spot in figure 3 presented above. Hence, a more promising approach is presented by the authors in *Figure 2: Rank Improvement of Female Candidates* of the article which is an RDD-plot for binned normalized rank improvements. A replication of this RDD-plot is displayed in figure 5 below.\n\nIn this plot, first, the running variable (female mayor candidate margin of victory) is limited o values from -30 to +30 %. This allows to focus on the part of the data which is most relevant for this analysis. Second, the authors decide to bin the observations into clusters of 3 percentage points width of the running variable. Third, local polynomial regression of the underlying observations is added (red line) estimating the relation of both variables. Finally, the pointwise 95% confidence intervals are illustrated as black lines.\n\n\n```python\n# Keep only observations that fir above described criteria\nrdd_plot_data = rdd_data.loc[(rdd_data.margin_1 >= -30) & (rdd_data.margin_1 <= 30)].copy()\n\n# Create the RDD plot using the function stored in the auxiliary file. \nrslt = rdd_plot(data=rdd_plot_data, x_variable=\"margin_1\", y_variable=\"gewinn_norm\", nbins=20, ylimits=(-6,6), width=20.1, deg=1)\n```\n\nThe regression discontinuity plot reveals a discontinuity at the cutoff value, i.e. a MoV of 0. Since a python package for the calculation of confidence intervals of a local polynomial regression is currently not available, I calculate pointwise confidence intervals. The results of this graphical analysis can be seen as a confirmation of the existence of a discontinuity at the cutoff value which is argued by the authors.\n\n\n### 3.2 Main Results\n#### 3.2.1 Regression Results\n\nAfter previous section provided graphical evidence on the existence and the extent of the discontinuity in rank improvements around the cutoff value of the MoV, this section replicates the results of a regression discontinuity analysis that aims to estimate the causal effect of a female mayor on success of female council candidates.\n\nFor the estimation of the effect of a female mayor on the success of a female council candidates, two different approaches are presented. The first relates gender of incumbent mayor to the normalized rank improvement of female candidates (i.e., normalized rank improvements are endogenous). The second relates gender of incumbent mayor to the likelihood that an elected member of the council in the same municipality is female (i.e. a dummy that equals 1 for council members that are female is endogenous).\n\nBoth regressions are performed using different bandwidths and functional forms. For this replication, I will focus on the main specification (highlighted in bold font) which is the basis for the discussion in the article.\n\n* a) bandwidths:\n    - **optimal CCT bandwidth (20.1)**\n    - CCT / 2 (10.05)\n    - CCT * 2 (40.2)\n    - IK (35.59)\n* b) functional form:\n    - **linear**\n    - quadratic\n\nOnly the optimal CCT bandwidth is used for the quadratic specification resulting in five specifications in total. The second approach results in insignificant results while point estimates seem to be in line with the results of the first approach. Since the subsequent discussion in mainly based on the first specification it will be calculated by default in the following cells. Note that the results for different bandwidths can easily be reproduced by adjusting the *bw* variable in subsequent code cells. \n\nFor further information on the chosen bandwidth selection criteria (CCT), the documentation of [rdrobust](https://d1e153b2-a-62cb3a1a-s-sites.googlegroups.com/site/rdpackages/rdrobust/stata/rdrobust.pdf?attachauth=ANoY7coYcDVv4k7XCZ-Kf0Mm5vUExsMu1m4V1ETm955F5qt8DADN1vnHjmhHjyvzwVWcN63n5F1PYajyeTnm1jsbwo16IirwoemO_u9o-USoBOAWOJPOVLTvew_zk1tToB_YI7rEiYhCSCDe98NIZ1M-RpQWaRD5aTCa8pOi2S2ivyMx08GvdcSe0bEbRsI9q_HYs_L7vmEH1E2qTTbJCDwy646Glx3uJVhGS4Ft6C_QP4fsX0Rp1wQ%3D&attredirects=0), the stata package that is used by the authors, can be consulted.\n\n**Specification 1: Rank Improvements of Female Candidates:**\n\nIn this specification normalized rank improvements are endogenous in the margin of victory of a female mayor, a dummy that takes value 1 if a female won the mayor election and an interaction term of both, margin and dummy. The regression model is illustrated in equation (3) below. In this notation, $i$ denotes one female council candidate. The dummy $D_{f\\_mayor, i}$ takes value 1 if the mayor in charge at the time of the council election is female. Finally, $MoV$ denotes the margin of victory of the female mayor candidate. Note that for values bigger 0 for $MoV$, $D_{f\\_mayor, i}$ takes value 1 and vice versa. \n\n\\begin{align}\n    normalized\\_rank\\_improvement_i = \\beta_0 + \\beta_1 D_{f\\_mayor, i} + \\beta_2 MoV_i + \\beta_3 D_{f\\_mayor, i} * MoV_i \\tag{3}\n\\end{align}\n\nAdditionally, observations are weighted using their distance to the cutoff value of 0 for the margin of victory. Lower weights are attached to observations farther away from the cutoff value. Thus, observations very close to the cutoff will have a weight close to 1. At the same time, observations where the size of the margin of victory close to the size of the bandwidth will have a weight close to 0. \n\n\n```python\n# Set the bandwidth (taken from the paper)\nbw = 20.1\n\n# Get regression weights\nrdd_data[\"weight\"] = calculate_weights(df=rdd_data, bandwidth=bw)\n\n# Run regression for approach (1): normalized rank improvement of female candidates on gender of mayor\nsm.WLS(endog=rdd_data.loc[abs(rdd_data[\"margin_1\"])<bw][\"gewinn_norm\"], \n       exog=sm.add_constant(rdd_data.loc[abs(rdd_data[\"margin_1\"])<bw][[\"female_mayor\", \"margin_1\", \"inter_1\"]]), \n       weights=rdd_data.loc[abs(rdd_data[\"margin_1\"])<bw][\"weight\"],\n      ).fit(cov_type=\"cluster\", \n             cov_kwds={\"groups\":rdd_data.loc[abs(rdd_data[\"margin_1\"])<bw][\"gkz\"]}\n            ).summary()\n```\n\n    C:\\ProgramData\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:5: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n      \"\"\"\n    C:\\ProgramData\\Anaconda3\\lib\\site-packages\\numpy\\core\\fromnumeric.py:2389: FutureWarning: Method .ptp is deprecated and will be removed in a future version. Use numpy.ptp instead.\n      return ptp(axis=axis, out=out, **kwargs)\n\n\n\n\n\n<table class=\"simpletable\">\n<caption>WLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>       <td>gewinn_norm</td>   <th>  R-squared:         </th> <td>   0.011</td> \n</tr>\n<tr>\n  <th>Model:</th>                   <td>WLS</td>       <th>  Adj. R-squared:    </th> <td>   0.010</td> \n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   5.982</td> \n</tr>\n<tr>\n  <th>Date:</th>             <td>Thu, 01 Aug 2019</td> <th>  Prob (F-statistic):</th>  <td>0.00133</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>01:33:17</td>     <th>  Log-Likelihood:    </th> <td> -11259.</td> \n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>  2878</td>      <th>  AIC:               </th> <td>2.253e+04</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>  2874</td>      <th>  BIC:               </th> <td>2.255e+04</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>    \n</tr>\n<tr>\n  <th>Covariance Type:</th>       <td>cluster</td>     <th>                     </th>     <td> </td>    \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n        <td></td>          <th>coef</th>     <th>std err</th>      <th>z</th>      <th>P>|z|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>const</th>        <td>   -1.0352</td> <td>    0.584</td> <td>   -1.772</td> <td> 0.076</td> <td>   -2.180</td> <td>    0.110</td>\n</tr>\n<tr>\n  <th>female_mayor</th> <td>    3.7118</td> <td>    0.980</td> <td>    3.788</td> <td> 0.000</td> <td>    1.791</td> <td>    5.632</td>\n</tr>\n<tr>\n  <th>margin_1</th>     <td>   -0.0689</td> <td>    0.068</td> <td>   -1.007</td> <td> 0.314</td> <td>   -0.203</td> <td>    0.065</td>\n</tr>\n<tr>\n  <th>inter_1</th>      <td>   -0.1210</td> <td>    0.104</td> <td>   -1.164</td> <td> 0.245</td> <td>   -0.325</td> <td>    0.083</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>990.914</td> <th>  Durbin-Watson:     </th> <td>   2.062</td> \n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>11077.674</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.304</td>  <th>  Prob(JB):          </th> <td>    0.00</td> \n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>12.251</td>  <th>  Cond. No.          </th> <td>    40.4</td> \n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors are robust tocluster correlation (cluster)\n\n\n\nComparing the results presented in the paper (see figure 6 below) to the regression summary above, it can be seen that the results presented in the article can be replicated. As eluded to earlier, the authors present a number of different specifications for varying bandwidths as well as functional forms. The results of the main model (optimal bandwidth and linear functional form) can be seen in the column denoted with (1) in the figure below. \n\nThe presented results for varying bandwidths can easily be replicated by adjusting the *bw* variable in the code cell above to take the according value in row \"Bandwidth size\" of figure 6. While the resulting estimates as well as the number of observations and other outputs can be replicated for specifications (1) through (4), the quadratic functional form (specification (5)) cannot be estimated due to limitations in the functional form of the python package used for this estimation.\n\nThe quadratic specification, however, acts merely as another robustness check for the main results. As seen in figure 6 below, changes in the functional form (i.e. adding the squared versions of the third and fourth summand on the right hand side of equation (3)) does not result in substantial changes in the regression outcome. The point estimate remains at approximately the same level and still shows to be significant at the 95% level. \n\n**Figure 6: Main results I: Rank improvement of female candidates as presented by the authors**\n\n\n\n\n```python\n# Descriptives of the regression result\nN = rdd_data.loc[abs(rdd_data[\"margin_1\"])<bw][\"gewinn_norm\"].count()\nelec = rdd_data.loc[abs(rdd_data[\"margin_1\"])<bw][\"gkz_jahr\"].nunique()\nmuni = rdd_data.loc[abs(rdd_data[\"margin_1\"])<bw][\"gkz\"].nunique()\ny_mean = rdd_data.loc[abs(rdd_data[\"margin_1\"])<bw][\"gewinn_norm\"].mean()\ny_sd = rdd_data.loc[abs(rdd_data[\"margin_1\"])<bw][\"gewinn_norm\"].std()\nmain_result_descriptive = pd.DataFrame(data=[N, elec, muni, y_mean, y_sd], \n                                       index=[\"Observations\", \n                                              \"Elections\", \n                                              \"Municipalities\", \n                                              \"Dep. Variable Mean\", \n                                              \"Dep. Variable SD\"\n                                             ], \n                                       columns = [\"value\"],\n                                      )\n\n# print the results\nmain_result_descriptive\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>value</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Observations</th>\n      <td>2878.000000</td>\n    </tr>\n    <tr>\n      <th>Elections</th>\n      <td>77.000000</td>\n    </tr>\n    <tr>\n      <th>Municipalities</th>\n      <td>56.000000</td>\n    </tr>\n    <tr>\n      <th>Dep. Variable Mean</th>\n      <td>0.411436</td>\n    </tr>\n    <tr>\n      <th>Dep. Variable SD</th>\n      <td>10.949259</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nAs a check for mistakes in the replication process, the descriptive statistics which the authors provide with the main result (see figure 6 above), are replicated as well. All descriptive values calculated for the data used in the replication process match with their counterparts presented by the authors. Thus, there is no reason to believe that the underlying observations of the regression analysis are different from the ones used by the authors of the article.\n\nThe results of this regression analysis indicate that the victory of a female candidate in the mayoral election in a municipality is associated with an improvement of 3.7 normalized ranks. For the median council size of 31 seats this corresponds to approximately 1.15 ranks.\n\n**Approach 2: Share of Women among Candidates Elected to the Council:**\n\nFor the second approach, the gender of an elected council member is used as the endogenous variable while the right side of the regression equation remains the same. Althogh the endogenous variable is a binary variable in this regression equation, the authors apply the same weighted linear regression method which is used in the first approach presented above. Thus, the estimated model can be denoted as follows.\n\n\\begin{align}\n    D_{gender\\_council\\_candidate,i} = \\beta_0 + \\beta_1 D_{f\\_mayor, i} + \\beta_2 MoV_i + \\beta_3 D_{f\\_mayor, i} * MoV_i  \\tag{4}\n\\end{align}\n\nNote that the right hand side of equation (4) remains unchanged in comparison to the previously discussed specification presented in equation (3). The binary endogenous variable $D_{gender\\_council\\_candidate,i}$ takes value 1 if candidate $i$ is female and 0 otherwise. \n\nAt the same time, the data set used for this regression model is slightly different from the one used previously. While it includes data on male as well as female council candidates now, it only contains those of council candidates that end up to be elected into council.\n\n\n```python\n# Select data on (a) mixed gender mayor elections and (b) council candidates who were elected\ncandidates_elected = df_main_dataset.loc[(df_main_dataset.rdd_sample == 1) & (df_main_dataset.elected == 1)].copy()\n\n# set same bandwidth as authors do\nbw = 23.90\n\n# Add weighing vector as calculated by the authors\ncandidates_elected[\"weight\"] = calculate_weights(df=candidates_elected, bandwidth=bw)\n\n# Run regression for approach (2): Gender of an elected council candidate\nsm.WLS(endog=candidates_elected.loc[abs(candidates_elected[\"margin_1\"])<bw][\"female\"], \n       exog=sm.add_constant(\n           candidates_elected.loc[abs(candidates_elected[\"margin_1\"])<bw][[\"female_mayor\", \n                                                                           \"margin_1\", \n                                                                           \"inter_1\"\n                                                                          ]]\n       ), \n       weights=candidates_elected.loc[abs(candidates_elected[\"margin_1\"])<bw][\"weight\"],\n      ).fit(cov_type=\"cluster\", \n             cov_kwds={\"groups\":candidates_elected.loc[abs(candidates_elected[\"margin_1\"])<bw][\"gkz\"]}\n            ).summary()\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>WLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>         <td>female</td>      <th>  R-squared:         </th> <td>   0.001</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>WLS</td>       <th>  Adj. R-squared:    </th> <td>   0.000</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>  0.4036</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Thu, 01 Aug 2019</td> <th>  Prob (F-statistic):</th>  <td> 0.751</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>01:33:17</td>     <th>  Log-Likelihood:    </th> <td> -2654.2</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>  3463</td>      <th>  AIC:               </th> <td>   5316.</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>  3459</td>      <th>  BIC:               </th> <td>   5341.</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>       <td>cluster</td>     <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n        <td></td>          <th>coef</th>     <th>std err</th>      <th>z</th>      <th>P>|z|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>const</th>        <td>    0.2563</td> <td>    0.021</td> <td>   12.210</td> <td> 0.000</td> <td>    0.215</td> <td>    0.297</td>\n</tr>\n<tr>\n  <th>female_mayor</th> <td>    0.0412</td> <td>    0.042</td> <td>    0.990</td> <td> 0.322</td> <td>   -0.040</td> <td>    0.123</td>\n</tr>\n<tr>\n  <th>margin_1</th>     <td>   -0.0004</td> <td>    0.002</td> <td>   -0.204</td> <td> 0.839</td> <td>   -0.004</td> <td>    0.003</td>\n</tr>\n<tr>\n  <th>inter_1</th>      <td>   -0.0006</td> <td>    0.003</td> <td>   -0.193</td> <td> 0.847</td> <td>   -0.007</td> <td>    0.005</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>522.050</td> <th>  Durbin-Watson:     </th> <td>   1.918</td> \n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td> 765.517</td> \n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.140</td>  <th>  Prob(JB):          </th> <td>5.89e-167</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 2.666</td>  <th>  Cond. No.          </th> <td>    40.1</td> \n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors are robust tocluster correlation (cluster)\n\n\n\nAgain, the results of this regression correspond to the results presented in the article (see figure 7 below). Similar to the replication of the first approach presented earlier, the regression summary is set to replicate the main results, hence, uses the optimal bandwidth and a linear functional form as presented in column (1) of figure 7 below. However, by setting the according value for the *bw* variable, specifications (2) through (4) can be replicated from the code block above effortlessly.\n\n**Figure 7: Main results II: Share of women among candidates elected to the council as presented by the authors**\n\n\nThe main result provides a point estimate of 0.041 which indicates that the voctory of a female mayor candidate in a mixed gender election is associated with a 4.1 percentage points increase in the share of female council members.\n\n\n```python\n# Calculate descriptives\nN = candidates_elected.loc[abs(candidates_elected[\"margin_1\"])<bw][\"female\"].count()\nelec = candidates_elected.loc[abs(candidates_elected[\"margin_1\"])<bw][\"gkz_jahr\"].nunique()\nmuni = candidates_elected.loc[abs(candidates_elected[\"margin_1\"])<bw][\"gkz\"].nunique()\ny_mean = candidates_elected.loc[abs(candidates_elected[\"margin_1\"])<bw][\"female\"].mean()\ny_sd = candidates_elected.loc[abs(candidates_elected[\"margin_1\"])<bw][\"female\"].std()\nmain_result_descriptive = pd.DataFrame(data=[N, elec, muni, y_mean, y_sd], \n                                       index=[\"Observations\", \n                                              \"Elections\", \n                                              \"Municipalities\", \n                                              \"Dep. Variable Mean\", \n                                              \"Dep. Variable SD\"\n                                             ], \n                                       columns = [\"value\"],\n                                      )\n\n# print the results\nmain_result_descriptive\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>value</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Observations</th>\n      <td>3463.000000</td>\n    </tr>\n    <tr>\n      <th>Elections</th>\n      <td>96.000000</td>\n    </tr>\n    <tr>\n      <th>Municipalities</th>\n      <td>72.000000</td>\n    </tr>\n    <tr>\n      <th>Dep. Variable Mean</th>\n      <td>0.273751</td>\n    </tr>\n    <tr>\n      <th>Dep. Variable SD</th>\n      <td>0.445954</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n#### 3.2.2 Robustness\nIn order to evaluate the robustness of their baseline results, the authors present two different approaches: First, a placebo test and, second, a test for different scalings of the outcome variable. The authors argue that, overall, the baseline results show to be robust to both of these checks.\n\n##### 3.2.2.1 Placebo Test\nThe placebo test is described to check whether past values of the outcome variable \"can be explained by contemporaneous values of the treatment variable\". Applied to the analysis presented in the article, this translates to a test for statistically significant correlations between the gender of the mayor in council election period $t$ and the rank improvements of female council candidates in period $t-k$. The authors argue that \"if the female mayor dummy has a significant effect on the rank improvements of women in past elections, this would call our baseline estimates into question.\"\n\nTime lag $k$ is chosen to be five by the authors, which amounts exactly to the time between two council elections ([Hessian Municipal Code \u00a736](http://www.lexsoft.de/cgi-bin/lexsoft/justizportal_nrw.cgi?t=156459931255666006&sessionID=1855059091299078653&chosenIndex=Dummy_nv_68&templateID=document&source=context&source=context&highlighting=off&xid=146137,46)). This assumption is not discussed in the article, although it is somewhat questionable since the regular period of office of a mayor in Hesse is six years ([Hessian Municipal Code, \u00a739](http://www.lexsoft.de/cgi-bin/lexsoft/justizportal_nrw.cgi?xid=146137,50)). By setting $k=5$ the authos ensure that a mayor is in office for at most one year before the council election takes place. Thus, mitigating effects on anti-female voters bias arguably are quite low. At the same time, one could argue that the effects of a female mayor on anti-female voters bias might be particularly large right after the mayor's election while media coverage of the mayor might be especially broad and while the election itself is not in the too distant past.\n\nIndeed, as shown in the next cell, only for 40% of the observations used in the placebo test, the mayor is in charge for less than five years at the moment the council election takes place. In other words, voters have been exposed to the same mayor in the council election in year $t$ that was already in charge during the council election in year $t-5$ in 60% of the observations. Hence, the results of the placebo test as it is presented by the authors might be imprecise.\n\nNext, the placebo test as it is depicted in the article is replicated. Subsequently, leaving the scope of a replication for a moment, a placebo test based on a stricter data selection than the one presented by the authors is carried out. Both these analyses are conducted using the placebo dataset (\"dataset_with_lagged_rank_improvments.dta\") which is provided by the authors. This dataset contains information on the mayor's gender and MoV at time $t$ as well as results for the council election in $t-5$.\n\n\n```python\n# Is the longer office term of mayors a relevant problem?\n# If the mayor is in office for 5 or more years at t (time of council election) then\n# he/ she was in charge during last council election -> no real placebo test!\n# How many mayors where in office for 5 or more years at time t, when t is the year of council election?\n\n# Merge placebo date with data on the sum of years a mayor is in office at year t\ndf_placebo_2 = pd.merge(left=df_placebo, \n                  right=df_main_dataset[[\n                      \"gkz_jahr\",\n                      \"sum_years_as_mayor\"\n                  ]].drop_duplicates(), \n                  on=[\"gkz_jahr\"], \n                  how=\"left\")\n\n# calculate share of observations with a mayor that is in office for less\n# then 5 years in all observations used in placebo test\ntemp = np.round(\n    len(df_placebo_2.loc[df_placebo_2[\"sum_years_as_mayor\"]<5,:].index) / len(df_placebo_2.index),\n    3\n)\nprint(\"The mayor in office is in charge for less than five years for {}%\".format(temp)+\n      \" of the observations on the placebo dataset.\")\n```\n\n    The mayor in office is in charge for less than five years for 0.401% of the observations on the placebo dataset.\n\n\n\n```python\n# Replicate the placebo test as it is performed and presented in the article\n\n# Set the bandwidth (taken from the paper)\nbw = 15.71 # CCT\n#bw = 15.71/2\n#bw = 15.71*2\n#bw = 17.22 # KI\n\n# Get regression weights\ndf_placebo[\"weight\"] = calculate_weights(df=df_placebo, bandwidth=bw)\n\n# Run regression of rank improvements in t-5 on mayor election result in t\nsm.WLS(endog=df_placebo.loc[abs(df_placebo[\"margin_1\"])<bw][\"gewinn_norm\"], \n       exog=sm.add_constant(df_placebo.loc[abs(df_placebo[\"margin_1\"])<bw][[\n           \"female_mayor\",\n           \"margin_1\",\n           \"inter_1\"\n       ]]), \n       weights=df_placebo.loc[abs(df_placebo[\"margin_1\"])<bw][\"weight\"],\n      ).fit(cov_type=\"cluster\", \n             cov_kwds={\"groups\":df_placebo.loc[abs(df_placebo[\"margin_1\"])<bw][\"gkz\"]}\n            ).summary()\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>WLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>       <td>gewinn_norm</td>   <th>  R-squared:         </th> <td>   0.006</td> \n</tr>\n<tr>\n  <th>Model:</th>                   <td>WLS</td>       <th>  Adj. R-squared:    </th> <td>   0.004</td> \n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   1.590</td> \n</tr>\n<tr>\n  <th>Date:</th>             <td>Thu, 01 Aug 2019</td> <th>  Prob (F-statistic):</th>  <td> 0.206</td>  \n</tr>\n<tr>\n  <th>Time:</th>                 <td>01:33:17</td>     <th>  Log-Likelihood:    </th> <td> -6293.4</td> \n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>  1603</td>      <th>  AIC:               </th> <td>1.259e+04</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>  1599</td>      <th>  BIC:               </th> <td>1.262e+04</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>    \n</tr>\n<tr>\n  <th>Covariance Type:</th>       <td>cluster</td>     <th>                     </th>     <td> </td>    \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n        <td></td>          <th>coef</th>     <th>std err</th>      <th>z</th>      <th>P>|z|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>const</th>        <td>   -0.2475</td> <td>    0.763</td> <td>   -0.324</td> <td> 0.746</td> <td>   -1.743</td> <td>    1.248</td>\n</tr>\n<tr>\n  <th>female_mayor</th> <td>    0.8003</td> <td>    1.365</td> <td>    0.586</td> <td> 0.558</td> <td>   -1.875</td> <td>    3.476</td>\n</tr>\n<tr>\n  <th>margin_1</th>     <td>    0.0117</td> <td>    0.105</td> <td>    0.112</td> <td> 0.911</td> <td>   -0.193</td> <td>    0.217</td>\n</tr>\n<tr>\n  <th>inter_1</th>      <td>    0.1117</td> <td>    0.161</td> <td>    0.695</td> <td> 0.487</td> <td>   -0.203</td> <td>    0.427</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>674.912</td> <th>  Durbin-Watson:     </th> <td>   2.037</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>8634.893</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.609</td>  <th>  Prob(JB):          </th> <td>    0.00</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>13.905</td>  <th>  Cond. No.          </th> <td>    32.2</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors are robust tocluster correlation (cluster)\n\n\n\n\n```python\n# placebo test with only those observations from placebo dataframe in which the mayor in in office\n# for less than 5 years\ndata = df_placebo_2.loc[df_placebo_2[\"sum_years_as_mayor\"]<5]\n\n# Set the bandwidth (chosen to be the same as in the authors approach)\n#bw = 15.71 # CCT\n#bw = 15.71/2 \n#bw = 15.71*2 \n#bw = 17.22 # IK\n\n# Get regression weights\ndata[\"weight\"] = calculate_weights(df=df_placebo_2, bandwidth=bw)\n\n# Replicate the placebo test using only these observations\nsm.WLS(endog=data.loc[abs(data[\"margin_1\"])<bw][\"gewinn_norm\"], \n       exog=sm.add_constant(data.loc[abs(data[\"margin_1\"])<bw][[\"female_mayor\", \"margin_1\", \"inter_1\"]]), \n       weights=data.loc[abs(data[\"margin_1\"])<bw][\"weight\"],\n      ).fit(cov_type=\"cluster\", \n             cov_kwds={\"groups\":data.loc[abs(data[\"margin_1\"])<bw][\"gkz\"]}\n            ).summary()\n```\n\n    C:\\ProgramData\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:12: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n      if sys.path[0] == '':\n\n\n\n\n\n<table class=\"simpletable\">\n<caption>WLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>       <td>gewinn_norm</td>   <th>  R-squared:         </th> <td>   0.002</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>WLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.002</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>  0.3645</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Thu, 01 Aug 2019</td> <th>  Prob (F-statistic):</th>  <td> 0.779</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>01:33:17</td>     <th>  Log-Likelihood:    </th> <td> -3072.2</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   774</td>      <th>  AIC:               </th> <td>   6152.</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   770</td>      <th>  BIC:               </th> <td>   6171.</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>       <td>cluster</td>     <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n        <td></td>          <th>coef</th>     <th>std err</th>      <th>z</th>      <th>P>|z|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>const</th>        <td>   -1.4878</td> <td>    1.150</td> <td>   -1.293</td> <td> 0.196</td> <td>   -3.742</td> <td>    0.767</td>\n</tr>\n<tr>\n  <th>female_mayor</th> <td>    1.3984</td> <td>    1.805</td> <td>    0.775</td> <td> 0.439</td> <td>   -2.140</td> <td>    4.936</td>\n</tr>\n<tr>\n  <th>margin_1</th>     <td>   -0.0958</td> <td>    0.126</td> <td>   -0.759</td> <td> 0.448</td> <td>   -0.343</td> <td>    0.151</td>\n</tr>\n<tr>\n  <th>inter_1</th>      <td>   -0.0174</td> <td>    0.195</td> <td>   -0.089</td> <td> 0.929</td> <td>   -0.399</td> <td>    0.364</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>266.359</td> <th>  Durbin-Watson:     </th> <td>   1.989</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>3781.182</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.144</td>  <th>  Prob(JB):          </th> <td>    0.00</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>13.584</td>  <th>  Cond. No.          </th> <td>    25.9</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors are robust tocluster correlation (cluster)\n\n\n\nSummarizing the results of the placebo test, the following can be concluded:\nFirst, the estimation results of a placebo test as it is presented in the article, particularly in table A.8 of the online appendix (see figure 8 below), can be replicated. In accordance to the argument in the article, the point estimate of this estimation shows to be relatively small in comparison to the main results. But more importantly, they do not show statistical significance and even reveal changes in signs for different bandwidths. This is seen as supporting evidence for robustness of the main results. \n\n\n**Figure 8: Robustness Test I: Rank improvement of female candidates in previous council election**\n\n\nSecond, following above discussion of the term duration of mayors in Hesse and, consequentially, excluding all observations for which the mayor at time $t$ was in office for five or more years, does not lead to substantial differences in results. While in this specification there is no change in signs of the point estimate of the female mayor dummy, estimates still do not show statistical significance. \n\n##### 3.2.2.2 Scaling of the Outcome Variable\n\nIn the second robustness test, the authors test whether the results of their analysis are sensitive regarding changes in the scaling of the outcome variable, i.e. the rank improvements of council candidates. As illustrated in section 2.2 of this notebook, the authors use normalized rank improvements in order to facilitate interpretability of the results as well comparability of changes in rank for different council sizes. Assessing robustness with regard to this scaling, alternative specifications of the regression model are presented using (a) raw rank improvements and (b) a dummy variable that takes value 1 if a candidate experienced a strictly positive rank improvement. Estimations for both specifications will be replicated in succeeding cells.\n\n\n```python\n# (a) raw rank improvements instead of normalized rank improvements as endogenous variable\n# Set the bandwidth (taken from the paper)\nbw = 19.31\n\n# Get regression weights\nrdd_data[\"weight\"] = calculate_weights(df=rdd_data, bandwidth=bw)\n\n# Run regression for approach (1): normalized rank improvement of female candidates on gender of mayor\nsm.WLS(endog=rdd_data.loc[abs(rdd_data[\"margin_1\"])<bw][\"gewinn\"], \n       exog=sm.add_constant(rdd_data.loc[abs(rdd_data[\"margin_1\"])<bw][[\n           \"female_mayor\",\n           \"margin_1\",\n           \"inter_1\"\n       ]]), \n       weights=rdd_data.loc[abs(rdd_data[\"margin_1\"])<bw][\"weight\"],\n      ).fit(cov_type=\"cluster\", \n             cov_kwds={\"groups\":rdd_data.loc[abs(rdd_data[\"margin_1\"])<bw][\"gkz\"]}\n            ).summary()\n```\n\n    C:\\ProgramData\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:6: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n      \n\n\n\n\n\n<table class=\"simpletable\">\n<caption>WLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>         <td>gewinn</td>      <th>  R-squared:         </th> <td>   0.022</td> \n</tr>\n<tr>\n  <th>Model:</th>                   <td>WLS</td>       <th>  Adj. R-squared:    </th> <td>   0.021</td> \n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   3.790</td> \n</tr>\n<tr>\n  <th>Date:</th>             <td>Thu, 01 Aug 2019</td> <th>  Prob (F-statistic):</th>  <td>0.0154</td>  \n</tr>\n<tr>\n  <th>Time:</th>                 <td>01:33:17</td>     <th>  Log-Likelihood:    </th> <td> -8870.9</td> \n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>  2842</td>      <th>  AIC:               </th> <td>1.775e+04</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>  2838</td>      <th>  BIC:               </th> <td>1.777e+04</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>    \n</tr>\n<tr>\n  <th>Covariance Type:</th>       <td>cluster</td>     <th>                     </th>     <td> </td>    \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n        <td></td>          <th>coef</th>     <th>std err</th>      <th>z</th>      <th>P>|z|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>const</th>        <td>   -0.4034</td> <td>    0.212</td> <td>   -1.907</td> <td> 0.056</td> <td>   -0.818</td> <td>    0.011</td>\n</tr>\n<tr>\n  <th>female_mayor</th> <td>    2.1297</td> <td>    0.633</td> <td>    3.365</td> <td> 0.001</td> <td>    0.889</td> <td>    3.370</td>\n</tr>\n<tr>\n  <th>margin_1</th>     <td>   -0.0343</td> <td>    0.029</td> <td>   -1.196</td> <td> 0.232</td> <td>   -0.090</td> <td>    0.022</td>\n</tr>\n<tr>\n  <th>inter_1</th>      <td>   -0.0669</td> <td>    0.052</td> <td>   -1.285</td> <td> 0.199</td> <td>   -0.169</td> <td>    0.035</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>974.904</td> <th>  Durbin-Watson:     </th> <td>   2.016</td> \n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>18644.289</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.136</td>  <th>  Prob(JB):          </th> <td>    0.00</td> \n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>15.340</td>  <th>  Cond. No.          </th> <td>    40.3</td> \n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors are robust tocluster correlation (cluster)\n\n\n\n\n```python\n# (b) rank improvement dummy instead of normalized rank improvement as endogenous variable\n# Set the bandwidth (taken from the paper)\nbw = 18.11\n\n# Get regression weights\nrdd_data[\"weight\"] = calculate_weights(df=rdd_data, bandwidth=bw)\n\n# Run regression for approach (1): normalized rank improvement of female candidates on gender of mayor\nsm.WLS(endog=rdd_data.loc[abs(rdd_data[\"margin_1\"])<bw][\"gewinn_dummy\"], \n       exog=sm.add_constant(rdd_data.loc[abs(rdd_data[\"margin_1\"])<bw][[\n           \"female_mayor\",\n           \"margin_1\",\n           \"inter_1\"\n       ]]), \n       weights=rdd_data.loc[abs(rdd_data[\"margin_1\"])<bw][\"weight\"],\n      ).fit(cov_type=\"cluster\", \n             cov_kwds={\"groups\":rdd_data.loc[abs(rdd_data[\"margin_1\"])<bw][\"gkz\"]}\n            ).summary()\n```\n\n    C:\\ProgramData\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:6: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n      \n\n\n\n\n\n<table class=\"simpletable\">\n<caption>WLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>      <td>gewinn_dummy</td>   <th>  R-squared:         </th> <td>   0.022</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>WLS</td>       <th>  Adj. R-squared:    </th> <td>   0.021</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   2.847</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Thu, 01 Aug 2019</td> <th>  Prob (F-statistic):</th>  <td>0.0464</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>01:33:17</td>     <th>  Log-Likelihood:    </th> <td> -2128.9</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>  2669</td>      <th>  AIC:               </th> <td>   4266.</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>  2665</td>      <th>  BIC:               </th> <td>   4289.</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>       <td>cluster</td>     <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n        <td></td>          <th>coef</th>     <th>std err</th>      <th>z</th>      <th>P>|z|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>const</th>        <td>    0.3146</td> <td>    0.028</td> <td>   11.092</td> <td> 0.000</td> <td>    0.259</td> <td>    0.370</td>\n</tr>\n<tr>\n  <th>female_mayor</th> <td>    0.2153</td> <td>    0.075</td> <td>    2.888</td> <td> 0.004</td> <td>    0.069</td> <td>    0.362</td>\n</tr>\n<tr>\n  <th>margin_1</th>     <td>   -0.0034</td> <td>    0.004</td> <td>   -0.908</td> <td> 0.364</td> <td>   -0.011</td> <td>    0.004</td>\n</tr>\n<tr>\n  <th>inter_1</th>      <td>   -0.0059</td> <td>    0.006</td> <td>   -0.963</td> <td> 0.335</td> <td>   -0.018</td> <td>    0.006</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>14966.361</td> <th>  Durbin-Watson:     </th> <td>   2.007</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th>  <td> 0.000</td>   <th>  Jarque-Bera (JB):  </th> <td> 325.586</td>\n</tr>\n<tr>\n  <th>Skew:</th>           <td> 0.355</td>   <th>  Prob(JB):          </th> <td>1.99e-71</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>       <td> 1.444</td>   <th>  Cond. No.          </th> <td>    39.7</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors are robust tocluster correlation (cluster)\n\n\n\nComparing the results of above analysis to the results presented in the article (figure A.10 of the online appendix, shown in figure 9 below), no differences in results become apparent. The replication of this test for robustness of the main results with regard to scaling of the outcome variable was successful.\n\n**Figure 9: Robustness Test II: Alternative scalings of rank improvement**\n\n\n### 3.3 Internal Validity of the RD Design\nEstablishing internal validity is a prerequisite of the regression discontinuity design to be able to identify treatment effects in the same way a randomized trial does (Jacob et al. 2012). Therefore, it is crucial to rule out a non-random distribution of observations around the cutoff value of the treatment variable. In the context of the replicated article this means that municipalities around the cutoff value in the margin of victory of the mayor must not systematically differ in their characteristics. In other words, we need to rule out other drivers and channels through which a correlation between the rating variable (i.e. the margin of victory) and the outcome (rank improvements) might arise.\n\n#### 3.3.1 Pretreatment Municipality Characteristics\nThe first test of validity the authors present adresses whether the RD design truly achieves a local randomization around the cutoff. If this is the case, then both, municipalities that are just below the cutoff of MoV = 0 and those just above this threshold should show the same distribution of characteristics. This is investigated using a t-test for differences in means of these characteristics in the year before the mayor election. Subsequently, a regression analysis is used to test for a correlation of the municipalities characteristics prior the mayor election and the elected mayors' genders. If observations are truly randomized around the cutoff value, we should not see any correlation between these characteristics and the mayors' genders.\n\nIn a first step, we will have a look at the municipalities' characteristics one year before a mayor election and perform a t-test to explore whether there are differences between municipalities in which a male candidate won the mixed-gender election and municipalities in which a female won the mixed-gender mayor election. This comparison will be performed for all mixed-gender elections as well as for close those mixed-gender elections only (i.e., with a margin of victory below 10%).\n\n\n\n```python\n# t-test for equality of means of muni's characteristics\n\n# Merge data on mayor elections with municipalities' characteristics in the year prior the mayor election\n# only keep observations on mixed gender elections\ndf_pretreatment_characteristics = df_mayor_election_data.loc[df_mayor_election_data.rdd_sample == 1].copy()\n\n# merge with muni's characteristics in previous year\n# comment out -1 in following line to get the same results the authors report.\ndf_pretreatment_characteristics[\"char_year\"] = df_pretreatment_characteristics.jahr -1\ndf_pretreatment_characteristics = df_pretreatment_characteristics.merge(right=df_municipality_characteristics, \n                                      how=\"left\", \n                                      left_on=[\"gkz\", \"char_year\"], \n                                      right_on=[\"gkz\", \"jahr\"], \n\n)\n# We want to perform t-tests twice: for all mixed-gender elections and only \"close\" ones with MoV < 10 %\nbandwidths = [100, 10]\n\n# get results from the function in the auxiliary file\nrslt_dict = ttest_mean_characteristics(df=df_pretreatment_characteristics, bw=bandwidths)\n\nfor k in rslt_dict.keys():\n    print(\"For a margin of victory of \" + str(k) + \" or less :\")\n    display(rslt_dict[k])\n```\n\n    For a margin of victory of 100 or less :\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>female_mayor</th>\n      <th>male_mayor</th>\n      <th>Diff.</th>\n      <th>Obs.</th>\n      <th>t_test_p</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>log_bevoelkerung</th>\n      <td>9.383204</td>\n      <td>9.211695</td>\n      <td>0.171510</td>\n      <td>268</td>\n      <td>0.159</td>\n    </tr>\n    <tr>\n      <th>log_flaeche</th>\n      <td>3.631587</td>\n      <td>3.611326</td>\n      <td>0.020261</td>\n      <td>268</td>\n      <td>0.840</td>\n    </tr>\n    <tr>\n      <th>log_debt_pc</th>\n      <td>-0.376616</td>\n      <td>-0.543338</td>\n      <td>0.166723</td>\n      <td>268</td>\n      <td>0.163</td>\n    </tr>\n    <tr>\n      <th>log_tottaxrev_pc</th>\n      <td>-0.389292</td>\n      <td>-0.458939</td>\n      <td>0.069647</td>\n      <td>268</td>\n      <td>0.186</td>\n    </tr>\n    <tr>\n      <th>log_tot_beschaeft_pc</th>\n      <td>-1.623035</td>\n      <td>-1.548890</td>\n      <td>-0.074145</td>\n      <td>268</td>\n      <td>0.330</td>\n    </tr>\n    <tr>\n      <th>log_female_share_totbesch</th>\n      <td>-0.832952</td>\n      <td>-0.850199</td>\n      <td>0.017247</td>\n      <td>268</td>\n      <td>0.549</td>\n    </tr>\n    <tr>\n      <th>log_gemeinde_beschaef_pc</th>\n      <td>-5.129807</td>\n      <td>-5.160559</td>\n      <td>0.030752</td>\n      <td>268</td>\n      <td>0.558</td>\n    </tr>\n    <tr>\n      <th>log_female_sh_gem_besch</th>\n      <td>-1.088507</td>\n      <td>-1.148531</td>\n      <td>0.060024</td>\n      <td>264</td>\n      <td>0.226</td>\n    </tr>\n    <tr>\n      <th>log_prod_share_tot</th>\n      <td>-1.116977</td>\n      <td>-1.042058</td>\n      <td>-0.074919</td>\n      <td>268</td>\n      <td>0.269</td>\n    </tr>\n    <tr>\n      <th>log_female_share_prod</th>\n      <td>-1.498887</td>\n      <td>-1.467056</td>\n      <td>-0.031831</td>\n      <td>268</td>\n      <td>0.449</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    For a margin of victory of 10 or less :\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>female_mayor</th>\n      <th>male_mayor</th>\n      <th>Diff.</th>\n      <th>Obs.</th>\n      <th>t_test_p</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>log_bevoelkerung</th>\n      <td>9.818720</td>\n      <td>9.222251</td>\n      <td>0.596469</td>\n      <td>55</td>\n      <td>0.056</td>\n    </tr>\n    <tr>\n      <th>log_flaeche</th>\n      <td>3.972175</td>\n      <td>3.771001</td>\n      <td>0.201174</td>\n      <td>55</td>\n      <td>0.311</td>\n    </tr>\n    <tr>\n      <th>log_debt_pc</th>\n      <td>-0.329899</td>\n      <td>-0.291191</td>\n      <td>-0.038708</td>\n      <td>55</td>\n      <td>0.882</td>\n    </tr>\n    <tr>\n      <th>log_tottaxrev_pc</th>\n      <td>-0.252976</td>\n      <td>-0.356741</td>\n      <td>0.103766</td>\n      <td>55</td>\n      <td>0.386</td>\n    </tr>\n    <tr>\n      <th>log_tot_beschaeft_pc</th>\n      <td>-1.330126</td>\n      <td>-1.505435</td>\n      <td>0.175308</td>\n      <td>55</td>\n      <td>0.261</td>\n    </tr>\n    <tr>\n      <th>log_female_share_totbesch</th>\n      <td>-0.892789</td>\n      <td>-0.880949</td>\n      <td>-0.011841</td>\n      <td>55</td>\n      <td>0.842</td>\n    </tr>\n    <tr>\n      <th>log_gemeinde_beschaef_pc</th>\n      <td>-4.922467</td>\n      <td>-5.111784</td>\n      <td>0.189317</td>\n      <td>55</td>\n      <td>0.219</td>\n    </tr>\n    <tr>\n      <th>log_female_sh_gem_besch</th>\n      <td>-1.058962</td>\n      <td>-1.097358</td>\n      <td>0.038396</td>\n      <td>55</td>\n      <td>0.693</td>\n    </tr>\n    <tr>\n      <th>log_prod_share_tot</th>\n      <td>-1.005072</td>\n      <td>-0.963759</td>\n      <td>-0.041313</td>\n      <td>55</td>\n      <td>0.744</td>\n    </tr>\n    <tr>\n      <th>log_female_share_prod</th>\n      <td>-1.542579</td>\n      <td>-1.479899</td>\n      <td>-0.062680</td>\n      <td>55</td>\n      <td>0.546</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\nIn comparison to the results of this analysis which are presented in table A4 by the authors (see figure 10 below), small differences can be seen. It is possible to replicate the results presented by the authors if, instead of considering the municipalities' characteristics of the *year preceding* the mayor election, one considers the characteristics of the *same year* as the mayor election. The results shown in this notebook, however, are calculated in accordance to the intuition discussed earlier: We want to find out, whether the RD design truly results in a local randomization, hence the municipalities closely around the cutoff must not significantly differ in characteristics that might have an impact on the outcome of a mixed gender mayor election. \n\nConsidering municipalities' characteristics of the year preceding the election will result in slightly different results than the ones presented by the authors. The authors argue, that when considering \n>all mixed-gender races, the share of women in local public employment \\[row log_female_sh_gem_besch\\] is 8 percent higher, while in the manufacturing sector \\[row log_female_share_prod\\] it is 8 percent lower in municipalities with female mayors. For close mixed-gender elections, we find only one significant difference: municipalities with female mayors have larger populations \\[row log_bevoelkerung\\] than municipalities with male mayors. Yet, the effect is only barely significant and may be explained by the highly skewed distribution of city sizes.\n\nThis replication is able to confirm these results with regard to the close mixed-gender elections. For all mixed-gender elections, however, no significant differences can be found comparing characteristics for one year before the election. Results of this test for differences in means show to be quite sensitive with respect to small changes in the year for which characteristics are observed. Particularly, estimations including all mixed-gender mayor elections change drastically (i.e. show significance for different characteristics) for small changes in the year for which these characteristics are observed. This limits robustness of these results, especially since one should not expect a characteristic like, e.g., the share of women in the manufacturing sector to change very rapidly from one year to the next.\n\nHowever, when assessing whether the local randomization around the cutoff truly is achieved, differences in characteristics of municipalities with close mixed-gender elections should be investigated in greater detail. Thus, the significant difference in population sizes of municipalities closely on either side of the cutoff really is what should be concerning when evaluating the internal validity of the RD design. Additionally, this difference shows to be robust with regard to changes in the year that is observed. Nevertheless, the authors argue that: \n>\"Yet, the effect is only barely significant and may be explained by the highly skewed distribution of city sizes.\"\n\nOverall, mixed results can be drawn from this analysis. While the authors argue that differences are rather small and might arise from a skewed distribution, it cannot be precluded that differences in characteristics (i.e. population sizes) have an impact on the distribution around the cutoff. This, particularly, holds for municipalities closely around the cutoff value. In case population size truly impacts the rating of municipalities around the threshold, the local randomization cannot be held on to. In consequence the RD design is likely to yield biased estimates for the causal impact of the treatment (Lee 2008). For this reason, I present further investigations on this aspect of local randomization in section 4 of this notebook, succeeding the replication of the article.\n\n**Figure 10: Validity test Ia: Differences in municipalitiy characteristics with female and male mayors**\n\n\nSubsequently, the authors analyze whether differences in municipalities are able to explain a discontinuity in rank improvements of female council candidates. This is done in two consecutive steps:\n1. Municipalities' characteristics are used to predict normalized rank improvements of council candidates.\n&rarr; See whether municipalities' characteristics have explanatory power on rank improvements.\n2. These prediced rank improvements are used as an endogenous variable in a RDD regression.\n&rarr; Can municipalities' characteristics explain a discontinuity in rank improvements?\n\nBoth these steps are replicated in the following cells.\n\nFirst, municipalities' characteristics are used to predict normalized rank improvement. The calculations in the article are resembled exactly by including all observations (*bw = 100*). However, it might by more relevant to check whether rank improvements can be predicted for municipalities in which the margin of victory is close to the cutoff value for two reasons:\n\n1. We want to preclude that differences in characteristics of municipalities lead to a non-random local distribution of municipalities around the cutoff.\n  \n2. We say earlier, that differences in municipalities' characteristics show more significance for close mixed-gender elections (i.e., those that end up closely to the cutoff) than for all mixed-gender elections.\n\nIn contrast to the analysis presented in the article, in particular table A5 of the online appendix, the following estimation, thus, does not include all mixed-gender elections but focusses of those with an absolute margin of victory (MoV) smaller then 10.\n\n\n```python\n# Define bandwidth of data around the cutoff value (measured in absolute values)\nbw=10\n\n# define working df that does not contain any missing values and only observations within given bw\ndf_predicted_rank_improvements = rdd_data.loc[abs(rdd_data[\"margin_1\"])<bw].dropna(subset=[\"margin_1\", \n                                                          \"gewinn_norm\", \n                                                          \"log_bevoelkerung\", \n                                                          \"log_flaeche\", \n                                                          \"log_debt_pc\", \n                                                          \"log_tottaxrev_pc\", \n                                                          \"log_gemeinde_beschaef_pc\", \n                                                          \"log_female_sh_gem_besch\", \n                                                          \"log_tot_beschaeft_pc\", \n                                                          \"log_female_share_totbesch\", \n                                                          \"log_prod_share_tot\", \n                                                          \"log_female_share_prod\"\n                                                         ]\n                                                )\n\n# Run regression of rank improvements on municipalities' characteristics\nmuni_characteristics = sm.OLS(endog=df_predicted_rank_improvements[\"gewinn_norm\"], \n       exog=df_predicted_rank_improvements[[\"log_bevoelkerung\", \n                      \"log_flaeche\", \n                      \"log_debt_pc\", \n                      \"log_tottaxrev_pc\", \n                      \"log_gemeinde_beschaef_pc\", \n                      \"log_female_sh_gem_besch\", \n                      \"log_tot_beschaeft_pc\", \n                      \"log_female_share_totbesch\", \n                      \"log_prod_share_tot\", \n                      \"log_female_share_prod\"\n                     ]]       \n      ).fit()\n\n# Add the predicted rank improvement to the dataframe as it is needed in subceeding steps\ndf_predicted_rank_improvements[\"pred_rank_improvement\"] = muni_characteristics.predict()\n\n# Show regression summary\nmuni_characteristics.summary()\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>       <td>gewinn_norm</td>   <th>  R-squared:         </th> <td>   0.022</td> \n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.017</td> \n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   4.017</td> \n</tr>\n<tr>\n  <th>Date:</th>             <td>Thu, 01 Aug 2019</td> <th>  Prob (F-statistic):</th> <td>1.83e-05</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>01:33:18</td>     <th>  Log-Likelihood:    </th> <td> -6735.1</td> \n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>  1780</td>      <th>  AIC:               </th> <td>1.349e+04</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>  1770</td>      <th>  BIC:               </th> <td>1.355e+04</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>    10</td>      <th>                     </th>     <td> </td>    \n</tr>\n<tr>\n  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>    \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n              <td></td>                 <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>log_bevoelkerung</th>          <td>    0.6205</td> <td>    0.326</td> <td>    1.902</td> <td> 0.057</td> <td>   -0.019</td> <td>    1.260</td>\n</tr>\n<tr>\n  <th>log_flaeche</th>               <td>   -0.0003</td> <td>    0.565</td> <td>   -0.000</td> <td> 1.000</td> <td>   -1.109</td> <td>    1.108</td>\n</tr>\n<tr>\n  <th>log_debt_pc</th>               <td>   -0.2981</td> <td>    0.362</td> <td>   -0.824</td> <td> 0.410</td> <td>   -1.008</td> <td>    0.412</td>\n</tr>\n<tr>\n  <th>log_tottaxrev_pc</th>          <td>   -1.9253</td> <td>    1.176</td> <td>   -1.637</td> <td> 0.102</td> <td>   -4.233</td> <td>    0.382</td>\n</tr>\n<tr>\n  <th>log_gemeinde_beschaef_pc</th>  <td>    1.5837</td> <td>    0.583</td> <td>    2.717</td> <td> 0.007</td> <td>    0.440</td> <td>    2.727</td>\n</tr>\n<tr>\n  <th>log_female_sh_gem_besch</th>   <td>    0.1834</td> <td>    1.004</td> <td>    0.183</td> <td> 0.855</td> <td>   -1.785</td> <td>    2.152</td>\n</tr>\n<tr>\n  <th>log_tot_beschaeft_pc</th>      <td>   -0.3582</td> <td>    0.919</td> <td>   -0.390</td> <td> 0.697</td> <td>   -2.160</td> <td>    1.443</td>\n</tr>\n<tr>\n  <th>log_female_share_totbesch</th> <td>    2.6888</td> <td>    2.627</td> <td>    1.023</td> <td> 0.306</td> <td>   -2.464</td> <td>    7.842</td>\n</tr>\n<tr>\n  <th>log_prod_share_tot</th>        <td>   -1.4404</td> <td>    0.934</td> <td>   -1.543</td> <td> 0.123</td> <td>   -3.272</td> <td>    0.391</td>\n</tr>\n<tr>\n  <th>log_female_share_prod</th>     <td>   -1.2761</td> <td>    1.098</td> <td>   -1.162</td> <td> 0.245</td> <td>   -3.429</td> <td>    0.877</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>543.706</td> <th>  Durbin-Watson:     </th> <td>   2.094</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>4193.135</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.215</td>  <th>  Prob(JB):          </th> <td>    0.00</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>10.116</td>  <th>  Cond. No.          </th> <td>    144.</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\nTwo characteristics of the municipalities reveal to be significantly correlated with the rank improvement of a female candidate: Population size of the municipality (10% level) and per capita government employees (1% level). In addition, the regressor tax revenues per capita just barely misses to 10% significance threshold.  \n\nWhile the population size appears to be significantly positive correlated with rank improvement, the effect is quite small and does not seem to be of high economic significance: An increase of 1 % in population is associated with an increase in rank improvement of a female council candidate of approximately 0.62/100 normalized ranks. For the median size of a council (31 seats) this corresponds to 0.192 ranks.\nSimilarly, an increase in government employees is associated with an positive rank improvement of a female council candidate of approximately 0.490 ranks for the median council size.\n\nIn the second step, the authors use the prediction for rank improvements from above OLS model and test whether a discontinuity around the cutoff value of a margin of victory for a female mayor can be determined.\n\n\n```python\n# Use predicted values from above regression as endogenous variable in a regresion of female mayor on \n# rank improvements (main model).\n\n# Keep only 1 observation for each council election, since muni's characteristics dont vary within that\ndf_predicted_rank_improvements.drop_duplicates(subset=[\"gkz\", \"pred_rank_improvement\"], inplace=True)\n\n# Set the bandwidth (taken from the paper)\nbw = 18.81\n\n\n# Get regression weights\ndf_predicted_rank_improvements[\"weight\"] = calculate_weights(df=df_predicted_rank_improvements, bandwidth=bw)\n\n# Run regression for predicted normalized rank improvement of female candidates on gender of mayor\nsm.WLS(endog=df_predicted_rank_improvements.loc[\n    abs(df_predicted_rank_improvements[\"margin_1\"])<bw][\"pred_rank_improvement\"\n        ], \n       exog=sm.add_constant(df_predicted_rank_improvements.loc[abs(df_predicted_rank_improvements[\"margin_1\"])<bw][[\n           \"female_mayor\", \"margin_1\", \"inter_1\"\n       ]]), \n       weights=df_predicted_rank_improvements.loc[abs(df_predicted_rank_improvements[\"margin_1\"])<bw][\"weight\"],\n      ).fit().summary()\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>WLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>    <td>pred_rank_improvement</td> <th>  R-squared:         </th> <td>   0.267</td>\n</tr>\n<tr>\n  <th>Model:</th>                     <td>WLS</td>          <th>  Adj. R-squared:    </th> <td>   0.213</td>\n</tr>\n<tr>\n  <th>Method:</th>               <td>Least Squares</td>     <th>  F-statistic:       </th> <td>   4.979</td>\n</tr>\n<tr>\n  <th>Date:</th>               <td>Thu, 01 Aug 2019</td>    <th>  Prob (F-statistic):</th>  <td>0.00489</td>\n</tr>\n<tr>\n  <th>Time:</th>                   <td>01:33:18</td>        <th>  Log-Likelihood:    </th> <td> -70.532</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>        <td>    45</td>         <th>  AIC:               </th> <td>   149.1</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>            <td>    41</td>         <th>  BIC:               </th> <td>   156.3</td>\n</tr>\n<tr>\n  <th>Df Model:</th>                <td>     3</td>         <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>        <td>nonrobust</td>       <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n        <td></td>          <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>const</th>        <td>   -1.3275</td> <td>    0.495</td> <td>   -2.684</td> <td> 0.010</td> <td>   -2.326</td> <td>   -0.329</td>\n</tr>\n<tr>\n  <th>female_mayor</th> <td>    2.6348</td> <td>    0.783</td> <td>    3.366</td> <td> 0.002</td> <td>    1.054</td> <td>    4.216</td>\n</tr>\n<tr>\n  <th>margin_1</th>     <td>   -0.1746</td> <td>    0.093</td> <td>   -1.887</td> <td> 0.066</td> <td>   -0.361</td> <td>    0.012</td>\n</tr>\n<tr>\n  <th>inter_1</th>      <td>    0.0414</td> <td>    0.141</td> <td>    0.293</td> <td> 0.771</td> <td>   -0.244</td> <td>    0.327</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td> 0.923</td> <th>  Durbin-Watson:     </th> <td>   1.260</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.630</td> <th>  Jarque-Bera (JB):  </th> <td>   0.831</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 0.014</td> <th>  Prob(JB):          </th> <td>   0.660</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 2.335</td> <th>  Cond. No.          </th> <td>    29.4</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n\nAt this point, noticeable differences in results arise between the article and this replication. As seen in figure 11 below, the authors do not find a statistically significant estimate for the *female_mayor* dummy. However, the specification presented above does indicate a significant discontinuity in predicted normalized rank improvements around the cutoff at the 1% significance level. Indeed, the point estimate for the *female_mayor* dummy results to be approximately 2.63, which translates to circa 0.82 ranks for the median council size. To illustrate the scale of this effect: This amounts to approximately 71% of the size of the estimated effect for the main model (see section 2.2.1: Regression Results).\n\n**Figure 11: Validity test Ib: Discontinuity in predicted rank improvements based on municipality characteristics**\n\n\nSummarizing, the presented results differ from those presented in the article by changing the bandwidth of data included. While the authors find no significant discontinuity and, thus, do not reject a successful local randomization by the RD design, the results presented in this notebook cannot support this conclusion. In contrast to the conclusions drawn in the article, this analysis does not preclude a non-random distribution of the rating variable around the cutoff value. Indeed, these results indicate that municipalities' charateristics for the *year before* the close mixed-gender election happened (i.e. *pretreatment*) are associated with the rank improvements of a female council candidate.\n\n#### 3.3.2 Discontinuity in Density\n\nThe next test with regard to internal validity that is presented by the authors is a test for a \"discontinuity in density of the running variable at the threshold\". That is, if there is a discontinuity in margins of victory that are closely around the cutoff value of 0. The result of this test can be seen in figure 12 below (figure A.2 in the article's online appendix). It is little surprising that a discontinuity cannot be found. Indeed, it is highly implausible that a council candidate can choose into treatment by raising the MoV of a mayor candidate to be just above the threshold of 0.\n\n**Figure 12: Validity test IIa: McCrary density plot**\n\n\nIn a related validity check, the authors test whether men and women are equally likely to win a mixed-gender mayor election. Particularly, if the likelihood of a victory is equal in close mixed-gender elections. The results as they are presented by the authors in table A.6 of the online appendix can be seen in figure 13 below.\n\n**Figure 13: Validity test IIb: Mixed-gender mayor elections and female victories**\n\n\n\n```python\n# Calculate the a priori probabilities of winning a mixed-gender election \n# as the share of elections they where actually won by each gender.\nrslt_dict = {}\nbandwidths = [100, 25, 10]\n\n# Loop over different bandwiths of data to consider\nfor bw in bandwidths:\n    # Select data\n    data = df_mayor_election_data.loc[\n        (df_mayor_election_data[\"rdd_sample\"]==1) & (abs(df_mayor_election_data[\"margin_1\"])<=bw)\n    ]\n    \n    # Write mean, difference in means, N and p-value of the t-test into a frame\n    container = pd.DataFrame(index=[1])\n    container[\"Mean female win\"] = (data[\"female_mayor\"].sum() / data.female_mayor.count()).round(3)\n    container[\"Diff.\"] = (2 * container[\"Mean female win\"] - 1).round(3)\n    container[\"Obs.\"] = data[\"female_mayor\"].count()\n    satistic, p_value = ttest_ind(data[\"female_mayor\"], data[\"male_mayor\"])\n    container[\"t_test_p\"] = p_value.round(3)\n    \n    # return results in a dictionary\n    rslt_dict[bw] = container\n\n# Print resulting dict in an understanable way\nfor k in rslt_dict.keys():\n    print(\"t-Test for differences in means for a bandwidth of {}\".format(k))\n    display(rslt_dict[k])\n```\n\n    t-Test for differences in means for a bandwidth of 100\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Mean female win</th>\n      <th>Diff.</th>\n      <th>Obs.</th>\n      <th>t_test_p</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>0.313</td>\n      <td>-0.374</td>\n      <td>268</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    t-Test for differences in means for a bandwidth of 25\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Mean female win</th>\n      <th>Diff.</th>\n      <th>Obs.</th>\n      <th>t_test_p</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>0.405</td>\n      <td>-0.19</td>\n      <td>126</td>\n      <td>0.002</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    t-Test for differences in means for a bandwidth of 10\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Mean female win</th>\n      <th>Diff.</th>\n      <th>Obs.</th>\n      <th>t_test_p</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>0.527</td>\n      <td>0.054</td>\n      <td>55</td>\n      <td>0.571</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\nThe results of this validity test can successfully be replicated. Just like presented by the authors, there is significant differences in the probability of a woman to win the mayoral election for large bandwidths, i.e. when not only close mixed-gender elections are considered. The significance in this difference, however, cannot be seen for mixed-gender elections with a MoV of 10% or lower. Thus, there is no reason to believe that either gender has a higher chance of winning close elections. This supports the hypotheses of a local randomization around the cutoff.\n\n#### 3.3.3. Confoundness with Mayor Ideology\nThe final concern the authors adress in the regard of internal validity are confounding effects due the political identity of mayors and council candidates. This might arise if males and females differ in their party affiliation. For example, female politicians might be more likely to be affiliated with left-wing parties. In this case, the success of a female council candidate in a municipality with a female mayor might be driven by their similar political affiliation and trends in general popularity of political ideologies, rather than a decrease in anti-female voters bias.\n\nIn the article, this is approached by testing for differences in ideology of female and male mayors. Results of this test are provided in table A.7 of the online appendix and can be found in figure 14 below. Again, the authors investigate both, the whole sample of mixed-gender mayor elections and a subsample of those with a MoV smaller 10%. Overall, differences in the ideology of mayors in mixed-gender elections do not show statistical significance. Hence, it is implausible to argue that election outcomes of council candidates are related to these differences.\n\n**Figure 14: Validity test III: Differences in ideology of female and male mayors**\n\n\n\n```python\n# Run a t-test for differences in the shares of party affiliation for male and female \n# mayors that won a mixed-gender election\n\n# Set the list of bandwiths for which these differences should be calculated\nbandwidths = [100, 25, 10]\n\n# get results from the function in the auxiliary file\nrslt_dict = party_affiliation(df=df_mayor_election_data, bw=bandwidths)\n    \n# Print resulting dict in an understanable way\nfor k in rslt_dict.keys():\n    print(\"t-Test for differences in shares of mayors that are\"+\n          \"affilited with each party for a bandwidth of {}\".format(k)\n         )\n    display(rslt_dict[k])\n```\n\n    t-Test for differences in shares of mayors that areaffilited with each party for a bandwidth of 100\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>female_mayor_shares</th>\n      <th>male_mayor_shares</th>\n      <th>p_value</th>\n      <th>difference</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>cdu</th>\n      <td>0.31</td>\n      <td>0.315</td>\n      <td>0.926</td>\n      <td>-0.005</td>\n    </tr>\n    <tr>\n      <th>spd</th>\n      <td>0.44</td>\n      <td>0.386</td>\n      <td>0.400</td>\n      <td>0.054</td>\n    </tr>\n    <tr>\n      <th>other_party</th>\n      <td>0.25</td>\n      <td>0.299</td>\n      <td>0.412</td>\n      <td>-0.049</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    t-Test for differences in shares of mayors that areaffilited with each party for a bandwidth of 25\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>female_mayor_shares</th>\n      <th>male_mayor_shares</th>\n      <th>p_value</th>\n      <th>difference</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>cdu</th>\n      <td>0.333</td>\n      <td>0.373</td>\n      <td>0.649</td>\n      <td>-0.040</td>\n    </tr>\n    <tr>\n      <th>spd</th>\n      <td>0.392</td>\n      <td>0.293</td>\n      <td>0.252</td>\n      <td>0.099</td>\n    </tr>\n    <tr>\n      <th>other_party</th>\n      <td>0.275</td>\n      <td>0.333</td>\n      <td>0.487</td>\n      <td>-0.058</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    t-Test for differences in shares of mayors that areaffilited with each party for a bandwidth of 10\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>female_mayor_shares</th>\n      <th>male_mayor_shares</th>\n      <th>p_value</th>\n      <th>difference</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>cdu</th>\n      <td>0.448</td>\n      <td>0.308</td>\n      <td>0.293</td>\n      <td>0.140</td>\n    </tr>\n    <tr>\n      <th>spd</th>\n      <td>0.276</td>\n      <td>0.308</td>\n      <td>0.800</td>\n      <td>-0.032</td>\n    </tr>\n    <tr>\n      <th>other_party</th>\n      <td>0.276</td>\n      <td>0.385</td>\n      <td>0.400</td>\n      <td>-0.109</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\nFirst of all, the results regarding differences in party affiliation of mayors of different gender as presented in the article can be replicated. From these results it can be seen that independent of the bandwidth selection around the cutoff value, mayors of different sexes reveal quite little differences in their party affiliation. In addition, none of these differences prove to be statistically significant. \n\nBuilding on this result, one can argue that differences in political ideology between male and female politicians are not driving the observed association of mayors that won a close mixed-gender election with rank improvements of council candidates of the same sex. Thus, a confoundedness of mayors' and council candidates' ideologies can be ruled out as an explanation of the main results presented in section 2.2.1.\n\n## 4. Independent Contribution: On Internal Validity of the RD Design\nValidity of the RD design as it is presented in the replicated article is discussed in section 3 of this notebook. In this context, I argue that significant differences in population sizes of municipalities closely below and closely above the threshold value of MoV = 0% might be a reason to question whether the RD design truly achieves a local randomization. It is shown that means of population sizes significantly differ between both sides of the threshold.\n\nFurthermore, using municipalitie's characteristics to predict rank improvements of council candidates (section 3.3.1) revealed a significant positive correlation between population size and rank improvements. This resulted from an estimation that only included observations that were within a 10 percentage point range around the cutoff value of MoV.\n\nA local randomization with regard to population sizes does not seem very convincing. Therefore, an alternative estimation model for the correlation between a female mayor and rank improvements of female council candidates is presented in the following which includes population size as a predictor. The model follows equation (4) which is equivalent to equation (3) (main model) appended by the population of the municipality in logs as well as an interaction term between the female mayor dummy and population in logs. \n\n\\begin{align}\n    normalized\\_rank\\_improvement_i = \\beta_0 + \\beta_1 D_{f\\_mayor, i} + \\beta_2 MoV_i + \\beta_3 D_{f\\_mayor, i} * MoV_i  + \\\\ \\beta_4 log(population_i) + \\beta_5 D_{f\\_mayor, i} * log(population_i) \\tag{4}\n\\end{align}\n\nThe estimation of this model follows the same WLS method as the estimation of the baseline results presented in section 3.2. A summary of the results of this regression can be seen below.\n\n\n```python\n# Add intercept of population size and MoV to regression data\ndf_population_regression = rdd_data.copy()\ndf_population_regression[\"inter_margin_pop\"] = df_population_regression[\"female_mayor\"] * df_population_regression[\"log_bevoelkerung\"]\n\n# Set the bandwidth \n#bw = 20\n#bw = 15\n#bw = 10\n\n# Get regression weights\ndf_population_regression[\"weight\"] = calculate_weights(df=df_population_regression, bandwidth=bw)\n\n# Run regression for approach (1): normalized rank improvement of female candidates on gender of mayor\nsm.WLS(endog=df_population_regression.loc[abs(df_population_regression[\"margin_1\"])<bw][\"gewinn_norm\"], \n       exog=sm.add_constant(df_population_regression.loc[abs(df_population_regression[\"margin_1\"])<bw][\n           [\"female_mayor\", \"margin_1\", \"inter_1\", \"log_bevoelkerung\", \"inter_margin_pop\"]\n       ]), \n       weights=df_population_regression.loc[abs(df_population_regression[\"margin_1\"])<bw][\"weight\"],\n      ).fit(cov_type=\"cluster\", \n             cov_kwds={\"groups\":df_population_regression.loc[abs(df_population_regression[\"margin_1\"])<bw][\"gkz\"]}\n            ).summary()\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>WLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>       <td>gewinn_norm</td>   <th>  R-squared:         </th> <td>   0.018</td> \n</tr>\n<tr>\n  <th>Model:</th>                   <td>WLS</td>       <th>  Adj. R-squared:    </th> <td>   0.015</td> \n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   16.10</td> \n</tr>\n<tr>\n  <th>Date:</th>             <td>Thu, 01 Aug 2019</td> <th>  Prob (F-statistic):</th> <td>2.49e-08</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>01:33:18</td>     <th>  Log-Likelihood:    </th> <td> -6966.8</td> \n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>  1784</td>      <th>  AIC:               </th> <td>1.395e+04</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>  1778</td>      <th>  BIC:               </th> <td>1.398e+04</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     5</td>      <th>                     </th>     <td> </td>    \n</tr>\n<tr>\n  <th>Covariance Type:</th>       <td>cluster</td>     <th>                     </th>     <td> </td>    \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n          <td></td>            <th>coef</th>     <th>std err</th>      <th>z</th>      <th>P>|z|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>const</th>            <td>   -5.8585</td> <td>    4.165</td> <td>   -1.406</td> <td> 0.160</td> <td>  -14.022</td> <td>    2.305</td>\n</tr>\n<tr>\n  <th>female_mayor</th>     <td>    2.2883</td> <td>    4.668</td> <td>    0.490</td> <td> 0.624</td> <td>   -6.861</td> <td>   11.438</td>\n</tr>\n<tr>\n  <th>margin_1</th>         <td>   -0.1434</td> <td>    0.124</td> <td>   -1.161</td> <td> 0.246</td> <td>   -0.386</td> <td>    0.099</td>\n</tr>\n<tr>\n  <th>inter_1</th>          <td>   -0.0377</td> <td>    0.207</td> <td>   -0.182</td> <td> 0.855</td> <td>   -0.443</td> <td>    0.368</td>\n</tr>\n<tr>\n  <th>log_bevoelkerung</th> <td>    0.4705</td> <td>    0.414</td> <td>    1.137</td> <td> 0.256</td> <td>   -0.341</td> <td>    1.282</td>\n</tr>\n<tr>\n  <th>inter_margin_pop</th> <td>    0.0820</td> <td>    0.442</td> <td>    0.186</td> <td> 0.853</td> <td>   -0.784</td> <td>    0.948</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td>694.757</td> <th>  Durbin-Watson:     </th> <td>   2.110</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.000</td>  <th>  Jarque-Bera (JB):  </th> <td>8850.060</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td> 1.461</td>  <th>  Prob(JB):          </th> <td>    0.00</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td>13.513</td>  <th>  Cond. No.          </th> <td>    419.</td>\n</tr>\n</table><br/><br/>Warnings:<br/>[1] Standard Errors are robust tocluster correlation (cluster)\n\n\n\nThe estimation results of this model reveal noticeable differences to the results presented for the baseline model. First, the estimation for the female mayor dummy is not significant in this estimation. Hence, the discontinuity in rank improvements at the cutoff is not significant for this estimation. Second, the only predictor that is significantly correlated with the outcome is the population size of the municipality. Third, the adjusted R-Squared is increased by approximately 50% in comparison to the baseline model. Changes in the bandwidth result in changes in the adjusted R-squared. However, this 50% increase appears to mark a lower bound.\n\nSince a python package for an optimal bandwidth selection that implements the method used in the article is not available, estimation results were calculated using an array of different bandwidths. This can be adjusted by modifying above cell. The currently chosen bandwidth of 15 is used since it fits in the range of different bandwidths that are presented by the authors for different estimations. Generally, optimal bandwidths throughout this article range from 15 to 20. These results are very little affected by changes in the bandwidth.\n\nTo summarize, a comparison of characteristics of municipalities that lie respectively just below or above the cutoff value indicates that a local randomization might not have been achieved. In particular, population size appears to have explanatory power on the election success of female council candidates. Including population size as a covariate in the estimation model results in a non-significant discontinuity while increasing the adjusted R-Squared. Finally, without a random assignment into treated and untreated groups around the cutoff, the internal validity of an RD design must be taken into question, hence causal inference looses credibility in the RD design (see Lee, 2008 for a discussion).\n\n## 5. Conclusions\nThe replication of the baseline results of Baskaran & Hessami (2018) presented throughout this notebook yields exactly the same results as the authors present in their article. In addition to the results of the baseline model, I also (mostly successful) replicate the results presented on robustness tests as well as tests for internal validity of the regression discontinuity design. Furthermore, the scope of a mere replication is left at several points and additional analyses on the internal validity of the RD design are presented. The results of this work can be summarized as follows.\n\nFirst, it was possible to replicate the baseline estimations. Using the data set as it is provided by the authors, a weighted linear regression yields the exact same results that are presented in section *IV Main Results* of the article. \n\nSecond, I was able to replicate the results of the tests for robustness of these baseline regression results, in particular a placebo test as well as a test for different scalings of the outcome variable. In the context of the placebo test, I additionally present results of an even stricter specification. This specification addresses a potential weakness of the placebo test implemented in the article regarding an overlap of the tenure of a mayor and the time lag chosen by the authors. However, the results of the placebo test are not affected by this.\n\nThird, at least two of the three presented results of tests for the internal validity can be confirmed by this replication. That is, the results of the test for a discontinuity in density as well as for a confoundedness of council candidates with the mayor's ideology can be confirmed by this work.  Yet, the outcome of the replication regarding the pretreatment municipality characteristics needs to be carried out in more detail. \n\nOne (minor) difference between the test results presented in the article and the outcome of their replication is based on a difference in coding. For the intuition of a pretreatment analysis it is argued that characteristics of municipalities which are respectively just below or barely above the cutoff value of the rating variable should be compared for a time before the treatment is in place. That is, before a close mixed-gender election was won by either candidate. Hence, the results presented in this notebook stem from a comparison of characteristics in the year before the mayor election. In the article, however, differences are calculated for the same year as the mayor election.\n\nThe more important difference in results, however, can be found in the succeding analysis. Here, municipalities' characteristics are used to predict rank improvements of council candidates. While the authors perform this analysis for all municipalities with mixed-gender mayor elections, I argue that a more relevant insight would result by focusing on close mixed-gender elections, only. Contrary to the results presented by the authors, including only this smaller set of municipalities indeed results in significant estimates for some of the characteristics, including the municipalities' population size.\n\nSubsequently, the resulting predicted rank improvements are tested for a discontinuity at the cutoff value of the rating variable. Again, in contrast to the results presented in the article the alternative specification presented in this notebook yields a significant estimate of relevant magnitude for this discontinuity. In particular, the main results indicate a discontinuity of approximately magnitude 3.7 while the point estimate for this discontinuity takes a value of circa 2.6 for the alternative specification.\n\nBased on these results, I propose a modified specification of the original regression model which includes population size as an additional predictor. An estimation of this specification yields a positive and significant coefficient for population size, indicating a positive association of population size and the normalized rank improvements of female council candidates, even within a small bandwidth around the cutoff value of the rating variable. Additionally, this specification does not result in significant estimations for the effect of a female mayor. \n\nThe results of these regression analyses put a question mark on the internal validity of the RD design presented by the authors. However, further investigations on this particular aspect of the relationship between rank improvements of female council candidates and the population sizes of municipalities would be needed to take a final position on the relation between female mayors and success of female council candidates. \n\n## References\n**Baskaran, T., & Hessami, Z.** (2018) Does the Election of a Female Leader Clear the Way for More Women in Politics? *American Economic Journal: Economic Policy*, 10(3): 91-121\n\n**Jacob, R., Zhu, P., Somers, M. A., & Bloom, H.** (2012). A Practical Guide to Regression Discontinuity. MDRC.\n\n**Lee, D. S.** (2008). Randomized experiments from non-random selection in US House elections. *Journal of Econometrics*, 142(2), 675-697\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "209a345add71be8eba2925f883236b6932883903", "size": 230489, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "student_project.ipynb", "max_stars_repo_name": "DaLueke/replication-baskeran-hessami-2018", "max_stars_repo_head_hexsha": "3ef606ba3ca82a726484f4f6da5dcb8f1373064f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "student_project.ipynb", "max_issues_repo_name": "DaLueke/replication-baskeran-hessami-2018", "max_issues_repo_head_hexsha": "3ef606ba3ca82a726484f4f6da5dcb8f1373064f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "student_project.ipynb", "max_forks_repo_name": "DaLueke/replication-baskeran-hessami-2018", "max_forks_repo_head_hexsha": "3ef606ba3ca82a726484f4f6da5dcb8f1373064f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.7436378248, "max_line_length": 29804, "alphanum_fraction": 0.5545774419, "converted": true, "num_tokens": 37033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116407397951, "lm_q2_score": 0.10970577969958141, "lm_q1q2_score": 0.043861647780328146}}
{"text": "____\n__Universidad Tecnol\u00f3gica Nacional, Buenos Aires__<br/>\n__Ingenier\u00eda Industrial__<br/>\n__C\u00e1tedra de Ciencia de Datos - Curso I5521 - Turno sabado ma\u00f1ana__<br/>\n__Elaborado por: Martin Palazzo__\n____\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/gdrive')\n```\n\n    Drive already mounted at /gdrive; to attempt to forcibly remount, call drive.mount(\"/gdrive\", force_remount=True).\n\n\n\n```python\nDRIVE_FOLDER = 'ClusterAI2020/'\nCLASS_FOLDER = 'clase_01/'\nDATA_PATH = \"../data/clase_01/\"\n%cd {'/gdrive/My Drive/'+DRIVE_FOLDER+CLASS_FOLDER}\n```\n\n    /gdrive/My Drive/ClusterAI2020/clase_01\n\n\nEn este script continuaremos el an\u00e1lisis exploratorio de datos que comenzamos la clase pasada con el dataset de subtes\n\n# clase_01: Importar data, describirla y visualizarla.\n\nEn esta segunda clase aprenderemos a realizar correlaciones lineales de Pearson, visualizar boxplots, comprender los quantiles de un set de datos y eliminar outliers observando que quantil (percentil) nos ayuda a filtrar. Primero haremos un repaso sobre el analisis exploratorio de subtes que realizamos la semana pasada. \n\n**Importamos las Librer\u00edas necesarias:** Utilizaremos Numpy para realizar calculos matriciales, pandas para manejar los datos y almacenarlos, y matplotlib junto con Seaborn para visualizar.\n\n\n```python\n# importamos las librer\u00edas necesarias para trabajar.\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n```\n\n**Read_CSV:** Descargamos de https://data.buenosaires.gob.ar/dataset/subte-viajes-molinetes el dataset de usuarios de subte por molinete del a\u00f1o 2017. Luego con el comando de Pandas \"pd.read_csv\" indicamos donde se ubica el dataset a ser leido. Una vez leido guardamos la tabla como un DataFrame de Pandas en el elemento \"molinetes\". \n\n\n```python\n# importante detallar que el delimiter indica como estan separadas las columnas en el dataframe.\nmolinetes = pd.read_csv(DATA_PATH+'molinetes_2017.csv', delimiter=';')\n```\n\ncon el comando .head() observamos las primeras 5 filas de nuestro dataframe\n\n\n```python\n# con el comando .head() podemos ver en pantalla las primeras filas y del dataframe\nmolinetes.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>PERIODO</th>\n      <th>FECHA</th>\n      <th>DESDE</th>\n      <th>HASTA</th>\n      <th>LINEA</th>\n      <th>MOLINETE</th>\n      <th>ESTACION</th>\n      <th>PAX_PAGOS</th>\n      <th>PAX_PASES_PAGOS</th>\n      <th>PAX_FRANQ</th>\n      <th>TOTAL</th>\n      <th>ID</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>201701</td>\n      <td>01/01/2017</td>\n      <td>08:00:00</td>\n      <td>08:15:00</td>\n      <td>LINEA_H</td>\n      <td>LINEA_H_CASEROS_SUR_TURN02</td>\n      <td>CASEROS</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>201701</td>\n      <td>01/01/2017</td>\n      <td>08:00:00</td>\n      <td>08:15:00</td>\n      <td>LINEA_H</td>\n      <td>LINEA_H_CASEROS_NORTE_TURN02</td>\n      <td>CASEROS</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>201701</td>\n      <td>01/01/2017</td>\n      <td>08:15:00</td>\n      <td>08:30:00</td>\n      <td>LINEA_H</td>\n      <td>LINEA_H_CASEROS_SUR_TURN02</td>\n      <td>CASEROS</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>201701</td>\n      <td>01/01/2017</td>\n      <td>08:15:00</td>\n      <td>08:30:00</td>\n      <td>LINEA_H</td>\n      <td>LINEA_H_CASEROS_SUR_TURN01</td>\n      <td>CASEROS</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>201701</td>\n      <td>01/01/2017</td>\n      <td>08:30:00</td>\n      <td>08:45:00</td>\n      <td>LINEA_H</td>\n      <td>LINEA_H_CASEROS_NORTE_TURN01</td>\n      <td>CASEROS</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nRecordemos que el comando de numpy np.shape() nos indica las dimensiones de nuestro elemento, en este caso un dataframe de pandas.\n\n\n```python\n# si queremos saber cuantos renglones y columnas tiene el objeto en cuestion, utilizamos el comando de numpy \"shape\".\n# asi podemos ver que nuestro dataset posee mas de 11 millones de renglones y 12 columnas\nnp.shape(molinetes)\n```\n\n\n\n\n    (11938476, 12)\n\n\n\nImprimimos en pantalla un breve reporte de un rengl\u00f3n sobre las dimensiones de nuestro dataframe.\n\n\n```python\n# Ver que utilizamos la funci\u00f3n de numpy \"shape\".\nprint(\"El dataset importado tiene \"+ str(np.shape(molinetes)[0]) + \" renglones y \" + str(np.shape(molinetes)[1]) + \" columnas\")\n```\n\n    El dataset importado tiene 11938476 renglones y 12 columnas\n\n\nSi bien en nuestro dataset de subtes no existen columnas que tengan valores nulos o faltantes (NaNs) es necesario entender para otros datasets si hay valores faltantes para eliminarlos (o reemplazarlos por otro valor como la mediana).\n\n\n```python\n# revisamos si existen columnas que contengan valores faltantes (NaNs)\ncol_nulls = molinetes.isnull().any()\ncol_nulls\n```\n\n\n\n\n    PERIODO            False\n    FECHA              False\n    DESDE              False\n    HASTA              False\n    LINEA              False\n    MOLINETE           False\n    ESTACION           False\n    PAX_PAGOS          False\n    PAX_PASES_PAGOS    False\n    PAX_FRANQ          False\n    TOTAL              False\n    ID                 False\n    dtype: bool\n\n\n\n# Columnas e Indices en Pandas\n\n**Columnas e Indices en Pandas:** los dataframes de pandas se caracterizan por tener nombres expl\u00edcitos por columna y por rengl\u00f3n (indice). Es decir que podemos llamar a un elemento (o varios) de un DataFrame por el nombre de su columna e \u00edndice.\n\n\n```python\n# Obtenemos los nombres de las columnas del dataframe Molinetes\ncolumnas_molinetes = molinetes.columns\ncolumnas_molinetes\n```\n\n\n\n\n    Index(['PERIODO', 'FECHA', 'DESDE', 'HASTA', 'LINEA', 'MOLINETE', 'ESTACION',\n           'PAX_PAGOS', 'PAX_PASES_PAGOS', 'PAX_FRANQ', 'TOTAL', 'ID'],\n          dtype='object')\n\n\n\n\n```python\n# Obtenemos los nombres de los \u00edndices (renglones o instancias) del dataframe Molinetes.\n# Observamos que cuando imprimimos en pantalla los \u00edndices, fueron definidos al importar el csv con el parametro \n# \"index_col\" seleccionando la columna \"PERIODO\".\ninstancias_molinetes = molinetes.index\ninstancias_molinetes\n```\n\n\n\n\n    RangeIndex(start=0, stop=11938476, step=1)\n\n\n\n# Filtrar un dataframe por el valor de una columna\n\n**Filtrar un dataframe por el valor de una columna:** Inicialmente filtraremos nuestro dataframe \"molinetes_b\" por el valor \"LINEA_B\" de la columna \"LINEA\". Para eso usamos la funcion \".loc\" de pandas, sobre el dataframe.\n\n\n```python\n# como inicialmente queremos trabajar con los datos de la Linea B, filtramos por el valor \"LINEA_B\" de la columna\n# \"LINEA\" nuestro dataframe original llamado molinetes.\nmolinetes_b = molinetes.loc[molinetes['LINEA'] == 'LINEA_B']\n```\n\n\n```python\n# observamos que la cantidad de renglones del nuevo dataframe es menor al del original, puesto que solo \n# estamos considerando a los molinetes de la linea B\nnp.shape(molinetes_b)\n```\n\n\n\n\n    (2855204, 12)\n\n\n\n\n```python\nmolinetes_b.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>PERIODO</th>\n      <th>FECHA</th>\n      <th>DESDE</th>\n      <th>HASTA</th>\n      <th>LINEA</th>\n      <th>MOLINETE</th>\n      <th>ESTACION</th>\n      <th>PAX_PAGOS</th>\n      <th>PAX_PASES_PAGOS</th>\n      <th>PAX_FRANQ</th>\n      <th>TOTAL</th>\n      <th>ID</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2492243</th>\n      <td>201701</td>\n      <td>01/01/2017</td>\n      <td>08:00:00</td>\n      <td>08:15:00</td>\n      <td>LINEA_B</td>\n      <td>LINEA_B_FLORIDA_O_TURN01</td>\n      <td>FLORIDA</td>\n      <td>4</td>\n      <td>0</td>\n      <td>0</td>\n      <td>4</td>\n      <td>20</td>\n    </tr>\n    <tr>\n      <th>2492244</th>\n      <td>201701</td>\n      <td>01/01/2017</td>\n      <td>08:00:00</td>\n      <td>08:15:00</td>\n      <td>LINEA_B</td>\n      <td>LINEA_B_FLORIDA_O_TURN03</td>\n      <td>FLORIDA</td>\n      <td>3</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>20</td>\n    </tr>\n    <tr>\n      <th>2492245</th>\n      <td>201701</td>\n      <td>01/01/2017</td>\n      <td>08:00:00</td>\n      <td>08:15:00</td>\n      <td>LINEA_B</td>\n      <td>LINEA_B_FLORIDA_O_TURN02</td>\n      <td>FLORIDA</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>20</td>\n    </tr>\n    <tr>\n      <th>2492246</th>\n      <td>201701</td>\n      <td>01/01/2017</td>\n      <td>08:00:00</td>\n      <td>08:15:00</td>\n      <td>LINEA_B</td>\n      <td>LINEA_B_FLORIDA_O_TURN04</td>\n      <td>FLORIDA</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>20</td>\n    </tr>\n    <tr>\n      <th>2492247</th>\n      <td>201701</td>\n      <td>01/01/2017</td>\n      <td>08:15:00</td>\n      <td>08:30:00</td>\n      <td>LINEA_B</td>\n      <td>LINEA_B_FLORIDA_O_TURN01</td>\n      <td>FLORIDA</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>20</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nprint(\"Los registros de la linea B representan el \" + str(np.round(np.shape(molinetes_b)[0]/np.shape(molinetes)[0],2)) + \" de los registros totales\")\n```\n\n    Los registros de la linea B representan el 0.24 de los registros totales\n\n\n# Visualizacion: Countplot\n\nVisualizaci\u00f3n Countplot de Seaborn para las distintas lineas de subte.\n\n\n```python\n# con el comando \"countplot\" de Seaborn (importado como sns) generamos un gr\u00e1fico de barras por la columna \"LINEA\"\nsns.set_context(\"talk\")\naz = sns.countplot(x=\"LINEA\", data=molinetes)\nplt.xticks(rotation=45)\nplt.title(\"Viajes en molinetes por linea durante 2017\")\nplt.show()\n```\n\nVisualizaci\u00f3n de Countplot de Seaborn para las distintas estaciones de la linea B.\n\n\n```python\n# luego generamos un countplot de seaborn por la columna estaci\u00f3n, esta vez utilizando el nuevo dataframe filtrado\n# molinetes_b, que solo contiene los datos de la linea B.\nax = sns.countplot(x=\"ESTACION\", data=molinetes_b)\nax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha=\"right\")\nplt.title(\"\")\nplt.show()\n```\n\n# Visualizacion: Boxplot con Seaborn para linea B\nProcedemos a realizar un boxplot por cada estacion, cuantificando asi donde se concentran cada lapso de tiempo en viajes de molinete. Ver que siempre la cantidad de periodos de 15 mins entre el 1er y 3er cuartil esta por debajo de 100 viajes. Es importante comprender la diferencia entre el boxplot visualizado a continuacion y el countplot visualizado en el paso anterior. \u00bfQue cambia entre uno y otro?\n\n\n```python\nay = sns.boxplot(x = molinetes_b.ESTACION, y = molinetes_b.TOTAL, data = molinetes_b)\nay.set_xticklabels(ay.get_xticklabels(), rotation=40, ha=\"right\")\nplt.title(\"distribucion de cantidad de tickets en periodos de 15 mins\")\nplt.show()\n```\n\n# An\u00e1lisis de la estaci\u00f3n Lacroze de la linea B\nCreamos un dataframe llamado \"molinetes_lacroze\" que contiene unicamente las instancias del dataframe \"molinetes_b\" cuyo valor del atributo/feature \"ESTACION\" sea igual a \"FEDERICO LACROZE\"\n\n\n```python\n# filtramos con \".loc\" el dataframe \"molinetes_b\" por el valor \"Federico Lacroze\" de la columna \"Estacion\"\nmolinetes_lacroze = molinetes_b.loc[molinetes_b.ESTACION== 'FEDERICO LACROZE']\n```\n\n\n```python\nmolinetes_lacroze.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>PERIODO</th>\n      <th>FECHA</th>\n      <th>DESDE</th>\n      <th>HASTA</th>\n      <th>LINEA</th>\n      <th>MOLINETE</th>\n      <th>ESTACION</th>\n      <th>PAX_PAGOS</th>\n      <th>PAX_PASES_PAGOS</th>\n      <th>PAX_FRANQ</th>\n      <th>TOTAL</th>\n      <th>ID</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>7622359</th>\n      <td>201701</td>\n      <td>01/01/2017</td>\n      <td>08:00:00</td>\n      <td>08:15:00</td>\n      <td>LINEA_B</td>\n      <td>LINEA_B_LACROZE_O_TURN09</td>\n      <td>FEDERICO LACROZE</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>66</td>\n    </tr>\n    <tr>\n      <th>7622360</th>\n      <td>201701</td>\n      <td>01/01/2017</td>\n      <td>08:00:00</td>\n      <td>08:15:00</td>\n      <td>LINEA_B</td>\n      <td>LINEA_B_LACROZE_E_TURN05</td>\n      <td>FEDERICO LACROZE</td>\n      <td>4</td>\n      <td>0</td>\n      <td>0</td>\n      <td>4</td>\n      <td>66</td>\n    </tr>\n    <tr>\n      <th>7622361</th>\n      <td>201701</td>\n      <td>01/01/2017</td>\n      <td>08:00:00</td>\n      <td>08:15:00</td>\n      <td>LINEA_B</td>\n      <td>LINEA_B_LACROZE_E_TURN06</td>\n      <td>FEDERICO LACROZE</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>66</td>\n    </tr>\n    <tr>\n      <th>7622362</th>\n      <td>201701</td>\n      <td>01/01/2017</td>\n      <td>08:00:00</td>\n      <td>08:15:00</td>\n      <td>LINEA_B</td>\n      <td>LINEA_B_LACROZE_O_TURN03</td>\n      <td>FEDERICO LACROZE</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n    </tr>\n    <tr>\n      <th>7622363</th>\n      <td>201701</td>\n      <td>01/01/2017</td>\n      <td>08:00:00</td>\n      <td>08:15:00</td>\n      <td>LINEA_B</td>\n      <td>LINEA_B_LACROZE_O_TURN07</td>\n      <td>FEDERICO LACROZE</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>66</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n**estadisticas descriptivas para la columna \"TOTAL\" del dataframe \"molinetes_lacroze\"**\n\n\n```python\nmolinetes_lacroze['TOTAL'].describe()\n```\n\n\n\n\n    count    421233.000000\n    mean         19.292629\n    std          25.177922\n    min           0.000000\n    25%           3.000000\n    50%           9.000000\n    75%          27.000000\n    max         248.000000\n    Name: TOTAL, dtype: float64\n\n\n\n**distplot para la columna \"TOTAL\" del dataframe \"molinetes_lacroze\"**\n\n\n```python\n# displot para la columna \"TOTAL\" nos generar\u00e1 un histograma + la distribuci\u00f3n generada de los datos a partir de \n# sus frecuencias poblacionales.\nsns.distplot(molinetes_lacroze['TOTAL'])\nplt.title('Distribuci\u00f3n de cantidad de viajes totales de molinetes. Linea B. Mes Abril.')\nplt.xlabel('Cantidad de Viajes en molinete por cada 15 mins')\nplt.show()\n```\n\n**Boxplot para la columna TOTAL del dataframe \"molinetes_lacroze\"**\nRealizaremos un boxplot con Matplotlib y otro con seaborn, simplemente para aprender que existen 2 maneras de visualizar.\n\n\n```python\n# boxplot realizado con Matplotlib\nplt.boxplot(molinetes_lacroze['TOTAL'])\nplt.title('Vueltas de molinete en Lacroze en 2017')\nplt.ylabel('Cant. de molinetes c/15 mins')\nplt.xlabel(\"Viajes por molinete Lacroze\")\nplt.show()\n```\n\n\n```python\n# probamos hacer el mismo boxplot con seaborn\nax = sns.boxplot(x = \"TOTAL\", data =  molinetes_lacroze)\nplt.show()\n```\n\n# Filtrado de outliers con cuantiles\nCalculamos el valor del percentil 90. Lo que este sobre el percentil 90 lo llamaremos \"hora pico\" y lo que este por debajo sera \"hora no pico\".\n\nCon el comando de pandas .quantile() calculamos los percentiles que deseemos. En algunos casos nos puede llegar a interesar tambien observar lo que se encuentre por debajo del percentil 10, aunque como observamos en el distplot, la distribucion es asimetrica a la derecha.\n\n\n```python\n# calculo el percentil 90 de la columna \"TOTAL\" para el dataframe \"molinetes_lacroze\".\npercentil_90 = molinetes_lacroze['TOTAL'].quantile(0.9)\n```\n\n\n```python\n# imprimimos en pantalla cuanto vale el percentil 0.9\npercentil_90\n```\n\n\n\n\n    50.0\n\n\n\nAhora filtramos por los valores de \"TOTAL\" que sean mayores al percentil 90 para guardarlos en otro dataframe llamado \"Lacroze_hora_pico\". Lo mismo hacemos para los que son menores al percentil 90 y los guardamos como \"hora no pico\".\n\n\n```python\nlacroze_hora_pico = molinetes_lacroze.loc[molinetes_lacroze['TOTAL']>percentil_90]\n```\n\n\n```python\nlacroze_hora_nopico = molinetes_lacroze.loc[molinetes_lacroze['TOTAL']<percentil_90]\n```\n\nObservamos que la expresion **\"molinetes_lacroze['TOTAL']<percentil_90\"** es un vector Boolean, es decir que arroja True o False, y al filtrar utilizando un vector boolean solo sobreviven las filas que esten asociadas a un True.\n\n\n```python\n# observamos que cuando indicamos una expresion logica, lo que devuelve python son valores Booleanos como True or False.\n(molinetes_lacroze['TOTAL']<percentil_90).head()\n```\n\n\n\n\n    7622359    True\n    7622360    True\n    7622361    True\n    7622362    True\n    7622363    True\n    Name: TOTAL, dtype: bool\n\n\n\n\n```python\n# observamos que dimensiones tienen ahora los dataframes de hora pico y hora no pico\nnp.shape(lacroze_hora_nopico)\n```\n\n\n\n\n    (378809, 12)\n\n\n\n\n```python\nnp.shape(lacroze_hora_pico)\n```\n\n\n\n\n    (40621, 12)\n\n\n\nPloteamos la distribucion / histograma de la hora pico, ver que los valores del eje X comienzan a partir de 50, que fue el umbral que seleccionamos para dividir ambas categorias.\n\n\n```python\n# hacemos un distplot de la columna TOTAL del dataframe \"lacroze_hora_pico\"\nsns.distplot(lacroze_hora_pico['TOTAL'], norm_hist = False)\nplt.title('Distribuci\u00f3n de cantidad de viajes en hora pico de la estacion Lacroze')\nplt.xlabel('Cantidad de Viajes en molinete por cada 15 mins')\nplt.show()\n```\n\n\n```python\n# con matplotlib hacemos un boxplot sobre la columna TOTAL del dataframe \"lacroze_hora_pico\"\nplt.boxplot(lacroze_hora_pico['TOTAL'])\nplt.title('Cant. viajes de Lacroze en 2017 Hora Pico')\nplt.ylabel('Cant. de vueltas de molinete c/15 mins')\nplt.xlabel(\"Estacion Lacroze\")\nplt.show()\n```\n\nCalculamos estadisticas descriptivas para la hora pico\n\n\n```python\n# aplicamos .describe() sobre la columna TOTAL del dataframe \"lacroze_hora_pico\"\nlacroze_hora_pico['TOTAL'].describe()\n```\n\n\n\n\n    count    40621.000000\n    mean        80.194604\n    std         28.975506\n    min         51.000000\n    25%         57.000000\n    50%         70.000000\n    75%         96.000000\n    max        248.000000\n    Name: TOTAL, dtype: float64\n\n\n\nAhora calculamos estadisticas descriptivas y graficos para la hora no pico. **\u00bfque diferencias hay en estas estadisticas entre hora pico y hora no pico?**\n\n\n```python\n# aplicamos .describe() sobre la columna TOTAL del dataframe \"lacroze_hora_nopico\"\nlacroze_hora_nopico['TOTAL'].describe()\n```\n\n\n\n\n    count    378809.000000\n    mean         12.615743\n    std          12.964954\n    min           0.000000\n    25%           2.000000\n    50%           7.000000\n    75%          19.000000\n    max          49.000000\n    Name: TOTAL, dtype: float64\n\n\n\n\n```python\n# hacemos un distplot sobre la columna TOTAL del dataframe \"lacroze_hora_nopico\"\nsns.distplot((lacroze_hora_nopico['TOTAL']))\nplt.title('Distribuci\u00f3n de cantidad de viajes en hora NO pico de la estacion Lacroze')\nplt.xlabel('Cantidad de Viajes en molinete por cada 15 mins')\nplt.show()\n```\n\n\n```python\n# hacemos un boxplot con matplotlib sobre la columna TOTAL del dataframe \"lacroze_hora_nopico\"\nplt.boxplot(lacroze_hora_nopico['TOTAL'])\nplt.title(\"Dist de cant. de viajes c/15 mins en hora no pico\")\nplt.xlabel(\"Estacion Lacroze. Hora no pico\")\nplt.show()\n```\n\nAhora comparamos como queda la distribucion de cantidad de viajes cada 15 mins con los datos originales, en hora pico y en hora no pico.\n\n\n```python\n# con matplotlib hacemos un boxplot de los 3 grupos de datos. Ver que ingresamos 3 dataframes filtrados por la columna TOTAL\nplt.boxplot([molinetes_lacroze['TOTAL'],lacroze_hora_pico['TOTAL'], lacroze_hora_nopico['TOTAL']])\nplt.title('comparacion de boxplots entre hora pico, no pico y pre filtrado')\nplt.xlabel(['pre-filtrado', 'hora pico', 'hora no pico'])\nplt.show()\n```\n\nTambien podriamos visualizar en simult\u00e1neo las distribuciones de los viajes en horas pico y no pico.\n\n\n```python\n# hacemos dos displots en el mismo grafico. Uno para hora pico y otro para hora no pico.\nsns.distplot((lacroze_hora_pico['TOTAL']))\nsns.distplot((lacroze_hora_nopico['TOTAL']))\nplt.title('Distribuci\u00f3n de cantidad de viajes en hora NO pico de la estacion Lacroze')\nplt.xlabel('Cantidad de Viajes en molinete por cada 15 mins')\nplt.show()\n```\n\n# Correlaci\u00f3n Lineal entre estaciones Linea C\n\n\\begin{equation}\nr = \\frac{\\sum_{i}^{n}\\left ( x_i - \\overline{x} \\right )\\left ( y_i - \\overline{y}  \\right )}{\\left [ \\sum_{i}^{n} \\left ( x_i - \\overline{x}  \\right )^{2} \\left ( y_i - \\overline{y} \\right ) ^{2}  \\right ]^{1/2}}\n\\end{equation}\n\nLa correlacion lineal (Pearson) es un indicador que varia entre -1 y 1. Indica si dos variables supuestas independientes, se comportan linealmente una de la otra al analizalas juntas. Correlacion r>0 implica correlacion lineal positiva y r<0 implica correlacion lineal negativa. Si r=0 quiere decir que no existe correlacion LINEAL, aunque puede existir otro tipo de correlacion no lineal.\n\n**IMPORTANTE: Correlacion no implica causalidad**. Si dos variables estan altamente correlacionadas, nada indica que una es la causa de la otra, es decir, nada indica que una depende de otra.\n\nCreamos un dataframe solo de la linea C filtrando el dataframe \"molinetes\" por la columna \"LINEA\"\n\n\n```python\n# f\nmolinetes_c = molinetes[(molinetes['LINEA'] == 'LINEA_C')]\n```\n\nAhora creamos una tabla pivote para resumir por columnas ESTACION y filas FECHA, los valores de cantidad de viajes de molinetes para la linea C\n\n\n```python\n# hacemos la tabla pivote para \"simplificar o resumir\" los datos provenientes de \"molinetes_c\" \nmolinetes_c_pivot = pd.pivot_table(molinetes_c, values = 'TOTAL', columns = 'ESTACION', index = 'PERIODO',fill_value=0, aggfunc = np.sum)\n```\n\n\n```python\n# observamos como quedo la tabla pivote con un .head()\nmolinetes_c_pivot.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>ESTACION</th>\n      <th>AVENIDA DE MAYO</th>\n      <th>CONSTITUCION</th>\n      <th>DIAGONAL NORTE</th>\n      <th>GENERAL SAN MARTIN</th>\n      <th>INDEPENDENCIA</th>\n      <th>LAVALLE</th>\n      <th>MARIANO MORENO</th>\n      <th>RETIRO</th>\n      <th>SAN JUAN</th>\n    </tr>\n    <tr>\n      <th>PERIODO</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>201701</th>\n      <td>106068</td>\n      <td>8229</td>\n      <td>88541</td>\n      <td>135184</td>\n      <td>195139</td>\n      <td>118027</td>\n      <td>110087</td>\n      <td>511180</td>\n      <td>705</td>\n    </tr>\n    <tr>\n      <th>201702</th>\n      <td>102016</td>\n      <td>1</td>\n      <td>92249</td>\n      <td>137498</td>\n      <td>228300</td>\n      <td>117724</td>\n      <td>124408</td>\n      <td>517505</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>201703</th>\n      <td>179735</td>\n      <td>1673294</td>\n      <td>180484</td>\n      <td>276231</td>\n      <td>188051</td>\n      <td>278616</td>\n      <td>219070</td>\n      <td>1016705</td>\n      <td>155478</td>\n    </tr>\n    <tr>\n      <th>201704</th>\n      <td>147947</td>\n      <td>1674946</td>\n      <td>152623</td>\n      <td>233642</td>\n      <td>161896</td>\n      <td>244432</td>\n      <td>184197</td>\n      <td>941852</td>\n      <td>157027</td>\n    </tr>\n    <tr>\n      <th>201705</th>\n      <td>173288</td>\n      <td>1973564</td>\n      <td>178884</td>\n      <td>280895</td>\n      <td>178144</td>\n      <td>290885</td>\n      <td>217205</td>\n      <td>1105674</td>\n      <td>179406</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nahora generamos una matriz de correlacion de Pearson entre cada estacion de la linea C. Con esto queremos entender si cuando aumenta o diminuye los viajes de molinetes de una estacion, el resto de las estaciones evoluciona directa o indirectamente proporcional de manera lineal.\n\n\n```python\n# creamos una matriz \"mol_c_corr\" que es lo obtenido de aplicar .corr() a \"molinetes_c_pivot\"\nmol_c_corr = molinetes_c_pivot.corr()\n```\n\n\n```python\n# observamos las dimensiones de esta matriz\nnp.shape(mol_c_corr)\n```\n\n\n\n\n    (9, 9)\n\n\n\n\n```python\n# visualizamos las primeras 3 filas de la matriz de correlacion\nmol_c_corr.head(3)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>ESTACION</th>\n      <th>AVENIDA DE MAYO</th>\n      <th>CONSTITUCION</th>\n      <th>DIAGONAL NORTE</th>\n      <th>GENERAL SAN MARTIN</th>\n      <th>INDEPENDENCIA</th>\n      <th>LAVALLE</th>\n      <th>MARIANO MORENO</th>\n      <th>RETIRO</th>\n      <th>SAN JUAN</th>\n    </tr>\n    <tr>\n      <th>ESTACION</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>AVENIDA DE MAYO</th>\n      <td>1.000000</td>\n      <td>0.944188</td>\n      <td>0.992863</td>\n      <td>0.981723</td>\n      <td>-0.457787</td>\n      <td>0.976326</td>\n      <td>0.988167</td>\n      <td>0.969090</td>\n      <td>0.957276</td>\n    </tr>\n    <tr>\n      <th>CONSTITUCION</th>\n      <td>0.944188</td>\n      <td>1.000000</td>\n      <td>0.954917</td>\n      <td>0.960572</td>\n      <td>-0.619212</td>\n      <td>0.982128</td>\n      <td>0.968479</td>\n      <td>0.993509</td>\n      <td>0.985945</td>\n    </tr>\n    <tr>\n      <th>DIAGONAL NORTE</th>\n      <td>0.992863</td>\n      <td>0.954917</td>\n      <td>1.000000</td>\n      <td>0.991764</td>\n      <td>-0.498654</td>\n      <td>0.987925</td>\n      <td>0.989611</td>\n      <td>0.975702</td>\n      <td>0.975865</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n# Heatmap de correlacion estaciones linea C\nUtilizamos la funcion Heatmap de seaborn para visualizar la matriz de correlacion que generamos en el paso anterior. Observamos que la estacion Independencia correlaciona negativamente con el resto. Esto quiere decir que cuando el resto de las estaciones incrementa su numero de pasajeros por molinete, en Independencia decrece demanera lineal.\n\n\n```python\ncorr_c_plot = sns.heatmap(mol_c_corr, xticklabels=1, yticklabels=1)\ncorr_c_plot.set_xticklabels(corr_c_plot.get_xticklabels(), rotation=40, ha=\"right\")\nplt.title(\"matriz de correlacion viajes en estaciones linea C\")\nplt.show()\n```\n\nObservamos que la estacion Independencia correlaciona negativamente con respecto al resto de las estaciones. Posiblemente sea un efecto de que Independencia es un nodo que intersecta a la linea E.\n\n\n```python\n\n```\n", "meta": {"hexsha": "7801a8e491c9acaf99a8ff7ca3884c66ca1e273b", "size": 454672, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "clases/clase_01/clusterai_2020_clase01_eda_subtes.ipynb", "max_stars_repo_name": "nmirson-ml/clusterai_2020", "max_stars_repo_head_hexsha": "4b558fc6db7615c2a6efbcf61ab30e3f59ab07ff", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2020-09-21T14:39:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-21T13:27:51.000Z", "max_issues_repo_path": "clases/clase_01/clusterai_2020_clase01_eda_subtes.ipynb", "max_issues_repo_name": "nmirson-ml/clusterai_2020", "max_issues_repo_head_hexsha": "4b558fc6db7615c2a6efbcf61ab30e3f59ab07ff", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-09-19T16:04:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-10T05:17:59.000Z", "max_forks_repo_path": "clases/clase_01/clusterai_2020_clase01_eda_subtes.ipynb", "max_forks_repo_name": "clusterai/clusterai_2020", "max_forks_repo_head_hexsha": "2c171bc2bb2639840d65a243cdc826b69473eb56", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-10-01T16:39:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-21T13:29:12.000Z", "avg_line_length": 454672.0, "max_line_length": 454672, "alphanum_fraction": 0.9258234508, "converted": true, "num_tokens": 9161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116407397951, "lm_q2_score": 0.10970577387797076, "lm_q1q2_score": 0.04386164545278044}}
{"text": "# ENGSCI233 - Computational Techniques and Computer Systems\n\n**ENGSCI233: Computational Techniques and Computer Systems** \n\n*Department of Engineering Science, University of Auckland*\n\nWelcome to ENGSCI233: Computational Techniques and Computer Systems.\n\nThe **purpose** of this course is to make you an [**awesome programmer**](https://www.reddit.com/r/programminghorror/). We do this by:\n\n- Exposing you to a range of **computational techniques and [algorithms](https://pics.me.me/algorithm-noun-word-used-by-programmers-when-they-do-not-6470233.png)** for working with data, building models, and solving problems.\n- Giving you **practice writing computer code**, including problem conceptualisation, pseudocode, implementation, and testing.\n- Demonstrating select **software design concepts** that improve the quality of your programs, including unit testing, version control, profiling, and API design.\n\nThis will be done through a mixture of Jupyter notebooks (this thing you're reading now), notebook-based activities in class, as well as computer-based labs.\n\n## Assessment\n\nYour performance in this course is assessed by a mixture of tests, lab assignments, and a final exam. The exact division is:\n\n- **30%** across **two tests** in weeks 6 and 11.\n- **60%** from ten **labs**, 6% each.\n- **10%** from ten Canvas **quizzes**, 1% each.\n\n### Labs\n\nThe majority of these are Python-based. For many of these labs, you will need to submit your written Python scripts through Canvas. Submissions are automatically **compared** against each other for **similarity**. The final project lab is partially assessed during the allocated lab time.\n\n***Copying of work is easy to detect and may amount to academic misconduct.***\n\nIn 2019, ten or so students in ENGSCI233 had academic misconduct interviews as a result of their CT lab submissions. \n\n### Canvas quizzes\n\nThere are **ten quizzes** scattered across the various topics. Each quiz comprises **a series of multichoice questions** and must be completed **before class starts**. You may have up to **three attempts** and your **best mark** will be kept. \n\nThe total allocated marks for the quizzes is low (10%). Their **purpose** is to incentivise you to familiarise yourself with the material before coming to class.\n\n## It's not working...\n\nUnfortunately, I'm not able to do any troubleshooting during class. However, please feel free to catch me at the front before or after. \n\nIf you're doing this at home, I'm afraid it's off to [**Google**](https://devhumor.com/content/uploads/images/August2019/google_programmer.jpg) with you... (or make a post on **Piazza**)\n\n## Feedback\n\nI'm very pleased to hear how this course could be made better so please participate in the **SET survey** at the end of the course. Let me know the things you liked, the things you hated, and what was most useful for your learning.\n\nIf things are going badly **RIGHT NOW**, then get in touch early. You can make public OR private posts on Piazza. Public posts are anonymous to other students. You can also email your lecturer directly if things are really terrible - we want to hear if that's the case!\n\n## Is this Python?\n\nNo. Yes. Sort of.\n\nYou're currently reading this text inside of something called a Jupyter Notebook. It enables me to write short explanations, with [web links](https://historytech.files.wordpress.com/2017/09/screen-shot-2017-09-14-at-4-11-16-pm.png?w=352&h=267), pictures\n\n\\begin{equation}\ne^{qu}\\times at=i\\left(on\\right)^s\n\\end{equation}\n\nand \n\n\n```python\n# live modifiable, Python code\n\n# run the command below by clicking inside the cell and hitting Ctrl+Enter\n1+2\n```\n\n# Python\n\nFor the rest of this course you will be working exclusively with the [Python](https://en.wikipedia.org/wiki/Python_(programming_language%29) programming language.\n\nPython is one of the most widely-used high-level programming languages in the world. It's popularity is due largely to it being open-source and [easy to learn](https://images7.memedroid.com/images/UPLOADED973/596e4c96650e5.jpeg). These notebooks embed snippets of Python code for you to run, modify and (sometimes) complete.\n\n\"***But I don't know Python, we were taught MATLAB in ENGGEN 131.***\"\n\nPython has many of the [same capabilities](https://docs.scipy.org/doc/numpy/user/numpy-for-matlab-users.html) as MATLAB. You will be provided with a range of resources to get you up and running with Python, including instruction documents, tutorials and help forums. Python will not be the last 'new' programming language you are asked to learn.\n\nThis document is called a Jupyter Notebook. It will serve both as the ***notes*** for this course, and the material we will cover in class. Your copy of this notebook is ***unique to you*** - I encourage you to take notes within it. One way to do this is to modify a text cell - **double click it, modify, then hit Ctrl+Enter to save** - with new text and [highlight it](http://stackoverflow.com/questions/25104738/text-highlight-in-markdown), e.g.\n\n> <mark>**I have enclosed this statement in    `<mark> </mark>` HTML tags. It is now an important highlighted note that my future self will definitely come back and read**</mark>\n\nThis notebook contains Python code embedded in *cells* that can be executed (by you, right now, on your laptop or, in theory, your phone). For example, ***execute the code in the cell immediately below*** by highlighting it and hitting Ctrl+Enter (or the *run* button at the top, a sideways triangle pointing to a vertical bar)\n\n\n```python\n# oh gawd, not that dumb computer science in-joke again\n\nprint(\"hello, world\")          # RECALL: print is a function, \"hello, world\" is a string\n\n# <-- the 'hash' symbol is a comment (it was a % in MATLAB)\n```\n\nYou can modify the code above. You ***should*** modify the code above. ***Change it*** to print something different.\n\nWe can do all the usual MATLAB stuff, define variables and do math things with them.\n\n\n```python\n# run the simple calculation below and view the result using the print function\na = 3.5\nb = 2.8\nc = a*b\n# *copy-paste the print statement from the cell above to display the value of c*\n```\n\nWe [***import*** modules](https://www.tutorialspoint.com/python/python_modules.htm) to make additional functionality available (in MATLAB, these are preloaded)\n\n\n```python\n# import the NumPy module, which duplicates much of what you want from MATLAB\nimport numpy as np\nv = np.linspace(0,10,11)        # RECALL: linspace creates a vector of evenly spaced numbers\nprint(v)\nprint(2*v)\n```\n\n- [Python indexing](http://stackoverflow.com/questions/509211/explain-pythons-slice-notation) is ***[from zero](https://i.redd.it/bpnzu5yy126z.png)*** just like with C. \n- You can index relative to the end of an array using ***negative*** indices. \n- Indexing uses ***square*** brackets, [], as opposed to round ones, (), in MATLAB.\n- Variables ***carry over*** from previous cells.\n- You don't need a semicolon (to suppress output in MATLAB, to [inexplicably](https://memeworld.funnyjunk.com/pictures/Scumbag+semicolon+just+something+that+pissed+me+off+while+in_88463d_3293276.jpg) allow your code to compile in C).\n\n\n```python\n# make sure you understand HOW these commands result in the printed output below.\nprint(v[0])\nprint(v[-1])\nprint(v[:2])\nprint(v[-2:])\n```\n\n**Indentation is important**. In this way, Python enforces that your code looks good. For example, executing the commands below raises an error. \n\n***Read the error message. Try to understand it. This is your BEST chance to debug a problem.***\n\n\n\n```python\nleft_hand = 2.\nright_hand = 3.\nhands = left_hand + right_hand\nif hands>6.:\nprint('not bad')\nelse:\nprint('you have small hands')\n```\n\nFix the error by indenting the two `print` statements.\n\n**Lists** are ordered collections of Python objects (floats, integers, booleans, strings, other lists, etc.)\n\n\n```python\nmy_list = [1,2,3,4]\nprint(my_list)\nempty_list = []\nprint(empty_list)\nempty_list.append('hi,')\nempty_list.append('not')\nempty_list.append('empty')\nempty_list.append('now')\nprint(empty_list)\n```\n\n**They are different to arrays**, which are ordered collections of numbers we can do math on.\n\n\n```python\na = np.array([1,2,3,4])\nb = 2*a\nprint(b)\namean = np.mean(a)\nprint(amean)\nprint(np.sum(a), np.std(a), np.min(a), np.max(a))\n```\n\n# [What now?](https://i.imgur.com/9OXCPp7.jpg)\n\n**Open the introductory Python notebook [python101](../supplementary/python101.ipynb)** and work through the exercises there.\n", "meta": {"hexsha": "cf98f8702bb32f4e0febdf145806988f379fb766", "size": 12760, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "introduction/introduction.ipynb", "max_stars_repo_name": "bryan-ruddy/ENGSCI233_2021", "max_stars_repo_head_hexsha": "97a9ede84183603ac7975d5692885921419608fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-02-09T02:15:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T02:22:42.000Z", "max_issues_repo_path": "introduction/introduction.ipynb", "max_issues_repo_name": "ddempsey/ENGSCI233_2020", "max_issues_repo_head_hexsha": "0fabddaf118999a06fef36ee4cd80074b9a5f0fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "introduction/introduction.ipynb", "max_forks_repo_name": "ddempsey/ENGSCI233_2020", "max_forks_repo_head_hexsha": "0fabddaf118999a06fef36ee4cd80074b9a5f0fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-11-25T22:25:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-26T03:06:03.000Z", "avg_line_length": 34.0266666667, "max_line_length": 457, "alphanum_fraction": 0.6151253918, "converted": true, "num_tokens": 2053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23370635691404026, "lm_q2_score": 0.18713268669577832, "lm_q1q2_score": 0.04373409846720684}}
{"text": "## PyCity_Calc tutorial (Part 2)\n\nNow we are going to learn how to generate a city object within pycity_calc. \n\nThe city object of pycity_calc is an inheritance of the city district object of pycity (which is an inheritance of uesgraph, which is an inheritance of networkx.Graph). Long list of dependencies...however, can be pretty powerful. \n\nAgain, we have to start to define an environment\n\n\n```python\nimport pycity_base.classes.Weather as Weather\n\nimport pycity_calc.environments.co2emissions as co2\nimport pycity_calc.environments.environment as env\nimport pycity_calc.environments.market as mark\nimport pycity_calc.environments.timer as time\n\n\n#  Input parameters\nyear = 2010  # Reference year\ntimestep = 3600  # Timestep in seconds\nlocation = (51.529086, 6.944689)  # (latitude, longitute) of location\naltitude = 55  # altitude of location in m\n\n#  Generate extended timer object\ntimer = time.TimerExtended(timestep=timestep, year=year)\n\n#  Generate weather object\nweather = Weather.Weather(timer, useTRY=True, location=location,\n                          altitude=altitude)\n\n#  Generate market object\nmarket = mark.Market()\n#  Market is an inheritance of pycity prices object\n\n#  Generate co2 emissions object (new in pycity_calc)\nco2em = co2.Emissions(year=year)\n\n#  Generate environment\nenvironment = env.EnvironmentExtended(timer, weather, prices=market,\n                                      location=location, co2em=co2em)\n\nprint('Kind of object:')\nprint(environment._kind)\n```\n\n    Kind of object:\n    environment\n\n\nNext, we are going to generate a city object (of pycity_calc)\n\n\n```python\nimport pycity_calc.cities.city as city\n\n#  Generate city object\ncity_object = city.City(environment=environment)\n\nprint('Kind of object:')\nprint(city_object._kind)\n#  city is an inheritance of city district. Thus, it holds the city district attribute _kind = 'citydistrict'\n```\n\n    Kind of object:\n    citydistrict\n\n\nNow we are going to generate three BuildingExtended objects for the city object (with single zones / one apartment per building!)\n\n\n```python\nimport sympy.geometry.point as point\n\nimport pycity_base.classes.demand.SpaceHeating as SpaceHeating\nimport pycity_base.classes.demand.ElectricalDemand as ElectricalDemand\nimport pycity_base.classes.demand.Apartment as Apartment\nimport pycity_calc.buildings.building as build_ex\n\n\n#  Iterate 3 times to generate 3 building objects\nfor i in range(3):\n    #  Create space heating demand object (with standardized load profiles (method=1))\n    heat_demand = SpaceHeating.SpaceHeating(environment,\n                                            method=1,\n                                            profile_type='HEF',\n                                            livingArea=100,\n                                            specificDemand=130)\n\n    #  Create electrical demand object (with standardized load profile)\n    el_demand = ElectricalDemand.ElectricalDemand(environment, method=1,\n                                                  annualDemand=3000,\n                                                  profileType=\"H0\")\n\n    #  We can create occupancy profiles, dhw profiles etc., but we are going to skip it, here.\n    \n    #  Create apartment\n    apartment = Apartment.Apartment(environment)\n\n    #  Add demands to apartment\n    apartment.addMultipleEntities([heat_demand, el_demand])\n\n    #  Create extended building object\n    extended_building = build_ex.BuildingExtended(environment,\n                                                  build_year=1962,\n                                                  mod_year=2003,\n                                                  build_type=0)\n\n    #  Add apartment to extended building\n    extended_building.addEntity(entity=apartment)\n\n    #  Generate positions (sympy Point object)\n    position = point.Point(i*10, 0)\n    \n    #  Add extended buildings to city object\n    city_object.add_extended_building(extended_building=extended_building,\n                                      position=position)\n\nprint('Get number of buildings:')\nprint(city_object.get_nb_of_building_entities())\n\nprint('Get annual space heating demand of one building:')\nprint(extended_building.get_annual_space_heat_demand())\n```\n\n    Get number of buildings:\n    3\n    Get annual space heating demand of one building:\n    13000.0\n\n\nCity holds further methods:\n\n\n```python\nprint('\\nGet list of node ids with building objects:')\nprint(city_object.get_list_build_entity_node_ids())\n\nprint('\\nGet power curves of all buildings')\nprint(city_object.get_power_curves())\n\nprint('\\nGet total annual space heating demand of all buildings')\nprint(city_object.get_annual_space_heating_demand())\n\nprint('\\nGet total annual electrical demand of all buildings')\nprint(city_object.get_annual_el_demand())\n\nprint('\\nNode ids of original city district')\nprint(city_object.nodes(data=False))\nprint('\\nWith data:')\nprint(city_object.nodes(data=True))\n```\n\n    \n    Get list of node ids with building objects:\n    [1001, 1002, 1003]\n    \n    Get power curves of all buildings\n    (array([ 244.82052 ,  226.913643,  209.84616 , ...,  206.098767,\n            239.055471,  268.429914]), array([ 5304.87276967,  5443.26075496,  5581.64874026, ...,  6646.54219399,\n            4537.2514064 ,  3308.09634313]))\n    \n    Get total annual space heating demand of all buildings\n    39000.0\n    \n    Get total annual electrical demand of all buildings\n    9000.00000004\n    \n    Node ids of original city district\n    [1001, 1002, 1003]\n    \n    With data:\n    [(1001, {'entity': <pycity_calc.buildings.building.BuildingExtended object at 0x000000000A99DBA8>, 'name': 1001, 'is_supply_cooling': False, 'is_supply_heating': False, 'is_supply_electricity': False, 'is_supply_gas': False, 'position': Point(0, 0), 'node_type': 'building', 'is_supply_other': False}), (1002, {'entity': <pycity_calc.buildings.building.BuildingExtended object at 0x000000000A99BB38>, 'name': 1002, 'is_supply_cooling': False, 'is_supply_heating': False, 'is_supply_electricity': False, 'is_supply_gas': False, 'position': Point(10, 0), 'node_type': 'building', 'is_supply_other': False}), (1003, {'entity': <pycity_calc.buildings.building.BuildingExtended object at 0x000000000C015B38>, 'name': 1003, 'is_supply_cooling': False, 'is_supply_heating': False, 'is_supply_electricity': False, 'is_supply_gas': False, 'position': Point(20, 0), 'node_type': 'building', 'is_supply_other': False})]\n\n\nNow we are going to add streets to our city object:\n\n\n```python\n#  Add street network\n\n#  Add str nodes\nnode_1 = city_object.add_street_node(position=point.Point(0, -1))\nnode_2 = city_object.add_street_node(position=point.Point(10, -1))\nnode_3 = city_object.add_street_node(position=point.Point(20, -1))\n\n#  Add edges\ncity_object.add_edge(node_1, node_2, network_type='street')\ncity_object.add_edge(node_2, node_3, network_type='street')\n\nprint('Nodelist street:')\nprint(city_object.nodelist_street)\n```\n\n    Nodelist street:\n    [1004, 1005, 1006]\n\n\npycity_calc hold plotting methods. We are going to plot our existing city now:\n\n\n```python\n%matplotlib inline\n\nimport pycity_calc.visualization.city_visual as citvis\n\n#  Plot city object\ncitvis.plot_city_district(city=city_object, offset=-0.2)\n```\n\nIt is possible to generate a city district with txt/csv input table. Please take a look at pycity_calc/cities/scripts/...\nHere you will find a city_generator (to generate city with buildings, only), a street_generator and a complex_city_generator (city with buildings and street network).\n\nYou should take a look at further examples within pycity_calc/examples folder to get more information. PyCity_Calc also holds a couple of toolbox-scripts for:\n* City analysis\n* Building clustering\n* Energy system dimensioning\n* Network operations\n* Interface to TEASER\n\nEnergysystems, electrical grid (pypower) and simulations scripts are currently under development (06.04.2016). Going to be added, soon...\n", "meta": {"hexsha": "66b62849e76f3d5588076b4dff70c332c1ffadfc", "size": 20093, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "pycity_calc/examples/tutorials/tutorial_pycity_calc_2.ipynb", "max_stars_repo_name": "RWTH-EBC/pyCity_calc", "max_stars_repo_head_hexsha": "99fd0dab7f9a9030fd84ba4715753364662927ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-06-22T14:14:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T11:47:01.000Z", "max_issues_repo_path": "pycity_calc/examples/tutorials/tutorial_pycity_calc_2.ipynb", "max_issues_repo_name": "RWTH-EBC/pyCity_calc", "max_issues_repo_head_hexsha": "99fd0dab7f9a9030fd84ba4715753364662927ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-08-28T19:42:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-28T19:43:44.000Z", "max_forks_repo_path": "pycity_calc/examples/tutorials/tutorial_pycity_calc_2.ipynb", "max_forks_repo_name": "RWTH-EBC/pyCity_calc", "max_forks_repo_head_hexsha": "99fd0dab7f9a9030fd84ba4715753364662927ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.2829131653, "max_line_length": 8270, "alphanum_fraction": 0.7312994575, "converted": true, "num_tokens": 1894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.08882028335534632, "lm_q1q2_score": 0.043716289678860716}}
{"text": "## Introduction to Object Oriented Programming with Python\n\nThis prepares you for a 2 day challenge. The goals:\n\n1. Be able to write Python code;\n2. Understand the ideas behind object oriented programming.\n\n### Basic Python\n\n1. Variables;\n2. Flow Control;\n3. Functions;\n4. Data structure.\n\n### Basic Object Oriented Programming\n\n1. Classes;\n2. Attributes;\n3. Methods;\n4. Inheritance.\n\n### The Challenge\n\n1. End of the day Thursday: Initial Feedback;\n2. End of the day Friday: results.\n\n## Overview of Python\n\nWhat is Python?\n\nPython is a programming language. There are various other programming languages:\n\nJava\nC\nC++\nRuby\nVBA\nand many more.\nA programming language allows you to write a program which is a sequence of instructions that specifies how to perform a computation.\n\nWhen writing a program you need two things:\n\nSomething to save the code (a text editor for example)\nSomething to run the code\nWe will be using a combination of these 2 things called notebooks.\n\n## Installing Python\n\nThere are various distributions of Python, we will use Anaconda which comes packaged with a variety of other useful tools (including the notebooks I mentioned above).\n\nTo install it on your personal machine follow these steps:\n\nGo to this webpage: https://www.continuum.io/downloads.\n\nIdentify and download the version of **Python 3** for your operating system (Windows, Mac OSX, Linux).\nRun the installer.\nWe will use a Jupyter notebook which runs in your browser. To open a local server find the Continuum navigator and click on Jupyter. You do not need to be connected to the internet to use this.\n\n## Interacting with Python\n\nOnce you have installed Anaconda, you will now have Python on your machine. You can interact with Python in multiple ways:\n\n\n### The Python shell\n\n\n- On Windows open a \"Command Prompt\":\n  \n- On Mac OS or Linux open a \"Terminal\":\n  \nThis is a simple utility that allows you to give commands to your computer. In there type:\n\n```bash\npython\n```\n\nThis should then look something like:\n\n```python\nPython 3.5.2 |Anaconda 4.2.0 (64-bit)| (default, Jul  2 2016, 17:53:06) \n[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> \n```\n\nThe `>>>` is a prompt for you to type a command. Let us carry out a straightforward addition:\n\n\n```python\n>>> 2 + 2\n```\n\nand press `ENTER`:\n\n\n```python\n>>> 2 + 2\n4\n```\n\n**This is not a very efficient and practical way of using Python.** We will instead learn to use a [Jupyter notebook](http://jupyter.org/).\n\n\n### Jupyter notebooks\n\nIf you are still in the Python shell (with a `>>>` waiting for you to give a command) then type:\n\n```python\n>>> exit()\n```\n\nThis will leave the prompt and you will now be back at the Command Prompt or the Terminal window. Here simply type:\n\n```bash\njupyter notebook\n```\n\nAfter a little moment this will open a Jupyter notebook page in a browser. Note that this is all just running on your computer and you do not need to be connected to the internet to use a Jupyter notebook.\n\nClick on `New` and create a notebook: we can start to write code now.\n\n\n### Basic Python\n\nWrite `2 + 2` in a cell and press `shift + Enter`:\n\n\n```python\n2 + 2\n```\n\n\n\n\n    4\n\n\n\n## Variables\n\n### Character variables:\n\n\n```python\nstring = \"Hello world\"\nstring\n```\n\n\n\n\n    'Hello world'\n\n\n\n### Numeric variables:\n\n\n```python\nnum_1 = 2\nnum_2 = 3.5\nnum_1 + num_2\n```\n\n\n\n\n    5.5\n\n\n\n### String manipulation\n\n\n```python\n#We define a variable called String \n# (note that # allows me to comment my code)\nstring = \"My name is Vince\"\n#Let's get the 5th letter of String \n# (Note that Python starts counting at 0):\nstring[4]\n```\n\n\n\n\n    'a'\n\n\n\n\n```python\nstring[1:4]\n```\n\n\n\n\n    'y n'\n\n\n\n\n```python\nindex_of_v = string.index(\"V\")\nindex_of_v\n```\n\n\n\n\n    11\n\n\n\n\n```python\nstring[index_of_v:]\nstring[:index_of_v]\n```\n\n\n\n\n    'My name is '\n\n\n\n### Numeric manipulation\n\n\n```python\nnum = 3\n\n# The following two lines are equivalent\nnum = num + 1\nnum += 1\nnum\n```\n\n\n\n\n    5\n\n\n\n\n```python\nnum -= 2\nnum *= 3\nnum **= 2\nnum\n```\n\n\n\n\n    81\n\n\n\n## Flow control\n\n- In Python indentation is important!\n- In all languages indentation is good practice, in Python it is a requirement.\n\n### If statements\n\n\n```python\nn = 11 \nif n <= 5:\n    value = 1\nelif n % 2 == 0:  \n    value = 2\nelse: \n    value = 3\nvalue\n```\n\n\n\n\n    3\n\n\n\n### While loops\n\n\n```python\ncount = 0  \ntotal = 0 \nwhile count < 10: \n    count += 1  \n    total += count \ntotal\n```\n\n\n\n\n    55\n\n\n\n### For loops\n\n\n```python\nfor i in [1, 2, 3, 4]:\n    print(i)\n```\n\n    1\n    2\n    3\n    4\n\n\n\n```python\nfor subject in [\"Queueing Theory\", \"Game Theory\", \n                \"Inventory Theory\", \"Reliability Theory\", \n                \"Project Management\", \"Decision Analysis\"]:\n    if \"Theory\" in subject:\n        print(subject)\n```\n\n    Queueing Theory\n    Game Theory\n    Inventory Theory\n    Reliability Theory\n\n\n## Functions\n\n\n```python\n#To create a function we use the 'def' statement:\ndef hi():\n    \"\"\"\n    This function simply prints a short statement. \n    \n    This is a shorter way of writing documentation, \n    it is good practice to always include a \n    description of what a function does.\n    \"\"\"\n    print(\"Hello everybody!\")\n\nhi()\n```\n\n    Hello everybody!\n\n\n\n```python\ndef fibonacci(n):\n    \"\"\"\n    This returns the nth Fibonacci number.\n    \"\"\"\n    if n == 0:\n        return 0\n    if n == 1:\n        return 1\n    return fibonacci(n - 1) + fibonacci(n - 2)\n```\n\n\n```python\nfibonacci(5)\n```\n\n\n\n\n    5\n\n\n\n## Data structures: Lists\n\n\n```python\nmy_list = list(range(6))\nmy_list[0]\n```\n\n\n\n\n    0\n\n\n\n\n```python\nmy_list.append(100)\nmy_list\n```\n\n\n\n\n    [0, 1, 2, 3, 4, 5, 100]\n\n\n\n# Object Oriented Programming\n\nThis is similar to cellular structure:\n\n\n\nWe can create \"things\" with:\n\n- attributes: things those \"things\" have;\n- methods: things those \"things\" can do.\n\n\n\n## Defining a class\n\n\n```python\nclass Student():\n    \"\"\"We can create a simple empty class.\n    \n    This is a set of rules that says what a student is.\n    \"\"\"\n```\n\n\n```python\nvince = Student()  # Creating an instance\nvince\n```\n\n\n\n\n    <__main__.Student at 0x7f34b4210b38>\n\n\n\n\n```python\nzoe = Student()  # Creating a different instance\nzoe\n```\n\n\n\n\n    <__main__.Student at 0x7f34b4210470>\n\n\n\n## Attributes\n\n\n```python\nclass Student():\n    courses = [\"Biology\", \"Mathematics\", \"English\"]\n    age = 5\n    gender = \"Male\"\n#Let us now create Vince again:\nvince = Student()\n```\n\nAccessing these attributes:\n\n\n```python\nvince.courses\n```\n\n\n\n\n    ['Biology', 'Mathematics', 'English']\n\n\n\n\n```python\nvince.age\n```\n\n\n\n\n    5\n\n\n\n\n```python\nvince.gender\n```\n\n\n\n\n    'Male'\n\n\n\nWe can manipulate these attributes just like **any other** python variable:\n\n\n```python\nvince.courses.append(\"Photography\")\nvince.courses\n```\n\n\n\n\n    ['Biology', 'Mathematics', 'English', 'Photography']\n\n\n\n\n```python\nvince.age = 28\nvince.age\n```\n\n\n\n\n    28\n\n\n\n\n```python\nvince.gender = \"M\"\nvince.gender\n```\n\n\n\n\n    'M'\n\n\n\n## Methods\n\n\n```python\nclass Student():\n    courses = [\"Biology\", \"Mathematics\", \"English\"]\n    age = 5\n    sex = \"Male\"\n\n    def have_a_birthday(self):\n        \"\"\"This method increments the age of our instance.\"\"\"\n        self.age += 1\n```\n\n\n```python\nvince = Student()\nvince.age\n```\n\n\n\n\n    5\n\n\n\n\n```python\nvince.have_a_birthday()\nvince.age\n```\n\n\n\n\n    6\n\n\n\n## The `__init__` method\n\n\n```python\nclass Student():\n    def __init__(self, courses, age, sex):\n        \"\"\"\n        What the class should do when it \n        is used to create an instance\n        \"\"\"\n        self.courses = courses\n        self.age = age\n        self.sex = sex\n\n    def have_a_birthday(self):\n        self.age += 1\n\n```\n\n\n```python\nvince = Student([\"Biology\",\"Math\"],28,\"Male\")\nvince.courses, vince.age, vince.sex\n```\n\n\n\n\n    (['Biology', 'Math'], 28, 'Male')\n\n\n\n## Inheritance\n\nWe can use a class to create new classes:\n\n\n```python\nclass Math_Student(Student):\n    \"\"\"\n    A Math student: behaves exactly like a Student \n    but also has a favourite class attribute.\n    \"\"\"\n    favourite_class = \"Mathematics\"\n```\n\n\n```python\nbecky = Math_Student([\"Mathematics\", \"Biology\"], 29, \"Female\")\nbecky.courses, becky.age, becky.sex, becky.favourite_class\n```\n\n\n\n\n    (['Mathematics', 'Biology'], 29, 'Female', 'Mathematics')\n\n\n\n\n```python\n#This class has the methods of the parent class:\nbecky.have_a_birthday()\nbecky.age\n```\n\n\n\n\n    30\n\n\n\n## Summary\n\n- Classes\n- Attributes\n- Methods\n- Inheritance\n\n## Advantages\n\n- Simplicity\n- Modularity\n- Modifiability\n- Extensibility\n- Re-usability\n\n# Libraries\n\nThere are a number of built in libraries that extend what Python can do.\n\n\n```python\nimport random\nrandom.seed(0)\nrandom.random()\n```\n\n\n\n\n    0.8444218515250481\n\n\n\n\n```python\nimport math\nmath.cos(math.pi)\n```\n\n\n\n\n    -1.0\n\n\n\nThere are also a number of external libraries. This is one of the huge strengths of Python. Some of these come with Anaconda (the distribution of Python I recommend):\n\n\n```python\nimport sympy  # symbolic mathematics\nx = sympy.symbols('x')\nsympy.diff(x ** 2, x)\n```\n\n\n\n\n    2*x\n\n\n\n\n```python\nimport numpy  # Fast numeric computations\nA = numpy.matrix([[0, 2], [1, 2]])\nB = numpy.matrix([[3, 1], [1, -2]])\nA * B\n```\n\n\n\n\n    matrix([[ 2, -4],\n            [ 5, -3]])\n\n\n\nThere are also a number of libraries outside of anaconda that are also very powerful. Some examples include:\n\n- Ciw: modeling of queues;\n- Axelrod: game theory.\n- tqdm: adding progress bars to your code :)\n- The list is very large...\n\nTo install these libraries from the internet you can open a command prompt (Windows) or a terminal (Mac OSX) and type:\n\n```bash\npip install <library-name>\n```\n\n# Further resources\n\nThere are a number of wonderful resources for learning Python. Here are some that I have made:\n\n- My first year computing for Mathematics course: http://vknight.org/cfm/\n- A short set of notebooks that used to teach Mathematics how to use Python: https://github.com/drvinceknight/Python-Mathematics-Handbook\n", "meta": {"hexsha": "519cb226237a26a5ce7bdaeaf2b383413badec04", "size": 24341, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "nbs/main.ipynb", "max_stars_repo_name": "drvinceknight/oop", "max_stars_repo_head_hexsha": "c243a6afc7ad92387222239909fecab2f4d27c08", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-02-22T00:04:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-03T16:33:09.000Z", "max_issues_repo_path": "nbs/main.ipynb", "max_issues_repo_name": "drvinceknight/oop", "max_issues_repo_head_hexsha": "c243a6afc7ad92387222239909fecab2f4d27c08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nbs/main.ipynb", "max_forks_repo_name": "drvinceknight/oop", "max_forks_repo_head_hexsha": "c243a6afc7ad92387222239909fecab2f4d27c08", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-11-25T17:49:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T09:08:45.000Z", "avg_line_length": 20.1832504146, "max_line_length": 214, "alphanum_fraction": 0.4770551744, "converted": true, "num_tokens": 2634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23651624182730094, "lm_q2_score": 0.18476750391438243, "lm_q1q2_score": 0.043700515637640845}}
{"text": "# Homework 4: Soft Actor Critic (10 Pts)\n\nAll homeworks are self-contained. They can be completed in their respective notebooks.\nTo edit and re-run code, you can therefore simply edit and restart the code cells below.\nThere is a timeout of about ~12 hours with Colab while it is active (and less if you close your browser window).\nThis file should automatically be synced with your Google Drive. We also save all recordings and logs in it by default so that you won't lose your work in the event of an instance timeout.\n However, you will need to re-mount your Google Drive and re-install packages with every new instance.\n\n\n```python\n# Your work will be stored in a folder called `drl_ws21` by default to prevent Colab\n# instance timeouts from deleting your edits.\n# We do this by mounting your google drive on the virtual machine created in this colab\n# session. For this, you will likely need to sign in to your Google account and copy a\n# passcode into a field below\n\nimport os\nfrom google.colab import drive\n\ndrive.mount('/content/gdrive')\n```\n\n\n```python\n# Create paths in your google drive\nDRIVE_PATH = '/content/gdrive/My\\ Drive/drl_ws21'\nDRIVE_PYTHON_PATH = DRIVE_PATH.replace('\\\\', '')\nif not os.path.exists(DRIVE_PYTHON_PATH):\n    % mkdir $DRIVE_PATH\n\n# the space in `My Drive` causes some issues,\n# make a symlink to avoid this\nSYM_PATH = '/content/drl_ws21'\nif not os.path.exists(SYM_PATH):\n    !ln -s $DRIVE_PATH $SYM_PATH\n% cd $SYM_PATH\n```\n\n\n```python\n# Install **python** and **system** packages\n\n# install required system dependencies\n!apt-get install -y xvfb x11-utils\n\n# install required python dependencies\n!pip install matplotlib numpy tqdm torch stable_baselines3 gym[box2d]==0.17.* pyvirtualdisplay==0.2.* PyOpenGL==3.1.* PyOpenGL-accelerate==3.1.*\n```\n\nWe start by importing all the necessary python modules and defining some helper\nfunctions which you do not need to change. Still, make sure you are aware of\nwhat they do.\n\n\n```python\n# Imports and utility\n# Progress bar\n\nimport os\nimport gym\nimport copy\nimport tqdm\nimport time\nimport torch\nimport numpy as np\nimport torch.nn as nn\nimport collections, random\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt\nfrom typing import Tuple, Dict, List\nfrom torch.distributions import Normal\nfrom stable_baselines3.common.vec_env import DummyVecEnv\nfrom stable_baselines3.common.vec_env import VecVideoRecorder\n\n# Set random seeds\nnp.random.seed(0)\n\nclass ProgressBar:\n    def __init__(self, num_iterations: int, verbose: bool = True):\n        if verbose:  # create a nice little progress bar\n            self.scalar_tracker = tqdm.tqdm(total=num_iterations, desc=\"Scalars\", bar_format=\"{desc}\",\n                                            position=0, leave=True)\n            progress_bar_format = '{desc} {n_fmt:' + str(\n                len(str(num_iterations))) + '}/{total_fmt}|{bar}|{elapsed}<{remaining}'\n            self.progress_bar = tqdm.tqdm(total=num_iterations, desc='Iteration', bar_format=progress_bar_format,\n                                          position=1, leave=True)\n        else:\n            self.scalar_tracker = None\n            self.progress_bar = None\n\n    def __call__(self, _steps: int = 1, **kwargs):\n        if self.progress_bar is not None:\n            formatted_scalars = {key: \"{:.3e}\".format(value[-1] if isinstance(value, list) else value)\n                                 for key, value in kwargs.items()}\n            description = (\"Scalars: \" + \"\".join([str(key) + \"=\" + value + \", \"\n                                                  for key, value in formatted_scalars.items()]))[:-2]\n            self.scalar_tracker.set_description(description)\n            self.progress_bar.update(_steps)\n\n# specify the path to save the recordings of this run to.\ndata_path = '/content/drl_ws21/exercise_4'\ndata_path = os.path.join(data_path, time.strftime(\"%d-%m-%Y_%H-%M\"))\nif not (os.path.exists(data_path)):\n    os.makedirs(data_path)\n\n# disable the actual display to prevent errors with colab\nfrom pyvirtualdisplay import Display\n_display = Display(visible=False, size=(1400, 900))\n_ = _display.start()\n\n# this function will automatically save your figure into your google drive folder (if correctly mounted!)\ndef save_figure(save_name: str) -> None:\n    assert save_name is not None, \"Need to provide a filename to save to\"\n    plt.savefig(os.path.join(data_path, save_name + \".png\"))\n\n\ndef evaluate_rollout(evaluation_environment: gym.Env, soft_actor_critic) -> float:\n    \"\"\"\n    Performs a full rollout using the mean of the current policy.\n    :param evaluation_environment: The environment used for evaluation. In our case, a Pendulum environment\n    :param soft_actor_critic: An instance of the SAC class defined above\n    :return: The total score for the rollout\n    \"\"\"\n    done = False\n    score = 0\n    state = evaluation_environment.reset()\n    while not done:  # alternate between collecting one step of data and updating SAC with one mini-batch\n        action, log_probabilities = soft_actor_critic.policy(torch.from_numpy(np.array(state)).float(), deterministic=True)\n        scaled_action = evaluation_environment.action_space.high[0] * action.item()\n        next_state, reward, done, info = evaluation_environment.step([[scaled_action]])\n        # need to wrap action in a list because of the video recording\n        state = next_state  # go to the next environment step\n        score += reward  # keep track of cumulative reward for recording\n    return score\n\n\ndef v_function_visualization(evaluation_environment: gym.Env,\n                             soft_actor_critic,\n                             current_step: int = 0,\n                             resolution: int = 100):\n    \"\"\"\n    Visualizes a numerical approximation of the value function by evaluating the Q-Function for a wide range\n    :param evaluation_environment:\n    :param soft_actor_critic:\n    :param current_step:\n    :param resolution:\n    :return:\n    \"\"\"\n    import matplotlib.pyplot as plt\n    plt.clf()\n\n    max_speed = 8\n    x = np.linspace(-np.pi, np.pi, num=resolution)\n    y = np.linspace(-max_speed, max_speed, num=resolution)\n    state_evaluation_grid = np.transpose([np.tile(x, len(y)), np.repeat(y, len(x))])\n    input_observations = torch.Tensor(np.array([np.cos(state_evaluation_grid[:, 0]),\n                                                np.sin(state_evaluation_grid[:, 0]),\n                                                state_evaluation_grid[:, 1]])).T\n\n    evaluations = []\n\n    for position, action in enumerate(np.linspace(evaluation_environment.action_space.low,\n                                                  evaluation_environment.action_space.high,\n                                                  50)):\n        action_tensor = torch.Tensor(np.full((len(state_evaluation_grid), 1), fill_value=action))\n\n        q1_val = soft_actor_critic.q_net_1(input_observations, action_tensor)\n        q2_val = soft_actor_critic.q_net_2(input_observations, action_tensor)\n        q1_q2 = torch.cat([q1_val, q2_val], dim=1)\n        reward_evaluation_grid = torch.min(q1_q2, 1, keepdim=True)[0]\n        reward_evaluation_grid = reward_evaluation_grid.reshape((resolution, resolution))\n\n        evaluations.append(reward_evaluation_grid.detach().numpy())\n\n    plt.title(f\"Numerically integrated V-function at step {current_step}\")\n    plt.xlabel(r\"$\\theta$\")\n    plt.ylabel(r\"$\\dot{\\theta}$\")\n    heatmap = plt.contourf(x, y, np.array(evaluations).max(axis=0), levels=100,\n                           cmap=plt.get_cmap(\"jet\"), zorder=0)\n    plt.colorbar(heatmap)\n    save_figure(save_name=f\"numerical_v_function_{current_step:04d}\")\n\n\ndef plot_metrics(metrics: Dict[str, List[float]]):\n    \"\"\"\n    Plots various metrics recorded during training\n    :param metrics:\n    :return:\n    \"\"\"\n    if len(metrics) > 0:\n        plt.clf()\n        plt.figure(figsize=(16, 9))\n        for position, (key, value) in enumerate(metrics.items()):\n            plt.subplot(len(metrics), 1, position + 1)\n            plt.plot(range(len(value)), np.array(value))\n            plt.ylabel(key.title())\n        plt.xlabel(\"Recorded Steps\")\n        plt.tight_layout()\n        save_figure(f\"training_metrics\")\n        plt.clf()\n        plt.close()\n\n\ndef evaluate(evaluation_environment: gym.Env, soft_actor_critic,\n             num_evaluation_rollouts: int = 10):\n    \"\"\"\n    Perform num_evaluation_rollouts rollouts on the evaluation environment using the current policy and average over\n    the achieved scores. Also plot a visualization of the first of these rollouts and a numerical integration\n    of the value function\n    :param evaluation_environment: The environment to evaluate. Will perform num_evaluation_rollouts full rollouts on\n      this environment\n    :param soft_actor_critic: Instance of SAC used to determine the actions\n    :param num_evaluation_rollouts: Number of rollouts to evaluate for\n    :return:\n    \"\"\"\n    scores = []\n    for rollout_idx in range(num_evaluation_rollouts):\n        rollout_score = evaluate_rollout(evaluation_environment=evaluation_environment,\n                                         soft_actor_critic=soft_actor_critic\n                                         )\n        scores.append(rollout_score)\n    mean_score = np.mean(scores)\n    return {\"score\": mean_score}\n\n\ndef visualize_rollout(soft_actor_critic, step: int):\n    # evaluation_environment = DummyVecEnv([lambda: gym.make('Pendulum-v0')])\n    # keep a second environment for evaluation purposes\n    from stable_baselines3.common.env_util import make_vec_env\n    evaluation_environment = make_vec_env('Pendulum-v0')\n    visualization_environment = VecVideoRecorder(evaluation_environment,\n                                                 video_folder=data_path,\n                                                 record_video_trigger=lambda x: x == 0,\n                                                 video_length=200,  # 200 steps per rollout\n                                                 name_prefix=f\"Pendulum_{step:05d}\")\n    evaluate_rollout(evaluation_environment=visualization_environment, soft_actor_critic=soft_actor_critic)\n\n```\n\n# **Soft Actor Critic**\n\nIn this exercise, we will re-implement the Soft Actor Critic (SAC) algorithm. SAC is an off-policy actor-critic method\nthat is widely used in the community due to its sample efficiency and (relative) stability. It acts under a maximum\nentropy principle to ensure sufficient exploration during training, and also employs tricks like the reparameterization\ntrick, polyak-updates of target Q networks and Twin-Delayed Q-Functions.\n\n\n## Pendulum\nWe will showcase the SAC algorithm on the very classic [Pendulum](https://gym.openai.com/envs/Pendulum-v0/) control environment.\nThe goal in this environment is to actuate a pendulum such that it stays upward without too much movement.\nIt has a one-dimensional action space that represents the torque acting on the pendulum,\nand a 2d internal *state* that is the angle $\\theta$ and the angular velocity $\\dot{\\theta}$ of the pendulum at the current time step.\nThe *external* state or observation is a 3-tuple ($\\cos(\\theta)$, $\\sin(\\theta)$, $\\dot{\\theta}$).\n\n\n## Replay Buffer\nWe start by defining our replay buffer which is used to store samples seen during the rollouts that can then\nbe used for training later on. You do *not* need to implement anything here.\n\n\n```python\n# Functional code\nclass ReplayBuffer:\n    def __init__(self, buffer_limit: int, batch_size: int):\n        self.batch_size = batch_size\n        self.buffer = collections.deque(maxlen=buffer_limit)  # use a dequeue as a buffer\n\n    def put(self, transition: tuple) -> None:\n        \"\"\"\n        Adds a transition to the buffer.\n        :param transition: (s, a, r, s', done) pair sampled by having the policy act on the environment\n        :return: None\n        \"\"\"\n        self.buffer.append(transition)\n\n    def sample(self) -> tuple:\n        mini_batch = random.sample(self.buffer, self.batch_size)  # get self.batch_size random samples from the buffer\n        states, actions, rewards, next_states, dones = [], [], [], [], []  # initialize list of (s, a, r, s', done) tuples\n\n        for transition in mini_batch:  # parse all transitions into their lists.\n            state, action, reward, next_state, done = transition\n            states.append(state)\n            actions.append([action])\n            rewards.append([reward])\n            next_states.append(next_state)\n            dones.append([float(done)])\n\n        return torch.tensor(states, dtype=torch.float), \\\n               torch.tensor(actions, dtype=torch.float), \\\n               torch.tensor(rewards, dtype=torch.float), \\\n               torch.tensor(next_states, dtype=torch.float), \\\n               torch.tensor(dones, dtype=torch.float)\n\n    def size(self) -> int:\n        return len(self.buffer)\n```\n\n## **TASK 1: Actor/Policy network** (2+2=4 Points)\n\nNext, we will set up the actor/policy.\n\n### Task 1.1: Tanh Squashing (2 Points)\nThe original SAC implementation squashes its actions into the $[-1, 1]$ range using a *tanh* activation.\nTo ensure proper probabilities for these actions, it also squashes the log probabilities of each action accordingly.\nYou can show using the change of variables theorem that\n\n\\begin{align}\n    \\log \\pi(\\boldsymbol{a}|\\boldsymbol{s}) = \\log \\mu(\\boldsymbol{u}|\\boldsymbol{s})-\\sum_{i=1}^D \\log\\left(1-\\tanh^2(u_i)\\right)\n\\end{align}\n\nfor (squashed) actions $\\boldsymbol{a}$, states $\\boldsymbol{s}$, proposed (unsquashed) actions $\\boldsymbol{u}$ and a policy\ndistribution $\\mu$ (which you shouldn't confuse with the mean, which is sometimes also called $\\mu$...)\nIn our case, the dimensionality $D=1$.\nYou will need to squash the action itself, as well as its log probability.\n\n### Task 1.2: Training from 2 Q Networks (2 Points)\nAs SAC is using Twin-Delayed Q-Networks to prevent the overestimatio bias in the Q-Values,\nthe actor/policy needs to choose the minimum of both available Q-Networks for its loss function.\nFor this, you will need to evaluate the action using both Q-Networks, and then simply choose their minimum.\n\n\n```python\nclass PolicyNet(nn.Module):\n    def __init__(self, learning_rate: float, entropy_alpha: float):\n        super(PolicyNet, self).__init__()  # make sure that the policy network is registered as a pytorch module\n\n        # specify neurons per layer. \"fc\" is short for \"fully_connected layer\".\n        self.common_mlp = nn.Linear(3, 128)\n        self.mean_mlp = nn.Linear(128, 1)\n        self.std_mlp = nn.Linear(128, 1)\n\n        self.optimizer = optim.Adam(self.parameters(), lr=learning_rate)  # use adam optimizer\n\n        self.entropy_alpha = entropy_alpha  # weight of the entropy term\n\n    def forward(self, state: torch.Tensor, deterministic: bool = False) -> Tuple[torch.Tensor, torch.Tensor]:\n        \"\"\"\n        Choose an action and calcualte its probability for the current state.\n        :param state: The state to choose the action for\n        :param deterministic: Whether to draw an action from\n        :return:\n        \"\"\"\n        state = F.relu(self.common_mlp(state))\n        mean = self.mean_mlp(state)\n        std = F.softplus(self.std_mlp(state))  # we need the standard deviation to be >0\n        normal_distribution = Normal(mean, std)\n\n        if deterministic:\n            action = mean\n        else:\n            action = normal_distribution.rsample()\n        log_probabilities = normal_distribution.log_prob(action)\n\n        # the original SAC implementation also squishes the action into [-1, 1] using a tanh activation.\n        # to keep the probabilities correct, they account for this using the update below.\n\n        ### TODO ###\n        ### Your code starts here ###\n        real_action = torch.tanh(action)\n        real_log_probabilities = log_probabilities - torch.log(1 - torch.tanh(action).pow(2) + 1e-7)\n        ### Your code ends here ###\n        return real_action, real_log_probabilities\n\n    def train_step(self, q_net_1, q_net_2, mini_batch: tuple) -> Dict[str, float]:\n        states, _, _, _, _ = mini_batch\n        actions, log_probabilities = self.forward(states)\n        entropy = -self.entropy_alpha * log_probabilities\n\n        # evaluate both q-networks for the current state-action pair\n        # and use their minimum (see Twin-Delayed Q functions)\n\n        ### TODO ###\n        ### Your code starts here ###\n        q1_value = q_net_1(states, actions)\n        q2_value = q_net_2(states, actions)\n        q1_q2 = torch.cat([q1_value, q2_value], dim=1)\n        min_q = torch.min(q1_q2, 1, keepdim=True)[0]\n        ### Your code ends here ###\n\n        loss = -(min_q + entropy).mean()  # \"-\" for gradient ascent\n        self.optimizer.zero_grad()\n        loss.backward()\n        self.optimizer.step()\n\n        return {\"entropy\": entropy.mean().item(),\n                \"policy_loss\": loss.item()}\n\n```\n\nNext, we implement our Q-Network. This will be used to evaluate (\"criticize\") the actions that the actor proposes.\nNote that this is only *one* Q-Network, and that the SAC class below will use multiple of those for the Twin-Delayed\nQ-Functions.\n\n## Task 2: Polyak Updates ( 2 Points)\nFor increasing stability in the update of the Q Networks, SAC uses polyak updates of each Q Network.\nThe update is given as\n\\begin{align}\n    \\beta'_i = (1-\\tau)\\beta'_i+(\\tau)\\beta_i\n\\end{align}\n\nfor Q-Network parameters $\\beta_1$, $\\beta_2$ and an update rate $\\tau$. Note that the slides use a reverse\norder of $(1-\\tau)$ and $\\tau$, which corresponds to values of $\\tau$ close to $1$ rather than close to $0$\nas done in the code.\n\nHint: Use the `parameters().data` attribute of torch.Tensor to access the parameters. You can copy them\nusing `parameters().data.copy_`.\n\n\n```python\nclass QNet(nn.Module):\n    def __init__(self, learning_rate: float, q_net_update_rate: float):\n        super(QNet, self).__init__()  # make sure that the Q Network is registered as a pytorch module\n        # specify network parameters. \"fc\" is short for \"fully_connected layer\".\n        self.state_layer = nn.Linear(3, 64)\n        self.action_layer = nn.Linear(1, 64)\n        self.common_layer = nn.Linear(128, 32)\n        self.fc_out = nn.Linear(32, 1)\n\n        self.optimizer = optim.Adam(self.parameters(), lr=learning_rate)  # use adam optimizer\n        self.q_net_update_rate = q_net_update_rate\n\n    def forward(self, state: torch.Tensor, action: torch.Tensor) -> torch.Tensor:\n        h1 = F.relu(self.state_layer(state))\n        h2 = F.relu(self.action_layer(action))\n        cat = torch.cat([h1, h2], dim=1)\n        q_evaluation = F.relu(self.common_layer(cat))\n        q_evaluation = self.fc_out(q_evaluation)\n        return q_evaluation\n\n    def train_step(self, target_values: torch.Tensor, mini_batch: tuple) -> float:\n        \"\"\"\n        Train the network for a single mini-batch update\n        :param target_values: The target values to regress to\n        :param mini_batch: A tuple (state, action, reward, next_state, done). For this update,\n          only the action and state are needed\n        :return: The mean loss for this update step\n        \"\"\"\n        states, actions, _, _, _ = mini_batch  # get action and state from current mini_batch\n        evaluation = self.forward(states, actions)\n\n        # calculate the loss and its gradients; update the network based on them\n        loss = F.smooth_l1_loss(evaluation, target_values).mean()\n        self.optimizer.zero_grad()\n        loss.backward()\n        self.optimizer.step()\n        return loss.item()\n\n    def polyak_update(self, target_network):\n        \"\"\"\n        Soft update the target network with the parameters of this network\n        :param target_network:\n        :return:\n        \"\"\"\n        ### TODO ###\n        ### Your code starts here ###\n        for param_target, param in zip(target_network.parameters(), self.parameters()):\n            param_target.data.copy_(param_target.data * (1.0 - self.q_net_update_rate)\n                                    + param.data * self.q_net_update_rate)\n        ### Your code ends here ###\n```\n\nFinally, we combine the Q-Network(s) and the Actor to build our SoftActorCritic class.\nThis class (roughly) implements the Pseudo-code shown in Slide Set 7, Slide 40.\n\n## Task 3: Q-Network Targets (4 Points)\nFor SAC, you will need to implement the targets of the Q-Networks. These are calculated using the rule on Slide Set 7, Slide 35, i.e.,\n\\begin{align}\ny_t = r_t +\\gamma\\left(Q_{\\beta'}(\\boldsymbol{s}'_t, \\boldsymbol{a}') - \\alpha \\log \\pi(\\boldsymbol{a}'|\\boldsymbol{s}'_t)\\right), \\qquad \\text{where ~} \\boldsymbol{a}'\\approx \\pi(\\boldsymbol{a}|\\boldsymbol{s}_t')\n\\end{align}\n\nHints:\n* Remember that $\\beta'$ are the parameters of the **target** Q-Network\n* In our case, $Q_{\\beta'}$ needs to be evaluated as the **minimum** of **both** target Q-Networks\n* You can only do a next step in your next step prediction if there is one, i.e., if the environment is **not** done.\n\n\n```python\nclass SoftActorCritic:\n    def __init__(self, args):\n        learning_rate = args[\"learning_rate\"]\n        q_net_update_rate = args[\"q_net_update_rate\"]\n        batch_size = args[\"batch_size\"]\n        self.discount_factor = args[\"discount_factor\"]\n\n        # initialize two Q-networks and their respective target networks\n        self.q_net_1 = QNet(learning_rate, q_net_update_rate)\n        self.q_net_2 = QNet(learning_rate, q_net_update_rate)\n\n        self.q_net_1_target = copy.deepcopy(self.q_net_1)\n        self.q_net_2_target = copy.deepcopy(self.q_net_2)\n\n        # get a replay buffer and a policy network\n        self.memory = ReplayBuffer(buffer_limit=args[\"buffer_limit\"], batch_size=batch_size)\n\n        self.policy = PolicyNet(learning_rate=learning_rate,\n                                entropy_alpha=args[\"entropy_alpha\"])\n\n    def train_step(self) -> Dict[str, float]:\n        mini_batch = self.memory.sample()\n        q_targets = self.calculate_q_targets(mini_batch)\n\n        # update both q networks\n        q_net_1_loss = self.q_net_1.train_step(q_targets, mini_batch)\n        q_net_2_loss = self.q_net_2.train_step(q_targets, mini_batch)\n\n        # update the policy\n        policy_metrics = self.policy.train_step(self.q_net_1, self.q_net_2, mini_batch)\n\n        # polyak updates for the target q networks\n        self.q_net_1.polyak_update(self.q_net_1_target)\n        self.q_net_2.polyak_update(self.q_net_2_target)\n\n        return {\"q_net_1_loss\": q_net_1_loss,\n                \"q_net_2_loss\": q_net_2_loss,\n                **policy_metrics}\n\n    def calculate_q_targets(self, mini_batch: tuple) -> torch.Tensor:\n        _, _, rewards, next_states, dones = mini_batch\n\n        with torch.no_grad():\n            ### TODO ###\n            ### Your code starts here ###\n            next_action, log_probabilities = self.policy(next_states)\n            entropy = -self.policy.entropy_alpha * log_probabilities\n            q1_val = self.q_net_1_target(next_states, next_action)\n            q2_val = self.q_net_2_target(next_states, next_action)\n            q1_q2 = torch.cat([q1_val, q2_val], dim=1)\n            min_q = torch.min(q1_q2, 1, keepdim=True)[0]\n            target = rewards + (1 - dones) * self.discount_factor * (min_q + entropy)\n            ### Your code ends here ###\n        return target\n```\n\n# Running the algorithm\n\nThat's it for SAC. The code below defines arguments/hyperparameters, as well as a general training loop. You do\n*not* need to change any code here (unless you want to fiddle with the parameters). If everything is implemented\ncorrectly, you should see training improvements after a couple thousand steps, and have a converged solution after\n30000-40000 steps.\nThe code will save\n* a couple of training metrics,\n* a contour plot of a numerical integration of the value function,\ni.e., the maximum of a number of Q-function evaluations on a grid of the state-space\n* a .mp4 video of the pendulum swinging.\n\nFor the homework, you only need to send in the last of each, i.e., the one at iteration 50000, but you can also\nturn in all of the plots as usual.\n\n\n```python\nclass Args:\n    def __getitem__(self, key):\n        return getattr(self, key)\n\n    def __setitem__(self, key, val):\n        setattr(self, key, val)\n\n    num_training_steps = 51000  # @param {type: \"integer\"}\n    learning_rate = 3.0e-4  # @param {type: \"number\"}\n    entropy_alpha = 0.02  # @param {type: \"number\"}\n    discount_factor = 0.98  # @param {type: \"number\"}\n    batch_size = 64  # @param {type: \"integer\"}\n    buffer_limit = 100000  # @param {type: \"integer\"}\n    reward_scale = 0.1  # @param {type: \"number\"}\n    q_net_update_rate = 0.002  # @param {type: \"number\"}\n\ndef main(args: Args):\n    environment = gym.make('Pendulum-v0')\n    evaluation_environment = DummyVecEnv([lambda: gym.make('Pendulum-v0')])\n    # keep a second environment for evaluation purposes.\n    # We wrap it in a Dummy Vector Environment for compatibility with\n    # the visualization utility\n\n    soft_actor_critic = SoftActorCritic(args=args)\n\n    reward_scale = args[\"reward_scale\"]\n    num_training_steps = args[\"num_training_steps\"]\n\n    # logging utility\n    logging_frequency = 100  # log progress every 100 steps\n    plot_frequency = 5000\n    progress_bar = ProgressBar(num_iterations=num_training_steps)\n\n    state = environment.reset()  # restart the environment, i.e., go back to some initial state\n    full_metrics = {\"score\": []}\n    train_step_metrics = {}\n    for current_step in range(num_training_steps):\n        if current_step % logging_frequency == 0:  # log every logging_frequency steps\n            for key, value in train_step_metrics.items():\n                if key not in full_metrics:\n                    full_metrics[key] = []\n                full_metrics[key].append(value)\n\n            evaluation_recordings = evaluate(evaluation_environment=evaluation_environment,\n                                             soft_actor_critic=soft_actor_critic)\n\n            progress_bar(_steps=logging_frequency,\n                         score=evaluation_recordings.get(\"score\"),\n                         **train_step_metrics)\n\n            full_metrics[\"score\"].append(evaluation_recordings.get(\"score\"))\n\n        if current_step % plot_frequency == 0:  # plot visualizations\n            v_function_visualization(evaluation_environment=evaluation_environment,\n                                     soft_actor_critic=soft_actor_critic,\n                                     current_step=current_step)\n            visualize_rollout(soft_actor_critic=soft_actor_critic,\n                              step=current_step)\n            plot_metrics(full_metrics)\n\n        # alternate between collecting one step of data and updating SAC with one mini-batch\n        action, log_probabilities = soft_actor_critic.policy(torch.from_numpy(np.array(state)).float())\n        next_state, reward, done, info = environment.step([environment.action_space.high[0] * action.item()])\n\n        # safe (s, a, r, s', done) tuple in memory buffer\n        soft_actor_critic.memory.put((state, action.item(), reward * reward_scale, next_state, done))\n\n        if done:\n            state = environment.reset()\n        else:\n            state = next_state\n\n        # wait until there are enough rollouts in the memory buffer before starting the training\n        if soft_actor_critic.memory.size() > 1000:\n            train_step_metrics = soft_actor_critic.train_step()\n            train_step_metrics[\"buffer_size\"] = soft_actor_critic.memory.size()\n    environment.close()\n\n\nargs = Args()\nmain(args=args)\n\n```\n", "meta": {"hexsha": "6787a8fd549ab573494238c8d997fd816dd97a03", "size": 36872, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "src/models/sac/4_soft_actor_critic_solution.ipynb", "max_stars_repo_name": "dapetri/coin-it", "max_stars_repo_head_hexsha": "933b56a85abca9e5130d7a657c9524e76bc09c35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/models/sac/4_soft_actor_critic_solution.ipynb", "max_issues_repo_name": "dapetri/coin-it", "max_issues_repo_head_hexsha": "933b56a85abca9e5130d7a657c9524e76bc09c35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/models/sac/4_soft_actor_critic_solution.ipynb", "max_forks_repo_name": "dapetri/coin-it", "max_forks_repo_head_hexsha": "933b56a85abca9e5130d7a657c9524e76bc09c35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.8037267081, "max_line_length": 241, "alphanum_fraction": 0.5534009547, "converted": true, "num_tokens": 6325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.1023047024186547, "lm_q1q2_score": 0.043614703660217954}}
{"text": "# <center><b>Oil Data Quality Index</b></center>\n\n### <center>First Draft<br><br>January 2015<br>Author: James L. Makela</center>\n\n## <u>1. Background</u>\n\nThe Adios3 Oil Library will accept data on crude oils and refined products provided they contain a minimum required set of data.  Additional missing data will be generated by approximation formulas according to the <b><i>Oil Properties Estimation</i></b> document.\n\nIt is reasonable to propose that the more measured data that an oil record has, the better job we will do when estimating missing oil properties. <i>(Ideally, we would not need to estimate anything, but simply use measured values)</i>\n\nSo in addition to requiring a minimum set of measured data, we will try to assess an oil record's <b>quality index</b>.  The quality index is a numeric score that we will use to represent an oils \"fitness\", or to put it another way, how well we expect to be able to calculate reasonable estimates of the missing oil properties.\n\n\n```python\n%pylab inline\nimport numpy as np\n\nimport oil_library\nfrom oil_library.models import Oil, ImportedRecord, KVis\n\nsession = oil_library._get_db_session()\n\n# these are some reasonable samples of oil records in the oil library\nans_mp = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'ALASKA NORTH SLOPE (MIDDLE PIPELINE)').one()\nans_2002 = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'ALASKA NORTH SLOPE (2002)').one()\nans_ps9 = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'ALASKA NORTH SLOPE-PUMP STATION #9, BP').one()\narabian_hvy = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'ARABIAN HEAVY, AMOCO').one()\nborholla = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'BORHOLLA').one()\nlls_bp = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'LIGHT LOUISIANNA SWEET, BP').one()\nbenin = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'BENIN RIVER, CHEVRON').one()\nempire = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'EMPIRE ISLAND, AMOCO').one()\nsajaa = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'SAJAA CONDENSATE, BP').one()\n\n```\n\n    Populating the interactive namespace from numpy and matplotlib\n\n\n## <u>2. Minimum Data Required</u>\n\nAs previously mentioned, we only accept oil records that contain a minimum required set of data.  Otherwise, we will not process the record.\n\n| Type | Density (or API) | Viscosity | Distillation Cuts |\n| ---- |:----------------:|:---------:|:-----------------:|\n| Crude | Yes | Yes | No |\n| Refined Product | Yes | Yes | Yes (at least 3) |\n\n\n## <u>3. Calculating the Quality Index</u>\n\n### <u>3.1 The General Scoring Method</u>\n\nThe total score of the oil will be an aggregation of 1 or more tests which will result in a quality index.  A quality index $Q$ is defined with a range:\n\n$$\n\\begin{align}\n0 &\\leq Q \\leq 1\n\\end{align}\n$$\n\nThis score can (naively) be considered a single test, but is more likely to be a compilation of scores of multiple sub-tests.  In turn, each sub-test could be considered in a similar fashion, making a tree structure of tests of which the leaf-level tests contain only a single test.  So we will define the terminology of our testing processes as either <b>'Aggregate'</b> or <b>'Atomic'</b>.\n\n\n### <u>3.2 Atomic Test Score</u>\n\nThe assumption for an atomic test method is that it is testing only one thing.  As such, the results of an atomic test method will be:\n\n$$\n\\begin{align}\nQ &= 0 \\qquad \\qquad \\text{(the test failed)} \\cr\nQ &= 1 \\qquad \\qquad \\text{(the test passed)} \\cr\n\\end{align}\n$$\n\n\n### <u>3.3 Aggregate Test Score</u>\n\nThe assumption for an aggregate test method is that it is testing a number of things.  These things are assumed to be a collection of sub-tests which will each return a score $Q_i$.  An aggregate test will return an ordinary or weighted average of the collection of sub-test scores $\\bar{Q}$, with the same numeric range as $Q$. \n\n$$\n\\begin{align}\nn &= \\text{the number of sub-tests} \\cr\nQ_i &= \\text{a sub-test result indexed by } i \\cr\nw_i &= \\text{the weighted value of a sub-test indexed by } i \\cr\n&\\quad \\text{for an ordinary average, the weights will be } [1, 1, \\ldots] \\cr\n\\cr\n\\bar{Q} &= {\\sum\\limits_{i=1}^{n}{w_i \\cdot Q_i} \\over \\sum\\limits_{i=1}^n{w_i}} \\cr\n\\end{align}\n$$\n\n\n```python\ndef aggregate_score(Q_i, w_i=None):\n    Q_i = np.array(Q_i)\n    \n    if w_i is None:\n        w_i = np.ones(Q_i.shape)\n    else:\n        w_i = np.array(w_i)\n    \n    return np.sum(w_i * Q_i) / np.sum(w_i)\n\nQ_i = [1.0, 1.0, 1.0, 0.0]\nw_i = [1.0, 1.0, 1.0, 1.0]\n\nprint aggregate_score(Q_i)  # simple average (0.75)\nprint aggregate_score(Q_i, w_i) # explicit simple average (0.75)\n\nQ_i = [1.0, 1.0, 1.0, 1.0]\nw_i = [3.0, 1.0, 1.0, 1.0]\nprint aggregate_score(Q_i, w_i)  # weighted average (1.0)\n\nQ_i = [1.0, 0.0, 0.0, 0.0]\nw_i = [3.0, 1.0, 1.0, 1.0]\nprint aggregate_score(Q_i, w_i)  # weighted average (0.5)\n\nQ_i = [0.0, 1.0, 0.0, 0.0]\nw_i = [3.0, 1.0, 1.0, 1.0]\nprint aggregate_score(Q_i, w_i)  # weighted average (1/6 or 0.1666)\n\n```\n\n    0.75\n    0.75\n    1.0\n    0.5\n    0.166666666667\n\n\n## <u>4. The Imported Oil Record Tests</u>\n\n### <u>4.1 Oil Demographics</u>\n\nWe would like to gauge the richness of the demographic data in the record.  These are the text fields that describe the oil record, and if the need arises, they can help us to investigate the source of the oil data found in the record.\n\nThe demographic fields will be tested simply for their presence.  For now, we will not place special importance on any particular demographic field, so a simple average will be used for scoring the multiple fields.\n\nThe demographic fields to be tested are:\n- reference\n\n<i>(<b>Note</b>: in future versions we may want to add source quality flag, and age.)</i>\n\n\n```python\ndef score_demographics(imported_rec):\n    fields = ('reference',)\n    scores = []\n\n    for f in fields:\n        if getattr(imported_rec, f) is not None:\n            scores.append(1.0)\n        else:\n            scores.append(0.0)\n\n    return aggregate_score(scores)\n\nfor ir in (ans_mp, ans_ps9, arabian_hvy, borholla,\n           lls_bp, benin, empire, sajaa):\n    print ('Oil: {}, Demographics Score: {}'\n           .format(ir.oil_name, score_demographics(ir)))\n\n```\n\n    Oil: ALASKA NORTH SLOPE (MIDDLE PIPELINE), Demographics Score: 1.0\n    Oil: ALASKA NORTH SLOPE-PUMP STATION #9, BP, Demographics Score: 1.0\n    Oil: ARABIAN HEAVY, AMOCO, Demographics Score: 1.0\n    Oil: BORHOLLA, Demographics Score: 1.0\n    Oil: LIGHT LOUISIANNA SWEET, BP, Demographics Score: 1.0\n    Oil: BENIN RIVER, CHEVRON, Demographics Score: 1.0\n    Oil: EMPIRE ISLAND, AMOCO, Demographics Score: 1.0\n    Oil: SAJAA CONDENSATE, BP, Demographics Score: 1.0\n\n\n### <u>4.2 Oil API</u>\n\nAn imported oil record is required by us to have either an API density value or a set of densities measured at reference temperatures.  So this may seem like an unnecessary test.  However we would surmise that a record that has both types of density information is of better quality than a record that contains only one or the other.  So for this reason we test the oil for an API value and return an atomic score.\n\n\n```python\ndef score_api(imported_rec):\n    if imported_rec.api is None:\n        return 0.0\n    else:\n        return 1.0\n\nfor ir in (ans_mp, ans_ps9, arabian_hvy, borholla,\n           lls_bp, benin, empire, sajaa):\n    print ('Oil: {}, API Score: {}'\n           .format(ir.oil_name, score_api(ir)))\n\n```\n\n    Oil: ALASKA NORTH SLOPE (MIDDLE PIPELINE), API Score: 1.0\n    Oil: ALASKA NORTH SLOPE-PUMP STATION #9, BP, API Score: 0.0\n    Oil: ARABIAN HEAVY, AMOCO, API Score: 0.0\n    Oil: BORHOLLA, API Score: 1.0\n    Oil: LIGHT LOUISIANNA SWEET, BP, API Score: 1.0\n    Oil: BENIN RIVER, CHEVRON, API Score: 1.0\n    Oil: EMPIRE ISLAND, AMOCO, API Score: 0.0\n    Oil: SAJAA CONDENSATE, BP, API Score: 1.0\n\n\n### <u>4.3 Oil Densities</u>\n\nAn imported oil record can contain 0 to 4 density values that are measured at different reference temperatures.  In addition, we will consider the oil's API as a density at $15^\\circ C$.  We will give an atomic pass/fail score to each density measurement set that is found in the oil record.\n\nRight now, we are testing that the oil's existing density attributes:\n- contain a valid numeric density value and...\n- contain a valid numeric temperature\n\n<i>(<b>Note</b>: For the future, we could test that density is in a reasonable range for oils, that the temperature is in a reasonable kelvin range, maybe a couple of other things)</i>\n\nIf any density attribute fails any one of the density testing criteria, it is given a score of 0.<br>\n\nWe would surmise that the more distinct measurements we have, the better we would be able to estimate oil density at an arbitrary temperature, and so the oil record would have a better quality.  I believe that we should place the biggest weight on the first density, and the weights of all successive densities should diminish exponentially as in the following series:\n\n$$\n\\begin{align}\nw_i &= \\left[0.5, 0.25, 0.125, \\ldots \\frac{1}{2^n}\\right] \\cr\n\\end{align}\n$$\n\nWe would like to see 4 valid density measurements present in our oil record, so if it has less than that, we would assign a score $Q = 0$ for any missing density up to that number.\n\n\n```python\ndef score_density_rec(density_rec):\n    if (density_rec.kg_m_3 is not None and\n            density_rec.ref_temp_k is not None):\n        return 1.0\n    else:\n        return 0.0\n\ndef score_densities(imported_rec):\n    scores = []\n\n    for d in imported_rec.densities:\n        scores.append(score_density_rec(d))\n\n    if not any([np.isclose(d.ref_temp_k, [288.0, 288.15]).any()\n                for d in imported_rec.densities]):\n        scores.append(score_api(imported_rec))\n\n    # We have a maximum number of 4 density field sets in our flat file\n    # We can set a lower acceptable number later\n    if len(scores) < 4:\n        scores += [0.0] * (4 - len(scores))\n\n    # compute our weights \n    w_i = 1.0 / (2.0 ** (np.arange(len(scores)) + 1))\n    w_i[-1] = w_i[-2]  # duplicate the last weight so we sum to 1.0\n\n    return aggregate_score(scores, w_i)\n\nfor ir in (ans_mp, ans_2002, ans_ps9, arabian_hvy, borholla,\n           lls_bp, benin, empire, sajaa):\n    print 'Oil: {}'.format(ir.oil_name)\n    print '\\tAPI: {}'.format(ir.api)\n    print '\\tDensities: {}'.format(ir.densities)\n    print ('\\tScore: {}'\n           .format(score_densities(ir)))\n\n```\n\n    Oil: ALASKA NORTH SLOPE (MIDDLE PIPELINE)\n    \tAPI: 29.9\n    \tDensities: [<Density(886.9 kg/m^3 at 273.15K)>, <Density(876.1 kg/m^3 at 288.15K)>]\n    \tScore: 0.75\n    Oil: ALASKA NORTH SLOPE (2002)\n    \tAPI: 30.9\n    \tDensities: [<Density(878.0 kg/m^3 at 273.0K)>, <Density(905.0 kg/m^3 at 273.0K)>, <Density(930.0 kg/m^3 at 273.0K)>, <Density(946.0 kg/m^3 at 273.0K)>]\n    \tScore: 1.0\n    Oil: ALASKA NORTH SLOPE-PUMP STATION #9, BP\n    \tAPI: None\n    \tDensities: [<Density(888.0 kg/m^3 at 274.15K)>, <Density(875.0 kg/m^3 at 288.15K)>]\n    \tScore: 0.75\n    Oil: ARABIAN HEAVY, AMOCO\n    \tAPI: None\n    \tDensities: [<Density(888.0 kg/m^3 at 288.15K)>]\n    \tScore: 0.5\n    Oil: BORHOLLA\n    \tAPI: 31.31\n    \tDensities: []\n    \tScore: 0.5\n    Oil: LIGHT LOUISIANNA SWEET, BP\n    \tAPI: 35.6\n    \tDensities: []\n    \tScore: 0.5\n    Oil: BENIN RIVER, CHEVRON\n    \tAPI: 39.3\n    \tDensities: []\n    \tScore: 0.5\n    Oil: EMPIRE ISLAND, AMOCO\n    \tAPI: None\n    \tDensities: [<Density(858.0 kg/m^3 at 288.15K)>]\n    \tScore: 0.5\n    Oil: SAJAA CONDENSATE, BP\n    \tAPI: 57.5\n    \tDensities: [<Density(748.0 kg/m^3 at 288.15K)>]\n    \tScore: 0.5\n\n\n### <u>4.4 Oil Pour Point</u>\n\nAn oil has two pour point values.  The notion of pour point is defined as simply the temperature at which the oil enters its solid phase or \"stops pouring\".  However, the paraffins in the oil have a tendency to form crystalline structures over time which will in turn elevate the pour point temperature.  So a maximum pour point is measured for the case in which the oil has stayed at a constant temperature for awhile, and a minimum pour point value is often measured for the case that the oil was recently heated, breaking down the crystalline structures.  The \"freshly heated\" pour point is expected to be lower than the pour point of older oil kept in a constant temperature.\n\nSo in the interest of evaluating the quality of an oil record, we would definitely like to see at least one valid pour point value.  But the presence of a second (min) value may simply indicate an oil with a lot of paraffins.  It's unclear whether we should assign extra credit for having two values.\n\nAt this point in time, we are assigning a score for both a minimum and maximum value, and we will apply the following weights:\n- pour_point_max_k: 2\n- pour_point_min_k: 1\n\nThis indicates that we want to at least see the maximum pour point temperature, and it will account for the majority of scoring for this test.  But we want to give half credit for having a minimum pour point.\n\n\n```python\ndef score_pour_point_min(imported_rec):\n    return (1.0 if imported_rec.pour_point_min_k is not None else 0.0)\n    \ndef score_pour_point_max(imported_rec):\n    return (1.0 if imported_rec.pour_point_max_k is not None else 0.0)\n    \ndef score_pour_point(imported_rec):\n    scores = []\n\n    scores.append(score_pour_point_max(imported_rec))\n    scores.append(score_pour_point_min(imported_rec))\n    weights = [2.0, 1.0]\n\n    return aggregate_score(scores, weights)\n\nprint score_pour_point(borholla)  # no pour point data\nprint score_pour_point(arabian_hvy)  # max, but not min\nprint score_pour_point(ans_mp)  # both max and min\n\n```\n\n    0.0\n    0.666666666667\n    1.0\n\n\n### <u>4.5 Oil Flash Point</u>\n\nAn oil record contains a flash point minimum and maximum value.  It is a bit unclear to me what the distinction between the minimum and maximum is.  However there are two possiblities, which I will explain.\n\nA <b>minimum flash point</b> is defined as the minimum temperature at which an oil or fuel product will ignite on application of an ignition source under specified conditions.\n\nThe <b>fire point</b> of an oil or fuel product is the temperature at which the vapor produced by that product will continue to burn for at least 5 seconds after ignition by an open flame. So at the flash point, which would be a lower temperature, a substance will ignite briefly, but vapor might not be produced at a high enough rate to sustain the fire.  The fire point can be estimated to be roughly $10^\\circ C$ higher than flash point.\n\nOk, based on this assessment of flash point and fire point, I looked at the source data for the oil records, and for the vast majority of records that contain both values, the values were nearly identical, which indicates to me we are not dealing with a fire point value stored as a maximum flash point.\n\nThere was a small handful of records that had a maximum flash point significantly higher than the minimum, which could indicate that it is a fire point.\n\nI believe that we can consider of both the minimum and maximum values as being a flash point, and that if we have at least one value, we probably have sufficient data quality.  So the rules are:\n\n- if we have no flash point, min or max, then $Q = 0$\n- if we have a minimum flash point, then $Q = 1$\n- if we have a maximum flash point, then $Q = 1$\n- if we have both a maximum and minimum flash point, then $Q = 1$\n\n\n\n```python\ndef score_flash_point(imported_rec):\n    if (imported_rec.flash_point_min_k is not None or\n            imported_rec.flash_point_max_k is not None):\n        return 1.0\n    else:\n        return 0.0\n\nfor ir in (ans_mp, ans_ps9, arabian_hvy, borholla,\n           lls_bp, benin, empire, sajaa):\n    print ('Oil: {}, \\tFlash Point Score: {}'\n           .format(ir.oil_name, score_flash_point(ir)))\n\n```\n\n    Oil: ALASKA NORTH SLOPE (MIDDLE PIPELINE), \tFlash Point Score: 1.0\n    Oil: ALASKA NORTH SLOPE-PUMP STATION #9, BP, \tFlash Point Score: 1.0\n    Oil: ARABIAN HEAVY, AMOCO, \tFlash Point Score: 1.0\n    Oil: BORHOLLA, \tFlash Point Score: 0.0\n    Oil: LIGHT LOUISIANNA SWEET, BP, \tFlash Point Score: 0.0\n    Oil: BENIN RIVER, CHEVRON, \tFlash Point Score: 0.0\n    Oil: EMPIRE ISLAND, AMOCO, \tFlash Point Score: 1.0\n    Oil: SAJAA CONDENSATE, BP, \tFlash Point Score: 0.0\n\n\n### <u>4.6 Oil SARA Fractions</u>\n\nThe sub-compounds that make up an oil have been categorized, at least traditionally, by organic chemists as saturates, aromatics, resins, and asphaltenes.  This group of four chemical categories is known as SARA.  And an imported oil record may (or may not) contain measured fractional values for them.  If it does, then we would say that the record has better data quality, since we have a reasonable reference to double check the veracity of the SARA component estimations that we perform.\n\nNo particular SARA value is perceived to have a more important role than any other, so we will evaluate them with equal weights when evaluating the score for existance of SARA fractions.\n\n\n```python\ndef score_sara_saturates(imported_rec):\n    return (1.0 if imported_rec.saturates is not None else 0.0)\n\ndef score_sara_aromatics(imported_rec):\n    return (1.0 if imported_rec.aromatics is not None else 0.0)\n\ndef score_sara_resins(imported_rec):\n    return (1.0 if imported_rec.resins is not None else 0.0)\n\ndef score_sara_asphaltenes(imported_rec):\n    return (1.0 if imported_rec.asphaltenes is not None else 0.0)\n\ndef score_sara_fractions(imported_rec):\n    scores = []\n\n    scores.append(score_sara_saturates(imported_rec))\n    scores.append(score_sara_aromatics(imported_rec))\n    scores.append(score_sara_resins(imported_rec))\n    scores.append(score_sara_asphaltenes(imported_rec))\n\n    return aggregate_score(scores)\n\nprint score_sara_fractions(ans_mp)  # no SARA fractions\nprint score_sara_fractions(lls_bp)  # Asphaltenes only\nprint score_sara_fractions(benin)  # Saturates, Aromatics, Asphaltenes, no Resins\n\n```\n\n    0.0\n    0.25\n    0.75\n\n\n### <u>4.7 Oil Emulsion Constants</u>\n\nAn imported oil record contains a minimum and maximum value for emulsion constant.\nAfter a discussion with Bill & Chris we have decided to go with the following weights for our emulsion properties.\n\n- water_content_emulsion: weight = 2\n- emuls_constant_min: weight = 3\n- emuls_constant_max: weight = 0\n\n\n```python\ndef score_water_content_emulsion(imported_rec):\n    return (1.0 if imported_rec.water_content_emulsion is not None else 0.0)\n\ndef score_emulsion_constant_min(imported_rec):\n    return (1.0 if imported_rec.emuls_constant_min is not None else 0.0)\n\ndef score_emulsion_constant_max(imported_rec):\n    return (1.0 if imported_rec.emuls_constant_max is not None else 0.0)\n\ndef score_emulsion_constants(imported_rec):\n    scores = []\n\n    scores.append(score_water_content_emulsion(imported_rec))\n    scores.append(score_emulsion_constant_min(imported_rec))\n    # scores.append(score_emulsion_constant_max(imported_rec))\n    w_i = [2.0, 3.0]\n\n    return aggregate_score(scores, w_i)\n\nprint score_emulsion_constants(ans_mp)  # no emulsion constant\nprint score_emulsion_constants(empire)  # both min & max\n\n```\n\n    0.0\n    0.6\n\n\n### <u>4.8 Interfacial Tensions</u>\n\nAn oil record contains values for oil/water and oil/seawater interfacial tensions measured at a reference temperature.  So the check we need to perform is an atomic score of each measured value and its associated reference temperature.\n\nWe will score each measurement set as such:\n- if the measurement and temperature are valid numeric values, then $Q = 1$\n- else $Q = 0$\n\nNo particular interfacial tension value is perceived to have a more important role than the other, so they will be evaluated with an equally weighted score.\n\n\n```python\ndef score_oil_water_tension(imported_rec):\n    if (imported_rec.oil_water_interfacial_tension_n_m is not None and\n            imported_rec.oil_water_interfacial_tension_ref_temp_k is not None):\n        return 1.0\n    else:\n        return 0.0\n\ndef score_oil_seawater_tension(imported_rec):\n    if (imported_rec.oil_seawater_interfacial_tension_n_m is not None and\n            imported_rec.oil_seawater_interfacial_tension_ref_temp_k is not None):\n        return 1.0\n    else:\n        return 0.0\n\ndef score_interfacial_tensions(imported_rec):\n    scores = []\n\n    scores.append(score_oil_water_tension(imported_rec))\n    scores.append(score_oil_seawater_tension(imported_rec))\n\n    return aggregate_score(scores)\n\nprint score_interfacial_tensions(lls_bp)  # no interfacial tensions\nprint score_interfacial_tensions(empire)  # only oil/seawater\nprint score_interfacial_tensions(ans_mp)  # both oil/water and oil/seawater\n\n```\n\n    0.0\n    0.5\n    1.0\n\n\n### <u>4.9 Oil Viscosities</u>\n\nAn oil record can contain measurement data for up to 6 kinematic viscosities and 6 dynamic viscosities, each with an associated measurement reference temperature.  So we need to perform an atomic score of each measured value and its associated reference temperature.\n\nWe will score each measurement set as such:\n- if the measurement and temperature are valid numeric values, then $Q = 1$\n- else $Q = 0$\n\nNo particular viscosity measurement is perceived to be more important than the other.\nBut it is often the case that a dynamic viscosity exists with a redundant reference temperature to that of a kinematic viscosity measurement.  In that case, we will count the kinematic viscosity as a unique measurement and ignore the dynamic measurement.\n\nWe would surmise that the more distinct measurements we have, the better we would be able to estimate oil viscosity at an arbitrary temperature, and so the oil record would have a better quality.  So I believe that we should place the biggest weight on the first viscosity, and the weights of all successive viscosities should diminish exponentially as in the following series:\n\n$$\n\\begin{align}\nw_i &= \\left[0.5, 0.25, 0.125, \\ldots \\frac{1}{2^n}\\right] \\cr\n\\end{align}\n$$\n\nWe would also like to see at least 4 valid viscosity measurements present in our oil record, so if it has less than that, we would assign a score $Q = 0$ for any missing viscosity up to that number.<br>\nIn addition, any viscosity measurement that exists for the record, but does not have a passing score should be counted even if the total number of viscosities exceeds 4.  The reasoning for this is that bad data is just as relevent as missing data.\n\n\n\n```python\ndef score_single_viscosity(viscosity_rec):\n    temp = viscosity_rec.ref_temp_k\n\n    try:\n        value = viscosity_rec.m_2_s\n    except AttributeError:\n        value = viscosity_rec.kg_ms\n\n    if (value is not None and temp is not None):\n        return 1.0\n    else:\n        return 0.0\n\ndef score_viscosities(imported_rec):\n    scores = []\n    all_temps = set()\n    all_viscosities = []\n\n    for v in imported_rec.kvis + imported_rec.dvis:\n        if v.ref_temp_k not in all_temps:\n            all_viscosities.append(v)\n            all_temps.add(v.ref_temp_k)\n\n    for v in all_viscosities:\n        scores.append(score_single_viscosity(v))\n\n    # We require a minimum number of 4 viscosity field sets\n    if len(scores) < 4:\n        scores += [0.0] * (4 - len(scores))\n\n    # compute our weights \n    w_i = 1.0 / (2.0 ** (np.arange(len(scores)) + 1))\n    w_i[-1] = w_i[-2]  # duplicate the last weight so we sum to 1.0\n\n    return aggregate_score(scores, w_i)\n\nfor ir in (ans_mp, arabian_hvy, borholla, lls_bp, benin, empire):\n    print ir.kvis, ir.dvis\n    print score_viscosities(ir)\n    print\n\n```\n\n    [] [<DVis(0.034 kg/ms at 273.15K)>, <DVis(0.016 kg/ms at 288.15K)>]\n    0.75\n    \n    [<KVis(4.71e-05 m^2/s at 288.15K)>, <KVis(3.54e-05 m^2/s at 295.15K)>] [<DVis(0.0418 kg/ms at 288.15K)>, <DVis(0.0313 kg/ms at 295.15K)>]\n    0.75\n    \n    [<KVis(7.36e-06 m^2/s at 323.15K)>, <KVis(3.26e-06 m^2/s at 333.15K)>] []\n    0.75\n    \n    [<KVis(5.3e-06 m^2/s at 310.9278K)>] []\n    0.5\n    \n    [] [<DVis(0.0951 kg/ms at 303.15K)>]\n    0.5\n    \n    [<KVis(1.41e-05 m^2/s at 285.15K)>, <KVis(8.8e-06 m^2/s at 300.15K)>] [<DVis(0.0121 kg/ms at 285.15K)>, <DVis(0.0075 kg/ms at 300.15K)>]\n    0.75\n    \n\n\n### <u>4.10 Oil Distillation Cuts</u>\n\nAn oil record can contain measurement data for up to 15 distillation cuts, each with an associated vapor temperature, liquid temperature, and a cumulative fractional value representing the portion of oil that is evaporated at that temperature. So we need to perform an aggregate score of each cut.\n\nFor each individual cut it is essential that it have at least a distilled fraction, otherwise it is not valid.\nAnd we would prefer a vapor temperature to be present, but we could still make use of a liquid temperature if it doesn't exist.  So we will determine a cut to be valid if it has either of those temperatures.\n\nThe score for each individual valid cut will be performed as follows:\n- if there is no evaporated fraction then $Q = 0$\n- otherwise:\n    - if there is a vapor temperature, then  $Q = 1$\n    - otherwise, if there is a liquid temperature only then $Q = 0.8$\n    - otherwise, $Q = 0$\n\nWe would surmise that the more distinct measurements we have, the better we would be able to estimate our oil distillation curve, and so the oil record would have a better quality.  I believe that we should place the biggest weight on the first cut, and the weights of all successive cuts should diminish exponentially as in the following series:\n\n$$\n\\begin{align}\nw_i &= \\left[0.5, 0.25, 0.125, \\ldots \\frac{1}{2^n}\\right] \\cr\n\\end{align}\n$$\n\nWe would also like to see at least 10 valid distillation cuts present in our oil record, so if it has less than that, we would assign a score $Q = 0$ for any missing distillation cut up to that number.<br>\nIn addition, any cut that exists for the record, but does not have a passing score should be counted even if the total number of cuts exceeds 10.  The reasoning for this is that bad data is just as relevent as missing data.\n\n<i>\n(<b>Note</b>: in the future we could be a bit more discerning of this data.  We could, for instance, exclude any cuts for which the distillation fraction does not increase with an increasing temperature.)\n</i>\n\n\n```python\ndef cut_has_vapor_temp(cut_rec):\n    return (0.0 if cut_rec.vapor_temp_k is None else 1.0)\n\ndef cut_has_liquid_temp(cut_rec):\n    return (0.0 if cut_rec.liquid_temp_k is None else 1.0)\n\ndef cut_has_fraction(cut_rec):\n    return (0.0 if cut_rec.fraction is None else 1.0)\n\ndef score_cut(cut_rec):\n    if cut_has_fraction(cut_rec) == 1.0:\n        if cut_has_vapor_temp(cut_rec) == 1.0:\n            return 1.0\n        elif cut_has_liquid_temp(cut_rec) == 1.0:\n            return 0.8\n        else:\n            return 0.0\n    else:\n        return 0.0\n\ndef score_cuts(imported_rec):\n    scores = []\n\n    for c in imported_rec.cuts:\n        scores.append(score_cut(c))\n\n    # We would like a minimum number of 10 distillation cuts\n    if len(scores) < 10:\n        scores += [0.0] * (10 - len(scores))\n\n    # compute our weights\n    w_i = 1.0 / (2.0 ** (np.arange(len(scores)) + 1))\n    w_i[-1] = w_i[-2]  # duplicate the last weight so we sum to 1.0\n\n    return aggregate_score(scores, w_i)\n\nfor ir in (ans_mp, benin, ans_ps9, arabian_hvy, sajaa, borholla):\n    print 'name = ', ir.oil_name\n    print '\\tnum_cuts: {}'.format(len(ir.cuts))\n    print ('\\tCuts that have vapor temp: {}'\n           .format(np.sum([(c.vapor_temp_k is not None)\n                           for c in ir.cuts])))\n    print '\\tCuts Score: {}'.format(score_cuts(ir))\n    print\n\n```\n\n    name =  ALASKA NORTH SLOPE (MIDDLE PIPELINE)\n    \tnum_cuts: 10\n    \tCuts that have vapor temp: 10\n    \tCuts Score: 1.0\n    \n    name =  BENIN RIVER, CHEVRON\n    \tnum_cuts: 13\n    \tCuts that have vapor temp: 13\n    \tCuts Score: 1.0\n    \n    name =  ALASKA NORTH SLOPE-PUMP STATION #9, BP\n    \tnum_cuts: 8\n    \tCuts that have vapor temp: 8\n    \tCuts Score: 0.99609375\n    \n    name =  ARABIAN HEAVY, AMOCO\n    \tnum_cuts: 6\n    \tCuts that have vapor temp: 6\n    \tCuts Score: 0.984375\n    \n    name =  SAJAA CONDENSATE, BP\n    \tnum_cuts: 3\n    \tCuts that have vapor temp: 3\n    \tCuts Score: 0.875\n    \n    name =  BORHOLLA\n    \tnum_cuts: 0\n    \tCuts that have vapor temp: 0.0\n    \tCuts Score: 0.0\n    \n\n\n### <u>4.11 Oil Toxicities</u>\n\nAn oil record can contain up to 6 sets of toxicity information.  These are separated into two groups of three items each; Effective Concentration (EC) and Lethal Concentration (LC).<br>\n\nWe don't currently use this information in our models, but it is concievable that it might be useful in the future.  So we will describe a scoring method for this information, but the bar for success will be low.\n\nThe effective concentration data set will include the name of the species of animal, and a number of concentrations necessary for immobilization of 50% of the population of that animal after a period of exposure.  The exposure times are 24, 48, and 96 hours.\n\nSimilarly, the lethal concentration data set will include the name of the species of animal, and a number of concentrations necessary to cause death of 50% of the population of that animal after a period of exposure.  The exposure times are 24, 48, and 96 hours.\n\nOur test of an individual toxicity set will simply be the presence of a species, and at least one concentration value.  If satisfies that requirement, it will get a score of $Q = 1$.  And we will only need to see one toxicity set to pass with a total score of $Q = 1$.\n\n<i>\n(<b>Note</b>: I can't find any oils with toxicities anymore.  Either the filemaker export process is broken, or we have decided not to include this information anymore.)\n</i>\n\n\n```python\ndef score_single_toxicity(tox_rec):\n    if (tox_rec.species is not None and\n        (tox_rec.after_24h is not None or\n         tox_rec.after_48h is not None or\n         tox_rec.after_96h is not None)):\n        return 1.0\n    else:\n        return 0.0\n\ndef score_toxicities(imported_rec):\n    scores = []\n\n    for t in imported_rec.toxicities:\n        scores.append(score_single_toxicity(t))\n\n    if any([(s == 1.0) for s in scores]):\n        return 1.0\n    else:\n        return 0.0\n\nfor ir in (ans_mp, benin):\n    print 'name = ', ir.oil_name\n    print 'toxicities = ', ir.toxicities\n    print score_toxicities(ir)\n    print\n\n```\n\n    name =  ALASKA NORTH SLOPE (MIDDLE PIPELINE)\n    toxicities =  []\n    0.0\n    \n    name =  BENIN RIVER, CHEVRON\n    toxicities =  []\n    0.0\n    \n\n\n## <u>5. The Final Score of an Imported Oil Record</u>\n\nThe final score of an imported oil record will be an aggregation of the resulting scores of the individual tests described above.  We will use a weighted average, and the weights will be tailored to the perceived importance of each test.\n\nThe perceived importance of the individual tests are certainly debatable.  For now, here is a current list of the individual tests here with their weighted importance.\n\n| Test                 | Weight | Cumulative |\n| ----                 |:------:|:----------:|\n| Densities            | 5      | 5          |\n| Viscosities          | 5      | 10         |\n| SARA Fractions       | 5      | 15         |\n| Distillation Cuts    | 10     | 25         |\n| Interfacial Tensions | 3      | 28         |\n| Pour Point           | 2      | 30         |\n| Demographics         | 1      | 31         |\n| Flash Point          | 1      | 32         |\n| Emulsion Constants   | 1      | 33         |\n| Toxicities           | 0      | 33         |\n\nNote: api and density taken together.  api = density at 15C total weight 5\n\n\n```python\ndef score_imported_oil(imported_rec):\n    scores = [(score_densities(imported_rec), 5.0),\n              (score_viscosities(imported_rec), 5.0),\n              (score_sara_fractions(imported_rec), 5.0),\n              (score_cuts(imported_rec), 10.0),\n              (score_interfacial_tensions(imported_rec), 3.0),\n              (score_pour_point(imported_rec), 2.0),\n              (score_demographics(imported_rec), 1.0),\n              (score_flash_point(imported_rec), 1.0),\n              (score_emulsion_constants(imported_rec), 1.0)]\n\n    return aggregate_score(*zip(*scores))\n\nfor ir in (ans_mp, ans_ps9, arabian_hvy, borholla,\n           lls_bp, benin, empire, sajaa):\n    print 'Oil: {}, Score: {}'.format(ir.oil_name,\n                                      score_imported_oil(ir))\n\n```\n\n    Oil: ALASKA NORTH SLOPE (MIDDLE PIPELINE), Score: 0.742424242424\n    Oil: ALASKA NORTH SLOPE-PUMP STATION #9, BP, Score: 0.741240530303\n    Oil: ARABIAN HEAVY, AMOCO, Score: 0.652335858586\n    Oil: BORHOLLA, Score: 0.219696969697\n    Oil: LIGHT LOUISIANNA SWEET, BP, Score: 0.583333333333\n    Oil: BENIN RIVER, CHEVRON, Score: 0.659090909091\n    Oil: EMPIRE ISLAND, AMOCO, Score: 0.654703282828\n    Oil: SAJAA CONDENSATE, BP, Score: 0.602272727273\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "dcaa003e2b0050178ad72b1380837efe039bac28", "size": 45852, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "documentation/notebooks/oil_data_quality_index_current.ipynb", "max_stars_repo_name": "gauteh/OilLibrary", "max_stars_repo_head_hexsha": "4e4f758863d5ff8351cb6eaeb138dadba1e6c267", "max_stars_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2016-12-15T14:54:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-08T09:05:08.000Z", "max_issues_repo_path": "documentation/notebooks/oil_data_quality_index_current.ipynb", "max_issues_repo_name": "gauteh/OilLibrary", "max_issues_repo_head_hexsha": "4e4f758863d5ff8351cb6eaeb138dadba1e6c267", "max_issues_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2016-11-15T20:58:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T22:30:55.000Z", "max_forks_repo_path": "documentation/notebooks/oil_data_quality_index_current.ipynb", "max_forks_repo_name": "gauteh/OilLibrary", "max_forks_repo_head_hexsha": "4e4f758863d5ff8351cb6eaeb138dadba1e6c267", "max_forks_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2016-12-18T08:22:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-02T12:57:15.000Z", "avg_line_length": 36.8881737731, "max_line_length": 692, "alphanum_fraction": 0.5840748495, "converted": true, "num_tokens": 9471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.09268777550652785, "lm_q1q2_score": 0.0434511603602978}}
{"text": "```python\n# This cell is mandatory in all Dymos documentation notebooks.\nmissing_packages = []\ntry:\n    import openmdao.api as om\nexcept ImportError:\n    if 'google.colab' in str(get_ipython()):\n        !python -m pip install openmdao[notebooks]\n    else:\n        missing_packages.append('openmdao')\ntry:\n    import dymos as dm\nexcept ImportError:\n    if 'google.colab' in str(get_ipython()):\n        !python -m pip install dymos\n    else:\n        missing_packages.append('dymos')\ntry:\n    import pyoptsparse\nexcept ImportError:\n    if 'google.colab' in str(get_ipython()):\n        !pip install -q condacolab\n        import condacolab\n        condacolab.install_miniconda()\n        !conda install -c conda-forge pyoptsparse\n    else:\n        missing_packages.append('pyoptsparse')\nif missing_packages:\n    raise EnvironmentError('This notebook requires the following packages '\n                           'please install them and restart this notebook\\'s runtime: {\",\".join(missing_packages)}')\n```\n\n# Multi-Phase Cannonball\n\nMaximizing the range of a cannonball in a vacuum is a typical\nintroductory problem for optimal control. In this example we are going\nto demonstrate a more multidisciplinary take on the problem. We will\nassume a density of the metal from which the cannonball is constructed,\nand a cannon that can fire any diameter cannonball but is limited to a\nmaximum muzzle energy. If we make the cannonball large it will be heavy\nand the cannon will not be capable of propelling it very far. If we make\nthe cannonball too small, it will have a low ballistic coefficient and\nnot be able to sustain its momentum in the presence of atmospheric drag.\nSomewhere between these two extremes is the cannonball radius which\nallows for maximum range flight.\n\nThe presence of atmospheric drag also means that we typically want to\nlaunch the cannonball with more horizontal velocity, and thus use a\nlaunch angle less than 45 degrees.\n\nThe goal of our optimization is to find the optimal design for the cannonball (its\nradius) and the optimal flight profile (its launch angle)\nsimultaneously.\n\n## Using two phases to capture an intermediate boundary constraint\n\nThis problem demonstrates the use of two phases to capture the state of\nthe system at an event in the trajectory. Here, we have the first phase\n(ascent) terminate when the flight path angle reaches zero (apogee). The\ndescent phase follows until the cannonball impacts the ground.\n\nThe dynamics are given by\n\n\\begin{align}\n  \\frac{dv}{dt} &= \\frac{D}{m} - g \\sin \\gamma \\\\\n  \\frac{d\\gamma}{dt} &= - \\frac{g \\cos \\gamma}{v} \\\\\n  \\frac{dh}{dt} &= v \\sin \\gamma \\\\\n  \\frac{dr}{dt} &= v \\cos \\gamma \\\\\n\\end{align}\n\nThe initial conditions are\n\n\\begin{align}\n  r_0 &= 0 \\rm{\\,m} \\\\\n  h_0 &= 100 \\rm{\\,m} \\\\\n  v_0 &= \\rm{free} \\\\\n  \\gamma_0 &= \\rm{free}\n\\end{align}\n\nand the final conditions are\n\n\\begin{align}\n  h_f &= 0 \\rm{\\,m}\n\\end{align}\n\n## Designing a cannonball for maximum range\n\nThis problem demonstrates a very simple vehicle design capability that\nis run before the trajectory.\n\nWe assume our cannon can shoot a cannonball with some fixed kinetic\nenergy and that our cannonball is made of solid iron. The volume (and\nmass) of the cannonball is proportional to its radius cubed, while the\ncross-sectional area is proportional to its radius squared. If we\nincrease the size of the cannonball, the ballistic coefficient\n\n\\begin{align}\n  BC &= \\frac{m}{C_D A}\n\\end{align}\n\nwill increase, meaning the cannonball overcome air resistance more\neasily and thus carry more distance.\n\nHowever, making the cannonball larger also increases its mass. Our\ncannon can impart the cannonball with, at most, 400 kJ of kinetic\nenergy. So making the cannonball larger will decrease the initial\nvelocity, and thus negatively impact its range.\n\nWe therefore have a design that affects the objective in competing ways.\nWe cannot make the cannonball too large, as it will be too heavy to\nshoot. We also cannot make the cannonball too small, as it will be more\nsusceptible to air resistance. Somewhere in between is the sweet spot\nthat provides the maximum range cannonball.\n\n## Building and running the problem\n\nThe following code defines the components for the physical\ncannonball calculations and ODE problem, sets up trajectory using two phases,\nand links them accordingly. The initial flight path angle is free, since\n45 degrees is not necessarily optimal once air resistance is taken into\naccount.\n\n\n```python\nimport numpy as np\nfrom scipy.interpolate import interp1d\nimport matplotlib.pyplot as plt\n\nimport openmdao.api as om\n\nimport dymos as dm\nfrom dymos.models.atmosphere.atmos_1976 import USatm1976Data\n\n#############################################\n# Component for the design part of the model\n#############################################\nclass CannonballSizeComp(om.ExplicitComponent):\n    \"\"\"\n    Compute the area and mass of a cannonball with a given radius and density.\n\n    Notes\n    -----\n    This component is not vectorized with 'num_nodes' as is the usual way\n    with Dymos, but is instead intended to compute a scalar mass and reference\n    area from scalar radius and density inputs. This component does not reside\n    in the ODE but instead its outputs are connected to the trajectory via\n    input design parameters.\n    \"\"\"\n    def setup(self):\n        self.add_input(name='radius', val=1.0, desc='cannonball radius', units='m')\n        self.add_input(name='dens', val=7870., desc='cannonball density', units='kg/m**3')\n\n        self.add_output(name='mass', shape=(1,), desc='cannonball mass', units='kg')\n        self.add_output(name='S', shape=(1,), desc='aerodynamic reference area', units='m**2')\n\n        self.declare_partials(of='mass', wrt='dens')\n        self.declare_partials(of='mass', wrt='radius')\n\n        self.declare_partials(of='S', wrt='radius')\n\n    def compute(self, inputs, outputs):\n        radius = inputs['radius']\n        dens = inputs['dens']\n\n        outputs['mass'] = (4/3.) * dens * np.pi * radius ** 3\n        outputs['S'] = np.pi * radius ** 2\n\n    def compute_partials(self, inputs, partials):\n        radius = inputs['radius']\n        dens = inputs['dens']\n\n        partials['mass', 'dens'] = (4/3.) * np.pi * radius ** 3\n        partials['mass', 'radius'] = 4. * dens * np.pi * radius ** 2\n\n        partials['S', 'radius'] = 2 * np.pi * radius\n\n#############################################\n# Build the ODE class\n#############################################\nclass CannonballODE(om.ExplicitComponent):\n    \"\"\"\n    Cannonball ODE assuming flat earth and accounting for air resistance\n    \"\"\"\n\n    def initialize(self):\n        self.options.declare('num_nodes', types=int)\n\n    def setup(self):\n        nn = self.options['num_nodes']\n\n        # static parameters\n        self.add_input('m', units='kg')\n        self.add_input('S', units='m**2')\n        # 0.5 good assumption for a sphere\n        self.add_input('CD', 0.5)\n\n        # time varying inputs\n        self.add_input('h', units='m', shape=nn)\n        self.add_input('v', units='m/s', shape=nn)\n        self.add_input('gam', units='rad', shape=nn)\n\n        # state rates\n        self.add_output('v_dot', shape=nn, units='m/s**2', tags=['dymos.state_rate_source:v'])\n        self.add_output('gam_dot', shape=nn, units='rad/s', tags=['dymos.state_rate_source:gam'])\n        self.add_output('h_dot', shape=nn, units='m/s', tags=['dymos.state_rate_source:h'])\n        self.add_output('r_dot', shape=nn, units='m/s', tags=['dymos.state_rate_source:r'])\n        self.add_output('ke', shape=nn, units='J')\n\n        # Ask OpenMDAO to compute the partial derivatives using complex-step\n        # with a partial coloring algorithm for improved performance, and use\n        # a graph coloring algorithm to automatically detect the sparsity pattern.\n        self.declare_coloring(wrt='*', method='cs')\n\n        alt_data = USatm1976Data.alt * om.unit_conversion('ft', 'm')[0]\n        rho_data = USatm1976Data.rho * om.unit_conversion('slug/ft**3', 'kg/m**3')[0]\n        self.rho_interp = interp1d(np.array(alt_data, dtype=complex),\n                                   np.array(rho_data, dtype=complex),\n                                   kind='linear')\n\n    def compute(self, inputs, outputs):\n\n        gam = inputs['gam']\n        v = inputs['v']\n        h = inputs['h']\n        m = inputs['m']\n        S = inputs['S']\n        CD = inputs['CD']\n\n        GRAVITY = 9.80665  # m/s**2\n\n        # handle complex-step gracefully from the interpolant\n        if np.iscomplexobj(h):\n            rho = self.rho_interp(inputs['h'])\n        else:\n            rho = self.rho_interp(inputs['h']).real\n\n        q = 0.5*rho*inputs['v']**2\n        qS = q * S\n        D = qS * CD\n        cgam = np.cos(gam)\n        sgam = np.sin(gam)\n        outputs['v_dot'] = - D/m-GRAVITY*sgam\n        outputs['gam_dot'] = -(GRAVITY/v)*cgam\n        outputs['h_dot'] = v*sgam\n        outputs['r_dot'] = v*cgam\n        outputs['ke'] = 0.5*m*v**2\n\n#############################################\n# Setup the Dymos problem\n#############################################\n\np = om.Problem(model=om.Group())\n\np.driver = om.pyOptSparseDriver()\np.driver.options['optimizer'] = 'SLSQP'\np.driver.declare_coloring()\n\np.model.add_subsystem('size_comp', CannonballSizeComp(),\n                      promotes_inputs=['radius', 'dens'])\np.model.set_input_defaults('dens', val=7.87, units='g/cm**3')\np.model.add_design_var('radius', lower=0.01, upper=0.10,\n                       ref0=0.01, ref=0.10, units='m')\n\ntraj = p.model.add_subsystem('traj', dm.Trajectory())\n\ntranscription = dm.Radau(num_segments=5, order=3, compressed=True)\nascent = dm.Phase(ode_class=CannonballODE, transcription=transcription)\n\nascent = traj.add_phase('ascent', ascent)\n\n# All initial states except flight path angle are fixed\n# Final flight path angle is fixed (we will set it to zero\n# so that the phase ends at apogee).\n# The output of the ODE which provides the rate source for each state\n# is obtained from the tags used on those outputs in the ODE.\n# The units of the states are automatically inferred by multiplying the units\n# of those rates by the time units.\nascent.set_time_options(fix_initial=True, duration_bounds=(1, 100),\n                        duration_ref=100, units='s')\nascent.set_state_options('r', fix_initial=True, fix_final=False)\nascent.set_state_options('h', fix_initial=True, fix_final=False)\nascent.set_state_options('gam', fix_initial=False, fix_final=True)\nascent.set_state_options('v', fix_initial=False, fix_final=False)\n\nascent.add_parameter('S', units='m**2', static_target=True)\nascent.add_parameter('m', units='kg', static_target=True)\n\n# Limit the muzzle energy\nascent.add_boundary_constraint('ke', loc='initial',\n                               upper=400000, lower=0, ref=100000)\n\n# Second Phase (descent)\ntranscription = dm.GaussLobatto(num_segments=5, order=3, compressed=True)\ndescent = dm.Phase(ode_class=CannonballODE, transcription=transcription)\n\ntraj.add_phase('descent', descent)\n\n# All initial states and time are free, since\n#    they will be linked to the final states of ascent.\n# Final altitude is fixed, because we will set\n#    it to zero so that the phase ends at ground impact)\ndescent.set_time_options(initial_bounds=(.5, 100), duration_bounds=(.5, 100),\n                         duration_ref=100, units='s')\ndescent.add_state('r')\ndescent.add_state('h', fix_initial=False, fix_final=True)\ndescent.add_state('gam', fix_initial=False, fix_final=False)\ndescent.add_state('v', fix_initial=False, fix_final=False)\n\ndescent.add_parameter('S', units='m**2', static_target=True)\ndescent.add_parameter('m', units='kg', static_target=True)\n\ndescent.add_objective('r', loc='final', scaler=-1.0)\n\n# Add internally-managed design parameters to the trajectory.\ntraj.add_parameter('CD',\n                   targets={'ascent': ['CD'], 'descent': ['CD']},\n                   val=0.5, units=None, opt=False, static_target=True)\n\n# Add externally-provided design parameters to the trajectory.\n# In this case, we connect 'm' to pre-existing input parameters\n# named 'mass' in each phase.\ntraj.add_parameter('m', units='kg', val=1.0,\n                   targets={'ascent': 'mass', 'descent': 'mass'}, static_target=True)\n\n# In this case, by omitting targets, we're connecting these\n# parameters to parameters with the same name in each phase.\ntraj.add_parameter('S', units='m**2', val=0.005, static_target=True)\n\n# Link Phases (link time and all state variables)\ntraj.link_phases(phases=['ascent', 'descent'], vars=['*'])\n\n# Issue Connections\np.model.connect('size_comp.mass', 'traj.parameters:m')\np.model.connect('size_comp.S', 'traj.parameters:S')\n\n# A linear solver at the top level can improve performance.\np.model.linear_solver = om.DirectSolver()\n\n# Finish Problem Setup\np.setup()\n\n#############################################\n# Set constants and initial guesses\n#############################################\np.set_val('radius', 0.05, units='m')\np.set_val('dens', 7.87, units='g/cm**3')\n\np.set_val('traj.parameters:CD', 0.5)\n\np.set_val('traj.ascent.t_initial', 0.0)\np.set_val('traj.ascent.t_duration', 10.0)\n\np.set_val('traj.ascent.states:r', ascent.interp('r', [0, 100]))\np.set_val('traj.ascent.states:h', ascent.interp('h', [0, 100]))\np.set_val('traj.ascent.states:v', ascent.interp('v', [200, 150]))\np.set_val('traj.ascent.states:gam', ascent.interp('gam', [25, 0]), units='deg')\n\np.set_val('traj.descent.t_initial', 10.0)\np.set_val('traj.descent.t_duration', 10.0)\n\np.set_val('traj.descent.states:r', descent.interp('r', [100, 200]))\np.set_val('traj.descent.states:h', descent.interp('h', [100, 0]))\np.set_val('traj.descent.states:v', descent.interp('v', [150, 200]))\np.set_val('traj.descent.states:gam', descent.interp('gam', [0, -45]), units='deg')\n\n#####################################################\n# Run the optimization and final explicit simulation\n#####################################################\ndm.run_problem(p)\n\n# use the explicit simulation to check the final collocation solution accuracy\nexp_out = traj.simulate()\n\n#############################################\n# Plot the results\n#############################################\nrad = p.get_val('radius', units='m')[0]\nprint(f'optimal radius: {rad} m ')\nmass = p.get_val('size_comp.mass', units='kg')[0]\nprint(f'cannonball mass: {mass} kg ')\nangle = p.get_val('traj.ascent.timeseries.states:gam', units='deg')[0, 0]\nprint(f'launch angle: {angle} deg')\nmax_range = p.get_val('traj.descent.timeseries.states:r')[-1, 0]\nprint(f'maximum range: {max_range} m')\n\nfig, axes = plt.subplots(nrows=1, ncols=1, figsize=(10, 6))\n\ntime_imp = {'ascent': p.get_val('traj.ascent.timeseries.time'),\n            'descent': p.get_val('traj.descent.timeseries.time')}\n\ntime_exp = {'ascent': exp_out.get_val('traj.ascent.timeseries.time'),\n            'descent': exp_out.get_val('traj.descent.timeseries.time')}\n\nr_imp = {'ascent': p.get_val('traj.ascent.timeseries.states:r'),\n         'descent': p.get_val('traj.descent.timeseries.states:r')}\n\nr_exp = {'ascent': exp_out.get_val('traj.ascent.timeseries.states:r'),\n         'descent': exp_out.get_val('traj.descent.timeseries.states:r')}\n\nh_imp = {'ascent': p.get_val('traj.ascent.timeseries.states:h'),\n         'descent': p.get_val('traj.descent.timeseries.states:h')}\n\nh_exp = {'ascent': exp_out.get_val('traj.ascent.timeseries.states:h'),\n         'descent': exp_out.get_val('traj.descent.timeseries.states:h')}\n\naxes.plot(r_imp['ascent'], h_imp['ascent'], 'bo')\n\naxes.plot(r_imp['descent'], h_imp['descent'], 'ro')\n\naxes.plot(r_exp['ascent'], h_exp['ascent'], 'b--')\n\naxes.plot(r_exp['descent'], h_exp['descent'], 'r--')\n\naxes.set_xlabel('range (m)')\naxes.set_ylabel('altitude (m)')\n\nfig, axes = plt.subplots(nrows=4, ncols=1, figsize=(10, 6))\nstates = ['r', 'h', 'v', 'gam']\nfor i, state in enumerate(states):\n    x_imp = {'ascent': p.get_val(f'traj.ascent.timeseries.states:{state}'),\n             'descent': p.get_val(f'traj.descent.timeseries.states:{state}')}\n\n    x_exp = {'ascent': exp_out.get_val(f'traj.ascent.timeseries.states:{state}'),\n             'descent': exp_out.get_val(f'traj.descent.timeseries.states:{state}')}\n\n    axes[i].set_ylabel(state)\n\n    axes[i].plot(time_imp['ascent'], x_imp['ascent'], 'bo')\n    axes[i].plot(time_imp['descent'], x_imp['descent'], 'ro')\n    axes[i].plot(time_exp['ascent'], x_exp['ascent'], 'b--')\n    axes[i].plot(time_exp['descent'], x_exp['descent'], 'r--')\n\nparams = ['m', 'S']\nfig, axes = plt.subplots(nrows=6, ncols=1, figsize=(12, 6))\nfor i, param in enumerate(params):\n    p_imp = {\n        'ascent': p.get_val(f'traj.ascent.timeseries.parameters:{param}'),\n        'descent': p.get_val(f'traj.descent.timeseries.parameters:{param}')}\n\n    p_exp = {'ascent': exp_out.get_val(f'traj.ascent.timeseries.parameters:{param}'),\n             'descent': exp_out.get_val(f'traj.descent.timeseries.parameters:{param}')}\n\n    axes[i].set_ylabel(param)\n\n    axes[i].plot(time_imp['ascent'], p_imp['ascent'], 'bo')\n    axes[i].plot(time_imp['descent'], p_imp['descent'], 'ro')\n    axes[i].plot(time_exp['ascent'], p_exp['ascent'], 'b--')\n    axes[i].plot(time_exp['descent'], p_exp['descent'], 'r--')\n\nplt.show()\n```\n\n\n```python\nfrom openmdao.utils.assert_utils import assert_near_equal\n\nassert_near_equal(p.get_val('traj.descent.states:r')[-1],\n                  3183.25, tolerance=1.0E-2)\n```\n", "meta": {"hexsha": "04daaf220fe73561854ce78bb3c6eac10ddb35dd", "size": 22672, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/dymos_book/examples/multi_phase_cannonball/multi_phase_cannonball.ipynb", "max_stars_repo_name": "yonghoonlee/dymos", "max_stars_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/dymos_book/examples/multi_phase_cannonball/multi_phase_cannonball.ipynb", "max_issues_repo_name": "yonghoonlee/dymos", "max_issues_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-05-24T15:14:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-28T21:12:55.000Z", "max_forks_repo_path": "docs/dymos_book/examples/multi_phase_cannonball/multi_phase_cannonball.ipynb", "max_forks_repo_name": "yonghoonlee/dymos", "max_forks_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9393939394, "max_line_length": 125, "alphanum_fraction": 0.552664079, "converted": true, "num_tokens": 4531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969238628498, "lm_q2_score": 0.1037486365654557, "lm_q1q2_score": 0.04343923498492108}}
{"text": "# Qiskit \uc0ac\uc6a9\ubc95 \uac15\uc758\n\n\uc548\ub155\ud558\uc138\uc694, \n\uc774 \ub178\ud2b8\ubd81\uc740 \uae30\ubcf8\uc801\uc778 Qiskit \uc0ac\uc6a9\ubc95\uc744 \uc775\ud788\uae30 \uc704\ud55c \ub178\ud2b8\ubd81\uc785\ub2c8\ub2e4. \uac04\ub2e8\ud55c \uc591\uc790\ud68c\ub85c\ub97c Qiskit \ub77c\uc774\ube0c\ub7ec\ub9ac\ub97c \uc774\uc6a9\ud574 \uad6c\uc131\ud558\uace0 \uc0ac\uc6a9\ud558\ub294 \ubc29\ubc95\uc744 \ubc30\uc6b0\uace0 \uc774\uc804\uc5d0 Johri \ubc15\uc0ac\ub2d8\uacfc \ud568\uaed8 \ub2e4\ub8e8\uc5c8\ub358 GHZ \uc0c1\ud0dc\ub97c \ub9cc\ub4dc\ub294 \uc591\uc790\ud68c\ub85c\ub97c \ub2e4\uc2dc \ud55c \ubc88 \ubcf5\uc2b5\ud560 \uac83\uc785\ub2c8\ub2e4.\n\n### Qiskit \uacfc Backend \uc124\uce58\n\nPython \ud658\uacbd\uc5d0 \uc775\uc219\ud558\uc9c0 \uc54a\uc740 \ubd84\ub4e4\uc740 \ub2e4\uc74c \uc140\uc744 \uc2e4\ud589\ud574\uc11c Qiskit\uacfc IonQ backend \ub77c\uc774\ube0c\ub7ec\ub9ac\ub97c \uc124\uce58\ud558\uc2e4 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\n\n```python\n## hit shift+enter to run this cell\n# IonQ backend installation\n!curl https://static.ionq.co/c501c899-8b6a-4aa3-8c51-1c4193943954/qiskit_ionq_provider-0.0.1.dev0%2Bd5a56c7-py3-none-any.whl -O -J\n!pip install qiskit_ionq_provider-0.0.1.dev0%2Bd5a56c7-py3-none-any.whl\n# Qiskit installation\n!pip install qiskit\n```\n\n      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current\n                                     Dload  Upload   Total   Spent    Left  Speed\n    \n      0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0\n      0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0\n    100 42174  100 42174    0     0  42174      0  0:00:01 --:--:--  0:00:01 56232\n\n\n    Processing d:\\skku\\ionq-skku quantum\\qiskit_ionq_provider-0.0.1.dev0%2bd5a56c7-py3-none-any.whl\n    Requirement already satisfied: requests>=2.24.0 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (2.25.1)\n    Requirement already satisfied: qiskit-terra>=0.16 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (0.16.4)\n    Requirement already satisfied: psutil>=5 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (5.8.0)\n    Requirement already satisfied: jsonschema>=2.6 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (3.2.0)\n    Requirement already satisfied: retworkx>=0.5.0 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (0.8.0)\n    Requirement already satisfied: ply>=3.10 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (3.11)\n    Requirement already satisfied: dill>=0.3 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (0.3.3)\n    Requirement already satisfied: scipy>=1.4 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (1.5.4)\n    Requirement already satisfied: sympy>=1.3 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (1.7.1)\n    Requirement already satisfied: contextvars>=2.4 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (2.4)\n    Requirement already satisfied: python-constraint>=1.4 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (1.4.0)\n    Requirement already satisfied: networkx>=2.2 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (2.5)\n    Requirement already satisfied: python-dateutil>=2.8.0 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (2.8.1)\n    Requirement already satisfied: numpy>=1.17 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (1.19.5)\n    Requirement already satisfied: fastjsonschema>=2.10 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (2.15.0)\n    Requirement already satisfied: immutables>=0.9 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from contextvars>=2.4->qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (0.15)\n    Requirement already satisfied: attrs>=17.4.0 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from jsonschema>=2.6->qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (20.3.0)\n    Requirement already satisfied: six>=1.11.0 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from jsonschema>=2.6->qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (1.15.0)\n    Requirement already satisfied: setuptools in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from jsonschema>=2.6->qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (50.0.0.post20200830)\n    Requirement already satisfied: importlib-metadata in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from jsonschema>=2.6->qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (3.7.3)\n    Requirement already satisfied: pyrsistent>=0.14.0 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from jsonschema>=2.6->qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (0.17.3)\n    Requirement already satisfied: decorator>=4.3.0 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from networkx>=2.2->qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (4.4.2)\n    Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from requests>=2.24.0->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (2020.12.5)\n    Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from requests>=2.24.0->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (1.26.4)\n    Requirement already satisfied: chardet<5,>=3.0.2 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from requests>=2.24.0->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (4.0.0)\n    Requirement already satisfied: idna<3,>=2.5 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from requests>=2.24.0->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (2.10)\n    Requirement already satisfied: mpmath>=0.19 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from sympy>=1.3->qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (1.2.1)\n    Requirement already satisfied: zipp>=0.5 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from importlib-metadata->jsonschema>=2.6->qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (3.4.1)\n    Requirement already satisfied: typing-extensions>=3.6.4 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from importlib-metadata->jsonschema>=2.6->qiskit-terra>=0.16->qiskit-ionq-provider==0.0.1.dev0+d5a56c7) (3.7.4.3)\n    qiskit-ionq-provider is already installed with the same version as the provided wheel. Use --force-reinstall to force an installation of the wheel.\n    Requirement already satisfied: qiskit in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (0.24.0)\n    Requirement already satisfied: qiskit-ignis==0.5.2 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit) (0.5.2)\n    Requirement already satisfied: qiskit-terra==0.16.4 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit) (0.16.4)\n    Requirement already satisfied: qiskit-aer==0.7.6 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit) (0.7.6)\n    Requirement already satisfied: qiskit-ibmq-provider==0.12.1 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit) (0.12.1)\n    Requirement already satisfied: qiskit-aqua==0.8.2 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit) (0.8.2)\n    Requirement already satisfied: pybind11>=2.4 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-aer==0.7.6->qiskit) (2.6.2)\n    Requirement already satisfied: cython>=0.27.1 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-aer==0.7.6->qiskit) (0.29.22)\n    Requirement already satisfied: numpy>=1.16.3 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-aer==0.7.6->qiskit) (1.19.5)\n    Requirement already satisfied: scipy>=1.0 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-aer==0.7.6->qiskit) (1.5.4)\n    Requirement already satisfied: scikit-learn>=0.20.0 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-aqua==0.8.2->qiskit) (0.24.1)\n    Requirement already satisfied: docplex==2.15.194 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-aqua==0.8.2->qiskit) (2.15.194)\n    Requirement already satisfied: sympy>=1.3 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-aqua==0.8.2->qiskit) (1.7.1)\n    Requirement already satisfied: psutil>=5 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-aqua==0.8.2->qiskit) (5.8.0)\n    Requirement already satisfied: dataclasses in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-aqua==0.8.2->qiskit) (0.8)\n    Requirement already satisfied: retworkx>=0.5.0 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-aqua==0.8.2->qiskit) (0.8.0)\n    Requirement already satisfied: yfinance in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-aqua==0.8.2->qiskit) (0.1.55)\n    Requirement already satisfied: h5py in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-aqua==0.8.2->qiskit) (3.1.0)\n    Requirement already satisfied: quandl in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-aqua==0.8.2->qiskit) (3.6.1)\n    Requirement already satisfied: setuptools>=40.1.0 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-aqua==0.8.2->qiskit) (50.0.0.post20200830)\n    Requirement already satisfied: pandas in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-aqua==0.8.2->qiskit) (1.1.5)\n    Requirement already satisfied: dlx in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-aqua==0.8.2->qiskit) (1.0.4)\n    Requirement already satisfied: fastdtw in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-aqua==0.8.2->qiskit) (0.3.4)\n    Requirement already satisfied: six in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from docplex==2.15.194->qiskit-aqua==0.8.2->qiskit) (1.15.0)\n    Requirement already satisfied: requests in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from docplex==2.15.194->qiskit-aqua==0.8.2->qiskit) (2.25.1)\n    Requirement already satisfied: websockets>=8 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-ibmq-provider==0.12.1->qiskit) (8.1)\n    Requirement already satisfied: requests-ntlm>=1.1.0 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-ibmq-provider==0.12.1->qiskit) (1.1.0)\n    Requirement already satisfied: nest-asyncio!=1.1.0,>=1.0.0 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-ibmq-provider==0.12.1->qiskit) (1.5.1)\n    Requirement already satisfied: urllib3>=1.21.1 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-ibmq-provider==0.12.1->qiskit) (1.26.4)\n    Requirement already satisfied: python-dateutil>=2.8.0 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-ibmq-provider==0.12.1->qiskit) (2.8.1)\n    Requirement already satisfied: networkx>=2.2 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-ignis==0.5.2->qiskit) (2.5)\n    Requirement already satisfied: python-constraint>=1.4 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-terra==0.16.4->qiskit) (1.4.0)\n    Requirement already satisfied: ply>=3.10 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-terra==0.16.4->qiskit) (3.11)\n    Requirement already satisfied: jsonschema>=2.6 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-terra==0.16.4->qiskit) (3.2.0)\n    Requirement already satisfied: contextvars>=2.4 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-terra==0.16.4->qiskit) (2.4)\n    Requirement already satisfied: dill>=0.3 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-terra==0.16.4->qiskit) (0.3.3)\n    Requirement already satisfied: fastjsonschema>=2.10 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from qiskit-terra==0.16.4->qiskit) (2.15.0)\n    Requirement already satisfied: immutables>=0.9 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from contextvars>=2.4->qiskit-terra==0.16.4->qiskit) (0.15)\n    Requirement already satisfied: attrs>=17.4.0 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from jsonschema>=2.6->qiskit-terra==0.16.4->qiskit) (20.3.0)\n    Requirement already satisfied: importlib-metadata in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from jsonschema>=2.6->qiskit-terra==0.16.4->qiskit) (3.7.3)\n    Requirement already satisfied: pyrsistent>=0.14.0 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from jsonschema>=2.6->qiskit-terra==0.16.4->qiskit) (0.17.3)\n    Requirement already satisfied: decorator>=4.3.0 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from networkx>=2.2->qiskit-ignis==0.5.2->qiskit) (4.4.2)\n    Requirement already satisfied: chardet<5,>=3.0.2 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from requests->docplex==2.15.194->qiskit-aqua==0.8.2->qiskit) (4.0.0)\n    Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from requests->docplex==2.15.194->qiskit-aqua==0.8.2->qiskit) (2020.12.5)\n    Requirement already satisfied: idna<3,>=2.5 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from requests->docplex==2.15.194->qiskit-aqua==0.8.2->qiskit) (2.10)\n    Requirement already satisfied: cryptography>=1.3 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.12.1->qiskit) (3.4.6)\n    Requirement already satisfied: ntlm-auth>=1.0.2 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.12.1->qiskit) (1.5.0)\n    Requirement already satisfied: cffi>=1.12 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.12.1->qiskit) (1.14.5)\n    Requirement already satisfied: pycparser in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.12.1->qiskit) (2.20)\n    Requirement already satisfied: joblib>=0.11 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.8.2->qiskit) (1.0.1)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.8.2->qiskit) (2.1.0)\n    Requirement already satisfied: mpmath>=0.19 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from sympy>=1.3->qiskit-aqua==0.8.2->qiskit) (1.2.1)\n    Requirement already satisfied: cached-property in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from h5py->qiskit-aqua==0.8.2->qiskit) (1.5.2)\n    Requirement already satisfied: zipp>=0.5 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from importlib-metadata->jsonschema>=2.6->qiskit-terra==0.16.4->qiskit) (3.4.1)\n    Requirement already satisfied: typing-extensions>=3.6.4 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from importlib-metadata->jsonschema>=2.6->qiskit-terra==0.16.4->qiskit) (3.7.4.3)\n    Requirement already satisfied: pytz>=2017.2 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from pandas->qiskit-aqua==0.8.2->qiskit) (2021.1)\n    Requirement already satisfied: inflection>=0.3.1 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from quandl->qiskit-aqua==0.8.2->qiskit) (0.5.1)\n    Requirement already satisfied: more-itertools in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from quandl->qiskit-aqua==0.8.2->qiskit) (8.7.0)\n    Requirement already satisfied: lxml>=4.5.1 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from yfinance->qiskit-aqua==0.8.2->qiskit) (4.6.3)\n    Requirement already satisfied: multitasking>=0.0.7 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from yfinance->qiskit-aqua==0.8.2->qiskit) (0.0.9)\n    Collecting matplotlib\n      Downloading matplotlib-3.3.4-cp36-cp36m-win_amd64.whl (8.5 MB)\n    Collecting cycler>=0.10\n      Using cached cycler-0.10.0-py2.py3-none-any.whl (6.5 kB)\n    Collecting pillow>=6.2.0\n      Downloading Pillow-8.1.2-cp36-cp36m-win_amd64.whl (2.1 MB)\n    Requirement already satisfied: python-dateutil>=2.1 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from matplotlib) (2.8.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from matplotlib) (2.4.7)\n    Collecting kiwisolver>=1.0.1\n      Downloading kiwisolver-1.3.1-cp36-cp36m-win_amd64.whl (51 kB)\n    Requirement already satisfied: numpy>=1.15 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from matplotlib) (1.19.5)\n    Requirement already satisfied: six in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from cycler>=0.10->matplotlib) (1.15.0)\n    Installing collected packages: pillow, kiwisolver, cycler, matplotlib\n    Successfully installed cycler-0.10.0 kiwisolver-1.3.1 matplotlib-3.3.4 pillow-8.1.2\n\n\n\n```python\n# Matplotlib, pylatexenc installation - for QuantumCircuit Visualization\n!pip install matplotlib\n!pip install pylatexenc\n# for qsphere visualization\n!pip install seaborn\n```\n\n    Requirement already satisfied: matplotlib in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (3.3.4)\n    Requirement already satisfied: python-dateutil>=2.1 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from matplotlib) (2.8.1)\n    Requirement already satisfied: cycler>=0.10 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from matplotlib) (0.10.0)\n    Requirement already satisfied: pillow>=6.2.0 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from matplotlib) (8.1.2)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from matplotlib) (2.4.7)\n    Requirement already satisfied: numpy>=1.15 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from matplotlib) (1.19.5)\n    Requirement already satisfied: kiwisolver>=1.0.1 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from matplotlib) (1.3.1)\n    Requirement already satisfied: six in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from cycler>=0.10->matplotlib) (1.15.0)\n    Requirement already satisfied: pylatexenc in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (2.9)\n    Collecting seaborn\n      Downloading seaborn-0.11.1-py3-none-any.whl (285 kB)\n    Requirement already satisfied: pandas>=0.23 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from seaborn) (1.1.5)\n    Requirement already satisfied: matplotlib>=2.2 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from seaborn) (3.3.4)\n    Requirement already satisfied: numpy>=1.15 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from seaborn) (1.19.5)\n    Requirement already satisfied: scipy>=1.0 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from seaborn) (1.5.4)\n    Requirement already satisfied: cycler>=0.10 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from matplotlib>=2.2->seaborn) (0.10.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from matplotlib>=2.2->seaborn) (2.4.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from matplotlib>=2.2->seaborn) (1.3.1)\n    Requirement already satisfied: pillow>=6.2.0 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from matplotlib>=2.2->seaborn) (8.1.2)\n    Requirement already satisfied: python-dateutil>=2.1 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from matplotlib>=2.2->seaborn) (2.8.1)\n    Requirement already satisfied: six in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from cycler>=0.10->matplotlib>=2.2->seaborn) (1.15.0)\n    Requirement already satisfied: pytz>=2017.2 in c:\\users\\ckdor\\anaconda3\\envs\\qiskit_ionq\\lib\\site-packages (from pandas>=0.23->seaborn) (2021.1)\n    Installing collected packages: seaborn\n    Successfully installed seaborn-0.11.1\n\n\n\n```python\ntoken_ionq = '94fROwsIfZ2W5r6e3JbECmeiridtFWIG'\n```\n\n## \uc591\uc790\ud68c\ub85c QuantumCircuit\n\n\n```python\nimport qiskit\n```\n\n\n```python\nqiskit.__qiskit_version__\n```\n\n\n\n\n    {'qiskit-terra': '0.16.4',\n     'qiskit-aer': '0.7.6',\n     'qiskit-ignis': '0.5.2',\n     'qiskit-ibmq-provider': '0.12.1',\n     'qiskit-aqua': '0.8.2',\n     'qiskit': '0.24.0'}\n\n\n\nQiskit\uc5d0\uc11c \uc591\uc790\ud68c\ub85c\ub294 `QuantumCircuit` \ud074\ub798\uc2a4\ub85c \ud45c\ud604\ub429\ub2c8\ub2e4. \ud68c\ub85c \ucd08\uae30\ud654, \uc591\uc790 \uac8c\uc774\ud2b8 \ucd94\uac00 \ubc0f \uce21\uc815\uc744 \ub2e4\ub904\ubcf4\uaca0\uc2b5\ub2c8\ub2e4.\n\n\n```python\n# QuantumCircuit\uc744 import\ud569\ub2c8\ub2e4.\nfrom qiskit import QuantumCircuit\n# Quantum Circuit\uc744 \uc791\uc131\nqc = QuantumCircuit(3)  # 3 qubit \uc591\uc790\ud68c\ub85c\ub97c \ub9cc\ub4ed\ub2c8\ub2e4.\n\n# \uc8fc\uc5b4\uc9c4 \uc591\uc790\ud68c\ub85c\ub97c \uadf8\ub824\ubd05\ub2c8\ub2e4.\nqc.draw()\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">     \nq_0: \n\nq_1: \n\nq_2: \n     </pre>\n\n\n\n\n```python\n# \uc591\uc790 \uac8c\uc774\ud2b8\ub4e4\uc744 \ucd94\uac00\ud574\ubcf4\uaca0\uc2b5\ub2c8\ub2e4.\nqc.h(0)         # 0\ubc88 \ud050\ube44\ud2b8\uc5d0 hadamard \uac8c\uc774\ud2b8\ub97c \uac00\ud569\ub2c8\ub2e4.\nqc.cx(0,1)      # CNOT \uac8c\uc774\ud2b8\ub97c \uac00\ud569\ub2c8\ub2e4. Control \ud050\ube44\ud2b8 0\ubc88 , Target \ud050\ube44\ud2b8 1\ubc88\nqc.cx(0,2)      # CNOT \uac8c\uc774\ud2b8\ub97c \uac00\ud569\ub2c8\ub2e4. Control \ud050\ube44\ud2b8 0\ubc88 , Target \ud050\ube44\ud2b8 2\ubc88\n\nqc.draw()\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">     \u250c\u2500\u2500\u2500\u2510          \nq_0: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\n     \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2534\u2500\u2510  \u2502  \nq_1: \u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\u2500\u2500\u253c\u2500\u2500\n          \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2534\u2500\u2510\nq_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\n               \u2514\u2500\u2500\u2500\u2518</pre>\n\n\n\n\n```python\n# \uce21\uc815\uc740 \ub2e4\uc74c\uacfc \uac19\uc774 \ud569\ub2c8\ub2e4.\nqc.measure_all()\n\nqc.draw()\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">        \u250c\u2500\u2500\u2500\u2510           \u2591 \u250c\u2500\u2510      \n   q_0: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2591\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u2500\u2500\n        \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2534\u2500\u2510  \u2502   \u2591 \u2514\u2565\u2518\u250c\u2500\u2510   \n   q_1: \u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\u2500\u2500\u253c\u2500\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u2500\u2500\n             \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2534\u2500\u2510 \u2591  \u2551 \u2514\u2565\u2518\u250c\u2500\u2510\n   q_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2524M\u251c\n                  \u2514\u2500\u2500\u2500\u2518 \u2591  \u2551  \u2551 \u2514\u2565\u2518\nmeas: 3/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\n                           0  1  2 </pre>\n\n\n\n\n```python\n# matplotlib\uc744 \uc774\uc6a9\ud558\uba74 \uc880 \ub354 \uc774\uc05c QuantumCircuit\uc744 \uadf8\ub9b4\uc218 \uc788\uc2b5\ub2c8\ub2e4.\nqc.draw('mpl') \n```\n\n### \uc54c\uc544\ub450\uba74 \uc88b\uc740 \uac83\ub4e4\n\n\n```python\n# \ucc98\uc74c Quantum Circuit\uc744 \ub9cc\ub4e4\ub54c Classical registre\ub97c \ud560\ub2f9\ud558\uba74 \uc9c1\uc811 \uc5b4\ub5a4 \ud050\ube57\uc758 \uc815\ubcf4\uac00 \uc5b4\ub5a4 \ub808\uc9c0\uc2a4\ud130\uc5d0 \uc800\uc7a5\ub420\uc9c0 \ud560\ub2f9\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\nqc = QuantumCircuit(3, 3)  # 3 qubit + 3 classcal register \uc591\uc790\ud68c\ub85c\ub97c \ub9cc\ub4ed\ub2c8\ub2e4.\n\n# \uc591\uc790 \uac8c\uc774\ud2b8\ub4e4\uc744 \ucd94\uac00\ud574\ubcf4\uaca0\uc2b5\ub2c8\ub2e4.\nqc.h(0)         # 0\ubc88 \ud050\ube44\ud2b8\uc5d0 hadamard \uac8c\uc774\ud2b8\ub97c \uac00\ud569\ub2c8\ub2e4.\nqc.cx(0,1)      # CNOT \uac8c\uc774\ud2b8\ub97c \uac00\ud569\ub2c8\ub2e4. Control \ud050\ube44\ud2b8 0\ubc88 , Target \ud050\ube44\ud2b8 1\ubc88\nqc.cx(0,2)      # CNOT \uac8c\uc774\ud2b8\ub97c \uac00\ud569\ub2c8\ub2e4. Control \ud050\ube44\ud2b8 0\ubc88 , Target \ud050\ube44\ud2b8 2\ubc88\n\nqc.measure((0,1,2), (0,1,2)) # i\ubc88 \ud050\ube44\ud2b8\uc758 \uc815\ubcf4\ub97c i\ubc88\uc9f8 \ub808\uc9c0\uc2a4\ud130\uc5d0 \uce21\uc815\ud558\uc5ec \uc800\uc7a5\ud569\ub2c8\ub2e4.\n\nqc.draw('mpl')\n```\n\n\n```python\n# QuantumCircuit\uc740 \uc11c\ub85c \ub354\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\nqc1 = QuantumCircuit(3)\nqc1.h(0)\nqc1.barrier()\n\nqc2 = QuantumCircuit(3)\nqc2.cx(0,1)\nqc2.cy(0,2)\n\nqc = qc1 + qc2\nqc.draw('mpl')\n```\n\n\n```python\n# \uc591\uc790\uac8c\uc774\ud2b8\uc758 \uac1c\uc218\ub294 \ub2e4\uc74c \ud568\uc218\ub85c \ubd88\ub7ec\uc62c\uc218 \uc788\uc2b5\ub2c8\ub2e4.\nqc.size()\n```\n\n\n\n\n    3\n\n\n\n\n```python\n# \ud050\ube44\ud2b8\ub97c \uac1c\ubcc4\uc801\uc73c\ub85c \ucd08\uae30\ud654\ud560 \uc218\ub3c4 \uc788\uc2b5\ub2c8\ub2e4.\nqc.reset(0)\nqc.draw('mpl')\n```\n\n\n```python\n# \uc784\uc758\uc758 \ud050\ube44\ud2b8 \ubc31\ud130 \uc0c1\ud0dc\ub85c \ucd08\uae30\ud654\ud558\uace0 \uc2f6\uc744 \ub54c\ub294 `initialize` \ud568\uc218\ub97c \uc774\uc6a9\ud569\ub2c8\ub2e4.\nimport numpy as np\nqc = QuantumCircuit(3)\nqc.initialize([1,0,0,0,0,0,0,1]/np.sqrt(2), [0,1,2])\nqc.draw('mpl')\n```\n\n## Backend \uc640 Job\n\n\uc791\uc131\ud55c \uc591\uc790\ud68c\ub85c\ub294 Backend\ub97c \uc774\uc6a9\ud574\uc11c \uad6c\ub3d9\ud569\ub2c8\ub2e4. Backend\ub294 \uc591\uc790\ud68c\ub85c\ub97c \uad6c\ub3d9\ud560 \uc218 \uc788\ub294 \ud558\ub4dc\uc6e8\uc5b4\ub098 \uc2dc\ubbac\ub808\uc774\ud130 \uc18c\ud504\ud2b8\uc6e8\uc5b4\ub97c \ub9d0\ud569\ub2c8\ub2e4. \uc8fc\uc5b4\uc9c4 \uc591\uc790\ud68c\ub85c\ub97c \uc218\ud589\ud558\uace0 \uacb0\uacfc\uac12\uc744 \ucd9c\ub825\ud574\uc90d\ub2c8\ub2e4. IonQ \ud558\ub4dc\uc6e8\uc5b4\ub97c \uc0ac\uc6a9\ud558\ub824\uba74 IonQ \ubc31\uc5d4\ub4dc\ub97c \uc0ac\uc6a9\ud558\uace0, \uadf8 \uc678\uc5d0 \ud558\ub4dc\uc6e8\uc5b4\ub098 \uc2dc\ubbac\ub808\uc774\ud130\ub97c \uc0ac\uc6a9\ud558\ub824\uba74 \ud574\ub2f9\ud558\ub294 \ubc31\uc5d4\ub4dc\ub97c \ubd88\ub7ec\uc640\uc11c \uc0ac\uc6a9\ud558\uba74 \ub429\ub2c8\ub2e4.\n\nQiskit\uc740 \uae30\ubcf8\uc801\uc73c\ub85c \uc5ec\ub7ec\uac00\uc9c0\uc758 \uc591\uc790\ud68c\ub85c \uc2dc\ubbac\ub808\uc774\ud130\ub97c Backend\ub85c \uc81c\uacf5\ud569\ub2c8\ub2e4. Qiskit \ub77c\uc774\ube0c\ub7ec\ub9ac\uc758 \uc5ec\ub7ec \uc2dc\ubbac\ub808\uc774\ud130\ub97c \uba3c\uc800 \uc54c\uc544\ubcf4\uace0 IonQ\uc758 Backend\ub97c \ud65c\uc6a9\ud558\ub294 \ubc95\uc744 \ubc30\uc6cc\ubcf4\uaca0\uc2b5\ub2c8\ub2e4.\n\n\n```python\n# qiskit.Aer \ub77c\uc774\ube0c\ub7ec\ub9ac\ub97c \ubd88\ub7ec\uc635\ub2c8\ub2e4.\nfrom qiskit import Aer\n\nAer.backends()\n```\n\n\n\n\n    [QasmSimulator(\n     backend_name='qasm_simulator', provider=AerProvider()),\n     StatevectorSimulator(\n     backend_name='statevector_simulator', provider=AerProvider()),\n     UnitarySimulator(\n     backend_name='unitary_simulator', provider=AerProvider()),\n     PulseSimulator(\n     backend_name='pulse_simulator', provider=AerProvider())]\n\n\n\n`qiskit.Aer`\uc5d0\uc11c \uae30\ubcf8\uc801\uc73c\ub85c \uc81c\uacf5\ud558\ub294 \uc2dc\ubbac\ub808\uc774\ud130\ub294 \ucd1d 4\uac00\uc9c0\uac00 \uc788\uc2b5\ub2c8\ub2e4. \uae30\ubcf8\uc801\uc73c\ub85c \uc0ac\uc6a9\uc790\uc758 \ucef4\ud4e8\ud130\uc5d0\uc11c \ub85c\uceec\ud558\uac8c \uacc4\uc0b0\uc744 \ud558\uae30 \ub54c\ubb38\uc5d0 \uac04\ub2e8\ud55c \uc5f0\uc0b0\ud655\uc778\uc5d0 \uc720\uc6a9\ud569\ub2c8\ub2e4.\n\n* `QasmSimulator`\ub294 \uc2e4\uc81c \ud558\ub4dc\uc6e8\uc5b4\uc758 \uc791\ub3d9\uc744 \ubaa8\uc0ac\ud569\ub2c8\ub2e4. \uce21\uc815\uc744 \ud3ec\ud568\ud55c \uc591\uc790\ud68c\ub85c\uc758 \uc5f0\uc0b0\uc744 \uc5ec\ub7ec\ubc88 \uc218\ud589\ud55c\ub4a4 \uce21\uc815\uac12\uc758 \ud1b5\uacc4\ubd84\ud3ec\ub97c \uacb0\uacfc\uac12\uc73c\ub85c \ucd9c\ub825\ud569\ub2c8\ub2e4.\n* `StatevectorSimulator`\ub294 \uc591\uc790\uc0c1\ud0dc\ub97c \ubca1\ud130\ud615\ud0dc\ub85c \uae30\uc220\ud558\uc5ec \uc591\uc790\ud68c\ub85c\ub97c \uacc4\uc0b0\ud569\ub2c8\ub2e4.\n* `UnitarySimulator`\ub294 \uc720\ub2c8\ud130\ub9ac \uc5f0\uc0b0\uc790 \ud615\ud0dc\ub85c \uc804\uccb4 \uc591\uc790\ud68c\ub85c\ub97c \uacc4\uc0b0\ud569\ub2c8\ub2e4. \uce21\uc815/\ud050\ube44\ud2b8 \ub9ac\uc14b\uc740 \uc0ac\uc6a9\ud560 \uc218 \uc5c6\uc2b5\ub2c8\ub2e4.\n* `PulseSimulator`\ub294 qiskit.pulse\ub97c \uc704\ud574 \uc0ac\uc6a9\ub429\ub2c8\ub2e4. \uc624\ub298 \uac15\uc758\uc5d0\uc11c\ub294 \ub2e4\ub8e8\uc9c0 \uc54a\uc2b5\ub2c8\ub2e4.\n\n\ubb34\uc5c7\uc744 \uace8\ub77c\uc57c \ud560\uc9c0 \uc798 \ubaa8\ub974\uaca0\uc73c\uba74 `QasmSimulator`\ub97c \uc774\uc6a9\ud558\uba74 \ub420 \uac83 \uac19\uc2b5\ub2c8\ub2e4. \uc624\ub298\uc740 `QasmSimulator`\ub9cc \uc9e7\uac8c \ub2e4\ub8e8\uace0 \ub118\uc5b4\uac00\uaca0\uc2b5\ub2c8\ub2e4.\n\n\n```python\n# GHZ \uc0c1\ud0dc\ub97c \ub9cc\ub4dc\ub294 \uc591\uc790\ud68c\ub85c\ub97c \ubc18\ud658\ud558\ub294 \ud568\uc218\ub97c \ubbf8\ub9ac \uc815\uc758\ud558\uaca0\uc2b5\ub2c8\ub2e4.\ndef ghz_circuit(n: int):\n    assert isinstance(n, int) and n > 0\n    qc = QuantumCircuit(n)\n    qc.h(0)\n    if n>1: \n        qc.cx(0, range(1,n))\n    qc.measure_all()\n    return qc\n```\n\n\ubc31\uc5d4\ub4dc\uc5d0\uc11c \uc591\uc790\ud68c\ub85c\ub97c \uc218\ud589\ud558\uae30 \uc704\ud574\uc11c\ub294 \ub450 \uac00\uc9c0 \ubc29\ubc95\uc774 \uc788\uc2b5\ub2c8\ub2e4. `execute`\ub97c \uc0ac\uc6a9\ud558\uac70\ub098 \uc9c1\uc811 `backend.run` \ud568\uc218\ub97c \uc0ac\uc6a9\ud558\ub294 \ubc29\ubc95\uc785\ub2c8\ub2e4.\n\n`execute` \ud568\uc218\ub294 \ubc31\uc5d4\ub4dc\uc758 \uc124\uc815\uc5d0 \ub9de\ucdb0\uc11c transpile\uc744 \uc790\ub3d9\uc801\uc73c\ub85c \uc218\ud589\ud569\ub2c8\ub2e4. `QuantumCircuit` \ud074\ub798\uc2a4\ub85c \uc591\uc790 \ud68c\ub85c\ub97c \ub9cc\ub4e4\uc5b4\uc11c \uc2e4\ud589\ud558\uba74 \ubc31\uc5d4\ub4dc\uc5d0 \ub9de\ucd94\uc5b4\uc11c \ud2b8\ub79c\uc2a4\ud30c\uc77c\uc744 \ud55c \ub4a4 \uc2e4\ud589\ud574\uc90d\ub2c8\ub2e4.\n\n\n```python\n# \ud68c\ub85c\ub97c \uc2e4\ud589\ud558\uae30 \uc704\ud55c `execute`\ud568\uc218\ub97c \ubd88\ub7ec\uc635\ub2c8\ub2e4.\nfrom qiskit import execute\n\n# Qubit 3\uac1c\uc9dc\ub9ac GHZ \uc0c1\ud0dc\ub97c \ub9cc\ub4dc\ub294 \uc591\uc790\ud68c\ub85c\ub97c \ub9cc\ub4ed\ub2c8\ub2e4.\nqc = ghz_circuit(3)\n\n# QasmSimulator \ubc31\uc5d4\ub4dc\ub97c \ubd88\ub7ec\uc635\ub2c8\ub2e4.\nbackend = Aer.get_backend('qasm_simulator')\n\n# \uc591\uc790\ud68c\ub85c\ub294 \ub2e4\uc74c\uacfc \uac19\uc774 \uc218\ud589\ud569\ub2c8\ub2e4. `execute` \ud568\uc218\ub294 Job \uc624\ube0c\uc81d\ud2b8\ub97c \ubc18\ud658\ud569\ub2c8\ub2e4.\njob = execute(qc, backend)\n```\n\n\ubc31\uc5d4\ub4dc\ub294 `Job` \uc624\ube0c\uc81d\ud2b8\ub97c \ubc18\ud658\ud558\uc5ec \uc5f0\uc0b0\uc758 \uc218\ud589\uc0c1\ud0dc\uc640 \uacb0\uacfc\ub97c \ud655\uc778\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4. \ubc18\ud658\ub418\ub294 `job` \uc624\ube0c\uc81d\ud2b8\ub97c \uaf2d \uc800\uc7a5\ud574\ub450\ub294 \uac83\uc774 \uc88b\uc2b5\ub2c8\ub2e4.\n\n\n```python\n# \uc5f0\uc0b0\uc758 \uc9c4\ud589\uc0c1\ud0dc\ub294 \ub2e4\uc74c \ud568\uc218\ub85c \ud655\uc778\uac00\ub2a5\ud569\ub2c8\ub2e4.\njob.status()\n```\n\n\n\n\n    <JobStatus.DONE: 'job has successfully run'>\n\n\n\n\n```python\n# \uc5f0\uc0b0 \uacb0\uacfc\ub294 `result` \ud568\uc218\ub85c \ud655\uc778\uac00\ub2a5\ud569\ub2c8\ub2e4.\nresult = job.result()\n\n# \uce21\uc815 \uacb0\uacfc\ub97c \ud788\uc2a4\ud1a0\uadf8\ub7a8\uc73c\ub85c \uadf8\ub824\ubcf4\uaca0\uc2b5\ub2c8\ub2e4.\nfrom qiskit.visualization import plot_histogram\nplot_histogram(result.get_counts())\n```\n\n\n```python\n# excute \ud568\uc218\ub294 \uc5ec\ub7ec run_config \ubcc0\uc218\ub4e4\uc744 \ubc1b\uc2b5\ub2c8\ub2e4. \uc774 \ubcc0\uc218\ub4e4\uc744 \ud65c\uc6a9\ud574\uc11c \uc5f0\uc0b0\uc124\uc815\uc744 \ubcc0\uacbd\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\n# \uce21\uc815\uc744 10\ub9cc\ubc88\uc744 \uc218\ud589\ud558\uace0, statevector simulation \ubc29\ubc95\uc744 \uc0ac\uc6a9\ud558\uace0, single (16bit) \uc815\ud655\ub3c4\ub85c \uc5f0\uc0b0\uc744 \uc218\ud589\ud558\ub294 \uc635\uc158\uc785\ub2c8\ub2e4.\njob = execute(qc, backend, shots = 10e5, method = 'statevector', precision = 'single') \n\nplot_histogram(job.result().get_counts())\n```\n\n`job` \uc624\ube0c\uc81d\ud2b8\ub294 \uc9c4\ud589\uc0c1\ud0dc\ub97c \ud655\uc778\ud558\uae30 \uc704\ud55c \ub2e4\uc591\ud55c \ud568\uc218\ub97c \uc81c\uacf5\ud569\ub2c8\ub2e4.\n\n\n```python\n# job id\ub294 \ub2e4\uc74c\uacfc \uac19\uc774 \ud655\uc778\ud569\ub2c8\ub2e4.\njob.job_id()\n\n# job \uc0c1\ud0dc\ub294 \ub2e4\uc74c \ud568\uc218\ub85c \ud655\uc778\ud569\ub2c8\ub2e4.\nprint(job.status())\n\n# job \uc0c1\ud0dc\ub97c \ud655\uc778\ud560\ub54c \uc720\uc6a9\ud55c \ud568\uc218\ub4e4\uc785\ub2c8\ub2e4.\nprint('job.done: ', job.done())\nprint('job.running: ', job.running())\nprint('job.in_final_state: ', job.in_final_state())\n```\n\n    JobStatus.CANCELLED\n    job.done:  False\n    job.running:  False\n    job.in_final_state:  True\n\n\n\n```python\n# Job\uc774 \ub108\ubb34 \uc624\ub798 \uac78\ub9ac\uac70\ub098 \ud68c\ub85c\uc5d0 \ubc84\uadf8\uac00 \uc788\uc744\ub54c\ub294 \ub2e4\uc74c\uacfc \uac19\uc774 \ucde8\uc18c\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\njob = execute(qc, backend, shots = 10e5)\njob.cancel()\njob.status()\n```\n\n\n\n\n    <JobStatus.CANCELLED: 'job has been cancelled'>\n\n\n\n`Result` \uc624\ube0c\uc81d\ud2b8\ub294 \uc5f0\uc0b0 \uacb0\uacfc\uc5d0 \ub300\ud55c \uc815\ubcf4\ub97c \ub2f4\uace0 \uc788\uc2b5\ub2c8\ub2e4. `QasmSimulator`\uc758 \uacbd\uc6b0 \uce21\uc815 \uce74\uc6b4\ud2b8\uc5d0 \ub300\ud55c \uc815\ubcf4\ub9cc \ub2f4\uace0 \uc788\uc9c0\ub9cc \ubc31\uc5d4\ub4dc \uc2dc\ubbac\ub808\uc774\ud130\uc758 \uc885\ub958\uc5d0 \ub530\ub77c \ubcf4\ub2e4 \uc790\uc138\ud55c \uc815\ubcf4\ub97c \ud3ec\ud568\ud558\uace0 \uc788\uc744\ub54c\ub3c4 \uc788\uc2b5\ub2c8\ub2e4.\n\n\n```python\n# Bell \uc0c1\ud0dc\ub97c \ub9cc\ub4dc\ub294 \uc591\uc790\ud68c\ub85c\ub97c \uc0dd\uac01\ud574\ubd05\uc2dc\ub2e4. (\uce21\uc815 X)\nqc = QuantumCircuit(2)\nqc.h(0)\nqc.cx(0,1)\nqc.draw()\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">     \u250c\u2500\u2500\u2500\u2510     \nq_0: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\n     \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2534\u2500\u2510\nq_1: \u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\n          \u2514\u2500\u2500\u2500\u2518</pre>\n\n\n\n\n```python\n# vector\uc758 density matrix\ub97c \ud655\uc778\ud558\uace0 \uc2f6\uc744 \ub54c \uc0ac\uc6a9\ud558\ub294 visualization \ud234\uc785\ub2c8\ub2e4.\nfrom qiskit.visualization import plot_state_city\n\n# statevector simulator\ub97c \uc0ac\uc6a9\ud558\uba74 `get_statevector` \ud568\uc218\ub97c \uc774\uc6a9\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\nbackend = Aer.get_backend('statevector_simulator')\n\njob = execute(qc, backend)\n\nresult = job.result()\n\nvector = result.get_statevector()\nplot_state_city(vector)\n```\n\n\n```python\n# unitary simulator\ub97c \uc774\uc6a9\ud558\uba74 `get_unitary` \ud568\uc218\ub97c \uc0ac\uc6a9\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\nbackend = Aer.get_backend('unitary_simulator')\n\njob = execute(qc, backend)\n\nresult = job.result()\n\nunitary = result.get_unitary()\nprint(unitary)\n```\n\n    [[ 0.70710678+0.00000000e+00j  0.70710678-8.65956056e-17j\n       0.        +0.00000000e+00j  0.        +0.00000000e+00j]\n     [ 0.        +0.00000000e+00j  0.        +0.00000000e+00j\n       0.70710678+0.00000000e+00j -0.70710678+8.65956056e-17j]\n     [ 0.        +0.00000000e+00j  0.        +0.00000000e+00j\n       0.70710678+0.00000000e+00j  0.70710678-8.65956056e-17j]\n     [ 0.70710678+0.00000000e+00j -0.70710678+8.65956056e-17j\n       0.        +0.00000000e+00j  0.        +0.00000000e+00j]]\n\n\n\n```python\nplot_state_city(unitary)\n```\n\n\uc9c1\uc811 \uc2a4\ucf00\uc974\uc744 \ub9cc\ub4e4\uc5b4\uc11c \uc2e4\ud589\uc744 \ud558\uace0 \uc2f6\uc744 \uacbd\uc6b0 `backend.run()` \ud568\uc218\ub97c \uc774\uc6a9\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4. \ubc31\uc5d4\ub4dc\uac00 `BaseBackend`\uc77c \uacbd\uc6b0 `assemble` \ud568\uc218\ub97c \uc774\uc6a9\ud574\uc11c \uc591\uc790\ud68c\ub85c\ub97c \ud55c\ubc88 \ubcc0\ud658\ud558\ub294 \uc808\ucc28\uac00 \ud544\uc694\ud569\ub2c8\ub2e4.\n\n\n```python\n# Aer \uae30\ubcf8 \uc2dc\ubbac\ub808\uc774\ud130\ub4e4\uc740 BaseBackend class\uc5d0 \ud574\ub2f9\ud569\ub2c8\ub2e4.\nfrom qiskit.providers import Backend, BaseBackend\nbackend = Aer.get_backend('qasm_simulator')\nprint('Backend?: ', isinstance(backend, Backend))\nprint('BaseBackend?: ', isinstance(backend, BaseBackend))\n```\n\n    Backend?:  False\n    BaseBackend?:  True\n\n\n\n```python\n# \ud2b8\ub79c\uc2a4\ud30c\uc77c, \uc5b4\uc0d8\ube14\uc744 \uc9c1\uc811 \ud574\uc8fc\uc5b4\uc57c\ud569\ub2c8\ub2e4.\nfrom qiskit import transpile, assemble\n\nqc = ghz_circuit(3)\n\nt_qc = transpile(qc)\nqobj = assemble(t_qc)\n\n# \ud68c\ub85c\ub97c backend\uc5d0\uc11c \uc218\ud589\ud569\ub2c8\ub2e4.\njob = backend.run(qobj)\n```\n\n\n```python\n# \uacb0\uacfc \ucd9c\ub825 \ubc29\ubc95\uc740 \ub3d9\uc77c\ud569\ub2c8\ub2e4.\nresult = job.result()\ncounts = result.get_counts()\nplot_histogram(counts)\n```\n\n### IonQ Backend\n\nIonQ backend\ub97c \uc0ac\uc6a9\ud558\ub824\uba74 \uc778\uc99d \ud1a0\ud070\uc774 \ud544\uc694\ud569\ub2c8\ub2e4. backend\ub97c \ubd88\ub7ec\uc628 \ub4a4\uc5d0\ub294 \uc704\uc5d0\uc11c \ubcf8 \uc2dc\ubbac\ub808\uc774\ud130\uc640 \ube44\uc2b7\ud558\uac8c \uc0ac\uc6a9\ud558\uba74 \ub429\ub2c8\ub2e4.\n\n\n```python\nfrom qiskit_ionq_provider import IonQProvider \n\n# Provider\ub97c \ubd88\ub7ec\uc635\ub2c8\ub2e4.\nprovider = IonQProvider(token=token_ionq)\n```\n\n\n```python\nprovider.backends()\n```\n\n\n\n\n    [<IonQSimulatorBackend('ionq_simulator')>, <IonQQPUBackend('ionq_qpu')>]\n\n\n\nIonQ backend\ub294 \uc2dc\ubbac\ub808\uc774\ud130 \ubc31\uc5d4\ub4dc ('ionq_simulator')\uc640 QPU \ud558\ub4dc\uc6e8\uc5b4 \ubc31\uc5d4\ub4dc ('ionq_qpu') \ub450 \uac00\uc9c0\uac00 \uc81c\uacf5\ub429\ub2c8\ub2e4. Qiskit Aer \uc2dc\ubbac\ub808\uc774\ud130\uc640 \ub2e4\ub974\uac8c ionq_simulator\ub294 ionq \uc11c\ubc84\uc5d0\uc11c \uc5f0\uc0b0\uc744 \uc218\ud589\ud558\uace0 \uacb0\uacfc\ub97c \ub124\ud2b8\uc6cc\ud06c\ub85c \ub3cc\ub824\uc90d\ub2c8\ub2e4.\n\n\n```python\nbackend = provider.get_backend('ionq_simulator')\n```\n\n\n```python\nqc = ghz_circuit(3)\njob = backend.run(qc, shots=1000)\n\njob.wait_for_final_state()  # job\uc774 \ub05d\ub0a0\ub54c\uae4c\uc9c0 \uae30\ub2e4\ub9bd\ub2c8\ub2e4.\nresult = job.result()\n\nplot_histogram(result.get_counts())\n```\n\n\n```python\nbackend = provider.get_backend('ionq_qpu')\n```\n\n\n```python\nqc = ghz_circuit(3)\njob = backend.run(qc, shots=1000)\n\njob.wait_for_final_state()  # job\uc774 \ub05d\ub0a0\ub54c\uae4c\uc9c0 \uae30\ub2e4\ub9bd\ub2c8\ub2e4.\nresult = job.result()\n\nplot_histogram(result.get_counts())\n```\n\n## \uc591\uc790\ud68c\ub85c\uc758 Visualization\n\nQiskit\uc740 \uc591\uc790\ud68c\ub85c\uc758 \ub2e4\uc591\ud55c \uc2dc\uac01\ud654 \ud234\uc744 \uc81c\uacf5\ud569\ub2c8\ub2e4.\n\n\uc55e\uc11c \ubcf8 `plot_histogram`, `plot_state_city` \uc678\uc5d0 \uc5b4\ub5a4 \uc2dc\uac01\ud654 \ud234\uc774 \uc788\ub294\uc9c0 \uc54c\uc544\ubcf4\uaca0\uc2b5\ub2c8\ub2e4.\n\n\n```python\n# Bloch vector\uc758 \uc2dc\uac01\ud654\uc785\ub2c8\ub2e4.\nfrom qiskit.visualization import plot_bloch_vector\n\nvec = [np.pi/2, 0, 1]  # theta, pi, radius\nplot_bloch_vector(vec)\n```\n\n\n```python\n# \uc591\uc790\ud68c\ub85c\uc758 vector \uc0c1\ud0dc\ub97c \uc774\uc6a9\ud558\uc5ec bloch vector\ub97c \uadf8\ub9ac\ub824\uba74 `plot_bloch_multivector`\ub97c \uc0ac\uc6a9\ud569\ub2c8\ub2e4.\nfrom qiskit.visualization import plot_bloch_multivector\n\nbackend = Aer.get_backend('statevector_simulator')\nqc = QuantumCircuit(1)\nqc.h(0)\njob = execute(qc, backend)\nvec = job.result().get_statevector()\n\nplot_bloch_multivector(vec)\n```\n\n\n```python\n# Qsphere\ub3c4 \uc720\uc6a9\ud558\uac8c \uc0ac\uc6a9\ub429\ub2c8\ub2e4.\nfrom qiskit.visualization import plot_state_qsphere\n\nplot_state_qsphere(vec)\n```\n\n\n```python\n## Qsphere\ub294 multi-qubit entangled state\uc5d0\uc11c \uac15\uc810\uc774 \uc788\uc2b5\ub2c8\ub2e4.\n\nqc = QuantumCircuit(2)\nqc.h(0)\nqc.cx(0,1)\n\n# \ub2e4\uc74c \ud568\uc218\ub3c4 \uc591\uc790\ud68c\ub85c\uc5d0\uc11c State vector\ub97c \uc5bb\uc5b4\ub0b4\ub294\ub370\uc5d0 \uc0ac\uc6a9\uac00\ub2a5\ud569\ub2c8\ub2e4.\nfrom qiskit.quantum_info import Statevector\nvec = Statevector.from_instruction(qc)\n\n# \ub450 \uac1c \uc774\uc0c1\uc758 \ud050\ube44\ud2b8 \uc0c1\ud0dc\ub294 Bloch vector\ub85c \ud45c\ud604\ud558\uba74 \uadf8 \uc758\ubbf8\uac00 \ubaa8\ud638\ud569\ub2c8\ub2e4.\nplot_bloch_multivector(vec)\n```\n\n\n```python\n# QSphere\ub294 \ubcf4\ub2e4 \uc9c1\uad00\uc801\uc778 \uc774\ud574\ub97c \ub3c4\uc640\uc90d\ub2c8\ub2e4.\nplot_state_qsphere(vec)\n```\n\n## Cat state (GHZ state) \ub9cc\ub4e4\uc5b4\ubcf4\uae30\n\n\uc704\uc5d0\uc11c\ub3c4 \uc0b4\ud3b4\ubcf4\uc558\uace0, \uc9c0\ub09c\ubc88 Sonika \ubc15\uc0ac\ub2d8\uacfc\ub3c4 \uc2e4\uc2b5\ud574\ubcf4\uc558\ub358 \uace0\uc591\uc774 \uc0c1\ud0dc \ub610\ub294 GHZ \uc0c1\ud0dc\ub97c \ub9cc\ub4e4\uc5b4 \ubd05\uc2dc\ub2e4.\n\nHadamard \uac8c\uc774\ud2b8\ub294 $|0\\rangle$ \uc0c1\ud0dc\ub97c $(|0\\rangle + |1\\rangle)/\\sqrt{2}$ \uc758 \uc911\ucca9\uc0c1\ud0dc\ub85c \ubc14\uafd4\uc90d\ub2c8\ub2e4. \uc774 Hadamard gate\uc640 CNOT \uac8c\uc774\ud2b8\ub4e4\uc744 \ud65c\uc6a9\ud574\uc11c \uc784\uc758\uc758 $n$ \ud050\ube44\ud2b8\uc5d0 \ub300\ud574\uc11c $(|00...0\\rangle + |11....1\\rangle)/\\sqrt{2}$ \uc0c1\ud0dc\ub97c \ub9cc\ub4e4\uc218 \uc788\uc2b5\ub2c8\ub2e4. \uc774\ub7f0 \uc0c1\ud0dc\ub97c GHZ (Greenberger\u2013Horne\u2013Zeilinger) \uc0c1\ud0dc \ub610\ub294 \uac70\uc2dc\uc801 \uc591\uc790 \uc911\ucca9\uc0c1\ud0dc\uc774\uae30 \ub54c\ubb38\uc5d0 Cat \uc0c1\ud0dc\ub77c\uace0\ub3c4 \ud569\ub2c8\ub2e4.\n\n\n```python\n# GHZ \uc0c1\ud0dc\ub97c \ub9cc\ub4dc\ub294 \uc591\uc790\ud68c\ub85c(\uce21\uc815 x)\ub97c \ubc18\ud658\ud558\ub294 \ud568\uc218\ub97c \ubbf8\ub9ac \uc815\uc758\ud558\uaca0\uc2b5\ub2c8\ub2e4.\ndef ghz_circuit_wo_measure(n: int):\n    assert isinstance(n, int) and n > 1\n    qc = QuantumCircuit(n)\n    qc.h(0)\n    qc.cx(0, range(1,n))\n    return qc\n\n# \ud050\ube44\ud2b8 \uac2f\uc218\ub97c \uc815\ud569\ub2c8\ub2e4.\nqubit_number = 5\n\nqc = ghz_circuit_wo_measure(qubit_number)\nqc.draw('mpl')\n```\n\n\n```python\nvec = Statevector.from_instruction(qc)\nplot_state_qsphere(vec)\n```\n\n\n```python\nbackend = provider.get_backend('ionq_simulator')\n```\n\n\n```python\n# \ud050\ube44\ud2b8 \uc22b\uc790\ub97c \ubc14\uafd4\uac00\uba74\uc11c \ud68c\ub85c\ub97c \ub9cc\ub4e4\uc5b4\uc11c \uc2e4\uc81c \ud558\ub4dc\uc6e8\uc5b4\uc5d0\uc11c \ud655\uc778\ud574 \ubcfc \uc218 \uc788\uc2b5\ub2c8\ub2e4.\nqubit_number = 1\nqc = ghz_circuit(qubit_number)\njob = backend.run(qc, shots=1000)\n\njob.wait_until_final_state()\nresult = job.result()\n\nplot_histogram(result.get_counts(), title = f'qubit number = {qubit_number:d}')\n```\n\n\n```python\nresult = job.result()\n\nplot_histogram(result.get_counts(), title = f'qubit number = {qubit_number:d}')\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "0fac6c63b9e6637ec45ab30756bd066cba26004b", "size": 692806, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "20210329_Qiskit_basic.ipynb", "max_stars_repo_name": "JKQuantum/Education_resource", "max_stars_repo_head_hexsha": "d9a5470a2349921e34f0aef9229d9d6df9abddea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "20210329_Qiskit_basic.ipynb", "max_issues_repo_name": "JKQuantum/Education_resource", "max_issues_repo_head_hexsha": "d9a5470a2349921e34f0aef9229d9d6df9abddea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "20210329_Qiskit_basic.ipynb", "max_forks_repo_name": "JKQuantum/Education_resource", "max_forks_repo_head_hexsha": "d9a5470a2349921e34f0aef9229d9d6df9abddea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 457.9021810972, "max_line_length": 102400, "alphanum_fraction": 0.9344246441, "converted": true, "num_tokens": 13840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869689484852374, "lm_q2_score": 0.1037486268663797, "lm_q1q2_score": 0.04343922791375131}}
{"text": "# Text Classification with SpaCy\n\nA common task in NLP is **text classification**. This is \"classification\" in the conventional machine learning sense, and it is applied to text. Examples include spam detection, sentiment analysis, and tagging customer queries. \n\nIn this tutorial, you'll learn text classification with spaCy. The classifier will detect spam messages, a common functionality in most email clients. Here is an overview of the data you'll use:\n\n\n```python\nimport pandas as pd\n\n# Loading the spam data\n# ham is the label for non-spam messages\nspam = pd.read_csv('../input/nlp-course/spam.csv')\nspam.head(10)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>label</th>\n      <th>text</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>ham</td>\n      <td>Go until jurong point, crazy.. Available only ...</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>ham</td>\n      <td>Ok lar... Joking wif u oni...</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>spam</td>\n      <td>Free entry in 2 a wkly comp to win FA Cup fina...</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>ham</td>\n      <td>U dun say so early hor... U c already then say...</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>ham</td>\n      <td>Nah I don't think he goes to usf, he lives aro...</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>spam</td>\n      <td>FreeMsg Hey there darling it's been 3 week's n...</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>ham</td>\n      <td>Even my brother is not like to speak with me. ...</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>ham</td>\n      <td>As per your request 'Melle Melle (Oru Minnamin...</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>spam</td>\n      <td>WINNER!! As a valued network customer you have...</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>spam</td>\n      <td>Had your mobile 11 months or more? U R entitle...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n# Bag of Words\nMachine learning models don't learn from raw text data. Instead, you need to convert the text to something numeric.\n\nThe simplest common representation is a variation of one-hot encoding. You represent each document as a vector of term frequencies for each term in the vocabulary. The vocabulary is built from all the tokens (terms) in the corpus (the collection of documents). \n\nAs an example, take the sentences \"Tea is life. Tea is love.\" and \"Tea is healthy, calming, and delicious.\" as our corpus. The vocabulary then is `{\"tea\", \"is\", \"life\", \"love\", \"healthy\", \"calming\", \"and\", \"delicious\"}` (ignoring punctuation).\n\nFor each document, count up how many times a term occurs, and place that count in the appropriate element of a vector. The first sentence has \"tea\" twice and that is the first position in our vocabulary, so we put the number 2 in the first element of the vector. Our sentences as vectors then look like \n\n$$\n\\begin{align}\nv_1 &= \\left[\\begin{matrix} 2 & 2 & 1 & 1 & 0 & 0 & 0 & 0 \\end{matrix}\\right] \\\\\nv_2 &= \\left[\\begin{matrix} 1 & 1 & 0 & 0 & 1 & 1 & 1 & 1 \\end{matrix}\\right]\n\\end{align}\n$$\n\nThis is called the **bag of words** representation. You can see that documents with similar terms will have similar vectors. Vocabularies frequently have tens of thousands of terms, so these vectors can be very large.\n\nAnother common representation is **TF-IDF (Term Frequency - Inverse Document Frequency)**. TF-IDF is similar to bag of words except that each term count is scaled by the term's frequency in the corpus. Using TF-IDF can potentially improve your models. You won't need it here. Feel free to look it up though!\n\n# Building a Bag of Words model\n\nOnce you have your documents in a bag of words representation, you can use those vectors as input to any machine learning model. spaCy handles the bag of words conversion and building a simple linear model for you with the `TextCategorizer` class.\n\nThe TextCategorizer is a spaCy **pipe**. Pipes are classes for processing and transforming tokens. When you create a spaCy model with `nlp = spacy.load('en_core_web_sm')`, there are default pipes that perform part of speech tagging, entity recognition, and other transformations. When you run text through a model `doc = nlp(\"Some text here\")`, the output of the pipes are attached to the tokens in the `doc` object. The lemmas for `token.lemma_` come from one of these pipes.\n\nYou can remove or add pipes to models. What we'll do here is create an empty model without any pipes (other than a tokenizer, since all models always have a tokenizer). Then, we'll create a TextCategorizer pipe and add it to the empty model.\n\n\n```python\nimport spacy\n\n# Create an empty model\nnlp = spacy.blank(\"en\")\n\n# Add the TextCategorizer to the empty model\ntextcat = nlp.add_pipe(\"textcat\")\n```\n\nNext we'll add the labels to the model. Here \"ham\" are for the real messages, \"spam\" are spam messages.\n\n\n```python\n# Add labels to text classifier\ntextcat.add_label(\"ham\")\ntextcat.add_label(\"spam\")\n```\n\n\n\n\n    1\n\n\n\n# Training a Text Categorizer Model\n\nNext, you'll convert the labels in the data to the form TextCategorizer requires. For each document, you'll create a dictionary of boolean values for each class. \n\nFor example, if a text is \"ham\", we need a dictionary `{'ham': True, 'spam': False}`. The model is looking for these labels inside another dictionary with the key `'cats'`.\n\n\n```python\ntrain_texts = spam['text'].values\ntrain_labels = [{'cats': {'ham': label == 'ham',\n                          'spam': label == 'spam'}} \n                for label in spam['label']]\n```\n\nThen we combine the texts and labels into a single list.\n\n\n```python\ntrain_data = list(zip(train_texts, train_labels))\ntrain_data[:3]\n```\n\n\n\n\n    [('Go until jurong point, crazy.. Available only in bugis n great world la e buffet... Cine there got amore wat...',\n      {'cats': {'ham': True, 'spam': False}}),\n     ('Ok lar... Joking wif u oni...', {'cats': {'ham': True, 'spam': False}}),\n     (\"Free entry in 2 a wkly comp to win FA Cup final tkts 21st May 2005. Text FA to 87121 to receive entry question(std txt rate)T&C's apply 08452810075over18's\",\n      {'cats': {'ham': False, 'spam': True}})]\n\n\n\nNow you are ready to train the model. First, create an `optimizer` using `nlp.begin_training()`. spaCy uses this optimizer to update the model. In general it's more efficient to train models in small batches. spaCy provides the `minibatch` function that returns a generator yielding minibatches for training. Finally, the minibatches are split into texts and labels, then used with `nlp.update` to update the model's parameters.\n\n\n```python\nfrom spacy.util import minibatch\nfrom spacy.training.example import Example\n\nspacy.util.fix_random_seed(1)\noptimizer = nlp.begin_training()\n\n# Create the batch generator with batch size = 8\nbatches = minibatch(train_data, size=8)\n# Iterate through minibatches\nfor batch in batches:\n    # Each batch is a list of (text, label) \n    for text, labels in batch:\n        doc = nlp.make_doc(text)\n        example = Example.from_dict(doc, labels)\n        nlp.update([example], sgd=optimizer)\n```\n\n    [2021-11-09 00:09:45,848] [INFO] Created vocabulary\n    [2021-11-09 00:09:45,851] [INFO] Finished initializing nlp object\n\n\nThis is just one training loop (or epoch) through the data. The model will typically need multiple epochs. Use another loop for more epochs, and optionally re-shuffle the training data at the begining of each loop. \n\n\n```python\nimport random\n\nrandom.seed(1)\nspacy.util.fix_random_seed(1)\noptimizer = nlp.begin_training()\n\nlosses = {}\nfor epoch in range(10):\n    random.shuffle(train_data)\n    # Create the batch generator with batch size = 8\n    batches = minibatch(train_data, size=8)\n    # Iterate through minibatches\n    for batch in batches:\n        for text, labels in batch:\n            doc = nlp.make_doc(text)\n            example = Example.from_dict(doc, labels)\n            nlp.update([example], sgd=optimizer, losses=losses)\n    print(losses)\n```\n\n    [2021-11-09 00:11:14,725] [INFO] Created vocabulary\n    [2021-11-09 00:11:14,727] [INFO] Finished initializing nlp object\n\n\n    {'textcat': 295.4672533843209}\n    {'textcat': 425.752376811059}\n    {'textcat': 513.7496465552074}\n    {'textcat': 574.2658501816283}\n    {'textcat': 613.3640732933637}\n    {'textcat': 641.618051840942}\n    {'textcat': 659.7342690400167}\n    {'textcat': 675.2031333876475}\n    {'textcat': 691.1385658034444}\n    {'textcat': 708.4780089379459}\n\n\n# Making Predictions\n\nNow that you have a trained model, you can make predictions with the `predict()` method. The input text needs to be tokenized with `nlp.tokenizer`. Then you pass the tokens to the predict method which returns scores. The scores are the probability the input text belongs to the classes.\n\n\n```python\ntexts = [\"Are you ready for the tea party????? It's gonna be wild\",\n         \"URGENT Reply to this message for GUARANTEED FREE TEA\" ]\ndocs = [nlp.tokenizer(text) for text in texts]\n    \n# Use textcat to get the scores for each doc\ntextcat = nlp.get_pipe('textcat')\nscores = textcat.predict(docs)\n\nprint(scores)\n```\n\n    [[9.9999440e-01 5.5444802e-06]\n     [1.6431263e-04 9.9983561e-01]]\n\n\nThe scores are used to predict a single class or label by choosing the label with the highest probability. You get the index of the highest probability with `scores.argmax`, then use the index to get the label string from `textcat.labels`.\n\n\n```python\n# From the scores, find the label with the highest score/probability\npredicted_labels = scores.argmax(axis=1)\nprint([textcat.labels[label] for label in predicted_labels])\n```\n\n    ['ham', 'spam']\n\n\nEvaluating the model is straightforward once you have the predictions. To measure the accuracy, calculate how many correct predictions are made on some test data, divided by the total number of predictions.\n\n# Your Turn\nTry it yourself as you **[predict the sentiment of Yelp reviews](https://www.kaggle.com/kernels/fork/6061027)**.\n\n---\n\n\n\n\n*Have questions or comments? Visit the [course discussion forum](https://www.kaggle.com/learn/natural-language-processing/discussion) to chat with other learners.*\n", "meta": {"hexsha": "9991184e530dde539f086a80674eb44a178809b1", "size": 24843, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "course/Natural Language Processing/text-classification.ipynb", "max_stars_repo_name": "furyhawk/kaggle_practice", "max_stars_repo_head_hexsha": "04bf045ae179db6a849fd2c2e833acc2e869f0f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-22T09:21:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T13:12:06.000Z", "max_issues_repo_path": "course/Natural Language Processing/text-classification.ipynb", "max_issues_repo_name": "furyhawk/kaggle_practice", "max_issues_repo_head_hexsha": "04bf045ae179db6a849fd2c2e833acc2e869f0f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "course/Natural Language Processing/text-classification.ipynb", "max_forks_repo_name": "furyhawk/kaggle_practice", "max_forks_repo_head_hexsha": "04bf045ae179db6a849fd2c2e833acc2e869f0f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1384217335, "max_line_length": 487, "alphanum_fraction": 0.5546029063, "converted": true, "num_tokens": 2803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.08882028456131581, "lm_q1q2_score": 0.04336947011674149}}
{"text": "```python\nprint(\"Hello world\")\n```\n\n    Hello world\n\n\n### My First Notebook\n\n\n```python\n# simple code\n2+2\n```\n\n\n\n\n    4\n\n\n\n\n```python\n# variable\nx=3\n```\n\n\n```python\nprint(x)\n```\n\n    3\n\n\n\n```python\n# used keyboard short cut ECS + L  to display line numbers\n\n```\n\n\n```python\n# use ! to run shell commands from jupiter\n\n! python --version\n```\n\n    Python 3.6.5 :: Anaconda, Inc.\n\n\n### Magic functions\n\n##### magic function: matplotlib\n\n\n```python\n%matplotlib inline\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nplt.plot(range(100))\n```\n\n##### magic function: time\n\n\n```python\n%time x= range(10000)\n```\n\n    Wall time: 1.01 ms\n\n\n##### magic function: timeit\n\n\n```python\n%%timeit x = range(10000)\nmax(x)\n```\n\n    347 \u00b5s \u00b1 95.7 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n\n\n##### magic function: writefile\n\n\n```python\n%%writefile test.txt\nThis is written from jupiter notebook\nA new file is created if no file exists with name test.txt\n```\n\n    Writing test.txt\n\n\n\n```python\n%%writefile test.txt\noverwriting to test.txt 2\n```\n\n    Overwriting test.txt\n\n\n##### magic function: ls\n\n\n```python\n%ls\n```\n\n     Volume in drive C is Windows\n     Volume Serial Number is 7E28-0B6E\n    \n     Directory of C:\\Users\\Sunit\\Documents\\GitHub\\Titanic\n    \n    10/22/2018  09:59 PM    <DIR>          .\n    10/22/2018  09:59 PM    <DIR>          ..\n    10/22/2018  09:39 PM    <DIR>          .ipynb_checkpoints\n    10/22/2018  09:59 PM            16,314 HelloWorld.ipynb\n    10/22/2018  09:31 PM             1,092 LICENSE\n    10/22/2018  09:53 PM                23 test.txt\n                   3 File(s)         17,429 bytes\n                   3 Dir(s)  176,694,788,096 bytes free\n\n\n##### magic function: HTML\n\n\n```python\n%%HTML\n<i> Image in jupyter notebook </i>\n</img>\n```\n\n\n<i> Image in jupyter notebook </i>\n</img>\n\n\n##### magic function: latex\n\n\n```latex\n%%latex\n\\begin{align}\nGradient :  \\nabla J = -2H^T (Y-HW)\n\\end{align}\n```\n\n\n\\begin{align}\nGradient :  \\nabla J = -2H^T (Y-HW)\n\\end{align}\n\n\n##### magic function: loat_ext\n\n\n\n```python\n! pip install ipython-sql\n```\n\n    Requirement already satisfied: ipython-sql in c:\\programdata\\anaconda3\\lib\\site-packages (0.3.9)\n    Requirement already satisfied: prettytable in c:\\programdata\\anaconda3\\lib\\site-packages (from ipython-sql) (0.7.2)\n    Requirement already satisfied: ipython-genutils>=0.1.0 in c:\\programdata\\anaconda3\\lib\\site-packages (from ipython-sql) (0.2.0)\n    Requirement already satisfied: sqlalchemy>=0.6.7 in c:\\programdata\\anaconda3\\lib\\site-packages (from ipython-sql) (1.2.7)\n    Requirement already satisfied: sqlparse in c:\\programdata\\anaconda3\\lib\\site-packages (from ipython-sql) (0.2.4)\n    Requirement already satisfied: ipython>=1.0 in c:\\programdata\\anaconda3\\lib\\site-packages (from ipython-sql) (6.4.0)\n    Requirement already satisfied: six in c:\\programdata\\anaconda3\\lib\\site-packages (from ipython-sql) (1.11.0)\n    Requirement already satisfied: simplegeneric>0.8 in c:\\programdata\\anaconda3\\lib\\site-packages (from ipython>=1.0->ipython-sql) (0.8.1)\n    Requirement already satisfied: pickleshare in c:\\programdata\\anaconda3\\lib\\site-packages (from ipython>=1.0->ipython-sql) (0.7.4)\n    Requirement already satisfied: pygments in c:\\programdata\\anaconda3\\lib\\site-packages (from ipython>=1.0->ipython-sql) (2.2.0)\n    Requirement already satisfied: decorator in c:\\programdata\\anaconda3\\lib\\site-packages (from ipython>=1.0->ipython-sql) (4.3.0)\n    Requirement already satisfied: setuptools>=18.5 in c:\\programdata\\anaconda3\\lib\\site-packages (from ipython>=1.0->ipython-sql) (39.1.0)\n    Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.15 in c:\\programdata\\anaconda3\\lib\\site-packages (from ipython>=1.0->ipython-sql) (1.0.15)\n    Requirement already satisfied: backcall in c:\\programdata\\anaconda3\\lib\\site-packages (from ipython>=1.0->ipython-sql) (0.1.0)\n    Requirement already satisfied: colorama; sys_platform == \"win32\" in c:\\programdata\\anaconda3\\lib\\site-packages (from ipython>=1.0->ipython-sql) (0.3.9)\n    Requirement already satisfied: jedi>=0.10 in c:\\programdata\\anaconda3\\lib\\site-packages (from ipython>=1.0->ipython-sql) (0.12.0)\n    Requirement already satisfied: traitlets>=4.2 in c:\\programdata\\anaconda3\\lib\\site-packages (from ipython>=1.0->ipython-sql) (4.3.2)\n    Requirement already satisfied: wcwidth in c:\\programdata\\anaconda3\\lib\\site-packages (from prompt-toolkit<2.0.0,>=1.0.15->ipython>=1.0->ipython-sql) (0.1.7)\n    Requirement already satisfied: parso>=0.2.0 in c:\\programdata\\anaconda3\\lib\\site-packages (from jedi>=0.10->ipython>=1.0->ipython-sql) (0.2.0)\n\n\n    launcher build: 64bit\n    launcher executable: Console\n    File 'C:\\Users\\Sunit\\AppData\\Local\\py.ini' non-existent\n    File 'C:\\ProgramData\\Anaconda3\\Scripts\\py.ini' non-existent\n    Called with command line: install ipython-sql\n    Using wrapped script file 'C:\\ProgramData\\Anaconda3\\Scripts\\pip-script.py'\n    Running wrapped script with command line 'C:\\ProgramData\\Anaconda3\\Scripts\\pip-script.py install ipython-sql'\n    maybe_handle_shebang: read 207 bytes\n    maybe_handle_shebang: BOM not found, using UTF-8\n    parse_shebang called without a valid shebang  (for argv0 C:\\ProgramData\\Anaconda3\\Scripts\\pip-script.py)\n    invented shebang: #!C:\\ProgramData\\Anaconda3\\python.exe\n    parse_shebang: found command: C:\\ProgramData\\Anaconda3\\python.exe\n    run_child: about to run 'C:\\ProgramData\\Anaconda3\\python.exe C:\\ProgramData\\Anaconda3\\Scripts\\pip-script.py install ipython-sql'\n    child process exit code: 0\n\n\n\n```python\n%%!\npip install ipython-sql\n```\n\n\n\n\n    ['launcher build: 64bit',\n     'launcher executable: Console',\n     \"File 'C:\\\\Users\\\\Sunit\\\\AppData\\\\Local\\\\py.ini' non-existent\",\n     \"File 'C:\\\\ProgramData\\\\Anaconda3\\\\Scripts\\\\py.ini' non-existent\",\n     'Called with command line: install ipython-sql',\n     \"Using wrapped script file 'C:\\\\ProgramData\\\\Anaconda3\\\\Scripts\\\\pip-script.py'\",\n     \"Running wrapped script with command line 'C:\\\\ProgramData\\\\Anaconda3\\\\Scripts\\\\pip-script.py install ipython-sql'\",\n     'maybe_handle_shebang: read 207 bytes',\n     'maybe_handle_shebang: BOM not found, using UTF-8',\n     'parse_shebang called without a valid shebang  (for argv0 C:\\\\ProgramData\\\\Anaconda3\\\\Scripts\\\\pip-script.py)',\n     'invented shebang: #!C:\\\\ProgramData\\\\Anaconda3\\\\python.exe',\n     'parse_shebang: found command: C:\\\\ProgramData\\\\Anaconda3\\\\python.exe',\n     \"run_child: about to run 'C:\\\\ProgramData\\\\Anaconda3\\\\python.exe C:\\\\ProgramData\\\\Anaconda3\\\\Scripts\\\\pip-script.py install ipython-sql'\",\n     'Requirement already satisfied: ipython-sql in c:\\\\programdata\\\\anaconda3\\\\lib\\\\site-packages (0.3.9)',\n     'Requirement already satisfied: ipython>=1.0 in c:\\\\programdata\\\\anaconda3\\\\lib\\\\site-packages (from ipython-sql) (6.4.0)',\n     'Requirement already satisfied: sqlparse in c:\\\\programdata\\\\anaconda3\\\\lib\\\\site-packages (from ipython-sql) (0.2.4)',\n     'Requirement already satisfied: six in c:\\\\programdata\\\\anaconda3\\\\lib\\\\site-packages (from ipython-sql) (1.11.0)',\n     'Requirement already satisfied: ipython-genutils>=0.1.0 in c:\\\\programdata\\\\anaconda3\\\\lib\\\\site-packages (from ipython-sql) (0.2.0)',\n     'Requirement already satisfied: sqlalchemy>=0.6.7 in c:\\\\programdata\\\\anaconda3\\\\lib\\\\site-packages (from ipython-sql) (1.2.7)',\n     'Requirement already satisfied: prettytable in c:\\\\programdata\\\\anaconda3\\\\lib\\\\site-packages (from ipython-sql) (0.7.2)',\n     'Requirement already satisfied: pickleshare in c:\\\\programdata\\\\anaconda3\\\\lib\\\\site-packages (from ipython>=1.0->ipython-sql) (0.7.4)',\n     'Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.15 in c:\\\\programdata\\\\anaconda3\\\\lib\\\\site-packages (from ipython>=1.0->ipython-sql) (1.0.15)',\n     'Requirement already satisfied: decorator in c:\\\\programdata\\\\anaconda3\\\\lib\\\\site-packages (from ipython>=1.0->ipython-sql) (4.3.0)',\n     'Requirement already satisfied: pygments in c:\\\\programdata\\\\anaconda3\\\\lib\\\\site-packages (from ipython>=1.0->ipython-sql) (2.2.0)',\n     'Requirement already satisfied: colorama; sys_platform == \"win32\" in c:\\\\programdata\\\\anaconda3\\\\lib\\\\site-packages (from ipython>=1.0->ipython-sql) (0.3.9)',\n     'Requirement already satisfied: jedi>=0.10 in c:\\\\programdata\\\\anaconda3\\\\lib\\\\site-packages (from ipython>=1.0->ipython-sql) (0.12.0)',\n     'Requirement already satisfied: traitlets>=4.2 in c:\\\\programdata\\\\anaconda3\\\\lib\\\\site-packages (from ipython>=1.0->ipython-sql) (4.3.2)',\n     'Requirement already satisfied: setuptools>=18.5 in c:\\\\programdata\\\\anaconda3\\\\lib\\\\site-packages (from ipython>=1.0->ipython-sql) (39.1.0)',\n     'Requirement already satisfied: backcall in c:\\\\programdata\\\\anaconda3\\\\lib\\\\site-packages (from ipython>=1.0->ipython-sql) (0.1.0)',\n     'Requirement already satisfied: simplegeneric>0.8 in c:\\\\programdata\\\\anaconda3\\\\lib\\\\site-packages (from ipython>=1.0->ipython-sql) (0.8.1)',\n     'Requirement already satisfied: wcwidth in c:\\\\programdata\\\\anaconda3\\\\lib\\\\site-packages (from prompt-toolkit<2.0.0,>=1.0.15->ipython>=1.0->ipython-sql) (0.1.7)',\n     'Requirement already satisfied: parso>=0.2.0 in c:\\\\programdata\\\\anaconda3\\\\lib\\\\site-packages (from jedi>=0.10->ipython>=1.0->ipython-sql) (0.2.0)',\n     'child process exit code: 0']\n\n\n\n\n```python\n%load_ext sql\n```\n\n\n```python\n%sql sqlite://\n```\n\n\n\n\n    'Connected: @None'\n\n\n\n\n```sql\n%%sql\nCREATE TABLE classroom(name, age, totalmarks);\nINSERT INTO classroom VALUES ('Sunith',20,89);\nINSERT INTO classroom VALUES ('Sid',07,95);\n\n```\n\n     * sqlite://\n    Done.\n    1 rows affected.\n    1 rows affected.\n\n\n\n\n\n    []\n\n\n\n\n```python\n%sql SELECT * FROM classroom\n```\n\n     * sqlite://\n    Done.\n\n\n\n\n\n<table>\n    <tr>\n        <th>name</th>\n        <th>age</th>\n        <th>totalmarks</th>\n    </tr>\n    <tr>\n        <td>Sunith</td>\n        <td>20</td>\n        <td>89</td>\n    </tr>\n    <tr>\n        <td>Sid</td>\n        <td>7</td>\n        <td>95</td>\n    </tr>\n</table>\n\n\n\n##### magic function: lsmagic\n\n\n```python\n%lsmagic\n```\n\n\n\n\n    Available line magics:\n    %alias  %alias_magic  %autocall  %automagic  %autosave  %bookmark  %cd  %clear  %cls  %colors  %config  %connect_info  %copy  %ddir  %debug  %dhist  %dirs  %doctest_mode  %echo  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %less  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %macro  %magic  %matplotlib  %mkdir  %more  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %popd  %pprint  %precision  %profile  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %ren  %rep  %rerun  %reset  %reset_selective  %rmdir  %run  %save  %sc  %set_env  %sql  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode\n    \n    Available cell magics:\n    %%!  %%HTML  %%SVG  %%bash  %%capture  %%cmd  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%markdown  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%sql  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile\n    \n    Automagic is ON, % prefix IS NOT needed for line magics.\n\n\n\n#### Extracting data from relation database\n\n\n##### SQLite Database\n\n###### import SQLite\n\n\n```python\nimport sqlite3\n```\n\n###### connect to DB\n\n\n```python\nconnection = sqlite3.connect(\"classroomDB.db\")\nconnection.close()\n```\n\n###### create table\n\n\n```python\nconnection = sqlite3.connect(\"classroomDB.db\")\n# open cursor\ncursor=connection.cursor()\n# query for creating table\ncreate_table= \"\"\" \n                CREATE TABLE classroom(\n                student_id INTEGER PRIMARY KEY,\n                name VARCHAR(20),\n                gender CHAR(1),\n                mark INTEGER\n                );\"\"\"\n# execute query\ncursor.execute(create_table)\n# commit change\nconnection.commit()\n# close connection\nconnection.close()\n```\n\n###### insert data\n\n\n\n```python\nclassroom=[(1,\"Sunith\",\"M\",92),\n        (2,\"Varsha\",\"F\",93),\n        (3,\"Jyotika\",\"F\",92),\n        (4,\"Sid\",\"M\",95)]\n\n# open connection\nconnection = sqlite3.connect(\"classroomDB.db\")\n# open cursor\ncursor=connection.cursor()\n#insert each student record\nfor student in classroom:\n    insert_statement=\"\"\"INSERT INTO classroom\n                    (student_id , name, gender, mark)\n                    VALUES\n                    ({0},\"{1}\",\"{2}\",{3});\"\"\".format(student[0],student[1],student[2],student[3])\n    #execute insert query\n    cursor.execute(insert_statement)\n    \n# commit change\nconnection.commit()\n# close connection\nconnection.close()\n```\n\n###### read data\n\n\n\n```python\n# open connection\nconnection = sqlite3.connect(\"classroomDB.db\")\n# open cursor\ncursor=connection.cursor()\n\nselect_query = \"SELECT * FROM classroom\"\nresults = cursor.execute(select_query)\n\nfor student in results:\n    print(student)\n\n# close connection\nconnection.close()\n\n```\n\n    (1, 'Sunith', 'M', 92)\n    (2, 'Varsha', 'F', 93)\n    (3, 'Jyotika', 'F', 92)\n    (4, 'Sid', 'M', 95)\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "8ed5c3a79789f4b9665f9a1a8c60e7ba694b4133", "size": 38759, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": ".ipynb_checkpoints/HelloWorld-checkpoint.ipynb", "max_stars_repo_name": "ramshagit/Helloworld", "max_stars_repo_head_hexsha": "ab17cfcda70b99b5be784337bd5e16609396d480", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": ".ipynb_checkpoints/HelloWorld-checkpoint.ipynb", "max_issues_repo_name": "ramshagit/Helloworld", "max_issues_repo_head_hexsha": "ab17cfcda70b99b5be784337bd5e16609396d480", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": ".ipynb_checkpoints/HelloWorld-checkpoint.ipynb", "max_forks_repo_name": "ramshagit/Helloworld", "max_forks_repo_head_hexsha": "ab17cfcda70b99b5be784337bd5e16609396d480", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-10-31T04:00:12.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-31T04:01:13.000Z", "avg_line_length": 42.0379609544, "max_line_length": 11660, "alphanum_fraction": 0.6569570938, "converted": true, "num_tokens": 4014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.11596071825396675, "lm_q1q2_score": 0.04335490894639872}}
{"text": "```python\nfrom IPython.html.services.config import ConfigManager\nfrom IPython.utils.path import locate_profile\ncm = ConfigManager(profile_dir=locate_profile(get_ipython().profile))\ncm.update('livereveal', {\n              'theme': 'sky',\n              'transition': 'zoom',\n              'start_slideshow_at': 'selected',\n})\n```\n\n\n\n\n    {u'start_slideshow_at': 'selected', u'theme': 'sky', u'transition': 'zoom'}\n\n\n\n#Lecture 10. Integral equations: discretization\n\n## Previous lecture \n- Introduction into the integral equations: the basic one, the concept of non-locality\n- Exterior and interior problems\n\n\n## Todays lecture\n- How to discretize: method of moments (MoM) and the Galerkin method\n- Computation of the singular integrals and exponential sums\n- Fast methods: the idea of the Barnes-Hut method\n\n## Books\nBooks on integral equations\n\n- [Integral equation methods in scattering theory, D. Colton R. Kress](https://www.google.com/books?hl=ru&lr=&id=Z9qmAgAAQBAJ&oi=fnd&pg=PR1&dq=Colton+Kress+integral+equation&ots=0H3pcRZBUs&sig=0RzExxkaSor_Sv9Ss7HIX3cd864) \n- Sauter, Schwab, Boundary element methods (2011)\n\n## Method of moments (collocation method)\nRecall the basic integral equation from electrostatics:\n\n$$\\int_{\\Omega} \\frac{q(y) dy}{\\Vert x - y \\Vert} = f(x).$$\n\n1. First we mesh the domain in simplices.\n2. Then, we introduce the discrete **solution space** (piecewise-linear, piecewise-constant functions).\n3. Then, we approximate the solution as a linear combination of the basis functions\n  $$ q(y) = \\sum_i q_i \\phi_i(y).$$\n\n## MoM (continued)\nThen, we get the system of equations\n$$\n     f(x) = \\sum_i q_i \\int_{\\Pi_i} \\frac{\\phi_i}{\\Vert x - y \\Vert } dy.\n$$\nThe <font color='red'> method of moments </font> is obtained by the selection of <font color='red'>\n</font> collocation points (aka staggerred grids), typically in the middle of triangles/rectangles\n\n## Piecewise-constant basis functions\n\nFor a piecewise constant basis functions, we have\n\n$$\\int_{\\Pi} \\frac{1}{\\Vert x - y \\Vert} dy, $$\n\nwhere this is a two-dimensional integral.\n\n## Computing the simplest integral\nWe can actually compute the anti-derivative of the integral in question, but taking successive integrals\n\n$$\n   \\frac{1}{\\sqrt{x^2 + y^2}}\n$$\n\n\\begin{equation}\n\\begin{split}\nF(x, y) = \\int \\int \\frac{1}{\\sqrt{x^2 + y^2}} dx dy = \\\\\n-y + \ny \\log(x + \\sqrt{x^2 + y^2}) + x \\log(y + \\sqrt{x^2 + y^2}),\n\\end{split}\n\\end{equation}\n\nand the final integral is just \n$$\n   I(x_0, y_0, x_1, y_1) = F(x_0, y_0) + F(x_1, y_1) - F(x_0, y_1) - F(x_1, y_0),\n$$\n\n(generalization of the Newton-Leibniz formula)\n\n\n```python\nimport sympy\nfrom sympy import Symbol, sqrt\nx = Symbol('x', real=True)\na = Symbol('a', real=True)\ny = Symbol('y', real=True)\nb = Symbol('b', real=True)\nr = sqrt(x ** 2 + y ** 2)\nsympy.init_printing()\nz = sympy.integrate(1/r, x, conds='none')\nprint z\n```\n\n## Nystrom method\nA Nystrom method is a popular choice: replace the integral by <font color='red'> quadrature </font>  \n\nprobably by the simplest one: the rectangle formula, \n\nwhich in 1D has the form\n\n$$I(f) = \\sum_{k=0}^n w_k f(x_k), $$\n\nwhere $x_k$ is the uniform grid on the interval, $w_0 = w_n = h/2, \\quad w_k = h$ for all other $k$.\n\n## For our equation, it looks like\n\n  $$A_{ij} = \\frac{1} {\\Vert x_i - y_j \\Vert} h^2,$$\n  \n  the set $x_i$ can be called <font color='red'> receivers </font> and the set $y_j$ can be called <font color='red'> sources </font>;\n  \n  A typical way is to shift the grid by half-step, i.e. in 1D it will be\n  \n  $$\n  A_{ij} = \\frac{1}{|i-j| + \\frac{1}{2}}.\n  $$\n  By the way, do you remember, what is the rank of this matrix?\n\n## Galerkin method\n1. Collocation method gives non-symmetric matrices, even if the original operator was symmetric;\n2. Nystrom method adds logarithmic factor into the accuracy estimate\n3. Galerkin method is the method of choice in many cases\n\n## Galerkin method \nA Galerkin method is defined for an arbitrary linear (and even non-linear) equations\n\n$$\n    A u = f, \n$$\n\nyou select the <font color='red'> test space </font> and <font color='red'> trial space </font>. \n\nFor simplicity, let them be equal,\n\ni.e. \n$$\n   u = \\sum_i u_i \\phi_i,\n$$\n\nand \n\n$$A_{ij} = (A \\phi_i, \\phi_j) $$\n\n\n## Integrals in the Galerkin method\nWe have to compute 4D integrals (here it is written for piecewise-constant functions)\n\n$$\n  A_{ij} = \\int_{\\Omega_i} \\int_{\\Omega_j}\\frac{1}{\\Vert x - y \\Vert} dx dy\n$$\nAnalytic expression are cumbersome!\n\n\n## Semi-numerical method\nYou can be **a little bit** smarter: approximate $1/r$ by something that can be well-integrated.  \n\nBy a sum of separable functions!\n\n$$\\frac{1}{\\Vert x - y\\Vert } \\approx \\sum_{\\alpha=1}^r u_{\\alpha}(x) u_{\\alpha}(y)$$\n\nWe have used the symmetry.\n\nBut how to compute these functions $u_{\\alpha}$?  (why it is useful?)\n\n\n## Exponential sums\n\nThere is an identity:\n\n$$\\frac{1}{\\sqrt{x}} = \\frac{1}{\\sqrt{\\pi}} \\int^{\\infty}_0 \\frac{e^{-px}}{\\sqrt{p}} dp.$$\n\nIt can be very useful in separating variables.\n\n\n## A quadrature\n\nSuppose we have a quadrature for the integral:\n\n$$ \\frac{1}{\\sqrt{x}} = \\frac{1}{\\sqrt{\\pi}} \\int^{\\infty}_0 \\frac{e^{-px}}{\\sqrt{p}} dp. \\approx \\sum_{k} w_k e^{-p_k x}.$$\n\nThen put \n\n$$x := x^2 + y^2$$\n\nand we get the sum of <font color='red'> Gaussians </font> on the right.\n\n## Sum of Gaussians\n\n$$\\frac{1}{r} \\approx \\sum_{k} w_k e^{-p_k (x^2 + y^2)},$$\n\nand the integrals reduce to the 1D integrals\n\n$$\n   \\int_a^b e^{-p_k x^2} dx, \n$$\n\nand this can be expressed via the <font color='red'> Error functions </font> (and there is a standard numpy erfc function)\n\n## But who you can approximate?\n\nWe reduced the problem to the problem of creating a good quadrature rule for the integral\n\n$$\\int^{\\infty}_0 \\frac{e^{-px}}{\\sqrt{p}} dp$$\n\nYou have to do the $p = e^t$ (why do we do so?) and we the new integral\n\n$$\n\\int^{\\infty}_{-\\infty} e^{-e^{t} x + t/2} dt\n$$\n\nand this integral is then approximate by **trapezoidal rule** $t_k = a_t + k h_t, \\quad h_t = (b_t - a_t)/K$\n\n\nThe integral is doubly exponentially decaying, and also its Fourier transform is decaying exponentially fast.\n\nThus, trapezoidal rule has exponential convergence in this setting\n\nA short demo...\n\n\n```python\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(style='ticks', palette='Set2')\nsns.despine()\n%matplotlib inline\na = -10\nb = 20\nn = 70\nt = np.linspace(a, b, n)\nh = t[1] - t[0]\nw = np.ones(n) * h\nw[0] = h/2\nw[n-1] = h/2\nw = w * np.exp(0.5 * t)/np.sqrt(math.pi)\nps = np.exp(t)\nx = np.linspace(0.1, 1)\nfun = 1.0/np.sqrt(x)\nappr = 0 * x\nfor i in xrange(n):\n    appr = appr + w[i] * np.exp(-(x) * ps[i])\n#plt.plot(x, fun)\nax = plt.subplot(1, 1, 1)\nax.plot(x, appr - fun)\n#ax.set_title('Approximation error by %d Gaussians' % n)\nax.set_title('Error')\nplt.tight_layout(.8)\n```\n\n## A sidenote about fitting by sum of exponentials\n- Approximation of a given function by a sum of exponentials is a ill-posed problem\n- Original method by Prony (1795)\n- Recent work by [G. Beylkin, et. al, Approximation by exponential sums revisited](https://www.google.ru/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&cad=rja&uact=8&ved=0CCYQFjAB&url=http%3A%2F%2Famath.colorado.edu%2Fpub%2Fwavelets%2Fpapers%2FBEY-MON-2010.pdf&ei=Cok1VZHkJKLnygO7hYCgBw&usg=AFQjCNGRcxece5lCuy9N7oheTBOzOpcSYw&sig2=Rf3DPGBAMmYO4parmQXzFQ&bvm=bv.91071109,d.bGQ) \n\n## Efficient quadratures (papers)\n- C. Schwab,  S. Sauter [Efficient automatic quadrature in 3-d Galerkin BEM](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.45.4312&rep=rep1&type=pdf)\n- A. Polimeridis, Traianos V Yioultsis [On the direct evaluation of weakly singular integrals in Galerkin mixed potential integral equation formulations](http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=4618709)\n\n## Green functions and fundamental solutions\n\nTerminology:\n- A fundamental solution is a \"point charge\" in free space: no boundary conditions\n- Green function can be for the boundary conditions/layered media/etc. (i.e. \"inverse\" of the differential operator)\n\n## Fundamental solution: Helmholtz\nThe Helmholtz equation has the form\n\n$$\\Delta u + k^2 u = f,$$\n\nand it describes the propagation of <font color='red'> scalar waves </font> (acoustic wave).  \n\n$k$ is called **wavenumber**.\n\nThe fundamental solution (the one that gives $\\delta$-function after the application of the operator)  has the form\n\n$$K(r) = \\frac{\\exp(i k r)}{r}.$$\n\nSo it oscillates.\n\n## Laplace in 2D\n\nWhat is the fundamental solution to the Laplace equation in 2D?\n\n$$G(x, y) = \\log \\Vert x - y \\Vert.$$\n\nIt plays a role in the theory of <font color='red'> conformal mappings </font>\n\nHelmholtz in 2D is solved by the <font color='red'> Hankel function </font>\n\n## Stokes problem\nStokes equation define the laminar flow in low Reynolds number regime:\n\n\\begin{equation}\n\\begin{split}\n- \\nabla p + \\mu \\Delta v = -F \\delta(r) \\\\\n \\nabla \\cdot p = 0\n\\end{split}\n\\end{equation}\n\n\n## Maxwell equations\n\n$$\n\\begin{split}\n\\nabla \\times H = \\frac{\\partial D}{\\partial t} + J, \\\\\\quad \\nabla \\times E = -\\frac{\\partial B}{\\partial t}, \\quad \\nabla \\cdot D =  \\rho, \\quad \\nabla \\cdot B = 0. \\\\\nD = \\varepsilon E, \\quad H = \\mu B.\n\\end{split}\n$$\n\n## How to make it fast\n\nThe memory is $\\mathcal{O}(N^2)$, the complexity is $\\mathcal{O}(N^3)$.  \n\nNeed to make it $\\mathcal{O}(N \\log N)$ both in memory and complexity of matrix-by-vector product.\n\n## Matrix structure\nThe integral operator matrix:\n\n1. Matrix is dense\n2. Matrix is not of low-rank\n3. Some blocks are of low rank!\n\nA demo\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nn = 128\na = [[1.0/(abs(i - j) + 0.5) for i in xrange(n)] for j in xrange(n)]\na = np.array(a)\n\n\n\nplt.plot(np.linalg.svd(a)[1])\n```\n\n\n```python\n#And for a block:\nplt.semilogy(np.linalg.svd(a[:n/2, n/2:])[1])\n```\n\n## Off-diagonal blocks correspond to \"far\" interaction\n\n$$y_i = \\sum_{j} a_{ij} q_j,$$\n\nand the sources are separated from the receivers. \n\nThis gives a hint: separated geometrically -- low-rank property.\n\n## Geometric separability and low rank\n\n\nFor $\\frac{1}{r}$ we can have the exponential sums to separate variables, if $r > r_0$. \n\nWhat happens, if $r_0$ goes to zero?\n\nThe separability property vanishes!\n\n## One-dimensional case\n\n\n$$A = \\begin{bmatrix} A_{11} & A_{12} \\\\ A_{21} & A_{22}\\end{bmatrix},$$\n\nwhere $A_{12}$ and $A_{21}$ correspond to the \"far\" interaction, and are of low-rank.\n\nRemember, that a low-rank matrix can be factored as \n\n$$A = U V^{\\top},$$\n\nwhere $U$ is $n \\times r$, $V$ is $m \\times r$, \n\n## Memory estimate\n\nThus we have \n\n$$Memory(n) = 2 Memory(n/2) + 2 n/2 r$$\n\nand that gives \n\n$Memory(n) = 2 n/2 * r + 4 n/4 * r + \\ldots = \\mathcal{O}( n \\log n)$\n\nSimilar estimates hold for the matrix-by-vector product procedure (why do we care about that?)\n\n## Two-dimensional case\nIn two dimension, the splitting is different.\n\n\n```python\nfrom numba import jit\nn = 32\nt = np.linspace(0, 1, n)\nh = t[1] - t[0]\nx_src, y_src  = np.meshgrid(t, t)\nx_src, y_src = x_src.flatten(), y_src.flatten()\nx_rec, y_rec = x_src + h * 0.5, y_src + 0.5 * h\nN = n * n\nmat = np.zeros((N, N))\n@jit(nopython=True)\ndef compute_mat(mat, x_src, y_src, x_rec, y_rec):\n    for i in range(N):\n        for j in xrange(N):\n            r = (x_src[i] - x_rec[j]) ** 2 + (y_src[i] - y_rec[j]) ** 2\n            mat[i, j] = 1.0/np.sqrt(r)\n            \n \n\n%timeit compute_mat(mat, x_src, y_src, x_rec, y_rec)\n#(x_rec - x_src)/h\n```\n\n    The slowest run took 20.23 times longer than the fastest. This could mean that an intermediate result is being cached \n    100 loops, best of 3: 9.62 ms per loop\n\n\nPlotting the singular values of the off-diagonal block shows that they do not decay that fast.  \n\nWhy? Because they correspond to the non-separated sets of sources and receivers.\n\n\n```python\nplt.semilogy(np.linalg.svd(mat[:N/2, N/2:])[1])\n```\n\n## The general scheme\n- Construct **trees** for the sources and receivers\n- Check the sets for geometric separability.\n- If they are not separated, call the recursion\n- Otherwise, do low-rank approximation.\n\nThis is the basis for the **Barnes-Hut** method (original work in astronomy)  \n\nand the preliminary approach to the <font color='red'> Fast Multipole Method </font>, proposed by Greengard and Rokhlin\n\n\n```python\nfrom IPython.core.display import HTML\ndef css_styling():\n    styles = open(\"./styles/alex.css\", \"r\").read()\n    return HTML(styles)\ncss_styling()\n```\n\n\n\n\n<link href='http://fonts.googleapis.com/css?family=Fenix' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:100,300,400,500,700,800,900,100italic,300italic,400italic,500italic,700italic,800italic,900italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Source+Code+Pro:300,400' rel='stylesheet' type='text/css'>\n<style>\n    @font-face {\n        font-family: \"Computer Modern\";\n        src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');\n    }\n    div.cell{\n        /*width:80%;*/\n        /*margin-left:auto !important;\n        margin-right:auto;*/\n    }\n    h1 {\n        font-family: 'Alegreya Sans', sans-serif;\n    }\n    h2 {\n        font-family: 'Fenix', serif;\n    }\n    h3{\n\t\tfont-family: 'Fenix', serif;\n        margin-top:12px;\n        margin-bottom: 3px;\n       }\n\th4{\n\t\tfont-family: 'Fenix', serif;\n       }\n    h5 {\n        font-family: 'Alegreya Sans', sans-serif;\n    }\t   \n    div.text_cell_render{\n        font-family: 'Alegreya Sans',Computer Modern, \"Helvetica Neue\", Arial, Helvetica, Geneva, sans-serif;\n        line-height: 1.2;\n        font-size: 100%;\n        /*width:70%;*/\n        /*margin-left:auto;*/\n        margin-right:auto;\n    }\n    .CodeMirror{\n            font-family: \"Source Code Pro\";\n\t\t\tfont-size: 90%;\n    }\n/*    .prompt{\n        display: None;\n    }*/\n    .text_cell_render h1 {\n        font-weight: 200;\n        font-size: 50pt;\n\t\tline-height: 100%;\n        color:#CD2305;\n        margin-bottom: 0.5em;\n        margin-top: 0.5em;\n        display: block;\n    }\t\n    .text_cell_render h5 {\n        font-weight: 300;\n        font-size: 16pt;\n        color: #CD2305;\n        font-style: italic;\n        margin-bottom: .5em;\n        margin-top: 0.5em;\n        display: block;\n    }\n\n    li {\n        line-height: 100%;\n    }\n    .warning{\n        color: rgb( 240, 20, 20 )\n        }  \n</style>\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "0a9f7b51bfbceb8ae86756197eb3f6a259963c75", "size": 78130, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lecture-10.ipynb", "max_stars_repo_name": "oseledets/fastpde", "max_stars_repo_head_hexsha": "1d6159716b4cf2e41e63e611d787ee887936bf2f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-09-29T14:44:38.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-06T22:25:53.000Z", "max_issues_repo_path": "lecture-10.ipynb", "max_issues_repo_name": "oseledets/fastpde", "max_issues_repo_head_hexsha": "1d6159716b4cf2e41e63e611d787ee887936bf2f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lecture-10.ipynb", "max_forks_repo_name": "oseledets/fastpde", "max_forks_repo_head_hexsha": "1d6159716b4cf2e41e63e611d787ee887936bf2f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2015-03-30T10:11:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-22T07:10:48.000Z", "avg_line_length": 48.1986428131, "max_line_length": 378, "alphanum_fraction": 0.717125304, "converted": true, "num_tokens": 4542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28140560742914383, "lm_q2_score": 0.15405755686555633, "lm_q1q2_score": 0.04335266036880175}}
{"text": "```python\nimport kamodo\nfrom readers.gitm.gitmK import GITM\n\nimport glob\nimport numpy as np\nfrom plotly.offline import init_notebook_mode, iplot, plot\nimport plotly.io as pio\nfrom kaleido.scopes.plotly import PlotlyScope\ninit_notebook_mode(connected = True)\n```\n\n\n\n\n\n\n\n```python\n# Select the data file\nrunpath = \"../../../data/\"\n#runname = \"Sophia_Schwalbe_062220_IT_4\"\n#runname = \"Aaron_Ridley_081017_IT_2\"\nrunname = \"GDC_GITM\"\nfiles = glob.glob(runpath+runname+'/*.bin')\nfiles.sort()\nfile = files[-1]\n\nmodel = GITM(file, runpath=runpath, runname=runname, debug=1)\nmodel\n```\n\n    opening ../../../data/GDC_GITM/3DALL_t980106_002900.bin\n    ... simulation time =  1998-01-06 00:29:00.000539\n    ... raw data array size =  (112, 184, 54)\n    ... range of altitudes is  96880.16186492516  to  567345.7542485126  meters.\n    ... GITM code version  4.03\n    Time loading file and kamodifying results: 2.6889 seconds\n\n\n\n\n\n\\begin{equation}\\rho{\\left(\\vec{x} \\right)} [kg/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{O3P}{\\left(\\vec{x} \\right)} [kg/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{O_{2}}{\\left(\\vec{x} \\right)} [kg/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{N_{2}}{\\left(\\vec{x} \\right)} [kg/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{N4S}{\\left(\\vec{x} \\right)} [kg/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{NO}{\\left(\\vec{x} \\right)} [kg/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{He}{\\left(\\vec{x} \\right)} [kg/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{N2D}{\\left(\\vec{x} \\right)} [kg/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{N2P}{\\left(\\vec{x} \\right)} [kg/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}H{\\left(\\vec{x} \\right)} [kg/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{CO_{2}}{\\left(\\vec{x} \\right)} [kg/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{O1D}{\\left(\\vec{x} \\right)} [kg/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{Tn}{\\left(\\vec{x} \\right)} [K] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{Vn_{east}}{\\left(\\vec{x} \\right)} [m/s] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{Vn_{north}}{\\left(\\vec{x} \\right)} [m/s] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{Vn_{up}}{\\left(\\vec{x} \\right)} [m/s] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{Vn_{upO3P}}{\\left(\\vec{x} \\right)} [m/s] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{Vn_{upO2}}{\\left(\\vec{x} \\right)} [m/s] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{Vn_{upN2}}{\\left(\\vec{x} \\right)} [m/s] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{Vn_{upN4S}}{\\left(\\vec{x} \\right)} [m/s] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{Vn_{upNO}}{\\left(\\vec{x} \\right)} [m/s] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{Vn_{upHe}}{\\left(\\vec{x} \\right)} [m/s] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{O4SP+}{\\left(\\vec{x} \\right)} [kg/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{O2+}{\\left(\\vec{x} \\right)} [kg/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{N2+}{\\left(\\vec{x} \\right)} [kg/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{N+}{\\left(\\vec{x} \\right)} [kg/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{NO+}{\\left(\\vec{x} \\right)} [kg/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{O2D+}{\\left(\\vec{x} \\right)} [1/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{O2P+}{\\left(\\vec{x} \\right)} [kg/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{H+}{\\left(\\vec{x} \\right)} [kg/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{He+}{\\left(\\vec{x} \\right)} [kg/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{e-}{\\left(\\vec{x} \\right)} [1/m^3] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{Te}{\\left(\\vec{x} \\right)} [K] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{Ti}{\\left(\\vec{x} \\right)} [K] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{Vi_{east}}{\\left(\\vec{x} \\right)} [m/s] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{Vi_{north}}{\\left(\\vec{x} \\right)} [m/s] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{Vi_{up}}{\\left(\\vec{x} \\right)} [m/s] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{MagneticLatitude}{\\left(\\vec{x} \\right)} [degrees] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\\begin{equation}\\operatorname{MagneticLongitude}{\\left(\\vec{x} \\right)} [degrees] = \\lambda{\\left(\\vec{x} \\right)}\\end{equation}\n\n\n\n\n```python\n#Write list of variables to file 'kamodo_info'\nmodel.write_variables()\n```\n\n# Interpolation\n\n\n```python\nprint(model.rho([[70,30.,440000.],[70,40.,400000.],[90,40.,400000.],[120,40.,440000.]]))\n```\n\n    [2.68652554e-14 9.22378231e-14 1.12557827e-13 9.39359154e-14]\n\n\n\n```python\nvar=\"rho\"\ngrid = np.ndarray(shape=(4,3), dtype=np.float32)\ngrid[:,0] = [70, 70, 90, 120]\ngrid[:,1] = [30, 40, 40, 40]\ngrid[:,2] = [440000., 400000., 400000., 440000.]\nunits=model.variables[var]['units']\ntest = model.variables[var]['interpolator'](grid)\nprint(units)\nprint(test)\n```\n\n    kg/m^3\n    [2.68652554e-14 9.22378231e-14 1.12557827e-13 9.39359154e-14]\n\n\n# Plotting\n\n\n```python\n# Slice at given Altitude\nfig=model.get_plot('rho', 400000., '2D-alt', colorscale='Viridis', log=\"T\")\n#iplot(fig)\n\n#pio.write_image(fig, 'images/GITM_2D-alt.svg')\n```\n\n\n\n\n```python\n# Slice at given latitude\nfig=model.get_plot('Tn', 0., '2D-lat', colorscale='Rainbow')\niplot(fig)\n\n#pio.write_image(fig, 'images/GITM_2D-lat.svg')\n```\n\n\n\n\n```python\n# Slice at given longitude\nfig=model.get_plot('rho', 180., '2D-lon', colorscale='Rainbow', log='T')\niplot(fig)\n\n#pio.write_image(fig, 'images/GITM_2D-lon.svg')\n```\n\n\n\n\n```python\n# 3D view at given Altitude\nfig=model.get_plot('rho', 400000., '3D-alt', colorscale='Rainbow')\niplot(fig)\n\n#pio.write_image(fig, 'images/GITM_3D-alt.svg')\n```\n\n\n\n\n```python\n# Isosurface with slice at Lat=0.\nfig=model.get_plot('Tn', 750., 'iso')\niplot(fig)\n\n#scope = PlotlyScope()\n#with open(\"images/GITM_iso.png\", \"wb\") as f:\n#    f.write(scope.transform(fig, format=\"png\"))\n\n#fig.write_html(\"GITM_iso.html\",full_html=False)\n```\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "8d11c9fad6c317e3b766dc2e3723b34938d1c7ad", "size": 21752, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/notebooks/GITM.ipynb", "max_stars_repo_name": "MrCull/Kamodo", "max_stars_repo_head_hexsha": "7f8289e5a21c81320f562a30f29e5d3dbe5366dd", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2019-08-30T16:18:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T16:33:51.000Z", "max_issues_repo_path": "docs/notebooks/GITM.ipynb", "max_issues_repo_name": "MrCull/Kamodo", "max_issues_repo_head_hexsha": "7f8289e5a21c81320f562a30f29e5d3dbe5366dd", "max_issues_repo_licenses": ["NASA-1.3"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2020-02-13T20:46:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T17:00:15.000Z", "max_forks_repo_path": "docs/notebooks/GITM.ipynb", "max_forks_repo_name": "MrCull/Kamodo", "max_forks_repo_head_hexsha": "7f8289e5a21c81320f562a30f29e5d3dbe5366dd", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2019-08-16T21:22:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T15:39:18.000Z", "avg_line_length": 48.5535714286, "max_line_length": 4825, "alphanum_fraction": 0.56027032, "converted": true, "num_tokens": 2593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047869292635403, "lm_q2_score": 0.09009300006965833, "lm_q1q2_score": 0.043287766915283354}}
{"text": "# 12. Analysing MD data\n\n### Important note:\n**This part of the tutorial was originally developed with the assumption that the reader had already gone through the Molecular Dynamics (MD) OxCompBio workshop. It makes some assumptions of prior knowledge about molecular dynamics and the trajectories generated from such simulations.**\n\n**We therefore advise readers to first complete the MD tutorial and then return to this section afterwards.**\n\nAs previously discussed, there are many things for which python can be used. One such example is the analysis of Molecular Dynamics (MD) simulations.\n\nThere exist several MD analysis libraries, including (but not limited to):\n- [MDAnalysis](https://www.mdanalysis.org/)\n- [MDTraj](http://mdtraj.org/1.9.3/)\n- [PyTraj](https://amber-md.github.io/pytraj/latest/index.html)\n- [LOOS](http://grossfieldlab.github.io/loos/)\n\nIn this section, we will look at how we can use the MDAnalysis library to process simulation structures and trajectories. We will also look at how we can interface with the [NGLView](https://amber-md.github.io/pytraj/latest/index.html) to visualise our simulations.\n\nThis tutorial will aim to put together all you have learned so far into one final exercise.\n\n## 12.1 The MDAnalysis Universe module\n\nTo work with structures and trajectories in MDAnalysis, you must first create an MDAnalysis `Universe`.\n\nThis is an object that contains all the necessary information about your system, including atomic coordinates, atom types, box vectors (if available), etc...\n\nA `Universe` is a 'class' object, which stores all the information above your system, including;\n- Atomic coordinates (i.e. positions).\n- Atom names.\n- Atom types.\n- Bond information (if available).\n\n.. and so on. Having access to this information is very useful for analysis, such as if you are trying to measure distances or dihedrals. \n\nWhen we load a trajectory (as we will do later in the section), the `Universe` also stores information like the current frame number, etc. \n\nFirst we import the MDAnalysis `Universe` module, we will also import `numpy` for later use:\n\n\n```python\nfrom MDAnalysis import Universe\nimport numpy\n```\n\nYou then load the structure file into a `Universe` instance named `alanine` with:\n\n\n```python\nalanine = Universe('datafiles/ALA.pdb')\n```\n\n**Note 1**: We could have also used `import MDAnalysis`, in which case we would have to use `MDAnalysis.Universe` in place of `Universe`. As previously discussed, the `from ... import ...` syntax allows us to import only a sub-module from a library, rather than the full thing, which can be convenient in various circumstances.\n\n**Note 2**: On loading the PDB file you will get a warning that element information is absent or missing. This is normal and occurs because the input PDB file we use does not have element information for all the atoms (which is expected in a normal PDB file). Therefore MDAnalysis warns us that there are no elements present for us to use.\n\nYou can check the different properties of your universe using MDAnalysis. The general syntax for this is `universename.attributename`; some properties (attributes) are themselves classes (e.g. `alanine.atoms` groups all the information about our atoms) and will have their own attributes. For example, if you want to check the names of the atoms of your structure, you can type:\n\n\n```python\nalanine.atoms.names\n```\n\nThe atom \"name\" is essentially a type of tag that defines the atoms in your system. Quite often this will be used to label similar atoms, for example in the PDB convention alpha carbons are always named \"CA\". When analysing MD simulations, the naming scheme will vary depending on the force field used (see MD tutorial).\n\n### How would you find the values of the Phi and Psi dihedral angles of alanine dipeptide, in degrees or radians?\n\nHint: the Phi dihedral is calculated from atoms CLP, NL, CA, and CRP, and the Psi dihedral is calculated using atoms NR, CRP, CA, and NL.\n\nFor this we can make use of the built-in functions associated with the Universe class (or 'methods'). We can use `select_atoms(selection)` to isolate a group of atoms that match `selection`; the syntax of the selections strings is generally the same as for VMD (which you may have use in the MD tutorial). \n\n`alanine.select_atoms(selection)` will give us an 'atom group' class instance. We can then use this instance's method `dihedral` to turn four atoms into a 'dihedral' instance, and finally using `value()` on this instance will return the (current) value of that dihedral angle.\n\n\n```python\nprint(type(alanine))\nprint(type(alanine.select_atoms('name CLP NL CA CRP')))\nprint(type(alanine.select_atoms('name CLP NL CA CRP').dihedral))\n\nphi = alanine.select_atoms('name CLP NL CA CRP').dihedral.value()\npsi = alanine.select_atoms('name NR CRP CA NL').dihedral.value()\nprint(f'The Phi dihedral is {phi:.2f} in degrees and {numpy.deg2rad(phi):.2f} in radians')\nprint(f'The Phi dihedral is {psi:.2f} in degrees and {numpy.deg2rad(psi):.2f} in radians')\n```\n\n### How would you plot the change in Phi and Psi over a trajectory?\n\nIn order to do this, let's break the process down into small steps.\n\nYou will first need to load the trajectory. The format to do this is:\n\nuniverse_name = Universe(PDBfile, TRJfile)\n\nIn this case we have provided you a trajectory in the `datafiles` folder, the PDB file is called 'ALA.pdb' and the TRJ file is called 'ALA.xtc'. So we can call them as `./datafiles/ALA.pdb` and `./datafiles/ALA.xtc`.\n\n\n```python\n# Exercise 12.1.1: Create a Universe called 'ala_trajectory' using the PDB file 'ALA.pdb' \n# and the trajectory file 'ALA.xtc'\nala_trajectory = Universe('./datafiles/ALA.pdb', './datafiles/ALA.xtc')\n```\n\nNow that you have a Universe with your trajectory, we can access another feature of the Universe: trajectory data.\n\nFirst we should look at what the current trajectory frame number is.\n\nThe frame number is stored under `universename.trajectory.frame` and the total number of frames is found under `universename.trajectory.n_frames`.\n\n\n```python\n# Exercise 12.1.2: Print the current frame number and the total number of frames\nprint(ala_trajectory.trajectory.frame)\nprint(ala_trajectory.trajectory.n_frames)\n```\n\nA `Universe.trajectory` acts kind of like a list storing each frame in a simulation and various information about it, so we can loop through it the same way we did for lists in previous sections. As we go through each frame, the coordinates of each atom, stored in Universe.atoms, will be updated.\n\nWe can therefore quite a quick `for` loop that prints the frame number for each frame in the trajectory.\n\n\n```python\n# When using MDanalysis, we usually refer to each frame as a 'timestep' or 'ts'\n# Here at each loop instance, we allocate the current frame to 'ts'\nfor ts in ala_trajectory.trajectory:\n    # the comma at the end here will stop it printing on a new line every time,\n    # so this doesn't take up too much space\n    print(ts.frame)\n```\n\nNow, use the same logic as Exercise 11.1 to print the phi and psi dihedral angles at each frame:\n\n\n```python\n# Exercise 12.1.3: Print the frame number and at least one of the dihedrals.\n# First create the phi and psi selections\nphi_dihedral = ala_trajectory.select_atoms('name CLP NL CA CRP').dihedral\npsi_dihedral = ala_trajectory.select_atoms('name NR CRP CA NL').dihedral\n\n# We then loop over the the trajectory\nfor ts in ala_trajectory.trajectory:\n    phi = phi_dihedral.value()\n    psi = psi_dihedral.value()\n    print(f\"Current frame: {ts.frame}, phi: {phi}, psi: {psi}\")\n```\n\n\nNow that you can access both the frame number and the phi and psi dihedrals, it's time to plot them.\n\nFirst, we will need to import a plotting library. In this case we import pyplot from matplotlib.\n\nWe then create three empty lists (`frames`, `all_phi`, and `all_psi`) to hold our trajectory data.\n\nThen we fill each of those lists with the relevant values.\n\n\n```python\n# We declare matplotlib inline to make sure it plots properly\n%matplotlib inline\n# We need pyplot from matplotlib to plot the dihedrals\nfrom matplotlib import pyplot\n\n# Create three empty lists\nframes = []\nall_phi = []\nall_psi = []\n\n# iterate through the trajectory\nfor frame in ala_trajectory.trajectory:\n    # calculate phi and psi\n    phi = ala_trajectory.select_atoms('name CLP or name NL or name CA or name CRP').dihedral.value()\n    psi = ala_trajectory.select_atoms('name NR or name CRP or name CA or name NL').dihedral.value()\n    # append frame number, phi, and psi to the lists\n    frames.append(frame.frame)\n    all_phi.append(phi)\n    all_psi.append(psi)\n\n# We then plot our data\npyplot.plot(frames, all_psi)\npyplot.plot(frames, all_phi)\npyplot.show()\n```\n\nAs shown above, you can use the matplotlib.pyplot module to plot `x` and `y` values in the following manner:\n\n```python\npyplot.plot(x_value, y_value)\n```\n\nWe then use `pyplot.show()` to make the plot appear.\n\n**Note:** You can adjust your matplotlib pyplot plot using various different options such as; `pyplot.title()`, `pyplot.xlim()`, `pyplot.ylim()`, `pyplot.xlabel()`, and `pyplot.ylabel()`.\n\nFor example, `pyplot.title()` will add a title.\n\nCheck the `help()` of these functions for more details!\n\n## 12.2 Analysing a protein simulation\n\nIn the MD tutorial you will do some molecular dynamics simulations of a HIV-1 protease protein using gromacs.\nLet's now look at how you could use MDAnalysis, and an associated python visulisation library NGLview, to analyse an MD trajectory of this system.\n\n_Note: depending on whether you have already done the MD tutorial, you may find that you have already done the analysis shown here. You may still find this section useful as we provide a few extra details which explain how the MD trajectory analysis works._\n\n### Visualising the trajectory using nglview\n\nThe nglview library is a python widget for visualising simulation trajectories, achieving a similar task to the VMD program that you may also use in the MD tutorial. One of the interesting advantages of nglview is that it interfaces directly with analysis packages such as MDAnalysis and runs within jupyter notebooks.\n\nLet's see how we can use nglview to visualise an MDAnalysis universe object.\n\nFirst we need to create a universe (let's call it `protein`) from the simulation output files \"pre_md.pdb\" and \"md_cent.xtc\" (which are present in the `datafiles` directory, hence will be passed to Universe as `./datafiles/pre_md.pdb` and `./datafiles/md_cent.xtc`).\n\n_Note 1: We have pre-aligned the trajectory to the first frame for you so as to remove any motions related to translation._\n\n_Note 2: When loading the trajectory you will get a warning that MDAnalysis needs to reload offsets, this is normal in this scenario._\n\n\n```python\n# Exercise 12.2.1: Let's load a universe named protein\nprotein = Universe('./datafiles/pre_md.pdb', './datafiles/md_cent.xtc')\n```\n\nNext let's load nglview and use it's `show_mdanalysis` function to load the MDAnalysis universe\n\n\n```python\nimport nglview\nprotein_view = nglview.show_mdanalysis(protein)\n```\n\nBy default this pre-sets the nglview to show the protein in the cartoon representation. Let's add a few options to colour the protein by secondary structure, show water oxygens and change the background colour\n\n\n```python\n# Let's update the cartoon representation to colour the protein by secondary structure\nprotein_view.update_cartoon(color='sstruc')\n\n# We then add a transparent hyperball representation of the water oxygens \n#(play with the opacity value, see what you get)\nprotein_view.add_hyperball('SOL and not hydrogen', opacity=0.4)\n\n# Let's change the display a little bit\nprotein_view.parameters = dict(camera_type='orthographic', clip_dist=0)\n\n# Set the background colour to black\nprotein_view.background = 'black'\n\n# Call protein_view to visualise the trajectory\nprotein_view\n```\n\nThe nglview output can be controlled in the following way:\n\n- play / pause button: play the trajectory \n- double click window: enter or exit full screen mode \n- left mouse button: rotate system \n- middle mouse wheel: zoom in/out \n- right mouse button: translate system \n\n\nAs you can be seen from the trajectory, the HIV-1 protease structure does indeed move, but by how much? In the next section we will see how we can use MDAnalysis to quantify backbone fluctuations.\n\n### Calculating the root-mean-square deviation\n\nIn order to gain a quantitative description of how the HIV-1 protease moves in our simulation we can calculate the root-mean-square deviation (RMSD) of the protein backbone.\n\nThe RMSD gives us an idea of how 'stable' our protein is when compared to our starting, static, structure. The lower the RMSD is the, more stable we can say our protein is. \n\nThe RMSD as a function of time, $\\rho (t)$, can be defined by the following equation:\n\n\\begin{equation}\n\\\\\n\\rho (t) = \\sqrt{\\frac{1}{N}\\sum^N_{i=1}w_i\\big(\\mathbf{x}_i(t) - \\mathbf{x}^{\\text{ref}}_i\\big)^2}\n\\end{equation}\n\nLuckily MDAnalysis has its own built-in function to calcualte this, we can import it like we did before.\n\n\n```python\nfrom MDAnalysis.analysis.rms import RMSD as rmsd\n```\n\nIn order to calculate the RMSD for every frame in our trajectory we will need:\n\n- A reference structure\n- A universe object\n- A selection of atoms\n\nIn our case the reference structure will be the HIV-1 protease structure in the first frame.\n\nOur universe object will be the 'protein' object we defined above.\n\nFor our selection we will use the backbone atoms.\n\n\n```python\nref = Universe('datafiles/pre_md.pdb', 'datafiles/md_cent.xtc')\n\n# Set the ref trajectory to the first frame\nref.trajectory[0]\n```\n\nDue to the way that GROMACS post processes the trajectory file we need to edit it slightly before running our RMSD.\n\nThis is done by aligning all frames to the reference structure. \n\n\n```python\nfrom MDAnalysis.analysis import align\n\n# Create the MD simulation universe\nprotein = Universe('datafiles/pre_md.pdb', 'datafiles/md_cent.xtc')\n# Call the MDAnalysis align function to align the MD simulation unvierse to the reference (first frame) universe\nalign_strucs = align.AlignTraj(protein, ref, select=\"backbone\", weights=\"mass\", in_memory=True, verbose=True)\n\nR = align_strucs.run()\n```\n\nYou will have noticed that running this function stores it in the variable 'R', we can now access the RMSD values:\n\n\n```python\nrmsd_data = R.rmsd\n```\n\nWe'd like to visualise how the RMSD changes over time and this can be done in the same way you did in Excercise 11.1.5.\n\nTake a look at the 'rmsd_data' variable (it's a numpy array) and try plotting it below.\n\nYou will need to access 'rmsd_data' (a numpy array) in order to plot both the time and the RMSD as a line plot.\n\n\n\n```python\n# Excercise 12.2.2: Plot the RMSD data for the HIV-1 protease system. \n\n# Make sure to add appropriate axis titles.\n# What does the RMSD tell you about the protein?\n# [If you have time] What happens when you calculate the RMSD using more atoms (i.e. not just the backbone)\npyplot.plot(rmsd_data)\npyplot.title(\"RMSD over time\")\npyplot.xlabel(\"Frame number\")\npyplot.ylabel(\"RMSD (Angstroms)\")\npyplot.show()\n```\n\n### Calculating the root-mean-square fluctuation\n\nTo look at how each residue flucuates over it's average postion we can use the closely related measurement of root-mean-square fluctuation (RMSF).\n\nThe RMSF for an atom, $\\rho_i$, is given by:\n\n\\begin{equation}\n\\rho_i = \\sqrt{\\sum^N_{i=1} \\big\\langle(\\mathbf{x}_i - \\langle \\mathbf{x}_i \\rangle )^2 \\big\\rangle }\n\\end{equation}\n\n\n```python\nfrom MDAnalysis.analysis.rms import RMSF as rmsf\n```\n\n\n```python\n# Reset the trajectory to the first frame\nprotein.trajectory[0]\n\n# We will need to select the alpha Carbons only\ncalphas = protein.select_atoms(\"name CA\")\nrmsf_calc = rmsf(calphas, verbose=True).run()\n```\n\n\n```python\n# Excercise 12.2.3: Plot the RMSF data for the HIV-1 protease system. \n    # Tip, in order to plot the resids you will need to access them through the rmsf_calc object\n\n# Make sure to add appropriate axis titles.\n# What parts of the protein have a high RMSF, can you locate these on the protein structure?\n# [If you have time] What happens when you calculate the RMSF using more atoms (i.e. not just the backbone)\npyplot.plot(calphas.resids, rmsf_calc.rmsf)\npyplot.title(\"Per-Residue Alpha Carbon RMSF\")\npyplot.xlabel(\"Residue Number\")\npyplot.ylabel(\"RMSF (Angstrom)\")\npyplot.show()\n```\n", "meta": {"hexsha": "c9f7e5e542ddc623513fa65a1a165646cbd0dd03", "size": 23788, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorials/Python/old-notebooks/12_AnalysingMD/AnalysingMD_solutions.ipynb", "max_stars_repo_name": "AfroditiMariaZaki/OxCompBio", "max_stars_repo_head_hexsha": "15d23de729c1558d80f476bf5a0a1f1cf3311bc6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-12-29T23:59:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T09:45:18.000Z", "max_issues_repo_path": "tutorials/Python/old-notebooks/12_AnalysingMD/AnalysingMD_solutions.ipynb", "max_issues_repo_name": "AfroditiMariaZaki/OxCompBio", "max_issues_repo_head_hexsha": "15d23de729c1558d80f476bf5a0a1f1cf3311bc6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 97, "max_issues_repo_issues_event_min_datetime": "2019-12-11T12:19:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T12:01:50.000Z", "max_forks_repo_path": "tutorials/Python/old-notebooks/12_AnalysingMD/AnalysingMD_solutions.ipynb", "max_forks_repo_name": "AfroditiMariaZaki/OxCompBio", "max_forks_repo_head_hexsha": "15d23de729c1558d80f476bf5a0a1f1cf3311bc6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-12-09T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T11:21:32.000Z", "avg_line_length": 35.7714285714, "max_line_length": 384, "alphanum_fraction": 0.6283840592, "converted": true, "num_tokens": 3999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.10087863151524239, "lm_q1q2_score": 0.04300673884158958}}
{"text": "# 3. Data Pre-processing\n\nData pre-processing techniques generally refer to the addition, deletion, or transformation of training set data. Different models have different sensitivities to the type of predictors in the model; *how* the predictors enter the model is also important.\n\nThe need for data pre-processing is determined by the type of model being used. Some procedures, such as tree-based models, are notably insensitive to the characteristics of the predictor data. Others, like linear regression, are not. In this chapter, a wide array of possible methodologies are discussed. \n\nHow the predictors are encoded, called *feature engineering*, can have a significant impact on model performance. Often the most effective encoding of the data is informed by the modeler's understanding of the problem and thus is not derived from any mathematical techniques.\n\n## 3.1 Case Study: Cell Segmentation in High-Content Screening\n\nCheck if data exists.\n\n\n```\n!ls -l ../datasets/segmentationOriginal/\n```\n\n    total 4016\r\n    -rw-r--r--  1 leigong  staff  2053006 Nov 24 15:58 segmentationOriginal.csv\r\n\n\nThis dataset is from Hill et al. (2007) that consists of 2019 cells. Of these cells, 1300 were judged to be poorly segmented (PS) and 719 were well segmented (WS); 1009 cells were reserved for the training set.\n\n\n```\nimport numpy as np\nimport pandas as pd\n\ncell_segmentation = pd.read_csv(\"../datasets/segmentationOriginal/segmentationOriginal.csv\")\n```\n\n\n```\ncell_segmentation.shape\n```\n\n\n\n\n    (2019, 120)\n\n\n\nA first look at the dataset.\n\n\n```\ncell_segmentation.head(5)\n```\n\n\n\n\n<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Unnamed: 0</th>\n      <th>Cell</th>\n      <th>Case</th>\n      <th>Class</th>\n      <th>AngleCh1</th>\n      <th>AngleStatusCh1</th>\n      <th>AreaCh1</th>\n      <th>AreaStatusCh1</th>\n      <th>AvgIntenCh1</th>\n      <th>AvgIntenCh2</th>\n      <th>...</th>\n      <th>VarIntenCh1</th>\n      <th>VarIntenCh3</th>\n      <th>VarIntenCh4</th>\n      <th>VarIntenStatusCh1</th>\n      <th>VarIntenStatusCh3</th>\n      <th>VarIntenStatusCh4</th>\n      <th>WidthCh1</th>\n      <th>WidthStatusCh1</th>\n      <th>XCentroid</th>\n      <th>YCentroid</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td> 1</td>\n      <td> 207827637</td>\n      <td>  Test</td>\n      <td> PS</td>\n      <td> 143.247705</td>\n      <td> 1</td>\n      <td> 185</td>\n      <td> 0</td>\n      <td> 15.711864</td>\n      <td>   3.954802</td>\n      <td>...</td>\n      <td> 12.474676</td>\n      <td>  7.609035</td>\n      <td>   2.714100</td>\n      <td> 0</td>\n      <td> 2</td>\n      <td> 2</td>\n      <td> 10.642974</td>\n      <td> 2</td>\n      <td>  42</td>\n      <td>  14</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td> 2</td>\n      <td> 207932307</td>\n      <td> Train</td>\n      <td> PS</td>\n      <td> 133.752037</td>\n      <td> 0</td>\n      <td> 819</td>\n      <td> 1</td>\n      <td> 31.923274</td>\n      <td> 205.878517</td>\n      <td>...</td>\n      <td> 18.809225</td>\n      <td> 56.715352</td>\n      <td> 118.388139</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 32.161261</td>\n      <td> 1</td>\n      <td> 215</td>\n      <td> 347</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td> 3</td>\n      <td> 207932463</td>\n      <td> Train</td>\n      <td> WS</td>\n      <td> 106.646387</td>\n      <td> 0</td>\n      <td> 431</td>\n      <td> 0</td>\n      <td> 28.038835</td>\n      <td> 115.315534</td>\n      <td>...</td>\n      <td> 17.295643</td>\n      <td> 37.671053</td>\n      <td>  49.470524</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 21.185525</td>\n      <td> 0</td>\n      <td> 371</td>\n      <td> 252</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td> 4</td>\n      <td> 207932470</td>\n      <td> Train</td>\n      <td> PS</td>\n      <td>  69.150325</td>\n      <td> 0</td>\n      <td> 298</td>\n      <td> 0</td>\n      <td> 19.456140</td>\n      <td> 101.294737</td>\n      <td>...</td>\n      <td> 13.818968</td>\n      <td> 30.005643</td>\n      <td>  24.749537</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 2</td>\n      <td> 13.392830</td>\n      <td> 0</td>\n      <td> 487</td>\n      <td> 295</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td> 5</td>\n      <td> 207932455</td>\n      <td>  Test</td>\n      <td> PS</td>\n      <td>   2.887837</td>\n      <td> 2</td>\n      <td> 285</td>\n      <td> 0</td>\n      <td> 24.275735</td>\n      <td> 111.415441</td>\n      <td>...</td>\n      <td> 15.407972</td>\n      <td> 20.504288</td>\n      <td>  45.450457</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 13.198561</td>\n      <td> 0</td>\n      <td> 283</td>\n      <td> 159</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 120 columns</p>\n</div>\n\n\n\nThis chapter will use the training set samples to demonstrate data pre-processing techniques.\n\n\n```\ncell_segmentation.groupby('Case').count()\n```\n\n\n\n\n<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Unnamed: 0</th>\n      <th>Cell</th>\n      <th>Class</th>\n      <th>AngleCh1</th>\n      <th>AngleStatusCh1</th>\n      <th>AreaCh1</th>\n      <th>AreaStatusCh1</th>\n      <th>AvgIntenCh1</th>\n      <th>AvgIntenCh2</th>\n      <th>AvgIntenCh3</th>\n      <th>...</th>\n      <th>VarIntenCh1</th>\n      <th>VarIntenCh3</th>\n      <th>VarIntenCh4</th>\n      <th>VarIntenStatusCh1</th>\n      <th>VarIntenStatusCh3</th>\n      <th>VarIntenStatusCh4</th>\n      <th>WidthCh1</th>\n      <th>WidthStatusCh1</th>\n      <th>XCentroid</th>\n      <th>YCentroid</th>\n    </tr>\n    <tr>\n      <th>Case</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Test</th>\n      <td> 1010</td>\n      <td> 1010</td>\n      <td> 1010</td>\n      <td> 1010</td>\n      <td> 1010</td>\n      <td> 1010</td>\n      <td> 1010</td>\n      <td> 1010</td>\n      <td> 1010</td>\n      <td> 1010</td>\n      <td>...</td>\n      <td> 1010</td>\n      <td> 1010</td>\n      <td> 1010</td>\n      <td> 1010</td>\n      <td> 1010</td>\n      <td> 1010</td>\n      <td> 1010</td>\n      <td> 1010</td>\n      <td> 1010</td>\n      <td> 1010</td>\n    </tr>\n    <tr>\n      <th>Train</th>\n      <td> 1009</td>\n      <td> 1009</td>\n      <td> 1009</td>\n      <td> 1009</td>\n      <td> 1009</td>\n      <td> 1009</td>\n      <td> 1009</td>\n      <td> 1009</td>\n      <td> 1009</td>\n      <td> 1009</td>\n      <td>...</td>\n      <td> 1009</td>\n      <td> 1009</td>\n      <td> 1009</td>\n      <td> 1009</td>\n      <td> 1009</td>\n      <td> 1009</td>\n      <td> 1009</td>\n      <td> 1009</td>\n      <td> 1009</td>\n      <td> 1009</td>\n    </tr>\n  </tbody>\n</table>\n<p>2 rows \u00d7 119 columns</p>\n</div>\n\n\n\n\n```\n# separate training and test data\ncell_train = cell_segmentation.ix[cell_segmentation['Case'] == 'Train']\ncell_test = cell_segmentation.ix[cell_segmentation['Case'] == 'Test']\n\ncell_train.head(5)\n```\n\n\n\n\n<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Unnamed: 0</th>\n      <th>Cell</th>\n      <th>Case</th>\n      <th>Class</th>\n      <th>AngleCh1</th>\n      <th>AngleStatusCh1</th>\n      <th>AreaCh1</th>\n      <th>AreaStatusCh1</th>\n      <th>AvgIntenCh1</th>\n      <th>AvgIntenCh2</th>\n      <th>...</th>\n      <th>VarIntenCh1</th>\n      <th>VarIntenCh3</th>\n      <th>VarIntenCh4</th>\n      <th>VarIntenStatusCh1</th>\n      <th>VarIntenStatusCh3</th>\n      <th>VarIntenStatusCh4</th>\n      <th>WidthCh1</th>\n      <th>WidthStatusCh1</th>\n      <th>XCentroid</th>\n      <th>YCentroid</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1 </th>\n      <td>  2</td>\n      <td> 207932307</td>\n      <td> Train</td>\n      <td> PS</td>\n      <td> 133.752037</td>\n      <td> 0</td>\n      <td> 819</td>\n      <td> 1</td>\n      <td> 31.923274</td>\n      <td> 205.878517</td>\n      <td>...</td>\n      <td> 18.809225</td>\n      <td> 56.715352</td>\n      <td> 118.388139</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 32.161261</td>\n      <td> 1</td>\n      <td> 215</td>\n      <td> 347</td>\n    </tr>\n    <tr>\n      <th>2 </th>\n      <td>  3</td>\n      <td> 207932463</td>\n      <td> Train</td>\n      <td> WS</td>\n      <td> 106.646387</td>\n      <td> 0</td>\n      <td> 431</td>\n      <td> 0</td>\n      <td> 28.038835</td>\n      <td> 115.315534</td>\n      <td>...</td>\n      <td> 17.295643</td>\n      <td> 37.671053</td>\n      <td>  49.470524</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 21.185525</td>\n      <td> 0</td>\n      <td> 371</td>\n      <td> 252</td>\n    </tr>\n    <tr>\n      <th>3 </th>\n      <td>  4</td>\n      <td> 207932470</td>\n      <td> Train</td>\n      <td> PS</td>\n      <td>  69.150325</td>\n      <td> 0</td>\n      <td> 298</td>\n      <td> 0</td>\n      <td> 19.456140</td>\n      <td> 101.294737</td>\n      <td>...</td>\n      <td> 13.818968</td>\n      <td> 30.005643</td>\n      <td>  24.749537</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 2</td>\n      <td> 13.392830</td>\n      <td> 0</td>\n      <td> 487</td>\n      <td> 295</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td> 12</td>\n      <td> 207932484</td>\n      <td> Train</td>\n      <td> WS</td>\n      <td> 109.416426</td>\n      <td> 0</td>\n      <td> 256</td>\n      <td> 0</td>\n      <td> 18.828571</td>\n      <td> 125.938776</td>\n      <td>...</td>\n      <td> 13.922937</td>\n      <td> 18.643027</td>\n      <td>  40.331747</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 2</td>\n      <td> 17.546861</td>\n      <td> 0</td>\n      <td> 211</td>\n      <td> 495</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td> 15</td>\n      <td> 207932459</td>\n      <td> Train</td>\n      <td> PS</td>\n      <td> 104.278654</td>\n      <td> 0</td>\n      <td> 258</td>\n      <td> 0</td>\n      <td> 17.570850</td>\n      <td> 124.368421</td>\n      <td>...</td>\n      <td> 12.324971</td>\n      <td> 17.747143</td>\n      <td>  41.928533</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 2</td>\n      <td> 17.660339</td>\n      <td> 0</td>\n      <td> 172</td>\n      <td> 207</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 120 columns</p>\n</div>\n\n\n\n## 3.2 Data Transformation for Individual Predictors\n\nTransformations of predictor variables may be needed for several reasons. Some modeling techniques may have strict requirements, such as the predictors having a commom scale. In other cases, creating a good model may be difficult due to specific characteristics of the data (e.g., outliers).\n\n### Centering and Scaling\n\nTo center a predictor variable, the average predictor value is substracted from all the values. As a result of centering, the predictor has a zero mean. Similarly, to scale the data, each value of the predictor variable is divided by its standard deviation. Scaling the data coerce the values to have a common standard deviation of one. These manipulations are generally used to improve the numerical stability of some calculations, such as PLS. The only real downside to these transformation is a loss of interpretability of the individual values.\n\n### Transformations to Resolve Skewness\n\nAn un-skewed distribution is one that is roughly symmetric. A rule of thumb to consider is that skewed data whose ratio of the highest value to the lowest value is greater than 20 have significant skewness. The sample skewness statistic is defined $$\\text{skewness} = {\\sum (x_i - \\bar{x})^3 \\over (n - 1) v^{3/2}},$$ where $$v = {\\sum (x_i - \\bar{x})^2 \\over (n - 1)}.$$ Note that the skewness for a normal distribution is zero.\n\nThe cell segmentation data contain a predictor that measures the standard deviation of the intensity of the pixels in the actin filaments.\n\n\n```\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\n# Some nice default configuration for plots\nplt.rcParams['figure.figsize'] = 10, 7.5\nplt.rcParams['axes.grid'] = True\nplt.gray()\n```\n\n\n    <matplotlib.figure.Figure at 0x10f0c2e10>\n\n\n\n```\nfig, (ax1, ax2, ax3) = plt.subplots(1, 3)\n\nax1.hist(cell_train['VarIntenCh3'].values, bins=20)\nax1.set_xlabel('Natural Units')\nax1.set_ylabel('Count')\n\nax2.hist(np.log(cell_train['VarIntenCh3'].values), bins=20)\nax2.set_xlabel('Log Units')\n\nax3.hist(np.sqrt(cell_train['VarIntenCh3'].values), bins=20)\nax3.set_xlabel('Square Root Units')\n```\n\nThe histogram shows a strong right skewness. The log transformation seems to work well for this dataset. The ratio of the smallest to largest value and the sample skewness statistic all agree with the histogram under natural units.\n\n\n```\nfrom scipy.stats import skew\n\nr = np.max(cell_train['VarIntenCh3'].values)/np.min(cell_train['VarIntenCh3'].values)\nskewness = skew(cell_train['VarIntenCh3'].values)\n\nprint 'Ratio of the smallest to largest value is {0} \\nSample skewness statistic is {1}'.format(r, skewness)\n```\n\n    Ratio of the smallest to largest value is 870.887247203 \n    Sample skewness statistic is 2.39518418124\n\n\nAlternatively, statistical models can be used to empirically identify an appropriate transformation. One of the most famous transformations is the Box-Cox family, i.e.\n\\begin{equation}\nx^* = \\begin{cases} {x^{\\lambda}-1 \\over \\lambda} & \\text{if} \\ \\lambda \\neq 0 \\\\ log(x) & \\text{if} \\ \\lambda = 0 \\end{cases}\n\\end{equation}\nThis family covers the log ($\\lambda = 0$), square ($\\lambda = 2$), square root ($\\lambda = 0.5$), inverse ($\\lambda = -1$), and others in-between. Using the training data, $\\lambda$ can be estimated using maximum likelihood estimation (MLE). This procedure would be applied independently to each predictor data that contain values **greater than 0**.\n\nThe boxcox() in *scipy.stats* finds the estimated lambda and performs the transformation at the same time.\n\n\n```\nfrom scipy.stats import boxcox\n\nprint 'Estimated lambda is {0}'.format(boxcox(cell_train['VarIntenCh3'].values)[1])\n```\n\n    Estimated lambda is 0.121531937325\n\n\nTake another predictor for example.\n\n\n```\nfig, (ax1, ax2) = plt.subplots(1, 2)\n\nax1.hist(cell_train['PerimCh1'].values, bins=20)\nax1.set_xlabel('Natural Units')\nax1.set_ylabel('Count')\n\nax2.hist(boxcox(cell_train['PerimCh1'].values)[0], bins=20)\nax2.set_xlabel('Transformed Data (lambda = {:1.4f})'.format(boxcox(cell_train['PerimCh1'].values)[1]))\n```\n\n## 3.3 Data Transformations for Multiple Predictors\n\nThese transformations act on groups of predictors, typically the entire set under consideration. Of primary importance are methods to resolve outliers and reducce the dimension of the data.\n\n### Transformations to Resolve Outliers\n\nWe generally define outliers as samples that are exceptionally far from the mainstream of the data. Even with a thorough understanding of the data, outliers can be hard to define. However, we can often identify an unusual value by looking at a figure. When one or more samples are suspected to be outliers, the first step is to make sure that the values are scientifically valid and that no data recording errors have occured. Great care should be taken not to hastily remove or change values, especially if the sample size is small. With small sample sizes, apparent outliers might be a result of a skewed distribution where there are not yet enough data to see the skewness. Also, the outlying data may be an indication of a special part of the population under study that is just starting to be sampled. Depending on how the data were collected, a \"cluster\" of valid points that reside outside the mainstream of the data might belong to a different population than the other samples, e.g. *extrapolation* and *applicability domain*. \n\nThere are several predictive models that are resistant to outliers, e.g.\n- Tree based classification models: creat splits of the training set.\n- Support Vector Machines (SVM) for classification: disregard a portion if tge training set that may be far away from the decision boundary.\n\nIf a model is considered to be sensitive to outliers, one data transformation that can minimize the problem is the *spatial sign*. Mathematically, each sample is divided by its squared norm: $$x_{ij}^* = {x_{ij} \\over \\sqrt{\\sum_{j=1}^p x_{ij}^2}}.$$ Since the denominator is intended to measure the squared distance to the center of the predictor's distribution, it is **important** to center and scale the predictor data prior to using this transformation. Note that, unlike centering and scaling, this manipulation of the predictors transform them as a group. Removing predictor variables after applying the spatial sign transformation may be problematic.\n\n\n```\n# toy example\nbeta0 = -2.3 # intercept\nbeta1 = 0.8 # slope\nn = 1000\nx1_true = np.random.normal(4, 2, n)\nx2_true = np.zeros(n)\n\n# generate a random sample\nfor i in xrange(n):\n    x2_true[i] = beta0 + beta1*x1_true[i] + np.random.normal(size = 1)\n    \n# generate outliers\nx1_outliers = np.random.uniform(-4, -3, 8)\nx2_outliers = np.zeros(8)\nfor i in xrange(8):\n    x2_outliers[i] = x1_outliers[i] + np.random.normal(size = 1)\n\nplt.scatter(x1_true, x2_true)\nplt.plot(x1_outliers, x2_outliers, 'ro', markersize=8)\n```\n\n\n```\nfrom sklearn.preprocessing import scale\nx1 = scale(np.concatenate([x1_true, x1_outliers]))\nx2 = scale(np.concatenate([x2_true, x2_outliers]))\nx = np.array(zip(x1, x2))\n\n# spatial sign\ndist = x[:, 0]**2 + x[:, 1]**2\nx1 = x[:, 0]/np.sqrt(dist)\nx2 = x[:, 1]/np.sqrt(dist)\n\nplt.scatter(x1[:-8], x2[:-8])\nplt.plot(x1[-7:], x2[-7:], 'ro', markersize=8)\n```\n\nThe *spatial sign* transformation brings the outliers towards the majority of the data.\n\n### Data Reduction and Feature Extraction\n\nThese methods reduce the data by generating a smaller set of predictors that seek to capture a majority of the information in the original variables. For most data reduction techniques, the new predictors are functions of the original predictors; therefore, all the original predictors are still needed to create the surrogate variables. This class of methods is often called *signal extraction* or *feature extraction* techniques.\n\nPrincipal component analysis (PCA) seeks to find linear combinations of the predictors, known as principal components (PCs), which capture the most possible variance. The first PC is defined as the linear combination of the predictors that captures the most variability of all possible linear combinations. Then, subsequent PCs are derived such that these linear combinations capture the most remaining variability while also being uncorrelated with all previous PCs. Mathematically, \n$$\\text{PC}_j = (a_{j1} \\times \\text{Predictor 1}) + \\cdots + (a_{jP} \\times \\text{Predictor P}).$$\nP is the number of predictors. The coefficients $a_{j1}, \\cdots, a_{jP}$ are called component weights and help us understand which predictors are most important to each PC.\n\nLet us look at an example from the previous dataset.\n\n\n```\ncell_train_subset = cell_train[['Class', 'FiberWidthCh1', 'EntropyIntenCh1']]\n```\n\n\n```\ncolors = ['b', 'r']\nmarkers = ['s', 'o']\nc = ['PS', 'WS']\nfor k, m in enumerate(colors):\n    i = (cell_train_subset['Class'] == c[k])\n    if k == 0:\n        plt.scatter(cell_train_subset['FiberWidthCh1'][i], cell_train_subset['EntropyIntenCh1'][i], \n                    c=m, marker=markers[k], alpha=0.4, s=26, label='PS')\n    else:\n        plt.scatter(cell_train_subset['FiberWidthCh1'][i], cell_train_subset['EntropyIntenCh1'][i], \n                    c=m, marker=markers[k], alpha=0.4, s=26, label='WS')\n\nplt.title('Original Data')\nplt.xlabel('Channel 1 Fiber Width')\nplt.ylabel('Entropy intensity of Channel 1')\nplt.legend(loc='upper right')\nplt.show()\n```\n\nCalculate PCs\n\n\n```\nfrom sklearn.decomposition import PCA\n\npca = PCA()\npca.fit(cell_train_subset[['FiberWidthCh1', 'EntropyIntenCh1']])\nprint 'variance explained by PCs {0}'.format(pca.explained_variance_ratio_)\n```\n\n    variance explained by PCs [ 0.96900659  0.03099341]\n\n\nThe first PC summarizes 97% of the original variability, while the second summarizes 3%. Hence, it is reasonable to use only the first PC for modeling since it accounts for the majority of the information in the data.\n\n\n```\ncell_train_subset_pca = pca.transform(cell_train_subset[['FiberWidthCh1', 'EntropyIntenCh1']])\n\ncolors = ['b', 'r']\nmarkers = ['s', 'o']\nc = ['PS', 'WS']\nfor k, m in enumerate(colors):\n    i = np.where(cell_train_subset['Class'] == c[k])[0]\n    if k == 0:\n        plt.scatter(cell_train_subset_pca[i, 0], cell_train_subset_pca[i, 1], \n                    c=m, marker=markers[k], alpha=0.4, s=26, label='PS')\n    else:\n        plt.scatter(cell_train_subset_pca[i, 0], cell_train_subset_pca[i, 1], \n                    c=m, marker=markers[k], alpha=0.4, s=26, label='WS')\n\nplt.title('Transformed')\nplt.xlabel('Principal Component #1')\nplt.ylabel('Principal Component #2')\nplt.legend(loc='upper right')\nplt.show()\n```\n\nThe primary advantage of PCA is that it creates components that are uncorrelated. PCA preprocessing creates new predictors with desirable characteristics for models that prefer predictors to be uncorrelated.\n\nWhile PCA delivers new predictors with desirable characteristics, it must be used with understanding and care. PCA seeks predictor-set variation without regard to any further understanding of the predictors (i.e. measurement scales or distributions) or to knowledge of the modeling objectives (i.e. response variable). Hence, without proper guidance, PCA can generate components that summarize characteristics of the data that are irrelevant to the underlying structure of the data and also to the ultimate modeling objectives.\n\nPCA was applied to the entire set of segmentation data predictors.\n\n\n```\ncell_train.head(5)\n```\n\n\n\n\n<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Unnamed: 0</th>\n      <th>Cell</th>\n      <th>Case</th>\n      <th>Class</th>\n      <th>AngleCh1</th>\n      <th>AngleStatusCh1</th>\n      <th>AreaCh1</th>\n      <th>AreaStatusCh1</th>\n      <th>AvgIntenCh1</th>\n      <th>AvgIntenCh2</th>\n      <th>...</th>\n      <th>VarIntenCh1</th>\n      <th>VarIntenCh3</th>\n      <th>VarIntenCh4</th>\n      <th>VarIntenStatusCh1</th>\n      <th>VarIntenStatusCh3</th>\n      <th>VarIntenStatusCh4</th>\n      <th>WidthCh1</th>\n      <th>WidthStatusCh1</th>\n      <th>XCentroid</th>\n      <th>YCentroid</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1 </th>\n      <td>  2</td>\n      <td> 207932307</td>\n      <td> Train</td>\n      <td> PS</td>\n      <td> 133.752037</td>\n      <td> 0</td>\n      <td> 819</td>\n      <td> 1</td>\n      <td> 31.923274</td>\n      <td> 205.878517</td>\n      <td>...</td>\n      <td> 18.809225</td>\n      <td> 56.715352</td>\n      <td> 118.388139</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 32.161261</td>\n      <td> 1</td>\n      <td> 215</td>\n      <td> 347</td>\n    </tr>\n    <tr>\n      <th>2 </th>\n      <td>  3</td>\n      <td> 207932463</td>\n      <td> Train</td>\n      <td> WS</td>\n      <td> 106.646387</td>\n      <td> 0</td>\n      <td> 431</td>\n      <td> 0</td>\n      <td> 28.038835</td>\n      <td> 115.315534</td>\n      <td>...</td>\n      <td> 17.295643</td>\n      <td> 37.671053</td>\n      <td>  49.470524</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 21.185525</td>\n      <td> 0</td>\n      <td> 371</td>\n      <td> 252</td>\n    </tr>\n    <tr>\n      <th>3 </th>\n      <td>  4</td>\n      <td> 207932470</td>\n      <td> Train</td>\n      <td> PS</td>\n      <td>  69.150325</td>\n      <td> 0</td>\n      <td> 298</td>\n      <td> 0</td>\n      <td> 19.456140</td>\n      <td> 101.294737</td>\n      <td>...</td>\n      <td> 13.818968</td>\n      <td> 30.005643</td>\n      <td>  24.749537</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 2</td>\n      <td> 13.392830</td>\n      <td> 0</td>\n      <td> 487</td>\n      <td> 295</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td> 12</td>\n      <td> 207932484</td>\n      <td> Train</td>\n      <td> WS</td>\n      <td> 109.416426</td>\n      <td> 0</td>\n      <td> 256</td>\n      <td> 0</td>\n      <td> 18.828571</td>\n      <td> 125.938776</td>\n      <td>...</td>\n      <td> 13.922937</td>\n      <td> 18.643027</td>\n      <td>  40.331747</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 2</td>\n      <td> 17.546861</td>\n      <td> 0</td>\n      <td> 211</td>\n      <td> 495</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td> 15</td>\n      <td> 207932459</td>\n      <td> Train</td>\n      <td> PS</td>\n      <td> 104.278654</td>\n      <td> 0</td>\n      <td> 258</td>\n      <td> 0</td>\n      <td> 17.570850</td>\n      <td> 124.368421</td>\n      <td>...</td>\n      <td> 12.324971</td>\n      <td> 17.747143</td>\n      <td>  41.928533</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 2</td>\n      <td> 17.660339</td>\n      <td> 0</td>\n      <td> 172</td>\n      <td> 207</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 120 columns</p>\n</div>\n\n\n\n\n```\ncell_train_feature = cell_train.iloc[:, 4:]\ncell_train_feature.head(5)\n```\n\n\n\n\n<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>AngleCh1</th>\n      <th>AngleStatusCh1</th>\n      <th>AreaCh1</th>\n      <th>AreaStatusCh1</th>\n      <th>AvgIntenCh1</th>\n      <th>AvgIntenCh2</th>\n      <th>AvgIntenCh3</th>\n      <th>AvgIntenCh4</th>\n      <th>AvgIntenStatusCh1</th>\n      <th>AvgIntenStatusCh2</th>\n      <th>...</th>\n      <th>VarIntenCh1</th>\n      <th>VarIntenCh3</th>\n      <th>VarIntenCh4</th>\n      <th>VarIntenStatusCh1</th>\n      <th>VarIntenStatusCh3</th>\n      <th>VarIntenStatusCh4</th>\n      <th>WidthCh1</th>\n      <th>WidthStatusCh1</th>\n      <th>XCentroid</th>\n      <th>YCentroid</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1 </th>\n      <td> 133.752037</td>\n      <td> 0</td>\n      <td> 819</td>\n      <td> 1</td>\n      <td> 31.923274</td>\n      <td> 205.878517</td>\n      <td> 69.916880</td>\n      <td> 164.153453</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td>...</td>\n      <td> 18.809225</td>\n      <td> 56.715352</td>\n      <td> 118.388139</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 32.161261</td>\n      <td> 1</td>\n      <td> 215</td>\n      <td> 347</td>\n    </tr>\n    <tr>\n      <th>2 </th>\n      <td> 106.646387</td>\n      <td> 0</td>\n      <td> 431</td>\n      <td> 0</td>\n      <td> 28.038835</td>\n      <td> 115.315534</td>\n      <td> 63.941748</td>\n      <td> 106.696602</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td>...</td>\n      <td> 17.295643</td>\n      <td> 37.671053</td>\n      <td>  49.470524</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 21.185525</td>\n      <td> 0</td>\n      <td> 371</td>\n      <td> 252</td>\n    </tr>\n    <tr>\n      <th>3 </th>\n      <td>  69.150325</td>\n      <td> 0</td>\n      <td> 298</td>\n      <td> 0</td>\n      <td> 19.456140</td>\n      <td> 101.294737</td>\n      <td> 28.217544</td>\n      <td>  31.028070</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td>...</td>\n      <td> 13.818968</td>\n      <td> 30.005643</td>\n      <td>  24.749537</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 2</td>\n      <td> 13.392830</td>\n      <td> 0</td>\n      <td> 487</td>\n      <td> 295</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td> 109.416426</td>\n      <td> 0</td>\n      <td> 256</td>\n      <td> 0</td>\n      <td> 18.828571</td>\n      <td> 125.938776</td>\n      <td> 13.600000</td>\n      <td>  46.800000</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td>...</td>\n      <td> 13.922937</td>\n      <td> 18.643027</td>\n      <td>  40.331747</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 2</td>\n      <td> 17.546861</td>\n      <td> 0</td>\n      <td> 211</td>\n      <td> 495</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td> 104.278654</td>\n      <td> 0</td>\n      <td> 258</td>\n      <td> 0</td>\n      <td> 17.570850</td>\n      <td> 124.368421</td>\n      <td> 22.461538</td>\n      <td>  71.206478</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td>...</td>\n      <td> 12.324971</td>\n      <td> 17.747143</td>\n      <td>  41.928533</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 2</td>\n      <td> 17.660339</td>\n      <td> 0</td>\n      <td> 172</td>\n      <td> 207</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 116 columns</p>\n</div>\n\n\n\nBecause PCA seeks linear combinations of predictors that maximize variability, it will naturally first be drawn to summarizing predictors that have more variation. If the original predictors are on measurement scales that differ in orders of magnitude or have skewed distributions, PCA will be focusing its efforts on identifying the data structure based on measurement scales and distributional difference rather than based on the important relationships within the data for the current problem. Hence, it is best to first transform skewed predictors and then center and scale the predictors prior to performing PCA.\n\n\n```\n# Box-Cox transformation on positive predictors\n# separate positive and non-positive predictors\npos_indx = np.where(cell_train_feature.apply(lambda x: np.all(x > 0)))[0]\ncell_train_feature_pos = cell_train_feature.iloc[:, pos_indx]\nprint \"# of positive features is {0}\".format(pos_indx.shape[0])\ncell_train_feature_nonpos = cell_train_feature.drop(cell_train_feature.columns[pos_indx], axis=1, inplace=False)\nprint \"# of npn-positive features is {0}\".format(cell_train_feature.shape[1] - pos_indx.shape[0])\n\ncell_train_feature_pos_tr = cell_train_feature_pos.apply(lambda x: boxcox(x)[0])\n\ncell_train_feature_tr = np.c_[cell_train_feature_pos_tr, cell_train_feature_nonpos]\nprint \"The shape before/after transformation is {0} and {1}\".format(cell_train_feature.shape, cell_train_feature_tr.shape)\n```\n\n    # of positive features is 47\n    # of npn-positive features is 69\n    The shape before/after transformation is (1009, 116) and (1009, 116)\n\n\n\n```\n# scale and center predictors\nfrom sklearn.preprocessing import scale\n\ncell_train_feature_tr = scale(cell_train_feature_tr, with_mean=True, with_std=True)\n```\n\nThe second caveat of PCA is that it does not consider the modeling obejective or response variable when summarizing variability -- it is an *unsupervised technique*. If the predictive relationship between the predictors and response is not connected to the predictors' variability, then the derived PCs will not provide a suitable relationship with the response. In this case, a *supervised technique*, like PLS will derive components while simultaneously considering the corresponding response.\n\nTo decide how many components to retain after PCA, a heuristic approach is to create a scree plot, which contains the ordered component number (x-axis) and the ammount of summarized variability (y-axis). Generally, the component number prior to the tapering off of variation is the maximal component that is retained. In an automated model building process, the optimal number of components can be determined by cross-validation.\n\n\n```\n# conduct PCA to transformed predictors\nfrom sklearn.decomposition import PCA\n\npca = PCA()\npca.fit(cell_train_feature_tr)\n\n# generate scree plot\nplt.plot(pca.explained_variance_ratio_)\nplt.xlabel('Percent of Total Variance')\nplt.ylabel('Component')\n```\n\n\n```\nprint \"The first four components account for {0} of the total variance\".format(pca.explained_variance_ratio_[:4])\nprint \"All together they account for {0} of the total variance\".format(np.sum(pca.explained_variance_ratio_[:4]))\n```\n\n    The first four components account for [ 0.14015262  0.12569721  0.09394676  0.06393814] of the total variance\n    All together they account for 0.42373472472 of the total variance\n\n\nVisually examining the principal components is a critical step for assessing data quality and gaining intuition for the problem. To do this, the first few PCs can be plotted against each other and the plot symbols can be colored by the relevant characteristics, such as the class labels. If PCA has captured a sufficient amount of the information in the data, this type of plot can demonstrate clusters of samples or outliers that may prompt a closer examination of the individual data points. Note that the scale of the components tend to become smaller as they account for less and less variation in the data. If axes are displayed on separate scales, there is the potential to over-interpret any patterns that might be seen for components that account for small amounts of variation.\n\n\n```\n# look at the first 3 PCs\npca = PCA(n_components=3)\ncell_train_feature_pca = pca.fit_transform(cell_train_feature_tr)\n```\n\n\n```\ncolors = ['b', 'r']\nmarkers = ['s', 'o']\nc = ['PS', 'WS']\n\nfig, axarr = plt.subplots(3, 3, sharex=True, sharey=True)\n\n# PC1 vs PC3\nfor k, m in enumerate(colors):\n    i = np.where(cell_train['Class'] == c[k])[0]\n    if k == 0:\n        line1= axarr[0,0].scatter(cell_train_feature_pca[i, 0], cell_train_feature_pca[i, 2], \n                    c=m, marker=markers[k], alpha=0.4, s=26, label='PS')\n    else:\n        line2= axarr[0,0].scatter(cell_train_feature_pca[i, 0], cell_train_feature_pca[i, 2], \n                    c=m, marker=markers[k], alpha=0.4, s=26, label='WS')\n\n# PC2 vs PC3\nfor k, m in enumerate(colors):\n    i = np.where(cell_train['Class'] == c[k])[0]\n    if k == 0:\n        axarr[0,1].scatter(cell_train_feature_pca[i, 1], cell_train_feature_pca[i, 2], \n                    c=m, marker=markers[k], alpha=0.4, s=26, label='PS')\n    else:\n        axarr[0,1].scatter(cell_train_feature_pca[i, 1], cell_train_feature_pca[i, 2], \n                    c=m, marker=markers[k], alpha=0.4, s=26, label='WS')\n\n# PC1 vs PC2\nfor k, m in enumerate(colors):\n    i = np.where(cell_train['Class'] == c[k])[0]\n    if k == 0:\n        axarr[1,0].scatter(cell_train_feature_pca[i, 0], cell_train_feature_pca[i, 1], \n                    c=m, marker=markers[k], alpha=0.4, s=26, label='PS')\n    else:\n        axarr[1,0].scatter(cell_train_feature_pca[i, 0], cell_train_feature_pca[i, 1], \n                    c=m, marker=markers[k], alpha=0.4, s=26, label='WS')\n\naxarr[2,0].text(0.5, -1.0, 'PC1', ha='center', va='center', fontsize=24)      \naxarr[1,1].text(0.5, -1.0, 'PC2', ha='center', va='center', fontsize=24)      \naxarr[0,2].text(0.5, -1.0, 'PC3', ha='center', va='center', fontsize=24)\nfig.legend([line1, line2], ('PS', 'WS'), loc='upper center', ncol=2, frameon=False)\nfig.subplots_adjust(hspace=0.12, wspace=0.1)\nfig.text(0.5, 0.06, 'Scatter Plot Matrix', ha='center', va='center', fontsize=18)\n```\n\nSince the percentages of variation explained are not large for the first three components, it is important not to over-interpret the resulting image. From this plot, there appears to be some separation between the classes when plotting the first and second components. However, the distribution of the well-segmented cells is roughly contained within the distribution of the poorly identified cells. One conclusion is that the cell types are not easily separated.\n\nAnother exploratory use of PCA is characterizing which predictors are associated with each component. Recall that each component is a linear combination of the predictors and the coefficient for each predictor is called the loading. Loadings close to zero indicate that the predictor variable did not contribute much to that component.\n\n\n```\n# loadings\npca.components_.shape\n```\n\n\n\n\n    (3, 116)\n\n\n\n## 3.4 Dealing with Missing Values\n\nIn many cases, some predictors have no values for a given sample. It is important to understand *why* the values are missing. First and foremost, it is important to know if the pattern of missing data is related to the outcome. This is called *informative missingness* since the missing data pattern is instructional on its own. Informative missingness can induce significant bias in the model.\n\nMissing data should not be confused with *censored* data where the exact value is missing but something is known about its value. When building traditional statistical models focused on interpretation or inference, the censoring is usually taken in to account in a formal manner by making assumptions about the censoring mechanism. For predictive models, it is more common to treat these data as simple missing data or use the censored value as the observed value.\n\nMissing values are more often related to predictive variables than the sample. Because of this, amount of missing data may be concentrated in a subset of predictors rather than occuring randomly across all the predictors. In some cases, the percentage of missing data is substantial enough to remove this predictor from subsequent modeling activities.\n\nThere are cases where the missing values might be concentrated in specific samples. For large datasets, removal of samples based on missing values is not a problem, assuming that the missingness is not informative. In smaller datasets, there is a steep price in removing samples; some of alternative approaches described below may be more appropriate.\n\nIf we do not remove the missing data, there are two general approaches. First, a few predictive models, especially tree-based techniques, can specifically account for missing data. Alternatively, missing data can be imputed. In this case, we can use information in the training set predictors to, in essence, estimate the values of other predictors.\n\nImputation is just another layer of modeling where we try to estimate values of the predictor variables based on other predictor variables. The most relevant scheme for accomplishing this is to use the training set to built an imputation model for each predictor in the daa set. Prior to model training or the prediction of new samples, missing values are filled in using imputation. Note that this extra layer of models adds uncertainty. If we are using resampling to select tuning parameter values or to estimate performance, the imputation should be incorporated within the resampling. This will increase the computational time for building models, but it will also provide honest estimates of model performance.\n\nIf the number of predictors affected by missing values is small, an exploratory analysis of the relationships between the preditors is a good idea. For example, visulization or methods like PCA can be used to determine if there are strong relationships between the predictors. If a variable with missing values is highly correlated with another predictor that has few missing values, a focused model can often be effective for imputation.\n\nOne popular technique for imputation is a $K$-nearest neighbor model. A new sample is imputed by finding the samples in the training set \"closest\" to it and averages these nearby points to fill in the value. One advantage of this approach is that the imputed data are confined to be within the range of the training set values. One disadvantage is that the entire training set is required every time a missing value needs to be imputed. Also, the number of neighbors is a tuning parameter, as is the method for determining \"closeness\" of two points. However, Troyanskaya et al. (2001) found the nearest neighbor approach to be fairly robust to the tuning parameters, as well as the amount of missing data.\n\n\n```\n# randomly sample 50 test set\nimport random\ncell_test_subset = cell_test.iloc[np.sort(random.sample(range(cell_test.shape[0]), 50))]\n\n# separate features\ncell_test_subset_f = cell_test_subset.iloc[:, 4:].drop('VarIntenCh3', 1)\ncell_test_subset_v = cell_test_subset.iloc[:, 4:]['VarIntenCh3']\ncell_train_f = cell_train_feature.drop('VarIntenCh3', 1)\ncell_train_v = cell_train_feature['VarIntenCh3']\n```\n\n\n```\n# scale and center before imputation\nfrom sklearn.preprocessing import StandardScaler\n\n# standardize based on training set\nsc_f = StandardScaler()\ncell_train_f_sc = sc_f.fit_transform(cell_train_f)\ncell_test_subset_f_sc = sc_f.transform(cell_test_subset_f)\n\nsc_v = StandardScaler()\ncell_train_v_sc = sc_v.fit_transform(cell_train_v)\ncell_test_subset_v_sc = sc_v.transform(cell_test_subset_v)\n```\n\n\n```\n# use 5-nearest neighbor\nfrom sklearn.neighbors import NearestNeighbors\n\nnbrs = NearestNeighbors(n_neighbors = 5)\nnbrs.fit(cell_train_f_sc) # based on training set\ndistance, indices = nbrs.kneighbors(cell_test_subset_f_sc) # neighbors for test set\n\n# imputation\ncell_test_subset_v_pred_knn = np.empty(50)\nfor idx, i in enumerate(indices):\n    cell_test_subset_v_pred_knn[idx] = np.mean(cell_train_v_sc[i[1:]])\n```\n\nFind the predictor with highest correlation.\n\n\n```\nfrom scipy.stats.stats import pearsonr\n\nprint \"corr('VarIntenCh3', 'DiffIntenDensityCh3') is {0}\".format(pearsonr(cell_train_v, cell_train_f['DiffIntenDensityCh3'])[0])\n```\n\n    corr('VarIntenCh3', 'DiffIntenDensityCh3') is 0.894871504785\n\n\n\n```\n# use linear model\nfrom sklearn.linear_model import LinearRegression\n\nlm = LinearRegression()\nlm.fit(cell_train_f_sc[:, cell_train_f.columns.get_loc('DiffIntenDensityCh3')][:, np.newaxis],\n       cell_train_v_sc[:, np.newaxis]) # find the predictor with highest correlation\ncell_test_subset_v_pred_lm = \\\nlm.predict(cell_test_subset_f_sc[:, cell_train_f.columns.get_loc('DiffIntenDensityCh3')][:, np.newaxis])\n```\n\nCorrelation between the real and imputed values\n\n\n```\nprint \"kNN: {0}\".format(pearsonr(cell_test_subset_v_sc, cell_test_subset_v_pred_knn)[0])\nprint \"Linear Model: {0}\".format(pearsonr(cell_test_subset_v_sc[:, np.newaxis], cell_test_subset_v_pred_lm)[0][0])\n```\n\n    kNN: 0.869781133553\n    Linear Model: 0.858789107105\n\n\nNote that the better performance of linear model is because of the high correlation (0.895) between these two predictors. kNN is generally more robust since it takes all predictors into consideration.\n\n\n```\nfig, (ax1, ax2) = plt.subplots(1, 2)\n\nax1.scatter(cell_test_subset_v_sc, cell_test_subset_v_pred_knn)\nax1.set(xlim=(-1.5, 3), ylim=(-1.5, 3))\nax1.plot(ax1.get_xlim(), ax1.get_ylim(), ls=\"--\", c=\".3\")\nax1.set_title('5NN')\n\nax2.scatter(cell_test_subset_v_sc, cell_test_subset_v_pred_lm)\nax2.set(xlim=(-1.5, 3), ylim=(-1.5, 3))\nax2.plot(ax2.get_xlim(), ax2.get_ylim(), ls=\"--\", c=\".3\")\nax2.set_title('Linear Model')\n\nfig.text(0.5, 0.04, 'Original Value (centered and scaled)', ha='center', va='center')\nfig.text(0.06, 0.5, 'Imputed', ha='center', va='center', rotation='vertical')\n```\n\n## 3.5 Removing Predictors\n\nThere are potential advantages to removing predictors prior to modeling. First, fewer predictors means decreased computational time and complexity. Second, if two predictors are highly correlated, this implies that they are measuring the same underlying information. Removing one should not compromise the performance of the model and might lead to a more parsimonious and interpretable model. Third, some models can be crippled by predictors with degenerate distributions, e.g. near-zero variance predictors. In these cases, there can be a significant improvement in model performance and/or stability without the problematic variables.\n\nA rule of thumb for detecting near-zero variance predictors:\n- The fraction of unique values over the sample size is low (say 10%)\n- The ratio of the frequency of the most prevalent value to the frequency of the second most prevalent value is large (say around 20)\n\nIf both of these criteria are true and the model in question is susceptible to this type of predictor, it may be advantageous to remove the variable from the model.\n\n### Between-Predictor Correlations\n\n*Collinearity* is the technical term for the situation where a pair of predictor variables have a substantial correlation with each other. It is also possible to have relationships between multiple predictors at once (called *multicollinearity*).\n\nA direct visualization of the correlation matrix from the training set.\n\n\n```\n# calculate the correlation matrix\ncorr_dataframe = cell_train_feature.corr()\n\n# compute hierarchical cluster on both rows and columns for correlation matrix and plot heatmap \ndef corr_heatmap(corr_dataframe):\n    import scipy.cluster.hierarchy as sch\n    \n    corr_matrix = np.array(corr_dataframe)\n    col_names = corr_dataframe.columns\n    \n    Y = sch.linkage(corr_matrix, 'single', 'correlation')\n    Z = sch.dendrogram(Y, color_threshold=0, no_plot=True)['leaves']\n    corr_matrix = corr_matrix[Z, :]\n    corr_matrix = corr_matrix[:, Z]\n    col_names = col_names[Z]\n    im = plt.imshow(corr_matrix, interpolation='nearest', aspect='auto', cmap='bwr')\n    plt.colorbar()\n    plt.xticks(range(corr_matrix.shape[0]), col_names, rotation='vertical', fontsize=4)\n    plt.yticks(range(corr_matrix.shape[0]), col_names[::-1], fontsize=4)\n    \n# plot\ncorr_heatmap(corr_dataframe)\n```\n\nNote that the predictor variables have been grouped using a clustering technique so that collinear groups of predictors are adjacent to one another.\n\nWhen the data set consists of too many predictors to examine visually, techniques such as PCA can be used to characterize the magnitude of the problem. For example, if the first principal component accounts for a large percentage of the variance, this implies that there is at least one group of predictors that represent the same information. The PCA loadings can be used to understand which predictors are associated with each component to tease out this relationship.\n\nIn general, there are good reasons to avoid data with highly correlated predictors. First, redundant predictors frequently add more complexity to the model than information they provide to the model. In situations where obtaining the predictor data is costly, fewer variables is obviously better. Using highly correlated predictors in techniques like linear regression can result in highly unstable models, numerical values, and degraded predictive performances.\n\nClassical regression analysis has several tools to diagnose multicollinearity for linear regression. A statistic called the variance inflation factor (VIF) can be used to identify predictors that are impacted. A common rule of thumb is that if VIF > 5, then multicollinearity is high. Note that this method is developed for linear models, it requires more samples than predictor variables and it does not determine which should be removed to resolve the problem\n\nA more heuristic approach is to remove the minimum number of predictors to ensure that all pairwise correlation are below a certain threshold. The algorithm is as follows:\n- Calculate the correlation matrix of the predictors.\n- Determine the two predictors associated with the largest absolute pairwise correlation (A and B).\n- Determine the average absolute correlation between A and the other variables. Do the same for predictor B.\n- If A has a larger average correlation, remove it; otherwise, remove predictor B.\n- Repeat Steps 2-4 until no absolute correlations are above the threshold.\n\nSuppose we wanted to use a model that is particularly sensitive to between predictor correlations, we might apply a threshold of 0.75.\n\nAs previously mentioned, feature extraction methods (e.g., principal components) are another technique for mitigating the effect of strong correlations between predictors. However, these techniques make the connection between the predictors and the outcome more complex. Additionally, since signal extraction methods are usually unsupervised, there is no guarantee that the resulting surrogate preditors have any relationship with the outcome.\n\n## 3.6 Adding Predictors\n\nWhen a predictor is categorical, it is common to decompose the predictor into a set of more specific variables.\n\nLook at the following example for the credit scoring data.\n\n\n```\n!ls -l ../datasets/GermanCredit/\n```\n\n    total 480\r\n    -rw-r--r--  1 leigong  staff  244776 Nov 24 15:58 GermanCredit.csv\r\n\n\n\n```\ncredit_data = pd.read_csv(\"../datasets/GermanCredit/GermanCredit.csv\")\ncredit_data.head(5)\n```\n\n\n\n\n<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Unnamed: 0</th>\n      <th>Duration</th>\n      <th>Amount</th>\n      <th>InstallmentRatePercentage</th>\n      <th>ResidenceDuration</th>\n      <th>Age</th>\n      <th>NumberExistingCredits</th>\n      <th>NumberPeopleMaintenance</th>\n      <th>Telephone</th>\n      <th>ForeignWorker</th>\n      <th>...</th>\n      <th>OtherInstallmentPlans.Bank</th>\n      <th>OtherInstallmentPlans.Stores</th>\n      <th>OtherInstallmentPlans.None</th>\n      <th>Housing.Rent</th>\n      <th>Housing.Own</th>\n      <th>Housing.ForFree</th>\n      <th>Job.UnemployedUnskilled</th>\n      <th>Job.UnskilledResident</th>\n      <th>Job.SkilledEmployee</th>\n      <th>Job.Management.SelfEmp.HighlyQualified</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td> 1</td>\n      <td>  6</td>\n      <td> 1169</td>\n      <td> 4</td>\n      <td> 4</td>\n      <td> 67</td>\n      <td> 2</td>\n      <td> 1</td>\n      <td> 0</td>\n      <td> 1</td>\n      <td>...</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 1</td>\n      <td> 0</td>\n      <td> 1</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 1</td>\n      <td> 0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td> 2</td>\n      <td> 48</td>\n      <td> 5951</td>\n      <td> 2</td>\n      <td> 2</td>\n      <td> 22</td>\n      <td> 1</td>\n      <td> 1</td>\n      <td> 1</td>\n      <td> 1</td>\n      <td>...</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 1</td>\n      <td> 0</td>\n      <td> 1</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 1</td>\n      <td> 0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td> 3</td>\n      <td> 12</td>\n      <td> 2096</td>\n      <td> 2</td>\n      <td> 3</td>\n      <td> 49</td>\n      <td> 1</td>\n      <td> 2</td>\n      <td> 1</td>\n      <td> 1</td>\n      <td>...</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 1</td>\n      <td> 0</td>\n      <td> 1</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 1</td>\n      <td> 0</td>\n      <td> 0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td> 4</td>\n      <td> 42</td>\n      <td> 7882</td>\n      <td> 2</td>\n      <td> 4</td>\n      <td> 45</td>\n      <td> 1</td>\n      <td> 2</td>\n      <td> 1</td>\n      <td> 1</td>\n      <td>...</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 1</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 1</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 1</td>\n      <td> 0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td> 5</td>\n      <td> 24</td>\n      <td> 4870</td>\n      <td> 3</td>\n      <td> 4</td>\n      <td> 53</td>\n      <td> 2</td>\n      <td> 2</td>\n      <td> 1</td>\n      <td> 1</td>\n      <td>...</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 1</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 1</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 1</td>\n      <td> 0</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 63 columns</p>\n</div>\n\n\n\n\n```\ncredit_data.shape\n```\n\n\n\n\n    (1000, 63)\n\n\n\nThe predictor based on how much money was in the applicant's saving account is categorical coded into dummy variables.\n\n\n```\ncredit_data_saving = credit_data[['SavingsAccountBonds.lt.100', 'SavingsAccountBonds.100.to.500', \n                                  'SavingsAccountBonds.500.to.1000', 'SavingsAccountBonds.gt.1000', \n                                  'SavingsAccountBonds.Unknown']]\ncredit_data_saving.head(10)\n```\n\n\n\n\n<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>SavingsAccountBonds.lt.100</th>\n      <th>SavingsAccountBonds.100.to.500</th>\n      <th>SavingsAccountBonds.500.to.1000</th>\n      <th>SavingsAccountBonds.gt.1000</th>\n      <th>SavingsAccountBonds.Unknown</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td> 1</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td> 1</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td> 1</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td> 1</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 1</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 1</td>\n      <td> 0</td>\n      <td> 0</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td> 1</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 1</td>\n      <td> 0</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td> 1</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n      <td> 0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\ncredit_data_saving.apply(np.sum)\n```\n\n\n\n\n    SavingsAccountBonds.lt.100         603\n    SavingsAccountBonds.100.to.500     103\n    SavingsAccountBonds.500.to.1000     63\n    SavingsAccountBonds.gt.1000         48\n    SavingsAccountBonds.Unknown        183\n    dtype: float64\n\n\n\n| Value    |  n   | <100 | 100-500 | 500-1000 | >1000 | Unknown |                                           \n|:---------|:----:|:----:|:-------:|:--------:|:-----:|:-------:|\n| < 100    | 603  |   1  |   0     |    0     |   0   |    0    |\n| 100-500  | 100  |   0  |   1     |    0     |   0   |    0    |\n| 500-1000 |  63  |   0  |   0     |    1     |   0   |    0    |\n| >1000    |  48  |   0  |   0     |    0     |   1   |    0    |\n| Unknown  | 183  |   0  |   0     |    0     |   0   |    1    |\n\n\nUsually, each category gets its own dummy variable that is a zero/one indicator for that group. Only four dummy variables are needed here, the fifth can be inferred. However, the decision to include all of the dummy variables can depend on the choice of the model. Models that include an intercept term, such as simple linear model, would have numerical issues if each dummy variable was included in the model. The reason is that, for each sample, these variables all add up to one and this would provide the same information as the intercept. If the model is insensitive to this type of issue, using the complete set of dummy variables would help improve interpretation of the model.\n\nMany of the advanced models automatically generate highly complex, nonlinear relationships between the predictors and the outcome. More simplistic models do not unless the user manually specifices which predictors should be nonlinear and in what way. Another technique to augment the prediction data for classification model is through the \"*class centroids*\", which are the centers of the predictor data for each class. For each predictor, the distance to each class centroid can be calculated and these distances can be added to the model.\n\n## 3.7 Binning Predictors (to avoid)\n\nThere are many issues with the manual binning of continuous data. First, there can be a significant loss of performance in the model. Second, there is a loss of precision in the predictions when the predictors are categorized. Unfortunately, the predictive models that are most powerful are usually the least interpretable. The bottom line is that the perceived improvement in interpretability gained by manual categorization is usually offset by a significant loss in performance.\n\nNote that the argument here is related to the *manual* categorization of predictors prior to model building. There are several models, such as classification/regression trees and multivariate adaptive regression splines, that estimate cut points in the process of model building. The difference between these methodologies and manual binning is that the models ues all the predictors to derive bins based on a single objective (such as maximizing accuracy). They evaluate many variable simultaneously and are usually based on statistically sound methodologies.\n", "meta": {"hexsha": "2544f46085cbea96f86aa033c29acfc20a58c282", "size": 828956, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Chapter 3.ipynb", "max_stars_repo_name": "keshavramaswamy/Applied-Predictive-Modeling-with-Python", "max_stars_repo_head_hexsha": "21717311fd7fe07d0d0cc1c8471bfa890d0e9c58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 243, "max_stars_repo_stars_event_min_datetime": "2015-03-12T13:06:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T08:20:54.000Z", "max_issues_repo_path": "notebooks/Chapter 3.ipynb", "max_issues_repo_name": "to-be-snail/Applied-Predictive-Modeling-with-Python", "max_issues_repo_head_hexsha": "21717311fd7fe07d0d0cc1c8471bfa890d0e9c58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2015-12-02T20:25:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-08T18:32:16.000Z", "max_forks_repo_path": "notebooks/Chapter 3.ipynb", "max_forks_repo_name": "to-be-snail/Applied-Predictive-Modeling-with-Python", "max_forks_repo_head_hexsha": "21717311fd7fe07d0d0cc1c8471bfa890d0e9c58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 133, "max_forks_repo_forks_event_min_datetime": "2015-04-09T21:06:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T03:32:53.000Z", "avg_line_length": 295.6333808845, "max_line_length": 290601, "alphanum_fraction": 0.8866863862, "converted": true, "num_tokens": 17311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.09009299396195183, "lm_q1q2_score": 0.042936487625668866}}
{"text": "--- \nProject for the course in Microeconometrics | Summer 2020, M.Sc. Economics, Bonn University | Julia Wilhelm\n\n# Replication of F. Barrera-Osorio, M. Bertrand, L. L. Linden, F. Perez-Calle  (2011) <a class=\"tocSkip\">   \n---\n\nThis notebook contains my replication of the results from the following paper:\n\n> Barrera-Osorio, Felipe, Marianne Bertrand, Leigh L. Linden, and Francisco Perez-Calle (2011). \"Improving the Design of Conditional Transfer Programs: Evidence from a Randomized Education Experiment in Colombia.\" American Economic Journal: Applied Economics, 3 (2): 167-95. \n\nThe original paper, as well as the data and code provided by the authors can be accessed [here](https://www.aeaweb.org/articles?id=10.1257/app.3.2.167).\n\n<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#1.-Introduction\" data-toc-modified-id=\"1.-Introduction-1\">1. Introduction</a></span></li><li><span><a href=\"#2.-Identification\" data-toc-modified-id=\"2.-Identification-2\">2. Identification</a></span></li><li><span><a href=\"#3.-Empirical-Strategy\" data-toc-modified-id=\"3.-Empirical-Strategy-3\">3. Empirical Strategy</a></span></li><li><span><a href=\"#4.-Replication-of-Barrera-Osorio-et-al.-(2011)\" data-toc-modified-id=\"4.-Replication-of-Barrera-Osorio-et-al.-(2011)-4\">4. Replication of Barrera-Osorio et al. (2011)</a></span><ul class=\"toc-item\"><li><span><a href=\"#4.1.-Data-&amp;-Descriptive-Statistics\" data-toc-modified-id=\"4.1.-Data-&amp;-Descriptive-Statistics-4.1\">4.1. Data &amp; Descriptive Statistics</a></span></li><li><span><a href=\"#4.2.-Baseline-Comparison\" data-toc-modified-id=\"4.2.-Baseline-Comparison-4.2\">4.2. Baseline Comparison</a></span></li><li><span><a href=\"#4.3.-Results\" data-toc-modified-id=\"4.3.-Results-4.3\">4.3. Results</a></span><ul class=\"toc-item\"><li><span><a href=\"#4.3.1.-Attendence\" data-toc-modified-id=\"4.3.1.-Attendence-4.3.1\">4.3.1. Attendence</a></span></li><li><span><a href=\"#4.3.2.-Re-enrollment\" data-toc-modified-id=\"4.3.2.-Re-enrollment-4.3.4\">4.3.2. Re-enrollment</a></span></li><li><span><a href=\"#4.3.3.-Survey-Based-Outcomes-Graduation-and-Tertiary-Enrollment\" data-toc-modified-id=\"4.3.3.-Survey-Based-Outcomes-Graduation-and-Tertiary-Enrollment-4.3.3\">4.3.3. Survey-Based Outcomes - Graduation and Tertiary Enrollment</a></span></li><li><span><a href=\"#4.3.4.-Siblings-Effects\" data-toc-modified-id=\"4.3.4.-Siblings-Effects-4.3.4\">4.3.4. Siblings Effects</a></span></li></ul></li></ul></li><li><span><a href=\"#5.-Critical-Assessment\" data-toc-modified-id=\"5.-Critical-Assessment-5\">5. Critical Assessment</a></span><li><span><a href=\"#6.-Extensions\" data-toc-modified-id=\"6.-Extensions-7\">6. Extensions</a></span><ul class=\"toc-item\"> <li><span><a href=\"#6.1.-Check-for-Balanced-Groups-across-Experiments\" data-toc-modified-id=\"6.1.-Check-for-Balanced-Groups-across-Experiments-6.1\">6.1. Check for Balanced Groups across Experiments</a></span></li><li><span><a href=\"#6.2.-Elimination-of-Back-door-Paths-Controlling-only-for-Locality\" data-toc-modified-id=\"6.2.-Elimination-of-Back-door-Paths-Controlling-only-for-Locality-6.2\">6.2. Elimination of Back-door Paths Controlling only for Locality</a></span></ul><li><span><a href=\"#7.-Conclusion\" data-toc-modified-id=\"7.-Conclusion-7\">7. Conclusion</a></span></li><li><span><a href=\"#8.-References\" data-toc-modified-id=\"8.-References-8\">8. References</a></span></li></ul></div>\n\n\n```python\nimport pandas as pd\nimport numpy as np\nimport pandas.io.formats.style\nimport statsmodels.api as sm_api\n```\n\n\n```python\nfrom auxiliary.auxiliary_tables import *\n```\n\n---\n# 1. Introduction \n---\n\nBarrera-Osorio et al. (2011) compare three education-based conditional cash transfer designs aimed at incentivizing academic participation. Using data from a pilot study in Bogota, Colombia they examine the effects of a bi-monthly transfer (basic treatment), a bi-monthly transfer combined with a lump-sum payment at the time students are supposed to re-enroll in school (savings treatment) and a bi-monthly transfer combined with a large payment upon graduation (tertiary treatment). The payments are conditional on school attendence of the child and designed to prevent dropout from secondary schools and to encourage matriculation at tertiary institutions. On the one hand, the savings and tertiary treatment impose more binding short-term liquidity constraints on participating families than the basic treatment. The authors examine whether this decreases monthly school attendence. On the other hand, these two treatments might provide stronger incentives for families to re-enroll their children at school or for graduation. \n\nTo estimate and compare the causal impact of the three treatments, Barrera-Osorio et al. (2011) apply a difference model to the data from Bogota. The Secretary of Education of the City implemented a pilot study running for one year, where they randomly allocated treatments to children in two localities. They randomize at child-level, generating variation within schools and families. This allows the authors to assess comparability of different groups. Barrera-Osorio et al. (2011) find that all designs significantly increase attendance and that the savings and tertiary treatments increase enrollment rates more strongly than the basic treatment. They conclude, that the structure of the intervention can help targeting resources.\n\nIn this notebook, I replicate the results presented in the paper by Barrera-Osorio et al. (2011). Additionally, I critically discuss the quality of the strategy and the results. My analysis supports the findings of Barrera-Osorio et al. (2011). \n\nThis notebook is structured as follows. In the next section, I present the identification strategy Barrera-Osorio et al. (2011) use to unravel the causal effects of the conditional cash transfers (section 2). Section 3 briefly discusses the empirical strategy the authors use for estimation. Section 4 shows my replication of the results of the paper, and section 5 is a critical discussion thereof. In section 6 I check the identification assumption across the two experiments and conduct regressions conditioning on one variable that blocks all back-door paths from the causal variable to the outcome variable to identify causal effects. Section 7 presents some conclusions.\n\n---\n# 2. Identification\n--- \n\n\nBarrera-Osorio et al. (2011) aim to answer the question on how three different education-based conditional cash transfer designs perform in preventing dropout from secondary schools and encouraging matriculation at tertiary institutions. \nThe different treatments were implemented in two localities in Bogota, San Cristobal and Suba. Eligible children in San Cristobal were randomly assigned between a control group, the basic treatment (bi-monthly transfer) and the savings treatment (bi-monthly transfer combined with a lump-sum payment at the time students are supposed to re-enroll in school). In Suba eligible children were randomly assigned to the tertiary treatment (bi-monthly transfer combined with a large payment upon graduation) and a control group. Since it is impossible to observe treatment effects at the individual level, researchers thus estimate average effects using treatment and control groups. For each individual $i$ we can image a potential outcome where they are treated $Y_i(1)$ and where they are not $Y_i(0)$, but we can never simultaneously observe both outcomes for each individual. The random treatment assignment allows the authors to estimate the causal effects of the three treatments using experiments. While they can compare the effect of the basic and savings treatment directly, comparing those with the tertiary treatment they cannot rely on purely random variation. This is because the tertiary treatment was implemented in another locality and therefore, the comparison to the tertiary treatment occurs across experiments.\n\nSince treatments were assigned randomly within the two localities, potential outcomes are independent of the treatment indicator $D$ and the selection bias is eliminated. The naive estimate which simply compares the observed average outcome of the treatment and control groups, then equals the true average treatment effect: \n\n\\begin{align*}\n  E[Y\\mid D = 1] - E[Y\\mid D = 0] & = E[Y^1\\mid D = 1] - E[Y^0\\mid D = 0] \\\\\n                                  & =E[Y^1\\mid D = 1]  - E[Y^0\\mid D = 1] + E[Y^0\\mid D = 1] - E[Y^0\\mid D = 0]  \\\\\n                                  & = \\underbrace{E[Y^1 - Y^0\\mid D = 1]}_{ATT} + \\underbrace{E[Y^0\\mid D= 1]- E[Y^0 \\mid D = 0]}_{\\text{Selection bias}} \\\\\n                                  & =E[Y^1 - Y^0\\mid D = 1] \\\\\n                                  & =E[Y^1 - Y^0\\mid D = 0] \\\\\n                                  & =E[Y^1 - Y^0]\n\\end{align*}\n\nThe authors here rely on the following two assumptions:\n\\begin{align*}\nE[Y^1\\mid D = 1] = E[Y^1\\mid D = 0] \\\\\nE[Y^0\\mid D = 1] = E[Y^0\\mid D = 0] \\\\\n\\end{align*}\n\nThe causal graphs below illustrate the relationship between the treatments $D_B$, $D_S$, $D_T$ and outcome $Y$ in the two localities. Additionally there may be observables $W$ and unobservables $U$ also affecting $Y$. Due to random treatment assignment within the two localities, treatment is independent of $W$ and $U$ and there is no back-door path which has to be eliminated.\n\n**San Cristobal:**\n  \n$D_B$: Basic treatment  \n$D_S$: Savings treatment  \n$Y$: Students outcome  \n$U$: Unobservables  \n$W$: Observables\n\n**Suba:**\n  \n$D_T$: Tertiary treatment  \n$Y$: Students outcome  \n$U$: Unobservables  \n$W$: Observables\n\nThe identification assumption to eliminate causal effects is, that randomization is successful within the localities. Barrera-Osorio et al. (2011) account for this checking whether treatment assignment created balanced treatment and control groups using household- and individual-level characteristics. These information were collected prior to the randomization, which suggests that students in each group should, on average, have similar characteristics. The authors make 60 comparisons and find 7 differences that are statistically significant at the 10 percent level, 5 at the 5 percent level and 2 at the 1 percent level. They conclude that randomization of the treatment assignment is successful.\n\nIn order to compare the effects of all three treatments the authors consider the experiments in the two localities together. The causal graph has three back-door paths which have to be eliminated. Treatment assignment is not completely random, since it is not random whether a person lives in Suba or San Cristobal. Observable or unobservable factors may affect treatment assignment and the outcome at the same time. The causal graph the authors use looks as follows:\n\n  \n$D_B$: Basic treatment  \n$D_S$: Savings treatment  \n$D_T$: Tertiary treatment  \n$L$: Dummy for locality of household (Suba or San Cristobal)  \n$Y$: Students outcome  \n$U$: Unobservables  \n$W$: Observables\n\nIn order to eliminate the back-door paths Barrera-Osorio et al. (2011) control for the locality of the householods and a large set of observable demographic characteristics. Nevertheless, the authors mention that differences between the tertiary treatment and the other treatments could be due to unobserved heterogeneity in treatment effects. I will refer to this problem later again.\n\n---\n# 3. Empirical Strategy\n---\nBarrera-Osorio et al. (2011) examine the impact of the basic, the savings and the tertiary treatment on student outcome. They use a simple difference model that compares different subsets of the sample without controlling for covariates. \n\nFor the basic-savings experiment in San Cristobal the specification takes the following form:\n\n\\begin{equation}\ny_{ij} = \\beta_0 + \\beta_B Basic_i + \\beta_S Savings_i + \\epsilon_{ij} \n\\end{equation}\n\nFor the tertiary experiment in Suba the specification takes the following form:\n\n\\begin{equation}\ny_{ij} = \\beta_0 + \\beta_T Tertiary_i + \\epsilon_{ij} \n\\end{equation}\n* $y_{ij}$ denotes a particular outcome for child $i$ in school $j$,\n* $Basic_i$, $Savings_i$ and $Tertiary_i$ are indicator variables for whether or not the child is in the respective treatment group,\n* $\\epsilon_{ij}$ is the error term, which is allowed to vary up to the school level.\n\nThe authors additionally use a difference estimator that controls for socio-demographic and school characteristics.\nFor the basic-savings experiment the model is specified as follows:\n\n\\begin{equation}\ny_{ij} = \\beta_0 + \\beta_B Basic_i + \\beta_S Savings_i + \\delta X_{ijk} + \\phi_{j} + \\epsilon_{ij} \n\\end{equation}\n\nFor the tertiary treatment the model is specified as follows:\n\n\\begin{equation}\ny_{ij} = \\beta_0 + \\beta_T Tertiary_i + \\delta X_{ijk} + \\phi_{j} + \\epsilon_{ij} \n\\end{equation}\n\nThe variables are defined as before. Additionally,\n* $X_{ijk}$ is a vector of socio-demographic controls for child $i$ in school $j$ and family $k$,\n* $\\phi_{j}$ are school fixed effects.\n\n---\n# 4. Replication of Barrera-Osorio et al. (2011)\n---\n\n## 4.1. Data & Descriptive Statistics\nBarrera-Osorio et al. (2011) restricted their sample of students spread across 251 schools to the 68 school with the largest number of registered students. Additionally, they filter the data by those students who completed a baseline survey they conducted. For the tertiary experiment they drop students in grade 6-8 since those were not eligible for the program.\n\n\n```python\ndata = pd.read_stata('data/Public_Data_AEJApp_2010-0132.dta')\ndata.index.name = \"individual\"\ndata['grade_group'] = 'Grades 6-8'\ndata.loc[data['grade'] > 8, 'grade_group'] = 'Grades 9-10'\ndata.loc[data['grade'] > 10, 'grade_group'] = 'Grade 11'\ndata['group'] = 'Control'\ndata.loc[data['T1_treat'] == 1, 'group'] = 'Basic'\ndata.loc[data['T2_treat'] == 1, 'group'] = 'Savings'\ndata.loc[data['T3_treat'] == 1, 'group'] = 'Tertiary'\nsample = data.drop(data[(data.suba == 1) & (data.grade < 9)].index)\nsample['s_teneviv_int'] = sample['s_teneviv'].cat.codes + 1\nsample['s_sexo_int'] = sample['s_sexo'].cat.codes\nsample['s_estcivil_int'] = sample['s_estcivil'].cat.codes + 1\nsample = sample.join(pd.get_dummies(sample['school_code']))\nsample = sample.join(pd.get_dummies(sample['s_teneviv']))\nsample = sample.join(pd.get_dummies(sample['s_estcivil']))\nsample = sample.join(pd.get_dummies(sample['grade'], prefix='grade'))\nsample = sample.join(pd.get_dummies(sample['s_estrato'],  prefix='estrato'))\nsample_baselinesurvey =  sample.drop(sample[sample.bl_observed == 0].index)\n```\n\nTable 1 summarizes the distribution of children by grade, gender and experimental group. They end up with a sample of 7158 students.\n\n#### Table 1- Distribution of Subjects by Research Groups\n\n\n```python\ncreate_table1(sample_baselinesurvey)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th>Experiment</th>\n      <th colspan=\"3\" halign=\"left\">Basic-Savings</th>\n      <th colspan=\"2\" halign=\"left\">Tertiary</th>\n      <th>Total</th>\n    </tr>\n    <tr>\n      <th>Group</th>\n      <th>Control</th>\n      <th>Basic</th>\n      <th>Savings</th>\n      <th>Control</th>\n      <th>Tertiary</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Grades 6-8</th>\n      <td>1189</td>\n      <td>1215</td>\n      <td>1166</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3570</td>\n    </tr>\n    <tr>\n      <th>Grades 9-10</th>\n      <td>643</td>\n      <td>633</td>\n      <td>586</td>\n      <td>449</td>\n      <td>425</td>\n      <td>2736</td>\n    </tr>\n    <tr>\n      <th>Grade 11</th>\n      <td>179</td>\n      <td>188</td>\n      <td>177</td>\n      <td>160</td>\n      <td>148</td>\n      <td>852</td>\n    </tr>\n    <tr>\n      <th>Female</th>\n      <td>1047</td>\n      <td>1022</td>\n      <td>1000</td>\n      <td>361</td>\n      <td>336</td>\n      <td>3766</td>\n    </tr>\n    <tr>\n      <th>Male</th>\n      <td>964</td>\n      <td>1014</td>\n      <td>929</td>\n      <td>248</td>\n      <td>237</td>\n      <td>3392</td>\n    </tr>\n    <tr>\n      <th>Total</th>\n      <td>2011</td>\n      <td>2036</td>\n      <td>1929</td>\n      <td>609</td>\n      <td>573</td>\n      <td>7158</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## 4.2. Baseline Comparison\nBarrera-Osorio et al. (2011) check if the randomization was successful and created balanced research groups. To do so, they compare characteristics of students between research groups. Table 2 shows the averages of 15 different variables for the control groups in the basic-savings experiment (B-S) and the tertiary experiment (T). The 4 other columns show 60 comparisons between the treatment and control groups. The standard errors are in the row below each difference, labeled with \"SE\". 7 differences are statistically significant at the 10 percent level, 5 at the 5 percent level, and 2 at the 1 percent level. Since the number of statistically significant differences is low, one can conclude that treatment is assigned randomly within the localities, which supports the identification assumption of their strategy.\n\n#### Table 2- Comparison of Students between Research Groups\n\n\n```python\nsancristobal = sample.drop(sample[sample.suba == 1].index)\nsuba = sample.drop(sample[sample.suba == 0].index)\ncreate_table2(sancristobal, suba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Control average B-S</th>\n      <th>Basic-Control</th>\n      <th>Savings-Control</th>\n      <th>Basic-Savings</th>\n      <th>Control average T</th>\n      <th>Tertiary-Control</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Possessions</th>\n      <td>1.90</td>\n      <td>0.07</td>\n      <td>0.04</td>\n      <td>0.03</td>\n      <td>1.94</td>\n      <td>-0.05</td>\n    </tr>\n    <tr>\n      <th>Possessions SE</th>\n      <td>1.1</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>1.02</td>\n      <td>0.04</td>\n    </tr>\n    <tr>\n      <th>Utilities</th>\n      <td>4.65</td>\n      <td>-0.02</td>\n      <td>0.06</td>\n      <td>-0.08</td>\n      <td>4.85</td>\n      <td>0.04</td>\n    </tr>\n    <tr>\n      <th>Utilities SE</th>\n      <td>1.42</td>\n      <td>0.03</td>\n      <td>0.03</td>\n      <td>0.03</td>\n      <td>1.32</td>\n      <td>0.04</td>\n    </tr>\n    <tr>\n      <th>Durable Goods</th>\n      <td>1.37</td>\n      <td>-0.02</td>\n      <td>0.01</td>\n      <td>-0.03</td>\n      <td>1.63</td>\n      <td>0.02</td>\n    </tr>\n    <tr>\n      <th>Durable Goods SE</th>\n      <td>0.89</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>0.86</td>\n      <td>0.03</td>\n    </tr>\n    <tr>\n      <th>Physical Infrastructure</th>\n      <td>11.65</td>\n      <td>-0.05</td>\n      <td>0.04</td>\n      <td>-0.09</td>\n      <td>12.14</td>\n      <td>-0.05</td>\n    </tr>\n    <tr>\n      <th>Physical Infrastructure SE</th>\n      <td>1.75</td>\n      <td>0.03</td>\n      <td>0.03</td>\n      <td>0.04</td>\n      <td>1.49</td>\n      <td>0.06</td>\n    </tr>\n    <tr>\n      <th>Age</th>\n      <td>14.38</td>\n      <td>0.09</td>\n      <td>-0.06</td>\n      <td>0.16</td>\n      <td>15.67</td>\n      <td>-0.06</td>\n    </tr>\n    <tr>\n      <th>Age SE</th>\n      <td>5.3</td>\n      <td>0.10</td>\n      <td>0.14</td>\n      <td>0.17</td>\n      <td>4.23</td>\n      <td>0.19</td>\n    </tr>\n    <tr>\n      <th>Gender</th>\n      <td>0.50</td>\n      <td>0.00</td>\n      <td>-0.00</td>\n      <td>0.01</td>\n      <td>0.45</td>\n      <td>-0.01</td>\n    </tr>\n    <tr>\n      <th>Gender SE</th>\n      <td>0.5</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.5</td>\n      <td>0.02</td>\n    </tr>\n    <tr>\n      <th>Years of Education</th>\n      <td>5.61</td>\n      <td>-0.02</td>\n      <td>-0.01</td>\n      <td>-0.02</td>\n      <td>7.43</td>\n      <td>-0.05</td>\n    </tr>\n    <tr>\n      <th>Years of Education SE</th>\n      <td>1.86</td>\n      <td>0.04</td>\n      <td>0.05</td>\n      <td>0.04</td>\n      <td>1.34</td>\n      <td>0.05</td>\n    </tr>\n    <tr>\n      <th>Single Head</th>\n      <td>0.30</td>\n      <td>0.02</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.27</td>\n      <td>0.01</td>\n    </tr>\n    <tr>\n      <th>Single Head SE</th>\n      <td>0.46</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.44</td>\n      <td>0.02</td>\n    </tr>\n    <tr>\n      <th>Age of Head</th>\n      <td>45.92</td>\n      <td>-0.07</td>\n      <td>0.11</td>\n      <td>-0.19</td>\n      <td>46.21</td>\n      <td>0.21</td>\n    </tr>\n    <tr>\n      <th>Age of Head SE</th>\n      <td>10.27</td>\n      <td>0.17</td>\n      <td>0.23</td>\n      <td>0.21</td>\n      <td>8.59</td>\n      <td>0.30</td>\n    </tr>\n    <tr>\n      <th>Years of ed., head</th>\n      <td>5.65</td>\n      <td>-0.11</td>\n      <td>-0.18</td>\n      <td>0.07</td>\n      <td>5.94</td>\n      <td>-0.13</td>\n    </tr>\n    <tr>\n      <th>Years of ed., head SE</th>\n      <td>2.94</td>\n      <td>0.08</td>\n      <td>0.07</td>\n      <td>0.07</td>\n      <td>2.94</td>\n      <td>0.09</td>\n    </tr>\n    <tr>\n      <th>People in Household</th>\n      <td>5.42</td>\n      <td>-0.04</td>\n      <td>-0.03</td>\n      <td>-0.02</td>\n      <td>5.16</td>\n      <td>-0.01</td>\n    </tr>\n    <tr>\n      <th>People in Household SE</th>\n      <td>2.01</td>\n      <td>0.05</td>\n      <td>0.05</td>\n      <td>0.04</td>\n      <td>1.78</td>\n      <td>0.07</td>\n    </tr>\n    <tr>\n      <th>Member under 18</th>\n      <td>2.57</td>\n      <td>0.03</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>2.31</td>\n      <td>0.05</td>\n    </tr>\n    <tr>\n      <th>Member under 18 SE</th>\n      <td>1.35</td>\n      <td>0.03</td>\n      <td>0.03</td>\n      <td>0.03</td>\n      <td>1.2</td>\n      <td>0.06</td>\n    </tr>\n    <tr>\n      <th>Estrato</th>\n      <td>1.44</td>\n      <td>-0.01</td>\n      <td>0.02</td>\n      <td>-0.03</td>\n      <td>1.63</td>\n      <td>-0.01</td>\n    </tr>\n    <tr>\n      <th>Estrato SE</th>\n      <td>0.83</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>0.77</td>\n      <td>0.03</td>\n    </tr>\n    <tr>\n      <th>SISBEN score</th>\n      <td>11.76</td>\n      <td>-0.11</td>\n      <td>-0.02</td>\n      <td>-0.10</td>\n      <td>13.44</td>\n      <td>0.03</td>\n    </tr>\n    <tr>\n      <th>SISBEN score SE</th>\n      <td>4.64</td>\n      <td>0.08</td>\n      <td>0.11</td>\n      <td>0.10</td>\n      <td>4.33</td>\n      <td>0.18</td>\n    </tr>\n    <tr>\n      <th>Household income (1,000 pesos)</th>\n      <td>366.70</td>\n      <td>-4.73</td>\n      <td>-0.35</td>\n      <td>-4.37</td>\n      <td>402.03</td>\n      <td>3.18</td>\n    </tr>\n    <tr>\n      <th>Household income (1,000 pesos) SE</th>\n      <td>241.01</td>\n      <td>5.77</td>\n      <td>6.17</td>\n      <td>6.64</td>\n      <td>235.44</td>\n      <td>7.67</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## 4.3. Results\n\n### 4.3.1 Attendence\nFirst, the authors analyse the effects of the conditional cash transfers on the school attendence rate. They include only individuals who are enrolled in one of the 68 schools selected for surveying. They also restrict the sample to students in grades 6-10, because they exclude students who are in grade 11 for the enrollment effect estimations, since they should graduate rather than re-enroll. In order to replicate their results I run simple regressions of the school attendence rate on the treatment variable, once without control variables, once with demographic controls and once with demographic controls and school fixed effects. The first three columns of table 3 show the results for the basic-savings experiment in Sancristobal, while columns 4 to 6 show the results for the tertiary experiment in Suba. The last column shows results of a regression containing all three treatments, demographic controls and school fixed effects. The estimated treatment effects and their standard errors (\"SE\") are provided in rows 1-6. The test statistics from comparisons of the relative treatment effects and their p-values are in rows 7-10.\n\n#### Table 3 - Effects on monitored school attendence rates\n\n\n```python\nsancristobal = sample.drop(sample[sample.suba == 1].index)\nsuba = sample.drop(sample[sample.suba == 0].index)\nsancristobal = sancristobal.drop(sancristobal[(sancristobal.survey_selected == 0) | (sancristobal.grade == 11)].index)\nsuba = suba.drop(suba[(suba.survey_selected == 0) | (suba.grade == 11) | (suba.grade < 9)].index)\nsample_survey = sample.drop(sample[(sample.survey_selected == 0) | (sample.grade == 11) | (sample.grade < 9)].index)\ncreate_table34(sancristobal, suba, sample_survey, 'at_msamean')\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Basic-Savings</th>\n      <th>Basic-Savings with demographics</th>\n      <th>Basic-Savings with demographics and school fixed effects</th>\n      <th>Tertiary</th>\n      <th>Tertiary with demographics</th>\n      <th>Tertiary with demographics and school fixed effects</th>\n      <th>Both</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Basic treatment</th>\n      <td>0.033</td>\n      <td>0.032</td>\n      <td>0.032</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>0.025</td>\n    </tr>\n    <tr>\n      <th>Basic treatment SE</th>\n      <td>0.007</td>\n      <td>0.008</td>\n      <td>0.007</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>0.01</td>\n    </tr>\n    <tr>\n      <th>Savings treatment</th>\n      <td>0.029</td>\n      <td>0.027</td>\n      <td>0.027</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>0.028</td>\n    </tr>\n    <tr>\n      <th>Savings treatment SE</th>\n      <td>0.008</td>\n      <td>0.008</td>\n      <td>0.007</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>0.012</td>\n    </tr>\n    <tr>\n      <th>Tertiary treatment</th>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>0.052</td>\n      <td>0.054</td>\n      <td>0.056</td>\n      <td>0.055</td>\n    </tr>\n    <tr>\n      <th>Tertiary treatment SE</th>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>0.018</td>\n      <td>0.016</td>\n      <td>0.02</td>\n      <td>0.02</td>\n    </tr>\n    <tr>\n      <th>H0: Basic-Savings F-Stat</th>\n      <td>0.312</td>\n      <td>0.404</td>\n      <td>0.481</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>0.053</td>\n    </tr>\n    <tr>\n      <th>p-value</th>\n      <td>0.581</td>\n      <td>0.53</td>\n      <td>0.494</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>0.819</td>\n    </tr>\n    <tr>\n      <th>H0: Tertiary-Basic F-Stat</th>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>1.863</td>\n    </tr>\n    <tr>\n      <th>p-value</th>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>0.18</td>\n    </tr>\n    <tr>\n      <th></th>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <th>Observations</th>\n      <td>5799</td>\n      <td>5799</td>\n      <td>5799</td>\n      <td>930</td>\n      <td>930</td>\n      <td>930</td>\n      <td>2937</td>\n    </tr>\n    <tr>\n      <th>R squared</th>\n      <td>0.003</td>\n      <td>0.037</td>\n      <td>0.089</td>\n      <td>0.008</td>\n      <td>0.058</td>\n      <td>0.269</td>\n      <td>0.134</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThe table shows:\n- Basic treatment increases attendence by 3.3 percentage points (significant at the one percent level)\n- Savings treatent increases attendence by 2.9 percentage points (significant at the one percent level)\n- Tertiary treatment increases attendence by 5.2 percentage points (significant at the one percent level)\n- no evidence that the treatments have different effects\n\nMy results from the regressions and difference tests are the same as those Barrera-Osorio et al. (2011) estimate in their paper. One can conclude, that although the savings and tertiary treatment impose more binding short-term liquidity constraints on families than the basic treatment, there is no evidence of this hurting monthly attendence. \n\n### 4.3.2 Re-enrollment\nSecond, the authors analyse the effects of the conditional cash transfers on re-enrollment. Table 4 is designed as table 3, running regressions on the observed re-enrollment rate.\n\n#### Table 4 - Effects on administrative enrollment in following year\n\n\n```python\nsancristobal = sample.drop(sample[(sample.suba == 1) | (sample.grade == 11)].index)\nsuba = sample.drop(sample[(sample.suba == 0) | (sample.grade == 11) | (sample.grade < 9)].index)\nsancristobal = sancristobal[sancristobal['m_enrolled'].notna()]\nsuba = suba[suba['m_enrolled'].notna()]\nsample_grade = sample.drop(sample[(sample.grade == 11) | (sample.grade < 9)].index)\nsample_grade = sample_grade[sample_grade['m_enrolled'].notna()]\ncreate_table34(sancristobal, suba, sample_grade, 'm_enrolled')\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Basic-Savings</th>\n      <th>Basic-Savings with demographics</th>\n      <th>Basic-Savings with demographics and school fixed effects</th>\n      <th>Tertiary</th>\n      <th>Tertiary with demographics</th>\n      <th>Tertiary with demographics and school fixed effects</th>\n      <th>Both</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Basic treatment</th>\n      <td>0.017</td>\n      <td>0.016</td>\n      <td>0.011</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>Basic treatment SE</th>\n      <td>0.009</td>\n      <td>0.008</td>\n      <td>0.01</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>0.016</td>\n    </tr>\n    <tr>\n      <th>Savings treatment</th>\n      <td>0.045</td>\n      <td>0.046</td>\n      <td>0.04</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>0.03</td>\n    </tr>\n    <tr>\n      <th>Savings treatment SE</th>\n      <td>0.016</td>\n      <td>0.015</td>\n      <td>0.011</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>0.017</td>\n    </tr>\n    <tr>\n      <th>Tertiary treatment</th>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>0.042</td>\n      <td>0.039</td>\n      <td>0.037</td>\n      <td>0.042</td>\n    </tr>\n    <tr>\n      <th>Tertiary treatment SE</th>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>0.022</td>\n      <td>0.021</td>\n      <td>0.02</td>\n      <td>0.019</td>\n    </tr>\n    <tr>\n      <th>H0: Basic-Savings F-Stat</th>\n      <td>3.99</td>\n      <td>3.941</td>\n      <td>5.519</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>2.271</td>\n    </tr>\n    <tr>\n      <th>p-value</th>\n      <td>0.048</td>\n      <td>0.049</td>\n      <td>0.02</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>0.133</td>\n    </tr>\n    <tr>\n      <th>H0: Tertiary-Basic F-Stat</th>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>2.228</td>\n    </tr>\n    <tr>\n      <th>p-value</th>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>0.137</td>\n    </tr>\n    <tr>\n      <th></th>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <th>Observations</th>\n      <td>8980</td>\n      <td>8980</td>\n      <td>8980</td>\n      <td>1735</td>\n      <td>1735</td>\n      <td>1735</td>\n      <td>4775</td>\n    </tr>\n    <tr>\n      <th>R squared</th>\n      <td>0.002</td>\n      <td>0.047</td>\n      <td>0.172</td>\n      <td>0.002</td>\n      <td>0.079</td>\n      <td>0.259</td>\n      <td>0.208</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThe table shows:\n- Basic treatment increases re-enrollment by 1.7 percentage points (significant at the 10 percent level)\n- Savings treatent increases re-enrollment by 4.5 percentage points (significant at the one percent level)\n- Tertiary treatment increases re-enrollment by 3.6 percentage points (significant at the 10 percent level)\n- difference in magnitude of the basic and savings treatment effects is statistically significant at the 5 percent level\n- no evidence that the tertiary and the basic treatment effects are different\n\nAgain, my results from the regressions are the same as those Barrera-Osorio et al. (2011) estimate in their paper. One can conclude, that the savings treatment, which consists of a bi-monthly transfer combined with a lump-sum payment at the time students are supposed to re-enroll in school, is more effective in increasing re-enrollment than the basic treatment. \n\n### 4.3.3 Survey-Based Outcomes - Graduation and Tertiary Enrollment\nBarrera-Osorio et al. (2011) use data from a follow-up survey which was conducted after the treatments were implemented to analyse the effects of each treatment on self-reported graduation and tertiary enrollment for students who were in grade 11. The sample is restricted to those students, for which the follow-up survey data is provided. In order to replicate the results from Barrera-Osorio et al. (2011), I run regressions of the binary variable for graduation and of the binary variable for tertiary enrollment on the treatment variables with demographic controls and school fixed effects. The first three columns of table 3 show the effects on graduation in the sample of Sancristobal, the sample in Suba and both together. Columns 4 to 6 show the effects on tertiary enrollment, again, in the sample of Sancristobal, the sample in Suba and both together. The estimated treatment effects and their standard errors (\"SE\") are provided in rows 1-6 and the test statistics from comparisons of the relative treatment effects and their p-values are in rows 7-10.\n\n#### Table 5 - Effects graduation and tertiary enrollment for students in grade 11\n\n\n```python\ncreate_table5(sample)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Graduation Basic-Savings</th>\n      <th>Graduation Tertiary</th>\n      <th>Graduation Both</th>\n      <th>Tertiary enrollment Basic-Savings</th>\n      <th>Tertiary enrollment Tertiary</th>\n      <th>Tertiary enrollment Both</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Basic treatment</th>\n      <td>0.039</td>\n      <td></td>\n      <td>0.036</td>\n      <td>0.043</td>\n      <td></td>\n      <td>0.048</td>\n    </tr>\n    <tr>\n      <th>Basic treatment SE</th>\n      <td>0.042</td>\n      <td></td>\n      <td>0.042</td>\n      <td>0.036</td>\n      <td></td>\n      <td>0.033</td>\n    </tr>\n    <tr>\n      <th>Savings treatment</th>\n      <td>0.04</td>\n      <td></td>\n      <td>0.039</td>\n      <td>0.094</td>\n      <td></td>\n      <td>0.094</td>\n    </tr>\n    <tr>\n      <th>Savings treatment SE</th>\n      <td>0.033</td>\n      <td></td>\n      <td>0.03</td>\n      <td>0.034</td>\n      <td></td>\n      <td>0.033</td>\n    </tr>\n    <tr>\n      <th>Tertiary treatment</th>\n      <td></td>\n      <td>0.047</td>\n      <td>0.044</td>\n      <td></td>\n      <td>0.489</td>\n      <td>0.487</td>\n    </tr>\n    <tr>\n      <th>Tertiary treatment SE</th>\n      <td></td>\n      <td>0.037</td>\n      <td>0.031</td>\n      <td></td>\n      <td>0.04</td>\n      <td>0.041</td>\n    </tr>\n    <tr>\n      <th>H0: Basic-Savings F-Stat</th>\n      <td>0</td>\n      <td></td>\n      <td>0.006</td>\n      <td>1.769</td>\n      <td></td>\n      <td>1.542</td>\n    </tr>\n    <tr>\n      <th>p-value</th>\n      <td>0.991</td>\n      <td></td>\n      <td>0.94</td>\n      <td>0.199</td>\n      <td></td>\n      <td>0.223</td>\n    </tr>\n    <tr>\n      <th>H0: Tertiary-Basic F-Stat</th>\n      <td></td>\n      <td></td>\n      <td>0.022</td>\n      <td></td>\n      <td></td>\n      <td>75.558</td>\n    </tr>\n    <tr>\n      <th>p-value</th>\n      <td></td>\n      <td></td>\n      <td>0.882</td>\n      <td></td>\n      <td></td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th></th>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <th>Observations</th>\n      <td>529</td>\n      <td>297</td>\n      <td>826</td>\n      <td>513</td>\n      <td>290</td>\n      <td>803</td>\n    </tr>\n    <tr>\n      <th>R squared</th>\n      <td>0.103</td>\n      <td>0.15</td>\n      <td>0.098</td>\n      <td>0.085</td>\n      <td>0.373</td>\n      <td>0.208</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThe table shows:\n- None of the estimated effects on graduation are statistically significant\n- Savings treatment increases tertiary enrollment by 9.4 percentage points (statistically significant at the 5 percent level)\n- Tertiary treatment increases tertiary enrollment by 48.9 percentage points (statistically significant at the 1 percent level)\n- The effect for the tertiary treatment is statistically significantly different from the effect of the basic treatment (p-value < 0.0001)\n\nThese estimates are of the same size as those provided by Barrera-Osorio et al. (2011). They mention that the tertiary enrollment findings might not be credible due to the extremely large estimate for the tertiary treatment group. One explanation for this result could be that students in the tertiary treatment group are lying in the follow-up survey about being enrolled in tertiary institutions. However, self-reported graduation rates seem to match the estimates based on the administrative enrollment data and verified attendence data.\n\n### 4.3.4 Siblings Effects\nBarrera-Osorio et al. (2011) analyse the effect of the treatments on school attendence and re-enrollment for siblings. They use the intra-familiy variation in treatment assignment to provide a reduced form test of whether receiving the transfer changes the allocation of opportunities within the household. In order to extract causal effects they restrict their sample to the subset of siblings that were also registered, since otherwise systematic differences between those families who registered one and those who registered two children might bias the results. They focus on families who registered two children and only choose those for which administrative enrollment data is available. They pool the treatments due to the small sample size. Columns 1 and 2 of Table 6 contain comparisons of untreated children with and without treated siblings. Columns 3 and 4 show comparisons only for girls and columns 5 and 6 for boys.\n\n#### Table 6 - Effects of treatment on siblings using monitored and administrative participation, households with two registered children\n\n\n```python\ncreate_table6(data)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Attendence</th>\n      <th>Enrollment</th>\n      <th>Attendence Female</th>\n      <th>Enrollment Female</th>\n      <th>Attendence Male</th>\n      <th>Enrollment Male</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Sibling is treated?</th>\n      <td>-0.03</td>\n      <td>-0.071</td>\n      <td>-0.053</td>\n      <td>-0.114</td>\n      <td>-0.029</td>\n      <td>-0.04</td>\n    </tr>\n    <tr>\n      <th>Sibling is treated? SE</th>\n      <td>0.015</td>\n      <td>0.026</td>\n      <td>0.021</td>\n      <td>0.053</td>\n      <td>0.032</td>\n      <td>0.04</td>\n    </tr>\n    <tr>\n      <th></th>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <th>Observations</th>\n      <td>690</td>\n      <td>668</td>\n      <td>352</td>\n      <td>340</td>\n      <td>338</td>\n      <td>328</td>\n    </tr>\n    <tr>\n      <th>R squared</th>\n      <td>0.278</td>\n      <td>0.137</td>\n      <td>0.332</td>\n      <td>0.23</td>\n      <td>0.383</td>\n      <td>0.234</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThe table shows:\n- Attendence of untreated children with treated siblings is 3 percentage points lower compared to untreated children whose siblings are also untreated (statistically significant at the 10 percent level)\n- Enrollment of untreated children with treated siblings is 7.1 percentage points lower compared to untreated children whose siblings are also untreated (statistically significant at the 1 percent level)\n- The effect is qualitatively similar for both genders\n- The effect is stronger for girls, statistically significant at the 5 percent level for attendence and at the 10 percent level for enrollment \n\nThe results in columns 1, 2, 3 and 5 are the same as those provided by Barrera-Osorio et al. (2011). The estimates of the effect on enrollment of female and male  are slightly different to those provided in the paper. However, qualitatively the effects are the same. The table suggest that the additional household resources generated by the program are not used to invest in the education of the untreated children. Instead, families with a treated child seem to take educational input away from the untreated child. The authors conclude, that eligibility rules that cut across children may increase inequality in the educational attainment within the household.\n\n---\n# 5. Critical Assessment\n---\n\nThe following section discusses the quality of the strategy and estimations provided by Barrera-Osorio et al. (2011).  \nFirst, one strength of their analysis is, that they use administrative data for attendence and enrollment. This implies a high quality of data, since it is not systematically affected by individuals lying or misreporting as survey data might be.  \nSecond, they check whether treatments are assigned randomly within the localities. Comparing characteristics between control and treatment groups they conclude that they are balanced. Furthermore, the fact that regression estimates do not differ strongly when demographics and school fixed effects are included, implies, that randomization was successful.  \nThird, in order to rule out spillover effects of the treatment between children through peer networks, Barrera-Osorio et al. (2011) check that children in the treatment and the control group have similar networks. Therefore, any indirect treatment effect would be equally distributed across the groups.  \nFourth, the authors make sure that there is no self selection into treatment. Only children from families, who lived in the localities prior to 2004 were eligible to register for the program. This rules out that families moved to take advantage of the treatments.  \nFifth, they mention that the SISBEN data, which they use for background characteristics, may underestimate assets and income, since the surveyed families knew that they were surveyed for the purpose of scoring them on a poverty index. However, the bias due to this hawthorne effect is not correlated with the differences investigated in the paper given the timing and purpose of the survey.  \nSixth, Barrera-Osorio et al. (2011) check whether their baseline and follow-up survey induce a bias due to attrition. They conclude that attrition occurs similar across treatment and control groups, which implies that the results should not be biased.  \n\nOne problem regarding their analysis is, that the tertiary treatment ends up being more generous than the basic and savings treatment. This makes it difficult to compare the treatments and the effects of the tertiary treatment might be biased upwards compared to the effect of the other two treatments.  \nNext, they cannot rely on random treatment assignment for comparisons between the treatments in the two experiments. This might bias the result if there are systematic differences of characteristics which at the same time affect treatment assignment and the outcome variable. For example, the fact that the difference in magnitude of the basic and the savings treatment effects on re-enrollment is statistically significant in the regression, where I only consider the experiment in San Cristobal, and not statistically significant in the regression, where I include both locations, indicates this.  \nAnother problem is, that the administrative enrollment data could not be matched to 9.3% of the students in the experiment from San Cristobal, and 8.5% could not be matched in Suba. If the children for which the data could not be matched have characteristics, which systematically affect their enrollment rate, this creates a bias.  \nThe results for the effects on graduation and tertiary enrollment relies on survey-based data. Since individuals might lie or misreport information, the results could be biased.  \nLastly, the sample size for the tertiary treatment is not very large, which reduces reliability of the results and therefore is another weakness of the paper.\n\n---\n# 6. Extensions\n---\n\n## 6.1. Check for Balanced Groups across Experiments\nAs mentioned above, to compare the effects of all three treatments, while considering the experiments in the two localities together, the causal graph has three back-door paths which have to be eliminated. Treatment assignment is not completely random, since it is not random whether a person lives in Suba or San Cristobal. Observable or unobservable factors may affect where a family lives and therefore also are correlated with the treatment assignment and the outcome at the same time. This can be seen, when comparing characteristics of all three treatment groups to each other and to the group of not treated individuals in both localities together. Table 7 shows these comparisons. The first column shows the average for all not treated children in the sample. The following columns present the differences between the corresponding groups. For each mean and difference standard errors are provided below, denoted by 'SE'. \n\n#### Table 7 - Comparisons of Students across Experiments\n\n\n```python\ncreate_table7(sample)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Control average</th>\n      <th>Basic-Control</th>\n      <th>Savings-Control</th>\n      <th>Tertiary-Conrol</th>\n      <th>Basic-Savings</th>\n      <th>Basic-Tertiary</th>\n      <th>Savings-Tertiary</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Possessions</th>\n      <td>1.91</td>\n      <td>0.06</td>\n      <td>0.02</td>\n      <td>-0.01</td>\n      <td>0.03</td>\n      <td>0.07</td>\n      <td>0.04</td>\n    </tr>\n    <tr>\n      <th>Possessions SE</th>\n      <td>1.08</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>0.04</td>\n      <td>0.02</td>\n      <td>0.05</td>\n      <td>0.05</td>\n    </tr>\n    <tr>\n      <th>Utilities</th>\n      <td>4.70</td>\n      <td>-0.07</td>\n      <td>0.01</td>\n      <td>0.19</td>\n      <td>-0.08</td>\n      <td>-0.25</td>\n      <td>-0.18</td>\n    </tr>\n    <tr>\n      <th>Utilities SE</th>\n      <td>1.39</td>\n      <td>0.03</td>\n      <td>0.03</td>\n      <td>0.06</td>\n      <td>0.03</td>\n      <td>0.08</td>\n      <td>0.07</td>\n    </tr>\n    <tr>\n      <th>Durable Goods</th>\n      <td>1.44</td>\n      <td>-0.09</td>\n      <td>-0.06</td>\n      <td>0.21</td>\n      <td>-0.03</td>\n      <td>-0.30</td>\n      <td>-0.27</td>\n    </tr>\n    <tr>\n      <th>Durable Goods SE</th>\n      <td>0.89</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>0.03</td>\n      <td>0.02</td>\n      <td>0.04</td>\n      <td>0.04</td>\n    </tr>\n    <tr>\n      <th>Physical Infrastructure</th>\n      <td>11.78</td>\n      <td>-0.18</td>\n      <td>-0.09</td>\n      <td>0.31</td>\n      <td>-0.09</td>\n      <td>-0.48</td>\n      <td>-0.40</td>\n    </tr>\n    <tr>\n      <th>Physical Infrastructure SE</th>\n      <td>1.70</td>\n      <td>0.04</td>\n      <td>0.03</td>\n      <td>0.06</td>\n      <td>0.04</td>\n      <td>0.07</td>\n      <td>0.06</td>\n    </tr>\n    <tr>\n      <th>Age</th>\n      <td>14.71</td>\n      <td>-0.24</td>\n      <td>-0.39</td>\n      <td>0.90</td>\n      <td>0.16</td>\n      <td>-1.13</td>\n      <td>-1.29</td>\n    </tr>\n    <tr>\n      <th>Age SE</th>\n      <td>5.08</td>\n      <td>0.13</td>\n      <td>0.14</td>\n      <td>0.20</td>\n      <td>0.17</td>\n      <td>0.25</td>\n      <td>0.21</td>\n    </tr>\n    <tr>\n      <th>Gender</th>\n      <td>0.48</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>-0.04</td>\n      <td>0.01</td>\n      <td>0.05</td>\n      <td>0.04</td>\n    </tr>\n    <tr>\n      <th>Gender SE</th>\n      <td>0.50</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.02</td>\n      <td>0.01</td>\n      <td>0.02</td>\n      <td>0.02</td>\n    </tr>\n    <tr>\n      <th>Years of Education</th>\n      <td>6.08</td>\n      <td>-0.49</td>\n      <td>-0.47</td>\n      <td>1.30</td>\n      <td>-0.02</td>\n      <td>-1.79</td>\n      <td>-1.77</td>\n    </tr>\n    <tr>\n      <th>Years of Education SE</th>\n      <td>1.91</td>\n      <td>0.10</td>\n      <td>0.10</td>\n      <td>0.12</td>\n      <td>0.04</td>\n      <td>0.13</td>\n      <td>0.13</td>\n    </tr>\n    <tr>\n      <th>Single Head</th>\n      <td>0.29</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>-0.01</td>\n      <td>0.01</td>\n      <td>0.04</td>\n      <td>0.03</td>\n    </tr>\n    <tr>\n      <th>Single Head SE</th>\n      <td>0.45</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.02</td>\n      <td>0.02</td>\n    </tr>\n    <tr>\n      <th>Age of Head</th>\n      <td>45.99</td>\n      <td>-0.15</td>\n      <td>0.04</td>\n      <td>0.43</td>\n      <td>-0.19</td>\n      <td>-0.58</td>\n      <td>-0.39</td>\n    </tr>\n    <tr>\n      <th>Age of Head SE</th>\n      <td>9.87</td>\n      <td>0.17</td>\n      <td>0.21</td>\n      <td>0.27</td>\n      <td>0.21</td>\n      <td>0.31</td>\n      <td>0.30</td>\n    </tr>\n    <tr>\n      <th>Years of ed., head</th>\n      <td>5.73</td>\n      <td>-0.18</td>\n      <td>-0.25</td>\n      <td>0.08</td>\n      <td>0.07</td>\n      <td>-0.26</td>\n      <td>-0.33</td>\n    </tr>\n    <tr>\n      <th>Years of ed., head SE</th>\n      <td>2.94</td>\n      <td>0.08</td>\n      <td>0.07</td>\n      <td>0.10</td>\n      <td>0.07</td>\n      <td>0.12</td>\n      <td>0.11</td>\n    </tr>\n    <tr>\n      <th>People in Household</th>\n      <td>5.35</td>\n      <td>0.02</td>\n      <td>0.04</td>\n      <td>-0.20</td>\n      <td>-0.02</td>\n      <td>0.22</td>\n      <td>0.24</td>\n    </tr>\n    <tr>\n      <th>People in Household SE</th>\n      <td>1.95</td>\n      <td>0.05</td>\n      <td>0.05</td>\n      <td>0.07</td>\n      <td>0.04</td>\n      <td>0.08</td>\n      <td>0.07</td>\n    </tr>\n    <tr>\n      <th>Member under 18</th>\n      <td>2.50</td>\n      <td>0.09</td>\n      <td>0.08</td>\n      <td>-0.14</td>\n      <td>0.01</td>\n      <td>0.24</td>\n      <td>0.22</td>\n    </tr>\n    <tr>\n      <th>Member under 18 SE</th>\n      <td>1.32</td>\n      <td>0.03</td>\n      <td>0.03</td>\n      <td>0.05</td>\n      <td>0.03</td>\n      <td>0.06</td>\n      <td>0.05</td>\n    </tr>\n    <tr>\n      <th>Estrato</th>\n      <td>1.49</td>\n      <td>-0.06</td>\n      <td>-0.03</td>\n      <td>0.13</td>\n      <td>-0.03</td>\n      <td>-0.19</td>\n      <td>-0.16</td>\n    </tr>\n    <tr>\n      <th>Estrato SE</th>\n      <td>0.82</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>0.04</td>\n      <td>0.02</td>\n      <td>0.05</td>\n      <td>0.05</td>\n    </tr>\n    <tr>\n      <th>SISBEN score</th>\n      <td>12.19</td>\n      <td>-0.55</td>\n      <td>-0.45</td>\n      <td>1.28</td>\n      <td>-0.10</td>\n      <td>-1.83</td>\n      <td>-1.73</td>\n    </tr>\n    <tr>\n      <th>SISBEN score SE</th>\n      <td>4.62</td>\n      <td>0.12</td>\n      <td>0.13</td>\n      <td>0.23</td>\n      <td>0.10</td>\n      <td>0.26</td>\n      <td>0.25</td>\n    </tr>\n    <tr>\n      <th>Household income (1,000 pesos)</th>\n      <td>375.73</td>\n      <td>-13.76</td>\n      <td>-9.39</td>\n      <td>29.47</td>\n      <td>-4.37</td>\n      <td>-43.23</td>\n      <td>-38.86</td>\n    </tr>\n    <tr>\n      <th>Household income (1,000 pesos) SE</th>\n      <td>240.07</td>\n      <td>5.85</td>\n      <td>6.10</td>\n      <td>7.15</td>\n      <td>6.64</td>\n      <td>8.41</td>\n      <td>8.71</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThe table provides 90 differences. 45 are statistically significant at the 1 percent level, 57 at the 5 percent level and 59 at the 10 percent level. Between the basic and the savings treatment group only 2 differences are statistically significant (one at the 1 percent level and two at the 5 percent level), which we already have seen in table 2. Out of the remaining 75 differences, 57 are statistically significant at the 10 percent level, 55 at the 5 percent level and 44 at the 1 percent level. One can conclude that the treatment and control groups in both localities together are not similar regarding these characteristics. This suggests, that simple estimates of regressing outcome variables on the treatment might be biased and the back-door paths have to be eliminated.\n\n## 6.2. Elimination of Back-door Paths Controlling only for Locality\nIn order to eliminate the back-door paths Barrera-Osorio et al. (2011) control for the locality of the households and a large set of observable demographic characteristics. However, all three back-door paths should be eliminated by simply controling for the locality in which the family lives, since within the localities treatment assignment is random. In the following, I estimate the effects of all three treatments together on attendence and enrollment rates only controlling for the locality. Table 7 shows the results of this regression. I compare my results with those presented in the last column of table 3, respectively table 4. \n\n#### Table 8 - Effects on Attendence and Re-enrollment only Controlling for the Locality\n\n\n```python\ncreate_table8(sample)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Attendence</th>\n      <th>Enrollment</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Basic treatment</th>\n      <td>0.023</td>\n      <td>0.004</td>\n    </tr>\n    <tr>\n      <th>Basic treatment SE</th>\n      <td>0.011</td>\n      <td>0.014</td>\n    </tr>\n    <tr>\n      <th>Savings treatment</th>\n      <td>0.028</td>\n      <td>0.024</td>\n    </tr>\n    <tr>\n      <th>Savings treatment SE</th>\n      <td>0.011</td>\n      <td>0.019</td>\n    </tr>\n    <tr>\n      <th>Tertiary treatment</th>\n      <td>0.052</td>\n      <td>0.042</td>\n    </tr>\n    <tr>\n      <th>Tertiary treatment SE</th>\n      <td>0.017</td>\n      <td>0.022</td>\n    </tr>\n    <tr>\n      <th>H0: Basic-Savings F-Stat</th>\n      <td>0.089</td>\n      <td>0.932</td>\n    </tr>\n    <tr>\n      <th>p-value</th>\n      <td>0.767</td>\n      <td>0.335</td>\n    </tr>\n    <tr>\n      <th>H0: Tertiary-Basic F-Stat</th>\n      <td>1.965</td>\n      <td>1.978</td>\n    </tr>\n    <tr>\n      <th>p-value</th>\n      <td>0.168</td>\n      <td>0.161</td>\n    </tr>\n    <tr>\n      <th></th>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <th>Observations</th>\n      <td>2937</td>\n      <td>4775</td>\n    </tr>\n    <tr>\n      <th>R squared</th>\n      <td>0.004</td>\n      <td>0.002</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThese estimates are very similar to those presented in the last column of table 3, respectively table 4. For example, the tertiary treatment here is estimated to increase the attendence rate by 5.2 percentage points, table 3 shows an effect of 5.5 percentage points. The largest difference occurs for the effect of the savings treatment on re-enrollment, which is an increase of 2.5 percentage points compared to 3 when we control for demographics and include school fixed effects. However, the results are statistically significant at the same significance levels as in table 3 and 4. Concerning the difference tests of the treatment effects the results differ more strongly, while in none of the cases they are statistically significant. One can conclude that including demographic characteristics and school fixed effects in addition to controlling for the locality in which the family lives does not change the results of the regression with all three treatments. This can be explained by the fact that the back-door paths are blocked by adding the locality to the regression.\n\n---\n# 7. Conclusion\n---\n\nThe results in this notebook support the findings reported in the paper by Barrera-Osorio et al. (2011). I reproduced the results precisely for almost all tables except for the third and sixth column of table 6 for which I could only produce similar results. In addition to the replication of the main results from Barrera-Osorio et al. (2011), I critically discuss the quality of their strategy and estimations and evaluate the robustness of their results. Comparing mean characteristics between the research groups across the two experiments, I find that the groups are different. This indicates that their identification assumption, which is that treatments are assigned randomly, is violated and estimates from the regressions, where all three treatments are included, might be biased. Barrera-Osorio et al. (2011) include demographic controls and school fixed effects in the regression in order to rule out potential biases. However, evaluating the causal graph I provide in section 2 one can conclude that including the locality into the regression equation eliminates all three back-door paths. Running this regression I find similar results as Barrera-Osorio et al. (2011). However, the fact that estimates of the effects of the basic and savings treatment are very different when the tertiary treatment is included in the regression or not, indicates a bias. Further analysis of the difference of the basic and savings treatment compared to the tertiary treatment might be helpful to provide more precise policy implications.  \n\nAdditionally, the study focuses only on the effects of the conditional cash transfers on the children included in the experiment in the two localities. It might be the case that the children who registered and are eligible for the experiment yield higher outcomes than those who did not register or are not eligible. This raises the question whether external validity of the results is given. Further research may address this issue.  \n\nOverall, the findings from Barrera-Osorio et al. (2011) offer credible results and policy implications regarding the design of education-based conditional cash transfers.\n\n---\n# 8. References\n---\n\n* **Barrera-Osorio, Felipe, Marianne Bertrand, Leigh L. Linden, and Francisco Perez-Calle (2011)**. \"Improving the Design of Conditional Transfer Programs: Evidence from a Randomized Education Experiment in Colombia.\" *American Economic Journal: Applied Economics*, 3 (2): 167-95. \n", "meta": {"hexsha": "ad725ba4f93b83d3de0749f977052f11cf4cb453", "size": 120353, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "replication-notebook.ipynb", "max_stars_repo_name": "juwilhel/Replication-of-Barrera-Osorio-Felipe-Marianne-Bertrand-Leigh-L.-Linden-and-Francisco-Perez-Calle", "max_stars_repo_head_hexsha": "c4df6c9d4195a7b5f6b4eab86c4737e492152ebb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "replication-notebook.ipynb", "max_issues_repo_name": "juwilhel/Replication-of-Barrera-Osorio-Felipe-Marianne-Bertrand-Leigh-L.-Linden-and-Francisco-Perez-Calle", "max_issues_repo_head_hexsha": "c4df6c9d4195a7b5f6b4eab86c4737e492152ebb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "replication-notebook.ipynb", "max_forks_repo_name": "juwilhel/Replication-of-Barrera-Osorio-Felipe-Marianne-Bertrand-Leigh-L.-Linden-and-Francisco-Perez-Calle", "max_forks_repo_head_hexsha": "c4df6c9d4195a7b5f6b4eab86c4737e492152ebb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.9876395534, "max_line_length": 2726, "alphanum_fraction": 0.417987088, "converted": true, "num_tokens": 18341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510527095787247, "lm_q2_score": 0.12421302132013365, "lm_q1q2_score": 0.042866568379180715}}
{"text": "# O que \u00e9 machine learning?\n\nMachine learning, ou aprendizado de m\u00e1quinas, \u00e9 o desenvolvimento de algoritmos gen\u00e9ricos que conseguem identificar e aprender coisas sobre um determinado monte de dados sem ser explicitamente programado para tal.\n\nAo inv\u00e9s de escrever decis\u00f5es l\u00f3gicas, voc\u00ea alimenta seu algor\u00edtmo com dados e ele decide como interpretar aquilo e tomar decis\u00f5es em cima dos dados.\n\nPor exemplo, voc\u00ea pode alimentar um algoritmo com dados sobre n\u00fameros escritos \u00e0 m\u00e3o e pedir que ele identifique novos n\u00fameros. Voc\u00ea pode, tamb\u00e9m, alimentar esse mesmo algoritmo com dados sobre emails que s\u00e3o spam e n\u00e3o spam e pedir que ele identifique novos emails.\n\n\n\n# Tipos de machine learning\nMachine learning \u00e9 um campo vasto. As 3 sub-\u00e1reas mais comuns s\u00e3o, por\u00e9m, **aprendizado supervisionado**, **n\u00e3o supervisionado** e **de refor\u00e7o**.\n\nNessa primeira aula vamos focar no primeiro tipo. Na pr\u00f3xima, falaremos de t\u00e9cnicas de otimiza\u00e7\u00e3o e do segundo. O terceiro tipo est\u00e1 fora do escopo dessas aulas.\n\nEsses 3 tipo s\u00e3o definidos mais ou menos assim:\n\n## Aprendizado supervisionado\nPara ilustrar o conceito, vamos pensar em um exemplo.\n\nDigamos que estamos nos anos 90 e voc\u00ea trabalha em uma locadora de filmes. Sua locadora \u00e9 diferenciada porque voc\u00eas costumam recomendar filmes para os seus clientes. Contudo, voc\u00ea percebe que tem um grande problema quando voc\u00eas contratam algu\u00e9m novo. Esse novo empregado n\u00e3o conhece todos os filmes da sua locadora e, por isso, n\u00e3o consegue recomendar muitos filmes para os clientes. Voc\u00ea descobre que voc\u00eas t\u00eam uma tabela com v\u00e1rias informa\u00e7\u00f5es como g\u00eanero, ano, dura\u00e7\u00e3o e v\u00e1rios outras caracter\u00edsticas dos filmes. Voc\u00ea tamb\u00e9m sabe que t\u00eam uma tabela com os \u00faltimos filmes que todos os seus clientes alugaram.\n\nVoc\u00ea decide ent\u00e3o escrever um programa que tenta recomendar filmes para os seus clientes com base no que eles costumam assistir.\n\n\n\n\nVoc\u00eas ent\u00e3o recebem um filme novo, Rei le\u00e3o, e devem decidir quem seria o cliente que mais gostaria daquele filme:\n\n\n\n\nIsso \u00e9 aprendizado supervisionado. Voc\u00ea entendeu o padr\u00e3o e foi capaz de encontrar qual a pessoa que poderia gostar mais desse filme. Nesse caso, talvez o ano ou nome n\u00e3o fa\u00e7am muita diferen\u00e7a, mas em casos mais complexos, como a previs\u00e3o de pre\u00e7os de casas ou de m\u00fasicas, seja necess\u00e1rio mais c\u00e1lculos.\n\nO seu algoritmo tem que ser capaz de ir al\u00e9m desses dados e generalizar as caracter\u00edsticas para decidir.\n\nEm aprendizado supervisionado voc\u00ea deixa o computador descobrir essa l\u00f3gica para voc\u00ea e, com ela, ele \u00e9 capaz de fazer previs\u00f5es e trabalhar com dados novos.\n\n## Aprendizado n\u00e3o supervisionado\n\nEm aprendizado supervisionado n\u00f3s n\u00e3o temos o que cada filme **\u00e9**. Temos apenas dados e temos que extrair informa\u00e7\u00f5es deles. Em nosso exemplo anterior, n\u00f3s podemos aplicar algoritmos de aprendizado n\u00e3o supervisionado para identificar mercados nos filmes. Podemos usar as idades dos clientes para descobrir que g\u00eaneros de filmes s\u00e3o mais populares com que faixas et\u00e1rias, descobrir se homens gostam mais de filmes de a\u00e7\u00e3o que mulheres e at\u00e9 fazer an\u00e1lises ao longo do tempo pra saber exatamente onde e como devemos promover um filme para obter o m\u00e1ximo poss\u00edvel de clientes interessados.\n\n## Aprendizado de refor\u00e7o\n\nAprendizado de refor\u00e7o \u00e9 muito menos sobre previs\u00f5es e muito mais sobre resultados. Usamos aprendizado de refor\u00e7o quando queremos criar algoritmos novos que atingem o melhor resultado poss\u00edvel.\n\nDigamos que queremos manter um cliente sendo fiel durante muito tempo. Para isso n\u00f3s mandamos emails de recomenda\u00e7\u00e3o e enviamos presentes de vez em quando para manter ele interessado em n\u00f3s. Por\u00e9m, n\u00e3o queremos que ele sinta que estamos for\u00e7ando a barra. Como encontrar esse equilibrio?\n\nPrimeiro criamos um algoritmo que decide quando enviar um email ou um presente. A partir da\u00ed, come\u00e7amos a mandar emails e presentes e avaliar a resposta dos clientes. Sempre que um cliente sai da nossa lista de email n\u00f3s dizemos pro algoritmo que ele fez besteira. Sempre que ele recomenda o nosso sistema para algu\u00e9m, dizemos que ele fez bem. Ao longo do tempo ele come\u00e7a a aprender quais padr\u00f5es de presentes e emails rendem mais \"elogios\" e menos \"cr\u00edticas\". N\u00f3s usamos essas reflex\u00f5es para **refor\u00e7ar comportamentos** que s\u00e3o bons ou ruins e incentivamos os algoritmos a se melhorarem e se adaptarem. Isso \u00e9 diferente de um algoritmo supervisionado pois o feedback pode demorar meses para vir e o algoritmo tem que ser capaz de refletir sobre suas a\u00e7\u00f5es e experimentar coisas novas para **otimizar** seus resultados.\n\n\nAgora que j\u00e1 vimos um pouco sobre eles, vamos mais a fundo em algortimos supervisionados.\n\n# Introdu\u00e7\u00e3o ao aprendizado supervisionado\n\nOk, j\u00e1 vimos a teoria, agora vamos escrever um programa que encontre filmes para a gente!\n\nSe voc\u00ea n\u00e3o soubesse nada sobre aprendizado de m\u00e1quinas, talvez escrevesse um programa mais ou menos assim:\n\n```Python\ndef recomendar_filme(filme, ano, g\u00eanero, lista_de_filmes):\n    \n    # Encontra os filmes que tem o mesmo genero do filme novo\n    filmes_com_mesmo_genero = filter(lambda x: x['g\u00eanero'] == g\u00eanero, lista_de_filmes)\n    \n    # Dentro desses, acha os que tem o um ano pr\u00f3ximo\n    filmes_ano_proximo = filter(lambda x: ano + 5 >= x['ano'] >= ano - 5, filmes_com_mesmo_genero)\n    \n    # Desses encontrados, pegar o cliente que alugou um desses filmes e recomendar pra ele\n    cliente = filmes_ano_proximo[0]['cliente']\n    return cliente\n```\n\nSe voc\u00ea ficar mexendo bastante nisso por horas talvez consiga alguma coisa que funcione, mas seu programa nunca ser\u00e1 perfeito e sempre ter\u00e1 que alterar alguma coisa pra filmes novos.\n\nO ideal seria simplesmente pedir que o computador fizesse tudo pra voc\u00ea\n\n```Python\ndef recomendar_filme(filme, ano, g\u00eanero, lista_de_filmes):\n    cliente = <computador, por favor, faz esses c\u00e1lculos por mim>\n    \n    return cliente\n```\n\nO que ele vai fazer na verdade \u00e9 transformar esses valores que n\u00f3s criamos, g\u00eaneros, anos e tal em **vetores em um hiperespa\u00e7o** que pode ser representado por n\u00fameros.\n\nNo fim o que o computador vai gerar \u00e9 algo como:\n\n```Python\ndef recomendar_filme(filme, ano, g\u00eanero, lista_de_filmes):\n    vetor_g\u00eanero = *vetorizador_g\u00eanero(g\u00eanero) * [63.61124, .053823, 23.23521, 294.43213, .000123, 1.]\n    \n    vetor_ano = *vetorizador_ano(ano) * [54.2421543, .00342, 5143532.3415]\n    \n    vetor_cliente = 873.5323 + vetor_g\u00eanero + vetor_ano\n    \n    cliente = distribui\u00e7\u00e3o_prob(lista_de_filmes, vetor_cliente)\n    \n    return cliente\n```\n\nTodos esses valores nas listas s\u00e3o o que chamamos de **pesos**. Eles s\u00e3o gerados **aleatoriamente** pelo computador e testados milhares de vezes at\u00e9 que o valor que obtem o **menor erro** seja encontrado. Como podem ver, s\u00e3o vetores multi dimensionais que podem ter, na verdade, centenas de dimens\u00f5es. Cada dimens\u00e3o representa um ano ou g\u00eanero de filme e os pesos representam a intera\u00e7\u00e3o entre eles.\n\nNo fim n\u00f3s podemos usar uma distribui\u00e7\u00e3o probabil\u00edstica para encontrar o cliente que teria a maior probabilidade de gostar do filme que estamos analisando.\n\n\u00c9 imporante ressaltar que os valores iniciais desses pesos s\u00e3o aleat\u00f3rios. Para encontrar os valores finais, existem diversas t\u00e9cnicas de otimiza\u00e7\u00e3o que, eventualmente, tendem a reduzir o erro total do sistema a um m\u00ednimo.\n\nPara calcular esse erro, podemos usar uma fun\u00e7\u00e3o de **custo** que define a **dist\u00e2ncia** entre o valor previsto e o valor definido como correto (a\u00ed est\u00e1, novamente, por que estamos usando aprendizado supervisionado).\n\nA **fun\u00e7\u00e3o de custo** pode tomar diversas formas, mas a mais comum e talvez a mais simples \u00e9 a **soma do erro quadrado**, onde por erro n\u00f3s definimos a dist\u00e2ncia probabil\u00edstica at\u00e9 o valor correto.\n\n\\begin{align}\nCusto = \\frac{\\sum_{i=1}^n \\left( meu\\_chute(i) - valor\\_real(i) \\right)^2}{2n}\n\\end{align}\n\nVamos agora reescrever essa fun\u00e7\u00e3o usando alguns jarg\u00f5es de machine learning que voc\u00ea n\u00e3o tem que se preocupar agora\n\n\\begin{align}\nJ(\\theta) = \\frac{1}{2m}\\sum_{i=0}^m \\left( h_\\theta(x^{(i)}) - y^{(i)} \\right)^2\n\\end{align}\n\nOnde $\\theta$ representa os **pesos** e $J(\\theta)$ o **custo para os pesos atuais**\n\nSe n\u00f3s fizermos um gr\u00e1fico dos pesos, teremos algo assim:\n\n\n\nOnde o eixo vertical representa o valor do custo dados os pesos nos eixos horizontais.\n\nNesse gr\u00e1fico, o que queremos fazer \u00e9 reduzir ao m\u00ednimo o nosso custo (erro). Para isso usamos t\u00e9cnicas de otimiza\u00e7\u00e3o, onde fazemos algo assim:\n\n\n\n\nPara isso n\u00f3s precisamos ajustar nossos pesos de forma que estejamos 'descendo a ladeira' em dire\u00e7\u00e3o ao m\u00ednimo.\n\nTer o erro m\u00ednimo significa estar o mais pr\u00f3ximo poss\u00edvel, teoreticamente, da previs\u00e3o perfeita.\n\nSe voc\u00ea lembra algo de c\u00e1lculo, deve saber que se n\u00f3s pegarmos a derivada de uma fun\u00e7\u00e3o em cada vari\u00e1vel e somarmos, obtemos uma outra fun\u00e7\u00e3o cujo valor define a dire\u00e7\u00e3o de crescimento m\u00e1ximo. ([gradiente](https://en.wikipedia.org/wiki/Gradient))\n\n\\begin{align}\n\\nabla f(x, y) = \\frac{\\partial f}{\\partial x} i + \\frac{\\partial f}{\\partial y} j\n\\end{align}\n\nEsse \u00e9 um m\u00e9todo de otimiza\u00e7\u00e3o simples, mas eficiente, que nos permite rapidamente encontrar os valores de peso m\u00ednimo de nossa fu\u00e7\u00e3o de custo e, logo, o **estado mais otimizado do nosso modelo**.\n\nIsso \u00e9 apenas uma introdu\u00e7\u00e3o, ent\u00e3o n\u00e3o vamos ir mais fundo que isso, mas sinta-se livre para [aprender mais caso queira](http://hbfs.wordpress.com/2012/04/24/introduction-to-gradient-descent/).\n\nN\u00e3o se preocupe, por\u00e9m, em ter tudo isso na cabe\u00e7a. Quando voc\u00ea usar uma biblioteca de machine learning tudo isso ser\u00e1 **feito pela biblioteca, n\u00e3o por voc\u00ea**. Por\u00e9m \u00e9 importante ter uma no\u00e7\u00e3o do que est\u00e1 acontecendo.\n\n## O que acabamos de aprender?\n\nIsso tudo que n\u00f3s vimos \u00e9 o funcionamento de uma **regress\u00e3o linear multivariacional**. Vamos ver isso novamente mais pra frente do curso, incluindo alguns conceitos como **overfitting**, **tend\u00eancia, ou bias**, **valida\u00e7\u00e3o** e outras coisas.\n\nSaiba, por\u00e9m, que nem sempre ser\u00e1 poss\u00edvel usar esses algoritmos para prever essas coisas. Isso acontece porque muitas vezes as rela\u00e7\u00f5es entre essa vari\u00e1veis (ano/g\u00eanero) n\u00e3o s\u00e3o lineares. Para esses outros casos n\u00f3s teremos que usar outros **modelos** e at\u00e9 outras t\u00e9cnicas. Veremos tudo isso mais pra frente.\n\n## Aprendizado de m\u00e1quinas \u00e9 m\u00e1gica?\nAssim que n\u00f3s come\u00e7armos a aplicar machine learning para solucionar alguns problemas, come\u00e7aremos a perceber que \u00e9 muito f\u00e1cil solucionar problemas que parecem ser muito dif\u00edceis de se resolver de outra forma.\n\n\u00c9 importante notar, por\u00e9m, que aprendizado de m\u00e1quinas s\u00f3 funciona para resolver problemas que **podem ser resolvidos**.\n\nPor exemplo, n\u00e3o \u00e9 poss\u00edvel determinar o tipo de filme que algu\u00e9m gosta baseado na ra\u00e7a de cachorro que essa pessoa tem. N\u00e3o importa o quanto voc\u00ea altere seu algoritmo e o qu\u00e3o bons os seus resultados fiquem para o dataset de treino, ser\u00e1 imposs\u00edvel ter uma boa valida\u00e7\u00e3o fora disso. Seu modelo sofrer\u00e1 de overfitting e voc\u00ea precisar\u00e1 de outras caracter\u00edsticas para resolver esse problema.\n\n\n\n\nCom isso n\u00f3s conclu\u00edmos nossa introdu\u00e7\u00e3o ao ML. Agora vamos come\u00e7ar a programar algumas coisas e fazer ML de verdade!\n\n# Programando Machine Learning\n\nPara programar e usar machine learning, vamos usar uma biblioteca de ML muito famosa chamada SKLearn. Ela cont\u00e9m centenas de modelos e algoritmos de classifica\u00e7\u00e3o, regress\u00e3o, clusteriza\u00e7\u00e3o e muito mais.\n\nVoc\u00ea pode ler sobre o projeto no site deles:\n[http://scikit-learn.org/stable/](http://scikit-learn.org/stable/)\n\n\n\n\n## Algoritmos e superficies de decis\u00e3o\n\nGeralmente n\u00f3s conseguimos plotar nossos dados em gr\u00e1ficos, onde cada eixo representa uma caracter\u00edstica dos dados e cada ponto um dado espec\u00edfico. Geralmente as cores representam o tipo, ou **label** de cada dado.\n\nPrimeiro vamos definir uma fun\u00e7\u00e3o que gera gr\u00e1ficos para n\u00f3s. Isso vai ser bem \u00fatil no futuro.\n\n\n```python\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\n```\n\n\n```python\ndef generate_data(blue, red, test_size=0.2, func=lambda x: x):\n    \n    blue_x = np.vectorize(func)(np.random.randint(*blue[0]))\n    blue_y = np.vectorize(func)(np.random.randint(*blue[1]))\n    red_x = np.vectorize(func)(np.random.randint(*red[0]))\n    red_y = np.vectorize(func)(np.random.randint(*red[1]))\n    \n    blue_vals = np.dstack((blue_x, blue_y, [\"blue\" for _ in blue_x]))[0]\n    red_vals = np.dstack((red_x, red_y, [\"red\" for _ in red_x]))[0]\n    \n    X = np.append(blue_vals, red_vals, axis=0)\n    \n    Y = [1 for _ in range(len(blue_vals))]\n    Y.extend([0 for _ in range(len(red_vals))])\n    \n    return train_test_split(X, Y, test_size=test_size)\n```\n\n\n```python\nX_train, X_test, y_train, y_test = generate_data([[0, 40, 100], [0, 40, 100]], [[50, 100, 100], [50, 100, 100]])\n\nplt.scatter(X_train[:, 0], X_train[:, 1], c=X_train[:, 2])\nplt.show()\n```\n\nComo pode ver, n\u00f3s temos dados separados no que s\u00e3o claramente objetos diferentes. \u00c9 muito f\u00e1cil criar uma barreira que separa os dois clusters.\n\nDepois de separar, fica bem f\u00e1cil assumir que tudo que estiver de um lado dela ser\u00e1 azul e do outro vermelho. Essa barreira se chama uma **superf\u00edcie de decis\u00e3o** e \u00e9 um dos conceitos principais quando lidamos com algoritmos de classifica\u00e7\u00e3o.\n\nAgora vamos ver um algoritmo de classifica\u00e7\u00e3o e experimentar com ele.\n\n# Naive Bayes\nPara o nosso primeiro modelo de aprendizado supervisionado, aprenderemos um modelo de classifica\u00e7\u00e3o probabil\u00edstico chamado Naive Bayes, que vem de um homem religioso chamado Bayes que criou o teorema de Bayes para provar a exist\u00eancia de Deus.\n\nO algoritmo, como o nome sugere, usa o [Teorema de Bayes](https://en.wikipedia.org/wiki/Bayes%27_theorem) para descobrir a probabilidade de um novo elemento se encaixar numa categoria espec\u00edfica.\n\n\nUsando o SKLearn, nosso c\u00f3digo sempre ter\u00e1 um padr\u00e3o como veremos abaixo.\n\n\n```python\n# Em X_train n\u00f3s temos os nossos dados brutos, suas coordenadas. \n# Em y_train n\u00f3s temos a categoria (1 para azul e 0 para vermelho)\n# N\u00e3o se preocupe com os _test por enquanto\nX_train, X_test, y_train, y_test = generate_data([[0, 40, 100], [0, 40, 100]], [[50, 100, 100], [50, 100, 100]])\n\n# Desses dados, n\u00f3s podemos importar o classificador de Nayve Bayes\nfrom sklearn.naive_bayes import GaussianNB\n\n# Criar um objeto classficador\nclf = GaussianNB()\n\n# E fitar, ou seja, treinar nosso clssificador usando os dados de X_train e y_train\nclf.fit(X_train[:, :2].astype(np.int), y_train)\n```\n\n\n\n\n    GaussianNB(priors=None)\n\n\n\n\n```python\n# Agora n\u00f3s criamos uma outra fun\u00e7\u00e3o que vai criar um gr\u00e1fico e desenhar a nossa superf\u00edcie de decis\u00e3o\nfrom matplotlib.colors import ListedColormap\ndef plot_decision_boundary(clf, X):\n    h = .02\n    cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])\n    cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])\n    # Plot the decision boundary. For that, we will assign a color to each\n    # point in the mesh [x_min, x_max]x[y_min, y_max].\n    x_min, x_max = X[:, 0].astype(np.float).min() - 1, X[:, 0].astype(np.float).max() + 1\n    y_min, y_max = X[:, 1].astype(np.float).min() - 1, X[:, 1].astype(np.float).max() + 1\n    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),\n                         np.arange(y_min, y_max, h))\n    print(\"predicting\")\n    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])\n    print(\"predicted\")\n    print(\"length\", len(Z))\n\n    # Put the result into a color plot\n    Z = Z.reshape(xx.shape)\n    plt.figure()\n    plt.pcolormesh(xx, yy, Z, cmap=cmap_light)\n    print(\"colormesh\")\n\n    # Plot also the training points\n    plt.scatter(X[:, 0].astype(np.float), X[:, 1].astype(np.float), c=X[:, 2])\n    plt.xlim(xx.min(), xx.max())\n    plt.ylim(yy.min(), yy.max())\n    print(\"showing\")     \n    plt.show()\n```\n\n\n```python\n# Finalmente, passamos os argumentos para nossa fun\u00e7\u00e3o\n%time plot_decision_boundary(clf, X_train)\n```\n\nPode demorar um tempo, mas no final voc\u00ea dever\u00e1 ser capaz de ver bem onde exatamente a decis\u00e3o\u00a0\u00e9 feita para separar ambas as cores. Qualquer ponto na zona azul ser\u00e1 previsto por nosso algoritmo como azul e o mesmo vale para a zona vermelha.\n\nN\u00f3s podemos, por exemplo, testar nosso algoritmo:\n\n\n```python\n# Criamos um novo ponto que queremos testar\nnovo_ponto = (0, 75)\n\n# Geramos uma previs\u00e3o para ele. Se sair 1, ser\u00e1 azul e 0 ser\u00e1 vermelho\nprint(clf.predict_proba([novo_ponto]))\n```\n\n    [[ 0.12264511  0.87735489]]\n\n\nExcelente! Temos nosso primeiro classificador. Agora algo importante que devemos fazer \u00e9 testar esse classificador.\n\n## Testando\n\nPara isso, usaremos uma ferramenta muito \u00fatil chamada **matriz de confus\u00e3o**. Essa matriz nos diz exatamente quantos pontos foram corretamente previstos, quantos foram falsos positivos e quantos foram falsos negativos. Para isso, criamos uma fun\u00e7\u00e3o que gera essa matriz para n\u00f3s:\n\n\n```python\nfrom sklearn.metrics import classification_report, confusion_matrix\ndef plot_confusion_matrix(y_true, y_predicted):\n    plt.matshow(confusion_matrix(y_true, y_predicted), cmap=plt.cm.binary, interpolation='nearest')\n    plt.title('Matriz de previs\u00e3o')\n    plt.colorbar()\n    plt.ylabel('Categoria esperada')\n    plt.xlabel('Categoria prevista')\n    plt.show()\n```\n\n\n```python\n# Vamos ver como fica para os dados que usamos para treinar\nplot_confusion_matrix(y_train, clf.predict(X_train[:, :2].astype(np.int)))\n```\n\nEsse formato que estamos vendo \u00e9 o ideal. Ele representa que todos os valores de azul foram previstos corretamente e os de vermelho tamb\u00e9m, sem falsos positivos ou negativos.\n\nN\u00f3s tamb\u00e9m podemos gerar algo chamado **relat\u00f3rio de classifica\u00e7\u00e3o**, que faz exatamente o que o nome sugere:\n\n\n```python\nprint(classification_report(y_train, clf.predict(X_train[:, :2].astype(np.int))))\n```\n\n                 precision    recall  f1-score   support\n    \n              0       1.00      1.00      1.00        76\n              1       1.00      1.00      1.00        84\n    \n    avg / total       1.00      1.00      1.00       160\n    \n\n\nNesse relat\u00f3rio, temos 4 valores:\n\n- **Precis\u00e3o**: Rela\u00e7\u00e3o entre os verdadeiros positivos e o total. Diz o qu\u00e3o preciso foi a classifica\u00e7\u00e3o dado todos os dados\n- **Recall**: Rela\u00e7\u00e3o entre verdadeiros positivos e positivos. Diz o qu\u00e3o certeiro foi a classifica\u00e7\u00e3o para encontrar os positivos\n- **F1-Score**: M\u00e9dia harm\u00f4nica entre precis\u00e3o e recall. Boa forma de avaliar de forma completa a classifica\u00e7\u00e3o\n- **Support**: \u00c9 o n\u00famero de ocorr\u00eancias de cada classe em verdadeiro-positivo\n\nEsses dados s\u00e3o bacanas, mas n\u00e3o s\u00e3o muito interessantes do ponto de vista de previs\u00f5es futuras. O que n\u00f3s queremos acima disso \u00e9 checar se nosso algoritmo \u00e9 capaz de ser generalizado para dados novos.\n\nPara isso vamos usar aquelas vari\u00e1veis que criamos antes: `X_test` e `y_test` que n\u00e3o foram fornecidas ao nosso classificador para treinamento:\n\n\n```python\nplot_confusion_matrix(y_test, clf.predict(X_test[:, :2].astype(np.int)))\nprint(classification_report(y_test, clf.predict(X_test[:, :2].astype(np.int))))\n```\n\nComo pode ver, mesmo assim o nosso algoritmo foi fant\u00e1stico na classifica\u00e7\u00e3o. Isso \u00e9 de se esperar, dado que foram dados bem simples.\n\nVamos testar algo mais complexo agora\n\n\n```python\nX_train, X_test, y_train, y_test = generate_data([[0, 100, 200], [0, 60, 200]], [[00, 100, 250], [20, 100, 250]])\nplt.scatter(X_train[:, 0], X_train[:, 1], c=X_train[:, 2])\nplt.show()\n```\n\nComo pode ver, esse j\u00e1 \u00e9 mais dif\u00edcil pois temos muita intersec\u00e7\u00e3o entre os pontos. Como noss algoritmo vai se sair agora?\n\n\n```python\nclf = GaussianNB()\nclf.fit(X_train[:, :2].astype(np.int), y_train)\nprint(classification_report(y_test, clf.predict(X_test[:, :2].astype(np.int))))\nplot_confusion_matrix(y_test, clf.predict(X_test[:, :2].astype(np.int)))\n%time plot_decision_boundary(clf, X_train)\n```\n\n70% de precis\u00e3o n\u00e3o \u00e9 t\u00e3o bom assim. D\u00e1 pra ver por que foi t\u00e3o ruim.\n\nNossas features n\u00e3o est\u00e3o sendo suficientes para separar corretamente os dados. Para separar, n\u00f3s precisaremos adiconar features novas que, em outras dimens\u00f5es, separem os nossos dados. Uma visualiza\u00e7\u00e3o desse resultado seria:\n\n\n\n```python\nfrom mpl_toolkits.mplot3d import Axes3D\nimport random\n\nfig = plt.figure()\nax = Axes3D(fig)\n\nsequence_containing_x_vals = list(range(0, 50))\nsequence_containing_y_vals = list(range(0, 50))\nsequence_containing_z_vals = list(range(50, 100))\n\nrandom.shuffle(sequence_containing_x_vals)\nrandom.shuffle(sequence_containing_y_vals)\nrandom.shuffle(sequence_containing_z_vals)\n\nax.scatter(sequence_containing_x_vals, sequence_containing_y_vals, sequence_containing_z_vals)\nsequence_containing_x_vals = list(range(50, 100))\nsequence_containing_y_vals = list(range(50, 100))\nsequence_containing_z_vals = list(range(50, 100))\n\nrandom.shuffle(sequence_containing_x_vals)\nrandom.shuffle(sequence_containing_y_vals)\nrandom.shuffle(sequence_containing_z_vals)\n\nax.scatter(sequence_containing_x_vals, sequence_containing_y_vals, sequence_containing_z_vals)\n\nplt.show()\n```\n\n\nAgora vamos sair um pouco de Nayve Bayes e testar outro algoritmo de classifica\u00e7\u00e3o. Esse agora se chama Support Vector Machines e \u00e9 melhor em algumas situa\u00e7\u00f5es em compara\u00e7\u00e3o com o Nayve Bayes.\n\n# Support Vector Machines\n\nPara treinar um SVM, fazemos da mesma forma que faz\u00edamos com NB:\n\n\n```python\nfrom sklearn.svm import SVC\nfrom math import sqrt\n```\n\n\n```python\nX_train, X_test, y_train, y_test = generate_data([[0, 40, 100], [0, 40, 100]], [[50, 100, 100], [50, 100, 100]])\n\nclf = SVC(kernel=\"linear\")\nclf.fit(X_train[:, :2].astype(np.int), y_train)\nprint(classification_report(y_test, clf.predict(X_test[:, :2].astype(np.int))))\nplot_confusion_matrix(y_test, clf.predict(X_test[:, :2].astype(np.int)))\n%time plot_decision_boundary(clf, X_train)\n```\n\nComo podem ver, \u00e9 bem parecido com o NB, mas \u00e9 mais linear.\n\nO que acontece quando nossa barreira de classifica\u00e7\u00e3o n\u00e3o \u00e9 separavel linearmente?\n\n\n```python\ndef generate_circular_data(min_radius, med_radius, max_radius, d1=100, d2=100, test_size=0.2, func=lambda x: x):\n    \n    x1 = np.random.uniform(-min_radius, min_radius, d1)\n    y1 = []\n    for i in x1:\n        yy = np.random.uniform(0, sqrt(min_radius**2 - i**2))\n        if random.choice([True, False]):\n            yy = -yy\n        y1.append(yy)\n\n    x2 = np.random.uniform(-max_radius, max_radius, d2)\n    y2 = []\n    for i in x2:\n        low = sqrt(med_radius**2 - i**2) if med_radius**2 - i**2 > 0 else 0\n        yy = np.random.uniform(low, sqrt(max_radius**2 - i**2))\n        if random.choice([True, False]):\n            yy = -yy\n        y2.append(yy)\n    \n    blue_vals = np.dstack((np.vectorize(func)(x1), np.vectorize(func)(y1), [\"blue\" for _ in x1]))[0]\n    red_vals = np.dstack((np.vectorize(func)(x2), np.vectorize(func)(y2), [\"red\" for _ in x2]))[0]\n    \n    X = np.append(blue_vals, red_vals, axis=0)\n    \n    Y = [1 for _ in range(len(blue_vals))]\n    Y.extend([0 for _ in range(len(red_vals))])\n    \n    return train_test_split(X, Y, test_size=test_size)\n```\n\n\n```python\nX_train, X_test, y_train, y_test = generate_circular_data(10, 15, 20, 100, 200)\n\nplt.scatter(X_train[:, 0], X_train[:, 1], c=X_train[:, 2])\nplt.show()\n```\n\n\n```python\nclf = SVC(kernel=\"linear\")\nclf.fit(X_train[:, :2].astype(np.float), y_train)\nprint(classification_report(y_test, clf.predict(X_test[:, :2].astype(np.float))))\nplot_confusion_matrix(y_test, clf.predict(X_test[:, :2].astype(np.float)))\n%time plot_decision_boundary(clf, X_train)\n```\n\n\u00c9 facil perceber que essa barreira ser\u00e1 dif\u00edcil pro nosso SVM classifier. O que podemos fazer ent\u00e3o?\n\nPodemos criar features novas a partir das anteriores. Nesse caso, podemos criar uma feature que representa o **quadrado das vari\u00e1veis**.\n\n\n```python\nsquare = lambda x: x**2\n\nX_train, X_test, y_train, y_test = generate_circular_data(10, 15, 20, 100, 200, func=square)\n\nplt.scatter(X_train[:, 0], X_train[:, 1], c=X_train[:, 2])\nplt.show()\n```\n\nE, finalmente, podemos testar nosso classificador usando essas features novas\n\n\n```python\nclf = SVC(kernel=\"linear\")\nclf.fit(X_train[:, :2].astype(np.float), y_train)\nprint(classification_report(y_test, clf.predict(X_test[:, :2].astype(np.float))))\nplot_confusion_matrix(y_test, clf.predict(X_test[:, :2].astype(np.float)))\n%time plot_decision_boundary(clf, X_train)\n```\n\nDe fato, \u00e9 isso que o SVC \u00e9 capaz de fazer sozinho. Ao contr\u00e1rio do NB, o SVC \u00e9 capaz de usar **truques de kernel** para explorar vari\u00e1veis novas e configura\u00e7\u00f5es novas de vari\u00e1veis. Experimentemos rodar o c\u00f3digo para o gr\u00e1fico circular, mas com a kernel sendo a padr\u00e3o:\n\n\n```python\nX_train, X_test, y_train, y_test = generate_circular_data(10, 15, 20, 100, 200)\n\nplt.scatter(X_train[:, 0], X_train[:, 1], c=X_train[:, 2])\nplt.show()\n\nclf = SVC()\nclf.fit(X_train[:, :2].astype(np.float), y_train)\nprint(classification_report(y_test, clf.predict(X_test[:, :2].astype(np.float))))\nplot_confusion_matrix(y_test, clf.predict(X_test[:, :2].astype(np.float)))\n%time plot_decision_boundary(clf, X_train)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "095f2b214335dd687c161a0656190be85dee738f", "size": 572787, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "aula_ds_pt_1/notebooks/curso.ipynb", "max_stars_repo_name": "Maronato/cursos_cetax", "max_stars_repo_head_hexsha": "cf15f5541464ba3d12617620f80e207a371d6dbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-30T21:11:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-30T21:11:46.000Z", "max_issues_repo_path": "aula_ds_pt_1/notebooks/curso.ipynb", "max_issues_repo_name": "Maronato/cursos_cetax", "max_issues_repo_head_hexsha": "cf15f5541464ba3d12617620f80e207a371d6dbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aula_ds_pt_1/notebooks/curso.ipynb", "max_forks_repo_name": "Maronato/cursos_cetax", "max_forks_repo_head_hexsha": "cf15f5541464ba3d12617620f80e207a371d6dbe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 487.8935264055, "max_line_length": 64156, "alphanum_fraction": 0.9270007874, "converted": true, "num_tokens": 6774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.1052105444185657, "lm_q1q2_score": 0.04285576877869774}}
{"text": "<font size = \"5\"> **Chapter 2: [Diffraction](CH2_00-Diffraction.ipynb)** </font>\n\n<hr style=\"height:1px;border-top:4px solid #FF8200\" />\n\n# Bethe Theory\n\n[Download](https://raw.githubusercontent.com/gduscher/MSE672-Introduction-to-TEM//main/Diffraction/CCH2_D01-Bloch.ipynb)\n \n[](\n    https://colab.research.google.com/github/gduscher/MSE672-Introduction-to-TEM/blob/main/Diffraction/CH2_D01-Bloch.ipynb)\n\n\n\npart of \n\n<font size = \"5\"> **[MSE672:  Introduction to Transmission Electron Microscopy](../_MSE672_Intro_TEM.ipynb)**</font>\n\nby Gerd Duscher, Spring 2021\n\nMicroscopy Facilities<br>\nJoint Institute of Advanced Materials<br>\nMaterials Science & Engineering<br>\nThe University of Tennessee, Knoxville\n\nBackground and methods to analysis and quantification of data acquired with transmission electron microscopes\n\n\n## Import numerical and plotting python packages\nImport the python packages that we will use:\n\nBeside the basic numerical (numpy) and plotting (pylab of matplotlib) libraries,\n\n\n\n```python\nimport sys\nif 'google.colab' in sys.modules:\n    %pylab --no-import-all inline\nelse:\n    %pylab --no-import-all notebook\n```\n\n    Populating the interactive namespace from numpy and matplotlib\n\n\n\n## Notation\n\nIn the following I will introduce this Bethe diffraction theory in Dirac's  bra--ket notation.\n\\begin{eqnarray*}\n|\\psi\\rangle &=& \\mbox{ket} = \\psi_1 |1\\rangle + \\psi_2 |2\\rangle\\\\\n&=& \\left( \\begin{array}{c} \\psi_1 \\\\\\psi_2  \\end{array} \\right)= \\mbox{column vector}\\\\\n\\langle \\phi| &=& \\mbox{bra} = \\phi^*_1\\langle 1|  + \\phi^*_2 \\langle 2|\\\\\n&=& \\left( \\phi^*_1 ,\\phi^*_2 \\right)= \\mbox{row vector}\n\\end{eqnarray*}\n\nConsequently the Dirac bracket is:\n\\begin{equation*}\n\\langle \\phi|\\psi\\rangle = \\left( \\phi^*_1 ,\\phi^*_2 \\right) \\left( \\begin{array}{c} \\psi_1 \\\\\\psi_2  \\end{array} \\right) = \\phi^*_1 \\psi_1 +\\phi^*_2 \\psi_2\n\\end{equation*}\n\nSimilarly \n\n\\begin{equation*}\n|\\psi\\rangle \\langle \\phi| = \\mbox {a matrix}\n\\end{equation*}\nand this will make it easier to follow the equations of many beams in diffraction, which otherwise can become very messy.\n\nThroughout this chapter we will use the notation for the wave vector common in solid state physics and not the one found in many crystallography books ($k=1/\\lambda$):\n\\begin{equation}\\label{vector}\nk = \\frac{2\\pi}{\\lambda} = \\frac{\\sqrt{2meE}}{\\hbar}\n\\end{equation} \nwith:\n- $\\lambda$: wavelength\n- $m=\\gamma_0$: relativistically corrected mass of the electron\n- $\\gamma = 1+\\frac{e^2E^2}{2m_0c^2}$: relativistic correction necessary for $E$ above 2kV \n- $e$: electron charge\n- $E$: acceleration voltage\n- $c$: speed of light in vacuum\n\nThis is the short version of quantum mechanics. The Axioms of quantum mechanics are:\n\n\n1. The state of a system is described by its state vector $|\\psi\\rangle$.\n\n2. An observables are expressed by hermitic operators $A$\n3. The mean value of an observable is given by $\\langle A \\rangle$\n4. The time dependence is given by the time-dependent Schr\u00f6dinger  \n    equation: $ H|\\psi,t\\rangle = i\\hbar \\frac{\\partial}{\\partial t} |\\psi,t\\rangle $\n5. If you measure $A$ the system changes to $|n\\rangle$ if $a_n$ was measured\n\nAxioms 2. and 3. give:\n\nIf a system is in the state $|\\psi\\rangle = \\sum_n c_n |n\\rangle$\n\nwith $c_n = \\langle n|\\psi\\rangle$, where $|n\\rangle$ are the Eigen states of $A$, meaning $A|n\\rangle = a_n |n\\rangle$. The probability to find the value $a_n$ when measuring $A$ is given by $|c_n|^2$.\n\n## Introduction to Bethe Theory\n\nThe dynamic theory calculates the probability of a transition from an initial state $|i\\rangle$ to a final state $|f\\rangle$. In our case, the initial state $|i\\rangle$ is the incoming beam which scatters to a final state the Bragg reflection $|f\\rangle$.\nWhat we want to know is the transition probability from the initial to the final state:\n\\begin{equation}\n\\omega_{i\\rightarrow f} =  \\langle i |T|f\\rangle \n\\end{equation}\nthe initial state is the beam with wave vector $\\vec{k}_0$ and the end state is a wave-vector of diffracted beam according to Bragg's law $\\vec{q} = \\vec{g}$.\nThe above equation now looks like this:\n\\begin{equation}\n\\omega_{0\\rightarrow g} = \\langle 0 |T|g\\rangle \n\\end{equation}\n\nFor the stationary problems the states $|\\psi,t\\rangle$ can be expressed as:\\\\\n\\begin{equation} \n|\\psi_n,t\\rangle = \\exp(-E_nt/\\hbar) |\\psi_n\\rangle\n\\end{equation}\nand we get the time-independent Schr\u00f6inger equation for $|\\psi_n\\rangle$:\n\\begin{equation}\nH|\\psi_n\\rangle = E_n |\\psi_n \\rangle\n\\end{equation}\n\nFor the incoming wave, we get:\n\n\\begin{equation}\nH_0 = { -\\frac{h^2}{8\\pi^2} \\nabla^2 }\n\\end{equation} \nwhich expresses the kinetic energy.\n\nWithin a crystal the Hamiltonian will change to:\n\\begin{equation}  \nH = H_0 + V\n\\end{equation} \nWe have  the Schr\u00f6dinger equation for the incoming wave:\n\\begin{equation}  \\label{IncomingWave}\n(H_0 ) |\\vec{k}\\rangle = E_k |\\vec{k}\\rangle\n\\end{equation}\n\nand we want to solve: \n\\begin{equation}\n(H_0 +V) |\\psi\\rangle = E_k |\\psi\\rangle\n\\end{equation}\n\nwhich we transform with equation \\ref{IncomingWave}:\n\n\n> Effectively, we changed in the integral equation.\n\n\\begin{equation*} \n|\\psi\\rangle = |\\vec{k}\\rangle + \\frac{1}{E_k -H_0}V|\\psi\\rangle\n\\end{equation*} \n\n### Hamiltonian in Bethe Theory\nFor our diffraction experiment is often better to use a Hamiltonian that contains the wave vector:\n\\begin{equation} \nH_0 = { -\\Delta_\\rho -\\xi^2 }\n\\end{equation} \n\nOOps, where is the wavevector $\\vec{k}$? \n\nI replaced it by $\\xi$ which is the effective deviation from wavevector $\\vec{k}$\n\nWe also take into account that our electrons are very fast and distort the space, reducing the problem to two dimensions ($\\rho = (x,y)$.\nThe crystal potential V has then to be changed as well to:\n\\begin{equation}\nV = V(\\rho,z)\n\\end{equation} \nand the full Hamiltonian is changed to:\n\\begin{equation}\nH = \\frac{1}{k_z} (H_0 + V(\\rho,z)\n\\end{equation} \n\nThe time- independent wave equation is then:\n\\begin{equation}\n\\nabla^2 \\psi  + k^2 \\psi = 0\n\\end{equation}\nwith the plane wave solution:\n\\begin{equation}\n\\psi  = \\exp(\\pm\\vec{k}\\bullet\\vec{r}) = 0\n\\end{equation}\n\n## Schr\u00f6dinger  Equation of Bethe Theory\n\nThe Bethe theory is based on the (time independent, non relativistic) Schr\u00f6dinger  equation:\n\n\\begin{equation}  \\label{Schrodinger}\n\\Big[ \\underbrace{ -\\frac{h^2}{8\\pi^2} \\nabla^2 }_{\\mbox{ kinetic energy}} +\\underbrace{ \\mathcal{V}(\\vec{r})}_{\\mbox{ pot. energy}} \\Big]\\, |\\psi(\\vec{r}) \\rangle = \\underbrace{\\mathcal{E}}_{\\mbox{ total energy}} \\underbrace{|\\psi(\\vec{r})\\rangle }_{\\mbox{ wave function}}\n\\end{equation} \n\nWhat does that mean for the TEM?\n>\n> We have a acceleration voltage (electric field potential) $E$ of 100kV\n>\n> We have a charge of the electron $q$ with the value $e$.\n>\n> We have a total Energy $-\\mathcal{E} = E\\cdot q$ which is just $E$ in the units of $[eV]$.\n>\n> We have a crystal with the potential $V(\\vec{r})$, which we declare positive inside the crystal and zero outside.\n>\n> We have a potential Energy $\\mathcal{V}(\\vec{r}) = q\\cdot V(\\vec{r})$.\n\n\nNow, that we declared all our variables we can transform the Schr\u00f6dinger equation \\ref{Schrodinger} to:\n\n$$\n\\nabla^2  |\\psi(\\vec{r})\\rangle = -\\frac{8\\pi m e}{h^2}\\,  [E+V]\\, |\\psi(\\vec{r})\\rangle \n$$\n\nThe left hand part of this equation is the impulse of the electron and the right hand part consists of a total energy part, which is boring and a part which originates from the crystal (interesting!). \n\n\n## Bloch Waves in Bethe Theory\nWell, if the potential is periodic, then the solution (wave function) must be periodic, too.\n\nFirst we make a substitution in case our wave function is complicated: we define it as a linear combination of other waves. That is a useful trick, which makes the mathematics easier as we'll see in a bit.\n\\begin{eqnarray} \\label{Bloch}\n|\\psi(\\vec{r})\\rangle &=& \\sum_j |b_j\\rangle \\\\\n|b_j\\rangle  &=&  = |b(\\vec{k}^{(j)}, \\vec{r})\\rangle\n\\end{eqnarray} \nThe $ |b(\\vec{k}^{(j)}, \\vec{r})\\rangle $ are called Bloch waves and are only defined for specific $\\vec{k}$--vectors,\nbecause the  $|b(\\vec{k}^{(j)}, \\vec{r})\\rangle$ are plane waves, each traveling in $k^{(j)}$ direction. For the $|\\psi(\\vec{r})\\rangle$ we did not and could not have made any assumption like that.\\\\\n\n\nNow, we express the fact that these Bloch waves are indeed plane waves mathematically:\n\n\\begin{equation} \\label{FourierExpand}\n|b^{(j)}(\\vec{r})\\rangle  = b(\\vec{k}^{(j)}, \\vec{r})=\\mu(\\vec{k}^{(j)}, \\vec{r})\\cdot e^{2\\pi i \\vec{k}^{(j)} \\vec{r}} = \\underbrace{\\mu^{(j)}(\\vec{r})}_{\\mbox{ Bloch function}}   e^{2\\pi i \\vec{k}^{(j)} \\vec{r}}\n\\end{equation} \n\nby dividing it in a plane wave part (the exponential function) and a amplitude part (the Bloch function).\nBecause of the periodicity which we assume for the solution, we expand the Bloch waves in a into a Fourier series, again (the same as in equation \\ref{FourierExpand} for the potential). \n\n\\begin{equation}\nb^{(j)}(\\vec{r}) = \\sum_g C_g^{(j)} e^{2\\pi i (\\vec{k}^{(j)} + \\vec{g}) \\vec{r}}\n\\end{equation}\nThe sum in this equation goes over all excited (aha!) points in the reciprocal lattice, including the incident direction $g_1 = 0$. (  \\vec{g} are defined through the Milller indices as (h/a, k/b, l/c), where the (a,b,c) are the real space lattice vectors).\n\nTheoretically, thre are an infinite number of $\\vec{g}$ vectors, but only few are allowed and only a few have a small excitation error.  \n\nSo in practice there are only a few $\\vec{g}$ vectors to consider.\n\n## Crystal Potential in Bethe Theory\n\nThe crystal potential is periodic and so we also make a Fourier exanion of that potential\n$$\nV = V(x,y,z) = V(\\vec{r}) = \\sum_g V_g \\exp(2\\pi i\\vec{g}\\cdot\\vec{r})\n$$\n\nThe Fourier component of the crystal potential (in Volts) consists of several atoms $j$ over which we sum:\n\\begin{eqnarray}\nV_g &=& \\frac{h^2}{2 \\pi m_0 e} \\frac{1}{\\Omega} \\sum_j  f_{e_j}(\\vec{g}) \\exp(-2\\pi i\\vec{g}\\cdot\\vec{r_j})\\\\\n&=& \\frac{2 \\pi  e a_0}{\\Omega} \\sum_j  f_{e_j}(\\vec{g}) \\exp(-2\\pi i\\vec{g}\\cdot\\vec{r_j})\\\\\n\\end{eqnarray}\n\nwhere:\n\n- $f_{e_j}$: atomic form (atomic scattering) factor of the $j$th atom\n- $e$: charge of electron\n- $m_0$: rest mass of electron\n- $a_0$: Bohr radius\n- $\\Omega$: Volume of the unit cell\n\n## Solution of Bethe Theory\n\n\nNow, so far we haven't done anything, but substitute and expand. Let's put all this into the Schr\u00f6dinger equation \\ref{Schrodinger} \n\\begin{equation}\n4\\pi \\left[ K^2 - (k_0^{(j)} + g)^2 +\\sum_{h \\neq 0} U_h e^{2\\pi i \\vec{h}\\vec{r} }  \\right] \\cdot C_g^{(j)} e^{2\\pi i (\\vec{k}_o^{(j)} +\\vec{g})\\cdot \\vec{r} }= 0\n\\end{equation}\nThis can only be zero, if all coefficients with same exponential function simultaneous become zero; this results in a set of equations, after collecting up terms containing the factor \n$e^{2\\pi i (\\vec{k}_o^{(j)} +\\vec{g})\\cdot \\vec{r} }$:\n\\begin{equation} \\label{setEquat}\n\\left[ K^2 -(\\vec{k}_o^{(j)} +\\vec{g})^2 \\right] C_g^{(j)} + \\sum_{h\\neq 0} U_h C_{g-h}^{(j)}=0; \\qquad \\vec{g}=\\vec{g}_1, \\vec{g}_2, ..., \\vec{g}_n \n\\end{equation}\n\nI made use of an abbreviation:\n\\begin{equation}\nK=\\frac{1}{h}\\left[ 2m_0 E (1+\\frac{E}{2E_0}) +2m_0 e U_0(1+\\frac{E}{E_0}) \\right]^{\\frac{1}{2}}\n\\end{equation}\nfor the wave vector inside the the crystal which are not identical to the magnitude of the wave vectors of the Bloch waves $\\vec{k}_g^{(j)}=\\vec{k}_o^{(j)} +\\vec{g}$.\n\nPlease note, that I introduced relativistic corrections (the terms in the round brackets in the equation above), too. It is enough to add this corrections for the energy at this point; it is not necessary to solve the Dirac equation (relativistic  Schr\u00f6dinger equation).\n\nThe set of equations defined in \\ref{setEquat} are essential for the  understanding of dynamic diffraction. Let's look at it a little more closely. \n\nWe get for each $j$ one equation; and this means we get for each Bloch wave one equation.\n\nThe second term in equation \\ref{setEquat} (the term with the sum) mixes the Bloch waves ($C_{g-h}^{(j)}$). Effectively, we state that the inner potential $U_h$ mixes the Bloch waves; this is called dynamical coupling.\n\n> **In summation:**\n>\n> We separated the problem! \n\n\n## Two Beam Case\nWe rewrite the matrix expression for the boundary condition \\ref{boundaryCond}in the two beam case:\n\\begin{equation}\n\\left(\n\\begin{array}{*{2}{c}}\nC_{0}^{(1)} & C_{0}^{(2)} \\\\\nC_{g}^{(1)} & C_{g}^{(2)} \\\\\n\\end{array}\n\\right) \\cdot \n\\left(\n\\begin{array}{*{1}{c}}\n\\epsilon^{(1)} \\\\\n\\epsilon^{(2)} \\\\\n\\end{array}\n\\right) =\n\\left(\n\\begin{array}{*{1}{c}}\n\\phi_0^{(0)} \\\\\n\\phi_g^{(0)} \\\\\n\\end{array}\n\\right) =\n\\left(\n\\begin{array}{*{1}{c}}\n1 \\\\\n0\\\\\n\\end{array}\n\\right) \n\\end{equation}\n\nIn the kinematic case, the centers M of the various Ewald spheres (for the various incident directions) lay on a sphere of radius $k=\\frac{1}{\\lambda}$ around the origin of the reciprocal lattice. At some point the intensity in the diffracted beam will be more intense than in the incident beam, and therefore, we have to treat this scattered beam now in the same way we have treated the incident beam before: we need an Ewald sphere of radius $k$ for this direction/ for this reciprocal lattice point $\\vec{g}$. Now we have two Ewald spheres, one around the origin $0$ and one around the reciprocal lattice point $\\vec{g}$. The two spheres are not allowed to intersect each other, but a smooth kind of complicated surface has to be constructed.\n\nThe fundamental equations of the dynamic theory for the two beam case are:\n\n\\begin{eqnarray}\n-\\gamma^{(j)} C_0^{j} +& \\frac{U_g}{2K} C_g^{(j)} &= 0\\\\\n\\frac{U_g}{2K} C_0^{j} +& (-\\gamma^{(j)}+s) C_g^{(j)} &= 0\n\\end{eqnarray}\n\nSuch a homogeneous linear equation system for the $C_g^{(j)}$ has a non-zero solution of and only if the determinant of the coefficients is zero:\n\n\\begin{equation}\n\\left|\n\\begin{array}{*{2}{c}}\n-\\gamma^{(j)} & \\frac{U_g}{2K}\\\\\n\\frac{U_g}{2K}& (-\\gamma^{(j)}+s)\\\\\n\\end{array}\n\\right| = {\\gamma^{(j)}}^2 -s\\gamma^{(j)}-\\frac{U_g^2}{4K^2} =0\n\\end{equation}\n\nWhich is the same as the Howie-Whelan equation \\ref{HaW3} with $\\xi_g = K^2/U_g$,\nbut now we know that the $\\gamma^{(j)}$ are the Eigenvalues of a matrix problem.\n\nSolution:\n\\begin{eqnarray}\n\\gamma^{(j)}  &=& \\frac{1}{2} \\left[ s-(-1)^j \\sqrt{(U_g/K)^2 +s^2}   \\right]\\\\\n&=& \\frac{1}{2} \\left[ s-(-1)^j \\sqrt{(1/\\xi^2 +s^2}   \\right]\\\\\n&=& \\frac{1}{2\\xi_g} \\left[ w-(-1)^j \\sqrt{(1+w^2}   \\right]\\\\\n\\end{eqnarray}\n\nWe made the substitution $w =s\\xi_g$, in which the parameter $w$ characterizes the tilt out of the exact Bragg condition ($w=0$). The excitation error $s$ is zero in the exact Bragg condition, isn't it.\n\n The separation is $\\Delta k_{z,min} = \\gamma^{(1)}-\\gamma^{(2)}= \\frac{U_g}{2K}=\\frac{1}{\\xi_g}$.\n\nBy use of the eigenvalues $\\gamma^{(j)}$, the linear systems of equations can be solved for the $C_g^{(j)}$. For the amplitude $\\epsilon^{(j)} C_g^{(j)} = C_0^{j} C_g^{(j)}$ of the four Bloch waves with the vector $\\vec{k}_0^{(j)}+\\vec{g}$ we obtain:\n\\begin{eqnarray}\nC_0^{j} C_0^{(j)} &=& \\frac{1}{2}\\left[ 1 + (-1)^j \\frac{w}{\\sqrt{1+w^2}} \\right]\\\\\nC_0^{j} C_g^{(j)} &=& -\\frac{1}{2}\\left[  \\frac{(-1)^j}{\\sqrt{1+w^2}} \\right]\n\\end{eqnarray}\n\nWe put this into the equation for the scattered wave and substitute the thickness $t$ for the $z$ component of the vector $\\vec{r}$:\n\\begin{eqnarray}\n\\psi_0(t)&=&\\sum_{j=1}^2 C_0^{j} C_0^{(j)}e^{2\\pi i k_z^{(j)}t}\\\\\n\\psi_g(t)&=&\\sum_{j=1}^2 C_0^{j} C_g^{(j)}e^{2\\pi i k_z^{(j)}t}\\, e^{2\\pi i k_z gx}\n\\end{eqnarray}\nand we find (omitting common phase factors):\n\\begin{eqnarray}\n\\psi_0(t)= \\cos (\\pi \\sqrt{1+w^2}\\frac{t}{\\xi_g}) & - \\frac{iw}{\\sqrt{1+w^2}} \\sin (\\pi \\sqrt{1+w^2}\\frac{t}{\\xi_g})\\\\\n\\psi_g(t)=  &  \\frac{i}{\\sqrt{1+w^2}} \\sin (\\pi \\sqrt{1+w^2}\\frac{t}{\\xi_g}) \\, e^{2\\pi i k_z gx}\n\\end{eqnarray}\n\n\nThe intensities of the transmission $T$ and reflection $R$ become:\n\\begin{equation}\n\\underbrace{\\psi_g \\psi_g^*}_R = \\underbrace{1-\\psi_0 \\psi_0^*}_{1-T} =  \\frac{1}{1+w^2} \\sin^2 (\\pi \\sqrt{\\sqrt{1+w^2} ( \\frac{1}{\\xi_g}})_{s_{eff}} \\cdot t)\n\\end{equation}\n\nThe solution is the Pendell\u00f6sung of two coupled oscillators (in mechanics: two pendulums connected with a spring).\n\nEven in exact Bragg condition, the intensity oscillates between primary beam and Bragg reflected beam with increasing film thickness. Look at the plot below, the Pendell\u00f6sung is shown without absorption. \n\nNormally one would want to add an absorption term to reduce the intensity with thickness. This absorption term is better named a damping term and stems form the inelatic scattering to random angles instead of the  considered (here two)  Bragg angles\n\n\n\nThese oscillations of the intensities are commonly called ``rocking curve``.\n\n\n\n\n```python\n# ------ Input ------\nxi_g = 4  # extiction distance (in terms of relative thickness )\nomega = 0 # tilt from Bragg condition\ndamping = 0.6\n# --------------------\n\nt = np.linspace(0,8,401)\n\nprint(omega)\nplt.figure()\nplt.plot(t, (1-np.sin(np.pi * np.sqrt(np.sqrt(1.+ omega**2)*1/xi_g)*t)**2) * 1/np.exp(t*damping), label='incident beam')\nplt.plot(t, np.sin(np.pi * np.sqrt(np.sqrt(1.+ omega**2)*1/xi_g)*t)**2 * 1/np.exp(t*damping), label='reflected beam')\n\nplt.legend();\n```\n\n    0\n\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n## Summary of Bethe Theory\nThe solution is the Pendell\u00f6sung of two coupled oscillators.\n\nThe periodicity is the extinction length $\\xi$, which tells at which thickness a beam is completely vanished.\n\nConsidering some absorption (well it's not a real absorption, but inelastic scattering) then we see that the amplitudes decrease slowly.\n\n## Using Bethe Theory for Thickness Determination\n\nWe will do this in a lab and it will be your homework.\n\n- The accurate thickness of the sample is an important but hard to obtain parameter, but it influences the contrast in all imaging modes.\n- Be aware that with different techniques you perform different thickness measurement. In any high resolution image and diffraction experiment, you always look at the thickness of the crystalline part of the sample, omitting the contribution of contamination and amorphous surface layer (from sample preparation). \n- In the Analytic Section of this class we learn how to the thickness from the  whole sample. \n\nWe can observe the above rocking curve in convergent beam electron diffraction patterns (CBED).\n\nBut we have to ensure that:\n- Excitation error is as small as possible \n- We are in two beam condition\n\n### Experimental Considerations\n- Choose a convergence angle $\\alpha$ so that $\\alpha < \\theta_B$, to avoid overlapping of disks in the ZOLZ.\n- The 000 disk usually contains concentric diffuse fringes, the Kossel-M\u00f6llenstedt fringes \n\n- If you move the specimen, then you will see that the number of this fringes changes. In fact the number of each fringes increases by one every time the thickness increases by one extinction length. \n- The foil thickness can be measured precisely at the point where you do your other analysis. \n\nPlease be aware that dynamic effects also occur for the HOLZ lines in a CBED pattern.\n\nIn practice to simplify the interpretation, we don't use zone axis conditions, but tilt to two--beam conditions with only one strongly excited Bragg beam. \n- The CBED disks contain then parallel rather than concentric intensity oscillations as shown in the earlier figure. \n- In fact, this intensity oscillations are equivalent to the rocking curve intensity oscillations discussed earlier.\n- It helps, of you use an energy filter for this method.\n\n\n### Thickness Determination\nBecause the oscillations are symmetric in the hkl disk we concentrate the analysis on this disk. \n- The middle of the hkl disk is bright and originates from the exact Bragg condition ($\\vec{s}=0$). \n- We measure the distance between the midle (bright fringe) of the $hkl$ disk and the dark lines.\n\nYou obtain a deviation $s_i$ for each fringe from the equation:\n\\begin{equation}\ns_i=\\lambda\\frac{\\Delta\\theta_i}{e\\theta_B d^2}\n\\end{equation}\nThe Bragg angle $\\theta_B$ is known from the separation of two disks and the lattice spacing $d$ is known from the sample or can be calculated through the camera length.\n\nIf the extinction distance $\\xi_g$ is known you can calculate the foil thickness $t$ with:\n\\begin{equation}\n\\frac{1}{t^2} = \\frac{s_1^2}{n_k^2}+\\frac{1}{\\xi_g^2n_k^2}\n\\end{equation}\nwhere $n_k$ is an integer.\n\n### Data Analysis\n- assign $n=1$ to the first fringe $s_1$\n- assign $n=2$ to the second fringe $s_2$\n  and so on for all other fringes\n- plot $(s_1/n_k)^2$ versus $(1/n_k)^2$.\n- if you get a straight line, then you are finished and you have $k=i+j$, where $j$ is the largest integer $<(t/\\xi_g)$.\n- if not repeat the same thing with $n=2$ for $s_1$, $n=3$ for $s_2$, etc.\n- repeat this increase by one till you get a straight line\n- the slope of the line is $1/\\xi_g^2$\n- the extrapolated value for $1/n_k^2$ is $1/t^2$.\n\nThe whole procedure is summarized in the figure below.\n\n\n\n## More about Bloch Waves\nWe can replace the  exponential functions by trigonometric functions and get:\n\\begin{eqnarray}\nA^{(1)} &=& \\cos \\frac{\\beta}{2}\\\\\nA^{(2)} &=& \\sin \\frac{\\beta}{2}\n\\end{eqnarray}  \n\nSome of the Bloch waves are located (have their maxima) between the atoms. These Bloch waves channel and are more or less undisturbed.\n\nAnother set is located on the atomic rows and will cause much more inelastic scattering than the other, also they will travel much faster.\n\nThe second set is especially important for Z-contrast image, where a small convergent beam is located at the atomic rows. You might consider the atoms like little lenses which keep the beam focused on the column.\n\n## Navigation\n\n\n- <font size = \"3\">  **Next: [Mutli-Slice Theory](CH2_D02-Multi_Slice.ipynb)** </font>\n- <font size = \"3\">  **Chapter 2: [Diffraction](CH2_00-Diffraction.ipynb)** </font>\n- <font size = \"3\">  **List of Content: [Front](../_MSE672_Intro_TEM.ipynb)** </font>\n\n\n```python\n\n```\n", "meta": {"hexsha": "85713647d749a1a24fb8b21940f7ce4aaec897d2", "size": 113854, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Diffraction/CH2_D01-Bloch.ipynb", "max_stars_repo_name": "mthompson360/MSE672-Introduction-to-TEM", "max_stars_repo_head_hexsha": "36001614aed8526b92e77ed61afbf2d29d027871", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Diffraction/CH2_D01-Bloch.ipynb", "max_issues_repo_name": "mthompson360/MSE672-Introduction-to-TEM", "max_issues_repo_head_hexsha": "36001614aed8526b92e77ed61afbf2d29d027871", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Diffraction/CH2_D01-Bloch.ipynb", "max_forks_repo_name": "mthompson360/MSE672-Introduction-to-TEM", "max_forks_repo_head_hexsha": "36001614aed8526b92e77ed61afbf2d29d027871", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 70.4106369821, "max_line_length": 39507, "alphanum_fraction": 0.6736522213, "converted": true, "num_tokens": 6842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869692386284973, "lm_q2_score": 0.1023047181564006, "lm_q1q2_score": 0.042834670788740765}}
{"text": "# Lazy Evaluation & Generators\n\n## Carrot Cake Recipe\n- Add 3 eggs\n- Add 300g flour\n- Add some sugar\n- Add 3 carrots cut into small pieces\n- Add baking powder\n- Mix all ingredients\n- Bake for 1 hour\n- Pour chocolate on top\n- Serve\n\nPython would do this in order and would realise late that preheating the oven is needed which could have been done earlier!\n\nDistributed computing is also a problem!\n\nWould go to the shop and by an ingredient, come back, see it needs flour, goes to shop etc...\n\n## Lazy Evaluation in Python\n\n- Lazy Evaluation reads it all once, and works out the steps!\n\n- It only starts to work when you know what the outcome is\n\nLazy evaluation with Generators saves time because:\n- Data is generated only when it is needed\n- Not all data is kept in memory all the time - huge!\n\n\n```python\ndef example1():\n    '''functions with yield are called generator functions'''\n    yield 1\n    yield 2\n    yield 4\n    yield 8\n```\n\n\n```python\ng = example1() # Does nothing yet\n```\n\n\n```python\ng\n```\n\n\n\n\n    <generator object example1 at 0x107730620>\n\n\n\n\n```python\nnext(g)\n```\n\n\n\n\n    1\n\n\n\n\n```python\ndef example1():\n    '''functions with yield are called generator functions'''\n    a = 1\n    for i in range(15):\n        yield a\n        a *= 2\n```\n\n\n```python\neg = example1()\neg\n```\n\n\n\n\n    <generator object example1 at 0x1077304c0>\n\n\n\n\n```python\nnext(eg)\n```\n\n\n\n\n    1\n\n\n\n\n```python\nfor i in range(3):\n    print(next(eg), next(eg))\n    print('----------------')\n```\n\n    2 4\n    ----------------\n    8 16\n    ----------------\n    32 64\n    ----------------\n\n\n\n```python\nlist(eg)\n```\n\n\n\n\n    [128, 256, 512, 1024, 2048, 4096, 8192, 16384]\n\n\n\n\n```python\ndef example1():\n    '''functions with yield are called generator functions'''\n    a = 1\n    while True:\n        yield a\n        a *= 2\n```\n\n#### We won't get endless loop because yield statement ends the loop\n\n\n```python\nh = example1()\n```\n\n\n```python\nnext(h)\n```\n\n\n\n\n    1\n\n\n\n\n```python\n[next(h) for x in range(3, 5)]\n```\n\n\n\n\n    [2, 4]\n\n\n\n\n```python\ne = enumerate(['a','b','c'])\ne\n```\n\n\n\n\n    <enumerate at 0x107751048>\n\n\n\n\n```python\nnext(e)\n```\n\n\n\n\n    (0, 'a')\n\n\n\n\n```python\nz = zip([1,2,3], ['a', 'b', 'c'])\nz\n```\n\n\n\n\n    <zip at 0x107584848>\n\n\n\n\n```python\nnext(z)\n```\n\n\n\n\n    (1, 'a')\n\n\n\n\n```python\nfor x in z:\n    print(x)\n```\n\n    (2, 'b')\n    (3, 'c')\n\n\n## Generators in Python\n- enumerate\n- zip\n- BeautifulSoup.findall\n- pd.GroupBy\n- open text files\n- many functions that iterate over data\n\n### For more info, see: FUNCTIONAL PROGRAMMING IN PYTHON\n\n### When to use Generators?\n\n**Generators are an advanced tool present in Python.**\n\n- Generators are \u201clazy functions\u201d. They produce results like normal Python functions, but only when they are needed. Generators are executed on demand and return results in small portions, instead of returning everything at once.\n\n- The main purpose of using generators is to save memory and calculation time when processing big datasets.\n\n### Cases where generators can increase efficiency:\n- Processing large amounts of data\n- Stream processing.\n- Piping: stacked generators can be used as pipes, in a manner similar to Unix pipes.\n- Concurrency: generators can be used to generate (simulate) concurrency.\n\n### Key concepts\n| concept | description |\n|---------|-------------|\n| yield | returns a value, generator keeps running | \n| next( ) | retrieves one value from a generator | \n| while True: | is possible in generators |  | \n| generator expression | generator equivalent of a list comprehension | \n| iterator | generator-like instance, e.g. from enumerate() | \n\n### Examples\nA Python generator is defined by the `yield` keyword. The `yield` keyword replaces return. `yield` can be executed mutliple times. You cannot have `yield` and `return` in the same function.\n\nAn example:\n\n\n```python\ndef simple_generator_function():\n    yield 1\n    yield 2\n    yield 3\n```\n\n- Generators can be consumed like any iterable type, e.g. in `for` loops:\n\n\n```python\nfor value in simple_generator_function():\n    print(value)\n```\n\n    1\n    2\n    3\n\n\n- Alternatively you can retrieve single elements from a generator with `next()`:\n\n\n```python\nour_generator = simple_generator_function()\n```\n\n- Calling the generator does nothing yet. Only when `next()` requests the next value, the generator is executed until the `yield` statement. Then it pauses until the next `yield` and so on.\n\n\n```python\nnext(our_generator)\n```\n\n\n\n\n    1\n\n\n\n\n```python\nnext(our_generator)\n\n```\n\n\n\n\n    2\n\n\n\n\n```python\nnext(our_generator)\n\n```\n\n\n\n\n    3\n\n\n\n### Number Generator\nMany generators contain a `while` loop:\n\n\n```python\ndef numberGenerator(n):\n    number = 0\n    while number < n:\n        yield number\n        number += 1\n```\n\n\n```python\nmyGenerator = numberGenerator(3)\n```\n\n\n```python\nnext(myGenerator)\n```\n\n\n\n\n    0\n\n\n\n\n```python\nnext(myGenerator)\n```\n\n\n\n\n    1\n\n\n\n\n```python\nnext(myGenerator)\n```\n\n\n\n\n    2\n\n\n\nWhen the generator function exits, an Exception is raised:\n\n\n```python\nnext(myGenerator)\n```\n\n### Iterators\nThe thing returned by a generator is called an **iterator**. Many functions in Python 3 return iterators (e.g. `range()`, `enumerate()`, `zip()`).\n\nAmong the things you can do to iterators are:\n\n- request values with `next`.\n- use them in a `for` loop.\n- convert them to lists with `list()`.\n\n### Infinite generators\nSome generators yield results forever. Of course, you shouldn\u2019t use them in a `for` loop:\n\n\n```python\ndef double():\n    i = 1\n    while True:\n        yield i\n        i = i * 2\n```\n\n\n```python\nnext(double())\n```\n\n\n\n\n    1\n\n\n\n\n```python\nnext(double())\n```\n\n\n\n\n    1\n\n\n\n\n```python\ndef take(n, seq):\n    \"\"\"Returns first n values from the given sequence.\"\"\"\n    seq = iter(seq)\n    result = []\n    try:\n        for i in range(n):\n            result.append(next(seq))\n    except StopIteration:\n        pass\n    return result\n```\n\n- We combine both functions to a stacked pipe:\n\n\n```python\nprint(take(5, double()))\n```\n\n    [1, 2, 4, 8, 16]\n\n\n### Generator Expressions\nGenerator expressions are very similar to list comprehensions, only with lazy evaluation.\n\n\n```python\ngen = (x + 1 for x in double() if x > 10)\n```\n\n\n```python\nnext(gen), next(gen), next(gen)\n```\n\n\n\n\n    (17, 33, 65)\n\n\n\n### Exercises\n#### Exercise 1: Square numbers\n- Write a generator that produces a sequence of square numbers (1, 4, 9..).\n\n\n- Retrieve the 100th number from the sequence.\n\n\n```python\ndef square(n):\n    yield n**2\n```\n\n\n```python\nnext(square(100))\n```\n\n\n\n\n    10000\n\n\n\n#### Exercise 2: Build a Fibonacci generator\nWrite a generator that produces a sequence of numbers: 0, 1, 1, 2, 3, 5, 8, 13\n\n\\begin{align}\nF_n = F_{n - 1} + F_{n - 2}\n\\end{align}\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n#### Exercise 3: Huge generator\nWrite a generator that endlessly repeats the text:\n\n`\"Peter Piper picked a peck of pickled peppers\"`\n\nWrite that sentence into a text file 10 million times. Track how much memory is consumed while the program is running.\n\n\n```python\n\n```\n", "meta": {"hexsha": "e276d4df4ad89b1ab6ec4d3074adf9931130642d", "size": 18646, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "14_LazyEvaluation&Generators.ipynb", "max_stars_repo_name": "maximcondon/Appendix", "max_stars_repo_head_hexsha": "b95c26f92c4083cdbce5461c1a55ea62a554f563", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "14_LazyEvaluation&Generators.ipynb", "max_issues_repo_name": "maximcondon/Appendix", "max_issues_repo_head_hexsha": "b95c26f92c4083cdbce5461c1a55ea62a554f563", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "14_LazyEvaluation&Generators.ipynb", "max_forks_repo_name": "maximcondon/Appendix", "max_forks_repo_head_hexsha": "b95c26f92c4083cdbce5461c1a55ea62a554f563", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.1578378378, "max_line_length": 297, "alphanum_fraction": 0.4819800493, "converted": true, "num_tokens": 1833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.14033624949008322, "lm_q1q2_score": 0.042668068353488194}}
{"text": " <p style=\"text-align: right;\"> &#9989; Put your name here</p>\n\n# Pre-Class Assignment: Practice\n\nIn todays pre-class assignment you are going to practice what we have learned.  \n\n# Goals for today's pre-class assignment \n\n</p>\n\n1. topic\n1. Assignment Wrap-up\n\n\n```python\n# Read data for this assignment\n%matplotlib inline \nimport matplotlib.pyplot as plt\nfrom scipy.misc import imread, imsave\nfrom urllib.request import urlopen\n\nurl1 = 'http://res.cloudinary.com/miles-extranet-dev/image/upload/ar_16:9,c_fill,w_1000,g_face,q_50/Michigan/migration_photos/G21696/G21696-msubeaumonttower01.jpg'\nwith urlopen(url1) as file:\n    im1 = imread(file, mode='RGB')\nurl2 = 'http://msutoday.msu.edu/_/img/assets/2013/beaumont-spring-1.jpg'\nwith urlopen(url2) as file:\n    im2 = imread(file, mode='RGB')\n    \nf, (ax1, ax2) = plt.subplots(1, 2,figsize=(20,10))\nax1.imshow(im1)\nax2.imshow(im2)\n```\n\n----\n# 1. Point Seleciton\n\n\n```python\n# The following command will install mpld3 - Uncomment and run once.\n\n!pip install -t ./packages mpld3 \n```\n\n    Collecting mpld3\n      Downloading mpld3-0.5.5.tar.gz (1.0 MB)\n    Collecting jinja2\n      Downloading Jinja2-3.0.2-py3-none-any.whl (133 kB)\n    Collecting matplotlib\n      Downloading matplotlib-3.4.3-cp39-cp39-win_amd64.whl (7.1 MB)\n    Collecting MarkupSafe>=2.0\n      Downloading MarkupSafe-2.0.1-cp39-cp39-win_amd64.whl (14 kB)\n    Collecting python-dateutil>=2.7\n      Downloading python_dateutil-2.8.2-py2.py3-none-any.whl (247 kB)\n    Collecting pyparsing>=2.2.1\n      Downloading pyparsing-2.4.7-py2.py3-none-any.whl (67 kB)\n    Collecting pillow>=6.2.0\n      Downloading Pillow-8.4.0-cp39-cp39-win_amd64.whl (3.2 MB)\n    Collecting cycler>=0.10\n      Downloading cycler-0.10.0-py2.py3-none-any.whl (6.5 kB)\n    Collecting kiwisolver>=1.0.1\n      Downloading kiwisolver-1.3.2-cp39-cp39-win_amd64.whl (52 kB)\n    Collecting numpy>=1.16\n      Downloading numpy-1.21.3-cp39-cp39-win_amd64.whl (14.0 MB)\n    Collecting six\n      Downloading six-1.16.0-py2.py3-none-any.whl (11 kB)\n    Building wheels for collected packages: mpld3\n      Building wheel for mpld3 (setup.py): started\n      Building wheel for mpld3 (setup.py): finished with status 'done'\n      Created wheel for mpld3: filename=mpld3-0.5.5-py3-none-any.whl size=200886 sha256=92ce84322a8357effb323059fc276b9df28bb02b05463dc5731527cbdc4ccc16\n      Stored in directory: c:\\users\\owner\\appdata\\local\\pip\\cache\\wheels\\d9\\ed\\51\\ac5c5c9f2f8105b101482c066a31f9e71a9eef9c2fd6379bdd\n    Successfully built mpld3\n    Installing collected packages: six, python-dateutil, pyparsing, pillow, numpy, MarkupSafe, kiwisolver, cycler, matplotlib, jinja2, mpld3\n    Successfully installed MarkupSafe-2.0.1 cycler-0.10.0 jinja2-3.0.2 kiwisolver-1.3.2 matplotlib-3.4.3 mpld3-0.5.5 numpy-1.21.3 pillow-8.4.0 pyparsing-2.4.7 python-dateutil-2.8.2 six-1.16.0\n\n\n\n```python\n#Add Packages folder to path (Do only once per run of notebook:\nfrom sys import path\npackage_folder = './packages'\nif not package_folder in path:\n    print('adding packages')\n    path.append(package_folder)\nelse:\n    print('found packages folder')\n```\n\n    adding packages\n\n\n\n```python\n# Code snipit to make point seleciton function (REQUIRES mpld3 installed)\n%matplotlib inline \nimport matplotlib.pyplot as plt\nimport matplotlib.image as img\nimport sys\n\nimport mpld3\nfrom mpld3 import plugins\nmpld3.enable_notebook()\n\n# PLOTS THE IMAGE IN THE NOTEBOOK\ndef plot(imgname):\n    fig, ax = plt.subplots()\n    im = img.imread(imgname)\n    plt.imshow(im, origin='lower')\n    return fig\n\n# FUNCTION CALLED IN THE NOTEBOOK\ndef pickpoints(fig='', radius=4, color=\"white\", x = 'x', y = 'y'):\n    if not fig:\n        fig = plt.gcf()\n    plugins.connect(fig, Annotate(radius, color, x, y)) # color='htmlcolorname', radius=int\n    plugins.connect(fig, plugins.MousePosition())\n\n# FORMATS x AND y LISTS INTO SHORTER DECIMALS, SO THEY'RE NOT TOO LENGTHY\ndef cleanformat(var):\n    varlist = []\n    if type(var) == float:\n        varlist = '{:05.2f}'.format(var)\n    else:\n        for i in range(len(var)):\n            varlist.append('{:05.2f}'.format(var[i]))\n    return varlist\n\n# MAIN CLASS THAT CONTAINS JAVASCRIPT CODE TO CREATE CIRCLES AND DRAG CIRCLES  \nclass Annotate(plugins.PluginBase):\n    \"\"\"A plugin that creates points in a figure by clicking the mouse\"\"\"\n   \n    JAVASCRIPT = r\"\"\"\n    mpld3.register_plugin(\"annotate\", Annotate);\n    Annotate.prototype = Object.create(mpld3.Plugin.prototype);\n    Annotate.prototype.constructor = Annotate;\n    Annotate.prototype.requiredProps = [];\n    Annotate.prototype.defaultProps = {radius: 4, color: \"white\", x: 'x', y: 'y'};\n    function Annotate(fig, props){\n        mpld3.Plugin.call(this, fig, props);\n    };\n\n    Annotate.prototype.draw = function(){\n        \n        /// NECESSARY STARTUP VARIABLES ///\n        \n        var fig = this.fig;\n        var ax = fig.axes;\n        var dataset = [];\n        var svg = d3.select(\".mpld3-figure\");   // existing svg element\n        var radius = this.props.radius;\n        var color = this.props.color;\n        var x = this.props.x;\n        var y = this.props.y;\n        var ax = fig.axes[0];\n        \n        \n        /// INDEXES HTML DOC TO PULL VALUES FOR x,y CALIBRATION ///\n        var xcal = this.parent.axes[0].position[0];\n        var ycal = this.parent.axes[0].position[1];\n        console.log('x calibration: ' + xcal);\n        console.log('y calibration: ' + ycal);\n        \n        var xcommand = x+\" = []\";\n        IPython.notebook.kernel.execute(xcommand);\n        var ycommand = y+\" = []\";\n        IPython.notebook.kernel.execute(ycommand);\n        \n        \n        ////////// CREATE POINT COMPONENT //////////\n        \n        var update_coords = function() {\n        \n            return function() {\n                var pos = d3.mouse(this),\n                    xpos = ax.x.invert(pos[0]),\n                    ypos = ax.y.invert(pos[1]);\n                    \n                var newpoint = {\n                    cx: pos[0] + xcal,\n                    cy: pos[1] + ycal,\n                    r: radius,\n                    fill: color\n                };\n                dataset.push(newpoint);\n                \n                var circles = svg.selectAll(\"circle\")\n                    .data(dataset)\n                    .enter()\n                    .append(\"circle\")\n                    .attr(newpoint)\n                    .call(drag);\n                       \n                var xcommand = x+\".append(\"+xpos+\")\";\n                IPython.notebook.kernel.execute(xcommand);\n                console.log(xcommand);\n                var ycommand = y+\".append(\"+ypos+\")\";\n                IPython.notebook.kernel.execute(ycommand);\n                console.log(ycommand);\n                   \n            };\n        }();\n        ax.baseaxes\n            .on(\"mousedown\", update_coords);\n\n        \n        \n        ////////// DRAG POINT COMPONENT //////////\n        \n        var drag = d3.behavior.drag()\n            .on(\"dragstart\", dragstarted)\n            .on(\"drag\", dragged)\n            .on(\"dragend\", dragended);\n            \n        function dragstarted(d) {\n             d3.event.sourceEvent.stopPropagation();\n             d3.select(this).classed(\"dragging\", true);\n        }\n        \n        function dragged(d) {\n             d3.select(this).attr(\"cx\", d3.event.x)\n                            .attr(\"cy\", d3.event.y);             \n        }\n\n        function dragended(d, i) {\n             d3.event.sourceEvent.stopPropagation();\n             d3.select(this).classed(\"dragging\", false);\n             var calib_cx = d3.select(this)[0][0].cx.animVal.value - xcal;\n             var calib_cy = d3.select(this)[0][0].cy.animVal.value - ycal;\n             var xcommand = x+\"[\"+i+\"] = \"+ax.x.invert(calib_cx);\n             var ycommand = y+\"[\"+i+\"] = \"+ax.y.invert(calib_cy);\n             IPython.notebook.kernel.execute(xcommand);\n             IPython.notebook.kernel.execute(ycommand);\n             console.log(xcommand);\n             console.log(ycommand);\n        }\n\n\n    };\"\"\"\n\n    def __init__(self, radius=4, color=\"white\", x ='x', y ='y'):\n        self.dict_ = {\"type\": \"annotate\",\n                      \"radius\": radius,\n                      \"color\": color,\n                      \"x\": x,\n                      \"y\": y};\n```\n\n\n```python\nfig = plt.figure(figsize=(9,6))\nplt.imshow(im1)\npickpoints(color='cyan', radius=2, x='x1', y='y1')\n```\n\n\n```python\nfig = plt.figure(figsize=(9,6))\nplt.imshow(im2)\npickpoints(color='cyan', radius=2, x='x2', y='y2')\n```\n\n----\n# 1. Topic one\n\n==TOPIC DESCRIPTION==\n\n\n```python\n%matplotlib inline\nfrom __future__ import division\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.misc as misc\n\n\nfrom skimage import transform\n\n# Here are some libraries you may need to use\n%matplotlib inline\nimport matplotlib.pylab as plt\n\nimport sympy as sp\nsp.init_printing()\n\nimport numpy as np\n\nfrom ipywidgets import interact\nimport math\n\n\n```\n\n\n```python\nplt.imshow(im2)\n```\n\n\n```python\nim = im1\ndef affine_image(a1=0,s=1,tx=0,ty=0, alpha=1):\n    theta = -a1/180  * math.pi\n    \n    dx = tx*im.shape[1]\n    dy = ty*im.shape[0]\n    S = np.matrix([[1/s,0,0], [0,1/s,0], [0,0,1]])\n    T2 = np.matrix([[1,0,im.shape[1]/2], [0,1,im.shape[0]/2], [0,0,1]])\n    T1 = np.matrix([[1,0,-im.shape[1]/2-dx], [0,1,-im.shape[0]/2-dy], [0,0,1]])\n    R = np.matrix([[math.cos(theta),-math.sin(theta),0],[math.sin(theta), math.cos(theta),0],[0,0,1]])\n    img = transform.warp(im, T2*S*R*T1);\n    plt.imshow(im2);\n    plt.imshow(img, alpha=alpha);\n\n    plt.show();\n```\n\n\n```python\ninteract(affine_image, a1=(-180,180), s=(0.001,5), tx=(-1.0,1.0), ty=(-1,1,0.1),alpha=(0.0,1.0)); ##TODO: Modify this line of code\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n# Here are some libraries you may need to use\n%matplotlib inline\nimport matplotlib.pylab as plt\n\nimport sympy as sp\nsp.init_printing()\n\nimport numpy as np\n\nfrom ipywidgets import interact\nimport math\n\n```\n\n\n```python\nfrom urllib.request import urlopen\nfrom scipy.misc import imread, imsave\n\nurl = 'http://res.cloudinary.com/miles-extranet-dev/image/upload/ar_16:9,c_fill,w_1000,g_face,q_50/Michigan/migration_photos/G21696/G21696-msubeaumonttower01.jpg'\n\nwith urlopen(url) as file:\n    im = imread(file, mode='RGB')\n    \n#Show the image\nplt.imshow(im);\n```\n\n\n```python\n##Put your function here\nfrom skimage import transform\n\ndef affine_image(a1=0,s=0.5,tx=0,ty=0,shx=0, shy=0):\n    T = np.matrix([[1,0,0],[0,1,0],[0,0,1]])\n    #Your transformations go here.\n    \n    img = transform.warp(im, T);\n    plt.imshow(img);\n    plt.show();\n```\n\n\n```python\n\n##ANSWER##\n\ndef affine_image(a1=0,s=0.5,tx=0,ty=0, shx=0, shy=0):\n    theta = -a1/180  * math.pi\n    \n    dx = tx*im.shape[1]\n    dy = ty*im.shape[0]\n    S = np.matrix([[1/s,0,0], [0,1/s,0], [0,0,1]])\n    SH = np.matrix([[1,shx,0], [shy,1,0], [0,0,1]])\n    T2 = np.matrix([[1,0,im.shape[1]/2], [0,1,im.shape[0]/2], [0,0,1]])\n    T1 = np.matrix([[1,0,-im.shape[1]/2-dx], [0,1,-im.shape[0]/2-dy], [0,0,1]])\n    R = np.matrix([[math.cos(theta),-math.sin(theta),0],[math.sin(theta), math.cos(theta),0],[0,0,1]])\n    img = transform.warp(im, T2*S*R*SH*T1);\n    plt.imshow(img);\n\n    plt.show();\n##ANSWER##\n```\n\n\n```python\n\ninteract(affine_image, a1=(-180,180), s=(0.001,5), tx=(-1,1,0.1), ty=(-1,1,0.1), shx = (-1,1,0.1), shy = (-1,1,0.1)); ##TODO: Modify this line of code\n```\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo(\"NzysdpexqsM\",width=640,height=360)\n```\n\n**Quesiton:** Ask a question that requires a written answer?\n\n<font size=8 color=\"#009600\">&#9998;</font> Do This - Erase the contents of this cell and replace it with your answer to the above question!  (double-click on this text to edit this cell, and hit shift+enter to save the text)\n\n &#9989; **To Do:** Task to be completed by student.\n\n\n```python\n%matplotlib inline\nimport matplotlib.pylab as plt\nimport numpy as np\nimport sympy as sp\nsp.init_printing(use_unicode=True)\n```\n\n\n```python\n#Example matrix in sympy\nsp.Matrix([[1,0], [0,1]])\n```\n\n\n```python\n#Example equation in sympy\n#First define all of the symples to use in our equation\nx,y,z,om = sp.symbols('x, y, z, \\omega', negative=False)\npa = om*x**2+om*y**2+om*z**2\npa\n```\n\n\n```python\n#Put your code here\n```\n\nExample matrix notation:\n\n$$ \n\\left[\n\\begin{matrix}\n    1   & 0 & 4  \\\\\n    0   & 2 & -2  \\\\\n    0   & 1 & 2 \n \\end{matrix}\n\\, \\middle\\vert \\,\n\\begin{matrix}\n-10 \\\\ 3 \\\\ 1\n\\end{matrix}\n\\right] \n$$\n\n----\n# 2. Assignment wrap-up\n\nPlease fill out the form that appears when you run the code below.  **You must completely fill this out in order to receive credit for the assignment!**\n\nDirect Link: https://goo.gl/YcjHHB\n\n\n```python\nfrom IPython.display import HTML\nHTML(\n\"\"\"\n\n\"\"\"\n)\n```\n\n---------\n### Congratulations, you're done with your pre-class assignment!\n\n&#169; Copyright 2018,  Michigan State University Board of Trustees\n", "meta": {"hexsha": "c5fae188199df3f91af230f9b4dcef34cdf63136", "size": 35567, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Point_Seleciton.ipynb", "max_stars_repo_name": "see-insight/pointselector", "max_stars_repo_head_hexsha": "5f4b785ccea016540bcb1cd279bbac976e6d6448", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-07T22:17:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T22:17:55.000Z", "max_issues_repo_path": "Point_Seleciton.ipynb", "max_issues_repo_name": "see-insight/pointselector", "max_issues_repo_head_hexsha": "5f4b785ccea016540bcb1cd279bbac976e6d6448", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Point_Seleciton.ipynb", "max_forks_repo_name": "see-insight/pointselector", "max_forks_repo_head_hexsha": "5f4b785ccea016540bcb1cd279bbac976e6d6448", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.7878440367, "max_line_length": 1575, "alphanum_fraction": 0.532712908, "converted": true, "num_tokens": 3793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2909808785120009, "lm_q2_score": 0.14608724518943894, "lm_q1q2_score": 0.04250859494462102}}
{"text": "---\n\n# Flamespeed\n\n---\n\n## What is Flamespeed?\n\nFlamespeed is an open-source Python library with object-orientated methods for chemical kinetics with the following core functionality:\n\n* API to import a database of elementary reactions in XML-format\n* Efficiently calculate reaction rates for systems of irreversible elementary chemical reactions\n* Output provided in format suitable for further analysis\n\nPotential **applications** for Flamespeed includes:\n\n* Validation of chemical phase input files\n* Input for solving ODEs for system of reactions\n* Input for machine learning methods (e.g. neural networks) that predict reaction types\n\n## Installation\n\nThere are two ways to install Flamespeed:\n\n**Install Flamespeed from PyPI (recommended)**\n\n```bash\npip install flamespeed\n```\n\n**Alternatively: Install Flamespeed form Github source**\n\nFirst, clone Flamespeed using `git`:\n\n```sh\ngit clone https://github.com/bkleyn/flamespeed.git\n```\nThen, `cd` to the root folder and run the install command:\n```sh\npython setup.py install\n```\n\nThe package **test suite** can be run as follows:\n\nFirst, `cd` to the flamespeed folder and then run pytest:\n```sh\ncd flamespeed\npytest\n```\n\n**Requirements:**\n* Python (>= 3.3)\n* NumPy (>= 1.8.2)\n* SciPy (>= 0.13.3)\n\n\n## Getting started\n\nImport the `chemkin` module in flamespeed, which is the main module to evaluate chemical reaction rates.\n\n```python\nfrom flamespeed import chemkin\n```\nInstantiate the reaction rates class and import reaction database in XML format. Example reaction files can be found in the `./data` directory within `flamespeed`.\n\n```python\na = chemkin.ReactionRate()\na.read_XML('./flamespeed/data/rxns_reversible.xml')\nprint(a)\n```\nNext, set the initial concentrations for each of the species included in the reaction and the temperature.\n\n```python\na.set_temp(750)\nx = [2.0, 1.0, 0.5, 1.0, 1.0, 1.5, 0.5, 1]\n```\nNow that all the input parameters have been specified the reaction rates for each of the species in the system can be determined as follows:\n\n```python\nr = a.get_reaction_rate(x)\nprint(r)\n```\n\n---\n\n## Technical detail\n\n#### Irreversible Elementary Reactions\n\nThe mathematical and physical underpinnings of this chemical kinetics library is to solve for the reaction rates of a system consisting of $N$ species undergoing $M$ **irreversible**, **elementary** reactions of the form:\n\n\\begin{align}\n  \\sum_{i=1}^{N}{\\nu_{ij}^{\\prime}\\mathcal{S}_{i}} \\longrightarrow \n  \\sum_{i=1}^{N}{\\nu_{ij}^{\\prime\\prime}\\mathcal{S}_{i}}, \\qquad j = 1, \\ldots, M\n\\end{align}\n\nAn example system of reactions for which the reaction rates can be determined by this library is:\n\n$$ H_{2} + O_{2} \\longrightarrow H_{2}O + O$$\n$$ H_{2}O + O \\longrightarrow 2OH $$\n$$ OH + H_{2} \\longrightarrow 2H + OH $$\n\nMore specifically, the **reaction rate** of specie $i$ can be written as:\n\n\\begin{align}\n  f_{i} = \\sum_{j=1}^{M}{\\nu_{ij}\\omega_{j}}, \\qquad i = 1, \\ldots, N\n\\end{align}\n\nwhere the **progress rate** for each reaction is denoted by:\n\n\\begin{align}\n  \\omega_{j} = k_{j}\\prod_{i=1}^{N}{x_{i}^{\\nu_{ij}^{\\prime}}}, \\qquad j = 1, \\ldots, M\n\\end{align}\n\nPlease refer to the table below for an overview of used symbols. Note that $k_{j}$ is the forward reaction rate coefficient, and is a direct input to a reaction's progress rate. Specifically, this library is capable of handling and calculating three different types of reaction rate coefficients:\n\n$$ Constant: k_j = c $$\n$$ Arrhenius: k_j = Ae^{(-\\dfrac{E}{RT})}$$\n$$ Modified \\hspace{0.25em} Arrhenius: k_j = AT^{b}e^{(-\\dfrac{E}{RT})}$$\n\nThe library assigns each elementary reaction its own reaction rate coefficient. When loading an XML-file with data, the rate coefficient type needs to be specified. In case of a Arrhenius reaction rate coefficient, additional values need to be provided for $A$, $E$, $R$, $T$. In case of Modified Arrhenius reaction rate coefficient, additional values need to be provided for $A$, $b$, $E$, $R$, $T$.\n\n---\n\n#### Reversible Elementary Reactions\n\nAlthough the above derivations hold for **irreversible** elementary reactions, oftentimes **reversible** elementary reactions occur in nature instead (i.e., the products can react and produce the reactants and so forth). Generally, a reversible reaction will have the form:\n\n$$\\sum_{i=1}^{N}{\\nu_{ij}^{\\prime}\\mathcal{S}_{i}}  \\rightleftharpoons \\sum_{i=1}^{N}{\\nu_{ij}^{\\prime\\prime}\\mathcal{S}_{i}} \\qquad j = 1, \\ldots, M$$\n\nwhere $\\rightleftharpoons$ indicts that the foward and backward reactions occur. Note this sign is technically the only difference with the above derive reaction forms.\n\nThe total progress rate is then given by:\n\n$$\\omega_{j} = k_{j}^{\\left(f\\right)}\\prod_{i=1}^{N}{x_{i}^{\\nu_{ij}^{\\prime}}} - k_{j}^{\\left(b\\right)}\\prod_{i=1}^{N}{x_{i}^{\\nu_{ij}^{\\prime\\prime}}}, \\qquad j = 1,\\ldots, M.$$\n\nIf, and only if, the reaction is elementary, the **backward reaction coefficient** can be defined as:\n\n$$k_{j}^{\\left(b\\right)} = \\frac{k_{j}^{\\left(f\\right)}}{k_{j}^{e}}, \\qquad j =1, \\ldots, M$$\n\nwhere $k_{j}^{e}$ is the **equilibrium coefficient** for reaction $j$.\n\nThe final expression for the equilibrium coefficient is\n\n$$k_{j}^{e} = \\left(\\frac{p_{0}}{RT}\\right)^{\\gamma_{j}}\\exp\\left(\\frac{\\Delta S_{j}}{R} - \\frac{\\Delta H_{j}}{RT}\\right), \\qquad j =1, \\ldots, M$$\n\nwhere $\\gamma_{j} = \\sum_{i=1}^{N}{\\nu_{ij}}$ and $p_{0}$ is the pressure of the reactor (take it to be $10^{5}$ Pa).\n\nThe entropy and enthalpy change of reaction $j$ can be defined in terms of the entropy and enthalpy of the species participating in reaction $j$.  We have:\n\n$$\\Delta S_{j} = \\sum_{i=1}^{N}{\\nu_{ij}S_{i}} \\quad \\textrm{and} \\quad \\Delta H_{j} = \\sum_{i=1}^{N}{\\nu_{ij}H_{i}}, , \\qquad j =1, \\ldots, M.$$\n\nThe **specific heat** at constant pressure ($C_{p,i}$), **enthalpy** ($H_{i}$) and **entropy** ($S_{i}$) are related via\n\n$$H_{i} = \\int_{T_{0}}^{T}{C_{p,i}\\left(T\\right) \\ \\mathrm{d}T}, \\qquad i = 1, \\ldots, N$$\n\nand \n\n$$S_{i} = \\int_{T_{0}}^{T}{\\frac{C_{p,i}\\left(T\\right)}{T} \\ \\mathrm{d}T}, \\qquad i = 1, \\ldots, N$$\n\nwhere $C_{p,i}$ is given by a polynomial in $T$ (called the **NASA polynomial**), \n\n$$C_{p,i} = \\left(\\sum_{k=1}^{5}{a_{ik}T^{k-1}}\\right)R, \\qquad i = 1, \\ldots, N.$$\n\nThe $7$th order NASA polynomials are given by \n\n$$\\frac{C_{p,i}}{R} = a_{i1} + a_{i2}T + a_{i3}T^{2} + a_{i4}T^{3} + a_{i5}T^{4}$$\n\n$$\\frac{H_{i}}{RT} = a_{i1} + \\frac{1}{2}a_{i2}T + \\frac{1}{3}a_{i3}T^{2} + \\frac{1}{4}a_{i4}T^{3} + \\frac{1}{5}a_{i5}T^{4} + \\frac{a_{i6}}{T}$$\n\n$$\\frac{S_{i}}{R} = a_{i1}\\ln\\left(T\\right) + a_{i2}T + \\frac{1}{2}a_{i3}T^{2} + \\frac{1}{3}a_{i4}T^{3} + \\frac{1}{4}a_{i5}T^{4} + a_{i7}$$\n\nfor $i = 1,\\dots, N$.\n\n---\n\nA few notes on symbols used:\n\n| Symbol | Meaning |\n|:--------:|:-------:|\n| $\\mathcal{S}_{i}$ | Chemical symbol of specie $i$ |\n| $\\nu_{ij}^{\\prime}$ | Stoichiometric coefficients of reactants |\n| $\\nu_{ij}^{\\prime\\prime}$ | Stoichiometric coefficients of products |\n| $N$                       | Number of species in system |\n| $M$                       | Number of elementary reactions |\n| $R$                       | Ideal gas constant |\n| $T$                       | Temperature of reaction |\n| $S_i$                     | Entropy of specie $i$ |\n| $H_i$                     | Enthalpy of specie $i$ |\n| $C_{p,i}$                 | Specific heat at constant pressure of specie $i$ |\n| $f_{i}$                   | Rate of consumption or formation of specie $i$ (reaction rate) |\n| $\\omega_{j}$              | Progress rate of reaction $j$ |\n| $x_{i}$                   | Concentration of specie $i$ |\n| $k^f_{j}$                 | (Forward) Reaction rate coefficient for reaction $j$ |\n| $k^b_{j}$                 | Backward reaction rate coefficient for reaction $j$ |\n| $k^e_{j}$                 | Equilibrium reaction rate coefficient for reaction $j$ |\n| $a_{i}$                   | NASA polynomial coefficients |\n\n---\n\n\n## Chemkin module\n\n### ReactionCoefficients Class\n\n**Methods:**\n    1. k_const(k=1.0) - Simply returns a constant reaction rate coefficient\n    2. k_arrhenius(A, E, T, R=8.314) - Arrhenius reaction rate coefficient\n    3. k_arrhenius_mod(A, b, E, T, R=8.314) - Modified Arrhenius reaction rate coefficient\n\n**k_const(k=1.0)**\n    \n    Parameters:\n    k: float, default value = 1.0 - Constant reaction rate coefficient\n\n    Returns:\n    k: Constant reaction rate coefficient\n\n**k_arrhenius(A, E, T, R=8.314)**\n    \n    Parameters:\n    A: float, positive - Arrhenius prefactor\n    E: float - Activation energy\n    T: float, positive - Temperature in Kelvin\n    R: float, positive, default value = 8.314 - Ideal gas constant\n    \n    Returns:\n    k: Arrhenius reaction rate coefficient\n\n**k_arrhenius_mod(A, b, E, T, R=8.314)**\n    \n    Parameters:\n    A: float, positive - Arrhenius prefactor\n    b: float - Modified Arrhenius parameter\n    E: float - Activation energy\n    T: float, positive - Temperature in Kelvin\n    R: float, positive, default value = 8.314 - Ideal gas constant\n    \n    Returns:\n    k: Modified Arrhenius reaction rate coefficient\n\n### ReactionRate Class\n\n**Methods:**\n    1. __init__ - Initialize ReactionRate class\n    2. __str__ - Return summary of XML file contents\n    3. __repr__ - Return class type\n    4. __len__ - Returns number of reactions\n    5. read_XML(path) - Reads XML from file path and extracts reaction information\n    6. set_temp(T) - Calculate reaction rate coefficients at specified temperature\n    7. get_progress_rate(concs) - Progress rate for a system of elementary reactions\n    8. get_reaction_rate(concs) - Reaction rate for a system of elementary reactions\n\n**\\__init__**\n    \n    Sets class-wide parameters\n\n**\\__str__**\n    \n    Returns: Returns summary of reaction phase, including species and number of reactions\n\n**\\__repr__**\n    \n    Returns: Class type\n\n**\\__len__**\n    \n    Returns: Number of reactions\n\n**read_XML(path)**\n\n    Parameters:\n    path: string, path to the XML file\n    \n    Returns:\n    ReactionRate class instance\n\n**set_temp(T)**\n\n    Parameters:\n    T: Float, positive - Temperature in Kelvin\n    \n    Returns:\n    k: float - Reaction rate coefficients for each reaction\n\n**get_progress_rate(concs)**\n\n    Parameters:\n    concs: numpy array of floats (size: num_species) - Concentration of species\n    \n    Returns:\n    w: numpy array of floats (size: num_reactions) - Progress rate for each reaction\n\n**get_progress_rate(concs)**\n\n    Parameters:\n    concs: numpy array of floats (size: num_species) - Concentration of species\n    \n    Returns:\n    f: numpy array of floats (size: num_species) - Reaction rate for each specie\n\n---\n\n## Thermo module\n\n**Methods:**\n\n    1. __init__(species, nu_coef) - Initialize ReactionRate class\n    2. read_nasa_coeffs(T) - Read thermo.sqlite database to obtain NASA coefficients\n    3. Cp_over_R(T) - Computes specific heat over ideal gas constant (R) at specified temperature\n    4. H_over_RT(T) - Computes enthalpy change (delta H) over (R*T) at specified temperature\n    5. S_over_R(T) - Computes entropy change (delta S) over (R) at specified temperature\n    6. backward_coeffs(kf, T) - Calculate the backward coefficents given forward rate coefficients\n    \n**\\__init__**\n    \n    Sets class-wide parameters\n    \n**read_nasa_coeffs(T)**\n\n    Parameters:\n    T: Temperature (in Kelvin)\n    \n    Returns:\n    NASA Coefficients\n    \n**Cp_over_R(T)**\n\n    Parameters:\n    T: Temperature (in Kelvin)\n    \n    Returns:\n    Specific Heat at constant pressure over Ideal Gas Constant (C/R)\n    \n**H_over_RT(T)**\n\n    Parameters:\n    T: Temperature (in Kelvin)\n    \n    Returns:\n    Enthalpy Change (Delta S) over Ideal Gas Constant times Temperature (RT)\n    \n**S_over_R(T)**\n\n    Parameters:\n    T: Temperature (in Kelvin)\n    \n    Returns:\n    Entropy Change (Delta S) over Ideal Gas Constant (R)\n    \n**S_over_R(T)**\n\n    Parameters:\n    kf: Forward Reaction Rate Coefficient\n    T: Temperature (in Kelvin)\n    \n    Returns:\n    Backward coefficient kf / ke where ke is the equilibrium coefficient\n\n---\n\n## Parser module\n\n### ReactionParser Class\n\n**Methods:**\n\n    1.  __init__(supported, hook) - Initialize ReactionRate class\n    2.  parse_species(rxns) - Return list of species in reaction data\n    3.  check_keys()\n    4.  check_structure()\n    5.  check_reaction_types()\n    6.  check_reaction_consistency() \n    7.  check_species_eq_consistency() \n    8.  check_species_stoich_consistency()\n    9.  check_species_in_db()\n    10. check_input_file(rxns)\n    11. parse_reaction_rate_params(reaction, convert_units) - Parse reaction coefficient params\n    12. parse_stoich_coefs(string, species) - Parse stoichiometric coefficients\n    13. get_weight(string, species) - Return total molecular weight for reactants/products of reactions\n    \n**\\__init__**\n    \n    Sets class-wide parameters\n    \n**parse_species(rxns)**\n\n    Parameters:\n    rxns: XML File\n    \n    Returns:\n    species: List of species\n    \n**check_keys()**\n\n    Parameters:\n    None\n    \n    Returns:\n    ValueError if missing tags in XML file\n    \n**check_structure()**\n\n    Parameters:\n    None\n    \n    Returns:\n    ValueError if structure of XML file not self-consistent\n    \n**check_reaction_types()**\n\n    Parameters:\n    None\n    \n    Returns:\n    ValueError if reaction type not implemented in parser\n    \n**check_reaction_consistency()**\n\n    Parameters:\n    None\n    \n    Returns:\n    ValueError if reaction type tag inconsistent with equation\n\n**check_species_eq_consistency()**\n\n    Parameters:\n    None\n    \n    Returns:\n    ValueError if species in phase array inconsistent with equations\n    \n**check_species_stoich_consistency()**\n\n    Parameters:\n    None\n    \n    Returns:\n    None\n    \n**check_species_in_db()**\n\n    Parameters:\n    None\n    \n    Returns:\n    ValueError if species in phase array inconsistent with reactants/products\n    \n**check_input_file(rxns, check_mass)**\n\n    Parameters:\n    rxns: XML File\n    check_mass: Boolean\n    \n    Returns:\n    ValueError if any of check_ methods fail\n\n**parse_reaction_rate_params(reaction, convert_units)**\n\n    Parameters:\n    reaction: Input reaction\n    convert_units: Boolean\n    \n    Returns:\n    output: A list of parsed dictionaries for each reaction\n    \n**parse_stoich_coefs(string, species)**\n\n    Parameters:\n    string:\n    species:\n    \n    Returns:\n    coef_out:\n\n**get_weight(string, species)**\n\n    Parameters:\n    string:\n    species:\n    \n    Returns:\n    total_weight:\n \n---\n    \n## API Input Format\n* Elementary reactions in XML-format\n    * Currently, the following input format is accepted:\n\n```xml\n<ctml>\n    <reactionData id=\"test_mechanism\">\n        <!-- reaction 01  -->\n        <reaction reversible=\"yes\" type=\"Elementary\" id=\"reaction01\">\n            <equation>H + O2 [=] OH + O</equation>\n            <rateCoeff>\n                <Kooij>\n                    <A units=\"cm3/mol/s\">3.52e+16</A>\n                    <b>-0.7</b>\n                    <E units=\"kJ/mol\">71.4</E>\n                </Kooij>\n            </rateCoeff>\n            <reactants>H:1 O2:1</reactants>\n            <products>OH:1 O:1</products>\n        </reaction>\n    </reactionData>\n</ctml>\n```\n\n---\n\n## Basic usage and examples\n\n**Example 1:**\n\n```python\n# Import numpy and relevant flamespeed modules\nimport os\nimport numpy as np\nfrom flamespeed import chemkin\nfrom flamespeed.thermo import thermochem\nfrom flamespeed.test import test_reaction_rate\n\n# Set specie concentration vector\nx = np.array([2.0, 1.0, 0.5, 1.0, 1.0])\n\n# Initialize chemkin module with XML file\na = fs.ReactionRate()\na.read_XML('./flamespeed/data/rxns_hw5.xml')\nprint(a)\n\n# Set temperature and get reaction rates\na.set_temp(750)\nf = a.get_reaction_rate(x)\nprint(f)\n\n--\nOutput:\n\nNumber_of_reactions:3                     \nNumber_of_species:5\nNumber_of_reversible_reactions:0\nReversible:False                     \nReaction_type:Elementary                     \nSpecies_list:['H2', 'O2', 'OH', 'HO2', 'H2O']\n\nReaction rate:\n\n[-3607077.87280406 -5613545.18362079  9220623.05642485  2006467.31081673\n -2006467.31081673]\n\n```\n\n**Example 2:**\n\n```python\n# Import numpy and relevant flamespeed modules\nfrom flamespeed import chemkin\n\n# Set specie concentration vector\nx = [1.0, 1.0, 1.0, 1.0, 1.0]\n\n# Initialize chemkin module with XML file\na = chemkin.ReactionRate()\na.read_XML('./flamespeed/data/rxns_hw5.xml')\n\n# Set temperature and get reaction rates\na.set_temp(2500)\nf = a.get_reaction_rate(x)\nprint(f)\n\n--\nOutput:\n\nReaction rate:\n\n[ -4.51065356e+08  -4.57236287e+08   9.08301644e+08   6.17093098e+06\n  -6.17093098e+06]\n```\n\n**Example 3:**\n\n```python\n# Import numpy and relevant flamespeed modules\nfrom flamespeed import chemkin\n\n# Set specie concentration vector\nx = [2.0, 1.0, 0.5, 1.0, 1.0, 1.5, 0.5, 1]\n\n# Initialize chemkin module with XML file\na = chemkin.ReactionRate()\na.read_XML('./flamespeed/data/rxns_reversible_mixed.xml')\nprint(a)\n\n# Set temperature and get reaction rates\na.set_temp(750)\nf = a.get_reaction_rate(x)\nprint(f)\n\n--\nOutput:\n\nNumber_of_reactions:11                   \nNumber_of_species:8\nNumber_of_reversible_reactions:7\nReversible:Some                     \nReaction_type:Elementary                     \nSpecies_list:['H', 'O', 'OH', 'H2', 'H2O', 'O2', 'HO2', 'H2O2']\n\nReaction rate:\n\n[-1.84263836e+14   3.18111565e+13   2.20832161e+14   4.07078985e+13\n   3.44685565e+13  -1.19150183e+13  -7.63606019e+13  -5.52803168e+13]\n```\n\n\n**Example 4: Verify Integrity & Convert Units**\n\n```python\n# Import numpy and relevant flamespeed modules\nfrom flamespeed import chemkin\n\n# Set specie concentration vector\nx = [0.5, 0, 0, 2, 0, 1]\n\n# Initialize chemkin module with XML file\na = chemkin.ReactionRate()\na.read_XML('./flamespeed/data/rxns_units.xml', verify_integrity=True, convert_units=True)\nprint(a)\n\n# Set temperature and get reaction rates\na.set_temp(900)\nf = a.get_reaction_rate(x)\nprint(f)\n\n--\nOutput:\n\nNumber_of_reactions:3                     \nNumber_of_species:6                     \nNumber_of_reversible_reactions:0                     \nReversible:No                     \nReaction_type:Elementary                     \nSpecies_list:['H', 'O', 'OH', 'H2', 'H2O', 'O2']\n\n\nReaction rate:\n[ -8.08297505e-14   8.08297505e-14   8.08297505e-14   0.00000000e+00\n   0.00000000e+00  -8.08297505e-14]\n```\n\n\n**Example 5: (Parsing Hooked Reactions - ThreeBody, TroeThreeBody, Duplicate)**\n\n```python\nx = [0.5, 0, 0, 2, 0, 1]\n\n# Import reaction data\na = chemkin.ReactionRate()\nprint (\"[Three Body Parsed]\")\na.read_XML('./flamespeed/data/rxn_ThreeBody.xml', verify_integrity=True, convert_units=True)\nfor idx, item in enumerate(a.k_params_nonelementary):\n\tprint (\"Reaction {}\".format(str(idx)))\n\tfor rxn in item:\n\t\tprint (rxn)\n\n\nprint (\"\\n[Troe Three Body Parsed]\")\na = chemkin.ReactionRate()\na.read_XML('./flamespeed/data/rxn_TroeFalloffThreeBody.xml', verify_integrity=True, convert_units=True)\nfor idx, item in enumerate(a.k_params_nonelementary):\n\tprint (\"Reaction {}\".format(str(idx)))\n\tfor rxn in item:\n\t\tprint (rxn)\n\nprint (\"\\n[Duplicate Parsed]\")\na = chemkin.ReactionRate()\na.read_XML('./flamespeed/data/rxn_Duplicate.xml', verify_integrity=True, convert_units=True)\nfor idx, item in enumerate(a.k_params_nonelementary):\n\tprint (\"Reaction {}\".format(str(idx)))\n\tfor rxn in item:\n\t\tprint (rxn)\n\n--\nOutput:\n\n[Three Body Parsed]\nReaction 0\n{'Type': 'Kooij', 'A': 38000000000.0, 'b': -2.0, 'E': 0.0, 'name': None}\n{'Type': 'efficiencies', 'H2': '2.5', 'H2O': '12.0', 'default': '1.0'}\nReaction 1\n{'Type': 'Kooij', 'A': 48000000000.0, 'b': -5.0, 'E': 4.1840000000000002, 'name': None}\n{'Type': 'efficiencies', 'H2': '2.5', 'H2O': '12.0', 'default': '1.0'}\n\n[Troe Three Body Parsed]\nReaction 0\n{'Type': 'Kooij', 'A': 636600000.0, 'b': -1.72, 'E': 2195.7631999999999, 'name': 'k0'}\n{'Type': 'Kooij', 'A': 1475000.0, 'b': 0.6, 'E': 0.0, 'name': None}\n{'Type': 'Troe', 'alpha': 0.8, 't1': 1e+30, 't2': 1e+30, 't3': 1e+30}\n{'Type': 'efficiencies', 'H2': '2.0', 'H2O': '11.0', 'O2': '0.78', 'default': '1.0'}\n\n[Duplicate Parsed]\nReaction 0\n{'Type': 'Arrhenius', 'A': 420000000.0, 'E': 50132.688000000002}\n{'Type': 'Arrhenius', 'A': 130000.0, 'E': -6816.9912000000004}\n```\n\n---\n\n## New Feature\n\n#### 1. Motivation and feature description\n\nThe new features for the Flamespeed library adds flexibility by converting user inputs with relevant warnings if incomplete or non-standard input is provided. An array of validation checks are performed on the input data to ensure the input data is self-consistent, improving the robustness of the package.\n\n**Flexibility**\n\n* Additional usage flexibility is allowed for in several areas:\n\n* Unit conversion:\n\n         a. Parsed reaction coefficient data is converted to metric units before any \n           computations for a finite set of common conversions that might be required\n\n* Incomplete Reaction Rate Parameters:\n\n         a. Calling Arrhenius yet providing factor b in the XML file \n            results in flamespeed applying Modified Arrhenius \n        \n* Three-Body Reactions:\n\n         a. Parser extended to import parameters for three-body reactions\n         b. Implemented hooks in code for further future development of three-body reactions\n\n**Robustness and consistency**\n\n* Additional robustness will be achieved following a two-pronged approach; namely checking user input consistency (i.e., in the form of XML files) as well as enforcing internal consistency throughout.\n\n* User Input:\n        \n        a. Parsed chemical reaction equations are checked for conservation of mass\n        b. Validation performed to ensure required data exists in thermo database for \n           input species\n\n* Self-consistent reaction data in XML file, by performing the following integrity checks:\n\n         a. XML file contains all the required tags and is self-consistent\n         b. Reaction type tags are consistent with reaction type implied by equations\n         c. Species in reaction equations correspond to the \"species array\" in XML file\n         d. Species in product/reactant arrays correspond to \"species array\" in XML file\n         \nThe primary goal of the flamespeed chemical kinetics library is for users to use the package for real-life chemical kinetics computations. As such, providing potential users with additional measures to assure both user input consistency and internal library consistency is deemed highly relevant and practical. Added flexibility in terms of reaction rate specification and three-body reaction hooks only add to the relevance of this library to practicioners.\n\n\n#### 2. Implementation details\n\nAnother module (parser.py) that contains most of the features described above, was added to the library. Given the scope of the additional features it made sense to create a separate module, rather than including this in the main chemkin module. Changes were also made to the main module (chemkin.py) to integrate the new features.\n\nAn overview of the additional features added to each of the modules is included below. See Parser Module section above for a more detailed specification of the classes and methods included in the module.\n\n**Module descriptions**\n\n*parser.py*\n\n* Contains all of the methods to check / validate self-consistency of the input data\n* Includes methods to extract the list of species, reaction rate coefficient parameters and stoichiometric coefficients\n* Checks reactions for conservation of mass and performs unit conversions if required\n\n*chemkin.py*\n\n* Contains the main method to read reaction data from the XML file (read_XML)\n* Performing validation checks on the input file and converting units have been added as optional parameters to ensure consistency with other projects and previous versions of this project\n\n**Unit Conversion**\n\nA central part to the proposed feature is the possibility to convert a random set of units inherited from an `xml` input file into a set of consistent SI-units. A few points are worth highlighting below.\n\nWhere do the units occur: \n* Arrhenius prefactor \"A\"\n    * Found in the `xml` input file\n* Activation energy \"E\"\n    * Found in the `xml` input file\n    \nWhat SI base units do conversions lead to:\n* Meter (and its derivatives such as $m^3$, $m^6$, etc.)\n* Joule\n* Mol\n* Seconds\n\nWhat units are accounted for?\n* A number of basic units are available as standard in the flamespeed package:\n    * Length: ft, yd, cm, mm, etc.\n    * Energy: cal, kcal, kJ, etc.\n    * Time: minutes, etc.\n* Users can expand the list of allowed units by simply expanding the `./data/units.csv` file with as many units as desired\n    * In `./data/units.csv` users can also easily change the base units (i.e., it need not necessarily be those specified above)\n    \n**Conservation of mass**\n\nThe read_XML method that reads the reaction data from an XML file has an option to check conservation of mass for each of the reactions. In order to do this, the molecular weight of each specie inlcuded in the system is read from the `thermo` SQL database to compare the total mass of the reactants and products in each reaction. If conservation of mass is vioated for any reaction in the system an appropriate error message is displayed. This option can be turned off if there are valid species included in the reaction data, which is not included in the database.\n\n\n```python\n\n```\n", "meta": {"hexsha": "99fe40e6837b27ae2e06688bb852e9c0f41e1e16", "size": 33255, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/documentation.ipynb", "max_stars_repo_name": "bkleyn/flamespeed", "max_stars_repo_head_hexsha": "00090c40dfb55e7f9203feab66b836da60bde353", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/documentation.ipynb", "max_issues_repo_name": "bkleyn/flamespeed", "max_issues_repo_head_hexsha": "00090c40dfb55e7f9203feab66b836da60bde353", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/documentation.ipynb", "max_forks_repo_name": "bkleyn/flamespeed", "max_forks_repo_head_hexsha": "00090c40dfb55e7f9203feab66b836da60bde353", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4483985765, "max_line_length": 571, "alphanum_fraction": 0.5499022703, "converted": true, "num_tokens": 7000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926492132671, "lm_q2_score": 0.09401017390532694, "lm_q1q2_score": 0.042247481104314824}}
{"text": "--- \nProject for the course in Microeconometrics | Summer 2020, M.Sc. Economics, Bonn University | [Ying-Xuan Wu](https://github.com/amanda8412383)\n\n# Replication of Duflo E, Dupas P, Ginn T, Barasa GM, Baraza M, Pouliquen V, et al. (2019) <a class=\"tocSkip\">   \n---\n\nThis notebook contains my replication of the results from the following paper:\n\n> Duflo E, Dupas P, Ginn T, Barasa GM, Baraza M, Pouliquen V, et al. (2019) HIV prevention among youth: A randomized controlled trial of voluntary counseling and testing for HIV and male condom distribution in rural Kenya\n\n<!-- ##### Downloading and viewing this notebook:\n\n* The best way to view this notebook is by downloading it and the repository it is located in from [GitHub](https://github.com/HumanCapitalAnalysis/microeconometrics-course-project-amanda8412383). \n\n* Other viewing options like _MyBinder_ or _NBViewer_ .\n\n\n* The original paper, as well as the data provided by the authors can be accessed [here](https://dataverse.harvard.edu/dataset.xhtml?persistentId=doi:10.7910/DVN/CVOPZL).\n\n##### Information about replication and individual contributions:\n\n* Due to the unavailability of original code and the massiveness of the dataset, the estimations all differ from the original paper in various degrees.\n\n* One of the most important outcome variable isn't found, the attempts on searching it is documented in section 7\n\n* For the replication, I try to remain true to the original structure of the paper, all the panels and rows are lined as they appear in Duflo et al. (2019) and named identically.\n\n* some of the columns feature in my replication appear as second-row indexes compared to the original tables, and the incidence rate has become independent to suit my workflow in Python.\n -->\n\n\n\n<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#1.-Introduction\" data-toc-modified-id=\"1.-Introduction-1\">1. Introduction</a></span></li><li><span><a href=\"#2.-Study-Design\" data-toc-modified-id=\"2.-Study-Design-2\">2. Study Design</a></span></li><li><span><a href=\"#3.-Identification-Problems\" data-toc-modified-id=\"3.-Identification-Problems-3\">3. Identification Problems</a></span></li><li><span><a href=\"#4.-Empirical-Strategy\" data-toc-modified-id=\"4.-Empirical-Strategy-4\">4. Empirical Strategy</a></span></li>\n    <li><span><a href=\"#5.-Replication-of-Duflo-et-al.-(2019)\" data-toc-modified-id=\"5.-Replication-of-Duflo-et-al.-(2019)-5\">5. Replication of Duflo et al. (2019)</a></span><ul class=\"toc-item\">\n        <li><span><a href=\"#5.1.-Data-and-Primary-cleaning\" data-toc-modified-id=\"5.1.-Data-and-Primary-cleaning-5.1\">5.1. Data and Primary cleaning</a></span></li>\n        <li><span><a href=\"#5.2.-Tables\" data-toc-modified-id=\"5.2.-Tables-5.2\">5.2. Tables</a></span><ul class=\"toc-item\"><li>\n            <span><a href=\"#5.2.1.-Table-1:-Summary-statistics-at-basline\" data-toc-modified-id=\"5.2.1.-Table-1:-Summary-statistics-at-basline-5.2.1\">5.2.1. Table 1: Summary statistics at basline</a></span></li><li><span><a href=\"#5.2.2.-Table-2:-Intention-to-treat-analysis\" data-toc-modified-id=\"5.2.2.-Table-2:-Intention-to-treat-analysis-5.2.2\">5.2.2. Table 2: Intention to treat analysis</a></span></li><li><span><a href=\"#5.2.3.-Table-3:-Effects-of-Intervention-on-other-outcomes\" data-toc-modified-id=\"5.2.3.-Table-3:-Effects-of-Intervention-on-other-outcomes-5.2.3\">5.2.3. Table 3: Effects of Intervention on other outcomes</a></span></li><li><span><a href=\"#5.2.4.-Table-4:-Heterogenetiy-test\" data-toc-modified-id=\"5.2.4.-Table-4:-Heterogenetiy-test-5.2.4\">5.2.4. Table 4: Heterogenetiy test</a></span></li></ul></li></ul></li>\n    <li><span><a href=\"#6.-Discussion\" data-toc-modified-id=\"6.-Discussion-6\">6. Discussion</a></span></li>\n    <li><span><a href=\"#7.-Debug:-HSV-2-at-baseline\" data-toc-modified-id=\"7.-Debug:-HSV-2-at-baseline-7\">7. Debug: HSV-2 at baseline</a></span><ul class=\"toc-item\">\n    <li><span><a href=\"#7.1.-Searching-dataset-and-verifying\" data-toc-modified-id=\"7.1.-Searching-dataset-and-verifying-7.1\">7.1 Searching dataset and verifying</a></span></li>\n    <li><span><a href=\"#7.2.-Others\" data-toc-modified-id=\"7.2.-Others-7.2\">7.2 Others</a></span></li>\n    </ul></li>\n    <li><span><a href=\"#8.-References\" data-toc-modified-id=\"8.-References-8\">8. References</a></span></li></ul></div>\n\n\n```python\nfrom auxiliary import *\nfrom IPython.display import display\nfrom IPython.display import Image\npd.options.display.max_rows = None\n```\n\n---\n# 1. Introduction \n---\n\nDuflo et al. (2019) examine the effects of Voluntary Counseling and Testing for HIV (VCT) and increasing access to male condoms compared to standard available HIV prevention services, using biological and behavioral outcomes, among youth in Western Kenya. VCT, serving as the entry to HIV treatment and care, is a test of accessing one\u2019s HIV serostatus, in addition to receiving individualized risk-reduction counseling. VCT is supposed to help individuals reduce risky sexual behaviors and prevent themselves and their partners from HIV and other sexually transmitted infections such as Herpes Simplex Type 2 (HSV-2). Even though some of the previous studies show the reduction of risky sexual behavior in testing-positive individuals, other studies bring about the concern of disinhibition among those testing negative (Sherr et al. 2007). \n\nThrough a four-arm, unblinded, individually randomized controlled trial implemented between 2009 and 2012 in four districts of Kenya\u2019s Western Province, including samples of 10,245 youth aged 17 to 24 randomly assigned to receive community-based VCT, 150 male condoms, both VCT and condoms, or neither program, Duflo et al. (2019) examine the effect of these two interventions among the youth. The result suggests there are no statistically significant effects on the risk of HIV, or other behavioral or knowledge outcomes including self-reported pregnancy rates.\n\n**Main variables** \n\n| **Interventions**      | **Main outcomes**       |\n|------------------------|-------------------------|\n| community-based VCT    | HIV                     |\n| 150 male condoms       | HSV-2                   |\n| both                   |                         |\n| neither                |                         |\n\n \n \n\nIn this notebook, I attempt to replicate the results presented in the paper by Duflo et al. (2019) but only acquire similar result and failed to find one of the most important outcome variable.In section 2, the methodology adopted by Duflo et al. (2019) is presented, regarding how sampling, treatment, randomizing and tracking are conducted. In Section 3, possible identification is brought out from 3 different aspects, containing selection bias, measure error from self report, and externality. Section 4 briefly discusses the methodology used by the authors. Section 5 shows my replication of the results in the paper and discussion thereof.  Section 6 offers  discussion on insignificant results. Section 7 reveals my failing attemps on finding HSV-2 testing result at baseline.\n\n\n---\n# 2. Study Design\n---\n\n#### **Sample**\n\nThe samples are from a previous study of the authors ( Duflo, Dupas, and Krewer 2015) which is clustered randomized controlled trial regarding teacher HIV training program and distribution of free uniform, consisting of 19289 enrolled students in grade 6 of 328 schools in 2003. 55% of them, 10245 individuals are trackable during the first round tracking between March 2009 to July 2010. In total, they represent 85% of aged 17 - 24 in 2009 western Kenya. \n\nAccording to the criteria, the participants must :\n1. Participated in the previous study, which implied at least attended grade 6\n2. Residency in the study district\n3. Provided informed consent \n\n#### **Randomizing** \nStratification by gender, primary school, matriculation of secondary school in as from July 2007, ever pregnant as of 2007, randomly assigned to four arms, 25% each. \n\n#### **Treatment** \nThere are standard VCT available to everyone at local health facilities, however, the intervention provided in the trial within community lowering travel time and cost, and social cost of visiting a HIV testing center. For the condom intervention arm, participants were provided 150 male condoms, they could take all or only of these condoms.\n\n#### **Tracking**\nFollowed up survey is conducted from April 2011 to May 2013, if the respondent did not show up, field officers would track down the person. 25% of those whose acquittances providing contact information and 10% of those who can\u2019t be contacted at all are randomly selected for further intensive tracking. Intensive tracking weight is included in the estimation.\n\n\n---\n# 3. Identification Problems\n---\nConsidering Duflo et al. (2019) do not obtain any significant result, it might be more suitable to discuss possible identification problems in this section instead of identification. I am not trying to suggest obtaining significant result means problem-free, it just doesn\u2019t seem meaningful to discuss how their identifications work in this case.\n\n#### **casaul graph**\nFor a randomized control trial, it is expected to block all the back door part of unobservables and other controlled variable and obtain a clean casal effect. However, in this paper it's either fail to block backdoor path successfully or the treatments have no effect to it. I'll discuss some of the possible non-blocked backdoor part at later part of this section. In discussion, the possible correlations suggest by authors are listed.\n\n\n```python\nImage(filename='causal graph.jpg')\n```\n\n\n\n\n    \n\n    \n\n\n\n#### **Selection bias**\nAs a randomized control trial, this estimation is supposed to be free from selection bias. Nevertheless, in study design, Duflo et al. (2019) mention that the sample is based on its previous study which restricts the participants of this study to those who have attended at least 6 grade and accepting HIV related knowledges. Considering the following model from Greene (2006): \n\\begin{equation}\nyi = xi' \\beta + ei\\\\\nzi^* = wi' \\gamma + ui\\\\\nzi = 1(zi^* > c)\n\\end{equation}\nWhere $yi$ is our outcome variable. $xi$ is the treatment group. $zi$ is attending grade 6 or not. wi is are exogenous factors decided to attend 6 grade or not. $ei, ui$ are error terms.\nThen we can rewrite the function into:\n\\begin{equation}\nE(yi|wi, ui) = xi' \\beta + E(ei|wi, ui)\\\\\n = xi' \\beta + E(ei|ui)\n\\end{equation}\nFor $E(ei|ui)$ not equals to zero, we might obtain a biased estimator. And such an example is easily thinking of, for example, children from poverty background may be more likely to drop out, and higher chance to become sex worker, can't afford to buy condoms, missing sex education in class are all factors that could increase their chance of getting STI. \n\nIn the latter discussion, the authors do not bring about this issue, but do admit lower external validity, while stressing as HIV prevention scaled up, increasing population would have access to prevention information.\n\n#### **Measure error from self report**\nBecause of the behavioral outcomes are acquired through surveys, one common problem from self-reported is the imprecision of the data, possibly resulting from causes such as forgetfulness or deception. \nconsidering models from Hansen (2020):\n\\begin{equation}\nyi = \\beta xi^* + ui\\\\\n\\textrm{where} \\quad E[ui|xi^*] = 0\\\\\nxi = xi^* + vi\n\\end{equation}\nWhere $yi$ is one of our outcome variables, $xi$ is reported behavior, $ui$ is the error term, and vi are deviation originated from forgetfulness or deception.\nrewritten the function as:\n\\begin{equation}\nyi = \\beta xi^* + ui\\\\\n\\textrm{where} \\quad ei = -\\beta vi + ui\\\\\n\\end{equation}\nThen we can get the covariance of our treatment and residual is the variance of this reporting mistake. As we need $xi$ and residual to be independent.\n\nBut I would say measurement error has limited influence in this case. Only a few behavior problems serving as independent variables, for example ever pregnant and school enrollment in 2007 and is theoretically possible to do fact checks on these two variables. Most of the behavioral outcomes are serving as dependent variables in the logistic regression stated at section 4, in which case affect our estimation much lesser.\n\n\n\n#### **Externalty**\nOne intriguing question to ask is whether these treatments induce externality, Miguel, Edward, and Kremer (2004) finds out in a randomized trial on 75 Kenya primary schools that medical treatment for intestinal helminths in the treatment group also reducing the transmission within the control group, even their randomized trial is taking place across schools. Using male condoms would undoubtedly reduce the possibility of infecting sex partners and thus contaminate the obtaining result. If the subject having any behavioral change after receiving VCT, it\u2019ll also affect their sexual partners. Such an externality exists hinder us to detach treatment effects from the treatment group. I haven\u2019t found any paper having empirical evidence on how would externality affecting HIV research, but some of the papers point this out and try to discuss the possible influence, such as Canning D. (2006).\n\n---\n<span style=\"color:orange\">**NOTE**:</span> the  model used in this paper is logistic regression while I use linear notations in section 3 for simplicity. For nonlinear model, endogeneity and externality are still problems that affect large sample property of estimators which have an in-depth discussion in _A Logit Model With Endogenous Explanatory Variables and Network Externalities_ ( de Grange et al. 2015)\n\n---\n# 4. Empirical Strategy\n---\nthe following listed methods are statistic analysis used In Duflo et al. (2019).\n\n#### **Descriptive statistic**\nFor both baseline and phase 2, descriptive data is shown. Estimation in stage 2 takes into account of weighted follow-up rate. The share of the total sample and comparison among males and females is shown and a second analysis to test for heterogeneity in the result by gender, childbearing experience at baseline, and baseline belief of HIV infection likelihood.\n\n#### **Incidence rate**\nHSV-2 incidence was calculated by dividing respondents who were negative at baseline to new HSV-2 cases in each treatment arm by the total person-years of exposure. If the person remained negative, person-years of exposure is calculated as the total time from the baseline test to the follow-up. For the newly infected cases, it\u2019s calculated as half the time between the baseline test and the positive test.\n\n#### **Weighted logistic regression**\nFor estimating the effect of interventions on outcomes, the following logistic regression weighted by survey tracking strategy is run to compare outcomes in each treatment arm to the control, and the adjusted odds ratio and confidence interval are reported. Regressors are listed as follow:\n\n\n|**regressors**          |                         \n|------------------------|\n| age group              |\n| months between 2 surveys             |\n| gender                               |\n| secondary school enrollment in 2007  |\n| ever pregnant by 2007  |\n| treatment arm          |  \n\n\n\n---\n# 5. Replication of Duflo et al. (2019)\n---\n\n## 5.1. Data and Primary cleaning \n\n\nDuflo et al. (2019) use a data set with 2374 variables and 19293 participants. The following list concluding main sources of these variable. I prune the dataset because of even lft can't afford to upload original data set.\n\n- answers, remarks of baseline questionnaire\n- answers, remarks of phase 2 questionnaire\n- school properties such as location, average scores of all students in KCPE\n- testing results, both HSV-2 and HIV require multiple time of testing  \n- poorly naming variable that might be created for analysis  \n\n\nEven though the problem set has 19293 respondents, the number of total participants in this project is supposed to yield 7565, the rest are participants of the authors\u2019 previous study. An important question would be how the authors filtering the data and ruling out problematic entries. Since neither the rules of excluding an entry nor how did they clean the data is mentioned in the essay. Besides, because of the majority data are from surveys, 92 variables are naming with \"comments\" describing the situation in the data collecting process. For example, in Log_comment there are entries describing as \"mentally ill\" or \"duplicate\" even though they are surveyed.  After trying all the combinations that seems reasonable to me, I filtered the data by \n1. having assigned to a treatment group\n2. labeled as surveyed\n3. labeled as tracked\n4. discarded all the entries that have LOG_comments \nThrough this, I gaining an approximate participation number. Unfortunately, this means all my statistics would be different in various degrees with the paper.\n\n\n\n\n```python\nind = df_filter.group.value_counts()\ntotal = ind.sum()\nprint(ind)\nprint(f'total participant {total}')\n```\n\n    Control           1889\n    VCT only          1866\n    Condom only       1855\n    Condom and VCT    1848\n    Name: group, dtype: int64\n    total participant 7458\n\n\n##  5.2. Tables\n\n### 5.2.1. Table 1: Summary statistics at basline\n\nTable 1 shows baseline characteristics of man and woman across 4 trial arm. This table only includes individuals that have been surveyed at follow up. Because of lacking the original code, these variables are recreating myself. The below list describes the method I choose. This is the only table I forgo recreate percentage. As previously mentioned, the baseline HSV-2 result is nowhere to find, thus, second phase HSV-2 is used here.\n\n| **Variables**          | **Method**              |\n|------------------------|-------------------------|\n| Number of individuals  | counting unique pupilid in each group   |\n| Age                    | create dummy through variable \"age2009\" |\n| Total year of schooling| create dummy through answer to \"Q_b1_13_school_years\"|\n| HSV-2 positive         | using HSV-2 result of phase 2 instead   |\n| Currently married      | people who have  \"an_spouse_age\"        |\n| Ever or partner ever pregnant|people who have \"evpreg07v2\" (womwn only) or \"Track_children_number\" > 0 (both gender)|\n| Ever had sex           | using \"an_everhadsex\"                   |\n| Last sex used condom   | using answer of \"Q_b4_127_last_sex_use_condom\" |\n| Ever had multiple partners| using \"an_multiplepartners\"          |\n| Ever tested for HIV    | using \"an_everHIVtested\"                |\n| Believed current HIV infection| using answer to \"Q_b3_99\"        |\n| Believed future HIV infection | using answer to \"Q_b3_100\"       |\n| Named 3 prevention      | from Dummies \"an_Q_b3_80_how_prevent_hiv_1\" to 19 has at least 3 of them being 1                         |\n| Answered 3 questions    |\"an_Q_b3_83\", \"an_Q_b3_84\" negative & \"an_Q_b3_88\" being positive |\n| Showed positive attitude|\"an_Q_b3_112_agree_with_statement\" is 1 & for question number 109 to 111 is 0|\n\n3 HIV knowledge question is defined as follow by the author:\n1. Can HIV be transmitted to a baby in the womb? (Q_b3_83)\n2. Can HIV be transmitted to a baby during breastfeeding? (Q_b3_84)\n3. Can HIV spread through mosquito bites? (Q_b3_88)\n\n\npositive attitude is defined as follow by the author:\n1. Agreed that people with HIV/AIDS should be treated the same as people without HIV/AIDS (an_Q_b3_112_agree_with_statement)\n2. Disagreed that prostitutes or promiscuous men are responsible for spreading HIV(\"(an_Q_b3_110_agree_with_statement, an_Q_b3_111_agree_with_statement)\n3. Disagreed that HIV was punishment for bad behavior (an_Q_b3_109_agree_with_statement)\n\n\n\n```python\n#variables in table 1\nvarlist = ['Number of individuals', 'Age at baseline_<19', 'Age at baseline_19-20', 'Age at baseline_21-22', 'Age at baseline_>22',\n          'Not enrolled in school', \n          'Total year of schooling_<10', 'Total year of schooling_10-11', 'Total year of schooling_12-13', 'Total year of schooling_>13',\n          'HSV-2 positive', 'Currently married', 'Ever or partner ever pregnant', 'Ever had sex', 'Last sex used condom', 'Ever had multiple partners', 'Ever tested for HIV',\n          'Believed current HIV infection', 'Believed future HIV infection', \n          'Named 3 prevention', 'Answered 3 questions', 'Showed positive attitude']\ntable1(df_merge, varlist)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th colspan=\"4\" halign=\"left\">all</th>\n      <th colspan=\"4\" halign=\"left\">woman</th>\n      <th colspan=\"4\" halign=\"left\">man</th>\n    </tr>\n    <tr>\n      <th>group</th>\n      <th>Condom and VCT</th>\n      <th>Condom only</th>\n      <th>Control</th>\n      <th>VCT only</th>\n      <th>Condom and VCT</th>\n      <th>Condom only</th>\n      <th>Control</th>\n      <th>VCT only</th>\n      <th>Condom and VCT</th>\n      <th>Condom only</th>\n      <th>Control</th>\n      <th>VCT only</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Number of individuals</th>\n      <td>1848</td>\n      <td>1855</td>\n      <td>1889</td>\n      <td>1866</td>\n      <td>823</td>\n      <td>814</td>\n      <td>864</td>\n      <td>838</td>\n      <td>1025</td>\n      <td>1041</td>\n      <td>1025</td>\n      <td>1028</td>\n    </tr>\n    <tr>\n      <th>Age at baseline_&lt;19</th>\n      <td>484</td>\n      <td>515</td>\n      <td>490</td>\n      <td>497</td>\n      <td>249</td>\n      <td>282</td>\n      <td>294</td>\n      <td>295</td>\n      <td>235</td>\n      <td>233</td>\n      <td>196</td>\n      <td>202</td>\n    </tr>\n    <tr>\n      <th>Age at baseline_19-20</th>\n      <td>933</td>\n      <td>915</td>\n      <td>957</td>\n      <td>920</td>\n      <td>449</td>\n      <td>424</td>\n      <td>446</td>\n      <td>410</td>\n      <td>484</td>\n      <td>491</td>\n      <td>511</td>\n      <td>510</td>\n    </tr>\n    <tr>\n      <th>Age at baseline_21-22</th>\n      <td>370</td>\n      <td>376</td>\n      <td>383</td>\n      <td>389</td>\n      <td>110</td>\n      <td>97</td>\n      <td>109</td>\n      <td>113</td>\n      <td>260</td>\n      <td>279</td>\n      <td>274</td>\n      <td>276</td>\n    </tr>\n    <tr>\n      <th>Age at baseline_&gt;22</th>\n      <td>61</td>\n      <td>49</td>\n      <td>59</td>\n      <td>59</td>\n      <td>15</td>\n      <td>11</td>\n      <td>15</td>\n      <td>20</td>\n      <td>46</td>\n      <td>38</td>\n      <td>44</td>\n      <td>39</td>\n    </tr>\n    <tr>\n      <th>Not enrolled in school</th>\n      <td>927</td>\n      <td>921</td>\n      <td>954</td>\n      <td>927</td>\n      <td>462</td>\n      <td>423</td>\n      <td>452</td>\n      <td>444</td>\n      <td>465</td>\n      <td>498</td>\n      <td>502</td>\n      <td>483</td>\n    </tr>\n    <tr>\n      <th>Total year of schooling_&lt;10</th>\n      <td>501</td>\n      <td>455</td>\n      <td>491</td>\n      <td>499</td>\n      <td>257</td>\n      <td>230</td>\n      <td>281</td>\n      <td>266</td>\n      <td>244</td>\n      <td>225</td>\n      <td>210</td>\n      <td>233</td>\n    </tr>\n    <tr>\n      <th>Total year of schooling_10-11</th>\n      <td>409</td>\n      <td>483</td>\n      <td>477</td>\n      <td>457</td>\n      <td>202</td>\n      <td>209</td>\n      <td>203</td>\n      <td>210</td>\n      <td>207</td>\n      <td>274</td>\n      <td>274</td>\n      <td>247</td>\n    </tr>\n    <tr>\n      <th>Total year of schooling_12-13</th>\n      <td>810</td>\n      <td>805</td>\n      <td>808</td>\n      <td>786</td>\n      <td>333</td>\n      <td>338</td>\n      <td>354</td>\n      <td>322</td>\n      <td>477</td>\n      <td>467</td>\n      <td>454</td>\n      <td>464</td>\n    </tr>\n    <tr>\n      <th>Total year of schooling_&gt;13</th>\n      <td>95</td>\n      <td>87</td>\n      <td>90</td>\n      <td>97</td>\n      <td>18</td>\n      <td>25</td>\n      <td>16</td>\n      <td>24</td>\n      <td>77</td>\n      <td>62</td>\n      <td>74</td>\n      <td>73</td>\n    </tr>\n    <tr>\n      <th>HSV-2 positive</th>\n      <td>164</td>\n      <td>141</td>\n      <td>146</td>\n      <td>146</td>\n      <td>85</td>\n      <td>76</td>\n      <td>81</td>\n      <td>78</td>\n      <td>79</td>\n      <td>65</td>\n      <td>65</td>\n      <td>68</td>\n    </tr>\n    <tr>\n      <th>Currently married</th>\n      <td>367</td>\n      <td>369</td>\n      <td>387</td>\n      <td>389</td>\n      <td>223</td>\n      <td>217</td>\n      <td>241</td>\n      <td>239</td>\n      <td>144</td>\n      <td>152</td>\n      <td>146</td>\n      <td>150</td>\n    </tr>\n    <tr>\n      <th>Ever or partner ever pregnant</th>\n      <td>397</td>\n      <td>363</td>\n      <td>385</td>\n      <td>395</td>\n      <td>292</td>\n      <td>271</td>\n      <td>290</td>\n      <td>291</td>\n      <td>105</td>\n      <td>92</td>\n      <td>95</td>\n      <td>104</td>\n    </tr>\n    <tr>\n      <th>Ever had sex</th>\n      <td>1239</td>\n      <td>1217</td>\n      <td>1256</td>\n      <td>1269</td>\n      <td>508</td>\n      <td>502</td>\n      <td>526</td>\n      <td>547</td>\n      <td>731</td>\n      <td>715</td>\n      <td>730</td>\n      <td>722</td>\n    </tr>\n    <tr>\n      <th>Last sex used condom</th>\n      <td>503</td>\n      <td>468</td>\n      <td>519</td>\n      <td>505</td>\n      <td>156</td>\n      <td>146</td>\n      <td>170</td>\n      <td>164</td>\n      <td>347</td>\n      <td>322</td>\n      <td>349</td>\n      <td>341</td>\n    </tr>\n    <tr>\n      <th>Ever had multiple partners</th>\n      <td>578</td>\n      <td>545</td>\n      <td>579</td>\n      <td>571</td>\n      <td>184</td>\n      <td>144</td>\n      <td>183</td>\n      <td>176</td>\n      <td>394</td>\n      <td>401</td>\n      <td>396</td>\n      <td>395</td>\n    </tr>\n    <tr>\n      <th>Ever tested for HIV</th>\n      <td>781</td>\n      <td>819</td>\n      <td>850</td>\n      <td>803</td>\n      <td>421</td>\n      <td>433</td>\n      <td>455</td>\n      <td>451</td>\n      <td>360</td>\n      <td>386</td>\n      <td>395</td>\n      <td>352</td>\n    </tr>\n    <tr>\n      <th>Believed current HIV infection</th>\n      <td>429</td>\n      <td>439</td>\n      <td>401</td>\n      <td>452</td>\n      <td>174</td>\n      <td>166</td>\n      <td>165</td>\n      <td>172</td>\n      <td>255</td>\n      <td>273</td>\n      <td>236</td>\n      <td>280</td>\n    </tr>\n    <tr>\n      <th>Believed future HIV infection</th>\n      <td>602</td>\n      <td>618</td>\n      <td>608</td>\n      <td>648</td>\n      <td>279</td>\n      <td>261</td>\n      <td>285</td>\n      <td>286</td>\n      <td>323</td>\n      <td>357</td>\n      <td>323</td>\n      <td>362</td>\n    </tr>\n    <tr>\n      <th>Named 3 prevention</th>\n      <td>554</td>\n      <td>561</td>\n      <td>548</td>\n      <td>569</td>\n      <td>234</td>\n      <td>232</td>\n      <td>243</td>\n      <td>247</td>\n      <td>320</td>\n      <td>329</td>\n      <td>305</td>\n      <td>322</td>\n    </tr>\n    <tr>\n      <th>Answered 3 questions</th>\n      <td>634</td>\n      <td>617</td>\n      <td>640</td>\n      <td>639</td>\n      <td>302</td>\n      <td>285</td>\n      <td>322</td>\n      <td>303</td>\n      <td>332</td>\n      <td>332</td>\n      <td>318</td>\n      <td>336</td>\n    </tr>\n    <tr>\n      <th>Showed positive attitude</th>\n      <td>334</td>\n      <td>352</td>\n      <td>330</td>\n      <td>312</td>\n      <td>114</td>\n      <td>152</td>\n      <td>140</td>\n      <td>108</td>\n      <td>220</td>\n      <td>200</td>\n      <td>190</td>\n      <td>204</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### 5.2.2. Table 2: Intention to treat analysis\nThis table shows HSV-2 and HIV outcomes across males and females. None of the intervention turns out to reduce the infection rate of any of these diseases significantly. Either adjusted odd ratio or weighted prevalence appears similar across interventions. \n\nFor recreation, query & key was passed into the function to create panels for all and both gender. And also variables are passed in as a pair of (consonant, denominator) to calculate weighted percent.due to these variables are all recorded in different forms and hidden in the variable sea. Hence it requires searching it out, transforming, and passing it in manually. The replication does not contain HSV-2 at baseline, hence the incidence rate is also not in this table. Although HIV cases can be found in both stages, the infection case is too low to have a valid estimation.\n\n\n| **Variables**          | **Method**              |\n|------------------------|-------------------------|\n| HSV-2                  | using \"hsv2_positive\"   |\n| HIV                    | using answer of \"p2_c2_233_hiv_result\" |\n\n\n```python\nquery = ['', 'sex == \"2 Female\"', 'sex == \"1 Male\"']\nkeys=['all', 'female', 'male']\nvarlist2 = [('HSV-2 positive', 'hsv2_accept'), ('HIV', 'p2_c2_233_hiv_result')]\n\nTable(df_merge, query, keys, varlist2, option = 'T2')\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>group</th>\n      <th>Condom and VCT</th>\n      <th>Condom only</th>\n      <th>Control</th>\n      <th>VCT only</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"10\" valign=\"top\">all</th>\n      <th rowspan=\"5\" valign=\"top\">HSV-2 positive</th>\n      <th>Weighted cases</th>\n      <td>191</td>\n      <td>162</td>\n      <td>164</td>\n      <td>179</td>\n    </tr>\n    <tr>\n      <th>N = 7440</th>\n      <td>1840</td>\n      <td>1854</td>\n      <td>1885</td>\n      <td>1861</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>10.38</td>\n      <td>8.74</td>\n      <td>8.7</td>\n      <td>9.62</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.14</td>\n      <td>0.95</td>\n      <td>NaN</td>\n      <td>0.96</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.94 - 1.39)</td>\n      <td>(0.77 - 1.16)</td>\n      <td>None</td>\n      <td>(0.79 - 1.18)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">HIV</th>\n      <th>Weighted cases</th>\n      <td>20</td>\n      <td>11</td>\n      <td>14</td>\n      <td>11</td>\n    </tr>\n    <tr>\n      <th>N = 5676</th>\n      <td>1420</td>\n      <td>1384</td>\n      <td>1396</td>\n      <td>1476</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>1.41</td>\n      <td>0.79</td>\n      <td>1</td>\n      <td>0.75</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.34</td>\n      <td>1.09</td>\n      <td>NaN</td>\n      <td>0.58</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.70 - 2.59)</td>\n      <td>(0.55 - 2.18)</td>\n      <td>None</td>\n      <td>(0.26 - 1.32)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"10\" valign=\"top\">female</th>\n      <th rowspan=\"5\" valign=\"top\">HSV-2 positive</th>\n      <th>Weighted cases</th>\n      <td>91</td>\n      <td>88</td>\n      <td>96</td>\n      <td>96</td>\n    </tr>\n    <tr>\n      <th>N = 3331</th>\n      <td>818</td>\n      <td>814</td>\n      <td>862</td>\n      <td>837</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>11.12</td>\n      <td>10.81</td>\n      <td>11.14</td>\n      <td>11.47</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.07</td>\n      <td>0.99</td>\n      <td>NaN</td>\n      <td>0.95</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.81 - 1.40)</td>\n      <td>(0.75 - 1.32)</td>\n      <td>None</td>\n      <td>(0.72 - 1.26)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">HIV</th>\n      <th>Weighted cases</th>\n      <td>14</td>\n      <td>6</td>\n      <td>6</td>\n      <td>11</td>\n    </tr>\n    <tr>\n      <th>N = 2681</th>\n      <td>669</td>\n      <td>638</td>\n      <td>686</td>\n      <td>688</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>2.09</td>\n      <td>0.94</td>\n      <td>0.87</td>\n      <td>1.6</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.6</td>\n      <td>0.8</td>\n      <td>NaN</td>\n      <td>0.94</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(nan - nan)</td>\n      <td>(0.33 - 1.98)</td>\n      <td>None</td>\n      <td>(0.40 - 2.22)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"10\" valign=\"top\">male</th>\n      <th rowspan=\"5\" valign=\"top\">HSV-2 positive</th>\n      <th>Weighted cases</th>\n      <td>100</td>\n      <td>74</td>\n      <td>68</td>\n      <td>83</td>\n    </tr>\n    <tr>\n      <th>N = 4109</th>\n      <td>1022</td>\n      <td>1040</td>\n      <td>1023</td>\n      <td>1024</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>9.78</td>\n      <td>7.12</td>\n      <td>6.65</td>\n      <td>8.11</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.23</td>\n      <td>0.91</td>\n      <td>NaN</td>\n      <td>0.97</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.93 - 1.62)</td>\n      <td>(0.68 - 1.22)</td>\n      <td>None</td>\n      <td>(0.72 - 1.30)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">HIV</th>\n      <th>Weighted cases</th>\n      <td>6</td>\n      <td>5</td>\n      <td>8</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>N = 2995</th>\n      <td>751</td>\n      <td>746</td>\n      <td>710</td>\n      <td>788</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>0.8</td>\n      <td>0.67</td>\n      <td>1.13</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.97</td>\n      <td>1.89</td>\n      <td>NaN</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.27 - 3.56)</td>\n      <td>(0.61 - 5.84)</td>\n      <td>None</td>\n      <td>(0.00 - inf)</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n ### 5.2.3. Table 3: Effects of Intervention on other outcomes\nIn this table, some other behavioral outcome at phase 2 is analyzed across 4 treatment groups and by gender. For the treatment groups receiving condoms, \"Ever received free condoms\" and \"Ever used the free condoms\" are statistically significant comparing to the control or VCT treatment group. Similarly in the outcome \"Ever had VCT\", groups that have receive VCT are more significant comparing to the rest. While other variables, including childbearing, remains statistically insignificant.\n\n| **Variables**               | **Method**              |\n|-----------------------------|-------------------------|\n| Ever received free condoms  | answer yes to \"p2_b8_200_condomsfree_ever\"    |\n| Ever used the free condems  | answer 1 or 2 to \"p2_b8_202_condfree_use\"     |\n| Ever sold/gave condoms      | answer 3 or 4  to \"p2_b8_202_condfree_use\"    |\n| Ever had VCT                | answer yes to \"p2_b9_204_evervct\" |\n| VCT more than once          | answer \"p2_b9_205_timesvct\" > 1   |\n| VCT more than twice         | answer \"p2_b9_205_timesvct\" > 2   |\n| Currently married p2        | answer currently married to \"p2_b5_115_married\"|\n| Sex in last 6 months        | using \"p2_b5_118_sexpartners_6mos\" > 0 |\n| Partner number last 6 months| using answer to \"p2_b5_118_sexpartners_6mos\"   |\n| Partner number lifetime     | using answer of \"p2_b5_119_sexpartners_life\"   |\n| Ever used condoms           | answer yes to \"p2_b8_182_everusedcondom\"       |\n| Used condoms last time      | answer yes to \"p2_b8_186_condom_lasttime\"      |\n| Unprotected sex non-monogamous| \"p2_b5_119_sexpartners_life\" > 1 & answer never to all of p2_b5_141 (using condoms with 3 most recent partner respectively)           |\n| Self reported STI           | answer yes to \"p2_b10_214_sti\"       |\n| Ever or partner ever pregnant p2| answer to \"p2_b7_148_pregnancies_number\" > 0|\n| Named 3 prevention p2       | having more at least 3 answer in \"p2_b4_72_protecthiv\"|\n| Answered 3 questions p2     | answer 1 to \"p2_b4_74_hivinwomb\", \"p2_b4_75_hivbreastfeed\" 2 to \"p2_b4_76_hivmosquitoes\" |\n| Showed positive attitude p2 | answer 4 or 5 to \"p2_b4_111_hivpunishment\", \"p2_b4_112_hivprostitutes\", \"p2_b4_113_hivpromiscuousmen\" and 1 or 2 to \"p2_b4_114_hivtreatedsame\"|\n| Child number p2             | using \"p2_b7_148_pregnancies_number\" |\n\n\n\n```python\nvarlist3 = [\n            (\"Ever received free condoms\", \"everfreecondoms_base\"),\n            (\"Ever used the free condems\", \"everfreecondoms_base\"),\n            ('Ever sold/gave condoms', 'Ever received free condoms'),\n            ('Ever had VCT', 'evervct_base'),\n            ('VCT more than once', 'evervct_base'),\n            ('VCT more than twice', 'evervct_base'),\n            ('Currently married p2', 'currentmarried_base'),\n            ('Sex in last 6 months', 'sexpartners6mon_base'), \n            ('Partner number last 6 months', None),\n            ('Partner number lifetime', None),\n            ('Ever used condoms', 'everusedcondom_base'),\n            ('Used condoms last time', 'lasttimecondom_base'),\n            ('Unprotected sex non-monogamous', 'polynocondom_base'),\n            ('Self reported STI', 'sti_base'),\n            ('Ever or partner ever pregnant p2', 'pregnant_base'),\n            ('Named 3 prevention p2', 'named3prev_base'),\n            ('Answered 3 questions p2', 'ans3q_base'),\n            ('Showed positive attitude p2', 'posplhiv_base'), \n            ('Child number', None)]\n\nTable(df_t3, query, keys, varlist3)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>group</th>\n      <th>Condom and VCT</th>\n      <th>Condom only</th>\n      <th>Control</th>\n      <th>VCT only</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"89\" valign=\"top\">all</th>\n      <th rowspan=\"5\" valign=\"top\">Ever received free condoms</th>\n      <th>Weighted cases</th>\n      <td>1354</td>\n      <td>1274</td>\n      <td>857</td>\n      <td>900</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1931</td>\n      <td>1776</td>\n      <td>1740</td>\n      <td>1814</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>70.12</td>\n      <td>71.73</td>\n      <td>49.25</td>\n      <td>49.61</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.56</td>\n      <td>1.83</td>\n      <td>NaN</td>\n      <td>0.6</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(1.39 - 1.75)</td>\n      <td>(1.63 - 2.06)</td>\n      <td>None</td>\n      <td>(0.53 - 0.67)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Ever used the free condems</th>\n      <th>Weighted cases</th>\n      <td>773</td>\n      <td>673</td>\n      <td>488</td>\n      <td>485</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1931</td>\n      <td>1776</td>\n      <td>1740</td>\n      <td>1814</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>40.03</td>\n      <td>37.89</td>\n      <td>28.05</td>\n      <td>26.74</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.37</td>\n      <td>1.47</td>\n      <td>NaN</td>\n      <td>0.7</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(1.20 - 1.56)</td>\n      <td>(1.29 - 1.67)</td>\n      <td>None</td>\n      <td>(0.61 - 0.81)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Ever sold/gave condoms</th>\n      <th>Weighted cases</th>\n      <td>958</td>\n      <td>804</td>\n      <td>400</td>\n      <td>425</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1354</td>\n      <td>1274</td>\n      <td>857</td>\n      <td>900</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>70.75</td>\n      <td>63.11</td>\n      <td>46.67</td>\n      <td>47.22</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.97</td>\n      <td>1.95</td>\n      <td>NaN</td>\n      <td>0.47</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(1.74 - 2.23)</td>\n      <td>(1.72 - 2.20)</td>\n      <td>None</td>\n      <td>(0.41 - 0.55)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Ever had VCT</th>\n      <th>Weighted cases</th>\n      <td>1751</td>\n      <td>1337</td>\n      <td>1367</td>\n      <td>1610</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1811</td>\n      <td>1650</td>\n      <td>1637</td>\n      <td>1711</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>96.69</td>\n      <td>81.03</td>\n      <td>83.51</td>\n      <td>94.1</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.39</td>\n      <td>0.76</td>\n      <td>NaN</td>\n      <td>1.35</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(1.23 - 1.57)</td>\n      <td>(0.67 - 0.85)</td>\n      <td>None</td>\n      <td>(1.20 - 1.53)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">VCT more than once</th>\n      <th>Weighted cases</th>\n      <td>1437</td>\n      <td>1049</td>\n      <td>1085</td>\n      <td>1320</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1811</td>\n      <td>1650</td>\n      <td>1637</td>\n      <td>1711</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>79.35</td>\n      <td>63.58</td>\n      <td>66.28</td>\n      <td>77.15</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.34</td>\n      <td>0.77</td>\n      <td>NaN</td>\n      <td>1.29</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(1.19 - 1.50)</td>\n      <td>(0.69 - 0.87)</td>\n      <td>None</td>\n      <td>(1.15 - 1.45)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">VCT more than twice</th>\n      <th>Weighted cases</th>\n      <td>1006</td>\n      <td>725</td>\n      <td>742</td>\n      <td>922</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1811</td>\n      <td>1650</td>\n      <td>1637</td>\n      <td>1711</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>55.55</td>\n      <td>43.94</td>\n      <td>45.33</td>\n      <td>53.89</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.26</td>\n      <td>0.8</td>\n      <td>NaN</td>\n      <td>1.3</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(1.12 - 1.42)</td>\n      <td>(0.71 - 0.90)</td>\n      <td>None</td>\n      <td>(1.16 - 1.47)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Currently married p2</th>\n      <th>Weighted cases</th>\n      <td>848</td>\n      <td>757</td>\n      <td>843</td>\n      <td>816</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>2411</td>\n      <td>2231</td>\n      <td>2261</td>\n      <td>2306</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>35.17</td>\n      <td>33.93</td>\n      <td>37.28</td>\n      <td>35.39</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.88</td>\n      <td>1.03</td>\n      <td>NaN</td>\n      <td>1.05</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.76 - 1.01)</td>\n      <td>(0.89 - 1.18)</td>\n      <td>None</td>\n      <td>(0.92 - 1.21)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Sex in last 6 months</th>\n      <th>Weighted cases</th>\n      <td>1577</td>\n      <td>1448</td>\n      <td>1538</td>\n      <td>1564</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>2406</td>\n      <td>2232</td>\n      <td>2261</td>\n      <td>2304</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>65.54</td>\n      <td>64.87</td>\n      <td>68.02</td>\n      <td>67.88</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.87</td>\n      <td>0.96</td>\n      <td>NaN</td>\n      <td>1.19</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.77 - 0.98)</td>\n      <td>(0.85 - 1.09)</td>\n      <td>None</td>\n      <td>(1.05 - 1.35)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Partner number last 6 months</th>\n      <th>Weighted cases</th>\n      <td>0.86</td>\n      <td>0.86</td>\n      <td>0.9</td>\n      <td>0.89</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.87</td>\n      <td>0.96</td>\n      <td>NaN</td>\n      <td>1.19</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.77 - 0.98)</td>\n      <td>(0.85 - 1.09)</td>\n      <td>None</td>\n      <td>(1.05 - 1.35)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Partner number lifetime</th>\n      <th>Weighted cases</th>\n      <td>3.57</td>\n      <td>2.99</td>\n      <td>3.13</td>\n      <td>3.06</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.87</td>\n      <td>1.16</td>\n      <td>NaN</td>\n      <td>1.09</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.74 - 1.02)</td>\n      <td>(0.99 - 1.37)</td>\n      <td>None</td>\n      <td>(0.92 - 1.27)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Ever used condoms</th>\n      <th>Weighted cases</th>\n      <td>1578</td>\n      <td>1459</td>\n      <td>1432</td>\n      <td>1460</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>2067</td>\n      <td>1917</td>\n      <td>1934</td>\n      <td>1967</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>76.34</td>\n      <td>76.11</td>\n      <td>74.04</td>\n      <td>74.22</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.02</td>\n      <td>1.07</td>\n      <td>NaN</td>\n      <td>0.97</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.91 - 1.14)</td>\n      <td>(0.96 - 1.20)</td>\n      <td>None</td>\n      <td>(0.87 - 1.09)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Used condoms last time</th>\n      <th>Weighted cases</th>\n      <td>819</td>\n      <td>784</td>\n      <td>794</td>\n      <td>782</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1587</td>\n      <td>1476</td>\n      <td>1444</td>\n      <td>1483</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>51.61</td>\n      <td>53.12</td>\n      <td>54.99</td>\n      <td>52.73</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.96</td>\n      <td>1.04</td>\n      <td>NaN</td>\n      <td>1.01</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.85 - 1.08)</td>\n      <td>(0.92 - 1.17)</td>\n      <td>None</td>\n      <td>(0.90 - 1.13)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Unprotected sex non-monogamous</th>\n      <th>Weighted cases</th>\n      <td>686</td>\n      <td>572</td>\n      <td>646</td>\n      <td>590</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>2402</td>\n      <td>2231</td>\n      <td>2261</td>\n      <td>2303</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>28.56</td>\n      <td>25.64</td>\n      <td>28.57</td>\n      <td>25.62</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.05</td>\n      <td>0.96</td>\n      <td>NaN</td>\n      <td>0.99</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.93 - 1.19)</td>\n      <td>(0.84 - 1.08)</td>\n      <td>None</td>\n      <td>(0.87 - 1.12)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Self reported STI</th>\n      <th>Weighted cases</th>\n      <td>59</td>\n      <td>30</td>\n      <td>45</td>\n      <td>49</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>2406</td>\n      <td>2230</td>\n      <td>2260</td>\n      <td>2305</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>2.45</td>\n      <td>1.35</td>\n      <td>1.99</td>\n      <td>2.13</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.95</td>\n      <td>0.78</td>\n      <td>NaN</td>\n      <td>1.18</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.64 - 1.40)</td>\n      <td>(0.51 - 1.17)</td>\n      <td>None</td>\n      <td>(0.81 - 1.71)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Ever or partner ever pregnant p2</th>\n      <th>Weighted cases</th>\n      <td>1100</td>\n      <td>999</td>\n      <td>1028</td>\n      <td>1072</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>2404</td>\n      <td>2231</td>\n      <td>2259</td>\n      <td>2302</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>45.76</td>\n      <td>44.78</td>\n      <td>45.51</td>\n      <td>46.57</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.95</td>\n      <td>1.13</td>\n      <td>NaN</td>\n      <td>1.06</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.82 - 1.09)</td>\n      <td>(0.98 - 1.30)</td>\n      <td>None</td>\n      <td>(0.92 - 1.22)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Named 3 prevention p2</th>\n      <th>Weighted cases</th>\n      <td>1016</td>\n      <td>953</td>\n      <td>975</td>\n      <td>913</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>2412</td>\n      <td>2232</td>\n      <td>2261</td>\n      <td>2308</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>42.12</td>\n      <td>42.7</td>\n      <td>43.12</td>\n      <td>39.56</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.94</td>\n      <td>1.04</td>\n      <td>NaN</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.84 - 1.05)</td>\n      <td>(0.93 - 1.16)</td>\n      <td>None</td>\n      <td>(0.90 - 1.12)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Answered 3 questions p2</th>\n      <th>Weighted cases</th>\n      <td>759</td>\n      <td>711</td>\n      <td>691</td>\n      <td>652</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>2411</td>\n      <td>2230</td>\n      <td>2247</td>\n      <td>2307</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>31.48</td>\n      <td>31.88</td>\n      <td>30.75</td>\n      <td>28.26</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.95</td>\n      <td>1.06</td>\n      <td>NaN</td>\n      <td>0.92</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.85 - 1.07)</td>\n      <td>(0.95 - 1.20)</td>\n      <td>None</td>\n      <td>(0.82 - 1.04)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Showed positive attitude p2</th>\n      <th>Weighted cases</th>\n      <td>433</td>\n      <td>378</td>\n      <td>389</td>\n      <td>470</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>2411</td>\n      <td>2230</td>\n      <td>2250</td>\n      <td>2296</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>17.96</td>\n      <td>16.95</td>\n      <td>17.29</td>\n      <td>20.47</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1</td>\n      <td>1</td>\n      <td>NaN</td>\n      <td>1.04</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.87 - 1.16)</td>\n      <td>(0.87 - 1.16)</td>\n      <td>None</td>\n      <td>(0.90 - 1.19)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Child number</th>\n      <th>Weighted cases</th>\n      <td>0.81</td>\n      <td>0.75</td>\n      <td>0.8</td>\n      <td>0.85</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.95</td>\n      <td>1.13</td>\n      <td>NaN</td>\n      <td>1.06</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.82 - 1.09)</td>\n      <td>(0.98 - 1.30)</td>\n      <td>None</td>\n      <td>(0.92 - 1.22)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"89\" valign=\"top\">female</th>\n      <th rowspan=\"5\" valign=\"top\">Ever received free condoms</th>\n      <th>Weighted cases</th>\n      <td>432</td>\n      <td>436</td>\n      <td>224</td>\n      <td>297</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>845</td>\n      <td>786</td>\n      <td>779</td>\n      <td>849</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>51.12</td>\n      <td>55.47</td>\n      <td>28.75</td>\n      <td>34.98</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.57</td>\n      <td>1.84</td>\n      <td>NaN</td>\n      <td>0.63</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(1.32 - 1.86)</td>\n      <td>(1.55 - 2.19)</td>\n      <td>None</td>\n      <td>(0.53 - 0.76)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Ever used the free condems</th>\n      <th>Weighted cases</th>\n      <td>145</td>\n      <td>134</td>\n      <td>63</td>\n      <td>100</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>845</td>\n      <td>786</td>\n      <td>779</td>\n      <td>849</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>17.16</td>\n      <td>17.05</td>\n      <td>8.09</td>\n      <td>11.78</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.43</td>\n      <td>1.51</td>\n      <td>NaN</td>\n      <td>0.76</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(1.11 - 1.84)</td>\n      <td>(1.17 - 1.96)</td>\n      <td>None</td>\n      <td>(0.57 - 1.01)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Ever sold/gave condoms</th>\n      <th>Weighted cases</th>\n      <td>251</td>\n      <td>229</td>\n      <td>72</td>\n      <td>94</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>432</td>\n      <td>436</td>\n      <td>224</td>\n      <td>297</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>58.1</td>\n      <td>52.52</td>\n      <td>32.14</td>\n      <td>31.65</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.99</td>\n      <td>2.06</td>\n      <td>NaN</td>\n      <td>0.43</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(1.61 - 2.47)</td>\n      <td>(1.66 - 2.55)</td>\n      <td>None</td>\n      <td>(0.33 - 0.57)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Ever had VCT</th>\n      <th>Weighted cases</th>\n      <td>731</td>\n      <td>587</td>\n      <td>625</td>\n      <td>749</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>743</td>\n      <td>680</td>\n      <td>697</td>\n      <td>764</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>98.38</td>\n      <td>86.32</td>\n      <td>89.67</td>\n      <td>98.04</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.15</td>\n      <td>0.83</td>\n      <td>NaN</td>\n      <td>1.36</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.95 - 1.39)</td>\n      <td>(0.69 - 1.01)</td>\n      <td>None</td>\n      <td>(1.13 - 1.65)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">VCT more than once</th>\n      <th>Weighted cases</th>\n      <td>634</td>\n      <td>494</td>\n      <td>508</td>\n      <td>670</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>743</td>\n      <td>680</td>\n      <td>697</td>\n      <td>764</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>85.33</td>\n      <td>72.65</td>\n      <td>72.88</td>\n      <td>87.7</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.18</td>\n      <td>0.83</td>\n      <td>NaN</td>\n      <td>1.4</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.98 - 1.42)</td>\n      <td>(0.69 - 0.99)</td>\n      <td>None</td>\n      <td>(1.17 - 1.68)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">VCT more than twice</th>\n      <th>Weighted cases</th>\n      <td>468</td>\n      <td>359</td>\n      <td>370</td>\n      <td>490</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>743</td>\n      <td>680</td>\n      <td>697</td>\n      <td>764</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>62.99</td>\n      <td>52.79</td>\n      <td>53.08</td>\n      <td>64.14</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.11</td>\n      <td>0.86</td>\n      <td>NaN</td>\n      <td>1.49</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.92 - 1.33)</td>\n      <td>(0.72 - 1.04)</td>\n      <td>None</td>\n      <td>(1.24 - 1.78)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Currently married p2</th>\n      <th>Weighted cases</th>\n      <td>480</td>\n      <td>423</td>\n      <td>488</td>\n      <td>430</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1060</td>\n      <td>984</td>\n      <td>1038</td>\n      <td>1066</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>45.28</td>\n      <td>42.99</td>\n      <td>47.01</td>\n      <td>40.34</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.88</td>\n      <td>1.11</td>\n      <td>NaN</td>\n      <td>0.99</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.72 - 1.08)</td>\n      <td>(0.91 - 1.37)</td>\n      <td>None</td>\n      <td>(0.81 - 1.22)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Sex in last 6 months</th>\n      <th>Weighted cases</th>\n      <td>703</td>\n      <td>660</td>\n      <td>694</td>\n      <td>702</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1060</td>\n      <td>984</td>\n      <td>1038</td>\n      <td>1064</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>66.32</td>\n      <td>67.07</td>\n      <td>66.86</td>\n      <td>65.98</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.92</td>\n      <td>1.04</td>\n      <td>NaN</td>\n      <td>1.16</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.76 - 1.12)</td>\n      <td>(0.85 - 1.26)</td>\n      <td>None</td>\n      <td>(0.96 - 1.41)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Partner number last 6 months</th>\n      <th>Weighted cases</th>\n      <td>0.71</td>\n      <td>0.72</td>\n      <td>0.69</td>\n      <td>0.7</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.92</td>\n      <td>1.04</td>\n      <td>NaN</td>\n      <td>1.16</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.76 - 1.12)</td>\n      <td>(0.85 - 1.26)</td>\n      <td>None</td>\n      <td>(0.96 - 1.41)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Partner number lifetime</th>\n      <th>Weighted cases</th>\n      <td>1.65</td>\n      <td>1.49</td>\n      <td>1.49</td>\n      <td>1.53</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.88</td>\n      <td>1.25</td>\n      <td>NaN</td>\n      <td>1.23</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.70 - 1.11)</td>\n      <td>(0.98 - 1.58)</td>\n      <td>None</td>\n      <td>(0.97 - 1.56)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Ever used condoms</th>\n      <th>Weighted cases</th>\n      <td>616</td>\n      <td>568</td>\n      <td>545</td>\n      <td>598</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>878</td>\n      <td>826</td>\n      <td>846</td>\n      <td>878</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>70.16</td>\n      <td>68.77</td>\n      <td>64.42</td>\n      <td>68.11</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.08</td>\n      <td>1.02</td>\n      <td>NaN</td>\n      <td>1.06</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.92 - 1.27)</td>\n      <td>(0.86 - 1.20)</td>\n      <td>None</td>\n      <td>(0.90 - 1.25)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Used condoms last time</th>\n      <th>Weighted cases</th>\n      <td>216</td>\n      <td>235</td>\n      <td>229</td>\n      <td>292</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>623</td>\n      <td>579</td>\n      <td>555</td>\n      <td>615</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>34.67</td>\n      <td>40.59</td>\n      <td>41.26</td>\n      <td>47.48</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.94</td>\n      <td>0.93</td>\n      <td>NaN</td>\n      <td>1.3</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.78 - 1.15)</td>\n      <td>(0.77 - 1.13)</td>\n      <td>None</td>\n      <td>(1.07 - 1.56)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Unprotected sex non-monogamous</th>\n      <th>Weighted cases</th>\n      <td>272</td>\n      <td>215</td>\n      <td>244</td>\n      <td>201</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1056</td>\n      <td>983</td>\n      <td>1038</td>\n      <td>1063</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>25.76</td>\n      <td>21.87</td>\n      <td>23.51</td>\n      <td>18.91</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.18</td>\n      <td>0.98</td>\n      <td>NaN</td>\n      <td>0.94</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.96 - 1.44)</td>\n      <td>(0.79 - 1.20)</td>\n      <td>None</td>\n      <td>(0.77 - 1.16)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Self reported STI</th>\n      <th>Weighted cases</th>\n      <td>20</td>\n      <td>14</td>\n      <td>24</td>\n      <td>31</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1060</td>\n      <td>983</td>\n      <td>1037</td>\n      <td>1065</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>1.89</td>\n      <td>1.42</td>\n      <td>2.31</td>\n      <td>2.91</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.88</td>\n      <td>0.71</td>\n      <td>NaN</td>\n      <td>1.36</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.50 - 1.54)</td>\n      <td>(0.39 - 1.31)</td>\n      <td>None</td>\n      <td>(0.82 - 2.28)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Ever or partner ever pregnant p2</th>\n      <th>Weighted cases</th>\n      <td>671</td>\n      <td>590</td>\n      <td>616</td>\n      <td>607</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1060</td>\n      <td>983</td>\n      <td>1037</td>\n      <td>1065</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>63.3</td>\n      <td>60.02</td>\n      <td>59.4</td>\n      <td>57</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.98</td>\n      <td>1.24</td>\n      <td>NaN</td>\n      <td>1.02</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.79 - 1.21)</td>\n      <td>(1.00 - 1.53)</td>\n      <td>None</td>\n      <td>(0.83 - 1.27)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Named 3 prevention p2</th>\n      <th>Weighted cases</th>\n      <td>395</td>\n      <td>358</td>\n      <td>388</td>\n      <td>384</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1060</td>\n      <td>984</td>\n      <td>1038</td>\n      <td>1066</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>37.26</td>\n      <td>36.38</td>\n      <td>37.38</td>\n      <td>36.02</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.04</td>\n      <td>1.02</td>\n      <td>NaN</td>\n      <td>0.98</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.87 - 1.24)</td>\n      <td>(0.86 - 1.22)</td>\n      <td>None</td>\n      <td>(0.82 - 1.16)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Answered 3 questions p2</th>\n      <th>Weighted cases</th>\n      <td>344</td>\n      <td>323</td>\n      <td>329</td>\n      <td>311</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1060</td>\n      <td>983</td>\n      <td>1024</td>\n      <td>1066</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>32.45</td>\n      <td>32.86</td>\n      <td>32.13</td>\n      <td>29.17</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.91</td>\n      <td>1.09</td>\n      <td>NaN</td>\n      <td>0.91</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.76 - 1.08)</td>\n      <td>(0.92 - 1.30)</td>\n      <td>None</td>\n      <td>(0.76 - 1.08)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Showed positive attitude p2</th>\n      <th>Weighted cases</th>\n      <td>171</td>\n      <td>166</td>\n      <td>156</td>\n      <td>241</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1060</td>\n      <td>983</td>\n      <td>1027</td>\n      <td>1065</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>16.13</td>\n      <td>16.89</td>\n      <td>15.19</td>\n      <td>22.63</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.06</td>\n      <td>1.03</td>\n      <td>NaN</td>\n      <td>1.04</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.85 - 1.32)</td>\n      <td>(0.83 - 1.28)</td>\n      <td>None</td>\n      <td>(0.84 - 1.30)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Child number</th>\n      <th>Weighted cases</th>\n      <td>1.17</td>\n      <td>1.08</td>\n      <td>1.11</td>\n      <td>1.12</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.98</td>\n      <td>1.24</td>\n      <td>NaN</td>\n      <td>1.02</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.79 - 1.21)</td>\n      <td>(1.00 - 1.53)</td>\n      <td>None</td>\n      <td>(0.83 - 1.27)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"89\" valign=\"top\">male</th>\n      <th rowspan=\"5\" valign=\"top\">Ever received free condoms</th>\n      <th>Weighted cases</th>\n      <td>922</td>\n      <td>838</td>\n      <td>633</td>\n      <td>603</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1086</td>\n      <td>990</td>\n      <td>961</td>\n      <td>965</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>84.9</td>\n      <td>84.65</td>\n      <td>65.87</td>\n      <td>62.49</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.56</td>\n      <td>1.85</td>\n      <td>NaN</td>\n      <td>0.57</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(1.33 - 1.82)</td>\n      <td>(1.58 - 2.16)</td>\n      <td>None</td>\n      <td>(0.49 - 0.66)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Ever used the free condems</th>\n      <th>Weighted cases</th>\n      <td>628</td>\n      <td>539</td>\n      <td>425</td>\n      <td>385</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1086</td>\n      <td>990</td>\n      <td>961</td>\n      <td>965</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>57.83</td>\n      <td>54.44</td>\n      <td>44.22</td>\n      <td>39.9</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.35</td>\n      <td>1.46</td>\n      <td>NaN</td>\n      <td>0.69</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(1.16 - 1.57)</td>\n      <td>(1.26 - 1.70)</td>\n      <td>None</td>\n      <td>(0.59 - 0.81)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Ever sold/gave condoms</th>\n      <th>Weighted cases</th>\n      <td>707</td>\n      <td>575</td>\n      <td>328</td>\n      <td>331</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>922</td>\n      <td>838</td>\n      <td>633</td>\n      <td>603</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>76.68</td>\n      <td>68.62</td>\n      <td>51.82</td>\n      <td>54.89</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.96</td>\n      <td>1.91</td>\n      <td>NaN</td>\n      <td>0.49</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(1.68 - 2.28)</td>\n      <td>(1.64 - 2.22)</td>\n      <td>None</td>\n      <td>(0.41 - 0.58)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Ever had VCT</th>\n      <th>Weighted cases</th>\n      <td>1020</td>\n      <td>750</td>\n      <td>742</td>\n      <td>861</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1068</td>\n      <td>970</td>\n      <td>940</td>\n      <td>947</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>95.51</td>\n      <td>77.32</td>\n      <td>78.94</td>\n      <td>90.92</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.6</td>\n      <td>0.71</td>\n      <td>NaN</td>\n      <td>1.34</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(1.35 - 1.88)</td>\n      <td>(0.61 - 0.83)</td>\n      <td>None</td>\n      <td>(1.14 - 1.58)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">VCT more than once</th>\n      <th>Weighted cases</th>\n      <td>803</td>\n      <td>555</td>\n      <td>577</td>\n      <td>650</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1068</td>\n      <td>970</td>\n      <td>940</td>\n      <td>947</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>75.19</td>\n      <td>57.22</td>\n      <td>61.38</td>\n      <td>68.64</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.46</td>\n      <td>0.73</td>\n      <td>NaN</td>\n      <td>1.22</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(1.25 - 1.70)</td>\n      <td>(0.63 - 0.85)</td>\n      <td>None</td>\n      <td>(1.05 - 1.42)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">VCT more than twice</th>\n      <th>Weighted cases</th>\n      <td>538</td>\n      <td>366</td>\n      <td>372</td>\n      <td>432</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1068</td>\n      <td>970</td>\n      <td>940</td>\n      <td>947</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>50.37</td>\n      <td>37.73</td>\n      <td>39.57</td>\n      <td>45.62</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.4</td>\n      <td>0.75</td>\n      <td>NaN</td>\n      <td>1.17</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(1.19 - 1.64)</td>\n      <td>(0.63 - 0.89)</td>\n      <td>None</td>\n      <td>(1.00 - 1.38)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Currently married p2</th>\n      <th>Weighted cases</th>\n      <td>368</td>\n      <td>334</td>\n      <td>355</td>\n      <td>386</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1351</td>\n      <td>1247</td>\n      <td>1223</td>\n      <td>1240</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>27.24</td>\n      <td>26.78</td>\n      <td>29.03</td>\n      <td>31.13</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.88</td>\n      <td>0.96</td>\n      <td>NaN</td>\n      <td>1.12</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.72 - 1.07)</td>\n      <td>(0.79 - 1.16)</td>\n      <td>None</td>\n      <td>(0.92 - 1.36)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Sex in last 6 months</th>\n      <th>Weighted cases</th>\n      <td>874</td>\n      <td>788</td>\n      <td>844</td>\n      <td>862</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1346</td>\n      <td>1248</td>\n      <td>1223</td>\n      <td>1240</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>64.93</td>\n      <td>63.14</td>\n      <td>69.01</td>\n      <td>69.52</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.83</td>\n      <td>0.92</td>\n      <td>NaN</td>\n      <td>1.21</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.71 - 0.98)</td>\n      <td>(0.78 - 1.08)</td>\n      <td>None</td>\n      <td>(1.03 - 1.43)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Partner number last 6 months</th>\n      <th>Weighted cases</th>\n      <td>0.98</td>\n      <td>0.98</td>\n      <td>1.09</td>\n      <td>1.05</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.83</td>\n      <td>0.92</td>\n      <td>NaN</td>\n      <td>1.21</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.71 - 0.98)</td>\n      <td>(0.78 - 1.08)</td>\n      <td>None</td>\n      <td>(1.03 - 1.43)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Partner number lifetime</th>\n      <th>Weighted cases</th>\n      <td>5.08</td>\n      <td>4.17</td>\n      <td>4.52</td>\n      <td>4.37</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.86</td>\n      <td>1.09</td>\n      <td>NaN</td>\n      <td>0.96</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.70 - 1.07)</td>\n      <td>(0.87 - 1.36)</td>\n      <td>None</td>\n      <td>(0.77 - 1.20)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Ever used condoms</th>\n      <th>Weighted cases</th>\n      <td>962</td>\n      <td>891</td>\n      <td>887</td>\n      <td>862</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1189</td>\n      <td>1091</td>\n      <td>1088</td>\n      <td>1089</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>80.91</td>\n      <td>81.67</td>\n      <td>81.53</td>\n      <td>79.16</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.97</td>\n      <td>1.12</td>\n      <td>NaN</td>\n      <td>0.89</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.83 - 1.14)</td>\n      <td>(0.96 - 1.31)</td>\n      <td>None</td>\n      <td>(0.76 - 1.04)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Used condoms last time</th>\n      <th>Weighted cases</th>\n      <td>603</td>\n      <td>549</td>\n      <td>565</td>\n      <td>490</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>964</td>\n      <td>897</td>\n      <td>889</td>\n      <td>868</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>62.55</td>\n      <td>61.2</td>\n      <td>63.55</td>\n      <td>56.45</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.97</td>\n      <td>1.11</td>\n      <td>NaN</td>\n      <td>0.86</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.83 - 1.12)</td>\n      <td>(0.95 - 1.28)</td>\n      <td>None</td>\n      <td>(0.74 - 1.00)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Unprotected sex non-monogamous</th>\n      <th>Weighted cases</th>\n      <td>414</td>\n      <td>357</td>\n      <td>402</td>\n      <td>389</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1346</td>\n      <td>1248</td>\n      <td>1223</td>\n      <td>1240</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>30.76</td>\n      <td>28.61</td>\n      <td>32.87</td>\n      <td>31.37</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.97</td>\n      <td>0.95</td>\n      <td>NaN</td>\n      <td>1.02</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.83 - 1.14)</td>\n      <td>(0.81 - 1.11)</td>\n      <td>None</td>\n      <td>(0.87 - 1.19)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Self reported STI</th>\n      <th>Weighted cases</th>\n      <td>39</td>\n      <td>16</td>\n      <td>21</td>\n      <td>18</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1346</td>\n      <td>1247</td>\n      <td>1223</td>\n      <td>1240</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>2.9</td>\n      <td>1.28</td>\n      <td>1.72</td>\n      <td>1.45</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.02</td>\n      <td>0.78</td>\n      <td>NaN</td>\n      <td>1.05</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.59 - 1.74)</td>\n      <td>(0.44 - 1.38)</td>\n      <td>None</td>\n      <td>(0.62 - 1.79)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Ever or partner ever pregnant p2</th>\n      <th>Weighted cases</th>\n      <td>429</td>\n      <td>409</td>\n      <td>412</td>\n      <td>465</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1344</td>\n      <td>1248</td>\n      <td>1222</td>\n      <td>1237</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>31.92</td>\n      <td>32.77</td>\n      <td>33.72</td>\n      <td>37.59</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.93</td>\n      <td>1.06</td>\n      <td>NaN</td>\n      <td>1.08</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.77 - 1.12)</td>\n      <td>(0.88 - 1.27)</td>\n      <td>None</td>\n      <td>(0.90 - 1.30)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Named 3 prevention p2</th>\n      <th>Weighted cases</th>\n      <td>621</td>\n      <td>595</td>\n      <td>587</td>\n      <td>529</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1352</td>\n      <td>1248</td>\n      <td>1223</td>\n      <td>1242</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>45.93</td>\n      <td>47.68</td>\n      <td>48</td>\n      <td>42.59</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.88</td>\n      <td>1.06</td>\n      <td>NaN</td>\n      <td>1.01</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.75 - 1.02)</td>\n      <td>(0.91 - 1.22)</td>\n      <td>None</td>\n      <td>(0.87 - 1.18)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Answered 3 questions p2</th>\n      <th>Weighted cases</th>\n      <td>415</td>\n      <td>388</td>\n      <td>362</td>\n      <td>341</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1351</td>\n      <td>1247</td>\n      <td>1223</td>\n      <td>1241</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>30.72</td>\n      <td>31.11</td>\n      <td>29.6</td>\n      <td>27.48</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.98</td>\n      <td>1.03</td>\n      <td>NaN</td>\n      <td>0.95</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.84 - 1.15)</td>\n      <td>(0.88 - 1.21)</td>\n      <td>None</td>\n      <td>(0.81 - 1.12)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">Showed positive attitude p2</th>\n      <th>Weighted cases</th>\n      <td>262</td>\n      <td>212</td>\n      <td>233</td>\n      <td>229</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1351</td>\n      <td>1247</td>\n      <td>1223</td>\n      <td>1231</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>19.39</td>\n      <td>17</td>\n      <td>19.05</td>\n      <td>18.6</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.96</td>\n      <td>0.99</td>\n      <td>NaN</td>\n      <td>1.02</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.79 - 1.17)</td>\n      <td>(0.81 - 1.19)</td>\n      <td>None</td>\n      <td>(0.85 - 1.24)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">Child number</th>\n      <th>Weighted cases</th>\n      <td>0.53</td>\n      <td>0.5</td>\n      <td>0.54</td>\n      <td>0.61</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.93</td>\n      <td>1.06</td>\n      <td>NaN</td>\n      <td>1.08</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.77 - 1.12)</td>\n      <td>(0.88 - 1.27)</td>\n      <td>None</td>\n      <td>(0.90 - 1.30)</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### 5.2.4. Table 4: Heterogenetiy test\nTable 4 presents heterogeneity tests on those who had started childbearing and those who hadn\u2019t in the first 2 panels, and comparing those respondents believed they have been infected at baseline to those who don\u2019t in the last 2 panels, to show the effect of interventions which yield no significant result as well.\n\n| **Panels**                        | **Method**              |\n|-----------------------------------|-------------------------|\n| Started child bearing             | using \"started_childbearing\"          |\n| Not started child bearing         | using \"started_childbearing\"   |\n| Believed current HIV infection > 0| using  \"Q_b3_99\" (what is the likelihood (chance) that you are infected with HIV/AIDS now)|\n| Believed current HIV infection = 0| using  \"Q_b3_99\" (what is the likelihood (chance) that you are infected with HIV/AIDS now)|\n\n\n\n\n```python\nquery4 = ['started_childbearing == 1', 'started_childbearing == 0', 'Q_b3_99 > 1', 'Q_b3_99 == 1']\nkeys4=['Started child bearing', 'Not started child bearing', 'Believed current HIV infection > 0', 'Believed current HIV infection = 0']\nvarlist4 = [('HSV-2 positive', 'hsv2_accept'), ('HSV-2 female', 'hsv2_accept_f'), ('HSV-2 male', 'hsv2_accept_m')]\n\n\nTable(df_t3, query4, keys4, varlist4)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>group</th>\n      <th>Condom and VCT</th>\n      <th>Condom only</th>\n      <th>Control</th>\n      <th>VCT only</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"15\" valign=\"top\">Started child bearing</th>\n      <th rowspan=\"5\" valign=\"top\">HSV-2 positive</th>\n      <th>Weighted cases</th>\n      <td>76</td>\n      <td>74</td>\n      <td>75</td>\n      <td>83</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>582</td>\n      <td>501</td>\n      <td>551</td>\n      <td>596</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>13.06</td>\n      <td>14.77</td>\n      <td>13.61</td>\n      <td>13.93</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.09</td>\n      <td>1.09</td>\n      <td>NaN</td>\n      <td>0.91</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.80 - 1.48)</td>\n      <td>(0.80 - 1.49)</td>\n      <td>None</td>\n      <td>(0.67 - 1.24)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">HSV-2 female</th>\n      <th>Weighted cases</th>\n      <td>59</td>\n      <td>56</td>\n      <td>58</td>\n      <td>55</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>416</td>\n      <td>353</td>\n      <td>380</td>\n      <td>397</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>14.18</td>\n      <td>15.86</td>\n      <td>15.26</td>\n      <td>13.85</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.1</td>\n      <td>1.03</td>\n      <td>NaN</td>\n      <td>0.91</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.77 - 1.57)</td>\n      <td>(0.71 - 1.49)</td>\n      <td>None</td>\n      <td>(0.63 - 1.30)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">HSV-2 male</th>\n      <th>Weighted cases</th>\n      <td>17</td>\n      <td>18</td>\n      <td>17</td>\n      <td>28</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>166</td>\n      <td>148</td>\n      <td>171</td>\n      <td>199</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>10.24</td>\n      <td>12.16</td>\n      <td>9.94</td>\n      <td>14.07</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.08</td>\n      <td>1.24</td>\n      <td>NaN</td>\n      <td>0.91</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.59 - 1.98)</td>\n      <td>(0.69 - 2.22)</td>\n      <td>None</td>\n      <td>(0.50 - 1.65)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"15\" valign=\"top\">Not started child bearing</th>\n      <th rowspan=\"5\" valign=\"top\">HSV-2 positive</th>\n      <th>Weighted cases</th>\n      <td>115</td>\n      <td>88</td>\n      <td>89</td>\n      <td>96</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1773</td>\n      <td>1692</td>\n      <td>1658</td>\n      <td>1657</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>6.49</td>\n      <td>5.2</td>\n      <td>5.37</td>\n      <td>5.79</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.19</td>\n      <td>0.86</td>\n      <td>NaN</td>\n      <td>0.98</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.92 - 1.54)</td>\n      <td>(0.66 - 1.13)</td>\n      <td>None</td>\n      <td>(0.75 - 1.29)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">HSV-2 female</th>\n      <th>Weighted cases</th>\n      <td>32</td>\n      <td>32</td>\n      <td>38</td>\n      <td>41</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>623</td>\n      <td>617</td>\n      <td>641</td>\n      <td>639</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>5.14</td>\n      <td>5.19</td>\n      <td>5.93</td>\n      <td>6.42</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.05</td>\n      <td>0.96</td>\n      <td>NaN</td>\n      <td>1.03</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.68 - 1.63)</td>\n      <td>(0.61 - 1.50)</td>\n      <td>None</td>\n      <td>(0.66 - 1.61)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">HSV-2 male</th>\n      <th>Weighted cases</th>\n      <td>83</td>\n      <td>56</td>\n      <td>51</td>\n      <td>55</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1150</td>\n      <td>1075</td>\n      <td>1017</td>\n      <td>1018</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>7.22</td>\n      <td>5.21</td>\n      <td>5.01</td>\n      <td>5.4</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.28</td>\n      <td>0.83</td>\n      <td>NaN</td>\n      <td>0.97</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.93 - 1.76)</td>\n      <td>(0.59 - 1.17)</td>\n      <td>None</td>\n      <td>(0.69 - 1.36)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"15\" valign=\"top\">Believed current HIV infection &gt; 0</th>\n      <th rowspan=\"5\" valign=\"top\">HSV-2 positive</th>\n      <th>Weighted cases</th>\n      <td>37</td>\n      <td>36</td>\n      <td>45</td>\n      <td>45</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>519</td>\n      <td>525</td>\n      <td>467</td>\n      <td>539</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>7.13</td>\n      <td>6.86</td>\n      <td>9.64</td>\n      <td>8.35</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.05</td>\n      <td>0.94</td>\n      <td>NaN</td>\n      <td>0.75</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.70 - 1.57)</td>\n      <td>(0.63 - 1.42)</td>\n      <td>None</td>\n      <td>(0.49 - 1.15)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">HSV-2 female</th>\n      <th>Weighted cases</th>\n      <td>20</td>\n      <td>19</td>\n      <td>27</td>\n      <td>19</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>212</td>\n      <td>203</td>\n      <td>199</td>\n      <td>205</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>9.43</td>\n      <td>9.36</td>\n      <td>13.57</td>\n      <td>9.27</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>0.99</td>\n      <td>0.95</td>\n      <td>NaN</td>\n      <td>0.71</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.57 - 1.71)</td>\n      <td>(0.54 - 1.66)</td>\n      <td>None</td>\n      <td>(0.39 - 1.29)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">HSV-2 male</th>\n      <th>Weighted cases</th>\n      <td>17</td>\n      <td>17</td>\n      <td>18</td>\n      <td>26</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>307</td>\n      <td>322</td>\n      <td>268</td>\n      <td>334</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>5.54</td>\n      <td>5.28</td>\n      <td>6.72</td>\n      <td>7.78</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.12</td>\n      <td>0.94</td>\n      <td>NaN</td>\n      <td>0.79</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.62 - 2.04)</td>\n      <td>(0.52 - 1.69)</td>\n      <td>None</td>\n      <td>(0.43 - 1.47)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"15\" valign=\"top\">Believed current HIV infection = 0</th>\n      <th rowspan=\"5\" valign=\"top\">HSV-2 positive</th>\n      <th>Weighted cases</th>\n      <td>154</td>\n      <td>126</td>\n      <td>119</td>\n      <td>134</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1834</td>\n      <td>1668</td>\n      <td>1741</td>\n      <td>1712</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>8.4</td>\n      <td>7.55</td>\n      <td>6.84</td>\n      <td>7.83</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.17</td>\n      <td>0.95</td>\n      <td>NaN</td>\n      <td>1.05</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.94 - 1.47)</td>\n      <td>(0.75 - 1.20)</td>\n      <td>None</td>\n      <td>(0.83 - 1.32)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">HSV-2 female</th>\n      <th>Weighted cases</th>\n      <td>71</td>\n      <td>69</td>\n      <td>69</td>\n      <td>77</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>827</td>\n      <td>767</td>\n      <td>822</td>\n      <td>830</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>8.59</td>\n      <td>9</td>\n      <td>8.39</td>\n      <td>9.28</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.1</td>\n      <td>1.01</td>\n      <td>NaN</td>\n      <td>1.04</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.80 - 1.51)</td>\n      <td>(0.73 - 1.41)</td>\n      <td>None</td>\n      <td>(0.76 - 1.43)</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">HSV-2 male</th>\n      <th>Weighted cases</th>\n      <td>83</td>\n      <td>57</td>\n      <td>50</td>\n      <td>57</td>\n    </tr>\n    <tr>\n      <th>Weighted base</th>\n      <td>1007</td>\n      <td>901</td>\n      <td>919</td>\n      <td>882</td>\n    </tr>\n    <tr>\n      <th>Weighted%</th>\n      <td>8.24</td>\n      <td>6.33</td>\n      <td>5.44</td>\n      <td>6.46</td>\n    </tr>\n    <tr>\n      <th>Addjusted odds ratio</th>\n      <td>1.25</td>\n      <td>0.89</td>\n      <td>NaN</td>\n      <td>1.05</td>\n    </tr>\n    <tr>\n      <th>95% CI</th>\n      <td>(0.91 - 1.72)</td>\n      <td>(0.64 - 1.26)</td>\n      <td>None</td>\n      <td>(0.75 - 1.46)</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n---\n# 6. Discussion \n---\nOverall the analysis does not yield any significant result except for the condom related behavioral outcomes to groups receiving condoms and VCT related behavioral outcomes to groups having VCT. \n\nDuflo et al. (2019) providing two possible explanations from previous studies for the non-significant result.\n1.\tMost of the past research only find behavioral changes in people testing positive of HIV. In a meta-analysis (Fonner 2012 et al.) summing up 17 studies, it appears that no significant changes in STI or HIV prevalence rate of those receiving VCT. However, to who being test positive for HIV, there is a reduction in sex partners and an increase in condom use. This cannot be assessed in our data due to overly low HIV prevalence.\n\n2.\tThe age group. Another multi-component HIV prevention program conducted in Africa and Thailand suggests there is a significant reduction among older women, but no effect among ages 18 to 24 (Coates 2014 et al.). In this study, the subjects are between 17 to 24, which is consistent with their finding.\n3.\tThere were several large scale HIV testing events in the area. At baseline, 44% of the control group had been tested for HIV, while 82.4% had been tested at follow up. The high participation rate is likely to interfere and weaken the effect of treatments.\n\nI have considered changing paper because my replication process doesn\u2019t feel like having closed connections to the course contents and the fact I failed to find HSV-2 at baseline. But I didn\u2019t, subjecting to sunk cost fallacy.\n\n\n---\n# 7. Debug: HSV-2 at baseline\n---\nThis section document all my failing attempts on searching for variable represent HSV-2 testing result at baseline.\n\n\n## 7.1. Searching dataset and verifying\n\n\n```python\nhsv = df_filter.filter(regex='.*(?i)hsv.*',axis=1)\nhsv.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>hsv2id</th>\n      <th>merge_HSVcode</th>\n      <th>HSV_result1</th>\n      <th>HSV_od1</th>\n      <th>HSV_result2</th>\n      <th>HSV_od2</th>\n      <th>HSV_result3</th>\n      <th>HSV_od3</th>\n      <th>HSV_result4</th>\n      <th>HSV_od4</th>\n      <th>HSV_finalresult</th>\n      <th>HSV_batch</th>\n      <th>merge_HSVresults</th>\n      <th>hsv2_positive</th>\n      <th>HSV2_blood_sample</th>\n      <th>hsv2_decline</th>\n      <th>hsv2_accept</th>\n      <th>HSV-2 positive</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>546864.0</td>\n      <td>3.0</td>\n      <td>Negative</td>\n      <td>NaN</td>\n      <td></td>\n      <td>NaN</td>\n      <td></td>\n      <td>NaN</td>\n      <td></td>\n      <td>NaN</td>\n      <td>Negative</td>\n      <td>1.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>378855.0</td>\n      <td>3.0</td>\n      <td>Negative</td>\n      <td>NaN</td>\n      <td></td>\n      <td>NaN</td>\n      <td></td>\n      <td>NaN</td>\n      <td></td>\n      <td>NaN</td>\n      <td>Negative</td>\n      <td>1.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>579082.0</td>\n      <td>3.0</td>\n      <td>Negative</td>\n      <td>NaN</td>\n      <td></td>\n      <td>NaN</td>\n      <td></td>\n      <td>NaN</td>\n      <td></td>\n      <td>NaN</td>\n      <td>Negative</td>\n      <td>1.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>775833.0</td>\n      <td>3.0</td>\n      <td>Positive</td>\n      <td>NaN</td>\n      <td>Positive</td>\n      <td>2.533</td>\n      <td></td>\n      <td>NaN</td>\n      <td></td>\n      <td>NaN</td>\n      <td>Positive</td>\n      <td>1.0</td>\n      <td>3.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>696069.0</td>\n      <td>3.0</td>\n      <td>Negative</td>\n      <td>NaN</td>\n      <td></td>\n      <td>NaN</td>\n      <td></td>\n      <td>NaN</td>\n      <td></td>\n      <td>NaN</td>\n      <td>Negative</td>\n      <td>1.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nFirst, rule out variables that are obviously irrelevant.\n- **hsv2id** is assigned to almost all individuals in the data set 19202 out of 19293 regardless of having HSV-2 result at stage 2 or not. Here, in the filtered data frame total number equals 7458 as the surveyed individuals that are filtered out previously.\n- **merge_HSVcode** seems to be some sort of merging key generated in data processing process of the authors, having only value 3.\n- **HSV_od1** to **HSV_od4** are supposed to be the numerical value records of some special cases in the testing process. It takes values that range from 0 to about 5, only have value if HSV_result is not null.\n- **HSV_batch** something takes value from 1 to 8, I assume it relates to testing branches.\n- **merge_HSVresults** taking value 1 & 3 with 144 & 7313 entries each, it supposed to be something related to merge_HSVcode\n- **HSV2_blood_sample**, **hsv2_decline**, **hsv2_accept** could be gauged by the number of entries and name that denoted taking hsv2 blood sample or not, accepting testing or not, declining test or not.\n- **HSV-2 positive** is variable I created for table 2 based on hsv-positive\n\nAs for HSV_result1 to HSV_result4, HSV_finalresult, hsv2_positive, it can be seemn from below, HSV_finalresult is the same thing as hsv-positive.\n\n\n```python\npd.crosstab(hsv['hsv2_positive'], hsv['HSV_finalresult'])\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>HSV_finalresult</th>\n      <th>Equivocal</th>\n      <th>Negative</th>\n      <th>Positive</th>\n    </tr>\n    <tr>\n      <th>hsv2_positive</th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0.0</th>\n      <td>31</td>\n      <td>6674</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1.0</th>\n      <td>0</td>\n      <td>0</td>\n      <td>597</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nAs for the 4 HSV_result, if counting how many non-null values in each column, it will appear to be declined sharply.\n\n\n```python\nhsv_results = hsv.filter(regex='HSV_result.',axis=1)\nhsv_results[hsv_results != ''].count()\n```\n\n\n\n\n    HSV_result1    7314\n    HSV_result2     763\n    HSV_result3     145\n    HSV_result4      14\n    dtype: int64\n\n\n\nIf comparing the only one testing that is covered almost the whole sample with the final result, it\u2019ll show those who have been testing negative in HSV_result1 are all considered as negative in the final result. This explains that it can\u2019t be testing at baseline because it suggests there is no new infections and is inconsistent with the number in Duflo et al. (2019). Combing these two characteristics and existence of HSV_od1 to 4, I\u2019ll say these are just variables recording repeated testing results for the follow-up test.\n\n\n```python\npd.crosstab(hsv['HSV_result1'], hsv['HSV_finalresult'])\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>HSV_finalresult</th>\n      <th></th>\n      <th>Equivocal</th>\n      <th>Negative</th>\n      <th>Positive</th>\n    </tr>\n    <tr>\n      <th>HSV_result1</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th></th>\n      <td>144</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>Equivocal</th>\n      <td>0</td>\n      <td>21</td>\n      <td>54</td>\n      <td>27</td>\n    </tr>\n    <tr>\n      <th>Negative</th>\n      <td>0</td>\n      <td>0</td>\n      <td>6555</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>Positive</th>\n      <td>0</td>\n      <td>22</td>\n      <td>65</td>\n      <td>570</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## 7.2. Others\n\nHere is a list of the rest of my attempts because showing them all would look tedious.\n- Using self-reported STI, an_STI_Q205 to compose the HSV-2 prevalence at baseline, sadly, it doesn\u2019t yield anything closed to the value reported in Duflo et al. (2019) and is not the same as how the paper described as well. In the paper, it mentioned about blood testing, instead of self-reporting as the source of HSV-2 infection.\n- Doing the searching and verifying process in 7.1 on keywords: \u2018bd\u2019, \u2018blood\u2019, \u2018test\u2019, \u2018result\u2019  etc.\n- Checking both questionnaires about whether they have HSV results  \n- Poring over the whole dataset and testing any variable that having a name can possibly be it.\n\nThe only possible solution that\u2019s left is writing to the author and ask about it. Considering of time they\u2019ll take to reply might exceed project deadline and inappropriateness, I didn\u2019t give this thought a shot.\n\n\n---\n# 8. References\n---\n\n* **Canning D. (2006)** _The economics of HIV/AIDS in low-income countries: the case for prevention. J Econ Perspect._ 20(3):121-142. doi:10.1257/jep.20.3.121\n\n* **Coates TJ, Kulich M, Celentano DD, Zelaya CE, Chariyalertsak S, Chingono A, et al. (2014)** _Effect of community-based voluntary counselling and testing on HIV incidence and social and behavioural outcomes (NIMH Project Accept; HPTN 043): a cluster-randomised trial._ Lancet Global Health. 2(5): E267\u201377. https://doi.org/10.1016/S2214-109X(14)70032-4 PMID: 25103167\n\n* **de Grange, L., Gonz\u00e1lez, F., Vargas, I. et al. (2015)** _A Logit Model With Endogenous Explanatory Variables and Network Externalities._ Netw Spat Econ 15, 89\u2013116. https://doi.org/10.1007/s11067-014-9271-5\n\n* **Duflo E, Dupas P, Ginn T, Barasa GM, Baraza M, Pouliquen V, et al. (2019)** _HIV prevention among youth: A randomized controlled trial of voluntary counseling and testing for HIV and male condom distribution in rural Kenya._ PLoS ONE 14(7): e0219535. https://doi.org/10.1371/journal.pone.0219535\n\n* **Duflo E, Dupas P, Kremer M. (2015)** _Education, HIV, and Early Fertility: Experimental Evidence from Kenya. American Economic Review._ 105(9):2257\u201397.\n\n* **Fonner VA, Denison J, Kennedy CE, O\u2019Reilly K, Sweat M. (2012)** _Voluntary counseling and testing (VCT) for changing HIV-related risk behavior in developing countries._ The Cochrane Library. https://doi.org/10.1002/14651858.CD010274\n\n* **Greene (2006)** _Econometric Analysis_\n\n* **Hansen B. (2020)** _Econometrics_\n\n* **Miguel, Edward, and Michael Kremer. (2004)** _Worms: Identifying Impacts on Education and Health in the Presence of Treatment Externalities._ Econometrica 72 (1): 159-217.\n\n* **Sherr L, Lopman B, Kakowa M, Dube S, Chawira G, Nyamukapa C, et al. (2007)** _Voluntary counselling and testing: uptake, impact on sexual behaviour, and HIV incidence in a rural Zimbabwean cohort. AIDS._ 21(7):851\u201386 https://doi.org/10.1097/QAD.0b013e32805e8711 PMID: 17415040\n\n\n\n-------\nNotebook by Amanda Wu | Find me on GitHub at https://github.com/amanda8412383\n\n---\n", "meta": {"hexsha": "adad01d72215c847068e551954ac6b61da97ad9a", "size": 304919, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Duflo_2019_Wu.ipynb", "max_stars_repo_name": "amanda8412383/microeconometrics-course-project-amanda8412383", "max_stars_repo_head_hexsha": "644d80363e866391bdfce64be2bb353ba9233e45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Duflo_2019_Wu.ipynb", "max_issues_repo_name": "amanda8412383/microeconometrics-course-project-amanda8412383", "max_issues_repo_head_hexsha": "644d80363e866391bdfce64be2bb353ba9233e45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Duflo_2019_Wu.ipynb", "max_forks_repo_name": "amanda8412383/microeconometrics-course-project-amanda8412383", "max_forks_repo_head_hexsha": "644d80363e866391bdfce64be2bb353ba9233e45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.1596802842, "max_line_length": 21789, "alphanum_fraction": 0.3577671447, "converted": true, "num_tokens": 35811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3174262785020255, "lm_q2_score": 0.13296423504419935, "lm_q1q2_score": 0.0422063423039488}}
{"text": "## \u91cf\u5b50\u30d7\u30ed\u30b0\u30e9\u30df\u30f3\u30b0\u5165\u9580\uff1aTKET \u7de8\n\nKentaro Yamamoto (Research Scientist)\n\n**Cambridge Quantum Computing Japan**\n\nkentaro.yamamoto@cambridgequantum.com\n\n### Overview\n\nIn this webinar, we will provide demos on `pytket` and `qermit`, both of which are open-source Python libraries developed by Cambridge Quantum.\n`pytket` is a Python interface to TKET --- platform-agnostic quantum software development kit (QSDK), wheras `qermit` is a quantum error mitigation framework integrated with `pytket`.\nExamples are taken from quantum chemistry problems, but the codes are available for general purposes.\nBy using `pytket` and `qermit`, **one can quickly prototype and run the platform-agnostic quantum programs.**\n\n### Why TKET?\n\nHow does pytket satisfy the constraints of NISQ-era quantum computers?\n\n* A Generic Compilation Strategy for the Unitary Coupled Cluster Ansatz &rightarrow; **arXiv:2007.10515** <br>\n* t|ket$\\rangle$: A Retargetable Compiler for NISQ Devices &rightarrow; **arXiv:2003.10611** <br>\n* Phase Gadget Synthesis for Shallow Circuits &rightarrow; **arXiv:1906.01734** <br>\n* On the qubit routing problem &rightarrow; **arXiv:1902.08091** <br>\n\n[github.com/CQCL/pytket](https://github.com/CQCL/pytket)\n\n### Required python packages\n\nPlease install the packages\n```\npytket          # Quantum circuit construction\npytket-qiskit   # Quantum circuit compilation\nqermit          # Quantum circuit execution (from CQCL/qermit)\n```\nIf these packages are not installed in your environment yet, uncomment the following cell and install them.\n\n\n```python\n#!pip install pytket==0.15.0\n#!pip install pytket-qiskit==0.18.0\n#!pip install qermit==0.1.2\n```\n\nVersion numbers are specified to make sure this script works,\nbut in general it is recommended to install the latest versions.\n\n[Getting started with Qiskit](https://qiskit.org/documentation/getting_started.html) would be helpful for users who are not familiar with setting up Python environment, including the IBM Quantum account setup to access IBM's hardware used in the following examples.\n\n### TKET Walled Garden: Playing with retargetability \n\n\n```python\n# Preparing backends\nfrom pytket.extensions.qiskit import IBMQBackend, IBMQEmulatorBackend, AerBackend\n\ndevice_id = 'ibmq_quito'\n# backend = IBMQBackend(device_id)\nbackend = IBMQEmulatorBackend(device_id)\nnoiseless_backend = AerBackend()\n```\n\nConstruct a quantum circuit for a Bell pair $|\\psi\\rangle = \\frac{1}{2}(|00\\rangle + |11\\rangle)$ as a `pytket` object.\n\n\n```python\n# Generate quantum circuit.\nfrom pytket import Circuit\n\nbell_circuit = Circuit(2,2).H(0).CX(0,1).measure_all()\n```\n\n\n```python\nfrom pytket.circuit.display import render_circuit_jupyter\n\nrender_circuit_jupyter(bell_circuit)\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n\n<style>\nbody, .circuit__preview-body {\n    font-family: \"roboto\", system-ui, sans-serif;\n    --accent-col: green;\n    --accent-col-fill: darkseagreen;\n    --accent-col-alt: #aca;\n    --accent-col-emph: limegreen;\n    --accent-col-overlay: rgba(130,255,140,0.2);\n    --accent-col-outline: rgba(30, 250, 30,0.2);\n    --main-col: black;\n    --mid-col: #bbb;\n    --faint-col: #eee;\n    --faint-col-overlay: rgba(0, 0, 0, 0.05);\n    --main-bg: white;\n}\n\n.row{\n    display: flex;\n    flex-wrap: wrap;\n    align-items: center;\n    padding: 10px;\n    border-bottom: 1px solid var(--faint-col);\n    position: relative;\n}\n.row-item{\n    flex-grow: 1\n}\n.row-item-l{\n    text-align: left;\n}\n.row-item-r{\n    text-align: right;\n}\n.row-sub-heading{\n    border-color: var(--accent-col-emph);\n}\n\n/* FOR DISPLAYING CIRCUITS */\n/* Main preview container */\n.circuit-preview {\n    width: 100%;\n    height: 100%;\n    text-align: center;\n    color: black;\n}\n.circuit_variables {\n    /* Define some variables */\n    --box-height: 40px;\n    --wire-col: black;\n    --c-wire-col: #bbb;\n    --box-col: #ccc;\n    --box-col-overlay: rgba(0,0,0,0.05);\n    --c-box-col: #ddd;\n    --index-col: #888;\n}\n.circuit-preview.condensed{\n    display: flex;\n    flex-wrap: nowrap;\n}\n\n/* Box colours */\n.h {\n    --box-col: #ffee00;\n    --box-col-overlay: rgba(255, 255, 0, 0.2);\n    --c-box-col: #ffee88;\n    --index-col: #ffcc00;\n}\n.x {\n    --box-col: #ff8888;\n    --box-col-overlay: rgba(255, 0, 0, 0.2);\n    --c-box-col: #e8a6a6;\n    --index-col: red;\n}\n.y {\n    --box-col: #6699ff;\n    --box-col-overlay: rgba(0, 0, 255, 0.2);\n    --c-box-col: #86c6f6;\n    --index-col: blue;\n}\n.z {\n    --box-col: #ccffcc;\n    --box-col-overlay: rgba(0, 255, 0, 0.2);\n    --c-box-col: #e2ffe2;\n    --index-col: green;\n}\n\n.circuit-container{\n    max-width: 100%;\n    display: flex;\n    flex-flow: row wrap;\n    justify-content: center;\n    align-content: flex-start;\n    margin: auto;\n    width: -moz-fit-content;\n    width: fit-content;\n    background: rgba(255, 255, 255, 1);\n}\n.circuit-preview.condensed > .circuit-container{\n    flex-wrap: nowrap;\n    min-width: fit-content;\n}\n.circuit-container.nested{\n    position: relative;\n    flex-wrap: nowrap;\n    margin: -2px 0;\n}\n.nested-circuit-container{\n    display: flex;\n    overflow: auto;\n    max-width: 400px;\n    background: var(--box-col-overlay);\n    border: 1px solid var(--box-col);\n}\n.nested-circuit-container::-webkit-scrollbar {\n    height: 0;\n    width: 0;\n}\n.circuit-inner-scroll{\n    overflow: visible;\n    width: -moz-fit-content;\n    width: fit-content;\n    margin: auto;\n    margin-top: 2px;\n}\n.circuit-end{\n    width: 2px;\n    height: auto;\n    border: 2px solid var(--wire-col);\n    margin: calc(var(--box-height)/2) 0 calc(var(--box-height)/2 + 20px);\n}\n.circuit-layer{\n    min-width: 40px;\n    width: max-content;\n    display: flex;\n    flex-flow: column nowrap;\n    flex-grow: 1;\n    justify-content: space-between;\n    align-items: stretch;\n    margin-bottom: 20px;\n}\n.circuit-container:not(.nested) > .circuit-layer:nth-child(2),\n.circuit-container:not(.nested) > .circuit-layer:nth-last-child(2),\n.circuit-container.nested > .circuit-layer:nth-child(2),\n.circuit-container.nested > .circuit-layer:nth-last-child(2),\n.gate_container.nested > .circuit-layer:first-child,\n.gate_container.nested > .circuit-layer:last-child{\n    min-width: 10px;\n}\n.nested .circuit-layer{\n    margin-bottom: 0;\n}\n.flex_wire{\n    flex-grow: 1;\n}\n/* Display qubit names at start of circuit */\n.circuit-layer.qubits{\n    flex-grow: 0;\n    color: var(--wire-col);\n}\n.qubit{\n    height: calc(var(--box-height) - 20px);\n    padding: 10px;\n    text-align: center;\n    font-family: monospace;\n    box-sizing: content-box;\n}\n.wire{\n    height: 0;\n    border: 1px solid var(--wire-col);\n    background: var(--wire-col);\n    margin: calc(var(--box-height)/2) 0;\n}\n.wire.classical{\n    border-color: var(--c-wire-col) !important;\n    background: var(--c-wire-col) !important;\n}\n.wire.transparent-wire{\n    border-color: transparent;\n    background: transparent;\n}\n\n/* Generic base for our gates */\n.gate_container{\n    position: relative;\n    min-width: -moz-fit-content;\n    min-width: fit-content;\n}\n.gate_container.nested{\n    display: flex;\n    flex-wrap: nowrap;\n}\n.gate_container.nested:after{\n    display: flex;\n    flex-wrap: nowrap;\n}\n.gate_container .classical{\n    background: var(--c-box-col);\n    border-color: var(--index-col);\n}\n.gate{\n    position: relative;\n    height: calc(var(--box-height) - 16px);\n    margin: 0 9px;\n    padding: 9px 5px;\n    border: 1px solid var(--index-col);\n    border-bottom: none;\n    border-top: none;\n    text-align: left;\n    background: var(--box-col);\n    display: flex;\n    box-sizing: content-box;\n    z-index: 1;\n}\n.wire-label{\n    color: var(--index-col);\n    width: -moz-fit-content;\n    width: fit-content;\n    height: calc(var(--box-height) - 18px);\n    padding-right: 5px;\n}\n.gate_top > .wire-label,\n.gate_bottom > .wire-label {\n    padding-top: 0;\n}\n.nested-label-layer{\n    background: var(--box-col);\n    padding: 0 5px;\n}\n.nested-label-layer .wire-label{\n    padding: 10px 0;\n}\n\n/* Multi-qubit gates */\n.gate_bottom{\n    height: calc(var(--box-height) - 18px);\n    margin-bottom: 10px;\n    padding-bottom: 0;\n    border-bottom: 1px solid var(--index-col);\n}\n.gate_top{\n    height: calc(var(--box-height) - 18px);\n    margin-top: 10px;\n    padding-top: 0;\n    border-top: 1px solid var(--index-col);\n}\n.gate_name{\n    text-align: center;\n    flex-grow: 1;\n}\n/* Single qubit gate*/\n.gate_box{\n    height: calc(var(--box-height) - 20px);\n    margin: 10px;\n    padding: 0 5px;\n    border: 1px solid var(--index-col);\n    text-align: center;\n}\n\n/* Special gates */\n.gate_connection {\n    position: absolute;\n    top: -3px;\n    left: -1px;\n    border: none;\n    margin: calc(var(--box-height)/2) calc(50% - 5px);\n    padding: 0;\n}\n.gate_swap {\n    height: 20px;\n    width: 20px;\n    margin: calc(var(--box-height)/2 - 6px) calc(50% - 9px);\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%270%200%2064%2064%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27currentcolor%27%3E%0A%20%20%3Cpath%20d%3D%27M60%200%20L32%2028%20L4%200%20L0%204%20L28%2032%20L0%2060%20L4%2064%20L32%2036%20L60%2064%20L64%2060%20L36%2032%20L64%204%27%20/%3E%0A%3C/svg%3E\n) center;\n    background-size: cover;\n}\n.gate_measure {\n    height: 20px;\n    width: 25px;\n    margin: calc(var(--box-height)/2 - 10px) calc(50% - 11px);\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%27-10%20-10%2084%2084%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27white%27%0A%20%20stroke%3D%22black%22%0A%20%20stroke-width%3D%224px%22%0A%3E%0A%20%20%3Cpath%20d%3D%27M63%2C63%20C63%2C32%2048%2C16%2032%2C16%20C16%2C16%201%2C32%201%2C63%20L63%2C63%27%20/%3E%0A%20%20%3Cpath%20d%3D%22M32%2C63%20L56%2C16%22%20/%3E%0A%3C/svg%3E\n) center;\n    background-size: cover;\n}\n.gate_control {\n    position: absolute;\n    top: 0;\n    left: 0;\n    border-radius: 50%;\n    width: 6px;\n    height: 6px;\n    margin: calc(var(--box-height)/2 - 3px) calc(50% - 5px);\n    padding: 0;\n    border: 2px solid var(--wire-col);\n    background: var(--box-col);\n}\n.gate_control.classical{\n    background: var(--c-wire-col);\n    border-color: var(--c-wire-col);\n}\n.control_index{\n    position: absolute;\n    right: calc(50% - 1em);\n    top: calc(50% - 1.4em);\n    color: var(--c-wire-col);\n    font-size: 0.8em;\n}\n.control_index.measure{\n    right: calc(50% - 1.2em);\n    top: calc(50% - 1.8em);\n    color: var(--index-col);\n}\n.gate_x {\n    top: -10px;\n    left: -6px;\n    border-radius: 50%;\n    border: 1px solid var(--wire-col);\n    width: 20px;\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%270%200%2064%2064%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27currentcolor%27%3E%0A%20%20%3Cpath%20d%3D%27M36%2064%20L36%2036%20L64%2036%20L64%2028%20L36%2028%20L36%200%20L28%200%20L28%2028%20L0%2028%20L0%2036%20L28%2036%20L28%2064%27%20/%3E%0A%3C/svg%3E\n) center;\n    background-color: var(--box-col);\n    background-size: cover;\n}\n.gate_reset{\n    margin: 11px 10px;\n    padding: 0 0 0 10px;\n    border: none !important;\n    border-left: 2px solid var(--wire-col) !important;\n    background: transparent;\n}\n.gate_reset_spider{\n    width: calc(var(--box-height) - 24px);\n    height: calc(var(--box-height) - 24px);\n    background: var(--box-col);\n    border: 2px solid var(--wire-col);\n    border-radius: 50%;\n    font-size: 0.75em;\n}\n\n/* Add wire sections coming in and out of the gate */\n.gate_in:before, .gate_in:after{\n    content: '';\n    position: absolute;\n    display: block;\n    top: calc(50% - 1px);\n    border: 1px solid var(--wire-col);\n    width: 9px;\n    height: 0;\n    background: var(--wire-col);\n    box-sizing: content-box;\n}\n.classical.gate_in:before,\n.classical.gate_in:after{\n    border-color: var(--c-wire-col);\n}\n\n.gate_in:before{\n    left: -12px;\n}\n.gate_out:after{\n    right: -12px;\n}\n.gate_top.gate_in:before, .gate_top.gate_out:after{\n    top:calc(50% - 6.5px)\n}\n.gate_bottom.gate_in:before, .gate_bottom.gate_out:after{\n    top:calc(50% + 4.5px)\n}\n\n\n.link-bottom, .link-top {\n    height: var(--box-height);\n    width: 0;\n    border: 1px solid var(--wire-col);\n    background: var(--wire-col);\n    position: absolute;\n    display: block;\n    left: calc(50% - 1px);\n    box-sizing: content-box;\n}\n.link-top{\n    top: calc(0px - var(--box-height)/2);\n}\n.link-bottom{\n    top: calc(var(--box-height)/2)\n}\n.half-link {\n    height: calc(var(--box-height) - 9px);\n}\n.half-link.link-bottom{\n    top: calc(var(--box-height)/2 + 11px)\n}\n.half-link.link-top{\n    top: calc(-2px - var(--box-height)/2);\n}\n.link-bottom.measurement{\n    width: 3px;\n    left: calc(50% - 0.5px);\n    border: none;\n    background: var(--c-wire-col);\n    height: calc(var(--box-height) + 2px);\n    z-index: 1;\n}\n\n\n\n/* tool tips */\n.tool-tip-container{\n    margin: calc(0px - var(--box-height)) auto 0;\n    padding-top: var(--box-height);\n    position: relative;\n    bottom: 0;\n    left: 0;\n    right: 0;\n    height: 0;\n    z-index: 4;\n    width: fit-content;\n    overflow: hidden;\n}\n.tool-tip-container.no-js{\n    overflow: visible;\n}\n.tool-tip-container.no-js:hover{\n    z-index: 10;\n}\n.nested > .tool-tip-container{\n    position: absolute;\n    bottom: -10px;\n}\n.tool-tip{\n    visibility: hidden;\n    opacity: 0;\n    -webkit-transition: visibility 0.2s, opacity 0.2s;\n    -moz-transition: visibility 0.2s, opacity 0.2s;\n    transition: visibility 0.2s, opacity 0.2s;\n    max-width: 250px;\n}\n.tool-tip-container.no-js:hover > .tool-tip{\n    visibility: visible;\n    opacity: 1;\n}\n.tool-tip-content{\n    background: var(--main-bg);\n    margin: 0 auto;\n    width: -moz-fit-content;\n    width: fit-content;\n    max-width: 100%;\n}\n.no-js > .tool-tip > .tool-tip-content{\n    height: auto;\n    padding: 20px;\n    margin: 0 auto;\n}\n.tool-tip-container.no-js:hover > .tool-tip > .tool-tip-content,\n.no-js > tool-tip > .tool-tip-content:hover{\n    box-shadow: 0 -5px 20px 5px var(--faint-col-overlay);\n}\n.tool-tip:after{\n    content: \" \";\n    position: absolute;\n    bottom: 0;\n    left: 50%;\n    margin-left: -5px;\n    border-width: 5px;\n    border-style: solid;\n    border-color: transparent transparent var(--main-bg) transparent;\n}\n.tool-tip .complex-number{\n    padding: 4px;\n}\n.tool-tip-content > .gate_container.nested{\n    width: 100%;\n    min-width: unset;\n}\n.nested-label-layer.as-height{\n    padding: 0;\n}\n.tool-tip-content > .gate_container.nested > .nested-circuit-container,\n.circuit-preview.condensed > .nested-circuit-container{\n    background: transparent;\n    border: none;\n    width: 100%;\n    min-width: unset;\n    max-width: unset;\n}\n\n/* Tool-tip modal */\n.circuit-grid{\n    display: flex;\n    flex-direction: row-reverse;\n    align-items: stretch;\n    align-content: stretch;\n}\n.circuit-grid-circuit{\n    flex: 1 1 auto;\n    margin-top: 30px;\n    overflow: auto;\n    max-height: inherit;\n}\n\n\n\n\n/*  FOR DISPLAYING CHARTS  */\ntable{\n    border-collapse: collapse;\n}\n.table-container{\n    margin: auto;\n}\n.bar-chart-container{\n    min-width: 300px;\n    width: 60%;\n}\n.square-chart-container{\n    width: auto;\n    min-width: 0;\n    overflow: hidden;\n}\n\n/* Make sure we can see the rightmost border */\n.square-chart-container tbody{\n    position: relative;\n    left: -1px;\n    display: block;\n}\nthead > tr{\n    background: transparent !important;\n}\ntr:hover, tr {\n    background: initial !important;\n}\n\ntd, th{\n    padding: 10px;\n    position: relative;\n}\n\n/* COMPLEX NUMBERS AND MATRICES */\n.complex-number{\n    padding: 10px;\n}\n.mid-number{\n    padding: 5px;\n    font-size: 0.75em;\n}\n.large-number{\n    padding: 2px;\n    font-size: 0.75em;\n}\n.matrix_container{\n    border: 2px solid var(--mid-col);\n    border-top: 0;\n    border-bottom: 0;\n    margin: auto !important;\n    border-collapse: collapse;\n    text-align: center;\n}\n\n\n/* LIST RESULTS NICELY */\n.list{\n    flex-wrap: wrap;\n    justify-content: space-evenly;\n    align-items: stretch;\n    padding: 0;\n}\n.list > *{\n    margin: 10px;\n}\n.list > .row-sub-heading{\n    margin: 10px 0;\n}\n</style>\n\n</head>\n<body>\n    <div class=\"row circuit-grid circuit__preview-body\">\n        <div class=\"circuit-grid-circuit thin-scrollbar\"  style=\"\">\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n    <div class=\"circuit-preview circuit_variables condensed\">\n\n\n            <div class=\"nested-label-layer as-height\">\n\n                    <div class=\"wire-label\"></div>\n\n                    <div class=\"wire-label\"></div>\n\n                    <div class=\"wire-label\"></div>\n\n                    <div class=\"wire-label\"></div>\n\n            </div>\n            <div class=\"nested-circuit-container\"><div class=\"circuit-inner-scroll\">\n\n        <div class=\"circuit-container nested\">\n            <div class=\"circuit-layer qubits\">\n\n            <div class=\"qubit\">q[0]</div>\n\n            <div class=\"qubit\">q[1]</div>\n\n\n            <div class=\"qubit bit\">c[0]</div>\n\n            <div class=\"qubit bit\">c[1]</div>\n\n    </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container h\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n                <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n                <div class=\"gate gate_control z\"></div>\n\n            </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container x\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">X</span>\n                </div>\n\n\n\n                <div class=\"link-top\"></div>\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n        <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection gate_measure\"></div>\n\n            <div class=\"control_index measure z\">z</div>\n\n    </div>\n\n            <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n\n    </div>\n\n        <div class=\"gate_container\">\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n        <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection gate_measure\"></div>\n\n            <div class=\"control_index measure z\">z</div>\n\n    </div>\n\n            <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n\n    </div>\n\n        <div class=\"gate_container\">\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n            <div class=\"circuit-layer qubits\">\n\n            <div class=\"qubit\">q[0]</div>\n\n            <div class=\"qubit\">q[1]</div>\n\n\n            <div class=\"qubit bit\">c[0]</div>\n\n            <div class=\"qubit bit\">c[1]</div>\n\n    </div>\n        </div>\n\n            </div></div>\n\n    </div>\n\n\n\n\n        </div>\n    </div>\n</body>\n</html>\n\n\nRetargeting: `pytket` $\\to$ `Qiskit`\n\n\n```python\n# Display the quantum circuit using Qiskit.\nfrom pytket.extensions.qiskit import tk_to_qiskit\n\nqisk_c = tk_to_qiskit(bell_circuit)\nprint(type(qisk_c))\nprint(qisk_c)\n```\n\n    <class 'qiskit.circuit.quantumcircuit.QuantumCircuit'>\n         \u250c\u2500\u2500\u2500\u2510     \u250c\u2500\u2510   \n    q_0: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524M\u251c\u2500\u2500\u2500\n         \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2534\u2500\u2510\u2514\u2565\u2518\u250c\u2500\u2510\n    q_1: \u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\u2500\u256b\u2500\u2524M\u251c\n              \u2514\u2500\u2500\u2500\u2518 \u2551 \u2514\u2565\u2518\n    c: 2/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\n                    0  1 \n\n\nCompile the circuit for a given backend.\n\n\n```python\n# Compile quantum circuit for the IBM devices.\nbackend.compile_circuit(bell_circuit)\n\nqisk_c = tk_to_qiskit(bell_circuit)\nprint(qisk_c)\n```\n\n                                              \n    node_0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n            \u250c\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2510     \u250c\u2500\u2510   \n    node_1: \u2524 \u221aX \u251c\u2524 Rz(\u03c0/2) \u251c\u2524 \u221aX \u251c\u2500\u2500\u25a0\u2500\u2500\u2524M\u251c\u2500\u2500\u2500\n            \u2514\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2518\u250c\u2500\u2534\u2500\u2510\u2514\u2565\u2518\u250c\u2500\u2510\n    node_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\u2500\u256b\u2500\u2524M\u251c\n                                   \u2514\u2500\u2500\u2500\u2518 \u2551 \u2514\u2565\u2518\n       c: 2/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\n                                         0  1 \n\n\nRetargeting: `pytket` $\\to$ `OpenQASM`\n\n\n```python\n# Convert the circuit into OpenQASM format.\nfrom pytket.qasm import circuit_to_qasm_str\n\nqasm_c = circuit_to_qasm_str(bell_circuit)\nprint(qasm_c)\n```\n\n    OPENQASM 2.0;\n    include \"qelib1.inc\";\n    \n    qreg node[3];\n    creg c[2];\n    sx node[1];\n    rz(0.5*pi) node[1];\n    sx node[1];\n    cx node[1],node[2];\n    measure node[1] -> c[0];\n    measure node[2] -> c[1];\n    \n\n\n\n```python\n# Convert the circuit from OpenQASM format.\nfrom pytket.qasm import circuit_from_qasm_str\nrender_circuit_jupyter(circuit_from_qasm_str(qasm_c))\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n\n<style>\nbody, .circuit__preview-body {\n    font-family: \"roboto\", system-ui, sans-serif;\n    --accent-col: green;\n    --accent-col-fill: darkseagreen;\n    --accent-col-alt: #aca;\n    --accent-col-emph: limegreen;\n    --accent-col-overlay: rgba(130,255,140,0.2);\n    --accent-col-outline: rgba(30, 250, 30,0.2);\n    --main-col: black;\n    --mid-col: #bbb;\n    --faint-col: #eee;\n    --faint-col-overlay: rgba(0, 0, 0, 0.05);\n    --main-bg: white;\n}\n\n.row{\n    display: flex;\n    flex-wrap: wrap;\n    align-items: center;\n    padding: 10px;\n    border-bottom: 1px solid var(--faint-col);\n    position: relative;\n}\n.row-item{\n    flex-grow: 1\n}\n.row-item-l{\n    text-align: left;\n}\n.row-item-r{\n    text-align: right;\n}\n.row-sub-heading{\n    border-color: var(--accent-col-emph);\n}\n\n/* FOR DISPLAYING CIRCUITS */\n/* Main preview container */\n.circuit-preview {\n    width: 100%;\n    height: 100%;\n    text-align: center;\n    color: black;\n}\n.circuit_variables {\n    /* Define some variables */\n    --box-height: 40px;\n    --wire-col: black;\n    --c-wire-col: #bbb;\n    --box-col: #ccc;\n    --box-col-overlay: rgba(0,0,0,0.05);\n    --c-box-col: #ddd;\n    --index-col: #888;\n}\n.circuit-preview.condensed{\n    display: flex;\n    flex-wrap: nowrap;\n}\n\n/* Box colours */\n.h {\n    --box-col: #ffee00;\n    --box-col-overlay: rgba(255, 255, 0, 0.2);\n    --c-box-col: #ffee88;\n    --index-col: #ffcc00;\n}\n.x {\n    --box-col: #ff8888;\n    --box-col-overlay: rgba(255, 0, 0, 0.2);\n    --c-box-col: #e8a6a6;\n    --index-col: red;\n}\n.y {\n    --box-col: #6699ff;\n    --box-col-overlay: rgba(0, 0, 255, 0.2);\n    --c-box-col: #86c6f6;\n    --index-col: blue;\n}\n.z {\n    --box-col: #ccffcc;\n    --box-col-overlay: rgba(0, 255, 0, 0.2);\n    --c-box-col: #e2ffe2;\n    --index-col: green;\n}\n\n.circuit-container{\n    max-width: 100%;\n    display: flex;\n    flex-flow: row wrap;\n    justify-content: center;\n    align-content: flex-start;\n    margin: auto;\n    width: -moz-fit-content;\n    width: fit-content;\n    background: rgba(255, 255, 255, 1);\n}\n.circuit-preview.condensed > .circuit-container{\n    flex-wrap: nowrap;\n    min-width: fit-content;\n}\n.circuit-container.nested{\n    position: relative;\n    flex-wrap: nowrap;\n    margin: -2px 0;\n}\n.nested-circuit-container{\n    display: flex;\n    overflow: auto;\n    max-width: 400px;\n    background: var(--box-col-overlay);\n    border: 1px solid var(--box-col);\n}\n.nested-circuit-container::-webkit-scrollbar {\n    height: 0;\n    width: 0;\n}\n.circuit-inner-scroll{\n    overflow: visible;\n    width: -moz-fit-content;\n    width: fit-content;\n    margin: auto;\n    margin-top: 2px;\n}\n.circuit-end{\n    width: 2px;\n    height: auto;\n    border: 2px solid var(--wire-col);\n    margin: calc(var(--box-height)/2) 0 calc(var(--box-height)/2 + 20px);\n}\n.circuit-layer{\n    min-width: 40px;\n    width: max-content;\n    display: flex;\n    flex-flow: column nowrap;\n    flex-grow: 1;\n    justify-content: space-between;\n    align-items: stretch;\n    margin-bottom: 20px;\n}\n.circuit-container:not(.nested) > .circuit-layer:nth-child(2),\n.circuit-container:not(.nested) > .circuit-layer:nth-last-child(2),\n.circuit-container.nested > .circuit-layer:nth-child(2),\n.circuit-container.nested > .circuit-layer:nth-last-child(2),\n.gate_container.nested > .circuit-layer:first-child,\n.gate_container.nested > .circuit-layer:last-child{\n    min-width: 10px;\n}\n.nested .circuit-layer{\n    margin-bottom: 0;\n}\n.flex_wire{\n    flex-grow: 1;\n}\n/* Display qubit names at start of circuit */\n.circuit-layer.qubits{\n    flex-grow: 0;\n    color: var(--wire-col);\n}\n.qubit{\n    height: calc(var(--box-height) - 20px);\n    padding: 10px;\n    text-align: center;\n    font-family: monospace;\n    box-sizing: content-box;\n}\n.wire{\n    height: 0;\n    border: 1px solid var(--wire-col);\n    background: var(--wire-col);\n    margin: calc(var(--box-height)/2) 0;\n}\n.wire.classical{\n    border-color: var(--c-wire-col) !important;\n    background: var(--c-wire-col) !important;\n}\n.wire.transparent-wire{\n    border-color: transparent;\n    background: transparent;\n}\n\n/* Generic base for our gates */\n.gate_container{\n    position: relative;\n    min-width: -moz-fit-content;\n    min-width: fit-content;\n}\n.gate_container.nested{\n    display: flex;\n    flex-wrap: nowrap;\n}\n.gate_container.nested:after{\n    display: flex;\n    flex-wrap: nowrap;\n}\n.gate_container .classical{\n    background: var(--c-box-col);\n    border-color: var(--index-col);\n}\n.gate{\n    position: relative;\n    height: calc(var(--box-height) - 16px);\n    margin: 0 9px;\n    padding: 9px 5px;\n    border: 1px solid var(--index-col);\n    border-bottom: none;\n    border-top: none;\n    text-align: left;\n    background: var(--box-col);\n    display: flex;\n    box-sizing: content-box;\n    z-index: 1;\n}\n.wire-label{\n    color: var(--index-col);\n    width: -moz-fit-content;\n    width: fit-content;\n    height: calc(var(--box-height) - 18px);\n    padding-right: 5px;\n}\n.gate_top > .wire-label,\n.gate_bottom > .wire-label {\n    padding-top: 0;\n}\n.nested-label-layer{\n    background: var(--box-col);\n    padding: 0 5px;\n}\n.nested-label-layer .wire-label{\n    padding: 10px 0;\n}\n\n/* Multi-qubit gates */\n.gate_bottom{\n    height: calc(var(--box-height) - 18px);\n    margin-bottom: 10px;\n    padding-bottom: 0;\n    border-bottom: 1px solid var(--index-col);\n}\n.gate_top{\n    height: calc(var(--box-height) - 18px);\n    margin-top: 10px;\n    padding-top: 0;\n    border-top: 1px solid var(--index-col);\n}\n.gate_name{\n    text-align: center;\n    flex-grow: 1;\n}\n/* Single qubit gate*/\n.gate_box{\n    height: calc(var(--box-height) - 20px);\n    margin: 10px;\n    padding: 0 5px;\n    border: 1px solid var(--index-col);\n    text-align: center;\n}\n\n/* Special gates */\n.gate_connection {\n    position: absolute;\n    top: -3px;\n    left: -1px;\n    border: none;\n    margin: calc(var(--box-height)/2) calc(50% - 5px);\n    padding: 0;\n}\n.gate_swap {\n    height: 20px;\n    width: 20px;\n    margin: calc(var(--box-height)/2 - 6px) calc(50% - 9px);\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%270%200%2064%2064%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27currentcolor%27%3E%0A%20%20%3Cpath%20d%3D%27M60%200%20L32%2028%20L4%200%20L0%204%20L28%2032%20L0%2060%20L4%2064%20L32%2036%20L60%2064%20L64%2060%20L36%2032%20L64%204%27%20/%3E%0A%3C/svg%3E\n) center;\n    background-size: cover;\n}\n.gate_measure {\n    height: 20px;\n    width: 25px;\n    margin: calc(var(--box-height)/2 - 10px) calc(50% - 11px);\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%27-10%20-10%2084%2084%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27white%27%0A%20%20stroke%3D%22black%22%0A%20%20stroke-width%3D%224px%22%0A%3E%0A%20%20%3Cpath%20d%3D%27M63%2C63%20C63%2C32%2048%2C16%2032%2C16%20C16%2C16%201%2C32%201%2C63%20L63%2C63%27%20/%3E%0A%20%20%3Cpath%20d%3D%22M32%2C63%20L56%2C16%22%20/%3E%0A%3C/svg%3E\n) center;\n    background-size: cover;\n}\n.gate_control {\n    position: absolute;\n    top: 0;\n    left: 0;\n    border-radius: 50%;\n    width: 6px;\n    height: 6px;\n    margin: calc(var(--box-height)/2 - 3px) calc(50% - 5px);\n    padding: 0;\n    border: 2px solid var(--wire-col);\n    background: var(--box-col);\n}\n.gate_control.classical{\n    background: var(--c-wire-col);\n    border-color: var(--c-wire-col);\n}\n.control_index{\n    position: absolute;\n    right: calc(50% - 1em);\n    top: calc(50% - 1.4em);\n    color: var(--c-wire-col);\n    font-size: 0.8em;\n}\n.control_index.measure{\n    right: calc(50% - 1.2em);\n    top: calc(50% - 1.8em);\n    color: var(--index-col);\n}\n.gate_x {\n    top: -10px;\n    left: -6px;\n    border-radius: 50%;\n    border: 1px solid var(--wire-col);\n    width: 20px;\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%270%200%2064%2064%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27currentcolor%27%3E%0A%20%20%3Cpath%20d%3D%27M36%2064%20L36%2036%20L64%2036%20L64%2028%20L36%2028%20L36%200%20L28%200%20L28%2028%20L0%2028%20L0%2036%20L28%2036%20L28%2064%27%20/%3E%0A%3C/svg%3E\n) center;\n    background-color: var(--box-col);\n    background-size: cover;\n}\n.gate_reset{\n    margin: 11px 10px;\n    padding: 0 0 0 10px;\n    border: none !important;\n    border-left: 2px solid var(--wire-col) !important;\n    background: transparent;\n}\n.gate_reset_spider{\n    width: calc(var(--box-height) - 24px);\n    height: calc(var(--box-height) - 24px);\n    background: var(--box-col);\n    border: 2px solid var(--wire-col);\n    border-radius: 50%;\n    font-size: 0.75em;\n}\n\n/* Add wire sections coming in and out of the gate */\n.gate_in:before, .gate_in:after{\n    content: '';\n    position: absolute;\n    display: block;\n    top: calc(50% - 1px);\n    border: 1px solid var(--wire-col);\n    width: 9px;\n    height: 0;\n    background: var(--wire-col);\n    box-sizing: content-box;\n}\n.classical.gate_in:before,\n.classical.gate_in:after{\n    border-color: var(--c-wire-col);\n}\n\n.gate_in:before{\n    left: -12px;\n}\n.gate_out:after{\n    right: -12px;\n}\n.gate_top.gate_in:before, .gate_top.gate_out:after{\n    top:calc(50% - 6.5px)\n}\n.gate_bottom.gate_in:before, .gate_bottom.gate_out:after{\n    top:calc(50% + 4.5px)\n}\n\n\n.link-bottom, .link-top {\n    height: var(--box-height);\n    width: 0;\n    border: 1px solid var(--wire-col);\n    background: var(--wire-col);\n    position: absolute;\n    display: block;\n    left: calc(50% - 1px);\n    box-sizing: content-box;\n}\n.link-top{\n    top: calc(0px - var(--box-height)/2);\n}\n.link-bottom{\n    top: calc(var(--box-height)/2)\n}\n.half-link {\n    height: calc(var(--box-height) - 9px);\n}\n.half-link.link-bottom{\n    top: calc(var(--box-height)/2 + 11px)\n}\n.half-link.link-top{\n    top: calc(-2px - var(--box-height)/2);\n}\n.link-bottom.measurement{\n    width: 3px;\n    left: calc(50% - 0.5px);\n    border: none;\n    background: var(--c-wire-col);\n    height: calc(var(--box-height) + 2px);\n    z-index: 1;\n}\n\n\n\n/* tool tips */\n.tool-tip-container{\n    margin: calc(0px - var(--box-height)) auto 0;\n    padding-top: var(--box-height);\n    position: relative;\n    bottom: 0;\n    left: 0;\n    right: 0;\n    height: 0;\n    z-index: 4;\n    width: fit-content;\n    overflow: hidden;\n}\n.tool-tip-container.no-js{\n    overflow: visible;\n}\n.tool-tip-container.no-js:hover{\n    z-index: 10;\n}\n.nested > .tool-tip-container{\n    position: absolute;\n    bottom: -10px;\n}\n.tool-tip{\n    visibility: hidden;\n    opacity: 0;\n    -webkit-transition: visibility 0.2s, opacity 0.2s;\n    -moz-transition: visibility 0.2s, opacity 0.2s;\n    transition: visibility 0.2s, opacity 0.2s;\n    max-width: 250px;\n}\n.tool-tip-container.no-js:hover > .tool-tip{\n    visibility: visible;\n    opacity: 1;\n}\n.tool-tip-content{\n    background: var(--main-bg);\n    margin: 0 auto;\n    width: -moz-fit-content;\n    width: fit-content;\n    max-width: 100%;\n}\n.no-js > .tool-tip > .tool-tip-content{\n    height: auto;\n    padding: 20px;\n    margin: 0 auto;\n}\n.tool-tip-container.no-js:hover > .tool-tip > .tool-tip-content,\n.no-js > tool-tip > .tool-tip-content:hover{\n    box-shadow: 0 -5px 20px 5px var(--faint-col-overlay);\n}\n.tool-tip:after{\n    content: \" \";\n    position: absolute;\n    bottom: 0;\n    left: 50%;\n    margin-left: -5px;\n    border-width: 5px;\n    border-style: solid;\n    border-color: transparent transparent var(--main-bg) transparent;\n}\n.tool-tip .complex-number{\n    padding: 4px;\n}\n.tool-tip-content > .gate_container.nested{\n    width: 100%;\n    min-width: unset;\n}\n.nested-label-layer.as-height{\n    padding: 0;\n}\n.tool-tip-content > .gate_container.nested > .nested-circuit-container,\n.circuit-preview.condensed > .nested-circuit-container{\n    background: transparent;\n    border: none;\n    width: 100%;\n    min-width: unset;\n    max-width: unset;\n}\n\n/* Tool-tip modal */\n.circuit-grid{\n    display: flex;\n    flex-direction: row-reverse;\n    align-items: stretch;\n    align-content: stretch;\n}\n.circuit-grid-circuit{\n    flex: 1 1 auto;\n    margin-top: 30px;\n    overflow: auto;\n    max-height: inherit;\n}\n\n\n\n\n/*  FOR DISPLAYING CHARTS  */\ntable{\n    border-collapse: collapse;\n}\n.table-container{\n    margin: auto;\n}\n.bar-chart-container{\n    min-width: 300px;\n    width: 60%;\n}\n.square-chart-container{\n    width: auto;\n    min-width: 0;\n    overflow: hidden;\n}\n\n/* Make sure we can see the rightmost border */\n.square-chart-container tbody{\n    position: relative;\n    left: -1px;\n    display: block;\n}\nthead > tr{\n    background: transparent !important;\n}\ntr:hover, tr {\n    background: initial !important;\n}\n\ntd, th{\n    padding: 10px;\n    position: relative;\n}\n\n/* COMPLEX NUMBERS AND MATRICES */\n.complex-number{\n    padding: 10px;\n}\n.mid-number{\n    padding: 5px;\n    font-size: 0.75em;\n}\n.large-number{\n    padding: 2px;\n    font-size: 0.75em;\n}\n.matrix_container{\n    border: 2px solid var(--mid-col);\n    border-top: 0;\n    border-bottom: 0;\n    margin: auto !important;\n    border-collapse: collapse;\n    text-align: center;\n}\n\n\n/* LIST RESULTS NICELY */\n.list{\n    flex-wrap: wrap;\n    justify-content: space-evenly;\n    align-items: stretch;\n    padding: 0;\n}\n.list > *{\n    margin: 10px;\n}\n.list > .row-sub-heading{\n    margin: 10px 0;\n}\n</style>\n\n</head>\n<body>\n    <div class=\"row circuit-grid circuit__preview-body\">\n        <div class=\"circuit-grid-circuit thin-scrollbar\"  style=\"\">\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n    <div class=\"circuit-preview circuit_variables condensed\">\n\n\n            <div class=\"nested-label-layer as-height\">\n\n                    <div class=\"wire-label\"></div>\n\n                    <div class=\"wire-label\"></div>\n\n                    <div class=\"wire-label\"></div>\n\n                    <div class=\"wire-label\"></div>\n\n                    <div class=\"wire-label\"></div>\n\n            </div>\n            <div class=\"nested-circuit-container\"><div class=\"circuit-inner-scroll\">\n\n        <div class=\"circuit-container nested\">\n            <div class=\"circuit-layer qubits\">\n\n            <div class=\"qubit\">node[0]</div>\n\n            <div class=\"qubit\">node[1]</div>\n\n            <div class=\"qubit\">node[2]</div>\n\n\n            <div class=\"qubit bit\">c[0]</div>\n\n            <div class=\"qubit bit\">c[1]</div>\n\n    </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container x\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">SX</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container z\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rz(0.5)</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container x\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">SX</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n                <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n                <div class=\"gate gate_control z\"></div>\n\n            </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container x\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">X</span>\n                </div>\n\n\n\n                <div class=\"link-top\"></div>\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n        <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection gate_measure\"></div>\n\n            <div class=\"control_index measure z\">z</div>\n\n    </div>\n\n            <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n\n    </div>\n\n        <div class=\"gate_container\">\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n        <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection gate_measure\"></div>\n\n            <div class=\"control_index measure z\">z</div>\n\n    </div>\n\n            <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n\n    </div>\n\n        <div class=\"gate_container\">\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n            <div class=\"circuit-layer qubits\">\n\n            <div class=\"qubit\">node[0]</div>\n\n            <div class=\"qubit\">node[1]</div>\n\n            <div class=\"qubit\">node[2]</div>\n\n\n            <div class=\"qubit bit\">c[0]</div>\n\n            <div class=\"qubit bit\">c[1]</div>\n\n    </div>\n        </div>\n\n            </div></div>\n\n    </div>\n\n\n\n\n        </div>\n    </div>\n</body>\n</html>\n\n\nMake a measurement with the given backend.\n\n\n```python\n# Execute quantum circuit.\nhandle = backend.process_circuit(bell_circuit, n_shots=1000)\nresult = backend.get_result(handle)\n\n# Check the shot counts.\nprint(result.get_counts())\n```\n\n    Counter({(0, 0): 487, (1, 1): 476, (0, 1): 20, (1, 0): 17})\n\n\n### Leaving the Walled Garden via VQE\n\nIt is widely believed that a variational (hybrid quantum-classical) algorithm\nis a promising approach to attain quantum advantage with NISQ devices.\nIn the variational algorithm,\nheavy tasks such as expectation value evaluation are performed by quantum computers,\nwhile the other tasks are handled by classical computers to drive a feedback loop.\n\nVariational quantum eigensolver (VQE) is one of the most frequently used\nvariational algorithms.\nIn the VQE algorithm,\nwe consider a cost function $E(\\boldsymbol{\\theta})$\ndepending on a set of\nparameters $\\boldsymbol{\\theta}$\ndescribing an associated trial wavefunction $|\\Psi(\\boldsymbol{\\theta})\\rangle$,\nwhich is expressed as\n\n$$\n    E(\\boldsymbol{\\theta})\n    =\n    \\langle\n        \\Psi(\\boldsymbol{\\theta}) | \\hat{H} | \\Psi(\\boldsymbol{\\theta})\n    \\rangle\n$$\n\nwhere $\\hat{H}$ is a Hamiltonian describing the system.\nThe trial wavefunction $|\\Psi(\\boldsymbol{\\theta})\\rangle$ is actually implemented\ninto the quantum computer in the following form\n\n$$\n    |\\Psi(\\boldsymbol{\\theta})\\rangle\n    =\n    \\hat{U}(\\boldsymbol{\\theta}) |\\Psi_{0}\\rangle\n$$\n\nwhere $|\\Psi_{0}\\rangle$ corresponds to an initial state that should be\neasily prepared.\nThe unitary operator $\\hat{U}(\\boldsymbol{\\theta})$ is implemented as\na parameterized quantum circuit,\nor ansatz.\nThe Hamiltonian $\\hat{H}$ is usually transformed into a series of $k$-local operators such as Pauli strings (tensor product of qubit local Pauli operator)\n$\\{\\hat{P}_{a}\\}$\n\n$$\n    \\hat{H} = \\sum_{a}h_{a}\\hat{P}_{a}\n$$\n\nwhere $\\{h_{a}\\}$ is a set of coefficients, each of which is complex valued in general.\nThus by evaluating $\\langle \\Psi(\\boldsymbol{\\theta})|\\hat{P}_{a}|\\Psi(\\boldsymbol{\\theta})\\rangle$\nfor all $a$, \n$E(\\boldsymbol{\\theta})$ can be evaluated.\n\nIn summary, to perform VQE algorithm, we need the following quantities:\n\n* $\\hat{H}=\\sum_{a}h_{a}\\hat{P}_{a}$: Hamiltonian (qubit Pauli operator)\n* $|\\Psi(\\boldsymbol{\\theta})\\rangle = \\hat{U}(\\boldsymbol{\\theta}) |\\Psi_{0}\\rangle$: Ansatz (parametrized quantum circuit)\n\n#### Hamiltonian operator as a `QubitPauliOperator`\n\nIn the examples below, we use Hamiltonian coming from quantum chemistry problems.\nThe qubit Hamiltonian was preliminary calculatied with \n[EUMEN](https://cqcl.github.io/eumen/build/html/index.html), a proprietary quantum computational chemistry packaged developed by Cambridge Quantum.\nThe hard-coded qubit Pauli operator below is generated from a fermionic Hamiltonian in the Hartree-Fock molecular orbital (MO) basis using Jordan-Wigner transformation.\nHere the MOs are calculated for a hydrogen molecule (the H-H distance is set to 0.735 \u00c5) with STO-3G basis set.\nQubit tapering by exploiting symmetry (alpha- and beta-spin particle number conservation) is applied to obtain a two qubit model system.\n\n\n```python\n# Prepare a qubit Hamiltonian in the direct (second-quantized) mapping.\nfrom pytket.circuit import Qubit\nfrom pytket.pauli import Pauli, QubitPauliString\nfrom pytket.utils import QubitPauliOperator\n\nn_qubits = 2\n\nqubits = [Qubit(i) for i in range(n_qubits)]\nqpo_identity = -0.3324042513238792\nqpo_dict = {\n    QubitPauliString([qubits[0]], [Pauli.Z]): -0.39793742484318023,\n    QubitPauliString([qubits[1]], [Pauli.Z]): -0.39793742484318023,                                                 \n    QubitPauliString([qubits[0], qubits[1]], [Pauli.Z, Pauli.Z]): 0.011280104256235296,\n    QubitPauliString([qubits[0], qubits[1]], [Pauli.Y, Pauli.Y]): -0.18093119978423144,\n}\noperator = QubitPauliOperator(qpo_dict)\nfor k, v in operator._dict.items():\n    print(f'{v:8.4f} {k}')\n```\n\n     -0.3979 (Zq[0])\n     -0.3979 (Zq[1])\n      0.0113 (Zq[0], Zq[1])\n     -0.1809 (Yq[0], Yq[1])\n\n\n\n```python\n# Some reference energy values\nhf_energy = -1.116998996754\ncc_energy = -1.137306035759\n```\n\n####  Ansatz as a symbolic `Circuit` and circuit optimization with TKET\n\nIn some chemistry-motivated ansatzes such as unitary coupled cluster (UCC),\na Pauli exponential $e^{i\\theta_{m}\\hat{P}_{m}}$ is a building block as\n$$\n    \\hat{U}(\\boldsymbol{\\theta}) = \\prod_{m}e^{i\\theta_{m}\\hat{P}_{m}}\n$$\nThere is a general recipe to efficiently implement a Pauli exponential to a circuit, which is called Pauli gadget.\n`pytket` provides an easy way to construct a pauli gadget as shown below:\n\n\n```python\nfrom pytket.circuit import PauliExpBox, fresh_symbol, OpType\nfrom pytket.passes import DecomposeBoxes\n\nbox = PauliExpBox([Pauli.I, Pauli.Z, Pauli.X, Pauli.Y], fresh_symbol('tm'))\ncirc = Circuit(4)\ncirc.add_pauliexpbox(box, circ.qubits)\nDecomposeBoxes().apply(circ)\nrender_circuit_jupyter(circ)\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n\n<style>\nbody, .circuit__preview-body {\n    font-family: \"roboto\", system-ui, sans-serif;\n    --accent-col: green;\n    --accent-col-fill: darkseagreen;\n    --accent-col-alt: #aca;\n    --accent-col-emph: limegreen;\n    --accent-col-overlay: rgba(130,255,140,0.2);\n    --accent-col-outline: rgba(30, 250, 30,0.2);\n    --main-col: black;\n    --mid-col: #bbb;\n    --faint-col: #eee;\n    --faint-col-overlay: rgba(0, 0, 0, 0.05);\n    --main-bg: white;\n}\n\n.row{\n    display: flex;\n    flex-wrap: wrap;\n    align-items: center;\n    padding: 10px;\n    border-bottom: 1px solid var(--faint-col);\n    position: relative;\n}\n.row-item{\n    flex-grow: 1\n}\n.row-item-l{\n    text-align: left;\n}\n.row-item-r{\n    text-align: right;\n}\n.row-sub-heading{\n    border-color: var(--accent-col-emph);\n}\n\n/* FOR DISPLAYING CIRCUITS */\n/* Main preview container */\n.circuit-preview {\n    width: 100%;\n    height: 100%;\n    text-align: center;\n    color: black;\n}\n.circuit_variables {\n    /* Define some variables */\n    --box-height: 40px;\n    --wire-col: black;\n    --c-wire-col: #bbb;\n    --box-col: #ccc;\n    --box-col-overlay: rgba(0,0,0,0.05);\n    --c-box-col: #ddd;\n    --index-col: #888;\n}\n.circuit-preview.condensed{\n    display: flex;\n    flex-wrap: nowrap;\n}\n\n/* Box colours */\n.h {\n    --box-col: #ffee00;\n    --box-col-overlay: rgba(255, 255, 0, 0.2);\n    --c-box-col: #ffee88;\n    --index-col: #ffcc00;\n}\n.x {\n    --box-col: #ff8888;\n    --box-col-overlay: rgba(255, 0, 0, 0.2);\n    --c-box-col: #e8a6a6;\n    --index-col: red;\n}\n.y {\n    --box-col: #6699ff;\n    --box-col-overlay: rgba(0, 0, 255, 0.2);\n    --c-box-col: #86c6f6;\n    --index-col: blue;\n}\n.z {\n    --box-col: #ccffcc;\n    --box-col-overlay: rgba(0, 255, 0, 0.2);\n    --c-box-col: #e2ffe2;\n    --index-col: green;\n}\n\n.circuit-container{\n    max-width: 100%;\n    display: flex;\n    flex-flow: row wrap;\n    justify-content: center;\n    align-content: flex-start;\n    margin: auto;\n    width: -moz-fit-content;\n    width: fit-content;\n    background: rgba(255, 255, 255, 1);\n}\n.circuit-preview.condensed > .circuit-container{\n    flex-wrap: nowrap;\n    min-width: fit-content;\n}\n.circuit-container.nested{\n    position: relative;\n    flex-wrap: nowrap;\n    margin: -2px 0;\n}\n.nested-circuit-container{\n    display: flex;\n    overflow: auto;\n    max-width: 400px;\n    background: var(--box-col-overlay);\n    border: 1px solid var(--box-col);\n}\n.nested-circuit-container::-webkit-scrollbar {\n    height: 0;\n    width: 0;\n}\n.circuit-inner-scroll{\n    overflow: visible;\n    width: -moz-fit-content;\n    width: fit-content;\n    margin: auto;\n    margin-top: 2px;\n}\n.circuit-end{\n    width: 2px;\n    height: auto;\n    border: 2px solid var(--wire-col);\n    margin: calc(var(--box-height)/2) 0 calc(var(--box-height)/2 + 20px);\n}\n.circuit-layer{\n    min-width: 40px;\n    width: max-content;\n    display: flex;\n    flex-flow: column nowrap;\n    flex-grow: 1;\n    justify-content: space-between;\n    align-items: stretch;\n    margin-bottom: 20px;\n}\n.circuit-container:not(.nested) > .circuit-layer:nth-child(2),\n.circuit-container:not(.nested) > .circuit-layer:nth-last-child(2),\n.circuit-container.nested > .circuit-layer:nth-child(2),\n.circuit-container.nested > .circuit-layer:nth-last-child(2),\n.gate_container.nested > .circuit-layer:first-child,\n.gate_container.nested > .circuit-layer:last-child{\n    min-width: 10px;\n}\n.nested .circuit-layer{\n    margin-bottom: 0;\n}\n.flex_wire{\n    flex-grow: 1;\n}\n/* Display qubit names at start of circuit */\n.circuit-layer.qubits{\n    flex-grow: 0;\n    color: var(--wire-col);\n}\n.qubit{\n    height: calc(var(--box-height) - 20px);\n    padding: 10px;\n    text-align: center;\n    font-family: monospace;\n    box-sizing: content-box;\n}\n.wire{\n    height: 0;\n    border: 1px solid var(--wire-col);\n    background: var(--wire-col);\n    margin: calc(var(--box-height)/2) 0;\n}\n.wire.classical{\n    border-color: var(--c-wire-col) !important;\n    background: var(--c-wire-col) !important;\n}\n.wire.transparent-wire{\n    border-color: transparent;\n    background: transparent;\n}\n\n/* Generic base for our gates */\n.gate_container{\n    position: relative;\n    min-width: -moz-fit-content;\n    min-width: fit-content;\n}\n.gate_container.nested{\n    display: flex;\n    flex-wrap: nowrap;\n}\n.gate_container.nested:after{\n    display: flex;\n    flex-wrap: nowrap;\n}\n.gate_container .classical{\n    background: var(--c-box-col);\n    border-color: var(--index-col);\n}\n.gate{\n    position: relative;\n    height: calc(var(--box-height) - 16px);\n    margin: 0 9px;\n    padding: 9px 5px;\n    border: 1px solid var(--index-col);\n    border-bottom: none;\n    border-top: none;\n    text-align: left;\n    background: var(--box-col);\n    display: flex;\n    box-sizing: content-box;\n    z-index: 1;\n}\n.wire-label{\n    color: var(--index-col);\n    width: -moz-fit-content;\n    width: fit-content;\n    height: calc(var(--box-height) - 18px);\n    padding-right: 5px;\n}\n.gate_top > .wire-label,\n.gate_bottom > .wire-label {\n    padding-top: 0;\n}\n.nested-label-layer{\n    background: var(--box-col);\n    padding: 0 5px;\n}\n.nested-label-layer .wire-label{\n    padding: 10px 0;\n}\n\n/* Multi-qubit gates */\n.gate_bottom{\n    height: calc(var(--box-height) - 18px);\n    margin-bottom: 10px;\n    padding-bottom: 0;\n    border-bottom: 1px solid var(--index-col);\n}\n.gate_top{\n    height: calc(var(--box-height) - 18px);\n    margin-top: 10px;\n    padding-top: 0;\n    border-top: 1px solid var(--index-col);\n}\n.gate_name{\n    text-align: center;\n    flex-grow: 1;\n}\n/* Single qubit gate*/\n.gate_box{\n    height: calc(var(--box-height) - 20px);\n    margin: 10px;\n    padding: 0 5px;\n    border: 1px solid var(--index-col);\n    text-align: center;\n}\n\n/* Special gates */\n.gate_connection {\n    position: absolute;\n    top: -3px;\n    left: -1px;\n    border: none;\n    margin: calc(var(--box-height)/2) calc(50% - 5px);\n    padding: 0;\n}\n.gate_swap {\n    height: 20px;\n    width: 20px;\n    margin: calc(var(--box-height)/2 - 6px) calc(50% - 9px);\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%270%200%2064%2064%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27currentcolor%27%3E%0A%20%20%3Cpath%20d%3D%27M60%200%20L32%2028%20L4%200%20L0%204%20L28%2032%20L0%2060%20L4%2064%20L32%2036%20L60%2064%20L64%2060%20L36%2032%20L64%204%27%20/%3E%0A%3C/svg%3E\n) center;\n    background-size: cover;\n}\n.gate_measure {\n    height: 20px;\n    width: 25px;\n    margin: calc(var(--box-height)/2 - 10px) calc(50% - 11px);\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%27-10%20-10%2084%2084%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27white%27%0A%20%20stroke%3D%22black%22%0A%20%20stroke-width%3D%224px%22%0A%3E%0A%20%20%3Cpath%20d%3D%27M63%2C63%20C63%2C32%2048%2C16%2032%2C16%20C16%2C16%201%2C32%201%2C63%20L63%2C63%27%20/%3E%0A%20%20%3Cpath%20d%3D%22M32%2C63%20L56%2C16%22%20/%3E%0A%3C/svg%3E\n) center;\n    background-size: cover;\n}\n.gate_control {\n    position: absolute;\n    top: 0;\n    left: 0;\n    border-radius: 50%;\n    width: 6px;\n    height: 6px;\n    margin: calc(var(--box-height)/2 - 3px) calc(50% - 5px);\n    padding: 0;\n    border: 2px solid var(--wire-col);\n    background: var(--box-col);\n}\n.gate_control.classical{\n    background: var(--c-wire-col);\n    border-color: var(--c-wire-col);\n}\n.control_index{\n    position: absolute;\n    right: calc(50% - 1em);\n    top: calc(50% - 1.4em);\n    color: var(--c-wire-col);\n    font-size: 0.8em;\n}\n.control_index.measure{\n    right: calc(50% - 1.2em);\n    top: calc(50% - 1.8em);\n    color: var(--index-col);\n}\n.gate_x {\n    top: -10px;\n    left: -6px;\n    border-radius: 50%;\n    border: 1px solid var(--wire-col);\n    width: 20px;\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%270%200%2064%2064%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27currentcolor%27%3E%0A%20%20%3Cpath%20d%3D%27M36%2064%20L36%2036%20L64%2036%20L64%2028%20L36%2028%20L36%200%20L28%200%20L28%2028%20L0%2028%20L0%2036%20L28%2036%20L28%2064%27%20/%3E%0A%3C/svg%3E\n) center;\n    background-color: var(--box-col);\n    background-size: cover;\n}\n.gate_reset{\n    margin: 11px 10px;\n    padding: 0 0 0 10px;\n    border: none !important;\n    border-left: 2px solid var(--wire-col) !important;\n    background: transparent;\n}\n.gate_reset_spider{\n    width: calc(var(--box-height) - 24px);\n    height: calc(var(--box-height) - 24px);\n    background: var(--box-col);\n    border: 2px solid var(--wire-col);\n    border-radius: 50%;\n    font-size: 0.75em;\n}\n\n/* Add wire sections coming in and out of the gate */\n.gate_in:before, .gate_in:after{\n    content: '';\n    position: absolute;\n    display: block;\n    top: calc(50% - 1px);\n    border: 1px solid var(--wire-col);\n    width: 9px;\n    height: 0;\n    background: var(--wire-col);\n    box-sizing: content-box;\n}\n.classical.gate_in:before,\n.classical.gate_in:after{\n    border-color: var(--c-wire-col);\n}\n\n.gate_in:before{\n    left: -12px;\n}\n.gate_out:after{\n    right: -12px;\n}\n.gate_top.gate_in:before, .gate_top.gate_out:after{\n    top:calc(50% - 6.5px)\n}\n.gate_bottom.gate_in:before, .gate_bottom.gate_out:after{\n    top:calc(50% + 4.5px)\n}\n\n\n.link-bottom, .link-top {\n    height: var(--box-height);\n    width: 0;\n    border: 1px solid var(--wire-col);\n    background: var(--wire-col);\n    position: absolute;\n    display: block;\n    left: calc(50% - 1px);\n    box-sizing: content-box;\n}\n.link-top{\n    top: calc(0px - var(--box-height)/2);\n}\n.link-bottom{\n    top: calc(var(--box-height)/2)\n}\n.half-link {\n    height: calc(var(--box-height) - 9px);\n}\n.half-link.link-bottom{\n    top: calc(var(--box-height)/2 + 11px)\n}\n.half-link.link-top{\n    top: calc(-2px - var(--box-height)/2);\n}\n.link-bottom.measurement{\n    width: 3px;\n    left: calc(50% - 0.5px);\n    border: none;\n    background: var(--c-wire-col);\n    height: calc(var(--box-height) + 2px);\n    z-index: 1;\n}\n\n\n\n/* tool tips */\n.tool-tip-container{\n    margin: calc(0px - var(--box-height)) auto 0;\n    padding-top: var(--box-height);\n    position: relative;\n    bottom: 0;\n    left: 0;\n    right: 0;\n    height: 0;\n    z-index: 4;\n    width: fit-content;\n    overflow: hidden;\n}\n.tool-tip-container.no-js{\n    overflow: visible;\n}\n.tool-tip-container.no-js:hover{\n    z-index: 10;\n}\n.nested > .tool-tip-container{\n    position: absolute;\n    bottom: -10px;\n}\n.tool-tip{\n    visibility: hidden;\n    opacity: 0;\n    -webkit-transition: visibility 0.2s, opacity 0.2s;\n    -moz-transition: visibility 0.2s, opacity 0.2s;\n    transition: visibility 0.2s, opacity 0.2s;\n    max-width: 250px;\n}\n.tool-tip-container.no-js:hover > .tool-tip{\n    visibility: visible;\n    opacity: 1;\n}\n.tool-tip-content{\n    background: var(--main-bg);\n    margin: 0 auto;\n    width: -moz-fit-content;\n    width: fit-content;\n    max-width: 100%;\n}\n.no-js > .tool-tip > .tool-tip-content{\n    height: auto;\n    padding: 20px;\n    margin: 0 auto;\n}\n.tool-tip-container.no-js:hover > .tool-tip > .tool-tip-content,\n.no-js > tool-tip > .tool-tip-content:hover{\n    box-shadow: 0 -5px 20px 5px var(--faint-col-overlay);\n}\n.tool-tip:after{\n    content: \" \";\n    position: absolute;\n    bottom: 0;\n    left: 50%;\n    margin-left: -5px;\n    border-width: 5px;\n    border-style: solid;\n    border-color: transparent transparent var(--main-bg) transparent;\n}\n.tool-tip .complex-number{\n    padding: 4px;\n}\n.tool-tip-content > .gate_container.nested{\n    width: 100%;\n    min-width: unset;\n}\n.nested-label-layer.as-height{\n    padding: 0;\n}\n.tool-tip-content > .gate_container.nested > .nested-circuit-container,\n.circuit-preview.condensed > .nested-circuit-container{\n    background: transparent;\n    border: none;\n    width: 100%;\n    min-width: unset;\n    max-width: unset;\n}\n\n/* Tool-tip modal */\n.circuit-grid{\n    display: flex;\n    flex-direction: row-reverse;\n    align-items: stretch;\n    align-content: stretch;\n}\n.circuit-grid-circuit{\n    flex: 1 1 auto;\n    margin-top: 30px;\n    overflow: auto;\n    max-height: inherit;\n}\n\n\n\n\n/*  FOR DISPLAYING CHARTS  */\ntable{\n    border-collapse: collapse;\n}\n.table-container{\n    margin: auto;\n}\n.bar-chart-container{\n    min-width: 300px;\n    width: 60%;\n}\n.square-chart-container{\n    width: auto;\n    min-width: 0;\n    overflow: hidden;\n}\n\n/* Make sure we can see the rightmost border */\n.square-chart-container tbody{\n    position: relative;\n    left: -1px;\n    display: block;\n}\nthead > tr{\n    background: transparent !important;\n}\ntr:hover, tr {\n    background: initial !important;\n}\n\ntd, th{\n    padding: 10px;\n    position: relative;\n}\n\n/* COMPLEX NUMBERS AND MATRICES */\n.complex-number{\n    padding: 10px;\n}\n.mid-number{\n    padding: 5px;\n    font-size: 0.75em;\n}\n.large-number{\n    padding: 2px;\n    font-size: 0.75em;\n}\n.matrix_container{\n    border: 2px solid var(--mid-col);\n    border-top: 0;\n    border-bottom: 0;\n    margin: auto !important;\n    border-collapse: collapse;\n    text-align: center;\n}\n\n\n/* LIST RESULTS NICELY */\n.list{\n    flex-wrap: wrap;\n    justify-content: space-evenly;\n    align-items: stretch;\n    padding: 0;\n}\n.list > *{\n    margin: 10px;\n}\n.list > .row-sub-heading{\n    margin: 10px 0;\n}\n</style>\n\n</head>\n<body>\n    <div class=\"row circuit-grid circuit__preview-body\">\n        <div class=\"circuit-grid-circuit thin-scrollbar\"  style=\"\">\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n    <div class=\"circuit-preview circuit_variables condensed\">\n\n\n            <div class=\"nested-label-layer as-height\">\n\n                    <div class=\"wire-label\"></div>\n\n                    <div class=\"wire-label\"></div>\n\n                    <div class=\"wire-label\"></div>\n\n                    <div class=\"wire-label\"></div>\n\n            </div>\n            <div class=\"nested-circuit-container\"><div class=\"circuit-inner-scroll\">\n\n        <div class=\"circuit-container nested\">\n            <div class=\"circuit-layer qubits\">\n\n            <div class=\"qubit\">q[0]</div>\n\n            <div class=\"qubit\">q[1]</div>\n\n            <div class=\"qubit\">q[2]</div>\n\n            <div class=\"qubit\">q[3]</div>\n\n\n    </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container h\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container x\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">V</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container x\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">X</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n                <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n                <div class=\"gate gate_control z\"></div>\n\n                    <div class=\"link-top\"></div>\n\n            </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container x\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">X</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n                <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n                <div class=\"gate gate_control z\"></div>\n\n                    <div class=\"link-top\"></div>\n\n            </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container z\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rz(tm)</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container x\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">X</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n                <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n                <div class=\"gate gate_control z\"></div>\n\n                    <div class=\"link-top\"></div>\n\n            </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container x\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">X</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n                <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n                <div class=\"gate gate_control z\"></div>\n\n                    <div class=\"link-top\"></div>\n\n            </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container h\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container x\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Vdg</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n            <div class=\"circuit-layer qubits\">\n\n            <div class=\"qubit\">q[0]</div>\n\n            <div class=\"qubit\">q[1]</div>\n\n            <div class=\"qubit\">q[2]</div>\n\n            <div class=\"qubit\">q[3]</div>\n\n\n    </div>\n        </div>\n\n            </div></div>\n\n    </div>\n\n\n\n\n        </div>\n    </div>\n</body>\n</html>\n\n\nIn NISQ era, it is important to reduce the circuit depth.\n`pytket` has various compilation passes to perform circuit optimization.\nIn the following example we optimize a large pauli gadgets by using `pytket.PauliSimp`. \n\n\n```python\nimport numpy as np\n\ndef get_random_pauli_gadgets(n_qubits, n_pauli_gadgets, max_entangle):\n    \"\"\" \"\"\"\n    paulis = [Pauli.I, Pauli.X, Pauli.Y, Pauli.Z]\n    circ = Circuit(n_qubits)\n    for i in range(n_pauli_gadgets):\n        ls_paulis = [np.random.choice(paulis) for k in range(max_entangle)]\n        if ls_paulis.count(Pauli.Y) % 2 == 0:\n            continue\n        if len(ls_paulis) - ls_paulis.count(Pauli.I) <= 1:\n            continue\n        # print(ls_paulis)\n        qubits = np.random.choice(\n            [i for i in range(n_qubits)], size=max_entangle, replace=False\n        )\n        box = PauliExpBox(ls_paulis, fresh_symbol('x'))\n        circ.add_pauliexpbox(box, sorted(qubits))\n    DecomposeBoxes().apply(circ)\n    return circ\n\ncirc = get_random_pauli_gadgets(\n    n_qubits=12, n_pauli_gadgets=500, max_entangle=8\n)\nprint('Circuit depth:', circ.depth())\nprint('CX depth:     ', circ.depth_by_type(OpType.CX))\n# render_circuit_jupyter(circ)\n```\n\n    Circuit depth: 3017\n    CX depth:      2417\n\n\nNow apply the compiler pass to optimize the circuit.\n\n\n```python\n# Circuit optimization by using compiler passes.\nfrom pytket.passes import PauliSimp\ncircx = circ.copy()\nPauliSimp().apply(circx)\nprint('Circuit depth:', circx.depth())\nprint('CX depth:     ', circx.depth_by_type(OpType.CX))\n```\n\n    Circuit depth: 2364\n    CX depth:      1739\n\n\n#### Simple 2 qubit 1 parameter ansatz for demonstration\n\nFor the simple demo, we use the ansatz given as\n\n$$\n    \\Psi(\\theta)\n    =\n    \\hat{U}(\\theta)|\\Psi_{0}\\rangle\n    =\n    e^{i\\theta \\hat{Y}_{0}\\hat{X}_{1}}|00\\rangle\n$$\n\nThis ansatz is equivalent to the configuration interaction doubles (CID) expressed as\n\n$$\n    \\Psi(\\theta) = \\cos(\\theta)|1100\\rangle + \\sin(\\theta)|0011\\rangle\n$$\n\nin the original computational basis in the Jordan-Wigner mapping.\n\n\n```python\nfrom pytket.circuit import PauliExpBox, fresh_symbol\nfrom pytket.passes import DecomposeBoxes\nfrom sympy import pi\n\nn_qubits = 2\nansatz = Circuit(n_qubits)\nt = fresh_symbol('t')\nbox = PauliExpBox([Pauli.Y, Pauli.X], -1 * (-2 * t / pi))\nansatz.add_pauliexpbox(box, ansatz.qubits)\nDecomposeBoxes().apply(ansatz)\nansatz0 = ansatz.copy()\nrender_circuit_jupyter(ansatz)\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n\n<style>\nbody, .circuit__preview-body {\n    font-family: \"roboto\", system-ui, sans-serif;\n    --accent-col: green;\n    --accent-col-fill: darkseagreen;\n    --accent-col-alt: #aca;\n    --accent-col-emph: limegreen;\n    --accent-col-overlay: rgba(130,255,140,0.2);\n    --accent-col-outline: rgba(30, 250, 30,0.2);\n    --main-col: black;\n    --mid-col: #bbb;\n    --faint-col: #eee;\n    --faint-col-overlay: rgba(0, 0, 0, 0.05);\n    --main-bg: white;\n}\n\n.row{\n    display: flex;\n    flex-wrap: wrap;\n    align-items: center;\n    padding: 10px;\n    border-bottom: 1px solid var(--faint-col);\n    position: relative;\n}\n.row-item{\n    flex-grow: 1\n}\n.row-item-l{\n    text-align: left;\n}\n.row-item-r{\n    text-align: right;\n}\n.row-sub-heading{\n    border-color: var(--accent-col-emph);\n}\n\n/* FOR DISPLAYING CIRCUITS */\n/* Main preview container */\n.circuit-preview {\n    width: 100%;\n    height: 100%;\n    text-align: center;\n    color: black;\n}\n.circuit_variables {\n    /* Define some variables */\n    --box-height: 40px;\n    --wire-col: black;\n    --c-wire-col: #bbb;\n    --box-col: #ccc;\n    --box-col-overlay: rgba(0,0,0,0.05);\n    --c-box-col: #ddd;\n    --index-col: #888;\n}\n.circuit-preview.condensed{\n    display: flex;\n    flex-wrap: nowrap;\n}\n\n/* Box colours */\n.h {\n    --box-col: #ffee00;\n    --box-col-overlay: rgba(255, 255, 0, 0.2);\n    --c-box-col: #ffee88;\n    --index-col: #ffcc00;\n}\n.x {\n    --box-col: #ff8888;\n    --box-col-overlay: rgba(255, 0, 0, 0.2);\n    --c-box-col: #e8a6a6;\n    --index-col: red;\n}\n.y {\n    --box-col: #6699ff;\n    --box-col-overlay: rgba(0, 0, 255, 0.2);\n    --c-box-col: #86c6f6;\n    --index-col: blue;\n}\n.z {\n    --box-col: #ccffcc;\n    --box-col-overlay: rgba(0, 255, 0, 0.2);\n    --c-box-col: #e2ffe2;\n    --index-col: green;\n}\n\n.circuit-container{\n    max-width: 100%;\n    display: flex;\n    flex-flow: row wrap;\n    justify-content: center;\n    align-content: flex-start;\n    margin: auto;\n    width: -moz-fit-content;\n    width: fit-content;\n    background: rgba(255, 255, 255, 1);\n}\n.circuit-preview.condensed > .circuit-container{\n    flex-wrap: nowrap;\n    min-width: fit-content;\n}\n.circuit-container.nested{\n    position: relative;\n    flex-wrap: nowrap;\n    margin: -2px 0;\n}\n.nested-circuit-container{\n    display: flex;\n    overflow: auto;\n    max-width: 400px;\n    background: var(--box-col-overlay);\n    border: 1px solid var(--box-col);\n}\n.nested-circuit-container::-webkit-scrollbar {\n    height: 0;\n    width: 0;\n}\n.circuit-inner-scroll{\n    overflow: visible;\n    width: -moz-fit-content;\n    width: fit-content;\n    margin: auto;\n    margin-top: 2px;\n}\n.circuit-end{\n    width: 2px;\n    height: auto;\n    border: 2px solid var(--wire-col);\n    margin: calc(var(--box-height)/2) 0 calc(var(--box-height)/2 + 20px);\n}\n.circuit-layer{\n    min-width: 40px;\n    width: max-content;\n    display: flex;\n    flex-flow: column nowrap;\n    flex-grow: 1;\n    justify-content: space-between;\n    align-items: stretch;\n    margin-bottom: 20px;\n}\n.circuit-container:not(.nested) > .circuit-layer:nth-child(2),\n.circuit-container:not(.nested) > .circuit-layer:nth-last-child(2),\n.circuit-container.nested > .circuit-layer:nth-child(2),\n.circuit-container.nested > .circuit-layer:nth-last-child(2),\n.gate_container.nested > .circuit-layer:first-child,\n.gate_container.nested > .circuit-layer:last-child{\n    min-width: 10px;\n}\n.nested .circuit-layer{\n    margin-bottom: 0;\n}\n.flex_wire{\n    flex-grow: 1;\n}\n/* Display qubit names at start of circuit */\n.circuit-layer.qubits{\n    flex-grow: 0;\n    color: var(--wire-col);\n}\n.qubit{\n    height: calc(var(--box-height) - 20px);\n    padding: 10px;\n    text-align: center;\n    font-family: monospace;\n    box-sizing: content-box;\n}\n.wire{\n    height: 0;\n    border: 1px solid var(--wire-col);\n    background: var(--wire-col);\n    margin: calc(var(--box-height)/2) 0;\n}\n.wire.classical{\n    border-color: var(--c-wire-col) !important;\n    background: var(--c-wire-col) !important;\n}\n.wire.transparent-wire{\n    border-color: transparent;\n    background: transparent;\n}\n\n/* Generic base for our gates */\n.gate_container{\n    position: relative;\n    min-width: -moz-fit-content;\n    min-width: fit-content;\n}\n.gate_container.nested{\n    display: flex;\n    flex-wrap: nowrap;\n}\n.gate_container.nested:after{\n    display: flex;\n    flex-wrap: nowrap;\n}\n.gate_container .classical{\n    background: var(--c-box-col);\n    border-color: var(--index-col);\n}\n.gate{\n    position: relative;\n    height: calc(var(--box-height) - 16px);\n    margin: 0 9px;\n    padding: 9px 5px;\n    border: 1px solid var(--index-col);\n    border-bottom: none;\n    border-top: none;\n    text-align: left;\n    background: var(--box-col);\n    display: flex;\n    box-sizing: content-box;\n    z-index: 1;\n}\n.wire-label{\n    color: var(--index-col);\n    width: -moz-fit-content;\n    width: fit-content;\n    height: calc(var(--box-height) - 18px);\n    padding-right: 5px;\n}\n.gate_top > .wire-label,\n.gate_bottom > .wire-label {\n    padding-top: 0;\n}\n.nested-label-layer{\n    background: var(--box-col);\n    padding: 0 5px;\n}\n.nested-label-layer .wire-label{\n    padding: 10px 0;\n}\n\n/* Multi-qubit gates */\n.gate_bottom{\n    height: calc(var(--box-height) - 18px);\n    margin-bottom: 10px;\n    padding-bottom: 0;\n    border-bottom: 1px solid var(--index-col);\n}\n.gate_top{\n    height: calc(var(--box-height) - 18px);\n    margin-top: 10px;\n    padding-top: 0;\n    border-top: 1px solid var(--index-col);\n}\n.gate_name{\n    text-align: center;\n    flex-grow: 1;\n}\n/* Single qubit gate*/\n.gate_box{\n    height: calc(var(--box-height) - 20px);\n    margin: 10px;\n    padding: 0 5px;\n    border: 1px solid var(--index-col);\n    text-align: center;\n}\n\n/* Special gates */\n.gate_connection {\n    position: absolute;\n    top: -3px;\n    left: -1px;\n    border: none;\n    margin: calc(var(--box-height)/2) calc(50% - 5px);\n    padding: 0;\n}\n.gate_swap {\n    height: 20px;\n    width: 20px;\n    margin: calc(var(--box-height)/2 - 6px) calc(50% - 9px);\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%270%200%2064%2064%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27currentcolor%27%3E%0A%20%20%3Cpath%20d%3D%27M60%200%20L32%2028%20L4%200%20L0%204%20L28%2032%20L0%2060%20L4%2064%20L32%2036%20L60%2064%20L64%2060%20L36%2032%20L64%204%27%20/%3E%0A%3C/svg%3E\n) center;\n    background-size: cover;\n}\n.gate_measure {\n    height: 20px;\n    width: 25px;\n    margin: calc(var(--box-height)/2 - 10px) calc(50% - 11px);\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%27-10%20-10%2084%2084%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27white%27%0A%20%20stroke%3D%22black%22%0A%20%20stroke-width%3D%224px%22%0A%3E%0A%20%20%3Cpath%20d%3D%27M63%2C63%20C63%2C32%2048%2C16%2032%2C16%20C16%2C16%201%2C32%201%2C63%20L63%2C63%27%20/%3E%0A%20%20%3Cpath%20d%3D%22M32%2C63%20L56%2C16%22%20/%3E%0A%3C/svg%3E\n) center;\n    background-size: cover;\n}\n.gate_control {\n    position: absolute;\n    top: 0;\n    left: 0;\n    border-radius: 50%;\n    width: 6px;\n    height: 6px;\n    margin: calc(var(--box-height)/2 - 3px) calc(50% - 5px);\n    padding: 0;\n    border: 2px solid var(--wire-col);\n    background: var(--box-col);\n}\n.gate_control.classical{\n    background: var(--c-wire-col);\n    border-color: var(--c-wire-col);\n}\n.control_index{\n    position: absolute;\n    right: calc(50% - 1em);\n    top: calc(50% - 1.4em);\n    color: var(--c-wire-col);\n    font-size: 0.8em;\n}\n.control_index.measure{\n    right: calc(50% - 1.2em);\n    top: calc(50% - 1.8em);\n    color: var(--index-col);\n}\n.gate_x {\n    top: -10px;\n    left: -6px;\n    border-radius: 50%;\n    border: 1px solid var(--wire-col);\n    width: 20px;\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%270%200%2064%2064%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27currentcolor%27%3E%0A%20%20%3Cpath%20d%3D%27M36%2064%20L36%2036%20L64%2036%20L64%2028%20L36%2028%20L36%200%20L28%200%20L28%2028%20L0%2028%20L0%2036%20L28%2036%20L28%2064%27%20/%3E%0A%3C/svg%3E\n) center;\n    background-color: var(--box-col);\n    background-size: cover;\n}\n.gate_reset{\n    margin: 11px 10px;\n    padding: 0 0 0 10px;\n    border: none !important;\n    border-left: 2px solid var(--wire-col) !important;\n    background: transparent;\n}\n.gate_reset_spider{\n    width: calc(var(--box-height) - 24px);\n    height: calc(var(--box-height) - 24px);\n    background: var(--box-col);\n    border: 2px solid var(--wire-col);\n    border-radius: 50%;\n    font-size: 0.75em;\n}\n\n/* Add wire sections coming in and out of the gate */\n.gate_in:before, .gate_in:after{\n    content: '';\n    position: absolute;\n    display: block;\n    top: calc(50% - 1px);\n    border: 1px solid var(--wire-col);\n    width: 9px;\n    height: 0;\n    background: var(--wire-col);\n    box-sizing: content-box;\n}\n.classical.gate_in:before,\n.classical.gate_in:after{\n    border-color: var(--c-wire-col);\n}\n\n.gate_in:before{\n    left: -12px;\n}\n.gate_out:after{\n    right: -12px;\n}\n.gate_top.gate_in:before, .gate_top.gate_out:after{\n    top:calc(50% - 6.5px)\n}\n.gate_bottom.gate_in:before, .gate_bottom.gate_out:after{\n    top:calc(50% + 4.5px)\n}\n\n\n.link-bottom, .link-top {\n    height: var(--box-height);\n    width: 0;\n    border: 1px solid var(--wire-col);\n    background: var(--wire-col);\n    position: absolute;\n    display: block;\n    left: calc(50% - 1px);\n    box-sizing: content-box;\n}\n.link-top{\n    top: calc(0px - var(--box-height)/2);\n}\n.link-bottom{\n    top: calc(var(--box-height)/2)\n}\n.half-link {\n    height: calc(var(--box-height) - 9px);\n}\n.half-link.link-bottom{\n    top: calc(var(--box-height)/2 + 11px)\n}\n.half-link.link-top{\n    top: calc(-2px - var(--box-height)/2);\n}\n.link-bottom.measurement{\n    width: 3px;\n    left: calc(50% - 0.5px);\n    border: none;\n    background: var(--c-wire-col);\n    height: calc(var(--box-height) + 2px);\n    z-index: 1;\n}\n\n\n\n/* tool tips */\n.tool-tip-container{\n    margin: calc(0px - var(--box-height)) auto 0;\n    padding-top: var(--box-height);\n    position: relative;\n    bottom: 0;\n    left: 0;\n    right: 0;\n    height: 0;\n    z-index: 4;\n    width: fit-content;\n    overflow: hidden;\n}\n.tool-tip-container.no-js{\n    overflow: visible;\n}\n.tool-tip-container.no-js:hover{\n    z-index: 10;\n}\n.nested > .tool-tip-container{\n    position: absolute;\n    bottom: -10px;\n}\n.tool-tip{\n    visibility: hidden;\n    opacity: 0;\n    -webkit-transition: visibility 0.2s, opacity 0.2s;\n    -moz-transition: visibility 0.2s, opacity 0.2s;\n    transition: visibility 0.2s, opacity 0.2s;\n    max-width: 250px;\n}\n.tool-tip-container.no-js:hover > .tool-tip{\n    visibility: visible;\n    opacity: 1;\n}\n.tool-tip-content{\n    background: var(--main-bg);\n    margin: 0 auto;\n    width: -moz-fit-content;\n    width: fit-content;\n    max-width: 100%;\n}\n.no-js > .tool-tip > .tool-tip-content{\n    height: auto;\n    padding: 20px;\n    margin: 0 auto;\n}\n.tool-tip-container.no-js:hover > .tool-tip > .tool-tip-content,\n.no-js > tool-tip > .tool-tip-content:hover{\n    box-shadow: 0 -5px 20px 5px var(--faint-col-overlay);\n}\n.tool-tip:after{\n    content: \" \";\n    position: absolute;\n    bottom: 0;\n    left: 50%;\n    margin-left: -5px;\n    border-width: 5px;\n    border-style: solid;\n    border-color: transparent transparent var(--main-bg) transparent;\n}\n.tool-tip .complex-number{\n    padding: 4px;\n}\n.tool-tip-content > .gate_container.nested{\n    width: 100%;\n    min-width: unset;\n}\n.nested-label-layer.as-height{\n    padding: 0;\n}\n.tool-tip-content > .gate_container.nested > .nested-circuit-container,\n.circuit-preview.condensed > .nested-circuit-container{\n    background: transparent;\n    border: none;\n    width: 100%;\n    min-width: unset;\n    max-width: unset;\n}\n\n/* Tool-tip modal */\n.circuit-grid{\n    display: flex;\n    flex-direction: row-reverse;\n    align-items: stretch;\n    align-content: stretch;\n}\n.circuit-grid-circuit{\n    flex: 1 1 auto;\n    margin-top: 30px;\n    overflow: auto;\n    max-height: inherit;\n}\n\n\n\n\n/*  FOR DISPLAYING CHARTS  */\ntable{\n    border-collapse: collapse;\n}\n.table-container{\n    margin: auto;\n}\n.bar-chart-container{\n    min-width: 300px;\n    width: 60%;\n}\n.square-chart-container{\n    width: auto;\n    min-width: 0;\n    overflow: hidden;\n}\n\n/* Make sure we can see the rightmost border */\n.square-chart-container tbody{\n    position: relative;\n    left: -1px;\n    display: block;\n}\nthead > tr{\n    background: transparent !important;\n}\ntr:hover, tr {\n    background: initial !important;\n}\n\ntd, th{\n    padding: 10px;\n    position: relative;\n}\n\n/* COMPLEX NUMBERS AND MATRICES */\n.complex-number{\n    padding: 10px;\n}\n.mid-number{\n    padding: 5px;\n    font-size: 0.75em;\n}\n.large-number{\n    padding: 2px;\n    font-size: 0.75em;\n}\n.matrix_container{\n    border: 2px solid var(--mid-col);\n    border-top: 0;\n    border-bottom: 0;\n    margin: auto !important;\n    border-collapse: collapse;\n    text-align: center;\n}\n\n\n/* LIST RESULTS NICELY */\n.list{\n    flex-wrap: wrap;\n    justify-content: space-evenly;\n    align-items: stretch;\n    padding: 0;\n}\n.list > *{\n    margin: 10px;\n}\n.list > .row-sub-heading{\n    margin: 10px 0;\n}\n</style>\n\n</head>\n<body>\n    <div class=\"row circuit-grid circuit__preview-body\">\n        <div class=\"circuit-grid-circuit thin-scrollbar\"  style=\"\">\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n    <div class=\"circuit-preview circuit_variables condensed\">\n\n\n            <div class=\"nested-label-layer as-height\">\n\n                    <div class=\"wire-label\"></div>\n\n                    <div class=\"wire-label\"></div>\n\n            </div>\n            <div class=\"nested-circuit-container\"><div class=\"circuit-inner-scroll\">\n\n        <div class=\"circuit-container nested\">\n            <div class=\"circuit-layer qubits\">\n\n            <div class=\"qubit\">q[0]</div>\n\n            <div class=\"qubit\">q[1]</div>\n\n\n    </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container x\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">V</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container h\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container x\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">X</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n                <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n                <div class=\"gate gate_control z\"></div>\n\n                    <div class=\"link-top\"></div>\n\n            </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container z\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rz(2*t/pi)</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container x\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">X</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n                <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n                <div class=\"gate gate_control z\"></div>\n\n                    <div class=\"link-top\"></div>\n\n            </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container x\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Vdg</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container h\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n            <div class=\"circuit-layer qubits\">\n\n            <div class=\"qubit\">q[0]</div>\n\n            <div class=\"qubit\">q[1]</div>\n\n\n    </div>\n        </div>\n\n            </div></div>\n\n    </div>\n\n\n\n\n        </div>\n    </div>\n</body>\n</html>\n\n\n### Circuit Execution\n\n* [github.com/CQCL/qermit](https://github.com/CQCL/qermit)\n* [User manual](https://cqcl.github.io/qermit/manual/index.html)\n\nPreparation for using `MitEx` object of `qermit`.\n\n\n```python\n# Generate ObservableTracker object to store the measurement circuit.\nfrom qermit import ObservableTracker\ntracker = ObservableTracker(operator)\n\n# Ansatz.\nfrom qermit import AnsatzCircuit, SymbolsDict\n\noptimal_parameter = -0.11223625\nansatz = ansatz0.copy()\nansatz.symbol_substitution({t: optimal_parameter})\nansatz_circuit = AnsatzCircuit(ansatz, 8000, SymbolsDict())\n\n# Prepare experiment by specifing the ansatz and the operator.\nfrom qermit import ObservableExperiment\n\nexperiment = ObservableExperiment(ansatz_circuit, tracker)\n```\n\nFirst run the simple `MitEx` without noise mitigation.\n\n\n```python\nfrom qermit import MitEx\n\nmitex = MitEx(backend)\nmitex.get_task_graph()\n```\n\n\n\n\n    \n\n    \n\n\n\n\n```python\nresult = mitex.run([experiment])\nenergy = sum(result[0]._dict.values()) + qpo_identity\nprint(f'E  = {energy:13.6f} Ha')\nprint(f'E0 = {cc_energy:13.6f} Ha (reference CC energy)')\n```\n\n    E  =     -1.108424 Ha\n    E0 =     -1.137306 Ha (reference CC energy)\n\n\nThen run the `MitEx` with noise mitigation technique.\n\n\n```python\nfrom qermit.clifford_noise_characterisation import gen_CDR_MitEx\n\ncdr_mitex = gen_CDR_MitEx(device_backend=backend,\n                      simulator_backend=noiseless_backend,\n                      n_non_cliffords=2,\n                      n_pairs=2,\n                      total_state_circuits=50\n)\ncdr_mitex.get_task_graph()\n```\n\n\n\n\n    \n\n    \n\n\n\n\n```python\n# This may take some time...\nresult = cdr_mitex.run([experiment])\nenergy = sum(result[0]._dict.values()) + qpo_identity\nprint(f'E  = {energy:13.6f} Ha')\nprint(f'E0 = {cc_energy:13.6f} Ha (reference CC energy)')\n```\n\n    E  =     -1.133449 Ha\n    E0 =     -1.137306 Ha (reference CC energy)\n\n", "meta": {"hexsha": "049d2af6180067df9a8b7957bbff2c4e1da588fb", "size": 229018, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "materials/2021-10-13/quantum_programming_with_tket.ipynb", "max_stars_repo_name": "dodosuke/tket-workshop", "max_stars_repo_head_hexsha": "b0ca08dad009792d0b5fa686ac29fb615943d51d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-24T08:13:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T08:13:48.000Z", "max_issues_repo_path": "materials/2021-10-13/quantum_programming_with_tket.ipynb", "max_issues_repo_name": "dodosuke/tket-workshop", "max_issues_repo_head_hexsha": "b0ca08dad009792d0b5fa686ac29fb615943d51d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "materials/2021-10-13/quantum_programming_with_tket.ipynb", "max_forks_repo_name": "dodosuke/tket-workshop", "max_forks_repo_head_hexsha": "b0ca08dad009792d0b5fa686ac29fb615943d51d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-10-12T00:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T09:21:08.000Z", "avg_line_length": 35.5673241187, "max_line_length": 529, "alphanum_fraction": 0.3842187077, "converted": true, "num_tokens": 29376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.09807932940215, "lm_q1q2_score": 0.04218856349341232}}
{"text": "\n\n<div style=\"text-align:center\">\n**ALEXANDRA RAIBOLT**\n</div>\n\n<div style=\"text-align:center\">\nMSc Student @ IME\u200b and\u200b BI & Data Management @ Firjan\n</div>\n\n# Construa sua pr\u00f3pria Rede Neural Convolucional em 3, 2, 1...!\n\n<div style=\"text-align:justify\">Uma introdu\u00e7\u00e3o as Redes Neurais Convolucionais em Python, usando o framework TensorFlow com Keras.</div>\n\n## Vis\u00e3o Geral\n\n<div style=\"text-align:justify\">Este Jupyter Notebook mostra passo a passo, o processo de constru\u00e7\u00e3o de uma Rede Neural Convolucional para reconhecimento e clasifica\u00e7\u00e3o de D\u00edgitos Manuscritos em Python, usando o framework TensorFlow com Keras.</div>\n<br>\n<div style=\"text-align:justify\">Neste exemplo, usamos o conjunto de dados [MNIST](http://yann.lecun.com/exdb/mnist \"MNIST\").</div>\n<br>\n<div style=\"text-align:justify\">**Aviso pr\u00e9vio:**</div>\n<br>\n<div style=\"text-align:justify\">O modelo de Redes Neurais Convolucional proposto nesta palestra foi implementado em Python (vers\u00e3o 5.4.0) usando o framework TensorFlow (vers\u00e3o 1.4.0) com Keras (vers\u00e3o 2.2.4) usando uma arquitetura baseada em GPU, e pode n\u00e3o funcionar com outras vers\u00f5es.</div>\n\n## Requisitos\n\n- Python 3 (vers\u00e3o 5.4.0);\n- TensorFlow (vers\u00e3o 1.4.0);\n- Keras (vers\u00e3o 2.2.4);\n- Jupyter Notebook (vers\u00e3o 4.4.0).\n\n## Depend\u00eancias\n\n- matplotlib;\n- numpy.\n\n<div style=\"text-align:justify\">Voc\u00ea pode instalar depend\u00eancias ausentes com [pip](https://pip.pypa.io/en/stable \"pip\"). E instalar o TensorFlow via [TensorFlow](https://www.tensorflow.org/install \"TensorFlow\") link.</div>\n\n## O que \u00e9 Aprendizado de M\u00e1quina?\n\n<div style=\"text-align:justify\">Aprendizado de M\u00e1quina (em ingl\u00eas, *Machine Learning*) \u00e9 uma sub\u00e1rea da Inteligencia Artifical que tem como prop\u00f3sito automatizar m\u00e1quinas atrav\u00e9s da cria\u00e7\u00e3o de modelos anal\u00edticos. Tal ideia se baseia na premissa de que m\u00e1quinas tem a habilidade de aprender, tomar decis\u00f5es, extrair *insights* e reconhecer padr\u00f5es (atrav\u00e9s de dados) sem a necessidade de serem explicitamente programadas, ou seja, sem interfer\u00eancia humana.</div>\n\n## Tipos de Aprendizado de M\u00e1quina:\n\n\n\n# Aprendizado Supervisionado:\n\n<div style=\"text-align:justify\">Um conjunto de dados de entradas e suas respectivas sa\u00eddas desejadas (denominadas como classes) s\u00e3o fornecidas por um \u201cprofessor\u201d ao modelo/computador, mostrando que h\u00e1 rela\u00e7\u00e3o entre os dados de entrada e de sa\u00edda.</div>\n<br>\n<div style=\"text-align:justify\">O objetivo deste tipo de aprendizado est\u00e1 em mapear as entradas para as suas respectivas sa\u00eddas desejadas ao encontrar uma regra geral que seja apta a classificar novos dados entre as classes j\u00e1 presentes no conjunto de dados.</div>\n\n## Classifica\u00e7\u00e3o:\n\n<div style=\"text-align:justify\">Em uma tarefa de classifica\u00e7\u00e3o, o objetivo \u00e9 mapear os tipos de entradas e categoriza-las em classes distintas, ou seja, realiza previs\u00f5es onde os resultados de sa\u00edda s\u00e3o de natureza discreta.</div>\n<br>\n<div style=\"text-align:justify\">Algoritmos de classifica\u00e7\u00e3o podem ser usados para problemas como: classifica\u00e7\u00e3o de g\u00eanero, classifica\u00e7\u00e3o de imagens m\u00e9dicas, classifica\u00e7\u00e3o de express\u00f5es faciais, etc.</div>\n<br>\n<div style=\"text-align:justify\">K-vizinhos mais pr\u00f3ximos, M\u00e1quinas de Vetores de Suporte e Redes Neurais Convolucionais s\u00e3o exemplos de algoritmos de classifica\u00e7\u00e3o.</div>\n\n## O que \u00e9 Rede Neural Artificial?\n\n<div style=\"text-align:justify\">Tendo como exemplo, a identifica\u00e7\u00e3o de objetos e ambientes distintos, \u00e9 questionado como o c\u00e9rebro humano \u00e9 capaz de traduzir uma imagem na retina humana para algo onde um indiv\u00edduo consiga identificar e classificar.</div>\n<br>\n<div style=\"text-align:justify\">Compreendendo toda a complexidade do c\u00e9rebro humano, tornou-se necess\u00e1rio o estudo e compreens\u00e3o de como os sistemas neurais biol\u00f3gicos funcionam, e a partir de tais estudos, pesquisadores foram capazes de proporcionar a estrutura b\u00e1sica para a constru\u00e7\u00e3o de modelos de Redes Neurais Artificiais (em ingl\u00eas, *Artificial Neural Networks - ANN*).</div>\n<br>\n<div style=\"text-align:justify\"></div>\n\n## O que \u00e9 Rede Neural Convolucional?\n\n<div style=\"text-align:justify\">As diversas arquiteturas de Redes Neurais Convolucionais s\u00e3o aplicadas com sucesso em desafios de reconhecimentoe classifica\u00e7\u00e3o de imagens, embora sejam tamb\u00e9m utilizadas em processamento de v\u00eddeo, e Processamento de Linguagem Natural (em ingl\u00eas, *Natural Language Processing*).</div>\n<br>\n<div style=\"text-align:justify\">Uma Rede Neural Convolucional pode ser caracterizada como sendo uma ANN de m\u00faltiplas camadas onde primariamente faz-se a suposi\u00e7\u00e3o de que os dados de entrada sejam imagens.</div>\n<br>\n<div style=\"text-align:justify\">As Redes Neurais Convolucionais hoje, s\u00e3o consideradas estado-da-arte para a resolu\u00e7\u00e3o de problemas na \u00e1rea de Vis\u00e3o Computacional, possuindo uma variedade de modelos e de arquiteturas (AlexNet, Inception, ResNet, etc.)</div>\n<br>\n<div style=\"text-align:justify\">Uma arquitetura b\u00e1sica de CNN pode ser dividida em camadas.</div>\n\n## Arquitetura de uma Rede Neural Convolucional\n\n\n\n## Camada de Entrada (ou em ingl\u00eas, Input Layer)\n\n<div style=\"text-align:justify\">Onde a imagem (ou base de imagens) \u00e9 inserida na rede.</div>\n<br>\n<div style=\"text-align:justify\">Computacionalmente falando, toda imagem pode ser representada como sendo uma matriz de valores de pixel, como pode ser visto abaixo:</div>\n\n\n\n<div style=\"text-align:justify\">Portanto, ao receber uma imagem em escala de cinza como entrada, o computador \"enxergar\u00e1\" uma matriz de valores de pixel (*m* x *n* x *1*), onde o valor 1 refere-se a um componente pr\u00e9-estabelecido de uma imagem \u2013 Canal - neste caso o valor 1 refere-se a uma imagem em escala de cinza. Portanto, ser\u00e1 atribu\u00eddo valores de intensidade de pixels dentro do intervalode 0 \u00e0 255 (onde 0 representa pontos pretos e 255 representa pontos brancos) para cada ponto da matriz.</div>\n\n## M\u00e3os a obra!\n\n\n```python\n# Imports\nfrom keras.datasets import mnist\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.models import Sequential\nfrom keras.optimizers import Adam\nimport keras\nimport matplotlib.pyplot as plt\nimport numpy as np\n```\n\n    Using TensorFlow backend.\n\n\n\n```python\n# Dimensions of the data\n\n# We know that images are 28 pixels in each dimension\nin_height = 28\nin_width = 28\n\n# Tuple with height and width of images used to reshape arrays\nimage_shape = (in_height, in_width)\n\n# We know MNIST has 60.000 training set images\nnum_data_train_images = 60000\n\n# We know MNIST has 10.000 training set images\nnum_data_test_images = 10000\n\n# Classes info\nclasses = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n\n# Number of classes\nnum_classes = len(classes)\n\n# Number of colour channels for the images: 1 channel for gray-scale\n# Channels mean number of primary colors\nnum_channels = 1\n```\n\n\n```python\n# Load Dataset\n\n# The data, split between train and test sets\n# The datasets are 3D arrays: (batch, height, width)\n# Returns the values of the function for images_set, labels_set on train-set\n# Returns the values of the function for images_set, labels_set on test-set\n(data_train_images, data_train_labels), (data_test_images, data_test_labels) = mnist.load_data()\n\n# Our CNN accepts only 4D arrays: (batch, height, width, channels)\n\n# Reshape data_train_images \ndata_train_images = data_train_images.reshape(num_data_train_images, in_height, in_width, num_channels)\n\n# Reshape data_test_images\ndata_test_images = data_test_images.reshape(num_data_test_images, in_height, in_width, num_channels)\n```\n\n\n```python\nprint(\"Size of:\")\nprint(\"- Training-set:\\t\\t{}\".format(len(data_train_images)))\nprint(\"- Test-set:\\t\\t{}\".format(len(data_test_images)))\n```\n\n    Size of:\n    - Training-set:\t\t60000\n    - Test-set:\t\t10000\n\n\n## Codifica\u00e7\u00e3o One-Hot\n\n<div style=\"text-align:justify\">As classes que representam os dez digitos manuscritos s\u00e3o representados por valores num\u00e9ricos.</div>\n<br>\n<div style=\"text-align:justify\">Utilizar valores num\u00e9ricos para representar r\u00f3tulos categ\u00f3ricos em algoritmos de ML n\u00e3o \u00e9 considerado como sendo uma boa pr\u00e1tica, pois \u00e9 poss\u00edvel que estes valores gerados possam prejudicar e influenciar a efetividade do algoritmo atrav\u00e9s do processo de aprendizado.</div>\n<br>\n<div style=\"text-align:justify\">Na presen\u00e7a desta restri\u00e7\u00e3o, convertemos os valores num\u00e9ricos que representam os r\u00f3tulos categ\u00f3ricos (tanto os valores num\u00e9ricos do conjunto de treinamento quanto os valores num\u00e9ricos do conjunto de teste) para vetores bin\u00e1rios que representam cada um dos valores num\u00e9ricos, atrav\u00e9s da codifica\u00e7\u00e3o One-Hot.</div>\n<br>\n<div style=\"text-align:justify\">A codifica\u00e7\u00e3o One-Hot \u00e9 uma codifica\u00e7\u00e3o de estados que consiste em gerar $ n $ vetores bin\u00e1rios para $ n $ valores num\u00e9ricos que representam cada um dos r\u00f3tulos categ\u00f3ricos. Deste modo, One-Hot realiza a codifica\u00e7\u00e3o para cada estado, de forma que cada valor num\u00e9rico seja representado por um \u00fanico vetor bin\u00e1rio de tamanho $ n $ igual a quantidade de classes presentes no conjunto de dados.</div>\n<br>\n<div style=\"text-align:justify\">Por exemplo: a sa\u00edda $ 8 $, de acordo com a codifica\u00e7\u00e3o One-Hot seria: $ [0, 0, 0, 0, 0, 0, 0, 0, 1, 0] $</div>\n\n\n```python\n# Class labels are One-Hot coded, meaning that each label is a vector with 10 elements,\n# all of which are zero except one element\ndata_train_labels = keras.utils.to_categorical(data_train_labels, num_classes)\ndata_test_labels = keras.utils.to_categorical(data_test_labels, num_classes)\n\ndata_test_cls = np.argmax(data_test_labels, axis=1)\n\nprint(data_test_cls)\n```\n\n    [7 2 1 ..., 4 5 6]\n\n\n\n```python\n# Helper-function for catch the class\n# number and print its corresponding name\ndef get_number(num_class):\n    if num_class == 0:\n        return 'Zero'\n    elif num_class == 1:\n        return 'One'\n    elif num_class == 2:\n        return 'Two'\n    elif num_class == 3:\n        return 'Three'\n    elif num_class == 4:\n        return 'Four'\n    elif num_class == 5:\n        return 'Five'\n    elif num_class == 6:\n        return 'Six'\n    elif num_class == 7:\n        return 'Seven'\n    elif num_class == 8:\n        return 'Eight'\n    elif num_class == 9:\n        return 'Nine'\n```\n\n\n```python\n# Helper-function for plotting images\ndef plot_images(images, cls_true, cls_pred=None):\n    assert len(images) == len(cls_true) == 9\n    \n    # Create figure with 3x3 sub-plots\n    fig, axes = plt.subplots(3, 3)\n    fig.subplots_adjust(hspace=0.3, wspace=0.3)\n\n    for i, ax in enumerate(axes.flat):\n        # Plot image\n        ax.imshow(images[i].reshape(image_shape), cmap='gray')\n\n        # Show true and predicted classes\n        # T = True, and P = Predicted\n        if cls_pred is None:\n            xlabel = \"T: {0}\".format(get_number(cls_true[i]))\n        else:\n            xlabel = \"T: {0}, P: {1}\".format(get_number(cls_true[i]), get_number(cls_pred[i]))\n\n        # Show the classes as the label on the x-axis\n        ax.set_xlabel(xlabel)\n        \n        # Remove ticks from the plot\n        ax.set_xticks([])\n        ax.set_yticks([])\n    \n    plt.show()\n```\n\n\n```python\n# Plot a few images to see if data is correct\n\n# Get the first images from the test-set\nimages = data_test_images[0:9]\n\n# Get the true classes for those images\ncls_true = data_test_cls[0:9]\n\n# Plot the images and labels using our helper-function above\nplot_images(images=images, cls_true=cls_true)\n```\n\n\n```python\n# We build a sequential model\n# The Sequential model is a linear stack of layers\nmodel = Sequential()\n```\n\n## Camada de Convolu\u00e7\u00e3o (ou em ingl\u00eas, Convolutional Layer)\n\n<div style=\"text-align:justify\">\u00c9 a principal opera\u00e7\u00e3o que ocorre nas imagens inseridas na rede, e seu principal objetivo est\u00e1 em extrair recursos de imagens de entrada.<br>\n    \n<div style=\"text-align:justify\">Uma imagem $ g $ \u00e9 gerada pela convolu\u00e7\u00e3o de um filtro $ f $ (comumente conhecido na literatura em ingl\u00eas como kernel) com a imagem de entrada idefinida pela equa\u00e7\u00e3o abaixo:<br>\n\n$$ g(m,n)=\\sum_{i=1}^{q}\\sum_{j=1}^{q}f(i,j)I(m-i,n-j) $$\n\n<div style=\"text-align:justify\">onde $ q $ \u00e9 a dimens\u00e3o da m\u00e1scara de convolu\u00e7\u00e3o.</div>\n\n\n\n<div style=\"text-align:justify\">Um filtro pode ressaltar determinada caracter\u00edstica presente em uma imagem, como por exemplo, sombras, bordas, entre outros.</div>\n<br>\n<div style=\"text-align:justify\">A Figura abaixo apresenta o resultado de uma convolu\u00e7\u00e3o aplicada a uma imagem de entrada.</div>\n\n\n\n<div style=\"text-align:justify\">Onde o resultado da convolu\u00e7\u00e3o \u00e9 comumente conhecido como um mapa de recursos (em ingl\u00eas,feature maps), e onde o filtro convolucional $ f $ utilizado foi uma matriz de tamanho $ 3x3 $ como na representa\u00e7\u00e3o a seguir:</div>\n\n\\begin{equation}\n\\label{equation:kernel}\nf = \\begin{bmatrix}\n1 &0   &0 \\\\ \n0 &-1  &0 \\\\ \n0 &0   &0 \n\\end{bmatrix}  \n\\end{equation}\n\n## Camada  ReLU (ou em ingl\u00eas, ReLU Layer)\n\n<div style=\"text-align:justify\">\u00c9 utilizada para que a rede possa convergir mais r\u00e1pido, aplica para as camadas escondidas da rede uma fun\u00e7\u00e3o de ativa\u00e7\u00e3o n\u00e3o linear \u00e0 sa\u00edda $ x $ da camada anterior, como abaixo:</div>\n\n\\begin{equation}\n\\label{equation:relu}\nf(x) = max(0, x)\n\\end{equation}\n\n<div style=\"text-align:justify\">Portanto, a sa\u00edda ser\u00e1 $ 0 $ quando a entrada for menor que $ 0 (x < 0) $, ou a sa\u00edda ser\u00e1 $ 1 $ caso contr\u00e1rio. Desta forma a ativa\u00e7\u00e3o \u00e9 limitada exclusivamente a $ 0 $, logo, a fun\u00e7\u00e3o de ativa\u00e7\u00e3o ReLU contribui em uma etapa de treinamento da rede mais r\u00e1pida para arquiteturas profundas</div>\n\n\n```python\n# Convolutional Layer 1\n\n# Convolution filters are 3 x 3 pixels\nfilter_height_1 = 3\nfilter_width_1 = 3\n\n# There are 8 of these filters\nnum_filters_1 = 32\n\n# Convolutional Layer 2\n\n# Convolution filters are 3 x 3 pixels\nfilter_height_2 = 3\nfilter_width_2 = 3\n\n# There are 16 of these filters\nnum_filters_2 = 64\n```\n\n\n```python\n# Convolutional Layer 1\nmodel.add(Conv2D(filters=num_filters_1,\n                 kernel_size=(filter_height_1, filter_width_1),\n                 activation='relu',\n                 input_shape=(in_height, in_width, num_channels)))\n```\n\n\n```python\n# Convolutional Layer 2\nmodel.add(Conv2D(filters=num_filters_2,\n                 kernel_size=(filter_height_2, filter_width_2),\n                 activation='relu'))\n```\n\n## Camada de Subamostragem (ou em ingl\u00eas, Pooling Layer)\n\n<div style=\"text-align:justify\">Reduz a dimensionalidade dos feature maps que ser\u00e3o utilizados pelas camadas seguintes, entretanto, sem perder as informa\u00e7\u00f5es mais relevantes.  Desta forma,  podemos definir a camada de subamostragem como uma convolu\u00e7\u00e3o que possui o objetivo de reduzir o tamanho espacial da representa\u00e7\u00e3o, de forma a contribuir com a diminui\u00e7\u00e3o de quantidade de par\u00e2metros e processamento computacional da rede.</div>\n<br>\n<div style=\"text-align:justify\">A fun\u00e7\u00e3o do Max-Pooling est\u00e1 em pegar o valor m\u00e1ximo dos elementos do feature maps presentes na janela $ 2x2 $ e agrupa-los como no exemplo abaixo:</div>\n\n\n\n\n```python\n# This is 2x2 max-pooling, which means that we\n# consider 2x2 windows and select the largest value\n# in each window. Then we move 2 pixels to the next window\nmodel.add(MaxPooling2D(pool_size=(2, 2),\n                       strides=(2, 2)))\n```\n\n\n```python\n# Dropout randomly switches off some neurons in\n# the network which forces the data to find new paths\nmodel.add(Dropout(0.25))\n```\n\n## Camada de Flatten (ou em ingl\u00eas, Flatten Layer)\n\n<div style=\"text-align:justify\">Ap\u00f3s passar pelas camadas de convolu\u00e7\u00e3o, ReLU e subamostragem a pr\u00f3xima etapa de uma CNN \u00e9 a classifica\u00e7\u00e3o, ou seja, \u00e9 necess\u00e1rio passar pela camada totalmente conectada.  A camada totalmente conectada aceita apenas como entrada, dados de dimens\u00e3o 1D.</div>\n<br>\n<div style=\"text-align:justify\">A camada Flatten possui o objetivo de \"achatar\" todo o volume de dados 3D em um \u00fanico vetor 1D de caracter\u00edsticas para posteriormente servir de entrada para a camada totalmente conectada.</div>\n\n\n```python\n# It allows the output to be processed by standard fully connected layers\nmodel.add(Flatten())\n```\n\n## Camada totalmente conectada (ou em ingl\u00eas, Fully Connected Layer)\n\n<div style=\"text-align:justify\">Essa camada age como um classificador, se localiza ao final da rede, geralmente \u00e9 do tipo soft-max usado para classificar a imagem de entrada. Realiza tal tarefa ao reconhecer padr\u00f5es que foram gerados pelas camadas anteriores. Portanto, estima a probabilidade de quais das $ n $ classes a imagem de entrada pertence.</div>\n\n\n```python\n# Fully-connected layer\n# Number of neurons in fully-connected layer\nfc_size = 128\n\nmodel.add(Dense(fc_size, activation='relu'))\n```\n\n\n```python\n# Dropout randomly switches off some neurons in\n# the network which forces the data to find new paths\nmodel.add(Dropout(0.5))\n```\n\n\n```python\n# Normalization of class-number output with 10 neurons (number of output classes)\n# and it uses softmax activation function.\n# Each neuron will give the probability of that class.\n#It\u2019s a multi-class classification that\u2019s why softmax activation function\nmodel.add(Dense(num_classes, activation='softmax'))\n```\n\n\n```python\n# Define the type of loss function, optimizer and the\n# metrics evaluated by the model during training and test\n\n# Cross Entropy as a Loss function\n# The lower the loss, the better a model\n# The loss is calculated on training and its interperation is how well the model is doing for this one set\n# Loss is not a percentage. It is a summation of the errors made for each example in training  set\n\n# AdamOptimizer as optimizer\n# It is an optimization algorithm used to perform the update of weights\n# in an iterative way according to the training data set\n# Needs few memory requirements, in addition to being computationally efficient\n\n# and Accuracy as metrics to improve the performance of our neural network\n\nmodel.compile(loss=keras.losses.categorical_crossentropy,\n              optimizer=keras.optimizers.Adam(),\n              metrics=['accuracy'])\n```\n\n\n```python\n# Training\n\n# Epoch:\n# One Epoch is when an ENTIRE dataset is passed forward\n# and backward through the neural network only ONCE\n\n# Batch Size:\n#Total number of training examples present in a single batch\n\n# Iterations:\n# Iterations is the number of batches needed to complete one epoch\n\n# Verbose:\n# Integer 0, 1, or 2\n# Verbosity mode: 0 = silent, 1 = progress bar, 2 = one line per epoch\n\nbatch_size = 128\nepochs = 12\n\nhistory = model.fit(data_train_images, data_train_labels,\n                    batch_size=batch_size,\n                    epochs=epochs,\n                    verbose=1)\n```\n\n    Epoch 1/12\n    60000/60000 [==============================] - 27s 457us/step - loss: 1.7346 - acc: 0.8363\n    Epoch 2/12\n    60000/60000 [==============================] - 10s 163us/step - loss: 0.1262 - acc: 0.9625\n    Epoch 3/12\n    60000/60000 [==============================] - 10s 164us/step - loss: 0.0964 - acc: 0.9708\n    Epoch 4/12\n    60000/60000 [==============================] - 10s 162us/step - loss: 0.0776 - acc: 0.9761\n    Epoch 5/12\n    60000/60000 [==============================] - 10s 163us/step - loss: 0.0677 - acc: 0.9795\n    Epoch 6/12\n    60000/60000 [==============================] - 10s 165us/step - loss: 0.0610 - acc: 0.9808\n    Epoch 7/12\n    60000/60000 [==============================] - 10s 164us/step - loss: 0.0561 - acc: 0.9823\n    Epoch 8/12\n    60000/60000 [==============================] - 10s 164us/step - loss: 0.0486 - acc: 0.9849\n    Epoch 9/12\n    60000/60000 [==============================] - 10s 165us/step - loss: 0.0483 - acc: 0.9847\n    Epoch 10/12\n    60000/60000 [==============================] - 10s 164us/step - loss: 0.0437 - acc: 0.9860\n    Epoch 11/12\n    60000/60000 [==============================] - 10s 164us/step - loss: 0.0462 - acc: 0.9857\n    Epoch 12/12\n    60000/60000 [==============================] - 10s 163us/step - loss: 0.0404 - acc: 0.9871\n\n\n## Google Cloud Platform\n\n<div style=\"text-align:justify\">Oferecida pelo Google, o GCP \u00e9 um conjunto de ferramentas, solu\u00e7\u00f5es e servi\u00e7os de computa\u00e7\u00e3o em nuvem que atua na mesma infraestrutura central do Google, ao lado de seus produtos, como o YouTube e o seu pr\u00f3prio mecanismo de busca.</div>\n<br>\n<div style=\"text-align:justify\">O GCP disponibiliza uma s\u00e9rie de solu\u00e7\u00f5es para processamento computacional, rede, armazenamento de dados, banco de dados escal\u00e1veis, explora\u00e7\u00e3o de dados, Internet das Coisas (em ingl\u00eas,Internet of Things- IoT), ML, ferramentas de gerenciamento, monitoramento, registro, diagn\u00f3sticos, entre outros.</div>\n<br>\n<div style=\"text-align:justify\">Este Notebook foi processado por  meio de uma inst\u00e2ncia de m\u00e1quina virtual de alto desempenho na infraestrutura do Google - Google Compute Engine (GCE) - um componente Infraestrutura como Servi\u00e7o (em ingl\u00eas, Infrastructure as a Service- IaaS).</div>\n<br> \n<div style=\"text-align:justify\">O GCE \u00e9 um recurso dispon\u00edvel na plataforma Google Cloud Platform (GCP). A inst\u00e2ncia de m\u00e1quina virtual on demand \u00e9 composta por uma GPU NVIDIA\u00ae Tesla\u00ae K80 com mem\u00f3ria da GPU de 12GB GDDR5 e 8 vCPUs dispon\u00edveis, al\u00e9m de 16 GB de mem\u00f3ria RAM e 50GB de HD e \u00e9 acessada por meio da interface de linha de comandos.</div>\n\n\n```python\n# Test\nscore = model.evaluate(data_test_images, data_test_labels, verbose=0)\n\n# Print test accuracy\nprint('Test accuracy:', score[1])\n```\n\n    Test accuracy: 0.9894\n\n\n\n\n## Dicas:\n\n- [TensorFlow](https://www.tensorflow.org/ \"TensorFlow\");\n- [Keras](https://keras.rstudio.com/index.html \"Keras\");\n- [An Intuitive Explanation of Convolutional Neural Networks](https://ujjwalkarn.me/2016/08/11/intuitive-explanation-convnets \"An Intuitive Explanation of Convolutional Neural Networks\");\n- [Hvass-Labs](https://github.com/Hvass-Labs/TensorFlow-Tutorials \"Hvass-Labs\");\n- [How to set up Tensorflow with CUDA and cuDNN on a free Google Cloud instance](https://www.youtube.com/watch?v=abEf3wQJBmE \"How to set up Tensorflow with CUDA and cuDNN on a free Google Cloud instance\").\n\n## Leituras Recomendadas:\n\n- BEALE, Russell; JACKSON, Tom. [Neural Computing-an introduction](https://bayanbox.ir/view/7901640340179926235/Neural-Computing-An-Introduction.pdf \"Neural Computing-an introduction\"). CRC Press, 1990.\n\n## Refer\u00eancias:\n\n- [Towards Data Science](https://towardsdatascience.com/build-your-own-convolution-neural-network-in-5-mins-4217c2cf964f \"Towards Data Science\");\n- [Hvass-Labs](https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/02_Convolutional_Neural_Network.ipynb \"Hvass-Labs\").\n\n# Distribui\u00e7\u00e3o MIT\n\nC\u00f3digo lan\u00e7ado sob a licen\u00e7a [MIT](https://github.com/whoisraibolt/Convolutional-Neural-Network-MNIST/blob/master/LICENSE \"MIT\").\n", "meta": {"hexsha": "8cda3c7005095266c18fc361ccaeed4c8066e5b8", "size": 46192, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Convolutional-Neural-Network-MNIST.ipynb", "max_stars_repo_name": "whoisraibolt/Convolutional-Neural-Network-MNIST", "max_stars_repo_head_hexsha": "276bd3abd3e23dcebe55b139138e6b11fcc2dbdd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Convolutional-Neural-Network-MNIST.ipynb", "max_issues_repo_name": "whoisraibolt/Convolutional-Neural-Network-MNIST", "max_issues_repo_head_hexsha": "276bd3abd3e23dcebe55b139138e6b11fcc2dbdd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Convolutional-Neural-Network-MNIST.ipynb", "max_forks_repo_name": "whoisraibolt/Convolutional-Neural-Network-MNIST", "max_forks_repo_head_hexsha": "276bd3abd3e23dcebe55b139138e6b11fcc2dbdd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.2382382382, "max_line_length": 11468, "alphanum_fraction": 0.6921111881, "converted": true, "num_tokens": 6141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.10521054301575125, "lm_q1q2_score": 0.04206439982625229}}
{"text": "##### Copyright 2019 Google LLC.\n\nLicensed under the Apache License, Version 2.0 (the \"License\")\n\n\n```\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# On Variational Bounds of Mutual Information\nBen Poole, Sherjil Ozair, A&auml;ron van den Oord, Alexander A. Alemi, George Tucker<br/>\n*ICML 2019*<br/>\n[paper](https://arxiv.org/abs/1905.06922) / [slides](https://docs.google.com/presentation/d/1dz0AVBy6VDz7SU43m0IQjuJDviEuf3NpWSeIWov_DYc/present?usp=sharing) / [video](https://www.facebook.com/icml.imls/videos/2202320806483370/?t=2562) / [poster](https://drive.google.com/file/d/1C5ZYqSJRaOupQelqYgVbc9lJ7__0CDXA/view?usp=sharing)\n\nThis notebook contains code for most of the variational bounds on mutual information presented in the paper, and experiments on the toy Gaussian problem. \n\nComments? Complaints? Questions? Bug Ben on Twitter [@poolio](https://twitter.com/poolio)\n\n<sup>Thanks to [Zhe Dong](https://www.linkedin.com/in/hoogendong/) for valuable feedback on this colab.</sup>\n\n### Introduction\n\nHere we give a brief overview of the challenges of MI estimation and a few of the variational bounds we presented in the paper. Please checkout the [paper](https://arxiv.org/abs/1905.06922) for more details.\n\nOur goal is to build efficient estimators of mutual information (MI) that leverage neural networks. Mutual information is given by:\n$$I(X; Y) = \\mathbb{E}_{p(x,y)}\\left[\\log \\frac{p(x,y)}{p(x)p(y)}\\right].$$\nEstimating MI is challenging as we often only have access to samples $x, y$ but do not know the densities.\n\nTo overcome these challenges, we review and presented several variational estimators of MI. These estimators replace the intractable MI objective with a tractable objective that lower or upper bounds MI, and depends on neural-network-powered critics and baselines. For example, the $I_\\text{NWJ}$ bound is given by:\n\n$$ I(X; Y) \\ge 1 + \\mathbb{E}_{p(x, y)} \\left[\\color{blue} f(x,y) \\right] - \\mathbb{E}_{p(x)p(y)} \\left[  \\exp{{\\color{blue} f(x , y)}}\\right] $$\nwhere $\\color{blue} f$ is a neural network that takes $x$ and $y$ as input and outputs a scalar.\n\nBelow, we code up several variational lower and upper bounds on mutual information:\n- Existing lower bounds: $I_\\text{NWJ}, \\,I_\\text{InfoNCE}$\n- New lower bounds: $I_\\text{TUBA},\\, I_{\\alpha},\\, I_\\text{JS}$\n- Structured lower bound ($I_\\text{TNCE}$) and upper bounds ($I_\\text{BA}$, $I_\\text{MBU}$) with known $p(y|x)$\n\nHere's a table of the bounds we'll code up here as well as the mathematical objectives:\n\n\nWe apply these bounds to a toy problem, where $(x, y)$ are jointly Gaussian, and we vary the correlation between $x$ and $y$ over time to increase the mutual information. For the bounds with neural network critics, we train the critics to tighten the variational bounds.\n\n### Practical suggestions\n- MI estimates with neural networks are highly sensitive to the representation of the input data, architecture, optimizer, and more. When applying these estimators to new datasets, you will need to experiment!\n- For representation learning, the $I_\\text{NCE}$ bounds are a good place to start. Implementing them is simple.\n- For estimation, start with the $I_\\alpha$ bounds with a small $\\alpha$. The implementation is trickier, but they can greatly reduce variance vs. $I_\\text{NWJ}$.\n- If you have known structure use it. For example, if you know a conditional distribution $p(y|x)$, use one of the structured bounds. \n\n### Implementation notes:\n- For most bounds, we will work with a matrix, denoted by `f` or `scores` that contains the output of the critic for every pair of elements in the minibatch: `scores[i, j] = critic(x[j], y[i])`\n- Most variational lower bounds on MI require samples from both the joint $p(x, y)$ and marginal distributions $p(x)p(y)$. For a minibatch of size $K$, we have $K$ samples from the joint $p(x,y)$ and can form samples from the marginal by using all pairs $x_i, y_j$ where $i \\ne j$, giving $K \\times (K -1)$ samples from the marginal. The diagonal elements of the `scores` matrix correspond to the $K$ critic scores for samples from the joint, and the off-diagonal elements correspond to the critic scores for samples from the marginal.\n- In this notebook we assume that we use all other elements in the minibatch as negative samples. For certain InfoMax tasks, for example when negatives come from the same image but at other spatial locations, one has to be more careful about summing over and selecting the right positive and negative examples to form the two expectations.\n- Separable critics are the more efficient and popular architecture. Instead of having to do $K^2$ forward passes, you only have to do $2 \\times K$ followed by an inner product. \n\n## Setup\nNotebook should work in TF 1.X, but uses Eager-mode.\n\n\n```\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport tensorflow as tf\ntf.enable_eager_execution()\n\nimport tensorflow_probability as tfp\ntfd = tfp.distributions\ntfkl = tf.keras.layers\ntfp = tfp.layers\n\nimport pandas as pd # used for exponential moving average\nfrom scipy.special import logit\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n## Variational bound implementations\n###  TUBA and NWJ lower bounds\nThe $I_\\text{TUBA}$ variational lower bound on mutual information is given by:\n$$ I(X; Y) \\ge 1 + \\mathbb{E}_{p(x, y)} \\left[\\log {e^{\\color{blue} f(x,y)}\\over{\\color{green}  a(y)}} \\right] - \\mathbb{E}_{p(x)p(y)} \\left[  \\frac{e^{{\\color{blue} f(x , y)}}}{\\color{green} a(y)}\\right] \\triangleq I_\\text{TUBA}$$\nThese bounds can be low bias, but are typically high variance. To implement this bound, we need the critic scores for all elements in the minibatch: `scores[i, j] = critic(x[i], y[j])`, and the value of the baseline `a[j] = baseline(y[j])` for every `y`. Instead of requiring the baseline to be non-negative, we assume that the argument passed in is $\\log {\\color{green} a(y)}$, and will exponentiate it to get the baseline ${\\color{green} a(y)}$.\n\nThe implementation requires averaging the exponentiated critic over all independent samples, corresponding to the off-diagonal terms in `scores`,  which is done by the `reduce_logmeanexp_nodiag` function.\n\nThe $I_\\text{NWJ}$ bound just uses the constant $e$ for the baseline, which is equivalent to adding 1 to the critic scores.\n\n\n```\ndef reduce_logmeanexp_nodiag(x, axis=None):\n  batch_size = x.shape[0].value\n  logsumexp = tf.reduce_logsumexp(x - tf.linalg.tensor_diag(np.inf * tf.ones(batch_size)), axis=axis)\n  if axis:\n    num_elem = batch_size - 1.\n  else:\n    num_elem  = batch_size * (batch_size - 1.)\n  return logsumexp - tf.math.log(num_elem)\n\ndef tuba_lower_bound(scores, log_baseline=None):\n  if log_baseline is not None:\n    scores -= log_baseline[:, None]\n  batch_size = tf.cast(scores.shape[0], tf.float32)\n  # First term is an expectation over samples from the joint,\n  # which are the diagonal elmements of the scores matrix.\n  joint_term = tf.reduce_mean(tf.linalg.diag_part(scores))\n  # Second term is an expectation over samples from the marginal,\n  # which are the off-diagonal elements of the scores matrix.\n  marg_term = tf.exp(reduce_logmeanexp_nodiag(scores))\n  return 1. + joint_term -  marg_term\n\ndef nwj_lower_bound(scores):\n  # equivalent to: tuba_lower_bound(scores, log_baseline=1.)\n  return tuba_lower_bound(scores - 1.) \n```\n\n### InfoNCE contrastive lower bound\nThe InfoNCE variational lower bound is the easiest to implement, and typically provides low variance but high bias estimates of MI:\n$$I(X; Y) \\ge \\mathbb{E}_{p^K(x,y)}\\left[\\frac{1}{K} \\sum_{i=1}^K \\log \\frac{e^{\\color{blue}f(x_i, y_i)}}{\\frac{1}{K}\\sum_{j=1}^K e^{\\color{blue} f(x_j, y_i)}}\\right].$$\nThe expectation $p^K(x,y)$ draws $K$ samples from the joint $(x, y)$. So for a minibatch of $K$ examples, we are effectively forming a single sample Monte-Carlo estimate of the quantity inside the expectation.\n\nHere we use `reduce_logsumexp` so the implementation matches the math, but you can also implement this with `sparse_softmax_cross_entropy_with_logits` using a different label for each of the `K` elements in the minibatch.\n\n\n```\ndef infonce_lower_bound(scores):\n  \"\"\"InfoNCE lower bound from van den Oord et al. (2018).\"\"\"\n  nll = tf.reduce_mean(tf.linalg.diag_part(scores) - tf.reduce_logsumexp(scores, axis=1))\n  # Alternative implementation:\n  # nll = -tf.nn.sparse_softmax_cross_entropy_with_logits(logits=scores, labels=tf.range(batch_size))\n  mi = tf.math.log(tf.cast(scores.shape[0].value, tf.float32)) + nll\n  return mi\n```\n\n### Interpolated lower bounds\nThe interpolated lower bounds are the trickiest to implement, but also provide the best of both worlds: lower bias or variance relative to the NWJ and InfoNCE bounds. We start with the multisample TUBA bound from the paper:\n$$I(X_1; Y) \\geq 1+\\mathbb{E}_{p(x_{1:K})p(y|x_1)}\\left[\\log \\frac{e^{f(x_1,y)}}{a(y; x_{1:K})}\\right]\n- \\mathbb{E}_{p(x_{1:K})p(y)}\\left[ \\frac{e^{f(x_1,y)}}{a(y; x_{1:K})}\\right]$$\nCoding up this bound is tricky as we need $K+1$ samples from the joint $p(x,y)$: $K$ of these samples are used for the first term, and the additional sample is used for the independent sample from $p(y)$ for the second term. In the minibatch setting, we can implement this by holding out the $j$th sample from the joint,  and using $y_j$ for the indepent sample from $p(y)$ for the second term, and $x_\\ne j$ (all elements in the minibatch except element $j$) for the samples from $p(x_{1:K})$. A single-sample Monte-Carlo approximation to the NWJ bound is then given by:\n\n$$1 + \\log \\frac{e^{f(x_1, y_1)}}{a(y_1; x_{\\ne j}, \\alpha)} - \\frac{e^{f(x_1, y_j)}}{a(y_j; x_{\\ne j}, \\alpha)}$$\nInstead of just using $(x_1, y_1)$ as the only positive example, we can use all samples from the joint in the minibatch: $(x_i, y_i)$. Summing over the $K$ elements which are not the element we are holding out for the second expectation ($y_j$), yields:\n$$1 + \\frac{1}{K}\\sum_{i\\ne j} \\left(\\log \\frac{e^{f(x_i, y_i)}}{a(y_i; x_{\\ne j}, \\alpha)} - \\frac{e^{f(x_i, y_j)}}{a(y_j; x_{\\ne j}, \\alpha)}\\right)$$\n\nFurthermore, in the minibatch setting we can choose any element in the minibatch to hold out for the second expectation. Summing over all possible (leave one out) combinations yields:\n$$1 + \\frac{1}{K+1} \\sum_{j=1}^{K+1} \\frac{1}{K}\\sum_{i\\ne j} \\left(\\log \\frac{e^{f(x_i, y_i)}}{a(y_i; x_{\\ne j}, \\alpha)} - \\frac{e^{f(x_i, y_j)}}{a(y_j; x_{\\ne j}, \\alpha)}\\right)$$\nwhere the interpolated baseline is given by $a(y; x_{1:M}) = \\alpha \\frac{1}{K} \\sum_{l=1}^K e^{f(x_l, y)} + (1-\\alpha) q(y)$. We work in log-space for numerical stability, using `compute_log_loomean` to compute the leave one out InfoNCE baselines, and `log_interpolate` to compute the log baseline for the interpolated bound.\n\n\n```\ndef log_interpolate(log_a, log_b, alpha_logit):\n  \"\"\"Numerically stable implementation of log(alpha * a + (1-alpha) * b).\"\"\"\n  log_alpha = -tf.nn.softplus(-alpha_logit)\n  log_1_minus_alpha = -tf.nn.softplus(alpha_logit)\n  y = tf.reduce_logsumexp(tf.stack((log_alpha + log_a, log_1_minus_alpha + log_b)), axis=0)\n  return y\n\ndef compute_log_loomean(scores):\n  \"\"\"Compute the log leave-one-out mean of the exponentiated scores.\n\n  For each column j we compute the log-sum-exp over the row holding out column j.\n  This is a numerically stable version of:\n  log_loosum = scores + tfd.softplus_inverse(tf.reduce_logsumexp(scores, axis=1, keepdims=True) - scores) \n  Implementation based on tfp.vi.csiszar_divergence.csiszar_vimco_helper.\n  \"\"\"\n  max_scores = tf.reduce_max(scores, axis=1, keepdims=True)\n  lse_minus_max = tf.reduce_logsumexp(scores - max_scores, axis=1, keepdims=True)\n  d = lse_minus_max + (max_scores - scores)\n  d_ok = tf.not_equal(d, 0.)\n  safe_d = tf.where(d_ok, d, tf.ones_like(d))\n  loo_lse = scores + tfd.softplus_inverse(safe_d)\n  # Normalize to get the leave one out log mean exp\n  loo_lme = loo_lse - tf.math.log(scores.shape[1].value - 1.)\n  return loo_lme\n\ndef interpolated_lower_bound(scores, baseline, alpha_logit):\n  \"\"\"Interpolated lower bound on mutual information.\n\n  Interpolates between the InfoNCE baseline ( alpha_logit -> -infty),\n  and the single-sample TUBA baseline (alpha_logit -> infty)\n\n  Args:\n    scores: [batch_size, batch_size] critic scores\n    baseline: [batch_size] log baseline scores\n    alpha_logit: logit for the mixture probability\n\n  Returns:\n    scalar, lower bound on MI\n  \"\"\"\n  batch_size = scores.shape[0].value\n  # Compute InfoNCE baseline\n  nce_baseline = compute_log_loomean(scores)\n  # Inerpolated baseline interpolates the InfoNCE baseline with a learned baseline\n  interpolated_baseline = log_interpolate(\n      nce_baseline, tf.tile(baseline[:, None], (1, batch_size)), alpha_logit)\n  # Marginal term.\n  critic_marg = scores - tf.linalg.diag_part(interpolated_baseline)[:, None]\n  marg_term = tf.exp(reduce_logmeanexp_nodiag(critic_marg))\n\n  # Joint term.\n  critic_joint = tf.linalg.diag_part(scores)[:, None] - interpolated_baseline\n  joint_term = (tf.reduce_sum(critic_joint) -\n                tf.reduce_sum(tf.linalg.diag_part(critic_joint))) / (batch_size * (batch_size - 1.))\n  return 1 + joint_term  - marg_term\n```\n\n### JS-KL hybrid lower bound\nWe can also use different approaches for training the critic vs. estimating mutual informaiton. The $I_\\text{JS}$ bound just trains the critic with the standard lower bound on the Jensen-Shannon divergence used in GANs, and then evaluates the critic using the $I_\\text{NWJ}$ lower bound on KL (mutual information). \n\nWe use a fun trick to simplify the code here:\n`z = x + tf.stop_gradient(y - x)`.<br/>\n`z` gives the value of `y` on the forward pass, but the gradient of `x` on the backward pass.\n\n\n```\ndef js_fgan_lower_bound(f):\n  \"\"\"Lower bound on Jensen-Shannon divergence from Nowozin et al. (2016).\"\"\"\n  f_diag = tf.linalg.tensor_diag_part(f)\n  first_term = tf.reduce_mean(-tf.nn.softplus(-f_diag))\n  n = tf.cast(f.shape[0], tf.float32)\n  second_term = (tf.reduce_sum(tf.nn.softplus(f)) - tf.reduce_sum(tf.nn.softplus(f_diag))) / (n * (n - 1.))\n  return first_term - second_term\n\ndef js_lower_bound(f):\n  \"\"\"NWJ lower bound on MI using critic trained with Jensen-Shannon.\n\n  The returned Tensor gives MI estimates when evaluated, but its gradients are\n  the gradients of the lower bound of the Jensen-Shannon divergence.\"\"\"\n  js = js_fgan_lower_bound(f)\n  mi = nwj_lower_bound(f)\n  return js + tf.stop_gradient(mi - js)\n```\n\n### Structured Bounds\n\nSee the end of the notebook for code for the structured bounds. The implementation when using these bounds is often different, as we use a known conditional distribution $p(y|x)$ instead of a critic function $f(x, y)$ that scores all pairs of points. For simplicity, we will just demonstrate the minibatch lower bound $I_\\text{TNCE}$, which is equivalent to $I_\\text{NCE}$ but using the critic $f(x,y) = \\log p(y|x)$. \n\n### Putting it together\n\n\n```\ndef estimate_mutual_information(estimator, x, y, critic_fn,\n                                baseline_fn=None, alpha_logit=None):\n  \"\"\"Estimate variational lower bounds on mutual information.\n\n  Args:\n    estimator: string specifying estimator, one of:\n      'nwj', 'infonce', 'tuba', 'js', 'interpolated'\n    x: [batch_size, dim_x] Tensor\n    y: [batch_size, dim_y] Tensor\n    critic_fn: callable that takes x and y as input and outputs critic scores\n      output shape is a [batch_size, batch_size] matrix\n    baseline_fn (optional): callable that takes y as input \n      outputs a [batch_size]  or [batch_size, 1] vector\n    alpha_logit (optional): logit(alpha) for interpolated bound\n\n  Returns:\n    scalar estimate of mutual information\n  \"\"\"\n  scores = critic_fn(x, y)\n  if baseline_fn is not None:\n    # Some baselines' output is (batch_size, 1) which we remove here.\n    log_baseline = tf.squeeze(baseline_fn(y))\n  if estimator == 'infonce':\n    mi = infonce_lower_bound(scores)\n  elif estimator == 'nwj':\n    mi = nwj_lower_bound(scores)\n  elif estimator == 'tuba':\n    mi = tuba_lower_bound(scores, log_baseline)\n  elif estimator == 'js':\n    mi = js_lower_bound(scores)\n  elif estimator == 'interpolated':\n    assert alpha_logit is not None, \"Must specify alpha_logit for interpolated bound.\"\n    mi = interpolated_lower_bound(scores, log_baseline, alpha_logit)\n  return mi\n```\n\n## Neural network architectures\n\n**Critics**: we consider two choices of neural network architectures for $\\color{blue} f(x,y)$:\n1. **Separable**: $f(x,y) = g(x)^Th(y)$ where $g$ and $h$ are two different MLPs\n2. **Concat**: $f(x,y) = g([x, y])$ where we concatenate $x$ and $y$ and feed them into a single MLP\n\nUsing a separable baseline is typically more efficient, as you only have to do `batch_size` forward passes through each network vs. the `batch_size * batch_size` with the concat critic.\n\n**Baselines**: we consider three possibilities for the baseline $\\color{green}a(y)$:\n1. **Constant**: $a(y)$ is a fixed constant (as in $I_\\text{NWJ}$)\n2. **Unnormalized**: $a(y)$ is a neural network that produces a scalar output (representing $\\log a(y)$)\n3. **Gaussian**: $a(y)$ is a Gaussian distribution. Here we fix the mean and variance to be 1, but you could use any tractable density with learnable parameters as well.\n\n### Critics\n\n\n```\ndef mlp(hidden_dim, output_dim, layers, activation):\n  return tf.keras.Sequential(\n      [tfkl.Dense(hidden_dim, activation) for _ in range(layers)] +\n      [tfkl.Dense(output_dim)])\n   \n\nclass SeparableCritic(tf.keras.Model):\n  def __init__(self, hidden_dim, embed_dim, layers, activation, **extra_kwargs):\n    super(SeparableCritic, self).__init__()\n    self._g = mlp(hidden_dim, embed_dim, layers, activation)\n    self._h = mlp(hidden_dim, embed_dim, layers, activation)\n\n  def call(self, x, y):\n    scores = tf.matmul(self._h(y), self._g(x), transpose_b=True)\n    return scores\n\n\nclass ConcatCritic(tf.keras.Model):\n  def __init__(self, hidden_dim, layers, activation, **extra_kwargs):\n    super(ConcatCritic, self).__init__()\n    # output is scalar score\n    self._f = mlp(hidden_dim, 1, layers, activation)\n\n  def call(self, x, y):\n    batch_size = tf.shape(x)[0]\n    # Tile all possible combinations of x and y\n    x_tiled = tf.tile(x[None, :],  (batch_size, 1, 1))\n    y_tiled = tf.tile(y[:, None],  (1, batch_size, 1))\n    # xy is [batch_size * batch_size, x_dim + y_dim]\n    xy_pairs = tf.reshape(tf.concat((x_tiled, y_tiled), axis=2), [batch_size * batch_size, -1])\n    # Compute scores for each x_i, y_j pair.\n    scores = self._f(xy_pairs) \n    return tf.transpose(tf.reshape(scores, [batch_size, batch_size]))\n\n\ndef gaussian_log_prob_pairs(dists, x):\n  \"\"\"Compute log probability for all pairs of distributions and samples.\"\"\"\n  mu, sigma = dists.mean(), dists.stddev()\n  sigma2 = sigma**2\n  normalizer_term = tf.reduce_sum(-0.5 * (np.log(2. * np.pi) + 2.0 *  tf.math.log(sigma)), axis=1)[None, :]\n  x2_term = -tf.matmul(x**2, 1.0 / (2 * sigma2), transpose_b=True)\n  mu2_term = - tf.reduce_sum(mu**2 / (2 * sigma2), axis=1)[None, :]\n  cross_term = tf.matmul(x, mu / sigma2, transpose_b=True)\n  log_prob = normalizer_term + x2_term + mu2_term + cross_term\n  return log_prob\n\n  \ndef build_log_prob_conditional(rho, **extra_kwargs):\n  \"\"\"True conditional distribution.\"\"\"\n  def log_prob_conditional(x, y):\n    mu = x * rho\n    q_y = tfd.MultivariateNormalDiag(mu, tf.ones_like(mu) * tf.cast(tf.sqrt(1.0 - rho**2), tf.float32))\n    return gaussian_log_prob_pairs(q_y, y)\n  return log_prob_conditional\n  \n\nCRITICS = {\n    'separable': SeparableCritic,\n    'concat': ConcatCritic,\n    'conditional': build_log_prob_conditional,\n}\n```\n\n### Baselines\n\n\n```\ndef log_prob_gaussian(x):\n  return tf.reduce_sum(tfd.Normal(0., 1.).log_prob(x), -1)\n\nBASELINES= {\n    'constant': lambda: None,\n    'unnormalized': lambda: mlp(hidden_dim=512, output_dim=1, layers=2, activation='relu'),\n    'gaussian': lambda: log_prob_gaussian,\n}\n```\n\n## Experiments\n\n### Dataset: correlated Gaussian\nWe experiment with a super simple correlated Gaussian dataset:\n\\begin{align}\nx &\\sim \\mathcal{N}(0, I_d)\\\\\ny &\\sim \\mathcal{N}(\\rho x, (1 - \\rho^2) I_d)\n\\end{align}\nwhere $d$ is the dimensionality, and $\\rho$ is the correlation. Each pair of dimensions $(x_i, y_i)$ has correlation $\\rho$, and correlation 0 with all other dimensions. We can control the information by varying the correlation $\\rho$:\n$$I(X; Y) = -\\frac{d}{2} \\log \\left(1 - \\rho^2\\right)$$\n\n\n```\ndef sample_correlated_gaussian(rho=0.5, dim=20, batch_size=128):\n  \"\"\"Generate samples from a correlated Gaussian distribution.\"\"\"\n  x, eps = tf.split(tf.random.normal((batch_size, 2 * dim)), 2, axis=1)\n  y = rho * x + tf.sqrt(tf.cast(1. - rho**2, tf.float32)) * eps\n  return x, y\n\ndef rho_to_mi(dim, rho):\n  return -0.5  * np.log(1-rho**2) * dim\n\ndef mi_to_rho(dim, mi):\n  return np.sqrt(1-np.exp(-2.0 / dim * mi))\n\ndef mi_schedule(n_iter):\n  \"\"\"Generate schedule for increasing correlation over time.\"\"\"\n  mis = np.round(np.linspace(0.5, 5.5-1e-9, n_iter)) *2.0#0.1\n  return mis.astype(np.float32)\n```\n\n\n```\nplt.figure(figsize=(6,3))\nfor i, rho in enumerate([0.5, 0.99]):\n  plt.subplot(1, 2, i + 1)\n  x, y = sample_correlated_gaussian(batch_size=500, dim=1, rho=rho)\n  plt.scatter(x[:, 0], y[:, 0])\n  plt.title(r'$\\rho=%.2f$,  $I(X; Y)=%.1f$' % (rho, rho_to_mi(1, rho)))\n  plt.xlim(-3, 3); plt.ylim(-3, 3);\n```\n\n### Training code\n\n\n```\ndef train_estimator(critic_params, data_params, mi_params):\n  \"\"\"Main training loop that estimates time-varying MI.\"\"\"\n  # Ground truth rho is only used by conditional critic\n  critic = CRITICS[mi_params.get('critic', 'concat')](rho=None, **critic_params)\n  baseline = BASELINES[mi_params.get('baseline', 'constant')]()\n  \n  opt = tf.keras.optimizers.Adam(opt_params['learning_rate'])\n  \n  @tf.function\n  def train_step(rho, data_params, mi_params):\n    # Annoying special case:\n    # For the true conditional, the critic depends on the true correlation rho,\n    # so we rebuild the critic at each iteration.\n    if mi_params['critic'] == 'conditional':\n      critic_ = CRITICS['conditional'](rho=rho)\n    else:\n      critic_ = critic\n    \n    with tf.GradientTape() as tape:\n      x, y = sample_correlated_gaussian(dim=data_params['dim'], rho=rho, batch_size=data_params['batch_size'])\n      mi = estimate_mutual_information(mi_params['estimator'], x, y, critic_, baseline, mi_params.get('alpha_logit', None))\n      loss = -mi\n  \n      trainable_vars = []\n      if isinstance(critic, tf.keras.Model):\n        trainable_vars += critic.trainable_variables \n      if isinstance(baseline, tf.keras.Model):\n        trainable_vars += baseline.trainable_variables\n      grads = tape.gradient(loss, trainable_vars)\n      opt.apply_gradients(zip(grads, trainable_vars))\n    return mi\n  \n  # Schedule of correlation over iterations \n  mis = mi_schedule(opt_params['iterations'])\n  rhos = mi_to_rho(data_params['dim'], mis)\n  \n  estimates = []\n  for i in range(opt_params['iterations']):\n    estimates.append(train_step(rhos[i], data_params, mi_params).numpy())\n\n  return np.array(estimates)\n```\n\nDataset, optimization, and critic parameters. Try experimenting with these.\n\n\n```\ndata_params = {\n    'dim': 20,\n    'batch_size': 64,\n}\n\ncritic_params = {\n    'layers': 2,\n    'embed_dim': 32,\n    'hidden_dim': 256,\n    'activation': 'relu',\n}\n\nopt_params = {\n    'iterations': 20000,\n    'learning_rate': 5e-4,\n}\n```\n\nBuild a dictionary of the mutual information estimators to train and their parameters.\n\n\n```\ncritic_type = 'concat' # or 'separable'\n\nestimators = {\n    'NWJ': dict(estimator='nwj', critic=critic_type, baseline='constant'),\n    'TUBA': dict(estimator='tuba', critic=critic_type, baseline='unnormalized'),\n    'InfoNCE': dict(estimator='infonce', critic=critic_type, baseline='constant'),\n    'JS': dict(estimator='js', critic=critic_type, baseline='constant'),\n    'TNCE': dict(estimator='infonce', critic='conditional', baseline='constant'),\n    # Optimal critic for TUBA\n    #'TUBA_opt': dict(estimator='tuba', critic='conditional', baseline='gaussian')\n}\n\n# Add interpolated bounds\ndef sigmoid(x):\n  return 1/(1. + np.exp(-x))\nfor alpha_logit in [-5., 0., 5.]:\n  name = 'alpha=%.2f' % sigmoid(alpha_logit)\n  estimators[name] = dict(estimator='interpolated', critic=critic_type,\n                          alpha_logit=alpha_logit, baseline='unnormalized')\n```\n\nTrain each estimator and store mutual information estimates (this takes ~2 minutes on a modern GPU).\n\n\n```\nestimates = {}\nfor estimator, mi_params in estimators.items():\n  print(\"Training %s...\" % estimator)\n  estimates[estimator] = train_estimator(critic_params, data_params, mi_params)\n```\n\n    Training NWJ...\n    Training TUBA...\n    Training InfoNCE...\n    Training JS...\n    Training TNCE...\n    Training alpha=0.01...\n    Training alpha=0.50...\n    Training alpha=0.99...\n\n\n### Results\n\n\n```\n# Smooting span for Exponential Moving Average\nEMA_SPAN = 200\n\n# Ground truth MI\nmi_true = mi_schedule(opt_params['iterations'])\n\n# Names specifies the key and ordering for plotting estimators\nnames = np.sort(list(estimators.keys()))\nlnames = list(map(lambda s: s.replace('alpha', '$\\\\alpha$'), names))\n\nnrows = min(2, len(estimates))\nncols = int(np.ceil(len(estimates) / float(nrows)))\nfig, axs = plt.subplots(nrows, ncols, figsize=(2.7 * ncols, 3 * nrows)) \nif len(estimates) == 1:\n  axs = [axs]\naxs = np.ravel(axs)\n  \nfor i, name in enumerate(names):\n  plt.sca(axs[i])\n  plt.title(lnames[i])\n  # Plot estimated MI and smoothed MI\n  mis = estimates[name]  \n  mis_smooth = pd.Series(mis).ewm(span=EMA_SPAN).mean()\n  p1 = plt.plot(mis, alpha=0.3)[0]\n  plt.plot(mis_smooth, c=p1.get_color())\n  # Plot true MI and line for log(batch size)\n  plt.plot(mi_true, color='k', label='True MI')\n  estimator = estimators[name]['estimator']\n  if 'interpolated' in estimator or 'nce' in estimator:\n    # Add theoretical upper bound lines\n    if 'interpolated' in estimator:\n      log_alpha = -np.log( 1+ tf.exp(-estimators[name]['alpha_logit']))\n    else:\n      log_alpha = 1.\n    plt.axhline(1 + np.log(data_params['batch_size']) - log_alpha, c='k', linestyle='--', label=r'1 + log(K/$\\alpha$)' )\n  plt.ylim(-1, mi_true.max()+1)\n  plt.xlim(0, opt_params['iterations'])\n  if i == len(estimates) - ncols:\n    plt.xlabel('steps')\n    plt.ylabel('Mutual information (nats)')\nplt.legend(loc='best', fontsize=8, framealpha=0.0)\nplt.gcf().tight_layout();\n```\n\n## Structured Bounds\n\nThe structured lower bounds use known conditional and learned marginal distributions to lower and upper bound mutual information. Check back soon for some more examples with these bounds!\n\n\n```\ndef log_prob_pairs(dists, samples):\n  if isinstance(dists, (tfd.Normal, tfd.MultivariateNormalDiag)):\n    return gaussian_log_prob_pairs(dists, samples)\n  batch_size = tf.shape(samples)[0]\n  multiples = [1] * (1 + len(samples.get_shape().as_list()))\n  multiples[1] = tf.shape(samples)[0]\n  samples_tiled = tf.tile(samples[:, None], multiples)\n  # Compute log probs, size [batch_size, batch_size]\n  log_probs = dists.log_prob(samples_tiled)\n  return log_probs\n\ndef variational_upper_bound(conditional_dist, marginal_dist, samples):\n  \"\"\"Variational upper bound on mutual information.\n\n  Args:\n    conditional_dist: true conditional density, p(y|x)\n    marginal_dist: approximate marginal density, m(y)\n    samples: samples from the conditional distribution p(y|x)\n\n  Returns:\n    scalar, upper bound on mutual information\n  \"\"\"\n  return tf.reduce_mean(conditional_dist.log_prob(samples) -\n                        marginal_dist.log_prob(samples))\n\n\ndef minibatch_upper_bound(conditional_dist, samples):\n  \"\"\"Minibatch upper bound on mutual information.\n\n  Args:\n    conditional_dist: approximate conditional density, e(y|x)\n    samples: samples from conditional_dist\n\n  Returns:\n    scalar, upper bound on mutual information\n  \"\"\"\n  log_probs = log_prob_pairs(conditional_dist, samples)\n  # Batch marginal holds out self (along diagonal), and averages over\n  # all other elements in the batch.\n  mask = tf.eye(tf.shape(samples)[0])\n  log_prob_marginal = tf.reduce_mean(reduce_logmeanexp_nodiag(log_probs, axis=1))\n  log_prob_cond = tf.reduce_mean(tf.linalg.tensor_diag_part(log_probs))\n  return log_prob_cond - log_prob_marginal\n\ndef minibatch_lower_bound(conditional_dist, samples):\n  \"\"\"Minibatch lower bound on mutual information.\n\n  Args:\n    conditional_dist: approximate conditional density, e(y|x)\n    samples: samples from conditional_dist\n\n  Returns:\n    scalar, lower bound on mutual information\n  \"\"\"\n  batch_marginal_dist = tfd.MixtureSameFamily(\n      mixture_distribution=tfd.Categorical(logits=tf.zeros(conditional_dist.batch_shape)),\n      components_distribution=conditional_dist)\n  return variational_upper_bound(conditional_dist, batch_marginal_dist, samples)\n```\n", "meta": {"hexsha": "d430865ee0ca70d3342975833b38c5e6883e1926", "size": 141205, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "vbmi/vbmi_demo.ipynb", "max_stars_repo_name": "yick2232/google-research", "max_stars_repo_head_hexsha": "99021ebda945e232abdcc592f2cea1375b3c84f7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-02-04T16:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T11:56:01.000Z", "max_issues_repo_path": "vbmi/vbmi_demo.ipynb", "max_issues_repo_name": "lceustc/google-research", "max_issues_repo_head_hexsha": "bf793f31022db2636f42e132198ffe8bd9631b58", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-09-26T00:19:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:04:29.000Z", "max_forks_repo_path": "vbmi/vbmi_demo.ipynb", "max_forks_repo_name": "lceustc/google-research", "max_forks_repo_head_hexsha": "bf793f31022db2636f42e132198ffe8bd9631b58", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-15T02:38:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T02:38:27.000Z", "avg_line_length": 133.5903500473, "max_line_length": 77418, "alphanum_fraction": 0.820927021, "converted": true, "num_tokens": 8023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.10230469831315611, "lm_q1q2_score": 0.04205857345005632}}
{"text": "# Cool things\n\n## Running console commands\n\nIn jupyter, the bang (`!`) symbolizes an escape into the underlying console (bash, zsh, powershell, cmd).\n\nYou can use this to easily grab the stdout of a commandline parameter and use it in a variable.\n\n\n```python\n!ls\n```\n\n\n```python\n!uname -a\n!whoami\n!ls /dev\n!lspci\n```\n\n\n```python\nfiles = !ls\n[\"%s.bak\" % f for f in files]\n```\n\n## Latex\n\nJupyter formats latex.\n\n$\n\\begin{equation}\n  x = a_0 + \\cfrac{1}{a_1 \n          + \\cfrac{1}{a_2 \n          + \\cfrac{1}{a_3 + \\cfrac{1}{a_4} } } }\n\\end{equation}\n$\n\n## JupyterLab\n\nJupyterlab is the future UI for jupyter.\n\nOn binder, it is included by default and can be accessed by replacing `tree` in the url by `lab`.\n\n## Save as feature\n\nYou can download a notebook as many formats including source code format, html, latex, pdf.\n\n## Convert to presentation\n\nYou can use a notebook for presentations and keynotes.\n\nEdit slides by going to View|Cell Toolbar|Slideshow\n\n\n```python\n!jupyter nbconvert 01-Cool-Things.ipynb --to slides # --reveal-prefix=reveal.js --post serve\n```\n\n## Examples in the wild\n\n* [A beginner python course I made for my friends](https://hub.mybinder.org/user/bwrsandman-learningpython-6vqa2dhl/tree)\n* [Coursea Machine Learning Ex1](https://github.com/jdwittenauer/ipython-notebooks/blob/master/notebooks/ml/ML-Exercise1.ipynb)\n* [geojson-extension](https://mybinder.org/v2/gh/binder-examples/jupyterlab/master?urlpath=lab)\n* [LIGO black hole detection](https://losc.ligo.org/s/events/GW150914/LOSC_Event_tutorial_GW150914.html)\n* [An open RNA-Seq data analysis pipeline tutorial with an example of reprocessing data from a recent Zika virus study](http://nbviewer.jupyter.org/github/maayanlab/Zika-RNAseq-Pipeline/blob/master/Zika.ipynb)\n* [Python for Signal Processing](http://nbviewer.jupyter.org/github/unpingco/Python-for-Signal-Processing/blob/master/Compressive_Sampling.ipynb)\n* [Timeseries Classification: KNN & DTW](http://nbviewer.jupyter.org/github/markdregan/K-Nearest-Neighbors-with-Dynamic-Time-Warping/blob/master/K_Nearest_Neighbor_Dynamic_Time_Warping.ipynb)\n* [OpenCV Detecting Faces](https://github.com/handee/opencv-gettingstarted/blob/master/5%20detecting%20faces%20and%20other%20things.ipynb)\n* [Analysis of the Gaza-Israel 2012 crisis](http://nbviewer.jupyter.org/gist/darribas/4121857)\n* [Extracting and manipulating article metadata (RDF) from Het Laatste Nieuws](http://nbviewer.jupyter.org/url/mhermans.net/files/tmp/demo_rdf_HLN.ipynb)\n* [Map of US Airports (Javascript)](https://nbviewer.jupyter.org/gist/Fil/efb1c9f3f0a9092c420dfe4cef8def96)\n* [Blogging with the IPython Notebook](http://nbviewer.jupyter.org/github/fperez/blog/blob/master/120907-Blogging%20with%20the%20IPython%20Notebook.ipynb)\n* [XKCD-style graphs](http://nbviewer.jupyter.org/url/jakevdp.github.com/downloads/notebooks/XKCD_plots.ipynb)\n", "meta": {"hexsha": "9d1e314cd09563f33ddd96dc66a702fed8585124", "size": 5431, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "01-Cool-Things.ipynb", "max_stars_repo_name": "bwrsandman/learningjupyter", "max_stars_repo_head_hexsha": "f8e6e5749ea8eea5bd51c21da10e5e2f629507b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "01-Cool-Things.ipynb", "max_issues_repo_name": "bwrsandman/learningjupyter", "max_issues_repo_head_hexsha": "f8e6e5749ea8eea5bd51c21da10e5e2f629507b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "01-Cool-Things.ipynb", "max_forks_repo_name": "bwrsandman/learningjupyter", "max_forks_repo_head_hexsha": "f8e6e5749ea8eea5bd51c21da10e5e2f629507b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3640776699, "max_line_length": 218, "alphanum_fraction": 0.5879211932, "converted": true, "num_tokens": 845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121955219593834, "lm_q2_score": 0.10970576660095782, "lm_q1q2_score": 0.041821983216929266}}
{"text": "# Q# notebooks #\n\nThis notebook will show you how to use IQ# to write your own quantum application notebooks.\n\n\n## Compiling Q# operations\n\nAn operation is the basic unit of quantum execution in Q#. It is roughly equivalent to a function in C or C++ or Python, or a static method in C# or Java.\n\nIQ#, the Q# Jupyter kernel, allows you to write Q# operations directly on a code cell and compile them by running the cell (pressing  Ctrl/\u2318+Enter). For example:\n\n\n```qsharp\noperation SayHello(name: String) : Unit {\n\n    // The following line will simply write a message to the console:\n    Message($\"Hello {name}!\");\n\n}\n```\n\n\n\n\n<ul><li>SayHello</li></ul>\n\n\n\nWhen you **Run** the cell, Q# compiles the code and returns the name of the operations it found. \nIn this case, it found only one operation (`SayHello`). \n\nIf the compiler detects any errors, it will instead show the list of errors in the output. For example:\n\n\n```qsharp\noperation InvalidQ() : Unit {\n\n    // The `FooBar` operation doesn't exist, so the following line\n    // will generate a `No variable with that name exists.` error:\n    FooBar(\"Hello again!\");\n    \n    // `Message` takes only one string argument, so the following line\n    // will generate a `Unexpected argument tuple.` error:\n    Message(1, 2);\n}\n```\n\n    C:\\snippet_.qs(5,5): error QS5022: No identifier with the name \"FooBar\" exists.\n    C:\\snippet_.qs(9,12): error QS6211: Unexpected argument tuple. Expecting an argument of type String.\n\n\nQ# operations can call other operations previously defined; they can also call all the operations defined in the \n[Microsoft.Quantum.Intrinsic](https://docs.microsoft.com/qsharp/api/qsharp/microsoft.quantum.intrinsic) and \n[Microsoft.Quantum.Canon](https://docs.microsoft.com/qsharp/api/qsharp/microsoft.quantum.canon) namespaces (like [Message](https://docs.microsoft.com/qsharp/api/qsharp/microsoft.quantum.intrinsic.message)).\n\nFor example, you can create a new operation that calls the previously compiled `SayHello`:\n\n\n\n```qsharp\noperation HelloAndres() : Unit {\n    SayHello(\"Andres\");\n}\n```\n\n\n\n\n<ul><li>HelloAndres</li></ul>\n\n\n\nThey can also use all [Q# standard library](https://docs.microsoft.com/qsharp/api/) operations defined in other namespaces by importing the namespace using the `open` statement. For example, to use [`PI`](https://docs.microsoft.com/qsharp/api/prelude/microsoft.quantum.math.pi) you would need to open the ` Microsoft.Quantum.Math` namespace; optionally you can call the operation providing its fully qualified name, for example:\n \n\n\n```qsharp\nopen Microsoft.Quantum.Math;\n\noperation HelloPi() : Unit {\n    let pi = Microsoft.Quantum.Convert.DoubleAsString(PI());\n    SayHello(pi);\n}\n```\n\n\n\n\n<ul><li>HelloPi</li></ul>\n\n\n\nYou can define multiple operations in a single cell and use any valid Q# code, for example:\n\n\n```qsharp\nopen Microsoft.Quantum.Random;\n\n/// # Summary\n/// Sets the qubit's state to |+\u27e9\noperation SetPlus(q: Qubit) : Unit {\n    Reset(q);\n    H(q);\n}\n\n/// # Summary\n/// Sets the qubit's state to |-\u27e9\noperation SetMinus(q: Qubit) : Unit {\n    Reset(q);\n    X(q);\n    H(q);\n}\n\n/// # Summary\n/// Randomly prepares the qubit into |+\u27e9 or |-\u27e9\noperation PrepareRandomMessage(q: Qubit) : Unit {\n\n    let choice = DrawRandomInt(0, 1);\n\n    if choice == 0 {\n        Message(\"Prepared |-\u27e9\");\n        SetMinus(q);\n    } else {\n        Message(\"Prepared |+\u27e9\");\n        SetPlus(q);\n    }\n}\n```\n\n\n\n\n<ul><li>SetPlus</li><li>SetMinus</li><li>PrepareRandomMessage</li></ul>\n\n\n\nand create other operations that uses them:\n\n\n```qsharp\nopen Microsoft.Quantum.Diagnostics;\nopen Microsoft.Quantum.Measurement;\n\noperation SampleRandomBit() : Result {\n    use q = Qubit();\n    SetPlus(q);\n    return MResetZ(q);\n}\n\noperation TestPrepareQubits() : Result {\n    mutable r = Zero;\n    \n    use qubits = Qubit[5];\n    ApplyToEach(PrepareRandomMessage, qubits);\n    DumpMachine();\n\n    set r = Measure([PauliX, PauliX, PauliX, PauliX, PauliX], qubits);\n\n    ResetAll(qubits);\n    \n    return r;\n}\n```\n\n\n\n\n<ul><li>SampleRandomBit</li><li>TestPrepareQubits</li></ul>\n\n\n\n## Simulating Q# operations\n\n\nOnce a Q# operation has been successfully compiled, you can use the `%simulate` command to simulate it. For example:\n\n\n```qsharp\n%simulate HelloPi\n```\n\n    Hello 3.141592653589793!\r\n\n\n\n\n\n    ()\n\n\n\n\n```qsharp\n%simulate SampleRandomBit\n```\n\n`%simulate` will print any console output on the notebook, and it will return the operation's return value. If the operation returns `Unit` it prints `()`, otherwise it prints the actual value.\n\n`%simulate` only accepts operations that take no arguments. If you want to call an operation that accepts parameters, like `SayHello`, create a wrapper operation that calls it with the corresponding values, like `HelloPi`.\n\nAs mentioned, all messages are printed on the notebook; this includes calls to [`DumpMachine`](https://docs.microsoft.com/en-us/qsharp/api/prelude/microsoft.quantum.extensions.diagnostics.dumpmachine):\n\n\n```qsharp\n%config dump.basisStateLabelingConvention = \"bitstring\"\n```\n\n\n\n\n    \"bitstring\"\n\n\n\n\n```qsharp\n%simulate TestPrepareQubits\n```\n\n    Prepared |+\u27e9\n    Prepared |+\u27e9\n    Prepared |-\u27e9\n    Prepared |+\u27e9\n    Prepared |+\u27e9\n\n\n\n\r\n                    <table style=\"table-layout: fixed; width: 100%\">\r\n                        <thead>\r\n                            \r\n                        <tr>\r\n                            <th>Qubit IDs</th>\r\n                            <td span=\"3\">0, 1, 2, 3, 4</td>\r\n                        </tr>\r\n                    \r\n                            <tr>\r\n                                <th style=\"width: 20ch)\">Basis state (bitstring)</th>\r\n                                <th style=\"width: 20ch\">Amplitude</th><th style=\"width: calc(100% - 26ch - 20ch)\">Meas. Pr.</th><th style=\"width: 6ch\">Phase</th>\r\n                            </tr>\r\n                        </thead>\r\n                        <tbody>\r\n                        \r\n                            <tr>\r\n                                <td>$\\left|00000\\right\\rangle$</td>\r\n                                <td>$0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-1d9a4bf6-4e2b-49f5-abcd-6c9c95dfa612\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(0deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|00001\\right\\rangle$</td>\r\n                                <td>$0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-f13e0bcb-cd45-4be0-ac2e-66344df89b80\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(0deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|00010\\right\\rangle$</td>\r\n                                <td>$0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-0fa43684-ac4b-40cb-b3ca-d0c83acc752d\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(0deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|00011\\right\\rangle$</td>\r\n                                <td>$0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-f7a19142-4d61-4664-9f94-1fc2d183c49d\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(0deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|00100\\right\\rangle$</td>\r\n                                <td>$-0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-3befcc80-2a3a-43ec-9c43-443cf4e067ec\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(180deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|00101\\right\\rangle$</td>\r\n                                <td>$-0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-b4724f02-21fb-44eb-88bf-465a959a9684\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(180deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|00110\\right\\rangle$</td>\r\n                                <td>$-0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-a1a85823-c68d-4162-a88c-ddb29539066c\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(180deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|00111\\right\\rangle$</td>\r\n                                <td>$-0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-053973b5-4228-419a-84dc-228ac929d9a0\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(180deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|01000\\right\\rangle$</td>\r\n                                <td>$0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-a4e2829c-f258-40be-bd2c-a661ffb5feb1\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(0deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|01001\\right\\rangle$</td>\r\n                                <td>$0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-1f176cfc-c418-4f72-adc8-e85dc4681385\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(0deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|01010\\right\\rangle$</td>\r\n                                <td>$0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-3271862c-459e-4838-a917-8d1776f3ff01\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(0deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|01011\\right\\rangle$</td>\r\n                                <td>$0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-56b4907f-9258-48ce-8cf1-dece15fbb01c\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(0deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|01100\\right\\rangle$</td>\r\n                                <td>$-0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-62a2ead5-a09d-4f86-837e-569796d1734e\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(180deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|01101\\right\\rangle$</td>\r\n                                <td>$-0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-3b7d3681-100d-4096-ade0-86543bbe5fd3\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(180deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|01110\\right\\rangle$</td>\r\n                                <td>$-0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-630f0866-f1c5-4677-b653-b8b82b05f933\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(180deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|01111\\right\\rangle$</td>\r\n                                <td>$-0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-004470f2-634e-4d82-ac03-b3c953f8122d\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(180deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|10000\\right\\rangle$</td>\r\n                                <td>$0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-6fc081a6-5204-4eaa-bbb3-6073d387da3f\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(0deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|10001\\right\\rangle$</td>\r\n                                <td>$0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-135e77ab-bf4d-4118-8ffe-435f8b7c1c3d\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(0deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|10010\\right\\rangle$</td>\r\n                                <td>$0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-71d243e2-0b8b-463b-b006-4c7a6272729f\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(0deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|10011\\right\\rangle$</td>\r\n                                <td>$0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-c5531ecb-fa36-4458-b4a0-3829fef53589\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(0deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|10100\\right\\rangle$</td>\r\n                                <td>$-0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-daf12820-0445-4307-b18e-c14d2151c5ee\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(180deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|10101\\right\\rangle$</td>\r\n                                <td>$-0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-e63afba7-5d28-424a-a267-d74cae330bfb\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(180deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|10110\\right\\rangle$</td>\r\n                                <td>$-0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-b1a6c715-195b-46b5-8062-956d60420c67\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(180deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|10111\\right\\rangle$</td>\r\n                                <td>$-0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-890c31db-be3f-40e3-b79f-2dd920ca17e9\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(180deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|11000\\right\\rangle$</td>\r\n                                <td>$0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-4e431da9-dac5-4959-b374-cc714e9d5ffb\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(0deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|11001\\right\\rangle$</td>\r\n                                <td>$0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-99ae3410-cb41-4cf9-b9f6-dac16643c2fe\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(0deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|11010\\right\\rangle$</td>\r\n                                <td>$0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-5af84f7a-5b8d-493d-888d-97d25163d349\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(0deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|11011\\right\\rangle$</td>\r\n                                <td>$0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-498bd817-0961-4adf-9343-ae1c7277e100\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(0deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|11100\\right\\rangle$</td>\r\n                                <td>$-0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-50a83d14-09ec-4fdc-bf86-9e19c0cc6dd7\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(180deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|11101\\right\\rangle$</td>\r\n                                <td>$-0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-51b7513a-6e11-4415-8d61-f684af8fc33b\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(180deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|11110\\right\\rangle$</td>\r\n                                <td>$-0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-0f51bcca-087d-4577-8cc5-6aef91c34ba6\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(180deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n\n\r\n                            <tr>\r\n                                <td>$\\left|11111\\right\\rangle$</td>\r\n                                <td>$-0.1768 + 0.0000 i$</td>\r\n                                \r\n                                <td>\r\n                                    <progress\r\n                                        max=\"100\"\r\n                                        value=\"3.1250000000000013\"\r\n                                        style=\"width: 100%;\"\r\n                                    > \r\n                                    <td>\r\n                                    <p id=\"round-799e2132-ba3d-4209-8c20-197652f14894\"> \r\n                                     </p>\r\n                                    </td>\r\n                                </td>\r\n                            \r\n                                \r\n                                <td style=\"transform: rotate(180deg);\r\n                   text-align: center;\">\r\n                                 \u2191\r\n                                </td>\r\n                            \r\n                            </tr>\r\n                        \r\n                        </tbody>\r\n                    </table>\n\n\n\n\n\n    One\n\n\n\n## Estimating resources\n\nThe `%estimate` command lets you estimate the resources a given quantum operation will need to execute, without actually executing the operation. Similar to `%simulate` it takes the name of a no-arguments operation. However, `%estimate` does not keep track of the qubit's state and will not return the output of the operation, instead it returns the estimated values of how many resources, like Qubits and CNOT gates, the corresponding operation will use:\n\n\n```qsharp\n%estimate TestPrepareQubits\n```\n\n\n\n\n<table><thead><tr><th style=\"text-align: start;\">Metric</th><th style=\"text-align: start;\">Sum</th><th style=\"text-align: start;\">Max</th></tr></thead><tbody><tr><td style=\"text-align: start;\">CNOT</td><td style=\"text-align: start;\">0</td><td style=\"text-align: start;\">0</td></tr><tr><td style=\"text-align: start;\">QubitClifford</td><td style=\"text-align: start;\">7</td><td style=\"text-align: start;\">7</td></tr><tr><td style=\"text-align: start;\">R</td><td style=\"text-align: start;\">0</td><td style=\"text-align: start;\">0</td></tr><tr><td style=\"text-align: start;\">Measure</td><td style=\"text-align: start;\">11</td><td style=\"text-align: start;\">11</td></tr><tr><td style=\"text-align: start;\">T</td><td style=\"text-align: start;\">0</td><td style=\"text-align: start;\">0</td></tr><tr><td style=\"text-align: start;\">Depth</td><td style=\"text-align: start;\">0</td><td style=\"text-align: start;\">0</td></tr><tr><td style=\"text-align: start;\">Width</td><td style=\"text-align: start;\">5</td><td style=\"text-align: start;\">5</td></tr><tr><td style=\"text-align: start;\">QubitCount</td><td style=\"text-align: start;\">5</td><td style=\"text-align: start;\">5</td></tr><tr><td style=\"text-align: start;\">BorrowedWidth</td><td style=\"text-align: start;\">0</td><td style=\"text-align: start;\">0</td></tr></tbody></table>\n\n\n\nTo learn more about resources estimation, take a look at [The ResourcesEstimator Target Machine](https://docs.microsoft.com/azure/quantum/user-guide/machines/resources-estimator) documentation.\n\n## The Workspace\n\nThe notebook uses the folder it lives on disk to define a workspace. It will try to compile all the Q# files (i.e. all files with a `.qs` extension) it finds under the current folder and will make the operations it finds available to operations in the notebook. For example, the [Operations.qs](/Operations.qs) file in this folder defines two operations:\n* Microsoft.Quantum.Samples.IsMinus\n* Microsoft.Quantum.Samples.IsPlus\n\nTo get the list of operations defined in the workspace, you can use the `%workspace` command:\n\n\n```qsharp\n%workspace\n```\n\n\n\n\n<ul><li>Microsoft.Quantum.Samples.IsMinus</li><li>Microsoft.Quantum.Samples.IsPlus</li></ul>\n\n\n\nThese operations can be used in this notebook, for example:\n\n\n```qsharp\nopen Microsoft.Quantum.Samples;\n\noperation CheckPlus() : Bool {\n    mutable result = false;\n    \n    use q = Qubit();\n    SetPlus(q);\n    set result = IsPlus(q);\n\n    Reset(q);\n\n    return result;\n}\n```\n\n\n\n\n<ul><li>CheckPlus</li></ul>\n\n\n\n\n```qsharp\n%simulate CheckPlus\n```\n\n\n\n\n    True\n\n\n\nTo pick up any changes you make to a Q# file in the workspace, use `%workspace reload`. \n\n\n```qsharp\n%workspace reload\n```\n\n\n    Reloading workspace: done!\n\n\n\n\n\n<ul><li>Microsoft.Quantum.Samples.IsMinus</li><li>Microsoft.Quantum.Samples.IsPlus</li></ul>\n\n\n\n## Getting Help ##\n\nQ# supports adding documentation to operations via comments in the code. When such documentation exists, you can access it from the notebook by adding a question mark before or after the operation name on a code cell, for example:\n\n\n```qsharp\nMicrosoft.Quantum.Intrinsic.X?\n```\n\n\n\n\n\r\n                    <h4><i class=\"fa fas fa-terminal\"></i> Microsoft.Quantum.Intrinsic.X <a href=\"C:\\Users\\cgran\\.dotnet\\tools\\.store\\microsoft.quantum.iqsharp\\0.15.2101125897\\microsoft.quantum.iqsharp\\0.15.2101125897\\tools\\netcoreapp3.1\\any\\Microsoft.Quantum.QSharp.Core.dll\"><i class=\"fa fas fa-code\"></i></a></h4>\r\n                    <h5>Summary</h5><p>Applies the Pauli $X$ gate.</p>\n<p>\\begin{align}\n\\sigma_x \\mathrel{:=}\n\\begin{bmatrix}\n0 &amp; 1 \\\\\n1 &amp; 0\n\\end{bmatrix}.\n\\end{align}</p>\n\r\n                    \r\n\n\n\n\nThis documentation is available for any operations in the Prelude, Canon and Workspace, or even those defined locally in the notebook:\n\n\n```qsharp\nPrepareRandomMessage?\n```\n\n\n\n\n\r\n                    <h4><i class=\"fa fas fa-terminal\"></i> PrepareRandomMessage <a href=\"C:\\Users\\cgran\\source\\repos\\microsoft\\quantum\\samples\\getting-started\\intro-to-iqsharp\\obj\\__snippets__.dll\"><i class=\"fa fas fa-code\"></i></a></h4>\r\n                    \r\n                    \r\n\n\n\n\n## Other commands ##\n\n### `%who`\n\n`%who` returns the list of all local and workspace operations available.\n\n\n```qsharp\n%who\n```\n\n\n\n\n<ul><li>CheckPlus</li><li>HelloAndres</li><li>HelloPi</li><li>Microsoft.Quantum.Samples.IsMinus</li><li>Microsoft.Quantum.Samples.IsPlus</li><li>PrepareRandomMessage</li><li>SampleRandomBit</li><li>SayHello</li><li>SetMinus</li><li>SetPlus</li><li>TestPrepareQubits</li></ul>\n\n\n\n### `%package`\n\n`%package` allows you to load nuget packages and makes available any Q# operations defined on them. For example, to use the operations from [Q#'s Quantum Chemistry Library](https://docs.microsoft.com/azure/quantum/user-guide/libraries/chemistry), you must load the [Microsoft.Quantum.Chemistry](https://www.nuget.org/packages/Microsoft.Quantum.Chemistry/) nuget package:\n\n\n```qsharp\n%package Microsoft.Quantum.Chemistry\n```\n\n\n    Adding package Microsoft.Quantum.Chemistry: done!\n\n\n\n\n\n<ul><li>Microsoft.Quantum.Standard::0.15.2101125897</li><li>Microsoft.Quantum.Standard.Visualization::0.15.2101125897</li><li>Microsoft.Quantum.Chemistry::0.15.2101125897</li></ul>\n\n\n\n`%package` returns the list of nuget packages currently loaded and their version.\n\n### `%project`\n\n`%project` allows you to load Q# projects from folders outside the current workspace and makes available any Q# operations defined in them. For example, to use the operations from the [quantum random number generator sample](https://github.com/microsoft/Quantum/tree/rmshaffer/project-reference-samples/samples/getting-started/qrng), you may add a reference to the `.csproj` file in that folder:\n\n\n```qsharp\n%project ../qrng/Qrng.csproj\n```\n\n    Adding reference to project: ../qrng/Qrng.csproj\r\n\n\n\n    Reloading workspace: done!\n\n\n\n\n\n<ul><li>C:\\Users\\cgran\\source\\repos\\microsoft\\quantum\\samples\\getting-started\\qrng\\Qrng.csproj</li></ul>\n\n\n\n`%project` returns the list of Q# projects currently loaded.\n\n### `%version`\n\n`%version` simply returns the current versions of IQ# and of Jupyter Core (a library used by IQ#):\n\n\n```qsharp\n%version\n```\n\n\n<table><thead><tr><th style=\"text-align: start;\">Component</th><th style=\"text-align: start;\">Version</th></tr></thead><tbody><tr><td style=\"text-align: start;\">iqsharp</td><td style=\"text-align: start;\">0.15.2101125897</td></tr><tr><td style=\"text-align: start;\">Jupyter Core</td><td style=\"text-align: start;\">1.5.0.0</td></tr><tr><td style=\"text-align: start;\">.NET Runtime</td><td style=\"text-align: start;\">.NETCoreApp,Version=v3.1</td></tr></tbody></table>\n\n\n\n```qsharp\n\n```\n", "meta": {"hexsha": "cebc6f97524c698c669a58499922b42b519efc9b", "size": 94401, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "samples/getting-started/intro-to-iqsharp/Notebook.ipynb", "max_stars_repo_name": "frtibble/Quantum", "max_stars_repo_head_hexsha": "b675ded6482af3a8eb213b35ebe64b9073568998", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1849, "max_stars_repo_stars_event_min_datetime": "2019-05-06T22:25:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:34:31.000Z", "max_issues_repo_path": "samples/getting-started/intro-to-iqsharp/Notebook.ipynb", "max_issues_repo_name": "frtibble/Quantum", "max_issues_repo_head_hexsha": "b675ded6482af3a8eb213b35ebe64b9073568998", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 217, "max_issues_repo_issues_event_min_datetime": "2019-05-09T02:28:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:18:53.000Z", "max_forks_repo_path": "samples/getting-started/intro-to-iqsharp/Notebook.ipynb", "max_forks_repo_name": "frtibble/Quantum", "max_forks_repo_head_hexsha": "b675ded6482af3a8eb213b35ebe64b9073568998", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 551, "max_forks_repo_forks_event_min_datetime": "2019-05-07T05:20:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:00:56.000Z", "avg_line_length": 49.9212057113, "max_line_length": 3501, "alphanum_fraction": 0.3313312359, "converted": true, "num_tokens": 8675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.08632347188514872, "lm_q1q2_score": 0.04181337058681023}}
{"text": "# **Save this file as studentid1_studentid2_lab#.ipynb**\n(Your student-id is the number shown on your student card.)\n\nE.g. if you work with 3 people, the notebook should be named:\n12301230_3434343_1238938934_lab1.ipynb.\n\n**This will be parsed by a regexp, so please double check your filename.**\n\nBefore you turn this problem in, please make sure everything runs correctly. First, **restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart) and then **run all cells** (in the menubar, select Cell$\\rightarrow$Run All). Note, that **you are not allowed to use Google Colab**.\n\n**Make sure you fill in any place that says `YOUR CODE HERE` or \"YOUR ANSWER HERE\", as well as your names and email adresses below.**\n\n\n\n\n```python\nNAME = \"Philipp Lintl\"\nNAME2 = \"Anca Diana VIcol\"\nEMAIL = \"lintl.philipp@gmail.com\"\nEMAIL2 = \"ancadianavicol@gmail.com\"\n\n```\n\n# Lab 3: Gaussian Processes and Support Vector Machines\n\n### Machine Learning 1, November 2018\n\nNotes on implementation:\n\n* You should write your code and answers in this IPython Notebook: http://ipython.org/notebook.html. If you have problems, please contact your teaching assistant.\n* Please write your answers right below the questions.\n* Among the first lines of your notebook should be \"%pylab inline\". This imports all required modules, and your plots will appear inline.\n* Refer to last week's lab notes, i.e. http://docs.scipy.org/doc/, if you are unsure about what function to use. There are different correct ways to implement each problem!\n* use the provided test boxes to check if your answers are correct\n\n\n```python\n%pylab inline\nplt.rcParams[\"figure.figsize\"] = [20,10]\n```\n\n    Populating the interactive namespace from numpy and matplotlib\n\n\n\n```python\n# This cell makes sure that you have all the necessary libraries installed\n\nimport sys\nimport platform\nfrom importlib.util import find_spec, module_from_spec\n\ndef check_newer_version(version_inst, version_nec):\n    version_inst_split = version_inst.split('.')\n    version_nec_split = version_nec.split('.')\n    for i in range(min(len(version_inst_split), len(version_nec_split))):\n        if int(version_nec_split[i]) > int(version_inst_split[i]):\n            return False\n        elif int(version_nec_split[i]) < int(version_inst_split[i]):\n            return True\n    return True\n        \n    \nmodule_list = [('jupyter', '1.0.0'), \n               ('matplotlib', '2.0.2'), \n               ('numpy', '1.13.1'), \n               ('python', '3.6.2'), \n               ('sklearn', '0.19.0'), \n               ('scipy', '0.19.1'), \n               ('nb_conda', '2.2.1')]\n\npackages_correct = True\npackages_errors = []\n\nfor module_name, version in module_list:\n    if module_name == 'scikit-learn':\n        module_name = 'sklearn'\n    if module_name == 'pyyaml':\n        module_name = 'yaml'\n    if 'python' in module_name:\n        python_version = platform.python_version()\n        if not check_newer_version(python_version, version):\n            packages_correct = False\n            error = f'Update {module_name} to version {version}. Current version is {python_version}.'\n            packages_errors.append(error) \n            print(error)\n    else:\n        spec = find_spec(module_name)\n        if spec is None:\n            packages_correct = False\n            error = f'Install {module_name} with version {version} or newer, it is required for this assignment!'\n            packages_errors.append(error) \n            print(error)\n        else:\n            x = __import__(module_name)\n            if hasattr(x, '__version__') and not check_newer_version(x.__version__, version):\n                packages_correct = False\n                error = f'Update {module_name} to version {version}. Current version is {x.__version__}.'\n                packages_errors.append(error) \n                print(error)\n\ntry:\n    from google.colab import drive\n    packages_correct = False\n    error = \"\"\"Please, don't use google colab!\nIt will make it much more complicated for us to check your homework as it merges all the cells into one.\"\"\"\n    packages_errors.append(error) \n    print(error)\nexcept:\n    pass\n\npackages_errors = '\\n'.join(packages_errors)\n```\n\n## Part 1: Gaussian Processes\n\nFor part 1 we will be refer to Bishop sections 6.4.2 and 6.4.3. You may also want to refer to Rasmussen's Gaussian Process text which is available online at http://www.gaussianprocess.org/gpml/chapters/ and especially to the project found at https://www.automaticstatistician.com/index/ by Ghahramani for some intuition in GP.  To understand Gaussian processes, it is highly recommended understand how marginal, partitioned Gaussian distributions can be converted into conditional Gaussian distributions.  This is covered in Bishop 2.3 and summarized in Eqns 2.94-2.98.\n$\\newcommand{\\bt}{\\mathbf{t}}$\n$\\newcommand{\\bx}{\\mathbf{x}}$\n$\\newcommand{\\by}{\\mathbf{y}}$\n$\\newcommand{\\bw}{\\mathbf{w}}$\n$\\newcommand{\\ba}{\\mathbf{a}}$\n\n### Periodic Data\n\nWe will use the same data generating function that we used previously for regression.\n\n\n```python\ndef true_mean_function(x):\n    return np.sin(2*pi*(x+1))\n\ndef add_noise(y, sigma):\n    return y + sigma*np.random.randn(len(y))\n\ndef generate_t(x, sigma):\n    return add_noise(true_mean_function(x), sigma)\n\n```\n\n\n```python\nsigma = 0.2\nbeta  = 1.0 / pow(sigma, 2)\nN_test = 100\n\nx_test = np.linspace(-1, 1, N_test) \nmu_test = np.zeros(N_test)\ny_test = true_mean_function(x_test)\nt_test = add_noise(y_test, sigma)\n\nplt.plot( x_test, y_test, 'b-', lw=2)\nplt.plot( x_test, t_test, 'go')\nplt.show()\n```\n\n### 1. Sampling from the Gaussian process prior (30 points)\nWe will implement Gaussian process regression using the kernel function in Bishop Eqn. 6.63.  \n\n#### 1.1 Why kernel function? (5 points)\n\nBefore implementing kernel function, it would be useful to understand why kernels are crucial for high dimensional data. Why are kernels useful when you are dealing with high dimensional data?\n\n- In GENERAL: Kernel methods allow for much more complex decision boundaries within the infinite dimensional space it is acting. Also, by projecting into even more high dimensional space, it becomes much more likely to actually represent the datapoints in a way, they are linearly separable, which is advantageous (Covers Theorem). \n\n- For HIGH-DIM Data: Within the process, a Kernel martix K $\\in \\mathbb{R}^{N\\times N}$  is constructed, whereas N is the number of training points. Compared to the number of dimensions for some very high dimensional data situation (Number of features D $>>N$), this will decrease training complexity. However, if the number of training instances N gets very large, the gains are limited. \n\n#### 1.2 k_n_m( xn, xm, thetas ) (5 points)\nTo start, implement function `k_n_m(xn, xm, thetas)` that takes scalars $x_n$ and $x_m$, and a vector of $4$ thetas, and computes the kernel function Bishop Eqn. 6.63 (10 points).  NB: usually the kernel function will take $D$ by $1$ vectors, but since we are using a univariate problem, this makes things easier.\n\n\n```python\ndef k_n_m(xn, xm, thetas):\n    norm_x = (xn - xm)**2\n    k = thetas[0]*np.exp(-(thetas[1]/2)*norm_x)+thetas[2]+thetas[3]*xn*xm\n    return k\n```\n\n\n```python\n# DO NOT REMOVE THIS CELL!\n# It contains hidden tests\n\n```\n\n#### 1.3 computeK( X1, X2, thetas ) (10 points)\nEqn 6.60 is the marginal distribution of mean output of $N$ data vectors: $p(\\mathbf{y}) = \\mathcal{N}(0, \\mathbf{K})$.  Notice that the expected mean function is $0$ at all locations, and that the covariance is a $N$ by $N$ kernel matrix $\\mathbf{K}$.  Write a function `computeK(x1, x2, thetas)`\nthat computes the kernel matrix. Use k_n_m as part of an inner loop (of course, there are more efficient ways of computing the kernel function making better use of vectorization, but that is not necessary) (5 points).  \n\n\n```python\ndef computeK(x1, x2, thetas):\n    \n    K = [[k_n_m(i, j, thetas) for j in x2] for i in x1] \n    K = np.array(K)\n    return K\n```\n\n\n```python\n### Test your function\nx1 = [0, 1, 2]\nx2 = [1, 2, 3, 4]\nthetas = [1, 2, 3, 4]\nK = computeK(x1, x2, thetas)\n\n\nassert K.shape == (len(x1), len(x2)), \"the shape of K is incorrect\"\n\n```\n\n#### 1.4 Plot function samples (15 points)\nNow sample mean functions at the x_test locations for the theta values in Bishop Figure 6.5, make a figure with a 2 by 3 subplot and make sure the title reflects the theta values (make sure everything is legible).  In other words, sample $\\by_i \\sim \\mathcal{N}(0, \\mathbf{K}_{\\theta})$.  Make use of numpy.random.multivariate_normal().  On your plots include the expected value of $\\by$ with a dashed line and fill_between 2 standard deviations of the uncertainty due to $\\mathbf{K}$ (the diagonal of $\\mathbf{K}$ is the variance of the model uncertainty) (15 points).\n\n\n```python\n# store all theta values in list of lists\nall_thetas = [[1,4,0,0], [9,4,0,0], [1,64,0,0] , [1,0.25,0,0], [1,4,10,0], [1,4,0,5]]\n\ndef make_one_subplot(thetas):\n    # number of x's\n    N = 200\n    # test x's\n    x = np.linspace(-1, 1, N) \n    # compute Kernel Matrix for x with itself\n    K = computeK(x, x, thetas)\n    # uncertainty of \n    var = np.diagonal(K)\n\n    for g in range(4):\n        \n        y = np.random.multivariate_normal(np.zeros(N), K)\n        plt.plot(x, y)\n        # expected y is 0    \n        avg = np.zeros(N)\n        plt.fill_between(x,avg+np.sqrt(var), avg-np.sqrt(var), alpha=0.1)\n        plt.plot(x, avg , linestyle = \"--\")\n    \n    plt.title('Thetas: ' +  str(thetas))\n\nplt.figure(1, figsize = [20,10])\n#fig, ax = plt.subplots(2, 3, figsize=[18,8])\n\nrandom.seed(42)\n\nfor i in range(2):\n    for j in range(3):\n        ind = 231 + i*3 +j\n        plt.subplot(ind)\n        make_one_subplot(all_thetas[i * 3 +j])\n        \nplt.show()\n\n\n```\n\n### 2. Predictive distribution (35 points)\nSo far we have sampled mean functions from the prior.  We can draw actual data $\\bt$ two ways.  The first way is generatively, by first sampling $\\by | \\mathbf{K}$, then sampling $\\bt | \\by, \\beta$ (Eqns 6.60 followed by 6.59).  The second way is to integrate over $\\by$ (the mean draw) and directly sample $\\bt | \\mathbf{K}, \\beta$ using Eqn 6.61.    This is the generative process for $\\bt$.  Note that we have not specified a distribution over inputs $\\bx$;  this is because Gaussian processes are conditional models.  Because of this we are free to generate locations $\\bx$ when playing around with the GP; obviously a dataset will give us input-output pairs.\n\nOnce we have data, we are interested in the predictive distribution (note: the prior is the predictive distribution when there is no data).  Consider the joint distribution for $N+1$ targets, given by Eqn 6.64.  Its covariance matrix is composed of block components $C_N$, $\\mathbf{k}$, and $c$.  The covariance matrix $C_N$ for $\\bt_N$ is $C_N = \\mathbf{K}_N + \\beta^{-1}\\mathbf{I}_N$.  We have just made explicit the size $N$ of the matrix; $N$ is the number of training points.  The kernel vector $\\mathbf{k}$ is a $N$ by $1$ vector of kernel function evaluations between the training input data and the test input vector.  The scalar $c$ is a kernel evaluation at the test input.\n\n#### 2.1 gp_predictive_distribution(...) (10 points)\nWrite a function `gp_predictive_distribution(x_train, t_train, x_test, theta, beta, C=None)` that computes  Eqns 6.66 and 6.67, except allow for an arbitrary number of test points (not just one) and now the kernel matrix is for training data.  By having C as an optional parameter, we can avoid computing it more than once (for this problem it is unimportant, but for real problems this is an issue).  The function should compute $\\mathbf{C}$, $\\mathbf{k}$, and return the mean, variance and $\\mathbf{C}$.  Do not forget: the computeK function computes $\\mathbf{K}$, not $\\mathbf{C}$.(10 points)\n\n\n```python\n# change it for to compute for more than one x\ndef compute_more_K(x_1, x_2, theta):\n    K = []\n    for x1 in x_1:\n            K.append(compute_pair_K(x1,x_2, theta))\n            \n    print(np.array(K))        \n    return np.array(K)\n\ndef gp_predictive_distribution(x_train, t_train, x_test, theta, beta, C = None):\n    \n    K = computeK(x_train, x_train, theta)\n    \n    k = computeK(x_train, x_test, theta)  \n    \n    k_transpose = np.transpose(k)\n\n    N = len(x_train)\n\n    if C is None: \n        C = K + (1/beta) * np.identity(N)\n        \n    C_inverse = np.linalg.inv(C)\n\n    k_test = computeK(x_test, x_test, theta)\n    \n    c = k_test + (1/beta)*np.identity(len(x_test))\n              \n    mean_test = k_transpose @ C_inverse @ t_train\n    covar_test = c -  k_transpose @ C_inverse @ k \n    \n    return mean_test, covar_test, C\n\n```\n\n\n```python\n### Test your function\nN = 2\ntrain_x = np.linspace(-1, 1, N)\ntrain_t = 2*train_x\ntest_N = 3\ntest_x = np.linspace(-1, 1, test_N) \ntheta = [1, 2, 3, 4]\nbeta = 25\ntest_mean, test_covar, C = gp_predictive_distribution(train_x, train_t, test_x, theta, beta, C=None)\n\n\nassert test_mean.shape == (test_N,), \"the shape of mean is incorrect\"\nassert test_covar.shape == (test_N, test_N), \"the shape of var is incorrect\"\nassert C.shape == (N, N), \"the shape of C is incorrect\"\n\nC_in = np.array([[0.804, -0.098168436], [-0.098168436, 0.804]])\n_, _, C_out = gp_predictive_distribution(train_x, train_t, test_x, theta, beta, C=C_in)\n\nassert np.allclose(C_in, C_out), \"C is not reused!\"\n\n```\n\n#### 2.2 gp_log_likelihood(...) (10 points)\nTo learn the hyperparameters, we would need to compute the log-likelihood of the of the training data.  Implicitly, this is conditioned on the value setting for $\\mathbf{\\theta}$.  Write a function `gp_log_likelihood(x_train, t_train, theta, C=None, invC=None, beta=None)`, where C and invC can be stored and reused. It should return the log-likelihood, `C` and `invC`  (10 points)\n\n\n```python\ndef gp_log_likelihood(x_train, t_train, theta, beta, C=None, invC=None):\n    \n    N = len(x_train)\n    \n    if C is None: \n        K = computeK(x_train, x_train, theta)\n        C = K + (1/beta) * np.identity(len(x_train))        \n    if invC is None:\n        invC = np.linalg.inv(C)\n    \n    lnCn = np.log(np.linalg.det(C))\n    tt_cn_t = np.transpose(t_train) @ invC @ t_train\n    \n    lp = -(1/2)* lnCn -(1/2) * tt_cn_t -(N/2) * np.log(2*math.pi) \n            \n    return lp, C, invC\n```\n\n\n```python\n### Test your function\nN = 2\ntrain_x = np.linspace(-1, 1, N)\ntrain_t = 2 * train_x\ntheta = [1, 2, 3, 4]\nbeta = 25\nlp, C, invC = gp_log_likelihood(train_x, train_t, theta, beta, C=None, invC=None)\n\nassert lp < 0, \"the log-likelihood should be smaller than 0\"\nassert C.shape == (N, N), \"the shape of var is incorrect\"\nassert invC.shape == (N, N), \"the shape of C is incorrect\"\n\nC_in = np.array([[0.804, -0.098168436], [-0.098168436, 0.804]])\n_, C_out, _ = gp_log_likelihood(train_x, train_t, theta, beta, C=C_in, invC=None)\n\nassert np.allclose(C_in, C_out), \"C is not reused!\"\n\ninvC_in = np.array([[1.26260453, 0.15416407], [0.15416407, 1.26260453]])\n_, _, invC_out = gp_log_likelihood(train_x, train_t, theta, beta, C=None, invC=invC_in)\n\nassert np.allclose(invC_in, invC_out), \"invC is not reused!\"\n\n```\n\n#### 2.3 Plotting (10 points)\nRepeat the 6 plots above, but this time conditioned on the training points.  Use the periodic data generator to create 2 training points where x is sampled uniformly between $-1$ and $1$.  For these plots, feel free to use the provided function \"gp_plot\".  Make sure you put the parameters in the title and this time also the log-likelihood. Try to understand the two types of uncertainty!  If you do not use `gp_plot(...)`, please add a fill between for the model and target noise. (10 points)\n\n\n```python\ndef gp_plot( x_test, y_test, mean_test, covar_test, x_train, t_train, theta, beta ):\n    # x_test: \n    # y_test:    the true function at x_test\n    # mean_test: predictive mean at x_test\n    # var_test:  predictive covariance at x_test \n    # t_train:   the training values\n    # theta:     the kernel parameters\n    # beta:      the precision (known)\n    \n    # the reason for the manipulation is to allow plots separating model and data stddevs.\n    std_total = np.sqrt(np.diag(covar_test))       # includes all uncertainty, model and target noise \n    std_model = np.sqrt(std_total**2 - 1.0/beta) # remove data noise to get model uncertainty in stddev\n    std_combo = std_model + np.sqrt(1.0/beta)    # add stddev (note: not the same as full)\n    \n    plt.plot(x_test, y_test, 'b', lw=3)\n    plt.plot(x_test, mean_test, 'k--', lw=2)\n    plt.fill_between(x_test, mean_test+2*std_combo,mean_test-2*std_combo, color='k', alpha=0.25)\n    plt.fill_between(x_test, mean_test+2*std_model,mean_test-2*std_model, color='r', alpha=0.25)\n    plt.plot(x_train, t_train, 'ro', ms=10)\n    \n```\n\n\n```python\nsigma = 0.2\nbeta  = 1.0 / pow(sigma, 2)\n\n\ndef plot_N_train(N):\n   \n    x_train = np.random.uniform(-1, 1, N)    \n\n    y_train = true_mean_function(x_train)\n    t_train = add_noise(y_train, sigma)\n\n    N_test = 100\n    x_test = np.linspace(-1, 1, N_test)\n    y_test = true_mean_function(x_test)\n\n\n    plt.figure(1, figsize = [20,10])\n\n    for i in range(2):\n        for j in range(3):\n            ind = 231 + i*3 +j\n            plt.subplot(ind)\n            mean_test, covar_test, C = gp_predictive_distribution(x_train, t_train, x_test, all_thetas[i*3 + j], beta, C=None)\n            gp_plot(x_test, y_test, mean_test, covar_test, x_train, t_train, all_thetas[i*3 + j], beta)\n            lp, _, _ = gp_log_likelihood(x_train, t_train, all_thetas[i*3 +j], beta, C)\n            title('Thetas: ' + str(all_thetas[i*3 + j]) + \"  \" + \"log-lik: \" + str(lp))\n\n\n    plt.show()\n    \nrandom.seed(42)\nplot_N_train(2)\n```\n\n#### 2.4 More plotting (5 points)\nRepeat the 6 plots above, but this time conditioned a new set of 10 training points. (5 points)\n\n\n```python\nrandom.seed(42)\nplot_N_train(10)\n```\n\n## Part 2: Support Vector Machines (45 points)\nAs seen in Part 1: Gaussian Processes, one of the significant limitations of many such algorithms is that the kernel function $k(\\bx_n , \\bx_m)$ must be evaluated for all possible pairs $\\bx_n$ and $\\bx_m$ of training points, which can be computationally infeasible during training and can lead to excessive computation times when making predictions for new data points.\nIn Part 2: Support Vector Machines, we shall look at kernel-based algorithms that have sparse solutions, so that predictions for new inputs depend only on the kernel function evaluated at a subset of the training data points. We are using the same notation as in Bishop chapter 7.\n\n### 2.1 Generating a linearly separable dataset (15 points)\na) (5 points) First of all, we are going to create our own 2D toy dataset $X$. The dataset will consists of two i.i.d. subsets $X_1$ and $X_2$, each of the subsets will be sampled from a multivariate Gaussian distribution,\n\n\\begin{align}\nX_1 \\sim &\\mathcal{N}(\\mu_1, \\Sigma_1)\\\\\n&\\text{ and }\\\\\nX_2 \\sim &\\mathcal{N}(\\mu_2, \\Sigma_2).\n\\end{align}\n\nIn the following, $X_1$ will have $N_1=20$ samples and a mean $\\mu_1=(1,1)$. $X_2$ will have $N_2=30$ samples and a mean $\\mu_2=(3,3)$.\n\nPlot the two subsets in one figure, choose two colors to indicate which sample belongs to which subset. In addition you should choose, $\\Sigma_1$ and $\\Sigma_2$ in a way that the two subsets become linearly separable. (Hint: Which form has the covariance matrix for a i.i.d. dataset?)\n\n\n```python\ndef create_X_1_and_2():\n    #np.random.seed(1234)\n    N1 = 20\n    N2 = 30\n    mu1 = [1, 1]\n    mu2 = [3, 3]\n    var1 = 0.1\n    var2 = 0.3\n    sigma1 = [[var1, 0], [0, var1]]\n    sigma2 = [[var2, 0], [0, var2]]\n\n    X1 = np.random.multivariate_normal(mu1, sigma, (N1))\n    X2 = np.random.multivariate_normal(mu2, sigma, (N2))\n    \n    return X1, X2\n\ndef plot_dataset(X, t):\n    plt.scatter(X.T[0], X.T[1], c=t)\n    \n#(X1, X2) = create_X_1_and_2()\n#plot_dataset(X1, numpy.ones(len(X1)))\n#plot_dataset(X2, -1 * numpy.ones(len(X2)))\n```\n\nb) (10 points) In the next step we will combine the two datasets X_1, X_2 and generate a vector `t` containing the labels. Write a function `create_X_and_t(X1, X2)` it should return the combined data set X and the corresponding target vector t.\n\n\n```python\ndef create_X_and_t(X1, X2):\n    X = []\n    t = []\n    dataset = [X1, X2]\n    indexes = [0, 0]\n    while True:\n        choice = np.round(np.random.randint(0, 2))\n        if indexes[choice] < len(dataset[choice]):\n            X += [dataset[choice][indexes[choice]]]\n            t += [1 * choice - 1 * (1 - choice)]\n            indexes[choice] += 1\n        if indexes[0] >= len(X1) and indexes[1] >= len(X2):\n            break\n            \n    return np.array(X), np.array(t) \n\n(X1, X2) = create_X_1_and_2()\nX, t = create_X_and_t(X1, X2)\nplot_dataset(X, t)\n```\n\n\n```python\n### Test your function\ndim = 2\nN1_test = 3\nN2_test = 4\nX1_test = np.arange(6).reshape((N1_test, dim))\nX2_test = np.arange(8).reshape((N2_test, dim))\nX_test, t_test = create_X_and_t(X1_test, X2_test)\n\n\nassert X_test.shape == (N1_test + N2_test, dim), \"the shape of X is incorrect\"\nassert t_test.shape == (N1_test + N2_test,), \"the shape of t is incorrect\"\n\n```\n\n### 2.2 Finding the support vectors (15 points)\nFinally we going to use a SVM to obtain the decision boundary for which the margin is maximized. We have to solve the optimization problem\n\n\\begin{align}\n\\arg \\min_{\\bw, b} \\frac{1}{2} \\lVert \\bw \\rVert^2,\n\\end{align}\n\nsubject to the constraints\n\n\\begin{align}\nt_n(\\bw^T \\phi(\\bx_n) + b) \\geq 1, n = 1,...,N.\n\\end{align}\n\nIn order to solve this constrained optimization problem, we introduce Lagrange multipliers $a_n \\geq 0$. We obtain the dual\nrepresentation of the maximum margin problem in which we maximize\n\n\\begin{align}\n\\sum_{n=1}^N a_n - \\frac{1}{2}\\sum_{n=1}^N\\sum_{m=1}^N a_n a_m t_n t_m k(\\bx_n, \\bx_m),\n\\end{align}\n\nwith respect to a subject to the constraints\n\n\\begin{align}\na_n &\\geq 0, n=1,...,N,\\\\\n\\sum_{n=1}^N a_n t_n &= 0.\n\\end{align}\n\nThis takes the form of a quadratic programming problem in which we optimize a quadratic function of $\\mathbf{a}$, subject to a set of inequality constraints.\n\n\n\na) (5 points) In this example we will use a linear kernel $k(\\bx, \\bx') = \\bx^T\\bx'$. Write a function `computeK(X)` that computes the kernel matrix $K$ for the 2D dataset $X$.\n\n\n```python\ndef computeK(X):    \n    return X @ np.transpose(X)\n```\n\n\n```python\ndim = 2\nN_test = 3\nX_test = np.arange(2, 8).reshape((N_test, dim))\nK_test = computeK(X_test)\n\n\nassert K_test.shape == (N_test, N_test)\n\n```\n\nNext, we will rewrite the dual representation so that we can make use of computationally efficient vector-matrix multiplication. The objective becomes\n\n\\begin{align}\n\\min_{\\ba} \\frac{1}{2} \\ba^T K' \\ba - 1^T\\ba,\n\\end{align}\n\nsubject to the constraints\n\n\\begin{align}\na_n &\\geq 0, n=1,...,N,\\\\\n\\bt^T\\ba &= 0.\n\\end{align}\n\nWhere\n\\begin{align}\nK'_{nm} = t_n t_m k(\\bx_n, \\bx_m),\n\\end{align}\nand in the special case of a linear kernel function,\n\\begin{align}\nK'_{nm} = t_n t_m k(\\bx_n, \\bx_m) = k(t_n \\bx_n, t_m \\bx_m).\n\\end{align}\n\nTo solve the quadratic programming problem we will use a python module called cvxopt. You first have to install the module in your virtual environment (you have to activate it first), using the following command:\n\n`conda install -c anaconda cvxopt`\n\nThe quadratic programming solver can be called as\n\n`cvxopt.solvers.qp(P, q[, G, h[, A, b[, solver[, initvals]]]])`\n\nThis solves the following problem,\n\n\\begin{align}\n\\min_{\\bx} \\frac{1}{2} \\bx^T P \\bx + q^T\\bx,\n\\end{align}\n\nsubject to the constraints,\n\n\\begin{align}\nG\\bx &\\leq h,\\\\\nA\\bx &= b.\n\\end{align}\n\nAll we need to do is to map our formulation to the cvxopt interface.\n\nb) (10 points) Write a function `compute_multipliers(X, t)` that solves the quadratic programming problem using the cvxopt module and returns the lagrangian multiplier for every sample in the dataset. \n\n\n```python\nimport cvxopt\n\ndef compute_multipliers(X, t):    \n    N = len(X)\n    K = computeK(X)\n    \n    P = cvxopt.matrix(K, tc='d')\n    q = cvxopt.matrix(np.ones((N, 1)), tc='d')\n    G = cvxopt.matrix(-1 * np.identity(N), tc='d')\n    h = cvxopt.matrix(np.zeros((N, 1)), tc='d')\n    A =  cvxopt.matrix(t.reshape(1, N), tc='d')\n    b =  cvxopt.matrix([[0]], tc='d')\n    sol = cvxopt.solvers.qp(P, q, G, h, A, b)\n    a = np.array(sol['x'])\n    return a\n```\n\n\n```python\n### Test your function\ndim = 2\nN_test = 3\nX_test = np.arange(2, 8).reshape((N_test, dim))\nt_test = np.array([-1., 1., 1.])\na_test = compute_multipliers(X_test, t_test)\n\n\nassert a_test.shape == (N_test, 1)\n\n```\n\n         pcost       dcost       gap    pres   dres\n     0: -1.2064e-01  1.4615e-01  4e+00  2e+00  1e+00\n     1:  2.1251e-02 -1.1827e-03  2e-01  8e-02  4e-02\n     2:  3.5039e-03 -1.5844e-04  4e-03  1e-17  4e-16\n     3:  4.2438e-05 -2.7429e-08  4e-05  3e-19  3e-16\n     4:  4.2415e-07 -2.7435e-12  4e-07  7e-21  0e+00\n     5:  4.2415e-09 -2.7435e-16  4e-09  6e-23  2e-16\n    Optimal solution found.\n\n\n### 2.3 Plot support vectors (5 points)\nNow that we have obtained the lagrangian multipliers $\\ba$, we use them to find our support vectors. Repeat the plot from 2.1, this time use a third color to indicate which samples are the support vectors.\n\n\n```python\n(X1, X2) = create_X_1_and_2()\nX, t = create_X_and_t(X1, X2)\n\na = compute_multipliers(X, t)\nprint(a)\na_aux = np.array([i if i == 0 else 1 for i in a])\nprint(a_aux.shape)\nprint(t.shape)\nprint(np.multiply(t, a_aux))\nplot_dataset(X, np.multiply(t, a_aux))\n\n\n```\n\n### 2.4 Plot the decision boundary (10 Points)\nThe decision boundary is fully specified by a (usually very small) subset of training samples, the support vectors. Make use of\n\n\\begin{align}\n\\bw &= \\sum_{n=1}^N a_n t_n \\mathbf{\\phi}(\\bx_n)\\\\\nb &= \\frac{1}{N_S}\\sum_{n \\in S} (t_n - \\sum_{m \\in S} a_m t_m k(\\bx_n, \\bx_m)),\n\\end{align}\n\nwhere $S$ denotes the set of indices of the support vectors, to calculate the slope and intercept of the decision boundary. Generate a last plot that contains the two subsets, support vectors and decision boundary.\n\n\n```python\n# YOUR CODE HERE\nraise NotImplementedError()\n\n```\n", "meta": {"hexsha": "a97ee21e2df4bbe7dcdadc266927154a22834d39", "size": 778173, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Machine Learning 1/lab3.ipynb", "max_stars_repo_name": "PhilLint/Master", "max_stars_repo_head_hexsha": "c7bc03273c24411575e34c98d768408a14d17a3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-20T20:02:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-20T20:02:20.000Z", "max_issues_repo_path": "Machine Learning 1/lab3.ipynb", "max_issues_repo_name": "PhilLint/Master", "max_issues_repo_head_hexsha": "c7bc03273c24411575e34c98d768408a14d17a3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Machine Learning 1/lab3.ipynb", "max_forks_repo_name": "PhilLint/Master", "max_forks_repo_head_hexsha": "c7bc03273c24411575e34c98d768408a14d17a3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 484.8429906542, "max_line_length": 284884, "alphanum_fraction": 0.9397190599, "converted": true, "num_tokens": 7679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22000710997428735, "lm_q2_score": 0.1895210844630953, "lm_q1q2_score": 0.041695986071918406}}
{"text": "##### Copyright 2020 The OpenFermion Developers\n\n\n```python\n#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# Circuits 1: Compiling arbitrary single-particle basis rotations in linear depth\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n  <td>\n    <a target=\"_blank\" href=\"https://www.example.org/openfermion/tutorials/circuits_1_basis_change\">View on QuantumLib</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/OpenFermion/blob/master/docs/tutorials/circuits_1_basis_change.ipynb\">Run in Google Colab</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://github.com/quantumlib/OpenFermion/blob/master/docs/tutorials/circuits_1_basis_change.ipynb\">View source on GitHub</a>\n  </td>\n  <td>\n    <a href=\"https://storage.googleapis.com/tensorflow_docs/OpenFermion/docs/tutorials/circuits_1_basis_change.ipynb\">Download notebook</a>\n  </td>\n</table>\n\nThis is the first of several tutorials demonstrating the compilation of quantum circuits. These tutorials build on one another and should be studied in order. In this tutorial we will discuss the compilation of circuits for implementing arbitrary rotations of the single-particle basis of an electronic structure simulation. As an example, we show how one can use these methods to simulate the evolution of an arbitrary non-interacting fermion model.\n\n## Setup\n\nInstall the OpenFermion package:\n\n\n```python\ntry:\n    import openfermion\nexcept ImportError:\n    !pip install git+https://github.com/quantumlib/OpenFermion.git@master#egg=openfermion\n```\n\n## Background\n\n### Second quantized fermionic operators\n\nIn order to represent fermionic systems on a quantum computer one must first discretize space. Usually, one expands the many-body wavefunction in a basis of spin-orbitals $\\varphi_p = \\varphi_p(r)$ which are single-particle basis functions. For reasons of spatial efficiency, all NISQ (and even most error-corrected) algorithms for simulating fermionic systems focus on representing operators in second-quantization. Second-quantized operators are expressed using the fermionic creation and annihilation operators, $a^\\dagger_p$ and $a_p$. The action of $a^\\dagger_p$ is to excite a fermion in spin-orbital $\\varphi_p$ and the action of $a_p$ is to annihilate a fermion from spin-orbital $\\varphi_p$. Specifically, if electron $i$ is represented in a space of spin-orbitals $\\{\\varphi_p(r_i)\\}$ then $a^\\dagger_p$ and $a_p$ are related to Slater determinants through the equivalence,\n$$\n\\langle r_0 \\cdots r_{\\eta-1} | a^\\dagger_{0} \\cdots a^\\dagger_{\\eta-1} | \\varnothing\\rangle \\equiv \\sqrt{\\frac{1}{\\eta!}}\n\\begin{vmatrix}\n\\varphi_{0}\\left(r_0\\right) & \\varphi_{1}\\left( r_0\\right) & \\cdots & \\varphi_{\\eta-1} \\left( r_0\\right) \\\\\n\\varphi_{0}\\left(r_1\\right) & \\varphi_{1}\\left( r_1\\right) & \\cdots & \\varphi_{\\eta-1} \\left( r_1\\right) \\\\\n\\vdots & \\vdots & \\ddots & \\vdots\\\\\n\\varphi_{0}\\left(r_{\\eta-1}\\right) & \\varphi_{1}\\left(r_{\\eta-1}\\right) & \\cdots & \\varphi_{\\eta-1} \\left(r_{\\eta-1}\\right) \\end{vmatrix}\n$$\nwhere $\\eta$ is the number of electrons in the system, $|\\varnothing \\rangle$ is the Fermi vacuum and $\\varphi_p(r)=\\langle r|\\varphi_p \\rangle$ are the single-particle orbitals that define the basis. By using a basis of Slater determinants, we ensure antisymmetry in the encoded state.\n\n### Rotations of the single-particle basis\n\nVery often in electronic structure calculations one would like to rotate the single-particle basis. That is, one would like to generate new orbitals that are formed from a linear combination of the old orbitals. Any particle-conserving rotation of the single-particle basis can be expressed as\n$$\n\\tilde{\\varphi}_p = \\sum_{q} \\varphi_q u_{pq}\n\\quad\n\\tilde{a}^\\dagger_p = \\sum_{q} a^\\dagger_q u_{pq}\n\\quad\n\\tilde{a}_p = \\sum_{q} a_q u_{pq}^*\n$$\nwhere $\\tilde{\\varphi}_p$, $\\tilde{a}^\\dagger_p$, and $\\tilde{a}^\\dagger_p$ correspond to spin-orbitals and operators in the rotated basis and $u$ is an $N\\times N$ unitary matrix. From the Thouless theorem, this single-particle rotation\nis equivalent to applying the $2^N \\times 2^N$ operator\n$$\n  U(u) = \\exp\\left(\\sum_{pq} \\left[\\log u \\right]_{pq} \\left(a^\\dagger_p a_q - a^\\dagger_q a_p\\right)\\right) \n$$\nwhere $\\left[\\log u\\right]_{pq}$ is the $(p, q)$ element of the matrix $\\log u$.\n\nThere are many reasons that one might be interested in performing such basis rotations. For instance, one might be interested in preparing the Hartree-Fock (mean-field) state of a chemical system, by rotating from some initial orbitals (e.g. atomic orbitals or plane waves) into the molecular orbitals of the system. Alternatively, one might be interested in rotating from a basis where certain operators are diagonal (e.g. the kinetic operator is diagonal in the plane wave basis) to a basis where certain other operators are diagonal (e.g. the Coulomb operator is diagonal in the position basis). Thus, it is a very useful thing to be able to apply circuits corresponding to $U(u)$ on a quantum computer in low depth.\n\n### Compiling linear depth circuits to rotate the orbital basis\n\nOpenFermion prominently features routines for implementing the linear depth / linear connectivity basis transformations described in [Phys. Rev. Lett. 120, 110501](https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.120.110501). While we will not discuss this functionality here, we also support routines for compiling the more general form of these transformations which do not conserve particle-number, known as a Bogoliubov transformation, using routines described in [Phys. Rev. Applied 9, 044036](https://journals.aps.org/prapplied/abstract/10.1103/PhysRevApplied.9.044036). We will not discuss the details of how these methods are implemented here and instead refer readers to those papers. All that one needs in order to compile the circuit $U(u)$ using OpenFermion is the $N \\times N$ matrix $u$, which we refer to in documentation as the \"basis_transformation_matrix\". Note that if one intends to apply this matrix to a computational basis state with only $\\eta$ electrons, then one can reduce the number of gates required by instead supplying the $\\eta \\times N$ rectangular matrix that characterizes the rotation of the occupied orbitals only. OpenFermion will automatically take advantage of this symmetry.\n\n## OpenFermion example implementation: exact evolution under tight binding models\nIn this example will show how basis transforms can be used to implement exact evolution under a random Hermitian one-body fermionic operator\n\\begin{equation}\nH = \\sum_{pq} T_{pq} a^\\dagger_p a_q.\n\\end{equation}\nThat is, we will compile a circuit to implement $e^{-i H t}$ for some time $t$. Of course, this is a tractable problem classically but we discuss it here since it is often useful as a subroutine for more complex quantum simulations. To accomplish this evolution, we will use basis transformations. Suppose that $u$ is the basis transformation matrix that diagonalizes $T$. Then, we could implement $e^{-i H t}$ by implementing $U(u)^\\dagger (\\prod_{k} e^{-i \\lambda_k Z_k}) U(u)$ where $\\lambda_k$ are the eigenvalues of $T$. \n\nBelow, we initialize the T matrix characterizing $H$ and then obtain the eigenvalues $\\lambda_k$ and eigenvectors $u_k$ of $T$. We print out the OpenFermion FermionOperator representation of $T$.\n\n\n```python\nimport openfermion\nimport numpy\n\n# Set the number of qubits in our example.\nn_qubits = 3\nsimulation_time = 1.\nrandom_seed = 8317\n\n# Generate the random one-body operator.\nT = openfermion.random_hermitian_matrix(n_qubits, seed=random_seed)\n\n# Diagonalize T and obtain basis transformation matrix (aka \"u\").\neigenvalues, eigenvectors = numpy.linalg.eigh(T)\nbasis_transformation_matrix = eigenvectors.transpose()\n\n# Print out familiar OpenFermion \"FermionOperator\" form of H.\nH = openfermion.FermionOperator()\nfor p in range(n_qubits):\n    for q in range(n_qubits):\n        term = ((p, 1), (q, 0))\n        H += openfermion.FermionOperator(term, T[p, q])\nprint(H)\n```\n\nNow we're ready to make a circuit! First we will use OpenFermion to generate the basis transform $U(u)$ from the basis transformation matrix $u$ by calling the Bogoliubov transform function (named as such because this function can also handle non-particle conserving basis transformations). Then, we'll apply local $Z$ rotations to phase by the eigenvalues, then we'll apply the inverse transformation. That will finish the circuit. We're just going to print out the first rotation to keep things easy-to-read, but feel free to play around with the notebook.\n\n\n```python\nimport openfermion\nimport cirq\n\n# Initialize the qubit register.\nqubits = cirq.LineQubit.range(n_qubits)\n\n# Start circuit with the inverse basis rotation, print out this step.\ninverse_basis_rotation = cirq.inverse(openfermion.bogoliubov_transform(qubits, basis_transformation_matrix))\ncircuit = cirq.Circuit(inverse_basis_rotation)\nprint(circuit)\n\n# Add diagonal phase rotations to circuit.\nfor k, eigenvalue in enumerate(eigenvalues):\n    phase = -eigenvalue * simulation_time\n    circuit.append(cirq.rz(rads=phase).on(qubits[k]))\n\n# Finally, restore basis.\nbasis_rotation = openfermion.bogoliubov_transform(qubits, basis_transformation_matrix)\ncircuit.append(basis_rotation)\n```\n\nFinally, we can check whether our circuit applied to a random initial state with the exact result. Print out the fidelity with the exact result.\n\n\n```python\n# Initialize a random initial state.\ninitial_state = openfermion.haar_random_vector(\n    2 ** n_qubits, random_seed).astype(numpy.complex64)\n\n# Numerically compute the correct circuit output.\nimport scipy\nhamiltonian_sparse = openfermion.get_sparse_operator(H)\nexact_state = scipy.sparse.linalg.expm_multiply(\n    -1j * simulation_time * hamiltonian_sparse, initial_state)\n\n# Use Cirq simulator to apply circuit.\nsimulator = cirq.Simulator()\nresult = simulator.simulate(circuit, qubit_order=qubits,\n                            initial_state=initial_state)\nsimulated_state = result.final_state_vector\n\n# Print final fidelity.\nfidelity = abs(numpy.dot(simulated_state, numpy.conjugate(exact_state)))**2\nprint(fidelity)\n```\n\nThus, we see that the circuit correctly effects the intended evolution. We can now use Cirq's compiler to output the circuit using gates native to near-term devices, and then optimize those circuits. We'll output in QASM 2.0 just to demonstrate that functionality.\n\n\n```python\nxmon_circuit = cirq.google.optimized_for_xmon(circuit)\nprint(xmon_circuit.to_qasm())\n```\n", "meta": {"hexsha": "cea2bb11ed933874776e0ef7affbc81cae2809f5", "size": 15072, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/circuits_1_basis_change.ipynb", "max_stars_repo_name": "Emieeel/OpenFermion", "max_stars_repo_head_hexsha": "c19d9667c5970473893f9bc0183556c4cd354dd7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/tutorials/circuits_1_basis_change.ipynb", "max_issues_repo_name": "Emieeel/OpenFermion", "max_issues_repo_head_hexsha": "c19d9667c5970473893f9bc0183556c4cd354dd7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/tutorials/circuits_1_basis_change.ipynb", "max_forks_repo_name": "Emieeel/OpenFermion", "max_forks_repo_head_hexsha": "c19d9667c5970473893f9bc0183556c4cd354dd7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-11-13T04:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T04:41:01.000Z", "avg_line_length": 47.6962025316, "max_line_length": 1236, "alphanum_fraction": 0.6572452229, "converted": true, "num_tokens": 2832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733338565660004, "lm_q2_score": 0.10230471131390213, "lm_q1q2_score": 0.041672124428112835}}
{"text": "```python\nfrom IPython.core.display import HTML\ndef css_styling():\n    styles = open(\"./styles/custom.css\", \"r\").read()\n    return HTML(styles)\ncss_styling()\n```\n\n\n\n\n<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:100,300,400,500,700,800,900,100italic,300italic,400italic,500italic,700italic,800italic,900italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Arvo:400,700,400italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=PT+Mono' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Shadows+Into+Light' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Philosopher:400,700,400italic,700italic' rel='stylesheet' type='text/css'>\n\n<style>\n\n@font-face {\n    font-family: \"Computer Modern\";\n    src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');\n}\n\n#notebook_panel { /* main background */\n    background: #888;\n    color: #f6f6f6;\n}\n\ndiv #notebook { /* centre the content */\n    background: #fff;\n    color: #333;\n    width: 1200px;\n    margin: auto;\n    padding-left: 0em;\n}\n\n#notebook li { /* More space between bullet points */\nmargin-top:0.8em;\n}\n\ndiv.cell { /* set cell width to about 80 chars */\n    width: 1000px;\n}\n\ndiv.cell.border-box-sizing.code_cell.running {\n    /* draw border around running cells */\n    border: 3px solid #111;\n}\n\n\nh1 {\n    font-family: 'Philosopher', sans-serif;\n}\nh2 {\n    font-family: 'Philosopher', serif;\n}\nh3{\n    font-family: 'Philosopher', serif;\n    font-style: 'italic';\n    margin-top:12px;\n    margin-bottom: 3px;\n}\nh4{\n    font-family: 'Philosopher', serif;\n}\nh5 {\n    font-family: 'Alegreya Sans', sans-serif;\n}\nh6 {\n    font-family: 'PT Mono', sans-serif;\n}\n\ndiv.text_cell_render{\n    font-family: 'Arvo' sans-serif;\n    line-height: 130%;\n    font-size: 115%;\n    width:900px;\n    margin-left:auto;\n    margin-right:auto;\n}\n\n.CodeMirror{\n        font-family: \"PT Mono\";\n                    font-size: 100%;\n            }\n\n.text_cell_render h1 {\n    font-weight: 400;\n    font-size: 64pt;\n    line-height: 100%;\n    color: rgb(12,85,97);\n    margin-bottom: 0.1em;\n    margin-top: 0.1em;\n    display: block;\n}\n.text_cell_render h2 {\n    font-weight: 700;\n    font-size: 24pt;\n    line-height: 100%;\n    color: rgb(171,165,131);\n    margin-bottom: 0.1em;\n    margin-top: 0.1em;\n    display: block;\n}\n\n.text_cell_render h3 {\n    font-style: italic;\n    color: rgb(95,92,72);\n}\n\n.text_cell_render h5 {\n    font-weight: 300;\n    font-size: 16pt;\n    color: grey;\n    font-style: italic;\n    margin-bottom: .1em;\n    margin-top: 0.1em;\n    display: block;\n}\n\n.text_cell_render h6 {\n    font-weight: 300;\n    font-size: 10pt;\n    color: grey;\n    margin-bottom: 1px;\n    margin-top: 1px;\n}\ndiv.cell.code_cell {  /* Group area containing both code and output */\nbackground-color: rgba(171,165,131,0.3);\nborder-radius: 10px; /* rounded borders */\npadding: 1em;\n}\n\n</style>\n\n\n\n\n\n\n# Theory results\n\nThere are a number of key theory results that we need when solving the Riemann problem, written as\n$$\n  \\partial_t {\\bf q} + \\partial_x {\\bf f}({\\bf q}) = {\\bf 0}, \\qquad {\\bf q}(x, t=0) = \\begin{cases} {\\bf q}_l & x < 0, \\\\ {\\bf q}_r & x > 0, \\end{cases}\n$$\nwhere the left and right states ${\\bf q}_{l, r}$ are constant.\n\n## Self similarity\n\nWe need to show that the solution is *self-similar*, which in this case means the solution can be written as a function of one variable, ${\\bf q} \\equiv {\\bf q}(\\xi)$ where $\\xi = x/t$.\n\nFirst, it is obvious that the equation defining the conservation law,\n$$\n  \\partial_t {\\bf q} + \\partial_x {\\bf f}({\\bf q}) = {\\bf 0},\n$$\nis *scale-free*. That is, if we change coordinates by any constant scaling to $t' = a t$ and $x' =  a x$ where $a > 0$, the conservation law is unchanged in form, \n$$\n  \\partial_{t'} {\\bf q} + \\partial_{x'} {\\bf f}({\\bf q}) = {\\bf 0}.\n$$\n\nSecond, we need the initial data to also be scale free. For the Riemann problem this is clearly true: applying the same scaling to the initial data leaves it unchanged.\n\nCombining these results we see that the solution must be scale free so that if $\\xi = x / t$ is constant (so that $x$ and $t$ are scaled in the same way), the solution must be constant. So ${\\bf q} \\equiv {\\bf q}(\\xi)$.\n\nWe will often think of $\\xi$ as a *spatial* coordinate, by considering the result at a fixed time $t = T$, say.\n\n## Differentiable solutions\n\nFor sections of the solution that are differentiable, we can take two steps. First we can write the conservation law in the quasilinear form\n$$\n  \\partial_t {\\bf q} + \\frac{\\partial {\\bf f}}{\\partial {\\bf q}} \\partial_x {\\bf q} = {\\bf 0}.\n$$\nSecond we can use the self-similarity to replace the partial derivatives, using\n$$\n\\begin{align}\n  \\partial_t & = \\frac{\\partial \\xi}{\\partial t} \\partial_{\\xi} & \\partial_x & = \\frac{\\partial \\xi}{\\partial x} \\partial_{\\xi} \\\\\n  & = -\\frac{\\xi}{t} \\partial_{\\xi} & & = \\frac{1}{t} \\partial_{\\xi},\n\\end{align}\n$$\nto get\n$$\n  \\frac{1}{t} \\left( \\frac{\\partial {\\bf f}}{\\partial {\\bf q}} - \\xi \\textrm{Id} \\right) \\partial_{\\xi} {\\bf q} = {\\bf 0}.\n$$\n\nFor $t > 0$ there are two possible cases:\n\n1. $\\partial_{\\xi} {\\bf q} = {\\bf 0}$: the state is *constant*. \n2. $\\xi$ is an eigenvalue of the Jacobian matrix $\\partial {\\bf f} / \\partial {\\bf q}$, and $\\partial_{\\xi} {\\bf q}$ is the eigenvector corresponding to this eigenvalue.\n\nWe note two consequences from this. First, it only makes sense if the eigenvalues of the Jacobian are real. This is one of the requirements of the system being *hyperbolic*: the eigenvalues must be real and the eigenvectors independent. Second, if we denote the eigenvalue by $\\lambda$ and its associated eigenvector by ${\\bf r}$, then we have\n$$\n\\begin{align}\n  && \\lambda({\\bf q}) & = \\xi \\\\\n  \\implies && \\frac{\\partial \\lambda}{\\partial {\\bf q}} \\frac{\\partial {\\bf q}}{\\partial \\xi} & = 1, \n\\end{align}\n$$\nby differentiating with respect to $\\xi$. Then, as $\\partial_{\\xi} {\\bf q}$ is, as noted above, an eigenvector, we write\n$$\n  \\frac{\\partial {\\bf q}}{\\partial \\xi} = \\alpha {\\bf r},\n$$\nand combining the two results determines the proportionality constant $\\alpha$ as\n$$\n  \\alpha = \\left[ {\\bf r} \\cdot \\frac{\\partial \\lambda}{\\partial {\\bf q}} \\right]^{-1}\n$$\nTherefore we have the *ordinary* differential equation for ${\\bf q}$\n$$\n  \\frac{\\partial {\\bf q}}{\\partial \\xi} = \\frac{{\\bf r}}{{\\bf r} \\cdot \\frac{\\partial \\lambda}{\\partial {\\bf q}}}.\n$$\nThis gives a continuous solution for ${\\bf q}$, *provided* that ${\\bf r} \\cdot \\frac{\\partial \\lambda}{\\partial {\\bf q}} \\ne 0$. This is the requirement that the solution across this wave is *genuinely nonlinear*.\n\nA final consequence of this section is the *number* of waves. If the system has size $N$ then there are $N$ eigenvalues, and hence $N$ waves. These will separate constant states, so we expect the solution to consist of $N+1$ constant states separated by $N$ waves.\n\n## Discontinuous solutions\n\nThere remains only one possibility: the solution is not a continuous function of the similarity coordinate $\\xi$. That such solutions may exist is no surprise, as it is true of the initial data. \n\nWhen the solution is discontinuous we must use the weak form\n$$\n  \\frac{\\textrm{d}}{\\textrm{d}t} \\int_{x_l}^{x_r} {\\bf q} \\, \\textrm{d}x = {\\bf f}({\\bf q}(x_l)) - {\\bf f}({\\bf q}(x_r)).\n$$\n\nLet us assume that the solution is discontinuous along the path $X(t)$. Consider the volume close to this discontinuity, so that $x_r$ and $x_l$ remain fixed points, but $x_r - x_l = \\epsilon \\ll 1$. We then split the integrals at the shock, as the data jumps there. In the weak form this gives\n$$\n\\begin{align}\n  && \\frac{\\textrm{d}}{\\textrm{d}t} \\int_{x_l}^{X(t)} {\\bf q} \\, \\textrm{d}x + \\frac{\\textrm{d}}{\\textrm{d}t} \\int_{X(t)}^{x_r} {\\bf q} \\, \\textrm{d}x & = {\\bf f}({\\bf q}(x_l)) - {\\bf f}({\\bf q}(x_r)) \\\\\n  \\implies && \\frac{\\textrm{d}X}{\\textrm{d}t} \\left\\{ {\\bf q} \\left( X(t)_{-}, t \\right) - {\\bf q} \\left( X(t)_{+}, t \\right) \\right\\} + \\int_{x_l}^{x_r} \\frac{\\partial {\\bf q}}{\\partial t} \\, \\textrm{d}x & = {\\bf f}({\\bf q}(x_l)) - {\\bf f}({\\bf q}(x_r)).\n\\end{align}\n$$\nTaking the limit $\\epsilon \\to 0$ the integral vanishes (as the width of the integral is $\\epsilon$) and we have $x_l \\to X(t)_{-}$ and $x_r \\to X(t)_{+}$. We are left with the *Rankine-Hugoniot conditions*\n$$\n  \\frac{\\textrm{d}X}{\\textrm{d}t} \\left[ {\\bf q} \\right] =  \\left[ {\\bf f}({\\bf q}) \\right].\n$$\nHere the notation $\\left[ {\\bf u} \\right]$ means the jump in the quantity ${\\bf u}$ across the discontinuity.\n\nAs the solution must be self-similar, the shock speed must be constant, $\\textrm{d}X / \\textrm{d}t = V_s$, giving the standard form\n$$\n  V_s \\left[ {\\bf q} \\right] =  \\left[ {\\bf f}({\\bf q}) \\right].\n$$\n\n## Summary\n\n1. The solution to the Riemann problem is self-similar.\n2. The solution contains $N+1$ constant states separated by $N$ waves.\n3. The wave may be continuous, in which case it solves an ordinary differential equation determined by eigenvalues and eigenvectors of the Jacobian matrix.\n4. The wave may be discontinuous, in which case it satisfies the Rankine-Hugoniot equations.\n\nThis is not the most general solution covering all cases, but is sufficient for most cases of interest.\n", "meta": {"hexsha": "a67e7106527753533de088a8c2dabb8f484156b4", "size": 15011, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lesson_02_Theory.ipynb", "max_stars_repo_name": "IanHawke/RiemannPython", "max_stars_repo_head_hexsha": "57d6e372861a9c89b15755fb1d6ff9ea8116f6e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2015-08-24T01:24:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T18:26:24.000Z", "max_issues_repo_path": "Lesson_02_Theory.ipynb", "max_issues_repo_name": "IanHawke/RiemannPython", "max_issues_repo_head_hexsha": "57d6e372861a9c89b15755fb1d6ff9ea8116f6e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lesson_02_Theory.ipynb", "max_forks_repo_name": "IanHawke/RiemannPython", "max_forks_repo_head_hexsha": "57d6e372861a9c89b15755fb1d6ff9ea8116f6e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-07-31T17:41:21.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-11T13:50:22.000Z", "avg_line_length": 36.8820638821, "max_line_length": 354, "alphanum_fraction": 0.5040303777, "converted": true, "num_tokens": 2901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22541661583507672, "lm_q2_score": 0.18476750391438243, "lm_q1q2_score": 0.04164966544867438}}
{"text": "--- \n### Project for the course in OSE Data Science | Summer 2021, M.Sc. Economics, Bonn University | Emily Schwab\n\n# Replication of Harounan Kazianga, Dan Levy, Leigh L. Linden, and Matt Sloan  (2013) <a class=\"tocSkip\">   \n---\n\nMy final project for the OSE Data Science course replicates the results published in the following journal article:\n\n> **Kazianga, H., Levy, D., Linden, L. L., & Sloan, M. (2013)**. The Effects of \u201cGirl-Friendly\u201d Schools: Evidence from the BRIGHT School Construction Program in Burkina Faso. *American Economic Journal: Applied Economics*, 5(3), 41-62.\n\nThe published article as well as the project's data set and corresponding code can be accessed [here](https://www.aeaweb.org/articles?id=10.1257/app.5.3.41).\n\n##### How to view this notebook:\n\n* To view this notebook, please download the project's [GitHub repository](https://github.com/OpenSourceEconomics/ose-data-science-course-projeect-s6emschw). Alternatively, it is possible to use _MyBinder_ or _NBViewer_. In the case that the causal graph images located in section 4 of the notebook do not appear while using these alternative viewing options, they are also available in the repository's [files](https://github.com/OpenSourceEconomics/ose-data-science-course-projeect-s6emschw/tree/master/files) folder.\n\n\n---\n# Table of Contents\n---\n1. [Introduction](#introduction)\n2. [The BRIGHT Program](#2)\n3. [Regression Discontinuity Design](#3)\n4. [A Visual Interpretation of the RD Design through Causal Graphs](#4)\n5. [Replication Results](#5)\n    * 5.1. [Description of Data Collection Procedure](#5.1)\n    * 5.2. [Internal Validity of Research Design](#5.2)\n        * 5.2.1. [Measurement of Treatment Differential](#5.2.1)\n        * 5.2.2. [Continuity Checks](#5.2.2)\n        * 5.2.3. [Measured Differences in Educational Infrastructure](#5.2.3)\n    * 5.3. [Estimated Treatment Effects](#5.3)\n        * 5.3.1. [Treatment Effect on Enrollment](#5.3.1)\n        * 5.3.2. [Treatment Effect on Test Scores](#5.3.2)\n    * 5.4. [School Access vs. BRIGHT Amenities](#5.4)\n6. [Project Extensions](#6)\n    * 6.1. [Supplementary Analysis of the Critical Continuity Assumption](#6.1)\n        * 6.1.1 [Initial Analysis of Descriptive Statistics for Control and Treatment Groups](#6.1.1)\n        * 6.1.2. [Visual Analysis of the Continuity Assumption](#6.1.2)\n    * 6.2. [Treatment Effect on Normalized Math and French Test Scores Disaggregated by Gender](#6.2)\n    * 6.3. [Plotting Parametric Regression Results](#6.3)\n        * 6.3.1. [Joint and Separate Regression Discontinuity Plots for the Treatment Effect on Attendance](#6.3.1)\n        * 6.3.2. [Joint and Separate Regression Discontinuity Plots for the Treatment Effect on Normalized Total Test Scores](#6.3.2)\n    * 6.4. [Evaluation of Placebo Thresholds](#6.4)\n        * 6.4.1. [Placebo Tests for the Treatment Effect on School Attendance](#6.4.1)\n        * 6.4.2. [Placebo Tests for the Treatment Effect on Total Test Scores](#6.4.2)\n    * 6.5. [Bandwidth Sensitivity Checks](#6.5)\n7. [Concluding Remarks](#7)\n8. [Bibliography](#8)\n\n\n\n```python\nimport pandas as pd \nimport numpy as np\nimport numpy as geek\n\nimport statsmodels.api as sm\nimport statsmodels.formula.api as smf\nfrom statsmodels.discrete.discrete_model import Probit\n\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import LeaveOneOut\n\nfrom functools import partial\n\nfrom stargazer.stargazer import Stargazer, LineLocation\n#from IPython.display import Image\nfrom IPython.core.display import HTML\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n#import matplotlib as plt\n\nimport warnings;\nwarnings.filterwarnings('ignore');\n\n\nfrom auxiliary.aux_plots import *\nfrom auxiliary.aux_predictions import *\nfrom auxiliary.aux_tables import *\n\n```\n\n---\n# 1. Introduction <a name=\"introduction\"></a>\n---\n\nIn Kazianga et al. (2013), the authors use a regression discontinuity design (RD design) to examine the effects of a \"girl-friendly\" primary school program implemented by the Ministry of Education in Burkina Faso. Despite an increase in primary school enrollment throughout the world, many regions including sub-Saharan Africa are struggling to catch up. As late as 2010, the net primary school enrollment rate in sub-Saharan Africa was 76 percent, approximately 14 percentage points below the average for emerging countries. \n\nAdditionally, Kazianga et al. (2013) point to several possible reasons, why education outcomes for girls are worse compared to those of their male counterparts. In many regions, long commutes make it difficult for students to travel to and from school. This limitation may be particularly difficult for girls to overcome, if their parents are more apprehensive about allowing them to travel. A lack of basic school infrastructure including gender-segregated bathrooms as well as an insufficient supply of female teaching staff pose further restrictions that negatively impact the primary school enrollment rate among girls. \n\nWhile the above issues reflect a potential shortage concerning the economic supply of school facilities, Kazianga et al. (2013) also consider whether the low enrollment rate in regions like sub-Saharan Africa could be a consequence of limited economic demand for educational services - given the relatively minimal returns to educational investments in the region, especially for girls. In addition to evaluating the effects of an education policy program on a number of outcomes including enrollment, test scores, and attendance, Kazianga et al. (2013) contribute insights regarding whether the below average enrollment rate in sub-Saharan Africa is a reflection of low economic supply or of low economic demand. \n\nUsing a scoring procedure to rank villages based on the number of school-aged girls likely to benefit from educational services, the Ministry of Education randomly allocated schools with several girl-friendly amenities and teaching resources to 132 villages. This program, called the  Burkinab\u00e9 Response to Improve Girls\u2019 Chances to Succeed (BRIGHT) program, was announced in 2005.  Due to the randomness of the program's selection procedure, Kazianga et al. (2013) were able to employ an RD design to examine the causal impact of the BRIGHT program. \n\nIn the following project report, I examine the analysis conducted by Kazianga et al. (2013) and replicate their main findings. Section 2 consists of a brief description of the BRIGHT program and its school allocation procedure. Sections 3 and 4 provide an introduction to the basic properties of the RD design. In section 5, I discuss the results of my replication efforts. Section 6 presents a number of robustness checks that I use to further evaluate the main findings of Kazianga et al. (2013). In section 7, I conclude my analysis.  \n\n---\n# 2. The BRIGHT Program <a name=\"2\"></a>\n---\n\nIn an effort to improve academic outcomes in rural regions of Burkina Faso by 1) increasing access to schools and 2) offering unique amenities to encourage enrollment among girls of primary-school age, the BRIGHT program selected 132 villages to participate in its education policy package. The program provided each village with a three-classroom school, housing for three teachers, gender-segregated bathroom facilities, and a source of clean water. The schools were also equipped with student and teacher desks, chairs, metal bookshelves, two multipurpose halls, and a playground. \n\nAdditionally, the BRIGHT program implemented a series of interventions to incentivize children, parents, and teachers. Schools arranged meals for all students each day they were in attendance. Female students were given supplementary food rations to take home each month provided they maintained an attendance rate of 90 percent. Students also received school supplies and textbooks. The program targeted parents by organizing an information campaign about the advantages of education, with emphasis on the particular benefits for girls. It also offered an adult literacy program for mothers as well as capacity building resources to aid local officials. Furthermore, BRIGHT prioritized the placement of female teachers in its schools and coordinated gender sensitivity trainings for teachers as well as ministry representatives.\n\nThe scoring system developed by the Ministry of Education to objectively allocate schools followed a careful procedure, in which 293 villages from 10 provinces and 49 departments (geographically, Burkina Faso is organized into 13 regions, 45 provinces, and 301 departments) were nominated to participate in the BRIGHT program. After each village completed a survey to assess its eligibility as a recipient of a BRIGHT school, the government then scored each village based on the approximate number of children in and around the nominated village, who would likely benefit from the education services offered by the BRIGHT program. Additional weight was also given to primary school-aged girls belonging to the proposed and nearby villages. The villages in each department were then ranked with the top 50 percent of villages receiving a BRIGHT school. Because some villages were later deemed inappropriate locations for the construction of a BRIGHT school (i.e., due to having an insufficient water source), the total number of villages selected for the BRIGHT program and ultimately received a school amounted to 127. Five additional villages that were initially not selected for the BRIGHT program based on their assigned score were later granted a school. Despite this minor discrepancy, the authors' analysis maintains the assumption that the assignment rule was strictly applied. \n\n---\n# 3. Regression Discontinuity Design <a name=\"3\"></a>\n---\n\nUsing an RD design, Kazianga et al. (2013) examine the observations around an arbitrarily assigned cutoff to identify local treatment effects caused by the BRIGHT program's policy interventions. In the following section, I will explain the general properties of the RD design as well as address how Kazianga et al. (2013) implement this approach in their analysis. \n\nThe RD design is a common quasi-experimental evaluation strategy that relies on an independent cutoff to assign observations into treatment and control groups. In a typical RD design individuals just above the cutoff are selected into treatment, while those just below the cutoff comprise the control group. As long as the cutoff is exogenously chosen such that it is not correlated with other factors that potentially influence the main outcome variable(s), the RD design takes advantage of the cutoff's ability to generate two groups that are as good as randomly selected (Cunningham, 2021). This critical assumption of the RD design, referred to in the literature as **continuity**, implies that the researcher can rule out systematic differences between the control and treatment groups. As a result, any measurable outcome differentials observed at the cutoff can be safely attributed to the treatment (Thistlethwaite and Campbell, 1960).\n\nThe potential outcomes framework is an essential concept for further understanding the validity of the RD design. According to the identification strategy's basic setup, there is a treatment variable $T$, which is a discontinuous function of some running variable $X$, \n\n\\begin{equation}\nT_{i}=I\\left\\{X_{i}>c\\right\\},\n\\end{equation}\n\nas well as two potential outcomes, $Y_{0}$ and $Y_{1}$. These potential outcomes exist as two unique, continuous functions that describe the underlying relationship between average outcomes and the running variable, which are characterized as $E[Y_i(1)|X]$ and $E[Y_i(0)|X]$. However, the researcher only observes the true outcome, $Y_i$. For all observations, where the running variable $X$ is below the threshold $c$ and subsequently $T = 0$, the researcher can only observe $E[Y_i(0)|X]$. Observations that exist to the right of the cutoff conversely fall into treatment, where the researcher only has access to $E[Y_i(1)|X]$. Hence, the researcher cannot observe both outcomes simultaneously for any individual in the sample.\n\nIf we consider the limits of either potential outcome function as the running variable approaches the cutoff from the right and from the left, randomness of the treatment assignment indicates that the limits should be equal:   \n\n\\begin{equation}\nlim_{\\epsilon \\downarrow 0}E[Y_i|X_i=c+\\epsilon] = lim_{\\epsilon \\uparrow 0} E[Y_i|X_i=c+\\epsilon]\n\\end{equation}\n\nThat is, the potential outcomes behave continuously at the cutoff, thus indicating that the critical assumption of the RD design holds. Under these circumstances, the RD design is a valid identification strategy, and any discontinuity in the outcome variable at the cutoff is interpreted as a consequence of the treatment (Lee and Lemieux, 2010):  \n\n\\begin{equation}\nlim_{\\epsilon \\downarrow 0}E[Y_i(1)|X_i=c+\\epsilon] - lim_{\\epsilon \\uparrow 0} E[Y_i(0)|X_i=c+\\epsilon] \n\\end{equation}\n\n\\begin{equation}\n= E[Y_i(1)|X=c] - E[Y_i(0)|X=c]\n\\end{equation}\n\n\\begin{equation}\n= E[Y_i(1)-Y_i(0)|X=c].\n\\end{equation}\n  \nReturning to the application of the RD design in Kazianga et al. (2013), the authors produce an independent running variable called $\\text{Rel_Score}_{j}$ based on the survey scores computed for each village. To generate the relative score assigned to each sample village, the authors identified, for each department, the lowest survey score from all villages that were selected to receive a BRIGHT school as well as the highest score from all villages that were not selected. The point of discontinuity for each department was thus determined by computing the halfway point between these two scores. The authors then rescaled the cutoff scores to derive $\\text{Rel_Score}_{j}$, equal to the village's assigned score minus the cutoff score calculated for the department to which the village belongs. As mentioned above, the assignment rule places villages with a $\\text{Rel_Score}_{j}$ larger than zero into treatment. Villages that do not fulfill this criterium become a part of the control group and consequently do not receive a BRIGHT school. Although some villages were assigned a BRIGHT school despite having a $\\text{Rel_Score}_{j}$ less than zero, Kazianga et al. (2013) continue with their analysis as if the assignment rule were strictly carried out and thus apply the following OLS regression to their data set represented here by equation (1): \n\n\\begin{equation}\ny_{i h j k}=\\beta_{0}+\\beta_{1} T_{j}+f\\left(\\text{Rel_Score}_{j}\\right)+\\delta \\mathbf{X}_{i h j k}+\\gamma \\mathbf{Z}_{k}+\\varepsilon_{i h j k},\n\\end{equation} \n\nwhere $i$ identifies the individual child from household $h$ located in village $j$ and department $k$. The dependent variable $y_{i h j k}$ constitutes several outcomes of interest that the authors explore in their analysis including test scores, enrollment, attendance, etc. $T_{j}$ is a binary variable that indicates whether or not a village was assigned into treatment. The authors also incorporate $f\\left(\\text{Rel_Score}_{j}\\right)$ as a polynomial expansion for the relative score. The variable ${X}_{i h j k}$ includes several child and household characteristics, and ${Z}_{k}$ represents department fixed effects. \n\nThis strategy is comparable to fitting a linear regression below the cutoff and another above it. The intercept of the regression below the cutoff is $\\beta_{0}$. In other words, the intercept is equivalent to the expected value at the threshold such that $\\beta_{0} = lim_{\\epsilon \\uparrow 0} E[Y_i|X_i=c+\\epsilon]$. Conversely, the intercept of the regression above the threshold, $\\beta_{0} + \\beta_{1}$, is also the expected value at the threshold as the running variable approaches the cutoff from the right: $lim_{\\epsilon \\downarrow 0} E[Y_i|X_i=c+\\epsilon]$. \n\nFinally, the following solution is obtained (Cunningham, 2021):  \n\n\\begin{equation}\nlim_{\\epsilon \\downarrow 0}E[Y_i(1)|X_i=c+\\epsilon] - lim_{\\epsilon \\uparrow 0} E[Y_i(0)|X_i=c+\\epsilon] = \\beta_{1} = E[ATE|X=c].\n\\end{equation}\n\nFrom this simple linear regression model, the coefficient of interest, $\\beta_{1}$, effectively estimates the average treatment effect at the selected cutoff.    \n\n\n--- \n# 4. A Visual Interpretation of the RD Design through Causal Graphs <a name=\"4\"></a>\n---\n\nTo further understand how the RD design yields such convincing measures of causal effect in many scenarios, I provide an explanation of its properties with the help of a simple data generating graph derived from Cunningham (2021). According to the basic setup of an RD design, treatment is assigned based on an continuous running variable $X$ ($X \\rightarrow T$). Additionally, the running variable may influence the outcome variable directly ($X \\rightarrow Y$) as well as indirectly via one or more observable or unobservable variables represented by $U$ ($X \\rightarrow U \\rightarrow Y$). \n\n#### Graph 1. Data Generating Graph\n\n\nIn this case, the running variable thus produces potential endogeneity biases, as it influences both $T$ and $Y$. Since we also face the dilemma that we cannot simultaneously account for a given observation in both the treatment and in the control group, it is infeasible to use a matching method (Cunningham, 2021). \n\nWe can alternatively use an RD design to eliminate the endogeneity bias and more effectively measure the causal effect of the treatment. To do so, the RD design's continuity assumption eliminates the direct effect the running variable imposes on the $Y$ outcome ($X \\rightarrow Y$). The strength of the RD design is illustrated in Graph 2, which has removed this direct effect by introducing an independent cutoff value, $c$.\n\n#### Graph 2. RD Design \n\n\nConsequently, this identification strategy looks more closely at a subset of observations located just above and just below this threshold in order to simulate random selection of observations into either the treatment or control group. The RD design thus neutralizes any omitted variable bias that may otherwise confound the estimated causal effect (Cunningham, 2021).          \n\n---\n# 5. Replication Results <a name=\"5\"></a>\n---\n\n## 5.1. Description of Data Collection Procedure <a name=\"5.1\"></a>\n\nAfter implementing the BRIGHT program in 2005, a survey was conducted in the spring of 2008 that collected information on school and household characteristics for 293 villages. To conduct the household survey, the research team initially collected census data from the participating villages for all households with children between five and 12 years of age. For each village, 30 households with primary school-aged girls were then randomly chosen for the survey. The selection of households was stratified based on each household's access to a beast of burden - a characteristic that served as an appropriate proxy for wealth to generate a representative sample of households in each village. The three strata include the following household types: \n\n* those that owned at least one beast of burden,\n* those that did not own a beast of burden, but had access to one, and\n* those that neither owned nor had access to one. \n\nTo ensure randomness, ten households were selected by drawing the names of eligible households out of a hat for each stratum (Levy et al., 2009a).  \n\nThe household questionnaire included a series of socio-demographic questions as well as an account of the academic status and background of all children between the ages of five and 12 belonging to each of the surveyed households. The children also completed a test based on math and French language competencies from the government-issued first grade textbook.\n\nThe survey on school characteristics included a maximum of three schools for each village. The data collection team spoke with village elders to identify the number of schools, if any, available for regular attendance by the primary school-aged children living in the respective  village. Data collectors then chose the three closest schools within a 10-kilometer radius of each village center, generating a sample of 370 schools in total. The response rate for the school survey was 99.2 percent, with 367 out of the original 370 schools completing the questionnaire.  The survey documented the availability of several amenities including those provided by the BRIGHT program. It also recorded specific characteristics of each school's physical infrastructure, teaching faculty, and student attendance roster (Levy et al., 2009a). \n\nDue to challenges locating particular villages, the data collection team was unable to survey four of the 293 nominated villages for the household-related part of the survey. Additionally, the authors removed two further villages from the final dataset that were the only ones from their respective departments to have been nominated for a BRIGHT school. For this reason, the research team was unable to compute a relative score for these villages. All children five years of age were also dropped from the final data set due to the fact that primary school attendance in Burkina Faso typically caters to children between the ages of six and 12 years old. After removing the six unavailable villages and all five-year-olds from the original survey report, the final data set included a sample of 287 villages, 8,432 households, and 17,970 children between six and 12 years of age (Levy et al., 2009a).\n\n\n\n```python\ndata = pd.read_stata('data/BRIGHT_Formatted.dta')\ndata.fillna(np.nan, inplace = True)\n```\n\n\n```python\ndata\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Ch_Age</th>\n      <th>Ch_Girl</th>\n      <th>Ch_GirlXMCC_School</th>\n      <th>Ch_GirlXatt</th>\n      <th>Ch_GirlXhas_school</th>\n      <th>Ch_GirlXproj</th>\n      <th>Ch_HeadChild</th>\n      <th>Ch_HeadGrandChild</th>\n      <th>Ch_HeadNephew</th>\n      <th>Ch_Highest_Grade</th>\n      <th>...</th>\n      <th>toilets</th>\n      <th>toilets_gender</th>\n      <th>total_norm</th>\n      <th>village_id</th>\n      <th>village_level</th>\n      <th>water_supply</th>\n      <th>words_easy_norm</th>\n      <th>words_easy_raw</th>\n      <th>words_hard_norm</th>\n      <th>words_hard_raw</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>6.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>-0.121444</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>-0.526749</td>\n      <td>0.0</td>\n      <td>-0.439538</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>5.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>-0.598520</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>-0.526749</td>\n      <td>0.0</td>\n      <td>-0.439538</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>9.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>-0.598520</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>NaN</td>\n      <td>-0.526749</td>\n      <td>0.0</td>\n      <td>-0.439538</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>6.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>-0.598520</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>-0.526749</td>\n      <td>0.0</td>\n      <td>-0.439538</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>12.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>-0.280470</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>-0.526749</td>\n      <td>0.0</td>\n      <td>-0.439538</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>23277</th>\n      <td>9.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>2.0</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.355631</td>\n      <td>82.0</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>-0.526749</td>\n      <td>0.0</td>\n      <td>-0.439538</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>23278</th>\n      <td>6.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>-0.598520</td>\n      <td>82.0</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>-0.526749</td>\n      <td>0.0</td>\n      <td>-0.439538</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>23279</th>\n      <td>7.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>-0.598520</td>\n      <td>82.0</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>-0.526749</td>\n      <td>0.0</td>\n      <td>-0.439538</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>23280</th>\n      <td>10.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>2.0</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.196606</td>\n      <td>82.0</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>-0.526749</td>\n      <td>0.0</td>\n      <td>-0.439538</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>23281</th>\n      <td>6.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>-0.598520</td>\n      <td>82.0</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>-0.526749</td>\n      <td>0.0</td>\n      <td>-0.439538</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>23282 rows \u00d7 115 columns</p>\n</div>\n\n\n\n## 5.2. Internal Validity of Research Design <a name=\"5.2\"></a>\n\nBefore Kazianga et al. (2013) present the estimated treatment effects from the BRIGHT program, they first provide a number of internal validity checks to ensure that the RD design serves as an appropriate identification strategy. As the treatment $T$ is a discontinuous function of the design's running variable $X$, section 5.2.1. replicates Figure 1 and Table 1 of Kazianga et al. (2013), in which the authors confirm the existence of a treatment differential at the cutoff. In section 5.2.2., I reproduce the analysis originally conducted by Kazianga et al. (2013) to verify that their data set fulfills the critical continuity assumption of the RD design. Section 5.2.3. replicates the authors' final validity check, where they evaluate whether the discontinuity in assigned treatment generated a notable difference in the educational infrastructure accessible to children from the control and treatment groups.\n\n### 5.2.1. Measurement of Treatment Differential <a name=\"5.2.1\"></a>\n\n#### Figure 1. Probability of Receiving a BRIGHT Program According to Village's Relative Score\n\nFigure 1 from Kazianga et al. (2013) replicated below uses a nonparametric procedure to estimate a village's probably of receiving a BRIGHT school based on its assigned relative score. While the full range of the relative score variable is (-855.5, 3791), the authors limit their analysis to observations with a relative score between -250 and 250. The probability of receiving a BRIGHT school is located on the left vertical axis, and the horizontal axis represents the restricted range of the relative score. The plot, which is represented by the black curves on either side of the cutoff, was generated by a linear local polynomial estimator with an Epanechnikov kernel and a bandwidth of 60 points. As indicated by the visualization, there is a clear discontinuity of assigned treatment at the cutoff. For those villages with a relative score less than zero, the probability of being selected into treatment is more or less zero. There are, however, a few low estimated probabilities due to the few villages in the final data set that were given a BRIGHT school despite not fulfilling the assignment rule. Observing the villages with a relative score to the right of the cutoff, the probability of receiving a BRIGHT school increases to above 80 percent.    \n\n\n```python\nX_untreated = compute_X_axis(0,-250,100)\nX_treated = compute_X_axis(250,0,100)\n```\n\n\n```python\nselected_columns_graph_1 = [\"selected\", \"proj_selected\", \"rel_score_redefined\",\"rel_score\", \"village_level\"]\n\nrslt_untreated_graph_1 = get_data_graphs(selected_columns_graph_1,1,0)\nrslt_treated_graph_1 = get_data_graphs(selected_columns_graph_1,1,1)\nrslt_graph_1 = get_data_graphs(selected_columns_graph_1,1,2)\n```\n\n\n```python\ny_var_graph_1 = \"selected\"\nx_var_graph_1 = \"rel_score_redefined\"\nbandwidth = 60\n\ncontrol_graph_1 = [compute_locally_weighted_reg(y_var_graph_1,x_var_graph_1,item,bandwidth, rslt_untreated_graph_1) for item in X_untreated]\ntreatment_graph_1 = [compute_locally_weighted_reg(y_var_graph_1,x_var_graph_1,item,bandwidth, rslt_treated_graph_1) \n                     for item in X_treated]\n\ndf_graph_1 = pd.DataFrame()\ndf_graph_1[\"y-axis\"] = control_graph_1 + treatment_graph_1\ndf_graph_1[\"x-axis\"] = X_untreated + X_treated\n```\n\nIn addition to the nonparametric plot described above, Figure 1 contains orange point estimates that represent the average probabilites for 60-point bins to the left and right of the cutoff. These averages closely reflect the results of the linear local polynomial estimator and further indicate a discontinuity of assigned treatment at the cutoff.\n\n\n```python\nbins_rhs_graph_1 = compute_binned_averages(1,\"selected\",60,5,rslt_graph_1)\nbins_lhs_graph_1 = compute_binned_averages(0,\"selected\",60,5,rslt_graph_1) \n```\n\nFollowing a procedure detailed by Card, Mas, and Rothstein (2008), the authors  plot the $R^2$ values estimated for the specification described here in equation (2): \n\n\\begin{equation}\ny_{i h j}=\\alpha_{0}+\\alpha_{1} I_{\\left(\\text {Rel_Score}_{j} \\geq a\\right)}+\\varepsilon_{i h j}\n\\end{equation}\n\nto confirm that the selected cutoff appropriately locates the discontinuity for treatment probability. The plotted $R^2$ values are represented by the blue curve in Figure 1.\n\n\n```python\nR_sq_iterated_df_graph_1 = create_R_sq_df(\"selected\",\"rel_score_redefined\",rslt_graph_1)\n```\n\n\n```python\nylabel_graph_1 = \"Received a BRIGHT School\"\ntitle_graph_1 = \"Figure 1: Probability of Receiving a BRIGHT Program According to Village's Relative Score\"\nplot_discontinuity(ylabel_graph_1, title_graph_1, df_graph_1, bins_lhs_graph_1, bins_rhs_graph_1, \n                   R_sq_iterated_df_graph_1, 1)\n```\n\nAs shown below in the dataframe `arg_maximum_graph_1`, the $R^2$ values  achieve a maximum of approximately 0.815 at a relative score of around 1 or 2. This estimate is consistent with assigned treatment varying discontinuously at zero.\n\n\n```python\narg_maximum_graph_1 = R_sq_iterated_df_graph_1.loc[R_sq_iterated_df_graph_1[\"R-squared Values\"] == max(R_sq_iterated_df_graph_1[\"R-squared Values\"])]\narg_maximum_graph_1\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Xgrid for R-squared Values</th>\n      <th>R-squared Values</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>251</th>\n      <td>1.0</td>\n      <td>0.814778</td>\n    </tr>\n    <tr>\n      <th>252</th>\n      <td>2.0</td>\n      <td>0.814778</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n#### Table 1. Estimated Discontinuity in Probability of a Village Receiving a BRIGHT School\n\nUsing the parametric regression specified in equation (1), the results from Table 1 confirm the size of the discontinuity for treatment probability estimated by the nonparametric plot in Figure 1. According to the preferred quadratic model with department-level fixed effects summarized in column (1), villages with a relative score greater than zero were approximately 87.4 percentage points more likely to be assigned a BRIGHT school. Furthermore, the estimate is statistically significant at the one percent level. While the authors prefer implementing a quadratic expansion of the relative score, they report treatment coefficient estimates for several fitted models including \n\n1. a linear specification, \n2. a cubic polynomial specification, \n3. a quadratic interaction term between the two main regressors (i.e., the treatment indicator variable and the relative score), and \n4. a specification that includes the treatment indicator variable for a subset of villages with a relative score less than 40.\n\nFor each regression, the authors also include controls for deparment-level fixed effects.\n\nDespite these variations in model specification, the coefficient estimate for the treatment indicator variable does not change and remains highly statistically significant. The results reported in both Figure 1 and Table 1 thus provide strong evidence that there exists a sufficient discontinuity in assigned treatment at the defined cutoff. \n\n\n```python\ny_var_table_1 = [\"MCC_School\"]\nX_matrix_table_1 = [\"proj_selected\", \"rel_score\", \"clustercode\"]\ny_table_1,X_table_1= get_data(1,0,0, y_var_table_1, X_matrix_table_1)\n```\n\n\n```python\nfitted_poly_models_table1 = fit_poly_models_iterate(y_table_1, X_table_1, 3, 0)\n```\n\n\n```python\ninteract1 = \"rel_score\"\ninteract2 = \"proj_selected\"\n\nmod_table1_interaction = calculate_polynomial_interaction(0, y_table_1,X_table_1, interact1, interact2, 2)\n```\n\n\n```python\nmod_table1_reduced = calculate_reduced_range_40(0,y_table_1,X_table_1)\n```\n\n\n```python\ntable_1_models = [fitted_poly_models_table1[1],\n                  fitted_poly_models_table1[0],\n                  fitted_poly_models_table1[2],\n                  mod_table1_interaction,\n                  mod_table1_reduced]\n\ntable_1_covariate_list = [\"proj_selected\",\"rel_score1\",\"rel_score2\",\"rel_score3\",\"interaction_term1\",\n                          \"interaction_term2\",\"const\"]\n\ntable_1_title = 'Table 1\u2014Estimated Discontinuity in Probability of a Village Receiving a BRIGHT School'\n\ntable_1_rename_covariates = {'proj_selected': 'Selected for BRIGHT (Rel. Score \u2265 0)',\n                           'rel_score1':'Rel. Score',\n                           'rel_score2':'Rel. Score ^ 2',\n                           'rel_score3':'Rel. Score ^ 3',\n                           'interaction_term1':'Rel. Score x Selected',\n                           'interaction_term2':'Rel. Score ^ 2 x Selected',\n                           'const': 'Constant'}\n\ntable_1_notes = [\"Model (1): Quadratic\",\"Model (2): Linear\",\"Model (3): Cubic\",\n                 \"Model (4): Interacted Quadratic\",\"Model (5): |Rel.Score| < 40\"]\n\ntable_1 = create_table(table_1_models,table_1_covariate_list,table_1_title,table_1_rename_covariates,table_1_notes)\ntable_1\n```\n\n\n\n\nTable 1\u2014Estimated Discontinuity in Probability of a Village Receiving a BRIGHT School<br><table style=\"text-align:center\"><tr><td colspan=\"6\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align:left\"></td><td colspan=\"5\"><em>Dependent variable:MCC_School</em></td></tr><tr><td style=\"text-align:left\"></td><tr><td style=\"text-align:left\"></td><td>(1)</td><td>(2)</td><td>(3)</td><td>(4)</td><td>(5)</td></tr><tr><td colspan=\"6\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align:left\">Selected for BRIGHT (Rel. Score \u2265 0)</td><td>0.874<sup>***</sup></td><td>0.878<sup>***</sup></td><td>0.877<sup>***</sup></td><td>0.877<sup>***</sup></td><td>0.868<sup>***</sup></td></tr><tr><td style=\"text-align:left\"></td><td>(0.035)</td><td>(0.031)</td><td>(0.035)</td><td>(0.042)</td><td>(0.053)</td></tr><tr><td style=\"text-align:left\">Rel. Score</td><td>0.792<sup></sup></td><td>0.615<sup></sup></td><td>0.605<sup></sup></td><td>-0.812<sup></sup></td><td></td></tr><tr><td style=\"text-align:left\"></td><td>(0.781)</td><td>(0.468)</td><td>(0.835)</td><td>(3.947)</td><td></td></tr><tr><td style=\"text-align:left\">Rel. Score ^ 2</td><td>-0.776<sup></sup></td><td></td><td>5.656<sup></sup></td><td>9.980<sup></sup></td><td></td></tr><tr><td style=\"text-align:left\"></td><td>(2.728)</td><td></td><td>(10.430)</td><td>(56.940)</td><td></td></tr><tr><td style=\"text-align:left\">Rel. Score ^ 3</td><td></td><td></td><td>-16.178<sup></sup></td><td></td><td></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td>(25.321)</td><td></td><td></td></tr><tr><td style=\"text-align:left\">Rel. Score x Selected</td><td></td><td></td><td></td><td>3.107<sup></sup></td><td></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td>(4.343)</td><td></td></tr><tr><td style=\"text-align:left\">Rel. Score ^ 2 x Selected</td><td></td><td></td><td></td><td>-14.881<sup></sup></td><td></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td>(56.889)</td><td></td></tr><tr><td style=\"text-align:left\">Constant</td><td>0.062<sup></sup></td><td>0.060<sup></sup></td><td>0.061<sup></sup></td><td>0.052<sup></sup></td><td>0.066<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td>(0.075)</td><td>(0.074)</td><td>(0.075)</td><td>(0.078)</td><td>(0.127)</td></tr><td colspan=\"6\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align: left\">Observations</td><td>287</td><td>287</td><td>287</td><td>287</td><td>93</td></tr><tr><td style=\"text-align: left\">R<sup>2</sup></td><td>0.824</td><td>0.824</td><td>0.824</td><td>0.826</td><td>0.831</td></tr><tr><td style=\"text-align: left\">Adjusted R<sup>2</sup></td><td>0.788</td><td>0.789</td><td>0.787</td><td>0.788</td><td>0.753</td></tr><tr><td style=\"text-align: left\">Residual Std. Error</td><td>0.230</td><td>0.229</td><td>0.230</td><td>0.229</td><td>0.249</td></tr><tr><td style=\"text-align: left\">F Statistic</td><td>22.656<sup>***</sup></td><td>23.216<sup>***</sup></td><td>22.156<sup>***</sup></td><td>21.898<sup>***</sup></td><td>10.652<sup>***</sup></td></tr><tr><td colspan=\"6\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align: left\">Note:</td>\n <td colspan=\"5\" style=\"text-align: right\">\n  <sup>*</sup>p&lt;0.1;\n  <sup>**</sup>p&lt;0.05;\n  <sup>***</sup>p&lt;0.01\n </td></tr><tr><td></td><td colspan=\"5\" style=\"text-align: right\">Model (1): Quadratic</td></tr><tr><td></td><td colspan=\"5\" style=\"text-align: right\">Model (2): Linear</td></tr><tr><td></td><td colspan=\"5\" style=\"text-align: right\">Model (3): Cubic</td></tr><tr><td></td><td colspan=\"5\" style=\"text-align: right\">Model (4): Interacted Quadratic</td></tr><tr><td></td><td colspan=\"5\" style=\"text-align: right\">Model (5): |Rel.Score| < 40</td></tr></table>\n\n\n\n---\n\n<span style=\"color:darkred\">**NOTE**:</span> For Table 1, I do not replicate the results from the probit quadratic model published by Kazianga et al. (2013) due to complications that I was unable to resolve. However, I do not consider this to be a major drawback, as I successfully replicated all other specification models from the original paper, which sufficiently confirm the robustness of the authors' preferred quadratic model reported in column (1).\n\n---\n\n### 5.2.2. Continuity Checks <a name=\"5.2.2\"></a>\n\n#### Figure 2. Distribution of Sample by Relative Score \n\nIn order to simulate randomness of treatment assignment, a valid RD design requires all other characteristics among the sampled villages to demonstrate continuity at the designated treatment cutoff. As recommended by McCrary (2008), Kazianga et al. (2013) visualize the distribution of children based on the relative scores of their villages. As in Figure 1, the range of relative scores is restricted to (-250, 250).  Although I do not directly follow the complementary Stata code, I construct a histogram using the recommended bin size of 41.2 and include a corresponding density plot to ensure a continuous distribution at the cutoff value. \n\nWith this very basic visual test, it is possible to ensure whether or not villages were able to manipulate their assigned relative score in order to be selected into the treatment group. Figure 2 shows a smooth, uninterrupted density and underlying histograph plot, which suggests that participating villages were successfully assigned to the control and treatment groups at random. In the event that villages could manipulate their assigned relative score, however, the distribution plot would indicate a visible discontinuity, in which the density just above the cutoff would be significantly larger. For example, if villages had been aware of the scoring procedure beforehand, and some had provided false information to data collectors to guarantee receipt of a BRIGHT school, then the treatment group could potentially exhibit characteristics that render it systematically different from the control group. Perhaps villages that provide false information contain a populace that is already aware of the potential benefits of education and therefore willing to manipulate the scoring procedure in order to obtain a BRIGHT school. In this case, later regression estimates that measure the treatment effects of the BRIGHT program could exhibit an upward bias.  \n\n\n```python\nrslt_graph_2 = rslt_graph_1.loc[abs(rslt_graph_1[\"rel_score_redefined\"]) <= 250]\n```\n\n\n```python\ntitle_graph_2 = 'Figure 2: Distribution of Sample by Relative Score'\nxlabel_graph_2 = 'Relative Score'\nylabel_graph_2 = 'Density'\nplot_graph_2(ylabel_graph_2, xlabel_graph_2, title_graph_2, rslt_graph_2)\n```\n\n#### Table 2. Continuity of Child Characteristics\n\nAs a second continuity check to make sure there are no systematic differences between the control and treatment groups, Kazianga et al. (2013) evaluate several demographic characteristics of the children observed in the study. The first ten outcome variables listed below in Table 2 include child and household characteristics such as the age of the household head, the gender of the household head, the number of household members, the child's age, the gender of the child, and the child's relationship to the head of the household. The following nine outcome variables describe the child's religious, ethnic, and linguist background. The remaining variables provide information on the owned assets of the child's household. \n\nTo estimate the discontinuities around the cutoff for the observed characteristics, Kazianga et al. (2013) regress each of the demographic variables on their preferred quadratic model with department fixed effects. Out of the 28 estimated discontinuities, only three yield regression coefficients that are statistically significant at conventional levels. Economically, the estimated coefficient for assigned treatment is small in all 28 regressions. In fact, the magnitudes of the three statistically significant discontinuities are so small that Kazianga et al. (2013) report implied biases of negligible size. As such, the results in Table 2 confirm that the critical continuity assumption holds for all demographic characteristics observed by the authors. Although discontinuities may exist for unobservable characteristics, the outcomes reported by Kazianga et al. (2013) do not suggest any systematic differences between the control and treatment groups that may bias the treatment effect estimates. \n\n\n```python\ny_var_table_2 = [\"Hh_HeadMale\", \"Hh_HeadAge\", \"Hh_HeadSchool\", \"Hh_NumMembers\", \"Hh_NumKids\", \"Ch_Age\",\n                \"Ch_Girl\",\"Ch_HeadChild\", \"Ch_HeadGrandChild\", \"Ch_HeadNephew\",\"Hh_ReligionMuslin\", \"Hh_Animist\",\n                \"Hh_Christian\", \"Hh_Lang_Fulfude\", \"Hh_Lang_Gulmachema\",\"Hh_Lang_Moore\", \"Hh_Ethnicity_Gourmanche\", \n                \"Hh_Ethnicity_Mossi\", \"Hh_Ethnicity_Peul\", \"Hh_FloorBasic\", \"Hh_RoofBasic\", \"Hh_Radio\", \"Hh_Telmob\",\n                \"Hh_Watch\", \"Hh_Bike\", \"Hh_Cows\",\"Hh_Motorbike\", \"Hh_Cart\"]\n\nX_matrix_table_2 = [\"proj_selected\", \"rel_score\", \"clustercode\"]\n\ny_table_2,X_table_2 = get_data(0,0,0, y_var_table_2, X_matrix_table_2)\n\n```\n\n\n```python\ntable_2 = create_table_df(y_table_2, y_var_table_2, X_table_2, 1,1)\ntable_2\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Regression Coefficient at Cutoff</th>\n      <th>Standard Error</th>\n      <th>P-value</th>\n      <th>Sample Average</th>\n    </tr>\n    <tr>\n      <th>Outcome Variables</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Hh_HeadMale</th>\n      <td>-0.008</td>\n      <td>0.006</td>\n      <td>0.158</td>\n      <td>0.982</td>\n    </tr>\n    <tr>\n      <th>Hh_HeadAge</th>\n      <td>-0.652</td>\n      <td>0.554</td>\n      <td>0.239</td>\n      <td>48.058</td>\n    </tr>\n    <tr>\n      <th>Hh_HeadSchool</th>\n      <td>-0.013</td>\n      <td>0.038</td>\n      <td>0.738</td>\n      <td>0.159</td>\n    </tr>\n    <tr>\n      <th>Hh_NumMembers</th>\n      <td>-0.106</td>\n      <td>0.319</td>\n      <td>0.740</td>\n      <td>10.908</td>\n    </tr>\n    <tr>\n      <th>Hh_NumKids</th>\n      <td>0.123</td>\n      <td>0.180</td>\n      <td>0.493</td>\n      <td>6.010</td>\n    </tr>\n    <tr>\n      <th>Ch_Age</th>\n      <td>-0.009</td>\n      <td>0.044</td>\n      <td>0.830</td>\n      <td>8.765</td>\n    </tr>\n    <tr>\n      <th>Ch_Girl</th>\n      <td>0.023</td>\n      <td>0.010</td>\n      <td>0.016</td>\n      <td>0.466</td>\n    </tr>\n    <tr>\n      <th>Ch_HeadChild</th>\n      <td>-0.011</td>\n      <td>0.012</td>\n      <td>0.337</td>\n      <td>0.884</td>\n    </tr>\n    <tr>\n      <th>Ch_HeadGrandChild</th>\n      <td>-0.013</td>\n      <td>0.008</td>\n      <td>0.109</td>\n      <td>0.052</td>\n    </tr>\n    <tr>\n      <th>Ch_HeadNephew</th>\n      <td>0.017</td>\n      <td>0.006</td>\n      <td>0.002</td>\n      <td>0.035</td>\n    </tr>\n    <tr>\n      <th>Hh_ReligionMuslin</th>\n      <td>0.006</td>\n      <td>0.032</td>\n      <td>0.854</td>\n      <td>0.583</td>\n    </tr>\n    <tr>\n      <th>Hh_Animist</th>\n      <td>0.007</td>\n      <td>0.027</td>\n      <td>0.788</td>\n      <td>0.269</td>\n    </tr>\n    <tr>\n      <th>Hh_Christian</th>\n      <td>-0.010</td>\n      <td>0.021</td>\n      <td>0.624</td>\n      <td>0.138</td>\n    </tr>\n    <tr>\n      <th>Hh_Lang_Fulfude</th>\n      <td>0.035</td>\n      <td>0.025</td>\n      <td>0.169</td>\n      <td>0.188</td>\n    </tr>\n    <tr>\n      <th>Hh_Lang_Gulmachema</th>\n      <td>-0.047</td>\n      <td>0.029</td>\n      <td>0.104</td>\n      <td>0.281</td>\n    </tr>\n    <tr>\n      <th>Hh_Lang_Moore</th>\n      <td>0.014</td>\n      <td>0.031</td>\n      <td>0.638</td>\n      <td>0.392</td>\n    </tr>\n    <tr>\n      <th>Hh_Ethnicity_Gourmanche</th>\n      <td>-0.032</td>\n      <td>0.030</td>\n      <td>0.280</td>\n      <td>0.289</td>\n    </tr>\n    <tr>\n      <th>Hh_Ethnicity_Mossi</th>\n      <td>0.003</td>\n      <td>0.031</td>\n      <td>0.923</td>\n      <td>0.400</td>\n    </tr>\n    <tr>\n      <th>Hh_Ethnicity_Peul</th>\n      <td>0.028</td>\n      <td>0.025</td>\n      <td>0.263</td>\n      <td>0.176</td>\n    </tr>\n    <tr>\n      <th>Hh_FloorBasic</th>\n      <td>-0.035</td>\n      <td>0.015</td>\n      <td>0.024</td>\n      <td>0.931</td>\n    </tr>\n    <tr>\n      <th>Hh_RoofBasic</th>\n      <td>-0.039</td>\n      <td>0.027</td>\n      <td>0.154</td>\n      <td>0.552</td>\n    </tr>\n    <tr>\n      <th>Hh_Radio</th>\n      <td>-0.009</td>\n      <td>0.038</td>\n      <td>0.819</td>\n      <td>0.752</td>\n    </tr>\n    <tr>\n      <th>Hh_Telmob</th>\n      <td>-0.015</td>\n      <td>0.022</td>\n      <td>0.487</td>\n      <td>0.187</td>\n    </tr>\n    <tr>\n      <th>Hh_Watch</th>\n      <td>-0.004</td>\n      <td>0.045</td>\n      <td>0.934</td>\n      <td>0.819</td>\n    </tr>\n    <tr>\n      <th>Hh_Bike</th>\n      <td>-0.076</td>\n      <td>0.075</td>\n      <td>0.311</td>\n      <td>1.473</td>\n    </tr>\n    <tr>\n      <th>Hh_Cows</th>\n      <td>0.198</td>\n      <td>0.526</td>\n      <td>0.706</td>\n      <td>5.665</td>\n    </tr>\n    <tr>\n      <th>Hh_Motorbike</th>\n      <td>0.031</td>\n      <td>0.024</td>\n      <td>0.207</td>\n      <td>0.303</td>\n    </tr>\n    <tr>\n      <th>Hh_Cart</th>\n      <td>-0.032</td>\n      <td>0.036</td>\n      <td>0.377</td>\n      <td>0.656</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### 5.2.3. Measured Differences in Educational Infrastructure <a name=\"5.2.3\"></a>\n\n#### Table 3. Existence of Any School Type in Villages Sampled\n\nIn the third and final validity check of the RD design, Kazianga et al. (2013) determine whether the discontinuity observed in assigned treatment created a notable discontinuity in the educational infrastructure accessible to primary school-aged children. The results in Table 3 report a series of regression coefficients from the preferred quadratic model that estimate the effect of the BRIGHT program on the likelihood that a village has any school, including ones not affiliated with the BRIGHT program. Column (1) estimates, for example, that villages assigned to the treatment group were 32 percentage points more likely to have any school in 2008. \n\nColumns (2) through (6) measure the effect of the BRIGHT program on the probability that a village has any school in the years leading up to and following the start of the BRIGHT initiative in 2005. As indicated by the coefficient estimates in columns (2) and (3), there is no difference of economic or statistical significance between selected and nonselected village for 2003 and 2004 before the BRIGHT program went into effect. When the BRIGHT program began in 2005, villages selected for a BRIGHT school constructed interim schools in anticipation of receiving a BRIGHT school at a future date. As such, it is apparent in column (4) that the treatment villages were 32.4 percentage points more likely to have a school than the villages in the control group. In 2006, the likelihood increased to 54.8 percentage points when the construction of BRIGHT schools was underway. A year later in 2007, this differential sank to 42 percentage points. Kazianga et al. (2013) further point out that this large and statistically significant difference for the period between 2005 and 2008 took place despite an increase in the number of schools constructed in nonselected villages. The final column in Table 3 suggests that villages in the treatment group had a school approximately 1.6 years earlier compared to villages not chosen to receive a BRIGHT school. \n\n\n```python\ny_var_table_3_pt1 = [\"has_school\"]\nX_matrix_table_3_pt1 = [\"proj_selected\", \"rel_score\", \"clustercode\"]\n\ny_table_3_pt1,X_table_3_pt1 = get_data(1,0,0, y_var_table_3_pt1, X_matrix_table_3_pt1)\n\ny_var_table_3_pt2 = [\"Vill_HadSchool2003\",\"Vill_HadSchool2004\",\"Vill_HadSchool2005\",\"Vill_HadSchool2006\",\n                     \"Vill_HadSchool2007\", \"Vill_YearsOfSchool\"]\n\nX_matrix_table_3_pt2 = [\"proj_selected\", \"rel_score\", \"clustercode\",]\n\ny_table_3_pt2,X_table_3_pt2 = get_data(1,1,0, y_var_table_3_pt2, X_matrix_table_3_pt2)\n\n```\n\n\n```python\nmod_table3_rel_2 = calculate_polynomial_features(0,y_table_3_pt1,X_table_3_pt1,2)\nvarying_depend_var_table3 = regress_for_diff_outcomes_poly_features(y_table_3_pt2,y_var_table_3_pt2,X_table_3_pt2,2,0)\n```\n\n\n```python\n##Compute non-selected averages \nnon_sel_average1 = y_table_3_pt1.loc[X_table_3_pt1[\"proj_selected\"] == 0].mean().values.tolist()\nnon_sel_average2 = y_table_3_pt2.loc[X_table_3_pt2[\"proj_selected\"] == 0].mean().values.tolist()\nnon_sel_averages = non_sel_average1 + non_sel_average2\nnon_sel_averages_rnded = [round(num, 3) for num in non_sel_averages]\n```\n\n\n```python\ntable_3_models = [mod_table3_rel_2,\n                  varying_depend_var_table3[0],\n                  varying_depend_var_table3[1],\n                  varying_depend_var_table3[2],\n                  varying_depend_var_table3[3],\n                  varying_depend_var_table3[4],\n                  varying_depend_var_table3[5]]\n\ntable_3_covariate_list = [\"proj_selected\",\"rel_score1\",\"rel_score2\", \"const\"]\n\ntable_3_title = 'Table 3\u2014Existence of Any School Type in Villages Sampled'\n\ntable_3_rename_covariates = {'proj_selected': 'Selected for BRIGHT (Rel. Score \u2265 0)','rel_score1':'Rel. Score',\n                             'rel_score2':'Rel. Score ^ 2','const': 'Constant'}\ntable_3_notes = ['']\n\ntable_3 = create_table(table_3_models,table_3_covariate_list,table_3_title,table_3_rename_covariates,table_3_notes)\n\ntable_3.custom_columns(['Any School, 2008', 'Village Had School, 2003','Village Had School, 2004',\n                       'Village Had School, 2005', 'Village Had School, 2006', 'Village Had School, 2007',\n                        'Number of Years with School'], [1, 1, 1, 1, 1, 1, 1])\n\ntable_3.add_line('Nonselected average', non_sel_averages_rnded,LineLocation.FOOTER_TOP)\ntable_3\n```\n\n\n\n\nTable 3\u2014Existence of Any School Type in Villages Sampled<br><table style=\"text-align:center\"><tr><td colspan=\"8\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align:left\"></td><tr><td></td><td colspan=\"1\">Any School, 2008</td><td colspan=\"1\">Village Had School, 2003</td><td colspan=\"1\">Village Had School, 2004</td><td colspan=\"1\">Village Had School, 2005</td><td colspan=\"1\">Village Had School, 2006</td><td colspan=\"1\">Village Had School, 2007</td><td colspan=\"1\">Number of Years with School</td></tr><tr><td style=\"text-align:left\"></td><td>(1)</td><td>(2)</td><td>(3)</td><td>(4)</td><td>(5)</td><td>(6)</td><td>(7)</td></tr><tr><td colspan=\"8\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align:left\">Selected for BRIGHT (Rel. Score \u2265 0)</td><td>0.315<sup>***</sup></td><td>-0.009<sup></sup></td><td>-0.045<sup></sup></td><td>0.324<sup>***</sup></td><td>0.548<sup>***</sup></td><td>0.420<sup>***</sup></td><td>1.592<sup>***</sup></td></tr><tr><td style=\"text-align:left\"></td><td>(0.057)</td><td>(0.032)</td><td>(0.040)</td><td>(0.065)</td><td>(0.058)</td><td>(0.061)</td><td>(0.234)</td></tr><tr><td style=\"text-align:left\">Rel. Score</td><td>1.271<sup></sup></td><td>0.264<sup></sup></td><td>0.915<sup></sup></td><td>1.639<sup></sup></td><td>1.570<sup></sup></td><td>1.714<sup></sup></td><td>7.311<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td>(1.267)</td><td>(0.709)</td><td>(0.905)</td><td>(1.447)</td><td>(1.308)</td><td>(1.370)</td><td>(5.232)</td></tr><tr><td style=\"text-align:left\">Rel. Score ^ 2</td><td>-0.935<sup></sup></td><td>-1.602<sup></sup></td><td>-3.305<sup></sup></td><td>-8.456<sup>*</sup></td><td>-2.495<sup></sup></td><td>-2.266<sup></sup></td><td>-19.106<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td>(4.423)</td><td>(2.439)</td><td>(3.114)</td><td>(4.978)</td><td>(4.501)</td><td>(4.713)</td><td>(17.997)</td></tr><tr><td style=\"text-align:left\">Constant</td><td>0.542<sup>***</sup></td><td>0.104<sup></sup></td><td>0.122<sup></sup></td><td>0.138<sup></sup></td><td>0.225<sup>*</sup></td><td>0.389<sup>***</sup></td><td>1.500<sup>***</sup></td></tr><tr><td style=\"text-align:left\"></td><td>(0.121)</td><td>(0.065)</td><td>(0.083)</td><td>(0.133)</td><td>(0.120)</td><td>(0.126)</td><td>(0.482)</td></tr><td colspan=\"8\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align: left\">Nonselected average</td><td>0.609</td><td>0.058</td><td>0.094</td><td>0.201</td><td>0.338</td><td>0.468</td><td>1.734</td></tr><tr><td style=\"text-align: left\">Observations</td><td>287</td><td>270</td><td>270</td><td>270</td><td>270</td><td>270</td><td>270</td></tr><tr><td style=\"text-align: left\">R<sup>2</sup></td><td>0.340</td><td>0.376</td><td>0.315</td><td>0.417</td><td>0.524</td><td>0.422</td><td>0.446</td></tr><tr><td style=\"text-align: left\">Adjusted R<sup>2</sup></td><td>0.203</td><td>0.237</td><td>0.162</td><td>0.287</td><td>0.418</td><td>0.293</td><td>0.322</td></tr><tr><td style=\"text-align: left\">Residual Std. Error</td><td>0.372</td><td>0.200</td><td>0.256</td><td>0.409</td><td>0.370</td><td>0.387</td><td>1.479</td></tr><tr><td style=\"text-align: left\">F Statistic</td><td>2.487<sup>***</sup></td><td>2.703<sup>***</sup></td><td>2.064<sup>***</sup></td><td>3.214<sup>***</sup></td><td>4.936<sup>***</sup></td><td>3.273<sup>***</sup></td><td>3.612<sup>***</sup></td></tr><tr><td colspan=\"8\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align: left\">Note:</td>\n <td colspan=\"7\" style=\"text-align: right\">\n  <sup>*</sup>p&lt;0.1;\n  <sup>**</sup>p&lt;0.05;\n  <sup>***</sup>p&lt;0.01\n </td></tr><tr><td></td><td colspan=\"7\" style=\"text-align: right\"></td></tr></table>\n\n\n\n#### Table 4. Comparison of Schools Attended by Students from Selected and Nonselected Villages\n\nIn addition to measuring the effect of the BRIGHT program on accessibility to education services in treatment villages, Kazianga et al. (2013) compare several characteristics of traditional and BRIGHT schools along the following three categories: \n\n1. girl-friendly characteristics (the first five variables reported in Table 4), \n2. school resources (variables six through 11), and \n3. teacher characteristics (the remaining variables in Table 4).\n\nThe results reported in Table 4 show that not only did the BRIGHT program increase a child's probability of having access to a school, it also provided specific amenities that schools in nonselected villages lacked. Columns (1) and (2) show that schools in villages from the control group have less access to girl-friendly characteristics such as meal and dry rations programs, gender-segregated bathrooms, or daycare programs (referred to as bisongo in Table 4). They also have fewer school resources (in particular, resources of higher quality) and teachers with experience in terms of postsecondary and gender sensitivity training. In columns (3) to (5), Kazianga et al. (2013) report regression discontinuity results for each of the listed school characteristics and find comparable differentials between selected and nonselected villages.    \n\n\n```python\ny_var_table_4 = [\"feeding_program\", \"dry_rations\", \"toilets\", \"toilets_gender\", \"bisongo\", \"insufficient_books\",\n                 \"insufficient_desks\", \"water_supply\", \"num_rooms_usable\", \"num_rooms_boards\", \"num_rooms_rboards\",\n                 \"num_teachers\", \"num_teachers_female\", \"num_teachers_postsec\", \"num_teachers_l5\", \"num_teachers_l10\",\n                 \"num_teachers_g10\", \"num_teachers_training\"]\n\nX_matrix_table_4 = [\"proj_selected\", \"rel_score\", \"clustercode\"]\n\ny_table_4,X_table_4 = get_data(2,0,0, y_var_table_4, X_matrix_table_4)\n```\n\n\n```python\ntable_4 = create_table_df(y_table_4,y_var_table_4,X_table_4, 2, 0)\ntable_4\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Sample Average for Non-Selected Villages</th>\n      <th>Sample Average for Selected Villages</th>\n      <th>Regression Coefficient at Cutoff</th>\n      <th>Standard Error</th>\n      <th>P-value</th>\n    </tr>\n    <tr>\n      <th>Outcome Variables</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>feeding_program</th>\n      <td>0.503</td>\n      <td>0.746</td>\n      <td>0.247</td>\n      <td>0.063</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>dry_rations</th>\n      <td>0.105</td>\n      <td>0.371</td>\n      <td>0.215</td>\n      <td>0.051</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>toilets</th>\n      <td>0.327</td>\n      <td>0.721</td>\n      <td>0.396</td>\n      <td>0.063</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>toilets_gender</th>\n      <td>0.240</td>\n      <td>0.619</td>\n      <td>0.351</td>\n      <td>0.063</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>bisongo</th>\n      <td>0.006</td>\n      <td>0.066</td>\n      <td>0.046</td>\n      <td>0.025</td>\n      <td>0.068</td>\n    </tr>\n    <tr>\n      <th>insufficient_books</th>\n      <td>0.737</td>\n      <td>0.584</td>\n      <td>-0.182</td>\n      <td>0.062</td>\n      <td>0.004</td>\n    </tr>\n    <tr>\n      <th>insufficient_desks</th>\n      <td>0.357</td>\n      <td>0.188</td>\n      <td>-0.250</td>\n      <td>0.060</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>water_supply</th>\n      <td>0.263</td>\n      <td>0.614</td>\n      <td>0.356</td>\n      <td>0.064</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>num_rooms_usable</th>\n      <td>2.509</td>\n      <td>3.063</td>\n      <td>0.508</td>\n      <td>0.179</td>\n      <td>0.005</td>\n    </tr>\n    <tr>\n      <th>num_rooms_boards</th>\n      <td>2.402</td>\n      <td>3.057</td>\n      <td>0.627</td>\n      <td>0.187</td>\n      <td>0.001</td>\n    </tr>\n    <tr>\n      <th>num_rooms_rboards</th>\n      <td>1.420</td>\n      <td>2.886</td>\n      <td>1.522</td>\n      <td>0.389</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>num_teachers</th>\n      <td>2.536</td>\n      <td>2.759</td>\n      <td>0.235</td>\n      <td>0.207</td>\n      <td>0.257</td>\n    </tr>\n    <tr>\n      <th>num_teachers_female</th>\n      <td>0.464</td>\n      <td>1.101</td>\n      <td>0.579</td>\n      <td>0.143</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>num_teachers_postsec</th>\n      <td>0.080</td>\n      <td>0.127</td>\n      <td>-0.002</td>\n      <td>0.051</td>\n      <td>0.969</td>\n    </tr>\n    <tr>\n      <th>num_teachers_l5</th>\n      <td>1.643</td>\n      <td>2.032</td>\n      <td>0.505</td>\n      <td>0.172</td>\n      <td>0.004</td>\n    </tr>\n    <tr>\n      <th>num_teachers_l10</th>\n      <td>0.696</td>\n      <td>0.576</td>\n      <td>-0.192</td>\n      <td>0.121</td>\n      <td>0.114</td>\n    </tr>\n    <tr>\n      <th>num_teachers_g10</th>\n      <td>0.196</td>\n      <td>0.152</td>\n      <td>-0.079</td>\n      <td>0.057</td>\n      <td>0.166</td>\n    </tr>\n    <tr>\n      <th>num_teachers_training</th>\n      <td>0.152</td>\n      <td>0.614</td>\n      <td>0.495</td>\n      <td>0.092</td>\n      <td>0.000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## 5.3. Estimated Treatment Effects <a name=\"5.3\"></a>\n\nAfter providing evidence to confirm the validity of an RD design, the authors examine the estimated treatment effects of the BRIGHT program. In the main body of their paper, Kazianga et al. (2013) report measured effects on enrollment and test scores. They also discuss treatment differentials according to gender.      \n\n### 5.3.1. Treatment Effect on Enrollment <a name=\"5.3.1\"></a>\n\n#### Table 5. Effects of BRIGHT Schools on Enrollment\n\nAccording to Table 5, the authors' preferred quadratic regression model (column 1) estimates that the BRIGHT program increased a child's probability of being enrolled in school by 18.5 percentage points. Removing the demographic controls from the preferred model (column 2) provides comparable results, which lends further evidence to the critical assumption that villages assigned relative scores above and below the arbitrary cutoff are **not** systematically different from one another. The coefficient estimates in columns (3) through (6) remain consistent, suggesting robustness of the estimated treatment effect. Using verified enrollment instead of self-reported enrollment as the dependent variable for the results in column (7), the authors estimate a similar albeit slightly smaller coefficient for the treatment indicator variable. As they were only able to visit each school once to directly confirm the presence of each child, who claimed to be enrolled, Kazianga et al. (2013) caution that the beta coefficient in column (7) is likely an underestimate of the treatment effect due to student absences on the day of enrollment verification.        \n\n\n```python\ny_var_table_5 = [\"attending\",\"attending2\"]\nX_matrix_table_5 = [\"proj_selected\", \"rel_score\",\"clustercode\"]\n\ny_table_5,X_table_5_controls = get_data(0,0,1, y_var_table_5, X_matrix_table_5)\ny_table_5,X_table_5_no_controls = get_data(0,0,0, y_var_table_5, X_matrix_table_5)\n```\n\n\n```python\nfitted_poly_models_table5 = []\nfor x in range(1, 4): # [1, 2, 3]\n    models = calculate_polynomial_features(1,y_table_5.iloc[:,0],X_table_5_controls, x)\n    fitted_poly_models_table5.append(models)\n```\n\n\n```python\nfitted_poly_models_table5 = fit_poly_models_iterate(y_table_5.iloc[:,0], X_table_5_controls, 3, 1)\n```\n\n\n```python\n#quadratic model without controls \nmod_table5_rel_2_no_controls = calculate_polynomial_features(1,y_table_5.iloc[:,0],X_table_5_no_controls, 2)\n\nmod_table5_interaction = calculate_polynomial_interaction(1,y_table_5.iloc[:,0],X_table_5_controls,interact1,interact2,2)\n\nmod_table5_reduced = calculate_reduced_range_40(1, y_table_5.iloc[:,0],X_table_5_no_controls)\n\nmod_table5_verified_enroll = calculate_polynomial_features(1,y_table_5.iloc[:,1],X_table_5_controls, 2)\n```\n\n\n```python\ntable_5_models = [fitted_poly_models_table5[1],\n                  mod_table5_rel_2_no_controls,  \n                  fitted_poly_models_table5[0],\n                  fitted_poly_models_table5[2],\n                  mod_table5_interaction,\n                  mod_table5_reduced,\n                  mod_table5_verified_enroll\n                 ]\ntable_5_covariate_list = [\"proj_selected\",\"rel_score1\",\"rel_score2\",\"rel_score3\", \"interaction_term1\",\"interaction_term2\",\"const\"]\n\ntable_5_title = 'Table 5\u2014Effects of BRIGHT Schools on Enrollment'\n\ntable_5_rename_covariates = {'proj_selected': 'Selected for BRIGHT (Rel. Score \u2265 0)',\n                           'rel_score1':'Rel. Score',\n                           'rel_score2':'Rel. Score ^ 2',\n                           'interaction_term1':'Rel. Score x Selected',\n                           'interaction_term2':'Rel. Score ^ 2 x Selected',\n                           'const': 'Constant'}\ntable_5_notes = [\"Model (1): Quadratic\", \n                 \"Model (2): Quadratic without Controls\",\n                 \"Model (3): Linear\",\n                 \"Model (4): Cubic\",\n                 \"Model (5): Interacted Quadratic\",\n                 \"Model (6): |Rel.Score| < 40\", \n                 \"Model (7): Quadratic\"]\n\ntable_5 = create_table(table_5_models,table_5_covariate_list,table_5_title, table_5_rename_covariates,table_5_notes)\n\ntable_5.custom_columns(['Reported Enrollment', 'Reported Enrollment', 'Reported Enrollment',\n                        'Reported Enrollment','Reported Enrollment','Reported Enrollment',\n                        'Verified Enrollment'], [1, 1, 1, 1, 1, 1, 1])\ntable_5.add_line('Demographic Controls', ['Yes','No','Yes','Yes','Yes','No','Yes'])\ntable_5.add_line('Department Fixed Effects', ['Yes','Yes','Yes','Yes','Yes','Yes','Yes'])\ntable_5\n```\n\n\n\n\nTable 5\u2014Effects of BRIGHT Schools on Enrollment<br><table style=\"text-align:center\"><tr><td colspan=\"8\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align:left\"></td><tr><td></td><td colspan=\"1\">Reported Enrollment</td><td colspan=\"1\">Reported Enrollment</td><td colspan=\"1\">Reported Enrollment</td><td colspan=\"1\">Reported Enrollment</td><td colspan=\"1\">Reported Enrollment</td><td colspan=\"1\">Reported Enrollment</td><td colspan=\"1\">Verified Enrollment</td></tr><tr><td style=\"text-align:left\"></td><td>(1)</td><td>(2)</td><td>(3)</td><td>(4)</td><td>(5)</td><td>(6)</td><td>(7)</td></tr><tr><td colspan=\"8\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align:left\">Selected for BRIGHT (Rel. Score \u2265 0)</td><td>0.185<sup>***</sup></td><td>0.191<sup>***</sup></td><td>0.203<sup>***</sup></td><td>0.193<sup>***</sup></td><td>0.184<sup>***</sup></td><td>0.177<sup>***</sup></td><td>0.154<sup>***</sup></td></tr><tr><td style=\"text-align:left\"></td><td>(0.025)</td><td>(0.026)</td><td>(0.025)</td><td>(0.026)</td><td>(0.031)</td><td>(0.032)</td><td>(0.027)</td></tr><tr><td style=\"text-align:left\">Rel. Score</td><td>1.141<sup>**</sup></td><td>1.338<sup>**</sup></td><td>0.434<sup></sup></td><td>0.683<sup></sup></td><td>0.713<sup></sup></td><td></td><td>0.810<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td>(0.548)</td><td>(0.550)</td><td>(0.447)</td><td>(0.619)</td><td>(3.223)</td><td></td><td>(0.682)</td></tr><tr><td style=\"text-align:left\">Rel. Score ^ 2</td><td>-3.186<sup>**</sup></td><td>-3.703<sup>**</sup></td><td></td><td>11.430<sup></sup></td><td>10.580<sup></sup></td><td></td><td>-2.518<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td>(1.619)</td><td>(1.663)</td><td></td><td>(7.650)</td><td>(43.308)</td><td></td><td>(1.787)</td></tr><tr><td style=\"text-align:left\">rel_score3</td><td></td><td></td><td></td><td>-36.499<sup>**</sup></td><td></td><td></td><td></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td>(17.215)</td><td></td><td></td><td></td></tr><tr><td style=\"text-align:left\">Rel. Score x Selected</td><td></td><td></td><td></td><td></td><td>1.213<sup></sup></td><td></td><td></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td>(3.577)</td><td></td><td></td></tr><tr><td style=\"text-align:left\">Rel. Score ^ 2 x Selected</td><td></td><td></td><td></td><td></td><td>-15.949<sup></sup></td><td></td><td></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td>(43.101)</td><td></td><td></td></tr><tr><td style=\"text-align:left\">Constant</td><td>0.102<sup></sup></td><td>0.424<sup>***</sup></td><td>0.091<sup></sup></td><td>0.084<sup></sup></td><td>0.091<sup></sup></td><td>0.428<sup>***</sup></td><td>0.139<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td>(0.122)</td><td>(0.101)</td><td>(0.121)</td><td>(0.123)</td><td>(0.125)</td><td>(0.141)</td><td>(0.126)</td></tr><tr><td style=\"text-align: left\">Demographic Controls</td><td>Yes</td><td>No</td><td>Yes</td><td>Yes</td><td>Yes</td><td>No</td><td>Yes</td></tr><tr><td style=\"text-align: left\">Department Fixed Effects</td><td>Yes</td><td>Yes</td><td>Yes</td><td>Yes</td><td>Yes</td><td>Yes</td><td>Yes</td></tr><td colspan=\"8\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align: left\">Observations</td><td>17,970</td><td>17,970</td><td>17,970</td><td>17,970</td><td>17,970</td><td>5,595</td><td>17,970</td></tr><tr><td style=\"text-align: left\">R<sup>2</sup></td><td>0.185</td><td>0.123</td><td>0.184</td><td>0.187</td><td>0.186</td><td>0.122</td><td>0.167</td></tr><tr><td style=\"text-align: left\">Adjusted R<sup>2</sup></td><td>0.181</td><td>0.120</td><td>0.180</td><td>0.183</td><td>0.182</td><td>0.118</td><td>0.163</td></tr><tr><td style=\"text-align: left\">Residual Std. Error</td><td>0.451</td><td>0.467</td><td>0.451</td><td>0.450</td><td>0.451</td><td>0.467</td><td>0.444</td></tr><tr><td style=\"text-align: left\">F Statistic</td><td>18.568<sup>***</sup></td><td>8.737<sup>***</sup></td><td>19.220<sup>***</sup></td><td>18.077<sup>***</sup></td><td>18.021<sup>***</sup></td><td>1676.894<sup>***</sup></td><td>15.164<sup>***</sup></td></tr><tr><td colspan=\"8\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align: left\">Note:</td>\n <td colspan=\"7\" style=\"text-align: right\">\n  <sup>*</sup>p&lt;0.1;\n  <sup>**</sup>p&lt;0.05;\n  <sup>***</sup>p&lt;0.01\n </td></tr><tr><td></td><td colspan=\"7\" style=\"text-align: right\">Model (1): Quadratic</td></tr><tr><td></td><td colspan=\"7\" style=\"text-align: right\">Model (2): Quadratic without Controls</td></tr><tr><td></td><td colspan=\"7\" style=\"text-align: right\">Model (3): Linear</td></tr><tr><td></td><td colspan=\"7\" style=\"text-align: right\">Model (4): Cubic</td></tr><tr><td></td><td colspan=\"7\" style=\"text-align: right\">Model (5): Interacted Quadratic</td></tr><tr><td></td><td colspan=\"7\" style=\"text-align: right\">Model (6): |Rel.Score| < 40</td></tr><tr><td></td><td colspan=\"7\" style=\"text-align: right\">Model (7): Quadratic</td></tr></table>\n\n\n\n---\n\n<span style=\"color:darkred\">**NOTE**:</span> For Table 5, I do not replicate the results from the probit quadratic model published by Kazianga et al. (2013) due to complications that I was unable to resolve. However, I do not consider this to be a major drawback, as I successfully replicated all other specification models from the original paper, which sufficiently confirm the robustness of the authors' preferred quadratic model reported in column (1).\n\n---\n\n#### Figure 3. Probability of Enrollment in School According to Village's Relative Score \n\nSimilar to Figure 1, Kazianga et al. (2013) present the results of a nonparametric estimate for the enrollment treatment effect in Figure 3. The plot measures the probability of school enrollment for primary school-aged children living in selected versus nonselected villages. As indicated by the visualization, there is a clear discontinuity at the cutoff that corroborates the parametric estimates summarized in Table 5. For villages that received a BRIGHT school and had a relative score just above zero, the probability of enrollment is approximately 20 percentage points higher compared to nonselected villages with a relative score just below zero.\n\nThe authors also plot the $R^2$ values estimated for the specification described in equation (2) to confirm the location of the discontinuity for enrollment probability. The plotted $R^2$ values are represented by the blue curve in Figure 3. According to the `arg_maximum_graph_3` dataframe produced below, the $R^2$ values are maximized at a relative score of 8, which is sufficiently close to the cutoff value.\n\n\n```python\nselected_columns_graph_3 = [\"attending\", \"proj_selected\", \"rel_score_redefined\",\"rel_score\"]\n\nrslt_untreated_graph_3 = get_data_graphs(selected_columns_graph_3,0,0)\nrslt_treated_graph_3 = get_data_graphs(selected_columns_graph_3,0,1)\nrslt_graph_3 = get_data_graphs(selected_columns_graph_3,0,2)\n```\n\n\n```python\ny_var_graph_3 = \"attending\"\nx_var_graph_3 = \"rel_score_redefined\"\n```\n\n\n```python\ncontrol_graph_3 = [compute_locally_weighted_reg(y_var_graph_3,x_var_graph_3,item,bandwidth, rslt_untreated_graph_3) \n                   for item in X_untreated]\ntreatment_graph_3 = [compute_locally_weighted_reg(y_var_graph_3,x_var_graph_3,item,bandwidth, rslt_treated_graph_3) \n                     for item in X_treated]\n\ndf_graph_3 = pd.DataFrame()\ndf_graph_3[\"y-axis\"] = control_graph_3 + treatment_graph_3\ndf_graph_3[\"x-axis\"] = X_untreated + X_treated\n```\n\n\n```python\nbins_rhs_graph_3 = compute_binned_averages(1,\"attending\",60,5,rslt_graph_3)\nbins_lhs_graph_3 = compute_binned_averages(0,\"attending\",60,5,rslt_graph_3)\n```\n\n\n```python\nR_sq_iterated_df_graph_3 = create_R_sq_df(\"attending\",\"rel_score_redefined\",rslt_graph_3)\n```\n\n\n```python\nylabel_graph_3 = \"Children Enrolled in School\"\ntitle_graph_3 = \"Figure 3: Probability of Enrollment in School According to Village's Relative Score\"\nplot_discontinuity(ylabel_graph_3,title_graph_3,df_graph_3,bins_lhs_graph_3,bins_rhs_graph_3,R_sq_iterated_df_graph_3,1)\n```\n\n\n```python\narg_maximum_graph_3 = R_sq_iterated_df_graph_3.loc[R_sq_iterated_df_graph_3[\"R-squared Values\"] == max(R_sq_iterated_df_graph_3[\"R-squared Values\"])]\narg_maximum_graph_3\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Xgrid for R-squared Values</th>\n      <th>R-squared Values</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>258</th>\n      <td>8.0</td>\n      <td>0.060633</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n#### Table 6. Effects of BRIGHT Schools According to Gender \n\nAs a primary goal of the BRIGHT program was to improve school outcomes for girls, Table 6 disaggregates a number of estimated treatment effects by gender. Using self-reported enrollment (column 1) as the dependent variable, the estimated coefficient for the interaction term between treatment and female indicator variables suggests that the BRIGHT program encouraged girls to attend school at a rate 4.7 percentage points higher than the rate calculated for boys. The estimated effect on verified enrollment (column 2) is comparably large at a rate of 5.6 percentage points over the boys' rate. Although the authors find an economically and statistically significant increase in school enrollment for girls, their results do not identify a significant gender differential in the highest grade achieved (column 3) or in total test scores (column 4).  \n\n\n```python\ny_var_table_6_pt1 = [\"attending\",\"attending2\", \"total_norm\"]\ny_var_table_6_pt2 = \"Ch_Highest_Grade\"\nX_matrix_table_6 = [\"proj_selected\", \"rel_score\", \"Ch_GirlXproj\", \"clustercode\"]\n\ny_table_6_pt1,X_table_6_pt1 = get_data(0,0,1, y_var_table_6_pt1, X_matrix_table_6)\n\ny_table_6_pt2, X_table_6_pt1 = get_data(0,0,1, y_var_table_6_pt2, X_matrix_table_6)\n```\n\n\n```python\nvarying_depend_var_table6 = regress_for_diff_outcomes_poly_features(y_table_6_pt1,y_var_table_6_pt1,X_table_6_pt1,2,1)\n```\n\n\n```python\nmod_table6_rel_2_cluster = regress_cluster_se_corrected(y_table_6_pt2, X_table_6_pt1, 2)\n```\n\n\n```python\ntable_6_models = [varying_depend_var_table6[0], \n                  varying_depend_var_table6[1], \n                  mod_table6_rel_2_cluster,\n                  varying_depend_var_table6[2]]\n\ntable_6_covariate_list = [\"proj_selected\",\"Ch_GirlXproj\",\"rel_score1\",\"rel_score2\",\"const\"]\n\ntable_6_title = 'Table 6\u2014Effects of BRIGHT Schools According to Gender'\n\ntable_6_rename_covariates = {'proj_selected': 'Selected for BRIGHT (Rel. Score \u2265 0)',\n                             'Ch_GirlXproj':'Selected x Female',\n                             'rel_score1':'Rel. Score',\n                             'rel_score2':'Rel. Score ^ 2',\n                             'const': 'Constant'}\ntable_6_notes = [\"\"]\n\ntable_6 = create_table(table_6_models,table_6_covariate_list,table_6_title,\n                       table_6_rename_covariates,table_6_notes)\n\ntable_6.add_line('Demographic Controls', ['Yes','Yes','Yes','Yes'])\ntable_6.add_line('Department Fixed Effects', ['Yes','Yes','Yes','Yes'])\ntable_6.custom_columns(['Reported Enrollment','Verified Enrollment','Highest Grade', 'Total Score'], [1,1,1,1])\ntable_6\n```\n\n\n\n\nTable 6\u2014Effects of BRIGHT Schools According to Gender<br><table style=\"text-align:center\"><tr><td colspan=\"5\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align:left\"></td><tr><td></td><td colspan=\"1\">Reported Enrollment</td><td colspan=\"1\">Verified Enrollment</td><td colspan=\"1\">Highest Grade</td><td colspan=\"1\">Total Score</td></tr><tr><td style=\"text-align:left\"></td><td>(1)</td><td>(2)</td><td>(3)</td><td>(4)</td></tr><tr><td colspan=\"5\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align:left\">Selected for BRIGHT (Rel. Score \u2265 0)</td><td>0.163<sup>***</sup></td><td>0.129<sup>***</sup></td><td>0.403<sup>***</sup></td><td>0.407<sup>***</sup></td></tr><tr><td style=\"text-align:left\"></td><td>(0.026)</td><td>(0.027)</td><td>(0.061)</td><td>(0.052)</td></tr><tr><td style=\"text-align:left\">Selected x Female</td><td>0.047<sup>***</sup></td><td>0.056<sup>***</sup></td><td>0.025<sup></sup></td><td>0.005<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td>(0.018)</td><td>(0.017)</td><td>(0.045)</td><td>(0.036)</td></tr><tr><td style=\"text-align:left\">Rel. Score</td><td>1.133<sup>**</sup></td><td>0.800<sup></sup></td><td>4.264<sup>***</sup></td><td>1.856<sup>**</sup></td></tr><tr><td style=\"text-align:left\"></td><td>(0.547)</td><td>(0.682)</td><td>(1.142)</td><td>(0.842)</td></tr><tr><td style=\"text-align:left\">Rel. Score ^ 2</td><td>-3.163<sup>*</sup></td><td>-2.491<sup></sup></td><td>-13.020<sup>***</sup></td><td>-6.598<sup>***</sup></td></tr><tr><td style=\"text-align:left\"></td><td>(1.618)</td><td>(1.786)</td><td>(3.233)</td><td>(2.374)</td></tr><tr><td style=\"text-align:left\">Constant</td><td>0.114<sup></sup></td><td>0.154<sup></sup></td><td>-0.253<sup></sup></td><td>-0.538<sup>**</sup></td></tr><tr><td style=\"text-align:left\"></td><td>(0.123)</td><td>(0.126)</td><td>(0.279)</td><td>(0.234)</td></tr><tr><td style=\"text-align: left\">Demographic Controls</td><td>Yes</td><td>Yes</td><td>Yes</td><td>Yes</td></tr><tr><td style=\"text-align: left\">Department Fixed Effects</td><td>Yes</td><td>Yes</td><td>Yes</td><td>Yes</td></tr><td colspan=\"5\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align: left\">Observations</td><td>17,970</td><td>17,970</td><td>17,925</td><td>17,970</td></tr><tr><td style=\"text-align: left\">R<sup>2</sup></td><td>0.186</td><td>0.168</td><td>0.200</td><td>0.187</td></tr><tr><td style=\"text-align: left\">Adjusted R<sup>2</sup></td><td>0.182</td><td>0.164</td><td>0.196</td><td>0.184</td></tr><tr><td style=\"text-align: left\">Residual Std. Error</td><td>0.451</td><td>0.444</td><td>1.206</td><td>0.969</td></tr><tr><td style=\"text-align: left\">F Statistic</td><td>19.266<sup>***</sup></td><td>16.047<sup>***</sup></td><td>26.006<sup>***</sup></td><td>22.752<sup>***</sup></td></tr><tr><td colspan=\"5\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align: left\">Note:</td>\n <td colspan=\"4\" style=\"text-align: right\">\n  <sup>*</sup>p&lt;0.1;\n  <sup>**</sup>p&lt;0.05;\n  <sup>***</sup>p&lt;0.01\n </td></tr><tr><td></td><td colspan=\"4\" style=\"text-align: right\"></td></tr></table>\n\n\n\n### 5.3.2. Treatment Effect on Test Scores <a name=\"5.3.2\"></a>\n\n#### Table 7. Effects of BRIGHT Schools on Total Scores\n\nFurther investigation of the program's effect on children's academic outcomes estimates an increase in total test scores by approximately 0.41 standard deviations (Table 7, column 1) using the preferred quadratic model specification. This estimated effect also proves insensitive to variations in the regression model. Although the authors report that the model restricting the relative score to a range of (-40,40) includes demographic controls as well as department fixed effects, the coefficient estimate I computed through my replication efforts did not match the treatment effect disclosed in Table 7 (column 6) of Kazianga et al. (2013). \n\nUpon further observation, the complementary Stata code suggests that the authors failed to account for demographic controls and only included department fixed effects in the regression model. For the sake of completeness, my replication of Table 7 summarizes the results for both model specifications: the model summarized in column 6 only includes department fixed effects, whereas the specification reported in column 7 accounts for both department-level fixed effects and for demographic controls. Despite this discrepancy in reported outcomes, both models estimate cofficients for the treatment indicator variable that are comparable in size and are statistically significant.   \n\n\n```python\ny_var_table_7 = \"total_norm\"\nX_matrix_table_7 = [\"rel_score\", \"clustercode\",\"proj_selected\"]\n\ny_table_7_pt1,X_table_7_pt1 = get_data(0,0,1, y_var_table_7, X_matrix_table_7)\n\ny_table_7_pt2_no_controls,X_table_7_pt2_no_controls = get_data(0,0,0, y_var_table_7,X_matrix_table_7)\n```\n\n\n```python\nfitted_poly_models_table7 = fit_poly_models_iterate(y_table_7_pt1, X_table_7_pt1,3, 1)\n\nmod_table7_rel_2_no_controls = calculate_polynomial_features(1, y_table_7_pt2_no_controls,X_table_7_pt2_no_controls, 2)\n\nmod_table7_interaction = calculate_polynomial_interaction(1, y_table_7_pt1,X_table_7_pt1, interact1, interact2, 2)\n\n#results slightly off, but not way off. Realized why: even though it says controls are included in this regression, \n#they are not included in Stata code. Report both below. \n\nmod_table7_reduced_no_controls = calculate_reduced_range_40(1, y_table_7_pt1,X_table_7_pt2_no_controls)\nmod_table7_reduced = calculate_reduced_range_40(1, y_table_7_pt1,X_table_7_pt1)\n```\n\n\n```python\ntable_7_models = [fitted_poly_models_table7[1],\n                  mod_table7_rel_2_no_controls,  \n                  fitted_poly_models_table7[0],\n                  fitted_poly_models_table7[2],\n                  mod_table7_interaction,\n                  mod_table7_reduced_no_controls,\n                  mod_table7_reduced]\ntable_7_covariate_list = [\"proj_selected\",\"rel_score1\",\"rel_score2\",\"rel_score3\",\n                          \"interaction_term1\",\"interaction_term2\",\"const\"]\ntable_7_title = 'Table 7\u2014Effects of BRIGHT Schools on Total Scores'\ntable_7_rename_covariates = {'proj_selected': 'Selected for BRIGHT (Rel. Score \u2265 0)',\n                           'rel_score1':'Rel. Score',\n                           'rel_score2':'Rel. Score ^ 2',\n                           'interaction_term1':'Rel. Score x Selected',\n                           'interaction_term2':'Rel. Score ^ 2 x Selected',\n                           'const': 'Constant'}\ntable_7_notes = [\"Model (1): Quadratic\", \n                 \"Model (2): Quadratic without Controls\",\n                 \"Model (3): Linear\",\n                 \"Model (4): Cubic\",\n                 \"Model (5): Interacted Quadratic\",\n                 \"Model (6): |Rel.Score| < 40 without controls\",\n                 \"Model (7): |Rel.Score| < 40 with controls\"]\ntable_7 = create_table(table_7_models,table_7_covariate_list,table_7_title,\n                       table_7_rename_covariates,table_7_notes)\ntable_7.add_line('Demographic Controls', ['Yes','No','Yes','Yes','Yes','No', 'Yes'])\ntable_7.add_line('Department Fixed Effects', ['Yes','Yes','Yes','Yes','Yes','Yes', 'Yes'])\ntable_7\n```\n\n\n\n\nTable 7\u2014Effects of BRIGHT Schools on Total Scores<br><table style=\"text-align:center\"><tr><td colspan=\"8\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align:left\"></td><td colspan=\"7\"><em>Dependent variable:total_norm</em></td></tr><tr><td style=\"text-align:left\"></td><tr><td style=\"text-align:left\"></td><td>(1)</td><td>(2)</td><td>(3)</td><td>(4)</td><td>(5)</td><td>(6)</td><td>(7)</td></tr><tr><td colspan=\"8\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align:left\">Selected for BRIGHT (Rel. Score \u2265 0)</td><td>0.409<sup>***</sup></td><td>0.420<sup>***</sup></td><td>0.446<sup>***</sup></td><td>0.420<sup>***</sup></td><td>0.422<sup>***</sup></td><td>0.384<sup>***</sup></td><td>0.356<sup>***</sup></td></tr><tr><td style=\"text-align:left\"></td><td>(0.050)</td><td>(0.053)</td><td>(0.049)</td><td>(0.050)</td><td>(0.060)</td><td>(0.063)</td><td>(0.060)</td></tr><tr><td style=\"text-align:left\">Rel. Score</td><td>1.857<sup>**</sup></td><td>2.400<sup>***</sup></td><td>0.392<sup></sup></td><td>1.217<sup></sup></td><td>-1.480<sup></sup></td><td></td><td></td></tr><tr><td style=\"text-align:left\"></td><td>(0.842)</td><td>(0.900)</td><td>(0.765)</td><td>(0.927)</td><td>(5.923)</td><td></td><td></td></tr><tr><td style=\"text-align:left\">Rel. Score ^ 2</td><td>-6.601<sup>***</sup></td><td>-8.346<sup>***</sup></td><td></td><td>13.822<sup></sup></td><td>-15.452<sup></sup></td><td></td><td></td></tr><tr><td style=\"text-align:left\"></td><td>(2.373)</td><td>(2.574)</td><td></td><td>(11.614)</td><td>(70.916)</td><td></td><td></td></tr><tr><td style=\"text-align:left\">rel_score3</td><td></td><td></td><td></td><td>-51.001<sup>*</sup></td><td></td><td></td><td></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td>(27.262)</td><td></td><td></td><td></td></tr><tr><td style=\"text-align:left\">Rel. Score x Selected</td><td></td><td></td><td></td><td></td><td>5.056<sup></sup></td><td></td><td></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td>(6.603)</td><td></td><td></td></tr><tr><td style=\"text-align:left\">Rel. Score ^ 2 x Selected</td><td></td><td></td><td></td><td></td><td>4.192<sup></sup></td><td></td><td></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td>(70.368)</td><td></td><td></td></tr><tr><td style=\"text-align:left\">Constant</td><td>-0.540<sup>**</sup></td><td>0.171<sup></sup></td><td>-0.561<sup>**</sup></td><td>-0.564<sup>**</sup></td><td>-0.574<sup>**</sup></td><td>0.024<sup></sup></td><td>-0.707<sup>**</sup></td></tr><tr><td style=\"text-align:left\"></td><td>(0.235)</td><td>(0.180)</td><td>(0.233)</td><td>(0.234)</td><td>(0.234)</td><td>(0.192)</td><td>(0.290)</td></tr><tr><td style=\"text-align: left\">Demographic Controls</td><td>Yes</td><td>No</td><td>Yes</td><td>Yes</td><td>Yes</td><td>No</td><td>Yes</td></tr><tr><td style=\"text-align: left\">Department Fixed Effects</td><td>Yes</td><td>Yes</td><td>Yes</td><td>Yes</td><td>Yes</td><td>Yes</td><td>Yes</td></tr><td colspan=\"8\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align: left\">Observations</td><td>17,970</td><td>17,970</td><td>17,970</td><td>17,970</td><td>17,970</td><td>5,595</td><td>5,595</td></tr><tr><td style=\"text-align: left\">R<sup>2</sup></td><td>0.187</td><td>0.107</td><td>0.186</td><td>0.188</td><td>0.188</td><td>0.100</td><td>0.180</td></tr><tr><td style=\"text-align: left\">Adjusted R<sup>2</sup></td><td>0.184</td><td>0.104</td><td>0.183</td><td>0.184</td><td>0.184</td><td>0.095</td><td>0.171</td></tr><tr><td style=\"text-align: left\">Residual Std. Error</td><td>0.969</td><td>1.015</td><td>0.970</td><td>0.969</td><td>0.969</td><td>0.997</td><td>0.954</td></tr><tr><td style=\"text-align: left\">F Statistic</td><td>22.172<sup>***</sup></td><td>11.580<sup>***</sup></td><td>21.839<sup>***</sup></td><td>23.293<sup>***</sup></td><td>22.437<sup>***</sup></td><td>14.502<sup>***</sup></td><td>31.222<sup>***</sup></td></tr><tr><td colspan=\"8\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align: left\">Note:</td>\n <td colspan=\"7\" style=\"text-align: right\">\n  <sup>*</sup>p&lt;0.1;\n  <sup>**</sup>p&lt;0.05;\n  <sup>***</sup>p&lt;0.01\n </td></tr><tr><td></td><td colspan=\"7\" style=\"text-align: right\">Model (1): Quadratic</td></tr><tr><td></td><td colspan=\"7\" style=\"text-align: right\">Model (2): Quadratic without Controls</td></tr><tr><td></td><td colspan=\"7\" style=\"text-align: right\">Model (3): Linear</td></tr><tr><td></td><td colspan=\"7\" style=\"text-align: right\">Model (4): Cubic</td></tr><tr><td></td><td colspan=\"7\" style=\"text-align: right\">Model (5): Interacted Quadratic</td></tr><tr><td></td><td colspan=\"7\" style=\"text-align: right\">Model (6): |Rel.Score| < 40 without controls</td></tr><tr><td></td><td colspan=\"7\" style=\"text-align: right\">Model (7): |Rel.Score| < 40 with controls</td></tr></table>\n\n\n\n#### Figure 4. Normalized Total Test Score According to Village's Relative Score\n\nFigure 4 employs a similar nonparametric estimation procedure shown in Figures 1 and 3 to complement the parametric results summarized above in Table 7. The discontinuity at the arbitrary cutoff represents a visible increase in total test scores for children, who attended a BRIGHT school.\n\nThe authors also plot the $R^2$ values estimated for the specification described in equation (2) to confirm the location of the discontinuity for total test scores. The plotted $R^2$ values are represented by the blue curve in Figure 4. According to the `arg_maximum_graph_4` dataframe produced below, the $R^2$ values are maximized exactly at the zero cutoff. \n\n\n```python\nselected_columns_graph_4 = [\"total_norm\", \"proj_selected\", \"rel_score_redefined\",\"rel_score\"]\n\nrslt_untreated_graph_4 = get_data_graphs(selected_columns_graph_4,0,0)\nrslt_treated_graph_4 = get_data_graphs(selected_columns_graph_4,0,1)\nrslt_graph_4 = get_data_graphs(selected_columns_graph_4,0,2)\n```\n\n\n```python\ny_var_graph_4 = \"total_norm\"\nx_var_graph_4 = \"rel_score_redefined\"\n```\n\n\n```python\ncontrol_graph_4 = [compute_locally_weighted_reg(y_var_graph_4,x_var_graph_4,item,bandwidth, rslt_untreated_graph_4) \n                   for item in X_untreated]\ntreatment_graph_4 = [compute_locally_weighted_reg(y_var_graph_4,x_var_graph_4,item,bandwidth, rslt_treated_graph_4) \n                     for item in X_treated]\n\ndf_graph_4 = pd.DataFrame()\ndf_graph_4[\"y-axis\"] = control_graph_4 + treatment_graph_4\ndf_graph_4[\"x-axis\"] = X_untreated + X_treated\n```\n\n\n```python\nbins_rhs_graph_4 = compute_binned_averages(1,\"total_norm\",60,5,rslt_graph_4)\nbins_lhs_graph_4 = compute_binned_averages(0,\"total_norm\",60,5,rslt_graph_4)\n```\n\n\n```python\nR_sq_iterated_df_graph_4 = create_R_sq_df(\"total_norm\",\"rel_score_redefined\",rslt_graph_4)\n```\n\n\n```python\nylabel_graph_4 = \"Normalized Total Test Scores\"\ntitle_graph_4 = \"Figure 4: Normalized Total Test Score According to Village's Relative Score\"\nplot_discontinuity(ylabel_graph_4, title_graph_4,df_graph_4,bins_lhs_graph_4,bins_rhs_graph_4,\n                   R_sq_iterated_df_graph_4,2)\n```\n\n\n```python\narg_maximum_graph_4 = R_sq_iterated_df_graph_4.loc[R_sq_iterated_df_graph_4[\"R-squared Values\"] == max(R_sq_iterated_df_graph_4[\"R-squared Values\"])]\narg_maximum_graph_4\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Xgrid for R-squared Values</th>\n      <th>R-squared Values</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>250</th>\n      <td>0.0</td>\n      <td>0.051859</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## 5.4. School Access vs. BRIGHT Amenities <a name=\"5.4\"></a>\n\nIn the final stage of their analysis, Kazianga et al. (2013) present evidence that examines whether the measured treatment effects were a result of increased school accessibility or of the BRIGHT program's unique characteristics. To do so, the authors make use of two different regression strategies. Using a traditional OLS regression model, they first estimate student outcomes for children in villages with BRIGHT schools, non-BRIGHT schools, and no schools. \n\nDespite providing evidence to corroborate the critical continuity assumption, Kazianga et al. (2013) address the potential existence of endogeneity bias in their second strategy by restricting the sample of villages to those that had schools in 2004 - just a year before the program announced the villages that were selected to receive a BRIGHT school. Since these schools were upgraded to meet the requirements of a BRIGHT school, the authors took advantage of this knowledge and directly employed the properties of the RD design to estimate the effect of the unique BRIGHT characteristics on student outcomes. For the sake of readability, I have decomposed the original Table 8 in Kazianga et al. (2013) into two smaller tables: Table 8.a. presents the relative effect of the BRIGHT program on enrollment, whereas Table 8.b. summarizes the program's relative effect on total test scores.   \n\n#### Table 8. Relative Effect of School Improvement versus School Access\n\n\n```python\ny_var_table_8 = [\"attending\", \"total_norm\"]\nX_matrix_table_8 = [\"MCC_School\", \"has_school\", \"clustercode\", \"rel_score\"]\n\ny_table_8_no_controls,X_table_8_no_controls = get_data(0,0,0, y_var_table_8,X_matrix_table_8)\n\ny_table_8_controls,X_table_8_controls = get_data(0,0,1, y_var_table_8, X_matrix_table_8)\n\nX_matrix_table_8_subset = [\"proj_selected\",\"rel_score\",\"Vill_HadSchool2004\", \"clustercode\"]\n\ny_table_8_subset, X_table_8_subset = get_data(0,0,1, y_var_table_8, X_matrix_table_8_subset)\n\ny_table_8_subset = y_table_8_subset.loc[X_table_8_subset[\"Vill_HadSchool2004\"]==1].reset_index(drop = True)\nX_table_8_subset = X_table_8_subset.loc[X_table_8_subset[\"Vill_HadSchool2004\"]==1].reset_index(drop = True)\n```\n\n\n```python\n#For some reason, Table 8 reports results for first and fourth columns when fixed effects are NOT included even though \n#the table indicates that fixed effects were included. I report here results for when fixed effects are included, since\n#it is more robust to include fixed effects \n\nvarying_depend_var_table8_no_controls = regress_for_diff_outcomes_poly_features(y_table_8_no_controls,\n                                                                                y_var_table_8,\n                                                                                X_table_8_no_controls,0,1)\n\n#results reported in Table 8, where fixed effects are not included are reported here: \n\nvarying_depend_var_table8_no_controls_or_FEs = regress_for_diff_outcomes_poly_features(y_table_8_no_controls,\n                                                                                       y_var_table_8,X_table_8_no_controls.iloc[:,0:5],0,1)\n\nvarying_depend_var_table8 = regress_for_diff_outcomes_poly_features(y_table_8_controls,\n                                                                    y_var_table_8,X_table_8_controls,0,1)  \n\nvarying_depend_var_table8_subset = regress_for_diff_outcomes_poly_features(y_table_8_subset,y_var_table_8,\n                                                                           X_table_8_subset.drop(\"Vill_HadSchool2004\", axis=1),\n                                                                           2,1)\n```\n\n\n```python\ntable_8a_models = [varying_depend_var_table8_no_controls_or_FEs[0],\n                   varying_depend_var_table8_no_controls[0], \n                   varying_depend_var_table8[0],\n                   varying_depend_var_table8_subset[0]]\ntable_8a_covariate_list = [\"proj_selected\",\"MCC_School\",\"has_school\",\"const\"]\n\ntable_8a_title = 'Table 8a\u2014Relative Effect of School Improvement versus School Access, Dependent Variable: Enrollment'\n\ntable_8a_rename_covariates = {'proj_selected': 'Selected for BRIGHT (Rel. Score \u2265 0)',\n                              'MCC_School':'MCC School',\n                              'has_school':'Any Village School',\n                              'const': 'Constant'}\ntable_8a_notes = ['']\ntable_8a = create_table(table_8a_models,table_8a_covariate_list,table_8a_title,\n                       table_8a_rename_covariates,table_8a_notes)\n\n\ntable_8a.custom_columns(['All Villages','All Villages', 'All Villages', 'Village Had School, 2004'], [1, 1, 1,1])\ntable_8a.add_line('Demographic Controls', ['No','No','Yes','Yes'])\ntable_8a.add_line('Department Fixed Effects', ['No','Yes','Yes','Yes'])\n\n\ntable_8b_models = [varying_depend_var_table8_no_controls_or_FEs[1],\n                   varying_depend_var_table8_no_controls[1],\n                   varying_depend_var_table8[1], \n                   varying_depend_var_table8_subset[1]]\n\ntable_8b_covariate_list = [\"proj_selected\",\"MCC_School\",\"has_school\",\"const\"]\n\ntable_8b_title = 'Table 8b\u2014Relative Effect of School Improvement versus School Access, Dependent Variable: Total Score'\n\ntable_8b_rename_covariates = {'proj_selected': 'Selected for BRIGHT (Rel. Score \u2265 0)',\n                              'MCC_School':'MCC School',\n                              'has_school':'Any Village School',\n                              'const': 'Constant'}\ntable_8b_notes = ['']\n\ntable_8b = create_table(table_8b_models,table_8b_covariate_list,table_8b_title,\n                        table_8b_rename_covariates,table_8b_notes)\n\ntable_8b.custom_columns(['All Villages','All Villages', 'All Villages', 'Village Had School, 2004'], [1, 1, 1, 1])\n\ntable_8b.add_line('Demographic Controls', ['No','No','Yes','Yes'])\ntable_8b.add_line('Department Fixed Effects', ['No','Yes','Yes','Yes'])\n```\n\n#### Table 8.a. Relative Effect of School Improvement versus School Access on Enrollment\n\nSimilar to the model specification disparity identified in Table 7, my replication efforts suggest inconsistencies in the results summarized under Table 8 as well. Although the authors claim that the estimates for the regression model reported in column (1) of their paper only include department fixed effects, it appears that their model neither contains demographic controls nor department fixed effects. For the purpose of transparency, I report both cases in my replication of Table 8. In column (1) of Table 8.a., I replicate the exact results of the initial model specification summarized in Table 8 of Kazianga et al. (2013) by eliminating both demographic controls and department fixed effects. I then include only department-level fixed effects for the specification in column (2) of Table 8.a. to estimate the model results for the specification that Kazianga et al. (2013) intended to summarize in column (1) of their Table 8 results. \n\nAccording to Table 8.a., these models indicate that the amenities provided at BRIGHT schools (referred to here also as MCC schools) produce an additional increase in enrollment of comparable size (around 13 or 14 percentage points above the effect on enrollment estimated for schools that do not have BRIGHT amenities). When the authors include demographic controls and department fixed effects, the magnitude of the treatment effect falls minimally to approximately 12.6 percentage points (column 3, Table 8.a.). In all three cases of the basic OLS estimation, the results remain statistically significant at the 1 percent level. \n\nIn the fourth column of Table 8.a., I replicate the authors' results for the RD design by limiting the regression sample to villages that had a school in 2004. With a disontinuity estimate that is only slightly larger than the results estimated by the OLS regressions and exhibits significance at the 1 percent level, the RD design yields comparable measurements to those reported in columns (1) through (3).    \n\n\n\n```python\ntable_8a\n```\n\n\n\n\nTable 8a\u2014Relative Effect of School Improvement versus School Access, Dependent Variable: Enrollment<br><table style=\"text-align:center\"><tr><td colspan=\"5\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align:left\"></td><td colspan=\"4\"><em>Dependent variable:attending</em></td></tr><tr><td style=\"text-align:left\"></td><tr><td></td><td colspan=\"1\">All Villages</td><td colspan=\"1\">All Villages</td><td colspan=\"1\">All Villages</td><td colspan=\"1\">Village Had School, 2004</td></tr><tr><td style=\"text-align:left\"></td><td>(1)</td><td>(2)</td><td>(3)</td><td>(4)</td></tr><tr><td colspan=\"5\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align:left\">Selected for BRIGHT (Rel. Score \u2265 0)</td><td></td><td></td><td></td><td>0.153<sup>***</sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td>(0.040)</td></tr><tr><td style=\"text-align:left\">MCC School</td><td>0.138<sup>***</sup></td><td>0.132<sup>***</sup></td><td>0.126<sup>***</sup></td><td></td></tr><tr><td style=\"text-align:left\"></td><td>(0.027)</td><td>(0.021)</td><td>(0.020)</td><td></td></tr><tr><td style=\"text-align:left\">Any Village School</td><td>0.267<sup>***</sup></td><td>0.277<sup>***</sup></td><td>0.265<sup>***</sup></td><td></td></tr><tr><td style=\"text-align:left\"></td><td>(0.034)</td><td>(0.031)</td><td>(0.031)</td><td></td></tr><tr><td style=\"text-align:left\">Constant</td><td>0.184<sup>***</sup></td><td>0.268<sup>***</sup></td><td>-0.030<sup></sup></td><td>0.855<sup>***</sup></td></tr><tr><td style=\"text-align:left\"></td><td>(0.027)</td><td>(0.071)</td><td>(0.102)</td><td>(0.165)</td></tr><tr><td style=\"text-align: left\">Demographic Controls</td><td>No</td><td>No</td><td>Yes</td><td>Yes</td></tr><tr><td style=\"text-align: left\">Department Fixed Effects</td><td>No</td><td>Yes</td><td>Yes</td><td>Yes</td></tr><td colspan=\"5\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align: left\">Observations</td><td>17,970</td><td>17,970</td><td>17,970</td><td>1,568</td></tr><tr><td style=\"text-align: left\">R<sup>2</sup></td><td>0.095</td><td>0.156</td><td>0.216</td><td>0.222</td></tr><tr><td style=\"text-align: left\">Adjusted R<sup>2</sup></td><td>0.095</td><td>0.153</td><td>0.212</td><td>0.196</td></tr><tr><td style=\"text-align: left\">Residual Std. Error</td><td>0.474</td><td>0.459</td><td>0.442</td><td>0.445</td></tr><tr><td style=\"text-align: left\">F Statistic</td><td>81.996<sup>***</sup></td><td>28.504<sup>***</sup></td><td>41.359<sup>***</sup></td><td>67.609<sup>***</sup></td></tr><tr><td colspan=\"5\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align: left\">Note:</td>\n <td colspan=\"4\" style=\"text-align: right\">\n  <sup>*</sup>p&lt;0.1;\n  <sup>**</sup>p&lt;0.05;\n  <sup>***</sup>p&lt;0.01\n </td></tr><tr><td></td><td colspan=\"4\" style=\"text-align: right\"></td></tr></table>\n\n\n\n#### Table 8.b. Relative Effect of School Improvement versus School Access on Total Test Scores\n\nAs the inconsistencies in model specification are also present in the measured relative effect on total test scores, I apply the same procedure from Table 8.a. to replicate the additional effect of BRIGHT amenities on test scores. Column (1) of Table 8.b. reports the exact results of the initial model specification summarized in Table 8 of Kazianga et al. (2013) by eliminating both demographic controls and department fixed effects. In column (2) of Table 8.b., I then include only department-level fixed effects to estimate the model results for the specification that Kazianga et al. (2013) intended to summarize in column (4) of their Table 8 results. Including both demographic controls and department fixed effects yields a comparable albeit slightly lower coefficient estimate. In all three cases of the basic OLS regression, the coefficient estimate indicates that BRIGHT school amenities increase test scores by approximately 0.35 standard deviations. Despite changes to the model specification, these results maintain statistical significance at the 1 percent level. In column (4) of Table 8.b., I was also able to replicate the estimated effect reported by the authors for the RD design. Although this final estimate is slightly larger than the results estimated by the OLS regressions, the difference is minimal and also exhibits significance at the 1 percent level. As such, the RD design yields comparable measurements to those reported by the simple OLS regression models in columns (1) through (3). \n\n\n```python\ntable_8b\n```\n\n\n\n\nTable 8b\u2014Relative Effect of School Improvement versus School Access, Dependent Variable: Total Score<br><table style=\"text-align:center\"><tr><td colspan=\"5\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align:left\"></td><td colspan=\"4\"><em>Dependent variable:total_norm</em></td></tr><tr><td style=\"text-align:left\"></td><tr><td></td><td colspan=\"1\">All Villages</td><td colspan=\"1\">All Villages</td><td colspan=\"1\">All Villages</td><td colspan=\"1\">Village Had School, 2004</td></tr><tr><td style=\"text-align:left\"></td><td>(1)</td><td>(2)</td><td>(3)</td><td>(4)</td></tr><tr><td colspan=\"5\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align:left\">Selected for BRIGHT (Rel. Score \u2265 0)</td><td></td><td></td><td></td><td>0.388<sup>***</sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td>(0.066)</td></tr><tr><td style=\"text-align:left\">MCC School</td><td>0.377<sup>***</sup></td><td>0.367<sup>***</sup></td><td>0.346<sup>***</sup></td><td></td></tr><tr><td style=\"text-align:left\"></td><td>(0.056)</td><td>(0.045)</td><td>(0.043)</td><td></td></tr><tr><td style=\"text-align:left\">Any Village School</td><td>0.284<sup>***</sup></td><td>0.324<sup>***</sup></td><td>0.323<sup>***</sup></td><td></td></tr><tr><td style=\"text-align:left\"></td><td>(0.071)</td><td>(0.069)</td><td>(0.066)</td><td></td></tr><tr><td style=\"text-align:left\">Constant</td><td>-0.242<sup>***</sup></td><td>-0.019<sup></sup></td><td>-0.691<sup>***</sup></td><td>1.168<sup>***</sup></td></tr><tr><td style=\"text-align:left\"></td><td>(0.057)</td><td>(0.148)</td><td>(0.218)</td><td>(0.423)</td></tr><tr><td style=\"text-align: left\">Demographic Controls</td><td>No</td><td>No</td><td>Yes</td><td>Yes</td></tr><tr><td style=\"text-align: left\">Department Fixed Effects</td><td>No</td><td>Yes</td><td>Yes</td><td>Yes</td></tr><td colspan=\"5\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align: left\">Observations</td><td>17,970</td><td>17,970</td><td>17,970</td><td>1,568</td></tr><tr><td style=\"text-align: left\">R<sup>2</sup></td><td>0.060</td><td>0.115</td><td>0.197</td><td>0.321</td></tr><tr><td style=\"text-align: left\">Adjusted R<sup>2</sup></td><td>0.060</td><td>0.112</td><td>0.193</td><td>0.299</td></tr><tr><td style=\"text-align: left\">Residual Std. Error</td><td>1.040</td><td>1.011</td><td>0.964</td><td>0.985</td></tr><tr><td style=\"text-align: left\">F Statistic</td><td>54.529<sup>***</sup></td><td>15.756<sup>***</sup></td><td>26.785<sup>***</sup></td><td>50.961<sup>***</sup></td></tr><tr><td colspan=\"5\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align: left\">Note:</td>\n <td colspan=\"4\" style=\"text-align: right\">\n  <sup>*</sup>p&lt;0.1;\n  <sup>**</sup>p&lt;0.05;\n  <sup>***</sup>p&lt;0.01\n </td></tr><tr><td></td><td colspan=\"4\" style=\"text-align: right\"></td></tr></table>\n\n\n\n---\n# 6. Project Extensions <a name=\"6\"></a>\n---\n\nIn the following section, I present a number of extensions for the results obtained by Kazianga et al. (2013). I begin with a supplementary analysis of the continuity assumption using further descriptive statistics and visualizations. I then explore the effect of the BRIGHT program on math and French test scores by gender to determine if the results for the normalized total test scores are representative of the disaggregated treatment effects as well. In the third subsection, I examine the differences between the joint and separate OLS model structures for estimating the treatment discontinuity at the cutoff. The fourth project extension implements a placebo test strategy to confirm that there are no discontinuities along the distributions of the main outcome variables except for at the selected cutoff value. The fifth and final subsection introduces two bandwidth sensitivity checks to evaluate the authors' decision to use a quadratic regression model as their preferred specification instead of a local linear regression (LLR) with an optimizing bandwidth.\n\n## 6.1. Supplementary Analysis of the Critical Continuity Assumption <a name=\"6.1\"></a>   \n\nBefore Kazianga et al. (2013) reported the estimated treatment effects of the BRIGHT program, they tested the internal validity of their chosen RD design by measuring several differentials through parametric and nonparametric methods. In particular, Table 2 provides evidence to suggest that the design of the BRIGHT program fulfills the critical continuity assumption. By parametrically estimating discontinuities at the cutoff value for 28 household characteristics, the authors find only three statistically significant differentials between children, who had access to a BRIGHT school, and those, who did not. Upon further analysis, however, these differences account for potentially negligible levels of implied bias. As such, Table 2 sufficiently demonstrates continuity at the cutoff for a number of observable characteristics and thus suggests that the villages in the control and treatment groups are largely similar with the exception of children's access to BRIGHT school facilities. To further support these findings, I include two additional continuity checks that serve as an appropriate initial look at all 28 observable characteristics.\n\n### 6.1.1. Initial Analysis of Descriptive Statistics for Control and Treatment Groups <a name=\"6.1.1\"></a>\n\nAfter splitting the observations at the child level according to their respective village's participation in the control or treatment group, the below table presents the mean and standard deviation of the characteristics listed in Table 2. As the mean and standard deviation outputs are similar for both subsets across all observed characteristics, this continuity table thus supports the general findings of Table 2's regression results. \n\nIt is however important to emphasize the extent to which these summarizing statistics are useful for assessing continuity. At first glance, the descriptive statistics suggest that the differential for households with basic flooring is nearly zero. If the authors were to simply rely on the difference in averages reported below, they would not have observed that the differential, albeit small, is statistically significant. To avoid potentially overlooking significant discrepancies between the control and treatment group that could invalidate the use of a particular evaluation design, it is imperative to conduct more robust analyses such as the regressions summarized in Table 2 of Kazianga et al. (2013). Table E1, however, serves as an initial confirmation that the selected and nonselected villages are more or less similar based on a series of observed characteristics.               \n\n\n```python\ny_table_2[\"rel_score_redefined\"] = X_table_2[\"rel_score\"] * 10000\ny_table_2[\"proj_selected\"] = X_table_2[\"proj_selected\"]\n\n```\n\n#### Table E1. Descriptive Statistics for Control and Treatment Groups\n\n\n```python\ncreate_continuity_table(y_table_2)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th colspan=\"2\" halign=\"left\">Control Villages</th>\n      <th colspan=\"2\" halign=\"left\">Treatment Villages</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>Mean</th>\n      <th>Standard Deviation</th>\n      <th>Mean</th>\n      <th>Standard Deviation</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Hh_HeadMale</th>\n      <td>0.985</td>\n      <td>0.123</td>\n      <td>0.980000</td>\n      <td>0.141</td>\n    </tr>\n    <tr>\n      <th>Hh_HeadAge</th>\n      <td>48.320</td>\n      <td>12.598</td>\n      <td>47.787998</td>\n      <td>12.238</td>\n    </tr>\n    <tr>\n      <th>Hh_HeadSchool</th>\n      <td>0.117</td>\n      <td>0.851</td>\n      <td>0.203000</td>\n      <td>1.002</td>\n    </tr>\n    <tr>\n      <th>Hh_NumMembers</th>\n      <td>10.906</td>\n      <td>6.102</td>\n      <td>10.910000</td>\n      <td>5.830</td>\n    </tr>\n    <tr>\n      <th>Hh_NumKids</th>\n      <td>5.887</td>\n      <td>3.476</td>\n      <td>6.136000</td>\n      <td>3.584</td>\n    </tr>\n    <tr>\n      <th>Ch_Age</th>\n      <td>8.756</td>\n      <td>2.006</td>\n      <td>8.774000</td>\n      <td>1.931</td>\n    </tr>\n    <tr>\n      <th>Ch_Girl</th>\n      <td>0.458</td>\n      <td>0.498</td>\n      <td>0.474000</td>\n      <td>0.499</td>\n    </tr>\n    <tr>\n      <th>Ch_HeadChild</th>\n      <td>0.897</td>\n      <td>0.303</td>\n      <td>0.870000</td>\n      <td>0.337</td>\n    </tr>\n    <tr>\n      <th>Ch_HeadGrandChild</th>\n      <td>0.051</td>\n      <td>0.220</td>\n      <td>0.053000</td>\n      <td>0.224</td>\n    </tr>\n    <tr>\n      <th>Ch_HeadNephew</th>\n      <td>0.030</td>\n      <td>0.170</td>\n      <td>0.041000</td>\n      <td>0.198</td>\n    </tr>\n    <tr>\n      <th>Hh_ReligionMuslin</th>\n      <td>0.591</td>\n      <td>0.492</td>\n      <td>0.575000</td>\n      <td>0.494</td>\n    </tr>\n    <tr>\n      <th>Hh_Animist</th>\n      <td>0.267</td>\n      <td>0.442</td>\n      <td>0.272000</td>\n      <td>0.445</td>\n    </tr>\n    <tr>\n      <th>Hh_Christian</th>\n      <td>0.132</td>\n      <td>0.338</td>\n      <td>0.145000</td>\n      <td>0.352</td>\n    </tr>\n    <tr>\n      <th>Hh_Lang_Fulfude</th>\n      <td>0.179</td>\n      <td>0.383</td>\n      <td>0.198000</td>\n      <td>0.398</td>\n    </tr>\n    <tr>\n      <th>Hh_Lang_Gulmachema</th>\n      <td>0.298</td>\n      <td>0.457</td>\n      <td>0.264000</td>\n      <td>0.441</td>\n    </tr>\n    <tr>\n      <th>Hh_Lang_Moore</th>\n      <td>0.385</td>\n      <td>0.487</td>\n      <td>0.400000</td>\n      <td>0.490</td>\n    </tr>\n    <tr>\n      <th>Hh_Ethnicity_Gourmanche</th>\n      <td>0.303</td>\n      <td>0.459</td>\n      <td>0.275000</td>\n      <td>0.446</td>\n    </tr>\n    <tr>\n      <th>Hh_Ethnicity_Mossi</th>\n      <td>0.398</td>\n      <td>0.489</td>\n      <td>0.402000</td>\n      <td>0.490</td>\n    </tr>\n    <tr>\n      <th>Hh_Ethnicity_Peul</th>\n      <td>0.167</td>\n      <td>0.373</td>\n      <td>0.185000</td>\n      <td>0.388</td>\n    </tr>\n    <tr>\n      <th>Hh_FloorBasic</th>\n      <td>0.947</td>\n      <td>0.224</td>\n      <td>0.915000</td>\n      <td>0.279</td>\n    </tr>\n    <tr>\n      <th>Hh_RoofBasic</th>\n      <td>0.569</td>\n      <td>0.495</td>\n      <td>0.535000</td>\n      <td>0.499</td>\n    </tr>\n    <tr>\n      <th>Hh_Radio</th>\n      <td>0.736</td>\n      <td>0.802</td>\n      <td>0.768000</td>\n      <td>0.813</td>\n    </tr>\n    <tr>\n      <th>Hh_Telmob</th>\n      <td>0.170</td>\n      <td>0.454</td>\n      <td>0.204000</td>\n      <td>0.504</td>\n    </tr>\n    <tr>\n      <th>Hh_Watch</th>\n      <td>0.814</td>\n      <td>0.971</td>\n      <td>0.824000</td>\n      <td>0.915</td>\n    </tr>\n    <tr>\n      <th>Hh_Bike</th>\n      <td>1.475</td>\n      <td>1.264</td>\n      <td>1.471000</td>\n      <td>1.270</td>\n    </tr>\n    <tr>\n      <th>Hh_Cows</th>\n      <td>5.763</td>\n      <td>10.425</td>\n      <td>5.563000</td>\n      <td>9.727</td>\n    </tr>\n    <tr>\n      <th>Hh_Motorbike</th>\n      <td>0.280</td>\n      <td>0.532</td>\n      <td>0.327000</td>\n      <td>0.543</td>\n    </tr>\n    <tr>\n      <th>Hh_Cart</th>\n      <td>0.670</td>\n      <td>0.724</td>\n      <td>0.642000</td>\n      <td>0.708</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### 6.1.2. Visual Analysis of the Continuity Assumption <a name=\"6.1.2\"></a>\n\nAs a second initial continuity check, I plotted the distributions of various household characteristics across the cutoff value to visually represent continuity among treatment and control villages. To do so, I used a binsize of 30 to plot grouped averages on either side of the threshold. Since the majority of children observed in the sample live in villages with relatives scores between -250 and 250 and Kazianga et al. (2013) restrict their plotted figures to observations with a relative score within this range, I will implement the same restriction to the binned averages depicted below. For nearly all observable characteristics plotted below, there does not appear to be any jumps at the threshold value that would indicate a systematic difference between selected and nonselected villages. However, the final visualization, which evaluates the plotted continuity for basic flooring, suggests some degree of discontinuity that requires further investigation.      \n\n#### Figure E1. Plotted Distributions of Demographic Characteristics \n\n\n```python\nplot_continuity_hh([\"Hh_NumMembers\",\"Hh_NumKids\",\"Ch_Age\",\"Ch_Girl\"], y_table_2)\n```\n\n\n```python\nplot_continuity_rel_lang([\"Hh_ReligionMuslin\",\"Hh_Animist\",\"Hh_Christian\", \n                          \"Hh_Lang_Fulfude\", \"Hh_Lang_Gulmachema\", \"Hh_Lang_Moore\"], y_table_2)\n```\n\n\n```python\nplot_continuity_assets([\"Hh_Radio\",\"Hh_Telmob\",\"Hh_Cows\",\"Hh_FloorBasic\"], y_table_2)\n```\n\nDue to coding complications that I was unable to resolve, I did not include fitted quadratic regression curves in the continuity subplots. I therefore selected four of the household characteristics depicted in the scatter plots above and created a separate function to do so below. The curves provide a more useful visualization of the estimated continuity for each characteristic. In order to generate fitted curves that are representative of the observations with a relative score between -250 and 250, I introduce a bandwidth of the same size for the regressions plotted below. Doing so does not significantly change the continuity regression results reported in Table 2.  \n\n\n```python\ny_var = [\"Hh_NumMembers\", \"Hh_ReligionMuslin\", \"Hh_Cows\",\"Hh_FloorBasic\", \"attending\", \"total_norm\"]\nX_matrix = [\"proj_selected\", \"rel_score\", \"clustercode\"]\ny_table_quad_reg,X_table_quad_reg = get_data(0,0,0, y_var, X_matrix)\ny_table_quad_reg = y_table_quad_reg.loc[abs(X_table_quad_reg[\"rel_score\"]) < 0.0250]\ny_table_quad_reg.reset_index(drop = True, inplace = True)\nX_table_quad_reg = X_table_quad_reg.loc[abs(X_table_quad_reg[\"rel_score\"]) < 0.0250]\nX_table_quad_reg.reset_index(drop = True, inplace = True)\n\n```\n\n#### Figure E2. Fitted Quadratic Regressions for A Subset of the Above Demographic Characteristics \n\n\n```python\nplot_continuity_quad_reg(y_table_quad_reg, X_table_quad_reg,\"Hh_FloorBasic\",\"Proportion of Children in Households with Basic Flooring\",0.7,1.1)\n\n\n```\n\n\n```python\nplot_continuity_quad_reg(y_table_quad_reg, X_table_quad_reg,\"Hh_ReligionMuslin\",\"Proportion of Children from Muslim Households\",0,1.1)\n\n```\n\n\n```python\nplot_continuity_quad_reg(y_table_quad_reg, X_table_quad_reg,\"Hh_NumMembers\",\"Number of Household Members\",5,16)\n\n```\n\n\n```python\nplot_continuity_quad_reg(y_table_quad_reg, X_table_quad_reg,\"Hh_Cows\",\"Number of Cows Owned by Each Household\",1,9)\n\n```\n\n## 6.2. Treatment Effect on Normalized Math and French Test Scores Disaggregated by Gender <a name=\"6.2\"></a>\n\nAs a further robustness check of the results reported by Kazianza et al. (2013), I look more closely at children's academic performance disaggregated by gender. Aside from the estimated treatment effect on overall normalized test scores reported in Table 7, the authors also evaluate the observed treatment effect of the BRIGHT program on French and math test scores, respectively, in Tables A5 and A6 of their [online Appendix](https://assets.aeaweb.org/asset-server/articles-attachments/aej/app/app/2012-0175_app.pdf). I take the regressions summarized in A5 and A6 a step further by observing if there is a markedly higher improvement in the French and math test results of girls over their male counterparts. According to the estimates summarized in  Table E2 below, the BRIGHT program does not achieve a significantly larger effect on the academic performance of girls compared to boys for either subject. \n\n\n```python\ny_var_robust_extension = [\"lang_norm\", \"math_norm\"]\nX_matrix_robust_extension = [\"proj_selected\", \"rel_score\", \"Ch_GirlXproj\", \"clustercode\"]\n\ny_table_robust_extension,X_table_robust_extension = get_data(0,0,1, y_var_robust_extension, X_matrix_robust_extension)\n```\n\n#### Table E2. The Estimated Treatment Effect on Normalized Math and French Test Scores by Gender \n\n\n```python\ncreate_table_E1(y_table_robust_extension,y_var_robust_extension,X_table_robust_extension)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th colspan=\"2\" halign=\"left\">BRIGHT Program (Selected)</th>\n      <th colspan=\"2\" halign=\"left\">Selected x Female</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>Coefficient</th>\n      <th>P-value</th>\n      <th>Coefficient</th>\n      <th>P-value</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>lang_norm</th>\n      <td>0.368</td>\n      <td>0.0</td>\n      <td>0.012</td>\n      <td>0.748</td>\n    </tr>\n    <tr>\n      <th>math_norm</th>\n      <td>0.399</td>\n      <td>0.0</td>\n      <td>0.014</td>\n      <td>0.678</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## 6.3. Plotting Parametric Regression Results <a name=\"6.3\"></a>\n\nAlthough Kazianga et al. (2013) visualize the estimated discontinuities for their nonparametric regressions in Figures 1, 3, and 4, they only publish the estimated regression coefficients in a table format for their parametric regression results. While this procedure is suitable for the authors' objectives, I slightly extend the scope of their paper by using two different regression models to plot the conditional mean functions on either side of the cutoff. I first plot the treatment effect using the joint regression discontinuity model originally specified by Kazianga et al. (2013) in equation (1). I then measure the effect by splitting the data set according to assigned treatment and running two independent regressions for the observations in the selected and nonselected villages, respectively. Plotting the fitted curves of these two model specifications lends further insight into their unique structural forms. \n\nAnalogous to the set up in section 6.1, I restrict the data set to a bandwidth of 250 in order to remain consistent with the authors' graphical formatting in the original paper. As mentioned previously, this modification does not impact the economic or statistical significance of the parametric estimates reported by Kazianga et al. (2013). Additionally, I only control for department fixed effects due to the robustness of the measured treatment effect of the BRIGHT program on attendance and normalized total test scores. To avoid confusion, I address the treatment effect on the two main outcome variables separately. In section 6.3.1, I plot the joint and individual discontinuity regressions for attendance. I then perform the same procedure in section 6.3.2 for total test scores. \n\nGiven the explicit structure of the joint regression, it is clear from Figures E3 and E5 that the slope on either side of the cutoff is the same. Although an advantage of running a joint regression is that one directly obtains an estimate and standard error for the treatment effect in question, restricting the slope to be identical for the control and treatment groups compromises the inherent strength of the RD design (Lee and Lemieux, 2010). In particular, the joint regression uses all observations on either side of the cutoff to compute its predictions. This implies that observations in the control group influence the estimate of the conditional expectation of $Y$ as the limit approaches the cutoff from the treatment side and vice versa. As the RD design seeks to estimate the potential outcome functions as the limits approach the cutoff from their respective sides, constraining the slopes may create a less efficient estimate of the treatment effect. In the case that the functional form is the same for both the control and treatment sides, however, the joint regression may be an appropriate strategy. Lee and Lemieux (2010) alternatively recommend running separate regressions for the observations on either side of the cutoff value in order to individually estimate the slope for each side.\n\nDespite the concerns discussed above, the joint and separate regression models plotted for the effects of the BRIGHT program on school attendance yield similar estimates. The difference between the two estimated effects is marginal. The measurements for test scores, however, appear to differ more between the two regression specifications. As is visible in Figure E5, the joint regression discontinuity estimates a nearly linear slope on both sides of the cutoff. Alternatively, the separate regressions in Figure E6 suggest that the individually estimated slopes on either side of the cutoff are not identical. For this reason, the joint regression may slightly overestimate the treatment effect.     \n\n### 6.3.1 Joint and Separate Regression Discontinuity Plots for the Treatment Effect on Attendance <a name=\"6.3.1\"></a>\n\n#### Figure E3. Joint Regression Discontinuity for School Attendance\n\n\n```python\nplot_continuity_quad_reg(y_table_quad_reg, X_table_quad_reg,\"attending\",\n                         \"Probability of Enrollment in School According to Village's Relative Score\",-0.2,1)\n```\n\n\n```python\nquad_attendance_coeff = calculate_polynomial_features(1, y_table_quad_reg[\"attending\"], X_table_quad_reg, 2).params[3]\nquad_attendance_pval = calculate_polynomial_features(1, y_table_quad_reg[\"attending\"], X_table_quad_reg, 2).pvalues[3]\nprint(f'For a bandwidth of 250, the effect of the BRIGHT program on attendance remains robust with a coefficient estimate of {quad_attendance_coeff*100:.4f}% and a statistically significant p-value.')\n\n```\n\n    For a bandwidth of 250, the effect of the BRIGHT program on attendance remains robust with a coefficient estimate of 18.6504% and a statistically significant p-value.\n\n\n#### Figure E4. School Attendance Regression Discontinuity Measured Using Separate OLS Estimations for Either Side of the Cutoff \n\n\n```python\nplot_continuity_quad_reg_separated(y_table_quad_reg, X_table_quad_reg, \"attending\", -0.2, 1, \"Probability of Enrollment in School According to Village's Relative Score\")\n```\n\n\n```python\ncompute_est_effect_separate(y_table_quad_reg, X_table_quad_reg, \"attending\",1)  \n\n```\n\n    The measured effect on attendance for separately plotted control and treatment regressions is 18.7695%.\n\n\n### 6.3.2 Joint and Separate Regression Discontinuity Plots for the Treatment Effect on Normalized Total Test Scores <a name=\"6.3.2\"></a>\n\n#### Figure E5. Joint Regression Discontinuity for Test Scores\n\n\n```python\nplot_continuity_quad_reg(y_table_quad_reg, X_table_quad_reg,\"total_norm\",\n                         \"Normalized Total Test Score According to Village's Relative Score\",-1,1)\n```\n\n\n```python\nquad_testing_coeff = calculate_polynomial_features(1, y_table_quad_reg[\"total_norm\"], X_table_quad_reg, 2).params[3]\nquad_testing_pval = calculate_polynomial_features(1, y_table_quad_reg[\"total_norm\"], X_table_quad_reg, 2).pvalues[3]\nprint(f'For a bandwidth of 250, the effect of the BRIGHT program on attendance remains robust with a coefficient estimate of {quad_testing_coeff:.4f} and a statistically significant p-value.')\n\n```\n\n    For a bandwidth of 250, the effect of the BRIGHT program on attendance remains robust with a coefficient estimate of 0.4175 and a statistically significant p-value.\n\n\n#### Figure E6. Test Score Regression Discontinuity Measured Using Separate OLS Estimations for Either Side of the Cutoff \n\n\n```python\nplot_continuity_quad_reg_separated(y_table_quad_reg, X_table_quad_reg, \"total_norm\", -1, 1,\"Normalized Total Test Score According to Village's Relative Score\")\n```\n\n\n```python\ncompute_est_effect_separate(y_table_quad_reg, X_table_quad_reg,\"total_norm\",0) \n```\n\n    The measured effect on normalized total test scores for separately plotted control and treatment regressions is 0.3835 standard deviations.\n\n\n## 6.4. Evaluation of Placebo Thresholds <a name=\"6.4\"></a>\n\nA common tool used to confirm the existence of a threshold discontinuity in RD designs are placebo tests. Among many other methods of application, placebo tests involve selecting an arbitrary value of the running variable that deviates from the true threshold and testing if there exists a measurable effect on the outcome variable. In so doing, we only anticipate an effect at the true cutoff point and no effect at any  placebo cutoff. To carry out this extension, I first subset the observations at the child level according to their treatment assignment. I then create a series of treatment dummies for various placebo cutoffs. For the untreated individuals, I select placebo cutoffs at the following relative score values around the true threshold: -125, -62.5, -31.25, and -15.625. I do the same for the subset of individuals belonging to the treatment group: 15.625, 31.25, 62.5, 125. At each placebo cutoff, I produce a dummy variable such that the individuals, who live in a village with a relative score that falls above the cutoff are selected into the placebo treatment group, while those from a village with a relative score  below the threshold are allocated to the placebo control group. I then run a simple linear OLS regression specified by equation (1), in which I account for department fixed effects. The results for the two principle outcome variables, school attendance and total test scores, are summarized below in Tables E7 through E10.\n\nAs expected, the regression results for this basic model specification yield small coefficient estimates on the respective placebo treatment variables that are statistically insignificant. To confirm the robustness of my results, I performed alternative model specifications in which I included the preferred quadratic model used by Kazianga et al. (2013) as well as demographic controls. For the strict regression evaluation, in which I apply a quadratic polynomial expansion as well as demographic controls and department fixed effects, the regression output indicates mild statistical significance at the 10 percent level for the placebo thresholds nearest to the true cutoff value. However, the corresponding confidence intervals remain centered around zero. These further specifications thus generate similar results to the basic case, indicating that there are no measurable effects on the outcome variables at randomly selected cutoffs.\n\n\n```python\ny_var_placebo = [\"attending\", \"total_norm\"]\nX_matrix_placebo = [\"proj_selected\", \"rel_score\", \"clustercode\"]\ny_placebo,X_placebo = get_data(0,0,0, y_var_placebo, X_matrix_placebo)\n\n#The code below includes the preferred quadratic model specification as well as\n#fixed effects **and** demographic controls:\n\n#X_matrix_placebo = [\"proj_selected\", \"rel_score\", \"rel_score2\", \"clustercode\"]\n#y_placebo,X_placebo = get_data(0,0,1, y_var_placebo, X_matrix_placebo)\n\n```\n\n### 6.4.1. Placebo Tests for the Treatment Effect on School Attendance <a name=\"6.4.1\"></a>\n\n#### Table E7. Placebo Threshold Results for School Attendance (Control Side)\n\n\n```python\nLHS_placebo_thresholds_attendance = iterate_placebo_test(y_placebo[\"attending\"], X_placebo, 0)\nLHS_placebo_thresholds_attendance\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Placebo Cutoff</th>\n      <th>Coefficient Estimate</th>\n      <th>P-value</th>\n      <th>Conf. Int. Lower</th>\n      <th>Conf. Int. Upper</th>\n    </tr>\n    <tr>\n      <th>Index</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>-125.000</td>\n      <td>0.019949</td>\n      <td>0.744669</td>\n      <td>-0.100107</td>\n      <td>0.140005</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>-62.500</td>\n      <td>-0.035528</td>\n      <td>0.375012</td>\n      <td>-0.114022</td>\n      <td>0.042966</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>-31.250</td>\n      <td>-0.014951</td>\n      <td>0.700693</td>\n      <td>-0.091186</td>\n      <td>0.061284</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>-15.625</td>\n      <td>0.047822</td>\n      <td>0.242614</td>\n      <td>-0.032393</td>\n      <td>0.128036</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n#### Table E8. Placebo Threshold Results for School Attendance (Treatment Side)\n\n\n```python\nRHS_placebo_thresholds_attendance = iterate_placebo_test(y_placebo[\"attending\"], X_placebo, 1)\nRHS_placebo_thresholds_attendance\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Placebo Cutoff</th>\n      <th>Coefficient Estimate</th>\n      <th>P-value</th>\n      <th>Conf. Int. Lower</th>\n      <th>Conf. Int. Upper</th>\n    </tr>\n    <tr>\n      <th>Index</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>125.000</td>\n      <td>0.025478</td>\n      <td>0.493609</td>\n      <td>-0.047466</td>\n      <td>0.098422</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>62.500</td>\n      <td>0.011074</td>\n      <td>0.758341</td>\n      <td>-0.059474</td>\n      <td>0.081622</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>31.250</td>\n      <td>0.008750</td>\n      <td>0.760680</td>\n      <td>-0.047556</td>\n      <td>0.065057</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>15.625</td>\n      <td>-0.023922</td>\n      <td>0.438972</td>\n      <td>-0.084504</td>\n      <td>0.036660</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### 6.4.2. Placebo Tests for the Treatment Effect on Total Test Scores <a name=\"6.4.2\"></a>\n\n#### Table E9. Placebo Threshold Results for Total Test Scores (Control Side)\n\n\n```python\nLHS_placebo_thresholds_testing = iterate_placebo_test(y_placebo[\"total_norm\"], X_placebo, 0)\nLHS_placebo_thresholds_testing\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Placebo Cutoff</th>\n      <th>Coefficient Estimate</th>\n      <th>P-value</th>\n      <th>Conf. Int. Lower</th>\n      <th>Conf. Int. Upper</th>\n    </tr>\n    <tr>\n      <th>Index</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>-125.000</td>\n      <td>-0.024010</td>\n      <td>0.858607</td>\n      <td>-0.288167</td>\n      <td>0.240147</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>-62.500</td>\n      <td>-0.059645</td>\n      <td>0.476069</td>\n      <td>-0.223684</td>\n      <td>0.104395</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>-31.250</td>\n      <td>-0.053977</td>\n      <td>0.508089</td>\n      <td>-0.213828</td>\n      <td>0.105875</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>-15.625</td>\n      <td>0.060101</td>\n      <td>0.492586</td>\n      <td>-0.111562</td>\n      <td>0.231763</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n#### Table E10. Placebo Threshold Results for Total Test Scores (Treatment Side)\n\n\n```python\nRHS_placebo_thresholds_testing = iterate_placebo_test(y_placebo[\"total_norm\"], X_placebo, 1)\nRHS_placebo_thresholds_testing\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Placebo Cutoff</th>\n      <th>Coefficient Estimate</th>\n      <th>P-value</th>\n      <th>Conf. Int. Lower</th>\n      <th>Conf. Int. Upper</th>\n    </tr>\n    <tr>\n      <th>Index</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>125.000</td>\n      <td>0.051727</td>\n      <td>0.485815</td>\n      <td>-0.093733</td>\n      <td>0.197186</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>62.500</td>\n      <td>0.006877</td>\n      <td>0.922398</td>\n      <td>-0.131479</td>\n      <td>0.145232</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>31.250</td>\n      <td>0.032120</td>\n      <td>0.644695</td>\n      <td>-0.104398</td>\n      <td>0.168639</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>15.625</td>\n      <td>-0.011364</td>\n      <td>0.877812</td>\n      <td>-0.156237</td>\n      <td>0.133509</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## 6.5. Bandwidth Sensitivity Checks <a name=\"6.5\"></a>\n\nWhen alternative parametric and nonparametric strategies generate a suboptimal regression fit, Lee and Lemieux (2010) suggest implementing a local linear regression (LLR), in which a linear regression is run for a  subset of data observations marginally close to the cutoff. Alternatively, if a parametric functional form such as a low-order polynomial expansion produces an appropriate regression fit, exhibiting little to no bias, then running a regression using all observations may be a suitable strategy.\n\nAs the authors do not extensitvely perform local linear regressions around the cutoff and instead use all 17,970 observations in their parametric regression analyses, I introduce bandwidth checks to observe whether the results reported by Kazianga et al. (2013) are sensitive to using increasingly smaller subsets of the original data near the cutoff. As the results from the linear model specification remain robust with the removal of demographic controls, I only include department fixed effects for the regressions reported here. In the following section, I perform these checks for changes in the two primary outcome variables, attendance and normalized total test scores, respectively. \n\nThe first analysis evaluates the changes to the estimated local treatment effect and to the corresponding p-value for several bandwidths. As a baseline estimate, the first row of Tables E3 and E5 reports the treatment effect before any bandwidth has been introduced. In this case, the BRIGHT program increases the probably of school attendance for all children by approximately 21.19% and improves test scores by 0.46 standard deviations. For the first seven bandwidths, starting with a fairly large relative score of 400 and decreasing to a score of 125, the estimated treatment effects on attendance remain consistent with the linear regression estimate without a bandwidth, ranging between 17.70% and 20.98%. The respective p-values are also highly statistically significant. As the bandwidths become increasingly smaller, however, the estimated treatment effect begins to exhibit more sensitivity. Although most of the corresponding p-values remain statistically significant at the 5% or 10% levels, they are clearly less significant than the estimates for larger bandwidths.\n\nThe observed changes in treatment effect on test scores suggests that the collected data for academic performance is more sensitive to the bandwidth check. For a bandwidth as small as 250, the treatment effect remains between .40 and .48 standard deviations. As the bandwidth decreases to relative score 125, the estimates of the effect fall below .40 standard deviations, but remain higher than 0.36 standard deviations. These estimates, however, maintain a high level of statistical significance. As the bandwidth drops below 125, the estimated treatment effects vary more intensely and begin to lose their statistical significance. Two estimates in particular - for bandwidths of 31.25 and 10 - remain economically significant, but no longer exhibit statistical significance at conventional levels.\n\nAs a second bandwidth sensitivity check, I apply the \u201cleave one out\u201d cross-validation procedure, in which the predicted values, $\\hat{Y}$, at $X = X_i$ are estimated by excluding the observation $i$ and running a local linear regression. This procedure is performed individually for all observations on either side of the threshold value. Once all predicted values are obtained for the observations within a specified bandwidth, the overall mean square error (MSE) is computed by averaging the squared prediction errors derived on either side of the cutoff. The bandwidth with the lowest MSE is thus large enough to derive a precise estimate, but small enough to yield a sufficiently accurate linear model specification (Lee and Lemieux, 2010). For the treatment effect on attendance and test scores, respectively, the MSEs calculated from the \"leave one out\" procedure exhibit little variation. The MSEs for the effect on attendance range between 0.211 and 0.201. Likewise, all but one bandwidth yield an MSE between 1.01 and 0.94 for the effect on test scores (for the final bandwidth at relative score 5, the MSE for the test score observations increases to 1.19). As a result, the introduced bandwidths do not significantly improve the MSE.\n\n\n\n\n```python\ny_bndwd, X_bndwd = get_data(0,0,0, [\"total_norm\",\"attending\"], [\"rel_score\",\"proj_selected\",\"clustercode\"])\ny_bndwd_MSE, X_bndwd_MSE = get_data(0,0,0, [\"attending\",\"total_norm\"], \"rel_score\")\n```\n\n\n```python\n#bandwidth = [1, 0.0400, 0.0300, 0.0250, 0.01875,0.0125, 0.003125, 0.0015625, 0.0010, 0.0005]\n```\n\n### | Bandwidth Sensitivity for the Treatment Effect on Attendance\n\n#### Table E3. Changes in the Estimated Treatment Effect on Attendance\n\n\n```python\ncheck_effect_bandwidth(y_bndwd[\"attending\"], X_bndwd, 1)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Treatment Effect, %</th>\n      <th>P-value</th>\n    </tr>\n    <tr>\n      <th>Bandwidth</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>10000.000</th>\n      <td>21.186229</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>400.000</th>\n      <td>20.981540</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>300.000</th>\n      <td>18.203129</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>250.000</th>\n      <td>18.572538</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>187.500</th>\n      <td>19.061769</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>125.000</th>\n      <td>18.975753</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>31.250</th>\n      <td>5.927554</td>\n      <td>0.360</td>\n    </tr>\n    <tr>\n      <th>15.625</th>\n      <td>13.993984</td>\n      <td>0.093</td>\n    </tr>\n    <tr>\n      <th>10.000</th>\n      <td>19.517079</td>\n      <td>0.085</td>\n    </tr>\n    <tr>\n      <th>5.000</th>\n      <td>57.337628</td>\n      <td>0.000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n#### Table E4. Results from the \u201cLeave One Out\u201d Cross-Validation Procedure for School Attendance\n\n\n```python\n#create_bandwidth_check(y_bndwd_MSE[\"attending\"], X_bndwd_MSE, bandwidth)\ncreate_bndwd_check_att = {\"Bandwidth\": [1000,400,300,250,187.5,125,31.25,15.625,10,5],\n                      \"MSE\": [0.21129,0.209526,0.208515,0.208851,0.208996,0.209181,\n                              0.200981,0.204528,0.200916,0.205581]}\ncreate_bndwd_check_att_df = pd.DataFrame(create_bndwd_check_att)\ncreate_bndwd_check_att_df.set_index([\"Bandwidth\"], inplace=True)\ncreate_bndwd_check_att_df\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>MSE</th>\n    </tr>\n    <tr>\n      <th>Bandwidth</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1000.000</th>\n      <td>0.211290</td>\n    </tr>\n    <tr>\n      <th>400.000</th>\n      <td>0.209526</td>\n    </tr>\n    <tr>\n      <th>300.000</th>\n      <td>0.208515</td>\n    </tr>\n    <tr>\n      <th>250.000</th>\n      <td>0.208851</td>\n    </tr>\n    <tr>\n      <th>187.500</th>\n      <td>0.208996</td>\n    </tr>\n    <tr>\n      <th>125.000</th>\n      <td>0.209181</td>\n    </tr>\n    <tr>\n      <th>31.250</th>\n      <td>0.200981</td>\n    </tr>\n    <tr>\n      <th>15.625</th>\n      <td>0.204528</td>\n    </tr>\n    <tr>\n      <th>10.000</th>\n      <td>0.200916</td>\n    </tr>\n    <tr>\n      <th>5.000</th>\n      <td>0.205581</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### | Bandwidth Sensitivity for the Treatment Effect on Normalized Total Test Scores\n\n#### Table E5. Changes in the Estimated Treatment Effect on Academic Performance\n\n\n```python\ncheck_effect_bandwidth(y_bndwd[\"total_norm\"], X_bndwd, 0)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Treatment Effect, std</th>\n      <th>P-value</th>\n    </tr>\n    <tr>\n      <th>Bandwidth</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>10000.000</th>\n      <td>0.464463</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>400.000</th>\n      <td>0.475228</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>300.000</th>\n      <td>0.402353</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>250.000</th>\n      <td>0.416954</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>187.500</th>\n      <td>0.363156</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>125.000</th>\n      <td>0.376530</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>31.250</th>\n      <td>0.189655</td>\n      <td>0.189</td>\n    </tr>\n    <tr>\n      <th>15.625</th>\n      <td>0.302297</td>\n      <td>0.094</td>\n    </tr>\n    <tr>\n      <th>10.000</th>\n      <td>0.310040</td>\n      <td>0.206</td>\n    </tr>\n    <tr>\n      <th>5.000</th>\n      <td>1.065590</td>\n      <td>0.000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n#### Table E6. Results from the \u201cLeave One Out\u201d Cross-Validation Procedure for Academic Performance\n\n\n```python\n#create_bandwidth_check(y_bndwd_MSE[\"total_norm\"], X_bndwd_MSE, bandwidth)\ncreate_bndwd_check_test = {\"Bandwidth\": [1000,400,300,250,187.5,125,31.25,15.625,10,5],\n                           \"MSE\": [1.01461,1.005749,1.001082,0.999612,0.988794,0.974925,\n                                   0.938921,0.961493,0.982658,1.186763]}\ncreate_bndwd_check_test_df = pd.DataFrame(create_bndwd_check_test)\ncreate_bndwd_check_test_df.set_index([\"Bandwidth\"], inplace=True)\ncreate_bndwd_check_test_df\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>MSE</th>\n    </tr>\n    <tr>\n      <th>Bandwidth</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1000.000</th>\n      <td>1.014610</td>\n    </tr>\n    <tr>\n      <th>400.000</th>\n      <td>1.005749</td>\n    </tr>\n    <tr>\n      <th>300.000</th>\n      <td>1.001082</td>\n    </tr>\n    <tr>\n      <th>250.000</th>\n      <td>0.999612</td>\n    </tr>\n    <tr>\n      <th>187.500</th>\n      <td>0.988794</td>\n    </tr>\n    <tr>\n      <th>125.000</th>\n      <td>0.974925</td>\n    </tr>\n    <tr>\n      <th>31.250</th>\n      <td>0.938921</td>\n    </tr>\n    <tr>\n      <th>15.625</th>\n      <td>0.961493</td>\n    </tr>\n    <tr>\n      <th>10.000</th>\n      <td>0.982658</td>\n    </tr>\n    <tr>\n      <th>5.000</th>\n      <td>1.186763</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nTo better understand the results from both sensitivity checks, it is necessary to take a closer look at the distributions of the demographic characteristics for the whole range of the relative score. In many other research contexts, observations farther away from the threshold may systematically differ from the data points marginally close to the cutoff in one or more of the observed covariates, thus introducing some degree of estimation bias into the measured treatment effect. Performing an LLR with a subset of observations selected by an optimizing bandwidth better ensures that the data points on either side of the cutoff exhibit continuity in the distributions of the covariates and thus may serve as an appropriate alternative to parametric regression. \n\nAs acknowledged in Table 2 of Kazianga et al. (2013) and in the extensions summarized in section 6.1 of this notebook, the control and treatment groups are largely similar across all 28 observed characteristics. Table A1 of the [Online Appendix](https://assets.aeaweb.org/asset-server/articles-attachments/aej/app/app/2012-0175_app.pdf) reports further analyses of the village characteristics by disaggregating the child observations according to how close their villages' relative score is to the cutoff. They conclude that children, whose villages have a relative score marginally close to the cutoff (i.e., villages with a relative score between -40 and 40), are characteristically similar to those living in villages with a score farther away from the cutoff. As the computed average differences for the 28 observed demographic controls are small, it is safe to conclude that the continuity assumption holds for the entire distribution of each demographic characteristic, not just for the observations with relative scores marginally close to the threshold. \n\nThe results from the two bandwidth sensitivity checks seem to confirm this analysis. As the introduced bandwidths do not significantly improve the MSE for either of the measured treatment effects, the balance between precision and bias described above does not significantly improve with the introduction of a bandwidth. Likewise, as the bandwidths become smaller and fewer observations are used in the LLR model, the estimated treatment effects lose much of their statistical significance. Given the features of the data set as well as the results from the bandwidth sensitivity checks, a parametric regression with a low-order polynomial is thus a more appropriate strategy than a nonparametric LLR with an optimized bandwidth.\n\n\n\n---\n\n<span style=\"color:darkred\">**NOTE**:</span> Due to a degree of computational intensity for the \"leave one out\" procedure that my computer cannot seem to handle, I calculated the MSE for each bandwidth individually using the `create_bandwidth_check()` function and created Tables E4 and E6 manually. \n\n---\n\n---\n# 7. Concluding Remarks <a name=\"7\"></a>\n---\n\nIn the above project report, I introduced the basic properties of the RD design and its strengths as an identification strategy. I also replicated the main findings reported in Kazianga et al. (2013) and provided further insights through a number of project extensions described in section 6 of this notebook. My replication results and robustness extensions both corroborate the results published by the authors in the original journal article. \n\nAfter only 2.5 years, the BRIGHT program significantly improved enrollment and test scores among all children. For example, BRIGHT increased enrollment by 19 percentage points and exam scores by 0.41 standard deviations for all primary school-age children. The program also increased school enrollment among girls by 5 percentage points more than their male counterparts. Despite this increase in the enrollment rate for girls, Kazianga et al. (2013) do not identify a differential impact on test scores based on gender. That is, the authors observe a comparable increase in test scores for both boys and girls. Furthermore, the individual effects of the BRIGHT program's characteristics are - from an economic as well as a statistical perspective - significantly larger than the education outcomes for children who attend a traditional school. The girl-friendly amenities of the BRIGHT program improve enrollment by 13 percentage points and test scores by 0.35 standard deviations above the effects observed by providing a regular school, indicating that school infrastructure plays an important role in a family's decision to seek education services for their children.\n\nAdditionally, the robustness extensions described in section 6.1 lend further evidence to support the critical continuity assumption. The robustness check in 6.2 shows that the lack of a differential impact on total test scores between boys and girls holds true when academic performance is measured separately for math and French. In sections 6.3 and 6.4, respectively, the parametric regression plots and the placebo tests corroborate the size as well as the location of the treatment discontinuity for the two main outcome variables. Finally, the bandwidth sensitivity checks in section 6.5 justify the authors' preferred use of a quadratic regression model as opposed to a nonparametric LLR.\n\n\n\n\n---\n# 8. Bibliography <a name=\"8\"></a>\n---\n\n* **Card, D., Mas, A., & Rothstein, J. (2008)**. Tipping and the Dynamics of Segregation. *Quarterly Journal of Economics*, 123(1), 177\u2013218.\n\n* **Cunningham, S. (2021)**. *Causal Inference: The Mixtape*. New Haven: Yale University Press.\n\n* **Kazianga, H., Levy, D., Linden, L. L., & Sloan, M. (2013)**. The Effects of \u201cGirl-Friendly\u201d Schools: Evidence from the BRIGHT School Construction Program in Burkina Faso. *American Economic Journal: Applied Economics*, 5(3), 41-62.\n\n* **Lee, D. S., & Lemieux, T. (2010)**. Regression Discontinuity Designs in Economics. *Journal of Economic Literature*, 48(2), 281-355.\n\n* **Levy, D., Sloan, M., Linden, L., & Kazianga, H. (2009a)**. Impact Evaluation of Burkina Faso\u2019s Bright Program: Final Report. *Mathematica Policy Research*. Washington, DC, June.\n\n* **McCrary, J. (2008)**. Manipulation of the Running Variable in the Regression Discontinuity Design: A Density Test. *Journal of Econometrics*, 142(2), 698\u2013714.\n\n* **Thistlethwaite, D. L., & Campbell, D. T. (1960)**. Regression-discontinuity analysis: An alternative to the ex post facto experiment. *Journal of Educational Psychology*, 51(6), 309.\n", "meta": {"hexsha": "50ce166bd65159f4c0099c067d20da10d779b0e0", "size": 828803, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "E_Schwab_Data_Sci_Project.ipynb", "max_stars_repo_name": "s6emschw/data-science-replication-project", "max_stars_repo_head_hexsha": "4dd6054f59096b30c02c3e5925030a5eb38d3e9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "E_Schwab_Data_Sci_Project.ipynb", "max_issues_repo_name": "s6emschw/data-science-replication-project", "max_issues_repo_head_hexsha": "4dd6054f59096b30c02c3e5925030a5eb38d3e9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "E_Schwab_Data_Sci_Project.ipynb", "max_forks_repo_name": "s6emschw/data-science-replication-project", "max_forks_repo_head_hexsha": "4dd6054f59096b30c02c3e5925030a5eb38d3e9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 174.8898501794, "max_line_length": 97104, "alphanum_fraction": 0.8407148623, "converted": true, "num_tokens": 46543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.0994702052060063, "lm_q1q2_score": 0.04164786749273078}}
{"text": "```python\ndef downloadDriveFile(file_id,file_name,file_extension):\n  '''\n  Allows charge of public files into colab's workspace\n  '''\n  !wget --load-cookies /tmp/cookies.txt \"https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id='$file_id -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\\1\\n/p')&id=\"$file_id -O \"$file_name\".\"$file_extension\" && rm -rf /tmp/cookies.txt\n\nif 'google.colab' in str(get_ipython()):\n    downloadDriveFile('1uY4ijPPkUxOO_BMwRnxuq10ucWCNkhGT','linalg_tools','py')\n    downloadDriveFile('1HpazHI56LLIKJGcdg-rj-8QWgnXu8SBe','optimize','py')\n```\n\n\n```python\nimport numpy as np\nimport sympy as sp\nfrom sympy.solvers.solveset import linsolve, nonlinsolve\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n\nimport linalg_tools\nimport optimize\n```\n\nExample 7\n=========\n\nConsider a wireless communication channel with transmit power $p_t$. The received power pr in decibel ($dB$) is derived using the model:\n\n$$p_r = p_t + K \u2212 10\\gamma log_{10} d$$\n\nwhere K is a constant depending on the radio frequency and antennas gains, $\\gamma$ is the path loss exponent, and $d$ in meters is the distance between the transmitter and the receiver. In a set of empirical measurements of $pr\u2212pt$ in $dB$, given in the nex table, find constants $K$ and $\\gamma$ to minimize the mean square error between the model and the empirical measurements.\n\n<center>\n\n| d     | $p_r$ - $p_t$ |\n|------:|:-------------:|\n| 10 m  | -70 dB    |\n| 20 m  | -75 dB    |\n| 50 m  | -90 dB    |\n| 100 m | -110 dB   |\n| 300 m | -125 dB   |\n\n</center>\n\n\n```python\ndistances = np.array([[10], [20], [50], [100], [300]])\nmeasures = np.array([[-70], [-75], [-90], [-110], [-125]])\n\ndistances_log = 10*np.log10(distances)\n```\n\n\n```python\nK, gamma = linalg_tools.least_squares(distances_log, measures)\n\nsynt_distances = np.linspace(distances[0], distances[-1], 20, endpoint=True)\nopt_curve = K - 10*gamma*np.log10(synt_distances)\n```\n\n\n```python\nfig, ax = plt.subplots()\n\nax.scatter(distances, measures, color='#F23B13', linewidth=0.8, s=10, label='Experimental measures')\nax.plot(synt_distances, opt_curve, color='#2781FF', linewidth=0.8, label='Fitted curve')\n\nax.set_xlabel('distance (m)')\nax.set_ylabel('$p_r - p_t$ (dB)')\n\nfig_dpi = 150\nfig_width = 15./2.54\nfig_height = 9.4/2.54\n\nfig.dpi=fig_dpi\nfig.set_size_inches((fig_width,fig_height))\nfig.tight_layout()\n\nplt.show()\n```\n\nProblem 1\n=========\n\nConsider the function:\n\n$$ \nf(\\mathbf{x}) = \\mathbf{x}^T \\begin{bmatrix} 3 & 1 \\\\ 1 & 2 \\end{bmatrix}\\mathbf{x}\n + \\mathbf{x}^T \\begin{bmatrix} 3 \\\\ 1 \\end{bmatrix} + 6\n$$\n\n\n```python\nx1, x2 = sp.symbols('x1 x2')\nx_vect = sp.matrices.Matrix([[x1], [x2]])\n\nf_x = x_vect.T*sp.matrices.Matrix([[3, 1], [1, 2]])*x_vect + x_vect.T*sp.matrices.Matrix([[3], [1]]) +np.full((1,1), 6)\n```\n\n\n```python\njacobian_sym = sp.derive_by_array(f_x[0], [x1, x2])\nhessian_sym = sp.derive_by_array(jacobian_sym, [x1, x2])\n```\n\nFor matrix operations, it is better to have numpy's versions.\n\n\n```python\njacobian = sp.lambdify((x1, x2), jacobian_sym, modules='numpy')\nhessian = sp.lambdify((x1, x2), hessian_sym, modules='numpy')\n```\n\n(a)\n---\nFind the gradient and Hessian of $f$ at $\\mathbf{x} = \\begin{bmatrix} 1 \\\\ -1 \\end{bmatrix}$\n\n\n```python\ngradient_at_x = jacobian_sym.subs({x1: 1, x2: -1})\nhessian_at_x = hessian_sym.subs({x1: 1, x2: -1})\n\nprint('The gradient at x is ', gradient_at_x)\nprint('The hessian at x is ', hessian_at_x)\n```\n\n(b)\n---\nFind the directional derivative of direction of maximum rate of increase with respect to a unit vector in direction of maximum rate of increase.\n\nThe direction of the maximum rate of increase of $f$ at $\\mathbf{x} = \\begin{bmatrix} 1 \\\\ -1 \\end{bmatrix}$ is the direction of the gradient evaluated at that point. Then, the unit vector in such direction could be computed by just normalizing the gradient.\n\n\n```python\ngradient_at_point = np.array(jacobian(1, -1))\nmax_incr_dir = gradient_at_point/np.linalg.norm(gradient_at_point)\n```\n\nThen, the directional derivative of direction of maximum rate of increase could be get both symbolic and analytic:\n\n\n```python\ndir_derivative = jacobian_sym@max_incr_dir\ndir_derivative\n```\n\n\n```python\ndir_derivative = gradient_at_point.T@max_incr_dir\nprint('The directional derivative at x is ', dir_derivative)\n```\n\n(c)\n---\nFind the point which satisfies the necessary and sufficient conditions of optimality for $f$.\nDetermine whether this point is a minimum, maximum, or saddle point.\n\nThe critical points could be finded making $\\nabla f(\\mathbf{x}) = 0$\n\n\n```python\nlinsolve(jacobian_sym, (x1, x2))\n```\n\n\n```python\nd1, d2 = sp.symbols('d1 d2')\ndirection = sp.matrices.Matrix([[d1], [d2]])\n```\n\nThe second condition of optimalilty could be verified by the Hessian matrix.\n\n\n```python\nH_crit_point = hessian(-1/2, 0)\n```\n\n\n```python\nf_eigvals, f_eigvects = np.linalg.eig(H_crit_point)\nis_positive = np.allclose(f_eigvals > 0, True)\nis_negative = np.allclose(f_eigvals < 0, True)\nprint('Is the Hessian matrix at the analysis point positive?', is_positive)\nprint('Is the Hessian matrix at the analysis point positive?', is_negative)\n```\n\n\n```python\ndirection.T@np.array(H_crit_point)\n```\n\nThe product $\\mathbf{d}^\\mathrm{T} \\; \\nabla f(\\mathbf{x^*})$ is positive in any direction $\\mathbf{d}$ and $\\mathbf{H}(\\mathbf{x^*})$ is a positive semi-definite matrix. Then, $\\mathbf{x^*} = \\begin{bmatrix} -1/2 \\\\ 0 \\end{bmatrix}$ satisfies the second-order neccesary condition of a local minimum point.\n\n\n```python\nlam_f = sp.lambdify([x1, x2], f_x[0,0], modules=['numpy'])\n\nstep = 0.1\ngradient_step = 0.1\nx_vals = np.arange(-8, 8, step)\ny_vals = np.arange(-8, 8, step)\nx_vals, y_vals = np.meshgrid(x_vals, y_vals)\n\n# Symbolic to real values\nf_vals = lam_f(x_vals, y_vals)\ngradient_x, gradient_y = np.gradient(f_vals, gradient_step)\n```\n\n\n```python\nfig = plt.figure()\nlevels = 10\n\nax0 = fig.add_subplot(1, 2, 1)\nax0.contour (x_vals, y_vals, f_vals, levels) \n\nskip=(slice(None,None,6),slice(None,None,6))\nax0.contour (x_vals, y_vals, f_vals)\nax0.quiver(x_vals[skip], y_vals[skip], gradient_x[skip], gradient_y[skip],\n minshaft=1.5, minlength=1.5, units='dots', scale_units='dots', scale=3, angles='xy')\nax0.set_xlabel( '$x_1$' ) \nax0.set_ylabel( '$x_2$' )\n\nax1 = fig.add_subplot(1, 2, 2, projection='3d')\nax1.plot_surface(x_vals, y_vals, f_vals, cmap=cm.viridis,\n                       linewidth=0.1, antialiased=True)\nax1.view_init(30, 45)\nax1.set_xlabel( '$x_1$' ) \nax1.set_ylabel( '$x_2$' )\n\nfig_dpi = 150\nfig_width = 18.8/2.54\nfig_height = 9.4/2.54\n\nfig.dpi=fig_dpi\nfig.set_size_inches((fig_width,fig_height))\nfig.tight_layout()\n\nplt.show()\n```\n\nProblem 2\n=========\n\nConsider function $f (x_1, x_2) = x_1^2 x_2 + x_2^3 x_1$\n\n(a)\n----\nFind the rate of increase of $f$ at point $x = \\begin{bmatrix} 2 & 1 \\end{bmatrix}^\\mathrm{T}$ in the direction $d = \\begin{bmatrix} 3 & 4 \\end{bmatrix}^\\mathrm{T}$\n\n\n```python\nx1, x2 = sp.symbols('x1 x2')\nf_x = x1**2*x2 + x2**3*x1\npoint = (2, 1)\ndirection = np.array([[3], [4]])\n\njacobian_sym = sp.derive_by_array(f_x, [x1, x2])\njacobian = sp.lambdify((x1, x2), jacobian_sym, modules='numpy')\ngradient_at_point = np.array(jacobian(2, 1))\ndir_derivative = gradient_at_point.T@direction\n\nprint('The rate of increase at the selected point and direction is ', dir_derivative)\n```\n\n(b)\n----\nIn what direction does the function f decreases most rapidly at the point $ x = \\begin{bmatrix} 2 & 1 \\end{bmatrix}^T? $\n\n\n```python\njacobian_sym = sp.derive_by_array(f_x, [x1, x2])\nhessian_sym = sp.derive_by_array(jacobian_sym, [x1, x2])\n\njacobian = sp.lambdify((x1, x2), jacobian_sym, modules='numpy')\nhessian = sp.lambdify((x1, x2), hessian_sym, modules='numpy')\n\ngradient_at_point = np.array(jacobian(2, 1))\nmax_incr_direction = gradient_at_point/np.linalg.norm(gradient_at_point)\nmin_incr_direction = max_incr_direction*-1\nprint('The direction of min increase at the selected point and direction is ', min_incr_direction)\n```\n\n\n```python\nlam_f = sp.lambdify([x1, x2], f_x, modules=['numpy'])\n\nstep = 0.1\ngradient_step = 0.1\nx_vals = np.arange(-8, 8, step)\ny_vals = np.arange(-8, 8, step)\nx_vals, y_vals = np.meshgrid(x_vals, y_vals)\n\n# Symbolic to real values\nf_vals = lam_f(x_vals, y_vals)\ngradient_x, gradient_y = np.gradient(f_vals, gradient_step)\n```\n\n\n```python\nfig = plt.figure()\nlevels = 10\n\nax0 = fig.add_subplot(1, 2, 1)\nax0.contour (x_vals, y_vals, f_vals, levels) \n\nskip=(slice(None,None,6),slice(None,None,6))\nax0.contour (x_vals, y_vals, f_vals)\nax0.quiver(x_vals[skip], y_vals[skip], gradient_x[skip], gradient_y[skip],\n minshaft=1.5, minlength=1.5, units='width', scale_units='dots', scale=20, angles='xy')\nax0.set_xlabel( '$x_1$' ) \nax0.set_ylabel( '$x_2$' )\n\nax1 = fig.add_subplot(1, 2, 2, projection='3d')\nax1.plot_surface(x_vals, y_vals, f_vals, cmap=cm.viridis,\n                       linewidth=0.1, antialiased=True)\nax1.view_init(30, 45)\nax1.set_xlabel( '$x_1$' ) \nax1.set_ylabel( '$x_2$' )\n\nfig_dpi = 150\nfig_width = 18.8/2.54\nfig_height = 9.4/2.54\n\nfig.dpi=fig_dpi\nfig.set_size_inches((fig_width,fig_height))\nfig.tight_layout()\n\nplt.show()\n```\n\nProblem 3\n=========\n\nFind minimum and maximum points of $f (x_1, x_2) = (x_1^2 + x_2^2-1)^2 + (x_2^2 - 1)^2$\n\n\n```python\nx1, x2 = sp.symbols('x1 x2')\nd1, d2 = sp.symbols('d1 d2')\nf_x = (x1**2 + x2**2-1)**2 + (x2**2 - 1)**2\n```\n\nFirst, we get critic points solving $\\nabla f(\\mathbf{x}) = 0$\n\n\n```python\njacobian_sym = sp.derive_by_array(f_x, [x1, x2])\nnonlinsolve(jacobian_sym, (x1, x2))\n```\n\nFinally, we check whether the Hessian matrix is positive or negative defined at the points previously found. This analysis can be done with the matrix eigenvalves or by prooving the Second-Order Necessary Condition.\n\n\n```python\nhessian_sym = sp.derive_by_array(jacobian_sym, [x1, x2])\nhessian = sp.lambdify((x1, x2), hessian_sym, modules='numpy')\nhessian_sym\n```\n\n1) At $\\mathbf{x}^* = [-1, 0]^T$, we are going to verify $\\mathbf{d}^\\mathrm{T} \\mathbf{H}(\\mathbf{x^*}) \\mathbf{d} $ all feasible directions.\n\n\n```python\nhessian_at_x = np.array(hessian(-1, 0))\ndirection = sp.matrices.Matrix([[d1], [d2]])\ndirection.T@hessian_at_x@direction\n```\n\n$\\mathbf{d}^\\mathrm{T} \\mathbf{H}(\\mathbf{x^*}) \\mathbf{d} $ can be either positive or negative according to $\\mathbf{d}$; then, $\\mathbf{x}^*$ is a saddle point.\n\n2) At $\\mathbf{x}^* = [0, -1]^T$, we are going to verify $\\mathbf{d}^\\mathrm{T} \\mathbf{H}(\\mathbf{x^*}) \\mathbf{d} $ all feasible directions.\n\n\n```python\nhessian_at_x = np.array(hessian(0, -1))\ndirection = sp.matrices.Matrix([[d1], [d2]])\ndirection.T@hessian_at_x@direction\n```\n\n$\\mathbf{d}^\\mathrm{T} \\mathbf{H}(\\mathbf{x^*}) \\mathbf{d}$ can be only positive for all feasible direction any direction $\\mathbf{d}$; then, $\\mathbf{x}^* = [0, -1]$ is a minimizer.\n\n3) At $\\mathbf{x}^* = [0, 0]^T$, we are going to verify $\\mathbf{d}^\\mathrm{T} \\mathbf{H}(\\mathbf{x^*}) \\mathbf{d} $ all feasible directions.\n\n\n```python\nhessian_at_x = np.array(hessian(0, 0))\ndirection = sp.matrices.Matrix([[d1], [d2]])\ndirection.T@hessian_at_x@direction\n```\n\n$\\mathbf{d}^\\mathrm{T} \\mathbf{H}(\\mathbf{x^*}) \\mathbf{d}$ can be only negative for all feasible direction any direction $\\mathbf{d}$; then, $\\mathbf{x}^* = [0, -1]$ is a maximizer.\n\n4) At $\\mathbf{x}^* = [0, 1]^T$, we are going to verify $\\mathbf{d}^\\mathrm{T} \\mathbf{H}(\\mathbf{x^*}) \\mathbf{d} $ all feasible directions.\n\n\n```python\nhessian_at_x = np.array(hessian(0, 1))\ndirection = sp.matrices.Matrix([[d1], [d2]])\ndirection.T@hessian_at_x@direction\n```\n\n$\\mathbf{d}^\\mathrm{T} \\mathbf{H}(\\mathbf{x^*}) \\mathbf{d}$ can be only positive for all feasible direction any direction $\\mathbf{d}$; then, $\\mathbf{x}^* = [0, 1]$ is a minimizer.\n\n5) At $\\mathbf{x}^* = [1, 0]^T$, we are going to verify $\\mathbf{d}^\\mathrm{T} \\mathbf{H}(\\mathbf{x^*}) \\mathbf{d} $ all feasible directions.\n\n\n```python\nhessian_at_x = np.array(hessian(1, 0))\ndirection = sp.matrices.Matrix([[d1], [d2]])\ndirection.T@hessian_at_x@direction\n```\n\n$\\mathbf{d}^\\mathrm{T} \\mathbf{H}(\\mathbf{x^*}) \\mathbf{d} $ can be either positive or negative according to $\\mathbf{d}$; then, $\\mathbf{x}^* = [1, 0]$  is a saddle point.\n\n\n```python\nlam_f = sp.lambdify([x1, x2], f_x, modules=['numpy'])\n\nstep = 0.001\nx_vals = np.arange(-1.2, 1.2, step)\ny_vals = np.arange(-1.2, 1.2, step)\nx_vals, y_vals = np.meshgrid(x_vals, y_vals)\n\n# Symbolic to real values\nf_vals = lam_f(x_vals, y_vals)\n```\n\n\n```python\nfig = plt.figure()\nlevels = 5\n\nax0 = fig.add_subplot(1, 2, 1)\nax0.contour (x_vals, y_vals, f_vals, levels) \n\nax0.contour(x_vals, y_vals, f_vals)\nax0.set_xlabel( '$x_1$' ) \nax0.set_ylabel( '$x_2$' )\n\nax1 = fig.add_subplot(1, 2, 2, projection='3d')\nax1.plot_surface(x_vals, y_vals, f_vals, cmap=cm.viridis,\n                       linewidth=0.1, antialiased=True)\n# ax1.view_init(30, 45)\nax1.set_xlabel( '$x_1$' ) \nax1.set_ylabel( '$x_2$' )\n\nfig_dpi = 150\nfig_width = 18.8/2.54\nfig_height = 9.4/2.54\n\nfig.dpi=fig_dpi\nfig.set_size_inches((fig_width,fig_height))\nfig.tight_layout()\n\nplt.show()\n```\n\nProblem 4\n=========\n\nFind the minimizer of $f(x_1, x_2, x_3) = (x_1-4)^2 +(x_2-3)^2 +(x_3+4)^2 $ using:\n\n(a) The steepest descent method. \n\n(b) The constant step size with $\\alpha = 0.1$.\n\nwith $\\mathbf{x}_0 = \\begin{bmatrix} 4 \\\\ 2 \\\\ -1 \\end{bmatrix}$ and stopping criteria $\\nabla f (\\mathbf{x}) < 0,001$.\n\n\n(a)\n----\nThe steepest descent method\n\n\n```python\nx = sp.symbols('x1 x2 x3')\nfunc = (x[0]-4)**2 +(x[1]-3)**2 +(x[2]+4)**2\nx0 = [-1, 1, 1]\nerror=0.001\nfunction = sp.lambdify([*x], func, modules='numpy')\n\nmin, search_steps = optimize.steepest_descent(func, x, start=x0, stop_criteria='gradient',\n err=error, full_output=True)\n```\n\n\n```python\nprint('The minimizer', min, 'was found in', search_steps.shape[0], 'iterations')\n```\n\n(b)\n---\nThe constant step size with $\\alpha = 0.1$.\n\n\n```python\nmin, search_steps = optimize.steepest_descent(func, x, start=x0, stop_criteria='gradient',\nstep_type='fix', err=error, full_output=True)\n```\n\n\n```python\nprint('The minimizer', min, 'was found in', search_steps.shape[0], 'iterations')\n```\n\nProblem 5\n=========\nFind the minimizer of Rosenbrock\u2019s function:\n$$\nf (x) = (1 \u2212 x_1)^2 + 100(x_2 \u2212 x_1^2)^2\n$$\n\nUse an initial point $x_0 = \\begin{bmatrix} -1  \\\\ -1 \\end{bmatrix}$ and terminate the algorithm when $||\\nabla f (\\mathbf{x})|| < 0,001$.\n\n\n\n```python\nx = sp.symbols('x1 x2')\nfunc = (1-x[0])**2 + 100*(x[1]-x[0]**2)**2\nx0 = [-1, -1]\nfunction = sp.lambdify([*x], func, modules='numpy')\n\nmin, search_steps = optimize.steepest_descent(func, x, start=x0, stop_criteria='gradient', err=0.001,\nmax_iter=2000, full_output=True)\n```\n\n\n```python\nfig = plt.figure()\n\nstep = 0.01\nx_vals = np.arange(-2, 2, step)\ny_vals = np.arange(-1., 3, step)\nX, Y = np.meshgrid(x_vals, y_vals)\nfunc_eval = function(X,Y)\n\nax1 = fig.add_subplot(1,2,1)\nax1.contour(X, Y, func_eval)\nax1.plot(search_steps[:, 0],search_steps[:, 1],'-k.', linewidth='0.8', markersize=6)\nax1.set_xlabel('$x_1$')\nax1.set_ylabel('$x_2$')\n\nax2 = fig.add_subplot(1,2,2, projection='3d')\nax2.plot_surface(X, Y, func_eval, cmap=cm.RdYlGn,\n                       linewidth=0.1, antialiased=True)\nax2.set_xlabel('$x_1$')\nax2.set_ylabel('$x_2$')\nax2.view_init(30, 135)\n\nfig_dpi = 150\nfig_width = 18.8/2.54\nfig_height = 9.4/2.54\n\nfig.dpi=fig_dpi\nfig.set_size_inches((fig_width,fig_height))\nfig.tight_layout()\n\nplt.show()\n```\n\n\n```python\nprint('The minimizer', min, 'was found in', search_steps.shape[0], 'iterations')\n```\n\n## Trying another start point:\n\n Lets see with $x_0 = \\begin{bmatrix} 1  \\\\ 2 \\end{bmatrix}$\n\n\n```python\nx0 = [1, 2]\nmin, search_steps = optimize.steepest_descent(func, x, start=x0, stop_criteria='gradient', err=0.001,\nmax_iter=2000, full_output=True)\n```\n\n\n```python\nfig = plt.figure()\n\nstep = 0.01\nx_vals = np.arange(-2, 2, step)\ny_vals = np.arange(-1., 3, step)\nX, Y = np.meshgrid(x_vals, y_vals)\nfunc_eval = function(X,Y)\n\nax1 = fig.add_subplot(1,2,1)\nax1.contour(X, Y, func_eval)\nax1.plot(search_steps[:, 0],search_steps[:, 1],'-k.', linewidth='0.8', markersize=6)\nax1.set_xlabel('$x_1$')\nax1.set_ylabel('$x_2$')\n\nax2 = fig.add_subplot(1,2,2, projection='3d')\nax2.plot_surface(X, Y, func_eval, cmap=cm.RdYlGn,\n                       linewidth=0.1, antialiased=True)\nax2.set_xlabel('$x_1$')\nax2.set_ylabel('$x_2$')\nax2.view_init(30, 135)\n\nfig_dpi = 150\nfig_width = 18.8/2.54\nfig_height = 9.4/2.54\n\nfig.dpi=fig_dpi\nfig.set_size_inches((fig_width,fig_height))\nfig.tight_layout()\n\nplt.show()\n```\n\n\n```python\nprint('The minimizer', min, 'was found in', search_steps.shape[0], 'iterations')\n```\n", "meta": {"hexsha": "f86f5801d0ba2fa9975027b07a5c3b1f0e4a3f8a", "size": 36687, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "numeric_analysis_exercises/cap3_set_constrained_optimization.ipynb", "max_stars_repo_name": "lufgarciaar/num_analysis_exercises", "max_stars_repo_head_hexsha": "d145908494c5a7453830ec32dcac91df6fb028a4", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numeric_analysis_exercises/cap3_set_constrained_optimization.ipynb", "max_issues_repo_name": "lufgarciaar/num_analysis_exercises", "max_issues_repo_head_hexsha": "d145908494c5a7453830ec32dcac91df6fb028a4", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numeric_analysis_exercises/cap3_set_constrained_optimization.ipynb", "max_forks_repo_name": "lufgarciaar/num_analysis_exercises", "max_forks_repo_head_hexsha": "d145908494c5a7453830ec32dcac91df6fb028a4", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36687.0, "max_line_length": 36687, "alphanum_fraction": 0.6923160793, "converted": true, "num_tokens": 5677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629691917376783, "lm_q2_score": 0.11436852467249821, "lm_q1q2_score": 0.04151225096060739}}
{"text": "##### Copyright 2020 The TensorFlow Authors.\n\n\n```python\n#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# Noise\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n  <td>\n    <a target=\"_blank\" href=\"https://www.tensorflow.org/quantum/tutorials/noise\">View on TensorFlow.org</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/quantum/blob/master/docs/tutorials/noise.ipynb\">Run in Google Colab</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://github.com/tensorflow/quantum/blob/master/docs/tutorials/noise.ipynb\">View source on GitHub</a>\n  </td>\n  <td>\n    <a href=\"https://storage.googleapis.com/tensorflow_docs/quantum/docs/tutorials/noise.ipynb\">Download notebook</a>\n  </td>\n</table>\n\nNoise is present in modern day quantum computers. Qubits are susceptible to interference from the surrounding environment, imperfect fabrication, TLS and sometimes even [gamma rays](https://arxiv.org/abs/2104.05219). Until large scale error correction is reached, the algorithms of today must be able to remain functional in the presence of noise. This makes testing algorithms under noise an important step for validating quantum algorithms / models will function on the quantum computers of today.\n\nIn this tutorial you will explore the basics of noisy circuit simulation in TFQ via the high level `tfq.layers` API.\n\n## Setup\n\n\n```python\n!pip install tensorflow==2.7.0 tensorflow-quantum\n```\n\n\n```python\n!pip install -q git+https://github.com/tensorflow/docs\n```\n\n\n```python\n# Update package resources to account for version changes.\nimport importlib, pkg_resources\nimportlib.reload(pkg_resources)\n```\n\n\n```python\nimport random\nimport cirq\nimport sympy\nimport tensorflow_quantum as tfq\nimport tensorflow as tf\nimport numpy as np\n# Plotting\nimport matplotlib.pyplot as plt\nimport tensorflow_docs as tfdocs\nimport tensorflow_docs.plots\n```\n\n## 1. Understanding quantum noise\n\n### 1.1 Basic circuit noise\n\nNoise on a quantum computer impacts the bitstring samples you are able to measure from it. One intuitive way you can start to think about this is that a noisy quantum computer will \"insert\", \"delete\" or \"replace\" gates in random places like the diagram below:\n\n\n\nBuilding off of this intuition, when dealing with noise, you are no longer using a single pure state $|\\psi \\rangle$ but instead dealing with an *ensemble* of all possible noisy realizations of your desired circuit: $\\rho = \\sum_j p_j |\\psi_j \\rangle \\langle \\psi_j |$ . Where $p_j$ gives the probability that the system is in $|\\psi_j \\rangle$ .\n\nRevisiting the above picture, if we knew beforehand that 90% of the time our system executed perfectly, or errored 10% of the time with just this one mode of failure, then our ensemble would be: \n\n$\\rho = 0.9 |\\psi_\\text{desired} \\rangle \\langle \\psi_\\text{desired}| + 0.1 |\\psi_\\text{noisy} \\rangle \\langle \\psi_\\text{noisy}| $\n\nIf there was more than just one way that our circuit could error, then the ensemble $\\rho$ would contain more than just two terms (one for each new noisy realization that could happen). $\\rho$ is referred to as the [density matrix](https://en.wikipedia.org/wiki/Density_matrix) describing your noisy system.\n\n### 1.2 Using channels to model circuit noise\n\nUnfortunately in practice it's nearly impossible to know all the ways your circuit might error and their exact probabilities. A simplifying assumption you can make is that after each operation in your circuit there is some kind of [channel](https://quantumai.google/cirq/noise) that roughly captures how that operation might error. You can quickly create a circuit with some noise:\n\n\n```python\ndef x_circuit(qubits):\n  \"\"\"Produces an X wall circuit on `qubits`.\"\"\"\n  return cirq.Circuit(cirq.X.on_each(*qubits))\n\ndef make_noisy(circuit, p):\n  \"\"\"Add a depolarization channel to all qubits in `circuit` before measurement.\"\"\"\n  return circuit + cirq.Circuit(cirq.depolarize(p).on_each(*circuit.all_qubits()))\n\nmy_qubits = cirq.GridQubit.rect(1, 2)\nmy_circuit = x_circuit(my_qubits)\nmy_noisy_circuit = make_noisy(my_circuit, 0.5)\nmy_circuit\n```\n\n\n```python\nmy_noisy_circuit\n```\n\nYou can examine the noiseless density matrix $\\rho$ with:\n\n\n```python\nrho = cirq.final_density_matrix(my_circuit)\nnp.round(rho, 3)\n```\n\nAnd the noisy density matrix $\\rho$ with:\n\n\n\n```python\nrho = cirq.final_density_matrix(my_noisy_circuit)\nnp.round(rho, 3)\n```\n\nComparing the two different $ \\rho $ 's you can see that the noise has impacted the amplitudes of the state (and consequently sampling probabilities). In the noiseless case you would always expect to sample the $ |11\\rangle $ state. But in the noisy state there is now a nonzero probability of sampling $ |00\\rangle $ or $ |01\\rangle $ or $ |10\\rangle $ as well:\n\n\n```python\n\"\"\"Sample from my_noisy_circuit.\"\"\"\ndef plot_samples(circuit):\n  samples = cirq.sample(circuit + cirq.measure(*circuit.all_qubits(), key='bits'), repetitions=1000)\n  freqs, _ = np.histogram(samples.data['bits'], bins=[i+0.01 for i in range(-1,2** len(my_qubits))])\n  plt.figure(figsize=(10,5))\n  plt.title('Noisy Circuit Sampling')\n  plt.xlabel('Bitstring')\n  plt.ylabel('Frequency')\n  plt.bar([i for i in range(2** len(my_qubits))], freqs, tick_label=['00','01','10','11'])\n\nplot_samples(my_noisy_circuit)\n```\n\nWithout any noise you will always get $|11\\rangle$:\n\n\n```python\n\"\"\"Sample from my_circuit.\"\"\"\nplot_samples(my_circuit)\n```\n\nIf you increase the noise a little further it will become harder and harder to distinguish the desired behavior (sampling $|11\\rangle$ ) from the noise:\n\n\n```python\nmy_really_noisy_circuit = make_noisy(my_circuit, 0.75)\nplot_samples(my_really_noisy_circuit)\n```\n\nNote: Try experimenting with different channels in your circuit to generate noise. Common channels supported in both Cirq and TFQ can be found [here](https://github.com/quantumlib/Cirq/blob/master/cirq-core/cirq/ops/common_channels.py)\n\n## 2. Basic noise in TFQ\nWith this understanding of how noise can impact circuit execution, you can explore how noise works in TFQ. TensorFlow Quantum uses monte-carlo / trajectory based simulation as an alternative to density matrix simulation. This is because the memory complexity of density matrix simulation limits large simulations to being <= 20 qubits with traditional full density matrix simulation methods. Monte-carlo / trajectory trades this cost in memory for additional cost in time. The `backend='noisy'` option available to all `tfq.layers.Sample`, `tfq.layers.SampledExpectation` and `tfq.layers.Expectation` (In the case of `Expectation` this does add a required `repetitions` parameter).\n\n### 2.1 Noisy sampling in TFQ\nTo recreate the above plots using TFQ and trajectory simulation you can use `tfq.layers.Sample`\n\n\n```python\n\"\"\"Draw bitstring samples from `my_noisy_circuit`\"\"\"\nbitstrings = tfq.layers.Sample(backend='noisy')(my_noisy_circuit, repetitions=1000)\n```\n\n\n```python\nnumeric_values = np.einsum('ijk,k->ij', bitstrings.to_tensor().numpy(), [1, 2])[0]\nfreqs, _ = np.histogram(numeric_values, bins=[i+0.01 for i in range(-1,2** len(my_qubits))])\nplt.figure(figsize=(10,5))\nplt.title('Noisy Circuit Sampling')\nplt.xlabel('Bitstring')\nplt.ylabel('Frequency')\nplt.bar([i for i in range(2** len(my_qubits))], freqs, tick_label=['00','01','10','11'])\n```\n\n### 2.2 Noisy sample based expectation\nTo do noisy sample based expectation calculation you can use `tfq.layers.SampleExpectation`:\n\n\n\n```python\nsome_observables = [cirq.X(my_qubits[0]), cirq.Z(my_qubits[0]), 3.0 * cirq.Y(my_qubits[1]) + 1]\nsome_observables\n```\n\nCompute the noiseless expectation estimates via sampling from the circuit:\n\n\n```python\nnoiseless_sampled_expectation = tfq.layers.SampledExpectation(backend='noiseless')(\n    my_circuit, operators=some_observables, repetitions=10000\n)\nnoiseless_sampled_expectation.numpy()\n```\n\nCompare those with the noisy versions:\n\n\n```python\nnoisy_sampled_expectation = tfq.layers.SampledExpectation(backend='noisy')(\n    [my_noisy_circuit, my_really_noisy_circuit], operators=some_observables, repetitions=10000\n)\nnoisy_sampled_expectation.numpy()\n```\n\nYou can see that the noise has particularly impacted the $\\langle \\psi | Z | \\psi \\rangle$ accuracy, with `my_really_noisy_circuit` concentrating very quickly towards 0.\n\n### 2.3 Noisy analytic expectation calculation\nDoing noisy analytic expectation calculations is nearly identical to above:\n\n\n\n\n```python\nnoiseless_analytic_expectation = tfq.layers.Expectation(backend='noiseless')(\n    my_circuit, operators=some_observables\n)\nnoiseless_analytic_expectation.numpy()\n```\n\n\n```python\nnoisy_analytic_expectation = tfq.layers.Expectation(backend='noisy')(\n    [my_noisy_circuit, my_really_noisy_circuit], operators=some_observables, repetitions=10000\n)\nnoisy_analytic_expectation.numpy()\n```\n\n## 3. Hybrid models and quantum data noise\nNow that you have implemented some noisy circuit simulations in TFQ, you can experiment with how noise impacts quantum and hybrid quantum classical models, by comparing and contrasting their noisy vs noiseless performance. A good first check to see if a model or algorithm is robust to noise is to test under a circuit wide depolarizing model which looks something like this:\n\n\n\nWhere each time slice of the circuit (sometimes referred to as moment) has a depolarizing channel appended after each gate operation in that time slice. The depolarizing channel with apply one of $\\{X, Y, Z \\}$ with probability $p$ or apply nothing (keep the original operation) with probability $1-p$.\n\n### 3.1 Data\nFor this example you can use some prepared circuits in the `tfq.datasets` module as training data:\n\n\n```python\nqubits = cirq.GridQubit.rect(1, 8)\ncircuits, labels, pauli_sums, _ = tfq.datasets.xxz_chain(qubits, 'closed')\ncircuits[0]\n```\n\nWriting a small helper function will help to generate the data for the noisy vs noiseless case:\n\n\n```python\ndef get_data(qubits, depolarize_p=0.):\n  \"\"\"Return quantum data circuits and labels in `tf.Tensor` form.\"\"\"\n  circuits, labels, pauli_sums, _ = tfq.datasets.xxz_chain(qubits, 'closed')\n  if depolarize_p >= 1e-5:\n    circuits = [circuit.with_noise(cirq.depolarize(depolarize_p)) for circuit in circuits]\n  tmp = list(zip(circuits, labels))\n  random.shuffle(tmp)\n  circuits_tensor = tfq.convert_to_tensor([x[0] for x in tmp])\n  labels_tensor = tf.convert_to_tensor([x[1] for x in tmp])\n\n  return circuits_tensor, labels_tensor\n```\n\n### 3.2 Define a model circuit\nNow that you have quantum data in the form of circuits, you will need a circuit to model this data, like with the data you can write a helper function to generate this circuit optionally containing noise:\n\n\n```python\ndef modelling_circuit(qubits, depth, depolarize_p=0.):\n  \"\"\"A simple classifier circuit.\"\"\"\n  dim = len(qubits)\n  ret = cirq.Circuit(cirq.H.on_each(*qubits))\n\n  for i in range(depth):\n    # Entangle layer.\n    ret += cirq.Circuit(cirq.CX(q1, q2) for (q1, q2) in zip(qubits[::2], qubits[1::2]))\n    ret += cirq.Circuit(cirq.CX(q1, q2) for (q1, q2) in zip(qubits[1::2], qubits[2::2]))\n    # Learnable rotation layer.\n    # i_params = sympy.symbols(f'layer-{i}-0:{dim}')\n    param = sympy.Symbol(f'layer-{i}')\n    single_qb = cirq.X\n    if i % 2 == 1:\n      single_qb = cirq.Y\n    ret += cirq.Circuit(single_qb(q) ** param for q in qubits)\n  \n  if depolarize_p >= 1e-5:\n    ret = ret.with_noise(cirq.depolarize(depolarize_p))\n\n  return ret, [op(q) for q in qubits for op in [cirq.X, cirq.Y, cirq.Z]]\n\nmodelling_circuit(qubits, 3)[0]\n```\n\n### 3.3 Model building and training\nWith your data and model circuit built, the final helper function you will need is one that can assemble both a noisy or a noiseless hybrid quantum `tf.keras.Model`:\n\n\n```python\ndef build_keras_model(qubits, depolarize_p=0.):\n  \"\"\"Prepare a noisy hybrid quantum classical Keras model.\"\"\"\n  spin_input = tf.keras.Input(shape=(), dtype=tf.dtypes.string)\n\n  circuit_and_readout = modelling_circuit(qubits, 4, depolarize_p)\n  if depolarize_p >= 1e-5:\n    quantum_model = tfq.layers.NoisyPQC(*circuit_and_readout, sample_based=False, repetitions=10)(spin_input)\n  else:\n    quantum_model = tfq.layers.PQC(*circuit_and_readout)(spin_input)\n\n  intermediate = tf.keras.layers.Dense(4, activation='sigmoid')(quantum_model)\n  post_process = tf.keras.layers.Dense(1)(intermediate)\n\n  return tf.keras.Model(inputs=[spin_input], outputs=[post_process])\n```\n\n## 4. Compare performance\n\n### 4.1 Noiseless baseline\n\nWith your data generation and model building code, you can now compare and contrast model performance in the noiseless and noisy settings, first you can run a reference noiseless training:\n\n\n```python\ntraining_histories = dict()\ndepolarize_p = 0.\nn_epochs = 50\nphase_classifier = build_keras_model(qubits, depolarize_p)\n\nphase_classifier.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.02),\n                   loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n                   metrics=['accuracy'])\n\n\n# Show the keras plot of the model\ntf.keras.utils.plot_model(phase_classifier, show_shapes=True, dpi=70)\n```\n\n\n```python\nnoiseless_data, noiseless_labels = get_data(qubits, depolarize_p)\ntraining_histories['noiseless'] = phase_classifier.fit(x=noiseless_data,\n                         y=noiseless_labels,\n                         batch_size=16,\n                         epochs=n_epochs,\n                         validation_split=0.15,\n                         verbose=1)\n```\n\nAnd explore the results and accuracy:\n\n\n```python\nloss_plotter = tfdocs.plots.HistoryPlotter(metric = 'loss', smoothing_std=10)\nloss_plotter.plot(training_histories)\n```\n\n\n```python\nacc_plotter = tfdocs.plots.HistoryPlotter(metric = 'accuracy', smoothing_std=10)\nacc_plotter.plot(training_histories)\n```\n\n### 4.2 Noisy comparison\nNow you can build a new model with noisy structure and compare to the above, the code is nearly identical:\n\n\n```python\ndepolarize_p = 0.001\nn_epochs = 50\nnoisy_phase_classifier = build_keras_model(qubits, depolarize_p)\n\nnoisy_phase_classifier.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.02),\n                   loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n                   metrics=['accuracy'])\n\n\n# Show the keras plot of the model\ntf.keras.utils.plot_model(noisy_phase_classifier, show_shapes=True, dpi=70)\n```\n\nNote: in the model diagram there is now a `tfq.layers.NoisyPQC` instead of a `tfq.layers.PQC` since the depolarization probability is no longer zero. Training will take significantly longer since noisy simulation is far more expensive than noiseless.\n\n\n```python\nnoisy_data, noisy_labels = get_data(qubits, depolarize_p)\ntraining_histories['noisy'] = noisy_phase_classifier.fit(x=noisy_data,\n                         y=noisy_labels,\n                         batch_size=16,\n                         epochs=n_epochs,\n                         validation_split=0.15,\n                         verbose=1)\n```\n\n\n```python\nloss_plotter.plot(training_histories)\n```\n\n\n```python\nacc_plotter.plot(training_histories)\n```\n\nSuccess: The noisy model still managed to train under some mild depolarization noise. Try experimenting with different noise models to see how and when training might fail. Also look out for noisy functionality under `tfq.layers` and `tfq.noise`.\n", "meta": {"hexsha": "3e9e0768137e818cfb1b0fe7dd8e3cc8dfdd67ec", "size": 28262, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/noise.ipynb", "max_stars_repo_name": "artiseza/quantum", "max_stars_repo_head_hexsha": "72f6e5bae843c841117426a0c8e1ee1d6557995e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-10T11:20:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T11:20:48.000Z", "max_issues_repo_path": "docs/tutorials/noise.ipynb", "max_issues_repo_name": "artiseza/quantum", "max_issues_repo_head_hexsha": "72f6e5bae843c841117426a0c8e1ee1d6557995e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/tutorials/noise.ipynb", "max_forks_repo_name": "artiseza/quantum", "max_forks_repo_head_hexsha": "72f6e5bae843c841117426a0c8e1ee1d6557995e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.064516129, "max_line_length": 694, "alphanum_fraction": 0.5471658057, "converted": true, "num_tokens": 3953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423539898095244, "lm_q2_score": 0.12765262532179067, "lm_q1q2_score": 0.04138949990217683}}
{"text": "This notebook is part of the `nbsphinx` documentation: https://nbsphinx.readthedocs.io/.\n\n# Code Cells\n\n## Code, Output, Streams\n\nAn empty code cell:\n\n\n```python\n\n```\n\nTwo empty lines:\n\n\n```python\n\n\n```\n\nLeading/trailing empty lines:\n\n\n```python\n\n\n# 2 empty lines before, 1 after\n\n```\n\nA simple output:\n\n\n```python\n6 * 7\n```\n\nThe standard output stream:\n\n\n```python\nprint('Hello, world!')\n```\n\nNormal output + standard output\n\n\n```python\nprint('Hello, world!')\n6 * 7\n```\n\nThe standard error stream is highlighted and displayed just below the code cell.\nThe standard output stream comes afterwards (with no special highlighting).\nFinally, the \"normal\" output is displayed.\n\n\n```python\nimport sys\n\nprint(\"I'll appear on the standard error stream\", file=sys.stderr)\nprint(\"I'll appear on the standard output stream\")\n\"I'm the 'normal' output\"\n```\n\n<div class=\"alert alert-info\">\n\nNote\n\nUsing the IPython kernel, the order is actually mixed up,\nsee https://github.com/ipython/ipykernel/issues/280.\n\n</div>\n\n## Cell Magics\n\nIPython can handle code in other languages by means of [cell magics](https://ipython.readthedocs.io/en/stable/interactive/magics.html#cell-magics):\n\n\n```bash\n%%bash\nfor i in 1 2 3\ndo\n    echo $i\ndone\n```\n\n## Special Display Formats\n\nSee [IPython example notebook](https://nbviewer.jupyter.org/github/ipython/ipython/blob/master/examples/IPython Kernel/Rich Output.ipynb).\n\n### Local Image Files\n\n\n```python\nfrom IPython.display import Image\ni = Image(filename='images/notebook_icon.png')\ni\n```\n\n\n```python\ndisplay(i)\n```\n\nSee also [SVG support for LaTeX](markdown-cells.ipynb#SVG-support-for-LaTeX).\n\n\n```python\nfrom IPython.display import SVG\nSVG(filename='images/python_logo.svg')\n```\n\n### Image URLs\n\n\n```python\nImage(url='https://www.python.org/static/img/python-logo-large.png')\n```\n\n\n```python\nImage(url='https://www.python.org/static/img/python-logo-large.png', embed=True)\n```\n\n\n```python\nImage(url='https://jupyter.org/assets/nav_logo.svg')\n```\n\n### Math\n\n\n```python\nfrom IPython.display import Math\neq = Math(r'\\int\\limits_{-\\infty}^\\infty f(x) \\delta(x - x_0) dx = f(x_0)')\neq\n```\n\n\n```python\ndisplay(eq)\n```\n\n\n```python\nfrom IPython.display import Latex\nLatex(r'This is a \\LaTeX{} equation: $a^2 + b^2 = c^2$')\n```\n\n\n```latex\n%%latex\n\\begin{equation}\n\\int\\limits_{-\\infty}^\\infty f(x) \\delta(x - x_0) dx = f(x_0)\n\\end{equation}\n```\n\n### Plots\n\nThe output formats for Matplotlib plots can be customized.\nYou'll need separate settings for the Jupyter Notebook application and for `nbsphinx`.\n\nIf you want to use SVG images for Matplotlib plots,\nadd this line to your IPython configuration file:\n\n```python\nc.InlineBackend.figure_formats = {'svg'}\n```\n\nIf you want SVG images, but also want nice plots when exporting to LaTeX/PDF, you can select:\n\n```python\nc.InlineBackend.figure_formats = {'svg', 'pdf'}\n```\n\nIf you want to use the default PNG plots or HiDPI plots using `'png2x'` (a.k.a. `'retina'`),\nmake sure to set this:\n\n```python\nc.InlineBackend.rc = {'figure.dpi': 96}\n```\n\nThis is needed because the default `'figure.dpi'` value of 72\nis only valid for the [Qt Console](https://qtconsole.readthedocs.io/).\n\nIf you are planning to store your SVG plots as part of your notebooks,\nyou should also have a look at the `'svg.hashsalt'` setting.\n\nFor more details on these and other settings, have a look at\n[Default Values for Matplotlib's \"inline\" Backend](https://nbviewer.jupyter.org/github/mgeier/python-audio/blob/master/plotting/matplotlib-inline-defaults.ipynb).\n\nThe configuration file `ipython_kernel_config.py` can be either\nin the directory where your notebook is located\n(see the [ipython_kernel_config.py](ipython_kernel_config.py) in this directory),\nor in your profile directory\n(typically `~/.ipython/profile_default/ipython_kernel_config.py`).\nTo find out your IPython profile directory, use this command:\n\n    python3 -m IPython profile locate\n\nA local `ipython_kernel_config.py` in the notebook directory\nalso works on https://mybinder.org/.\nAlternatively, you can create a file with those settings in a file named\n`.ipython/profile_default/ipython_kernel_config.py` in your repository.\n\nTo get SVG and PDF plots for `nbsphinx`,\nuse something like this in your `conf.py` file:\n\n```python\nnbsphinx_execute_arguments = [\n    \"--InlineBackend.figure_formats={'svg', 'pdf'}\",\n    \"--InlineBackend.rc={'figure.dpi': 96}\",\n]\n```\n    \nIn the following example, `nbsphinx` should use an SVG image in the HTML output\nand a PDF image for LaTeX/PDF output.\n\n\n```python\nimport matplotlib.pyplot as plt\n```\n\n\n```python\nfig, ax = plt.subplots(figsize=[6, 3])\nax.plot([4, 9, 7, 20, 6, 33, 13, 23, 16, 62, 8]);\n```\n\nAlternatively, the figure format(s) can also be chosen directly in the notebook\n(which overrides the setting in `nbsphinx_execute_arguments` and in the IPython configuration):\n\n\n```python\n%config InlineBackend.figure_formats = ['png']\n```\n\n\n```python\nfig\n```\n\nIf you want to use PNG images, but with HiDPI resolution,\nuse the special `'png2x'` (a.k.a. `'retina'`) format\n(which also looks nice in the LaTeX output):\n\n\n```python\n%config InlineBackend.figure_formats = ['png2x']\n```\n\n\n```python\nfig\n```\n\n### Pandas Dataframes\n\n[Pandas dataframes](https://pandas.pydata.org/pandas-docs/stable/user_guide/dsintro.html#dataframe)\nshould be displayed as nicely formatted HTML tables (if you are using HTML output).\n\n\n```python\nimport numpy as np\nimport pandas as pd\n```\n\n\n```python\ndf = pd.DataFrame(np.random.randint(0, 100, size=[5, 4]),\n                  columns=['a', 'b', 'c', 'd'])\ndf\n```\n\nFor LaTeX output, however, the plain text output is used by default.\n\nTo get nice LaTeX tables, a few settings have to be changed:\n\n\n```python\npd.set_option('display.latex.repr', True)\n```\n\nThis is not enabled by default because of\n[Pandas issue #12182](https://github.com/pandas-dev/pandas/issues/12182).\n\nThe generated LaTeX tables utilize the `booktabs` package, so you have to make sure that package is [loaded in the preamble](https://www.sphinx-doc.org/en/master/latex.html) with:\n\n    \\usepackage{booktabs}\n\nIn order to allow page breaks within tables, you should use:\n\n\n```python\npd.set_option('display.latex.longtable', True)\n```\n\nThe `longtable` package is already used by Sphinx,\nso you don't have to manually load it in the preamble.\n\nFinally, if you want to use LaTeX math expressions in your dataframe, you'll have to disable escaping:\n\n\n```python\npd.set_option('display.latex.escape', False)\n```\n\nThe above settings should have no influence on the HTML output, but the LaTeX output should now look nicer:\n\n\n```python\ndf = pd.DataFrame(np.random.randint(0, 100, size=[10, 4]),\n                  columns=[r'$\\alpha$', r'$\\beta$', r'$\\gamma$', r'$\\delta$'])\ndf\n```\n\n### YouTube Videos\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('WAikxUGbomY')\n```\n\n### Interactive Widgets (HTML only)\n\nThe basic widget infrastructure is provided by\nthe [ipywidgets](https://ipywidgets.readthedocs.io/) module.\nMore advanced widgets are available in separate packages,\nsee for example https://jupyter.org/widgets.\n\nThe JavaScript code which is needed to display Jupyter widgets\nis loaded automatically (using RequireJS).\nIf you want to use non-default URLs or local files,\nyou can use the\n[nbsphinx_widgets_path](usage.ipynb#nbsphinx_widgets_path) and\n[nbsphinx_requirejs_path](usage.ipynb#nbsphinx_requirejs_path)\nsettings.\n\n\n```python\nimport ipywidgets as w\n```\n\n\n```python\nslider = w.IntSlider()\nslider.value = 42\nslider\n```\n\nA widget typically consists of a so-called \"model\" and a \"view\" into that model.\n\nIf you display a widget multiple times,\nall instances act as a \"view\" into the same \"model\".\nThat means that their state is synchronized.\nYou can move either one of these sliders to try this out:\n\n\n```python\nslider\n```\n\nYou can also link different widgets.\n\nWidgets can be linked via the kernel\n(which of course only works while a kernel is running)\nor directly in the client\n(which even works in the rendered HTML pages).\n\nWidgets can be linked uni- or bi-directionally.\n\nExamples for all 4 combinations are shown here:\n\n\n```python\nlink = w.IntSlider(description='link')\nw.link((slider, 'value'), (link, 'value'))\njslink = w.IntSlider(description='jslink')\nw.jslink((slider, 'value'), (jslink, 'value'))\ndlink = w.IntSlider(description='dlink')\nw.dlink((slider, 'value'), (dlink, 'value'))\njsdlink = w.IntSlider(description='jsdlink')\nw.jsdlink((slider, 'value'), (jsdlink, 'value'))\nw.VBox([link, jslink, dlink, jsdlink])\n```\n\n<div class=\"alert alert-info\">\n\nOther Languages\n\nThe examples shown here are using Python,\nbut the widget technology can also be used with\ndifferent Jupyter kernels\n(i.e. with different programming languages).\n\n</div>\n\n### Arbitrary JavaScript Output (HTML only)\n\n\n```javascript\n%%javascript\n\nvar text = document.createTextNode(\"Hello, I was generated with JavaScript!\");\n// Content appended to \"element\" will be visible in the output area:\nelement.appendChild(text);\n```\n\n### Unsupported Output Types\n\nIf a code cell produces data with an unsupported MIME type, the Jupyter Notebook doesn't generate any output.\n`nbsphinx`, however, shows a warning message.\n\n\n```python\ndisplay({\n    'text/x-python': 'print(\"Hello, world!\")',\n    'text/x-haskell': 'main = putStrLn \"Hello, world!\"',\n}, raw=True)\n```\n\n## ANSI Colors\n\nThe standard output and standard error streams may contain [ANSI escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code) to change the text and background colors.\n\n\n```python\nprint('BEWARE: \\x1b[1;33;41mugly colors\\x1b[m!', file=sys.stderr)\nprint('AB\\x1b[43mCD\\x1b[35mEF\\x1b[1mGH\\x1b[4mIJ\\x1b[7m'\n      'KL\\x1b[49mMN\\x1b[39mOP\\x1b[22mQR\\x1b[24mST\\x1b[27mUV')\n```\n\nThe following code showing the 8 basic ANSI colors is based on https://tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html.\nEach of the 8 colors has an \"intense\" variation, which is used for bold text.\n\n\n```python\ntext = ' XYZ '\nformatstring = '\\x1b[{}m' + text + '\\x1b[m'\n\nprint(' ' * 6 + ' ' * len(text) +\n      ''.join('{:^{}}'.format(bg, len(text)) for bg in range(40, 48)))\nfor fg in range(30, 38):\n    for bold in False, True:\n        fg_code = ('1;' if bold else '') + str(fg)\n        print(' {:>4} '.format(fg_code) + formatstring.format(fg_code) +\n              ''.join(formatstring.format(fg_code + ';' + str(bg))\n                      for bg in range(40, 48)))\n```\n\nANSI also supports a set of 256 indexed colors.\nThe following code showing all of them is based on [http://bitmote.com/index.php?post/2012/11/19/Using-ANSI-Color-Codes-to-Colorize-Your-Bash-Prompt-on-Linux](https://web.archive.org/web/20190109005413/http://bitmote.com/index.php?post/2012/11/19/Using-ANSI-Color-Codes-to-Colorize-Your-Bash-Prompt-on-Linux).\n\n\n```python\nformatstring = '\\x1b[38;5;{0};48;5;{0}mX\\x1b[1mX\\x1b[m'\n\nprint('  + ' + ''.join('{:2}'.format(i) for i in range(36)))\nprint('  0 ' + ''.join(formatstring.format(i) for i in range(16)))\nfor i in range(7):\n    i = i * 36 + 16\n    print('{:3} '.format(i) + ''.join(formatstring.format(i + j)\n                                      for j in range(36) if i + j < 256))\n```\n\nYou can even use 24-bit RGB colors:\n\n\n```python\nstart = 255, 0, 0\nend = 0, 0, 255\nlength = 79\nout = []\n\nfor i in range(length):\n    rgb = [start[c] + int(i * (end[c] - start[c]) / length) for c in range(3)]\n    out.append('\\x1b['\n               '38;2;{rgb[2]};{rgb[1]};{rgb[0]};'\n               '48;2;{rgb[0]};{rgb[1]};{rgb[2]}mX\\x1b[m'.format(rgb=rgb))\nprint(''.join(out))\n```\n", "meta": {"hexsha": "3bf2feb86eaa5c70d38788dfe34307e811c28075", "size": 21081, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/code-cells.ipynb", "max_stars_repo_name": "vosjo/nbsphinx", "max_stars_repo_head_hexsha": "98005a9d6b331b7d6d14221539154df69f7ae51a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/code-cells.ipynb", "max_issues_repo_name": "vosjo/nbsphinx", "max_issues_repo_head_hexsha": "98005a9d6b331b7d6d14221539154df69f7ae51a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/code-cells.ipynb", "max_forks_repo_name": "vosjo/nbsphinx", "max_forks_repo_head_hexsha": "98005a9d6b331b7d6d14221539154df69f7ae51a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0071174377, "max_line_length": 315, "alphanum_fraction": 0.5460841516, "converted": true, "num_tokens": 3145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3812195803163617, "lm_q2_score": 0.10818895743752079, "lm_q1q2_score": 0.04124374894919639}}
{"text": "<div class='bar_title'></div>\n\n*Practical Data Science*\n\n# Feature Engineering\n\nNikolai Stein<br>\nChair of Information Systems and Management\n\nWinter Semester 19/20\n\n<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Introduction\" data-toc-modified-id=\"Introduction-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Introduction</a></span></li><li><span><a href=\"#Loading-the-Data\" data-toc-modified-id=\"Loading-the-Data-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Loading the Data</a></span></li><li><span><a href=\"#Select-Variables-and-Split-Dataset\" data-toc-modified-id=\"Select-Variables-and-Split-Dataset-3\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>Select Variables and Split Dataset</a></span></li><li><span><a href=\"#Feature-Engineering-on-Numeric-Data\" data-toc-modified-id=\"Feature-Engineering-on-Numeric-Data-4\"><span class=\"toc-item-num\">4&nbsp;&nbsp;</span>Feature Engineering on Numeric Data</a></span><ul class=\"toc-item\"><li><span><a href=\"#Preprocessing\" data-toc-modified-id=\"Preprocessing-4.1\"><span class=\"toc-item-num\">4.1&nbsp;&nbsp;</span>Preprocessing</a></span></li><li><span><a href=\"#Binarization\" data-toc-modified-id=\"Binarization-4.2\"><span class=\"toc-item-num\">4.2&nbsp;&nbsp;</span>Binarization</a></span></li><li><span><a href=\"#Binning\" data-toc-modified-id=\"Binning-4.3\"><span class=\"toc-item-num\">4.3&nbsp;&nbsp;</span>Binning</a></span></li><li><span><a href=\"#Statistical-Transformations\" data-toc-modified-id=\"Statistical-Transformations-4.4\"><span class=\"toc-item-num\">4.4&nbsp;&nbsp;</span>Statistical Transformations</a></span></li><li><span><a href=\"#Evaluation\" data-toc-modified-id=\"Evaluation-4.5\"><span class=\"toc-item-num\">4.5&nbsp;&nbsp;</span>Evaluation</a></span></li></ul></li><li><span><a href=\"#Feature-Engineering-on-Categorical-Data\" data-toc-modified-id=\"Feature-Engineering-on-Categorical-Data-5\"><span class=\"toc-item-num\">5&nbsp;&nbsp;</span>Feature Engineering on Categorical Data</a></span><ul class=\"toc-item\"><li><span><a href=\"#Label-and-One-Hot-Encoding\" data-toc-modified-id=\"Label-and-One-Hot-Encoding-5.1\"><span class=\"toc-item-num\">5.1&nbsp;&nbsp;</span>Label and One-Hot-Encoding</a></span></li><li><span><a href=\"#Count-Encodings\" data-toc-modified-id=\"Count-Encodings-5.2\"><span class=\"toc-item-num\">5.2&nbsp;&nbsp;</span>Count Encodings</a></span></li><li><span><a href=\"#Target-Encodings\" data-toc-modified-id=\"Target-Encodings-5.3\"><span class=\"toc-item-num\">5.3&nbsp;&nbsp;</span>Target Encodings</a></span></li><li><span><a href=\"#CatBoost-Encoding\" data-toc-modified-id=\"CatBoost-Encoding-5.4\"><span class=\"toc-item-num\">5.4&nbsp;&nbsp;</span>CatBoost Encoding</a></span></li><li><span><a href=\"#Warning\" data-toc-modified-id=\"Warning-5.5\"><span class=\"toc-item-num\">5.5&nbsp;&nbsp;</span>Warning</a></span></li></ul></li><li><span><a href=\"#Conclusion\" data-toc-modified-id=\"Conclusion-6\"><span class=\"toc-item-num\">6&nbsp;&nbsp;</span>Conclusion</a></span></li></ul></div>\n\n__Credits__\n\nParts of the material of this lecture are adopted from www.kaggle.com\n\n## Introduction\n\n**This lecture provides an overview on different feature engineering techniques.**\n\nStarting with a baseline dataset, we will\n\n- modify existing variables \n- add additional features to  our dataset \n- train a predictive model \n\n**Feature engineering** is an essential part of building a powerful predictive model. \n\nEach problem is domain specific and better features (suited to the problem) are often the deciding factor of the performance of your system. \n\nFeature Engineering requires experience as well as creativity and this is the reason **Data Scientists often spend the majority of their time** in the data preparation phase before modeling.\n\n_\"Coming up with features is difficult, time-consuming, requires expert knowledge. Applied machine learning is basically feature engineering.\"_\n\nProf. Andrew Ng.\n\n_\"Feature engineering is the process of transforming raw data into features that better represent the underlying problem to the predictive models, resulting in improved model accuracy on unseen data.\"_\n\nDr. Jason Brownlee\n\n_\"At the end of the day, some machine learning projects succeed and some fail. What makes the difference? Easily the most important factor is the features used.\"_\n\nProf. Pedro Domingos\n\n## Loading the Data\nThis week, we will work with a sample of the [adult dataset](https://archive.ics.uci.edu/ml/datasets/adult) which has some census information on individuals. We'll use it to train a model to predict whether salary is greater than \\$50k or not. Again, our first step is to load and familiarize ourself with the data. To this end, we can use the pandas library and load the dataset with the following commands:\n\n\n```python\nimport pandas as pd\n```\n\n\n```python\nfile_path = 'https://raw.githubusercontent.com/wi3jmu/PDS1920/master/Lecture/data/adult.csv'\nadult_data = pd.read_csv(file_path)\nadult_data\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>age</th>\n      <th>workclass</th>\n      <th>fnlwgt</th>\n      <th>education</th>\n      <th>education-num</th>\n      <th>marital-status</th>\n      <th>occupation</th>\n      <th>relationship</th>\n      <th>race</th>\n      <th>sex</th>\n      <th>capital-gain</th>\n      <th>capital-loss</th>\n      <th>hours-per-week</th>\n      <th>native-country</th>\n      <th>salary</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>49</td>\n      <td>Private</td>\n      <td>101320</td>\n      <td>Assoc-acdm</td>\n      <td>12.0</td>\n      <td>Married-civ-spouse</td>\n      <td>NaN</td>\n      <td>Wife</td>\n      <td>White</td>\n      <td>Female</td>\n      <td>0</td>\n      <td>1902</td>\n      <td>40</td>\n      <td>United-States</td>\n      <td>&gt;=50k</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>44</td>\n      <td>Private</td>\n      <td>236746</td>\n      <td>Masters</td>\n      <td>14.0</td>\n      <td>Divorced</td>\n      <td>Exec-managerial</td>\n      <td>Not-in-family</td>\n      <td>White</td>\n      <td>Male</td>\n      <td>10520</td>\n      <td>0</td>\n      <td>45</td>\n      <td>United-States</td>\n      <td>&gt;=50k</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>38</td>\n      <td>Private</td>\n      <td>96185</td>\n      <td>HS-grad</td>\n      <td>NaN</td>\n      <td>Divorced</td>\n      <td>NaN</td>\n      <td>Unmarried</td>\n      <td>Black</td>\n      <td>Female</td>\n      <td>0</td>\n      <td>0</td>\n      <td>32</td>\n      <td>United-States</td>\n      <td>&lt;50k</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>38</td>\n      <td>Self-emp-inc</td>\n      <td>112847</td>\n      <td>Prof-school</td>\n      <td>15.0</td>\n      <td>Married-civ-spouse</td>\n      <td>Prof-specialty</td>\n      <td>Husband</td>\n      <td>Asian-Pac-Islander</td>\n      <td>Male</td>\n      <td>0</td>\n      <td>0</td>\n      <td>40</td>\n      <td>United-States</td>\n      <td>&gt;=50k</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>42</td>\n      <td>Self-emp-not-inc</td>\n      <td>82297</td>\n      <td>7th-8th</td>\n      <td>NaN</td>\n      <td>Married-civ-spouse</td>\n      <td>Other-service</td>\n      <td>Wife</td>\n      <td>Black</td>\n      <td>Female</td>\n      <td>0</td>\n      <td>0</td>\n      <td>50</td>\n      <td>United-States</td>\n      <td>&lt;50k</td>\n    </tr>\n    <tr>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <td>32556</td>\n      <td>36</td>\n      <td>Private</td>\n      <td>297449</td>\n      <td>Bachelors</td>\n      <td>13.0</td>\n      <td>Divorced</td>\n      <td>Prof-specialty</td>\n      <td>Not-in-family</td>\n      <td>White</td>\n      <td>Male</td>\n      <td>14084</td>\n      <td>0</td>\n      <td>40</td>\n      <td>United-States</td>\n      <td>&gt;=50k</td>\n    </tr>\n    <tr>\n      <td>32557</td>\n      <td>23</td>\n      <td>?</td>\n      <td>123983</td>\n      <td>Bachelors</td>\n      <td>13.0</td>\n      <td>Never-married</td>\n      <td>?</td>\n      <td>Own-child</td>\n      <td>Other</td>\n      <td>Male</td>\n      <td>0</td>\n      <td>0</td>\n      <td>40</td>\n      <td>United-States</td>\n      <td>&lt;50k</td>\n    </tr>\n    <tr>\n      <td>32558</td>\n      <td>53</td>\n      <td>Private</td>\n      <td>157069</td>\n      <td>Assoc-acdm</td>\n      <td>12.0</td>\n      <td>Married-civ-spouse</td>\n      <td>Machine-op-inspct</td>\n      <td>Husband</td>\n      <td>White</td>\n      <td>Male</td>\n      <td>0</td>\n      <td>0</td>\n      <td>40</td>\n      <td>United-States</td>\n      <td>&gt;=50k</td>\n    </tr>\n    <tr>\n      <td>32559</td>\n      <td>32</td>\n      <td>Local-gov</td>\n      <td>217296</td>\n      <td>HS-grad</td>\n      <td>9.0</td>\n      <td>Married-civ-spouse</td>\n      <td>Transport-moving</td>\n      <td>Wife</td>\n      <td>White</td>\n      <td>Female</td>\n      <td>4064</td>\n      <td>0</td>\n      <td>22</td>\n      <td>United-States</td>\n      <td>&lt;50k</td>\n    </tr>\n    <tr>\n      <td>32560</td>\n      <td>26</td>\n      <td>Private</td>\n      <td>182308</td>\n      <td>Some-college</td>\n      <td>10.0</td>\n      <td>Married-civ-spouse</td>\n      <td>Prof-specialty</td>\n      <td>Husband</td>\n      <td>White</td>\n      <td>Male</td>\n      <td>0</td>\n      <td>0</td>\n      <td>40</td>\n      <td>United-States</td>\n      <td>&lt;50k</td>\n    </tr>\n  </tbody>\n</table>\n<p>32561 rows \u00d7 15 columns</p>\n</div>\n\n\n\n## Select Variables and Split Dataset\n\nBefore we start to engineer new features, we select the feature and target variables. \n\nThe (binary) variable ``salary`` describes if a person earns more or less that \\\\$50k. We replace the labels with numeric values (0: Salary < \\\\$50k, 1: Salary > \\\\$50k) and subsequently select it as our target variable y.\n\n\n```python\nadult_data = adult_data.assign(salary=(adult_data['salary']=='>=50k').astype(int))\ny = adult_data['salary']\n```\n\nThe remaining columns serve as our features X.\n\n\n```python\nX = adult_data.drop('salary', axis=1)\n```\n\nNext, we perform a train-test split to train and evaluate our machine learning models for the model validation.\n\n\n```python\nfrom sklearn.model_selection import train_test_split\n```\n\n\n```python\ntrain_X, val_X, train_y, val_y = train_test_split(X, y, random_state = 0)\n```\n\nNow we are ready to start preparing and enhancing our numerical and categorical features!\n\n## Feature Engineering on Numeric Data\n\nBy Numeric data we mean continuous data and not discrete data which is typically represented as categorical data. Integers and floats are the most common and widely used numeric data types for continuous numeric data. Even though numeric data can be directly fed into machine learning models, we still have to engineer and preprocess features which are relevant to the scenario, problem, domain and machine learning model.\n\nTo this end, we can distinguish between preprocessing and feature generation.\n\nTo work on our numeric features, we have to identify all numeric columns in our dataset:\n\n\n```python\nnumCols = [cname for cname in train_X.columns if train_X[cname].dtype != \"object\"]; numCols\n```\n\n\n\n\n    ['age',\n     'fnlwgt',\n     'education-num',\n     'capital-gain',\n     'capital-loss',\n     'hours-per-week']\n\n\n\nTo avoid problems with missing values we use a ``SimpleImputer`` for the numeric columns before we continue:\n\n\n```python\nfrom sklearn.impute import SimpleImputer\n\nsimple_imputer = SimpleImputer()\n\ntrain_X_num = pd.DataFrame(simple_imputer.fit_transform(train_X[numCols]), columns=numCols, index=train_X.index)\nval_X_num = pd.DataFrame(simple_imputer.fit_transform(val_X[numCols]), columns=numCols, index=val_X.index)\n```\n\n### Preprocessing\n\nOur dataset may contain attributes with a mixture of scales for various quantities. However, many machine learning methods require or at least are more effective if the data attributes have the same scale. \n\nFor example, ``capital gain`` and ``capital loss`` is measured in USD while age is measured in years in our dataset at hand.\n\nTo avoid having numeric values from different scales we can use two popular data scaling methods: normalization and standardization.\n\n#### Normalization\n\nNormalization refers to rescaling numeric attributes into the range 0 and 1. It is useful to scale the input attributes for a model that relies on the magnitude of values, such as distance measures used in k-nearest neighbors and in the preparation of coefficients in regression.\n\nUsing Scikit-learn's ``MinMaxScaler`` we can rescale an attribute according to the following formula:\n\n\n\\begin{equation}\n    X = \\frac{(X - min(X))}{(max(X) - min(X))}\n\\end{equation}\n\n\n```python\nfrom sklearn.preprocessing import MinMaxScaler\n\nscaler = MinMaxScaler()\n\ntrain_X_num_normalized = pd.DataFrame(scaler.fit_transform(train_X_num), \n                                      columns=train_X_num.columns, index=train_X_num.index)\nval_X_num_normalized = pd.DataFrame(scaler.transform(val_X_num), \n                                    columns=train_X_num.columns, index=val_X_num.index)\n\ntrain_X_num_normalized\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>age</th>\n      <th>fnlwgt</th>\n      <th>education-num</th>\n      <th>capital-gain</th>\n      <th>capital-loss</th>\n      <th>hours-per-week</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>26464</td>\n      <td>0.136986</td>\n      <td>0.215102</td>\n      <td>0.533333</td>\n      <td>0.00000</td>\n      <td>0.0</td>\n      <td>0.397959</td>\n    </tr>\n    <tr>\n      <td>16134</td>\n      <td>0.054795</td>\n      <td>0.118419</td>\n      <td>0.600000</td>\n      <td>0.00000</td>\n      <td>0.0</td>\n      <td>0.193878</td>\n    </tr>\n    <tr>\n      <td>4747</td>\n      <td>0.465753</td>\n      <td>0.038438</td>\n      <td>0.066667</td>\n      <td>0.00000</td>\n      <td>0.0</td>\n      <td>0.346939</td>\n    </tr>\n    <tr>\n      <td>8369</td>\n      <td>0.095890</td>\n      <td>0.128628</td>\n      <td>0.533333</td>\n      <td>0.00000</td>\n      <td>0.0</td>\n      <td>0.602041</td>\n    </tr>\n    <tr>\n      <td>5741</td>\n      <td>0.205479</td>\n      <td>0.064474</td>\n      <td>0.800000</td>\n      <td>0.00000</td>\n      <td>0.0</td>\n      <td>0.397959</td>\n    </tr>\n    <tr>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <td>13123</td>\n      <td>0.041096</td>\n      <td>0.093175</td>\n      <td>0.600000</td>\n      <td>0.00000</td>\n      <td>0.0</td>\n      <td>0.244898</td>\n    </tr>\n    <tr>\n      <td>19648</td>\n      <td>0.205479</td>\n      <td>0.176642</td>\n      <td>0.733333</td>\n      <td>0.00000</td>\n      <td>0.0</td>\n      <td>0.397959</td>\n    </tr>\n    <tr>\n      <td>9845</td>\n      <td>0.315068</td>\n      <td>0.039635</td>\n      <td>0.000000</td>\n      <td>0.00000</td>\n      <td>0.0</td>\n      <td>0.193878</td>\n    </tr>\n    <tr>\n      <td>10799</td>\n      <td>0.150685</td>\n      <td>0.011654</td>\n      <td>0.533333</td>\n      <td>0.00000</td>\n      <td>0.0</td>\n      <td>0.397959</td>\n    </tr>\n    <tr>\n      <td>2732</td>\n      <td>0.109589</td>\n      <td>0.142264</td>\n      <td>0.533333</td>\n      <td>0.03325</td>\n      <td>0.0</td>\n      <td>0.448980</td>\n    </tr>\n  </tbody>\n</table>\n<p>24420 rows \u00d7 6 columns</p>\n</div>\n\n\n\n#### Standardization\n\nIn contrast to normalization, we could also use standardization for our numerical variables. In this context, standardization refers to shifting the distribution of each attribute to have a mean of zero and a standard deviation of one. It is useful to standardize attributes for a model that relies on the distribution of attributes such as Gaussian processes.\n\nUsing Scikit-learn's ```StandardScaler``` we can rescale an attribute according to the following formula:\n\n\n\\begin{equation}\n    X = \\frac{(X - mean(X))}{\\sqrt{var(X)}}\n\\end{equation}\n\n\n```python\nfrom sklearn.preprocessing import StandardScaler\n\nscaler = StandardScaler()\n\ntrain_X_num_standardized = pd.DataFrame(scaler.fit_transform(train_X_num), \n                                        columns=train_X_num.columns, index=train_X_num.index)\nval_X_num_standardized = pd.DataFrame(scaler.transform(val_X_num), \n                                      columns=train_X_num.columns, index=val_X_num.index)\n\ntrain_X_num_standardized.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>age</th>\n      <th>fnlwgt</th>\n      <th>education-num</th>\n      <th>capital-gain</th>\n      <th>capital-loss</th>\n      <th>hours-per-week</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>26464</td>\n      <td>-0.853017</td>\n      <td>1.316410</td>\n      <td>-0.420746</td>\n      <td>-0.146391</td>\n      <td>-0.217388</td>\n      <td>-0.036400</td>\n    </tr>\n    <tr>\n      <td>16134</td>\n      <td>-1.292554</td>\n      <td>-0.027373</td>\n      <td>-0.029346</td>\n      <td>-0.146391</td>\n      <td>-0.217388</td>\n      <td>-1.652429</td>\n    </tr>\n    <tr>\n      <td>4747</td>\n      <td>0.905131</td>\n      <td>-1.139029</td>\n      <td>-3.160546</td>\n      <td>-0.146391</td>\n      <td>-0.217388</td>\n      <td>-0.440408</td>\n    </tr>\n    <tr>\n      <td>8369</td>\n      <td>-1.072786</td>\n      <td>0.114522</td>\n      <td>-0.420746</td>\n      <td>-0.146391</td>\n      <td>-0.217388</td>\n      <td>1.579628</td>\n    </tr>\n    <tr>\n      <td>5741</td>\n      <td>-0.486737</td>\n      <td>-0.777155</td>\n      <td>1.144853</td>\n      <td>-0.146391</td>\n      <td>-0.217388</td>\n      <td>-0.036400</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n#### Summary\n\nData rescaling is an important part of data preparation before applying machine learning algorithms. However, it is hard to know whether normalization or standardization of the data will improve the performance of a predictive model in advance. \n\nA good tip for a practical application is to create rescaled copies of your dataset and evaluate them against each other. This process can quickly show which rescaling method will improve your selected models in the problem at hand.\n\n### Binarization\n\nFor some problems raw frequencies or counts may not be relevant for building a model. In these cases it is only relevant if a numeric value exceeds a specific threshold (e.g. a person is at least 40 years old). Hence we do not require the number of times the action was performed but only a binary feature.\n\nWe can binarize a feature using Scikit-learn's ``Binarizer`` function (Note that we use the raw dataset for this example - clearly we could normalize or standardize the dataframe afterwards):\n\n\n```python\nfrom sklearn.preprocessing import Binarizer\n\ntrain_X_binary_age = train_X_num.copy()\nval_X_binary_age = val_X_num.copy()\n\nbinarizer = Binarizer(threshold=40)\n\ntrain_X_binary_age['40Plus'] = binarizer.transform([train_X_binary_age['age']])[0]\nval_X_binary_age['40Plus'] = binarizer.transform([val_X_binary_age['age']])[0]\n\ntrain_X_binary_age.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>age</th>\n      <th>fnlwgt</th>\n      <th>education-num</th>\n      <th>capital-gain</th>\n      <th>capital-loss</th>\n      <th>hours-per-week</th>\n      <th>40Plus</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>26464</td>\n      <td>27.0</td>\n      <td>329005.0</td>\n      <td>9.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>40.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <td>16134</td>\n      <td>21.0</td>\n      <td>186648.0</td>\n      <td>10.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>20.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <td>4747</td>\n      <td>51.0</td>\n      <td>68882.0</td>\n      <td>2.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>35.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <td>8369</td>\n      <td>24.0</td>\n      <td>201680.0</td>\n      <td>9.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>60.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <td>5741</td>\n      <td>32.0</td>\n      <td>107218.0</td>\n      <td>13.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>40.0</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### Binning\n\nThe problem of working with raw, numeric features is that often the distribution of values in these features will be skewed. This signifies that some values will occur quite frequently while some will be quite rare. Hence there are strategies to deal with this, which include binning. \n\nBinning is used for transforming continuous numeric features into discrete ones. These discrete values can be interpreted as categories or bins into which the raw values are grouped into. Each group represents a specific degree of intensity and hence a specific range of continuous numeric values fall into it.\n\nLet's again use the age variable to perform two different types of binning.\n\n#### Fixed-Width Binning\n\nIn fixed-width binning, specific fixed widths for each bin are defined by the user. Each bin has a fixed range of values which should be assigned to that bin on the basis of some domain knowledge.\n\nWe can use Pandas ```cut``` function to bin the age into predefined groups and assign labels:\n\n\n```python\ntrain_X_bin_age = train_X_num.copy()\nval_X_bin_age = val_X_num.copy()\n\nbin_ranges = [0, 25, 60, 999]\nbin_labels = [0, 1, 2]\n\ntrain_X_bin_age['AgeBinned'] = pd.cut(train_X_bin_age['age'], \n                                      bins=bin_ranges, labels=bin_labels)\nval_X_bin_age['AgeBinned'] = pd.cut(val_X_bin_age['age'], \n                                    bins=bin_ranges, labels=bin_labels)\n\ntrain_X_bin_age.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>age</th>\n      <th>fnlwgt</th>\n      <th>education-num</th>\n      <th>capital-gain</th>\n      <th>capital-loss</th>\n      <th>hours-per-week</th>\n      <th>AgeBinned</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>26464</td>\n      <td>27.0</td>\n      <td>329005.0</td>\n      <td>9.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>40.0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <td>16134</td>\n      <td>21.0</td>\n      <td>186648.0</td>\n      <td>10.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>20.0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <td>4747</td>\n      <td>51.0</td>\n      <td>68882.0</td>\n      <td>2.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>35.0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <td>8369</td>\n      <td>24.0</td>\n      <td>201680.0</td>\n      <td>9.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>60.0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <td>5741</td>\n      <td>32.0</td>\n      <td>107218.0</td>\n      <td>13.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>40.0</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n#### Adaptive Binning\n\nThe major drawback in using fixed-width binning is unbalanced bin sizes. As we manually decide the bin ranges, we can end up with irregular bins which are not uniform based on the number of data points. Some bins (such as \"young (0)\" and \"old (2)\") might be sparsely populated while some (such as \"medium (1)\") are densely populated.\n\nTo overcome this issues we can use adaptive binning based on the distribution of the data.\n\nTo cut the space into equal partitions we can use the quantiles as cut-points:\n\n\n```python\nquantile_list = [0, 0.33, 0.66, 1]\nquantile_labels = [0, 1, 2]\n\ntrain_X_bin_age['AgeBinnedAdaptive'] = pd.qcut(train_X_bin_age['age'], \n                                               q=quantile_list, labels=quantile_labels)\nval_X_bin_age['AgeBinnedAdaptive'] = pd.qcut(val_X_bin_age['age'], \n                                             q=quantile_list, labels=quantile_labels)\n\ntrain_X_bin_age.head(5)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>age</th>\n      <th>fnlwgt</th>\n      <th>education-num</th>\n      <th>capital-gain</th>\n      <th>capital-loss</th>\n      <th>hours-per-week</th>\n      <th>AgeBinned</th>\n      <th>AgeBinnedAdaptive</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>26464</td>\n      <td>27.0</td>\n      <td>329005.0</td>\n      <td>9.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>40.0</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <td>16134</td>\n      <td>21.0</td>\n      <td>186648.0</td>\n      <td>10.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>20.0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <td>4747</td>\n      <td>51.0</td>\n      <td>68882.0</td>\n      <td>2.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>35.0</td>\n      <td>1</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <td>8369</td>\n      <td>24.0</td>\n      <td>201680.0</td>\n      <td>9.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>60.0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <td>5741</td>\n      <td>32.0</td>\n      <td>107218.0</td>\n      <td>13.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>40.0</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### Statistical Transformations\n\nMany variables, such as ``capital-gain`` or ``fnlwgt`` (sampling weight) span several orders of magnitude. While the vast majority of persons has very small capital-gains, a few people have very high gains. To work with such skewed variables we can use the log transformation. \n\nLog transforms are useful when applied to skewed distributions as they tend to expand the values which fall in the range of lower magnitudes and tend to compress or reduce the values which fall in the range of higher magnitudes. This tends to make the skewed distribution as normal-like as possible.\n\n\n```python\nimport numpy as np\n\ntrain_X_logGains = train_X_num.copy()\nval_X_logGains = val_X_num.copy()\n\ntrain_X_logGains['logfnlwgt'] = np.log1p(train_X_logGains['fnlwgt'])\nval_X_logGains['logfnlwgt'] = np.log1p(val_X_logGains['fnlwgt'])\n```\n\nWe can see this effect plotting both histograms:\n\n\n```python\n%matplotlib inline\ntrain_X_logGains[['fnlwgt', 'logfnlwgt']].hist();\n```\n\n### Evaluation\n\nWe can train support vector machines (``SVC``) using the different datasets and feature engineering techniques to evaluate their impact on the model performance. Note that we could (and should) combine these techniques to train powerful models and apply them in real-world problems.\n\n\n```python\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score\n\ndef score_dataset(X_train, X_valid, y_train, y_valid):\n    model = SVC(gamma='auto', random_state=0)\n    model.fit(X_train, y_train)\n    preds = model.predict(X_valid)\n    return accuracy_score(y_valid, preds)\n```\n\n\n```python\nprint(\"Raw Features: {}\".\n      format(score_dataset(train_X_num, val_X_num, train_y, val_y)))\nprint(\"Normalized Features: {}\".\n      format(score_dataset(train_X_num_normalized, val_X_num_normalized, train_y, val_y)))\nprint(\"Standardized Features: {}\".\n      format(score_dataset(train_X_num_standardized, val_X_num_standardized, train_y, val_y)))\nprint(\"Binary Age: {}\".format(score_dataset(train_X_binary_age, val_X_binary_age, train_y, val_y)))\nprint(\"Binned Age: {}\".format(score_dataset(train_X_bin_age, val_X_bin_age, train_y, val_y)))\nprint(\"Log FNLWGT: {}\".format(score_dataset(train_X_logGains, val_X_logGains, train_y, val_y)))\n```\n\n    Raw Features: 0.7558039552880481\n    Normalized Features: 0.800761577201818\n    Standardized Features: 0.8204151824100233\n    Binary Age: 0.7560496253531507\n    Binned Age: 0.7560496253531507\n    Log FNLWGT: 0.7560496253531507\n\n\n## Feature Engineering on Categorical Data\n\nIn contrast to continuous numeric data we mean discrete values which belong to a specific finite set of categories or classes when we talk about categorical data. These discrete values can be text or numeric in nature and there are two major classes of categorical data, nominal and ordinal.\n\nWhile a lot of advancements have been made in state of the art machine learning frameworks to accept categorical data types like text labels. Typically any standard workflow in feature engineering involves some form of transformation of these categorical values into numeric labels and then applying some encoding scheme on these values.\n\n### Label and One-Hot-Encoding\n\nLast week, we already talked about label and one-hot-encoding to prepare our categorical features for machine learning models. To get started, we will impute missing values and encode all categorical features using the ``LabelEncoder``:\n\n\n```python\nfrom sklearn.preprocessing import LabelEncoder\n```\n\n\n```python\ncatCols = [cname for cname in train_X.columns if train_X[cname].dtype == \"object\"]\n\ntrain_X_cat = train_X[catCols].copy()\nval_X_cat = val_X[catCols].copy()\n\nsimple_imputer = SimpleImputer(strategy='most_frequent')\n\ntrain_X_labelenc = pd.DataFrame(simple_imputer.fit_transform(train_X_cat), columns=catCols)\nval_X_labelenc = pd.DataFrame(simple_imputer.fit_transform(val_X_cat), columns=catCols)\n\nlabel_encoder = LabelEncoder()\nfor col in catCols:\n    train_X_labelenc[col] = label_encoder.fit_transform(train_X_labelenc[col])\n    val_X_labelenc[col] = label_encoder.transform(val_X_labelenc[col])\n    \ntrain_X_labelenc.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>workclass</th>\n      <th>education</th>\n      <th>marital-status</th>\n      <th>occupation</th>\n      <th>relationship</th>\n      <th>race</th>\n      <th>sex</th>\n      <th>native-country</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>4</td>\n      <td>11</td>\n      <td>4</td>\n      <td>3</td>\n      <td>3</td>\n      <td>4</td>\n      <td>1</td>\n      <td>39</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>4</td>\n      <td>15</td>\n      <td>4</td>\n      <td>8</td>\n      <td>3</td>\n      <td>4</td>\n      <td>1</td>\n      <td>39</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>4</td>\n      <td>3</td>\n      <td>6</td>\n      <td>8</td>\n      <td>4</td>\n      <td>4</td>\n      <td>0</td>\n      <td>32</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>4</td>\n      <td>11</td>\n      <td>4</td>\n      <td>1</td>\n      <td>4</td>\n      <td>4</td>\n      <td>1</td>\n      <td>39</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>4</td>\n      <td>9</td>\n      <td>4</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>39</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nAgain, we will use a helper function to evaluate the performance of our models. This time, we will rely on a random forest model.\n\n\n```python\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score\n\ndef score_dataset(X_train, X_valid, y_train, y_valid):\n    model = RandomForestClassifier(n_estimators=100, random_state=0)\n    model.fit(X_train, y_train)\n    preds = model.predict(X_valid)\n    return accuracy_score(y_valid, preds)\n```\n\nTo evaluate the model we combine the raw numerical data and the encoded categorical variables.\n\n\n```python\ntrain_X_label_num = train_X_num.join(train_X_labelenc.add_suffix(\"_labelenc\"))\nval_X_label_num = val_X_num.join(val_X_labelenc.add_suffix(\"_labelenc\"))\n\n\nprint(\"Label encoded categorical + raw numeric: {}\".\n      format(score_dataset(train_X_labelenc, val_X_labelenc, train_y, val_y)))\n```\n\n    Label encoded categorical + raw numeric: 0.8249600786144208\n\n\n### Count Encodings\n\nWhile label and one-hot encoding often yield good results, there are also a lot of other (more complex) techniques to encode categorical variables. The package [categorical-encoding](https://github.com/scikit-learn-contrib/categorical-encoding) offers implementations of many different techniques.\n\nOne prominent variant is called count encoding. Count encoding replaces each categorical value with the number of times it appears in the dataset. For example, if the value \"USA\" occures 50 times in the country feature, then each \"USA\" would be replaced with the number 50.\n\n\n```python\n!pip install category_encoders\n```\n\nor\n\n\n```python\n!conda install -c conda-forge category_encoders -y\n```\n\n\n```python\nfrom category_encoders import CountEncoder\n\ncount_encoder = CountEncoder(handle_unknown=0, handle_missing='count')\n\ntrain_X_countenc = count_encoder.fit_transform(train_X_cat)\nval_X_countenc = count_encoder.transform(val_X_cat)\n\ntrain_X_count_num = train_X_num.join(train_X_countenc.add_suffix(\"_countenc\"))\nval_X_count_num = val_X_num.join(val_X_countenc.add_suffix(\"_countenc\"))\n\nprint(\"Count encoded categorical + raw numeric: {}\".\n      format(score_dataset(train_X_count_num, val_X_count_num, train_y, val_y)))\n```\n\n    Count encoded categorical + raw numeric: 0.8522294558408058\n\n\n### Target Encodings\n\nTarget encoding is another advanced (but sometimes dangerous) approach to encode categorical features. It replaces a categorical value with the average value of the target for that value of the feature. \n\nFor example, given the country value \"GER\", you'd calculate the average outcome for all the rows with country == 'GER'. This value is often blended with the target probability over the entire dataset to reduce the variance of values with few occurences.\n\nThis technique uses the targets to create new features. So including the validation or test data in the target encodings would be a form of target leakage. Instead, you should learn the target encodings from the training dataset only and apply it to the other datasets (as we did with all other encoding methods).\n\n\n```python\nfrom category_encoders import TargetEncoder\n\ntarget_encoder = TargetEncoder()\n\ntrain_X_targetenc = target_encoder.fit_transform(train_X_cat, train_y)\nval_X_targetenc = target_encoder.transform(val_X_cat)\n\ntrain_X_target_num = train_X_num.join(train_X_targetenc.add_suffix(\"_targetenc\"))\nval_X_target_num = val_X_num.join(val_X_targetenc.add_suffix(\"_targetenc\"))\n\nprint(\"Target encoded categorical + raw numeric: {}\".\n      format(score_dataset(train_X_target_num, val_X_target_num, train_y, val_y)))\n```\n\n    Target encoded categorical + raw numeric: 0.8534578061663186\n\n\n### CatBoost Encoding\n\nFinally, we'll look at CatBoost encoding. This is similar to target encoding in that it's based on the target probablity for a given value. However with CatBoost, for each row, the target probability is calculated only from the rows before it.\n\n\n```python\nfrom category_encoders import CatBoostEncoder\n\ncatboost_encoder = CatBoostEncoder()\n\ntrain_X_catboostenc = catboost_encoder.fit_transform(train_X_cat, train_y)\nval_X_catboostenc = catboost_encoder.transform(val_X_cat)\n\ntrain_X_catboost_num = train_X_num.join(train_X_catboostenc.add_suffix(\"_targetenc\"))\nval_X_catboost_num = val_X_num.join(val_X_catboostenc.add_suffix(\"_targetenc\"))\n\nprint(\"CatBoost encoded categorical + raw numeric: {}\".\n      format(score_dataset(train_X_catboost_num, val_X_catboost_num, train_y, val_y)))\n```\n\n    CatBoost encoded categorical + raw numeric: 0.8637759489006265\n\n\n### Warning\n\nTarget encoding is a powerful but dangerous way to improve on your machine learning methods. \n\nAdvantages: \n* Compact transformation of categorical variables\n* Powerful basis for feature engineering\n\nDisadvantages:\n* Careful validation is required to avoid overfitting\n* Significant performance improvements only on some datasets\n\n## Conclusion\n\nToday, we have seen a variety of ways to encode numerical and categorical features to improve the performance of our machine learning models. To try even more encoding methods you can try the implementations in the categorical-encoding package on [github](https://github.com/scikit-learn-contrib/categorical-encoding).\n\nWhile the approaches we have talked about today have the potential to create powerful models, they require a lot of manual tuning and testing. \n", "meta": {"hexsha": "e2b3fd336395c8adb6150fcf9aa349c20491fcd1", "size": 81221, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lecture/04_Feature_Engineering.ipynb", "max_stars_repo_name": "SchmittYannic/PDS1920", "max_stars_repo_head_hexsha": "dabc2d7c98fe98792cf2a1a79d35f3ee5d013e70", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-17T10:11:02.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-17T10:12:11.000Z", "max_issues_repo_path": "Lecture/04_Feature_Engineering.ipynb", "max_issues_repo_name": "SchmittYannic/PDS1920", "max_issues_repo_head_hexsha": "dabc2d7c98fe98792cf2a1a79d35f3ee5d013e70", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-11-05T09:08:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-05T09:08:11.000Z", "max_forks_repo_path": "Lecture/04_Feature_Engineering.ipynb", "max_forks_repo_name": "SchmittYannic/PDS1920", "max_forks_repo_head_hexsha": "dabc2d7c98fe98792cf2a1a79d35f3ee5d013e70", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-10-16T20:38:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-20T22:56:12.000Z", "avg_line_length": 37.9360112097, "max_line_length": 9784, "alphanum_fraction": 0.5252951823, "converted": true, "num_tokens": 11297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.13117323395124272, "lm_q1q2_score": 0.04119502561072564}}
{"text": "<a id='logbook'></a>\n# Report\nThis is the notebook that created the report.\n\n\n```python\n%matplotlib inline\n%load_ext autoreload\n%autoreload 2\n\nimport warnings\nwarnings.filterwarnings('ignore')\n```\n\n    Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 462 ('figure.figsize   : 5, 3   ## figure size in inches')\n    Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 463 ('figure.dpi       : 100        ## figure dots per inch')\n\n\n\n```python\nimport os\nimport matplotlib.pyplot as plt\nimport pandas as pd\npd.options.display.max_rows = 999\npd.options.display.max_columns = 999\npd.set_option(\"display.max_columns\", None)\nimport sympy as sp\n\nimport pandas as pd\nimport numpy as np\n\nif os.name == 'nt':\n    plt.style.use('paper.mplstyle')  # Windows\n\nimport statsmodels.api as sm\nfrom statsmodels.sandbox.regression.predstd import wls_prediction_std\nfrom sklearn.metrics import r2_score\nfrom scipy.integrate import solve_ivp\nimport seaborn as sns\n\nfrom copy import deepcopy\nimport sys\nsys.path.append('../../')\nfrom src.notebook_to_latex import Equation, equation_dict\nfrom src import equations,symbols\nimport reports.paper_writing\nfrom src.df_to_latex import LateXTable\nfrom src.data.helpers import load\nfrom src.visualization import rolldecay\n\n## Examples:\n\n```\n\n    Duplicate key in file 'paper.mplstyle', line 462 ('figure.figsize   : 5, 3   ## figure size in inches')\n    Duplicate key in file 'paper.mplstyle', line 463 ('figure.dpi       : 100        ## figure dots per inch')\n\n\n\n```python\nfrom IPython.display import set_matplotlib_formats\nset_matplotlib_formats('pdf','png')\n\nfrom IPython.display import HTML, Markdown, Image\nfrom src.df_to_latex import LateXTable\n```\n\n# Abstract\nShort abstract of report\n\n# Introduction\n\n<a id='fig_rolldecay_example>'></a>\n\n\n```python\nfig,ax=plt.subplots()\ndf = pd.DataFrame(data=np.random.normal(size=(1000,2)))\ndf.plot(ax=ax);\n```\n\nThe oscillating motion can be described by a spring-mass-damper system as seen in Fig.[(below)](#fig_spring_mass_damper).\n\n<a id=\"fig_spring_mass_damper\"></a>\n\n\n```python\nImage('../figures/220px-Mass_spring_damper.svg.png')\n```\n\nThis system can me described as the following equation [(below)](#eq_equation1):\n\n<a id=\"eq_equation1\"></a>\n\n\n```python\neq = r'$E=m \\dot c^2 $'\nEquation(eq, label='equation1')\n```\n\n\n\n\n$\\displaystyle \n\\begin{equation}\n$E=m \\dot c^2 $\n\\label{eq:equation1}\n\\end{equation}\n$\n\n\n\n\n```python\nA,r = sp.symbols('A r')\neq = sp.Eq(A,\n          r**2*sp.pi)\nEquation(eq, label='equation2')\n```\n\n\n\n\n$\\displaystyle \n\\begin{equation}\nA = \\pi r^{2}\n\\label{eq:equation2}\n\\end{equation}\n$\n\n\n\n# Data\nThe data used in this study is described in Tab.[(below)](#tab_data_files). There is one result with a pure FNPF simulation at 0 knots. For model test results, two tests are available at 0 knots and one test at 15.5 knots. There is also a result at 15.5 with a hybrid method, where semi empirical viscosity has been injected into the FNPF calculations.\n\n<a id=\"tab_data_files\"></a>\n\n\n```python\ncontent = pd.read_csv('../../data/external/content.csv', sep=';')\ntable_parameters = content.round(decimals=3)\ncontent.set_index('file', inplace=True)\n\nrename = {}\nunits = {\n    'Ship speed' : r'$[kts]$',\n}\n\ntable_parameters['data file'] = table_parameters['data file'].apply(lambda x : x.replace('_',r' '))\n\n\nlt = LateXTable(table_parameters, units=units, rename=rename, caption='Data files', label='data_files')\nlt\n```\n\n\n\n\n<table><tr><td>file</td><td>data file</td><td>Ship speed</td><td>Method</td></tr><tr><td></td><td></td><td>$[kts]$</td><td></td></tr><tr><td>1</td><td>fnpf kvlcc2 rolldecay 0kn.csv</td><td>0.0</td><td>FNPF</td></tr><tr><td>2</td><td>model test 21337.csv</td><td>0.0</td><td>model test</td></tr><tr><td>3</td><td>model test 21338.csv</td><td>0.0</td><td>model test</td></tr><tr><td>4</td><td>model test 21340.csv</td><td>15.5</td><td>model test</td></tr><tr><td>5</td><td>fnpf kvlcc2 rolldecay 15-5kn ikeda dev.csv</td><td>15.5</td><td>hybrid</td></tr></table>\n\n\n\n# Analysis\n\n# Conclusions\n  \n\n\n\n\n# References\n<div class=\"cite2c-biblio\"></div>\n", "meta": {"hexsha": "843b7f944666b7f6524629eeaa5fe29335dd29fb", "size": 261768, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "reports/report/.ipynb_checkpoints/01.1.report-checkpoint.ipynb", "max_stars_repo_name": "martinlarsalbert/project", "max_stars_repo_head_hexsha": "a52368f8640374a910226b7a656feb16b1808cbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reports/report/.ipynb_checkpoints/01.1.report-checkpoint.ipynb", "max_issues_repo_name": "martinlarsalbert/project", "max_issues_repo_head_hexsha": "a52368f8640374a910226b7a656feb16b1808cbb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reports/report/.ipynb_checkpoints/01.1.report-checkpoint.ipynb", "max_forks_repo_name": "martinlarsalbert/project", "max_forks_repo_head_hexsha": "a52368f8640374a910226b7a656feb16b1808cbb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 226.4429065744, "max_line_length": 154998, "alphanum_fraction": 0.9096795636, "converted": true, "num_tokens": 1216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.10087862948789175, "lm_q1q2_score": 0.041091235141276584}}
{"text": "\n\n<style type=\"text/css\">\n  div#preloader { position: fixed;\n      left: 0;\n      top: 0;\n      z-index: 999;\n      width: 100%;\n      height: 100%;\n      overflow: visible;\n      background: #fff url('http://preloaders.net/preloaders/720/Moving%20line.gif') no-repeat center center;\n  }\n\n</style>\n\n<div id=\"preloader\"></div>\n\n<table width=60% >\n    <tr style=\"background-color: white;\">\n        <td></td>\n<!--         <td></td> -->\n    </tr>\n</table>\n\n---\n\n\n\n---\n\n<br>\n\n<center> <h1> Quantum teleportation </h1></center>\n\n<div class=\"alert alert-info\">\n\u201cA trick that quantum magicians use to produce phenomena that cannot be imitated by classical magicians.\u201d - A. Peres\n</div>\n\nTo get a feel for how Strawberry Fields works, let's walk through an example of quantum teleportation.\n\n\n## Background info\nQuantum teleportation is the reliable transfer of an unknown quantum state across spatially separated qubits or qumodes, through the use of a classical transmission channel and quantum entanglement. Considered a fundamental quantum information protocol, it has applications ranging from quantum communication to enabling distributed information processing in quantum computation.\n\nIn general, all quantum teleportation circuits work on the same basic principle. Two distant observers, Alice and Bob, share a maximally entangled quantum state (in discrete variables, any one of the four Bell states; or in CV, a maximally entangled state for a fixed energy), and have access to a classical communication channel. Alice, in possession of an unknown state which she wishes to transport to Bob, makes a joint measurement of the unknown state and her half of the entangled state, by projecting onto the Bell basis. By transmitting the results of her measurement to Bob, Bob is then able to transform his half of the entangled state to an accurate replica of the original unknown state, by performing a conditional phase flip (for qubits) or displacement (for qumodes).\n\n## The teleportation circuit\n\n\n\n$$\\newcommand{ket}[1]{\\left|#1\\right\\rangle}$$\n\n* Here, qumodes $q_1$ and $q_2$ are initially prepared as highly squeezed vacuum states in momentum and position space respectively. We do this by highly squeezing these two qumodes in the phase space:\n\n\\begin{align}\n&\\ket{0}_x \\approx S(2)\\ket{0}\\\\\n&\\ket{0}_p \\approx S(-2) \\ket{0}\n\\end{align}\n\n\n* They are then maximally entangled by a 50-50 beamsplitter. This is a beamsplitter with parameters $\\theta=\\pi/4$, $\\phi=0$.\n\n\n\n* These two qumodes are now spatially separated, with $\\ket{q_1}$ held by Alice, and $\\ket{q_2}$ held by Bob, with the two connected via the classical communication channels $c_0$ and $c_1$.\n\n\n* To teleport her unknown state $\\ket{\\psi}$ to Bob, Alice now performs a projective measurement of her entire system onto the maximally entangled basis states. This is done by entangling $\\ket{\\psi}$ and $\\ket{q_1}$ via another 50-50 beamsplitter, before performing two homodyne measurements, in the $x$ and $p$ quadratures respectively. The two resulting measurements are referred to as $m_1$ and $m_2$.\n\n\n* The results of these measurements are then transmitted to Bob, who performs both a position displacement (conditional on the $x$ measurement) using a $X$ gate, and a momentum displacement (conditional on the $p$ measurement) using a $Z$ gate, to recover exactly the transmitted state $\\ket{\\psi}$. In particular, Bob has to make the following displacements:\n\n\\begin{align}\nZ\\left(-\\sqrt{2}m_2\\right)X\\left(\\sqrt{2}m_1\\right)\\ket{q_2}\n\\end{align}\n\n## Importing Strawberry Fields\n\nWe import the Strawberry Fields, as well as all quantum operations, using the following commands:\n\n\n```python\nimport strawberryfields as sf\nfrom strawberryfields.ops import *\n```\n\nThe first import statement imports Strawberry Fields as sf, allowing us to access the engine and backends. The second import statement imports all available CV gates into the global namespace.\n\nIn addition, we will also need some utilities from the `utils` subpackage, a module containing Strawberry Fields utilities and extensions. Finally, we import $\\pi$ and the square root from NumPy so that we can pass angle parameters to gates such as beamsplitters, and perform some custom classical processing.\n\n\n```python\nfrom strawberryfields.utils import scale\nfrom numpy import pi, sqrt\n```\n\n\n<div class=\"alert alert-success\" style=\"border: 0px; border-left: 3px solid #119a68; color: black; background-color: #daf0e9\">\n<p style=\"color: #119a68;\">**Available CV gates**</p>\n\nCheck out our <a href=\"https://strawberryfields.readthedocs.io/en/stable/op_conventions.html\">documentation</a> to see the available CV gates, states, measurements, and other operations available in Strawberry Fields.\n</div>\n\n\n## Program initialization\n\nIn Strawberry Fields, a quantum computation (or quantum circuit) are encapsulatd in a `Program` object, which has the following syntax:\n\n    prog = sf.Program(num_subsystems)\n\nwhere\n\n* `num_subsystems` (*int*) is the number of modes we want to initialize in our quantum register.\n\nThis command will create an empty program, ready to be populated with various operations that make up a quantum computation.\n\n\n```python\nprog = sf.Program(3)\n```\n\n## Circuit construction\n\nIn Strawberry Fields, circuit construction *always* occurs within a `Program` context. Inside this context, operations are applied using the syntax\n\n```python3\nwith prog.context as q:\n    Operation(arguments) | (sequence of qumodes within q)\n```\n\nFor example, to apply prepare a squeezed state, followed by a beamsplitter, we can write\n\n```python3\nwith prog.context as q:\n    Squeezed(0.5) | q[0]\n    BSgate(pi/4, 0) | (q[0], q[1])\n```\n\nSome operations in Strawberry Fields apply to one mode, and some apply to two. Be sure to consult the documentation to double check the operation arguments, and to see how many qumodes they act on.\n\n<div class=\"alert alert-info\" style=\"border: 0px; border-left: 3px solid #31708f; color: black; background-color: #d9edf7\">\n<p style=\"color: #31708f;\">**Exercise**</p>\n\nThe cell below corresponding to the teleportation circuit is partially complete. Using the above, and referring to the docs, fill in the cell below to finish constructing the teleportation circuit.\n</div>\n\n\n\n\n```python\nwith prog.context as q:\n    # prepare the initial states\n    Coherent(1+0.5j) | q[0]  # This is the state we will teleport\n    Sgate(-2) | q[1]\n    Sgate(2) | q[2]\n    \n    # apply the gates\n    BSgate(pi/4, 0) | (q[1], q[2])  # a 50-50 beamsplitter\n    BSgate(pi/4, 0) | (q[0], q[1])  # a 50-50 beamsplitter\n    \n    # perform the homodyne measurements\n    MeasureX | q[0]\n    MeasureP | q[1]    \n    \n    # displacement gates conditioned on the measurements\n    Xgate(scale(q[0], sqrt(2))) | q[2]\n    Zgate(scale(q[1], sqrt(2))) | q[2]\n```\n\nA couple of things to note:\n\n* **Operations must be applied in temporal order.** Different operation orderings can result in the same quantum circuit, providing the operations do not apply sequentially to the same mode.\n\n\n* **Gates are standard Python objects, and can be treated as such.** In this case, since both beamsplitters use the same parameters, a single instance can be created and stored under variable BS.\n\n\n* **The results of measured modes are passed to gates simply by passing the measured mode as an argument.** In order to perform additional classical processing to the measured mode, we can use the basic classical processing functions available in `strawberryfields.utils`; here we used the `scale()` function.\n\n\n## Running the engine\n\nOnce the circuit is constructed, you can execute the program using an `Engine` object. The Engine is responsible for sending the commands from your circuit to be executed on a particular backend. Engines are linked to a particular backend when they are created:\n\n```python3\n    eng = sf.Engine(backend, backend_options)\n```\nHere `backend` is a string representing the Strawberry Fields backend we wish to use; we have the choice of two Fock basis backends, the NumPy based (`'fock'`) and Tensorflow (`'tf'`), and one Gaussian representation backend (`'gaussian'`). Additionally, `backend_options` is a dictionary which contains any additional keyword arguments to be passed to the backend. For example, to create an engine linked to the Fock Backend, with a cutoff dimension of 10, we we write\n\n```python3\n    eng = sf.Engine('fock', backend_options={\"cutoff_dim\": 10})\n```\n\nTo execute a program on the backend, we simply call `eng.run`:\n\n```python3\n    results = eng.run(prog, run_options)\n```\nHere, `prog` is a Strawberry Fields `Program` object (like the one we created above), and `run_options` is a dictionary of keyword arguments which can be used to specify additional options for the returned object. \n\n`eng.run()` returns a `Results` object which contains both measurement results and -- for local simulators -- a `State` object which contains the simulated quantum state of the circuit after execution of the program. Depending on backend used, the state returned might be a BaseFockState, which represents the state using the Fock/number basis, or might be a BaseGaussianState, which represents the state using Gaussian representation, as a vector of means and a covariance matrix. Many methods are provided for state manipulation, see [Quantum States API](https://strawberryfields.readthedocs.io/en/stable/code/backend.states.html) for more details.\n\nFor more details on the technical differences between the backends, see the [Backend API](https://strawberryfields.readthedocs.io/en/stable/code/backend.html) in the documentation.\n\n### How do we choose a backend?\n\n\n* **Fock backends** are backends which represent the quantum state and operations via the Fock basis. <br>These can represent all possible continuous-variable states and operations, but also introduce numerical error due to truncation of the Fock space, and can consume more memory.\n\n\n* The **gaussian backend**, due to its ability to represent states and operations as gaussian objects/transforms in the phase space, can be less computationally intensive then the Fock backends. <br>However, it cannot represent non-gaussian operations and states (such as the cubic phase gate, and fock states, amongst others). The only exception to this is fock measurements: the gaussian backend can simulate measurement of Fock states, but it cannot update the state after doing so.</li>\n\nIn the Fock backends, due to the infinite Hilbert space, we must specify a **cutoff dimension**. For example, choosing `cutoff_dim=5`, a state $|\\psi\\rangle$ has approximation\n\n$$|{\\psi}\\rangle = \\sum_{n=0}^\\infty c_n|{n}\\rangle \\approx\\sum_{n=0}^{5-1} c_n|{n}\\rangle$$\n\nin our truncated Fock basis - i.e. all information of quantum amplitudes of Fock states $|n\\rangle$, with $n\\geq 5$, is discarded.\n\n<div class=\"alert\" style=\"border: 0px; border-left: 3px solid #F0AD4E; color: black; background-color: #FFF1E3\">\n<p style=\"color: #9B5831;\">**Warning**</p>\nTo avoid significant numerical error when working with the Fock backend, we generally need to ensure that all initial states and gates we apply result in negligible amplitude in the Fock basis for Fock states $|{n}\\rangle, ~~n\\geq \\texttt{cutoff_dim}$.\n<br><br>\n\nFor example, to prepare a squeezed vacuum state in the $x$ quadrature with `cutoff_dim=10`, a squeezing factor of $r=1$ provides an acceptable approximation, since $\\left|\\left\\langle{n}\\middle|{\\xi}\\right\\rangle\\right|^2<0.02$ for $n\\geq 10$.\n</div>\n\n<div class=\"alert alert-success\" style=\"border: 0px; border-left: 3px solid #119a68; color: black; background-color: #daf0e9\">\n<p style=\"color: #119a68;\">**Scaling**</p>\nAs we are performing a classical simualation of a quantum system, we still need to consider how the simulation scales. Using the Fock backends, memory usage and computational time will scale like $\\sim D^N$, where $N$ is the number of modes and $D$ the cutoff dimension.\n<br><br>\nIdeally, we would like to choose a cutoff large enough that minimises truncation error, but small enough to reduce classical computational resources!\n</div>\n\n\n<div class=\"alert alert-info\" style=\"border: 0px; border-left: 3px solid #31708f; color: black; background-color: #d9edf7\">\n<p style=\"color: #31708f;\">**Exercise**</p>\n\nRun the engine using the Gaussian or the Fock backend.\n\n</div>\n\n\n```python\neng = sf.Engine('fock', backend_options={\"cutoff_dim\": 15})\nresults = eng.run(prog)\nstate = results.state\n```\n\n## Results and visualization\nOnce the engine has been run, we can extract results of measurements and the quantum state from the circuit. Any measurements performed on a mode are stored in the `samples` attribute of the `Results` object returned by the engine:\n\n\n```python\nresults.samples[0]\n```\n\n\n\n\n    1.5429154291542915\n\n\n\n\n```python\nresults.samples[1]\n```\n\n\n\n\n    -2.5587255872558723\n\n\n\nThe returned `results` object stores the resulting state of the circuit after the engine run within `results.state`. The state object also contains some convenient functions for state manipulation.\n\n<div class=\"alert alert-info\" style=\"border: 0px; border-left: 3px solid #31708f; color: black; background-color: #d9edf7\">\n<p style=\"color: #31708f;\">**Exercise**</p>\n\nPrint the state object below to see some info about the state.\n\n</div>\n\n\n```python\nprint(state)\n```\n\n    <FockState: num_modes=3, cutoff=15, pure=False, hbar=2>\n\n\nThe actual state representation can also be returned; in the Fock backends, the state vector in the truncated Fock basis is available via `state.ket()`, while the density matrix is given by `state.dm()`. In the Gaussian backend, the vector of means and covariance matrix are accessible via `state.means()` and `state.cov()` respectively.\n\n### Fock backend example\nTo return the density matrix representing the Fock state, we can use the method state.dm(). In this case, the density matrix has dimension\n\n\n```python\nstate.dm().shape\n```\n\n\n\n\n    (15, 15, 15, 15, 15, 15)\n\n\n\nHere, we use the convention that every pair of consecutive dimensions corresponds to a subsystem; i.e.,\n\n$$\\rho_{\\underbrace{ij}_{q[0]}\\underbrace{kl}_{q[1]}\\underbrace{mn}_{q[2]}}$$\n\nThus we can calculate the reduced density matrix for mode `q[2]`, $\\rho_2$:\n\n\n```python\nimport numpy as np\nrho2 = np.einsum('kkllij->ij', state.dm())\nrho2.shape\n```\n\n\n\n\n    (15, 15)\n\n\n\n<div class=\"alert alert-success\" style=\"border: 0px; border-left: 3px solid #119a68; color: black; background-color: #daf0e9\">\n<p style=\"color: #119a68;\">**Note**</p>\nThe Fock state also provides the method `reduced_dm()` for extracting the reduced density matrix automatically.\n</div>\n\n\n```python\nstate.reduced_dm([2])\n```\n\n\n\n\n    array([[ 3.97509440e-01+7.80625564e-18j,  3.09261536e-01-1.69764298e-01j,\n             1.76226624e-01-9.89415763e-02j,  1.57684377e-01-1.06593446e-01j,\n             6.92509105e-02-9.71046698e-02j,  3.50702779e-02-8.35268673e-02j,\n             4.22298889e-03-4.31654588e-02j, -1.00429332e-03-4.83879790e-02j,\n            -8.19486437e-03-1.85604701e-02j, -7.96094113e-03-2.63628309e-02j,\n            -6.59716117e-03-1.06155097e-02j, -8.68276607e-03-1.55811703e-02j,\n            -1.97168200e-03-1.28390201e-02j, -6.66967170e-04-5.97618111e-03j,\n            -8.21885332e-03-1.04782503e-02j],\n           [ 3.09261536e-01+1.69764298e-01j,  3.13106060e-01+1.73472348e-17j,\n             1.79358919e-01-1.71526686e-03j,  1.68200972e-01-1.55872409e-02j,\n             9.53475446e-02-4.59722594e-02j,  6.29564118e-02-5.00062744e-02j,\n             2.17201429e-02-3.17791279e-02j,  1.98837089e-02-3.80746526e-02j,\n             1.55102944e-03-1.79397875e-02j,  5.06517430e-03-2.39101068e-02j,\n            -5.99013817e-04-1.10762936e-02j, -1.00926210e-04-1.58302665e-02j,\n             3.94919382e-03-1.08307774e-02j,  2.03334769e-03-4.93429832e-03j,\n            -1.91930635e-03-1.16620819e-02j],\n           [ 1.76226624e-01+9.89415763e-02j,  1.79358919e-01+1.71526686e-03j,\n             1.02752927e-01+1.73472348e-18j,  9.64372292e-02-8.00751389e-03j,\n             5.48705038e-02-2.58123023e-02j,  3.63377448e-02-2.83005838e-02j,\n             1.26162076e-02-1.80852910e-02j,  1.15987175e-02-2.17016646e-02j,\n             9.86766231e-04-1.02680877e-02j,  3.03250727e-03-1.36688596e-02j,\n            -2.82459150e-04-6.34819881e-03j,  2.89075066e-05-9.06872452e-03j,\n             2.32158014e-03-6.18264180e-03j,  1.19180920e-03-2.81541239e-03j,\n            -1.03556325e-03-6.69099325e-03j],\n           [ 1.57684377e-01+1.06593446e-01j,  1.68200972e-01+1.55872409e-02j,\n             9.64372292e-02+8.00751389e-03j,  9.11337491e-02+2.23345648e-17j,\n             5.35094414e-02-1.99497052e-02j,  3.63097077e-02-2.37292987e-02j,\n             1.32501366e-02-1.59905021e-02j,  1.25770097e-02-1.94638885e-02j,\n             1.72630465e-03-9.56006228e-03j,  3.91132588e-03-1.25923820e-02j,\n             2.29615964e-04-5.98001943e-03j,  7.33854497e-04-8.50906358e-03j,\n             2.66069643e-03-5.62170614e-03j,  1.33795927e-03-2.54948593e-03j,\n            -4.50484776e-04-6.36043329e-03j],\n           [ 6.92509105e-02+9.71046698e-02j,  9.53475446e-02+4.59722594e-02j,\n             5.48705038e-02+2.58123023e-02j,  5.35094414e-02+1.99497052e-02j,\n             3.57853275e-02-4.33680869e-19j,  2.65138296e-02-5.98432041e-03j,\n             1.12802691e-02-6.48833744e-03j,  1.16453851e-02-8.67509756e-03j,\n             3.10635768e-03-5.23531983e-03j,  5.05309148e-03-6.53744123e-03j,\n             1.44388054e-03-3.46092125e-03j,  2.29356804e-03-4.83547603e-03j,\n             2.79285953e-03-2.71835899e-03j,  1.34368384e-03-1.20405093e-03j,\n             1.12783224e-03-3.83316032e-03j],\n           [ 3.50702779e-02+8.35268673e-02j,  6.29564118e-02+5.00062744e-02j,\n             3.63377448e-02+2.83005838e-02j,  3.63097077e-02+2.37292987e-02j,\n             2.65138296e-02+5.98432041e-03j,  2.06452002e-02-1.51788304e-18j,\n             9.44273661e-03-2.92091580e-03j,  1.00789442e-02-4.48005800e-03j,\n             3.17703588e-03-3.35944775e-03j,  4.83714867e-03-3.99865794e-03j,\n             1.64855454e-03-2.32278529e-03j,  2.50796391e-03-3.19911956e-03j,\n             2.52385374e-03-1.54702344e-03j,  1.19690481e-03-6.67395499e-04j,\n             1.47663903e-03-2.65143445e-03j],\n           [ 4.22298889e-03+4.31654588e-02j,  2.17201429e-02+3.17791279e-02j,\n             1.26162076e-02+1.80852910e-02j,  1.32501366e-02+1.59905021e-02j,\n             1.12802691e-02+6.48833744e-03j,  9.44273661e-03+2.92091580e-03j,\n             4.73219068e-03+6.31547765e-18j,  5.24377029e-03-6.23111440e-04j,\n             1.92841807e-03-1.08705781e-03j,  2.77815974e-03-1.14454544e-03j,\n             1.08265003e-03-8.29159348e-04j,  1.59971331e-03-1.10838799e-03j,\n             1.37323984e-03-3.50501355e-04j,  6.41866529e-04-1.35914484e-04j,\n             1.05051683e-03-1.00380034e-03j],\n           [-1.00429332e-03+4.83879790e-02j,  1.98837089e-02+3.80746526e-02j,\n             1.15987175e-02+2.17016646e-02j,  1.25770097e-02+1.94638885e-02j,\n             1.16453851e-02+8.67509756e-03j,  1.00789442e-02+4.48005800e-03j,\n             5.24377029e-03+6.23111440e-04j,  5.89270311e-03-1.08420217e-17j,\n             2.28003060e-03-9.50651056e-04j,  3.22920438e-03-9.02463693e-04j,\n             1.30887091e-03-7.76238699e-04j,  1.91859944e-03-1.01756939e-03j,\n             1.56784800e-03-2.07571335e-04j,  7.29152890e-04-6.60898887e-05j,\n             1.29625977e-03-9.73990618e-04j],\n           [-8.19486437e-03+1.85604701e-02j,  1.55102944e-03+1.79397875e-02j,\n             9.86766231e-04+1.02680877e-02j,  1.72630465e-03+9.56006228e-03j,\n             3.10635768e-03+5.23531983e-03j,  3.17703588e-03+3.35944775e-03j,\n             1.92841807e-03+1.08705781e-03j,  2.28003060e-03+9.50651056e-04j,\n             1.03556497e-03+6.99310401e-18j,  1.39504956e-03+1.71772055e-04j,\n             6.31662209e-04-8.91897078e-05j,  9.06514163e-04-8.42008745e-05j,\n             6.40125464e-04+1.72621518e-04j,  2.92789113e-04+9.20601268e-05j,\n             6.58685339e-04-1.67739265e-04j],\n           [-7.96094113e-03+2.63628309e-02j,  5.06517430e-03+2.39101068e-02j,\n             3.03250727e-03+1.36688596e-02j,  3.91132588e-03+1.25923820e-02j,\n             5.05309148e-03+6.53744123e-03j,  4.83714867e-03+3.99865794e-03j,\n             2.77815974e-03+1.14454544e-03j,  3.22920438e-03+9.02463693e-04j,\n             1.39504956e-03-1.71772055e-04j,  1.90781742e-03+2.55871713e-17j,\n             8.36142402e-04-2.24926474e-04j,  1.20723359e-03-2.63796285e-04j,\n             8.90970938e-04+1.26365713e-04j,  4.09697788e-04+7.54520027e-05j,\n             8.59517068e-04-3.35226017e-04j],\n           [-6.59716117e-03+1.06155097e-02j, -5.99013817e-04+1.10762936e-02j,\n            -2.82459150e-04+6.34819881e-03j,  2.29615964e-04+5.98001943e-03j,\n             1.44388054e-03+3.46092125e-03j,  1.64855454e-03+2.32278529e-03j,\n             1.08265003e-03+8.29159348e-04j,  1.30887091e-03+7.76238699e-04j,\n             6.31662209e-04+8.91897078e-05j,  8.36142402e-04+2.24926474e-04j,\n             3.92975777e-04+1.77809156e-17j,  5.60197191e-04+2.67151010e-05j,\n             3.75589182e-04+1.60425562e-04j,  1.70663364e-04+8.13707306e-05j,\n             4.16224248e-04-4.55853597e-05j],\n           [-8.68276607e-03+1.55811703e-02j, -1.00926210e-04+1.58302665e-02j,\n             2.89075066e-05+9.06872452e-03j,  7.33854497e-04+8.50906358e-03j,\n             2.29356804e-03+4.83547603e-03j,  2.50796391e-03+3.19911956e-03j,\n             1.59971331e-03+1.10838799e-03j,  1.91859944e-03+1.01756939e-03j,\n             9.06514163e-04+8.42008745e-05j,  1.20723359e-03+2.63796285e-04j,\n             5.60197191e-04-2.67151010e-05j,  8.00391800e-04+0.00000000e+00j,\n             5.46318126e-04+2.03157678e-04j,  2.48816773e-04+1.04394133e-04j,\n             5.90239528e-04-9.32786839e-05j],\n           [-1.97168200e-03+1.28390201e-02j,  3.94919382e-03+1.08307774e-02j,\n             2.32158014e-03+6.18264180e-03j,  2.66069643e-03+5.62170614e-03j,\n             2.79285953e-03+2.71835899e-03j,  2.52385374e-03+1.54702344e-03j,\n             1.37323984e-03+3.50501355e-04j,  1.56784800e-03+2.07571335e-04j,\n             6.40125464e-04-1.72621518e-04j,  8.90970938e-04-1.26365713e-04j,\n             3.75589182e-04-1.60425562e-04j,  5.46318126e-04-2.03157678e-04j,\n             4.24462790e-04-6.93889390e-18j,  1.96330825e-04+8.10024505e-06j,\n             3.79199627e-04-2.13484855e-04j],\n           [-6.66967170e-04+5.97618111e-03j,  2.03334769e-03+4.93429832e-03j,\n             1.19180920e-03+2.81541239e-03j,  1.33795927e-03+2.54948593e-03j,\n             1.34368384e-03+1.20405093e-03j,  1.19690481e-03+6.67395499e-04j,\n             6.41866529e-04+1.35914484e-04j,  7.29152890e-04+6.60898887e-05j,\n             2.92789113e-04-9.20601268e-05j,  4.09697788e-04-7.54520027e-05j,\n             1.70663364e-04-8.13707306e-05j,  2.48816773e-04-1.04394133e-04j,\n             1.96330825e-04-8.10024505e-06j,  9.09653514e-05-1.31730564e-17j,\n             1.71320779e-04-1.05981652e-04j],\n           [-8.21885332e-03+1.04782503e-02j, -1.91930635e-03+1.16620819e-02j,\n            -1.03556325e-03+6.69099325e-03j, -4.50484776e-04+6.36043329e-03j,\n             1.12783224e-03+3.83316032e-03j,  1.47663903e-03+2.65143445e-03j,\n             1.05051683e-03+1.00380034e-03j,  1.29625977e-03+9.73990618e-04j,\n             6.58685339e-04+1.67739265e-04j,  8.59517068e-04+3.35226017e-04j,\n             4.16224248e-04+4.55853597e-05j,  5.90239528e-04+9.32786839e-05j,\n             3.79199627e-04+2.13484855e-04j,  1.71320779e-04+1.05981652e-04j,\n             4.46136021e-04-1.08420217e-17j]])\n\n\n\nThe diagonal values of the reduced density matrix contain the marginal Fock state probabilities $\\left|\\left\\langle{i}\\mid{\\rho_2}\\right\\rangle\\right|^2,~~ 0\\leq i< cutoff$:\n\n\n```python\nnp.real_if_close(np.diag(state.reduced_dm([2])))\n```\n\n\n\n\n    array([3.97509440e-01, 3.13106060e-01, 1.02752927e-01, 9.11337491e-02,\n           3.57853275e-02, 2.06452002e-02, 4.73219068e-03, 5.89270311e-03,\n           1.03556497e-03, 1.90781742e-03, 3.92975777e-04, 8.00391800e-04,\n           4.24462790e-04, 9.09653514e-05, 4.46136021e-04])\n\n\n\nThis can also be returned via the state method `all_fock_probs`.\n\n### Plotting the Wigner function\n\n<div class=\"alert alert-info\" style=\"border: 0px; border-left: 3px solid #31708f; color: black; background-color: #d9edf7\">\n<p style=\"color: #31708f;\">**Exercise**</p>\n\nUsing the `state.wigner` function, plot the wigner function of the input state and the resulting teleported state.\n\n</div>\n\n\n```python\nimport matplotlib.pyplot as plt\n```\n\n\n```python\nx = np.arange(-5, 5, 0.1)\np = np.arange(-5, 5, 0.1)\n```\n\n\n```python\nW = state.wigner(2, x, p)\n```\n\n\n```python\nW.shape\n```\n\n\n\n\n    (100, 100)\n\n\n\n\n```python\nX, P = np.meshgrid(x, p)\nplt.contourf(X, P, W)\n```\n\n<div class=\"alert alert-info\" style=\"border: 0px; border-left: 3px solid #31708f; color: black; background-color: #d9edf7\">\n<p style=\"color: #31708f;\">**Exercise**</p>\n\nRepeat this notebook, but using the `'gaussian'` backend instead. How does the teleportation fidelity compare to the fock backend?\n\n</div>\n\n\n```python\n\n```\n", "meta": {"hexsha": "aa3ce07af1e16f3ffb2f5e0bb2d14056ded5723f", "size": 43621, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/QuantumTeleportation.ipynb", "max_stars_repo_name": "Lucaman99/strawberryfields", "max_stars_repo_head_hexsha": "627b8e6c1049d1108303bf0d9ba53cf6b120ea1f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-12T17:53:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-12T17:53:56.000Z", "max_issues_repo_path": "examples/QuantumTeleportation.ipynb", "max_issues_repo_name": "Lucaman99/strawberryfields", "max_issues_repo_head_hexsha": "627b8e6c1049d1108303bf0d9ba53cf6b120ea1f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-09-26T01:27:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T02:13:49.000Z", "max_forks_repo_path": "examples/QuantumTeleportation.ipynb", "max_forks_repo_name": "Lucaman99/strawberryfields", "max_forks_repo_head_hexsha": "627b8e6c1049d1108303bf0d9ba53cf6b120ea1f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.8739393939, "max_line_length": 8700, "alphanum_fraction": 0.6724054928, "converted": true, "num_tokens": 8900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.09807932281138339, "lm_q1q2_score": 0.04106550933282492}}
{"text": "```python\nimport numpy as np\n%matplotlib ipympl\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom latexify import latexify\nimport os\n#%matplotlib ipympl\n#import seaborn as sns # it will set to SNS style\n#sns.reset_orig() # set back to the Matplotlib style\n#sns.set() # set to sns style\n\n# print plt.style.available # all available styles\n\n# you set differnt styles\n#plt.style.use('ggplot')\n#plt.style.use('presentation')\n#plt.style.use(['dark_background', 'presentation'])\n\n# OR set style temperarily\n#with plt.style.context('styleName'):\n#    plt.plot()\n\n# you can set color_palette of sns\n#flatui = [\"#9b59b6\", \"#3498db\", \"#95a5a6\", \"#e74c3c\", \"#34495e\", \"#2ecc71\"]\n#ax.set_color_cycle(sns.color_palette(flatui)) \n# OR \n#ax.set_color_cycle(sns.color_palette('name'))\n# OR\n#sns.set_palette(\"husl\") # only when using sns for plot\n\n\n# set the font\n#plt.rcParams[\"font.family\"] = 'arial'\n#%matplotlib notebook\n\n#from latexify import latexify\n```\n\n\n```python\nimport matplotlib\n'''To make the tex-style/mathtext text look like the regular text, \nyou need to set the mathtext font to Bitstream Vera Sans:'''\n\nmatplotlib.rcParams['mathtext.fontset'] = 'custom'\n# set the font\nplt.rcParams[\"font.family\"] = 'arial' #'Bitstream Vera Sans'# 'arial' #\nmatplotlib.rcParams['mathtext.rm'] = 'arial' #'Bitstream Vera Sans'\nmatplotlib.rcParams['mathtext.it'] = 'arial:italic' #'Bitstream Vera Sans:italic'\nmatplotlib.rcParams['mathtext.bf'] = 'arial:bold' #'Bitstream Vera Sans:bold'\nfig, ax = plt.subplots(figsize=(5, 4))\nmatplotlib.pyplot.title(r'ABC123 vs $ABC^2\\mathrm{ABC123}^{123}\\mathsf{ABCabc}$')\n\n'''If you want the regular text to look like the mathtext text, \nyou can change everything to Stix. This will affect labels, titles, ticks, etc.'''\n\n# matplotlib.rcParams['mathtext.fontset'] = 'stix'\n# matplotlib.rcParams['font.family'] = 'arial' #'STIXGeneral'\n# matplotlib.pyplot.text(0.,0.5,r'ABC123 vs $\\mathrm{ABC123}^{123}\\mathsf{ABCabc}$')\n\n#plt.style.use(u'classic')#u'seaborn-paper') # Set back to default\n```\n\n\n```python\n(491+375+375)/3.*0.0001*8*3.1415**2\n```\n\n\n\n\n    3.2659884299333335\n\n\n\n\n```python\nfrom matplotlib.text import Text\nclass DragTextHandler(object):\n    \"\"\" A simple class to handle Drag n Drop.\n    This is a simple example, which works for Text objects only.\n    \"\"\"\n    def __init__(self, figure=None) :\n        \"\"\" Create a new drag handler and connect it to the figure's event system.\n        If the figure handler is not given, the current figure is used instead\n        \"\"\"\n\n        if figure is None : figure = plt.gcf()\n        # simple attibute to store the dragged text object\n        self.dragged = None\n\n        # Connect events and callbacks\n        figure.canvas.mpl_connect(\"pick_event\", self.on_pick_event)\n        #figure.canvas.mpl_connect(\"motion_notify_event\", self.on_move_event)\n        figure.canvas.mpl_connect(\"button_release_event\", self.on_release_event)\n\n    def on_pick_event(self, event):\n        \" Store which text object was picked and were the pick event occurs.\"\n        if isinstance(event.artist, Text):\n            self.dragged = event.artist\n            self.pick_pos = (event.mouseevent.xdata, event.mouseevent.ydata)\n        return True\n#     def on_move_event(self, event):# by Xu not working well (sticky to the mouse)\n#         \" Update text position and redraw\"\n#         if self.dragged is not None :\n#             old_pos = self.dragged.get_position()\n#             new_pos = (old_pos[0] + event.xdata - self.pick_pos[0],\n#                        old_pos[1] + event.ydata - self.pick_pos[1])\n#             self.dragged.set_position(new_pos)\n#             #self.dragged = None\n#             plt.draw()\n#         return True\n    def on_release_event(self, event):\n        \" Update text position and redraw\"\n        if self.dragged is not None :\n            old_pos = self.dragged.get_position()\n            new_pos = (old_pos[0] + event.xdata - self.pick_pos[0],\n                       old_pos[1] + event.ydata - self.pick_pos[1])\n            self.dragged.set_position(new_pos)\n            self.dragged = None\n            plt.draw()\n        return True\n# set picker=True when drawing the Text\n# dragh = DragTextHandler()\n\nclass DraggableText(object): \n    \"\"\" A simple class to handle Drag n Drop.\n    This is a simple example, which works for Text objects only.\n    \"\"\"\n    def __init__(self, figure=None):\n        \"\"\" Create a new drag handler and connect it to the figure's event system.\n        If the figure handler is not given, the current figure is used instead\n        \"\"\"\n        if figure is None:\n            figure = plt.gcf()          \n        # simple attibute to store the dragged text object\n        self.dragged = None # store the text to drag\n        self.press = None # store the old text position and the press event position\n        # the location of the text location in axes coords to show the position of the dragged text\n        self.txt = ax.text(0.7, 0.9, '', transform=ax.transAxes)\n\n        # Connect events and callbacks\n        figure.canvas.mpl_connect(\"pick_event\", self.on_pick_event)\n        figure.canvas.mpl_connect(\"motion_notify_event\", self.on_motion_event)\n        figure.canvas.mpl_connect(\"button_release_event\", self.on_release_event)\n     \n    def on_pick_event(self, event):\n        \" Store which text object was picked and were the pick event occurs.\"\n        if isinstance(event.artist, Text):\n            self.dragged = event.artist\n            x0, y0 = event.artist.get_position()\n            self.press = x0, y0, event.mouseevent.xdata, event.mouseevent.ydata # have to insert '.mouseevent'\n\n    def on_motion_event(self, event):\n        'on motion we will move the rect if the mouse is over us'\n        if self.press is None: return\n        x0, y0, xpress0, ypress0 = self.press\n        new_position = (x0+event.xdata - xpress0, y0+event.ydata - ypress0)\n        self.dragged.set_position(new_position)\n        self.txt.set_text('x=%1.2f, y=%1.2f' % new_position)\n        plt.draw()\n\n    def on_release_event(self, event):\n        'on release we reset the press data'\n        self.press = None\n        self.txt.set_text('')\n        plt.draw()\n        return\n# set picker=True when drawing the Text\n# dragh = DragTextHandler()\n```\n\n## Cp of crystal Nd2Zr2O7 in zero field (fit nuclear, magnon, phonon)\n\n\n```python\n# \uff4c\uff4f\uff41\uff44\u3000\uff44\uff41\uff54\uff41\nfpath = r'D:\\3_Physical Properties\\Heat_Capacity\\1_Cp_NdZrO_Ausburg'\nfname0 = r'cp_ndzro_lowT_with_ppms.txt'\nfname1 = r'cp_lazro_2-400k.txt'\nfname2 = r'Nd2Sn2O7_digitized_1969Blote.txt' # T, Cp/R(JK/mol Nd)\n#fname = r'cp_ndzro_lowT_with_ppms_subLa.txt'\nf0 = os.path.join(fpath, fname0)\nf1 = os.path.join(fpath, fname1)\nf2 = os.path.join(fpath, fname2)\ncpnd = np.genfromtxt(f0, usecols=(0,1), skip_header=1)\ncpla = np.genfromtxt(f1, usecols=(0,1), skip_header=1)\ncpndsn = np.genfromtxt(f2, usecols=(0,1), skip_header=1)\ncpndsn[:,1] = 2*8.315*cpndsn[:,1] # convert to Cp/mol\n\n#%matplotlib inline\nfig=plt.figure(figsize=(3,2))\nax = fig.add_subplot(111, xscale='log', yscale='log')# autoscale_on=True, xlim=(0.01, 10), ylim=(0., 0.65),\nax.plot(cpnd[:,0], cpnd[:,1]/2,'o', mfc='white',mec='black',label=r'Nd$_2$Zr$_2$O$_7$')\nax.plot(cpla[:,0], cpla[:,1]/2,'r.',markersize=3,label=r'La$_2$Zr$_2$O$_7$')\nax.plot(cpndsn[:,0], cpndsn[:,1]/2,'o',mfc='white',mec='blue',label=r'Nd$_2$Sn$_2$O$_7$')\nax.set_xlabel('T (K)')\nax.set_ylabel('Cp (J/K/mold R)')\nplt.legend()\nplt.show()\n\n# Export data for Owen\n#np.savetxt(os.path.join(fpath, 'Nd2Zr2O7_Cp_2-100K.txt'),np.vstack([cpnd[:,0],cpnd[:,1]/2]).T)\n#np.savetxt(os.path.join(fpath, 'La2Zr2O7_Cp_2-300K.txt'),np.vstack([cpla[:,0],cpla[:,1]/2]).T)\n```\n\n\n```python\n#\u3000\uff24\uff45\uff46\uff49\uff4e\uff45\u3000\uff46\uff55\uff4e\uff53\u3000\uff46\uff4f\uff52\u3000\uff23\uff50\u3000\uff4f\uff46\u3000\uff4e\uff55\uff43\uff4c\uff45\uff41\uff52\u3000\uff11\uff0f\uff34\uff12\uff0c\u3000\uff4d\uff41\uff47\uff4e\uff4f\uff4e\u3000\uff34\uff13\u3000\uff41\uff4e\uff44\u3000\uff50\uff48\uff4f\uff4e\uff4f\uff4e\u3000\uff34\uff13\nfrom scipy import optimize\n\nR = 8.314 #in J/K/mol\n\ndef cpNuclear(t, n):\n    return R*n/t**2\n\ndef cpMag(t, a,b):\n    return R*a*t**b    \n\ndef cpnm(t,n,a,b):# nuclear + mag\n    return R*n/t**2 + R*a*t**b \n\ndef cpph(t,n): # phonon\n    return R*n*t**3\n\ndef cpph0(t,n0,n1): # phonon\n    return n0*t**3 + n1*t**5\n# def cpph1(t,n,m):\n#     return R*n*t**m\n\ndef cpph1(t,*args):\n    #print len(args), args\n    if len(args)==1:\n        return R*args[0][0]*t**args[0][1]\n    else:\n        return R*args[0]*t**args[1]\n\ndef cpNuclear1(t, n,m):\n    return R*n/t**m\n\ndef cpnm1(t,n,m,a,b):\n    return R*n / t**m + R*a * t**b \n\ndef fitReg(dat, *args):\n    if len(args)==1:# when the low and high limits is in a list\n        mask = (args[0][0]< dat[:,0]) & (dat[:,0] < args[0][1])\n    else: # two augs give the the two limits\n        mask = (args[0]< dat[:,0]) & (dat[:,0] < args[1])\n    return dat[mask,:]\n\n#print fitReg(cpnd,0.0,0.2)\n\n# Test fit\npopt, pcov = optimize.curve_fit(cpnm, fitReg(cpnd,[0.0,0.2])[:,0], fitReg(cpnd,0.0,0.2)[:,1], [0.00065,50,3])\nprint(popt)\n```\n\n    [6.08283701e-04 3.44451182e+01 2.83960860e+00]\n\n\n\n```python\n# \uff21\uff4a\uff55\uff53\uff54\u3000\uff54\uff48\uff45\u3000\uff46\uff49\uff54\uff54\uff49\uff4e\uff47\u3000\uff52\uff45\uff47\uff49\uff4f\uff4e\n#\u3000\uff46\uff49\uff54\u3000\uff13\u3000\uff50\uff41\uff52\uff41\uff4d\uff45\uff54\uff45\uff52\uff53\u3000\uff4e\uff0c\u3000\uff41\uff0c\uff42\nfrom ipywidgets import interact, interactive, fixed\nimport ipywidgets as widgets\n\n#%matplotlib inline\nfig_label = ('Data', r'Nuclear$\\sim T^{-2}$', r'Magnon$\\sim T^{3}$', 'Nuclear+magnon')\nprint(fig_label)\n\ndef pltFitReg(x1,x2=0.18):\n    popt, pcov = optimize.curve_fit(cpnm, fitReg(cpnd,x1,x2)[:,0], fitReg(cpnd,x1,x2)[:,1], [0.00065,50,3])\n    print(popt)    \n    \n    global fig, ax\n    ax.cla()\n    #ax.grid(color='w', linewidth=2, linestyle='solid')\n    \n    ax.plot(cpnd[:,0], cpnd[:,1], 'o', mfc='white',label=fig_label[0])\n    # Strange: \u2018label=...\u2019 must put after 'o'? \n    # after keyword='o', it works\n\n    t = np.linspace(0.01, 1, 100)\n    ax.plot(t, cpNuclear(t, popt[0]), 'b--', lw=0.5, alpha=1, label=fig_label[1])\n    ax.plot(t, cpMag(t, popt[1], popt[2]),  'b--', lw=0.5, alpha=1, label=fig_label[2])\n    #ax.plot(t, cpMag(t, 7.45, 2.32),color='orange',linestyle='--', lw=0.5, alpha=1)   \n    ax.plot(t, cpnm(t,popt[0],popt[1],popt[2]), 'r', lw=1, alpha=1, label=fig_label[3])\n        \n    ax.set_xlim(0.05, 1)\n    ax.set_ylim(0.1, 15)\n    ax.set_xscale('log')\n    ax.set_yscale('log')\n       \n    ax.set_ylabel(r'$C\\mathrm{_p}$ (J/K/mol Nd)',size=14,labelpad=-1)  \n    ax.set_xlabel(r'T (K)',size=14,labelpad=-1)\n    \n    ax.tick_params(axis='both',which='both',labelsize=14,width=1,length=3)\n\n#   ax.xaxis.set_ticks_position('bottom')\n#   ax.yaxis.set_ticks_position('left')\n\n    handles, labels = ax.get_legend_handles_labels()\n    #ax.legend([handles[0],handles[3]], [labels[0],labels[3]],loc='best',numpoints=1,frameon=False,framealpha=1,fontsize=13,fancybox=True,shadow=False)\n    ax.legend([handles[0],handles[3],handles[1],handles[2]], [labels[0],labels[3],labels[1],labels[2]],loc='best',numpoints=1,frameon=False,framealpha=1,fontsize=13,fancybox=True,shadow=False)\n    #ax.legend(loc='best',numpoints=1,fontsize=13, frameon=False)\n\n    ax.axvspan(0.07, 0.175, alpha=0.5, color='lightgrey')    \n    ax.text(0.11, 1.2,r'Fitted'+'\\n'+'region',size=14, ha='center', va='center',\n             backgroundcolor='white',bbox=dict(facecolor='white', alpha=0, edgecolor='white', boxstyle='round'))\n\n    #ax.text(0.45, 9,r'$\\sim T^{2.34}$',size=14,color='orange', ha='left', va='center',\n             #backgroundcolor='white',bbox=dict(facecolor='white', alpha=0, edgecolor='white', boxstyle='round'))\n    \n    ax.text(0.072,7,r'Nd$_2$Zr$_2$O$_7$'+ '\\n'+'crystal',size=14, ha='left', va='center',\n             backgroundcolor='white',bbox=dict(facecolor='white', alpha=0, edgecolor='white', boxstyle='round'))\n    \n    #fig.savefig(os.path.join(fpath, r'nd_cp_crys_lowT1.pdf'), bbox_inches=\"tight\", verbose=True) \n\n    return fig\n\n#interact(pltFitReg, x1=(0,0.2,0.01), x2=(0.1,0.4,0.005),__manual=True)\n#interact(pltFitReg, x1=(0,0.2,0.01), x2=(0.1,0.4,0.005),continuous_update=False)\n\nfig, ax = plt.subplots(figsize=(5, 4))#,subplot_kw={'axisbg':'#EEEEEE','axisbelow':True})\ninteract(pltFitReg, x1=widgets.FloatSlider(min=0.,max=0.2,step=0.005,value=0.0),\n         x2=widgets.FloatSlider(min=0.1,max=0.4,step=0.005,value=0.18),__manual=True) \n\n```\n\n\n```python\n# \uff21\uff4a\uff55\uff53\uff54\u3000\uff54\uff48\uff45\u3000\uff46\uff49\uff54\uff54\uff49\uff4e\uff47\u3000\uff52\uff45\uff47\uff49\uff4f\uff4e \uff4e\uff55\uff43\uff4c\uff45\uff41\uff52\uff0b\uff4d\uff41\uff47\uff0b\uff50\uff48\uff4f\uff4e\uff4f\uff4e\n#\u3000\uff46\uff49\uff54\u3000\uff14\u3000\uff50\uff41\uff52\uff41\uff4d\uff45\uff54\uff45\uff52\uff53\uff1a\u3000\uff4e\u3000\uff08\uff4e\uff55\uff43\uff4c\uff45\uff41\uff52\uff09\uff0c\u3000\uff41\uff0c\u3000\uff42\u3000\uff08\uff4d\uff41\uff47\uff4e\uff4f\uff4e\uff09\u3000\uff41\uff4e\uff44\u3000\u3000\uff4e\u3000\uff08\uff50\uff48\uff4f\uff4e\uff4f\uff4e\uff09\u3000\nfrom ipywidgets import interact, interactive, fixed\nimport ipywidgets as widgets\n\nfig_label = ('Data', r'Nuclear$\\sim T^{-2}$', r'Magnon$\\sim T^{3}$', 'Nuclear+magnon', 'Phonon')\nprint(fig_label)\n\ndef pltFitReg(x1=10,x2=18, x3=0,x4=0.18):\n    global fig, ax\n    plt.cla()  \n    ax.plot(cpnd[:,0], cpnd[:,1], 'o', mfc='white',label=fig_label[0])\n    ax.plot(cpla[:,0], cpla[:,1],'b.',markersize=3)\n#   Fit phonon with n*T**m    \n#     popt0, pcov = optimize.curve_fit(lambda t, n,m: cpph1(t,n,m), fitReg(cpnd,x1,x2)[:,0], fitReg(cpnd,x1,x2)[:,1], [0.00065,3])\n#     print popt0    \n#     t = np.linspace(5, 18, 100)\n#     ax.plot(t, cpph1(t, popt0), 'r--', lw=0.5, alpha=1, label=fig_label[4])\n\n#   Fit phonon with n0*T**3+n1*T**5 Note: the unit is per mole Nd\n    popt0, pcov = optimize.curve_fit(lambda t, n0,n1: cpph0(t,n0,n1), fitReg(cpnd,x1,x2)[:,0], fitReg(cpnd,x1,x2)[:,1], [0.00015,0.0000012])\n    print(popt0)    \n    t = np.linspace(5, 18, 100)\n    ax.plot(t, cpph0(t, popt0[0], popt0[1]), 'r--', lw=0.5, alpha=1, label=fig_label[4])\n\n#   Fit mag+nuclear with aT**-2 + bT**3        \n    popt, pcov = optimize.curve_fit(cpnm, fitReg(cpnd,x3,x4)[:,0], fitReg(cpnd,x3,x4)[:,1], [0.00065,50,3])\n    print(popt)\n    \n    t = np.linspace(0.01, 1, 100)\n    ax.plot(t, cpNuclear(t, popt[0]), 'b--', lw=0.5, alpha=1, label=fig_label[1])\n    ax.plot(t, cpMag(t, popt[1], popt[2]),  'b--', lw=0.5, alpha=1, label=fig_label[2])\n    #ax.plot(t, cpMag(t, 7.45, 2.32),color='orange',linestyle='--', lw=0.5, alpha=1)  \n    ax.plot(t, cpnm(t,popt[0],popt[1],popt[2]), 'r', lw=1, alpha=1, label=fig_label[3])\n\n    \n    ax.set_xlim(0.06, 30)\n    ax.set_ylim(0.02, 30)\n    ax.set_xscale('log')\n    ax.set_yscale('log')\n       \n    ax.set_ylabel(r'Cp (J/K/mol Nd)',size=14,labelpad=-1)  \n    ax.set_xlabel(r'T (K)',size=14,labelpad=-1)  \n    ax.tick_params(axis='both',which='both',labelsize=14,width=1,length=3)\n\n    handles, labels = ax.get_legend_handles_labels()\n    ax.legend([handles[0],handles[4],handles[1]],\n              [labels[0],labels[4],labels[1]],loc='best',numpoints=1,frameon=False,framealpha=1,\n              fontsize=12,fancybox=True,shadow=False)\n \n    ax.axvspan(0.07, 0.175, alpha=0.5, color='lightgrey')    \n    ax.text(0.11, 1.4,r'Fitted'+'\\n'+'region',size=13, ha='center', va='center',\n             backgroundcolor='white',bbox=dict(facecolor='white', alpha=0, edgecolor='white', boxstyle='round'))\n\n    #ax.text(0.45, 9,r'$\\sim T^{2.34}$',size=13,color='orange', ha='left', va='center',\n             #backgroundcolor='white',bbox=dict(facecolor='white', alpha=0, edgecolor='white', boxstyle='round'))\n    \n    ax.text(0.4,0.2,r'Nd$_2$Zr$_2$O$_7$'+ '\\n'+'crystal',size=13, ha='left', va='center',\n             backgroundcolor='white',bbox=dict(facecolor='white', alpha=0, edgecolor='white', boxstyle='round'))\n    \n    ax.text(3,1,r'Entropy'+'\\n'+'~ 0.95R ln2',size=13, ha='left', va='center',\n             backgroundcolor='white',bbox=dict(facecolor='white', alpha=0, edgecolor='white', boxstyle='round'))\n    #fig.savefig(os.path.join(fpath, r'nd_cp_crys_lowT.pdf'), bbox_inches=\"tight\", verbose=True) \n    \n    return fig\n\nfig, ax = plt.subplots(figsize=(5, 4))#,subplot_kw={'axisbg':'#EEEEEE','axisbelow':True})\n\ninteract(pltFitReg, x1=widgets.FloatSlider(min=8.,max=18,step=0.5,value=10),\n         x2=widgets.FloatSlider(min=11,max=20,step=0.5,value=16),\n        x3=widgets.FloatSlider(min=0.,max=0.2,step=0.005,value=0.0),\n         x4=widgets.FloatSlider(min=0.1,max=0.4,step=0.005,value=0.18))#,__manual=True) \n\n```\n\n\n```python\n480+850+68+20+250+280+50\n```\n\n\n\n\n    1998\n\n\n\n\n```python\n# \uff21\uff4a\uff55\uff53\uff54\u3000\uff54\uff48\uff45\u3000\uff46\uff49\uff54\uff54\uff49\uff4e\uff47\u3000\uff52\uff45\uff47\uff49\uff4f\uff4e \uff4e\uff55\uff43\uff4c\uff45\uff41\uff52\uff0b\uff4d\uff41\uff47\uff0b\uff50\uff48\uff4f\uff4e\uff4f\uff4e\n#\u3000\uff46\uff49\uff54\u3000\uff14\u3000\uff50\uff41\uff52\uff41\uff4d\uff45\uff54\uff45\uff52\uff53\uff1a\u3000\uff4e\u3000\uff08\uff4e\uff55\uff43\uff4c\uff45\uff41\uff52\uff09\uff0c\u3000\uff41\uff0c\u3000\uff42\u3000\uff08\uff4d\uff41\uff47\uff4e\uff4f\uff4e\uff09\u3000\uff41\uff4e\uff44\u3000\u3000\uff4e\u3000\uff08\uff50\uff48\uff4f\uff4e\uff4f\uff4e\uff09\u3000\nfrom ipywidgets import interact, interactive, fixed\nimport ipywidgets as widgets\nlatexify()\nfig_label = (r'Nd$_2$Zr$_2$O$_7$', r'Nuclear$\\sim T^{-2}$', r'Magnon$\\sim T^{3}$', 'Nuclear+magnon', 'Phonon',r'La$_2$Zr$_2$O$_7$')\nprint(fig_label)\n\ncp_rep = np.genfromtxt(r'D:\\3_Physical Properties\\Heat_Capacity\\Cp_ndzro_reported.txt')\ndef pltFitReg(x1=10,x2=18, x3=0,x4=0.18):\n    global fig, ax\n    plt.cla()  \n    ax.plot(cpnd[:,0], cpnd[:,1], 'o',mec='r', mfc='white',markersize=1,label=fig_label[0])# plot raw data: Nd\n    ax.plot(cpla[:,0], cpla[:,1],'s',mec='black',mfc='white',markersize=1,label=fig_label[5],zorder=0)# plot raw data: La\n    ax.plot(cp_rep[:,0],cp_rep[:,1], '^',mec='blue',mfc='white',markersize=1,label='Ref. [18]',zorder=0)\n#   Fit phonon with n*T**m    \n#     popt0, pcov = optimize.curve_fit(lambda t, n,m: cpph1(t,n,m), fitReg(cpnd,x1,x2)[:,0], fitReg(cpnd,x1,x2)[:,1], [0.00065,3])\n#     print popt0    \n#     t = np.linspace(5, 18, 100)\n#     ax.plot(t, cpph1(t, popt0), 'r--', lw=0.5, alpha=1, label=fig_label[4])\n\n#   Fit phonon with n0*T**3+n1*T**5 Note: the unit is per mole Nd2 or La2\n#     popt0, pcov = optimize.curve_fit(lambda t, n0,n1: cpph0(t,n0,n1), fitReg(cpla,x1,x2)[:,0], fitReg(cpla,x1,x2)[:,1], [0.00015,0.0000012])\n#     print popt0    \n#     t = np.linspace(0, x2, 100)\n#     ax.plot(t, cpph0(t, popt0[0], popt0[1]), 'r--', lw=0.5, alpha=1, label=fig_label[4])\n\n#   Fit mag+nuclear with aT**-2 exp(-d/kbT) \n#     popt, pcov = optimize.curve_fit(cpnm, fitReg(cpnd,x3,x4)[:,0], fitReg(cpnd,x3,x4)[:,1], [0.00065,50,3])\n#     print popt\n    \n    t = np.linspace(0.01, 0.2, 100)\n    ax.plot(t, 0.0062 * t**-2, 'r--', dashes=(1, 1), lw=0.5, alpha=1, label=fig_label[1]) # use fited A in A T^-2 + T^2 Exp-d/T\n#     ax.plot(t, cpMag(t, popt[1], popt[2]),  'b--', lw=0.5, alpha=1, label=fig_label[2])\n#     #ax.plot(t, cpMag(t, 7.45, 2.32),color='orange',linestyle='--', lw=0.5, alpha=1)  \n#     ax.plot(t, cpnm(t,popt[0],popt[1],popt[2]), 'r', lw=1, alpha=1, label=fig_label[3])\n        \n    ax.set_xlim(0.06, 80)\n    ax.set_ylim(0.015, 100)\n    ax.set_xscale('log')\n    ax.set_yscale('log')\n       \n    ax.set_ylabel(r'$C_\\mathrm{p}$ (J/K/mol)',labelpad=-1)  \n    ax.set_xlabel(r'T (K)',labelpad=-1)  \n    ax.tick_params(axis='both',which='both',direction='in')\n    \n    #ax.legend(loc='best',numpoints=1,frameon=False,framealpha=1,fontsize=13,fancybox=True,shadow=False).draggable()\n    ax.legend(loc=[-0.05,0.78],ncol=2,numpoints=1,frameon=False,framealpha=1,fancybox=True,\n              shadow=False,handletextpad=0,columnspacing=0.,labelspacing=0).draggable()\n#     handles, labels = ax.get_legend_handles_labels()\n#     ax.legend([handles[0],handles[4],handles[1]],\n#               [labels[0],labels[4],labels[1]],loc='best',numpoints=1,frameon=False,framealpha=1,\n#               fontsize=12,fancybox=True,shadow=False)\n \n#     ax.axvspan(0.07, 0.175, alpha=0.5, color='lightgrey')    \n#     ax.text(0.11, 4,r'Fitted'+'\\n'+'region',size=13, ha='center', va='center',\n#              backgroundcolor='white',bbox=dict(facecolor='white', alpha=0, edgecolor='white', boxstyle='round'))\n\n    #ax.text(0.45, 9,r'$\\sim T^{2.34}$',size=13,color='orange', ha='left', va='center',\n             #backgroundcolor='white',bbox=dict(facecolor='white', alpha=0, edgecolor='white', boxstyle='round'))\n    \n#     ax.text(0.4,0.2,r'Nd$_2$Zr$_2$O$_7$'+ '\\n'+'crystal',size=13, ha='left', va='center',\n#              backgroundcolor='white',bbox=dict(facecolor='white', alpha=0, edgecolor='white', boxstyle='round'))\n\n    ax.text(0.13,0.06,r'Entropy'+'\\n'+r'~ $0.93\\,\\times2\\,R\\,\\ln(2)$', ha='left', va='center',picker=True,\n             backgroundcolor='white',bbox=dict(facecolor='white', alpha=0, edgecolor='white', boxstyle='round'))\n    \n    #dragh = DragTextHandler()#set picker=True when drawing the Text\n    #dragh = DraggableText(fig)\n    #fig.savefig(os.path.join(fpath, r'nd_cp_crys_lowT0_new.pdf'), bbox_inches=\"tight\", verbose=True) \n    \n    return\n\nfig, ax = plt.subplots(figsize=(3,2.4))#,subplot_kw={'axisbg':'#EEEEEE','axisbelow':True})\n\ninteract(pltFitReg, x1=widgets.FloatSlider(min=5.,max=18,step=0.5,value=10),\n         x2=widgets.FloatSlider(min=11,max=50,step=0.5,value=20),\n         x3=widgets.FloatSlider(min=0.,max=0.2,step=0.005,value=0.0),\n         x4=widgets.FloatSlider(min=0.1,max=0.4,step=0.005,value=0.18))#,__manual=True) \n\ndragh = DraggableText()# must put here not in the function!!\n\n```\n\n\n```python\n# after drag the legend and text, save it\nfig.savefig(os.path.join(fpath, r'nd_cp_crys_lowT000.pdf'), bbox_inches=\"tight\", pad_inches=0.01,verbose=True) \n```\n\n\n```python\n# \uff26\uff49\uff54\u3000\uff57\uff49\uff54\uff48\u3000\uff41\u3000\uff47\uff41\uff50\uff50\uff45\uff44\u3000\uff45\uff58\uff43\uff49\uff54\uff41\uff54\uff49\uff4f\uff4e\uff53\u3000\uff34\uff3e\uff0d\uff12\u3000\uff25\uff58\uff50\uff08\uff0d\uff44\uff45\uff4c\uff54\uff41\uff0f\uff34\uff09\n%matplotlib ipympl\ndef cpnmGap(t,n,a,b):# nuclear + mag\n    return n / t**2 + a/t**2 * np.exp(-b/t)\n\n# Plot to check the starting parameters\nndT, ndCp = fitReg(cpnd,0,0.5)[:,0], fitReg(cpnd,0,0.5)[:,1]\ninvT, logCp = 1/ndT, ndCp * ndT**2\n\ncpNd = np.vstack([invT, logCp]).T\n\n# t = np.linspace(0.01, 0.4, 100)\n# cpfit = cpnmGap(t,0.001,5,1.1)\n\n# x, y = 1/t, np.log2(cpfit * t**2)\n\n# fig, ax = plt.subplots(figsize=(5, 4))\n\n# plt.plot(cpNd[:,0],cpNd[:,1])\n# plt.plot(x,y)\n\n# plt.show()\n\ndef pltFitReg(x1=0,x2=0.3):    \n    global fig, ax\n    plt.cla()  \n    \n    popt, pcov = optimize.curve_fit(cpnmGap, fitReg(cpnd,x1,x2)[:,0], fitReg(cpnd,x1,x2)[:,1], [0.008,4,0.7])\n    print(popt, pcov)\n\n    # plot the raw data\n    ax.plot(cpNd[:,0], cpNd[:,1], 'o', mec='b', mfc='white',label='Total specific heat') \n    # plot the subtracted data\n    cpNuclear = popt[0] /  cpnd[:,0]**2\n    cpSub = cpnd[:,1] - cpNuclear\n    ax.plot(1/cpnd[:,0], cpSub * cpnd[:,0]**2, 'o', mfc='white',label=r'$C\\mathrm{_M}$ ($C\\mathrm{_N}$ subtracted)') \n    \n    # plot the fit (only the mag) and the nuclear\n    t = np.linspace(0.01, 0.6, 100)\n    cpMag = popt[1]/t**2 * np.exp(-popt[2]/t)    \n    ax.plot(1/t, cpMag * t**2, 'r-', label=r'Linear fit ($0.07-0.18\\,$K)' ) \n    ax.plot(1/t, popt[0]/t**2 * t**2, 'b-', label=r'$C_\\mathrm{N}\\sim T^{-2}$')\n    \n#     cpfit = cpnmGap(t,popt[0],popt[1],popt[2])\n#     x, y = 1/t, np.log2(cpfit * t**2)\n#     ax.plot(x, y, 'b--', lw=0.5, alpha=1)\n    \n    ax.set_xlim(2.5, 15) # 1/T limit\n    ax.set_ylim(0.00005, 15)   \n    ax.set_yscale('log')\n    \n    ax.set_ylabel(r'$C\\mathrm{_p}$ (J/K/mol)',size=14,labelpad=2)  \n    ax.set_xlabel(r'$1\\,/\\,$T (K)',size=14,labelpad=2)  \n    ax.tick_params(axis='both',which='both',labelsize=14,width=1,length=3)\n    \n    plt.legend(loc='best',numpoints=1,fontsize=12, frameon=False,framealpha=1)\n    #fig.savefig(os.path.join(fpath, r'nd_cp_crys_lowT1.pdf'), bbox_inches=\"tight\", verbose=True) \n    \n    return #fig\n    \nfig, ax = plt.subplots(figsize=(5, 4))\n\ninteract(pltFitReg, \n         x1=widgets.FloatSlider(min=0,max=0.1,step=0.01,value=0.0),\n         x2=widgets.FloatSlider(min=0.1,max=0.4,step=0.01,value=0.18))#,__manual=True) \n```\n\n\n    Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous \u2026\n\n\n\n    interactive(children=(FloatSlider(value=0.0, description='x1', max=0.1, step=0.01), FloatSlider(value=0.18, de\u2026\n\n\n\n\n\n    <function __main__.pltFitReg(x1=0, x2=0.3)>\n\n\n\n\n```python\n# \uff2e\uff44\uff12\uff33\uff4e\uff12\uff2f\uff17\u3000\uff54\uff52\uff59\uff1a\u3000\uff26\uff49\uff54\u3000\uff57\uff49\uff54\uff48\u3000\uff41\u3000\uff47\uff41\uff50\uff50\uff45\uff44\u3000\uff45\uff58\uff43\uff49\uff54\uff41\uff54\uff49\uff4f\uff4e\uff53\u3000\uff34\uff3e\uff0d\uff12\u3000\uff25\uff58\uff50\uff08\uff0d\uff44\uff45\uff4c\uff54\uff41\uff0f\uff34\uff09\ndef cpnmGap(t,n,a,b):# nuclear + mag\n    return n / t**2 + a/t**2 * np.exp(-b/t)\n\n# Plot to check the starting parameters\nndT, ndCp = fitReg(cpndsn,0,1)[:,0], fitReg(cpndsn,0,1)[:,1]\ninvT, logCp = 1/ndT, ndCp * ndT**2\n\ncpNd = np.vstack([invT, logCp]).T\n\ndef pltFitReg(x1=0,x2=0.8):    \n    global fig, ax\n    plt.cla()  \n    cpnd = cpndsn\n    popt, pcov = optimize.curve_fit(cpnmGap, fitReg(cpnd,x1,x2)[:,0], fitReg(cpnd,x1,x2)[:,1], [0.008,4,0.7])\n    print(popt, pcov, '\\n', 'The gap is:   %4f meV'%(popt[2]/11.6) )\n\n    # plot the raw data\n    ax.plot(cpNd[:,0], cpNd[:,1], 'o', mec='b', mfc='white',label='Total specific heat') \n    # plot the subtracted data\n    cpNuclear = popt[0] /  cpnd[:,0]**2\n    cpSub = cpnd[:,1] - cpNuclear\n    ax.plot(1/cpnd[:,0], cpSub * cpnd[:,0]**2, 'o', mfc='white',label=r'$C\\mathrm{_M}$ ($C\\mathrm{_N}$ subtracted)') \n    \n    # plot the fit (only the mag) and the nuclear\n    t = np.linspace(0.01, 1, 200)\n    cpMag = popt[1]/t**2 * np.exp(-popt[2]/t)    \n    ax.plot(1/t, cpMag * t**2, 'r-', label=r'Linear fit (below %.2f K)'%x2 ) \n    ax.plot(1/t, popt[0]/t**2 * t**2, 'b-', label=r'$C_\\mathrm{N}\\sim T^{-2}$')\n    ax.text(0.5,0.1,r'Nd$_2$Sn$_2$O$_7$',fontsize=14)\n    \n    ax.set_xlim(0.1, 5) # 1/T limit\n    ax.set_ylim(0.0005, 50)   \n    ax.set_yscale('log')\n    \n    ax.set_ylabel(r'$C\\mathrm{_p}$ (J/K/mol)',size=14,labelpad=2)  \n    ax.set_xlabel(r'$1\\,/\\,$T (K)',size=14,labelpad=2)  \n    ax.tick_params(axis='both',which='both',labelsize=14,width=1,length=3)\n    \n    plt.legend(loc='best',numpoints=1,fontsize=12, frameon=False,framealpha=1)\n    #fig.savefig(os.path.join(fpath, r'nd_cp_crys_lowT1.pdf'), bbox_inches=\"tight\", verbose=True) \n    \n    return #fig\n    \nfig, ax = plt.subplots(figsize=(5, 4))\n\ninteract(pltFitReg, \n         x1=widgets.FloatSlider(min=0,max=5,step=0.01,value=0.0),\n         x2=widgets.FloatSlider(min=0.1,max=1.0,step=0.01,value=0.4))#,__manual=True) \n```\n\n\n    Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous \u2026\n\n\n\n    interactive(children=(FloatSlider(value=0.0, description='x1', max=5.0, step=0.01), FloatSlider(value=0.4, des\u2026\n\n\n\n\n\n    <function __main__.pltFitReg(x1=0, x2=0.8)>\n\n\n\n## Calucualte entropy: old, subtract fitted phonon and nuclear\n\n\n```python\n# \uff23\uff41\uff4c\uff43\uff55\uff4c\uff41\uff54\uff45\u3000\uff45\uff4e\uff54\uff52\uff4f\uff50\uff59\uff1a\u3000\uff54\uff57\uff4f\u3000\uff4d\uff45\uff54\uff48\uff4f\uff44\uff53\n%matplotlib notebook\n##############################\n# 1st method: use interplatation (not good) take long time\nfrom scipy.integrate import quad, cumtrapz\nfrom scipy.interpolate import interp1d\n\n# subtract nuclear and magnon contributions\n# take care of 'R*' in the defined functions\ncpsub = cpnd[:,1] - cpNuclear(cpnd[:,0], 3.19721123e-04) - cpph1(cpnd[:,0], 1.22717554e-06, 4.12695321e+00)\ncpt = np.array(cpsub) / cpnd[:,0]\n\n# interplatation functions\ncpinter= interp1d(cpnd[:,0],cpsub)\ncptinter= interp1d(cpnd[:,0],cpt)\n\n# plot\nfig, ax = plt.subplots(figsize=(5, 4))\nax.plot(cpnd[:,0],cpsub)\n\nx = np.linspace(0.072,18,500)\n#ax.plot(x,np.interp(x, cpnd[:,0],cpsub))\nax.plot(x,cpinter(x))\nax.set_xscale('log')\nax.set_yscale('log')\nplt.show()\n\n# calculate entropy\ndef entropy(t):\n    return quad(cptinter,0.072,t)[0]/R/np.log2(2)\nprint(entropy(18))\n# fig, ax = plt.subplots(figsize=(5, 4))\n# ax.plot(x,[entropy(x) for  x in x]) #take long time\n# fig.show()\n\n##############################\n#2nd method\ncpsub = cpnd[:,1] - cpNuclear(cpnd[:,0], 3.19721123e-04) - cpph1(cpnd[:,0], 1.22717554e-06, 4.12695321e+00)\n\ncpt = np.array(cpsub) / cpnd[:,0]\nentropy = cumtrapz(cpt,cpnd[:,0], initial=0)/R/np.log(2)\n\nfig, ax = plt.subplots(figsize=(5, 4))\nax.plot(cpnd[:,0],entropy,'-')\nax.set_xlim(0,10)\nfig.show()\n```\n\n    Warning: Cannot change to a different GUI toolkit: notebook. Using ipympl instead.\n\n\n\n    Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous \u2026\n\n\n    1.3473731530833808\n\n\n    C:\\ProgramData\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:30: IntegrationWarning: The maximum number of subdivisions (50) has been achieved.\n      If increasing the limit yields no improvement it is advised to analyze \n      the integrand in order to determine the difficulties.  If the position of a \n      local difficulty can be determined (singularity, discontinuity) one will \n      probably gain from splitting up the interval and calling the integrator \n      on the subranges.  Perhaps a special-purpose integrator should be used.\n\n\n\n    Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous \u2026\n\n\n## Calucualte entropy: new, subtract La phonon and nuclear (fitted gapped magons)\n\n\n```python\nfrom scipy.integrate import quad, cumtrapz\nfrom scipy.interpolate import interp1d\n\n# Subtract nuclear and La phonon\ncpNu = 0.00613702 /  cpnd[:,0]**2\ncpLaInter = interp1d(cpla[:,0], cpla[:,1])\n\ncpsub = cpnd[:,1] - cpNu\n\nmask = np.array( np.where( (cpnd[:,0]>cpla[:,0].min()) & (cpnd[:,0]<30) ) ).ravel()\ncpsub[mask] = cpsub[mask] - cpLaInter(cpnd[mask,0])\n\ncpt = np.array(cpsub) / cpnd[:,0]\nentropy = cumtrapz(cpt,cpnd[:,0], initial=0.1)/2/R/np.log(2)\nprint(entropy[cpnd[:,0]<=10].max())\n\nfig, ax = plt.subplots(figsize=(5, 4))\nax.plot(cpnd[:,0],entropy,'-')\nax.set_xlim(0,90)\nax.set_ylim(0,4)\nfig.canvas.layout.width = '5in'\nfig.canvas.layout.height= '4in'\nfig.show()\n```\n\n    0.9114454556671989\n\n\n    C:\\ProgramData\\Anaconda3\\lib\\site-packages\\matplotlib\\pyplot.py:514: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).\n      max_open_warning, RuntimeWarning)\n\n\n\n    Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous \u2026\n\n\n\n```python\n# \uff46\uff49\uff54\u3000\uff14\u3000\uff50\uff41\uff52\uff41\uff4d\uff45\uff54\uff45\uff52\uff53\uff0c\u3000\uff4e\uff0c\uff4d\u3000\uff08\uff4e\uff55\uff43\uff4c\uff45\uff41\uff52\uff09\uff0c\u3000\uff41\uff0c\uff42\u3000\uff08\uff4d\uff41\uff47\uff49\uff4f\uff4e\uff09\uff1b\u3000\uff46\uff49\uff54\u3000\uff54\uff48\uff45\u3000\uff45\uff58\uff50\uff4f\uff4e\uff45\uff4e\uff54\u3000\uff46\uff4f\uff52\u3000\uff4e\uff55\uff43\uff4c\uff45\uff41\uff52\u3000\uff23\uff50\u3000\uff41\uff4c\uff53\uff4f\n\ndef pltFitReg(x1,x2):\n    popt, pcov = optimize.curve_fit(lambda t, n,m, a, b: cpnm1(t, n,m,a,b), fitReg(cpnd,x1,x2)[:,0], fitReg(cpnd,x1,x2)[:,1], [0.00065,2, 50, 3])\n    #popt, pcov = optimize.curve_fit(cpnm1, fitReg(cpnd,x1,x2)[:,0], fitReg(cpnd,x1,x2)[:,1], [0.00065, 2, 50, 3])\n    print(popt)\n    \n    global fig, ax\n    plt.cla()\n    ax.grid(color='w', linewidth=2, linestyle='solid')\n    ax.plot(cpnd[:,0], cpnd[:,1] , 'o', mfc='none')\n\n    t = np.linspace(0.01, 1, 100)\n\n    ax.plot(t, cpNuclear1(t, popt[0],popt[1]), 'b--', lw=0.5, alpha=1)\n    ax.plot(t, cpMag(t, popt[2], popt[3]), 'b--', lw=0.5, alpha=1)\n    ax.plot(t, cpnm1(t,popt[0],popt[1],popt[2],popt[3]), color='r', lw=1, alpha=1)\n       \n    ax.set_xlim(0.05, 1)\n    ax.set_ylim(0.1, 15)\n    ax.set_xscale('log')\n    ax.set_yscale('log')\n    #fig.show()\n    return #fig\n\nfig, ax = plt.subplots(figsize=(5, 4))#,subplot_kw={'axisbg':'#EEEEEE','axisbelow':True})\nfig.canvas.layout.width = '5in'\nfig.canvas.layout.height= '4in'\ninteract(pltFitReg, x1=(0,0.2,0.01), x2=(0.1,0.4,0.005),continuous_update=False)\n\n```\n\n    C:\\ProgramData\\Anaconda3\\lib\\site-packages\\matplotlib\\pyplot.py:514: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).\n      max_open_warning, RuntimeWarning)\n\n\n\n    Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous \u2026\n\n\n\n    interactive(children=(FloatSlider(value=0.1, description='x1', max=0.2, step=0.01), FloatSlider(value=0.25, de\u2026\n\n\n\n\n\n    <function __main__.pltFitReg(x1, x2)>\n\n\n\n## Cp of Nd2Zr2O7 with field along [111]\n1. Plot all; \n2. load and strore all data\n3. Maually subtraction for each data and fitting data with gapped magon+neclear\n\n\n```python\n#\u3000\uff23\uff50\u3000\uff49\uff4e\u3000\uff46\uff49\uff45\uff4c\uff44\uff53\u3000\uff10\uff0c\u3000\uff10\uff0e\uff12\uff0c\u3000\uff10\uff0e\uff15\uff0c\u3000\uff12\uff34\nimport numpy as np\nimport fnmatch\nimport os\n\nfpath = r'D:\\3_Physical Properties\\Heat_Capacity\\1_Cp_NdZrO_Ausburg'\nfname = r'C vs T_Nd2Zr2O7_*.txt'\n#sns.set()\n#sns.reset_orig()\nfig, ax = plt.subplots(figsize=(2, 3))\n#flatui = [\"#9b59b6\", \"#3498db\", \"#95a5a6\", \"#e74c3c\", \"#34495e\", \"#2ecc71\"]\n#ax.set_color_cycle(sns.color_palette('husl',5))\n#sns.set_style(\"white\")\n\nax.set_xscale('log')\nax.set_yscale('log')\nfor file in os.listdir(fpath):\n    if fnmatch.fnmatch(file, fname):      \n        print(file)\n        temp = np.genfromtxt(os.path.join(fpath,file), usecols=(0,2), skip_header=1)      \n        #with plt.style.context(u'seaborn-dark-palette'):\n        ax.plot(temp[:,0],temp[:,1],'o', mfc=None, ms='4')\nx = np.linspace(0.01,0.5,20)        \nax.plot(x,cpNuclear(x,6.1e-04),color='black')                \nax.set_xlim(0.05, 1.5)\nax.set_ylim(0.2, 18)      \nfig.canvas.layout.width = '4in'\nfig.canvas.layout.height= '5in'\nplt.show()\n```\n\n\n```python\n# \u3000\uff34\uff45\uff53\uff54\uff1a\u3000\uff4c\uff4f\uff41\uff44\uff0c\u3000\uff46\uff49\uff54\u3000\uff4e\uff55\uff43\uff4c\uff45\uff41\uff52\u3000\uff23\uff50 \uff41\uff4e\uff44\u3000\uff50\uff4c\uff4f\uff54\nfpath = r'D:\\3_Physical Properties\\Heat_Capacity\\1_Cp_NdZrO_Ausburg'\nfname = r'C vs T_Nd2Zr2O7_*.txt'\n\nfitHlim = [0.1,0.1,0.09,0.1,0.2] # high limit the fitting region for data 0.2T, 0.5T, 0T, 1T, 2T\n\nfig, ax = plt.subplots(figsize=(2.5, 4))\nax.set_xscale('log')\nax.set_yscale('log')\n\nidx = 0\nfor file in os.listdir(fpath):\n    if fnmatch.fnmatch(file, fname):      \n        print(file)\n        temp = np.genfromtxt(os.path.join(fpath,file), usecols=(0,2), skip_header=1)      \n        \n        fitLims = np.ravel([temp[:,0].min(),fitHlim[idx]])\n        print('fitLimits:', fitLims)\n        popt, pcov = optimize.curve_fit(cpNuclear, fitReg(temp,fitLims)[:,0],fitReg(temp,fitLims)[:,1] , [0.00065])\n        print('fit:', popt)\n        \n        idx = idx +1\n        \n        dataPlot, = ax.plot(temp[:,0],temp[:,1],'o',mec=None, ms='4')\n        t = np.linspace(0.05, 1, 100)\n        ax.plot(t, cpNuclear(t, popt[0]), 'b--', lw=0.5, alpha=1,color=dataPlot.get_color())\n        \n#x = np.linspace(0.01,0.5,20)        \n#ax.plot(x,cpNuclear(x,3.1e-04),color='black')        \n\nax.set_xlim(0.05, 1.5)\nax.set_ylim(0.2, 18)    \nfig.canvas.layout.width = '4in'\nfig.canvas.layout.height= '5in'\n\nplt.show()\n```\n\n\n```python\n# \uff2c\uff4f\uff41\uff44\u3000\uff41\uff4e\uff44\u3000\uff53\uff54\uff4f\uff52\uff45\u3000\uff41\uff4c\uff4c\u3000\uff54\uff48\uff45\u3000\uff44\uff41\uff54\uff41 in fields 0.2T, 0.5T, 0T, 1T, 2T\n# find out the number of files and their names and lengths\nfnamestr = []\nflengths = []\nfor file in os.listdir(fpath):\n    if fnmatch.fnmatch(file, fname): \n        #print fname\n        fnamestr.append(os.path.join(fpath,file))\n        temp = np.genfromtxt(os.path.join(fpath,file), usecols=(0,2), skip_header=1)  \n        flengths.append(len(temp))\n#print fnamestr, flengths \n#print max(flengths)\n\n# store data into a array, short data is appended 'nan'\ndata = np.zeros((max(flengths),2*5))\ndata[:,:] = np.nan\n\nidx = 0\nfor file in os.listdir(fpath):\n    if fnmatch.fnmatch(file, fname): \n        temp = np.genfromtxt(os.path.join(fpath,file), usecols=(0,2), skip_header=1)  \n        temp = temp[temp[:, 0].argsort()]\n        print(file, temp.shape)\n        data[:flengths[idx],idx*2:idx*2+2] = temp[:,:] # Sort: the temperature not increases monotonically for 1T data\n        idx = idx + 1\n\n# Export data for owen\n# print fnamestr\n# idx = 0\n# for i in [2,0,1,3,4]:\n#     file = fnamestr[i]\n#     temp = np.genfromtxt(file, usecols=(0,2), skip_header=1)  \n#     temp = temp[temp[:, 0].argsort()]\n#     print file, temp.shape\n#     data[:len(temp),idx*2:idx*2+2] = temp[:,:] # Sort: the temperature not increases monotonically for 1T data\n#     idx = idx + 1\n# np.savetxt(os.path.join(fpath,'Nd2Zr2O7_Cp_0-1K_field-[111]-0_0p2_0p5_1_2T_rawdata.txt'),data)\n```\n\n    C vs T_Nd2Zr2O7_0.2T.TXT (118, 2)\n    C vs T_Nd2Zr2O7_0.5T.TXT (102, 2)\n    C vs T_Nd2Zr2O7_0T.TXT (119, 2)\n    C vs T_Nd2Zr2O7_1T.TXT (108, 2)\n    C vs T_Nd2Zr2O7_2T.TXT (79, 2)\n\n\n\n```python\n# \u3000\uff2d\uff41\uff4e\uff55\uff41\uff4c\uff4c\uff59\u3000\uff53\uff55\uff42\uff53\uff54\uff52\uff41\uff43\uff54\u3000\uff4e\uff55\uff43\uff4c\uff45\uff41\uff52\u3000\uff23\uff50\u3000\uff41\uff4e\uff44\u3000\uff50\uff4c\uff4f\uff54\n%matplotlib ipympl\ndatIdx= {'0.2T':0, '0.5T':1, '0T':2, '1T':3, '2T':4}\ndef manSub(whichD='0T', n=0.0007):\n    global fig, ax, data\n    plt.cla()   \n    dat = data[:, datIdx[whichD]*2:datIdx[whichD]*2+2]   \n    ax.plot(dat[:,0], dat[:,1], 'o', mec='none')\n    cpNcal = cpNuclear(dat[:,0], n)\n    ax.plot(dat[:,0], cpNcal, 'b--', lw=0.5)\n    ax.plot(dat[:,0],dat[:,1]-cpNcal, 'o', mec='none')\n        \n    ax.set_xlim(0.01, 1.2)\n    ax.set_ylim(0.05, 18)\n    ax.set_xscale('log')\n    ax.set_yscale('log')\n       \n    ax.set_ylabel(r'Cp (J/K/mol Nd)',size=14,labelpad=-1)  \n    ax.set_xlabel(r'T (K)',size=14,labelpad=-1)  \n    #ax.tick_params(axis='both',which='both',labelsize=14,width=1,length=3)\n    #plt.show() # remove it otherwise two fig show\n    #plt.draw() # for using extra fig window: plt.draw() and return fig.show()\n    return #fig #.show()\n#sns.reset_orig()\nfig, ax = plt.subplots(figsize=(5, 4))\nfig.canvas.layout.width = '5in'\nfig.canvas.layout.height= '4in'\n#RadioButtons\ninteract(manSub, whichD = widgets.Dropdown(description='Which data:',options=['0T', '0.2T', '0.5T','1T','2T']),\n         n= widgets.FloatSlider(min=0.0001,max=0.001,step=0.00001,value=0.0008),__manual=True) \n```\n\n\n    Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous \u2026\n\n\n\n    interactive(children=(Dropdown(description='Which data:', options=('0T', '0.2T', '0.5T', '1T', '2T'), value='0\u2026\n\n\n\n\n\n    <function __main__.manSub(whichD='0T', n=0.0007)>\n\n\n\n\n```python\n# \uff26\uff49\uff54\u3000\uff57\uff49\uff54\uff48\u3000\uff41\u3000\uff47\uff41\uff50\uff50\uff45\uff44\u3000\uff45\uff58\uff43\uff49\uff54\uff41\uff54\uff49\uff4f\uff4e\uff53\u3000\uff34\uff3e\uff0d\uff12\u3000\uff25\uff58\uff50\uff08\uff0d\uff44\uff45\uff4c\uff54\uff41\uff0f\uff34\uff09\n%matplotlib ipympl\n\ndef cpmGap(t,a,b):\n    return a/t**2 * np.exp(-b/t)\ndef cpnmGap(t,n,a,b):# nuclear + mag\n    return n / t**2 + cpmGap(t,a,b)\n\n# Functions below cal a=R/2*(b/t)^2\n# kb = 1.38*10**-23 # in J/K \n# R = 8.31; # in J/K/mol\n# def cpmGap(t,a,b):# per mole Nd2, the un-used 'a' for keeping consistent with first def. above\n#     return R/2. * b**2/t**2 * np.exp(-b/t)\n# def cpnmGap(t,n,a,b):# nuclear + mag\n#     return n / t**2 +  cpmGap(t,a,b)\n\n\ndatIdx= {'0.2 T':0, '0.5 T':1, '0 T':2, '1 T':3, '2 T':4}# the order in the data matrix\n\ndef WhichDataRegPlot(whichD='0T', x1=0, x2=0.3):    \n    global fig, ax, fig1, ax1\n    ax.cla();ax1.cla()  \n    \n    # By '2*' we have per mol Nd2Zr2O7!!!!!\n    cpnd = np.vstack( ( data[:,datIdx[whichD]*2], 2 * data[:,datIdx[whichD]*2+1] ) ).T# Cp data of Nd at which field\n    #cpnd[:,1] = 2 * cpnd[:,1] # not working: *2 every time change the data set \n    \n    ndT, ndCp = fitReg(cpnd,0,0.5)[:,0], fitReg(cpnd,0,0.5)[:,1]\n    invT, logCp = 1/ndT, ndCp * ndT**2\n    cpNd = np.vstack([invT, logCp]).T\n\n    popt, pcov = optimize.curve_fit(cpnmGap, fitReg(cpnd,x1,x2)[:,0],fitReg(cpnd,x1,x2)[:,1], [0.007,4,0.7])\n    print('fitted par', popt,'\\n', 'error', np.sqrt(np.diag(pcov)) )\n\n    # plot the raw data\n    ax.plot(cpNd[:,0], cpNd[:,1], 'o', mec='b', mfc='white',label='Total specific heat'+' (%s)'%whichD) \n    # plot the subtracted data\n    cpNuclear = popt[0] /  cpnd[:,0]**2\n    cpSub = cpnd[:,1] - cpNuclear\n    ax.plot(1/cpnd[:,0], cpSub * cpnd[:,0]**2, 'o', mfc='white',label=r'$C\\mathrm{_M}$ ($C\\mathrm{_N}$ subtracted)') \n    \n    # plot the fit (only the mag)\n    t = np.linspace(0.01, 0.6, 100)\n    cpMag = cpmGap(t,popt[1],popt[2])\n    ax.plot(1/t, cpMag * t**2, 'r-', label=r'Linear fit (below %.2f K)'%x2 )#r'Linear fit (%.2f-%.2f K)'%(x1, x2) ) \n    \n    #ax.axvspan(1/x1, 1/x2, alpha=0.5, color='lightgrey')    \n    #ax.text(1/((x1+x2)/2), 0.05,r'Fitted'+'\\n'+'region',size=13, ha='center', va='center',\n    #         backgroundcolor='white',bbox=dict(facecolor='white', alpha=0, edgecolor='white', boxstyle='round'))\n    \n    ax.set_xlim(1, 16) # 1/T limit\n    ax.set_ylim(0.000001, 15)   \n    ax.set_yscale('log')\n    \n    ax.set_ylabel(r'$C\\mathrm{_p}T^2$ (JK/mol)',size=14,labelpad=2)  \n    ax.set_xlabel(r'$T^{-1}\\ (\\mathrm{K}^{-1})$',size=14,labelpad=2)  \n    ax.tick_params(axis='both',which='both',labelsize=14,width=1,length=3)\n    \n    plt.legend(loc='best',numpoints=1,frameon=False,framealpha=1)\n    #fig.savefig(os.path.join(fpath, 'nd_cp_crys_lowT_' + '%s'%whichD.replace(\" \", \"\") + '.pdf'), bbox_inches=\"tight\", verbose=True) \n    \n    ax1.plot(cpnd[:,0],cpnd[:,1],'ro',label='data')\n    t = np.linspace(0.05,0.4)\n    #cpMag = popt[1]/t**2 * np.exp(-popt[2]/t)  \n    cpMag = cpmGap(t,popt[1], popt[2])\n    ax1.plot(t,cpMag,label='fit')\n    ax1.plot(t,popt[0] / t**2,label='Nuclear')\n    return #fig\n    \nfig, ax = plt.subplots(figsize=(5, 4))\nfig1,ax1  = plt.subplots(figsize=(5, 4))\nfig.canvas.layout.width = '5in'\nfig.canvas.layout.height= '4in'\nfig1.canvas.layout.width = '5in'\nfig1.canvas.layout.height= '4in'\n\ninteract(WhichDataRegPlot, \n         whichD = widgets.Dropdown(description='Which data:',options=['0 T','0.2 T','0.5 T','1 T','2 T']),\n         x1=widgets.FloatSlider(min=0,max=0.1,step=0.01,value=0.07),\n         x2=widgets.FloatSlider(min=0.1,max=0.4,step=0.01,value=0.18))#,__manual=True) # For 2T use x2=0.25!!!!!\n[0.0075,0.011,0.0062,0.011,0.0158]\n```\n\n\n    Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous \u2026\n\n\n\n    Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous \u2026\n\n\n\n    interactive(children=(Dropdown(description='Which data:', options=('0 T', '0.2 T', '0.5 T', '1 T', '2 T'), val\u2026\n\n\n\n\n\n    [0.0075, 0.011, 0.0062, 0.011, 0.0158]\n\n\n\n\n```python\n# \uff34\uff41\uff4b\uff45\u3000\uff54\uff48\uff45\u3000\uff50\uff41\uff52\uff53\u3000\uff46\uff4f\uff55\uff4e\uff44\u3000\uff4d\uff41\uff4e\uff55\uff41\uff4c\uff4c\uff59\u3000\uff41\uff42\uff4f\uff56\uff45\u3000\uff41\uff4e\uff44\u3000\uff50\uff4c\uff4f\uff54\u3000\uff41\uff4c\uff4c\u3000\uff23\uff50\uff0c\u3000\uff33\uff55\uff42\u3000\uff41\uff4e\uff44\u3000\uff23\uff50\u3000\uff4e\uff55\uff43\uff4c\uff45\uff41\uff52\n#plt.style.use(u'classic')#u'seaborn-paper')\n\np_lab = ['0.2 T', '0.5 T', '0 T','1 T','2 T']\nnuclearN = [0.0075,0.011,0.0062,0.011,0.0158] #Fited T^-2+T^2Exp(-d/T) (2mol Nd)the parameter for nuclear Cp\nlab_pos = np.array([[0.46,8.5],[0.5,5.7],[0.44,13],[0.25,1.6],[0.35,0.85]]) # Text position for 2mol Nd\n#colors =[\"#9b59b6\", \"#3498db\", \"#95a5a6\", \"#e74c3c\", \"#34495e\", \"#2ecc71\"]\ncolors =  ['red','blue', 'green','purple', 'orange' ]\n#colors = sns.color_palette(\"hls\", 5)\n\nfig, ax = plt.subplots(figsize=(4,5))\nt = np.linspace(0.01, 0.6, 100) \nfor idx, didx in enumerate([2,0,1,3,4]): # plot low field data first: 0T, 0.2T...\n\n    dat = np.vstack( [data[:, didx*2], 2*data[:, didx*2+1] ] ).T #data[:, didx*2 : didx*2+2]\n    # plot raw data\n    ax.plot(dat[:,0], dat[:,1], 'o',ms=4, mec='none', mfc = colors[idx], label=p_lab[didx])\n    # plot nuclear and subtracted\n    ax.plot(t, nuclearN[didx]*t**-2, '--',lw= 0.5, c=colors[idx], label=r'$C_\\mathrm{N}\\sim T^{-2}$')   \n    ax.plot(dat[:,0], dat[:,1] - nuclearN[didx]*dat[:,0]**-2, 'o',ms=4, mfc='white', mec=colors[idx])\n    \n    ax.text(lab_pos[didx,0],lab_pos[didx,1], p_lab[didx],size=14, ha='left', va='center',color=colors[idx],picker=True,\n            backgroundcolor='white',bbox=dict(facecolor='white', alpha=0, edgecolor='white', boxstyle='round'))\n        \nax.set_xlim(0.06, 1.2)\nax.set_ylim(0.1, 20)\nax.set_xscale('log')\nax.set_yscale('log')\n       \nax.set_ylabel(r'$C\\mathrm{_p}$ (J/K/mol)',size=14,labelpad=-1)  \nax.set_xlabel(r'T (K)',size=14,labelpad=-1)  \nax.tick_params(axis='both',which='both',labelsize=14,width=1,length=3)\n    \n#plt.legend(loc='best')\n\ntxt1= ax.text(0.07,9.5,r'Nd$_2$Zr$_2$O$_7$'+ '\\n'+'crystal'+'\\n' + r'H$\\parallel~$[111]',size=14, ha='left', va='center',\n        backgroundcolor='white',picker=True,bbox=dict(facecolor='white', alpha=0, edgecolor='white', boxstyle='round'))\n\nax.text(0.31,0.28,r'Solid: raw data' +'\\n'+ r'Open: 4f part'+'\\n'+ r'Dashed: nuclear', \n        size=13, ha='left', va='center',picker=True,\n        backgroundcolor='white',bbox=dict(facecolor='white', alpha=0, edgecolor='white', boxstyle='round'))\n#dragh = DragTextHandler()#set picker=True when drawing the Text\ndragh = DraggableText()\n#fig.savefig(os.path.join(fpath, r'nd_cp_crys_lowT_allH_dragg1.pdf'), bbox_inches=\"tight\", verbose=True) \nfig.canvas.layout.width = '4in'\nfig.canvas.layout.height= '5in'\n#https://github.com/matplotlib/jupyter-matplotlib/issues/117\nplt.show()\n```\n\n    C:\\ProgramData\\Anaconda3\\lib\\site-packages\\matplotlib\\pyplot.py:514: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).\n      max_open_warning, RuntimeWarning)\n\n\n\n    Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous \u2026\n\n\n\n```python\n# \uff23\uff41\uff4c\uff43\uff55\uff4c\uff41\uff54\uff45\u3000\uff41\uff4e\uff44\u3000\uff50\uff4c\uff4f\uff54\u3000\uff45\uff4e\uff54\uff52\uff4f\uff50\uff59\u3000\uff41\uff46\uff54\uff45\uff52\u3000\uff53\uff55\uff42\uff53\uff54\uff52\uff41\uff43\uff54\uff49\uff4f\uff4e\u3000\uff54\uff48\uff45\u3000\uff4e\uff55\uff4c\uff45\uff41\uff52\u3000\uff50\uff41\uff52\uff54\nfrom scipy.integrate import simps, cumtrapz\np_lab = ['0.2 T', '0.5 T', '0 T','1 T','2 T']\nnuclearN = [0.00035,0.0005,0.0003,0.00062,0.0008] # old manual parameter for nuclear Cp 1 mol Nd\nnuclearN = [0.0075,0.011,0.0062,0.011,0.0158] #Fited T^-2+T^2Exp(-d/T) (2mol Nd)the parameter for nuclear Cp\nlab_pos = np.array([[0.15,4.9],[0.82,6.49],[0.43,7.92],[0.88,5.07],[0.91,2.65]])\ncolors = [ 'red', 'blue', 'green','purple', 'orange']\n\nfig, ax = plt.subplots(figsize=(4,5))\nfor idx, didx in enumerate([2,0,1,3,4]): # plot low field data first: 0T, 0.2T...\n    dat = np.vstack( [data[:, didx*2], 2*data[:, didx*2+1] ] ).T # data[:, didx*2 : didx*2+2]\n    cptSub = (dat[:,1]- nuclearN[didx]*dat[:,0]**-2) / dat[:,0]  # Cp/T\n\n    entropy = cumtrapz(cptSub, dat[:,0], initial=0)#/R/np.log(2)\n    #entropy = np.array([simps(cptSub[:t+1], dat[:t+1,0]) for t in range(len(dat))])/R/np.log(2)\n    \n    ax.plot(dat[:,0],entropy,'o',ms=4, mfc='white', mec=colors[idx])\n    ax.plot((0, 2), (2*R*np.log(2), 2*R*np.log(2)), 'k-')\n    ax.text(lab_pos[didx,0],lab_pos[didx,1], p_lab[didx],size=14, ha='left', va='center',color=colors[idx],picker=True,\n            backgroundcolor='white',bbox=dict(facecolor='white', alpha=0, edgecolor='white', boxstyle='round'))\n    \nax.text(0.9,10.6,r'$2\\,R\\,\\ln(2)$',size=14, ha='left', va='center',color='black',picker=True,\n        backgroundcolor='white',bbox=dict(facecolor='white', alpha=0, edgecolor='white', boxstyle='round'))    \nax.text(0.05,9.7,r'Nd$_2$Zr$_2$O$_7$'+ '\\n'+'crystal'+'\\n' + r'H$\\parallel~$[111]',size=14, ha='left', va='center',\n        picker=True,backgroundcolor='white',bbox=dict(facecolor='white', alpha=0, edgecolor='white', boxstyle='round'))\n\nax.set_xlim(0.0, 1.2)\nax.set_ylim(-0.5, 12)    \nax.set_ylabel(r'S (J/K/mol)',size=14,labelpad=5)  \nax.set_xlabel(r'T (K)',size=14,labelpad=5)  \nax.tick_params(axis='both',which='both',labelsize=14,width=1,length=3) \ndragTxt = DraggableText()\nfig.canvas.layout.width = '4in'\nfig.canvas.layout.height= '5in'\n#fig.savefig(os.path.join(fpath, r'nd_cpS_crys_lowT_allH1.pdf'), bbox_inches=\"tight\", verbose=True) \nplt.show()\n```\n\n    C:\\ProgramData\\Anaconda3\\lib\\site-packages\\matplotlib\\pyplot.py:514: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).\n      max_open_warning, RuntimeWarning)\n\n\n\n    Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous \u2026\n\n\n# Theoretical neuclear Cp in different fields\n\u6ce8\u610f\u6539\u4e0a\u56fe\u7684 per mol Nd2 not mol Nd\n\n\n```python\n##### Define function for calculate and plot crystal field heat capacity\nimport sympy as sp # for calculating derivative\nkb = 1.38*10**-23 # in J/K\nnmol = 6.02*10**23; \nR = 8.31; # in J/K/mol\nt = sp.symbols('t')\n\ndef cefcp(t, elevels, degen): # in K, meV, number\n    # this fun retures a sympy object containing symbol 't'\n    e = elevels*11.606*kb # in J\n    g = degen\n    energy = nmol*sum([ei*gi*sp.exp(-ei/kb/t) for ei,gi in zip(e, g)])/sum([gi*sp.exp(-ei/kb/t) for ei,gi in zip(e, g)])\n    cp = sp.diff(energy,t)# sp.Sum can not sum over a python list, but sum can and sp.diff works on the summation\n    return cp\n\ndef lamcefcp(elevels, degen):\n    # return a fun that take the temperature as varable which can be array\n    cefcpv = sp.lambdify(t, cefcp(t, elevels, degen), modules=['numpy', 'sympy'])\n    return cefcpv\n\ndef plotcp(tRange, npts, elevels, degen):   \n    temps = np.linspace(tRange[0],tRange[1],num=npts,endpoint=True)\n    cefcpv = lamcefcp(elevels, degen)  \n    cefcpdat = cefcpv(temps)\n    #fig, ax = plt.subplots()\n    global fig, ax\n    plt.plot(temps, cefcpdat)\n    #fig.show()\n    return\n```\n\n\n```python\n# \uff23\uff41\uff4c\uff43\uff55\uff4c\uff41\uff54\uff45\u3000\uff54\uff48\uff45\u3000\uff4e\uff55\uff43\uff4c\uff45\uff41\uff52\u3000\uff48\uff59\uff50\uff45\uff52\uff46\uff49\uff4e\uff45\u3000\uff3a\uff45\uff45\uff4d\uff41\uff4e\u3000\uff53\uff50\uff4c\uff49\uff54\uff54\uff49\uff4e\uff47\n%matplotlib inline\nmun = 3.1524512550e-5 # nuclear magneton in meV/T\nA143 = 0.0209 # in T, hyperfine constant for Nd143 in G: Zeeman gap = m(Nd e moment)*A (Ref: Phys. Rev. B 19, 5495 (1979).)\nA145 = 0.0131\ngamma143 = -14.57e6 # gyomagnetic ratio of Nd143 in rad s\u22121 T\u22121, Ref. Bertin A. PhD thesis\ngamma145 = -8.894630e5 # calculated\nhbar = 4.135667662e-12/(2*np.pi) # in meV/s\nmub = 5.7883818012e-2 # Bohr magneton in meV/T\n\nmagf = [0., 0.2, 0.5, 1.0, 2.0]\norderM = [1.3, 1.8, 2.0, 2.3, 2.6]\norderM = np.hstack( ([1.3], np.array([0.7, 0.9, 1.0, 1.15])/1.15*2.5) ) # cal. ordered moment base on the MH in Ref.\nprint(orderM)\n\nfig, ax = plt.subplots(figsize=(5, 4))\n\ntRange, npts = [0.01, 2.0], 501\ntemps = np.linspace(tRange[0],tRange[1],num=npts,endpoint=True)\nfor idx, didx in enumerate([2,0,1,3,4]): # plot low field data first: 0T, 0.2T...\n    dat = np.vstack( [data[:, didx*2], 2*data[:, didx*2+1] ] ).T #data[:, didx*2 : didx*2+2]\n    # plot raw data\n    ax.plot(dat[:,0], dat[:,1], 'o',ms=4, mec='none', mfc = colors[idx], label=p_lab[didx])\n\nfor i in np.arange(0,5):# the magnetic fields in T\n    #energy levels in meV; total splitting = (7/2*2+1)*gap, where gap is A*M_ordered + dI*hbar*gamma*magF\n    # assume B_hyper and applied B are parallel\n    e1 = np.linspace(0, (A143*orderM[i]*mub + hbar*gamma143*1.*magf[i])*8,8) \n    g1 = np.ones(8) #Degenercy \n    e2 = np.linspace(0, (A145*orderM[i]*mub + hbar*gamma145*1.*magf[i])*8,8) \n    g2 = np.ones(8) #Degenercy \n    cefcpv1, cefcpv2 = lamcefcp(e1,g1), lamcefcp(e2,g2)  \n    cefcpdat = 12.0/100*cefcpv1(temps) + 8.0/100*cefcpv2(temps)# add aboundance\n    ax.plot(temps, 2*cefcpdat,c=colors[i]) #,label='%s'%magf[i]+' T') # per mol Nd2\n    # fit the high T part with A*T^-2\n    popt, pcov = optimize.curve_fit(lambda x, A: A * x**-2, temps[150:], 2*cefcpdat[150:], [0.01])\n    print(popt)\n    \n#plt.axvline(0.07,color='black')      \nax.set_xlim([0.05,1.2])\nax.set_ylim([0.3,15])\nax.set_xscale('log')\nax.set_yscale('log')\nplt.minorticks_on() \nax.tick_params(axis='both',which='both',labelsize=14)   \nax.set_ylabel(r'Nuclear $C_\\mathrm{p}$ (J/K/mol)',size=14,labelpad=5)  \nax.set_xlabel(r'T (K)',size=14,labelpad=5)  \nax.legend(loc='best' ,numpoints=1,frameon=False,framealpha=1,fontsize=14,handletextpad=0)\nax.text(0.55,0.15,'Lines: calc. nuclear \\nspecific heat using \\nstatic moments',size=14, ha='left', va='center',transform=ax.transAxes,\n        backgroundcolor='white',bbox=dict(facecolor='white', alpha=0, edgecolor='white', boxstyle='round'))\n#fig.canvas.layout.width = '5in'\n#fig.canvas.layout.height= '4in'\nfig.savefig(os.path.join(fpath, r'nd_cal_nuclearCp.pdf'), bbox_inches=\"tight\", verbose=True) \nfig.show()\n```\n\n\n```python\n# \uff23\uff41\uff4c\uff43\uff55\uff4c\uff41\uff54\uff45\u3000\uff54\uff48\uff45\u3000\uff4e\uff55\uff43\uff4c\uff45\uff41\uff52\u3000\uff48\uff59\uff50\uff45\uff52\uff46\uff49\uff4e\uff45\u3000\uff3a\uff45\uff45\uff4d\uff41\uff4e\u3000\uff53\uff50\uff4c\uff49\uff54\uff54\uff49\uff4e\uff47\n# only zero field data\nmun = 3.1524512550e-5 # nuclear magneton in meV/T\nA143 = 0.0209 # in T, hyperfine constant for Nd143 in G: Zeeman gap = m(Nd e moment)*A (Ref: Phys. Rev. B 19, 5495 (1979).)\nA145 = 0.0131\ngamma143 = -14.57e6 # gyomagnetic ratio of Nd143 in rad s\u22121 T\u22121, Ref. Bertin A. PhD thesis\ngamma145 = -8.894630e5 # calculated\nhbar = 4.135667662e-12/(2*np.pi) # in meV/s\nmub = 5.7883818012e-2 # Bohr magneton in meV/T\n\nmagf = [0., 0.2, 0.5, 1.0, 2.0]\norderM = [1.3, 1.8, 2.0, 2.3, 2.6]\n#orderM = np.hstack( ([1.26], np.array([0.7, 0.9, 1.0, 1.15])/1.15*2.6) ) # cal. ordered moment base on the MH in Ref.\nprint(orderM)\n\nfig, ax = plt.subplots(figsize=(5, 4))\n\ntRange, npts = [0.01, 2.0], 501\ntemps = np.linspace(tRange[0],tRange[1],num=npts,endpoint=True)\nfor idx, didx in enumerate([2]): # plot low field data first: 0T, 0.2T...\n    dat = np.vstack( [data[:, didx*2], 2*data[:, didx*2+1] ] ).T #data[:, didx*2 : didx*2+2]\n    # plot raw data\n    ax.plot(dat[:,0], dat[:,1], 'o',ms=4, mec='none', mfc = colors[idx], label=p_lab[didx])\n\nfor i in [0,4]:# the magnetic fields in T\n    #energy levels in meV; total splitting = (7/2*2+1)*gap, where gap is A*M_ordered + dI*hbar*gamma*magF\n    # assume B_hyper and applied B are parallel\n    e1 = np.linspace(0, (A143*orderM[i]*mub + hbar*gamma143*1.*magf[i])*8,8) \n    g1 = np.ones(8) #Degenercy \n    e2 = np.linspace(0, (A145*orderM[i]*mub + hbar*gamma145*1.*magf[i])*8,8) \n    g2 = np.ones(8) #Degenercy \n    cefcpv1, cefcpv2 = lamcefcp(e1,g1), lamcefcp(e2,g2)  \n    cefcpdat = 12.0/100*cefcpv1(temps) + 8.0/100*cefcpv2(temps)# add aboundance\n    ax.plot(temps, 2*cefcpdat,c=colors[i]) #,label='%s'%magf[i]+' T') # per mol Nd2\n    # fit the high T part with A*T^-2\n    #popt, pcov = optimize.curve_fit(lambda x, A: A * x**-2, temps[150:], 2*cefcpdat[150:], [0.01])\n    #print(popt)\n    \n#plt.axvline(0.07,color='black')      \nax.set_xlim([0.05,1.2])\nax.set_ylim([0.5,20])\nax.set_xscale('log')\nax.set_yscale('log')\nplt.minorticks_on() \nax.tick_params(axis='both',which='both',labelsize=14)   \nax.set_ylabel(r'Nuclear $C_\\mathrm{p}$ (J/K/mol)',size=14,labelpad=5)  \nax.set_xlabel(r'T (K)',size=14,labelpad=5)  \nax.legend(loc='upper right' ,numpoints=1,frameon=False,framealpha=1,fontsize=14)\nax.text(0.015,0.01,r'Nuclear specific heat'+'\\n'+'for $^{143}$Nd and $^{145}$Nd',size=14, ha='left', va='center',\n        backgroundcolor='white',bbox=dict(facecolor='white', alpha=0, edgecolor='white', boxstyle='round'))\nfig.canvas.layout.width = '5in'\nfig.canvas.layout.height= '4in'\n#fig.savefig(os.path.join(fpath, r'nd_cal_nuclearCp.pdf'), bbox_inches=\"tight\", verbose=True) \nfig.show()\n```\n\n\n```python\n'''\nHyper magnetic field is far larger than the applied field.\n'''\nprint(r'hyper gap', 0.0209*1.0*mub, 'meV')\nprint(r'B_hyper/\\mu_B', -0.0209*1.7*mub/(hbar*gamma143),'T')\nprint(r'gapped induced by the applied field', -hbar*gamma143*1, 'meV')\nprint('Nd143 nuclear dipolar moment in clear magneton',7/2.*gamma143*hbar/mun, 'Correct')\nprint('Nd145 neclear gyomagnetic ratio in rad s\u22121 T\u22121', -0.65*mun/(7/2.)/hbar)\nprint(np.ones(8))\n```\n\n    hyper gap 0.0012097717964508 meV\n    B_hyper/\\mu_B 214.45049916892668 T\n    gapped induced by the applied field 9.59014813179021e-06 meV\n    Nd143 nuclear dipolar moment in clear magneton -1.0647434566364369 Correct\n    Nd145 neclear gyomagnetic ratio in rad s\u22121 T\u22121 -8894630.853067324\n    [1. 1. 1. 1. 1. 1. 1. 1.]\n\n\n\n```python\na=5.28; b=5.59; c= 7.605\nnp.sqrt(a**2+b**2)/2\n4.42*1.732/2\nth1 = 56.6613/180*3.1415; th2 = 26.5426/180*3.1415\nprint(np.cos(th2)*np.sin(th2/2) / (np.sin(th1)*np.sin(th1/2)))\n```\n\n    0.5180089199809037\n\n\n\n```python\na=4.46; b=a; c=5.93\nh0,k0,l0 = 1, 1, 0\nh0,k0,l0 = 1, 1, 3\nh1,k1,l1 = 0, 0, 3\nnp.arccos(  (4/(3*a**2)*(h0*h0 + k0*k0 + 0.5*(h0*k1+k0*h1))+ l0*l1/c**2) /\n            (np.sqrt((4/(3*a**2)*(h0*h0+k0*k0+h0*k0)+l0*l0/c**2)) * np.sqrt((4/(3*a**2)*(h1*h1+k1*k1+h1*k1)+l1*l1/c**2)))\n         )*180/3.14\n```\n\n    C:\\ProgramData\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:7: RuntimeWarning: invalid value encountered in arccos\n      import sys\n\n\n\n\n\n    nan\n\n\n\n# Debye-Einstein fit of LaZrO\n\n\n```python\nlafpath = 'D:\\3_Physical Properties\\Heat_Capacity'\nlafname = '3 La2Zr2O7_ppms.txt'\nlafpath = r'D:\\3_Physical Properties\\Heat_Capacity\\1_Cp_NdZrO_Ausburg'\nlafname = r'cp_lazro_2-400k.txt'\nlacp = np.genfromtxt(os.path.join(lafpath,lafname), usecols=(0,1), skip_header=1)  \nfig, ax = plt.subplots(figsize=(5, 4))\nax.plot(lacp[:,0],lacp[:,1])\nplt.show\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n\n\n\n    <function matplotlib.pyplot.show>\n\n\n\n\n```python\n(582.9278/572.2546)**0.5/(10.67/10.80)\n```\n\n\n\n\n    1.021579274705271\n\n\n\n\n```python\nfrom scipy import integrate\nR = 8.314 # in J/K/mol\nkb = 1.38*10**-23 # in J/K\nnmol = 6*10**23 # Av\nhbar = 6.626e-34/(2*np.pi) #in J*s OR  4.135667662e-12/(2*np.pi) # in meV*s\n\ndef Debye(t,thetaD): # Debye model for 11 atoms in Nd2Zr2O7\n    return 11* 9*R* (t/thetaD)**3 * integrate.quad(lambda x: x**4 * np.exp(x) / (np.exp(x) - 1)**2, 0, thetaD/t)[0]\nvDebye = np.vectorize(Debye, excluded=['thetaD'])\n\ndef Einstein(t,thetaE): # Einstein model t and e1 are in K for 11 atoms in Nd2Zr2O7\n    return 11* 3*R* (thetaE/t)**2 * np.exp(thetaE/t) / (np.exp(thetaE/t) - 1)**2\nvEinstein = np.vectorize(Einstein, excluded=['thetaE'])\n\ndef DebyeEin(t,ratio,thetaD,thetaE): #Debye+Einstein Model: t, thetaD,thetaE are in K for 11 atoms in Nd2Zr2O7\n    return ratio*Debye(t,thetaD) + (1-ratio)*Einstein(t,thetaE)\n#     return rario* 9*R* (t/thetaD)**3 * integrate.quad(lambda x: x**4 * np.exp(x) / (np.exp(x) - 1)**2, 0, thetaD/t)[0]\\\n#          + (1-ratio)* 3*R* (thetaE/t)**2 * np.exp(thetaE/t) / (np.exp(thetaE/t) - 1)**2\n\nvDebyeEin = np.vectorize(DebyeEin, excluded=['ratio','thetaD','thetaE'])\n\ndef DebyeEin0(t,ratio,ratio0, thetaD,thetaE,thetaE0): #Debye+Einstein Model: t, thetaD,thetaE are in K for 11 atoms in Nd2Zr2O7\n    return ratio0* ( ratio*Debye(t,thetaD) + (1-ratio)*Einstein(t,thetaE) ) + (1-ratio0)*Einstein(t,thetaE)\nvDebyeEin0 = np.vectorize(DebyeEin0, excluded=['ratio','ratio0','thetaD','thetaE','thetaE0'])\n```\n\n\n```python\n# \uff26\uff49\uff54\u3000\uff24\uff45\uff42\uff59\uff45\uff0b\uff25\uff49\uff4e\nx1,x2 = 50, 300 \npopt, pcov = optimize.curve_fit(vDebyeEin, fitReg(lacp,x1,x2)[:,0],fitReg(lacp,x1,x2)[:,1], [0.5,700,200])\nprint popt\n\nfig, ax = plt.subplots(figsize=(5, 4))\nax.plot(lacp[:,0],lacp[:,1],'o',c='black',mfc='white',label='Data')\n\nfit = vDebyeEin(lacp[:,0],popt[0],popt[1],popt[2])\nax.plot(lacp[:,0],fit,c='r',label='Fit')\n\nax.plot(lacp[:,0], popt[0]*vDebye(lacp[:,0],popt[1]), c='b',label='Debye' )\nax.plot(lacp[:,0], (1-popt[0])*vEinstein(lacp[:,0],popt[2]),c='g',label='Einstein' )\nax.legend(loc='best')\nplt.show()\n```\n\n    [  6.54070777e-01   7.76313335e+02   1.93491586e+02]\n\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n    C:\\Users\\kew\\AppData\\Local\\Continuum\\Anaconda2\\lib\\site-packages\\ipykernel\\__main__.py:8: RuntimeWarning: overflow encountered in double_scalars\n\n\n\n```python\nnp.savetxt( os.path.join(lafpath,'cp_lazro_2-400k_fit_Degye+Eins.txt'),np.vstack([lacp[:,0],fit]).T, fmt='%1.3e' )\n```\n\n\n```python\n# \uff26\uff49\uff54\u3000\uff24\uff45\uff42\uff59\uff45\uff0b\uff25\uff49\uff4e\uff0b\uff25\uff49\uff4e\npopt, pcov = optimize.curve_fit(vDebyeEin0, lacp[:,0],lacp[:,1], [0.7,0.1, 700,200,100])\nprint popt\n\nfig, ax = plt.subplots(figsize=(5, 4))\nax.plot(lacp[:,0],lacp[:,1],'o',c='black',mfc='white',label='Data')\n\nfit = vDebyeEin0(lacp[:,0],popt[0],popt[1],popt[2],popt[3],popt[4])\nax.plot(lacp[:,0],fit,c='r',label='Fit')\n\nax.plot(lacp[:,0], popt[1]*popt[0]     *vDebye(lacp[:,0],popt[2]), c='b',label='Debye' )\nax.plot(lacp[:,0], popt[1]*(1-popt[0]) *vEinstein(lacp[:,0],popt[3]),c='g',label='Einstein' )\nax.plot(lacp[:,0], (1-popt[1])         *vEinstein(lacp[:,0],popt[4]),c='y',label='Einstein0' )\nax.legend(loc='best')\nplt.show()\n```\n\n    C:\\Users\\kew\\AppData\\Local\\Continuum\\Anaconda2\\lib\\site-packages\\ipykernel\\__main__.py:8: RuntimeWarning: overflow encountered in double_scalars\n\n\n    [  1.79659972e+00   3.96503584e-01   7.40715826e+02   1.64995201e+02\n       1.00000000e+02]\n\n\n    C:\\Users\\kew\\AppData\\Local\\Continuum\\Anaconda2\\lib\\site-packages\\scipy\\optimize\\minpack.py:779: OptimizeWarning: Covariance of the parameters could not be estimated\n      category=OptimizeWarning)\n\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n", "meta": {"hexsha": "86f88718da9a2595cadc18f00fb1891e13cc040e", "size": 393360, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "scientific_data_analysis/spinwave_data/Nd2Zr2O7_lowT_Cp_fit_plot.ipynb", "max_stars_repo_name": "jh-xu/scientific_data_analysis", "max_stars_repo_head_hexsha": "c7b45d9c3ce5024ccbb47113d861f238156dc937", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scientific_data_analysis/spinwave_data/Nd2Zr2O7_lowT_Cp_fit_plot.ipynb", "max_issues_repo_name": "jh-xu/scientific_data_analysis", "max_issues_repo_head_hexsha": "c7b45d9c3ce5024ccbb47113d861f238156dc937", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scientific_data_analysis/spinwave_data/Nd2Zr2O7_lowT_Cp_fit_plot.ipynb", "max_forks_repo_name": "jh-xu/scientific_data_analysis", "max_forks_repo_head_hexsha": "c7b45d9c3ce5024ccbb47113d861f238156dc937", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 84.4120171674, "max_line_length": 43036, "alphanum_fraction": 0.7404743746, "converted": true, "num_tokens": 22258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.08389039099136326, "lm_q1q2_score": 0.04096228494595795}}
{"text": "[](https://colab.research.google.com/github/QuCAI-Lab/QHack2022/blob/dev/solutions_notebook.ipynb)\n\n[](https://github.com/QuCAI-Lab/QHack2022/blob/dev/LICENSE.md)\n\n[](https://github.com/QuCAI-Lab/QHack2022/graphs/commit-activity)\n[](https://github.com/QuCAI-Lab/QHack2022/releases)\n[](https://github.com/QuCAI-Lab/QHack2022/commits)\n[](https://github.com/QuCAI-Lab/QHack2022/fork)\n\n<div align=\"center\">\n  <h1> <a href=\"https://qhack.ai/\"> QHack2022 </a> -  <a href=\"https://qhack.ai/events/#coding-challenges\">Coding Challenge Solutions</a> </h1>\n  <h2> Hackeinberg Team Repository</h2>\n</div>\n\n<center> <b>Author\u00b9: Lucas Camponogara Viera</b></center>\n<center><b>\u00b9National Taiwan Normal University (\u570b\u7acb\u81fa\u7063\u5e2b\u7bc4\u5927\u5b78).</b></center>\n\n<!--  -->\n\n<br>\n\n[comment]: <> ()\n<table class=\"tfo-notebook-buttons\" align=\"head\">\n  <td>\n    <a target=\"_blank\" href=\"https://github.com/QuCAI-Lab/QHack2022\"></a>\n  </td>\n</table>\n\n<center><a href=\"https://github.com/QuCAI-Lab/QHack2022\"><b>View source on GitHub.</b></a></center>\n\n    \n\n\n---\n\nIn this jupyter notebook, the reader may find some of the solutions of the QHack2022 coding challenge.\n\n---\n\n\n```\n%autosave 30\n```\n\n\n\n    Autosaving every 30 seconds\n\n\n# &nbsp; <a href=\"https://creativecommons.org/licenses/by/4.0/\"></a> License\n\nYou don't wanna be a copycat laggard.\n\n\n```\n#@title Copyright 2022.\n# This code is part of QHack2022.\n#\n# (C) Copyright NTNU QuCAI-Lab, 2022.\n#\n# This code is licensed under the Creative Commons Zero v1.0 Universal License. \n# You may obtain a copy of the License at https://github.com/QuCAI-Lab/QHack2022/blob/dev/LICENSE.md.\n```\n\n# &nbsp; <a href=\"https://drive.google.com/drive\"></a> Google Drive Credentials \n\n**Run this cell only if you wish to read the dataset from your Google Drive folder.**\n\n\n```\nfrom google.colab import drive\ndrive.mount('/content/gdrive')\n```\n\n    Mounted at /content/gdrive\n\n\n\n```\n!find . -maxdepth 2 -type d -exec ls -ld \"{}\" \\;\n```\n\n    drwxr-xr-x 1 root root 4096 Mar  6 03:24 .\n    drwxr-xr-x 1 root root 4096 Feb 18 14:33 ./.config\n    drwxr-xr-x 3 root root 4096 Feb 18 14:32 ./.config/logs\n    drwxr-xr-x 2 root root 4096 Feb 18 14:32 ./.config/configurations\n    drwx------ 6 root root 4096 Mar  6 03:24 ./gdrive\n    dr-x------ 2 root root 4096 Mar  6 03:24 ./gdrive/.shortcut-targets-by-id\n    dr-x------ 2 root root 4096 Mar  6 03:24 ./gdrive/.file-revisions-by-id\n    drwx------ 9 root root 4096 Mar  6 03:24 ./gdrive/MyDrive\n    drwx------ 2 root root 4096 Mar  6 03:24 ./gdrive/Shareddrives\n    drwx------ 5 root root 4096 Mar  6 03:24 ./gdrive/.Trash-0\n    drwxr-xr-x 1 root root 4096 Feb 18 14:33 ./sample_data\n\n\n\n```\n!pwd # Display the current working directory.\nprint('')\n\n#%cd /content/gdrive/'My Drive/'\n!ls -l # List files/folders in the current directory.\n```\n\n    /content\n    \n    total 8\n    drwx------ 6 root root 4096 Mar  6 03:24 gdrive\n    drwxr-xr-x 1 root root 4096 Feb 18 14:33 sample_data\n\n\n**To read a file:**\n\n```python\ndataset_dir = F'/content/gdrive/My Drive/{...}.extension'\nwith open(dataset_dir, 'r') as f:\n  input = f.readlines()\n```\n\n**Example:**\n\n\n```\ndataset_dir='/content/gdrive/My Drive/Hackeinberg/dataset/'\nin1 = dataset_dir+'1.in'\nin2 = dataset_dir+'2.in'\n\ndef read(file):\n  with open(file, 'r') as f:\n    filein = f.readlines()\n    inputs = filein[0].split(\";\")\n    print('filein = {}\\nfilein[0] = {}\\ninputs = {}'.format(filein, filein[0], inputs))\n    return inputs\n```\n\n\n```\ninputs = read(in1)\ninput1 = ['4','Hadamard','0','CNOT','0,1','Hadamard','0']\ninputs == input1\n```\n\n    filein = ['4;Hadamard;0;CNOT;0,1;Hadamard;0']\n    filein[0] = 4;Hadamard;0;CNOT;0,1;Hadamard;0\n    inputs = ['4', 'Hadamard', '0', 'CNOT', '0,1', 'Hadamard', '0']\n\n\n\n\n\n    True\n\n\n\n\n```\ninputs = read(in2)\ninput2 = ['4','DoubleExcitation','0,1,2,3','0.732','SingleExcitation','0,1','1.0']\ninputs == input2\n```\n\n    filein = ['4;DoubleExcitation;0,1,2,3;0.732;SingleExcitation;0,1;1.0']\n    filein[0] = 4;DoubleExcitation;0,1,2,3;0.732;SingleExcitation;0,1;1.0\n    inputs = ['4', 'DoubleExcitation', '0,1,2,3', '0.732', 'SingleExcitation', '0,1', '1.0']\n\n\n\n\n\n    True\n\n\n\n# &nbsp; <a href=\"https://cloud.google.com/tpu/\"></a> Colab's memory card \n\n\"Executing a code cell within a GPU or TPU runtime does not mean that GPU or TPU is being used.\" \n\n[For more information about GPU usage on Colab](https://research.google.com/colaboratory/faq.html#gpu-availability).\n\n## CPU\n\n1. Click on the tab `Runtime -> Change runtime type`.\n1. Click on `Hardware accelerator`.\n1. Select `None` from the drop-down menu and click `Save`.\n1. Click `Connect` in the upper right corner and select `Connect to hosted runtime` (if not automatically).\n\n\n```\n!free -h    # Show CPU Memory.\n              # 'free' = wasted memory (not being used).\n              # 'available' = memory for allocation.\n              # 'buff/cache' used memory for cache (Data has been read) and buffer (data is being written).\n              # 'free' + 'buff/cache' = 'available'.\n\nprint('')\n!lscpu      # Show CPU Architecture.\n```\n\n                  total        used        free      shared  buff/cache   available\n    Mem:            12G        927M        7.8G        1.2M        4.0G         11G\n    Swap:            0B          0B          0B\n    \n    Architecture:        x86_64\n    CPU op-mode(s):      32-bit, 64-bit\n    Byte Order:          Little Endian\n    CPU(s):              2\n    On-line CPU(s) list: 0,1\n    Thread(s) per core:  2\n    Core(s) per socket:  1\n    Socket(s):           1\n    NUMA node(s):        1\n    Vendor ID:           GenuineIntel\n    CPU family:          6\n    Model:               79\n    Model name:          Intel(R) Xeon(R) CPU @ 2.20GHz\n    Stepping:            0\n    CPU MHz:             2200.220\n    BogoMIPS:            4400.44\n    Hypervisor vendor:   KVM\n    Virtualization type: full\n    L1d cache:           32K\n    L1i cache:           32K\n    L2 cache:            256K\n    L3 cache:            56320K\n    NUMA node0 CPU(s):   0,1\n    Flags:               fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm rdseed adx smap xsaveopt arat md_clear arch_capabilities\n\n\n## GPU\n\n1. Click on the tab `Runtime -> Change runtime type`.\n1. Click on `Hardware accelerator`.\n1. Select `GPU` from the drop-down menu and click `Save`.\n1. Click `Connect` in the upper right corner and select `Connect to hosted runtime` (if not automatically).\n\n\n```\n!nvidia-smi #Show GPU Card\n```\n\n    NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver. Make sure that the latest NVIDIA driver is installed and running.\n    \n\n\n# &nbsp; <a href=\"https://colab.research.google.com/\"></a> Pip Install\n\n**Run this cell only if you are running this jupyter notebook on Google Colab.**\n\nInstalling `PennyLane`.\n\n\n```\n'''\n# Installing a non-default library\n\n!python3 -m pip install <library_name>\n\n# Alternative \n\n!apt-get -qq install -y <library_name> && python3 -m pip install -U <library_name> \n\n# Upgrading an installed library\n\n!python3 -m pip install -U --upgrade <library_name> \n'''\n```\n\n\n\n\n    '\\n# Installing a non-default library\\n\\n!python3 -m pip install <library_name>\\n\\n# Alternative \\n\\n!apt-get -qq install -y <library_name> && python3 -m pip install -U <library_name> \\n\\n# Upgrading an installed library\\n\\n!python3 -m pip install -U --upgrade <library_name> \\n'\n\n\n\n\n```\n!pip --version\n```\n\n    pip 21.1.3 from /usr/local/lib/python3.7/dist-packages/pip (python 3.7)\n\n\n**PennyLane:**\n\n\n```\n!python3 -m pip install PennyLane==0.21.0\n```\n\n    Collecting PennyLane==0.21.0\n      Downloading PennyLane-0.21.0-py3-none-any.whl (800 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 800 kB 30.5 MB/s \n    \u001b[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from PennyLane==0.21.0) (1.21.5)\n    Collecting pennylane-lightning>=0.21\n      Downloading PennyLane_Lightning-0.22.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (8.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 8.2 MB 40.1 MB/s \n    \u001b[?25hRequirement already satisfied: networkx in /usr/local/lib/python3.7/dist-packages (from PennyLane==0.21.0) (2.6.3)\n    Requirement already satisfied: autograd in /usr/local/lib/python3.7/dist-packages (from PennyLane==0.21.0) (1.3)\n    Collecting retworkx\n      Downloading retworkx-0.11.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.6 MB 45.8 MB/s \n    \u001b[?25hRequirement already satisfied: cachetools in /usr/local/lib/python3.7/dist-packages (from PennyLane==0.21.0) (4.2.4)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from PennyLane==0.21.0) (1.4.1)\n    Requirement already satisfied: appdirs in /usr/local/lib/python3.7/dist-packages (from PennyLane==0.21.0) (1.4.4)\n    Collecting toml\n      Downloading toml-0.10.2-py2.py3-none-any.whl (16 kB)\n    Collecting autoray\n      Downloading autoray-0.2.5-py3-none-any.whl (16 kB)\n    Collecting semantic-version==2.6\n      Downloading semantic_version-2.6.0-py3-none-any.whl (14 kB)\n    Collecting ninja\n      Downloading ninja-1.10.2.3-py2.py3-none-manylinux_2_5_x86_64.manylinux1_x86_64.whl (108 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 108 kB 55.0 MB/s \n    \u001b[?25hRequirement already satisfied: future>=0.15.2 in /usr/local/lib/python3.7/dist-packages (from autograd->PennyLane==0.21.0) (0.16.0)\n    Installing collected packages: ninja, toml, semantic-version, retworkx, pennylane-lightning, autoray, PennyLane\n    Successfully installed PennyLane-0.21.0 autoray-0.2.5 ninja-1.10.2.3 pennylane-lightning-0.22.0 retworkx-0.11.0 semantic-version-2.6.0 toml-0.10.2\n\n\n# &nbsp; <a href=\"#\"></a> Dependencies\n\nAlternatively, you may resort to the `environment.txt` file from the [official GitHub repository](https://github.com/QuCAI-Lab/QHack2022/blob/dev/requirements.txt).\n\n\n```\nimport sys, subprocess\nimport pennylane as qml\nfrom pennylane import numpy as np\nimport matplotlib\n\nif \"google.colab\" in sys.modules:\n  cmd = \"python3 -m pip install --upgrade watermark\"\n  process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)   \n```\n\n\n```\n# If you get hit by the error \"No module named watermark\", run this cell twice!\n\n%load_ext watermark\n%watermark -a 'Lucas Camponogara Viera' -gu 'camponogaraviera' -e 'vieracamponogara@gmail.com' -ws 'https://qucai-lab.github.io/' -w -u -d -v -m -iv -r -b\n```\n\n    The watermark extension is already loaded. To reload it, use:\n      %reload_ext watermark\n    Author: Lucas Camponogara Viera\n    \n    Github username: camponogaraviera\n    \n    Email: vieracamponogara@gmail.com\n    \n    Website: https://qucai-lab.github.io/\n    \n    Last updated: 2022-03-22\n    \n    Python implementation: CPython\n    Python version       : 3.7.12\n    IPython version      : 5.5.0\n    \n    Compiler    : GCC 7.5.0\n    OS          : Linux\n    Release     : 5.4.144+\n    Machine     : x86_64\n    Processor   : x86_64\n    CPU cores   : 2\n    Architecture: 64bit\n    \n    Git repo: \n    \n    Git branch: \n    \n    sys       : 3.7.12 (default, Jan 15 2022, 18:48:18) \n    [GCC 7.5.0]\n    pennylane : 0.21.0\n    IPython   : 5.5.0\n    matplotlib: 3.2.2\n    \n    Watermark: 2.3.0\n    \n\n\n\n```\n#%watermark?\n```\n\n\n```\nqml.about()\n```\n\n    WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.\n    Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.\n    To avoid this problem you can invoke Python with '-m pip' instead of running pip directly.\n\n\n    Name: PennyLane\n    Version: 0.21.0\n    Summary: PennyLane is a Python quantum machine learning library by Xanadu Inc.\n    Home-page: https://github.com/XanaduAI/pennylane\n    Author: None\n    Author-email: None\n    License: Apache License 2.0\n    Location: /usr/local/lib/python3.7/dist-packages\n    Requires: autoray, autograd, cachetools, numpy, scipy, toml, retworkx, networkx, semantic-version, pennylane-lightning, appdirs\n    Required-by: PennyLane-Lightning\n    Platform info:           Linux-5.4.144+-x86_64-with-Ubuntu-18.04-bionic\n    Python version:          3.7.12\n    Numpy version:           1.21.5\n    Scipy version:           1.4.1\n    Installed devices:\n\n\n\n```\nimport IPython\nprint(IPython.sys_info())\n```\n\n    {'commit_hash': 'b467d487e',\n     'commit_source': 'installation',\n     'default_encoding': 'UTF-8',\n     'ipython_path': '/usr/local/lib/python3.7/dist-packages/IPython',\n     'ipython_version': '5.5.0',\n     'os_name': 'posix',\n     'platform': 'Linux-5.4.144+-x86_64-with-Ubuntu-18.04-bionic',\n     'sys_executable': '/usr/bin/python3',\n     'sys_platform': 'linux',\n     'sys_version': '3.7.12 (default, Jan 15 2022, 18:48:18) \\n[GCC 7.5.0]'}\n\n\n# &nbsp; <a href=\"#\"></a> Problem Solutions\n\n## PennyLane101\n\n### pennylane101_100_OrderMatters_solution\n\nTemplate: [here](https://github.com/XanaduAI/QHack/blob/master/Coding_Challenges/pennylane101_100_OrderMatters_template/order_matters_template.py).\n\n\n```\n#! /usr/bin/python3\n\nimport sys\nimport pennylane as qml\nfrom pennylane import numpy as np\n\n\ndef compare_circuits(angles):\n    \"\"\"Given two angles, compare two circuit outputs that have their order of operations flipped: RX then RY VERSUS RY then RX.\n    Args:\n        - angles (np.ndarray): Two angles\n    Returns:\n        - (float): | < \\sigma^x >_1 - < \\sigma^x >_2 |\n    \"\"\"\n\n    # QHACK #\n\n    # define a device and quantum functions/circuits here\n\n    # QHACK #\n\n    dev=qml.device(\"default.qubit\", wires=1) # Define the quantum device.\n\n    \n    @qml.qnode(dev)\n    def circuit1(angles):                    # Create the first quantum function.\n      qml.RX(angles[0], wires=0)\n      qml.RY(angles[1], wires=0)\n      return qml.expval(qml.PauliX(0))\n\n    @qml.qnode(dev)\n    def circuit2(angles):                    # Create the second quantum function.\n      qml.RY(angles[1], wires=0)\n      qml.RX(angles[0], wires=0)\n      return qml.expval(qml.PauliX(0))\n\n    abs=np.sqrt((circuit1(angles)-circuit2(angles))**2) # Process the results from both circuits.\n    return float(abs)                                   # Return the absolute value of the difference between the circuit outputs.\n\n    # QHACK #\n'''\nif __name__ == \"__main__\":\n    # DO NOT MODIFY anything in this code block\n    angles = np.array(sys.stdin.read().split(\",\"), dtype=float)\n    output = compare_circuits(angles)\n    print(f\"{output:.6f}\")\n'''\n```\n\n\n\n\n    '\\nif __name__ == \"__main__\":\\n    # DO NOT MODIFY anything in this code block\\n    angles = np.array(sys.stdin.read().split(\",\"), dtype=float)\\n    output = compare_circuits(angles)\\n    print(f\"{output:.6f}\")\\n'\n\n\n\n\n```\nin1 = [3.79894785, 0.71678115] \nans1=1.177019\nin2  = [5.88344281, 0.30672784]\nans2=0.023805\nans=[ans1, ans2]\ninputs=[in1, in2]\n\nfor angles in inputs:\n  output=compare_circuits(angles)\n  print(f\"{output:.6f}\", round(output,6) == ans[inputs.index(angles)])\n```\n\n    1.177019 True\n    0.023805 True\n\n\n\n```\ndev=qml.device(\"default.qubit\", wires=1)\n@qml.qnode(dev)\ndef circuit(angles):    \n  qml.RX(angles[0], wires=0)\n  qml.RY(angles[1], wires=0)\n  return qml.expval(qml.PauliX(0))\nprint(circuit(in1))\nfig, ax = qml.draw_mpl(circuit, decimals=6)(in2)\n```\n\n### pennylane101_200_KnowYourDevices_solution\n\n\nTemplate: [here](https://github.com/XanaduAI/QHack/blob/master/Coding_Challenges/pennylane101_200_KnowYourDevices_template/know_your_devices_template.py).\n\n\n```\n#! /usr/bin/python3\nimport sys\nimport pennylane as qml\nfrom pennylane import numpy as np\n\n\ndef matrix_norm(mixed_state, pure_state):\n    \"\"\"Computes the matrix one-norm of the difference between mixed and pure states.\n\n    Args:\n        - mixed_state (np.tensor): A density matrix\n        - pure_state (np.tensor): A pure state\n\n    Returns:\n        - (float): The matrix one-norm\n    \"\"\"\n\n    return np.sum(np.abs(mixed_state - np.outer(pure_state, np.conj(pure_state))))\n\n\ndef compare_circuits(num_wires, params):\n    \"\"\"Function that returns the matrix norm between the mixed- and pure-state versions of the same state.\n\n    Args:\n        - num_wires (int): The number of qubits / wires\n        - params (list(np.ndarray)): Two arrays with num_wires floats that correspond to angles of y-rotations\n        for each wire\n\n    Returns:\n        - mat_norm (float): The matrix one-norm\n    \"\"\"\n\n    # QHACK #\n    # define devices\n\n    # add a decorator here\n    dev=qml.device(\"default.qubit\", wires=num_wires)\n    @qml.qnode(dev)\n    def pure_circuit():\n        \"\"\"A circuit that contains `num_wires` y-rotation gates.\n        The argument params[0] are the parameters you should use here to define the y-rotations.\n\n        Returns:\n            - (np.tensor): A state vector\n        \"\"\"\n        # create the circuit here\n        for i in range(len(params[0])):\n          qml.RY(params[0][i], wires=i)\n        return qml.state()\n\n    # add a decorator here\n    dev2=qml.device(\"default.mixed\", wires=num_wires)\n    @qml.qnode(dev2)\n    def mixed_circuit():\n        \"\"\"A circuit that contains `num_wires` y-rotation gates.\n        The argument params[1] are the parameters you should use here to define the y-rotations.\n\n        Returns:\n            - (np.tensor): A density matrix\n        \"\"\"\n        # create the circuit here\n        for i in range(len(params[1])):\n          qml.RY(params[1][i], wires=i)\n        return qml.state()\n\n    # QHACK #\n\n    # DO NOT MODIFY any of the next lines in this scope\n    mixed_state = mixed_circuit()\n    pure_state = pure_circuit()\n    mat_norm = matrix_norm(mixed_state, pure_state)\n\n    return mat_norm\n\n'''\nif __name__ == \"__main__\":\n    # DO NOT MODIFY anything in this code block\n    inputs = sys.stdin.read().split(\",\")\n    num_wires = int(inputs[0])\n    l = int(len(inputs[1:]) / 2)\n    params = [\n        np.array(inputs[1 : (l + 1)], dtype=float),  # for pure circuit\n        np.array(inputs[(l + 1) :], dtype=float),  # for mixed circuit\n    ]\n\n    output = compare_circuits(num_wires, params)\n    print(f\"{output:.6f}\")\n'''\n```\n\n\n\n\n    '\\nif __name__ == \"__main__\":\\n    # DO NOT MODIFY anything in this code block\\n    inputs = sys.stdin.read().split(\",\")\\n    num_wires = int(inputs[0])\\n    l = int(len(inputs[1:]) / 2)\\n    params = [\\n        np.array(inputs[1 : (l + 1)], dtype=float),  # for pure circuit\\n        np.array(inputs[(l + 1) :], dtype=float),  # for mixed circuit\\n    ]\\n\\n    output = compare_circuits(num_wires, params)\\n    print(f\"{output:.6f}\")\\n'\n\n\n\n\n```\nin1 = [2, 0.17085641, 4.69202289, 0.4478956, 3.69402896]\nans1= 1.765778\nin2 = [4, 2.1051399, 5.02920013, 1.48450097, 4.06791362, 5.19513356, 0.65491091, 3.0127959, 4.03855719]\nans2= 15.747060\nans=[ans1,ans2]\ninput=[in1, in2]\n\nfor inputs in input:\n  num_wires = int(inputs[0])\n  l = int(len(inputs[1:]) / 2)\n  params = [\n      np.array(inputs[1 : (l + 1)], dtype=float),  # for pure state circuit\n      np.array(inputs[(l + 1) :], dtype=float),  # for mixed state circuit\n  ]\n\n  output = compare_circuits(num_wires, params)\n  print(f\"{output:.6f}\", output.round(6) == ans[input.index(inputs)])\n```\n\n    1.765778 True\n    15.747060 True\n\n\n### pennylane101_300_superdense_coding_solution\n\n\nTemplate: [here](https://github.com/XanaduAI/QHack/blob/master/Coding_Challenges/pennylane101_300_superdense_coding_template/superdense_coding_template.py).\n\n\n```\n#! /usr/bin/python3\n\nimport sys\nimport pennylane as qml\nfrom pennylane import numpy as np\n\ndev = qml.device(\"default.qubit\", wires=2)\n\n\n@qml.qnode(dev)\ndef superdense_coding(bits, alpha):\n    \"\"\"Construct a quantum circuit that implements superdense coding, given a not necessarily maximally entangled state\n\n    Args:\n        - bits (int): 0 (binary: 00), 1 (binary: 01), 2 (binary: 10), or 3 (binary: 11), Alice's bits that she wants to communicate to Bob.\n        - alpha (float): angle parametrizing the entangled state\n\n    Returns:\n        - (np.tensor): Probability that Bob will guess Alice's bits correctly\n    \"\"\"\n\n    # QHACK #\n\n    # Prepare entangled state here\n    qml.U3(alpha*2,0,0, wires=0)\n    qml.CNOT(wires=[0, 1])\n    # Implement Alice's operations on her qubit here\n    if bits == 0:\n      pass\n    elif bits==1:\n      qml.PauliX(0)\n    elif bits == 3:\n      qml.PauliX(0)\n      qml.PauliZ(0)\n    else:\n      qml.PauliZ(0)\n    # Implement Bob's measurement procedure here\n    qml.CNOT(wires=[0, 1])\n    qml.Hadamard(wires=0) \n\n    # QHACK #\n\n    return qml.probs(wires=[0, 1])\n\n\ndef return_probs(bits, alpha):\n    \"\"\"Returns the output of the superdense_coding function for a given index (bits)\"\"\"\n    # DO NOT MODIFY anything in this code block\n    return superdense_coding(bits, alpha)[bits].numpy()\n\n'''\nif __name__ == \"__main__\":\n    # DO NOT MODIFY anything in this code block\n    inputs = sys.stdin.read().split(\",\")\n    output = return_probs(int(inputs[0]), float(inputs[1]))\n    print(f\"{output:.6f}\")\n'''\n```\n\n\n\n\n    '\\nif __name__ == \"__main__\":\\n    # DO NOT MODIFY anything in this code block\\n    inputs = sys.stdin.read().split(\",\")\\n    output = return_probs(int(inputs[0]), float(inputs[1]))\\n    print(f\"{output:.6f}\")\\n'\n\n\n\n\n```\nparam = [[0, 0.7854], [2, 0.4]]\nans=[1.0, 0.858678]\ni=0\nfor x in param:\n  output = return_probs(int(x[0]), float(x[1]))\n  print(f\"{output:.6f}\", round(output, 6) == ans[i])\n  i+=1\n```\n\n    1.000000 True\n    0.858678 True\n\n\n\n```\ninput=[[0, 0.7854], [1, 0.7854], [2, 0.4], [3, 0.4]]\nlabel_dict = {0:'I', 1: 'X', 2: 'Z', 3: 'ZX'}\n\ni=0\nfor inputs in input:\n  print('Alice\\'s applied gate:', label_dict[i])\n  qml.draw_mpl(superdense_coding, decimals=6)(inputs[0], inputs[1])\n  i+=1\n```\n\n### pennylane101_400_FiniteDifferenceGradient_solution\nTemplate: [here](https://github.com/XanaduAI/QHack/blob/master/Coding_Challenges/pennylane101_400_FiniteDifferenceGradient_template/finite_difference_template.py).\n\n\n```\n#! /usr/bin/python3\n\nimport sys\nimport pennylane as qml\nfrom pennylane import numpy as np\n\ndev = qml.device(\"default.qubit\", wires=3)\n\n\ndef my_finite_diff_grad(params):\n    \"\"\"Function that returns the gradients of the cost function (defined below) with respect \n    to all parameters in params.\n\n    Args:\n        - params (np.ndarray): The parameters needed to create the variational circuit.\n\n    Returns:\n        - gradients (np.ndarray): the gradient w.r.t. each parameter\n    \"\"\"\n\n    gradients = np.zeros([len(params)])\n    for i in range(len(params)):\n        # QHACK #\n        delta = 0.000001\n        tensor1=params.copy()\n        tensor1[i]+=delta/2\n        tensor2=params.copy()\n        tensor2[i]-=delta/2\n        grad=(cost(tensor1)-cost(tensor2))/delta\n        gradients[i]=grad \n\n        # QHACK #\n\n    return gradients\n\n\ndef variational_circuit(params):\n    \"\"\"A layered variational circuit. The first layer comprises of x, y, and z rotations on wires\n    0, 1, and 2, respectively. The second layer is a ring of CNOT gates. The final layer comprises \n    of x, y, and z rotations on wires 0, 1, and 2, respectively.\n    \"\"\"\n\n    # DO NOT MODIFY anything in this code block\n    qml.RX(params[0], wires=0)\n    qml.RY(params[1], wires=1)\n    qml.RZ(params[2], wires=2)\n\n    qml.broadcast(qml.CNOT, wires=[0, 1, 2], pattern=\"ring\")\n\n    qml.RX(params[3], wires=0)\n    qml.RY(params[4], wires=1)\n    qml.RZ(params[5], wires=2)\n\n    qml.broadcast(qml.CNOT, wires=[0, 1, 2], pattern=\"ring\")\n\n\n@qml.qnode(dev)\ndef cost(params):\n    \"\"\"A QNode that pairs the variational_circuit with an expectation value measurement.\n\n    Args:\n        - params (np.ndarray): Variational circuit parameters\n\n    Returns:\n        - (float): qml.expval(qml.PauliY(0) @ qml.PauliZ(2))\n    \"\"\"\n\n    # DO NOT MODIFY anything in this code block\n    variational_circuit(params)\n    return qml.expval(qml.PauliY(0) @ qml.PauliZ(2))\n\n'''\nif __name__ == \"__main__\":\n    # DO NOT MODIFY anything in this code block\n    params = np.array(sys.stdin.read().split(\",\"), dtype=float)\n    output = my_finite_diff_grad(params)\n    print(*output, sep=\",\")\n'''\n```\n\n\n\n\n    '\\nif __name__ == \"__main__\":\\n    # DO NOT MODIFY anything in this code block\\n    params = np.array(sys.stdin.read().split(\",\"), dtype=float)\\n    output = my_finite_diff_grad(params)\\n    print(*output, sep=\",\")\\n'\n\n\n\n\n```\nin1=np.array([0.37454012, 0.95071431, 0.73199394, 0.59865848, 0.15601864, 0.15599452], dtype=float)\nans1 = -0.06518877,-0.02728919,-0.0,-0.09339346,-0.76106754,0.0\nin2=np.array([0.7286407160000131, 0.604431298517586, 0.5966297756635066, 0.3361356009032367, 0.1633339827097956, 0.2086455467304198], dtype=float)\nans2=-0.0293733,-0.08410477,0.0,-0.09423404,-0.59528383,0.0\n\nfor params in [in1, in2]:\n  output=my_finite_diff_grad(params)\n  print(*output.round(6), sep=\",\")\n```\n\n    -0.065189,-0.027289,-0.0,-0.093393,-0.761068,0.0\n    -0.029373,-0.084105,0.0,-0.094234,-0.595284,0.0\n\n\n### pennylane101_500_BitflipErrorCode_solution\n\nTemplate [here](https://github.com/XanaduAI/QHack/blob/master/Coding_Challenges/pennylane101_500_BitflipErrorCode_template/bitflip_error_template.py).\n\n\n```\n#! /usr/bin/python3\n\nimport sys\nimport pennylane as qml\nfrom pennylane import numpy as np\n\ndef error_wire(circuit_output):\n    \"\"\"Function that returns an error readout.\n\n    Args:\n        - circuit_output (?): the output of the `circuit` function.\n\n    Returns:\n        - (np.ndarray): a length-4 array that reveals the statistics of the\n        error channel. It should display your algorithm's statistical prediction for\n        whether an error occurred on wire `k` (k in {1,2,3}). The zeroth element represents\n        the probability that a bitflip error does not occur.\n\n        e.g., [0.28, 0.0, 0.72, 0.0] means a 28% chance no bitflip error occurs, but if one\n        does occur it occurs on qubit #2 with a 72% chance.\n    \"\"\"\n\n    # QHACK #\n\n    # process the circuit output here and return which qubit was the victim of a bitflip error!\n    return [circuit_output[0], circuit_output[3], circuit_output[2], circuit_output[1]]\n\n    # QHACK #\n\n\ndev = qml.device(\"default.mixed\", wires=3)\n\n\n@qml.qnode(dev)\ndef circuit(p, alpha, tampered_wire):\n    \"\"\"A quantum circuit that will be able to identify bitflip errors.\n\n    DO NOT MODIFY any already-written lines in this function.\n\n    Args:\n        p (float): The bit flip probability\n        alpha (float): The parameter used to calculate `density_matrix(alpha)`\n        tampered_wire (int): The wire that may or may not be flipped (zero-index)\n\n    Returns:\n        Some expectation value, state, probs, ... you decide!\n    \"\"\"\n\n    qml.QubitDensityMatrix(density_matrix(alpha), wires=[0, 1, 2])\n\n    # QHACK #\n\n    # put any input processing gates here\n    qml.CNOT(wires=[0,1])\n    qml.CNOT(wires=[0,2])\n\n    qml.BitFlip(p, wires=int(tampered_wire))\n\n    # put any gates here after the bitflip error has occurred\n    qml.CNOT(wires=[0,1])\n    qml.CNOT(wires=[0,2])\n    qml.Toffoli(wires=[2,1,0])\n    # return something!\n    return  qml.probs(wires=[1,2])\n    # QHACK #\n\n\ndef density_matrix(alpha):\n    \"\"\"Creates a density matrix from a pure state.\"\"\"\n    # DO NOT MODIFY anything in this code block\n    psi = alpha * np.array([1, 0], dtype=float) + np.sqrt(1 - alpha**2) * np.array(\n        [0, 1], dtype=float\n    )\n    psi = np.kron(psi, np.array([1, 0, 0, 0], dtype=float))\n    return np.outer(psi, np.conj(psi))\n'''\nif __name__ == \"__main__\":\n    # DO NOT MODIFY anything in this code block\n    inputs = np.array(sys.stdin.read().split(\",\"), dtype=float)\n    p, alpha, tampered_wire = inputs[0], inputs[1], int(inputs[2])\n\n    error_readout = np.zeros(4, dtype=float)\n    circuit_output = circuit(p, alpha, tampered_wire)\n    error_readout = error_wire(circuit_output)\n\n    print(*error_readout, sep=\",\")\n'''\n```\n\n\n\n\n    '\\nif __name__ == \"__main__\":\\n    # DO NOT MODIFY anything in this code block\\n    inputs = np.array(sys.stdin.read().split(\",\"), dtype=float)\\n    p, alpha, tampered_wire = inputs[0], inputs[1], int(inputs[2])\\n\\n    error_readout = np.zeros(4, dtype=float)\\n    circuit_output = circuit(p, alpha, tampered_wire)\\n    error_readout = error_wire(circuit_output)\\n\\n    print(*error_readout, sep=\",\")\\n'\n\n\n\n\n```\nin1=np.array([0.8, 0.1234, 0], dtype=float)\nans1=0.19999999999999993,0.7999999999999999,0.0,0.0\nin2=np.array([1, 0.9876, 2], dtype=float)\nans2=0.0,0.0,0.0,1.0\nans=[ans1,ans2]\nj=0\nfor inputs in [in1, in2]:\n  p, alpha, tampered_wire = inputs[0], inputs[1], int(inputs[2])\n  error_readout = np.zeros(4, dtype=float)\n  circuit_output = circuit(p, alpha, tampered_wire)\n  error_readout = error_wire(circuit_output)\n  print(*error_readout, sep=\",\")\n  print(*[error_readout[i]==ans[j][i] for i in range(4)])\n  fig, ax = qml.draw_mpl(circuit, decimals=6)(p,alpha,tampered_wire)\n  j+=1\n```\n\n## Algorithms\n\n### algorithms_100_DeutschJozsa_solution\n\nTemplate: [here](https://github.com/XanaduAI/QHack/blob/master/Coding_Challenges/algorithms_100_DeutschJozsa_template/deutsch_jozsa_template.py).\n\n\n```\nimport sys\nimport pennylane as qml\nfrom pennylane import numpy as np\n\ndef deutsch_jozsa(oracle):\n    \"\"\"This function will determine whether an oracle defined by a function f is constant or balanced.\n\n    Args:\n        - oracle (function): Encoding of the f function as a quantum gate. The first two qubits refer to the input and the third to the output.\n\n    Returns:\n        - (str): \"constant\" or \"balanced\"\n    \"\"\"\n\n    dev = qml.device(\"default.qubit\", wires=3, shots=1)\n\n    @qml.qnode(dev)\n    def circuit():\n        \"\"\"Implements the Deutsch Jozsa algorithm.\"\"\"\n\n        # QHACK #\n\n        # Insert any pre-oracle processing here\n        qml.Hadamard(wires=0)\n        qml.Hadamard(wires=1)\n        qml.PauliX(wires=2)\n        qml.Hadamard(wires=2)\n\n        oracle()  # DO NOT MODIFY this line\n\n        # Insert any post-oracle processing here\n        qml.Hadamard(wires=0)\n        qml.Hadamard(wires=1)\n\n        # QHACK #\n\n        return qml.sample(wires=range(2))\n\n    sample = circuit()\n\n    \n\n    # QHACK #\n    prob = 1/2**(len(sample)) * (sum(sample))**2\n    if prob == 0:\n        func = 'constant'\n    else:\n        func = 'balanced'\n    \n    # From `sample` (a single call to the circuit), determine whether the function is constant or balanced.\n    return func\n    # QHACK #\n\n'''\nif __name__ == \"__main__\":\n    # DO NOT MODIFY anything in this code block\n    inputs = sys.stdin.read().split(\",\")\n    numbers = [int(i) for i in inputs]\n\n    def oracle():\n        for i in numbers:\n            qml.CNOT(wires=[i, 2])\n\n    output = deutsch_jozsa(oracle)\n    print(output)\n'''\n```\n\n\n\n\n    '\\nif __name__ == \"__main__\":\\n    # DO NOT MODIFY anything in this code block\\n    inputs = sys.stdin.read().split(\",\")\\n    numbers = [int(i) for i in inputs]\\n\\n    def oracle():\\n        for i in numbers:\\n            qml.CNOT(wires=[i, 2])\\n\\n    output = deutsch_jozsa(oracle)\\n    print(output)\\n'\n\n\n\n\n```\nin1 = [0]\n#ans1='balanced'\nin2 = [1,1]\n#ans2='constant'\n\nif __name__ == \"__main__\":\n    # DO NOT MODIFY anything in this code block\n    for inputs in [in1, in2]:\n      numbers = [int(i) for i in inputs]\n      def oracle():\n          for i in numbers:\n              qml.CNOT(wires=[i, 2])\n\n      output = deutsch_jozsa(oracle)\n      print(output)\n```\n\n    balanced\n    constant\n\n\n\n```\ndev = qml.device(\"default.qubit\", wires=3, shots=1)\n@qml.qnode(dev)\ndef circuit():\n    qml.Hadamard(wires=0)\n    qml.Hadamard(wires=1)\n    qml.PauliX(wires=2)\n    qml.Hadamard(wires=2)\n    oracle()  \n    qml.Hadamard(wires=0)\n    qml.Hadamard(wires=1)\n    return qml.sample(wires=range(2))\nfig, ax = qml.draw_mpl(circuit, decimals=6)()\n```\n\n### algorithms_200_AdaptingTopology_solution\n\nTemplate: [here](https://github.com/XanaduAI/QHack/blob/master/Coding_Challenges/algorithms_200_AdaptingTopology_template/adapting_topology_template.py).\n\n\n```\n#! /usr/bin/python3\nimport sys\nfrom pennylane import numpy as np\nimport pennylane as qml\n\ngraph = {\n    0: [1],\n    1: [0, 2, 3, 4],\n    2: [1],\n    3: [1],\n    4: [1, 5, 7, 8],\n    5: [4, 6],\n    6: [5, 7],\n    7: [4, 6],\n    8: [4],\n}\n\n\ndef n_swaps(cnot):\n    \"\"\"Count the minimum number of swaps needed to create the equivalent CNOT.\n    Args:\n        - cnot (qml.Operation): A CNOT gate that needs to be implemented on the hardware\n        You can find out the wires on which an operator works by asking for the 'wires' attribute: 'cnot.wires'\n    Returns:\n        - (int): minimum number of swaps\n    \"\"\"\n\n    # QHACK #\n    import queue\n    def minEdgeBFS(edges, u, v, n):\n\n        # visited[n] for keeping track\n        # of visited node in BFS\n        visited = [0] * n\n\n        # Initialize distances as 0\n        distance = [0] * n\n\n        # queue to do BFS.\n        Q = queue.Queue()\n        distance[u] = 0\n\n        Q.put(u)\n        visited[u] = True\n        while (not Q.empty()):\n            x = Q.get()\n\n            for i in range(len(edges[x])):\n                if (visited[edges[x][i]]):\n                    continue\n\n                # update distance for i\n                distance[edges[x][i]] = distance[x] + 1\n                Q.put(edges[x][i])\n                visited[edges[x][i]] = 1\n        return distance[v] - 1    \n    return 2*minEdgeBFS(graph, cnot.wires[0], cnot.wires[1], len(graph.keys()))\n    # QHACK #\n'''\nif __name__ == \"__main__\":\n    # DO NOT MODIFY anything in this code block\n    inputs = sys.stdin.read().split(\",\")\n    output = n_swaps(qml.CNOT(wires=[int(i) for i in inputs]))\n    print(f\"{output}\")\n'''\n```\n\n\n\n\n    '\\nif __name__ == \"__main__\":\\n    # DO NOT MODIFY anything in this code block\\n    inputs = sys.stdin.read().split(\",\")\\n    output = n_swaps(qml.CNOT(wires=[int(i) for i in inputs]))\\n    print(f\"{output}\")\\n'\n\n\n\n\n```\nin1 = 0, 1\nans1=0\nin2=8,2\nans2=4\nans=[ans1,ans2]\ni=0\nfor inputs in [in1, in2]:\n  output = n_swaps(qml.CNOT(wires=[int(i) for i in inputs]))\n  print(f\"{output}\", output== ans[i])\n  i=+1\n```\n\n    0 True\n    4 True\n\n\n### algorithms_300_AdderQFT_solution\n\nTemplate: [here](https://github.com/XanaduAI/QHack/blob/master/Coding_Challenges/algorithms_300_AdderQFT_template/adder_QFT_template.py).\n\n\n```\n#! /usr/bin/python3\n\nimport sys\nfrom pennylane import numpy as np\nimport pennylane as qml\n\n\ndef qfunc_adder(m, wires):\n    \"\"\"Quantum function capable of adding m units to a basic state given as input.\n\n    Args:\n        - m (int): units to add.\n        - wires (list(int)): list of wires in which the function will be executed on.\n    \"\"\"\n\n    qml.QFT(wires=wires)\n\n    # QHACK #\n    angle = np.pi * m\n    for i in wires:\n        qml.PhaseShift(angle/(2**i), wires=i)\n    # QHACK #\n\n    qml.QFT(wires=wires).inv()\n'''\nif __name__ == \"__main__\":\n    # DO NOT MODIFY anything in this code block\n    inputs = sys.stdin.read().split(\",\")\n    m = int(inputs[0])\n    n_wires = int(inputs[1])\n    wires = range(n_wires)\n\n    dev = qml.device(\"default.qubit\", wires=wires, shots=1)\n\n    @qml.qnode(dev)\n    def test_circuit():\n        # Input:  |2^{N-1}>\n        qml.PauliX(wires=0)\n\n        qfunc_adder(m, wires)\n        return qml.sample()\n\n    output = test_circuit()\n    print(*output, sep=\",\")\n'''\n```\n\n\n\n\n    '\\nif __name__ == \"__main__\":\\n    # DO NOT MODIFY anything in this code block\\n    inputs = sys.stdin.read().split(\",\")\\n    m = int(inputs[0])\\n    n_wires = int(inputs[1])\\n    wires = range(n_wires)\\n\\n    dev = qml.device(\"default.qubit\", wires=wires, shots=1)\\n\\n    @qml.qnode(dev)\\n    def test_circuit():\\n        # Input:  |2^{N-1}>\\n        qml.PauliX(wires=0)\\n\\n        qfunc_adder(m, wires)\\n        return qml.sample()\\n\\n    output = test_circuit()\\n    print(*output, sep=\",\")\\n'\n\n\n\n\n```\nin1=[2,3]\n#ans: 1,1,0\nin2=[5,4]\n#ans: 1,1,0,1\n\nif __name__ == \"__main__\":\n    # DO NOT MODIFY anything in this code block\n    for inputs in [in1, in2]:\n      #inputs = sys.stdin.read().split(\",\")\n      m = int(inputs[0])\n      n_wires = int(inputs[1])\n      wires = range(n_wires)\n\n      dev = qml.device(\"default.qubit\", wires=wires, shots=1)\n\n      @qml.qnode(dev)\n      def test_circuit():\n          # Input:  |2^{N-1}>\n          qml.PauliX(wires=0)\n\n          qfunc_adder(m, wires)\n          return qml.sample()\n\n      output = test_circuit()\n      print(*output, sep=\",\")\n```\n\n    1,1,0\n    1,1,0,1\n\n\n## Quantum Machine Learning\n\n### qml_100_GeneratingFourierState_solution\n\nTemplate: [here](https://github.com/XanaduAI/QHack/blob/master/Coding_Challenges/qml_100_GeneratingFourierState_template/generating_fourier_state_template.py).\n\n\n```\n#! /usr/bin/python3\n\nimport sys\nfrom pennylane import numpy as np\nimport pennylane as qml\n\ndef generating_fourier_state(n_qubits, m):\n    \"\"\"Function which, given the number of qubits and an integer m, returns the circuit and the angles that generate the state\n    QFT|m> following the above template.\n    Args:\n        - n_qubits (int): number of qubits in the circuit.\n        - m (int): basis state that we generate. For example, for 'm = 3' and 'n_qubits = 4'\n        we would generate the state QFT|0011> (3 in binary is 11).\n    Returns:\n       - (qml.QNode): circuit used to generate the state.\n       - (list[float]): angles that generate the state QFT|m>.\n    \"\"\"\n\n    dev = qml.device(\"default.qubit\", wires=n_qubits)\n\n    @qml.qnode(dev)\n    def circuit(angles):\n        \"\"\"This is the quantum circuit that we will use.\"\"\"\n\n        # QHACK #\n\n        # Add the template of the statement with the angles passed as an argument.\n        for w in range(n_qubits):\n            qml.Hadamard(wires=w)\n            qml.RZ(angles[w],wires=w)\n\n        # QHACK #\n\n        # We apply QFT^-1 to return to the computational basis.\n        # This will help us to see how well we have done.\n        qml.adjoint(qml.QFT)(wires=range(n_qubits))\n\n        # We return the probabilities of seeing each basis state.\n        return qml.probs(wires=range(n_qubits))\n\n    def error(angles):\n        \"\"\"This function will determine, given a set of angles, how well it approximates\n        the desired state. Here it will be necessary to call the circuit to work with these results.\n        \"\"\"\n\n        probs = circuit(angles)\n        # QHACK #\n\n        # The return error should be smaller when the state m is more likely to be obtained.\n        target=np.zeros(2**n_qubits)\n        target[m]=1\n\n        loss=np.sum((target-probs)**2)\n        return loss\n        # QHACK #\n\n    # This subroutine will find the angles that minimize the error function.\n    # Do not modify anything from here.\n\n    opt = qml.AdamOptimizer(stepsize=0.8)\n    epochs = 5000\n\n    angles = np.zeros(n_qubits, requires_grad=True)\n    for epoch in range(epochs):\n        angles = opt.step(error, angles)\n        angles = np.clip(opt.step(error, angles), -2 * np.pi, 2 * np.pi)\n\n    return circuit, angles\n\n'''\nif __name__ == \"__main__\":\n    # DO NOT MODIFY anything in this code block\n    inputs = sys.stdin.read().split(\",\")\n    n_qubits = int(inputs[0])\n    m = int(inputs[1])\n\n    output = generating_fourier_state(n_qubits, m)\n    output[0](output[1])\n    dev = qml.device(\"default.qubit\", wires=n_qubits)\n\n    @qml.qnode(dev)\n    def check_with_arbitrary_state():\n        for i in range(n_qubits):\n            qml.RY(i, wires=i)\n        for op in output[0].qtape.operations:\n            qml.apply(op)\n        return qml.state()\n\n    print(\",\".join([f\"{p.real.round(5)},{p.imag.round(5)}\" for p in check_with_arbitrary_state()]))\n'''\n```\n\n\n\n\n    '\\nif __name__ == \"__main__\":\\n    # DO NOT MODIFY anything in this code block\\n    inputs = sys.stdin.read().split(\",\")\\n    n_qubits = int(inputs[0])\\n    m = int(inputs[1])\\n\\n    output = generating_fourier_state(n_qubits, m)\\n    output[0](output[1])\\n    dev = qml.device(\"default.qubit\", wires=n_qubits)\\n\\n    @qml.qnode(dev)\\n    def check_with_arbitrary_state():\\n        for i in range(n_qubits):\\n            qml.RY(i, wires=i)\\n        for op in output[0].qtape.operations:\\n            qml.apply(op)\\n        return qml.state()\\n\\n    print(\",\".join([f\"{p.real.round(5)},{p.imag.round(5)}\" for p in check_with_arbitrary_state()]))\\n'\n\n\n\n\n```\nin1=[2,3]\n#Ans1=[0.0,0.0,0.33901,-0.33901,0.0,0.0,0.62054,-0.62054]\nin2=[3,2]\n#Ans2=[-0.28526,-0.18317,0.0,-0.0,-0.33528,-0.33528,-0.0,0.0,-0.18317,-0.28526,-0.0,0.0,-0.52217,-0.52217,-0.0,0.0]\n\nfor inputs in [in1, in2]:\n  n_qubits = int(inputs[0])\n  m = int(inputs[1])\n\n  output = generating_fourier_state(n_qubits, m)\n  output[0](output[1])\n  dev = qml.device(\"default.qubit\", wires=n_qubits)\n\n  @qml.qnode(dev)\n  def check_with_arbitrary_state():\n      for i in range(n_qubits):\n          qml.RY(i, wires=i)\n      for op in output[0].qtape.operations:\n          qml.apply(op)\n      return qml.state()\n\n  print(\",\".join([f\"{p.real.round(5)},{p.imag.round(5)}\" for p in check_with_arbitrary_state()]))\n```\n\n    0.0,0.0,0.33901,-0.33901,0.0,0.0,0.62054,-0.62054\n    -0.28526,-0.18317,0.0,-0.0,-0.33528,-0.33528,-0.0,0.0,-0.18316,-0.28526,-0.0,0.0,-0.52217,-0.52217,-0.0,0.0\n\n\n### qml_200_WhoLikesTheBeatles_solution\n\nTemplate: [here](https://github.com/XanaduAI/QHack/blob/master/Coding_Challenges/qml_200_WhoLikesTheBeatles_template/who_likes_the_beatles_template.py).\n\n\n```\n#! /usr/bin/python3\n\nimport sys\nfrom pennylane import numpy as np\nimport pennylane as qml\n\n\ndef distance(A, B):\n    \"\"\"Function that returns the distance between two vectors.\n\n    Args:\n        - A (list[int]): person's information: [age, minutes spent watching TV].\n        - B (list[int]): person's information: [age, minutes spent watching TV].\n\n    Returns:\n        - (float): distance between the two feature vectors.\n    \"\"\"\n\n    # QHACK #\n\n    # The Swap test is a method that allows you to calculate |<A|B>|^2 , you could use it to help you.\n    # The qml.AmplitudeEmbedding operator could help you too.\n    # qubit_number = int(np.ceil(np.log2(len(A))))\n    # dev = qml.device('default.qubit', wires=3 * qubit_number)\n    # # dev = qml.device(\"default.qubit\", ...\n    # @qml.qnode(dev)\n    def calc_angle(v1, v2):\n        unit_vector_1 = v1 / np.linalg.norm(v1)\n        unit_vector_2 = v2 / np.linalg.norm(v2)\n        dot_product = np.dot(unit_vector_1, unit_vector_2)\n        angle = np.arccos(dot_product)\n        return angle\n    dist = np.sqrt(2*(1-np.abs(np.cos(calc_angle(A, B)))))\n    \n\n    return dist\n    # QHACK #\n\n\ndef predict(dataset, new, k):\n    \"\"\"Function that given a dataset, determines if a new person do like Beatles or not.\n\n    Args:\n        - dataset (list): List with the age, minutes that different people watch TV, and if they like Beatles.\n        - new (list(int)): Age and TV minutes of the person we want to classify.\n        - k (int): number of nearby neighbors to be taken into account.\n\n    Returns:\n        - (str): \"YES\" if they like Beatles, \"NO\" otherwise.\n    \"\"\"\n\n    # DO NOT MODIFY anything in this code block\n\n    def k_nearest_classes():\n        \"\"\"Function that returns a list of k near neighbors.\"\"\"\n        distances = []\n        for data in dataset:\n            distances.append(distance(data[0], new))\n        nearest = []\n        for _ in range(k):\n            indx = np.argmin(distances)\n            nearest.append(indx)\n            distances[indx] += 2\n\n        return [dataset[i][1] for i in nearest]\n\n    output = k_nearest_classes()\n\n    return (\n        \"YES\" if len([i for i in output if i == \"YES\"]) > len(output) / 2 else \"NO\",\n        float(distance(dataset[0][0], new)),\n    )\n'''\nif __name__ == \"__main__\":\n    # DO NOT MODIFY anything in this code block\n    inputs = sys.stdin.read().split(\",\")\n    dataset = []\n    new = [int(inputs[0]), int(inputs[1])]\n    k = int(inputs[2])\n    for i in range(3, len(inputs), 3):\n        dataset.append([[int(inputs[i + 0]), int(inputs[i + 1])], str(inputs[i + 2])])\n\n    output = predict(dataset, new, k)\n    sol = 0 if output[0] == \"YES\" else 1\n    print(f\"{sol},{output[1]}\")\n'''\n```\n\n\n\n\n    '\\nif __name__ == \"__main__\":\\n    # DO NOT MODIFY anything in this code block\\n    inputs = sys.stdin.read().split(\",\")\\n    dataset = []\\n    new = [int(inputs[0]), int(inputs[1])]\\n    k = int(inputs[2])\\n    for i in range(3, len(inputs), 3):\\n        dataset.append([[int(inputs[i + 0]), int(inputs[i + 1])], str(inputs[i + 2])])\\n\\n    output = predict(dataset, new, k)\\n    sol = 0 if output[0] == \"YES\" else 1\\n    print(f\"{sol},{output[1]}\")\\n'\n\n\n\n\n```\n#ans1=0,0.4210528986556\n#ans2=0,0.9264606253589677\n\nfor i in range (1,3):\n  dataset_dir = F'/content/gdrive/My Drive/Contests/QHack2022/Coding Challenge/dataset/Beatles/{i}.in'\n  with open(dataset_dir, 'r') as f:\n    filein = f.readlines()\n    inputs = filein[0].split(\",\")\n\n  dataset = []\n  new = [int(inputs[0]), int(inputs[1])]\n  k = int(inputs[2])\n  for i in range(3, len(inputs), 3):\n      dataset.append([[int(inputs[i + 0]), int(inputs[i + 1])], str(inputs[i + 2])])\n\n  output = predict(dataset, new, k)\n  sol = 0 if output[0] == \"YES\" else 1\n  print(f\"{sol},{output[1]}\")\n```\n\n    0,0.42105289865559875\n    0,0.926460625358967\n\n\n### qml_400_BuildingQRAM_template_solution\n\nTemplate: [here](https://github.com/XanaduAI/QHack/blob/master/Coding_Challenges/qml_400_BuildingQRAM_template/building_QRAM_template.py).\n\nThe original idea was to use the RYGate(theta).control(3) instruction from qiskit to build the multicontrolledRY gate, however, PennyLane does not currently support said instruction via the pennylane-qiskit plugin. Therefore, one needs to hardcode the CCCRY gate. Available approaches:\n\n1) Define the 16x16 CCCRY gate matrix as a numpy.array() and pass it to the argument of the [qml.QubitUnitary()](https://pennylane.readthedocs.io/en/stable/code/api/pennylane.QubitUnitary.html) class. One more step: requires to set up a block matrix [[identity, 0], [0, U]] according to Tom Bromley's answer on the [XANADU discussion forum](https://discuss.pennylane.ai/t/control-of-a-quantum-state/796). \n\n2) Decompose the CCCRY gate into cNOTs and CRY gates. This would require to find the V and $V^{\\dagger}$ matrices of the decomposed circuit, solve the eigenvalue-eingenvector equation and calculate the fourth root square of the eigenvalues.\n\n3) The chosen approach: define the ry target gate and the control wires (qubits) using the [qml.ControlledQubitUnitary()](https://pennylane.readthedocs.io/en/stable/code/api/pennylane.ControlledQubitUnitary.html) class from PennyLane. \n\n#### Solution\n\n\n```\n#! /usr/bin/python3\n\nimport sys\nfrom pennylane import numpy as np\nimport pennylane as qml\n\n\ndef qRAM(thetas):\n    \"\"\"Function that generates the superposition state.\n\n    Args:\n        - thetas (list(float)): list of parameters (angles) to perform rotations.\n\n    Returns:\n        - (list(complex)): final state.\n    \"\"\"\n\n    # QHACK #\n\n    # Use this space to create auxiliary functions if you need it.\n\n    def CCCRY(theta, i):\n      \n      '''\n      Function that returns the CCCRY gate using the qml.ControlledQubitUnitary() class from PennyLane.\n      '''\n\n      ry  = np.array([[np.cos(theta/2), -np.sin(theta/2)],\n                      [np.sin(theta/2), np.cos(theta/2)]])     \n       \n      lst=[str(j) for j in basis[i]] \n      gate = qml.ControlledQubitUnitary(ry, control_wires=[0, 1, 2], wires=3, control_values=str(''.join(lst)))\n      return gate\n\n    n=3   \n    basis=[]\n    for i in range(2**n):\n      arr = []\n      for j in list(f'{i:0{n}b}'):    \n        arr.append(int(j))  \n      basis.append(arr)\n\n    # QHACK #\n\n    dev = qml.device(\"default.qubit\", wires=range(4))\n    global circuit\n    @qml.qnode(dev)\n    def circuit():\n\n        # QHACK #\n\n        # Create your circuit: the first three qubits will refer to the index, the fourth to the RY rotation.\n        for i in range (3):\n          qml.Hadamard(wires=i)\n        for i in range(len(thetas)):\n          CCCRY(thetas[i], i)\n\n        # QHACK #\n\n        return qml.state()\n\n    return circuit()\n\n'''\nif __name__ == \"__main__\":\n    # DO NOT MODIFY anything in this code block\n    inputs = sys.stdin.read().split(\",\")\n    thetas = np.array(inputs, dtype=float)\n\n    output = qRAM(thetas)\n    output = [float(i.real.round(6)) for i in output]\n    print(*output, sep=\",\")\n'''\n```\n\n\n\n\n    '\\nif __name__ == \"__main__\":\\n    # DO NOT MODIFY anything in this code block\\n    inputs = sys.stdin.read().split(\",\")\\n    thetas = np.array(inputs, dtype=float)\\n\\n    output = qRAM(thetas)\\n    output = [float(i.real.round(6)) for i in output]\\n    print(*output, sep=\",\")\\n'\n\n\n\n\n```\nin1=[0,0,0,0,0,0,0,0]\nAns1=[0.353553,0.0,0.353553,0.0,0.353553,0.0,0.353553,0.0,0.353553,-0.0,0.353553,-0.0,0.353553,0.0,0.353553,0.0]\nin2=[3.141592653589793,3.141592653589793,3.141592653589793,3.141592653589793,3.141592653589793,3.141592653589793,3.141592653589793,3.141592653589793]\nAns2= [0.0,0.353553,0.0,0.353553,0.0,0.353553,0.0,0.353553,-0.0,0.353553,-0.0,0.353553,-0.0,0.353553,-0.0,0.353553]\nin3=[0,0.2,0.5,0.1,0.1,0.2,0.4,0.6]\nAns3=[0.353553,0.0,0.351787,0.035296,0.342562,0.087471,0.353112,0.01767,0.353112,0.01767,0.351787,0.035296,0.346506,0.07024,0.337762,0.104482]\n\nfor inputs in [in1, in2, in3]:\n  if __name__ == \"__main__\":\n      # DO NOT MODIFY anything in this code block\n      thetas = np.array(inputs, dtype=float)\n\n      output = qRAM(thetas)\n      output = [float(i.real.round(6)) for i in output]\n      print(*output, sep=\",\")\n      fig, ax = qml.draw_mpl(circuit, decimals=6)()\n```\n\n#### **Bonus**\n\nApproaches 1 and 2 with PennyLane and Qiskit.\n\n##### **1) CCCRY gate from scratch (tensor product of its primitives)**\n\n\n\nThe algebra looks like this:\n\n$CRY = I\\otimes |0\\rangle\\langle 0\\rangle + RY(\\theta) \\otimes |1 \\rangle \\langle 1|$\n\n$CCRY = I\\otimes I\\otimes |0\\rangle\\langle 0\\rangle + CRY \\otimes |1 \\rangle \\langle 1|$\n\n$CCCRY = I\\otimes I\\otimes I\\otimes |0\\rangle\\langle 0\\rangle + CCRY \\otimes |1 \\rangle \\langle 1|$\n\n\n```\nfrom pennylane import numpy as np\n\ndef CRY(theta):\n  '''\n  Function that defines the CRY gate. Where CRY = CU3(0,0,theta).\n  '''\n  CRY  = np.array([[1, 0, 0, 0],\n                  [0, np.cos(theta/2), 0, -np.sin(theta/2)],\n                  [0, 0, 1, 0],\n                  [0, np.sin(theta/2), 0, np.cos(theta/2)]])\n  return CRY\n\nCRY(np.pi).round()\n```\n\n\n\n\n    tensor([[ 1.,  0.,  0.,  0.],\n            [ 0.,  0.,  0., -1.],\n            [ 0.,  0.,  1.,  0.],\n            [ 0.,  1.,  0.,  0.]], requires_grad=True)\n\n\n\n\n```\ndef CCCRY(theta):\n  '''\n  Function that returns the CCCRY gate coded with numpy from tensor product of its primitives. \n  '''\n\n  # First, define the CRY gate, where CRY = CU3(0,0,theta).\n  CRY  = np.array([[1, 0, 0, 0],\n                  [0, np.cos(theta/2), 0, -np.sin(theta/2)],\n                  [0, 0, 1, 0],\n                  [0, np.sin(theta/2), 0, np.cos(theta/2)]])\n  \n  psi_0 = np.array([1, 0])\n  psi_1 = np.array([0, 1])\n\n  outer0 = np.outer(psi_0, psi_0)\n  outer1 = np.outer(psi_1, psi_1)\n\n  ccry = np.kron(np.identity(4), outer0) + np.kron(CRY, outer1)\n  cccry = np.kron(np.identity(8), outer0) + np.kron(ccry, outer1)\n  \n  gate = qml.QubitUnitary(cccry, wires=[0, 1, 2, 3])\n\n  return gate\n\nCCCRY(0) # Evaluating for angle 0.\n```\n\n\n\n\n    QubitUnitary(tensor([[1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],\n            [0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],\n            [0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],\n            [0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],\n            [0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],\n            [0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],\n            [0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.],\n            [0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],\n            [0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],\n            [0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0.],\n            [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],\n            [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],\n            [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0.],\n            [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0.],\n            [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0.],\n            [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]], requires_grad=True), wires=[0, 1, 2, 3])\n\n\n\n**Using Qiskit:**\n\n\n```\n!pip install qiskit\n```\n\n    Requirement already satisfied: qiskit in /usr/local/lib/python3.7/dist-packages (0.34.2)\n    Requirement already satisfied: qiskit-ibmq-provider==0.18.3 in /usr/local/lib/python3.7/dist-packages (from qiskit) (0.18.3)\n    Requirement already satisfied: qiskit-ignis==0.7.0 in /usr/local/lib/python3.7/dist-packages (from qiskit) (0.7.0)\n    Requirement already satisfied: qiskit-terra==0.19.2 in /usr/local/lib/python3.7/dist-packages (from qiskit) (0.19.2)\n    Requirement already satisfied: qiskit-aer==0.10.3 in /usr/local/lib/python3.7/dist-packages (from qiskit) (0.10.3)\n    Requirement already satisfied: numpy>=1.16.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.10.3->qiskit) (1.21.5)\n    Requirement already satisfied: scipy>=1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.10.3->qiskit) (1.7.3)\n    Requirement already satisfied: requests-ntlm>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (1.1.0)\n    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (2.23.0)\n    Requirement already satisfied: websocket-client>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (1.3.1)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (2.8.2)\n    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (1.24.3)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ignis==0.7.0->qiskit) (57.4.0)\n    Requirement already satisfied: retworkx>=0.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ignis==0.7.0->qiskit) (0.11.0)\n    Requirement already satisfied: ply>=3.10 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.2->qiskit) (3.11)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.2->qiskit) (5.4.8)\n    Requirement already satisfied: tweedledum<2.0,>=1.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.2->qiskit) (1.1.1)\n    Requirement already satisfied: symengine>=0.8 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.2->qiskit) (0.9.2)\n    Requirement already satisfied: python-constraint>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.2->qiskit) (1.4.0)\n    Requirement already satisfied: stevedore>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.2->qiskit) (3.5.0)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.2->qiskit) (0.3.4)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.2->qiskit) (1.7.1)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.8.0->qiskit-ibmq-provider==0.18.3->qiskit) (1.15.0)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit) (2021.10.8)\n    Requirement already satisfied: cryptography>=1.3 in /usr/local/lib/python3.7/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit) (36.0.2)\n    Requirement already satisfied: ntlm-auth>=1.0.2 in /usr/local/lib/python3.7/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit) (1.5.0)\n    Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit) (1.15.0)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit) (2.21)\n    Requirement already satisfied: pbr!=2.1.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from stevedore>=3.0.0->qiskit-terra==0.19.2->qiskit) (5.8.1)\n    Requirement already satisfied: importlib-metadata>=1.7.0 in /usr/local/lib/python3.7/dist-packages (from stevedore>=3.0.0->qiskit-terra==0.19.2->qiskit) (2.1.3)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=1.7.0->stevedore>=3.0.0->qiskit-terra==0.19.2->qiskit) (3.7.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra==0.19.2->qiskit) (1.2.1)\n\n\n\n```\nfrom qiskit import QuantumCircuit, QuantumRegister, transpile\nfrom qiskit.circuit.library.standard_gates import RYGate\nfrom qiskit.circuit import Parameter\nfrom qiskit import BasicAer\n\nbackend = BasicAer.get_backend('unitary_simulator')\n\nqr=QuantumRegister(2)\nqc=QuantumCircuit(qr)\na=Parameter('a') # You can replace a with your choice of angle here.\nCRYg=RYGate(np.pi).control(1) # Or passing the angle directly here.\nqc.append(CRYg,qr)\nprint(qc)\n#print(qc.draw())\njob = backend.run(transpile(qc, backend))\njob.result().get_unitary(qc, decimals=3)\n```\n\n                    \n    q85_0: \u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\n           \u250c\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2510\n    q85_1: \u2524 Ry(\u03c0) \u251c\n           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n    Pass: UnitarySynthesis - 0.01144 (ms)\n    Pass: UnrollCustomDefinitions - 0.05627 (ms)\n    Begin BasisTranslator from source basis {('cry', 2)} to target basis {'u1', 'x', 'rz', 'u3', 'measure', 'snapshot', 'delay', 'cx', 'sx', 'id', 'reset', 'barrier', 'unitary', 'u2'}.\n    Basis translation path search completed in 0.021s.\n    Basis translation paths composed in 0.075s.\n    Basis translation instructions replaced in 0.002s.\n    Pass: BasisTranslator - 109.61914 (ms)\n    Pass: RemoveResetInZeroState - 0.01860 (ms)\n    Pass: Depth - 0.03767 (ms)\n    Pass: FixedPoint - 0.02599 (ms)\n    Pass: Optimize1qGatesDecomposition - 3.59464 (ms)\n    Pass: CXCancellation - 0.05293 (ms)\n    Pass: UnitarySynthesis - 0.01669 (ms)\n    Pass: UnrollCustomDefinitions - 0.14544 (ms)\n    Begin BasisTranslator from source basis {('cx', 2), ('u2', 1)} to target basis {'u1', 'x', 'rz', 'u3', 'measure', 'snapshot', 'delay', 'cx', 'sx', 'id', 'reset', 'barrier', 'unitary', 'u2'}.\n    Basis translation path search completed in 0.001s.\n    Basis translation paths composed in 0.000s.\n    Basis translation instructions replaced in 0.000s.\n    Pass: BasisTranslator - 14.85324 (ms)\n    Pass: Depth - 0.03505 (ms)\n    Pass: FixedPoint - 0.02337 (ms)\n    Pass: Optimize1qGatesDecomposition - 2.71153 (ms)\n    Pass: CXCancellation - 0.05817 (ms)\n    Pass: UnitarySynthesis - 0.01693 (ms)\n    Pass: UnrollCustomDefinitions - 0.05722 (ms)\n    Begin BasisTranslator from source basis {('cx', 2), ('u2', 1)} to target basis {'u1', 'x', 'rz', 'u3', 'measure', 'snapshot', 'delay', 'cx', 'sx', 'id', 'reset', 'barrier', 'unitary', 'u2'}.\n    Basis translation path search completed in 0.001s.\n    Basis translation paths composed in 0.001s.\n    Basis translation instructions replaced in 0.000s.\n    Pass: BasisTranslator - 9.08780 (ms)\n    Pass: ContainsInstruction - 0.01478 (ms)\n    Total Transpile Time - 215.13820 (ms)\n    Total Assembly Time - 0.17762 (ms)\n    \"unitary_simulator\" only supports 1 shot. Setting shots=1.\n\n\n\n\n\n    array([[ 1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j],\n           [ 0.+0.j,  0.+0.j,  0.+0.j, -1.-0.j],\n           [ 0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j],\n           [ 0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j]])\n\n\n\n- $CCRY = I\\otimes I\\otimes |0\\rangle\\langle 0\\rangle + CRY \\otimes |1 \\rangle \\langle 1|$\n\n\n```\npsi_0 = np.array([1, 0])\npsi_1 = np.array([0, 1])\n\nouter0 = np.outer(psi_0, psi_0)\nouter1 = np.outer(psi_1, psi_1)\n\nid4=np.identity(4)\n\nccry = np.kron(id4, outer0) + np.kron(CRY(np.pi), outer1)\nccry.round()\n```\n\n\n\n\n    tensor([[ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],\n            [ 0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.],\n            [ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.],\n            [ 0.,  0.,  0.,  0.,  0.,  0.,  0., -1.],\n            [ 0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.],\n            [ 0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.],\n            [ 0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.],\n            [ 0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.]], requires_grad=True)\n\n\n\n\n```\nfrom qiskit import QuantumCircuit, QuantumRegister, transpile\nfrom qiskit.circuit.library.standard_gates import RYGate\nfrom qiskit.circuit import Parameter\nfrom qiskit import BasicAer\n\nbackend = BasicAer.get_backend('unitary_simulator')\nqr=QuantumRegister(3)\nqc=QuantumCircuit(qr)\na=Parameter('a') # You can replace a with your choice of angle here.\nCCRY=RYGate(np.pi).control(2) # Or passing the angle directly here.\nqc.append(CCRY,qr)\nprint(qc)\njob = backend.run(transpile(qc, backend))\njob.result().get_unitary(qc, decimals=3)\n```\n\n                    \n    q42_0: \u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\n               \u2502    \n    q42_1: \u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\n           \u250c\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2510\n    q42_2: \u2524 Ry(\u03c0) \u251c\n           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n    Pass: UnitarySynthesis - 0.01121 (ms)\n    Pass: UnrollCustomDefinitions - 0.97299 (ms)\n    Begin BasisTranslator from source basis {('ry', 1), ('ccx', 3)} to target basis {'u1', 'x', 'rz', 'u3', 'measure', 'snapshot', 'delay', 'cx', 'sx', 'id', 'reset', 'barrier', 'unitary', 'u2'}.\n    Basis translation path search completed in 0.021s.\n    Basis translation paths composed in 0.047s.\n    Basis translation instructions replaced in 0.002s.\n    Pass: BasisTranslator - 78.46189 (ms)\n    Pass: RemoveResetInZeroState - 0.02861 (ms)\n    Pass: Depth - 0.04268 (ms)\n    Pass: FixedPoint - 0.02360 (ms)\n    Pass: Optimize1qGatesDecomposition - 9.78231 (ms)\n    Pass: CXCancellation - 0.12493 (ms)\n    Pass: UnitarySynthesis - 0.01597 (ms)\n    Pass: UnrollCustomDefinitions - 0.13447 (ms)\n    Begin BasisTranslator from source basis {('u1', 1), ('cx', 2), ('u2', 1)} to target basis {'u1', 'x', 'rz', 'u3', 'measure', 'snapshot', 'delay', 'cx', 'sx', 'id', 'reset', 'barrier', 'unitary', 'u2'}.\n    Basis translation path search completed in 0.000s.\n    Basis translation paths composed in 0.001s.\n    Basis translation instructions replaced in 0.000s.\n    Pass: BasisTranslator - 8.47244 (ms)\n    Pass: Depth - 0.05341 (ms)\n    Pass: FixedPoint - 0.02360 (ms)\n    Pass: Optimize1qGatesDecomposition - 11.36684 (ms)\n    Pass: CXCancellation - 0.11635 (ms)\n    Pass: UnitarySynthesis - 0.01645 (ms)\n    Pass: UnrollCustomDefinitions - 0.41437 (ms)\n    Begin BasisTranslator from source basis {('u1', 1), ('cx', 2), ('u2', 1)} to target basis {'u1', 'x', 'rz', 'u3', 'measure', 'snapshot', 'delay', 'cx', 'sx', 'id', 'reset', 'barrier', 'unitary', 'u2'}.\n    Basis translation path search completed in 0.000s.\n    Basis translation paths composed in 0.003s.\n    Basis translation instructions replaced in 0.000s.\n    Pass: BasisTranslator - 9.82809 (ms)\n    Pass: Depth - 0.04005 (ms)\n    Pass: FixedPoint - 0.02217 (ms)\n    Pass: Optimize1qGatesDecomposition - 7.84516 (ms)\n    Pass: CXCancellation - 0.11587 (ms)\n    Pass: UnitarySynthesis - 0.01597 (ms)\n    Pass: UnrollCustomDefinitions - 0.12851 (ms)\n    Begin BasisTranslator from source basis {('u1', 1), ('cx', 2), ('u2', 1)} to target basis {'u1', 'x', 'rz', 'u3', 'measure', 'snapshot', 'delay', 'cx', 'sx', 'id', 'reset', 'barrier', 'unitary', 'u2'}.\n    Basis translation path search completed in 0.000s.\n    Basis translation paths composed in 0.001s.\n    Basis translation instructions replaced in 0.000s.\n    Pass: BasisTranslator - 6.37126 (ms)\n    Pass: ContainsInstruction - 0.01407 (ms)\n    Total Transpile Time - 197.58224 (ms)\n    Total Assembly Time - 0.17500 (ms)\n    \"unitary_simulator\" only supports 1 shot. Setting shots=1.\n\n\n\n\n\n    array([[ 1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j],\n           [ 0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j],\n           [ 0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j],\n           [ 0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n            -1.+0.j],\n           [ 0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  1.-0.j,  0.+0.j,  0.+0.j,\n             0.+0.j],\n           [ 0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  1.-0.j,  0.+0.j,\n             0.+0.j],\n           [ 0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  1.-0.j,\n             0.+0.j],\n           [ 0.+0.j,  0.+0.j,  0.+0.j,  1.-0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j]])\n\n\n\n- $CCCRY = I\\otimes I\\otimes I\\otimes |0\\rangle\\langle 0\\rangle + CCRY \\otimes |1 \\rangle \\langle 1|$\n\n\n```\ncccry = np.kron(np.identity(8), outer0) + np.kron(ccry, outer1)\ncccry.round()\n```\n\n\n\n\n    tensor([[ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,\n              0.,  0.,  0.],\n            [ 0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,\n              0.,  0.,  0.],\n            [ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,\n              0.,  0.,  0.],\n            [ 0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,\n              0.,  0.,  0.],\n            [ 0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,\n              0.,  0.,  0.],\n            [ 0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,\n              0.,  0.,  0.],\n            [ 0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,\n              0.,  0.,  0.],\n            [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,\n              0.,  0., -1.],\n            [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,\n              0.,  0.,  0.],\n            [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,\n              0.,  0.,  0.],\n            [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,\n              0.,  0.,  0.],\n            [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,\n              0.,  0.,  0.],\n            [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,\n              0.,  0.,  0.],\n            [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,\n              1.,  0.,  0.],\n            [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,\n              0.,  1.,  0.],\n            [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,\n              0.,  0.,  0.]], requires_grad=True)\n\n\n\n\n```\nfrom qiskit import QuantumCircuit, QuantumRegister, transpile\nfrom qiskit.circuit.library.standard_gates import RYGate\nfrom qiskit.circuit import Parameter\nfrom qiskit import BasicAer\n\nbackend = BasicAer.get_backend('unitary_simulator')\nqr=QuantumRegister(4)\nqc=QuantumCircuit(qr)\na=Parameter('a') # You can replace a with your choice of angle here.\nCCRY=RYGate(np.pi).control(3) # Or passing the angle directly here.\nqc.append(CCRY,qr)\nprint(qc)\njob = backend.run(transpile(qc, backend))\njob.result().get_unitary(qc, decimals=3)\n```\n\n                    \n    q56_0: \u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\n               \u2502    \n    q56_1: \u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\n               \u2502    \n    q56_2: \u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\n           \u250c\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2510\n    q56_3: \u2524 Ry(\u03c0) \u251c\n           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n    Pass: UnitarySynthesis - 0.00811 (ms)\n    Pass: UnrollCustomDefinitions - 4.09937 (ms)\n    Begin BasisTranslator from source basis {('u', 1), ('cx', 2), ('p', 1)} to target basis {'u1', 'x', 'rz', 'u3', 'measure', 'snapshot', 'delay', 'cx', 'sx', 'id', 'reset', 'barrier', 'unitary', 'u2'}.\n    Basis translation path search completed in 0.003s.\n    Basis translation paths composed in 0.006s.\n    Basis translation instructions replaced in 0.008s.\n    Pass: BasisTranslator - 25.99406 (ms)\n    Pass: RemoveResetInZeroState - 0.04315 (ms)\n    Pass: Depth - 0.05531 (ms)\n    Pass: FixedPoint - 0.02337 (ms)\n    Pass: Optimize1qGatesDecomposition - 14.12964 (ms)\n    Pass: CXCancellation - 0.18859 (ms)\n    Pass: UnitarySynthesis - 0.01645 (ms)\n    Pass: UnrollCustomDefinitions - 0.16713 (ms)\n    Begin BasisTranslator from source basis {('u3', 1), ('cx', 2)} to target basis {'u1', 'x', 'rz', 'u3', 'measure', 'snapshot', 'delay', 'cx', 'sx', 'id', 'reset', 'barrier', 'unitary', 'u2'}.\n    Basis translation path search completed in 0.000s.\n    Basis translation paths composed in 0.001s.\n    Basis translation instructions replaced in 0.000s.\n    Pass: BasisTranslator - 6.92129 (ms)\n    Pass: Depth - 0.05412 (ms)\n    Pass: FixedPoint - 0.02313 (ms)\n    Pass: Optimize1qGatesDecomposition - 21.16537 (ms)\n    Pass: CXCancellation - 0.14496 (ms)\n    Pass: UnitarySynthesis - 0.01693 (ms)\n    Pass: UnrollCustomDefinitions - 0.12732 (ms)\n    Begin BasisTranslator from source basis {('u3', 1), ('cx', 2)} to target basis {'u1', 'x', 'rz', 'u3', 'measure', 'snapshot', 'delay', 'cx', 'sx', 'id', 'reset', 'barrier', 'unitary', 'u2'}.\n    Basis translation path search completed in 0.000s.\n    Basis translation paths composed in 0.000s.\n    Basis translation instructions replaced in 0.000s.\n    Pass: BasisTranslator - 14.92429 (ms)\n    Pass: Depth - 0.04506 (ms)\n    Pass: FixedPoint - 0.02241 (ms)\n    Pass: Optimize1qGatesDecomposition - 13.02290 (ms)\n    Pass: CXCancellation - 0.15664 (ms)\n    Pass: UnitarySynthesis - 0.06413 (ms)\n    Pass: UnrollCustomDefinitions - 0.20313 (ms)\n    Begin BasisTranslator from source basis {('u3', 1), ('cx', 2)} to target basis {'u1', 'x', 'rz', 'u3', 'measure', 'snapshot', 'delay', 'cx', 'sx', 'id', 'reset', 'barrier', 'unitary', 'u2'}.\n    Basis translation path search completed in 0.000s.\n    Basis translation paths composed in 0.000s.\n    Basis translation instructions replaced in 0.000s.\n    Pass: BasisTranslator - 7.99203 (ms)\n    Pass: ContainsInstruction - 0.01287 (ms)\n    Total Transpile Time - 183.41327 (ms)\n    Total Assembly Time - 0.19264 (ms)\n    \"unitary_simulator\" only supports 1 shot. Setting shots=1.\n\n\n\n\n\n    array([[ 1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j],\n           [ 0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j],\n           [ 0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j],\n           [ 0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j],\n           [ 0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j],\n           [ 0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j],\n           [ 0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j,\n             0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j],\n           [ 0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j, -1.-0.j],\n           [ 0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j],\n           [ 0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j],\n           [ 0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j],\n           [ 0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j],\n           [ 0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j],\n           [ 0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j,\n             0.+0.j,  0.+0.j],\n           [ 0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             1.+0.j,  0.+0.j],\n           [ 0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j,\n             0.+0.j,  0.+0.j]])\n\n\n\n##### **2) CCCRU gate decomposition**\n\n\n```\ndef CYdagger(gate, theta):\n  return np.conjugate(gate(theta))\n\ndef my_ansatz(gate, gate_dagger, **kwargs):\n  '''\n  This function performs the decomposition of a MultiControlled gate according to Barenco et al., 1995, pg. 17.\n  '''\n\n  qml.QubitUnitary(gate, wires=[0, 3])\n  qml.CNOT(wires=[0,1])\n  qml.QubitUnitary(gate_dagger, wires=[1, 3]) #adjunt\n  qml.CNOT(wires=[0,1])\n  qml.QubitUnitary(gate, wires=[1, 3])\n  qml.CNOT(wires=[1,2])\n  qml.QubitUnitary(gate_dagger, wires=[2, 3]) #adjunt\n  qml.CNOT(wires=[0,2])\n  qml.QubitUnitary(gate, wires=[2, 3])\n  qml.CNOT(wires=[1,2])\n  qml.QubitUnitary(gate_dagger, wires=[2, 3]) #adjunt\n  qml.CNOT(wires=[0,2])\n  qml.QubitUnitary(gate, wires=[2, 3])\n```\n\n## Quantum Chemistry\n\n### qchem_100_IsParticlePreserving_solution\n\nTemplate [here](https://github.com/XanaduAI/QHack/blob/master/Coding_Challenges/qchem_100_IsParticlePreserving_template/particle_conservation_template.py).\n\n\n```\n#! /usr/bin/python3\n\nimport sys\nimport pennylane as qml\nfrom pennylane import numpy as np\n\n\ndef binary_list(m, n):\n    \"\"\"Converts number m to binary encoded on a list of length n\n\n    Args:\n        - m (int): Number to convert to binary\n        - n (int): Number of wires in the circuit\n\n    Returns:\n        - (list(int)): Binary stored as a list of length n\n    \"\"\"\n\n    arr = []\n    # QHACK #\n    for i in list(f'{m:0{n}b}'):\n      arr.append(int(i))\n    # QHACK #\n    return arr\n\n\ndef basis_states(n):\n    \"\"\"Given a number n, returns a list of all binary_list(m,n) for m < 2**n, thus providing all basis states\n         for a circuit of n wires\n\n    Args:\n        - n(int): integer representing the number of wires in the circuit\n\n    Returns:\n        - (list(list(int))): list of basis states represented as lists of 0s and 1s.\n    \"\"\"\n\n    arr = []\n\n    # QHACK #\n    for i in range(2**n):\n      basis = binary_list(i, n)\n      arr.append(basis)\n    # QHACK #\n\n    return arr\n\n\ndef is_particle_preserving(circuit, n):\n    \"\"\"Given a circuit and its number of wires n, returns 1 if it preserves the number of particles, and 0 if it does not\n\n    Args:\n        - circuit (qml.QNode): A QNode that has a state such as [0,0,1,0] as an input and outputs the final state after performing\n        quantum operation\n        - n (int): the number of wires of circuit\n\n    Returns:\n        - (bool): True / False according to whether the input circuit preserves the number of particles or not\n    \"\"\"\n\n    # QHACK #\n    list_of_basis = basis_states(n)\n    arr=[]\n    for basis in list_of_basis:\n      statevector = circuit(basis)\n      arr.append(sum(x !=0 for x in statevector)) # hamming_weight \n    result = all(element == arr[0] for element in arr)\n    if result:\n      return False\n    else:\n      return True\n    # QHACK #\n\n'''\nif __name__ == \"__main__\":\n    # DO NOT MODIFY anything in this code block\n    inputs = sys.stdin.read().split(\";\")\n    gate_list = []\n    wire_list = []\n    param_list = []\n    i = 1\n\n    while i < len(inputs):\n        gate_obj = getattr(qml, str(inputs[i]))\n        gate_wires = gate_obj.num_wires\n        input_wires = list(map(int, str(inputs[i + 1]).split(\",\")))\n        gate_list.append(str(inputs[i]))\n        wire_list.append(input_wires)\n        if \"non_parametric_ops\" not in gate_obj.__module__.split(\".\"):\n            input_params = list(map(float, str(inputs[i + 2]).split(\",\")))\n            param_list.append(input_params)\n            i += 1\n        i += 2\n\n    wire_list = np.array(wire_list, dtype=object)\n    param_list = np.array(param_list, dtype=object)\n\n    n = int(inputs[0])\n    dev = qml.device(\"default.qubit\", wires=n)\n\n    @qml.qnode(dev)\n    def circ(gate_list, wire_list, param_list, state):\n        qml.BasisState(np.array(state), wires=range(n))\n        j = 0\n        for i in range(len(gate_list)):\n            gate = getattr(qml, str(gate_list[i]))\n            if \"non_parametric_ops\" not in gate.__module__.split(\".\"):\n                gate(*param_list[j], wires=[int(w) for w in wire_list[i]])\n                j += 1\n            else:\n                gate(wires=[int(w) for w in wire_list[i]])\n        return qml.state()\n\n    def circuit(state):\n        return circ(gate_list, wire_list, param_list, state)\n\n    output = is_particle_preserving(circuit, n)\n\n    print(output)\n'''\n```\n\n\n\n\n    '\\nif __name__ == \"__main__\":\\n    # DO NOT MODIFY anything in this code block\\n    inputs = sys.stdin.read().split(\";\")\\n    gate_list = []\\n    wire_list = []\\n    param_list = []\\n    i = 1\\n\\n    while i < len(inputs):\\n        gate_obj = getattr(qml, str(inputs[i]))\\n        gate_wires = gate_obj.num_wires\\n        input_wires = list(map(int, str(inputs[i + 1]).split(\",\")))\\n        gate_list.append(str(inputs[i]))\\n        wire_list.append(input_wires)\\n        if \"non_parametric_ops\" not in gate_obj.__module__.split(\".\"):\\n            input_params = list(map(float, str(inputs[i + 2]).split(\",\")))\\n            param_list.append(input_params)\\n            i += 1\\n        i += 2\\n\\n    wire_list = np.array(wire_list, dtype=object)\\n    param_list = np.array(param_list, dtype=object)\\n\\n    n = int(inputs[0])\\n    dev = qml.device(\"default.qubit\", wires=n)\\n\\n    @qml.qnode(dev)\\n    def circ(gate_list, wire_list, param_list, state):\\n        qml.BasisState(np.array(state), wires=range(n))\\n        j = 0\\n        for i in range(len(gate_list)):\\n            gate = getattr(qml, str(gate_list[i]))\\n            if \"non_parametric_ops\" not in gate.__module__.split(\".\"):\\n                gate(*param_list[j], wires=[int(w) for w in wire_list[i]])\\n                j += 1\\n            else:\\n                gate(wires=[int(w) for w in wire_list[i]])\\n        return qml.state()\\n\\n    def circuit(state):\\n        return circ(gate_list, wire_list, param_list, state)\\n\\n    output = is_particle_preserving(circuit, n)\\n\\n    print(output)\\n'\n\n\n\n\n```\nin1 = ['4','Hadamard','0','CNOT','0,1','Hadamard','0']\n#Ans: False\nin2 = ['4','DoubleExcitation','0,1,2,3','0.732','SingleExcitation','0,1','1.0']\n#Ans: True\n```\n\n\n```\nfor inputs in [in1, in2]:\n  gate_list = []\n  wire_list = []\n  param_list = []\n  i = 1\n\n  while i < len(inputs):\n      gate_obj = getattr(qml, str(inputs[i]))\n      gate_wires = gate_obj.num_wires\n      input_wires = list(map(int, str(inputs[i + 1]).split(\",\")))\n      gate_list.append(str(inputs[i]))\n      wire_list.append(input_wires)\n      if \"non_parametric_ops\" not in gate_obj.__module__.split(\".\"):\n          input_params = list(map(float, str(inputs[i + 2]).split(\",\")))\n          param_list.append(input_params)\n          i += 1\n      i += 2\n\n  wire_list = np.array(wire_list, dtype=object)\n  param_list = np.array(param_list, dtype=object)\n\n  n = int(inputs[0])\n  dev = qml.device(\"default.qubit\", wires=n)\n\n  @qml.qnode(dev)\n  def circ(gate_list, wire_list, param_list, state):\n      qml.BasisState(np.array(state), wires=range(n))\n      j = 0\n      for i in range(len(gate_list)):\n          gate = getattr(qml, str(gate_list[i]))\n          if \"non_parametric_ops\" not in gate.__module__.split(\".\"):\n              gate(*param_list[j], wires=[int(w) for w in wire_list[i]])\n              j += 1\n          else:\n              gate(wires=[int(w) for w in wire_list[i]])\n      return qml.state()\n\n  def circuit(state):\n      return circ(gate_list, wire_list, param_list, state)\n\n  output = is_particle_preserving(circuit, n)\n\n  print(output)\n```\n\n    False\n    True\n\n\n### qchem_200_OptimizingMeasurements_solution\n\nTemplate [here](https://github.com/XanaduAI/QHack/blob/master/Coding_Challenges/qchem_200_OptimizingMeasurements_template/optimizing_measurements_template.py).\n\n\n```\n#! /usr/bin/python3\n\nimport sys\n\n\ndef check_simplification(op1, op2):\n    \"\"\"As we have seen in the problem statement, given two Pauli operators, you could obtain the expected value\n    of each of them by running a single circuit following the two defined rules. This function will determine whether,\n    given two Pauli operators, such a simplification can be produced.\n\n    Args:\n        - op1 (list(str)): First Pauli word (list of Pauli operators), e.g., [\"Y\", \"I\", \"Z\", \"I\"].\n        - op2 (list(str)): Second Pauli word (list of Pauli operators), e.g., [\"Y\", \"I\", \"X\", \"I\"].\n\n    Returns:\n        - (bool): 'True' if we can simplify them, 'False' otherwise. For the example args above, the third qubit does not allow simplification, so the function would return `False`.\n    \"\"\"\n\n    # QHACK\n    '''\n    for i in op1:\n      for j in op2:\n        value=False\n        if i==j or i=='I' or j=='I':\n          value=True \n    return value\n    '''\n    # This algorithm has the same effect as the one above, however with complexity O(N) rather than O(N**2). Both lists must have the same dimension.\n    for i in range(len(op1)):\n      if op1[i] != op2[i] and op1[i] != 'I' and op2[i] != 'I':\n        return False\n    return True\n    # QHACK\n\n\ndef join_operators(op1, op2):\n    \"\"\"This function will receive two operators that we know can be simplified\n    and returns the operator corresponding to the union of the two previous ones.\n\n    Args:\n        - op1 (list(str)): First Pauli word (list of Pauli operators), e.g., [\"Y\", \"I\", \"Z\", \"I\"].\n        - op2 (list(str)): Second Pauli word (list of Pauli operators), e.g., [\"Y\", \"X\", \"I\", \"I\"].\n\n    Returns:\n        - (list(str)): Pauli operator corresponding to the union of op1 and op2.\n        For the case above the output would be [\"Y\", \"X\", \"Z\", \"I\"]\n    \"\"\"\n\n    # QHACK\n    result = []\n    if check_simplification(op1, op2):\n      for index, elem in enumerate(op1):\n        if elem == op2[index] or elem==\"I\":\n          result.append(op2[index])\n        elif op2[index]=='I':\n          result.append(elem)\n      return result\n    else:\n      return None\n    # QHACK\n\n\ndef optimize_measurements(obs_hamiltonian):\n    \"\"\"This function will go through the list of Pauli words provided in the statement, grouping the operators\n    following the simplification process of the previous functions.\n\n    Args:\n        - obs_hamiltonian (list(list(str))): Groups of Pauli words making up the Hamiltonian.\n\n    Returns:\n        - (list(list(str))): The chosen Pauli operators to measure after grouping.\n    \"\"\"\n\n    final_solution = []\n\n    for op1 in obs_hamiltonian:\n        added = False\n        for i, op2 in enumerate(final_solution):\n\n            if check_simplification(op1, op2):\n                final_solution[i] = join_operators(op1, op2)\n                added = True\n                break\n        if not added:\n            final_solution.append(op1)\n\n    return final_solution\n\n\ndef compression_ratio(obs_hamiltonian, final_solution):\n    \"\"\"Function that calculates the compression ratio of the procedure.\n\n    Args:\n        - obs_hamiltonian (list(list(str))): Groups of Pauli operators making up the Hamiltonian.\n        - final_solution (list(list(str))): Your final selection of observables.\n\n    Returns:\n        - (float): Compression ratio your solution.\n    \"\"\"\n\n    # QHACK\n    initial=len(obs_hamiltonian)\n    final=len(final_solution)\n    r=1-(final/initial)\n    return r\n    # QHACK\n\n'''\nif __name__ == \"__main__\":\n    # DO NOT MODIFY anything in this code block\n\n    inputs = sys.stdin.read().split(\",\")\n\n    obs_hamiltonian = []\n    # open file and read the content in a list\n    aux = []\n    for i, line in enumerate(inputs):\n        if i == 0:\n            first = int(line)\n        else:\n            aux.append(line[0])\n            if i % first == 0:\n                obs_hamiltonian.append(aux)\n                aux = []\n\n    output = optimize_measurements(obs_hamiltonian)\n    print(compression_ratio(obs_hamiltonian, output))\n'''\n```\n\n\n\n\n    '\\nif __name__ == \"__main__\":\\n    # DO NOT MODIFY anything in this code block\\n\\n    inputs = sys.stdin.read().split(\",\")\\n\\n    obs_hamiltonian = []\\n    # open file and read the content in a list\\n    aux = []\\n    for i, line in enumerate(inputs):\\n        if i == 0:\\n            first = int(line)\\n        else:\\n            aux.append(line[0])\\n            if i % first == 0:\\n                obs_hamiltonian.append(aux)\\n                aux = []\\n\\n    output = optimize_measurements(obs_hamiltonian)\\n    print(compression_ratio(obs_hamiltonian, output))\\n'\n\n\n\n\n```\nin1=['4','Z','I','I','I','Z','Y','I','I','X','I','X','Y','I','Z','I','I']\n#Ans: 0.5\n\nin2=['4','Z','X','I','I','Z','Y','I','I','X','I','X','Y','I','Z','I','I']\n#Ans 0.25\n\nfor inputs in [in1, in2]:\n  obs_hamiltonian = []\n  aux = []\n  for i, line in enumerate(inputs):\n      if i == 0:\n          first = int(line)\n      else:\n          aux.append(line[0])\n          if i % first == 0:\n              obs_hamiltonian.append(aux)\n              aux = []\n\n  output = optimize_measurements(obs_hamiltonian)\n  print(compression_ratio(obs_hamiltonian, output))\n```\n\n    0.5\n    0.25\n\n\n## Games\n\n### games_100_TardigradeMasquerade_solution\n\nTemplate: [here](https://github.com/XanaduAI/QHack/blob/master/Coding_Challenges/games_100_TardigradeMasquerade_template/tardigrade_template.py)\n\n\n```\nimport sys\nimport pennylane as qml\nfrom pennylane import numpy as np\n\n\ndef second_renyi_entropy(rho):\n    \"\"\"Computes the second Renyi entropy of a given density matrix.\"\"\"\n    # DO NOT MODIFY anything in this code block\n    rho_diag_2 = np.diagonal(rho) ** 2.0\n    return -np.real(np.log(np.sum(rho_diag_2)))\n\n\ndef compute_entanglement(theta):\n    \"\"\"Computes the second Renyi entropy of circuits with and without a tardigrade present.\n\n    Args:\n        - theta (float): the angle that defines the state psi_ABT\n\n    Returns:\n        - (float): The entanglement entropy of qubit B with no tardigrade\n        initially present\n        - (float): The entanglement entropy of qubit B where the tardigrade\n        was initially present\n    \"\"\"\n\n    dev = qml.device(\"default.qubit\", wires=3)\n\n    # QHACK #\n    @qml.qnode(dev)\n    def circuits(theta, tartigrade):\n      if not tartigrade:\n        qml.Hadamard(wires=0)\n        qml.CNOT(wires=[0, 1])\n        qml.PauliX(wires=0)\n        return qml.density_matrix(wires=[0])     \n\n    def partial_trace(rho, qubit_2_keep): # Credits: GitHub @neversakura.\n        num_qubit = int(np.log2(rho.shape[0]))\n        qubit_axis = [(i, num_qubit + i) for i in range(num_qubit)\n                      if i not in qubit_2_keep]\n        minus_factor = [(i, 2 * i) for i in range(len(qubit_axis))]\n        minus_qubit_axis = [(q[0] - m[0], q[1] - m[1])\n                            for q, m in zip(qubit_axis, minus_factor)]\n        rho_res = np.reshape(rho, [2, 2] * num_qubit)\n        qubit_left = num_qubit - len(qubit_axis)\n        for i, j in minus_qubit_axis:\n            rho_res = np.trace(rho_res, axis1=i, axis2=j)\n        if qubit_left > 1:\n            rho_res = np.reshape(rho_res, [2 ** qubit_left] * 2)\n        return rho_res  \n\n    psi_0 = np.array([1, 0])\n    psi_1 = np.array([0, 1])\n    g_bt = np.kron(psi_0, psi_0)\n    e_bt=np.cos(theta/2)*np.kron(psi_1,psi_0)+np.sin(theta/2)*np.kron(psi_0,psi_1)\n    psi_abt = 1/np.sqrt(2)*(np.kron(psi_0, e_bt)+np.kron(psi_1, g_bt))\n    rho_abt = np.outer(psi_abt, np.conj(psi_abt))\n    rho_b = partial_trace(rho_abt, [1])\n    mu_b = circuits(theta, 0)\n    s_mub = second_renyi_entropy(mu_b)\n    s_rhob = second_renyi_entropy(rho_b)\n   \n    return s_mub, s_rhob\n    # QHACK #\n\n'''\nif __name__ == \"__main__\":\n    # DO NOT MODIFY anything in this code block\n    theta = np.array(sys.stdin.read(), dtype=float)\n\n    S2_without_tardigrade, S2_with_tardigrade = compute_entanglement(theta)\n    print(*[S2_without_tardigrade, S2_with_tardigrade], sep=\",\")\n'''\n```\n\n\n\n\n    '\\nif __name__ == \"__main__\":\\n    # DO NOT MODIFY anything in this code block\\n    theta = np.array(sys.stdin.read(), dtype=float)\\n\\n    S2_without_tardigrade, S2_with_tardigrade = compute_entanglement(theta)\\n    print(*[S2_without_tardigrade, S2_with_tardigrade], sep=\",\")\\n'\n\n\n\n\n```\nin1=0.7745598277086928\nin2=4.91504584447079\nans1=0.6931471805599457,0.6730064814954014\nans2=0.6931471805599457,0.545165726123828\n\nfor theta in [in1, in2]:\n  S2_without_tardigrade, S2_with_tardigrade = compute_entanglement(theta)\n  print(*[S2_without_tardigrade, S2_with_tardigrade], sep=\",\")\n```\n\n    0.6931471805599457,0.6730064814954021\n    0.6931471805599457,0.5451657261238287\n\n\n### games_200_CHSH_solution\n\nTemplate: [here](https://github.com/XanaduAI/QHack/blob/master/Coding_Challenges/games_200_CHSH_template/CHSH_game_template.py)\n\n\n```\n#! /usr/bin/python3\n\nimport sys\nimport pennylane as qml\nfrom pennylane import numpy as np\n\n\ndev = qml.device(\"default.qubit\", wires=2)\n\n\ndef prepare_entangled(alpha, beta):\n    \"\"\"Construct a circuit that prepares the (not necessarily maximally) entangled state in terms of alpha and beta\n    Do not forget to normalize.\n\n    Args:\n        - alpha (float): real coefficient of |00>\n        - beta (float): real coefficient of |11>\n    \"\"\"\n\n    # QHACK #\n    theta=2*np.arctan2(beta,alpha)\n    qml.RY(theta,wires=0)\n    qml.CNOT(wires=[0,1])\n\n    # QHACK #\n\n@qml.qnode(dev)\ndef chsh_circuit(theta_A0, theta_A1, theta_B0, theta_B1, x, y, alpha, beta):\n    \"\"\"Construct a circuit that implements Alice's and Bob's measurements in the rotated bases\n\n    Args:\n        - theta_A0 (float): angle that Alice chooses when she receives x=0\n        - theta_A1 (float): angle that Alice chooses when she receives x=1\n        - theta_B0 (float): angle that Bob chooses when he receives x=0\n        - theta_B1 (float): angle that Bob chooses when he receives x=1\n        - x (int): bit received by Alice\n        - y (int): bit received by Bob\n        - alpha (float): real coefficient of |00>\n        - beta (float): real coefficient of |11>\n\n    Returns:\n        - (np.tensor): Probabilities of each basis state\n    \"\"\"\n\n    prepare_entangled(alpha, beta)\n\n    # QHACK #\n    if x==0:\n        qml.RY(2*theta_A0,wires=0)\n    else:\n        qml.RY(2*theta_A1,wires=0)\n    if y==0:\n        qml.RY(2*theta_B0+np.pi/2,wires=1)\n    else:\n        qml.RY(2*theta_B1+np.pi/2,wires=1)\n    # QHACK #\n\n    return qml.probs(wires=[0, 1])\n    \n\ndef winning_prob(params, alpha, beta):\n    \"\"\"Define a function that returns the probability of Alice and Bob winning the game.\n\n    Args:\n        - params (list(float)): List containing [theta_A0,theta_A1,theta_B0,theta_B1]\n        - alpha (float): real coefficient of |00>\n        - beta (float): real coefficient of |11>\n\n    Returns:\n        - (float): Probability of winning the game\n    \"\"\"\n\n    # QHACK #\n    win=0\n    p=chsh_circuit(params[0],params[1],params[2],\n                   params[3],1,1,alpha,beta)\n    win=win+p[1]+p[2]\n    p=chsh_circuit(params[0],params[1],params[2],\n                   params[3],0,1,alpha,beta)\n    win=win+p[0]+p[3]\n    p=chsh_circuit(params[0],params[1],params[2],\n                   params[3],1,0,alpha,beta)\n    win=win+p[0]+p[3]\n    p=chsh_circuit(params[0],params[1],params[2],\n                   params[3],0,0,alpha,beta)\n    win=win+p[0]+p[3]\n    # QHACK #\n    \n    return win/4\n\ndef optimize(alpha, beta):\n    \"\"\"Define a function that optimizes theta_A0, theta_A1, theta_B0, theta_B1 to maximize the probability of winning the game\n\n    Args:\n        - alpha (float): real coefficient of |00>\n        - beta (float): real coefficient of |11>\n\n    Returns:\n        - (float): Probability of winning\n    \"\"\"\n\n    def cost(params):\n        \"\"\"Define a cost function that only depends on params, given alpha and beta fixed\"\"\"\n        return 1-winning_prob(params, alpha, beta)**2\n\n    # QHACK #\n\n    #Initialize parameters, choose an optimization method and number of steps\n    init_params = np.zeros(4, requires_grad=True)\n    opt = qml.AdagradOptimizer(stepsize=0.23)\n    steps = 100\n\n    # QHACK #\n    \n    # set the initial parameter values\n    params = init_params\n\n    for i in range(steps):\n        # update the circuit parameters \n        # QHACK #\n \n        params = opt.step(cost, params)\n\n        # QHACK #\n\n    return winning_prob(params, alpha, beta)\n'''\nif __name__ == '__main__':\n    inputs = sys.stdin.read().split(\",\")\n    output = optimize(float(inputs[0]), float(inputs[1]))\n    print(f\"{output}\")\n'''\n```\n\n\n\n\n    '\\nif __name__ == \\'__main__\\':\\n    inputs = sys.stdin.read().split(\",\")\\n    output = optimize(float(inputs[0]), float(inputs[1]))\\n    print(f\"{output}\")\\n'\n\n\n\n\n```\nin1=1,1\n#0.85355\nin2=1.0,0.0\n#0.75\n\nfor inputs in [in1, in2]:\n  output = optimize(float(inputs[0]), float(inputs[1]))\n  print(f\"{output}\")\n```\n\n    0.8535533905932737\n    0.75\n\n\n# &nbsp; <a href=\"#\"></a> References\n\n\\[1] [QHack2022 problemset templates](https://github.com/XanaduAI/QHack/tree/master/Coding_Challenges).\n\n[2] [PennyLane Documentation](https://pennylane.readthedocs.io/en/stable/).\n\n[3] Nielsen MA, Chuang IL. 2010. Quantum Computation and Quantum Information. New York: [Cambridge Univ. Press.](https://doi.org/10.1017/CBO9780511976667) 10th Anniv. Ed.\n", "meta": {"hexsha": "2a65bb1ecbd35167fcb9e1acb31529fc0836de01", "size": 340573, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "solutions_notebook.ipynb", "max_stars_repo_name": "zemarchezi/QHack2022", "max_stars_repo_head_hexsha": "e388a546027168c3f1d48ad2e7ecf831425bb2dc", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "solutions_notebook.ipynb", "max_issues_repo_name": "zemarchezi/QHack2022", "max_issues_repo_head_hexsha": "e388a546027168c3f1d48ad2e7ecf831425bb2dc", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solutions_notebook.ipynb", "max_forks_repo_name": "zemarchezi/QHack2022", "max_forks_repo_head_hexsha": "e388a546027168c3f1d48ad2e7ecf831425bb2dc", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2022-03-16T00:02:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T20:12:23.000Z", "avg_line_length": 340573.0, "max_line_length": 340573, "alphanum_fraction": 0.8123221747, "converted": true, "num_tokens": 31612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3415824994383169, "lm_q2_score": 0.11920292045759122, "lm_q1q2_score": 0.04071763151025089}}
{"text": "# Constraint-based modelling using CobraPy\n\n## Installing CobraPy\n\n\n```python\n!pip install cobra\n```\n\n    Collecting cobra\n      Downloading cobra-0.22.1-py2.py3-none-any.whl (2.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.4 MB 5.1 MB/s \n    \u001b[?25hRequirement already satisfied: pandas~=1.0 in /usr/local/lib/python3.7/dist-packages (from cobra) (1.1.5)\n    Collecting ruamel.yaml~=0.16\n      Downloading ruamel.yaml-0.17.17-py3-none-any.whl (109 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 109 kB 51.0 MB/s \n    \u001b[?25hCollecting optlang~=1.5\n      Downloading optlang-1.5.2-py2.py3-none-any.whl (147 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 147 kB 55.8 MB/s \n    \u001b[?25hCollecting depinfo\n      Downloading depinfo-1.7.0-py2.py3-none-any.whl (8.6 kB)\n    Collecting pydantic~=1.6\n      Downloading pydantic-1.8.2-cp37-cp37m-manylinux2014_x86_64.whl (10.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 10.1 MB 56.2 MB/s \n    \u001b[?25hCollecting httpx~=0.14\n      Downloading httpx-0.21.1-py3-none-any.whl (83 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 83 kB 2.0 MB/s \n    \u001b[?25hRequirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from cobra) (0.16.0)\n    Collecting diskcache~=5.0\n      Downloading diskcache-5.3.0-py3-none-any.whl (44 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 44 kB 2.8 MB/s \n    \u001b[?25hCollecting swiglpk\n      Downloading swiglpk-5.0.3-cp37-cp37m-manylinux2010_x86_64.whl (2.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.1 MB 54.3 MB/s \n    \u001b[?25hCollecting rich>=8.0\n      Downloading rich-10.15.2-py3-none-any.whl (214 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 214 kB 68.1 MB/s \n    \u001b[?25hRequirement already satisfied: importlib-resources in /usr/local/lib/python3.7/dist-packages (from cobra) (5.4.0)\n    Requirement already satisfied: numpy~=1.13 in /usr/local/lib/python3.7/dist-packages (from cobra) (1.19.5)\n    Collecting python-libsbml==5.19.0\n      Downloading python_libsbml-5.19.0-cp37-cp37m-manylinux1_x86_64.whl (6.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.2 MB 11.3 MB/s \n    \u001b[?25hRequirement already satisfied: appdirs~=1.4 in /usr/local/lib/python3.7/dist-packages (from cobra) (1.4.4)\n    Collecting httpcore<0.15.0,>=0.14.0\n      Downloading httpcore-0.14.3-py3-none-any.whl (56 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 56 kB 4.1 MB/s \n    \u001b[?25hCollecting rfc3986[idna2008]<2,>=1.3\n      Downloading rfc3986-1.5.0-py2.py3-none-any.whl (31 kB)\n    Collecting sniffio\n      Downloading sniffio-1.2.0-py3-none-any.whl (10 kB)\n    Requirement already satisfied: charset-normalizer in /usr/local/lib/python3.7/dist-packages (from httpx~=0.14->cobra) (2.0.8)\n    Requirement already satisfied: certifi in /usr/local/lib/python3.7/dist-packages (from httpx~=0.14->cobra) (2021.10.8)\n    Collecting anyio==3.*\n      Downloading anyio-3.4.0-py3-none-any.whl (78 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 78 kB 7.6 MB/s \n    \u001b[?25hCollecting h11<0.13,>=0.11\n      Downloading h11-0.12.0-py3-none-any.whl (54 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 54 kB 3.3 MB/s \n    \u001b[?25hRequirement already satisfied: idna>=2.8 in /usr/local/lib/python3.7/dist-packages (from anyio==3.*->httpcore<0.15.0,>=0.14.0->httpx~=0.14->cobra) (2.10)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from anyio==3.*->httpcore<0.15.0,>=0.14.0->httpx~=0.14->cobra) (3.10.0.2)\n    Requirement already satisfied: six>=1.9 in /usr/local/lib/python3.7/dist-packages (from optlang~=1.5->cobra) (1.15.0)\n    Requirement already satisfied: sympy>=1.0 in /usr/local/lib/python3.7/dist-packages (from optlang~=1.5->cobra) (1.7.1)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas~=1.0->cobra) (2.8.2)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas~=1.0->cobra) (2018.9)\n    Collecting commonmark<0.10.0,>=0.9.0\n      Downloading commonmark-0.9.1-py2.py3-none-any.whl (51 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51 kB 7.0 MB/s \n    \u001b[?25hCollecting colorama<0.5.0,>=0.4.0\n      Downloading colorama-0.4.4-py2.py3-none-any.whl (16 kB)\n    Requirement already satisfied: pygments<3.0.0,>=2.6.0 in /usr/local/lib/python3.7/dist-packages (from rich>=8.0->cobra) (2.6.1)\n    Collecting ruamel.yaml.clib>=0.1.2\n      Downloading ruamel.yaml.clib-0.2.6-cp37-cp37m-manylinux1_x86_64.whl (546 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 546 kB 41.8 MB/s \n    \u001b[?25hRequirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.0->optlang~=1.5->cobra) (1.2.1)\n    Requirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from depinfo->cobra) (4.8.2)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->depinfo->cobra) (3.6.0)\n    Installing collected packages: sniffio, rfc3986, h11, anyio, swiglpk, ruamel.yaml.clib, httpcore, commonmark, colorama, ruamel.yaml, rich, python-libsbml, pydantic, optlang, httpx, diskcache, depinfo, cobra\n    Successfully installed anyio-3.4.0 cobra-0.22.1 colorama-0.4.4 commonmark-0.9.1 depinfo-1.7.0 diskcache-5.3.0 h11-0.12.0 httpcore-0.14.3 httpx-0.21.1 optlang-1.5.2 pydantic-1.8.2 python-libsbml-5.19.0 rfc3986-1.5.0 rich-10.15.2 ruamel.yaml-0.17.17 ruamel.yaml.clib-0.2.6 sniffio-1.2.0 swiglpk-5.0.3\n\n\n\n```python\n!pip install pytest_benchmark\n```\n\n    Collecting pytest_benchmark\n      Downloading pytest_benchmark-3.4.1-py2.py3-none-any.whl (50 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 50 kB 2.7 MB/s \n    \u001b[?25hCollecting py-cpuinfo\n      Downloading py-cpuinfo-8.0.0.tar.gz (99 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 99 kB 5.5 MB/s \n    \u001b[?25hCollecting pytest>=3.8\n      Downloading pytest-6.2.5-py3-none-any.whl (280 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 280 kB 32.2 MB/s \n    \u001b[?25hRequirement already satisfied: attrs>=19.2.0 in /usr/local/lib/python3.7/dist-packages (from pytest>=3.8->pytest_benchmark) (21.2.0)\n    Requirement already satisfied: py>=1.8.2 in /usr/local/lib/python3.7/dist-packages (from pytest>=3.8->pytest_benchmark) (1.11.0)\n    Requirement already satisfied: importlib-metadata>=0.12 in /usr/local/lib/python3.7/dist-packages (from pytest>=3.8->pytest_benchmark) (4.8.2)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from pytest>=3.8->pytest_benchmark) (21.3)\n    Collecting pluggy<2.0,>=0.12\n      Downloading pluggy-1.0.0-py2.py3-none-any.whl (13 kB)\n    Requirement already satisfied: toml in /usr/local/lib/python3.7/dist-packages (from pytest>=3.8->pytest_benchmark) (0.10.2)\n    Requirement already satisfied: iniconfig in /usr/local/lib/python3.7/dist-packages (from pytest>=3.8->pytest_benchmark) (1.1.1)\n    Requirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=0.12->pytest>=3.8->pytest_benchmark) (3.10.0.2)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=0.12->pytest>=3.8->pytest_benchmark) (3.6.0)\n    Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->pytest>=3.8->pytest_benchmark) (3.0.6)\n    Building wheels for collected packages: py-cpuinfo\n      Building wheel for py-cpuinfo (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for py-cpuinfo: filename=py_cpuinfo-8.0.0-py3-none-any.whl size=22258 sha256=80d722800ae4468be413d6b14e309641237d7dd2cbe6e617bda71df7d589706f\n      Stored in directory: /root/.cache/pip/wheels/d2/f1/1f/041add21dc9c4220157f1bd2bd6afe1f1a49524c3396b94401\n    Successfully built py-cpuinfo\n    Installing collected packages: pluggy, pytest, py-cpuinfo, pytest-benchmark\n      Attempting uninstall: pluggy\n        Found existing installation: pluggy 0.7.1\n        Uninstalling pluggy-0.7.1:\n          Successfully uninstalled pluggy-0.7.1\n      Attempting uninstall: pytest\n        Found existing installation: pytest 3.6.4\n        Uninstalling pytest-3.6.4:\n          Successfully uninstalled pytest-3.6.4\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    datascience 0.10.6 requires folium==0.2.1, but you have folium 0.8.3 which is incompatible.\u001b[0m\n    Successfully installed pluggy-1.0.0 py-cpuinfo-8.0.0 pytest-6.2.5 pytest-benchmark-3.4.1\n\n\n\n\n\n```python\nimport cobra\n```\n\n### Testing all the requirements are satisified\n\n\n```python\nimport cobra.test\ncobra.test.test_all()\n```\n\n    ============================= test session starts ==============================\n    platform linux -- Python 3.7.12, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 -- /usr/bin/python3\n    cachedir: .pytest_cache\n    benchmark: 3.4.1 (defaults: timer=time.perf_counter disable_gc=False min_rounds=5 min_time=0.000005 max_time=1.0 calibration_precision=10 warmup=False warmup_iterations=100000)\n    rootdir: /content\n    plugins: benchmark-3.4.1, anyio-3.4.0, typeguard-2.7.1\n    collecting ... collected 11 items\n    \n    test/test_manipulation/test_annotate.py::test_sbo_annotation PASSED      [  9%]\n    test/test_manipulation/test_delete.py::test_prune_unused_metabolites_output_type PASSED [ 18%]\n    test/test_manipulation/test_delete.py::test_prune_unused_metabolites_sanity PASSED [ 27%]\n    test/test_manipulation/test_delete.py::test_prune_unused_reactions_output_type PASSED [ 36%]\n    test/test_manipulation/test_delete.py::test_prune_unused_rxns_functionality PASSED [ 45%]\n    test/test_manipulation/test_delete.py::test_gene_knockout PASSED         [ 54%]\n    test/test_manipulation/test_delete.py::test_remove_genes PASSED          [ 63%]\n    test/test_manipulation/test_modify.py::test_escape_ids PASSED            [ 72%]\n    test/test_manipulation/test_modify.py::test_rename_genes PASSED          [ 81%]\n    test/test_manipulation/test_validate.py::test_validate_mass_balance PASSED [ 90%]\n    test/test_manipulation/test_validate.py::test_validate_formula_compartment PASSED [100%]\n    \n    =============================== warnings summary ===============================\n    ../usr/local/lib/python3.7/dist-packages/_pytest/config/__init__.py:1114\n      /usr/local/lib/python3.7/dist-packages/_pytest/config/__init__.py:1114: PytestAssertRewriteWarning: Module already imported so cannot be rewritten: anyio\n        self._mark_plugins_for_rewrite(hook)\n    \n    -- Docs: https://docs.pytest.org/en/stable/warnings.html\n    ======================== 11 passed, 1 warning in 2.82s =========================\n\n\n\n\n\n    <ExitCode.OK: 0>\n\n\n\n### Reading a constraint-based model\n\nIf you have a SBML model\n\n\n```python\necoli = cobra.io.read_sbml_model(\"e_coli_core.xml\")\n```\n\nIf you have a JSON model\n\n\n```python\necoli = cobra.io.load_json_model(filename)\n```\n\nIf you have a MAT model\n\n\n```python\necoli =  cobra.io.load_matlab_model(\"e_coli_core.mat\")\n```\n\n### How a model object looks like\n\n\n```python\necoli\n```\n\n\n\n\n\n<table>\n    <tr>\n        <td><strong>Name</strong></td>\n        <td>e_coli_core</td>\n    </tr><tr>\n        <td><strong>Memory address</strong></td>\n        <td>0x07fbfebe36f50</td>\n    </tr><tr>\n        <td><strong>Number of metabolites</strong></td>\n        <td>72</td>\n    </tr><tr>\n        <td><strong>Number of reactions</strong></td>\n        <td>95</td>\n    </tr><tr>\n        <td><strong>Number of groups</strong></td>\n        <td>0</td>\n    </tr><tr>\n        <td><strong>Objective expression</strong></td>\n        <td>1.0*BIOMASS_Ecoli_core_w_GAM - 1.0*BIOMASS_Ecoli_core_w_GAM_reverse_712e5</td>\n    </tr><tr>\n        <td><strong>Compartments</strong></td>\n        <td>extracellular space, cytosol</td>\n    </tr>\n  </table>\n\n\n\n### Different attributes of this model object\n\n\n```python\nvars(ecoli).keys()\n```\n\n\n\n\n    dict_keys(['_id', 'name', 'notes', '_annotation', '_trimmed', '_trimmed_genes', '_trimmed_reactions', 'genes', 'reactions', 'metabolites', 'groups', '_compartments', '_contexts', '_solver', '_tolerance', '_sbml'])\n\n\n\n\n```python\necoli.genes[:10]\n```\n\n\n\n\n    [<Gene b1241 at 0x7fbfe876eb10>,\n     <Gene b0351 at 0x7fbfe8773050>,\n     <Gene s0001 at 0x7fbfe8773410>,\n     <Gene b1849 at 0x7fbfe8773990>,\n     <Gene b3115 at 0x7fbfe8773ed0>,\n     <Gene b2296 at 0x7fbfe8775050>,\n     <Gene b1276 at 0x7fbfe87758d0>,\n     <Gene b0118 at 0x7fbfe8775a10>,\n     <Gene b0474 at 0x7fbfe8775f10>,\n     <Gene b0116 at 0x7fbfe8775510>]\n\n\n\nLooking at active exchange reactions\n\n\n```python\necoli.medium\n```\n\n\n\n\n    {'EX_co2_e': 1000.0,\n     'EX_glc__D_e': 10.0,\n     'EX_h2o_e': 1000.0,\n     'EX_h_e': 1000.0,\n     'EX_nh4_e': 1000.0,\n     'EX_o2_e': 1000.0,\n     'EX_pi_e': 1000.0}\n\n\n\nLooking at all echange reactions\n\n\n```python\necoli.exchanges\n```\n\n\n\n\n    [<Reaction EX_ac_e at 0x7fbfe86a9d90>,\n     <Reaction EX_acald_e at 0x7fbfe86acc90>,\n     <Reaction EX_akg_e at 0x7fbfe86b22d0>,\n     <Reaction EX_co2_e at 0x7fbfe86b7e10>,\n     <Reaction EX_etoh_e at 0x7fbfe86b2b50>,\n     <Reaction EX_for_e at 0x7fbfe86bb5d0>,\n     <Reaction EX_fru_e at 0x7fbfe86bb790>,\n     <Reaction EX_fum_e at 0x7fbfe86becd0>,\n     <Reaction EX_glc__D_e at 0x7fbfe86bed50>,\n     <Reaction EX_gln__L_e at 0x7fbfe86bb2d0>,\n     <Reaction EX_glu__L_e at 0x7fbfe86c0a50>,\n     <Reaction EX_h_e at 0x7fbfe86c0d10>,\n     <Reaction EX_h2o_e at 0x7fbfe86c0f10>,\n     <Reaction EX_lac__D_e at 0x7fbfe86c8dd0>,\n     <Reaction EX_mal__L_e at 0x7fbfe86c8b50>,\n     <Reaction EX_nh4_e at 0x7fbfe86c4650>,\n     <Reaction EX_o2_e at 0x7fbfe86c8e10>,\n     <Reaction EX_pi_e at 0x7fbfe86caf10>,\n     <Reaction EX_pyr_e at 0x7fbfe86cbc50>,\n     <Reaction EX_succ_e at 0x7fbfe86cb150>]\n\n\n\n### Accessing the metabolites and reactions in the model\n\nMetabolites\n\n\n```python\necoli.metabolites[:10]\n```\n\n\n\n\n    [<Metabolite glc__D_e at 0x7fbfe87b9cd0>,\n     <Metabolite gln__L_c at 0x7fbfe87b9d50>,\n     <Metabolite gln__L_e at 0x7fbfe87c05d0>,\n     <Metabolite glu__L_c at 0x7fbfe87c0690>,\n     <Metabolite glu__L_e at 0x7fbfe87c21d0>,\n     <Metabolite glx_c at 0x7fbfe87c3810>,\n     <Metabolite h2o_c at 0x7fbfe87c42d0>,\n     <Metabolite h2o_e at 0x7fbfe87c4c10>,\n     <Metabolite h_c at 0x7fbfe87c6c90>,\n     <Metabolite h_e at 0x7fbfe87c38d0>]\n\n\n\n\n```python\necoli.metabolites.glc__D_e.summary()\n```\n\n\n\n\n<h3>glc__D_e</h3><p>C6H12O6</p><h4>Producing Reactions</h4><table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Percent</th>\n      <th>Flux</th>\n      <th>Reaction</th>\n      <th>Definition</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>100.00%</td>\n      <td>10</td>\n      <td>EX_glc__D_e</td>\n      <td>glc__D_e &lt;=&gt;</td>\n    </tr>\n  </tbody>\n</table><h4>Consuming Reactions</h4><table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Percent</th>\n      <th>Flux</th>\n      <th>Reaction</th>\n      <th>Definition</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>100.00%</td>\n      <td>-10</td>\n      <td>GLCpts</td>\n      <td>glc__D_e + pep_c --&gt; g6p_c + pyr_c</td>\n    </tr>\n  </tbody>\n</table>\n\n\n\n\n```python\nvars(ecoli.metabolites.glc__D_e).keys()\n```\n\n\n\n\n    dict_keys(['_id', 'name', 'notes', '_annotation', '_model', '_reaction', 'formula', 'compartment', 'charge', '_bound'])\n\n\n\nReactions\n\n\n```python\necoli.reactions[:10]\n```\n\n\n\n\n    [<Reaction PFK at 0x7fbfe873e410>,\n     <Reaction PFL at 0x7fbfe873e390>,\n     <Reaction PGI at 0x7fbfe8740310>,\n     <Reaction PGK at 0x7fbfe8740f10>,\n     <Reaction PGL at 0x7fbfe8740550>,\n     <Reaction ACALD at 0x7fbfe8749590>,\n     <Reaction AKGt2r at 0x7fbfe874b3d0>,\n     <Reaction PGM at 0x7fbfe873eb90>,\n     <Reaction PIt2r at 0x7fbfe874e890>,\n     <Reaction ALCD2x at 0x7fbfe874e490>]\n\n\n\n\n```python\necoli.reactions.ATPM.summary()\n```\n\n\n\n\n<h3>ATPM</h3><p>atp_c + h2o_c --> adp_c + h_c + pi_c</p><p>Bounds: 8.39, 1000.0</p><p>Flux: 8.39</p>\n\n\n\n\n```python\nvars(ecoli.reactions.ATPM).keys()\n```\n\n\n\n\n    dict_keys(['_id', 'name', 'notes', '_annotation', '_gene_reaction_rule', 'subsystem', '_genes', '_metabolites', '_model', '_lower_bound', '_upper_bound'])\n\n\n\n\n```python\necoli.reactions.ATPM.name\n```\n\n\n\n\n    'ATP maintenance requirement'\n\n\n\n### Simulating the model using flux balance analysis\n\n\n```python\nsolution = ecoli.optimize()\nvars(solution).keys()\n```\n\n\n\n\n    dict_keys(['objective_value', 'status', 'fluxes', 'reduced_costs', 'shadow_prices'])\n\n\n\n\n```python\nprint('Satus: ',solution.status)\nprint('Growth rate: %.2f' % solution.objective_value)\n```\n\n    Satus:  optimal\n    Growth rate: 0.87\n\n\nUsing the `model.summary()` function for FBA\n\n\n```python\necoli.summary()\n```\n\n\n\n\n<h3>Objective</h3><p>1.0 BIOMASS_Ecoli_core_w_GAM = 0.8739215069684302</p><h4>Uptake</h4><table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Metabolite</th>\n      <th>Reaction</th>\n      <th>Flux</th>\n      <th>C-Number</th>\n      <th>C-Flux</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>glc__D_e</td>\n      <td>EX_glc__D_e</td>\n      <td>10</td>\n      <td>6</td>\n      <td>100.00%</td>\n    </tr>\n    <tr>\n      <td>nh4_e</td>\n      <td>EX_nh4_e</td>\n      <td>4.765</td>\n      <td>0</td>\n      <td>0.00%</td>\n    </tr>\n    <tr>\n      <td>o2_e</td>\n      <td>EX_o2_e</td>\n      <td>21.8</td>\n      <td>0</td>\n      <td>0.00%</td>\n    </tr>\n    <tr>\n      <td>pi_e</td>\n      <td>EX_pi_e</td>\n      <td>3.215</td>\n      <td>0</td>\n      <td>0.00%</td>\n    </tr>\n  </tbody>\n</table><h4>Secretion</h4><table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Metabolite</th>\n      <th>Reaction</th>\n      <th>Flux</th>\n      <th>C-Number</th>\n      <th>C-Flux</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>co2_e</td>\n      <td>EX_co2_e</td>\n      <td>-22.81</td>\n      <td>1</td>\n      <td>100.00%</td>\n    </tr>\n    <tr>\n      <td>h2o_e</td>\n      <td>EX_h2o_e</td>\n      <td>-29.18</td>\n      <td>0</td>\n      <td>0.00%</td>\n    </tr>\n    <tr>\n      <td>h_e</td>\n      <td>EX_h_e</td>\n      <td>-17.53</td>\n      <td>0</td>\n      <td>0.00%</td>\n    </tr>\n  </tbody>\n</table>\n\n\n\n### Flux variability analysis (FVA)\n\n\n```python\nfrom cobra.flux_analysis import flux_variability_analysis\nflux_variability_analysis(ecoli, ecoli.reactions[:10])\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>minimum</th>\n      <th>maximum</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>PFK</th>\n      <td>7.477382e+00</td>\n      <td>7.477382e+00</td>\n    </tr>\n    <tr>\n      <th>PFL</th>\n      <td>0.000000e+00</td>\n      <td>-2.906827e-14</td>\n    </tr>\n    <tr>\n      <th>PGI</th>\n      <td>4.860861e+00</td>\n      <td>4.860861e+00</td>\n    </tr>\n    <tr>\n      <th>PGK</th>\n      <td>-1.602353e+01</td>\n      <td>-1.602353e+01</td>\n    </tr>\n    <tr>\n      <th>PGL</th>\n      <td>4.959985e+00</td>\n      <td>4.959985e+00</td>\n    </tr>\n    <tr>\n      <th>ACALD</th>\n      <td>6.459615e-15</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>AKGt2r</th>\n      <td>3.633533e-15</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>PGM</th>\n      <td>-1.471614e+01</td>\n      <td>-1.471614e+01</td>\n    </tr>\n    <tr>\n      <th>PIt2r</th>\n      <td>3.214895e+00</td>\n      <td>3.214895e+00</td>\n    </tr>\n    <tr>\n      <th>ALCD2x</th>\n      <td>5.626116e-15</td>\n      <td>0.000000e+00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nUsing `model.summary()` function for FVA\n\n\n```python\necoli.summary(fva=0.95)\n```\n\n\n\n\n<h3>Objective</h3><p>1.0 BIOMASS_Ecoli_core_w_GAM = 0.7040369478590289</p><h4>Uptake</h4><table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Metabolite</th>\n      <th>Reaction</th>\n      <th>Flux</th>\n      <th>Range</th>\n      <th>C-Number</th>\n      <th>C-Flux</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>glc__D_e</td>\n      <td>EX_glc__D_e</td>\n      <td>10</td>\n      <td>[9.5;  10]</td>\n      <td>6</td>\n      <td>100.00%</td>\n    </tr>\n    <tr>\n      <td>nh4_e</td>\n      <td>EX_nh4_e</td>\n      <td>3.839</td>\n      <td>[3.647;  3.897]</td>\n      <td>0</td>\n      <td>0.00%</td>\n    </tr>\n    <tr>\n      <td>o2_e</td>\n      <td>EX_o2_e</td>\n      <td>27.53</td>\n      <td>[26.15;  30.76]</td>\n      <td>0</td>\n      <td>0.00%</td>\n    </tr>\n    <tr>\n      <td>pi_e</td>\n      <td>EX_pi_e</td>\n      <td>2.59</td>\n      <td>[2.46;  2.59]</td>\n      <td>0</td>\n      <td>0.00%</td>\n    </tr>\n  </tbody>\n</table><h4>Secretion</h4><table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Metabolite</th>\n      <th>Reaction</th>\n      <th>Flux</th>\n      <th>Range</th>\n      <th>C-Number</th>\n      <th>C-Flux</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>ac_e</td>\n      <td>EX_ac_e</td>\n      <td>0</td>\n      <td>[-0.5;  0]</td>\n      <td>2</td>\n      <td>0.00%</td>\n    </tr>\n    <tr>\n      <td>acald_e</td>\n      <td>EX_acald_e</td>\n      <td>0</td>\n      <td>[-0.5;  0]</td>\n      <td>2</td>\n      <td>0.00%</td>\n    </tr>\n    <tr>\n      <td>akg_e</td>\n      <td>EX_akg_e</td>\n      <td>0</td>\n      <td>[-0.25;  0]</td>\n      <td>5</td>\n      <td>0.00%</td>\n    </tr>\n    <tr>\n      <td>co2_e</td>\n      <td>EX_co2_e</td>\n      <td>-26.64</td>\n      <td>[-31.54;  -25.31]</td>\n      <td>1</td>\n      <td>88.69%</td>\n    </tr>\n    <tr>\n      <td>etoh_e</td>\n      <td>EX_etoh_e</td>\n      <td>0</td>\n      <td>[-0.5;  0]</td>\n      <td>2</td>\n      <td>0.00%</td>\n    </tr>\n    <tr>\n      <td>for_e</td>\n      <td>EX_for_e</td>\n      <td>-3.398</td>\n      <td>[-4.228;  0]</td>\n      <td>1</td>\n      <td>11.31%</td>\n    </tr>\n    <tr>\n      <td>glu__L_e</td>\n      <td>EX_glu__L_e</td>\n      <td>0</td>\n      <td>[-0.25;  0]</td>\n      <td>5</td>\n      <td>0.00%</td>\n    </tr>\n    <tr>\n      <td>h2o_e</td>\n      <td>EX_h2o_e</td>\n      <td>-31.77</td>\n      <td>[-36.41;  -30.18]</td>\n      <td>0</td>\n      <td>0.00%</td>\n    </tr>\n    <tr>\n      <td>h_e</td>\n      <td>EX_h_e</td>\n      <td>-17.52</td>\n      <td>[-17.65;  -13.42]</td>\n      <td>0</td>\n      <td>0.00%</td>\n    </tr>\n    <tr>\n      <td>lac__D_e</td>\n      <td>EX_lac__D_e</td>\n      <td>0</td>\n      <td>[-0.5;  0]</td>\n      <td>3</td>\n      <td>0.00%</td>\n    </tr>\n    <tr>\n      <td>pyr_e</td>\n      <td>EX_pyr_e</td>\n      <td>0</td>\n      <td>[-0.5;  0]</td>\n      <td>3</td>\n      <td>0.00%</td>\n    </tr>\n    <tr>\n      <td>succ_e</td>\n      <td>EX_succ_e</td>\n      <td>0</td>\n      <td>[-0.5;  0]</td>\n      <td>4</td>\n      <td>0.00%</td>\n    </tr>\n  </tbody>\n</table>\n\n\n\n### Simulating deletions\n\n\n```python\nfrom cobra.flux_analysis import (\n    single_gene_deletion, single_reaction_deletion, double_gene_deletion,\n    double_reaction_deletion)\n```\n\nReaction deletions\n\n\n```python\nprint('complete model: ', ecoli.optimize())\nwith ecoli:\n    ecoli.reactions.PFK.knock_out()\n    print('pfk knocked out: ', ecoli.optimize())\n```\n\n    complete model:  <Solution 0.874 at 0x7fbfe8663a50>\n    pfk knocked out:  <Solution 0.704 at 0x7fbfe8663fd0>\n\n\n\n```python\nsingle_reaction_deletion(ecoli, ecoli.reactions[:20])\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>ids</th>\n      <th>growth</th>\n      <th>status</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>{ACONTa}</td>\n      <td>1.511990e-15</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>{PPCK}</td>\n      <td>8.739215e-01</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>{PGI}</td>\n      <td>8.631596e-01</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>{AKGt2r}</td>\n      <td>8.739215e-01</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>{PGL}</td>\n      <td>8.638133e-01</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>{ACALD}</td>\n      <td>8.739215e-01</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>{PPS}</td>\n      <td>8.739215e-01</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>{PGK}</td>\n      <td>1.354023e-15</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>{PPC}</td>\n      <td>8.707448e-01</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>{ACKr}</td>\n      <td>8.739215e-01</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>{ACONTb}</td>\n      <td>8.307127e-15</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>{ALCD2x}</td>\n      <td>8.739215e-01</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>{PIt2r}</td>\n      <td>-1.140194e-15</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>{ACALDt}</td>\n      <td>8.739215e-01</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>{PGM}</td>\n      <td>-7.865014e-32</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>{ATPM}</td>\n      <td>9.166475e-01</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>{PFL}</td>\n      <td>8.739215e-01</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>{PFK}</td>\n      <td>7.040369e-01</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>{ACt2r}</td>\n      <td>8.739215e-01</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>{ADK1}</td>\n      <td>8.739215e-01</td>\n      <td>optimal</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nGene deletions\n\n\n```python\nprint('complete model: ', ecoli.optimize())\nwith ecoli:\n    ecoli.genes.b1723.knock_out()\n    print('pfkA knocked out: ', ecoli.optimize())\n    ecoli.genes.b3916.knock_out()\n    print('pfkB knocked out: ', ecoli.optimize())\n```\n\n    complete model:  <Solution 0.874 at 0x7fbfe87b9750>\n    pfkA knocked out:  <Solution 0.874 at 0x7fbfe87b9790>\n    pfkB knocked out:  <Solution 0.704 at 0x7fbfe87b9710>\n\n\n\n```python\nsin_gene_deletion_results = single_gene_deletion(ecoli)\n```\n\n\n```python\nprint(sin_gene_deletion_results.knockout[\"b1723\"])\n```\n\n            ids    growth   status\n    58  {b1723}  0.873922  optimal\n\n\n\n```python\nsin_deletion_results\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>ids</th>\n      <th>growth</th>\n      <th>status</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>{b0904}</td>\n      <td>0.873922</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>{b2284}</td>\n      <td>0.211663</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>{b3916}</td>\n      <td>0.873922</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>{b0721}</td>\n      <td>0.814298</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>{b2285}</td>\n      <td>0.211663</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>132</th>\n      <td>{b0729}</td>\n      <td>0.858307</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>133</th>\n      <td>{b3737}</td>\n      <td>0.374230</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>134</th>\n      <td>{b3739}</td>\n      <td>0.873922</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>135</th>\n      <td>{b1611}</td>\n      <td>0.873922</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>136</th>\n      <td>{b2925}</td>\n      <td>0.873922</td>\n      <td>optimal</td>\n    </tr>\n  </tbody>\n</table>\n<p>137 rows \u00d7 3 columns</p>\n</div>\n\n\n\nDouble deletions\n\n\n```python\ndouble_gene_deletion(ecoli, ecoli.genes[-5:]).round(4)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>ids</th>\n      <th>growth</th>\n      <th>status</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>{b3919, b2464}</td>\n      <td>0.7040</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>{b3919}</td>\n      <td>0.7040</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>{b2935}</td>\n      <td>0.8739</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>{b3919, b2465}</td>\n      <td>0.7040</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>{b0008, b2935}</td>\n      <td>0.8739</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>{b2935, b2464}</td>\n      <td>0.8739</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>{b0008, b2464}</td>\n      <td>0.8648</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>{b2465}</td>\n      <td>0.8739</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>{b0008}</td>\n      <td>0.8739</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>{b2464}</td>\n      <td>0.8739</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>{b0008, b2465}</td>\n      <td>0.8739</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>{b2935, b2465}</td>\n      <td>0.0000</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>{b3919, b2935}</td>\n      <td>0.7040</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>{b2464, b2465}</td>\n      <td>0.8739</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>{b0008, b3919}</td>\n      <td>0.7040</td>\n      <td>optimal</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndouble_reaction_deletion(ecoli, ecoli.reactions[-5:]).round(4)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>ids</th>\n      <th>growth</th>\n      <th>status</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>{PDH, NADTRHD}</td>\n      <td>0.7925</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>{O2t}</td>\n      <td>0.2117</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>{O2t, NH4t}</td>\n      <td>-0.0000</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>{O2t, PDH}</td>\n      <td>0.2117</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>{NADTRHD}</td>\n      <td>0.8739</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>{PDH}</td>\n      <td>0.7967</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>{PDH, NH4t}</td>\n      <td>-0.0000</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>{NADH16, PDH}</td>\n      <td>0.2117</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>{NADH16, NH4t}</td>\n      <td>0.0000</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>{O2t, NADTRHD}</td>\n      <td>0.2117</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>{NADH16, O2t}</td>\n      <td>0.2117</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>{NH4t}</td>\n      <td>0.0000</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>{NH4t, NADTRHD}</td>\n      <td>0.0000</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>{NADH16, NADTRHD}</td>\n      <td>0.2117</td>\n      <td>optimal</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>{NADH16}</td>\n      <td>0.2117</td>\n      <td>optimal</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n", "meta": {"hexsha": "ba06e96a0f30feab5f4ebac53fbc0ec1e6bcc9ab", "size": 58281, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Constraint based modelling using CobraPy.ipynb", "max_stars_repo_name": "dinesh-kumar-k-b/CobraPy-tutorial-jupyter", "max_stars_repo_head_hexsha": "276809da0d87d5daac93f1e4b2022c284d7be647", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Constraint based modelling using CobraPy.ipynb", "max_issues_repo_name": "dinesh-kumar-k-b/CobraPy-tutorial-jupyter", "max_issues_repo_head_hexsha": "276809da0d87d5daac93f1e4b2022c284d7be647", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Constraint based modelling using CobraPy.ipynb", "max_forks_repo_name": "dinesh-kumar-k-b/CobraPy-tutorial-jupyter", "max_forks_repo_head_hexsha": "276809da0d87d5daac93f1e4b2022c284d7be647", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58281.0, "max_line_length": 58281, "alphanum_fraction": 0.5948422299, "converted": true, "num_tokens": 12443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632160712508727, "lm_q2_score": 0.09534947196849917, "lm_q1q2_score": 0.040649540128139025}}
{"text": "# CBMPy Tutorial 01 Getting Started\n\n## Checking dependencies and loading CBMPy\n\nPySCeS CBMPy is a flexible framework for contraint based modelling. With this tutorial we setup a CBMPy session and load a model. To begin with let's see if we have all the basic dependencies installed. For more information please see the CBMPy reference guide (available from http://cbmpy.sourceforge.net).\n\nNo additional files are required for this tutorial.\n\n\n```python\n# Required for basic CBMPy functionality\nimport numpy\n\n# extended functionaliy\nimport libsbml\nprint('\\nYou are using libSBML version {}'.format(libsbml.LIBSBML_VERSION_STRING))\nif libsbml.LIBSBML_VERSION > 51100 and libsbml.LIBSBML_VERSION < 51106:\n    print('Your version of libSBML supports SBML 3 FBC version 1, please consider upgrading to the latest version for FBC version 2 support.\\n')\nelif libsbml.LIBSBML_VERSION >= 51106:\n    print('Your version of libSBML supports SBML 3 FBC versions 1 and 2.\\n')\nelse:\n    print('You are using an extrememly old version of libSBML please upgrade now!\\n')\n    \n# optional, but highly recommended for rerading/writing excel spreadsheets\nimport xlrd\nimport xlwt\n# sympy is only required for methods utilizing exact arithmetic\ntry:\n    import sympy\nexcept ImportError:\n    print('\\nSympy is only required for selected methods utilizing exact arithmetic and is not required for normal functionality.')\n    \n\n```\n\n    \n    You are using libSBML version 51700\n    Your version of libSBML supports SBML 3 FBC versions 1 and 2.\n    \n\n\nIf any of of the above imports failed consider installing them. Please see the online documentation for comprehensive installation [instructions](http://cbmpy.sourceforge.net/reference/cbmpy.html). Next we need to import CBMPy, at this point it is convenient to alias the imported module. In all tutorials this will be `cbm`.\n\n\n```python\nimport cbmpy\n```\n\nYou should some status text and a version of the welcome screen:\n```\n***********************************************************************\n* Welcome to CBMPy (0.7.20) - PySCeS Constraint Based Modelling       *\n*                http://cbmpy.sourceforge.net                         *\n* Copyright(C) Brett G. Olivier 2014 - 2017                           *\n* Dept. of Systems Bioinformatics                                     *\n* Vrije Universiteit Amsterdam, Amsterdam, The Netherlands            *\n* CBMPy is developed as part of the BeBasic MetaToolKit Project       *\n* Distributed under the GNU GPL v 3.0 licence, see                    *\n* LICENCE (supplied with this release) for details                    *\n***********************************************************************\n```\n\n## Testing the installation, loading the default models\n\nCBMPy now includes a growing set of Nose based unittests, try run them to test your installation (this may take a few minutes) unfortunately the test runner does not seem to like the Notebook environment but try the following in a console:\n\n```import cbmpy\ncbmpy.test()```\n\nIn addition CBMPy is also shipped with two models that can be used to test your installation and get going quickly. In order to use these models at least SBML FBC version 1 support is required and both models can be loaded using the *special* filenames: `cbmpy_test_core` and  `cbmpy_test_ecoli`.\n\nIn CBMPy models are *read* from files and *instantiated* as Python objects. Here I will instantiated two model objectes from the two test files: `cmod` and `ecoli` but you can use any Python name. Note it is possible to instantiate multiple *independent* instances from the same input file.\n\n\n```python\ncmod = cbmpy.readSBML3FBC('cbmpy_test_core')\necoli = cbmpy.readSBML3FBC('cbmpy_test_ecoli')\n```\n\n    core_memesa_model.l3.xml\n    FBC version: 1\n    M.getNumReactions: 26\n    M.getNumSpecies: 22\n    FBC.getNumObjectives: 1\n    FBC.getNumGeneAssociations: 0\n    FBC.getNumFluxBounds: 52\n    Zero dimension compartment detected: Cell\n    INFO: Active objective: objMaxJ25\n    Adding objective: objMaxJ25\n    \n    SBML3 load time: 0.018\n    \n    INFO: no standard gene encoding detected, attempting to load from annotations.\n    INFO: used key(s) '[]'\n    INFO: Added 0 new genes and 0 associations to model\n    Ecoli_iJR904.glc.l3.xml\n    FBC version: 2\n    M.getNumReactions: 1075\n    M.getNumSpecies: 761\n    FBC.getNumObjectives: 1\n    FBC.getNumParameters: 7\n    FBC.getNumGeneProducts: 904\n    Zero dimension compartment detected: c\n    Zero dimension compartment detected: e\n    INFO: Active objective: obj\n    Adding objective: obj\n    Groups support: <GroupsModelPlugin>\n    Group.getNumGroups: 31\n    \n    SBML3 load time: 2.082\n    \n\n\nOnce model objects have been instantiated they can be modified and analysed, here we will perform FBA on each model and test that CBMPy is calculating the correct result:\n\n\n```python\nprint('\\n*****\\nCalculating FBA for model: core\\n*****')\noptcm = cbmpy.doFBA(cmod)\n\nprint('\\n*****\\nCalculating FBA for model: ecoli\\n*****')\noptec = cbmpy.doFBA(ecoli)\n\nif 1.0 - abs(round(optcm, 2)) < 1.2e-10:\n    print('\\nCore model test FBA: PASSED.\\n Value expected: 1.0, calculated: {}'.format(round(optcm, 2)))\nelse:\n    print('\\nCore model test FBA: FAILED.\\n Value expected: 1.0, calculated: {}'.format(round(optcm, 2)))\nif 0.92 - abs(round(optec, 2)) < 1.2e-10:\n    print('\\nE. Coli model test FBA: PASSED.\\n Value expected: 0.92, calculated: {}'.format(round(optec, 2)))\nelse:\n    print('\\nE. Coli model test FBA: FAILED.\\n Value expected: 0.92, calculated: {}'.format(round(optec, 2)))\n\n```\n\n    \n    *****\n    Calculating FBA for model: core\n    *****\n    \n    cplx_constructLPfromFBA time: 0.00600004196167\n    \n    \n    cplx_analyzeModel FBA --> LP time: 0.00600004196167\n    \n    CPXPARAM_Read_DataCheck                          1\n    Tried aggregator 1 time.\n    LP Presolve eliminated 0 rows and 4 columns.\n    Aggregator did 11 substitutions.\n    Reduced LP has 8 rows, 11 columns, and 20 nonzeros.\n    Presolve time = 0.02 sec. (0.02 ticks)\n    Initializing dual steep norms . . .\n    \n    Iteration log . . .\n    Iteration:     1   Dual objective     =          1000.000000\n    INFO: Model is optimal: 1\n    Solution status =  1 : optimal\n    Solution method =  2 : dual\n    Objective value =  1.0\n    Model is optimal\n    Status: LPS_OPT\n    Model is optimal\n    Model is optimal\n    \n    analyzeModel objective value: 1.0\n    \n    \n    *****\n    Calculating FBA for model: ecoli\n    *****\n    \n    cplx_constructLPfromFBA time: 0.0649998188019\n    \n    \n    cplx_analyzeModel FBA --> LP time: 0.0649998188019\n    \n    CPXPARAM_Read_DataCheck                          1\n    Tried aggregator 1 time.\n    LP Presolve eliminated 274 rows and 363 columns.\n    Aggregator did 231 substitutions.\n    Reduced LP has 256 rows, 481 columns, and 2430 nonzeros.\n    Presolve time = 0.01 sec. (1.12 ticks)\n    \n    Iteration log . . .\n    Iteration:     1   Dual objective     =        999999.000000\n    Iteration:    62   Dual objective     =        552515.995359\n    Iteration:   124   Dual objective     =        362603.457641\n    Iteration:   186   Dual objective     =        130350.090149\n    Iteration:   248   Dual objective     =         99850.178645\n    Iteration:   310   Dual objective     =         49824.030589\n    Iteration:   372   Dual objective     =             1.401622\n    INFO: Model is optimal: 1\n    Solution status =  1 : optimal\n    Solution method =  2 : dual\n    Objective value =  0.921948095023\n    Model is optimal\n    Status: LPS_OPT\n    Model is optimal\n    Model is optimal\n    \n    analyzeModel objective value: 0.921948095023\n    \n    \n    Core model test FBA: PASSED.\n     Value expected: 1.0, calculated: 1.0\n    \n    E. Coli model test FBA: PASSED.\n     Value expected: 0.92, calculated: 0.92\n\n\nIf both of the above tests passed, congratulations you are ready to model with CBMPy. In tutorial 2 we will look in more detail at model ecoding formats that can be used with CBMPy.\n", "meta": {"hexsha": "55b6a69546f42570c672f973bd2ebaf7c3f3bdfa", "size": 11194, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorials/jupyter/cbmpy_01_getting-started.ipynb", "max_stars_repo_name": "bgoli/cbmpy-docs", "max_stars_repo_head_hexsha": "d1489ecf140ab2fcb4d6c390cb592e5127c843a0", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorials/jupyter/cbmpy_01_getting-started.ipynb", "max_issues_repo_name": "bgoli/cbmpy-docs", "max_issues_repo_head_hexsha": "d1489ecf140ab2fcb4d6c390cb592e5127c843a0", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/jupyter/cbmpy_01_getting-started.ipynb", "max_forks_repo_name": "bgoli/cbmpy-docs", "max_forks_repo_head_hexsha": "d1489ecf140ab2fcb4d6c390cb592e5127c843a0", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3123028391, "max_line_length": 331, "alphanum_fraction": 0.5696801858, "converted": true, "num_tokens": 2114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.09009298663270453, "lm_q1q2_score": 0.04048712460966947}}
{"text": "```python\n# Copyright 2019 NVIDIA Corporation. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n```\n\n\n\n# Torch-TensorRT Getting Started - CitriNet\n\n## Overview\n\n[Citrinet](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/main/asr/models.html#citrinet) is an acoustic model used for the speech to text recognition task. It is a version of [QuartzNet](https://arxiv.org/pdf/1910.10261.pdf) that extends [ContextNet](https://arxiv.org/pdf/2005.03191.pdf), utilizing subword encoding (via Word Piece tokenization) and Squeeze-and-Excitation(SE) mechanism and are therefore smaller than QuartzNet models.\n\nCitriNet models take in audio segments and transcribe them to letter, byte pair, or word piece sequences. \n\n\n\n\n### Learning objectives\n\nThis notebook demonstrates the steps for optimizing a pretrained CitriNet model with Torch-TensorRT, and running it to test the speedup obtained.\n\n## Content\n1. [Requirements](#1)\n1. [Download Citrinet model](#2)\n1. [Create Torch-TensorRT modules](#3)\n1. [Benchmark Torch-TensorRT models](#4)\n1. [Conclusion](#5)\n\n<a id=\"1\"></a>\n## 1. Requirements\n\nFollow the steps in [README](README.md) to prepare a Docker container, within which you can run this notebook. \nThis notebook assumes that you are within a Jupyter environment in a docker container with Torch-TensorRT installed, such as an NGC monthly release of `nvcr.io/nvidia/pytorch:<yy.mm>-py3` (where `yy` indicates the last two numbers of a calendar year, and `mm` indicates the month in two-digit numerical form)\n\nNow that you are in the docker, the next step is to install the required dependencies.\n\n\n```python\n# Install dependencies\n!pip install wget\n!apt-get update && DEBIAN_FRONTEND=noninteractive  apt-get install -y libsndfile1 ffmpeg\n!pip install Cython\n\n## Install NeMo\n!pip install nemo_toolkit[all]==1.5.1\n```\n\n    Looking in indexes: https://pypi.org/simple, https://pypi.ngc.nvidia.com\n    Requirement already satisfied: wget in /opt/conda/lib/python3.8/site-packages (3.2)\n    \u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\n    Hit:1 http://security.ubuntu.com/ubuntu focal-security InRelease\n    Hit:2 http://archive.ubuntu.com/ubuntu focal InRelease\n    Hit:3 http://archive.ubuntu.com/ubuntu focal-updates InRelease\n    Hit:4 http://archive.ubuntu.com/ubuntu focal-backports InRelease\n    Reading package lists... Done\n    Reading package lists... Done\n    Building dependency tree       \n    Reading state information... Done\n    libsndfile1 is already the newest version (1.0.28-7ubuntu0.1).\n    ffmpeg is already the newest version (7:4.2.4-1ubuntu0.1).\n    0 upgraded, 0 newly installed, 0 to remove and 22 not upgraded.\n    Looking in indexes: https://pypi.org/simple, https://pypi.ngc.nvidia.com\n    Requirement already satisfied: Cython in /opt/conda/lib/python3.8/site-packages (0.29.28)\n    \u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\n    Looking in indexes: https://pypi.org/simple, https://pypi.ngc.nvidia.com\n    Requirement already satisfied: nemo_toolkit[all]==1.5.1 in /opt/conda/lib/python3.8/site-packages (1.5.1)\n    Requirement already satisfied: numpy>=1.18.2 in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (1.22.3)\n    Requirement already satisfied: onnx>=1.7.0 in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (1.10.1)\n    Requirement already satisfied: python-dateutil in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (2.8.2)\n    Requirement already satisfied: tqdm>=4.41.0 in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (4.63.0)\n    Requirement already satisfied: sentencepiece<1.0.0 in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.1.96)\n    Requirement already satisfied: wget in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (3.2)\n    Requirement already satisfied: numba in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.53.1)\n    Requirement already satisfied: torch in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (1.12.0a0+2c916ef)\n    Requirement already satisfied: unidecode in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (1.3.4)\n    Requirement already satisfied: frozendict in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (2.3.2)\n    Requirement already satisfied: wrapt in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (1.14.0)\n    Requirement already satisfied: scikit-learn in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.24.2)\n    Requirement already satisfied: ruamel.yaml in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.17.21)\n    Requirement already satisfied: pesq in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.0.3)\n    Requirement already satisfied: torchvision in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.13.0a0)\n    Requirement already satisfied: gdown in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (4.4.0)\n    Requirement already satisfied: editdistance in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.6.0)\n    Requirement already satisfied: boto3 in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (1.21.45)\n    Requirement already satisfied: isort[requirements]<5 in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (4.3.21)\n    Requirement already satisfied: hydra-core>=1.1.0 in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (1.1.2)\n    Requirement already satisfied: youtokentome>=1.0.5 in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (1.0.6)\n    Requirement already satisfied: pytorch-lightning>=1.5.0 in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (1.6.1)\n    Requirement already satisfied: jieba in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.42.1)\n    Requirement already satisfied: fasttext in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.9.2)\n    Requirement already satisfied: soundfile in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.10.3.post1)\n    Requirement already satisfied: kaldiio in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (2.17.2)\n    Requirement already satisfied: pangu in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (4.0.6.1)\n    Requirement already satisfied: kaldi-python-io in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (1.2.2)\n    Requirement already satisfied: parameterized in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.8.1)\n    Requirement already satisfied: h5py in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (3.6.0)\n    Requirement already satisfied: rapidfuzz in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (2.0.10)\n    Requirement already satisfied: marshmallow in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (3.15.0)\n    Requirement already satisfied: opencc in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (1.1.3)\n    Requirement already satisfied: braceexpand in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.1.7)\n    Requirement already satisfied: omegaconf>=2.1.0 in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (2.1.2)\n    Requirement already satisfied: sphinx in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (4.4.0)\n    Requirement already satisfied: pillow in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (9.0.0)\n    Requirement already satisfied: wordninja==2.0.0 in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (2.0.0)\n    Requirement already satisfied: torch-stft in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.1.4)\n    Requirement already satisfied: sox in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (1.4.1)\n    Requirement already satisfied: librosa in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.9.1)\n    Requirement already satisfied: regex in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (2022.3.15)\n    Requirement already satisfied: sacrebleu[ja] in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (2.0.0)\n    Requirement already satisfied: black==19.10b0 in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (19.10b0)\n    Requirement already satisfied: pydub in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.25.1)\n    Requirement already satisfied: sphinxcontrib-bibtex in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (2.4.2)\n    Requirement already satisfied: inflect in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (5.5.2)\n    Requirement already satisfied: pyannote.core in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (4.4)\n    Requirement already satisfied: packaging in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (21.3)\n    Requirement already satisfied: kaldi-io in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.9.4)\n    Requirement already satisfied: pyannote.metrics in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (3.2)\n    Requirement already satisfied: g2p-en in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (2.1.0)\n    Requirement already satisfied: matplotlib in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (3.5.1)\n    Requirement already satisfied: torchmetrics>=0.4.1rc0 in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.8.0)\n    Requirement already satisfied: nltk>=3.6.5 in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (3.7)\n    Requirement already satisfied: pyyaml<6 in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (5.4.1)\n    Requirement already satisfied: scipy in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (1.6.3)\n    Requirement already satisfied: ipywidgets in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (7.7.0)\n    Requirement already satisfied: pytest in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (6.2.5)\n    Requirement already satisfied: pandas in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (1.3.5)\n    Requirement already satisfied: pytest-runner in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (6.0.0)\n    Requirement already satisfied: transformers>=4.0.1 in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (4.18.0)\n    Requirement already satisfied: sacremoses>=0.0.43 in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.0.49)\n    Requirement already satisfied: pystoi in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.3.3)\n    Requirement already satisfied: attrdict in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (2.0.1)\n    Requirement already satisfied: webdataset<=0.1.62,>=0.1.48 in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.1.62)\n    Requirement already satisfied: wandb in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.12.15)\n    Requirement already satisfied: pypinyin in /opt/conda/lib/python3.8/site-packages (from nemo_toolkit[all]==1.5.1) (0.46.0)\n    Requirement already satisfied: attrs>=18.1.0 in /opt/conda/lib/python3.8/site-packages (from black==19.10b0->nemo_toolkit[all]==1.5.1) (21.4.0)\n    Requirement already satisfied: appdirs in /opt/conda/lib/python3.8/site-packages (from black==19.10b0->nemo_toolkit[all]==1.5.1) (1.4.4)\n    Requirement already satisfied: typed-ast>=1.4.0 in /opt/conda/lib/python3.8/site-packages (from black==19.10b0->nemo_toolkit[all]==1.5.1) (1.5.3)\n    Requirement already satisfied: pathspec<1,>=0.6 in /opt/conda/lib/python3.8/site-packages (from black==19.10b0->nemo_toolkit[all]==1.5.1) (0.9.0)\n    Requirement already satisfied: click>=6.5 in /opt/conda/lib/python3.8/site-packages (from black==19.10b0->nemo_toolkit[all]==1.5.1) (8.0.4)\n    Requirement already satisfied: toml>=0.9.4 in /opt/conda/lib/python3.8/site-packages (from black==19.10b0->nemo_toolkit[all]==1.5.1) (0.10.2)\n    Requirement already satisfied: antlr4-python3-runtime==4.8 in /opt/conda/lib/python3.8/site-packages (from hydra-core>=1.1.0->nemo_toolkit[all]==1.5.1) (4.8)\n    Requirement already satisfied: importlib-resources<5.3 in /opt/conda/lib/python3.8/site-packages (from hydra-core>=1.1.0->nemo_toolkit[all]==1.5.1) (5.2.3)\n    Requirement already satisfied: zipp>=3.1.0 in /opt/conda/lib/python3.8/site-packages (from importlib-resources<5.3->hydra-core>=1.1.0->nemo_toolkit[all]==1.5.1) (3.7.0)\n    Requirement already satisfied: pip-api in /opt/conda/lib/python3.8/site-packages (from isort[requirements]<5->nemo_toolkit[all]==1.5.1) (0.0.29)\n    Requirement already satisfied: pipreqs in /opt/conda/lib/python3.8/site-packages (from isort[requirements]<5->nemo_toolkit[all]==1.5.1) (0.4.11)\n    Requirement already satisfied: fonttools>=4.22.0 in /opt/conda/lib/python3.8/site-packages (from matplotlib->nemo_toolkit[all]==1.5.1) (4.31.2)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /opt/conda/lib/python3.8/site-packages (from matplotlib->nemo_toolkit[all]==1.5.1) (1.4.0)\n    Requirement already satisfied: pyparsing>=2.2.1 in /opt/conda/lib/python3.8/site-packages (from matplotlib->nemo_toolkit[all]==1.5.1) (3.0.7)\n    Requirement already satisfied: cycler>=0.10 in /opt/conda/lib/python3.8/site-packages (from matplotlib->nemo_toolkit[all]==1.5.1) (0.11.0)\n    Requirement already satisfied: joblib in /opt/conda/lib/python3.8/site-packages (from nltk>=3.6.5->nemo_toolkit[all]==1.5.1) (1.1.0)\n    Requirement already satisfied: typing-extensions>=3.6.2.1 in /opt/conda/lib/python3.8/site-packages (from onnx>=1.7.0->nemo_toolkit[all]==1.5.1) (4.1.1)\n    Requirement already satisfied: six in /opt/conda/lib/python3.8/site-packages (from onnx>=1.7.0->nemo_toolkit[all]==1.5.1) (1.16.0)\n    Requirement already satisfied: protobuf>=3.12.2 in /opt/conda/lib/python3.8/site-packages (from onnx>=1.7.0->nemo_toolkit[all]==1.5.1) (3.19.4)\n    Requirement already satisfied: pyDeprecate<0.4.0,>=0.3.1 in /opt/conda/lib/python3.8/site-packages (from pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (0.3.2)\n    Requirement already satisfied: tensorboard>=2.2.0 in /opt/conda/lib/python3.8/site-packages (from pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (2.8.0)\n    Requirement already satisfied: fsspec[http]!=2021.06.0,>=2021.05.0 in /opt/conda/lib/python3.8/site-packages (from pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (2022.2.0)\n    Requirement already satisfied: requests in /opt/conda/lib/python3.8/site-packages (from fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (2.27.1)\n    Requirement already satisfied: aiohttp in /opt/conda/lib/python3.8/site-packages (from fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (3.8.1)\n    Requirement already satisfied: werkzeug>=0.11.15 in /opt/conda/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (2.0.3)\n    Requirement already satisfied: markdown>=2.6.8 in /opt/conda/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (3.3.6)\n    Requirement already satisfied: setuptools>=41.0.0 in /opt/conda/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (59.5.0)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /opt/conda/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (0.4.6)\n    Requirement already satisfied: google-auth<3,>=1.6.3 in /opt/conda/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (2.6.2)\n    Requirement already satisfied: wheel>=0.26 in /opt/conda/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (0.37.1)\n    Requirement already satisfied: grpcio>=1.24.3 in /opt/conda/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (1.44.0)\n    Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /opt/conda/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (0.6.1)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /opt/conda/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (1.8.1)\n    Requirement already satisfied: absl-py>=0.4 in /opt/conda/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (1.0.0)\n    Requirement already satisfied: cachetools<6.0,>=2.0.0 in /opt/conda/lib/python3.8/site-packages (from google-auth<3,>=1.6.3->tensorboard>=2.2.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (5.0.0)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /opt/conda/lib/python3.8/site-packages (from google-auth<3,>=1.6.3->tensorboard>=2.2.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (0.2.8)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /opt/conda/lib/python3.8/site-packages (from google-auth<3,>=1.6.3->tensorboard>=2.2.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (4.8)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /opt/conda/lib/python3.8/site-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard>=2.2.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (1.3.1)\n    Requirement already satisfied: importlib-metadata>=4.4 in /opt/conda/lib/python3.8/site-packages (from markdown>=2.6.8->tensorboard>=2.2.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (4.11.3)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /opt/conda/lib/python3.8/site-packages (from pyasn1-modules>=0.2.1->google-auth<3,>=1.6.3->tensorboard>=2.2.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (0.4.8)\n    Requirement already satisfied: charset-normalizer~=2.0.0 in /opt/conda/lib/python3.8/site-packages (from requests->fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (2.0.12)\n    Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.8/site-packages (from requests->fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (2021.10.8)\n    Requirement already satisfied: idna<4,>=2.5 in /opt/conda/lib/python3.8/site-packages (from requests->fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (3.3)\n    Requirement already satisfied: urllib3<1.27,>=1.21.1 in /opt/conda/lib/python3.8/site-packages (from requests->fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (1.26.8)\n    Requirement already satisfied: oauthlib>=3.0.0 in /opt/conda/lib/python3.8/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard>=2.2.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (3.2.0)\n    Requirement already satisfied: huggingface-hub<1.0,>=0.1.0 in /opt/conda/lib/python3.8/site-packages (from transformers>=4.0.1->nemo_toolkit[all]==1.5.1) (0.5.1)\n    Requirement already satisfied: tokenizers!=0.11.3,<0.13,>=0.11.1 in /opt/conda/lib/python3.8/site-packages (from transformers>=4.0.1->nemo_toolkit[all]==1.5.1) (0.12.1)\n    Requirement already satisfied: filelock in /opt/conda/lib/python3.8/site-packages (from transformers>=4.0.1->nemo_toolkit[all]==1.5.1) (3.6.0)\n    Requirement already satisfied: frozenlist>=1.1.1 in /opt/conda/lib/python3.8/site-packages (from aiohttp->fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (1.3.0)\n    Requirement already satisfied: yarl<2.0,>=1.0 in /opt/conda/lib/python3.8/site-packages (from aiohttp->fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (1.7.2)\n    Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /opt/conda/lib/python3.8/site-packages (from aiohttp->fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (4.0.2)\n    Requirement already satisfied: multidict<7.0,>=4.5 in /opt/conda/lib/python3.8/site-packages (from aiohttp->fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (6.0.2)\n    Requirement already satisfied: aiosignal>=1.1.2 in /opt/conda/lib/python3.8/site-packages (from aiohttp->fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (1.2.0)\n    Requirement already satisfied: s3transfer<0.6.0,>=0.5.0 in /opt/conda/lib/python3.8/site-packages (from boto3->nemo_toolkit[all]==1.5.1) (0.5.2)\n    Requirement already satisfied: botocore<1.25.0,>=1.24.45 in /opt/conda/lib/python3.8/site-packages (from boto3->nemo_toolkit[all]==1.5.1) (1.24.45)\n    Requirement already satisfied: jmespath<2.0.0,>=0.7.1 in /opt/conda/lib/python3.8/site-packages (from boto3->nemo_toolkit[all]==1.5.1) (1.0.0)\n    Requirement already satisfied: pybind11>=2.2 in /opt/conda/lib/python3.8/site-packages (from fasttext->nemo_toolkit[all]==1.5.1) (2.9.1)\n    Requirement already satisfied: distance>=0.1.3 in /opt/conda/lib/python3.8/site-packages (from g2p-en->nemo_toolkit[all]==1.5.1) (0.1.3)\n    Requirement already satisfied: beautifulsoup4 in /opt/conda/lib/python3.8/site-packages (from gdown->nemo_toolkit[all]==1.5.1) (4.10.0)\n    Requirement already satisfied: soupsieve>1.2 in /opt/conda/lib/python3.8/site-packages (from beautifulsoup4->gdown->nemo_toolkit[all]==1.5.1) (2.3.1)\n    Requirement already satisfied: ipython-genutils~=0.2.0 in /opt/conda/lib/python3.8/site-packages (from ipywidgets->nemo_toolkit[all]==1.5.1) (0.2.0)\n    Requirement already satisfied: ipython>=4.0.0 in /opt/conda/lib/python3.8/site-packages (from ipywidgets->nemo_toolkit[all]==1.5.1) (8.1.1)\n    Requirement already satisfied: ipykernel>=4.5.1 in /opt/conda/lib/python3.8/site-packages (from ipywidgets->nemo_toolkit[all]==1.5.1) (6.9.2)\n    Requirement already satisfied: jupyterlab-widgets>=1.0.0 in /opt/conda/lib/python3.8/site-packages (from ipywidgets->nemo_toolkit[all]==1.5.1) (1.1.0)\n    Requirement already satisfied: widgetsnbextension~=3.6.0 in /opt/conda/lib/python3.8/site-packages (from ipywidgets->nemo_toolkit[all]==1.5.1) (3.6.0)\n    Requirement already satisfied: traitlets>=4.3.1 in /opt/conda/lib/python3.8/site-packages (from ipywidgets->nemo_toolkit[all]==1.5.1) (5.1.1)\n    Requirement already satisfied: nbformat>=4.2.0 in /opt/conda/lib/python3.8/site-packages (from ipywidgets->nemo_toolkit[all]==1.5.1) (5.2.0)\n    Requirement already satisfied: jupyter-client<8.0 in /opt/conda/lib/python3.8/site-packages (from ipykernel>=4.5.1->ipywidgets->nemo_toolkit[all]==1.5.1) (7.1.2)\n    Requirement already satisfied: psutil in /opt/conda/lib/python3.8/site-packages (from ipykernel>=4.5.1->ipywidgets->nemo_toolkit[all]==1.5.1) (5.9.0)\n    Requirement already satisfied: tornado<7.0,>=4.2 in /opt/conda/lib/python3.8/site-packages (from ipykernel>=4.5.1->ipywidgets->nemo_toolkit[all]==1.5.1) (6.1)\n    Requirement already satisfied: debugpy<2.0,>=1.0.0 in /opt/conda/lib/python3.8/site-packages (from ipykernel>=4.5.1->ipywidgets->nemo_toolkit[all]==1.5.1) (1.5.1)\n    Requirement already satisfied: nest-asyncio in /opt/conda/lib/python3.8/site-packages (from ipykernel>=4.5.1->ipywidgets->nemo_toolkit[all]==1.5.1) (1.5.4)\n    Requirement already satisfied: matplotlib-inline<0.2.0,>=0.1.0 in /opt/conda/lib/python3.8/site-packages (from ipykernel>=4.5.1->ipywidgets->nemo_toolkit[all]==1.5.1) (0.1.3)\n    Requirement already satisfied: pickleshare in /opt/conda/lib/python3.8/site-packages (from ipython>=4.0.0->ipywidgets->nemo_toolkit[all]==1.5.1) (0.7.5)\n    Requirement already satisfied: decorator in /opt/conda/lib/python3.8/site-packages (from ipython>=4.0.0->ipywidgets->nemo_toolkit[all]==1.5.1) (5.1.1)\n    Requirement already satisfied: pygments>=2.4.0 in /opt/conda/lib/python3.8/site-packages (from ipython>=4.0.0->ipywidgets->nemo_toolkit[all]==1.5.1) (2.11.2)\n    Requirement already satisfied: stack-data in /opt/conda/lib/python3.8/site-packages (from ipython>=4.0.0->ipywidgets->nemo_toolkit[all]==1.5.1) (0.2.0)\n    Requirement already satisfied: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in /opt/conda/lib/python3.8/site-packages (from ipython>=4.0.0->ipywidgets->nemo_toolkit[all]==1.5.1) (3.0.27)\n    Requirement already satisfied: backcall in /opt/conda/lib/python3.8/site-packages (from ipython>=4.0.0->ipywidgets->nemo_toolkit[all]==1.5.1) (0.2.0)\n    Requirement already satisfied: jedi>=0.16 in /opt/conda/lib/python3.8/site-packages (from ipython>=4.0.0->ipywidgets->nemo_toolkit[all]==1.5.1) (0.18.1)\n    Requirement already satisfied: pexpect>4.3 in /opt/conda/lib/python3.8/site-packages (from ipython>=4.0.0->ipywidgets->nemo_toolkit[all]==1.5.1) (4.8.0)\n    Requirement already satisfied: parso<0.9.0,>=0.8.0 in /opt/conda/lib/python3.8/site-packages (from jedi>=0.16->ipython>=4.0.0->ipywidgets->nemo_toolkit[all]==1.5.1) (0.8.3)\n    Requirement already satisfied: entrypoints in /opt/conda/lib/python3.8/site-packages (from jupyter-client<8.0->ipykernel>=4.5.1->ipywidgets->nemo_toolkit[all]==1.5.1) (0.4)\n    Requirement already satisfied: pyzmq>=13 in /opt/conda/lib/python3.8/site-packages (from jupyter-client<8.0->ipykernel>=4.5.1->ipywidgets->nemo_toolkit[all]==1.5.1) (22.3.0)\n    Requirement already satisfied: jupyter-core>=4.6.0 in /opt/conda/lib/python3.8/site-packages (from jupyter-client<8.0->ipykernel>=4.5.1->ipywidgets->nemo_toolkit[all]==1.5.1) (4.9.2)\n    Requirement already satisfied: jsonschema!=2.5.0,>=2.4 in /opt/conda/lib/python3.8/site-packages (from nbformat>=4.2.0->ipywidgets->nemo_toolkit[all]==1.5.1) (4.4.0)\n    Requirement already satisfied: pyrsistent!=0.17.0,!=0.17.1,!=0.17.2,>=0.14.0 in /opt/conda/lib/python3.8/site-packages (from jsonschema!=2.5.0,>=2.4->nbformat>=4.2.0->ipywidgets->nemo_toolkit[all]==1.5.1) (0.18.1)\n    Requirement already satisfied: ptyprocess>=0.5 in /opt/conda/lib/python3.8/site-packages (from pexpect>4.3->ipython>=4.0.0->ipywidgets->nemo_toolkit[all]==1.5.1) (0.7.0)\n    Requirement already satisfied: wcwidth in /opt/conda/lib/python3.8/site-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->ipython>=4.0.0->ipywidgets->nemo_toolkit[all]==1.5.1) (0.2.5)\n    Requirement already satisfied: notebook>=4.4.1 in /opt/conda/lib/python3.8/site-packages (from widgetsnbextension~=3.6.0->ipywidgets->nemo_toolkit[all]==1.5.1) (6.4.1)\n    Requirement already satisfied: Send2Trash>=1.5.0 in /opt/conda/lib/python3.8/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets->nemo_toolkit[all]==1.5.1) (1.8.0)\n    Requirement already satisfied: prometheus-client in /opt/conda/lib/python3.8/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets->nemo_toolkit[all]==1.5.1) (0.13.1)\n    Requirement already satisfied: terminado>=0.8.3 in /opt/conda/lib/python3.8/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets->nemo_toolkit[all]==1.5.1) (0.13.3)\n    Requirement already satisfied: jinja2 in /opt/conda/lib/python3.8/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets->nemo_toolkit[all]==1.5.1) (3.0.3)\n    Requirement already satisfied: nbconvert in /opt/conda/lib/python3.8/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets->nemo_toolkit[all]==1.5.1) (6.4.4)\n    Requirement already satisfied: argon2-cffi in /opt/conda/lib/python3.8/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets->nemo_toolkit[all]==1.5.1) (21.3.0)\n    Requirement already satisfied: argon2-cffi-bindings in /opt/conda/lib/python3.8/site-packages (from argon2-cffi->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets->nemo_toolkit[all]==1.5.1) (21.2.0)\n    Requirement already satisfied: cffi>=1.0.1 in /opt/conda/lib/python3.8/site-packages (from argon2-cffi-bindings->argon2-cffi->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets->nemo_toolkit[all]==1.5.1) (1.15.0)\n    Requirement already satisfied: pycparser in /opt/conda/lib/python3.8/site-packages (from cffi>=1.0.1->argon2-cffi-bindings->argon2-cffi->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets->nemo_toolkit[all]==1.5.1) (2.21)\n    Requirement already satisfied: MarkupSafe>=2.0 in /opt/conda/lib/python3.8/site-packages (from jinja2->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets->nemo_toolkit[all]==1.5.1) (2.1.1)\n    Requirement already satisfied: resampy>=0.2.2 in /opt/conda/lib/python3.8/site-packages (from librosa->nemo_toolkit[all]==1.5.1) (0.2.2)\n    Requirement already satisfied: pooch>=1.0 in /opt/conda/lib/python3.8/site-packages (from librosa->nemo_toolkit[all]==1.5.1) (1.6.0)\n    Requirement already satisfied: audioread>=2.1.5 in /opt/conda/lib/python3.8/site-packages (from librosa->nemo_toolkit[all]==1.5.1) (2.1.9)\n    Requirement already satisfied: llvmlite<0.37,>=0.36.0rc1 in /opt/conda/lib/python3.8/site-packages (from numba->nemo_toolkit[all]==1.5.1) (0.36.0)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /opt/conda/lib/python3.8/site-packages (from scikit-learn->nemo_toolkit[all]==1.5.1) (3.1.0)\n    Requirement already satisfied: defusedxml in /opt/conda/lib/python3.8/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets->nemo_toolkit[all]==1.5.1) (0.7.1)\n    Requirement already satisfied: nbclient<0.6.0,>=0.5.0 in /opt/conda/lib/python3.8/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets->nemo_toolkit[all]==1.5.1) (0.5.13)\n    Requirement already satisfied: bleach in /opt/conda/lib/python3.8/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets->nemo_toolkit[all]==1.5.1) (4.1.0)\n    Requirement already satisfied: mistune<2,>=0.8.1 in /opt/conda/lib/python3.8/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets->nemo_toolkit[all]==1.5.1) (0.8.4)\n    Requirement already satisfied: pandocfilters>=1.4.1 in /opt/conda/lib/python3.8/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets->nemo_toolkit[all]==1.5.1) (1.5.0)\n    Requirement already satisfied: testpath in /opt/conda/lib/python3.8/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets->nemo_toolkit[all]==1.5.1) (0.6.0)\n    Requirement already satisfied: jupyterlab-pygments in /opt/conda/lib/python3.8/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets->nemo_toolkit[all]==1.5.1) (0.1.2)\n    Requirement already satisfied: webencodings in /opt/conda/lib/python3.8/site-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets->nemo_toolkit[all]==1.5.1) (0.5.1)\n    Requirement already satisfied: pytz>=2017.3 in /opt/conda/lib/python3.8/site-packages (from pandas->nemo_toolkit[all]==1.5.1) (2021.3)\n    Requirement already satisfied: pip in /opt/conda/lib/python3.8/site-packages (from pip-api->isort[requirements]<5->nemo_toolkit[all]==1.5.1) (21.2.4)\n    Requirement already satisfied: yarg in /opt/conda/lib/python3.8/site-packages (from pipreqs->isort[requirements]<5->nemo_toolkit[all]==1.5.1) (0.1.9)\n    Requirement already satisfied: docopt in /opt/conda/lib/python3.8/site-packages (from pipreqs->isort[requirements]<5->nemo_toolkit[all]==1.5.1) (0.6.2)\n    Requirement already satisfied: simplejson>=3.8.1 in /opt/conda/lib/python3.8/site-packages (from pyannote.core->nemo_toolkit[all]==1.5.1) (3.17.6)\n    Requirement already satisfied: sortedcontainers>=2.0.4 in /opt/conda/lib/python3.8/site-packages (from pyannote.core->nemo_toolkit[all]==1.5.1) (2.4.0)\n    Requirement already satisfied: tabulate>=0.7.7 in /opt/conda/lib/python3.8/site-packages (from pyannote.metrics->nemo_toolkit[all]==1.5.1) (0.8.9)\n    Requirement already satisfied: pyannote.database>=4.0.1 in /opt/conda/lib/python3.8/site-packages (from pyannote.metrics->nemo_toolkit[all]==1.5.1) (4.1.3)\n    Requirement already satisfied: sympy>=1.1 in /opt/conda/lib/python3.8/site-packages (from pyannote.metrics->nemo_toolkit[all]==1.5.1) (1.10.1)\n    Requirement already satisfied: typer[all]>=0.2.1 in /opt/conda/lib/python3.8/site-packages (from pyannote.database>=4.0.1->pyannote.metrics->nemo_toolkit[all]==1.5.1) (0.4.0)\n    Requirement already satisfied: mpmath>=0.19 in /opt/conda/lib/python3.8/site-packages (from sympy>=1.1->pyannote.metrics->nemo_toolkit[all]==1.5.1) (1.2.1)\n    Requirement already satisfied: colorama<0.5.0,>=0.4.3 in /opt/conda/lib/python3.8/site-packages (from typer[all]>=0.2.1->pyannote.database>=4.0.1->pyannote.metrics->nemo_toolkit[all]==1.5.1) (0.4.4)\n    Requirement already satisfied: shellingham<2.0.0,>=1.3.0 in /opt/conda/lib/python3.8/site-packages (from typer[all]>=0.2.1->pyannote.database>=4.0.1->pyannote.metrics->nemo_toolkit[all]==1.5.1) (1.4.0)\n    Requirement already satisfied: py>=1.8.2 in /opt/conda/lib/python3.8/site-packages (from pytest->nemo_toolkit[all]==1.5.1) (1.11.0)\n    Requirement already satisfied: iniconfig in /opt/conda/lib/python3.8/site-packages (from pytest->nemo_toolkit[all]==1.5.1) (1.1.1)\n    Requirement already satisfied: pluggy<2.0,>=0.12 in /opt/conda/lib/python3.8/site-packages (from pytest->nemo_toolkit[all]==1.5.1) (1.0.0)\n    Requirement already satisfied: jarowinkler<1.1.0,>=1.0.2 in /opt/conda/lib/python3.8/site-packages (from rapidfuzz->nemo_toolkit[all]==1.5.1) (1.0.2)\n    Requirement already satisfied: PySocks!=1.5.7,>=1.5.6 in /opt/conda/lib/python3.8/site-packages (from requests->fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning>=1.5.0->nemo_toolkit[all]==1.5.1) (1.7.1)\n    Requirement already satisfied: ruamel.yaml.clib>=0.2.6 in /opt/conda/lib/python3.8/site-packages (from ruamel.yaml->nemo_toolkit[all]==1.5.1) (0.2.6)\n    Requirement already satisfied: portalocker in /opt/conda/lib/python3.8/site-packages (from sacrebleu[ja]->nemo_toolkit[all]==1.5.1) (2.4.0)\n    Requirement already satisfied: ipadic<2.0,>=1.0 in /opt/conda/lib/python3.8/site-packages (from sacrebleu[ja]->nemo_toolkit[all]==1.5.1) (1.0.0)\n    Requirement already satisfied: mecab-python3==1.0.3 in /opt/conda/lib/python3.8/site-packages (from sacrebleu[ja]->nemo_toolkit[all]==1.5.1) (1.0.3)\n    Requirement already satisfied: sphinxcontrib-htmlhelp>=2.0.0 in /opt/conda/lib/python3.8/site-packages (from sphinx->nemo_toolkit[all]==1.5.1) (2.0.0)\n    Requirement already satisfied: alabaster<0.8,>=0.7 in /opt/conda/lib/python3.8/site-packages (from sphinx->nemo_toolkit[all]==1.5.1) (0.7.12)\n    Requirement already satisfied: babel>=1.3 in /opt/conda/lib/python3.8/site-packages (from sphinx->nemo_toolkit[all]==1.5.1) (2.9.1)\n    Requirement already satisfied: sphinxcontrib-serializinghtml>=1.1.5 in /opt/conda/lib/python3.8/site-packages (from sphinx->nemo_toolkit[all]==1.5.1) (1.1.5)\n    Requirement already satisfied: sphinxcontrib-devhelp in /opt/conda/lib/python3.8/site-packages (from sphinx->nemo_toolkit[all]==1.5.1) (1.0.2)\n    Requirement already satisfied: sphinxcontrib-jsmath in /opt/conda/lib/python3.8/site-packages (from sphinx->nemo_toolkit[all]==1.5.1) (1.0.1)\n    Requirement already satisfied: sphinxcontrib-qthelp in /opt/conda/lib/python3.8/site-packages (from sphinx->nemo_toolkit[all]==1.5.1) (1.0.3)\n    Requirement already satisfied: snowballstemmer>=1.1 in /opt/conda/lib/python3.8/site-packages (from sphinx->nemo_toolkit[all]==1.5.1) (2.2.0)\n    Requirement already satisfied: imagesize in /opt/conda/lib/python3.8/site-packages (from sphinx->nemo_toolkit[all]==1.5.1) (1.3.0)\n    Requirement already satisfied: sphinxcontrib-applehelp in /opt/conda/lib/python3.8/site-packages (from sphinx->nemo_toolkit[all]==1.5.1) (1.0.2)\n    Requirement already satisfied: docutils<0.18,>=0.14 in /opt/conda/lib/python3.8/site-packages (from sphinx->nemo_toolkit[all]==1.5.1) (0.17.1)\n    Requirement already satisfied: pybtex-docutils>=1.0.0 in /opt/conda/lib/python3.8/site-packages (from sphinxcontrib-bibtex->nemo_toolkit[all]==1.5.1) (1.0.1)\n    Requirement already satisfied: pybtex>=0.24 in /opt/conda/lib/python3.8/site-packages (from sphinxcontrib-bibtex->nemo_toolkit[all]==1.5.1) (0.24.0)\n    Requirement already satisfied: latexcodec>=1.0.4 in /opt/conda/lib/python3.8/site-packages (from pybtex>=0.24->sphinxcontrib-bibtex->nemo_toolkit[all]==1.5.1) (2.0.1)\n    Requirement already satisfied: pure-eval in /opt/conda/lib/python3.8/site-packages (from stack-data->ipython>=4.0.0->ipywidgets->nemo_toolkit[all]==1.5.1) (0.2.2)\n    Requirement already satisfied: asttokens in /opt/conda/lib/python3.8/site-packages (from stack-data->ipython>=4.0.0->ipywidgets->nemo_toolkit[all]==1.5.1) (2.0.5)\n    Requirement already satisfied: executing in /opt/conda/lib/python3.8/site-packages (from stack-data->ipython>=4.0.0->ipywidgets->nemo_toolkit[all]==1.5.1) (0.8.3)\n    Requirement already satisfied: pathtools in /opt/conda/lib/python3.8/site-packages (from wandb->nemo_toolkit[all]==1.5.1) (0.1.2)\n    Requirement already satisfied: setproctitle in /opt/conda/lib/python3.8/site-packages (from wandb->nemo_toolkit[all]==1.5.1) (1.2.3)\n    Requirement already satisfied: GitPython>=1.0.0 in /opt/conda/lib/python3.8/site-packages (from wandb->nemo_toolkit[all]==1.5.1) (3.1.27)\n    Requirement already satisfied: sentry-sdk>=1.0.0 in /opt/conda/lib/python3.8/site-packages (from wandb->nemo_toolkit[all]==1.5.1) (1.5.10)\n    Requirement already satisfied: shortuuid>=0.5.0 in /opt/conda/lib/python3.8/site-packages (from wandb->nemo_toolkit[all]==1.5.1) (1.0.8)\n    Requirement already satisfied: docker-pycreds>=0.4.0 in /opt/conda/lib/python3.8/site-packages (from wandb->nemo_toolkit[all]==1.5.1) (0.4.0)\n    Requirement already satisfied: promise<3,>=2.0 in /opt/conda/lib/python3.8/site-packages (from wandb->nemo_toolkit[all]==1.5.1) (2.3)\n    Requirement already satisfied: gitdb<5,>=4.0.1 in /opt/conda/lib/python3.8/site-packages (from GitPython>=1.0.0->wandb->nemo_toolkit[all]==1.5.1) (4.0.9)\n    Requirement already satisfied: smmap<6,>=3.0.1 in /opt/conda/lib/python3.8/site-packages (from gitdb<5,>=4.0.1->GitPython>=1.0.0->wandb->nemo_toolkit[all]==1.5.1) (5.0.0)\n    \u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\n\n\n<a id=\"2\"></a>\n## 2. Download Citrinet model\n\nNext, we download a pretrained Nemo Citrinet model and convert it to a Torchscript module:\n\n\n```python\nimport nemo\nimport torch\n\nimport nemo.collections.asr as nemo_asr\nfrom nemo.core import typecheck\ntypecheck.set_typecheck_enabled(False) \n```\n\n\n```python\nvariant = 'stt_en_citrinet_256'\n\nprint(f\"Downloading and saving {variant}...\")\nasr_model = nemo_asr.models.EncDecCTCModelBPE.from_pretrained(model_name=variant)\nasr_model.export(f\"{variant}.ts\")\n```\n\n    Downloading and saving stt_en_citrinet_256...\n    [NeMo I 2022-04-21 23:12:45 cloud:56] Found existing object /root/.cache/torch/NeMo/NeMo_1.5.1/stt_en_citrinet_256/91a9cc5850784b2065e8a0aa3d526fd9/stt_en_citrinet_256.nemo.\n    [NeMo I 2022-04-21 23:12:45 cloud:62] Re-using file from: /root/.cache/torch/NeMo/NeMo_1.5.1/stt_en_citrinet_256/91a9cc5850784b2065e8a0aa3d526fd9/stt_en_citrinet_256.nemo\n    [NeMo I 2022-04-21 23:12:45 common:728] Instantiating model from pre-trained checkpoint\n    [NeMo I 2022-04-21 23:12:46 mixins:146] Tokenizer SentencePieceTokenizer initialized with 1024 tokens\n\n\n    [NeMo W 2022-04-21 23:12:47 modelPT:130] If you intend to do training or fine-tuning, please call the ModelPT.setup_training_data() method and provide a valid configuration file to setup the train data loader.\n        Train config : \n        manifest_filepath: null\n        sample_rate: 16000\n        batch_size: 32\n        trim_silence: true\n        max_duration: 16.7\n        shuffle: true\n        is_tarred: false\n        tarred_audio_filepaths: null\n        use_start_end_token: false\n        \n    [NeMo W 2022-04-21 23:12:47 modelPT:137] If you intend to do validation, please call the ModelPT.setup_validation_data() or ModelPT.setup_multiple_validation_data() method and provide a valid configuration file to setup the validation data loader(s). \n        Validation config : \n        manifest_filepath: null\n        sample_rate: 16000\n        batch_size: 32\n        shuffle: false\n        use_start_end_token: false\n        \n    [NeMo W 2022-04-21 23:12:47 modelPT:143] Please call the ModelPT.setup_test_data() or ModelPT.setup_multiple_test_data() method and provide a valid configuration file to setup the test data loader(s).\n        Test config : \n        manifest_filepath: null\n        sample_rate: 16000\n        batch_size: 32\n        shuffle: false\n        use_start_end_token: false\n        \n\n\n    [NeMo I 2022-04-21 23:12:47 features:265] PADDING: 16\n    [NeMo I 2022-04-21 23:12:47 features:282] STFT using torch\n\n\n    [NeMo W 2022-04-21 23:12:47 nemo_logging:349] /opt/conda/lib/python3.8/site-packages/nemo/collections/asr/parts/preprocessing/features.py:315: FutureWarning: Pass sr=16000, n_fft=512 as keyword args. From version 0.10 passing these as positional arguments will result in an error\n          librosa.filters.mel(sample_rate, self.n_fft, n_mels=nfilt, fmin=lowfreq, fmax=highfreq), dtype=torch.float\n        \n\n\n    [NeMo I 2022-04-21 23:12:49 save_restore_connector:149] Model EncDecCTCModelBPE was successfully restored from /root/.cache/torch/NeMo/NeMo_1.5.1/stt_en_citrinet_256/91a9cc5850784b2065e8a0aa3d526fd9/stt_en_citrinet_256.nemo.\n\n\n    [NeMo W 2022-04-21 23:12:49 export_utils:198] Swapped 0 modules\n    [NeMo W 2022-04-21 23:12:49 conv_asr:73] Turned off 235 masked convolutions\n    [NeMo W 2022-04-21 23:12:49 export_utils:198] Swapped 0 modules\n    [NeMo W 2022-04-21 23:12:50 nemo_logging:349] /opt/conda/lib/python3.8/site-packages/torch/jit/_trace.py:916: UserWarning: `optimize` is deprecated and has no effect. Use `with torch.jit.optimized_execution() instead\n          warnings.warn(\n        \n    [NeMo W 2022-04-21 23:12:50 nemo_logging:349] /opt/conda/lib/python3.8/site-packages/torch/_jit_internal.py:668: LightningDeprecationWarning: The `LightningModule.model_size` property was deprecated in v1.5 and will be removed in v1.7. Please use the `pytorch_lightning.utilities.memory.get_model_size_mb`.\n          if hasattr(mod, name):\n        \n    [NeMo W 2022-04-21 23:12:50 nemo_logging:349] /opt/conda/lib/python3.8/site-packages/torch/_jit_internal.py:669: LightningDeprecationWarning: The `LightningModule.model_size` property was deprecated in v1.5 and will be removed in v1.7. Please use the `pytorch_lightning.utilities.memory.get_model_size_mb`.\n          item = getattr(mod, name)\n        \n    [NeMo W 2022-04-21 23:12:50 nemo_logging:349] /opt/conda/lib/python3.8/site-packages/torch/_jit_internal.py:668: LightningDeprecationWarning: `LightningModule.use_amp` was deprecated in v1.6 and will be removed in v1.8. Please use `Trainer.amp_backend`.\n          if hasattr(mod, name):\n        \n    [NeMo W 2022-04-21 23:12:50 nemo_logging:349] /opt/conda/lib/python3.8/site-packages/torch/_jit_internal.py:669: LightningDeprecationWarning: `LightningModule.use_amp` was deprecated in v1.6 and will be removed in v1.8. Please use `Trainer.amp_backend`.\n          item = getattr(mod, name)\n        \n\n\n\n\n\n    (['stt_en_citrinet_256.ts'],\n     ['nemo.collections.asr.models.ctc_bpe_models.EncDecCTCModelBPE exported to ONNX'])\n\n\n\n### Benchmark utility\n\nLet us define a helper benchmarking function, then benchmark the original Pytorch model.\n\n\n```python\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport argparse\nimport timeit\nimport numpy as np\nimport torch\nimport torch_tensorrt as trtorch\nimport torch.backends.cudnn as cudnn\n\ndef benchmark(model, input_tensor, num_loops, model_name, batch_size):\n    def timeGraph(model, input_tensor, num_loops):\n        print(\"Warm up ...\")\n        with torch.no_grad():\n            for _ in range(20):\n                features = model(input_tensor)\n\n        torch.cuda.synchronize()\n        print(\"Start timing ...\")\n        timings = []\n        with torch.no_grad():\n            for i in range(num_loops):\n                start_time = timeit.default_timer()\n                features = model(input_tensor)\n                torch.cuda.synchronize()\n                end_time = timeit.default_timer()\n                timings.append(end_time - start_time)\n                # print(\"Iteration {}: {:.6f} s\".format(i, end_time - start_time))\n        return timings\n    def printStats(graphName, timings, batch_size):\n        times = np.array(timings)\n        steps = len(times)\n        speeds = batch_size / times\n        time_mean = np.mean(times)\n        time_med = np.median(times)\n        time_99th = np.percentile(times, 99)\n        time_std = np.std(times, ddof=0)\n        speed_mean = np.mean(speeds)\n        speed_med = np.median(speeds)\n        msg = (\"\\n%s =================================\\n\"\n                \"batch size=%d, num iterations=%d\\n\"\n                \"  Median samples/s: %.1f, mean: %.1f\\n\"\n                \"  Median latency (s): %.6f, mean: %.6f, 99th_p: %.6f, std_dev: %.6f\\n\"\n                ) % (graphName,\n                    batch_size, steps,\n                    speed_med, speed_mean,\n                    time_med, time_mean, time_99th, time_std)\n        print(msg)\n    timings = timeGraph(model, input_tensor, num_loops)\n    printStats(model_name, timings, batch_size)\n\nprecisions_str = 'fp32' # Precision (default=fp32, fp16)\nvariant = 'stt_en_citrinet_256' # Nemo Citrinet variant\nbatch_sizes = [1, 8, 32, 128] # Batch sizes (default=1,8,32,128)\ntrt = False # If True, infer with Torch-TensorRT engine. Else, infer with Pytorch model.\nprecision = torch.float32 if precisions_str =='fp32' else torch.float16\n\nfor batch_size in batch_sizes:\n    if trt:\n        model_name = f\"{variant}_bs{batch_size}_{precision}.torch-tensorrt\"\n    else:\n        model_name = f\"{variant}.ts\"\n\n    print(f\"Loading model: {model_name}\") \n    # Load traced model to CPU first\n    model = torch.jit.load(model_name).cuda()\n    cudnn.benchmark = True\n    # Create random input tensor of certain size\n    torch.manual_seed(12345)\n    input_shape=(batch_size, 80, 1488)\n    input_tensor = torch.randn(input_shape).cuda()\n\n    # Timing graph inference\n    benchmark(model, input_tensor, 50, model_name, batch_size)\n```\n\n    Loading model: stt_en_citrinet_256.ts\n    Warm up ...\n    Start timing ...\n    \n    stt_en_citrinet_256.ts =================================\n    batch size=1, num iterations=50\n      Median samples/s: 102.0, mean: 102.0\n      Median latency (s): 0.009802, mean: 0.009803, 99th_p: 0.009836, std_dev: 0.000014\n    \n    Loading model: stt_en_citrinet_256.ts\n    Warm up ...\n    Start timing ...\n    \n    stt_en_citrinet_256.ts =================================\n    batch size=8, num iterations=50\n      Median samples/s: 429.1, mean: 429.1\n      Median latency (s): 0.018642, mean: 0.018643, 99th_p: 0.018670, std_dev: 0.000014\n    \n    Loading model: stt_en_citrinet_256.ts\n    Warm up ...\n    Start timing ...\n    \n    stt_en_citrinet_256.ts =================================\n    batch size=32, num iterations=50\n      Median samples/s: 551.3, mean: 551.2\n      Median latency (s): 0.058047, mean: 0.058053, 99th_p: 0.058375, std_dev: 0.000106\n    \n    Loading model: stt_en_citrinet_256.ts\n    Warm up ...\n    Start timing ...\n    \n    stt_en_citrinet_256.ts =================================\n    batch size=128, num iterations=50\n      Median samples/s: 594.1, mean: 594.1\n      Median latency (s): 0.215434, mean: 0.215446, 99th_p: 0.215806, std_dev: 0.000116\n    \n\n\nConfirming the GPU we are using here:\n\n\n```python\n!nvidia-smi\n```\n\n    Thu Apr 21 23:13:32 2022       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 510.47.03    Driver Version: 510.47.03    CUDA Version: 11.6     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  NVIDIA TITAN V      On   | 00000000:17:00.0 Off |                  N/A |\n    | 38%   55C    P2    42W / 250W |   2462MiB / 12288MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n    |   1  NVIDIA TITAN V      On   | 00000000:65:00.0 Off |                  N/A |\n    | 28%   39C    P8    26W / 250W |    112MiB / 12288MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    |    0   N/A  N/A      3909      G                                       4MiB |\n    |    0   N/A  N/A      6047      C                                    2453MiB |\n    |    1   N/A  N/A      3909      G                                      39MiB |\n    |    1   N/A  N/A      4161      G                                      67MiB |\n    +-----------------------------------------------------------------------------+\n\n\n<a id=\"3\"></a>\n## 3. Create Torch-TensorRT modules\n\nIn this step, we optimize the Citrinet Torchscript module with Torch-TensorRT with various precisions and batch sizes.\n\n\n```python\nimport torch\nimport torch.nn as nn\nimport torch_tensorrt as torchtrt\nimport argparse\n\nvariant = \"stt_en_citrinet_256\"\nprecisions = [torch.float, torch.half]\nbatch_sizes = [1,8,32,128]\n\nmodel = torch.jit.load(f\"{variant}.ts\")\n\nfor precision in precisions:\n    for batch_size in batch_sizes:\n        compile_settings = {\n            \"inputs\": [torchtrt.Input(shape=[batch_size, 80, 1488])],\n            \"enabled_precisions\": {precision},\n            \"workspace_size\": 2000000000,\n            \"truncate_long_and_double\": True,\n        }\n        print(f\"Generating Torchscript-TensorRT module for batchsize {batch_size} precision {precision}\")\n        trt_ts_module = torchtrt.compile(model, **compile_settings)\n        torch.jit.save(trt_ts_module, f\"{variant}_bs{batch_size}_{precision}.torch-tensorrt\")\n```\n\n    Generating Torchscript-TensorRT module for batchsize 1 precision torch.float32\n    Generating Torchscript-TensorRT module for batchsize 8 precision torch.float32\n    Generating Torchscript-TensorRT module for batchsize 32 precision torch.float32\n    Generating Torchscript-TensorRT module for batchsize 128 precision torch.float32\n    Generating Torchscript-TensorRT module for batchsize 1 precision torch.float16\n    Generating Torchscript-TensorRT module for batchsize 8 precision torch.float16\n    Generating Torchscript-TensorRT module for batchsize 32 precision torch.float16\n    Generating Torchscript-TensorRT module for batchsize 128 precision torch.float16\n\n\n<a id=\"4\"></a>\n## 4. Benchmark Torch-TensorRT models\n\nFinally, we are ready to benchmark the Torch-TensorRT optimized Citrinet models.\n\n### FP32 (single precision)\n\n\n```python\nprecisions_str = 'fp32' # Precision (default=fp32, fp16)\nbatch_sizes = [1, 8, 32, 128] # Batch sizes (default=1,8,32,128)\nprecision = torch.float32 if precisions_str =='fp32' else torch.float16\ntrt = True\n\nfor batch_size in batch_sizes:\n    if trt:\n        model_name = f\"{variant}_bs{batch_size}_{precision}.torch-tensorrt\"\n    else:\n        model_name = f\"{variant}.ts\"\n\n    print(f\"Loading model: {model_name}\") \n    # Load traced model to CPU first\n    model = torch.jit.load(model_name).cuda()\n    cudnn.benchmark = True\n    # Create random input tensor of certain size\n    torch.manual_seed(12345)\n    input_shape=(batch_size, 80, 1488)\n    input_tensor = torch.randn(input_shape).cuda()\n\n    # Timing graph inference\n    benchmark(model, input_tensor, 50, model_name, batch_size)\n```\n\n    Loading model: stt_en_citrinet_256_bs1_torch.float32.torch-tensorrt\n    Warm up ...\n    Start timing ...\n    \n    stt_en_citrinet_256_bs1_torch.float32.torch-tensorrt =================================\n    batch size=1, num iterations=50\n      Median samples/s: 242.2, mean: 218.0\n      Median latency (s): 0.004128, mean: 0.004825, 99th_p: 0.008071, std_dev: 0.001270\n    \n    Loading model: stt_en_citrinet_256_bs8_torch.float32.torch-tensorrt\n    Warm up ...\n    Start timing ...\n    \n    stt_en_citrinet_256_bs8_torch.float32.torch-tensorrt =================================\n    batch size=8, num iterations=50\n      Median samples/s: 729.9, mean: 709.0\n      Median latency (s): 0.010961, mean: 0.011388, 99th_p: 0.016114, std_dev: 0.001256\n    \n    Loading model: stt_en_citrinet_256_bs32_torch.float32.torch-tensorrt\n    Warm up ...\n    Start timing ...\n    \n    stt_en_citrinet_256_bs32_torch.float32.torch-tensorrt =================================\n    batch size=32, num iterations=50\n      Median samples/s: 955.6, mean: 953.4\n      Median latency (s): 0.033488, mean: 0.033572, 99th_p: 0.035722, std_dev: 0.000545\n    \n    Loading model: stt_en_citrinet_256_bs128_torch.float32.torch-tensorrt\n    Warm up ...\n    Start timing ...\n    \n    stt_en_citrinet_256_bs128_torch.float32.torch-tensorrt =================================\n    batch size=128, num iterations=50\n      Median samples/s: 1065.8, mean: 1069.4\n      Median latency (s): 0.120097, mean: 0.119708, 99th_p: 0.121618, std_dev: 0.001260\n    \n\n\n### FP16 (half precision)\n\n\n```python\nprecisions_str = 'fp16' # Precision (default=fp32, fp16)\nbatch_sizes = [1, 8, 32, 128] # Batch sizes (default=1,8,32,128)\nprecision = torch.float32 if precisions_str =='fp32' else torch.float16\n\nfor batch_size in batch_sizes:\n    if trt:\n        model_name = f\"{variant}_bs{batch_size}_{precision}.torch-tensorrt\"\n    else:\n        model_name = f\"{variant}.ts\"\n\n    print(f\"Loading model: {model_name}\") \n    # Load traced model to CPU first\n    model = torch.jit.load(model_name).cuda()\n    cudnn.benchmark = True\n    # Create random input tensor of certain size\n    torch.manual_seed(12345)\n    input_shape=(batch_size, 80, 1488)\n    input_tensor = torch.randn(input_shape).cuda()\n\n    # Timing graph inference\n    benchmark(model, input_tensor, 50, model_name, batch_size)\n```\n\n    Loading model: stt_en_citrinet_256_bs1_torch.float16.torch-tensorrt\n    Warm up ...\n    Start timing ...\n    \n    stt_en_citrinet_256_bs1_torch.float16.torch-tensorrt =================================\n    batch size=1, num iterations=50\n      Median samples/s: 288.9, mean: 272.9\n      Median latency (s): 0.003462, mean: 0.003774, 99th_p: 0.006846, std_dev: 0.000820\n    \n    Loading model: stt_en_citrinet_256_bs8_torch.float16.torch-tensorrt\n    Warm up ...\n    Start timing ...\n    \n    stt_en_citrinet_256_bs8_torch.float16.torch-tensorrt =================================\n    batch size=8, num iterations=50\n      Median samples/s: 1201.0, mean: 1190.9\n      Median latency (s): 0.006661, mean: 0.006733, 99th_p: 0.008453, std_dev: 0.000368\n    \n    Loading model: stt_en_citrinet_256_bs32_torch.float16.torch-tensorrt\n    Warm up ...\n    Start timing ...\n    \n    stt_en_citrinet_256_bs32_torch.float16.torch-tensorrt =================================\n    batch size=32, num iterations=50\n      Median samples/s: 1538.2, mean: 1516.4\n      Median latency (s): 0.020804, mean: 0.021143, 99th_p: 0.024492, std_dev: 0.000973\n    \n    Loading model: stt_en_citrinet_256_bs128_torch.float16.torch-tensorrt\n    Warm up ...\n    Start timing ...\n    \n    stt_en_citrinet_256_bs128_torch.float16.torch-tensorrt =================================\n    batch size=128, num iterations=50\n      Median samples/s: 1792.0, mean: 1777.0\n      Median latency (s): 0.071428, mean: 0.072057, 99th_p: 0.076796, std_dev: 0.001351\n    \n\n\n<a id=\"5\"></a>\n## 5. Conclusion\n\nIn this notebook, we have walked through the complete process of optimizing the Citrinet model with Torch-TensorRT. On an A100 GPU, with Torch-TensorRT, we observe a speedup of ~**2.4X** with FP32, and ~**2.9X** with FP16 at batchsize of 128.\n\n### What's next\nNow it's time to try Torch-TensorRT on your own model. Fill out issues at https://github.com/NVIDIA/Torch-TensorRT. Your involvement will help future development of Torch-TensorRT.\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "0573af0176a317f8de46a3a75f69274d08e971dd", "size": 68238, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/_notebooks/CitriNet-example.ipynb", "max_stars_repo_name": "hassan11196/Torch-TensorRT", "max_stars_repo_head_hexsha": "a2d0d0e935bf223523a7c28d7814cdbd32f323b2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 430, "max_stars_repo_stars_event_min_datetime": "2021-11-09T08:08:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T10:13:45.000Z", "max_issues_repo_path": "docs/v1.1.0/_sources/_notebooks/CitriNet-example.ipynb.txt", "max_issues_repo_name": "NVIDIA/Torch-TensorRT", "max_issues_repo_head_hexsha": "1a22204fecec690bc3c2a318dab4f57b98c57f05", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 257, "max_issues_repo_issues_event_min_datetime": "2021-11-09T07:17:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:29:31.000Z", "max_forks_repo_path": "notebooks/CitriNet-example.ipynb", "max_forks_repo_name": "hassan11196/Torch-TensorRT", "max_forks_repo_head_hexsha": "a2d0d0e935bf223523a7c28d7814cdbd32f323b2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 68, "max_forks_repo_forks_event_min_datetime": "2021-11-10T05:03:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T17:07:32.000Z", "avg_line_length": 70.7129533679, "max_line_length": 459, "alphanum_fraction": 0.6368885372, "converted": true, "num_tokens": 19125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404168757891037, "lm_q2_score": 0.1329642436335826, "lm_q1q2_score": 0.04042667302200785}}
{"text": "<a href=\"https://colab.research.google.com/github/kalz2q/mycolabnotebooks/blob/master/chainer.ipynb\" target=\"_parent\"></a>\n\n# \u30e1\u30e2\n\nChainer \u306e\u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb\u30b5\u30a4\u30c8\u304c Open in Colab \u30dc\u30bf\u30f3\u306e\u3042\u308b\u30b5\u30a4\u30c8\u3060\u3063\u305f\u306e\u3067\u305d\u3053\u304b\u3089\u62fe\u3044\u8aad\u307f\n\nhttps://tutorials.chainer.org/ja/tutorial.html\n\n&nbsp;\n\n\u30aa\u30f3\u30e9\u30a4\u30f3\u5b66\u7fd2\u8cc7\u6599\n\n- \u6570\u5b66\u306e\u77e5\u8b58\n- Python \u3092\u7528\u3044\u305f\u30b3\u30fc\u30c7\u30a3\u30f3\u30b0\u306e\u57fa\u672c\n- \u6a5f\u68b0\u5b66\u7fd2\u30fb\u30c7\u30a3\u30fc\u30d7\u30e9\u30fc\u30cb\u30f3\u30b0\u306e\u57fa\u790e\u7684\u306a\u7406\u8ad6\n- \u753b\u50cf\u8a8d\u8b58\u3084\u81ea\u7136\u8a00\u8a9e\u51e6\u7406\u306a\u3069\u306b\u6a5f\u68b0\u5b66\u7fd2\u3092\u5fdc\u7528\u3059\u308b\u65b9\u6cd5\n\n\u304c\u5b66\u3079\u308b\u3068\u306e\u3053\u3068\u3002\n&nbsp;\n\n\n\n\u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb\u30b5\u30a4\u30c8\u306e\u304a\u3059\u3059\u3081\u306e\u5229\u7528\u65b9\u6cd5\n\n1. `Open in Colab` \u30dc\u30bf\u30f3\u3067 Colab \u3067\u958b\u304f\n2. \u30e1\u30cb\u30e5\u30fc\u306e\u30c9\u30e9\u30a4\u30d6\u306b\u30b3\u30d4\u30fc\u3001\u3067\u81ea\u5206\u306e\u30c9\u30e9\u30a4\u30d6\u306b\u30b3\u30d4\u30fc\u3059\u308b\n3. \u30b3\u30fc\u30c9\u3092\u5b9f\u884c\u3057\u306a\u304c\u3089\u8aad\u3093\u3067\u3044\u304f\n\n\u3068\u8a00\u3046\u624b\u9806\u304c\u3001\u672c\u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb\u30b5\u30a4\u30c8\u306e\u304a\u3059\u3059\u3081\u306e\u5229\u7528\u65b9\u6cd5\n\n&nbsp;\n\n# Colab \u306e\u4fbf\u5229\u306a\u30b7\u30e7\u30fc\u30c8\u30ab\u30c3\u30c8\n\n| \u8aac\u660e                 | \u30b3\u30de\u30f3\u30c9      |\n| -------------------- | ------------- |\n| Markdown\u30e2\u30fc\u30c9\u3078\u5909\u66f4 | Ctrl + M \u2192 M |\n| Code\u30e2\u30fc\u30c9\u3078\u5909\u66f4     | Ctrl + M \u2192 Y |\n| \u30bb\u30eb\u306e\u5b9f\u884c           | Shift + Enter |\n| \u30bb\u30eb\u3092\u4e0a\u306b\u8ffd\u52a0       | Ctrl + M \u2192 A |\n| \u30bb\u30eb\u3092\u4e0b\u306b\u8ffd\u52a0       | Ctrl + M \u2192 B |\n| \u30bb\u30eb\u306e\u30b3\u30d4\u30fc         | Ctrl + M \u2192 C |\n| \u30bb\u30eb\u306e\u8cbc\u308a\u4ed8\u3051       | Ctrl + M \u2192 V |\n| \u30bb\u30eb\u306e\u6d88\u53bb           | Ctrl + M \u2192 D |\n| \u30b3\u30e1\u30f3\u30c8\u30a2\u30a6\u30c8       | Ctrl + /      |\n\n&nbsp;\n\n\n\n\n```python\n#@title\n%%html\n<style>\n    /* table {\n        border-collapse: collapse;\n        border: 2px solid rgb(200, 200, 200);\n        letter-spacing: 1px;\n        margin: auto;\n    } */\n\n    td,\n    th {\n        border: 1px solid rgb(190, 190, 190);\n        padding: 10px 20px;\n    }\n\n    tr:nth-child(even) td {\n        /* background-color: rgb(250, 250, 250); */\n        background-color: red;\n    }\n\n    tr:nth-child(odd) td {\n        background-color: rgb(80,30,0);\n        color: white;\n    }\n\n    /* tr td:nth-child(3) {\n        color: red;\n        font-size: 300%;\n    } */\n</style>\n\n<table>\n<thead>\n<tr>\n<th>\u8aac\u660e</th>\n<th>\u30b3\u30de\u30f3\u30c9</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Markdown\u30e2\u30fc\u30c9\u3078\u5909\u66f4</td>\n<td>Ctrl + M \u2192 M</td>\n</tr>\n<tr>\n<td>Code\u30e2\u30fc\u30c9\u3078\u5909\u66f4</td>\n<td>Ctrl + M \u2192 Y</td>\n</tr>\n<tr>\n<td>\u30bb\u30eb\u306e\u5b9f\u884c</td>\n<td>Shift + Enter</td>\n</tr>\n<tr>\n<td>\u30bb\u30eb\u3092\u4e0a\u306b\u8ffd\u52a0</td>\n<td>Ctrl + M \u2192 A</td>\n</tr>\n<tr>\n<td>\u30bb\u30eb\u3092\u4e0b\u306b\u8ffd\u52a0</td>\n<td>Ctrl + M \u2192 B</td>\n</tr>\n<tr>\n<td>\u30bb\u30eb\u306e\u30b3\u30d4\u30fc</td>\n<td>Ctrl + M \u2192 C</td>\n</tr>\n<tr>\n<td>\u30bb\u30eb\u306e\u8cbc\u308a\u4ed8\u3051</td>\n<td>Ctrl + M \u2192 V</td>\n</tr>\n<tr>\n<td>\u30bb\u30eb\u306e\u6d88\u53bb</td>\n<td>Ctrl + M \u2192 D</td>\n</tr>\n<tr>\n<td>\u30b3\u30e1\u30f3\u30c8\u30a2\u30a6\u30c8</td>\n<td>Ctrl + /</td>\n</tr>\n</tbody>\n</table>\n\n```\n\n\n<style>\n    /* table {\n        border-collapse: collapse;\n        border: 2px solid rgb(200, 200, 200);\n        letter-spacing: 1px;\n        margin: auto;\n    } */\n\n    td,\n    th {\n        border: 1px solid rgb(190, 190, 190);\n        padding: 10px 20px;\n    }\n\n    tr:nth-child(even) td {\n        /* background-color: rgb(250, 250, 250); */\n        background-color: red;\n    }\n\n    tr:nth-child(odd) td {\n        background-color: rgb(80,30,0);\n        color: white;\n    }\n\n    /* tr td:nth-child(3) {\n        color: red;\n        font-size: 300%;\n    } */\n</style>\n\n<table>\n<thead>\n<tr>\n<th>\u8aac\u660e</th>\n<th>\u30b3\u30de\u30f3\u30c9</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Markdown\u30e2\u30fc\u30c9\u3078\u5909\u66f4</td>\n<td>Ctrl + M \u2192 M</td>\n</tr>\n<tr>\n<td>Code\u30e2\u30fc\u30c9\u3078\u5909\u66f4</td>\n<td>Ctrl + M \u2192 Y</td>\n</tr>\n<tr>\n<td>\u30bb\u30eb\u306e\u5b9f\u884c</td>\n<td>Shift + Enter</td>\n</tr>\n<tr>\n<td>\u30bb\u30eb\u3092\u4e0a\u306b\u8ffd\u52a0</td>\n<td>Ctrl + M \u2192 A</td>\n</tr>\n<tr>\n<td>\u30bb\u30eb\u3092\u4e0b\u306b\u8ffd\u52a0</td>\n<td>Ctrl + M \u2192 B</td>\n</tr>\n<tr>\n<td>\u30bb\u30eb\u306e\u30b3\u30d4\u30fc</td>\n<td>Ctrl + M \u2192 C</td>\n</tr>\n<tr>\n<td>\u30bb\u30eb\u306e\u8cbc\u308a\u4ed8\u3051</td>\n<td>Ctrl + M \u2192 V</td>\n</tr>\n<tr>\n<td>\u30bb\u30eb\u306e\u6d88\u53bb</td>\n<td>Ctrl + M \u2192 D</td>\n</tr>\n<tr>\n<td>\u30b3\u30e1\u30f3\u30c8\u30a2\u30a6\u30c8</td>\n<td>Ctrl + /</td>\n</tr>\n</tbody>\n</table>\n\n\n# Python \u5165\u9580\n\n\n\u3068\u3066\u3082\u3059\u3063\u304d\u308a\u3057\u305f Python \u5165\u9580\n\n- \u5909\u6570\u3001\u30ea\u30b9\u30c8\u3001\u30bf\u30d7\u30eb\u3001\u8f9e\u66f8\n- \u5236\u5fa1\u69cb\u6587\n- \u95a2\u6570\u3001\u30b9\u30b3\u30fc\u30d7\n- \u30af\u30e9\u30b9\u3001\u7d99\u627f\n\n\n```python\na = 1\n```\n\n\n```python\nb = 1.2\n```\n\n\n```python\nc = 'Chainer'\n```\n\n\n```python\ntype(a)\n```\n\n\n\n\n    int\n\n\n\n\n```python\ntype(b)\n```\n\n\n\n\n    float\n\n\n\n\n```python\ntype(c)\n```\n\n\n\n\n    str\n\n\n\nPython \u3067\u306f\u3001`.` \u3092\u542b\u307e\u306a\u3044\u9023\u7d9a\u3057\u305f\u6570\u5b57\u3092 `int`\u3001\n\n\u76f4\u524d\u30fb\u76f4\u5f8c\u3082\u542b\u3081 `.` \u304c\u542b\u307e\u308c\u308b\u9023\u7d9a\u3057\u305f\u6570\u5b57\u3092 `float` \n\n\u3060\u3068\u81ea\u52d5\u7684\u306b\u89e3\u91c8\u3059\u308b\u3002\n\n\u4f8b\u3048\u3070\u3001`7` \u3084 `365` \u306f `int` \u3060\u304c\u3001\n\n`2.718`\u3001`.25`\u3001`10.` \u306a\u3069\u306f `float` \u306b\u306a\u308b\u3002\n\n\u5b9f\u6570\u306e `0` \u306f `0.0` \u3068\u3082 `.0` \u3068\u3082 `0.` \u3068\u3082\u66f8\u304f\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\n```python\ntype(0)\n```\n\n\n\n\n    int\n\n\n\n\n```python\ntype(0.)\n```\n\n\n\n\n    float\n\n\n\n\n```python\ntype(.0)\n```\n\n\n\n\n    float\n\n\n\nPython 3 \u3067\u306f\u3001 `/` \u8a18\u53f7\u3092\u7528\u3044\u3066\u9664\u7b97\u3092\u884c\u3046\u5834\u5408\u3001\n\n\u9664\u6570\uff08\u5272\u308b\u6570\uff09\u3068\u88ab\u9664\u6570\uff08\u5272\u3089\u308c\u308b\u6570\uff09\u304c\u6574\u6570\u3067\u3042\u3063\u3066\u3082\u3001\n\n\u8a08\u7b97\u7d50\u679c\u3068\u3057\u3066\u5b9f\u6570\u304c\u8fd4\u308b\u3002\n\n\u8a08\u7b97\u7d50\u679c\u3068\u3057\u3066\u5b9f\u6570\u3092\u8fd4\u3059\u9664\u7b97\u306e\u3053\u3068\u3092\u7279\u306b\u3001\n\n**\u771f\u306e\u9664\u7b97 (true division)** \u3068\u8a00\u3046\u3002\n\n\u4e00\u65b9\u3001\u5546\uff08\u6574\u6570\u90e8\u5206\uff09\u3092\u8fd4\u3059\u3088\u3046\u306a\u9664\u7b97\u6f14\u7b97\u5b50\u3068\u3057\u3066\u3001\n\n `//` \u8a18\u53f7\u304c\u7528\u610f\u3055\u308c\u3066\u3044\u308b\u3002 \n \n \u8a08\u7b97\u7d50\u679c\u3068\u3057\u3066\u5546\u3092\u8fd4\u3059\u9664\u7b97\u306e\u3053\u3068\u3092\u3001 **\u5207\u308a\u6368\u3066\u9664\u7b97 (floor division)** \u3068\u547c\u3076\u3002\n\n\n\n```python\n# \u6574\u6570\u3068\u6574\u6570\u3067\u5207\u308a\u6368\u3066\u9664\u7b97 -> \u7d50\u679c\u306f\u6574\u6570\n3 // 2\n```\n\n\n\n\n    1\n\n\n\n\n```python\n# \u6574\u6570\u3068\u6574\u6570\u3067\u5207\u308a\u6368\u3066\u9664\u7b97 -> \u7d50\u679c\u306f\u6574\u6570\n4 // 2\n```\n\n\n\n\n    2\n\n\n\n\u6574\u6570\u3084\u5b9f\u6570\u3068\u6587\u5b57\u5217\u306e\u6f14\u7b97\u306f\u57fa\u672c\u7684\u306b\u30a8\u30e9\u30fc\u306b\u306a\u308b\u3002\n\n\n```python\n# a + c #=> TypeError: unsupported operand type(s) for +: 'int' and 'str'\n```\n\n\n```python\n# str \u3068 int \u3067\u4e57\u7b97\nc = 'Chainer'\nc * 3\n```\n\n\n\n\n    'ChainerChainerChainer'\n\n\n\n\u4e0a\u306e\u30b3\u30fc\u30c9\u306f\u3001`c` \u3068\u8a00\u3046\u6587\u5b57\u5217\u3092 `3` \u56de\u7e70\u308a\u8fd4\u3059\u3001\u3068\u8a00\u3046\u610f\u5473\u306b\u306a\u308b\u3002\n\n`str` \u540c\u58eb\u306f\u8db3\u3057\u7b97\u3092\u884c\u3046\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\n```python\nname1 = 'Chainer'\nname2 = '\u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb'\n\nname1 + name2\n```\n\n\n\n\n    'Chainer\u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb'\n\n\n\n\u6574\u6570\u3068\u6587\u5b57\u5217\u3092\u9023\u7d50\u3057\u305f\u3044\u3053\u3068\u3082\u3042\u308b\u3002  \n\n\u4f8b\u3048\u3070\u3001`1` \u3068\u8a00\u3046\u6574\u6570\u306b\u3001 `'\u756a\u76ee'` \u3068\u8a00\u3046\u6587\u5b57\u5217\u3092\u8db3\u3057\u3066 `'1\u756a\u76ee'` \u3068\u8a00\u3046\u6587\u5b57\u5217\u3092\u4f5c\u308a\u305f\u3044\u3088\u3046\u306a\u5834\u5408\u306b\u306f\u3001\u578b\u3092\u5909\u63db\u3059\u308b**\u30ad\u30e3\u30b9\u30c8 (cast)** \u3068\u8a00\u3046\u64cd\u4f5c\u3092\u3059\u308b\u5fc5\u8981\u304c\u3042\u308b\u3002\n\n\u4f55\u304b\u3092 `int` \u306b\u30ad\u30e3\u30b9\u30c8\u3057\u305f\u3044\u5834\u5408\u306f `int()` \u3068\u8a00\u3046\u7d44\u307f\u8fbc\u307f\u95a2\u6570\u3092\u4f7f\u3044\u3001\n\n`str` \u306b\u30ad\u30e3\u30b9\u30c8\u3057\u305f\u3044\u5834\u5408\u306f `str()` \u3068\u8a00\u3046\u7d44\u307f\u8fbc\u307f\u95a2\u6570\u3092\u4f7f\u3046\u3002\n\n\n```python\ntype(str(1))\n```\n\n\n\n\n    str\n\n\n\n\n```python\nstr(1) + '\u756a\u76ee'\n```\n\n\n\n\n    '1\u756a\u76ee'\n\n\n\nPython \u306b\u306f\u3001\u4ed6\u306b\u3082\u5e7e\u3064\u304b\u306e\u7b97\u8853\u6f14\u7b97\u5b50\u304c\u7528\u610f\u3055\u308c\u3066\u3044\u308b\u3002\n\n| \u6f14\u7b97 | \u8a18\u53f7 |\n|------|------|\n| \u7d2f\u4e57 | `**` |\n|  \u5270\u4f59\u3000 | `%` |\n\n\n\n```python\n# \u7d2f\u4e57\n2 ** 3\n```\n\n\n\n\n    8\n\n\n\n`%` \u3092\u4f7f\u3063\u3066\u3001`9` \u3092 `2` \u3067\u5272\u3063\u305f\u4f59\u308a\u3092\u8a08\u7b97\u3057\u3066\u307f\u308b\u3002\n\n\n```python\n# \u5270\u4f59\n9 % 2\n```\n\n\n\n\n    1\n\n\n\n\u6bd4\u8f03\u6f14\u7b97\u5b50\u306f\u30012 \u3064\u306e\u5024\u306e\u6bd4\u8f03\u3092\u884c\u3046\u305f\u3081\u306e\u6f14\u7b97\u5b50\u3067\u3042\u308b\u3002\n\n| \u6f14\u7b97 | \u8a18\u53f7 |\n|------|------|\n| \u5c0f\u306a\u308a | `<` |\n| \u5927\u306a\u308a | `>` |\n| \u4ee5\u4e0b | `<=` |\n| \u4ee5\u4e0a | `>=` |\n| \u7b49\u3057\u3044 | `==` |\n| \u7b49\u3057\u304f\u306a\u3044 | `!=` |\n\n\n\u30a8\u30b9\u30b1\u30fc\u30d7\u30b7\u30fc\u30b1\u30f3\u30b9\n\n\n```python\nprint('Hello\\nWorld')\n```\n\n    Hello\n    World\n\n\n\n```python\nprint('Hello\\tWorld')\n```\n\n    Hello\tWorld\n\n\n**\u6587\u5b57\u5217\u30e1\u30bd\u30c3\u30c9**\n\n`str` \u578b\u306e\u5909\u6570\u306b\u306f\u3001\u3044\u304f\u3064\u304b\u4fbf\u5229\u306a\u6a5f\u80fd\u304c\u3064\u3044\u3066\u3044\u308b\u3002\n\n\u4f8b\u3048\u3070\u3001\u305d\u306e\u5909\u6570\u304c\u6301\u3064\u5168\u3066\u306e\u6587\u5b57\u3092\u5c0f\u6587\u5b57\u3084\u5927\u6587\u5b57\u306b\u5909\u63db\u3059\u308b `lower()` \u3084 `upper()` \u3068\u3044\u3063\u305f\u6a5f\u80fd\u304c\u3042\u308b\u3002\n\n\u578b\u304c\u6301\u3063\u3066\u3044\u308b\u95a2\u6570\u3092**\u30e1\u30bd\u30c3\u30c9 (method)** \u3068\u547c\u3076\u3002\n\n\n\n```python\nname = 'Chainer'\nname\n```\n\n\n\n\n    'Chainer'\n\n\n\n\n```python\n# \u3059\u3079\u3066\u3092\u5c0f\u6587\u5b57\u306b\u5909\u63db\nname.lower()\n```\n\n\n\n\n    'chainer'\n\n\n\n\n```python\n# \u3059\u3079\u3066\u3092\u5927\u6587\u5b57\u306b\u5909\u63db\nname.upper()\n```\n\n\n\n\n    'CHAINER'\n\n\n\n\u6587\u5b57\u5217\u30e1\u30bd\u30c3\u30c9\u306e\u4e00\u3064\u306b\u3001 `format()` \u304c\u3042\u308b\u3002\n\n\u3053\u308c\u306f\u3001\u3042\u308b\u6587\u5b57\u5217\u306e\u4e00\u90e8\u5206\u306b\u3001\u3042\u3068\u304b\u3089\u5225\u306a\u6587\u5b57\u5217\u3092\u57cb\u3081\u8fbc\u3080\u305f\u3081\u306b\u4f7f\u7528\u3059\u308b\u3002\n\n\u5bfe\u8c61\u306e\u6587\u5b57\u5217\u306b\u306f `{}` \u3067\u4e88\u3081\u5024\u3092\u57cb\u3081\u8fbc\u307f\u305f\u3044\u5834\u6240\u3092\u6307\u5b9a\u3057\u3066\u304a\u304f\u3002\n\n\n```python\nname = 'Chainer'\n\n'{} \u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb\u3078\u3088\u3046\u3053\u305d'.format(name)\n```\n\n\n\n\n    'Chainer \u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb\u3078\u3088\u3046\u3053\u305d'\n\n\n\n\n```python\nname1 = 'Chainer'\nname2 = '\u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb'\n\n'{} {}\u3078\u3088\u3046\u3053\u305d'.format(name1, name2)\n```\n\n\n\n\n    'Chainer \u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb\u3078\u3088\u3046\u3053\u305d'\n\n\n\n`format()` \u30e1\u30bd\u30c3\u30c9\u3092\u7528\u3044\u308b\u3068 `int` \u578b \u3084 `float` \u578b\u306e\u5909\u6570\u3092\u3001`str` \u578b\u3078\u660e\u793a\u7684\u306b\u30ad\u30e3\u30b9\u30c8\u3059\u308b\u3053\u3068\u306a\u304f\u6587\u5b57\u5217\u306b\u57cb\u3081\u8fbc\u3080\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\n```python\nversion = 3.7\n\n'Python {}'.format(version)\n```\n\n\n\n\n    'Python 3.7'\n\n\n\n**\u6d6e\u52d5\u5c0f\u6570\u70b9\u6570\u304c\u3082\u3064\u30e1\u30bd\u30c3\u30c9**\n\n`int` \u578b\u306e\u5909\u6570\u3084\u3001`float` \u578b\u306e\u5909\u6570\u306b\u3082\u3001\u305d\u306e\u578b\u306e\u7279\u5fb4\u306b\u5408\u308f\u305b\u305f\u6a5f\u80fd\u304c\u3001\u30e1\u30bd\u30c3\u30c9\u3068\u3057\u3066\u63d0\u4f9b\u3055\u308c\u3066\u3044\u308b\u3002\n\n\u4f8b\u3048\u3070\u3001`float` \u578b\u306e\u5909\u6570\u306b\u306f\u3001`as_integer_ratio()` \u3068\u8a00\u3046\u30e1\u30bd\u30c3\u30c9\u304c\u3042\u308a\u3001\u6bd4\u304c\u305d\u306e\u6d6e\u52d5\u5c0f\u6570\u70b9\u6570\u306e\u5024\u3068\u306a\u308b\u3088\u3046\u306a\u6574\u6570\u306e\u7d44\u3092\u8fd4\u3059\u3002\n\n\u4f8b\u3048\u3070\u30010.5 \u3068\u8a00\u3046\u5024\u306f\u3001\u5206\u6570\u3067\u8868\u3059\u3068 $\\frac{1}{2}$ \u3067\u3042\u308b\u3002\n\u3053\u308c\u306f\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u3057\u3066\u8abf\u3079\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\n```python\n0.5.as_integer_ratio()\n```\n\n\n\n\n    (1, 2)\n\n\n\n0.25 \u3067\u3042\u308c\u3070\u3001$\\frac{1}{4}$ \u3068\u306a\u308b\u3002\n\n\n```python\n0.25.as_integer_ratio()\n```\n\n\n\n\n    (1, 4)\n\n\n\n\n```python\ntype(0.25.as_integer_ratio())\n```\n\n\n\n\n    tuple\n\n\n\n**\u8907\u5408\u30c7\u30fc\u30bf\u578b**\n\n\u4ee5\u4e0b\u306e 3\u3064\u306e\u8907\u5408\u30c7\u30fc\u30bf\u578b\u304c\u3042\u308b\u3002\n\n- \u30ea\u30b9\u30c8 (list)\n- \u30bf\u30d7\u30eb (tuple)\n- \u8f9e\u66f8 (dictionary)\n\n**\u30ea\u30b9\u30c8**\n\n\u8907\u6570\u306e\u5909\u6570\u3092 `,` \uff08\u30ab\u30f3\u30de\uff09\u533a\u5207\u308a\u3067\u4e26\u3079\u3001\u305d\u308c\u3089\u306e\u5168\u4f53\u3092 `[ ]` \u3067\u56f2\u3093\u3060\u3082\u306e\u3092 **\u30ea\u30b9\u30c8 (list)** \u3068\u8a00\u3046\u3002\n\u30ea\u30b9\u30c8\u306b\u542b\u307e\u308c\u308b\u5024\u3092**\u8981\u7d20**\u3068\u547c\u3073\u3001\u6574\u6570\u306e**\u30a4\u30f3\u30c7\u30c3\u30af\u30b9** \uff08\u8981\u7d20\u756a\u53f7\uff09\u3092\u4f7f\u3063\u3066\u30a2\u30af\u30bb\u30b9\u3059\u308b\u3002\n\n\n```python\n# \u30ea\u30b9\u30c8\u578b\u306e\u5909\u6570\u3092\u5b9a\u7fa9\nnumbers = [4, 5, 6, 7]\n\n# \u5024\u306e\u78ba\u8a8d\nprint(numbers)\n```\n\n    [4, 5, 6, 7]\n\n\n\n```python\n# \u578b\u306e\u78ba\u8a8d\ntype(numbers)\n```\n\n\n\n\n    list\n\n\n\n`numbers` \u306b\u306f 4 \u3064\u306e\u6570\u5024\u304c\u5165\u3063\u3066\u304a\u308a\u3001**\u8981\u7d20\u6570** \u306f 4 \u3067\u3042\u308b\u3002\n\u30ea\u30b9\u30c8\u306e\u8981\u7d20\u6570\u306f\u3001\u30ea\u30b9\u30c8\u306e**\u9577\u3055 (length)** \u3068\u3082\u547c\u3070\u308c\u3001\u7d44\u307f\u8fbc\u307f\u95a2\u6570\u306e `len()` \u3092\u7528\u3044\u3066\u53d6\u5f97\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\n\n\n\n```python\n# \u8981\u7d20\u6570\u306e\u78ba\u8a8d\nnumbers = [4, 5, 6, 7]\nprint(len(numbers))\nnumbers.append(3)\nprint(len(numbers))\n```\n\n    4\n    5\n\n\n\u4e0a\u306e\u30b3\u30fc\u30c9\u3067 len() \u3068 append() \u306e\u4f7f\u3044\u65b9\u304c\u9055\u3046\u3002 len \u306f\u7d44\u307f\u8fbc\u307f\u95a2\u6570\u3067\u3001append \u306f list \u306e\u30e1\u30bd\u30c3\u30c9\u3060\u3068\u3088\u304f\u8aac\u660e\u3055\u308c\u308b\u304c\u3001\u8a00\u8449\u306e\u4f7f\u3044\u65b9\u304c\u306a\u3093\u3068\u306a\u304f\u5909\u3058\u3083\u306a\u3044\u304b\u3002 \u305d\u308c\u3067\u306f len \u304c\u95a2\u6570\u3067 append \u304c\u95a2\u6570\u3067\u306f\u306a\u3044\u3088\u3046\u306b\u8aad\u3081\u3066\u3057\u307e\u3046\u3002 \u30e1\u30bd\u30c3\u30c9\u306f\u578b(\u30af\u30e9\u30b9)\u304c\u6301\u3063\u3066\u3044\u308b\u95a2\u6570\u3067\u3001\u95a2\u6570\u3068\u8a00\u3046\u610f\u5473\u3067\u306f\u540c\u3058\u3067\u3042\u308b\u3002\n\n`dir(numbers)`\n\n\u3068\u3059\u308b\u3068\u30ea\u30b9\u30c8\u306e\u6301\u3063\u3066\u3044\u308b\u30e1\u30bd\u30c3\u30c9(\u95a2\u6570)\u304c\u308f\u304b\u3063\u3066\u305d\u306e\u4e2d\u306b `__len__` \u3068\u8a00\u3046\u306e\u304c\u3042\u308b\u306e\u3067\u3001\u6b21\u306e\u3088\u3046\u306b\u4f7f\u3063\u3066\u307f\u308b\u3068\u4f7f\u3048\u308b\u3002  \n\n\u6b74\u53f2\u7684\u306a\u5224\u65ad\u304b\u3082\u3057\u308c\u306a\u3044\u3002\n\n\n\n```python\nnumbers.__len__()\n```\n\n\n\n\n    5\n\n\n\n`dir()` \u3068\u3059\u308b\u3068\u51fa\u3066\u304f\u308b\u4e00\u89a7\u306b `__builtin__` \u3068\u8a00\u3046\u306e\u304c\u3042\u308b\u306e\u3067\u8abf\u3079\u3066\u307f\u308b\u3002\n\n\n```python\n# dir(__builtin__) #=? \u7d50\u69cb\u306a\u6570\u306e\u7d44\u307f\u8fbc\u307f\u95a2\u6570\u304c\u3042\u308b\u306e\u304c\u308f\u304b\u308b\n```\n\n\n```python\n# \u5b9f\u9a13\nprint(abs(-5))\nprint((-5).__abs__())\n```\n\n    5\n    5\n\n\n\u30ea\u30b9\u30c8\u306e\u5404\u8981\u7d20\u3078\u30a2\u30af\u30bb\u30b9\u3059\u308b\u65b9\u6cd5\u306f\u3044\u304f\u3064\u304b\u3042\u308b\u3002\n\u6700\u3082\u7c21\u5358\u306a\u65b9\u6cd5\u306f bracket `[]` \u3092\u4f7f\u3063\u3066\u30a2\u30af\u30bb\u30b9\u3057\u305f\u3044\u8981\u7d20\u756a\u53f7\u3092\u6307\u5b9a\u3057\u3066\u3001\u30ea\u30b9\u30c8\u304b\u3089\u5024\u3092\u53d6\u308a\u51fa\u3057\u305f\u308a\u3001\u305d\u306e\u4f4d\u7f6e\u306e\u5024\u3092\u66f8\u304d\u63db\u3048\u305f\u308a\u3059\u308b\u65b9\u6cd5\u3067\u3042\u308b\u3002\n\n\u5148\u982d\u306e\u8981\u7d20\u306e\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u756a\u53f7\u306f `0` \u3067\u3042\u308b\u3002\n\n\n\n```python\n# \u5148\u982d\u306e\u8981\u7d20\u306b\u30a2\u30af\u30bb\u30b9\nnumbers[0]\n```\n\n\n\n\n    4\n\n\n\n\n```python\n# \u5148\u982d\u304b\u30893\u756a\u76ee\u306e\u8981\u7d20\u306b\u30a2\u30af\u30bb\u30b9\nnumbers[2]\n```\n\n\n\n\n    6\n\n\n\n\n```python\n# 2 \u756a\u76ee\u306e\u8981\u7d20\u3092\u66f8\u304d\u63db\u3048\nnumbers[1] = 10\n```\n\n\n```python\n# \u5024\u306e\u78ba\u8a8d\nnumbers\n```\n\n\n\n\n    [4, 10, 6, 7, 3]\n\n\n\n\u307e\u305f\u3001\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u306b\u8ca0\u306e\u5024\u3092\u6307\u5b9a\u3059\u308b\u3068\u3001\u672b\u5c3e\u304b\u3089\u306e\u4f4d\u7f6e\u3068\u306a\u308b\u3002\n\u8981\u7d20\u756a\u53f7 `-1` \u3067\u6700\u5f8c\u306e\u8981\u7d20\u3092\u53c2\u7167\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\n```python\n# \u672b\u5c3e\u306e\u8981\u7d20\u306b\u30a2\u30af\u30bb\u30b9\nnumbers[-1]\n```\n\n\n\n\n    3\n\n\n\n\n```python\n# \u672b\u5c3e\u304b\u30893\u756a\u76ee\u306e\u8981\u7d20\u306b\u30a2\u30af\u30bb\u30b9\nnumbers[-3]\n```\n\n\n\n\n    6\n\n\n\n\u6b21\u306b\u3001\u30ea\u30b9\u30c8\u304b\u3089\u4e00\u5ea6\u306b\u8907\u6570\u306e\u8981\u7d20\u3092\u53d6\u308a\u51fa\u3059\u64cd\u4f5c\u3067\u3042\u308b**\u30b9\u30e9\u30a4\u30b9 (slice)** \u3092\u7d39\u4ecb\u3059\u308b\u3002\n`\u958b\u59cb\u4f4d\u7f6e:\u7d42\u4e86\u4f4d\u7f6e` \u306e\u3088\u3046\u306b\u30b3\u30ed\u30f3 `:` \u3092\u7528\u3044\u3066\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u3092\u7bc4\u56f2\u6307\u5b9a\u3057\u3001\u8907\u6570\u306e\u90e8\u5206\u8981\u7d20\u306b\u30a2\u30af\u30bb\u30b9\u3059\u308b\u3002\n\u3053\u306e\u30b9\u30e9\u30a4\u30b9\u306e\u51e6\u7406\u306f\u3001\u3053\u306e\u5f8c\u306e\u7ae0\u3067\u3082\u591a\u7528\u3059\u308b\u305f\u3081\u3001\u6163\u308c\u3066\u304a\u304f\u3002\n\n\u4f8b\u3048\u3070\u3001\u5148\u982d\u304b\u3089 2 \u3064\u306e\u8981\u7d20\u3092\u53d6\u308a\u51fa\u3057\u305f\u3044\u5834\u5408\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u6307\u5b9a\u3059\u308b\u3002\n\n\n```python\nnumbers[0:2]\n```\n\n\n\n\n    [4, 10]\n\n\n\n\n```python\nnumbers\n```\n\n\n\n\n    [4, 10, 6, 7, 3]\n\n\n\n\n```python\nslice(0,2)\n```\n\n\n\n\n    slice(0, 2, None)\n\n\n\n\n```python\nnumbers[slice(0,2)]\n```\n\n\n\n\n    [4, 10]\n\n\n\n`\u958b\u59cb\u4f4d\u7f6e:\u7d42\u4e86\u4f4d\u7f6e` \u3068\u6307\u5b9a\u3059\u308b\u3053\u3068\u3067\u3001\u958b\u59cb\u4f4d\u7f6e\u304b\u3089**\u7d42\u4e86\u4f4d\u7f6e\u306e\u3072\u3068\u3064\u624b\u524d**\u307e\u3067\u306e\u8981\u7d20\u3092\u62bd\u51fa\u3059\u308b\u3002 \n\u7d42\u4e86\u4f4d\u7f6e\u306b\u6307\u5b9a\u3057\u305f\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u306e\u5024\u306f\u542b\u307e\u308c\u306a\u3044\u3053\u3068\u306b\u6ce8\u610f\u3059\u308b\u3002\n\n\u307e\u305f\u3001\u6307\u5b9a\u3059\u308b\u958b\u59cb\u756a\u53f7\u304c `0` \u3067\u3042\u308b\u5834\u5408\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306a\u7565\u8a18\u304c\u3088\u304f\u7528\u3044\u3089\u308c\u308b\u3002\n\n\n```python\nnumbers[:2]\n```\n\n\n\n\n    [4, 10]\n\n\n\n\u3053\u306e\u3088\u3046\u306b\u3001\u5148\u982d\u306e\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u306f\u7701\u7565\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\u3053\u306e\u3088\u3046\u306a\u8a18\u6cd5\u3092\u4f7f\u3046\u5834\u5408\u306f\u3001\u7d42\u4e86\u4f4d\u7f6e\u3092\u793a\u3059\u6570\u5b57\u3092**\u53d6\u308a\u51fa\u3057\u305f\u3044\u8981\u7d20\u306e\u500b\u6570**\u3068\u6349\u3048\u3066\u3001**\u5148\u982d\u304b\u3089 2 \u3064\u3092\u53d6\u308a\u51fa\u3059**\u64cd\u4f5c\u3060\u3068\u8003\u3048\u308b\u3068\u5206\u304b\u308a\u3084\u3059\u304f\u306a\u308b\u3002\n\n\u540c\u69d8\u306b\u3001\u3042\u308b\u4f4d\u7f6e\u304b\u3089\u30ea\u30b9\u30c8\u306e\u672b\u5c3e\u307e\u3067\u3092\u53d6\u308a\u51fa\u3059\u5834\u5408\u3082\u3001\u7d42\u4e86\u4f4d\u7f6e\u306e\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u3092\u7701\u7565\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\u4f8b\u3048\u3070\u30012 \u500b\u76ee\u306e\u8981\u7d20\u304b\u3089\u6700\u5f8c\u307e\u3067\u3092\u53d6\u308a\u51fa\u3059\u306b\u306f\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u3059\u308b\u3002\n\n\n```python\nnumbers[1:]\n```\n\n\n\n\n    [10, 6, 7, 3]\n\n\n\n\u3053\u306e\u5834\u5408\u306f\u3001\u53d6\u308a\u51fa\u3055\u308c\u308b\u8981\u7d20\u306e\u500b\u6570\u306f `len(numbers) - 1` \u500b\u3068\u306a\u308b\u3053\u3068\u306b\u6ce8\u610f\u3059\u308b\u3002\n\n\u4ee5\u4e0a\u304b\u3089\u3001`numbers[:2]` \u3068 `numbers[2:]` \u306f\u3001\u3061\u3087\u3046\u3069 2 \u500b\u76ee\u306e\u8981\u7d20\u3092\u5883\u306b `numbers` \u306e\u8981\u7d20\u3092 2 \u5206\u5272\u3057\u305f\u524d\u534a\u90e8\u5206\u3068\u5f8c\u534a\u90e8\u5206\u306b\u306a\u3063\u3066\u3044\u308b\u3002\n\u3053\u3053\u3067\u3001\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u304c 2 \u306e\u8981\u7d20\u81ea\u4f53\u306f**\u5f8c\u534a\u90e8\u306b\u542b\u307e\u308c\u308b**\u3068\u8a00\u3046\u3053\u3068\u306b\u6ce8\u610f\u3059\u308b\u3002\n\n\u307e\u305f\u3001\u958b\u59cb\u4f4d\u7f6e\u3082\u7d42\u4e86\u4f4d\u7f6e\u3082\u7701\u7565\u3057\u305f\u5834\u5408\u306f\u3001\u3059\u3079\u3066\u306e\u8981\u7d20\u304c\u9078\u629e\u3055\u308c\u308b\u3002\n\n\n```python\nnumbers[:]\n```\n\n\n\n\n    [4, 10, 6, 7, 3]\n\n\n\n\u73fe\u72b6\u3067\u306f\u3001`numbers[:]` \u3068 `numbers` \u306e\u7d50\u679c\u304c\u540c\u3058\u3067\u3042\u308b\u305f\u3081\u3001\u3069\u306e\u3088\u3046\u306b\u4f7f\u7528\u3059\u308b\u304b\u7591\u554f\u306b\u601d\u308f\u308c\u308b\u304b\u3082\u77e5\u308c\u306a\u3044\u3002\n\u3057\u304b\u3057\u3001\u5f8c\u306e\u7ae0\u3067\u306f NumPy \u3068\u8a00\u3046\u30e9\u30a4\u30d6\u30e9\u30ea\u3092\u7528\u3044\u3066\u30ea\u30b9\u30c8\u306e\u4e2d\u306b\u30ea\u30b9\u30c8\u304c\u5165\u3063\u305f\u3088\u3046\u306a**\u591a\u6b21\u5143\u914d\u5217 (multidimensional array)** \u3092\u6271\u3063\u3066\u3044\u304f\u3002\n\n\u305d\u3057\u3066\u591a\u6b21\u5143\u914d\u5217\u3092\u7528\u3044\u3066\u884c\u5217\u3092\u8868\u3059\u5834\u5408\u306b\u306f\u3001`0 \u5217\u76ee\u306e\u3059\u3079\u3066\u306e\u5024`\u3092\u62bd\u51fa\u3059\u308b\u305f\u3081\u306b `[:, 0]` \u306e\u3088\u3046\u306a\u8a18\u6cd5\u3092\u7528\u3044\u308b\u30b1\u30fc\u30b9\u304c\u767b\u5834\u3059\u308b\u3002\n\u3053\u308c\u306f Python \u6a19\u6e96\u306e\u6a5f\u80fd\u3067\u306f\u306a\u3044\u304c\u3001Python \u6a19\u6e96\u306e\u30b9\u30e9\u30a4\u30b9\u8868\u8a18\u3092\u62e1\u5f35\u3057\u305f\u3082\u306e\u306b\u306a\u3063\u3066\u3044\u308b\u3002\n\n\n```python\nx = [[1,2],[3,4]]\nx[:][0]\n```\n\n\n\n\n    [1, 2]\n\n\n\n\u30ea\u30b9\u30c8\u306f\u6570\u5024\u4ee5\u5916\u306b\u3001\u6587\u5b57\u5217\u3092\u6271\u3046\u3053\u3068\u3082\u3067\u304d\u3001\u307e\u305f\u8907\u6570\u306e\u578b\u3092\u540c\u4e00\u306e\u30ea\u30b9\u30c8\u5185\u306b\u6df7\u5728\u3055\u305b\u308b\u3053\u3068\u3082\u3067\u304d\u308b\u3002\n\n\n```python\n# \u6587\u5b57\u5217\u3092\u683c\u7d0d\u3057\u305f\u30ea\u30b9\u30c8\narray = ['hello', 'world']\narray\n```\n\n\n\n\n    ['hello', 'world']\n\n\n\n\n```python\nlen('hello')\n```\n\n\n\n\n    5\n\n\n\n\n```python\n# \u8907\u6570\u306e\u578b\u304c\u6df7\u5728\u3057\u305f\u30ea\u30b9\u30c8\narray = [1, 1.2, 'Chainer']\narray\n```\n\n\n\n\n    [1, 1.2, 'Chainer']\n\n\n\n\u30ea\u30b9\u30c8\u306b\u30ea\u30b9\u30c8\u3092\u4ee3\u5165\u3059\u308b\u3053\u3068\u3082\u3067\u304d\u308b\u3002\n\u307e\u305f\u3001Python \u6a19\u6e96\u306e\u30ea\u30b9\u30c8\u3067\u306f\u5165\u308c\u5b50\u306b\u306a\u3063\u305f\u30ea\u30b9\u30c8\u5185\u306e\u8981\u7d20\u6570\u304c\u3070\u3089\u3070\u3089\u3067\u3082\u554f\u984c\u306a\u3044\u3002\n\n\n```python\narray = [[1, 1.2, 'Chainer', True], [3.2, 'Tutorial']]\narray\n```\n\n\n\n\n    [[1, 1.2, 'Chainer', True], [3.2, 'Tutorial']]\n\n\n\n\u30ea\u30b9\u30c8\u3092\u4f7f\u3046\u969b\u306b\u983b\u51fa\u3059\u308b\u64cd\u4f5c\u3068\u3057\u3066\u3001**\u30ea\u30b9\u30c8\u3078\u306e\u5024\u306e\u8ffd\u52a0**\u304c\u3042\u308b\u3002\n\u30ea\u30b9\u30c8\u578b\u306b\u306f `append()` \u3068\u8a00\u3046\u30e1\u30bd\u30c3\u30c9\u304c\u5b9a\u7fa9\u3055\u308c\u3066\u304a\u308a\u3001\u3053\u308c\u3092\u7528\u3044\u3066\u30ea\u30b9\u30c8\u306e\u672b\u5c3e\u306b\u65b0\u3057\u3044\u5024\u3092\u8ffd\u52a0\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\u4e0a\u8a18\u306e `array` \u306b\u5024\u3092\u8ffd\u52a0\u3057\u3066\u307f\u308b\u3002\n\n\n```python\n# \u672b\u5c3e\u306b 2.5 \u3092\u8ffd\u52a0\narray.append(2.5)\n```\n\n\n```python\n# \u5024\u306e\u78ba\u8a8d\narray\n```\n\n\n\n\n    [[1, 1.2, 'Chainer', True], [3.2, 'Tutorial'], 2.5]\n\n\n\n\u307e\u305f\u3001\u4eca\u5f8c\u983b\u51fa\u3059\u308b\u51e6\u7406\u3068\u3057\u3066\u3001**\u7a7a\u306e\u30ea\u30b9\u30c8**\u3092\u5b9a\u7fa9\u3057\u3066\u304a\u304d\u3001\u305d\u3053\u306b\u5f8c\u6bb5\u306e\u51e6\u7406\u306e\u4e2d\u3067\u9069\u5b9c\u65b0\u305f\u306a\u8981\u7d20\u3092\u8ffd\u52a0\u3057\u3066\u3044\u304f\u3068\u8a00\u3046\u4f7f\u3044\u65b9\u304c\u3042\u308b\u3002\n\n\n```python\n# \u7a7a\u306e\u30ea\u30b9\u30c8\u3092\u5b9a\u7fa9\narray = []\n\n# \u7a7a\u306e\u30ea\u30b9\u30c8\u306b\u8981\u7d20\u3092\u8ffd\u52a0\narray.append('Chainer')\narray.append('\u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb')\n\narray\n```\n\n\n\n\n    ['Chainer', '\u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb']\n\n\n\n**\u30bf\u30d7\u30eb**\n\n**\u30bf\u30d7\u30eb (tuple)** \u306f\u30ea\u30b9\u30c8\u3068\u540c\u69d8\u306b\u8907\u6570\u306e\u8981\u7d20\u3092\u307e\u3068\u3081\u305f\u578b\u3060\u304c\u3001\u30ea\u30b9\u30c8\u3068\u306f\u7570\u306a\u308b\u70b9\u3068\u3057\u3066\u3001\u5b9a\u7fa9\u3057\u305f\u5f8c\u306b**\u4e2d\u306e\u8981\u7d20\u3092\u5909\u66f4\u3067\u304d\u306a\u3044**\u3068\u8a00\u3046\u6027\u8cea\u3092\u6301\u3064\u3002\n\n\u30bf\u30d7\u30eb\u306e\u5b9a\u7fa9\u306b\u306f\u4e38\u62ec\u5f27 parenthesis `( )`\u3092\u7528\u3044\u308b\u3002\n\n\n```python\n# \u30bf\u30d7\u30eb\u3092\u5b9a\u7fa9\narray = (4, 5, 6, 7)\narray\n```\n\n\n\n\n    (4, 5, 6, 7)\n\n\n\n\n```python\n# \u578b\u306e\u78ba\u8a8d\ntype(array)\n```\n\n\n\n\n    tuple\n\n\n\n\u30bf\u30d7\u30eb\u306e\u5b9a\u7fa9\u3059\u308b\u969b\u306b `( )` \u3092\u4f7f\u7528\u3057\u305f\u305f\u3081\u3001\u8981\u7d20\u3078\u306e\u30a2\u30af\u30bb\u30b9\u3082 `( )` \u3092\u4f7f\u3046\u3088\u3046\u306b\u611f\u3058\u308b\u304b\u3082\u3057\u308c\u306a\u3044\u304c\u3001\u5b9f\u969b\u306b\u306f\u30ea\u30b9\u30c8\u3068\u540c\u69d8 `[ ]` \u3092\u4f7f\u7528\u3059\u308b\u3002\n\n\n```python\n# \u5148\u982d\u306e\u8981\u7d20\u3078\u30a2\u30af\u30bb\u30b9\narray[0]\n```\n\n\n\n\n    4\n\n\n\n\n```python\n# \u30ea\u30b9\u30c8\u3068\u540c\u69d8\u3001\u30b9\u30e9\u30a4\u30b9\u3082\u4f7f\u7528\u53ef\u80fd\narray[:3]\n```\n\n\n\n\n    (4, 5, 6)\n\n\n\n\u5148\u8ff0\u306e\u901a\u308a\u3001\u30bf\u30d7\u30eb\u306f\u5404\u8981\u7d20\u306e\u5024\u3092\u5909\u66f4\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u306a\u3044\u3002\n\u3053\u306e\u6027\u8cea\u306f\u3001\u5b9a\u6570\u9805\u306a\u3069\u30d7\u30ed\u30b0\u30e9\u30e0\u306e\u9014\u4e2d\u3067\u66f8\u304d\u63db\u308f\u3063\u3066\u3057\u307e\u3046\u3053\u3068\u304c\u671b\u307e\u3057\u304f\u306a\u3044\u3082\u306e\u3092\u307e\u3068\u3081\u3066\u6271\u3046\u306e\u306b\u4fbf\u5229\u3067\u3042\u308b\u3002\n\n\u5b9f\u969b\u306b\u3001\u30bf\u30d7\u30eb\u306e\u8981\u7d20\u306b\u5024\u306e\u66f8\u304d\u63db\u3048\u3092\u884c\u3046\u3068\u30a8\u30e9\u30fc\u304c\u767a\u751f\u3059\u308b\u3002\n\n\n```python\n# array[0] = 10 #=> TypeError: 'tuple' object does not support item assignment\n```\n\n`tuple` \u306e\u3088\u3046\u306b\u4e2d\u8eab\u304c\u5909\u66f4\u3067\u304d\u306a\u3044\u6027\u8cea\u306e\u3053\u3068\u3092**\u30a4\u30df\u30e5\u30fc\u30bf\u30d6\u30eb (immutable)**\u3067\u3042\u308b\u3068\u8a00\u3046\u3002\u53cd\u5bfe\u306b\u3001`list` \u306e\u3088\u3046\u306b\u4e2d\u8eab\u304c\u5909\u66f4\u3067\u304d\u308b\u6027\u8cea\u306e\u3053\u3068\u3092**\u30df\u30e5\u30fc\u30bf\u30d6\u30eb (mutable)**\u3067\u3042\u308b\u3068\u8a00\u3046\n\n\u30bf\u30d7\u30eb\u3082 Chainer \u3067\u30c7\u30fc\u30bf\u30bb\u30c3\u30c8\u3092\u6271\u3046\u3068\u304d\u306a\u3069\u306b\u983b\u51fa\u3059\u308b\u578b\u3067\u3042\u308b\u3002\u305d\u306e\u6027\u8cea\u3068\u53d6\u308a\u6271\u3044\u65b9\u3092\u899a\u3048\u3066\u304a\u304f\u3002\n\n**\u8f9e\u66f8**\n\n\u30ea\u30b9\u30c8\u3084\u30bf\u30d7\u30eb\u3067\u306f\u3001\u8907\u6570\u306e\u5024\u3092\u307e\u3068\u3081\u3066\u6271\u3046\u3053\u3068\u304c\u3067\u304d\u305f\u3002\n\n\u5b9a\u671f\u30c6\u30b9\u30c8\u306e\u7d50\u679c\u3092\u307e\u3068\u3081\u308b\u3053\u3068\u3092\u8003\u3048\u3066\u307f\u308b\u3002\n\n\u4f8b\u3048\u3070\u3001\u6570\u5b66 90 \u70b9\u3001\u7406\u79d1 75 \u70b9\u3001\u82f1\u8a9e 80 \u70b9\u3060\u3063\u305f\u3068\u8a00\u3046\u7d50\u679c\u3092 `scores = [90, 75, 80]` \u3068\u30ea\u30b9\u30c8\u3067\u8868\u3057\u3066\u307f\u308b\u3002\n\u3057\u304b\u3057\u3001\u3053\u308c\u3067\u306f**\u4f55\u756a\u76ee\u304c\u3069\u306e\u6559\u79d1\u306e\u70b9\u6570\u306b\u5bfe\u5fdc\u3059\u308b\u304b**\u3001\u4e00\u898b\u3057\u3066\u5206\u304b\u308a\u306b\u304f\u3044\u3002\n\nPython \u306e `dict` \u578b\u306f\u3001**\u30ad\u30fc (key)** \u3068\u305d\u308c\u306b\u5bfe\u5fdc\u3059\u308b**\u5024 (value)** \u3092\u30bb\u30c3\u30c8\u306b\u3057\u3066\u683c\u7d0d\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u578b\u3067\u3042\u308a\u3001\u3053\u306e\u3088\u3046\u306a\u3068\u304d\u306b\u4fbf\u5229\u3067\u3042\u308b\u3002\n\n\u30ea\u30b9\u30c8\u3084\u30bf\u30d7\u30eb\u3067\u306f\u3001\u5404\u8981\u7d20\u306b\u30a2\u30af\u30bb\u30b9\u3059\u308b\u969b\u306b\u6574\u6570\u306e\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u3092\u7528\u3044\u3066\u3044\u305f\u304c\u3001\u8f9e\u66f8\u3067\u306f\u30ad\u30fc\u3067\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u5316\u3055\u308c\u3066\u3044\u308b\u305f\u3081\u3001\u6574\u6570\u3084\u6587\u5b57\u5217\u306a\u3069\u3001\u8272\u3005\u306a\u3082\u306e\u3092\u4f7f\u3063\u3066\u8981\u7d20\u3092\u6307\u5b9a\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\u8f9e\u66f8\u306f brace `{}` \u3092\u7528\u3044\u3066\u5b9a\u7fa9\u3057\u3001\u8981\u7d20\u306b\u30a2\u30af\u30bb\u30b9\u3059\u308b\u969b\u306b\u306f\u3001\u30ea\u30b9\u30c8\u3084\u30bf\u30d7\u30eb\u3068\u540c\u69d8\u306b `[ ]` \u3092\u4f7f\u7528\u3057\u3001`[ ]` \u306e\u4e2d\u306b\u30ad\u30fc\u3092\u6307\u5b9a\u3057\u3066\u5bfe\u5fdc\u3059\u308b\u5024\u3092\u53d6\u308a\u51fa\u3059\u3002\n\n\n```python\n# \u8f9e\u66f8\u3092\u5b9a\u7fa9\nscores = {'Math': 90, 'Science': 75, 'English': 80 }\nscores\n```\n\n\n\n\n    {'English': 80, 'Math': 90, 'Science': 75}\n\n\n\n\n```python\n# key \u304c Math \u306e value \u306b\u30a2\u30af\u30bb\u30b9\nscores['Math'] \n```\n\n\n\n\n    90\n\n\n\n\n```python\n# key \u306b\u65e5\u672c\u8a9e\u3092\u4f7f\u7528\u3059\u308b\u3053\u3068\u3082\u53ef\u80fd\nscores = {'\u6570\u5b66': 90, '\u7406\u79d1': 75, '\u82f1\u8a9e': 80}\nscores\n```\n\n\n\n\n    {'\u6570\u5b66': 90, '\u7406\u79d1': 75, '\u82f1\u8a9e': 80}\n\n\n\n\n```python\nscores['\u6570\u5b66']\n```\n\n\n\n\n    90\n\n\n\n\u4ed6\u306e\u4eba\u304c\u5b9a\u7fa9\u3057\u305f\u8f9e\u66f8\u306b\u3001**\u3069\u306e\u3088\u3046\u306a\u30ad\u30fc\u304c\u5b58\u5728\u3059\u308b\u306e\u304b**\u3092\u8abf\u3079\u305f\u3044\u3068\u304d\u304c\u3042\u308b\u3002\n\u8f9e\u66f8\u306b\u306f\u3001\u305d\u306e\u3088\u3046\u306a\u5834\u5408\u306b\u4f7f\u3048\u308b\u4fbf\u5229\u306a\u30e1\u30bd\u30c3\u30c9\u304c\u3044\u304f\u3064\u304b\u5b58\u5728\u3059\u308b\u3002\n\n- `keys()`: \u30ad\u30fc\u306e\u30ea\u30b9\u30c8\u3092\u53d6\u5f97\u3002`dict_keys` \u3068\u8a00\u3046\u30ea\u30b9\u30c8\u3068\u6027\u8cea\u304c\u4f3c\u305f\u578b\u304c\u8fd4\u308b\n- `values()`: \u5024\u306e\u30ea\u30b9\u30c8\u3092\u53d6\u5f97\u3002`dict_values` \u3068\u8a00\u3046\u30ea\u30b9\u30c8\u3068\u6027\u8cea\u304c\u4f3c\u305f\u578b\u304c\u8fd4\u308b\n- `items()`: \u5404\u8981\u7d20\u306e `(key, value)` \u306e\u30bf\u30d7\u30eb\u304c\u4e26\u3093\u3060\u30ea\u30b9\u30c8\u3092\u53d6\u5f97\u3002`dict_items` \u3068\u8a00\u3046\u30ea\u30b9\u30c8\u3068\u6027\u8cea\u304c\u4f3c\u305f\u578b\u304c\u8fd4\u308b\n\n\n```python\n# \u30ad\u30fc\u306e\u30ea\u30b9\u30c8\nscores.keys()\n```\n\n\n\n\n    dict_keys(['\u6570\u5b66', '\u7406\u79d1', '\u82f1\u8a9e'])\n\n\n\n\n```python\n# \u5024\u306e\u30ea\u30b9\u30c8\nscores.values()\n```\n\n\n\n\n    dict_values([90, 75, 80])\n\n\n\n\n```python\n# (\u30ad\u30fc, \u5024)\u3068\u8a00\u3046\u30bf\u30d7\u30eb\u3092\u8981\u7d20\u3068\u3059\u308b\u30ea\u30b9\u30c8\nscores.items()\n```\n\n\n\n\n    dict_items([('\u6570\u5b66', 90), ('\u7406\u79d1', 75), ('\u82f1\u8a9e', 80)])\n\n\n\n`dict_keys`, `dict_values`, `dict_items` \u3068\u65b0\u3057\u3044\u578b\u304c\u767b\u5834\u3057\u305f\u304c\u3001\u3053\u308c\u306f\u8f9e\u66f8\u578b\u7279\u6709\u306e\u578b\u3067\u3042\u308a\u53b3\u5bc6\u306b\u306f\u6a19\u6e96\u306e\u30ea\u30b9\u30c8\u3068\u306f\u7570\u306a\u308b\u304c\u3001\u30ea\u30b9\u30c8\u3068\u6027\u8cea\u306e\u4f3c\u305f\u578b\u3067\u3042\u308b\u3068\u8a00\u3046\u7a0b\u5ea6\u306e\u8a8d\u8b58\u3067\u554f\u984c\u306a\u3044\u3002\n\n\u8f9e\u66f8\u306b\u8981\u7d20\u3092\u8ffd\u52a0\u3059\u308b\u5834\u5408\u306f\u3001\u65b0\u3057\u3044\u30ad\u30fc\u3092\u6307\u5b9a\u3057\u3066\u5024\u3092\u4ee3\u5165\u3059\u308b\u3002\n\n\n```python\nscores['\u56fd\u8a9e'] = 85\n```\n\n\n```python\nscores\n```\n\n\n\n\n    {'\u56fd\u8a9e': 85, '\u6570\u5b66': 90, '\u7406\u79d1': 75, '\u82f1\u8a9e': 80}\n\n\n\n\u307e\u305f\u3001\u65e2\u306b\u5b58\u5728\u3059\u308b\u30ad\u30fc\u3092\u6307\u5b9a\u3057\u305f\u5834\u5408\u306b\u306f\u3001\u5024\u304c\u4e0a\u66f8\u304d\u3055\u308c\u308b\u3002\n\n\n```python\nscores['\u6570\u5b66'] = 95\n```\n\n\n```python\nscores\n```\n\n\n\n\n    {'\u56fd\u8a9e': 85, '\u6570\u5b66': 95, '\u7406\u79d1': 75, '\u82f1\u8a9e': 80}\n\n\n\n**\u5236\u5fa1\u69cb\u6587 control structure, control flow**\n\n\u8907\u96d1\u306a\u30d7\u30ed\u30b0\u30e9\u30e0\u3092\u8a18\u8ff0\u3057\u3088\u3046\u3068\u3059\u308b\u3068\u3001\u7e70\u308a\u8fd4\u3057\u306e\u51e6\u7406\u3084\u3001\u6761\u4ef6\u306b\u3088\u3063\u3066\u52d5\u4f5c\u3092\u5909\u3048\u308b\u51e6\u7406\u304c\u5fc5\u8981\u3068\u306a\u308b\u3002\n\u3053\u308c\u3089\u306f**\u5236\u5fa1\u69cb\u6587**\u3092\u7528\u3044\u3066\u8a18\u8ff0\u3059\u308b\u3002\n\n\u3053\u3053\u3067\u306f\u6700\u3082\u57fa\u672c\u7684\u306a\u5236\u5fa1\u69cb\u6587\u3092 2 \u3064\u7d39\u4ecb\u3059\u308b\u3002\n\n- \u7e70\u308a\u8fd4\u3057 (`for`, `while`)\n- \u6761\u4ef6\u5206\u5c90 (`if`)\n\nPython \u306e\u5236\u5fa1\u69cb\u6587\u306f\u3001**\u30d8\u30c3\u30c0 (header)** \u3068 **\u30d6\u30ed\u30c3\u30af (block)** \u3068\u547c\u3070\u308c\u308b 2 \u3064\u306e\u90e8\u5206\u3067\u69cb\u6210\u3055\u308c\u3066\u3044\u308b\u3002\n\u3053\u308c\u3089\u3092\u5408\u308f\u305b\u3066 **\u8907\u5408\u6587 (compound statement)** \u3068\u547c\u3076\u3002\n\n\n```\nif \u6761\u4ef6: # \u30b3\u30ed\u30f3\u304c\u5fc5\u8981\u3002 \u30d8\u30c3\u30c0\u30fc\n    \u51e6\u7406\u30d6\u30ed\u30c3\u30af # \u30a4\u30f3\u30c7\u30f3\u30c8\u304c\u5fc5\u8981\u3002\u534a\u89d2\u30b9\u30da\u30fc\u30b94\u3064\n```\n\n\n\u4e0a\u56f3\u306b\u793a\u3059\u3088\u3046\u306b\u3001\u5236\u5fa1\u69cb\u6587\u3067\u306f\u30d8\u30c3\u30c0\u884c\u306b `for` \u6587\u3084 `if-else` \u53e5\u3092\u8a18\u8ff0\u3057\u3001\u884c\u672b\u306b `:` \u8a18\u53f7\u3092\u66f8\u304f\u3002\u6b21\u306b\u3001\u30d8\u30c3\u30c0\u884c\u306e\u6761\u4ef6\u3067\u5b9f\u884c\u3057\u305f\u3044\u4e00\u9023\u306e\u51e6\u7406\u6587\u3092\u3001\u30d6\u30ed\u30c3\u30af\u3068\u3057\u3066\u305d\u306e\u6b21\u306e\u884c\u4ee5\u964d\u306b\u8a18\u8ff0\u3057\u3066\u3044\u304f\u3002\u305d\u306e\u969b\u3001 **\u30a4\u30f3\u30c7\u30f3\u30c8 (indent)** \u3068\u547c\u3070\u308c\u308b\u7a7a\u767d\u6587\u5b57\u3092\u5148\u982d\u306b\u633f\u5165\u3059\u308b\u3053\u3068\u3067\u3001\u30d6\u30ed\u30c3\u30af\u3092\u8868\u73fe\u3059\u308b\u3002\u540c\u3058\u6570\u306e\u7a7a\u767d\u3067\u30a4\u30f3\u30c7\u30f3\u30c8\u3055\u308c\u305f\u6587\u304c\u30d6\u30ed\u30c3\u30af\u3068\u307f\u306a\u3055\u308c\u308b\u3002\n\nPython \u3067\u306f\u3001\u30a4\u30f3\u30c7\u30f3\u30c8\u3068\u3057\u3066**\u30b9\u30da\u30fc\u30b9 4 \u3064**\u3092\u7528\u3044\u308b\u3053\u3068\u304c\u63a8\u5968\u3055\u308c\u3066\u3044\u308b\u3002\n\n&nbsp;\n\n**\u7e70\u308a\u8fd4\u3057\uff08for \u6587\uff09**\n\n\u540c\u3058\u5185\u5bb9\u306e\u30e1\u30fc\u30eb\u3092\u5b9b\u540d\u3060\u3051\u500b\u5225\u306b\u5909\u3048\u3066\u30011000 \u4eba\u306b\u4e00\u6589\u9001\u4fe1\u3057\u305f\u3044\u5834\u5408\u306a\u3069\u3001\u7e70\u308a\u8fd4\u3059\u51e6\u7406\u3092\u8a18\u8ff0\u3059\u308b\u5236\u5fa1\u69cb\u6587\u3067\u3042\u308b `for` \u3092\u4f7f\u3046\u3002\n\n```\nfor \u5909\u6570\u540d in \u30a4\u30c6\u30e9\u30d6\u30eb\u30aa\u30d6\u30b8\u30a7\u30af\u30c8: \u30d8\u30c3\u30c0\u30fc\n    \u30d6\u30ed\u30c3\u30af\u51e6\u7406\n```\n\n**\u30a4\u30c6\u30e9\u30d6\u30eb\u30aa\u30d6\u30b8\u30a7\u30af\u30c8 (iterable object)** \u3068\u306f\u3001\u53cd\u5fa9\u53ef\u80fd\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u306e\u3053\u3068\u3067\u3042\u308a\u3001\u8981\u7d20\u3092\u4e00\u5ea6\u306b 1 \u3064\u305a\u3064\u8fd4\u305b\u308b\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u306e\u3053\u3068\u3092\u6307\u3059\u3002\n`range()` \u3068\u8a00\u3046\u7d44\u307f\u8fbc\u307f\u95a2\u6570\u3092\u4f7f\u3046\u3068\u3001\u5f15\u6570\u306b\u4e0e\u3048\u305f\u6574\u6570\u306e\u56de\u6570\u3060\u3051\u9806\u756a\u306b\u6574\u6570\u3092\u8fd4\u3059\u30a4\u30c6\u30e9\u30d6\u30eb\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u3092\u4f5c\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n`range(5)` \u3068\u66f8\u304f\u3068\u30010, 1, 2, 3, 4 \u3068\u8a00\u3046\u6574\u6570 5 \u3064\u3092\u9806\u756a\u306b\u8fd4\u3059\u30a4\u30c6\u30e9\u30d6\u30eb\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u306b\u306a\u308b\u3002\n\n\u3053\u306e\u30a4\u30c6\u30e9\u30d6\u30eb\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u3068\u3057\u3066\u3001\u30ea\u30b9\u30c8\u3084\u30bf\u30d7\u30eb\u3082\u6307\u5b9a\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\n```python\n# 5\u56de\u7e70\u308a\u8fd4\u3059\nfor i in range(5):\n    print(i)\n```\n\n    0\n    1\n    2\n    3\n    4\n\n\n\u4e0a\u8a18\u306e\u4f8b\u3067\u306f\u3001\u30a4\u30c6\u30e9\u30d6\u30eb\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u304c1 \u3064\u305a\u3064\u8fd4\u3059\u5024\u3092\u5909\u6570 `i` \u3067\u53d7\u3051\u53d6\u3063\u3066\u3044\u308b\u3002\n\n\u6700\u521d\u306f `i = 0` \u304b\u3089\u59cb\u307e\u3063\u3066\u3044\u308b\u3002\n\n\u6700\u5f8c\u306e\u5024\u3082\u3001`5` \u3067\u306f\u306a\u304f `4` \u3068\u306a\u3063\u3066\u3044\u308b\u3002\n\n\u3053\u306e\u3088\u3046\u306b\u3001`range()` \u306b 1 \u3064\u306e\u6574\u6570\u3092\u4e0e\u3048\u305f\u5834\u5408\u306f\u3001\u305d\u306e\u6574\u6570 - 1 \u307e\u3067 0 \u304b\u3089 1 \u3064\u305a\u3064\u5897\u3048\u3066\u3044\u304f\u6574\u6570\u3092\u9806\u756a\u306b\u8fd4\u3059\u3002\n\n\n```python\n# \u7e70\u308a\u8fd4\u3057\u51e6\u7406\u304c\u7d42\u308f\u3063\u305f\u5f8c\u306e\u5024\u306e\u78ba\u8a8d => \u4eca\u56de\u306e\u5834\u5408 4\ni\n```\n\n\n\n\n    4\n\n\n\nJupyter Notebook \u3067\u306f\u5909\u6570\u540d\u3092\u30b3\u30fc\u30c9\u30bb\u30eb\u306e\u6700\u5f8c\u306e\u884c\u306b\u66f8\u3044\u3066\u5b9f\u884c\u3059\u308b\u3068\u305d\u306e\u5909\u6570\u306b\u4ee3\u5165\u3055\u308c\u3066\u3044\u308b\u5024\u3092\u78ba\u8a8d\u3067\u304d\u305f\u304c\u3001for \u6587\u306e\u4e2d\u306e\u30d6\u30ed\u30c3\u30af\u3067\u306f\u660e\u793a\u7684\u306b `print()` \u3092\u4f7f\u3046\u5fc5\u8981\u304c\u3042\u308b\u3002\n`print()` \u3092\u7528\u3044\u306a\u3044\u3068\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u4f55\u3082\u8868\u793a\u3055\u308c\u306a\u3044\u3002\n\n\n```python\n# \u5909\u6570\u306e\u5024\u306f\u8868\u793a\u3055\u308c\u306a\u3044\nfor i in range(5):\n    i\n```\n\nfor \u6587\u3092\u4f7f\u3063\u3066\u30010 \u304b\u3089\u59cb\u307e\u3063\u3066 1 \u305a\u3064\u5927\u304d\u304f\u306a\u3063\u3066\u3044\u304f\u6574\u6570\u9806\u756a\u306b\u53d6\u5f97\u3057\u3001\u3053\u308c\u3092\u30ea\u30b9\u30c8\u306e\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u306b\u5229\u7528\u3059\u308c\u3070\u3001\u30ea\u30b9\u30c8\u306e\u5404\u8981\u7d20\u306b\u9806\u756a\u306b\u30a2\u30af\u30bb\u30b9\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\n```python\nnames = ['\u4f50\u85e4', '\u9234\u6728', '\u9ad8\u6a4b']\n\nfor i in range(3):\n    print(names[i])\n```\n\n    \u4f50\u85e4\n    \u9234\u6728\n    \u9ad8\u6a4b\n\n\n\u5c11\u3057\u5fdc\u7528\u3057\u3066\u3001\u81ea\u52d5\u7684\u306b\u656c\u79f0\u3092\u3064\u3051\u3066\u8868\u793a\u3057\u3066\u307f\u308b\u3002\n\n\n```python\nfor i in range(3):\n    print('{}\u3055\u3093'.format(names[i]))\n```\n\n    \u4f50\u85e4\u3055\u3093\n    \u9234\u6728\u3055\u3093\n    \u9ad8\u6a4b\u3055\u3093\n\n\n\u4e0a\u8a18\u306e\u30b3\u30fc\u30c9\u306b\u95a2\u3057\u3066\u3001\u6c4e\u7528\u6027\u304c\u4f4e\u3044\u70b9\u3068\u3057\u3066\u3001`range(3)` \u306e\u3088\u3046\u306b `3` \u3068\u8a00\u3046\u5024\u3092\u76f4\u63a5\u8a18\u8ff0\u3057\u3066\u3044\u308b\u3053\u3068\u304c\u6319\u3052\u3089\u308c\u308b\u3002\n\n\u3053\u306e `3` \u306f\u30ea\u30b9\u30c8\u306e\u8981\u7d20\u306e\u6570\u3092\u610f\u5473\u3057\u3066\u3044\u308b\u304c\u3001\u30ea\u30b9\u30c8\u306e\u8981\u7d20\u306e\u6570\u304c\u5909\u308f\u308b\u3068\u3001\u3053\u306e\u30d7\u30ed\u30b0\u30e9\u30e0\u3082\u66f8\u304d\u63db\u3048\u308b\u5fc5\u8981\u304c\u3042\u308a\u3001\u624b\u9593\u304c\u304b\u304b\u3063\u305f\u308a\u3001\u30df\u30b9\u304c\u767a\u751f\u3059\u308b\u539f\u56e0\u3068\u306a\u3063\u305f\u308a\u3059\u308b\u3002\n\n\u30ea\u30b9\u30c8\u5185\u306e\u8981\u7d20\u306e\u6570\u306f\u3001\u7d44\u307f\u8fbc\u307f\u95a2\u6570\u3067\u3042\u308b `len()` \u3092\u7528\u3044\u3066\u53d6\u5f97\u3067\u304d\u308b\u305f\u3081\u3001\u3053\u308c\u3092\u4f7f\u7528\u3057\u305f\u6c4e\u7528\u6027\u306e\u9ad8\u3044\u30d7\u30ed\u30b0\u30e9\u30e0\u306b\u66f8\u304d\u63db\u3048\u308b\u3002\n\n&nbsp;\n\n\n```python\nlen(names)\n```\n\n\n\n\n    3\n\n\n\n\n```python\nfor i in range(len(names)):\n    print('{}\u3055\u3093'.format(names[i]))\n```\n\n    \u4f50\u85e4\u3055\u3093\n    \u9234\u6728\u3055\u3093\n    \u9ad8\u6a4b\u3055\u3093\n\n\n\u3053\u308c\u3067\u30ea\u30b9\u30c8\u306e\u8981\u7d20\u6570\u306b\u4f9d\u5b58\u3057\u306a\u3044\u30d7\u30ed\u30b0\u30e9\u30e0\u306b\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u305f\u3002\n\n\u307e\u305f\u3001\u30ea\u30b9\u30c8\u81ea\u4f53\u3092\u30a4\u30c6\u30e9\u30d6\u30eb\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u3068\u3057\u3066\u6307\u5b9a\u3059\u308b\u3053\u3068\u306b\u3088\u308a\u3001\u30ea\u30b9\u30c8\u8981\u7d20\u6570\u306e\u53d6\u5f97\u3082 `[]` \u3067\u306e\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u756a\u53f7\u306e\u6307\u5b9a\u3082\u305b\u305a\u306b\u3001\u3088\u308a\u53ef\u8aad\u6027\u306e\u9ad8\u3044\u30d7\u30ed\u30b0\u30e9\u30e0\u3092\u66f8\u304f\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\n```python\n# \u30ea\u30b9\u30c8\u3092\u30a4\u30c6\u30e9\u30d6\u30eb\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u306b\u6307\u5b9a\nfor name in names:\n    print('{}\u3055\u3093'.format(name))\n```\n\n    \u4f50\u85e4\u3055\u3093\n    \u9234\u6728\u3055\u3093\n    \u9ad8\u6a4b\u3055\u3093\n\n\n\u30ea\u30b9\u30c8\u3092\u30a4\u30c6\u30e9\u30d6\u30eb\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u3068\u3057\u3066\u6307\u5b9a\u3057\u305f\u5834\u5408\u3001\u8981\u7d20\u756a\u53f7\u3092\u53d6\u5f97\u3067\u304d\u306a\u3044\u304c\u3001\u72b6\u6cc1\u306b\u3088\u3063\u3066\u306f\u8981\u7d20\u756a\u53f7\u3092\u4f7f\u7528\u3057\u305f\u3044\u3053\u3068\u304c\u3042\u308b\u3002\n\n\u305d\u306e\u3088\u3046\u306a\u5834\u5408\u306f\u3001`enumerate()` \u3068\u8a00\u3046\u7d44\u307f\u8fbc\u307f\u95a2\u6570\u3092\u4f7f\u3046\u3002\n\u3053\u308c\u306b\u30a4\u30c6\u30e9\u30d6\u30eb\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u3092\u6e21\u3059\u3068\u3001`(\u8981\u7d20\u756a\u53f7, \u8981\u7d20)` \u3068\u8a00\u3046\u30bf\u30d7\u30eb\u3092 1 \u3064\u305a\u3064\u8fd4\u3059\u30a4\u30c6\u30e9\u30d6\u30eb\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u306b\u306a\u308b\u3002\n\n\n```python\n# enumerate \u306e\u4f7f\u3044\u65b9\nfor i, name in enumerate(names):\n    message = '{}\u756a\u76ee: {}\u3055\u3093'.format(i, name)\n    print(message)\n```\n\n\n```python\n# \u5b9f\u9a13\nprint(list(enumerate(names)))\n```\n\n    [(0, '\u4f50\u85e4'), (1, '\u9234\u6728'), (2, '\u9ad8\u6a4b')]\n\n\n`enumerate()` \u3068\u540c\u69d8\u3001`for` \u6587\u3068\u5408\u308f\u305b\u3066\u3088\u304f\u4f7f\u3046\u7d44\u307f\u8fbc\u307f\u95a2\u6570\u306b `zip()` \u304c\u3042\u308b\u3002\n\n`zip()` \u306f\u3001\u8907\u6570\u306e\u30a4\u30c6\u30e9\u30d6\u30eb\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u3092\u53d7\u3051\u53d6\u308a\u3001\u305d\u306e\u8981\u7d20\u306e\u30da\u30a2\u3092\u9806\u756a\u306b\u8fd4\u3059\u30a4\u30c6\u30e9\u30d6\u30eb\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u3092\u4f5c\u308b\u3002\n\u3053\u306e\u30a4\u30c6\u30e9\u30d6\u30eb\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u306f\u3001\u6e21\u3055\u308c\u305f\u30a4\u30c6\u30e9\u30d6\u30eb\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u305d\u308c\u305e\u308c\u306e\u5148\u982d\u306e\u8981\u7d20\u304b\u3089\u9806\u756a\u306b\u3001\u30bf\u30d7\u30eb\u306b\u675f\u306d\u3066\u8fd4\u3059\u3002\n\u3053\u306e\u30a4\u30c6\u30e9\u30d6\u30eb\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u306e\u9577\u3055\u306f\u3001\u6e21\u3055\u308c\u305f\u30a4\u30c6\u30e9\u30d6\u30eb\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u306e\u3046\u3061\u6700\u3082\u77ed\u3044\u9577\u3055\u3068\u4e00\u81f4\u3059\u308b\u3002\n\n\n```python\n# zip \u306e\u4f7f\u3044\u65b9\nnames = ['Python', 'Chainer']\nversions = ['3.7', '5.3.0']\nsuffixes = ['!!', '!!', '?']\n\nfor name, version, suffix in zip(names, versions, suffixes):\n    print('{} {} {}'.format(name, version, suffix))\n\n#\u5b9f\u9a13\nprint(list(zip(names, versions, suffixes)))\n```\n\n    Python 3.7 !!\n    Chainer 5.3.0 !!\n    [('Python', '3.7', '!!'), ('Chainer', '5.3.0', '!!')]\n\n\n`suffixes` \u306e\u8981\u7d20\u6570\u306f 3 \u3060\u304c\u3001\u3088\u308a\u77ed\u3044\u30a4\u30c6\u30e9\u30d6\u30eb\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u3068\u5171\u306b `zip` \u306b\u6e21\u3055\u308c\u305f\u305f\u3081\u3001\u5148\u982d\u304b\u3089 2 \u3064\u76ee\u307e\u3067\u3057\u304b\u5024\u304c\u53d6\u308a\u51fa\u3055\u308c\u3066\u3044\u306a\u3044\u3002\n\n**\u6761\u4ef6\u5206\u5c90\uff08if \u6587\uff09**\n\n`if` \u306f\u3001\u6307\u5b9a\u3057\u305f\u6761\u4ef6\u304c `True` \u304b `False` \u304b\u306b\u3088\u3063\u3066\u3001\u51e6\u7406\u3092\u5909\u3048\u308b\u305f\u3081\u306e\u5236\u5fa1\u69cb\u6587\u3067\u3042\u308b\u3002\n```\nif \u6761\u4ef6: # \u6761\u4ef6\u304c True \u3067\u3042\u308c\u3070\u30d6\u30ed\u30c3\u30af\u51e6\u7406\u3092\u5b9f\u884c\u3002\u30d8\u30c3\u30c0\u30fc\n    \u51e6\u7406\u30d6\u30ed\u30c3\u30af\nelif \u6761\u4ef6: # if \u306e\u6761\u4ef6\u304c False \u3067\u8ffd\u52a0\u306e\u6761\u4ef6\u5206\u5c90(\u4efb\u610f)\u3002\u30d8\u30c3\u30c0\u30fc\n    \u51e6\u7406\u30d6\u30ed\u30c3\u30af\nelse: # \u3059\u3079\u3066\u304c False \u306e\u5834\u5408\u306e\u6761\u4ef6\u5206\u5c90(\u4efb\u610f)\u3002\u30d8\u30c3\u30c0\u30fc\n    \u51e6\u7406\u30d6\u30ed\u30c3\u30af\n```\n\n**python \u306e if \u306f\u6587\u3067\u3042\u3063\u3066\u3001\u5f0f\u3067\u306f\u306a\u3044\u3002**\n\n&nbsp;\n\n`elif` \u3068 `else` \u306f\u4efb\u610f\u3067\u3042\u308a\u3001`elif` \u306f 1 \u3064\u3060\u3051\u3067\u306a\u304f\u8907\u6570\u9023\u306d\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\u4f8b\u3048\u3070\u30010 \u3088\u308a\u5927\u304d\u3044\u3053\u3068\u3092\u6761\u4ef6\u3068\u3057\u305f\u51e6\u7406\u3092\u66f8\u3044\u3066\u307f\u308b\u3002\n\n\n```python\n# if \u306e\u6761\u4ef6\u3092\u6e80\u305f\u3059\u5834\u5408\na = 1\n\nif a > 0:\n    print('0\u3088\u308a\u5927\u304d\u3044')\nelse:\n    print('0\u4ee5\u4e0b')\n```\n\n    0\u3088\u308a\u5927\u304d\u3044\n\n\n\n```python\n# if \u306e\u6761\u4ef6\u3092\u6e80\u305f\u3055\u306a\u3044\u5834\u5408\na = -1\n\nif a > 0:\n    print('0\u3088\u308a\u5927\u304d\u3044')\nelse:\n    print('0\u4ee5\u4e0b')\n```\n\n    0\u4ee5\u4e0b\n\n\n\u307e\u305f\u3001`if` \u306b\u5bfe\u3059\u308b\u6761\u4ef6\u4ee5\u5916\u306e\u6761\u4ef6\u5206\u5c90\u3092\u8ffd\u52a0\u3059\u308b\u5834\u5408\u306f\u3001\u4e0b\u8a18\u306e\u3088\u3046\u306b `elif` \u3092\u4f7f\u3046\u3002\n\n\n```python\na = 0\n\nif a > 0:    \n    print('0\u3088\u308a\u5927\u304d\u3044')\nelif a == 0:\n    print('\uff10')\nelse:\n    print('0\u3088\u308a\u5c0f\u3055\u3044')\n```\n\n    \uff10\n\n\n**\u7e70\u308a\u8fd4\u3057\uff08while \u6587\uff09**\n\n\u7e70\u308a\u8fd4\u3057\u51e6\u7406\u306f\u3001`for` \u4ee5\u5916\u306b\u3082 `while` \u3092\u7528\u3044\u3066\u8a18\u8ff0\u3059\u308b\u3053\u3068\u3082\u3067\u304d\u308b\u3002\n`while` \u6587\u3067\u306f\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306b**\u30eb\u30fc\u30d7\u3092\u7d99\u7d9a\u3059\u308b\u6761\u4ef6**\u3092\u6307\u5b9a\u3059\u308b\u3002\n\u6307\u5b9a\u3055\u308c\u305f\u6761\u4ef6\u6587\u304c `True` \u3067\u3042\u308b\u9650\u308a\u3001\u30d6\u30ed\u30c3\u30af\u306e\u90e8\u5206\u306b\u8a18\u8ff0\u3055\u308c\u305f\u51e6\u7406\u304c\u7e70\u308a\u8fd4\u3057\u5b9f\u884c\u3055\u308c\u308b\u3002\n\n```\nwhile \u6761\u4ef6: # True \u3067\u3042\u308c\u3070\u30d6\u30ed\u30c3\u30af\u51e6\u7406\u3092\u5b9f\u884c\u3002\u30d8\u30c3\u30c0\u30fc\n    \u30d6\u30ed\u30c3\u30af\u51e6\u7406\n```\n\n\n`while` \u6587\u3092\u4f7f\u7528\u3057\u305f 3 \u56de\u7e70\u308a\u8fd4\u3059\u30d7\u30ed\u30b0\u30e9\u30e0\u306f\u4e0b\u8a18\u306e\u3068\u304a\u308a\u3067\u3042\u308b\u3002\n\n\n```python\ncount = 0\n\nwhile count < 3:\n    print(count)\n    count += 1\n```\n\n    0\n    1\n    2\n\n\n\u3053\u3053\u3067\u4f7f\u308f\u308c\u3066\u3044\u308b `count` \u3068\u8a00\u3046\u5909\u6570\u306f\u3001\u30eb\u30fc\u30d7\u306e\u4e2d\u8eab\u304c\u4f55\u56de\u5b9f\u884c\u3055\u308c\u305f\u304b\u3092\u6570\u3048\u308b\u305f\u3081\u306b\u4f7f\u308f\u308c\u3066\u3044\u308b\u3002\n\u307e\u305a `0` \u3067\u521d\u671f\u5316\u3057\u3001\u30eb\u30fc\u30d7\u5185\u306e\u51e6\u7406\u304c\u4e00\u5ea6\u884c\u308f\u308c\u308b\u305f\u3073\u306b `count` \u306e\u5024\u306b 1 \u3092\u8db3\u3057\u3066\u3044\u308b\u3002\n\u3053\u306e `count` \u3092\u4f7f\u3063\u305f\u6761\u4ef6\u5f0f\u3092 `while` \u6587\u306b\u4e0e\u3048\u308b\u3053\u3068\u3067\u3001\u30eb\u30fc\u30d7\u3092\u56de\u3057\u305f\u3044\u56de\u6570\u3092\u6307\u5b9a\u3057\u3066\u3044\u308b\u3002\n\n\u4e00\u65b9\u3001`while True` \u3068\u6307\u5b9a\u3059\u308b\u3068\u3001`True` \u306f\u5909\u6570\u3067\u306f\u306a\u304f\u5024\u306a\u306e\u3067\u3001\u5909\u66f4\u3055\u308c\u308b\u3053\u3068\u306f\u306a\u304f\u3001\u30eb\u30fc\u30d7\u306f\u7121\u9650\u306b\u56de\u308a\u7d9a\u3051\u308b\u3002\n`while` \u6587\u81ea\u4f53\u306f\u7121\u9650\u30eb\u30fc\u30d7\u306e\u72b6\u614b\u306b\u3057\u3066\u304a\u304d\u3001\u30eb\u30fc\u30d7\u306e\u4e2d\u3067 `if` \u6587\u3092\u4f7f\u3063\u3066\u3001\u3042\u308b\u6761\u4ef6\u304c\u6e80\u305f\u3055\u308c\u305f\u5834\u5408\u306f\u30eb\u30fc\u30d7\u3092\u4e2d\u65ad\u3059\u308b\u3001\u3068\u8a00\u3046\u4f7f\u3044\u65b9\u304c\u3067\u304d\u308b\u3002\n\u3053\u308c\u306b\u306f `break` \u6587\u304c\u7528\u3044\u3089\u308c\u308b\u3002\n\n\u4ee5\u4e0b\u306f\u3001`break` \u6587\u3092\u4f7f\u3063\u3066\u4e0a\u306e\u30b3\u30fc\u30c9\u3068\u540c\u69d8\u306b 3 \u56de\u30eb\u30fc\u30d7\u3092\u56de\u3059\u30b3\u30fc\u30c9\u3067\u3042\u308b\u3002\n\n\n```python\ncount = 0\n\nwhile True:\n    print(count)\n    count += 1\n    \n    if count == 3:\n        break\n```\n\n    0\n    1\n    2\n\n\n`count` \u306e\u5024\u304c 3 \u3068\u7b49\u3057\u3044\u304b\u3069\u3046\u304b\u304c\u6bce\u56de\u30c1\u30a7\u30c3\u30af\u3055\u308c\u3001\u7b49\u3057\u304f\u306a\u3063\u3066\u3044\u308c\u3070 `break` \u6587\u304c\u5b9f\u884c\u3055\u308c\u3066 `while` \u30eb\u30fc\u30d7\u304c\u7d42\u4e86\u3059\u308b\u3002\n\n`while` \u6587\u3092\u4f7f\u3063\u3066\u3001\u6307\u5b9a\u3055\u308c\u305f\u6761\u4ef6\u3092\u6e80\u305f\u3057\u3066**\u3044\u306a\u3044**\u9593\u30eb\u30fc\u30d7\u3092\u7e70\u308a\u8fd4\u3059\u3068\u8a00\u3046\u51e6\u7406\u3082\u66f8\u304f\u3053\u3068\u304c\u3067\u304d\u308b\u3002`while` \u6587\u81ea\u4f53\u306e\u4f7f\u3044\u65b9\u306f\u540c\u3058\u3060\u304c\u3001\u6761\u4ef6\u3092\u53cd\u8ee2\u3057\u3066\u4e0e\u3048\u308b\u3053\u3068\u3067\u3001\u4e0e\u3048\u305f\u6761\u4ef6\u304c `False` \u3067\u3042\u308b\u9593\u7e70\u308a\u8fd4\u3055\u308c\u308b\u3088\u3046\u306b\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\u3053\u308c\u306b\u306f\u3001\u30d6\u30fc\u30eb\u5024\u3092\u53cd\u8ee2\u3059\u308b `not` \u3092\u7528\u3044\u308b\u3002\n`not True` \u306f `False` \u3092\u8fd4\u3057\u3001`not False` \u306f `True` \u3092\u8fd4\u3059\u3002\n\n\n```python\nnot True\n```\n\n\n\n\n    False\n\n\n\n\n```python\nnot False\n```\n\n\n\n\n    True\n\n\n\n\n```python\nnot 1 == 2\n```\n\n\n\n\n    True\n\n\n\n\u3053\u306e\u3088\u3046\u306b\u3001`not` \u306f\u3042\u3068\u306b\u7d9a\u304f\u30d6\u30fc\u30eb\u5024\u3092\u53cd\u8ee2\u3059\u308b\u3002\n\u3053\u308c\u3092\u7528\u3044\u3066\u3001`count` \u304c 3 **\u3067\u306f\u306a\u3044**\u9650\u308a\u30eb\u30fc\u30d7\u3092\u7e70\u308a\u8fd4\u3059\u3068\u8a00\u3046\u30b3\u30fc\u30c9\u3092 `while` \u6587\u3092\u4f7f\u3063\u3066\u66f8\u3044\u3066\u307f\u308b\u3002\n\n\n```python\ncount = 0\n\nwhile not count == 3:\n    print(count)\n    count += 1\n```\n\n    0\n    1\n    2\n\n\n**\u95a2\u6570**\n\n\u4f55\u304b\u3072\u3068\u307e\u3068\u307e\u308a\u306e\u51e6\u7406\u3092\u66f8\u3044\u305f\u969b\u306b\u306f\u3001\u305d\u306e\u51e6\u7406\u306e\u305f\u3081\u306e\u30b3\u30fc\u30c9\u3092\u307e\u3068\u3081\u3066\u3001\u30d7\u30ed\u30b0\u30e9\u30e0\u5168\u4f53\u306e\u8272\u3005\u306a\u7b87\u6240\u304b\u3089\u518d\u5229\u7528\u3067\u304d\u308b\u3088\u3046\u306b\u3057\u3066\u304a\u304f\u3068\u3001\u4fbf\u5229\u306a\u5834\u5408\u304c\u3042\u308b\u3002\n\u3053\u3053\u3067\u306f\u3001\u51e6\u7406\u3092\u3072\u3068\u307e\u3068\u3081\u306b\u3059\u308b\u65b9\u6cd5\u306e\u4e00\u3064\u3068\u3057\u3066**\u95a2\u6570 (function)** \u3092\u5b9a\u7fa9\u3059\u308b\u65b9\u6cd5\u3092\u7d39\u4ecb\u3059\u308b\u3002\n\n**\u95a2\u6570\u3092\u5b9a\u7fa9\u3059\u308b**\n\n\n\n```\ndef \u95a2\u6570\u540d (\u5f15\u65701,2,...): \u30d8\u30c3\u30c0\u30fc\n    \u51e6\u7406\u30d6\u30ed\u30c3\u30af\n```\n\n\u4f8b\u3048\u3070\u3001**\u53d7\u3051\u53d6\u3063\u305f\u5024\u3092 2 \u500d\u3057\u3066\u8868\u793a\u3059\u308b\u95a2\u6570**\u3092\u4f5c\u3063\u3066\u307f\u308b\u3002\n\n\u95a2\u6570\u3092\u5b9a\u7fa9\u3059\u308b\u306b\u306f\u3001\u307e\u305a\u540d\u524d\u3092\u6c7a\u3081\u308b\u5fc5\u8981\u304c\u3042\u308b\u3002\n\u4eca\u56de\u306f `double()` \u3068\u8a00\u3046\u540d\u524d\u306e\u95a2\u6570\u3092\u5b9a\u7fa9\u3057\u3066\u307f\u308b\u3002\n\n\u95a2\u6570\u3082\u5236\u5fa1\u69cb\u6587\u3068\u540c\u3058\u304f**\u30d8\u30c3\u30c0\u30fc**\u3068**\u30d6\u30ed\u30c3\u30af**\u3092\u6301\u3063\u3066\u3044\u308b\u3002\n\n\n```python\n# \u95a2\u6570 double() \u306e\u5b9a\u7fa9\ndef double(x):\n    print(2 * x)\n```\n\n\n```python\n# \u5b9f\u9a13 1 \u884c\u306b\u66f8\u3051\u308b\u304b => \u66f8\u3051\u308b\ndef double(x): print (2*x)\n\ndouble (3)\n```\n\n    6\n\n\n\n```python\n# \u5b9f\u9a13 \u7121\u540d\u95a2\u6570 lambda => \u5b9a\u7fa9\u3068\u540c\u3058\u69cb\u6587\n(lambda x: print (2*x))(3)\n```\n\n    6\n\n\n\n```python\n# \u5b9f\u9a13 \u7121\u540d\u95a2\u6570 lambda => \u5b9a\u7fa9\u3068\u540c\u3058\u69cb\u6587\n(lambda x: \n     print (2*x))\n(3)\n```\n\n\n\n\n    3\n\n\n\n**\u95a2\u6570\u306f\u5b9a\u7fa9\u3055\u308c\u305f\u3060\u3051\u3067\u306f\u5b9f\u884c\u3055\u308c\u306a\u3044\u3002**\n\u5b9a\u7fa9\u3057\u305f\u95a2\u6570\u3092\u4f7f\u7528\u3059\u308b\u305f\u3081\u306b\u306f\u3001\u5b9a\u7fa9\u3092\u884c\u3046\u30b3\u30fc\u30c9\u3068\u306f\u5225\u306b\u3001\u5b9f\u884c\u3092\u884c\u3046\u30b3\u30fc\u30c9\u304c\u5fc5\u8981\u3067\u3042\u308b\u3002\n\n\n```python\n# \u95a2\u6570 double() \u306e\u5b9a\u7fa9\ndef double(x):\n    print(2 * x)\n# \u95a2\u6570\u306e\u5b9f\u884c\ndouble(3)\n```\n\n    6\n\n\n\n```python\ndouble(5)\n```\n\n    10\n\n\n\n```python\ndouble(1.5)\n```\n\n    3.0\n\n\n`double(x)` \u306b\u304a\u3051\u308b `x` \u306e\u3088\u3046\u306b\u3001\u95a2\u6570\u306b\u6e21\u3055\u308c\u308b\u5909\u6570\u3084\u5024\u306e\u3053\u3068\u3092**\u5f15\u6570 (argument, \u3072\u304d\u3059\u3046)** \u3068\u8a00\u3046\u3002\n\u4e0a\u306e\u4f8b\u306f\u3001\u540d\u524d\u304c `double` \u3067\u30011\u3064\u306e\u5f15\u6570 `x` \u3092\u3068\u308a\u3001`2 * x` \u3068\u8a00\u3046\u8a08\u7b97\u3092\u884c\u3044\u3001\u305d\u306e\u7d50\u679c\u3092\u8868\u793a\u3057\u3066\u3044\u308b\u3002\n\n**\u8907\u6570\u306e\u5f15\u6570\u3092\u3068\u308b\u95a2\u6570**\n\n\u8907\u6570\u306e\u5f15\u6570\u3092\u3068\u308b\u95a2\u6570\u3092\u5b9a\u7fa9\u3059\u308b\u5834\u5408\u306f\u3001\u95a2\u6570\u540d\u306b\u7d9a\u304f `()` \u306e\u4e2d\u306b\u3001\u30ab\u30f3\u30de `,` \u533a\u5207\u308a\u3067\u5f15\u6570\u540d\u3092\u4e26\u3079\u308b\u3002\n\n\u4f8b\u3048\u3070\u3001\u5f15\u6570\u3092 2 \u3064\u3068\u308a\u3001\u8db3\u3057\u7b97\u3092\u884c\u3046\u95a2\u6570 `add()` \u3092\u4f5c\u3063\u3066\u307f\u308b\u3002\n\n\n```python\n# \u95a2\u6570\u306e\u5b9a\u7fa9\ndef add(a, b):\n    print(a + b)\n```\n\n\n```python\n# \u95a2\u6570\u306e\u5b9f\u884c\nadd(1, 2)\n```\n\n    3\n\n\n\n```python\nadd(3, 2.5)\n```\n\n    5.5\n\n\n\n```python\nadd(1, -5)\n```\n\n    -4\n\n\n\u4eca\u56de\u306e `double()` \u3084 `add()` \u306f\u5b9a\u7fa9\u3092\u884c\u3044\u81ea\u4f5c\u3057\u305f\u95a2\u6570\u3060\u304c\u3001Python \u306b\u306f\u4e88\u3081\u591a\u304f\u306e\u95a2\u6570\u304c\u5b9a\u7fa9\u3055\u308c\u3066\u3044\u308b\u3002\n\u305d\u306e\u3088\u3046\u306a\u95a2\u6570\u3092**\u7d44\u307f\u8fbc\u307f\u95a2\u6570 (built-in function)** \u3068\u547c\u3076\u3002\n\u3059\u3067\u306b\u4f7f\u7528\u3057\u3066\u3044\u308b `print()` \u3084 `len()`, `range()` \u306a\u3069\u304c\u3001\u3053\u308c\u306b\u8a72\u5f53\u3059\u308b\u3002\n\u7d44\u307f\u8fbc\u307f\u95a2\u6570\u306e\u4e00\u89a7\u306f[\u3053\u3061\u3089](https://docs.python.org/ja/3/library/functions.html)\u3067\u78ba\u8a8d\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\ncolab \u74b0\u5883\u3067 `dir(__builtin__)` \u3067\u3082\u78ba\u8a8d\u3067\u304d\u308b\n\n\n\n**\u5f15\u6570\u3092\u3068\u3089\u306a\u3044\u95a2\u6570**\n\n\u5f15\u6570\u3092\u3068\u3089\u306a\u3044\u95a2\u6570\u3092\u5b9a\u7fa9\u3059\u308b\u5834\u5408\u3067\u3082\u3001\u95a2\u6570\u540d\u306e\u5f8c\u306b `()` \u3092\u52a0\u3048\u308b\u5fc5\u8981\u304c\u3042\u308b\u3002\n\n\u4f8b\u3048\u3070\u3001\u5b9f\u884c\u3059\u308b\u3068\u30e1\u30c3\u30bb\u30fc\u30b8\u3092\u8868\u793a\u3059\u308b\u95a2\u6570\u3092\u5b9a\u7fa9\u3057\u3066\u3001\u5b9f\u884c\u3057\u3066\u307f\u308b\u3002\n\n\n```python\n# \u5f15\u6570\u306e\u306a\u3044\u95a2\u6570\u306e\u5b9a\u7fa9\ndef hello():\n    print('Chainer\u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb\u306b\u3088\u3046\u3053\u305d')\n```\n\n\n```python\n# \u5f15\u6570\u306e\u306a\u3044\u95a2\u6570\u306e\u5b9f\u884c\nhello()\n```\n\n    Chainer\u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb\u306b\u3088\u3046\u3053\u305d\n\n\n**\u5f15\u6570\u306e\u30c7\u30d5\u30a9\u30eb\u30c8\u5024**\n\n\u5f15\u6570\u306b\u306f\u3001\u3042\u3089\u304b\u3058\u3081\u5024\u3092\u4e0e\u3048\u3066\u304a\u304f\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\u3053\u308c\u306f\u3001\u5f15\u6570\u3092\u3068\u308b\u95a2\u6570\u3092\u5b9a\u7fa9\u3059\u308b\u969b\u306b\u3001\u4f55\u3082\u5f15\u6570\u306b\u5024\u304c\u6e21\u3055\u308c\u306a\u304b\u3063\u305f\u3068\u304d\u306b\u3069\u306e\u3088\u3046\u306a\u5024\u304c\u305d\u306e\u5f15\u6570\u306b\u6e21\u3055\u308c\u305f\u3053\u3068\u306b\u3059\u308b\u304b\u3092\u3042\u3089\u304b\u3058\u3081\u6c7a\u3081\u3066\u304a\u3051\u308b\u6a5f\u80fd\u3067\u3001\u305d\u306e\u5024\u306e\u3053\u3068\u3092**\u30c7\u30d5\u30a9\u30eb\u30c8\u5024**\u3068\u547c\u3076\u3002\n\n\u4f8b\u3048\u3070\u3001\u4e0a\u306e `hello()` \u3068\u8a00\u3046\u95a2\u6570\u306b\u3001`message` \u3068\u8a00\u3046\u5f15\u6570\u3092\u3082\u305f\u305b\u3001\u305d\u3053\u306b\u30c7\u30d5\u30a9\u30eb\u30c8\u5024\u3092\u8a2d\u5b9a\u3057\u3066\u304a\u304f\u3002\n\n\n```python\ndef hello(message='Chainer\u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb\u306b\u3088\u3046\u3053\u305d'):\n    print(message)\n```\n\n\u3053\u306e\u95a2\u6570\u306f\u5f15\u6570\u306b\u4f55\u3082\u4e0e\u3048\u305a\u306b\u547c\u3073\u51fa\u3059\u3068\u3001\u300cChainer\u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb\u306b\u3088\u3046\u3053\u305d\u300d\u3068\u8a00\u3046\u30e1\u30c3\u30bb\u30fc\u30b8\u3092\u8868\u793a\u3057\u3001\u5f15\u6570\u306b\u5225\u306a\u5024\u304c\u6e21\u3055\u308c\u308b\u3068\u3001\u305d\u306e\u5024\u3092\u8868\u793a\u3059\u308b\u3002\n\n\n```python\nhello()\n```\n\n    Chainer\u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb\u306b\u3088\u3046\u3053\u305d\n\n\n\n```python\nhello('Welcome to Chainer tutorial')\n```\n\n    Welcome to Chainer tutorial\n\n\n\u30c7\u30d5\u30a9\u30eb\u30c8\u5024\u304c\u4e0e\u3048\u3089\u308c\u3066\u3044\u306a\u3044\u5f15\u6570\u306f\u3001\u95a2\u6570\u547c\u3073\u51fa\u3057\u306e\u969b\u306b\u5fc5\u305a\u4f55\u3089\u304b\u306e\u5024\u304c\u6e21\u3055\u308c\u308b\u5fc5\u8981\u304c\u3042\u308b\u304c\u3001\u30c7\u30d5\u30a9\u30eb\u30c8\u5024\u3092\u6301\u3064\u5834\u5408\u306f\u3001\u4f55\u3082\u6307\u5b9a\u3057\u306a\u304f\u3066\u3082\u95a2\u6570\u3092\u547c\u3073\u51fa\u3059\u3053\u3068\u304c\u3067\u304d\u308b\u3088\u3046\u306b\u306a\u308b\u3002\n\n**\u8fd4\u308a\u5024\u306e\u3042\u308b\u95a2\u6570**\n\n\u4e0a\u3067\u5b9a\u7fa9\u3057\u305f\u8db3\u3057\u7b97\u3092\u884c\u3046\u95a2\u6570 `add()` \u3067\u306f\u3001\u8a08\u7b97\u7d50\u679c\u3092\u8868\u793a\u3059\u308b\u3060\u3051\u3067\u3001\u8a08\u7b97\u7d50\u679c\u3092\u547c\u3073\u51fa\u3057\u5143\u306b\u623b\u3057\u3066\u3044\u306a\u3044\u3002\n\u305d\u306e\u305f\u3081\u3001\u3053\u306e\u307e\u307e\u3067\u306f\u8a08\u7b97\u7d50\u679c\u3092\u95a2\u6570\u306e\u5916\u304b\u3089\u5229\u7528\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u306a\u3044\u3002\n\n\u305d\u3053\u3067\u3001`add()` \u95a2\u6570\u306e\u672b\u5c3e\u306b `return` \u6587\u3092\u8ffd\u52a0\u3057\u3066\u3001\u8a08\u7b97\u7d50\u679c\u3092\u547c\u3073\u51fa\u3057\u5143\u306b\u8fd4\u3059\u3088\u3046\u306b\u5909\u66f4\u3057\u3066\u307f\u308b\u3002\n\n\n```python\n# \u8fd4\u308a\u5024\u306e\u3042\u308b\u95a2\u6570\u306e\u5b9a\u7fa9\ndef add(a, b):\n    return a + b\n```\n\n\u3053\u306e\u3088\u3046\u306b\u3001\u547c\u3073\u51fa\u3057\u5143\u306b\u8fd4\u3057\u305f\u3044\u5024\u3092 `return` \u306b\u7d9a\u3044\u3066\u66f8\u304f\u3068\u3001\u305d\u306e\u5024\u304c `add()` \u95a2\u6570\u3092\u547c\u3073\u51fa\u3057\u305f\u3068\u3053\u308d\u3078\u623b\u3055\u308c\u308b\u3002\n`return` \u3067\u8fd4\u3055\u308c\u308b\u5024\u306e\u3053\u3068\u3092**\u8fd4\u308a\u5024 (return value)** \u3068\u8a00\u3046\u3002\n\n\u4ee5\u4e0b\u306b\u3001\u8a08\u7b97\u7d50\u679c\u3092 `result` \u3068\u8a00\u3046\u5909\u6570\u306b\u683c\u7d0d\u3057\u3001\u8868\u793a\u3059\u308b\u4f8b\u3092\u793a\u3059\u3002\n\n\n```python\nresult = add(1, 3)\n\nresult\n```\n\n\n\n\n    4\n\n\n\n\u8a08\u7b97\u7d50\u679c\u304c `result` \u306b\u683c\u7d0d\u3055\u308c\u3066\u3044\u308b\u306e\u3067\u3001\u3053\u306e\u7d50\u679c\u3092\u7528\u3044\u3066\u3055\u3089\u306b\u5225\u306e\u51e6\u7406\u3092\u884c\u3046\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\n```python\nresult = add(1, 3)\n\nresult_doubled = result * 2\n\nresult_doubled\n```\n\n\n\n\n    8\n\n\n\n\u307e\u305f\u3001\u8fd4\u308a\u5024\u306f\u300c\u547c\u3073\u51fa\u3057\u5143\u300d\u306b\u8fd4\u3055\u308c\u308b\u3068\u66f8\u3044\u305f\u3002\n\u3053\u306e\u300c\u547c\u3073\u51fa\u3057\u5143\u300d\u3068\u8a00\u3046\u306e\u306f\u3001\u95a2\u6570\u3092\u547c\u3073\u51fa\u3059\u90e8\u5206\u306e\u3053\u3068\u3067\u3001\u4e0a\u306e\u30b3\u30fc\u30c9\u306f `add(1, 3)` \u306e\u90e8\u5206\u304c `4` \u3068\u8a00\u3046\u7d50\u679c\u306e\u5024\u306b\u306a\u308a\u3001\u305d\u308c\u304c\u5de6\u8fba\u306e `result` \u306b\u4ee3\u5165\u3055\u308c\u3066\u3044\u308b\u3002\n\n\u3053\u308c\u3092\u7528\u3044\u308b\u3068\u3001\u4f8b\u3048\u3070\u300c2 \u3068 3 \u3092\u8db3\u3057\u305f\u7d50\u679c\u3068\u30011 \u3068 3 \u3092\u8db3\u3057\u305f\u7d50\u679c\u3092\u3001\u639b\u3051\u5408\u308f\u305b\u308b\u300d\u3068\u8a00\u3046\u8a08\u7b97\u304c\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u66f8\u3051\u308b\u3002\n\n\n```python\nadd(2, 3) * add(1, 3)\n```\n\n\n\n\n    20\n\n\n\n**\u5909\u6570\u306e\u30b9\u30b3\u30fc\u30d7**\n\n\u95a2\u6570\u306e\u4e2d\u3067\u5b9a\u7fa9\u3057\u305f\u5909\u6570\u306f\u57fa\u672c\u7684\u306b\u306f\u95a2\u6570\u306e\u5916\u3067\u306f\u5229\u7528\u3067\u304d\u306a\u3044\u3002\n\u4f8b\u3048\u3070\u3001\u4ee5\u4e0b\u306e\u4f8b\u3092\u898b\u3066\u307f\u308b\u3002\n\n\n```python\na = 1\n\n# \u95a2\u6570\u306e\u5185\u90e8\u3067 a \u306b 2 \u3092\u4ee3\u5165\ndef change():\n    a = 2\n    \nchange()\n\na\n```\n\n\n\n\n    1\n\n\n\n\u95a2\u6570\u306e\u5916\u3067 `a = 1` \u3068\u521d\u671f\u5316\u3057\u305f\u5909\u6570\u3068\u540c\u3058\u540d\u524d\u306e\u5909\u6570\u306b\u5bfe\u3057\u3066\u3001`change()` \u95a2\u6570\u306e\u5185\u90e8\u3067 `a = 2` \u3068\u8a00\u3046\u4ee3\u5165\u3092\u884c\u3063\u3066\u3044\u308b\u306b\u3082\u304b\u304b\u308f\u3089\u305a\u3001`change()` \u95a2\u6570\u306e\u5b9f\u884c\u5f8c\u306b\u3082\u95a2\u6570\u306e\u5916\u5074\u3067\u306f `a` \u306e\u5024\u306f 1 \u306e\u307e\u307e\u306b\u306a\u3063\u3066\u3044\u308b\u3002\n**\u95a2\u6570\u306e\u5916\u5074\u3067\u5b9a\u7fa9\u3055\u308c\u305f\u5909\u6570** `a` **\u306b\u3001\u95a2\u6570\u5185\u90e8\u3067\u306e\u51e6\u7406\u304c\u5f71\u97ff\u3057\u3066\u3044\u306a\u3044\u3053\u3068\u304c\u308f\u304b\u308b\u3002**\n\n\u306a\u305c\u3053\u3046\u306a\u308b\u304b\u3068\u8a00\u3046\u3068\u3001\u95a2\u6570\u306e\u4e2d\u3067\u5909\u6570\u306b\u5024\u304c\u4ee3\u5165\u3055\u308c\u308b\u3068\u304d\u3001\u305d\u306e\u5909\u6570\u306f\u305d\u306e\u95a2\u6570\u306e**\u30b9\u30b3\u30fc\u30d7 (scope)** \u3067\u3060\u3051\u6709\u52b9\u306a**\u30ed\u30fc\u30ab\u30eb\u5909\u6570**\u306b\u306a\u308a\u3001\u95a2\u6570\u306e\u5916\u306b\u3042\u308b\u540c\u3058\u540d\u524d\u306e\u5909\u6570\u3068\u306f\u5225\u306e\u3082\u306e\u3092\u6307\u3059\u3088\u3046\u306b\u306a\u308b\u305f\u3081\u3067\u3042\u308b\u3002\n\u30b9\u30b3\u30fc\u30d7\u3068\u306f\u3001\u305d\u306e\u5909\u6570\u304c\u53c2\u7167\u53ef\u80fd\u306a\u7bc4\u56f2\u306e\u3053\u3068\u3067\u3042\u308b\u3002\n\u4e0a\u306e\u4f8b\u3067\u306f\u3001`a = 2` \u306e\u4ee3\u5165\u3092\u884c\u3063\u305f\u6642\u70b9\u3067`change()` \u95a2\u6570\u306e\u30b9\u30b3\u30fc\u30d7\u306b `a` \u3068\u8a00\u3046\u5909\u6570\u304c\u4f5c\u3089\u308c\u3001`change()` \u95a2\u6570\u306e\u4e2d\u304b\u3089\u306f `a` \u3068\u3044\u3048\u3070\u3053\u308c\u3092\u6307\u3059\u3088\u3046\u306b\u306a\u308b\u3002\u95a2\u6570\u304b\u3089\u629c\u3051\u308b\u3068\u3001`a` \u306f 1 \u3092\u5024\u306b\u6301\u3064\u5916\u5074\u306e\u5909\u6570\u3092\u6307\u3059\u3088\u3046\u306b\u306a\u308b\u3002\n\n\u305f\u3060\u3057\u3001\u4ee3\u5165\u3092\u884c\u308f\u305a\u306b\u3001\u53c2\u7167\u3059\u308b\u3060\u3051\u3067\u3042\u308c\u3070\u3001\u95a2\u6570\u306e\u5185\u5074\u304b\u3089\u5916\u5074\u3067\u5b9a\u7fa9\u3055\u308c\u305f\u5909\u6570\u3092\u5229\u7528\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\n```python\na = 1\n\ndef change():\n    print('From inside:', a)\n    \nchange()\n\nprint('From outside:', a)\n```\n\n    From inside: 1\n    From outside: 1\n\n\n\u3053\u306e\u5834\u5408\u306f\u3001`change()` \u95a2\u6570\u306e\u30b9\u30b3\u30fc\u30d7\u306b\u306f `a` \u3068\u8a00\u3046\u5909\u6570\u306f\u4f5c\u3089\u308c\u306a\u3044\u306e\u3067\u3001\u95a2\u6570\u306e\u4e2d\u3067 `a` \u3068\u3044\u3048\u3070\u5916\u5074\u3067\u5b9a\u7fa9\u3055\u308c\u305f\u5909\u6570\u3092\u6307\u3059\u3002\n\n\u95a2\u6570\u306e\u5916\u3067\u5b9a\u7fa9\u3055\u308c\u305f\u5909\u6570\u306f**\u30b0\u30ed\u30fc\u30d0\u30eb\u5909\u6570**\u3068\u547c\u3070\u308c\u308b\u3002\n\u30b0\u30ed\u30fc\u30d0\u30eb\u5909\u6570\u306f\u3001\u7279\u306b\u7279\u5225\u306a\u8a18\u8ff0\u3092\u8981\u305b\u305a\u53c2\u7167\u3059\u308b\u3053\u3068\u306f\u3067\u304d\u308b\u304c\u3001\u95a2\u6570\u306e\u4e2d\u3067**\u4ee3\u5165**\u3092\u884c\u3046\u5834\u5408\u306f\u3001`global` \u6587\u3092\u4f7f\u3063\u3066\u3001\u4ee3\u5165\u5148\u3092\u30b0\u30ed\u30fc\u30d0\u30eb\u5909\u6570\u3068\u3059\u308b\u5ba3\u8a00\u3092\u884c\u3046\u5fc5\u8981\u304c\u3042\u308b\u3002\n\n\n```python\na = 1\n\ndef change():\n    global a  # a \u3092\u30b0\u30ed\u30fc\u30d0\u30eb\u5909\u6570\u3067\u3042\u308b\u5ba3\u8a00\n    a = 2       # \u30b0\u30ed\u30fc\u30d0\u30eb\u5909\u6570\u3078\u306e\u4ee3\u5165\n\n# \u95a2\u6570\u306e\u5b9f\u884c\nchange()\n\n# \u7d50\u679c\u306e\u78ba\u8a8d <- a \u306e\u5024\u304c\u4e0a\u66f8\u304d\u3055\u308c\u3066\u3044\u308b\na\n```\n\n\n\n\n    2\n\n\n\n`global a` \u3068\u8a00\u3046\u884c\u3092 `change()` \u95a2\u6570\u5185\u3067 `a` \u3068\u8a00\u3046\u5909\u6570\u3092\u4f7f\u7528\u3059\u308b\u524d\u306b\u8ffd\u52a0\u3059\u308b\u3068\u3001\u305d\u306e\u884c\u4ee5\u964d\u306f `a` \u3068\u8a00\u3046\u5909\u6570\u3078\u306e\u4ee3\u5165\u3082\u95a2\u6570\u306e\u5916\u5074\u3067\u5b9a\u7fa9\u3055\u308c\u305f\u30b0\u30ed\u30fc\u30d0\u30eb\u5909\u6570\u306e `a` \u306b\u5bfe\u3057\u3066\u884c\u308f\u308c\u308b\u3002\n\n**\u30af\u30e9\u30b9**\n\n**\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u6307\u5411\u30d7\u30ed\u30b0\u30e9\u30df\u30f3\u30b0 (object-oriented programming)** \u306e\u7279\u5fb4\u306e\u4e00\u3064\u3067\u3042\u308b**\u30af\u30e9\u30b9 (class)** \u306f\u3001**\u30aa\u30d6\u30b8\u30a7\u30af\u30c8 (object)** \u3092\u751f\u6210\u3059\u308b\u305f\u3081\u306e\u8a2d\u8a08\u56f3\u306b\u3042\u305f\u308b\u3082\u306e\u3067\u3042\u308b\u3002\n\n\u30af\u30e9\u30b9\u304b\u3089\u4f5c\u6210\u3055\u308c\u305f\u5b9f\u4f53\u306e\u3053\u3068\u3092**\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9 (instance)** \u307e\u305f\u306f**\u30aa\u30d6\u30b8\u30a7\u30af\u30c8 (object)** \u3068\u3082\u547c\u3073\u3001**\u30af\u30e9\u30b9\u304b\u3089\u5b9f\u4f53\u3092\u4f5c\u6210\u3059\u308b**\u3068\u8a00\u3046\u64cd\u4f5c\u306e\u3053\u3068\u3092**\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u5316 (instantiation)** \u3068\u547c\u3076\u3002\n\n**\u30af\u30e9\u30b9\u306e\u5b9a\u7fa9**\n\n\u305d\u308c\u3067\u306f\u3001\u5bb6\u306e\u8a2d\u8a08\u56f3\u3092\u8868\u3059 `House` \u3068\u8a00\u3046\u30af\u30e9\u30b9\u3092\u5b9a\u7fa9\u3057\u3066\u307f\u308b\u3002\n\n`House` \u30af\u30e9\u30b9\u306b\u306f\u3001\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u5316\u3055\u308c\u305f\u3042\u3068\u306b\u3001\u5404\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u3001\u3059\u306a\u308f\u3061\u8ab0\u304b\u7279\u5b9a\u306e\u4eba\u306e\u5bb6\u3054\u3068\u306b\u7570\u306a\u308b\u5024\u3092\u6301\u3064\u3001`name_plate` \u3068\u8a00\u3046\u5909\u6570\u3092\u6301\u305f\u305b\u3066\u307f\u308b\u3002\n\n`name_plate` \u3068\u8a00\u3046\u5909\u6570\u306b\u306f\u3001\u500b\u5225\u306e\u5bb6\u306e\u8868\u672d\u306b\u8868\u793a\u3059\u308b\u305f\u3081\u306e\u6587\u5b57\u5217\u304c\u4e0e\u3048\u3089\u308c\u308b\u304c\u3001\u30af\u30e9\u30b9\u3092\u5b9a\u7fa9\u3059\u308b\u969b\u306b\u306f\u300c`name_plate` \u3068\u8a00\u3046\u5909\u6570\u3092\u6301\u3064\u3053\u3068\u304c\u3067\u304d\u308b\u300d\u3088\u3046\u306b\u3057\u3066\u304a\u304f\u3060\u3051\u3067\u3088\u304f\u3001**\u5b9f\u969b\u306b\u305d\u306e\u5909\u6570\u306b\u4f55\u304b\u5177\u4f53\u7684\u306a\u5024\u3092\u4e0e\u3048\u308b\u5fc5\u8981\u306f\u306a\u3044\u3002**\n\n\u30af\u30e9\u30b9\u306f\u3001**\u8a2d\u8a08\u56f3**\u3067\u3042\u308c\u3070\u3088\u304f\u3001\u5177\u4f53\u7684\u306a\u5024\u3092\u6301\u305f\u305b\u306a\u304f\u3066\u3082\u3088\u3044\u305f\u3081\u3067\u3042\u308b\u3002\n\n\u5177\u4f53\u7684\u306a\u5024\u306f\u3001\u500b\u5225\u306e\u5bb6\u3092\u4f5c\u6210\u3059\u308b\u3068\u304d\u3001\u3059\u306a\u308f\u3061\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u5316\u306e\u969b\u306b\u4e0e\u3048\u3001\u5404\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u304c `name_plate` \u3068\u8a00\u3046\u5024\u306b\u81ea\u5206\u306e\u5bb6\u306e\u8868\u672d\u306e\u540d\u524d\u3092\u4fdd\u6301\u3059\u308b\u3088\u3046\u306b\u3059\u308b\u3002\n\n\u3053\u306e\u3088\u3046\u306a\u3001\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u306b\u5c5e\u3057\u3066\u3044\u308b\u5909\u6570\u3092**\u5c5e\u6027 (attribute)** \u3068\u547c\u3076\u3002\u540c\u69d8\u306b\u3001\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u304b\u3089\u547c\u3073\u51fa\u3059\u3053\u3068\u304c\u3067\u304d\u308b\u95a2\u6570\u306e\u3053\u3068\u3092**\u30e1\u30bd\u30c3\u30c9 (method)** \u3068\u547c\u3076\u3002\n\n\u30af\u30e9\u30b9\u306f\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306a\u69cb\u6587\u3092\u4f7f\u3063\u3066\u5b9a\u7fa9\u3059\u308b\u3002\n\n\u5177\u4f53\u7684\u306b\u306f\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u306a\u308b\u3002\n```\nclass \u30af\u30e9\u30b9\u540d: \u30d8\u30c3\u30c0\u30fc\n    def \u30e1\u30bd\u30c3\u30c9\u540d(\u5f15\u65701, ...): \u30d8\u30c3\u30c0\u30fc\n        \u30d6\u30ed\u30c3\u30af\u51e6\u7406\n```\n\n\n```python\n# \u30af\u30e9\u30b9\u306e\u5b9a\u7fa9\nclass House:\n    # __init__() \u30e1\u30bd\u30c3\u30c9\u306e\u5b9a\u7fa9\n    def __init__(self, name):\n        self.name_plate = name\n```\n\n\u3053\u3053\u3067\u3001`__init__()` \u3068\u8a00\u3046\u540d\u524d\u306e\u30e1\u30bd\u30c3\u30c9\u304c `House` \u30af\u30e9\u30b9\u306e\u4e2d\u306b\u5b9a\u7fa9\u3055\u308c\u3066\u3044\u308b\u3002\n\u30e1\u30bd\u30c3\u30c9\u306e\u540d\u524d\u306f\u81ea\u7531\u306b\u540d\u4ed8\u3051\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u304c\u3001\u3044\u304f\u3064\u304b\u7279\u5225\u306a\u610f\u5473\u3092\u6301\u3064\u30e1\u30bd\u30c3\u30c9\u540d\u304c\u4e88\u3081\u6c7a\u3081\u3089\u308c\u3066\u3044\u308b\u3002\n`__init__()` \u306f\u305d\u3046\u3044\u3063\u305f\u30e1\u30bd\u30c3\u30c9\u306e\u4e00\u3064\u3067\u3001**\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u5316\u3059\u308b\u969b\u306b\u81ea\u52d5\u7684\u306b\u547c\u3070\u308c\u308b\u30e1\u30bd\u30c3\u30c9**\u3067\u3042\u308b\u3002\n\n`House` \u30af\u30e9\u30b9\u306e `__init__()` \u306f\u3001`name` \u3068\u8a00\u3046\u5f15\u6570\u3092\u3068\u308a\u3001\u3053\u308c\u3092 `self.name_plate` \u3068\u8a00\u3046\u5909\u6570\u306b\u4ee3\u5165\u3057\u3066\u3044\u308b\u3002\n\u3053\u306e `self` \u3068\u8a00\u3046\u306e\u306f\u3001\u30af\u30e9\u30b9\u304c\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u5316\u3055\u308c\u305f\u3042\u3068\u3001\u4f5c\u6210\u3055\u308c\u305f\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u81ea\u8eab\u3092\u53c2\u7167\u3059\u308b\u306e\u306b\u7528\u3044\u3089\u308c\u308b\u3002\n\u3053\u308c\u3092\u4f7f\u3063\u3066\u3001`self.name_plate = name` \u3068\u3059\u308b\u3053\u3068\u3067\u3001\u4f5c\u6210\u3055\u308c\u305f\u500b\u5225\u306e\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u306b\u5c5e\u3059\u308b\u5909\u6570 `self.name_plate` \u3078\u3001\u5f15\u6570\u306b\u6e21\u3055\u308c\u305f `name` \u304c\u6301\u3064\u5024\u3092\u4ee3\u5165\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n`self` \u304c\u6307\u3059\u3082\u306e\u306f\u3001\u5404\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u304b\u3089\u898b\u305f\u300c\u81ea\u5206\u81ea\u8eab\u300d\u306a\u306e\u3067\u3001\u5404\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u3054\u3068\u306b\u7570\u306a\u308b\u3002\n\u3053\u308c\u306b\u3088\u3063\u3066\u3001`self.name_plate` \u306f\u5404\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u306b\u7d10\u4ed8\u3044\u305f\u5225\u3005\u306e\u5024\u3092\u6301\u3064\u3082\u306e\u3068\u306a\u308b\u3002\n\n\u30e1\u30bd\u30c3\u30c9\u306f\u3001\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u304b\u3089\u547c\u3073\u51fa\u3055\u308c\u308b\u3068\u304d\u81ea\u52d5\u7684\u306b\u7b2c\u4e00\u5f15\u6570\u306b\u305d\u306e\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u3078\u306e\u53c2\u7167\u3092\u6e21\u3059\u3002\n\u305d\u306e\u305f\u3081\u3001\u30e1\u30bd\u30c3\u30c9\u306e\u7b2c\u4e00\u5f15\u6570\u306f `self` \u3068\u3057\u3001\u6e21\u3055\u308c\u3066\u304f\u308b\u81ea\u5206\u81ea\u8eab\u3078\u306e\u53c2\u7167\u3092\u53d7\u3051\u53d6\u308b\u3088\u3046\u306b\u3057\u3066\u3044\u308b\u3002\n\u305f\u3060\u3057\u3001\u547c\u3073\u51fa\u3059\u969b\u306b\u306f**\u305d\u306e\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u3092\u5f15\u6570\u306b\u6307\u5b9a\u3059\u308b\u5fc5\u8981\u306f\u306a\u3044\u3002**\n\u4ee5\u4e0b\u306b\u5177\u4f53\u4f8b\u3092\u793a\u3057\u3001\u518d\u5ea6\u3053\u306e\u3053\u3068\u3092\u78ba\u8a8d\u3059\u308b\u3002\n\n\u305d\u308c\u3067\u306f\u3001\u4e0a\u3067\u5b9a\u7fa9\u3057\u305f `House` \u30af\u30e9\u30b9\u306e\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u3092\u4f5c\u6210\u3057\u3066\u307f\u308b\u3002\n\u30af\u30e9\u30b9\u306e\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u5316\u306b\u306f\u3001\u30af\u30e9\u30b9\u540d\u306e\u3042\u3068\u306b `()` \u3092\u8ffd\u52a0\u3057\u3066\u3001\u30af\u30e9\u30b9\u3092\u547c\u3073\u51fa\u3059\u3088\u3046\u306a\u8a18\u6cd5\u3092\u4f7f\u3046\u3002\n\u3053\u306e\u969b\u3001\u95a2\u6570\u3092\u547c\u3073\u51fa\u3059\u3068\u304d\u3068\u540c\u69d8\u306b\u3057\u3066\u3001`()` \u306b\u5f15\u6570\u3092\u6e21\u3059\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\u305d\u306e\u5f15\u6570\u306f\u3001`__init__()` \u30e1\u30bd\u30c3\u30c9\u306b\u6e21\u3055\u308c\u308b\u3002\n\n\n```python\nmy_house = House('Chainer')\n```\n\n`House` \u3068\u8a00\u3046\u30af\u30e9\u30b9\u306e `__init__()` \u30e1\u30bd\u30c3\u30c9\u306b\u3001`'Chainer'` \u3068\u8a00\u3046\u6587\u5b57\u5217\u3092\u6e21\u3057\u3066\u3044\u308b\u3002\n`my_house` \u304c\u3001`House` \u30af\u30e9\u30b9\u304b\u3089\u4f5c\u6210\u3055\u308c\u305f\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u3067\u3042\u308b\u3002\n\u3053\u3053\u3067\u3001\u30af\u30e9\u30b9\u5b9a\u7fa9\u3067\u306f `__init__()` \u30e1\u30bd\u30c3\u30c9\u306f `self` \u3068 `name` \u3068\u8a00\u3046 2 \u3064\u306e\u5f15\u6570\u3092\u3068\u3063\u3066\u3044\u305f\u304c\u3001\u547c\u3073\u51fa\u3057\u306e\u969b\u306b\u306f `'Chainer'` \u3068\u8a00\u3046\u4e00\u3064\u306e\u5f15\u6570\u3057\u304b\u4e0e\u3048\u3066\u3044\u306a\u3044\u3002\n\u3053\u306e `'Chainer'` \u3068\u8a00\u3046\u6587\u5b57\u5217\u306f\u30011 \u3064\u76ee\u306e\u5f15\u6570\u3067\u3042\u308b\u306b\u3082\u95a2\u308f\u3089\u305a\u3001`__init__()` \u30e1\u30bd\u30c3\u30c9\u306e\u5b9a\u7fa9\u3067\u306f 2 \u3064\u76ee\u306e\u5f15\u6570\u3067\u3042\u3063\u305f `name` \u306b\u6e21\u3055\u308c\u308b\u3002\n\u524d\u8ff0\u306e\u3088\u3046\u306b\u3001**\u30e1\u30bd\u30c3\u30c9\u306f\u3001\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u304b\u3089\u547c\u3073\u51fa\u3055\u308c\u308b\u3068\u304d\u81ea\u52d5\u7684\u306b\u7b2c\u4e00\u5f15\u6570\u306b\u305d\u306e\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u3078\u306e\u53c2\u7167\u3092\u6e21\u3059**\u305f\u3081\u3067\u3042\u308b\u3002\n\u3053\u306e\u81ea\u52d5\u7684\u306b\u6e21\u3055\u308c\u308b\u81ea\u8eab\u3078\u306e\u53c2\u7167\u306f\u3001\u547c\u3073\u51fa\u3057\u306e\u969b\u306b\u306f\u660e\u793a\u7684\u306b\u6307\u5b9a\u3057\u306a\u3044\u3002\n\u307e\u305f\u3001\u304b\u306a\u3089\u305a 1 \u3064\u76ee\u306e\u5f15\u6570\u306b\u81ea\u52d5\u7684\u306b\u6e21\u3055\u308c\u308b\u305f\u3081\u3001\u547c\u3073\u51fa\u3057\u6642\u306b\u660e\u793a\u7684\u306b\u4e0e\u3048\u3089\u308c\u305f\u5f15\u6570\u306f 2 \u3064\u76ee\u4ee5\u964d\u306e\u5f15\u6570\u306b\u6e21\u3055\u308c\u305f\u3082\u306e\u3068\u3057\u3066\u53d6\u308a\u6271\u308f\u308c\u308b\u3002\n\n\u305d\u308c\u3067\u306f\u6b21\u306b\u3001\u3053\u306e\u30af\u30e9\u30b9\u306b `hello()` \u3068\u8a00\u3046\u30e1\u30bd\u30c3\u30c9\u3092\u8ffd\u52a0\u3057\u3001\u547c\u3073\u51fa\u3059\u3068\u8ab0\u306e\u5bb6\u3067\u3042\u308b\u304b\u3092\u8868\u793a\u3059\u308b\u3068\u8a00\u3046\u6a5f\u80fd\u3092\u5b9f\u88c5\u3057\u3066\u307f\u308b\u3002\n\n\n```python\n# \u30af\u30e9\u30b9\u306e\u5b9a\u7fa9\nclass House:\n\n    # __init__() \u306e\u5b9a\u7fa9\n    def __init__(self, name):\n        self.name_plate = name\n\n    # \u30e1\u30bd\u30c3\u30c9\u306e\u5b9a\u7fa9\n    def hello(self):\n        print('{}\u306e\u5bb6\u3067\u3042\u308b\u3002'.format(self.name_plate))\n```\n\n\u305d\u308c\u3067\u306f\u30012 \u3064\u306e\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u3092\u4f5c\u6210\u3057\u3066\u3001\u305d\u308c\u305e\u308c\u304b\u3089 `hello()` \u30e1\u30bd\u30c3\u30c9\u3092\u547c\u3073\u51fa\u3057\u3066\u307f\u308b\u3002\n\n\n```python\nsato = House('\u4f50\u85e4')\nsuzuki = House('\u30b9\u30ba\u30ad')\n\nsato.hello()   # \u5b9f\u884c\u306e\u969b\u306b\u306f hello() \u306e\u5f15\u6570\u306b\u3042\u308b self \u306f\u7121\u8996\nsuzuki.hello() # \u5b9f\u884c\u306e\u969b\u306b\u306f hello() \u306e\u5f15\u6570\u306b\u3042\u308b self \u306f\u7121\u8996\n```\n\n    \u4f50\u85e4\u306e\u5bb6\u3067\u3042\u308b\u3002\n    \u30b9\u30ba\u30ad\u306e\u5bb6\u3067\u3042\u308b\u3002\n\n\n`sato` \u3068\u8a00\u3046\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u306e `name_plate` \u5c5e\u6027\u306b\u306f\u3001`'\u4f50\u85e4'` \u3068\u8a00\u3046\u6587\u5b57\u5217\u304c\u683c\u7d0d\u3055\u308c\u3066\u3044\u308b\u3002  \n`suzuki` \u3068\u8a00\u3046\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u306e `name_plate` \u5c5e\u6027\u306b\u306f\u3001`'\u30b9\u30ba\u30ad'` \u3068\u8a00\u3046\u6587\u5b57\u5217\u304c\u683c\u7d0d\u3055\u308c\u3066\u3044\u308b\u3002  \n\u305d\u308c\u305e\u308c\u306e\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u304b\u3089\u547c\u3073\u51fa\u3055\u308c\u305f `hello()` \u30e1\u30bd\u30c3\u30c9\u306f\u3001`self.name_plate` \u306b\u683c\u7d0d\u3055\u308c\u305f\u5225\u3005\u306e\u5024\u3092 `print()` \u3092\u7528\u3044\u3066\u8868\u793a\u3057\u3066\u3044\u308b\u3002\n\n\u3053\u306e\u3088\u3046\u306b\u3001\u540c\u3058\u6a5f\u80fd\u3092\u6301\u3064\u304c\u3001\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u306b\u3088\u3063\u3066\u4fdd\u6301\u3059\u308b\u30c7\u30fc\u30bf\u304c\u7570\u306a\u3063\u305f\u308a\u3001\u4e00\u90e8\u306e\u52d5\u4f5c\u304c\u7570\u306a\u3063\u305f\u308a\u3059\u308b\u3088\u3046\u306a\u30b1\u30fc\u30b9\u3092\u6271\u3046\u306e\u306b\u30af\u30e9\u30b9\u3092\u5229\u7528\u3059\u308b\u3002\nPython \u306e `int` \u578b\u3001`float` \u578b\u3001`str` \u578b\u2026\u306a\u3069\u306f\u3001\u5b9f\u969b\u306b\u306f `int` \u30af\u30e9\u30b9\u3001`float` \u30af\u30e9\u30b9\u3001`str` \u30af\u30e9\u30b9\u3067\u3042\u308a\u3001\u305d\u308c\u3089\u306e\u4e2d\u3067\u306f\u500b\u5225\u306e\u5909\u6570\uff08\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\uff09\u304c\u3069\u306e\u3088\u3046\u306a\u5024\u306b\u306a\u308b\u304b\u306b\u306f\u95a2\u4fc2\u306a\u304f\u3001\u540c\u3058\u578b\u3067\u3042\u308c\u3070\u5171\u901a\u3057\u3066\u6301\u3063\u3066\u3044\u308b\u6a5f\u80fd\u304c\u5b9a\u7fa9\u3055\u308c\u3066\u3044\u308b\u3002\n`5` \u3084 `0.3` \u3084 `'Chainer'` \u306a\u3069\u306f\u3001\u305d\u308c\u305e\u308c `int` \u30af\u30e9\u30b9\u306e\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u3001`float` \u30af\u30e9\u30b9\u306e\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u3001`str` \u30af\u30e9\u30b9\u306e\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u3067\u3042\u308b\u3002\n\n\u4ee5\u4e0a\u304b\u3089\u3001\u30af\u30e9\u30b9\u3092\u5b9a\u7fa9\u3059\u308b\u3068\u8a00\u3046\u306e\u306f\u3001**\u65b0\u3057\u3044\u578b\u3092\u4f5c\u308b**\u3068\u8a00\u3046\u3053\u3068\u3067\u3082\u3042\u308b\u3068\u5206\u304b\u308b\u3002\n\n**\u7d99\u627f**\n\n\u3042\u308b\u30af\u30e9\u30b9\u3092\u5b9a\u7fa9\u3057\u305f\u3089\u3001\u305d\u306e\u4e00\u90e8\u306e\u6a5f\u80fd\u3092\u5909\u66f4\u3057\u305f\u308a\u3001\u65b0\u3057\u3044\u6a5f\u80fd\u3092\u4ed8\u3051\u8db3\u3057\u305f\u308a\u3057\u305f\u304f\u306a\u308b\u3053\u3068\u304c\u3042\u308b\u3002\n\u3053\u308c\u3092\u5b9f\u73fe\u3059\u308b\u6a5f\u80fd\u304c**\u7d99\u627f (inheritance)** \u3067\u3042\u308b\u3002\n\u4f8b\u3048\u3070\u3001`Link` \u3068\u8a00\u3046\u30af\u30e9\u30b9\u3092\u5b9a\u7fa9\u3057\u3001\u305d\u306e\u30af\u30e9\u30b9\u3092\u7d99\u627f\u3057\u305f `Chain` \u3068\u8a00\u3046\u65b0\u3057\u3044\u30af\u30e9\u30b9\u3092\u4f5c\u3063\u3066\u307f\u308b\u3002\n\u307e\u305a\u3001`Link` \u30af\u30e9\u30b9\u3092\u5b9a\u7fa9\u3059\u308b\u3002\n\n\n```python\nclass Link:\n\n    def __init__(self):\n        self.a = 1\n        self.b = 2\n```\n\n\u3053\u306e `Link` \u3068\u8a00\u3046\u30af\u30e9\u30b9\u306f\u3001\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u5316\u3092\u884c\u3046\u969b\u306b\u306f 1 \u3064\u3082\u5f15\u6570\u3092\u3068\u3089\u306a\u3044\u304c\u3001\u5c5e\u6027\u3068\u3057\u3066 `a` \u3068 `b` \u306e 2 \u3064\u306e\u5909\u6570\u3092\u4fdd\u6301\u3057\u3001\u305d\u308c\u305e\u308c\u306b\u306f `__init__()` \u30e1\u30bd\u30c3\u30c9\u3067 1 \u3068 2 \u3068\u8a00\u3046\u5024\u304c\u4ee3\u5165\u3055\u308c\u308b\u3002\n\u3053\u306e\u30af\u30e9\u30b9\u306e\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u3092\u4f5c\u6210\u3057\u3066\u307f\u308b\u3002\n\n\n```python\nl = Link()\n\nl.a\n```\n\n\n\n\n    1\n\n\n\n\n```python\nl.b\n```\n\n\n\n\n    2\n\n\n\n`l` \u3068\u8a00\u3046 `Link` \u30af\u30e9\u30b9\u306e\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u304c\u6301\u3064 2 \u3064\u306e\u5c5e\u6027\u3092\u8868\u793a\u3057\u3066\u3044\u308b\u3002\n\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u5316\u3092\u884c\u3063\u305f\u969b\u306b `__init__()` \u30e1\u30bd\u30c3\u30c9\u306e\u4e2d\u3067\u4ee3\u5165\u3057\u3066\u3044\u305f\u5024\u304c\u3001\u8868\u793a\u3055\u308c\u3066\u3044\u308b\u3002\n\n\u6b21\u306b\u3001\u3053\u306e\u30af\u30e9\u30b9\u3092**\u7d99\u627f**\u3059\u308b\u3001`Chain` \u3068\u8a00\u3046\u30af\u30e9\u30b9\u3092\u5b9a\u7fa9\u3057\u3066\u307f\u308b\u3002\n\u7d99\u627f\u3092\u884c\u3046\u5834\u5408\u306f\u3001\u30af\u30e9\u30b9\u5b9a\u7fa9\u306e\u969b\u306b\u30af\u30e9\u30b9\u540d\u306b\u7d9a\u3051\u3066 `()` \u3092\u66f8\u304d\u3001\u305d\u306e\u4e2d\u306b\u30d9\u30fc\u30b9\u306b\u3057\u305f\u3044\u30af\u30e9\u30b9\u306e\u540d\u524d\u3092\u66f8\u304f\u3002\n`()` \u306e\u4e2d\u306b\u66f8\u304b\u308c\u305f\u30af\u30e9\u30b9\u306e\u3053\u3068\u3092\u3001\u5b9a\u7fa9\u3055\u308c\u308b\u30af\u30e9\u30b9\u306e**\u89aa\u30af\u30e9\u30b9**\u3068\u8a00\u3046\u3002\n\u305d\u308c\u306b\u5bfe\u3057\u3001`()` \u306e\u4e2d\u306b\u66f8\u304b\u308c\u305f\u30af\u30e9\u30b9\u304b\u3089\u307f\u308b\u3068\u3001\u5b9a\u7fa9\u3055\u308c\u308b\u30af\u30e9\u30b9\u306f**\u5b50\u30af\u30e9\u30b9**\u3068\u547c\u3070\u308c\u308b\u3002\n\u89aa\u304b\u3089\u5b50\u3078\u6a5f\u80fd\u304c\u53d7\u3051\u7d99\u304c\u308c\u308b\u305f\u3081\u3067\u3042\u308b\u3002\n\n\n```python\nclass Chain(Link):\n    \n    def sum(self):\n        return self.a + self.b\n```\n\n`Chain` \u30af\u30e9\u30b9\u306f `__init__()` \u30e1\u30bd\u30c3\u30c9\u306e\u5b9a\u7fa9\u3092\u6301\u3061\u306a\u3044\u3002\n`__init__()` \u30e1\u30bd\u30c3\u30c9\u304c\u5b9a\u7fa9\u3055\u308c\u3066\u3044\u306a\u3044\u5834\u5408\u3001\u89aa\u30af\u30e9\u30b9\u306e `__init__()`  \u30e1\u30bd\u30c3\u30c9\u304c\u81ea\u52d5\u7684\u306b\u547c\u3073\u51fa\u3055\u308c\u308b\u3002\n\u305d\u306e\u305f\u3081\u3001`Chain` \u30af\u30e9\u30b9\u3067\u306f\u4e00\u898b\u4f55\u3082\u5c5e\u6027\u3092\u5b9a\u7fa9\u3057\u3066\u3044\u306a\u3044\u3088\u3046\u306b\u898b\u3048\u308b\u304c\u3001\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u5316\u3092\u884c\u3046\u3068\u89aa\u30af\u30e9\u30b9\u3067\u3042\u308b `Link` \u306e `__init__()`  \u30e1\u30bd\u30c3\u30c9\u304c\u81ea\u52d5\u7684\u306b\u5b9f\u884c\u3055\u308c\u3001`a`\u3001`b` \u3068\u8a00\u3046\u5c5e\u6027\u304c\u5b9a\u7fa9\u3055\u308c\u308b\u3002\n\u4ee5\u4e0b\u306e\u30b3\u30fc\u30c9\u3067\u78ba\u8a8d\u3057\u3066\u307f\u308b\u3002\n\n\n```python\n# Chain \u30af\u30e9\u30b9\u3092\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u5316\nc = Chain()\n\nc.a\n```\n\n\n\n\n    1\n\n\n\n\n```python\nc.b\n```\n\n\n\n\n    2\n\n\n\n`Chain` \u30af\u30e9\u30b9\u306e `sum()` \u30e1\u30bd\u30c3\u30c9\u3067\u306f\u3001\u3053\u306e\u89aa\u30af\u30e9\u30b9\u306e `__init__()`  \u30e1\u30bd\u30c3\u30c9\u3067\u5b9a\u7fa9\u3055\u308c\u3066\u3044\u308b 2 \u3064\u306e\u5c5e\u6027\u3092\u8db3\u3057\u5408\u308f\u305b\u3066\u8fd4\u3057\u3066\u3044\u308b\u3002\n\u4eca\u4f5c\u6210\u3057\u305f\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u304b\u3089\u3001\u3053\u306e `sum()` \u30e1\u30bd\u30c3\u30c9\u3092\u547c\u3073\u51fa\u3057\u3066\u307f\u308b\u3002\n\n\n```python\n# sum \u30e1\u30bd\u30c3\u30c9\u3092\u5b9f\u884c\nc.sum()\n```\n\n\n\n\n    3\n\n\n\n\u3053\u306e\u3088\u3046\u306b\u3001**\u89aa\u30af\u30e9\u30b9\u3092\u7d99\u627f\u3057\u3001\u89aa\u30af\u30e9\u30b9\u306b\u7121\u304b\u3063\u305f\u65b0\u3057\u3044\u6a5f\u80fd\u304c\u8ffd\u52a0\u3055\u308c\u305f\u3001\u65b0\u3057\u3044\u30af\u30e9\u30b9\u3092\u5b9a\u7fa9\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002**\n\n\u305d\u308c\u3067\u306f\u3001\u3053\u306e `Chain` \u3068\u8a00\u3046\u30af\u30e9\u30b9\u306b\u3082 `__init__()`  \u30e1\u30bd\u30c3\u30c9\u3092\u5b9a\u7fa9\u3057\u3066\u3001\u65b0\u3057\u3044\u5c5e\u6027 `c` \u3092\u5b9a\u7fa9\u3057\u3001`sum()` \u30e1\u30bd\u30c3\u30c9\u3067\u306f\u89aa\u30af\u30e9\u30b9\u306e `a`\u3001`b` \u3068\u8a00\u3046\u5c5e\u6027\u3068\u3053\u306e\u65b0\u305f\u306a `c` \u3068\u8a00\u3046\u5c5e\u6027\u306e 3 \u3064\u306e\u548c\u3092\u8fd4\u3059\u3088\u3046\u306b\u5909\u66f4\u3057\u3066\u307f\u308b\u3002\n\n\n```python\nclass Chain(Link):\n\n    def __init__(self):\n        self.c = 5  # self.c \u3092\u65b0\u305f\u306b\u8ffd\u52a0\n    \n    def sum(self):\n        return self.a + self.b + self.c\n\n# \u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u5316\nC = Chain()\n```\n\n\n```python\n# error\n# C.sum()\n```\n\n\u30a8\u30e9\u30fc\u304c\u51fa\u305f\u3002\n\n**\u30a8\u30e9\u30fc\u30e1\u30c3\u30bb\u30fc\u30b8\u3092\u8aad\u3080\u3002**\n\n> AttributeError: 'Chain' object has no attribute 'a'\n\n`'Chain'` \u3068\u8a00\u3046\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u306f\u3001`'a'` \u3068\u8a00\u3046\u540d\u524d\u306e\u5c5e\u6027\u3092\u6301\u3063\u3066\u3044\u306a\u3044\u3001\u3068\u8a00\u308f\u308c\u3066\u3044\u308b\u3002\n`a` \u3068\u8a00\u3046\u5c5e\u6027\u306f\u3001`Chain` \u306e\u89aa\u30af\u30e9\u30b9\u3067\u3042\u308b `Link` \u306e `__init__()`  \u30e1\u30bd\u30c3\u30c9\u3067\u5b9a\u7fa9\u3055\u308c\u3066\u3044\u308b\u3002\n\u305d\u306e\u305f\u3081\u3001`Chain` \u30af\u30e9\u30b9\u3092\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u5316\u3059\u308b\u969b\u306b\u3001\u89aa\u30af\u30e9\u30b9\u3067\u3042\u308b `Link` \u306e `__init__()`  \u30e1\u30bd\u30c3\u30c9\u304c\u547c\u3070\u308c\u3066\u3044\u308b\u306e\u3067\u3042\u308c\u3070\u3001\u3053\u306e\u30a8\u30e9\u30fc\u306f\u8d77\u3053\u3089\u306a\u3044\u306f\u305a\u3067\u3042\u308b\u3002\n\u306a\u305c\u30a8\u30e9\u30fc\u3068\u306a\u3063\u3066\u3057\u307e\u3063\u305f\u306e\u3060\u308d\u3046\u304b\u3002\n\n\u305d\u308c\u306f\u3001`Chain` \u30af\u30e9\u30b9\u306b\u3082 `__init__()` \u30e1\u30bd\u30c3\u30c9\u3092\u5b9a\u7fa9\u3057\u305f\u305f\u3081\u3001\u89aa\u30af\u30e9\u30b9\u3067\u3042\u308b `Link` \u306e `__init__()`  \u30e1\u30bd\u30c3\u30c9\u304c\u4e0a\u66f8\u304d\u3055\u308c\u3066\u3057\u307e\u3044\u3001\u5b9f\u884c\u3055\u308c\u306a\u304b\u3063\u305f\u305f\u3081\u3067\u3042\u308b\u3002\n\u3057\u304b\u3057\u3001\u89aa\u30af\u30e9\u30b9\u306e `__init__()`  \u30e1\u30bd\u30c3\u30c9\u3092\u660e\u793a\u7684\u306b\u547c\u3076\u3053\u3068\u3067\u3001\u3053\u308c\u306f\u89e3\u6c7a\u3067\u304d\u308b\u3002\n\n\u305d\u308c\u306b\u306f\u3001`super()` \u3068\u8a00\u3046\u7d44\u307f\u8fbc\u307f\u95a2\u6570\u3092\u7528\u3044\u308b\u3002\n\u3053\u308c\u3092\u7528\u3044\u308b\u3068\u3001\u5b50\u30af\u30e9\u30b9\u304b\u3089\u89aa\u30af\u30e9\u30b9\u3092\u53c2\u7167\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\n```python\nclass Chain(Link):\n\n    def __init__(self):\n        # \u89aa\u30af\u30e9\u30b9\u306e `__init__()` \u30e1\u30bd\u30c3\u30c9\u3092\u547c\u3073\u51fa\u3059\n        super().__init__()\n        \n        # self.c \u3092\u65b0\u305f\u306b\u8ffd\u52a0\n        self.c = 5\n    \n    def sum(self):\n        return self.a + self.b + self.c\n\n# \u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u5316\nc = Chain()\n```\n\n\n```python\nc.sum()\n```\n\n\n\n\n    8\n\n\n\n\u4eca\u56de\u306f\u30a8\u30e9\u30fc\u304c\u8d77\u304d\u306a\u3044\u3002\n`Link` \u30af\u30e9\u30b9\u306e `__init__()`  \u30e1\u30bd\u30c3\u30c9\u306e\u5192\u982d\u3067\u3001\u307e\u305a\u89aa\u30af\u30e9\u30b9\u306e `__init__()`  \u30e1\u30bd\u30c3\u30c9\u3092\u5b9f\u884c\u3057\u3001`a`\u3001`b` \u3068\u8a00\u3046\u5c5e\u6027\u3092\u5b9a\u7fa9\u3057\u3066\u3044\u308b\u305f\u3081\u3067\u3042\u308b\u3002\n\n\u3042\u308b\u30af\u30e9\u30b9\u3092\u7d99\u627f\u3057\u3066\u4f5c\u3089\u308c\u305f\u30af\u30e9\u30b9\u3092\u3001\u3055\u3089\u306b\u7d99\u627f\u3057\u3066\u5225\u306e\u30af\u30e9\u30b9\u3092\u5b9a\u7fa9\u3059\u308b\u3053\u3068\u3082\u3067\u304d\u308b\u3002\n\n\n```python\nclass MyNetwork(Chain):\n    \n    def mul(self):\n        return self.a * self.b * self.c\n```\n\n`MyNetwork` \u30af\u30e9\u30b9\u306f\u3001`Link` \u30af\u30e9\u30b9\u3092\u7d99\u627f\u3057\u305f `Chain` \u30af\u30e9\u30b9\u3092\u3055\u3089\u306b\u7d99\u627f\u3057\u305f\u30af\u30e9\u30b9\u3067\u3001`a`\u3001`b`\u3001`c` \u3068\u8a00\u3046 3 \u3064\u306e\u5c5e\u6027\u3092\u639b\u3051\u5408\u308f\u305b\u305f\u7d50\u679c\u3092\u8fd4\u3059 `mul()` \u3068\u8a00\u3046\u30e1\u30bd\u30c3\u30c9\u3092\u6301\u3064\u3002\n\n\u3053\u306e\u30af\u30e9\u30b9\u306e\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u3092\u4f5c\u6210\u3057\u3001`mul()` \u3092\u5b9f\u884c\u3057\u3066\u307f\u308b\u3002\n\n\n```python\nnet = MyNetwork()\n\nnet.mul()\n```\n\n\n\n\n    10\n\n\n\n$1 \\times 2 \\times 5 = 10$ \u304c\u8fd4\u3063\u3066\u304d\u305f\u3002\n\n\u4ee5\u4e0a\u3067\u3001Python \u306e\u57fa\u672c\u306b\u3064\u3044\u3066\u306e\u89e3\u8aac\u3092\u7d42\u4e86\u3059\u308b\u3002\n\nPython \u306b\u306f\u4ed6\u306b\u3082\u3053\u3053\u3067\u306f\u7d39\u4ecb\u3055\u308c\u3066\u3044\u306a\u3044\u591a\u304f\u306e\u7279\u5fb4\u3084\u6a5f\u80fd\u304c\u3042\u308b\u3002\n\nPython\u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb \n\nhttps://docs.python.org/ja/3/tutorial/index.html\n\n&nbsp;\n\n# \u6a5f\u68b0\u5b66\u7fd2\u306b\u4f7f\u308f\u308c\u308b\u6570\u5b66\n\n\u6b21\u7ae0\u3088\u308a\u30c7\u30a3\u30fc\u30d7\u30e9\u30fc\u30cb\u30f3\u30b0\u3092\u542b\u3080\u6a5f\u68b0\u5b66\u7fd2\u306b\u5fc5\u8981\u306a\u6570\u5b66\u306e\n\n- \u5fae\u5206\n- \u7dda\u5f62\u4ee3\u6570\n- \u78ba\u7387\u7d71\u8a08\n\n\u306b\u3064\u3044\u3066\u3001\u7d39\u4ecb\u3057\u3066\u3044\u304f\u3002\n\n&nbsp;\n\n\u305d\u306e\u524d\u306b\u3001\u672c\u7ae0\u3067\u306f**\u6a5f\u68b0\u5b66\u7fd2 (machine learning)** \u306e\u8003\u3048\u65b9\u306b\u3064\u3044\u3066\u5927\u67a0\u3092\u63b4\u307f\u3001\u3069\u306e\u90e8\u5206\u3067\u305d\u308c\u305e\u308c\u306e\u9805\u76ee\u304c\u767b\u5834\u3059\u308b\u304b\u3092\u628a\u63e1\u3057\u3066\u304a\u304f\u3002\n\n&nbsp;\n\n\n**\u6a5f\u68b0\u5b66\u7fd2\u3068\u306f**\n\n\u6a5f\u68b0\u5b66\u7fd2\u306f\u3001\u4e0e\u3048\u3089\u308c\u305f\u30c7\u30fc\u30bf\u304b\u3089\u3001\u672a\u77e5\u306e\u30c7\u30fc\u30bf\u306b\u5bfe\u3057\u3066\u3082\u5f53\u3066\u306f\u307e\u308b\u898f\u5247\u3084\u30d1\u30bf\u30fc\u30f3\u3092\u62bd\u51fa\u3057\u305f\u308a\u3001\u305d\u308c\u3089\u3092\u5143\u306b\u672a\u77e5\u306e\u30c7\u30fc\u30bf\u3092\u5206\u985e\u3057\u305f\u308a\u3001\u4e88\u6e2c\u3057\u305f\u308a\u3059\u308b\u624b\u6cd5\u3092\u7814\u7a76\u3059\u308b\u5b66\u8853\u9818\u57df\u3067\u3042\u308b\u3002\n\n\u6a5f\u68b0\u5b66\u7fd2\u306f\u69d8\u3005\u306a\u6280\u8853\u306b\u5fdc\u7528\u3055\u308c\u3066\u304a\u308a\u3001\u4f8b\u3048\u3070\u753b\u50cf\u8a8d\u8b58\u3001\u97f3\u58f0\u8a8d\u8b58\u3001\u6587\u66f8\u5206\u985e\u3001\u533b\u7642\u8a3a\u65ad\u3001\u8ff7\u60d1\u30e1\u30fc\u30eb\u691c\u77e5\u3001\u5546\u54c1\u63a8\u85a6\u306a\u3069\u3001\u5e45\u5e83\u3044\u5206\u91ce\u3067\u91cd\u8981\u306a\u5f79\u5272\u3092\u679c\u305f\u3057\u3066\u3044\u308b\u3002\n\n&nbsp;\n\n\n**\u6559\u5e2b\u3042\u308a\u5b66\u7fd2\u306e\u8003\u3048\u65b9**\n\n\u6a5f\u68b0\u5b66\u7fd2\u306e\u4ee3\u8868\u7684\u306a\u554f\u984c\u8a2d\u5b9a\u3068\u3057\u3066\u3001**\u6559\u5e2b\u3042\u308a\u5b66\u7fd2 (supervised learning)** \u3068\u8a00\u3046\u3082\u306e\u304c\u3042\u308b\u3002\n\u3053\u308c\u306f\u3001\u554f\u984c\u306b\u5bfe\u3057\u3066\u4e88\u3081\u7b54\u3048\u3092\u7528\u610f\u3057\u3066\u304a\u304d\u3001\u4e88\u60f3\u3055\u308c\u305f\u7b54\u3048\u3068\u5b9f\u969b\u306e\u7b54\u3048\u306e\u9055\u3044\u304c\u5c0f\u3055\u304f\u306a\u308b\u3088\u3046\u306b\u8a13\u7df4\u3092\u884c\u3046\u65b9\u6cd5\u3067\u3042\u308b\u3002\n\n\u3082\u3046\u5c11\u3057\u5177\u4f53\u7684\u306b\u6559\u5e2b\u3042\u308a\u5b66\u7fd2\u306e\u8003\u3048\u65b9\u3092\u8aac\u660e\u3057\u3066\u307f\u308b\u3002\n\u4f8b\u3048\u3070\u3001\u4ee5\u4e0b\u306e\u56f3\u306e\u3088\u3046\u306a\u8d64\u3044\u70b9\u306e\u96c6\u307e\u308a\u304c\u3042\u3063\u305f\u3068\u3059\u308b\u3002\n\n**\u56f3\u8868**\n\n\n\n\u3053\u306e\u56f3\u306f\u3001\u6a2a\u8ef8\u304c $x$ \u8ef8\u3001\u7e26\u8ef8\u304c $t$ \u8ef8\u3068\u306a\u3063\u3066\u3044\u308b\u3002\n\u3053\u306e\u8d64\u3044\u70b9\u306e 1 \u3064 1 \u3064\u306f\u3001$x$ \u3068 $t$ \u306e\u5024\u306e\u7d44\u3092\u8868\u3057\u3066\u3044\u308b\u3002\n\u56f3\u304b\u3089\u3001$x = 0$ \u4ed8\u8fd1\u3067\u306f $t$ \u3082 $0$ \u4ed8\u8fd1\u306e\u5024\u3092\u3068\u308b\u3053\u3068\u304c\u591a\u3044\u3088\u3046\u3060\u3002\n\u307e\u305f\u3001$x = 200$ \u4ed8\u8fd1\u3067\u306f\u3001$t$ \u306f $40$ \u524d\u5f8c\u306e\u5024\u3092\u3068\u3063\u3066\u3044\u308b\u3088\u3046\u306b\u898b\u3048\u308b\u3002\n\u305d\u308c\u3067\u306f\u3001$x = -200$ \u306e\u3068\u304d\u3001$t$ \u306f\u3069\u306e\u3088\u3046\u306a\u5024\u3092\u3068\u308b\u3060\u308d\u3046\u304b\u3002\n\n\u3053\u306e\u3088\u3046\u306b\u3001\u4e0e\u3048\u3089\u308c\u305f\u30c7\u30fc\u30bf\u304b\u3089\u95a2\u4fc2\u6027\u3092\u4e88\u60f3\u3057\u3001\u672a\u77e5\u306e\u30c7\u30fc\u30bf\u306b\u5bfe\u3057\u3066\u3082\u7b4b\u306e\u3088\u3044\u898b\u901a\u3057\u3092\u7acb\u3066\u308b\u3053\u3068\u304c\u3001\u6559\u5e2b\u3042\u308a\u5b66\u7fd2\u306e\u4ee3\u8868\u7684\u306a\u76ee\u6a19\u306e 1 \u3064\u3067\u3042\u308b\u3002\n\n&nbsp;\n\n\u30e1\u30e2 $\\quad$ \u3053\u306e\u56f3\u306f\u30d3\u30c3\u30c8\u30de\u30c3\u30d7\u306e png \u3060\u304c\u3053\u306e\u3088\u3046\u306a\u56f3\u3092 matplotlib \u304b svg \u3067\u30b3\u30fc\u30c9\u3067\u66f8\u3044\u3066\u304a\u304d\u305f\u3044\u3002 \u5916\u306f\u4fe1\u7528\u304c\u3067\u304d\u306a\u3044\u3002 \u3044\u3064\u307e\u3067\u3042\u308b\u304b\u3001\u3068\u3044\u3046\u3053\u3068\u3068\u3001\u7d10\u4ed8\u3051\u65b9\u6cd5\u304c\u5909\u308f\u308b\u53ef\u80fd\u6027\u304c\u3042\u308b\u3002\n\n\u30a2\u30a4\u30c7\u30a2\u3068\u3057\u3066\u306f\u3001y=ax + b \u306e\u6570\u5f0f\u306e\u5404\u70b9\u304b\u3089\u30e9\u30f3\u30c0\u30e0\u306b\u9060\u3044\u70b9\u3092\u9069\u5f53\u306a\u6570\u30d7\u30ed\u30c3\u30c8\u3059\u308c\u3070\u3088\u3044\u3002 \u3084\u3063\u3066\u307f\u3088\u3046\u3002\n\n&nbsp;\n\n\n\n\n**\u76f4\u7dda\u306b\u3088\u308b\u8fd1\u4f3c**\n\n\u6b21\u306b\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306a\u76f4\u7dda\u306e\u65b9\u7a0b\u5f0f\u3092\u8003\u3048\u3066\u307f\u308b\u3002\n\n$$\nf(x) = wx + b\n\\tag{2.1}\n\\label{line}\n$$\n\n**\u56f3\u8868**\n\n\n\n\u3053\u308c\u306f\u30011 \u3064\u306e\u5165\u529b $x$ \u3092\u4e0e\u3048\u308b\u3068 1 \u3064\u306e\u51fa\u529b\u3092\u8fd4\u3059\u95a2\u6570 $f$ \u3092\u8868\u3057\u3066\u3044\u3066\u3001\u3053\u306e\u95a2\u6570\u306f\u50be\u304d $w$ \u3068\u5207\u7247 $b$ \u306e **2 \u3064\u306e\u30d1\u30e9\u30e1\u30fc\u30bf\u3067\u7279\u5fb4\u3065\u3051\u3089\u308c\u3066\u3044\u308b\u3002**\n\u4e0a\u306e\u56f3\u306f\u3001$w = 0.5$\u3001$b = 50$ \u306e\u5834\u5408\u3092\u8868\u3057\u3066\u3044\u308b\u3002\n\u3053\u3053\u3067\u3001\u521d\u3081\u306e\u56f3\u306b\u3042\u3063\u305f\u8d64\u3044\u70b9\u306e\u96c6\u307e\u308a\u306b\u898b\u3089\u308c\u308b $x$ \u3068 $t$ \u306e\u95a2\u4fc2\u3092\u3001\u3046\u307e\u304f\u5f0f $\\eqref{line}$ \u306e\u76f4\u7dda\u306b\u3088\u3063\u3066\u8fd1\u4f3c\u3059\u308b\u3053\u3068\u3092\u8003\u3048\u3066\u307f\u308b\u3002\n\n\u3053\u306e\u76f4\u7dda\u3092\u305d\u306e\u307e\u307e\u8d64\u3044\u70b9\u306e\u96c6\u307e\u308a\u306e\u4e0a\u306b\u304a\u304f\u3068\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u306a\u308b\u3002\n\n**\u56f3\u8868**\n\n\n\n\u3042\u307e\u308a\u3046\u307e\u304f $x$ \u3068 $t$ \u306e\u95a2\u4fc2\u3092\u8868\u3057\u3066\u3044\u308b\u3088\u3046\u306b\u306f\u898b\u3048\u306a\u3044\u3002\n\n\u5f0f $\\eqref{line}$ \u3067\u8868\u3055\u308c\u308b\u76f4\u7dda\u306f\u3001$w$ \u3068 $b$ \u304c\u6c7a\u307e\u308b\u3068\u3001\u3069\u306e\u3088\u3046\u306a\u76f4\u7dda\u306b\u306a\u308b\u304b\u304c\u6c7a\u5b9a\u3055\u308c\u308b\u3002\n\u3064\u307e\u308a\u3001\u3053\u306e $w$ \u3068 $b$ \u306e\u5024\u3092\u3046\u307e\u304f\u6c7a\u5b9a\u3057\u3066\u3001\u8d64\u3044\u70b9\u306e\u96c6\u307e\u308a\u306b\u3067\u304d\u308b\u3060\u3051\u6cbf\u3046\u3088\u3046\u306a\u76f4\u7dda\u3092\u898b\u3064\u3051\u308b\u3053\u3068\u304c\u3067\u304d\u308c\u3070\u3001\u65b0\u3057\u3044 $x$ \u304c\u4e0e\u3048\u3089\u308c\u305f\u3068\u304d\u306b\u3001$t$ \u306e\u5024\u304c\u3069\u306e\u3088\u3046\u306a\u5024\u306b\u306a\u308a\u305d\u3046\u304b\u3092\u4e88\u6e2c\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u305d\u3046\u3067\u3042\u308b\u3002\n\u3053\u306e\u3068\u304d\u3001\u672a\u77e5\u306e\u30c7\u30fc\u30bf\u306b\u5bfe\u3057\u3066\u3082\u7cbe\u5ea6\u826f\u304f\u4e88\u6e2c\u304c\u884c\u3048\u308b\u3053\u3068\u3092**\u6c4e\u5316\u6027\u80fd (generalizability)** \u304c\u9ad8\u3044\u3068\u8a00\u3046\u3002\n\n\u307e\u305f\u3001\u30d1\u30e9\u30e1\u30fc\u30bf $w$ \u3068 $b$ \u306b\u3088\u3063\u3066\u7279\u5fb4\u3065\u3051\u3089\u308c\u305f\u76f4\u7dda\u306e\u5f0f  $\\eqref{line}$ \u306e\u3088\u3046\u306a\u3001\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u4f7f\u3063\u3066\u4f55\u3089\u304b\u306e\u8a08\u7b97\u3092\u884c\u3046\u3053\u3068\u3067\u3001\u4e0e\u3048\u3089\u308c\u305f\u30c7\u30fc\u30bf\u306e\u7279\u5fb4\u3084\u95a2\u4fc2\u6027\u3092\u8868\u3059\u3082\u306e\u3092\u3001\u4ee5\u964d\u7c21\u5358\u306b**\u30e2\u30c7\u30eb (model)** \u3068\u547c\u3076\u3053\u3068\u306b\u3059\u308b\uff08[\u6ce8\u91c81](#note1)\uff09\u3002\n\n\u305d\u308c\u3067\u306f\u3001$x$ \u3068 $t$ \u306e\u95a2\u4fc2\u3092\u3088\u304f\u8868\u3059\u30e2\u30c7\u30eb\u306e\u30d1\u30e9\u30e1\u30fc\u30bf $w$ \u3068 $b$ \u306f\u3001\u3069\u3046\u3084\u3063\u3066\u6c7a\u5b9a\u3059\u308c\u3070\u3088\u3044\u306e\u3060\u308d\u3046\u304b\u3002\n\u5148\u7a0b\u306e\u3088\u3046\u306b\u3001\u4eba\u304c\u8d64\u3044\u70b9\u306e\u96c6\u307e\u308a\u3092\u76ee\u3067\u898b\u3066 $x$ \u3068 $t$ \u306e\u95a2\u4fc2\u306b\u5f53\u305f\u308a\u3092\u3064\u3051\u3001\u6700\u9069\u306a $w$ \u3068 $b$ \u306e\u5024\u3092\u4eba\u624b\u3067\u63a2\u308a\u5f53\u3066\u308b\u306e\u306f\u3001\u8d64\u3044\u70b9\u304c\u3082\u3057 3 \u6b21\u5143\u7a7a\u9593\u3084\u30014 \u6b21\u5143\u30015 \u6b21\u5143\u2026\u3068\u3044\u3063\u305f\u4eba\u9593\u306b\u306f\u60f3\u50cf\u3059\u308b\u3053\u3068\u304c\u96e3\u3057\u3044\u9ad8\u6b21\u5143\u7a7a\u9593\u306b\u6563\u3089\u3070\u3063\u3066\u3044\u305f\u3089\u3001\u76ee\u3067\u898b\u308b\u3053\u3068\u3082\u3067\u304d\u306a\u3044\u305f\u3081\u3001\u56f0\u96e3\u306b\u306a\u308b\u3002\n\u305d\u3053\u3067\u3001\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u306b\u3053\u308c\u3089\u306e\u8d64\u3044\u70b9\u306e\u30c7\u30fc\u30bf\u3092\u4e0e\u3048\u3066\u3001\u81ea\u52d5\u7684\u306b\u6700\u9069\u306a $w$ \u3068 $b$ \u3092\u63a2\u3055\u305b\u3088\u3046\u3068\u8a00\u3046\u306e\u304c\u3001\u6a5f\u68b0\u5b66\u7fd2\u3067\u884c\u308f\u308c\u308b\u4ee3\u8868\u7684\u306a\u51e6\u7406\u306e\u3072\u3068\u3064\u3067\u3042\u308b\u3002\n\n\n\n**\u76ee\u7684\u95a2\u6570**\n\n\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u306b\u3088\u3044\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u81ea\u52d5\u7684\u306b\u898b\u3064\u3051\u3066\u3082\u3089\u3046\u305f\u3081\u306b\u306f\u3001**\u4f55\u304c\u3088\u3044\u30d1\u30e9\u30e1\u30fc\u30bf\u306a\u306e\u304b**\u3068\u8a00\u3046\u6307\u6a19\u3092\u5b9a\u7fa9\u3059\u308b\u5fc5\u8981\u304c\u3042\u308b\u3002\n\u305d\u306e\u3088\u3046\u306a\u6307\u6a19\u3092\u8868\u3059\u95a2\u6570\u3092**\u76ee\u7684\u95a2\u6570 (objective function)** \u3068\u547c\u3076\u3002\n\n\u3053\u3053\u3067\u3001\u4e0a\u306e\u76f4\u7dda\u306e\u4f8b\u306b\u623b\u3063\u3066\u8003\u3048\u3066\u307f\u308b\u3002\n\u307e\u305a\u3001\u5f0f $\\eqref{line}$ \u306b\u3042\u308b $x$ \u3092\u4e0e\u3048\u308b\u3068\u3001$w$ \u3068 $b$ \u3092\u4f7f\u3063\u3066 $wx + b$ \u3068\u8a00\u3046\u8a08\u7b97\u304c\u884c\u308f\u308c\u308b\u3002\n\u305d\u306e\u7d50\u679c\u3092 $y$ \u3068\u8868\u3059\u3053\u3068\u306b\u3059\u308b\u3002\n\u3053\u3053\u3067\u3001$x$ \u3092**\u5165\u529b\u5909\u6570 (input variable)**\u3001$y$ \u3092**\u51fa\u529b\u5909\u6570 (output variable)** \u3068\u547c\u3076\u3002\n\u4eca\u3001\u4e0a\u56f3\u306e\u8d64\u3044\u70b9\u306e\u96c6\u307e\u308a\u304b\u3089 1 \u70b9\u3092\u9078\u3073\u51fa\u3057\u3001\u305d\u306e $x$ \u5ea7\u6a19\u306e\u5024\u3092\u5f0f $\\eqref{line}$ \u306b\u4e0e\u3048\u305f\u3068\u3059\u308b\u3002\n\u3053\u306e\u3068\u304d\u3001\u5f0f $\\eqref{line}$ \u306b\u4e0e\u3048\u3089\u308c\u305f\u5177\u4f53\u7684\u306a $x$ \u306e\u5024\u3092\u3001**\u5165\u529b\u5024 (input value)** \u3068\u547c\u3076\u3002\n\u305d\u3057\u3066\u3001\u30d1\u30e9\u30e1\u30fc\u30bf $w$ \u3068 $b$ \u3092\u7528\u3044\u3066\u8a08\u7b97\u3092\u884c\u3063\u305f\u7d50\u679c\u5f97\u3089\u308c\u308b\u5177\u4f53\u7684\u306a $y$ \u306e\u5024\u3092\u3001**\u4e88\u6e2c\u5024 (predicted value)** \u3068\u547c\u3076\u3002\n\u3053\u306e\u3068\u304d\u3001\u76f4\u7dda\u306e\u5f0f\u3067\u306f\u306a\u304f\u3001\u5b9f\u969b\u306e\u8d64\u3044\u70b9\u306e\u6301\u3064 $t$ \u306e\u5024\u306f\u3001\u3053\u306e\u5f0f\u304c\u4e88\u6e2c\u3057\u305f\u3044\u76ee\u6a19\u306e\u5024\u306a\u306e\u3067\u3001**\u76ee\u6a19\u5024 (target value)** \u3068\u547c\u3076\u3002\n\n\u76ee\u7684\u95a2\u6570\u306f\u591a\u304f\u306e\u5834\u5408\u3001\u30e2\u30c7\u30eb\u306e\u4e88\u6e2c\u5024\u3068\u76ee\u6a19\u5024\u3092\u53d7\u3051\u53d6\u3063\u3066\u3001\u305d\u306e\u9593\u306e\u5dee\u7570\u3092\u6e2c\u3063\u3066\u8fd4\u3059\u3088\u3046\u306a\u95a2\u6570\u3067\u3042\u308b\u3002\n\u5dee\u7570\u306f\u5c0f\u3055\u3051\u308c\u3070\u5c0f\u3055\u3044\u307b\u3069\u30e2\u30c7\u30eb\u306e\u4e88\u6e2c\u304c\u5f53\u305f\u3063\u3066\u3044\u308b\u3053\u3068\u3092\u610f\u5473\u3059\u308b\u305f\u3081\u3001\u3053\u306e\u5834\u5408\u306f\u76ee\u7684\u95a2\u6570\u306e\u5024\u3092\u6700\u5c0f\u306b\u3059\u308b\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u898b\u3064\u3051\u51fa\u3059\u306e\u304c\u76ee\u7684\u306b\u306a\u308b\u3002\n\n\n\n**\u4e8c\u4e57\u8aa4\u5dee\u95a2\u6570**\n\n\u76ee\u7684\u95a2\u6570\u306e\u5177\u4f53\u4f8b\u3092\u6319\u3052\u308b\u3002\n\u4f8b\u3048\u3070\u3001\u9069\u5f53\u306b\u8d64\u3044\u70b9\u3092 1 \u3064\u9078\u3073\u3001\u305d\u306e $x$ \u5ea7\u6a19\u304c $100$ \u3067\u3001 $t$ \u5ea7\u6a19\u304c $40$ \u3060\u3063\u305f\u3068\u3059\u308b\u3002\n\u3053\u306e\u5024\u3092\u3001$x_1 = 100, t_1 = 40$ \u306e\u3088\u3046\u306b\u304a\u3044\u3066\u307f\u308b\u3002\n\u305d\u3057\u3066\u3001\u5225\u306a\u70b9\u3082\u53d6\u308a\u51fa\u3057\u3066\u304d\u3066\u3001\u540c\u3058\u3088\u3046\u306b\u5ea7\u6a19\u5024 $(x, t)$ \u3092 $(x_2, t_2)$ \u3068\u66f8\u304f\u3053\u3068\u306b\u3059\u308b\u3002\n\u540c\u69d8\u306b\u3057\u3066\u3001200 \u500b\u8d64\u3044\u70b9\u3092\u53d6\u308a\u51fa\u3057\u3066\u304d\u305f\u3068\u3059\u308b\u3068\u3001200 \u500b\u306e $x$ \u306e\u5024 $x_1, x_2, \\dots, x_{200}$ \u3068 $t_1, t_2, \\dots, t_{200}$ \u304c\u5f97\u3089\u308c\u308b\u3002  \n\n\u3053\u306e $x_1, x_2, \\dots, x_{200}$ \u304b\u3089 $t_1, t_2, \\dots, t_{200}$ \u3092\u4e88\u6e2c\u3059\u308b\u306e\u304c\u76ee\u6a19\u3060\u3063\u305f\u3002  \n\u3064\u307e\u308a\u3001$x_1, x_2, \\dots, x_{200}$ \u304c\u5165\u529b\u5024\u3001$t_1, t_2, \\dots, t_{200}$ \u304c\u76ee\u6a19\u5024\u3067\u3042\u308b\u3002\n\n\u305d\u3057\u3066\u3001\u3053\u306e 200 \u500b\u306e $x$ \u306e\u5024\u5168\u3066\u306b\u5bfe\u3057\u3066\u3001\u5f0f $\\eqref{line}$ \u306b\u3088\u308b\u4e88\u6e2c\u5024 $y$ \u3092\u8a08\u7b97\u3057\u305f\u7d50\u679c\u3001$y_1, y_2, \\dots, y_{200}$ \u304c\u5f97\u3089\u308c\u305f\u3068\u3059\u308b\u3002\n\n\u3053\u306e\u3068\u304d\u3001\u3053\u308c\u3089\u306e\u4e88\u6e2c\u5024\u306e\u6b63\u78ba\u3055\u3092\u3001\u5bfe\u5fdc\u3059\u308b\u76ee\u6a19\u5024\u3068\u306e\u9593\u306e**\u5dee\u306e\u4e8c\u4e57**\u306b\u3088\u3063\u3066\u6e2c\u308b\u306e\u304c\u3001**\u4e8c\u4e57\u8aa4\u5dee\u95a2\u6570 (squared error function)** \u3068\u547c\u3070\u308c\u308b\u3082\u306e\u3067\u3042\u308b\u3002\n\n\u5177\u4f53\u7684\u306b\u306f\u3001$n$ \u500b\u76ee\u306e\u4e88\u6e2c\u5024\u3092 $y_n$\u3001\u76ee\u6a19\u5024\u3092 $t_n$ \u3068\u3059\u308b\u3068\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306a\u95a2\u6570\u3067\u3042\u308b\u3002\n\n$$\n\\mathcal{l} = (t_n - y_n)^2\n$$\n\n\u3053\u308c\u306f\u3001$n$ \u500b\u76ee\u306e\u30c7\u30fc\u30bf\u306b\u5bfe\u3059\u308b\u4e88\u6e2c\u5024\u3068\u76ee\u6a19\u5024\u306e\u5dee\u7570\u3092\u8868\u3057\u3066\u3044\u308b\u3002\n\u3057\u304b\u3057\u3001\u3042\u308b 1 \u3064\u306e\u30c7\u30fc\u30bf\u306b\u5bfe\u3057\u3066\u3060\u3051\u4e88\u6e2c\u304c\u3046\u307e\u304f\u3044\u3063\u3066\u3044\u305f\u3068\u3057\u3066\u3082\u3001\u305d\u308c\u4ee5\u5916\u306e\u30c7\u30fc\u30bf\u306b\u5bfe\u3057\u3066\u5168\u304f\u3046\u307e\u304f\u4e88\u6e2c\u3067\u304d\u306a\u3044\u306e\u3067\u3042\u308c\u3070\u3001\u305d\u306e\u30e2\u30c7\u30eb\u304c\u65b0\u3057\u3044\u5024\u306b\u5bfe\u3057\u3066\u6b63\u78ba\u306a\u4e88\u6e2c\u3092\u884c\u3046\u3053\u3068\u306f\u56f0\u96e3\u3067\u3042\u308b\u3068\u8003\u3048\u3089\u308c\u308b\u3002\n\u305d\u3053\u3067\u3001200 \u500b\u306e\u30c7\u30fc\u30bf\u5168\u3066\u306b\u6e21\u3063\u3066\u3001\u3053\u306e\u4e8c\u4e57\u8aa4\u5dee\u3092\u8db3\u3057\u5408\u308f\u305b\u3001\u30c7\u30fc\u30bf\u6570\u306e 200 \u3067\u5272\u3063\u3066\u5e73\u5747\u3092\u3068\u3063\u305f\u3082\u306e\u3092\u8003\u3048\u308b\u3002\n\n$$\nL = \\frac{1}{200} \\sum_{n=1}^{200} (t_n - y_n)^2\n$$\n\n$\\sum$ \u3068\u8a00\u3046\u8a18\u53f7\u306f\u3001**\u7dcf\u548c**\u3092\u8868\u3059\u3002\n\u4e0a\u306e\u5f0f\u306f\u3001$(t_n - y_n)^2$ \u306e\u5024\u3092\u3001$n = 1$ \u304b\u3089\u9806\u756a\u306b $n = 2, n = 3, \\dots, n = 200$ \u307e\u3067\u8a08\u7b97\u3057\u3066\u3044\u304d\u3001\u5168\u3066\u3092\u8db3\u3057\u5408\u308f\u305b\u3001$200$ \u3067\u5272\u308b\u3001\u3068\u8a00\u3046\u3053\u3068\u3092\u610f\u5473\u3059\u308b\u3002\n\n\u3053\u308c\u306f\u3001**\u5e73\u5747\u4e8c\u4e57\u8aa4\u5dee (mean squared error)** \u3068\u547c\u3070\u308c\u3001\u9023\u7d9a\u5024\u3092\u4e88\u6e2c\u3059\u308b\u56de\u5e30\u554f\u984c\u306a\u3069\u3067\u3088\u304f\u7528\u3044\u3089\u308c\u308b\u4ee3\u8868\u7684\u306a\u76ee\u7684\u95a2\u6570\u306e 1 \u3064\u3067\u3042\u308b\u3002\n\u3053\u306e\u95a2\u6570\u306f\u3001\u4e88\u6e2c\u5024\u3068\u76ee\u6a19\u5024\u304c\u3059\u3079\u3066\u306e $n$ \u306b\u304a\u3044\u3066\u5b8c\u5168\u306b\u4e00\u81f4\u3059\u308b\u3068\u304d\u3060\u3051 $0$ \u306b\u306a\u308a\u3001\u305d\u308c\u4ee5\u5916\u3067\u306f\u5fc5\u305a\u6b63\u306e\u5024\u3092\u3068\u308b\u3002\n\u3088\u3063\u3066\u3001\u3053\u306e\u76ee\u7684\u95a2\u6570\u306e\u5024\u3092\u6700\u5c0f\u306b\u3059\u308b $w$ \u3068 $b$ \u304c\u3001\u6c42\u3081\u305f\u3044\u6700\u9069\u306a\u30d1\u30e9\u30e1\u30fc\u30bf\u3067\u3042\u308b\u3002\n\u300c\u3088\u3044\u30d1\u30e9\u30e1\u30fc\u30bf\u3068\u306f\u4f55\u304b\u300d\u304c\u5b9a\u91cf\u7684\u306b\u5b9a\u7fa9\u3067\u304d\u305f\u306e\u3067\u3001\u6b21\u306f\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u306b\u89e3\u3092\u63a2\u7d22\u3055\u305b\u308b\u65b9\u6cd5\u3092\u8003\u3048\u308b\u3002\n\n\n\n**\u76ee\u7684\u95a2\u6570\u306e\u6700\u9069\u5316**\n\n\u3042\u308b\u95a2\u6570\u3092\u6700\u5c0f\u306b\u3059\u308b\u5165\u529b\u5909\u6570\u306e\u5024\u3092\u6c42\u3081\u308b\u3053\u3068\u3092\u6700\u9069\u5316\u3068\u8a00\u3046\u3002\u3053\u306e\u6700\u9069\u5316\u3092\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u3067\u81ea\u52d5\u7684\u306b\u884c\u3046\u306b\u306f\u3001\u3069\u3046\u3059\u308c\u3070\u3088\u3044\u306e\u3060\u308d\u3046\u304b\u3002\n\u4f8b\u3048\u3070\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306a\u95a2\u6570\u304c\u3042\u308b\u3068\u3059\u308b\u3002\n\u6a2a\u8ef8\u304c\u5165\u529b\u306e\u5024\u3001\u7e26\u8ef8\u304c\u51fa\u529b\u306e\u5024\u3067\u3042\u308b\u3002\n\n**\u56f3\u8868**\n\n\n\n\u3053\u306e\u3068\u304d\u3001\u95a2\u6570\u306b\u9069\u5f53\u306a\u5024\u3092\u307e\u305a\u5165\u529b\u3057\u3066\u307f\u3066\u3001\u5f97\u3089\u308c\u305f\u5024\u3092\u4f7f\u3063\u3066\u305d\u306e\u5024\u304c\u5c0f\u3055\u304f\u306a\u308a\u305d\u3046\u306a\u65b9\u5411\u306b\u5165\u529b\u3092\u5c11\u3057\u52d5\u304b\u3059\u3001\u3068\u8a00\u3046\u3053\u3068\u3092\u7e70\u308a\u8fd4\u3057\u884c\u3063\u3066\u3001\u95a2\u6570\u304c\u6700\u5c0f\u5024\u3092\u3068\u308b\u5165\u529b\u5024\u3092\u63a2\u7d22\u3059\u308b\u3001\u3068\u8a00\u3046\u65b9\u6cd5\u304c\u3042\u308b\u3002\n\n\n\n**\u6a5f\u68b0\u5b66\u7fd2\u3067\u4f7f\u308f\u308c\u308b\u6570\u5b66**\n\n\u3053\u306e\u3088\u3046\u306a\u6700\u9069\u5316\u3092\u884c\u3046\u306e\u306b\u5fc5\u8981\u306b\u306a\u308b\u306e\u304c**\u5fae\u5206 (differential)** \u306e\u77e5\u8b58\u3067\u3042\u308b\u3002\n\u306a\u305c\u306a\u3089\u3001\u300c\u5165\u529b\u3092\u3069\u3061\u3089\u306b\u52d5\u304b\u305b\u3070\u51fa\u529b\u304c\u5c0f\u3055\u306a\u5024\u306b\u306a\u308a\u305d\u3046\u304b\u300d\u3068\u8a00\u3046\u3053\u3068\u3092\u77e5\u308b\u305f\u3081\u306b\u306f\u3001\u5bfe\u8c61\u306e\u95a2\u6570\u3092\u5fae\u5206\u3059\u308b\u5fc5\u8981\u304c\u3042\u308b\u304b\u3089\u3067\u3042\u308b\u3002\u8a73\u7d30\u306f\u6b21\u7ae0\u3067\u8aac\u660e\u3059\u308b\u3002\n\n\u307e\u305f\u3001\u521d\u3081\u306b\u3042\u3052\u305f\u8d64\u3044\u70b9\u306e\u96c6\u307e\u308a\u306b\u6700\u3082\u3088\u304f\u6cbf\u3046\u3088\u3046\u306a\u76f4\u7dda\u3092\u6c42\u3081\u308b\u554f\u984c\u3067\u306f\u30011 \u3064\u306e\u5024\u3092\u5165\u529b\u3057\u3066 1 \u3064\u306e\u5024\u304c\u51fa\u529b\u3055\u308c\u308b\u95a2\u6570\u3092\u8003\u3048\u3066\u3044\u305f\u304c\u3001\u8907\u6570\u306e\u5024\u3092\u540c\u6642\u306b\u6271\u3044\u305f\u3044\u3068\u304d\u306b\u5fc5\u8981\u306b\u306a\u308b\u306e\u304c\u3001**\u7dda\u5f62\u4ee3\u6570 (linear algebra)** \u306e\u77e5\u8b58\u3067\u3042\u308b\u3002\n\n\u3055\u3089\u306b\u3001\u8d64\u3044\u70b9\u304c\u3082\u3057\u672c\u5f53\u306f\u76f4\u7dda\u4e0a\u306b\u3074\u3063\u305f\u308a\u6cbf\u3046\u3088\u3046\u306a\u30c7\u30fc\u30bf\u3067\u3042\u3063\u305f\u306e\u306b\u3001\u89b3\u6e2c\u6642\u306b\u4f55\u3089\u304b\u306e\u7406\u7531\u3067\u30ce\u30a4\u30ba\u304c\u4e57\u3063\u3066\u3057\u307e\u3063\u305f\u304c\u305f\u3081\u306b\u76f4\u7dda\u306e\u5468\u8fba\u306b\u3070\u3089\u3064\u3044\u3066\u51fa\u3066\u304d\u3066\u3044\u308b\u306e\u3060\u3068\u3057\u305f\u3089\u3001\u305d\u306e\u30ce\u30a4\u30ba\u304c\u3069\u306e\u7a0b\u5ea6\u306e\u7bc4\u56f2\u3067\u5024\u306e\u30ba\u30ec\u3092\u767a\u751f\u3055\u305b\u308b\u3082\u306e\u306a\u306e\u304b\u3001\u898b\u5f53\u3092\u3064\u3051\u3066\u304a\u304d\u305f\u304f\u306a\u308b\u304b\u3082\u77e5\u308c\u306a\u3044\u3002\n\u305d\u3046\u3044\u3063\u305f\u3068\u304d\u306b\u5fc5\u8981\u306b\u306a\u308b\u306e\u304c\u3001**\u78ba\u7387(probability)\u30fb\u7d71\u8a08 (statistics)** \u306e\u77e5\u8b58\u3067\u3042\u308b\u3002\n\n\u3053\u306e 3 \u3064\u306b\u3064\u3044\u3066\u3001\u6a5f\u68b0\u5b66\u7fd2\u306e\u5b66\u7fd2\u306b\u5fc5\u8981\u3068\u306a\u308b\u6700\u4f4e\u9650\u306e\u77e5\u8b58\u306b\u7d5e\u3063\u3066\u4ee5\u964d\u306e 3 \u7ae0\u3067\u89e3\u8aac\u3092\u884c\u3046\u3002\n\n\u305d\u308c\u3067\u306f\u3001\u6b21\u7ae0\u306f\u307e\u305a\u5fae\u5206\u306b\u3064\u3044\u3066\u3067\u3042\u308b\u3002\n\n<hr />\n\n\n# \u3044\u307e\u3053\u3053\n\n# \u5fae\u5206\u306e\u57fa\u790e\n\n\n\n**\u5fae\u5206\u3068\u95a2\u6570\u6700\u5c0f\u5316\u306e\u95a2\u4fc2**\n\n\u524d\u7ae0\u3067\u5fae\u5206\u304c\u76ee\u7684\u95a2\u6570\u306e\u6700\u5c0f\u5316\u306b\u5f79\u7acb\u3064\u3068\u7d39\u4ecb\u3057\u305f\u3002\u672c\u7bc0\u3067\u306f\u307e\u305a\u5177\u4f53\u4f8b\u3092\u7528\u3044\u3066\u305d\u306e\u3053\u3068\u3092\u76f4\u611f\u7684\u306b\u7406\u89e3\u3059\u308b\u3002\n\u4f8b\u3068\u3057\u3066\u3001\u4e0b\u56f3\u306e\u3088\u3046\u306a\u4e0b\u5411\u304d\u306b\u304f\u307c\u3093\u3060\u5f62\u3092\u3057\u305f\u95a2\u6570\u304c\u3069\u3053\u3067\u6700\u5c0f\u5024\u3092\u3068\u308b\u304b\u3092\u63a2\u3059\u554f\u984c\u3092\u8003\u3048\u308b\u3002\n\n**\u56f3\u8868**\n\n\n\n\u9069\u5f53\u306a\u70b9 $\\theta_{1}$ \u3067\u3053\u306e\u95a2\u6570\u306e\u30b0\u30e9\u30d5\u306b\u63a5\u3059\u308b\u76f4\u7dda\uff08**\u63a5\u7dda**\uff09\u3092\u8003\u3048\u308b\uff08[\u6ce8\u91c81](#note1)\uff09\u3002\n\u4eee\u306b\u3053\u306e\u63a5\u7dda\u306e\u50be\u304d\u304c $+3$ \u3001\u3059\u306a\u308f\u3061\u6b63\u306e\u5024\u3067\u3042\u3063\u305f\u3068\u3059\u308b\u3002\u3053\u306e\u6642\u3001\u63a5\u7dda\u306f\u53f3\u306b\u9032\u3080\u307b\u3069\u9ad8\u3055\u304c\u4e0a\u304c\u308a\uff0c\u9006\u306b\u5de6\u306b\u9032\u3080\u307b\u3069\u9ad8\u3055\u304c\u4e0b\u304c\u308b\u3002\n$\\theta_{1}$ \u306e\u5468\u8fba\u3067\u306f\u3001\u95a2\u6570\u306e\u30b0\u30e9\u30d5\u3068\u63a5\u7dda\u306f\u975e\u5e38\u306b\u8fd1\u304f\u3001\u4e21\u8005\u306f\u307b\u3068\u3093\u3069\u898b\u5206\u3051\u308b\u3053\u3068\u304c\u3067\u304d\u306a\u3044\u3002\n\u3059\u308b\u3068\u3001\u95a2\u6570\u3082\u63a5\u7dda\u3068\u540c\u3058\u3088\u3046\u306b $\\theta_{1}$ \u53f3\u306b\u9032\u3080\u3068\u5897\u52a0\u3057\uff0c\u5de6\u306b\u9032\u3080\u3068\u6e1b\u5c11\u3057\u3066\u3044\u308b\u3053\u3068\u304c\u308f\u304b\u308b\u3002\n\n\n**\u56f3\u8868**\n\n\n\n\u6b21\u306b\u3001\u30b0\u30e9\u30d5\u4e0a\u306e\u5225\u306e\u70b9 $\\theta_{2}$ \u306b\u304a\u3044\u3066\u3053\u306e\u30b0\u30e9\u30d5\u306b\u63a5\u3059\u308b\u63a5\u7dda\u3092\u8003\u3048\u308b\u3002\n\u4eca\u5ea6\u306f\u63a5\u7dda\u306e\u50be\u304d\u304c $-1$ \u3067\u3042\u308b\u3068\u3059\u308b\u3002\u50be\u304d\u304c\u8ca0\u306e\u305f\u3081\u3001\u63a5\u7dda\u306f\u53f3\u80a9\u4e0b\u304c\u308a\u306e\u76f4\u7dda\u3067\u3042\u308b\u3002\n\u30b0\u30e9\u30d5\u306f\u63a5\u7dda\u3068\u975e\u5e38\u306b\u8fd1\u3044\u305f\u3081\u3001\u30b0\u30e9\u30d5\u3082 $\\theta_{2}$ \u306e\u5468\u8fba\u3067\u306f\u3001\u540c\u3058\u3088\u3046\u306b\u53f3\u80a9\u4e0b\u304c\u308a\u3067\u3042\u308b\u3068\u308f\u304b\u308b\u3002\n\n\n**\u56f3\u8868**\n\n\n\n\u6700\u5f8c\u306b\u3061\u3087\u3046\u3069\u30b0\u30e9\u30d5\u306e\u8c37\u3068\u306a\u3063\u3066\u3044\u308b\u70b9 $\\theta_{3}$ \u3092\u8003\u3048\u308b\u3002\n\u56f3\u3092\u898b\u3066\u5206\u304b\u308b\u901a\u308a\u3001\u95a2\u6570\u306f\u3053\u306e\u70b9\u3067\u6700\u5c0f\u5024\u3092\u53d6\u308b\u3002\n\u4e00\u65b9\u3001\u70b9 $\\theta_{3}$ \u3067\u30b0\u30e9\u30d5\u306b\u63a5\u3059\u308b\u63a5\u7dda\u306f\u6c34\u5e73\u3001\u3059\u306a\u308f\u3061**\u50be\u304d\u304c0**\u3067\u3042\u308b\u3002\n\n\u3053\u308c\u307e\u3067\u306e\u89b3\u5bdf\u3092\u307e\u3068\u3081\u308b\u3068\u3001\u63a5\u7dda\u306e\u50be\u304d\u3068\u95a2\u6570\u306e\u632f\u308b\u821e\u3044\u306b\u306f\u6b21\u306e\u95a2\u4fc2\u304c\u3042\u308b\u3053\u3068\u304c\u308f\u304b\u308b\u3002\n\n- \u3042\u308b\u70b9\u3067\u63a5\u3059\u308b\u63a5\u7dda\u306e\u50be\u304d\u304c\u6b63\u306a\u3089\u3070\u3001\u305d\u306e\u70b9\u306e\u8fd1\u304f\u3067\u30b0\u30e9\u30d5\u306f\u53f3\u80a9\u4e0a\u304c\u308a\uff08= \u5de6\u306b\u9032\u3080\u3068\u9ad8\u3055\u304c\u4e0b\u304c\u308b\uff09\n- \u3042\u308b\u70b9\u3067\u63a5\u3059\u308b\u63a5\u7dda\u306e\u50be\u304d\u304c\u8ca0\u306a\u3089\u3070\u3001\u305d\u306e\u70b9\u306e\u8fd1\u304f\u3067\u30b0\u30e9\u30d5\u306f\u53f3\u80a9\u4e0b\u304c\u308a\uff08= \u53f3\u306b\u9032\u3080\u3068\u9ad8\u3055\u304c\u4e0b\u304c\u308b\uff09\n- \u95a2\u6570\u304c\u6700\u5c0f\u5024\u3092\u3068\u308b\u70b9\u306b\u63a5\u3059\u308b\u63a5\u7dda\u306e\u50be\u304d\u306f $0$ \u3067\u3042\u308b\n\n\u3064\u307e\u308a\u3001\u95a2\u6570\u306e\u6700\u5c0f\u5024\u3092\u3068\u308b\u70b9\u3092\u6c42\u3081\u308b\u554f\u984c\u3067\u306f\u3001\u63a5\u7dda\u306e\u50be\u304d\u304c $0$ \u3068\u306a\u308b\u70b9\u304c\u7b54\u3048\u306e\u5019\u88dc\uff08[\u6ce8\u91c82](#note2)\uff09\u3068\u306a\u308b\u3053\u3068\u304c\u308f\u304b\u308b\u3002\n\u672c\u7ae0\u3067\u8aac\u660e\u3059\u308b\u3088\u3046\u306b\u3001**\u5fae\u5206\u3092\u7528\u3044\u308b\u3068\u63a5\u7dda\u306e\u50be\u304d\u3092\u8a08\u7b97\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b**\u3002\n\u3053\u306e\u3053\u3068\u304b\u3089\u3001\u5fae\u5206\u304c\u95a2\u6570\u306e\u6700\u5c0f\u5316\u554f\u984c\u306b\u6709\u7528\u306a\u30c4\u30fc\u30eb\u3067\u3042\u308b\u3053\u3068\u304c\u308f\u304b\u308b\u3002\n\n\u4ee5\u964d\u3067\u306f\u3001\u5fae\u5206\u306e\u5b9a\u7fa9\u3068\u5fae\u5206\u306b\u95a2\u3059\u308b\u516c\u5f0f\u3092\u7d39\u4ecb\u3059\u308b\u3002\u3055\u3089\u306b\u3001\u5165\u529b\u304c\u591a\u5909\u6570\u306e\u95a2\u6570\u3067\u306e\u5fae\u5206\uff08\u504f\u5fae\u5206\uff09\u306b\u3064\u3044\u3066\u3082\u89e3\u8aac\u3059\u308b\u3002\n\n## 2 \u70b9\u9593\u3092\u901a\u308b\u76f4\u7dda\u306e\u50be\u304d\n\n\u63a5\u7dda\u306e\u50be\u304d\u3068\u5fae\u5206\u306e\u95a2\u4fc2\u3092\u8abf\u3079\u308b\u305f\u3081\u3001\u307e\u305a\u306f2\u70b9\u3092\u901a\u308b\u76f4\u7dda\u306e\u50be\u304d\u3092\u6c42\u3081\u308b\u554f\u984c\u3092\u8003\u3048\u308b\u3002\n\n**\u56f3\u8868**\n\n\n\n\u76f4\u7dda\u306e\u50be\u304d\u306f \u300c$y$ \uff08\u7e26\u65b9\u5411\uff09\u306e\u5897\u52a0\u91cf / $x$ \uff08\u6a2a\u65b9\u5411\uff09\u306e\u5897\u52a0\u91cf\u300d\u3067\u8a08\u7b97\u3067\u304d\u308b\u306e\u3067\u3001\u4e0a\u56f3\u306e\u76f4\u7dda\u306e\u50be\u304d $a$ \u306f\u3001\n\n$$\na = \\dfrac{f(x_{2}) - f(x_{1})}{x_{2}-x_{1}}\n$$\n\n\u3067\u6c42\u3081\u3089\u308c\u308b\u3002\n\n## \u63a5\u7dda\u306e\u50be\u304d\n\n\u4e0a\u56f3\u3067\u306e\u70b9 $x_1$ \u306b\u304a\u3051\u308b\u63a5\u7dda\u306e\u50be\u304d\u3092\u6c42\u3081\u308b\u305f\u3081\u306b\u3001\u3082\u3046\u4e00\u65b9\u306e\u70b9 $x_2$ \u3092 $x_1$ \u306b\u8fd1\u3065\u3051\u3066\u3044\u304f\u3002\u305f\u3060\u3057\u3001 $x_1$ \u3068 $x_2$ \u304c\u5b8c\u5168\u306b\u540c\u3058\u306b\u306a\u3063\u3066\u3057\u307e\u3046\u3068\u3001$x$ \u65b9\u5411\u3001 $y$ \u65b9\u5411\u306e\u5897\u52a0\u91cf\u304c\u3069\u3061\u3089\u3082 $0$ \u306b\u306a\u3063\u3066\u3057\u307e\u3046\u305f\u3081\u3001\u50be\u304d\u306f $0/0$ \u3067\u8a08\u7b97\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u306a\u3044\u3002\n\u305d\u3053\u3067 2 \u70b9\u306f\u7570\u306a\u308b\u70b9\u3067\u3042\u308a\u3064\u3064\u3001 $x_2$ \u3092\u9650\u308a\u306a\u304f $x_1$ \u306b\u8fd1\u3065\u3051\u3066\u3044\u3063\u305f\u6642\u3001\u76f4\u7dda\u306e\u50be\u304d\u304c\u3069\u306e\u3088\u3046\u306b\u632f\u308b\u821e\u3046\u304b\u3092\u898b\u308b\u5fc5\u8981\u304c\u3042\u308b\u3002\u3053\u308c\u3092\u6570\u5f0f\u7684\u306b\u8868\u73fe\u3059\u308b\u306b\u306f\u3001**\u6975\u9650**\u306e\u8003\u3048\u304c\u5fc5\u8981\u306b\u306a\u308b\u3002\n\n\u6975\u9650\u3067\u306f\u3001\u5909\u6570\u304c\u3042\u308b\u5024\u306b\u9650\u308a\u306a\u304f\u8fd1\u3065\u304f\u3068\u304d\u3001\u305d\u306e\u5909\u6570\u306b\u3088\u3063\u3066\u8a18\u8ff0\u3055\u308c\u308b\u95a2\u6570\u304c\u3069\u306e\u3088\u3046\u306a\u5024\u306b\u8fd1\u3065\u304f\u304b\u3092\u8003\u3048\u308b\u3002\n\u95a2\u6570 $f$ \u306b\u5bfe\u3057\u3001$h$ \u3068\u8a00\u3046\u5909\u6570\u3092 $a$ \u306b\u8fd1\u3065\u3051\u3066\u3044\u3063\u305f\u3068\u304d\u306e $f(h)$ \u304c\u8fd1\u3065\u304f\u5024\u3092 $\\lim$ \u3068\u8a00\u3046\u8a18\u53f7\u3092\u7528\u3044\u3066\n\n$$\n\\displaystyle \\lim _{h\\rightarrow a} f(h)\n$$\n\n\u3068\u66f8\u304f\u3002\u4f8b\u3048\u3070\u3001 $h$ \u3092\u9650\u308a\u306a\u304f $0$ \u306b\u8fd1\u3065\u3051\u305f\u6642\u306b\u3001 $3h$ \u3082\u9650\u308a\u306a\u304f $0$ \u306b\u8fd1\u3065\u3044\u3066\u3044\u304f\u3002\n\u5f93\u3063\u3066\n\n$$\n\\displaystyle \\lim _{h\\rightarrow 0} 3h=0\n$$\n\n\u3067\u3042\u308b\u3002\u3082\u3063\u3068\u4e00\u822c\u306b $n$ \u3092\u81ea\u7136\u6570\u3001 $c$ \u3092\u5b9a\u6570\u3068\u3057\u3066\u3001\n\n$$\n\\displaystyle \\lim _{h\\rightarrow a} c h^n=c a^n\n$$\n\n\u304c\u6210\u7acb\u3059\u308b\u3002\u3053\u308c\u3060\u3051\u898b\u308b\u3068\u5358\u306b\u95a2\u6570 $\\lim _{h\\rightarrow a} f(h)$ \u306f $h$ \u306b $a$ \u3092\u4ee3\u5165\u3057\u305f\u5024 $f(a)$ \u306e\u3088\u3046\u306b\u601d\u3048\u308b\u304b\u3082\u77e5\u308c\u306a\u3044\u3002\u3057\u304b\u3057\u3001\u4eca\u8003\u3048\u3066\u3044\u308b\u76f4\u7dda\u306e\u50be\u304d\u306e\u5834\u5408\u3001\u305d\u306e\u3088\u3046\u306a\u4ee3\u5165\u64cd\u4f5c\u3092\u884c\u3046\u3068\u5148\u7a0b\u306e\u3088\u3046\u306b $0/0$ \u306e\u5f62\u304c\u73fe\u308c\u3066\u3057\u307e\u3046\u305f\u3081\u3001\u5358\u7d14\u306a\u4ee3\u5165\u3067\u306f\u6975\u9650\u3092\u6c42\u3081\u308b\u3053\u3068\u306f\u3067\u304d\u306a\u3044\u3002\n\u6975\u9650\u306e\u8a08\u7b97\u65b9\u6cd5\u306f\u5f8c\u307b\u3069\u8a73\u3057\u304f\u89e3\u8aac\u3059\u308b\u3002\n\n\u305d\u308c\u3067\u306f\u3001\u4e0b\u56f3\u306e\u3042\u308b\u70b9 $x$ \u306b\u304a\u3051\u308b\u63a5\u7dda\u306e\u50be\u304d $a$ \u3092\u6c42\u3081\u3066\u3044\u3053\u3046\u3002\n\n**\u56f3\u8868**\n\n\n\n2\u70b9\u3092\u901a\u308b\u76f4\u7dda\u306e\u50be\u304d\u306e\u5f0f\u3068\u6975\u9650\u3092\u7d44\u307f\u5408\u308f\u305b\u3066\u3001\u63a5\u7dda\u306e\u50be\u304d\u3092\u6c42\u3081\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\n**\u56f3\u8868**\n\n\n\n\u306f\u3058\u3081\u306b\u3001 $x$ \u304b\u3089 $h$ \u3060\u3051\u96e2\u308c\u305f\u70b9 $x + h$ \u3092\u8003\u3048\u30012\u70b9\u3092\u901a\u308b\u76f4\u7dda\u306e\u50be\u304d\u3092\u6c42\u3081\u3066\u307f\u308b\u3002\n\u6b21\u306b $h$ \u3092 $0$ \u306b\u9650\u308a\u306a\u304f\u8fd1\u3065\u3051\u3066\u3044\u3051\u3070\u30011\u70b9 $x$ \u3067\u63a5\u3059\u308b\u63a5\u7dda\u3092\u8003\u3048\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\u3053\u308c\u3092\u5f0f\u3067\u307f\u308b\u3068\n\n$$\n\\begin{aligned}\na\n&= \\lim_{h \\rightarrow 0} \\frac{f(x + h) - f(x)}{(x + h) - x} \\\\\n&= \\lim_{h \\rightarrow 0} \\frac{f(x + h) - f(x)}{h} \\\\\n\\end{aligned}\n$$\n\n\u3068\u306a\u308b\u3002\u3088\u304f\u898b\u308b\u3068\u3053\u306e\u5f0f\u306f $x$ \u3092\u6c7a\u3081\u308b\u3054\u3068\u306b\u3042\u308b1\u3064\u306e\u5024\u3092\u5b9a\u3081\u3066\u3044\u308b\u3001\u3059\u306a\u308f\u3061\u3053\u306e\u5f0f\u306f $x$ \u306e\u95a2\u6570\u3067\u3042\u308b\uff08$h$ \u306f $h\\to 0$ \u306e\u6975\u9650\u3092\u53d6\u3063\u3066\u3044\u308b\u306e\u3067 $h$ \u306e\u95a2\u6570\u306b\u306f\u306a\u3063\u3066\u3044\u306a\u3044\u3053\u3068\u306b\u6ce8\u610f\u3059\u308b\uff09\u3002\n\u3053\u306e\u5f0f\u3092 $f$ \u306e **\u5c0e\u95a2\u6570 (derivative)**\u3068\u547c\u3073\u3001 $f'(x)$ \u3068\u66f8\u304f\u3002\u3059\u306a\u308f\u3061\u3001\n\n$$\nf'(x)= \\lim_{h \\rightarrow 0} \\frac{f(x + h) - f(x)}{h}\n$$\n\n\u3067\u3042\u308b\u3002\u5c0e\u95a2\u6570\u3092\u6c42\u3081\u308b\u3053\u3068\u3092**\u5fae\u5206(differentiation)**\u3059\u308b\u3068\u8a00\u3046\u3002\n\u8a18\u53f7\u306e\u4f7f\u3044\u65b9\u3068\u3057\u3066\u3001 $f'(x)$ \u3092\n\n$$\n\\frac{d}{dx}f (x)\n$$\n\u307e\u305f\u306f\n$$\n\\frac{df}{dx} (x)\n$$\n\n\u3068\u66f8\u3044\u3066\u3082\u69cb\u308f\u306a\u3044\u3002\n\u3053\u306e $d$ \u3068\u8a00\u3046\u8a18\u53f7\u306f\u5897\u5206\u3092\u3068\u308b\u64cd\u4f5c\u3092\u8868\u3057\u3066\u304a\u308a\u3001\u4f8b\u3048\u3070 $dx$ \u306f $x$ \u306e\u5909\u5316\u91cf\u3092\u8868\u3059\u3002\n\u3053\u306e\u8a18\u6cd5\u306f\u7169\u96d1\u3067\u3042\u308b\u304c\u3001$x, y$ \u306a\u3069\u5909\u6570\u304c\u8907\u6570\u3042\u308b\u5834\u5408\u3001 \u3069\u306e\u5909\u6570\u3067\u5fae\u5206\u3057\u3066\u3044\u308b\u304b\u304c\u660e\u78ba\u306b\u306a\u308b\u305f\u3081\u3001\u8868\u73fe\u3092\u6b63\u78ba\u306b\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n## \u5fae\u5206\u306e\u516c\u5f0f\n\n\u3042\u308b\u95a2\u6570\u306e\u5c0e\u95a2\u6570\u3092\u8a08\u7b97\u3059\u308b\u306b\u306f\u3001\u5c0e\u95a2\u6570\u306e\u5b9a\u7fa9\u901a\u308a\u306b\u8a08\u7b97\u3059\u308b\u306e\u304c\u6700\u3082\u611a\u76f4\u306a\u65b9\u6cd5\u3067\u3042\u308b\uff0e\n\u3057\u304b\u3057\u3001\u3053\u308c\u304b\u3089\u7d39\u4ecb\u3059\u308b\u7a2e\u3005\u306e\u516c\u5f0f\u3092\u7d44\u307f\u5408\u308f\u305b\u308b\u3053\u3068\u3067\u3001\u308f\u3056\u308f\u3056\u5b9a\u7fa9\u306b\u623b\u3089\u306a\u304f\u3066\u3082\u3001\u8907\u96d1\u306a\u95a2\u6570\u306e\u5c0e\u95a2\u6570\u3092\u8a08\u7b97\u3067\u304d\u308b\u3002\n\u4ee5\u4e0b\u3067\u306f\u3001 $c$ \u306f\u5b9a\u6570\u3001 $x$ \u306f\u5909\u6570\u3092\u8868\u3059\u3002\n\n\u307e\u305a\u306f\u3058\u3081\u306b\u3001\u4ee5\u4e0b\u306e 3 \u3064\u306e\u516c\u5f0f\u3092\u7d39\u4ecb\u3059\u308b\u3002\n\n$$\n\\begin{align}\n\\left( c\\right)^{'} &= 0 \\\\\n\\left( x\\right)^{'} &= 1\\\\\n\\left( x^{2}\\right)^{'} &= 2x\n\\end{align}\n$$\n\n1\u3064\u76ee\u306e\u5de6\u8fba\u306f\u5b9a\u6570\u95a2\u6570 $f(x) = c$ \u3092 $x$ \u3067\u5fae\u5206\u3057\u305f\u5c0e\u95a2\u6570\u3092\u8868\u3057\u3066\u3044\u308b\u3002\n\u5b9a\u6570\u95a2\u6570\u306e\u30b0\u30e9\u30d5\u3092\u66f8\u304f\u3068 $x$ \u8ef8\u306b\u5e73\u884c\u306b\u306a\u308b\u305f\u3081\u3001\u3069\u306e\u70b9\u3067\u63a5\u7dda\u3092\u5f15\u3044\u3066\u3082\u305d\u306e\u50be\u304d\u306f $0$\u3067\u3042\u308b\uff08\u30b0\u30e9\u30d5\u3068\u63a5\u7dda\u306f\u540c\u4e00\u306e\u76f4\u7dda\u3068\u306a\u308b\uff09\u3002\u3053\u308c\u306f\u5c0e\u95a2\u6570\u306f 0 \u3067\u3042\u308b\u3053\u3068\u3092\u610f\u5473\u3059\u308b\u3002\u3053\u308c\u304c 1 \u3064\u76ee\u306e\u5f0f\u306e\u56f3\u5f62\u7684\u306a\u7406\u89e3\u3067\u3042\u308b\u3002\n\u540c\u69d8\u306b2\u3064\u76ee\u306e\u516c\u5f0f\u306f \u300c$y=x$ \u306e\u30b0\u30e9\u30d5\u3067\u306f\u3069\u306e\u70b9\u3067\u63a5\u7dda\u3092\u5f15\u3044\u3066\u3082\u50be\u304d\u304c1\u300d\u3067\u3042\u308b\u3053\u3068\u3092\u610f\u5473\u3059\u308b\uff08\u3053\u306e\u5834\u5408\u3082\u30b0\u30e9\u30d5\u3068\u63a5\u7dda\u306f\u540c\u4e00\u306e\u76f4\u7dda\u3067\u3042\u308b\uff09\u3002\n\u6975\u9650\u306e\u6271\u3044\u306b\u6163\u308c\u308b\u305f\u3081\u306b\u30013\u756a\u76ee\u306e\u516c\u5f0f\u3092\u8a3c\u660e\u3059\u308b\u3002\u5c0e\u95a2\u6570\u306e\u5b9a\u7fa9\u304b\u3089\u5de6\u8fba\u306f\n\n$$\n\\displaystyle \\lim _{h\\to 0} \\frac{(x+h)^2 - x^2}{(x+h) - x}\n$$\n\u3067\u3042\u308b\u3002\u3053\u308c\u306f\n\n$$\n\\begin{align}\n\\lim _{h\\to 0} \\frac{(x+h)^2 - x^2}{(x+h) - x} = \\lim _{h\\to 0} \\frac{2xh + h^2}{h} = \\lim _{h\\to 0} (2x + h)\n\\end{align}\n$$\n\n\u3068\u8a08\u7b97\u3067\u304d\u308b\u3002\u3053\u3053\u3067 $h\\to 0$ \u3001\u3059\u306a\u308f\u3061 $h$ \u3092\u9650\u308a\u306a\u304f $0$ \u306b\u8fd1\u3065\u3051\u308b\u3068\u3001 $2x + h$ \u306f $2x$ \u306b\u9650\u308a\u306a\u304f\u8fd1\u3065\u3044\u3066\u3044\u304f\u3002\u5f93\u3063\u3066\u3001 $\\left( x^{2}\\right)^{'} = 2x$ \u304c\u5c0e\u304b\u308c\u305f\u3002\n\n\u4ee5\u4e0b\u306e\u516c\u5f0f\u3082\u983b\u7e41\u306b\u5229\u7528\u3059\u308b\u3002\n\n$$\n\\begin{align}\n\\left( x^{n} \\right)^{'} &= nx^{n-1} \\\\\n\\left( e^{ax} \\right)^{'} &= ae^{ax}\n\\end{align}\n$$\n\n\u3053\u3053\u3067\u3001$a$ \u306f\u5b9a\u6570\u3001 $e$ \u306f**\u81ea\u7136\u5bfe\u6570\u306e\u5e95**\u3001\u3082\u3057\u304f\u306f **\u30cd\u30a4\u30d4\u30a2\u6570** \u3068\u547c\u3070\u308c\u308b\u7279\u5225\u306a\u5b9a\u6570\u3067\u3001\u304a\u3088\u305d $2.71828\\cdots$ \u3067\u3042\u308b\u3002 $1$ \u3064\u76ee\u306e\u516c\u5f0f\u3067 $n=1, 2$\u3068\u3059\u308b\u3068\u3001\u672c\u7bc0\u306e\u6700\u521d\u306b\u7d39\u4ecb\u3057\u305f $x$, $x^2$ \u306e\u5fae\u5206\u306e\u516c\u5f0f\u306b\u5e30\u7740\u3055\u308c\u308b\u3053\u3068\u306b\u6ce8\u610f\u3059\u308b\u3002\n$e^{ax}$ \u306f $\\exp(ax)$ \u306e\u3088\u3046\u306b\u8868\u8a18\u3055\u308c\u308b\u3053\u3068\u304c\u3088\u304f\u3042\u308b\u3002\u305d\u306e\u8868\u8a18\u3092\u7528\u3044\u308b\u3068\u6700\u5f8c\u306e\u516c\u5f0f\u306f\n\n$$\n\\bigl( \\exp(ax) \\bigr)^{'} = a\\exp(ax)\n$$\n\n\u3068\u3082\u66f8\u3051\u308b\u3002\n\n## \u7dda\u5f62\u6027\n\n\u5fae\u5206\u306f**\u7dda\u5f62\u6027**\u3068\u8a00\u3046\u6027\u8cea\u3092\u6301\u3063\u3066\u3044\u308b\u3002\n\u305d\u308c\u304c\u3069\u306e\u3088\u3046\u306a\u6027\u8cea\u306a\u306e\u304b\u3001\u5177\u4f53\u4f8b\u3092\u6319\u3052\u3066\u898b\u3066\u3044\u3053\u3046\u3002\n\u5fae\u5206\u306b\u306f\u7dda\u5f62\u6027\u3068\u8a00\u3046\u6027\u8cea\u306b\u3088\u3063\u3066\u3001\n\n$$\n(3x)' = 3 \\times (x)'\n$$\n\n\u306e\u3088\u3046\u306b\u5b9a\u6570\u9805\u3092\u5fae\u5206\u306e\u6f14\u7b97\u306e\u5916\u5074\u306b\u51fa\u3059\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\u307e\u305f\u3001\n\n$$\n\\left( 3x^{2} + 4x - 5 \\right)' = \\left( 3x^{2} \\right)' + \\left( 4x \\right)' - \\left( 5 \\right)' \n$$\n\n\u306e\u3088\u3046\u306b\u3001\u52a0\u7b97\u3084\u6e1b\u7b97\u306f\u305d\u308c\u305e\u308c\u9805\u3054\u3068\u306b\u72ec\u7acb\u306b\u5fae\u5206\u306e\u6f14\u7b97\u3092\u884c\u3046\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\u3053\u306e 2 \u3064\u306e\u7279\u6027\u3092\u5408\u308f\u305b\u3066\u7dda\u5f62\u6027\u3068\u547c\u3076\u3002\n\n\u3082\u3046\u5c11\u3057\u5fae\u5206\u306e\u8a08\u7b97\u3092\u7df4\u7fd2\u3057\u3066\u307f\u308b\u3002\n\n$$\n\\begin{aligned}\n\\left( 3x^{2} + 4x + 5 \\right)' &= \\left( 3x^{2} \\right)' + \\left( 4x \\right)' - \\left( 5 \\right)' \\\\ \n&= 3 \\times \\left( x^{2} \\right)' + 4 \\times \\left( x \\right)' - 5 \\times \\left( 1 \\right)' \\\\ \n&= 3 \\times 2x + 4 \\times 1 - 5 \\times 0  \\\\ \n&= 6x + 4 \n\\end{aligned}\n$$\n\n\u3053\u306e\u7dda\u5f62\u6027\u306b\u95a2\u3057\u3066\u306f\u3001\u4e0b\u8a18\u306e\u3088\u3046\u306b\u516c\u5f0f\u3068\u3057\u3066\u307e\u3068\u3081\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n$$\n\\begin{align}\n\\left( cf(x) \\right)^{'} &= c f'(x) \\\\\n\\left( f(x) + g(x) \\right)^{'} &= f^{'}(x) + g^{'}(x) \\\\\n\\end{align}\n$$\n\n\n2 \u3064\u306e\u95a2\u6570\u306e\u7a4d\u306e\u5f62\u3067\u66f8\u304b\u308c\u3066\u3044\u308b\u95a2\u6570\u306b\u95a2\u3057\u3066\u306f\u6b21\u306e\u516c\u5f0f\u304c\u6210\u308a\u7acb\u3064\u3002\n\n$$\n\\bigl( f(x) g(x) \\bigr)^{'} = f^{'}(x)g(x) + f(x)g^{'}(x)\n$$\n\n\u95a2\u6570 $f$ \u306e\u5c0e\u95a2\u6570\u3068\u95a2\u6570 $g$ \u306e\u5c0e\u95a2\u6570\u304c\u308f\u304b\u308c\u3070\u3001\u95a2\u6570 $fg$ \u3092\u8a08\u7b97\u3067\u304d\u308b\u3053\u3068\u304c\u308f\u304b\u308b\u3002\n\n## \u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\n\n\u95a2\u6570 $y = f(x)$ \u3068 $z = g(y)$ \u306e**\u5408\u6210**\u3068\u306f $f$ \u3092\u9069\u7528\u3057\u305f\u3042\u3068\u306b $g$ \u3092\u9069\u7528\u3059\u308b\u95a2\u6570\u3001\u3059\u306a\u308f\u3061 $z  = g(f(x))$ \u306e\u3053\u3068\u3092\u6307\u3059\u3002\n\u30c7\u30a3\u30fc\u30d7\u30e9\u30fc\u30cb\u30f3\u30b0\u3067\u7528\u3044\u308b\u30cb\u30e5\u30fc\u30e9\u30eb\u30cd\u30c3\u30c8\u30ef\u30fc\u30af\u306f\u3001\u5c64\u3092\u4f55\u5c64\u3082\u91cd\u306d\u3066\u8907\u96d1\u306a\u95a2\u6570\u3092\u8868\u73fe\u3059\u308b\u3002\u5404\u3005\u306e\u5c64\u3092 1 \u3064\u306e\u95a2\u6570\u3068\u307f\u306a\u3059\u3068\u3001\u30cb\u30e5\u30fc\u30e9\u30eb\u30cd\u30c3\u30c8\u30ef\u30fc\u30af\u306f\u591a\u304f\u306e\u95a2\u6570\uff08\u5c64\uff09\u3092\u5408\u6210\u3057\u305f**\u5408\u6210\u95a2\u6570**\u3068\u898b\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u3092\u8003\u3048\u308b\u6642\u306b\u306f\u6b21\u306b\u7d39\u4ecb\u3059\u308b\u516c\u5f0f\uff08\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u306e\u516c\u5f0f\uff09\u304c\u6709\u7528\u3067\u3042\u308b\u3002\n\u3053\u306e\u516c\u5f0f\u306f**\u9023\u9396\u5f8b (chain rule)** \u3068\u3082\u547c\u3070\u308c\u3066\u3044\u308b\u3002\n\u9023\u9396\u5f8b\u306f\u5408\u6210\u95a2\u6570\u3092\u5fae\u5206\u3092\u7c21\u5358\u306b\u8a08\u7b97\u3059\u308b\u305f\u3081\u306e\u516c\u5f0f\u3068\u8a00\u3046\u3060\u3051\u3067\u306f\u306a\u304f\u3001\u30cb\u30e5\u30fc\u30e9\u30eb\u30cd\u30c3\u30c8\u30ef\u30fc\u30af\u306e\u8a13\u7df4\u65b9\u6cd5\u3067\u3042\u308b\u8aa4\u5dee\u9006\u4f1d\u64ad\u6cd5\u3092\u7406\u89e3\u3059\u308b\u4e0a\u3067\u672c\u8cea\u7684\u306a\u5f79\u5272\u3092\u679c\u305f\u3059\u3002\n\n\u7c21\u5358\u306a\u4f8b\u3068\u3057\u3066\u3001\n\n$$\n\\left\\{ (3x + 4)^{2} \\right\\}'\n$$\n\n\u3092\u8a08\u7b97\u3059\u308b\u3053\u3068\u3092\u8003\u3048\u308b\u3002\n\u3053\u306e\u5f0f\u306f\u3001 $3x+4$ \u3068\u8a00\u3046\u5185\u5074\u306e\u90e8\u5206\u3068 $(\\cdot)^{2}$ \u3068\u8a00\u3046\u5916\u5074\u306e\u90e8\u5206\u3067\u69cb\u6210\u3055\u308c\u3066\u3044\u308b\u3002\n\u3053\u306e\u5f0f\u3092 $(9x^2 + 24x + 16)'$ \u306e\u3088\u3046\u306b\u5c55\u958b\u3057\u3066\u304b\u3089\u5fae\u5206\u3092\u8a08\u7b97\u3057\u3066\u3082\u3088\u3044\u306e\u3060\u304c\u30013\u4e57\u30844\u4e57\u3068\u3079\u304d\u6570\u304c\u5897\u3048\u308b\u3068\u5f0f\u3092\u5c55\u958b\u3059\u308b\u306e\u304c\u5927\u5909\u306b\u306a\u308b\u3002\n\u3053\u3053\u3067\u5f79\u306b\u7acb\u3064\u8003\u3048\u65b9\u304c\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u3067\u3042\u308b\u3002\n\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u306f\u3001\u5185\u5074\u306e\u5fae\u5206\u3068\u5916\u5074\u306e\u5fae\u5206\u3092\u305d\u308c\u305e\u308c\u884c\u3044\u3001\u305d\u306e\u7d50\u679c\u3092\u304b\u3051\u5408\u308f\u305b\u308b\u3053\u3068\u3067\u6c42\u3081\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\u5916\u5074\u306e\u5fae\u5206\u306e\u969b\u306b\u306f\u95a2\u6570\u306e\u5f15\u6570\u3092\u5165\u529b\u3068\u307f\u306a\u3057\u3001\u305d\u306e\u5165\u529b\u306b\u3064\u3044\u3066\u306e\u5fae\u5206\u3092\u8a08\u7b97\u3059\u308b\u3002\n\n\u305d\u308c\u3067\u306f\u3001\u5177\u4f53\u7684\u306b\u3053\u306e $(3x+4)^2$ \u3068\u8a00\u3046\u95a2\u6570\u306e\u5fae\u5206\u3092\u8003\u3048\u3066\u307f\u308b\u3002\n\u307e\u305a\u5185\u5074\u306e\u95a2\u6570\u3092 $u = (3x+4)$ \u3068\u304a\u3044\u3066\u3001\n\n$$\n\\left\\{ (3x + 4)^{2} \\right\\}' = (u^{2})'\n$$\n\n\u3068\u898b\u308b\u3002\u3053\u3053\u3067\u3001 $(\\cdot)'$ \u3092\u3082\u3046\u5c11\u3057\u53b3\u5bc6\u306b\u8003\u3048\u308b\u5fc5\u8981\u304c\u51fa\u3066\u304f\u308b\u3002\n\u4eca\u5909\u6570\u306f $x$, $u$ \u306e2\u3064\u3042\u308b\u305f\u3081\u3001 $(\\cdot)'$ \u3068\u8a00\u3046\u8868\u8a18\u3067\u306f\u3001 $x$ \u3067\u5fae\u5206\u3057\u3066\u3044\u308b\u306e\u304b $u$ \u3067\u5fae\u5206\u3057\u3066\u3044\u308b\u306e\u304b\u306e\u533a\u5225\u304c\u3064\u304b\u306a\u3044\u3002\n\u305d\u3053\u3067\u3001\u591a\u5c11\u8907\u96d1\u306b\u898b\u3048\u308b\u304c\u3001\u5148\u7a0b\u7d39\u4ecb\u3057\u305f $d$ \u3092\u4f7f\u3063\u305f\u8a18\u6cd5\u3092\u7528\u3044\u3066\u5fae\u5206\u3059\u308b\u5909\u6570\u3092\u660e\u793a\u3059\u308b\u3002\n\n\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u3092\u516c\u5f0f\u3068\u3057\u3066\u307e\u3068\u3081\u308b\u3068\u6b21\u306e\u3088\u3046\u306b\u306a\u308b\u3002\n\n$$\n\\frac{d}{dx} f(g(x)) = \\frac{df(u)}{du}\\frac{du}{dx}\n$$\n\n\u3053\u3053\u3067 $u = g(x)$ \u3067\u3042\u308b\u3002\n\n\u516c\u5f0f\u3092\u898b\u308b\u3088\u308a\u3082\u5b9f\u969b\u306e\u9069\u7528\u4f8b\u3092\u898b\u305f\u65b9\u304c\u7406\u89e3\u3057\u3084\u3059\u3044\u304b\u3082\u77e5\u308c\u306a\u3044\u3002\n\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u306e\u516c\u5f0f\u3092\u7528\u3044\u3066\u3001\u5148\u7a0b\u306e $(3x+4)^2$ \u306e\u5fae\u5206\u3092\u8a08\u7b97\u3059\u308b\u3068\u6b21\u306e\u3088\u3046\u306b\u306a\u308b\u3002\n2\u884c\u76ee\u3067\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u306e\u516c\u5f0f\u3092\u5229\u7528\u3057\u3066\u3044\u308b\u3053\u3068\u306b\u6ce8\u76ee\u3059\u308b\u3002\n\n$$\n\\begin{aligned}\n\\left\\{ (3x + 4)^{2} \\right\\}' &= \\frac{d}{dx} \\left\\{ (3x + 4)^{2} \\right\\} \\\\\n&= \\frac{du}{dx} \\frac{d}{du} (u^2) \\\\\n&= \\frac{d}{dx} (3x + 4) \\cdot \\frac{d}{du} (u^{2}) \\\\ \n&= 3 \\cdot 2u   \\\\ \n&= 6u = 6(3x + 4) = 18x + 24 \\\\ \n\\end{aligned}\n$$\n\n\u6c17\u306b\u306a\u308b\u4eba\u306f\u3001 $(3x + 4)^2$ \u3092\u5c55\u958b\u3057\u3066\u304b\u3089\u5404\u9805\u3092\u5fae\u5206\u3057\u305f\u5834\u5408\u3068\u7d50\u679c\u304c\u4e00\u81f4\u3057\u3066\u3044\u308b\u3053\u3068\u3092\u78ba\u304b\u3081\u3066\u307f\u308b\u3002\n\n## \u504f\u5fae\u5206\n\n\u6a5f\u68b0\u5b66\u7fd2\u3067\u306f\u30011\u3064\u306e\u5165\u529b\u5909\u6570 $x$ \u304b\u3089\u51fa\u529b\u5909\u6570 $y$ \u3092\u4e88\u6e2c\u3059\u308b\u30b1\u30fc\u30b9\u306f\u7a00\u3067\u3042\u308a\u3001\u591a\u304f\u306e\u5834\u5408\u3001\u8907\u6570\u306e\u5165\u529b\u5909\u6570 $x_1, x_2, \\dots, x_M$ \u3092\u7528\u3044\u3066 $y$ \u3092\u4e88\u6e2c\u3059\u308b**\u591a\u5909\u6570\u95a2\u6570**\u304c\u6271\u308f\u308c\u308b\u3002\n\u4f8b\u3048\u3070\u3001\u5bb6\u8cc3\u3092\u4e88\u6e2c\u3059\u308b\u5834\u5408\u3001\u90e8\u5c4b\u306e\u5e83\u3055\u3060\u3051\u3067\u306f\u306a\u304f\u3001\u99c5\u304b\u3089\u306e\u8ddd\u96e2\u3084\u5468\u8fba\u306e\u72af\u7f6a\u767a\u751f\u7387\u306a\u3069\u3082\u540c\u6642\u306b\u8003\u616e\u3057\u305f\u65b9\u304c\u3088\u308a\u6b63\u78ba\u306b\u4e88\u6e2c\u304c\u3067\u304d\u308b\u3068\u671f\u5f85\u3055\u308c\u308b\u3002\n\u8907\u6570\u306e\u5165\u529b $x_1, x_2, \\dots, x_M$ \u3092\u3068\u308b\u95a2\u6570 $f(x_1, x_2, \\dots, x_M)$ \u3092\u591a\u5909\u6570\u95a2\u6570\u3068\u547c\u3076\u3002\n\u3053\u306e\u591a\u5909\u6570\u95a2\u6570\u306b\u304a\u3044\u3066\u3001\u3042\u308b\u5165\u529b $x_m$ \u306b\u306e\u307f\u6ce8\u76ee\u3057\u3066\u5fae\u5206\u3059\u308b\u3053\u3068\u3092 **\u504f\u5fae\u5206** \u3068\u3088\u3073\u3001\n\n$$\n\\frac{\\partial}{\\partial x_{m}} f(x_1, x_2, \\dots, x_M)\n$$\n\n\u3068\u8868\u3059\u3002\u5fae\u5206\u3092\u610f\u5473\u3059\u308b\u8a18\u53f7\u304c\u3001 $d$ \u304b\u3089 $\\partial$ \u306b\u5909\u308f\u3063\u3066\u3044\u308b\u3002\u3053\u3046\u3059\u308b\u3068\u3001 $\\frac{\\partial}{\\partial x_m}$ \u306f $x_m$ \u4ee5\u5916\u3092\u5b9a\u6570\u3068\u8003\u3048\u3001 $x_m$ \u306b\u306e\u307f\u7740\u76ee\u3057\u3066\u5fae\u5206\u3092\u884c\u3046\u3068\u8a00\u3046\u610f\u5473\u3068\u306a\u308b\uff08[\u6ce8\u91c83](#note3)\uff09\u3002\n\n\u4ee5\u4e0b\u306e\u4f8b\u3067\u5177\u4f53\u7684\u306a\u8a08\u7b97\u306e\u6d41\u308c\u3092\u78ba\u8a8d\u3059\u308b\u3002\n\n$$\n\\begin{aligned}\n\\frac{\\partial}{\\partial x_1}\n\\left( 3x_1+4x_2 \\right)\n&= \\frac{\\partial}{\\partial x_1}\n\\left( 3x_1 \\right) + \\frac{\\partial}{\\partial x_1} \\left( 4x_2 \\right) \\\\\n&= 3 \\times \\frac{\\partial}{\\partial x_1} \\left( x_1 \\right) + 4 \\times \\frac{\\partial}{\\partial x_1} x_2 \\\\\n&= 3 \\times 1 + 4 \\times 0 \\\\\n&= 3\n\\end{aligned}\n$$\n\n\u504f\u5fae\u5206\u3067\u3082\u5fae\u5206\u3068\u540c\u3058\u516c\u5f0f\u3092\u9069\u7528\u3067\u304d\u308b\u3002\u4eca\u56de\u306e\u30b1\u30fc\u30b9\u3067\u306f\u3001 $x_1$ \u306b\u3060\u3051\u7740\u76ee\u3057\u3066\u304a\u308a\u3001 $x_2$ \u306f\u5b9a\u6570\u3068\u3057\u3066\u6271\u304b\u3063\u3066\u3044\u308b\u3002\u305d\u306e\u305f\u3081\u3001\u4e0a\u5f0f\u306e 2 \u884c\u76ee\u304b\u3089 3 \u884c\u76ee\u3067 $x_2$ \u3092 $x_1$ \u3067\u504f\u5fae\u5206\u3057\u305f\u5024\u3092 $0$ \u3068\u3057\u3066\u3044\u308b\uff08\u5b9a\u6570\u306e\u5fae\u5206\u306f $0$ \u3067\u3042\u3063\u305f\u3053\u3068\u3092\u601d\u3044\u51fa\u3059\uff09\u3002\n\n<hr />\n\n<div class=\"alert alert-info\">\n**\u6ce8\u91c8 1**\n\n\u3053\u3053\u3067\u8003\u3048\u3066\u3044\u308b\u95a2\u6570\u306e\u30b0\u30e9\u30d5\u3067\u306f\u3001\u30b0\u30e9\u30d5\u4e0a\u306e\u3069\u306e\u70b9\u3092\u53d6\u3063\u3066\u3082\u305d\u306e\u70b9\u3067\u63a5\u3059\u308b\u63a5\u7dda\u304c\u305f\u30601\u672c\u3060\u3051\u5f15\u3051\u308b\u72b6\u6cc1\u3092\u8003\u3048\u3066\u3044\u308b\u3002\u4f8b\u3048\u3070\u95a2\u6570\u306e\u30b0\u30e9\u30d5\u304c\u8c37\u306e\u90e8\u5206\u3067\u300c\u5c16\u3063\u305f\u300d\u5f62\u3092\u3057\u3066\u3044\u308b\u3068\uff0c\u8c37\u306e\u5e95\u3067\u8907\u6570\u306e\u63a5\u7dda\u304c\u5f15\u3051\u3066\u3057\u307e\u3046\u3002\u3053\u3053\u3067\u306f\u305d\u306e\u3088\u3046\u306a\u30b1\u30fc\u30b9\u306f\u8003\u3048\u305a\u3001\u95a2\u6570\u306e\u30b0\u30e9\u30d5\u306f\u56f3\u306e\u3088\u3046\u306a\u300c\u6ed1\u3089\u304b\u300d\u306a\u30ab\u30fc\u30d6\u306b\u306a\u3063\u3066\u3044\u308b\u5834\u5408\u3092\u30a4\u30e1\u30fc\u30b8\u3059\u308b\u3002 \n\n[\u25b2\u4e0a\u3078\u623b\u308b](#ref_note1)\n</div>\n\n<div class=\"alert alert-info\">\n**\u6ce8\u91c8 2**\n\n\u4eca\u306f\u95a2\u6570\u306e\u30b0\u30e9\u30d5\u306e\u300c\u8c37\u300d\u3092\u8003\u3048\u305f\u304c\u3001\u300c\u5c71\u300d\u3067\u3082\u540c\u69d8\u306b\u63a5\u7dda\u306e\u50be\u304d\u304c $0$ \u3068\u306a\u308b\u305f\u3081\u3001\u3042\u308b\u70b9\u3067\u306e\u63a5\u7dda\u306e\u50be\u304d\u304c $0$ \u3060\u304b\u3089\u3068\u8a00\u3063\u3066\u3001\u5fc5\u305a\u3057\u3082\u95a2\u6570\u304c\u305d\u306e\u70b9\u3067\u6700\u5c0f\u5024\u3092\u3068\u308b\u3068\u306f\u9650\u3089\u306a\u3044\u3002\n\n[\u25b2\u4e0a\u3078\u623b\u308b](#ref_note2)\n</div>\n\n<div class=\"alert alert-info\">\n**\u6ce8\u91c8 3**\n\n\u5165\u529b\u5909\u6570\u304c\u4ed6\u306e\u5165\u529b\u5909\u6570\u3068\u72ec\u7acb\u3067\u306a\u3044\u5834\u5408\u306f\u5b9a\u6570\u3068\u8003\u3048\u308b\u3053\u3068\u306f\u3067\u304d\u306a\u3044\u3002\u3057\u304b\u3057\u672c\u8cc7\u6599\u3067\u306f\u305d\u306e\u3088\u3046\u306a\u30b1\u30fc\u30b9\u306f\u51fa\u3066\u3053\u306a\u3044\u3002\n\n[\u25b2\u4e0a\u3078\u623b\u308b](#ref_note3)\n</div>\n\n\n```python\n\n```\n\n\n\n# \u7dda\u5f62\u4ee3\u6570\u306e\u57fa\u790e\n\n\u6a5f\u68b0\u5b66\u7fd2\u306e\u7406\u8ad6\u3067\u306f\u7dda\u5f62\u4ee3\u6570\u3067\u7528\u3044\u3089\u308c\u308b\u6982\u5ff5\u304c\u591a\u304f\u767b\u5834\u3059\u308b\u3002\n\u3053\u308c\u3089\u306e\u6982\u5ff5\u3092\u5229\u7528\u3059\u308b\u3053\u3068\u3067\u3001\u8907\u6570\u306e\u5024\u3084\u5909\u6570\u3092\u307e\u3068\u3081\u3066\u6271\u3046\u3053\u3068\u304c\u3067\u304d\u308b\u3088\u3046\u306b\u306a\u308a\u3001\u6570\u5f0f\u3092\u7c21\u6f54\u306b\u8868\u73fe\u3067\u304d\u308b\u3088\u3046\u306b\u306a\u308b\u3002\n\u672c\u7ae0\u3067\u306f\u3001\u7279\u306b\u4ee5\u4e0b\u306e\u6982\u5ff5\u3092\u9806\u756a\u306b\u7d39\u4ecb\u3059\u308b\n\n- \u30b9\u30ab\u30e9\u30fb\u30d9\u30af\u30c8\u30eb\u30fb\u884c\u5217\u30fb\u30c6\u30f3\u30bd\u30eb\n- \u30d9\u30af\u30c8\u30eb\u30fb\u884c\u5217\u306e\u6f14\u7b97\uff08\u52a0\u6e1b\u7b97\u30fb\u30b9\u30ab\u30e9\u500d\u30fb\u5185\u7a4d\u30fb\u884c\u5217\u7a4d\uff09\n- \u7279\u5225\u306a\u884c\u5217\uff08\u5358\u4f4d\u884c\u5217\u30fb\u9006\u884c\u5217\uff09\n- \u591a\u5909\u6570\u95a2\u6570\uff08\u7dda\u5f62\u7d50\u5408\uff0c\u4e8c\u6b21\u5f62\u5f0f\uff09\u3068\u305d\u306e\u5fae\u5206\n\n## \u30b9\u30ab\u30e9\u30fb\u30d9\u30af\u30c8\u30eb\u30fb\u884c\u5217\u30fb\u30c6\u30f3\u30bd\u30eb\n\n\u59cb\u3081\u306b\u3001\u30b9\u30ab\u30e9\u3001\u30d9\u30af\u30c8\u30eb\u3001\u884c\u5217\u3001\u30c6\u30f3\u30bd\u30eb\u3068\u8a00\u3046 4 \u3064\u306e\u8a00\u8449\u3092\u89e3\u8aac\u3059\u308b\u3002\n\n**\u30b9\u30ab\u30e9 (scalar)** \u306f\u30012.5\u3001-1\u3001$\\sqrt{2}$\u3001$\\pi$\u3068\u3044\u3063\u305f 1 \u3064\u306e\u5024\u3082\u3057\u304f\u306f\u5909\u6570\u306e\u3053\u3068\u3092\u6307\u3059\u3002\u30b9\u30ab\u30e9\u306f\u6e29\u5ea6\u3084\u8eab\u9577\u3068\u3044\u3063\u305f\u5358\u4e00\u306e\u6570\u91cf\u3092\u8868\u3059\u3002\u30b9\u30ab\u30e9\u5909\u6570\u3092\u8868\u3059\u306b\u306f\n\n$$\nx, \\ y,\\  M,\\  N\n$$\n\n\u306e\u3088\u3046\u306a\u6587\u5b57\u3092\u5229\u7528\u3059\u308b\u306e\u304c\u4e00\u822c\u7684\u3067\u3042\u308b\u3002\n\n$2.4+3.2i$ \u306e\u3088\u3046\u306a\u8907\u7d20\u6570\u3067\u3082\u3001\u5024\u304c 1 \u3064\u306a\u3089\u3070\u30b9\u30ab\u30e9\uff08\u8907\u7d20\u6570\u306e\u30b9\u30ab\u30e9\uff09\u3068\u547c\u3076\u304c\u3001\u672c\u8cc7\u6599\u3067\u306f\u7279\u306b\u660e\u793a\u3057\u306a\u3051\u308c\u3070\u5b9f\u6570\u306e\u30b9\u30ab\u30e9\u3092\u6271\u3046\u3002\u5f8c\u8ff0\u3059\u308b\u30d9\u30af\u30c8\u30eb\u3001\u884c\u5217\u3001\u30c6\u30f3\u30bd\u30eb\u306b\u3064\u3044\u3066\u3082\u540c\u69d8\u3067\u3042\u308b\u3002\n\n$x$ \u304c\u5b9f\u6570\u306e\u30b9\u30ab\u30e9\u3067\u3042\u308b\u3053\u3068\u3092\u3057\u3070\u3057\u3070\u300c$x\\in \\mathbb{R}$\u300d\u3068\u66f8\u304f\u3002\n\n$\\mathbb{R}$ \u306f\u5b9f\u6570\u306e\u30b9\u30ab\u30e9\u304b\u3089\u306a\u308b\u96c6\u5408\u3092\u8868\u3057\u3001\u300c$A\\in B$\u300d\u306f\u300c$A$ \u306f $B$ \u306b\u5c5e\u3059\u308b\u300d\u3068\u8a00\u3046\u610f\u5473\u3067\u3042\u308b\u3002\u5f93\u3063\u3066\u3001$x\\in \\mathbb{R}$ \u3067\u300c$x$ \u306f\u5b9f\u6570\u306e\u30b9\u30ab\u30e9\u304b\u3089\u306a\u308b\u96c6\u5408\u306b\u5c5e\u3059\u308b\u300d\u3001\u3059\u306a\u308f\u3061\u300c$x$ \u306f\u5b9f\u6570\u306e\u30b9\u30ab\u30e9\u3067\u3042\u308b\u300d\u3068\u89e3\u91c8\u3067\u304d\u308b\u3002\n\n&nbsp;\n\n\n\n**\u30d9\u30af\u30c8\u30eb (vector)** \u306f\u3001\u30b9\u30ab\u30e9\u3092 1 \u65b9\u5411\u306b\u4e26\u3079\u305f\u3082\u306e\u3067\u3042\u308b\u3002\u4f8b\u3048\u3070\u3001\n\n$$\n{\\bf x}=\\begin{bmatrix}\nx_{1} \\\\\nx_{2} \\\\\nx_{3}\n\\end{bmatrix}, \\\n{\\bf y}=\\begin{bmatrix}\ny_{1} \\\\\ny_{2} \\\\\n\\vdots \\\\\ny_{N}\n\\end{bmatrix}\n$$\n\n\u306e\u3088\u3046\u306b\u8868\u3059\u3002\u30d9\u30af\u30c8\u30eb\u3092\u69cb\u6210\u3059\u308b\u30b9\u30ab\u30e9\u9054\uff08$x_1$ \u3084 $y_2$ \u306a\u3069\uff09\u306e\u3053\u3068\u3092**\u8981\u7d20**\u3084**\u6210\u5206**\u3068\u547c\u3076\u3002\n\u30d9\u30af\u30c8\u30eb\u3092\u8868\u3059\u306e\u306b\u7528\u3044\u3089\u308c\u308b\u6587\u5b57\u306f\u3001\u30b9\u30ab\u30e9\u3068\u533a\u5225\u3057\u3084\u3059\u3044\u3088\u3046\u592a\u5b57\u3068\u3059\u308b\u306e\u304c\u4e00\u822c\u7684\u3067\u3042\u308b\u3002\n\u4e0a\u306e 2 \u3064\u306e\u4f8b\u306e\u3088\u3046\u306b\u3001\u305d\u306e\u8981\u7d20\u3092**\u7e26\u65b9\u5411\u306b\u4e26\u3079\u305f\u3082\u306e\u306f\u5217\u30d9\u30af\u30c8\u30eb**\u3068\u547c\u3076\u3002\n\u4e00\u65b9\u3001\n\n$$\n{\\bf z}=\\begin{bmatrix}\nz_{1} & z_{2} & z_{3}\n\\end{bmatrix}\n$$\n\n\u306e\u3088\u3046\u306b\u3001\u8981\u7d20\u3092**\u6a2a\u65b9\u5411\u306b\u4e26\u3079\u305f\u3082\u306e\u306f\u884c\u30d9\u30af\u30c8\u30eb**\u3068\u547c\u3076\u3002\n\n\u672c\u8cc7\u6599\u3067\u306f\u3001\u7279\u306b\u660e\u793a\u3057\u306a\u3044\u9650\u308a\u3001**\u5358\u306b\u30d9\u30af\u30c8\u30eb\u3068\u8868\u73fe\u3057\u305f\u5834\u5408\u306b\u306f\u5217\u30d9\u30af\u30c8\u30eb\u3092\u6307\u3059\u3082\u306e**\u3068\u3059\u308b\u3002\n\n\u30d9\u30af\u30c8\u30eb\u306b\u542b\u307e\u308c\u308b\u30b9\u30ab\u30e9\u306e\u6570\u306e\u3053\u3068\u3092\u3001\u305d\u306e\u30d9\u30af\u30c8\u30eb\u306e**\u6b21\u5143**\u3068\u547c\u3076\u3002\n\u4f8b\u3048\u3070\u3001${\\bf x}$\u306f3\u6b21\u5143\u306e\u5217\u30d9\u30af\u30c8\u30eb\u3001${\\bf z}$ \u306f3\u6b21\u5143\u306e\u884c\u30d9\u30af\u30c8\u30eb\u3067\u3042\u308b\u3002\n\u30b9\u30ab\u30e9\u306e\u5834\u5408\u3068\u540c\u69d8\u306b\u3001\u30d9\u30af\u30c8\u30eb ${\\bf x}$ \u304c$N$\u6b21\u5143\u306e\u30d9\u30af\u30c8\u30eb\u3067\u3001\u30d9\u30af\u30c8\u30eb\u3092\u69cb\u6210\u3059\u308b\u30b9\u30ab\u30e9\u304c\u5b9f\u6570\u3067\u3042\u308b\u3053\u3068\u3092\u3001\u6570\u5f0f\u3092\u7528\u3044\u3066\u300c${\\bf x}\\in \\mathbb{R}^N$\u300d\u3068\u3082\u66f8\u304f\u3002\n\n&nbsp;\n\n\n**\u884c\u5217 (matrix)** \u306f\u540c\u3058\u30b5\u30a4\u30ba\u306e\u30d9\u30af\u30c8\u30eb\u3092\u8907\u6570\u500b\u4e26\u3079\u305f\u3082\u306e\u3067\u3042\u308b\u3002\u4f8b\u3048\u3070\u3001\n\n$$\n{\\pmb X} =\n\\begin{bmatrix}\nx_{11} & x_{12} \\\\\nx_{21} & x_{22} \\\\\nx_{31} & x_{32}\n\\end{bmatrix}\n$$\n\n\u306f\u884c\u5217\u306e\u4e00\u4f8b\u3067\u3042\u308b\u3002\u884c\u5217\u306f\u5927\u6587\u5b57\u3001\u307e\u305f\u306f\u5927\u6587\u5b57\u306e\u592a\u6587\u5b57\u3067\u8868\u8a18\u3059\u308b\u3053\u3068\u3067\u30b9\u30ab\u30e9\u3084\u30d9\u30af\u30c8\u30eb\u3068\u533a\u5225\u3059\u308b\u3002\n\u884c\u5217\u306e\u5f62\uff08\u30b5\u30a4\u30ba\uff09\u306f\u884c\u6570\u3068\u5217\u6570\u3067\u8868\u73fe\u3059\u308b\u3002\n\u4f8b\u3048\u3070\u3001\u4e0a\u306b\u6319\u3052\u305f ${\\bf X}$ \u306f\u884c\u30d9\u30af\u30c8\u30eb\u304c 3 \u3064\u4e26\u3093\u3060\u3082\u306e\u3068\u898b\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\u305d\u306e\u305f\u3081\u3001 ${\\bf X}$ \u306e\u884c\u6570\u306f 3 \u3067\u3042\u308b\u3002\n\u4e00\u65b9\u3001\u898b\u65b9\u3092\u5909\u3048\u308b\u3068 ${\\bf X}$ \u306f\u5217\u30d9\u30af\u30c8\u30eb\u304c 2 \u3064\u4e26\u3093\u3060\u3082\u306e\u3068\u898b\u308b\u3053\u3068\u3082\u3067\u304d\u308b\u306e\u3067\u3001 ${\\bf X}$ \u306e\u5217\u6570\u306f 2 \u3067\u3042\u308b\u3002\n\u305d\u3053\u3067\u3001 ${\\bf X}$ \u3092\u300c 3 \u884c 2 \u5217\u306e\u884c\u5217\u300d\u3068\u547c\u3076\u3002\n\u300c\u30b5\u30a4\u30ba\u304c $(3, 2)$ \u3067\u3042\u308b\u884c\u5217\u300d\u3084\u300c\u30b5\u30a4\u30ba\u304c $3\\times 2$ \u306e\u884c\u5217\u300d\u3068\u547c\u3093\u3067\u3082\u69cb\u308f\u306a\u3044\u3002\n$N$ \u6b21\u5143\u306e\u5217\u30d9\u30af\u30c8\u30eb\u306f\u30b5\u30a4\u30ba\u304c $(N, 1)$ \u306e\u884c\u5217\u3001 $N$ \u6b21\u5143\u306e\u884c\u30d9\u30af\u30c8\u30eb\u306f\u30b5\u30a4\u30ba\u304c $(1, N)$ \u306e\u884c\u5217\u3068\u898b\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\u30b9\u30ab\u30e9\u3001\u30d9\u30af\u30c8\u30eb\u306e\u5834\u5408\u3068\u4e26\u884c\u3057\u3066\u3001\u884c\u5217 ${\\bf X}$ \u306e\u30b5\u30a4\u30ba\u304c $(N, M)$ \u3067\u3042\u308a\u3001\u5404\u8981\u7d20\u304c\u5b9f\u6570\u3067\u3042\u308b\u3053\u3068\u3092\u3001\u300c${\\bf X} \\in \\mathbb{R}^{N \\times M}$\u300d \u3068\u3082\u66f8\u304f\u3002\u4f8b\u3048\u3070\u3001\u5148\u7a0b\u306e ${\\bf X}$ \u306b\u3064\u3044\u3066\u306f ${\\bf X}\\in \\mathbb{R}^{3\\times 2}$ \u3067\u3042\u308b\u3002\n\n&nbsp;\n\n\n**\u30c6\u30f3\u30bd\u30eb (tensor)** \u306f\u30d9\u30af\u30c8\u30eb\u3084\u884c\u5217\u3092\u4e00\u822c\u5316\u3057\u305f\u6982\u5ff5\u3067\u3042\u308b\u3002\n\n\u4f8b\u3048\u3070\u3001\u30d9\u30af\u30c8\u30eb\u306f 1 \u65b9\u5411\u306b\u3001\u884c\u5217\u306f 2 \u65b9\u5411\u306b\u30b9\u30ab\u30e9\u304c\u4e26\u3093\u3067\u3044\u308b\u3002\n\n\u3053\u308c\u306f\u300c\u30d9\u30af\u30c8\u30eb\u306f 1 \u968e\u306e\u30c6\u30f3\u30bd\u30eb\u3067\u3001\u884c\u5217\u306f 2 \u968e\u306e\u30c6\u30f3\u30bd\u30eb\u3067\u3042\u308b\u300d\u3067\u3042\u308b\u3053\u3068\u3092\u610f\u5473\u3059\u308b\u3002\n\n\u3053\u306e\u8003\u3048\u65b9\u3092\u3055\u3089\u306b\u9032\u3081\u3066\u3001\u884c\u5217\u3092\u5965\u884c\u304d\u65b9\u5411\u306b\u3055\u3089\u306b\u4e26\u3079\u305f\u3082\u306e\u30923\u968e\u306e\u30c6\u30f3\u30bd\u30eb\u3068\u547c\u3076\u3002\n\n\u4f8b\u3048\u3070\u3001\u30ab\u30e9\u30fc\u753b\u50cf\u3092\u30c7\u30b8\u30bf\u30eb\u8868\u73fe\u3059\u308b\u5834\u5408\u30011 \u679a\u306e\u753b\u50cf\u306f RGB (Red Green Blue) \u306e3\u679a\u306e\u30ec\u30a4\u30e4\u30fc\uff08\u30c1\u30e3\u30f3\u30cd\u30eb\u3068\u547c\u3076\uff09\u3092\u6301\u3064\u306e\u304c\u4e00\u822c\u7684\u3067\u3042\u308b\u3002\n\n\u5404\u30c1\u30e3\u30f3\u30cd\u30eb\u306f\u884c\u5217\u3068\u3057\u3066\u8868\u3055\u308c\u3001\u305d\u306e\u884c\u5217\u304c\u30c1\u30e3\u30f3\u30cd\u30eb\u65b9\u5411\u306b\u8907\u6570\u7a4d\u307f\u91cd\u306a\u3063\u3066\u3044\u308b\u305f\u3081\u3001\u753b\u50cf\u306f 3 \u968e\u30c6\u30f3\u30bd\u30eb\u3068\u307f\u306a\u3059\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n3 \u968e\u306e\u30c6\u30f3\u30bd\u30eb\u306f\u3001\u7279\u5b9a\u306e\u8981\u7d20\u3092\u6307\u5b9a\u3059\u308b\u306e\u306b\u300c\u4e0a\u304b\u3089 3 \u756a\u76ee\u3001\u5de6\u304b\u3089 2 \u756a\u76ee\u3001\u624b\u524d\u304b\u3089 5 \u756a\u76ee\u300d\u306e\u3088\u3046\u306b\u6574\u6570\uff08\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\uff09\u30923\u500b\u5fc5\u8981\u3068\u3059\u308b\u3002\n\n\u540c\u69d8\u306b\u30014 \u6b21\u5143\u4ee5\u4e0a\u306e\u5834\u5408\u3067\u3082\u3001$N$ \u6b21\u5143\u306b\u30b9\u30ab\u30e9\u3092\u4e26\u3079\u305f\u3082\u306e\uff08\u3064\u307e\u308a\u3001\u8981\u7d20\u3092\u6307\u5b9a\u3059\u308b\u306e\u306b $N$ \u500b\u306e\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u304c\u5fc5\u8981\u306a\u3082\u306e\uff09\u3092 $N$ \u968e\u306e\u30c6\u30f3\u30bd\u30eb\u3068\u8a00\u3046\u3002\u4f8b\u3048\u3070\u3001\u591a\u304f\u306e\u30c7\u30a3\u30fc\u30d7\u30e9\u30fc\u30cb\u30f3\u30b0\u30d5\u30ec\u30fc\u30e0\u30ef\u30fc\u30af\u3067\u306f\u3001\u8907\u6570\u679a\u306e\u753b\u50cf\u306e\u96c6\u307e\u308a\u3092\u300c\u753b\u50cf\u306e\u30a4\u30f3\u30c7\u30c3\u30af\u30b91\u3064\u300d+\u300c\u5404\u753b\u50cf\u306e\u30a4\u30f3\u30c7\u30c3\u30af\u30b9 3 \u3064\uff08\u5e45\u3001\u9ad8\u3055\u3001\u30c1\u30e3\u30f3\u30cd\u30eb\uff09\u300d\u306e 4 \u968e\u30c6\u30f3\u30bd\u30eb\u3068\u3057\u3066\u8868\u73fe\u3059\u308b\u3002\n\n\u524d\u8ff0\u306e\u3088\u3046\u306b\u30d9\u30af\u30c8\u30eb\u3084\u884c\u5217\u306f\u30c6\u30f3\u30bd\u30eb\u306e\u4e00\u7a2e\u3068\u307f\u306a\u3059\u3053\u3068\u304c\u3067\u304d\u308b\u304c\u3001\u672c\u8cc7\u6599\u3067\u306f\u5358\u306b\u300c\u30c6\u30f3\u30bd\u30eb\u300d\u3068\u8a00\u3063\u305f\u5834\u5408\u306f3\u968e\u4ee5\u4e0a\u306e\u30c6\u30f3\u30bd\u30eb\u3092\u6307\u3059\u3002\n\n&nbsp;\n\n\n\n### \u5909\u6570\u306e\u5f62\u3068\u5b57\u4f53\u306e\u95a2\u4fc2\n\n\u591a\u304f\u306e\u6559\u79d1\u66f8\uff08\u7279\u306b\u7dda\u5f62\u4ee3\u6570\u306e\u6559\u79d1\u66f8\uff09\u3067\u306f\u3001\u5909\u6570\u3092\u4e00\u76ee\u898b\u3066\u305d\u306e\u578b\u304c\u4f55\u304b\u304c\u308f\u304b\u308b\u3088\u3046\u306b\u3001\u7279\u5b9a\u306e\u5f62\uff08\u30d9\u30af\u30c8\u30eb\u3001\u884c\u5217\u306a\u3069\uff09\u306e\u5909\u6570\u306b\u306f\u7279\u5b9a\u306e\u5b57\u4f53\u3092\u7528\u3044\u308b\u3068\u8a00\u3046\u5de5\u592b\u304c\u3055\u308c\u3066\u3044\u308b\u3002\n\u672c\u8cc7\u6599\u306b\u9650\u3089\u305a\u3001\u6570\u5f0f\u3092\u8ffd\u3046\u6642\u306b\u306f\u5909\u6570\u306e\u5b57\u4f53\u3092\u898b\u3066\u3001\u305d\u306e\u5909\u6570\u306e\u5f62\u3092\u610f\u8b58\u3059\u308b\u306e\u304c\u304a\u3059\u3059\u3081\u3067\u3042\u308b\u3002\n\u5909\u6570\u306e\u5f62\u3068\u5b57\u4f53\u306e\u5bfe\u5fdc\u95a2\u4fc2\u306f\u6559\u79d1\u66f8\u306b\u3088\u3063\u3066\u6d41\u6d3e\u304c\u3042\u308b\u304c\u3001\u4ee5\u4e0b\u306b\u305d\u306e\u4e00\u4f8b\u3092\u7d39\u4ecb\u3059\u308b\uff08\u672c\u8cc7\u6599\u3082\u3053\u306e\u898f\u7d04\u306b\u5f93\u3046\uff09\u3002\n\n|  \u5b57\u4f53  | \u5c0f\u6587\u5b57         | \u5927\u6587\u5b57         |\n|:------:|:--------------:|:--------------:|\n| \u7d30\u5b57   | \u30b9\u30ab\u30e9\u306e\u5909\u6570 ($a, b$ \u306a\u3069) | \u30b9\u30ab\u30e9\u306e\u5b9a\u6570 ($A, B$ \u306a\u3069) |\n| \u592a\u5b57   | \u30d9\u30af\u30c8\u30eb (${\\bf x}, {\\bf y}$ \u306a\u3069)       | \u884c\u5217\u3001\u30c6\u30f3\u30bd\u30eb (${\\bf A}, {\\bf B}$ \u306a\u3069) |\n\n&nbsp;\n\n# \u3044\u307e\u3053\u3053 2\n\n### \u52a0\u7b97\u30fb\u6e1b\u7b97\u30fb\u30b9\u30ab\u30e9\u500d\n\n\u6b21\u306b\u3001\u30d9\u30af\u30c8\u30eb\u3001\u884c\u5217\u3001\u30c6\u30f3\u30bd\u30eb\u306e\u6f14\u7b97\u306b\u3064\u3044\u3066\u89e3\u8aac\u3059\u308b\u3002\n\n**\u52a0\u7b97\uff08\u8db3\u3057\u7b97\uff09**\u53ca\u3073**\u6e1b\u7b97\uff08\u5f15\u304d\u7b97\uff09**\u306f\u540c\u3058\u30b5\u30a4\u30ba\u306e\u30d9\u30af\u30c8\u30eb\u540c\u58eb\u3001\u884c\u5217\u540c\u58eb\u3001\u30c6\u30f3\u30bd\u30eb\u540c\u58eb\u306e\u9593\u3060\u3051\u3067\u6210\u7acb\u3059\u308b\u3002\n\n\u4ee5\u4e0b\u306b\u3001\u884c\u5217\u304a\u3088\u3073\u30d9\u30af\u30c8\u30eb\u540c\u58eb\u306e\u52a0\u7b97\u3092\u5177\u4f53\u4f8b\u3067\u793a\u3059\u3002\n\n**\u30d9\u30af\u30c8\u30eb\u540c\u58eb\u306e\u52a0\u7b97**\n$$\n\\begin{bmatrix}\n1 \\\\\n2 \\\\\n3\n\\end{bmatrix}+\\begin{bmatrix}\n4 \\\\\n5 \\\\\n6\n\\end{bmatrix}=\\begin{bmatrix}\n1 + 4 \\\\\n2 + 5 \\\\\n3 + 6\n\\end{bmatrix}=\\begin{bmatrix}\n5 \\\\\n7 \\\\\n9\n\\end{bmatrix}\n$$\n\n**\u884c\u5217\u540c\u58eb\u306e\u52a0\u7b97**\n$$\n\\begin{bmatrix}\n1 & 2 & 3 \\\\\n4 & 5 & 6\n\\end{bmatrix}+\\begin{bmatrix}\n7 & 8 & 9 \\\\\n10 & 11 & 12 \n\\end{bmatrix}=\\begin{bmatrix}\n1+7 & 2+8 & 3+9 \\\\\n4+10 & 5+11 & 6+12\n\\end{bmatrix}=\\begin{bmatrix}\n8 & 10 & 12 \\\\\n14 & 16 & 18\n\\end{bmatrix}\n$$\n\n\u3053\u306e\u3088\u3046\u306b\u3001\u52a0\u7b97\u3001\u6e1b\u7b97\u3067\u306f\u30d9\u30af\u30c8\u30eb\uff08\u884c\u5217/\u30c6\u30f3\u30bd\u30eb\uff09\u306e\u540c\u3058\u4f4d\u7f6e\u306b\u3042\u308b\u8981\u7d20\u540c\u58eb\u306b\u6f14\u7b97\u3092\u884c\u3046\u3002\n\u3053\u306e\u3088\u3046\u306a\u8a08\u7b97\u306f\u3001**\u8981\u7d20\u3054\u3068\u306e (element-wise)** \u8a08\u7b97\u3068\u3082\u547c\u3070\u308c\u3066\u3044\u308b\u3002\n\u30d9\u30af\u30c8\u30eb\uff08\u884c\u5217/\u30c6\u30f3\u30bd\u30eb\uff09\u306e\u30b5\u30a4\u30ba\u304c\u7570\u306a\u308b\u5834\u5408\u3001\u8a08\u7b97\u304c\u5b9a\u7fa9\u3067\u304d\u306a\u3044\u3053\u3068\u306b\u6ce8\u610f\u3059\u308b\u3002\n\n**\u30b9\u30ab\u30e9\u500d**\u3068\u306f\u30d9\u30af\u30c8\u30eb\u3001\u884c\u5217\u3001\u30c6\u30f3\u30bd\u30eb\u306b\u30b9\u30ab\u30e9\u3092\u639b\u3051\u308b\u6f14\u7b97\u3067\u3042\u308b\u3002\n\u4f8b\u3048\u3070\u3001\u30b9\u30ab\u30e9 $k$ \u306b\u5bfe\u3057\u3001\u300c\u30d9\u30af\u30c8\u30eb ${\\bf x}$ \u306e $k$ \u500d\u300d\u3068\u306f\u3001\u30d9\u30af\u30c8\u30eb\u306e\u5404\u8981\u7d20\u306b$k$\u3092\u639b\u3051\u308b\u64cd\u4f5c\u3067\u3042\u308b\u3002\n\u884c\u5217\u3084\u30c6\u30f3\u30bd\u30eb\u306e\u5834\u5408\u3082\u540c\u69d8\u306b\u8981\u7d20\u3054\u3068\u306b\u540c\u3058\u30b9\u30ab\u30e9$k$\u3092\u639b\u3051\u307e\u3059\u3002\n\u8a00\u8449\u3067\u8aac\u660e\u3059\u308b\u3088\u308a\u3082\u4ee5\u4e0b\u306e\u5177\u4f53\u4f8b\u3092\u898b\u308b\u65b9\u304c\u308f\u304b\u308a\u3084\u3059\u3044\u304b\u3082\u3057\u308c\u306a\u3044\u3002\n\n\n**\u30d9\u30af\u30c8\u30eb\u306e\u30b9\u30ab\u30e9\u500d**\n$$\n10\n\\begin{bmatrix}\n1 \\\\\n2 \\\\\n3\n\\end{bmatrix}=\\begin{bmatrix}\n10 * 1 \\\\\n10 * 2 \\\\\n10 * 3\n\\end{bmatrix}=\\begin{bmatrix}\n10 \\\\\n20 \\\\\n30\n\\end{bmatrix}\n$$\n\n**\u884c\u5217\u306e\u30b9\u30ab\u30e9\u500d**\n$$\n10\n\\begin{bmatrix}\n1 & 2 & 3 \\\\\n4 & 5 & 6\n\\end{bmatrix}=\\begin{bmatrix}\n10 * 1 & 10 * 2 & 10 * 3 \\\\\n10 * 4 & 10 * 5 & 10 * 6\n\\end{bmatrix}=\\begin{bmatrix}\n10 & 20 & 30 \\\\\n40 & 50 & 60\n\\end{bmatrix}\n$$\n\n\u30b9\u30ab\u30e9\u500d\u3092\u884c\u3046\u524d\u5f8c\u3067\u30d9\u30af\u30c8\u30eb\uff08\u884c\u5217/\u30c6\u30f3\u30bd\u30eb\uff09\u306e\u30b5\u30a4\u30ba\u306f\u5909\u5316\u3057\u306a\u3044\u3053\u3068\u306b\u6ce8\u610f\u3059\u308b\u3002\n\n### \u5185\u7a4d\n\n\u540c\u3058\u30b5\u30a4\u30ba\u306e2\u3064\u306e\u30d9\u30af\u30c8\u30eb\u306b\u306f\u3001**\u5185\u7a4d (inner product)** \u3068\u8a00\u3046\u6f14\u7b97\u304c\u5b9a\u7fa9\u3067\u304d\u308b\u3002\n\u3053\u308c\u306f\u3001\u305d\u308c\u305e\u308c\u306e\u30d9\u30af\u30c8\u30eb\u306e\u540c\u3058\u4f4d\u7f6e\u306b\u5bfe\u5fdc\u3059\u308b\u8981\u7d20\u540c\u58eb\u3092\u639b\u3051\u3001\u305d\u308c\u3089\u3092\u8db3\u3057\u5408\u308f\u305b\u308b\u8a08\u7b97\u3067\u3042\u308b\u3002\n${\\bf x}$ \u3068 ${\\bf y}$ \u306e\u5185\u7a4d\u306f ${\\bf x}\\cdot {\\bf y}$ \u3067\u8868\u3055\u308c\u307e\u3059\u3002\n\u4f8b\u3048\u3070\u3001\u4ee5\u4e0b\u306e\u4f8b\u3067\u306f 3 \u6b21\u5143\u306e\u30d9\u30af\u30c8\u30eb\u306e\u5185\u7a4d\u3092\u8a08\u7b97\u3057\u3066\u3044\u308b\u3002\n\n$$\n\\begin{aligned}& \\begin{bmatrix}\n1 & 2 & 3\n\\end{bmatrix} \\cdot \\begin{bmatrix}\n4 \\\\ \n5 \\\\ \n6\n \\end{bmatrix} = 1 \\times 4 + 2 \\times 5  + 3 \\times 6 = 32 \\end{aligned}\n$$\n\n2 \u3064\u306e\u30d9\u30af\u30c8\u30eb\u306e\u5185\u7a4d\u306f\u30b9\u30ab\u30e9\u306b\u306a\u308b\u3053\u3068\u306b\u6ce8\u610f\u3059\u308b\u3002\n\u4e0a\u306e\u4f8b\u3067\u793a\u3057\u3066\u3044\u308b\u3088\u3046\u306b\u3001\u5185\u7a4d\u3092\u8003\u3048\u308b\u6642\u306b\u306f 1 \u3064\u76ee\u306e\u30d9\u30af\u30c8\u30eb\u3092\u884c\u30d9\u30af\u30c8\u30eb\uff08\u3064\u307e\u308a\u3001\u30b9\u30ab\u30e9\u3092\u6a2a\u306b\u4e26\u3079\u305f\u30d9\u30af\u30c8\u30eb\uff09\u3068\u601d\u3046\u3068\u90fd\u5408\u304c\u3088\u3044\u3002\u3053\u308c\u306f\u6b21\u306b\u8aac\u660e\u3059\u308b\u884c\u5217\u7a4d\u306b\u95a2\u9023\u3059\u308b\u3002\u3053\u306e\u3088\u3046\u306b\u66f8\u3044\u305f\u5834\u5408\u306b\u306f\u5185\u7a4d\u3092\u8868\u3059 $\\cdot$ \u306f\u7701\u7565\u3067\u304d\u308b\u3002\n\n### \u884c\u5217\u7a4d\n\n\u884c\u5217\u306e\u4e57\u7b97\u306b\u306f\u3001**\u884c\u5217\u7a4d**\u3001**\u5916\u7a4d**\u3001**\u8981\u7d20\u7a4d\uff08\u30a2\u30c0\u30de\u30fc\u30eb\u7a4d\uff09**\u306a\u3069\u8907\u6570\u306e\u65b9\u6cd5\u304c\u3042\u308b\u3002\n\u3053\u3053\u3067\u306f\u305d\u306e\u3046\u3061\u3001\u7dda\u5f62\u4ee3\u6570\u3084\u6a5f\u68b0\u5b66\u7fd2\u306e\u591a\u304f\u306e\u554f\u984c\u3067\u767b\u5834\u3059\u308b**\u884c\u5217\u7a4d**\u306b\u3064\u3044\u3066\u8aac\u660e\u3059\u308b\u3002\n\u4ee5\u964d\u3067\u306f\u660e\u793a\u3057\u306a\u3044\u9650\u308a\u3001\u300c\u884c\u5217\u306e\u639b\u3051\u7b97\u300d\u3068\u8a00\u3063\u305f\u3068\u304d\u306b\u306f\u884c\u5217\u7a4d\u3092\u6307\u3059\u3053\u3068\u3068\u3059\u308b\u3002\n\n\u884c\u5217 ${\\bf A}$ \u3068\u884c\u5217 ${\\bf B}$ \u306e\u884c\u5217\u7a4d\u306f ${\\bf AB}$ \u3068\u66f8\u304d \u3001${\\bf A}$ \u306e\u5404\u884c\u3068 ${\\bf B}$ \u306e\u5404\u5217\u306e\u5185\u7a4d\u3092\u4e26\u3079\u305f\u3082\u306e\u3068\u3057\u3066\u5b9a\u7fa9\u3055\u308c\u307e\u3059\u3002\n\u4f8b\u3048\u3070\u3001\u884c\u5217 ${\\bf A}$ \u306e 1 \u884c\u76ee\u306e\u884c\u30d9\u30af\u30c8\u30eb\u3068\u3001\u884c\u5217 ${\\bf B}$ \u306e 1 \u5217\u76ee\u306e\u5217\u30d9\u30af\u30c8\u30eb\u306e\u5185\u7a4d\u306e\u7d50\u679c\u306f\u3001${\\bf A}$ \u3068 ${\\bf B}$ \u306e\u884c\u5217\u7a4d\u306e\u7d50\u679c\u3092\u8868\u3059\u884c\u5217 ${\\bf C}$ \u306e 1 \u884c 1 \u5217\u76ee\u306b\u5bfe\u5fdc\u3059\u308b\u3002\n\n**\u56f3\u8868**\n\n\n\n\n\u5185\u7a4d\u304c\u5b9a\u7fa9\u3055\u308c\u308b\u6761\u4ef6\u306f\u30d9\u30af\u30c8\u30eb\u306e\u30b5\u30a4\u30ba\u304c\u7b49\u3057\u304f\u306a\u3051\u308c\u3070\u306a\u3089\u306a\u3044\u3067\u3057\u305f\u3002\u3053\u3053\u3067\u3082\u305d\u308c\u304c\u6210\u308a\u7acb\u305f\u306a\u3051\u308c\u3070\u306a\u3089\u306a\u3044\u3002\u5177\u4f53\u7684\u306b\u306f\u3001${\\bf A} \\in \\mathbb{R}^{N \\times M}$, ${\\bf B} \\in \\mathbb{R}^{O \\times  P}$ \u306e\u6642\u3001${\\bf A} {\\bf B}={\\bf C}$ \u306e\u884c\u5217\u7a4d\u3092\u5b9a\u7fa9\u3059\u308b\u305f\u3081\u306b\u306f\u3001${\\bf  A}$ \u306e**\u5217\u6570** $M$ \u3068 ${\\bf B}$ \u306e**\u884c\u6570**  $O$ \u304c\u4e00\u81f4\u3059\u308b\u5fc5\u8981\u304c\u3042\u308b\uff08[\u6ce8\u91c81](#note1)\uff09\u3002\n\u3064\u307e\u308a\u3001\n\n$$\nM = O\n$$\n\n\u3067\u306a\u3051\u308c\u3070\u306a\u3089\u306a\u3044\u3002\n\u305d\u3057\u3066\u3001\u7d50\u679c\u306e\u884c\u5217 ${\\bf C}$ \u306e\u884c\u6570\u3068\u5217\u6570\u306f ${\\bf A}$ \u306e\u884c\u6570 $N$ \u3068 ${\\bf B}$ \u306e\u5217\u6570 $P$ \u3068\u305d\u308c\u305e\u308c\u7b49\u3057\u304f\u306a\u308b\u3002\n\u3059\u306a\u308f\u3061\u3001${\\bf C} \\in \\mathbb{R}^{N \\times P}$ \u3067\u3042\u308b\u3002\n\n2 \u3064\u306e $N$ \u6b21\u5143\u30d9\u30af\u30c8\u30eb ${\\bf x}, {\\bf y}$ \u306e\u5185\u7a4d\u306f\u3001 ${\\bf x}$ \u3092\u30b5\u30a4\u30ba $(1, N)$ \u306e\u884c\u5217\uff08\u3059\u306a\u308f\u3061\u884c\u30d9\u30af\u30c8\u30eb\uff09\uff0c${\\bf y}$ \u3092\u30b5\u30a4\u30ba $(N, 1)$ \u306e\u884c\u5217\uff08\u3059\u306a\u308f\u3061\u5217\u30d9\u30af\u30c8\u30eb\uff09\u3068\u307f\u306a\u3057\u3066\u884c\u5217\u7a4d\u3092\u884c\u3046\u3053\u3068\u3068\u8003\u3048\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n2 \u3064\u306e\u30d9\u30af\u30c8\u30eb\u306e\u884c\u5217\u7a4d\u306f\u30b5\u30a4\u30ba\u304c $(1, 1)$ \u306e\u884c\u5217\u3001\u3059\u306a\u308f\u3061\u30b9\u30ab\u30e9\u3068\u306a\u308b\u3002\u3053\u308c\u306f 2 \u3064\u306e\u30d9\u30af\u30c8\u30eb\u306e\u5185\u7a4d\u306e\u7d50\u679c\u304c\u30b9\u30ab\u30e9\u3068\u306a\u308b\u3053\u3068\u3068\u4e00\u81f4\u3057\u3066\u3044\u308b\u3002\n\n**\u56f3\u8868**\n\n\n\n\u884c\u5217\u7a4d\u306f${\\bf AB}$ \u3068 ${\\bf BA}$ \u304c\u7b49\u3057\u3044\u3068\u306f\u9650\u3089\u306a\u3044\u3068\u8a00\u3046\u70b9\u3067\u30b9\u30ab\u30e9\u306e\u639b\u3051\u7b97\u3068\u5927\u304d\u304f\u7570\u306a\u308b\u3002\u4f8b\u3048\u3070\u3001\n\n$$\n{\\bf A} = \\begin{bmatrix}\n1 & 2 \\\\\n3 & 4 \n\\end{bmatrix}, \n{\\bf B} = \\begin{bmatrix}\n5 & 6 \\\\\n7 & 8 \n\\end{bmatrix}\n$$\n\n\u3068\u3059\u308b\u3068\uff0c\n\n$$\n{\\bf AB} = \\begin{bmatrix}\n1 & 2 \\\\\n3 & 4 \n\\end{bmatrix}\n\\begin{bmatrix}\n5 & 6 \\\\\n7 & 8 \n\\end{bmatrix} = \n\\begin{bmatrix}\n1 * 5 + 2 * 7 & 1 * 6 + 2 * 8 \\\\\n3 * 5 + 4 * 7 & 3 * 6 + 4 * 8\n\\end{bmatrix} = \n\\begin{bmatrix}\n19 & 22 \\\\\n43 & 50\n\\end{bmatrix}\n$$\n\n$$\n{\\bf BA} = \\begin{bmatrix}\n5 & 6 \\\\\n7 & 8 \n\\end{bmatrix}\n\\begin{bmatrix}\n1 & 2 \\\\\n3 & 4 \n\\end{bmatrix} = \n\\begin{bmatrix}\n5 * 1 + 6 * 3 & 5 * 2 + 6 * 4 \\\\\n7 * 1 + 8 * 3 & 7 * 2 + 8 * 4\n\\end{bmatrix} = \n\\begin{bmatrix}\n23 & 34 \\\\\n31 & 46\n\\end{bmatrix}\n$$\n\n\u3068\u306a\u308a\u3001 ${\\bf AB} \\not = {\\bf BA}$ \u3067\u3042\u308b\u3002\n\u639b\u3051\u7b97\u306e\u9806\u5e8f\u306e\u9055\u3044\u3092\u660e\u793a\u7684\u306b\u8868\u73fe\u3059\u308b\u5834\u5408\u3001\u884c\u5217 ${\\bf A}$ \u306b\u884c\u5217 ${\\bf B}$ \u3092\u5de6\u304b\u3089\u639b\u3051\u308b\u3053\u3068\uff08 ${\\bf BA}$ \u306e\u8a08\u7b97\uff09\u3092\u884c\u5217 ${\\bf B}$ \u3092\u884c\u5217 ${\\bf A}$ \u306b**\u5de6\u4e57**\u3059\u308b\u3068\u8a00\u3044\u3001\u53f3\u304b\u3089\u639b\u3051\u308b\u5834\u5408\u306f**\u53f3\u4e57**\u3059\u308b\u3068\u8a00\u3046\u3002\n\n${\\bf A}$ \u3068 ${\\bf B}$ \u306e\u9078\u3073\u65b9\u306b\u3088\u3063\u3066\u306f ${\\bf AB}$ \u3068 ${\\bf BA}$ \u304c\u7b49\u3057\u304f\u306a\u308b\u5834\u5408\u3082\u3042\u308b\u3002\n\u4f8b\u3048\u3070\u3001\n\n$$\n{\\bf A} = \\begin{bmatrix}\n1 & 2 \\\\\n3 & 4 \n\\end{bmatrix}, \n{\\bf B} = \\begin{bmatrix}\n3 & 0 \\\\\n0 & 3\n\\end{bmatrix}\n$$\n\n\u3068\u3059\u308b\u3068\u3001\n\n$$\n\\begin{bmatrix}\n1 & 2 \\\\\n3 & 4 \n\\end{bmatrix}\n\\begin{bmatrix}\n3 & 0 \\\\\n0 & 3\n\\end{bmatrix} =\n\\begin{bmatrix}\n3 & 0 \\\\\n0 & 3\n\\end{bmatrix}\n\\begin{bmatrix}\n1 & 2 \\\\\n3 & 4 \n\\end{bmatrix} =\n\\begin{bmatrix}\n3 & 6 \\\\\n9 & 12\n\\end{bmatrix}\n$$\n\n\u3068\u306a\u308a\u3001 ${\\bf AB}$ \u3068 ${\\bf BA}$ \u306f\u4e00\u81f4\u3059\u308b\u3002\u3053\u3053\u3067\u8ff0\u3079\u3066\u3044\u308b\u6ce8\u610f\u306f \u300c**\u3069\u3093\u306a** ${\\bf A}, {\\bf B}$ \u3067\u3082${\\bf AB} = {\\bf BA}$ \u304c\u6210\u7acb\u3059\u308b\u300d\u3068\u8a00\u3046\u4e3b\u5f35\u306f\u6b63\u3057\u304f\u306a\u3044\u3053\u3068\u3092\u610f\u5473\u3057\u3066\u3044\u308b\u3002\n\n\u305d\u308c\u3067\u306f\u3001\u884c\u5217\u306e\u8a08\u7b97\u6761\u4ef6\u3082\u78ba\u8a8d\u3057\u306a\u304c\u3089\u3001\u4e0b\u8a18\u306e 3 \u3064\u306e\u7df4\u7fd2\u554f\u984c\u306e\u8a08\u7b97\u3092\u884c\u3046\u3002\n\n$$\n\\begin{aligned}\n&\\left( 1\\right) \n\\begin{bmatrix}\n1 & 2\n\\end{bmatrix}\n\\begin{bmatrix}\n3 \\\\ \n4\n\\end{bmatrix}\\\\ \n&\\left( 2\\right) \n\\begin{bmatrix}\n1 & 2 \\\\ \n3 & 4 \n\\end{bmatrix}\\begin{bmatrix}\n5 \\\\ \n6 \n\\end{bmatrix}\\\\ \n&\\left( 3\\right) \n\\begin{bmatrix} \n1 & 2 \n\\end{bmatrix}\\begin{bmatrix} \n3 & 4 \\\\ \n5 & 6 \n\\end{bmatrix}\\begin{bmatrix} \n3 \\\\ \n1\n\\end{bmatrix} \n\\end{aligned} \n$$ \n\n\u3053\u3061\u3089\u304c\u89e3\u7b54\u3067\u3042\u308b\u3002\n\n$$\n\\begin{aligned} \n&\\left( 1\\right) \n\\begin{bmatrix} \n1 & 2 \n\\end{bmatrix}\\begin{bmatrix} \n3 \\\\ \n4 \n\\end{bmatrix} = 1\\times 3 + 2 \\times 4 = 11\\\\ \n&\\left( 2\\right) \n\\begin{bmatrix} \n1 & 2 \\\\ \n3 & 4\n\\end{bmatrix}\\begin{bmatrix} \n5 \\\\ \n6\n\\end{bmatrix} = \\begin{bmatrix} \n1 \\times 5 + 2 \\times 6 \\\\ \n3 \\times 5 + 4 \\times 6 \n\\end{bmatrix} = \\begin{bmatrix} \n17 \\\\ \n39 \n\\end{bmatrix}\\\\ \n&\\left( 3\\right) \n\\begin{bmatrix} \n1 & 2 \n\\end{bmatrix}\\begin{bmatrix} \n3 & 4 \\\\ \n5 & 6 \n\\end{bmatrix}\\begin{bmatrix} \n3 \\\\ \n1 \n\\end{bmatrix} \n=\\begin{bmatrix} \n1 & 2 \n\\end{bmatrix}\\begin{bmatrix} \n3 \\times 3 + 4 \\times 1 \\\\ \n5 \\times 3 + 6 \\times 1 \n\\end{bmatrix} = \\begin{bmatrix} \n1 & 2 \n\\end{bmatrix}\\begin{bmatrix} \n13 \\\\ \n21 \n\\end{bmatrix}\n= 1 \\times 13 + 2 \\times 21 \n=55\n\\end{aligned} \n$$\n\n\u3053\u306e\u3088\u3046\u306a\u8a08\u7b97\u306f\u3001\u6a5f\u68b0\u5b66\u7fd2\u306e\u57fa\u790e\u3092\u5b66\u7fd2\u3057\u3066\u3044\u304f\u904e\u7a0b\u3067\u3088\u304f\u767b\u5834\u3059\u308b\u3002\u884c\u5217\u7a4d\u3067\u306f\u3001\u6f14\u7b97\u524d\u3068\u5f8c\u306e\u884c\u6570\u30fb\u5217\u6570\u306e\u5909\u5316\u306b\u6ce8\u610f\u3059\u308b\u3002\n\n### \u884c\u5217\u7a4d\u306b\u3088\u308b\u30d9\u30af\u30c8\u30eb\u30fb\u884c\u5217\u306e\u30b5\u30a4\u30ba\u5909\u5316\n\n\u884c\u5217\u306e\u524d\u5f8c\u3067\u306f\u884c\u5217\u306e\u5f62\u304c\u5909\u5316\u3059\u308b\u3002\n\u5177\u4f53\u7684\u306b\u306f\u30b5\u30a4\u30ba\u304c $(L, M)$ \u3068 $(M, N)$ \u306e\u884c\u5217\u306e\u884c\u5217\u7a4d\u306e\u7d50\u679c\u306f\u30b5\u30a4\u30ba\u304c $(L, N)$ \u306e\u884c\u5217\u3068\u306a\u308b\u3002\n\u5148\u307b\u3069\u306e 3 \u3064\u306e\u7df4\u7fd2\u554f\u984c\u3067\u306f\u3001\u884c\u5217\u3084\u30d9\u30af\u30c8\u30eb\u306e\u5f62\u30fb\u30b5\u30a4\u30ba\u304c\u3069\u306e\u3088\u3046\u306b\u5909\u5316\u3057\u3066\u3044\u305f\u304b\u3092\u78ba\u8a8d\u3057\u3066\u307f\u308b\u3002\n\n**\u56f3\u8868**\n\n\n\n\n\u7279\u306b (3) \u3067\u306f\u3001\u4e00\u756a\u5de6\u7aef\u306e\u30d9\u30af\u30c8\u30eb\u3068\u3001\u771f\u3093\u4e2d\u306e\u884c\u5217\u306e\u4e57\u7b97\u7d50\u679c\u304c\u3001\u884c\u30d9\u30af\u30c8\u30eb\u3067\u3042\u308b\u305f\u3081\u3001\u30b5\u30a4\u30ba\u306e\u5909\u5316\u304c (1) \u3068\u540c\u3058\u30b1\u30fc\u30b9\u306b\u5e30\u7740\u3059\u308b\u3053\u3068\u306b\u6ce8\u610f\u3059\u308b\u3002\n\n\u307e\u305f\u3001\u4f8b\u3048\u3070 $(3, 1)$ \u306e\u884c\u5217\u306e\u3088\u3046\u306b\u3042\u308b\u6b21\u5143\u306e\u30b5\u30a4\u30ba\u304c 1 \u3068\u306a\u3063\u305f\u5834\u5408\u3001\u305d\u306e\u6b21\u5143\u3092\u524a\u9664\u3059\u308b\u5834\u5408\u304c\u3042\u308b\u3002\u4f8b\u3048\u3070 (2)\u306e\u8a08\u7b97\u7d50\u679c\u306f\u30b5\u30a4\u30ba\u304c $(2, 1)$ \u306e\u884c\u5217\u3067\u3042\u308b\u304c\u3001\u3053\u308c\u306f2\u6b21\u5143\u306e\u30d9\u30af\u30c8\u30eb\u3068\u3057\u3066\u6271\u3048\u307e\u3059\u3002\u540c\u69d8\u306b\u3001 (1), (3) \u306e\u7b54\u3048\u306f\u30b5\u30a4\u30ba $(1, 1)$ \u306e\u884c\u5217\u3067\u3042\u308b\u304c\u3001\u30b9\u30ab\u30e9\u3068\u307f\u306a\u3059\u3053\u3068\u304c\u3067\u304d\u308b\u3002\u3053\u306e\u3088\u3046\u306b\u30b5\u30a4\u30ba\u304c 1 \u306b\u306a\u3063\u305f\u6b21\u5143\u3092\u3064\u3076\u3059\u64cd\u4f5c\u3092\u3057\u3070\u3057\u3070 `squeeze` \u3068\u547c\u3076\u3002\n\n### \u8ee2\u7f6e\n\n\u30d9\u30af\u30c8\u30eb\u306f\u7e26\u65b9\u5411\u306b\u8981\u7d20\u304c\u4e26\u3093\u3060\u5217\u30d9\u30af\u30c8\u30eb\u3092\u57fa\u672c\u3068\u3057\u3066\u3044\u307e\u3057\u305f\u304c\u3001\u6a2a\u65b9\u5411\u306b\u8981\u7d20\u304c\u4e26\u3093\u3060\u884c\u30d9\u30af\u30c8\u30eb\u3092\u4f7f\u3044\u305f\u3044\u5834\u5408\u3082\u3042\u308b\u3002\u305d\u3053\u3067\u5217\u30d9\u30af\u30c8\u30eb\u3092\u884c\u30d9\u30af\u30c8\u30eb\u306b\u3001\u884c\u30d9\u30af\u30c8\u30eb\u3092\u5217\u30d9\u30af\u30c8\u30eb\u306b\u5909\u63db\u3059\u308b\u64cd\u4f5c\u3092**\u8ee2\u7f6e (transpose)** \u3068\u547c\u3076\u3002\u8ee2\u7f6e\u306f\u30d9\u30af\u30c8\u30eb\u306e\u53f3\u80a9\u306b ${\\rm T}$ \u3068\u66f8\u304f\u3053\u3068\u3067\u8868\u3059\u3002\u4f8b\u3048\u3070\u3001 ${\\bf x}$ \u304c 3 \u6b21\u5143\u306e\u30d9\u30af\u30c8\u30eb\u306a\u3089\u3070\u3001\n\n$$\n{\\bf x}\n=\\begin{bmatrix}\n1 \\\\\n2 \\\\\n3\n\\end{bmatrix}, \\ \n{\\bf x}^{\\rm T} = \\begin{bmatrix} 1 & 2 & 3 \\end{bmatrix}\n$$\n\n\u3067\u3042\u308b\u3002\n\u8ee2\u7f6e\u306f\u884c\u5217\u306b\u5bfe\u3057\u3066\u3082\u5b9a\u7fa9\u3067\u304d\u308b\u3002\u4f8b\u3048\u3070\u3001\n\n$$\n{\\bf X}\n=\\begin{bmatrix}\n1 & 4 \\\\\n2 & 5 \\\\\n3 & 6\n\\end{bmatrix}, \\\n{\\bf X}^{\\rm T}=\\begin{bmatrix}\n1 & 2 & 3 \\\\\n4 & 5 & 6\n\\end{bmatrix}\n$$\n\n\u3067\u3042\u308b\u3002\u884c\u5217\u306b\u5bfe\u3059\u308b\u8ee2\u7f6e\u3067\u306f\u3001\u884c\u3068\u5217\u304c\u5165\u308c\u66ff\u308f\u308b\u305f\u3081\u3001\u30b5\u30a4\u30ba\u304c $(N, M)$ \u3060\u3063\u305f\u884c\u5217\u306f\u3001\u8ee2\u7f6e\u3059\u308b\u3068\u30b5\u30a4\u30ba\u304c $(M, N)$ \u306e\u884c\u5217\u3068\u306a\u308b\u3002\u3064\u307e\u308a\u3001 $i$ \u884c $j$ \u5217\u76ee\u306e\u5024\u304c\u8ee2\u7f6e\u5f8c\u306b\u306f $j$ \u884c $i$ \u5217\u76ee\u306e\u5024\u306b\u306a\u308b\u3002\u8ee2\u7f6e\u306e\u516c\u5f0f\u3068\u3057\u3066\u6b21\u3092\u899a\u3048\u3066\u304a\u304f\u3002\n\n$$\n\\begin{aligned}\n&\\left( 1\\right) \\ \\left( {\\bf A}^{\\rm T} \\right)^{\\rm T} = {\\bf A} \\\\\n&\\left( 2\\right) \\ \\left( {\\bf A}{\\bf B} \\right)^{\\rm T} = {\\bf B}^{\\rm T}{\\bf A}^{\\rm T}\\\\\n&\\left( 3\\right) \\ \\left( {\\bf A}{\\bf B}{\\bf C} \\right)^{\\rm T} = {\\bf C}^{\\rm T}{\\bf B}^{\\rm T}{\\bf A}^{\\rm T}\n\\end{aligned}\n$$\n\n\n\u8ee2\u7f6e\u3092\u7528\u3044\u308b\u3068\u3001 2 \u3064\u306e\u5217\u30d9\u30af\u30c8\u30eb ${\\bf x}$, ${\\bf y}$ \u306e\u5185\u7a4d ${\\bf x}\\cdot {\\bf y}$ \u306f\u3001\u884c\u5217\u7a4d\u3092\u7528\u3044\u3066 ${\\bf x^{\\rm T} y}$ \u3068\u66f8\u3051\u308b\u3053\u3068\u306b\u6ce8\u610f\u3059\u308b\u3002\n\n### \u5358\u4f4d\u884c\u5217\n\n\u30b9\u30ab\u30e9\u5024\u306e $1$ \u306f\u3001 $10 \\times 1 = 10$ \u306e\u3088\u3046\u306b\u3001\u4efb\u610f\u306e\u6570\u3092 $1$ \u306b\u4e57\u3058\u3066\u3082\u5024\u304c\u5909\u5316\u3057\u306a\u3044\u3068\u8a00\u3046\u6027\u8cea\u3092\u6301\u3061\u307e\u3059\u3002\u884c\u5217\u306e\u6f14\u7b97\u306b\u304a\u3044\u3066\u3001\u3053\u308c\u3068\u540c\u69d8\u306e\u50cd\u304d\u3092\u3059\u308b\u884c\u5217\u304c**\u5358\u4f4d\u884c\u5217 (identity matrix, unit matrix)** \u3067\u3042\u308b\uff08[\u6ce8\u91c82](#note2)\uff09\u3002\n\u5358\u4f4d\u884c\u5217\u306f\n\n$$\n{\\bf I} =\n\\begin{bmatrix}\n1 & 0 & \\cdots  & 0 \\\\\n0 & 1 & \\cdots  & 0 \\\\\n\\vdots & \\vdots & \\ddots & \\vdots  \\\\\n0 & 0 & \\cdots  & 1\n\\end{bmatrix}\n$$\n\n\u3068\u8a00\u3046\u5f62\u3092\u3057\u3066\u304a\u308a\u3001\u8a18\u53f7 ${\\bf I}$ \u3067\u8868\u3059\u306e\u304c\u4e00\u822c\u7684\u3067\u3042\u308b\u3002\u884c\u5217\u306e\u659c\u3081\u306e\u8981\u7d20\u3092**\u5bfe\u89d2\u8981\u7d20**\u3068\u3088\u3073\u3001\u305d\u308c\u4ee5\u5916\u306e\u8981\u7d20\u3092\u975e\u5bfe\u89d2\u8981\u7d20\u3068\u3088\u3073\u307e\u3059\u3002\u5358\u4f4d\u884c\u5217\u306f\u3001\u5bfe\u89d2\u8981\u7d20\u304c\u5168\u3066 $1$ \u3067\u3001\u975e\u5bfe\u89d2\u8981\u7d20\u304c\u5168\u3066 $0$ \u3067\u3042\u308b\u3088\u3046\u306a **\u6b63\u65b9\u884c\u5217**\uff08\u884c\u6570\u3068\u5217\u6570\u304c\u7b49\u3057\u3044\u884c\u5217\uff09\u3067\u3042\u308b\u3002\u4f8b\u3048\u3070\u3001$2 \\times 2$ \u306e\u5358\u4f4d\u884c\u5217\u306f\u3001\n\n$$\n{\\bf I} =\n\\begin{bmatrix}\n1 & 0 \\\\\n0 & 1\n\\end{bmatrix}\n$$\n\n\u3067\u3042\u308a\u3001$3 \\times 3$\u306e\u5358\u4f4d\u884c\u5217\u306f\u3001\n\n$$\n{\\bf I} =\n\\begin{bmatrix}\n1 & 0 & 0 \\\\\n0 & 1 & 0 \\\\\n0 & 0 & 1\n\\end{bmatrix}\n$$\n\n\u3067\u3042\u308b\u3002\u884c\u5217\u306e\u30b5\u30a4\u30ba\u3092\u660e\u793a\u3057\u305f\u3044\u5834\u5408\u306b\u306f\u3001 $I_n$ \uff08 $n \\times n$ \u306e\u5358\u4f4d\u884c\u5217\u306e\u610f\u5473\uff09\u3068\u6dfb\u5b57\u3067\u30b5\u30a4\u30ba\u3092\u8868\u8a18\u3059\u308b\u3053\u3068\u304c\u3042\u308b\u3002\n\n\u5358\u4f4d\u884c\u5217\u306f\u30b5\u30a4\u30ba\u304c\u7b49\u3057\u3044\u4efb\u610f\u306e\u6b63\u65b9\u884c\u5217 ${\\bf A}$ \u306b\u5bfe\u3057\u3066\u4ee5\u4e0b\u306e\u8a08\u7b97\u304c\u6210\u7acb\u3059\u308b\u3002\n\n$$\n\\begin{aligned}\n{\\bf A}{\\bf I} &= {\\bf A} \\\\\n{\\bf I}{\\bf A} &= {\\bf A}\n\\end{aligned}\n$$\n\n\u9069\u5f53\u306a\u884c\u5217\u3067\u3001\u5358\u4f4d\u884c\u5217\u3092\u639b\u3051\u3066\u3082\u5143\u306e\u884c\u5217\u3068\u5024\u304c\u5909\u308f\u3089\u306a\u3044\u3053\u3068\u3092\u78ba\u8a8d\u3057\u3066\u307f\u308b\u3002\n\n$$\n\\begin{aligned}\n\\begin{bmatrix}\n1 & 2 \\\\\n3 & 4\n\\end{bmatrix}\n\\begin{bmatrix}\n1 & 0 \\\\\n0 & 1\n\\end{bmatrix}\n&=\n\\begin{bmatrix}\n1 \\times 1 + 2 \\times 0 & 1 \\times 0 + 2 \\times 1 \\\\\n3 \\times 1 + 4 \\times 0 & 3 \\times 0 + 4 \\times 1\n\\end{bmatrix} \\\\\n&=\n\\begin{bmatrix}\n1 & 2 \\\\\n3 & 4\n\\end{bmatrix}\n\\end{aligned}\n$$\n\n\u8a08\u7b97\u7d50\u679c\u304b\u3089\u5206\u304b\u308b\u901a\u308a\u3001\u5143\u306e\u884c\u5217\u3068\u5168\u3066\u306e\u8981\u7d20\u304c\u4e00\u81f4\u3057\u307e\u3057\u305f\u3002\n${\\bf I}$ \u3092\u5de6\u304b\u3089\u639b\u3051\u3066\u3082\u540c\u69d8\u306e\u7d50\u679c\u3068\u306a\u308b\u3053\u3068\u3092\u78ba\u304b\u3081\u3066\u307f\u308b\u3002\n\n### \u9006\u884c\u5217\n\n$0$ \u3067\u306a\u3044\u30b9\u30ab\u30e9 $x$ \u306b\u306f\u3001 \u9006\u6570 $x^{-1}$ \u3092\u8003\u3048\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\u884c\u5217\u3067\u9006\u6570\u306b\u5bfe\u5fdc\u3059\u308b\u3082\u306e\u304c **\u9006\u884c\u5217 (inverse matrix)** \u3067\u3042\u308b\u3002\n\n\u53b3\u5bc6\u306a\u5b9a\u7fa9\u306f\u6b21\u306e\u901a\u308a\u3067\u3042\u308b\u3002\u884c\u5217 ${\\bf A}$ \u306b\u5bfe\u3057\u3001 ${\\bf AB} = {\\bf I}$ , ${\\bf BA} = {\\bf I}$ \u3092\u6e80\u305f\u3059\u884c\u5217 ${\\bf B}$ \u306e\u3053\u3068\u3092 ${\\bf A}$ \u306e\u9006\u884c\u5217 \u3068\u8a00\u3046\u3002\n\u3053\u306e\u3088\u3046\u306a\u6761\u4ef6\u3092\u6e80\u305f\u3059\u884c\u5217 ${\\bf B}$ \u306f \u884c\u5217 ${\\bf A}$ \u306b\u3088\u3063\u3066\u5b58\u5728\u3057\u305f\u308a\u5b58\u5728\u3057\u306a\u304b\u3063\u305f\u308a\u3059\u308b\u3002\n\u3057\u304b\u3057\u3001\u3082\u3057 ${\\bf A}$ \u306b\u5bfe\u3057\u3053\u306e\u6761\u4ef6\u3092\u6e80\u305f\u3059\u884c\u5217\u304c\u5b58\u5728\u3059\u308b\u306a\u3089\u3070\u3001\u305d\u306e\u3088\u3046\u306a\u884c\u5217\u306f\u305f\u3060 1 \u3064\u3067\u3042\u308b\u3053\u3068\u304c\u77e5\u3089\u308c\u3066\u3044\u308b\u3002\n\u305d\u3053\u3067\u3001\u884c\u5217 ${\\bf A}$ \u306e\u9006\u884c\u5217\u3092 ${\\bf A}^{-1}$ \u3068\u66f8\u304f\u3002\n\n\u9006\u884c\u5217\u306e\u5b9a\u7fa9\u304b\u3089\u3001\n\n$$\n\\begin{aligned}\n{\\bf AA}^{-1} = {\\bf I} \\\\\n{\\bf A}^{-1}{\\bf A} = {\\bf I}\n\\end{aligned}\n$$\n\n\u304c\u6210\u7acb\u3059\u308b\u3053\u3068\u306b\u6ce8\u610f\u3059\u308b\u3002\u3053\u3053\u3067\u3001 ${\\bf I}$ \u306f\u5358\u4f4d\u884c\u5217\u3067\u3042\u308b\u3002\n\n\u9006\u884c\u5217\u304c\u5b58\u5728\u3059\u308b\u3088\u3046\u306a\u884c\u5217\u306e\u3053\u3068\u3092**\u6b63\u5247\u884c\u5217**\u3068\u547c\u3076\u3002\n\u6b63\u5247\u884c\u5217\u3068\u306a\u308b\u306b\u306f\u5c11\u306a\u304f\u3068\u3082\u884c\u5217\u7a4d ${\\bf AA^{-1}}$ \u3068 ${\\bf A^{-1}A}$ \u306e\u4e21\u65b9\u304c\u5b9a\u7fa9\u3055\u308c\u3066\u3044\u306a\u3051\u308c\u3070\u306a\u3089\u306a\u3044\u3002\n\u3053\u308c\u306f ${\\bf A}$ \u306f\u6b63\u65b9\u884c\u5217\uff08\u3064\u307e\u308a\u3001\u884c\u6570\u3068\u5217\u6570\u304c\u540c\u3058\u884c\u5217\uff09\u3067\u3042\u308b\u3053\u3068\u3092\u610f\u5473\u3059\u308b \uff08\u306a\u305c\u304b\u8003\u3048\u3066\u307f\u308b\uff09\u3002\n\u3057\u304b\u3057\u3001 ${\\bf A}$ \u306e\u884c\u6570\u3068\u5217\u6570\u304c\u540c\u3058\u3067\u3042\u308b\u304b\u3089\u3068\u8a00\u3063\u3066\u3001\u5e38\u306b ${\\bf A}$ \u304c\u6b63\u5247\u884c\u5217\u3068\u306f\u9650\u3089\u306a\u3044\u3002\n\u884c\u5217\u304c\u6b63\u5247\u3067\u3042\u308b\u305f\u3081\u306e\u6761\u4ef6\u306b\u95a2\u3059\u308b\u8a73\u7d30\u306a\u8aac\u660e\u306f\u3053\u3053\u3067\u306f\u7701\u7565\u3059\u308b\u3002\n\n\u30b5\u30a4\u30ba\u304c $2 \\times 2$ \u3084 $3 \\times 3$ \u3068\u3044\u3063\u305f\u5c0f\u3055\u306a\u884c\u5217\u306e\u5834\u5408\u306b\u306f\u3001\u624b\u8a08\u7b97\u3067\u3082\u53ef\u80fd\u306a\u9006\u884c\u5217\u8a08\u7b97\u306e\u65b9\u6cd5\u304c\u77e5\u3089\u308c\u3066\u3044\u308b\u304c\u3001\u6a5f\u68b0\u5b66\u7fd2\u3067\u306f\u3088\u308a\u5927\u304d\u306a\u30b5\u30a4\u30ba\u306e\u884c\u5217\uff08 $1000 \\times 1000$ \u306a\u3069\uff09\u3092\u6271\u3046\u3053\u3068\u304c\u3042\u308a\u3001\u305d\u3046\u3044\u3063\u305f\u5927\u304d\u306a\u884c\u5217\u306e\u9006\u884c\u5217\u3092\u52b9\u7387\u7684\u307e\u305f\u306f\u8fd1\u4f3c\u7684\u306b\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u3092\u4f7f\u3063\u3066\u8a08\u7b97\u3059\u308b\u624b\u6cd5\u304c\u7814\u7a76\u3055\u308c\u3066\u3044\u308b\u3002\n\n### \u7dda\u5f62\u7d50\u5408\u3068\u4e8c\u6b21\u5f62\u5f0f\n\n\u6a5f\u68b0\u5b66\u7fd2\u306e\u6570\u5f0f\u3067\u983b\u51fa\u3059\u308b\u5f62\u5f0f\u3068\u3057\u3066\u3001 ${\\bf b}^{\\rm T}{\\bf x}$ \u3068 ${\\bf x}^{\\rm T}{\\bf A}{\\bf x}$ \u306e 2 \u3064\u304c\u3042\u308b\u3002\n\u524d\u8005\u306f**\u7dda\u5f62\u7d50\u5408**\u3082\u3057\u304f\u306f**\u4e00\u6b21\u7d50\u5408**\u3001\u5f8c\u8005\u306f**\u4e8c\u6b21\u5f62\u5f0f**\u3068\u547c\u3070\u308c\u3066\u3044\u308b\u3002\n\u30b9\u30ab\u30e9\u306e\u4e00\u6b21\u5f0f ($ax + b$) \u3084\u4e8c\u6b21\u5f0f ($ax^2 + bx + c$) \u3092\u30d9\u30af\u30c8\u30eb\u306b\u62e1\u5f35\u3057\u305f\u3082\u306e\u3068\u6349\u3048\u308b\u3068\u3088\u3044\u3067\u3057\u3087\u3046\u3002\n\n\u7dda\u5f62\u7d50\u5408\u306e\u8a08\u7b97\u3092\u8981\u7d20\u3054\u3068\u306b\u898b\u3066\u307f\u308b\u3068\u3001\n\n$$\n\\begin{aligned}\n{\\bf b}\n&=\n\\begin{bmatrix}\n1 \\\\\n2\n\\end{bmatrix},\\ \n{\\bf x} =\n\\begin{bmatrix}\nx_{1} \\\\\nx_{2}\n\\end{bmatrix}\\\\\n{\\bf b}^{\\rm T}{\\bf x}\n&=\n\\begin{bmatrix}\n1 & 2\n\\end{bmatrix}\n\\begin{bmatrix}\nx_1 \\\\\nx_2\n\\end{bmatrix}\n= x_1 + 2x_2\n\\end{aligned}\n$$\n\n\u306e\u3088\u3046\u306b ${\\bf x}$ \u306e\u8981\u7d20\u3067\u3042\u308b $x_1$ \u304a\u3088\u3073 $x_2$ \u306b\u95a2\u3057\u3066\u4e00\u6b21\u5f0f\u3068\u306a\u3063\u3066\u3044\u308b\u3002\n\n\u307e\u305f\u3001\u4e8c\u6b21\u5f62\u5f0f\u3082\u540c\u69d8\u306b\u8981\u7d20\u3054\u3068\u306b\u78ba\u8a8d\u3057\u3066\u307f\u308b\u3068\u3001\n\n$$\n\\begin{aligned}\n{\\bf A} &=\n\\begin{bmatrix}\n1 & 2 \\\\\n3 & 4\n\\end{bmatrix},\\ \n{\\bf x} =\n\\begin{bmatrix}\nx_{1} \\\\\nx_{2}\n\\end{bmatrix}\\\\\n{\\bf x}^{\\rm T}{\\bf A}{\\bf x}\n&=\n\\begin{bmatrix}\nx_1 & x_2\n\\end{bmatrix}\n\\begin{bmatrix}\n1 & 2 \\\\\n3 & 4\n\\end{bmatrix}\n\\begin{bmatrix}\nx_1 \\\\\nx_2\n\\end{bmatrix} \\\\\n&=\n\\begin{bmatrix}\nx_1 & x_2\n\\end{bmatrix}\n\\begin{bmatrix}\nx_1 + 2x_2 \\\\\n3x_1 + 4x_2\n\\end{bmatrix} \\\\\n&=\nx_1 \\left( x_1 + 2x_2 \\right) + x_2 \\left( 3x_1 + 4x_2 \\right) \\\\\n&=\nx^2_1 + 5x_1 x_2 + 4x_2^2\n\\end{aligned}\n$$\n\n\u3068\u306a\u308a\u3001\u5404\u8981\u7d20\u306b\u95a2\u3057\u3066\u4e8c\u6b21\u5f0f\u3068\u306a\u3063\u3066\u3044\u308b\u3002\n\u4e00\u822c\u306b\u3001$x_1, \\ldots, x_N$ \u306b\u95a2\u3059\u308b\u4e8c\u6b21\u95a2\u6570\u306f\u3001\n\n$$\n{\\bf x} = \\begin{bmatrix}\nx_1 \\\\\n\\vdots \\\\\nx_n \\\\\n\\end{bmatrix}\n$$\n\n\u3068\u3057\u3066\u3001\n\n$$\n{\\bf x}^{\\rm T}{\\bf A}{\\bf x} + {\\bf b}^{\\rm T}{\\bf x} + c\n$$\n\n\u3068\u8868\u8a18\u3067\u304d\u308b\u3002\u3053\u3053\u3067\u3001 ${\\bf A}$ \u306f 2\u6b21\u306e\u9805\u306e\u4fc2\u6570\u3092\u8868\u3059\u30b5\u30a4\u30ba $(n, n)$ \u306e \u884c\u5217\u3001 ${\\bf b}$ \u306f1\u6b21\u306e\u9805\u306e\u4fc2\u6570\u3092\u8868\u3059 $n$ \u6b21\u5143\u306e\u30d9\u30af\u30c8\u30eb\u3001 $c$ \u306f\u30b9\u30ab\u30e9\u306e\u5b9a\u6570\u9805\u3067\u3042\u308b\u3002\n\n### \u30d9\u30af\u30c8\u30eb\u306b\u3088\u308b\u5fae\u5206\u3068\u52fe\u914d\n\n\u5fae\u5206\u306f\u5165\u529b\u304c\u5909\u5316\u3057\u305f\u5834\u5408\u306e\u95a2\u6570\u5024\u306e\u5909\u5316\u91cf\u304b\u3089\u6c42\u3081\u3089\u308c\u307e\u3057\u305f\u3002\n\u3053\u308c\u306f\u95a2\u6570\u306e\u5165\u529b\u304c\u30d9\u30af\u30c8\u30eb\u3067\u3042\u308b\u5834\u5408\u3082\u540c\u69d8\u3067\u3042\u308b\u3002\n\u30d9\u30af\u30c8\u30eb\u3092\u5165\u529b\u306b\u3068\u308b\u95a2\u6570\u306e\u5fae\u5206\u3092\u8003\u3048\u3066\u307f\u308b\u3002\n\u5165\u529b\u30d9\u30af\u30c8\u30eb\u306e\u8981\u7d20\u6bce\u306b\u51fa\u529b\u306b\u5bfe\u3059\u308b\u504f\u5fae\u5206\u3092\u8a08\u7b97\u3057\u3001\u305d\u308c\u3089\u3092\u4e26\u3079\u3066\u30d9\u30af\u30c8\u30eb\u306b\u3057\u305f\u3082\u306e\u304c**\u52fe\u914d (gradient)** \u3067\u3042\u308b\u3002\n\n\u307e\u305a\u52fe\u914d\u306b\u95a2\u3059\u308b\u8a08\u7b97\u306e\u5177\u4f53\u4f8b\u3092\u898b\u3066\u307f\u308b\u3002\n\n$$\n\\begin{aligned}\n{\\bf b}\n&=\\begin{bmatrix}\n3 \\\\\n4\n\\end{bmatrix}, \\ \n{\\bf x} =\n\\begin{bmatrix}\nx_{1} \\\\\nx_{2}\n\\end{bmatrix}\\\\\n{\\bf b}^{\\rm T}{\\bf x} &=\n\\begin{bmatrix}\n3 & 4\n\\end{bmatrix}\n\\begin{bmatrix}\nx_1 \\\\\nx_2\n\\end{bmatrix}\n= 3x_1 + 4x_2\n\\end{aligned}\n$$\n\n\u3053\u306e ${\\bf b}^{\\rm T}{\\bf x}$ \u3092\u30d9\u30af\u30c8\u30eb ${\\bf x}$ \u3067\u5fae\u5206\u3057\u305f\u3082\u306e\u3092\u3001\n\n$$\n\\frac{\\partial}{\\partial {\\bf x}} \\left( {\\bf b}^{\\rm T}{\\bf x} \\right)\n$$\n\n\u3068\u8868\u3059\u3002\n\u300c\u30d9\u30af\u30c8\u30eb\u3067\u5fae\u5206\u300d\u3068\u306f\u3001\u30d9\u30af\u30c8\u30eb\u306e\u305d\u308c\u305e\u308c\u306e\u8981\u7d20\u3067\u5bfe\u8c61\u3092\u5fae\u5206\u3057\u3001\u305d\u306e\u7d50\u679c\u3092\u8981\u7d20\u306b\u5bfe\u5fdc\u3059\u308b\u4f4d\u7f6e\u306b\u4e26\u3079\u3066\u30d9\u30af\u30c8\u30eb\u3092\u4f5c\u308b\u3053\u3068\u3067\u3042\u308b\u3002\n\u524d\u8ff0\u306e\u4f8b\u3067\u306f\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u8a08\u7b97\u3092\u884c\u3046\u3002\n\n$$\n\\begin{aligned}\n\\frac{\\partial}{\\partial {\\bf x}} \\left( {\\bf b}^{\\rm T} {\\bf x} \\right)\n&= \\frac{\\partial}{\\partial {\\bf x}} \\left( 3x_1 + 4x_2 \\right) \\\\\n&=\n\\begin{bmatrix}\n\\frac{\\partial}{\\partial x_1} \\left( 3x_1 + 4x_2 \\right) & \\frac{\\partial}{\\partial x_2} \\left( 3x_1 + 4x_2 \\right)\n\\end{bmatrix}\n\\end{aligned}\n$$\n\n\u5404\u8981\u7d20\u306e\u8a08\u7b97\u3092\u9032\u3081\u308b\u3068\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u306a\u308b\u3002\u672c\u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb\u3067\u306f\u3001\u30d9\u30af\u30c8\u30eb\u306f\u539f\u5247\u3068\u3057\u3066\u5217\u30d9\u30af\u30c8\u30eb\u3092\u7528\u3044\u308b\u30eb\u30fc\u30eb\u3092\u63a1\u7528\u3057\u3066\u3044\u308b\u304c\u3001\u3053\u3053\u3067\u306f\u5fae\u5206\u3057\u305f\u7d50\u679c\u3092\u884c\u30d9\u30af\u30c8\u30eb\u3067\u8868\u3057\u3066\u3044\u308b\u3053\u3068\u306b\u6ce8\u610f\u3059\u308b\u3002\u3053\u308c\u306f\u3001\u5f8c\u3067\u767b\u5834\u3059\u308b\u30d9\u30af\u30c8\u30eb\u5024\u95a2\u6570\uff08\u30d9\u30af\u30c8\u30eb\u3092\u51fa\u529b\u3068\u3059\u308b\u95a2\u6570\uff09\u306e\u5fae\u5206\u3092\u8003\u3048\u305f\u5834\u5408\u3068\u306e\u6574\u5408\u6027\u3092\u3068\u308b\u305f\u3081\u3067\u3042\u308b\u3002\n\n$$\n\\begin{aligned}\n\\frac{\\partial}{\\partial x_1} \\left( 3x_1 + 4x_2 \\right)\n&= \\frac{\\partial}{\\partial x_1} \\left( 3x_1 \\right)\n+ \\frac{\\partial}{\\partial x_1} \\left( 4x_2 \\right) \\\\\n&= 3 \\times \\frac{\\partial}{\\partial x_1} \\left( x_1 \\right)\n+ 4x_{2} \\times \\frac{\\partial}{\\partial x_1} (1) \\\\\n&= 3 \\times 1 + 4x_{2} \\times 0 \\\\\n&= 3\n\\end{aligned}\n$$\n\n$$\n\\begin{aligned}\n\\frac{\\partial}{\\partial x_2} \\left( 3x_1 + 4x_2 \\right)\n&= \\frac{\\partial}{\\partial x_2} \\left( 3x_1 \\right)\n+ \\frac{\\partial}{\\partial x_2} \\left( 4x_2 \\right) \\\\\n&= 3x_{1} \\times \\frac{\\partial}{\\partial x_2} (1)\n+ 4 \\times \\frac{\\partial}{\\partial ax_2} (x_{2}) \\\\\n&= 3x_{1} \\times 0 + 4 \\times 1 \\\\\n&= 4\n\\end{aligned}\n$$\n\n\u5f93\u3063\u3066\u3001\u8a08\u7b97\u7d50\u679c\u3092\u6574\u7406\u3059\u308b\u3068\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u306a\u308b\u3002\n\n$$\n\\begin{aligned}\n\\frac{\\partial}{\\partial {\\bf x}} \\left( {\\bf b}^{\\rm T}{\\bf x} \\right)\n&=\n\\begin{bmatrix}\n\\frac{\\partial}{\\partial x_1} \\left( 3x_1 + 4x_2 \\right) & \\frac{\\partial}{\\partial x_2} \\left( 3x_1 + 4x_2\\right) \n\\end{bmatrix}\n=\n\\begin{bmatrix}\n3 & 4\n\\end{bmatrix}\n=\n{\\bf b}^{\\rm T}\n\\end{aligned}\n$$\n\n\u3082\u3046\u4e00\u3064\u5225\u306e\u4f8b\u3092\u8003\u3048\u3066\u307f\u308b\u3002\u4eca\u5ea6\u306f\u5b9a\u6570\u30b9\u30ab\u30e9\u30fc\u3092\u30d9\u30af\u30c8\u30eb\u3067\u5fae\u5206\u3059\u308b\u3002\n\n$$\n\\begin{aligned}\nc\n&=\n3 ,\n{\\bf x}\n=\n\\begin{bmatrix}\nx_{1} \\\\\nx_{2}\n\\end{bmatrix} \\\\\n\\frac{\\partial}{\\partial {\\bf x}} \\left( c \\right)\n&=\n\\begin{bmatrix}\n\\frac{\\partial}{\\partial x_1} \\left( 3 \\right) & \\frac{\\partial}{\\partial x_2} \\left( 3 \\right)\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n0 & 0\n\\end{bmatrix}\n=\n{\\bf 0}\n\\end{aligned}\n$$\n\n\u504f\u5fae\u5206\u3092\u884c\u3046\u5bfe\u8c61\u306b\u5909\u6570\u304c\u542b\u307e\u308c\u3066\u3044\u306a\u3044\u5834\u5408\u3001\u305d\u306e\u504f\u5fae\u5206\u306f $0$ \u3068\u306a\u308b\u3002\u8981\u7d20\u304c $0$ \u306e\u307f\u3067\u69cb\u6210\u3055\u308c\u305f\u30d9\u30af\u30c8\u30eb\u3092**\u30bc\u30ed\u30d9\u30af\u30c8\u30eb**\u3068\u8a00\u3044\u3001\u6570\u5b57\u306e $0$ \u3092\u592a\u5b57\u306b\u3057\u305f ${\\bf 0}$ \u3067\u8868\u3059\u3002\n\n\u3053\u308c\u3089\u3092\u8e0f\u307e\u3048\u3066\u3001\u6a5f\u68b0\u5b66\u7fd2\u3067\u983b\u51fa\u3059\u308b\u8a08\u7b97\u7d50\u679c\u3092\u307e\u3068\u3081\u3066\u899a\u3048\u3066\u304a\u304f\u3002\n\n$$\n\\begin{aligned}\n&\\left( 1 \\right) \\ \\frac{\\partial}{\\partial {\\bf x}} \\left( c \\right) = {\\bf 0} \\\\\n&\\left( 2 \\right) \\ \\frac{\\partial}{\\partial {\\bf x}} \\left( {\\bf b}^{\\rm T}{\\bf x} \\right) = {\\bf b}^{\\rm T} \\\\\n&\\left( 3 \\right) \\ \\frac{\\partial}{\\partial {\\bf x}} \\left( {\\bf x}^{\\rm T}{\\bf A}{\\bf x} \\right) = {\\bf x}^{\\rm T} \\left( {\\bf A} + {\\bf A}^{\\rm T} \\right)\n\\end{aligned}\n$$\n\n\u3053\u3053\u3067\u3001(1) \u3068 (2) \u306f\u3059\u3067\u306b\u5c0e\u51fa\u6e08\u307f\u3067\u3042\u308b\u3002(3) \u306f\u5c0e\u51fa\u304c\u5c11\u3057\u8907\u96d1\u306a\u306e\u3067\u7701\u7565\u3059\u308b\u304c\u3001\u6570\u5024\u3092\u4ee3\u5165\u3057\u3066\u78ba\u8a8d\u3057\u3066\u307f\u308b\u3002\n\n## \u30d9\u30af\u30c8\u30eb\u3092\u5165\u529b\u3068\u3059\u308b\u95a2\u6570\n\n\u524d\u7bc0\u3067\u8003\u3048\u305f ${\\bf b^T x}$ \u3084 ${\\bf x^T A x}$ \u306f  \u30d9\u30af\u30c8\u30eb ${\\bf x}$ \u3092\u53d7\u3051\u53d6\u3063\u3066\u3001\u30b9\u30ab\u30e9 ${\\bf b^T x}$, ${\\bf x^T A x}$ \u3092\u51fa\u529b\u3059\u308b\u95a2\u6570\u3068\u8003\u3048\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002 ${\\bf x}$ \u3092\u6210\u5206\u8868\u793a\u3057\u3066\n\n$$\n{\\bf x} = \\begin{bmatrix} x_1 \\\\ x_2 \\end{bmatrix}\n$$\n\n\u3068\u66f8\u304f\u3068\u3001\u3053\u306e\u95a2\u6570\u306f 2 \u3064\u306e\u30b9\u30ab\u30e9\u5909\u6570 $x_1$, $x_2$ \u3092\u5165\u529b\u3068\u3059\u308b\u591a\u5909\u6570\u95a2\u6570\u3067\u3042\u308b\u3002\n\u540c\u69d8\u306b\u3001\u5165\u529b\u304c $M$ \u500b\u306e\u30b9\u30ab\u30e9\u5909\u6570\u306e\u95a2\u6570\u306f\u3001 $M$ \u6b21\u5143\u306e\u30d9\u30af\u30c8\u30eb 1 \u500b\u3092\u5165\u529b\u3068\u3059\u308b\u95a2\u6570\u3068\u3082\u89e3\u91c8\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\u591a\u5909\u6570\u95a2\u6570 $f(x_1, \\ldots, x_M)$ \u306f\u3001\u5165\u529b\u3092\u307e\u3068\u3081\u3066\n\n$$\n{\\bf x} = \\begin{bmatrix} x_1 \\\\ \\vdots \\\\ x_M \\end{bmatrix}\n$$\n\n\u3068\u66f8\u304d\u3001 $f({\\bf x})$ \u3068\u8868\u8a18\u3057\u3066\u3082\u69cb\u308f\u306a\u3044\u3002 $f({\\bf x})$ \u306e\u5fae\u5206\u306f\u3001\u524d\u7ae0\u3067\u8aac\u660e\u3057\u305f\u504f\u5fae\u5206\u3092\u5404\u5909\u6570 $x_1, \\ldots, x_M$ \u306b\u5bfe\u3057\u3066\u884c\u3044\n\n$$\n\\frac{\\partial}{\\partial {\\bf x}} f({\\bf x}) =\n\\begin{bmatrix}\n    \\frac{\\partial}{\\partial x_1} f({\\bf x})  & \\dots & \\frac{\\partial}{\\partial x_M} f({\\bf x}) \\\\\n\\end{bmatrix}\n$$\n\n\u3068\u8a08\u7b97\u3059\u308b\u3002\n\n## \u30d9\u30af\u30c8\u30eb\u5024\u95a2\u6570\n\n\u6b21\u306b\u5165\u529b\u3067\u306f\u306a\u304f\u51fa\u529b\u304c\u591a\u5909\u6570\u306e\u95a2\u6570\u3092\u8003\u3048\u307e\u3059\u3002\n\u307e\u305a\u30011 \u3064\u306e\u30b9\u30ab\u30e9\u5909\u6570 $x$ \u3092\u5165\u529b\u3068\u3057\u3001 $N$ \u500b\u306e\u30b9\u30ab\u30e9\uff08\u3064\u307e\u308a\u3001 $N$ \u6b21\u5143\u306e\u30d9\u30af\u30c8\u30eb\u3092 1 \u500b\uff09\u3092\u51fa\u529b\u3059\u308b\u95a2\u6570 ${\\bf f}(x)$ \u3092\u8003\u3048\u307e\u3059\u3002\n\u30d9\u30af\u30c8\u30eb\u5909\u6570\u306f ${\\bf y}$ \u306a\u3069\u306e\u592a\u5b57\u3067\u66f8\u3044\u3066\u3044\u307e\u3057\u305f\u3002\u305d\u308c\u3068\u540c\u69d8\u306b\u3001\u3053\u306e\u95a2\u6570\u3082\u51fa\u529b\u304c\u30d9\u30af\u30c8\u30eb\u3067\u3042\u308b\u3053\u3068\u3092\u5f37\u8abf\u3057\u3066 ${\\bf f}$ \u3068\u592a\u5b57\u3067\u8868\u3059\u3002\n${\\bf f}$ \u306e\u3088\u3046\u306b\u51fa\u529b\u304c\u30d9\u30af\u30c8\u30eb\u3067\u3042\u308b\u95a2\u6570\u3092 **\u30d9\u30af\u30c8\u30eb\u5024\u95a2\u6570 (vector-valued function)** \u3068\u547c\u3076\u3002\u305d\u308c\u306b\u5bfe\u3057\u3001\u51fa\u529b\u304c\u30b9\u30ab\u30e9\u3067\u3042\u308b\u95a2\u6570\u3092\uff08\u305d\u306e\u3053\u3068\u3092\u5f37\u8abf\u3057\u305f\u3044\u5834\u5408\u306b\u306f\uff09 **\u30b9\u30ab\u30e9\u5024\u95a2\u6570 (scalar-valued function)** \u3068\u547c\u3076\u3002\n\n${\\bf f}$ \u306e\u51fa\u529b\u306e\u5404\u6210\u5206\u306b\u6ce8\u76ee\u3059\u308b\u3068\u3001 ${\\bf f}$ \u306f $N$ \u500b\u306e\u30b9\u30ab\u30e9\u5024\u95a2\u6570\u306e\u96c6\u307e\u308a\u3068\u8003\u3048\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\u3064\u307e\u308a\u3001 $x$ \u3092\u53d7\u3051\u53d6\u308a\u3001 ${\\bf f}$ \u306e \u7b2c $n$ \u6210\u5206\u3092\u51fa\u529b\u3059\u308b\u95a2\u6570\u3092 $f_n$ \u3068\u66f8\u304f\u3068\u3001\n\n$$\n{\\bf f}(x) = \\begin{bmatrix}f_1(x) \\\\ \\vdots \\\\ f_N(x)\\end{bmatrix}\n$$\n\n\u3067\u3042\u308b\u3002\n\u5165\u529b\u304c\u591a\u5909\u6570\u3067\u3082\u540c\u69d8\u306b\u6210\u5206\u8868\u793a\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\u3059\u306a\u308f\u3061\u3001\u5165\u529b\u5909\u6570\u304c $M$ \u6b21\u5143\u30d9\u30af\u30c8\u30eb\u3001\u51fa\u529b\u5909\u6570\u304c $N$ \u6b21\u5143\u30d9\u30af\u30c8\u30eb\u3067\u3042\u308b\u95a2\u6570 ${\\bf g}$ \u306f\n\n$$\n{\\bf g}({\\bf x}) = \n\\begin{bmatrix}g_1({\\bf x}) \\\\ \\vdots \\\\ g_N({\\bf x})\\end{bmatrix} = \n\\begin{bmatrix}g_1(x_1, \\ldots, x_M) \\\\ \\vdots \\\\ g_N(x_1, \\ldots, x_M)\\end{bmatrix}\n$$\n\n\u3068\u6210\u5206\u8868\u793a\u3067\u304d\u308b\u3002\u8aa4\u89e3\u304c\u751f\u3058\u306a\u3044\u306a\u3089\u3070\u3001\u4e00\u756a\u53f3\u306e\u8868\u5f0f\u306e\u3088\u3046\u306b\u5165\u529b\u5909\u6570 ${\\bf x}$ \u3092\u6210\u5206\u8868\u793a\u3057\u3066\u3082\u69cb\u308f\u306a\u3044\u3002\n\n## \u30d9\u30af\u30c8\u30eb\u5024\u95a2\u6570\u306e\u5fae\u5206\n\n\u30d9\u30af\u30c8\u30eb\u5024\u95a2\u6570\u306e\u5fae\u5206\u3092\u884c\u3046\u306b\u306f\u3001\u5404\u6210\u5206\u3054\u3068\u306b\u30b9\u30ab\u30e9\u5024\u95a2\u6570\u3068\u540c\u69d8\u306e\u65b9\u6cd5\u3067\u5fae\u5206\u3059\u308b\u3002\u4f8b\u3048\u3070\u524d\u7bc0\u306e ${\\bf f}$ \u306e\u5fae\u5206\u306f\n\n$$\n{\\bf f}'(x) = \\begin{bmatrix} f'_1(x) \\\\ \\vdots \\\\ f'_N(x) \\end{bmatrix}\n$$\n\n\u3067\u3042\u308b\u3002\u51fa\u529b\u304c\u30d9\u30af\u30c8\u30eb\u3067\u3042\u308b\u3053\u3068\u306b\u5bfe\u5fdc\u3057\u3066\u3001\u5fae\u5206\u3082\u30d9\u30af\u30c8\u30eb\u3067\u3042\u308b\u3053\u3068\u306b\u6ce8\u610f\u3059\u308b\u3002\n\u5fae\u5c0f\u91cf\u3092\u8868\u3059 $d$ \u3092\u7528\u3044\u3066\n\n$$\n\\frac{d}{dx} {\\bf f} (x) = \\begin{bmatrix} \\frac{d}{dx}f_1(x) \\\\ \\vdots \\\\ \\frac{d}{dx}f_N(x) \\end{bmatrix}\n$$\n\n\u3068\u66f8\u3044\u3066\u3082\u69cb\u308f\u306a\u3044\u3002\n\n\u5165\u51fa\u529b\u304c\u5171\u306b\u591a\u5909\u6570\u3067\u3042\u308b\u95a2\u6570\u3092\u5fae\u5206\u3059\u308b\u5834\u5408\u3082\u3001\u51fa\u529b\u306e\u6210\u5206\u3054\u3068\u306b\u5fae\u5206\u3059\u308b\u3002\n\u305f\u3060\u3057\u3001\u4eca\u5ea6\u306f\u5165\u529b\u3082\u591a\u5909\u6570\u3067\u3042\u308b\u305f\u3081\u3001\u5165\u529b\u306e\u6210\u5206\u3054\u3068\u306b\u504f\u5fae\u5206\u3092\u884c\u308f\u306a\u3051\u308c\u3070\u306a\u3089\u306a\u3044\u3002\n\u4f8b\u3048\u3070\u3001\u524d\u7bc0\u306e ${\\bf g}$ \u3092\u5fae\u5206\u3059\u308b\u3068\u3001\u524d\u7bc0\u306e\u6210\u5206\u8868\u793a\u3092\u7528\u3044\u3066\n\n$$\n\\frac{\\partial {\\bf g}}{\\partial {\\bf x}}({\\bf x}) = \n\\begin{bmatrix}\n    \\frac{\\partial g_{1}}{\\partial {x_1}}({\\bf x}) & \\cdots & \\frac{\\partial g_{1}}{\\partial {x_M}}({\\bf x}) \\\\\n    \\vdots & \\ddots & \\vdots \\\\\n    \\frac{\\partial g_{N}}{\\partial {x_1}}({\\bf x}) & \\cdots & \\frac{\\partial g_{N}}{\\partial {x_M}}({\\bf x})\n\\end{bmatrix}\n$$\n\n\u3068\u306a\u308b\u3002 $M$ \u500b\u306e\u5165\u529b\u5909\u6570\u3068 $N$ \u500b\u306e\u51fa\u529b\u5909\u6570\u306e\u7d44\u307f\u5408\u308f\u305b\u3092\u8003\u3048\u308b\u5fc5\u8981\u304c\u3042\u308b\u306e\u3067\u3001\u5fae\u5206\u306f\u30b5\u30a4\u30ba $(N, M)$ \u306e\u884c\u5217\u3068\u306a\u308b\u3053\u3068\u306b\u6ce8\u610f\u3059\u308b\u3002\u3053\u306e\u3001\u3059\u3079\u3066\u306e\u504f\u5fae\u5206\u306e\u7d44\u307f\u5408\u308f\u305b\u3092\u307e\u3068\u3081\u3066\u4f5c\u3063\u305f\u884c\u5217\u306e\u3053\u3068\u3092 **\u30e4\u30b3\u30d3\u884c\u5217** \u3068\u547c\u3076\u3002\n\n## \u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\uff08\u591a\u5909\u6570\u30d0\u30fc\u30b8\u30e7\u30f3\uff09\n\n\u5148\u7a0b 1 \u5909\u6570\u5165\u529b\u30011 \u5909\u6570\u51fa\u529b\u306e\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\uff08\u9023\u9396\u5f8b\uff09\u3092\u8aac\u660e\u3057\u307e\u3057\u305f\u3002\n\u985e\u4f3c\u306e\u5b9a\u7406\u304c\u591a\u5909\u6570\u5165\u529b\u3001\u591a\u5909\u6570\u51fa\u529b\u306e\u5834\u5408\u306b\u3082\u6210\u7acb\u3059\u308b\u3002\n\u672c\u7bc0\u3067\u306f\u591a\u5909\u6570\u30d0\u30fc\u30b8\u30e7\u30f3\u306e\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u306e\u516c\u5f0f\u3092\u7d39\u4ecb\u3059\u308b\u3002\n\n${\\bf g}$ \u3092 $M$ \u5909\u6570\u5165\u529b $N$ \u5909\u6570\u51fa\u529b\u3001${\\bf f}$ \u3092 $N$ \u5909\u6570\u5165\u529b $L$ \u5909\u6570\u51fa\u529b\u306e\u95a2\u6570\u3068\u3059\u308b\u3002\n\u3053\u308c\u3089\u306e\u95a2\u6570\u306e\u5408\u6210 ${\\bf h} = {\\bf f}({\\bf g} ({\\bf x}))$ \u306f $M$ \u5909\u6570\u5165\u529b $L$ \u5909\u6570\u51fa\u529b\u306e\u95a2\u6570\u3067\u3042\u308b\u3053\u3068\u306b\u6ce8\u610f\u3059\u308b\u3002\n\u3053\u308c\u3092 $x$ \u3067\u5fae\u5206\u3059\u308b\u3002\n\u4ee5\u4e0b\u306e\u5f0f\u304c\u591a\u5909\u6570\u95a2\u6570\u30d0\u30fc\u30b8\u30e7\u30f3\u306e\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u306e\u516c\u5f0f\u3067\u3042\u308b\u3002\n\n$$\n\\frac{\\partial {\\bf h}}{\\partial {\\bf x}}({\\bf x})  = \\frac{\\partial {\\bf f}}{\\partial {\\bf u}}({\\bf u}) \\frac{\\partial {\\bf g}}{\\partial {\\bf x}}({\\bf x}).\n$$\n\n\u3053\u3053\u3067\u3001 ${\\bf u} = {\\bf g}({\\bf x})$\u3067\u3042\u308b\u3002\n\n1 \u5909\u6570\u5165\u529b\u30011\u5909\u6570\u51fa\u529b\u306e\u5834\u5408\u306e\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u306e\u516c\u5f0f\u3068\u898b\u6bd4\u3079\u308b\u3068\u7d30\u5b57\u3060\u3063\u305f\u5909\u6570\u3084\u95a2\u6570\u304c\u592a\u5b57\u3068\u306a\u308a $d$ \u3067\u3042\u3063\u305f\u6240\u304c\u504f\u5fae\u5206\u3092\u8868\u3059 $\\partial$ \u306b\u7f6e\u304d\u63db\u3048\u3089\u308c\u3066\u3044\u308b\u3002\u3059\u306a\u308f\u3061\u3001 1 \u5909\u6570\u306e\u5834\u5408\u3068\u306e\u6700\u3082\u5927\u304d\u306a\u9055\u3044\u306f\n\n$$\n\\frac{\\partial {\\bf h}}{\\partial {\\bf x}}({\\bf x}), \n\\frac{\\partial {\\bf f}}{\\partial {\\bf u}}({\\bf u}), \n\\frac{\\partial {\\bf g}}{\\partial {\\bf x}}({\\bf x})\n$$\n\n\u304c\u884c\u5217\u3067\u3042\u308b\u3053\u3068\u3067\u3042\u308b\u3002\u884c\u5217\u306e\u30b5\u30a4\u30ba\u306f\u305d\u308c\u305e\u308c $(L, M)$, $(L, N)$, $(N, M)$ \u3067\u3042\u308b\u3002\n\u305d\u308c\u306b\u4f34\u3044\u3001\u516c\u5f0f\u306e\u53f3\u8fba\u306e\u639b\u3051\u7b97\u306f\u884c\u5217\u7a4d\u3067\u3042\u308b\u3002\u30b5\u30a4\u30ba\u304c $(L, N)$ \u3068 $(N, M)$ \u306a\u306e\u3067\u3001\u884c\u5217\u7a4d\u304c\u304d\u3061\u3093\u3068\u5b9a\u7fa9\u3067\u304d\u308b\u3053\u3068\u306b\u6ce8\u610f\u3059\u308b\u3002\n\u307e\u305f\u3001\u884c\u5217\u306e\u7a4d\u306f\u4ea4\u63db\u53ef\u80fd\u3067\u306f\u306a\u3044\u306e\u3067\u3001\u53f3\u8fba\u3092\u4ea4\u63db\u3057\u3066 $\\frac{\\partial {\\bf g}}{\\partial {\\bf x}}({\\bf x}) \\frac{\\partial {\\bf f}}{\\partial {\\bf u}}({\\bf u})$ \u3068\u3059\u308b\u3068\u5225\u306e\u610f\u5473\u306b\u306a\u3063\u3066\u3057\u307e\u3046\uff08\u305d\u3082\u305d\u3082\u5b9a\u7fa9\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u306a\u3044\u304b\u3082\u3057\u308c\u306a\u3044\uff09\u3053\u3068\u306b\u3082\u6ce8\u610f\u3059\u308b\u3002\n\n$M = N = L = 1$ \u3068\u3059\u308b\u3068\u3001\u524d\u7bc0\u306e\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u3068\u5168\u304f\u540c\u3058\u516c\u5f0f\u3067\u3042\u308b\u3002\n\u305d\u306e\u610f\u5473\u3067\u591a\u5909\u6570\u95a2\u6570\u306e\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u306f 1 \u5909\u6570\u306e\u5834\u5408\u3092\u4e00\u822c\u5316\u3057\u305f\u516c\u5f0f\u3067\u3042\u308b\u3002\n\u9006\u306b\u30011 \u5909\u6570\u306e\u516c\u5f0f\u306f\u591a\u5909\u6570\u306e\u516c\u5f0f\u306e\u7279\u5225\u306a\u5834\u5408\u3068\u8a00\u3046\u3053\u3068\u3082\u3067\u304d\u308b\u3002\n\n\n### \u8a08\u7b97\u4f8b1\n\n\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u3092\u4f7f\u3063\u3066\u3001\u591a\u5909\u6570\u95a2\u6570\u306e\u5fae\u5206\u3092\u5177\u4f53\u7684\u306b\u8a08\u7b97\u3057\u3066\u307f\u308b\u3002\n\n$$\n{\\bf x} = \\begin{bmatrix} x_1 \\\\ x_2 \\end{bmatrix}, \n{\\bf u} = \\begin{bmatrix} u_1 \\\\ u_2 \\\\ u_3 \\\\ u_4 \\end{bmatrix}\n$$\n\n\u3068\u3057\u3066\u3001\n\n$$\n{\\bf g}({\\bf x}) =\n\\begin{bmatrix}\n    3x_1 + 1 \\\\\n    2x_2 + 4 \\\\\n    x_1 x_2 \\\\\n    5\n\\end{bmatrix},\n{\\bf f}({\\bf u}) =\n\\begin{bmatrix}\n    2 u_1 + 1 \\\\\n    u_2^2 + u_3^2 \\\\\n    u_3 u_4\n\\end{bmatrix}\n$$\n\n\u3068\u3059\u308b\u3002\n\u3064\u307e\u308a\u3001${\\bf g}$ \u306f 2 \u5165\u529b 4 \u51fa\u529b\u3001${\\bf f}$ \u306f 4 \u5165\u529b 3 \u51fa\u529b\u3067\u3042\u308b\u3002\n\n\u3053\u308c\u3089\u306b\u3064\u3044\u3066 $\\frac{\\partial {\\bf f}({\\bf g}({\\bf x}))}{\\partial {\\bf x}}$ \u3092\u8a08\u7b97\u3059\u308b\u3002\n\u504f\u5fae\u5206\u3092\u5b9a\u7fa9\u3069\u304a\u308a\u8a08\u7b97\u3059\u308b\u3068\n\n$$\n\\begin{align*}\n\\frac{\\partial {\\bf g}}{\\partial {\\bf x}} ({\\bf x})&=\n\\begin{bmatrix}\n    \\frac{\\partial g_1}{\\partial x_1} & \\frac{\\partial g_1}{\\partial x_2} \\\\\n    \\frac{\\partial g_2}{\\partial x_1} & \\frac{\\partial g_2}{\\partial x_2} \\\\\n    \\frac{\\partial g_3}{\\partial x_1} & \\frac{\\partial g_3}{\\partial x_2} \\\\\n    \\frac{\\partial g_4}{\\partial x_1} & \\frac{\\partial g_4}{\\partial x_2} \n\\end{bmatrix} =\n\\begin{bmatrix}\n    3 & 0 \\\\\n    0 & 2 \\\\\n    x_2 & x_1 \\\\\n    0 & 0\n\\end{bmatrix}\\\\\n\\frac{\\partial {\\bf f}}{\\partial {\\bf u}} ({\\bf u})&=\n\\begin{bmatrix}\n    \\frac{\\partial f_1}{\\partial u_1} & \\frac{\\partial f_1}{\\partial u_2} & \\frac{\\partial f_1}{\\partial u_3} & \\frac{\\partial f_1}{\\partial u_4}\\\\\n    \\frac{\\partial f_2}{\\partial u_1} & \\frac{\\partial f_2}{\\partial u_2} & \\frac{\\partial f_2}{\\partial u_3} & \\frac{\\partial f_2}{\\partial u_4}\\\\\n    \\frac{\\partial f_3}{\\partial u_1} & \\frac{\\partial f_3}{\\partial u_2} & \\frac{\\partial f_3}{\\partial u_3} & \\frac{\\partial f_3}{\\partial u_4}\\\\\n\\end{bmatrix} =\n\\begin{bmatrix}\n    2 & 0 & 0 & 0\\\\\n    0 & 2u_2 & 2u_3 & 0 \\\\\n    0 & 0 & u_4 & u_3 \n\\end{bmatrix}\n\\end{align*}\n$$\n\n\u3068\u306a\u308b\uff08\u884c\u5217\u4e2d\u306e $\\frac{\\partial g_1}{\\partial x_1}$ \u306a\u3069\u306f\u672c\u6765\u306f $\\frac{\\partial g_1}{\\partial x_1}({\\bf x})$ \u306a\u3069\u3068\u66f8\u304f\u3079\u304d\u3067\u3042\u308b\u304c\u3001\u5f0f\u304c\u7169\u96d1\u306b\u306a\u308b\u305f\u3081\u7701\u7565\u3057\u307e\u3057\u305f\uff09\u3002\n\u3088\u3063\u3066\u3001\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u306e\u516c\u5f0f\u3088\u308a\u3001 \n\n$$\n\\begin{align*}\n\\frac{\\partial {\\bf f}({\\bf g}({\\bf x}))}{\\partial {\\bf x}}\n&=\n\\begin{bmatrix}\n    2 & 0 & 0 & 0\\\\\n    0 & 2u_2 & 2u_3 & 0 \\\\\n    0 & 0 & u_4 & u_3 \n\\end{bmatrix}\n\\begin{bmatrix}\n    3 & 0 \\\\\n    0 & 2 \\\\\n    x_2 & x_1 \\\\\n    0 & 0\n\\end{bmatrix} \\\\ \n&=\n\\begin{bmatrix}\n    6 & 0 \\\\\n    2u_3x_2 & 4u_2 + 2u_3x_1 \\\\\n    u_4x_2 & u_4x_1 \n\\end{bmatrix} \\\\\n&=\n\\begin{bmatrix}\n    6 & 0 \\\\\n    2x_1x_2^2 & 2x_1^2x_2 + 8x_2 + 16 \\\\\n    5x_2 & 5x_1\n\\end{bmatrix}\n\\end{align*}\n$$\n\n\u3068\u306a\u308b\u3002\u516c\u5f0f\u3092\u9069\u7528\u3059\u308b\u969b\u306b ${\\bf u} = {\\bf g}(\\bf x)$ \u3001\u3059\u306a\u308f\u3061\n\n$$\n\\begin{bmatrix}\n    u_1 \\\\\n    u_2 \\\\\n    u_3 \\\\\n    u_4\n\\end{bmatrix} = \n\\begin{bmatrix}\n    3x_1 + 1 \\\\\n    2x_2 + 4 \\\\\n    x_1 x_2 \\\\\n    5\n\\end{bmatrix}\n$$\n\n\u3092\u7528\u3044\u307e\u3057\u305f\u3002\n\n\n### \u8a08\u7b97\u4f8b2\n\n\u3082\u30461\u3064\u306e\u4f8b\u3068\u3057\u3066\u3001\u5408\u6210\u3057\u305f\u95a2\u6570\u306e\u5165\u51fa\u529b\u304c 1 \u5909\u6570\u3068\u306a\u308b\u5834\u5408\u3001\u3064\u307e\u308a\u3001$M = 1, L = 1$ \u306e\u5834\u5408\u3092\u8003\u3048\u3066\u307f\u308b\u3002\n\u5f0f\u3092\u7c21\u5358\u306b\u3059\u308b\u305f\u3081\u306b\u3001 $N = 2$ \u3068\u3059\u308b\u3002\n1 \u5909\u6570\u3067\u3042\u308b\u3053\u3068\u3092\u5f37\u8abf\u3057\u3066\u3001 ${\\bf u} = {\\bf g}(x)$, $y = f({\\bf u})$ \u3068\u30b9\u30ab\u30e9\u30fc\u3068\u306a\u308b\u5909\u6570\u306b\u306f\u5c0f\u6587\u5b57\u3092\u7528\u3044\u308b\u3053\u3068\u306b\u3059\u308b\u3002\n$f$ \u3068 ${\\bf g}$ \u3092\u5408\u6210\u3057\u305f\u95a2\u6570\u3092 $h(x) = f({\\bf g}(x))$ \u3068\u3059\u308b\u3002 \n$h$ \u306f \u5165\u51fa\u529b\u304c\u5171\u306b 1 \u5909\u6570\u306a\u306e\u3067\u3001\u305d\u306e\u5fae\u5206\u3092\u7c21\u4fbf\u306b $h'(x)$ \u3068\u66f8\u304f\u3053\u3068\u306b\u3059\u308b\u3068\u3001\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u306e\u516c\u5f0f\u306f\n\n$$\n\\begin{align*}\nh'(x) &= \n\\frac{\\partial f}{\\partial {\\bf u}} ({\\bf u}) \\frac{d {\\bf g}}{d x} (x)\\\\\n&= \\begin{bmatrix}\n    \\frac{\\partial f}{\\partial u_1} ({\\bf u}) & \\frac{\\partial f}{\\partial u_2} ({\\bf u})\n\\end{bmatrix} \n\\begin{bmatrix}\n    \\frac{d g_1}{d x} (x) \\\\\n    \\frac{d g_2}{d x} (x)\n\\end{bmatrix} \\\\\n&= \n\\frac{\\partial f}{\\partial u_1} ({\\bf u})\\frac{d g_1}{d x}(x) + \n\\frac{\\partial f}{\\partial u_2} ({\\bf u})\\frac{d g_2}{d x}(x)\n\\end{align*}\n$$\n\n\u3068\u66f8\u304d\u4e0b\u3059\u3053\u3068\u304c\u3067\u304d\u308b\uff08\u5fae\u5206\u3059\u308b\u5909\u6570\u304c 1 \u3064\u3057\u304b\u306a\u3044\u5834\u5408\u306f\u504f\u5fae\u5206\u8a18\u53f7 $\\partial$ \u3067\u306f\u306a\u304f 1 \u5909\u6570\u5fae\u5206 $d$ \u3092\u7528\u3044\u3066\u66f8\u304d\u307e\u3057\u305f\uff09\u3002\n\n\u672c\u8cc7\u6599\u3067\u7d39\u4ecb\u3057\u305f\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u306e\u516c\u5f0f\u306e\u4ed6\u306b\u3082\u884c\u5217\u3084\u30d9\u30af\u30c8\u30eb\u306e\u8a08\u7b97\u3067\u7528\u3044\u3089\u308c\u308b\u516c\u5f0f\u306f\u305f\u304f\u3055\u3093\u3042\u308b\u3002\n\u305d\u308c\u3089\u306e\u516c\u5f0f\u306f [The Matrix Cookbook](https://www.math.uwaterloo.ca/~hwolkowi/matrixcookbook.pdf) \u306a\u3069\u306b\u307e\u3068\u307e\u3063\u3066\u3044\u308b\u306e\u3067\u3001\u8ad6\u6587\u7b49\u3092\u8aad\u3080\u969b\u306a\u3069\u306b\u3082\u5fc5\u8981\u306b\u5fdc\u3058\u3066\u3053\u308c\u3089\u3092\u53c2\u7167\u3059\u308b\u3068\u3088\u3044\u3067\u3057\u3087\u3046\u3002\n\u307e\u305f\u3001\u30e4\u30b3\u30d3\u884c\u5217\u306e\u8a08\u7b97\u65b9\u6cd5\u306f [The Matrix Calculus You Need For Deep Learning](https://arxiv.org/abs/1802.01528)\u306a\u3069\u306b\u307e\u3068\u307e\u3063\u3066\u3044\u308b\u3002\n\n<hr />\n\n<div class=\"alert alert-info\">\n**\u6ce8\u91c8 1**\n\n$N \\times M$ \u884c\u5217\u3001\u306a\u3069\u3068\u8a00\u308f\u308c\u305f\u3068\u304d\u306b\u3001$N$ \u3068 $M$ \u306e\u3069\u3061\u3089\u304c\u884c\u3067\u3001\u3069\u3061\u3089\u304c\u5217\u3060\u308d\u3046\uff1f\u3068\u8ff7\u3063\u305f\u3068\u304d\u306f\u3001\u300c\u884c\u5217\u300d\u3068\u8a00\u3046\u8a00\u8449\u3092\u518d\u5ea6\u601d\u3044\u6d6e\u304b\u3079\u3066\u3001\u300c\u884c\u2192\u5217\u300d\u3064\u307e\u308a\u5148\u306b\u304f\u308b $N$ \u304c\u884c\u6570\u3067\u3001$M$ \u304c\u5217\u6570\u3060\u3001\u3068\u601d\u3044\u51fa\u3059\u306e\u304c\u304a\u3059\u3059\u3081\u3067\u3042\u308b\u3002\n\n[\u25b2\u4e0a\u3078\u623b\u308b](#ref_note1)\n</div>\n\n<div class=\"alert alert-info\">\n**\u6ce8\u91c8 2**\n\n\u6587\u732e\u306b\u3088\u3063\u3066\u306f\u5358\u4f4d\u884c\u5217\u3067\u306f\u306a\u304f\u3001\u3059\u3079\u3066\u306e\u6210\u5206\u304c1\u306e\u884c\u5217\u306e\u3053\u3068\u3092unit matrix\u3068\u547c\u3076\u3053\u3068\u3082\u3042\u308b\u3002\n\n[\u25b2\u4e0a\u3078\u623b\u308b](#ref_note2)\n</div>\n\n\n\n# \u78ba\u7387\u30fb\u7d71\u8a08\u306e\u57fa\u790e\n\n\u672c\u7bc0\u3067\u306f\u6a5f\u68b0\u5b66\u7fd2\u3067\u7528\u3044\u308b\u78ba\u7387\u8ad6\u3001\u7d71\u8a08\u5b66\u306e\u6982\u5ff5\u3084\u7528\u8a9e\u3092\u89e3\u8aac\u3059\u308b\u3002\n\n\u4e16\u306e\u4e2d\u306b\u306f\u300c\u30e9\u30f3\u30c0\u30e0\u300d\u306b\u8d77\u3053\u308b\u51fa\u6765\u4e8b\u3001\u3082\u3057\u304f\u306f\u80cc\u666f\u306e\u30e1\u30ab\u30cb\u30ba\u30e0\u304c\u308f\u304b\u3089\u306a\u3044\u305f\u3081\u300c\u30e9\u30f3\u30c0\u30e0\u300d\u3068\u3057\u3066\u6271\u308f\u3056\u308b\u3092\u5f97\u306a\u3044\u51fa\u6765\u4e8b\u304c\u5b58\u5728\u3059\u308b\u3002\u305d\u306e\u3088\u3046\u306a\u30e9\u30f3\u30c0\u30e0\u306a\u51fa\u6765\u4e8b\u3092\u7406\u8ad6\u7684\u306b\u6271\u3046\u306b\u306f\u3001\u51fa\u6765\u4e8b\u305d\u306e\u3082\u306e\u3084\u3001\u3042\u308b\u51fa\u6765\u4e8b\u3068\u5225\u306e\u51fa\u6765\u4e8b\u306e\u95a2\u9023\u3092\u6570\u5b66\u7684\u306b\u8a18\u8ff0\u3067\u304d\u306a\u3051\u308c\u3070\u306a\u3089\u306a\u3044\u3002\u78ba\u7387\u8ad6\u3067\u306f\u30e9\u30f3\u30c0\u30e0\u306a\u51fa\u6765\u4e8b\u306e\u3053\u3068\u3092**\u4e8b\u8c61 (event)**\u3068\u547c\u3076\uff08\u53b3\u5bc6\u306a\u5b9a\u7fa9\u306f\u672c\u8cc7\u6599\u3067\u306f\u7701\u7565\u3059\u308b\uff09\u3002\n\n\u672c\u7bc0\u3067\u306f\u3001\u307e\u305a\u4e8b\u8c61\u3092\u8a18\u8ff0\u3059\u308b\u9053\u5177\u3068\u3057\u3066\u78ba\u7387\u5206\u5e03\u3092\u5c0e\u5165\u3057\u3001\u305d\u308c\u306b\u95a2\u9023\u3059\u308b\u6982\u5ff5\uff08\u5468\u8fba\u78ba\u7387\u3001\u6761\u4ef6\u4ed8\u304d\u78ba\u7387\u3001\u78ba\u7387\u5909\u6570\u306e\u72ec\u7acb\uff09\u3092\u89e3\u8aac\u3059\u308b\u3002\u3055\u3089\u306b\u3053\u308c\u3089\u306e\u6982\u5ff5\u3092\u7528\u3044\u3066\u30d9\u30a4\u30ba\u306e\u5b9a\u7406\u3092\u8aac\u660e\u3059\u308b\u3002\u30d9\u30a4\u30ba\u306e\u5b9a\u7406\u306b\u3088\u308a\u3001\u3042\u308b\u51fa\u6765\u4e8b\u304c\u89b3\u6e2c\u3055\u308c\u305f\u6642\u306b\u3001\u305d\u306e\u539f\u56e0\u3068\u306a\u308b\u51fa\u6765\u4e8b\u304c\u8d77\u3053\u3063\u305f\u78ba\u7387\u306e\u8a08\u7b97\u304c\u3067\u304d\u308b\u3088\u3046\u306b\u306a\u308b\u3002\n\u6b21\u306b\u3001\u78ba\u7387\u5206\u5e03\u306e\u4e2d\u304b\u3089\u89b3\u6e2c\u30c7\u30fc\u30bf\u306b\u9069\u5408\u3057\u305f\u6700\u9069\u306a\u78ba\u7387\u5206\u5e03\u3092\u9078\u629e\u3059\u308b\u65b9\u6cd5\u3067\u3042\u308b\u3001\u6700\u5c24\u63a8\u5b9a\u3068\u4e8b\u5f8c\u5206\u5e03\u6700\u5927\u5316\u63a8\u5b9a\uff08MAP \u63a8\u5b9a\uff09\u3092\u7d39\u4ecb\u3059\u308b\u3002\n\u6a5f\u68b0\u5b66\u7fd2\u306e\u6587\u8108\u3067\u306f\u3001\u3053\u308c\u3089\u306f\u8a13\u7df4\u30e2\u30c7\u30eb\u306e\u300c\u6700\u9069\u306a\u300d\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u6c7a\u5b9a\u3059\u308b\u3053\u3068\u306b\u5bfe\u5fdc\u3059\u308b\u3002\n\u6700\u5f8c\u306b\u3001\u6a5f\u68b0\u5b66\u7fd2\u3067\u983b\u7e41\u306b\u5229\u7528\u3055\u308c\u308b\u7d71\u8a08\u5b66\u306e\u7528\u8a9e\uff08\u5e73\u5747\u3001\u5206\u6563\u3001\u6a19\u6e96\u504f\u5dee\u3001\u76f8\u95a2\u4fc2\u6570\u306a\u3069\uff09\u3092\u89e3\u8aac\u3059\u308b\u3002\n\n\n## \u78ba\u7387\u30fb\u7d71\u8a08\u3068\u6a5f\u68b0\u5b66\u7fd2\u306e\u95a2\u4fc2\n\n\u6a5f\u68b0\u5b66\u7fd2\u30b7\u30b9\u30c6\u30e0\u304c\u5b66\u7fd2\u306b\u7528\u3044\u308b\u306e\u306f\u9650\u3089\u308c\u305f\u6570\u306e\u89b3\u6e2c\u30c7\u30fc\u30bf\u3067\u3042\u308b\u304c\u3001\u591a\u304f\u306e\u6a5f\u68b0\u5b66\u7fd2\u30bf\u30b9\u30af\u3067\u3084\u308a\u305f\u3044\u3053\u3068\u306f\u3001\u4e0e\u3048\u3089\u308c\u305f\u89b3\u6e2c\u30c7\u30fc\u30bf\u306e\u80cc\u5f8c\u306b\u3042\u308b\u666e\u904d\u6027\u3084\u6cd5\u5247\u3092\u6349\u3048\u3001\u5c06\u6765\u306e\u51fa\u6765\u4e8b\u306b\u5bfe\u3057\u4e88\u6e2c\u3092\u884c\u3048\u308b\u3053\u3068\u3067\u3042\u308b\u3002\u6a5f\u68b0\u5b66\u7fd2\u3067\u306f\u305d\u308c\u3092\u9054\u6210\u3059\u308b\u305f\u3081\u306b\u7d71\u8a08\u5b66\u306e\u8003\u3048\u65b9\u3092\u5229\u7528\u3059\u308b\u3002\n\n\u7d71\u8a08\u5b66\u3067\u306f\u3001\u3042\u308b\u96c6\u56e3\u3059\u3079\u3066\u306b\u3064\u3044\u3066\u8abf\u67fb\u304c\u3067\u304d\u306a\u3044\u6642\u3001\u96c6\u56e3\u304b\u3089\u30e9\u30f3\u30c0\u30e0\u30b5\u30f3\u30d7\u30ea\u30f3\u30b0\u3092\u884c\u3044\u5143\u306e\u96c6\u56e3\u306e\u6027\u8cea\u3092\u63a8\u5b9a\u3059\u308b\u3002\u624b\u5143\u306b\u3042\u308b\u89b3\u6e2c\u30c7\u30fc\u30bf\u304c\u3001\u4f55\u3089\u304b\u306e\u6cd5\u5247\u306b\u5f93\u3063\u3066\u5f97\u3089\u308c\u308b\u78ba\u7387\u7684\u306a\u30b5\u30f3\u30d7\u30eb\u3067\u3042\u308b\u3068\u8003\u3048\u308b\u3053\u3068\u3067\u3001\u6a5f\u68b0\u5b66\u7fd2\u3068\u7d71\u8a08\u5b66\u304c\u3064\u306a\u304c\u308b\u3002\n\u7d71\u8a08\u5b66\u3092\u5229\u7528\u3059\u308b\u3053\u3068\u3067\u3001\u3042\u308b\u30c7\u30fc\u30bf\u304c\u672a\u77e5\u306e\u30c7\u30fc\u30bf\u6e90\u304b\u3089\u767a\u751f\u3057\u3084\u3059\u3044\u304b\u3001\u30c7\u30fc\u30bf\u304c\u5916\u308c\u5024\u304b\u3069\u3046\u304b\u3001\u3069\u3046\u3044\u3063\u305f\u65b9\u6cd5\u3067\u30e2\u30c7\u30eb\u3092\u5b66\u7fd2\u3055\u305b\u308c\u3070\u3088\u3044\u304b\u3001\u3068\u3044\u3063\u305f\u554f\u984c\u3092\u5ba2\u89b3\u7684\u306b\u5224\u65ad\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3088\u3046\u306b\u306a\u308b\u3002\u307e\u305f\u3001\u5b66\u7fd2\u3055\u305b\u305f\u30e2\u30c7\u30eb\u306e\u6027\u80fd\u306b\u5bfe\u3057\u3066\u7406\u8ad6\u7684\u306a\u4fdd\u8a3c\u3092\u4e0e\u3048\u308b\u3053\u3068\u3082\u7d71\u8a08\u5b66\u306b\u3088\u308a\u53ef\u80fd\u3068\u306a\u308b\u3002\n\u3053\u306e\u3088\u3046\u306a\u3001\u6a5f\u68b0\u5b66\u7fd2\u306e\u7d71\u8a08\u5b66\u3068\u3057\u3066\u306e\u5074\u9762\u3092\u5f37\u8abf\u3059\u308b\u5834\u5408\u3001\u6a5f\u68b0\u5b66\u7fd2\u3092\u7279\u306b\u300c\u7d71\u8a08\u7684\u6a5f\u68b0\u5b66\u7fd2\u300d\u3068\u547c\u3076\u3002\n\n## \u78ba\u7387\u5909\u6570\u3068\u78ba\u7387\u5206\u5e03\n\n\u73fe\u4ee3\u6570\u5b66\u3067\u5e83\u304f\u5229\u7528\u3055\u308c\u3066\u3044\u308b\u300c\u78ba\u7387\u300d\u306e\u6982\u5ff5\u3092\u5b9a\u5f0f\u5316\u3059\u308b\u306b\u306f\u69d8\u3005\u306a\u6e96\u5099\u304c\u5fc5\u8981\u306b\u306a\u308b\u305f\u3081\u3001\u3053\u306e\u8cc7\u6599\u3067\u306f\u300c\u78ba\u7387\u300d\u3068\u8a00\u3046\u8a00\u8449\u3092\u6570\u5b66\u7684\u306b\u53b3\u5bc6\u306b\u306f\u5b9a\u7fa9\u3057\u306a\u3044\u3002\u4ee3\u308f\u308a\u306b\u6b21\u306e\u3088\u3046\u306b\u8003\u3048\u307e\u3059\u3002\u3042\u308b\u5bfe\u8c61\u3068\u3057\u3066\u3044\u308b\u73fe\u8c61\u306e\u4e2d\u3067\u3001\u69d8\u3005\u306a\u4e8b\u8c61\u304c\u3042\u308a\u5f97\u308b\u3068\u304d\u3001\u305d\u308c\u305e\u308c\u306e\u4e8b\u8c61\u3054\u3068\u306b\u3001\u305d\u308c\u304c\u300c\u3069\u306e\u7a0b\u5ea6\u8d77\u304d\u305d\u3046\u304b\u300d\u3068\u8a00\u3046\u5ea6\u5408\u3044\u3092\u8003\u3048\u307e\u3059\u3002\u78ba\u7387\u3068\u306f\u305d\u306e\u5ea6\u5408\u3044\u306e\u3053\u3068\u3068\u3059\u308b\u3002\u305d\u3057\u3066\u3001\u305d\u306e\u78ba\u7387\u306b\u5f93\u3063\u3066\u3001\u8272\u3005\u306a\u5024\u3092\u3068\u308a\u3046\u308b**\u78ba\u7387\u5909\u6570\uff08random variable\uff09**\u3092\u8003\u3048\u307e\u3059\u3002\u78ba\u7387\u5909\u6570\u306f\u3001\u540d\u524d\u306b\u300c\u5909\u6570\u300d\u3068\u3064\u3044\u3066\u3044\u308b\u304c\u3001**\u300c\u4e8b\u8c61\u300d\u3092\u300c\u6570\u5024\u300d\u306b\u5909\u63db\u3059\u308b\u95a2\u6570**\u3068\u8003\u3048\u308b\u3068\u7406\u89e3\u3057\u3084\u3059\u304f\u306a\u308b\u3002\u4f8b\u3048\u3070\u3001\u300c\u30b3\u30a4\u30f3\u3092\u6295\u3052\u3066\u8868\u304c\u51fa\u308b\u300d\u3068\u8a00\u3046\u300c\u4e8b\u8c61\u300d\u3092\u3001\u300c1\u300d\u3068\u8a00\u3046\u300c\u6570\u5024\u300d\u306b\u5909\u63db\u3057\u3001\u300c\u30b3\u30a4\u30f3\u3092\u6295\u3052\u3066\u88cf\u304c\u51fa\u308b\u300d\u3068\u8a00\u3046\u300c\u4e8b\u8c61\u300d\u3092\u3001\u300c0\u300d\u3068\u8a00\u3046\u300c\u6570\u5024\u300d\u306b\u5909\u63db\u3059\u308b\u95a2\u6570\u3092\u8003\u3048\u308b\u3068\u3001\u3053\u308c\u306f\u300c1\u300d\u304b\u300c0\u300d\u3068\u8a00\u3046\u5024\u306e\u3069\u3061\u3089\u304b\u3092\u3068\u308a\u3046\u308b\u78ba\u7387\u5909\u6570\u3060\uff08[\u6ce8\u91c81](#note1)\uff09\u3068\u8a00\u3046\u3053\u3068\u306b\u306a\u308b\u3002\n\n\u305d\u308c\u3067\u306f\u3001\u78ba\u7387\u7684\u73fe\u8c61\u306e\u5177\u4f53\u4f8b\u3092\u8003\u3048\u3066\u307f\u308b\u3002\u3042\u308b\u6b6a\u3093\u3060\u30b5\u30a4\u30b3\u30ed\u304c\u3042\u308a\u3001\u300c\u30b5\u30a4\u30b3\u30ed\u3092\u6295\u3052\u3066 $x$ \u3068\u8a00\u3046\u76ee\u304c\u51fa\u305f\u300d\u3068\u8a00\u3046\u4e8b\u8c61\uff08[\u6ce8\u91c82](#note2)\uff09\u3092\u3001$x$ \u3068\u8a00\u3046\u6570\u5024\u306b\u5bfe\u5fdc\u3055\u305b\u308b\u78ba\u7387\u5909\u6570 $X$ \u304c\u3042\u308b\u3068\u3059\u308b\u3002\u305d\u3057\u3066\u3001\u3053\u306e\u78ba\u7387\u5909\u6570\u304c\u3068\u308a\u3046\u308b\u5168\u3066\u306e\u5024\u304c\u3001\u305d\u308c\u305e\u308c\u3069\u306e\u3088\u3046\u306a\u78ba\u7387\u3067\u51fa\u73fe\u3059\u308b\u304b\u3092\u8868\u3057\u305f\u4ee5\u4e0b\u306e\u3088\u3046\u306a\u8868\u304c\u3042\u308b\u3002\n\n| \u78ba\u7387\u5909\u6570 $X$ \u306e\u5024 | \u305d\u306e\u5024\u3092\u3068\u308b\u78ba\u7387 |\n|:-----------------:|:----------------:|\n| 1                 | $0.3$            |\n| 2                 | $0.1$            |\n| 3                 | $0.1$            |\n| 4                 | $0.2$            |\n| 5                 | $0.1$            |\n| 6                 | $0.2$            |\n\n\u3053\u306e\u3088\u3046\u306a\u8868\u3092**\u78ba\u7387\u5206\u5e03 (probability distribution)** \u3068\u547c\u3076\u3002\u78ba\u7387\u5206\u5e03\u306b\u306f\u91cd\u8981\u306a\u5236\u7d04\u304c\u3042\u308a\u3001\u300c\u78ba\u7387\u5909\u6570\u304c\u3068\u308a\u3046\u308b\u3042\u3089\u3086\u308b\u5024\u306e\u78ba\u7387\u3092\u3059\u3079\u3066\u8db3\u3059\u3068\u548c\u304c\u5fc5\u305a $1$ \u306b\u306a\u308b\u3053\u3068\u300d\u53ca\u3073\u300c\u5168\u3066\u306e\u78ba\u7387\u306f $0$ \u4ee5\u4e0a\u306e\u5024\u3067\u3042\u308b\u3053\u3068\u300d\u306e\u4e21\u8005\u3092\u5e38\u306b\u6e80\u305f\u3059\u3002\u4e0a\u306e\u8868\u306e\u5de6\u306e\u5217\u306b\u4e26\u3076\u6570\u5024\u3092**\u5b9f\u73fe\u5024**\u3068\u547c\u3073\u3001\u5c0f\u6587\u5b57\u306e $x$ \u3067\u8868\u3059\u3002\u305d\u3057\u3066\u3001\u53f3\u306e\u5217\u306b\u4e26\u3076\u305d\u308c\u305e\u308c\u306e $x$ \u306b\u5bfe\u5fdc\u3059\u308b\u78ba\u7387\u3092 $p(x)$ \u3068\u66f8\u304f\u3053\u3068\u306b\u3059\u308b\u3002\u3059\u306a\u308f\u3061\u4e0a\u306e\u8868\u304b\u3089 $p(1) = 0.3$ , $p(2) = 0.1$ , $\\ldots$ \u3067\u3042\u308b\u3002\u3053\u306e\u8868\u8a18\u3092\u7528\u3044\u308b\u3068\u3001\u78ba\u7387\u5206\u5e03\u304c\u6301\u30642\u3064\u306e\u5236\u7d04\u306f\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u8868\u305b\u307e\u3059\u3002\n\n$$\n\\begin{align}\n\\sum_x p(x) &= 1 \\\\\n\\forall x, \\ p(x) & \\geq  0\n\\end{align}\n$$\n\n\u3053\u3053\u3067\u3001 $\\sum_x$ \u306f\u5168\u3066\u306e\u3042\u308a\u3046\u308b $x$ \u306e\u5024\u306b\u308f\u305f\u308b\u548c\u3092\u8868\u3057\u3001\u4f8b\u3048\u3070\u4e0a\u306e\u30b5\u30a4\u30b3\u30ed\u306e\u4f8b\u3067\u306f\u3001 $\\sum_{x=1}^6$ \u3068\u540c\u3058\u3053\u3068\u3092\u610f\u5473\u3059\u308b\u3002 $\\forall x$ \u306f\u3001\u3042\u308a\u5f97\u308b $x$ \u306e\u5024\u3059\u3079\u3066\u306b\u304a\u3044\u3066\u3001\u53f3\u306e\u6761\u4ef6\uff08 $p(x) \\geq 0$ \uff09\u304c\u6210\u308a\u7acb\u3064\u3001\u3068\u8a00\u3046\u3053\u3068\u3092\u610f\u5473\u3057\u3066\u3044\u308b\u3002\n\n$p(1) = 0.3$ \u3068\u8a00\u3046\u306e\u306f\u3001\u78ba\u7387\u5909\u6570 $X$ \u304c $1$ \u3068\u8a00\u3046\u5024\u3092\u3068\u308b\u78ba\u7387\u3068\u8a00\u3046\u3053\u3068\u3067\u3042\u308b\u304c\u3001\u3053\u308c\u3092 $p(X = 1) = 0.3$ \u3068\u3082\u66f8\u304f\u3002\u524d\u8ff0\u306e $p(x)$ \u306f\u3001\u78ba\u7387\u5909\u6570 $X$ \u306e\u5b58\u5728\u3092\u6697\u306b\u4eee\u5b9a\u3057\u3001 $p(X = x)$ \u3092\u7c21\u5358\u306b\u8868\u8a18\u3057\u305f\u3082\u306e\u3001\u3059\u306a\u308f\u3061 $X$ \u3068\u8a00\u3046\u78ba\u7387\u5909\u6570\u304c\u3042\u308b\u5024 $x$ \u3092\u3068\u308b\u78ba\u7387\u3068\u8003\u3048\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\u4e00\u65b9\u3001 $p(X)$ \u3068\u78ba\u7387\u5909\u6570\u3060\u3051\u3092\u5f15\u6570\u306b\u3068\u308b\u5834\u5408\u3001\u3053\u308c\u306f\u4e0a\u306e\u8868\u306e\u3088\u3046\u306a\u78ba\u7387\u5206\u5e03\u3092\u610f\u5473\u3059\u308b\u3002\n\n## \u540c\u6642\u5206\u5e03\u30fb\u5468\u8fba\u78ba\u7387\n\n\u524d\u7bc0\u3067\u306f\u30011 \u3064\u306e\u78ba\u7387\u5909\u6570\u306b\u3064\u3044\u3066\u3001\u305d\u306e\u5206\u5e03\uff08\u78ba\u7387\u5206\u5e03\u306e\u3053\u3068\uff09\u3068\u306f\u4f55\u304b\u3068\u3001\u5206\u5e03\u304c\u6301\u3064\u5236\u7d04\u306b\u3064\u3044\u3066\u8aac\u660e\u3057\u307e\u3057\u305f\u3002\u3053\u306e\u7bc0\u3067\u306f\u3001\u8907\u6570\u306e\u78ba\u7387\u5909\u6570\u304c\u767b\u5834\u3059\u308b\u5834\u5408\u306b\u3064\u3044\u3066\u8003\u3048\u307e\u3059\u3002\n\n\u307e\u305a\u5177\u4f53\u4f8b\u3092\u7528\u3044\u3066\u8003\u3048\u3066\u307f\u308b\u3002\u3053\u3053\u306b 2 \u3064\u306e\u30b5\u30a4\u30b3\u30ed\u304c\u3042\u308a\u3001\u305d\u308c\u305e\u308c\u306e\u30b5\u30a4\u30b3\u30ed\u306e\u51fa\u76ee\u3092 2 \u3064\u306e\u78ba\u7387\u5909\u6570 $X, Y$ \u3067\u8868\u3059\u3002\u3053\u306e 2 \u3064\u306e\u30b5\u30a4\u30b3\u30ed\u3092\u540c\u6642\u306b\u632f\u3063\u3066\u30011 \u3064\u76ee\u306e\u30b5\u30a4\u30b3\u30ed\u304c $x$ \u3068\u8a00\u3046\u5024\u3092\u3068\u308a\u30012 \u3064\u76ee\u306e\u30b5\u30a4\u30b3\u30ed\u304c $y$ \u3068\u8a00\u3046\u5024\u3092\u3068\u3063\u305f\u3068\u8a00\u3046\u4e8b\u8c61\u306e\u78ba\u7387\u306f\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u66f8\u304d\u8868\u3059\u3002\n\n$$\np(X = x, Y = y)\n$$\n\n $x, y$ \u306f\u3044\u305a\u308c\u3082 $1, 2, 3, 4, 5, 6$ \u306e6\u3064\u306e\u6570\u5b57\u306e\u3069\u308c\u304b\u3067\u3042\u308b\u3002\u4f8b\u3048\u3070\u3001\u300c3\u300d\u3068\u300c5\u300d\u306e\u76ee\u304c\u51fa\u308b\u3001\u3068\u8a00\u3046\u4e8b\u8c61\u304c\u8d77\u3053\u308b\u78ba\u7387\u306f\n\n$$\np(X = 3, Y = 5)\n$$\n\n\u3068\u8868\u3055\u308c\u307e\u3059\u3002\u3053\u306e\u3088\u3046\u306b\u3001 $X = 3$ \u3068\u306a\u308b**\u304b\u3064** $Y = 5$ \u3068\u306a\u308b\u3001\u3068\u3044\u3063\u305f\u8907\u6570\u306e\u6761\u4ef6\u3092\u6307\u5b9a\u3057\u305f\u3068\u304d\u306b\u3001\u305d\u308c\u3089\u304c\u5168\u3066\u540c\u6642\u306b\u6210\u308a\u7acb\u3064\u78ba\u7387\u306e\u3053\u3068\u3092\u3001**\u540c\u6642\u78ba\u7387\uff08joint probability\uff09**\u3068\u547c\u3076\u3002\n\n\u3067\u306f\u6b21\u306b\u3001\u3053\u306e 2 \u3064\u306e\u30b5\u30a4\u30b3\u30ed\u3092\u5225\u3005\u306b\u898b\u3066\u307f\u308b\u3002\u4f8b\u3048\u3070\u3001\u300c1 \u3064\u76ee\u306e\u30b5\u30a4\u30b3\u30ed\u304c $3$ \u306e\u76ee\u3092\u51fa\u3057\u305f\u300d\u3068\u8a00\u3046\u4e8b\u8c61\u304c\u8d77\u3053\u308b\u78ba\u7387 $p(X = 3)$ \u306f\u30011\u3064\u76ee\u306e\u30b5\u30a4\u30b3\u30ed\u304c $3$ **\u304b\u3064** 2 \u3064\u76ee\u306e\u30b5\u30a4\u30b3\u30ed\u304c $1$ \u306e\u3068\u304d\uff0f $2$ \u306e\u3068\u304d\uff0f $3$ \u306e\u3068\u304d\uff0f\u2026\uff0f $6$ \u306e\u3068\u304d\u3001\u306e6\u3064\u306e\u30d1\u30bf\u30fc\u30f3\u304c\u767a\u751f\u3059\u308b\u78ba\u7387\u3092\u5168\u3066\u8db3\u3057\u305f\u3082\u306e\u306b\u306a\u308b\u3002\u3064\u307e\u308a\u3001\n\n$$\np(X = 3) = \\sum_y p(X = 3, Y = y)\n$$\n\n\u3068\u66f8\u3051\u307e\u3059\u3002\u3053\u306e\u3068\u304d\u3001 $\\sum_y$ \u306f\u300c $Y$ \u306e\u3068\u308a\u5f97\u308b\u3042\u3089\u3086\u308b\u5024 $y$ \u306b\u3064\u3044\u3066\u306e\u548c\u300d\u3068\u8a00\u3046\u610f\u5473\u3067\u3042\u308b\u3002\u3053\u308c\u3092\u3001\u300c\uff082 \u3064\u76ee\u306e\u30b5\u30a4\u30b3\u30ed\u306e\u76ee\u304c\u306a\u3093\u3067\u3042\u308c\uff09 1 \u3064\u76ee\u306e\u30b5\u30a4\u30b3\u30ed\u306e\u76ee\u304c $x$ \u3067\u3042\u308b\u78ba\u7387\u300d\u3068\u4e00\u822c\u5316\u3059\u308b\u3068\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u306a\u308b\u3002\n\n$$\np(X = x) = \\sum_y p(X = x, Y = y)\n$$\n\n\u540c\u69d8\u306b\u3001\u300c\uff081\u3064\u76ee\u306e\u30b5\u30a4\u30b3\u30ed\u306e\u76ee\u304c\u306a\u3093\u3067\u3042\u308c\uff092 \u3064\u76ee\u306e\u30b5\u30a4\u30b3\u30ed\u306e\u76ee\u304c $y$ \u3067\u3042\u308b\u78ba\u7387\u300d\u306f\u30011\u3064\u76ee\u306e\u30b5\u30a4\u30b3\u30ed\u306b\u3064\u3044\u3066\u3042\u308a\u5f97\u308b\u5024\u3059\u3079\u3066\u306e\u78ba\u7387\u306e\u548c\u3092\u53d6\u308c\u3070\u3088\u3044\u306e\u3067\u3001\n\n$$\np(Y = y) = \\sum_x p(X = x, Y = y)\n$$\n\n\u3068\u306a\u308b\u3002\u3053\u306e\u3088\u3046\u306b\u3001\u540c\u6642\u78ba\u7387\u304c\u4e0e\u3048\u3089\u308c\u305f\u3068\u304d\u3001\u7740\u76ee\u3057\u3066\u3044\u306a\u3044\u65b9\u306e\u78ba\u7387\u5909\u6570\u304c\u3068\u308a\u5f97\u308b\u5168\u3066\u306e\u5024\u306b\u3064\u3044\u3066\u540c\u6642\u78ba\u7387\u3092\u8a08\u7b97\u3057\u305d\u306e\u548c\u3092\u3068\u308b\u3053\u3068\u3092**\u5468\u8fba\u5316 (marginalization)** \u3068\u547c\u3073\u3001\u7d50\u679c\u3068\u3057\u3066\u5f97\u3089\u308c\u308b\u78ba\u7387\u3092**\u5468\u8fba\u78ba\u7387 (marginal probability)** \u3068\u547c\u3076\u3002\n\u307e\u305f\u3001\u5468\u8fba\u78ba\u7387\u3092\u305d\u306e\u7740\u76ee\u3057\u3066\u3044\u308b\u78ba\u7387\u5909\u6570\u304c\u3068\u308a\u5f97\u308b\u5168\u3066\u306e\u5024\u306b\u3064\u3044\u3066\u4e26\u3079\u3066\u4e00\u89a7\u306b\u3057\u305f\u3082\u306e\u304c**\u5468\u8fba\u78ba\u7387\u5206\u5e03 (marginal probability distribution)** \u3067\u3042\u308b\u3002\n\u3055\u3089\u306b\u3001\u4e0a\u306e\u4f8b\u306e\u3088\u3046\u306b2\u3064\u306e\u78ba\u7387\u5909\u6570\u306e\u540c\u6642\u78ba\u7387\u3092\u8003\u3048\u308b\u3068\u304d\u3001\u3068\u308a\u5f97\u308b\u5168\u3066\u306e\u7d44\u307f\u5408\u308f\u305b\u306e\u78ba\u7387\u3092\u4e00\u89a7\u306b\u3057\u305f\u3082\u306e\u304c\u3001**\u540c\u6642\u5206\u5e03 (joint distribution)** \u3067\u3042\u308b\u3002\n\n\u3053\u3053\u3067\u30012 \u3064\u306e\u30b5\u30a4\u30b3\u30ed\u306e\u540c\u6642\u5206\u5e03\u306e\u8868\u306f\u5927\u304d\u304f\u306a\u3063\u3066\u3057\u307e\u3046\u306e\u3067\u3001\u3088\u308a\u7c21\u5358\u306a\u4f8b\u3068\u3057\u3066\u3001\u8868\u304c\u51fa\u308b\u78ba\u7387\u3068\u88cf\u304c\u51fa\u308b\u78ba\u7387\u304c\u7570\u306a\u308b 2 \u3064\u306e\u30b3\u30a4\u30f3\u3092\u8003\u3048\u3066\u307f\u308b\u3002\u3053\u306e 2 \u3064\u306e\u30b3\u30a4\u30f3\u3092\u540c\u6642\u306b\u6295\u3052\u305f\u3068\u304d\u306e\u8868\u88cf\u306e\u7d44\u307f\u5408\u308f\u305b\u306b\u3064\u3044\u3066\u306e\u540c\u6642\u5206\u5e03\u304c\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u306a\u3063\u305f\u3068\u3059\u308b\u3002\n\n\n| $\\ $   | Y = \u8868 | Y = \u88cf |\n|:------:|:------:|:------:|\n| X = \u8868 | 1 / 5  | 2 / 5  |\n| X = \u88cf | 1 / 5  | 1 / 5  |\n\n\u3053\u3053\u3067\u30011 \u3064\u76ee\u306e\u30b3\u30a4\u30f3\u306e\u8868\u88cf\u3092\u8868\u3059\u78ba\u7387\u5909\u6570\u3092 $X$ \u30012 \u3064\u76ee\u306e\u30b3\u30a4\u30f3\u306e\u8868\u88cf\u3092\u8868\u3059\u78ba\u7387\u5909\u6570\u3092 $Y$ \u3068\u3057\u3066\u3044\u308b\u3002\u8868\u306e\u4e2d\u8eab\u304c\u3069\u3046\u8a00\u3046\u610f\u5473\u3092\u6301\u3063\u3066\u3044\u308b\u304b\u78ba\u8a8d\u3059\u308b\u30022 \u3064\u306e\u30b3\u30a4\u30f3\u304c\u4e21\u65b9\u8868\u306b\u306a\u308b\u78ba\u7387\u306f $p(X = \u8868, Y = \u8868) = 1 / 5$ \u3068\u306a\u3063\u3066\u3044\u308b\u3002\u4ed6\u306e\u30de\u30b9\u306b\u66f8\u304b\u308c\u3066\u3044\u308b\u540c\u6642\u78ba\u7387\u306e\u5024\u306e\u610f\u5473\u3082\u78ba\u8a8d\u3059\u308b\u3002\n\n\u3067\u306f\u3001\u3053\u306e\u8868\u306e\u4e2d\u306e\u6570\u5b57\u3092\u3001\u884c\u3054\u3068\u306b\u5408\u8a08\u3057\u3066\u307f\u308b\u30021 \u884c\u76ee\u306f\u3001\n\n$$\np(X = \u8868, Y = \u8868) + p(X = \u8868, Y = \u88cf) = 1 / 5 + 2 / 5 = 3 / 5\n$$\n\n\u3067\u3042\u308b\u3002\n\u3053\u308c\u306f\u3001 $\\sum_y p(X = \u8868, Y = y)$ \uff08[\u6ce8\u91c83](#note3)\uff09\u3092\u8a08\u7b97\u3057\u3066\u3044\u308b\u3053\u3068\u306b\u306a\u308b\u306e\u3067\u3001**\u5468\u8fba\u5316\u306b\u3088\u3063\u3066** $p(X = \u8868)$ **\u3068\u8a00\u3046\u5468\u8fba\u78ba\u7387\u3092\u6c42\u3081\u3066\u3044\u308b\u3053\u3068\u306b\u76f8\u5f53\u3059\u308b\u3002**\n\n\u540c\u69d8\u306b\u30011 \u5217\u76ee\u306e\u5024\u3092\u5408\u8a08\u3057\u3066\u307f\u308b\u3068\u3001\u4eca\u5ea6\u306f $\\sum_x p(X = x, Y = \u8868)$ \uff08[\u6ce8\u91c84](#note4)\uff09 \u3092\u8a08\u7b97\u3059\u308b\u3053\u3068\u306b\u76f8\u5f53\u3057\u3001\u3053\u308c\u306f\u5468\u8fba\u5316\u306b\u3088\u3063\u3066 $P(Y = \u8868)$ \u3068\u8a00\u3046\u5468\u8fba\u78ba\u7387\u3092\u8a08\u7b97\u3057\u3066\u3044\u308b\u3053\u3068\u306b\u306a\u308b\u3002\n\n\u3053\u3046\u3057\u3066\u8a08\u7b97\u3055\u308c\u308b\u5468\u8fba\u78ba\u7387\u3092\u3001\u4e0a\u306e\u540c\u6642\u5206\u5e03\u306e\u8868\u306b\u66f8\u304d\u5165\u308c\u3066\u307f\u308b\u3002\n\n| $\\ $   | Y = \u8868 | Y = \u88cf | p(X)  |\n|:------:|:------:|:------:|:-----:|\n| X = \u8868 | 1 / 5  | 2 / 5  | 3 / 5 |\n| X = \u88cf | 1 / 5  | 1 / 5  | 2 / 5 |\n| p(Y)   | 2 / 5  | 3 / 5  |       |\n\n\u3053\u306e\u3088\u3046\u306b\u3001\u5468\u8fba\u78ba\u7387\u306f\u3057\u3070\u3057\u3070\u540c\u6642\u5206\u5e03\u8868\u306e\u5468\u8fba\u306b\u8a18\u8ff0\u3055\u308c\u307e\u3059\u3002\n\n## \u6761\u4ef6\u4ed8\u304d\u78ba\u7387\n\n\u524d\u7bc0\u3067\u306f\u3001\u8907\u6570\u306e\u78ba\u7387\u5909\u6570\u3092\u540c\u6642\u306b\u8003\u3048\u308b\u65b9\u6cd5\u3068\u3057\u3066\u3001\u540c\u6642\u78ba\u7387\u304a\u3088\u3073\u540c\u6642\u5206\u5e03\u3068\u8a00\u3046\u6982\u5ff5\u3068\u3001\u540c\u6642\u78ba\u7387\u3068\u4e00\u3064\u4e00\u3064\u306e\u78ba\u7387\u5909\u6570\u306e\u307f\u306b\u7740\u76ee\u3057\u305f\u969b\u306e\u78ba\u7387\uff08\u5468\u8fba\u78ba\u7387\uff09\u306e\u9593\u306e\u95a2\u4fc2\u3092\u3001\u5468\u8fba\u5316\u3068\u8a00\u3046\u8a08\u7b97\u3067\u8aac\u660e\u3057\u307e\u3057\u305f\u3002\n\u672c\u7bc0\u3067\u306f\u3001\u300c\u3068\u3042\u308b\u6761\u4ef6\u4e0b\u3067\u306e\u7740\u76ee\u4e8b\u8c61\u306e\u78ba\u7387\u300d\u3092\u8003\u3048\u308b**\u6761\u4ef6\u4ed8\u304d\u78ba\u7387 (conditional probability)** \u3068\u8a00\u3046\u6982\u5ff5\u3092\u8aac\u660e\u3059\u308b\u3002\n\u3053\u308c\u307e\u3067\u306e\u7bc0\u3067\u6271\u3063\u3066\u3044\u305f\u78ba\u7387\u3067\u306f\u3001\u307e\u305a\u5bfe\u8c61\u3068\u3059\u308b\u73fe\u8c61\u306b\u3064\u3044\u3066\u3001\u8003\u3048\u3046\u308b\u5168\u3066\u306e\u4e8b\u8c61\u3092\u8003\u3048\u3001\u305d\u306e\u3046\u3061\u5bfe\u8c61\u3068\u3059\u308b\u4e8b\u8c61\u304c\u8d77\u304d\u308b\u78ba\u7387\u306f\u3044\u304f\u3089\u304b\u3001\u3092\u8003\u3048\u3066\u3044\u307e\u3057\u305f\u3002\n\u4e00\u65b9\u3001\u6761\u4ef6\u4ed8\u304d\u78ba\u7387\u306f\u3001\u305d\u308c\u3089\u306e\u8003\u3048\u3046\u308b\u4e8b\u8c61\u306e\u3046\u3061\u3001\u7279\u5b9a\u306e\u6761\u4ef6\u3092\u6e80\u305f\u3057\u305f\u4e8b\u8c61\u306e\u307f\u3092\u307e\u305a\u629c\u304d\u51fa\u3057\u3001\u305d\u306e\u4e2d\u3067\u3001\u3055\u3089\u306b\u7740\u76ee\u3059\u308b\u7279\u5b9a\u306e\u4e8b\u8c61\u304c\u8d77\u304d\u308b\u78ba\u7387\u3092\u8003\u3048\u308b\u305f\u3081\u306e\u3082\u306e\u3067\u3042\u308b\u3002\n\n\u4f8b\u3048\u3070\u3001\u3042\u308b\u304a\u5e97\u306b\u3084\u3063\u3066\u304d\u305f\u4eba\uff08\u4ee5\u4e0b\u3001\u5ba2\uff09\u304c\u5098\u3092\u6301\u3063\u3066\u3044\u308b\u3068\u304d\u306b $1$ \u3001\u6301\u3063\u3066\u3044\u306a\u304b\u3063\u305f\u3068\u304d\u306b $0$ \u3092\u3068\u308b\u78ba\u7387\u5909\u6570 $X$ \u3092\u8003\u3048\u307e\u3059\u3002\n\u307e\u305f\u3001\u3042\u308b\u5ba2\u304c\u3084\u3063\u3066\u304d\u305f\u3068\u304d\u306b\u5916\u3067\u96e8\u304c\u964d\u3063\u3066\u3044\u305f\u3068\u304d\u306b $1$ \u3001\u964d\u3063\u3066\u3044\u306a\u304b\u3063\u305f\u3068\u304d\u306b $0$ \u3092\u3068\u308b\u78ba\u7387\u5909\u6570 $Y$ \u3092\u8003\u3048\u307e\u3059\u3002\n\u5ba2\u304c\u5098\u3092\u6301\u3063\u3066\u3044\u305f\u304b\u3068\u3001\u305d\u306e\u77ac\u9593\u306b\u96e8\u304c\u964d\u3063\u3066\u3044\u305f\u304b\u3069\u3046\u304b\u3001\u3068\u8a00\u3046 2 \u3064\u306e\u60c5\u5831\u304c\u7d44\u3068\u306a\u3063\u305f\u30c7\u30fc\u30bf\u304c 16 \u500b\u3042\u308b\u3068\u3059\u308b\u3002\n16 \u4eba\u306e\u5ba2\u3092\u89b3\u6e2c\u3057\u3066\u30c7\u30fc\u30bf\u3092\u96c6\u3081\u305f\u3001\u3068\u8a00\u3046\u3053\u3068\u3067\u3042\u308b\u3002\n\u305d\u308c\u306f\u4ee5\u4e0b\u306e\u69d8\u306a\u3082\u306e\u3067\u3057\u305f\u3002\n\n| \u5098 ( $X$ ) | \u96e8 ( $Y$ ) |\n|:--------:|:-------:|\n| 1 | 1 |\n| 1 | 1 |\n| 1 | 1 |\n| 1 | 1 |\n| 1 | 1 |\n| 1 | 1 |\n| 0 | 1 |\n| 0 | 1 |\n| 0 | 1 |\n| 1 | 0 |\n| 0 | 0 |\n| 0 | 0 |\n| 0 | 0 |\n| 0 | 0 |\n| 0 | 0 |\n| 0 | 0 |\n\n\u3053\u308c\u3089\u306e\u30c7\u30fc\u30bf\u304b\u3089\u3001\u78ba\u7387\u5909\u6570 $X, Y$ \u306e\u540c\u6642\u5206\u5e03\u8868\u3092\u4f5c\u6210\u3059\u308b\u3068\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u306a\u308b\u3002\u3053\u306e\u8868\u306e\u4f5c\u308a\u65b9\u306f\u3001\u4f8b\u3048\u3070\u8868\u306e\u5de6\u4e0a\u306e\u30de\u30b9\u306f $X = 0$ \u304b\u3064 $Y = 0$ \u3068\u306a\u3063\u3066\u3044\u308b\u30c7\u30fc\u30bf\u304c\u300016 \u500b\u4e2d\u4f55\u500b\u3042\u308b\u304b\u3092\u6570\u3048\u3066\u3001\u305d\u306e\u5272\u5408\u3092\u8a18\u5165\u3059\u308c\u3070\u3088\u304f\u3001\u4ed6\u306e\u30de\u30b9\u306b\u3064\u3044\u3066\u3082\u540c\u69d8\u3068\u306a\u308b\u3002\n\n| $\\ $  | Y = 0  | Y = 1  |\n|:-----:|:------:|:------:|\n| X = 0 | 6 / 16 | 3 / 16 |\n| X = 1 | 1 / 16 | 6 / 16 |\n\n\u3067\u306f\u3001\u300c\u5ba2\u304c\u5098\u3092\u6301\u3063\u3066\u3044\u305f\uff08 $X = 1$ \uff09\u300d\u3068\u8a00\u3046**\u6761\u4ef6\u306e\u4e0b\u3067**\u3001\u300c\u305d\u306e\u3068\u304d\u96e8\u304c\u964d\u3063\u3066\u3044\u306a\u304b\u3063\u305f\uff08 $Y = 0$ \uff09\u300d\u3068\u8a00\u3046\u78ba\u7387\u306f\u3001\u3069\u306e\u3088\u3046\u306b\u306a\u308b\u3067\u3057\u3087\u3046\u304b\uff1f\n\n\u307e\u305a\u3001\u300c\u5ba2\u304c\u5098\u3092\u6301\u3063\u3066\u3044\u305f\uff08 $X = 1$ \uff09\u300d\u3068\u8a00\u3046\u72b6\u6cc1\u4e0b\u306e\u30c7\u30fc\u30bf\u3060\u3051\u3092\u3001\u4e0a\u306e\u540c\u6642\u5206\u5e03\u8868\u304b\u3089\u629c\u304d\u51fa\u3057\u3066\u304a\u304f\u3002\n\n| \u5098 ($X$) | \u96e8 ($Y$) |\n|:--------:|:-------:|\n| 1 | 1 |\n| 1 | 1 |\n| 1 | 1 |\n| 1 | 1 |\n| 1 | 1 |\n| 1 | 1 |\n| 1 | 0 |\n\n\u5168\u90e8\u3067 7 \u500b\u306e\u30c7\u30fc\u30bf\u304c\u3042\u308a\u3001\u3053\u306e\u4e2d\u3067\u300c\u96e8\u304c\u964d\u3063\u3066\u3044\u306a\u304b\u3063\u305f\uff08 $Y = 0$ \uff09\u300d\u3068\u306a\u3063\u3066\u3044\u308b\u30c7\u30fc\u30bf\u306f 1 \u500b\u3067\u3042\u308b\u3002\u3059\u306a\u308f\u3061\u3001\u300c\u5ba2\u304c\u5098\u3092\u6301\u3063\u3066\u3044\u305f\u3068\u8a00\u3046**\u6761\u4ef6\u306e\u4e0b\u3067**\u3001\u305d\u306e\u3068\u304d\u96e8\u304c\u964d\u3063\u3066\u3044\u306a\u304b\u3063\u305f\u78ba\u7387\u300d\u306f $1 / 7$ \u3068\u306a\u308b\u3002\u3053\u308c\u3092\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u66f8\u304f\u3002\n\n$$\np(Y = 0 | X = 1) = \\frac{1}{7}\n$$\n\n\u3053\u308c\u304c**\u6761\u4ef6\u4ed8\u304d\u78ba\u7387**\u3068\u547c\u3070\u308c\u308b\u3082\u306e\u3067\u3001\u6761\u4ef6\u3068\u306a\u308b\u4e8b\u8c61\u3092\u7e26\u68d2 $|$ \u306e\u5f8c\u306b\u66f8\u304d\u3001\u305d\u306e\u6761\u4ef6\u4e0b\u3067\u6ce8\u76ee\u3057\u3066\u3044\u308b\u4e8b\u8c61\u3092\u7e26\u68d2 $|$ \u306e\u524d\u306b\u66f8\u304f\u3002\u540c\u69d8\u306b\u3001\u300c\u5ba2\u304c\u5098\u3092\u6301\u3063\u3066\u3044\u305f\u3068\u8a00\u3046**\u6761\u4ef6\u306e\u4e0b\u3067**\u3001\u305d\u306e\u3068\u304d\u96e8\u304c\u964d\u3063\u3066\u3044\u305f\u78ba\u7387\u300d\u306f\u3001\u4e0a\u306e\u8868\u304b\u3089 $6 / 7$ \u306a\u306e\u3067\u3001\u4ee5\u4e0b\u304c\u6210\u308a\u7acb\u3061\u307e\u3059\u3002\n\n$$\np(Y = 1 | X = 1) = \\frac{6}{7}\n$$\n\n\u3053\u308c\u3089\u306e 2 \u3064\u306e\u78ba\u7387\u304c\u3001\u305d\u308c\u305e\u308c $p(Y = 0, X = 1) = 1 / 16$ , $p(Y = 1, X = 1) = 6 / 16$ \u3068\u8a00\u3046\u540c\u6642\u78ba\u7387\u3068\u306f\u7570\u306a\u3063\u3066\u3044\u308b\u3053\u3068\u3092\u3001\u4e0a\u306e\u540c\u6642\u5206\u5e03\u8868\u3068\u898b\u6bd4\u3079\u3066\u78ba\u8a8d\u3057\u3066\u307f\u308b\u3002\n\u300c\u5ba2\u304c\u5098\u3092\u6301\u3063\u3066\u3044\u3066**\u304b\u3064**\u5916\u3067\u96e8\u304c\u964d\u3063\u3066\u3044\u308b\u300d\u3068\u8a00\u3046\u540c\u6642\u78ba\u7387\u306f $6 / 16$ \u3068\u306a\u3063\u3066\u3044\u308b\u304c\u3001\u300c\u5ba2\u304c\u5098\u3092\u6301\u3063\u3066\u3044\u308b\u3068\u8a00\u3046**\u6761\u4ef6\u306e\u4e0b\u3067**\u5916\u3067\u96e8\u304c\u964d\u3063\u3066\u3044\u308b\u300d\u3068\u8a00\u3046\u6761\u4ef6\u4ed8\u304d\u78ba\u7387\u306f $6 / 7$ \u3067\u3057\u305f\u3002\n\u524d\u8005\u306f\u300c\u5ba2\u304c\u5098\u3092\u6301\u3063\u3066\u304a\u3089\u305a\u5916\u3067\u96e8\u304c\u964d\u3063\u3066\u3044\u305f\u300d\u300c\u5ba2\u304c\u5098\u3092\u6301\u3063\u3066\u304a\u3089\u305a\u5916\u3067\u96e8\u304c\u964d\u3063\u3066\u3044\u306a\u304b\u3063\u305f\u300d\u300c\u5ba2\u304c\u5098\u3092\u6301\u3063\u3066\u3044\u305f\u304c\u5916\u3067\u96e8\u304c\u964d\u3063\u3066\u3044\u306a\u304b\u3063\u305f\u300d\u3092\u542b\u3080\u3042\u308a\u5f97\u308b\u5168\u3066\u306e\u4e8b\u8c61\u3092\u8003\u3048\u305f\u4e0a\u3067\u3001\u305d\u306e\u4e2d\u3067\u5bfe\u8c61\u3068\u3057\u3066\u3044\u308b\u4e8b\u8c61\u300c\u5ba2\u304c\u5098\u3092\u6301\u3063\u3066\u3044\u3066\u5916\u3067\u96e8\u304c\u964d\u3063\u3066\u3044\u308b\u300d\u304c\u8d77\u3053\u308b\u78ba\u7387\u3092\u610f\u5473\u3057\u3066\u3044\u308b\u3002\u4e00\u65b9\u3067\u3001\u5f8c\u8005\u306e\u6761\u4ef6\u4ed8\u304d\u78ba\u7387\u306f\u3001\u4eca\u6761\u4ef6\u3068\u306a\u3063\u3066\u3044\u308b\u4e8b\u8c61\u300c\u5ba2\u304c\u5098\u3092\u6301\u3063\u3066\u3044\u308b\u300d\u304c\u6210\u308a\u7acb\u3063\u3066\u3044\u308b\u4e8b\u8c61\u3060\u3051\u3092\u307e\u305a\u5bfe\u8c61\u3068\u3057\u3001\u305d\u306e\u4e2d\u3067\u7740\u76ee\u3057\u3066\u3044\u308b\u4e8b\u8c61\u300c\u5916\u3067\u96e8\u304c\u964d\u3063\u3066\u3044\u308b\u300d\u304c\u8d77\u3053\u308b\u78ba\u7387\u3092\u8003\u3048\u307e\u3059\u3002\u305d\u308c\u305e\u308c\u306e\u78ba\u7387\u306e\u5024\u3092\u8a08\u7b97\u3059\u308b\u969b\u306e\u5206\u6bcd\u304c\u7570\u306a\u3063\u3066\u3044\u308b\u3053\u3068\u306b\u6ce8\u76ee\u3059\u308b\u3002\n\n\u307e\u305f\u3001\u4e0a\u8a18\u306e 2 \u3064\u306e\u6761\u4ef6\u4ed8\u304d\u78ba\u7387\u3092\u8db3\u3059\u3068\u3001 $1$ \u306b\u306a\u308b\u3002\u300c\u3042\u308b\u6761\u4ef6\u4e0b\u3067\u300d\u3068\u8a00\u3046\u5236\u7d04\u3055\u308c\u305f\u4e16\u754c\u3067\u3001\u5bfe\u8c61\u3068\u3059\u308b\u78ba\u7387\u5909\u6570\u304c\u3068\u308a\u5f97\u308b\u5024\u5168\u3066\u306e\u78ba\u7387\u3092\u4e26\u3079\u3066\u4e00\u89a7\u3057\u305f\u3082\u306e\u306f**\u6761\u4ef6\u4ed8\u304d\u5206\u5e03\uff08conditional distribution\uff09**\u3068\u547c\u3070\u308c\u3001\u305d\u308c\u3089\u306e\u78ba\u7387\u3092\u5168\u3066\u8db3\u3059\u3068\u5fc5\u305a $1$ \u306b\u306a\u308b\u3002\u4e0a\u306e\u4f8b\u3067\u306f\u3001\u4ee5\u4e0b\u306e\u8a08\u7b97\u3067\u78ba\u304b\u3081\u3089\u308c\u307e\u3059\u3002\n\n$$\np(Y = 0 | X = 1) + p(Y = 1 | X = 1) = \\frac{1}{7} + \\frac{6}{7} = 1\n$$\n\n\u3053\u3053\u3067\u3001\u78ba\u7387\u5909\u6570 $X$ \u304c\u3068\u308a\u3046\u308b\u5b9f\u969b\u306e\u5024\u306e\u3046\u3061\u3044\u305a\u308c\u304b\u3092\u8868\u3059\u6587\u5b57\u3068\u3057\u3066 $x$ \u3092\u3001\u78ba\u7387\u5909\u6570 $Y$ \u304c\u3068\u308a\u3046\u308b\u5b9f\u969b\u306e\u5024\u306e\u3046\u3061\u3044\u305a\u308c\u304b\u3092\u8868\u3059\u6587\u5b57\u3068\u3057\u3066 $y$ \u3092\u7528\u3044\u308b\u3068\u3001\u4e00\u822c\u7684\u306b\u3001\u6761\u4ef6\u4ed8\u304d\u78ba\u7387\u306f\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u5b9a\u7fa9\u3055\u308c\u307e\u3059\u3002\n\n$$\np(Y = y | X = x)\n= \\frac{p(X = x, Y = y)}{p(X = x)}\n$$\n\n\u3053\u306e\u3068\u304d\u3001\u6761\u4ef6\u4ed8\u304d\u5206\u5e03\u304c\u6e80\u305f\u3059\u6761\u4ef6\u306f\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u8868\u305b\u307e\u3059\u3002\n\n$$\n\\sum_y p(Y = y | X = x) = 1\n$$\n\n\u3053\u3053\u3067\u3001 $\\sum_x P(Y = y | X = x)$ \u306f\u5fc5\u305a\u3057\u30821\u306b\u306a\u3089\u306a\u3044\u3068\u8a00\u3046\u3053\u3068\u306b\u6ce8\u610f\u3059\u308b\u3002\n\n\u3067\u306f\u3001\u4e0a\u306e\u6761\u4ef6\u4ed8\u304d\u78ba\u7387\u306e\u5b9a\u7fa9\u3092\u7528\u3044\u3066\u3001\u540c\u6642\u78ba\u7387\u3068\u5468\u8fba\u78ba\u7387\u304b\u3089\u6761\u4ef6\u4ed8\u304d\u78ba\u7387\u3092\u3001\u518d\u5ea6\u8a08\u7b97\u3057\u3066\u307f\u308b\u3002\n\n$$\n\\begin{align}\np(Y = 0 | X = 1)\n&= \\frac{p(X = 1, Y = 0)}{p(X = 1)} \\\\\n&= \\frac{\\frac{1}{16}}{\\frac{7}{16}} \\\\\n&= \\frac{1}{7}\n\\end{align}\n$$\n\n\u78ba\u304b\u306b\u3001\u4e0a\u3067\u5225\u306e\u65b9\u6cd5\u3067\u6c42\u3081\u305f\u6761\u4ef6\u4ed8\u304d\u78ba\u7387\u3068\u4e00\u81f4\u3057\u307e\u3057\u305f\u3002\n\n\u3055\u3066\u3001\u4e0a\u3067\u89e6\u308c\u305f\u3001\u540c\u6642\u78ba\u7387\u3068\u6761\u4ef6\u4ed8\u304d\u78ba\u7387\u306e\u95a2\u4fc2\u306b\u3064\u3044\u3066\u518d\u5ea6\u8003\u3048\u3066\u307f\u308b\u3002\u524d\u8ff0\u306e\u300c\u6761\u4ef6\u4ed8\u304d\u78ba\u7387\u306e\u5b9a\u7fa9\u300d\u306e\u5f0f\u3092\u5909\u5f62\u3059\u308b\u3068\u3001\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u306a\u308b\u3002\u4ee5\u964d\u3067\u306f\u3001\u7c21\u5358\u306e\u305f\u3081\u306b\u3001\u78ba\u7387\u5909\u6570\u306e\u8a18\u8ff0\u3092\u7701\u304d\u3001 $p(X = x)$ \u3092 $p(x)$ \u3068\u8868\u8a18\u3059\u308b\u3002\u78ba\u7387\u5909\u6570 $X$ \u306b\u3088\u3063\u3066 $x$ \u3068\u8a00\u3046\u5024\u306b\u5bfe\u5fdc\u4ed8\u3051\u3089\u308c\u3066\u3044\u308b\u4e8b\u8c61\u304c\u751f\u3058\u308b\u78ba\u7387\u3001\u3068\u8a00\u3046\u610f\u5473\u3067\u3042\u308b\u3002\u540c\u69d8\u306b\u3001 $p(Y = y)$ \u3092 $p(y)$ \u3068\u8868\u8a18\u3059\u308b\u3002\n\n$$\np(x, y) = p(y | x) p(x)\n$$\n\n\u540c\u6642\u78ba\u7387\u306f\u3001\u6761\u4ef6\u4ed8\u304d\u78ba\u7387\u306b\u3001\u305d\u306e\u6761\u4ef6\u3068\u306a\u3063\u3066\u3044\u308b\u4e8b\u8c61\u304c\u751f\u3058\u308b\u78ba\u7387\uff08\u5468\u8fba\u78ba\u7387\uff09\u3092\u639b\u3051\u5408\u308f\u305b\u308b\u3053\u3068\u3067\u5f97\u3089\u308c\u308b\u3053\u3068\u304c\u5206\u304b\u308b\u3002\n\n\u4eca\u56de\u306e\u4f8b\u3067\u306f\u3001\u300c\u96e8\u304c\u964d\u3063\u3066\u3044\u308b\u304b\u3069\u3046\u304b\u300d\u306b\u3088\u3063\u3066\u300c\u5ba2\u304c\u5098\u3092\u6301\u3063\u3066\u3044\u305f\u304b\u3069\u3046\u304b\u300d\u306f\u5f71\u97ff\u3092\u53d7\u3051\u308b\u305f\u3081\u30012\u3064\u306e\u78ba\u7387\u5909\u6570 $Y, X$ \u306f**\u5f93\u5c5e (dependent)**\u3001\u3068\u8a00\u3046\u3002\u4e00\u65b9\u3001\u4f8b\u3048\u3070\u300c\u5ba2\u304c\u6765\u305f\u3068\u304d\u96e8\u304c\u964d\u3063\u3066\u3044\u305f\u304b\u3069\u3046\u304b\u300d\u3068\u300c\u79c1\u304c\u4eca\u304a\u8179\u304c\u7a7a\u3044\u3066\u3044\u308b\u304b\u3069\u3046\u304b\u300d\u304c\u5168\u304f\u95a2\u4fc2\u3057\u3066\u3044\u306a\u3044\u3068\u3059\u308b\u3002\u5f8c\u8005\u306b\u3064\u3044\u3066\u3001\u304a\u8179\u304c\u7a7a\u3044\u3066\u3044\u308b\u3068\u8a00\u3046\u4e8b\u8c61\u3092 $1$ \u306b\u3001\u304a\u8179\u304c\u7a7a\u3044\u3066\u3044\u306a\u3044\u3068\u8a00\u3046\u4e8b\u8c61\u3092 $0$ \u306b\u5bfe\u5fdc\u4ed8\u3051\u308b\u78ba\u7387\u5909\u6570 $Z$ \u3092\u5c0e\u5165\u3059\u308b\u3068\u3001$Y$ \u3068 $Z$ \u304c\u4eca**\u72ec\u7acb (independent)**\u3067\u3042\u308b\u3068\u8a00\u3046\u72b6\u6cc1\u3067\u3042\u308b\u3002\u3053\u306e\u3068\u304d\u3001$Z$ \u306e\u5b9f\u73fe\u5024\u3092 $z$ \u3068\u3057\u3066\u3001\u6761\u4ef6\u4ed8\u304d\u78ba\u7387 $p(y | z)$ \u306f\u3001$Y$ \u304c\u3069\u3046\u306a\u308b\u304b\u304c $Z$ \u304c\u3069\u3046\u306a\u308b\u304b\u306b\u5168\u304f\u95a2\u4fc2\u304c\u306a\u3044\u3053\u3068\u304b\u3089\u3001 $p(y)$ \u3068\u7b49\u3057\u304f\u306a\u308b\u3002\u6761\u4ef6\u4ed8\u3051\u305f\u3068\u3057\u3066\u3082\u3001\u6761\u4ef6\u4ed8\u3051\u306a\u304b\u3063\u305f\u3068\u3057\u3066\u3082\u3001\u7d50\u679c\u304c\u5909\u308f\u3089\u306a\u3044\u305f\u3081\u3067\u3042\u308b\u3002\u3053\u308c\u3092\u7528\u3044\u308b\u3068\u3001 $y$ \u3068 $z$ \u306e\u540c\u6642\u78ba\u7387\u306f\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u5909\u5f62\u3067\u304d\u308b\u3002\n\n$$\n\\begin{align}\np(y, z) &= p(y | z) p(z) \\\\\np(y, z) &= p(y) p(z)\n\\end{align}\n$$\n\n $Y$ \u3068 $Z$ \u304c\u72ec\u7acb\u3067\u3042\u308b\u3053\u3068\u304b\u3089\u3001 $p(y | z) = p(y)$ \u3068\u306a\u308b\u3053\u3068\u3092\u7528\u3044\u307e\u3057\u305f\u3002\u3053\u306e\u5f0f\u304b\u3089\u3001**2\u3064\u306e\u78ba\u7387\u5909\u6570\u304c\u72ec\u7acb\u3067\u3042\u308b\u3068\u304d\u3001\u540c\u6642\u78ba\u7387\u306f\u305d\u308c\u305e\u308c\u306e\u5468\u8fba\u78ba\u7387\u306e\u7a4d\u3067\u66f8\u3051\u308b**\u3068\u8a00\u3046\u3053\u3068\u304c\u8a00\u3048\u307e\u3059\u3002\n\n## \u30d9\u30a4\u30ba\u306e\u5b9a\u7406\n\n\u524d\u7bc0\u3067\u8aac\u660e\u3057\u305f\u6761\u4ef6\u4ed8\u304d\u78ba\u7387\u306f\u3001\u3042\u308b\u524d\u63d0\u304c\u6210\u308a\u7acb\u3063\u3066\u3044\u308b\u72b6\u6cc1\u4e0b\u3067\u7740\u76ee\u3059\u308b\u4e8b\u8c61\u304c\u751f\u3058\u308b\u78ba\u7387\u3092\u8a18\u8ff0\u3059\u308b\u305f\u3081\u306e\u3082\u306e\u3067\u3057\u305f\u3002\u3053\u308c\u306f\u3001\u300c\u3042\u308b\"\u539f\u56e0\"\u304c\u751f\u3058\u305f\u3068\u8a00\u3046\u6761\u4ef6\u306e\u4e0b\u3067\u3001\u3042\u308b\"\u7d50\u679c\"\u304c\u751f\u3058\u308b\u78ba\u7387\u300d\u3092\u8003\u3048\u3066\u3044\u308b\u3068\u6349\u3048\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\u3067\u306f\u3001\u9006\u306b**\u300c\u3042\u308b\"\u7d50\u679c\"\u304c\u89b3\u6e2c\u3055\u308c\u305f\u3068\u8a00\u3046\u3068\u304d\u3001\u3042\u308b\u4e8b\u8c61\u304c\"\u539f\u56e0\"\u3067\u3042\u308b\u78ba\u7387\u300d**\u3092\u8003\u3048\u308b\u306b\u306f\u3069\u3046\u3057\u305f\u3089\u3088\u3044\u3067\u3057\u3087\u3046\u304b\u3002\u4eca\u3001\u539f\u56e0\u3068\u306a\u308a\u5f97\u308b\u4e8b\u8c61\u304c\u78ba\u7387\u5909\u6570 $X$ \u3067\u8868\u3055\u308c\u3001\u7d50\u679c\u3068\u306a\u308a\u5f97\u308b\u4e8b\u8c61\u304c\u78ba\u7387\u5909\u6570 $Y$ \u3067\u8868\u3055\u308c\u308b\u3068\u3059\u308b\u3002\u3053\u306e\u3068\u304d\u3001\u539f\u56e0\u3068\u3057\u3066\u5b9f\u969b\u306b $x$ \u304c\u89b3\u6e2c\u3055\u308c\u305f\u3082\u3068\u3067\u7d50\u679c\u304c $y$ \u3068\u306a\u308b\u78ba\u7387\u304c\u6761\u4ef6\u4ed8\u304d\u78ba\u7387\n\n$$\np(Y = y | X = x)\n$$\n\n\u3067\u8868\u3055\u308c\u307e\u3057\u305f\u3002\u524d\u7bc0\u306e\u5b9a\u7fa9\u304b\u3089\u3001\u3053\u308c\u306b\u539f\u56e0 $x$ \u304c\u305d\u3082\u305d\u3082\u767a\u751f\u3059\u308b\u78ba\u7387 $p(X = x)$ \u3092\u639b\u3051\u5408\u308f\u305b\u308b\u3068\u3001\u540c\u6642\u78ba\u7387 $p(Y = y, X = x)$ \u306b\u306a\u308b\u3002\u3059\u306a\u308f\u3061\u3001\n\n$$\np(Y = y | X = x) p(X = x) = p(Y = y, X = x) \\hspace{2em} \\cdots (1)\n$$\n\n\u3067\u3042\u308b\u3002\u3067\u306f\u3001\u7d50\u679c\u304c $y$ \u3067\u3042\u3063\u305f\u3068\u8a00\u3046\u89b3\u6e2c\u306e\u4e0b\u3067\u3001\u539f\u56e0\u304c $x$ \u3067\u3042\u308b\u78ba\u7387\u306f\u3069\u306e\u3088\u3046\u306b\u8868\u3055\u308c\u308b\u3067\u3057\u3087\u3046\u304b\u3002\u3053\u308c\u306f\u4e0a\u306e\u300c\u6761\u4ef6\u306e\u4e8b\u8c61\u300d\u3068\u300c\u7740\u76ee\u3059\u308b\u4e8b\u8c61\u300d\u3092\u5165\u308c\u66ff\u3048\u305f\u6761\u4ef6\u4ed8\u304d\u78ba\u7387\u3068\u3057\u3066\u3001\n\n$$\np(X = x | Y = y)\n$$\n\n\u3068\u66f8\u304f\u3053\u3068\u304c\u3067\u304d\u308b\u3002 $y$ \u3068\u8a00\u3046\u7d50\u679c\u304c\u89b3\u6e2c\u3055\u308c\u305f\u3082\u3068\u3067\u3001\u539f\u56e0\u304c $x$ \u3067\u3042\u3063\u305f\u78ba\u7387\u3068\u8a00\u3046\u610f\u5473\u3067\u3042\u308b\u3002\u3053\u308c\u306b\u7d50\u679c $y$ \u304c\u305d\u3082\u305d\u3082\u767a\u751f\u3059\u308b\u78ba\u7387 $p(Y = y)$ \u3092\u304b\u3051\u5408\u308f\u305b\u308b\u3068\u3001\u6761\u4ef6\u4ed8\u304d\u78ba\u7387\u306e\u5b9a\u7fa9\u304b\u3089\n\n$$\np(X = x| Y = y) p(Y = y) = p(X = x, Y = y) \\hspace{2em} \\cdots (2)\n$$\n\n\u304c\u5c0e\u304b\u308c\u307e\u3059\u3002\u3053\u3053\u3067\u3001\u5f0f(1)\u3068\u5f0f(2)\u306e\u53f3\u8fba\u304c\u540c\u3058\u306b\u306a\u3063\u3066\u3044\u308b\u3053\u3068\u306b\u7740\u76ee\u3059\u308b\u3002\u3059\u308b\u3068\u3001\u5f0f(1)\u3068\u5f0f(2)\u306e\u5de6\u8fba\u540c\u58eb\u3092\u7b49\u53f7\u3067\u7d50\u3076\u3053\u3068\u304c\u3067\u304d\u3001\n\n$$\np(Y = y | X = x) p(X = x) = p(X = x | Y = y) p(Y = y)\n$$\n\n\u304c\u6210\u308a\u7acb\u3064\u3053\u3068\u304c\u5206\u304b\u308b\u3002\u3053\u306e\u5f0f\u3092\u5909\u5f62\u3057\u3066\u3001\u6c42\u3081\u305f\u3044\u300c\u7d50\u679c $y$ \u304c\u751f\u3058\u305f\u3068\u8a00\u3046**\u6761\u4ef6\u306e\u4e0b\u3067**\u539f\u56e0\u304c $x$ \u3067\u3042\u308b\u78ba\u7387\u300d\u3092\u5de6\u8fba\u306b\u6b8b\u3059\u3068\u3001\n\n$$\np(X = x | Y = y) = \\frac{p(Y = y | X = x) p(X = x)}{p(Y = y)}\n$$\n\n\u304c\u5c0e\u304b\u308c\u307e\u3059\u3002\u3053\u308c\u3092**\u30d9\u30a4\u30ba\u306e\u5b9a\u7406\uff08Bayes' theorem\uff09**\u3068\u8a00\u3046\u3002\u3053\u308c\u306b\u3088\u3063\u3066\u3001\u3042\u308b\u7d50\u679c\u304c\u89b3\u6e2c\u3055\u308c\u305f\u3068\u304d\u306b\u3001\u3042\u308b\u4e8b\u8c61\u304c\u539f\u56e0\u3067\u3042\u308b\u78ba\u7387\u3092\u3001\n\n- \u539f\u56e0\u3068\u3057\u3066\u8003\u3048\u3066\u3044\u308b\u4e8b\u8c61\u304c\uff08\u7d50\u679c\u3068\u95a2\u4fc2\u306a\u304f\uff09\u305d\u3082\u305d\u3082\u751f\u3058\u308b\u78ba\u7387\uff08 $p(X = x)$ \uff09\n- \u7d50\u679c\u3068\u3057\u3066\u89b3\u6e2c\u3057\u305f\u4e8b\u8c61\u304c\uff08\u539f\u56e0\u306b\u95a2\u4fc2\u306a\u304f\uff09\u305d\u3082\u305d\u3082\u751f\u3058\u308b\u78ba\u7387\uff08 $p(Y = y)$ \uff09\n- \u8003\u3048\u3066\u3044\u308b\u539f\u56e0\u304c\u5b9f\u969b\u306b\u751f\u3058\u305f\u3068\u8a00\u3046\u4e0b\u3067\u89b3\u6e2c\u3055\u308c\u305f\u7d50\u679c\u304c\u751f\u3058\u308b\u78ba\u7387\uff08 $p(Y = y | X = x)$ \uff09\n\n\u306e3\u3064\u304b\u3089\u3001\u6c42\u3081\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\u30d9\u30a4\u30ba\u306e\u5b9a\u7406\u306b\u767b\u5834\u3059\u308b\u5de6\u8fba\u306e\u6761\u4ef6\u4ed8\u304d\u78ba\u7387\u3068\u53f3\u8fba\u306e\u5206\u5b50\u306b\u3042\u308b\u5468\u8fba\u78ba\u7387\u306b\u306f\u3001\u7279\u5225\u306a\u547c\u3073\u65b9\u304c\u3042\u308b\u3002\u307e\u305a\u53f3\u8fba\u306e\u5206\u5b50\u306b\u3042\u308b\u5468\u8fba\u78ba\u7387\uff08\u4e0a\u5f0f\u3067\u306f $p(X = x)$ \uff09\u306f\u3001\u300c\u7d50\u679c\u300d\u304c\u89b3\u6e2c\u3059\u308b\u524d\uff08\u4e8b\u524d\uff09\u306b\u3001\u539f\u56e0 $x$ \u304c\u305d\u3082\u305d\u3082\u751f\u3058\u308b\u78ba\u7387\u3092\u8868\u3059\u306e\u3067\u3001**\u4e8b\u524d\u78ba\u7387\uff08prior probability)**\u3068\u547c\u3070\u308c\u307e\u3059\u3002\u4e00\u65b9\u3001\u5de6\u8fba\u306e\u6761\u4ef6\u4ed8\u304d\u78ba\u7387\uff08\u4e0a\u5f0f\u3067\u306f $p(X = x | Y = y)$ \uff09\u306f\u3001\u3042\u308b\u300c\u7d50\u679c $y$\u300d\u304c\u89b3\u6e2c\u3055\u308c\u305f\u3068\u8a00\u3046\u6761\u4ef6\u306e\u4e0b\u3067\uff08\u4e8b\u5f8c\u306b\uff09\u3001\u539f\u56e0 $x$ \u304c\u751f\u3058\u3066\u3044\u305f\u3068\u8a00\u3046\u78ba\u7387\u3092\u8868\u3059\u306e\u3067\u3001**\u4e8b\u5f8c\u78ba\u7387\uff08posterior probability\uff09**\u3068\u547c\u3070\u308c\u307e\u3059\u3002\n\n\u30d9\u30a4\u30ba\u306e\u5b9a\u7406\u306e\u5fdc\u7528\u4e8b\u4f8b\u3068\u3057\u3066\u3001\u30b9\u30d1\u30e0\u30e1\u30fc\u30eb\u30d5\u30a3\u30eb\u30bf\u30fc\u304c\u3042\u308b\u3002\u307e\u305a\u3001 $N$ \u500b\u306e\u7740\u76ee\u3059\u308b\u5358\u8a9e $w_i (i=1, \\dots, N)$ \u3092\u6c7a\u3081\u307e\u3059\uff08\"sale\", \"buy\", \"free\", ...\u306a\u3069\uff09\u3002\u305d\u3057\u3066\u3001\u30e1\u30fc\u30eb\u306b\u3042\u308b\u5358\u8a9e $w_i$ \u304c\u542b\u307e\u308c\u308b\u3068\u304d $1$ \u3068\u306a\u308a\u3001\u542b\u307e\u308c\u306a\u3044\u3068\u304d $0$ \u3068\u306a\u308b\u78ba\u7387\u5909\u6570\u3092 $W_i$ \u3068\u3057\u3001\u300c\u30e1\u30fc\u30eb\u306b\u3042\u308b\u5358\u8a9e $w_i$ \u304c\u542b\u307e\u308c\u308b\u78ba\u7387\u300d\u3092 $p(W_i = 1)$ \u3068\u3059\u308b\u3002 \u6b21\u306b\u3001\u30e1\u30fc\u30eb\u304c\u30b9\u30d1\u30e0\u30e1\u30fc\u30eb\u3067\u3042\u308b\u3068\u304d $1$ \u3068\u306a\u308a\u3001\u30b9\u30d1\u30e0\u30e1\u30fc\u30eb\u3067\u306a\u3044\u3068\u304d $0$ \u3068\u306a\u308b\u78ba\u7387\u5909\u6570\u3092 $Y$ \u3068\u3057\u3001\u300c\u30b9\u30d1\u30e0\u30e1\u30fc\u30eb\u306e\u5b58\u5728\u78ba\u7387\u300d\u3092 $p(Y = 1)$ \u3068\u3059\u308b\u3002\u3053\u306e\u3068\u304d\u3001\u300c\u3042\u308b\u30e1\u30fc\u30eb\u304c\u30b9\u30d1\u30e0\u30e1\u30fc\u30eb\u3067\u3042\u3063\u305f\u3068\u8a00\u3046**\u72b6\u6cc1\u306e\u4e0b\u3067**\u5358\u8a9e $w_i$ \u304c\u542b\u307e\u308c\u3066\u3044\u305f\u300d\u3068\u8a00\u3046\u78ba\u7387\u306f $p(W_i = 1 | Y = 1)$ \u3068\u306a\u308b\u3002\u3059\u308b\u3068\u3001\u4f8b\u3048\u3070 $w_i$ \u3068 $w_j$ \u304c\u4e21\u65b9\u542b\u307e\u308c\u3066\u3044\u305f\u5834\u5408\u306f\u3001\u540c\u6642\u78ba\u7387 $p(W_i = 1, W_j = 1 | Y = 1)$ \u3092\u8003\u3048\u308b\u3053\u3068\u306b\u306a\u308b\u304c\u3001\u5404\u5358\u8a9e\u304c\u72ec\u7acb\u306b\u73fe\u308c\u308b\u3068\u4eee\u5b9a\u3059\u308b\u3068\u3001\u3053\u308c\u306f $p(W_i = 1 | Y = 1) p(W_j = 1 | Y = 1)$ \u3068\u5206\u89e3\u3067\u304d\u308b\u3002\u3053\u3053\u3067\u3001\u4e16\u306e\u4e2d\u306b\u3042\u308b\u5927\u91cf\u306e\u30e1\u30fc\u30eb\u3092\u96c6\u3081\u3066\u3001\u5404\u5358\u8a9e\u304c\u3069\u306e\u304f\u3089\u3044\u306e\u78ba\u7387\u3067\u73fe\u308c\u308b\u304b\u3092\u8abf\u3079\u308b\u3068\u3001 $p(W_i = 1) \\ (i=1,\\dots,N)$ \u304c\u6c42\u307e\u308b\u3002\u307e\u305f\u3001\u96c6\u3081\u305f\u30e1\u30fc\u30eb\u304b\u3089\u30b9\u30d1\u30e0\u30e1\u30fc\u30eb\u3060\u3051\u3092\u629c\u304d\u51fa\u3059\u3002\u3059\u308b\u3068\u3001\u30e1\u30fc\u30eb\u304c\u30b9\u30d1\u30e0\u30e1\u30fc\u30eb\u3067\u3042\u308b\u78ba\u7387 $p(Y = 1)$ \u304c\u6c42\u307e\u308b\u3002\u3055\u3089\u306b\u3001\u305d\u308c\u3089\u306e\u30b9\u30d1\u30e0\u30e1\u30fc\u30eb\u4e2d\u306b\u542b\u307e\u308c\u308b\u5358\u8a9e\u3092\u8abf\u3079\u3001\u3069\u306e\u5358\u8a9e\u304c\u3069\u3046\u8a00\u3046\u78ba\u7387\u3067\u51fa\u73fe\u3057\u3066\u3044\u308b\u304b\u3092\u3001\u7740\u76ee\u3057\u3066\u3044\u308b\u5168\u5358\u8a9e\u306b\u3064\u3044\u3066\u6c42\u3081\u308b\u3068\u3001 $p(W_i = 1 | Y = 1) \\ (i=1, \\dots, N)$ \u304c\u5168\u3066\u6c42\u307e\u308b\u3002\u3053\u308c\u3089\u3092\u7528\u3044\u308b\u3068\u3001\u300c\u3042\u308b\u30e1\u30fc\u30eb\u306b\u5358\u8a9e $w_i, w_j, w_k, \\dots$ \u3089\u304c\u542b\u307e\u308c\u3066\u3044\u308b\u3068\u304d\u3001\u305d\u306e\u30e1\u30fc\u30eb\u304c\u30b9\u30d1\u30e0\u30e1\u30fc\u30eb\u3067\u3042\u308b\u78ba\u7387\u300d\u3092\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u8a08\u7b97\u3067\u304d\u308b\u3002\n\n$$\np(Y = 1 | W_i = 1, W_j = 1, W_k = 1, \\dots ) = \\frac{p(W_i = 1, W_j = 1, W_k = 1, \\dots | Y = 1) p(Y = 1)}{p(W_i = 1, W_j = 1, W_k = 1, \\dots )}\n$$\n\n## \u5c24\u5ea6\u3068\u6700\u5c24\u63a8\u5b9a\n\n\u3053\u308c\u307e\u3067\u306e\u7bc0\u3067\u306f\u3001\u300c**\u78ba\u7387\u5909\u6570\u304c\u3068\u308a\u3046\u308b\u69d8\u3005\u306a\u5024\u306b\u78ba\u7387\u3092\u5bfe\u5fdc\u3055\u305b\u308b**\u300d\u78ba\u7387\u5206\u5e03\u306f\u3001\u8868\u306e\u5f62\u3067\u8868\u3055\u308c\u3066\u3044\u307e\u3057\u305f\u3002\u3053\u3053\u3067\u3001\u78ba\u7387\u5909\u6570 $X$ \u304c $x$ \u3068\u8a00\u3046\u5024\u3092\u3068\u308b\u78ba\u7387 $p(X = x)$ \u3092\u3001\u8868\u306e\u4ee3\u308f\u308a\u306b\u3001\u3042\u308b\u30d1\u30e9\u30e1\u30fc\u30bf $\\theta$ \u3067\u7279\u5fb4\u3065\u3051\u3089\u308c\u305f\u95a2\u6570 $f(x; \\theta)$ \u306b\u3088\u3063\u3066\u8868\u3057\u3066\u307f\u308b\u3002\u3053\u306e\u95a2\u6570\u306f\u3001\u300c**\u78ba\u7387\u5909\u6570** $X$ **\u304c\u3068\u308a\u3046\u308b\u69d8\u3005\u306a\u5024** $x$ **\u306b\u78ba\u7387\u3092\u5bfe\u5fdc\u3055\u305b\u308b**\u300d\u306e\u3067\u3001 $X$ \u306e\u78ba\u7387\u5206\u5e03\u3092\u8868\u3057\u3066\u3044\u308b\u3002\u3053\u306e\u3088\u3046\u306a\u95a2\u6570\u306f**\u78ba\u7387\u30e2\u30c7\u30eb\uff08probabilistic model\uff09**\u3068\u3082\u547c\u3070\u308c\u3001\u7279\u306b\u30d1\u30e9\u30e1\u30fc\u30bf\u306b\u3088\u3063\u3066\u5f62\u72b6\u304c\u6c7a\u5b9a\u3055\u308c\u308b\u95a2\u6570\u3092\u7528\u3044\u308b\u5834\u5408\u306f**\u30d1\u30e9\u30e1\u30c8\u30ea\u30c3\u30af\u30e2\u30c7\u30eb\uff08parametric model\uff09**\u3068\u547c\u3070\u308c\u307e\u3059\u3002\n\n\u3053\u306e\u3088\u3046\u306a\u78ba\u7387\u30e2\u30c7\u30eb\u306e\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u3046\u307e\u304f\u6c7a\u5b9a\u3059\u308b\u3053\u3068\u3067\u3001\u30c7\u30fc\u30bf\u306e\u5206\u5e03\u3092\u8868\u73fe\u3067\u304d\u308c\u3070\u3001\u672a\u77e5\u306e\u30c7\u30fc\u30bf\u306b\u5bfe\u3057\u3066\u3082\u305d\u308c\u304c\u3069\u306e\u304f\u3089\u3044\u306e\u78ba\u7387\u3067\u767a\u751f\u3059\u308b\u306e\u304b\u3068\u3044\u3063\u305f\u4e88\u6e2c\u304c\u53ef\u80fd\u3068\u306a\u3063\u305f\u308a\u3001\u4fbf\u5229\u3067\u3042\u308b\u3002\u63a8\u5b9a\u65b9\u6cd5\u306b\u306f\u69d8\u3005\u306a\u3082\u306e\u304c\u3042\u308a\u3001\u3069\u3046\u3084\u3063\u3066\u63a8\u5b9a\u3059\u308b\u304b\u306f\u63a8\u5b9a\u3059\u308b\u4eba\u306e\u81ea\u7531\u3067\u3042\u308b\u304c\u3001\u672c\u7bc0\u3067\u306f\u6700\u3082\u4e00\u822c\u7684\u306a\u65b9\u6cd5\u306e\u4e00\u3064\u3067\u3042\u308b\u6700\u5c24\u63a8\u5b9a\u3092\u8aac\u660e\u3059\u308b\u3002\u6700\u5c24\u63a8\u5b9a\u306f\u78ba\u7387\u8ad6\u304b\u3089\u6b63\u5f53\u5316\u3067\u304d\u308b\u3068\u8a00\u3046\u9577\u6240\u304c\u3042\u308b\u3002\n\n\u3055\u3066\u3001\u78ba\u7387\u30e2\u30c7\u30eb\u304c\u3069\u306e\u304f\u3089\u3044\u5b9f\u969b\u306e\u89b3\u6e2c\u30c7\u30fc\u30bf\u306b\u5373\u3057\u3066\u3044\u308b\u304b\u3092**\u5c24\u5ea6\uff08\u3086\u3046\u3069\uff09\uff08likelihood\uff09**\u3068\u8a00\u3044\u3001\u89b3\u6e2c\u3055\u308c\u305f\u30c7\u30fc\u30bf\u3092\u30e2\u30c7\u30eb\u306b\u5165\u529b\u3057\u3001\u305d\u306e\u51fa\u529b\u3092\u304b\u3051\u5408\u308f\u305b\u305f\u3082\u306e\u3067\u5b9a\u7fa9\u3055\u308c\u307e\u3059\u3002\n\n\u4f8b\u3048\u3070\u3001 $N$ \u500b\u306e\u30c7\u30fc\u30bf $x_i \\ (i=1,\\dots,N)$ \u304c\u72ec\u7acb\u306b\u89b3\u6e2c\u3055\u308c\u305f\u3068\u304d\u3001\u3053\u306e\u89b3\u6e2c\u30c7\u30fc\u30bf\u306e\u4e0b\u3067\u306e\u78ba\u7387\u30e2\u30c7\u30eb $f(x; \\theta)$ \u306e**\u5c24\u5ea6**\u306f\n\n$$\nL(\\theta) = \\prod_{i=1}^N f(x_i; \\theta)\n$$\n\n\u3068\u8a08\u7b97\u3055\u308c\u307e\u3059\u3002\u4e0e\u3048\u3089\u308c\u305f\u30c7\u30fc\u30bf\u304b\u3089\u3001\u300c\u3069\u306e\u3088\u3046\u306a\u30c7\u30fc\u30bf\u304c\u3069\u306e\u304f\u3089\u3044\u3088\u304f\u89b3\u6e2c\u3055\u308c\u308b\u304b\u300d\u3092\u8868\u3059\u78ba\u7387\u5206\u5e03\u3092\u63a8\u5b9a\uff08[\u6ce8\u91c85](#note5)\uff09\u3059\u308b\u305f\u3081\u306b\u3001\u4e88\u3081\u7528\u610f\u3057\u305f\u78ba\u7387\u30e2\u30c7\u30eb\u306e\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u3001\u305d\u308c\u3089\u306e\u89b3\u6e2c\u30c7\u30fc\u30bf\u306e\u4e0b\u3067\u306e**\u5c24\u5ea6\u304c\u6700\u5927**\u306b\u306a\u308b\u3088\u3046\u306b\u6c7a\u5b9a\u3059\u308b\u65b9\u6cd5\u3092\u3001**\u6700\u5c24\uff08\u3055\u3044\u3086\u3046\uff09\u63a8\u5b9a\uff08maximum likelihood estimation\uff09**\u3068\u8a00\u3046\u3002\n\n\u4e0a\u5f0f\u306e $\\prod$ \u3068\u8a00\u3046\u8a18\u53f7\u306f\u3001 $\\sum$ \u306e\u639b\u3051\u7b97\u7248\u3067\u3001\u5168\u3066\u306e\u5024\u3092\u639b\u3051\u5408\u308f\u305b\u308b\u3068\u8a00\u3046\u610f\u5473\u3067\u3042\u308b\u3002\u8907\u6570\u30c7\u30fc\u30bf\u306b\u5bfe\u3059\u308b\u5c24\u5ea6\u306f\u3001 $1$ \u3088\u308a\u5c0f\u3055\u306a\u5024\u306e\u7a4d\u3068\u306a\u308b\u305f\u3081\u3001\u7d50\u679c\u306f\u975e\u5e38\u306b\u5c0f\u3055\u306a\u6570\u306b\u306a\u308a\u3001\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u3067\u3053\u306e\u8a08\u7b97\u3092\u884c\u3046\u969b\u306b\u306f\u30a2\u30f3\u30c0\u30fc\u30d5\u30ed\u30fc\u3068\u8a00\u3046\u554f\u984c\u304c\u767a\u751f\u3057\u3084\u3059\u304f\u306a\u308b\u3002\u307e\u305f\u5c24\u5ea6\u3092\u6700\u5927\u5316\u3057\u305f\u3044\u5834\u5408\u3001\u7a4d\u306e\u5f62\u306e\u5f0f\u306e\u6700\u5927\u5316\u306f\u96e3\u3057\u3044\u3053\u3068\u304c\u77e5\u3089\u308c\u3066\u3044\u308b\u3002\u305d\u3053\u3067\u5c24\u5ea6\u306e\u5bfe\u6570\u3092\u3068\u3063\u305f**\u5bfe\u6570\u5c24\u5ea6\uff08log likelihood\uff09**\u3092\u8003\u3048\u307e\u3059\u3002 $y = \\log(x)$ \u306f\u5358\u8abf\u5897\u52a0\u3067\u3042\u308b\u305f\u3081\u3001\u5bfe\u6570\u3092\u3068\u308b\u524d\u5f8c\u3067\u5927\u5c0f\u95a2\u4fc2\u306f\u5909\u308f\u3089\u306a\u3044\u3002\u305d\u306e\u305f\u3081\u5bfe\u6570\u5c24\u5ea6\u3092\u6700\u5927\u306b\u3059\u308b\u3068\u304d\u306e $\\theta$ \u306f\u3001\u5143\u306e\u5c24\u5ea6\u3082\u6700\u5927\u306b\u3059\u308b\u3002\n\n$$\n\\log L(\\theta) = \\sum_{i=1}^N \\log f(x_i; \\theta)\n$$\n\n\u3088\u3063\u3066\u3001\u3053\u306e\u5bfe\u6570\u5c24\u5ea6\u3092\u6700\u5927\u5316\u3059\u308b\u30d1\u30e9\u30e1\u30fc\u30bf $\\theta$ \u3092\u6c42\u3081\u308b\u3053\u3068\u304c\u3067\u304d\u308c\u3070\u3001\u305d\u306e\u5024\u304c\u89b3\u6e2c\u30c7\u30fc\u30bf $x_i (i=1,\\dots,N)$ \u306e\u5206\u5e03\u3092\u6700\u3082\u3088\u304f\u8868\u73fe\u3059\u308b\u78ba\u7387\u30e2\u30c7\u30eb\u306e\u30d1\u30e9\u30e1\u30fc\u30bf\u3068\u306a\u308b\u3002\n\n### \u4f8b\uff1a\u30b3\u30a4\u30f3\u30c8\u30b9\u306e\u30d1\u30e9\u30e1\u30fc\u30bf\u63a8\u5b9a\n\n\u3053\u3053\u3067\u3001\u5177\u4f53\u4f8b\u3068\u3057\u3066\u3001\u30b3\u30a4\u30f3\u306e\u8868\u30fb\u88cf\u304c\u51fa\u308b\u78ba\u7387\u3092\u63a8\u5b9a\u3059\u308b\u554f\u984c\u3092\u8003\u3048\u3066\u307f\u308b\u3002\u30b3\u30a4\u30f3\u3092\u6295\u3052\u3066\u300c\u8868\u304c\u51fa\u308b\u300d\u4e8b\u8c61\u3092 $1$ \u306b\u3001\u300c\u88cf\u304c\u51fa\u308b\u300d\u4e8b\u8c61\u3092 $0$ \u306b\u5bfe\u5fdc\u4ed8\u3051\u308b\u78ba\u7387\u5909\u6570\u3092 $X$ \u3068\u3059\u308b\u3002\u3053\u306e\u3068\u304d\u3001 $p(X)$ \u3092\u30b7\u30f3\u30d7\u30eb\u306a\u78ba\u7387\u30e2\u30c7\u30eb\n\n$$\nf(x; \\theta) = \\theta^x (1 - \\theta)^{1 - x}\n$$\n\n\u3067\u8868\u73fe\u3059\u308b\u3053\u3068\u306b\u3059\u308b\uff08[\u6ce8\u91c86](#note6)\uff09\u3002\u3053\u308c\u306f $x = 1$ \u306e\u3068\u304d\u3001\u3059\u306a\u308f\u3061\u30b3\u30a4\u30f3\u304c\u8868\u3067\u3042\u308b\u3068\u304d $\\theta$ \u3092\u305d\u306e\u307e\u307e\u8fd4\u3057\u3001 $x = 0$ \u306e\u3068\u304d\u3001\u3059\u306a\u308f\u3061\u30b3\u30a4\u30f3\u304c\u88cf\u3067\u3042\u308b\u3068\u304d $1 - \\theta$ \u3092\u8fd4\u3059\u3088\u3046\u306a\u95a2\u6570\u3068\u306a\u3063\u3066\u3044\u308b\u3002\u305f\u3060\u3057\u3001 $0 \\leq \\theta \\leq 1$ \u3092\u6e80\u305f\u3059\u3053\u3068\u3068\u3059\u308b\u3002\u4eca\u3001\u30b3\u30a4\u30f3\u3092 $10$ \u56de\u6295\u3052\u3001\u4ee5\u4e0b\u306e\u89b3\u6e2c\u7d50\u679c\u304c\u5f97\u3089\u308c\u305f\u3068\u3059\u308b\u3002\n\n| $\\ $ | 1\u56de\u76ee | 2\u56de\u76ee | 3\u56de\u76ee | 4\u56de\u76ee | 5\u56de\u76ee | 6\u56de\u76ee | 7\u56de\u76ee | 8\u56de\u76ee | 9\u56de\u76ee | 10\u56de\u76ee |\n|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|\n| X | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | 0 |\n\n\u3053\u308c\u3089\u306e\u89b3\u6e2c\u30c7\u30fc\u30bf\u306e\u4e0b\u3067\u306e\u78ba\u7387\u30e2\u30c7\u30eb\u306e\u5c24\u5ea6\u306f\n\n$$\n\\begin{aligned}\nL(\\theta) &=\n\\theta \\cdot\n(1 - \\theta) \\cdot\n\\theta \\cdot\n\\theta \\cdot\n\\theta \\cdot\n(1 - \\theta) \\cdot\n(1 - \\theta) \\cdot\n\\theta \\cdot\n(1 - \\theta) \\cdot\n(1 - \\theta) \\\\\n&= \\theta^{5} \\cdot (1 - \\theta)^{5}\n\\end{aligned}\n$$\n\n\u3067\u3042\u308b\u3002\u5bfe\u6570\u5c24\u5ea6\u306f\u3001\n\n$$\n\\log L(\\theta) = 5 \\log \\theta + 5 \\log \\left( 1 - \\theta \\right)\n$$\n\n\u3068\u306a\u308b\u3002\u3053\u308c\u304c\u6700\u5927\u3068\u306a\u308b\u3068\u304d\u306e $\\theta$ \u306f\u3001\u3053\u306e\u5f0f\u3092 $\\theta$ \u3067\u5fae\u5206\u3057\u305f\u5f0f\u3092 $0$ \u3068\u304a\u3044\u3066\u89e3\u6790\u7684\u306b\u89e3\u3051\u3070\u3088\u304f\u3001\n\n$$\n\\begin{align}\n\\frac{5}{\\theta} - \\frac{5}{\\left( 1 - \\theta \\right)} &= 0 \\\\\n\\therefore \\theta = \\frac{1}{2}\n\\end{align}\n$$\n\n\u3068\u6c7a\u5b9a\u3059\u308b\u3002\u3053\u308c\u304c\u6700\u5c24\u63a8\u5b9a\u3067\u3042\u308b\u3002\n\n## \u4e8b\u5f8c\u78ba\u7387\u6700\u5927\u5316\u63a8\u5b9a\uff08MAP\u63a8\u5b9a\uff09\n\n\u524d\u7bc0\u3067\u89e3\u8aac\u3057\u305f\u6700\u5c24\u63a8\u5b9a\u306f\u3001\u591a\u304f\u306e\u5834\u5408\u3067\u6709\u7528\u3067\u3042\u308b\u304c\u3001\u6c42\u3081\u308b\u30d1\u30e9\u30e1\u30fc\u30bf\u306b\u4f55\u3089\u304b\u306e**\u4e8b\u524d\u77e5\u8b58**\u304c\u3042\u3063\u3066\u3082\u3001\u305d\u308c\u3092\u6d3b\u304b\u3059\u3053\u3068\u304c\u3067\u304d\u306a\u3044\u3002\u305d\u306e\u305f\u3081\u3001\u30b5\u30f3\u30d7\u30eb\u30b5\u30a4\u30ba\u304c\u5c0f\u3055\u3044\u5834\u5408\u306b\u3001\u5b9f\u969b\u306b\u306f\u307b\u3068\u3093\u3069\u3042\u308a\u5f97\u306a\u3044\u7d50\u679c\u304c\u6c42\u307e\u308b\u3053\u3068\u304c\u3042\u308b\u3002\u5177\u4f53\u4f8b\u3092\u898b\u3066\u307f\u308b\u3002\n\n\u518d\u3073\u3001\u30b3\u30a4\u30f3\u306e\u8868\u30fb\u88cf\u304c\u51fa\u308b\u78ba\u7387\u3092\u63a8\u5b9a\u3059\u308b\u4f8b\u3092\u8003\u3048\u307e\u3059\u3002\u30b3\u30a4\u30f3\u3092 $5$ \u56de\u6295\u3052\u305f\u3068\u3053\u308d\u3001**\u305f\u307e\u305f\u307e** ${\\bf 5}$ **\u56de\u3068\u3082\u8868\u304c\u51fa\u305f**\u3068\u3059\u308b\u3002\u3053\u306e\u5834\u5408\u3001\u524d\u7bc0\u3068\u540c\u3058\u78ba\u7387\u30e2\u30c7\u30eb\u3092\u7528\u3044\u3066\u5c24\u5ea6\u3092\u8a08\u7b97\u3057\u3001\u6700\u5c24\u63a8\u5b9a\u3067\u30e2\u30c7\u30eb\u306e\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u6c7a\u5b9a\u3059\u308b\u3068\u3001 $0 \\leq \\theta \\leq 1$ \u3092\u6e80\u305f\u3057\u306a\u304c\u3089\u3001\u4eca\u56de\u306e\u89b3\u6e2c\u30c7\u30fc\u30bf\u306e\u4e0b\u3067\u306e\u5c24\u5ea6 $\\theta^5$ \u3092\u6700\u5927\u306b\u3059\u308b $\\theta$ \u306f $1$ \u3068\u306a\u308b\u3002\u3053\u308c\u306f\u300c\u8868\u304c\u51fa\u308b\u78ba\u7387\u304c $1$ \u300d\u3059\u306a\u308f\u3061**\u300c\u88cf\u9762\u304c\u51fa\u308b\u78ba\u7387\u306f** $0$**\u300d**\u3068\u8a00\u3046\u63a8\u5b9a\u7d50\u679c\u304c\u5f97\u3089\u308c\u3066\u3057\u307e\u3063\u305f\u3053\u3068\u3092\u610f\u5473\u3059\u308b\u3002\u3082\u3057\u300c\u88cf\u304c\u51fa\u308b\u78ba\u7387\u3082 $0$ \u3088\u308a\u306f\u5927\u304d\u3044\u3060\u308d\u3046\u300d\u3068\u8a00\u3046\u4e8b\u524d\u77e5\u8b58\u3092\u6301\u3063\u3066\u304a\u308a\u305d\u308c\u3092\u6d3b\u7528\u3067\u304d\u308c\u3070\u3001\u4eca\u56de\u306e\u3088\u3046\u306a\u5834\u5408\u3067\u3082\u3088\u308a\u3088\u3044\u63a8\u5b9a\u304c\u3067\u304d\u305d\u3046\u3067\u3042\u308b\u3002\n\n\u4e8b\u524d\u77e5\u8b58\u3082\u8003\u616e\u3057\u306a\u304c\u3089\u3001\u89b3\u6e2c\u30c7\u30fc\u30bf\u306b\u57fa\u3065\u3044\u3066\u78ba\u7387\u30e2\u30c7\u30eb\u306e\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u63a8\u5b9a\u3059\u308b\u65b9\u6cd5\u306b\u306f\u3001**\u4e8b\u5f8c\u78ba\u7387\u6700\u5927\u5316\uff08maximum a posteriori, \u4ee5\u964d MAP\uff09\u63a8\u5b9a**\u304c\u3042\u308b\u3002MAP \u63a8\u5b9a\u3067\u3082\u3001\u5bfe\u8c61\u306e\u30c7\u30fc\u30bf\u306e\u78ba\u7387\u5206\u5e03\u3092\u8868\u3059\u78ba\u7387\u30e2\u30c7\u30eb\u306e\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u3001\u30c7\u30fc\u30bf\u3092\u5229\u7528\u3057\u3066\u6c7a\u5b9a\u3059\u308b\u304c\u3001\u30c7\u30fc\u30bf\u3060\u3051\u3067\u306a\u304f**\u30d1\u30e9\u30e1\u30fc\u30bf\u3082\u78ba\u7387\u5909\u6570\u3060\u3068\u8003\u3048\u308b**\u70b9\u304c\u6700\u5c24\u63a8\u5b9a\u3068\u306f\u7570\u306a\u3063\u3066\u3044\u308b\u3002\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u78ba\u7387\u5909\u6570 $\\Theta$ \u3068\u3059\u308b\u3068\u3001\u3053\u306e\u30d1\u30e9\u30e1\u30fc\u30bf\u304c\u3069\u306e\u3088\u3046\u306a\u5024\u3092\u3068\u308b\u304b\u3092\u8868\u3059\u5206\u5e03 $p(\\Theta)$ \u304c\u5c0e\u5165\u3067\u304d\u308b\u3002\u3053\u308c\u3092**\u4e8b\u524d\u5206\u5e03\uff08prior distribution\uff09**\u3068\u547c\u3073\u3001\u3053\u3053\u306b\u300c\u6c42\u3081\u305f\u3044\u30d1\u30e9\u30e1\u30fc\u30bf\u306b\u5bfe\u3059\u308b\u4e8b\u524d\u77e5\u8b58\u300d\u3092\u53cd\u6620\u3055\u305b\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\u3053\u3053\u3067\u3001 $\\Theta = \\theta$ \u3068\u306a\u308b\u78ba\u7387 $p(\\Theta = \\theta)$\uff08\u4ee5\u964d\u306f $p(\\theta)$ \u3068\u7565\u8a18\uff09\u3092\u30c7\u30fc\u30bf\u306e\u78ba\u7387\u30e2\u30c7\u30eb $f(x; \\theta)$ \u3068\u306f\u5225\u306e\u78ba\u7387\u30e2\u30c7\u30eb $g(\\theta; \\beta)$ \u3067\u8868\u305b\u3070\u3001 $\\beta$ \u3092\u4eba\u70ba\u7684\u306b\u4e0e\u3048\u308b\u304b\u3001\u306a\u3093\u3089\u304b\u306e\u65b9\u6cd5\u3067\u6c7a\u5b9a\u3057\u3066\u304a\u304f\u3053\u3068\u3067\u3001\u300c\u3069\u306e\u3088\u3046\u306a $\\theta$ \u304c\u8d77\u3053\u308a\u3084\u3059\u3044\u304b\u300d\u3068\u8a00\u3046\u4e8b\u524d\u77e5\u8b58\u3092\u8868\u73fe\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\nMAP \u63a8\u5b9a\u3067\u306f\u3001\u89b3\u6e2c\u30c7\u30fc\u30bf $x_i \\ (i=1,\\dots,N)$ \u304c\u89b3\u6e2c\u3055\u308c\u305f\u3068\u8a00\u3046**\u6761\u4ef6\u306e\u4e0b\u3067**\u6700\u3082\u78ba\u7387\u304c\u5927\u304d\u304f\u306a\u308b $\\theta$ \u3092\u6c42\u3081\u307e\u3059\u3002\u3059\u306a\u308f\u3061\u3001 $p(\\theta | x_1, \\dots, x_N)$ \u3092\u6700\u5927\u3068\u3059\u308b $\\theta$ \u3092\u6c42\u3081\u307e\u3059\u3002\u3053\u308c\u306f\u300c $x_i \\ (i=1,\\dots,N)$ \u304c\u89b3\u6e2c\u3055\u308c\u305f\u300d\u3068\u8a00\u3046**\u7d50\u679c**\u306e\u3082\u3068\u3067\u300c\u30c7\u30fc\u30bf\u306e\u78ba\u7387\u5206\u5e03\u3092\u8868\u3059\u30e2\u30c7\u30eb\u306e\u30d1\u30e9\u30e1\u30fc\u30bf\u304c $\\theta$ \u3067\u3042\u3063\u305f\u3053\u3068\u304c**\u539f\u56e0**\u3067\u3042\u308b\u300d\u78ba\u7387\u3092\u610f\u5473\u3059\u308b\u306e\u3067\u3001**\u4e8b\u5f8c\u78ba\u7387**\u3067\u3042\u308b\u3002\u30d9\u30a4\u30ba\u306e\u5b9a\u7406\u304b\u3089\u3001\u4e8b\u5f8c\u78ba\u7387\u306f\n\n$$\np(\\theta | x_1,\\dots,x_N) = \\frac{p(x_1,\\dots,x_N | \\theta) p(\\theta)}{p(x_1,\\dots,x_N)}\n$$\n\n\u3068\u66f8\u3051\u307e\u3057\u305f\u3002\u53f3\u8fba\u306b\u7740\u76ee\u3059\u308b\u3002\u5206\u5b50\u306b\u3042\u308b $p(x_1,\\dots,x_N | \\theta)$ \u3092\u3001\u78ba\u7387\u30e2\u30c7\u30eb $f(x; \\theta)$ \u3092\u7528\u3044\u3066 $\\prod_{i=1}^N f(x_i; \\theta)$ \u3068\u8868\u3059\u3068\u3001\u3053\u308c\u306f\u89b3\u6e2c\u30c7\u30fc\u30bf $x_i \\ (i=1,\\dots,N)$ \u306e\u4e0b\u3067\u306e\u78ba\u7387\u30e2\u30c7\u30eb $f(x; \\theta)$ \u306e**\u5c24\u5ea6**\u3067\u3042\u308b\u3002\u307e\u305f\u3001\u305d\u306e\u53f3\u306e $p(\\theta)$ \u306f\u3001\u30d1\u30e9\u30e1\u30fc\u30bf\u304c $\\theta$ \u3068\u8a00\u3046\u5024\u306b\u306a\u308b**\u4e8b\u524d\u78ba\u7387**\u3067\u3057\u305f\u3002\u3053\u308c\u304c $g(\\theta; \\beta)$ \u3068\u8a00\u3046\u78ba\u7387\u30e2\u30c7\u30eb\u3067\u8868\u3055\u308c\u308b\u3068\u3059\u308b\u3002\n\n\u4eca\u3001\u4e8b\u5f8c\u78ba\u7387\u3092\u6700\u5927\u306b\u3059\u308b\u30d1\u30e9\u30e1\u30fc\u30bf $\\theta$ \u3092\u6c42\u3081\u308b\u305f\u3081\u306b\u3001\u53f3\u8fba\u3092\u6700\u5927\u5316\u3059\u308b $\\theta$ \u3092\u8003\u3048\u307e\u3059\u3002\u3053\u306e\u3068\u304d\u3001\u30d1\u30e9\u30e1\u30fc\u30bf\u3068\u7121\u95a2\u4fc2\u306b\u6c7a\u307e\u308b $p(x_1,\\dots,x_N)$ \u3092\u7121\u8996\u3057\n\n$$\np(x_1,\\dots,x_N | \\theta) p(\\theta)\n$$\n\n\u3060\u3051\u306b\u6ce8\u76ee\u3057\u3066\u3053\u308c\u3092\u6700\u5927\u5316\u3059\u308b\u3088\u3046\u306b\u30d1\u30e9\u30e1\u30fc\u30bf $\\theta$ \u3092\u6c7a\u5b9a\u3059\u308b\u3068\u3001\u305d\u306e $\\theta$ \u306f\u6c42\u3081\u305f\u3044\u5de6\u8fba\u306e\u4e8b\u5f8c\u78ba\u7387\u3092\u6700\u5927\u306b\u3059\u308b $\\theta$ \u306b\u4e00\u81f4\u3059\u308b\u3002\u4e0a\u5f0f\u306f\u3001\u5c24\u5ea6\u3068\u4e8b\u524d\u5206\u5e03\u306e\u7a4d\u306b\u306a\u3063\u3066\u3044\u308b\u3002\u3053\u306e\u3053\u3068\u304b\u3089\u3001**\u4e8b\u5f8c\u5206\u5e03\u306f\u5c24\u5ea6\u3068\u4e8b\u524d\u5206\u5e03\u306e\u7a4d\u306b\u6bd4\u4f8b\u3059\u308b**\u3068\u8a00\u3046\u3053\u3068\u304c\u5206\u304b\u308b\u3002\n\n### \u4f8b\uff1a\u30b3\u30a4\u30f3\u30c8\u30b9\u3067\u306e\u30d1\u30e9\u30e1\u30fc\u30bf\u63a8\u5b9a\n\n\u524d\u7bc0\u306e\u6700\u5c24\u63a8\u5b9a\u3067\u7528\u3044\u305f\u30b3\u30a4\u30f3\u30c8\u30b9\u306e\u4f8b\u3092\u518d\u3073\u8003\u3048\u307e\u3059\u3002\n\u4eca\u5ea6\u306f MAP \u63a8\u5b9a\u3092\u7528\u3044\u3066\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u63a8\u5b9a\u3057\u3066\u307f\u308b\u3002\u7528\u3044\u308b\u30c7\u30fc\u30bf\u306f\u5148\u7a0b\u3068\u540c\u69d8\u306e $10$ \u56de\u306e\u30b3\u30a4\u30f3\u30c8\u30b9\u7d50\u679c\u3067\u3042\u308b\u3002\n\u307e\u305f\u3001\u78ba\u7387\u30e2\u30c7\u30eb $f(x; \\theta)$ \u3082\u540c\u69d8\u306b\u6700\u5c24\u63a8\u5b9a\u306e\u5834\u5408\u3068\u540c\u69d8\u306e\u3082\u306e\u3092\u7528\u3044\u308b\u3002\nMAP \u63a8\u5b9a\u3067\u306f\u78ba\u7387\u30e2\u30c7\u30eb $f(x;\\theta)$ \u306e\u4ed6\u306b\u3001\u4e8b\u524d\u5206\u5e03 $p(\\theta)$ \u3092\u8a2d\u8a08\u3059\u308b\u5fc5\u8981\u304c\u3042\u308b\u3002\n$p(\\theta)$ \u306e\u6c7a\u3081\u65b9\u306f\u63a8\u5b9a\u3092\u884c\u3046\u4eba\u304c\u3069\u306e\u3088\u3046\u306a\u4e8b\u524d\u77e5\u8b58\uff08\u3082\u3057\u304f\u306f\u4fe1\u5ff5\uff09\u3092\u6301\u3063\u3066\u3044\u308b\u304b\u306b\u3088\u3063\u3066\u81ea\u7531\u306b\u9078\u629e\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u304c\u3001\u3053\u3053\u3067\u306f\u4e8b\u524d\u5206\u5e03\u3092\n\n$$\np(\\theta) = 12\\theta (1-\\theta)^2\n$$\n\n\u3068\u8a2d\u5b9a\u3059\u308b\uff08[\u6ce8\u91c87](#note7)\uff09\u3002 \u30b0\u30e9\u30d5\u3092\u66f8\u304f\u3068 $p(\\theta)$ \u306f $\\theta = 1/3$ \u3067\u6700\u5927\u5024\u3092\u3068\u308b\u3053\u3068\u304c\u308f\u304b\u308b\u3002\u3053\u308c\u306f\u300c\u30b3\u30a4\u30f3\u30c8\u30b9\u304c\u884c\u308f\u308c\u308b\u524d\u306b\u306f\u3001\u5b9f\u9a13\u8005\u306f $\\theta=1/3$ \u304c\u6700\u3082\u3042\u308a\u5f97\u308b\u53ef\u80fd\u6027\u3067\u3042\u308b\u300d\u3059\u306a\u308f\u3061\u3001\u300c\u3053\u306e\u30b3\u30a4\u30f3\u306f\u8868\u3088\u308a\u3082\u88cf\u306e\u65b9\u304c\u51fa\u3084\u3059\u3044\u300d\u3068\u4fe1\u3058\u3066\u3044\u308b\uff08\u4e8b\u524d\u77e5\u8b58\u3092\u6301\u3063\u3066\u3044\u308b\uff09\u3068\u89e3\u91c8\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\u4e8b\u5f8c\u5206\u5e03\u306f $\\theta$ \u306e\u95a2\u6570\u3068\u3057\u3066 $p(x_1, \\ldots, x_N | \\theta) p(\\theta)$ \u306b\u6bd4\u4f8b\u3059\u308b\u306e\u3067\u3057\u305f\u3002\n\u3053\u308c\u3092\u5177\u4f53\u7684\u306b\u8a08\u7b97\u3059\u308b\u3068\n\n$$\np(x_1, \\ldots, x_N | \\theta) p(\\theta) = \\theta^5 (1-\\theta)^5 \\times 12 \\theta (1-\\theta)^2 = 12 \\theta^6 (1-\\theta)^7\n$$\n\n\u3068\u306a\u308b\u3002\u3053\u308c\u3092 $\\theta$ \u306e\u95a2\u6570\u3068\u3057\u3066\u6700\u5927\u5316\u3059\u308b\u3002\n\u6700\u5c24\u63a8\u5b9a\u306e\u6642\u3068\u540c\u69d8\u306b\u3001\u3053\u306e\u5024\u305d\u306e\u3082\u306e\u3067\u306f\u306a\u304f\u3001\u5bfe\u6570\u3092\u53d6\u3063\u305f\u5024\u3092\u6700\u5927\u3068\u3059\u308b $\\theta$ \u3092\u6c42\u3081\u307e\u3059\u3002\n\n$$\n\\log p(x_1, \\ldots, x_N | \\theta) p(\\theta) = 6\\log \\theta + 7 \\log (1-\\theta) + const.\n$$\n\n\u3053\u3053\u3067\uff0c $const.$ \u306f $\\theta$ \u306b\u4f9d\u5b58\u3057\u306a\u3044\u5b9a\u6570\uff08\u5177\u4f53\u7684\u306b\u306f $\\log 12$ \uff09\u3067\u3001\u5024\u3092\u6700\u5927\u306b\u3059\u308b $\\theta$ \u3092\u6c7a\u5b9a\u3059\u308b\u306e\u306b\u5f71\u97ff\u3092\u53ca\u307c\u3057\u306a\u3044\u3002\n\u3053\u308c\u3092 $\\theta$ \u3067\u5fae\u5206\u3057\u305f\u3082\u306e\u304c $0$ \u306b\u7b49\u3057\u3044\u3068\u8a00\u3046\u65b9\u7a0b\u5f0f\u3092\u7acb\u3066\u308b\u3068\u3001\n\n$$\n\\begin{align}\n\\frac{6}{\\theta} - \\frac{7}{1-\\theta} = 0 \\\\\n\\therefore \\theta = \\frac{6}{13}\n\\end{align}\n$$\n\n\u3068\u89e3\u304f\u3053\u3068\u304c\u3067\u304d\u308b\uff0e\u3053\u308c\u304c MAP \u63a8\u5b9a\u3067\u5f97\u3089\u308c\u305f\u63a8\u5b9a\u5024\u3067\u3042\u308b\u3002\n\n\u6700\u5c24\u63a8\u5b9a\u3067\u5f97\u3089\u308c\u305f\u63a8\u5b9a\u5024\u306f $\\theta = 1/2$ \u3060\u3063\u305f\u306e\u3067\u3001MAP \u63a8\u5b9a\u306f\u6700\u5c24\u63a8\u5b9a\u3088\u308a\u3082\u4f4e\u3081\u306b $\\theta$ \u3092\u63a8\u5b9a\u3057\u3066\u3044\u308b\u3053\u3068\u304c\u308f\u304b\u308b\u3002\n\u3053\u308c\u306f\u4e8b\u524d\u5206\u5e03 $p(\\theta)$ \u306b\u3088\u308a $\\theta$ \u306f $1/2$ \u3088\u308a\u5c0f\u3055\u3044\u5024\u304c\u51fa\u3084\u3059\u3044\u3068\u8a00\u3046\u4e8b\u524d\u77e5\u8b58\u3092\u5165\u308c\u3066\u3044\u305f\u3053\u3068\u3092\u53cd\u6620\u3057\u3066\u3044\u308b\u3002\u9006\u306b\u4e8b\u524d\u5206\u5e03\u3067\u5927\u304d\u3044 $\\theta$ \u304c\u51fa\u3084\u3059\u3044\u3068\u8a00\u3046\u4e8b\u524d\u77e5\u8b58\u3092\u5165\u308c\u308c\u3070\u3001MAP \u63a8\u5b9a\u306e\u5024\u3092\u6700\u5c24\u63a8\u5b9a\u3088\u308a\u3082\u5927\u304d\u304f\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n\u3053\u306e\u4f8b\u304b\u3089\u3082\u5206\u304b\u308b\u901a\u308a\u3001MAP \u63a8\u5b9a\u306f\u4e8b\u524d\u5206\u5e03\u306e\u8a2d\u5b9a\u306b\u3088\u308a\u5f97\u3089\u308c\u308b\u63a8\u5b9a\u5024\u304c\u5909\u5316\u3059\u308b\u3002\n\u3053\u306e\u4e8b\u306f\u3001MAP \u63a8\u5b9a\u306e\u65b9\u304c\u4e8b\u524d\u77e5\u8b58\u306b\u3088\u308a\u67d4\u8edf\u306a\u30e2\u30c7\u30ea\u30f3\u30b0\u304c\u3067\u304d\u308b\u534a\u9762\u3001\u8aa4\u3063\u305f\u4e8b\u524d\u77e5\u8b58\u306b\u57fa\u3065\u3044\u3066\u4e8b\u524d\u5206\u5e03\u3092\u8a2d\u8a08\u3059\u308b\u3068\u3001\u63a8\u5b9a\u5024\u304c\u5b9f\u969b\u306e\u30c7\u30fc\u30bf\u3068\u4e56\u96e2\u3059\u308b\u53ef\u80fd\u6027\u3092\u6301\u3064\u3053\u3068\u3092\u610f\u5473\u3059\u308b\u3002\n\n## \u7d71\u8a08\u91cf\n\n\u672c\u7bc0\u3067\u306f\u3001\u3044\u304f\u3064\u304b\u3088\u304f\u7528\u3044\u3089\u308c\u308b\u7d71\u8a08\u91cf\u3092\u8aac\u660e\u3059\u308b\u3002\u7d71\u8a08\u91cf\u3068\u306f\u3001**\u89b3\u6e2c\u3055\u308c\u305f\u30c7\u30fc\u30bf\u306e\u7279\u5fb4\u3092\u8981\u7d04\u3059\u308b\u6570\u5024**\u306e\u3053\u3068\u3092\u6307\u3059\u3002\u4ee3\u8868\u7684\u306a\u7d71\u8a08\u91cf\u3068\u3057\u3066\u5e73\u5747\u3001\u5206\u6563\u3001\u6a19\u6e96\u504f\u5dee\u3092\u7d39\u4ecb\u3059\u308b\u3002\n\n### \u5e73\u5747\n\n**\u5e73\u5747 (mean)** \u306f\u3001\u89b3\u6e2c\u3055\u308c\u305f\u6570\u5024\u3092\u5408\u8a08\u3057\u3001\u305d\u306e\u6570\u5024\u306e\u500b\u6570\u3067\u5272\u3063\u305f\u3082\u306e\u306e\u3053\u3068\u3092\u8a00\u3046\u3002\u305f\u3068\u3048\u3070\u3001300 \u5186\u3001400 \u5186\u3001500 \u5186\u306e\u5e73\u5747\u306f\u3001\n\n$$\n\\frac{300 + 400 + 500}{3} = 400\n$$\n\n\u3067\u3042\u308b\u3002\u4e00\u822c\u306b\u3001 $N$ \u500b\u306e\u30c7\u30fc\u30bf $x_i \\ (i=1,\\dots,N)$ \u304c\u89b3\u6e2c\u3055\u308c\u305f\u3068\u304d\u3001\u305d\u306e\u5e73\u5747\u306f\n\n$$\n\\begin{aligned}\n\\overline{x}\n= \\frac{x_1 + x_2 + \\dots + x_N}{N}\n= \\frac{1}{N} \\sum^{N}_{n=1} x_{n}\n\\end{aligned}\n$$\n\n\u3068\u5b9a\u7fa9\u3055\u308c\u307e\u3059\u3002\n\u5e73\u5747\u3092\u8868\u3059\u8a18\u53f7\u3068\u3057\u3066\u3001 $\\bar{x}$ \u3084 $\\mu$ \u304c\u3088\u304f\u7528\u3044\u3089\u308c\u307e\u3059\u3002\n\u30c7\u30fc\u30bf\u306e\u5206\u5e03\u306b\u304a\u3044\u3066\u3001\u5e73\u5747\u306f\u305d\u306e\u91cd\u5fc3\u306b\u76f8\u5f53\u3059\u308b\u5024\u3067\u3042\u308b\u3002\n\n### \u5206\u6563\n\n\u6b21\u306b\u3001**\u5206\u6563 (variance)** \u3092\u7d39\u4ecb\u3059\u308b\u3002\u5206\u6563\u306f\u3088\u304f $\\sigma^2$ \u3068\u8868\u3055\u308c\u3001\n\n$$\n\\sigma^2 = \\frac{1}{N} \\sum_{n=1}^N \\left( x_n - \\overline{x} \\right)^2\n$$\n\n\u3068\u5b9a\u7fa9\u3055\u308c\u307e\u3059\u3002\u5404\u30c7\u30fc\u30bf\u70b9 $x_i \\ (i=1,\\dots,N)$ \u306e\u5024\u304b\u3089\u3001\u305d\u308c\u3089\u306e\u5e73\u5747 $\\bar{x}$ \u3092\u5f15\u304d\u4e8c\u4e57\u3057\u305f\u5024\uff08 $(x_i - \\bar{x})^2 \\ (i=1,\\dots,N)$ \uff09\u306e\u5e73\u5747\u3092\u8a08\u7b97\u3057\u3066\u3044\u308b\u3002\u3053\u308c\u306f\u3001\u300c\u30c7\u30fc\u30bf\u304c\u81ea\u3089\u306e\u5e73\u5747\u3088\u308a\u5e73\u5747\u7684\u306b\u3069\u306e\u304f\u3089\u3044\u3070\u3089\u3064\u3044\u3066\u3044\u308b\u304b\u300d\u3092\u8868\u3059\u3002\u5e73\u5747\u304c\u540c\u3058\u30c7\u30fc\u30bf\u3067\u3082\u3001\u5168\u3066\u306e\u30c7\u30fc\u30bf\u304c\u5e73\u5747\u4ed8\u8fd1\u306b\u3042\u308b\u5834\u5408\u306f\u5206\u6563\u306f\u5c0f\u3055\u304f\u3001\u5e73\u5747\u3088\u308a\u3082\u6975\u3081\u3066\u5927\u304d\u306a\u30c7\u30fc\u30bf\u70b9\u3084\u5c0f\u3055\u306a\u30c7\u30fc\u30bf\u70b9\u304c\u591a\u6570\u3042\u308b\u5834\u5408\u3001\u5206\u6563\u306f\u5927\u304d\u304f\u306a\u308b\u3002\u5206\u6563\u306b\u306f\u3082\u3046\u4e00\u7a2e\u985e\u3042\u308b\u3002\u4ee5\u4e0b\u306e\u3088\u3046\u306a\u3082\u306e\u3067\u3042\u308b\u3002\n\n$$\n\\begin{aligned}\ns^2 = \\frac{1}{N - 1} \\sum_{n=1}^N \\left( x_n - \\overline{x} \\right)^2\n\\end{aligned}\n$$\n\n\u59cb\u3081\u306b\u767b\u5834\u3057\u305f $\\sigma^2$ \u306e\u5b9a\u7fa9\u3067\u306f $\\frac{1}{N}$ \u3068\u306a\u3063\u3066\u3044\u305f\u90e8\u5206\u304c $\\frac{1}{N - 1}$ \u306b\u5909\u308f\u3063\u3066\u3044\u308b\u3002\n\u524d\u8005\u306f**\u6a19\u672c\u5206\u6563 (sample variance)** \u3068\u3044\u3044\u3001\u5f8c\u8005\u306f**\u4e0d\u504f\u5206\u6563 (unbiased variance)** \u3068\u8a00\u3046\u3002\n\u3053\u308c\u3089\u306e\u5f0f\u306e\u5c0e\u51fa\u306f\u4ed6\u306e\u6587\u732e\u306b\u8b72\u308b\u3068\u3057\u3066\u3001\u3053\u3053\u3067\u306f\u305d\u306e\u4f7f\u3044\u5206\u3051\u306b\u3064\u3044\u3066\u8aac\u660e\u3059\u308b\u3002\n\n**\u56f3\u8868**\n\n\n\n\n\u4f8b\u3048\u3070\u3001\u5168\u56fd\u306e\u5c0f\u5b66\u751f\u306e\u8eab\u9577\u3068\u4f53\u91cd\u306e\u5206\u6563\u3092\u8abf\u3079\u305f\u3044\u3068\u3059\u308b\u3002\u3053\u306e\u3068\u304d\u3001\u5168\u56fd\u306e\u5c0f\u5b66\u751f\u3092\u4e00\u4eba\u306e\u629c\u3051\u6f0f\u308c\u3082\u306a\u304f\u8abf\u3079\u305f\u306a\u3089\u3001\u96c6\u307e\u3063\u305f\u30c7\u30fc\u30bf\u306f**\u6bcd\u96c6\u56e3 (population)** \u3068\u547c\u3070\u308c\u307e\u3059\u3002\n\u4e00\u65b9\u3001\u5404\u90fd\u9053\u5e9c\u770c\u306e\u5c0f\u5b66\u751f\u3092100\u4eba\u305a\u3064\u8abf\u3079\u305f\u5834\u5408\u3001\u305d\u306e\u30c7\u30fc\u30bf\u306f**\u6a19\u672c\u96c6\u56e3 (sample population)** \u3068\u8a00\u3046\u3002\n\u3059\u306a\u308f\u3061\u3001\u6bcd\u96c6\u56e3\u3068\u306f\u89e3\u6790\u3092\u884c\u3044\u305f\u3044\u30c7\u30fc\u30bf\u5168\u3066\u306e\u96c6\u5408\u3092\u6307\u3057\u3001\u6a19\u672c\u96c6\u56e3\u3068\u306f\u6bcd\u96c6\u56e3\u304b\u3089\u62bd\u51fa\u3055\u308c\u305f\u4e00\u90e8\u306e\u30c7\u30fc\u30bf\u306e\u96c6\u5408\u3092\u6307\u3059\u3002\u4e00\u822c\u306b\u3001\u6a19\u672c\u96c6\u56e3\u306e\u30c7\u30fc\u30bf\u6570\u304c\u5c11\u306a\u3044\u3068\u304d\u3001\u6a19\u672c\u5206\u6563\u306f\u6bcd\u96c6\u56e3\u306e\u5206\u6563\u3088\u308a\u3082\u5c0f\u3055\u304f\u306a\u308b\u3053\u3068\u304c\u77e5\u3089\u308c\u3066\u3044\u308b\u3002\u4e0d\u504f\u5206\u6563\u306f\u3001\u305d\u306e\u5dee\u3092\u88dc\u6b63\u3059\u308b\u3053\u3068\u3067\u3001\u6bcd\u96c6\u56e3\u306e\u5206\u6563\u3092\u3088\u308a\u6b63\u78ba\u306b\u63a8\u5b9a\u3059\u308b\u305f\u3081\u306b\u7528\u3044\u308b\u3002\u4e0d\u504f\u5206\u6563\u306f\u62bd\u51fa\u3059\u30c7\u30fc\u30bf\u306e\u6570\uff08$N$\uff09\u3092\u5897\u3084\u305b\u3070\u3001\u3044\u305a\u308c\u6bcd\u96c6\u56e3\u306e\u5206\u6563\u306b\u4e00\u81f4\u3059\u308b\u3002\u307e\u305f\u3001$N$ \u304c\u5927\u304d\u3044\u3068\u6a19\u672c\u5206\u6563\u3068\u4e0d\u504f\u5206\u6563\u306f\u307b\u307c\u4e00\u81f4\u3059\u308b\u306e\u3067\u3001\u305f\u304f\u3055\u3093\u306e\u30c7\u30fc\u30bf\u6570\u3092\u3068\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u72b6\u6cc1\u3067\u306f\u3001\u4e21\u8005\u306b\u5927\u304d\u306a\u9055\u3044\u304c\u751f\u3058\u306a\u3044\u3053\u3068\u3082\u591a\u3005\u3042\u308b\u3002\n\n\u5206\u6563\u3092\u5229\u7528\u3059\u308b\u3068\u3001\u30c7\u30fc\u30bf\u306e\u3070\u3089\u3064\u304d\u3092\u5b9a\u91cf\u8a55\u4fa1\u3059\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3088\u3046\u306b\u306a\u308b\u3002\u4f8b\u3048\u3070\u3001\u540c\u3058\u73fe\u8c61\u3092\u8907\u6570\u56de\u89b3\u6e2c\u3059\u308b\u5b9f\u9a13\u3092\u884c\u3063\u305f\u969b\u3001\u7d50\u679c\u306e\u3070\u3089\u3064\u304d\u304c\u5927\u304d\u3051\u308c\u3070\u3001\u305d\u306e\u89b3\u6e2c\u65b9\u6cd5\u306b\u306f\u554f\u984c\u304c\u3042\u308b\u53ef\u80fd\u6027\u304c\u3042\u308b\u3002\u3082\u3057\u304f\u306f\u3001\u540c\u3058\u3060\u3068\u601d\u3063\u3066\u3044\u305f\u73fe\u8c61\u306f\u3001\u5b9f\u306f\u89b3\u6e2c\u306e\u305f\u3073\u306b\u7570\u306a\u308b\u73fe\u8c61\u3067\u3042\u3063\u305f\u53ef\u80fd\u6027\u304c\u3042\u308b\u3002\u3053\u306e\u3088\u3046\u306b\u3001\u591a\u6570\u306e\u8a66\u884c\u306e\u7d50\u679c\u304c\u3042\u308b\u5024\u306b\u96c6\u307e\u3063\u3066\u3044\u308b\u3053\u3068\u304c\u671b\u307e\u3057\u3044\u3088\u3046\u306a\u72b6\u6cc1\u306b\u304a\u3044\u3066\u3001\u3070\u3089\u3064\u304d\u306e\u5ea6\u5408\u3044\u3092\u5b9a\u91cf\u3057\u8a55\u4fa1\u3059\u308b\u3053\u3068\u306f\u91cd\u8981\u3067\u3042\u308b\u3002\n\n### \u6a19\u6e96\u504f\u5dee\n\n\u6b21\u306b**\u6a19\u6e96\u504f\u5dee (standard deviation)** \u3092\u7d39\u4ecb\u3059\u308b\u3002\n\u5206\u6563\u306f\u30c7\u30fc\u30bf\u306e\u5e73\u5747\u304b\u3089\u306e\u5dee\u306e**\u4e8c\u4e57**\u306e\u5e73\u5747\u3067\u3057\u305f\u3002\u305d\u306e\u305f\u3081\u5358\u4f4d\u306f\u5143\u306e\u5358\u4f4d\u3092\u4e8c\u4e57\u3057\u305f\u3082\u306e\u306b\u306a\u308b\u3002\u4f8b\u3048\u3070\u30c7\u30fc\u30bf\u306e\u5358\u4f4d\u304c ${\\rm kg}$ \u3067\u3042\u308c\u3070\u3001\u5206\u6563\u306e\u5358\u4f4d\u306f ${\\rm kg}^2$ \u306b\u306a\u308b\u3002\u305d\u3053\u3067\u3001\u5206\u6563 $\\sigma^2$ \u306e\u5e73\u65b9\u6839 $\\sigma$ \u3092\u8a08\u7b97\u3059\u308b\u3053\u3068\u3067\u3001\u30c7\u30fc\u30bf\u3068\u5358\u4f4d\u304c\u7b49\u3057\u304f\u306a\u308a\u3001\u89e3\u91c8\u304c\u5bb9\u6613\u306b\u306a\u308b\u3002\u3053\u306e $\\sigma$ \u3092\u6a19\u6e96\u504f\u5dee\u3068\u547c\u3076\u3002\n\n\u7df4\u7fd2\u554f\u984c\u3067\u5177\u4f53\u7684\u306a\u8a08\u7b97\u624b\u9806\u306e\u78ba\u8a8d\u3092\u884c\u3046\u3002\u4ee5\u4e0b\u306e\u2460\u3068\u2461\u306e\u30c7\u30fc\u30bf\u306b\u5bfe\u3057\u3066\u3001\u5e73\u5747\u3001\u5206\u6563\u3001\u6a19\u6e96\u504f\u5dee\u3092\u6c42\u3081\u308b\u3002\u305f\u3060\u3057\u3001\u4eca\u56de\u306f\u6a19\u672c\u5206\u6563\u3092\u4f7f\u7528\u3059\u308b\u3053\u3068\u3068\u3059\u308b\u3002\n\n**\u56f3\u8868**\n\n\n\n\n\u2460\u306e\u89e3\u7b54\u306f\u4ee5\u4e0b\u306e\u901a\u308a\u3067\u3042\u308b\u3002\n\n$$\n\\begin{aligned}\n\\bar{x} &= \\frac{1}{5} \\left( -2 -1 + 0 + 1 + 2 \\right) = 0 \\\\\n\\sigma^{2} &= \\frac{1}{5} \\left\\{ \\left( -2 -0 \\right)^{2} + \\left( -1 -0 \\right)^{2} + (0 - 0)^{2} + (1 - 0)^{2} + (2 - 0)^{2} \\right \\} \\\\\n&= \\frac{1}{5} \\times 10 = 2 \\\\\n\\sigma &= \\sqrt{2}\n\\end{aligned}\n$$\n\n\u2461\u306e\u89e3\u7b54\u306f\u4ee5\u4e0b\u306e\u901a\u308a\u3067\u3042\u308b\u3002\n\n$$\n\\begin{aligned}\n\\overline{x} &= \\frac{1}{5} ( -4 -2 + 0 + 2 + 4 ) = 0 \\\\\n\\sigma^2 &= \\frac{1}{5}\n\\left\\{ (-4 -0)^2 + (-2 -0)^2 + (0 - 0)^2 + (2 - 0)^2 + (4 - 0)^2 \\right\\} \\\\\n&= \\frac{1}{5} \\times 40 = 8 \\\\\n\\sigma &= \\sqrt{8} = 2 \\sqrt{2}\n\\end{aligned}\n$$\n\n\u3053\u308c\u3088\u308a\u3001\u2461\u306e\u30b1\u30fc\u30b9\u306e\u65b9\u304c\u5206\u6563\u304c\u5927\u304d\u304f\u3001\u30c7\u30fc\u30bf\u306e\u3070\u3089\u3064\u304d\u304c\u5927\u304d\u3044\u3053\u3068\u304c\u308f\u304b\u308b\u3002\n\n### \u76f8\u95a2\u4fc2\u6570\n\n\u6700\u5f8c\u306b**\u76f8\u95a2\u4fc2\u6570 (correlation coefficient)** \u3092\u7d39\u4ecb\u3059\u308b\u3002\n\n2 \u7a2e\u985e\u306e\u30c7\u30fc\u30bf\u304c\u5f97\u3089\u308c\u3066\u3044\u308b\u72b6\u6cc1\u3067\u306f\u3001\u4e21\u8005\u306e\u95a2\u4fc2\u6027\u306e\u89e3\u6790\u304c\u3057\u3070\u3057\u3070\u91cd\u8981\u3068\u306a\u308b\u3002\n\u76f8\u95a2\u4fc2\u6570\u306f\u4e21\u8005\u306e\u95a2\u9023\u306e\u5ea6\u5408\u3044\u3092\u5b9a\u91cf\u7684\u306b\u6e2c\u308b\u306e\u306b\u7528\u3044\u308b\u3002\n\n2 \u7a2e\u985e\u306e\u30c7\u30fc\u30bf\u70b9\u304c\u30b9\u30ab\u30e9\u30fc\u5024\u3067 $N$ \u500b\u305a\u3064\u3042\u308b\u72b6\u6cc1\u3092\u8003\u3048\u307e\u3059\u3002\u305d\u308c\u305e\u308c\u3092 $x_n, y_n  \\ (n=1,\\dots,N)$ \u3068\u3057\u305f\u5834\u5408\u3001\u76f8\u95a2\u4fc2\u6570\u306e\u4e2d\u3067\u3082\u826f\u304f\u7528\u3044\u3089\u308c\u308b\u30d4\u30a2\u30bd\u30f3\u306e\u76f8\u95a2\u4fc2\u6570\u306f\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u5b9a\u7fa9\u3055\u308c\u307e\u3059\u3002\n\n$$\nr = \\frac{\\sum_{n=1}^{N} (x_{n}-\\bar{x})(y_{n}-\\bar{y}) }{\\sqrt{\\left( \\displaystyle \\sum_{n=1}^N(x_{n}-\\bar{x})^2 \\right) \\left( \\displaystyle \\sum_{n=1}^N(y_{n}-\\bar{y})^2 \\right) }}\n$$\n\n\u4e0a\u5f0f\u306e\u3088\u3046\u306b\u76f8\u95a2\u4fc2\u6570\u3092\u8868\u3059\u8a18\u53f7\u306f $r$ \u3092\u7528\u3044\u308b\u306e\u304c\u4e00\u822c\u7684\u3067\u3042\u308b\u3002\n\u76f8\u95a2\u4fc2\u6570 $r$ \u306f\u5e38\u306b $-1 \\leq r \\leq 1$ \u306b\u306a\u308a\u3001\u76f8\u95a2\u304c\u8a8d\u3081\u3089\u308c\u308b\u3068\u304d\u3001 $r$\u306e\u5024\u304c\u6b63\u306e\u5834\u5408\u306f**\u6b63\u306e\u76f8\u95a2**\u304c\u3042\u308b\u3068\u3044\u3044\u3001\u9006\u306b\u8ca0\u306e\u5024\u306e\u3068\u304d\u306f**\u8ca0\u306e\u76f8\u95a2**\u304c\u3042\u308b\u3068\u8a00\u3046\u3002\n\n2 \u7a2e\u985e\u306e\u30c7\u30fc\u30bf\u9593\u306e\u76f8\u95a2\u304c\u5f37\u3044\u307b\u3069 $r$ \u306e\u7d76\u5bfe\u5024\u306f\u5927\u304d\u304f\u306a\u308b\u3002\n\u3057\u304b\u3057\u3001\u300c$r$ \u304c\u3044\u304f\u3064\u4ee5\u4e0a\u306a\u3089\u3070\u76f8\u95a2\u304c\u3042\u308b\u3068\u601d\u3063\u3066\u554f\u984c\u306a\u3044\u300d\u3068\u8a00\u3046\u95be\u5024\u306f\u30bf\u30b9\u30af\u3054\u3068\u306b\u7570\u306a\u308a\u3001\u4f8b\u3048\u3070 $r=0.2$ \u304b\u3089\u76f8\u95a2\u3042\u308a\u3068\u5224\u65ad\u3057\u3066\u3088\u3044\u304b\u306f\u4e00\u6982\u306b\u306f\u8a00\u3048\u306a\u3044\u3002\u672c\u8cc7\u6599\u3067\u306f\u8aac\u660e\u3092\u7701\u7565\u3059\u308b\u304c\u3001\u7121\u76f8\u95a2\u691c\u5b9a\u306a\u3069\u306e\u624b\u6cd5\u3092\u5229\u7528\u3059\u308b\u3053\u3068\u3067\u5ba2\u89b3\u7684\u306a\u5224\u65ad\u3092\u884c\u3046\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n<hr />\n\n<div class=\"alert alert-info\">\n**\u6ce8\u91c8 1**\n\n\u3053\u3053\u3067\u306f\u6982\u5ff5\u306e\u8aac\u660e\u3092\u7c21\u5358\u306b\u3059\u308b\u305f\u3081\u3001\u3053\u306e\u4f8b\u306e\u3088\u3046\u306b\u96e2\u6563\u7684\u306a\u5024\u3092\u3068\u308b\u78ba\u7387\u5909\u6570\u3092\u8003\u3048\u3001\u7279\u306b\u660e\u793a\u3057\u306a\u3044\u9650\u308a\u9023\u7d9a\u5024\u306e\u78ba\u7387\u5909\u6570\u306f\u8003\u3048\u306a\u3044\u3053\u3068\u306b\u3059\u308b\u3002\n\n[\u25b2\u4e0a\u3078\u623b\u308b](#ref_note1)\n</div>\n\n<div class=\"alert alert-info\">\n**\u6ce8\u91c8 2**\n\n$x$ \u306f $1, 2, 3, 4, 5, 6$ \u306e\u3044\u305a\u308c\u304b\u3002\u3059\u306a\u308f\u3061 $x \\in \\{1, 2, 3, 4, 5, 6\\}$ \u3067\u3042\u308b\u3002\n\n[\u25b2\u4e0a\u3078\u623b\u308b](#ref_note2)\n</div>\n\n<div class=\"alert alert-info\">\n**\u6ce8\u91c8 3**\n\n$y$ \u306f 2 \u3064\u76ee\u306e\u30b3\u30a4\u30f3\u304c\u3068\u308a\u3046\u308b\u72b6\u614b\u3067\u3001\u3053\u306e\u5834\u5408\u3001\u300c\u8868\u300d\u3068\u300c\u88cf\u300d\u3068\u8a00\u3046\u5024\u306e\u3044\u305a\u308c\u304b\u3002\n\n[\u25b2\u4e0a\u3078\u623b\u308b](#ref_note3)\n</div>\n\n<div class=\"alert alert-info\">\n**\u6ce8\u91c8 4**\n\n$x$ \u306f 1 \u3064\u76ee\u306e\u30b3\u30a4\u30f3\u304c\u3068\u308a\u3046\u308b\u72b6\u614b\u3067\u3001\u3053\u306e\u5834\u5408\u3001\u300c\u8868\u300d\u3068\u300c\u88cf\u300d\u3068\u8a00\u3046\u5024\u306e\u3044\u305a\u308c\u304b\u3002\n\n[\u25b2\u4e0a\u3078\u623b\u308b](#ref_note4)\n</div>\n\n<div class=\"alert alert-info\">\n**\u6ce8\u91c8 5**\n\n\u4ee5\u964d\u3001\u3053\u306e\u3053\u3068\u3092\u300c\u30c7\u30fc\u30bf\u306e\u5206\u5e03\u3092\u63a8\u5b9a\u3059\u308b\u300d\u3068\u8a00\u3046\u3053\u3068\u304c\u3042\u308b\u3002\u307e\u305f\u3001\u89b3\u6e2c\u3055\u308c\u305f\u30c7\u30fc\u30bf\u306e\u307f\u304b\u3089\u5404\u30c7\u30fc\u30bf\u306e\u767a\u751f\u78ba\u7387\uff08\u983b\u5ea6\u3068\u3082\u6349\u3048\u3089\u308c\u308b\uff09\u3092\u6c42\u3081\u305f\u3082\u306e\u306f**\u7d4c\u9a13\u5206\u5e03\uff08empirical distribution\uff09**\u3068\u3082\u547c\u3070\u308c\u3001\u672c\u7bc0\u3067\u8aac\u660e\u3057\u3066\u3044\u308b\u306e\u306f\u6b63\u78ba\u306b\u306f\u3053\u306e\u7d4c\u9a13\u5206\u5e03\u3092\u78ba\u7387\u30e2\u30c7\u30eb\u3067\u8fd1\u4f3c\u3059\u308b\u65b9\u6cd5\u3067\u3042\u308b\u3002\n\n[\u25b2\u4e0a\u3078\u623b\u308b](#ref_note5)\n</div>\n\n<div class=\"alert alert-info\">\n**\u6ce8\u91c8 6**\n\n\u3053\u306e\u95a2\u6570\u306b\u306f\u3001\u30d9\u30eb\u30cc\u30fc\u30a4\u5206\u5e03\u3068\u8a00\u3046\u540d\u524d\u304c\u3064\u3044\u3066\u3044\u308b\u3002\n\n[\u25b2\u4e0a\u3078\u623b\u308b](#ref_note6)\n</div>\n\n<div class=\"alert alert-info\">\n**\u6ce8\u91c8 7**\n\n\u5148\u982d\u306e $12$ \u306f $p(\\theta)$ $0$ \u304b\u3089 $1$ \u307e\u3067\u7a4d\u5206\u3057\u305f\u5024\u304c $1$ \u3068\u306a\u308b\u3088\u3046\u306b\u6c7a\u3081\u3066\u3044\u308b\u3002\u3053\u308c\u306b\u3088\u308a\u3001$p(\\theta)$ \u304c $0 \\leq \\theta \\leq 1$ \u306e\u4e0a\u306e\u78ba\u7387\u5206\u5e03\u3068\u306a\u308b\u3002\n\n[\u25b2\u4e0a\u3078\u623b\u308b](#ref_note7)\n</div>\n\n\n\n# Step 1 \u306e\u6f14\u7fd2\u554f\u984c\n\n\u672c\u7ae0\u3067\u306f Step 1 \u3067\u6271\u3063\u305f\u30c6\u30fc\u30de\u306b\u3064\u3044\u3066\u6f14\u7fd2\u554f\u984c\u3092\u8a18\u3059\u308b\u3002\n\u672c\u7ae0\u306e\u6f14\u7fd2\u554f\u984c\u306b\u306f Step 1 \u3067\u6271\u3063\u305f\u77e5\u8b58\u3060\u3051\u3067\u89e3\u3051\u308b\u3082\u306e\u3082\u3042\u308c\u3070\u3001\u5916\u90e8\u306e\u8cc7\u6599\u3092\u8abf\u3079\u308b\u5fc5\u8981\u304c\u3042\u308b\u3082\u306e\u3082\u3042\u308b\u3002\n\n\n## \"2. Python \u5165\u9580\" \u306e\u6f14\u7fd2\u554f\u984c\n\n### \u554f2.1 (\u7d44\u307f\u8fbc\u307f\u95a2\u6570)\n\nPython \u306b\u306f2\u7ae0\u3067\u7d39\u4ecb\u3057\u305f\u4ee5\u5916\u306b\u3082\u6570\u591a\u304f\u306e\u7d44\u307f\u8fbc\u307f\u95a2\u6570\u304c\u5b9a\u7fa9\u3055\u308c\u3066\u3044\u308b\u3002\u7d44\u307f\u8fbc\u307f\u95a2\u6570\u3092\u9069\u5207\u306b\u4f7f\u3046\u3053\u3068\u3067\u30b3\u30fc\u30c9\u3092\u7c21\u6f54\u306b\u8a18\u305b\u307e\u3059\u3002`a=[4, 8, 3, 4, 1]` \u3068\u8a00\u3046\u30ea\u30b9\u30c8\u306b\u5bfe\u3057\u3066\u4ee5\u4e0b\u306e\u64cd\u4f5c\u3092\u884c\u3046\u7d44\u307f\u8fbc\u307f\u95a2\u6570\u3092[\u516c\u5f0f\u30c9\u30ad\u30e5\u30e1\u30f3\u30c8](https://docs.python.org/ja/3/library/functions.html)\u304b\u3089\u305d\u308c\u305e\u308c\u63a2\u3057\u3001\u9069\u7528\u3057\u3066\u4e0b\u3055\u3044\u3002\u3059\u306a\u308f\u3061\u3001\u4ee5\u4e0b\u306e\u30b3\u30fc\u30c9\u30bb\u30eb\u4e2d\u306e `FUNC` \u306e\u90e8\u5206\u3092\u9069\u5207\u306a\u7d44\u307f\u8fbc\u307f\u95a2\u6570\u306b\u7f6e\u304d\u63db\u3048\u308b\u3002\n\n- \u30ea\u30b9\u30c8 `a` \u306e\u9577\u3055\u3092\u6c42\u3081\u308b\u3002\n- \u30ea\u30b9\u30c8 `a` \u306b\u542b\u307e\u308c\u308b\u5024\u306e\u6700\u5927\u5024\u3092\u6c42\u3081\u308b\u3002\n- \u30ea\u30b9\u30c8 `a` \u306b\u542b\u307e\u308c\u308b\u5024\u306e\u6700\u5c0f\u5024\u3092\u6c42\u3081\u308b\u3002\n- \u30ea\u30b9\u30c8 `a` \u306b\u542b\u307e\u308c\u308b\u5024\u306e\u5408\u8a08\u5024\u3092\u6c42\u3081\u308b\u3002\n- \u30ea\u30b9\u30c8 `a` \u3092\u30bd\u30fc\u30c8\u3057\u3066\u3001`[1, 3, 4, 4, 8]` \u3068\u8a00\u3046\u30ea\u30b9\u30c8\u3092\u8fd4\u3059\u3002\n\n\n```python\n# \u4ee5\u4e0b\u306e FUNC \u3068\u8a00\u3046\u90e8\u5206\u3092\u7d44\u307f\u8fbc\u307f\u95a2\u6570\u306b\u7f6e\u304d\u63db\u3048\u308b\n\na = [4, 8, 3, 4, 1]\nres = FUNC(a)\nprint(res)\n```\n\n### \u554f2.2 (\u6f14\u7b97)\n\n\u4ee5\u4e0b\u306e\u6f14\u7b97\u3084\u95a2\u6570\u3092\u305d\u308c\u305e\u308c\u8a55\u4fa1\u3057\u305f\u3068\u304d\u3001\u7d50\u679c\u306e\u5024\u3068\u578b\u304c\u4f55\u306b\u306a\u308b\u304b\u4e88\u60f3\u3059\u308b\u3002\u5b9f\u969b\u306b\u30b3\u30fc\u30c9\u3092\u5b9f\u884c\u3057\u3066\u3001\u7d50\u679c\u304c\u4e88\u60f3\u3068\u5408\u3046\u304b\u78ba\u304b\u3081\u308b\u3002\u578b\u306e\u78ba\u8a8d\u306b\u306f `type()` \u95a2\u6570\u3092\u4f7f\u7528\u3059\u308b\u3002\n\n- `1.2 + 3.8`\n- `10 // 100`\n- `1 >= 0`\n- `'Hello World' == 'Hello World'`\n- `not 'Chainer' != 'Tutorial'`\n- `all([True, True, False])`  (`all` \u306e\u5b9a\u7fa9\u306f[\u516c\u5f0f\u30c9\u30ad\u30e5\u30e1\u30f3\u30c8\u3092\u53c2\u7167](https://docs.python.org/ja/3/library/functions.html#all))\n- `any([True, True, False])`  (`any` \u306e\u5b9a\u7fa9\u306f[\u516c\u5f0f\u30c9\u30ad\u30e5\u30e1\u30f3\u30c8\u3092\u53c2\u7167](https://docs.python.org/ja/3/library/functions.html#any))\n- `abs(-3)`  (`abs` \u306e\u5b9a\u7fa9\u306f[\u516c\u5f0f\u30c9\u30ad\u30e5\u30e1\u30f3\u30c8\u3092\u53c2\u7167](https://docs.python.org/ja/3/library/functions.html#abs))\n- `2 // 0`\n\n\n```python\n# \u3053\u3053\u306b\u30b3\u30fc\u30c9\u3092\u66f8\u304f\n\n```\n\n### \u554f2.3 (\u30ea\u30b9\u30c8\u306e\u57fa\u672c\u64cd\u4f5c)\n\n\u6a5f\u68b0\u5b66\u7fd2\u3067\u306f\u5927\u91cf\u306e\u30c7\u30fc\u30bf\u3092\u6271\u3046\u3053\u3068\u304c\u591a\u3044\u305f\u3081\u3001\u30ea\u30b9\u30c8\u306e\u6271\u3044\u306b\u6163\u308c\u3066\u304a\u304f\u3068\u4fbf\u5229\u306a\u3053\u3068\u304c\u591a\u3044\u3002\n`a=[4, 8, 3, 4, 1]` \u3068\u8a00\u3046\u30ea\u30b9\u30c8\u306b\u5bfe\u3057\u3066\u4ee5\u4e0b\u306e\u64cd\u4f5c\u3092\u884c\u3046\u30b3\u30fc\u30c9\u3092\u66f8\u3044\u3066\u4e0b\u3055\u3044\u3002\n\n- \u30ea\u30b9\u30c8 `a` \u306e\u5148\u982d\u306e\u8981\u7d20\u3092\u53d6\u308a\u9664\u3044\u3066\u3001`[8, 3, 4, 1]` \u3068\u306a\u308b\u3088\u3046\u306b\u3057\u3066\u4e0b\u3055\u3044\u3002\n- \u30ea\u30b9\u30c8 `a` \u306e\u672b\u5c3e\u306e\u8981\u7d20\u3092\u53d6\u308a\u9664\u3044\u3066\u3001`[4, 8, 3, 4]` \u3068\u306a\u308b\u3088\u3046\u306b\u3057\u3066\u4e0b\u3055\u3044\u3002\n- \u30ea\u30b9\u30c8 `a` \u306e\u672b\u5c3e\u306b `100` \u3068\u8a00\u3046\u5024\u3092\u8ffd\u52a0\u3057\u3066\u3001`[4, 8, 3, 4, 1, 100]` \u3068\u306a\u308b\u3088\u3046\u306b\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n\n```python\n# \u3053\u3053\u306b\u30b3\u30fc\u30c9\u3092\u66f8\u304f\n\n```\n\n### \u554f2.4 (\u30ea\u30b9\u30c8\u5185\u5305\u8868\u8a18)\n\n**\u30ea\u30b9\u30c8\u5185\u5305\u8868\u8a18**\u306f\u30ea\u30b9\u30c8\u3092\u751f\u6210\u3059\u308b\u305f\u3081\u306e\u7c21\u6f54\u306a\u624b\u6bb5\u3067\u3042\u308b\u3002\u4f8b\u3048\u3070\u3001\u5e73\u65b9\u6570\u306e\u30ea\u30b9\u30c8 `[0, 1, 4, 9, 16, ...]` \u3092\u69cb\u6210\u3057\u305f\u3044\u3068\u304d\u3001\n```python\nsquares = []\nfor x in range(10):\n    squares.append(x ** 2)\n```\n\u3068\u66f8\u304f\u4ee3\u308f\u308a\u306b\u3001\n```python\nsquares = [x ** 2 for x in range(10)]\n```\n\u3068\u66f8\u304f\u3053\u3068\u304c\u3067\u304d\u308b\u3002\u30ea\u30b9\u30c8\u5185\u5305\u8868\u8a18\u306f\u4e00\u822c\u306b `[(\u5f0f) for (\u5909\u6570) in (iterable\u30aa\u30d6\u30b8\u30a7\u30af\u30c8)]` \u3068\u8a00\u3046\u69cb\u6587\u3092\u53d6\u308b\u3002\u30ea\u30b9\u30c8\u5185\u5305\u8868\u8a18\u306e\u4e00\u822c\u7684\u306a\u8aac\u660e\u306f[\u516c\u5f0f\u30c9\u30ad\u30e5\u30e1\u30f3\u30c8](https://docs.python.org/ja/3/tutorial/datastructures.html#list-comprehensions)\u3092\u53c2\u7167\u3057\u3066\u4e0b\u3055\u3044\u3002\u30ea\u30b9\u30c8\u5185\u5305\u8868\u8a18\u3067 `in` \u306e\u5f8c\u306b\u7d9a\u304f iterable \u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u306f `range` \u3067\u3042\u308b\u5fc5\u8981\u306f\u306a\u304f\u3001\u4f8b\u3048\u3070\u30ea\u30b9\u30c8\u3092\u6307\u5b9a\u3067\u304d\u308b\u3002\n\n```python\na = [4, 8, 3, 4, 1]\nsquares = [x ** 2 for x in a]\nprint(squares)  # => [16, 64, 9, 16, 1]\n```\n\n\u4ee5\u4e0b\u306e\u554f\u3044\u306b\u7b54\u3048\u3066\u4e0b\u3055\u3044\u3002\n\n(1) `a=[4, 8, 3, 4, 1]` \u3068\u8a00\u3046\u30ea\u30b9\u30c8\u306b\u5bfe\u3057\u3001\u8981\u7d20\u304c\u5076\u6570\u306a\u3089 `0`, \u5947\u6570\u306a\u3089 `1` \u306b\u5909\u63db\u3059\u308b\u30b3\u30fc\u30c9\u3092\u30ea\u30b9\u30c8\u5185\u5305\u8868\u8a18\u3092\u7528\u3044\u3066\u66f8\u3044\u3066\u4e0b\u3055\u3044\u3002\u3053\u306e\u7d50\u679c\u3001\u3053\u306e\u30ea\u30b9\u30c8\u306f `[0, 0, 1, 0, 1]` \u306b\u5909\u63db\u3055\u308c\u308b\u3079\u304d\u3067\u3042\u308b\u3002\n\n(2) (1) \u3067\u66f8\u3044\u305f\u30b3\u30fc\u30c9\u3068\u7d44\u307f\u8fbc\u307f\u95a2\u6570\u3092\u7d44\u307f\u5408\u308f\u305b\u3066\u3001\u30ea\u30b9\u30c8 `a` \u306b\u542b\u307e\u308c\u308b\u5947\u6570\u306e\u500b\u6570\u3092\u6570\u3048\u308b\u30b3\u30fc\u30c9\u3092\u66f8\u3044\u3066\u4e0b\u3055\u3044\u3002\n\n(3) \u30ea\u30b9\u30c8\u5185\u5305\u8868\u8a18\u3067\u306f\u3001`if` \u6587\u3092\u7528\u3044\u308b\u3053\u3068\u3067\u6761\u4ef6\u3092\u6e80\u305f\u3059\u8981\u7d20\u3060\u3051\u3092\u30ea\u30b9\u30c8\u306b\u6b8b\u3059\u3053\u3068\u304c\u3067\u304d\u308b\u3002\u4f8b\u3048\u3070\n```python\nb = [x for x in range(10) if x > 5]\n```\n\u3068\u8a18\u3059\u3068\u3001`b` \u306f\u8981\u7d20\u304c `5` \u3088\u308a\u5927\u304d\u3044\u3082\u306e\u306e\u307f\u304c\u6b8b\u308a `[6, 7, 8, 9]` \u3068\u306a\u308b\u3002\n\n\u30ea\u30b9\u30c8\u5185\u5305\u8868\u8a18\u3092\u4f7f\u3063\u3066\u30ea\u30b9\u30c8 `a` \u304b\u3089\u5947\u6570\u306e\u8981\u7d20\u3060\u3051\u3092\u6b8b\u3059\u30b3\u30fc\u30c9\u3092\u66f8\u3044\u3066\u4e0b\u3055\u3044\u3002\n\n\n```python\n# \u3053\u3053\u306b\u30b3\u30fc\u30c9\u3092\u66f8\u304f\n\n```\n\n### \u554f2.5 (\u6587\u5b57\u5217)\n\nPython \u3067\u306f\u6587\u5b57\u5217\u578b\u306b\u5bfe\u3057\u3066\u4fbf\u5229\u306a\u7d44\u307f\u8fbc\u307f\u95a2\u6570\u304c\u591a\u6570\u5b9a\u7fa9\u3055\u308c\u3066\u3044\u308b([\u516c\u5f0f\u306e\u30c9\u30ad\u30e5\u30e1\u30f3\u30c8](https://docs.python.org/ja/3/library/stdtypes.html#text-sequence-type-str))\u3002\u7d44\u307f\u8fbc\u307f\u95a2\u6570\u3092\u4f7f\u3063\u3066\u4ee5\u4e0b\u306e\u51e6\u7406\u3092\u884c\u3063\u3066\u4e0b\u3055\u3044\u3002\n\n(1) [str.join()](https://docs.python.org/ja/3/library/stdtypes.html#str.join) \u3092\u4f7f\u3063\u3066\u3001`0` \u304b\u3089 `99` \u307e\u3067\u306e\u6570\u3092\u30b9\u30da\u30fc\u30b9\u533a\u5207\u308a\u3067\u4e26\u3079\u305f\u6587\u5b57\u5217 `\"0 1 2 3 4 ... 99\"` \u3092\u69cb\u6210\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n(2) [str.format()](https://docs.python.org/ja/3/library/stdtypes.html#str.format) \u3092\u4f7f\u3063\u3066 `float` \u306e\u5024 `(1.0 / 7.0)` \u306e\u5c0f\u6570\u70b9\u4ee5\u4e0b9\u6841\u307e\u3067\u3092\u8868\u793a\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n\n```python\n# \u3053\u3053\u306b\u30b3\u30fc\u30c9\u3092\u66f8\u304f\n\n```\n\n### \u554f2.6 (\u30af\u30e9\u30b9)\n\n\u30af\u30e9\u30b9\u3092\u5b9f\u88c5\u3059\u308b\u7df4\u7fd2\u3068\u3057\u3066\u3001\u30c7\u30fc\u30bf\u3092\u7ba1\u7406\u3059\u308b\u30af\u30e9\u30b9\u3092\u5b9f\u88c5\u3057\u3066\u307f\u308b\u3002\n\u6b21\u306e\u30e1\u30bd\u30c3\u30c9\u3092\u5168\u3066\u6301\u3064\u30af\u30e9\u30b9 `DataManager` \u3092\u8a18\u8ff0\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n* `__init__(self, x, y, z)`: 3\u3064\u306e\u6570 `x`, `y`, `z` \u3092\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\u3067\u53d7\u3051\u53d6\u308a\u3001\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u306e\u5c5e\u6027\u3067\u305d\u308c\u305e\u308c\u306e\u5024\u3092\u8a18\u61b6\u3059\u308b\u3002\n* `add_x(self, delta)`: `x` \u306b `delta` \u3060\u3051\u8db3\u3057\u3066\u3001\u5024\u3092\u66f4\u65b0\u3059\u308b\u3002\n* `add_y(self, delta)`: `y` \u306b `delta` \u3060\u3051\u8db3\u3057\u3066\u3001\u5024\u3092\u66f4\u65b0\u3059\u308b\u3002\n* `add_z(self, delta)`: `z` \u306b `delta` \u3060\u3051\u8db3\u3057\u3066\u3001\u5024\u3092\u66f4\u65b0\u3059\u308b\u3002\n* `sum(self)`: `x`, `y`, `z` \u306e3\u3064\u306e\u6570\u306e\u5408\u8a08\u5024\u3092\u8fd4\u3059\u3002\n\n\u3053\u306e\u30af\u30e9\u30b9\u3092\u4f7f\u3063\u3066\u4ee5\u4e0b\u306e\u3088\u3046\u306a\u30b3\u30fc\u30c9\u304c\u66f8\u3051\u308b\u3082\u306e\u3068\u3059\u308b\u3002\n\n```python\ndata_manager = DataManager(2, 3, 5)\nprint(data_manager.sum())  # => 10\ndata_manager.add_x(4)      # => data_manager.x \u306e\u5024\u304c 2 \u304b\u3089 6 \u306b\u66f4\u65b0\u3055\u308c\u308b\nprint(data_manager.sum())  # => 14\ndata_manager.add_y(0)      # => data_manager.y \u306e\u5024\u304c 3 \u304b\u3089 3 \u306b\u66f4\u65b0\u3055\u308c\u308b\nprint(data_manager.sum())  # => 14\ndata_manager.add_z(-9)     # => data_manager.z \u306e\u5024\u304c 5 \u304b\u3089 -4 \u306b\u66f4\u65b0\u3055\u308c\u308b\nprint(data_manager.sum())  # => 5\n```\n\n\n```python\n# \u3053\u3053\u306b\u30b3\u30fc\u30c9\u3092\u66f8\u304f\n\n```\n\n### \u554f2.7 (\u95a2\u6570\u547c\u3073\u51fa\u3057)\n\u4ee5\u4e0b\u3067\u5b9a\u7fa9\u3055\u308c\u308b\u95a2\u6570 `f`, `g` \u304c\u3042\u308b\u3068\u3059\u308b\u3002\n\n```python\ndef f(a):\n    a = [6, 7, 8]\n    \ndef g(a):\n    a.append(1)\n```\n\n\u3053\u308c\u3089\u306b\u5bfe\u3057\u3001\u6b21\u306e\u30b3\u30fc\u30c9\u306e\u5b9f\u884c\u7d50\u679c\u304c\u3069\u3046\u306a\u308b\u304b\u4e88\u60f3\u3057\u3066\u4e0b\u3055\u3044\u3002\u5b9f\u969b\u306b\u30b3\u30fc\u30c9\u3092\u5b9f\u884c\u3057\u3066\u4e88\u60f3\u3068\u4e00\u81f4\u3057\u3066\u3044\u308b\u304b\u78ba\u8a8d\u3057\u3001\u306a\u305c\u305d\u306e\u3088\u3046\u306a\u7d50\u679c\u306b\u306a\u3063\u305f\u306e\u304b\u8aac\u660e\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n```python\ndef somefunction():\n    a0 = [1, 2, 3]\n    f(a0)\n    print(a0)\n\n    a1 = [1, 2, 3]\n    g(a1)\n    print(a1)\n    \nsomefunction()\n```\n\n\n```python\n# \u3053\u3053\u306b\u30b3\u30fc\u30c9\u3092\u66f8\u304f\n\n```\n\n### \u554f2.8 (\u5236\u5fa1\u69cb\u6587)\n\n2\u4ee5\u4e0a\u306e\u6574\u6570 `p` \u304c\u7d20\u6570\u3067\u3042\u308b\u3068\u306f\u3001\u300c\u3069\u3093\u306a `2` \u4ee5\u4e0a `p-1` \u4ee5\u4e0b\u306e\u6574\u6570 `k` \u306b\u5bfe\u3057\u3066\u3082 `p` \u306f `k` \u3067\u5272\u308a\u5207\u308c\u306a\u3044\u300d\u304c\u6210\u308a\u7acb\u3064\u3053\u3068\u3092\u6307\u3059\u3002\u7d20\u6570\u3092\u5c0f\u3055\u3044\u9806\u304b\u3089\u5217\u6319\u3059\u308b\u3068\u3001`2`, `3`, `5`, `7`, `11`, `13`, `17`, ... \u3068\u306a\u308b\u3002\n\u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb\u3067\u5b66\u3093\u3060\u5236\u5fa1\u69cb\u6587\u3067\u3042\u308b `if` \u3084 `for` \u3092\u7528\u3044\u3066\u3001`2` \u304b\u3089 `100` \u304b\u3089\u307e\u3067\u306b\u542b\u307e\u308c\u308b\u7d20\u6570\u3092\u5217\u6319\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n\n```python\n# \u3053\u3053\u306b\u30b3\u30fc\u30c9\u3092\u66f8\u304f\n\n```\n\n## \"4. \u5fae\u5206\u306e\u57fa\u790e\" \u306e\u6f14\u7fd2\u554f\u984c\n\n\u3053\u3053\u304b\u3089\u306f\u3001\u7d19\u3068\u925b\u7b46\u3092\u7528\u610f\u3059\u308b\u3002\n\n### \u554f4.1 (\u5c0e\u95a2\u6570)\n\u5c0e\u95a2\u6570\u306e\u5b9a\u7fa9 $f'(x) = \\lim_{h \\rightarrow 0} \\frac{f(x+h)-f(x)}{h}$ \u3092\u7528\u3044\u3066\u4ee5\u4e0b\u306e\u95a2\u6570 $f_1(x), f_2(x)$ \u306e\u5c0e\u95a2\u6570 $f^{'}_1(x), f^{'}_2(x)$ \u3092\u305d\u308c\u305e\u308c\u6c42\u3081\u3066\u4e0b\u3055\u3044\u3002\n\n* $f_1(x) = x^3$.\n* $f_2(x) = \\sqrt{x}$. (\u30d2\u30f3\u30c8: \u5206\u6bcd\u3068\u5206\u5b50\u306b $(\\sqrt{x+h}+\\sqrt{x})$ \u3092\u639b\u3051\u3066\u5f0f\u3092\u6574\u7406\u3057\u3066\u307f\u3066\u4e0b\u3055\u3044)\n\n### \u554f4.2 (\u7dda\u5f62\u6027)\n\u5fae\u5206\u306e\u7dda\u5f62\u6027 $\\left( cf(x) \\right)^{'} = c f'(x)$, $\\left( f(x) + g(x) \\right)^{'} = f^{'}(x) + g^{'}(x)$ \u3092\u7528\u3044\u3066\u3001\u4ee5\u4e0b\u306e\u95a2\u6570\u306e\u5c0e\u95a2\u6570\u3092\u6c42\u3081\u3066\u4e0b\u3055\u3044\u3002\n\n* $f_1(x) = 2x^2-5x+1$\n* $f_2(x) = \\sum_{k=1}^{123} (k^2+1)x^k$\n\n### \u554f4.3 (\u7a4d\u306e\u5fae\u5206)\n\u7a4d\u306e\u5fae\u5206 $\\bigl( f(x) \\cdot g(x) \\bigr)^{'} = f^{'}(x)g(x) + f(x)g^{'}(x)$ \u3092\u4f7f\u3063\u3066\u4ee5\u4e0b\u306e\u95a2\u6570\u3092\u5fae\u5206\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n* $f_1(x) = x \\cdot x$.\n* $f_2(x) = x \\cdot x^2$.\n* $f_3(x) = x \\cdot x^3$.\n\n\u3053\u308c\u3092\u7e70\u308a\u8fd4\u3057\u3066\u3044\u304f\u3068\u3001$g(x) = x^{100}$ \u306b\u5bfe\u3057\u3066 $g^{'}(x) = 100x^{99}$ \u306a\u3069\u304c\u6210\u308a\u7acb\u3064\u3053\u3068\u3092\u78ba\u304b\u3081\u3066\u4e0b\u3055\u3044\u3002\n\n### \u554f4.4 (\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206)\n\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u5247 $\\frac{d}{dx} f(g(x)) = \\frac{df(u)}{du}\\frac{du}{dx}$ ($u=g(x)$) \u3092\u4f7f\u3063\u3066\u4ee5\u4e0b\u306e\u95a2\u6570\u3092\u5fae\u5206\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n* $f_1(x) = (x+1)^3$.\n* $f_2(x) = (4x)^3$.\n* $f_3(x) = \\exp(2x-1)$.\n* $f_4(x) = \\exp(-x^2)$.\n* $f_5(x) = 2^x$.  (\u30d2\u30f3\u30c8: $2^x = \\exp(\\log(2) x)$ \u3092\u5229\u7528\u3059\u308b)\n\n### \u554f4.5 (\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206)\n$f(x) = x^2 + 1$, $g(x) = f(f(x))$ \u3068\u3059\u308b\u3002\n\n(1) $g(x) = x^4 + 2x^2 + 2$ \u3068\u306a\u308b\u3053\u3068\u3092\u78ba\u8a8d\u3057\u3066\u4e0b\u3055\u3044\u3002\u307e\u305f\u3001\u3053\u308c\u3088\u308a $g'(x) = 4x^3 + 4x$ \u3068\u306a\u308b\u3053\u3068\u3092\u78ba\u8a8d\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n(2) \u4e00\u65b9\u3067\u3001\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u5247\u306b\u3088\u3063\u3066 $g'(x)$ \u3092\u8a08\u7b97\u3057\u3001(1) \u3067\u6c42\u3081\u305f\u5c0e\u95a2\u6570\u3068\u4e00\u81f4\u3059\u308b\u3053\u3068\u3092\u78ba\u8a8d\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n(3) $h(x) = f(f(f(x)))$ \u3068\u3059\u308b\u3002\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u306b\u3088\u3063\u3066 $h'(x)$ \u3092\u8a08\u7b97\u3057\u3066\u4e0b\u3055\u3044\u3002(\u30d2\u30f3\u30c8: $h(x)=f(g(x))$ \u3067\u3042\u308b\u3053\u3068\u3092\u5229\u7528\u3059\u308b)\n\n### \u554f4.6 (\u6307\u6570\u95a2\u6570\u30fb\u5bfe\u6570\u95a2\u6570)\n\u6307\u6570\u95a2\u6570 $\\exp(x)$ \u3068\u5bfe\u6570\u95a2\u6570 $\\log(x)$ \u306e\u5c0e\u95a2\u6570\u306f\u4ee5\u4e0b\u3067\u5b9a\u307e\u308b\u3002\n\n$$\n\\begin{align}\n\\exp^{'}(x) &= \\exp(x). \\\\\n\\log^{'}(x) &= \\frac{1}{x}. \\\\\n\\end{align}\n$$\n\n\u3053\u306e\u3053\u3068\u3092\u30d7\u30ed\u30b0\u30e9\u30e0\u3092\u7528\u3044\u305f\u5b9f\u9a13\u306b\u3088\u3063\u3066\u78ba\u8a8d\u3057\u3066\u307f\u308b\u3002\n**\u6570\u5024\u5fae\u5206**\u306f\u5c0e\u95a2\u6570\u3092\u8fd1\u4f3c\u7684\u306b\u8a08\u7b97\u3059\u308b\u624b\u6cd5\u3067\u3042\u308b\u3002\u5c0e\u95a2\u6570\u306e\u5b9a\u7fa9\n\n$$f^{'}(x) = \\lim_{h \\rightarrow 0} \\frac{f(x+h)-f(x)}{h}$$\n\n\u306b\u304a\u3044\u3066\u3001\u6975\u9650\u3092\u53d6\u308b\u4ee3\u308f\u308a\u306b\u3042\u308b\u5fae\u5c0f\u306a\u5024 $\\Delta h$ \u3092 $h$ \u306b\u4ee3\u5165\u3057\u3001\n\n$$\nf'(x) \\approx \\frac{f(x+\\Delta h)-f(x)}{\\Delta h}\n$$\n\n\u3068\u3057\u3066\u8a08\u7b97\u3059\u308b\u3053\u3068\u306b\u3088\u3063\u3066\u5c0e\u95a2\u6570\u306e\u5024\u3092\u8fd1\u4f3c\u3059\u308b\u65b9\u6cd5\u304c\u6570\u5024\u5fae\u5206\u3067\u3042\u308b\u3002\u5177\u4f53\u7684\u306a $x$ \u306e\u5024\u306b\u5bfe\u3059\u308b $\\exp(x)$ \u306e\u5fae\u5206\u3092\u6570\u5024\u5fae\u5206\u306b\u3088\u3063\u3066\u8a08\u7b97\u3059\u308b\u30b3\u30fc\u30c9\u306f\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u306a\u308b\u3002\n\n```python\nimport math  # exp \u3092\u547c\u3073\u51fa\u3059\u305f\u3081\u306b math \u30e2\u30b8\u30e5\u30fc\u30eb\u3092\u30a4\u30f3\u30dd\u30fc\u30c8\n\ndef f(x):\n    return math.exp(x)\n\ndef dfdx_approx(x):\n    dh = 0.0001\n    return (f(x + dh) - f(x)) / dh\n```\n\n(1) `x=-3,-2,-1,0,1,2,3` \u306b\u5bfe\u3057\u3066\u6570\u5024\u5fae\u5206\u306e\u95a2\u6570 `dfdx_approx` \u3092\u547c\u3073\u51fa\u3057\u3001\u305d\u306e\u7d50\u679c\u5f97\u3089\u308c\u305f\u5024\u3068\u6b63\u78ba\u306a\u5fae\u5206\u306e\u5024($\\exp^{'}(-3),\\ldots,\\exp^{'}(3)$)\u3068\u3092\u6bd4\u8f03\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n(2) \u5bfe\u6570\u95a2\u6570 $\\log(x)$ \u306b\u3064\u3044\u3066\u3082\u540c\u69d8\u306e\u5b9f\u9a13\u3092\u884c\u3044\u3001`x=0.25,0.5,1,2,4,8` \u306b\u5bfe\u3057\u3066\u6bd4\u8f03\u3057\u3066\u4e0b\u3055\u3044\u3002Python \u304b\u3089\u5bfe\u6570\u95a2\u6570\u3092\u547c\u3073\u51fa\u3059\u5834\u5408\u3001`math.log` \u3092\u4f7f\u7528\u3059\u308b\u3002\n\n\n```python\n# \u3053\u3053\u306b\u30b3\u30fc\u30c9\u3092\u66f8\u304f\n\n```\n\n### \u554f4.7 (\u30cb\u30e5\u30fc\u30e9\u30eb\u30cd\u30c3\u30c8\u30ef\u30fc\u30af\u306e\u95a2\u6570\u306e\u5fae\u5206)\n\u30cb\u30e5\u30fc\u30e9\u30eb\u30cd\u30c3\u30c8\u30ef\u30fc\u30af\u306e\u30e2\u30c7\u30eb\u3067\u3088\u304f\u6271\u308f\u308c\u308b\u95a2\u6570\u306e\u5c0e\u95a2\u6570\u3092\u8a08\u7b97\u3057\u3066\u307f\u308b\u3002\n\n* $\\mathrm{ReLU}(x) = \\max(x, 0)$.\n* $\\tanh(x) = \\frac{e^x - e^{-x}}{e^x + e^{-x}}$.  (\u6ce8\u610f: \u5546\u306e\u5fae\u5206\u5247 $\\bigl(\\frac{f(x)}{g(x)}\\bigr)^{'}=\\frac{f^{'}(x)g(x)-f(x)g^{'}(x)}{g(x)^2}$ \u3092\u7528\u3044\u308b)\n* $\\mathrm{Sigmoid}(x) = \\frac{1}{1 + e^{-x}}$.\n* $\\mathrm{Softplus}(x) = \\log(1+e^x)$.\n\n### \u554f4.8 (\u504f\u5fae\u5206)\n(1) 2\u5909\u6570\u95a2\u6570 $f(x, y) = |x| + |y|$ \u306b\u5bfe\u3057\u3066\u504f\u5fae\u5206 $\\frac{\\partial}{\\partial x}f(x,y)$, $\\frac{\\partial}{\\partial y}f(x,y)$ \u3092\u6c42\u3081\u3066\u4e0b\u3055\u3044\u3002\n\n(2) 2\u5909\u6570\u95a2\u6570 $f(x, y) = |x + y|$ \u306b\u5bfe\u3057\u3066\u504f\u5fae\u5206 $\\frac{\\partial}{\\partial x}f(x,y)$, $\\frac{\\partial}{\\partial y}f(x,y)$ \u3092\u6c42\u3081\u3066\u4e0b\u3055\u3044\u3002\n\n## \"5. \u7dda\u5f62\u4ee3\u6570\u306e\u57fa\u790e\" \u306e\u6f14\u7fd2\u554f\u984c\n\n### \u554f5.1 (\u30d7\u30ed\u30b0\u30e9\u30e0\u306b\u304a\u3051\u308b\u30d9\u30af\u30c8\u30eb\u30fb\u884c\u5217\u306e\u8a08\u7b97)\n\nPython \u30b3\u30fc\u30c9\u4e0a\u3067\u30d9\u30af\u30c8\u30eb\u3084\u884c\u5217\u306b\u95a2\u3059\u308b\u6f14\u7b97\u3092\u884c\u3046\u3053\u3068\u3092\u8003\u3048\u3066\u307f\u308b\u3002\u30d9\u30af\u30c8\u30eb\u306f `float` \u306e\u30ea\u30b9\u30c8\u3001\u884c\u5217\u306f `float` \u306e\u30ea\u30b9\u30c8\u306e\u30ea\u30b9\u30c8\u306b\u3088\u3063\u3066\u8868\u3059\u3053\u3068\u304c\u3067\u304d\u308b\u3002\u4f8b\u3048\u3070\u3001\n\n$$\n{\\bf x}=\\begin{bmatrix}\n3 \\\\\n7 \\\\\n2\n\\end{bmatrix}, \\\n{\\bf A}=\\begin{bmatrix}\n1 & 2 & 3 \\\\\n4 & 5 & 6\n\\end{bmatrix}\n$$\n\n\u3068\u8a00\u3046\u30d9\u30af\u30c8\u30eb\u3068\u884c\u5217\u306f\u305d\u308c\u305e\u308c `[3, 7, 2]` \u3068 `[[1, 2, 3], [4, 5, 6]]` \u3068 Python \u30b3\u30fc\u30c9\u4e0a\u3067\u8868\u3059\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n\n(1) 2\u3064\u306e\u30d9\u30af\u30c8\u30eb ${\\bf x}$, ${\\bf y}$ \u3092\u53d7\u3051\u53d6\u308a\u3001\u305d\u306e\u548c ${\\bf x} + {\\bf y}$ \u3092\u8fd4\u3059\u95a2\u6570\u3092\u66f8\u3044\u3066\u4e0b\u3055\u3044\u3002\u30b3\u30fc\u30c9\u306f\u4f8b\u3048\u3070\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u306a\u308b\u3002\n\n```python\ndef vector_sum(x, y):\n    # ...\n\nx = [1, 2, 3]\ny = [8, 1, 2]\nanswer = vector_sum(x, y)\nprint(answer)  # => [9, 3, 5]\n```\n\n(2) 2\u3064\u306e\u884c\u5217 ${\\bf X}$, ${\\bf Y}$ \u3092\u53d7\u3051\u53d6\u308a\u3001\u305d\u306e\u548c ${\\bf X} + {\\bf Y}$ \u3092\u8fd4\u3059\u95a2\u6570\u3092\u66f8\u3044\u3066\u4e0b\u3055\u3044\u3002\u30b3\u30fc\u30c9\u306f\u4f8b\u3048\u3070\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u306a\u308b\u3002\n\n```python\ndef matrix_sum(X, Y):\n    # ...\n\nX = [[1, 2, 3],\n     [4, 5, 6]]\nY = [[8, 1, 2],\n     [-1, 0, -2]]\nanswer = matrix_sum(X, Y)\nprint(answer)  # => [[9, 3, 5], [3, 5, 4]]\n```\n\n(3) \u884c\u5217 ${\\bf X}$ \u3068\u30d9\u30af\u30c8\u30eb ${\\bf y}$ \u3092\u53d7\u3051\u53d6\u308a\u3001\u305d\u306e\u7a4d ${\\bf X}{\\bf y}$ \u3092\u8fd4\u3059\u95a2\u6570\u3092\u66f8\u3044\u3066\u4e0b\u3055\u3044\u3002\n\n```python\ndef matrix_vector_product(X, y):\n    # ...\n\nX = [[1, 2, 3],\n     [4, 5, 6]]\ny = [8, 1, 2]\nanswer = matrix_vector_product(X, y)\nprint(answer)  # => [16, 49]\n```\n\n(4) 2\u3064\u306e\u884c\u5217 ${\\bf X}$, ${\\bf Y}$ \u3092\u53d7\u3051\u53d6\u308a\u3001\u305d\u306e\u7a4d ${\\bf X}{\\bf Y}$ \u3092\u8fd4\u3059\u95a2\u6570\u3092\u66f8\u3044\u3066\u4e0b\u3055\u3044\u3002\n\n```python\ndef matrix_product(X, Y):\n    # ...\n\nX = [[1, 2, 3],\n     [4, 5, 6]]\nY = [[8, 1],\n     [-1, 0],\n     [0, 1]]\nanswer = matrix_product(X, Y)\nprint(answer)  # => [[6, 4], [27, 10]]\n```\n\n(5) \u884c\u5217 ${\\bf X}$ \u3092\u53d7\u3051\u53d6\u308a\u3001\u305d\u306e\u8ee2\u7f6e ${\\bf X}^{\\rm T}$ \u3092\u8fd4\u3059\u95a2\u6570\u3092\u66f8\u3044\u3066\u4e0b\u3055\u3044\u3002\n\n```python\ndef matrix_transpose(X):\n    # ...\n\nX = [[1, 2, 3],\n     [4, 5, 6]]\nanswer = matrix_transpose(X)\nprint(answer)  # => [[1, 4], [2, 5], [3, 6]]\n```\n\n\n```python\n# \u3053\u3053\u306b\u30b3\u30fc\u30c9\u3092\u66f8\u304f\n\n```\n\n### \u554f5.2 (\u30d9\u30af\u30c8\u30eb\u306e\u5fae\u5206)\n${\\bf x}$ \u3092\u6b21\u5143\u6570 $n$ \u306e\u30d9\u30af\u30c8\u30eb\u3001${\\bf A}$ \u3092 $n \\times n$ \u306e\u6b63\u65b9\u884c\u5217\u3068\u3059\u308b\u3002\n\n$$\n{\\bf x}=\\begin{bmatrix}\nx_{1} \\\\\n\\vdots \\\\\nx_{n}\n\\end{bmatrix}, \\\n{\\bf A}=\\begin{bmatrix}\na_{11} & \\ldots & a_{1n} \\\\\n\\vdots &        & \\vdots \\\\\na_{n1} & \\ldots & a_{nn}\n\\end{bmatrix}\n$$\n\n\n\u4e8c\u6b21\u5f62\u5f0f\u306b\u95a2\u3059\u308b\u5fae\u5206 $\\frac{\\partial}{\\partial {\\bf x}} \\left( {\\bf x}^{\\rm T}{\\bf A}{\\bf x} \\right) = {\\bf x}^{\\rm T} \\left( {\\bf A} + {\\bf A}^{\\rm T} \\right)$ \u3092\u8a3c\u660e\u3057\u3066\u307f\u308b\u3002\n\n(1) ${\\bf x}^{\\rm T}{\\bf A}{\\bf x} = \\sum_{i=1}^n \\sum_{j=1}^n a_{ij} x_i x_j$ \u3067\u3042\u308b\u3053\u3068\u3092\u793a\u3057\u3066\u4e0b\u3055\u3044\u3002\u3055\u3089\u306b\u3001\u3053\u308c\u3088\u308a\u4ee5\u4e0b\u3092\u793a\u3057\u3066\u4e0b\u3055\u3044\u3002\n$$\n{\\bf x}^{\\rm T}{\\bf A}{\\bf x} = a_{11} x_1^2 + \\left( \\sum_{i=2}^n (a_{1i} + a_{i1}) x_i \\right) x_1 + \\sum_{i=2}^n \\sum_{j=2}^n x_i x_j a_{ij}.\n$$\n\n(2) \u504f\u5fae\u5206 $\\frac{\\partial}{\\partial x_1} \\left( {\\bf x}^{\\rm T}{\\bf A}{\\bf x} \\right)$ \u3092\u8a08\u7b97\u3057\u3001$\\sum_{i=1}^n (a_{1i} x_i + a_{i1} x_i)$ \u3068\u306a\u308b\u3053\u3068\u3092\u793a\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n(3) \u4e00\u822c\u306b\u3001$k=1,\\ldots,n$ \u306b\u5bfe\u3057\u3066 $\\frac{\\partial}{\\partial x_k} \\left( {\\bf x}^{\\rm T}{\\bf A}{\\bf x} \\right) = \\sum_{i=1}^n (a_{ki} x_i + a_{ik} x_i)$ \u3068\u306a\u308b\u3053\u3068\u3092\u793a\u3057\u3066\u4e0b\u3055\u3044\u3002\u3053\u308c\u306b\u3088\u3063\u3066 $\\frac{\\partial}{\\partial {\\bf x}} \\left( {\\bf x}^{\\rm T}{\\bf A}{\\bf x} \\right) = {\\bf x}^{\\rm T} \\left( {\\bf A} + {\\bf A}^{\\rm T} \\right)$ \u304c\u6210\u308a\u7acb\u3064\u3053\u3068\u3092\u78ba\u304b\u3081\u3066\u4e0b\u3055\u3044\u3002\n\n### \u554f5.3 (\u30d9\u30af\u30c8\u30eb\u3092\u5165\u529b\u3068\u3059\u308b\u95a2\u6570\u306e\u5fae\u5206)\n\n$f, g$ \u3092\u30d9\u30af\u30c8\u30eb\u3092\u5165\u529b\u3068\u3059\u308b\u5b9f\u6570\u5024\u95a2\u6570\u3068\u3059\u308b\u3002\n\u5fae\u5206\u306b\u3064\u3044\u3066\u4ee5\u4e0b\u306e\u6027\u8cea\u304c\u6210\u308a\u7acb\u3064\u3053\u3068\u3092\u793a\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n* $\\frac{\\partial}{\\partial {\\bf x}}(f({\\bf x}) + g({\\bf x})) = \\frac{\\partial}{\\partial {\\bf x}}f({\\bf x}) + \\frac{\\partial}{\\partial {\\bf x}}g({\\bf x})$.\n* $c$ \u3092\u4efb\u610f\u306e\u5b9f\u6570\u3068\u3059\u308b\u3068\u304d\u3001$\\frac{\\partial}{\\partial {\\bf x}}(cf({\\bf x})) = c\\frac{\\partial}{\\partial {\\bf x}}f({\\bf x})$.\n* $c$ \u3092\u4efb\u610f\u306e\u5b9f\u6570\u3001${\\bf b}$ \u3092\u4efb\u610f\u306e\u30d9\u30af\u30c8\u30eb\u3068\u3059\u308b\u3068\u304d\u3001$\\frac{\\partial}{\\partial {\\bf x}}f(c{\\bf x} + {\\bf b}) = c\\frac{\\partial}{\\partial {\\bf y}}{\\bf f}({\\bf y})$. (\u3053\u3053\u3067 ${\\bf y}=c{\\bf x}+{\\bf a}$ \u3068\u3059\u308b\u3002)\n\n### \u554f5.4 (\u30d9\u30af\u30c8\u30eb\u3092\u5165\u529b\u3068\u3059\u308b\u95a2\u6570\u306e\u5fae\u5206)\n\n${\\bf x}$ \u3092 $n$ \u6b21\u5143\u30d9\u30af\u30c8\u30eb\u3068\u3059\u308b\u3002\n\u4ee5\u4e0b\u306e\u95a2\u6570 $f$ \u306b\u5bfe\u3059\u308b\u30d9\u30af\u30c8\u30eb\u306e\u5fae\u5206 $\\frac{\\partial}{\\partial {\\bf x}}f({\\bf x})$ \u3092\u8a08\u7b97\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n* $f({\\bf x}) = \\max(x_1, x_2, \\ldots, x_n)$.\n\n* $f({\\bf x}) = \\sqrt{x_1^2 + x_2^2 + \\ldots + x_n^2}$.\n\n* $f({\\bf x}) = |x_1 + x_2 + \\ldots + x_n|$.\n\n### \u554f5.5 (\u591a\u5909\u6570\u95a2\u6570\u306e\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206)\n\n3\u6b21\u5143\u30d9\u30af\u30c8\u30eb\u306b\u5bfe\u3059\u308b\u30d9\u30af\u30c8\u30eb\u5024\u95a2\u6570 ${\\bf f}$ \u3092\u4ee5\u4e0b\u306b\u3088\u3063\u3066\u5b9a\u7fa9\u3059\u308b\u3002\n$$\n{\\bf f}(\\begin{bmatrix}\nx_{1} \\\\\nx_{2} \\\\\nx_{3}\n\\end{bmatrix}) = \\begin{bmatrix}\nx_{2}^2 \\\\\nx_{3}^2 \\\\\nx_{1}^2\n\\end{bmatrix}.\n$$\n\n(1) ${\\bf f}({\\bf x})$ \u306e\u30e4\u30b3\u30d3\u884c\u5217 $\\frac{\\partial}{\\partial {\\bf x}}{\\bf f}({\\bf x})$ \u3092\u8a08\u7b97\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n(2) ${\\bf f}({\\bf f}({\\bf x}))$ \u3092\u8a08\u7b97\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n(3) ${\\bf f}({\\bf f}({\\bf x}))$ \u306e\u30e4\u30b3\u30d3\u884c\u5217 $\\frac{\\partial}{\\partial {\\bf x}}{\\bf f}({\\bf f}({\\bf x}))$ \u3092\u3001(1) \u306e\u7d50\u679c\u3092\u7528\u3044\u3066\u8a08\u7b97\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n(4) $\\frac{\\partial}{\\partial {\\bf x}}{\\bf f}({\\bf f}({\\bf x}))$ \u3092\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u5247 $\\frac{\\partial}{\\partial {\\bf x}} {\\bf f}( {\\bf g}({\\bf x}))  = \\frac{\\partial {\\bf f}}{\\partial {\\bf u}}({\\bf u}) \\frac{\\partial {\\bf g}}{\\partial {\\bf x}}({\\bf x})$ (${\\bf u}={\\bf g}({\\bf x})$) \u306b\u3088\u3063\u3066\u8a08\u7b97\u3057\u3001\u7d50\u679c\u304c (3) \u3068\u4e00\u81f4\u3059\u308b\u3053\u3068\u3092\u78ba\u8a8d\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n### \u554f5.6 (\u591a\u5909\u6570\u95a2\u6570\u306e\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206)\n${\\bf A}$, ${\\bf B}$ \u3092 $n \\times n$ \u884c\u5217\u3068\u3059\u308b\u3002$n$ \u6b21\u5143\u30d9\u30af\u30c8\u30eb ${\\bf x}$ \u306b\u5bfe\u3057\u3066 ${\\bf f}({\\bf x})={\\bf A}{\\bf x}$, ${\\bf g}({\\bf x})={\\bf B}{\\bf x}$ \u3068\u3059\u308b\u3002\n\n\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u5247\u3092\u7528\u3044\u3066 $\\frac{\\partial}{\\partial {\\bf x}}{\\bf g}({\\bf f}({\\bf x})) = {\\bf B}{\\bf A}$ \u3092\u793a\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n### \u554f5.7 (\u591a\u5909\u6570\u95a2\u6570\u306e\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206)\n\n(1) $f(y, z) = 2y-3z$ \u3068\u3059\u308b\u3002\u3053\u306e\u3068\u304d\u30011\u5909\u6570\u95a2\u6570 $g(x)$ \u3068 $h(x)$ \u306b\u5bfe\u3057\u3066\n\n$$\n\\frac{d}{dx}f(g(x), h(x)) = 2g^{'}(x)-3h^{'}(x)\n$$\n\n\u3067\u3042\u308b\u3053\u3068\u3092\u78ba\u8a8d\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n(2) $f(y, z) = yz$ \u3068\u3059\u308b\u3002\u3053\u306e\u3068\u304d $\\frac{d}{dx}f(g(x), h(x)) = g^{'}(x)h(x) + g(x)h^{'}(x)$ \u3067\u3042\u308b\u3053\u3068\u3092\u78ba\u8a8d\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n(3) 2\u5909\u6570\u5b9f\u6570\u5024\u95a2\u6570 $f(y, z)$ \u30681\u5909\u6570\u95a2\u6570 $g(x), h(x)$ \u306b\u5bfe\u3057\u4ee5\u4e0b\u304c\u6210\u308a\u7acb\u3064\u3053\u3068\u3092\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206\u5247 $\\frac{\\partial}{\\partial {\\bf x}} {\\bf f}( {\\bf g}({\\bf x}))  = \\frac{\\partial {\\bf f}}{\\partial {\\bf u}}({\\bf u}) \\frac{\\partial {\\bf g}}{\\partial {\\bf x}}({\\bf x})$ (${\\bf u}={\\bf g}({\\bf x})$) \u3092\u7528\u3044\u3066\u793a\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n$$\n\\frac{d}{dx}f(g(x), h(x)) = \\frac{\\partial f}{\\partial y}(y, z) \\cdot g^{'}(x) + \\frac{\\partial f}{\\partial z}(y, z) \\cdot h^{'}(x)\n$$\n\n\u3053\u3053\u3067\u3001$y=g(x)$, $z=h(x)$ \u3068\u3059\u308b\u3002\u3053\u306e\u7d50\u679c\u304c (1) \u3068 (2) \u306e\u5f0f\u306e\u4e00\u822c\u5316\u306b\u306a\u3063\u3066\u3044\u308b\u3053\u3068\u3092\u78ba\u304b\u3081\u3066\u4e0b\u3055\u3044\u3002\n\n(4) \u5e73\u9762\u4e0a\u3092\u79fb\u52d5\u3059\u308b\u70b9\u304c\u3042\u308a\u3001\u6642\u523b $t$ \u306e\u70b9\u306e\u5ea7\u6a19 $(x(t), y(t))$ \u306f $x(t)=t^2+t+1, y(t)=t^2-t+1$ \u3067\u3042\u308b\u3068\u3059\u308b\u3002\u5ea7\u6a19 $(x,y)$ \u306b\u3044\u308b\u3068\u304d\u3001\u70b9\u306f $E(x,y)=\\exp(\\frac{1}{\\sqrt{x^2+y^2}})$ \u306e\u30a8\u30cd\u30eb\u30ae\u30fc\u3092\u6301\u3063\u3066\u3044\u308b\u3068\u3059\u308b\u3002\u30a8\u30cd\u30eb\u30ae\u30fc\u306e\u6642\u9593\u306b\u95a2\u3059\u308b\u5fae\u5206 $\\frac{\\partial}{\\partial t}E(x(t),y(t))$ \u3092 (3) \u306e\u7d50\u679c\u3092\u7528\u3044\u3066\u6c42\u3081\u3066\u4e0b\u3055\u3044\u3002\n\n### \u554f5.8 (\u591a\u5909\u6570\u95a2\u6570\u306e\u5408\u6210\u95a2\u6570\u306e\u5fae\u5206)\n\u30d9\u30af\u30c8\u30eb\u5024\u95a2\u6570 ${\\bf f}$ \u3092\u4ee5\u4e0b\u3067\u5b9a\u7fa9\u3059\u308b\u3002\n\n$$\n{\\bf f}(\\begin{bmatrix}\nz \\\\\nw\n\\end{bmatrix}) = \\begin{bmatrix}\n\\frac{e^z}{e^{z+w}} \\\\\n\\frac{e^w}{e^{z+w}}\n\\end{bmatrix}.\n$$\n\n${\\bf X}$ \u3092 $2 \\times N$ \u884c\u5217\u3001${\\bf y}$ \u3092 $N$ \u6b21\u5143\u30d9\u30af\u30c8\u30eb\u3068\u3059\u308b\u3002\n\u504f\u5fae\u5206 $\\frac{\\partial}{\\partial x_{ij}}{\\bf f}({\\bf X}{\\bf y})$ \u3092\u8a08\u7b97\u3057\u3066\u4e0b\u3055\u3044\u3002\u3053\u3053\u3067\u3001$x_{ij}$ \u306f ${\\bf X}$ \u306e $(i,j)$ \u6210\u5206\u3068\u3059\u308b\u3002\n\n## \"6. \u78ba\u7387\u30fb\u7d71\u8a08\u306e\u57fa\u790e\" \u306e\u6f14\u7fd2\u554f\u984c\n\n### \u554f6.1 (\u540c\u6642\u5206\u5e03\u30fb\u5468\u8fba\u78ba\u7387)\n\n\u504f\u308a\u306e\u3042\u308b\u30b3\u30a4\u30f3 ${\\rm A}$ \u3068 ${\\rm B}$ \u304c\u3042\u308b\u3002\n\u30b3\u30a4\u30f3 ${\\rm A}$ \u3092\u632f\u3063\u305f\u3068\u304d\u306b\u8868\u304c\u51fa\u308b\u78ba\u7387\u306f1/4\u3001\u88cf\u304c\u51fa\u308b\u78ba\u7387\u306f3/4\u3067\u3042\u308b\u3002\u30b3\u30a4\u30f3 ${\\rm B}$ \u3092\u632f\u3063\u305f\u3068\u304d\u306b\u8868\u304c\u51fa\u308b\u78ba\u7387\u306f2/3\u3001\u88cf\u304c\u51fa\u308b\u78ba\u7387\u306f1/3\u3067\u3042\u308b\u3002\n\n\u3053\u306e\u4e8c\u3064\u306e\u30b3\u30a4\u30f3\u306e\u3046\u3061\u3069\u3061\u3089\u304b\u4e00\u3064\u3092\u7b49\u3057\u3044\u78ba\u7387\u3067\u30e9\u30f3\u30c0\u30e0\u306b\u9078\u3073\u3001\u9078\u3093\u3060\u65b9\u306e\u30b3\u30a4\u30f3\u3092\u632f\u308b\u3068\u8a00\u3046\u8a66\u884c\u3092\u8003\u3048\u307e\u3059\u3002\n\u9078\u3093\u3060\u30b3\u30a4\u30f3\u304c ${\\rm A}$ \u3068 ${\\rm B}$ \u3069\u3061\u3089\u3060\u3063\u305f\u304b\u3092\u8868\u3059\u78ba\u7387\u5909\u6570\u3092 $X$\u3001\u30b3\u30a4\u30f3\u3092\u632f\u3063\u305f\u7d50\u679c(\u8868\u88cf)\u3092\u8868\u3059\u78ba\u7387\u5909\u6570\u3092 $Y$ \u3068\u3059\u308b\u3002\n\n(1) \u540c\u6642\u78ba\u7387 $p(X={\\rm A}, Y=\u8868)$, $p(X={\\rm A}, Y=\u88cf)$, $p(X={\\rm B}, Y=\u8868)$, $p(X={\\rm B}, Y=\u88cf)$ \u3092\u305d\u308c\u305e\u308c\u8a08\u7b97\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n(2) \u540c\u6642\u78ba\u7387\u3092\u5468\u8fba\u5316\u3057\u3066\u3001\u78ba\u7387 $p(Y=\u8868)$ \u3068 $p(Y=\u88cf)$ \u3092\u8a08\u7b97\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n### \u554f6.2 (\u6761\u4ef6\u4ed8\u304d\u78ba\u7387)\n\n\u554f6.1 \u306e\u8a66\u884c\u3067\u6761\u4ef6\u4ed8\u304d\u78ba\u7387 $p(Y=\u8868 \\mid X={\\rm A})$ \u3092\u8a08\u7b97\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n### \u554f6.3 (\u30d9\u30a4\u30ba\u306e\u5b9a\u7406)\n\n(1) \u554f6.1 \u306e\u8a66\u884c\u3067\u4e8b\u5f8c\u78ba\u7387 $p(X={\\rm A} \\mid Y=\u8868)$, $p(X={\\rm B} \\mid Y=\u8868)$, $p(X={\\rm A} \\mid Y=\u88cf)$, $p(X={\\rm B} \\mid Y=\u88cf)$ \u3092\u305d\u308c\u305e\u308c\u8a08\u7b97\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n(2) \u554f6.1 \u306e\u8a66\u884c\u3092\u884c\u3063\u305f\u5f8c\u3001\u30b3\u30a4\u30f3\u306f\u8868\u304c\u51fa\u305f\u3068\u3059\u308b\u3002\u3053\u306e\u5f8c\u3055\u3089\u306b\u540c\u3058\u30b3\u30a4\u30f3\u3092\u632f\u3063\u305f\u3068\u304d\u306b\u518d\u3073\u8868\u304c\u51fa\u308b\u78ba\u7387\u3092\u8a08\u7b97\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n### \u554f6.4 (\u30d9\u30a4\u30ba\u306e\u5b9a\u7406)\n\n\u4e00\u69d8\u306a\u78ba\u7387\u30671\u304b\u30896\u307e\u3067\u306e\u6570\u304c\u51fa\u308b\u30b5\u30a4\u30b3\u30ed\u304c\u3042\u308b\u3002\n\u30b5\u30a4\u30b3\u30ed\u3092\u4f55\u56de\u304b\u9023\u7d9a\u3067\u632f\u308b\u8a66\u884c\u3092\u8003\u3048\u307e\u3059\u3002\u30b5\u30a4\u30b3\u30ed\u3092\u632f\u3063\u305f\u5f8c\u3001\u76f4\u524d\u306b\u51fa\u305f\u6570\u3088\u308a\u5927\u304d\u3044\u6570\u304c\u51fa\u305f\u3068\u304d\u306b\u300c\u30e9\u30c3\u30ad\u30fc\u3067\u3042\u308b\u300d\u3068\u547c\u3076\u3053\u3068\u306b\u3059\u308b\u3002\n\u4f8b\u3048\u3070\u30b5\u30a4\u30b3\u30ed\u30925\u56de\u632f\u3063\u3066 2,5,3,4,4 \u3068\u9806\u306b\u51fa\u305f\u5834\u5408\u30012\u56de\u76ee\u30684\u56de\u76ee\u306f\u30e9\u30c3\u30ad\u30fc\u3067\u3042\u308b\u304c\u3001\u305d\u308c\u4ee5\u5916\u306f\u30e9\u30c3\u30ad\u30fc\u3067\u306f\u306a\u3044\u3002\n\n\u3044\u307e\u3001\u30b5\u30a4\u30b3\u30ed\u3092 10 \u56de\u632f\u3063\u3066\u4e00\u5ea6\u3082\u30e9\u30c3\u30ad\u30fc\u3067\u306f\u306a\u304b\u3063\u305f\u3068\u3059\u308b\u3002\u3053\u306e\u3068\u304d\u3001\u6b21\u306b\u30b5\u30a4\u30b3\u30ed\u3092\u632f\u3063\u3066\u30e9\u30c3\u30ad\u30fc\u306b\u306a\u308b\u78ba\u7387\u306f\u3044\u304f\u3089\u306b\u306a\u308b\u3067\u3057\u3087\u3046\u304b\u3002\u30d7\u30ed\u30b0\u30e9\u30e0\u3092\u4f7f\u3063\u3066\u5206\u6790\u3057\u3066\u307f\u3066\u4e0b\u3055\u3044\u3002\n\n\n```python\n# \u3053\u3053\u306b\u30b3\u30fc\u30c9\u3092\u66f8\u304f\n\n```\n\n### \u554f6.5 (\u5c24\u5ea6\u3068\u6700\u5c24\u63a8\u5b9a)\n\n\u504f\u308a\u306e\u3042\u308b\u30b5\u30a4\u30b3\u30ed\u306e\u51fa\u308b\u76ee\u306e\u78ba\u7387\u3092\u63a8\u5b9a\u3059\u308b\u554f\u984c\u3092\u8003\u3048\u307e\u3059\u3002\u30b5\u30a4\u30b3\u30ed\u3092\u632f\u3063\u305f\u3068\u304d\u306b\u51fa\u308b\u6570\u3092\u8868\u3059\u78ba\u7387\u5909\u6570\u3092 $X$ \u3068\u3059\u308b\u3002\u78ba\u7387\u30e2\u30c7\u30eb\u306e\u30d1\u30e9\u30e1\u30fc\u30bf\u3092 $\\theta=(\\theta_1, \\theta_2, \\theta_3, \\theta_4, \\theta_5, \\theta_6)$ \u3068\u3057\u3066\u3001\u78ba\u7387 $p(X=x)$ \u3092\n\n$$\nf(x; \\theta) = \\theta_x\n$$\n\n\u306b\u3088\u3063\u3066\u30e2\u30c7\u30eb\u5316\u3059\u308b\u3002\u3053\u3053\u3067\u3001\u30d1\u30e9\u30e1\u30fc\u30bf\u306f $\\theta_1, \\ldots, \\theta_6 \\ge 0$ \u304b\u3064 $\\theta_1+\\ldots+\\theta_6=1$ \u3092\u6e80\u305f\u3055\u306a\u304f\u3066\u306f\u306a\u3089\u306a\u3044\u3068\u3059\u308b\u3002\n\n\u3044\u307e\u3001\u30b5\u30a4\u30b3\u30ed\u309260\u56de\u632f\u3063\u3066\u30011\u306e\u76ee\u304c30\u56de\u3001\u305d\u308c\u4ee5\u5916\u306e\u76ee\u304c6\u56de\u51fa\u305f\u3068\u3059\u308b\u3002\n\n(1) \u89b3\u6e2c\u30c7\u30fc\u30bf\u306b\u5bfe\u3059\u308b\u5bfe\u6570\u5c24\u5ea6\u3092\u6c42\u3081\u3066\u4e0b\u3055\u3044\u3002\n\n(2) \u30d7\u30ed\u30b0\u30e9\u30e0\u3092\u7528\u3044\u3066\u3001$\\theta=(\\theta_1, \\ldots, \\theta_6)$ \u306b\u69d8\u3005\u306a\u5024\u3092\u5165\u308c\u305f\u5834\u5408\u306b\u5bfe\u6570\u5c24\u5ea6\u304c\u3069\u306e\u3088\u3046\u306b\u306a\u308b\u304b\u3092\u89b3\u6e2c\u3057\u3066\u4e0b\u3055\u3044\u3002$\\theta$ \u304c\u3069\u306e\u3088\u3046\u306a\u3068\u304d\u306b\u5bfe\u6570\u5c24\u5ea6\u304c\u5927\u304d\u304f\u306a\u308b\u304b\u4e88\u60f3\u3059\u308b\u3002\n\n\n```python\n# \u3053\u3053\u306b\u30b3\u30fc\u30c9\u3092\u66f8\u304f\n\n```\n\n### \u554f6.6 (\u5c24\u5ea6\u3068\u6700\u5c24\u63a8\u5b9a)\n\n\u30dd\u30a2\u30bd\u30f3\u5206\u5e03\u306f\u6b63\u306e\u5b9f\u6570 $\\lambda>0$ \u3092\u30d1\u30e9\u30e1\u30fc\u30bf\u3068\u3057\u3066\u6301\u3064\u5206\u5e03\u3067\u3042\u308b\u3002$0$ \u4ee5\u4e0a\u306e\u6574\u6570\u5024\u3092\u53d6\u308b\u78ba\u7387\u5909\u6570 $X$ \u304c\u4ee5\u4e0b\u306e\u78ba\u7387\u5024\u306b\u5f93\u3046\u3068\u304d\u3001$X$ \u306f\u30dd\u30a2\u30bd\u30f3\u5206\u5e03\u306b\u5f93\u3046\u3068\u8a00\u3046\u3002\n\n$$p(X=k)=\\frac{\\lambda^k e^{-\\lambda}}{k!} \\; \\; \\; (k=0,1,2,\\ldots).$$\n\n\u3044\u307e\u3001\u3042\u308b\u4ea4\u5dee\u70b9\u3067\u7279\u5b9a\u306e\u6642\u9593\u5e2f\u306b\u5b58\u5728\u3059\u308b\u6b69\u884c\u8005\u306e\u4eba\u6570\u306e\u3092\u30dd\u30a2\u30bd\u30f3\u5206\u5e03\u3067\u30e2\u30c7\u30eb\u5316\u3059\u308b\u3053\u3068\u3092\u8003\u3048\u307e\u3059\u3002\n$X$ \u3092\u7279\u5b9a\u306e\u6642\u9593\u5e2f\u306b\u5b58\u5728\u3059\u308b\u6b69\u884c\u8005\u306e\u4eba\u6570\u3092\u8868\u3059\u78ba\u7387\u5909\u6570\u3068\u3059\u308b\u3002\u78ba\u7387 $p(X=k)$ \u306f\u4e0a\u8a18\u306e\u30dd\u30a2\u30bd\u30f3\u5206\u5e03\u306b\u5f93\u3046\u3068\u3059\u308b\u3002\n\n20\u65e5\u9593\u306e\u89b3\u6e2c\u7d50\u679c\u306b\u3088\u308b\u3068\u3001$i$ \u65e5\u76ee\u306b\u306f $10+i$ \u4eba\u306e\u6b69\u884c\u8005\u3092\u89b3\u6e2c\u3057\u305f\u3053\u3068\u304c\u5206\u304b\u3063\u3066\u3044\u308b\u3068\u3059\u308b\u3002($i=1,2,\\ldots,20$)\n\n(1) \u89b3\u6e2c\u30c7\u30fc\u30bf\u306b\u5bfe\u3059\u308b\u5bfe\u6570\u5c24\u5ea6\u3092\u6c42\u3081\u3066\u4e0b\u3055\u3044\u3002\n\n(2) \u5bfe\u6570\u5c24\u5ea6\u3092\u6700\u5927\u306b\u3059\u308b $\\lambda$ \u306e\u5024\u3092\u6c42\u3081\u3066\u4e0b\u3055\u3044\u3002\n\n(3) (2) \u3067\u6c42\u3081\u305f $\\lambda$ \u3092\u30d1\u30e9\u30e1\u30fc\u30bf\u3068\u3057\u3066\u7528\u3044\u305f\u3068\u304d\u3001$k=0,1,\\ldots,50$ \u306b\u5bfe\u3057\u3066 $p(X=k)$ \u3092\u30d7\u30ed\u30b0\u30e9\u30e0\u3092\u7528\u3044\u3066\u8a08\u7b97\u3057\u3066\u4e0b\u3055\u3044\u3002\u306a\u304a\u3001\u7d2f\u4e57 $\\lambda^k$ \u306e\u8a08\u7b97\u306b\u306f\u7d44\u307f\u8fbc\u307f\u95a2\u6570\u306e `pow` \u3092\u3001\u968e\u4e57 $k!$ \u306e\u8a08\u7b97\u306b\u306f `math` \u30e2\u30b8\u30e5\u30fc\u30eb\u306b\u3042\u308b `math.factorial` \u3092\u7528\u3044\u308b\u3068\u4fbf\u5229\u3067\u3042\u308b\u3002\n\n\n```python\n# \u3053\u3053\u306b\u30b3\u30fc\u30c9\u3092\u66f8\u304f\n\n```\n\n### \u554f6.7 (\u4e8b\u5f8c\u78ba\u7387\u6700\u5927\u5316\u63a8\u5b9a(MAP\u63a8\u5b9a))\n\n6\u7ae0\u306e\u4f8b6.7.1 \u306b\u3042\u308b\u30b3\u30a4\u30f3\u30c8\u30b9\u306e\u8a66\u884c\u3067\u3001\u4e8b\u524d\u78ba\u7387 $p(\\theta)$ \u3092\u4ee5\u4e0b\u306e\u3088\u3046\u306b\u5909\u66f4\u3057\u305f\u5834\u5408\u306b\u3069\u3046\u306a\u308b\u304b\u3092\u8003\u3048\u3066\u307f\u308b\u3002\n\n$$\np(\\theta)=\\begin{cases}\n3 & (1/3 \\le \\theta \\le 3/2) \\\\\n0 & (\\text{otherwise})\n\\end{cases}\n$$\n\n\u30b3\u30a4\u30f3\u309210\u56de\u632f\u3063\u30669\u56de\u8868\u304c\u51fa\u30661\u56de\u88cf\u304c\u51fa\u305f\u3068\u304d\u3001MAP \u63a8\u5b9a\u306b\u3088\u3063\u3066\u30d1\u30e9\u30e1\u30fc\u30bf $\\theta$ \u3092\u63a8\u5b9a\u3057\u3066\u4e0b\u3055\u3044\u3002\n\n### \u554f6.8 (\u7d71\u8a08\u91cf)\n\n\u751f\u5f92\u304c100\u4eba\u3044\u308b\u5b66\u6821\u3067\u671f\u672b\u8a66\u9a13\u3092\u3057\u305f\u7d50\u679c\u3001\u79d1\u76eeA\u3068\u79d1\u76eeB\u306e\u70b9\u6570\u306f\u4ee5\u4e0b\u306e\u3088\u3046\u306a\u7d50\u679c\u306b\u306a\u308a\u307e\u3057\u305f\u3002\n\n* \u79d1\u76eeA: 20\u70b9\u306e\u751f\u5f92\u304c50\u4eba\u300180\u70b9\u306e\u751f\u5f92\u304c50\u4eba\n* \u79d1\u76eeB: 0\u70b9\u306e\u751f\u5f92\u304c1\u4eba\u30011\u70b9\u306e\u751f\u5f92\u304c1\u4eba\u30012\u70b9\u306e\u751f\u5f92\u304c1\u4eba\u3001\u2026\u300199\u70b9\u306e\u751f\u5f92\u304c1\u4eba\n\n\u3053\u306e\u4e8c\u3064\u306e\u79d1\u76ee\u306b\u3064\u3044\u3066\u3001\u751f\u5f92\u306e\u70b9\u6570\u306e\u5e73\u5747\u3068\u6a19\u6e96\u504f\u5dee\u3092\u305d\u308c\u305e\u308c\u8a08\u7b97\u3057\u3066\u4e0b\u3055\u3044\u3002\u30d7\u30ed\u30b0\u30e9\u30e0\u3092\u7528\u3044\u3066\u3082\u3088\u3044\u3002\n\n\u3053\u306e\u4f8b\u304b\u3089\u5206\u304b\u308b\u3088\u3046\u306b\u3001\u30c7\u30fc\u30bf\u306e\u3070\u3089\u3064\u304d\u304c\u975e\u5e38\u306b\u7570\u306a\u308b\u6027\u8cea\u3092\u3082\u3063\u3066\u3044\u3066\u3082\u5e73\u5747\u3084\u6a19\u6e96\u504f\u5dee\u304c\u8fd1\u3044\u5024\u306b\u306a\u308b\u3053\u3068\u304c\u3042\u308b\u3002\n\n\n```python\n# \u30d7\u30ed\u30b0\u30e9\u30e0\u3092\u7528\u3044\u308b\u5834\u5408\u306f\u3053\u3053\u306b\u30b3\u30fc\u30c9\u3092\u66f8\u304f\n\n```\n", "meta": {"hexsha": "567cda90fbf150a91eba9326ebff8a702f86926b", "size": 246691, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chainer.ipynb", "max_stars_repo_name": "kalz2q/-yjupyternotebooks", "max_stars_repo_head_hexsha": "ba37ac7822543b830fe8602b3f611bb617943463", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-16T03:45:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T03:45:19.000Z", "max_issues_repo_path": "chainer.ipynb", "max_issues_repo_name": "kalz2q/-yjupyternotebooks", "max_issues_repo_head_hexsha": "ba37ac7822543b830fe8602b3f611bb617943463", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chainer.ipynb", "max_forks_repo_name": "kalz2q/-yjupyternotebooks", "max_forks_repo_head_hexsha": "ba37ac7822543b830fe8602b3f611bb617943463", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7217371056, "max_line_length": 896, "alphanum_fraction": 0.4286577135, "converted": true, "num_tokens": 75900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629691917376783, "lm_q2_score": 0.11124120503431591, "lm_q1q2_score": 0.04037713027923099}}
{"text": "# <center>Oil Properties Estimation</center>\n\n### <center>Sept 2014<br>Author: Bill Lehr<br>Edited By: James L. Makela</center>\n\n## <u>Minimum Requirements</u>\n\nAdios 3 requires certain minimum amounts of data for any oil to be included in the library\n\nCrude Oil:\n<ul>\n<li>API and/or density at a reference temperature</li>\n<li>Viscosity (either kinematic or dynamic) at a reference temperature</li>\n</ul>\n\nRefined Product or 'Other' oil:\n<ul>\n<li>API and/or density at a reference temperature</li>\n<li>Viscosity (either kinematic or dynamic) at a reference temperature</li>\n<li>At least three distillation cuts giving mass or volume fraction at boiling(bubble) point</li>\n</ul>\n\nUnlike Adios 2, Adios 3 stores both structural and distillation fractional components <b><u>(see figure 1)</u></b>.\nCertain properties are valid for the whole oil while others may be defined for each structural fraction and still others vary for both the distillation and chemical structural fraction.\n\nThe SQL oil database needs a complete set of oil data.  If measured data exists, it takes priority over estimated values.  Many of the more complex estimation formulas are based upon Adios 2 calculations and/or the following reference:\n\n<b><i>Characterization and Properties of Petroleum Fractions</b></i><br>\n<b>Author:</b> Dr. M. R. Riazi, Professor of Chemical Engineering, Kuwait University<br>\n<b>Published:</b> 2005<br>\n<b>Publisher:</b> American Society for Testing and Materials (ASTM), International<br>\n<b>Stock No.:</b> MNL50<br>\n\nThis will be abbreviated further in this document as CPPF.\n\n## <u>Setting Up for our Estimations</u>\n\nThis is just a bit of setup so that we may verify our estimations with code snippets.\n\n\n```python\n%pylab inline\nimport numpy as np\nfrom scipy.optimize import curve_fit\n\nimport oil_library\nfrom oil_library.models import Oil, ImportedRecord, KVis, Density\n\nfrom pprint import PrettyPrinter\npp = PrettyPrinter(indent=2, width=120)\n\nsession = oil_library._get_db_session()\n\n# these are some reasonable samples of oil records in the oil library\nans_mp = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'ALASKA NORTH SLOPE (MIDDLE PIPELINE)').one()\nans_2002 = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'ALASKA NORTH SLOPE (2002)').one()\nbahia = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'BAHIA').one()\narabian = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'ARABIAN MEDIUM, AMOCO').one()\n\n# These samples are problematic in some way or another\ncanola = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'CANOLA OIL (REFERENCE)').one()\nabu_safah = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'ABU SAFAH').one()\nsajaa = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'SAJAA CONDENSATE, BP').one()\nbontang = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'BONTANG MIX, BP').one()\ngeisum = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'NORTH GEISUM, GEISUM OIL').one()\ncl_bitumen = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'COLD LAKE BITUMEN').one()\nbonny_light = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'BONNY LIGHT').one()\npetro_star = session.query(ImportedRecord).filter(ImportedRecord.oil_name ==\n                                                  'FUEL OIL NO.1 (DIESEL/HEATING FUEL), PETRO STAR').one()\nifo_180 = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'IFO 180').one()\nboscan = session.query(ImportedRecord).filter(ImportedRecord.oil_name == 'BOSCAN, OIL & GAS').one()\n\nprint ans_mp\nprint ans_2002\nprint bahia\nprint arabian\nprint canola\n\n```\n\n    Populating the interactive namespace from numpy and matplotlib\n    <ImportedRecord('ALASKA NORTH SLOPE (MIDDLE PIPELINE)')>\n    <ImportedRecord('ALASKA NORTH SLOPE (2002)')>\n    <ImportedRecord('BAHIA')>\n    <ImportedRecord('ARABIAN MEDIUM, AMOCO')>\n    <ImportedRecord('CANOLA OIL (REFERENCE)')>\n\n\n## <u>Procedural Order of Oil Estimation</u>\n\nOur estimations of properties for an input oil record are based on a set of minimal data requirements.\nWe necessarily build upon this minimal set in an ordered fashion because some calculations are needed to provide input to later calculations.\n\nIf we could describe the general flow of calculations it might be something like this.\n\n- Foundational Aggregate Oil Properties\n- Oil Distillation Fractional Properties\n- Oil SARA Component Properties\n- Oil Miscellaneous Properties\n\n## <u>Foundational Aggregate Oil Properties</u>\n\nThese are the baseline oil property estimations which take the properties supplied by the input oil record and produce the minimum set of whole oil properties necessary to estimate the more complex properties, such as the distillation fractions and SARA component properties.  These are:\n\n- Density\n- API\n- Viscosity\n\n### 1. Density:\n\n(A) If no density value exists, estimate it from the oil's API using the following equation:\n\n$$\n\\begin{align}\n\\rho0_{oil} &= \\text{density of the oil at a } T_{ref} \\text{of } 288.15^\\circ K \\,\\, (kg/m^3) \\cr\n&= {141.5 \\over 131.5 + API} \\cdot 1000 \\qquad \\qquad \\qquad \\qquad \\qquad \\qquad \\boldsymbol{(eq. 1)} \\cr\n\\end{align}\n$$\n\n(B) If a density measurement $\\rho_0$ at some temperature $T_0$ exists, but no API, then (eq. 1) can be inverted to give an API.\n\n$$\n\\begin{align}\nAPI &= \\left( {141.5 \\over \\rho0_{oil}} \\cdot 1000 \\right) - 131.5 \n\\qquad \\qquad \\qquad \\qquad \\qquad \\boldsymbol{(eq. 2)} \\cr\n\\end{align}\n$$\n\nBut this can only be done after the density value has been adjusted to be a density at $T_{ref} = 288.15^\\circ K (15^\\circ C)$.  The density conversion formula for different temperatures is:\n\n$$\n\\begin{align}\n\\rho_0 &= \\text{measured density} \\cr\nT_0 &= \\text{temperature at which density is measured} \\cr\nk_{\\rho T} &= 0.0008 \\, K^{-1} \\cr\n\\cr\n\\rho_{ref} &= \\rho_0 \\cdot (1 - k_{\\rho T} \\cdot (T_{ref} - T_0 ))\n\\qquad \\qquad \\qquad \\qquad \\qquad \\boldsymbol{(eq. 3)} \\cr\n\\end{align}\n$$\n\n<i>(Referenced Source: Adios2, File: InputData.cpp, Function: CAdiosData::CalcRhoOil() )</i>\n\n\n```python\ndef lowest_temperature(obj_list):\n    '''\n        General utility function.\n\n        From a list of objects containing a ref_temp_k attribute,\n        return the object that has the lowest temperature\n    '''\n    if len(obj_list) > 0:\n        return sorted(obj_list, key=lambda d: d.ref_temp_k)[0]\n    else:\n        return None\n\ndef closest_to_temperature(obj_list, temperature):\n    '''\n        General Utility Function\n\n        From a list of objects containing a ref_temp_k attribute,\n        return the object that is closest to the specified temperature\n    '''\n    temp_diffs = [(obj, abs(obj.ref_temp_k - temperature))\n                  for obj in obj_list\n                  if obj.ref_temp_k is not None]\n    if len(temp_diffs) > 0:\n        return sorted(temp_diffs, key=lambda d: d[1])[0][0]\n    else:\n        return None\n\ndef estimate_density_from_api(api):\n    kg_m_3 = 141.5 / (131.5 + api) * 1000.0\n    ref_temp_k = 273.15 + 15.0\n\n    return kg_m_3, ref_temp_k\n\ndef estimate_api_from_density(density):\n    return (141.5 / density * 1000.0) - 131.5\n\ndef estimate_density_at_temp(ref_density, ref_temp_k,\n                             temperature):\n    k_pt = 0.0008\n    return ref_density / (1 - k_pt * (ref_temp_k - temperature))\n\ndef oil_density_at_temp(imported_rec, temperature, weathering=0.0):\n    density_list = [d for d in imported_rec.densities\n                    if (d.kg_m_3 is not None and\n                        d.ref_temp_k is not None and\n                        d.weathering == weathering)]\n    closest_density = closest_to_temperature(density_list, temperature)\n\n    if closest_density is not None:\n        d_ref, t_ref = (closest_density.kg_m_3,\n                        closest_density.ref_temp_k)\n    elif imported_rec.api is not None:\n        d_ref, t_ref = estimate_density_from_api(imported_rec.api)\n    else:\n        return None\n\n    return estimate_density_at_temp(d_ref, t_ref, temperature)\n\n#for obj in (ans_mp, ans_2002, bahia, arabian, canola):\nfor obj in (ans_mp,):\n    print 'oil = ', obj.oil_name\n    print 'oil.api = ', obj.api\n    print 'oil.densities = ', obj.densities\n\n    if obj.api is not None:\n        print 'density(api) = ', estimate_density_from_api(obj.api)\n    else:\n        print 'density(api) = N/A'\n\n    if len(obj.densities) > 0:\n        print 'API(density) = ', estimate_api_from_density(oil_density_at_temp(obj, 288.15))\n    else:\n        print 'API(density) = N/A'\n\n    print 'density at 288.15K = ', (oil_density_at_temp(obj, 288.15), 288.15)\n    print\n```\n\n    oil =  ALASKA NORTH SLOPE (MIDDLE PIPELINE)\n    oil.api =  29.9\n    oil.densities =  [<Density(886.9 kg/m^3 at 273.15K)>, <Density(876.1 kg/m^3 at 288.15K)>]\n    density(api) =  (876.7038413878562, 288.15)\n    API(density) =  30.0112430088\n    density at 288.15K =  (876.1, 288.15)\n    \n\n\n### 2. Kinematic Viscosity:\n\nThe input oil record could contain a number of viscosity properties, measured as either dynamic viscosity, kinematic viscosity, or a mix of both.  Each viscosity property in the oil record is accompanied by a reference temperature $\\,^\\circ K$ which is the temperature at which the viscosity was measured at.  We want to deal exclusively in kinematic viscosity.\n\nConverting a dynamic viscosity value into a kinematic viscosity value is done as follows.\n\n$$\n\\begin{align}\n\\eta 0_{oil} &= \\text{measured dynamic viscosity } (kg/(m \\cdot s)) \\cr\n\\rho 0_{oil} &= \\text{measured density } (kg/m^3) \\cr\n\\cr\nv0_{oil} &= \\text{kinematic viscosity } (m^2/s) \\cr\n&= {\\eta 0_{oil} \\over \\rho 0_{oil} }\n\\qquad \\qquad \\qquad \\qquad \\qquad \\qquad \\boldsymbol{(eq. 4)} \\cr\n\\end{align}\n$$\n\nBasically we want to take advantage of any and all measured viscosities that are available.  We will of course prefer the kinematic measurements, but we will want to use any dynamic viscosity measurements that are not redundant.  So the basic program flow will be as follows:\n\n<ul>\n<li>Collect all existing measured kinematic viscosities and their associated reference temperatures</li>\n<li>Collect any dynamic viscosities measured at temperatures not already represented in the kinematic measurements</li>\n<li>Convert the dynamic viscosities into kinematic viscosities using (eq. 3)</li>\n<li>Combine our kinematic and converted dynamic viscosities into one aggregate list</li>\n</ul>\n\nUsing the measured kinematic viscosities, we should be able to estimate the oil kinematic viscosity at an arbitrary temperature.  I believe this is what Adios2 does:\n$$\n\\begin{align}\nT &= \\text{temperature in } \\,^\\circ K \\cr\nk_{v2} &= 5000^\\circ K \\cr\nT_{ref} &= \\text{measured reference temperature} \\cr\nv_{ref} &= \\text{measured reference viscosity} \\cr\n\\cr\nv_T &= \\text{the viscosity at a specified temperature} \\cr\n&= v_{ref} \\cdot exp \\left( {k_{v2} \\over T} - {k_{v2} \\over T_{ref}} \\right)\n\\qquad \\qquad \\qquad \\qquad \\qquad \\qquad \\boldsymbol{(eq. 5)} \\cr\n\\end{align}\n$$\n\n<i>(Referenced Source: Adios2, File: OilInitialize.cpp, Function: CAdiosData::InitialViscosity() )</i>\n\n\n```python\ndef dvis_to_kvis(dvis, density):\n    return dvis / density\n\ndef estimate_kvis_at_temp(temp_k, kvis_ref, ref_temp_k):\n    k_v2 = 5000.0\n    return kvis_ref * np.exp(k_v2 / temp_k - k_v2 / ref_temp_k)\n\ndef oil_aggregate_kvis(imported_rec):\n    kvis_list = [(k.ref_temp_k, k.m_2_s)\n                 for k in imported_rec.kvis\n                 if k.m_2_s is not None and\n                 k.ref_temp_k is not None]\n    dvis_list = [(d.ref_temp_k,\n                  dvis_to_kvis(d.kg_ms,\n                               oil_density_at_temp(imported_rec, d.ref_temp_k)))\n                 for d in imported_rec.dvis\n                 if d.kg_ms is not None and\n                 d.ref_temp_k is not None]\n\n    agg = dict(dvis_list)\n    agg.update(kvis_list)\n\n    return [KVis(ref_temp_k=i[0], m_2_s=i[1]) \n            for i in agg.iteritems()]\n\ndef oil_kvis_at_temp(imported_rec, temp_k, weathering=0.0):\n    kvis_list = [kv for kv in oil_aggregate_kvis(imported_rec)\n                 if (kv.weathering == weathering)]\n    closest_kvis = closest_to_temperature(kvis_list, temp_k)\n\n    if closest_kvis is not None:\n        kvis_ref, t_ref = (closest_kvis.m_2_s,\n                           closest_kvis.ref_temp_k)\n    else:\n        return None\n\n    return estimate_kvis_at_temp(temp_k, kvis_ref, t_ref)\n\n#for obj in (ans_mp, ans_2002, bahia, arabian, canola):\nfor obj in (ans_mp,):\n    print 'oil = ', obj.oil_name\n    print 'oil.kvis = ', obj.kvis\n    print 'oil.dvis = ', obj.dvis\n    print 'aggregate kvis = ', oil_aggregate_kvis(obj)\n    print 'kvis at 288k = ', oil_kvis_at_temp(obj, 288.0)\n    print\n\n# TODO: Okay, the ANS (2002) oil record has a crazy list of dynamic viscosities\n#       This has got to be fixed.\n```\n\n    oil =  ALASKA NORTH SLOPE (MIDDLE PIPELINE)\n    oil.kvis =  []\n    oil.dvis =  [<DVis(0.034 kg/ms at 273.15K)>, <DVis(0.016 kg/ms at 288.15K)>]\n    aggregate kvis =  [<KVis(3.83357762995e-05 m^2/s at 273.15K)>, <KVis(1.82627553932e-05 m^2/s at 288.15K)>]\n    kvis at 288k =  1.84285538212e-05\n    \n\n\n## <u>Oil Distillation Fractional Properties</u>\n\nA large number of our estimations depend upon a characterization of the fractional amounts of compounds that fit somewhere in a high level classification named SARA.  SARA is an acronym meaning Saturates, Aromatics, Resins, and Asphaltenes.  There is much literature on the characterization of these petroleum hydrocarbons, but generally:\n\n- Saturates are volatile, and evaporate at an estimable rate with increasing temperature.\n- Aromatics are similarly volatile, but at different rates.\n- Resins are considered inert.  That is to say they will not evaporate at any reasonable temperature.\n- Asphaltenes are also considered inert.\n\nMost oil records do not contain precise information regarding these fractional amounts.  But they do often contain fractional distillation cut properties.  The distillation cuts describe the rate at which the volatile portions of the oil evaporate.  And from this we can attempt to estimate the SARA fractional amounts.\n\nThe steps involved in getting our distillation data are as follows:\n\n- We will first get the fraction of the oil that is inert.  That is the resins and asphaltenes.\n- We will then get the data points that represent the fractions of oil that are evaporated at associated temperatures.\n- We will then try to normalize the inert and volatile fractions so that they measure up to the total fraction of oil.\n\n### 3. Initial Resin and Asphaltene Fractions and Densities:\n\n<i>\nReference: Fingas empirical formulas that are based upon analysis of ESTC oil properties database.\n</i>\n\nIf the imported oil record contains valid values for resins and asphaltenes, we will use those values when building our oil.<br>\nOtherwise, we will need to estimate them.\n\nFirst we define some values $A$ and $B$ that will be used for our component fraction formulas:\n\n$$\n\\begin{align}\n\\rho 0_{oil} &= \\text{oil aggregate density at } 288.15^\\circ K \\text{  (from eqs. 1,2)} \\cr\nv0_{oil} &= \\text{oil kinematic viscosity at } 288.15^\\circ K \\text{  (from eq. 5)} \\cr\n\\cr\nA &= 10 \\cdot exp(0.001 \\cdot \\rho 0_{oil}) \\qquad \\qquad \\qquad \\qquad \\boldsymbol{(eq. 6)} \\cr\nB &= 10 \\cdot ln(1000 \\cdot \\rho 0_{oil} \\cdot v0_{oil}) \\qquad \\qquad \\qquad \\boldsymbol{(eq. 7)}\\cr\n\\end{align}\n$$\n\nThen our component fraction formulas:\n\n$$\n\\begin{align}\nf_{res} &= (0.033 \\cdot A + 0.00087 \\cdot B - 0.74)_{\\bot 0}^{\\top 1}\n\\qquad \\qquad \\qquad \\qquad \\qquad \\boldsymbol{(eq. 8)} \\cr\nf_{asph} &= (0.000014 \\cdot A^3 + 0.000004 \\cdot B^2 - 0.18)_{\\bot 0}^{\\top (1 - f_{res})}\n\\qquad \\qquad \\qquad \\boldsymbol{(eq. 9)} \\cr\n\\end{align}\n$$\n\n\n```python\ndef estimate_A_coeff(density):\n    return 10.0 * np.exp(0.001 * density)\n\ndef estimate_B_coeff(density, viscosity):\n    return 10.0 * np.log(1000.0 * density * viscosity)\n\ndef estimate_resin_fraction(density, viscosity, f_other=0.0):\n    A = estimate_A_coeff(density)\n    B = estimate_B_coeff(density, viscosity)\n\n    f_res = 0.033 * A + 0.00087 * B - 0.74\n    f_res = np.clip(f_res, 0.0, 1.0 - f_other)\n    \n    return f_res\n\n\ndef estimate_asphaltene_fraction(density, viscosity, f_other=0.0):\n    A = estimate_A_coeff(density)\n    B = estimate_B_coeff(density, viscosity)\n\n    f_asph = (0.000014 * A ** 3.0 +\n              0.000004 * B ** 2.0 -\n              0.18)\n    f_asph = np.clip(f_asph, 0.0, 1.0 - f_other)\n    \n    return f_asph\n\ndef oil_inert_fractions(imported_rec):\n    f_res, f_asph = imported_rec.resins, imported_rec.asphaltenes\n\n    if f_res is not None and f_asph is not None:\n        return f_res, f_asph\n    else:\n        density = oil_density_at_temp(imported_rec, 288.15)\n        viscosity = oil_kvis_at_temp(imported_rec, 288.15)\n\n    if f_res is None:\n        f_res = estimate_resin_fraction(density, viscosity)\n\n    if f_asph is None:\n        f_asph = estimate_asphaltene_fraction(density, viscosity,\n                                              f_res)\n\n    return f_res, f_asph\n\n#for obj in (ans_mp, ans_2002, bahia, arabian, canola):\nfor obj in (ans_mp,):\n    print 'oil = ', obj.oil_name\n    print 'oil.api = ', obj.api\n    print 'oil.resins = ', obj.resins\n    print 'oil.asphaltenes = ', obj.asphaltenes\n    obj_density = oil_density_at_temp(obj, 288.15)\n    obj_viscosity = oil_kvis_at_temp(obj, 288.15)\n    print 'oil density at temp = ', obj_density\n    print 'oil viscosity at temp = ', obj_viscosity\n    print 'f_res, f_asph = ',\n    print estimate_resin_fraction(obj_density, obj_viscosity),\n    print estimate_asphaltene_fraction(obj_density, obj_viscosity)\n    print 'f_res, f_asph = ', oil_inert_fractions(obj)\n    print 'sum of inert fractions = ', np.sum(oil_inert_fractions(obj))\n    print\n\n```\n\n    oil =  ALASKA NORTH SLOPE (MIDDLE PIPELINE)\n    oil.api =  29.9\n    oil.resins =  None\n    oil.asphaltenes =  None\n    oil density at temp =  876.1\n    oil viscosity at temp =  1.82627553932e-05\n    f_res, f_asph =  0.0766216397354 0.0169777627026\n    f_res, f_asph =  (0.076621639735448888, 0.016977762702612892)\n    sum of inert fractions =  0.0935994024381\n    \n\n\n### 4. Distillation Cut Boiling Point:\n\n<i>\n<b>Reference:</b> Adios2 and Jones R. (1997), A Simplified Pseudo-component Oil Evaporation Model, Proceedings of the 20th Arctic and Marine Oil Spill Program (AMOP), Vancouver, CA, Vol. 1, pp. 43-62\n</i>\n\nIf the oil record contains distillation data, then we can use the distillation cut temperatures.<br>\nOtherwise, if no distillation data exists, then we can estimate the distillation data from the oil's API.\n\nThis is done as follows:\n\nFirst we estimate our lower and upper temperature bounds:\n\n$$\n\\begin{align}\nT_0 &= \\text{the lower temperature boundary} \\cr\n&= 457 - 3.34 \\cdot API \\qquad \\qquad \\qquad \\qquad \\boldsymbol{(eq. 10)} \\cr\nT_G &= \\text{the upper temperature boundary} \\cr\n&= 1357 - 247.7 \\cdot ln(API) \\qquad \\qquad \\qquad \\boldsymbol{(eq. 11)} \\cr\n\\end{align}\n$$\n\nNext, we would like to generate a set of $N$ temperatures associated with our cuts $T_i$.  We will use a default of 5 cuts for this.\n\n$$\n\\begin{align}\nN &= 5 \\cr\nT_i &= T_0 + T_G \\cdot {i \\over N} \\quad \\{ i \\in \\Bbb Z \\,\\,|\\,\\, 0 \\leq i < N \\}\n\\qquad \\boldsymbol{(eq. 12)} \\cr\n\\end{align}\n$$\n\n\n```python\ndef estimate_cut_temps_from_api(api, N=5):\n    T_0 = 457.0 - 3.34 * api\n    T_G = 1357.0 - 247.7 * np.log(api)\n    \n    return np.array([(T_0 + T_G * i / N)\n                     for i in range(N)])\n\ndef oil_cut_temps(imported_rec):\n    culled_cuts = imported_rec.cuts\n    if len(culled_cuts) > 0:\n        return np.array([c.vapor_temp_k\n                         for c in culled_cuts])\n    elif imported_rec.api is not None:\n        return estimate_cut_temps_from_api(imported_rec.api)\n    else:\n        est_api = estimate_api_from_density(oil_density_at_temp(imported_rec, 288.15))\n        return estimate_cut_temps_from_api(est_api)\n\n#for obj in (ans_mp, ans_2002, bahia, arabian, canola):\nfor obj in (ans_mp,):\n    print 'oil = ', obj.oil_name\n    print 'oil.api = ', obj.api\n    print 'oil.densities = ', obj.densities\n    print 'oil.cut.vapor_temp_k = ', [c.vapor_temp_k for c in obj.cuts]\n    print 'oil.cut.fraction = ', [c.fraction for c in obj.cuts]\n    print 'cut temperatures = ', oil_cut_temps(obj)\n    print\n\n```\n\n    oil =  ALASKA NORTH SLOPE (MIDDLE PIPELINE)\n    oil.api =  29.9\n    oil.densities =  [<Density(886.9 kg/m^3 at 273.15K)>, <Density(876.1 kg/m^3 at 288.15K)>]\n    oil.cut.vapor_temp_k =  [313.15, 353.15, 393.15, 433.15, 473.15, 573.15, 673.15, 773.15, 873.15, 973.15]\n    oil.cut.fraction =  [0.03, 0.07, 0.13, 0.19, 0.25, 0.42, 0.6, 0.76, 0.88, 0.95]\n    cut temperatures =  [ 313.15  353.15  393.15  433.15  473.15  573.15  673.15  773.15  873.15\n      973.15]\n    \n\n\n### 5. Distillation Cut Mass Fraction:\n\nThe distillation cuts are a series of temperatures and mass fractions.  And each temperature $T_i$ is associated with a fractional value $fevap_i$ representing the portion of substance that was evaporated at that temperature. \n\nFor any temperature below about $530^\\circ K$, we can assume that the portion of substance that was evaporated contains a mix of saturates and aromatics, and that no resins or asphaltenes have been released.\nThe fractional quantity that was evaporated at a distillation cut temperature, is what we would like to consider to be our distillation cut mass fractions.\n\n<b>(A)</b> If the oil record contains at least two distillation cuts exist for which $T_i < 530^\\circ K$, then we will use the supplied distillation cut fractional masses to generate $fmass_i$.\n\nThe distillation cut mass fractions that we get in the imported oil record are cumulative in nature, so it is necessary to collect the differences in the distillation cut mass fractions when generating $fmass_i$\n\n$$\n\\begin{align}\nfmass_i &= {d \\over di} \\left( fevap_i \\right)\n\\qquad \\{ i \\in \\Bbb Z \\,\\,|\\,\\, 0 \\leq i \\leq N \\}\n\\qquad \\qquad \\boldsymbol{(eq. 13)} \\cr\n\\end{align}\n$$\n\n<b>(B)</b> If distillation cut temperatures were generated by approximation (eq. 18), then it can be assumed that there were no measured mass fractions.  For this we will evenly distribute our fractional masses such that for all distillation cuts:\n\n$$\n\\begin{align}\nfmass_i &= {(1 - (f_{res} + f_{asph})) \\over N}\n\\qquad \\qquad \\boldsymbol{(eq. 14)} \\cr\n\\end{align}\n$$\n\n\n```python\ndef estimate_fmasses_from_cuts(f_evap_i):\n    fmass_i = np.array(f_evap_i)\n    fmass_i[1:] = np.diff(fmass_i)\n\n    return fmass_i\n\ndef estimate_n_fmasses(f_res, f_asph, N=5):\n    return np.array([(1.0 - f_res - f_asph) / N] * N)\n\ndef oil_fmasses(imported_rec):\n    f_res, f_asph = oil_inert_fractions(imported_rec)\n    culled_cuts = imported_rec.cuts\n\n    if len(culled_cuts) > 0:\n        fractions = [c.fraction for c in culled_cuts]\n        return estimate_fmasses_from_cuts(fractions)\n    else:\n        return estimate_n_fmasses(f_res, f_asph)\n\n#for obj in (ans_mp, ans_2002, bahia, arabian, canola):\nfor obj in (ans_mp,):\n    print 'oil = ', obj.oil_name\n    print 'oil cut temps = ', oil_cut_temps(obj)\n    fractions = [c.fraction for c in obj.cuts]\n    print 'oil.cuts.fractions = ', fractions\n    f_res, f_asph = oil_inert_fractions(obj)\n    print 'f_res, f_asph = ', f_res, f_asph\n\n    fmasses = estimate_fmasses_from_cuts(fractions)\n    print 'sum(fmasses) = ', np.sum(fmasses) + f_res + f_asph\n\n    fmasses = estimate_n_fmasses(f_res, f_asph)\n    print 'sum(N fmasses) = ', np.sum(fmasses) + f_res + f_asph\n    \n    fmasses = oil_fmasses(obj)\n    print 'sum(oil_fmasses()) = ', np.sum(fmasses) + f_res + f_asph\n    print\n\n```\n\n    oil =  ALASKA NORTH SLOPE (MIDDLE PIPELINE)\n    oil cut temps =  [ 313.15  353.15  393.15  433.15  473.15  573.15  673.15  773.15  873.15\n      973.15]\n    oil.cuts.fractions =  [0.03, 0.07, 0.13, 0.19, 0.25, 0.42, 0.6, 0.76, 0.88, 0.95]\n    f_res, f_asph =  0.0766216397354 0.0169777627026\n    sum(fmasses) =  1.04359940244\n    sum(N fmasses) =  1.0\n    sum(oil_fmasses()) =  1.04359940244\n    \n\n\n### 16. Normalizing our Distillation Cut Data:\n\nBecause there are so many calculations that propagate from the distillation cuts, it is important that we interpret them in such a way that results in a reasonable, or at least plausible, distillation curve.  And since we are dealing with records that were manually entered into a database, data entry errors need to be anticipated.\n\nWe expect the evaporated fractions to be cumulative with rising temperature.  And if someone incorrectly entered a value when generating the imported oil record, then our cut data could fail to follow this cumulative trend, and our evaporation curve is thrown off.  Some specific errors and their implications are:\n\n- <b>Smaller fraction</b> entered than what it should have been: This will likely cause the fraction to be smaller than the previous one, and the $fmass_i$ value will go negative.\n- <b>Bigger fraction</b> entered than what it should have been: This will likely cause the next fraction to be smaller, and the next $fmass_i$ value will go negative.\n- <b>Smaller temperature</b> entered than what it should have been: Optimistically the series of $(T_i, fevap_i)$ could be reordered by temperature.  But if we reorder a mistaken temperature, then the fraction will be mistakenly reordered as well, and the error will manifest itself in a similar way as a <b>bigger fraction</b>.\n\nI don't think we can treat this in a naive way.  \n\n- We need to treat the temperatures and their associated fractions as atomic units of data\n- Temperatures are required to be in ascending order.  If the temperature of a particular cut is lower than the previous, we throw out the cut.\n- Cut fractions might seem to be less consequential.  This will happen only once per error in the series, and we could simply clip the value to be $\\geq 0$.  But this will have implications in that the sum of the differences will add up to something bigger than the total evaporated amount, which we don't want.  It's probably better to just throw out the cut.\n\n\n```python\ndef oil_culled_cuts(imported_rec):\n    prev_temp = prev_fraction = 0.0\n    for c in imported_rec.cuts:\n        if c.vapor_temp_k < prev_temp:\n            continue\n\n        if c.fraction < prev_fraction:\n            continue\n\n        prev_temp = c.vapor_temp_k\n        prev_fraction = c.fraction\n\n        yield c\n\n# we need to redefine our cut temperatures function\n# to utilize our culled cuts instead of raw cuts.\ndef oil_cut_temps(imported_rec):\n    culled_cuts = list(oil_culled_cuts(imported_rec))\n\n    if len(culled_cuts) > 0:\n        return np.array([c.vapor_temp_k\n                         for c in culled_cuts])\n    elif imported_rec.api is not None:\n        return estimate_cut_temps_from_api(imported_rec.api)\n    else:\n        est_api = estimate_api_from_density(oil_density_at_temp(imported_rec, 288.15))\n        return estimate_cut_temps_from_api(est_api)\n\n# we need to redefine our cut fractions function\n# to utilize our culled cuts instead of raw cuts.\ndef oil_fmasses(imported_rec):\n    f_res, f_asph = oil_inert_fractions(imported_rec)\n    culled_cuts = list(oil_culled_cuts(imported_rec))\n\n    if len(culled_cuts) > 0:\n        fractions = [c.fraction for c in culled_cuts]\n        return estimate_fmasses_from_cuts(f_res, f_asph,\n                                          fractions\n                                          )\n    else:\n        return estimate_n_fmasses(f_res, f_asph)\n\nobj = ans_2002\nplt.figure(1, figsize=(12,6))\nplt.subplot(111)\n\nplt.plot(*zip(*[(c.vapor_temp_k, c.fraction) for c in obj.cuts]) + ['ro'],\n         label=ans_2002.oil_name)\nplt.plot(*zip(*[(c.vapor_temp_k, c.fraction) for c in obj.cuts]) + ['r-'])\n\nplt.plot(*zip(*[(c.vapor_temp_k, c.fraction) for c in oil_culled_cuts(obj)]) + ['bo'],\n         label=ans_2002.oil_name + ' culled')\nplt.plot(*zip(*[(c.vapor_temp_k, c.fraction) for c in oil_culled_cuts(obj)]) + ['b-'])\n\nplt.xlabel(r'$T_i$')\nplt.ylabel('% Evap')\nplt.grid()\nplt.title(r'Distillation Cuts Comparison', fontsize=18)\n\nplt.legend(loc='upper left')\n```\n\nNot only do we seem to have typographic errors in the distillation cut data, but we have incomplete representation of distillation.  The cut data of some oil records have a maximum distillation amount that is considerably less than the total oil, and the inert fractions, calculated or read from the record, do not account for a complete fraction (1.0) of oil mass.\n\nI will suggest this for our distillation curves.  I think we need to calculate the maximum amount we expect to be evaporated with our distillation cuts.  Call it $fevap_{max}$.  We can obtain this from the following equation:\n$$\n\\begin{align}\nfevap_{max} &= 1 - f_{res} - f_{asph} \\cr\n\\end{align}\n$$\n\n\nThen we take the culled distillation cuts that exist, and use them to approximate a linear curve of our fractional distillation.  I believe Bill, Robert, and Chris would agree that the distillation data approximates a linear curve of the form $(ax + b)_{\\bot 0}^{\\top 1}$.  But just for fun, we will also try a sigmoid.\n\n\n```python\nplt.figure(1, figsize=(12,6))\nplt.subplot(111)\n\nobj = ans_2002\n\nboiling_points = [c.vapor_temp_k for c in oil_culled_cuts(obj)]\ncum_fractions = [c.fraction for c in oil_culled_cuts(obj)]\nplt.plot(boiling_points, cum_fractions, '.b', label=\"Cut Fractions\")\n\nplt.xlabel(r'$T_i$', fontsize=16)\nplt.ylabel(r'$f_{evap}$', fontsize=16)\nplt.grid()\n\n#def func(x, a, b, c, d):\n#    return a*x**3 + b*x**2 +c*x + d\n\ndef sigmoid(x, j, k, lamb):\n    # intuitively, our cut fractions could approximate\n    # a similar shape as a cumulative distribution function\n    # or sigmoid.\n    return (1.0 - j ** (-1.0 * (x / lamb) ** k))\n\ndef linear(x, a, b):\n    # intuitively, our cut fractions could approximate\n    # a similar shape as a linear function.\n    return (a * x + b)\n\n\nnew_bps = np.linspace(100., 1200., 100)\n\n\"\"\"\n    curve_fit the sigmoid\n\"\"\"\nif len(boiling_points) >= 3:\n    popt, pcov = curve_fit(sigmoid, boiling_points, cum_fractions)\n    plt.title(r'$f(T_i)= '\n              '1 - {0}^{{-(T_i / {2})^{{{1}}} }} + '\n              '$'.format(*popt),\n              fontsize=18)\n\n    # now plot our sigmoid curve with a bunch of boiling points from 273K to 1015K\n    plt.plot(new_bps, sigmoid(new_bps, *popt), '-r', label=\"Fitted Sigmoid Curve\")\nelse:\n    print 'not enough data for a sigmoid!'\n\n\"\"\"\n    curve_fit the linear\n\"\"\"\npopt, pcov = curve_fit(linear, boiling_points, cum_fractions)\n\n# now plot our linear curve with a bunch of boiling points from 273K to 1015K\nplt.plot(new_bps, np.clip(linear(new_bps, *popt), 0.0, 1.0), '-g', label=\"Fitted Linear Curve\")\n\nplt.legend(loc='upper left')\n\n```\n\nOkay, the linear curve seems to fit somewhat better, although it would be interesting to test this with a lot of oils.  We'll go with the linear fit for now.\n\nWhat we would like to do now is inverse the linear curve function so that it will calculate the temperature at which a certain fraction has boiled off.  Then we can take a set of N fractions that represent equidistant intervals between 0.0 and $fevap_{max}$.\n\nOur inverse linear function looks like this:\n$$\n\\begin{align}\nx &= {y - b \\over a} \\cr\n\\end{align}\n$$\n\n\n```python\nplt.figure(1, figsize=(12,6))\nax = plt.subplot(111)\n\nobj = ans_2002\n#print list(oil_culled_cuts(ans_2002))\nnum_cuts = 10\nboiling_points = [c.vapor_temp_k for c in oil_culled_cuts(obj)]\ncum_fractions = [c.fraction for c in oil_culled_cuts(obj)]\nf_res, f_asph = oil_inert_fractions(obj)\n\n\n'''\n    plot the cut points\n'''\nplt.plot(cum_fractions, boiling_points, 'ro', label=\"Measured Cuts\")\n\nplt.xlabel(r'$f_{evap,i}$', fontsize=18)\nplt.ylabel(r'$T_i$', fontsize=18)\nplt.grid()\n\ndef linear(x, a, b):\n    return (a * x + b)\n\ndef inverse_linear(y, a, b):\n    return (y - b) / a\n\n\"\"\"\n    curve_fit the linear\n\"\"\"\npopt, pcov = curve_fit(linear, boiling_points, cum_fractions)\nplt.title(r'$T_i = '\n          '(f_{{evap,i}} - {1}) / {0}'\n          '$'.format(*popt),\n          fontsize=18)\n\n# now plot our inverse linear curve with a bunch of fractions from 0.0001 to 0.9999\nnew_fracs = np.linspace(0.0001, 0.9999, 100)\nplt.plot(new_fracs, inverse_linear(new_fracs, *popt), '-c', label=\"Fitted Curve\")\n\n# now plot our inverse linear curve with the N fractions we intend to use\nnew_fracs = np.linspace(0.0, 1.0 - f_res - f_asph, num_cuts + 1)[1:]\nplt.plot(new_fracs, inverse_linear(new_fracs, *popt), 'go', label=\"Estimated Cuts\")\n\n# make the shaded region\nlow, high = 1.0 - f_res - f_asph, 1.0\nix = (low, high)\niy = (1000.0, 1000.0)\nverts = [(low,0)] + list(zip(ix,iy)) + [(high,0)]\npoly = Polygon(verts, facecolor='0.8', edgecolor='k')\nax.add_patch(poly)\n\n# ticks for the shaded region\nextraticks = [low,]\nextralabels = [r'${f_{inert}}$',]\nplt.xticks(list(plt.xticks()[0]) + extraticks,\n           list(plt.xticks()[0]) + extralabels)\n\nfor tick in ax.xaxis.get_major_ticks():\n    if tick.label.get_text().find('inert') >= 0:\n        tick.label.set_fontsize(14)\n        tick.label.set_rotation('vertical')\n\nplt.legend(loc='upper left')\n\n```\n\nAlright, that doesn't look too bad, but we are still missing something.\n\nFirst, it is possible for us to fit a curve that will give negative kelvin temperatures.  Negative Kelvin temperatures, are of course impossible.  We need to make sure our curve fit anticipates that.\n\nWhat we have works ok for total evaporated amounts, and differencing them should give us reasonable values for $fmass_i$.  But the temperatures we get from our curve represent only the maximum slice of distilled components within $fmass_i$.  What we really need is the average temperature from $T_{i-1}$ to $T_i$\n\n\n```python\nplt.figure(1, figsize=(12,6))\nax = plt.subplot(111)\n\nobj = ans_2002\n#print list(oil_culled_cuts(ans_2002))\nnum_cuts = 10\nboiling_points = [c.vapor_temp_k for c in oil_culled_cuts(obj)]\ncum_fractions = [c.fraction for c in oil_culled_cuts(obj)]\nf_res, f_asph = oil_inert_fractions(obj)\nprint 'boiling_points:', boiling_points\nprint 'cum_fractions:', cum_fractions\nprint 'inert_fractions:', f_res, f_asph\n\nplt.xlabel('% Evap')\nplt.ylabel(r'$T_i$', fontsize=16)\nplt.grid()\n\ndef linear(x, a, b):\n    return (a * x + b)\n\ndef inverse_linear(y, a, b):\n    return (y - b) / a\n\n\"\"\"\n    curve_fit the linear\n\"\"\"\npopt, pcov = curve_fit(linear, boiling_points, cum_fractions)\n\n# plot our distillation curve\nnew_fracs = np.linspace(0.0001, 0.9999, 100)\nnew_temps = np.clip(inverse_linear(new_fracs, *popt), 0.0, 5000.0)\nplt.plot(new_fracs, new_temps, '-b', label=\"Distillation Curve\")\n\n# now plot the N fractions we intend to use\nnew_fracs = np.linspace(0.0, 1.0 - f_res - f_asph, (num_cuts * 2) + 1)[1:]\nnew_temps = inverse_linear(new_fracs, *popt)\n\nnew_fracs = new_fracs.reshape(-1,2)[:,1]\nnew_temps = new_temps.reshape(-1,2)[:,0]\nabove_zero = new_temps > 0.0\nnew_temps = new_temps[above_zero]\nnew_fracs = new_fracs[above_zero]\n\nplt.plot(new_fracs, new_temps, 'go', label=\"Estimated Cuts\")\n\n# plot our inert fraction\nplt.plot(1.0, 1015.0, 'go')\n\n# now we would like to graph the quantized \"areas\"\n# that our fractional masses represent\ndef make_shaded_region(f_low, f_high,\n                       t_low, t_high,\n                      facecolor='0.8'):\n    ix = (f_low, f_high)\n    iy = (t_low, t_high)\n    verts = [(x, y) for x in ix for y in iy]\n    verts[2:] = reversed(verts[2:])\n    poly = Polygon(verts, facecolor=facecolor, edgecolor='k')\n    ax.add_patch(poly)\n\nfor r in zip([0.0] + new_fracs.tolist(),\n             new_fracs,\n             [inverse_linear(0.0, *popt)] + new_temps.tolist(),\n             new_temps):\n    make_shaded_region(*r, facecolor='#ddeeff')\n\n# make the shaded region for our inert fraction\nmake_shaded_region(new_fracs[-1], 1.0,\n                   new_temps[-1], 1015.0)\n\n# ticks for the shaded region\nextraticks = [low,]\nextralabels = [r'${f_{inert}}$',]\nplt.xticks(list(plt.xticks()[0]) + extraticks,\n           list(plt.xticks()[0]) + extralabels)\n\nfor tick in ax.xaxis.get_major_ticks():\n    if tick.label.get_text().find('inert') >= 0:\n        tick.label.set_fontsize(16)\n        tick.label.set_rotation('vertical')\n\nplt.legend(loc='upper left')\n\n```\n\nAlright, **now** this looks like a reasonable quantization of our distillation curve.\n\nputting it all together in code...\n\n\n```python\ndef linear_curve(x, a, b):\n    return (a * x + b)\n\ndef inverse_linear_curve(y, a, b):\n    return (y - b) / a\n\ndef oil_normalized_cut_values(imported_rec, num_cuts=10):\n    f_res, f_asph = oil_inert_fractions(imported_rec)\n    \n    culled_cuts = list(oil_culled_cuts(imported_rec))\n\n    if len(culled_cuts) == 0:\n        if imported_rec.api is not None:\n            oil_api = imported_rec.api\n        else:\n            oil_rho = oil_density_at_temp(imported_rec, 288.15)\n            oil_api = estimate_api_from_density(oil_rho)\n\n        BP_i = estimate_cut_temps_from_api(oil_api)\n        fevap_i = np.cumsum(estimate_n_fmasses(f_res, f_asph))\n    else:\n        BP_i, fevap_i = zip(*[(c.vapor_temp_k, c.fraction)\n                              for c in culled_cuts])\n\n    popt, pcov = curve_fit(linear_curve, BP_i, fevap_i)\n\n    fevap_i = np.linspace(0.0, 1.0 - f_res - f_asph, (num_cuts * 2) + 1)[1:]\n    T_i = np.clip(inverse_linear(fevap_i, *popt), 0.0, 5000.0)\n\n    fevap_i = fevap_i.reshape(-1,2)[:,1]\n    T_i = T_i.reshape(-1,2)[:,0]\n\n    above_zero = T_i > 0.0\n    T_i = T_i[above_zero]\n    fevap_i = fevap_i[above_zero]\n\n    return T_i, fevap_i\n\ndef oil_normalized_cut_temps(imported_rec, num_cuts=10):\n    cut_temps, _f_evap_i = oil_normalized_cut_values(imported_rec)\n    \n    return cut_temps\n\ndef oil_normalized_cut_fmasses(imported_rec, num_cuts=10):\n    _cut_temps, f_evap_i = oil_normalized_cut_values(imported_rec)\n    \n    return estimate_fmasses_from_cuts(f_evap_i)\n\ndef oil_normalized_cut_temps_fmasses(imported_rec, num_cuts=10):\n    cut_temps, f_evap_i = oil_normalized_cut_values(imported_rec)\n    \n    return cut_temps, estimate_fmasses_from_cuts(f_evap_i)\n\n\n\n#for obj in (ans_mp, ans_2002, bahia, arabian, canola):\nfor obj in (ans_mp,):\n    print 'oil = ', obj.oil_name\n    print 'oil.api = ', obj.api\n    print 'oil cut temps = ', oil_cut_temps(obj)\n    fractions = [c.fraction for c in oil_culled_cuts(obj)]\n    print 'oil.cuts.fractions = ', fractions\n    f_res, f_asph = oil_inert_fractions(obj)\n    print 'f_res, f_asph = ', f_res, f_asph\n    if len(fractions) > 0:\n        print ('sum of all non-normalized fractions = {}'\n               .format(fractions[-1] + f_res + f_asph))\n    else:\n        print 'No measured fractions found.'\n\n    print ('normalized fmasses = {}'\n           .format(oil_normalized_cut_fmasses(obj) + f_res + f_asph))\n    print ('sum of all normalized fmasses = {}'\n           .format(np.sum(oil_normalized_cut_fmasses(obj)) + f_res + f_asph))\n    print\n\n```\n\n    oil =  ALASKA NORTH SLOPE (MIDDLE PIPELINE)\n    oil.api =  29.9\n    oil cut temps =  [ 313.15  353.15  393.15  433.15  473.15  573.15  673.15  773.15  873.15\n      973.15]\n    oil.cuts.fractions =  [0.03, 0.07, 0.13, 0.19, 0.25, 0.42, 0.6, 0.76, 0.88, 0.95]\n    f_res, f_asph =  0.0766216397354 0.0169777627026\n    sum of all non-normalized fractions = 1.04359940244\n    normalized fmasses = [ 0.18423946  0.18423946  0.18423946  0.18423946  0.18423946  0.18423946\n      0.18423946  0.18423946  0.18423946  0.18423946]\n    sum of all normalized fmasses = 1.0\n    \n\n\n## <u>Oil Component Fractional Properties</u>\n\nOnce we have estimated the distilled and inert fractions of our oil, we can then begin to break it down even further, into SARA component fractional properties.  This will include:\n\n- Component Molecular Weight\n- Component Density\n- Component Specific Gravity <i>(basically a representation of density)</i>\n- Saturate and Aromatic Mass Fractions <i>(we have already estimated our resins & asphaltenes, and they will not change)</i>\n\nWe will organize our components in arrays that are consistently ordered so that all properties of any particular component will share a common index.  The ordering will be as follows:\n\n$$\n\\begin{align}\n[\n&C_{sat,0} \\, C_{arom,0} \\cr\n&C_{sat,1} \\, C_{arom,1} \\cr\n&C_{sat,2} \\, C_{arom,2} \\cr\n&... \\cr\n&C_{sat,N} \\, C_{arom,N} \\cr\n&C_{res} \\, C_{asph} ] \\cr\n\\end{align}\n$$\n\n### 17. Component Temperatures:\n\nHere we will define a temperature for each of our components.  This is a fairly straight forward copy of the cut temperatures in regards to the saturate and aromatic components.\n\nBut our resins and asphaltenes need a temperature too.  We will choose a default value of $1015^\\circ K$ for them.\n\n\n```python\ndef oil_component_temps(imported_rec):\n    cut_temps = oil_normalized_cut_temps(imported_rec)\n\n    component_temps = np.append([1015.0, 1015.0],\n                                zip(cut_temps, cut_temps))\n    return np.roll(component_temps, -2)\n\n```\n\n### 18. Initial Component Molecular Weight:\n\n<i>\nReference: CPPF eq. 2.48 and table 2.6\n</i>\n\nThe saturate and aromatic component molecular weights can be calculated using the distillation cut temperatures as follows:\n\n$$\n\\begin{align}\nM_{w,sat,i} &= \\left( 49.677 \\cdot \\left[ 6.98291 - ln(1070 - T_i) \\right] \\right)^{3/2}\n\\qquad \\qquad \\qquad \\boldsymbol{(eq. 15)} \\cr\nM_{w,arom,i} &= \\left( 44.504 \\cdot \\left[ 6.911 - ln(1015 - T_i) \\right] \\right)^{3/2}\n\\qquad \\qquad \\qquad \\boldsymbol{(eq. 16)} \\cr\n\\end{align}\n$$\n\nSo that we have a full complement of molecular weights for <u>all</u> components, We need some estimation method for our resins and asphaltenes.  Bill recommends using the following average values:\n$$\n\\begin{align}\nM_{w,res} &= \\text{molecular weight of our resin component} \\cr\n&= 800 \\, g/mol \\text{ at } 1015^\\circ K \\cr\nM_{w,asph} &= \\text{molecular weight of our asphaltene component} \\cr\n&= 1000 \\, g/mol \\text{ at } 1015^\\circ K \\cr\n\\end{align}\n$$\n\n\n```python\ndef estimate_saturate_mol_wt(boiling_point):\n    T_i = np.array(boiling_point)\n    return (49.677 * (6.98291 - np.log(1070.0 - T_i))) ** (3.0 / 2.0)\n\ndef estimate_aromatic_mol_wt(boiling_point):\n    T_i = np.array(boiling_point)\n    return (44.504 * (6.911 - np.log(1015.0 - T_i))) ** (3.0 / 2.0)\n\ndef estimate_resin_mol_wt():\n    return 800.0\n\ndef estimate_asphaltene_mol_wt():\n    return 1000.0\n\ndef estimate_component_mol_wt(boiling_points):\n    rho_list = np.append([estimate_resin_mol_wt(),\n                          estimate_asphaltene_mol_wt()],\n                         zip(estimate_saturate_mol_wt(boiling_points),\n                             estimate_aromatic_mol_wt(boiling_points)))\n    return np.roll(rho_list, -2)\n\ndef oil_component_mol_wt(imported_rec):\n    cut_temps = oil_normalized_cut_temps(imported_rec)\n\n    return estimate_component_mol_wt(cut_temps)\n\n\n#for obj in (ans_mp, ans_2002, bahia, arabian, canola):\nfor obj in (ans_mp,):\n    print 'oil = ', obj.oil_name\n    print 'component mol_wt = ', oil_component_mol_wt(obj).reshape(-1,2)\n    print\n\n```\n\n    oil =  ALASKA NORTH SLOPE (MIDDLE PIPELINE)\n    component mol_wt =  [[   79.87780305    69.12113917]\n     [  108.64997116    95.83581338]\n     [  143.29934679   128.44923122]\n     [  185.03374123   168.31003924]\n     [  235.5421871    217.36221559]\n     [  297.24730182   278.50203314]\n     [  373.75782192   356.26148978]\n     [  470.73764917   458.24068943]\n     [  597.74261583   598.52643549]\n     [  772.66404782   807.61243414]\n     [  800.          1000.        ]]\n    \n\n\n### 19. Component Density:\n\n<i>\nReference: CPPF eq. 2.13 and table 9.6\n</i>\n\nInitial density estimate for both resin and asphaltene fractional componens is set to:\n\n$$\n\\begin{align}\n\\rho_{res} &= \\rho_{asph} = 1100 \\, kg/m^3 \\cr\n\\end{align}\n$$\n\nThen we define Watson characterization factors for saturates and aromatics:\n\n$$\n\\begin{align}\nK_{arom,w} &= \\text{Watson characterization factor for aromatics} \\cr\n&= 10 \\cr\nK_{sat,w} &= \\text{Watson characterization factor for saturates} \\cr\n&= 12 \\cr\n\\end{align}\n$$\n\nThen we apply the appropriate Watson characterization to calculate an initial trial estimate for each density component:\n\n$$\n\\begin{align}\nT_i &= \\text{component boiling point } (\\,^\\circ K) \\cr\n\\cr\n\\rho try_{arom,i} &= 1000 \\cdot {\\root 3 \\of { 1.8 \\cdot T_i} \\over K_{arom,w} }\n\\qquad \\qquad \\boldsymbol{(eq. 17)} \\cr\n\\rho try_{sat,i} &= 1000 \\cdot {\\root 3 \\of { 1.8 \\cdot T_i} \\over K_{sat,w} }\n\\qquad \\qquad \\boldsymbol{(eq. 18)} \\cr\n\\end{align}\n$$\n\nThis should be a reasonable estimate.  However, the average density (fractionally weighted average of the component densities) must match the measured value or the value from approximation (eqs. 1, 2).<br>\nTo find the scaling factor between our densities and the aggregate density, we do the following:\n\n$$\n\\begin{align}\nj &= \\text{index representing all oil components } \\{ j \\in \\Bbb Z \\} \\cr\njMAX &= \\text{index of the last oil component} \\cr\n&= 2N + 2 \\cr\nfmass0_j &= \\text{the fractional mass of our jth component} \\cr\n\\cr\nCf_{dens} &= { \\rho 0_{oil} \\over \\sum_{j=1}^{jMAX} fmass0_j \\cdot \\rho try_j}\n\\qquad \\qquad \\boldsymbol{(eq. 19)} \\cr\n\\end{align}\n$$\n\nThen we evenly apply this scaling factor to our trial densities to come up with densities that are consistent with the aggregate density.\n\n$$\n\\begin{align}\n\\rho_j = Cf_{dens} \\cdot \\rho try_j \\qquad \\qquad \\boldsymbol{(eq. 20)} \\cr\n\\end{align}\n$$\n\n<center><b>--- Begin JamesM Comments ---</b></center>\n\nWell, I don't know about the resin & asphaltene densities.  It seems that at the higher temperatures, the Aromatic densities get slightly denser than the inert components.  This doesn't seem right.\n\n<center><b>--- End JamesM Comments ---</b></center>\n\n\n```python\ndef estimate_trial_densities(boiling_points, watson_factor):\n    return 1000.0 * (1.8 * boiling_points) ** (1.0 / 3.0) / watson_factor\n\ndef estimate_saturate_densities(boiling_points):\n    return estimate_trial_densities(boiling_points, 12)\n\ndef estimate_aromatic_densities(boiling_points):\n    return estimate_trial_densities(boiling_points, 10)\n\ndef estimate_resin_density():\n    return 1100.0\n\ndef estimate_asphaltene_density():\n    return 1100.0\n\ndef estimate_component_densities(boiling_points):\n    rho_list = np.append([estimate_resin_density(),\n                          estimate_asphaltene_density()],\n                         zip(estimate_saturate_densities(boiling_points),\n                             estimate_aromatic_densities(boiling_points)))\n    return np.roll(rho_list, -2)\n\ndef oil_component_densities(imported_rec):\n    cut_temps = oil_normalized_cut_temps(imported_rec)\n    return estimate_component_densities(cut_temps)\n    \n\n#for obj in (ans_mp, ans_2002, bahia, arabian, canola):\nfor obj in (ans_mp,):\n    print 'oil = ', obj.oil_name\n    print 'component densities from oil = ', oil_component_densities(obj).reshape(-1, 2)\n    print\n\n```\n\n    oil =  ALASKA NORTH SLOPE (MIDDLE PIPELINE)\n    component densities from oil =  [[  698.98635463   838.78362555]\n     [  739.55939262   887.47127114]\n     [  776.11098612   931.33318334]\n     [  809.51024975   971.41229971]\n     [  840.3598753   1008.43185036]\n     [  869.09696831  1042.91636197]\n     [  896.04981383  1075.25977659]\n     [  921.47197405  1105.76636886]\n     [  945.56384999  1134.67661999]\n     [  968.48689805  1162.18427766]\n     [ 1100.          1100.        ]]\n    \n\n\n### 20. Component Specific Gravity:\n\nSpecific Gravity of a substance is the ratio of density of the substance to the density of another substance (typically water) at a specified temperature.<br>\n\n<i>\nReference: https://en.wikipedia.org/wiki/Specific_gravity\n</i>\n\nFor simplicity, we will make the assumption that our water density is $1000 \\, kg/m^3$.  This is water's density at $4^\\circ C$, Which is the maximum density it can achieve.<br>\nSo our estimation of the specific gravity of our oil components will be:\n\n$$\n\\begin{align}\nSG_j &= \\rho_j / 1000 \\qquad \\qquad \\boldsymbol{(eq. 21)} \\cr\n\\end{align}\n$$\n\n\n```python\ndef estimate_specific_gravity(rho_kg_m_3):\n    return rho_kg_m_3 / 1000.0\n\ndef oil_component_specific_gravity(imported_rec):\n    rho_list = oil_component_densities(imported_rec)\n    \n    return estimate_specific_gravity(rho_list)\n\n\n#for obj in (ans_mp, ans_2002, bahia, arabian, canola):\nfor obj in (ans_mp,):\n    print 'oil = ', obj.oil_name\n    print 'specific gravity = ', oil_component_specific_gravity(obj).reshape(-1, 2)\n    print\n\n```\n\n    oil =  ALASKA NORTH SLOPE (MIDDLE PIPELINE)\n    specific gravity =  [[ 0.69898635  0.83878363]\n     [ 0.73955939  0.88747127]\n     [ 0.77611099  0.93133318]\n     [ 0.80951025  0.9714123 ]\n     [ 0.84035988  1.00843185]\n     [ 0.86909697  1.04291636]\n     [ 0.89604981  1.07525978]\n     [ 0.92147197  1.10576637]\n     [ 0.94556385  1.13467662]\n     [ 0.9684869   1.16218428]\n     [ 1.1         1.1       ]]\n    \n\n\n### 21. Initial Saturate and Aromatic Mass Fractions:\n\n<i>\nReferences:\n  <ul>\n    <li>CPPF eqs. 2.114, 2.115, 3.77 and 3.78</li>\n    <li>Huang, E K., Characterization and Thermodynamic Correlations for Undefined Hydrocarbon Mixtures, Ph.D. Dissertation, Pennsylvania State University, University Park, PA, 1977</li>\n  </ul>\n</i>\n\nWe start by computing our saturate mass fractions.  This is done using the distillation cuts, and the specific gravity, and molecular weight of our saturate components.\n\nUsing Riazi, we perform a number of intermediate calculations to finally come up with the estimation for saturate component fractional mass.\n\nFirst is a dimensionless parameter $I$, that was first used by Huang to correlate hydrocarbon properties.  This is necessary to calculate the saturate refractive index $n$.<br>\n\nNext is the calculation of refractive index $n$.  This is necessary to calculate $m$.\n\nThe next intermediate calculation $m$ can be best described as a hydrocarbon grouping parameter, Riazi describes $m$ as a parameter that \"not only separates paraffins and aromatics but also identifies various hydrocarbon types\", and is (AFAIK) based on an observed correlation of refractive index and Molecular weight.\n\n$$\n\\begin{align}\nT_i &= \\text{distillation cut boiling point} \\cr\nM_{w,sat,i} &= \\text{molecular weight of our saturate component} \\cr\nSG_{sat, i} &= \\text{specific gravity of saturate component} \\cr\n\\cr\nI &= \\text{hydrocarbon characterization parameter} \\cr\n&= 0.3773 T_i^{-0.02269} SG_{sat,i}^{0.9182} \\qquad \\qquad \\boldsymbol{(eq. 22)} \\cr\n\\cr\nn &= \\text{refractive index of our saturate component at } 20^\\circ C \\cr\n&= \\left( 1 + 2 I \\over 1 - I \\right)^{1/2} \\qquad \\qquad \\qquad \\qquad \\boldsymbol{(eq. 23)} \\cr\n\\cr\nm &= \\text{hydrocarbon grouping parameter} \\cr\n&= M_{w,sat,i}(n - 1.475) \\qquad \\qquad \\qquad \\boldsymbol{(eq. 24)} \\cr\n\\end{align}\n$$\n\nAnd finally, after these intermediate calculations are completed, we can estimate the saturate component fractional mass.\n\n\n$$\n\\begin{align}\nfmass_i &= \\text{distillation cut fractional mass} \\cr\n\\cr\nf_{sat,i} &= (fmass_i \\cdot (2.24 - 1.98 \\cdot SG_{sat,i} - 0.009 \\cdot m))_{\\bot 0}^{\\top fmass_i}\n\\qquad \\qquad \\boldsymbol{(eq. 25)} \\cr\n\\end{align}\n$$\n\nAfter our saturate mass fraction has been computed, we compute our aromatic mass fraction simply as:\n\n$$\n\\begin{align}\nf_{arom,i} &= fmass_i - f_{sat,i} \\qquad \\qquad \\qquad \\boldsymbol{(eq. 26)} \\cr\n\\end{align}\n$$\n\n\n```python\ndef hydrocarbon_characterization_param(specific_gravity, temp_k):\n    T_i = temp_k\n    SG_i = specific_gravity\n    return 0.3773 * (T_i ** -0.02269) * (SG_i ** 0.9182)\n\ndef refractive_index(hc_char_param):\n    I = hc_char_param\n    return ((1 + 2 * I) / (1 - I)) ** (1.0 / 2.0)\n\ndef hydrocarbon_grouping_param(mol_wt, specific_gravity, temp_k):\n    I = hydrocarbon_characterization_param(specific_gravity, temp_k)\n    n = refractive_index(I)\n\n    return mol_wt * (n - 1.475)\n\ndef estimate_saturate_mass_fraction(fmass_i, mol_wt, specific_gravity, temp_k):\n    SG_sat_i = specific_gravity\n    m = hydrocarbon_grouping_param(mol_wt, SG_sat_i, temp_k)\n    \n    X_P = 3.7387 - 4.0829 * SG_sat_i + 0.014772 * m\n    X_N = -1.5027 + 2.10152 * SG_sat_i - 0.02388 * m\n\n    f_sat_i = fmass_i * (X_P + X_N)\n    f_sat_i = np.clip(f_sat_i, 0.0, fmass_i)\n\n    return f_sat_i\n\ndef oil_component_mass_fractions(imported_rec):\n    f_res, f_asph = oil_inert_fractions(imported_rec)\n    cut_temps, fmass_i = oil_normalized_cut_temps_fmasses(imported_rec)\n\n    sat_mask = np.array(range(len(cut_temps))) * 2\n\n    sat_temps = oil_component_temps(imported_rec)[sat_mask]\n    sat_mol_wts = estimate_component_mol_wt(cut_temps)[sat_mask]\n    sat_rhos = estimate_component_densities(cut_temps)[sat_mask]\n    sat_SGs = estimate_specific_gravity(sat_rhos)\n\n    f_sat_i = estimate_saturate_mass_fraction(fmass_i,\n                                              sat_mol_wts,\n                                              sat_SGs,\n                                              sat_temps)\n    f_arom_i = fmass_i - f_sat_i\n\n    f_all = [n for l in zip(f_sat_i, f_arom_i) for n in l] + [f_res, f_asph]\n    \n    return np.array(f_all)\n\n#for obj in (ans_mp, ans_2002, bahia, arabian, canola):\nfor obj in (ans_mp,):\n    print 'oil = ', obj.oil_name\n    print 'oil.cuts.fractions = ', [c.fraction for c in obj.cuts]\n    print 'oil.cuts.vapor_temp_k = ', [c.vapor_temp_k for c in obj.cuts]\n    print 'component mass fractions = ', oil_component_mass_fractions(obj).reshape(-1, 2)\n    print 'sum(component mass fractions) = ', np.sum(oil_component_mass_fractions(obj))\n    print\n\n```\n\n    oil =  ALASKA NORTH SLOPE (MIDDLE PIPELINE)\n    oil.cuts.fractions =  [0.03, 0.07, 0.13, 0.19, 0.25, 0.42, 0.6, 0.76, 0.88, 0.95]\n    oil.cuts.vapor_temp_k =  [313.15, 353.15, 393.15, 433.15, 473.15, 573.15, 673.15, 773.15, 873.15, 973.15]\n    component mass fractions =  [[ 0.08261257  0.00802749]\n     [ 0.07533448  0.01530558]\n     [ 0.06816963  0.02247043]\n     [ 0.06080267  0.02983739]\n     [ 0.05291778  0.03772228]\n     [ 0.04415324  0.04648682]\n     [ 0.0340444   0.05659566]\n     [ 0.02192987  0.06871019]\n     [ 0.00676619  0.08387387]\n     [ 0.          0.09064006]\n     [ 0.07662164  0.01697776]]\n    sum(component mass fractions) =  1.0\n    \n\n\n<center><b>--- Begin JamesM Comments ---</b></center>\n\nAfter staring at Riazi's equations for awhile and reading the surrounding descriptions, I am not convinced that we should be using $M_{w,sat,i}$ and $SG_{sat,i}$ for computing the saturate fractional mass.  Instead, I think it is possible that we should use the average molecular weight and specific gravity of the distillation cut.<br>\nThat is, if we can determine it.\n$$\n\\begin{align}\nfmass_i &= \\text{distillation cut fractional mass} \\cr\nT_i &= \\text{distillation cut boiling point} \\cr\nM_{w,i} &= \\text{distillation cut molecular weight} \\cr\nSG_i &= \\text{distillation cut specific gravity} \\cr\n\\cr\nI &= 0.3773 T_i^{-0.02269} SG_i^{0.9182} \\cr\n\\cr\nn &= \\left( 1 + 2 I \\over 1 - I \\right)^{1/2} \\cr\n\\cr\nm &= M_{w,i}(n - 1.475) \\cr\n\\cr\nf_{sat,i} &= (fmass_i \\cdot (2.24 - 1.98 \\cdot SG_i - 0.009 \\cdot m))_{\\bot 0}^{\\top fmass_i} \\cr\n\\end{align}\n$$\n\nI am not sure, but it might be possible to do the following:\n\n- Start by assuming a 50/50 mix of saturates and aromatics for a particular cut\n- Estimate the aggregate molecular weight and specific gravity of our mix\n- Figure out the saturate and aromatic fractions using the Riazi correlation\n- Repeat using the newly calculated mix until the mix converges (will it converge?)\n\n\n```python\n\ndef verify_cut_fractional_masses(fmass_i, T_i,\n                                 f_sat_i, f_arom_i):\n    assert np.all(fmass_i == f_sat_i + f_arom_i)\n\n    M_w_sat_i = estimate_saturate_mol_wt(T_i)\n    M_w_arom_i = estimate_aromatic_mol_wt(T_i)\n\n    M_w_avg_i = (M_w_sat_i * f_sat_i / fmass_i +\n                 M_w_arom_i * f_arom_i / fmass_i)\n\n    # estimate specific gravity\n    rho_sat_i = estimate_saturate_densities(T_i)\n    SG_sat_i = estimate_specific_gravity(rho_sat_i)\n\n    rho_arom_i = estimate_aromatic_densities(T_i)\n    SG_arom_i = estimate_specific_gravity(rho_arom_i)\n\n    SG_avg_i = (SG_sat_i * f_sat_i / fmass_i +\n                SG_arom_i * f_arom_i / fmass_i)\n\n    f_sat_i = estimate_saturate_mass_fraction(fmass_i,\n                                              M_w_avg_i,\n                                              SG_avg_i,\n                                              T_i)\n    f_arom_i = fmass_i - f_sat_i\n    \n    # Riazi states that CPPF eqs. 3.77 and 3.78 only work with\n    # molecular weights less than 200.  So we will punt\n    # with Bill's recommendation of 50/50 in those cases.\n    # In the future we might be able to figure out how\n    # to implement CPPF eqs. 3.81 and 3.82, which work with\n    # the molecular weights above 200.\n    above_200 = M_w_avg_i > 200.0\n    try:\n        f_sat_i[above_200] = fmass_i[above_200] / 2.0\n        f_arom_i[above_200] = fmass_i[above_200] / 2.0\n    except TypeError:\n        # numpy array assignment failed, try a scalar assignment\n        if above_200:\n            f_sat_i = fmass_i / 2.0\n            f_arom_i = fmass_i / 2.0\n        \n\n    return f_sat_i, f_arom_i\n\nfmass_i, f_sat_i, f_arom_i = 1.0, 0.5, 0.5\nprint f_sat_i, f_arom_i\nfor i in range(20):\n    f_sat_i, f_arom_i = verify_cut_fractional_masses(fmass_i, 313.15,\n                                                     f_sat_i, f_arom_i)\n    print f_sat_i, f_arom_i\n\n```\n\n    0.5 0.5\n    0.765877772496 0.234122227504\n    0.853589462036 0.146410537964\n    0.882725805954 0.117274194046\n    0.892426356465 0.107573643535\n    0.895658449095 0.104341550905\n    0.896735607832 0.103264392168\n    0.897094622141 0.102905377859\n    0.897214284029 0.102785715971\n    0.897254168511 0.102745831489\n    0.897267462441 0.102732537559\n    0.897271893457 0.102728106543\n    0.897273370364 0.102726629636\n    0.897273862634 0.102726137366\n    0.897274026714 0.102725973286\n    0.897274081403 0.102725918597\n    0.897274099632 0.102725900368\n    0.897274105708 0.102725894292\n    0.897274107733 0.102725892267\n    0.897274108408 0.102725891592\n    0.897274108633 0.102725891367\n\n\nWell, it does seem to converge, at least with the example above.  Let's try plotting an oil record.\n\n\n```python\nplt.figure(1, figsize=(12,6))\nplt.subplot(111)\n\nobj = ans_mp\n\nplt.xlabel(r'$T_i$', fontsize=16)\nplt.ylabel(r'$f_{sat,i}$', fontsize=16)\nplt.grid()\nplt.title(r'Convergence of $f_{{sat,i}}$ for oil {}'.format(obj.oil_name),\n          fontsize=18)\n\n#for obj in (ans_mp, ans_2002, bahia, arabian, canola):\ncut_temps, fmass_i = oil_normalized_cut_temps_fmasses(obj)\n\nf_sat_i = fmass_i / 2.0\nf_arom_i = fmass_i / 2.0\n\nlabel=r'Initial $f_{sat,i}$'\ncolor, linestyle, marker = 'b', 'None', 'o'\nplt.plot(cut_temps, f_sat_i,\n         color=color, linestyle=linestyle, marker=marker, label=label)\n\nfor i in range(20):\n    color, linestyle, marker = 'b', 'None', '.'\n    label=''\n\n    f_sat_i, f_arom_i = verify_cut_fractional_masses(fmass_i, cut_temps,\n                                                     f_sat_i, f_arom_i)\n\n    plt.plot(cut_temps, f_sat_i,\n             color=color, linestyle=linestyle, marker=marker, label=label)\n\ncolor, linestyle, marker = '#00ff00', 'None', 'o'\nlabel=r'Final $f_{sat,i}$'\nplt.plot(cut_temps, f_sat_i,\n         color=color, linestyle=linestyle, marker=marker, label=label)\ncolor, linestyle, marker = '#00ff00', '-', 'o'\nlabel=''\nplt.plot(cut_temps, f_sat_i,\n         color=color, linestyle=linestyle, marker=marker, label=label)\n\nplt.legend(loc='upper right')\n\n```\n\nWell, our saturate fractions do seem to converge into values that indicate the following:\n\n- There is an inversely proportional relationship with boiling point.  The trend looks more-or-less linear.\n- The temperature at which we achieve a 50/50 mix of saturates and aromatics appears to be somewhere around $470^\\circ K$.\n- The temperature at which we have lost all saturates is somewhere between $600^\\circ K$ and $630^\\circ K$. \n\nBut I can't be completely sure if this is how our saturates are supposed to behave.  For one thing, this would also indicate that the fraction of aromatics in our cuts would proportionally increase until about $600^\\circ K$ or so, where the distilled fractions become 100% aromatics.  Again, I can't be sure if this is how aromatics are supposed to behave.\n\nI think I will submit this line of thinking to Bill & Co. before actually putting this into our estimations code.\n\n<center><b>--- End JamesM Comments ---</b></center>\n\n## <u>Oil Miscellaneous Properties</u>\n\nThese are oil properties that can be computed based on the previous computations, and in some cases are simply assigned a default value.\n\n### 22. Oil-Water Surface Tension:\n\nIf the imported oil record does not contain a value for surface tension, then we will estimate it from the oil's API:\n\n$$\n\\begin{align}\n\\sigma_{o-w} &= \\text{oil/water surface tension at } 288.15^\\circ K \\,\\, (N/m) \\cr\n&= 0.001 \\cdot (39 - 0.2571 \\cdot API) \\qquad \\qquad \\qquad \\qquad \\boldsymbol{(eq. 27)} \\cr\n\\end{align}\n$$\n\n<i>\nReference: Baker, O. and W. Swerdloff (1956), Calculation of Surface Tensions - Finding the Surface Tension of Hydrocarbon Liquids, Oil Gas J. (2 January 1956) pp. 125\n</i>\n\n\n```python\ndef o_w_surface_tension_from_api(api):\n    if api is not None:\n        return 0.001 * (39.0 - 0.2571 * api)\n    else:\n        return None\n\ndef oil_o_w_surface_tension(imported_rec):\n    if (imported_rec.oil_water_interfacial_tension_n_m is not None and\n            imported_rec.oil_water_interfacial_tension_ref_temp_k is not None):\n        ow_st = imported_rec.oil_water_interfacial_tension_n_m\n        ref_temp_k = imported_rec.oil_water_interfacial_tension_ref_temp_k\n\n        return ow_st, ref_temp_k\n    elif imported_rec.api is not None:\n        ow_st = oil_water_surface_tension_from_api(imported_rec.api)\n\n        return ow_st, 273.15 + 15\n    else:\n        est_api = api_from_density(oil_density_at_temp(imported_rec, 288.15))\n        ow_st = oil_water_surface_tension_from_api(est_api)\n\n        return ow_st, 273.15 + 15\n\n#for obj in (ans_mp, ans_2002, bahia, arabian, canola):\nfor obj in (ans_mp,):\n    print 'oil = ', obj.oil_name\n    print 'oil/water surface tension = ', o_w_surface_tension_from_api(obj.api)\n    print 'oil/water surface tension = ', oil_o_w_surface_tension(obj)\n    print\n```\n\n    oil =  ALASKA NORTH SLOPE (MIDDLE PIPELINE)\n    oil/water surface tension =  0.03131271\n    oil/water surface tension =  (0.0238, 273.15)\n    \n\n\n### 23. Pour Point:\n\nIf the imported oil record contains a pour point property then we will simply use it when building the final oil record.<br>\nOtherwise, if we have measured molecular weights for the distillation fractions (unusual) then use method <b>(A)</b>.<br>\nOtherwise, use method <b>(B)</b>\n\n<b>(A)</b> If molecular weight and mass fractions are given for all the oil fractions $j = 1 \\dots jMAX$, then an average molecular weight for the whole oil $\\bar M_w$ can be estimated as:\n\n$$\n\\begin{align}\nN &= \\text{number of distillation cuts} \\cr\njMAX &= 2 (N + 1) \\cr\nM_{w,j} &= \\text{molecular weight of component j} (kg/kmole)\\cr\nfmass_j &= \\text{mass fraction of component j} \\cr\n\\cr\n\\bar M_w &= \\sum_1^{jMAX} M_{w,j} \\cdot fmass_j \\qquad \\qquad \\qquad \\qquad \\boldsymbol{(eq. 28)} \\cr\n\\end{align}\n$$\n\n<i>(Note: The calculation for $jMAX$ may seem counterintuitive. It simply states that we sum over all the SARA fractions, each distillation cut represents 1 saturate and 1 aromatic fraction, and that resins and asphaltenes do not have distillation cut data.  So for $N$ distillation cuts, we would calculate $2 N + 2 \\rightarrow 2(N + 1)$)</i>\n\nDefine $SG = \\rho_{oil} / 1000 \\cdot kg$ as specific gravity\n\nThen, using CPPF eq. 3.119, our pour point temperature is calculated as:\n\n$$\n\\begin{align}\nT_{API} &= \\text{reference temperature for oil kinematic viscosity} \\cr\n&= 311^\\circ K \\cr\n\\cr\nT_{pp} &= 130.47 SG^{2.97} \\cdot \\bar M_w^{0.61235 - 0.47357 SG} \\cdot v_{oil}^{0.31 - 0.3283 SG} \\cdot T_{API} \\qquad \\qquad \\boldsymbol{(eq. 29)} \\cr\n\\end{align}\n$$\n\n<b>(B)</b> Pour point is estimated by reversing the viscosity-temperature correction in Adios2 and assuming that, at the pour point, viscosity is equal to 1 million centistokes.\n\n$$\n\\begin{align}\nc_{v1} &= 5000 K \\cr\n\\cr\nT_{pp} &= { c_{v1} \\cdot T_{ref} \\over c_{v1} - T_{ref} ln(v_{ref}) }\n\\qquad \\qquad \\qquad \\qquad \\boldsymbol{(eq. 30)} \\cr\n\\end{align}\n$$\n\n<center><b>--- Begin JamesM Comments ---</b></center>\n\nIn <b>(A)</b>, we reference CPPF eq. 3.119, which seems to not include $T_{API}$ as an input.  Riazi describes this equation as:\n\n$$\n\\begin{align}\nSG &= \\text{oil specific gravity} \\cr\nM &= \\text{oil molecular weight} \\cr\nv_{38(100)} &= \\text{oil kinematic viscosity at } 37.8^\\circ C (100^\\circ F) \\cr\n\\cr\nT_P &= \\text{pour point (ASTM D 97) in } \\,^\\circ K \\cr\n&= 130.47 [SG^{2.970566}] \\cdot [M^{(0.61235 - 0.47357 SG)}] \\cdot [v_{38(100)}^{(0.310331 - 0.32834 SG)}] \\cr\n\\end{align}\n$$\n\nSo I think that eq. 6 is not correct.\n\nBeyond that, I think that we would only use this formula if we had actual measured component densities in our imported oil record, which is very unlikely.\nThe component molecular weights and densities that we estimate already use viscosity as an input, at least in part.  So I am not convinced that an estimation based on them would be any more accurate than <b>(B)</b>.\n\nIn <b>(B)</b>, exactly which $(T_{ref}, v_{ref})$ measurement should we use if multiple viscosity measurements exist?  Since we are calculating pour point, which I understand to mean the lowest temperature for which a finite viscosity exists, I believe we should use the lowest measured temperature and its associated viscosity.\n\nDoes the viscosity-temperature correction formula in Adios2 define what $c_{v1}$ is?\n\n<center><b>--- End JamesM Comments ---</b></center>\n\n\n```python\ndef estimate_pour_point_from_kvis(ref_kvis, ref_temp_k):\n    c_v1 = 5000.0\n    T_pp = (c_v1 * ref_temp_k) / (c_v1 - ref_temp_k * np.log(ref_kvis))\n    \n    return T_pp\n\ndef oil_pour_point(imported_rec):\n    min_k = max_k = None\n\n    if (imported_rec.pour_point_min_k is not None or\n            imported_rec.pour_point_max_k is not None):\n        min_k = imported_rec.pour_point_min_k\n        max_k = imported_rec.pour_point_max_k\n    else:\n        lowest_kvis = lowest_temperature(oil_aggregate_kvis(imported_rec)[0])\n        max_k = pour_point_from_kvis(lowest_kvis.m_2_s, lowest_kvis.ref_temp_k)\n\n    return min_k, max_k\n\n# pour point estimation based on (T_ref, v_ref)\n# seems a bit inaccurate\n#for obj in (ans_mp, ans_2002, bahia, arabian, canola):\nfor obj in (ans_mp,):\n    print 'oil = ', obj.oil_name\n    print 'oil.pour_point_min = ', obj.pour_point_min_k\n    print 'oil.pour_point_max = ', obj.pour_point_max_k\n\n    lowest_kvis = lowest_temperature(oil_aggregate_kvis(obj))\n    ref_kvis, ref_temp_k = lowest_kvis.m_2_s, lowest_kvis.ref_temp_k\n    print 'pour point (T_ref, v_ref) = ', estimate_pour_point_from_kvis(ref_kvis, ref_temp_k)\n\n    print 'oil_pour_point() = ', oil_pour_point(obj)\n\n    print\n\n```\n\n    oil =  ALASKA NORTH SLOPE (MIDDLE PIPELINE)\n    oil.pour_point_min =  219.15\n    oil.pour_point_max =  219.15\n    pour point (T_ref, v_ref) =  175.598251438\n    oil_pour_point() =  (219.15, 219.15)\n    \n\n\n### 24. Flash Point:\n\nIf a measured minimum flash point exists for the incoming record, we will use it.<br>\nOtherwise, if a measured maximum flash point exists for the incoming record, we will use that instead.<br>\nOtherwise, if measured distillation cut data exists, use method <b>(A)</b>.<br>\nOtherwise, use method <b>(B)</b>.\n\n<b>(A)</b> Flash point can be estimated from the first pseudo-component cut:\n\n$$\n\\begin{align}\nT_{cut1} &= \\text{the boiling point of the first pseudo-component cut } (^\\circ K) \\cr\n\\cr\nT_{flsh} &= 117 + 0.69 \\cdot T_{cut1} \\qquad \\qquad \\qquad \\qquad \\boldsymbol{(eq. 31)} \\cr\n\\end{align}\n$$\n\n<i>\nReference: Chang A., K. Pashakanti, and Y. Liu (2012), Integrated Process Modeling and Optimization, Wiley Verlag.\n</i>\n\n<b>(B)</b> Flash point can be estimated from the API value:\n\n$$\n\\begin{align}\nT_{flsh} &= 457 - 3.34 \\cdot API \\qquad \\qquad \\qquad \\qquad \\boldsymbol{(eq. 32)} \\cr\n\\end{align}\n$$\n\n<center><b>--- Begin JamesM Comments ---</b></center>\n\nI have some reservations about simply using the first distillation cut boiling point.<br>\nIt seems that the results could vary wildly depending on the quality of the cut data.\n\nI would be much more confident in a curve fit to the cuts, in which we take the temperature where a certain fraction is evaporated.\n\n<center><b>--- End JamesM Comments ---</b></center>\n\n\n```python\ndef estimate_flash_point_from_bp(ref_temp_k):\n    return 117.0 + 0.69 * ref_temp_k\n\ndef estimate_flash_point_from_api(api):\n    return 457.0 - 3.34 * api\n\ndef oil_flash_point(imported_rec):\n    if imported_rec.flash_point_min_k is not None:\n        return imported_rec.flash_point_min_k\n    elif imported_rec.flash_point_max_k is not None:\n        return imported_rec.flash_point_max_k\n    elif len(list(oil_culled_cuts(imported_rec))) > 2:\n        cut_temps = oil_normalized_cut_temps(imported_rec)\n        return estimate_flash_point_from_bp(cut_temps[0])\n    elif imported_rec.api is not None:\n        return estimate_flash_point_from_api(imported_rec.api)\n    else:\n        est_api = estimate_api_from_density(oil_density_at_temp(imported_rec, 288.15))\n        return estimate_flash_point_from_api(est_api)\n\n# ANS oil has both an api and distillation cuts.\n# For this oil, methods (A) and (B) estimate different results.\n# but the difference is only about 7%.  Probably acceptable.\n# we should try this on other oils to compare.\n\n#for obj in (ans_mp, ans_2002, bahia, arabian, canola):\nfor obj in (ans_mp,):\n    print 'oil = ', obj.oil_name\n    print 'oil.flash_point_min_k = ', obj.flash_point_min_k\n    print 'oil.flash_point_max_k = ', obj.flash_point_max_k\n    if len(list(oil_culled_cuts(obj))) > 0:\n        print 'oil.cuts[0] = ', oil_normalized_cut_values(obj)[0][0]\n    else:\n        print 'no cut data'\n    print 'oil.api = ', obj.api\n\n    print 'oil flash point = ', oil_flash_point(obj)\n    print\n```\n\n    oil =  ALASKA NORTH SLOPE (MIDDLE PIPELINE)\n    oil.flash_point_min_k =  250.15\n    oil.flash_point_max_k =  250.15\n    oil.cuts[0] =  327.851614045\n    oil.api =  29.9\n    oil flash point =  250.15\n    \n\n\n### 25. Maximum water fraction of emulsion:\n\nThis quantity will be set after the emulsification approach in Adios3 is finalized.  It will vary depending upon the emulsion stability.  For now the following rule will be applied:\n\nIf our substance is a crude oil, then $f_{w max} = 0.9$<br>\nIf our substance is a refined product, then $f_{w max} = 0$\n\n### 26. Bullwinkle (time):\n\nAdios3 needs to know when to initiate emulsification.  The Adios2 development team called this term Bullwinkle.  SINTEF has measured this parameter for some oils, and the new, not yet completed, analysis of emulsification may provide formulas for Bullwinkle.  Bullwinkle may be either a time value (i.e. time delay after which the emulsification formulas are turned on) or a fraction of the oil that needs to evaporate or dissolve before emulsification can start.\n\nBullwinkle(time) is undefined unless the user explicitly sets a value.  Then it overrides Bullwinkle(fraction) as the determining parameter for the onset of emulsification.\n\n### 27. Bullwinkle (fraction):\n\n<i>\nReference: Adios2\n</i>\n\nBullwinkle is the mass fraction that must evaporate or dissolve before stable emulsification can begin.  This formula will change when we complete the emulsification module.\n\nIf $f_{asph} > 0$, then we use method <b>(A)</b><br>\nOtherwise, we use method <b>(B)</b><br>\n\n<b>(A)</b> $f_{bull}$ can be calculated from $f_{asph}$:\n$$\n\\begin{align}\nf_{bull} &= 0.32 - 3.59 \\cdot f_{asph} \\qquad \\qquad \\qquad \\boldsymbol{(eq. 33)} \\cr\n\\end{align}\n$$\n\n<b>(B)</b> $f_{bull}$ can be calculated from the oil's API:\n$$\n\\begin{align}\nf_{bull} &= 0.5762 \\cdot log10(API) - 0.6353 \\qquad \\qquad \\boldsymbol{(eq. 34)} \\cr\n\\end{align}\n$$\n\nA result of $f_{bull} < 0$ or $f_{bull} > 1$ indicates no emulsification.\n\n<center><b>--- Begin JamesM Comments ---</b></center>\n\nI don't think documentation exists for how Adios2 is __really__ calculating the bullwinkle fraction.  But we can look at the C++ code for adios2 in the file OilInitialize.cpp.  Here is what it basically does.\n\nFirst we define the input terms that decide our bullwinkle fraction:\n$$\n\\begin{align}\nN_i &= \\text{Nickel content of our oil} \\cr\nV_a &= \\text{Vanadium content of our oil} \\cr\nf_{asph} &= \\text{asphaltene fraction of our oil} \\cr\nAPI &= \\text{The API density of our oil} \\cr\n\\end{align}\n$$\n\nThere are also some very briefly documented intermediate terms that are used for calculating the final result, which I will describe as best I can based on the code comments: \n\n$$\n\\begin{align}\nt_g &= \\text{documented as '} dT/df \\text{evaporation'} \\cr\n&\\quad \\, \\text{I can only assume this is the rate of evaporation with temperature} \\cr\nt_{bp} &= \\text{documented as the 'ADIOS 1 liquid boiling point (bubble point)'} \\cr\nf_{bull,adios1} &= \\text{the ADIOS 1 calculated bullwinkle fraction possibly???} \\cr\n\\end{align}\n$$\n\nAnd our decision tree goes a bit like this:\n- if oil type is refined: then $f_{bull} = 1$\n- else if oil has an emuls_constant_max property: then $f_{bull} = \\text{emuls_constant_max}$\n- else:\n    - if $N_i > 0$ and $V_a > 0$ and $N_i + V_a > 15$: then $f_{bull} = 0$\n    - else if $f_{asph} > 0$: then $f_{bull} = 0.20219 - 0.168 \\cdot log_{10}(f_{asph})$\n    - else if $API < 26$: then $f_{bull} = 0.08$\n    - else if $API > 50$: then $f_{bull} = 0.303$\n    - else:\n        - $f_{bull} = -1.038 - 0.78935 \\cdot log_{10}(1 / API)$\n    - $t_g = 1356.7 - 247.36 \\cdot log(API)$\n    - $t_{bp} = 532.98 - 3.1295 \\cdot API$\n    - $f_{bull,adios1} = \\left( \\frac{483 - t_{bp}}{t_g} \\right)_{\\bot 0}^{\\top 0.4} $\n    - $f_{bull} = avg\\left( (f_{bull}, f_{bull,adios1}) \\right)$\n\n\n<center><b>--- End JamesM Comments ---</b></center>\n\n\n```python\ndef estimate_bullwinkle_fraction_from_asph(f_asph):\n    return 0.32 - 3.59 * f_asph\n\ndef estimate_bullwinkle_fraction_from_api(api):\n    return 0.5762 * np.log10(api) - 0.6353\n\ndef oil_bullwinkle_fraction(imported_rec):\n    _f_res, f_asph = oil_inert_fractions(imported_rec)\n\n    if f_asph > 0.0:\n        return estimate_bullwinkle_fraction_from_asph(f_asph)\n    elif imported_rec.api is not None:\n        return estimate_bullwinkle_fraction_from_api(imported_rec.api)\n    else:\n        est_api = api_from_density(oil_density_at_temp(imported_rec, 288.15))\n        return estimate_bullwinkle_fraction_from_api(est_api)\n\n#for obj in (ans_mp, ans_2002, bahia, arabian, canola):\nfor obj in (ans_mp,):\n    print 'oil = ', obj.oil_name\n    print 'oil.api = ', obj.api\n    print 'oil.asphaltenes = ', obj.asphaltenes\n    print 'oil.densities = ', obj.densities\n\n    print 'bullwinkle(fraction) = ', oil_bullwinkle_fraction(obj)\n    print\n\n```\n\n    oil =  ALASKA NORTH SLOPE (MIDDLE PIPELINE)\n    oil.api =  29.9\n    oil.asphaltenes =  None\n    oil.densities =  [<Density(886.9 kg/m^3 at 273.15K)>, <Density(876.1 kg/m^3 at 288.15K)>]\n    bullwinkle(fraction) =  0.259049831898\n    \n\n\n### 28. Solubility:\n\nIf the imported oil record contains a valid value for solubility, we will use that value when building our oil.<br>\nOtherwise, $c_{solu} = 0 \\, kg/m^3$\n\n### 29. Adhesion <i>(not currently used by model)</i>:\n\nIf the imported oil record contains a valid value for adhesion, we will use that value when building our oil.<br>\nOtherwise, $Adh_{oil} = 0.035 \\, kg/m^2$\n\n<i>\nReference: ESTC data\n</i>\n\n### 30. Sulphur Mass Fraction <i>(not currently used by model)</i>:\n\nIf the imported oil record contains a valid value for sulphur mass fraction, we will use that value when building our oil.<br>\nOtherwise, $f_{sulf} = 0$\n\n## <u>Addendum 1</u>\n\n### <center>Addressing Heavy Volatile components</center>\n\nIn practice, we have seen that certain oil records in our database result in heavy estimated saturate and aromatic components.  That is to say we have saturates and aromatic components that have a higher density than our resins and asphaltenes.  Intuitively this does not seem right, and we can identify some things we are doing in our estimations that would cause this:\n\n- We have set a hard-coded density of $1100 \\, kg/m^3$ in the case of resins and asphaltenes, which is why we are getting the rejections.  Maybe this value should be higher.\n- We estimate our component densities based on a Watson characterization factor combined with a component boiling point.  And as the boiling temperature rises, our component density calculation will eventually rise to a value higher than $1100 \\, kg/m^3$.  Maybe we should consider that the volatile component boiling points will not exceed a certain threshold.\n\nAnd after discussing this at great length, we have decided that:\n\n- $1100 \\, kg/m^3$ is probably a reasonable value for our inert components.\n- We should set a cap density for the volatile components so they do not exceed that of the involatile components.\n\nSo how might we do this?  Well the most reasonable way to do this would probably be to alter our distillation temperature curve.  Right now it is a linear function that extends from a fraction of $0$ to a fraction of $(1 - f_{res} - f_{asph})$.  We could put a threshold limit that would level the curve at a certain upper temperature.\n\nTo do this, we will make use of a generalized logistic function or Richard's curve.  This should allow us to make our distillation function flexible and not add to the software complexity of our estimations.\n\n$$\n\\begin{align}\nY(x, M) &= \\text{generalized logistic function} \\cr\n&= A + \\frac{K - A}{(C + Qe^{-B(x - M)})^{1/\\nu}} \\cr\n&= 0 + \\frac{1 - 0}{(1 + e^{-20(x - M)})^{1/\\nu}} \\cr\n&= \\frac{1}{(1 + e^{-20(x - M)})^{1/\\nu}} \\cr\n\\cr\n\\zeta &= \\text{smoothing factor for when we cross the M boundary} \\cr\n&\\approx 0.03 \\cr\n\\cr\nx_s &= \\text{clamped x value} \\cr\n&= x - x \\cdot Y(x, M) + M \\cdot Y(x, M) \\cr\n&= x - \\frac{x}{(1 + e^{-20(x - M)})^{1/(1 + \\zeta)}} + \\frac{M}{(1 + e^{-20(x - M)})^{1/(1 - \\zeta)}} \\cr\n\\end{align}\n$$\n\n\n```python\ndef clamp(x, M, zeta=0.03):\n    '''\n        The parameters nu, and B have been tweaked a bit to show a smooth\n        Transition as we cross the M boundary.\n    '''\n    return (x -\n            (x / (1.0 + np.e ** (-15 * (x - M))) ** (1.0 / (1 + zeta)) ) +\n            (M / (1.0 + np.e ** (-15 * (x - M))) ** (1.0 / (1 - zeta)) ))\n\ndef linear_curve(x, a, b, M, zeta=0.09):\n    x_c = clamp(x, M, zeta)\n\n    return (a * x_c + b)\n\n```\n\n\n```python\nplt.figure(figsize=(12, 6))  # make the drawing area a bit bigger\n\nax1 = plt.subplot(111)\n\nx = np.linspace(-1.0, 5.0, 100)\n\n# let's plot the function (x + 3), limited at 3\n# this should give us a zero crossing of y=3.0,\n# and an upper limit of y=6.0\ny = linear_curve(x, 1.0, 3.0, 3.0, 0.03)\n\nax1.plot(x, x, linewidth=1)\nax1.plot(x, y, linewidth=1)\n\nplt.axhline(0)\nplt.axvline(0)\n\nshow()\n```\n\nOk, this is a pretty reasonable, but general, example of what we would like to do.  Let's see what it looks like using distillation cut data.  First, let's estimate what our cutoff should be for $T_i$.  From Section 19 (Component Density), our density formulas are:\n\n$$\n\\begin{align}\n\\rho try_{arom,i} &= 1000 \\cdot {\\root 3 \\of { 1.8 \\cdot T_{arom,i}} \\over K_{arom,w} } \\cr\n\\frac{\\rho try_{arom,i} \\cdot K_{arom,w}}{1000} &= \\root 3 \\of { 1.8 \\cdot T_{arom,i}} \\cr\n\\left( \\frac{\\rho try_{arom,i} \\cdot K_{arom,w}}{1000} \\right)^3 &= 1.8 \\cdot T_{arom,i} \\cr\n\\left( \\frac{\\rho try_{arom,i} \\cdot K_{arom,w}}{1000} \\right)^3 \\cdot \\frac{1}{1.8} &= T_{arom,i} \\cr\n\\left( \\frac{1100 \\cdot 10}{1000} \\right)^3 \\cdot \\frac{1}{1.8} &= T_{arom,i} \\cr\n\\frac{1331}{1.8} &= T_{arom,i} \\cr\n739.444 &= T_{arom,i} \\cr\n\\cr\n\\rho try_{sat,i} &= 1000 \\cdot {\\root 3 \\of { 1.8 \\cdot T_{sat,i}} \\over K_{sat,w} } \\cr\n\\left( \\frac{\\rho try_{sat,i} \\cdot K_{sat,w}}{1000} \\right)^3 \\cdot \\frac{1}{1.8} &= T_{sat,i} \\cr\n\\left( \\frac{1100 \\cdot 12}{1000} \\right)^3 \\cdot \\frac{1}{1.8} &= T_{sat,i} \\cr\n\\frac{2299.968}{1.8} &= T_{sat,i} \\cr\n1277.76 &= T_{sat,i} \\cr\n\\end{align}\n$$\n\nBased on the above, it is likely that our aromatic components will become heavier than the inert components at around $739^\\circ K$.<br>\nOur saturate components will eventually appear too heavy, but at such a great temperature it is unlikely to happen.\n\nSo let's choose 739 as our temperature cutoff.\n\n\n```python\ndef linear_curve(x, a, b):\n    return (a * x + b)\n\n\ndef inverse_linear_old(y, a, b):\n    return (y - b) / a\n\n\ndef inverse_linear_curve(y, a, b, M, zeta=0.12):\n    y_c = clamp(y, M, zeta)\n\n    return (y_c - b) / a\n\n\ndef oil_normalized_cut_values(imported_rec, num_cuts=10):\n    f_res, f_asph = oil_inert_fractions(imported_rec)\n    \n    culled_cuts = list(oil_culled_cuts(imported_rec))\n\n    if len(culled_cuts) == 0:\n        if imported_rec.api is not None:\n            oil_api = imported_rec.api\n        else:\n            oil_rho = oil_density_at_temp(imported_rec, 288.15)\n            oil_api = estimate_api_from_density(oil_rho)\n\n        BP_i = estimate_cut_temps_from_api(oil_api)\n        fevap_i = np.cumsum(estimate_n_fmasses(f_res, f_asph))\n    else:\n        BP_i, fevap_i = zip(*[(c.vapor_temp_k, c.fraction)\n                              for c in culled_cuts])\n\n    popt, pcov = curve_fit(linear_curve, BP_i, fevap_i)\n    f_cutoff = linear_curve(732.0, *popt)  # value of asymptote center (< 739)\n    popt = popt.tolist() + [f_cutoff]\n\n    fevap_i = np.linspace(0.0, 1.0 - f_res - f_asph, (num_cuts * 2) + 1)[1:]\n    T_i = np.clip(inverse_linear_curve(fevap_i, *popt), 0.0, 5000.0)\n\n    fevap_i = fevap_i.reshape(-1,2)[:,1]\n    T_i = T_i.reshape(-1,2)[:,0]\n\n    above_zero = T_i > 0.0\n    T_i = T_i[above_zero]\n    fevap_i = fevap_i[above_zero]\n\n    return T_i, fevap_i\n\n```\n\n\n```python\nplt.figure(1, figsize=(12,6))\nax = plt.subplot(111)\n\nobj = boscan\n\nplt.xlabel('% Evap')\nplt.ylabel(r'$T_i$', fontsize=16)\nplt.grid()\n\n# plot our distillation curve\nboiling_points = [c.vapor_temp_k for c in oil_culled_cuts(obj)]\ncum_fractions = [c.fraction for c in oil_culled_cuts(obj)]\n\nif len(boiling_points) == 0:\n    if obj.api is not None:\n        oil_api = obj.api\n    else:\n        oil_rho = oil_density_at_temp(obj, 288.15)\n        oil_api = estimate_api_from_density(oil_rho)\n\n    f_res, f_asph = oil_inert_fractions(obj)\n    boiling_points = estimate_cut_temps_from_api(oil_api)\n    cum_fractions = np.cumsum(estimate_n_fmasses(f_res, f_asph))\n\npopt, pcov = curve_fit(linear_curve, boiling_points, cum_fractions)\n\nnew_fracs = np.linspace(0.0001, 0.9999, 100)\nnew_temps = np.clip(inverse_linear_old(new_fracs, *popt), 0.0, 5000.0)\nplt.plot(new_fracs, new_temps, '-b', label=\"Distillation Curve\")\n\n\n# now plot the N fractions we intend to use\nnew_temps, new_fracs = oil_normalized_cut_values(obj)\nplt.plot(new_fracs, new_temps, 'go', label=\"Estimated Cuts\")\n\n# plot our inert fraction\nplt.plot(1.0, 1015.0, 'go')\n\n# now we would like to graph the quantized \"areas\"\n# that our fractional masses represent\ndef make_shaded_region(f_low, f_high,\n                       t_low, t_high,\n                      facecolor='0.8'):\n    ix = (f_low, f_high)\n    iy = (t_low, t_high)\n    verts = [(x, y) for x in ix for y in iy]\n    verts[2:] = reversed(verts[2:])\n    poly = Polygon(verts, facecolor=facecolor, edgecolor='k')\n    ax.add_patch(poly)\n\nfor r in zip([0.0] + new_fracs.tolist(),\n             new_fracs,\n             [inverse_linear(0.0, *popt)] + new_temps.tolist(),\n             new_temps):\n    make_shaded_region(*r, facecolor='#ddeeff')\n\n# make the shaded region for our inert fraction\nmake_shaded_region(new_fracs[-1], 1.0,\n                   new_temps[-1], 1015.0)\n\n# ticks for the shaded region\nextraticks = [low,]\nextralabels = [r'${f_{inert}}$',]\nplt.xticks(list(plt.xticks()[0]) + extraticks,\n           list(plt.xticks()[0]) + extralabels)\n\nfor tick in ax.xaxis.get_major_ticks():\n    if tick.label.get_text().find('inert') >= 0:\n        tick.label.set_fontsize(16)\n        tick.label.set_rotation('vertical')\n\nplt.axhline(739, color='r')\nplt.legend(loc='upper left')\n\nplt.show()\n```\n\nOk, that seems like a pretty reasonable response.  This solution will require some peer review from Chris, Bill, and Robert, but it will certainly prevent our estimation methods from returning volatile oil fractions with higher densities than the inert fractions.\n\n## <u>Addendum 2</u>\n\n### <center>The Oil Density Temperature Expansion Coefficient</center>\n\nCurrently, we define the density conversion formula for different temperatures as:\n\n$$\n\\begin{align}\n\\rho_0 &= \\text{measured density} \\cr\nT_0 &= \\text{temperature at which density is measured} \\cr\nk_{\\rho T} &= \\text{the volumetric expansion coefficient} \\cr\n&= 0.0008 \\, K^{-1} \\cr\n\\cr\n\\rho_{ref} &= \\rho_0 \\cdot (1 - k_{\\rho T} \\cdot (T_{ref} - T_0 ))\n\\end{align}\n$$\n\nThis is what Adios2 did, and it seems to produce sane estimations of an oil's density at some arbitrary temperature.  But the constant value that is used for the volumetric expansion coefficient is simply an average of a bunch of sampled oils.  As such, it is a good middle-of-the-road value to use in lieu of a precise coefficient.\n\nIt would be better if we could determine a precise value for this coefficient, and if an oil has two or more density measurements, we should be able to do it by referring to the above equation and modifying it as follows:\n\n$$\n\\begin{align}\n\\rho_{i} &= \\text{a density value indexed by } i \\cr\nT_{i} &= \\text{a temperature value indexed by } i \\cr\nk_{\\rho T} &= \\text{the volumetric expansion coefficient} \\cr\n\\cr\n\\rho_{i+1} &= \\rho_i \\cdot (1 - k_{\\rho T} \\cdot (T_{i+1} - T_i)) \\cr\n\\frac{\\rho_{i+1}}{\\rho_i}  &= 1 - k_{\\rho T} \\cdot (T_{i+1} - T_i) \\cr\n\\frac{\\rho_{i+1}}{\\rho_i} - 1  &= - k_{\\rho T} \\cdot (T_{i+1} - T_i) \\cr\n\\frac{\\rho_{i+1} - \\rho_i}{\\rho_i} &= - k_{\\rho T} \\cdot (T_{i+1} - T_i) \\cr\n\\frac{\\rho_{i+1} - \\rho_i}{\\rho_i  \\cdot (T_{i+1} - T_i)} &= - k_{\\rho T} \\cr\n\\frac{\\rho_i - \\rho_{i+1}}{\\rho_i  \\cdot (T_{i+1} - T_i)} &= k_{\\rho T} \\cr\n\\cr\n\\end{align}\n$$\n\nWell, there it is.  Let's see if this gives us anything sane.\n\n\n```python\ndef get_vol_expansion_coeff(rho_0, t_0, rho_1, t_1):\n    k_rho_t = (rho_0 - rho_1) / (rho_0 * (t_1 - t_0))\n\n    return k_rho_t\n\ndef oil_vol_expansion_coeff(imported_rec, weathering=0.0):\n    density_list = [(d.kg_m_3, d.ref_temp_k)\n                    for d in imported_rec.densities\n                    if (d.kg_m_3 is not None and\n                        d.ref_temp_k is not None and\n                        d.weathering == weathering)]\n\n    if len(density_list) >= 2:\n        d_args = [t for d in density_list[:2] for t in d]\n        k_rho_t = get_vol_expansion_coeff(*d_args)\n    else:\n        k_rho_t = 0.0008\n\n    return k_rho_t\n\n```\n\n\n```python\nprint ans_mp.densities\nprint oil_vol_expansion_coeff(ans_mp)\n```\n\n    [<Density(886.9 kg/m^3 at 273.15K)>, <Density(876.1 kg/m^3 at 288.15K)>]\n    0.000811816439283\n\n\nOk, so far so good.  Let's see if we can try this out on all oils that have multiple density measurements.\n\n\n```python\nmult_dens_oils = [ir for ir in session.query(ImportedRecord).all()\n                  if (ir.product_type is not None and\n                      ir.product_type.lower() == 'crude' and\n                      len(ir.densities) >= 2)]\n\nprint len(mult_dens_oils)\nfor o in mult_dens_oils:\n    print '{} ({}):\\t'.format(o.oil_name, o.product_type),\n    print '{}'.format(oil_vol_expansion_coeff(o))\n\nmult_dens_oils = [ir for ir in session.query(ImportedRecord).all()\n                  if (ir.product_type is not None and\n                      ir.product_type.lower() == 'refined' and\n                      len(ir.densities) >= 2)]\n\nprint '\\n', len(mult_dens_oils)\nfor o in mult_dens_oils:\n    print '{} ({}):\\t'.format(o.oil_name, o.product_type),\n    print '{}'.format(oil_vol_expansion_coeff(o))\n\n```\n\n    9\n    GALEOTA MIX, AMOCO (Crude):\t0.000719217491369\n    POUI, AMOCO (Crude):\t0.000413838768416\n    ALASKA NORTH SLOPE (MIDDLE PIPELINE) (Crude):\t0.000811816439283\n    ALASKA NORTH SLOPE (NORTHERN PIPELINE) (Crude):\t0.000823138498716\n    ALASKA NORTH SLOPE-PUMP STATION #9, BP (Crude):\t0.00104568854569\n    COLD LAKE BITUMEN (Crude):\t0.0019801980198\n    WEST TEXAS (Crude):\t0.0008\n    SOUTH LOUISIANA (Crude):\t0.0008\n    ALASKA NORTH SLOPE (2002) (Crude):\t0.0008\n    \n    5\n    FUEL OIL NO.1 (JET B, ALASKA) (Refined):\t0.000900024324982\n    IFO 300 (Refined):\t0.000669344042838\n    DIESEL FUEL OIL (ALASKA) (Refined):\t0.000871977804201\n    INTERMEDIATE FUEL OIL 300 (Refined):\t0.000602409638554\n    AVIATION GASOLINE 100 (Refined):\t0.00119047619048\n\n\nOk, that seems to be producing results that are in a reasonable range for crude as well as refined products.\nBill has given us a new document 'density_thermal_expansion.docx' (Jan 2017), in which he defines a couple of different expansion coefficients to be used if we don't have enough density data to perform a calculation.\n\n- 0.0008: for crude oils and heavy refined products\n- 0.0009: for refined products with an API > 30\n\nThis was amended, through discussion with Chris, to inclusively group both crude and refined products with API > 30.  The document has not been updated at this time, but we will go with this amendment since it is truly what we want.  So what we get is:\n\n- 0.0008: if API <= 30\n- 0.0009: if API > 30\n\nSo let's update our function:\n\n\n```python\ndef get_vol_expansion_coeff(rho_0, t_0, rho_1, t_1):\n    if t_0 == t_1:\n        k_rho_t = 0.0\n    else:\n        k_rho_t = (rho_0 - rho_1) / (rho_0 * (t_1 - t_0))\n\n    return k_rho_t\n\ndef oil_vol_expansion_coeff(imported_rec, weathering=0.0):\n    density_list = [(d.kg_m_3, d.ref_temp_k)\n                    for d in imported_rec.densities\n                    if (d.kg_m_3 is not None and\n                        d.ref_temp_k is not None and\n                        d.weathering == weathering)]\n\n    if len(density_list) >= 2:\n        d_args = [t for d in density_list[:2] for t in d]\n        k_rho_t = get_vol_expansion_coeff(*d_args)\n    else:\n        if imported_rec.api > 30:\n            k_rho_t = 0.0009\n        else:\n            k_rho_t = 0.0008\n\n    return k_rho_t\n\n```\n\n\n```python\nprint 'Checking some low API oils:'\nlow_api_oils = (session.query(ImportedRecord)\n                .filter(ImportedRecord.api <= 30).all())\n\nfor o in low_api_oils[:10]:\n    print '{} ({}):\\t'.format(o.oil_name, o.product_type),\n    print '{}'.format(oil_vol_expansion_coeff(o))\n\nprint '\\nChecking some high API oils:'\nhigh_api_oils = (session.query(ImportedRecord)\n                 .filter(ImportedRecord.api > 30).all())\n\nfor o in high_api_oils[:10]:\n    print '{} ({}):\\t'.format(o.oil_name, o.product_type),\n    print '{}'.format(oil_vol_expansion_coeff(o))\n\n```\n\n    Checking some low API oils:\n    ABU SAFAH (Crude):\t0.0008\n    ABU SAFAH, ARAMCO (Crude):\t0.0008\n    ARABIAN HEAVY, CITGO (Crude):\t0.0008\n    ARABIAN HEAVY, EXXON (Crude):\t0.0008\n    ARABIAN HEAVY, STAR ENTERPRISE (Crude):\t0.0008\n    ARABIAN HEAVY, ARAMCO (Crude):\t0.0008\n    ARABIAN LIGHT, CITGO (Crude):\t0.0008\n    ARABIAN MEDIUM, EXXON (Crude):\t0.0008\n    BACHAGUERO, CITGO (Crude):\t0.0008\n    BACHAQUERO 17, EXXON (Crude):\t0.0008\n    \n    Checking some high API oils:\n    ALGERIAN BLEND (Crude):\t0.0009\n    ALGERIAN CONDENSATE (Crude):\t0.0009\n    ALGERIAN CONDENSATE, CITGO (Crude):\t0.0009\n    ARABIAN EXTRA LIGHT, PHILLIPS (Crude):\t0.0009\n    ARABIAN EXTRA LIGHT, STAR ENTERPRISE (Crude):\t0.0009\n    ARABIAN EXTRA LIGHT, ARAMCO (Crude):\t0.0009\n    ARABIAN LIGHT, PHILLIPS (Crude):\t0.0009\n    ARABIAN LIGHT, STAR ENTERPRISE (Crude):\t0.0009\n    ARABIAN LIGHT, ARAMCO (Crude):\t0.0009\n    ARABIAN MEDIUM, PHILLIPS (Crude):\t0.0009\n\n\nAlright, this seems to exhibit the right default behavior for oils that don't have enough density information to calculate the expansion coefficient.\n\n\n```python\nimported_rec = session.query(ImportedRecord).filter(ImportedRecord.oil_name == \"COLD LAKE BITUMEN\").one()\nprint imported_rec.adios_oil_id\n\nfor d in imported_rec.densities:\n    print (d.kg_m_3, d.ref_temp_k, d.weathering)\n\n```\n\n    AD02543\n    (1010.0, 273.0, 0.0)\n    (1000.0, 278.0, 0.0)\n    (1000.0, 283.0, 0.0)\n    (977.0, 288.0, 0.0)\n\n\n\n```python\nfig, ax = plt.subplots()\n\nop_obj = oil_library.get_oil_props(\"COLD LAKE BITUMEN\")\n\nfor d in op_obj.get_densities():\n    print (d.kg_m_3, d.ref_temp_k, d.weathering)\n\ndensities = op_obj.get_densities()\nref_t = [d.ref_temp_k for d in densities]\nref_d = [d.kg_m_3 for d in densities]\nax.plot(ref_t, ref_d, 'o')\n\ntemps = np.linspace(273.0, 300.0, 100)\ndensities = op_obj.density_at_temp(temps)\nax.plot(temps, densities, '-')\n\nax.set_xlabel(r'temperature ($\\degree K$)')\nax.set_ylabel(r'density ($kg/m^3$)')\n```\n\nOk, I think we found an oil record that has some bad data.  I see two issue that are slightly different:\n\n- Bad density values.  In this case it is a density value that is repeated at two different temperatures.\n- Chris mentioned that he noticed 'glitches' midway between two density data points, and that he would like there to be a smooth interpolation between them.\n\n### Smooth transition between Oil Density Data Values\n\nWe already have a method of determining the volumetric expansion coefficient.  For oil records that have more than two density measurements, it is simply a problem of choosing the right two based on the temperature for which we are trying to estimate the density.\n\nIf we have two or more densities, then we should be able to determine the expansion coefficient, but there are some edge cases that we will list:\n- temperature within bounds: we take the two closest measurements, specifically the closest one immediately lower than the specified temperature and the closest one immediately higher.\n- low temperature out-of-bounds: Chris & Bill would like to take the lowest measurement and use the default expansion coefficient\n- high temperature out-of-bounds: Chris & Bill would like to take the highest measurement and use the default expansion coefficient\n\nLet's see if we can do this.\n\n\n```python\ndef closest_to_temperature(obj_list, temperature):\n    '''\n        General Utility Function\n\n        From a list of objects containing a ref_temp_k attribute,\n        return the object(s) that are closest to the specified temperature(s)\n        specifically:\n        - we want the ones that immediately bound our temperature.\n        - if our temperature is high and out of bounds of the temperatures\n          in our obj_list, then we return a range containing only the highest\n          temperature.\n        - if our temperature is low and out of bounds of the temperatures\n          in our obj_list, then we return a range containing only the lowest\n          temperature.\n\n        We accept only a scalar temperature or a sequence of temperatures\n    '''\n    temperature = np.array(temperature)\n\n    if len(obj_list) <= 1:\n        # range where the lowest and highest are basically the same.\n        return [(obj_list * 2) for t in temperature]\n    else:\n        geq_temps = temperature.reshape(-1, 1) >= [obj.ref_temp_k\n                                                   for obj in obj_list]\n        high_and_oob = np.all(geq_temps, axis=1)\n        low_and_oob = np.all(geq_temps ^ True, axis=1)\n\n        rho_idxs0 = np.argmin(geq_temps, axis=1)\n        rho_idxs0[rho_idxs0 > 0] -= 1\n        rho_idxs0[high_and_oob] = len(obj_list) - 1\n\n        rho_idxs1 = (rho_idxs0 + 1).clip(0, len(obj_list) - 1)\n        rho_idxs1[low_and_oob] = 0\n\n        range_idxs = np.array((rho_idxs0, rho_idxs1)).T\n\n        return zip([obj_list[i] for i in rho_idxs0],\n                   [obj_list[i] for i in rho_idxs1])\n\ndef oil_vol_expansion_coeff(densities, temperature):\n    closest_densities = closest_to_temperature(densities,\n                                               temperature)\n    temperature = np.array(temperature)\n    closest_values = np.array([[(d.kg_m_3, d.ref_temp_k)\n                                for d in r]\n                               for r in closest_densities])\n\n    args_list = [[t for d in v for t in d]\n                 for v in closest_values]\n    k_rho_t = np.array([get_vol_expansion_coeff(*args)\n                        for args in args_list])\n\n    greater_than = np.all((temperature > closest_values[:,:,1].T).T, axis=1)\n    less_than = np.all((temperature < closest_values[:,:,1].T).T, axis=1)\n\n    if imported_rec.api > 30:\n        k_rho_default = 0.0009\n    else:\n        k_rho_default = 0.0008\n\n    k_rho_t[greater_than | less_than] = k_rho_default\n\n    if k_rho_t.shape[0] == 1:\n        return k_rho_t[0]\n    else:\n        return k_rho_t\n\n\nop_obj = oil_library.get_oil_props('COLD LAKE BITUMEN')\n\nfor d in op_obj.get_densities():\n    print d\n\ntemp_k = (272.0, 274.0, 279.0, 282.0, 284.0, 287.0, 288.1, 300.0)\n\nprint\npp.pprint(closest_to_temperature(op_obj.get_densities(), temp_k))\n\nfor t in temp_k:\n    print\n    print closest_to_temperature(op_obj.get_densities(), t),\n\nprint; print\npp.pprint(oil_vol_expansion_coeff(op_obj.get_densities(), temp_k))\n\nfor t in temp_k:\n    print\n    print oil_vol_expansion_coeff(op_obj.get_densities(), t),\n\n```\n\n    <Density(1010.0 kg/m^3 at 273.0K)>\n    <Density(1000.0 kg/m^3 at 278.0K)>\n    <Density(1000.0 kg/m^3 at 283.0K)>\n    <Density(977.0 kg/m^3 at 288.0K)>\n    <Density(977.885279889 kg/m^3 at 288.15K)>\n    \n    [ (<Density(1010.0 kg/m^3 at 273.0K)>, <Density(1010.0 kg/m^3 at 273.0K)>),\n      (<Density(1010.0 kg/m^3 at 273.0K)>, <Density(1000.0 kg/m^3 at 278.0K)>),\n      (<Density(1000.0 kg/m^3 at 278.0K)>, <Density(1000.0 kg/m^3 at 283.0K)>),\n      (<Density(1000.0 kg/m^3 at 278.0K)>, <Density(1000.0 kg/m^3 at 283.0K)>),\n      (<Density(1000.0 kg/m^3 at 283.0K)>, <Density(977.0 kg/m^3 at 288.0K)>),\n      (<Density(1000.0 kg/m^3 at 283.0K)>, <Density(977.0 kg/m^3 at 288.0K)>),\n      (<Density(977.0 kg/m^3 at 288.0K)>, <Density(977.885279889 kg/m^3 at 288.15K)>),\n      (<Density(977.885279889 kg/m^3 at 288.15K)>, <Density(977.885279889 kg/m^3 at 288.15K)>)]\n    \n    [(<Density(1010.0 kg/m^3 at 273.0K)>, <Density(1010.0 kg/m^3 at 273.0K)>)]\n    [(<Density(1010.0 kg/m^3 at 273.0K)>, <Density(1000.0 kg/m^3 at 278.0K)>)]\n    [(<Density(1000.0 kg/m^3 at 278.0K)>, <Density(1000.0 kg/m^3 at 283.0K)>)]\n    [(<Density(1000.0 kg/m^3 at 278.0K)>, <Density(1000.0 kg/m^3 at 283.0K)>)]\n    [(<Density(1000.0 kg/m^3 at 283.0K)>, <Density(977.0 kg/m^3 at 288.0K)>)]\n    [(<Density(1000.0 kg/m^3 at 283.0K)>, <Density(977.0 kg/m^3 at 288.0K)>)]\n    [(<Density(977.0 kg/m^3 at 288.0K)>, <Density(977.885279889 kg/m^3 at 288.15K)>)]\n    [(<Density(977.885279889 kg/m^3 at 288.15K)>, <Density(977.885279889 kg/m^3 at 288.15K)>)]\n    \n    array([ 0.0008   ,  0.0019802,  0.       ,  0.       ,  0.0046   ,\n            0.0046   , -0.0060408,  0.0008   ])\n    \n    0.0008\n    0.0019801980198\n    0.0\n    0.0\n    0.0046\n    0.0046\n    -0.00604080443143\n    0.0008\n\n\nOk, now all we have to do is redefine our function for calculating density at a temperature so that it uses a temperature sensitive expansion coefficient.\n\n\n```python\ndef estimate_density_at_temp(ref_density, ref_temp_k, temp_k, k_rho_t=0.0008):\n    return ref_density / (1.0 - k_rho_t * (ref_temp_k - temp_k))\n\ndef get_reference_densities(densities, temperature):\n    closest_densities = closest_to_temperature(densities,\n                                               temperature)\n\n    try:\n        # sequence of ranges\n        density_values = np.array([[d.kg_m_3 for d in r]\n                                   for r in closest_densities])\n        ref_temp_values = np.array([[d.ref_temp_k for d in r]\n                                    for r in closest_densities])\n\n        greater_than = np.all((temperature > ref_temp_values.T).T, axis=1)\n        density_values[greater_than,0] = density_values[greater_than,1]\n        ref_temp_values[greater_than,0] = ref_temp_values[greater_than,1]\n\n        return density_values[:,0], ref_temp_values[:,0]\n    except TypeError:\n        # single range\n        density_values = np.array([d.kg_m_3 for d in closest_densities])\n        ref_temp_values = np.array([d.ref_temp_k for d in closest_densities])\n\n        if np.all(temperature > ref_temp_values):\n            return density_values[1], ref_temp_values[1]\n        else:\n            return density_values[0], ref_temp_values[0]\n            \ndef oil_get_densities(imported_rec, weathering=0.0):\n    densities = [d for d in imported_rec.densities\n                 if (d.kg_m_3 is not None and\n                     d.ref_temp_k is not None and\n                     d.weathering == weathering)]\n\n    if (weathering == 0.0 and\n            imported_rec.api is not None and\n            len([d for d in densities if d.ref_temp_k == 288.15]) == 0):\n        kg_m_3, ref_temp_k = estimate_density_from_api(imported_rec.api)\n\n        densities.append(Density(kg_m_3=kg_m_3,\n                                 ref_temp_k=ref_temp_k,\n                                 weathering=0.0))\n\n    return sorted(densities, key=lambda d: d.ref_temp_k)\n\ndef oil_density_at_temp(imported_rec, temperature=288.15, weathering=0.0):\n    densities = oil_get_densities(imported_rec, weathering=weathering)\n\n    # set the minimum temperature to be the oil's pour point\n    min_temp = np.min([t for t in oil_pour_point(imported_rec)] +\n                      [d.ref_temp_k for d in densities])\n\n    temperature = np.clip(temperature, min_temp, 1000.0)\n\n    ref_density, ref_temp_k = get_reference_densities(densities, temperature)\n    k_rho_t = oil_vol_expansion_coeff(densities, temperature)\n\n    rho_t = estimate_density_at_temp(ref_density, ref_temp_k, temperature, k_rho_t)\n\n    return estimate_density_at_temp(ref_density, ref_temp_k, temperature, k_rho_t)\n\n```\n\n\n```python\npp.pprint(oil_get_densities(imported_rec))\n\ntemp_k = (260.0, 270.0, 275.0, 280.0, 285.0, 300)\n\nprint\nprint oil_density_at_temp(imported_rec, temp_k)\n\nfor t in temp_k:\n    print\n    print oil_density_at_temp(imported_rec, t),\n    \n```\n\n    [ <Density(1010.0 kg/m^3 at 273.0K)>,\n      <Density(1000.0 kg/m^3 at 278.0K)>,\n      <Density(1000.0 kg/m^3 at 283.0K)>,\n      <Density(977.0 kg/m^3 at 288.0K)>,\n      <Density(977.885279889 kg/m^3 at 288.15K)>]\n    \n    [ 1013.2423756   1012.4298316   1006.01577909  1000.           990.88386841\n       968.70198507]\n    \n    [ 1013.2423756]\n    [ 1012.4298316]\n    [ 1006.01577909]\n    [ 1000.]\n    [ 990.88386841]\n    [ 968.70198507]\n\n\n\n```python\nplt.figure(1, figsize=(12,8))\nax = plt.subplot(111)\n\noil_obj = session.query(ImportedRecord).filter(ImportedRecord.oil_name == \"COLD LAKE BITUMEN\").one()\n#oil_obj = session.query(ImportedRecord).filter(ImportedRecord.adios_oil_id == 'AD00102').one()\n\nprint 'Oil: {}, Adios ID: {}'.format(oil_obj.oil_name, oil_obj.adios_oil_id)\n\ndensities = oil_get_densities(oil_obj)\nfor d in densities:\n    print (d.kg_m_3, d.ref_temp_k, d.weathering)\n\nref_t = [d.ref_temp_k for d in densities]\nref_d = [d.kg_m_3 for d in densities]\nax.plot(ref_t, ref_d, 'o')\n\ntemps = np.linspace(260.0, 320.0, 200)\nrho_t = oil_density_at_temp(oil_obj, temps)\n\nax.plot(temps, rho_t, '-')\n\nax.set_xlabel(r'temperature ($\\degree K$)')\nax.set_ylabel(r'density ($kg/m^3$)')\n```\n\nOk that's not too bad.  We have a linear interpolation between measured densities, the expansion coefficient above and below the range of our measured densities, at least for this oil, is 0.0008, and we cut off the lower temperature densities at the oil's pour point.\n\n\n```python\n\n```\n", "meta": {"hexsha": "fb331a0c28e39f608c6e7b8d11928addde6828b1", "size": 415255, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "documentation/notebooks/Oil_Properties_Estimation.ipynb", "max_stars_repo_name": "gauteh/OilLibrary", "max_stars_repo_head_hexsha": "4e4f758863d5ff8351cb6eaeb138dadba1e6c267", "max_stars_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2016-12-15T14:54:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-08T09:05:08.000Z", "max_issues_repo_path": "documentation/notebooks/Oil_Properties_Estimation.ipynb", "max_issues_repo_name": "gauteh/OilLibrary", "max_issues_repo_head_hexsha": "4e4f758863d5ff8351cb6eaeb138dadba1e6c267", "max_issues_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2016-11-15T20:58:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T22:30:55.000Z", "max_forks_repo_path": "documentation/notebooks/Oil_Properties_Estimation.ipynb", "max_forks_repo_name": "gauteh/OilLibrary", "max_forks_repo_head_hexsha": "4e4f758863d5ff8351cb6eaeb138dadba1e6c267", "max_forks_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2016-12-18T08:22:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-02T12:57:15.000Z", "avg_line_length": 95.9018475751, "max_line_length": 40230, "alphanum_fraction": 0.8103815728, "converted": true, "num_tokens": 31786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.08389037724901396, "lm_q1q2_score": 0.040307537561546446}}
{"text": "--- \nProject for the course in Microeconometrics | Summer 2020, M.Sc. Economics, Bonn University | [Marc Kerstan](https://github.com/McKers)\n\n# Replication of Thushyanthan Baskaran and Zohal Hessami (2018) <a class=\"tocSkip\">   \n---\n\nIn this notebook are my results of the replication of the core results of the following paper:  \n\n* Baskaran, Thushyanthan, and Zohal Hessami. 2018. \"Does the Election of a Female Leader Clear the Way for More Women in Politics?\" American Economic Journal: Economic Policy, 10 (3): 95-121. DOI: 10.1257/pol.20170045\n\n- The original paper and its corresponding data are  available at: https://www.aeaweb.org/articles?id=10.1257/pol.20170045. <br>\n\n- For the purpose of comparison are all tables and figures presented in section 5 named as in the original paper\n\n\n---\n\n\n```python\nimport pandas as pd\nimport numpy as np \nimport matplotlib.pyplot as plt \nimport matplotlib.image as mpimg\nimport seaborn as sb\nimport statsmodels as sm\nimport statsmodels.formula.api as smf\nimport statsmodels.api as sm_api\nimport scipy.interpolate\nimport rpy2\nimport rpy2.robjects as ro\n```\n\n\n```python\nfrom rpy2.robjects.packages import importr\nfrom rpy2.robjects import DataFrame, FloatVector\nfrom matplotlib.pyplot import figure\nfrom auxiliary.functions import *\nfrom auxiliary.data_processing import *\nfrom auxiliary.plots import *\nfrom localreg import *\nfrom IPython.display import Image\n```\n\n---\n\n\n```python\nutils = importr(\"utils\")\nutils.chooseCRANmirror(ind=1)\nutils.install_packages(\"rdrobust\")\nutils.install_packages(\"foreign\")\nutils.install_packages(\"rdd\")\nrdrobust =importr(\"rdrobust\")\nrddpack=importr(\"foreign\")\nrddpack=importr(\"rdd\")\ngrdevices = importr('grDevices')\n```\n\n---\n# Table of contents\n1. [Introduction](#introduction)\n2. [Experiment Setting & Voting System](#Experiment_Setting_&_Voting_System)\n3. [Identification](#ID)\n4. [Empirical Analysis](#Empirical_Analysis)    \n5. [Replication Study](#Replication_Study) \n    1. [Data and Descriptive Summary](#Data_and_Descriptive_Summary)\n    2. [Vailidity of the RD Design](#Vailidity_of_the_RD_Design)\n        1. [Pretreatment Municipality Characteristics](#Pretreatment_Municipality_Characteristics)\n        2. [Discontinuity in Density](#Discontinuity_in_Density)\n        3. [Confoundedness with Mayor Ideology](#Confoundedness_with_Mayor_Ideology)\n    3. [Main Results](#Main_Results)\n        1. [Graphical Evidence](#Graphical_Evidence)\n        2. [Main Result I](#Main_Result_I)\n        3. [Main Result II](#Main_Result_II)\n6. [Extension](#Extension) \n    1. [Data and Descriptive Summary for Main Analysis](#Data_and_Descriptive_Summary_for_Main_Analysis)\n    2. [Treatment Effect Heterogeneity with Regards to Council Candidate Characteristics](#Treatment_Effect_Heterogeneity_with_Regards_to_Council_Candidate_Characteristics)\n7. [Critical Assessment and Conclusion](#Critical_Assessment_and_Conclusion) \n8. [References](#Keks)\n\n\n---\n# 1. Introduction <a name=\"introduction\"></a>\n---\n\nBaskaran & Hessami (2018) analyze the impact of the election of a female mayor on the subsequent electoral results of female local council candidates. The setting of this analyzes is the german federal State Hesse where both, the mayor and the local council are important administrative/political institutions on a municipality-level. The election of the local council follows an open list electoral rule, which enables the authors to measure the performance of candidates with two independent variables. The first is the election status, meaning that a female candidate has been elected to the local council or not. The second variable is the rank improvement of a candidate on their party list. Since voters can allocate their votes relatively freely across parties and candidates, individual candidates can be promoted or demoted on their party list. By relating rank improvement on the party list to the gender of a candidate the authors can assess the performance of female candidates, regardless of election status. <br>\nAs women generally remain underrepresented in politics the analysis by the authors gives insight on how voters react to female politicians and through which channels underrepresentation of women in politics can be counteracted. By implementing a **regression discontinuity design** for **close gender-mixed mayor elections** the authors find a significant positive effect on the performance of female candidates in council elections if a  female mayor has been elected into office in the previous election. This leads the authors to conclude that the election of a high ranking female politician reduces anti-female voter bias, in turn suggesting that an effective way to eliminate the underrepresentation of women in politics is to encourage women to compete for high ranking political office. Overall my replication supports the findings made by Baskaran & Hessami (2018).\n\n\n\n\n| **Treatment**  | **Main outcomes**  | **Assignment Variable**  | **Main Covariates**  |\n|---|---|---|----|\n| Female Mayor   |  Rank Improvment   | Margin of Victory        | Municipality Characteristics   |\n|                |  Election Status   |                          | Party of Mayor  |\n\nThe remainder of this notebook is structured as follows. Section 2 describes the experimental setting and the voting systems as presented by Baskaran and Hessami (2018). Their strategy to identify a causal effect the authors will be shown in section 3. Section 4 explains the empirical methodology used by the authors. In section 5, I conduct my replication study of the main results. Extensions to the original paper are in section 6 and section 7 concludes this notebook.\n\n---\n# 2. Experiment Setting & Voting System <a name=\"Experiment_Setting_&_Voting_System\"></a>\n---\n\nGenerally speaking, municipalities and equivalently municipality administrations in Hesse have enough (political) autonomy to affect the life of its citizens. They provide various public goods such as daycare facilities and social services, while also determining several regulations such as traffic rules or closing hours. Political decision-makers in the city council can, therefore, excel a significant influence on their citizens. <br>\nThe single highest-ranking official within a municipality is its mayor. The mayor is appointed for six years through the election by the citizens of that municipality. In most cases, a candidate for mayors office is a member of a party in the municipality (although it is possible to run as an independent candidate). Consequently, a small and a large field of candidates is possible. The winner of the election is determined by absolute majority rule in a maximum of two election rounds. If in the first round no candidate can reach an absolute majority of votes, a second-round will be conducted, with the two candidates, that received the most votes in the first round. The winner of that round becomes the elected mayor of that municipality. <br>\nOn a municipality level, the main decision-making body is the local council (that can be interpreted as a municipality-level parlament). It monitors the administration and decides upon important local policy decisions.\nFor all municipalities in Hesse, the election of council members takes place at a uniform date, and council members are elected for five years. The voting system follows an open-list electoral rule, which has two key properties for the analysis of Baskaran and Hessami (2018). The first one is that before the election parties set up a list of candidates for the upcoming election. On this list, every candidate is assigned a rank, ranging from one to the maximum number of council seats available (a lower number of candidates than council seats, is equally possible).<br> For an individual candidate to become a council member two factors are relevant. First, the number of list candidates that are elected is determined by the overall share of votes a party receives. Secondly, which candidate becomes a city council member is influenced by the rank of the candidate, where ranks with a lower number are advantageous as it increases the likelihood of receiving a council seat.<br>\nThe second relevant property is that voters can allocate their votes in various manners. Generally, every voter has as many votes as there are council seats available. The simplest way would be to make a cross for the entire party. Assuming that the list has as many candidates as there are council seats, every candidate would receive one vote. In the case that the list is shorter than the number of candidates, the first few candidates would receive an additional vote until the maximum number of votes is reached. Next, there is the possibility to strike out individual candidates on a party list, resulting again in additional votes for the candidates placed at the top of the list. However, there is also the possibility to allocate the votes on individual candidates across different parties, where three votes are the maximum a candidate can receive from one voter. This enables candidates to accumulate more votes than the candidate placed in front of him in the initial list. That implies that the candidate would move up in ranks the post-election list and has an increased chance of receiving a set. Intuitively, this rank improvement expresses the preference for a specific candidate relative to other candidates, independent of the appointment to the city council.\n\n---\n# 3. Identification <a name=\"ID\"></a>\n---\n\nBaskaran and Hessami (2018) analyze the impact of a female mayor on the average performance of female council candidates. Ideally, one would set up a randomized experiment to quantify the effect of such treatment, where municipalities are randomly assigned to treatment and control groups. The election of a female mayor can then be interpreted as an exogenous treatment for the municipality. One can then compare the performance of female candidates in the subsequent council election of the treatment group and the control group to determine the average treatment effect. Since treatment is assigned randomly we can neglect underlying characteristics in municipalities which might affect the magnitude of the treatment effect on female council candidate performance.<br> Denoting the average performance of a female council candidate as $Y$ and the corresponding treatment indicator as $D$, the average treatment effect is the difference in expected outcomes, conditional on treatment status:\n<br>\n\\begin{equation} \nE[Y\\mid D=1]-E[Y\\mid D=0]=\\tau_{r}\n\\end{equation}\n<br>\nwhere D is 1 if a female mayor has been \"assigned\" in the last election and 0 for the other case. $\\tau$ is then our unbiased average treatment effect. <br>\nHowever, the expression above does not result in an unbiased estimator of the treatment effect in the setting by Baskaran and Hessami (2018). This is because in this environment treatment assignment is not random, but determined by the outcome of an election. Due to the complex nature of voting decisions in political elections, it is reasonable to assume that there are many possible confounding factors when it comes to the choice if a municipality selects into treatment by electing a female mayor (and vice versa). An intuitive example in this context would be a possible distaste for women in politics. If such a confounding factor is present, this would not only affect the performance of a female council candidate but also the assignment into treatment and control group, as it is unlikely for a municipality with such a distaste to select into treatment. An unbiased estimation based on the equation above is then not possible because treated and untreated groups differ significantly in their observable and unobservable characteristics. This problem can be visualized by causal graph 1.  \n\nCausal Graph 1\n\n\n\nThe goal is to identify the effect of D on the outcome variable $Y$. However,  there are two challenges in this setting. The first one is the relationship of the assignment variable $X$ with the variables $W$ and $U$. As one can see, the status of the treatment indicator D is determined by the variable $X$. In the setting of Baskaran and Hessami (2018) $X$ is the margin of victory of a female candidate for the office of mayor in a mixed-gender election. If a female mayor candidate is victorious, the assignment variable would take on a positive value and induce the treatment indicator $D$ to be one. In case of a defeat of the female mayor candidate, $X$ is negative, no treatment takes place and the respective municipality is in the control group. Consequently, the factors determining the margin of victory also affect the assignment of treatment. These factors are summarized as the variables $W$ and $U$, which represent all observable and unobservable factors that influence the margin of victory of a female mayor. Since these variables influence treatment assignment, the split of  the  test population into control and treatmen group is non-random. Usually, this issue is solved by conditioning on these variables. But this is only partially possible here since it is not possible to condition on unobservable characteristics.   <br>\nThe second problem is the confounding nature of the variable $X$, because the margin of victory might not only affect the performance of female candidates through the assignment of treatment. $X$ itself may exert an effect on the performance of female council candidates. An example would be a landslide victory of a male mayor candidate against an unqualified female mayor candidate. In this case, the municipality would select into the control group, but due to the weak performance of the female candidate, voters might relate this performance to the gender of council candidates in a subsequent council election, resulting in a weak electoral result of female candidates. Again,  one would try to solve this problem by conditioning on the $X$, and observe the treatment effect for different subgroups of $X$. Unfortunately, this is not possible in our setting due to the role of $X$ as assignment variable of treatment. This can be illstrated by assuming (for simplicity) that $X$ can only take on two realizations that satisfy: $x_1<0<x_2$. In this case, we cannot observe the impact of treatment in the population where $X=x_1$, since being in $x_1$ and simultaneously being assigned to treatment is mutually exclusive. <br> Facing these problems one cannot identify a causal relationship based on the back-door-criterion as it is not possible to close all backdoor paths.\n  \nTo overcome these issues and identify a causal effect of $D$ on $Y$, Baskaran & Hessami (2018) apply a regression discontinuity design. The underlying idea of this approach is that under a certain condition,  treatment assignment to the test population is locally randomized around a predefined cutoff value. This requires that treatment takes place just above the cutoff, whereas under it no treatment takes place. Under this quasi-randomized experimental setting causal interpretation of a treatment effect is possible, since agents who are just below the threshold of receiving treatment represent reasonable counterfactuals of those that receive treatment. <br> In Baskaran & Hessami (2008) the cutoff value for treatment is reached ones a female mayor candidate receives more than $50\\%$ of votes, meaning that $X$ is positive. Following the logic of a regression discontinuity design, we can now treat the assignment of treatment  as locally randomized close to this cutoff.<br>\nHowever, for an regression discontinuity design to be valid in identifying a causal effect, the test population (municipality) has to be unable to precisely manipulate the assignment variable around the cutoff, meaning they may only exert imprecise control over the assignment variable close to the cutoff. This can intuitively be explained by thinking of a mayor election between two candidates, where all votes but one are counted and amount to a draw. The last voter then decides to make his voting decision by a coin flip. While voters were generally able to manipulate the assignment variable to be close to the cutoff, the voters were only able to manipulate it imperfectly as the final treatment assignment was determined entirely by chance. <br>\nA more formal definition is given by:\n\n<h5 align=\"center\" >\"We say individuals have imprecise control over $X$ when conditional on $W$ $=$ $w$ and $U$ $=$ $u$, the density of $V$ (and hence $X$) is continuous.\" (Lee and Lemieux,2010,p.295)</h5>  \n\nMathematically, this takes on the following form\n\\begin{align*}\nPr[W = w, U = u \\mid X = x]. \n\\end{align*}\nApplying Bayes' theorem and setting $x=c$, with c being the cutoff of treatment assignment, it follows that\n\n\\begin{align*}\n& \\Pr[W = w, U = u \\mid X = c] \n\\quad = \\quad f(c \\mid W = w, U = u) \\quad\\frac{\\Pr[W = w, U = u]}{f(c)}.\n\\end{align*}\n\nThe expression implies that $W$ and $U$ follow the same conditional distribution at the cutoff, independant of treatment assignment. Accordingly treatment assignment is \"as good as random\" (Lee and Lemieux,2010,p.295), as all differences in realizations of $W$ and $U$ are determined by chance. The implication is that the treatment effect takes on  the following form\n\\begin{align*}\n  &\\lim_{\u03b5\u21930}E[Y|X =\u2009c +\u2009\u03b5]-\\lim_{\u03b5\u21910}E[Y |X =\u2009c +\u2009\u03b5]\\quad=\\quad\u2009\u03c4.\n\\end{align*}\n\n\nFor the setting in Baskaran and Hessami (2018), if the criterion of imprecise control near the cutoff is fulfilled causal inference is possible as presented by causal graph 2.\n\n\nCausal Graph 2\n\n\n\nThis graph follows the same logic as causal graph 1, with the difference that we restrict our view to values of $X$ close around the cutoff of treatment assignment. First, notice that the assignment variable is no longer a confounding factor since all effects of $X$ on  $Y$ are only due to the change in treatment assignment. Similarly, W and U now follow the same distribution on either side of the cutoff. Consequently, their realization is randomly determined for a given municipality and not correlated with $X$. <br>\nIn the setting of Baskaran and Hessami (2018) this means that if we restrict our look to mix gender elections, where the female or male candidate for mayors office, won the election by a margin \"small enough\", all observable and unobservables that could influence treatment assignment are now (locally) random. Accordingly,  this implies the arbitrary designation of treatment. Consequently, a causal interpretation of the victory of a female candidate is possible for close gender-mixed elections. \n\n---\n# 4. Empirical Analysis <a name=\"Empirical_Analysis\"></a>\n---\n\nIn order to determine the treatment effect, the authors consider $two$ $different$ $dependant$ $variables$, the $rank$ $improvement$ of a female candidate within a party voting list and secondly the $gender$ $of$ $an$ $elected$ $council$ $candidate$. The authors formalize the  former  as follows:\n\n<br>\n\\begin{equation} \nrank\\: improvement = \\left(\\frac{initial\\:rank - final\\:rank}{council\\:size}\\right) \\times   100\n\\end{equation}\n\n<br>\nFollowing this design improvement in ranks, meaning a candidate receives more preferential votes than the candidate in front of him on the initial list, has a positive sign, and degradation is labeled with a minus sign. The change in ranks is then normalized by council size and multiplied by 100 to ensure comparability between different municipalities since the actual number of council seats differ considerably. <br>\nThe $second$ $dependant$ $variable$ is a dummy variable that takes on the value one if an elected council candidate is female and zero otherwise. Consequently, the analysis of these dependant variables differs in their sample structure, since the analysis on rank improvement only includes female candidates which may or may not have been elected. However, the second analysis includes all candidates that won a council seat, independent of gender.<br>\nThe effect of a female mayor for both dependent variables is estimated by linear and quadratic local regression using identical functional designs for both outcome variables. Formally, the regression model is \n\n\n\n\\begin{equation} \ndependant\\:variable_{k,i,t}\\:=\\:\\alpha\\:+\\:\\beta female\\: mayor_{i,t} \\:+\\:f(vote\\:margin)_{i,t}\\:+\\:female\\:mayor_{i,t}\\:\\times\\:g(vote\\:margin)_{i,t}\\: + \\:\\varepsilon_{k,i,t}.\n\\end{equation}\n\n\nThe indices $k$,$i$, and $t$ refer to the individual council candidate, the municipality, and the year of the council election respectively. Variable $female$ $mayor$ is a dummy that takes on the value one if a female mayor was elected in the last mayoral election. The functions  $f(\\cdot)$ and $g(\\cdot)$ are linear (or quadratic) functions of $vote$ $margin$, the percentage margin of victory of the female mayor candidate in the preceding mayor election, our assignment variable in the regression discontinuity design. Since we want to explore the impact of a female mayor, the margin of victory is positive above the cutoff of 0% and negative otherwise, implying the defeat of the female candidate. <br>\nIn addition to the functional form of the regression, the chosen bandwidth, the amount of data included in the estimation relative to the cutoff point, is critical. In order to achieve an unbiased treatment we rely on the criteria of local randomization as argued above. This would encourage to restrict our analysis as close as possible to the cutoff. This however implies that less  data is available to estimate the treatment, effect resulting in higher variance in the estimation of the treatment effect. To overcome this problem, Baskaran & Hessami (2018) estimate equation (2) for five different bandwidths for each of the outcome variables. The bandwidths chosen are the ones proposed by Calonico, Cattaneo, and Titiunik (2014), half of this bandwidth, and double of it. Estimates according to the bandwidth proposed by Imbens & Kalyanaraman (2012) are also included. Additionally, one model estimates the effect by including quadratic terms of $vote$ $margin$ and its interaction with $female$ $mayor$. The underlying process to determine the bandwidth for this specification is again chosen according to Calonico, Cattaneo, and Titiunik (2014). For all calculations, the authors use heteroscedasticity-robust and municipality-level clustered standard errors for hypothesis testing.\n\n---\n# 5. Replication Study <a name=\"Replication_Study\"></a>\n---\n\n---\n## 5.1 Data and Descriptive Summary <a name=\"Data_and_Descriptive_Summary\"></a>\n---\n\nTo assess the data used by Baskaran and Hessami (2018) a distinction between the data for mayoral elections and the data for council elections has to be made.\nThe data set for mayoral elections stems directly from the Statistical Office of Hesse and contains data on all mayoral elections taking place between 1993  -2015, including dates, number of votes, party affiliation,  gender and names of the  respective candidate.<br>\nThe data for council elections is less consistent. For council elections in the year 2016 administrative data is provided by the Statistical Office of Hesse (consisting of the initial list rank, their final position as well as gender and name). This type of data is not available for previous elections, which required the authors to hand collect the data through various means of communication with municipality administration officials and official municipality websites.<br>\n\n## Figure 1. Sample Coverage\n\n\n```python\ndata=pd.read_stata(\"Data/main_dataset.dta\")\nfig1_a=data_fig1_a(data)\nfig1_b=data_fig1_b(data)\nplt1_1=(fig1_a)\nplt2_1=(fig1_b)\nfigure1_plot(plt1_1,plt2_1)\n```\n\nFigure 1 depicts the overall sample coverage of local council elections analyzed by the authors. The bar chart on the left-hand side shows the total number of single municipalities in the sample, clustered by years of council elections. The right-hand side shows the same statistic but on an individual candidate level. As it is visible the data coverage declines considerably when moving further into the past. This is attributed to the fact that the authors had to collect the data for those elections manually since no central source was available.\n\n## Table 1 - Summary Statistics For Candidate Characteristics\n\n### All council candidates \n\n\n```python\nTable1_a=table1(data, dictionary_table1(), female=False)\nTable1_a\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>max</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Rank improvement (normalized)</th>\n      <td>109017.0</td>\n      <td>0.066676</td>\n      <td>13.253290</td>\n      <td>-89.189186</td>\n      <td>97.297295</td>\n    </tr>\n    <tr>\n      <th>Initial list rank (normalized)</th>\n      <td>109017.0</td>\n      <td>40.101704</td>\n      <td>26.774668</td>\n      <td>0.000000</td>\n      <td>100.000000</td>\n    </tr>\n    <tr>\n      <th>Age</th>\n      <td>54676.0</td>\n      <td>51.580711</td>\n      <td>13.780560</td>\n      <td>18.000000</td>\n      <td>102.000000</td>\n    </tr>\n    <tr>\n      <th>High school</th>\n      <td>48729.0</td>\n      <td>0.650578</td>\n      <td>0.476792</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>University</th>\n      <td>48729.0</td>\n      <td>0.281598</td>\n      <td>0.449783</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Phd</th>\n      <td>48729.0</td>\n      <td>0.067824</td>\n      <td>0.251446</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Architect</th>\n      <td>49399.0</td>\n      <td>0.008603</td>\n      <td>0.092356</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Businesswoman/-man</th>\n      <td>49399.0</td>\n      <td>0.075892</td>\n      <td>0.264828</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Engineer</th>\n      <td>49399.0</td>\n      <td>0.055305</td>\n      <td>0.228576</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Lawyer</th>\n      <td>49399.0</td>\n      <td>0.031377</td>\n      <td>0.174337</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Civil administration</th>\n      <td>49399.0</td>\n      <td>0.077309</td>\n      <td>0.267084</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Teacher</th>\n      <td>49399.0</td>\n      <td>0.051661</td>\n      <td>0.221344</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Employed</th>\n      <td>55416.0</td>\n      <td>0.714721</td>\n      <td>0.451551</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Self-employed</th>\n      <td>55416.0</td>\n      <td>0.058467</td>\n      <td>0.234626</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Student</th>\n      <td>55416.0</td>\n      <td>0.044392</td>\n      <td>0.205965</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Retired</th>\n      <td>55416.0</td>\n      <td>0.143930</td>\n      <td>0.351021</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Housewife/-husband</th>\n      <td>55416.0</td>\n      <td>0.022900</td>\n      <td>0.149585</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### Female council candidates\n\n\n```python\nTable1_b=table1(data, dictionary_table1(), female=True)\nTable1_b\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>max</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Rank improvement (normalized)</th>\n      <td>28480.0</td>\n      <td>-0.458683</td>\n      <td>11.933606</td>\n      <td>-89.189186</td>\n      <td>97.297295</td>\n    </tr>\n    <tr>\n      <th>Initial list rank (normalized)</th>\n      <td>28480.0</td>\n      <td>38.816017</td>\n      <td>26.086885</td>\n      <td>0.000000</td>\n      <td>100.000000</td>\n    </tr>\n    <tr>\n      <th>Age</th>\n      <td>13923.0</td>\n      <td>51.035049</td>\n      <td>13.602677</td>\n      <td>18.000000</td>\n      <td>96.000000</td>\n    </tr>\n    <tr>\n      <th>High school</th>\n      <td>11734.0</td>\n      <td>0.671723</td>\n      <td>0.469606</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>University</th>\n      <td>11734.0</td>\n      <td>0.277399</td>\n      <td>0.447734</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Phd</th>\n      <td>11734.0</td>\n      <td>0.050878</td>\n      <td>0.219757</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Architect</th>\n      <td>11832.0</td>\n      <td>0.006930</td>\n      <td>0.082963</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Businesswoman/-man</th>\n      <td>11832.0</td>\n      <td>0.064148</td>\n      <td>0.245027</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Engineer</th>\n      <td>11832.0</td>\n      <td>0.013861</td>\n      <td>0.116918</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Lawyer</th>\n      <td>11832.0</td>\n      <td>0.035159</td>\n      <td>0.184189</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Civil administration</th>\n      <td>11832.0</td>\n      <td>0.058147</td>\n      <td>0.234032</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Teacher</th>\n      <td>11832.0</td>\n      <td>0.078178</td>\n      <td>0.268463</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Employed</th>\n      <td>14043.0</td>\n      <td>0.697501</td>\n      <td>0.459357</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Self-employed</th>\n      <td>14043.0</td>\n      <td>0.036175</td>\n      <td>0.186731</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Student</th>\n      <td>14043.0</td>\n      <td>0.051627</td>\n      <td>0.221281</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Retired</th>\n      <td>14043.0</td>\n      <td>0.112868</td>\n      <td>0.316442</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Housewife/-husband</th>\n      <td>14043.0</td>\n      <td>0.088015</td>\n      <td>0.283327</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nTable 1 presents summary statistics on (normalized) rank improvement, initial list rank, age, and occupational characteristics of candidates. The first table contains data on all council candidates while the second one is restricted to female candidates. The fact that we observe a (small) positive average rank improvement for all candidates is attributed to the normalization as outlined in section 4. Additionally, it is noteworthy that on average women are demoted by voters. To determine the signficance of this finding \n\n## Table A.2: Differences In Initial List Placement And Rank Improvement, Female vs. Male Candidates \n\n\n```python\ntt_rank=t_test_prepare_rank(data)\nttest(tt_rank,\"Rank\")\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Treatment</th>\n      <th>Control</th>\n      <th>Diff</th>\n      <th>Std. Error</th>\n      <th>Observations</th>\n    </tr>\n    <tr>\n      <th>Rank</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Rank improvement (normalized)</th>\n      <td>-0.459000</td>\n      <td>0.252</td>\n      <td>-0.711***</td>\n      <td>0.091</td>\n      <td>109017.0</td>\n    </tr>\n    <tr>\n      <th>Initial list rank (normalized)</th>\n      <td>38.816002</td>\n      <td>40.556</td>\n      <td>-1.74***</td>\n      <td>0.185</td>\n      <td>109017.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThe table above presents the results of t-tests performed to test whether there are significant differences in the rank improvement and initial rank between female and male candidates. Following the results, female candidates perform worse in rank improvement and are initially placed better than male candidates. However, these results are far from conclusive, since the underlying mechanism (list placement of candidates by parties) or potential omitted variables are neglected.\n\n---\n## 5.2 Vailidity of the RD Design <a name=\"Vailidity_of_the_RD_Design\"></a>\n---\n\nAs described in section 4,  the validity of a regression discontinuity design depends on the assumption that agenst habe only imprecise control over the assignment variable at the cutoff. Baskaran and Hessami (2018) perform therefore several different test in order to show the validity of their approach.\n\n### 5.2.1 Pretreatment Municipality Characteristics <a name=\"Pretreatment_Municipality_Characteristics\"></a>\n---\n\nOne possible pitfall for the validity of the outlined methodology could be if municipalities that elect a female mayors differ structurally from those that do not. To test if this is the case the authors perform t-tests on several observable characteristics of municipalities. For these tests, the sample as outlined above is reduced to data of council elections, where the previous mayor election was between candidates of a different gender. Since this subset of the data will be used frequently from now on, this sample will be referred to as **rdd-sample**.\n\n## Table A.4: Validity Test I: Differences In Municipality Characteristics With Female And Male Mayors\n\n\n```python\nmayor_df=pd.read_stata(\"Data/mayor_election_data.dta\")\nmunicipality_df=pd.read_stata(\"Data/municipality_characteristics_data.dta\")\ndf_ttest_ch=mayor_df.merge(right= municipality_df, how='inner', on=['gkz','jahr']).loc[(mayor_df[\"rdd_sample\"] == 1)]\ndf_ttest_ch_10=subset_by_margin(df_ttest_ch,10)\ntest_ch_all=t_test_prepare_cha(df_ttest_ch)\nttest(test_ch_all,\"Municipality Characteristics\")\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Treatment</th>\n      <th>Control</th>\n      <th>Diff</th>\n      <th>Std. Error</th>\n      <th>Observations</th>\n    </tr>\n    <tr>\n      <th>Municipality Characteristics</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Log(population)</th>\n      <td>9.384</td>\n      <td>9.211</td>\n      <td>0.173</td>\n      <td>0.121</td>\n      <td>268.0</td>\n    </tr>\n    <tr>\n      <th>Log(land area)</th>\n      <td>3.632</td>\n      <td>3.611</td>\n      <td>0.021</td>\n      <td>0.100</td>\n      <td>268.0</td>\n    </tr>\n    <tr>\n      <th>Log(debt p.c.)</th>\n      <td>-0.364</td>\n      <td>-0.513</td>\n      <td>0.149</td>\n      <td>0.118</td>\n      <td>268.0</td>\n    </tr>\n    <tr>\n      <th>Log(tax revenues p.c.)</th>\n      <td>-0.392</td>\n      <td>-0.430</td>\n      <td>0.038</td>\n      <td>0.053</td>\n      <td>268.0</td>\n    </tr>\n    <tr>\n      <th>Log(local gov. employment p.c.)</th>\n      <td>-5.129</td>\n      <td>-5.158</td>\n      <td>0.029</td>\n      <td>0.051</td>\n      <td>268.0</td>\n    </tr>\n    <tr>\n      <th>Log(female share, local gov. employment)</th>\n      <td>-1.076</td>\n      <td>-1.156</td>\n      <td>0.08*</td>\n      <td>0.046</td>\n      <td>265.0</td>\n    </tr>\n    <tr>\n      <th>Log(total employment p.c.)</th>\n      <td>-1.627</td>\n      <td>-1.540</td>\n      <td>-0.087</td>\n      <td>0.076</td>\n      <td>268.0</td>\n    </tr>\n    <tr>\n      <th>Log(female share, total employment)</th>\n      <td>-0.833</td>\n      <td>-0.850</td>\n      <td>0.017</td>\n      <td>0.029</td>\n      <td>268.0</td>\n    </tr>\n    <tr>\n      <th>Log(manufacturing / total employment)</th>\n      <td>-1.137</td>\n      <td>-1.060</td>\n      <td>-0.077</td>\n      <td>0.068</td>\n      <td>268.0</td>\n    </tr>\n    <tr>\n      <th>Log(female share, manufacturing</th>\n      <td>-1.553</td>\n      <td>-1.471</td>\n      <td>-0.082**</td>\n      <td>0.041</td>\n      <td>268.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThe t-tests report statistically significant differences in the shares of female employment in the local administration and the manufacturing industry at a significance level of 10% and 5%. However, this difference vanishes when looking at differences of municipalities closer to the cutoff as the table below shows. \n\n\n```python\ntest_ch_10=t_test_prepare_cha(df_ttest_ch_10)\nttest(test_ch_10,\"Municipality Characteristics\")\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Treatment</th>\n      <th>Control</th>\n      <th>Diff</th>\n      <th>Std. Error</th>\n      <th>Observations</th>\n    </tr>\n    <tr>\n      <th>Municipality Characteristics</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Log(population)</th>\n      <td>9.821</td>\n      <td>9.219</td>\n      <td>0.602*</td>\n      <td>0.300</td>\n      <td>55.0</td>\n    </tr>\n    <tr>\n      <th>Log(land area)</th>\n      <td>3.972</td>\n      <td>3.771</td>\n      <td>0.201</td>\n      <td>0.193</td>\n      <td>55.0</td>\n    </tr>\n    <tr>\n      <th>Log(debt p.c.)</th>\n      <td>-0.264</td>\n      <td>-0.253</td>\n      <td>-0.011</td>\n      <td>0.243</td>\n      <td>55.0</td>\n    </tr>\n    <tr>\n      <th>Log(tax revenues p.c.)</th>\n      <td>-0.306</td>\n      <td>-0.327</td>\n      <td>0.021</td>\n      <td>0.115</td>\n      <td>55.0</td>\n    </tr>\n    <tr>\n      <th>Log(local gov. employment p.c.)</th>\n      <td>-4.929</td>\n      <td>-5.080</td>\n      <td>0.151</td>\n      <td>0.145</td>\n      <td>55.0</td>\n    </tr>\n    <tr>\n      <th>Log(female share, local gov. employment)</th>\n      <td>-1.044</td>\n      <td>-1.146</td>\n      <td>0.102</td>\n      <td>0.098</td>\n      <td>55.0</td>\n    </tr>\n    <tr>\n      <th>Log(total employment p.c.)</th>\n      <td>-1.332</td>\n      <td>-1.490</td>\n      <td>0.158</td>\n      <td>0.152</td>\n      <td>55.0</td>\n    </tr>\n    <tr>\n      <th>Log(female share, total employment)</th>\n      <td>-0.887</td>\n      <td>-0.885</td>\n      <td>-0.002</td>\n      <td>0.058</td>\n      <td>55.0</td>\n    </tr>\n    <tr>\n      <th>Log(manufacturing / total employment)</th>\n      <td>-1.042</td>\n      <td>-0.981</td>\n      <td>-0.061</td>\n      <td>0.126</td>\n      <td>55.0</td>\n    </tr>\n    <tr>\n      <th>Log(female share, manufacturing</th>\n      <td>-1.576</td>\n      <td>-1.484</td>\n      <td>-0.092</td>\n      <td>0.099</td>\n      <td>55.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nRestricting the rdd-sample to a 10 percent margin of victory on both sides of the cutoff reveals no statistically significant differences in the local employment structure. However, at a significance level of 10%, an increased frequency of female mayor in cities with higher populations can be observed. The effect is barely significant and the authors attribute it to the highly skewed distribution of city sizes.\n\n## Table A.5: Validity Test I: Discontinutiy In Predicted Rank Improvement Based on Municipality Characteristics\n\nBaskaran and Hessami (2018) further analyze if the above-observed differences in municipalities result in a discontinuity of the margin of victory at the cutoff. To test this the authors restrict the rdd-sample to female candidates and regress their performance on the observed municipality characteristics. They use the resulting parameters to construct the predicted average rank improvement of a female candidate. These predicted values are then used as the dependant variable in their model shown in section 4.\n\n\n```python\ndata_rdd_f=get_rdd_data(data,female=True)\ndf_TableA5=prepare_table_a5(data_rdd_f)\ndf_A5_r = DataFrame({\"margin_1\": FloatVector(df_TableA5[\"margin_1\"]), \"y_hat\": FloatVector(df_TableA5[\"y_hat\"])})\nCCT_bw_A5=rdrobust.rdbwselect_2014(df_A5_r.rx2('y_hat'), df_A5_r.rx2('margin_1'), c = 0, p = 1, q = 0, deriv = 0,kernel = \"tri\", bwselect = \"CCT\")[2][0]\nIK_bw_A5=rdrobust.rdbwselect_2014(df_A5_r.rx2('y_hat'), df_A5_r.rx2('margin_1'), c = 0, p = 1, q = 0, deriv = 0,kernel = \"tri\", bwselect = \"IK\")[2][0]\nCCT_quad_bw_A5=rdrobust.rdbwselect_2014(df_A5_r.rx2('y_hat'), df_A5_r.rx2('margin_1'), c = 0, p = 2, q = 0, deriv = 0,kernel = \"tri\", bwselect = \"CCT\")[2][0]\nprint(\"The optimal bandwith according to Calonico, Cattaneo & Titiunik (2014) is: {:5.3f}\".format(CCT_bw_A5))\nprint(\"The optimal bandwith according to Imbens & Kalyanaraman (2011) is: {:5.3f}\".format(IK_bw_A5))\nprint(\"The optimal bandwith according to Calonico, Cattaneo & Titiunik (2014) using a quadratic functional form is: {:5.3f}\".format(CCT_quad_bw_A5))\n```\n\n    The optimal bandwith according to Calonico, Cattaneo & Titiunik (2014) is: 18.805\n    The optimal bandwith according to Imbens & Kalyanaraman (2011) is: 35.682\n    The optimal bandwith according to Calonico, Cattaneo & Titiunik (2014) using a quadratic functional form is: 24.763\n\n\n\n```python\nresult1=[df_TableA5,\"linear\",CCT_bw_A5,\"y_hat\",\"CCT\"]\nresult2=[df_TableA5,\"linear\",CCT_bw_A5/2,\"y_hat\",\"CCT/2\"]\nresult3=[df_TableA5,\"linear\",CCT_bw_A5*2,\"y_hat\",\"CCT*2\"]\nresult4=[df_TableA5,\"linear\",IK_bw_A5,\"y_hat\",\"IK\"]\nresult5=[df_TableA5,\"quadratic\",CCT_quad_bw_A5,\"y_hat\",\"CCT\"]\nreg_tab(result1,result2,result3,result4,result5)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Female Mayor</th>\n      <th>Std.err</th>\n      <th>Bandwidth type</th>\n      <th>Bandwidth size</th>\n      <th>Polynomial</th>\n      <th>Observations</th>\n      <th>Elections</th>\n      <th>Municipalities</th>\n      <th>Mean</th>\n      <th>Std.err (Mean)</th>\n    </tr>\n    <tr>\n      <th>Model</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>(1)</th>\n      <td>0.422</td>\n      <td>0.801</td>\n      <td>CCT</td>\n      <td>18.8</td>\n      <td>Linear</td>\n      <td>71.0</td>\n      <td>71.0</td>\n      <td>52.0</td>\n      <td>-0.45</td>\n      <td>1.172</td>\n    </tr>\n    <tr>\n      <th>(2)</th>\n      <td>0.408</td>\n      <td>1.142</td>\n      <td>CCT/2</td>\n      <td>9.4</td>\n      <td>Linear</td>\n      <td>44.0</td>\n      <td>44.0</td>\n      <td>35.0</td>\n      <td>-0.52</td>\n      <td>1.188</td>\n    </tr>\n    <tr>\n      <th>(3)</th>\n      <td>0.855*</td>\n      <td>0.508</td>\n      <td>CCT*2</td>\n      <td>37.61</td>\n      <td>Linear</td>\n      <td>143.0</td>\n      <td>143.0</td>\n      <td>96.0</td>\n      <td>-0.54</td>\n      <td>1.160</td>\n    </tr>\n    <tr>\n      <th>(4)</th>\n      <td>0.847</td>\n      <td>0.525</td>\n      <td>IK</td>\n      <td>35.68</td>\n      <td>Linear</td>\n      <td>136.0</td>\n      <td>136.0</td>\n      <td>94.0</td>\n      <td>-0.53</td>\n      <td>1.162</td>\n    </tr>\n    <tr>\n      <th>(5)</th>\n      <td>0.114</td>\n      <td>1.032</td>\n      <td>CCT</td>\n      <td>24.76</td>\n      <td>Quadratic</td>\n      <td>101.0</td>\n      <td>101.0</td>\n      <td>74.0</td>\n      <td>-0.50</td>\n      <td>1.164</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nTesting the model for the variations as outlined in section 4, the regression shows a significant effect of a female mayor for model 3. However, the effect is barely significant and vanishes as we move closer to the cutoff. The corresponding regression discontinuity plot of the predicted average rank improvement relative to the assignment variable can is presented below.\n\n## Figure A.1: Validity Test I: Predicted (Normalized) Rank Improvement Based Municipality Characteristics\n\n\n```python\nfigure_A1=subset_by_margin(df_TableA5,30)\nrdd_plot(figure_A1,3,CCT_bw_A5,100,1,\"y_hat\")\n```\n\n---\n<span style=\"color:red\">**NOTE**:</span> \n  The confidence intervals above are the result of 100 iterations of resampling the data by bootstrapping. Increasing the number of iterations does not yield different results and only increases the runtime of this notebook.\n---\n\nThe dots are the local averages of the predicted rank improvement in bins of a 3 percent margin and the lines are the result of a local linear smooth of the data on each side of the cutoff. The colored areas are the 95 percent bootstrapped confidence intervals of the smooth. There is no indication of a discontinuity conditional on municipality characteristics observable.\n\n---\n### 5.2.2 Discontinuity in Density <a name=\"Discontinuity_in_Density\"></a>\n---\n\n## Figure A.2: Validity test II: McCrary Density Plot\n\nThe authors further test for a general discontinuity in running variable at the cutoff by performing the density test proposed by McCrary (2008). The corresponding McCrary plot is depicted below and shows no significant discontinuity.\n\n\n```python\nmayor_df=pd.read_stata(\"Data/mayor_election_data.dta\")\nmayor_df_rdd=mayor_df[mayor_df[\"rdd_sample\"]==1].sort_values(by=['margin_1'])\nmayor_df_r = DataFrame({\"margin_1\": FloatVector(mayor_df_rdd[\"margin_1\"])})\n```\n\n\n```python\ngrdevices.png(file=\"MCC_Test1.png\", width=512, height=512)\np = rddpack.DCdensity(mayor_df_r.rx2(\"margin_1\"),cutpoint=0,plot=True)     \ngrdevices.dev_off()\nimg=mpimg.imread('MCC_Test1.png')\nfig, ax0 = plt.subplots(1, 1, figsize=(12, 8), tight_layout=True)\nax0.imshow(img,aspect='auto')\nplt.axis('off') \nplt.show()\n```\n\n---\n### 5.2.3 Confoundedness with Mayor Ideology <a name=\"Confoundedness_with_Mayor_Ideology\"></a>\n---\n\n## Table A.7: Validity Test III: Differences In Ideology Of Female And Male Mayors\n\nAnother possible pitfall for a causal interpretation of the regression discontinuity design in Baskaran and Hessami (2018) could be the ideological difference in elected male and female mayor. If such a systematic difference is present,  voters might prefer female council members if they think that they can work more effectively with the mayor of a given ideology. Using party affiliation as a proxy for ideological differences the authors test if female and male candidates differ systemically in their party membership.  The results of the corresponding t-tests are presented below, where the first table reports outcomes for the entire rdd-sample, and the second table shows the results for elections where the winner was determined within a 10 percent vote margin. None of the differences are statistically significant, suggesting no difference in ideology between elected female and male mayors.\n\n\n```python\nttest_pa_all=t_test_prepare_party(mayor_df_rdd)\nmayor_df_rdd_test_10=subset_by_margin(mayor_df_rdd,10)\nttest_pa_10=t_test_prepare_party(mayor_df_rdd_test_10)\nttest(ttest_pa_all,\"Party\")\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Treatment</th>\n      <th>Control</th>\n      <th>Diff</th>\n      <th>Std. Error</th>\n      <th>Observations</th>\n    </tr>\n    <tr>\n      <th>Party</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>CDU</th>\n      <td>0.31</td>\n      <td>0.315</td>\n      <td>-0.005</td>\n      <td>0.061</td>\n      <td>268.0</td>\n    </tr>\n    <tr>\n      <th>SPD</th>\n      <td>0.44</td>\n      <td>0.386</td>\n      <td>0.054</td>\n      <td>0.065</td>\n      <td>268.0</td>\n    </tr>\n    <tr>\n      <th>Other</th>\n      <td>0.25</td>\n      <td>0.299</td>\n      <td>-0.049</td>\n      <td>0.059</td>\n      <td>268.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nttest(ttest_pa_10,\"Party\")\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Treatment</th>\n      <th>Control</th>\n      <th>Diff</th>\n      <th>Std. Error</th>\n      <th>Observations</th>\n    </tr>\n    <tr>\n      <th>Party</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>CDU</th>\n      <td>0.448</td>\n      <td>0.308</td>\n      <td>0.14</td>\n      <td>0.130</td>\n      <td>55.0</td>\n    </tr>\n    <tr>\n      <th>SPD</th>\n      <td>0.276</td>\n      <td>0.308</td>\n      <td>-0.032</td>\n      <td>0.123</td>\n      <td>55.0</td>\n    </tr>\n    <tr>\n      <th>Other</th>\n      <td>0.276</td>\n      <td>0.385</td>\n      <td>-0.109</td>\n      <td>0.126</td>\n      <td>55.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n---\n##  5.3 Main Results <a name=\"Main_Results\"></a>\n---\n\n### 5.3.1 Graphical Evidence <a name=\"Graphical_Evidence\"></a>\n---\n\n## Figure 2. Rank Improvement of Female Candidates\n\n\n```python\ndata_rdd=get_rdd_data(data,female=False)\ndf_r = DataFrame({\"margin_1\": FloatVector(data_rdd_f[\"margin_1\"]), \"gewinn_norm\": FloatVector(data_rdd_f[\"gewinn_norm\"])})\nCCT_bw_I=rdrobust.rdbwselect_2014(df_r.rx2('gewinn_norm'), df_r.rx2('margin_1'), c = 0, p = 1, q = 0, deriv = 0,kernel = \"tri\", bwselect = \"CCT\")[2][0]\nprint(\"The optimal bandwith according to Calonico, Cattaneo & Titiunik (2014) is: {:5.3f}\".format(CCT_bw_I))\n```\n\n    The optimal bandwith according to Calonico, Cattaneo & Titiunik (2014) is: 20.100\n\n\n\n```python\ndata_fig2=subset_by_margin(data_rdd_f,30)\nrdd_plot(data_fig2,3,CCT_bw_I,100,100,\"gewinn_norm\")\n```\n\nFigure 2 shows the regression discontinuity plot for the observed rank improvement of female candidates in the rdd-sample. The dots are again the local averages of rank improvement for bins of 3 percent, the lines are the results from local linear smooths on both sides, plotted with their respective confidence intervals. Since potential confounding factors have been ruled out the observed and significant discontinuity is attributed by Baskaran & Hessami  (2018) to the treatment effect of a female mayor. At the threshold an average rank improvement of 3.7. ranks (per 100 seats) takes place if a female mayor has been recently elected into the office.\n\n---\n<span style=\"color:red\">**NOTE**:</span> \n  The confidence intervals above are the result of 100 iterations of resampling the data by bootstrapping. Increasing the number of iterations does not yield different results and only increases the runtime of this notebook.\n---\n\n### 5.3.2 Main Result I - Rank improvement of female Council Candiates <a name=\"Main_Result_I\"></a>\n---\n\n## Table 2 - Baseline Results: Rank Improvment fo Female Candidates\n\n\n```python\nCCT_bw_I=rdrobust.rdbwselect_2014(df_r.rx2('gewinn_norm'), df_r.rx2('margin_1'), c = 0, p = 1, q = 0, deriv = 0,kernel = \"tri\", bwselect = \"CCT\")[2][0]\nIK_bw_I=rdrobust.rdbwselect_2014(df_r.rx2('gewinn_norm'), df_r.rx2('margin_1'), c = 0, p = 1, q = 0, deriv = 0,kernel = \"tri\", bwselect = \"IK\")[2][0]\nCCT_quad_bw_I=rdrobust.rdbwselect_2014(df_r.rx2('gewinn_norm'), df_r.rx2('margin_1'), c = 0, p = 2, q = 0, deriv = 0,kernel = \"tri\", bwselect = \"CCT\")[2][0]\nprint(\"The optimal bandwith according to Calonico, Cattaneo & Titiunik (2014) is: {:5.3f}\".format(CCT_bw_I))\nprint(\"The optimal bandwith according to Imbens & Kalyanaraman (2011) is: {:5.3f}\".format(IK_bw_I))\nprint(\"The optimal bandwith according to Calonico, Cattaneo & Titiunik (2014) using a quadratic functional form is: {:5.3f}\".format(CCT_quad_bw_I))\n```\n\n    The optimal bandwith according to Calonico, Cattaneo & Titiunik (2014) is: 20.100\n    The optimal bandwith according to Imbens & Kalyanaraman (2011) is: 35.587\n    The optimal bandwith according to Calonico, Cattaneo & Titiunik (2014) using a quadratic functional form is: 19.932\n\n\n\n```python\nresult1=[data_rdd_f,\"linear\",CCT_bw_I,\"gewinn_norm\",\"CCT\"]\nresult2=[data_rdd_f,\"linear\",CCT_bw_I/2,\"gewinn_norm\",\"CCT/2\"]\nresult3=[data_rdd_f,\"linear\",CCT_bw_I*2,\"gewinn_norm\",\"CCT*2\"]\nresult4=[data_rdd_f,\"linear\",IK_bw_I,\"gewinn_norm\",\"IK\"]\nresult5=[data_rdd_f,\"quadratic\",CCT_quad_bw_I,\"gewinn_norm\",\"CCT\"]\n```\n\n\n```python\nreg_tab(result1,result2,result3,result4,result5)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Female Mayor</th>\n      <th>Std.err</th>\n      <th>Bandwidth type</th>\n      <th>Bandwidth size</th>\n      <th>Polynomial</th>\n      <th>Observations</th>\n      <th>Elections</th>\n      <th>Municipalities</th>\n      <th>Mean</th>\n      <th>Std.err (Mean)</th>\n    </tr>\n    <tr>\n      <th>Model</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>(1)</th>\n      <td>3.712***</td>\n      <td>0.980</td>\n      <td>CCT</td>\n      <td>20.1</td>\n      <td>Linear</td>\n      <td>2878.0</td>\n      <td>77.0</td>\n      <td>56.0</td>\n      <td>0.41</td>\n      <td>10.947</td>\n    </tr>\n    <tr>\n      <th>(2)</th>\n      <td>3.322**</td>\n      <td>1.491</td>\n      <td>CCT/2</td>\n      <td>10.05</td>\n      <td>Linear</td>\n      <td>1784.0</td>\n      <td>46.0</td>\n      <td>37.0</td>\n      <td>0.73</td>\n      <td>10.750</td>\n    </tr>\n    <tr>\n      <th>(3)</th>\n      <td>2.836***</td>\n      <td>0.548</td>\n      <td>CCT*2</td>\n      <td>40.2</td>\n      <td>Linear</td>\n      <td>5232.0</td>\n      <td>155.0</td>\n      <td>102.0</td>\n      <td>0.27</td>\n      <td>11.327</td>\n    </tr>\n    <tr>\n      <th>(4)</th>\n      <td>3.124***</td>\n      <td>0.613</td>\n      <td>IK</td>\n      <td>35.59</td>\n      <td>Linear</td>\n      <td>4803.0</td>\n      <td>139.0</td>\n      <td>94.0</td>\n      <td>0.21</td>\n      <td>11.364</td>\n    </tr>\n    <tr>\n      <th>(5)</th>\n      <td>3.293**</td>\n      <td>1.545</td>\n      <td>CCT</td>\n      <td>19.93</td>\n      <td>Quadratic</td>\n      <td>2842.0</td>\n      <td>76.0</td>\n      <td>55.0</td>\n      <td>0.41</td>\n      <td>10.996</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nTable 2 reports the results of the regression outlined in section 4, with rank improvements of female candidates as the dependant variable. For the linear models that use the bandwidths by Imbens & Kalyanaraman (2011) and Calonico, Cattaneo & Titiunik (2014) (and the bandwidth multiplied by two), the average rank improvement ranges from 2.8 to  3.7, while being significant at a level of 1 percent. The remaining two models report an average rank improvement of roughly 3.2 ranks while being significant at the 5 percent level.  \n\n### 5.3.3 Main Result II - Share of Women Among Candidates Elected to the Council <a name=\"Main_Result_II\"></a>\n---\n\n## Table 3 - Baseline Results II: Share of Women Among Candidates Elected to the Council\n\n\n```python\ndata_rdd_e=data_rdd[data_rdd[\"elected\"]==1]\ndf_r_mix = DataFrame({\"margin_1\": FloatVector(data_rdd_e[\"margin_1\"]), \"female\": FloatVector(data_rdd_e[\"female\"])})\nCCT_bw_II=rdrobust.rdbwselect_2014(df_r_mix.rx2('female'), df_r_mix.rx2('margin_1'), c = 0, p = 1, q = 0, deriv = 0,kernel = \"tri\", bwselect = \"CCT\")[2][0]\nIK_bw_II=rdrobust.rdbwselect_2014(df_r_mix.rx2('female'), df_r_mix.rx2('margin_1'), c = 0, p = 1, q = 0, deriv = 0,kernel = \"tri\", bwselect = \"IK\")[2][0]\nCCT_quad_bw_II=rdrobust.rdbwselect_2014(df_r_mix.rx2('female'), df_r_mix.rx2('margin_1'), c = 0, p = 2, q = 0, deriv = 0,kernel = \"tri\", bwselect = \"CCT\")[2][0]\nprint(\"The optimal bandwith according to Calonico, Cattaneo & Titiunik (2014) is: {:5.3f}\".format(CCT_bw_II))\nprint(\"The optimal bandwith according to Imbens & Kalyanaraman (2011) is: {:5.3f}\".format(IK_bw_II))\nprint(\"The optimal bandwith according to Calonico, Cattaneo & Titiunik (2014) using a quadratic functional form is: {:5.3f}\".format(CCT_quad_bw_II))\n```\n\n    The optimal bandwith according to Calonico, Cattaneo & Titiunik (2014) is: 23.900\n    The optimal bandwith according to Imbens & Kalyanaraman (2011) is: 21.159\n    The optimal bandwith according to Calonico, Cattaneo & Titiunik (2014) using a quadratic functional form is: 25.496\n\n\n\n```python\ndata_rdd=get_rdd_data(data,female=False)\ndata_rdd_e=data_rdd.loc[(data_rdd[\"elected\"] == 1)]\n\nresult2_1=[data_rdd_e,\"linear\",CCT_bw_II,\"female\",\"CCT\"]\nresult2_2=[data_rdd_e,\"linear\",CCT_bw_II/2,\"female\",\"CCT/2\"]\nresult2_3=[data_rdd_e,\"linear\",CCT_bw_II*2,\"female\",\"CCT*2\"]\nresult2_4=[data_rdd_e,\"linear\",IK_bw_II,\"female\",\"IK\"]\nresult2_5=[data_rdd_e,\"quadratic\",CCT_quad_bw_II,\"female\",\"CCT\"]\n\nreg_tab(result2_1,result2_2,result2_3,result2_4,result2_5)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Female Mayor</th>\n      <th>Std.err</th>\n      <th>Bandwidth type</th>\n      <th>Bandwidth size</th>\n      <th>Polynomial</th>\n      <th>Observations</th>\n      <th>Elections</th>\n      <th>Municipalities</th>\n      <th>Mean</th>\n      <th>Std.err (Mean)</th>\n    </tr>\n    <tr>\n      <th>Model</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>(1)</th>\n      <td>0.041</td>\n      <td>0.042</td>\n      <td>CCT</td>\n      <td>23.9</td>\n      <td>Linear</td>\n      <td>3463.0</td>\n      <td>96.0</td>\n      <td>72.0</td>\n      <td>0.27</td>\n      <td>0.446</td>\n    </tr>\n    <tr>\n      <th>(2)</th>\n      <td>0.045</td>\n      <td>0.043</td>\n      <td>CCT/2</td>\n      <td>11.95</td>\n      <td>Linear</td>\n      <td>2033.0</td>\n      <td>55.0</td>\n      <td>44.0</td>\n      <td>0.27</td>\n      <td>0.446</td>\n    </tr>\n    <tr>\n      <th>(3)</th>\n      <td>0.038</td>\n      <td>0.035</td>\n      <td>CCT*2</td>\n      <td>47.8</td>\n      <td>Linear</td>\n      <td>6135.0</td>\n      <td>178.0</td>\n      <td>116.0</td>\n      <td>0.26</td>\n      <td>0.441</td>\n    </tr>\n    <tr>\n      <th>(4)</th>\n      <td>0.042</td>\n      <td>0.043</td>\n      <td>IK</td>\n      <td>21.16</td>\n      <td>Linear</td>\n      <td>3056.0</td>\n      <td>85.0</td>\n      <td>63.0</td>\n      <td>0.27</td>\n      <td>0.446</td>\n    </tr>\n    <tr>\n      <th>(5)</th>\n      <td>0.05</td>\n      <td>0.046</td>\n      <td>CCT</td>\n      <td>25.5</td>\n      <td>Quadratic</td>\n      <td>3796.0</td>\n      <td>107.0</td>\n      <td>77.0</td>\n      <td>0.27</td>\n      <td>0.445</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nTable 3 reports the results of the specified regression with a dummy variable as the dependent variable that takes on the value 1 if an elected council candidate is female. None of the different specifications report a significant effect of a female mayor.  However, this is likely due to the marginal effect of rank improvement,  as it only enables female candidates with a sufficient initial rank to get elected.\n\n---\n#  6. Extension <a name=\"Extension\"></a>\n---\n\n##  6.1 Data and Descriptive Summary for Main Analysis <a name=\"Data_and_Descriptive_Summary_for_Main_Analysis\"></a>\n---\n\n\n```python\nfig1_a=data_fig1_a(data,ext=True)\nfig1_b=data_fig1_b(data,ext=True)\nplt1_1=(fig1_a[0],\"Full-sample\")\nplt1_2=(fig1_a[1],\"RDD-sample\")\nplt2_1=(fig1_b[0],\"Full-sample\")\nplt2_2=(fig1_b[1],\"Female\")\nplt2_3=(fig1_b[2],\"RDD-Sample\")\nplt2_4=(fig1_b[3],\"RDD-Sample-Female\")\nfigure1_plot_extension(plt1_1,plt1_2,plt2_1,plt2_2,plt2_3,plt2_4)\n```\n\nIn addition to the total number of municipalities and candidates presented by Baskaran & Hessami (2018), I have added the respective statistics for the rdd-sample that is used in the actual analysis. It is noteworthy, that while the proportion of data used in the regression discontinuity analysis remains constant (ranging from roughly 15 to 20 percent), the total amount of data available in the main analysis is extremly small compared to the overall sample size as presented by the authors. \n\n### Summary Statistics for all council candidates in rdd-sample\n\n\n```python\nrdd=get_rdd_data(data,female=False)\nTable1_a_rdd=table1(rdd, dictionary_table1(), female=False)\nTable1_b_rdd=table1(rdd, dictionary_table1(), female=True)\nTable1_a_rdd\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>max</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Rank improvement (normalized)</th>\n      <td>23169.0</td>\n      <td>0.051748</td>\n      <td>12.466993</td>\n      <td>-68.000000</td>\n      <td>97.297295</td>\n    </tr>\n    <tr>\n      <th>Initial list rank (normalized)</th>\n      <td>23169.0</td>\n      <td>39.327198</td>\n      <td>26.550978</td>\n      <td>1.075269</td>\n      <td>100.000000</td>\n    </tr>\n    <tr>\n      <th>Age</th>\n      <td>11792.0</td>\n      <td>52.181648</td>\n      <td>13.866792</td>\n      <td>18.000000</td>\n      <td>96.000000</td>\n    </tr>\n    <tr>\n      <th>High school</th>\n      <td>10422.0</td>\n      <td>0.619363</td>\n      <td>0.485567</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>University</th>\n      <td>10422.0</td>\n      <td>0.298023</td>\n      <td>0.457412</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Phd</th>\n      <td>10422.0</td>\n      <td>0.082614</td>\n      <td>0.275311</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Architect</th>\n      <td>10534.0</td>\n      <td>0.010158</td>\n      <td>0.100276</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Businesswoman/-man</th>\n      <td>10534.0</td>\n      <td>0.078223</td>\n      <td>0.268535</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Engineer</th>\n      <td>10534.0</td>\n      <td>0.059711</td>\n      <td>0.236963</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Lawyer</th>\n      <td>10534.0</td>\n      <td>0.037877</td>\n      <td>0.190909</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Civil administration</th>\n      <td>10534.0</td>\n      <td>0.075090</td>\n      <td>0.263549</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Teacher</th>\n      <td>10534.0</td>\n      <td>0.053066</td>\n      <td>0.224176</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Employed</th>\n      <td>11925.0</td>\n      <td>0.701468</td>\n      <td>0.457633</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Self-employed</th>\n      <td>11925.0</td>\n      <td>0.059706</td>\n      <td>0.236952</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Student</th>\n      <td>11925.0</td>\n      <td>0.044528</td>\n      <td>0.206274</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Retired</th>\n      <td>11925.0</td>\n      <td>0.152537</td>\n      <td>0.359555</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Housewife/-husband</th>\n      <td>11925.0</td>\n      <td>0.024822</td>\n      <td>0.155588</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### Summary Statistics for female council candidates in rdd-sample\n\n\n```python\nTable1_b_rdd\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>max</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Rank improvement (normalized)</th>\n      <td>6472.0</td>\n      <td>0.106067</td>\n      <td>11.495141</td>\n      <td>-65.217392</td>\n      <td>87.096771</td>\n    </tr>\n    <tr>\n      <th>Initial list rank (normalized)</th>\n      <td>6472.0</td>\n      <td>37.888557</td>\n      <td>25.996939</td>\n      <td>1.075269</td>\n      <td>100.000000</td>\n    </tr>\n    <tr>\n      <th>Age</th>\n      <td>3229.0</td>\n      <td>51.300095</td>\n      <td>13.423151</td>\n      <td>18.000000</td>\n      <td>91.000000</td>\n    </tr>\n    <tr>\n      <th>High school</th>\n      <td>2723.0</td>\n      <td>0.653324</td>\n      <td>0.475999</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>University</th>\n      <td>2723.0</td>\n      <td>0.286816</td>\n      <td>0.452358</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Phd</th>\n      <td>2723.0</td>\n      <td>0.059860</td>\n      <td>0.237272</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Architect</th>\n      <td>2744.0</td>\n      <td>0.007289</td>\n      <td>0.085077</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Businesswoman/-man</th>\n      <td>2744.0</td>\n      <td>0.063411</td>\n      <td>0.243745</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Engineer</th>\n      <td>2744.0</td>\n      <td>0.017128</td>\n      <td>0.129773</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Lawyer</th>\n      <td>2744.0</td>\n      <td>0.037536</td>\n      <td>0.190107</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Civil administration</th>\n      <td>2744.0</td>\n      <td>0.061953</td>\n      <td>0.241115</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Teacher</th>\n      <td>2744.0</td>\n      <td>0.075802</td>\n      <td>0.264729</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Employed</th>\n      <td>3238.0</td>\n      <td>0.692094</td>\n      <td>0.461699</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Self-employed</th>\n      <td>3238.0</td>\n      <td>0.040457</td>\n      <td>0.197059</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Student</th>\n      <td>3238.0</td>\n      <td>0.046943</td>\n      <td>0.211549</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Retired</th>\n      <td>3238.0</td>\n      <td>0.114886</td>\n      <td>0.318933</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Housewife/-husband</th>\n      <td>3238.0</td>\n      <td>0.089561</td>\n      <td>0.285597</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nWhen restricting the analysis to the rdd-sample one can observe that now women on average gain ranks, indicating a possible effect of a close gender-mixed mayoral election. This is further supporter by the t-test below. The test shows, that when restricting to the rdd-sample, female and male candidates do not differ significantly in their rank improvement. Unchanged is the result that female candidates remain better placed on the initial list.\n\n\n```python\ntt_rank=t_test_prepare_rank(rdd)\nttest(tt_rank,\"Rank\")\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Treatment</th>\n      <th>Control</th>\n      <th>Diff</th>\n      <th>Std. Error</th>\n      <th>Observations</th>\n    </tr>\n    <tr>\n      <th>Rank</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Rank improvement (normalized)</th>\n      <td>0.106</td>\n      <td>0.031000</td>\n      <td>0.075</td>\n      <td>0.183</td>\n      <td>23169.0</td>\n    </tr>\n    <tr>\n      <th>Initial list rank (normalized)</th>\n      <td>37.889</td>\n      <td>39.884998</td>\n      <td>-1.996***</td>\n      <td>0.389</td>\n      <td>23169.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n##  6.2 Treatment Effect Heterogeneity with Regards to Council Candidate Characteristics<a name= \"Treatment_Effect_Heterogeneity_with_Regards_to_Council_Candidate_Characteristics\"></a>\n---\n\nAdditional insight on how the election of a female mayor reduces anti-female voter bias can be gained by searching for heterogeneity in treatment effects. Voters may for example be more inclined to give additional votes to a female candidate if they have a higher degree of education, suggesting a higher qualification for the city council. To test this I perform the analysis as outlined in section 5.3.2 but include dummy variables that equal 1 if a candidate has a university-level education or a PhD degree of education. The results are presented below.\n\n\n```python\ndata_rdd_ex=prepare_ext(data_rdd_f)\ndf_r_ex = DataFrame({\"margin_1\": FloatVector(data_rdd_ex[\"margin_1\"]), 'gewinn_norm': FloatVector(data_rdd_ex['gewinn_norm'])})\nCCT_bw_ext=rdrobust.rdbwselect_2014(df_r_ex.rx2('gewinn_norm'), df_r_ex.rx2('margin_1'), c = 0, p = 1, q = 0, deriv = 0,kernel = \"tri\", bwselect = \"CCT\")[2][0]\nIK_bw_ext=rdrobust.rdbwselect_2014(df_r_ex.rx2('gewinn_norm'), df_r_ex.rx2('margin_1'), c = 0, p = 1, q = 0, deriv = 0,kernel = \"tri\", bwselect = \"IK\")[2][0]\nCCT_quad_bw_ext=rdrobust.rdbwselect_2014(df_r_ex.rx2('gewinn_norm'), df_r_ex.rx2('margin_1'), c = 0, p = 2, q = 0, deriv = 0,kernel = \"tri\", bwselect = \"CCT\")[2][0]\nprint(\"The optimal bandwith according to Calonico, Cattaneo & Titiunik (2014) is: {:5.3f}\".format(CCT_bw_ext))\nprint(\"The optimal bandwith according to Imbens & Kalyanaraman (2011) is: {:5.3f}\".format(IK_bw_ext))\nprint(\"The optimal bandwith according to Calonico, Cattaneo & Titiunik (2014) using a quadratic functional form is: {:5.3f}\".format(CCT_quad_bw_ext))\n```\n\n    The optimal bandwith according to Calonico, Cattaneo & Titiunik (2014) is: 15.871\n    The optimal bandwith according to Imbens & Kalyanaraman (2011) is: 16.908\n    The optimal bandwith according to Calonico, Cattaneo & Titiunik (2014) using a quadratic functional form is: 19.737\n\n\n\n```python\nmodel_ext_1=[data_rdd_ex,\"linear\",CCT_bw_ext,\"gewinn_norm\",\"CCT\"]\nmodel_ext_2=[data_rdd_ex,\"linear\",CCT_bw_ext/2,\"gewinn_norm\",\"CCT/2\"]\nmodel_ext_3=[data_rdd_ex,\"linear\",CCT_bw_ext*2,\"gewinn_norm\",\"CCT*2\"]\nmodel_ext_4=[data_rdd_ex,\"linear\",IK_bw_ext,\"gewinn_norm\",\"IK\"]\nmodel_ext_5=[data_rdd_ex,\"quadratic\",CCT_quad_bw_ext,\"gewinn_norm\",\"CCT\"]\n```\n\n\n```python\nreg_tab_ext(model_ext_1,model_ext_2,model_ext_3,model_ext_4,model_ext_5)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Female Mayor</th>\n      <th>Std.err_Female Mayor</th>\n      <th>University</th>\n      <th>Std.err_University</th>\n      <th>PhD</th>\n      <th>Std.err_PhD</th>\n      <th>Bandwidth type</th>\n      <th>Bandwidth size</th>\n      <th>Polynomial</th>\n      <th>Observations</th>\n      <th>Elections</th>\n      <th>Municipalities</th>\n      <th>Mean</th>\n      <th>Std.err (Mean)</th>\n    </tr>\n    <tr>\n      <th>Model</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>(1)</th>\n      <td>5.48***</td>\n      <td>1.475</td>\n      <td>-0.295**</td>\n      <td>0.748</td>\n      <td>0.156</td>\n      <td>1.205</td>\n      <td>CCT</td>\n      <td>15.87</td>\n      <td>Linear</td>\n      <td>1069.0</td>\n      <td>54.0</td>\n      <td>42.0</td>\n      <td>0.31</td>\n      <td>10.083</td>\n    </tr>\n    <tr>\n      <th>(2)</th>\n      <td>5.764***</td>\n      <td>1.440</td>\n      <td>-0.746**</td>\n      <td>0.929</td>\n      <td>0.908</td>\n      <td>2.108</td>\n      <td>CCT/2</td>\n      <td>7.94</td>\n      <td>Linear</td>\n      <td>699.0</td>\n      <td>32.0</td>\n      <td>27.0</td>\n      <td>0.82</td>\n      <td>9.947</td>\n    </tr>\n    <tr>\n      <th>(3)</th>\n      <td>4.563***</td>\n      <td>1.156</td>\n      <td>-0.125**</td>\n      <td>0.667</td>\n      <td>-0.056*</td>\n      <td>0.921</td>\n      <td>CCT*2</td>\n      <td>31.74</td>\n      <td>Linear</td>\n      <td>1805.0</td>\n      <td>102.0</td>\n      <td>69.0</td>\n      <td>0.16</td>\n      <td>11.323</td>\n    </tr>\n    <tr>\n      <th>(4)</th>\n      <td>5.473***</td>\n      <td>1.526</td>\n      <td>-0.268**</td>\n      <td>0.740</td>\n      <td>0.105</td>\n      <td>1.179</td>\n      <td>IK</td>\n      <td>16.91</td>\n      <td>Linear</td>\n      <td>1091.0</td>\n      <td>56.0</td>\n      <td>44.0</td>\n      <td>0.36</td>\n      <td>10.142</td>\n    </tr>\n    <tr>\n      <th>(5)</th>\n      <td>5.342***</td>\n      <td>1.536</td>\n      <td>-0.664**</td>\n      <td>0.715</td>\n      <td>0.904</td>\n      <td>1.091</td>\n      <td>CCT</td>\n      <td>19.74</td>\n      <td>Quadratic</td>\n      <td>1213.0</td>\n      <td>63.0</td>\n      <td>47.0</td>\n      <td>0.60</td>\n      <td>10.632</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nFor all models, the table shows a significant negative effect of a university degree on average rank improvement, significant at a level of 5 percent. While the treatment effect of a female mayor is stronger for this subgroup of female candidates in the rdd-sample, the results suggest a backlash-effect against female council candidates with higher education by voters. However, this conclusion is premature, as just like different municipality characteristics (like anti-female voter bias) motivated the initial implementation of a regression discontinuity design, the fact that we observe a negative effect of higher qualification may originate from different preferences in the educational level of politicians. <br> In the online appendix Baskaran & Hessami (2018) relate individual candidate characteristics to their election performance by including corresponding characteristics as well. However, they also include those characteristics for the mayor of the municipality. When controlling for differences in educational levels between mayor and council candidates, a higher degree of education exerts a positive influence on female candidate performance. While their findings differ in statistical significance for model specifications these results in combination with my results above, suggest that municipalities may have a distinct preference with regards to the academic qualification of their politicians. However, a more detailed analysis may result in robust results and conclusive insight on that topic. \n\n---\n#  7. Critical Assessment and Conclusion <a name=\"Critical_Assessment_and_Conclusion\"></a>\n---\n\nTo summarize, my findings generally support the results of Baskaran & Hessami (2018). Except for small deviations in standard errors for regression results, I was able to understand and replicate all key numerical results by the authors in an exact manner. Since the differences in standard errors are generally small and do not change the significance of results, and the fact that authors and I use the heteroscedastic clustered standard errors I attribute the difference to the fact that Baskaran & Hessami (2018) relied on Stata for their derivations. Economically, the authors applied the methodology of a regression discontinuity design in an intriguing setting. It is generally a considerable challenge to identify causal effects in election results. Through the application of a regression discontinuity design, such issues become solvable. To validate this approach the authors checked the necessary condition of a continuous running variable. Additionally, they tested the relevance of observable covariates in the treatment assignment. While this showed no significant differences, the selection of covariates deserves a closer look. While the characteristics of a municipality used by the authors serve as a good proxy to categorize municipalities, the inclusion of additional covariates, that capture the political climate within a municipality more accurately can yield additional robustness. While generally, all parties encourage the increased political participation of women, they differ to the extent to which they actively support it. To test this possible confound of political ideology, the authors analyze differences in party membership of mayor candidates.  Although this serves as a proxy for the general political climate in a municipality,  it only projects the *median* political climate. A possible additional covariate in this context can be an index of the previous party composition of a local council. If there are no significant differences observable this would further strengthen the result of Baskaran & Hessami (2008).<br>\nConcerning the bandwidth choice,  the authors provided strong evidence of a significant effect since they tested their model for a wide range of bandwidth choices. For normalized rank improvement as a dependent variable, all models show a significant treatment effect. Concerning the model where the gender of an elected council member is the outcome variable, it might be initially a disappointment to observe no statistically significant effect. However, as Baskaran & Hesssami (2008) point out, this is due to the effect that their average rank improvement will only result in elections for those candidates, with a good enough initial rank. Consequently, we only observe an effect of treatment on the margin. This however does not change the significance of the treatment as a whole due to the more accurate variable rank improvement. In this regard, it may prove worthwhile to revisit this experimental setting, when more data is available. \nOverall, the results of Baskaran & Hessami are very robust.\nFinally, it has to be highlighted that the authors worked very transparently. The required datasets and detailed descriptions of the collection procedure are available in the online appendix. The original Stata code used by the authors to produce all results in the original paper and the online appendix is also provided. That generally allowed me to understand choices of parameters, so that I could assess and apply them in a python environment accordingly.Through this and the expansion of python to R via rp2y I was able to find strong support for the findings of Baskaran & Hessami (2018).\n\n---\n#  8. References <a name=\"Keks\"></a>\n---\n\n* **Baskaran, T., & Hessami, Z. (2018).** Does the Election of a Female Leader Clear the Way for More Women in Politics? American economic journal. Economic policy, 10(3), 95-121. doi:10.1257/pol.20170045.\n<br>\n* **Calonico, S., Cattaneo, M. D., & Titiunik, R. (2014).** Robust Nonparametric Confidence Intervals for Regression-Discontinuity Designs: Robust Nonparametric Confidence Intervals. Econometrica, 82(6), 2295-2326. doi:10.3982/ECTA11757. \n<br>\n* **Eisenhauer, P. (2020).** Course project template, HumanCapitalAnalysis.\n<br>\n* **Gehlen, A. (2019).** Replication of Jason M. Lindo, Nicholas J. Sanders & Philip Oreopoulos (2010).\n<br>\n* **Imbens, G., & Kalyanaraman, K. (2011).** Optimal Bandwidth Choice for the Regression Discontinuity Estimator. The Review of economic studies, 79(3), 933-959. doi:10.1093/restud/rdr043. \n<br>\n* **Lee, D. S., & Lemieux, T. (2010).** Regression Discontinuity Designs in Economics. Journal of Economic Literature, 48(2), 281-355. doi:10.1257/jel.48.2.281. \n\n\n\n", "meta": {"hexsha": "14b91de2e17aa84291d969fe16fa819a487760b8", "size": 341080, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Replication.ipynb", "max_stars_repo_name": "McKers/replication-Baskaran-Hessami-2018", "max_stars_repo_head_hexsha": "663ba44dd3cc05772d02c58c057f48b801c8e449", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Replication.ipynb", "max_issues_repo_name": "McKers/replication-Baskaran-Hessami-2018", "max_issues_repo_head_hexsha": "663ba44dd3cc05772d02c58c057f48b801c8e449", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Replication.ipynb", "max_forks_repo_name": "McKers/replication-Baskaran-Hessami-2018", "max_forks_repo_head_hexsha": "663ba44dd3cc05772d02c58c057f48b801c8e449", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 104.3377179566, "max_line_length": 64984, "alphanum_fraction": 0.7717426997, "converted": true, "num_tokens": 24764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.09534945911506375, "lm_q1q2_score": 0.040285588403140386}}
{"text": "# Assignement for course ML2\n\nStudents: Tristan STAMPFLER and Thomas CARTA\n\n## Table of contents\n\n### 1) Exploration of the dataset\n### 2) Data cleaning\n### 3) Feature engineering\n### 4) Feature selection\n### 5) Metric definition\n### 6) Various prediction models\n### 7) Conclusion\n\n## 1) Exploration of the dataset\n\nPreliminary exploration of the dataset is necessary to determine which field we can use.\n\n\n```python\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n```\n\n\n```python\ndf = pd.read_csv(\"data/CreditTraining.csv\")\n```\n\n\n```python\ndf.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Id_Customer</th>\n      <th>Y</th>\n      <th>Customer_Type</th>\n      <th>BirthDate</th>\n      <th>Customer_Open_Date</th>\n      <th>P_Client</th>\n      <th>Educational_Level</th>\n      <th>Marital_Status</th>\n      <th>Number_Of_Dependant</th>\n      <th>Years_At_Residence</th>\n      <th>Net_Annual_Income</th>\n      <th>Years_At_Business</th>\n      <th>Prod_Sub_Category</th>\n      <th>Prod_Decision_Date</th>\n      <th>Source</th>\n      <th>Type_Of_Residence</th>\n      <th>Nb_Of_Products</th>\n      <th>Prod_Closed_Date</th>\n      <th>Prod_Category</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>7440</td>\n      <td>0</td>\n      <td>Non Existing Client</td>\n      <td>07/08/1977</td>\n      <td>13/02/2012</td>\n      <td>NP_Client</td>\n      <td>University</td>\n      <td>Married</td>\n      <td>3.0</td>\n      <td>1</td>\n      <td>36</td>\n      <td>1.0</td>\n      <td>C</td>\n      <td>14/02/2012</td>\n      <td>Sales</td>\n      <td>Owned</td>\n      <td>1</td>\n      <td>NaN</td>\n      <td>B</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>573</td>\n      <td>0</td>\n      <td>Existing Client</td>\n      <td>13/06/1974</td>\n      <td>04/02/2009</td>\n      <td>P_Client</td>\n      <td>University</td>\n      <td>Married</td>\n      <td>0.0</td>\n      <td>12</td>\n      <td>18</td>\n      <td>2.0</td>\n      <td>C</td>\n      <td>30/06/2011</td>\n      <td>Sales</td>\n      <td>Parents</td>\n      <td>1</td>\n      <td>NaN</td>\n      <td>G</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>9194</td>\n      <td>0</td>\n      <td>Non Existing Client</td>\n      <td>07/11/1973</td>\n      <td>03/04/2012</td>\n      <td>NP_Client</td>\n      <td>University</td>\n      <td>Married</td>\n      <td>2.0</td>\n      <td>10</td>\n      <td>36</td>\n      <td>1.0</td>\n      <td>C</td>\n      <td>04/04/2012</td>\n      <td>Sales</td>\n      <td>Owned</td>\n      <td>1</td>\n      <td>NaN</td>\n      <td>B</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>3016</td>\n      <td>1</td>\n      <td>Existing Client</td>\n      <td>08/07/1982</td>\n      <td>25/08/2011</td>\n      <td>NP_Client</td>\n      <td>University</td>\n      <td>Married</td>\n      <td>3.0</td>\n      <td>3</td>\n      <td>36</td>\n      <td>1.0</td>\n      <td>C</td>\n      <td>07/09/2011</td>\n      <td>Sales</td>\n      <td>New rent</td>\n      <td>1</td>\n      <td>31/12/2012</td>\n      <td>L</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>6524</td>\n      <td>0</td>\n      <td>Non Existing Client</td>\n      <td>18/08/1953</td>\n      <td>10/01/2012</td>\n      <td>NP_Client</td>\n      <td>University</td>\n      <td>Married</td>\n      <td>2.0</td>\n      <td>1</td>\n      <td>36</td>\n      <td>1.0</td>\n      <td>C</td>\n      <td>11/01/2012</td>\n      <td>Sales</td>\n      <td>Owned</td>\n      <td>1</td>\n      <td>NaN</td>\n      <td>D</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf.describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Id_Customer</th>\n      <th>Y</th>\n      <th>Number_Of_Dependant</th>\n      <th>Years_At_Residence</th>\n      <th>Years_At_Business</th>\n      <th>Nb_Of_Products</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>5380.000000</td>\n      <td>5380.000000</td>\n      <td>5378.000000</td>\n      <td>5380.000000</td>\n      <td>5378.000000</td>\n      <td>5380.000000</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>4784.535688</td>\n      <td>0.073048</td>\n      <td>1.058572</td>\n      <td>12.626022</td>\n      <td>4.266270</td>\n      <td>1.089033</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>2781.436262</td>\n      <td>0.260240</td>\n      <td>1.339001</td>\n      <td>9.972164</td>\n      <td>7.225926</td>\n      <td>0.297587</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>1.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>2368.500000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>4.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>4762.500000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>10.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>7180.250000</td>\n      <td>0.000000</td>\n      <td>2.000000</td>\n      <td>18.000000</td>\n      <td>4.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>9605.000000</td>\n      <td>1.000000</td>\n      <td>20.000000</td>\n      <td>70.000000</td>\n      <td>98.000000</td>\n      <td>3.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### Checking for NaNs\n\n\n```python\ndf.isna().sum()\n```\n\n\n\n\n    Id_Customer               0\n    Y                         0\n    Customer_Type             0\n    BirthDate                 0\n    Customer_Open_Date        0\n    P_Client                  0\n    Educational_Level         0\n    Marital_Status            0\n    Number_Of_Dependant       2\n    Years_At_Residence        0\n    Net_Annual_Income         2\n    Years_At_Business         2\n    Prod_Sub_Category         0\n    Prod_Decision_Date        0\n    Source                    0\n    Type_Of_Residence         0\n    Nb_Of_Products            0\n    Prod_Closed_Date       4206\n    Prod_Category             0\n    dtype: int64\n\n\n\nWe can see have a lot of missing values for the field Prod_Closed_Date, and some for Number_Of_Dependant, Net_Annual_Income and Years_At_Business\n\n### Checking if Id_Customer is an unique key\n\n\n```python\nprint(df[['Id_Customer']].nunique() == len(df))\n```\n\n    Id_Customer    True\n    dtype: bool\n\n\nYes, Id_Customer is a unique key for this dataset\n\n### Practising on marital\n\n\n```python\ndf_marital = df[['Id_Customer','Y','Marital_Status']]\ndf_marital['Marital_Status'].value_counts()\n```\n\n\n\n\n    Married      4206\n    Single       1046\n    Widowed        64\n    Divorced       63\n    Separated       1\n    Name: Marital_Status, dtype: int64\n\n\n\n\n```python\nmarital_grp = df_marital.groupby('Marital_Status')\nmarital_grp['Y'].value_counts(normalize=True)\n```\n\n\n\n\n    Marital_Status  Y\n    Divorced        0    0.920635\n                    1    0.079365\n    Married         0    0.930813\n                    1    0.069187\n    Separated       0    1.000000\n    Single          0    0.911090\n                    1    0.088910\n    Widowed         0    0.937500\n                    1    0.062500\n    Name: Y, dtype: float64\n\n\n\n\n```python\nmarital_grp.agg({'Y':'mean',\n                 'Id_Customer':'count'})\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Y</th>\n      <th>Id_Customer</th>\n    </tr>\n    <tr>\n      <th>Marital_Status</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Divorced</th>\n      <td>0.079365</td>\n      <td>63</td>\n    </tr>\n    <tr>\n      <th>Married</th>\n      <td>0.069187</td>\n      <td>4206</td>\n    </tr>\n    <tr>\n      <th>Separated</th>\n      <td>0.000000</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>Single</th>\n      <td>0.088910</td>\n      <td>1046</td>\n    </tr>\n    <tr>\n      <th>Widowed</th>\n      <td>0.062500</td>\n      <td>64</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## 2) Data cleaning\n\nWe need to handle NaNs and select the columns we will use for our approaches\n\n\n```python\ndf.isna().sum()\n```\n\n\n\n\n    Id_Customer               0\n    Y                         0\n    Customer_Type             0\n    BirthDate                 0\n    Customer_Open_Date        0\n    P_Client                  0\n    Educational_Level         0\n    Marital_Status            0\n    Number_Of_Dependant       2\n    Years_At_Residence        0\n    Net_Annual_Income         2\n    Years_At_Business         2\n    Prod_Sub_Category         0\n    Prod_Decision_Date        0\n    Source                    0\n    Type_Of_Residence         0\n    Nb_Of_Products            0\n    Prod_Closed_Date       4206\n    Prod_Category             0\n    dtype: int64\n\n\n\n### Removing NaNs\n\nWe will remove NaNs in 2 ways. For Prod_Closed_Date there are too much values missing so we will just get rid of this field. For Number_Of_Dependant, Net_Annual_Income and Years_At_Business we just have a few values missing. Assuming the clients are iid, we can remove the rows with missing values.\n\n\n```python\ndf = df.drop(\"Prod_Closed_Date\", axis=1)\ndf = df.dropna()\n```\n\n\n```python\ndf = df.reset_index(drop=True)\ndf.isna().sum()\ndf.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Id_Customer</th>\n      <th>Y</th>\n      <th>Customer_Type</th>\n      <th>BirthDate</th>\n      <th>Customer_Open_Date</th>\n      <th>P_Client</th>\n      <th>Educational_Level</th>\n      <th>Marital_Status</th>\n      <th>Number_Of_Dependant</th>\n      <th>Years_At_Residence</th>\n      <th>Net_Annual_Income</th>\n      <th>Years_At_Business</th>\n      <th>Prod_Sub_Category</th>\n      <th>Prod_Decision_Date</th>\n      <th>Source</th>\n      <th>Type_Of_Residence</th>\n      <th>Nb_Of_Products</th>\n      <th>Prod_Category</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>7440</td>\n      <td>0</td>\n      <td>Non Existing Client</td>\n      <td>07/08/1977</td>\n      <td>13/02/2012</td>\n      <td>NP_Client</td>\n      <td>University</td>\n      <td>Married</td>\n      <td>3.0</td>\n      <td>1</td>\n      <td>36</td>\n      <td>1.0</td>\n      <td>C</td>\n      <td>14/02/2012</td>\n      <td>Sales</td>\n      <td>Owned</td>\n      <td>1</td>\n      <td>B</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>573</td>\n      <td>0</td>\n      <td>Existing Client</td>\n      <td>13/06/1974</td>\n      <td>04/02/2009</td>\n      <td>P_Client</td>\n      <td>University</td>\n      <td>Married</td>\n      <td>0.0</td>\n      <td>12</td>\n      <td>18</td>\n      <td>2.0</td>\n      <td>C</td>\n      <td>30/06/2011</td>\n      <td>Sales</td>\n      <td>Parents</td>\n      <td>1</td>\n      <td>G</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>9194</td>\n      <td>0</td>\n      <td>Non Existing Client</td>\n      <td>07/11/1973</td>\n      <td>03/04/2012</td>\n      <td>NP_Client</td>\n      <td>University</td>\n      <td>Married</td>\n      <td>2.0</td>\n      <td>10</td>\n      <td>36</td>\n      <td>1.0</td>\n      <td>C</td>\n      <td>04/04/2012</td>\n      <td>Sales</td>\n      <td>Owned</td>\n      <td>1</td>\n      <td>B</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>3016</td>\n      <td>1</td>\n      <td>Existing Client</td>\n      <td>08/07/1982</td>\n      <td>25/08/2011</td>\n      <td>NP_Client</td>\n      <td>University</td>\n      <td>Married</td>\n      <td>3.0</td>\n      <td>3</td>\n      <td>36</td>\n      <td>1.0</td>\n      <td>C</td>\n      <td>07/09/2011</td>\n      <td>Sales</td>\n      <td>New rent</td>\n      <td>1</td>\n      <td>L</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>6524</td>\n      <td>0</td>\n      <td>Non Existing Client</td>\n      <td>18/08/1953</td>\n      <td>10/01/2012</td>\n      <td>NP_Client</td>\n      <td>University</td>\n      <td>Married</td>\n      <td>2.0</td>\n      <td>1</td>\n      <td>36</td>\n      <td>1.0</td>\n      <td>C</td>\n      <td>11/01/2012</td>\n      <td>Sales</td>\n      <td>Owned</td>\n      <td>1</td>\n      <td>D</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Replace some object type with float\n\n\n```python\ndf['Net_Annual_Income'] = df['Net_Annual_Income'].str.replace(',','.').astype(float)\n```\n\n## 3) Feature engineering\n\nWe create some features from the fields we have in our dataset.\n<br>\nWe compute here for instance the age of the client. We then get rid of obsolete fields.\n\n\n```python\ndf['Age'] = (pd.Timestamp('2020-01-01 00:00:00.000000') - pd.to_datetime(df['BirthDate'])).dt.days / 365.25\ndf = df.drop('BirthDate', axis=1)\n```\n\n## 4) Feature selection\n\nWe select all features\n\n\n```python\ndf.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Id_Customer</th>\n      <th>Y</th>\n      <th>Customer_Type</th>\n      <th>Customer_Open_Date</th>\n      <th>P_Client</th>\n      <th>Educational_Level</th>\n      <th>Marital_Status</th>\n      <th>Number_Of_Dependant</th>\n      <th>Years_At_Residence</th>\n      <th>Net_Annual_Income</th>\n      <th>Years_At_Business</th>\n      <th>Prod_Sub_Category</th>\n      <th>Prod_Decision_Date</th>\n      <th>Source</th>\n      <th>Type_Of_Residence</th>\n      <th>Nb_Of_Products</th>\n      <th>Prod_Category</th>\n      <th>Age</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>7440</td>\n      <td>0</td>\n      <td>Non Existing Client</td>\n      <td>13/02/2012</td>\n      <td>NP_Client</td>\n      <td>University</td>\n      <td>Married</td>\n      <td>3.0</td>\n      <td>1</td>\n      <td>36.0</td>\n      <td>1.0</td>\n      <td>C</td>\n      <td>14/02/2012</td>\n      <td>Sales</td>\n      <td>Owned</td>\n      <td>1</td>\n      <td>B</td>\n      <td>42.483231</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>573</td>\n      <td>0</td>\n      <td>Existing Client</td>\n      <td>04/02/2009</td>\n      <td>P_Client</td>\n      <td>University</td>\n      <td>Married</td>\n      <td>0.0</td>\n      <td>12</td>\n      <td>18.0</td>\n      <td>2.0</td>\n      <td>C</td>\n      <td>30/06/2011</td>\n      <td>Sales</td>\n      <td>Parents</td>\n      <td>1</td>\n      <td>G</td>\n      <td>45.552361</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>9194</td>\n      <td>0</td>\n      <td>Non Existing Client</td>\n      <td>03/04/2012</td>\n      <td>NP_Client</td>\n      <td>University</td>\n      <td>Married</td>\n      <td>2.0</td>\n      <td>10</td>\n      <td>36.0</td>\n      <td>1.0</td>\n      <td>C</td>\n      <td>04/04/2012</td>\n      <td>Sales</td>\n      <td>Owned</td>\n      <td>1</td>\n      <td>B</td>\n      <td>46.475017</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>3016</td>\n      <td>1</td>\n      <td>Existing Client</td>\n      <td>25/08/2011</td>\n      <td>NP_Client</td>\n      <td>University</td>\n      <td>Married</td>\n      <td>3.0</td>\n      <td>3</td>\n      <td>36.0</td>\n      <td>1.0</td>\n      <td>C</td>\n      <td>07/09/2011</td>\n      <td>Sales</td>\n      <td>New rent</td>\n      <td>1</td>\n      <td>L</td>\n      <td>37.401780</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>6524</td>\n      <td>0</td>\n      <td>Non Existing Client</td>\n      <td>10/01/2012</td>\n      <td>NP_Client</td>\n      <td>University</td>\n      <td>Married</td>\n      <td>2.0</td>\n      <td>1</td>\n      <td>36.0</td>\n      <td>1.0</td>\n      <td>C</td>\n      <td>11/01/2012</td>\n      <td>Sales</td>\n      <td>Owned</td>\n      <td>1</td>\n      <td>D</td>\n      <td>66.370979</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf.dtypes\n```\n\n\n\n\n    Id_Customer              int64\n    Y                        int64\n    Customer_Type           object\n    Customer_Open_Date      object\n    P_Client                object\n    Educational_Level       object\n    Marital_Status          object\n    Number_Of_Dependant    float64\n    Years_At_Residence       int64\n    Net_Annual_Income      float64\n    Years_At_Business      float64\n    Prod_Sub_Category       object\n    Prod_Decision_Date      object\n    Source                  object\n    Type_Of_Residence       object\n    Nb_Of_Products           int64\n    Prod_Category           object\n    Age                    float64\n    dtype: object\n\n\n\n## 5) Metric definition\n\n\n```python\nfrom IPython.display import Latex\n```\n\n\n```python\ndf['Y'].mean()\n```\n\n\n\n\n    0.07294380349832527\n\n\n\nWe need a consistent metric for our models to optimize. Since the dataset is heavily imbalanced (about 7.3% of 1 and 92.7% of 0) the accuracy is not by itself so relevant. Indeed a predictor that always predict 0 could get a 92.7% accuracy on this dataset). Furthermore, misclassifying a credit default as 0 is far more costly than misclassifying a credit that will be repaid as 1. But for the bank to earn some money we cannot reject all credit applications either.\n\nWe choose a target metric that maximizes the bank's profit per capita. We claim that this metric is:\n<br>\n<br>\n\\begin{equation}\n\\text{metric} = (1-\\alpha) i \\times \\text{true_negative_rate} + \\alpha \\times \\text{true_positive_rate} - \\alpha\n\\end{equation}\n\nWith $i$ the annual interest rate and $\\alpha$ the proportion credit default among all credits.\n\n__Demonstration__: <br>\nWe firstly assume that the rows in the dataset are realisations of iid distributed variables reprensenting the population. We then assume that the bank only lends money for a one year period with no monthly payment and always lend the same amount. So after one year, either the bank gets back its money plus $i$ of interests or it faces a credit default and lost all of its money. \n<br>\nSo if the bank uses a prediction algorithm to decide wether or not to give a credit to a customer and follows strictly the algorithm predictions, its total profit (normalized by the amount of the credit) on the population is:\n\\begin{equation}\n\\text{total profit} = i* TN - FN\n\\end{equation}\n\nWhere we note $n$ the total number of individuals, $TP$ the number of true positives, $FP$ the number of false positives, $TN$ the number of true negatives and $FN$ the number of false negatives. According to our modelisation we have the following properties:\n<br>\n<br>\n\\begin{equation}\nn = TP + FP + TN + FN \\; \\text{(1)} \\text{,}\\;\\;\\;\\;\\; TP + FN = \\alpha n \\; \\text{(2)} \\;\\;\\; \\text{and}\\;\\;\\; TN + FP = (1-\\alpha)n \\; \\text{(3)}\n\\end{equation}\n\nWe can next rewrite the total profit using (1): $\\text{total profit} = i*TN - n + TN + FP + TP$.\n<br>\nIf we set our metric to be the profit per capita (including all individuals) we get:\n<br>\n<br>\n\\begin{equation}\n\\text{metric} = \\text{profit per capita} \\\\\n= \\frac{\\text{total profit}}{n} \\\\\n= i*\\frac{TN}{n} - 1 + \\frac{TN + FP}{n} + \\frac{TP}{n} \\\\\n= (1-\\alpha)i*\\frac{TN}{TN+FP} -1 + (1-\\alpha)\\frac{TN+FP}{TN+FP} + \\alpha\\frac{TP}{TP+FN} \\;\\;\\; \\text{using (2) and (3)} \\\\\n= (1-\\alpha)i*\\text{true negative rate} + \\alpha*\\text{true positive rate} - \\alpha\n\\end{equation}\nWhich is exactly the metric stated above. <br>\n__End of demonstration__\n\nFor the rest of the exercise, we set $i=5\\%$ for the annual interest rate and we estimate $\\alpha$ with the dataset.\n\n\n```python\nfrom sklearn.metrics import confusion_matrix\n```\n\n\n```python\ndef metric(y, y_pred, i=0.05):\n    tn, fp, fn, tp = confusion_matrix(y, y_pred).ravel()\n    n = y_pred.size\n    alpha = (tp+fn)/n\n    metric = (1-alpha)*i*(tn/(tn+fp))+alpha*(tp/(tp+fn)) - alpha\n    return metric\n```\n\n## 6) Various prediction models\n\n### a) Logistic regression on quantitative variables\n\nWe try out Logistic regression on the quantitative variables\n\n\n```python\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score\nfrom sklearn.model_selection import train_test_split\n```\n\nWe split the data between a train set and a test. We use the train set to train the algorithm and to tune hyperparameters, and we use the test set to evaluate the algorithm performance.\n\n\n```python\nquant_cols = ['Number_Of_Dependant','Years_At_Residence','Net_Annual_Income','Years_At_Business','Nb_Of_Products','Age']\nX = df.loc[:,quant_cols]\nY = df.loc[:,'Y']\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.4, random_state=42)\nclf = LogisticRegression()\nclf.fit(X_train, y_train)\n```\n\n    C:\\Users\\Thomas\\Anaconda3\\lib\\site-packages\\sklearn\\linear_model\\logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.\n      FutureWarning)\n\n\n\n\n\n    LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,\n                       intercept_scaling=1, l1_ratio=None, max_iter=100,\n                       multi_class='warn', n_jobs=None, penalty='l2',\n                       random_state=None, solver='warn', tol=0.0001, verbose=0,\n                       warm_start=False)\n\n\n\n\n```python\ny_pred = clf.predict(X_test)\naccuracy = accuracy_score(y_test, y_pred)\nprecision = precision_score(y_test, y_pred, zero_division=False)\nrecall = recall_score(y_test, y_pred, zero_division=False)\nmetric_score = metric(y_test, y_pred)\nprint(f'metric:{metric_score}')\nprint(f'accuracy:{accuracy}, 1-mean_Y:{1-np.average(y_test)}, precision:{precision}, recall:{recall}')\n```\n\nAs we can notice here, Y_pred is all zeros. The logistic regression has learned to predict only the majority class: 0. As the metric shows, with such prediction algorithm the bank is loosing money.\n<br>\nWe can fix it with weighting the classes in the loss. \n<br>\nThe \u201cbalanced\u201d mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as n_samples / (n_classes * np.bincount(y)).\n\n\n```python\nclf_balanced = LogisticRegression(class_weight='balanced')\nclf_balanced.fit(X_train, y_train)\n```\n\n    C:\\Users\\Thomas\\Anaconda3\\lib\\site-packages\\sklearn\\linear_model\\logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.\n      FutureWarning)\n\n\n\n\n\n    LogisticRegression(C=1.0, class_weight='balanced', dual=False,\n                       fit_intercept=True, intercept_scaling=1, l1_ratio=None,\n                       max_iter=100, multi_class='warn', n_jobs=None, penalty='l2',\n                       random_state=None, solver='warn', tol=0.0001, verbose=0,\n                       warm_start=False)\n\n\n\n\n```python\ny_pred = clf_balanced.predict(X_test)\naccuracy = accuracy_score(y_test, y_pred)\nprecision = precision_score(y_test, y_pred)\nrecall = recall_score(y_test, y_pred)\nmetric_score = metric(y_test, y_pred)\nprint(f'metric:{metric_score}')\nprint(f'accuracy:{accuracy}, 1-mean_Y:{1-np.average(y_test)}, precision:{precision}, recall:{recall}')\n```\n\n    metric:-0.007999999999999993\n    accuracy:0.5144186046511627, 1-mean_Y:0.9265116279069767, precision:0.08442776735459662, recall:0.569620253164557\n\n\nWhat we lost in accuracy we gained in recall, more credit default are being detected by the logistic regression. From now on we will use balanced loss for logistic regression. But the bank is still loosing money, we have to improve our model.\n\n### b) Logistic regression on qualitative variables\n\nWe use one-hot encoder to encode class variables so we can use them as well for the logistic regression. We will use OneHotEncoder from sklearn.preprocessing for this task.\n\n\n```python\nfrom sklearn.preprocessing import OneHotEncoder\n```\n\n#### Demo with marital status\n\n\n```python\nohe = OneHotEncoder(sparse=False, handle_unknown='ignore')\nX = ohe.fit_transform(df[['Marital_Status']])\nX\n```\n\n\n\n\n    array([[0., 1., 0., 0., 0.],\n           [0., 1., 0., 0., 0.],\n           [0., 1., 0., 0., 0.],\n           ...,\n           [1., 0., 0., 0., 0.],\n           [0., 1., 0., 0., 0.],\n           [0., 1., 0., 0., 0.]])\n\n\n\n\n```python\nohe.get_feature_names()\n```\n\n\n\n\n    array(['x0_Divorced', 'x0_Married', 'x0_Separated', 'x0_Single',\n           'x0_Widowed'], dtype=object)\n\n\n\n\n```python\nclf = LogisticRegression(class_weight='balanced')\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.4, random_state=42)\nclf.fit(X_train, y_train)\n```\n\n    C:\\Users\\Thomas\\Anaconda3\\lib\\site-packages\\sklearn\\linear_model\\logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.\n      FutureWarning)\n\n\n\n\n\n    LogisticRegression(C=1.0, class_weight='balanced', dual=False,\n                       fit_intercept=True, intercept_scaling=1, l1_ratio=None,\n                       max_iter=100, multi_class='warn', n_jobs=None, penalty='l2',\n                       random_state=None, solver='warn', tol=0.0001, verbose=0,\n                       warm_start=False)\n\n\n\n\n```python\ny_pred = clf.predict(X_test)\naccuracy = accuracy_score(y_test, y_pred)\nprecision = precision_score(y_test, y_pred)\nrecall = recall_score(y_test, y_pred)\nmetric_score = metric(y_test, y_pred)\nprint(f'metric:{metric_score}')\nprint(f'accuracy:{accuracy}, 1-mean_Y:{1-np.average(y_test)}, precision:{precision}, recall:{recall}')\n```\n\n    metric:-0.017186046511627903\n    accuracy:0.7637209302325582, 1-mean_Y:0.9265116279069767, precision:0.09490740740740741, recall:0.25949367088607594\n\n\n#### We can encode all strings columns\n\n\n```python\ndf.dtypes\n```\n\n\n\n\n    Id_Customer              int64\n    Y                        int64\n    Customer_Type           object\n    Customer_Open_Date      object\n    P_Client                object\n    Educational_Level       object\n    Marital_Status          object\n    Number_Of_Dependant    float64\n    Years_At_Residence       int64\n    Net_Annual_Income      float64\n    Years_At_Business      float64\n    Prod_Sub_Category       object\n    Prod_Decision_Date      object\n    Source                  object\n    Type_Of_Residence       object\n    Nb_Of_Products           int64\n    Prod_Category           object\n    Age                    float64\n    dtype: object\n\n\n\n\n```python\nstring_cols = ['Customer_Type', 'P_Client', 'Educational_Level', 'Marital_Status', 'Prod_Sub_Category', 'Source', 'Type_Of_Residence', 'Prod_Category']\nX = ohe.fit_transform(df[string_cols])\nX.shape\n```\n\n\n\n\n    (5374, 36)\n\n\n\n\n```python\nclf = LogisticRegression(class_weight='balanced')\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.4, random_state=42)\nclf.fit(X_train, y_train)\n```\n\n    C:\\Users\\Thomas\\Anaconda3\\lib\\site-packages\\sklearn\\linear_model\\logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.\n      FutureWarning)\n\n\n\n\n\n    LogisticRegression(C=1.0, class_weight='balanced', dual=False,\n                       fit_intercept=True, intercept_scaling=1, l1_ratio=None,\n                       max_iter=100, multi_class='warn', n_jobs=None, penalty='l2',\n                       random_state=None, solver='warn', tol=0.0001, verbose=0,\n                       warm_start=False)\n\n\n\n\n```python\ny_pred = clf.predict(X_test)\naccuracy = accuracy_score(y_test, y_pred)\nprecision = precision_score(y_test, y_pred)\nrecall = recall_score(y_test, y_pred)\nmetric_score = metric(y_test, y_pred)\nprint(f'metric:{metric_score}')\nprint(f'accuracy:{accuracy}, 1-mean_Y:{1-np.average(y_test)}, precision:{precision}, recall:{recall}')\n```\n\n    metric:-0.004860465116279064\n    accuracy:0.7893023255813953, 1-mean_Y:0.9265116279069767, precision:0.15456674473067916, recall:0.4177215189873418\n\n\n### c) Logistic regression on all variables\n\nWe can concatenate the encoding of class variables to quantitative variables\n\n\n```python\nX_quantitative = df.loc[:,quant_cols]\nX_class = ohe.fit_transform(df[string_cols])\nprint(X_quantitative.shape, X_class.shape)\nX = np.concatenate((X_quantitative,X_class), axis=1)\nprint(X.shape)\n```\n\n    (5374, 6) (5374, 36)\n    (5374, 42)\n\n\n\n```python\nclf = LogisticRegression(class_weight='balanced')\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.4, random_state=42)\nclf.fit(X_train, y_train)\n```\n\n    C:\\Users\\Thomas\\Anaconda3\\lib\\site-packages\\sklearn\\linear_model\\logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.\n      FutureWarning)\n\n\n\n\n\n    LogisticRegression(C=1.0, class_weight='balanced', dual=False,\n                       fit_intercept=True, intercept_scaling=1, l1_ratio=None,\n                       max_iter=100, multi_class='warn', n_jobs=None, penalty='l2',\n                       random_state=None, solver='warn', tol=0.0001, verbose=0,\n                       warm_start=False)\n\n\n\n\n```python\ny_pred = clf.predict(X_test)\naccuracy = accuracy_score(y_test, y_pred)\nprecision = precision_score(y_test, y_pred)\nrecall = recall_score(y_test, y_pred)\nmetric_score = metric(y_test, y_pred)\nprint(f'metric:{metric_score}')\nprint(f'accuracy:{accuracy}, 1-mean_Y:{1-np.average(y_test)}, precision:{precision}, recall:{recall}')\n```\n\n    metric:-0.003534883720930221\n    accuracy:0.6920930232558139, 1-mean_Y:0.9265116279069767, precision:0.12048192771084337, recall:0.5063291139240507\n\n\n### c-bis) Adjusting the threshold for the decision to achieve optimal metric\n\nWe can plot the ROC curve thanks to adjusments made to the threshold for decision. Indeed logistic regression gives a number between 0 and 1 representing the probability of the sample beeing positive. We can then play on the decision boundary to increase our True Positive Rate or to increase our True Negative Rate.\n\n\n```python\nfrom sklearn.metrics import roc_curve\n```\n\n\n```python\ny_pred_score = clf.predict_proba(X_test)[:,1]\nfpr, tpr, thresholds = roc_curve(y_test, y_pred_score)\n```\n\n\n```python\nplt.figure()\nlw = 2\nplt.plot(fpr, tpr, color='darkorange',\n         lw=lw, label='ROC curve')\nplt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('1 - True Negative Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic')\nplt.legend(loc=\"lower right\")\nplt.show()\n```\n\nNote: $\\;\\; \\text{False Positive Rate} = 1 - \\text{True Negative Rate}$\n\nFinally we can look for the best metric across all thresholds (but we select it only using the train set):\n\n\n```python\ny_pred_score = clf.predict_proba(X_train)[:,1]\nfpr, tpr, thresholds = roc_curve(y_train, y_pred_score)\n```\n\n\n```python\nmetric_best = -1\nthreshold_best = 0\nfor threshold in thresholds:\n    y_pred =  (clf.predict_proba(X_train)[:,1] >= threshold).astype(int)\n    metric_score = metric(y_train, y_pred)\n    if metric_score >= metric_best:\n        metric_best = metric_score\n        threshold_best = threshold\n        \n\nprint(f'metric_best_train:{metric_best}, threshold_best:{threshold_best}')\n```\n\n    metric_best_train:0.01065446650124069, threshold_best:0.43739613642560293\n\n\n__Conclusion for Logistic Regression__:\n<br>\nThe optimal threshold to reject a credit application is about 0.36, which is lower than the default threshold of 0.5. Indeed, as stated in the beginning, misclassiying a credit default is more costly compared to misclasfying a credit that will be repaid. Our best logistic regression algorithm has the following metrics scores.\n\n\n```python\ny_pred = (clf.predict_proba(X_test)[:,1] >= threshold_best).astype(int)\naccuracy = accuracy_score(y_test, y_pred)\nprecision = precision_score(y_test, y_pred)\nrecall = recall_score(y_test, y_pred)\nmetric_score = metric(y_test, y_pred)\nprint(f'metric:{metric_score}')\nprint(f'accuracy:{accuracy}, 1-mean_Y:{1-np.average(y_test)}, precision:{precision}, recall:{recall}')\n```\n\n    metric:0.0035581395348837225\n    accuracy:0.5246511627906977, 1-mean_Y:0.9265116279069767, precision:0.10511882998171847, recall:0.7278481012658228\n\n\nAs we can notice, an high recall is necessary (despite a low precision) to maximise the bank's profits. This comes with a fairly low accuracy because the bank has to be very cautious of credit default. In a further study, we could vary the interest rate $i$, which was set to $5\\%$ here, and observe how the metrics for the best algorithm would repond to it.\n<br> As $i$ increases, we would probably see the recall going down and the accuracy and the precision go up, as paid-back credits become more lucrative.\n\n### d) Tree classification\n\n\n```python\nfrom xgboost import XGBClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nfrom xgboost import plot_importance\nimport matplotlib.pyplot as plt\n\n```\n\nWe first compute a tree with general parameters then print the importance of features \n\n\n```python\nX = np.concatenate((X_quantitative,X_class), axis=1)\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.25, random_state=42)\ny_train = y_train.to_numpy()\ny_test = y_test.to_numpy()\n\nmodel = XGBClassifier(learning_rate = 0.05, n_estimators=300, max_depth=8)\nmodel.fit(X_train, y_train)\n\ny_pred = model.predict(X_test)\naccuracy = accuracy_score(y_test, y_pred)\nprecision = precision_score(y_test, y_pred)\nrecall = recall_score(y_test, y_pred)\nmetric_score = metric(y_test, y_pred)\nprint(f'metric:{metric_score}')\nprint(f'accuracy:{accuracy}, 1-mean_Y:{1-np.average(y_test)}, precision:{precision}, recall:{recall}')\n\n# plot feature importance\nplot_importance(model)\n#to_graphviz(model)\nplt.show()\n```\n\nThe quantitave figures (f0 to f5) are the most important features, the age is overall the most important one. The important disparity among the weights of the features entices us to elastic net penalisation $J(\\beta)=(1-\\alpha) || \\beta ||^{2} +\\alpha || \\beta||_{1}$ to get rid of not important features.\n\n\n```python\nX = df.loc[:,quant_cols]\nX = X.loc[:,['Age','Net_Annual_Income','Years_At_Residence','Years_At_Business']]\n\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.25, random_state=42)\ny_train = y_train.to_numpy()\ny_test = y_test.to_numpy()\n\nmodel = XGBClassifier(learning_rate = 0.05, n_estimators=300, max_depth=10, reg_alpha=0.5)\nmodel.fit(X_train, y_train)\ny_pred = model.predict(X_test)\naccuracy = accuracy_score(y_test, y_pred)\nprecision = precision_score(y_test, y_pred)\nrecall = recall_score(y_test, y_pred)\nmetric_score = metric(y_test, y_pred)\nprint(f'metric:{metric_score}')\nprint(f'accuracy:{accuracy}, 1-mean_Y:{1-np.average(y_test)}, precision:{precision}, recall:{recall}')\n\n# plot feature importance\nplot_importance(model)\n\nplt.show()\n```\n\nIf we exclude the threshold for the classification we have 4 parameters to optimize:\n\nthe learning rate $lr \\in [0.01, 0.09]$, \n\nthe number of estimators $  \\in [\\![500;1500]\\!]  $,\n\nthe coefficient $\\alpha$ for the L1 regularisation in the elastic net $ \\in ]0,1[$, \n\nthe depth of the tree $ \\in [\\![4;8]\\!]   $\n\nThe vast state space to explore prevent us to use exhaustive search of the best hyperparameters, we use stochastic research instead refering  to the paper  [Random Search for Hyper-Parameter Optimization]( https://pdfs.semanticscholar.org/8e28/30fb6ba9ea201d4ec5d2d800ab9a9bf9677c.pdf)\n\n\n```python\nar=np.arange(0.01,0.09,0.0005)\n\nX = np.concatenate((X_quantitative,X_class), axis=1)\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.4, random_state=42)\ny_train = y_train.to_numpy()\ny_test = y_test.to_numpy()\n\nscale_pos_weight=y_train.size/y_train.sum()\n\nm_lr = -1\nm_n_estimators = -1\nm_max_depth = -1\nm_L1 = -1 \nmax_metric=0\n\nthresholds_tree = np.arange(10**(-4),10**(-2),10**(-5))\nprint('done')\nn_step=50 \nfor j in range(n_step):\n    \n    #param\u00e8tres\n    lr = np.random.choice(ar)\n    n_estim = np.random.randint(500,1500)\n    m_depth = np.random.randint(4,8)\n    L1 = np.random.choice([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9])\n    \n    model = XGBClassifier(learning_rate = lr, n_estimators=n_estim, max_depth=m_depth, reg_alpha=L1,scale_pos_weight=scale_pos_weight,objective='multi:softprob',num_class=2)\n    model.fit(X_train, y_train)\n    \n    y_pred = model.predict_proba(X_test)\n    \n    metric_best = -1\n    threshold_best = 0\n    for threshold in thresholds_tree:\n       \n        y_pred_tuning =  (y_pred[:,1] >= threshold).astype(int)\n        metric_score = metric(y_test, y_pred_tuning)\n        \n        if metric_score >= metric_best:\n            metric_best = metric_score\n            threshold_best = threshold\n\n    \n    print(\"\\r {:.2%} loading...\".format(j/n_step), end=\"\")\n    if max_metric < metric_best:\n        max_metric=metric_best\n        m_lr = lr\n        m_n_estimators =  n_estim\n        m_max_depth = m_depth\n        m_L1 = L1\n        print(j)\n        print(f'lr:{m_lr}, n_estimators:{m_n_estimators}, max_depth:{m_max_depth}, reg L1:{m_L1}, metric:{max_metric},threshold:{threshold_best}')\n\n```\n\n    done\n     0.00% loading...0\n    lr:0.022500000000000013, n_estimators:1495, max_depth:5, reg L1:0.9, metric:0.00448837209302326,threshold:0.00677\n     2.00% loading...1\n    lr:0.04050000000000003, n_estimators:1057, max_depth:6, reg L1:0.1, metric:0.00595348837209303,threshold:0.0047799999999999995\n     30.00% loading...15\n    lr:0.02100000000000001, n_estimators:1212, max_depth:7, reg L1:0.2, metric:0.006558139534883725,threshold:0.00509\n     98.00% loading...\n\nIf we test the select parameters on the test set we obtain:\n\n\n```python\nprint(f'lr:{m_lr}, n_estimators:{m_n_estimators}, max_depth:{m_max_depth}, reg L1:{m_L1}, metric on the train set:{max_metric},threshold:{threshold_best}')\nmodel = XGBClassifier(learning_rate = m_lr, n_estimators=m_n_estimators, max_depth=m_max_depth, reg_alpha=m_L1,scale_pos_weight=100,objective='multi:softprob',num_class=2)\nmodel.fit(X_train, y_train)\n\ny_pred = model.predict_proba(X_test) \ny_pred = (y_pred[:,1]>= threshold_best).astype(int)\n\nmetric_final = metric(y_test, y_pred)\nprint(f'metric on the test set:{metric_final}') \n\naccuracy = accuracy_score(y_test, y_pred)\nprecision = precision_score(y_test, y_pred)\nrecall = recall_score(y_test, y_pred)\nprint(f'accuracy:{accuracy}, 1-mean_Y:{1-np.average(Y)}, precision:{precision}, recall:{recall}')\n```\n\n    lr:0.02100000000000001, n_estimators:1212, max_depth:7, reg L1:0.2, metric on the train set:0.006558139534883725,threshold:0.00584\n    metric on the test set:0.004837209302325576\n    accuracy:0.37348837209302327, 1-mean_Y:0.9270561965016747, precision:0.09252912954078135, recall:0.8544303797468354\n\n\nAs in the logistic regression the chosen metric has for consequence to give a high importance to the recall at the expense of the precision\n\n### Deep Learning\n\n\n```python\nimport tensorflow as tf\nfrom tensorflow import keras\n```\n\nWe build our neural network using the sigmoid function for activation and  dense layers with dropout to reduce overfiting, we also use a normalization layer to have a continuum of values between zero and one and thus easily separate the results with a threshold. \n\n\n```python\nmodel_deep = keras.Sequential([\n    keras.layers.Dense(128, activation='sigmoid'),\n    keras.layers.Dropout(0.2),\n    keras.layers.Dense(128, activation='sigmoid'),\n    keras.layers.Dropout(0.5),\n    keras.layers.BatchNormalization(),\n    keras.layers.Dense(2, activation= 'sigmoid')\n])\n\n```\n\n\n```python\nmodel_deep.compile(optimizer='adam',\n              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n              metrics=['accuracy',])\n\n```\n\n\n```python\nmodel_deep.fit(X_train,y_train, epochs=30)\n```\n\n    Train on 3224 samples\n    Epoch 1/30\n    3224/3224 [==============================] - 1s 332us/sample - loss: 0.6388 - accuracy: 0.6616\n    Epoch 2/30\n    3224/3224 [==============================] - 0s 97us/sample - loss: 0.4905 - accuracy: 0.8824\n    Epoch 3/30\n    3224/3224 [==============================] - 0s 99us/sample - loss: 0.4175 - accuracy: 0.9225\n    Epoch 4/30\n    3224/3224 [==============================] - 0s 100us/sample - loss: 0.3966 - accuracy: 0.9271\n    Epoch 5/30\n    3224/3224 [==============================] - 0s 97us/sample - loss: 0.3918 - accuracy: 0.9274\n    Epoch 6/30\n    3224/3224 [==============================] - 0s 97us/sample - loss: 0.3899 - accuracy: 0.9274\n    Epoch 7/30\n    3224/3224 [==============================] - 0s 100us/sample - loss: 0.3884 - accuracy: 0.9274\n    Epoch 8/30\n    3224/3224 [==============================] - 0s 97us/sample - loss: 0.3874 - accuracy: 0.9274\n    Epoch 9/30\n    3224/3224 [==============================] - 0s 99us/sample - loss: 0.3873 - accuracy: 0.9274\n    Epoch 10/30\n    3224/3224 [==============================] - 0s 99us/sample - loss: 0.3869 - accuracy: 0.9274\n    Epoch 11/30\n    3224/3224 [==============================] - 0s 96us/sample - loss: 0.3866 - accuracy: 0.9274\n    Epoch 12/30\n    3224/3224 [==============================] - 0s 97us/sample - loss: 0.3864 - accuracy: 0.9274\n    Epoch 13/30\n    3224/3224 [==============================] - 0s 113us/sample - loss: 0.3864 - accuracy: 0.9274\n    Epoch 14/30\n    3224/3224 [==============================] - 0s 112us/sample - loss: 0.3863 - accuracy: 0.9274\n    Epoch 15/30\n    3224/3224 [==============================] - 0s 95us/sample - loss: 0.3862 - accuracy: 0.9274\n    Epoch 16/30\n    3224/3224 [==============================] - 0s 94us/sample - loss: 0.3862 - accuracy: 0.9274\n    Epoch 17/30\n    3224/3224 [==============================] - 0s 96us/sample - loss: 0.3861 - accuracy: 0.9274\n    Epoch 18/30\n    3224/3224 [==============================] - 0s 95us/sample - loss: 0.3861 - accuracy: 0.9274\n    Epoch 19/30\n    3224/3224 [==============================] - 0s 94us/sample - loss: 0.3861 - accuracy: 0.9274\n    Epoch 20/30\n    3224/3224 [==============================] - 0s 96us/sample - loss: 0.3860 - accuracy: 0.9274\n    Epoch 21/30\n    3224/3224 [==============================] - 0s 95us/sample - loss: 0.3860 - accuracy: 0.9274\n    Epoch 22/30\n    3224/3224 [==============================] - 0s 95us/sample - loss: 0.3860 - accuracy: 0.9274\n    Epoch 23/30\n    3224/3224 [==============================] - 0s 96us/sample - loss: 0.3860 - accuracy: 0.9274\n    Epoch 24/30\n    3224/3224 [==============================] - 0s 95us/sample - loss: 0.3860 - accuracy: 0.9274\n    Epoch 25/30\n    3224/3224 [==============================] - 0s 95us/sample - loss: 0.3860 - accuracy: 0.9274\n    Epoch 26/30\n    3224/3224 [==============================] - 0s 118us/sample - loss: 0.3860 - accuracy: 0.9274\n    Epoch 27/30\n    3224/3224 [==============================] - 0s 122us/sample - loss: 0.3860 - accuracy: 0.9274\n    Epoch 28/30\n    3224/3224 [==============================] - 0s 111us/sample - loss: 0.3860 - accuracy: 0.9274\n    Epoch 29/30\n    3224/3224 [==============================] - 0s 117us/sample - loss: 0.3860 - accuracy: 0.9274\n    Epoch 30/30\n    3224/3224 [==============================] - 0s 103us/sample - loss: 0.3859 - accuracy: 0.9274\n\n\n\n\n\n    <tensorflow.python.keras.callbacks.History at 0x16c7b995fc8>\n\n\n\nWe then selection the best threshold\n\n\n```python\ny_pred = model_deep.predict(X_train)\ny_pred_tuning = y_pred\n\namax = np.amax(y_pred_tuning[:,1])\namin = np.amin(y_pred_tuning[:,1])\n#print(amin)\n#print(amax)\n\nthresholds_deep = np.arange(amin,amax,10**(-7))\n\nmetric_best = -1\nthreshold_best = 0\n\nfor threshold in thresholds_deep:\n    y_pred_tuning = y_pred\n    y_pred_tuning =  (y_pred_tuning[:,1] >= threshold).astype(int)\n    metric_score = metric(y_train, y_pred_tuning)\n    \n    if metric_score >= metric_best:\n        metric_best = metric_score\n        threshold_best = threshold\n        \nprint(f'metric on the train set with best_threshold:{metric_best}, threshold_best:{threshold_best}')\n```\n\n    metric on the train set with best_threshold:0.0041098014888337475, threshold_best:2.537273865878827e-05\n\n\n\n```python\ny_pred = model_deep.predict(X_test)\ny_pred =  (y_pred[:,1] >= threshold_best).astype(int)\naccuracy = accuracy_score(y_test, y_pred)\nprecision = precision_score(y_test, y_pred)\nrecall = recall_score(y_test, y_pred)\nmetric_score = metric(y_test, y_pred)\nprint(f'metric on the test set:{metric_score}')\nprint(f'accuracy:{accuracy}, 1-mean_Y:{1-np.average(y_test)}, precision:{precision}, recall:{recall}, threshold_best:{threshold_best}')\n```\n\n    metric on the test set:0.0024883720930232583\n    accuracy:0.22930232558139535, 1-mean_Y:0.9265116279069767, precision:0.08151870463428253, recall:0.9240506329113924, threshold_best:2.537273865878827e-05\n\n\nOnce again the recall is really high\n\n## 7) Conclusion\n\nAfter preprocessing the data we tried various models and evaluated how each one performed on optimising the metric we defined for detecting credit default. After comparing them, we can conclude that our best model is the classification using tree with a metric score of 0.0048 (profit per capita/credit application) on the test set.\n<br>\nLooking at other standard ML metrics for this best model, we have a precision of 0.0925 and a recall of 0.8544 The high recall and low precision highlight the necessity of finding the credit default as they are far more costly to the bank.\n", "meta": {"hexsha": "3189025a00aa96448c8e0f4eb23af211587031cd", "size": 152232, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tristan_stampfler.ipynb", "max_stars_repo_name": "AceZz/CreditDefault", "max_stars_repo_head_hexsha": "2dd275e2074cfaaa63548247c38f23169af80b19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tristan_stampfler.ipynb", "max_issues_repo_name": "AceZz/CreditDefault", "max_issues_repo_head_hexsha": "2dd275e2074cfaaa63548247c38f23169af80b19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tristan_stampfler.ipynb", "max_forks_repo_name": "AceZz/CreditDefault", "max_forks_repo_head_hexsha": "2dd275e2074cfaaa63548247c38f23169af80b19", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.867802385, "max_line_length": 26032, "alphanum_fraction": 0.6756398129, "converted": true, "num_tokens": 14192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.09009299945888766, "lm_q1q2_score": 0.04013909215923869}}
{"text": "\n\n# Qiskit Tutorials\n\nWelcome Qiskitters.\n\n\nThese tutorials aim to explain how to use Qiskit. We assume you have installed Qiskit; if not, please look at [qiskit.org](http://www.qiskit.org) or the install [documentation](https://qiskit.org/documentation/install.html). \n\nThe focus of these notebooks is not on learning quantum computing.  Instead we will focus on how to use Qiskit, and will go into details only when needed. For those interested in learning about quantum computing we recommend the [Qiskit Textbook](https://qiskit.org/textbook) that we and the community have put together, or the [Qiskit documentation](https://qiskit.org/documentation).\n\n\n## Circuits\n\nThis section gives you the tools to make your first circuits, execute them, and view the data.\n\n1. [Circuit basics](tutorials/circuits/01_circuit_basics.ipynb) - How to use the Qiskit quantum circuit.\n\n\n2. [Plotting data in Qiskit](tutorials/circuits/2_plotting_data_in_qiskit.ipynb) -  Illustrates the different ways of plotting data in Qiskit.\n\n\n3. [Summary of quantum operations](tutorials/circuits/3_summary_of_quantum_operations.ipynb) - List of quantum operations (gates, reset, measurements) in Qiskit Terra\n  \n        \n## Advanced Circuits\n\n1. [Advanced circuits](tutorials/circuits_advanced/01_advanced_circuits.ipynb) - Circuit building tools added including registerless declarations, composite gate updates and parameterized circuits.\n\n\n2. [Operators overview](tutorials/circuits_advanced/02_operators_overview.ipynb) - Gives a summary of the features and uses of the Operator class.\n\n\n3. [Advanced circuit visualization](tutorials/circuits_advanced/03_advanced_circuit_visualization.ipynb) - Details on drawing your quantum circuits.\n\n\n4. [Transpiler passes and passmanager](tutorials/circuits_advanced/04_transpiler_passes_and_passmanager.ipynb) - How to use the transpiler passes, passmanger, and extend the transpiler with a new pass.\n\n\n## Pulse\n\n1. [Building pulse schedules](tutorials/circuits_advanced/06_building_pulse_schedules.ipynb) - Building schedules of pulses.\n\n\n2. [Pulse Scheduler](tutorials/circuits_advanced/07_pulse_scheduler.ipynb) - Scheduling pulse.\n\n\n3. [Getting system information](tutorials/circuits_advanced/08_gathering_system_information.ipynb) - Obtaining system information.\n\n\n4. [Pulse simulation](tutorials/circuits_advanced/09_pulse_simulator_duffing_model.ipynb) - Simulate a Duffing oscillator using the pulse simulator.\n\n\n##  High-Performance Simulators\n\nTo really speed up development of quantum computers, we need better simulators with the ability to model realistic noise processes that occur during computation on actual devices. Qiskit provides a high-performance simulator framework called `Aer` for studying quantum computing algorithms and applications in the noisy intermediate-scale quantum regime. \n\n1. [Simulators](tutorials/simulators/1_aer_provider.ipynb) - Gives a summary of the Qiskit Aer provider containing the Qasm, statevector, and unitary simulator.\n\n\n2. [Device noise simulation](tutorials/simulators/2_device_noise_simulation.ipynb) - Shows how to use the Qiskit Aer noise module to automatically generate a basic noise model for simulating hardware backends.\n\n\n3. [Building noise models](tutorials/simulators/3_building_noise_models.ipynb) - Shows how to use Qiskit Aer noise module to construct custom noise models for noisy simulations\n\n\n4. [Custom gate noise](tutorials/simulators/4_custom_gate_noise.ipynb) - Shows to implement simulations using custom noisy gates.\n\n\n5. [Noise transformations](tutorials/simulators/5_noise_transformation.ipynb) - Noise approximation utility functions to construct approximate Clifford noise models out of a general noise model\n\n\n6. [Extended stabilizer tutorial](tutorials/simulators/6_extended_stabilizer_tutorial.ipynb) - Gives an overview of the *extended stabilizer* Qasm Simulator method\n\n\n7. [Matrix Product State simulator](tutorials/simulators/7_matrix_product_state_method.ipynb) - Gives an overview of the *matrix product state* Simulator method\n\n\n##  Quantum Device Noise Analysis\n\nThis includes better characterization of errors, improving gates, and computing in the presence of noise. Qiskit `ignis` is meant for those who want to design quantum error correction codes, or who wish to study ways to characterize errors through methods such as tomography and randomized benchmarking, or even to find a better way for using gates by exploring dynamical decoupling and optimal control.\n\n1. [Hamiltonian and gate characterizations](tutorials/noise/1_hamiltonian_and_gate_characterization.ipynb) - Sequences to measure ZZ rates between qubits and to measure rotation and angle errors in the gates.\n\n\n2. [Relaxation and decoherence](tutorials/noise/2_relaxation_and_decoherence.ipynb) - How to measure coherence times on the real quantum hardware\n\n\n3. [Measurement error mitigation](tutorials/noise/3_measurement_error_mitigation.ipynb) - How to peform calibration experiments for measurement errors and fed those calibrations into a \"filter\" that can be utilized to mitigate errors in subsequent experiments.\n\n\n4. [Randomized benchmarking](tutorials/noise/4_randomized_benchmarking.ipynb) - Randomized benchmarking (RB) is a technique used to measure the average gate error by measuring the outcomes of random Clifford circuits. This is used internally to report gate errors on our systems. \n\n\n5. [Quantum volume](tutorials/noise/5_quantum_volume.ipynb) - How to run quantum volume measurements on the quantum hardware.\n\n\n6. [Repetition Code](tutorials/noise/6_repetition_code.ipynb) - How to run a simple error correction code, known as the repetition code. This can be used to characterize bit flip errors in the hardware.\n\n\n7. [Accreditation](tutorials/noise/7_accreditation.ipynb) - protocol devised to characterize the reliability of noisy quantum devices.\n\n\n```python\nimport qiskit.tools.jupyter\n%qiskit_copyright\n```\n\n\n<div style='width: 100%; background-color:#d5d9e0;padding-left: 10px; padding-bottom: 10px; padding-right: 10px; padding-top: 5px'><h3>This code is a part of Qiskit</h3><p>&copy; Copyright IBM 2017, 2022.</p><p>This code is licensed under the Apache License, Version 2.0. You may<br>obtain a copy of this license in the LICENSE.txt file in the root directory<br> of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.<p>Any modifications or derivative works of this code must retain this<br>copyright notice, and modified files need to carry a notice indicating<br>that they have been altered from the originals.</p></div>\n\n\n\n```python\npip install qiskit\n```\n\n    Collecting qiskit\n      Using cached qiskit-0.34.2.tar.gz (13 kB)\n    Collecting qiskit-terra==0.19.2\n      Downloading qiskit_terra-0.19.2-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (6.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.5 MB 3.5 MB/s eta 0:00:01\n    \u001b[?25hCollecting qiskit-aer==0.10.3\n      Downloading qiskit_aer-0.10.3-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (18.0 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 18.0 MB 11.2 MB/s eta 0:00:01\n    \u001b[?25hCollecting qiskit-ibmq-provider==0.18.3\n      Using cached qiskit_ibmq_provider-0.18.3-py3-none-any.whl (238 kB)\n    Collecting qiskit-ignis==0.7.0\n      Using cached qiskit_ignis-0.7.0-py3-none-any.whl (200 kB)\n    Requirement already satisfied: numpy>=1.16.3 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-aer==0.10.3->qiskit) (1.20.1)\n    Requirement already satisfied: scipy>=1.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-aer==0.10.3->qiskit) (1.6.2)\n    Requirement already satisfied: requests>=2.19 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (2.25.1)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (2.8.1)\n    Collecting websocket-client>=1.0.1\n      Using cached websocket_client-1.3.1-py3-none-any.whl (54 kB)\n    Collecting requests-ntlm>=1.1.0\n      Using cached requests_ntlm-1.1.0-py2.py3-none-any.whl (5.7 kB)\n    Requirement already satisfied: urllib3>=1.21.1 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (1.26.4)\n    Collecting retworkx>=0.8.0\n      Downloading retworkx-0.11.0-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.6 MB 19.1 MB/s eta 0:00:01\n    \u001b[?25hRequirement already satisfied: setuptools>=40.1.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-ignis==0.7.0->qiskit) (52.0.0.post20210125)\n    Requirement already satisfied: sympy>=1.3 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-terra==0.19.2->qiskit) (1.8)\n    Collecting python-constraint>=1.4\n      Using cached python-constraint-1.4.0.tar.bz2 (18 kB)\n    Collecting dill>=0.3\n      Using cached dill-0.3.4-py2.py3-none-any.whl (86 kB)\n    Requirement already satisfied: psutil>=5 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-terra==0.19.2->qiskit) (5.8.0)\n    Collecting tweedledum<2.0,>=1.1\n      Downloading tweedledum-1.1.1-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (929 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 929 kB 15.5 MB/s eta 0:00:01\n    \u001b[?25hRequirement already satisfied: ply>=3.10 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-terra==0.19.2->qiskit) (3.11)\n    Collecting symengine>=0.8\n      Downloading symengine-0.9.2-cp38-cp38-manylinux2010_x86_64.whl (37.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 37.5 MB 20.5 MB/s eta 0:00:01\n    \u001b[?25hCollecting stevedore>=3.0.0\n      Using cached stevedore-3.5.0-py3-none-any.whl (49 kB)\n    Requirement already satisfied: six>=1.5 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from python-dateutil>=2.8.0->qiskit-ibmq-provider==0.18.3->qiskit) (1.15.0)\n    Requirement already satisfied: chardet<5,>=3.0.2 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit) (4.0.0)\n    Requirement already satisfied: idna<3,>=2.5 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit) (2020.12.5)\n    Requirement already satisfied: cryptography>=1.3 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit) (3.4.7)\n    Collecting ntlm-auth>=1.0.2\n      Using cached ntlm_auth-1.5.0-py2.py3-none-any.whl (29 kB)\n    Requirement already satisfied: cffi>=1.12 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit) (1.14.5)\n    Requirement already satisfied: pycparser in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit) (2.20)\n    Collecting pbr!=2.1.0,>=2.0.0\n      Using cached pbr-5.8.1-py2.py3-none-any.whl (113 kB)\n    Requirement already satisfied: mpmath>=0.19 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from sympy>=1.3->qiskit-terra==0.19.2->qiskit) (1.2.1)\n    Building wheels for collected packages: qiskit, python-constraint\n      Building wheel for qiskit (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Created wheel for qiskit: filename=qiskit-0.34.2-py3-none-any.whl size=11792 sha256=c39badb3b0928def2628a9dac0acc060a9f28936042334e0589bee4834bc4a4c\n      Stored in directory: /home/dsmishler/.cache/pip/wheels/fc/65/25/bf94d3c84cabe3eca2af16a7e8fcc0d39a0910e9497245a1e4\n      Building wheel for python-constraint (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Created wheel for python-constraint: filename=python_constraint-1.4.0-py2.py3-none-any.whl size=24079 sha256=e782789a0c00a0a6ce83f411d90d1e244450609583627506130e145402c19324\n      Stored in directory: /home/dsmishler/.cache/pip/wheels/86/ba/5c/4e9115777de42c6a2e1ca77ef7c9d0d479254c5080341b55c5\n    Successfully built qiskit python-constraint\n    Installing collected packages: pbr, tweedledum, symengine, stevedore, retworkx, python-constraint, ntlm-auth, dill, websocket-client, requests-ntlm, qiskit-terra, qiskit-ignis, qiskit-ibmq-provider, qiskit-aer, qiskit\n    Successfully installed dill-0.3.4 ntlm-auth-1.5.0 pbr-5.8.1 python-constraint-1.4.0 qiskit-0.34.2 qiskit-aer-0.10.3 qiskit-ibmq-provider-0.18.3 qiskit-ignis-0.7.0 qiskit-terra-0.19.2 requests-ntlm-1.1.0 retworkx-0.11.0 stevedore-3.5.0 symengine-0.9.2 tweedledum-1.1.1 websocket-client-1.3.1\n    Note: you may need to restart the kernel to use updated packages.\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "c8b4e7ff612f51ae43dce3a81e36858213c8a6bd", "size": 16352, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "start_here.ipynb", "max_stars_repo_name": "DSMishler/Qiskit-clone-CS561", "max_stars_repo_head_hexsha": "6aff182e591588d157364e6e6a9f89efdab9ec20", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "start_here.ipynb", "max_issues_repo_name": "DSMishler/Qiskit-clone-CS561", "max_issues_repo_head_hexsha": "6aff182e591588d157364e6e6a9f89efdab9ec20", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "start_here.ipynb", "max_forks_repo_name": "DSMishler/Qiskit-clone-CS561", "max_forks_repo_head_hexsha": "6aff182e591588d157364e6e6a9f89efdab9ec20", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.9858156028, "max_line_length": 646, "alphanum_fraction": 0.678816047, "converted": true, "num_tokens": 4017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.0863234718851487, "lm_q1q2_score": 0.040131917725812156}}
{"text": "## Formal Grammar Example: Barsalou Perceptual Symbol Grammar\n\nTo demonstrate the formal grammar and language framework I developed, I created a formal grammar that implements a weird version of Barsalou's Percetpual Symbol Systems. Each sentence is a \"simulation\", with each simulation having exactly one \"simulator\", which in turn could have many categories and instances that make it up. Not that that's exactly what he was saying, but it's a fun attempt to formalize his system from his 1999 BBS paper.\n\n\n```python\nfrom IPython.display import display, Latex\n\nfrom grammar import Grammar, ProductionRule\n\n# build a hierarchy of production rules\nproduction_rules = [\n    ProductionRule('simulation', ['simulator', 'category', 'instance'], n_outputs='all'),\n        ProductionRule('simulator', ['driving', 'flying', 'seeing red', 'seeing blue', 'seeing green'], n_outputs='one'),\n        ProductionRule('category', ['car', 'airplane', 'bird', 'grass', 'bed'], n_outputs='many'),\n        ProductionRule('instance', ['2004 pontiac grand am', '2016 subaru crosstrack', '2010 chevy silverado', \n                                    'Boeing 747', 'queen bed with yellow sheets', 'cardinal', 'sky',\n                                    'cheatgrass', 'kentucky bluegrass'], n_outputs='many')\n]\n\n# instantiate the grammar based on the rules\nperceptual_symbol_grammar = Grammar(production_rules)\n# use the print_latex() method of the Grammar class to print the formal grammar\ndisplay(Latex(perceptual_symbol_grammar.print_latex()))\n```\n\n\n\n\\begin{equation}\n\\begin{array}{ll}\n    ( & \\\\\n       & S = \\{\\textrm{ simulation }\\}, \\\\\n       & N = \\{ \\textrm{category}, \\textrm{simulation}, \\textrm{instance}, \\textrm{simulator} \\}, \\\\\n       & \\Sigma = \\{ \\textrm{queen bed with yellow sheets}, \\textrm{2016 subaru crosstrack}, \\textrm{car}, \\textrm{seeing blue}, \\textrm{cheatgrass}, \\textrm{2004 pontiac grand am}, \\textrm{flying}, \\textrm{seeing green}, \\textrm{bed}, \\textrm{Boeing 747}, \\textrm{driving}, \\textrm{seeing red}, \\textrm{grass}, \\textrm{2010 chevy silverado}, \\textrm{sky}, \\textrm{cardinal}, \\textrm{bird}, \\textrm{airplane}, \\textrm{kentucky bluegrass} \\}, \\\\\n       &P = \\{ \\\\\n       & \\begin{array}{ll}\n            & simulation\\rightarrow\\textrm{simulator}~|~\\textrm{category}~|~\\textrm{instance} \\\\\n& simulator\\rightarrow\\textrm{driving}~|~\\textrm{flying}~|~\\textrm{seeing red}~|~\\textrm{seeing blue}~|~\\textrm{seeing green} \\\\\n& category\\rightarrow\\textrm{car}~|~\\textrm{airplane}~|~\\textrm{bird}~|~\\textrm{grass}~|~\\textrm{bed} \\\\\n& instance\\rightarrow\\textrm{2004 pontiac grand am}~|~\\textrm{2016 subaru crosstrack}~|~\\textrm{2010 chevy silverado}~|~\\textrm{Boeing 747}~|~\\textrm{queen bed with yellow sheets}~|~\\textrm{cardinal}~|~\\textrm{sky}~|~\\textrm{cheatgrass}~|~\\textrm{kentucky bluegrass} \\\\\n       \\end{array} \\\\\n     & \\} \\\\\n\n    ) &\n\\end{array}\n\\end{equation}\n\n\n\n\n```python\n# now let's create a language that will produce sentences based on the grammar\nfrom grammar import Language\n\nl = Language(perceptual_symbol_grammar)\n\nprods = l.productions()\n```\n\n\n```python\n# You can run this as many times as you like and get a new production\nfor i in range(10):\n    p = next(prods)\n    print(next(prods) + '\\n')\n```\n\n    seeing green bird car airplane grass 2010 chevy silverado cheatgrass sky Boeing 747\n    \n    flying airplane 2004 pontiac grand am Boeing 747 2010 chevy silverado queen bed with yellow sheets kentucky bluegrass cheatgrass sky 2016 subaru crosstrack\n    \n    seeing green grass airplane bird car bed sky cardinal 2016 subaru crosstrack kentucky bluegrass cheatgrass 2004 pontiac grand am Boeing 747 2010 chevy silverado queen bed with yellow sheets\n    \n    driving car bird bed airplane grass 2010 chevy silverado Boeing 747 2016 subaru crosstrack\n    \n    seeing red bird car kentucky bluegrass 2010 chevy silverado Boeing 747 cardinal cheatgrass sky 2016 subaru crosstrack\n    \n    seeing blue airplane car bed bird queen bed with yellow sheets 2016 subaru crosstrack Boeing 747\n    \n    seeing red bird airplane 2010 chevy silverado\n    \n    flying car 2010 chevy silverado queen bed with yellow sheets kentucky bluegrass cheatgrass cardinal 2004 pontiac grand am sky 2016 subaru crosstrack Boeing 747\n    \n    driving bird car queen bed with yellow sheets Boeing 747 sky 2004 pontiac grand am 2016 subaru crosstrack cardinal 2010 chevy silverado\n    \n    seeing blue airplane grass Boeing 747 2010 chevy silverado queen bed with yellow sheets 2016 subaru crosstrack\n    \n\n", "meta": {"hexsha": "5b2ec8fcd8b852227ba8cf8083b21eb14f504b03", "size": 6419, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "formal-grammar/PerceptualSymbolGrammar.ipynb", "max_stars_repo_name": "mtpain/COGS-202-HW", "max_stars_repo_head_hexsha": "951b913fc8d9510061f1c770db57451009fe1b35", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "formal-grammar/PerceptualSymbolGrammar.ipynb", "max_issues_repo_name": "mtpain/COGS-202-HW", "max_issues_repo_head_hexsha": "951b913fc8d9510061f1c770db57451009fe1b35", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "formal-grammar/PerceptualSymbolGrammar.ipynb", "max_forks_repo_name": "mtpain/COGS-202-HW", "max_forks_repo_head_hexsha": "951b913fc8d9510061f1c770db57451009fe1b35", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.5099337748, "max_line_length": 480, "alphanum_fraction": 0.59900296, "converted": true, "num_tokens": 1304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.08269734493579813, "lm_q1q2_score": 0.04005694690948474}}
{"text": "\\title{Some extensions for Jupyter/IPython notebook}\n\\author{J.-F Bercher \\par \\par Professor at ESIEE Paris}\n\\maketitle\n\n**Foreword -- ** \n\nThis notebook was used during a talk at [PyParis 2017](http://pyparis.org/). In order to fully reproduce what was done there, \n\n1. you should have a working installation of the  [jupyter_contrib](https://github.com/ipython-contrib/jupyter_contrib_nbextensions) notebook extensions. See [here](https://github.com/ipython-contrib/jupyter_contrib_nbextensions) for installation instructions. Using pip, it should be as easy as\n```\npip install https://github.com/ipython-contrib/jupyter_contrib_nbextensions/tarball/master\n```\nand then \n```\njupyter contrib nbextension install --user\n``` \n(or `--system` to install system wide). The, you should enable at least `highlighter`, `latex_envs`\n\n2. You need to have a copy of the following repo and a demo nbextension `toggleCase` installed: do this by\n    - install the demo nbextension by \n    ```\n    jupyter nbextension install https://rawgit.com/jfbercher/small_nbextensions/master/toggleCase.zip --user\n    ```\n    - download https://github.com/jfbercher/PyParis2017/raw/master/JupNbextensions.zip, unzip, change to PyParis2017 directory and \\underline{run jupyter notebook from that directory} (this preserve links) -- alternatively, you can just git clone this repo.\n    \n3. Displaying correcly the present notebook needs the [jupyter_latex_envs](https://pypi.python.org/pypi/jupyter_latex_envs) nbextension to be installed and enabled; is it not a strong requirement though.\n\n- Unfortunately, during the talk, the demo for `python-markdown` failed. This was due to the fact that this extension needs the notebook to be *trusted* (by pressing a menu button on the upper right)\n\n\n```javascript\n%%javascript\n// Load useful extensions\nJupyter.utils.load_extensions('highlighter/highlighter')\nJupyter.utils.load_extensions('latex_envs/latex_envs')\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n# Objective and agenda\n\n- Present and describe some Jupyter/IPython notebook extensions by the author and others of the [jupyter_contrib_nbextensions](https://github.com/ipython-contrib/jupyter_contrib_nbextensions) group which are useful for\n\n    - core development and data analysis,\n    - authoring; publication of research reports and papers,\n    - education/classroom animation.\n- [*jupyter_contrib_nbextensions is also a forum to experiment new ideas and have fun*]    \n- Give some hints on ways to develop an nbextension\n- call for ideas and contributors for the `jupyter_contrib_nbextensions` group\n\n\\begin{comment}\n\n- open source: many contributors to find in the commit history\n- will preferentially describe extensions I have initiated or contributed to, but also other ones\n- even if I say \"I\" or \"my\", there are often other contribs (code by others/suggestions/patches,etc )\n\\end{comment}\n\n\\begin{comment}\n\n- Wonderful introduction by Sylvain Corlay\n\n    - --> be involved in open source and start small! Almost only small things here\n    - --> Almost everybody have alreay used Jupyter... don't need to advocate \n    \n\\end{comment}\n\n# A small recall: what is the Jupyter notebook \n\n(formerly the IPython notebook)\n\n- a browser application that allows to create and share live documents which embed text, code and multimedia. \n- use as an IDE with integrated documentation capabilities, \n- for reproductible research\n- as an authoring system, \n- demos or full experimentations for teaching. \n\nIn these three areas (and more), the basic capabilities of the notebook can be extended through notebook extensions.\n\n\n## Markdown cells\nCan mix [markdown](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet), with\n- *emphasis*, \n- **strong emphasis**,\n- lists\n- support for images, $\\LaTeX$ equations, e.g. \n\\begin{equation}\n\\sum_{n=0}^{N-1} x[n] e^{j2\\pi f n}\n\\end{equation}\netc...\n\n## Code cells\n\n\n```python\nimport numpy as np\ndef random_letters(size=1, maxletter=52):\n    import string\n    return [string.ascii_letters[k] \n            for k in np.random.randint( 0, maxletter, size=size)]\n\nz = random_letters(12, 26)\nprint(z)\n```\n\n\n```python\n%matplotlib inline\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nplt.plot(np.random.randn(256))\n```\n\n\\begin{textboxa}The basic capabilities of the notebook can be extended through notebook extensions. These can modify the UI or behavior of the notebook, such as adding buttons to your toolbar, new keyboard shortcuts, etc. They can also add new functionalities. \n\\end{textboxa}\n\n# Example of a small toy extension\n\n*from [https://mindtrove.info/4-ways-to-extend-jupyter-notebook/#nb-extensions](https://mindtrove.info/4-ways-to-extend-jupyter-notebook/#nb-extensions)*\n\nJupyter Notebook extensions (nbextensions) are javaScript modules. \n\nTo write a new extension, you must implement your logic in a JavaScript file conforming to the **AMD specification** so that Jupyter can load it using RequireJS. You should define and **export a load_ipython_extension function** in your module so that Jupyter can invoke it after initializing its own components. \n\nWithin that function, you are free to \n- manipulate the DOM of the page, \n- invoke Jupyter JavaScript APIs, \n- listen for Jupyter events, \n- load other modules, and so on.\n\n## First extension \n\nThe extension features a menu button and a keyboard shortcut. It displays an alert dialog. You can test it with the \"T\" button on the toolbar. \n\n[Source: demo1.js](http://localhost:8888/nbextensions/toggleCase/demo1.js)\n\n<span class=\"mark\">The line below loads the extension we devised. \nSince the javascript is stored silently in a `<script>` tag in the output. The extension will be reloaded automatically when reloading the notebook.\n\n<span class=\"mark\">To avoid this, you will need to clear the output (or all outputs) of the relevant cells before reloading, by the `Cell/Curent Output/Clear` menu; then save and reload.</span></span> \n\n\n```javascript\n%%javascript\nJupyter.utils.load_extensions('toggleCase/demo1')\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n## Organizing \n\n- button and shorcut definitions can be devoted to separated functions. A initialisation step can be added. \n\n[Source: demo2.js](http://localhost:8888/nbextensions/toggleCase/demo2.js)\n\n\n```javascript\n%%javascript\nJupyter.utils.load_extensions('toggleCase/demo2')\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n## Something to do \n\n- A function is added to do something with the extension. When a text is selected and the button pushed, or the shortcut pressed, then the case of that text is toogled. \n\n[Source: demo3.js](http://localhost:8888/nbextensions/toggleCase/demo3.js)\n\n\n\n```javascript\n%%javascript\nJupyter.utils.load_extensions('toggleCase/demo3')\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n## Loading a configuration\n\n- <span class=\"burk\">It is possible to store parameters in system, and even *edit* them.</span> \n- The great utility here is the [nbextensions_configurator](https://github.com/Jupyter-contrib/jupyter_nbextensions_configurator) by @jcb91  [Application](http://localhost:8888/nbextensions/) -- This is a *server extension*. \n     - the parameters are specified via a *yaml* description file\n     - they can be inspected, selected, edited via a UI - Here, we edit the keyboard shortcut\n\n[Source: demo4.js](http://localhost:8888/nbextensions/toggleCase/demo4.js)\n\n[demo4.yaml](https://raw.githubusercontent.com/jfbercher/small_nbextensions/master/toggleCase/toggleCase.yaml)\n\n\n```javascript\n%%javascript\nJupyter.utils.load_extensions('toggleCase/demo4')\n```\n\n## Ensuring correct loading by waiting for the notebook or kernel to be fully available. \n\nIndeed, <span class=\"mark\">it is possible that the extension is loaded **before** the notebook is fully loaded</span>. \nBut sometimes the extension needs the notebook to be fully ready, or the kernel to be started. \n\n- This check is not necessary here, though, but an example is provided.\n\nAlso a css can be loaded in the notebook with styles added for the nbextension. \n\n[Source: toggleCase](http://localhost:8888/nbextensions/toggleCase/toggleCase.js)\n\n\n```javascript\n%%javascript\nJupyter.utils.load_extensions('toggleCase/toggleCase')\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n## Summary\nSo, we see that the structure of a nbextension is\n\nDIRECTORY _____  main.js               // main script\n            |__  extension_name.yaml   // extension description and parameters (for @jcb91's nbextension configurator)         \n            |__  main.css              // optional css\n            |__  other.js              // other js file that can be loaded by the main one\n                        \n**Loading (one shot/one notebook)** : `Jupyter.utils.load_extensions('DIRECTORY/main.js')`\n\n**Loading (permanently/any notebook)** : `jupyter nbextension enable DIRECTORY/main.js`\n\n**Loading via the nbextension_configurator**: use the UI in `Edit/nbextensions Config` or directly at [http://localhost:8888/nbextensions](http://localhost:8888/nbextensions) (adapt the port if your server runs on a different port, maybe on a different address if you use JupyterHub)\n\n# A tour of some nbextensions\n\nWe will have a tour of some nbextensions, pointing out\n- history, contributors\n- new functionalities\n- some implementation details (principles and Jupyter API)\n- specific highlights\n\n1. classroom\n2. usability/authoring\n3. coding\n\n## Classroom/Education\n\n  - classroom e.g: [exercise](http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/exercise/readme.html), [exercise2](http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/exercise2/readme.html) (include exercises with hidden solutions), [highlighter](http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/highlighter/readme.html) (select, highlight, annotate text), [snippets menu](http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/snippets_menu/readme.html)..\n\n### exercise and exercise2\n\n- Exercise is an extension by @juhasch Juergen Hasch\n- Exercise 2 is a fork by @jfbercher with a different layout -- but the underlying logic is the same\n\ndemo [here](http://localhost:8888/nbextensions/nbextensions_configurator/rendermd/nbextensions/exercise/readme.md)\nor\n[here](http://localhost:8888/notebooks/Example%20exercise2.ipynb)\n\n**Internals** exercise and exercise2 add respectively a solution and solution2 metadata to solution cells, with for value the current state hidden/shown of the solution. \n- For exercise, a div with the plus/minus character is prepended to the solution heading cell. \n- For exercise2, a flex-wrap style is added to the solution heading cell and a checkbox widget, with some css styling, is appended to the cell.\n\n\u261e At startup, a loop over all cells tests if these metadata are present and restore the widgets, and the visibility to  the last recorded state. \n[source](http://localhost:8888/nbextensions/exercise/main.js)\n\n\n\u261e Jupyter API: `cell = IPython.notebook.get_selected_cell();` `IPython.notebook.select_next();`\nThe cell object has a metadata attribute (another object) --> `cell.metadata.solution = shown`\n\n\n### Highlighter\n\n**Use case:** With IPython notebooks distributed to students, in class, let them highlight what they feel important. \n\ndemo [here](http://localhost:8888/nbextensions/nbextensions_configurator/rendermd/nbextensions/highlighter/README.md)\n\n[Source](http://localhost:8888/nbextensions/highlighter/highlighter.js)\n\n**Internals** \n\n\n\u261e API: `var selectedText = window.getSelection().toString();` \n`cell_text = cell_text.replace(identifiedText,highlight(identifiedText,scheme))`\n(command mode)\n\n\u261e Jupyter/codemirror API: `var cm = cell.code_mirror;  var selectedText = cm.getSelection()`\n`cm.replaceSelection(highlight(selectedText,scheme))`\n(edit mode) \n\n\u261e A fuzzy search is implemented to align the rendered text (command mode) to the underlying source text\n\n**Highlights can be exported to html/LaTeX**\n\n- see [this documentation](http://localhost:8888/nbextensions/highlighter/export_highlights.html)\n- Conversion is achieved using `nbconvert`. This app. supports pre and postprocessing. \n\nThe pre-post script is [here](http://localhost:8888/files/pp_highlighter.py). \n\nThe key for conversion resides in subclassing \n```\npreprocess_cell(self, cell, resources, index)\n```\nand `postprocess(self, input)`\n\n\n### Snippets menu\n\nThat's a great extension by @moble (with contribs from @jcb91)\n\n[documentation](http://localhost:8888/nbextensions/nbextensions_configurator/rendermd/nbextensions/snippets_menu/readme.md) and demo\n\n## Usability/authoring\n\n - notebook usage and publication: [toc2](http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/toc2/README.html) (table of contents/navigation menu),  [jupyter_highlight_selected_word](https://github.com/jcb91/jupyter_highlight_selected_word),[collapsible headings](http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/collapsible_headings/readme.html), [python markdown](http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/python-markdown/readme.html),  [nbTranslate](http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/nbTranslate/README.html) (multilanguage support), [latex_envs](http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/latex_envs/README.html) (use LaTeX environments within the notebook -- and export them)\n\n### The toc2 extension\n\n\nThis is a fork of  @minrk's toc extension, with many additional capabilities. It is a quite big extension (essentially) maintained by @jfbercher.\n\n[documentation](http://localhost:8888/nbextensions/nbextensions_configurator/rendermd/nbextensions/toc2/README.md) and demo\n\nSources : \n- [main](http://localhost:8888/nbextensions/toc2/main.js);\n- [toc2](http://localhost:8888/nbextensions/toc2/toc2.js)\n\n\n\n**Internals** \n\nMany things, but let us point out\n\n- Configuration is stored in part in system (`notebook.json`) and in each edited notebooks. Thus config can be modified per notebook and states stored (and restored)\n- Additional css is generated on the fly from user parameters (as entered in configurator UI, eg colors)\n- Structure for waiting full availabilty of the notebook before running extension code.\n\n\n**Exporting** the table of contents\n\nSince the toc is generated and updated on the fly, with many options and functionalities, the idea was to\n- *embed in the html output the very same javascript that is used in the liveNotebook*\n   - [jinja2 template](http://localhost:8888/files/toc2.tpl)\n   - [exporter](http://localhost:8888/files/toc2.py) (python file) --> only set the template name\n   - entry point set in [setup.py](http://localhost:8888/files/setup.py) recognized by `nbconvert`, as in \n   ```\n     'nbconvert.exporters': [\n                'html_toc = jupyter_contrib_nbextensions.nbconvert_support.toc2:TocExporter',  # noqa: E501\n   ...\n    ```\n\nExport can be done as follows:\n\n```jupyter nbconvert FILE.ipynb --template toc2```\n\nAn exporter is also available. It is possible to export to html with toc by\n\n```jupyter nbconvert --to html_toc FILE.ipynb```\n\nIf you also use latex_envs, you can embed both functionalities while exporting with\n\n```jupyter nbconvert --to html_with_toclenvs FILE.ipynb```\n\nSee the example just below:\n\n\n```bash\n%%bash\njupyter nbconvert --to html_toc JupExtensions_talk.ipynb\nxdg-open JupExtensions_talk.html\n```\n\n### Python markdown\n\nAn extension by @juhasch which enables to include variable values in the markdown code. \n\n**!** -- **Needs the notebook to be *trusted***\n\n\n```python\nimport numpy as np\nnp.random.seed(55)\na = np.random.randn(3)\na\n```\n\n\n\n\n    array([-1.62373111, -0.10178393, -1.8097911 ])\n\n\n\n\n```javascript\n%%javascript\nJupyter.utils.load_extensions('python-markdown/main')\n```\n\n\n```python\nx=3\n```\n\n\n`variable x is {{ x }}`\nvariable x is {{ x }}\n\nThis is a markdown **text cell** with the value of a variable, {{a[1]}} inserted in it. \n\n### latex_envs\n\nThe `latex_envs` extension enables\n\n- to use many familiar $\\LaTeX$ structures in the notebook; \n- export all that (in $\\LaTeX$ and html) \n- and enables to copy and paste from $\\LaTeX$ documents, \n\n\n\n[documentation](http://localhost:8888/notebooks/JFB/JupNbextensions_talk/latex_env_doc.ipynb) and demo. \n\n**Internals/Highlights** \n\nMany things, but let us point out\n\n- `latex_envs` menu\n- toolbar\n- read user configuration/extension from json files\n- store configuration in notebook's metadata\n\n\n**Exporting** \n\n- template `latex_envs.tpl`\n- an entry point \n\n```\njupyter nbconvert --to html_with_lenvs FILE.ipynb\n```\nIt should be noted that the rendering is done exactly in the same way as in the livenotebook. Actually, it is the very same javascript which is run in the html file, as for the `toc2` nbextension.\n\n[The exporter](http://localhost:8888/edit/latex_envs.py)\n\n\\begin{theorem}\\label{theo:one}\nThis is a first theorem\n\\end{theorem}\n\n\\begin{theorem}\\label{theo:two}\nAnd a second one\n\\end{theorem}\n\n\\begin{exercise}\\label{exo:exo1}\nAnd an exercise\n\\end{exercise}\n\nWith a reference to theo:one \\ref{theo:one} and another to theo:two \\ref{theo:two}\n\n### nbTranslate\n\n\n[documentation](http://localhost:8888/nbextensions/nbextensions_configurator/rendermd/nbextensions/nbTranslate/README.md) and demo\n\n\nSource:\n\n- [main](http://localhost:8888/nbextensions/nbTranslate/main.js);\n- [nbTranslate](http://localhost:8888/nbextensions/nbTranslate/nbTranslate.js)\n\n\n```javascript\n%%javascript\nJupyter.utils.load_extensions('nbTranslate/main')\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\nA small text with an equation in it, an why not, a\ndefinition\n\\begin{definition}\nSomething on $x_k$ for $k>0$\n\\end{definition}\n\nMala tekst jednad\u017eba u njemu, \u0161to je za\u0161to ne, a\ndefinicija\n\\begin{definition}\nNe\u0161to o $x_k$ za $k>0$\n\\end{definition}\n\nUn petit texte avec une \u00e9quation, et pourquoi pas, un\nd\u00e9finition\n\\begin{definition}\nQuelque chose sur $x_k$ pour $k>0$\n\\end{definition}\n\n**Internals/Highlights** \n\nMany things, but let us point out\n\n- `Langs` menu\n- configuration toolbar\n- Request to a web service (google translate) \n- configuration stored in notebook's metadata (langs in notebook)\n\n\n**Exporting** \n\nIt is possible to extract one language from the multilanguage notebook. \nAn exporter with an entry-point selectLanguage is provided that converts the notebook into another one as follows\n```\njupyter nbconvert --to selectLanguage --NotebookLangExporter.language=lang  FILE.ipynb\n```\n\n### Some other nice extensions\n\nBy @jcb91\n\n- [jupyter_highlight_selected_word](https://github.com/jcb91/jupyter_highlight_selected_word),\n- [collapsible headings](http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/collapsible_headings/readme.html),\n\n## Code developpement\n\n- code developpement: [code_prettify](http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/code_prettify/README_code_prettify.html) (code formatter via yapf or auto PEP8), [2to3](http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/code_prettify/README_2to3.html)  (python converter),\n[hinterland](http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/hinterland/README.html),\n[runtools](http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/runtools/readme.html), [codefolding](http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/codefolding/readme.html), [varinspector](http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/varInspector/README.html) (variable inspector), \n     \n\n### Code_prettify / 2to3 / autopep8\n\n**A bit of history**\n\nOriginally, a request was sent on `jupyter_contrib_nbextensions` for using YAPF for Python code formatting. \nThis was done using a simple strategy [yapf_ext](http://localhost:8888/files/README_yapf_ext.md) / [source](http://localhost:8888/files/yapf_ext.js)\n \n\n- read the cell content\n- transform it using a call to the python kernel\n\nThis was rapidly extended to recognize the running kernel and reformat accordingly (using ` formatR` and `jsbeautify`) under the name [code_prettify](http://localhost:8888/nbextensions/nbextensions_configurator/rendermd/nbextensions/code_prettify/README_code_prettify.md). \n\nAnother request on `jupyter_contrib_nbextensions` was sent for a 2to3 conversion. The architecture for the extension is the same. With @jcb91, we developped a general library for that: [KerneExecOnCells library](http://localhost:8888/nbextensions/nbextensions_configurator/rendermd/nbextensions/code_prettify/README.md). A [2to3](http://localhost:8888/nbextensions/nbextensions_configurator/rendermd/nbextensions/code_prettify/README_2to3.md) plugin was defined, as well as a [autopep8](http://localhost:8888/nbextensions/nbextensions_configurator/rendermd/nbextensions/code_prettify/README_autopep8.md) reformatter plugin. \n\n\n[Source for code_prettify as a plugin](http://localhost:8888/nbextensions/code_prettify/code_prettify.js)\n\n\n### Some other nice extensions\n\n- [hinterland](http://localhost:8888/nbextensions/nbextensions_configurator/rendermd/nbextensions/hinterland/README.md) by @jcb91\n- [runtools](http://localhost:8888/nbextensions/nbextensions_configurator/rendermd/nbextensions/runtools/readme.md) by @juhasch  \n- [codefolding](http://localhost:8888/nbextensions/nbextensions_configurator/rendermd/nbextensions/codefolding/readme.md),\n- [codefolding](http://localhost:8888/nbextensions/nbextensions_configurator/rendermd/nbextensions/codefolding/readme.md)\n- [ExecuteTime](http://localhost:8888/nbextensions/nbextensions_configurator/rendermd/nbextensions/execute_time/readme.md)\n\n\n```python\n# demo for hinterland\n\n```\n\n### Variable inspector\n\nA request on `jupyter_contrib_nbextensions` asked for a variable inspector like in some commercial packages as well as in RStudio. A small googling provided [some hints](https://github.com/jupyter-widgets/ipywidgets/blob/ffa094e061c899292036049b00ff93e46e8b4691/docs/source/examples/Variable%20Inspector.ipynb) from ipywidgets. \n\nThen the extension was built using lot of code from toc2 and the same approach as in `code-prettify`, that is call the kernel with some provided code and catch the result.\n\n\n[varInspector documentation](http://localhost:8888/nbextensions/nbextensions_configurator/rendermd/nbextensions/varInspector/README.md)\n\n[source code](http://localhost:8888/nbextensions/varInspector/main.js);\n\n[kernel code](http://localhost:8888/nbextensions/varInspector/var_list.py);\n\n**events**\n```\n // event: on cell execution, update the list of variables \n            events.on('execute.CodeCell', varRefresh);\n            events.on('varRefresh', varRefresh);\n   \n // on variable deletion   \n Jupyter.notebook.events.trigger('varRefresh')           \n```\n\n\n```python\nw = \"A long string \"\n```\n\n# Miscellaneous\n\n- **Building a nbextension package** Actually a python package, embedding the javascript files, the templates, and defining entry points. See [jupyter_highlight_selected_word](https://github.com/jcb91/jupyter_highlight_selected_word) or [jupyter_latex_envs](https://github.com/jfbercher/jupyter_latex_envs) for examples.\n- **Installing the [jupyter_contrib_nbextensions](https://github.com/ipython-contrib/jupyter_contrib_nbextensions)** See instructions on the repo.\n- **This document** will be available shortly, say before next week, on  https://github.com/jfbercher\n", "meta": {"hexsha": "e5088af8ec79433993eaaabf0ec6c5a681a09487", "size": 38179, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "JupExtensions_talk.ipynb", "max_stars_repo_name": "jfbercher/pyParis2017", "max_stars_repo_head_hexsha": "3209719be0caf323d81e37e971536507dccf3c05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "JupExtensions_talk.ipynb", "max_issues_repo_name": "jfbercher/pyParis2017", "max_issues_repo_head_hexsha": "3209719be0caf323d81e37e971536507dccf3c05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JupExtensions_talk.ipynb", "max_forks_repo_name": "jfbercher/pyParis2017", "max_forks_repo_head_hexsha": "3209719be0caf323d81e37e971536507dccf3c05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-03-13T01:27:44.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-13T01:27:44.000Z", "avg_line_length": 32.0562552477, "max_line_length": 837, "alphanum_fraction": 0.6147882344, "converted": true, "num_tokens": 5785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814056074291439, "lm_q2_score": 0.14223189682786758, "lm_q1q2_score": 0.0400248533226454}}
{"text": "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Evaluating-Imbalanced-Datasets\" data-toc-modified-id=\"Evaluating-Imbalanced-Datasets-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Evaluating Imbalanced Datasets</a></span><ul class=\"toc-item\"><li><span><a href=\"#Dataset\" data-toc-modified-id=\"Dataset-1.1\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;</span>Dataset</a></span></li><li><span><a href=\"#Class-Weighting\" data-toc-modified-id=\"Class-Weighting-1.2\"><span class=\"toc-item-num\">1.2&nbsp;&nbsp;</span>Class Weighting</a></span></li><li><span><a href=\"#F1-Score\" data-toc-modified-id=\"F1-Score-1.3\"><span class=\"toc-item-num\">1.3&nbsp;&nbsp;</span>F1 Score</a></span></li><li><span><a href=\"#Conclusion\" data-toc-modified-id=\"Conclusion-1.4\"><span class=\"toc-item-num\">1.4&nbsp;&nbsp;</span>Conclusion</a></span></li></ul></li><li><span><a href=\"#Reference\" data-toc-modified-id=\"Reference-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Reference</a></span></li></ul></div>\n\n\n```python\n# code for loading the format for the notebook\nimport os\n\n# path : store the current path to convert back to it later\npath = os.getcwd()\nos.chdir(os.path.join('..', '..', 'notebook_format'))\nfrom formats import load_style\nload_style(plot_style = False)\n```\n\n\n\n\n<style>\n@import url('http://fonts.googleapis.com/css?family=Source+Code+Pro');\n@import url('http://fonts.googleapis.com/css?family=Vollkorn');\n@import url('http://fonts.googleapis.com/css?family=Arimo');\n@import url('http://fonts.googleapis.com/css?family=Fira_sans');\n\n    div.cell {\n        width: 1000px;\n        margin-left: 0% !important;\n        margin-right: auto;\n    }\n    div.text_cell code {\n        background: transparent;\n        color: #000000;\n        font-weight: 600;\n        font-size: 12pt;\n        font-style: bold;\n        font-family:  'Source Code Pro', Consolas, monocco, monospace;\n    }\n    h1 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n\t}\n\n    div.input_area {\n        background: #F6F6F9;\n        border: 1px solid #586e75;\n    }\n\n    .text_cell_render h1 {\n        font-weight: 200;\n        font-size: 30pt;\n        line-height: 100%;\n        color:#c76c0c;\n        margin-bottom: 0.5em;\n        margin-top: 1em;\n        display: block;\n        white-space: wrap;\n        text-align: left;\n    } \n    h2 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n        text-align: left;\n    }\n    .text_cell_render h2 {\n        font-weight: 200;\n        font-size: 16pt;\n        font-style: italic;\n        line-height: 100%;\n        color:#c76c0c;\n        margin-bottom: 0.5em;\n        margin-top: 1.5em;\n        display: block;\n        white-space: wrap;\n        text-align: left;\n    } \n    h3 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n    }\n    .text_cell_render h3 {\n        font-weight: 200;\n        font-size: 14pt;\n        line-height: 100%;\n        color:#d77c0c;\n        margin-bottom: 0.5em;\n        margin-top: 2em;\n        display: block;\n        white-space: wrap;\n        text-align: left;\n    }\n    h4 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n    }\n    .text_cell_render h4 {\n        font-weight: 100;\n        font-size: 14pt;\n        color:#d77c0c;\n        margin-bottom: 0.5em;\n        margin-top: 0.5em;\n        display: block;\n        white-space: nowrap;\n    }\n    h5 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n    }\n    .text_cell_render h5 {\n        font-weight: 200;\n        font-style: normal;\n        color: #1d3b84;\n        font-size: 16pt;\n        margin-bottom: 0em;\n        margin-top: 0.5em;\n        display: block;\n        white-space: nowrap;\n    }\n    div.text_cell_render{\n        font-family: 'Fira sans', verdana,arial,sans-serif;\n        line-height: 125%;\n        font-size: 115%;\n        text-align:justify;\n        text-justify:inter-word;\n    }\n    div.output_wrapper{\n        margin-top:0.2em;\n        margin-bottom:0.2em;\n    }\n\n    code{\n      font-size: 70%;\n    }\n    .rendered_html code{\n    background-color: transparent;\n    }\n    ul{\n        margin: 2em;\n    }\n    ul li{\n        padding-left: 0.5em; \n        margin-bottom: 0.5em; \n        margin-top: 0.5em; \n    }\n    ul li li{\n        padding-left: 0.2em; \n        margin-bottom: 0.2em; \n        margin-top: 0.2em; \n    }\n    ol{\n        margin: 2em;\n    }\n    ol li{\n        padding-left: 0.5em; \n        margin-bottom: 0.5em; \n        margin-top: 0.5em; \n    }\n    ul li{\n        padding-left: 0.5em; \n        margin-bottom: 0.5em; \n        margin-top: 0.2em; \n    }\n    a:link{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:visited{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:hover{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:focus{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:active{\n       font-weight: bold;\n       color:#447adb;\n    }\n    .rendered_html :link {\n       text-decoration: underline; \n    }\n    .rendered_html :hover {\n       text-decoration: none; \n    }\n    .rendered_html :visited {\n      text-decoration: none;\n    }\n    .rendered_html :focus {\n      text-decoration: none;\n    }\n    .rendered_html :active {\n      text-decoration: none;\n    }\n    .warning{\n        color: rgb( 240, 20, 20 )\n    } \n    hr {\n      color: #f3f3f3;\n      background-color: #f3f3f3;\n      height: 1px;\n    }\n    blockquote{\n      display:block;\n      background: #fcfcfc;\n      border-left: 5px solid #c76c0c;\n      font-family: 'Open sans',verdana,arial,sans-serif;\n      width:680px;\n      padding: 10px 10px 10px 10px;\n      text-align:justify;\n      text-justify:inter-word;\n      }\n      blockquote p {\n        margin-bottom: 0;\n        line-height: 125%;\n        font-size: 100%;\n      }\n</style>\n\n\n\n\n\n\n```python\nos.chdir(path)\n\n# 1. magic for inline plot\n# 2. magic to print version\n# 3. magic so that the notebook will reload external python modules\n# 4. magic to enable retina (high resolution) plots\n# https://gist.github.com/minrk/3301035\n%matplotlib inline\n%load_ext watermark\n%load_ext autoreload\n%autoreload 2\n%config InlineBackend.figure_format = 'retina'\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import precision_recall_curve, roc_curve\nfrom sklearn.metrics import precision_score, recall_score, f1_score\n\n%watermark -a 'Ethen' -d -t -v -p numpy,pandas,sklearn,matplotlib\n```\n\n    Ethen 2018-06-16 11:54:30 \n    \n    CPython 3.6.4\n    IPython 6.4.0\n    \n    numpy 1.14.4\n    pandas 0.23.0\n    sklearn 0.19.1\n    matplotlib 2.2.2\n\n\n# Evaluating Imbalanced Datasets\n\nThis documentation illustrates the trade off between True Positive Rate and False Positive Rate using ROC and Precision/Recall (PR) curves. In the end, we will take a look at why, for binary classification problem, apart from solely using the popular evaluation metric ROC curve we should also look at other evaluation metric such as precision and recall especially when working with highly imbalanced dataset.\n\n## Dataset\n\nThe dataset we'll be using today can be downloaded from the [Kaggle website](https://www.kaggle.com/mlg-ulb/creditcardfraud).\n\n\n```python\nfilepath = os.path.join('data', 'creditcard.csv')\ndf = pd.read_csv(filepath)\nprint('dimension: ', df.shape)\ndf.head()\n```\n\n    dimension:  (284807, 31)\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Time</th>\n      <th>V1</th>\n      <th>V2</th>\n      <th>V3</th>\n      <th>V4</th>\n      <th>V5</th>\n      <th>V6</th>\n      <th>V7</th>\n      <th>V8</th>\n      <th>V9</th>\n      <th>...</th>\n      <th>V21</th>\n      <th>V22</th>\n      <th>V23</th>\n      <th>V24</th>\n      <th>V25</th>\n      <th>V26</th>\n      <th>V27</th>\n      <th>V28</th>\n      <th>Amount</th>\n      <th>Class</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.0</td>\n      <td>-1.359807</td>\n      <td>-0.072781</td>\n      <td>2.536347</td>\n      <td>1.378155</td>\n      <td>-0.338321</td>\n      <td>0.462388</td>\n      <td>0.239599</td>\n      <td>0.098698</td>\n      <td>0.363787</td>\n      <td>...</td>\n      <td>-0.018307</td>\n      <td>0.277838</td>\n      <td>-0.110474</td>\n      <td>0.066928</td>\n      <td>0.128539</td>\n      <td>-0.189115</td>\n      <td>0.133558</td>\n      <td>-0.021053</td>\n      <td>149.62</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.0</td>\n      <td>1.191857</td>\n      <td>0.266151</td>\n      <td>0.166480</td>\n      <td>0.448154</td>\n      <td>0.060018</td>\n      <td>-0.082361</td>\n      <td>-0.078803</td>\n      <td>0.085102</td>\n      <td>-0.255425</td>\n      <td>...</td>\n      <td>-0.225775</td>\n      <td>-0.638672</td>\n      <td>0.101288</td>\n      <td>-0.339846</td>\n      <td>0.167170</td>\n      <td>0.125895</td>\n      <td>-0.008983</td>\n      <td>0.014724</td>\n      <td>2.69</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1.0</td>\n      <td>-1.358354</td>\n      <td>-1.340163</td>\n      <td>1.773209</td>\n      <td>0.379780</td>\n      <td>-0.503198</td>\n      <td>1.800499</td>\n      <td>0.791461</td>\n      <td>0.247676</td>\n      <td>-1.514654</td>\n      <td>...</td>\n      <td>0.247998</td>\n      <td>0.771679</td>\n      <td>0.909412</td>\n      <td>-0.689281</td>\n      <td>-0.327642</td>\n      <td>-0.139097</td>\n      <td>-0.055353</td>\n      <td>-0.059752</td>\n      <td>378.66</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1.0</td>\n      <td>-0.966272</td>\n      <td>-0.185226</td>\n      <td>1.792993</td>\n      <td>-0.863291</td>\n      <td>-0.010309</td>\n      <td>1.247203</td>\n      <td>0.237609</td>\n      <td>0.377436</td>\n      <td>-1.387024</td>\n      <td>...</td>\n      <td>-0.108300</td>\n      <td>0.005274</td>\n      <td>-0.190321</td>\n      <td>-1.175575</td>\n      <td>0.647376</td>\n      <td>-0.221929</td>\n      <td>0.062723</td>\n      <td>0.061458</td>\n      <td>123.50</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>2.0</td>\n      <td>-1.158233</td>\n      <td>0.877737</td>\n      <td>1.548718</td>\n      <td>0.403034</td>\n      <td>-0.407193</td>\n      <td>0.095921</td>\n      <td>0.592941</td>\n      <td>-0.270533</td>\n      <td>0.817739</td>\n      <td>...</td>\n      <td>-0.009431</td>\n      <td>0.798278</td>\n      <td>-0.137458</td>\n      <td>0.141267</td>\n      <td>-0.206010</td>\n      <td>0.502292</td>\n      <td>0.219422</td>\n      <td>0.215153</td>\n      <td>69.99</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 31 columns</p>\n</div>\n\n\n\nA brief description of the dataset based on the data overview section from the download source.\n\n> The datasets contains transactions made by credit cards in September 2013 by european cardholders. This dataset presents transactions that occurred in two days, where we have 492 frauds out of 284,807 transactions.\n> Unfortunately, due to confidentiality issues, we cannot provide the original features and more background information about the data. Features V1, V2, ... V28 are the principal components obtained with PCA, the only features which have not been transformed with PCA are 'Time' and 'Amount'. Feature 'Time' contains the seconds elapsed between each transaction and the first transaction in the dataset. The feature 'Amount' is the transaction amount. Feature 'Class' is the response variable and it takes value 1 in case of fraud and 0 otherwise.\n\nThe only feature-engineering that we'll be doing for now is to convert the feature \"Time\" (seconds from which the very first data observation took place) to hours of a day. While we're at it, let's take a look at a breakdown of our legit vs fraud transactions via a pivot table and a plot of fraud transactions' count over time for a quick exploratory data analysis.\n\n\n```python\ndf['hour'] = np.ceil(df['Time'].values / 3600) % 24\nfraud_over_hour = df.pivot_table(values = 'Amount', index = 'hour', columns = 'Class', aggfunc = 'count')\nfraud_over_hour\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Class</th>\n      <th>0</th>\n      <th>1</th>\n    </tr>\n    <tr>\n      <th>hour</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0.0</th>\n      <td>10919</td>\n      <td>21</td>\n    </tr>\n    <tr>\n      <th>1.0</th>\n      <td>7687</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>2.0</th>\n      <td>4212</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>3.0</th>\n      <td>3269</td>\n      <td>57</td>\n    </tr>\n    <tr>\n      <th>4.0</th>\n      <td>3476</td>\n      <td>17</td>\n    </tr>\n    <tr>\n      <th>5.0</th>\n      <td>2185</td>\n      <td>23</td>\n    </tr>\n    <tr>\n      <th>6.0</th>\n      <td>2979</td>\n      <td>11</td>\n    </tr>\n    <tr>\n      <th>7.0</th>\n      <td>4093</td>\n      <td>9</td>\n    </tr>\n    <tr>\n      <th>8.0</th>\n      <td>7219</td>\n      <td>23</td>\n    </tr>\n    <tr>\n      <th>9.0</th>\n      <td>10266</td>\n      <td>9</td>\n    </tr>\n    <tr>\n      <th>10.0</th>\n      <td>15824</td>\n      <td>16</td>\n    </tr>\n    <tr>\n      <th>11.0</th>\n      <td>16593</td>\n      <td>8</td>\n    </tr>\n    <tr>\n      <th>12.0</th>\n      <td>16804</td>\n      <td>53</td>\n    </tr>\n    <tr>\n      <th>13.0</th>\n      <td>15400</td>\n      <td>17</td>\n    </tr>\n    <tr>\n      <th>14.0</th>\n      <td>15350</td>\n      <td>17</td>\n    </tr>\n    <tr>\n      <th>15.0</th>\n      <td>16545</td>\n      <td>23</td>\n    </tr>\n    <tr>\n      <th>16.0</th>\n      <td>16434</td>\n      <td>26</td>\n    </tr>\n    <tr>\n      <th>17.0</th>\n      <td>16435</td>\n      <td>22</td>\n    </tr>\n    <tr>\n      <th>18.0</th>\n      <td>16135</td>\n      <td>29</td>\n    </tr>\n    <tr>\n      <th>19.0</th>\n      <td>17003</td>\n      <td>33</td>\n    </tr>\n    <tr>\n      <th>20.0</th>\n      <td>15632</td>\n      <td>19</td>\n    </tr>\n    <tr>\n      <th>21.0</th>\n      <td>16739</td>\n      <td>18</td>\n    </tr>\n    <tr>\n      <th>22.0</th>\n      <td>17692</td>\n      <td>16</td>\n    </tr>\n    <tr>\n      <th>23.0</th>\n      <td>15424</td>\n      <td>9</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nplt.rcParams['font.size'] = 12\nplt.rcParams['figure.figsize'] = 8, 6\n\n\nplt.plot(fraud_over_hour.index, fraud_over_hour[1])\nplt.title('Fraudulent Transaction over Hour')\nplt.ylabel('Fraudulent Count')\nplt.xlabel('Hour')\nplt.show()\n```\n\n\n```python\n# prepare the dataset for modeling;\n# extract the features and labels, perform a quick train/test split\nlabel = df['Class']\npca_cols = [col for col in df.columns if col.startswith('V')]\ninput_cols = ['hour', 'Amount'] + pca_cols\ndf = df[input_cols]\n\ndf_train, df_test, y_train, y_test = train_test_split(\n    df, label, stratify = label, test_size = 0.35, random_state = 1)\n\nprint('training data dimension:', df_train.shape)\ndf_train.head()\n```\n\n    training data dimension: (185124, 30)\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>hour</th>\n      <th>Amount</th>\n      <th>V1</th>\n      <th>V2</th>\n      <th>V3</th>\n      <th>V4</th>\n      <th>V5</th>\n      <th>V6</th>\n      <th>V7</th>\n      <th>V8</th>\n      <th>...</th>\n      <th>V19</th>\n      <th>V20</th>\n      <th>V21</th>\n      <th>V22</th>\n      <th>V23</th>\n      <th>V24</th>\n      <th>V25</th>\n      <th>V26</th>\n      <th>V27</th>\n      <th>V28</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>183716</th>\n      <td>11.0</td>\n      <td>0.76</td>\n      <td>2.089242</td>\n      <td>0.629632</td>\n      <td>-3.364200</td>\n      <td>0.489395</td>\n      <td>1.553483</td>\n      <td>-0.986382</td>\n      <td>0.698731</td>\n      <td>-0.284807</td>\n      <td>...</td>\n      <td>0.084549</td>\n      <td>-0.107484</td>\n      <td>-0.041904</td>\n      <td>0.058986</td>\n      <td>-0.103786</td>\n      <td>0.050964</td>\n      <td>0.416364</td>\n      <td>0.694420</td>\n      <td>-0.082845</td>\n      <td>-0.028126</td>\n    </tr>\n    <tr>\n      <th>145898</th>\n      <td>1.0</td>\n      <td>0.49</td>\n      <td>-0.914450</td>\n      <td>2.361973</td>\n      <td>0.335526</td>\n      <td>4.114377</td>\n      <td>0.557196</td>\n      <td>0.874183</td>\n      <td>0.332492</td>\n      <td>0.540016</td>\n      <td>...</td>\n      <td>1.614699</td>\n      <td>0.352808</td>\n      <td>-0.159933</td>\n      <td>-0.261357</td>\n      <td>0.186308</td>\n      <td>0.718244</td>\n      <td>-0.911284</td>\n      <td>-0.093219</td>\n      <td>-0.282263</td>\n      <td>-0.229368</td>\n    </tr>\n    <tr>\n      <th>247003</th>\n      <td>19.0</td>\n      <td>2.69</td>\n      <td>2.070918</td>\n      <td>-0.062049</td>\n      <td>-1.128898</td>\n      <td>0.383220</td>\n      <td>-0.079241</td>\n      <td>-1.130912</td>\n      <td>0.177956</td>\n      <td>-0.321792</td>\n      <td>...</td>\n      <td>0.201919</td>\n      <td>-0.222333</td>\n      <td>-0.299237</td>\n      <td>-0.732516</td>\n      <td>0.322038</td>\n      <td>-0.112259</td>\n      <td>-0.281414</td>\n      <td>0.205225</td>\n      <td>-0.071557</td>\n      <td>-0.061429</td>\n    </tr>\n    <tr>\n      <th>56024</th>\n      <td>14.0</td>\n      <td>159.95</td>\n      <td>0.929003</td>\n      <td>-0.262584</td>\n      <td>-0.026089</td>\n      <td>0.596927</td>\n      <td>-0.469012</td>\n      <td>-1.022218</td>\n      <td>0.463968</td>\n      <td>-0.176288</td>\n      <td>...</td>\n      <td>0.278433</td>\n      <td>0.152181</td>\n      <td>-0.236715</td>\n      <td>-1.149710</td>\n      <td>0.035834</td>\n      <td>0.504788</td>\n      <td>0.139781</td>\n      <td>0.095334</td>\n      <td>-0.102652</td>\n      <td>0.025986</td>\n    </tr>\n    <tr>\n      <th>217153</th>\n      <td>16.0</td>\n      <td>44.22</td>\n      <td>1.831384</td>\n      <td>-0.814800</td>\n      <td>-0.727692</td>\n      <td>-0.075094</td>\n      <td>0.028202</td>\n      <td>1.380668</td>\n      <td>-0.941283</td>\n      <td>0.502667</td>\n      <td>...</td>\n      <td>-1.051171</td>\n      <td>-0.240155</td>\n      <td>0.242974</td>\n      <td>0.905053</td>\n      <td>0.189693</td>\n      <td>-0.540499</td>\n      <td>-0.358400</td>\n      <td>0.202675</td>\n      <td>0.048368</td>\n      <td>-0.044683</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 30 columns</p>\n</div>\n\n\n\n\n```python\n# we'll be using linear models later, hence\n# we standardize our features to ensure they are\n# all at the same scale\nstandardize = StandardScaler()\nX_train = standardize.fit_transform(df_train)\nX_test = standardize.transform(df_test)\n\nlabel_distribution = np.bincount(label) / label.size\nprint('labels distribution:', label_distribution)\nprint('Fraud is {}% of our data'.format(label_distribution[1] * 100))\n```\n\n    labels distribution: [0.99827251 0.00172749]\n    Fraud is 0.1727485630620034% of our data\n\n\n## Class Weighting\n\nWith scikit-learn, we can give higher weights to the minority class (the model will be penalized more when misclassifying a minority class) by modifying the `class_weight` argument during model initialization. Let's see what affect will this have with our model. The following code chunk manually selects a range of weights to boost the minority class and tracks various metrics to see the model's performance across different class weighting values.\n\nNote that the following section assumes knowledge of model performance metric such as precision, recall and AUC. The following link contains resources into those concepts if needed. [Notebook: AUC (Area under the ROC curve and precision/recall curve) from scratch](http://nbviewer.jupyter.org/github/ethen8181/machine-learning/blob/master/model_selection/auc/auc.ipynb)\n\n\n```python\nfig = plt.figure(figsize = (15, 8))\nax1 = fig.add_subplot(1, 2, 1)\nax1.set_xlim([-0.05, 1.05])\nax1.set_ylim([-0.05, 1.05])\nax1.set_xlabel('Recall')\nax1.set_ylabel('Precision')\nax1.set_title('PR Curve')\n\nax2 = fig.add_subplot(1, 2, 2)\nax2.set_xlim([-0.05, 1.05])\nax2.set_ylim([-0.05, 1.05])\nax2.set_xlabel('False Positive Rate')\nax2.set_ylabel('True Positive Rate')\nax2.set_title('ROC Curve')\n\nf1_scores = []\nrecall_scores = []\nprecision_scores = []\npos_weights = [1, 10, 25, 50, 100, 10000]\nfor pos_weight in pos_weights:\n    lr_model = LogisticRegression(class_weight = {0: 1, 1: pos_weight})\n    lr_model.fit(X_train, y_train)\n\n    # plot the precision-recall curve and AUC curve\n    pred_prob = lr_model.predict_proba(X_test)[:, 1]\n    precision, recall, _ = precision_recall_curve(y_test, pred_prob)\n    tpr, fpr, _ = roc_curve(y_test, pred_prob)\n\n    ax1.plot(recall, precision, label = pos_weight)\n    ax2.plot(tpr, fpr, label = pos_weight)\n\n    # track the precision, recall and f1 score\n    pred = lr_model.predict(X_test)\n    f1_test = f1_score(y_test, pred)\n    recall_test = recall_score(y_test, pred)\n    precision_test = precision_score(y_test, pred)\n    f1_scores.append(f1_test)\n    recall_scores.append(recall_test)\n    precision_scores.append(precision_test)\n\nax1.legend(loc = 'lower left')    \nax2.legend(loc = 'lower right')\n\nplt.show()\n```\n\nA good classifier would have a PR (Precision/Recall) curve closer to the upper-right corner and a ROC curve to the upper-left corner. Based on the plot above, we can see that while both curves uses the same underlying data, i.e. the real class labels and the predicted probability, the two charts can tell different stories, with some weights seem to perform better based on the ROC curve's chart.\n\nTo be explicit, different settings of the `class_weight` argument all seem to perform pretty well for ROC curve, but some poorly for PR curve. This is due to the fact that for ROC curve, one of the axis shows the false positive rate (number of false positives / total number of negatives), and this ratio will change much when the total number of negatives is large. Whereas for PR curve, one of the axis, precision (number of true positives / total number of predicted positives), is less affected by this.\n\nAnother way to visualize the model's performance metric is to use a bar-plot to visualize the precision/recall/f1 score at different class weighting values.\n\n\n```python\ndef score_barplot(precision_scores, recall_scores, f1_scores, pos_weights, figsize = (8, 6)):\n    \"\"\"Visualize precision/recall/f1 score at different class weighting values.\"\"\"\n    width = 0.3\n    ind = np.arange(len(precision_scores))      \n    fig = plt.figure(figsize = figsize)\n    ax = fig.add_subplot(111)\n    b1 = ax.bar(ind, precision_scores, width, color = 'lightskyblue')\n    b2 = ax.bar(ind + width, recall_scores, width, color = 'lightcoral')\n    b3 = ax.bar(ind + (2 * width), f1_scores, width, color = 'gold')\n\n    ax.set_xticks(ind + width)\n    ax.set_xticklabels(pos_weights)\n    ax.set_ylabel('score')\n    ax.set_xlabel('positive weights')\n    ax.set_ylim(0, 1.3)\n    ax.legend(handles = [b1, b2, b3], labels = ['precision', 'recall', 'f1'])\n    plt.tight_layout()\n    plt.show()\n\n\nscore_barplot(precision_scores, recall_scores, f1_scores, pos_weights)\n```\n\nJudging from the plot above, the can see that when the weight's value is set at 10, we seem to have strike a good balance between precision and recall (this setting has the highest f1 score, we'll have a deeper discussion on f1 score in the next section), where our model can detect 80% of the fraudulent transaction, while not annoying a bunch of customers with false positives. Another observation is that if we were to set the class weighting value to 10,000 we would be able to increase our recall score at the expense of more mis-classified legit cases (as depicted by the low precision score).\n\n\n```python\n# this code chunk shows the same idea applies when using tree-based models\nf1_scores = []\nrecall_scores = []\nprecision_scores = []\npos_weights = [1, 10, 100, 10000]\nfor pos_weight in pos_weights:\n    rf_model = RandomForestClassifier(n_estimators = 50, max_depth = 6, n_jobs = -1,\n                                      class_weight = {0: 1, 1: pos_weight})\n    rf_model.fit(df_train, y_train)\n\n    # track the precision, recall and f1 score\n    pred = rf_model.predict(df_test)\n    f1_test = f1_score(y_test, pred)\n    recall_test = recall_score(y_test, pred)\n    precision_test = precision_score(y_test, pred)\n    f1_scores.append(f1_test)\n    recall_scores.append(recall_test)\n    precision_scores.append(precision_test)\n\nscore_barplot(precision_scores, recall_scores, f1_scores, pos_weights)\n```\n\n## F1 Score\n\nThe formula for F1 score is:\n\n\\begin{align}\nF1 &= 2 * \\frac{\\text{precision} * \\text{recall}}{\\text{precision} + \\text{recall}}\n\\end{align}\n\nF1 score can be interpreted as a weighted average or harmonic mean of precision and recall, where the relative contribution of precision and recall to the F1 score are equal. F1 score reaches its best value at 1 and worst score at 0.\n\nWhen we create a classifier, often times we need to make a compromise between the recall and precision, it is kind of hard to compare a model with high recall and low precision versus a model with high precision but low recall. F1 score merge these two metrics into a single measure that we can use to compare two models. This is not to say that a model with higher F1 score is always better as it depends on the use case, more on this in the conclusion section.\n\nTo understand the rationale behind harmonic means, let's digress from machine learning evaluation metrics and take a look at a canonical example of using harmonic means. Consider a trip to the grocery store & back:\n\n- On the way there we drove 30 mph the entire way.\n- On the way back traffic was crawling, so we instead drove 10 mph the entire way.\n- We took the same route and covered the same amount of ground (5 miles) each way.\n\nWhat was our average speed across this entire trip's duration? When prompted to calculate the average of something, we might naively turn to arithmetic mean to 30 mph and 10 mph and proudly declare that the average speed for the whole trip was 20 mph. But if we step back and think about it for a moment, we'll realize that because we traveled faster on our way there, we covered the 5 miles quicker & spent less time overall traveling at that speed, thus our average speed across our entire trip should be closer to 10 mph because we spent longer traveling at that speed. In order to calculate the arithmetic mean correctly here, we have to first calculate the amount of time spent traveling at each rate, then weight our mean calculation accordingly.\n\n- Trip There: (at 30 mph)\n    - 30 miles per 60 minutes = 1 mile every 2 minutes = 1/2 mile every minute\n    - 5 miles at 1/2 mile per minute = 5 / 1/2 = 10 minutes\n    - Trip There time = 10 minutes\n- Trip Back: (at 10 mph)\n    - 10 miles per 60 minutes = 1 mile every 6 minutes = 1/6 miles every minute\n    - 5 miles at 1/6 mile per minute = 5 / 1/6 = 30 minutes\n    - Trip Back time = 30 minutes\n- Total trip time = 10 + 30 = 40 minutes\n    - Trip there / total trip = 10 / 40 minutes = .25\n    - Trip back / total trip = 30 / 40 minutes = .75\n- Weighted Arithmetic Mean = (30 mph x .25) + (10 mph x .75) = 7.5 + 7.5 = 15 \n\nWe now get an average speed of 15 mph, which matches the intuition that the number should be lower than our unweighted arithmetic mean of 20 mph. Now let's look at the same problem from a harmonic mean perspective. The harmonic mean can be described in words as: the reciprocal of the arithmetic mean of the reciprocals of the dataset. That's a lot of reciprocal flips there ..., the notation for the computation is:\n\n\\begin{align}\n\\text{Harmonic mean} &= \\big( \\frac{\\sum_{i=1}^n x_i^{-1}}{n} \\big)^{-1}\n\\end{align}\n\nNow back our original example, the harmonic mean of 30 mph and 10 mph:\n\n- Arithmetic mean of reciprocals = 1/30 + 1/10 = 4/30 / 2 = 4/60 = 1/15\n- Reciprocal of arithmetic mean = 1 / 1/15 = 15/1 = 15\n\nOur true average rate of travel, automagically adjusted for time spent traveling in each direction = 15 mph! In this example, using harmonic mean helps us find relationship with datasets of rates/ratios/fractions over different length/periods. By using reciprocals, it already accounts for the proportion of time that was implicit in the rates.\n\nWith this knowledge in mind, let's turn our heads back to F1 score's calculation. Precision and recall both have true positives in the numerator, but they have different denominators. In order for an average to be valid, we need the values to be in the same scaled units. In our traveling distance example miles per hour need to be compared over the same number of hours. Thus, to take the average of precision and recall really only makes sense to average their reciprocals (adjusts for scale), thus the harmonic mean.\n\n## Conclusion\n\nTo sum it up, when using model-based metrics to evaluate a imbalanced classification problem, it is often times recommended to look at the precision and recall score to fully evaluate the overall effectiveness of a model.\n\nA model with high recall but low precision score returns many positive results, but most of its predicted labels are incorrect when compared to the ground truth. On the other hand, a model with high precision but low recall score returns very few results, but most of its predicted labels are correct when compared to the ground-truth. An ideal scenario would be a model with high precision and high recall, meaning it will return many results, with all results labeled correctly. Unfortunately, in most cases, precision and recall are often in tension. That is, improving precision typically reduces recall and vice versa.\n\nSo how do we know if we should sacrifice our precision for more recall, i.e. catching fraud? That is business decisions come into play. If the cost of missing a fraud highly outweighs the cost of canceling a bunch of legit customer transactions, i.e. false positives, then perhaps we can choose a weight that gives us a higher recall rate. Or maybe catching 80% of fraud is good enough for the business, in that case, we can also minimize the \"user friction\" by keeping our precision high.\n\n# Reference\n\n- [Notes: The Harmonic Mean](http://jwilson.coe.uga.edu/EMT725/HM/HM.html)\n- [Blog: \nClassification: Precision and Recall](https://developers.google.com/machine-learning/crash-course/classification/precision-and-recall)\n- [Blog: On Average, You\u2019re Using the Wrong Average: Geometric & Harmonic Means in Data Analysis](https://towardsdatascience.com/on-average-youre-using-the-wrong-average-geometric-harmonic-means-in-data-analysis-2a703e21ea0)\n- [Kaggle Kernel: Imbalanced data & why you should NOT use ROC curve](https://www.kaggle.com/lct14558/imbalanced-data-why-you-should-not-use-roc-curve)\n- [Stackoverflow: what is f1-score and what its value indicates?](https://stackoverflow.com/questions/45963174/what-is-f1-score-and-what-its-value-indicates)\n- [Stackoverflow: Why is the F-Measure a harmonic mean and not an arithmetic mean of the Precision and Recall measures?](https://stackoverflow.com/questions/26355942/why-is-the-f-measure-a-harmonic-mean-and-not-an-arithmetic-mean-of-the-precision)\n", "meta": {"hexsha": "5c126e0dce4c04400fff91dceeb7b268243c2865", "size": 297678, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "model_selection/imbalanced/imbalanced_metrics.ipynb", "max_stars_repo_name": "gvvynplaine/machine-learning", "max_stars_repo_head_hexsha": "9ecfa7bc960d02bc68496e383d7492509d4f3e84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-18T14:48:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T14:53:17.000Z", "max_issues_repo_path": "model_selection/imbalanced/imbalanced_metrics.ipynb", "max_issues_repo_name": "gvvynplaine/machine-learning", "max_issues_repo_head_hexsha": "9ecfa7bc960d02bc68496e383d7492509d4f3e84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model_selection/imbalanced/imbalanced_metrics.ipynb", "max_forks_repo_name": "gvvynplaine/machine-learning", "max_forks_repo_head_hexsha": "9ecfa7bc960d02bc68496e383d7492509d4f3e84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-21T17:25:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T17:25:15.000Z", "avg_line_length": 212.1724875267, "max_line_length": 108944, "alphanum_fraction": 0.8776228005, "converted": true, "num_tokens": 9789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334144352605, "lm_q2_score": 0.098079314902464, "lm_q1q2_score": 0.03995098222469179}}
{"text": "<a href=\"https://colab.research.google.com/github/cedeerwe/brutalna-akademia/blob/master/notebooks/02_suboj_minci.ipynb\" target=\"_parent\"></a>\n\n## In\u0161trukcie\n\nPred za\u010diatkom v\u00e1s popros\u00edm spusti\u0165 pr\u00edkaz z hornej li\u0161ty `Runtime -> Run All` alebo `Ctrl + F9`.  \nPre spustenie \u013eubovo\u013enej bunky k\u00f3du stla\u010dte `Ctrl + Enter` alebo \u0161\u00edpku v\u013eavo od samotnej bunky.  \nToto prostredie obashuje ve\u013ea r\u00f4znych skratiek, ktor\u00e9 sa sp\u00fa\u0161\u0165aj\u00fa stla\u010den\u00edm kombin\u00e1cie `Ctrl + M` a n\u00e1sledne nejak\u00e9 \u010fal\u0161ie tla\u010d\u00edtko. Napr\u00edklad pomocn\u00edka na pou\u017e\u00edvanie tohto prostredia n\u00e1jdete po stla\u010den\u00ed `Ctrl + M` a n\u00e1sledne `h`.\n\nPri n\u00e1zvoch sekci\u00ed \u010dasto n\u00e1jdete n\u00e1pis `1 cell hidden` alebo nie\u010do podobn\u00e9. Text pred nimi v\u00e1m v\u017edy prezrad\u00ed, \u010do sa v nich nach\u00e1dza. Rozbalte ich iba ak chcete pokra\u010dova\u0165 \u010falej, s\u00fa zabalen\u00e9 napr\u00edklad preto, aby ste rovno nevideli rie\u0161enia a mali ste \u010das sa zamyslie\u0165.  \n\n# Pomocn\u00fd k\u00f3d\n\n\n```python\nimport graphviz\n\nCOLOR_VYHRA_PRVY = \"darkorange\"\nCOLOR_VYHRA_DRUHY = \"darkorchid\"\nCOLOR_HLAVA = \"forestgreen\"\nCOLOR_ZNAK = \"red\"\n\nHLAVA = \"H\"\nZNAK = \"Z\"\nPRAZDNY = \"_\"\n\nHODY = [HLAVA, ZNAK, PRAZDNY]\nFARBY = {HLAVA: COLOR_HLAVA, ZNAK: COLOR_ZNAK}\n\ndef graf1_1():\n    d = graphviz.Digraph(graph_attr={\"rankdir\": \"LR\"})\n    for prvy_hod in HODY:\n        for druhy_hod in HODY:\n            if druhy_hod == PRAZDNY and prvy_hod != PRAZDNY:\n                continue # vynechaj tieto moznosti\n            for novy_hod in [HLAVA, ZNAK]:\n                d.edge(prvy_hod + druhy_hod, druhy_hod + novy_hod, color=FARBY[novy_hod])\n    d.node(HLAVA + ZNAK, color=COLOR_VYHRA_PRVY)\n    d.node(HLAVA + HLAVA, color=COLOR_VYHRA_DRUHY)\n    return d\n\ndef graf1_2():\n    d = graphviz.Digraph(graph_attr={\"rankdir\": \"LR\"})\n    d.edge(PRAZDNY + PRAZDNY, PRAZDNY + HLAVA, color=FARBY[HLAVA])\n    d.edge(PRAZDNY + PRAZDNY, PRAZDNY + PRAZDNY, color=FARBY[ZNAK])\n    d.edge(PRAZDNY + HLAVA, HLAVA + HLAVA, color=FARBY[HLAVA])\n    d.edge(PRAZDNY + HLAVA, HLAVA + ZNAK, color=FARBY[ZNAK])\n    d.node(HLAVA + ZNAK, color=COLOR_VYHRA_PRVY)\n    d.node(HLAVA + HLAVA, color=COLOR_VYHRA_DRUHY)\n    return d\n\ndef graf2_1():\n    d = graphviz.Digraph(graph_attr={\"rankdir\": \"LR\"})\n    for prvy_hod in HODY:\n        for druhy_hod in HODY:\n            if druhy_hod == PRAZDNY and prvy_hod != PRAZDNY:\n                continue # vynechaj tieto moznosti\n            for novy_hod in [HLAVA, ZNAK]:\n                d.edge(prvy_hod + druhy_hod, druhy_hod + novy_hod, color=FARBY[novy_hod])\n    d.node(ZNAK + HLAVA, color=COLOR_VYHRA_PRVY)\n    d.node(HLAVA + HLAVA, color=COLOR_VYHRA_DRUHY)\n    return d\n\ndef graf2_2():\n    d = graphviz.Digraph(graph_attr={\"rankdir\": \"LR\"})\n    d.edge(PRAZDNY + PRAZDNY, PRAZDNY + HLAVA, color=FARBY[HLAVA])\n    d.edge(PRAZDNY + PRAZDNY, PRAZDNY + ZNAK, color=FARBY[ZNAK])\n    d.edge(PRAZDNY + HLAVA, HLAVA + HLAVA, color=FARBY[HLAVA])\n    d.edge(PRAZDNY + HLAVA, PRAZDNY + ZNAK, color=FARBY[ZNAK])\n    d.edge(PRAZDNY + ZNAK, ZNAK + HLAVA, color=FARBY[HLAVA])\n    d.edge(PRAZDNY + ZNAK, PRAZDNY + ZNAK, color=FARBY[ZNAK])\n    d.node(ZNAK + HLAVA, color=COLOR_VYHRA_PRVY)\n    d.node(HLAVA + HLAVA, color=COLOR_VYHRA_DRUHY)\n    return d\n\ndef graf3_1():\n    d = graphviz.Digraph(graph_attr={\"rankdir\": \"LR\"})\n    for prvy_hod in HODY:\n        for druhy_hod in HODY:\n            for treti_hod in HODY:\n                if (druhy_hod == PRAZDNY and prvy_hod != PRAZDNY) or (\n                    treti_hod == PRAZDNY and (prvy_hod != PRAZDNY or druhy_hod != PRAZDNY)):\n                    continue # vynechaj tieto moznosti\n                for novy_hod in [HLAVA, ZNAK]:\n                    d.edge(\n                        prvy_hod + druhy_hod + treti_hod,\n                        druhy_hod + treti_hod + novy_hod,\n                        color=FARBY[novy_hod]\n                    )\n    d.node(HLAVA + HLAVA + ZNAK, color=COLOR_VYHRA_PRVY)\n    d.node(ZNAK + HLAVA + HLAVA, color=COLOR_VYHRA_DRUHY)\n    return d\n\ndef graf3_2():\n    d = graphviz.Digraph(graph_attr={\"rankdir\": \"LR\"})\n    d.edge(PRAZDNY + PRAZDNY + PRAZDNY, PRAZDNY + PRAZDNY + HLAVA, color=FARBY[HLAVA])\n    d.edge(PRAZDNY + PRAZDNY + PRAZDNY, PRAZDNY + PRAZDNY + ZNAK, color=FARBY[ZNAK])\n    d.edge(PRAZDNY + PRAZDNY + HLAVA, PRAZDNY + HLAVA + HLAVA, color=FARBY[HLAVA])\n    d.edge(PRAZDNY + PRAZDNY + HLAVA, PRAZDNY + PRAZDNY + ZNAK, color=FARBY[ZNAK])\n    d.edge(PRAZDNY + PRAZDNY + ZNAK, PRAZDNY + ZNAK + HLAVA, color=FARBY[HLAVA])\n    d.edge(PRAZDNY + PRAZDNY + ZNAK, PRAZDNY + PRAZDNY + ZNAK, color=FARBY[ZNAK])\n    d.edge(PRAZDNY + HLAVA + HLAVA, PRAZDNY + HLAVA + HLAVA, color=FARBY[HLAVA])\n    d.edge(PRAZDNY + HLAVA + HLAVA, HLAVA + HLAVA + ZNAK, color=FARBY[ZNAK])\n    d.edge(PRAZDNY + ZNAK + HLAVA, ZNAK + HLAVA + HLAVA, color=FARBY[HLAVA])\n    d.edge(PRAZDNY + ZNAK + HLAVA, PRAZDNY + PRAZDNY + ZNAK, color=FARBY[ZNAK])\n    d.node(HLAVA + HLAVA + ZNAK, color=COLOR_VYHRA_PRVY)\n    d.node(ZNAK + HLAVA + HLAVA, color=COLOR_VYHRA_DRUHY)\n    return d\n\ndef graf4_1():\n    d = graphviz.Digraph(graph_attr={\"rankdir\": \"LR\"})\n    for prvy_hod in HODY:\n        for druhy_hod in HODY:\n            for treti_hod in HODY:\n                if (druhy_hod == PRAZDNY and prvy_hod != PRAZDNY) or (\n                    treti_hod == PRAZDNY and (prvy_hod != PRAZDNY or druhy_hod != PRAZDNY)):\n                    continue # vynechaj tieto moznosti\n                for novy_hod in [HLAVA, ZNAK]:\n                    d.edge(\n                        prvy_hod + druhy_hod + treti_hod,\n                        druhy_hod + treti_hod + novy_hod,\n                        color=FARBY[novy_hod]\n                    )\n    d.node(HLAVA + ZNAK + ZNAK, color=COLOR_VYHRA_PRVY)\n    d.node(ZNAK + HLAVA + ZNAK, color=COLOR_VYHRA_DRUHY)\n    return d\n\ndef graf4_2():\n    d = graphviz.Digraph(graph_attr={\"rankdir\": \"LR\"})\n    d.edge(PRAZDNY + PRAZDNY + PRAZDNY, PRAZDNY + PRAZDNY + HLAVA, color=FARBY[HLAVA])\n    d.edge(PRAZDNY + PRAZDNY + PRAZDNY, PRAZDNY + PRAZDNY + ZNAK, color=FARBY[ZNAK])\n    d.edge(PRAZDNY + PRAZDNY + HLAVA, PRAZDNY + PRAZDNY + HLAVA, color=FARBY[HLAVA])\n    d.edge(PRAZDNY + PRAZDNY + HLAVA, PRAZDNY + HLAVA + ZNAK, color=FARBY[ZNAK])\n    d.edge(PRAZDNY + PRAZDNY + ZNAK, PRAZDNY + ZNAK + HLAVA, color=FARBY[HLAVA])\n    d.edge(PRAZDNY + PRAZDNY + ZNAK, PRAZDNY + PRAZDNY + ZNAK, color=FARBY[ZNAK])\n    d.edge(PRAZDNY + HLAVA + ZNAK, PRAZDNY + ZNAK + HLAVA, color=FARBY[HLAVA])\n    d.edge(PRAZDNY + HLAVA + ZNAK, HLAVA + ZNAK + ZNAK, color=FARBY[ZNAK])\n    d.edge(PRAZDNY + ZNAK + HLAVA, PRAZDNY + PRAZDNY + HLAVA, color=FARBY[HLAVA])\n    d.edge(PRAZDNY + ZNAK + HLAVA, ZNAK + HLAVA + ZNAK, color=FARBY[ZNAK])\n    d.node(HLAVA + ZNAK + ZNAK, color=COLOR_VYHRA_PRVY)\n    d.node(ZNAK + HLAVA + ZNAK, color=COLOR_VYHRA_DRUHY)\n    return d\n```\n\n# \u00daloha \u010d. 1\nDnes sa budeme venova\u0165 nasleduj\u00facej hre: h\u00e1d\u017eeme mincou, a\u017e k\u00fdm jeden z hr\u00e1\u010dov nevyhr\u00e1. Prv\u00fd hr\u00e1\u010d vyhr\u00e1, ak padne za sebou hlava-znak. Druh\u00fd hr\u00e1\u010d vyhr\u00e1, ak padne za sebou hlava-hlava. **Ktor\u00fd hr\u00e1\u010d m\u00e1 v\u00e4\u010d\u0161iu \u0161ancu, \u017ee vyhr\u00e1? O ko\u013eko presne?**\n\n## N\u00e1povedy\n\n### N\u00e1poveda 1\n\nPodobne ako na minulej hodine, budeme h\u00e1dza\u0165 mincou, a\u017e k\u00fdm nie\u010do nebude splnen\u00e9. Premyslite si, ako pou\u017ei\u0165 vedomosti a hlavn\u00fa techniku z minulej hodiny na tak\u00fdto druh pr\u00edkladu.\n\n### N\u00e1poveda 2\n\nNakreslite si v\u0161etky mo\u017en\u00e9 stavy a vz\u0165ahy medzi nimi do pekn\u00e9ho grafu. Sk\u00faste z neho vymyslie\u0165 rie\u0161enie.\n\n## Rie\u0161enie\n\nPoriadne sa zamyslite predt\u00fdm, ako budete \u010d\u00edta\u0165 \u010falej. Toto nie je kniha, ale interakt\u00edvna lekcia o tom, ako samostatne pou\u017ei\u0165 matematiku na rie\u0161enie rozli\u010dn\u00fdch probl\u00e9mov.\n\n### Odhad\n\nAko na minulej hodine, odhady budeme robi\u0165 r\u00fdchle. Pon\u00faknu n\u00e1m z\u00e1kladn\u00fa intu\u00edciu o probl\u00e9me.\n\nZ minulej hodiny vieme, \u017ee treba v priemere $4$ hody na to, aby padla hlava-znak a z\u00e1rove\u0148, \u017ee treba v priemere $6$ hody na to, aby padli dve hlavy po sebe. Prvotn\u00fd odhad by teda d\u00e1val zmysel, \u017ee v\u00e4\u010d\u0161iu \u0161ancu vyhra\u0165 m\u00e1 hlava-znak. Nie je \u00faplne jasn\u00e9 o ko\u013eko, ale pomerovo by sme \u010dakali nie\u010do ako $\\tfrac{2}{3}$. \n\n### Simul\u00e1cia\n\nPodobn\u00fdch simul\u00e1cii sme u\u017e na minulej hodine nieko\u013eko robili, nemalo by \u00eds\u0165 o ni\u010d nov\u00e9. Pozorne si ale k\u00f3d pre\u010d\u00edtajte, aby ste mu dobre rozumeli a vedeli aj sami nap\u00edsa\u0165 nie\u010do podobn\u00e9.\n\n\n```python\nimport random\nHLAVA = \"H\" # ulo\u017e\u00edme si tieto dva \u0161peci\u00e1lne znaky, aby sa n\u00e1m lep\u0161ie \u010d\u00edtal k\u00f3d\nZNAK = \"Z\"\n\ndef hadz_hlava_hlava_proti_hlava_znak():\n    posledny_hod = \"\"\n    while True:\n        hod = HLAVA if random.random() < 0.5 else ZNAK\n        # porovn\u00e1me minul\u00fd hod a s\u00fa\u010dasn\u00fd proti hlave a znaku.\n        if [posledny_hod, hod] == [HLAVA, ZNAK]: \n            return 1 # vyhral prv\u00fd hr\u00e1\u010d\n        # porovn\u00e1me minul\u00fd hod a s\u00fa\u010dasn\u00fd proti hlave a hlave.\n        if [posledny_hod, hod] == [HLAVA, HLAVA]: \n            return 0 # vyhral druh\u00fd hr\u00e1\u010d\n        posledny_hod = hod # ak nikto nevyhral, s\u00fa\u010dasn\u00fdm hodom si prep\u00ed\u0161eme posledn\u00fd\n```\n\n\n```python\nhadz_hlava_hlava_proti_hlava_znak()\n```\n\n\n\n\n    1\n\n\n\n\n```python\nN = 10000\nsum(hadz_hlava_hlava_proti_hlava_znak() for i in range(N)) / N\n```\n\n\n\n\n    0.5033\n\n\n\nTo je zauj\u00edmav\u00fd v\u00fdsledok, ke\u010f\u017ee n\u00e1m nesed\u00ed \u00faplne s odhadom. Kde sme spravili chybu, v k\u00f3de alebo v odhade? Ke\u010f m\u00e1te premyslen\u00e9, m\u00f4\u017eme pokra\u010dova\u0165 k matematick\u00e9mu rie\u0161eniu.\n\n### Matematika\n\nSk\u00fasme si zap\u00edsa\u0165 t\u00fato hru pomocou na\u0161ich grafov z minulej hodiny. V prvom rade si mus\u00edme premyslie\u0165, ak\u00e9 s\u00fa v\u0161etky situ\u00e1cie, v ktor\u00fdch m\u00f4\u017eme by\u0165?\n- `__`: nepadlo e\u0161te ni\u010d, pr\u00e1ve za\u010d\u00edname,\n- `_H`, `_Z`: sme po prvom hode a padla jedna hlava respekt\u00edve jeden znak,\n- `HH`, `HZ`, `ZH`, `ZZ`: posledn\u00e9 dva hody boli hlava-hlava, at\u010f..\n\nZakreslime si do pekn\u00e9ho preh\u013eadn\u00e9ho grafu vz\u0165ahy medzi v\u0161etk\u00fdmi t\u00fdmito mo\u017enos\u0165ami:\n\n\n```python\ngraf1_1()\n```\n\n\n\n\n    \n\n    \n\n\n\nOran\u017eovou farbou je ozna\u010den\u00e1 v\u00fdhern\u00e1 situ\u00e1cia za prv\u00e9ho hr\u00e1\u010da a fialovou druh\u00e9ho hr\u00e1\u010da.\n\nAk sa pozrieme dos\u0165 pozorne na graf, m\u00f4\u017eme si v\u0161imn\u00fa\u0165, \u017ee jedin\u00e9 \u0161\u00edpky do v\u00fdhern\u00fdch poz\u00edci\u00ed ved\u00fa zo stavov `_H` a `ZH`. Z oboch stavov ide pr\u00e1ve jedna \u0161\u00edpka k v\u00fdhre prv\u00e9ho a pr\u00e1ve jedna \u0161\u00edpka k v\u00fdhre druh\u00e9ho hr\u00e1\u010da. \u0160anca na v\u00fdhru ka\u017ed\u00e9ho hr\u00e1\u010da by teda mala by\u0165 $\\tfrac{1}{2}$.\n\nPri\u0161li sme k tomu ale celkom zlo\u017eitou cestou, sk\u00fasme si to zjednodu\u0161i\u0165. Z poh\u013eadu tejto hry s\u00fa stavy `__`, `_Z` a `ZZ` \u00faplne toto\u017en\u00e9. Nehodili sme ni\u010d d\u00f4le\u017eit\u00e9 pre \u017eiadneho z hr\u00e1\u010dov. Tieto stavy si ozna\u010d\u00edme ako `__`. Rovnako stavy `_H` a `ZH` s\u00fa toto\u017en\u00e9 $\\rightarrow$ posledn\u00e1 bola hlava a predt\u00fdm padlo nie\u010do ned\u00f4le\u017eit\u00e9. A teraz si sk\u00fasme prekresli\u0165 graf. Ako by vyzeral?\n\n#### Pokra\u010dovanie\n\n\n```python\ngraf1_2()\n```\n\n\n\n\n    \n\n    \n\n\n\nOverte si, \u017ee tento nov\u00fd graf zachycuje podstatu hry rovnako ako n\u00e1\u0161 prv\u00fd graf. Ost\u00e1vaj\u00fa zachovan\u00e9 \u0161\u00edpky, pravdepodobnosti aj stavy.\n\nZ tohto grafu je pekne vidie\u0165, ako bude hra prebieha\u0165. Budeme h\u00e1dza\u0165 ned\u00f4le\u017eit\u00e9 veci, a\u017e k\u00fdm padne prv\u00e1 hlava. Potom sa \u010fal\u0161\u00edm hodom u\u017e rozhodne, a tento hod bude fifty-fifty, teda obaja hr\u00e1\u010di maj\u00fa rovnak\u00fa \u0161ancu na v\u00fdhru.\n\nVid\u00edme teda, \u017ee sme sa m\u00fdlili v na\u0161om odhade. Pre\u010do sme sa ale zm\u00fdlili?\n\nAk by ka\u017ed\u00fd hr\u00e1\u010d h\u00e1dzal vlastnou mincou a tie\u017e by sme \u010dakali, komu padne prv\u00e9mu jeho postupnos\u0165, n\u00e1\u0161 odhad by bol pravdepodobne spr\u00e1vny. Jednalo by sa toti\u017e o **nez\u00e1visl\u00e9** udalosti. V pr\u00edpade na\u0161ej hry s\u00fa ale hody mincou **z\u00e1visl\u00e9**. D\u00f4vod, pre\u010do v priemere padne r\u00fdchlej\u0161ie hlava-znak bol, \u017ee ak sa n\u00e1m po hoden\u00ed prvej hlavy nepodar\u00ed hodi\u0165 rovno znak, tak sa dostaneme do stavu, \u017ee st\u00e1le m\u00e1me hoden\u00fa hlavu. V na\u0161ej dne\u0161nej hre sa ale rovno dostaneme do stavu prehry, preto\u017ee sme pr\u00e1ve hodili postupnos\u0165 hlava-hlava.\n\nZ\u00e1visl\u00e9 a nez\u00e1visl\u00e9 udalosti s\u00fa v pravdepodobnosti \u0165a\u017ek\u00fd orie\u0161ok a my sme pr\u00e1ve videli prv\u00fd pr\u00edklad na t\u00fato t\u00e9mu. Budeme sa s nimi stret\u00e1va\u0165 ve\u013ea, tak\u017ee aj ke\u010f ste hne\u010f nepochopili o \u010do ide, nebojte sa \u00eds\u0165 \u010falej. Budeme ma\u0165 e\u0161te ve\u013ea \u010dasu na precvi\u010dovanie a prem\u00fd\u0161\u013eanie.\n\n# \u00daloha \u010d.2\nHr\u00e1me sa rovnak\u00fa hru, akur\u00e1t prv\u00fd hr\u00e1\u010d vyhr\u00e1, ak padne znak-hlava. Druh\u00fd hr\u00e1\u010d st\u00e1le vyhr\u00e1, ke\u010f padne hlava-hlava. **Zmen\u00ed sa nie\u010do? Ak\u00e9 s\u00fa pravdepodobnosti?**\n\n## Rie\u0161enie\n\n### Odhad\n\nN\u00e1\u0161 predch\u00e1dzaj\u00faci odhad bol chybn\u00fd, lebo sme ner\u00e1tali so z\u00e1vislos\u0165ou medzi postupnos\u0165ami hlava-hlava a hlava-znak. O\u010dividne n\u00e1s tak\u00e9to pr\u00edklady m\u00f4\u017eu v\u0161eli\u010d\u00edm prekvapi\u0165.\n\nTeraz ale znej\u00fa na\u0161e postupnosti dos\u0165 odli\u0161ne, tak by n\u00e1m odhady z minul\u00e9ho pr\u00edkladu mo\u017eno mohli fungova\u0165. Na prv\u00fd poh\u013ead sa v tejto \u00falohe nedostaneme do podobn\u00e9ho stavu ako `_H` a preto nevid\u00edme *o\u010dividn\u00fd* d\u00f4vod, aby to bolo zase $\\tfrac{1}{2}$ a nie povedzme $\\frac{2}{3}$ v prospech znak-hlava.\n\n### Simul\u00e1cia\n\nSk\u00fasime si to naprogramova\u0165 vo v\u0161eobecnosti pre \u013eubovo\u013en\u00e9 dva posledn\u00e9 hody.\n\n\n```python\ndef hadz_kym_dva_posledne(hrac1, hrac2): # hr\u00e1\u010d bude charakterizovan\u00fd dvojicou vysledkov hodov\n    posledny_hod = \"\"\n    while True:\n        hod = HLAVA if random.random() < 0.5 else ZNAK\n        if [posledny_hod, hod] == hrac1: # ak sa posledn\u00e9 dva hody rovnaj\u00fa hr\u00e1\u010dovi, skon\u010dime\n            return 1\n        if [posledny_hod, hod] == hrac2:\n            return 0\n        posledny_hod = hod\n```\n\n\n```python\nhadz_kym_dva_posledne([HLAVA, HLAVA], [ZNAK, HLAVA])\n```\n\n\n\n\n    0\n\n\n\n\n```python\nN = 10000\nsum(hadz_kym_dva_posledne([HLAVA, HLAVA], [ZNAK, HLAVA]) for i in range(N)) / N\n```\n\n\n\n\n    0.2454\n\n\n\nK\u00f3d si m\u00f4\u017eme overi\u0165 aj t\u00fdm, \u017ee d\u00e1va rovnak\u00e9 v\u00fdsledky pre prv\u00fd pr\u00edklad ako predch\u00e1dzaj\u00faci k\u00f3d. Sk\u00faste si to overi\u0165.\n\nPravdepodobnos\u0165 vyzer\u00e1 by\u0165 okolo $\\tfrac{3}{4}$, tak\u017ee n\u00e1\u0161 odhad bol tentoraz celkom dobr\u00fd. Teda, aspo\u0148 to tak zatia\u013e vyzer\u00e1.\n\n### Matematika\n\nV minulom pr\u00edklade sme si nakreslili v\u0161etky vz\u0165ahy medzi stavmi, m\u00f4\u017eme sa teda iba pozrie\u0165 na u\u017e hotov\u00e9 dielo a akur\u00e1t si prezna\u010di\u0165 v\u00ed\u0165azn\u00e9 vrcholy.\n\n\n```python\ngraf2_1()\n```\n\n\n\n\n    \n\n    \n\n\n\nTento graf je torcha komplikovanej\u0161\u00ed, ale tie\u017e si m\u00f4\u017eme nie\u010do v\u0161imn\u00fa\u0165. Do stavu `HH` sa vieme dosta\u0165 bu\u010f zo stavu `ZH` - \u010do sa nikdy nestane, lebo stavom `ZH` kon\u010d\u00edme - alebo zo stavu `_H`. Do stavu `_H` sa vieme dosta\u0165 iba zo stavu `__`. Do stavu `__` sa ale nevieme dosta\u0165 v\u00f4bec, iba ke\u010f v \u0148om za\u010d\u00edname. Tak\u017ee jedin\u00e1 \u0161anca na v\u00fdhru druh\u00e9ho hr\u00e1\u010da je, \u017ee by hodil rovno `HH` za sebou ako prv\u00e9 dva hody. V\u0161etky ostatn\u00e9 cesty ved\u00fa do `ZH`. \u0160anca na hodenie `HH` ako prv\u00e9 dva hody je $\\tfrac{1}{4}$ a teda \u0161anca v\u00fdhry druh\u00e9ho hr\u00e1\u010da je zvy\u0161ok: $\\tfrac{3}{4}$.\n\nRovnako ako minule, aj teraz si sk\u00fasme tento graf zjednodu\u0161i\u0165 a mo\u017eno si v\u0161imneme nejak\u00fd zauj\u00edmav\u00fd vz\u0165ah. Ako by v tomto pr\u00edpade vyzeral zmen\u0161en\u00fd graf, bez zbyto\u010dn\u00fdch vrcholov? \n\n#### Pokra\u010dovanie\n\nPodstatn\u00e9 stavy bud\u00fa:\n- `__`: nehodili sme e\u0161te ni\u010d podstatn\u00e9\n- `_H`, `_Z`: posledn\u00fd hod bol hlava, respekt\u00edve znak, a hod predt\u00fdm bol nezauj\u00edmav\u00fd\n- `HH`, `ZH`: posledn\u00e9 dva hody boli v\u00fdhern\u00e9 \n\nV princ\u00edpe sa k t\u00fdmto stavom vieme dosta\u0165 tak, \u017ee si nap\u00ed\u0161eme v\u00fdsledn\u00e9 stavy a v\u0161etky stavy na ceste k nim. Ostatn\u00e9 nie s\u00fa zauj\u00edmav\u00e9. Hrany si vieme dokresli\u0165 tak, \u017ee si premysl\u00edme, \u010do sa stane po pridan\u00ed hlavy / znaku na koniec predch\u00e1dzaj\u00faceho stavu a do ktor\u00e9ho stavu n\u00e1s to dostane. \n\nZmen\u0161en\u00fd graf bude vyzera\u0165 nasledovne:\n\n\n```python\ngraf2_2()\n```\n\n\n\n\n    \n\n    \n\n\n\nNezabudnite si zase poriadne overi\u0165, \u017ee naozaj ide o spr\u00e1vny graf.\n\n\u010co sa teda v tomto pr\u00edpade deje? Akon\u00e1hle padne \u013eubovo\u013en\u00fd znak, u\u017e sme skon\u010dili. Jeden poh\u013ead je, \u017ee zo stavu s posledn\u00fdm znakom bu\u010f rovno vyhr\u00e1 prv\u00fd hr\u00e1\u010d, alebo bude zase posledn\u00fd znak. \n\nDruh\u00fd poh\u013ead je, \u017ee aby vyhral druh\u00fd hr\u00e1\u010d, potrebuje hodi\u0165 dve hlavy po sebe. V momente ke\u010f ich hod\u00ed pred nimi ale nem\u00f4\u017ee by\u0165 znak, preto\u017ee by u\u017e vyhral prv\u00fd hr\u00e1\u010d svojou postupnos\u0165ou znak-hlava. To je splnen\u00e9 iba ak nepadne \u017eiaden znak.\n\nAkoko\u013evek si tento graf vysvetl\u00edme, pravdepodobnosti vyjd\u00fa tie ist\u00e9 - druh\u00fd hr\u00e1\u010d vyhr\u00e1, iba ak hod\u00ed po sebe dve hlavy, \u010do je pravdepodobnos\u0165 $\\tfrac{1}{4}$.\n\n# \u00daloha \u010d. 3\nKe\u010f u\u017e sme sa rozohriali, pred\u013a\u017eime si postupnosti. Ako dopadne **hlava - hlava - znak** proti **znak - hlava - hlava?** \n\n## N\u00e1poveda\n\nNakresli\u0165 si cel\u00fd ve\u013ek\u00fd graf v\u0161etk\u00fdch stavov je ur\u010dite cesta, ale n\u00e1ro\u010dn\u00e1. Navy\u0161e v \u0148om bude \u0165a\u017ek\u00e9 nie\u010do vidie\u0165 pravdepodobne ni\u010d neuvid\u00edme. Sk\u00faste si rovno nakresli\u0165 zmen\u0161en\u00fd graf, mo\u017eno v \u0148om nie\u010do uvid\u00edte.\n\n## Rie\u0161enie\n\n### Odhad\n\nAk sme si spr\u00e1vne spravili dom\u00e1cu \u00falohu z minulej hodiny, dostali sme sa k \u010d\u00edslam, \u017ee na hodenie oboch postupnost\u00ed treba v priemere $8$ hodov. Na z\u00e1klade tohto \u010d\u00edsla je \u0165a\u017ek\u00e9 poveda\u0165, ktor\u00fd hr\u00e1\u010d m\u00e1 v\u00e4\u010d\u0161iu \u0161ancu vyhra\u0165.\n\nM\u00f4\u017eme si ale v\u0161imn\u00fa\u0165, \u017ee na chvoste postupnosti znak-hlava-hlava s\u00fa prv\u00e9 dva hody postupnosti hlava-hlava-znak. D\u00e1va teda zmysel, \u017ee by to mohlo dopadn\u00fa\u0165 podobne, ako znak-hlava proti hlava-hlava, teda tentoraz v prospech druh\u00e9ho hr\u00e1\u010da. Pravdepodobnostne by to mohlo by\u0165 tie\u017e podobne.\n\n### Simul\u00e1cia\n\nNasimulujme si rovno v\u0161eobecne v\u0161etky s\u00faboje d\u013a\u017eky $3$, obdobne ako sme to spravili v druhej \u00falohe. Sta\u010dia drobn\u00e9 \u00fapravy na zapam\u00e4tanie predposledn\u00e9ho hodu.\n\n\n```python\ndef hadz_kym_tri_posledne(hrac1, hrac2):\n    posledny_hod = \"\" \n    predposledny_hod = \"\"\n    while True:\n        hod = HLAVA if random.random() < 0.5 else ZNAK\n        if [posledny_hod, predposledny_hod, hod] == hrac1:\n            return 1\n        if [posledny_hod, predposledny_hod, hod] == hrac2:\n            return 0\n        posledny_hod, predposledny_hod = hod, posledny_hod\n```\n\n\n```python\nhrac1 = [HLAVA, HLAVA, ZNAK]\nhrac2 = [ZNAK, HLAVA, HLAVA]\nhadz_kym_tri_posledne(hrac1, hrac2)\n```\n\n\n\n\n    1\n\n\n\n\n```python\nN = 10000\nsum(hadz_kym_tri_posledne(hrac1, hrac2) for i in range(N)) / N\n```\n\n\n\n\n    0.6659\n\n\n\nZase n\u00e1m odhad nesed\u00ed s v\u00fdsledkom zo simul\u00e1cie. Sk\u00faste identifikova\u0165 chybu predt\u00fdm, ako sa pust\u00edme do matematick\u00e9ho dokazovania.\n\n### Matematika\n\nPre \u00faplnos\u0165 sme si pre v\u00e1s pripravili graf v\u0161etk\u00fdch mo\u017en\u00fdch stavov, obdobne ako v predch\u00e1dzaj\u00facich \u00faloh\u00e1ch. Je mierne v\u00e4\u010d\u0161\u00ed a menej preh\u013eadn\u00fd, ale rozhodne zauj\u00edmav\u00fd:\n\n\n```python\ngraf3_1()\n```\n\n\n\n\n    \n\n    \n\n\n\nPre brut\u00e1lnych odpor\u00fa\u010dame sk\u00fasi\u0165 uvidie\u0165 rie\u0161enie pr\u00edkladu priamo v tomto grafe.\n\nMy ostatn\u00ed si to zjednodu\u0161\u00edme a nakresl\u00edme si zmen\u0161en\u00fd graf. Zauj\u00edmav\u00e9 stavy s\u00fa `___`, `__H`, `_HH`, `HHZ`, `__Z`, `_ZH` a `ZHH`. Vz\u0165ahy medzi nimi si mus\u00edme chv\u00ed\u013eu premyslie\u0165, ale mali by sme sa dosta\u0165 k nie\u010domu tak\u00e9muto: \n\n\n```python\ngraf3_2()\n```\n\n\n\n\n    \n\n    \n\n\n\nZ tohto grafu je kr\u00e1sne vidie\u0165, \u017ee sme v rovnakej situ\u00e1cii ako v druhej \u00falohe, iba sme za kone\u010dn\u00e9 poz\u00edcie `ZH` a `HH` pridali e\u0161te jeden vrchol, do ktor\u00e9ho sa in\u00e1\u010d dosta\u0165 ned\u00e1. Pravdepodobnos\u0165 teda bude tie\u017e rovnak\u00e1 a druh\u00fd hr\u00e1\u010d vyhr\u00e1va s \u0161ancou $\\tfrac{3}{4}$.\n\nKde sme teda mali chybu? O\u010dividne v k\u00f3de, preto\u017ee odhad n\u00e1m d\u00e1val rovnak\u00fd v\u00fdsledok. Alebo v matematike aj odhade. N\u00e1jdenie ch\u00fdb a ich opravenie u\u017e nech\u00e1me na v\u00e1s.\n\n# \u00daloha \u010d. 4\nZ\u00e1vere\u010dn\u00e1 \u00faloha z hodiny bude zr\u00e1ta\u0165 pravdepodobnosti v\u00fdhry hr\u00e1\u010da s postupnos\u0165ou **hlava-znak-znak** proti hr\u00e1\u010dovi s postupnos\u0165ou **znak-hlava-znak**.\n\n## Rie\u0161enie\n\n### Odhad\n\nV dom\u00e1cej \u00falohe z minulej hodiny sme si zr\u00e1tali, \u017ee priemern\u00fd po\u010det hodov na hodenie postupnosti hlava-znak-znak je $8$ hodov a postupnosti znak-hlava-znak je $10$. To n\u00e1m napoved\u00e1, \u017ee prv\u00fd hr\u00e1\u010d by mohol ma\u0165 nejak\u00fa v\u00fdhodu. \n\nNa druh\u00fa stranu zase vid\u00edme, \u017ee posledn\u00e9 dva hody druh\u00e9ho hr\u00e1\u010da s\u00fa rovnak\u00e9 ako prv\u00e9 dva hody prv\u00e9ho hr\u00e1\u010da. V predch\u00e1dzaj\u00facich dvoch \u00faloh\u00e1ch to malo siln\u00fd v\u00fdznam, mohlo by to ma\u0165 v\u00fdznam aj teraz.\n\nM\u00e1me teda situ\u00e1ciu, ke\u010f maj\u00fa obaja hr\u00e1\u010di navrch z nejak\u00e9ho d\u00f4vodu. Ktor\u00fd z d\u00f4vodov prev\u00e1\u017ei, si m\u00f4\u017eme len tipn\u00fa\u0165. Nemala by n\u00e1s ale prekvapi\u0165 ani mo\u017en\u00e1 rem\u00edza. \n\n### Simul\u00e1cia\n\nPou\u017eijeme opraven\u00fd k\u00f3d z tretej \u00falohy, d\u00fafame, \u017ee ste pri\u0161li na rovnak\u00fa chybu.\n\n\n```python\ndef hadz_kym_tri_posledne_spravne(hrac1, hrac2):\n    posledny_hod = \"\" \n    predposledny_hod = \"\"\n    while True:\n        hod = HLAVA if random.random() < 0.5 else ZNAK\n        if [posledny_hod, predposledny_hod, hod] == hrac1:\n            return 1\n        if [posledny_hod, predposledny_hod, hod] == hrac2:\n            return 0\n        posledny_hod, predposledny_hod = predposledny_hod, hod\n```\n\n\n```python\nhrac1 = [HLAVA, ZNAK, ZNAK]\nhrac2 = [ZNAK, HLAVA, ZNAK]\n\nhadz_kym_tri_posledne_spravne(hrac1, hrac2)\n```\n\n\n\n\n    0\n\n\n\n\n```python\nN = 10000\nsum(hadz_kym_tri_posledne_spravne(hrac1, hrac2) for i in range(N)) / N\n```\n\n\n\n\n    0.4964\n\n\n\nTak to naozaj vyzer\u00e1 na vyrovnan\u00e9 \u0161ance. Pozrime sa e\u0161te, \u010do na to hovor\u00ed matematika.\n\n### Matematika\n\nAko v minulom pr\u00edklade, priklad\u00e1me \u00faplny graf pre brut\u00e1lnych. Odkomentujte (odstr\u00e1\u0148te mrie\u017eku zo za\u010diatku) \u010fal\u0161ieho riadku a spustite pre zobrazenie cel\u00e9ho grafu. Dr\u017e\u00edm v\u00e1m brut\u00e1lnym palce pri h\u013eadan\u00ed rie\u0161enia vo ve\u013ekom grafe.\n\n\n```python\n# graf4_1()\n```\n\nMy ostatn\u00ed sa pozrieme na zmen\u0161en\u00fd graf. Vytvorili sme ho \u00faplne rovnak\u00fdm sp\u00f4sobom ako predch\u00e1dzaj\u00faci:\n\n\n```python\ngraf4_2()\n```\n\n\n\n\n    \n\n    \n\n\n\nTento graf je o kus komplikovanej\u0161\u00ed ako na\u0161e predch\u00e1dzaj\u00face. V tomto sa nach\u00e1dzaj\u00fa cykly a nevid\u00edme \u017eiaden priamo\u010diary sp\u00f4sob, ako spo\u010d\u00edta\u0165 pravdepodobnosti. Z ka\u017ed\u00e9ho vrchola okrem koncov\u00fdch existuje \u0161anca, \u017ee vyhr\u00e1 ka\u017ed\u00fd z hr\u00e1\u010dov. Ako to teda spo\u010d\u00edtame? Nech\u00e1me v\u00e1m teraz s pekn\u00fdm obr\u00e1zkom priestor na zamyslenie.\n\n#### N\u00e1poveda\n\nSpome\u0148te si na hlavn\u00fd trik z minulej hodiny. Vedeli by sme ho vyu\u017ei\u0165?\n\n#### Rie\u0161enie\n\nNa minulej hodine sme si zvykli ozna\u010di\u0165 v podobn\u00fdch situ\u00e1ci\u00e1ch niektor\u00e9 hodnoty a potom s nimi po\u010d\u00edta\u0165. Sk\u00fasime to aj teraz. \n\nOzna\u010dme si pravdepodobnos\u0165 v\u00fdhry prv\u00e9ho hr\u00e1\u010da v stave `_HZ` ako $p$. Zo vz\u0165ahov vid\u00edme, \u017ee pravdepodobnos\u0165 bude rovnak\u00e1 aj v stave `__H`, teda tie\u017e $p$. \n\n\u0160anca v\u00fdhry v stave `_ZH` bude polovica \u0161ance v\u00fdhry v stave `ZHZ` s\u010d\u00edtan\u00e1 s polovicou \u0161ance v\u00fdhry v stave `__H`. \u0160anca v\u00fdhry v stave `ZHZ` je jednoducho $0$, lebo u\u017e vyhral druh\u00fd hr\u00e1\u010d. \u0160anca v stave `_ZH` bude teda $\\tfrac{1}{2}p$.\n\nTeraz u\u017e vieme vypo\u010d\u00edta\u0165 aj `_HZ`. Ke\u010f\u017ee stav `HZZ` je rovn\u00fd 1, tak stav `_HZ` vypo\u010d\u00edtame obdobne ako predch\u00e1dzaj\u00faci, teda ako $\\tfrac{1}{2} + \\frac{1}{4}p$. Z\u00e1rove\u0148 je rovn\u00fd $p$, lebo tak sme ho ozna\u010dili na za\u010diatku. Ak d\u00e1me tieto dva v\u00fdsledky do rovnosti, dost\u00e1vame $p = \\tfrac{1}{2} + \\tfrac{1}{4}p$ a vypo\u010d\u00edtame $p = \\tfrac{2}{3}.$\n\nSt\u00e1le n\u00e1m e\u0161te ch\u00fdba vypo\u010d\u00edta\u0165 pravdepodobnos\u0165 v\u00fdhry zo za\u010diato\u010dnej poz\u00edcie. Na to n\u00e1m e\u0161te ch\u00fdba pravdepodobnos\u0165 v stave `__Z`, ktor\u00e1 je ale rovnak\u00e1 ako v stave `_ZH`, teda $\\tfrac{1}{2}p$, \u010do je $\\tfrac{1}{3}$.\n\nPravdepodobnos\u0165 v za\u010diatku si teda m\u00f4\u017eme vypo\u010d\u00edta\u0165 zo stavov `__H` a `__Z` a dost\u00e1vame $\\tfrac{1}{2}\\cdot\\tfrac{1}{3} + \\tfrac{1}{2}\\cdot\\tfrac{2}{3} = \\tfrac{1}{2}$\n\nV predch\u00e1dzaj\u00facej \u010dasti sme spravili ve\u013ea v\u00fdpo\u010dtov v porad\u00ed, ktor\u00e9 m\u00f4\u017ee vyzera\u0165 aj ako n\u00e1hodn\u00e9. Ak ste zvl\u00e1dli tento postup sledova\u0165, super. Ale je celkom pochopite\u013en\u00e9, ak ste sa v tom n\u00e1hodou stratili. Niektor\u00ed maj\u00fa rad\u0161ej systematickej\u0161\u00ed postup, ktor\u00fd si uk\u00e1\u017eeme ako \u010fal\u0161\u00ed.\n\n#### Rie\u0161enie 2\n\nOzna\u010dme si pravdepodobnosti v\u00fdhry prv\u00e9ho hr\u00e1\u010da vo vrcholoch ako $P(x)$. Napr\u00edklad vieme, \u017ee \n\n$$P(\\mathrm{HZZ}) \\quad=\\quad 1  \\qquad\\qquad\\mathrm{a}\\qquad\\qquad P(\\mathrm{ZHZ}) \\quad=\\quad 0,$$\n\npreto\u017ee prv\u00fd hr\u00e1\u010d vyhral v situ\u00e1cii `HZZ` a prehral v situ\u00e1cii `ZHZ`.\n\nNap\u00ed\u0161me si teraz \u0161\u00edpky ako rovnice medzi t\u00fdmito pravdepodobnos\u0165ami. Prepisovan\u00edm \u0161\u00edpok zhora dole dost\u00e1vame\n\n\\begin{align}\nP(\\mathrm{\\_HZ}) \\quad&=\\quad \\tfrac{1}{2}P(\\mathrm{HZZ}) + \\tfrac{1}{2} P(\\mathrm{\\_ZH}) \\quad=\\quad \\tfrac{1}{2} + \\tfrac{1}{2}P(\\mathrm{\\_ZH})\\\\\nP(\\mathrm{\\_\\_H}) \\quad&=\\quad P(\\mathrm{\\_HZ}) \\\\\nP(\\mathrm{\\_ZH}) \\quad&=\\quad = \\tfrac{1}{2} P(\\mathrm{ZHZ}) + \\tfrac{1}{2} P(\\mathrm{\\_\\_H}) \\quad=\\quad \\tfrac{1}{2} P(\\mathrm{\\_\\_H}) \\\\\nP(\\mathrm{\\_\\_\\_}) \\quad&=\\quad \\tfrac{1}{2}P(\\mathrm{\\_\\_H}) + \\tfrac{1}{2}P(\\mathrm{\\_\\_Z}) \\\\\nP(\\mathrm{\\_\\_Z}) \\quad&=\\quad P(\\mathrm{\\_ZH})\n\\end{align}\n\nZ tejto s\u00fastavy rovn\u00edc u\u017e vieme dor\u00e1ta\u0165 v\u00fdsledok, \u00faplne priamo. M\u00f4\u017ete si to sk\u00fasi\u0165.\n\nT\u00fdmto sme ukon\u010dili uk\u00e1\u017ekov\u00e9 \u00falohy. Posledn\u00e1 bola trocha n\u00e1ro\u010dnej\u0161ia, ale d\u00fafame, \u017ee ste sa \u0148ou zvl\u00e1dli prek\u00fasa\u0165.\n\n# Dom\u00e1ca \u00faloha \u010d.1\nH\u00e1d\u017eeme mincou. Prv\u00fd hra\u010d vyhr\u00e1 ak padne po sebe 10 hl\u00e1v. Ak\u00fa postupnos\u0165 10 hodov si proti nemu m\u00e1 vybra\u0165 druh\u00fd hr\u00e1\u010d, aby mal \u010do najv\u00e4\u010d\u0161iu \u0161ancu vyhra\u0165? Ak\u00e1 je to \u0161anca?\n\n# Dom\u00e1ca \u00faloha \u010d.2\nH\u00e1d\u017eeme kockou namiesto mince. Prv\u00fd hr\u00e1\u010d vyhr\u00e1 ke\u010f padne postupne $2$, $1$, $5$. Ak\u00fa postupnos\u0165 troch \u010d\u00edsel si m\u00e1 vybra\u0165 druh\u00fd hr\u00e1\u010d, aby mal \u010do najv\u00e4\u010d\u0161iu \u0161ancu vyhra\u0165? Ak\u00e1 je to \u0161anca?\n\n# \u00daloha pre praktikov\nVymyslite si \u00falohu, ktor\u00fa viete vyrie\u0161i\u0165 pomocou svojich nov\u00fdch vedomost\u00ed. \n\n# \u00daloha pre brut\u00e1lnych\nSte prv\u00fd hr\u00e1\u010d na\u0161ej dne\u0161nej hry. Druh\u00fd hr\u00e1\u010d si vyberie n\u00e1hodne zo v\u0161etk\u00fdch 8 mo\u017en\u00fdch postupnost\u00ed d\u013a\u017eky 3. Ak\u00fa postupnos\u0165 d\u013a\u017eky 3 si vyberiete, aby ste mali v priemere \u010do najv\u00e4\u010d\u0161iu \u0161ancu vyhra\u0165?\n\n# \u00daloha pre akademikov\nH\u00e1d\u017eeme mincou. Prv\u00fd hr\u00e1\u010d si vyberie postupnos\u0165 d\u013a\u017eky $n$ v\u00fdsledkov hodov mincou a prezrad\u00ed n\u00e1m ju. Ak\u00fa postupnos\u0165 d\u013a\u017eky $n$ si m\u00e1m vybra\u0165 ako druh\u00fd hr\u00e1\u010d, aby som mal proti nemu \u010do najv\u00e4\u010d\u0161iu \u0161ancu vyhra\u0165?\n", "meta": {"hexsha": "6188807c539aeb64d42bffe77e4786f227c3b86a", "size": 107177, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/02_suboj_minci.ipynb", "max_stars_repo_name": "cedeerwe/slobodna-akademia", "max_stars_repo_head_hexsha": "10ea3ac5935da19419af5600934cc5df8b45a4f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-04-11T18:53:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-20T13:48:19.000Z", "max_issues_repo_path": "notebooks/02_suboj_minci.ipynb", "max_issues_repo_name": "cedeerwe/slobodna-akademia", "max_issues_repo_head_hexsha": "10ea3ac5935da19419af5600934cc5df8b45a4f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2019-07-21T17:54:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-24T20:37:25.000Z", "max_forks_repo_path": "notebooks/02_suboj_minci.ipynb", "max_forks_repo_name": "cedeerwe/brutalna-akademia", "max_forks_repo_head_hexsha": "10ea3ac5935da19419af5600934cc5df8b45a4f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.0244922342, "max_line_length": 16815, "alphanum_fraction": 0.5593830766, "converted": true, "num_tokens": 10374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.09534947132582736, "lm_q1q2_score": 0.039922528952822584}}
{"text": "# Circuit generation: tket example\n\nThis notebook will provide a brief introduction to some of the more advanced methods of circuit generation available in `pytket`, including:<br>\n* how to address wires and registers;<br>\n* reading in circuits from QASM and Quipper ASCII files;<br>\n* various types of 'boxes';<br>\n* composition of circuits (both 'horizontally' and 'vertically');<br>\n* use of symbolic gate parameters;<br>\n* representation of classically controlled gates.\n\n## Wires, unit IDs and registers\n\nLet's get started by constructing a circuit with 3 qubits and 2 classical bits:\n\n\n```python\nfrom pytket.circuit import Circuit\n```\n\n\n```python\nc = Circuit(3, 2)\nprint(c.qubits)\nprint(c.bits)\n```\n\nThe qubits have automatically been assigned to a register with name `q` and indices 0, 1 and 2, while the bits have been assigned to a register with name `c` and indices 0 and 1.<br>\n<br>\nWe can give these units arbitrary names and indices of arbitrary dimension:\n\n\n```python\nfrom pytket.circuit import Qubit\n```\n\n\n```python\nnew_q1 = Qubit(\"alpha\", 0)\nnew_q2 = Qubit(\"beta\", 2, 1)\nnew_q3 = Qubit(\"gamma\", (0, 0, 0))\nc.add_qubit(new_q1)\nc.add_qubit(new_q2)\nc.add_qubit(new_q3)\nprint(c.qubits)\n```\n\nWe can also add a new register of qubits in one go:\n\n\n```python\nc.add_q_register(\"delta\", 4)\nprint(c.qubits)\n```\n\nSimilar commands are available for classical bits.<br>\n<br>\nWe can add gates to the circuit as follows:\n\n\n```python\nc.CX(0, 1)\n```\n\nThis command appends a CX gate with control `q[0]` and target `q[1]`. Note that the integer arguments are automatically converted to the default unit IDs. For simple circuits it is often easiest to stick to the default register and refer to the qubits by integers. To add gates to our own named units, we simply pass the `Qubit` (or classical `Bit`) as an argument. (We can't mix the two conventions in one command, however.)\n\n\n```python\nc.H(new_q1)\nc.CX(Qubit(\"q\", 1), new_q2)\nc.Rz(0.5, new_q2)\nprint(c.get_commands())\n```\n\nLet's have a look at our circuit:\n\n\n```python\nprint(c.get_commands())\n```\n\n## Exporting to and importing from standard formats\n\nWe can export a `Circuit` to a file in QASM format. Conversely, if we have such a file we can import it into `pytket`. There are some limitations on the circuits that can be converted: for example, multi-dimensional indices (as in `beta` and `gamma` above) are not allowed.<br>\n<br>\nHere is a simple example:\n\n\n```python\nfrom pytket.qasm import circuit_to_qasm, circuit_from_qasm\n```\n\n\n```python\nc = Circuit(3, 1)\nc.H(0)\nc.CX(0, 1)\nc.CX(1, 2)\nc.Rz(0.25, 2)\nc.Measure(2, 0)\n```\n\n\n```python\nqasmfile = \"c.qasm\"\ncircuit_to_qasm(c, qasmfile)\n```\n\n\n```python\nwith open(qasmfile) as f:\n    print(f.read())\n```\n\n\n```python\nc1 = circuit_from_qasm(qasmfile)\nc == c1\n```\n\nWe can also import files in the Quipper ASCII format:\n\n\n```python\nfrom pytket.quipper import circuit_from_quipper\n```\n\n\n```python\nquipfile = \"c.quip\"\nwith open(quipfile, \"w\") as f:\n    f.write(\n        \"\"\"Inputs: 0:Qbit, 1:Qbit\nQGate[\"W\"](0,1)\nQGate[\"omega\"](1)\nQGate[\"swap\"](0,1)\nQGate[\"W\"]*(1,0)\nOutputs: 0:Qbit, 1:Qbit\n\"\"\"\n    )\n```\n\n\n```python\nc = circuit_from_quipper(quipfile)\nprint(c.get_commands())\n```\n\nNote that the Quipper gates that are not supported directly in `pytket` (`W` and `omega`) are translated into equivalent sequences of `pytket` gates.<br>\n<br>\nQuipper subroutines are also supported, corresponding to `CircBox` operations in `pytket`:\n\n\n```python\nwith open(quipfile, \"w\") as f:\n    f.write(\n        \"\"\"Inputs: 0:Qbit, 1:Qbit, 2:Qbit\nQGate[\"H\"](0)\nSubroutine(x2)[\"sub\", shape \"([Q,Q],())\"] (2,1) -> (2,1)\nQGate[\"H\"](1)\nOutputs: 0:Qbit, 1:Qbit, 2:Qbit\n```\n\n\n```python\nSubroutine: \"sub\"\nShape: \"([Q,Q],())\"\nControllable: no\nInputs: 0:Qbit, 1:Qbit\nQGate[\"Y\"](0)\nQGate[\"not\"](1) with controls=[+0]\nQGate[\"Z\"](1)\nOutputs: 0:Qbit, 1:Qbit\n\"\"\"\n    )\n```\n\n\n```python\nc = circuit_from_quipper(quipfile)\ncmds = c.get_commands()\nprint(cmds)\n```\n\n## Boxes\n\nThe `CircBox` is an example of a `pytket` 'box', which is a reusable encapsulation of a circuit inside another. We can recover the circuit 'inside' the box using the `get_circuit()` method:\n\n\n```python\nboxed_circuit = cmds[1].op.get_circuit()\nprint(boxed_circuit.get_commands())\n```\n\nThe `CircBox` is the most general type of box, implementing an arbitrary circuit. But `pytket` supports several other useful box types:<br>\n* `Unitary1qBox` (implementing an arbitrary $2 \\times 2$ unitary matrix);<br>\n* `Unitary2qBox` (implementing an arbitrary $4 \\times 4$ unitary matrix);<br>\n* `ExpBox` (implementing $e^{itA}$ for an arbitrary $4 \\times 4$ hermitian matrix $A$ and parameter $t$);<br>\n* `PauliExpBox` (implementing $e^{-\\frac{1}{2} i \\pi t (\\sigma_0 \\otimes \\sigma_1 \\otimes \\cdots)}$ for arbitrary Pauli operators $\\sigma_i \\in \\{\\mathrm{I}, \\mathrm{X}, \\mathrm{Y}, \\mathrm{Z}\\}$ and parameter $t$).\n\nAn example will illustrate how these various box types are added to a circuit:\n\n\n```python\nfrom pytket.circuit import CircBox, Unitary1qBox, Unitary2qBox, ExpBox, PauliExpBox\nfrom pytket.pauli import Pauli\nimport numpy as np\nfrom math import sqrt\n```\n\n\n```python\nboxycirc = Circuit(3)\n```\n\nAdd a `CircBox`:\n\n\n```python\nsubcirc = Circuit(2)\nsubcirc.X(0).Y(1).CZ(0, 1)\ncbox = CircBox(subcirc)\nboxycirc.add_circbox(cbox, args=[Qubit(0), Qubit(1)])\n```\n\nAdd a `Unitary1qBox`:\n\n\n```python\nm1 = np.asarray([[1 / 2, sqrt(3) / 2], [sqrt(3) / 2, -1 / 2]])\nm1box = Unitary1qBox(m1)\nboxycirc.add_unitary1qbox(m1box, 2)\n```\n\nAdd a `Unitary2qBox`:\n\n\n```python\nm2 = np.asarray([[0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0]])\nm2box = Unitary2qBox(m2)\nboxycirc.add_unitary2qbox(m2box, 1, 2)\n```\n\nAdd an `ExpBox`:\n\n\n```python\nA = np.asarray(\n    [[1, 2, 3, 4 + 1j], [2, 0, 1j, -1], [3, -1j, 2, 1j], [4 - 1j, -1, -1j, 1]]\n)\nebox = ExpBox(A, 0.5)\nboxycirc.add_expbox(ebox, 0, 1)\n```\n\nAdd a `PauliExpBox`:\n\n\n```python\npbox = PauliExpBox([Pauli.X, Pauli.Z, Pauli.X], 0.75)\nboxycirc.add_pauliexpbox(pbox, [0, 1, 2])\n```\n\n\n```python\nprint(boxycirc.get_commands())\n```\n\nThe `get_circuit()` method is available for all box types, and returns a `Circuit` object. For example:\n\n\n```python\nprint(pbox.get_circuit().get_commands())\n```\n\n## Circuit composition\n\nCircuits can be composed either serially, whereby wires are joined together, or in parallel, using the `append()` command.<br>\n<br>\nFor a simple illustration of serial composition, let's create two circuits with compatible set of wires, and append the second to the first:\n\n\n```python\nc = Circuit(2)\nc.CX(0, 1)\n```\n\n\n```python\nc1 = Circuit(2)\nc1.CZ(1, 0)\n```\n\n\n```python\nc.append(c1)\n```\n\n\n```python\nprint(c.get_commands())\n```\n\nIn the above example, there was a one-to-one match between the unit IDs in the two circuits, and they were matched up accordingly. The same applied with named unit IDs:\n\n\n```python\nx, y = Qubit(\"x\"), Qubit(\"y\")\n```\n\n\n```python\nc = Circuit()\nc.add_qubit(x)\nc.add_qubit(y)\nc.CX(x, y)\n```\n\n\n```python\nc1 = Circuit()\nc1.add_qubit(x)\nc1.add_qubit(y)\nc1.CZ(y, x)\n```\n\n\n```python\nc.append(c1)\n```\n\n\n```python\nprint(c.get_commands())\n```\n\nIf either circuit contains wires not matching any wires in the other, those are added to the other circuit before composition:\n\n\n```python\nz = Qubit(\"z\")\nc1.add_qubit(z)\nc1.CY(y, z)\nc.append(c1)\nprint(c.qubits)\nprint(c.get_commands())\n```\n\nIf the sets of unit IDs for the two circuits are disjoint, then the composition is entirely parallel.<br>\n<br>\nWhat if we want to serially compose two circuits having different sets of `Qubit`? In that case, we can use the `rename_units()` method on one or other of them to bring them into line. This method takes a dictionary mapping current unit IDs to new one:\n\n\n```python\nc2 = Circuit()\nc2.add_q_register(\"w\", 3)\nw = [Qubit(\"w\", i) for i in range(3)]\nc2.H(w[0]).CX(w[0], w[1]).CRz(0.25, w[1], w[2])\n```\n\n\n```python\nc.rename_units({x: w[0], y: w[1], z: w[2]})\n```\n\n\n```python\nc.append(c2)\n```\n\n\n```python\nprint(c.get_commands())\n```\n\n## Symbolic parameters\n\nMany of the gates supported by `pytket` are parametrized by one or more phase parameters, which represent rotations in multiples of $\\pi$. For example, $\\mathrm{Rz}(\\frac{1}{2})$ represents a quarter turn, i.e. a rotation of $\\pi/2$, about the Z axis. If we know the values of these parameters we can add the gates directly to our circuit:\n\n\n```python\nc = Circuit(1)\nc.Rz(0.5, 0)\n```\n\nHowever, we may wish to construct and manipulate circuits containing such parametrized gates without specifying the values. This allows us to do calculations in a general setting, only later substituting values for the parameters.<br>\n<br>\nThus `pytket` allows us to specify any of the parameters as symbols. All manipulations (such as combination and cancellation of gates) are performed on the symbolic representation:\n\n\n```python\nfrom sympy import Symbol\n```\n\n\n```python\na = Symbol(\"a\")\nc.Rz(a, 0)\n```\n\n\n```python\nprint(c.get_commands())\n```\n\nWhen we apply any transformation to this circuit, the symbolic parameter is preserved in the result:\n\n\n```python\nfrom pytket.transform import Transform\n```\n\n\n```python\nTransform.RemoveRedundancies().apply(c)\n```\n\n\n```python\nprint(c.get_commands())\n```\n\nTo substitute values for symbols, we use the `symbol_substitution()` method, supplying a dictionary from symbols to values:\n\n\n```python\nc.symbol_substitution({a: 0.75})\n```\n\n\n```python\nprint(c.get_commands())\n```\n\nWe can also substitute symbols for other symbols:\n\n\n```python\nb = Symbol(\"b\")\nc = Circuit(1)\nc.Rz(a + b, 0)\nc.symbol_substitution({b: 2 * a})\nprint(c.get_commands())\n```\n\n## Custom gates\n\nWe can define custom parametrized gates in `pytket` by first setting up a circuit containing symbolic parameters and then converting this to a parametrized operation type:\n\n\n```python\nfrom pytket.circuit import CustomGateDef\n```\n\n\n```python\na = Symbol(\"a\")\nb = Symbol(\"b\")\nsetup = Circuit(3)\nsetup.CX(0, 1)\nsetup.Rz(a + 0.5, 2)\nsetup.CRz(b, 0, 2)\nmy_gate = CustomGateDef.define(\"g\", setup, [a, b])\nc = Circuit(4)\nc.add_custom_gate(my_gate, [0.2, 1.3], [0, 3, 1])\nprint(c.get_commands())\n```\n\nCustom gates can also receive symbolic parameters:\n\n\n```python\nx = Symbol(\"x\")\nc.add_custom_gate(my_gate, [x, 1.0], [0, 1, 2])\nprint(c.get_commands())\n```\n\n## Decomposing boxes and custom gates\n\nHaving defined a circuit containing custom gates, we may now want to decompose it into elementary gates. The `DecomposeBoxes()` transform allows us to do this:\n\n\n```python\nTransform.DecomposeBoxes().apply(c)\nprint(c.get_commands())\n```\n\nThe same transform works on circuits composed of arbitrary boxes. Let's try it on a copy of the circuit we built up earlier out of various box types.\n\n\n```python\nc = boxycirc.copy()\nTransform.DecomposeBoxes().apply(c)\nprint(c.get_commands())\n```\n\nNote that the unitaries have been decomposed into elementary gates.\n\n## Classical controls\n\nMost of the examples above involve only pure quantum gates. However, `pytket` can also represent gates whose operation is conditional on one or more classical inputs.<br>\n<br>\nFor example, suppose we want to run the complex circuit `c` we've just constructed, then measure qubits 0 and 1, and finally apply an $\\mathrm{Rz}(\\frac{1}{2})$ rotation to qubit 2 if and only if the measurements were 0 and 1 respectively.<br>\n<br>\nFirst, we'll add two classical wires to the circuit to store the measurement results:\n\n\n```python\nfrom pytket.circuit import Bit\n```\n\n\n```python\nc.add_c_register(\"m\", 2)\nm = [Bit(\"m\", i) for i in range(2)]\n```\n\nClassically conditioned operations depend on all their inputs being 1. Since we want to condition on `m[0]` being 0, we must first apply an X gate to its qubit, and then measure:\n\n\n```python\nq = [Qubit(\"q\", i) for i in range(3)]\nc.X(q[0])\nc.Measure(q[0], m[0])\nc.Measure(q[1], m[1])\n```\n\nFinally we add the classically conditioned Rz operation, using the `add_gate()` method:\n\n\n```python\nfrom pytket.circuit import OpType\n```\n\n\n```python\nc.add_gate(OpType.Rz, [0.5], [q[2]], condition_bits=[m[0], m[1]], condition_value=3)\n```\n\nNote that many of the transforms and compilation passes will not accept circuits that contain classical controls.\n", "meta": {"hexsha": "ada5e706a64a49985d564a81abc87a2c8a22d7d1", "size": 20749, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/circuit_generation_example.ipynb", "max_stars_repo_name": "CQCL/pytket", "max_stars_repo_head_hexsha": "44fa95eb060afc8c45598f89afda993aa2d06634", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 249, "max_stars_repo_stars_event_min_datetime": "2018-07-20T03:04:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:45:58.000Z", "max_issues_repo_path": "examples/circuit_generation_example.ipynb", "max_issues_repo_name": "CQCL/pytket", "max_issues_repo_head_hexsha": "44fa95eb060afc8c45598f89afda993aa2d06634", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 67, "max_issues_repo_issues_event_min_datetime": "2018-08-03T09:38:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T09:39:45.000Z", "max_forks_repo_path": "examples/circuit_generation_example.ipynb", "max_forks_repo_name": "CQCL/pytket", "max_forks_repo_head_hexsha": "44fa95eb060afc8c45598f89afda993aa2d06634", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 69, "max_forks_repo_forks_event_min_datetime": "2019-02-26T15:15:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T14:47:24.000Z", "avg_line_length": 20749.0, "max_line_length": 20749, "alphanum_fraction": 0.6354041159, "converted": true, "num_tokens": 3676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926492132671, "lm_q2_score": 0.08882030144488992, "lm_q1q2_score": 0.03991519057024006}}
{"text": "```python\n%matplotlib inline\n```\n\n\nTrain a Mario-playing RL Agent\n================\n\nAuthors: `Yuansong Feng <https://github.com/YuansongFeng>`__, `Suraj\nSubramanian <https://github.com/suraj813>`__, `Howard\nWang <https://github.com/hw26>`__, `Steven\nGuo <https://github.com/GuoYuzhang>`__.\n\n\nThis tutorial walks you through the fundamentals of Deep Reinforcement\nLearning. At the end, you will implement an AI-powered Mario (using\n`Double Deep Q-Networks <https://arxiv.org/pdf/1509.06461.pdf>`__) that\ncan play the game by itself.\n\nAlthough no prior knowledge of RL is necessary for this tutorial, you\ncan familiarize yourself with these RL\n`concepts <https://spinningup.openai.com/en/latest/spinningup/rl_intro.html>`__,\nand have this handy\n`cheatsheet <https://colab.research.google.com/drive/1eN33dPVtdPViiS1njTW_-r-IYCDTFU7N>`__\nas your companion. The full code is available\n`here <https://github.com/yuansongFeng/MadMario/>`__.\n\n.. figure:: /_static/img/mario.gif\n   :alt: mario\n\n\n\n\n\n```python\n# !pip install gym-super-mario-bros==7.3.0\n\nimport torch\nfrom torch import nn\nfrom torchvision import transforms as T\nfrom PIL import Image\nimport numpy as np\nfrom pathlib import Path\nfrom collections import deque\nimport random, datetime, os, copy\n\n# Gym is an OpenAI toolkit for RL\nimport gym\nfrom gym.spaces import Box\nfrom gym.wrappers import FrameStack\n\n# NES Emulator for OpenAI Gym\nfrom nes_py.wrappers import JoypadSpace\n\n# Super Mario environment for OpenAI Gym\nimport gym_super_mario_bros\n```\n\nRL Definitions\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n**Environment** The world that an agent interacts with and learns from.\n\n**Action** $a$ : How the Agent responds to the Environment. The\nset of all possible Actions is called *action-space*.\n\n**State** $s$ : The current characteristic of the Environment. The\nset of all possible States the Environment can be in is called\n*state-space*.\n\n**Reward** $r$ : Reward is the key feedback from Environment to\nAgent. It is what drives the Agent to learn and to change its future\naction. An aggregation of rewards over multiple time steps is called\n**Return**.\n\n**Optimal Action-Value function** $Q^*(s,a)$ : Gives the expected\nreturn if you start in state $s$, take an arbitrary action\n$a$, and then for each future time step take the action that\nmaximizes returns. $Q$ can be said to stand for the \u201cquality\u201d of\nthe action in a state. We try to approximate this function.\n\n\n\n\nEnvironment\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\nInitialize Environment\n------------------------\n\nIn Mario, the environment consists of tubes, mushrooms and other\ncomponents.\n\nWhen Mario makes an action, the environment responds with the changed\n(next) state, reward and other info.\n\n\n\n\n\n```python\n# Initialize Super Mario environment\nenv = gym_super_mario_bros.make(\"SuperMarioBros-1-1-v0\")\n\n# Limit the action-space to\n#   0. walk right\n#   1. jump right\nenv = JoypadSpace(env, [[\"right\"], [\"right\", \"A\"]])\n\nenv.reset()\nnext_state, reward, done, info = env.step(action=0)\nprint(f\"{next_state.shape},\\n {reward},\\n {done},\\n {info}\")\n```\n\nPreprocess Environment\n------------------------\n\nEnvironment data is returned to the agent in ``next_state``. As you saw\nabove, each state is represented by a ``[3, 240, 256]`` size array.\nOften that is more information than our agent needs; for instance,\nMario\u2019s actions do not depend on the color of the pipes or the sky!\n\nWe use **Wrappers** to preprocess environment data before sending it to\nthe agent.\n\n``GrayScaleObservation`` is a common wrapper to transform an RGB image\nto grayscale; doing so reduces the size of the state representation\nwithout losing useful information. Now the size of each state:\n``[1, 240, 256]``\n\n``ResizeObservation`` downsamples each observation into a square image.\nNew size: ``[1, 84, 84]``\n\n``SkipFrame`` is a custom wrapper that inherits from ``gym.Wrapper`` and\nimplements the ``step()`` function. Because consecutive frames don\u2019t\nvary much, we can skip n-intermediate frames without losing much\ninformation. The n-th frame aggregates rewards accumulated over each\nskipped frame.\n\n``FrameStack`` is a wrapper that allows us to squash consecutive frames\nof the environment into a single observation point to feed to our\nlearning model. This way, we can identify if Mario was landing or\njumping based on the direction of his movement in the previous several\nframes.\n\n\n\n\n\n```python\nclass SkipFrame(gym.Wrapper):\n    def __init__(self, env, skip):\n        \"\"\"Return only every `skip`-th frame\"\"\"\n        super().__init__(env)\n        self._skip = skip\n\n    def step(self, action):\n        \"\"\"Repeat action, and sum reward\"\"\"\n        total_reward = 0.0\n        done = False\n        for i in range(self._skip):\n            # Accumulate reward and repeat the same action\n            obs, reward, done, info = self.env.step(action)\n            total_reward += reward\n            if done:\n                break\n        return obs, total_reward, done, info\n\n\nclass GrayScaleObservation(gym.ObservationWrapper):\n    def __init__(self, env):\n        super().__init__(env)\n        obs_shape = self.observation_space.shape[:2]\n        self.observation_space = Box(low=0, high=255, shape=obs_shape, dtype=np.uint8)\n\n    def permute_orientation(self, observation):\n        # permute [H, W, C] array to [C, H, W] tensor\n        observation = np.transpose(observation, (2, 0, 1))\n        observation = torch.tensor(observation.copy(), dtype=torch.float)\n        return observation\n\n    def observation(self, observation):\n        observation = self.permute_orientation(observation)\n        transform = T.Grayscale()\n        observation = transform(observation)\n        return observation\n\n\nclass ResizeObservation(gym.ObservationWrapper):\n    def __init__(self, env, shape):\n        super().__init__(env)\n        if isinstance(shape, int):\n            self.shape = (shape, shape)\n        else:\n            self.shape = tuple(shape)\n\n        obs_shape = self.shape + self.observation_space.shape[2:]\n        self.observation_space = Box(low=0, high=255, shape=obs_shape, dtype=np.uint8)\n\n    def observation(self, observation):\n        transforms = T.Compose(\n            [T.Resize(self.shape), T.Normalize(0, 255)]\n        )\n        observation = transforms(observation).squeeze(0)\n        return observation\n\n\n# Apply Wrappers to environment\nenv = SkipFrame(env, skip=4)\nenv = GrayScaleObservation(env)\nenv = ResizeObservation(env, shape=84)\nenv = FrameStack(env, num_stack=4)\n```\n\nAfter applying the above wrappers to the environment, the final wrapped\nstate consists of 4 gray-scaled consecutive frames stacked together, as\nshown above in the image on the left. Each time Mario makes an action,\nthe environment responds with a state of this structure. The structure\nis represented by a 3-D array of size ``[4, 84, 84]``.\n\n.. figure:: /_static/img/mario_env.png\n   :alt: picture\n\n\n\n\n\nAgent\n\"\"\"\"\"\"\"\"\"\n\nWe create a class ``Mario`` to represent our agent in the game. Mario\nshould be able to:\n\n-  **Act** according to the optimal action policy based on the current\n   state (of the environment).\n\n-  **Remember** experiences. Experience = (current state, current\n   action, reward, next state). Mario *caches* and later *recalls* his\n   experiences to update his action policy.\n\n-  **Learn** a better action policy over time\n\n\n\n\n\n```python\nclass Mario:\n    def __init__():\n        pass\n\n    def act(self, state):\n        \"\"\"Given a state, choose an epsilon-greedy action\"\"\"\n        pass\n\n    def cache(self, experience):\n        \"\"\"Add the experience to memory\"\"\"\n        pass\n\n    def recall(self):\n        \"\"\"Sample experiences from memory\"\"\"\n        pass\n\n    def learn(self):\n        \"\"\"Update online action value (Q) function with a batch of experiences\"\"\"\n        pass\n```\n\nIn the following sections, we will populate Mario\u2019s parameters and\ndefine his functions.\n\n\n\n\nAct\n--------------\n\nFor any given state, an agent can choose to do the most optimal action\n(**exploit**) or a random action (**explore**).\n\nMario randomly explores with a chance of ``self.exploration_rate``; when\nhe chooses to exploit, he relies on ``MarioNet`` (implemented in\n``Learn`` section) to provide the most optimal action.\n\n\n\n\n\n```python\nclass Mario:\n    def __init__(self, state_dim, action_dim, save_dir):\n        self.state_dim = state_dim\n        self.action_dim = action_dim\n        self.save_dir = save_dir\n\n        self.use_cuda = torch.cuda.is_available()\n\n        # Mario's DNN to predict the most optimal action - we implement this in the Learn section\n        self.net = MarioNet(self.state_dim, self.action_dim).float()\n        if self.use_cuda:\n            self.net = self.net.to(device=\"cuda\")\n\n        self.exploration_rate = 1\n        self.exploration_rate_decay = 0.99999975\n        self.exploration_rate_min = 0.1\n        self.curr_step = 0\n\n        self.save_every = 5e5  # no. of experiences between saving Mario Net\n\n    def act(self, state):\n        \"\"\"\n    Given a state, choose an epsilon-greedy action and update value of step.\n\n    Inputs:\n    state(LazyFrame): A single observation of the current state, dimension is (state_dim)\n    Outputs:\n    action_idx (int): An integer representing which action Mario will perform\n    \"\"\"\n        # EXPLORE\n        if np.random.rand() < self.exploration_rate:\n            action_idx = np.random.randint(self.action_dim)\n\n        # EXPLOIT\n        else:\n            state = state.__array__()\n            if self.use_cuda:\n                state = torch.tensor(state).cuda()\n            else:\n                state = torch.tensor(state)\n            state = state.unsqueeze(0)\n            action_values = self.net(state, model=\"online\")\n            action_idx = torch.argmax(action_values, axis=1).item()\n\n        # decrease exploration_rate\n        self.exploration_rate *= self.exploration_rate_decay\n        self.exploration_rate = max(self.exploration_rate_min, self.exploration_rate)\n\n        # increment step\n        self.curr_step += 1\n        return action_idx\n```\n\nCache and Recall\n----------------------\n\nThese two functions serve as Mario\u2019s \u201cmemory\u201d process.\n\n``cache()``: Each time Mario performs an action, he stores the\n``experience`` to his memory. His experience includes the current\n*state*, *action* performed, *reward* from the action, the *next state*,\nand whether the game is *done*.\n\n``recall()``: Mario randomly samples a batch of experiences from his\nmemory, and uses that to learn the game.\n\n\n\n\n\n```python\nclass Mario(Mario):  # subclassing for continuity\n    def __init__(self, state_dim, action_dim, save_dir):\n        super().__init__(state_dim, action_dim, save_dir)\n        self.memory = deque(maxlen=100000)\n        self.batch_size = 32\n\n    def cache(self, state, next_state, action, reward, done):\n        \"\"\"\n        Store the experience to self.memory (replay buffer)\n\n        Inputs:\n        state (LazyFrame),\n        next_state (LazyFrame),\n        action (int),\n        reward (float),\n        done(bool))\n        \"\"\"\n        state = state.__array__()\n        next_state = next_state.__array__()\n\n        if self.use_cuda:\n            state = torch.tensor(state).cuda()\n            next_state = torch.tensor(next_state).cuda()\n            action = torch.tensor([action]).cuda()\n            reward = torch.tensor([reward]).cuda()\n            done = torch.tensor([done]).cuda()\n        else:\n            state = torch.tensor(state)\n            next_state = torch.tensor(next_state)\n            action = torch.tensor([action])\n            reward = torch.tensor([reward])\n            done = torch.tensor([done])\n\n        self.memory.append((state, next_state, action, reward, done,))\n\n    def recall(self):\n        \"\"\"\n        Retrieve a batch of experiences from memory\n        \"\"\"\n        batch = random.sample(self.memory, self.batch_size)\n        state, next_state, action, reward, done = map(torch.stack, zip(*batch))\n        return state, next_state, action.squeeze(), reward.squeeze(), done.squeeze()\n```\n\nLearn\n--------------\n\nMario uses the `DDQN algorithm <https://arxiv.org/pdf/1509.06461>`__\nunder the hood. DDQN uses two ConvNets - $Q_{online}$ and\n$Q_{target}$ - that independently approximate the optimal\naction-value function.\n\nIn our implementation, we share feature generator ``features`` across\n$Q_{online}$ and $Q_{target}$, but maintain separate FC\nclassifiers for each. $\\theta_{target}$ (the parameters of\n$Q_{target}$) is frozen to prevent updation by backprop. Instead,\nit is periodically synced with $\\theta_{online}$ (more on this\nlater).\n\nNeural Network\n~~~~~~~~~~~~~~~~~~\n\n\n\n\n```python\nclass MarioNet(nn.Module):\n    \"\"\"mini cnn structure\n  input -> (conv2d + relu) x 3 -> flatten -> (dense + relu) x 2 -> output\n  \"\"\"\n\n    def __init__(self, input_dim, output_dim):\n        super().__init__()\n        c, h, w = input_dim\n\n        if h != 84:\n            raise ValueError(f\"Expecting input height: 84, got: {h}\")\n        if w != 84:\n            raise ValueError(f\"Expecting input width: 84, got: {w}\")\n\n        self.online = nn.Sequential(\n            nn.Conv2d(in_channels=c, out_channels=32, kernel_size=8, stride=4),\n            nn.ReLU(),\n            nn.Conv2d(in_channels=32, out_channels=64, kernel_size=4, stride=2),\n            nn.ReLU(),\n            nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1),\n            nn.ReLU(),\n            nn.Flatten(),\n            nn.Linear(3136, 512),\n            nn.ReLU(),\n            nn.Linear(512, output_dim),\n        )\n\n        self.target = copy.deepcopy(self.online)\n\n        # Q_target parameters are frozen.\n        for p in self.target.parameters():\n            p.requires_grad = False\n\n    def forward(self, input, model):\n        if model == \"online\":\n            return self.online(input)\n        elif model == \"target\":\n            return self.target(input)\n```\n\nTD Estimate & TD Target\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nTwo values are involved in learning:\n\n**TD Estimate** - the predicted optimal $Q^*$ for a given state\n$s$\n\n\\begin{align}{TD}_e = Q_{online}^*(s,a)\\end{align}\n\n**TD Target** - aggregation of current reward and the estimated\n$Q^*$ in the next state $s'$\n\n\\begin{align}a' = argmax_{a} Q_{online}(s', a)\\end{align}\n\n\\begin{align}{TD}_t = r + \\gamma Q_{target}^*(s',a')\\end{align}\n\nBecause we don\u2019t know what next action $a'$ will be, we use the\naction $a'$ maximizes $Q_{online}$ in the next state\n$s'$.\n\nNotice we use the\n`@torch.no_grad() <https://pytorch.org/docs/stable/generated/torch.no_grad.html#no-grad>`__\ndecorator on ``td_target()`` to disable gradient calculations here\n(because we don\u2019t need to backpropagate on $\\theta_{target}$).\n\n\n\n\n\n```python\nclass Mario(Mario):\n    def __init__(self, state_dim, action_dim, save_dir):\n        super().__init__(state_dim, action_dim, save_dir)\n        self.gamma = 0.9\n\n    def td_estimate(self, state, action):\n        current_Q = self.net(state, model=\"online\")[\n            np.arange(0, self.batch_size), action\n        ]  # Q_online(s,a)\n        return current_Q\n\n    @torch.no_grad()\n    def td_target(self, reward, next_state, done):\n        next_state_Q = self.net(next_state, model=\"online\")\n        best_action = torch.argmax(next_state_Q, axis=1)\n        next_Q = self.net(next_state, model=\"target\")[\n            np.arange(0, self.batch_size), best_action\n        ]\n        return (reward + (1 - done.float()) * self.gamma * next_Q).float()\n```\n\nUpdating the model\n~~~~~~~~~~~~~~~~~~~~~~\n\nAs Mario samples inputs from his replay buffer, we compute $TD_t$\nand $TD_e$ and backpropagate this loss down $Q_{online}$ to\nupdate its parameters $\\theta_{online}$ ($\\alpha$ is the\nlearning rate ``lr`` passed to the ``optimizer``)\n\n\\begin{align}\\theta_{online} \\leftarrow \\theta_{online} + \\alpha \\nabla(TD_e - TD_t)\\end{align}\n\n$\\theta_{target}$ does not update through backpropagation.\nInstead, we periodically copy $\\theta_{online}$ to\n$\\theta_{target}$\n\n\\begin{align}\\theta_{target} \\leftarrow \\theta_{online}\\end{align}\n\n\n\n\n\n\n```python\nclass Mario(Mario):\n    def __init__(self, state_dim, action_dim, save_dir):\n        super().__init__(state_dim, action_dim, save_dir)\n        self.optimizer = torch.optim.Adam(self.net.parameters(), lr=0.00025)\n        self.loss_fn = torch.nn.SmoothL1Loss()\n\n    def update_Q_online(self, td_estimate, td_target):\n        loss = self.loss_fn(td_estimate, td_target)\n        self.optimizer.zero_grad()\n        loss.backward()\n        self.optimizer.step()\n        return loss.item()\n\n    def sync_Q_target(self):\n        self.net.target.load_state_dict(self.net.online.state_dict())\n```\n\nSave checkpoint\n~~~~~~~~~~~~~~~~~~\n\n\n\n\n\n```python\nclass Mario(Mario):\n    def save(self):\n        save_path = (\n            self.save_dir / f\"mario_net_{int(self.curr_step // self.save_every)}.chkpt\"\n        )\n        torch.save(\n            dict(model=self.net.state_dict(), exploration_rate=self.exploration_rate),\n            save_path,\n        )\n        print(f\"MarioNet saved to {save_path} at step {self.curr_step}\")\n```\n\nPutting it all together\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\n\n\n\n```python\nclass Mario(Mario):\n    def __init__(self, state_dim, action_dim, save_dir):\n        super().__init__(state_dim, action_dim, save_dir)\n        self.burnin = 1e4  # min. experiences before training\n        self.learn_every = 3  # no. of experiences between updates to Q_online\n        self.sync_every = 1e4  # no. of experiences between Q_target & Q_online sync\n\n    def learn(self):\n        if self.curr_step % self.sync_every == 0:\n            self.sync_Q_target()\n\n        if self.curr_step % self.save_every == 0:\n            self.save()\n\n        if self.curr_step < self.burnin:\n            return None, None\n\n        if self.curr_step % self.learn_every != 0:\n            return None, None\n\n        # Sample from memory\n        state, next_state, action, reward, done = self.recall()\n\n        # Get TD Estimate\n        td_est = self.td_estimate(state, action)\n\n        # Get TD Target\n        td_tgt = self.td_target(reward, next_state, done)\n\n        # Backpropagate loss through Q_online\n        loss = self.update_Q_online(td_est, td_tgt)\n\n        return (td_est.mean().item(), loss)\n```\n\nLogging\n--------------\n\n\n\n\n\n```python\nimport numpy as np\nimport time, datetime\nimport matplotlib.pyplot as plt\n\n\nclass MetricLogger:\n    def __init__(self, save_dir):\n        self.save_log = save_dir / \"log\"\n        with open(self.save_log, \"w\") as f:\n            f.write(\n                f\"{'Episode':>8}{'Step':>8}{'Epsilon':>10}{'MeanReward':>15}\"\n                f\"{'MeanLength':>15}{'MeanLoss':>15}{'MeanQValue':>15}\"\n                f\"{'TimeDelta':>15}{'Time':>20}\\n\"\n            )\n        self.ep_rewards_plot = save_dir / \"reward_plot.jpg\"\n        self.ep_lengths_plot = save_dir / \"length_plot.jpg\"\n        self.ep_avg_losses_plot = save_dir / \"loss_plot.jpg\"\n        self.ep_avg_qs_plot = save_dir / \"q_plot.jpg\"\n\n        # History metrics\n        self.ep_rewards = []\n        self.ep_lengths = []\n        self.ep_avg_losses = []\n        self.ep_avg_qs = []\n\n        # Moving averages, added for every call to record()\n        self.moving_avg_ep_rewards = []\n        self.moving_avg_ep_lengths = []\n        self.moving_avg_ep_avg_losses = []\n        self.moving_avg_ep_avg_qs = []\n\n        # Current episode metric\n        self.init_episode()\n\n        # Timing\n        self.record_time = time.time()\n\n    def log_step(self, reward, loss, q):\n        self.curr_ep_reward += reward\n        self.curr_ep_length += 1\n        if loss:\n            self.curr_ep_loss += loss\n            self.curr_ep_q += q\n            self.curr_ep_loss_length += 1\n\n    def log_episode(self):\n        \"Mark end of episode\"\n        self.ep_rewards.append(self.curr_ep_reward)\n        self.ep_lengths.append(self.curr_ep_length)\n        if self.curr_ep_loss_length == 0:\n            ep_avg_loss = 0\n            ep_avg_q = 0\n        else:\n            ep_avg_loss = np.round(self.curr_ep_loss / self.curr_ep_loss_length, 5)\n            ep_avg_q = np.round(self.curr_ep_q / self.curr_ep_loss_length, 5)\n        self.ep_avg_losses.append(ep_avg_loss)\n        self.ep_avg_qs.append(ep_avg_q)\n\n        self.init_episode()\n\n    def init_episode(self):\n        self.curr_ep_reward = 0.0\n        self.curr_ep_length = 0\n        self.curr_ep_loss = 0.0\n        self.curr_ep_q = 0.0\n        self.curr_ep_loss_length = 0\n\n    def record(self, episode, epsilon, step):\n        mean_ep_reward = np.round(np.mean(self.ep_rewards[-100:]), 3)\n        mean_ep_length = np.round(np.mean(self.ep_lengths[-100:]), 3)\n        mean_ep_loss = np.round(np.mean(self.ep_avg_losses[-100:]), 3)\n        mean_ep_q = np.round(np.mean(self.ep_avg_qs[-100:]), 3)\n        self.moving_avg_ep_rewards.append(mean_ep_reward)\n        self.moving_avg_ep_lengths.append(mean_ep_length)\n        self.moving_avg_ep_avg_losses.append(mean_ep_loss)\n        self.moving_avg_ep_avg_qs.append(mean_ep_q)\n\n        last_record_time = self.record_time\n        self.record_time = time.time()\n        time_since_last_record = np.round(self.record_time - last_record_time, 3)\n\n        print(\n            f\"Episode {episode} - \"\n            f\"Step {step} - \"\n            f\"Epsilon {epsilon} - \"\n            f\"Mean Reward {mean_ep_reward} - \"\n            f\"Mean Length {mean_ep_length} - \"\n            f\"Mean Loss {mean_ep_loss} - \"\n            f\"Mean Q Value {mean_ep_q} - \"\n            f\"Time Delta {time_since_last_record} - \"\n            f\"Time {datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S')}\"\n        )\n\n        with open(self.save_log, \"a\") as f:\n            f.write(\n                f\"{episode:8d}{step:8d}{epsilon:10.3f}\"\n                f\"{mean_ep_reward:15.3f}{mean_ep_length:15.3f}{mean_ep_loss:15.3f}{mean_ep_q:15.3f}\"\n                f\"{time_since_last_record:15.3f}\"\n                f\"{datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S'):>20}\\n\"\n            )\n\n        for metric in [\"ep_rewards\", \"ep_lengths\", \"ep_avg_losses\", \"ep_avg_qs\"]:\n            plt.plot(getattr(self, f\"moving_avg_{metric}\"))\n            plt.savefig(getattr(self, f\"{metric}_plot\"))\n            plt.clf()\n```\n\nLet\u2019s play!\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\nIn this example we run the training loop for 10 episodes, but for Mario to truly learn the ways of\nhis world, we suggest running the loop for at least 40,000 episodes!\n\n\n\n\n\n```python\nuse_cuda = torch.cuda.is_available()\nprint(f\"Using CUDA: {use_cuda}\")\nprint()\n\nsave_dir = Path(\"checkpoints\") / datetime.datetime.now().strftime(\"%Y-%m-%dT%H-%M-%S\")\nsave_dir.mkdir(parents=True)\n\nmario = Mario(state_dim=(4, 84, 84), action_dim=env.action_space.n, save_dir=save_dir)\n\nlogger = MetricLogger(save_dir)\n\nepisodes = 10\nfor e in range(episodes):\n\n    state = env.reset()\n\n    # Play the game!\n    while True:\n\n        # Run agent on the state\n        action = mario.act(state)\n\n        # Agent performs action\n        next_state, reward, done, info = env.step(action)\n\n        # Remember\n        mario.cache(state, next_state, action, reward, done)\n\n        # Learn\n        q, loss = mario.learn()\n\n        # Logging\n        logger.log_step(reward, loss, q)\n\n        # Update state\n        state = next_state\n\n        # Check if end of game\n        if done or info[\"flag_get\"]:\n            break\n\n    logger.log_episode()\n\n    if e % 20 == 0:\n        logger.record(episode=e, epsilon=mario.exploration_rate, step=mario.curr_step)\n```\n\nConclusion\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\nIn this tutorial, we saw how we can use PyTorch to train a game-playing AI. You can use the same methods\nto train an AI to play any of the games at the `OpenAI gym <https://gym.openai.com/>`__. Hope you enjoyed this tutorial, feel free to reach us at\n`our github <https://github.com/yuansongFeng/MadMario/>`__!\n\n\n", "meta": {"hexsha": "3b86e0b2c63e3a5cc75b617ec2738c9f31d0998e", "size": 29241, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "PyTorch/Visual-Audio/Torchscript/mario_rl_tutorial.ipynb", "max_stars_repo_name": "MitchellTesla/Quantm", "max_stars_repo_head_hexsha": "57045e0ea9ee7b965ecd26e4a8d0c1902df65245", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-02-15T06:43:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T10:43:32.000Z", "max_issues_repo_path": "PyTorch/Visual-Audio/Torchscript/mario_rl_tutorial.ipynb", "max_issues_repo_name": "MitchellTesla/Quantm", "max_issues_repo_head_hexsha": "57045e0ea9ee7b965ecd26e4a8d0c1902df65245", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-19T12:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T12:32:49.000Z", "max_forks_repo_path": "PyTorch/Visual-Audio/Torchscript/mario_rl_tutorial.ipynb", "max_forks_repo_name": "MitchellTesla/Quantm", "max_forks_repo_head_hexsha": "57045e0ea9ee7b965ecd26e4a8d0c1902df65245", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-14T23:10:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T23:10:58.000Z", "avg_line_length": 98.1241610738, "max_line_length": 4074, "alphanum_fraction": 0.6023391813, "converted": true, "num_tokens": 5820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33458945452352534, "lm_q2_score": 0.11920293140927592, "lm_q1q2_score": 0.039884043797834834}}
{"text": "# OPTIMADE and *pymatgen*\n\n# What is *pymatgen*?\n\n[*pymatgen*](https://pymatgen.org) is a materials science analysis code written in the Python programming language. It helps power the [Materials Project](https://materialsproject.org)'s high-throughput DFT workflows. It supports integration with a wide variety of simulation codes and can perform many analysis tasks such as the generation of phase diagrams or diffraction patterns.\n\n# The motivation behind this tutorial\n\n**This tutorial is aimed either at:**\n\n* People who are already familiar with using *pymatgen* or the Materials Project\n    * In particular, anyone already using the Materials Project API through the `MPRester`, and who would like to start using the OPTIMADE API in a similar way\n\n* People who like using Python and think they might appreciate an interface like the one provided by *pymatgen*.\n    * *pymatgen* provides a lot of input/output routines (such as conversion to CIF, POSCAR, etc.) and analysis tools (such as determination of symmetry, analysis of possible bonds, etc.) that can be performed directly on structures retrieved from OPTIMADE providers.\n\n**What this tutorial is not:**\n\n* This is not necessarily the way everyone should be accessing OPTIMADE providers!\n    * This tool may be useful to you, or it may not be. There are a lot of good tools available in our community. You are encouraged to try out different tools and find the one that's most useful for your own work.\n\n* It is not currently the best way to access OPTIMADE APIs for advanced users.\n    * It is still under development.\n    * It is unit tested against several OPTIMADE providers but **some do not work yet**.\n    * It only currently supports information retrieval from `/v1/structures/` routes.\n\n# Pre-requisites\n\nThis tutorial is aimed at people who already have a basic understanding of Python, including how to import modules, the use of basic data structures like dictionaries and lists, and how to intantiate and use objects.\n\nIf you do not have this understanding of Python, this tutorial may help you become familiar, but you are highly encouraged to follow a dedicated Python course such as those provided by [Software Carpentry](https://software-carpentry.org).\n\n# Install pymatgen\n\nThis tutorial uses the Python programming language. It can be run on any computer with Python installed. For convenience, here we are running in Google's \"Colaboratory\" notebook environment.\n\nBefore we begin, we must install the `pymatgen` package:\n\n\n```python\n!pip install pymatgen pybtex\n```\n\n    Requirement already satisfied: pymatgen in /usr/local/lib/python3.7/dist-packages (2022.0.14)\n    Requirement already satisfied: pybtex in /usr/local/lib/python3.7/dist-packages (0.24.0)\n    Requirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.7/dist-packages (from pymatgen) (3.7.4.3)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen) (3.2.2)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen) (2.23.0)\n    Requirement already satisfied: plotly>=4.5.0 in /usr/local/lib/python3.7/dist-packages (from pymatgen) (5.3.1)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen) (0.8.9)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from pymatgen) (1.7.1)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen) (1.16.2)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from pymatgen) (1.1.5)\n    Requirement already satisfied: uncertainties>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from pymatgen) (3.1.6)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen) (2.6.2)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen) (2021.8.17)\n    Requirement already satisfied: scipy>=1.5.0 in /usr/local/lib/python3.7/dist-packages (from pymatgen) (1.7.1)\n    Requirement already satisfied: numpy>=1.20.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen) (1.21.2)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen) (0.17.16)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen) (3.3.0)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen) (0.10.0)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen) (2.8.2)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen) (2.4.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen) (1.3.1)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from cycler>=0.10->matplotlib>=1.5->pymatgen) (1.15.0)\n    Requirement already satisfied: tenacity>=6.2.0 in /usr/local/lib/python3.7/dist-packages (from plotly>=4.5.0->pymatgen) (8.0.1)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2 in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen) (0.2.6)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from uncertainties>=3.1.4->pymatgen) (0.16.0)\n    Requirement already satisfied: latexcodec>=1.0.4 in /usr/local/lib/python3.7/dist-packages (from pybtex) (2.0.1)\n    Requirement already satisfied: PyYAML>=3.01 in /usr/local/lib/python3.7/dist-packages (from pybtex) (3.13)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen) (2018.9)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen) (2021.5.30)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen) (2.10)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->pymatgen) (1.2.1)\n\n\nNext, let us **verify the correct version of *pymatgen* is installed**. This is good practice to do before starting out! For this tutorial we need version 2022.0.17 or above. We also need the `pybtex` package installed.\n\n\n```python\ntry:\n    from importlib_metadata import version\nexcept ImportError:\n    from importlib.metadata import version\n```\n\n\n```python\nversion(\"pymatgen\")\n```\n\n\n\n\n    '2022.0.14'\n\n\n\n# Import and learn about the `OptimadeRester`\n\nThe `OptimadeRester` is a class that is designed to retrieve data from an OPTIMADE provider and automatically convert the data into *pymatgen* `Structure` objects. These `Structure` objects are designed as a good intermediate format for crystallographic structure analysis, transformation and input/output.\n\nYou can read documentation on the `OptimadeRester` here: https://pymatgen.org/pymatgen.ext.optimade.html\n\n\n```python\nfrom pymatgen.ext.optimade import OptimadeRester\n```\n\nThe first step is to inspect the **documentation** for the `OptimadeRester`. We can run:\n\n\n```python\nOptimadeRester?\n```\n\n# Understanding \"aliases\" as shortcuts for accessing given providers\n\n\n```python\nOptimadeRester.aliases\n```\n\n\n\n\n    {'aflow': 'http://aflow.org/API/optimade/',\n     'cod': 'https://www.crystallography.net/cod/optimade',\n     'mcloud.2dstructures': 'https://aiida.materialscloud.org/2dstructures/optimade',\n     'mcloud.2dtopo': 'https://aiida.materialscloud.org/2dtopo/optimade',\n     'mcloud.curated-cofs': 'https://aiida.materialscloud.org/curated-cofs/optimade',\n     'mcloud.li-ion-conductors': 'https://aiida.materialscloud.org/li-ion-conductors/optimade',\n     'mcloud.optimade-sample': 'https://aiida.materialscloud.org/optimade-sample/optimade',\n     'mcloud.pyrene-mofs': 'https://aiida.materialscloud.org/pyrene-mofs/optimade',\n     'mcloud.scdm': 'https://aiida.materialscloud.org/autowannier/optimade',\n     'mcloud.sssp': 'https://aiida.materialscloud.org/sssplibrary/optimade',\n     'mcloud.stoceriaitf': 'https://aiida.materialscloud.org/stoceriaitf/optimade',\n     'mcloud.tc-applicability': 'https://aiida.materialscloud.org/tc-applicability/optimade',\n     'mcloud.threedd': 'https://aiida.materialscloud.org/3dd/optimade',\n     'mp': 'https://optimade.materialsproject.org',\n     'odbx': 'https://optimade.odbx.science',\n     'omdb.omdb_production': 'http://optimade.openmaterialsdb.se',\n     'oqmd': 'http://oqmd.org/optimade/',\n     'tcod': 'https://www.crystallography.net/tcod/optimade'}\n\n\n\nThese aliases are useful since they can provide a quick shorthand for a given database without having to remember a full URL.\n\nThis list of aliases is updated periodically. However, new OPTIMADE providers can be made available and will be listed at https://providers.optimade.org. The `OptimadeRester` can query the OPTIMADE providers list to refresh the available aliases.\n\nYou can do this as follows, but be aware this might take a few moments:\n\n\n```python\nopt = OptimadeRester()\nopt.refresh_aliases()\n```\n\n    Connecting to all known OPTIMADE providers, this will be slow. Please connect to only the OPTIMADE providers you want to query. Choose from: aflow, cod, mcloud.2dstructures, mcloud.2dtopo, mcloud.curated-cofs, mcloud.li-ion-conductors, mcloud.optimade-sample, mcloud.pyrene-mofs, mcloud.scdm, mcloud.sssp, mcloud.stoceriaitf, mcloud.tc-applicability, mcloud.threedd, mp, odbx, omdb.omdb_production, oqmd, tcod\n\n\n    \n    odbx: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 54/54 [00:19<00:00, 26.75it/s]\u001b[A\n\n# Connecting to one or more OPTIMADE providers\n\nLet's begin by connecting to the Materials Project (`mp`) and Materials Cloud \"2D Structures\" (`mcloud.2dstructures`) databases.\nBy default pymatgen expects a server to reply within 5 seconds, some servers however require up to several minutes to process a querry.\nYou can therefore set the timeout to a different value (in seconds) if you get a \"Read timed out\" error.\n\n\n```python\nopt = OptimadeRester([\"mp\", \"mcloud.2dstructures\"],timeout=10)\n```\n\nWe can find more information about the OPTIMADE providers we are connected to using the `describe()` method.\n\n\n```python\nprint(opt.describe())\n```\n\n    OptimadeRester connected to:\n    Provider(name='The Materials Project', base_url='https://optimade.materialsproject.org', description='The Materials Project OPTIMADE endpoint', homepage='https://materialsproject.org', prefix='mp')\n    Provider(name='Materials Cloud', base_url='https://aiida.materialscloud.org/3dd/optimade', description='A platform for Open Science built for seamless sharing of resources in computational materials science', homepage='https://materialscloud.org', prefix='mcloud')\n\n\n# Query for materials: binary nitrides case study\n\n`OptimadeRester` provides an `get_structures` method. **It does not support all features of OPTIMADE filters** but is a good place to get started.\n\nFor this case study, we will search for materials containing nitrogen and that have two elements.\n\n\n```python\nresults = opt.get_structures(elements=[\"N\"], nelements=2)\n```\n\n    \n    \n    \n    mp:   2%|\u258f         | 20/892 [00:00<?, ?it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:   4%|\u258d         | 40/892 [00:00<00:10, 80.59it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:   7%|\u258b         | 60/892 [00:00<00:16, 50.73it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:   9%|\u2589         | 80/892 [00:01<00:15, 52.98it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  11%|\u2588         | 100/892 [00:01<00:13, 57.95it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  13%|\u2588\u258e        | 120/892 [00:01<00:15, 50.05it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  16%|\u2588\u258c        | 140/892 [00:02<00:13, 54.44it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  18%|\u2588\u258a        | 160/892 [00:02<00:13, 54.04it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  20%|\u2588\u2588        | 180/892 [00:03<00:14, 47.85it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  22%|\u2588\u2588\u258f       | 200/892 [00:03<00:14, 46.13it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  25%|\u2588\u2588\u258d       | 220/892 [00:04<00:15, 44.63it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  27%|\u2588\u2588\u258b       | 240/892 [00:04<00:14, 43.67it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  29%|\u2588\u2588\u2589       | 260/892 [00:04<00:13, 46.71it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  31%|\u2588\u2588\u2588\u258f      | 280/892 [00:05<00:12, 49.17it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  34%|\u2588\u2588\u2588\u258e      | 300/892 [00:05<00:12, 46.48it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  36%|\u2588\u2588\u2588\u258c      | 320/892 [00:06<00:10, 52.24it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  38%|\u2588\u2588\u2588\u258a      | 340/892 [00:06<00:09, 56.87it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  40%|\u2588\u2588\u2588\u2588      | 360/892 [00:06<00:08, 59.89it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  43%|\u2588\u2588\u2588\u2588\u258e     | 380/892 [00:07<00:09, 52.13it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  45%|\u2588\u2588\u2588\u2588\u258d     | 400/892 [00:07<00:08, 55.45it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  47%|\u2588\u2588\u2588\u2588\u258b     | 420/892 [00:07<00:07, 59.55it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 892/892 [07:30<00:00,  1.94it/s]\n    mcloud.threedd: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 87/87 [07:13<00:00,  6.02s/it]\n    odbx: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 54/54 [00:30<00:00,  1.11it/s]\n    \n    \n    \n    mp:  52%|\u2588\u2588\u2588\u2588\u2588\u258f    | 460/892 [00:08<00:08, 50.54it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  54%|\u2588\u2588\u2588\u2588\u2588\u258d    | 480/892 [00:08<00:08, 48.59it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  56%|\u2588\u2588\u2588\u2588\u2588\u258c    | 500/892 [00:09<00:07, 52.73it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  58%|\u2588\u2588\u2588\u2588\u2588\u258a    | 520/892 [00:09<00:07, 52.49it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  61%|\u2588\u2588\u2588\u2588\u2588\u2588    | 540/892 [00:09<00:06, 56.16it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  63%|\u2588\u2588\u2588\u2588\u2588\u2588\u258e   | 560/892 [00:10<00:06, 55.00it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  65%|\u2588\u2588\u2588\u2588\u2588\u2588\u258c   | 580/892 [00:10<00:05, 58.61it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  67%|\u2588\u2588\u2588\u2588\u2588\u2588\u258b   | 600/892 [00:11<00:05, 57.08it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  70%|\u2588\u2588\u2588\u2588\u2588\u2588\u2589   | 620/892 [00:11<00:04, 56.17it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  72%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f  | 640/892 [00:11<00:04, 58.87it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  74%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d  | 660/892 [00:12<00:04, 56.31it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  76%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c  | 680/892 [00:12<00:03, 58.23it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  78%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a  | 700/892 [00:12<00:03, 60.50it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  81%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588  | 720/892 [00:12<00:02, 62.29it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  83%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e | 740/892 [00:13<00:02, 59.05it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  85%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c | 760/892 [00:13<00:02, 55.66it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  87%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b | 780/892 [00:14<00:01, 59.02it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  90%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589 | 800/892 [00:14<00:01, 61.37it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  92%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f| 820/892 [00:14<00:01, 53.02it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  94%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d| 840/892 [00:15<00:00, 59.87it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  96%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b| 860/892 [00:15<00:00, 61.36it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mp:  99%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a| 880/892 [00:15<00:00, 62.68it/s]\u001b[A\u001b[A\u001b[A\n    \n    \n    mcloud.threedd: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 87/87 [00:02<00:00, 32.31it/s]\n\nWe see that the `OptimadeRester` does some of the hard work for us: it automatically retrieves multiple pages of results when many results are available, and also gives us a progress bar.\n\nLet us inspect the `results`:\n\n\n```python\ntype(results)  # this method returns a dictionary, so let's examine the keys of this dictionary...\n```\n\n\n\n\n    dict\n\n\n\n\n```python\nresults.keys()  # we see that the results dictionary is keyed by provider/alias\n```\n\n\n\n\n    dict_keys(['mp', 'mcloud.threedd'])\n\n\n\n\n```python\nresults['mp'].keys()  # and these are then keyed by that database's unique identifier\n```\n\n\n\n\n    dict_keys(['mp-1008610', 'mp-1019271', 'mp-1065394', 'mp-7790', 'mp-1015582', 'mp-1104441', 'mp-1019272', 'mp-1102235', 'mp-29973', 'mp-2245', 'mp-1014303', 'mp-1007824', 'mp-1245326', 'mp-973935', 'mp-834', 'mp-1018160', 'mp-1014298', 'mp-1214623', 'mp-1245013', 'mp-1244914', 'mp-27908', 'mp-32652', 'mp-1216472', 'mp-1014358', 'mp-1018733', 'mp-1009885', 'mp-1058019', 'mp-11660', 'mp-1209181', 'mp-510557', 'mp-1245132', 'mp-1009769', 'mvc-15478', 'mp-1865', 'mp-9981', 'mp-1077354', 'mp-10736', 'mp-1091417', 'mp-1245165', 'mp-1204550', 'mp-1245046', 'mp-661', 'mp-8101', 'mp-1001117', 'mp-2114', 'mp-1008833', 'mp-1008489', 'mp-1009483', 'mp-1188353', 'mp-1245244', 'mp-1077275', 'mp-1271276', 'mp-2828', 'mp-1078568', 'mp-1093992', 'mp-1213154', 'mp-2341', 'mvc-11235', 'mp-1014324', 'mp-1102114', 'mp-1244927', 'mp-634410', 'mp-567617', 'mp-1001826', 'mp-1002222', 'mp-1014995', 'mp-1072543', 'mp-1001916', 'mp-1064529', 'mp-754553', 'mp-1097011', 'mp-1096882', 'mp-1008921', 'mvc-13808', 'mp-1188721', 'mp-1933', 'mp-1097766', 'mp-754353', 'mp-986716', 'mp-1017550', 'mp-1096965', 'mp-1120744', 'mp-13480', 'mp-1180282', 'mp-1079947', 'mp-1212113', 'mp-1954', 'mp-510087', 'mp-27954', 'mp-999496', 'mp-476', 'mp-1018027', 'mp-1080201', 'mp-1096917', 'mp-1245010', 'mp-998899', 'mp-608071', 'mp-1014287', 'mp-1096962', 'mp-1218446', 'mp-1245263', 'mp-1009130', 'mp-1062817', 'mp-1220479', 'mp-251', 'mp-1018849', 'mp-1016048', 'mp-1079684', 'mp-1221793', 'mp-13175', 'mp-570604', 'mp-1009646', 'mp-1410', 'mp-973674', 'mp-1002207', 'mp-1188869', 'mp-1217167', 'mp-570471', 'mp-1060281', 'mp-1080202', 'mp-1179691', 'mp-2565', 'mp-504769', 'mvc-15427', 'mp-1047', 'mp-1096966', 'mp-1173453', 'mp-1019316', 'mp-1245258', 'mp-776470', 'mp-1077346', 'mp-1804', 'mp-2852', 'mp-637209', 'mp-1014264', 'mp-1014316', 'mp-1057758', 'mp-1208632', 'mvc-13729', 'mp-1016058', 'mp-1180215', 'mp-1180313', 'mp-804', 'mp-940', 'mp-984', 'mp-1097042', 'mp-1196421', 'mp-1245106', 'mp-530081', 'mp-1065265', 'mp-604884', 'mp-1008986', 'mp-1078389', 'mp-1015780', 'mp-754628', 'mp-1216464', 'mp-1940', 'mp-2131', 'mp-535', 'mvc-13927', 'mp-1180230', 'mp-1238814', 'mp-2599', 'mp-1014281', 'mp-1008826', 'mp-27488', 'mp-1244991', 'mp-570454', 'mp-779689', 'mp-684642', 'mp-1018734', 'mp-1014565', 'mp-1179882', 'mp-569461', 'mp-754556', 'mp-1009639', 'mp-1015065', 'mp-1096957', 'mp-1009640', 'mp-1077506', 'mp-510350', 'mp-973', 'mp-1017546', 'mp-10564', 'mp-2634', 'mp-568172', 'mp-1017532', 'mp-1013529', 'mp-1187906', 'mp-1200511', 'mp-1195863', 'mp-1271281', 'mp-13146', 'mp-685145', 'mp-1001844', 'mp-1209103', 'mp-1014379', 'mp-1102941', 'mp-1018852', 'mp-1056900', 'mp-1079760', 'mp-11607', 'mp-1193580', 'mp-1015026', 'mp-1097039', 'mp-13098', 'mp-1009649', 'mp-1096909', 'mp-8282', 'mp-1061865', 'mp-1580', 'mp-36891', 'mp-1180345', 'mp-616407', 'mp-883', 'mp-1080197', 'mp-1246153', 'mp-754629', 'mp-1008965', 'mp-1245175', 'mp-13117', 'mp-32590', 'mp-1008820', 'mp-1207010', 'mvc-13455', 'mp-1002229', 'mp-1009720', 'mp-1080242', 'mp-1080623', 'mp-1208477', 'mp-248', 'mp-2789', 'mp-6988', 'mp-971694', 'mp-1079585', 'mp-1204171', 'mp-1245228', 'mp-1096911', 'mp-1101174', 'mp-1181864', 'mp-570538', 'mp-999264', 'mp-1009596', 'mp-1184048', 'mp-1019052', 'mp-1069841', 'mp-1244984', 'mp-1244972', 'mp-32913', 'mp-1009734', 'mp-1222421', 'mp-607371', 'mp-1067139', 'mp-1245229', 'mp-676', 'mp-864647', 'mp-1066400', 'mp-1096924', 'mp-1225746', 'mp-925', 'mp-1014454', 'mp-1078828', 'mp-1105655', 'mp-755988', 'mp-1014214', 'mp-1080193', 'mp-1220310', 'mp-684592', 'mp-754434', 'mp-1009767', 'mp-1245130', 'mp-1244934', 'mp-569957', 'mp-1062345', 'mp-6933', 'mp-870', 'mp-999263', 'mp-1072167', 'mp-1080198', 'mp-1096961', 'mp-1245281', 'mp-999195', 'mp-1203253', 'mp-1205002', 'mp-1245322', 'mp-1078816', 'mp-999266', 'mp-1018948', 'mp-1104403', 'mp-1639', 'mp-581833', 'mp-1599', 'mp-1080203', 'mp-1220830', 'mp-20812', 'mp-504768', 'mp-601223', 'mp-8102', 'mp-1066162', 'mp-2033', 'mp-1208406', 'mp-2596', 'mp-999485', 'mp-1101901', 'mp-1193871', 'mp-18337', 'mp-999469', 'mp-1009219', 'mp-1009015', 'mp-1096918', 'mp-1201150', 'mp-1014478', 'mp-1018655', 'mp-999296', 'mp-1102429', 'mp-583712', 'mp-1018049', 'mp-1014345', 'mp-1077096', 'mp-1184774', 'mp-684692', 'mvc-13841', 'mp-1078791', 'mp-1719', 'mp-1002197', 'mp-637576', 'mp-999294', 'mp-2117', 'mp-567885', 'mp-571653', 'mp-1198545', 'mp-1009836', 'mp-1015612', 'mp-1244872', 'mp-973933', 'mp-980941', 'mp-22631', 'mp-6913', 'mp-999517', 'mp-2653', 'mp-1096890', 'mp-1014509', 'mp-1019239', 'mp-1180334', 'mp-1187056', 'mp-1189035', 'mp-1224501', 'mp-555136', 'mp-1002181', 'mp-1002182', 'mp-1014311', 'mp-1019086', 'mp-1104513', 'mp-12981', 'mp-1064647', 'mp-1097032', 'mp-1244946', 'mp-673635', 'mp-2701', 'mp-1018157', 'mp-1014347', 'mp-1014296', 'mp-1058586', 'mp-1180473', 'mp-1019083', 'mp-1079812', 'mp-1190322', 'mp-685209', 'mp-1225831', 'mp-1096899', 'mp-1078576', 'mp-1080172', 'mp-1096913', 'mp-1096900', 'mp-13173', 'mp-568293', 'mp-1180500', 'mp-569167', 'mp-972036', 'mp-1016073', 'mp-1212961', 'mp-1707', 'mp-1001834', 'mp-1330', 'mp-684887', 'mp-1008823', 'mp-1064119', 'mp-1066707', 'mp-1080199', 'mp-1009601', 'mp-1014342', 'mp-1014339', 'mp-1211954', 'mp-343', 'mp-672264', 'mp-1009078', 'mp-1077299', 'mp-1096893', 'mp-1188048', 'mp-982734', 'mp-1097757', 'mp-1180757', 'mp-1419', 'mp-1975', 'mp-998908', 'mp-1009237', 'mp-1096888', 'mp-1173647', 'mp-1183691', 'mp-33090', 'mp-641541', 'mp-1016069', 'mp-1202811', 'mp-1219567', 'mp-13035', 'mp-2118', 'mp-1009694', 'mp-563', 'mp-1009833', 'mp-1096935', 'mp-1244866', 'mp-1225758', 'mp-1096968', 'mp-1220726', 'mp-13099', 'mp-1776', 'mp-534', 'mp-1120742', 'mp-1190632', 'mp-1245149', 'mp-1244917', 'mp-20304', 'mp-680640', 'mp-1014332', 'mp-749', 'mp-1079708', 'mp-2493', 'mp-1195888', 'mp-1214748', 'mp-971684', 'mp-1014318', 'mp-1179538', 'mp-8046', 'mp-864918', 'mp-998903', 'mvc-11162', 'mvc-11231', 'mp-1014366', 'mp-1190039', 'mp-567290', 'mp-975606', 'mp-999357', 'mp-1009545', 'mp-1078609', 'mp-1096907', 'mp-40793', 'mp-620058', 'mp-1014910', 'mp-1019080', 'mp-1097803', 'mp-16031', 'mp-827', 'mp-1209413', 'mp-1245048', 'mp-1180438', 'mp-1245193', 'mp-1080190', 'mp-1245', 'mp-7927', 'mp-999495', 'mp-1057084', 'mp-1245002', 'mp-1206425', 'mp-1097059', 'mp-1245123', 'mp-685023', 'mp-1080194', 'mp-1192688', 'mp-641539', 'mp-999303', 'mp-1205065', 'mp-1245075', 'mp-13151', 'mp-754381', 'mp-1102', 'mp-22003', 'mp-999355', 'mp-1009548', 'mp-20340', 'mp-1642', 'mp-344', 'mp-651723', 'mp-11801', 'mp-1245172', 'mp-755880', 'mp-1014297', 'mp-1001', 'mp-1008600', 'mp-1014558', 'mp-1019077', 'mp-1095181', 'mp-1009657', 'mp-1245188', 'mp-1245295', 'mp-13148', 'mp-1194075', 'mp-998900', 'mp-1008918', 'mp-1096928', 'mp-1196867', 'mp-1245150', 'mp-2355', 'mvc-14553', 'mp-1096898', 'mp-1216242', 'mp-1245095', 'mp-13178', 'mp-13076', 'mp-2132', 'mp-1009831', 'mp-1007778', 'mp-1210764', 'mp-1096896', 'mp-1178600', 'mp-1218021', 'mp-13034', 'mp-15799', 'mp-988', 'mp-10196', 'mp-1058549', 'mp-1103129', 'mp-1182172', 'mp-1009766', 'mp-1096906', 'mp-1224686', 'mp-1019082', 'mp-467', 'mp-636839', 'mp-1008483', 'mp-1203301', 'mp-13132', 'mp-568867', 'mp-1019078', 'mp-1096914', 'mp-2659', 'mp-999197', 'mp-1058689', 'mp-1245301', 'mp-864675', 'mp-1244896', 'mp-2811', 'mp-567907', 'mp-6977', 'mp-1066', 'mp-1205986', 'mp-1245252', 'mp-1224383', 'mp-720515', 'mp-1009493', 'mp-1018947', 'mp-974435', 'mp-1014265', 'mp-1008798', 'mp-1064952', 'mp-1013524', 'mp-1009732', 'mp-1225203', 'mp-999117', 'mp-999292', 'mp-1096951', 'mp-568862', 'mp-1244916', 'mp-256', 'mp-1059612', 'mp-1080192', 'mp-1106142', 'mp-1185783', 'mp-20411', 'mp-985299', 'mp-1216967', 'mp-2251', 'mp-971657', 'mp-1016076', 'mp-1016071', 'mp-1097796', 'mp-7139', 'mp-981366', 'mp-991', 'mp-1009485', 'mp-34761', 'mp-643432', 'mp-1015076', 'mp-1173466', 'mp-1244943', 'mp-13150', 'mp-608366', 'mp-673174', 'mp-1096892', 'mp-1103420', 'mp-1245231', 'mp-1019319', 'mp-1245069', 'mp-1182484', 'mp-9460', 'mp-542738', 'mp-1059160', 'mp-1180220', 'mp-1057979', 'mp-1096919', 'mp-1103897', 'mp-1459', 'mp-1352', 'mp-1559', 'mp-235', 'mp-448', 'mp-1244977', 'mp-22777', 'mp-1009019', 'mp-1204579', 'mp-1216851', 'mp-1064161', 'mp-1245286', 'mp-21476', 'mp-1018142', 'mp-1019055', 'mp-1096889', 'mp-830', 'mp-1014286', 'mp-1096864', 'mp-1120827', 'mp-1700', 'mp-1221446', 'mp-29145', 'mp-1245233', 'mp-8780', 'mp-980940', 'mp-1203286', 'mp-570572', 'mp-1009005', 'mp-1009471', 'mp-1180808', 'mp-776343', 'mp-864757', 'mp-1077595', 'mp-1220519', 'mp-644751', 'mp-9410', 'mp-555', 'mp-1078219', 'mp-1244884', 'mp-571297', 'mp-685079', 'mp-1101173', 'mp-1102441', 'mp-999300', 'mp-1094090', 'mp-1097018', 'mp-22387', 'mp-685050', 'mp-1016078', 'mp-1245249', 'mp-999307', 'mp-1014373', 'mp-32584', 'mp-1095618', 'mp-32742', 'mp-415', 'mp-1056955', 'mp-1080032', 'mp-20839', 'mp-999293', 'mp-1066821', 'mp-1096908', 'mp-1245302', 'mp-1059879', 'mp-574424', 'mp-7234', 'mp-999473', 'mp-1009049', 'mp-1018716', 'mp-1203025', 'mp-236', 'mp-1009770', 'mp-1064706', 'mp-1198478', 'mp-1207164', 'mp-23922', 'mp-7991', 'mp-999317', 'mp-1105105', 'mp-1205447', 'mp-636056', 'mp-999086', 'mp-1244886', 'mp-27953', 'mp-542635', 'mvc-15387', 'mp-1016070', 'mp-1217984', 'mp-1009818', 'mp-1077232', 'mp-1080196', 'mp-1096886', 'mvc-13461', 'mp-569228', 'mp-971683', 'mp-1008929', 'mp-1009838', 'mp-1245148', 'mp-1245287', 'mp-684744', 'mvc-15664', 'mp-1013528', 'mp-1080200', 'mp-1206884', 'mp-1279', 'mp-2853', 'mp-973785', 'mp-1892', 'mp-1008987', 'mp-1009494', 'mp-1180208', 'mp-1244995', 'mp-1245181', 'mp-1014333', 'mp-1097738', 'mp-13174', 'mp-672289', 'mp-1018018', 'mp-1016081', 'mp-1147700', 'mp-1245030', 'mp-1071980', 'mp-1187591', 'mp-22205', 'mp-32994', 'mp-999503', 'mp-1009496', 'mp-1064272', 'mp-1096894', 'mp-1101868', 'mp-1014444', 'mp-1071531', 'mp-1080191', 'mp-1102074', 'mvc-15384', 'mp-27943', 'mp-2718', 'mp-1078930', 'mp-1244903', 'mp-569655', 'mp-971682', 'mp-1206907', 'mp-973835', 'mp-1188347', 'mp-1212209', 'mp-1007660', 'mp-1104073', 'mp-1008922', 'mp-1016063', 'mp-1067644', 'mp-1173210', 'mp-1103427', 'mp-1217048', 'mp-1008762', 'mp-1019238', 'mp-1070456', 'mvc-13303', 'mp-1008985', 'mp-1014160', 'mp-1002209', 'mp-866083', 'mp-1096901', 'mp-13116', 'mp-2075', 'mp-1096885', 'mp-1188944', 'mp-1224391', 'mp-674509', 'mp-2857', 'mp-31000', 'mp-1015567', 'mp-1014369', 'mp-1016059', 'mp-1071868', 'mp-13126', 'mp-999295', 'mp-1009488', 'mp-1096994', 'mp-1180489', 'mp-2639', 'mp-492', 'mp-1224698', 'mp-540572', 'mp-277', 'mp-743', 'mp-1017982', 'mp-1017533', 'mp-1096903', 'mp-1101178', 'mp-1079438', 'mp-1244975', 'mp-12857', 'mp-603694', 'mp-667338', 'mp-1072204', 'mp-1102371', 'mp-844', 'mp-1014993', 'mp-1200550', 'mp-1224388', 'mp-1771', 'mp-1008558', 'mp-1001828', 'mp-1015908', 'mp-1079251', 'mp-1096931', 'mp-12120', 'mp-1245297', 'mvc-13772', 'mp-1214163', 'mp-22762', 'mp-1096910', 'mp-1096912', 'mp-1245288', 'mp-21264', 'mp-1217441', 'mp-13036', 'mp-776321', 'mvc-11196', 'mp-1058151', 'mp-1101975', 'mp-1179622', 'mp-1220496', 'mp-27461', 'mp-13852', 'mp-2686', 'mp-1009750', 'mp-1188283', 'mp-33046', 'mp-971911', 'mp-1182030', 'mvc-14624', 'mp-1017987', 'mp-1080204', 'mp-1245014', 'mp-2247', 'mp-571281', 'mp-1180221', 'mp-1225892', 'mp-1008923', 'mp-1002117', 'mp-1018648', 'mp-557865', 'mp-1225717', 'mp-1245033', 'mp-505622', 'mp-1014365', 'mp-1188007', 'mp-1002105', 'mp-11661', 'mp-1221525', 'mp-1080195', 'mp-629015', 'mp-1009128', 'mp-1009495', 'mp-1094084', 'mp-1189239', 'mp-1008809', 'mp-1009221', 'mp-1059462', 'mp-999549', 'mp-1245138', 'mp-1985', 'mp-570155', 'mp-16730', 'mp-1497', 'mp-1063003', 'mp-1096922', 'mp-1100774', 'mp-1102681', 'mp-1244998', 'mp-1018851', 'mp-1064715', 'mp-1096934', 'mp-1226927', 'mp-19830', 'mp-1244870', 'mp-1205092', 'mp-866056', 'mp-1014460', 'mp-1219988'])\n\n\n\nSo let us inspect one structure as an example:\n\n\n```python\nexample_structure = results['mp']['mp-804']\nprint(example_structure)\n```\n\n    Full Formula (Ga2 N2)\n    Reduced Formula: GaN\n    abc   :   3.216290   3.216290   5.239962\n    angles:  90.000000  90.000000 120.000003\n    Sites (4)\n      #  SP           a         b        c\n    ---  ----  --------  --------  -------\n      0  Ga    0.666667  0.333333  0.49912\n      1  Ga    0.333333  0.666667  0.99912\n      2  N     0.666667  0.333333  0.87588\n      3  N     0.333333  0.666667  0.37588\n\n\nWe can then use *pymatgen* to further manipulate these `Structure` objects, for example to calculate the spacegroup or to convert to a CIF:\n\n\n```python\nexample_structure.get_space_group_info()\n```\n\n\n\n\n    ('P6_3mc', 186)\n\n\n\n\n```python\nprint(example_structure.to(fmt=\"cif\", symprec=0.01))\n```\n\n    # generated using pymatgen\n    data_GaN\n    _symmetry_space_group_name_H-M   P6_3mc\n    _cell_length_a   3.21629007\n    _cell_length_b   3.21629007\n    _cell_length_c   5.23996200\n    _cell_angle_alpha   90.00000000\n    _cell_angle_beta   90.00000000\n    _cell_angle_gamma   120.00000000\n    _symmetry_Int_Tables_number   186\n    _chemical_formula_structural   GaN\n    _chemical_formula_sum   'Ga2 N2'\n    _cell_volume   46.94282137\n    _cell_formula_units_Z   2\n    loop_\n     _symmetry_equiv_pos_site_id\n     _symmetry_equiv_pos_as_xyz\n      1  'x, y, z'\n      2  'x-y, x, z+1/2'\n      3  '-y, x-y, z'\n      4  '-x, -y, z+1/2'\n      5  '-x+y, -x, z'\n      6  'y, -x+y, z+1/2'\n      7  'y, x, z+1/2'\n      8  'x, x-y, z'\n      9  'x-y, -y, z+1/2'\n      10  '-y, -x, z'\n      11  '-x, -x+y, z+1/2'\n      12  '-x+y, y, z'\n    loop_\n     _atom_site_type_symbol\n     _atom_site_label\n     _atom_site_symmetry_multiplicity\n     _atom_site_fract_x\n     _atom_site_fract_y\n     _atom_site_fract_z\n     _atom_site_occupancy\n      Ga  Ga0  2  0.33333333  0.66666667  0.99912000  1\n      N  N1  2  0.33333333  0.66666667  0.37588000  1\n    \n\n\n# Data analysis\n\nThis section I will use some code I prepared earlier to summarize the `results` into a tabular format (`DataFrame`).\n\n\n```python\nimport pandas as pd\n```\n\n\n```python\nrecords = []\nfor provider, structures in results.items():\n    for identifier, structure in structures.items():\n        records.append({\n            \"provider\": provider,\n            \"identifier\": identifier,\n            \"formula\": structure.composition.reduced_formula,\n            \"spacegroup\": structure.get_space_group_info()[0],\n            \"a_lattice_param\": structure.lattice.a,\n            \"volume\": structure.volume,\n        })\ndf = pd.DataFrame(records)\n```\n\n\n```python\ndf\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>provider</th>\n      <th>identifier</th>\n      <th>formula</th>\n      <th>spacegroup</th>\n      <th>a_lattice_param</th>\n      <th>volume</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>mp</td>\n      <td>mp-1008610</td>\n      <td>AuN</td>\n      <td>Fm-3m</td>\n      <td>3.302053</td>\n      <td>25.458750</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>mp</td>\n      <td>mp-1019271</td>\n      <td>TaN2</td>\n      <td>P6/mmm</td>\n      <td>5.459583</td>\n      <td>72.277001</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>mp</td>\n      <td>mp-1065394</td>\n      <td>MoN</td>\n      <td>P6_3/mmc</td>\n      <td>2.870508</td>\n      <td>40.722201</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>mp</td>\n      <td>mp-7790</td>\n      <td>Ti2N</td>\n      <td>I4_1/amd</td>\n      <td>5.322762</td>\n      <td>76.524076</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>mp</td>\n      <td>mp-1015582</td>\n      <td>CrN2</td>\n      <td>Pbcn</td>\n      <td>4.405213</td>\n      <td>118.349470</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>974</th>\n      <td>mcloud.threedd</td>\n      <td>25786</td>\n      <td>N2O</td>\n      <td>Pa-3</td>\n      <td>5.842646</td>\n      <td>199.447562</td>\n    </tr>\n    <tr>\n      <th>975</th>\n      <td>mcloud.threedd</td>\n      <td>26371</td>\n      <td>SbN9</td>\n      <td>P-1</td>\n      <td>7.350390</td>\n      <td>322.370944</td>\n    </tr>\n    <tr>\n      <th>976</th>\n      <td>mcloud.threedd</td>\n      <td>26467</td>\n      <td>SmN</td>\n      <td>Fm-3m</td>\n      <td>3.559131</td>\n      <td>31.879910</td>\n    </tr>\n    <tr>\n      <th>977</th>\n      <td>mcloud.threedd</td>\n      <td>26627</td>\n      <td>CsN</td>\n      <td>Pm-3m</td>\n      <td>3.821708</td>\n      <td>55.817766</td>\n    </tr>\n    <tr>\n      <th>978</th>\n      <td>mcloud.threedd</td>\n      <td>26808</td>\n      <td>GdN</td>\n      <td>Fm-3m</td>\n      <td>3.527077</td>\n      <td>31.026289</td>\n    </tr>\n  </tbody>\n</table>\n<p>979 rows \u00d7 6 columns</p>\n</div>\n\n\n\nTo pick one specific formula as an example, we can use tools from `pandas` to show the spacegroups present for that formula:\n\n\n```python\ndf[df[\"formula\"] == \"GaN\"].spacegroup\n```\n\n\n\n\n    11     P6_3/mmc\n    12           P1\n    18           P1\n    30           P1\n    38           P1\n    40           P1\n    49           P1\n    60           P1\n    128          P1\n    142      P6_3mc\n    147          P1\n    239      P6_3mc\n    246          P1\n    270          P1\n    271          P1\n    420          P1\n    471          P1\n    481          P1\n    493          P1\n    502          P1\n    503          P1\n    510          P1\n    515          P1\n    549          P1\n    571          P1\n    601          P1\n    621          P1\n    626       F-43m\n    633          P1\n    649          P1\n    673          P1\n    693          P1\n    708          P1\n    716       Fm-3m\n    722          P1\n    723          P1\n    731          P1\n    749          P1\n    801          P1\n    824          P1\n    855          P1\n    872          P1\n    881          P1\n    969      P6_3mc\n    Name: spacegroup, dtype: object\n\n\n\nHere, we see that there are a few common high-symmetry spacegroups (such as $P6_3mc$) there are also many low-symmetry structures ($P1$).\n\nI know that in this instance, this is because the $P1$ structures are actually amorphous and not crystalline. This highlights the importance of doing appropraiate **data cleaning** on retrieved data.\n\n### Plotting data\n\nAs a quick example, we can also plot information in our table:\n\n\n```python\nimport plotly.express as px\n```\n\n\n```python\npx.bar(df, x=\"spacegroup\", facet_row=\"provider\")\n```\n\n\n<html>\n<head><meta charset=\"utf-8\" /></head>\n<body>\n    <div>                            \n                        <div id=\"a12b656a-4ddc-4b53-bd4d-4dbcc6f61374\" class=\"plotly-graph-div\" style=\"height:525px; width:100%;\"></div>                    </div>\n</body>\n</html>\n\n\n**Remember, there is no single \"best database\" to use. Every database might be constructed for a specific purpose, subject to different biases, with different data qualities and sources.**\n\nThe ideal database for one scientist with one application in mind may be different to the ideal database for another scientist with a different application.\n\n**The power of OPTIMADE is that you can query across multiple databases!**\n\n# Advanced usage: querying using the OPTIMADE filter grammar\n\nYou can also query using an OPTIMADE filter as defined in the OPTIMADE specification and publication.\n\n**This is recommended** for advanced queries to use the full power of OPTIMADE.\n\nFor example, the above query could have equally been performed as:\n\n\n```python\nresults = opt.get_structures_with_filter('(elements HAS ALL \"N\") AND (nelements=2)')\n```\n\n    \n    mp:   2%|\u258f         | 20/892 [00:00<?, ?it/s]\u001b[A\n    mp:   4%|\u258d         | 40/892 [00:00<00:11, 72.90it/s]\u001b[A\n    mp:   7%|\u258b         | 60/892 [00:00<00:11, 72.88it/s]\u001b[A\n    mp:   9%|\u2589         | 80/892 [00:00<00:11, 72.95it/s]\u001b[A\n    mp:  11%|\u2588         | 100/892 [00:01<00:12, 65.69it/s]\u001b[A\n    mp:  13%|\u2588\u258e        | 120/892 [00:01<00:14, 54.45it/s]\u001b[A\n    \n    \n    mp: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 892/892 [00:27<00:00, 47.21it/s]\u001b[A\u001b[A\u001b[A\n    mp:  16%|\u2588\u258c        | 140/892 [00:02<00:13, 54.42it/s]\u001b[A\n    mp:  18%|\u2588\u258a        | 160/892 [00:02<00:13, 54.52it/s]\u001b[A\n    mp:  20%|\u2588\u2588        | 180/892 [00:02<00:12, 57.95it/s]\u001b[A\n    mp:  22%|\u2588\u2588\u258f       | 200/892 [00:02<00:11, 61.80it/s]\u001b[A\n    mp:  25%|\u2588\u2588\u258d       | 220/892 [00:03<00:10, 63.65it/s]\u001b[A\n    mp: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 892/892 [00:29<00:00, 29.79it/s]\n    mcloud.threedd: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 87/87 [00:12<00:00,  5.91it/s]\n    \n    mp:  29%|\u2588\u2588\u2589       | 260/892 [00:03<00:10, 57.87it/s]\u001b[A\n    mp:  31%|\u2588\u2588\u2588\u258f      | 280/892 [00:04<00:10, 57.30it/s]\u001b[A\n    mp:  34%|\u2588\u2588\u2588\u258e      | 300/892 [00:04<00:09, 60.09it/s]\u001b[A\n    mp:  36%|\u2588\u2588\u2588\u258c      | 320/892 [00:04<00:09, 62.86it/s]\u001b[A\n    mp:  38%|\u2588\u2588\u2588\u258a      | 340/892 [00:05<00:08, 64.44it/s]\u001b[A\n    mp:  40%|\u2588\u2588\u2588\u2588      | 360/892 [00:05<00:08, 64.95it/s]\u001b[A\n    mp:  43%|\u2588\u2588\u2588\u2588\u258e     | 380/892 [00:05<00:07, 70.98it/s]\u001b[A\n    mp:  45%|\u2588\u2588\u2588\u2588\u258d     | 400/892 [00:06<00:06, 70.61it/s]\u001b[A\n    mp:  47%|\u2588\u2588\u2588\u2588\u258b     | 420/892 [00:06<00:06, 70.85it/s]\u001b[A\n    mp:  49%|\u2588\u2588\u2588\u2588\u2589     | 440/892 [00:06<00:06, 68.00it/s]\u001b[A\n    mp:  52%|\u2588\u2588\u2588\u2588\u2588\u258f    | 460/892 [00:06<00:06, 69.75it/s]\u001b[A\n    mp:  54%|\u2588\u2588\u2588\u2588\u2588\u258d    | 480/892 [00:07<00:06, 63.08it/s]\u001b[A\n    mp:  56%|\u2588\u2588\u2588\u2588\u2588\u258c    | 500/892 [00:07<00:06, 64.69it/s]\u001b[A\n    mp:  58%|\u2588\u2588\u2588\u2588\u2588\u258a    | 520/892 [00:07<00:05, 65.02it/s]\u001b[A\n    mp:  61%|\u2588\u2588\u2588\u2588\u2588\u2588    | 540/892 [00:08<00:05, 67.29it/s]\u001b[A\n    mp:  63%|\u2588\u2588\u2588\u2588\u2588\u2588\u258e   | 560/892 [00:08<00:05, 62.68it/s]\u001b[A\n    mp:  65%|\u2588\u2588\u2588\u2588\u2588\u2588\u258c   | 580/892 [00:08<00:04, 62.63it/s]\u001b[A\n    mp:  67%|\u2588\u2588\u2588\u2588\u2588\u2588\u258b   | 600/892 [00:09<00:04, 58.89it/s]\u001b[A\n    mp:  70%|\u2588\u2588\u2588\u2588\u2588\u2588\u2589   | 620/892 [00:09<00:04, 57.19it/s]\u001b[A\n    mp:  72%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f  | 640/892 [00:09<00:04, 58.50it/s]\u001b[A\n    mp:  74%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d  | 660/892 [00:10<00:03, 62.53it/s]\u001b[A\n    mp:  76%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c  | 680/892 [00:10<00:03, 54.97it/s]\u001b[A\n    mp:  78%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a  | 700/892 [00:10<00:03, 58.01it/s]\u001b[A\n    mp:  81%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588  | 720/892 [00:11<00:02, 60.39it/s]\u001b[A\n    mp:  83%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e | 740/892 [00:11<00:03, 49.75it/s]\u001b[A\n    mp:  85%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c | 760/892 [00:12<00:02, 51.13it/s]\u001b[A\n    mp:  87%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b | 780/892 [00:12<00:02, 55.38it/s]\u001b[A\n    mp:  90%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589 | 800/892 [00:12<00:01, 58.72it/s]\u001b[A\n    mp:  92%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f| 820/892 [00:13<00:01, 53.50it/s]\u001b[A\n    mp:  94%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d| 840/892 [00:13<00:00, 56.96it/s]\u001b[A\n    mp:  96%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b| 860/892 [00:13<00:00, 63.27it/s]\u001b[A\n    mp:  99%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a| 880/892 [00:14<00:00, 64.92it/s]\u001b[A\n    mcloud.threedd: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 87/87 [00:02<00:00, 31.86it/s]\n\n# Advanced usage: retrieving provider-specific property information\n\nThe OPTIMADE specification allows for providers to include database-specific information in the returned data, prefixed by namespace.\n\nTo access this information with *pymatgen* we have to request \"snls\" (`StructureNL`) instead of \"structures\". A `StructureNL` is a `Structure` with additional metadata included, such as the URL it was downloaded from and any of this additional database-specific information.\n\n\n```python\nresults_snls = OptimadeRester(\"odbx\").get_snls(nelements=2, additional_response_fields=[\"_odbx_thermodynamics\"])\n```\n\n    \n    \n    odbx:  37%|\u2588\u2588\u2588\u258b      | 20/54 [00:00<?, ?it/s]\u001b[A\u001b[A\n    \n    odbx:  74%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d  | 40/54 [00:00<00:00, 31.84it/s]\u001b[A\u001b[A\n    \n    odbx: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 54/54 [00:01<00:00, 27.29it/s]\u001b[A\u001b[A\n\n\n```python\nexample_snl = results_snls['odbx']['odbx/2']\n```\n\n\n```python\nexample_snl.data['_optimade']['_odbx_thermodynamics']\n```\n\n\n\n\n    {'enthalpy': -816.9762466666666,\n     'formation_energy': -0.39885422222209854,\n     'hull_distance': 0.0004641666667737354,\n     'relative_enthalpy': None,\n     'total_energy': -816.9727734428334}\n\n\n\nThis extra data provided differs from every database, and sometimes from material to material, so some exploration is required!\n\n# When Things Go Wrong and How to Get Help\n\nBugs may be present! The `OptimadeRester` is still fairly new.\n\nIf it does not work it is likely because of either:\n\n* A bug in the *pymatgen* code. This may be reported directly to Matthew Horton at mkhorton@lbl.gov or an issue can be opened in the *pymatgen* code repository. Matt apologises in advance if this is the case! \n\n* An issue with a provider. This may be because the provider does not yet fully follow the OPTIMADE specification, because the provider is suffering an outage, or because the filters are not yet optimized with that provider.\n\n    * If this happens, you may try to first increase the `timeout` value to something larger. The default is too low for some providers.\n\n    * Otherwise, you may want to contact the provider directly, or create a post at the OPTIMADE discussion forum: https://matsci.org/optimade\n\n# How to Get Involved\n\nNew developers are very welcome to add code to *pymatgen*! If you want to get involved, help fix bugs or add new features, your help would be very much appreciated. *pymatgen* can only exist and be what it is today thanks to the many efforts of its [development team](https://pymatgen.org/team.html).\n", "meta": {"hexsha": "c63d8b87205fbed1ff6143a95b86fb7f4e029751", "size": 89181, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/demonstration-pymatgen-for-optimade-queries.ipynb", "max_stars_repo_name": "Materials-Consortia/optimade-tutorial-exercises", "max_stars_repo_head_hexsha": "2dd001825acd128fb067a0d068e0c4a450b1a991", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-09-07T09:09:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-07T13:03:40.000Z", "max_issues_repo_path": "notebooks/demonstration-pymatgen-for-optimade-queries.ipynb", "max_issues_repo_name": "Materials-Consortia/optimade-tutorial-exercises", "max_issues_repo_head_hexsha": "2dd001825acd128fb067a0d068e0c4a450b1a991", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-11-17T17:46:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T19:16:34.000Z", "max_forks_repo_path": "notebooks/demonstration-pymatgen-for-optimade-queries.ipynb", "max_forks_repo_name": "Materials-Consortia/optimade-tutorial-exercises", "max_forks_repo_head_hexsha": "2dd001825acd128fb067a0d068e0c4a450b1a991", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-09-06T22:51:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-30T10:21:11.000Z", "avg_line_length": 62.7593244194, "max_line_length": 21861, "alphanum_fraction": 0.4911584306, "converted": true, "num_tokens": 16103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.10970577678877605, "lm_q1q2_score": 0.039819818641934464}}
{"text": "## Utils\n\n---\n\nYou are currently looking at **version 1.0** of this notebook.  \nProject/objective:  \nDate: 24-may-2018  \nAuthor: Frank Ebbers  \nContributors:   \nLicense: MIT https://opensource.org/licenses/MIT  \n\n---\n\n## Changelog\n\n- \n\nUseful resources:\n\nhttps://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/\n\nhttp://blog.juliusschulz.de/blog/ultimate-ipython-notebook\n\nhttp://nbviewer.jupyter.org/github/jupyter/nbconvert/blob/master/docs/source/customizing.ipynb\n\n\n\n```python\n# %pylab inline         # imports numpy, pandas, scipy, matplotlib inline\n# %matplotlib inline    # shows plots in notebook\n# %matplotlib notebook  # same, interactive but slower\n```\n\n### Markdown on Output\n\n\n```python\nfrom IPython.display import display, Markdown, Latex\ntext = '**some markdown** `truly nice` $\\phi$ {}'.format(' what the hack')\ndisplay(Markdown(text))\n```\n\n\n```python\ndef printmd(text):\n    \"\"\"Prints out as markdown\n    Example:\n    text = '**some markdown** `truly nice` $\\phi$ {}'.format(' what the hack')\n    \"\"\"\n    from IPython.display import display, Markdown, Latex\n    return display(Markdown(text))\nprintmd(text)\n```\n\n\n```python\ndef printmd(text):\n    \"\"\"Prints out as markdown\n    Examples:\n    md_text = '** green::some markdown ** `truly nice` $\\phi$ {}'.format(' red::hack')\n    colored_text = 'red::green'\n    \"\"\"\n    import re\n    from IPython.display import display, Markdown, Latex\n\n    try:\n        for col_item in re.findall(r\"(\\w+::\\S+)\", text):\n            col, item = col_item.split('::')\n            text = re.sub(col_item, '<span style=\"color:{}\">{}</span>'.format(col, item), text)\n    except: pass\n    return display(Markdown(text))\n\nmd_text = '** green::some markdown ** `truly nice` $\\phi$ {}'.format(' red::hack')\nprintmd(md_text)\nprintmd('** {}::{} **'.format('green', 'bold_green_text'))\nprintmd('<green::red> more text')\nprintmd('red::red, black:orange::orange : blue: :green::c')\n\n```\n\n\n```python\n# in flask env\n!touch requirements.txt && pip freeze > requirements.txt\n```\n\n\n```python\n# Running servers\n!jupyter notebook list\n```\n\n\n```python\n# Automatically reload modules - for working with own modules\n# https://ipython.org/ipython-doc/3/config/extensions/autoreload.html\n%load_ext autoreload\n%autoreload 2\n```\n\n\n```python\n!pwd\n```\n\n\n```python\n# Ipython.__file__\n```\n\n\n```python\n%psearch?\n```\n\n\n```python\n%config\n# https://ipython.org/ipython-doc/3/interactive/magics.html\n```\n\n### Load aliases \nfrom my_lib/aliases.py\n\n\n```python\n%alias aliases \\%load my_lib/aliases.py\n```\n\n\n```python\n%aliases\n```\n\n\n```python\n# %load my_lib/aliases.py\n# Generic aliases\n%alias show echo\n%alias mop echo Monty Python\n%alias tree pwd && tree . %s\n%alias find find ~ | grep -i %s\n%alias find.. find .. | grep -i %s\n%alias find. find . | grep -i %s\n%alias findx find ~ | grep -Ei %s\n%alias read cat %s\n%alias aug ls -al | grep Aug | grep -v 2018\n\n# !brew install cowsay\n%alias say cowsay\n%alias_magic t timeit\n\n# Create directory with packages for importing\n%alias make_lib mkdir my_lib && touch my_lib/__init__.py  \n%alias add_lib cp %s my_lib/my_module.py\n%alias to_lib mkdir my_lib && touch my_lib/__init__.py && cp %s my_lib/my_module.py\n```\n\n---\n## Setup notebook\n---\n\n### Import the generic libraries used in this notebook\n\n\n```python\nimport numpy as np\nimport pandas as pd\n\n%matplotlib inline\n# import matplotlib\nimport matplotlib.pyplot as plt\n\nfrom collections import OrderedDict, Counter\nimport string\nimport re\nimport datetime\nimport requests\nimport json\nimport pprint\n```\n\n### Import interactive widgets library\n\n\n```python\nfrom ipywidgets import interact, fixed\nfrom IPython.html import widgets\nfrom IPython.display import HTML, IFrame\n```\n\n### Toggle code dispay\n\n\n```python\nHTML('''\n<form action=\"javascript:code_toggle()\"><input type=\"submit\" value=\"Show/hide code\"></form>''')\n```\n\n### Manage warnings\n\n\n```python\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n# warnings.filterwarnings(\"once\") # always will print every occurance\n```\n\n### Set defaults and constants\n\n\n```python\n# seed the random number generator so we all get the same results\nrand_seed = 2018\nnp.random.seed(rand_seed)\nepsy = 1e-10\n```\n\n\n```python\nmatplotlib.rc('xtick', labelsize=14) \nmatplotlib.rc('ytick', labelsize=14)\n```\n\n### Check current working directory and file structure\n\n\n```python\n%%!\n# directories with token\nls -FGlAhp | grep 'ml'\n```\n\n\n```python\ntoday = datetime.now().strftime(r'%Y-%m-%d')\ndirname = os.path.join('../_data/news-{}'.format(today, '_name'))\nos.makedirs(dirname, exist_ok=True)\n```\n\n\n```python\ndef sys_info():\n    !echo \"You are logged on:$NC \"; scutil --get ComputerName\n    !echo \"The current datetime is:$NC \" ; date\n    !echo  \"\\nMachine stats:$NC \" ; uptime; macstats\n    !echo  \"\\nDisk usage:$NC \"; df -l\n    !echo \"\\nPublic facing IP address:$NC \"; myip\n    !echo\n```\n\n\n```python\nsys_info()\n```\n\n\n```python\n# !brew install cowsay\n!cowsay 'Hello Awesome Notebook'\n```\n\n\n```python\n# !brew install tree\n!tree . | head -10\n```\n\n\n```python\n!find .. | grep -i edit\n```\n\n\n```python\n!pwd\n!ls data | head -5\n```\n\n\n```python\n# Find file\ndef get_file_path(filename, first=5):\n    !pwd\n    !find . | grep '$filename' | head -'$first'\n    return None\n```\n\n\n```python\nfilename = 'full_set.txt'\nget_file_path(filename, 10)\n```\n\n### Run helper notebooks\n\n\n```python\n%run 'organ_helper.py'\n```\n\n---\n## Utils\n---\n\n\n```python\n# Mute terminal Output / Out[]:\n\n_ = 3\n3;\n```\n\n### Debug, test, \n\n\n```python\n%timeit\n```\n\n### Save as Excel spreadsheet\n\n\n```python\nwriter = pd.ExcelWriter('data/excel_test.xlsx')\ndf = pd.DataFrame(np.ones(10).reshape(-1, 5))\n\n# index startrow/startcol N means value is inserted at N+1\ndf.to_excel(writer, 'sheet_name', startrow=5, startcol=5, header=False, index=False)\nwriter.save()\n```\n\n### Print output at same position\n\n\n```python\nprint('\\b\\b\\b{}'.format(i), sep='', end='', flush=True)\n# or\nprint('{}{}'.format('\\b'*len(str(len(text))), len(text)), end='')\n```\n\n### Download files from list\n\n\n```python\n!cat url-list.txt | xargs wget \u2013c\n```\n\n### Show all Out from cell - iso only the last\n\n\n```python\nfrom IPython.core.interactiveshell import InteractiveShell\n\nInteractiveShell.ast_node_interactivity = \"all\"\n```\n\n\n```python\n# !find ~ | grep .ipython/profile_default\n```\n\n#### Run all nodes interactively for all instances of Jupyter (Notebook and Console)\n\n - simply create a file ~/.ipython/profile_default/ipython_config.py with the lines below.\n\n\n```python\n%%writefile ~/.ipython/profile_default/ipython_config.py\nget_config()\n\n# Run all nodes interactively\nc.InteractiveShell.ast_node_interactivity = \"all\"\n```\n\n\n```python\n!cat ~/.ipython/profile_default/ipython_config.py\n```\n\n### Open TextEdit to edit file\n\n\n```python\n!open -e $ipython_config\n```\n\n### RISE slideshow\n\n\n```python\n!pip install RISE\n```\n\n\n```python\n!jupyter-nbextension install rise --py --sys-prefix\n```\n\n\n```python\n!jupyter-nbextension enable rise --py --sys-prefix\n```\n\n\n```python\n# matplotlib legend without repeat\n```\n\n\n```python\n# Legend without repeat\nhandles, labels = plt.gca().get_legend_handles_labels()\nby_label = OrderedDict(zip(labels, handles))\nplt.legend(by_label.values(), by_label.keys())\n```\n\n\n```python\nplt.rcParams.find_all\n```\n\n\n```python\n%%writefile ../../_data/standard_import.txt\n\n%matplotlib inline\nplt.style.use('seaborn-white')\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n```\n\n\n```python\n# %load ../_data/standard_import.txt\n\n%matplotlib inline\nplt.style.use('seaborn-white')\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n```\n\n\n```python\n\n# https://pandas.pydata.org/pandas-docs/stable/generated/pandas.set_option.html\n# pd.set_option('display.notebook_repr_html', False)\n```\n\n\n<font  style=\"color:blue\"> **Code**</font>\n```python\n# test function \ntesty_L2 = NN_L2(trainx, trainy, testx)\nprint( type( testy_L2) )\nprint( len(testy_L2) )\nprint( testy_L2[40:50] )\n```\n\n<font  style=\"color:magenta\"> **Output**</font>\n```\n<class 'numpy.ndarray'>\n62\n[ 2.  2.  1.  0.  0.  2.  0.  0.  0.  0.]\n```\n\n\n\n```python\ntrain_digits, train_counts = np.unique(train_labels, return_counts=True)\nprint(\"Training set distribution:\")\nprint(dict(zip(train_digits, train_counts)))\n```\n\n\n```python\ndef tree_plot(clf, features, labels=None):\n    \"\"\"Plot decision tree in Notebook\"\"\"\n    from sklearn import tree\n    import graphviz\n    from pydotplus import graph_from_dot_data\n\n    dot_data = tree.export_graphviz(clf, out_file=None, feature_names=features, class_names=labels,\n                             filled=True, rounded=True, special_characters=True, impurity=True, proportion=False)\n    return Image(graph_from_dot_data(dot_data).create_png())\n```\n\n\n```python\n# nxn similarity matrix\nx = np.arange(-5, 5.1, 0.1)\ny = np.arange(-4, 4.1, 0.1)\n\nK = np.zeros((x.shape[0], y.shape[0]))        \nfor (i,j), _ in np.ndenumerate(K):\n    K[i,j] = (x[i] - y[j])\nK\n```\n\n\n```python\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Create all possible pairs (x, y)\nx = np.arange(-1, 1.1, 0.1)\ny = np.arange(-2, 2.1, 0.1)\nxx, yy = np.meshgrid(x, y, sparse=False)\nxx[:3, :3]\nyy[:3, :3]\n[(x.round(1), y.round(1)) for x, y in zip(xx.ravel(), yy.ravel())][:25]\n\nz = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)\n\nprint(x.shape, y.shape, xx.shape, yy.shape, z.shape)\nh = plt.contourf(x, y, z)\n```\n\n\n```python\ndef xy_grid(x, y, ax_pad=0, density=0.1):\n    \"\"\"returns grid of (xx, yy) pairs, w.r.t. density and padding\"\"\"\n    xmin, xmax = min(x)-ax_pad, max(x)+ax_pad\n    ymin, ymax = min(y)-ax_pad, max(y)+ax_pad\n    xx, yy = np.meshgrid(np.arange(xmin, xmax+density, density), np.arange(ymin, ymax+density, density))\n    return np.c_[xx.ravel(), yy.ravel()]\n\nx = np.arange(-1, 1.1)\ny = np.arange(-2, 2.1)\nxy_grid(x, y, ax_pad=0, density=0.05)\n```\n\n\n```python\ndef xy_grid(x, y, ax_pad=0, density=0.1):\n    \"\"\"returns grid of (xx, yy) pairs, w.r.t. density and padding\"\"\"\n    xmin, xmax = min(x)-ax_pad, max(x)+ax_pad\n    ymin, ymax = min(y)-ax_pad, max(y)+ax_pad\n    xx, yy = np.meshgrid(np.arange(xmin, xmax+density, density), np.arange(ymin, ymax+density, density))\n    return {'array': np.c_[xx.ravel(), yy.ravel()], \n            'xx': xx, 'yy': yy,\n            'xmin': xmin, 'xmax': xmax, \n            'ymin': ymin, 'ymax': ymax}\n```\n\n\n```python\ndef confusion_df(y_true, y_pred):\n    cm = confusion_matrix(y_true, y_pred)\n    cm_df = pd.DataFrame(cm.T, index=svc.classes_, columns=svc.classes_)\n    cm_df.index.name = 'Predicted'\n    cm_df.columns.name = 'True'\n    return cm_df\n```\n\n\n```python\n\n```\n\n\n```python\n# Making the Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\n\ncm = confusion_matrix(y_test, y_pred)\ncm\n# Accuracy\nnp.sum(np.eye(2) * cm) / np.sum(cm)\n```\n\n\n```python\n# confusion matrix/pivot table\ndef pivot(df, ftr1, ftr2):\n    return df.groupby([ftr1,ftr2]).size().unstack(ftr2).T\n```\n\n\n```python\ndef pivot(y, y_pred):\n    df = pd.DataFrame({'True label': y, 'Predicted label': y_pred})\n    return df.groupby(['True label', 'Predicted label']).size().unstack('Predicted label').T\n```\n\n\n```python\ndef pivot(y, y_pred, labels=['Negative', 'Positive']):\n    dict_labels = {k:v for k, v in zip(np.unique(y), labels)}\n    df = pd.DataFrame({y.name: y, y_pred.name: y_pred})\n    df.replace(to_replace=dict_labels, inplace=True)\n    return df.groupby([y.name, y_pred.name]).size().unstack(y_pred.name).T\n```\n\n\n```python\ndef pivot(y, y_pred, labels=['Negative', 'Positive']):\n    dict_labels = {k:v for k, v in zip(np.unique(y), labels)}\n    try:\n        y_name, y_pred_name = y.name, y_pred.name\n    except:\n        y_name, y_pred_name = 'True label', 'Predicted label'\n    df = pd.DataFrame({y_name: y, y_pred_name: y_pred})  \n    df.replace(to_replace=dict_labels, inplace=True)\n    return df.groupby([y_name, y_pred_name]).size().unstack(y_pred_name)\n```\n\n\n```python\n# Workaround to fix bug in statsmodels .summary()\n# https://github.com/statsmodels/statsmodels/issues/3931\nfrom scipy import stats\nstats.chisqprob = lambda chisq, df: stats.chi2.sf(chisq, df)\n```\n\n## Bug fixes - statsmodels not compatible with current stable version of scipy/pandas\n\n\n```python\n# Statsmodels bug fix:\nfrom pandas.core import datetools\n\nimport statsmodels.api as sm\nimport statsmodels.formula.api as smf\n\n# Workaround to fix bug in statsmodels .summary() - missing stats.chisqprob function\n# https://github.com/statsmodels/statsmodels/issues/3931\nfrom scipy import stats\nstats.chisqprob = lambda chisq, df: stats.chi2.sf(chisq, df)\n```\n\n\n```python\n# parse datetime \ndf = pd.read_csv('../../_data/Smarket.csv', usecols=range(1, 10), index_col=0, parse_dates=True) \n# select columns\npd.read_csv('../../_data/Advertising.csv', usecols=[1,2,3,4])\npd.read_csv('../../_data/Credit.csv', usecols=list(range(1,12)))\npd.read_csv('../../_data/Auto.csv', na_values='?').dropna()\n```\n\n\n```python\n# Probability counter with threshold\nthres = 0.9\nband = [0.4, 0.6]\n\npred_p = clf.predict_proba(X_test)\nnp.unique(pred_p[:, 1]>thres, return_counts=True)\nnp.unique(band[0] > pred_p[:, 1] > band[-1], return_counts=True)\n```\n\n\n```python\nmargin = 0.03\nnp.unique(pred_p[:, 1] < 0.5+margin, return_counts=True), 'smaller than .5+margin'\nnp.unique(0.5-margin < pred_p[:, 1], return_counts=True), 'bigger than .5-margin'\n'Predictions between margin({}) [false true] : {}'.format(margin, \nnp.unique(pred_p[:, 1] < 0.5+margin, return_counts=True)[1] + np.unique(0.5-margin < pred_p[:, 1], return_counts=True)[1])\n```\n\n\n```python\nnp.set_printoptions(suppress=True, precision=3, threshold=10)\n# np.set_printoptions()  # formatter gets reset\n```\n\n\n```python\n# Output numpy as laTex\nimport IPython\nip = IPython.core.getipython.get_ipython()\nfrom IPython.display import display, Math, Latex\nimport sympy as sp\nfrom IPython.display import Latex, display, display_latex\nfrom sympy.interactive import printing\nprinting.init_printing(use_latex='png')\n\nfrom sympy import Matrix as spx\nsp.init_printing(use_unicode=True)\n# sp.init_printing(use_latex='png')\nip.display_formatter.formatters['text/latex'].enabled = True\n\nspx([[1, -1], [3, 4], [0, 2]])\n```\n\n\n```python\n# http://docs.sympy.org/0.7.2/tutorial.html#printing-tutorial\nfrom sympy.printing import print_latex as plx\nfrom sympy.printing import print_mathml as plm\n\nfrom sympy.printing import latex as slx\nfrom sympy.printing import mathml as slm\n\nip.display_formatter.formatters['text/latex'].enabled = True\n\nplx([[1, -1], [3, 4], [0, 2]])\nltx = slx([[1, -1],\n           [3, 4], \n           [0, 2]])\ndisplay(Latex('${}$'.format(ltx)))\n\ndisplay(Latex(slx([[1, -1], [3, 4], [0, 2]])))\n\n```\n\n\n```python\nimport IPython\nip = IPython.core.getipython.get_ipython()\n\n# Sympy are setting:\nip.display_formatter.formatters['text/latex'].enabled = False\n# to disable all latex output. You can revert this with \nip.display_formatter.formatters['text/latex'].enabled = True\n```\n\n\n```python\nfrom IPython.display import Latex, display, display_latex\nfrom sympy.interactive import printing\nprinting.init_printing(use_latex='png')\ndisplay(Latex('$\\\\alpha^2 + \\\\eta$'))\n\ndisplay(Latex(slx([[1, -1], [3, 4], [0, 2]])))\n```\n\n\n```python\n# set precision\npd.set_option('float_format', '{:.2f}'.format)\n```\n\n\n```python\n# qgrid.version_info\n!jupyter notebook --version\n!jupyter lab --version\n!pip list | grep widgets\n!pip list | grep jupyter\n!pip list | grep qgrid\n```\n\n\n```python\nN = 5\nZ = np.zeros(N*N).reshape(-1, N)\nZ = [distance(MNIST.data[i], MNIST.data[j]) for (i,j), v in np.ndenumerate(np.zeros(N*N).reshape(-1, N))]\nZ = np.array(Z).reshape(-1, N)\nZ\n```\n\n\n```python\nN = 5\nZ = np.zeros(N*N).reshape(-1, N)\nfor (i,j), v in np.ndenumerate(Z):\n    Z[i,j] = distance(MNIST.data[i], MNIST.data[j])\nZ\n```\n\n\n```python\ndef pairwise_map(data, fn, N=0):\n    if N == 0: N = len(data)\n    Z = np.zeros(N*N).reshape(-1, N)\n    for (i,j), v in np.ndenumerate(Z):\n        Z[i,j] = fn(data[i], data[j])\n    return Z\n```\n\n\n```python\nimport numpy as np\n# Peak to peak - (max - min)\nb1 = np.array([2,1,1])\nb2 = np.array([1,3,4])\nb3 = np.array([1,4,9])\n\nB = np.stack((b1, b2, b3), axis=0)\nnp.ptp(B, axis=0)\nnp.ptp(B, axis=1)\n```\n\n\n```python\n# Piecewise binning and clipping\nx = np.arange(50)\nx\ny = 20\nnp.piecewise(x, [x>0 , x>10, x>20], [0, 10, y])\nnp.piecewise(x, [x<10, ((10<=x) & (x<40)), x>=40], [-1, lambda x: x, 1])\n```\n\n\n```python\ndef cut_outliers(pd_series, z_value=1.96):\n    X = pd_series\n    lb = np.mean(X) - z_value * np.std(X)\n    ub = np.mean(X) + z_value * np.std(X)\n    return np.piecewise(X, [X < lb, ((lb <= X) & (X < ub)), X >= ub], [lb, lambda X: X, ub])\n```\n\n\n```python\ndef cut_min_max(pd_series, mini, maxi):\n    X = pd_series\n    lb = mini\n    ub = maxi\n    return np.piecewise(X, [X < lb, ((lb <= X) & (X < ub)), X >= ub], [lb, lambda X: X, ub])\n```\n\n#### DataFrame to dictionary - key is index\n\nDrops NaN's from index!\n\n\n```python\ncities = pd.read_excel('../_data/global-city-population-estimates.xlsx', 'CITIES-OVER-300K')\ncities.sample(5)\ncities_dict = cities[['Urban Agglomeration', '2015']].set_index('Urban Agglomeration').to_dict()['2015']\ncities_dict\n```\n\n\n```python\ndf.to_dict\ndf.to_dict('index')\ndf.to_dict('index').items()\nairport_dict = airports[['lon', 'lat']].to_dict('index') \n```\n\n\n```python\nhttps://www.census.gov/popclock/world/nl\n```\n\nNext we can use a lambda to pull out the outcome from the attributes dictionary.\n\n\n```python\ndf['outcome'] = df['outcome'].map(lambda x: x['outcome'])\ndf.head()\n```\n\n\n```python\ndef extract_dict_value(x, ftr):\n    try: return x[ftr]\n    except: return 0\n\ndf['score'] = df['score_weight'].map(lambda x: extract_dict_value(x, 'score'))\n```\n\n\n```python\n# [:] copies the slice\n```\n\n\n```python\nX_train.select_dtypes('float')\n```\n\n### open notebook link\n[Open Notebook](./nlp_part2_sentiment_topic_similarity_classification_.ipynb)\n\n\n```python\n\n```\n\n\n```python\nfile = '../_credentials/twitter_credentials.txt'\npickle_file = '../_credentials/twitter_credentials.pkl'\n```\n\n\n```python\n%%writefile {file}\np6mTTVJjjBi0G59xIbpkooJXH\nY44ZH5ME8SndWYSCk7WpegQKwyPecnmLOUX2UAIFEGaC3TZayR\n27198609-TDq5p3hTA8VTNJtwUASxUT21nnTs6jOxYlDONgkeQ\n1wDvWkmZnoxeQnzaylH00FIhgNBhlX4DOy5vWLBUIow53\n```\n\n\n```python\ndef recursive_keys(json, i=2):\n    \"\"\"Recursively get keys and list items\"\"\"\n    if type(json) == dict:\n        for key, value in json.items():\n#                 print('-'*i, key)\n                if type(json[key]) == str: \n                    print('--', key)\n                    continue\n                elif type(json[key]) == list: \n                    print('list', key)\n                    recursive_keys(json[key]) # [0]\n                elif type(json[key]) == dict: \n                    print('dict', key)\n                    recursive_keys(json[key])\n\n    elif type(json) == list:\n        for i, item in enumerate(json):\n            print(i, end=' ')\n            recursive_keys(json[i])\n```\n\n\n```python\n\n```\n\n\n```python\ndef xml2dict(xml):\n    \"\"\"Convert XML to dictionary format.\"\"\"\n    import plistlib\n    return plistlib.loads(str.encode(xml), fmt=plistlib.FMT_XML)\n```\n\n\n```python\ndef wifi_positioning(saved_map=False):\n    \"\"\"Return current location based on nearby wifi-hotspots.\"\"\"\n    \n    payload = wifi_hotspots()\n    \n    if payload is None:\n        print('WIFI positioning failed, returning IP location from provider')\n        _, lat, lon, radius = ip_location()\n        latlon = '{}, {}'.format(lat, lon)\n    else:\n        api_url_locate = 'https://pos.cit.api.here.com/positioning/v1/locate'\n        json_result = geo_location(api_url_locate, payload)\n        lat, lon = json_result['location']['lat'], json_result['location']['lng']\n        latlon = '{}, {}'.format(lat, lon)\n        radius = json_result['location']['accuracy']\n\n    # Print address and lat, lon, radius and open/show location on map\n#     print('\\ngeoPy Nominatim location: ', geolocator.reverse(latlon))\n#     rev_geocoder(lat, lon, radius)\n#     here_maps = 'https://wego.here.com/directions/mix/{},{}/?map={},{},15'.format(lat, lon, lat, lon)\n#     google_maps = 'https://www.google.com/maps/search/{},{}/@{},{},17z'.format(lat, lon, lat, lon)\n#     !open -a Safari $here_maps; open -a Safari $google_maps\n#     if saved_map: mia_saved_map(lon, lat, radius)\n        \n    return lat, lon\n```\n\n\n```python\nimport quilt\n# https://quiltdata.com\nquilt.install(\"ResidentMario/geoplot_data\")\n```\n\nIndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices\n", "meta": {"hexsha": "a518bdc9689a9bdae405bebc1741ec70768f8a07", "size": 37618, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "_productivity/utils_.ipynb", "max_stars_repo_name": "aixpact/data-science", "max_stars_repo_head_hexsha": "f04a54595fbc2d797918d450b979fd4c2eabac15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-07-22T23:12:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-25T02:30:48.000Z", "max_issues_repo_path": "_productivity/utils_.ipynb", "max_issues_repo_name": "aixpact/data-science", "max_issues_repo_head_hexsha": "f04a54595fbc2d797918d450b979fd4c2eabac15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_productivity/utils_.ipynb", "max_forks_repo_name": "aixpact/data-science", "max_forks_repo_head_hexsha": "f04a54595fbc2d797918d450b979fd4c2eabac15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7812911726, "max_line_length": 135, "alphanum_fraction": 0.519884098, "converted": true, "num_tokens": 5983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771241500058, "lm_q2_score": 0.11757213199952934, "lm_q1q2_score": 0.03974844826658575}}
{"text": "<div class=\"alert alert-block alert-info\">\n    \n    <u><h1>Introduction to respy</h1></u>\n</div>\n\n### What is **respy**?\n\n**respy** is an open source framework written in Python for the simulation and estimation of some finite-horizon discrete choice dynamic programming models. The group of models which can be currently represented in **respy** are called Eckstein-Keane-Wolpin models.\n\n### Where do I find more information?\n\n**GitHub:** The source code is available at https://github.com/OpenSourceEconomics/respy.\n\n**Online Documentation:** The online documentation with tutorials, guides, and more is available at https://respy.readthedocs.io.\n\n**Lectures:** Lectures on selected topics like Maximum Likilhood estimation using **respy** can be found here: https://ekw-lectures.readthedocs.io.\n\n### Why should I use the package?\n\nWhat makes **respy** powerful is that it allows to build and solve structural models in weeks or months whose development usually takes years. \n\n### Tutorial Outline\n\nThe upcoming tutorial provides an example on how you can utilize **respy** to set up your own model. As an example, we implement a Robinson Crusoe economy as a discrete choice dynamic programming model. The tutorial is structured as follows:\n\n 1.  Installation  \n 2.  Introductory Tutorial  \n  2.1. Theoretical Framework  \n  2.2. Specifying a Model in Respy  \n  2.3. Simulating Data  \n  2.4. Extending the Model  \n 3. Example Models in respy\n 4. Further and upcoming functionalities in respy and other OpenSourceEconomics packages\n    \n\n<div class=\"alert alert-block alert-info\">\n    <u><h2>1. Installation</h2></u>\n</div>\n\nThe package can be installed via conda as follows\n\n```\n$ conda config --add channels conda-forge\n$ conda install -c opensourceeconomics respy\n```\n\nAfter doing so, you can import respy alongside all other packages you are using.\n\n\n```python\nimport io\nimport copy\nimport yaml\nimport numpy as np\nimport pandas as pd\nimport respy as rp\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom IPython.display import Image\nfrom pathlib import Path\n\nfrom auxiliary.auxiliary import *\n```\n\n<div class=\"alert alert-block alert-info\">\n    <u><h1>2. Introductory Tutorial</h1></u>\n</div>\n\n<div class=\"alert alert-block alert-info\">\n    <u><h2>2.1. Theoretical Framework: Robinson Crusoe on an island</h2></u>\n</div>\n\n> After setting sail against his parents' wishes, being captured by pirates, escaping from them, building a plantation, and setting sail again, [Robinson Crusoe](https://en.wikipedia.org/wiki/Robinson_Crusoe) stranded on a small island. He is alone with one dog, two cats, and only some supplies. He goes fishing to make ends meet and if he is too tired he will relax in his hammock. But, he cannot relax to often as storing food is a difficult task on a tropical island.\n\n\nSummarizing this economic problem:\n\n- Robinson chooses every period $t = 0, \\dots, T$ to either go fishing, $a = 0$, or spend the day in the hammock, $a = 1$.\n\n\n```python\nImage(filename=\"figures/tree_small.jpg\")\n```\n\n\n\n\n    \n\n    \n\n\n\n- If Robinson chooses to go fishing, he gains one additional unit of experience in the next period. Experience starts at zero.\n\n- The utility of a choice, $U(s_t, a_t)$, depends on the state $s_t$, which contains information on the individual's characteristics, and the chosen alternative $a_t$.\n\n- Robinson's utility for any given option can be denoted by\n\n$$\\begin{align}\n    U(s_t, a_t) = \\underbrace{W(s_t, a_t)}_{wage} + \\underbrace{N(s_t, a_t)}_{non-pecuniary}\n\\end{align}$$\n\n**Working alternatives**\n\n- For working alternatives like fishing, utility consists of two components, a wage and a non-pecuniary component. The wage is defined as \n\n$$\\begin{align}\n        W(s_t, a_t)  &= r_a \\exp\\{x^w_{at} \\beta^w_a + \\epsilon_{at}\\}\\\\\n    \\ln(W(s_t, a_t)) &= \\ln(r_a) + x^w_{at} \\beta^w_a + \\epsilon_{at}\n\\end{align}$$\n\n- It consists of several components:\n    - $r_a$ is a market rental price for skill units.\n    - $x^w_{at}$ and $\\beta^w_a$ are the choice- and time-dependent covariates and returns related to the wage signaled by superscript $w$. \n    - $\\epsilon_{at}$ is a choice-specific random shock from the shock vector $\\epsilon_t \\sim \\mathcal{N}(0, \\Sigma)$ for all choices.\n\n- The non-pecuniary rewards for working alternatives are a vector dot product of covariates $x_t^w$ and parameters $\\beta^w$. The superscript $w$ signals that the components belong to working alternatives.\n\n$$\\begin{align}\n    N^w(s_t, a_t) = x_t^w\\beta^w\n\\end{align}$$\n\n**Non-working alternatives**\n\n- For non-working alternatives like the hammock, $W(s_t, a_t) = 0$. The non-pecuniary reward for non-working alternatives is very similar to the working alternative except that the shocks enter the equation additively. Superscript $n$ stands for non-pecuniary.\n\n$$\n    N^n(s_t, a_t) = x_t^n\\beta^n + \\epsilon_{at}\n$$\n\n\n- Robinson's choice set thus consists of a \"working\" alternative which awards him a pecuniary compensation or wage and a \"leisure\" or non-working alternative which he derives a utility from, but no experience or wage. Experience in this basic model starts at zero and increases by one for every period $t$ in $1, ..., T$ where he chooses to go fishing. \n\n\n**Robinson's choice problem**\n\n- During his time on the island, Robinson has to make choices about which actions to take. The general assumption is that Robinson is forward-looking and maximizes the expected present value of utility over the remaining lifetime which is achieved by selecting the optimal sequence of choices $\\{a_t\\}^T_{t = 0}$.\n\n\n- Robinsons decision problem can be expressed as a Bellman equation where the value of a given state consists of the current and future state values associated with it.  \n\n$$\\begin{align}\n    V(s_{t})&= \\max_{a_t} \\, \\{\\underbrace{U(s_t, a_t)}_{\\text{flow utility}}+ \\delta \\underbrace{\\text{E}[ V(s_{t+1})]\\}}_{\\text{continuation value}}\n\\end{align}$$\n\n- For each period, the value of a given choice consists of its flow utility and its continuation value. Since the realization of shocks becomes known in each period before Robinson makes his choice, the flow utility can be extracted from the expectation operator. As shocks in period $t + 1$ are unknown to the individual in period $t$, utility must be maximized given the joint distribution of shocks in period $t + 1$ which is a maximization problem over a two-dimensional integral. Denote the non-stochastic part of a state as $s^-$. Then, Robinson maximizes\n\n$$\\begin{equation}\n    V(s_t) = \\max_{a_t}\\{\n        U(s_t, a_t) + \\delta \\int_{\\epsilon_{1, t + 1}} \\int_{\\epsilon_{0, t + 1}}\n        \\max_{a_{t + 1}} V_{a_{t + 1}}(s^-_{t + 1}, \\epsilon_{t + 1})\n        f_\\epsilon(\\epsilon_{t + 1})\n        d_{\\epsilon_{0, t + 1}}, d_{\\epsilon_{1, t + 1}}\n    \\}\n\\end{equation}$$\n\n<div class=\"alert alert-block alert-info\">\n    <u><h2>2.2. Specifying the Model in respy</h2></u>\n</div>\n\nWe can use **respy** to implement the model specified above. In order to process a model, **respy** requires two main inputs: `params` and `options`.\n\n\n### params\n\nThe `params` object acts as the parameter vector of the model. Most of its values translate directly to parameters you can see in the equations. \n\nParameters are specified as a [MultiIndex pandas.DataFrame](https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html) with two index levels. A *category* which indicates certain parameters groups and a *name* which indicates a specific parameter. There are certain naming conventions in place that help **respy** recognize different parameters of the model.\n\nWe can read in parameters from a .csv-file. Here we define the parameter data in a string format to showcase the specification. Usually, the more convenient way would be to specify the parameters outside this notebook and to just import them from a separate file.\n\n\n```python\nparams = \"\"\"category,name,value\ndelta,delta,0.95\nwage_fishing,exp_fishing,0.1\nnonpec_fishing,constant,-1\nnonpec_hammock,constant,2.5\nnonpec_hammock,not_fishing_last_period,-1\nshocks_sdcorr,sd_fishing,1\nshocks_sdcorr,sd_hammock,1\nshocks_sdcorr,corr_hammock_fishing,-0.2\nlagged_choice_1_hammock,constant,1\n\"\"\"\n```\n\n\n```python\nparams_basic = pd.read_csv(\n    io.StringIO(params), sep=\",\", index_col=[\"category\", \"name\"]\n)\n```\n\n\n```python\nparams_basic\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>value</th>\n    </tr>\n    <tr>\n      <th>category</th>\n      <th>name</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>delta</th>\n      <th>delta</th>\n      <td>0.95</td>\n    </tr>\n    <tr>\n      <th>wage_fishing</th>\n      <th>exp_fishing</th>\n      <td>0.10</td>\n    </tr>\n    <tr>\n      <th>nonpec_fishing</th>\n      <th>constant</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">nonpec_hammock</th>\n      <th>constant</th>\n      <td>2.50</td>\n    </tr>\n    <tr>\n      <th>not_fishing_last_period</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">shocks_sdcorr</th>\n      <th>sd_fishing</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>sd_hammock</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>corr_hammock_fishing</th>\n      <td>-0.20</td>\n    </tr>\n    <tr>\n      <th>lagged_choice_1_hammock</th>\n      <th>constant</th>\n      <td>1.00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### options\n\nThe second object required to set up a model are the `options`. The are specified as a dictionary which contains additional information like the number of periods in the model or the size of the simulated sample.\n\n\n```python\noptions_basic = {\n    \"n_periods\": 10,\n    \"simulation_agents\": 1000,\n    \"simulation_seed\": 123,\n    \"covariates\": {\n        \"constant\": \"1\",\n        \"not_fishing_last_period\": \"lagged_choice_1 != 'fishing'\",\n    },\n}\n```\n\n\n```python\noptions_basic\n```\n\n\n\n\n    {'n_periods': 10,\n     'simulation_agents': 1000,\n     'simulation_seed': 123,\n     'covariates': {'constant': '1',\n      'not_fishing_last_period': \"lagged_choice_1 != 'fishing'\"}}\n\n\n\n<div class=\"alert alert-block alert-info\">\n    <u><h2>2.3. Simulating Data</h2></u>\n</div>\n\nUsing the `params` and `options` we can set up a simulator using the function `get_simulate_func` and subsequently simulate a data for our selected parametrization.\n\n\n```python\nsimulate = rp.get_simulate_func(params_basic, options_basic)\ndf_basic = simulate(params_basic)\n```\n\n\n```python\ndf_basic.head(5)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>Experience_Fishing</th>\n      <th>Lagged_Choice_1</th>\n      <th>Shock_Reward_Fishing</th>\n      <th>Meas_Error_Wage_Fishing</th>\n      <th>Shock_Reward_Hammock</th>\n      <th>Meas_Error_Wage_Hammock</th>\n      <th>Dense_Key</th>\n      <th>Core_Index</th>\n      <th>Choice</th>\n      <th>Wage</th>\n      <th>...</th>\n      <th>Nonpecuniary_Reward_Fishing</th>\n      <th>Wage_Fishing</th>\n      <th>Flow_Utility_Fishing</th>\n      <th>Value_Function_Fishing</th>\n      <th>Continuation_Value_Fishing</th>\n      <th>Nonpecuniary_Reward_Hammock</th>\n      <th>Wage_Hammock</th>\n      <th>Flow_Utility_Hammock</th>\n      <th>Value_Function_Hammock</th>\n      <th>Continuation_Value_Hammock</th>\n    </tr>\n    <tr>\n      <th>Identifier</th>\n      <th>Period</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">0</th>\n      <th>0</th>\n      <td>0</td>\n      <td>hammock</td>\n      <td>0.428556</td>\n      <td>1</td>\n      <td>0.427466</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>fishing</td>\n      <td>1.535039</td>\n      <td>...</td>\n      <td>-1</td>\n      <td>1.535039</td>\n      <td>0.535039</td>\n      <td>19.006626</td>\n      <td>19.443776</td>\n      <td>1.5</td>\n      <td>NaN</td>\n      <td>1.833118</td>\n      <td>18.704274</td>\n      <td>17.759111</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>fishing</td>\n      <td>0.780145</td>\n      <td>1</td>\n      <td>1.850937</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>hammock</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>-1</td>\n      <td>2.411250</td>\n      <td>1.411250</td>\n      <td>19.104983</td>\n      <td>18.624982</td>\n      <td>2.5</td>\n      <td>NaN</td>\n      <td>4.157512</td>\n      <td>20.273393</td>\n      <td>16.964086</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1</td>\n      <td>hammock</td>\n      <td>2.063393</td>\n      <td>1</td>\n      <td>0.708209</td>\n      <td>1</td>\n      <td>2</td>\n      <td>0</td>\n      <td>fishing</td>\n      <td>8.700606</td>\n      <td>...</td>\n      <td>-1</td>\n      <td>8.700606</td>\n      <td>7.700606</td>\n      <td>23.415469</td>\n      <td>16.541961</td>\n      <td>1.5</td>\n      <td>NaN</td>\n      <td>1.781221</td>\n      <td>16.030649</td>\n      <td>14.999397</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>2</td>\n      <td>fishing</td>\n      <td>-1.190336</td>\n      <td>1</td>\n      <td>-2.028002</td>\n      <td>1</td>\n      <td>3</td>\n      <td>4</td>\n      <td>fishing</td>\n      <td>0.371452</td>\n      <td>...</td>\n      <td>-1</td>\n      <td>0.371452</td>\n      <td>-0.628548</td>\n      <td>13.904880</td>\n      <td>15.298346</td>\n      <td>2.5</td>\n      <td>NaN</td>\n      <td>0.751039</td>\n      <td>13.874853</td>\n      <td>13.814541</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>3</td>\n      <td>fishing</td>\n      <td>-0.049084</td>\n      <td>1</td>\n      <td>0.607816</td>\n      <td>1</td>\n      <td>4</td>\n      <td>5</td>\n      <td>hammock</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>-1</td>\n      <td>1.285202</td>\n      <td>0.285202</td>\n      <td>13.405278</td>\n      <td>13.810606</td>\n      <td>2.5</td>\n      <td>NaN</td>\n      <td>3.105353</td>\n      <td>14.884157</td>\n      <td>12.398742</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 22 columns</p>\n</div>\n\n\n\nUsing our simulated data, we can now inspect the choices of Robinson.\n\n\n```python\nplot_choice_shares(df_basic)\n```\n\nInspecting the persistence in choices shows that Robinson rarely chooses the same option multiple times in a row.\n\n\n```python\ndata = pd.crosstab(df_basic.Lagged_Choice_1, df_basic.Choice, normalize=True)\nsns.heatmap(data, cmap=\"Blues\", annot=True)\n```\n\n<div class=\"alert alert-block alert-info\">\n    <u><h2>2.4. Extending the Model</h2></u>\n</div>\n\nAs already stated in the introduction, one of the main advantages of **respy** is that the package is flexible regarding the model structure. We will illustrate this by extending the previously introduced model framework in several different ways.\n\n<div class=\"alert alert-block alert-info\">\n    <u><h3>2.4.1. Extension: Covariates</h3></u>\n</div>\n\nNext we want to add a covariate. As before, we concentrate on a simple example, but this can be extended in any direction. Note, that in the basic model we had two covariates: \n\n1. The constant, which is the simplest covariate\n2. The indicator whether Robinson went fishing last period.\n\nCovariates allow to specify advanced return structures to each choice. In the following example, Robinson's return to fishing decreases as he gets older. We assume that he arrives at the island with 16 years. Then his age in each period, which we assume for now is one year, increases by one. So in each period his age is given by `period + 16`. We define the covariate and his value in each period in the option file.\n\n\n```python\noptions_age = copy.deepcopy(options_basic)\noptions_age[\"covariates\"].update({\"age\": \"period + 16\"})\noptions_age\n```\n\n\n\n\n    {'n_periods': 10,\n     'simulation_agents': 1000,\n     'simulation_seed': 123,\n     'covariates': {'constant': '1',\n      'not_fishing_last_period': \"lagged_choice_1 != 'fishing'\",\n      'age': 'period + 16'}}\n\n\n\nIn a second step, we specify the return for the choice for this covariate.\n\n\n```python\nparams_age = params_basic.copy()\nparams_age.loc[(\"wage_fishing\", \"age\"), \"value\"] = -0.015\nparams_age\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>value</th>\n    </tr>\n    <tr>\n      <th>category</th>\n      <th>name</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>delta</th>\n      <th>delta</th>\n      <td>0.950</td>\n    </tr>\n    <tr>\n      <th>wage_fishing</th>\n      <th>exp_fishing</th>\n      <td>0.100</td>\n    </tr>\n    <tr>\n      <th>nonpec_fishing</th>\n      <th>constant</th>\n      <td>-1.000</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">nonpec_hammock</th>\n      <th>constant</th>\n      <td>2.500</td>\n    </tr>\n    <tr>\n      <th>not_fishing_last_period</th>\n      <td>-1.000</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">shocks_sdcorr</th>\n      <th>sd_fishing</th>\n      <td>1.000</td>\n    </tr>\n    <tr>\n      <th>sd_hammock</th>\n      <td>1.000</td>\n    </tr>\n    <tr>\n      <th>corr_hammock_fishing</th>\n      <td>-0.200</td>\n    </tr>\n    <tr>\n      <th>lagged_choice_1_hammock</th>\n      <th>constant</th>\n      <td>1.000</td>\n    </tr>\n    <tr>\n      <th>wage_fishing</th>\n      <th>age</th>\n      <td>-0.015</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nHaving adjusted the parameters and options accordingly, we can now simulate data that incorporates the new age covariate. As the plot below shows, including the negative effect of age reduces the proportion of individuals that choose fishing, increasingly so in later periods.\n\n\n```python\nsimulate = rp.get_simulate_func(params_age, options_age)\ndf_age = simulate(params_age)\n```\n\n\n```python\nplot_choice_shares(df_age)\n```\n\n<div class=\"alert alert-block alert-info\">\n    <u><h3>2.4.2. Extension: Adding Choices</h3></u>\n</div>\n\nLets return to the basic example and alter the choice set of Robinson. Let's assume after some time on the island, Robinson meets Friday we can help him improve his fishing.\n\nWe thus add the option `\"friday\"`, which affects the utility of fishing. The choice should be available only once starting with the third period, and only after Robinson has been fishing before. As a first step, we need to alter the parameter vector. Here we just import a pre-defined parameter vector from a .csv-file. There have been three main changes to the base parameter vector:\n\n1. `wage_fishing` now includes a return to contemplation with Friday.\n2. There is a new category,`nonpec_friday`, which captures the non-pecuniary reward for of spending a period with Friday. Since talking to Friday is purely non-pecuniary option, Robinson does not earn a wage when choosing it.\n3. The shock shock variance-covariance matrix has been altered to include the additional option. \n\n\n\n```python\nparams_friday = pd.read_csv(\n    \"params_files/robinson_crusoe_friday.csv\", index_col=[\"category\", \"name\"]\n)\nparams_friday\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>value</th>\n    </tr>\n    <tr>\n      <th>category</th>\n      <th>name</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>delta</th>\n      <th>delta</th>\n      <td>0.95</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">wage_fishing</th>\n      <th>exp_fishing</th>\n      <td>0.10</td>\n    </tr>\n    <tr>\n      <th>contemplation_with_friday</th>\n      <td>0.40</td>\n    </tr>\n    <tr>\n      <th>nonpec_fishing</th>\n      <th>constant</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">nonpec_friday</th>\n      <th>constant</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th>not_fishing_last_period</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">nonpec_hammock</th>\n      <th>constant</th>\n      <td>2.50</td>\n    </tr>\n    <tr>\n      <th>not_fishing_last_period</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th rowspan=\"6\" valign=\"top\">shocks_sdcorr</th>\n      <th>sd_fishing</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>sd_friday</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>sd_hammock</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>corr_friday_fishing</th>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>corr_hammock_fishing</th>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>corr_hammock_friday</th>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>lagged_choice_1_hammock</th>\n      <th>constant</th>\n      <td>1.00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nTurning to the `options`, we can see that the new covariate `\"contemplation_with_friday\"` is only affecting utility if Robinson is experienced in fishing and only for one interaction with Friday. This naturally limits the interaction with Friday.\n\n\n```python\noptions_friday = yaml.safe_load(open(\"option_files/options_friday.yml\"))\noptions_friday[\"covariates\"]\n```\n\n\n\n\n    {'constant': '1',\n     'contemplation_with_friday': 'exp_friday == 1 and exp_fishing >= 1',\n     'not_fishing_last_period': \"lagged_choice_1 != 'fishing'\"}\n\n\n\nThe key `\"negative_choice_set\"` can be used to restrict the choice Friday to the third and following periods. The first key matches a choice. \n\n\n```python\noptions_friday[\"negative_choice_set\"]\n```\n\n\n\n\n    {'friday': ['period < 2', 'exp_fishing == 0']}\n\n\n\nWe additionally need to define `core_state_space_filters` now that we added Friday. They are specified as a list of strings that define certain events which shall be avoided. If the string evaluates to `True` for a potential state, the corresponding state is eliminated from the core state space. These options thus compliment the `negative_choice_set`. \n\nSome states are impossible from a model perspective, but eliminating them using the `core_state_space_filters` is still worthwhile to eliminate them to ease the computational burden of the model. See for instance the string `\"period > 0 and exp_fishing + exp_friday == period and lagged_choice_1 == 'hammock'\"`. This expression  essentially states hat whenever individuals accumulated as many years of experience as there are periods, the previous choice cannot be a choice without experience accumulation. This seems trivial, but states for which this expression evaluates to `True` will still be included in the state space if we do not eliminate them using the filters.\n\n\n```python\noptions_friday[\"core_state_space_filters\"]\n```\n\n\n\n\n    [\"period > 0 and exp_fishing + exp_friday == period and lagged_choice_1 == 'hammock'\",\n     'period <= 2 and exp_friday != 0',\n     'period >= 3 and period - exp_friday < 2',\n     'exp_friday > 0 and exp_fishing == 0',\n     \"exp_friday > 0 and exp_fishing == 1 and lagged_choice_1 == 'fishing'\",\n     \"period - exp_friday == 2 and lagged_choice_1 != 'friday' and period > 2\",\n     \"exp_{choices_w_exp} == 0 and lagged_choice_1 == '{choices_w_exp}'\"]\n\n\n\nWe can now simulate our new model including Friday.\n\n\n```python\nsimulate = rp.get_simulate_func(params_friday, options_friday)\ndf_friday = simulate(params_friday)\n```\n\n\n```python\nplot_choice_shares(df_friday, friday=True)\n```\n\n<div class=\"alert alert-block alert-info\">\n    <u><h3>2.4.3. Extension: Initial Experience</h3></u>\n</div>\n\nAgain returning to the basic example, we will next demonstrate how to include heterogeneity in initial conditions in `respy`: In period $t=0$, Robinson will have $0$, $1$, or $2$ periods of experience in fishing. We can thus analyze what happens to Robinson's choices if he lands on the island with previous experience in fishing attained before being stranded.\n\nTo allow Robinson to have nonzero experience in fishing in the first period, we need to modify `params`: We specify the distribution of initial experience via **probability mass functions**, as the probabilities do not depend on any information. \nThe keyword is `\"initial_exp_fishing_*\"` in the category-level of the index, where the asterisk needs to be replaced with the experience level. In the name-level, use `\"probability\"` to signal that the float in `\"value\"` is a probability. \n\nThe new parameter specification is below: Robinson has equal probability to start out with 0, 1 or 2 periods of experience. However, one probability is set to 0.34 so that all probabilities sum to one. If that is not the case, `respy` will emit a warning and normalize probabilities to a uniform distribution.\n\n\n```python\nparams_initial_exp = params_basic.copy()\nparams_initial_exp.loc[\n    (\"initial_exp_fishing_0\", \"probability\"), \"value\"\n] = 0.33\nparams_initial_exp.loc[\n    (\"initial_exp_fishing_1\", \"probability\"), \"value\"\n] = 0.33\nparams_initial_exp.loc[\n    (\"initial_exp_fishing_2\", \"probability\"), \"value\"\n] = 0.34\nparams_initial_exp\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>value</th>\n    </tr>\n    <tr>\n      <th>category</th>\n      <th>name</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>delta</th>\n      <th>delta</th>\n      <td>0.95</td>\n    </tr>\n    <tr>\n      <th>wage_fishing</th>\n      <th>exp_fishing</th>\n      <td>0.10</td>\n    </tr>\n    <tr>\n      <th>nonpec_fishing</th>\n      <th>constant</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">nonpec_hammock</th>\n      <th>constant</th>\n      <td>2.50</td>\n    </tr>\n    <tr>\n      <th>not_fishing_last_period</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">shocks_sdcorr</th>\n      <th>sd_fishing</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>sd_hammock</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>corr_hammock_fishing</th>\n      <td>-0.20</td>\n    </tr>\n    <tr>\n      <th>lagged_choice_1_hammock</th>\n      <th>constant</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>initial_exp_fishing_0</th>\n      <th>probability</th>\n      <td>0.33</td>\n    </tr>\n    <tr>\n      <th>initial_exp_fishing_1</th>\n      <th>probability</th>\n      <td>0.33</td>\n    </tr>\n    <tr>\n      <th>initial_exp_fishing_2</th>\n      <th>probability</th>\n      <td>0.34</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nsimulate = rp.get_simulate_func(params_initial_exp, options_basic)\ndf_exp = simulate(params_initial_exp)\n```\n\nWe can the plot the choice frequencies for both scenarios to compare Robinson's actions.\n\n\n```python\nplot_choice_prob_and_exp_level(df_basic)\n```\n\nComparing the plots shows that the share of engagement in fishing increases compared to the baseline scenario, as two thirds of Robinsons land on the island with previous experience in fishing. \n\n\n```python\nplot_choice_prob_and_exp_level(df_exp)\n```\n\n<div class=\"alert alert-block alert-info\">\n    <u><h3>2.4.4. Extension: Observables</h3></u>\n</div>\n\nNext add one observable characteristic to the baseline model, `\"Fishing_Grounds\"`: Now Robinson can end up, with a certain probability, on the side of the island which has `\"poor\"` or `\"rich\"` fishing grounds. Experiencing rich fishing grounds affects the **non-pecuniary reward** for fishing. \n\nTo specify the observable, we add three additional rows to `params`:\n\n- The probability with which Robinson will find himself in rich and in poor fishing grounds;\n\n- The return for being in a rich fishing ground, which here is set to be positive and constant.\n\n`respy` allows for complex probability distributions of observables, which may for instance depend on other covariates. However, we will assume that the observable's probability distribution does not depend on any other information. We assume that each Robinson is randomly assigned to a certain side of the island, according to the float specified under value in the name-level probability.\n\nNote that all probabilities sum to one. If that is not the case, **respy** will emit a warning and normalize probabilities.\n\n\n```python\nparams_fish_ground = params_basic.copy()\nparams_fish_ground.loc[\n    (\"observable_fishing_grounds_rich\", \"probability\"), \"value\"\n] = 0.5\nparams_fish_ground.loc[\n    (\"observable_fishing_grounds_poor\", \"probability\"), \"value\"\n] = 0.5\nparams_fish_ground.loc[\n    (\"nonpec_fishing\", \"rich_fishing_grounds\"), \"value\"\n] = 0.5\nparams_fish_ground\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>value</th>\n    </tr>\n    <tr>\n      <th>category</th>\n      <th>name</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>delta</th>\n      <th>delta</th>\n      <td>0.95</td>\n    </tr>\n    <tr>\n      <th>wage_fishing</th>\n      <th>exp_fishing</th>\n      <td>0.10</td>\n    </tr>\n    <tr>\n      <th>nonpec_fishing</th>\n      <th>constant</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">nonpec_hammock</th>\n      <th>constant</th>\n      <td>2.50</td>\n    </tr>\n    <tr>\n      <th>not_fishing_last_period</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">shocks_sdcorr</th>\n      <th>sd_fishing</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>sd_hammock</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>corr_hammock_fishing</th>\n      <td>-0.20</td>\n    </tr>\n    <tr>\n      <th>lagged_choice_1_hammock</th>\n      <th>constant</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>observable_fishing_grounds_rich</th>\n      <th>probability</th>\n      <td>0.50</td>\n    </tr>\n    <tr>\n      <th>observable_fishing_grounds_poor</th>\n      <th>probability</th>\n      <td>0.50</td>\n    </tr>\n    <tr>\n      <th>nonpec_fishing</th>\n      <th>rich_fishing_grounds</th>\n      <td>0.50</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nWe also need to overwrite the covariates section of `options` to include which level of the observable is associated with a higher nonpecuniary reward for fishing:\n\n\n```python\noptions_fish_ground = options_basic.copy()\noptions_fish_ground[\"covariates\"] = {\n    \"constant\": \"1\",\n    \"not_fishing_last_period\": \"lagged_choice_1 != 'fishing'\",\n    \"rich_fishing_grounds\": \"fishing_grounds == 'rich'\",\n}\noptions_fish_ground\n```\n\n\n\n\n    {'n_periods': 10,\n     'simulation_agents': 1000,\n     'simulation_seed': 123,\n     'covariates': {'constant': '1',\n      'not_fishing_last_period': \"lagged_choice_1 != 'fishing'\",\n      'rich_fishing_grounds': \"fishing_grounds == 'rich'\"}}\n\n\n\n\n```python\nsimulate = rp.get_simulate_func(params_fish_ground, options_fish_ground)\ndf_fish_ground = simulate(params_fish_ground)\n```\n\nAs can be expected, Robinson engages in fishing more often if he is stranded on the side of the island with rich fishing grounds.\n\n\n```python\nplot_fishing_grounds(df_fish_ground)\n```\n\n<div class=\"alert alert-block alert-info\">\n    <u><h2>3. Example Models in respy</h2></u>\n</div>\n\nThe story of Robinson is an illustrative introductory example to `respy`'s modeling capabilities. What may not be evident at first sight, is that it in this context is a story of human capital accumulation which constitutes a central topic in economic research. `respy` is designed to be used for much larger and more complex models that are capable of addressing real world policy questions and are calibrated to empirical data. To illustrate the scalability of `respy` models, the interface includes a number of example models that are taken from actual economic publications.\n\nThey can be accessed as ```params, options, data = rp.get_example_model(<model>)```\n\nBelow are the example models that are currently available. \n\n### Toy models\n\nThe package provides users with two toy models. These models can be used to acquaintance oneself with **respy**'s functionalities and can be encountered in the [tutorials](https://respy.readthedocs.io/en/latest/tutorials/index.html) in the documentation. The models are called:\n\n- `robinson_crusoe_basic`\n- `robinson_crusoe_extended`\n\nWe have gotten to know the toy models in this tutorial: we started off with a version of the most basic model in which has Robinson either fishing or relaxing in the hammock and, amongst other things, extended the model to `robinson_crusoe_extended` where he can additionally talk to Friday to improve his fishing.\n\nThese models are excellent examples to use for learning and prototyping because they are very computationally feasible due to the small number of available choices and low number of periods in the models.\n\n#### Basic Robinson Model\n\n\n```python\n_, _, data = rp.get_example_model(\"robinson_crusoe_basic\")\n```\n\n\n```python\nplot_choice_shares(data)\n```\n\n#### Extended Robinson Model\n\n\n```python\n_, _, data = rp.get_example_model(\"robinson_crusoe_extended\")\n```\n\n\n```python\nplot_choice_shares(data, friday=True)\n```\n\n### Keane and Wolpin (1994)\n\nAside from toy models, **respy** also provides several models that stem from the economic literature on dynamic life-cycle models. The most simple examples are a group of models based on the following publication:\n\n- Keane, M. P., & Wolpin, K. I. (1994). The Solution and Estimation of Discrete Choice Dynamic Programming Models by Simulation and Interpolation: Monte Carlo Evidence. *The Review of Economics and Statistics*, 648-672.\n\nThe study is mainly concerned with the computational difficulties that accompany the solution of discrete choice dynamic programming (DCDP) problems such as the ones encountered in dynamic life-cycle models of educational and occupational choice. In the study, Keane and Wolpin (1994) develop an approximate solution method which consists of Monte Carlo integration with simulation and an interpolation approach to ease the computational burden of solving the DCDP model. They utilize one model with three different parametrizations to assess their solution method. This model and its three parametrizations are example models that are part of the **respy** interface. They are called:\n\n- `kw_94_one`\n- `kw_94_two`\n- `kw_94_three`\n\nThe model consists of four mutually exclusive alternatives that individuals can choose in each period. Agents can either choose to work in one of two sectors `a` or `b`, invest in education, or stay home. The work alternatives award a wage and experience, while school only awards experience. In the home option, individuals gain neither a wage nor experience. The plot below shows the choice patterns for the three parametrizations. The model considers a time horizon of 40 periods.\n\n\n```python\nplot_choices_kw(example=\"1994\")\n```\n\n### Keane and Wolpin (1997)\n\nA more advanced group of examples are given by the models developed by Keane and Wolpin (1997). In this study, the authors implement an empirical structural life-cycle model of occupational choice and human capital investment. They estimate their models on data from the National Longitudinal Survey of Youth (NLSY).\n\n* Keane, M. P., & Wolpin, K. I. (1997). The Career Decisions of Young Men. *Journal of Political Economy*, 105(3), 473-522.\n\n**respy** supports both the basic and extended model from the paper. They are named:\n\n- `kw_97_basic`\n- `kw_97_extended`\n\nHowever, the parametrization from the paper returns different life-cycle patterns for **respy** than presented in the paper. You can thus also access our estimates based for the models that are based on the same empirical data by adding `_respy` to the model name. \n\n\nThe modelsnumber consists of three occupational choices (*white collar*, *blue collar*, and *military*), one educational choice (*school*), and a *home* option. Both models consider a life-cycle of 50 periods. These models are decidedly larger than the toy models explored in this tutorial and require a considerable amount of computation power to solve, especially the extended model. The estimated life-cycle patterns are shown below.\n\n\n\n```python\nplot_choices_kw(example=\"1997\")\n```\n\n#### How do the models compare to empirical data?\n\nBelow are the model predictions plotted against the observed choices. These plots correspond to Figure 1-5 (p.492-494) in the paper.  \n\n\n```python\nplot_kw_97_comparison()\n```\n\n### Keane and Wolpin (2000)\n\nAnother example model provided in the respy interface is the model presented in Keane and Wolpin (2000). The model incorporates an observable charactistic to account for race aiming to analyze the effects of monetary incentive schemes designed to reduce racial differences in school attainment and earnings.\n\n- Keane, M. P., & Wolpin, K. I. (2000). Eliminating Race Differences in School Attainment and Labor Market Success. *Journal of Labor Economics*, 18(4), 614-652.\n\nThe model is named \n\n- `kw_2000`\n\nThe model is very similar to the extended model specification in Keane and Wolpin (1997).\n\n<div class=\"alert alert-block alert-info\">\n    <u><h2>4. Further and upcoming functionalities in respy and other OpenSourceEconomics packages</h2></u>\n</div>\n\nAs `respy` is an open source project multiple teams work on extensions of the existing flexibility. The next major advancements are:\n\n- Exogenous processes (childbirth, health shocks etc.)\n\n- Consumption and saving decision.\n \nA very recent and big step for `respy` was the introduction of state specific choice sets. As documentation is still in development, there are not tutorials yet for every aspect. The current documentation can be found [here](https://respy.readthedocs.io/en/latest/).\n\nBesides simulation of economic models, `respy` of course offers the possibility to estimate your model on data. Furthermore you have the option to fix certain parameters and only estimate others. For the estimation, the following techniques are available:\n\n- Maximum likelihood estimation (ML)\n- Method of simulated moments (MSM)\n\nFor both techniques you can find details in our [ekw-lectures](https://github.com/OpenSourceEconomics/ekw-lectures/tree/master/lectures).\n\nNote that `respy`, does not have any optimizers implemented. For a set of given parameters `respy` creates the corresponding criterion function value. It is best optimized by the OpenSourceEconomics estimation package `estimagic`. Further examples of OSE software packages designed to interact with each other are:\n\n- [`ruspy`](https://ruspy.readthedocs.io/en/latest/) is an open-source Python package for the simulation and estimation of a prototypical infinite-horizon dynamic discrete choice model based on Rust (1987).\n\n- [`grmpy`](https://grmpy.readthedocs.io/en/latest/) is an open-source Python package for the simulation and estimation of the generalized Roy model.\n\n- [`econsa`](https://econsa.readthedocs.io/en/latest/) is an open-source Python package that facilitates uncertainty propagation and global sensitivity of computational economic models.analysis.\n\n- [`robupy`](https://robupy.readthedocs.io/en/latest/) is an open-source Python package for robust decision making.\n\n- [`gettsim`](https://gettsim.readthedocs.io/en/stable/) is an open-source Python package developed by OSE members providing a depiction of the German Taxes and Transfers System.\n \n\nCheck out the OpenSourceEconomics homepage for more information on all packages https://open-econ.org.\n", "meta": {"hexsha": "32743538e453fd9cc4b4cd7b3d3ef4d7cac23aaa", "size": 398114, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "respy-showcase-short.ipynb", "max_stars_repo_name": "amageh/respy-tut", "max_stars_repo_head_hexsha": "115a8a3cf0069b03ee18c6eac70b0b9b1cba6857", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "respy-showcase-short.ipynb", "max_issues_repo_name": "amageh/respy-tut", "max_issues_repo_head_hexsha": "115a8a3cf0069b03ee18c6eac70b0b9b1cba6857", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "respy-showcase-short.ipynb", "max_forks_repo_name": "amageh/respy-tut", "max_forks_repo_head_hexsha": "115a8a3cf0069b03ee18c6eac70b0b9b1cba6857", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 173.0178183399, "max_line_length": 86296, "alphanum_fraction": 0.8721120081, "converted": true, "num_tokens": 11405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.08269734154465924, "lm_q1q2_score": 0.039734309343454136}}
{"text": "# Equation Blocks \n\n\n```python\nimport re\nimport sys\nimport json\nimport numpy as np\nfrom operator import itemgetter\nfrom itertools import chain\n#############################################\n# Settings\n#############################################\n```\n\n\n```python\nnb_infile = \"book/content/chapter3.ipynb\"\nnb_outfile = \"book/content/chapter3_new.ipynb\"\nbib_filename = None\n```\n\n\n```python\n# Load Jupyter Notebook as Dictionary\ntry:\n    with open(nb_infile,'r') as fp:\n        nb = json.load(fp)\n    fp.close()\n    print(\"Input Jupyter Notebook read successfully\")\nexcept:\n    print(\"Couldn't find Jupyter Notebook. Check your input path\")\n```\n\n    Input Jupyter Notebook read successfully\n\n\n\n```python\ndef split_cell_content(cell_content, latex_markers_positions):\n    first_idx = latex_markers_positions[0]\n    last_idx = latex_markers_positions[-1]\n    latex_markers_positions = [0] + latex_markers_positions + [-1]\n    \n    eqs_begin_indices = latex_markers_positions[1:-1:2]\n    eqs_end_indices = list(np.array( latex_markers_positions[2::2] ) + 1)\n    eqs_idx_pairs = list(zip(eqs_begin_indices, eqs_end_indices))\n    \n    text_begin_indices = list(np.array( latex_markers_positions[2::2] ) + 1)\n    text_end_indices = list(np.array( latex_markers_positions[3:-1:2] ) + 0)\n    text_idx_pairs = [(0,first_idx)] + list(zip(text_begin_indices, text_end_indices)) + [(last_idx+1, -1)]\n    \n    all_idx_pairs = [(x, 'txt') for x in text_idx_pairs] + [(x, 'eq') for x in eqs_idx_pairs]\n    all_idx_pairs.sort(key = lambda x: x[0][0])\n\n    cell_content_split = [cell_content[idx_pair[0][0]: idx_pair[0][1]] for idx_pair in all_idx_pairs]\n    cell_content_type = [idx_pair[1] for idx_pair in all_idx_pairs]\n    \n    return cell_content_split, cell_content_type\n```\n\n\n```python\ndef insert_math_env(cell_content_split, cell_content_type):\n    cell_content_new = []\n    N = len(cell_content_split)\n    for i in range(N):\n        content_chunk = cell_content_split[i]\n        content_type = cell_content_type[i]\n        if content_type == \"eq\":\n            # Define label name as empty character by default\n            label_name = \"\"\n            for line in content_chunk:\n                # Find all LaTeX equation labels\n                item_matched = re.findall(latex_eqlabel_pattern, line)\n                if len(item_matched) > 0:\n                    # Extract label name\n                    try:\n                        # if label name accompanied by LaTeX label marker\n                        label_type, label_name = item_matched[0].strip().split(\":\")\n                    except:\n                        # or without\n                        label_name = item_matched[0].strip()\n                        \n            # Wrap equation block up, MyST syntax\n            upper = [\"```{math}\\n\", \"---\\n\", \"label: \"+label_name+\"\\n\", \"---\\n\"]\n            body  =  content_chunk\n            lower = [\"```\\n\"]\n            content_chunk =  list(chain.from_iterable([upper, body, lower])) \n            cell_content_new.append(content_chunk)\n        else:\n            cell_content_new.append(content_chunk)\n\n    return list(chain.from_iterable(cell_content_new))\n```\n\n\n```python\nmarkdown_env_equation = [\"```{math}\", \"```\"] # MyST Markdown Equation environment markers\nmarkdown_eqlabel = [\"---\", \"label: \", \"---\"] # MyST Markdown equation label format\n\nlatex_eqlabel_pattern = re.compile(r'\\\\label\\{(.+?)\\}') # LaTeX equation label pattern\nlatex_env_equation = [r\"\\\\begin{equation}\", r\"\\\\end{equation}\"] #LaTeX equation environment markers\nlatex_env_eqnarray = [r\"\\\\begin{eqnarray}\", r\"\\\\end{eqnarray}\"] #LaTeX eqnarray environment markers\n```\n\n\n```python\nPATTERNS = latex_env_equation + latex_env_eqnarray\n\nfor i in range(len(nb['cells'])):\n    cell = nb['cells'][i]\n    latex_markers_positions = []\n    cell_content = cell['source']\n    \n    for j in range(len(cell['source'])):\n        item = cell['source'][j]\n\n        for string in PATTERNS:\n            item_matched = re.findall(string, item)\n            if len(item_matched) > 0:\n                latex_markers_positions.append(j)\n    if len(latex_markers_positions) > 0:\n        cell_content_split, cell_content_type = split_cell_content(cell_content, latex_markers_positions)\n        cell_content_modified = insert_math_env(cell_content_split, cell_content_type)\n        nb['cells'][i]['source'] = cell_content_modified\n```\n\n    Xt\n    Ito\n    deterministic_system\n    noisy_saddle\n    noisy_saddle_solutions\n    noisy_saddle_RDS\n    invariance\n    invariance_x\n    invariance_y\n    stationary_orbit\n    general_noisy_saddle_solutions\n    x_increments\n    y_increments\n    higher_order_x\n    higher_order_y\n\n\n\n```python\nwith open(nb_outfile,'w') as fp:\n    json.dump(nb, fp)\nfp.close()\n```\n\n# Equation referencing\n\n\n```python\n%%writefile scripts/citations_latex2myst.py\ndef replace_citation_syntax(references_matched_raw, item):\n    \"\"\"Replace native LaTeX syntax for inline citations in a cell item (paragraph) with MyST Markdown\"\"\"\n    item_modified = item\n    for match in references_matched_raw:\n        ref_tags_raw = re.split(\",\", match)\n        ref_tags_clean = [x.strip() for x in ref_tags_raw]\n        \n        # Replace LaTeX syntax with new one in cell items\n        new_syntax_items = [\"{eq}`\"]+[\",\".join(ref_tags_clean)]+[\"`\"]\n        separator = ''\n        chunk_new = separator.join(new_syntax_items)\n        chunk_original = '\\eqref{'+match+'}'\n        item_modified = item_modified.replace(chunk_original, chunk_new)\n    return item_modified\n\ndef latex_to_new_syntax_bib(nb):\n    for i in range(len(nb['cells'])):\n        cell = nb['cells'][i]\n        for j in range(len(cell['source'])):\n            item = cell['source'][j]\n            references_matched_raw = re.findall(reference_pattern,item)\n            if references_matched_raw:\n                item_modified = replace_citation_syntax(references_matched_raw, item)\n                nb['cells'][i]['source'][j] = item_modified\n    return nb\n\nif __name__ == \"__main__\":\n    import re\n    import sys\n    import json\n    \n    # Script inputs\n    nb_infile = sys.argv[1]  # Input NoteBook (.ipynb)\n    nb_outfile = sys.argv[2] # Output Notebook (.ipynb)\n    \n    # Matching patterns of native LaTeX syntax for replacement\n    reference_pattern = re.compile(r'\\\\eqref\\{(.+?)\\}')\n    \n    # Load Jupyter Notebook via JSON\n    try:\n        with open(nb_infile,'r') as fp:\n            nb = json.load(fp)\n        fp.close()\n    except:\n        error_mssg = \"Couldn't find Jupyter Notebook. Check your input path.\"\n        print(error_mssg)\n        sys.exit()\n    \n    # Modify syntax in all cells of input NoteBook\n    nb_modified = latex_to_new_syntax_bib(nb)\n    \n    # Save modified Notebook\n    with open(nb_outfile,'w') as fp:\n        json.dump(nb_modified, fp)\n    fp.close()\n    output_mssg = \"New Notebook successfully generated\"\n    print(output_mssg)\n```\n\n\n```python\n\n```\n\n# Inline Citations and Bibliography Syntax\n\n\n```python\n%%writefile scripts/citations_latex2myst.py\ndef replace_citation_syntax(citations_matched_raw, item):\n    \"\"\"Replace native LaTeX syntax for inline citations in a cell item (paragraph) with MyST Markdown\"\"\"\n    item_modified = item\n    for match in citations_matched_raw:\n        bib_tags_raw = re.split(\",\", match)\n        bib_tags_clean = [x.strip() for x in bib_tags_raw]\n        \n        # Replace LaTeX syntax with new one in cell items\n        new_syntax_items = [\"{cite}`\"]+[\",\".join(bib_tags_clean)]+[\"`\"]\n        separator = ''\n        chunk_new = separator.join(new_syntax_items)\n        chunk_original = '\\cite{'+match+'}'\n        item_modified = item_modified.replace(chunk_original, chunk_new)\n    return item_modified\n\ndef replace_bibliography_syntax(bibliography_matched_raw, item):\n    # Only one single bibliography line exists\n    bib_filename = bibliography_matched_raw[0].strip()\n    separator = ''\n    new_syntax_items = [\"```{bibliography} \"]+[bib_filename+\"\\n\"]+[\"```\\n\"]\n    chunk_new = separator.join(new_syntax_items)\n    chunk_original = r'\\bibliography{'+bibliography_matched_raw[0]+'}'\n    item_modified = item.replace(chunk_original, chunk_new)\n    return item_modified\n\ndef latex_to_new_syntax_bib(nb):\n    for i in range(len(nb['cells'])):\n        cell = nb['cells'][i]\n        for j in range(len(cell['source'])):\n            item = cell['source'][j]\n\n            citations_matched_raw = re.findall(citations_pattern,item)\n            bibliography_matched_raw = re.findall(bibliography_pattern,item)\n\n            if citations_matched_raw:\n                item_modified = replace_citation_syntax(citations_matched_raw, item)\n                nb['cells'][i]['source'][j] = item_modified\n\n            elif bibliography_matched_raw:\n                item_modified = replace_bibliography_syntax(bibliography_matched_raw, item)\n                nb['cells'][i]['source'][j] = item_modified\n    return nb\n\nif __name__ == \"__main__\":\n    import re\n    import sys\n    import json\n    \n    # Script inputs\n    nb_infile = sys.argv[1]  # Input NoteBook (.ipynb)\n    nb_outfile = sys.argv[2] # Output Notebook (.ipynb)\n    bib_filename = sys.argv[3] # BibTeX file name (.bib)\n    \n    # Matching patterns of native LaTeX syntax for replacement\n    citations_pattern = re.compile(r'\\\\cite\\{(.+?)\\}')\n    bibliography_pattern = re.compile(r'\\\\bibliography\\{(.+?)\\}')\n    \n    # Load Jupyter Notebook via JSON\n    try:\n        with open(nb_infile,'r') as fp:\n            nb = json.load(fp)\n        fp.close()\n    except:\n        error_mssg = \"Couldn't find Jupyter Notebook. Check your input path.\"\n        print(error_mssg)\n        sys.exit()\n    \n    # Modify syntax in all cells of input NoteBook\n    nb_modified = latex_to_new_syntax_bib(nb)\n    \n    # Save modified Notebook\n    with open(nb_outfile,'w') as fp:\n        json.dump(nb_modified, fp)\n    fp.close()\n    output_mssg = \"New Notebook successfully generated\"\n    print(output_mssg)\n```\n", "meta": {"hexsha": "45eeee46a6c6ac392205342ac0c3d13b7909cba9", "size": 15501, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "scripts/.ipynb_checkpoints/ScratchNotes-checkpoint.ipynb", "max_stars_repo_name": "champsproject/lagrangian_descriptors", "max_stars_repo_head_hexsha": "b3a88a2243bd5b0dce7cc945f9504bfadc9a4b19", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2020-07-24T17:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-12T17:31:53.000Z", "max_issues_repo_path": "scripts/ScratchNotes.ipynb", "max_issues_repo_name": "champsproject/lagrangian_descriptors", "max_issues_repo_head_hexsha": "b3a88a2243bd5b0dce7cc945f9504bfadc9a4b19", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-05-26T17:28:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-27T10:40:54.000Z", "max_forks_repo_path": "scripts/ScratchNotes.ipynb", "max_forks_repo_name": "champsproject/lagrangian_descriptors", "max_forks_repo_head_hexsha": "b3a88a2243bd5b0dce7cc945f9504bfadc9a4b19", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4466666667, "max_line_length": 119, "alphanum_fraction": 0.5326107993, "converted": true, "num_tokens": 2379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834914771176, "lm_q2_score": 0.08389039270915707, "lm_q1q2_score": 0.0396536037271509}}
{"text": "# Labbrapport: laboration 2 - reaktionskinetik f\u00f6r ett koboltkomplex\n\n**Utf\u00f6rd av:** L., H.   \n**Datum:** 2013-01-11  \n**Handledare:** Taha Ahmed\n\n## Syfte\n\nSyftet med laborationen \u00e4r att ...\n\n## Teori\n\n$\\left[\\mathrm{Co\\left(NH_3\\right)_5H_2O}\\right]^{3+} \\;\\xrightarrow[-\\mathrm{H_2O}]{+\\mathrm{NO_2^-}}\\; \\left[\\mathrm{Co\\left(NH_3\\right)_5NO_2}\\right]^{2+} \\rightarrow \\left[\\mathrm{Co\\left(NH_3\\right)_5ONO}\\right]^{2+}$ (mekanism 1)\n\n$\\left[\\mathrm{Co\\left(NH_3\\right)_5H_2O}\\right]^{3+} \\;\\xrightarrow[-\\mathrm{H_2O}]{+\\mathrm{NO_2^-}}\\; \\left[\\mathrm{Co\\left(NH_3\\right)_5ONO}\\right]^{2+} \\rightarrow \\left[\\mathrm{Co\\left(NH_3\\right)_5NO_2}\\right]^{2+}$ (mekanism 2)\n\nVi f\u00f6ljer ligandutbytet spektrofotometriskt\n\n### Reaktionsmekanism f\u00f6r ligandutbytet\n\n$$r = -\\frac{d\\left[\\left[\\mathrm{Co(NH_3)_5H_2O}\\right]^{3+}\\right]}{dt} = k_1 \\left[\\left[\\mathrm{Co(NH_3)_5H_2O}\\right]^{3+}\\right] \\left[\\mathrm{HNO_2}\\right] \\left[\\mathrm{NO_2^-}\\right]$$\n\n$$r = -\\frac{d\\left[\\left[\\mathrm{Co(NH_3)_5H_2O}\\right]^{3+}\\right]}{dt} = k_1^\\prime \\left[\\left[\\mathrm{Co(NH_3)_5H_2O}\\right]^{3+}\\right]$$\n\nD\u00e4r $k_1^\\prime = k_1 \\left[\\mathrm{HNO_2}\\right] \\left[\\mathrm{NO_2^-}\\right]$.  \nJ\u00e4mvikt inst\u00e4ller sig mellan de tv\u00e5 isomererna. Den observerade hastighetskonstanten \u00e4r av f\u00f6rsta ordningen, $k_2 = k_+ + k_-$.\n\n$$r = -\\frac{d\\left[\\left[\\mathrm{Co(NH_3)_5H_2O}\\right]^{3+}\\right]}{dt} = k_2 \\left(\\left[\\left[\\mathrm{Co(NH_3)_5H_2O}\\right]^{3+}\\right] - \\left[\\left[\\mathrm{Co(NH_3)_5H_2O}\\right]^{3+}\\right]_\\mathrm{eq}\\right)$$\n\n### Beskrivning av den kinetiska modellen\n\n\\begin{equation}\nR \\;\\;\\xrightarrow[]{k_1^\\prime}\\;\\; I \\;\\;\\xrightarrow[]{k_2}\\;\\; P\n\\end{equation}\n\n\\begin{equation}\\tag{4}\n[R]_t = [R]_0 \\exp(-k_1^\\prime t)\n\\end{equation}\n\n\\begin{equation}\\tag{5}\n[I]_t = \\frac{k_1^\\prime [R]_0}{k_2 - k_1^\\prime} \\left(\\exp(-k_1^\\prime t) - \\exp(-k_2 t)\\right)\n\\end{equation}\n\n\\begin{equation}\\tag{6}\n[P]_t = [R]_0 - [R]_t - [I]_t\n\\end{equation}\n\n\\begin{equation}\\tag{7}\n\\mathrm{Abs}_\\mathrm{l\u00f6sning} = {\\mathrm{Abs_R}} + {\\mathrm{Abs_I}} + {\\mathrm{Abs_P}} = l\\left([R\\:]\\varepsilon_\\mathrm{R} + [I\\:]\\varepsilon_\\mathrm{I} + [P\\:]\\varepsilon_\\mathrm{P}\\right)\n\\end{equation}\n\n\\begin{equation}\\tag{8}\n\\mathrm{Abs}_t = l[R\\:]_0\\left(\\varepsilon_P + \\left(\\varepsilon_R + \\frac{\\varepsilon_I k_1^\\prime - \\varepsilon_P k_2}{k_2 - k_1^\\prime} \\right)\\exp(-k_1^\\prime t) + \\frac{k_1^\\prime(\\varepsilon_P - \\varepsilon_I)}{k_2 - k_1^\\prime}\\exp(-k_2 t)\\right)\n\\end{equation}\n\n\\begin{equation}\\tag{9}\n\\mathrm{Abs}_t = \\mathrm{Abs} _\\infty + \\Delta\\mathrm{Abs}_1\\exp(-k_1^\\prime t) + \\Delta\\mathrm{Abs}_2\\exp(-k_2 t)\n\\end{equation}\n\n\\begin{equation}\\tag{10}\n\\mathrm{Abs}_t = \\mathrm{Abs} _\\infty + \\Delta\\mathrm{Abs}_1\\exp(-t/\\tau_1) + \\Delta\\mathrm{Abs}_2\\exp(-t/\\tau_2), \\quad\\quad k_1^\\prime = \\left(\\tau_1\\right)^{-1}, \\quad k_2 = \\left(\\tau_2\\right)^{-1}\n\\end{equation}\n\n## Svar till f\u00f6rstuderingsfr\u00e5gor\n\n### Del 1\n\n1. Best\u00e4m v\u00e5gl\u00e4ngden vid absorptionsmaxima f\u00f6r de tre koboltkomplexen (aqua, nitro, nitrito).\n    Vilken f\u00e4rg har ljus med motsvarande v\u00e5gl\u00e4ngd?\n    Vilken f\u00e4rg har l\u00f6sningar som absorberar vid respektive v\u00e5gl\u00e4ngd?\n\n2. Skissa absorbansen, `Abs`,  vid 510 nm mot tiden, `t`, f\u00f6r de tv\u00e5 f\u00f6reslagna reaktionsmekanismerna.\n\n3. Vilken eller vilka av f\u00f6ljande v\u00e5gl\u00e4ngder kan anv\u00e4ndas f\u00f6r att urskilja mellan de tv\u00e5 f\u00f6reslagna reaktionsmekanismerna?\n    - 415 nm, \n    - 450 nm, \n    - 482 nm, \n    - 495 nm, \n    - 510 nm.\n\n4. Antag att mekanism 1 \u00e4r korrekt. Vilken eller vilka av de ovanst\u00e5ende v\u00e5gl\u00e4ngderna skulle vara bra f\u00f6r att anv\u00e4nda f\u00f6r att best\u00e4mma hastighetskonstanten f\u00f6r\n    - reaktion 1?\n    - reaktion 2?\n    - reaktion 1 och reaktion 2?\n\n5. G\u00e5r det att anv\u00e4nda resonemanget fr\u00e5n fr\u00e5ga 4 (ovan) om vi ist\u00e4llet antar att mekanism 2 \u00e4r korrekt? Vilka skillnader kan f\u00f6rutses?\n\n### Del 2\n\n6. Vilka \u00e4r de \u00f6nskv\u00e4rda reaktionsf\u00f6rh\u00e5llandena f\u00f6r att ligandutbytesreaktionen ska bli en pseudo-f\u00f6rsta ordningens reaktion?\n\n7. N\u00e4mn tv\u00e5 parametrar som \u00e4r viktiga att kontrollera under ett kinetikexperiment.\n\n## Utf\u00f6rande\n\n### Utrustning och kemikalier\n\nSpektrofotometer (fabrikat, modell), termostat (fabrikat, modell), pH-meter, etc.  \nCo-l\u00f6sningar (koncentrationer, och dylikt).\n\n### Beredning av reaktionsl\u00f6sningar\n\n1. **Tillredde reaktionsl\u00f6sningar**   \n    L\u00f6sning av $\\mathrm{Co}$-komplex vatten.   \n    L\u00f6sning av $\\mathrm{NaNO_2}$ i vatten, med tillsats av stark syra.\n\n2. **Startade upp termostaten**\n\n3. **Tillverkade l\u00f6sning f\u00f6r m\u00e4tning av \"slutproduktens\" absorbans**\n\n4. **F\u00f6rv\u00e4rmde l\u00f6sningarna (temperatur?)**\n\n5. **Kalibrerade spektrofotometerns baslinje med avjonat vatten**\n\n6. **Kinetikstudier vid $510~\\mathrm{nm}$ och $45^{\\circ}\\mathrm{C}$**\n\n7. **Best\u00e4mde $[\\mathrm{HNO_2}]$ och $[\\mathrm{NO_2^-}]$**\n\n8. **M\u00e4tte absorbans f\u00f6r startmaterialet**\n\n9. **M\u00e4tte absorbans f\u00f6r \"slutprodukten\"**\n\n\n\n\n## Resultat\n\nVi b\u00f6rjar med att plotta den uppm\u00e4tta absorbanskurvan. F\u00f6r att kunna g\u00f6ra det beh\u00f6ver vi *importera* den funktion som vi vill anv\u00e4nda f\u00f6r plottning (vi anv\u00e4nder `matplotlib`). Detta g\u00e4ller f\u00f6r resten av dokumentet.\n\n\n```python\nimport matplotlib.pyplot as plt\n# \u00d6ka bredden p\u00e5 text-output till 140 kolumner\nnumpy.set_printoptions(linewidth = 140)\n# G\u00f6r plottar lite st\u00f6rre \u00e4n annars\nfigsize(14, 8.75)\n```\n\nNedan plottar vi v\u00e5r experimentellt uppm\u00e4tta absorbanskurva, Abs mot tid i sekunder.   \nDet \u00e4r tydligt att isomeriseringsreaktionen f\u00f6ljer reaktionsmekanism 2 (Abs \u00f6kar f\u00f6rst, sjunker sedan).\n\n\n```python\nfilnamn = \"data-Lindgren-Holm.csv\"\n# perhaps we could use scipy.loadtxt() instead? More pedagogical if it avoids the \"unpack\" parameter\n# from scipy import loadtxt\n# loadtxt(\"TEK0006.CSV\", delimiter=\",\", usecols=(0,1)) # load cols number 0 and 1\nx_data, y_data = numpy.loadtxt(filnamn, delimiter=\",\", unpack=True)\nplt.plot(x_data, y_data)\nplt.xlabel(\"Tid/sekunder\")\nplt.ylabel(\"Abs\")\nplt.title(filnamn)\nplt.yscale(\"linear\")\nplt.show()\n```\n\nH\u00e4r har vi vissa saker som f\u00f6rmodligen b\u00f6r l\u00f6sas:  \n\n1. Hur tar vi enklast bort outliers i data?\n\n## Analys av kinetikdata -- anpassning av kinetiksp\u00e5r\n\nVi importerar tv\u00e5 funktioner som vi kommer att anv\u00e4nda f\u00f6r kurvanpassningen (`curve_fit`) och f\u00f6r annan ber\u00e4kning (`chdtrc`).\n\n\n```python\n# fit with arbitrary function\n# fr\u00e5n modulen scipy.optimize importerar vi funktionen curve_fit, som optimiserar anpassningen baserat p\u00e5 non-linear least squares\nfrom scipy.optimize import curve_fit\n# n\u00e5got obskyr funktion, k\u00e4lla http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.chdtrc.html\nfrom scipy.special import chdtrc\n# uncertainties f\u00f6r att enklare utf\u00f6ra ber\u00e4kningar med os\u00e4kerheter\nfrom uncertainties import unumpy\n```\n\nDe fyra f\u00f6ljande rutorna med kod \u00e4r viktiga, och b\u00f6r skrivas f\u00f6r hand av studenten.\n\n\n```python\n# Definiera den kinetiska modellen\ndef kinetic_model(t, abs0, abs1, abs2, tau1, tau2):\n    return abs0 + abs1 * exp(-t/tau1) + abs2 * exp(-t/tau2)\n```\n\n\n```python\n# Namngivning i str\u00e4ngen p_names av rent kosmetiska sk\u00e4l (anv\u00e4nds senare...)\np_names = (\"abs0\", \"abs1\", \"abs2\", \"tau1\", \"tau2\")\n# Initialv\u00e4rden f\u00f6r parametrarna till v\u00e5r kinetiska modell (gissningar)\np_guess = (2.0E-1,  # abs0 = p_guess[0]\n          -5.0E-2,  # abs1 = p_guess[1]\n           2.0E-1,  # abs2 = p_guess[2]\n           250,     # tau1 = p_guess[3]\n           900)     # tau2 = p_guess[4]\n# Ber\u00e4kna absorbansv\u00e4rden baserat p\u00e5 initialv\u00e4rdena ovan (f\u00f6r senare j\u00e4mf\u00f6relse med anpassade parametrar)\ny_initial = kinetic_model(x_data, *p_guess)\n```\n\n\n```python\n# Anv\u00e4nd den kinetiska modellen f\u00f6r att anpassa parametrarna\n# popt: anpassade parametrar, pcov: deras kovariansmatris (statistik)\npopt, pcov = curve_fit(kinetic_model,\n                       x_data,\n                       y_data,\n                       p0 = p_guess,\n                       maxfev = int(1E2))\n# maxfev is the maximum number of iterations tried; you\n# can try increasing this value if the fit fails.\n```\n\n\n```python\n# Stoppa in de anpassade parametrarna i den kinetiska modellen och ber\u00e4kna anpassad absorbans-kurva\ny_fit = kinetic_model(x_data, *popt)\n# Ber\u00e4kna residualer (skillnad mellan experimentell absorbans och anpassad absorbans-kurva)\ny_residual = y_data - y_fit\n# Calculate degrees of freedom of fit\nDoF = len(x_data) - len(p_guess)\n# Calculate Chi-Squared\nchisq = sum((y_residual)**2)\n```\n\nResterande rutor med kod i denna sektion (\"Analys av kinetikdata\") kan med f\u00f6rdel kopieras och klistras in verbatim, ingen anledning att knappa in rad-f\u00f6r-rad.\n\n\n```python\nplot_exp, = plt.plot(x_data, y_data, \"k:\", linewidth = 2, label = \"Experimental\")\nplot_init, = plt.plot(x_data, y_initial, \"c-\", linewidth = 2, label = \"Initial fit\")\nplot_final, = plt.plot(x_data, y_fit, \"r--\", linewidth = 2, label = \"Optimized fit\")\n# Skapa en legend\nlegend(loc = 1, ncol = 1)\n# Skapa titel och ben\u00e4mning p\u00e5 axlarna\nplt.title(\"Comparing experimental data, initial fit, and optimized fit\")\nplt.xlabel(\"Time/seconds\")\nplt.ylabel(\"Abs\")\nplt.show()\n```\n\n\n```python\n# Show residual: difference between data and optimized fit\nplt.plot(x_data, y_residual, \"r-\")\nplt.title(\"Residual\")\n# Draw horizontal line at 0\nplt.axhline(y = 0)\n# Label axes\nplt.xlabel(\"Time/seconds\")\nplt.ylabel(\"Abs\")\nplt.show()\n```\n\n\n```python\nprint \"Antal datapunkter  =\", len(x_data)\nprint \"Antal parametrar   =\", len(p_guess)\nprint \"Degrees of freedom =\", DoF\n```\n\n    Antal datapunkter  = 1601\n    Antal parametrar   = 5\n    Degrees of freedom = 1596\n\n\n\n```python\nprint \"Kovariansmatris : \\n\", pcov, \"\\n\"\n```\n\n    Kovariansmatris : \n    [[  6.10020726e-09  -4.71160660e-08   4.24484128e-08   1.13179885e-04  -2.72915619e-04]\n     [ -4.71160660e-08   4.31034079e-07  -3.98674727e-07  -1.09888474e-03   2.34604279e-03]\n     [  4.24484128e-08  -3.98674727e-07   3.72520016e-07   1.04321100e-03  -2.15564451e-03]\n     [  1.13179885e-04  -1.09888474e-03   1.04321100e-03   3.04216653e+00  -5.87442427e+00]\n     [ -2.72915619e-04   2.34604279e-03  -2.15564451e-03  -5.87442427e+00   1.31057966e+01]] \n    \n\n\n\n```python\n# G\u00f6m undan i en funktion?\nprint \"Correlation Matrix :\"\nfor i,row in enumerate(pcov):\n    for j in range(len(popt)) :\n        print \"%10f\"%(pcov[i, j]/sqrt(pcov[i, i]*pcov[j, j])), # note: comma at end of print statement suppresses new line\n    print # required for proper formatting of matrix\n```\n\n    Correlation Matrix :\n      1.000000  -0.918842   0.890460   0.830817  -0.965216\n     -0.918842   1.000000  -0.994920  -0.959632   0.987071\n      0.890460  -0.994920   1.000000   0.979954  -0.975597\n      0.830817  -0.959632   0.979954   1.000000  -0.930341\n     -0.965216   0.987071  -0.975597  -0.930341   1.000000\n\n\n\n```python\nprint \"Estimated parameters with uncertainties (initial guess in parentheses)\"\npoptwerr = range(len(popt))\nfor i in range(len(popt)):\n    # Here (inside the for-loop) we should build up a unumpy array (arrary with uncertainty values) for each parameter\n    poptwerr[i] = unumpy.uarray([popt[i], pcov[i,i]**0.5*max(1, sqrt(chisq/DoF))])\n    print (\"  %s = %10.5f +/- %10.8f   (%9.5f)\" %(p_names[i], unumpy.nominal_values(poptwerr[i]), unumpy.std_devs(poptwerr[i]), p_guess[i]))\n```\n\n    Estimated parameters with uncertainties (initial guess in parentheses)\n      abs0 =    0.15877 +/- 0.00007810   (  0.20000)\n      abs1 =   -0.10565 +/- 0.00065653   ( -0.05000)\n      abs2 =    0.22035 +/- 0.00061034   (  0.20000)\n      tau1 =  408.55501 +/- 1.74418076   (250.00000)\n      tau2 = 1358.81341 +/- 3.62019289   (900.00000)\n\n\n\n```python\nprint \"Curve fit converged with:\"\nprint \"  ChiSq     = %1.5E\" %(chisq)\nprint \"  DoF       = %4g\" %(DoF)\nprint \"  ChiSq/DoF = %1.5E\" %(chisq/DoF)\nprint \"  CDF       = %4.2f%%\" %(100*chdtrc(DoF,chisq))\n```\n\n    Curve fit converged with:\n      ChiSq     = 1.29030E-04\n      DoF       = 1596\n      ChiSq/DoF = 8.08461E-08\n      CDF       = 100.00%\n\n\n**Next step:** calculate $k$ and $K$, preferably without losing uncertainties  \nPerhaps we should use the `uncertainties` package!\n\n\n```python\nk1prim = 1 / poptwerr[3]\nk2 = 1 / poptwerr[4]\nprint \"k1prim =\", k1prim, \"ENHET?\"\nprint \"k2 =\", k2, \"ENHET?\"\n```\n\n    k1prim = 0.00244765079648+/-1.04493772085e-05 ENHET?\n    k2 = 0.00073593621875+/-1.96070413922e-06 ENHET?\n\n\nTa 5 ml av $\\mathrm{HNO_2}/\\mathrm{NaNO_2}$-l\u00f6sningen och sp\u00e4d ut det med 5 ml avjonat vatten (s\u00e5 att koncentrationen blir samma som under kinetikm\u00e4tningen). M\u00e4t pH p\u00e5 l\u00f6sningen.  \nFr\u00e5n k\u00e4nd koncentration av $\\mathrm{NaNO_2}$, k\u00e4nt pH och $p\\mathrm{K_a}$-v\u00e4rde f\u00f6r $\\mathrm{HNO_2}$ (se SI-data) kan ni sedan r\u00e4kna ut $[\\mathrm{HNO_2}]$ och $[\\mathrm{NO_2^-}]$.  \nVi saknar v\u00e4rden f\u00f6r $[\\mathrm{NaNO_2}]$, $[\\mathrm{HNO_2}]$ och $[\\mathrm{NO_2^-}]$.\n\n\n```python\nconc_NaNO2 = 0.5 # mol/L\nconc_HNO2 = 0.0125 # mol/L\nconc_NO2m = 0.5 # mol/L\nk1 = k1prim / (conc_HNO2 * conc_NO2m)\nprint \"k1 =\", k1 # H\u00c4R BEH\u00d6VS KORREKTA V\u00c4RDEN\nprint \"k2 =\", k2\n```\n\n    k1 = 0.391624127437+/-0.00167190035336\n    k2 = 0.00073593621875+/-1.96070413922e-06\n\n\n\n```python\n# Conc Co is known (each lab group should calculate from weighed mass)\nconc_Co = 1 # H\u00c4R BEH\u00d6VS L\u00c4MPLIGT V\u00c4RDE\n# Abs / (conc * length)\n# Abs read from plot at 510 nm, conc in M, length in dm\nepsilon510_ONO = 0.35 / (6.7E-3 * 0.1)\nepsilon510_NO2 = 0.15 / (6.7E-3 * 0.1)\n```\n\n\\begin{equation}\nA_\\infty = \\varepsilon_\\mathrm{ONO^-} \\cdot [\\mathrm{ONO^-}] \\cdot l + \\varepsilon_\\mathrm{NO_2^-} \\cdot [\\mathrm{NO_2^-}] \\cdot l\n\\end{equation}\n\n\\begin{equation}\n[\\mathrm{Co^{3+}}] = [\\mathrm{ONO^-}] + [\\mathrm{NO_2^-}] \\quad\\Leftrightarrow\\quad [\\mathrm{ONO^-}] = [\\mathrm{Co^{3+}}] - [\\mathrm{NO_2^-}]\n\\end{equation}\n\n\\begin{equation}\n[\\mathrm{NO_2^-}] = \\frac{A_\\infty - \\varepsilon_\\mathrm{ONO^-} \\cdot [\\mathrm{Co^{3+}}] \\cdot l}{\\varepsilon_\\mathrm{NO_2^-} \\cdot l - \\varepsilon_\\mathrm{ONO^-} \\cdot l}\n\\end{equation}\n\n## Slutsats\n\nAnpassningen ...\n\n## Referenser\n\n1. http://dawes.wordpress.com/2011/01/02/scientific-python/\n2. http://packages.python.org/uncertainties/numpy_guide.html  \n3. http://web.uvic.ca/~jalexndr/192UncertRules.pdf  \n4. http://spiff.rit.edu/classes/phys273/uncert/uncert.html\n\n\n```python\n\n```\n", "meta": {"hexsha": "8886f2722932605c1561d696834cc73ece4626db", "size": 180931, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Co-complexes.ipynb", "max_stars_repo_name": "chepec/binder-jupyter", "max_stars_repo_head_hexsha": "b3e1bcc764a3bc645beffd33ebfdd9fba6803264", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Co-complexes.ipynb", "max_issues_repo_name": "chepec/binder-jupyter", "max_issues_repo_head_hexsha": "b3e1bcc764a3bc645beffd33ebfdd9fba6803264", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Co-complexes.ipynb", "max_forks_repo_name": "chepec/binder-jupyter", "max_forks_repo_head_hexsha": "b3e1bcc764a3bc645beffd33ebfdd9fba6803264", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 217.7268351384, "max_line_length": 71015, "alphanum_fraction": 0.9005808844, "converted": true, "num_tokens": 5253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276683008207139, "lm_q2_score": 0.1208532261576127, "lm_q1q2_score": 0.03959977126376641}}
{"text": "# Circuit\n\n\n```python\nfrom pytket.circuit.display import render_circuit_jupyter\n\nfrom lambeq import AtomicType, BobcatParser, IQPAnsatz\n\nN = AtomicType.NOUN\nS = AtomicType.SENTENCE\n```\n\n\n```python\nparser = BobcatParser()\ndiagram = parser.sentence2diagram('Alice runs')\ndiagram.draw()\n```\n\n\n```python\nansatz = IQPAnsatz({N: 1, S: 1}, n_layers=2)\ndiscopy_circuit = ansatz(diagram)\ndiscopy_circuit.draw(figsize=(10, 15))\n```\n\n\n```python\ntket_circuit = ansatz(diagram).to_tk()\n\n# This does not render properly on GitHub, please view it at:\n# https://cqcl.github.io/lambeq/examples/circuit.html\nrender_circuit_jupyter(tket_circuit)\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n\n<style>\nbody, .circuit__preview-body {\n    font-family: \"roboto\", system-ui, sans-serif;\n    --accent-col: green;\n    --accent-col-fill: darkseagreen;\n    --accent-col-alt: #aca;\n    --accent-col-emph: limegreen;\n    --accent-col-overlay: rgba(130,255,140,0.2);\n    --accent-col-outline: rgba(30, 250, 30,0.2);\n    --main-col: black;\n    --mid-col: #bbb;\n    --faint-col: #eee;\n    --faint-col-overlay: rgba(0, 0, 0, 0.05);\n    --main-bg: white;\n}\n\n.row{\n    display: flex;\n    flex-wrap: wrap;\n    align-items: center;\n    padding: 10px;\n    border-bottom: 1px solid var(--faint-col);\n    position: relative;\n}\n.row-item{\n    flex-grow: 1\n}\n.row-item-l{\n    text-align: left;\n}\n.row-item-r{\n    text-align: right;\n}\n.row-sub-heading{\n    border-color: var(--accent-col-emph);\n}\n\n/* FOR DISPLAYING CIRCUITS */\n/* Main preview container */\n.circuit-preview {\n    width: 100%;\n    height: 100%;\n    text-align: center;\n    color: black;\n}\n.circuit_variables {\n    /* Define some variables */\n    --box-height: 40px;\n    --wire-col: black;\n    --c-wire-col: #bbb;\n    --box-col: #ccc;\n    --box-col-overlay: rgba(0,0,0,0.05);\n    --c-box-col: #ddd;\n    --index-col: #888;\n}\n.circuit-preview.condensed{\n    display: flex;\n    flex-wrap: nowrap;\n}\n\n/* Box colours */\n.h {\n    --box-col: #ffee00;\n    --box-col-overlay: rgba(255, 255, 0, 0.2);\n    --c-box-col: #ffee88;\n    --index-col: #ffcc00;\n}\n.x {\n    --box-col: #ff8888;\n    --box-col-overlay: rgba(255, 0, 0, 0.2);\n    --c-box-col: #e8a6a6;\n    --index-col: red;\n}\n.y {\n    --box-col: #6699ff;\n    --box-col-overlay: rgba(0, 0, 255, 0.2);\n    --c-box-col: #86c6f6;\n    --index-col: blue;\n}\n.z {\n    --box-col: #ccffcc;\n    --box-col-overlay: rgba(0, 255, 0, 0.2);\n    --c-box-col: #e2ffe2;\n    --index-col: green;\n}\n\n.circuit-container{\n    max-width: 100%;\n    display: flex;\n    flex-flow: row wrap;\n    justify-content: center;\n    align-content: flex-start;\n    margin: auto;\n    width: -moz-fit-content;\n    width: fit-content;\n    background: rgba(255, 255, 255, 1);\n}\n.circuit-preview.condensed > .circuit-container{\n    flex-wrap: nowrap;\n    min-width: fit-content;\n}\n.circuit-container.nested{\n    position: relative;\n    flex-wrap: nowrap;\n    margin: -2px 0;\n}\n.nested-circuit-container{\n    display: flex;\n    overflow: auto;\n    max-width: 400px;\n    background: var(--box-col-overlay);\n    border: 1px solid var(--box-col);\n}\n.nested-circuit-container::-webkit-scrollbar {\n    height: 0;\n    width: 0;\n}\n.circuit-inner-scroll{\n    overflow: visible;\n    width: -moz-fit-content;\n    width: fit-content;\n    margin: auto;\n    margin-top: 2px;\n}\n.circuit-end{\n    width: 2px;\n    height: auto;\n    border: 2px solid var(--wire-col);\n    margin: calc(var(--box-height)/2) 0 calc(var(--box-height)/2 + 20px);\n}\n.circuit-layer{\n    min-width: 40px;\n    width: max-content;\n    display: flex;\n    flex-flow: column nowrap;\n    flex-grow: 1;\n    justify-content: space-between;\n    align-items: stretch;\n    margin-bottom: 20px;\n}\n.circuit-container:not(.nested) > .circuit-layer:nth-child(2),\n.circuit-container:not(.nested) > .circuit-layer:nth-last-child(2),\n.circuit-container.nested > .circuit-layer:nth-child(2),\n.circuit-container.nested > .circuit-layer:nth-last-child(2),\n.gate_container.nested > .circuit-layer:first-child,\n.gate_container.nested > .circuit-layer:last-child{\n    min-width: 10px;\n}\n.nested .circuit-layer{\n    margin-bottom: 0;\n}\n.flex_wire{\n    flex-grow: 1;\n}\n/* Display qubit names at start of circuit */\n.circuit-layer.qubits{\n    flex-grow: 0;\n    color: var(--wire-col);\n}\n.qubit{\n    height: calc(var(--box-height) - 20px);\n    padding: 10px;\n    text-align: center;\n    font-family: monospace;\n    box-sizing: content-box;\n}\n.wire{\n    height: 0;\n    border: 1px solid var(--wire-col);\n    background: var(--wire-col);\n    margin: calc(var(--box-height)/2) 0;\n}\n.wire.classical{\n    border-color: var(--c-wire-col) !important;\n    background: var(--c-wire-col) !important;\n}\n.wire.transparent-wire{\n    border-color: transparent;\n    background: transparent;\n}\n\n/* Generic base for our gates */\n.gate_container{\n    position: relative;\n    min-width: -moz-fit-content;\n    min-width: fit-content;\n}\n.gate_container.nested{\n    display: flex;\n    flex-wrap: nowrap;\n}\n.gate_container.nested:after{\n    display: flex;\n    flex-wrap: nowrap;\n}\n.gate_container .classical{\n    background: var(--c-box-col);\n    border-color: var(--index-col);\n}\n.gate{\n    position: relative;\n    height: calc(var(--box-height) - 16px);\n    margin: 0 9px;\n    padding: 9px 5px;\n    border: 1px solid var(--index-col);\n    border-bottom: none;\n    border-top: none;\n    text-align: left;\n    background: var(--box-col);\n    display: flex;\n    box-sizing: content-box;\n    z-index: 1;\n}\n.wire-label{\n    color: var(--index-col);\n    width: -moz-fit-content;\n    width: fit-content;\n    height: calc(var(--box-height) - 18px);\n    padding-right: 5px;\n}\n.gate_top > .wire-label,\n.gate_bottom > .wire-label {\n    padding-top: 0;\n}\n.nested-label-layer{\n    background: var(--box-col);\n    padding: 0 5px;\n}\n.nested-label-layer .wire-label{\n    padding: 10px 0;\n}\n\n/* Multi-qubit gates */\n.gate_bottom{\n    height: calc(var(--box-height) - 18px);\n    margin-bottom: 10px;\n    padding-bottom: 0;\n    border-bottom: 1px solid var(--index-col);\n}\n.gate_top{\n    height: calc(var(--box-height) - 18px);\n    margin-top: 10px;\n    padding-top: 0;\n    border-top: 1px solid var(--index-col);\n}\n.gate_name{\n    text-align: center;\n    flex-grow: 1;\n}\n/* Single qubit gate*/\n.gate_box{\n    height: calc(var(--box-height) - 20px);\n    margin: 10px;\n    padding: 0 5px;\n    border: 1px solid var(--index-col);\n    text-align: center;\n}\n\n/* Special gates */\n.gate_connection {\n    position: absolute;\n    top: -3px;\n    left: -1px;\n    border: none;\n    margin: calc(var(--box-height)/2) calc(50% - 5px);\n    padding: 0;\n}\n.gate_swap {\n    height: 20px;\n    width: 20px;\n    margin: calc(var(--box-height)/2 - 6px) calc(50% - 9px);\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%270%200%2064%2064%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27currentcolor%27%3E%0A%20%20%3Cpath%20d%3D%27M60%200%20L32%2028%20L4%200%20L0%204%20L28%2032%20L0%2060%20L4%2064%20L32%2036%20L60%2064%20L64%2060%20L36%2032%20L64%204%27%20/%3E%0A%3C/svg%3E\n) center;\n    background-size: cover;\n}\n.gate_measure {\n    height: 20px;\n    width: 25px;\n    margin: calc(var(--box-height)/2 - 10px) calc(50% - 11px);\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%27-10%20-10%2084%2084%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27white%27%0A%20%20stroke%3D%22black%22%0A%20%20stroke-width%3D%224px%22%0A%3E%0A%20%20%3Cpath%20d%3D%27M63%2C63%20C63%2C32%2048%2C16%2032%2C16%20C16%2C16%201%2C32%201%2C63%20L63%2C63%27%20/%3E%0A%20%20%3Cpath%20d%3D%22M32%2C63%20L56%2C16%22%20/%3E%0A%3C/svg%3E\n) center;\n    background-size: cover;\n}\n.gate_control {\n    position: absolute;\n    top: 0;\n    left: 0;\n    border-radius: 50%;\n    width: 6px;\n    height: 6px;\n    margin: calc(var(--box-height)/2 - 3px) calc(50% - 5px);\n    padding: 0;\n    border: 2px solid var(--wire-col);\n    background: var(--box-col);\n}\n.gate_control.classical{\n    background: var(--c-wire-col);\n    border-color: var(--c-wire-col);\n}\n.control_index{\n    position: absolute;\n    right: calc(50% - 1em);\n    top: calc(50% - 1.4em);\n    color: var(--c-wire-col);\n    font-size: 0.8em;\n}\n.control_index.measure{\n    right: calc(50% - 1.2em);\n    top: calc(50% - 1.8em);\n    color: var(--index-col);\n}\n.gate_x {\n    top: -10px;\n    left: -6px;\n    border-radius: 50%;\n    border: 1px solid var(--wire-col);\n    width: 20px;\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%270%200%2064%2064%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27currentcolor%27%3E%0A%20%20%3Cpath%20d%3D%27M36%2064%20L36%2036%20L64%2036%20L64%2028%20L36%2028%20L36%200%20L28%200%20L28%2028%20L0%2028%20L0%2036%20L28%2036%20L28%2064%27%20/%3E%0A%3C/svg%3E\n) center;\n    background-color: var(--box-col);\n    background-size: cover;\n}\n.gate_reset{\n    margin: 11px 10px;\n    padding: 0 0 0 10px;\n    border: none !important;\n    border-left: 2px solid var(--wire-col) !important;\n    background: transparent;\n}\n.gate_reset_spider{\n    width: calc(var(--box-height) - 24px);\n    height: calc(var(--box-height) - 24px);\n    background: var(--box-col);\n    border: 2px solid var(--wire-col);\n    border-radius: 50%;\n    font-size: 0.75em;\n}\n\n/* Add wire sections coming in and out of the gate */\n.gate_in:before, .gate_in:after{\n    content: '';\n    position: absolute;\n    display: block;\n    top: calc(50% - 1px);\n    border: 1px solid var(--wire-col);\n    width: 9px;\n    height: 0;\n    background: var(--wire-col);\n    box-sizing: content-box;\n}\n.classical.gate_in:before,\n.classical.gate_in:after{\n    border-color: var(--c-wire-col);\n}\n\n.gate_in:before{\n    left: -12px;\n}\n.gate_out:after{\n    right: -12px;\n}\n.gate_top.gate_in:before, .gate_top.gate_out:after{\n    top:calc(50% - 6.5px)\n}\n.gate_bottom.gate_in:before, .gate_bottom.gate_out:after{\n    top:calc(50% + 4.5px)\n}\n\n\n.link-bottom, .link-top {\n    height: var(--box-height);\n    width: 0;\n    border: 1px solid var(--wire-col);\n    background: var(--wire-col);\n    position: absolute;\n    display: block;\n    left: calc(50% - 1px);\n    box-sizing: content-box;\n}\n.link-top{\n    top: calc(0px - var(--box-height)/2);\n}\n.link-bottom{\n    top: calc(var(--box-height)/2)\n}\n.half-link {\n    height: calc(var(--box-height) - 9px);\n}\n.half-link.link-bottom{\n    top: calc(var(--box-height)/2 + 11px)\n}\n.half-link.link-top{\n    top: calc(-2px - var(--box-height)/2);\n}\n.link-bottom.measurement{\n    width: 3px;\n    left: calc(50% - 0.5px);\n    border: none;\n    background: var(--c-wire-col);\n    height: calc(var(--box-height) + 2px);\n    z-index: 1;\n}\n\n\n\n/* tool tips */\n.tool-tip-container{\n    margin: calc(0px - var(--box-height)) auto 0;\n    padding-top: var(--box-height);\n    position: relative;\n    bottom: 0;\n    left: 0;\n    right: 0;\n    height: 0;\n    z-index: 4;\n    width: fit-content;\n    overflow: hidden;\n}\n.tool-tip-container.no-js{\n    overflow: visible;\n}\n.tool-tip-container.no-js:hover{\n    z-index: 10;\n}\n.nested > .tool-tip-container{\n    position: absolute;\n    bottom: -10px;\n}\n.tool-tip{\n    visibility: hidden;\n    opacity: 0;\n    -webkit-transition: visibility 0.2s, opacity 0.2s;\n    -moz-transition: visibility 0.2s, opacity 0.2s;\n    transition: visibility 0.2s, opacity 0.2s;\n    max-width: 250px;\n}\n.tool-tip-container.no-js:hover > .tool-tip{\n    visibility: visible;\n    opacity: 1;\n}\n.tool-tip-content{\n    background: var(--main-bg);\n    margin: 0 auto;\n    width: -moz-fit-content;\n    width: fit-content;\n    max-width: 100%;\n}\n.no-js > .tool-tip > .tool-tip-content{\n    height: auto;\n    padding: 20px;\n    margin: 0 auto;\n}\n.tool-tip-container.no-js:hover > .tool-tip > .tool-tip-content,\n.no-js > tool-tip > .tool-tip-content:hover{\n    box-shadow: 0 -5px 20px 5px var(--faint-col-overlay);\n}\n.tool-tip:after{\n    content: \" \";\n    position: absolute;\n    bottom: 0;\n    left: 50%;\n    margin-left: -5px;\n    border-width: 5px;\n    border-style: solid;\n    border-color: transparent transparent var(--main-bg) transparent;\n}\n.tool-tip .complex-number{\n    padding: 4px;\n}\n.tool-tip-content > .gate_container.nested{\n    width: 100%;\n    min-width: unset;\n}\n.nested-label-layer.as-height{\n    padding: 0;\n}\n.tool-tip-content > .gate_container.nested > .nested-circuit-container,\n.circuit-preview.condensed > .nested-circuit-container{\n    background: transparent;\n    border: none;\n    width: 100%;\n    min-width: unset;\n    max-width: unset;\n}\n\n/* Tool-tip modal */\n.circuit-grid{\n    display: flex;\n    flex-direction: row-reverse;\n    align-items: stretch;\n    align-content: stretch;\n}\n.circuit-grid-circuit{\n    flex: 1 1 auto;\n    margin-top: 30px;\n    overflow: auto;\n    max-height: inherit;\n}\n\n\n\n\n/*  FOR DISPLAYING CHARTS  */\ntable{\n    border-collapse: collapse;\n}\n.table-container{\n    margin: auto;\n}\n.bar-chart-container{\n    min-width: 300px;\n    width: 60%;\n}\n.square-chart-container{\n    width: auto;\n    min-width: 0;\n    overflow: hidden;\n}\n\n/* Make sure we can see the rightmost border */\n.square-chart-container tbody{\n    position: relative;\n    left: -1px;\n    display: block;\n}\nthead > tr{\n    background: transparent !important;\n}\ntr:hover, tr {\n    background: initial !important;\n}\n\ntd, th{\n    padding: 10px;\n    position: relative;\n}\n\n/* COMPLEX NUMBERS AND MATRICES */\n.complex-number{\n    padding: 10px;\n}\n.mid-number{\n    padding: 5px;\n    font-size: 0.75em;\n}\n.large-number{\n    padding: 2px;\n    font-size: 0.75em;\n}\n.matrix_container{\n    border: 2px solid var(--mid-col);\n    border-top: 0;\n    border-bottom: 0;\n    margin: auto !important;\n    border-collapse: collapse;\n    text-align: center;\n}\n\n\n/* LIST RESULTS NICELY */\n.list{\n    flex-wrap: wrap;\n    justify-content: space-evenly;\n    align-items: stretch;\n    padding: 0;\n}\n.list > *{\n    margin: 10px;\n}\n.list > .row-sub-heading{\n    margin: 10px 0;\n}\n</style>\n\n</head>\n<body>\n    <div class=\"row circuit-grid circuit__preview-body\">\n        <div class=\"circuit-grid-circuit thin-scrollbar\"  style=\"\">\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n    <div class=\"circuit-preview circuit_variables condensed\">\n\n\n            <div class=\"nested-label-layer as-height\">\n\n                    <div class=\"wire-label\"></div>\n\n                    <div class=\"wire-label\"></div>\n\n                    <div class=\"wire-label\"></div>\n\n                    <div class=\"wire-label\"></div>\n\n                    <div class=\"wire-label\"></div>\n\n            </div>\n            <div class=\"nested-circuit-container\"><div class=\"circuit-inner-scroll\">\n\n        <div class=\"circuit-container nested\">\n            <div class=\"circuit-layer qubits\">\n\n            <div class=\"qubit\">q[0]</div>\n\n            <div class=\"qubit\">q[1]</div>\n\n            <div class=\"qubit\">q[2]</div>\n\n\n            <div class=\"qubit bit\">c[0]</div>\n\n            <div class=\"qubit bit\">c[1]</div>\n\n    </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container x\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rx(2*Alice__n_0)</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container h\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container h\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container z\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rz(2*Alice__n_1)</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n                <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n                <div class=\"gate gate_control z\"></div>\n\n            </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container z\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rz(2*runs__n.r@s_0)</span>\n                </div>\n\n\n\n                <div class=\"link-top\"></div>\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container x\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rx(2*Alice__n_2)</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container h\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container h\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n                <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n                <div class=\"gate gate_control z\"></div>\n\n            </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container z\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rz(2*runs__n.r@s_1)</span>\n                </div>\n\n\n\n                <div class=\"link-top\"></div>\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n                <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n                <div class=\"gate gate_control z\"></div>\n\n            </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container x\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">X</span>\n                </div>\n\n\n\n                <div class=\"link-top\"></div>\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n        <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection gate_measure\"></div>\n\n            <div class=\"control_index measure z\">z</div>\n\n    </div>\n\n            <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n\n    </div>\n\n        <div class=\"gate_container\">\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container h\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n        <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection gate_measure\"></div>\n\n            <div class=\"control_index measure z\">z</div>\n\n    </div>\n\n            <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n\n    </div>\n\n        <div class=\"gate_container\">\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n            <div class=\"circuit-layer qubits\">\n\n            <div class=\"qubit\">q[0]</div>\n\n            <div class=\"qubit\">q[1]</div>\n\n            <div class=\"qubit\">q[2]</div>\n\n\n            <div class=\"qubit bit\">c[0]</div>\n\n            <div class=\"qubit bit\">c[1]</div>\n\n    </div>\n        </div>\n\n            </div></div>\n\n    </div>\n\n\n\n\n        </div>\n    </div>\n</body>\n</html>\n\n\n\n```python\nfrom sympy import default_sort_key\n\n# Make sure you sort your symbols as they are returned as a set.\nparameters = sorted(tket_circuit.free_symbols(), key=default_sort_key)\n\nparam_dict = {p: i * 0.001 for i, p in enumerate(parameters)}\nparam_dict\n```\n\n\n\n\n    {Alice__n_0: 0.0,\n     Alice__n_1: 0.001,\n     Alice__n_2: 0.002,\n     runs__n.r@s_0: 0.003,\n     runs__n.r@s_1: 0.004}\n\n\n\n\n```python\ntket_circuit.symbol_substitution(param_dict)\n\n# This does not render properly on GitHub, please view it at:\n# https://cqcl.github.io/lambeq/examples/circuit.html\nrender_circuit_jupyter(tket_circuit)\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n\n<style>\nbody, .circuit__preview-body {\n    font-family: \"roboto\", system-ui, sans-serif;\n    --accent-col: green;\n    --accent-col-fill: darkseagreen;\n    --accent-col-alt: #aca;\n    --accent-col-emph: limegreen;\n    --accent-col-overlay: rgba(130,255,140,0.2);\n    --accent-col-outline: rgba(30, 250, 30,0.2);\n    --main-col: black;\n    --mid-col: #bbb;\n    --faint-col: #eee;\n    --faint-col-overlay: rgba(0, 0, 0, 0.05);\n    --main-bg: white;\n}\n\n.row{\n    display: flex;\n    flex-wrap: wrap;\n    align-items: center;\n    padding: 10px;\n    border-bottom: 1px solid var(--faint-col);\n    position: relative;\n}\n.row-item{\n    flex-grow: 1\n}\n.row-item-l{\n    text-align: left;\n}\n.row-item-r{\n    text-align: right;\n}\n.row-sub-heading{\n    border-color: var(--accent-col-emph);\n}\n\n/* FOR DISPLAYING CIRCUITS */\n/* Main preview container */\n.circuit-preview {\n    width: 100%;\n    height: 100%;\n    text-align: center;\n    color: black;\n}\n.circuit_variables {\n    /* Define some variables */\n    --box-height: 40px;\n    --wire-col: black;\n    --c-wire-col: #bbb;\n    --box-col: #ccc;\n    --box-col-overlay: rgba(0,0,0,0.05);\n    --c-box-col: #ddd;\n    --index-col: #888;\n}\n.circuit-preview.condensed{\n    display: flex;\n    flex-wrap: nowrap;\n}\n\n/* Box colours */\n.h {\n    --box-col: #ffee00;\n    --box-col-overlay: rgba(255, 255, 0, 0.2);\n    --c-box-col: #ffee88;\n    --index-col: #ffcc00;\n}\n.x {\n    --box-col: #ff8888;\n    --box-col-overlay: rgba(255, 0, 0, 0.2);\n    --c-box-col: #e8a6a6;\n    --index-col: red;\n}\n.y {\n    --box-col: #6699ff;\n    --box-col-overlay: rgba(0, 0, 255, 0.2);\n    --c-box-col: #86c6f6;\n    --index-col: blue;\n}\n.z {\n    --box-col: #ccffcc;\n    --box-col-overlay: rgba(0, 255, 0, 0.2);\n    --c-box-col: #e2ffe2;\n    --index-col: green;\n}\n\n.circuit-container{\n    max-width: 100%;\n    display: flex;\n    flex-flow: row wrap;\n    justify-content: center;\n    align-content: flex-start;\n    margin: auto;\n    width: -moz-fit-content;\n    width: fit-content;\n    background: rgba(255, 255, 255, 1);\n}\n.circuit-preview.condensed > .circuit-container{\n    flex-wrap: nowrap;\n    min-width: fit-content;\n}\n.circuit-container.nested{\n    position: relative;\n    flex-wrap: nowrap;\n    margin: -2px 0;\n}\n.nested-circuit-container{\n    display: flex;\n    overflow: auto;\n    max-width: 400px;\n    background: var(--box-col-overlay);\n    border: 1px solid var(--box-col);\n}\n.nested-circuit-container::-webkit-scrollbar {\n    height: 0;\n    width: 0;\n}\n.circuit-inner-scroll{\n    overflow: visible;\n    width: -moz-fit-content;\n    width: fit-content;\n    margin: auto;\n    margin-top: 2px;\n}\n.circuit-end{\n    width: 2px;\n    height: auto;\n    border: 2px solid var(--wire-col);\n    margin: calc(var(--box-height)/2) 0 calc(var(--box-height)/2 + 20px);\n}\n.circuit-layer{\n    min-width: 40px;\n    width: max-content;\n    display: flex;\n    flex-flow: column nowrap;\n    flex-grow: 1;\n    justify-content: space-between;\n    align-items: stretch;\n    margin-bottom: 20px;\n}\n.circuit-container:not(.nested) > .circuit-layer:nth-child(2),\n.circuit-container:not(.nested) > .circuit-layer:nth-last-child(2),\n.circuit-container.nested > .circuit-layer:nth-child(2),\n.circuit-container.nested > .circuit-layer:nth-last-child(2),\n.gate_container.nested > .circuit-layer:first-child,\n.gate_container.nested > .circuit-layer:last-child{\n    min-width: 10px;\n}\n.nested .circuit-layer{\n    margin-bottom: 0;\n}\n.flex_wire{\n    flex-grow: 1;\n}\n/* Display qubit names at start of circuit */\n.circuit-layer.qubits{\n    flex-grow: 0;\n    color: var(--wire-col);\n}\n.qubit{\n    height: calc(var(--box-height) - 20px);\n    padding: 10px;\n    text-align: center;\n    font-family: monospace;\n    box-sizing: content-box;\n}\n.wire{\n    height: 0;\n    border: 1px solid var(--wire-col);\n    background: var(--wire-col);\n    margin: calc(var(--box-height)/2) 0;\n}\n.wire.classical{\n    border-color: var(--c-wire-col) !important;\n    background: var(--c-wire-col) !important;\n}\n.wire.transparent-wire{\n    border-color: transparent;\n    background: transparent;\n}\n\n/* Generic base for our gates */\n.gate_container{\n    position: relative;\n    min-width: -moz-fit-content;\n    min-width: fit-content;\n}\n.gate_container.nested{\n    display: flex;\n    flex-wrap: nowrap;\n}\n.gate_container.nested:after{\n    display: flex;\n    flex-wrap: nowrap;\n}\n.gate_container .classical{\n    background: var(--c-box-col);\n    border-color: var(--index-col);\n}\n.gate{\n    position: relative;\n    height: calc(var(--box-height) - 16px);\n    margin: 0 9px;\n    padding: 9px 5px;\n    border: 1px solid var(--index-col);\n    border-bottom: none;\n    border-top: none;\n    text-align: left;\n    background: var(--box-col);\n    display: flex;\n    box-sizing: content-box;\n    z-index: 1;\n}\n.wire-label{\n    color: var(--index-col);\n    width: -moz-fit-content;\n    width: fit-content;\n    height: calc(var(--box-height) - 18px);\n    padding-right: 5px;\n}\n.gate_top > .wire-label,\n.gate_bottom > .wire-label {\n    padding-top: 0;\n}\n.nested-label-layer{\n    background: var(--box-col);\n    padding: 0 5px;\n}\n.nested-label-layer .wire-label{\n    padding: 10px 0;\n}\n\n/* Multi-qubit gates */\n.gate_bottom{\n    height: calc(var(--box-height) - 18px);\n    margin-bottom: 10px;\n    padding-bottom: 0;\n    border-bottom: 1px solid var(--index-col);\n}\n.gate_top{\n    height: calc(var(--box-height) - 18px);\n    margin-top: 10px;\n    padding-top: 0;\n    border-top: 1px solid var(--index-col);\n}\n.gate_name{\n    text-align: center;\n    flex-grow: 1;\n}\n/* Single qubit gate*/\n.gate_box{\n    height: calc(var(--box-height) - 20px);\n    margin: 10px;\n    padding: 0 5px;\n    border: 1px solid var(--index-col);\n    text-align: center;\n}\n\n/* Special gates */\n.gate_connection {\n    position: absolute;\n    top: -3px;\n    left: -1px;\n    border: none;\n    margin: calc(var(--box-height)/2) calc(50% - 5px);\n    padding: 0;\n}\n.gate_swap {\n    height: 20px;\n    width: 20px;\n    margin: calc(var(--box-height)/2 - 6px) calc(50% - 9px);\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%270%200%2064%2064%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27currentcolor%27%3E%0A%20%20%3Cpath%20d%3D%27M60%200%20L32%2028%20L4%200%20L0%204%20L28%2032%20L0%2060%20L4%2064%20L32%2036%20L60%2064%20L64%2060%20L36%2032%20L64%204%27%20/%3E%0A%3C/svg%3E\n) center;\n    background-size: cover;\n}\n.gate_measure {\n    height: 20px;\n    width: 25px;\n    margin: calc(var(--box-height)/2 - 10px) calc(50% - 11px);\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%27-10%20-10%2084%2084%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27white%27%0A%20%20stroke%3D%22black%22%0A%20%20stroke-width%3D%224px%22%0A%3E%0A%20%20%3Cpath%20d%3D%27M63%2C63%20C63%2C32%2048%2C16%2032%2C16%20C16%2C16%201%2C32%201%2C63%20L63%2C63%27%20/%3E%0A%20%20%3Cpath%20d%3D%22M32%2C63%20L56%2C16%22%20/%3E%0A%3C/svg%3E\n) center;\n    background-size: cover;\n}\n.gate_control {\n    position: absolute;\n    top: 0;\n    left: 0;\n    border-radius: 50%;\n    width: 6px;\n    height: 6px;\n    margin: calc(var(--box-height)/2 - 3px) calc(50% - 5px);\n    padding: 0;\n    border: 2px solid var(--wire-col);\n    background: var(--box-col);\n}\n.gate_control.classical{\n    background: var(--c-wire-col);\n    border-color: var(--c-wire-col);\n}\n.control_index{\n    position: absolute;\n    right: calc(50% - 1em);\n    top: calc(50% - 1.4em);\n    color: var(--c-wire-col);\n    font-size: 0.8em;\n}\n.control_index.measure{\n    right: calc(50% - 1.2em);\n    top: calc(50% - 1.8em);\n    color: var(--index-col);\n}\n.gate_x {\n    top: -10px;\n    left: -6px;\n    border-radius: 50%;\n    border: 1px solid var(--wire-col);\n    width: 20px;\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%270%200%2064%2064%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27currentcolor%27%3E%0A%20%20%3Cpath%20d%3D%27M36%2064%20L36%2036%20L64%2036%20L64%2028%20L36%2028%20L36%200%20L28%200%20L28%2028%20L0%2028%20L0%2036%20L28%2036%20L28%2064%27%20/%3E%0A%3C/svg%3E\n) center;\n    background-color: var(--box-col);\n    background-size: cover;\n}\n.gate_reset{\n    margin: 11px 10px;\n    padding: 0 0 0 10px;\n    border: none !important;\n    border-left: 2px solid var(--wire-col) !important;\n    background: transparent;\n}\n.gate_reset_spider{\n    width: calc(var(--box-height) - 24px);\n    height: calc(var(--box-height) - 24px);\n    background: var(--box-col);\n    border: 2px solid var(--wire-col);\n    border-radius: 50%;\n    font-size: 0.75em;\n}\n\n/* Add wire sections coming in and out of the gate */\n.gate_in:before, .gate_in:after{\n    content: '';\n    position: absolute;\n    display: block;\n    top: calc(50% - 1px);\n    border: 1px solid var(--wire-col);\n    width: 9px;\n    height: 0;\n    background: var(--wire-col);\n    box-sizing: content-box;\n}\n.classical.gate_in:before,\n.classical.gate_in:after{\n    border-color: var(--c-wire-col);\n}\n\n.gate_in:before{\n    left: -12px;\n}\n.gate_out:after{\n    right: -12px;\n}\n.gate_top.gate_in:before, .gate_top.gate_out:after{\n    top:calc(50% - 6.5px)\n}\n.gate_bottom.gate_in:before, .gate_bottom.gate_out:after{\n    top:calc(50% + 4.5px)\n}\n\n\n.link-bottom, .link-top {\n    height: var(--box-height);\n    width: 0;\n    border: 1px solid var(--wire-col);\n    background: var(--wire-col);\n    position: absolute;\n    display: block;\n    left: calc(50% - 1px);\n    box-sizing: content-box;\n}\n.link-top{\n    top: calc(0px - var(--box-height)/2);\n}\n.link-bottom{\n    top: calc(var(--box-height)/2)\n}\n.half-link {\n    height: calc(var(--box-height) - 9px);\n}\n.half-link.link-bottom{\n    top: calc(var(--box-height)/2 + 11px)\n}\n.half-link.link-top{\n    top: calc(-2px - var(--box-height)/2);\n}\n.link-bottom.measurement{\n    width: 3px;\n    left: calc(50% - 0.5px);\n    border: none;\n    background: var(--c-wire-col);\n    height: calc(var(--box-height) + 2px);\n    z-index: 1;\n}\n\n\n\n/* tool tips */\n.tool-tip-container{\n    margin: calc(0px - var(--box-height)) auto 0;\n    padding-top: var(--box-height);\n    position: relative;\n    bottom: 0;\n    left: 0;\n    right: 0;\n    height: 0;\n    z-index: 4;\n    width: fit-content;\n    overflow: hidden;\n}\n.tool-tip-container.no-js{\n    overflow: visible;\n}\n.tool-tip-container.no-js:hover{\n    z-index: 10;\n}\n.nested > .tool-tip-container{\n    position: absolute;\n    bottom: -10px;\n}\n.tool-tip{\n    visibility: hidden;\n    opacity: 0;\n    -webkit-transition: visibility 0.2s, opacity 0.2s;\n    -moz-transition: visibility 0.2s, opacity 0.2s;\n    transition: visibility 0.2s, opacity 0.2s;\n    max-width: 250px;\n}\n.tool-tip-container.no-js:hover > .tool-tip{\n    visibility: visible;\n    opacity: 1;\n}\n.tool-tip-content{\n    background: var(--main-bg);\n    margin: 0 auto;\n    width: -moz-fit-content;\n    width: fit-content;\n    max-width: 100%;\n}\n.no-js > .tool-tip > .tool-tip-content{\n    height: auto;\n    padding: 20px;\n    margin: 0 auto;\n}\n.tool-tip-container.no-js:hover > .tool-tip > .tool-tip-content,\n.no-js > tool-tip > .tool-tip-content:hover{\n    box-shadow: 0 -5px 20px 5px var(--faint-col-overlay);\n}\n.tool-tip:after{\n    content: \" \";\n    position: absolute;\n    bottom: 0;\n    left: 50%;\n    margin-left: -5px;\n    border-width: 5px;\n    border-style: solid;\n    border-color: transparent transparent var(--main-bg) transparent;\n}\n.tool-tip .complex-number{\n    padding: 4px;\n}\n.tool-tip-content > .gate_container.nested{\n    width: 100%;\n    min-width: unset;\n}\n.nested-label-layer.as-height{\n    padding: 0;\n}\n.tool-tip-content > .gate_container.nested > .nested-circuit-container,\n.circuit-preview.condensed > .nested-circuit-container{\n    background: transparent;\n    border: none;\n    width: 100%;\n    min-width: unset;\n    max-width: unset;\n}\n\n/* Tool-tip modal */\n.circuit-grid{\n    display: flex;\n    flex-direction: row-reverse;\n    align-items: stretch;\n    align-content: stretch;\n}\n.circuit-grid-circuit{\n    flex: 1 1 auto;\n    margin-top: 30px;\n    overflow: auto;\n    max-height: inherit;\n}\n\n\n\n\n/*  FOR DISPLAYING CHARTS  */\ntable{\n    border-collapse: collapse;\n}\n.table-container{\n    margin: auto;\n}\n.bar-chart-container{\n    min-width: 300px;\n    width: 60%;\n}\n.square-chart-container{\n    width: auto;\n    min-width: 0;\n    overflow: hidden;\n}\n\n/* Make sure we can see the rightmost border */\n.square-chart-container tbody{\n    position: relative;\n    left: -1px;\n    display: block;\n}\nthead > tr{\n    background: transparent !important;\n}\ntr:hover, tr {\n    background: initial !important;\n}\n\ntd, th{\n    padding: 10px;\n    position: relative;\n}\n\n/* COMPLEX NUMBERS AND MATRICES */\n.complex-number{\n    padding: 10px;\n}\n.mid-number{\n    padding: 5px;\n    font-size: 0.75em;\n}\n.large-number{\n    padding: 2px;\n    font-size: 0.75em;\n}\n.matrix_container{\n    border: 2px solid var(--mid-col);\n    border-top: 0;\n    border-bottom: 0;\n    margin: auto !important;\n    border-collapse: collapse;\n    text-align: center;\n}\n\n\n/* LIST RESULTS NICELY */\n.list{\n    flex-wrap: wrap;\n    justify-content: space-evenly;\n    align-items: stretch;\n    padding: 0;\n}\n.list > *{\n    margin: 10px;\n}\n.list > .row-sub-heading{\n    margin: 10px 0;\n}\n</style>\n\n</head>\n<body>\n    <div class=\"row circuit-grid circuit__preview-body\">\n        <div class=\"circuit-grid-circuit thin-scrollbar\"  style=\"\">\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n    <div class=\"circuit-preview circuit_variables condensed\">\n\n\n            <div class=\"nested-label-layer as-height\">\n\n                    <div class=\"wire-label\"></div>\n\n                    <div class=\"wire-label\"></div>\n\n                    <div class=\"wire-label\"></div>\n\n                    <div class=\"wire-label\"></div>\n\n                    <div class=\"wire-label\"></div>\n\n            </div>\n            <div class=\"nested-circuit-container\"><div class=\"circuit-inner-scroll\">\n\n        <div class=\"circuit-container nested\">\n            <div class=\"circuit-layer qubits\">\n\n            <div class=\"qubit\">q[0]</div>\n\n            <div class=\"qubit\">q[1]</div>\n\n            <div class=\"qubit\">q[2]</div>\n\n\n            <div class=\"qubit bit\">c[0]</div>\n\n            <div class=\"qubit bit\">c[1]</div>\n\n    </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container x\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rx(0.0)</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container h\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container h\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container z\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rz(0.002)</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n                <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n                <div class=\"gate gate_control z\"></div>\n\n            </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container z\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rz(0.006)</span>\n                </div>\n\n\n\n                <div class=\"link-top\"></div>\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container x\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rx(0.004)</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container h\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container h\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n                <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n                <div class=\"gate gate_control z\"></div>\n\n            </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container z\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rz(0.008)</span>\n                </div>\n\n\n\n                <div class=\"link-top\"></div>\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n                <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n                <div class=\"gate gate_control z\"></div>\n\n            </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container x\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">X</span>\n                </div>\n\n\n\n                <div class=\"link-top\"></div>\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n        <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection gate_measure\"></div>\n\n            <div class=\"control_index measure z\">z</div>\n\n    </div>\n\n            <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n\n    </div>\n\n        <div class=\"gate_container\">\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container h\">\n\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n        <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection gate_measure\"></div>\n\n            <div class=\"control_index measure z\">z</div>\n\n    </div>\n\n            <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n\n    </div>\n\n        <div class=\"gate_container\">\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n                <div class=\"circuit-layer hover-highlight-circuit\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n            </div>\n\n            <div class=\"circuit-layer qubits\">\n\n            <div class=\"qubit\">q[0]</div>\n\n            <div class=\"qubit\">q[1]</div>\n\n            <div class=\"qubit\">q[2]</div>\n\n\n            <div class=\"qubit bit\">c[0]</div>\n\n            <div class=\"qubit bit\">c[1]</div>\n\n    </div>\n        </div>\n\n            </div></div>\n\n    </div>\n\n\n\n\n        </div>\n    </div>\n</body>\n</html>\n\n", "meta": {"hexsha": "16936d9b3798a2d4bb267fecad408111670245ab", "size": 151372, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/examples/circuit.ipynb", "max_stars_repo_name": "CQCL/lambeq", "max_stars_repo_head_hexsha": "04e4f736552c1ed51087dc9913f33464fad3783e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 131, "max_stars_repo_stars_event_min_datetime": "2021-10-11T02:45:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T22:28:05.000Z", "max_issues_repo_path": "docs/examples/circuit.ipynb", "max_issues_repo_name": "CQCL/lambeq", "max_issues_repo_head_hexsha": "04e4f736552c1ed51087dc9913f33464fad3783e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-11-04T10:56:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-04T11:20:20.000Z", "max_forks_repo_path": "docs/examples/circuit.ipynb", "max_forks_repo_name": "CQCL/lambeq", "max_forks_repo_head_hexsha": "04e4f736552c1ed51087dc9913f33464fad3783e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25, "max_forks_repo_forks_event_min_datetime": "2021-10-13T03:34:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T11:48:21.000Z", "avg_line_length": 42.6279921149, "max_line_length": 33954, "alphanum_fraction": 0.4791110641, "converted": true, "num_tokens": 15771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.08509904094645104, "lm_q1q2_score": 0.03956267785837342}}
{"text": "# Transformadores\n__UNLZ - Facultad de Ingenier\u00eda__       \n__Electrotecnia__      \n__Alumno:__ Daniel Antonio Lorenzo\n\n<a href=\"https://colab.research.google.com/github/daniel-lorenzo/Electrotecnia/blob/master/Transformadores_ideales.ipynb\"></a>\n\n## Introducci\u00f3n\nUno de los dispositivos que han hecho posible el sistema de potencia de ca comercial como se le conoce hoy en d\u00eda es el transformador.\nLos transformadores tienen muchas aplicaciones. Se usan en sistemas de potencia el\u00e9ctrica para aumentar el voltaje en transmisiones a larga distancia y para disminuirlo luego otra vez a un nivel seguro para su empleo en casas y oficinas. Se utilizan en fuentes de potencia para equipo electr\u00f3nico con el fin de subir o bajar el voltaje, en sistemas de audio para igualar las cargas de las bocinas a los amplificadores, en telefon\u00eda, en radio y en sistemas de televisi\u00f3n para acoplar se\u00f1ales, etc\u00e9tera.\n\nUn transformador es un __circuito acoplado__ magn\u00e9ticamente, es decir, un circuito en el cual el campo magn\u00e9tico producido por la corriente que var\u00eda en el tiempo induce voltaje en otro. Para ilustrarlo, en la figura se muestra un transformador b\u00e1sico con n\u00facleo de hierro. Se compone de dos bobinas devanadas en un n\u00facleo com\u00fan. La corriente alterna en uno de los devanados establece un flujo que enlaza el otro devanado e induce un voltaje en \u00e9l. Entonces, la potencia fluye de un circuito al otro a trav\u00e9s de un medio del campo magn\u00e9tico, sin ninguna conexi\u00f3n el\u00e9ctrica entre los dos lados. El devanado al cual se le suministra potencia se llama __primario__, mientras que el devanado el cual toma la potencia se le llama __secundario__. La potencia puede fluir en cualquier direcci\u00f3n, ya que cualquiera de los devanados puede usarse como primario o secundario.\n\n\n\nLos transformadores se clasifican en dos tipos: de n\u00facleo de hierro y de n\u00facleo de aire. Se inicia con los del tipo de n\u00facleo de hierro. Estos transformadores se usan por lo general en aplicaciones de baja frecuencia.\n\nEl hierro (en realidad un acero especial llamado acero de transformador) se usa para n\u00facleos porque incremente el acoplamiento entre las bobinas proporcionando una trayectoria f\u00e1cil para el flujo magn\u00e9tico. Se usan dos tipos b\u00e1sicos en la construcci\u00f3n del n\u00facleo de hierro: el __tipo n\u00facleo__ y el __tipo acorazado__. En ambos casos, los n\u00facleos se fabrican con l\u00e1minas de acero, aisladas unas de otras mediante una delgada cubierta de cer\u00e1mica u otro material para ayudar a minimizar las p\u00e9rdidas por corrientes par\u00e1sitas.\n\nSin embargo, el hierro tiene p\u00e9rdidas de potencia considerables debidas a la hist\u00e9resis y a las corrientes par\u00e1sitas a altas frecuencias, por esa raz\u00f3n no es \u00fatil como material de n\u00facleo por arriba de 50 kHz. Para aplicaciones de alta frecuencia (como en circuitos de radio) se usan los tipos de __n\u00facleo de aire__ y __n\u00facleo de ferrita__.\n\n\n\n__Tipo n\u00facleo y tipo acorazado:__\n\n\n\n> Para el tipo n\u00facleo (izquierda), los devanados est\u00e1n en brazos separados, mientras que para el tipo acorazado (derecha) ambos devanados est\u00e1n en el mismo brazo.\n\n__Direcciones del devanado__\n\nUna de las ventajas de un transformador es que puede usarse para cambiar la polaridad de un voltaje de ca. Esto se ilustra en la siguiente figura para un par de transformadores de n\u00facleo de hierro. Para el transformador (a) los voltajes del primario y del secundario est\u00e1n en fase (por razones que se discutir\u00e1n despu\u00e9s), mientras que en (b) est\u00e1n fuera de fase por 180\u00b0.\n\n\n\nA primera vista, los transformadores de n\u00facleo de hierro parecen dif\u00edciles de analizar porque tienen caracter\u00edsticas tales como resistencia del devanado, p\u00e9rdidas en el n\u00facleo y fugas de flujo que parecen dif\u00edciles de manejar. Por fortuna, estos efectos son peque\u00f1os y a menudo se pueden pasar por alto. El resultado es el __transformador ideal__. Sin embargo, una vez que se conoce c\u00f3mo analizar un transformador ideal, es relativamente f\u00e1cil agregar los efectos no ideales.\n\n## Transformador ideal\n\n<div class=\"alert-success\">Un <strong>transformador ideal</strong> es un transformador de acoplamiento unitario sin p\u00e9rdidas en el que las bobinas primaria y secundaria tienen autoinductacias infinitas.</div>\n\n__En un transformador ideal:__\n1. No se toma en cuenta la resistencia de sus bobinas\n2. Se desprecian sus p\u00e9rdidas en el n\u00facleo\n3. Se supone que todo el flujo est\u00e1 confinado en su n\u00facleo\n4. Se supone que se necesita una corriente \u00ednfima para establecer el flujo en su n\u00facleo\n\nLos transformadores de potencia de n\u00facleo de hierro bien dise\u00f1ados son casi ideales.\n\n\n\nSe dice que dos bobinas est\u00e1n acopladas mutuamente si el flujo magn\u00e9tico \ud835\udf19 que emana de una de ellas pasa por la otra. La inductancia mutua entre las dos bobinas est\u00e1 dada por\n\n$$ M = k \\sqrt{L_1 L_2} $$\n\ndonde $k$ es el coeficiente de acoplamiento $0<k<1$.\n\n<div class=\"alert-success\">La <strong>inductancia mutua</strong> es la capacidad de un inductor de inducir una tensi\u00f3n en un inductor cercano, medida en henrys (H).\n    </div>\n\nUn __transformador ideal__ es aquel con acoplamiento perfecto $(k=1)$. Consta de dos (o m\u00e1s) bobinas con gran n\u00famero de vueltas devanadas en un n\u00facleo com\u00fan de alta permeabilidad. A causa de esta permeabilidad del n\u00facleo, el flujo enlaza a todas las vueltas de ambas bobinas, lo que da por resultado un acoplamiento perfecto.\n\nLos transformadores de n\u00facleo de hierro son una aproximaci\u00f3n muy cercana de transformadores ideales. Se les emplea en sistemas de potencia y en electr\u00f3nica.\n\nCuando se aplica una tensi\u00f3n senoidal al devanado primario, como se advierte en la figura, por ambos devanados pasa el mismo flujo magn\u00e9tico $\\phi$. De acuerdo con la ley de Faraday, la tensi\u00f3n en el devanado primario es\n\n$$ v_1 = N_1 \\frac{d \\phi}{dt} \\tag{a} $$\n\nmientras que a trav\u00e9s del devanado secundario es\n\n$$ v_2 = N_2 \\frac{d \\phi}{dt} \\tag{b} $$\n\nAl dividir la ecuaci\u00f3n (b) entre la ecuaci\u00f3n (a) se obtiene\n\n$$ \\frac{v_2}{v_1} = \\frac{N_2}{N_1} = \\frac{1}{a} = n \\tag{1} $$\n\ndonde $n$ es, de nueva cuanta, la *relaci\u00f3n de vueltas* o *relaci\u00f3n de transformaci\u00f3n*. Pueden usarse las tensiones fasoriales $V_1$ y $V_2$ en lugar de los valores instant\u00e1neos $v_1$ y $v_2$. As\u00ed, la ecuaci\u00f3n (1) puede escribirse como\n\n$$ \\frac{V_2}{V_1} = \\frac{N_2}{N_1} = \\frac{1}{a} = n \\tag{2} $$\n\nPor efecto de la conservaci\u00f3n de la potencia, la energ\u00eda suministrada al devanador primario debe ser igual a la energ\u00eda absorbida por el devanado secundario, ya que en un transformador ideal no hay p\u00e9rdidas. Esto implica que\n\n$$ v_1 i_1 = v_2 i_2 \\tag{3} $$\n\nEn forma fasorial, la ecuaci\u00f3n (3) se convierte, junto con la ecuaci\u00f3n (2), en\n\n$$ \\frac{I_1}{I_2} = \\frac{V_2}{V_1} = \\frac{1}{a} = n \\tag{4} $$\n\nlo que indica que las corrientes primaria y secundaria se determinan con la relaci\u00f3n de vueltas en forma inversa que las tensiones. As\u00ed,\n\n$$ \\frac{I_2}{I_1} = \\frac{N_1}{N_2} = a = \\frac{1}{n} \\tag{5} $$\n\nCuando $n=1$, el transformador se llama por lo general *transformador de aislamiento*. Si $n>1$, se tiene un *transformador elevador*, pues la tensi\u00f3n aumenta de primaria a secundaria $(V_2 > V_1)$. Por otra parte, $n<1$, el transformador es un transformador reductor, ya que la tensi\u00f3n se reduce de primaria a secundaria $(V_2 < V_1)$\n\n<div class=\"alert-success\">Un <strong>transformador reductor</strong> es aquel cuya tensi\u00f3n secundaria es menor que su tensi\u00f3n primaria.</div>\n\n<div class=\"alert-success\">Un <strong>transformador elevador</strong> es aquel cuya tensi\u00f3n secundaria es mayor que su tensi\u00f3n primaria.</div>\n\nLa capacidad nominal de los transformadores suele especificarse como $V_1/V_2$. Un transformador con capacidad nominal de 2400/120 V debe tener 2400 V en el devanado primario y 120 en el secundario (es decir, se trata de un transformador reductor). T\u00e9ngase presente que las capacidades nominales de tensi\u00f3n est\u00e1n en rms.\n\nLas compan\u00edas de electricidad generan a menudo cierta tensi\u00f3n conveniente y se sirven de un transformador elevador para aumentar la tensi\u00f3n a fin de que la energ\u00eda el\u00e9ctrica pueda transmitirse a muy alta tensi\u00f3n y baja corriente por las l\u00edneas de transmisi\u00f3n, lo cual permite ahorros significativos. Cerca de las residencias de los consumidores, se emplean transformadores reductores para disminuir las tensi\u00f3n.\n\nEs importante saber c\u00f3mo obtener la polaridad apropiada de las tensiones y la direcci\u00f3n de las corrientes del transformador de la figura. Si la polaridad de $V_1$ o $V_2$ o la direcci\u00f3n de $I_1$ o $I_2$ cambia, podr\u00eda ser necesario reemplazar $n$ en las ecuaciones (1) a (5) por $-n$- Las dos reglas simples por seguir son:\n\n\n\n1. Si tanto $V_1$ como $V_2$ son *ambas* positivas o negativas en las terminales con marca, se usa $+n$ en la ecuaci\u00f3n.      \nDe lo contrario, se usa $-n$.\n2. Si tanto $I_1$ como $I_2$ *ambas* entran o salen de las terminales marcadas, se usa $-n$ en la ecuaci\u00f3n (5).    \nDe lo contrario, se usa $+n$.\n\nEstas reglas se demuestran en los cuatro circuitos de la figura\n\n\n\n\n\nUsando las ecuaciones (2) y (5), siempre es posible expresar $V_1$ en t\u00e9rmino de $V_2$ e $I_2$ o viceversa:\n\n$$ V_1 = \\frac{V_2}{n} \\qquad \\mbox{o} \\qquad V_2 = n V_1 \\tag{6} $$\n\n$$ I_1 = n I_2 \\qquad \\mbox{o} \\qquad I_2 = \\frac{I_1}{n} \\tag{7} $$\n\nLa potencia compleja en el devanado primario es\n\n$$ S_1 = V_1 I^\\ast_1 = \\frac{V_2}{n} (n I_2)^\\ast = V_2 I^\\ast_2 = S_2 \\tag{8} $$\n\nlo que indica que la potencia compleja provista al devanado primario se entrega al devanado secundario sin p\u00e9rdidas. El transformador no absorbe potencia.\n\n$$ Z_{ent} = \\frac{V_2}{I_1} = \\frac{1}{n^2} \\frac{V_2}{I_2} \\tag{9} $$\n\nEn la figura siguiente es evidente que $V_2/I_2 = Z_L$ de modo que\n\n$$ Z_{ent} = \\frac{Z_L}{n^2} \\tag{10} $$\n\nLa impedancia de entrada tambi\u00e9n se llama *impedancia reflejada*, puesto que parecer\u00eda que la impedancia de carga se reflejara en el lado primario. Esta capacidad del transformador para convertir una impedancia dada en otra impedancia proporciona un medio de *acoplamiento de impedancias* que garantice la transferencia de potencia m\u00e1xima.\n\nAl analizar un circuito que contiene un transformador ideal, es pr\u00e1ctica com\u00fan eliminar el transformador reflejando impedancias y fuentes de un lado del transformador al otro.\n\nSup\u00f3ngase que en el circuito de la figura, se desea reflejar el lado secundario del circuito en el lado primario. Se halla el equivalente de Thevenin del circuito a la derecha de las terminales *a-b*. Se obtiene $V_{TH}$ como la tensi\u00f3n de circuito abierto en las terminales *a-b*, como se observa en la figura.\n\n\n\n<center>Circuito con transformador ideal cuyos circuitos equivalentes se desea hallar.</center>\n\n\n\n<center>(a) Obtenci\u00f3n de $V_{TH}$   ;   (b) Obtenci\u00f3n de $Z_{TH}$</center>\n\nDado que las terminales *a-b* est\u00e1n abiertas, $I_1 = 0 = I_2$, de manera que $V_2 = V_{s2}$. As\u00ed, con base en la ecuaci\u00f3n (6)\n\n$$ V_{TH} = V_1 = \\frac{V_2}{n} = \\frac{V_{s2}}{n} \\tag{11} $$\n\nPara obtener $Z_{TH}$, se elimina la fuente de tensi\u00f3n del bobinado secundario y se inserta una fuente unitaria entre las terminales *a-b*.\n\nPartiendo de las ecuaciones (6) y (7), $I_1 = n I_2$ y $V_1 = V_2/n$, de modo que\n\n$$ Z_{Th} = \\frac{V_1}{I_1} = \\frac{V_2/n}{n I_2} = \\frac{Z_2}{n^2} \\qquad ; \\qquad V_2 = Z_2 I_2 \\tag{12} $$\n\nUna vez que se tiene $V_{TH}$ y $Z_{TH}$, se a\u00f1ade el equivalente de Thevenin a la parte del circuito de la figura a la izquierda de las terminales *a-b*\n\n\n\n\n\n<center>Circuito equivalente al de la figura anterior obtenido reflejando el circuito secundario en el lado primario.</center>\n\n\n\n<center>Circuito equivalente obtenido reflejando el circuito primario en el lado secundario.</center>\n\n<div class=\"alert-success\">La regla general para eliminar el transformador y reflejar el circuito secundario en el lado primario es: divida la impedancia secundaria entre $n^2$, divida la tensi\u00f3n secundaria entre $n$ y multiplique la corriente secundaria por $n$.</div>\n\nDe acuerdo con la ecuaci\u00f3n (8), la potencia se mantiene sin cambios ya sea que se calcule en el lado primario o en el secundario. Sin embargo, debe tomarse en cuenta que este m\u00e9todo de reflexi\u00f3n s\u00f3lo se aplica si no hay conexiones externas sobre los devanados primario y secundario, se aplica simplemente el an\u00e1lisis regular de lazo y de nodo. Ejemplos de circuitos en los que hay conexiones externas entre los devanados primario y secundario se dan en las figuras. Advi\u00e9rtase asimismo que si la ubicaci\u00f3n de las marcas en la figura cambia, quiz\u00e1 tendr\u00eda que reemplazarse $n$ por $-n$ para obedecer la regla del punto.\n\n## Ejemplo 13.7\nUn transformador ideal tiene capacidad nominal de 2400/120 V, 9,6 kVA y 50 vueltas en el lado secundario.Calcule:\n\na) la raz\u00f3n de vueltas.\n\nb) el n\u00famero de vueltas en el lado primario.\n\nc) las capacidades nominales de corriente de los devanados primario y secundario.\n\n### Soluci\u00f3n\n__a)__ \u00c9ste es un transformador reductor, ya que $V_1 = 2400 \\, \\mathrm{V} > V_2 = 120 \\, \\mathrm{V}$.\n\n$$ n = \\frac{V_2}{V_1} = \\frac{120}{2400} = 0,05 $$\n\n__b)__\n$$ n = \\frac{N_2}{N_1} \\qquad \\Rightarrow \\qquad 0,05 = \\frac{50}{N_1} $$\n\no sea\n$$ N_1 = \\frac{50}{0,05} = 1000 \\, \\mbox{vueltas} $$\n\n__c)__\n$$ S = V_1 I_1 = V_2 I_2 = 9,6 \\, \\mathrm{kVA} $$\n\nPor lo tanto,\n$$ I_1 = \\frac{S}{V_1} = \\frac{9600}{2400} = 4 \\, \\mathrm{A} $$\n\n$$ I_2 = \\frac{S}{V_2} = \\frac{9600}{120} = 80 \\, \\mathrm{A} $$\n\n\n```python\n# Datos:\nV1 = 2400 # V\nV2 = 120 # V\nN2 = 50\nS = 9.6e3 # VA \n```\n\n\n```python\nn = V2/V1\nN1 = N2/n\nI1 = S/V1\nI2 = S/V2\n```\n\n\n```python\nprint('a) \u00edtem')\nprint('n = %.2f'%n)\nprint('b) \u00edtem')\nprint('N1 = %.0f'%N1)\nprint('c) \u00edtem')\nprint('I1 = %.1f A'%I1)\nprint('I2 = %.1f A'%I2)\n```\n\n    a) \u00edtem\n    n = 0.05\n    b) \u00edtem\n    N1 = 1000\n    c) \u00edtem\n    I1 = 4.0 A\n    I2 = 80.0 A\n\n\n\n```python\n%reset -s -f\n```\n\n## Problema de pr\u00e1ctica 13.7\nLa corriente primaria que entra a un transformador ideal con capacidad nominal de 3300/110 V es de 3 A. Calcule:\n\na) la raz\u00f3n de vueltas.\n\nb) la capacidad nominal en kVA.\n\nc) la corriente secundaria.\n\n### Soluci\u00f3n\na) \u00c9ste es un transformador reductor, ya que $V_1 = 3300 \\, \\mathrm{V} > V_2 = 110 \\, \\mathrm{V}$.\n\n$$ n = \\frac{V_2}{V_1} = \\frac{1}{30} \\cong 0,03333 $$\n\nb) Capacidad nominal en kVA\n$$ S = V_2 I_2 = V_2 \\left( \\frac{I_1}{n} \\right) = 9,9 \\, \\mathrm{kVA} $$\n\nc) Corriente secundaria\n$$ I_2 = \\frac{I_1}{n} = 90 \\, \\mathrm{A} $$\n\n\n```python\n# Datos:\nV1 = 3300 # V\nV2 =  110 # V\nI1 =    3 # A\n```\n\n\n```python\n# item a) raz\u00f3n de vueltas.\nn = V2/V1\n# item c) corriente secundaria.\nI2 = I1/n\n# item b) capacidad nominal en kVA.\nS = V2*I2\n```\n\n\n```python\nprint('a) Raz\u00f3n de vualtas:     n  = %.5f'%n)\nprint('b) Capacidad nominal:    S  = %.2f kVA'%(S/1000) )\nprint('c) Corriente secundaria: I2 = %.1f A'%I2)\n```\n\n    a) Raz\u00f3n de vualtas:     n  = 0.03333\n    b) Capacidad nominal:    S  = 9.90 kVA\n    c) Corriente secundaria: I2 = 90.0 A\n\n\n\n```python\n%reset -s -f\n```\n\n## Ejemplo 13.8\nEn referencia al circuito con transformador ideal de la figura, halle:\n1. la corriente $I_1$\n2. la tensi\u00f3n de salida $V_0$\n3. la potencia compleja suministrada por la fuente.\n\n\n\n### Soluci\u00f3n\n\n\n```python\nimport cmath\nimport numpy as np\n```\n\n\n```python\n# Datos:\nVs = 120\nZ1 = 4 - 6j # Ohm\nZ2 = 20 # Ohm\nn = 2\n```\n\n\n```python\n# a) La impedancia Z2 puede reflejarse en el lado primario\nZR = Z2/n**2\nZent = Z1 + ZR\nI1 = Vs/Zent\n# b) Puesto que tanto I1 como I2 salen de las terminales marcas\nI2 = -(1/n)*I1\nVo = I2*Z2\n# c) La potencia compleja suministrada es\nS = Vs*I1.conjugate()\n```\n\n\n```python\nprint('a) La impedancia Z2 puede reflejarse en el lado primario')\nprint('   I1 = (%.2f < %.2f\u00b0) A'%(abs(I1) , np.rad2deg( cmath.phase(I1) ) ))\nprint('b) Puesto que tanto I1 como I2 salen de las terminales marcas')\nprint('   I2 = (%.2f < %.2f\u00b0) A'%(abs(I2) , np.rad2deg( cmath.phase(I2) ) ))\nprint('   Vo = (%.2f < %.2f\u00b0) V'%(abs(Vo) , np.rad2deg( cmath.phase(Vo) ) ))\nprint('c) La potencia compleja suministrada es')\nprint('   S  = (%.2f < %.2f) VA'%(abs(S) , np.rad2deg( cmath.phase(S) )))\n```\n\n    a) La impedancia Z2 puede reflejarse en el lado primario\n       I1 = (11.09 < 33.69\u00b0) A\n    b) Puesto que tanto I1 como I2 salen de las terminales marcas\n       I2 = (5.55 < -146.31\u00b0) A\n       Vo = (110.94 < -146.31\u00b0) V\n    c) La potencia compleja suministrada es\n       S  = (1331.28 < -33.69) VA\n\n\n\n```python\n%reset -s -f\n```\n\n## Problema de pr\u00e1ctica 13.8\nEn el circuito con transformador ideal de la figura, halle $V_0$ y la potencia compleja suministrada por la fuente.\n\n\n\n### Soluci\u00f3n\n\n\n```python\nimport cmath\nimport numpy as np\n```\n\n\n```python\n# Datos:\nVs = 120 # V\nZ1 = 2 # Ohm\nZ2 = 16 - 24j # Ohm\nC1 = -24j # Ohm\nn = 4\n```\n\n\n```python\nZR = Z2/n**2\nZent = Z1 + ZR\nI1 = Vs/Zent\nI2 = -(1/n)*I1\nVo = I2*C1\nS = Vs*I1.conjugate()\n```\n\n\n```python\nprint('Vo = (%.1f < %.2f\u00b0) V'%(abs(Vo) , np.rad2deg( cmath.phase(Vo) ) ))\nprint('S  = (%.3f < %.2f) kVA'%(abs(S)/1e3 , np.rad2deg( cmath.phase(S) )))\n```\n\n    Vo = (214.7 < 116.57\u00b0) V\n    S  = (4.293 < -26.57) kVA\n\n\n\n```python\n%reset -s -f\n```\n\n## Ejemplo 13.9\nCalcule la potencia suministrada a la resistencia de $10 \\, \\Omega$ en el circuito con transformador ideal de la figura.\n\n\n\n## Soluci\u00f3n\nEn este circuito no puede realizarse el reflejo en el lado secundario o primario; hay una conexi\u00f3n directa entre los lados primario y secundario debido al resistor de $30 \\, \\Omega$. Se aplica el an\u00e1lisis de lazos.\n\nEn cuanto al lazo 1\n$$ -120 + (20 + 30)I_1 - 30I_2 + V_1 = 0  $$\n\no sea\n$$ 50 I_1 - 30 I_2 + V_1 = 120 \\tag{1} $$\n\nEn cuanto al lazo 2\n$$ -V_2 + (10 + 30)I_2 + 30I_2 = 0 $$\n\no sea\n$$ -30I_1 + 40I_2 + V_2 = 0 \\tag{2} $$\n\nEn las terminales del transformador\n\n$$ V_2 = - \\frac{1}{2} V_1 \\tag{3} $$\n\n$$ I_2 = 2 I_1 \\tag{4} $$\n\n(N\u00f3tese que $n = 1/2$) Ahora se tiene cuatro ecuaciones y cuatro inc\u00f3gnitas, pero la meta es obtener $I_2$. As\u00ed, se sustituye $V_1$ e $I_1$ en t\u00e9rminos de $V_2$ e $I_2$ en las ecuaciones (1) y (2). La ecuaci\u00f3n (1) se convierte en\n\n$$ -55 I_1 - 2 V_2 = 120 \\tag{5} $$\n\ny la ecuaci\u00f3n (2) en\n$$ 15 I_2 + 40 I_2 - V_2 = 0 $$\n\n$$ V_2 = 55 I_2 \\tag{6} $$\n\nAl sustituir la ecuaci\u00f3n (6) en la ecuaci\u00f3n (5)\n\n$$ -165 I_2 = 120 $$\n\n$$ I_2 = - \\frac{120}{165} = - 0,7272 \\, \\mathrm{A} $$\n\nLa potencia absorbida por la resistencia de $10 \\, \\Omega$ es\n\n$$ P = I_2^2 Z_2 = 5,3 \\, \\mathrm{W} $$\n\n\n```python\n# Datos:\nVs = 120 # V (rms)\nZ1 = 20 # Ohm\nZ2 = 10 # Ohm\nR1 = 30 # Ohm\n```\n\nEn forma matricial\n\n$$\\left[\n\\begin{array}{cccc}\n50 & - 30 & 1 & 0 \\\\\n-30 & 40 & 0 & 1 \\\\\n0 & 0 & -1/2 & 1 \\\\\n2 & 1 & 0 & 0 \\\\\n\\end{array}\n\\right]\n\\left[\n\\begin{array}{c}\nI_1 \\\\\nI_2 \\\\\nV_1 \\\\\nV_2 \\\\\n\\end{array}\n\\right]\n=\n\\left[\n\\begin{array}{c}\n120 \\\\\n0 \\\\\n0 \\\\\n0 \\\\\n\\end{array}\n\\right]$$\n\n$$ A I = B $$\n\nEntonces\n$$ I = A^{-1} B $$\n\n### Usando numpy\n\n\n```python\nimport numpy as np\nimport cmath\n```\n\n\n```python\nA = np.array([[50,-30,1,0],[-30,40,0,1],[0,0,-1/2,1],[2,1,0,0]])\nB = np.array([[120],[0],[0],[0]])\n```\n\n\n```python\nI = np.dot( np.linalg.inv(A) , B )\n```\n\n\n```python\nI1 = I[0] ; I2 = I[1]\nP = I2**2 * Z2\n```\n\n\n```python\nprint('I1 = %.4f A'%I[0])\nprint('I2 = %.4f A'%I[1])\nprint('P = %.2f W'%P)\n```\n\n    I1 = 0.3636 A\n    I2 = -0.7273 A\n    P = 5.29 W\n\n\n### Usando sympy\n\n\n```python\nimport sympy as sp\n```\n\n\n```python\nM = sp.Matrix([[50,-30,1,0,120],[-30,40,0,1,0],[0,0,-1/2,1,0],[2,1,0,0,0]])\nM\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}50 & -30 & 1 & 0 & 120\\\\-30 & 40 & 0 & 1 & 0\\\\0 & 0 & -0.5 & 1 & 0\\\\2 & 1 & 0 & 0 & 0\\end{matrix}\\right]$\n\n\n\n\n```python\nS = M.rref()\nSol = S[0]\n```\n\n\n```python\nSol\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 0 & 0 & 0 & 0.363636363636364\\\\0 & 1 & 0 & 0 & -0.727272727272727\\\\0 & 0 & 1 & 0 & 80.0\\\\0 & 0 & 0 & 1 & 40.0\\end{matrix}\\right]$\n\n\n\n\n```python\nI1 = Sol[0,4]\nI2 = Sol[1,4]\nV1 = Sol[2,4]\nV2 = Sol[3,4]\n```\n\n\n```python\n%reset -s -f\n```\n\n<a href=\"https://colab.research.google.com/github/daniel-lorenzo/Electrotecnia/blob/master/Transformadores_ideales.ipynb\"></a>\n", "meta": {"hexsha": "61da30c45538c7d729245d9ca7f8747589dac4a1", "size": 36870, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Transformadores_ideales.ipynb", "max_stars_repo_name": "daniel-lorenzo/Electrotecnia", "max_stars_repo_head_hexsha": "c9441dd58c84a635954e85b755bdd2c47b09c589", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-16T16:46:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T16:46:27.000Z", "max_issues_repo_path": "Transformadores_ideales.ipynb", "max_issues_repo_name": "daniel-lorenzo/Electrotecnia", "max_issues_repo_head_hexsha": "c9441dd58c84a635954e85b755bdd2c47b09c589", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Transformadores_ideales.ipynb", "max_forks_repo_name": "daniel-lorenzo/Electrotecnia", "max_forks_repo_head_hexsha": "c9441dd58c84a635954e85b755bdd2c47b09c589", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-04T00:08:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T00:08:57.000Z", "avg_line_length": 26.6787264834, "max_line_length": 870, "alphanum_fraction": 0.549660971, "converted": true, "num_tokens": 6992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022539259558657, "lm_q2_score": 0.10669058897496682, "lm_q1q2_score": 0.03949956518951145}}
{"text": "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Ki\u1ec3m-so\u00e1t-Th\u1ee9-m\u00e0-b\u1ea1n-Kh\u00f4ng-th\u1ea5y\" data-toc-modified-id=\"Ki\u1ec3m-so\u00e1t-Th\u1ee9-m\u00e0-b\u1ea1n-Kh\u00f4ng-th\u1ea5y-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Ki\u1ec3m so\u00e1t Th\u1ee9 m\u00e0 b\u1ea1n Kh\u00f4ng th\u1ea5y</a></span></li><li><span><a href=\"#Hi\u1ec7u \u1ee8ng C\u1ed1 \u0110\u1ecbnh\" data-toc-modified-id=\"Hi\u1ec7u \u1ee8ng C\u1ed1 \u0110\u1ecbnh-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Hi\u1ec7u \u1ee8ng C\u1ed1 \u0110\u1ecbnh</a></span></li><li><span><a href=\"#Bi\u1ec3u-di\u1ec5n-Hi\u1ec7u \u1ee8ng C\u1ed1 \u0110\u1ecbnh\" data-toc-modified-id=\"Bi\u1ec3u-di\u1ec5n-Hi\u1ec7u \u1ee8ng C\u1ed1 \u0110\u1ecbnh-3\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>Bi\u1ec3u di\u1ec5n Hi\u1ec7u \u1ee8ng C\u1ed1 \u0110\u1ecbnh</a></span></li><li><span><a href=\"#Hi\u1ec7u-\u1ee9ng-th\u1eddi-gian\" data-toc-modified-id=\"Hi\u1ec7u-\u1ee9ng-th\u1eddi-gian-4\"><span class=\"toc-item-num\">4&nbsp;&nbsp;</span>Hi\u1ec7u \u1ee9ng th\u1eddi gian</a></span></li><li><span><a href=\"#Khi-D\u1eef Li\u1ec7u B\u1ea3ng-Kh\u00f4ng-th\u1ec3-Gi\u00fap-b\u1ea1n\" data-toc-modified-id=\"Khi-D\u1eef Li\u1ec7u B\u1ea3ng-Kh\u00f4ng-th\u1ec3-Gi\u00fap-b\u1ea1n-5\"><span class=\"toc-item-num\">5&nbsp;&nbsp;</span>Khi D\u1eef Li\u1ec7u B\u1ea3ng Kh\u00f4ng th\u1ec3 Gi\u00fap b\u1ea1n</a></span></li><li><span><a href=\"#\u00dd-t\u01b0\u1edfng-ch\u1ee7-\u0111\u1ea1o\" data-toc-modified-id=\"\u00dd-t\u01b0\u1edfng-ch\u1ee7-\u0111\u1ea1o-6\"><span class=\"toc-item-num\">6&nbsp;&nbsp;</span>\u00dd t\u01b0\u1edfng ch\u1ee7 \u0111\u1ea1o</a></span></li><li><span><a href=\"#T\u00e0i-li\u1ec7u-tham-kh\u1ea3o\" data-toc-modified-id=\"T\u00e0i-li\u1ec7u-tham-kh\u1ea3o-7\"><span class=\"toc-item-num\">7&nbsp;&nbsp;</span>T\u00e0i li\u1ec7u tham kh\u1ea3o</a></span></li></ul></div>\n\n## Ki\u1ec3m so\u00e1t \u0110i\u1ec1u m\u00e0 b\u1ea1n Kh\u00f4ng th\u1ea5y\nC\u00e1c ph\u01b0\u01a1ng ph\u00e1p nh\u01b0 \u0111i\u1ec3m xu h\u01b0\u1edbng, h\u1ed3i quy tuy\u1ebfn t\u00ednh v\u00e0 gh\u00e9p c\u1eb7p r\u1ea5t t\u1ed1t \u0111\u1ec3 ki\u1ec3m so\u00e1t nhi\u1ec5u khi s\u1eed d\u1ee5ng d\u1eef li\u1ec7u kh\u00f4ng ng\u1eabu nhi\u00ean, nh\u01b0ng ch\u00fang l\u1ec7 thu\u1ed9c v\u00e0o m\u1ed9t gi\u1ea3 thi\u1ebft quan tr\u1ecdng: kh\u00f4ng nhi\u1ec5u c\u00f3 \u0111i\u1ec1u ki\u1ec7n:\n\n$\n(Y_0, Y_1) \\perp T | X\n$\n\nNgh\u0129a l\u00e0 ch\u00fang \u0111\u00f2i h\u1ecfi t\u1ea5t c\u1ea3 c\u00e1c bi\u1ebfn nhi\u1ec5u \u0111\u1ec1u \u0111\u00e3 \u0111\u01b0\u1ee3c bi\u1ebft v\u00e0 \u0111o l\u01b0\u1eddng, v\u00ec th\u1ebf ch\u00fang ta c\u00f3 th\u1ec3 c\u1ed1 \u0111\u1ecbnh ch\u00fang v\u00e0 khi\u1ebfn can thi\u1ec7p t\u1ed1t nh\u01b0 th\u1ec3 ng\u1eabu nhi\u00ean. Th\u00e1ch th\u1ee9c ch\u00ednh v\u1edbi \u0111i\u1ec1u n\u00e0y l\u00e0 \u0111\u00f4i khi ch\u00fang ta kh\u00f4ng th\u1ec3 \u0111o l\u01b0\u1eddng m\u1ed9t bi\u1ebfn nhi\u1ec5u n\u00e0o \u0111\u00f3. V\u00ed d\u1ee5, trong m\u1ed9t b\u00e0i to\u00e1n kinh t\u1ebf lao \u0111\u1ed9ng c\u1ed5 \u0111i\u1ec3n: \u01b0\u1edbc l\u01b0\u1ee3ng t\u00e1c \u0111\u1ed9ng thu nh\u1eadp c\u1ee7a h\u00f4n nh\u00e2n \u0111\u1ed1i v\u1edbi nam gi\u1edbi. M\u1ed9t s\u1ef1 th\u1eadt \u0111\u01b0\u1ee3c bi\u1ebft r\u1ed9ng r\u00e3i trong Kinh t\u1ebf h\u1ecdc l\u00e0 nam gi\u1edbi \u0111\u00e3 l\u1eadp gia \u0111\u00ecnh c\u00f3 thu nh\u1eadp cao h\u01a1n nam gi\u1edbi \u0111\u1ed9c th\u00e2n. \u0110i\u1ec1u c\u00f2n ch\u01b0a s\u00e1ng t\u1ecf l\u00e0 li\u1ec7u m\u1ed1i quan h\u1ec7 n\u00e0y c\u00f3 t\u00ednh nh\u00e2n qu\u1ea3 hay kh\u00f4ng. C\u00f3 th\u1ec3 do nh\u1eefng ng\u01b0\u1eddi c\u00f3 h\u1ecdc v\u1ea5n t\u1ed1t th\u01b0\u1eddng d\u1ec5 k\u1ebft h\u00f4n v\u00e0 \u0111\u1ed3ng th\u1eddi c\u00f3 thu nh\u1eadp t\u1ed1t h\u01a1n, ngh\u0129a l\u00e0 h\u1ecdc v\u1ea5n l\u00e0 m\u1ed9t bi\u1ebfn nhi\u1ec5u c\u1ee7a t\u00e1c \u0111\u1ed9ng \u0111\u1ed1i v\u1edbi thu nh\u1eadp c\u1ee7a h\u00f4n nh\u00e2n. \u00dd th\u1ee9c \u0111\u01b0\u1ee3c y\u1ebfu t\u1ed1 g\u00e2y nhi\u1ec5u n\u00e0y, ch\u00fang ta c\u00f3 th\u1ec3 \u0111o l\u01b0\u1eddng h\u1ecdc v\u1ea5n c\u1ee7a c\u00e1c c\u00e1 nh\u00e2n tham gia nghi\u00ean c\u1ee9u v\u00e0 ch\u1ea1y m\u1ed9t m\u00f4 h\u00ecnh h\u1ed3i quy ki\u1ec3m so\u00e1t n\u00f3. Nh\u01b0ng m\u1ed9t bi\u1ebfn nhi\u1ec5u ti\u1ec1m n\u0103ng kh\u00e1c l\u00e0 \u0111\u1ed9 \u0111i\u1ec3n trai. C\u00f3 kh\u1ea3 n\u0103ng nh\u1eefng ng\u01b0\u1eddi \u0111i\u1ec3n trai d\u1ec5 k\u1ebft h\u00f4n v\u00e0 c\u0169ng d\u1ec5 ki\u1ebfm \u0111\u01b0\u1ee3c c\u00f4ng vi\u1ec7c thu nh\u1eadp t\u1ed1t. \u0110\u00e1ng ti\u1ebfc l\u00e0 \u0111\u1ed9 \u0111i\u1ec3n trai kh\u00f4ng ph\u1ea3i m\u1ed9t \u0111\u1eb7c t\u00ednh ki\u1ec3u nh\u01b0 tr\u00ed tu\u1ec7. N\u00f3 kh\u00f4ng h\u1ec1 d\u1ec5 \u0111\u1ecbnh l\u01b0\u1ee3ng ch\u00fat n\u00e0o.  \n\n\u0110i\u1ec1u n\u00e0y \u0111\u1eb7t ch\u00fang ta v\u00e0o m\u1ed9t t\u00ecnh th\u1ebf r\u1ea5t kh\u00f3 kh\u0103n, v\u00ec n\u1ebfu ch\u00fang ta c\u00f3 nh\u1eefng bi\u1ec5n nhi\u1ec5u kh\u00f4ng \u0111\u01b0\u1ee3c \u0111o l\u01b0\u1eddng, ch\u00fang ta c\u00f3 thi\u00ean l\u1ec7ch. M\u1ed9t gi\u1ea3i ph\u00e1p l\u00e0 s\u1eed d\u1ee5ng bi\u1ebfn c\u00f4ng c\u1ee5, gi\u1ed1ng nh\u01b0 ch\u00fang ta \u0111\u00e3 th\u1ea5y trong b\u00e0i tr\u01b0\u1edbc. Nh\u01b0ng t\u00ecm ra bi\u1ebfn c\u00f4ng c\u1ee5 t\u1ed1t kh\u00f4ng d\u1ec5 v\u00e0 \u0111\u00f2i h\u1ecfi r\u1ea5t nhi\u1ec1u s\u1ef1 s\u00e1ng t\u1ea1o. \u1ede \u0111\u00e2y ch\u00fang ta s\u1ebd t\u00ecm hi\u1ec3u m\u1ed9t bi\u1ec7n ph\u00e1p kh\u00e1c t\u1eadn d\u1ee5ng y\u1ebfu t\u1ed1 th\u1eddi gian v\u00e0 c\u1ea5u tr\u00fac th\u1eddi gian c\u1ee7a d\u1eef li\u1ec7u. \n\n\u00dd t\u01b0\u1edfng l\u00e0 s\u1eed d\u1ee5ng **d\u1eef li\u1ec7u b\u1ea3ng**. D\u1eef li\u1ec7u b\u1ea3ng l\u00e0 khi ta c\u00f3 **nhi\u1ec1u quan s\u00e1t cho c\u00f9ng m\u1ed9t \u0111\u1ed1i t\u01b0\u1ee3ng trong nhi\u1ec1u kho\u1ea3ng th\u1eddi gian kh\u00e1c nhau**. D\u1eef li\u1ec7u b\u1ea3ng r\u1ea5t ph\u1ed5 bi\u1ebfn trong kinh doanh, n\u01a1i m\u00e0 ng\u01b0\u1eddi ta l\u01b0u gi\u1eef c\u00e1c b\u1ea3n ghi v\u1ec1 h\u00e0nh vi ti\u00eau d\u00f9ng c\u1ee7a c\u00f9ng m\u1ed9t kh\u00e1ch h\u00e0ng t\u1ea1i nhi\u1ec1u th\u1eddi \u0111i\u1ec3m. L\u00fd do \u0111\u1ec3 ta s\u1eed d\u1ee5ng d\u1eef li\u1ec7u b\u1ea3ng l\u00e0 v\u00ec n\u00f3 cho ph\u00e9p ta so s\u00e1nh c\u00f9ng m\u1ed9t \u0111\u1ed1i t\u01b0\u1ee3ng tr\u01b0\u1edbc v\u00e0 sau can thi\u1ec7p v\u00e0 theo d\u00f5i h\u00e0nh vi c\u1ee7a h\u1ecd. Tr\u01b0\u1edbc khi \u0111i s\u00e2u v\u00e0o c\u00e1c c\u00f4ng th\u1ee9c to\u00e1n, h\u00e3y xem n\u00f3 c\u00f3 \u00fd ngh\u0129a tr\u1ef1c quan nh\u01b0 th\u1ebf n\u00e0o.\n\n\n```python\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import style\nfrom matplotlib import pyplot as plt\nimport statsmodels.formula.api as smf\nimport graphviz as gr\n\nfrom linearmodels.panel import PanelOLS\n\n\n%matplotlib inline\npd.set_option(\"display.max_columns\", 6)\nstyle.use(\"fivethirtyeight\")\n```\n\nTr\u01b0\u1edbc h\u1ebft, h\u00e3y nh\u00ecn v\u00e0o \u0111\u1ed3 th\u1ecb nh\u00e2n qu\u1ea3 m\u00e0 ch\u00fang ta \u0111\u00e3 x\u00e2y d\u1ef1ng cho nhi\u1ec1u quan s\u00e1t c\u1ee7a c\u00f9ng m\u1ed9t \u0111\u1ed1i t\u01b0\u1ee3ng theo th\u1eddi gian. Gi\u1ea3 s\u1eed ch\u00fang ta c\u00f3 t\u00ecnh hu\u1ed1ng m\u00e0 t\u00ecnh tr\u1ea1ng h\u00f4n nh\u00e2n t\u1ea1i th\u1eddi \u0111i\u1ec3m 1 chi ph\u1ed1i thu nh\u1eadp \u1edf c\u00f9ng th\u1eddi \u0111i\u1ec3m v\u00e0 t\u00ecnh tr\u1ea1ng h\u00f4n nh\u00e2n ngay sau \u0111\u00f3. \u0110i\u1ec1u n\u00e0y c\u0169ng \u00e1p d\u1ee5ng cho th\u1eddi \u0111i\u1ec3m 2 v\u00e0 3. V\u00e0 gi\u1ea3 s\u1eed \u0111\u1ed9 \u0111i\u1ec3n trai l\u00e0 nh\u01b0 nhau \u1edf c\u00e1c th\u1eddi \u0111i\u1ec3m (gi\u1ea3 \u0111\u1ecbnh n\u00e0y qu\u00e1 c\u1ee9ng nh\u1eafc, nh\u01b0ng c\u00f3 th\u1ec3 ph\u00f9 h\u1ee3p n\u1ebfu kho\u1ea3ng c\u00e1ch th\u1eddi gian \u0111\u1ee7 ng\u1eafn v\u00ed d\u1ee5 m\u1ed9t v\u00e0i n\u0103m) v\u00e0 n\u00f3 chi ph\u1ed1i c\u1ea3 t\u00ecnh tr\u1ea1ng h\u00f4n nh\u00e2n l\u1eabn thu nh\u1eadp.\n\n\n\n```python\ng = gr.Digraph()\ng.edge(\"K\u1ebft_h\u00f4n_1\", \"Thu_nh\u1eadp_1\")\ng.edge(\"K\u1ebft_h\u00f4n_1\", \"K\u1ebft_h\u00f4n_2\")\ng.edge(\"K\u1ebft_h\u00f4n_2\", \"Thu_nh\u1eadp_2\")\ng.edge(\"K\u1ebft_h\u00f4n_2\", \"K\u1ebft_h\u00f4n_3\")\ng.edge(\"K\u1ebft_h\u00f4n_3\", \"Thu_nh\u1eadp_3\")\n\ng.edge(\"\u0110i\u1ec3n_trai\", \"K\u1ebft_h\u00f4n_1\")\ng.edge(\"\u0110i\u1ec3n_trai\", \"K\u1ebft_h\u00f4n_2\")\ng.edge(\"\u0110i\u1ec3n_trai\", \"K\u1ebft_h\u00f4n_3\")\n\ng.edge(\"\u0110i\u1ec3n_trai\", \"Thu_nh\u1eadp_1\")\ng.edge(\"\u0110i\u1ec3n_trai\", \"Thu_nh\u1eadp_2\")\ng.edge(\"\u0110i\u1ec3n_trai\", \"Thu_nh\u1eadp_3\")\n\ng\n```\n\n\n\n\n    \n\n    \n\n\n\nL\u01b0u \u00fd l\u00e0 ch\u00fang ta kh\u00f4ng th\u1ec3 ki\u1ec3m so\u00e1t \u0111\u1ed9 \u0111i\u1ec3n trai v\u00ec ch\u00fang ta kh\u00f4ng th\u1ec3 l\u01b0\u1ee3ng h\u00f3a n\u00f3. Nh\u01b0ng ch\u00fang ta v\u1eabn c\u00f3 th\u1ec3 s\u1eed d\u1ee5ng c\u1ea5u tr\u00fac b\u1ea3ng v\u00e0 y\u1ebfu t\u1ed1 n\u00e0y kh\u00f4ng c\u00f2n l\u00e0 tr\u1edf ng\u1ea1i n\u1eefa. \u00dd t\u01b0\u1edfng l\u00e0 ch\u00fang ta c\u00f3 th\u1ec3 th\u1ea5y \u0111\u1ed9 \u0111i\u1ec3n trai - c\u0169ng nh\u01b0 nhi\u1ec1u \u0111\u1eb7c \u0111i\u1ec3m kh\u00e1c kh\u00f4ng thay \u0111\u1ed5i theo th\u1eddi gian nh\u01b0 c\u00e1c \u0111\u1eb7c t\u00ednh c\u1ee7a m\u1ed9t ng\u01b0\u1eddi. V\u00e0 m\u1eb7c d\u00f9 ch\u00fang ta kh\u00f4ng th\u1ec3 ki\u1ec3m so\u00e1t c\u00e1c \u0111\u1eb7c t\u00ednh n\u00e0y m\u1ed9t c\u00e1ch tr\u1ef1c ti\u1ebfp, ch\u00fang ta c\u00f3 th\u1ec3 ki\u1ec3m so\u00e1t lu\u00f4n b\u1ea3n th\u00e2n \u0111\u1ed1i t\u01b0\u1ee3ng \u0111\u01b0\u1ee3c nghi\u00ean c\u1ee9u.\n\n\n```python\ng = gr.Digraph()\ng.edge(\"K\u1ebft_h\u00f4n_1\", \"Thu_nh\u1eadp_1\")\ng.edge(\"K\u1ebft_h\u00f4n_1\", \"K\u1ebft_h\u00f4n_2\")\ng.edge(\"K\u1ebft_h\u00f4n_2\", \"Thu_nh\u1eadp_2\")\ng.edge(\"K\u1ebft_h\u00f4n_2\", \"K\u1ebft_h\u00f4n_3\")\ng.edge(\"K\u1ebft_h\u00f4n_3\", \"Thu_nh\u1eadp_3\")\n\ng.edge(\"\u0110\u1ed1i t\u01b0\u1ee3ng (\u0110i\u1ec3n trai, Tr\u00ed tu\u1ec7...)\", \"K\u1ebft_h\u00f4n_1\")\ng.edge(\"\u0110\u1ed1i t\u01b0\u1ee3ng (\u0110i\u1ec3n trai, Tr\u00ed tu\u1ec7...)\", \"K\u1ebft_h\u00f4n_2\")\ng.edge(\"\u0110\u1ed1i t\u01b0\u1ee3ng (\u0110i\u1ec3n trai, Tr\u00ed tu\u1ec7...)\", \"K\u1ebft_h\u00f4n_3\")\n\ng.edge(\"\u0110\u1ed1i t\u01b0\u1ee3ng (\u0110i\u1ec3n trai, Tr\u00ed tu\u1ec7...)\", \"Thu_nh\u1eadp_1\")\ng.edge(\"\u0110\u1ed1i t\u01b0\u1ee3ng (\u0110i\u1ec3n trai, Tr\u00ed tu\u1ec7...)\", \"Thu_nh\u1eadp_2\")\ng.edge(\"\u0110\u1ed1i t\u01b0\u1ee3ng (\u0110i\u1ec3n trai, Tr\u00ed tu\u1ec7...)\", \"Thu_nh\u1eadp_3\")\n\ng\n```\n\n\n\n\n    \n\n    \n\n\n\nTh\u1eed ngh\u0129 xem. Ch\u00fang ta kh\u00f4ng bi\u1ebft c\u00e1c \u0111\u1eb7c t\u00ednh nh\u01b0 \u0111i\u1ec3n trai, tr\u00ed tu\u1ec7, nh\u01b0ng ch\u00fang ta bi\u1ebft ch\u00fang c\u00f9ng thu\u1ed9c v\u1ec1 m\u1ed9t ng\u01b0\u1eddi. V\u00ec th\u1ebf, ch\u00fang t\u1ea1o ra m\u1ed9t bi\u1ebfn gi\u1ea3 \u0111\u1ec3 x\u00e1c \u0111\u1ecbnh ng\u01b0\u1eddi \u0111\u00f3 v\u00e0 \u0111\u01b0a n\u00f3 v\u00e0o m\u1ed9t m\u00f4 h\u00ecnh tuy\u1ebfn t\u00ednh. \u0110\u00e2y l\u00e0 \u0111i\u1ec1u ch\u00fang ta nh\u1eafc t\u1edbi \u1edf tr\u00ean khi ch\u00fang ta ki\u1ec3m so\u00e1t \u0111\u1ed1i t\u01b0\u1ee3ng \u0111\u01b0\u1ee3c nghi\u00ean c\u1ee9u. Khi \u01b0\u1edbc l\u01b0\u1ee3ng t\u00e1c \u0111\u1ed9ng c\u1ee7a h\u00f4n nh\u00e2n \u0111\u1ed1i v\u1edbi thu nh\u1eadp s\u1eed d\u1ee5ng bi\u1ebfn gi\u1ea3 ch\u1ec9 ng\u01b0\u1eddi trong m\u00f4 h\u00ecnh c\u1ee7a ch\u00fang ta, m\u00f4 h\u00ecnh h\u1ed3i quy s\u1ebd x\u00e1c \u0111\u1ecbnh t\u00e1c \u0111\u1ed9ng c\u1ee7a h\u00f4n nh\u00e2n khi **gi\u1eef c\u1ed1 \u0111\u1ecbnh ng\u01b0\u1eddi \u0111\u01b0\u1ee3c nghi\u00ean c\u1ee9u**. Vi\u1ec7c th\u00eam v\u00e0o bi\u1ebfn gi\u1ea3 n\u00e0y \u0111\u01b0\u1ee3c g\u1ecdi l\u00e0 m\u00f4 h\u00ecnh hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh.\n\n## Hi\u1ec7u \u1ee8ng C\u1ed1 \u0110\u1ecbnh\n\n\u0110\u1ec3 m\u00f4 t\u1ea3 v\u1ea5n \u0111\u1ec1 b\u1eb1ng c\u00f4ng th\u1ee9c to\u00e1n h\u1ecdc, tr\u01b0\u1edbc h\u1ebft h\u00e3y nh\u00ecn v\u00e0o d\u1eef li\u1ec7u m\u00e0 ch\u00fang ta c\u00f3. Trong v\u00ed d\u1ee5 tr\u00ean, ch\u00fang ta mu\u1ed1n \u01b0\u1edbc l\u01b0\u1ee3ng t\u00e1c \u0111\u1ed9ng c\u1ee7a h\u00f4n nh\u00e2n \u0111\u1ed1i v\u1edbi thu nh\u1eadp. D\u1eef li\u1ec7u g\u1ed3m 2 bi\u1ebfn `k\u1ebft_h\u00f4n` v\u00e0 `log_l\u01b0\u01a1ng`, cho nhi\u1ec1u \u0111\u1ed1i t\u01b0\u1ee3ng (`nr`) qua nhi\u1ec1u n\u0103m. L\u01b0u \u00fd l\u00e0 ti\u1ec1n l\u01b0\u01a1ng \u0111\u00e3 \u0111\u01b0\u1ee3c l\u1ea5y log. Th\u00eam v\u00e0o \u0111\u00f3, ch\u00fang ta \u0111\u01b0a v\u00e0o c\u00e1c bi\u1ebfn ki\u1ec3m so\u00e1t kh\u00e1c nh\u01b0 s\u1ed1 gi\u1edd l\u00e0m vi\u1ec7c m\u1ed7i n\u0103m, s\u1ed1 n\u0103m h\u1ecdc v\u1ea5n,...\n\n\n```python\nfrom linearmodels.datasets import wage_panel\ndata = wage_panel.load()\ndata.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>nr</th>\n      <th>year</th>\n      <th>black</th>\n      <th>...</th>\n      <th>lwage</th>\n      <th>expersq</th>\n      <th>occupation</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>13</td>\n      <td>1980</td>\n      <td>0</td>\n      <td>...</td>\n      <td>1.197540</td>\n      <td>1</td>\n      <td>9</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>13</td>\n      <td>1981</td>\n      <td>0</td>\n      <td>...</td>\n      <td>1.853060</td>\n      <td>4</td>\n      <td>9</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>13</td>\n      <td>1982</td>\n      <td>0</td>\n      <td>...</td>\n      <td>1.344462</td>\n      <td>9</td>\n      <td>9</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>13</td>\n      <td>1983</td>\n      <td>0</td>\n      <td>...</td>\n      <td>1.433213</td>\n      <td>16</td>\n      <td>9</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>13</td>\n      <td>1984</td>\n      <td>0</td>\n      <td>...</td>\n      <td>1.568125</td>\n      <td>25</td>\n      <td>5</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 12 columns</p>\n</div>\n\n\n\nGenerally, the fixed effect model is defined as\n\n$\ny_{it} = \\beta X_{it} + \\gamma U_i + e_{it}\n$\n\nwhere \\\\(y_{it}\\\\) is the outcome of individual \\\\(i\\\\) at time \\\\(t\\\\), \\\\(X_{it}\\\\) is the vector of variables for individual \\\\(i\\\\) at time \\\\(t\\\\), \\\\(U_i\\\\) is a set of unobservables for individual \\\\(i\\\\) that are unchanging through time, hence the lack of the time subscript, and \\\\(e_{it}\\\\) is the error term. For the education example, \\\\(y_{it}\\\\) is log wages,  \\\\(X_{it}\\\\) are the observable variables that change in time, like marriage and experience and \\\\(U_i\\\\) are the variables that are not observed but constant for each individual, like beauty and intelligence. \n\n\nNow, remember how I've said that using panel data with a fixed effect model is as simple as adding a dummy for the entities. It's true, but in practice, we don't actually do it. Imagine a dataset where we have 1 million customers. If we add one dummy for each of them, we would end up with 1 million columns, which is probably not a good idea. Instead, we use the trick of partitioning the linear regression into 2 separate models. We've seen this before, but now is a good time to recap it. Suppose you have a linear regression model with a set of features \\\\(X_1\\\\) and another set of features \\\\(X_2\\\\).\n\n$\n\\hat{Y} = \\hat{\\beta_1} X_1 + \\hat{\\beta_2} X_2\n$\n\nYou can get the exact same \\\\(\\hat{\\beta_1}\\\\) parameter by doing\n\n1. regress the the outcome \\\\(y\\\\) on the second set of features \\\\(\\hat{y^*} = \\hat{\\gamma_1} X_2\\\\)\n2. regress the first set of features on the second \\\\(\\hat{X_1} = \\hat{\\gamma_2} X_2\\\\)\n3. obtain the residuals \\\\(\\tilde{X}_1 = X_1 - \\hat{X_1}\\\\) and \\\\(\\tilde{y}_1 = y_1 - \\hat{y^*}\\\\)\n4. regress the residuals of the outcome on the residuals of the features \\\\(\\hat{y} = \\hat{\\beta_1} \\tilde{X}_1\\\\)\n\nThe parameter from this last regression will be exactly the same as running the regression with all the features. But how exactly does this help us? Well, we can break the estimation of the model with the entity dummies into 2. First, we use the dummies to predict the outcome and the feature. These are steps 1 and 2 above. \n\nNow, remember how running a regression on a dummy variable is as simple as estimating the mean for that dummy? If you don't, let's use our data to show how this is true. Let's run a model where we predict wages as a function of the year dummy. \n\nTh\u00f4ng th\u01b0\u1eddng m\u00f4 h\u00ecnh hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh \u0111\u01b0\u1ee3c m\u00f4 t\u1ea3 nh\u01b0 sau:\n\n$\ny_{it} = \\beta X_{it} + \\gamma U_i + e_{it}\n$\n\ntrong \u0111\u00f3 \\\\(y_{it}\\\\) l\u00e0 k\u1ebft qu\u1ea3 c\u1ee7a c\u00e1 nh\u00e2n \\\\(i\\\\) t\u1ea1i th\u1eddi \u0111i\u1ec3m \\\\(t\\\\), \\\\(X_{it}\\\\) l\u00e0 v\u00e9c-t\u01a1  ch\u1ee9a c\u00e1c bi\u1ebfn s\u1ed1 c\u1ee7a c\u00e1 nh\u00e2n \\\\(i\\\\) t\u1ea1i th\u1eddi \u0111i\u1ec3m \\\\(t\\\\), \\\\(U_i\\\\) l\u00e0 c\u00e1c bi\u1ebfn kh\u00f4ng quan s\u00e1t \u0111\u01b0\u1ee3c kh\u00f4ng \u0111\u1ed5i theo th\u1eddi gian c\u1ee7a c\u00e1 nh\u00e2n \\\\(i\\\\)  (v\u00ec th\u1ebf kh\u00f4ng c\u00f3 ch\u1ec9 s\u1ed1 th\u1eddi gian), v\u00e0 \\\\(e_{it}\\\\) l\u00e0 ph\u1ea7n d\u01b0. Trong v\u00ed d\u1ee5 v\u1ec1 gi\u00e1o d\u1ee5c, \\\\(y_{it}\\\\) l\u00e0 log ti\u1ec1n l\u01b0\u01a1ng,  \\\\(X_{it}\\\\) l\u00e0 c\u00e1c bi\u1ebfn quan s\u00e1t \u0111\u01b0\u1ee3c thay \u0111\u1ed5i theo th\u1eddi gian, nh\u01b0 t\u00ecnh tr\u1ea1ng h\u00f4n nh\u00e2n v\u00e0 kinh nghi\u1ec7m v\u00e0 \\\\(U_i\\\\) l\u00e0 c\u00e1c bi\u1ebfn kh\u00f4ng \u0111\u01b0\u1ee3c quan s\u00e1t nh\u01b0ng kh\u00f4ng \u0111\u1ed5i cho m\u1ed7i c\u00e1 nh\u00e2n, nh\u01b0 v\u1ebb \u0111i\u1ec3n trai v\u00e0 tr\u00ed tu\u1ec7. \n\nN\u00e0o h\u00e3y nh\u1edb l\u1ea1i nh\u1eefng g\u00ec t\u00f4i \u0111\u00e3 n\u00f3i. S\u1eed d\u1ee5ng d\u1eef li\u1ec7u b\u1ea3ng v\u1edbi m\u00f4 h\u00ecnh hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh \u0111\u01a1n gi\u1ea3n gi\u1ed1ng nh\u01b0 \u0111\u01b0a v\u00e0o m\u00f4 h\u00ecnh c\u00e1c bi\u1ebfn gi\u1ea3 cho c\u00e1c \u0111\u1ed1i t\u01b0\u1ee3ng. \u0110i\u1ec1u n\u00e0y \u0111\u00fang, nh\u01b0ng trong th\u1ef1c t\u1ebf, ch\u00fang ta th\u01b0\u1eddng kh\u00f4ng l\u00e0m v\u1eady. H\u00e3y t\u01b0\u1edfng t\u01b0\u1ee3ng m\u1ed9t b\u1ed9 d\u1eef li\u1ec7u v\u1edbi 1 tri\u1ec7u kh\u00e1ch h\u00e0ng. N\u1ebfu ch\u00fang ta \u0111\u01b0a th\u00eam 1 bi\u1ebfn gi\u1ea3 cho m\u1ed7i kh\u00e1ch h\u00e0ng, ch\u00fang ta s\u1ebd ph\u1ea3i t\u1ea1o th\u00eam 1 tri\u1ec7u c\u1ed9t d\u1eef li\u1ec7u n\u1eefa, v\u00e0 \u0111\u00f3 kh\u00f4ng ph\u1ea3i \u00fd hay. Thay v\u00e0o \u0111\u00f3, ch\u00fang ta s\u1ebd s\u1eed d\u1ee5ng m\u1ed9t m\u1eb9o, ph\u00e2n t\u00e1ch m\u00f4 h\u00ecnh h\u1ed3i quy tuy\u1ebfn t\u00ednh th\u00e0nh 2 m\u00f4 h\u00ecnh. Ch\u00fang ta t\u1eebng nh\u00ecn th\u1ea5y n\u00f3 tr\u01b0\u1edbc \u0111\u00e2y, nh\u01b0ng b\u00e2y gi\u1edd l\u00e0 l\u00fac th\u00edch h\u1ee3p \u0111\u1ec3 \u00f4n l\u1ea1i. Gi\u1ea3 s\u1eed b\u1ea1n c\u00f3 m\u1ed9t m\u00f4 h\u00ecnh h\u1ed3i quy tuy\u1ebfn t\u00ednh v\u1edbi m\u1ed9t nh\u00f3m c\u00e1c thu\u1ed9c t\u00ednh \\\\(X_1\\\\) v\u00e0 m\u1ed9t nh\u00f3m c\u00e1c thu\u1ed9c t\u00ednh kh\u00e1c \\\\(X_2\\\\).\n\n$\n\\hat{Y} = \\hat{\\beta_1} X_1 + \\hat{\\beta_2} X_2\n$\n\nB\u1ea1n c\u00f3 th\u1ec3 thu \u0111\u01b0\u1ee3c gi\u00e1 tr\u1ecb ch\u00ednh x\u00e1c c\u1ee7a \\\\(\\hat{\\beta_1}\\\\) b\u1eb1ng c\u00e1ch:\n\n1. h\u1ed3i quy k\u1ebft qu\u1ea3 \\\\(y\\\\) theo nh\u00f3m c\u00e1c thu\u1ed9c t\u00ednh th\u1ee9 hai \\\\(\\hat{y^*} = \\hat{\\gamma_1} X_2\\\\)\n2. h\u1ed3i quy m\u1ed7i thu\u1ed9c t\u00ednh trong nh\u00f3m th\u1ee9 nh\u1ea5t theo nh\u00f3m th\u1ee9 hai  \\\\(\\hat{X_1} = \\hat{\\gamma_2} X_2\\\\)\n3. t\u00ednh to\u00e1n c\u00e1c ph\u1ea7n d\u01b0 \\\\(\\tilde{X}_1 = X_1 - \\hat{X_1}\\\\) v\u00e0 \\\\(\\tilde{y}_1 = y_1 - \\hat{y^*}\\\\)\n4. h\u1ed3i quy ph\u1ea7n d\u01b0 c\u1ee7a k\u1ebft qu\u1ea3 theo ph\u1ea7n d\u01b0 c\u1ee7a c\u00e1c thu\u1ed9c t\u00ednh \\\\(\\hat{y} = \\hat{\\beta_1} \\tilde{X}_1\\\\)\n\nTham s\u1ed1 thu \u0111\u01b0\u1ee3c t\u1eeb m\u00f4 h\u00ecnh h\u1ed3i quy sau c\u00f9ng s\u1ebd gi\u1ed1ng h\u1ec7t n\u1ebfu ta ch\u1ea1y h\u1ed3i quy theo t\u1ea5t c\u1ea3 c\u00e1c thu\u1ed9c t\u00ednh. Nh\u01b0ng \u0111i\u1ec1u n\u00e0y c\u00f3 th\u1ec3 gi\u00fap \u00edch ch\u00fang ta nh\u01b0 th\u1ebf n\u00e0o? Ch\u00fang ta c\u00f3 th\u1ec3 ph\u00e2n chia vi\u1ec7c \u01b0\u1edbc l\u01b0\u1ee3ng m\u00f4 h\u00ecnh v\u1edbi c\u00e1c bi\u1ebfn gi\u1ea3 \u0111\u1ed1i t\u01b0\u1ee3ng th\u00e0nh hai. Tr\u01b0\u1edbc h\u1ebft, ch\u00fang ta s\u1eed d\u1ee5ng c\u00e1c bi\u1ebfn gi\u1ea3 \u0111\u1ec3 d\u1ef1 \u0111o\u00e1n k\u1ebft qu\u1ea3 v\u00e0 c\u00e1c thu\u1ed9c t\u00ednh. Ch\u00fang t\u01b0\u01a1ng \u1ee9ng v\u1edbi c\u00e1c b\u01b0\u1edbc 1 v\u00e0 2 tr\u00ean \u0111\u00e2y. \n\nN\u00e0o, h\u00e3y nh\u1edb r\u1eb1ng vi\u1ec7c ch\u1ea1y h\u1ed3i quy theo bi\u1ebfn gi\u1ea3  \u0111\u01a1n gi\u1ea3n ch\u1ec9 l\u00e0 \u01b0\u1edbc l\u01b0\u1ee3ng gi\u00e1 tr\u1ecb trung b\u00ecnh theo bi\u1ebfn gi\u1ea3 \u0111\u00f3 ph\u1ea3i kh\u00f4ng? N\u1ebfu b\u1ea1n kh\u00f4ng \u0111\u1ed3ng \u00fd, ch\u00fang ta h\u00e3y s\u1eed d\u1ee5ng d\u1eef li\u1ec7u \u0111\u1ec3 ch\u1ee9ng minh. H\u00e3y ch\u1ea1y m\u1ed9t m\u00f4 h\u00ecnh \u0111\u1ec3 d\u1ef1 \u0111o\u00e1n l\u01b0\u01a1ng theo bi\u1ebfn gi\u1ea3 n\u0103m. \n\n\n```python\nmod = smf.ols(\"lwage ~ C(year)\", data=data).fit()\nmod.summary().tables[1]\n```\n\n\n\n\n<table class=\"simpletable\">\n<tr>\n         <td></td>            <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th>       <td>    1.3935</td> <td>    0.022</td> <td>   63.462</td> <td> 0.000</td> <td>    1.350</td> <td>    1.437</td>\n</tr>\n<tr>\n  <th>C(year)[T.1981]</th> <td>    0.1194</td> <td>    0.031</td> <td>    3.845</td> <td> 0.000</td> <td>    0.059</td> <td>    0.180</td>\n</tr>\n<tr>\n  <th>C(year)[T.1982]</th> <td>    0.1782</td> <td>    0.031</td> <td>    5.738</td> <td> 0.000</td> <td>    0.117</td> <td>    0.239</td>\n</tr>\n<tr>\n  <th>C(year)[T.1983]</th> <td>    0.2258</td> <td>    0.031</td> <td>    7.271</td> <td> 0.000</td> <td>    0.165</td> <td>    0.287</td>\n</tr>\n<tr>\n  <th>C(year)[T.1984]</th> <td>    0.2968</td> <td>    0.031</td> <td>    9.558</td> <td> 0.000</td> <td>    0.236</td> <td>    0.358</td>\n</tr>\n<tr>\n  <th>C(year)[T.1985]</th> <td>    0.3459</td> <td>    0.031</td> <td>   11.140</td> <td> 0.000</td> <td>    0.285</td> <td>    0.407</td>\n</tr>\n<tr>\n  <th>C(year)[T.1986]</th> <td>    0.4062</td> <td>    0.031</td> <td>   13.082</td> <td> 0.000</td> <td>    0.345</td> <td>    0.467</td>\n</tr>\n<tr>\n  <th>C(year)[T.1987]</th> <td>    0.4730</td> <td>    0.031</td> <td>   15.232</td> <td> 0.000</td> <td>    0.412</td> <td>    0.534</td>\n</tr>\n</table>\n\n\n\nH\u00e3y l\u01b0u \u00fd c\u00e1ch m\u00f4 h\u00ecnh n\u00e0y d\u1ef1 \u0111o\u00e1n m\u1ee9c l\u01b0\u01a1ng b\u00ecnh qu\u00e2n cho n\u0103m 1980 l\u00e0 1.3935, n\u0103m 1981 l\u00e0 {{1.3935+0.1194}} (1.3935+0.1194), v\u00e0 t\u01b0\u01a1ng t\u1ef1 cho c\u00e1c n\u0103m kh\u00e1c. B\u00e2y gi\u1edd n\u1ebfu ch\u00fang ta t\u00ednh gi\u00e1 tr\u1ecb trung b\u00ecnh theo n\u0103m, ch\u00fang ta thu \u0111\u01b0\u1ee3c k\u1ebft qu\u1ea3 gi\u1ed1ng h\u1ec7t (c\u1ed9ng gi\u00e1 tr\u1ecb h\u1ec7 s\u1ed1 ch\u1eb7n v\u1edbi h\u1ec7 s\u1ed1 c\u1ee7a c\u00e1c n\u0103m \u0111\u1ec3 thu \u0111\u01b0\u1ee3c gi\u00e1 tr\u1ecb trung b\u00ecnh n\u0103m).\n\n\n```python\ndata.groupby(\"year\")[\"lwage\"].mean()\n```\n\n\n\n\n    year\n    1980    1.393477\n    1981    1.512867\n    1982    1.571667\n    1983    1.619263\n    1984    1.690295\n    1985    1.739410\n    1986    1.799719\n    1987    1.866479\n    Name: lwage, dtype: float64\n\n\n\n\u0110i\u1ec1u n\u00e0y ngh\u0129a l\u00e0 vi\u1ec7c t\u00ednh gi\u00e1 tr\u1ecb trung b\u00ecnh cho m\u1ed7i ng\u01b0\u1eddi trong b\u1ea3ng c\u1ee7a ch\u00fang ta t\u01b0\u01a1ng \u0111\u01b0\u01a1ng v\u1edbi vi\u1ec7c h\u1ed3i quy c\u00e1c bi\u1ebfn kh\u00e1c theo c\u00e1c bi\u1ebfn gi\u1ea3 cho c\u00e1 nh\u00e2n. \u0110i\u1ec1u n\u00e0y g\u1ee3i \u00fd quy tr\u00ecnh \u01b0\u1edbc l\u01b0\u1ee3ng sau:\n\n1. T\u1ea1o ra c\u00e1c bi\u1ebfn kh\u1eed gi\u00e1 tr\u1ecb trung b\u00ecnh theo th\u1eddi gian b\u1eb1ng c\u00e1ch tr\u1eeb \u0111i gi\u00e1 tr\u1ecb trung b\u00ecnh c\u1ee7a m\u1ed7i c\u00e1 nh\u00e2n:   \n\\\\(\\ddot{Y}_{it} = Y_{it} -  \\bar{Y}_i\\\\)  \n\\\\(\\ddot{X}_{it} = X_{it} -  \\bar{X}_i\\\\)\n2. Ch\u1ea1y m\u00f4 h\u00ecnh h\u1ed3i quy \\\\(\\ddot{Y}_{it}\\\\) theo \\\\(\\ddot{X}_{it}\\\\)\n\nCh\u00fa \u00fd r\u1eb1ng, c\u00e1c bi\u1ebfn kh\u00f4ng quan s\u00e1t \u0111\u01b0\u1ee3c v\u00e0 kh\u00f4ng \u0111\u1ed5i theo th\u1eddi gian \\\\(U_i\\\\) ti\u00eau bi\u1ebfn, v\u00ec \\\\(\\bar{U_i}=U_i\\\\):\n\n\\begin{align}\nY_{it} & = \\beta X_{it} + \\gamma U_i + e_{it} \\\\\n\\bar{Y}_{i} & = \\beta \\bar{X}_{it} + \\gamma U_i + \\bar{e}_{it} \\\\\n(Y_{it} - \\bar{Y}_{i}) & = (\\beta X_{it} - \\beta \\bar{X}_{it}) + (\\gamma U_i - \\gamma U_i) + (e_{it}-\\bar{e}_{it}) \\\\\n(Y_{it} - \\bar{Y}_{i}) & = \\beta(X_{it} - \\bar{X}_{it}) + (e_{it}-\\bar{e}_{it}) \\\\\n\\ddot{Y}_{it} & = \\beta \\ddot{X}_{it} + \\ddot{e}_{it} \\\\\n\\end{align}\n\nTh\u1ef1c ra kh\u00f4ng ch\u1ec9 c\u00e1c bi\u1ebfn kh\u00f4ng quan s\u00e1t \u0111\u01b0\u1ee3c v\u00e0 kh\u00f4ng \u0111\u1ed5i theo th\u1eddi gian ti\u00eau bi\u1ebfn. \u0110i\u1ec1u n\u00e0y x\u1ea3y ra c\u1ea3 v\u1edbi c\u00e1c bi\u1ebfn quan s\u00e1t \u0111\u01b0\u1ee3c v\u00e0 kh\u00f4ng \u0111\u1ed5i theo th\u1eddi gian. V\u00ec l\u00ed do n\u00e0y, b\u1ea1n kh\u00f4ng th\u1ec3 \u0111\u01b0a v\u00e0o m\u00f4 h\u00ecnh b\u1ea5t k\u00ec bi\u1ebfn n\u00e0o kh\u00f4ng \u0111\u1ed5i theo th\u1eddi gian, v\u00ec ch\u00fang s\u1ebd t\u1ea1o th\u00e0nh m\u1ed9t  t\u1ed5 h\u1ee3p tuy\u1ebfn t\u00ednh v\u1edbi c\u00e1c bi\u1ebfn gi\u1ea3 v\u00e0 m\u00f4 h\u00ecnh s\u1ebd kh\u00f4ng ho\u1ea1t \u0111\u1ed9ng.\n\n\n\n\u0110\u1ec3 ki\u1ec3m tra c\u00e1c bi\u1ebfn n\u00e0y, ch\u00fang ta ch\u1ec9 c\u1ea7n nh\u00f3m d\u1eef li\u1ec7u theo c\u00e1 nh\u00e2n v\u00e0 t\u00ednh t\u1ed5ng c\u1ee7a \u0111\u1ed9 l\u1ec7ch chu\u1ea9n. Gi\u00e1 tr\u1ecb c\u1ee7a bi\u1ebfn s\u1ed1 n\u00e0o b\u1eb1ng 0 th\u00ec bi\u1ebfn \u0111\u00f3 c\u1ed1 \u0111\u1ecbnh cho m\u1ed7i \u0111\u1ed1i t\u01b0\u1ee3ng. \n\n\n```python\ndata.groupby(\"nr\").std().sum()\n```\n\n\n\n\n    year            1334.971910\n    black              0.000000\n    exper           1334.971910\n    hisp               0.000000\n    hours         203098.215649\n    married          140.372801\n    educ               0.000000\n    union            106.512445\n    lwage            173.929670\n    expersq        17608.242825\n    occupation       739.222281\n    dtype: float64\n\n\n\nTrong d\u1eef li\u1ec7u c\u1ee7a ch\u00fang ta, c\u1ea7n ph\u1ea3i lo\u1ea1i b\u1ecf c\u00e1c bi\u1ebfn gi\u1ea3 cho ch\u1ee7ng t\u1ed9c nh\u01b0 `black` v\u00e0 `hisp`, v\u00ec ch\u00fang c\u1ed1 \u0111\u1ecbnh cho m\u1ed7i c\u00e1 nh\u00e2n. H\u01a1n n\u1eefa, ch\u00fang ta ph\u1ea3i lo\u1ea1i b\u1ecf h\u1ecdc v\u1ea5n `eudc`. Ch\u00fang ta c\u0169ng s\u1ebd kh\u00f4ng s\u1eed d\u1ee5ng ngh\u1ec1 nghi\u1ec7p v\u00ec n\u00f3 c\u00f3 th\u1ec3 \u0111\u00f3ng vai tr\u00f2 trung gian cho t\u00e1c \u0111\u1ed9ng c\u1ee7a h\u00f4n nh\u00e2n \u0111\u1ed1i v\u1edbi ti\u1ec1n l\u01b0\u01a1ng (V\u00ed d\u1ee5 nh\u1eefng ng\u01b0\u1eddi \u0111\u1ed9c th\u00e2n c\u00f3 th\u1ec3 l\u00e0m nh\u1eefng c\u00f4ng vi\u1ec7c d\u00e0i gi\u1edd h\u01a1n). \n\n\u0110\u1ec3 ch\u1ea1y m\u00f4 h\u00ecnh hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh, tr\u01b0\u1edbc h\u1ebft, h\u00e3y t\u00ednh d\u1eef li\u1ec7u trung b\u00ecnh.\n\n\n```python\nY = \"lwage\"\nT = \"married\"\nX = [T, \"expersq\", \"union\", \"hours\"]\n\nmean_data = data.groupby(\"nr\")[X+[Y]].mean()\nmean_data.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>married</th>\n      <th>expersq</th>\n      <th>union</th>\n      <th>hours</th>\n      <th>lwage</th>\n    </tr>\n    <tr>\n      <th>nr</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>13</th>\n      <td>0.000</td>\n      <td>25.5</td>\n      <td>0.125</td>\n      <td>2807.625</td>\n      <td>1.255652</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>0.000</td>\n      <td>61.5</td>\n      <td>0.000</td>\n      <td>2504.125</td>\n      <td>1.637786</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>1.000</td>\n      <td>61.5</td>\n      <td>0.000</td>\n      <td>2350.500</td>\n      <td>2.034387</td>\n    </tr>\n    <tr>\n      <th>45</th>\n      <td>0.125</td>\n      <td>35.5</td>\n      <td>0.250</td>\n      <td>2225.875</td>\n      <td>1.773664</td>\n    </tr>\n    <tr>\n      <th>110</th>\n      <td>0.500</td>\n      <td>77.5</td>\n      <td>0.125</td>\n      <td>2108.000</td>\n      <td>2.055129</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\u0110\u1ec3 kh\u1eed gi\u00e1 tr\u1ecb trung b\u00ecnh (theo th\u1eddi gian) c\u1ee7a d\u1eef li\u1ec7u, ch\u00fang ta c\u1ea7n \u0111\u1eb7t ch\u1ec9 s\u1ed1 c\u1ee7a d\u1eef li\u1ec7u g\u1ed1c tr\u00f9ng v\u1edbi ch\u1ec9 s\u1ed1 c\u00e1 nh\u00e2n, `nr`. Sau \u0111\u00f3 ch\u00fang ta \u0111\u01a1n gi\u1ea3n ch\u1ec9 c\u1ea7n l\u1ea5y gi\u00e1 tr\u1ecb khung d\u1eef li\u1ec7u tr\u1eeb \u0111i gi\u00e1 tr\u1ecb trung b\u00ecnh c\u1ee7a khung d\u1eef li\u1ec7u.\n\n\n```python\ndeamed_data = (data\n               .set_index(\"nr\") # set the index as the person indicator\n               [X+[Y]]\n               - mean_data) # subtract the mean data\n\ndeamed_data.head()\n```\n\nCu\u1ed1i c\u00f9ng, ch\u00fang ta c\u00f3 th\u1ec3 ch\u1ea1y m\u00f4 h\u00ecnh hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh s\u1eed d\u1ee5ng d\u1eef li\u1ec7u \u0111\u00e3 kh\u1eed gi\u00e1 tr\u1ecb trung b\u00ecnh theo th\u1eddi gian.\n\n\n```python\nmod = smf.ols(f\"{Y} ~ {'+'.join(X)}\", data=deamed_data).fit()\nmod.summary().tables[1]\n```\n\n\n\n\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>-8.327e-17</td> <td>    0.005</td> <td>-1.64e-14</td> <td> 1.000</td> <td>   -0.010</td> <td>    0.010</td>\n</tr>\n<tr>\n  <th>married</th>   <td>    0.1147</td> <td>    0.017</td> <td>    6.756</td> <td> 0.000</td> <td>    0.081</td> <td>    0.148</td>\n</tr>\n<tr>\n  <th>expersq</th>   <td>    0.0040</td> <td>    0.000</td> <td>   21.958</td> <td> 0.000</td> <td>    0.004</td> <td>    0.004</td>\n</tr>\n<tr>\n  <th>union</th>     <td>    0.0784</td> <td>    0.018</td> <td>    4.261</td> <td> 0.000</td> <td>    0.042</td> <td>    0.115</td>\n</tr>\n<tr>\n  <th>hours</th>     <td> -8.46e-05</td> <td> 1.25e-05</td> <td>   -6.744</td> <td> 0.000</td> <td>   -0.000</td> <td>   -6e-05</td>\n</tr>\n</table>\n\n\n\nN\u1ebfu ch\u00fang ta tin r\u1eb1ng hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh lo\u1ea1i tr\u1eeb ho\u00e0n to\u00e0n thi\u00ean l\u1ec7ch thi\u1ebfu bi\u1ebfn, m\u00f4 h\u00ecnh n\u00e0y cho ta bi\u1ebft vi\u1ec7c k\u1ebft h\u00f4n l\u00e0m t\u0103ng thu nh\u1eadp c\u1ee7a nam gi\u1edbi th\u00eam 11%. K\u1ebft qu\u1ea3 n\u00e0y c\u00f3 \u00fd ngh\u0129a th\u1ed1ng k\u00ea. M\u1ed9t chi ti\u1ebft \u1edf \u0111\u00e2y l\u00e0 \u0111\u1ed1i v\u1edbi m\u00f4 h\u00ecnh hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh, c\u00e1c sai s\u1ed1 chu\u1ea9n c\u1ea7n \u0111\u01b0\u1ee3c nh\u00f3m c\u1ee5m. Do \u0111\u00f3 thay v\u00ec t\u00ednh \u01b0\u1edbc l\u01b0\u1ee3ng b\u1eb1ng tay (ch\u1ec9 ph\u00f9 h\u1ee3p cho l\u00fd do s\u01b0 ph\u1ea1m), ch\u00fang ta c\u00f3 th\u1ec3 d\u00f9ng th\u01b0 vi\u1ec7n `linearmodels` v\u00e0 \u0111\u1eb7t tham s\u1ed1 th\u1ef1c `cluster_entity` l\u00e0 True.\n\n\n```python\nfrom linearmodels.panel import PanelOLS\nmod = PanelOLS.from_formula(\"lwage ~ expersq+union+married+hours+EntityEffects\",\n                            data=data.set_index([\"nr\", \"year\"]))\n\nresult = mod.fit(cov_type='clustered', cluster_entity=True)\nresult.summary.tables[1]\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>Parameter Estimates</caption>\n<tr>\n     <td></td>     <th>Parameter</th> <th>Std. Err.</th> <th>T-stat</th>  <th>P-value</th> <th>Lower CI</th>  <th>Upper CI</th> \n</tr>\n<tr>\n  <th>expersq</th>  <td>0.0040</td>    <td>0.0002</td>   <td>16.552</td>  <td>0.0000</td>   <td>0.0035</td>    <td>0.0044</td>  \n</tr>\n<tr>\n  <th>union</th>    <td>0.0784</td>    <td>0.0236</td>   <td>3.3225</td>  <td>0.0009</td>   <td>0.0322</td>    <td>0.1247</td>  \n</tr>\n<tr>\n  <th>married</th>  <td>0.1147</td>    <td>0.0220</td>   <td>5.2213</td>  <td>0.0000</td>   <td>0.0716</td>    <td>0.1577</td>  \n</tr>\n<tr>\n  <th>hours</th>   <td>-8.46e-05</td> <td>2.22e-05</td>  <td>-3.8105</td> <td>0.0001</td>   <td>-0.0001</td> <td>-4.107e-05</td>\n</tr>\n</table>\n\n\n\nB\u1ea1n c\u00f3 th\u1ec3 th\u1ea5y c\u00e1c \u01b0\u1edbc l\u01b0\u1ee3ng h\u1ec7 s\u1ed1 gi\u1ed1ng v\u1edbi tr\u01b0\u1eddng h\u1ee3p s\u1eed d\u1ee5ng d\u1eef li\u1ec7u \u0111\u00e3 kh\u1eed gi\u00e1 tr\u1ecb trung b\u00ecnh theo th\u1eddi gian. Kh\u00e1c bi\u1ec7t duy nh\u1ea5t l\u00e0 c\u00e1c sai s\u1ed1 chu\u1ea9n l\u1edbn h\u01a1n m\u1ed9t ch\u00fat. N\u00e0o, h\u00e3y so s\u00e1nh ch\u00fang v\u1edbi OLS model \u0111\u01a1n gi\u1ea3n kh\u00f4ng t\u1eadn d\u1ee5ng c\u1ea5u tr\u00fac th\u1eddi gian c\u1ee7a d\u1eef li\u1ec7u. V\u1edbi m\u00f4 h\u00ecnh n\u00e0y, ch\u00fang ta \u0111\u01b0a tr\u1edf l\u1ea1i c\u00e1c bi\u1ebfn kh\u00f4ng \u0111\u1ed5i theo th\u1eddi gian.\n\n\n```python\nmod = smf.ols(\"lwage ~ expersq+union+married+hours+black+hisp+educ\", data=data).fit()\nmod.summary().tables[1]\n```\n\n\n\n\n<table class=\"simpletable\">\n<tr>\n      <td></td>         <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th> <td>    0.2654</td> <td>    0.065</td> <td>    4.103</td> <td> 0.000</td> <td>    0.139</td> <td>    0.392</td>\n</tr>\n<tr>\n  <th>expersq</th>   <td>    0.0032</td> <td>    0.000</td> <td>   15.750</td> <td> 0.000</td> <td>    0.003</td> <td>    0.004</td>\n</tr>\n<tr>\n  <th>union</th>     <td>    0.1829</td> <td>    0.017</td> <td>   10.598</td> <td> 0.000</td> <td>    0.149</td> <td>    0.217</td>\n</tr>\n<tr>\n  <th>married</th>   <td>    0.1410</td> <td>    0.016</td> <td>    8.931</td> <td> 0.000</td> <td>    0.110</td> <td>    0.172</td>\n</tr>\n<tr>\n  <th>hours</th>     <td> -5.32e-05</td> <td> 1.34e-05</td> <td>   -3.978</td> <td> 0.000</td> <td>-7.94e-05</td> <td> -2.7e-05</td>\n</tr>\n<tr>\n  <th>black</th>     <td>   -0.1347</td> <td>    0.024</td> <td>   -5.679</td> <td> 0.000</td> <td>   -0.181</td> <td>   -0.088</td>\n</tr>\n<tr>\n  <th>hisp</th>      <td>    0.0132</td> <td>    0.021</td> <td>    0.632</td> <td> 0.528</td> <td>   -0.028</td> <td>    0.054</td>\n</tr>\n<tr>\n  <th>educ</th>      <td>    0.1057</td> <td>    0.005</td> <td>   22.550</td> <td> 0.000</td> <td>    0.097</td> <td>    0.115</td>\n</tr>\n</table>\n\n\n\nM\u00f4 h\u00ecnh n\u00e0y cho r\u1eb1ng k\u1ebft h\u00f4n l\u00e0m t\u0103ng ti\u1ec1n l\u01b0\u01a1ng c\u1ee7a nam gi\u1edbi th\u00eam 14%. M\u1ee9c t\u00e1c \u0111\u1ed9ng n\u00e0y cao h\u01a1n k\u1ebft qu\u1ea3 ch\u00fang ta t\u00ecm \u0111\u01b0\u1ee3c v\u1edbi m\u00f4 h\u00ecnh hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh. \u0110i\u1ec1u n\u00e0y g\u1ee3i \u00fd r\u1eb1ng c\u00f3 thi\u00ean l\u1ec7ch thi\u1ebfu bi\u1ebfn do c\u00e1c y\u1ebfu t\u1ed1 c\u1ed1 \u0111\u1ecbnh theo t\u1eebng c\u00e1 nh\u00e2n, nh\u01b0 tr\u00ed tu\u1ec7 v\u00e0 \u0111\u1ed9 \u0111i\u1ec3n trai ch\u01b0a \u0111\u01b0\u1ee3c \u0111\u01b0a v\u00e0o m\u00f4 h\u00ecnh. \n\n## Bi\u1ec3u di\u1ec5n Hi\u1ec7u \u1ee8ng C\u1ed1 \u0110\u1ecbnh\n\u0110\u1ec3 m\u1edf r\u1ed9ng hi\u1ec3u bi\u1ebft v\u1ec1 c\u00e1ch  m\u00f4 h\u00ecnh hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh ho\u1ea1t \u0111\u1ed9ng, h\u00e3y c\u00f9ng xem x\u00e9t m\u1ed9t v\u00ed d\u1ee5 kh\u00e1c. Gi\u1ea3 s\u1eed b\u1ea1n l\u00e0m vi\u1ec7c cho m\u1ed9t c\u00f4ng ty c\u00f4ng ngh\u1ec7 v\u00e0 c\u1ea7n \u01b0\u1edbc l\u01b0\u1ee3ng t\u00e1c \u0111\u1ed9ng c\u1ee7a chi\u1ebfn d\u1ecbch marketing billboard (bi\u1ec3n qu\u1ea3ng c\u00e1o ngo\u00e0i tr\u1eddi) cho d\u1ecbch v\u1ee5 mua b\u00e1n qua \u1ee9ng d\u1ee5ng. Khi nh\u00ecn v\u00e0o d\u1eef li\u1ec7u qu\u00e1 kh\u1ee9, b\u1ea1n nh\u1eadn th\u1ea5y ph\u00f2ng marketing c\u00f3 xu h\u01b0\u1edbng chi ti\u1ec1n cho bi\u1ec3n qu\u1ea3ng c\u00e1o \u1edf c\u00e1c th\u00e0nh ph\u1ed1 c\u00f3 l\u01b0\u1ee3ng mua h\u00e0ng th\u1ea5p. \u0110i\u1ec1u n\u00e0y c\u00f3 l\u00ed ph\u1ea3i kh\u00f4ng? H\u1ecd \u0111\u00e3 ch\u1eb3ng c\u1ea7n marketing nhi\u1ec1u n\u1ebfu n\u01a1i \u0111\u00f3 c\u00f3 l\u01b0\u1ee3ng b\u00e1n h\u00e0ng \u1ed3 \u1ea1t. N\u1ebfu b\u1ea1n ch\u1ea1y m\u1ed9t m\u00f4 h\u00ecnh h\u1ed3i quy s\u1eed d\u1ee5ng d\u1eef li\u1ec7u n\u00e0y th\u00ec s\u1ebd tr\u00f4ng nh\u01b0 th\u1ec3 chi ph\u00ed marketing cao d\u1eabn \u0111\u1ebfn l\u01b0\u1ee3ng mua h\u00e0ng qua \u1ee9ng d\u1ee5ng th\u1ea5p.\n\n\n```python\ntoy_panel = pd.DataFrame({\n    \"mkt_costs\":[5,4,3.5,3, 10,9.5,9,8, 4,3,2,1, 8,7,6,4],\n    \"purchase\":[12,9,7.5,7, 9,7,6.5,5, 15,14.5,14,13, 11,9.5,8,5],\n    \"city\":[\"C0\",\"C0\",\"C0\",\"C0\", \"C2\",\"C2\",\"C2\",\"C2\", \"C1\",\"C1\",\"C1\",\"C1\", \"C3\",\"C3\",\"C3\",\"C3\"]\n})\n\nm = smf.ols(\"purchase ~ mkt_costs\", data=toy_panel).fit()\n\nplt.scatter(toy_panel.mkt_costs, toy_panel.purchase)\nplt.plot(toy_panel.mkt_costs, m.fittedvalues, c=\"C5\", label=\"\u0110\u01b0\u1eddng H\u1ed3i quy\")\nplt.xlabel(\"Chi ph\u00ed Marketing (ng\u00e0n)\")\nplt.ylabel(\"L\u01b0\u1ee3ng mua h\u00e0ng qua \u1ee9ng d\u1ee5ng (ng\u00e0n)\")\nplt.title(\"M\u00f4 h\u00ecnh OLS \u0111\u01a1n gi\u1ea3n\")\nplt.legend();\n```\n\nHi\u1ec3u r\u00f5 v\u1ec1 suy lu\u1eadn nh\u00e2n qu\u1ea3, b\u1ea1n quy\u1ebft \u0111\u1ecbnh ch\u1ea1y m\u1ed9t m\u00f4 h\u00ecnh hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh, \u0111\u01b0a c\u00e1c bi\u1ebfn ch\u1ec9 b\u00e1o th\u00e0nh ph\u1ed1 d\u01b0\u1edbi d\u1ea1ng c\u00e1c bi\u1ebfn gi\u1ea3 v\u00e0o m\u00f4 h\u00ecnh. M\u00f4 h\u00ecnh hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh ki\u1ec3m so\u00e1t c\u00e1c \u0111\u1eb7c t\u00ednh c\u1ee7a th\u00e0nh ph\u1ed1 kh\u00f4ng \u0111\u1ed5i theo th\u1eddi gian, n\u1ebfu m\u1ed9t th\u00e0nh ph\u1ed1 c\u00f2n e d\u00e8 v\u1edbi s\u1ea3n ph\u1ea9m c\u1ee7a b\u1ea1n, n\u00f3 s\u1ebd n\u1eafm b\u1eaft \u0111i\u1ec1u n\u00e0y. Khi ch\u1ea1y m\u00f4 h\u00ecnh n\u00e0y, cu\u1ed1i c\u00f9ng b\u1ea1n c\u0169ng th\u1ea5y vi\u1ec7c t\u0103ng th\u00eam chi ph\u00ed marketing qu\u1ea3 th\u1eadt mang l\u1ea1i l\u01b0\u1ee3ng mua h\u00e0ng qua \u1ee9ng d\u1ee5ng nhi\u1ec1u h\u01a1n.\n\n\n```python\nfe = smf.ols(\"purchase ~ mkt_costs + C(city)\", data=toy_panel).fit()\n\nfe_toy = toy_panel.assign(y_hat = fe.fittedvalues)\n\nplt.scatter(toy_panel.mkt_costs, toy_panel.purchase, c=toy_panel.city)\nfor city in fe_toy[\"city\"].unique():\n    plot_df = fe_toy.query(f\"city=='{city}'\")\n    plt.plot(plot_df.mkt_costs, plot_df.y_hat, c=\"C5\")\n\nplt.title(\"M\u00f4 H\u00ecnh Hi\u1ec7u \u1ee8ng C\u1ed1 \u0110\u1ecbnh\")\nplt.xlabel(\"Chi ph\u00ed Marketing (ng\u00e0n)\")\nplt.ylabel(\"L\u01b0\u1ee3ng mua h\u00e0ng qua \u1ee9ng d\u1ee5ng (ng\u00e0n)\");\n```\n\nH\u00e3y d\u00e0nh m\u1ed9t ph\u00fat \u0111\u1ec3 \u0111\u00e1nh gi\u00e1 \u0111\u1ed3 th\u1ecb ph\u00eda tr\u00ean v\u00e0 \u0111\u1ec3 n\u00f3 cho b\u1ea1n bi\u1ebft th\u1ef1c ra hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh \u0111ang l\u00e0m g\u00ec. Ch\u00fa \u00fd r\u1eb1ng hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh \u0111ang \u01b0\u1edbc l\u01b0\u1ee3ng **m\u1ed9t \u0111\u01b0\u1eddng h\u1ed3i quy cho m\u1ed7i th\u00e0nh ph\u1ed1**. V\u00e0 h\u00e3y l\u01b0u \u00fd c\u00e1c \u0111\u01b0\u1eddng n\u00e0y song song v\u1edbi nhau. \u0110\u1ed9 d\u1ed1c c\u1ee7a \u0111\u01b0\u1eddng h\u1ed3i quy l\u00e0 t\u00e1c \u0111\u1ed9ng c\u1ee7a chi ph\u00ed marketing v\u1edbi l\u01b0\u1ee3ng mua h\u00e0ng qua \u1ee9ng d\u1ee5ng. V\u00ec th\u1ebf **hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh gi\u1ea3 \u0111\u1ecbnh r\u1eb1ng t\u00e1c \u0111\u1ed9ng nh\u00e2n qu\u1ea3 kh\u00f4ng \u0111\u1ed5i theo \u0111\u1ed1i t\u01b0\u1ee3ng**, trong tr\u01b0\u1eddng h\u1ee3p n\u00e0y l\u00e0 c\u00e1c \u0111\u1ecba b\u00e0n th\u00e0nh ph\u1ed1. \u0110\u00e2y c\u00f3 th\u1ec3 l\u00e0 \u0111i\u1ec3m y\u1ebfu v\u00e0 c\u0169ng c\u00f3 th\u1ec3 l\u00e0 \u0111i\u1ec3m m\u1ea1nh, ph\u1ee5 thu\u1ed9c v\u00e0o vi\u1ec7c b\u1ea1n d\u00f9ng n\u00f3 v\u00e0o vi\u1ec7c g\u00ec. N\u00f3 l\u00e0 \u0111i\u1ec3m y\u1ebfu n\u1ebfu b\u1ea1n mu\u1ed1n t\u00ecm hi\u1ec3u t\u00e1c \u0111\u1ed9ng nh\u00e2n qu\u1ea3 c\u1ee5 th\u1ec3 cho t\u1eebng th\u00e0nh ph\u1ed1. V\u00ec m\u00f4 h\u00ecnh FE gi\u1ea3 \u0111\u1ecbnh t\u00e1c \u0111\u1ed9ng n\u00e0y c\u1ed1 \u0111\u1ecbnh theo \u0111\u1ed1i t\u01b0\u1ee3ng, b\u1ea1n s\u1ebd kh\u00f4ng th\u1ea5y kh\u00e1c bi\u1ec7t trong t\u00e1c \u0111\u1ed9ng nh\u00e2n qu\u1ea3. Tuy nhi\u00ean, n\u1ebfu b\u1ea1n mu\u1ed1n \u0111\u00e1nh gi\u00e1 t\u00e1c \u0111\u1ed9ng t\u1ed5ng th\u1ec3 c\u1ee7a marketing v\u1edbi l\u01b0\u1ee3ng mua h\u00e0ng qua \u1ee9ng d\u1ee5ng, c\u1ea5u tr\u00fac d\u1eef li\u1ec7u b\u1ea3ng s\u1ebd r\u1ea5t h\u1eefu d\u1ee5ng cho hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh. \n\n## Hi\u1ec7u \u1ee9ng th\u1eddi gian\n\nGi\u1ed1ng nh\u01b0 nh\u1eefng g\u00ec ch\u00fang ta \u0111\u00e3 l\u00e0m v\u1edbi hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh cho c\u00e1c c\u00e1 nh\u00e2n, ch\u00fang ta c\u00f3 th\u1ec3 thi\u1ebft k\u1ebf m\u1ed9t m\u00f4 h\u00ecnh hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh cho th\u1eddi gian. N\u1ebfu ta \u0111\u01b0a v\u00e0o m\u00f4 h\u00ecnh m\u1ed9t bi\u1ebfn gi\u1ea3 cho m\u1ed7i c\u00e1 nh\u00e2n \u0111\u1ec3 ki\u1ec3m so\u00e1t c\u00e1c \u0111\u1eb7c t\u00ednh c\u1ed1 \u0111\u1ecbnh cho m\u1ed7i c\u00e1 nh\u00e2n,  ta c\u00f3 th\u1ec3 \u0111\u01b0a v\u00e0o c\u00e1c bi\u1ebfn gi\u1ea3 th\u1eddi gian \u0111\u1ec3 ki\u1ec3m so\u00e1t c\u00e1c bi\u1ebfn kh\u00f4ng \u0111\u1ed5i theo th\u1eddi gian. M\u1ed9t v\u00ed d\u1ee5 l\u00e0 bi\u1ebfn l\u1ea1m ph\u00e1t. M\u1ee9c gi\u00e1 v\u00e0 ti\u1ec1n l\u01b0\u01a1ng c\u00f3 xu h\u01b0\u1edbng t\u0103ng theo th\u1eddi gian. N\u1ebfu ti\u1ec1n l\u01b0\u01a1ng v\u00e0 t\u1ec9 l\u1ec7 k\u1ebft h\u00f4n c\u0169ng t\u0103ng theo th\u1eddi gian, th\u00ec th\u1eddi gian l\u00e0 m\u1ed9t bi\u1ebfn nhi\u1ec5u. M\u1ed9t v\u00ed d\u1ee5 ch\u1eb7t ch\u1ebd h\u01a1n, gi\u1ea3 s\u1eed t\u1ec9 l\u1ec7 k\u1ebft h\u00f4n t\u0103ng theo th\u1eddi gian. V\u00ec l\u1ea1m ph\u00e1t l\u00e0m m\u1ee9c l\u01b0\u01a1ng t\u0103ng theo th\u1eddi gian, m\u1ed9t ph\u1ea7n t\u01b0\u01a1ng quan c\u00f9ng chi\u1ec1u ta th\u1ea5y gi\u1eefa vi\u1ec7c k\u1ebft h\u00f4n v\u00e0 m\u1ee9c l\u01b0\u01a1ng \u0111\u01a1n gi\u1ea3n l\u00e0 do c\u1ea3 hai \u0111ang t\u0103ng theo th\u1eddi gian. \u0110\u1ec3 s\u1eeda ch\u1eefa n\u00f3, ta c\u00f3 th\u1ec3 \u0111\u01b0a v\u00e0o m\u1ed9t bi\u1ebfn bi\u1ebfn gi\u1ea3 cho m\u1ed7i th\u1eddi \u0111i\u1ec3m. Trong `linear models`, \u0111i\u1ec1u n\u00e0y \u0111\u01b0\u1ee3c th\u1ef1c hi\u1ec7n d\u1ec5 d\u00e0ng b\u1eb1ng c\u00e1ch th\u00eam `TimeEffects` v\u00e0o c\u00f4ng th\u1ee9c c\u1ee7a ch\u00fang ta v\u00e0 \u0111\u1eb7t gi\u00e1 tr\u1ecb `cluster_time` b\u1eb1ng True.\n\n\n```python\nmod = PanelOLS.from_formula(\"lwage ~ expersq+union+married+hours+EntityEffects+TimeEffects\",\n                            data=data.set_index([\"nr\", \"year\"]))\n\nresult = mod.fit(cov_type='clustered', cluster_entity=True, cluster_time=True)\nresult.summary.tables[1]\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>Parameter Estimates</caption>\n<tr>\n     <td></td>     <th>Parameter</th> <th>Std. Err.</th> <th>T-stat</th>  <th>P-value</th> <th>Lower CI</th>  <th>Upper CI</th> \n</tr>\n<tr>\n  <th>expersq</th>  <td>-0.0062</td>   <td>0.0008</td>   <td>-8.1479</td> <td>0.0000</td>   <td>-0.0077</td>   <td>-0.0047</td> \n</tr>\n<tr>\n  <th>union</th>    <td>0.0727</td>    <td>0.0228</td>   <td>3.1858</td>  <td>0.0015</td>   <td>0.0279</td>    <td>0.1174</td>  \n</tr>\n<tr>\n  <th>married</th>  <td>0.0476</td>    <td>0.0177</td>   <td>2.6906</td>  <td>0.0072</td>   <td>0.0129</td>    <td>0.0823</td>  \n</tr>\n<tr>\n  <th>hours</th>    <td>-0.0001</td>  <td>3.546e-05</td> <td>-3.8258</td> <td>0.0001</td>   <td>-0.0002</td> <td>-6.614e-05</td>\n</tr>\n</table>\n\n\n\nTrong m\u00f4 h\u00ecnh m\u1edbi n\u00e0y, t\u00e1c \u0111\u1ed9ng c\u1ee7a h\u00f4n nh\u00e2n \u0111\u1ed1i v\u1edbi ti\u1ec1n l\u01b0\u01a1ng gi\u1ea3m m\u1ea1nh t\u1eeb `0.1147` xu\u1ed1ng `0.0476`. K\u1ebft qu\u1ea3 n\u00e0y v\u1eabn c\u00f3 \u00fd ngh\u0129a th\u1ed1ng k\u00ea \u1edf m\u1ee9c 99%, v\u00ec th\u1ebf nam gi\u1edbi v\u1eabn c\u00f3 th\u1ec3 k\u00ec v\u1ecdng t\u0103ng l\u01b0\u01a1ng nh\u1edd v\u00e0o k\u1ebft h\u00f4n. \n\n## Khi D\u1eef Li\u1ec7u B\u1ea3ng Kh\u00f4ng th\u1ec3 Gi\u00fap b\u1ea1n\n\nS\u1eed d\u1ee5ng d\u1eef li\u1ec7u b\u1ea3ng v\u00e0 m\u00f4 h\u00ecnh hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh l\u00e0 c\u00f4ng c\u1ee5 v\u00f4 c\u00f9ng hi\u1ec7u qu\u1ea3 cho suy lu\u1eadn nh\u00e2n qu\u1ea3. Khi b\u1ea1n kh\u00f4ng c\u00f3 d\u1eef li\u1ec7u ng\u1eabu nhi\u00ean ho\u1eb7c bi\u1ebfn c\u00f4ng c\u1ee5 t\u1ed1t, hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh l\u00e0 ph\u01b0\u01a1ng ti\u1ec7n suy lu\u1eadn nh\u00e2n qu\u1ea3 thuy\u1ebft ph\u1ee5c v\u1edbi d\u1eef li\u1ec7u phi th\u1ef1c nghi\u1ec7m. Tuy v\u1eady n\u00f3 kh\u00f4ng ph\u1ea3i li\u1ec1u thu\u1ed1c v\u1ea1n n\u0103ng. C\u00f3 nh\u1eefng t\u00ecnh hu\u1ed1ng m\u00e0 ngay c\u1ea3 d\u1eef li\u1ec7u b\u1ea3ng kh\u00f4ng th\u1ec3 gi\u00fap b\u1ea1n.\n\nTr\u01b0\u1eddng h\u1ee3p d\u1ec5 th\u1ea5y nh\u1ea5t l\u00e0 khi b\u1ea1n c\u00f3 c\u00e1c bi\u1ebfn nhi\u1ec5u thay \u0111\u1ed5i theo th\u1eddi gian. Hi\u1ec7u \u1ee8ng C\u1ed1 \u0110\u1ecbnh ch\u1ec9 c\u00f3 th\u1ec3 lo\u1ea1i b\u1ecf thi\u00ean l\u1ec7ch t\u1eeb c\u00e1c thu\u1ed9c t\u00ednh c\u1ed1 \u0111\u1ecbnh theo c\u00e1 nh\u00e2n. V\u00ed d\u1ee5, gi\u1ea3 s\u1eed tr\u00ed tu\u1ec7 \u0111\u01b0\u1ee3c t\u0103ng c\u01b0\u1eddng khi \u0111\u1ecdc nhi\u1ec1u s\u00e1ch v\u00e0 ti\u00eau th\u1ee5 nhi\u1ec1u ch\u1ea5t b\u00e9o t\u1ed1t. \u0110i\u1ec1u n\u00e0y gi\u00fap b\u1ea1n ki\u1ebfm \u0111\u01b0\u1ee3c c\u00f4ng vi\u1ec7c t\u1ed1t v\u00e0 l\u1ea5y \u0111\u01b0\u1ee3c v\u1ee3. Hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh s\u1ebd kh\u00f4ng th\u1ec3 lo\u1ea1i b\u1ecf  lo\u1ea1i thi\u00ean l\u1ec7ch ph\u00e1t sinh t\u1eeb nhi\u1ec5u tr\u00ed tu\u1ec7 kh\u00f4ng \u0111\u01b0\u1ee3c \u0111o l\u01b0\u1eddng v\u00ec trong v\u00ed d\u1ee5 n\u00e0y tr\u00ed tu\u1ec7 thay \u0111\u1ed5i theo th\u1eddi gian. \n\n\n\nM\u1ed9t tr\u01b0\u1eddng h\u1ee3p kh\u00e1c kh\u00f3 th\u1ea5y h\u01a1n l\u00e0 khi hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh kh\u00f4ng th\u1ec3 gi\u00fap khi b\u1ea1n g\u1eb7p ph\u1ea3i **quan h\u1ec7 nh\u00e2n qu\u1ea3 ng\u01b0\u1ee3c**. V\u00ed d\u1ee5, h\u00e3y n\u00f3i r\u1eb1ng vi\u1ec7c k\u1ebft h\u00f4n kh\u00f4ng l\u00e0m t\u0103ng thu nh\u1eadp c\u1ee7a b\u1ea1n. Ph\u1ea3i ch\u0103ng thu nh\u1eadp cao l\u00e0m t\u0103ng kh\u1ea3 n\u0103ng k\u1ebft h\u00f4n c\u1ee7a b\u1ea1n? Trong tr\u01b0\u1eddng h\u1ee3p n\u00e0y, b\u1ea1n s\u1ebd th\u1ea5y m\u1ed1i t\u01b0\u01a1ng quan c\u00f9ng chi\u1ec1u nh\u01b0ng m\u1ee9c thu nh\u1eadp \u0111\u01b0\u1ee3c \u0111\u1ecbnh tr\u01b0\u1edbc. Ch\u00fang s\u1ebd c\u00f9ng thay \u0111\u1ed5i theo th\u1eddi gian v\u00e0 theo c\u00f9ng m\u1ed9t h\u01b0\u1edbng, v\u00ec v\u1eady hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh s\u1ebd kh\u00f4ng th\u1ec3 ki\u1ec3m so\u00e1t \u0111\u01b0\u1ee3c \u0111i\u1ec1u n\u00e0y. \n\n## \u00dd t\u01b0\u1edfng ch\u1ee7 \u0111\u1ea1o\n\nTrong b\u00e0i n\u00e0y ch\u00fang ta \u0111\u00e3 th\u1ea5y c\u00e1ch s\u1eed d\u1ee5ng d\u1eef li\u1ec7u b\u1ea3ng, lo\u1ea1i d\u1eef li\u1ec7u v\u1edbi nhi\u1ec1u k\u1ebft qu\u1ea3 \u0111o cho c\u00f9ng c\u00e1 nh\u00e2n t\u1ea1i c\u00e1c th\u1eddi \u0111i\u1ec3m kh\u00e1c nhau. Trong tr\u01b0\u1eddng h\u1ee3p n\u00e0y, ch\u00fang ta c\u1ea7n s\u1eed d\u1ee5ng m\u00f4 h\u00ecnh hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh ki\u1ec3m so\u00e1t c\u00e1c thu\u1ed9c t\u00ednh c\u1ed1 \u0111\u1ecbnh theo th\u1eddi gian c\u1ee7a m\u1ed7i \u0111\u1ed1i t\u01b0\u1ee3ng. \u0110\u00e2y l\u00e0 m\u1ed9t ph\u01b0\u01a1ng ph\u00e1p r\u1ea5t hi\u1ec7u qu\u1ea3 v\u00e0 thuy\u1ebft ph\u1ee5c \u0111\u1ec3 ki\u1ec3m so\u00e1t c\u00e1c bi\u1ebfn nhi\u1ec5u v\u00e0 c\u00f3 th\u1ec3 \u00e1p d\u1ee5ng t\u1ed1t cho d\u1eef li\u1ec7u kh\u00f4ng ng\u1eabu nhi\u00ean.\n\nCu\u1ed1i c\u00f9ng, ch\u00fang ta \u0111\u00e3 th\u1ea5y FE kh\u00f4ng ph\u1ea3i li\u1ec1u thu\u1ed1c v\u1ea1n n\u0103ng. Ch\u00fang ta \u0111\u00e3 n\u1eafm \u0111\u01b0\u1ee3c hai t\u00ecnh hu\u1ed1ng m\u00e0 ph\u01b0\u01a1ng ph\u00e1p n\u00e0y \u00edt t\u00e1c d\u1ee5ng: khi ch\u00fang ta c\u00f3 quan h\u1ec7 nh\u00e2n qu\u1ea3 ng\u01b0\u1ee3c v\u00e0 khi c\u00e1c bi\u1ebfn nhi\u1ec5u kh\u00f4ng \u0111o \u0111\u01b0\u1ee3c thay \u0111\u1ed5i theo th\u1eddi gian.\n\n## T\u00e0i li\u1ec7u tham kh\u1ea3o\n\nT\u00f4i mu\u1ed1n d\u00e0nh lo\u1ea1t b\u00e0i vi\u1ebft n\u00e0y \u0111\u1ec3 vinh danh Joshua Angrist, Alberto Abadie and Christopher Walters v\u00ec kh\u00f3a h\u1ecdc Kinh t\u1ebf l\u01b0\u1ee3ng tuy\u1ec7t c\u00fa m\u00e8o c\u1ee7a h\u1ecd. Ph\u1ea7n l\u1edbn \u00fd t\u01b0\u1edfng trong lo\u1ea1t b\u00e0i n\u00e0y \u0111\u01b0\u1ee3c l\u1ea5y t\u1eeb c\u00e1c b\u00e0i gi\u1ea3ng c\u1ee7a h\u1ecd \u0111\u01b0\u1ee3c t\u1ed5 ch\u1ee9c b\u1edfi Hi\u1ec7p h\u1ed9i Kinh t\u1ebf M\u0129.  Theo d\u00f5i c\u00e1c b\u00e0i gi\u1ea3ng n\u00e0y l\u00e0 nh\u1eefng g\u00ec t\u00f4i l\u00e0m trong su\u1ed1t n\u0103m 2020 kh\u00f3 nh\u1eb1n.\n* [Kinh t\u1ebf l\u01b0\u1ee3ng v\u1edbi d\u1eef li\u1ec7u ch\u00e9o](https://www.aeaweb.org/conference/cont-ed/2017-webcasts)\n* [Luy\u1ec7n ch\u01b0\u1edfng Kinh t\u1ebf l\u01b0\u1ee3ng G\u1ea7n nh\u01b0 V\u00f4 h\u1ea1i](https://www.aeaweb.org/conference/cont-ed/2020-webcasts)\n\nT\u00f4i c\u0169ng mu\u1ed1n gi\u1edbi thi\u1ec7u cu\u1ed1n s\u00e1ch l\u00fd th\u00fa c\u1ee7a Angrist. Ch\u00fang cho t\u00f4i th\u1ea5y Kinh t\u1ebf l\u01b0\u1ee3ng, ho\u1eb7c 'L\u01b0\u1ee3ng theo c\u00e1ch h\u1ecd g\u1ecdi kh\u00f4ng ch\u1ec9 v\u00f4 c\u00f9ng h\u1eefu \u00edch m\u00e0 c\u00f2n r\u1ea5t vui.\n\n* [Kinh t\u1ebf l\u01b0\u1ee3ng G\u1ea7n nh\u01b0 V\u00f4 h\u1ea1i](https://www.mostlyharmlesseconometrics.com/)\n* [Luy\u1ec7n ch\u01b0\u1edfng 'L\u01b0\u1ee3ng](https://www.masteringmetrics.com/)\n\nT\u00e0i li\u1ec7u tham kh\u1ea3o cu\u1ed1i c\u00f9ng c\u1ee7a t\u00f4i l\u00e0 cu\u1ed1n s\u00e1ch c\u1ee7a Miguel Hernan and Jamie Robins. N\u00f3 l\u00e0 ng\u01b0\u1eddi b\u1ea1n \u0111\u1ed3ng h\u00e0nh tin c\u1eady v\u1edbi t\u00f4i khi tr\u1ea3 l\u1eddi nh\u1eefng c\u00e2u h\u1ecfi nh\u00e2n qu\u1ea3 kh\u00f3 nh\u1eb1n.\n\n* [S\u00e1ch Suy Lu\u1eadn Nh\u00e2n Qu\u1ea3](https://www.hsph.harvard.edu/miguel-hernan/causal-inference-book/)\n\nCu\u1ed1i c\u00f9ng, t\u00f4i c\u0169ng mu\u1ed1n t\u00e1n d\u01b0\u01a1ng Scott Cunningham v\u00e0 v\u00e0 s\u1ea3n ph\u1ea9m xu\u1ea5t s\u1eafc c\u1ee7a \u00f4ng pha tr\u1ed9n Suy Lu\u1eadn Nh\u00e2n Qu\u1ea3 v\u1edbi l\u1eddi tho\u1ea1i Rap:\n\n* [Suy Lu\u1eadn Nh\u00e2n Qu\u1ea3: \u0110\u0129a nh\u1ea1c](https://www.scunning.com/mixtape.html)\n\n# B\u1ea3ng T\u1eeb Vi\u1ebft t\u1eaft \n|Vi\u1ebft t\u1eaft| Ti\u1ebfng Anh | Ti\u1ebfng Vi\u1ec7t |\n| --- | --- | --- | \n|FE|Fixed Effects|FE| \n\n\n# B\u1ea3ng Thu\u1eadt ng\u1eef \n| Thu\u1eadt ng\u1eef | Ti\u1ebfng Anh |\n| --- | --- | \n|bi\u1ebfn|variable| \n|bi\u1ebfn c\u00f4ng c\u1ee5|instrumental-variable, instrumental variable, instrument, instrument variable| \n|bi\u1ebfn gi\u1ea3|dummy, dummy variable| \n|bi\u1ebfn nhi\u1ec5u|confounder, confounding variable| \n|bi\u1ec5n nhi\u1ec5u kh\u00f4ng \u0111\u01b0\u1ee3c \u0111o l\u01b0\u1eddng|unmeasured confounder| \n|b\u1ea3ng|panel| \n|c\u1ea5u tr\u00fac b\u1ea3ng|panel structure| \n|c\u1ed1 \u0111\u1ecbnh|condition on| \n|d\u1eef li\u1ec7u|data| \n|d\u1eef li\u1ec7u b\u1ea3ng|panel data| \n|d\u1eef li\u1ec7u kh\u00f4ng ng\u1eabu nhi\u00ean|non-random data| \n|d\u1eef li\u1ec7u ng\u1eabu nhi\u00ean|random data| \n|d\u1eef li\u1ec7u phi th\u1ef1c nghi\u1ec7m|non experimental data| \n|d\u1eef li\u1ec7u \u0111\u00e3 kh\u1eed gi\u00e1 tr\u1ecb trung b\u00ecnh theo th\u1eddi gian|time-demeaned data| \n|d\u1ef1 \u0111o\u00e1n|predict, prediction| \n|gh\u00e9p c\u1eb7p|matching| \n|gi\u1ea3 thi\u1ebft|assumption| \n|hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh|fixed-effect, fixed effects| \n|h\u1ec7 s\u1ed1 ch\u1eb7n|intercept| \n|h\u1ed3i quy|regression, regress| \n|h\u1ed3i quy tuy\u1ebfn t\u00ednh|linear regression| \n|khung d\u1eef li\u1ec7u|data frame| \n|kh\u00f4ng nhi\u1ec5u c\u00f3 \u0111i\u1ec1u ki\u1ec7n|conditional unconfoundedness| \n|kh\u1eed gi\u00e1 tr\u1ecb trung b\u00ecnh (theo th\u1eddi gian)|deamean| \n|kh\u1eed gi\u00e1 tr\u1ecb trung b\u00ecnh theo th\u1eddi gian|time-demeaned| \n|kinh t\u1ebf l\u01b0\u1ee3ng|econometrics| \n|k\u1ebft qu\u1ea3|outcome| \n|m\u00f4 h\u00ecnh|model| \n|m\u00f4 h\u00ecnh fe|fe model| \n|m\u00f4 h\u00ecnh hi\u1ec7u \u1ee9ng c\u1ed1 \u0111\u1ecbnh|fixed effects model, fixed effect model| \n|m\u00f4 h\u00ecnh h\u1ed3i quy|regression model| \n|m\u00f4 h\u00ecnh h\u1ed3i quy tuy\u1ebfn t\u00ednh|linear regression model| \n|m\u00f4 h\u00ecnh tuy\u1ebfn t\u00ednh|linear model| \n|nh\u00f3m c\u1ee5m|clustered| \n|ph\u1ea7n d\u01b0|error term, residual| \n|quan h\u1ec7 nh\u00e2n qu\u1ea3 ng\u01b0\u1ee3c|reverse causality| \n|quan s\u00e1t|observe, observation| \n|sai s\u1ed1 chu\u1ea9n|standard error| \n|suy lu\u1eadn nh\u00e2n qu\u1ea3|causal inference, causal reasoning| \n|tham s\u1ed1|parameter| \n|tham s\u1ed1 th\u1ef1c|true parameter, argument| \n|thi\u00ean l\u1ec7ch|bias| \n|thi\u00ean l\u1ec7ch thi\u1ebfu bi\u1ebfn|omitted variable bias| \n|thu\u1ed9c t\u00ednh|feature| \n|th\u01b0 vi\u1ec7n|library| \n|t\u1ed5 h\u1ee3p tuy\u1ebfn t\u00ednh|linear combination| \n|v\u00e9c-t\u01a1|vector| \n|\u0111i\u1ec3m xu h\u01b0\u1edbng|propensity score| \n|\u0111\u01b0\u1eddng h\u1ed3i quy|fitted line, regression line| \n|\u0111\u1ed9 d\u1ed1c|slope| \n|\u0111\u1ed9 l\u1ec7ch chu\u1ea9n|standard deviation| \n|\u01b0\u1edbc l\u01b0\u1ee3ng h\u1ec7 s\u1ed1|parameter estimate| \n\n", "meta": {"hexsha": "119d5f92e763fee9581498f7b754e226bde434fd", "size": 157832, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ipynb/13-D\u1eef-li\u1ec7u-B\u1ea3ng-v\u00e0-Hi\u1ec7u-\u1ee9ng-C\u1ed1-\u0111\u1ecbnh-VN.ipynb", "max_stars_repo_name": "vietecon/NhanQuaPython", "max_stars_repo_head_hexsha": "0cf0e78faa9eeef23d8ed2c41125b58cd5a5330b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-11-19T11:59:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-20T02:06:07.000Z", "max_issues_repo_path": "ipynb/13-D\u1eef-li\u1ec7u-B\u1ea3ng-v\u00e0-Hi\u1ec7u-\u1ee9ng-C\u1ed1-\u0111\u1ecbnh-VN.ipynb", "max_issues_repo_name": "vietecon/NhanQuaPython", "max_issues_repo_head_hexsha": "0cf0e78faa9eeef23d8ed2c41125b58cd5a5330b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ipynb/13-D\u1eef-li\u1ec7u-B\u1ea3ng-v\u00e0-Hi\u1ec7u-\u1ee9ng-C\u1ed1-\u0111\u1ecbnh-VN.ipynb", "max_forks_repo_name": "vietecon/NhanQuaPython", "max_forks_repo_head_hexsha": "0cf0e78faa9eeef23d8ed2c41125b58cd5a5330b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-11-21T09:09:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T12:25:37.000Z", "avg_line_length": 157832.0, "max_line_length": 157832, "alphanum_fraction": 0.8045960262, "converted": true, "num_tokens": 15523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.08151975374329136, "lm_q1q2_score": 0.03948654518841448}}
{"text": "```python\n#remove cell visibility\nfrom IPython.display import HTML\ntag = HTML('''\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.''')\ndisplay(tag)\n```\n\n\n\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.\n\n\n\n```python\n%matplotlib inline\nimport control\nimport numpy\nimport sympy as sym\nfrom IPython.display import display, Markdown\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\n\n\n#print a matrix latex-like\ndef bmatrix(a):\n     \"\"\"Returns a LaTeX bmatrix - by Damir Arbula (ICCT project)\n\n     :a: numpy array\n     :returns: LaTeX bmatrix as a string\n     \"\"\"\n     if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n     lines = str(a).replace('[', '').replace(']', '').splitlines()\n     rv = [r'\\begin{bmatrix}']\n     rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n     rv +=  [r'\\end{bmatrix}']\n     return '\\n'.join(rv)\n\n\n# Display formatted matrix: \ndef vmatrix(a):\n    if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n    lines = str(a).replace('[', '').replace(']', '').splitlines()\n    rv = [r'\\begin{vmatrix}']\n    rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n    rv +=  [r'\\end{vmatrix}']\n    return '\\n'.join(rv)\n\n\n#matrixWidget is a matrix looking widget built with a VBox of HBox(es) that returns a numPy array as value !\nclass matrixWidget(widgets.VBox):\n    def updateM(self,change):\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.M_[irow,icol] = self.children[irow].children[icol].value\n                #print(self.M_[irow,icol])\n        self.value = self.M_\n\n    def dummychangecallback(self,change):\n        pass\n    \n    \n    def __init__(self,n,m):\n        self.n = n\n        self.m = m\n        self.M_ = numpy.matrix(numpy.zeros((self.n,self.m)))\n        self.value = self.M_\n        widgets.VBox.__init__(self,\n                             children = [\n                                 widgets.HBox(children = \n                                              [widgets.FloatText(value=0.0, layout=widgets.Layout(width='90px')) for i in range(m)]\n                                             ) \n                                 for j in range(n)\n                             ])\n        \n        #fill in widgets and tell interact to call updateM each time a children changes value\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        #value = Unicode('example@example.com', help=\"The email value.\").tag(sync=True)\n        self.observe(self.updateM, names='value', type= 'All')\n        \n    def setM(self, newM):\n        #disable callbacks, change values, and reenable\n        self.unobserve(self.updateM, names='value', type= 'All')\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].unobserve(self.updateM, names='value')\n        self.M_ = newM\n        self.value = self.M_\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        self.observe(self.updateM, names='value', type= 'All')        \n\n                #self.children[irow].children[icol].observe(self.updateM, names='value')\n\n             \n#overlaod class for state space systems that DO NOT remove \"useless\" states (what \"professor\" of automatic control would do this?)\nclass sss(control.StateSpace):\n    def __init__(self,*args):\n        #call base class init constructor\n        control.StateSpace.__init__(self,*args)\n    #disable function below in base class\n    def _remove_useless_states(self):\n        pass\n```\n\n## Autonomous Underwater Vehicle (AUV) depth control\n\nDynamics of the pitch angle $\\theta$ of an Autonomous Underwater Vehicle (AUV) can be modelled as:  \n$$\nJ_y\\ddot{\\theta}=\u2212D\\dot{\\theta}+CV\\gamma,\n$$\nwhere $J_y=8.333$ kg$\\text{m}^2$ is the vehicle moment of inertia around the pitch axis, $D = 30$ Nms the drag coefficient, $C=45$ Ns the tail fin effectiveness coefficient, $\\gamma$ the tail fin angle (expressed in radians and to be kept within $\\pm10\u00b0$), and $V$ current cruising speed in m/s. \n\nThe vertical (heave) velocity $w$ of an AUV can be modelled approximately as: \n$$\nw = V\\theta.\n$$\n\nFor safety reasons, the pitch angle should never exceed $\\pm20\u00b0$ during operation. Pitch angle and depth ($z$) are measured by a Navigation Filter.\n\nThe dynamics equations in state space form are\n\\begin{cases}\n    \\dot{x} = \\begin{bmatrix} -D/J_y & 0 & 0 \\\\ 1 & 0 & 0 \\\\ 0 & V & 0 \\end{bmatrix}x + \\begin{bmatrix} CV/J_y \\\\ 0 \\\\ 0 \\end{bmatrix}u\\\\\n    y = \\begin{bmatrix} 0 & 1 & 0 \\\\ 0 & 0 & 1 \\end{bmatrix}x,\n\\end{cases}\n\nwhere $x=\\begin{bmatrix} x_1 & x_2 & x_3 \\end{bmatrix}^T=\\begin{bmatrix} \\dot{\\theta} & \\theta & z \\end{bmatrix}^T$ and $u=\\gamma$.\n\nConsidering $V=1$ m/s constant, we want to develop a regulator for $z$ which allows to have zero steady-state error in response to a step position request.\n\n### Regulator design\n#### Controller design\n\nTo meet the requirements we first add a new state:\n$$\n\\dot{x_4} = z-y_d = x_3 - y_d\n$$\nThe resulting augmented system is thus:\n\\begin{cases}\n    \\dot{x_a} = \\begin{bmatrix} -D/J_y & 0 & 0 & 0 \\\\ 1 & 0 & 0 & 0 \\\\ 0 & V & 0 & 0 \\\\ 0 & 0 & 1 & 0 \\end{bmatrix}x_a + \\begin{bmatrix} CV/J_y & 0 \\\\ 0 & 0 \\\\ 0 & 0 \\\\ 0 & -1 \\end{bmatrix} \\begin{bmatrix} u \\\\ y_d \\end{bmatrix}\\\\\n    y = \\begin{bmatrix} 0 & 1 & 0 & 0 \\\\ 0 & 0 & 1 & 0 \\\\ 0 & 0 & 0 & 1 \\end{bmatrix}x_a,\n\\end{cases}\n\nwhere $x_a = \\begin{bmatrix} x_1 & x_2 & x_3 & x_4 \\end{bmatrix}^T = \\begin{bmatrix} \\dot{\\theta} & \\theta & z & x_4 \\end{bmatrix}^T$.\n\nWith the first input $u$, since the system is controllable, we place the poles in order to stabilize the system and respect the limits on $u$ ($\\pm10\u00b0$) and $\\theta$ ($\\pm20\u00b0$) when giving a step of $y_d=1$ m. A possible solution is to place the poles in $-5.9$, $-0.9$ and $-0.63\\pm0.70i$.\n\n#### Observer design\n\nWe have the measurements of $x_2$, $x_3$ and $x_4$ so we need only to estimate $x_1$. We can work with the subsystem \n$x_l =\\begin{bmatrix} x_1 & x_2 \\end{bmatrix}^T$, $\\dot{x_l}=A_lx_l + B_lu$ and $y_l = x_2 = C_lx_l$. Defining $L=\\begin{bmatrix} l_1 & l_2 \\end{bmatrix}^T$ we can calculate the eigenvalues $\\lambda_1$ and $\\lambda_2$ of $A_l-LC_l$ and solve for $l_1$ and $l_2$:\n\\begin{cases}\nl_1 = \\lambda_1\\lambda_2 + D\\lambda_1/J_y + D\\lambda_2/J_y + D^2/J_y^2 \\\\\nl_2 = -\\lambda_1 - \\lambda_2 - D/J_y \\, .\n\\end{cases}\n\nWe choose $\\lambda_1 = \\lambda_2 = -15$.\n\n### How to use this notebook?\n- Try, changing the poles of the controller, to meet the requirements with $V = 0.75$ m/s.\n- Verify the behaviour of the regulator in presence of an initial error in the estimate and try to improve its performance.\n\n\n```python\n# Preparatory cell\n\nX0 = numpy.matrix('0.0')\nK = numpy.matrix([0,0,0,0])\nL = numpy.matrix([[0],[0]])\n\nX0w = matrixWidget(1,1)\nX0w.setM(X0)\nKw = matrixWidget(1,4)\nKw.setM(K)\nLw = matrixWidget(2,1)\nLw.setM(L)\n\n\neig1c = matrixWidget(1,1)\neig2c = matrixWidget(2,1)\neig3c = matrixWidget(1,1)\neig4c = matrixWidget(2,1)\neig1c.setM(numpy.matrix([-5.7])) \neig2c.setM(numpy.matrix([[-0.63],[-0.70]]))\neig3c.setM(numpy.matrix([-0.9]))\neig4c.setM(numpy.matrix([[-0.63],[-0.70]]))\n\neig1o = matrixWidget(1,1)\neig2o = matrixWidget(2,1)\neig1o.setM(numpy.matrix([-15.])) \neig2o.setM(numpy.matrix([[-15.],[0.]]))\n```\n\n\n```python\n# Misc\n\n#create dummy widget \nDW = widgets.FloatText(layout=widgets.Layout(width='0px', height='0px'))\n\n#create button widget\nSTART = widgets.Button(\n    description='Test',\n    disabled=False,\n    button_style='', # 'success', 'info', 'warning', 'danger' or ''\n    tooltip='Test',\n    icon='check'\n)\n                       \ndef on_start_button_clicked(b):\n    #This is a workaround to have intreactive_output call the callback:\n    #   force the value of the dummy widget to change\n    if DW.value> 0 :\n        DW.value = -1\n    else: \n        DW.value = 1\n    pass\nSTART.on_click(on_start_button_clicked)\n\n# Define type of method \nselm = widgets.Dropdown(\n    options= ['Set K and L', 'Set the eigenvalues'],\n    value= 'Set the eigenvalues',\n    description='',\n    disabled=False\n)\n\n# Define the number of complex eigenvalues\nselec = widgets.Dropdown(\n    options= ['0 complex eigenvalues', '2 complex eigenvalues', '4 complex eigenvalues'],\n    value= '2 complex eigenvalues',\n    description='Eig controller:',\n    disabled=False\n)\nseleo = widgets.Dropdown(\n    options= ['0 complex eigenvalues', '2 complex eigenvalues'],\n    value= '0 complex eigenvalues',\n    description='Eig observer:',\n    disabled=False\n)\n\n#define type of ipout \nselu = widgets.Dropdown(\n    options=['impulse', 'step', 'sinusoid', 'square wave'],\n    value='step',\n    description='Type of reference:',\n    style = {'description_width': 'initial'},\n    disabled=False\n)\n# Define the values of the input\nu = widgets.FloatSlider(\n    value=1,\n    min=0,\n    max=4,\n    step=0.1,\n    description='',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.1f',\n)\nv = widgets.FloatSlider(\n    value=1,\n    min=0.5,\n    max=4,\n    step=0.1,\n    description=r'$V$:',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.1f',\n)\nperiod = widgets.FloatSlider(\n    value=0.5,\n    min=0.001,\n    max=10,\n    step=0.001,\n    description='Period: ',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.2f',\n)\n\nsimTime = widgets.FloatText(\n    value=10,\n    description='',\n    disabled=False\n)\n```\n\n\n```python\n# Support functions\n\ndef eigen_choice(selec,seleo):\n    if selec == '0 complex eigenvalues':\n        eig1c.children[0].children[0].disabled = False\n        eig2c.children[1].children[0].disabled = True\n        eig3c.children[0].children[0].disabled = False\n        eig4c.children[0].children[0].disabled = False\n        eig4c.children[1].children[0].disabled = True\n        eigc = 0\n    if seleo == '0 complex eigenvalues':\n        eig1o.children[0].children[0].disabled = False\n        eig2o.children[1].children[0].disabled = True\n        eigo = 0\n    if selec == '2 complex eigenvalues':\n        eig1c.children[0].children[0].disabled = False\n        eig2c.children[1].children[0].disabled = False\n        eig3c.children[0].children[0].disabled = False\n        eig4c.children[0].children[0].disabled = True\n        eig4c.children[1].children[0].disabled = True\n        eigc = 2\n    if seleo == '2 complex eigenvalues':\n        eig1o.children[0].children[0].disabled = True\n        eig2o.children[1].children[0].disabled = False\n        eigo = 2\n    if selec == '4 complex eigenvalues':\n        eig1c.children[0].children[0].disabled = True\n        eig2c.children[1].children[0].disabled = False\n        eig3c.children[0].children[0].disabled = True\n        eig4c.children[0].children[0].disabled = False\n        eig4c.children[1].children[0].disabled = False\n        eigc = 4\n    return eigc, eigo\n\ndef method_choice(selm):\n    if selm == 'Set K and L':\n        method = 1\n        selec.disabled = True\n        seleo.disabled = True\n    if selm == 'Set the eigenvalues':\n        method = 2\n        selec.disabled = False\n        seleo.disabled = False\n    return method\n```\n\n\n```python\nD = 30\nc = 45\nV = 1\nJy = 8.333\n\nA = numpy.matrix([[-D/Jy, 0, 0, 0],\n                  [1, 0, 0, 0],\n                  [0, V, 0, 0],\n                  [0, 0, 1, 0]])\nBu = numpy.matrix([[c*V/Jy],[0],[0],[0]])\nBref = numpy.matrix([[0],[0],[0],[-1]])\nC = numpy.matrix([0,0,1,0])\n\nAl = numpy.matrix([[-D/Jy, 0],\n                  [1, 0]])\nCl = numpy.matrix([0,1])\n\ndef main_callback2(v, X0w, K, L, eig1c, eig2c, eig3c, eig4c, eig1o, eig2o, u, period, selm, selec, seleo, selu, simTime, DW):\n    eigc, eigo = eigen_choice(selec,seleo)\n    method = method_choice(selm)\n    \n    A = numpy.matrix([[-D/Jy, 0, 0, 0],\n                  [1, 0, 0, 0],\n                  [0, v, 0, 0],\n                  [0, 0, 1, 0]])\n    Bu = numpy.matrix([[c*v/Jy],[0],[0],[0]])\n    \n    if method == 1:\n        solc = numpy.linalg.eig(A-Bu*K)\n        solo = numpy.linalg.eig(Al-L*Cl)\n    if method == 2:\n        if eig1c[0,0]==eig2c[0,0] or eig1c[0,0]==eig3c[0,0] or eig1c[0,0]==eig4c[0,0]:\n            eig1c[0,0] -= 0.0001\n        if eig2c[0,0]==eig3c[0,0] or eig2c[0,0]==eig4c[0,0]:\n            eig3c[0,0] -= 0.0002\n        if eigc == 0:\n            K = control.acker(A, Bu, [eig1c[0,0], eig2c[0,0], eig3c[0,0], eig4c[0,0]])\n            Kw.setM(K)\n        if eigc == 2:\n            K = control.acker(A, Bu, [eig3c[0,0],\n                                      eig1c[0,0],\n                                      numpy.complex(eig2c[0,0], eig2c[1,0]), \n                                      numpy.complex(eig2c[0,0],-eig2c[1,0])])\n            Kw.setM(K)\n        if eigc == 4:\n            K = control.acker(A, Bu, [numpy.complex(eig4c[0,0], eig4c[1,0]), \n                                      numpy.complex(eig4c[0,0],-eig4c[1,0]),\n                                      numpy.complex(eig2c[0,0], eig2c[1,0]), \n                                      numpy.complex(eig2c[0,0],-eig2c[1,0])])\n            Kw.setM(K)\n        if eigo == 0:\n            temp1 = eig1o[0,0]\n            temp2 = eig2o[0,0]\n            L = numpy.matrix([[temp1*temp2 + D*temp1/Jy + D*temp2/Jy + D**2/Jy**2], [-temp1 - temp2 - D/Jy]]) \n            Lw.setM(L)\n        if eigo == 2:\n            temp1 = numpy.complex(eig2o[0,0], eig2o[1,0])\n            temp2 = numpy.complex(eig2o[0,0],-eig2o[1,0])\n            L = numpy.matrix([[temp1*temp2 + D*temp1/Jy + D*temp2/Jy + D**2/Jy**2], [-temp1 - temp2 - D/Jy]]) \n            L = numpy.real(L)\n            Lw.setM(L)\n            \n    sys = sss(A,numpy.hstack((Bu,Bref)),[[0,1,0,0],[0,0,1,0],[0,0,0,1]],[[0,0],[0,0],[0,0]])\n    syse = sss(Al-L*Cl,numpy.hstack((Bu[0:2],L)),[1,0],[0,0])\n    sysc = sss(0,[0,0,0,0],0,-K)\n    sys_append = control.append(sys,syse,sysc)\n    sys_CL = control.connect(sys_append,\n                             [[1,5],[3,5],[4,1],[5,4],[6,1],[7,2],[8,3]],\n                             [2],\n                             [2,5])\n    \n    X0w1 = numpy.zeros((6,1))\n    X0w1[4,0] = X0w\n    if simTime != 0:\n        T = numpy.linspace(0, simTime, 10000)\n    else:\n        T = numpy.linspace(0, 1, 10000)\n      \n    if selu == 'impulse': #selu\n        U = [0 for t in range(0,len(T))]\n        U[0] = u\n        T, yout, xout = control.forced_response(sys_CL,T,U,X0w1)\n    if selu == 'step':\n        U = [u for t in range(0,len(T))]\n        T, yout, xout = control.forced_response(sys_CL,T,U,X0w1)\n    if selu == 'sinusoid':\n        U = u*numpy.sin(2*numpy.pi/period*T)\n        T, yout, xout = control.forced_response(sys_CL,T,U,X0w1)\n    if selu == 'square wave':\n        U = u*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n        T, yout, xout = control.forced_response(sys_CL,T,U,X0w1)\n    \n    try:\n        step_info_dict = control.step_info(sys_CL[0,0],SettlingTimeThreshold=0.05,T=T)\n        print('Step info: \\n\\tRise time =',step_info_dict['RiseTime'],'\\n\\tSettling time (5%) =',step_info_dict['SettlingTime'],'\\n\\tOvershoot (%)=',step_info_dict['Overshoot'])\n        print('Max x_2 value (% of 20\u00b0)=', max(abs(xout[1]))/(numpy.pi/180*20)*100)\n        print('Max u value (% of 10\u00b0)=', max(abs(yout[1]))/(numpy.pi/180*10)*100)\n    except:\n        print(\"Error in the calculation of step info.\")\n    \n    fig = plt.figure(num='Simulation1', figsize=(14,12))\n    \n    fig.add_subplot(221)\n    plt.title('Output response')\n    plt.ylabel('Output')\n    plt.plot(T,yout[0],T,U,'r--')\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$y$','Reference'])\n    plt.grid()\n    \n    fig.add_subplot(222)\n    plt.title('Input')\n    plt.ylabel('$u$')\n    plt.plot(T,yout[1])\n    plt.plot(T,[numpy.pi/180*10 for i in range(len(T))],'r--')\n    plt.plot(T,[-numpy.pi/180*10 for i in range(len(T))],'r--')\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(223)\n    plt.title('States response')\n    plt.ylabel('States')\n    plt.plot(T,xout[0],\n             T,xout[1],\n             T,xout[2],\n             T,xout[3],\n             T,[numpy.pi/180*20 for i in range(len(T))],'r--',\n             T,[-numpy.pi/180*20 for i in range(len(T))],'r--')\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$x_{1}$','$x_{2}$','$x_{3}$','$x_{4}$','+lim $x_2$','-lim $x_2$'])\n    plt.grid()\n    \n    fig.add_subplot(224)\n    plt.title('Estimated errors')\n    plt.ylabel('Error')\n    plt.plot(T,xout[4]-xout[0])\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$e_{1}$'])\n    plt.grid()\n    #plt.tight_layout()\n   \nalltogether2 = widgets.VBox([widgets.HBox([selm, \n                                          selec,\n                                          seleo,\n                                          selu]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.VBox([widgets.Label('K:',border=3), Kw, \n                                                        widgets.Label('Eigenvalues:',border=3),\n                                                        widgets.HBox([eig1c, \n                                                                      eig2c, \n                                                                      eig3c,\n                                                                      eig4c])]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.VBox([widgets.HBox([widgets.Label('L:',border=3), Lw, widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Eigenvalues:',border=3), \n                                          eig1o, \n                                          eig2o,\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('X0 est.:',border=3), X0w]),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                                       widgets.HBox([\n                                          widgets.VBox([widgets.Label('Simulation time [s]:',border=3)]),\n                                          widgets.VBox([simTime])])])]),\n                                          widgets.Label(' ',border=3)]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.Label('Reference [m]:',border=3),u,\n                                          v]),\n                            widgets.HBox([period,START])])\nout2 = widgets.interactive_output(main_callback2, {'v':v, 'X0w':X0w, 'K':Kw, 'L':Lw,\n                                                   'eig1c':eig1c, 'eig2c':eig2c, 'eig3c':eig3c, 'eig4c':eig4c, \n                                                   'eig1o':eig1o, 'eig2o':eig2o, \n                                                   'u':u, 'period':period, 'selm':selm, 'selec':selec, 'seleo':seleo, 'selu':selu, 'simTime':simTime, 'DW':DW})\nout2.layout.height = '880px'\ndisplay(out2, alltogether2)\n```\n\n\n    Output(layout=Layout(height='880px'))\n\n\n\n    VBox(children=(HBox(children=(Dropdown(index=1, options=('Set K and L', 'Set the eigenvalues'), value='Set the\u2026\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "7d3600541b9c2bbef31479c2818d2cbf7f9f7666", "size": 27665, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_en/examples/04/SS-50-AUV_depth_control.ipynb", "max_stars_repo_name": "ICCTerasmus/ICCT", "max_stars_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-22T18:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:10:22.000Z", "max_issues_repo_path": "ICCT/ENG/examples/04/SS-50-AUV_depth_control.ipynb", "max_issues_repo_name": "tuxsaurus/ICCT", "max_issues_repo_head_hexsha": "30d1aea4fb056c9736c9b4c5a0f50fff14fa6382", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICCT/ENG/examples/04/SS-50-AUV_depth_control.ipynb", "max_forks_repo_name": "tuxsaurus/ICCT", "max_forks_repo_head_hexsha": "30d1aea4fb056c9736c9b4c5a0f50fff14fa6382", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-24T11:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T16:36:18.000Z", "avg_line_length": 41.6015037594, "max_line_length": 308, "alphanum_fraction": 0.4626423279, "converted": true, "num_tokens": 6062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.10230469968165563, "lm_q1q2_score": 0.039378321345250863}}
{"text": "# Python, numpy, and Nifti-images\n\nThis tutorial is about the programming language Python and how to use it for psychology/neuroimaging analysis. Part 2 of this tutorial is a quite extensive recap of basic Python syntax and constructs; this should be doable for students who are comfortable with programming (e.g., from previous experience with other programming languages). If you're *not* comfortable with programming, or you notice during this tutorial that you get stuck often, we recommend working through the [Codecademy](https://www.codecademy.com/learn/python) up to and including unit 8 (`loops`). You *don't* have to do the quizzes (because you need to pay for that).\n\nGiven that you have learned the basics of Python's syntax, this tutorial will recap some of the most important aspects of Python (section 2.: General Python). Then, 'numpy' (Python's scientific computing package) is discussed and explained and followed by a section on 'Matplotlib' (Python's plotting package). Finally, this tutorial ends with a section on how to interact with Nifti-files - the file format used by most (MRI) neuroimaging data.\n\n\n## What this tutorial is about\nThis tutorial will recap some of the most important aspects of Python (section 2: General Python). Then, 'numpy' (Python's numeric computing package) is discussed and explained and followed by a section on 'Matplotlib' (Python's plotting package). Finally, this tutorial ends with a section on how to work with Nifti-files - the file format used by most (MRI) neuroimaging software packages.\n\nAt the end of this tutorial, you are able to implement any computation/routine necessary for complex fMRI analysis using a combination of basic Python and Numpy.\n\n### Contents:\n\n1. Jupyter notebooks\n2. General Python\n3. Numpy\n4. Matplotlib / plotting\n5. Interacting with Nifti-files\n\nBut before anything else, let's get more familiar with the Jupyter notebook environment!\n\n## 1. Jupyter Notebooks\n\nSo, what are Jupyter notebooks, actually? Basically, using Jupyter notebooks is like using the web-browser as a kind of editor from which you can run Python code, similar to the MATLAB interactive editor or RStudio. The cool thing about these notebooks is that they allow you to mix code \"cells\" (see below) and text \"cells\" (such as this one). The (printed) output from code blocks are displayed right below the code blocks themselves. \n\nJupyter notebooks have two **modes**: edit mode and command mode.\n\n- *Command mode* is indicated by a grey cell border with a blue left margin (as is the case now!): When you are in command mode, you are able to edit the notebook as a whole, but not type into individual cells. Most importantly, in command mode, the keyboard is mapped to a set of shortcuts that let you perform notebook and cell actions efficiently (some shortcuts in command mode will be discussed later!). Enter command mode by pressing **Esc** or using the mouse to click outside a cell\u2019s editor area; <br><br>\n- *Edit mode* is indicated by a green cell border and a prompt showing in the editor area: When a cell is in edit mode, you can type into the cell, like a normal text editor. Enter edit mode by pressing Enter or using the mouse to double-click on a cell\u2019s editor area.\n\nWhen you're reading and scrolling through the tutorials, you'll be in the command mode mostly. But once you have to program (or write) stuff yourself, you have to switch to edit mode. But we'll get to that. First, we'll explain something about the two types of cells: code cells and text cells.\n\n### 1.1. Code cells\n\nCode cells are the place to write your Python code, similar to MATLAB 'code sections' (which are usually deliniated by %%). Importantly, unlike the interactive editors in RStudio and MATLAB, a code cell in Jupyter notebooks can only be run all at once. This means you cannot run it line-by-line, but you have to run the entire cell!\n\n#### 1.1.1. Running cells\nLet's look at an example. Below, you see a code-cell with two print-statements. To run the cell, select it (i.e., the cell should have a green or blue frame around it; doesn't matter whether you're in edit or command mode), and click on the \"&#9654; `Run`\" icon or press `ctr+Enter`). Try it with the cell below!\n\nYou can also try it with the cell way at the top where you entered your name and student number...\n\n\n```python\nprint(\"I'm printing Python code\")\nprint(3 + 3)\n```\n\n    I'm printing Python code\n    6\n\n\n(You might be confused because we use the `print` statement with brackets -- `print()` -- while you've learned in Codecademy that you should use `print` without brackets. This is because Codecademy uses an old version of Python, Python2.7, while we use a newer version, Python3.5. In the new version, `print()` should be used with brackets!)\n\n#### 1.1.2. Stop running/execution of cells\nSometimes, you might want to quit the execution of a code-cell because it's taking too long (or worse, you created an infinite loop!). To do so, click the stop icon &#9632; in the top menu!\n\n#### 1.1.3. Restarting the kernel\nSometimes, you accidentally 'crash' the notebook, for example when creating an infinite loop or when loading in too much data. You know your notebook 'crashed' when stopping the cell (&#9632;) does not work and your cell continues its execution, as evident by the `In [*]:` prompt next to the cell. In those cases, you need to completely restart the notebook, or in programming lingo: you need to \"restart the kernel\". To do so, click `Kernel` and `Restart`.\n\nImportantly, when you restart the kernel, it will keep all text/code that you've written, but it will **not** remember all the variables that you defined before restarting the kernel, including the imports. So if you restart the kernel, you will have to re-import everything (e.g. run `import numpy as np` again).\n\n#### 1.1.3. Inserting cells\nAs you can see in the code cell above, you can only run the entire cell (i.e. both print statements). Sometimes, of course, you'd like to organise code across multiple cells. To do this, you can simply add new blocks (cells) by selecting \"Insert --> Insert Cell Below\" on the toolbar (or use the shortcut ctr+B when you're in command mode; \"B\" refers to \"below\"). This will insert a new code cell below the cell you have currently highlighted (the currently highlighted cell has a blue box around it). \n\nTry inserting a cell below and write some code (e.g. `print(10 * 10)`).\n\n\n```python\n10/5\n```\n\n\n\n\n    2.0\n\n\n\n#### 1.1.4. Inline plotting\nAnother cool feature of Jupyter notebooks is that you can display figures in the same notebook! You simply define some plots in a code cell and it'll output the plot below it.\n\nCheck it out by executing (click the \"play\" button or ctr+Enter) the next cell.\n\n\n```python\n# We'll get to what the code means later in the tutorial\nimport matplotlib.pyplot as plt # The plotting package 'Matplotlib' is discussed in section 3!\n\n# This command makes sure that the figure is plotted in the notebook instead of in a separate window!\n%matplotlib inline \n\n# Now, let's plot something\nplt.plot(range(10))\nplt.show()\n```\n\n### 1.2. Text ('markdown') cells\nNext to code cells, jupyter notebooks allow you to write text in so-called \"markdown cells\" (the cell this text is written in is, obviously, also a markdown cell). Markdown cells accept plain text and can be formatted by special markdown-syntax. A couple of examples:\n\n\\# One hash creates a large heading <br>\n\\#\\# Two hashes creates a slightly smaller heading (this goes up to four hashes)\n\nBold text can be created by enclosing text in \\*\\*double asterisks\\*\\* and italicized text can be created by enclosing text in \\*single asterisks\\*. You can even include URLs and insert images from the web; check this [link](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) for a cheatsheet with markdown syntax and options! All the special markdown-syntax and options will be converted to readable text *after running the text cell* (again, by pressing the \"play\" icon in the toolbar or by ctr+Enter).\n\nTo insert a text (markdown) cell, insert a new cell (\"Insert --> Insert Cell Below\" or ctr+B). Then, *while highlighting the new cell*, press \"Cell --> Cell Type --> Markdown\" on the toolbar on top of the notebook (or, while in command mode, press ctr+m; \"m\" refers to \"markdown\"). You should see the prompt (the **`In [ ]`** thingie) disappear. Voil\u00e0, now it's a text cell!\n\nTry it below! Insert a new markdown cell and try to write the following:\n\n\"**OMG**, this is th emost awesome Python tutorial *ever*.\"\n\n\"**OMG**, this is the most... *ever*\"\n\n### 1.3. Getting help\nThroughout this course, you'll encounter situations in which you have to use functions that you'd like to get some more information on, e.g. which inputs it expects. To get help on any python function you'd like to use, you can simply write the function-name appended with a \"?\" and run the cell. This will open a window below with the \"docstring\" (explanation of the function). Take for example the built-in function **`len()`**. To get some more information, simply type `len?` in a code cell and run the cell.\n\nTry it out yourself: create a code cell below, type `len?` and check the output!\n\n\n```python\nlen?\n```\n\nIf this method (i.e. appending with \"?\") does not give you enough information, try to google the name of the function together with 'python' and, if you know from which package the function comes, the name of that package. For instance, for len() you could google: ['python len()'](http://lmgtfy.com/?q=python+len), or later when you'll use the numpy package, and you'd like to know how the `numpy.arange` function works you could google: 'python numpy arange'. \n\n** REMEMBER: Google is your friend! Please try to google things first, before you ask your classmates and your tutors! **\n\nThe online python community is huge, so someone definitely already wondered about something you might be struggling with.\n\n### 1.4. Saving your work & closing down the notebook\nYou're running and actively editing the notebook in a browser, but remember that it's still just a file located on your account on the server (that you're accessing through Jupyterhub). Therefore, for your work to persist, you need to save the notebook once in a while (and definitely before closing the notebook). To save, simply press the floppy-disk image in the top-left (or do ctr+s). If you want to close your notebook, simply close the browser. \n\n*However, when you close the browser, the notebook is still \"running\" in the background in your terminal where you started it!* \n\nTo stop the notebook from running after you've closed it, go to the `Running` tab, and click the `Shutdown` button next to the notebook that you want to stop. \n\nAlright. Now that you've had your first contact with Jupyter notebooks - let's talk about about exercises and assignments.\n\n## A note on exercises (ToDo/ToThink) and assignments\nYou'll encounter different types of exercises throughout the notebook, being:\n\n- <font color='orange'>ToDos</font> : short programming exercises, either zero or for a few points\n- <font color='blue'>ToThinks</font>: questions about the (preceding) text/material, either zero or for a few points\n- <font color='red'>Assignments</font>: a larger programming exercise (sometimes with additional questions), usually for a larger amount of points\n\nWe highly recommend doing/answering the ToDos/ToThinks, not only because they are worth points, but also because they are designed to improve your understanding of the material!\n\nAnyway, a \"ToDo\" would look something like this:\n\n<div class=\"alert alert-warning\">\n<b>ToDo</b> (0 points)\n</div>\nIn the code-cell below, set the variable `x` to 5 and remove the `raise AssertionError` statement below.\n\n\n```python\nx = 5\nx\n```\n\n\n\n\n    5\n\n\n\nThen, *after* each code-cell corresponding to the ToDo, there are one or more code-cell(s) with \"tests\" written by us. These tests may provide you with feedback about whether you implemented the \"ToDo\" correctly, and optionally gives you some hints on how to solve your error(s). If you run this cell and you don't get any errors, you did it correctly and you'll receive the point(s) for that ToDo. If it gives any errors, try to use the information from the error and/or print statements to solve the ToDo. \n\nThese tests are usually implemented as a set of `assert` statements, which 'assert' whether a specific statement is true. If it evaluates to `False`, then that means you've made an error. For example, for the above `ToDo`, we simply evaluated the statement `assert(x == 5)` to check whether you set `x` to 5 correctly, as is shown in the cell below:\n\n\n```python\n''' Checks whether the above ToDo is correct. '''\ntry:\n    assert(x == 5)\nexcept AssertionError as e:\n    print(\"x does not evaluate to 5! Did you replace 'not yet 5' with 5?\")\n    raise(e)\nelse:\n    print(\"Well done!\")\n```\n\n**Note**: each *ToDo* is explicitly tested, so you can always check your answer (and continue trying until you get it right). \n\nNow, let's try another one, but this time for real! It's a super simple one, so use this to earn a free point. Note that it is followed by two test-cells, which test different aspects of your implementation (each passed test gives you 0.5 points).\n\n<div class=\"alert alert-warning\">\n<b>ToDo</b> (1 point)\n</div>\nIn the code-cell below, set the variable `y` to `x * 2`, so you have to replace `None` with `x * 2` (yes, this is as easy as it sounds).\n\n\n```python\nx = 2\ny = x * 2\n```\n\n\n```python\n''' This tests the above ToDo. '''\ntry:\n    assert(y == x * 2)\nexcept AssertionError as e:\n    print(\"y does not evaluate to x * 2 (i.e., 4)! Did you replace y with x * 2?\")\n    raise(e)\nelse:\n    print(\"Well done!\")\n```\n\n    Well done!\n\n\n\n```python\n''' This tests the above ToDo as well. '''\ntry:\n    assert(isinstance(y, int))\nexcept AssertionError as e:\n    print(\"y doesn't seem to be an integer (it is of type %s; make sure it is!\" % (type(y)))\n    raise(e)\nelse:\n    print(\"Well done!\")\n```\n\n    Well done!\n\n\nThroughout the notebook you'll encounter several 'ToDos' - some are worth points, some don't. In addition to these 'ToDos', you'll also encounter 'ToThinks', which are short questions about the material, meant to make you think about what you're doing. Like the 'ToDos', some of these are worth points, others don't. Each 'ToThink' cell is followed by a markdown-cell in which you can write your answer. Obviously, these answers cannot be automatically tested, so there won't be a test-cell with `asserts`. These 'ToThinks' are later (by us) graded manually. \n\nA typical 'ToThink' may look like this:  \n\n<div class='alert alert-info'>\n<b>ToThink</b> (1 point)\n</div>\nWhat's your name? Please write it in the text-cell below.\n\nTomas Knapen\n\nMake sure you actually write your name in the cell above for another free point! (You'll have to double-click the text-cell to go into 'edit mode' and replace 'YOUR ANSWER HERE' with your name.)\n\nNext to 'ToDos' and 'ToThinks', there are Assignments. These are basically just a collection of programming exercises and/or open questions, each with a certain amount of points associated with it. You'll encounter assignments usually at the end of a specific section. Usually, altogether these assignments are worth substantially more points than 'ToDos' or 'ToThinks'. \n\nAn assigment may look like this:\n\n<div class='alert alert-danger'>\n<b>Assignment</b> (5 points)\n</div>\nThis is an example assignment; it's not actually worth any points. In a real assignment, you would see one or more coding assignments or open questions below. \n\nAlright, by now you should known enough to start with section 2: a recap of basic Python syntax! (As we mentioned earlier, if you find this section too difficult, it might help to do the Codecademy Python course, up to and including section 8, before you go on!)\n\n## 2. General Python\nThis section will provide short tutorial on basic Python syntax and concepts (if you've done Codecademy, this should all be familiar).\n\nHere, we will cover:\n\n* Python data types (integers, floats, lists, dictionaries)\n* Python functions\n* Python classes\n* Conditionals (if-then-else)\n* Loops (for-loop, list-comprehensions)\n* Imports\n\n### 2.1. Structure of Python\n\nPython is a multipurpose programming language, meaning it can be used for almost anything. While R is mostly used for statistics, and php is used for web programming only, Python is a general language, specified by the packages you add on to it (using import statements). So, \"pure\" Python provides some basic functionality, but Python's versatility comes from specialized packages for almost any purpose. \n\nFor example:\n* the [scipy](https://www.scipy.org/) package provides functionality for scientific computing (e.g. statistics, signal processing);\n* the [numpy](http://www.numpy.org/) package provides data structures and functionality for (very fast) numeric computing (e.g. multidimensional numeric array computations, some linear algebra);\n* the [matplotlib](http://matplotlib.org/) package provides plotting functions;\n* and various specialied neuroimaging packages provide functionality to work and analyze (f)MRI (e.g. [nibabel](http://nipy.org/nibabel/) and [nipype](http://nipy.org/nipype)) and MEG/EEG (e.g. [MNE](http://www.martinos.org/mne/stable/index.html)).\n\nBasically, there are packages for everything you can think of (also: creating websites, game programming, etc.)! In this course, we will mostly use basic Python in combination with the scientific computing packages ('numpy', 'scipy') and specialized neuroimaging packages ('nibabel', 'nipype').  \n\n#### Import statements\nAs explained above, Python ships with some default functionality. This means that it's already available upon starting a notebook (or any other Python environment) and doesn't need to be imported. An example is the function `len()`.\n\n\n```python\nmy_list = [1, 2, 3]\nprint(len(my_list))\n```\n\n    3\n\n\nHowever, non-built-in packages - such as `numpy` - need to be explicitly imported to access their functionality. After importing, their functions are accessible as: `{package}.{function}`.\n\nFor example:\n\n\n```python\nimport numpy\n\n# Now you can access the numpy function `add()` as numpy.add()\nprint(numpy.add(5, 3)) \n```\n\n    8\n\n\nHowever, writing `numpy` in front of every function you access from it becomes annoying very quickly. Therefore, we usually abbreviate the package name by two or three characters, which can be achieved through:\n\n`import {package} as {abbreviation}` \n\nFor example, people usually abbreviate the numpy import as:\n\n\n```python\nimport numpy as np\n\n# Now you can access numpy functions such as 'add()' as:\nprint(np.add(5, 3))\n```\n\nThroughout the tutorials, you'll see different packages (e.g. nibabel and scipy) being imported using abbreviations. \n\nAlso, you don't need to import an *entire* package, but you can also import a specific function or class. This is done as follows:\n\n`from {package} import {function1}, {function2}, {etc}`\n\nAn example:\n\n\n```python\nfrom numpy import add, subtract\n\n# Now I can simply call add() and subtract()\nprint(add(5, 3))\n```\n\n    8\n\n\nNote that some packages have a hierarchical structure with subpackages (also called modules). For example, scipy has a subpackage `ndimage` (with functions for n-dimensional arrays). To import *only* this subpackage, do the following:\n\n\n```python\nfrom scipy import ndimage\n# Now you can call functions from the ndimage subpackage,\n# e.g. gaussian_filter\n\nprint(ndimage.gaussian_filter([10, 5, 4], 2))\n```\n\nNote that you can mix and match all of these operations to customize the import to your own liking (see cell below for such a fancy import). In this course, we'll usually just import entire packages (e.g. `import numpy as np`) or specific functions/subpackages (e.g. `from scipy import stats`). \n\n\n```python\n# a fancy import\nfrom scipy.stats import binom_test as omg_binomial_testing_so_cool\n\nprint(omg_binomial_testing_so_cool(0.5, 10))\n```\n\n<div class=\"alert alert-warning\">\n<b>ToDo</b> (1 point)\n</div>\n\nImport the function \"randn\" from the numpy subpackage \"random\" and rename it \"random_normal_generator\".\n\n\n```python\nfrom numpy.random import randn as random_normal_generator\n```\n\n\n```python\n''' Tests the above ToDo. '''\ntry:\n    assert('random_normal_generator' in dir())\nexcept AssertionError as e:\n    print(\"I couldn't find the function 'random_normal_generator'; did you spell it correctly?\")\n    raise(e)\nelse:\n    print(\"Well done!\")\n```\n\n    Well done!\n\n\n\n```python\n''' Another test for the above ToDo. '''\ntry:\n    assert(random_normal_generator.__name__ == 'randn')\nexcept AssertionError as e:\n    print(\"Your 'random_normal_generator' function does not point to the 'randn' numpy.random subpackage!\")\n    raise(e)\nelse:\n    print(\"Well done!\")\n```\n\n    Well done!\n\n\n#### Whitespace for indentation\nIn most programming languages, code blocks (e.g., if-else blocks, or for-loops) are delineated by dedicated symbols (often curly brackets, `{}`). For example, an if-else block in R is written like this:\n\n```\nif (x > 0) {\n   y = x + 5\n} else {\n   y = x - 5\n}\n```\n\nWhile in languages like R and MATLAB whitespace/indentation is used for readability, it is not necessary! The above if-else statement in R can also be written as:\n\n```\nif (x > 0) { y = x + 5 } else { y = x - 5 }\n```\n\nHowever, in Python, whitespace and indentation is important! In Python, indendation - instead of curly braces - delineates code blocks, and if code is incorrectly indented, Python will give an error! For example, an if-else statement in Python must be indented (always with 4 spaces or a tab). If you don't do this, it will give an error, as show below:\n\n\n```python\nx = 0\nif x < 0:\n    y = x + 5\nelse:\n    y = x - 5   \n```\n\nIf you make sure the two statements beginning with `y = ...` are indented with 4 spaces/a tab, the error disappears (try it yourself!).\n\n#### Python versions\nAs a side note: there are currently two different supported versions of Python, 2.7 and 3.6. Somewhat confusingly, Python 3.0 introduced many backwards-incompatible changes to the language, so code written for 2.7 may not work under 3.x and vice versa. For this class all code will use Python **3.6** (but 90% of this notebook should be compatible with Python 2.7., we think ...). So if you want to use code from this class on your own computer, make sure you use Python 3.6!\n\n### 2.2 Basic data types\n\"Pure\" (i.e. built-in) Python has mostly the same data types as you might know from MATLAB or R, such as numbers (integers/floats), strings, and lists (cells in MATLAB; lists in R). Also, Python has to data types that might be unknown to MATLAB/R users, such as \"dictionaries\" and \"tuples\", which are explained later. \n\n#### Numbers\nNumbers are represented either as integers (\"whole\" numbers) or floats (numbers with decimals, basically).\n\n\n```python\nx = 3 \nprint(x, type(x)) # use type(variable) to find out of what data-type something is!\n\ny = 3.15\nprint(y, type(y))\n```\n\n    3 <class 'int'>\n    3.15 <class 'float'>\n\n\nLet's try to apply arithmetic to x as defined above with some basic operations:\n\n\n```python\nprint(x + 1)   # Addition;\nprint(x - 1)   # Subtraction;\nprint(x / 2)   # Division;\nprint(x * 2)   # Multiplication;\nprint(x ** 2)  # Exponentiation;\n```\n\n    4\n    2\n    1.5\n    6\n    9\n\n\nThe above commands apply operations to x, but do not *change* x itself. To permanently change x, you have to store the results of the operation (e.g. `x + 1`) into a variable (e.g. `x2 = x + 1`), as shown in the cell below:\n\n\n```python\nx = 3\nx_new = x + 2\n\n# If you simply want to update an existing variable, you can do this in two ways:\nx = x + 1\n\n# ... or:\nx += 1\n\nprint(x)  \n\nx *= 2 # This is the same as: x = x * 2\nprint(x) \n```\n\n    5\n    10\n\n\n<div class=\"alert alert-warning\">\n<b>ToDo</b> (1 point) \n</div>\n\nIn the cell below, make a new variable, `y`, which should contain x minus 5 and subsequently raised to the 4th power. \n\n\n```python\nx = 8\n# your solution here\ny = (x - 5) ** 4\n```\n\n\n```python\n''' Tests the above ToDo.'''\n\n# Check if there exists a variable 'y'\ntry:\n    assert('y' in dir())\nexcept AssertionError as e:\n    print(\"The variable 'y' doesn't seem to exist! Did you name it correctly?\")\n    raise(e)\nelse:\n    print(\"Well done! 1 out of tests 2 passed\")\n\n# Check if it has the correct number\ntry:\n    assert(y == 81)\nexcept AssertionError as e:\n    print(\"The variable y does not seem to equal x minus 5, raise to the power 4.\")\n    raise(e)\nelse:\n    print(\"Well done! 2 out of tests 2 passed\")\n```\n\n    Well done! 1 out of tests 2 passed\n    Well done! 2 out of tests 2 passed\n\n\n#### Booleans\nPython implements all of the usual operators for comparisons. Similar to what you might know from other languages, '==' tests equivalence, '!=' for not equivalent, and '<' and '>' for larger/smaller than.\n\nCheck out some examples below:\n\n\n```python\na = 3\nb = 5\nis_a_equal_to_b = a == b\n\nprint(is_a_equal_to_b)\nprint(type(is_a_equal_to_b)) \n```\n\n    False\n    <class 'bool'>\n\n\nHowever, for Boolean logic, python doesn't use operators (such as && for \"and\" and | for \"or\") but uses special (regular English) **words**: \n\n\n```python\nbool_1 = 3 > 5 # False, because 3 is not greater than 5\nbool_2 = 5 == 5 # True, because, well, 5 is 5\n\nprint(bool_1 and bool_2)  # Logical AND, both have to be True\nprint(bool_1 or bool_2)   # Logical OR, either one of them has to be True\nprint(not bool_1)         # Logical NOT, the inverse of bool_1\nprint(bool_1 != bool_2)   # Logical XOR, yields True when bool_1 and bool_2 are not equal\n```\n\n    False\n    True\n    True\n    True\n\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (0 points)\n</div>\nMess around with booleans in the cell below. Try some more complex things, like: `not ((3 > 5) and not (5 < 2))`. \nDo you understand why the result is the way it is? Try to follow the logic in the sequence of statements (not graded, so no tests follow the code block).\n\n\n```python\n# Do your ToDo here:\n[1, 3, 4] == [1, 3, 4]\n```\n\n\n\n\n    True\n\n\n\n#### Strings\nStrings in Python are largely the same as in other languages.\n\n\n```python\nh = 'hello'   # String literals can use single quotes\nw = \"world\"   # or double quotes; it does not matter.\n\nprint(h)\nprint(len(h))  # see how many characters in this string\n```\n\n    hello\n    5\n\n\nA very nice feature of Python strings is that they are easy to concatenate: just use '+'!\n\n\n```python\nhw = h + ', ' + w + '!' # String concatenation\nprint(hw)\n```\n\n    hello, world!\n\n\nYou can also create and combine strings with what is called 'string formatting'. This is accomplished by inserting a placeholder in a string, that you can fill with variables. An example is given below:\n\n\n```python\n# Here, we have a string with a placeholder '%s' (the 's' refers to 'string' placeholder)\nmy_string = 'My favorite programming language is: %s'\nprint('Before formatting:')\nprint(my_string)\n\n# Now, to 'fill' the placeholder, do the following:\nmy_fav_language = 'Python'\nmy_string = 'My favorite programming language is: %s' % my_fav_language\n\nprint('After formatting')\nprint(my_string)\n```\n\n    Before formatting:\n    My favorite programming language is: %s\n    After formatting\n    My favorite programming language is: Python\n\n\nYou can also use specific placeholders for different data types:\n\n\n```python\nweek_no = 1 # integer\nstring1 = 'This is week %i of neuroimaging' % week_no # the %i expects an integer!\nprint(string1)\n\nproject_score = 99.50 # float\nstring2 = 'I will get a %f on my midterm exam!' % project_score\nprint(string2)\n\n# You can also combine different types in a string:\nstring3 = 'In week %i of neuroimaging, %s will get a %f for my lab-assignment' % (week_no, \"I\", 95.00)\nprint(string3)\n```\n\nFor a full list of placeholders see https://docs.python.org/2/library/stdtypes.html#string-formatting-operations\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nUsing the variable `to_print` defined below, print the string:\n\n\"Neuroimaging will be my favorite course 4ever\"\n\nSo you'll have to \"fill\" the \"%\" placeholders using string formatting.\n(This is a manually graded answer, so no tests!)\n\n\n```python\nto_print = \"%s will be my favorite course %iever\"\n# print the to_print variable, with the appropriate string formatters!\nprint(to_print % (\"Neuroimaging\", 4))\n\n```\n\n    Neuroimaging will be my favorite course 4ever\n\n\n#### Lists\nA list is the Python equivalent of an array, but can be resized and can contain elements of different types. It is similar to a list in R and a cell in MATLAB. Note that indices in python start with 0! This means that the 3rd element of the list below is accessed through `[2]`.\n\nLet's check out some lists and how to index them!\n\n\n```python\n# Note that list may contain numbers ...\nlist1 = [3, 1, 2]\n\n# ... or strings\nlist2 = ['hello', 'world']\n\n# ... or, actually, anything at all! List lists themselves\nlist3 = ['hello', [3, 1, 2], 'world', 5.3, -999]\nlist3[1][0]\n```\n\n\n\n\n    3\n\n\n\nWhatever the contents of a list, they are indexed the same way: using square brackets with an integer, e.g. `[0]`:\n\n\n```python\nprint('The first element of list1 is: %i' % list1[0])\nprint('The second element of list2 is: %s' % list2[1])\nprint('The last element of list3 is: %i' % list3[-1])\nprint('The second-to-last element of list3 is: %f' % list3[-2])\n```\n\n    The first element of list1 is: 3\n    The second element of list2 is: world\n    The last element of list3 is: -999\n    The second-to-last element of list3 is: 5.300000\n\n\nNote that you can also use negative indices! Negative indices start indexing from the end of the list, so `[-1]` indexes the last element, `[-2]` indexes the second-to-last element, etc.\n\nWe cannot only 'extract' element from lists using indexing, but we can also replace them! This works as follows:\n\n\n```python\nsome_list = [1, 2, 3, ['A', 'B', 'C']]\n\n# Let's set the first element of some_list to 100:\nsome_list[0] = 100\nprint(some_list)\n\n# Note that indexing a list within a list is done with sequential square brackets,\n# so if we want to index the element 'A' in some_list, we do:\nsome_list[-1][0] = 'ANOTHER STRING'\nprint(some_list)\n```\n\n    [100, 2, 3, ['A', 'B', 'C']]\n    [100, 2, 3, ['ANOTHER STRING', 'B', 'C']]\n\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nIn the cell below, replace the element 'TO_REPLACE_1' with 'REPLACED' and the element 'TO_REPLACE_2' also with 'REPLACED' in the list `todo_list`.\n\n\n```python\ntodo_list = [1, 'B', 'TO_REPLACE_1', [5, 3, 1038, 'C'], [1, 3, 5, [9, 3, 1, 'TO_REPLACE_2']]]\n\n# your solution here\ntodo_list[2] = 'REPLACED'\ntodo_list[-1][-1][-1] = 'REPLACED'\ntodo_list\n```\n\n\n\n\n    [1, 'B', 'REPLACED', [5, 3, 1038, 'C'], [1, 3, 5, [9, 3, 1, 'REPLACED']]]\n\n\n\n**Note**: the code-cell below as usual tests your ToDo, but we haven't written out the tests in the cell itself. Instead, we wrote the tests in a separate Python module (a file with a collection of functions, objects, etc.), which we import here. (We do this, because writing out the tests here would give you the answer rightaway!)\n\n\n```python\n''' Tests the above ToDo with a custom function. '''\n# Below, we import all our tests (*) \nfrom tests import *\ntest_list_indexing(todo_list)\n```\n\nIn addition to accessing list elements one at a time, Python provides concise syntax to access specific parts of a list (sublists); this is known as **slicing**. \n\nLet's look at some slice operations:\n\n\n```python\nnums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nprint(nums)         # Our original list\n\n# Get a slice form index 2 to 4 (exclusive); prints \"[2, 3]\"\nprint(nums[2:4])    \n\n# Get a slice from index 2 to the end; prints \"[2, 3, 4, 5, 6, 7, 8, 9]\"\nprint(nums[2:])  \n\n# Get a slice from the start to index 2 (exclusive); prints \"[0, 1]\"\nprint(nums[:2])     \n\n# Get a slice of the whole list; prints [\"0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\"\nprint(nums[:])\n\n# Slice indices can be negative; prints [\"0, 1, 2, 3, 4, 5, 6, 7, 8]\",\n# so everything up to (but not including) the last element\nprint(nums[:-1])    \n```\n\nApart from the syntax `[from:to]`, you can also specify a \"stride\" (sort of step-size) of your slice using the syntax `[from:to:stride]`:\n\n\n```python\n# Return values in steps of 2\nprint(nums[::2])    \n\n# Returns values in steps of 3, but starting from the second element\nprint(nums[1::3])   \n```\n\nWith 'normal' indexing of lists, you can only index a subsequently set/replace one element at the time. With slices, however, you can set multiple elements at the same time:\n\n\n```python\nnums[2:4] = [100, 200] # Assign a new sublist to a slice\nprint(nums)         # Prints \"[0, 1, 100, 200, 4, 5, 6, 7, 8, 9]\"\n```\n\nImportantly, slicing in Python is \"end exclusive\", which means that the last index in your slice is not returned. Thus ...\n\n`nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nnums[0:5]` \n\n... returns 0 up till and including 4 (not 5!).\n\nCheck it out below:\n\n\n```python\nnums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nprint(nums[0:5])\n```\n\n    [0, 1, 2, 3, 4]\n\n\n<font color='blue'><b>Tip</b></font>: instead of creating sequential lists like:\n\n`num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]`\n\n... we can also create a list using the syntax: \n\n`num = list(range(starting_point, exclusive_end_point))`\n\nFor example, to create a list from 5 to 15, use the following:\n\n`num = list(range(5, 16))` \n\nWe'll use this construction (`list(range(x, y))`, or without the `list`) quite often in this course!\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nFrom the list (`my_list`) below, extract the numbers 2, 3, 4, 5, and 6 using a slice and store it in a new variable named `my_new_list`!\n\n\n```python\nmy_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n# your solution here\nmy_new_list = my_list[1:6]\nmy_new_list\n```\n\n\n\n\n    [2, 3, 4, 5, 6]\n\n\n\n\n```python\navailable_vars = dir()\nif 'my_new_list' not in available_vars:\n    raise ValueError(\"You did not store the results in a new variable caleld 'my_new_list'!\")\n    \ntest_slicing_1(my_new_list)\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point) \n</div>\nFrom the list below (`my_list_2`), extract the values `[5, 7, 9, 11]` using a slice (i.e., in a single operation!) and store it in a new variable named `my_new_list_2`.\n\n\n```python\nmy_list_2 = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21]\n\n# your solution here\nmy_new_list_2 = my_list_2[2:6]\nmy_new_list_2\n```\n\n\n\n\n    [5, 7, 9, 11]\n\n\n\n\n```python\navailable_vars = dir()\n\nif 'my_new_list_2' not in available_vars:\n    raise ValueError(\"You didn't define the variable 'my_new_list_2'!\")\n\ntest_slicing_2(my_new_list_2)\n```\n\n**NOTE**: you can index *strings* the same way as you index lists! Try to see it this way: a string is, quite literally, a *string* (\"list\") of characters. So, to get the first letter of some string s (e.g, 'this is a string'), you simply write: `s[0]`. To get first 5 characters, you write `s[:5]`, etc etc. Remember this!\n\n#### Dictionaries\nDictionaries might be new for those who are used to MATLAB or R. Basically, a dictionary is an **unordered** list in which list entries have a name (which is also referred to as a \"key\"). To get a value from a dictionary, you have to use the \"key\" as index instead of using an integer.\n\nLet's check out such a dictionary and how to index it. We build a dictionary using the following syntax: \n\n`{some_key: value, another_key: another_value, etc: etc}`\n\nThe keys can be anything! Strings, integers, lists ... doesn't matter! Mostly, though, strings are used as keys. \nSo, let's look at an example:\n\n\n```python\nmy_dict = {'cat': 'cute', 'dog': 'furry'}  # Create a new dictionary with some data\n```\n\nTo index a dictionary, we'll use square brackets `[]` again, just like with lists. But now, we can index using the key!\n\n\n```python\nindexed_value = my_dict['cat']\nprint(indexed_value)\n```\n\n    cute\n\n\nAdding new key-value pairs to dictionaries is easy! Just index it with a new key, and assign the value to it:\n\n\n```python\nmy_dict['fish'] = 'wet'     # Set an entry in a dictionary\nprint(my_dict['fish'])      # Prints \"wet\"\n```\n\n    wet\n\n\nLike a list, an entry in a dictionary can be of any data type:\n\n\n```python\nmy_dict['rabbit'] = ['omg', 'so', 'cute']\nprint(my_dict['rabbit'])\n```\n\n    ['omg', 'so', 'cute']\n\n\nIf you try to 'index' a dictionary with a key that doesn't exist, it raises a \"KeyError\", which means you're trying to index something that doesn't exist:\n\n\n```python\nprint(my_dict['monkey'])\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nIn the code cell below, add a new key to the dictionary `my_dict` named `\"rat\"` and with the value `\"nasty\"`.\n\n\n```python\n# Add the key-value pair here!\n\n# your solution here\nmy_dict['rat'] = 'nasty'\n```\n\n\n```python\n''' Tests the above ToDo. '''\n\ntry:\n    assert('rat' in my_dict)\nexcept AssertionError as e:\n    print(\"There exists no key 'rat' in my_dict!\")\n    raise(e)\n\ntry:\n    assert(my_dict['rat'] == 'nasty')\nexcept AssertionError as e:\n    print(\"The value of key 'rat' is '%s' and NOT 'nasty'\" % my_dict['rat'])\n\nprint('Well done!')\n```\n\n    Well done!\n\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nValues of dictionaries can be any type of object, even dictionaries themselves! So, add a new key to the dictionary `my_dict` named `\"another_dict\"` with the value of *another* dictionary with the keys `\"a\"` and `\"b\"` and the corresponding values `1` and `2`. Also, try to figure out how to index the value `1` from the 'nested' dictionary (this is not graded, but try it nonetheless!).\n\n\n```python\n# Do the ToDo here\n\nmy_dict[\"another_dict\"] = {'a':1, 'b':2}\n```\n\n\n```python\n''' Tests the above ToDo. '''\n\ntry:\n    assert('another_dict' in my_dict)\nexcept AssertionError as e:\n    print(\"There exists no key 'another_dict' in my_dict!\")\n    raise(e)\n\ntry:\n    assert(my_dict['another_dict']['a'] == 1)\n    assert(my_dict['another_dict']['b'] == 2)\nexcept AssertionError as e:\n    print(\"The key 'another_dictionary' should contain a dictionary with keys 'a' and 'b', corresponding\"\n          \"to values 1 and 2, respectively.\")\n    raise(e)\n\nprint('Well done!')\n```\n\n    Well done!\n\n\n#### tuples\nTuples are very much like lists, but the main difference is that they are immutable. In other words, after creating them, they cannot be modified (their values cannot be replaced/altered):\n\n\n```python\n# A list can be modified ...\nmy_list = [1, 2, 3]\nmy_list[0] = 0\nprint(my_list)\n```\n\n\n```python\n# ... but a tuple cannot.\nmy_tuple = (1, 2, 3)\nprint(my_tuple[0]) # you can print parts of tuple ...\nmy_tuple[0] = 0   # but you cannot modify it!\n```\n\nYou probably won't use tuples a lot, but you might come across them when using and writing functions (but more about that in the next section!).\n\n\n```python\ndef my_epic_function(integer):\n    \n    return integer, integer * 2\n\noutputs = my_epic_function(10)\nprint(outputs)\nprint(type(outputs))\n\n# also, you can unpack tuples (and also lists) as follows:\noutput1, output2 = outputs\nprint(output2)\n```\n\n    (10, 20)\n    <class 'tuple'>\n    20\n\n\n### 2.3 Functions and methods\n\nIf you followed the Codecademy tutorial, you are familiar with the basic syntax of functions in Python; if you're familiar with other programming languages, you'll see that the syntax of Python functions is quite similar to what you're used to.\n\nA function definition in Python starts with the keyword `def`, followed by the function name and round brackets with the arguments to the function, and finally the contents of the function, like so (note the indentation with four spaces/tab!!!):\n\n```\ndef my_awesome_function(arg_1, arg_2):\n    print(\"Argument 1: %s\" % arg_1)\n    print(\"Argument 2: %s\" % arg_2)\n```\n\nThis dummy-function above prints some stuff, but does not **return** something. Similar to R (but unlike MATLAB), you have to explicitly state what you want to **return** from the function by the \"return\" statement. \n\nSo, suppose you have a function that adds 2 to any number. Let's define it as follows (you have to run the cell to let Python know you've defined this function):\n\n\n```python\ndef add_2_to_a_number(some_number):\n    new_number = some_number + 2\n```\n\nHere, we omitted a **return** statement to return the value of `new_number`. This is a problem, because in Python (like most languages) you cannot 'peek' inside the function after using it! You can only access whatever is returned. \n\nSo, in the function defined above, we cannot access the value of `new_number`, because we didn't return it:\n\n\n```python\n# This will give an error!\nadd_2_to_a_number(5)\nprint(new_number)\n```\n\nSo, to access the *value* of `new_number` (that is, *not* `new_number` itself, but its associated value), we need to return it:\n\n\n```python\ndef add_2_to_a_number_fixed(some_number):\n    new_number = some_number + 2\n    return new_number\n```\n\n\n```python\nvalue_contained_in_new_number = add_2_to_a_number_fixed(5)\nprint(\"Results of function 'add_2_to_a_number' with argument '5': %i\" % value_contained_in_new_number)\n```\n\n    Results of function 'add_2_to_a_number' with argument '5': 7\n\n\nImportantly, you can name the variable to which you assign the return value *anyway you like*. This doesn't have to be `new_number`! Like above, we named it `value_contained_in_new_number`, but it really doesn't matter.\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 points) \n</div>\nIn the code cell below, we've started writing a function named `extract_last_element` that takes one input-argument - a list - and returns the last element of the list. Some parts of the function are missing, though, which you need to write! When you're done, run the test-cell below it to check if it's right!\n\n\n```python\ndef extract_last_element(input_list):\n    \n    # your solution here\n    return input_list[-1]\n    \n```\n\n\n```python\ntry:\n    assert(extract_last_element(input_list=[0, 1, 2]) == 2)\nexcept AssertionError as e:\n    print(\"Your function fails for input [0, 1, 2]\")\n    raise(e)\n\ntry:\n    assert(extract_last_element(input_list=[0]) == 0)\nexcept AssertionError as e:\n    print(\"Your function fails for input [0]\")\n    raise(e)\n\ntry:\n    assert(extract_last_element(input_list=['string1', 'string2', 'string3']) == 'string3')\nexcept AssertionError as e:\n    print(\"Your function fails for input ['string1', 'string2', 'string3']\")\n    raise(e)\n\nprint(\"Well done!\")\n```\n\n    Well done!\n\n\nAlright, that was probably relatively easy. Let's do a slightly harder one.\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point) \n</div>\nWrite a completely new function named `get_values_from_odd_indices` (so you have to write the `def ...` part!) that takes one input-argument - a list - and returns all values from the odd indices of that list. So, suppose you have a list:\n\n`[2, 100, 25, 48, 92, -5, 12]`\n\n... your function should return: \n\n`[100, 48, -5]`\n\n... i.e, the values from odd indices (here: 1, 3, 5; we exclude index zero!)\n\nHint: slices might be useful here!\n\nWhen you're done, run the test-cell below it to check if it's right!\n\n\n```python\n# Implement your function (called get_values_from_odd_indices) here:\n\ndef get_values_from_odd_indices(input_list):\n    return input_list[1:-1:2]\n\n```\n\n\n```python\n''' Tests the ToDo above. '''\ntry:\n    assert('get_values_from_odd_indices' in dir())\n    assert(callable(get_values_from_odd_indices))\nexcept AssertionError as e:\n    print(\"Your function 'get_values_from_odd_indices' does not seem to exist!\")\n\ntry:\n    out = get_values_from_odd_indices([0, 1, 2])\n    if out is None:\n        msg = \"ERROR: did you forget the Return statement?\"\n        raise ValueError(msg)\nexcept ValueError as e:\n    raise(e)\n    \nprint(\"Well done (also run the next cell with tests)!\")\n```\n\n    Well done (also run the next cell with tests)!\n\n\n\n```python\n''' Some other tests for the ToDo above. '''\ninp = [0, 1, 2]\noutp = get_values_from_odd_indices(inp)\nans = [1]\ntry:\n    assert(outp == ans)\nexcept AssertionError as e:\n    print(\"Your function returned '%r' but I expected '%r'\" % (outp, ans))\n    raise(e)\n\ninp = [5, 7, 9, 11, 13, 15, 18, 20, 21]\noutp = get_values_from_odd_indices(inp)\nans = [7, 11, 15, 20]\ntry:\n    assert(outp == ans)\nexcept AssertionError as e:\n    print(\"Your function returned '%r' but I expected '%r'\" % (outp, ans))\n    raise(e)\n\nprint(\"Well done!\")\n```\n\n    Well done!\n\n\n**IMPORTANT**: it is possible to return *multiple things* from a function. The function, then, returns these things as a tuple, which can subsequently be \"unpacked\". Let's check out an example using a custom function called `minmax_of_list` which returns both the minimum and maximum of a list:\n\n\n```python\ndef minmax_of_list(some_list):\n    ''' Returns both the minimum and maximum of a list.\n    \n    Parameters\n    ----------\n    some_list : a Python list\n    \n    Returns\n    -------\n    min_value : a float or int\n        The minimum of a list\n    max_value : a float or int\n        The maximum of a list\n    '''\n    min_value = min(some_list)\n    max_value = max(some_list)\n    \n    return min_value, max_value\n```\n\nAs you can see, returning multiple things is a simple as adding more variables after the `return` statement, separated by commas. If we now call the function with a particular list, it gives us back a tuple of size 2 (one value for the minimum, one value for the maximum):\n\n\n```python\noutput_from_function = minmax_of_list([0, 1, 2, 3])\nprint(output_from_function)\nprint(type(output_from_function))\n```\n\n    (0, 3)\n    <class 'tuple'>\n\n\nWe can now \"unpack\" the tuple (i.e., extract the separate values) in several ways. One way is to simply index the values:\n\n\n```python\noutput_from_function = minmax_of_list([0, 1, 2, 3])\nminimum = output_from_function[0]\nprint(\"Minimum: %i\" % minimum)\n\nmaximum = output_from_function[1]\nprint(\"Maximum: %i\" % maximum)\n```\n\n    Minimum: 0\n    Maximum: 3\n\n\nAlternatively, we can already \"extract\" one value, let's say the maximum (index 1 of the tuple) right after calling the function, so we can skip dealing with the tuple altogether:\n\n\n```python\nmaximum = minmax_of_list([0, 1, 2, 3])[1]  # The [1] extracts the maximum from the output of the function immediately!\nprint(\"Maximum: %i\" % maximum)\n\n```\n\n    Maximum: 3\n\n\nKeep this feature of returning multiple things and tuple unpacking in mind for the rest of the course (you'll definitely encounter it more often!).\n\n#### Methods\nHowever, in Python, functions are not the only things that allow you to 'do' things with data. In others' code, you'll often see function-like expressions written with periods, like this: `some_variable.function()`. These `.function()` parts are called 'methods', which are like functions 'inherent' to a specific type of object. In other words, it is a function that is applied to the object it belongs to. \n\nDifferent type of objects in Python, such as stings and lists, have their own set of methods. For example, the function you defined above (`extract_last_element()`) also exists as a method each list has, called `pop()`! (This is a builtin, standard, method that each list in Python has.) See for yourself in the block below.\n\n\n```python\nmy_list = [0, 5, 10, 15] \nprint(my_list.pop())\n\n# You can also just do the following (i.e. no need to define a variable first!):\nprint([0, 5, 10, 15].pop())\n\n# ... which is the same as:\nprint(extract_last_element([0, 5, 10, 15]))\n```\n\n    15\n    15\n    15\n\n\nNot only lists, but also other data-types (such as strings, dictionaries, and, as we'll see later, numpy arrays) have their own methods. How methods work exactly is not really important (this belongs to the topic of 'object-oriented programming'), but it is necessary to know **what** it does, as you'll see them a lot throughout this course. \n\nWe'll show you a couple of (often-used) examples:\n\n\n```python\n# For lists, we have .append()\nx = [0, 10, 15]\nx.append(20) # Add a new element to the end of the list using the append() method!\nprint(x)\n```\n\n**Note**: sometimes, methods modify the object (above: `x`) *in-place*, which means that the method does not return anything, so you don't have to assign it to a new variable. If you accidentally do this, the new object's value is `None`, as you see below: \n\n\n```python\nx = [0, 10, 15]\nx_new = x.append(20)\nprint(x_new)\n```\n\n    None\n\n\nSome often-used methods for dictionaries:\n\n\n```python\nmy_dict = {'a': 0, 'b': 1, 'c': 2}\n\n# The .values() method returns all the values of the dictionary \nprint(list(my_dict.values()))\n\n# And the .keys() method returns all the keys of the dictionary\nprint(list(my_dict.keys()))\n```\n\n    [2, 1, 0]\n    ['c', 'b', 'a']\n\n\n**Note**: these dictionary-methods actually *do* return values! \n\nSome often-used methods for strings:\n\n\n```python\nmy_string = 'neuroimaging is fun!'\n\n# The .upper() method returns the string in uppercase!\nprint(my_string.upper())\n\n# The .count(substring) method returns the number of times a substring occurs in a string\nprint(my_string.count('n'))\n\n# The .replace(old, new) method replaces substrings\nprint(my_string.replace('fun', 'awesome'))\n\n# The .split(separator) splits a string into subparts (returned as a list)\nprint(my_string.split(' '))  # split by whitespace\n```\n\n    NEUROIMAGING IS FUN!\n    3\n    neuroimaging is awesome!\n    ['neuroimaging', 'is', 'fun!']\n\n\n#### Default arguments in functions/methods\nImportantly, and unlike most (scientific) programming languages, Python supports the use of 'default' arguments in functions. Basically, if you don't specify an optional argument, it uses the default:\n\n\n```python\ndef exponentiate_number(number, power=2):\n    return number ** power\n\nprint(exponentiate_number(2)) # now it uses the default!\nprint(exponentiate_number(2, 10)) # now it \"overwrites\" the default and uses power=10\nprint(exponentiate_number(number=2, power=10)) # also note that you can 'name' arguments \n```\n\n    4\n    1024\n    1024\n\n\n### 2.4 If-statements\nIf-elif-else statements in Python are quite straightforward. An example:\n\n\n```python\nx = 5\n\nif x > 0:\n    print('x is larger than 0')\nelif x < 0:\n    print('x is smaller than 0')\nelse:\n    print('x must be exactly 0!')\n```\n\n    x is larger than 0\n\n\nIf-statements contain at least an `if` keyword, but optionally also one or more `elif` (\"else if\") statements and an optional `else` statement. We'll practice this (in a `ToDo`) after the section on Loops.\n\n### 2.4 Loops\nLoops in Python (for- and while-loops) are largely similar to MATLAB and R loops, with some minor differences in  their syntax:\n\n\n```python\nanimals = ['cat', 'dog', 'monkey']\nfor animal in animals:\n    print(animal)\n```\n\n    cat\n    dog\n    monkey\n\n\nBasically, each data type that is also an \"iterable\" (something that you can iterate over) can be used in loops, including lists, dictionaries, and tuples.\n\n\n```python\n# An example of looping over a list\nmy_list = [1, 2, 3]\nfor x in my_list:\n    print(x)\n```\n\n    1\n    2\n    3\n\n\nMATLAB users might be used to looping over indices instead of the actual list values, like the following:\n\n```\nfor i=1:100\n    disp(some_list(i));\nend```\n\nIn Python, however, you loop (by default) over the contents of a list:\n\n```\nfor entry in some_list:\n    print(entry)\n```\n    \nIf you want to access for the value **AND** the index, you can use the built-in `enumerate` function:\n\n\n```python\nmy_list = ['a', 'b', 'c']\nfor index, value in enumerate(my_list):\n    \n    print('Loop iteration number (index) = %i, value = %s' % (index, value))\n\n# Don't forget that Python indexing starts at zero!\n```\n\n    Loop iteration number (index) = 0, value = a\n    Loop iteration number (index) = 1, value = b\n    Loop iteration number (index) = 2, value = c\n\n\n\n```python\n# Looping over a tuple (exactly the same as looping over a list)\nmy_tuple = (1, 2, 3)\nfor x in my_tuple:\n    print(x)\n    \nlen(my_tuple)\n```\n\n    1\n    2\n    3\n\n\n\n\n\n    3\n\n\n\n\n```python\n# Iterating over a dictionary can be done in a couple of ways!\nmy_dict = {'a': 1, 'b': 2, 'c': 3}\n\n# Looping over the keys ONLY\nfor key in my_dict:\n    print(key)\n```\n\n    c\n    b\n    a\n\n\n\n```python\n# Looping over both the keys and the entries\nfor key, entry in my_dict.items():\n    print(key, entry)\n```\n\n    c 3\n    b 2\n    a 1\n\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (2 points) \n</div>\nComplete the function below - named `extract_values_smaller_than_0` - that takes a single list with numbers as input and returns a new list with *only the values smaller than 0* from the input-list. For example, suppose our input-list is:\n\n```\n[2, -5.3, 1.8, 0.0, -205.1, 6029]\n```\n\n... the function should return:\n\n```\n[-5.3, -205.1]\n```\n\nHint: use an if-statement in combination with the `.append()` method of the empty list we initialized below (`list_to_return`) to fill the `list_to_return` variable in a for-loop. In other words, the function should contain an if-statement in a for-loop (in which you need to use the `.append()` method).\n\n\n```python\n# Complete the function below (make sure to remove raise NotImplementedError!)\ndef extract_values_smaller_than_0(input_list):\n    \n    # We initialize an empty list here (which you need to fill using a for-loop)\n    list_to_return = []\n    \n    # your solution here\n    for i in input_list:\n        if i < 0:\n            list_to_return.append(i)\n\n    \n    return list_to_return\n```\n\n\n```python\n''' Tests the ToDo above. '''\ninp = [-5, 2, 3, -8]\noutp = extract_values_smaller_than_0(inp)\nans = [-5, -8]\ntry:\n    assert(outp == ans)\nexcept AssertionError as e:\n    print(\"Your function  with input '%r' returned '%r', but I expected '%r'\" % (inp, outp, ans))\n    raise(e)\n    \ninp = [0, 2, -3]\noutp = extract_values_smaller_than_0(inp)\nans = [-3]\ntry:\n    assert(outp == ans)\nexcept AssertionError as e:\n    print(\"Your function  with input '%r' returned '%r', but I expected '%r'\" % (inp, outp, ans))\n    raise(e)\n\ninp = [0, 0, 0]\noutp = extract_values_smaller_than_0(inp)\nans = []\ntry:\n    assert(outp == ans)\nexcept AssertionError as e:\n    print(\"Your function  with input '%r' returned '%r', but I expected '%r'\" % (inp, outp, ans))\n    raise(e)\n\nprint(\"Well done!\")\n```\n\n    Well done!\n\n\n#### Advanced loops: list comprehensions\nSometimes, writing (and reading!) for-loops can be confusing and lead to \"ugly\" code. Wouldn't it be nice to represent (small) for-loops on a single line? Python has a way to do this: using what is called `list comprehensions`. It does exactly the same thing as a for-loop: it takes a list, iterates over its entries (and does something with each entry), and (optionally) returns a (modified) list. \n\nLet's look at an arbitrary example of a for-loop over a list:\n\n\n```python\nnums = [0, 1, 2, 3, 4]\n\n# Also, check out the way 'enumerate' is used here!\nfor index, x in enumerate(nums):\n    nums[index] = x ** 2\n    \n\nprint(nums)\n```\n\n    [0, 1, 4, 9, 16]\n\n\nYou can make this code simpler using a list comprehension:\n\n\n```python\nnums = [0, 1, 2, 3, 4]\nsquares = [x ** 2 for x in nums] # importantly, a list comprehension always returns a (modified) list!\nprint(squares)\n```\n\n    [0, 1, 4, 9, 16]\n\n\nAlso, list comprehensions may contain if-statements!\n\n\n```python\nstring_nums = ['one', 'two', 'three']\nstarts_with_t = ['yes' if s[0] == 't' else 'no' for s in string_nums]\nprint(starts_with_t)\n```\n\n    ['no', 'yes', 'yes']\n\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (0 points; optional)\n</div>\nWrite a list comprehension that adds the string '\\_check' to each value in the list `my_list` below, except if the value is 'B'. (This is an optional ToDo to practice list comprehensions.)\n\n\n```python\nmy_list = ['A', 'B', 'C', 'D']\n# Implement your list comprehension here!\n\nmy_list = [x if x == 'B' else x + \"_check\" for x in my_list]\nmy_list\n\n\n```\n\n\n\n\n    ['A_check', 'B', 'C_check', 'D_check']\n\n\n\nList comprehensions are somewhat of a more advanced Python concept, so if you don't feel comfortable using them (correctly) in your future assignments, use regular for-loops by all means! In the upcoming tutorials, though, we'll definitely use them, so make sure you understand what they do!\n\n## 2. Numpy\nThis section is about Numpy, Python's core library for numeric computing. While the syntax of basic Python (as we've gone over in the previous section) is important to do neuroimaging analysis in Python, knowing numpy is **essential**. Basicially, Numpy is the go-to package whenever you want to do (anything related to) data analysis in Python. Make sure you understand what is going on in this section, as the rest of the course will feature a lot of Numpy-code!\n\nThe most important feature of Numpy is it's core data structure: the numpy *ndarray* (which stands for *n*-dimensional array, referring to the fact that the array may be of any dimension: 1D, 2D, 3D, 180D ... *n*D). This is, just like basic lists/dictionaries/integers/tuples, a data structure with its own syntax, operations, and methods, as we will explain below.\n\n### Python lists vs. numpy arrays\nBasically, numpy arrays are a lot like Python lists. The major difference, however, is that **numpy arrays may contain only a single data-type**, while Python lists may contain different data-types within the same list.\n\nLet check this out:\n\n\n```python\n# Python lists may contain mixed data-types: an integer, a float, a string, a list\npython_list = [1, 2.5, \"whatever\", [3, 4, 5]] \n\nfor value in python_list:\n    \n    print(\"%s is a: %s\" % (str(value), type(value)))\n```\n\n    1 is a: <class 'int'>\n    2.5 is a: <class 'float'>\n    whatever is a: <class 'str'>\n    [3, 4, 5] is a: <class 'list'>\n\n\nUnlike Python lists, numpy only allows entries of the same data-type. This difference between Python lists and numpy arrays is basically the same as R lists (allow multiple data-types) versus R matrices/arrays (only allow one data type), and is also the same as MATLAB cells (allow multiple data-types) versus MATLAB matrices (only allow one data type).\n\nIn fact, if you try to make a numpy array with different data-types, numpy will force the entries into the same data-type (in a smart way), as is shown in the example below:\n\n\n```python\nimport numpy as np\n# Importantly, you often specify your arrays as Python lists first, and then convert them to numpy\nto_convert_to_numpy = [1, 2, 3.5]               # specify python list ...\nnumpy_array = np.array(to_convert_to_numpy)     # ... and convert ('cast') it to numpy\n\nfor entry in numpy_array:\n    \n    print(entry)\n    print('this is a: %s \\n' % type(entry))\n```\n\n    1.0\n    this is a: <class 'numpy.float64'> \n    \n    2.0\n    this is a: <class 'numpy.float64'> \n    \n    3.5\n    this is a: <class 'numpy.float64'> \n    \n\n\n\n```python\n\n```\n\nAs you can see, Numpy converted our original list (to_convert_to_numpy), which contained both integers and floats, to an array with only floats! You might think that such a data structure that only allows one single data type is not ideal. However, the very fact that it only contains a single data-type makes operations on numpy arrays extremely fast. For example, loops over numpy arrays are often way faster than loops over python lists. This is because, internally, Python has to check the data-type of each loop entry before doing something with that entry. Because numpy arrays one allow a single data-type, it only has to check for the entries' data type **once**. If you imagine looping over an array or list of length 100,000, you probably understand that the numpy loop is way faster.\n\nLet's check out the speed difference between Python list operations and numpy array operations:\n\n\n```python\n# timeit is a cool 'feature' that you can use in Notebooks (no need to understand how it works)\n# it basically performs a computation that you specify a couple of times and prints how long it took on average\nresults_python = %timeit -o [x * 2 for x in range(0, 100000)] \n```\n\n    7.53 ms \u00b1 768 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 100 loops each)\n\n\nAnd now let's do the same with numpy:\n\n\n```python\nresults_numpy = %timeit -o np.arange(0, 10000) * 2 \n\nratio = results_python.average / results_numpy.average\nprint(\"Numpy is %i times faster than Python!\" % ratio)\n```\n\n    19.4 \u00b5s \u00b1 2.67 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 10000 loops each)\n    Numpy is 388 times faster than Python!\n\n\nYou see that Numpy 10 times as fast! This really matters when you start doing more complex operations, on, let's say, multidimensional brain images!\n\n### Numpy arrays: creation\nAs shown an earlier example, numpy arrays can be created as follows:\n\n1. Define a Python list (e.g. `my_list = [0, 1, 2]`) \n2. Convert the list to a numpy array (`numpy_array = np.array(my_list)`)\n\nImportantly, a simple Python list will be converted to a 1D numpy array, but a nested Python list will be converted to a 2D (or even higher-dimensional array). Nesting is simply combining different lists, separated by commans, as is shown here:\n\n\n```python\nmy_list = [1, 2, 3]\nmy_array = np.array(my_list)\n\nprint(\"A 1D (or 'flat') array:\")\nprint(my_array, '\\n')\n\nmy_nested_list = [[1, 2, 3],\n                  [4, 5, 6],\n                  [7, 8, 9]]\n\nmy_2D_array = np.array(my_nested_list)\nprint(\"A 2D array:\")\nprint(my_2D_array)\n```\n\n    A 1D (or 'flat') array:\n    [1 2 3] \n    \n    A 2D array:\n    [[1 2 3]\n     [4 5 6]\n     [7 8 9]]\n\n\nAs you can imagine, creating numpy arrays from nested lists becomes cumbersome if you want to create (large) arrays with more than 2 dimensions. There are, fortunately, a lot of other ways to create ('initialize') large, high-dimensional numpy arrays. One often-used method is to create an array with zeros using the numpy function `np.zeros`. This function takes one (mandatory) argument, which is a tuple with the dimensions of your desired array:\n\n\n```python\nmy_desired_dimensions = (2, 5) # suppose I want to create a matrix with zeros of size 2 by 5\nmy_array = np.zeros(my_desired_dimensions)\n\nprint(my_array)\n```\n\n    [[0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0.]]\n\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nusing the `np.zeros` function, create a five dimensional array of shape $2 \\times 3 \\times 5 \\times 3 \\times 7$ and store it in a variable named `array_5d`.\n\n\n```python\n# Implement your ToDo here\n\n# your solution here\ndims = (2, 3, 5, 3, 7)\narray_5d = np.zeros(dims)\nprint(array_5d)\n\n```\n\n    [[[[[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]]\n    \n    \n      [[[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]]\n    \n    \n      [[[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]]]\n    \n    \n    \n     [[[[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]]\n    \n    \n      [[[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]]\n    \n    \n      [[[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]\n    \n       [[0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]\n        [0. 0. 0. 0. 0. 0. 0.]]]]]\n\n\n\n```python\n''' Tests the above ToDo. '''\navailable_vars = dir()\nif 'array_5d' not in available_vars:\n    raise ValueError(\"You didn't define the variable 'array_5d'!\")\n\ntest_create_array_with_zeros(array_5d)\n```\n\nUsing arrays with zeros is often used in what is called 'pre-allocation', in which you create an 'empty' array with only zeros and for example, 'fill' that array in a loop.\n\nBelow, we show you an example in which we pre-allocate an array with 5 zeros, and fill that in a for-loop with the squares of 1 - 5. Try to understand how it works! (You have to do something similar in the next ToDo!)\n\n\n```python\nmy_array = np.zeros(5)\n\nprint('Original zeros-array')\nprint(my_array)\n\nfor i in range(5):  # notice the range function here! This loop now iterates over [0, 1, 2, 3, 4]\n    number_to_calculate_the_square_of = i + 1\n    my_array[i] = number_to_calculate_the_square_of ** 2\n\nprint('\\nFilled array')\nprint(my_array)\n```\n\n    Original zeros-array\n    [0. 0. 0. 0. 0.]\n    \n    Filled array\n    [ 1.  4.  9. 16. 25.]\n\n\n**Important**: realize that loops (not shown above), if-statements and other boolean logic is the same for numpy and python!\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (2 points)\n</div>\nWrite a loop in which you fill each value in the variable `my_array2` with the value 1 divided by the current index plus one. So, suppose the index (usually `i`, like the last example) is 3, then you should fill `my_array2` at index `i` with `1 / (3 + 1)`.\n\n\n```python\nimport numpy as np\nmy_array2 = np.zeros(8)\n\n# your solution here\nfor i in range(len(my_array2)):\n    my_array2[i] = 1 / (i + 1)\nmy_array2\n```\n\n\n\n\n    array([1.        , 0.5       , 0.33333333, 0.25      , 0.2       ,\n           0.16666667, 0.14285714, 0.125     ])\n\n\n\n\n```python\n''' Tests the above ToDo. '''\navailable_vars = dir()\nif 'my_array2' not in available_vars:\n    raise ValueError(\"The variable my_array2 does not exist!\")\n    \ntest_fill_array_with_complement(my_array2)\n```\n\nIn addition to `np.zeros`, you can create numpy arrays using other functions, like `np.ones` and `random` from the `np.random` module:\n\n\n```python\nones = np.ones((5, 10)) # create an array with ones\nprint(ones, '\\n')\n\nrndom = np.random.random((5, 10)) # Create an array filled with random values (0 - 1 uniform)\nprint(rndom)\n```\n\n    [[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]\n     [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]\n     [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]\n     [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]\n     [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]] \n    \n    [[0.58225787 0.43376404 0.96060657 0.33026376 0.69259438 0.99373706\n      0.25255857 0.47050424 0.41794689 0.15479334]\n     [0.72601987 0.06520818 0.95751049 0.40067078 0.74343008 0.59082416\n      0.4996278  0.59197313 0.36211512 0.19820634]\n     [0.56748169 0.5800225  0.05323937 0.62624096 0.22568656 0.6317539\n      0.05626455 0.39777624 0.86300044 0.58308046]\n     [0.02028157 0.28217899 0.39147311 0.13873879 0.8198226  0.33758146\n      0.43110568 0.90999583 0.06693565 0.13153269]\n     [0.60902323 0.05956734 0.75681971 0.63561485 0.18279177 0.47373918\n      0.72369829 0.28068653 0.50107507 0.79094778]]\n\n\n### Numpy: indexing\nIndexing (extracting a single value of an array) and slicing (extracting multiple values - a subset - from an array) of numpy arrays is largely the same as with regular Python lists and data structures from other scientific computing languages such as R and MATLAB. Let's check out a couple of examples of a 1D array:\n\n\n```python\nmy_array = np.arange(10, 21)  # numpy equivalent of list(range(10, 21))\nprint('Full array:')\nprint(my_array, '\\n') \n\nprint(\"Index the first element:\")\nprint(my_array[0], '\\n')\n\nprint(\"Index the second-to-last element:\")\nprint(my_array[-2], '\\n')\n\nprint(\"Slice from 5 until (not including!) 8\")\nprint(my_array[5:8], '\\n') \n\nprint(\"Slice from beginning until 4\")\nprint(my_array[:4])\n\n\n```\n\n    Full array:\n    [10 11 12 13 14 15 16 17 18 19 20] \n    \n    Index the first element:\n    10 \n    \n    Index the second-to-last element:\n    19 \n    \n    Slice from 5 until (not including!) 8\n    [15 16 17] \n    \n    Slice from beginning until 4\n    [10 11 12 13]\n\n\n\n\n\n    range(0, 3)\n\n\n\nSetting values in numpy arrays works the same way as lists:\n\n\n```python\nmy_array = np.arange(10, 21)\nmy_array[0] = 10000\nprint(my_array)\n\nmy_array[5:7] = 0\nprint(my_array)\n```\n\n    [10000    11    12    13    14    15    16    17    18    19    20]\n    [10000    11    12    13    14     0     0    17    18    19    20]\n\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nIn the array `my_array` below, set all odd indices (i.e., the first element, the third element, the fifth element, etc.) to the value `0.0` *in a single statement using a slice* (i.e., not a for-loop).\n\n\n```python\n# Implement the ToDo here\nmy_array = np.arange(3, 25)\n\n# your solution here\nmy_array[1:-1:2] = 0.0\nmy_array\n```\n\n\n\n\n    array([ 3,  0,  5,  0,  7,  0,  9,  0, 11,  0, 13,  0, 15,  0, 17,  0, 19,\n            0, 21,  0, 23, 24])\n\n\n\n\n```python\n''' Tests the above ToDo. '''\ntest_set_odd_indices_to_zero(my_array)\n```\n\n#### Multidimensional indexing\nOften, instead of working on and indexing 1D array, we'll work with multi-dimensional (>1D) arrays. Indexing multi-dimensional arrays is, again, quite similar to other scientific computing languages. \n\nLike indexing Python lists, indexing multidimensional numpy arrays is done with square brackets `[]`, in which you can put as many comma-delimited numbers as there are dimensions in your array. \n\nFor example, suppose you have a 2D array of shape $3 \\times 3$ and you want to index the value in the first row and first column. You would do this as follows:\n\n\n```python\nmy_array = np.zeros((3, 3)) # 3 by 3 array with zeros\nindexed_value = my_array[0, 0]\nprint(\"Value of first row and first column: %.1f\" % indexed_value)\n```\n\n    Value of first row and first column: 0.0\n\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nUsing multidimensional indexing, set the value in the last row and last column of the 2D array `my_array` to `1.0`. In other words, set the value in the lower-right \"corner\" of the 2D array to 1.0.\n\n\n```python\nimport numpy as np\nmy_array = np.zeros((3, 3))\n\nprint(my_array)\n\n# ToDo: set the value in the lower right corner to 1\n\n# your solution here\nmy_array[-1, -1] = 1.0\nprint(my_array)\n\n```\n\n    [[0. 0. 0.]\n     [0. 0. 0.]\n     [0. 0. 0.]]\n    [[0. 0. 0.]\n     [0. 0. 0.]\n     [0. 0. 1.]]\n\n\n\n```python\n''' Tests the ToDo above. '''\ntest_set_lower_right_value_to_one(my_array)\n```\n\nIn addition to setting specific slices to specific values, you can also extract sub-arrays using slicing/indexing. An important construct here is that you can use a single colon `:` to select all values from a particular dimension. For example, if you want to select all column-values (second dimension) from only the first row (first dimension), do this:\n\n```\nsome_2d_arr[0, :]\n```\n\nWe'll show you some examples below:\n\n\n```python\nmy_array = np.array([[1, 2, 3],\n                     [4, 5, 6],\n                     [7, 8, 9]])\n\nprint(my_array, '\\n')\n\nall_column_values_from_first_row = my_array[0, :]\nprint('First row')\nprint(all_column_values_from_first_row, '\\n')\n\nall_row_values_from_first_col = my_array[:, 0]\nprint('First column')\nprint(all_row_values_from_first_col)\n```\n\n    [[1 2 3]\n     [4 5 6]\n     [7 8 9]] \n    \n    First row\n    [1 2 3] \n    \n    First column\n    [1 4 7]\n\n\nSo far, we only talked about 2D arrays, which are relatively easy to 'understand'. In neuroimaging, however, we usually work with 3D, 4D, or even higher-dimensional arrays. These arrays are great for organizing data (like 3D brain scans!), but they are somewhat unintuitive. This takes some time to get used to!\n\nTo get you used to thinking in more than 2 (or 3) dimensions, consider the following scenario. A researcher wants to test the efficacy of a particular medicine against high blood pressure. To do so, he/she measures the (average systolic) blood pressure of a group of twenty subjects every hour for 30 days when they're not on the medication. The same subjects are then again measured for another 30 days, but then when they're on medication.\n\nAfter this period of data collection, the researcher has $20\\ (subjects)\\ \\times\\ 24\\ (hours)\\ \\times\\ 30\\ (days)\\ \\times\\ 2\\ (conditions: off/on) = 28800$ measurements! We can then organize the data in a 4D array, in which each factor (subjects/hours/days/conditions) represents a separate dimension (also called \"axis\") of our array!\n\nSo, let's generate some random data (from a normal distribution to generate 'realistic' blood pressure data) that could represent this blood pressure dataset:\n\n\n```python\nnp.random.seed(42)  # this is not important for now\nbp_data = np.random.normal(loc=100, scale=5, size=(20, 24, 30, 2))\n```\n\n(Note that we're not printing the `bp_data` variable here, because it's way too much to visualize/interpret at once anyway!)\n\nNow, suppose I would want to extract the blood pressure of subject 5 at 09.00 (AM) in the morning at day 21 when he/she was *not* on medication. In that case, I would do:\n\n\n```python\n# Note that I count midnight as the first measurement\nthis_particular_datapoint = bp_data[4, 8, 20, 0]\nprint(\"Blood pressure of participant 5 at 09.00 (AM) on day 21 in \"\n      \"the no-medication (off) condition is %.3f\" % this_particular_datapoint)\n\n# Also, remember that Python is zero-based, so e.g. participant 5 is indexed by index 4!\n```\n\n    Blood pressure of participant 5 at 09.00 (AM) on day 21 in the no-medication (off) condition is 100.567\n\n\nTry to remember this: **in multidimensional arrays, each dimension (axis) represents a different attribute of your data (e.g. subjects, time, condition, etc.)**. This concept will become very important to understand later when we're going to analyze 4D MRI-datasets (with 3 spatial dimensions and 1 time dimension)!\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nConsider the blood-pressure dataset again. In the code-cell below, extract from all participants all data from day 18 in the medication (\"on\") condition. You'll have to use slices with the single `:`! Store the results of your index-operation in the variable `day_18_condition_on`.\n\n\n```python\n# Implement your ToDo here (index the bp_data variable)\n\n# your solution here\n\n```\n\n\n```python\n''' Tests the above ToDo. '''\nif 'day_18_condition_on' not in dir():\n    raise ValueError(\"The variable 'day_18_condition_on' is not defined!\")\n    \ntest_bloodpressure_index(day_18_condition_on)\n```\n\nMultidimensional indexing using slices (especially the single colon `:` slice, i.e., selecting everything) is very common in scientific programming such as neuroimaging analyses. There is, however, yet another way of (multidimensional) indexing called \"boolean indexing\". \n\nIn this type of indexing, you index an array with a boolean array (i.e. array with True and False values) of the same shape. Basically, when you're indexing the array `my_array` with boolean array `bool_array`, you're saying: \"give me all values in `my_array` that are `True` at the same location in `bool_array`!\"\n\nLet's look at an example:\n\n\n```python\nmy_array = np.array([[1, 2, 3],\n                     [4, 5, 6],\n                     [7, 8, 9]])\n\nprint(\"The original array:\\n\")\nprint(my_array, '\\n')\n\nbool_array = np.array([[True, False, True],\n                       [False, True, False],\n                       [True, False, True]])\n\nprint(\"The boolean array:\\n\")\nprint(bool_array, '\\n')\n\nprint('Result of indexing my_array with bool_array:\\n')\nprint(my_array[bool_array])\n```\n\n    The original array:\n    \n    [[1 2 3]\n     [4 5 6]\n     [7 8 9]] \n    \n    The boolean array:\n    \n    [[ True False  True]\n     [False  True False]\n     [ True False  True]] \n    \n    Result of indexing my_array with bool_array:\n    \n    [1 3 5 7 9]\n\n\nUsually, you do not write out the boolean array in full (as we did above), but you base it on the data itself to \"filter\" it according to some criterion formalized as a logical statement (i.e., using the boolean operators >, <, ==, or !=). For example, suppose I want to extract only the values above 6 from the `my_array` variable in the above example. \n\nTo do so, I could do the following:\n\n\n```python\nmy_array = np.array([[1, 2, 3],\n                     [4, 5, 6],\n                     [7, 8, 9]])\n\nprint(\"The original array:\\n\")\nprint(my_array, '\\n')\n\nbool_array = my_array > 6\n\nprint(\"The boolean array:\\n\")\nprint(bool_array, '\\n')\n\nprint('Result of indexing my_array with bool_array:\\n')\nprint(my_array[bool_array])\n```\n\n    The original array:\n    \n    [[1 2 3]\n     [4 5 6]\n     [7 8 9]] \n    \n    The boolean array:\n    \n    [[False False False]\n     [False False False]\n     [ True  True  True]] \n    \n    Result of indexing my_array with bool_array:\n    \n    [7 8 9]\n\n\nEasy, right? Now try it yourself in the next ToDo!\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nUse a boolean index to extract all values whose square (i.e. $value^2$) is larger than 4 from the array (`my_array`) below. Store the results in a variable with the name `square_is_larger_than_4`.\n\n\n```python\nmy_array = np.array([[0, 1, -1, -2],\n                     [2, -5, 1, 4],\n                     [10, -2, -4, 20]])\n\n# Make a new boolean array below (name it whatever you want) ...\n\n# And use it to index my_array and store it in a variable `square_is_larger_than_4`.\nbol_ar = my_array**2 > 4\n# your solution here\nsquare_is_larger_than_4 = my_array[bol_ar]\nsquare_is_larger_than_4\n```\n\n\n\n\n    array([-5,  4, 10, -4, 20])\n\n\n\n\n```python\nif 'square_is_larger_than_4' not in dir():\n    raise ValueError(\"Could not find the variable 'square_is_larger_than_4'; did you name it correctly?\")\n\ntest_boolean_indexing(square_is_larger_than_4)\n```\n\nAgain, it's very important to understand how to (effectively) index multidimensional numpy arrays using slices and boolean indexing, as we'll use it a lot in this course!\n\n### Numpy: data-types\nEvery numpy array is a grid of values of the same type. Numpy provides a large set of numeric datatypes that you can use to construct arrays. Numpy guesses the datatype when you create an array, but functions that construct arrays usually also include an optional argument to explicitly specify the datatype.\n\nHere are a couple of examples:\n\n\n```python\nx1 = np.array([1, 2])  # Let numpy choose the datatype (here: int)\nx2 = np.array([1.0, 2.0])  # Let numpy choose the datatype (here: float)\nx3 = np.array([1, 2], dtype=np.float64)  # Force a particular datatype (input: int, but converted to 64bit float)\nx4 = np.array([-1, 0, 1, 2], dtype=bool)  # Convert ints to booleans! 0 -> False, everthing else -> True \n\nprint('%r (%s)' % (x1, type(x1[0])))\nprint('%r (%s)' % (x2, type(x2[0])))\nprint('%r (%s)' % (x3, type(x3[0])))\nprint('%r (%s)' % (x4, type(x4[0])))\n```\n\n    array([1, 2]) (<class 'numpy.int64'>)\n    array([1., 2.]) (<class 'numpy.float64'>)\n    array([1., 2.]) (<class 'numpy.float64'>)\n    array([ True, False,  True,  True]) (<class 'numpy.bool_'>)\n\n\n### Numpy: methods vs. functions\nIn the previous section (Basic Python), you've learned that, in addition to functions, 'methods' exist that are like functions of an object. In other words, methods are functions that are applied to the object itself. You've seen examples of list methods, e.g. `my_list.append(1)`, and string methods, e.g. `my_string.replace('a', 'b')`.\n\nLike lists and strings, numpy arrays have a lot of convenient methods that you can call. Again, this is just like a function, but then applied to itself. Often, numpy provides both a function and method for simple operations. \n\nLet's look at an example: \n\n\n```python\nmy_array = np.arange(10)  # creates a numpy array from 0 until (excluding!) 10\nprint(my_array, '\\n')\n\nmean_array = np.mean(my_array)\nprint('The mean of the array is: %f' % mean_array, '\\n')\n\nmean_array2 = my_array.mean() \nprint('The mean of the array (computed by its corresponding method) is: %f' % mean_array2, '\\n')\n\nprint('Is the results from the numpy function the same as '\n      'the corresponding method? Answer: %s' % str(mean_array == mean_array2))\n```\n\n    [0 1 2 3 4 5 6 7 8 9] \n    \n    The mean of the array is: 4.500000 \n    \n    The mean of the array (computed by its corresponding method) is: 4.500000 \n    \n    Is the results from the numpy function the same as the corresponding method? Answer: True\n\n\nIf there is both a function and a method for the operation you want to apply to the array, it really doesn't matter what you choose! Let's look at some more (often used) methods of numpy ndarrays:\n\n\n```python\nmy_array = np.array([[1, 2, 3],\n                     [4, 5, 6],\n                     [7, 8, 9]])\n\nstd_my_array = my_array.std()  # same as np.std(array)\nprint(\"Standard deviation of my_array: %.3f\" % std_my_array, '\\n')\n\ntranspose_my_array = my_array.T  # same as np.transpose(array)\nprint(\"Transpose of my_array:\\n%r\" % transpose_my_array, '\\n')\n\nmin_my_array = my_array.min()  # same as np.min(array)\nprint(\"Minimum of my_array: %i\" % my_array.min(), '\\n')\n\nmax_my_array = my_array.max()  # same as np.max(array)\nprint(\"Maximum of my_array: %i\" % max_my_array, '\\n')\n\nsum_my_array = my_array.sum()  # same as np.sum(array)\nprint(\"Sum of my_array: %i\" % sum_my_array, '\\n')\n```\n\n    Standard deviation of my_array: 2.582 \n    \n    Transpose of my_array:\n    array([[1, 4, 7],\n           [2, 5, 8],\n           [3, 6, 9]]) \n    \n    Minimum of my_array: 1 \n    \n    Maximum of my_array: 9 \n    \n    Sum of my_array: 45 \n    \n\n\nImportantly, a method may or may not take arguments (input).\nIf no arguments are given, it just looks like \"object.method()\", i.e. two enclosing brackets with nothing in between.\nHowever, a method may take one or more arguments (like the my_list.append(1) method)! \nThis argument may be named or unnamed - doesn't matter. An example:\n\n\n```python\nmy_array2 = np.random.random((3, 3))\nprint('Original array:')\nprint(my_array2, '\\n')\n\nprint('Use the round() method with the argument 3:')\nprint(my_array2.round(3), '\\n')\n\nprint('Use the round() method with the named argument 5:')\nprint(my_array2.round(decimals=5), '\\n')\n```\n\n    Original array:\n    [[0.32710922 0.30512889 0.84403235]\n     [0.6239239  0.29343832 0.71361229]\n     [0.34459281 0.58655561 0.99263403]] \n    \n    Use the round() method with the argument 3:\n    [[0.327 0.305 0.844]\n     [0.624 0.293 0.714]\n     [0.345 0.587 0.993]] \n    \n    Use the round() method with the named argument 5:\n    [[0.32711 0.30513 0.84403]\n     [0.62392 0.29344 0.71361]\n     [0.34459 0.58656 0.99263]] \n    \n\n\n**Some methods that you'll see a lot in the upcoming tutorials**. In addition to the methods listed above, you'll probably see the following methods a lot in the rest of this course (make sure you understand them!):\n\nReshaping arrays:\n\n\n```python\nmy_array = np.arange(10)\nprint(my_array.reshape((5, 2))) # reshape to desired shape\n```\n\n    [[0 1]\n     [2 3]\n     [4 5]\n     [6 7]\n     [8 9]]\n\n\n\n```python\n\n```\n\nRavel (\"flatten\") an array:\n\n\n```python\ntemporary = my_array.reshape((5, 2))\nprint(\"Initial shape: %s\" % (temporary.shape,))\nprint(temporary.ravel()) # unroll multi-dimensional array to single 1D array\nprint(\"Shape after ravel(): %s\" % (temporary.ravel().shape,))\n```\n\n    Initial shape: (5, 2)\n    [0 1 2 3 4 5 6 7 8 9]\n    Shape after ravel(): (10,)\n\n\n\n```python\n# .dot() does matrix multiplication (dot product: https://en.wikipedia.org/wiki/Dot_product)\n# This linear algebra operation is used very often in neuroimaging research \n# (which depends heavily on the General Linear Model!)\narray1 = np.array([0, 1, 2, 3])\narray2 = np.array([4, 5, 6, 7])\n\ndot_product = array1.dot(array2)\nprint(dot_product)\n```\n\n    38\n\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nLet's practice writing functions some more. Complete the function below, named `calculate_range`. This function takes  a single input-argument - a 1D numpy array - and subsequently calculates the [range](https://en.wikipedia.org/wiki/Range_(statistics) of the array. The range is the difference between the maximum and minimum of any given array (vector) $x$:\n\n\\begin{align}\nrange(x) = max(x) - min(x)\n\\end{align}\n\nYou may use the corresponding numpy min/max methods or functions in your custom function, doesn't matter. Don't forget to explicitly return the value of the range! \n\nNote: this custom function that implements the *mathematical* formula for a vector's range is completely unrelated to the *Python function* `range` that is often used in for-loops! \n\n\n```python\n# Complete the function below\ndef calculate_range(arr):\n    ''' Calculate the range of an array.\n    \n    Parameters\n    ----------\n    arr : a 1D numpy array\n    \n    Returns\n    -------\n    The range of the input arr\n    '''\n    \n    # your solution here\n    return arr.max() - arr.min()\n\n```\n\n\n```python\n''' Tests the above ToDo. '''\n\noutp = calculate_range(np.array([0, 1, 2, 3]))\nif outp is None:\n    raise ValueError(\"Didn't get any output! Did you explicitly return the range?\")\n\nassert(outp == 3)\nassert(calculate_range(np.array([-1, 0, 1, 2])) == 3)\nassert(calculate_range(np.array([0, 0, 0, 0])) == 0)\n\nprint(\"Well done!\")\n```\n\n    Well done!\n\n\n### Numpy: methods vs. attributes?\nAlright, by now, if you see a variable followed by a word ending with enclosed brackets, e.g. `my_array.mean()`, you'll know that it's a method! But sometimes you might see something similar, but **without** the brackets, such as `my_array.size`. This `.size` is called an **attribute** of the variable `my_array`. Like a method, it's an integral part of an object (such as a numpy ndarray). The attribute may be of any data-type, like a string, integer, tuple, an array itself. Let's look at an example:\n\n\n```python\nmy_array = np.array([[1, 2, 3],\n                     [4, 5, 6],\n                     [7, 8, 9]])\n\nprint(my_array, '\\n')\nprint('The size (number of element) in the array is:')\nprint(my_array.size, '\\n')\nprint('The .size attribute is of data-type: %s' % type(my_array.size))\nlen(my_array)\n```\n\n    [[1 2 3]\n     [4 5 6]\n     [7 8 9]] \n    \n    The size (number of element) in the array is:\n    9 \n    \n    The .size attribute is of data-type: <class 'int'>\n\n\n\n\n\n    3\n\n\n\nAlright, so by now you might be wondering what the difference between a method and an attribute is. Superficially, you can recognize a method by the form `object.method()` (note the brackets!), like `my_array.round()`; an attribute is virtually the same **but without brackets**, in the form of `object.attribute`, like `my_array.size`. \n\nConceptually, you may think of methods as things that **do** something with the array, while attributes **say** something about the array.\n\nFor example, `my_array.size` **does nothing** with the array - it only **says** something about the array (it gives information about its size), while `my_array.mean()` really **does** something (i.e. calculates the mean of the array). \n\nAgain, you might not use attributes a lot during this course, but you'll definitely see them around in the code of the tutorials. Below, some of the common ndarray attributes are listed:\n\n\n```python\nmy_array = np.array([[1, 2, 3],\n                     [4, 5, 6],\n                     [7, 8, 9]])\n\nprint('Size (number of elements) of array:')\nprint(my_array.size, '\\n') # returns an integer\n\nprint('Shape of array:')\nprint(my_array.shape, '\\n') # this is a tuple!\n\nprint('Number of dimensions:')\nprint(my_array.ndim) # this is an integer\n```\n\n    Size (number of elements) of array:\n    9 \n    \n    Shape of array:\n    (3, 3) \n    \n    Number of dimensions:\n    2\n\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (2 points)\n</div>\nLet's try another one. Complete the function below, named `compute_one_sample_ttest`. This function takes two input arguments:\n\n- arr : a 1D numpy array\n- h0 : a scalar value (single number) that represents the value representing the null-hypothesis\n\nThe function should compute the one-sample t-test, which tests whether the mean of an array is significantly different from a given value representing the null-hypothesis. Formally, for any given array $x$ and null-hypothesis $h_{0}$:\n\n\\begin{align}\nt = \\frac{\\bar{x} - h_{0}}{s\\ / \\sqrt{N}}\n\\end{align}\n\nHere: $\\bar{x}$ represents the mean of $x$, $s$ represents the standard deviation of $x$, and $N$ represents the length ('size') of x. So, in slightly less mathematical notation:\n\n\\begin{align}\nt = \\frac{mean(x) - h_{0}}{std(x)\\ / \\sqrt{length(x)}}\n\\end{align}\n\nMake sure to return the t-value! \n\n**Hint 1**: to compute $N$, you can use the `.size` attribute of an array ... <br>\n**Hint 2**: use the function `np.sqrt(some_number)` to calculate the square root ...\n\n\n```python\n# Complete the function below!\ndef compute_one_sample_ttest(arr, h0):\n    ''' Computes the one-sample t-test for any array and h0. \n    \n    Parameters\n    ----------\n    arr : a 1D numpy array\n    h0 : an int or float\n    \n    Returns\n    -------\n    A single value representing the t-value\n    '''\n    \n    # your solution here\n    return (arr.mean() - h0) / (arr.std() / np.sqrt(arr.size))\n\n```\n\n\n```python\n''' Tests the ToDo above. '''\narr = np.random.randn(100)\noutp = compute_one_sample_ttest(arr , 0)\n\nif outp is None:\n    raise ValueError(\"Your function didn't return anything! Did you forget the return statement?\")\n\ntest_tvalue_computation(arr, 0, outp)\n\noutp = compute_one_sample_ttest(arr, 5) \ntest_tvalue_computation(arr, 5, outp)\n\noutp = compute_one_sample_ttest(arr, -3) \ntest_tvalue_computation(arr, -3, outp)\n```\n\n### Numpy: array math\nNow you know all the numpy basics necessary to do neuroimaging analysis! As you'll see in the last section (Working with nifti-images), we'll work with 3D (structural MRI images) or 4D (functional MRI images) numpy arrays a lot. Given that you know how the basics about numpy in general and numpy ndarrays in particular, we can utilize some of numpy's best features: (very fast) array math.\n\nBasic mathematical functions operate elementwise on arrays, which means that the operation (e.g. addition) is applied onto each element in the array.\n\nSo, let's initialize a 1D array with ten zeros and let's add 1 to it:\n\n\n```python\nx = np.zeros(10)\nprint(x, '\\n')\nx += 1 # remember: this the same as x = x + 1\nprint(x)\n```\n\n    [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] \n    \n    [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]\n\n\nAdditionally, you can also sum two arrays together in an elementwise manner by simply writing: `array_1 + array_2`, given that these two (or more) arrays are of the same shape! Let's look at an example:\n\n\n```python\nx = np.array([[1,2],[3,4]], dtype=np.float64)\ny = np.array([[5,6],[7,8]], dtype=np.float64)\n\nprint(\"x: \\n%r\" % x, '\\n')\nprint(\"y: \\n%r\" % y, '\\n')\nprint(\"x+y: \\n%r\" % (x + y), '\\n')\n```\n\n    x: \n    array([[1., 2.],\n           [3., 4.]]) \n    \n    y: \n    array([[5., 6.],\n           [7., 8.]]) \n    \n    x+y: \n    array([[ 6.,  8.],\n           [10., 12.]]) \n    \n\n\nOften, there exist function-equivalents of the mathematical operators. For example, `x + y` is the same as `np.add(x, y)`. However, it is recommended to use the operators wherever possible to improve readability of your code. See below for an example:\n\n\n```python\nprint(x + y, '\\n')\nprint(np.add(x, y))\n```\n\n    [[ 6.  8.]\n     [10. 12.]] \n    \n    [[ 6.  8.]\n     [10. 12.]]\n\n\nNext to addition, we can also do elementwise subtraction, multiplication, divison, square root, and exponentiation:\n\n\n```python\n# Elementwise difference; both produce the array\nprint(x - y, '\\n')\nprint(np.subtract(x, y))  # function-equivalent of above \n```\n\n    [[-4. -4.]\n     [-4. -4.]] \n    \n    [[-4. -4.]\n     [-4. -4.]]\n\n\n\n```python\n# Elementwise product; both produce the array\nprint(x * y, '\\n')\nprint(np.multiply(x, y))\n```\n\n    [[ 5. 12.]\n     [21. 32.]] \n    \n    [[ 5. 12.]\n     [21. 32.]]\n\n\n\n```python\n# Elementwise division; both produce the array\n# [[ 0.2         0.33333333]\n#  [ 0.42857143  0.5       ]]\nprint(x / y, '\\n')\nprint(np.divide(x, y))\n```\n\n    [[0.2        0.33333333]\n     [0.42857143 0.5       ]] \n    \n    [[0.2        0.33333333]\n     [0.42857143 0.5       ]]\n\n\n\n```python\n# Elementwise square root; there is no operator-equivalent!\nprint(np.sqrt(x))\n```\n\n    [[1.         1.41421356]\n     [1.73205081 2.        ]]\n\n\n\n```python\n# Elementwise exponentiation\nprint(x ** y, '\\n')\nprint(np.power(x, y))\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nDo an elementwise product between the two variables defined below (`arr_A` and `arr_B`) and subsequently add 5 to each element; store the result in a new variable called `result_product_and_sum`.\n\n\n```python\n# Implement the ToDo!\narr_A = np.arange(10).reshape((5, 2))\narr_B = np.arange(10, 20).reshape((5, 2))\n\n# your solution here\nresult_product_and_sum = arr_A * arr_B + 5\n\n```\n\n\n```python\n''' Tests the above ToDo. '''\nif 'result_product_and_sum' not in dir():\n    raise ValueError(\"The variable 'result_product_and_sum' does not seem to exist!\")\n\ntest_array_product_and_sum(result_product_and_sum)    \n```\n\nNote that unlike MATLAB, `*` is elementwise multiplication, not matrix multiplication. We instead use the dot function (or method!) to  compute matrix operations like inner products of vectors, multiplication of a vector by a matrix, and multiplication of two matrices.\n\nThese matrix operations are quite important in this course, because they are used a lot in neuroimaging methods (such as the General Linear Model, the topic of next week!). You're not expected to fully understand these matrix operations, but you'll see them several times in this course, so make sure you're familiar with its implementation in Python/Numpy.\n\nAn example of the inner product (\"dot product\") of two vectors in both the function-format and the method-format:\n\n\n```python\nv = np.array([9,10])\nw = np.array([11, 12])\n\n# Inner product of vectors; both produce 219\nprint(v.dot(w))\nprint(np.dot(v, w))\n```\n\n    219\n    219\n\n\nProbably the most used functions in numpy are the sum() and mean() fuctions (or equivalent methods!). A nice feature is that they can operate on the entire array (this is the default) or they can be applied per dimension (or, in numpy lingo, per \"axis\").\n\nApplying functions along axes is very common in scientific computing! Let's look at an example in which we apply the `sum` function/method across rows and columns:\n\n\n```python\nx = np.array([[1, 2],[3, 4], [5, 6]])\n\nprint('Original array:')\nprint(x, '\\n')\n\nprint('Sum over ALL elements of x:')\nprint(np.sum(x), '\\n')\n\nprint('Sum across rows of x:')\nprint(np.sum(x, axis=0), '\\n')\n\nprint('Sum across columns of x:')\nprint(x.sum(axis=1)) # this is the method form! Is exactly the same as np.sum(x, axis=1) \n```\n\n    Original array:\n    [[1 2]\n     [3 4]\n     [5 6]] \n    \n    Sum over ALL elements of x:\n    21 \n    \n    Sum across rows of x:\n    [ 9 12] \n    \n    Sum across columns of x:\n    [ 3  7 11]\n\n\nImportantly, application of functions across axes is much quicker (and more concise) than writing for-loops! Let's look at the speed difference between a for-loop (implemented as a list comprehension) and the numpy-style application of the `sum` function across axes:\n\n\n```python\narr = np.random.random((1000, 100))\nloop_style = %timeit -o [arr[i, :].sum() for i in range(arr.shape[0])]\naxis_style = %timeit -o arr.sum(axis=1)\nprint(\"Using the axis-argument is %.3f times faster than a for-loop!\" % (loop_style.average / axis_style.average))\n```\n\n    1.76 ms \u00b1 279 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 100 loops each)\n    60.6 \u00b5s \u00b1 6.24 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 10000 loops each)\n    Using the axis-argument is 28.995 times faster than a for-loop!\n\n\nThis application of functions on entire arrays (in an elementwise manner, like `arr_1 + arr_2`) and application of functions across a certain axis (like `np.sum(arr_1, axis=1)`) is often called **vectorization**. This is an incredibly useful concept and something we'll use a lot in this course! Make sure you understand this. \n\nLet's practice this a bit.\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nRemember the \"range\" function from before? Below, we started writing a function, called `calculate_range_vectorized`, that calculates, for any 2D array, the range of each column (i.e. calculates range **across rows** for each column) in a *vectorized manner* (so without any for loops!).\n\nComplete the function, and make sure to return the result, which should be a 1D vector which values represents the ranges for all columns. So, if the input array would be of shape `(100, 10)`, then the shape of your returned array should be `(10,)`.\n\n\n```python\ndef compute_range_vectorized(arr):\n    ''' Compute the range across rows for each column in a 2D array. \n    \n    Parameters\n    ----------\n    arr : a 2D numpy array\n    \n    Returns\n    -------\n    A 1D vector with the ranges for each column\n    '''\n    \n    # your solution here\n    return arr.max(axis = 0) - arr.min(axis = 0)\n\n```\n\n\n```python\n\n```\n\n\n```python\nnp.random.seed(42)\ntest_arr = np.random.random((100, 10))\noutp = compute_range_vectorized(test_arr)\noutp\n\n\n\n```\n\n\n\n\n    array([0.97835067, 0.99508565, 0.99111472, 0.94810375, 0.97019384,\n           0.98376774, 0.97464742, 0.9860366 , 0.98221455, 0.94601832])\n\n\n\n### Broadcasting\nBroadcasting is a powerful mechanism that allows numpy to work with arrays of different shapes when performing arithmetic operations. Frequently we have a smaller array and a larger array, and we want to use the smaller array multiple times to perform some operation on the larger array.\n\nFor example, suppose that we want to add a vector to each row of a matrix. We could do it like this:\n\n\n```python\n# We will add the vector v to each row of the matrix x,\n# storing the result in the matrix y\nx = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\n\nprint('x array is of shape: %r' % (x.shape,))\nprint(x, '\\n')\n\nv = np.array([1, 0, 1])\nprint('v vector is of shape: %r (different shape than x!)' % (v.shape,))\nprint(v, '\\n')\n\ny = np.zeros(x.shape)   # Create an empty (zeros) matrix with the same shape as x\nprint('Shape of (pre-allocated) y-matrix: %r' % (y.shape,))\n\n# Add the vector v to each row of the matrix x with an explicit loop\nfor i in range(x.shape[0]): # see how the shape attributes comes in handy in creating loops?\n    y[i, :] = x[i, :] + v\n\nprint('The result of adding v to each row of x, as stored in y:')\nprint(y)\n```\n\nThis works; however when the matrix `x` is very large, computing an explicit for-loop in Python could be slow. Note that adding the vector v to each row of the matrix `x` is equivalent to forming a matrix `vv` by stacking multiple copies of `v` vertically, like this `[[1 0 1], [1 0 1], [1 0 1], [1 0 1]]`, and subsequently elementwise addition of `x + vv`:\n\n\n```python\nvv = np.tile(v, (4, 1)) # i.e. expand vector 'v' 4 times along the row dimension (similar to MATLAB's repmat function)\ny = x + vv  # Add x and vv elementwise\nprint(y)\n```\n\nNumpy **broadcasting** allows us to perform this computation without actually creating multiple copies of v. Consider this version, using broadcasting:\n\n\n```python\n# We will add the vector v to each row of the matrix x,\n# storing the result in the matrix y\nx = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\nv = np.array([1, 0, 1])\ny = x + v  # Add v to each row of x using broadcasting\nprint(y)\n```\n\nThe line `y = x + v` works even though `x` has shape `(4, 3)` and `v` has shape `(3,)` due to broadcasting; this line works as if v actually had shape `(4, 3)`, where each row was a copy of `v`, and the sum was performed elementwise.\n\nThis broadcasting function is really useful, as it prevents us from writing unnessary and by definition slower explicit for-loops. Additionally, it's way easier to read and write than explicit for-loops (which need pre-allocation). Functions that support broadcasting are known as universal functions. You can find the list of all universal functions in the [documentation](http://docs.scipy.org/doc/numpy/reference/ufuncs.html#available-ufuncs).\n\nHere are some applications of broadcasting using different functions:\n\n\n```python\nx = np.array([[1, 2],[3, 4], [5, 6]], dtype=np.float)\nx_sum = x.sum(axis=0)\n\nprint(x / x_sum, '\\n')\n\nx_mean = x.mean(axis=0)\nprint(x / x_mean)\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (2 points)\n</div>\nBelow, we started writing a function called `standardize_columns`, which takes a single input-argument - a 2D numpy array - and should subsequently *standardize* each column such that each column has a mean of zero and a standard deviation of 1. In other words, standardization subtracts the mean (across rows) of each column from the values in that column, and then divides those value with the standard deviation of that column. Formally, for each column $j$ in any 2D array, standardization entails:\n\n\\begin{align}\nx_{j}\\ standardized = \\frac{(x_{j} - \\bar{x_{j}})}{std(x_{j})}\n\\end{align}\n\nStandardization, which is also oftend called \"z-transformation\", is often done in statistics. We'll also see this next week.\n\nSo, in the function below, make sure that it is able to standardize each column in any 2D array. Make sure to use vectorized array computations (i.e, the `np.mean` and `np.std` functions/methods across rows) and broadcasting, so no for-loops! \n\n\n```python\ndef standardize_columns(arr):\n    ''' Standardize each column of a 2D input-array. \n    \n    Parameters\n    ----------\n    arr : a 2D numpy array\n    \n    Returns\n    -------\n    The input-array with standardized columns (should have the same shape as the input-array!)\n    '''\n    \n    # your solution here\n    \n```\n\n\n```python\n''' Tests the above ToDo. '''\n\ntest_arr = np.random.normal(5, 2, size=(100, 10))\noutp = standardize_columns(test_arr)\n\nif outp is None:\n    raise ValueError(\"The output from your function is None; did you forget the Return statement?\")\n\ntry:\n    np.testing.assert_array_almost_equal(outp.mean(axis=0), np.zeros(test_arr.shape[1]))\nexcept AssertionError as e:\n    print(\"The mean of the columns of your standardized array are not 0!\")\n    raise(e)\n\ntry:\n    np.testing.assert_array_almost_equal(outp.std(axis=0), np.ones(test_arr.shape[1]))\nexcept AssertionError as e:\n    print(\"The std of the columns of your standardized array are not 1!\")\n    raise(e)\n    \nprint(\"Well done!\")\n```\n\nNow, you know the most important numpy concepts and functionality that is necessary to do neuroimaging analysis. Surely, there is a lot more to the numpy package that what we've covered here! But for now, let's continue with plotting using Matplotlib!\n\n## 3. Matplotlib\nMatplotlib is Python's main plotting library. In this section give a brief introduction to the `matplotlib.pyplot` module, which provides a plotting system similar to that of MATLAB.\n\n\n```python\nimport matplotlib.pyplot as plt # this is how matplotlib.pyplot is usually imported\nimport numpy as np\n```\n\nBy running this special iPython command, we will be displaying plots inline (instead of in a new window; this is only relevant in Jupyter notebooks!):\n\n\n```python\n%matplotlib inline\n```\n\n### Plotting\nThe most important function in `matplotlib` is **`plot`**, which allows you to plot 1 dimensional data. Here is a simple example:\n\n\n```python\n# Draw a line with coordinates from vectors x and y\nx = np.arange(0, 11)  # 0 - 10\ny = np.arange(0, 11)  # 0 - 10, same as x\n\n# Plot the points using matplotlib\nplt.plot(x, y)\nplt.show()\n```\n\nWith just a little bit of extra work we can easily plot multiple lines at once, and add a title, legend, and axis labels:\n\n\n```python\ny2 = np.ones(x.size)  # vector of ones, i.e., straight line\n\n# Plot the points using matplotlib\nplt.plot(x, y)\nplt.plot(x, y2)\nplt.xlabel('x axis label')\nplt.ylabel('y axis label')\nplt.title('Two lines')\nplt.legend(['Linear increasing line', 'Constant line'])\nplt.show()\n```\n\n### Subplots \nYou can plot different subplots in a single figure using the subplot function. Here is an example:\n\n\n```python\n# Compute the x and y coordinates for points on sine and cosine curves\nx = np.arange(0, 3 * np.pi, 0.1)\ny_sin = np.sin(x)\ny_cos = np.cos(x)\n\n# Set up a subplot grid that has 2 'rows' and 1 'column',\n# and set the first such subplot as active.\nplt.subplot(2, 1, 1)  # the third argument here sets the 'active' plot\n\n# Make the first plot\nplt.plot(x, y_sin)\nplt.title('Sine')\n\n# Set the second subplot as active, and make the second plot.\nplt.subplot(2, 1, 2)\nplt.plot(x, y_cos)\nplt.title('Cosine')\n\n# Show the figure.\nplt.tight_layout() # this prevents plots from overlapping\nplt.show()\n```\n\nAnd we can add text to plots as such:\n\n\n```python\nx = np.arange(-1, 1, 0.01) # array from -1 to 1 in steps of 0.01\n\n# Set up a subplot grid that has 2 'rows' and 1 'column',\n# and set the first such subplot as active.\nplt.subplot(2, 1, 1)\nplt.plot(x, x ** 2)\nplt.title('x squared')\nplt.text(-0.5, 0.4, r\"$y=x^2$\", fontsize=20, color=\"blue\")\n\n# Set the second subplot as active, and make the second plot.\nplt.subplot(2, 1, 2)\nplt.plot(x, x ** 3)\nplt.title('x cubed')\nplt.text(-0.5, 0.4, r\"$y=x^3$\", fontsize=20, color=\"green\")\n\nplt.tight_layout()\nplt.show()\n```\n\nYou can read much more about the `subplot` function in the [documentation](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplot).\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nBelow, we initialized a 2D array of shape `(10, 100)` named `arr_2D`. In a figure with two subplots (across two columns), plot in the left subplot the mean across columns (i.e., 10 values) and in the right subplot plot the standard deviation across columns (also 10 values). **Hint**: these values represent the values on the `y-axis`. You can use `x = np.arange(10)` for the `x-axis`.\n\nAlso, give the subplots labels for the x- and y-axis, and give it a title.\n\nNote: this ToDo is manually graded, so there is no test-cell!\n\n\n```python\narr_2D = np.random.normal(0, 1, size=(10, 100))\n\n# Make your plot below!\n\n# your solution here\nx = np.arange(10)\n\nplt.subplot(1, 2, 1)\nplt.plot(x, arr_2D.mean(axis = 1))\nplt.title(\"col means\")\n\nplt.subplot(1, 2, 2)\nplt.plot(x, arr_2D.std(axis = 1))\nplt.title(\"col stds\")\nplt.show\n\n```\n\n\n```python\n\n```\n\n### Histograms\nNow let's generate some random data using the np.random functionality, and get some histograms of their distributions\n\n\n```python\nrand_uniform = np.random.uniform(size = (1000)) # uniform distribution\nrand_normal = np.random.normal(size = (1000))   # normal distribution\nrand_exponential = np.random.exponential(size = (1000)) # exponential distribution\n```\n\n\n```python\n# Set up a subplot grid that has rows=2 and columns=3,\n# and set the first such subplot as active.\nplt.subplot(1, 3, 1)\n\n# Make the first plot\nplt.hist(rand_uniform, color='g')\nplt.title('uniform')\n\n# Set the second subplot as active, and make the second plot.\nplt.subplot(1, 3, 2)\nplt.hist(rand_normal, color='b')\n\nplt.title('normal')\n\n# Set the second subplot as active, and make the second plot.\nplt.subplot(1, 3, 3)\nplt.hist(rand_exponential, color='r')\nplt.title('exponential')\n\nplt.tight_layout()\nplt.show()\n```\n\n### Images\nSo far, we've been plotting lines. Matplotlib also has easy functionality for plotting two-dimensional data-arrays, such as pictures. This is done using the command `plt.imshow()`. We'll use this feature a lot, because it allows us to visualize 2D slices of MRI-data as well! (Remember, MRI data is essentially just a 3D \"picture\" of the brain.) \n\n\n```python\n# the scipy module includes some pictures, so we can use those:\nfrom scipy import misc\nbw_photo = misc.face(gray=True)\n\n# now we can use the imshow command to plot 2d data:\nplt.imshow(bw_photo,cmap='gray')\nplt.show()\n```\n\nImportanty, photos are just 2D arrays with numbers representing the luminance (in black-and-white pictures) of each pixel. You can see this by printing the loaded image:\n\n\n```python\nprint(\"Shape of photo object: %r\" % (bw_photo.shape,), '\\n')\nprint(bw_photo)\n```\n\n    Shape of photo object: (768, 1024) \n    \n    [[114 130 145 ... 119 129 137]\n     [ 83 104 123 ... 118 134 146]\n     [ 68  88 109 ... 119 134 145]\n     ...\n     [ 98 103 116 ... 144 143 143]\n     [ 94 104 120 ... 143 142 142]\n     [ 94 106 119 ... 142 141 140]]\n\n\nYou can see that it's actually just a bunch of numbers (one number per pixel), and when we plot colorbar with the original picture, we see that high numbers convert to bright shades, and low numbers convert to dark shades. \n\n\n```python\nplt.imshow(bw_photo,cmap='gray')\nplt.colorbar()\nplt.show()\n```\n\nUsing the knowledge that black and white images are nothing more than just 2d-arrays of values, we can also generate our own images:\n\n\n```python\nrand_img = np.random.random((200,200)) # Create an array filled with random values\nprint(rand_img, '\\n')\nplt.imshow(rand_img, cmap='gray')\nplt.colorbar()\nplt.show()\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (0 points, no test-cell)\n</div>\nBelow, we loaded in a 2D array of shape (91, 108) named `mystery_data`. Visualize it using `plt.imshow()` (using the argument `cmap='gray'`) to check out what the data entails!\n\n\n```python\nmystery_data = np.load('mystery_data.npy')\n\n# Visualize it using plt.imshow!\nplt.imshow(mystery_data, cmap = 'gray')\nplt.colorbar()\nplt.show()\n```\n\nNow that you know some basics of data types, arrays and plotting, it's time to get to work with some fMRI data!\n\n## 3. Neuroimaging analysis with Python\nAlthough (f)MRI data can come in many formats, by far the most used format is **nifti** (nifti has been developed by the **n**euroimaging **i**n**f**ormatics **t**echnology **i**nitiative). Throughout these tutorials you'll work with these nifti-files (also called nifti images), which you can recognize by their extension of **.nii** or its compressed version **.nii.gz**. This file-format is also used by some of the main neuroimaging software packages such as AFNI, nipype, and FSL. (You'll use FSL later in this course!). \n\nHowever, we'd like to inspect and analyze nifti images in Python as well! **Nibabel** is a Python package that allows us to read and load nifti images as numpy arrays in a straightforward manner. Let's look at an example:\n\n\n```python\n# If you haven't done so already, load some other packages we need\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport nibabel as nib # common way of importing nibabel\n```\n\n    /opt/conda/lib/python3.5/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n      from ._conv import register_converters as _register_converters\n\n\nWe'll load in an fMRI-scan using nibabel below:\n\n\n```python\ndata_path = 'func_data.nii.gz'\ndata = nib.load(data_path)\n```\n\nRight now, we haven't loaded the *actual* data **in memory** yet, but only the meta-data (information **about** the data, such as its shape, dimensions, and some technical MRI acquisition parameters). So, what we've loaded now (in the variable `data`) is **not** a numpy array (yet), but a different object: a `Nifti-object`.\n\nLike a numpy array, this object has some attributes and methods that we can use. \nLet's check out some of this meta-data that is already available through its methods/attributes.\n\nFor example, `Nifti-objects`, like numpy-arrays, also have a `shape` attribute:\n\n\n```python\nprint('Shape of the data:')\nprint(data.shape) # this is one of the attributes of a Nifti-object in Python, just like a numpy array shape attribute!\n```\n\n    Shape of the data:\n    (80, 80, 37, 200)\n\n\nFrom the shape of the data, we can already infer some things about the file we're working with. Clearly, it has 4 dimensions, which means that it is a functional file: 3 spatial dimensions, and 1 time dimension! Remember the blood-pressure data? This 4D representation of fMRI files is very similar. Here, each axis represents a different feature/factor of the data: \n\n1. the first axis represents the first spatial dimension (the \"saggital\" dimension, usually referred to as $X$)\n2. the second axis represents the second spatial dimension (the \"coronal\" dimension, usually referred to as $Y$)\n3. the third axis represents the third spatial dimension (the \"axial\" dimension, usually referred to as $Z$)\n4. the fourth axis represents the time dimension (usually referred to as $T$, or $N$, \"volumes\", or \"dynamics\")\n\nWe'll practice with this data-organization later.\n\nAnother attribute of this Nifti-object that you might check is the **header** attribute. Perhaps confusingly, the header attribute is another object itself, also with its own methods and attributes. Let's check out some of them: \n\n\n```python\nheader = data.header\nprint('Get the measurements of our dimensions:')\nprint(header.get_zooms())\n```\n\n    Get the measurements of our dimensions:\n    (3.0, 3.0, 3.3, 2.0)\n\n\nAbove, the four numbers represent the measurements of the data's four dimensions (3 space dims, 1 time dim). But what the hell do these numbers represent? Millimeters, liters, km/hr?\n\nActually, the units of these dimensions can be accessed through the `header.get_xyzt_units()` (x, y, and z = spatial dims, t = time dims):\n\n\n```python\nprint('Units of our measurements:')\nprint(header.get_xyzt_units())\n# so space is in mm (voxels are 3 x 3 x 3.3 mm in size!) and time is in seconds (time resolution = 2 seconds)\n```\n\n    Units of our measurements:\n    ('mm', 'sec')\n\n\nSo now we know that our data reflects activity from 3 x 3 x 3.3 mm voxels across 200 timepoints sampled at a time resolution of 2 seconds. Now, let's dig a little deeper into the data! But remember, we still have to load the actual data in memory. We can do that by the `get_data()` method. This method actually returns a numpy 4D-array we can work with!\n\n\n```python\nfunc_data_in_memory = data.get_data()\nprint(type(func_data_in_memory))  # this is in fact a numpy array!\n```\n\n    <class 'numpy.ndarray'>\n\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nFrom the variable `func_data_in_memory`, extract (i.e., index) all values (across time) from the voxel located at saggital slice number 30, coronal slice number 50, and axial slice number 23. Store these values in the variable `voxel_timeseries`, which should be of shape `(100,)`.\n\n\n```python\n# Implement the ToDo here (remember: Python's indexing is zero-based!)\n\n# your solution here\n\n```\n\n\n```python\n''' Tests the above ToDo. '''\nif 'voxel_timeseries' not in dir():\n    raise ValueError(\"Could not find any variable named 'voxel_timeseries'; did you spell it correctly?\")\n\ntest_extract_voxel_timeseries(func_data_in_memory, voxel_timeseries)\n```\n\nLet's look at some of the data! Because we have $80\\ (X) \\times\\ 80\\ (Y)\\times\\ 37\\ (Z)\\times\\ 100\\ (T) = 23680000$ values in total, let's not look at all data at once. We'll select a [axial](https://en.wikipedia.org/wiki/Anatomical_plane) slice somewhere in the middle of the brain of the first recorded volume (i.e. t = 1).\n\n\n```python\naxial_slice_no = 18\nslice_1 = func_data_in_memory[:, :, axial_slice_no, 0] # the 0 refers to the first timepoint (t = 1)\nprint(slice_1, '\\n')\nprint('Shape of slice_1: %r' % list(slice_1.shape))\n```\n\n    [[0. 0. 0. ... 0. 0. 0.]\n     [0. 0. 0. ... 0. 0. 0.]\n     [0. 0. 0. ... 0. 0. 0.]\n     ...\n     [0. 0. 0. ... 0. 0. 0.]\n     [0. 0. 0. ... 0. 0. 0.]\n     [0. 0. 0. ... 0. 0. 0.]] \n    \n    Shape of slice_1: [80, 80]\n\n\nHmm, seems like nothing is going on! This is because Python doesn't print out the entire array, because that would clutter the notebook. Here, it is only plotting the first couple of rows and the last couple of rows from slice_1. The fact that we're only seeing zeros is because not all 23680000 values contain brain data! If a data point has value 0, it is very likely that this data point falls outside the recording of the brain.\n\nLet's check whether this is indeed the case. To visualize the entire slice, let's plot is using `imshow`:\n\n\n```python\nplt.imshow(slice_1, cmap='gray')\nplt.axis('off')  # Do not plot the tickmarks of x-axis and y-axis \nplt.show()\n```\n\nAs you can see, only a part of the image is brain data, which is centered in the middle of the image. All completely black locations in the image are represented as zeros in the slice-data. Knowing this, let's select (slice) only a small part of some actual brain data, as visualized below:\n\n\n```python\nimport matplotlib.patches as patches\n\nprint('We will select (index) the region indicated by red square:')\nrect = patches.Rectangle((35, 35), 5, 5, linewidth=2, edgecolor='r', facecolor='none')\nplt.imshow(slice_1, cmap='gray')\nax = plt.gca()\nax.add_patch(rect)\nplt.axis('off')\nplt.show()\n```\n\n\n```python\n# The data corresponding to the red square above\nprint(slice_1[35:41, 35:41])\n```\n\n    [[18910.754 19797.008 19496.709 18136.812 16348.341 14807.348]\n     [18662.031 19416.506 19315.932 18834.494 17968.053 16776.805]\n     [16337.761 18613.24  19266.787 18997.826 18172.816 17015.344]\n     [13643.852 16853.826 18110.594 17964.703 17332.225 16250.853]\n     [13439.482 16374.295 16968.223 16023.93  15165.015 14135.762]\n     [14196.337 16780.568 16897.617 15501.976 14583.225 13987.994]]\n\n\nWhat does this tell you? Well, fMRI data is simply a lot of numbers, with (relatively) higher numbers indicating (relatively) higher activity in functional MRI images.\n\nSo far, we have only looked at some (static) representation of voxel activity of some voxels at one particular timepoint (i.e, $t = 1$, the first volume of the data), ignoring the time-dimension of our data. We can also look at the activity of a single voxel (e.g., $X = 35$, $Y = 35$, $Z=18$) across time.\n\nThis basically amounts to indexing at these X/Y/Z coordinates! We'll show you what this entails conceptually in the code-block below, in which we show you that particular voxel at location X/Y/Z for the first 20 timepoints (not all 100, because that clutters the notebook too much):\n\n\n```python\nvolumes_to_plot = 20\nplt.figure(figsize=(30, 30))\n\n# Loop over the first 20 volumes/timepoints\nfor t in range(volumes_to_plot):\n    \n    plt.subplot(5, 5, (t+1))\n    plt.imshow(func_data_in_memory[:, :, axial_slice_no, t], cmap='gray')  # index with t!\n    rect = patches.Rectangle((35, 35), 1, 1, linewidth=1, edgecolor='r', facecolor='none')\n    ax = plt.gca()\n    ax.add_patch(rect)\n    plt.axis('off')\n    plt.title('t = %i' % (t + 1), fontsize=20)\nplt.show()\n```\n\nIt is really hard to spot whether the image of the slice is actually different between different time points! To the naked eye, it just seems like the same picture. This is because activity fluctations (over time) in fMRI are **very** small - most of the time just 1-3% compared to baseline (average) activity. That's why it's hard to spot activity differences by looking at the pictures alone.\n\nThe activity fluctuations become clearer when you plot the activity of voxels across time in a linegraph (which allows you to see *relative* activity fluctuations better). So, let's plot the activity over time (t = 1:100) for the voxel within the red square in the figure above:\n\n\n```python\nplt.plot(func_data_in_memory[35, 35, axial_slice_no, :])\nplt.title('Activity over time for voxel (35, 35, %i)' % axial_slice_no, fontsize=15)\nplt.xlabel('Time (t)', fontsize=15)\nplt.ylabel('Activity (arbitrary units)', fontsize=15)\n\nplt.show()\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (3 points)\n</div>\n\nLet's practice some of the skills that you learned in this tutorial! For this ToDo, you goal is to **plot an histogram of the average activity value across time for all non-zero voxels in the brain**. So, what you have to do is the following:\n\n1. Average the `func_data_in_memory` variable across time (resulting array should by of shape (80, 80, 37)\n2. Remove all voxels which are zero (use boolean indexing!)\n3. Make a histogram of all the resulting non-zero voxels (use the argument `bins=100` in `plt.hist`)\n\nDo this in the code-cell below. Also, *give the plot sensible labels for the axes*. This is a manually graded ToDo, so there is no test-cell.\n\nThe resulting histogram should show a \"bimodal distribution\" of average activity values - roughly with a peak around $x = 1000$ and a peak round $x = 10,000$. \n\n\n```python\n# Implement to ToDo here\n\n# your solution here\n\n```\n\nAlright, that's it! \n\n\n", "meta": {"hexsha": "ae5eb456487123606175efaaf980a203f404c006", "size": 1024754, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "python_tutorial.ipynb", "max_stars_repo_name": "mdsteiner/python_workshop-Basel", "max_stars_repo_head_hexsha": "57937a88681bd4650fe23873a56f7cb1a2d44481", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python_tutorial.ipynb", "max_issues_repo_name": "mdsteiner/python_workshop-Basel", "max_issues_repo_head_hexsha": "57937a88681bd4650fe23873a56f7cb1a2d44481", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python_tutorial.ipynb", "max_forks_repo_name": "mdsteiner/python_workshop-Basel", "max_forks_repo_head_hexsha": "57937a88681bd4650fe23873a56f7cb1a2d44481", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 153.4982025165, "max_line_length": 177024, "alphanum_fraction": 0.8822039241, "converted": true, "num_tokens": 34532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2877678157610531, "lm_q2_score": 0.13660837772343723, "lm_q1q2_score": 0.03931149447213443}}
{"text": "```python\n!pip install econml\n```\n\n    Collecting econml\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/fe/4d/a94c40f3af6fabc3160d4be7378913dcb652fe8a930e3f9ae523934aab2f/econml-0.10.0-cp37-cp37m-manylinux2010_x86_64.whl (3.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.0MB 6.6MB/s \n    \u001b[?25hCollecting dowhy\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/c4/e0/c1480994d39eaa66faa7d4106a4daea7b345dcc31ad83196460c2676701c/dowhy-0.6-py3-none-any.whl (123kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 133kB 37.4MB/s \n    \u001b[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from econml) (1.19.5)\n    Collecting shap~=0.38.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/44/20/54381999efe3000f70a7f68af79ba857cfa3f82278ab0e02e6ba1c06b002/shap-0.38.1.tar.gz (352kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 358kB 30.0MB/s \n    \u001b[?25hCollecting sparse\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/46/20/c409a0d0ea7623a936080e0038eb77a02e62629a07944706c26f24ebcbb8/sparse-0.12.0-py2.py3-none-any.whl (76kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 81kB 7.9MB/s \n    \u001b[?25hRequirement already satisfied: numba!=0.42.1 in /usr/local/lib/python3.7/dist-packages (from econml) (0.51.2)\n    Requirement already satisfied: statsmodels>=0.9 in /usr/local/lib/python3.7/dist-packages (from econml) (0.10.2)\n    Requirement already satisfied: scikit-learn>0.22.0 in /usr/local/lib/python3.7/dist-packages (from econml) (0.22.2.post1)\n    Requirement already satisfied: scipy>1.4.0 in /usr/local/lib/python3.7/dist-packages (from econml) (1.4.1)\n    Requirement already satisfied: graphviz in /usr/local/lib/python3.7/dist-packages (from econml) (0.10.1)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from econml) (1.1.5)\n    Requirement already satisfied: joblib>=0.13.0 in /usr/local/lib/python3.7/dist-packages (from econml) (1.0.1)\n    Requirement already satisfied: sympy>=1.4 in /usr/local/lib/python3.7/dist-packages (from dowhy->econml) (1.7.1)\n    Collecting pydot>=1.4\n      Downloading https://files.pythonhosted.org/packages/ea/76/75b1bb82e9bad3e3d656556eaa353d8cd17c4254393b08ec9786ac8ed273/pydot-1.4.2-py2.py3-none-any.whl\n    Requirement already satisfied: networkx>=2.0 in /usr/local/lib/python3.7/dist-packages (from dowhy->econml) (2.5.1)\n    Requirement already satisfied: tqdm>4.25.0 in /usr/local/lib/python3.7/dist-packages (from shap~=0.38.1->econml) (4.41.1)\n    Collecting slicer==0.0.7\n      Downloading https://files.pythonhosted.org/packages/78/c2/b3f55dfdb8af9812fdb9baf70cacf3b9e82e505b2bd4324d588888b81202/slicer-0.0.7-py3-none-any.whl\n    Requirement already satisfied: cloudpickle in /usr/local/lib/python3.7/dist-packages (from shap~=0.38.1->econml) (1.3.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from numba!=0.42.1->econml) (56.0.0)\n    Requirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba!=0.42.1->econml) (0.34.0)\n    Requirement already satisfied: patsy>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from statsmodels>=0.9->econml) (0.5.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->econml) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->econml) (2.8.1)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.4->dowhy->econml) (1.2.1)\n    Requirement already satisfied: pyparsing>=2.1.4 in /usr/local/lib/python3.7/dist-packages (from pydot>=1.4->dowhy->econml) (2.4.7)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.0->dowhy->econml) (4.4.2)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from patsy>=0.4.0->statsmodels>=0.9->econml) (1.15.0)\n    Building wheels for collected packages: shap\n      Building wheel for shap (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for shap: filename=shap-0.38.1-cp37-cp37m-linux_x86_64.whl size=490498 sha256=d13ab7c39debe73384eb735766167906abeace88737bd4415955f661167a8435\n      Stored in directory: /root/.cache/pip/wheels/a8/fb/e4/88012be41842b9be62ae18d82d1b1e880daf8539d1fef1fa00\n    Successfully built shap\n    Installing collected packages: pydot, dowhy, slicer, shap, sparse, econml\n      Found existing installation: pydot 1.3.0\n        Uninstalling pydot-1.3.0:\n          Successfully uninstalled pydot-1.3.0\n    Successfully installed dowhy-0.6 econml-0.10.0 pydot-1.4.2 shap-0.38.1 slicer-0.0.7 sparse-0.12.0\n\n\n\n```python\nfrom econml.policy import PolicyTree\nfrom econml.cate_interpreter import SingleTreePolicyInterpreter\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\n    /usr/local/lib/python3.7/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.\n      import pandas.util.testing as tm\n\n\n\n```python\nQ = pd.read_csv(\"CATE average.csv\", index_col=0)\n```\n\n\n```python\nQ\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>job search</th>\n      <th>vocational</th>\n      <th>computer</th>\n      <th>language</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>-1.280430</td>\n      <td>2.556203</td>\n      <td>1.482988</td>\n      <td>0.885377</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>-1.171464</td>\n      <td>2.273266</td>\n      <td>2.403585</td>\n      <td>2.758233</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>-1.589187</td>\n      <td>2.933885</td>\n      <td>2.899676</td>\n      <td>2.048820</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>-1.285102</td>\n      <td>2.904400</td>\n      <td>4.035316</td>\n      <td>1.410639</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>-1.804006</td>\n      <td>2.012930</td>\n      <td>4.175508</td>\n      <td>0.424482</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>62557</th>\n      <td>-1.754338</td>\n      <td>2.213183</td>\n      <td>2.095295</td>\n      <td>3.119136</td>\n    </tr>\n    <tr>\n      <th>62558</th>\n      <td>-2.180696</td>\n      <td>2.489197</td>\n      <td>2.776620</td>\n      <td>2.639378</td>\n    </tr>\n    <tr>\n      <th>62559</th>\n      <td>-0.992194</td>\n      <td>3.140326</td>\n      <td>4.095090</td>\n      <td>1.963767</td>\n    </tr>\n    <tr>\n      <th>62560</th>\n      <td>-1.407170</td>\n      <td>3.003563</td>\n      <td>2.470632</td>\n      <td>3.149166</td>\n    </tr>\n    <tr>\n      <th>62561</th>\n      <td>-0.661846</td>\n      <td>2.912520</td>\n      <td>1.920541</td>\n      <td>0.546992</td>\n    </tr>\n  </tbody>\n</table>\n<p>62561 rows \u00d7 4 columns</p>\n</div>\n\n\n\n\n```python\nQ['nontr'] = 0\nQ = Q[[\"nontr\", \"job search\", \"vocational\", \"computer\", \"language\"]]\n```\n\n\n```python\nX = pd.read_csv(\"x_clean.csv\", index_col=0)\n```\n\n\n```python\nX = X[[\"age\", \"female\", \"employability\", \"past_income\", \"gdp_pc\", \"unemp_rate\"]]\n```\n\n\n```python\npolicy = PolicyTree(honest=True, max_depth=6, random_state=0).fit(X, Q)\n```\n\n\n```python\npolicy.feature_importances_\n```\n\n\n\n\n    array([ 0.00000000e+00,  0.00000000e+00,  0.00000000e+00,  0.00000000e+00,\n            0.00000000e+00,  8.60450514e-04,  0.00000000e+00,  8.78323978e-17,\n            0.00000000e+00,  0.00000000e+00,  5.48952486e-17, -2.63497193e-14,\n            0.00000000e+00,  0.00000000e+00,  0.00000000e+00,  0.00000000e+00,\n            4.49658380e-03,  9.21500148e-01,  0.00000000e+00,  0.00000000e+00,\n            2.53825944e-02,  0.00000000e+00,  4.67163211e-02,  1.04390229e-03,\n            0.00000000e+00,  0.00000000e+00,  0.00000000e+00,  0.00000000e+00,\n            0.00000000e+00,  0.00000000e+00,  0.00000000e+00,  0.00000000e+00,\n            0.00000000e+00,  0.00000000e+00,  0.00000000e+00,  0.00000000e+00,\n            0.00000000e+00,  0.00000000e+00,  0.00000000e+00,  0.00000000e+00,\n           -2.19580995e-18,  0.00000000e+00])\n\n\n\n\n```python\nplt.figure(figsize=(25,10))\npolicy.plot(treatment_names=['nontr', 'jobsh', 'vocat', 'compu', 'langu'])\nplt.show()\nplt.savefig(\"policy tree.png\")\n```\n\n\n```python\npolicy.predict([[0, 0, 1, 5, 2, 0]])\n```\n\n\n\n\n    array([1])\n\n\n\n\n```python\nQ.mean()\n```\n\n\n\n\n    nontr         0.000000\n    job search   -1.039687\n    vocational    2.751877\n    computer      3.152447\n    language      1.664231\n    dtype: float64\n\n\n\n\n```python\nfor i in range(len(X.columns)):\n  print(i, X.columns[i])\n```\n\n    0 age\n    1 female\n    2 employability\n    3 past_income\n    4 gdp_pc\n    5 unemp_rate\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "c3cee802a495f40ad0235ffab74b2bd085daeebb", "size": 124348, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Code/Policy_tree_with_EconML.ipynb", "max_stars_repo_name": "anondissertation/Dissertation", "max_stars_repo_head_hexsha": "96a116f93a05fd8beac3df9b43a4251dc0a330fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/Policy_tree_with_EconML.ipynb", "max_issues_repo_name": "anondissertation/Dissertation", "max_issues_repo_head_hexsha": "96a116f93a05fd8beac3df9b43a4251dc0a330fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Policy_tree_with_EconML.ipynb", "max_forks_repo_name": "anondissertation/Dissertation", "max_forks_repo_head_hexsha": "96a116f93a05fd8beac3df9b43a4251dc0a330fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 245.7470355731, "max_line_length": 105454, "alphanum_fraction": 0.8883456107, "converted": true, "num_tokens": 3451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473339755162, "lm_q2_score": 0.09138211172802313, "lm_q1q2_score": 0.0393077717328619}}
{"text": "```python\n# This cell is mandatory in all Dymos documentation notebooks.\nmissing_packages = []\ntry:\n    import openmdao.api as om\nexcept ImportError:\n    if 'google.colab' in str(get_ipython()):\n        !python -m pip install openmdao[notebooks]\n    else:\n        missing_packages.append('openmdao')\ntry:\n    import dymos as dm\nexcept ImportError:\n    if 'google.colab' in str(get_ipython()):\n        !python -m pip install dymos\n    else:\n        missing_packages.append('dymos')\ntry:\n    import pyoptsparse\nexcept ImportError:\n    if 'google.colab' in str(get_ipython()):\n        !pip install -q condacolab\n        import condacolab\n        condacolab.install_miniconda()\n        !conda install -c conda-forge pyoptsparse\n    else:\n        missing_packages.append('pyoptsparse')\nif missing_packages:\n    raise EnvironmentError('This notebook requires the following packages '\n                           'please install them and restart this notebook\\'s runtime: {\",\".join(missing_packages)}')\n```\n\n(getting_started:collocation:what_is_collocation)=\n# What is collocation?\n\nDymos is focused on direct optimization methods based on an implicit integration technique, collocation.\n\nThe _state_ of a dynamic system defines its configuration at a point in time.\nCommon state variables for dynamic systems are position, velocity, and mass.\nGiven an initial state, a time duration, and ordinary differential equations that define the evolution of the states in time, the state of the system at the end of the time duration can be determined.\nThis is known as the _initial value problem_ (IVP) and there are numerous techniques and software packages that can be used to solve the IVP.\nThe initial value problem is typically the basis for the simulation of systems.\nThis time-marching approach is the basis for _shooting methods_ in optimization.\nWhile Dymos supports shooting methods, its focus is on implicit collocation techniques, for performance reasons.\n\nFirst, a few assumptions about the dynamic system:\n\n1.  Over portions of the trajectory, the state is continuous (there are no instantaneous changes in the states)\n2.  Over portions of the trajectory, the state is continuous in its first derivative w.r.t. time. (there are no instantaneous changes in the state rates)\n\nIf those two conditions are met, then it's reasonable to fit a polynomial to a plot of the state value over time.\nGiven the initial or final value of a state, and values of its rate at some number of points across the trajectory, then a polynomial can be fit whose initial or final value matches, and whose rates match the sampled rates.\nThe value of the state at any point throughout the trajectory can then be inferred by interpolating the collocated polynomial.\n\nSolving this trajectory implicitly basically means _guessing_ values for the states along the trajectory.\nWhile one could use a power series polynomial coefficients ($a t^2 + b t + c$), these coefficients can have vastly different values depending on the shape of the curve, making them difficult to scale numerically.\nInstead, Lagrange interpolating polynomials are typically used, where the actual values to be interpolated at various points are the implicit variables.\nThis makes scaling the problem easier, and gives the implicit variables more intuitive meaning, making it easier to provide an initial guess.\n\n## Example:  Simulating the fall of an object\n\nAs a \"hello, world\" problem for Dymos, consider the vertical fall of an object acting under gravity - like Galileo dropping cannonballs from the Tower of Pisa.\nIgnoring aerodynamics and treating the ball as a point mass in a rectilinear gravity field, the motion is governed by:\n\n\\begin{align}\n    \\ddot{y} = -g\n\\end{align}\n\nThe techniques in Dymos are generally centered around first-order dynamics, so we convert the above equation into the following system of ODEs.\n\n\\begin{align}\n    \\dot{y} &= v_y \\\\\n    \\dot{v_y} &= -g\n\\end{align}\n\nOne common way to propagate this trajectory would be to use an \"explicit time-marching\" approach.\nThat is, we can use Euler's method or a Runge-Kutta approach to propagate the trajectory of the ball, one small slice of time at a time.\nWhen performing trajectory optimization, the trajectory is typically evaluated at least dozens of time.\nIf the ODE for the system is computationally expensive, this time-marching approach can take a very long time.\n\nInstead, we can use an implicit simulation technique to more efficiently model the trajectory.\nFirst, let's assume that the value of the _states_ $y$ and $v_y$ smoothly vary in time (there's no teleportation or instantaneous changes in velocity).\nNow we can fit a polynomial to the plot of each of these states with respect to time.\nIn this case, basic physics tells us that $v_y$ should be linear with time and $y$ should be quadratic with time.\n\nNow for the simulation, lets solve a _boundary value problem_.\nWe know the initial and final height of the ball.\nWe know the initial velocity but not the terminal velocity.\n\n_How long does it take the ball to reach the ground from an initial height of 100 m?_\n\nWe will explain how this problem is solved using the two implicit simulation techniques in Dymos:  high-order Gauss-Lobatto collocation, and the Radau Pseudospectral Method.\n\n## Finding the trajectory using high-order Legendre-Gauss-Lobatto collocation\n\nUsing a 3rd-order polynomial segment to mimic the trajectory, we have two states and thus two polynomials.\nLegendre-Gauss-Lobatto (LGL) collocation uses knowledge of the states and state-rates to form an interpolating polynomial.\nA third-order polynomial requires four pieces of information to define it.\nWe'll take two points along the trajectory, and use those to guess the state values.\nIn Dymos, these points where state values are provided are called the _state discretization nodes_.\nIn LGL collocation, these points are chosen to be the LGL _nodes_ in the dimensionless time of the segment, which we call $\\tau_s$.\n\nOur initial guess for the trajectory might look something like this:\n\n| Variables  | Description       | Value          | Notes                  |\n|------------|-------------------|----------------|------------------------|\n| $y_0$      | initial height    | 100 m          | fixed                  |\n| $y_f$      | final height      | 0 m            | fixed                  |\n| $v_{y0}$   | initial velocity  | 0 m/s          | fixed                  |\n| $v_{yf}$   | final velocity    | -50 m/s        | free                   |\n| $t_0$      | initial time      | 0              | fixed                  |\n| $t_d$      | time duration     | 5              | free                   |\n| $g$        | grav. acceleration| 9.80665 m/s^2  | assumed                |\n\nTo form 3rd-order polynomials for the states we need four pieces of information, but so far we only have the two endpoint values.\nWe'll use the state rates at the state discretization nodes to provide the other two values needed for interpolation.\nTo obtain these, we evaluate our ODE at the state discretization nodes.\n\n\\begin{align}\n    \\dot{y}_0 &= 0 \\\\\n    \\dot{y}_f &= -50 \\\\\n    \\dot{v}_{y0} &= -9.80665 \\\\\n    \\dot{v}_{yf} &= -9.80665\n\\end{align}\n\n\n\nBut how do we know that our assumed trajectory is correct?\nIn LGL collocation, we check the interpolated slope of the polynomial at a 3rd point (the collocation node) and compare it to an evaluation of the ODE at the same point.\nIf the difference between the two is sufficiently close to zero, we can be somewhat confident that our polynomial is a reasonable match for the true time-history.\nWe call this difference in slope the collocation _defect_.\n\nHaving computed the ODE at the state discretization nodes, we can form interpolants for the values and the slope of the states at the collocation nodes.\nDymos uses Lagrange interpolants, such that the inputs to the system are the values of the states and controls, rather than less intuitive coefficients.\nIn this case, the state values at our single collocation node are:\n\n\\begin{align}\n    y_m &= 50 \\\\\n    v_{ym} &= -25\n\\end{align}\n\n\n\nThe polynomial slopes at the collocation node are:\n\n\\begin{align}\n    y'_m &= 50 \\\\\n    v'_{ym} &= -25\n\\end{align}\n\nNow, having the state and time values at the collocation nodes, we can again evaluate the ODE.\n\n\\begin{align}\n    \\dot{y}_m &= -17 \\\\\n    \\dot{v}_{ym} &= -9.80665\n\\end{align}\n\n\n\nIn this case the known variables are the value of the polynomial at the left endpoint ($y_0$), and the value of the independent variable at the left and right endpoints of the interval to be fitted ($x_0$, $x_1$)\nIn this case, there are no _control_ inputs to the ODE.\nHowever, if there were, the value of the control would also need to be provided at the collocation node.\nThus, in high-order Gauss-Lobatto collocation, the _control input nodes_ include both the state discretization nodes and the collocation nodes.\n\nThe free variables in the problem ($t_{duration}$ and $vy_f$) can be iterated until the difference between the interpolated state rates and the ODE-computed state rates is zero.\n\n\n\n## Finding the trajectory using the Radau Pseudospectral Method\n\nAgain, there are two states, and two corresponding 3rd-order polynomials representing the time history.\nAs with the Gauss-Lobatto method, a third-order polynomial requires four pieces of information to define it.\nIn the case of the Radau Pseudospectral Method, we'll use four state values, guessed at the Radau nodes in dimensionless time in addition to the right endpoint of the interval (the _state discretization nodes_).\n\nA linear interpolation of the endpoint values will serve as the initial guess in this instance.\nThe three Radau nodes that don't include the right endpoint will serve as the _collocation nodes_ in this case.\nSince these are a subset of the state discretization nodes, no interpolation of values is necessary...all of the state values have been provided.\n\n\n\nThe derivative of the interpolating polynomial is computed using a differentiation matrix and the state discretization values.\n\n\n\nNow the ODE can be evaluated to calculate the state rates, and the results compared to the interpolated slopes.\n\n\n\nAgain, the free variables are iterated until the defects are zero and any boundary conditions are met.\n\n\n\n## Multiple Segments\n\nThe simple examples above use one single 3rd-order polynomial to represent the time history of the states.\nWith more complex states, a single 3rd-order polynomial would not be capable of replicating the time history.\nIn practice, we can use more polynomial segments _and_ higher-order polynomials to better match the dynamics.\n\nIn the case of adding more segments, one can choose whether the segment boundaries are shared by the segments, or independent.\nIf they are shared, fewer design variables are necessary, but it may be more difficult for the optimizer to search for a solution.\nThis is called \"compressed\" transcription.\nOn the other hand, we can doubly-specify state values at segment boundaries as design variables, thus increasing the size of the problem.\nIn this \"uncompressed\" formulation, continuity constraints are imposed at the segment bounds to ensure that there are no discontinuities in the state time-history at segment bounds.\n\n## LGL vs LGR Collocation\n\nGauss-Lobatto collocation results in smaller NLP sizes for the optimizer since fewer states are treated as design variables.\nThe cost of this reduction is the interpolation step in the Gauss-Lobatto algorithm.\nWhile the Radau Pseudospectral method requires one evaluation of the ODE to assess the defects, the Gauss-Lobatto method requires two.\nIn addition, the interpolation step used by the Gauss-Lobatto method can result in interpolated state values falling well outside the user's expected range if the initial guess is not sufficiently accurate.\nThis can cause convergence issues if there are nonlinear solvers within the ODE that rely on a reasonable guess to achieve convergence.\n\n## Satisfying Defects with a Nonlinear Solver\n\nTypically, collocation problems are solved by posing the defects as constraints to an optimizer.\nIn Dymos, another option exists.\nOne can use an embedded Newton-solver satisfy the defect and continuity constraints.\nThis mode, which we call `solve_segments`, gives the Newton-Solver control over all but the first or final state value in the phase.\nThe optimizer only controls the initial or final value, and the solver is responsible for converging the trajectory time history.\nThis results in a shooting method, but one that is mathematically consistent with the collocation methods.\nThis `solve_segments` capability is useful if a user simply wants to propagate a dynamic system and not optimize it.\n\n\n```python\n\n```\n", "meta": {"hexsha": "72e2d13a389fb34f8db7260d3023c730404395a4", "size": 16095, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/dymos_book/getting_started/collocation.ipynb", "max_stars_repo_name": "yonghoonlee/dymos", "max_stars_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/dymos_book/getting_started/collocation.ipynb", "max_issues_repo_name": "yonghoonlee/dymos", "max_issues_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-05-24T15:14:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-28T21:12:55.000Z", "max_forks_repo_path": "docs/dymos_book/getting_started/collocation.ipynb", "max_forks_repo_name": "yonghoonlee/dymos", "max_forks_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.4821428571, "max_line_length": 232, "alphanum_fraction": 0.6621932277, "converted": true, "num_tokens": 2810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814501625211, "lm_q2_score": 0.09009299701580503, "lm_q1q2_score": 0.03909868949440675}}
{"text": "```\n!pip install cirq\n```\n\n    Collecting cirq\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/53/29/a66c4c28306dae359745e37c4c10120e477da44cb050d06d8ceb1117a22a/cirq-0.7.0-py3-none-any.whl (1.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.2MB 2.8MB/s \n    \u001b[?25hRequirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from cirq) (0.7)\n    Collecting protobuf==3.8.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/d2/fb/29de8d08967f0cce1bb10b39846d836b0f3bf6776ddc36aed7c73498ca7e/protobuf-3.8.0-cp36-cp36m-manylinux1_x86_64.whl (1.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.2MB 47.3MB/s \n    \u001b[?25hRequirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from cirq) (1.4.1)\n    Requirement already satisfied: numpy~=1.16 in /usr/local/lib/python3.6/dist-packages (from cirq) (1.17.5)\n    Collecting sympy==1.4\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/21/21/f4105795ca7f35c541d82c5b06be684dd2f5cb4f508fb487cd7aea4de776/sympy-1.4-py2.py3-none-any.whl (5.3MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5.3MB 35.4MB/s \n    \u001b[?25hCollecting networkx==2.3\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/85/08/f20aef11d4c343b557e5de6b9548761811eb16e438cee3d32b1c66c8566b/networkx-2.3.zip (1.7MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.8MB 29.4MB/s \n    \u001b[?25hRequirement already satisfied: typing-extensions in /usr/local/lib/python3.6/dist-packages (from cirq) (3.6.6)\n    Requirement already satisfied: sortedcontainers~=2.0 in /usr/local/lib/python3.6/dist-packages (from cirq) (2.1.0)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from cirq) (0.25.3)\n    Requirement already satisfied: requests~=2.18 in /usr/local/lib/python3.6/dist-packages (from cirq) (2.21.0)\n    Requirement already satisfied: matplotlib~=3.0 in /usr/local/lib/python3.6/dist-packages (from cirq) (3.1.2)\n    Requirement already satisfied: google-api-python-client~=1.6 in /usr/local/lib/python3.6/dist-packages (from cirq) (1.7.11)\n    Requirement already satisfied: six>=1.9 in /usr/local/lib/python3.6/dist-packages (from protobuf==3.8.0->cirq) (1.12.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from protobuf==3.8.0->cirq) (45.1.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy==1.4->cirq) (1.1.0)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx==2.3->cirq) (4.4.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas->cirq) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas->cirq) (2.6.1)\n    Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (1.24.3)\n    Requirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (2.8)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (2019.11.28)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (3.0.4)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq) (1.1.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq) (2.4.6)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq) (0.10.0)\n    Requirement already satisfied: google-auth>=1.4.1 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client~=1.6->cirq) (1.4.2)\n    Requirement already satisfied: google-auth-httplib2>=0.0.3 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client~=1.6->cirq) (0.0.3)\n    Requirement already satisfied: uritemplate<4dev,>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client~=1.6->cirq) (3.0.1)\n    Requirement already satisfied: httplib2<1dev,>=0.9.2 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client~=1.6->cirq) (0.11.3)\n    Requirement already satisfied: rsa>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from google-auth>=1.4.1->google-api-python-client~=1.6->cirq) (4.0)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.6/dist-packages (from google-auth>=1.4.1->google-api-python-client~=1.6->cirq) (0.2.8)\n    Requirement already satisfied: cachetools>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth>=1.4.1->google-api-python-client~=1.6->cirq) (4.0.0)\n    Requirement already satisfied: pyasn1>=0.1.3 in /usr/local/lib/python3.6/dist-packages (from rsa>=3.1.4->google-auth>=1.4.1->google-api-python-client~=1.6->cirq) (0.4.8)\n    Building wheels for collected packages: networkx\n      Building wheel for networkx (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for networkx: filename=networkx-2.3-py2.py3-none-any.whl size=1556408 sha256=3f0f6bb9e78ac09bf8f86ac6f7e20b27b4042418c81c816c176fbdad8884f444\n      Stored in directory: /root/.cache/pip/wheels/de/63/64/3699be2a9d0ccdb37c7f16329acf3863fd76eda58c39c737af\n    Successfully built networkx\n    \u001b[31mERROR: albumentations 0.1.12 has requirement imgaug<0.2.7,>=0.2.5, but you'll have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Installing collected packages: protobuf, sympy, networkx, cirq\n      Found existing installation: protobuf 3.10.0\n        Uninstalling protobuf-3.10.0:\n          Successfully uninstalled protobuf-3.10.0\n      Found existing installation: sympy 1.1.1\n        Uninstalling sympy-1.1.1:\n          Successfully uninstalled sympy-1.1.1\n      Found existing installation: networkx 2.4\n        Uninstalling networkx-2.4:\n          Successfully uninstalled networkx-2.4\n    Successfully installed cirq-0.7.0 networkx-2.3 protobuf-3.8.0 sympy-1.4\n\n\n\n\n\n```\nimport cirq\nimport random\n```\n\n\n```\n# Number of input qubits\nqubitNo=8\ninputQubit=[cirq.GridQubit(i,0) for i in range(qubitNo)]\n\n# Output qubit\noutputQubit=cirq.GridQubit(qubitNo,0)\n\n# String S such that f(x)=x.s \nfactorString=[random.randint(0,1) for _ in range(qubitNo)]\n\n```\n\n\n```\n# define Oracle U_f\ndef makeOracle(inputQubit, outputQubit, factorString):\n  for qubit, bit in zip(inputQubit,factorString):\n    if bit:\n      yield cirq.CNOT(qubit, outputQubit)\n```\n\n\n```\n# define the whole BV algorithm circuit\ndef makeBVcircuit(inputQubit, outputQubit, Oracle):\n  BV=cirq.Circuit()\n  BV.append([\n  cirq.X(outputQubit),\n  cirq.H(outputQubit),\n  cirq.H.on_each(*inputQubit)             \n  ])\n\n  BV.append(Oracle)\n\n  BV.append([\n  cirq.H.on_each(*inputQubit),\n  cirq.measure(*inputQubit, key='result')          \n  ])\n\n  return BV  \n```\n\n\n```\n#make one example of Oracle and BVcircuit\nOracle=makeOracle(inputQubit, outputQubit, factorString)\n\nBVcircuit=makeBVcircuit(inputQubit, outputQubit, Oracle)\nprint('BVCircuit')\nprint(BVcircuit)\n\n```\n\n    BVCircuit\n    (0, 0): \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                                   \u2502\n    (1, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502           \u2502\n    (2, 0): \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502           \u2502\n    (3, 0): \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502           \u2502\n    (4, 0): \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502           \u2502\n    (5, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502       \u2502\n    (6, 0): \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502       \u2502\n    (7, 0): \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502\n    (8, 0): \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n\n```\n#measurement \nsimulator=cirq.Simulator()\nresult=simulator.run(BVcircuit)\n\n#comparison measurement result with factorString\nprint(result)\nprint('factorString=',factorString)\n```\n\n    result=0, 1, 0, 0, 0, 1, 0, 0\n    factorString= [0, 1, 0, 0, 0, 1, 0, 0]\n\n\n\n```\n\n```\n", "meta": {"hexsha": "7274d27a882621d3a7e1fa69038a8302049a13ef", "size": 13060, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Bernstein-Vazirani Algorithm/BV_Algorithm_Code.ipynb", "max_stars_repo_name": "sunlaito/QuantumProgramming", "max_stars_repo_head_hexsha": "d355e11293886ba5df256bf152c13a27bd24b169", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Bernstein-Vazirani Algorithm/BV_Algorithm_Code.ipynb", "max_issues_repo_name": "sunlaito/QuantumProgramming", "max_issues_repo_head_hexsha": "d355e11293886ba5df256bf152c13a27bd24b169", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Bernstein-Vazirani Algorithm/BV_Algorithm_Code.ipynb", "max_forks_repo_name": "sunlaito/QuantumProgramming", "max_forks_repo_head_hexsha": "d355e11293886ba5df256bf152c13a27bd24b169", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.5052264808, "max_line_length": 204, "alphanum_fraction": 0.5174578867, "converted": true, "num_tokens": 2850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834914771175, "lm_q2_score": 0.08269734041427963, "lm_q1q2_score": 0.03908966760289343}}
{"text": "# Select suitable MDL test: KVLCC2 **NO** speed\n\n# Purpose\nFind suitable roll decay tests from MDL, to reproduce in Motions later on.\n\n# Methodology\nLook at the results from the KLVCC2 ship.\n* Load model tests from MDL\n* Determine damping\n\n# WIP - improvements\n(WORK IN PROGRESS)\nUse this section only if the notebook is not final.\n\nNotable TODOs:\n* todo 1\n* todo 2\n* todo 3\n\n## Results\nDescribe and comment the most important results.\n\n# Suggested next steps\nState suggested next steps, based on results obtained in this notebook.\n\n# Setup\n\n\n```python\n# %load imports.py\n\"\"\"\nThese is the standard setup for the notebooks.\n\"\"\"\n\n%matplotlib inline\n%load_ext autoreload\n%autoreload 2\n\nfrom jupyterthemes import jtplot\njtplot.style(theme='onedork', context='notebook', ticks=True, grid=False)\n\nimport pandas as pd\npd.options.display.max_rows = 999\npd.options.display.max_columns = 999\npd.set_option(\"display.max_columns\", None)\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom collections import OrderedDict\n#plt.style.use('paper')\n\n#import data\nimport copy\nfrom mdldb.run import Run\n\nfrom sklearn.pipeline import Pipeline\nfrom rolldecayestimators.transformers import CutTransformer, LowpassFilterDerivatorTransformer, ScaleFactorTransformer, OffsetTransformer\nfrom rolldecayestimators.direct_estimator_cubic import EstimatorQuadraticB, EstimatorCubic\nfrom rolldecayestimators.ikeda_estimator import IkedaQuadraticEstimator\nimport rolldecayestimators.equations as equations\nimport rolldecayestimators.lambdas as lambdas\nfrom rolldecayestimators.substitute_dynamic_symbols import lambdify\nimport rolldecayestimators.symbols as symbols\nimport sympy as sp\n\nfrom sklearn.metrics import r2_score\nfrom src.data import database\nfrom mdldb import tables\n\n```\n\n    Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 461 ('figure.figsize   : 5, 3   ## figure size in inches')\n    Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 462 ('figure.dpi       : 100        ## figure dots per inch')\n\n\n\n```python\nfrom mdldb.hdf5_file import Hdf5File\nfrom rolldecayestimators.direct_estimator_cubic import EstimatorCubic,EstimatorQuadraticB\nfrom sklearn.base import clone\nfrom copy import deepcopy\nimport joblib\n```\n\n\n```python\ndb = database.get_db()\n```\n\n\n```python\nsql = \"\"\"\nSELECT * from run\nWHERE model_number='M5057-01-A' and test_type='roll decay' and project_number=40178362;\n\"\"\"\ndf_rolldecays = pd.read_sql(sql=sql, con=db.engine, index_col='id')\n\ndf_rolldecays['ship_speed'].fillna(0, inplace=True)\n\n```\n\n\n```python\ndf_rolldecays\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>project_number</th>\n      <th>series_number</th>\n      <th>run_number</th>\n      <th>test_number</th>\n      <th>model_number</th>\n      <th>ship_name</th>\n      <th>loading_condition_id</th>\n      <th>ascii_name</th>\n      <th>ship_speed</th>\n      <th>comment</th>\n      <th>file_path_ascii</th>\n      <th>file_path_ascii_temp</th>\n      <th>file_path_log</th>\n      <th>file_path_hdf5</th>\n      <th>date</th>\n      <th>test_type</th>\n      <th>facility</th>\n      <th>angle1</th>\n      <th>angle2</th>\n      <th>K\u00f6rfallstyp</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>21337</th>\n      <td>40178362</td>\n      <td>1</td>\n      <td>94</td>\n      <td>1</td>\n      <td>M5057-01-A</td>\n      <td>M5057-01-A</td>\n      <td>166</td>\n      <td>94.0</td>\n      <td>0.0</td>\n      <td>Roll decay, 0 kn</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...</td>\n      <td>\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...</td>\n      <td>2018-04-03</td>\n      <td>roll decay</td>\n      <td>MDL</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n    </tr>\n    <tr>\n      <th>21338</th>\n      <td>40178362</td>\n      <td>1</td>\n      <td>95</td>\n      <td>1</td>\n      <td>M5057-01-A</td>\n      <td>M5057-01-A</td>\n      <td>166</td>\n      <td>95.0</td>\n      <td>0.0</td>\n      <td>Roll decay, 0 kn</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...</td>\n      <td>\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...</td>\n      <td>2018-04-03</td>\n      <td>roll decay</td>\n      <td>MDL</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n    </tr>\n    <tr>\n      <th>21339</th>\n      <td>40178362</td>\n      <td>1</td>\n      <td>96</td>\n      <td>1</td>\n      <td>M5057-01-A</td>\n      <td>M5057-01-A</td>\n      <td>166</td>\n      <td>96.0</td>\n      <td>0.0</td>\n      <td>Roll decay, 0 kn</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...</td>\n      <td>\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...</td>\n      <td>2018-11-28</td>\n      <td>roll decay</td>\n      <td>MDL</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n    </tr>\n    <tr>\n      <th>21340</th>\n      <td>40178362</td>\n      <td>1</td>\n      <td>97</td>\n      <td>1</td>\n      <td>M5057-01-A</td>\n      <td>M5057-01-A</td>\n      <td>166</td>\n      <td>97.0</td>\n      <td>15.5</td>\n      <td>Roll decay, 15.5 kn</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...</td>\n      <td>\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...</td>\n      <td>2018-04-04</td>\n      <td>roll decay</td>\n      <td>MDL</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf_rolldecays[['date','ship_speed']]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>date</th>\n      <th>ship_speed</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>21337</th>\n      <td>2018-04-03</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>21338</th>\n      <td>2018-04-03</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>21339</th>\n      <td>2018-11-28</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>21340</th>\n      <td>2018-04-04</td>\n      <td>15.5</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf_rolldecays=df_rolldecays.loc[[21337,21338]].copy()\n```\n\n<a id='rolldecay'></a>\n\n\n```python\nfig,axes=plt.subplots(nrows=len(df_rolldecays))\n\nfor (id, row),ax in zip(df_rolldecays.iterrows(),axes):\n\n    run = db.session.query(Run).get(int(id))\n    run = database.load_run(run, save_as_example=False, prefer_hdf5=True)\n    \n    run.df.plot(y='phi', ax=ax)\n    ax.set_ylabel(f\"roll [{run.units['phi']}]\")\n    ax.grid(True)\n    ax.set_ylim([-0.2,0.2])\n    \nplt.tight_layout()\n```\n\n\n```python\nfig,axes=plt.subplots(ncols=len(df_rolldecays))\n\nfor (id, row),ax in zip(df_rolldecays.iterrows(),axes):\n\n    run = db.session.query(Run).get(int(id))\n    run = database.load_run(run, save_as_example=False, prefer_hdf5=True)\n    \n    run.track_plot(ax)\n    \nplt.tight_layout()\n```\n\n## Analyze the damping\n\n\n```python\n#run = db.session.query(Run).get(21338)\n#run = db.session.query(Run).get(21339)\nrun = db.session.query(Run).get(21337)\n\n\n\n#run = db.session.query(Run).get(21340)\n\n\t\nrun = database.load_run(run, save_as_example=False, prefer_hdf5=True)\n```\n\n    c:\\dev\\evaluation\\signal_lab\\mdl_to_evaluation.py:106: UserWarning: Pandas doesn't allow columns to be created via a new attribute name - see https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access\n      df_.units = units\n\n\n\n```python\nlowpass_filter = LowpassFilterDerivatorTransformer(cutoff=1, minimum_score=0.999)\ncutter = CutTransformer(phi_max=np.deg2rad(15), phi_min=np.deg2rad(3.5), phi1d_start_tolerance=0.015)\noffset_transformer = OffsetTransformer()\n```\n\n\n```python\nestimator_cubic = EstimatorCubic(fit_method='derivation')\nestimator_quadratic_b = EstimatorQuadraticB(fit_method='derivation', maxfev=1000)\n```\n\n\n```python\nsteps = [\n    ('filter',lowpass_filter),\n    ('cutter', cutter), \n#    ('offset_transformer',offset_transformer),\n    ('estimator', estimator_cubic)\n]\n\npipline_cubic = Pipeline(steps=steps)\n```\n\n\n```python\nsteps = [\n    ('filter',lowpass_filter),\n    ('cutter', cutter), \n#    ('offset_transformer',offset_transformer),\n    ('estimator', estimator_quadratic_b)\n]\n\npipline_quadratic_b = Pipeline(steps=steps)\n```\n\n\n```python\nmodels_cubic = OrderedDict()\nscores = pd.DataFrame()\n\nfor (id, row),ax in zip(df_rolldecays.iterrows(),axes):\n\n    run = db.session.query(Run).get(int(id))\n    run = database.load_run(run, save_as_example=False, prefer_hdf5=True)\n    \n    pipline_cubic.fit(X=run.df[['phi']])\n    scores.loc['models_cubic',id] = pipline_cubic.score(X=run.df[['phi']])\n    \n    models_cubic[id]=deepcopy(pipline_cubic)\n```\n\n    c:\\dev\\evaluation\\signal_lab\\mdl_to_evaluation.py:106: UserWarning: Pandas doesn't allow columns to be created via a new attribute name - see https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access\n      df_.units = units\n\n\n\n```python\nfig,ax=plt.subplots()\n\nfor id, model in models_cubic.items():\n    \n    estimator = model['estimator']\n    estimator.plot_damping(ax=ax)\n    \nfig,ax=plt.subplots()\nfor id, model in models_cubic.items():\n    \n    estimator = model['estimator']\n    estimator.plot_omega0(ax=ax, include_model_test=True)\n```\n\n## Quadratic\n\n\n```python\nmodels_quadratic = OrderedDict()\n\nfor (id, row),ax in zip(df_rolldecays.iterrows(),axes):\n\n    run = db.session.query(Run).get(int(id))\n    run = database.load_run(run, save_as_example=False, prefer_hdf5=True)\n    \n    pipline_quadratic_b.fit(X=run.df[['phi']])\n    scores.loc['pipline_quadratic_b',id] = pipline_quadratic_b.score(X=run.df[['phi']])\n    \n    models_quadratic[id]=deepcopy(pipline_quadratic_b)\n```\n\n    c:\\dev\\evaluation\\signal_lab\\mdl_to_evaluation.py:106: UserWarning: Pandas doesn't allow columns to be created via a new attribute name - see https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access\n      df_.units = units\n    c:\\dev\\evaluation\\signal_lab\\mdl_to_evaluation.py:106: UserWarning: Pandas doesn't allow columns to be created via a new attribute name - see https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access\n      df_.units = units\n\n\n\n```python\nfig,ax=plt.subplots()\n\ncolors = ['r','g','b']\nmarkers = ['o','*','+']\n\nfor id, model in models_quadratic.items():\n    \n    estimator = model['estimator']\n    estimator.plot_damping(ax=ax)\n    \nfig,ax=plt.subplots()\nfor id, model in models_quadratic.items():\n    \n    estimator = model['estimator']\n    estimator.plot_omega0(ax=ax, include_model_test=True)\n```\n\n## Integration\n\n\n### Quadratic\n\n\n```python\nestimator_quadratic_b_int = EstimatorQuadraticB(fit_method='integration', maxfev=100000, p0=estimator_quadratic_b.parameters)\n\nsteps = [\n    ('filter',lowpass_filter),\n    ('cutter', cutter), \n#    ('offset_transformer',offset_transformer),\n    ('estimator', estimator_quadratic_b_int)\n]\n\npipline_quadratic_b_int = Pipeline(steps=steps)\n```\n\n\n```python\nmodels_quadratic_b_int = OrderedDict()\n\nfor (id, row),ax in zip(df_rolldecays.iterrows(),axes):\n\n    run = db.session.query(Run).get(int(id))\n    run = database.load_run(run, save_as_example=False, prefer_hdf5=True)\n    \n    pipline_quadratic_b_int.fit(X=run.df[['phi']])\n    scores.loc['pipline_quadratic_b_int',id] = pipline_quadratic_b_int.score(X=run.df[['phi']])\n    \n    models_quadratic_b_int[id]=deepcopy(pipline_quadratic_b_int)\n```\n\n    c:\\dev\\evaluation\\signal_lab\\mdl_to_evaluation.py:106: UserWarning: Pandas doesn't allow columns to be created via a new attribute name - see https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access\n      df_.units = units\n    c:\\dev\\evaluation\\signal_lab\\mdl_to_evaluation.py:106: UserWarning: Pandas doesn't allow columns to be created via a new attribute name - see https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access\n      df_.units = units\n\n\n\n```python\nfig,ax=plt.subplots()\n\ncolors = ['r','g','b']\nmarkers = ['o','*','+']\n\nfor id, model in models_quadratic_b_int.items():\n    \n    estimator = model['estimator']\n    estimator.plot_damping(ax=ax)\n    \nfig,ax=plt.subplots()\nfor id, model in models_quadratic.items():\n    \n    estimator = model['estimator']\n    estimator.plot_omega0(ax=ax, include_model_test=True)\n```\n\n### Cubic\n\n\n```python\nestimator_cubic_int = EstimatorCubic(fit_method='integration', maxfev=100000, p0=estimator_cubic.parameters)\n\nsteps = [\n    ('filter',lowpass_filter),\n    ('cutter', cutter), \n#    ('offset_transformer',offset_transformer),\n    ('estimator', estimator_cubic_int)\n]\n\npipline_cubic_int = Pipeline(steps=steps)\n```\n\n\n```python\nmodels_cubic_int = OrderedDict()\n\nfor (id, row),ax in zip(df_rolldecays.iterrows(),axes):\n\n    run = db.session.query(Run).get(int(id))\n    run = database.load_run(run, save_as_example=False, prefer_hdf5=True)\n    \n    pipline_cubic_int.fit(X=run.df[['phi']])\n    scores.loc['models_cubic_int',id] = pipline_cubic_int.score(X=run.df[['phi']])\n    \n    models_cubic_int[id]=deepcopy(pipline_cubic_int)\n```\n\n    c:\\dev\\evaluation\\signal_lab\\mdl_to_evaluation.py:106: UserWarning: Pandas doesn't allow columns to be created via a new attribute name - see https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access\n      df_.units = units\n    c:\\dev\\evaluation\\signal_lab\\mdl_to_evaluation.py:106: UserWarning: Pandas doesn't allow columns to be created via a new attribute name - see https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access\n      df_.units = units\n\n\n<a id='cubic_model'></a>\n\n\n```python\nfig,ax=plt.subplots()\n\ncolors = ['r','g','b']\nmarkers = ['o','*','+']\n\nfor id, model in models_cubic_int.items():\n    \n    estimator = model['estimator']\n    estimator.plot_damping(ax=ax)\n    \nfig,ax=plt.subplots()\nfor id, model in models_cubic_int.items():\n    \n    estimator = model['estimator']\n    estimator.plot_omega0(ax=ax, include_model_test=True)\n```\n\n\n```python\nscores\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>21337</th>\n      <th>21338</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>models_cubic</th>\n      <td>0.999130</td>\n      <td>0.998342</td>\n    </tr>\n    <tr>\n      <th>pipline_quadratic_b</th>\n      <td>0.996430</td>\n      <td>0.992402</td>\n    </tr>\n    <tr>\n      <th>pipline_quadratic_b_int</th>\n      <td>0.996755</td>\n      <td>0.993559</td>\n    </tr>\n    <tr>\n      <th>models_cubic_int</th>\n      <td>0.999980</td>\n      <td>0.999968</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nmodel = models_cubic_int[21338]\n```\n\n\n```python\njoblib.dump(model, '../models/KVLCC2_0_speed.pkl')\n```\n\n\n\n\n    ['../models/KVLCC2_0_speed.pkl']\n\n\n\n\n```python\nfor name, model in models_cubic_int.items():\n    \n    joblib.dump(model, '../models/KVLCC2_%i.pkl' % name)\n    \n```\n\n\n```python\nscale_factor = run.model.scale_factor\n\nmeta_data = {\n    'Volume':run.loading_condition.Volume/(scale_factor**3),\n    'GM':run.loading_condition.gm/scale_factor,\n    'rho':1000,\n    'g':9.81,\n}\n\nestimator = model['estimator']\nresult_for_database = estimator.result_for_database(meta_data=meta_data)\nresult_for_database\n```\n\n\n```python\nresult_for_database['omega0']\n```\n\n\n```python\nresult_for_database['omega0']/np.sqrt(run.model.scale_factor)\n```\n\n\n```python\nphi_a = np.deg2rad(10)\n\nB_e = lambdas.B_e_lambda_cubic(B_1=result_for_database['B_1'],\n                         B_2=result_for_database['B_2'],\n                         B_3=result_for_database['B_3'],\n                         omega0=result_for_database['omega0'],\n                         phi_a = phi_a)\n```\n\n\n```python\ng=9.81\nrho=1000\nVolume = run.loading_condition.Volume/(scale_factor**3)\nbeam = run.ship.beam/scale_factor\nlambdas.B_hat_lambda(B=B_e, Disp=Volume, beam=beam,g=g, rho=rho)\n```\n\n## $A_{44}$\n\n\n```python\nresult_for_database['A_44']\n```\n\n\n```python\nmass = run.loading_condition.Volume*rho\nmass*run.loading_condition.KXX**2\n```\n\n\n```python\nnp.sqrt(result_for_database['A_44']/mass)\n```\n\n\n```python\nresult_for_database['A_44']/(mass*run.loading_condition.KXX**2)\n```\n\n\n```python\nrun.loading_condition.Volume/(run.ship.lpp*run.ship.beam*run.loading_condition.TA)\n```\n\n\n```python\nrun.ship.lpp\n```\n\n\n```python\nrun.ship.beam\n```\n\n\n```python\nrun.loading_condition.TA\n```\n\n\n```python\nequations.A44\n```\n\n\n```python\nomega0 = result_for_database['omega0']\nscale_factor = run.model.scale_factor\nGM = run.loading_condition.gm/scale_factor\nm = run.loading_condition.Volume/(scale_factor**3)*rho\n\nA_44 = lambdas.A44_lambda(GM=GM, g=g, m=m, omega0=omega0)\nA_44\n```\n\n\n```python\nkxx = run.loading_condition.KXX/scale_factor #???\nI_44 = m*kxx**2\nI_44\n```\n\n\n```python\nA_44/I_44\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "8b9ba41cd26231e101fc960c41d3f3b18ecd0e7f", "size": 585720, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/01.2_select_suitable_MDL_test_KLVCC2.ipynb", "max_stars_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_stars_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/01.2_select_suitable_MDL_test_KLVCC2.ipynb", "max_issues_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_issues_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/01.2_select_suitable_MDL_test_KLVCC2.ipynb", "max_forks_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_forks_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-05T15:38:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T15:38:54.000Z", "avg_line_length": 429.7285399853, "max_line_length": 86792, "alphanum_fraction": 0.9319896879, "converted": true, "num_tokens": 5420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510527095787247, "lm_q2_score": 0.11279541821247763, "lm_q1q2_score": 0.03892629336502364}}
{"text": "# Real Time Diagrammatics in QmeQ - Tutorial\n\nThis notebook contains a few examples highlighting the capabilities and usage of the RTD approach in QmeQ. The theory behind the approach is described [elsewhere](https://github.com/M-Josefsson/RTD-docs/blob/master/RTD.pdf).\n\n## Installation\n\nThis notebook assumes that the latest version of QmeQ is installed. If not, it can be installed using\n\n`\npip install qmeq\n`\n\nor \n\n`pip install --upgrade qmeq`\n\nif an older version of qmeq is already installed.\n\n## The RTD approach\n\nThe RTD approach provides the functionality to solve the transport problem for diagonal density matrices using the Real Time Diagrammatic technique. It is a second order  approach ($\\propto\\Gamma^2$, fourth order in $t$) and it can be seen as the second order extension of the Pauli approach. As such, it cannot properly handle degenerate (or almost degenerate $\\Delta E\\lesssim \\Gamma$) states coupled to the same lead since such conditions tend to lead to off-diagonal terms in the density matrix. However, recall that different spins couple to different leads in QmeQ, so spin-degeneracy is not a problem. \n\nBeing a second order approach means it takes into account processes such as co-tunneling, pair tunneling and energy re-normalization. It is however still perturbative in $\\Gamma$ (formally in $t$) and is valid when $\\hbar\\Gamma\\ll k_B T$. Choosing a too large $\\Gamma$ can leads to unphysical artifacts, but one can generally make sure that a feature is not an artifact by checking that its magnitude scales with at most $\\Gamma^2$, instead of $\\Gamma^3$.\n\n\nThe approach is called RTD (i.e. `kerntype='pyRTD'` or `kerntype='RTD'`). It can be used in the same way as the first-order approaches, i.e. no additional parameters need to be specified. However, only `itype=1` is supported in the RTD approach, and the provided bandwidth should therefore always be a lot larger than all other energies in the problem. A larger bandwidth increases the accuracy of the results.\n\nFurthermore, the RTD approach differs from the first order approaches in a few more ways. It does not support a matrix free method for solving the master equations, `mfreeq=True`, or the usage of symmetries `symmetry=True`. In addition, the only supported indexing type is `indexing=charge`.\n\nWe set $\\hbar=e=k_b=1$ throughout this notebook.\n\n## Auxiliary functions and imports\n\nBefore introducing the examples we'll define some functions used for calculating currents and for plotting.\n\n\n```python\ndef current(system, V, Vg, T, dT, leads=[0]):\n    \"\"\"Calculates current for single, and double level systems. The variable\n    leads defines which leads the current is evaluated in.\"\"\"\n    if system.nleads==2:\n        system.change( mulst={0:V/2, 1:-V/2} )\n        system.change( tlst={0:T+dT, 1:T} )      \n    elif system.nleads==4:\n        system.change( mulst={0:V/2, 1:-V/2, 2:V/2, 3:-V/2} )\n        system.change( tlst={0:T+dT, 1:T, 2:T+dT, 3:T} )\n    else:\n        raise ValueError('Current only defined for 2 or 4 leads.')\n        \n    if system.nsingle == 1:\n        system.change( hsingle={(0,0):-vg} )\n    elif system.nsingle == 2:\n        system.change( hsingle={(0,0):-vg, (1,1):-vg} )\n    else:\n        raise ValueError('Current only defined for systems with nsingle = 1 or 2 .')\n        \n    system.solve()\n    I, Q = 0, 0\n    for l in leads:\n        I += system.current[l]\n        Q += system.heat_current[l]\n    return I,Q\n\ndef generate_plot(data_x, data_y, label, color, ylabel, xlabel='Vg'):\n    \"\"\"Plots data_x[i] vs data_y[i]. Sets color and labels based on\n    the input parameters.\"\"\"\n    \n    xlabels = {'Vg' : r'$V_g\\ [\\hbar\\Gamma/e]$', 'Vg_U' : r'$V_g\\ [U/e]$'}\n    ylabels = {'I' : r'$I\\ [e\\Gamma]$', 'Q' : r'$Q\\ [\\hbar\\Gamma^2]$', \n               'Vth': r'$V_{th}\\ [\\hbar\\Gamma/e]$', 'P': r'$P\\ [\\hbar\\Gamma^2]$',\n              'n':r'$\\eta\\ [\\eta_C]$', 'absI':r'$|I|\\ [e\\Gamma]$'}\n    \n    for i in range(len(data_y)):\n        p1 = plt.plot(data_x, data_y[i], color[i], label=label[i])\n    plt.xlabel(xlabels[xlabel], size=14)\n    plt.ylabel(ylabels[ylabel], size=14)\n    plt.legend()\n```\n\n\n```python\n#Imports\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport scipy.optimize as optimize\nimport qmeq\n```\n\n## Minimal example: single level\n\nAs a first example let's look at a single level (no spin) connected to two leads. The Hamiltonian for this case reads:\n\n\\begin{equation}\n    H = H_R + H_T + H_{QD} \\\\\n    H_R = \\sum_{k,r=l,r}\\omega_{k, r}c^\\dagger_{k,r}c_{k, r}\\\\\n    H_T = \\sum_{k,r} t_{k, r}d^\\dagger c_{k, r} + h.c. . \\\\\n    H_{QD} = \\varepsilon d^\\dagger d,\n\\end{equation}\n\nwhere $c$ denotes fermion field operators acting on the lead subspace and $d$ the QD counterparts.\n\nWe'll use both `kerntype='RTD'` and `kerntype='Pauli'` to get a comparison between the two. Non-equilibrium conditions are included using either a voltage bias or a thermal biases. First we setup our `qmeq.Builder` objects:\n\n\n```python\nnsingle, nleads = 1, 2\nhsingle = {(0,0):0}\n\ngamma = 1\nt = np.sqrt(gamma/2/np.pi)\ntleads = {(0,0):t, (1,0):t}\nT, V = 10*gamma, 0\n\nsystem_RTD = qmeq.Builder(nsingle=nsingle, nleads=nleads, tleads=tleads, kerntype='pyRTD', itype=1, dband=1e6)\nsystem_Pauli= qmeq.Builder(nsingle=nsingle, nleads=nleads, tleads=tleads, kerntype='Pauli', itype=1, dband=1e6)\n```\n\nNext we sweep the gate voltage $V_g$ (level energy)  at a fixed bias voltage $V=10\\Gamma=T \\ (\\Delta T=0)$ and plot the results.\n\n\n```python\nVg = np.linspace(-100, 100, 200)\nI_RTD, I_Pauli = np.zeros(len(Vg)), np.zeros(len(Vg))\nQ_RTD, Q_Pauli = np.zeros(len(Vg)), np.zeros(len(Vg))\nV = 10\n\nfor i, vg in enumerate(Vg):\n    I_RTD[i], Q_RTD[i] = current(system_RTD, V, vg, T, 0)\n    I_Pauli[i], Q_Pauli[i] = current(system_Pauli, V, vg, T, 0)\n\n#Plotting\nplt.figure(figsize=(11, 3.5))\nf1 = plt.subplot(121)\ngenerate_plot(Vg, [I_RTD, I_Pauli], ['RTD', 'Pauli'], ['k', 'r--'], 'I', 'Vg')\nplt.subplot(122)\ngenerate_plot(Vg, [Q_RTD, Q_Pauli], ['RTD', 'Pauli'], ['k', 'r--'], 'Q', 'Vg')\nplt.show()\n```\n\nHere one can see that the second order processes make the results qualitatively different, with generally lower currents. \n\nSwitching to a thermal bias $\\Delta T = T/2$ $(V=0)$ instead of a voltage bias we get:\n\n\n```python\ndT = T/2\n\nfor i, vg in enumerate(Vg):\n    I_RTD[i], Q_RTD[i] = current(system_RTD, 0, vg, T, dT)\n    I_Pauli[i], Q_Pauli[i] = current(system_Pauli, 0, vg, T, dT)\n\n#Plotting\nplt.figure(figsize=(11, 3.5))\nf1 = plt.subplot(121)\ngenerate_plot(Vg, [I_RTD, I_Pauli], ['RTD', 'Pauli'], ['k', 'r--'], 'I', 'Vg')\nplt.subplot(122)\ngenerate_plot(Vg, [Q_RTD, Q_Pauli], ['RTD', 'Pauli'], ['k', 'r--'], 'Q', 'Vg')\nplt.show()\n```\n\nSecond order processes allow electron transport at a finite, but small, energy window around the energy level, in contrast to first order processes where the energy of the transported electrons is always exactly equal to that of the QD state. This finite energy window leads to a finite heat current when $\\mu_1=\\mu_2=V_g$, as can be seen for the black line at $V_g=0$ in the right-hand side figure, something that is not possible in first order.\n\nAlthough the effects of the second order corrections might seem small in these plots, they can have large consequences in certain situations, as will be seen later.\n\n## Anderson model: co-tunneling \n\nLet's turn our attention to the Anderson model:\n\n\\begin{equation}\n    H = H_R + H_T + H_{QD} \\\\\n    H_R = \\sum_{k,\\sigma,r=l,r}\\omega_{k,\\sigma, r}c^\\dagger_{k,\\sigma,r}c_{k,\\sigma, r}\\\\\n    H_T = \\sum_{k,\\sigma,r} t_{k,\\sigma, r}d^\\dagger_{\\sigma}c_{k,\\sigma, r} + h.c. . \\\\\n    H_{QD} = \\sum_{\\sigma=\\uparrow\\downarrow}\\varepsilon_\\sigma n_\\sigma + Un_\\uparrow n_\\downarrow\n\\end{equation}\n\nwhere $n_\\sigma = d^\\dagger_\\sigma d_\\sigma$. When the QD is subjected to an external magnetic field the single particle states will be Seeman-split $\\Delta \\varepsilon = \\varepsilon_\\uparrow - \\varepsilon_\\downarrow>0$. In that case one expects to see familiar co-tunneling lines inside the Coulomb diamond when performing measurements on QDs. Both second order approaches in QmeQ are able to capture this feature, as we will see now. However, due to the  numerical complexity of the 2nd order von Neumann approach we only demonstrate this for the RTD approach.\n\nFirst we build the system.\n\n\n```python\ndef Anderson_model(kerntype, T, U, Ez):\n    \"\"\"Sets up an Anderson model with lead temperature\n    T, interaction strength U and Seeman split Ez.\"\"\"\n    nsingle, nleads = 2, 4\n    gamma = 1\n    t = np.sqrt(gamma/2/np.pi)\n    T = T\n    U = U\n    Ez = Ez #Seeman split \n\n    tlst = {0:T, 1:T, 2:T, 3:T}\n    tleads = {(0,0):t, (1,0):t, (2,1):t, (3,1):t}\n    coulomb = {(0,1,1,0):U}\n    mulst = {0:0, 1:0, 2:0, 3:0}\n    hsingle = {(0,0):0, (1,1):0}\n\n    system = qmeq.Builder(nsingle, hsingle, coulomb,\n                          nleads, tleads, mulst, tlst, 5e5,\n                          kerntype=kerntype, itype=1)\n    return system\n\n#Set up the model\nT, U, Ez = 10, 500, 100\nsystem = Anderson_model('RTD', T, U, Ez)\n```\n\nNext we solve for the differential conductance $G=\\frac{dI}{dV}$ for both $V$ and $V_g$ to be able to plot a stability diagram.\n\n\n```python\n%%time\nVg = np.linspace(-U/2, U*3/2, 100)\nV = np.linspace(-U*3/2, U*3/2, 100)\nG = np.zeros((len(V), len(Vg)))\ndV = 1e-3\n\nfor i, vg in enumerate(Vg):\n    system.change(hsingle={(0,0):-vg -Ez/2,(1,1):-vg+Ez/2})\n    for j, v in enumerate(V):      \n        system.change(mulst={0:v/2+dV, 1:-v/2-dV, 2:v/2+dV, 3:-v/2-dV})\n        system.solve()\n        I1 = system.current[0] + system.current[2]\n                  \n        system.change(mulst={0:v/2-dV, 1:-v/2+dV, 2:v/2-dV, 3:-v/2+dV})\n        system.solve()\n        G[j,i] = (I1 - system.current[0] - system.current[2])/(2*dV)                            \n```\n\n    Wall time: 25.7 s\n\n\nWhen plotting the result we see large areas of finite (but small) conductance away from the zero-bias line $V=0$ in the Coulomb diamond. This is an effect of co-tunneling, which is properly captured by the RTD approach.\n\n\n```python\nplt.figure(figsize=(7,5))\nplt.pcolormesh(Vg/U, V/U, G, norm=matplotlib.colors.LogNorm() )\nc = plt.colorbar(label=r'$G \\ [e^2/{\\hbar}]$')\nplt.xlabel(r'$V_g\\ [U]$', size=14)\nplt.ylabel(r'$V\\ [U]$', size=14)\nplt.show()\n```\n\n## A larger example: the quantum dot heat engine\n\nIn order to see when it can be absolutely necessary to include second order effects we can keep studying the Anderson model. However, now we'll use the QD as a heat engine, converting thermal energy into electrical energy using the Seebeck effect. When using the QD as a heat engine it's connected in series to an external (resistive) load, instead of a voltage source, yielding the circuit diagram:\n\n\n\nThe red and blue blocks next to the QD symbolize leads at different temperatures. Due to current conservation in the circuit the same current needs to flow through both components. In addition, Krichhoff's voltage law states that the size of the voltages need to be the same over both components, but with opposite polarity. Thus, determining the operating conditions for the QD requires solving (iteratively)\n\n\\begin{equation}\n    I_{QD}(V_{QD}) + \\frac{V_{QD}}{R}=0,\n\\end{equation}\n\nfor $V_{QD}$. In the limit $R\\rightarrow\\infty$ the equation can be used to define the thermovoltage $V_{th}=V_{QD}\\Big |_{I=0}$.\n\nAll electrical power generated by the QD will be dissipated in the load and it is evaluated as $P=IV_{QD}$. We're also interested in the thermodynamic efficiency of device\n\n\\begin{equation}\n    \\eta=\\frac{P}{\\dot{Q}_H},\n\\end{equation}\n\nwith $\\dot{Q}_H$ denoting the heat current entering the QD from the hot side.\n\nBefore calculating the power and efficiency of the device we need to introduce functions for calculating the voltage over the QD in the presence of a load, and during open circuit conditions.\n\n\n```python\ndef func_root(v, vg, T, dT, system, R):\n    I, Q = current(system, v, vg, T, dT, leads=[0,2])\n    if R != np.inf:\n        I += v/R\n    return I\n\ndef voltage_R(vg, T, dT, system, R):\n    result = optimize.root_scalar(func_root, args=(vg, T, dT, system, R), method='brentq', bracket=[-200, 200])\n    return result.root\n```\n\nIt's well-known that sequential (first order) tunneling processes often don't give accurate predictions of $V_{th}$ (i.e. $\\lim_{R\\rightarrow \\infty}V_{QD}$) due to a tight coupling between particle and energy flow. Including also second order processes breaks this tight coupling, which can lead to drastic changes of the thermovoltage, even for seemingly small $\\Gamma$s.\n\nTo see this we calculate $V_{th}$ using both `kerntype='RTD'` and `kerntype='Pauli'` for an Anderson model where $T=\\Delta T = 10\\hbar\\Gamma$ and $U = 20T$.\n\n\n```python\nsystem_RTD = Anderson_model('RTD', T, U, 0)\nsystem_Pauli = Anderson_model('Pauli', T, U, 0)\n\ndT = T\nVg = np.linspace(-U/2, U*3/2, 200)\nVth_RTD, Vth_Pauli = np.zeros(len(Vg)), np.zeros(len(Vg))\nfor i, vg in enumerate(Vg):\n    Vth_RTD[i] = voltage_R(vg, T, dT, system_RTD, np.inf)\n    Vth_Pauli[i] = voltage_R(vg, T, dT, system_Pauli, np.inf)\n\ngenerate_plot(Vg, [Vth_RTD, Vth_Pauli], ['RTD', 'Pauli'], ['k', 'r--'], 'Vth', 'Vg_U')\n```\n\nIndeed, we see that including the second order processes drastically change the lineshape of $V_{th}(V_g)$.\n\nNext, we change the load to a finite value $R=5\\ M\\Omega$ such that the device can generate power. We focus on the generated power and absorbed heat current as a function of $V_g$:\n\n\n```python\nR = 243*5 #5 MOhm i units of hbar/e^2\nI_Pauli, I_RTD = np.zeros(len(Vg)), np.zeros(len(Vg)) \nP_Pauli, P_RTD = np.zeros(len(Vg)), np.zeros(len(Vg)) \nQ_Pauli, Q_RTD = np.zeros(len(Vg)), np.zeros(len(Vg)) \n\nfor i, vg in enumerate(Vg):\n    v_Pauli = voltage_R(vg, T, dT, system_Pauli, R)\n    I_Pauli[i], Q_Pauli[i] = current(system_Pauli, v_Pauli, vg, T, dT, leads=[0,2])\n    P_Pauli[i] = -v_Pauli*I_Pauli[i]\n    \n    v_RTD = voltage_R(vg, T, dT, system_RTD, R)\n    I_RTD[i], Q_RTD[i] = current(system_RTD, v_RTD, vg, T, dT, leads=[0,2])\n    P_RTD[i] = -v_RTD*I_RTD[i]\n\n#Plotting\nplt.figure(figsize=(11, 3.5))\nplt.subplot(121)\ngenerate_plot(Vg/U, [P_RTD, P_Pauli], ['RTD', 'Pauli'], ['k', 'r--'], 'P', 'Vg_U')\nplt.subplot(122)\ngenerate_plot(Vg/U, [Q_RTD, Q_Pauli], ['RTD', 'Pauli'], ['k', 'r--'], 'Q', 'Vg_U')\n```\n\nThe differences between the two approaches are quite substantial, especially for the heat current, and they lead to even larger differences when calculating the efficiency:\n\n\n```python\nn_Pauli = P_Pauli/Q_Pauli\nn_RTD = P_RTD/Q_RTD\nnc = dT/(T+dT)\n\ngenerate_plot(Vg/U, [n_RTD/nc, n_Pauli/nc], ['RTD', 'Pauli'], ['k', 'r--'], 'n', 'Vg_U')\n```\n\nHere we see that ignoring the second order processes leads to very large errors. The differences stem from the fact the QD can be seen as a perfect energy filter in the Pauli case (energy of transported electrons = energy of the QD state), which is no longer true when using the RTD approach. This has a large impact on $\\eta$.\n\n(The Pauli result actually gives $\\eta=0$ for $V_g=0$ and $V_g=U$, but the resolution used here is too small to capture that feature.)\n\n## Off-diagonal corrections\n\nThe RTD approach sets up Master equations for diagonal density matrices. However, when one derives these equations by performing a systematic expansion of the Liouville-von Neumann equation up to second order in $\\Gamma$ one needs to include a correction term that stems from off-diagonal elements in first order. See [this article](https://journals.aps.org/prb/abstract/10.1103/PhysRevB.78.235424) for an explanation.\n\nThese correction terms are included by default in QmeQ, but can be turned off by the user. This is done by setting the variable `off_diag_corrections` of the `qmeq.Builder` object to `False` before calling `solve()`, e.g. \n\n```Python\nsystem = qmeq.Builder(..., kerntype='RTD')\nsystem.off_diag_corrections = False\nsystem.solve()\n```\n\nHowever, turning off the corrections generally does not lead to any noticeable performance gains, although it reduces memory consumption a bit.\n\nThese corrections can be important as long as first order off-diagonal terms are not identically zero (which they can be due to selection rules, e.g. in the Anderson model). They are e.g. important when more than one QD state connect to the same lead, even when the energy difference between the states is large. To illustrate this we can study a model with two states, both connected to the same two leads.\n\n\\begin{equation}\n    H = H_R + H_T + H_{QD} \\\\\n    H_R = \\sum_{k,r=l,r}\\omega_{k,r}c^\\dagger_{k,r}c_{k, r}\\\\\n    H_T = \\sum_{k,r,i} t_{k, r, i}d^\\dagger_{i}c_{k,r} + h.c. . \\\\\n    H_{QD} = \\sum_{i=1,2}\\varepsilon_i d^\\dagger_id_i\n\\end{equation}\n\nWe set up the systems using parameters where the corrections become important (in this case $T=10\\Gamma$, $V=3T,\\ \\Delta\\varepsilon = 2T,\\ U = 10^4T$):\n\n\n```python\nnsingle, nleads = 2, 2\ngamma, T, V, dE, U = 1, 10, 30, 20, 1e5\n\ncoulomb = {(0,1,1,0):U}\nhsingle = {(0,0):0, (1,1):dE}\n\nt = np.sqrt(gamma/2/np.pi)\ntleads = {(0,0):t, (1,0):t, (0,1):t, (1,1):t}\ntlst = {0:T, 1:T}\nmulst = {0:-V/2, 1:V/2}\n\nsystem = qmeq.Builder(nsingle=nsingle, hsingle=hsingle, nleads=nleads, tleads=tleads, mulst=mulst,\n                      coulomb=coulomb, tlst=tlst, kerntype='RTD', itype=1, dband=1e6)\n```\n\nSweeping $V_g$ and plotting the current with and without the corrections shows the importance of these effects.\n\n\n```python\nVg = np.linspace(-0.2*U, 1.2*U , 300)\nI1, I2 = np.zeros(len(Vg)), np.zeros(len(Vg))\n\nfor i, vg in enumerate(Vg):    \n    system.change(hsingle={(0,0):-vg, (1,1):dE-vg})\n    system.solve()\n    I1[i] = system.current[0]\n    \n    system.off_diag_corrections = False\n    system.solve()\n    I2[i] = system.current[0]\n    system.off_diag_corrections = True\n    \n#Plotting\nplt.figure(figsize=(13,4))\nplt.subplot(121)\ngenerate_plot(Vg/U, [abs(I1), abs(I2)], ['w/ corr', 'w/o corr'], ['r', 'b'], 'absI', 'Vg_U')\nplt.semilogy()\n\nplt.subplot(122)\nplt.semilogy(Vg/U, abs((I2-I1)/I1), 'k')\nplt.xlabel(r'$V_g\\ [U/e]$', size=14)\nplt.ylabel('relative error ' + r'$\\left | (I-I_{w/o})\\ / \\ I \\right|$', size=14)\nplt.show()\n```\n\nIt's obvious that it is absolutely crucial to include the correction terms for these parameters. The relative strength of the corrections will of course depend on the model and its parameters, but it's generally recommended to keep the corrections turned on.\n\n## Complex $t$s\n\nThe RTD approach can in general handle complex $t$s, with the exception that the energy current cannot be evaluated when the product of $t$s lead to complex matrix elements of the energy kernels. However, if one, for example, rotates all $t$s with a global complex phase one will not change the resulting currents. We exemplify this using the Anderson model\n\n\n```python\ndef rotate_tleads(g, theta):\n    t = np.sqrt(g/2/np.pi)\n    t2 = t*(np.cos(theta)+ 1j*np.sin(theta))\n    tleads = {(0,0):t2, (1,0):t2, (2,1):t2, (3,1):t2}\n    return tleads\n\nT, dT = 10, 10\nU = 400\nN = 100\n\n#Set up system and rotate tleads\nsystem = Anderson_model('RTD', T, U, 0)\nsystem2 = Anderson_model('RTD', T, U, 0)\ntheta = np.random.rand()*2*np.pi\ntleads = rotate_tleads(1, theta)\nsystem2.change(tleads = tleads)\n\n#Sweep Vg and calculate current\nVg = np.linspace(-150, 550, N)\nI, Q = np.zeros(N), np.zeros(N)\nI2, Q2 = np.zeros(N), np.zeros(N)\nfor i, vg in enumerate(Vg):\n    I[i], Q[i] = current(system, 0, vg, T, dT, leads=[0,2])\n    I2[i], Q2[i] = current(system2, 0, vg, T, dT, leads=[0,2])\n\n#Plotting\ngenerate_plot(Vg/U, [I, I2], [r'$\\theta=0$', r'$\\theta\\ne 0$'], ['k', 'r--'], 'I', 'Vg_U')\nplt.title(r'$\\theta$ = ' + str(round(theta, 2)) )\nplt.show()\n```\n\n## Comparison with 2nd order von Neumann (2vN)\n\nThe `RTD` approach and the `2vN` approach are based on different assumptions, and they can thus model different physical processes. Both are second order approaches, but whereas `RTD` is second order in $\\Gamma$, `2vN` is second order in the number of electron/hole excitations. The currents calculated using the two approaches are thus expected to differ sometimes, but will give identical results other times.\n\nOne example where they give identical results are for the an Anderson model where $U=1000\\Gamma$, $T = 10\\Gamma$. Below are some pre-computed results comparing the charge currents for the two approaches when sweeping either $V_g$ with a thermal bias $(\\Delta T=\\frac{1}{2}T, V=0)$ or sweeping $V$ with a voltage bias $(\\ \\Delta T = 0, V_g = 100\\Gamma)$\n\n\n\n\n\n\n## RTD with ManyBodyBuilder\n\nIn the RTD approach the energy current out from a lead is evaluated using three Kernels:\n\n\\begin{equation}\n\\langle J_r \\rangle = \\underset{D}{\\text{Tr}} L_D W_r \\rho_D - \\frac{1}{2}\\underset{D}{\\text{Tr}}W_{E,1}^r\\rho_D + \\frac{1}{2}\\underset{D}{\\text{Tr}}W_{E,2}^r\\rho_D\n\\end{equation}\n\nThe kernels in the two right-most terms depend on both the usual *many body* tunneling amplitudes in `Tba` as well as the pure *single particle* tunneling amplitudes defined in `tleads`. Therefore, using the RTD approach together with`qmeq.ManyBodyBuilder` can lead to incorrect evaluation of the energy- and heat currents as no single particle tunneling amplitudes are defined, and the last two terms are simply ignored. This is no problem in models where each single particle state only connects to a *single* lead, since the kernels contain terms proportional to $t_{l,r}t_{l,r'}$ where $l$ denotes a single particle state and $r,\\ r'$ two *different* leads.\n\nIf that is not the case also single particle tunneling amplitudes have to be added when using the `ManyBodyBuilder`. We exemplify this by looking at a model with two single particle states that are hybridized. We include two leads and both states couple to both leads.\n\n\\begin{equation}\n    H = H_R + H_T + H_{QD} \\\\\n    H_R = \\sum_{k,r=l,r}\\omega_{k,r}c^\\dagger_{k,r}c_{k, r}\\\\\n    H_T = \\sum_{k,r,i} t_{k, r, i}d^\\dagger_{i}c_{k,r} + h.c. . \\\\\n    H_{QD} = \\sum_{i=1,2}\\varepsilon_i d^\\dagger_id_i + \\sum_{i\\ne j}\\Omega_{ij}d^\\dagger_i d_j\n\\end{equation}\n\nWe first build our model using `qmeq.Builder` to be able obtain many-body tunnel matrix elements and a diagonalized QD Hamiltonian:\n\n\n```python\n#lead parameters\nnleads = 2\nmulst = [0, 0]\ntlst = [20, 10]\nt = 1/np.sqrt(2*np.pi)\ntleads_ref = {(0, 0): t, (0,1):t/10, (1, 1): t, (1,0):t/10}\n\n#QD parameters\nnsingle = 2\nOmega, U = 5, 500\ncoulomb = {(0,1,1,0):U}\nhsingle = {(0,0):0, (1,1):0, (0,1):Omega}\n\n#Setup reference system and soolve once\nsystem_ref = qmeq.Builder(nsingle=nsingle, nleads=nleads, hsingle=hsingle, mulst=mulst, coulomb=coulomb,\n                      tlst=tlst, tleads=tleads_ref, dband=5e5, kerntype='RTD', itype=1)\nsystem_ref.solve()\nprint('Many-body energies: ', system_ref.Ea, '\\n')\nprint('Many-body tunneling:\\n ', system_ref.Tba)\n```\n\n    Many-body energies:  [  0.  -5.   5. 500.] \n    \n    Many-body tunneling:\n      [[[ 0.        +0.j  0.25388531+0.j  0.31030427+0.j  0.        +0.j]\n      [ 0.25388531-0.j  0.        +0.j  0.        +0.j -0.31030427+0.j]\n      [ 0.31030427-0.j  0.        +0.j  0.        +0.j  0.25388531+0.j]\n      [ 0.        +0.j -0.31030427-0.j  0.25388531-0.j  0.        +0.j]]\n    \n     [[ 0.        +0.j -0.25388531+0.j  0.31030427+0.j  0.        +0.j]\n      [-0.25388531-0.j  0.        +0.j  0.        +0.j -0.31030427+0.j]\n      [ 0.31030427-0.j  0.        +0.j  0.        +0.j -0.25388531+0.j]\n      [ 0.        +0.j -0.31030427-0.j -0.25388531-0.j  0.        +0.j]]]\n\n\nFor convenience we define a function for looping over $V_g$ and calculating the energy current for the two methods of building the system:\n\n\n```python\ndef loop_energy_current(sys, MB=False):\n    \"\"\"Loops Vg and calculates E. If MB=True it is assumed that\n    the ManyBodyBuilder was used.\"\"\"\n    I = []\n    for vg in Vg:\n        if MB is True:\n            sys.Ea = np.array([0, -vg-Omega, -vg+Omega, U-2*vg])\n            sys.si.states_changed = True\n            sys.solve(qdq=False, rotateq=False)\n        else:\n            sys.change(hsingle = {(0,0):-vg, (1,1):-vg, (0,1):Omega})\n            sys.solve()\n        I.append(sys.energy_current[0])        \n    return I    \n\nVg = np.linspace(-200,U + 200, 100)\n```\n\nNext we see what happens if we use `qmeq.ManyBodyBuilder()` without specifying single particle tunneling. We plot the absolute value of the relative error with respect to the reference $\\varepsilon= |(I_{MB}-I_{ref})/I_{ref}|$.\n\n*Note that when using `qmeq.BuilderManyBody` we need to create the system using `pyRTD` and then change the kernel to `RTD`. This is due to a bug in the current version of the `RTD` approach. This will be fixed in later versions.*\n\n\n```python\n#Setup MB system\nMB_charge = [0,1,1,2] #Charge of many body states\nsystem1 = qmeq.BuilderManyBody(system_ref.qd.Ea, MB_charge, system_ref.Tba, mulst, tlst, 5e5, \n                               kerntype='RTD', itype=1)\nsystem1.kerntype='RTD'\n\n#Calculate reference and many body energy currents\nI_ref = loop_energy_current(system_ref)\nI1 = loop_energy_current(system1, MB = True)\n\n#Plotting\nplt.semilogy(Vg/U, abs((np.array(I_ref) - np.array(I1))/np.array(I_ref)))\nplt.ylabel('| relative error |', size=14)\nplt.xlabel(r'$V_g\\ [U]$', size=14)\nplt.show()\n```\n\nHere it is obvious that we make mistakes when calculating the energy current. The magnitude of the error will of course depend on the model and its parameters.\n\nWe'll therefore add single particle tunneling amplitudes to the ManyBodyBuilder system. This requires specifying `ManyBodyBuilder.nsingle` and `ManyBodyBuilder.tleads_array` where `tleads_array` is an `nleads*nsingle` array.\n\nWhen specifying `tleads_array` we need to choose a single particle basis. We'll exemplify this by using both the same basis as for the reference system (see above), and the bonding/anti-bonding (molecule) basis. For the former we have already defined the $t$s in `tleads`. For the latter we need to rotate `tleads` to the new basis.\n\n\n```python\n#Define the two systems\nsystem2 = qmeq.BuilderManyBody(system_ref.qd.Ea, MB_charge, system_ref.Tba, mulst, tlst, 5e5, \n                               kerntype='pyRTD', itype=1)\nsystem2.kerntype = 'RTD'\n\nsystem3 = qmeq.BuilderManyBody(system_ref.qd.Ea, MB_charge, system_ref.Tba, mulst, tlst, 5e5, \n                               kerntype='pyRTD', itype=1)\nsystem3.kerntype = 'RTD'\n\n#Rotate tleads for bonding/anti-bonding basis\nf1 = 0.6363961030854391\nf2 = 0.7778174593127221\ntleads_bond = {(0, 0): t*f1, (0,1):t*f2, (1, 1): t*f2, (1,0):-t*f1}\n\n#Translate tleads to arrays\ntleads_array2 = np.zeros((2,2), dtype=complex)\ntleads_array3 = np.zeros((2,2), dtype=complex)\nfor i in range(2):\n    for j in range(2):\n        tleads_array2[i,j] = tleads_ref[(i,j)]\n        tleads_array3[i,j] = tleads_bond[(i,j)]\n        \n#Set single particle tunneling and calculate energy currents\nsystem2.nsingle = 2\nsystem3.nsingle = 2\nsystem2.tleads_array = tleads_array2\nsystem3.tleads_array = tleads_array3\nI2 = loop_energy_current(system2, MB = True)\nI3 = loop_energy_current(system3, MB = True)\n\n#Plotting\nplt.semilogy(Vg/U, abs((np.array(I_ref) - np.array(I2))/np.array(I_ref)), 'k')\nplt.semilogy(Vg/U, abs((np.array(I_ref) - np.array(I3))/np.array(I_ref)),'r--')\nplt.ylabel('| relative error |', size=14)\nplt.xlabel(r'$V_g\\ [U]$', size=14)\nplt.show()\n```\n\nHere we can see that both basis choices give (approximately) the same error, which is many orders of magnitude smaller than for the case without single particle tunneling.\n", "meta": {"hexsha": "a23c768bca75d4fd1d30ed32aa904b4167e1453c", "size": 364933, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorial/RTD tutorial.ipynb", "max_stars_repo_name": "M-Josefsson/qmeq-examples", "max_stars_repo_head_hexsha": "ff7bdf0ae30a5f03d418a0ab63a830232c300c9d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-10T17:46:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-10T17:46:19.000Z", "max_issues_repo_path": "tutorial/RTD tutorial.ipynb", "max_issues_repo_name": "M-Josefsson/qmeq-examples", "max_issues_repo_head_hexsha": "ff7bdf0ae30a5f03d418a0ab63a830232c300c9d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-12T12:53:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-12T12:53:16.000Z", "max_forks_repo_path": "tutorial/RTD tutorial.ipynb", "max_forks_repo_name": "M-Josefsson/qmeq-examples", "max_forks_repo_head_hexsha": "ff7bdf0ae30a5f03d418a0ab63a830232c300c9d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-01-23T14:17:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-23T09:02:55.000Z", "avg_line_length": 366.0310932798, "max_line_length": 48408, "alphanum_fraction": 0.9252301107, "converted": true, "num_tokens": 8609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.0803574633162173, "lm_q1q2_score": 0.03892355485339402}}
{"text": "# Implementaci\u00f3n de los m\u00e9todos\n\n\n\n\nEn este notebook se plantea la soluci\u00f3n del problema utilizando los siguiente m\u00e9todos: Newton, Broyden-Fletcher-Goldfarb-Shanno  (BFGS) y el gradiente descendente estoc\u00e1stico (SGD). El presente notebook es autocontenido, sin embargo, la implementaci\u00f3n principal se realiza con un enfoque modular.\n\nA continuaci\u00f3n, se describe el conjunto de datos que se emplear\u00e1n y se define el planteamiento del problema. Una explicaci\u00f3n m\u00e1s detallada se realiza en el informe (en formato PDF) de este proyecto.\n\n**Nota:** Esta implementaci\u00f3n se basa en material y actividades impartidas por los profesores de los cursos de [M\u00e9todos Num\u00e9ricos y optimizaci\u00f3n](https://github.com/ITAM-DS/analisis-numerico-computo-cientifico/blob/master/temas/IV.optimizacion_convexa_y_machine_learning/4.3.Regresion_logistica_R.ipynb) (2010-I) (Prof. Erick Palacios Moreno) y Aprendizaje de M\u00e1quina (2019-II) (Prof. Rodrigo Mendoza Smith).\n\n\n## Conjunto de datos\n\nPor la restricciones de uso de la base de datos de entrenamiento original (adem\u00e1s de una serie de requerimientos protocolares como contar con la aprobaci\u00f3n de un Comit\u00e9 de \u00c9tica Independiente), optamos por trabajar con una de las dos bases de datos que los autores emplearon para validar sus modelos: KGH. La base de datos en menci\u00f3n, consta de $106$ casos positivos  de  pacientes  con  \u00e9bola  y  un  case fatality rate global por encima del setenta por ciento.  Originalmente,  previo  al tratamiento de los datos, la base ten\u00eda \u00fanicamente $44$ registros de triaje, $58$ registros de carga viral, con un total de 78 valores faltantes en todo el data set. Para  harmonizar  los  datos,  los  autores  transformaron  la  carga  viral  en  CT,  conforme  con  la curva est\u00e1ndar qPCR:\n\n$$log_{(carga \\; viral)} = m*CT + c_0$$\n\nNosotros, para fines del presente trabajo, empleamos una de las versiones imputadas de esta base de datos, dispuesta en el siguiente sitio: [ebola-imc-public](https://github.com/dapivei/ebola-imc-public/blob/master/data/kenema/test/pres-kgh/imputation-50.csv), misma que cuenta con $11$ variables: la variable output, $y_{i}$ asociada a la supervivencia o no del paciente ${i}$ con virus del \u00e9bola, y ${j}$ variables explicativas asociadas, $x_{i,j}$. Los regresores escogidos son aquellos que, conforme con nuestra principal referencia, son buenos predictores de la probabilidad de muerte o no de un paciente. \n\n|Tipo| Nombre|Descripci\u00f3n|\n|---| --- | --- |\n|Variable Num\u00e9rica| CT |El cycle threshold (CT) es una variable que se calcula a partir de una relaci\u00f3n m\u00e9dica bien conocida (qPCR) y la carga viral (una expresi\u00f3n n\u00famerica de la cantidad de virus dado un vol\u00famen de fluido que normalmente se correlaciona con la severidad de una infecci\u00f3n viral activa).|\n|Variable Num\u00e9rica|TEMP|Temperatura corporal del paciente. Toma valores de 1 a 73.|\n|Variable Num\u00e9rica|_AGE_ |Edad del paciente. Toma valores de $1$ a $73$.|\n|Variable Categ\u00f3rica |_HEADCH_ | Presencia o no dolores de cabeza. Toma valores valores $0$ o $1$, dependiendo de si el paciente presenta o no dolores de cabeza.|\n|Variable Categ\u00f3rica |  _BLEED_ | Presencia o no de sangrado. Toma valores valores $0$ o $1$, dependiendo de si el paciente presenta o no sangrado. |\n|Variable Categ\u00f3rica |  _DIARR_ | Presencia o no de diarrea. Toma valores valores $0$ o $1$, dependiendo de si el paciente presenta o no diarrea.|\n|Variable Categ\u00f3rica | _VOMIT_ | Dificultad para comer, conocido como disfagia, t\u00e9rmino t\u00e9cnico para describir el s\u00edntoma consistente en dificultad para la degluci\u00f3n (problemaspara  tragar).   Esta  dificultad  suele  ir  acompa\u00f1ada  de  dolores,  a  veces lancinantes (disfagia dolorosa u odinofagia .  Toma valores valores $1$ o $0$, dependiendo de si el paciente presenta o no de disfacia\n|Variable Categ\u00f3rica | _PABD_ | Presencia o no de PADB.\n|Variable Categ\u00f3rica |_WEAK_ | Presencia o no de debilidad o fatiga general.|\n|Variable Categ\u00f3rica |_JAUN_ |Condici\u00f3n  en la cu\u00e1l la piel, los ojos y los miembros mucosos que vuelven amarillos debido a altos niveles de bilirubina. Toma valores valores $0$ o $1$, dependiendo de si el paciente presenta o no ictericia.|\n|Variable Categ\u00f3rica |_OUT_| Muerte o no muerte del paciente.  Toma valores $1$ o $0$.  Dependiendo desi el paciente muere o no muere.|\n\n\n\n\n## Problema de regresi\u00f3n Log\u00edstica\n\nMatem\u00e1ticamente, este conjunto se define de la siguiente manera: \n\n$$\\mathcal{D}=\\left\\{ \\left(x_{i},y_{i}\\right)\\in\\mathbb{R}^{p}\\times\\left\\{ 0,1\\right\\} :i\\in\\left[m\\right]\\right\\} $$.\n\nEl m\u00e9todo de _regresi\u00f3n log\u00edstica_ asume que $Pr\\left[y_{i}\\mid x_{i},\\beta\\right]\\sim Bernoulli\\left(\\mu_{i}\\right)$\ncon los siguientes supuestos sobre la media, $\\mu_{i}$:\n\n$$\n\\mu_{i}=\\sigma\\left(\\beta^{T}x_{i}\\right) \\label{eq-3.1} \\tag{1}\n$$\n$$\n\\sigma(z)=\\left(1+\\exp\\left(-z\\right)\\right)^{-1} \\label{eq-3.2} \\tag{2}\n$$\n\ndonde $\\beta\\in\\mathbb{R}^{p}$. \n\n\nDado lo anterior, nuestro problema es encontrar un modelo tal que $\\hat{\\beta}\\in\\mathbb{R}^{p}$ explica de la mejor manera posible a $\\mathcal{D}$. \n\nPara lograr lo anterior, debemos estimar el conjunto de par\u00e1metros $\\hat{\\beta}$ para modelar $Pr\\left[y\\mid x,\\hat{\\beta}\\right]$ y predecir la etiqueta $\\hat{y}\\in\\left\\{ 0,1\\right\\} $ de un nuevo\ndato $x$ por medio de:\n\n$$\n\\hat{y}=\\begin{cases}\n1 & si\\,\\sigma\\left(\\hat{\\beta}^{T}x\\right)\\geq0.5\\\\\n0 & si\\,\\sigma\\left(\\hat{\\beta}^{T}x\\right)<0.5\n\\end{cases}\\label{eq-3.3} \\tag{3}\n$$\n\nla funci\u00f3n de p\u00e9rdida que queremos minimizar en este problema corresponde a la _log-verosimilitud negativa_ , que est\u00e1 dada por:\n\n$$\nF(\\beta):=LVN(\\beta)=-\\sum_{i=1}^{m}\\left[y_{i}log\\mu_{i}+(1-y_{i})log(1-\\mu_{i})\\right]\\label{eq-3.4} \\tag{4}\n$$\n\n\nUna vez planteado lo anterior, queremos encontrar $\\hat{\\beta}$ por medio de m\u00e9todos num\u00e9ricos de optimizaci\u00f3n de tal forma que se minimize ([4](#mjx-eqn-eq1)) para el conjunto de datos dado.\n\n\n_En los siguientes fragmentos de c\u00f3digo se realiza el planteamiento del problema, desde la importaci\u00f3n de datos hasta el proceso de entrenamiento del modelo utilizando distintos algoritmos de optimizaci\u00f3n que se explican con brevedad._\n\n\n\n---------------------\n\n## Importaci\u00f3n y exploraci\u00f3n del conjunto de datos\n\nEn esta secci\u00f3n se importa y transforma los datos, con el fin de obtener el conjunto $\\mathcal{D}$.\n\n\n```python\n# librer\u00edas\nimport math\nimport numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import OneHotEncoder\nimport seaborn as sns\nimport sys\nimport matplotlib.pyplot as plt\n```\n\n\n```python\nurl=\"https://raw.githubusercontent.com/afcarl/ebola-imc-public/master/data/kenema/test/pres-kgh/imputation-50.csv\"\ndf_raw=pd.read_csv(url,sep=\",\")\n```\n\n\n```python\ndf_raw.head()\n# df[df.isnull().any(axis=1)] - no hay NAs\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>OUT</th>\n      <th>CT</th>\n      <th>AGE</th>\n      <th>TEMP</th>\n      <th>HEADCH</th>\n      <th>BLEED</th>\n      <th>DIARR</th>\n      <th>JAUN</th>\n      <th>VOMIT</th>\n      <th>PABD</th>\n      <th>WEAK</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>28.652450</td>\n      <td>42.0</td>\n      <td>36.3</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>25.736016</td>\n      <td>45.0</td>\n      <td>36.5</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1</td>\n      <td>20.747653</td>\n      <td>65.0</td>\n      <td>38.0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1</td>\n      <td>22.736993</td>\n      <td>44.0</td>\n      <td>38.6</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1</td>\n      <td>20.846284</td>\n      <td>11.0</td>\n      <td>38.4</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# verificar tipo de variables \ndf_raw.dtypes\n```\n\n\n\n\n    OUT         int64\n    CT        float64\n    AGE       float64\n    TEMP      float64\n    HEADCH      int64\n    BLEED       int64\n    DIARR       int64\n    JAUN        int64\n    VOMIT       int64\n    PABD        int64\n    WEAK        int64\n    dtype: object\n\n\n\n\n```python\n# Resumen de las variables\ndf_raw.describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>OUT</th>\n      <th>CT</th>\n      <th>AGE</th>\n      <th>TEMP</th>\n      <th>HEADCH</th>\n      <th>BLEED</th>\n      <th>DIARR</th>\n      <th>JAUN</th>\n      <th>VOMIT</th>\n      <th>PABD</th>\n      <th>WEAK</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>106.000000</td>\n      <td>106.000000</td>\n      <td>106.000000</td>\n      <td>106.000000</td>\n      <td>106.000000</td>\n      <td>106.000000</td>\n      <td>106.000000</td>\n      <td>106.0</td>\n      <td>106.000000</td>\n      <td>106.000000</td>\n      <td>106.000000</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>0.764151</td>\n      <td>25.720411</td>\n      <td>34.102170</td>\n      <td>37.256604</td>\n      <td>0.603774</td>\n      <td>0.066038</td>\n      <td>0.405660</td>\n      <td>0.0</td>\n      <td>0.207547</td>\n      <td>0.273585</td>\n      <td>0.500000</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>0.426545</td>\n      <td>5.869164</td>\n      <td>17.382844</td>\n      <td>1.030767</td>\n      <td>0.491436</td>\n      <td>0.249528</td>\n      <td>0.493352</td>\n      <td>0.0</td>\n      <td>0.407477</td>\n      <td>0.447916</td>\n      <td>0.502375</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>0.000000</td>\n      <td>12.100000</td>\n      <td>0.830000</td>\n      <td>36.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>1.000000</td>\n      <td>22.149857</td>\n      <td>22.000000</td>\n      <td>36.300000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>1.000000</td>\n      <td>25.236301</td>\n      <td>35.500000</td>\n      <td>37.250000</td>\n      <td>1.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.500000</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>1.000000</td>\n      <td>28.680924</td>\n      <td>45.000000</td>\n      <td>38.225000</td>\n      <td>1.000000</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n      <td>0.0</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>1.000000</td>\n      <td>39.799999</td>\n      <td>80.000000</td>\n      <td>39.900000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>0.0</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf_raw_cat = df_raw.copy()\n\ncat_vars = ['OUT', 'HEADCH', 'BLEED', 'DIARR', 'JAUN', 'VOMIT',\n       'PABD', 'WEAK']\nfor var in cat_vars:\n    df_raw_cat[var] = df_raw_cat[var].astype('category')\ndf_raw_cat.dtypes\n\n```\n\n\n\n\n    OUT       category\n    CT         float64\n    AGE        float64\n    TEMP       float64\n    HEADCH    category\n    BLEED     category\n    DIARR     category\n    JAUN      category\n    VOMIT     category\n    PABD      category\n    WEAK      category\n    dtype: object\n\n\n\n\n```python\ndf_raw_cat.describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>CT</th>\n      <th>AGE</th>\n      <th>TEMP</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>106.000000</td>\n      <td>106.000000</td>\n      <td>106.000000</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>25.720411</td>\n      <td>34.102170</td>\n      <td>37.256604</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>5.869164</td>\n      <td>17.382844</td>\n      <td>1.030767</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>12.100000</td>\n      <td>0.830000</td>\n      <td>36.000000</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>22.149857</td>\n      <td>22.000000</td>\n      <td>36.300000</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>25.236301</td>\n      <td>35.500000</td>\n      <td>37.250000</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>28.680924</td>\n      <td>45.000000</td>\n      <td>38.225000</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>39.799999</td>\n      <td>80.000000</td>\n      <td>39.900000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# Describe categorical data\ndf_proc_cat = df_raw_cat.select_dtypes(include=['category']).copy()\ndf_proc_cat.describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>OUT</th>\n      <th>HEADCH</th>\n      <th>BLEED</th>\n      <th>DIARR</th>\n      <th>JAUN</th>\n      <th>VOMIT</th>\n      <th>PABD</th>\n      <th>WEAK</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>106</td>\n      <td>106</td>\n      <td>106</td>\n      <td>106</td>\n      <td>106</td>\n      <td>106</td>\n      <td>106</td>\n      <td>106</td>\n    </tr>\n    <tr>\n      <th>unique</th>\n      <td>2</td>\n      <td>2</td>\n      <td>2</td>\n      <td>2</td>\n      <td>1</td>\n      <td>2</td>\n      <td>2</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>top</th>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>freq</th>\n      <td>81</td>\n      <td>64</td>\n      <td>99</td>\n      <td>63</td>\n      <td>106</td>\n      <td>84</td>\n      <td>77</td>\n      <td>53</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ncat_vars = cat_vars[1:]\n\nfor i, col_val in enumerate(cat_vars):\n    sns.catplot(x = col_val, y = None, hue= None, col=\"OUT\",\n                data=df_proc_cat, kind=\"count\",\n                height=3, aspect=2);\n\n```\n\n**Algunas observaciones sobre los datos**\n\n- El case fatality rate (OUT) de nuestra base de datos se sit\u00faa en 76 por ciento. Es decir, del total de pacientes con \u00e9bola, 81 murieron.\n\n- Para este conjunto de datos la variable `JAUN` no tiene variabilidad, por lo tanto no es una variable, y se omite.\n\n\nDado lo anterior, se ajusta el set de datos:\n\n- Se crean 3 grupos de edades, utilizando el percetil 25 (22 a\u00f1os), percentil 50 (36 a\u00f1os) y percentil 75 (45 a\u00f1os).\n\n- Se elimina la columna `JAUN`.\n\n## Transformaciones al conjunto de datos\n\n\n```python\n# ajustes en df_raw \ndf_proc = df_raw\ndf_proc['INTER_AGE'] = \"NA\"\n\ndf_proc.dtypes\n```\n\n\n\n\n    OUT            int64\n    CT           float64\n    AGE          float64\n    TEMP         float64\n    HEADCH         int64\n    BLEED          int64\n    DIARR          int64\n    JAUN           int64\n    VOMIT          int64\n    PABD           int64\n    WEAK           int64\n    INTER_AGE     object\n    dtype: object\n\n\n\n\n```python\n# ajustes en df_raw \ndf_proc = df_raw\n\n# para la variable edad se crean cuatro categor\u00edas\nage_p25 = math.ceil(df_proc['AGE'].quantile(.25))\nage_p50 = math.ceil(df_proc['AGE'].quantile(.50))\nage_p75 = math.ceil(df_proc['AGE'].quantile(.75))\n\ndf_proc['INTER_AGE'] = \"NA\"\ndf_proc.loc[(df_proc['AGE'] <= age_p25), 'INTER_AGE'] = 1\ndf_proc.loc[(df_proc['AGE'] > age_p25) & (df_proc['AGE'] <= age_p50), 'INTER_AGE'] = 2\ndf_proc.loc[(df_proc['AGE'] > age_p50) & (df_proc['AGE'] <= age_p75), 'INTER_AGE'] = 3\ndf_proc.loc[(df_proc['AGE'] > age_p75), 'INTER_AGE'] = 4\n\n## one hot encoding\nenc = OneHotEncoder(handle_unknown='ignore')\nenc_df = pd.DataFrame(enc.fit_transform(df_proc[['INTER_AGE']]).toarray())\nenc_df = enc_df.rename(columns={0: f\"hasta{age_p25}\", 1: f\"entre{age_p25+1}y{age_p50}\", 2: f\"entre{age_p50+1}y{age_p75}\", 3:f\"mayor{age_p75}\"})\n# merge with main df bridge_df on key values\ndf_proc = df_proc.join(enc_df)\n\n# se asignan como categoricas a las binarias, incluido el output\n#bin_vars = ['OUT', 'HEADCH', 'BLEED', 'DIARR', 'JAUN', 'VOMIT',\n#       'PABD', 'WEAK', 'INTER_AGE', f\"hasta{age_p25}\", f\"entre{age_p25+1}y{age_p50}\", f\"entre{age_p50+1}y{age_p75}\", f\"mayor{age_p75}\"]\n\n#esta asignacion hace que genera problemas al evaluar el sigmoide\n#for var in bin_vars:\n#    df_proc[var] = df_proc[var].astype('category')\n    \n# se omiten las variables JAUN, AGE, INTER_AGE\ndel_vars = [\"JAUN\", \"AGE\", \"INTER_AGE\"]\nfor var in del_vars:\n    df_proc = df_proc.drop(var, axis=1)    \n    \n# se comprueban los tipos de variable\ndf_proc.dtypes\n```\n\n\n\n\n    OUT             int64\n    CT            float64\n    TEMP          float64\n    HEADCH          int64\n    BLEED           int64\n    DIARR           int64\n    VOMIT           int64\n    PABD            int64\n    WEAK            int64\n    hasta22       float64\n    entre23y36    float64\n    entre37y45    float64\n    mayor45       float64\n    dtype: object\n\n\n\n\n```python\ndf_proc\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>OUT</th>\n      <th>CT</th>\n      <th>TEMP</th>\n      <th>HEADCH</th>\n      <th>BLEED</th>\n      <th>DIARR</th>\n      <th>VOMIT</th>\n      <th>PABD</th>\n      <th>WEAK</th>\n      <th>hasta22</th>\n      <th>entre23y36</th>\n      <th>entre37y45</th>\n      <th>mayor45</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>28.652450</td>\n      <td>36.3</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>25.736016</td>\n      <td>36.5</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1</td>\n      <td>20.747653</td>\n      <td>38.0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1</td>\n      <td>22.736993</td>\n      <td>38.6</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1</td>\n      <td>20.846284</td>\n      <td>38.4</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>101</th>\n      <td>1</td>\n      <td>24.191797</td>\n      <td>36.4</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>102</th>\n      <td>1</td>\n      <td>20.846284</td>\n      <td>38.4</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>103</th>\n      <td>0</td>\n      <td>38.816561</td>\n      <td>36.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>104</th>\n      <td>1</td>\n      <td>21.960294</td>\n      <td>36.4</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>105</th>\n      <td>0</td>\n      <td>26.221948</td>\n      <td>36.5</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>106 rows \u00d7 13 columns</p>\n</div>\n\n\n\n## Planteamiento del problema de regresi\u00f3n\n\nA continuaci\u00f3n se plantea el c\u00f3digo que computa las ecuaciones ([1](#mjx-eqn-eq1)), ([2](#mjx-eqn-eq1)) y ([4](#mjx-eqn-eq1)), planteadas inicialmente.\n\n\n```python\ndef sigmoide(z):\n    '''\n    \n    Funci\u00f3n que devuelve el sigmoide de un vector\n    \n        - Par\u00e1metros:\n        \n            -- z (vec): vector num\u00e9rico de m entradas\n        \n        - Salidas\n        \n            -- sig (vec): vector n\u00famerico de m entradas, cada entrada tiene \n        \n                         un valor entre -1 y 1\n    '''\n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    if type(z) is not np.ndarray:\n        sys.exit('Error: la entrada debe ser de tipo numpy.ndarray')\n        \n    sig = 1/(1+ np.exp(-z))\n    \n    return sig\n    \ndef calc_mu(X,beta):\n    '''\n    \n    Funci\u00f3n que calcula la media para una variable aleatoria con distribuci\u00f3n bernoulli.\n    \n        - Par\u00e1metros:\n        \n            -- X (mat): matriz de mxp entradas\n            \n            -- beta (vec): vector con p entradas\n            \n        - Salidas\n        \n            -- mu (vec): vector de m entradas\n    '''\n    a = np.matmul(beta,np.transpose(X))\n    mu = sigmoide(a)\n\n    return mu\n    \ndef f(X,y,beta):\n    '''\n    \n    Funci\u00f3n que computa la log-verosimilitud negativa\n    \n        - Par\u00e1metros:\n    \n            -- X (mat): matriz de mxp entradas\n\n            -- y (vec): vector de de m entradas de la variable output\n\n            -- beta (vec): vector de p entradas\n\n        - Salidas\n    \n            -- lvn (int): log-verosimilitud negativa\n    '''\n    \n    \n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    m,p = X.shape\n    if y.shape[0]!= m:\n        sys.exit('Error:  El n\u00famero de renglones de X debe ser igual al n\u00famero de entradas del vector y.')\n    if beta.shape[0]!= p:\n        sys.exit('Error:  El n\u00famero de columnas de X debe ser igual al n\u00famero de entradas del vector beta.')\n\n    prob = calc_mu(X,beta)\n    # Log-verosimilitud negativa \n    lvn = -sum(y*np.log(prob)+(1-y)*(np.log(1-prob)))\n    return lvn\n```\n\nReescribiendo la ecuaci\u00f3n de la funci\u00f3n de p\u00e9rdida ([4](#mjx-eqn-eq1)), tenemos:\n\n$$F(\\beta)=- \\sum_{i=1}^{m}[y_i log\\mu_i + (1-y_i)log(1-\\mu_i)]$$\n\nLas expresiones correspondientes al gradiente y a la matriz hessiana asociados a este problema, se plantean a continuaci\u00f3n:\n\n\\begin{align}\n\\nabla F(\\beta) & =\\frac{d}{d\\beta}F(\\beta)\\nonumber \\\\\n & =\\sum_{i}\\left(\\mu_{i}-y_{i}\\right)x_{i}\\nonumber \\\\\n & =\\boldsymbol{X}^{T}\\left(\\boldsymbol{\\mu}-\\boldsymbol{y}\\right)\\label{eq:gradient}\n\\end{align}\n\nPor otro lado, la ecuaci\u00f3n que describe la matrix Hessiana es la siguiente:\n\n\\begin{align}\n\\nabla^{2}F(\\beta) & =\\frac{d}{d\\beta}\\nabla F\\left(\\beta\\right)^{T}\\nonumber \\\\\n & =\\sum_{i}\\left(\\nabla_{\\beta}\\mu_{i}\\right)x_{i}^{T}\\nonumber \\\\\n & =\\sum_{i}\\mu_{i}\\left(1-\\mu_{i}\\right)x_{i}x_{i}^{T}\\nonumber \\\\\n & =\\boldsymbol{X^{T}SX}\\label{eq:hessian}\n\\end{align}\n\ndonde $\\boldsymbol{S}\\triangleq diag\\left(\\mu_{i}\\left(1-\\mu_{i}\\right)\\right)$.\nComo es resaltado por Murphy (2012), es definida positiva, lo que implica que ([4](#mjx-eqn-eq1)) es convexa\ny tiene un m\u00ednimo global.\n\n\n```python\ndef gradiente_f(X,y,beta):\n    '''\n    \n    Funci\u00f3n que calcula el gradiente asociado la log-verosimilitud negativa del \n    \n    problema de regresi\u00f3n log\u00edstica\n    \n        ** Par\u00e1metros:\n        \n            - X (mat): matriz de mxp entradas\n            \n            - y (vec): vector de de m entradas de la variable output\n            \n            - beta (vec): vector de p entradas\n        \n        ** Salidas\n        \n            - grad (vec): vector de m entradas\n    '''\n        \n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    m,p = X.shape\n    if y.shape[0]!= m:\n        sys.exit('Error:  El n\u00famero de renglones de X debe ser igual al n\u00famero de entradas del vector y.')\n    if beta.shape[0]!= p:\n        sys.exit('Error:  El n\u00famero de columnas de X debe ser igual al n\u00famero de entradas del vector beta.')\n\n    mu = calc_mu(X,beta)    \n    grad = np.matmul(np.transpose(X), mu-y)    \n    return grad\n\n\ndef hessiana_f(X,y,beta):\n    '''\n    \n    Funci\u00f3n que calcula la matriz Hessiana asociada a la log-verosimilitud negativa del \n    \n    problema de regresi\u00f3n log\u00edstica\n    \n        ** Par\u00e1metros:\n        \n            - X (mat): matriz de mxp entradas\n            \n            - y (vec): vector de de m entradas de la variable output\n            \n            - beta (vec): vector de p entradas\n        \n        ** Salidas\n        \n            - hes (vec): vector de m entradas\n    '''\n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    m,p = X.shape\n    if y.shape[0]!= m:\n        sys.exit('Error:  El n\u00famero de renglones de X debe ser igual al n\u00famero de entradas del vector y.')\n    if beta.shape[0]!= p:\n        sys.exit('Error:  El n\u00famero de columnas de X debe ser igual al n\u00famero de entradas del vector beta.')\n\n    mu = calc_mu(X,beta)\n    S = np.diag(mu*(1-mu))\n    hes = np.matmul(np.transpose(X),np.matmul(S,X))\n    return hes\n```\n\n\n```python\ndef normalize(x):\n    '''\n    \n    Funci\u00f3n que normaliza un vector\n    \n        ** Parametros:\n    \n            - x: vector a normalizar\n    \n        ** Salidas:\n    \n            - norm : vector x normalizado\n    '''\n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    if type(x) is not np.ndarray:\n        sys.exit('Error: la entrada debe ser de tipo numpy.ndarray')\n         \n    norm = x/np.sqrt(sum(x*x))\n    return norm\n```\n\n\n```python\ndef clasifica(X, beta_hat,limit=0.5):\n    '''\n    \n    Funci\u00f3n que clasifica la ocurrencia de probabilidades en dos grupos.\n    \n    Emplea el par\u00e1metro l\u00edmite para delimitar si se clasifica en el grupo 0 o 1.\n    \n        ** Par\u00e1metros:\n        \n            - X (mat): matriz de mxp entradas\n            \n            - beta_hat (array): optimized parameter\n            \n            - limit (float64): 0<limit<1: Threshold for each classification\n            \n        \n        ** Salidas:\n        \n            - yhat: array of classifed data\n    '''\n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    if type(X) is not np.ndarray or type (beta_hat) is not np.ndarray:\n        sys.exit('Error: X y beta_hat deben ser de tipo numpy.ndarray')\n    if limit > 1 or limit < 0:\n        sys.exit('Error:  limit es un param\u00e9tro que debe estar entre 0 y 1')       \n    \n    mu = calc_mu(X,beta_hat)\n    yhat = mu\n    yhat[mu<limit] = 0\n    yhat[mu>=limit] = 1\n    return yhat\n```\n\n\n```python\ndef descent_direction(X, y, beta, method=\"max\",H=None):\n    '''\n    \n    Funci\u00f3n que devuelve vector normalizado (px1) que apunta en la direccion de decenso\n    \n        ** Par\u00e1metros:\n        \n            - X (mat): matriz de mxp entradas\n\n            - y (vec): vector de de m entradas de la variable output\n\n            - beta (vec float64): vector de entradas a optimizar\n\n            - method (str): m\u00e9todo que determina la direcci\u00f3n de descenso\n    \n                    --Opciones:\n    \n                            --- max: m\u00e9todo de descenso\n                            \n                            --- newton: m\u00e9todo de Newton\n                            \n                            --- bfsg: metodo bfsg\n                            \n            - H (mat pxp): Par\u00e1metro para la direcci\u00f3n de decenso del metodo bfgs\n    \n        ** Salidas\n    \n            - pk (vec): vector normalizado con la direccion del paso\n    '''\n    if(method == \"max\"):\n        pk = gradiente_f(X,y,beta)\n    \n    elif(method == \"newton\"):\n        grad = gradiente_f(X,y,beta)\n        hess = hessiana_f(X,y,beta)\n        pk = np.linalg.solve(hess,grad)\n        \n    elif(method==\"bfsg\"):\n        # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n        if type(H) is not np.ndarray:\n            sys.exit('Error: H debe ser de tipo numpy.ndarray')\n        pk = np.matmul(H,gradiente_f(X,y,beta))\n                              \n    return - normalize(pk)\n\n```\n\n\n```python\ndef calc_H(X,y,beta,beta_new=None,H=None):\n    '''\n    \n    Funci\u00f3n que actualiza los valores de la matriz H del metodo bfgs para cada iteracion\n    \n        ** Parametros:\n        \n            - X (mat): matriz de mxp entradas\n\n            - y (vec): vector de de m entradas de la variable output\n        \n            - beta (array) - valor de cantidad a optimizar en la iteracion actual\n            \n            - beta_new (array)- valore de la cantidad a optimizar despues de la actualizacion\n            \n            - H (mat)- valor de la matriz H en la iteracion anterior\n        \n        \n        \n        ** Salidas:\n        \n            - H (mat): valor de la matriz para la siguiente iteracion       \n    '''\n    \n    w = gradiente_f(X,y,beta_new)- gradiente_f(X,y,beta)\n    z = beta_new-beta\n    Hz = np.matmul(H,z)\n    dotwz = np.dot(w,z)\n    dotzhz = np.dot(Hz,z)\n    H = H+(np.outer(w,w)/dotwz)-(np.outer(Hz,Hz)/dotzhz)\n   \n    return H\n```\n\n\n```python\ndef calc_lr(X, y, beta, lr, pk, c1=10**(-4), tao=0.5, reset_lr=False):\n    '''\n    \n    Funci\u00f3n que calcula el tama\u00f1o del paso para cada iteraci\u00f3n utilizando la condicion de armijo.\n    \n    La tasa de aprendizaje minima es la que tenia en el paso anterior.\n    \n        ** Par\u00e1metros:\n        \n            - X (mat): matriz de mxp entradas\n            \n            - y (vec): vector de de m entradas de la variable output\n            \n            - lr (float64): tasa de aprendizaje\n            \n            - pk (array px1 float64): direccion de decenso\n            \n            - c1 (float64) 0<c1<1: parametro de control\n            \n            - tao (float64) 0<tao<1: parametro de decrecimiento de lr\n            \n        ** Salidas\n        \n            - lr (float64): tama\u00f1o de paso\n    '''\n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad    \n    if tao > 1 or tao < 0:\n        sys.exit('Error:  tao es un par\u00e1metro que debe estar entre 0 y 1')  \n    if c1 > 1 or c1 < 0:\n        sys.exit('Error:  c1 es un param\u00e9tro que debe estar entre 0 y 1') \n\n    # Inicializamos \n    tao = 0.9\n    max_iter = 100\n    iter = 0\n    \n    # Inicializa lr\n    if reset_lr==True: lr = 1\n\n    # Evaluaciones peri\u00f3dicas\n    grad = gradiente_f(X,y,beta)\n    eval_f = f(X,y, beta)\n    \n    # Primera iteracion\n    f_x =  f(X,y, beta + lr*pk) #en nocedal es phi(alpha)\n    f_x1 = eval_f + c1 * lr *  np.dot(grad,pk) # en nocedal es l(alhpa)\n    \n    while ((f_x > f_x1) & (iter < max_iter)):\n        lr = lr*tao\n        f_x =  f(X,y, beta + lr*pk) \n        f_x1 = eval_f + c1 * lr *  np.dot(grad,pk) \n        iter+=1\n    \n    return lr\n```\n\n\n```python\n# prueba\n# prueba\n# No esta funcionando bien\n# Longitud de paso con condiciones completas de wolf\n\ndef calc_lr_wolf(X, y, beta, lr, pk, c1=10**(-4), c2=0.9, tao=0.5, reset_lr=False):\n    '''\n    \n    Funci\u00f3n que calcula el tama\u00f1o del paso para cada iteraci\u00f3n utilizando la condicion de armijo.\n    \n    La tasa de aprendizaje minima es la que ten\u00eda en el paso anterior.\n    \n        ** Par\u00e1metros:\n        \n            - X (mat): matriz de mxp entradas\n            \n            - y (vec): vector de de m entradas de la variable output\n            \n            - lr (float64): tasa de aprendizaje\n            \n            - pk (array px1 float64): direccion de decenso\n            \n            - c1 (float64) 0<c1<1: parametro de control\n            \n            - tao (float64) 0<tao<1: parametro de decrecimiento de lr\n        \n        \n        \n        ** Salidas\n        \n            - lr (float64): tama\u00f1o de paso\n    '''\n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    if tao > 1 or tao < 0:\n        sys.exit('Error:  tao es un par\u00e1metro que debe estar entre 0 y 1')  \n    if c1 > 1 or c1 < 0:\n        sys.exit('Error:  c1 es un param\u00e9tro que debe estar entre 0 y 1') \n    #if pk >= 0 :\n    #    sys.exit('Error: pk debe ser negativo')\n        \n    # Inicializamos \n    tao = 0.5\n    max_iter = 50\n    iter = 0\n    \n    # Inicializa lr\n    if reset_lr==True: lr=1\n\n    # Evalauciones periodicas\n    grad = gradiente_f(X,y,beta)\n    eval_f = f(X,y, beta)\n    \n    # Primera iteracion\n    f_x =  f(X,y, beta + lr*pk) #en nocedal es phi(alpha)\n    f_x1 = eval_f + c1 * lr *  np.dot(grad,pk) # en nocedal es l(alhpa)\n    \n    gf_x = np.dot(gradiente_f(X,y, beta+lr*pk) , pk)\n    gf_x1 = c2* np.dot(grad, pk)\n    \n    while ((f_x>f_x1) & (gf_x<gf_x1) & (iter<max_iter)):\n        lr =lr*tao\n        f_x =  f(X,y, beta + lr*pk) \n        f_x1 = eval_f + c1 * lr *  np.dot(grad,pk) \n        \n        gf_x = np.dot(gradiente_f(X,y, beta+lr*pk) , pk)\n        #gf_x1 = c2* np.dot(grad, pk)\n    \n        \n        iter+=1\n    \n    return lr\n```\n\n\n```python\ndef gradient_descent(X, y, lr=1, tol=10**(-7), max_iter=10**5, method=\"max\", reset_lr=False, verbose_n=1000):\n    '''\n    \n    Funci\u00f3n que devuelve vector de par\u00e1metros beta (px1) resultante del proceso\n    \n    de optimizaci\u00f3n por descenso de gradiente\n    \n        ** Par\u00e1metros:\n        \n            - X (mat): matriz de mxp entradas\n            \n            - y (vec): vector de de m entradas de la variable output\n            \n            - lr (float64): valor inicial de la tasa de aprendizaje\n            \n            - tol (float64): criterio de convergencia\n            \n            - max_iter (int): n\u00famero m\u00e1ximo de iteraciones\n            \n            - method (str): m\u00e9todo que determina la direcci\u00f3n de descenso\n            \n                Opciones:\n                \n                    -- max: m\u00e9todo de descenso\n                    \n                    -- newton: m\u00e9todo de Newton\n                    \n                    -- bfsg\n        \n        ** Salidas\n        \n            - beta_new (vec): vector de p entradas con par\u00e1metros que minimizan la funci\u00f3n de p\u00e9rdida\n    '''\n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    m,p = X.shape\n    if y.shape[0]!= m:\n        sys.exit('Error:  El n\u00famero de renglones de X debe ser igual al n\u00famero de entradas del vector y.')\n\n    \n    # Inicializa\n    iteraciones=0\n    H = None\n    dims = X.shape[1]\n    tol = tol*dims\n    \n    # Inicializamos beta aleatoria\n    beta = np.random.normal(1,3,dims)\n    if method ==\"bfsg\": H = np.identity(dims)\n    \n    # Primera iteracion\n    pk =  descent_direction(X, y, beta, method,H)\n    beta_new = beta + lr*pk\n    if method == \"bfsg\": H=calc_H(X,y,beta,beta_new,H) \n    \n    # Condici\u00f3n de paro.\n    while ((np.linalg.norm(gradiente_f(X,y,beta_new)) > tol) & (iteraciones < max_iter)):\n        iteraciones+=1 #contador de ciclo\n        \n        beta = beta_new\n        pk =  descent_direction(X,y,beta,method,H)\n        lr = calc_lr(X, y, beta, lr, pk, reset_lr = reset_lr)\n        \n        beta_new = beta + lr*pk\n        \n        if method == \"bfsg\": H=calc_H(X,y,beta,beta_new,H)\n            \n        # Imprime\n\n        if iteraciones % verbose_n == 0:\n            print(\"************************************************************************\")\n            grad=np.linalg.norm(gradiente_f(X,y,beta_new))\n            print(f'GRADIENTE: {grad:.7E}, LEARNING RATE: {lr:.4E}, N\u00ba ITERACIONES: {iteraciones}')\n            \n\n    print(\"*========================================================================*\")    \n    if iteraciones == max_iter:print(\"Alcanz\u00f3 el n\u00famero m\u00e1ximo de iteraciones\")\n\n    print(\"ITERACIONES: \",iteraciones)\n    print(\"GRADIENTE DE F: \",np.linalg.norm(gradiente_f(X,y,beta_new)))\n    print(\"*========================================================================*\")\n    \n    return beta_new\n```\n\n## Split and Train\n\n\n```python\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\n\ndata =df_proc.to_numpy()\ny = data[:,0]\nX = data[:,1:]\nx_train, x_test, y_train, y_test=train_test_split(X,y,test_size=.2)\n\n# Scale data\nscaler = MinMaxScaler()\nx_train = scaler.fit_transform(x_train)\nx_test = scaler.fit_transform(x_test)\n```\n\n\n```python\n\n%%time \n\nbeta_hat = gradient_descent(x_train,y_train,max_iter=10**6,reset_lr=False,verbose_n=100000)\nyhat = clasifica(x_test,beta_hat)\n\nprint(\"BETA_HAT: \", beta_hat)\nprint(\"ERROR DE CLASIFICACI\u00d3N: \",round(100*sum(abs(y_test-yhat))/len(yhat),2),\"%\")\nprint(\"*========================================================================*\")\n\n```\n\n    /Users/danielapintoveizaga/Library/Python/3.7/lib/python/site-packages/ipykernel_launcher.py:72: RuntimeWarning: divide by zero encountered in log\n    /Users/danielapintoveizaga/Library/Python/3.7/lib/python/site-packages/ipykernel_launcher.py:72: RuntimeWarning: invalid value encountered in multiply\n\n\n    *========================================================================*\n    ITERACIONES:  14972\n    GRADIENTE DE F:  1.1991469950207157e-06\n    *========================================================================*\n    BETA_HAT:  [-207.30981145  607.26475844  -77.35480567    0.66725438   25.50300541\n      120.11341839  -59.10582665   91.50642227   24.95644907   27.20024392\n       67.40971947   71.84324543]\n    ERROR DE CLASIFICACI\u00d3N:  13.64 %\n    *========================================================================*\n    CPU times: user 2.04 s, sys: 86.6 ms, total: 2.13 s\n    Wall time: 2.06 s\n\n\n\n```python\n%%time\n# M\u00e9todo de Newton\nbeta_hat = gradient_descent(x_train,y_train, method=\"newton\",max_iter = 10**5,verbose_n = 10)\nyhat = clasifica(x_test,beta_hat)\n\nprint(\"BETA_HAT: \", beta_hat)\nprint(\"ERROR DE CLASIFICACI\u00d3N: \",round(100*sum(abs(y_test-yhat))/len(yhat),2),\"%\")\nprint(\"*========================================================================*\")\n```\n\n    ************************************************************************\n    GRADIENTE: 2.2161580E+01, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 10\n    ************************************************************************\n    GRADIENTE: 5.7651872E+00, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 20\n    ************************************************************************\n    GRADIENTE: 1.9273256E+00, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 30\n    ************************************************************************\n    GRADIENTE: 9.7325156E-01, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 40\n    ************************************************************************\n    GRADIENTE: 5.8676466E-01, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 50\n    ************************************************************************\n    GRADIENTE: 4.0312244E-01, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 60\n    ************************************************************************\n    GRADIENTE: 2.9780635E-01, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 70\n    ************************************************************************\n    GRADIENTE: 2.2801381E-01, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 80\n    ************************************************************************\n    GRADIENTE: 1.7786662E-01, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 90\n    ************************************************************************\n    GRADIENTE: 1.4016474E-01, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 100\n    ************************************************************************\n    GRADIENTE: 1.1108688E-01, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 110\n    ************************************************************************\n    GRADIENTE: 8.8345234E-02, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 120\n    ************************************************************************\n    GRADIENTE: 7.0422575E-02, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 130\n    ************************************************************************\n    GRADIENTE: 5.6234722E-02, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 140\n    ************************************************************************\n    GRADIENTE: 4.4970875E-02, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 150\n    ************************************************************************\n    GRADIENTE: 3.6009336E-02, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 160\n    ************************************************************************\n    GRADIENTE: 2.8867028E-02, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 170\n    ************************************************************************\n    GRADIENTE: 2.3165848E-02, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 180\n    ************************************************************************\n    GRADIENTE: 1.8608596E-02, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 190\n    ************************************************************************\n    GRADIENTE: 1.4961011E-02, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 200\n    ************************************************************************\n    GRADIENTE: 1.2038038E-02, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 210\n    ************************************************************************\n    GRADIENTE: 9.6931989E-03, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 220\n    ************************************************************************\n    GRADIENTE: 7.8103161E-03, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 230\n    ************************************************************************\n    GRADIENTE: 6.2970619E-03, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 240\n    ************************************************************************\n    GRADIENTE: 5.0799194E-03, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 250\n    ************************************************************************\n    GRADIENTE: 4.1002474E-03, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 260\n    ************************************************************************\n    GRADIENTE: 3.3111969E-03, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 270\n    ************************************************************************\n    GRADIENTE: 2.6752900E-03, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 280\n    ************************************************************************\n    GRADIENTE: 2.1625102E-03, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 290\n    ************************************************************************\n    GRADIENTE: 1.7487931E-03, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 300\n    ************************************************************************\n    GRADIENTE: 1.4148287E-03, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 310\n    ************************************************************************\n    GRADIENTE: 1.1451100E-03, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 320\n    ************************************************************************\n    GRADIENTE: 9.2717489E-04, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 330\n    ************************************************************************\n    GRADIENTE: 7.5100122E-04, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 340\n    ************************************************************************\n    GRADIENTE: 6.0852432E-04, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 350\n    ************************************************************************\n    GRADIENTE: 4.9325050E-04, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 360\n    ************************************************************************\n    GRADIENTE: 3.9994813E-04, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 370\n    ************************************************************************\n    GRADIENTE: 3.2439995E-04, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 380\n    ************************************************************************\n    GRADIENTE: 2.6320462E-04, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 390\n    ************************************************************************\n    GRADIENTE: 2.1361744E-04, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 400\n    ************************************************************************\n    GRADIENTE: 1.7342249E-04, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 410\n    ************************************************************************\n    GRADIENTE: 1.4082989E-04, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 420\n    ************************************************************************\n    GRADIENTE: 1.1439326E-04, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 430\n    ************************************************************************\n    GRADIENTE: 9.2943229E-05, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 440\n    ************************************************************************\n    GRADIENTE: 7.5534020E-05, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 450\n    ************************************************************************\n    GRADIENTE: 6.1400359E-05, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 460\n    ************************************************************************\n    GRADIENTE: 4.9922784E-05, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 470\n    ************************************************************************\n    GRADIENTE: 4.0599675E-05, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 480\n    ************************************************************************\n    GRADIENTE: 3.3024679E-05, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 490\n    ************************************************************************\n    GRADIENTE: 2.6868508E-05, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 500\n    ************************************************************************\n    GRADIENTE: 2.1864228E-05, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 510\n    ************************************************************************\n    GRADIENTE: 1.7795379E-05, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 520\n    ************************************************************************\n    GRADIENTE: 1.4486381E-05, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 530\n    ************************************************************************\n    GRADIENTE: 1.1794764E-05, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 540\n    ************************************************************************\n    GRADIENTE: 9.6048940E-06, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 550\n    ************************************************************************\n    GRADIENTE: 7.8228915E-06, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 560\n    ************************************************************************\n    GRADIENTE: 6.3725164E-06, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 570\n    ************************************************************************\n    GRADIENTE: 5.1918385E-06, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 580\n    ************************************************************************\n    GRADIENTE: 4.2305389E-06, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 590\n    ************************************************************************\n    GRADIENTE: 3.4477229E-06, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 600\n    ************************************************************************\n    GRADIENTE: 2.8101472E-06, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 610\n    ************************************************************************\n    GRADIENTE: 2.2907826E-06, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 620\n    ************************************************************************\n    GRADIENTE: 1.8676471E-06, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 630\n    ************************************************************************\n    GRADIENTE: 1.5228602E-06, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 640\n    ************************************************************************\n    GRADIENTE: 1.2418744E-06, LEARNING RATE: 1.0000E+00, N\u00ba ITERACIONES: 650\n    *========================================================================*\n    ITERACIONES:  652\n    GRADIENTE DE F:  1.1922499579476228e-06\n    *========================================================================*\n    BETA_HAT:  [-191.47292429  562.44031196  -71.36867787  123.1299603    20.34578023\n      115.58259723  -55.47819992   84.83809904   23.16274978   25.55337006\n       65.80294491   69.46380373]\n    ERROR DE CLASIFICACI\u00d3N:  13.64 %\n    *========================================================================*\n    CPU times: user 165 ms, sys: 16.5 ms, total: 181 ms\n    Wall time: 176 ms\n\n\n    /Users/danielapintoveizaga/Library/Python/3.7/lib/python/site-packages/ipykernel_launcher.py:72: RuntimeWarning: divide by zero encountered in log\n    /Users/danielapintoveizaga/Library/Python/3.7/lib/python/site-packages/ipykernel_launcher.py:72: RuntimeWarning: invalid value encountered in multiply\n\n\n\n```python\n%%time\n# M\u00e9todo BFSG\n\nbeta_hat = gradient_descent(x_train,y_train, method = \"bfsg\",max_iter = 10**6,lr=1,verbose_n = 100000)\nyhat = clasifica(x_test,beta_hat)\n\nprint(\"BETA_HAT: \", beta_hat)\nprint(\"ERROR DE CLASIFICACI\u00d3N: \",round(100*sum(abs(y_test-yhat))/len(yhat),2),\"%\")\nprint(\"*========================================================================*\")\n```\n\n    /Users/danielapintoveizaga/Library/Python/3.7/lib/python/site-packages/ipykernel_launcher.py:72: RuntimeWarning: divide by zero encountered in log\n    /Users/danielapintoveizaga/Library/Python/3.7/lib/python/site-packages/ipykernel_launcher.py:72: RuntimeWarning: invalid value encountered in multiply\n\n\n    ************************************************************************\n    GRADIENTE: 6.7604013E-04, LEARNING RATE: 1.8530E-01, N\u00ba ITERACIONES: 100000\n    ************************************************************************\n    GRADIENTE: 1.8246751E-06, LEARNING RATE: 1.8530E-01, N\u00ba ITERACIONES: 200000\n    *========================================================================*\n    ITERACIONES:  207214\n    GRADIENTE DE F:  1.1997522410752398e-06\n    *========================================================================*\n    BETA_HAT:  [-1.92597509e+02  5.62066406e+02 -7.16006035e+01 -9.05363951e-02\n      2.33935569e+01  1.11631145e+02 -5.46857075e+01  8.48952910e+01\n      2.35974039e+01  2.56294180e+01  6.29470910e+01  6.70883012e+01]\n    ERROR DE CLASIFICACI\u00d3N:  13.64 %\n    *========================================================================*\n    CPU times: user 38.1 s, sys: 225 ms, total: 38.3 s\n    Wall time: 38.2 s\n\n\n## Descenso del gradiente estocastico\n\nCalculamos la funci\u00f3n de riesgo emp\u00edrico como la esperanza de la funcion de perdida evaluada sobre todos los puntos del dominio.\n\n$$L_{emp}=\\frac{1}{m} \\sum^{m}_{i=1} y_i log(\\mu_i) + (1-y_i) log(1-\\mu_i)$$  \n<br>\n$$ \\mu_i = (1+e^{-\\beta^T x_i})^{-1}= \\sigma(\\beta^T x_i)$$\n\nY el gradiente de la funci\u00f3n de riesgo esta dado por:\n\n$$\\nabla L=\\frac{dL}{d\\mu_i} =\\frac{1}{m} \\sum^{m}_{i=1} x_i(\\mu_i-y_i)$$\n\n\n```python\ndef riesgo_empirico(X,y,beta):\n    \n    '''\n    Funci\u00f3n que calcular el riesgo emp\u00edrico como la esperanza de la funci\u00f3n de p\u00e9rdida\n    \n    evaluada sobre todos los puntos del dominio.\n    \n        - Par\u00e1metros:\n        \n            -- X (mat): matriz de mxp entradas\n            \n            -- y (vec): vector de de m entradas de la variable output\n            \n            -- beta (vec): vector con p entradas\n\n        - Salidas\n            \n            -- loss (float64): riesgo emp\u00edrico\n    '''\n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    m,p = X.shape\n    if y.shape[0]!= m:\n        sys.exit('Error:  El n\u00famero de renglones de X debe ser igual al n\u00famero de entradas del vector y.')\n    if beta.shape[0]!= p:\n        sys.exit('Error:  El n\u00famero de columnas de X debe ser igual al n\u00famero de entradas del vector beta.')\n\n\n    mu=calc_mu(X,beta)\n    loss=-sum(y*np.log(mu)+(1-y)*np.log(1-mu))\n    return loss\n\ndef gradiente_riesgo_empirico(X,y,beta):\n    \n    '''\n    Funci\u00f3n que calcular el gradiente de la funci\u00f3n de riesgo.\n    \n        - Par\u00e1metros:\n        \n            -- X (mat): matriz de mxp entradas.\n            \n            -- y (vec): vector de de m entradas de la variable output.\n            \n            -- beta (vec): vector con p entradas.\n\n        - Salidas\n            \n            -- grad_riesgo_emp (vec): vector de p entradas\n    '''\n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    m,p = X.shape\n    if y.shape[0]!= m:\n        sys.exit('Error:  El n\u00famero de renglones de X debe ser igual al n\u00famero de entradas del vector y.')\n    if beta.shape[0]!= p:\n        sys.exit('Error:  El n\u00famero de columnas de X debe ser igual al n\u00famero de entradas del vector beta.')\n\n    m = X.shape[0]\n    mu = calc_mu(X,beta)\n    grad_riesgo_emp = np.matmul(np.transpose(X),mu-y)/m\n    return grad_riesgo_emp\n```\n\n\n```python\nimport random\ndef mini_lotes(X,y,q=3):\n    '''\n    \n    \n    \n    \n    \n    \n    '''\n    \n    cols = X.shape[1]\n    data = np.hstack((X,y[:,None]))\n    np.random.shuffle(data)\n    data = data[0:q]\n    X = data[:,0:cols]\n    y = data[:,cols]\n    return X,y\n\ndef batch(m,q=10):\n    \n    '''\n    \n    \n    \n    \n    '''\n    \n    \n    \n    index=np.random.randint(low=0,high=m,size=q)\n    return index\n\ndef error_train(X,y,beta):\n    prediction=clasifica(X,beta)\n    err=round(100*sum(abs(y-prediction))/len(prediction),2)\n    return err\n```\n\n\n```python\nbatch_size=10\n```\n\n\n```python\n\ndef SGD(X,y,batch_size,verbose_n=100,max_iter=10**5, q=10):\n    \n    '''\n    \n    \n    \n    '''\n\n     # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    m,p = X.shape\n    if y.shape[0]!= m:\n        sys.exit('Error:  El n\u00famero de renglones de X debe ser igual al n\u00famero de entradas del vector y.')\n\n\n    # Inicializa\n    m=X.shape[0]\n    epsilon = 10**(-6)\n    beta = np.random.normal(0,1,X.shape[1])    \n    step_size=.01\n    iteraciones = 0\n    epoca=0\n    ipe=int(m/q)#iteraciones por epoca\n    \n    # Primera iteracion\n    index=batch(m,batch_size)\n    x_lote=X[index,:]\n    y_lote = y[index]\n    beta_new = beta - step_size * gradiente_riesgo_empirico(x_lote,y_lote,beta) \n    \n\n    perdida=riesgo_empirico(X,y,beta)\n    error=error_train(X,y,beta)\n    \n    # while ((np.linalg.norm(gradiente_f(X,y,beta_new)) > epsilon) & (iteraciones < max_iter)):\n    # while abs(f(X,y,beta) - f(X,y,beta_new)) > epsilon:\n    while iteraciones<max_iter:\n        iteraciones +=1\n        #print(\"iteraciones1=\",iteraciones)\n        beta = beta_new\n        #x_lote,y_lote = mini_lotes(X,y,q)\n        index=batch(m,batch_size)\n        x_lote=X[index,:]\n        y_lote = y[index]\n        beta_new = beta - step_size * gradiente_riesgo_empirico(x_lote,y_lote,beta)\n        #print(\"iteraciones2=\",iteraciones)\n        if iteraciones%1000==0:\n            epoca+=1\n            loss=riesgo_empirico(X,y,beta)\n            perdida=np.append(perdida,loss)\n            err=error_train(X,y,beta)\n            error=np.append(error, error_train(x_test,y_test,beta_hat))\n            #print(f'loss:{loss:.4}, epoca:{epoca}, iter:{iteraciones}')\n        #print(\"iteraciones3=\",iteraciones)\n    print(\"N\u00ba DE INTERACIONES: \",iteraciones)\n    return beta_new,perdida,error\n```\n\n\n```python\nx=1\ny=[]\nfor y in range(1,7):\n    x=np.append(x,y)\nprint(x)\n```\n\n    [1 1 2 3 4 5 6]\n\n\n\n```python\ndef graf_loss_err(loss,error,title):\n    '''\n    \n    Funci\u00f3n para graficar la p\u00e9rdida o riesgo em\u00edrico y el error\n    \n    de entrenamiento en cada iterazaci\u00f3n.\n    \n        - Entradas:\n                    -- loss\n                    -- error\n                    ---title\n        \n        - Salidas:\n                    -- plot\n    \n    '''\n    \n    x=np.arange(0,len(error))\n    fig, axs = plt.subplots(2, 1)\n    axs[0].plot(x, error)\n    axs[0].set_xlabel('Iteraciones')\n    axs[0].set_ylabel('Train error %')\n    axs[0].grid(True)\n    \n    axs[1].plot(x, loss)\n    axs[1].set_xlabel('Iteraciones')\n    axs[1].set_ylabel('Perdida')\n    axs[1].grid(True)\n    axs[0].set_title(title, fontsize=14)\n    \n    fig.tight_layout()\n    plt.show()\n    \n#graf_loss_err(loss[0,20],error[0:20],\"Batch size\")\n```\n\n\n```python\n%%time\n\n# M\u00e9todo de SGD\nfor batch_size in range(1,10):\n    \n    \n    print(\"*========================================================================*\")\n    #print(\"Tama\u00f1o de minilote= \",batch_size)\n    beta_hat, loss, error = SGD(x_train, y_train, max_iter=10**5, batch_size=batch_size)\n    yhat = clasifica(x_test,beta_hat)\n    titulo=\"Batch size = \"+ str(batch_size)\n    graf_loss_err(loss,error,titulo)\n    #print(\"beta_hat=\", beta_hat)\n    #print(\"Error de clasificacion=\",round(100*sum(abs(y_test-yhat))/len(yhat),2),\"%\")\n    print(\"\\n\")\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "49f4e1c356fc480f4a05bac2a47af4e2f35971f8", "size": 283713, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/.ipynb_checkpoints/notebook_implementacion-checkpoint.ipynb", "max_stars_repo_name": "C1587S/MNO_numericalOptimization", "max_stars_repo_head_hexsha": "1d60d81b97bf7690ca1a7c1226fd1bcc82c5c049", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/.ipynb_checkpoints/notebook_implementacion-checkpoint.ipynb", "max_issues_repo_name": "C1587S/MNO_numericalOptimization", "max_issues_repo_head_hexsha": "1d60d81b97bf7690ca1a7c1226fd1bcc82c5c049", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2020-05-08T15:38:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-30T01:20:07.000Z", "max_forks_repo_path": "notebooks/.ipynb_checkpoints/notebook_implementacion-checkpoint.ipynb", "max_forks_repo_name": "C1587S/MNO_numericalOptimization", "max_forks_repo_head_hexsha": "1d60d81b97bf7690ca1a7c1226fd1bcc82c5c049", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-15T19:23:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T19:23:41.000Z", "avg_line_length": 107.2638941399, "max_line_length": 17232, "alphanum_fraction": 0.7871370011, "converted": true, "num_tokens": 18180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.08509904848750825, "lm_q1q2_score": 0.03890189963072331}}
{"text": "#### TELEPERFORMANCE (TP) - Prueba T\u00e9cnica - Cient\u00edfico de Datos  (Por: Andr\u00e9s Felipe Escall\u00f3n Portilla,  22-24 / Feb / 2021)\n\n\n# CASO DE CONSULTORIA \n\n###### **Requerimiento:**\n\nUna de las operaciones de cobranzas de la compa\u00f1\u00eda quiere generar estrategias diferenciadas para el proceso de gesti\u00f3n de recuperaci\u00f3n de cartera de clientes de acuerdo con el riesgo de no pago de la primera factura.\n\nLa estrategia se divide en 3 grupos de intervenci\u00f3n:\n\n1. Alto riesgo: Llamarlos al 5 d\u00eda de mora.\n2. Medio riesgo: Enviar mensaje de texto al 5 d\u00eda de mora.\n3. Bajo riesgo: Enviar mensaje de texto al d\u00eda 15 de mora.\n\nLos costos por cada tipo de contacto son los siguientes:\n\n- Llamada asesor de cobranza 1700 pesos\n- Mensaje de texto 40 pesos\n\n#### **Instrucciones**\n\n1. Muestre un an\u00e1lisis descriptivo y/o diagn\u00f3stico inicial de la informaci\u00f3n insumo para el modelo.\n2. Construya un modelo estad\u00edstico que calcule la probabilidad de que un cliente no pague la primera factura. Explique por qu\u00e9 escogi\u00f3 las variables con las que va a trabajar y si debi\u00f3 hacer modificaciones de estas.\n3. Defina los puntos de corte que determinen a que grupo de estrategia pertenece cada cliente.\n4. Describa el perfil de los clientes con un alto riesgo de no pago.\n5. \u00bfQu\u00e9 sugerencias har\u00eda usted al equipo de cobranzas de acuerdo con el an\u00e1lisis de la informaci\u00f3n del modelo?\n6. Explique el modelo y sustente su validez estad\u00edstica, as\u00ed como los puntos de corte, la cantidad de clientes que pertenecen a cada estrategia, los perfiles de riesgo y sus sugerencias y conclusiones.\n7. Adjunte la base de datos con la probabilidad de riesgo de cada cliente.\n\nTodos los puntos anteriores deben evidenciarse en un notebook de Python o un Markdown de R que se deben compartir a trav\u00e9s de GitHub.\n\n\n# Soluci\u00f3n del Caso:\r\nResponder\u00e9 a este caso en Espa\u00f1ol aclarando que lo ideal hubiese sido hacerlo en Ingl\u00e9s (algunos comentarios si est\u00e1n en Ingl\u00e9s).\n\n1. **Muestre un an\u00e1lisis descriptivo y/o diagn\u00f3stico inicial de la informaci\u00f3n insumo para el modelo:**\n\n#### An\u00e1lisis de Datos Exploratorio (EDA):\n\n\n```python\nfrom google.colab import drive\r\ndrive.mount('/content/drive')\n```\n\n    Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n\n\n\n```python\n!pip install -r '/content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt'\n```\n\n    Requirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 1)) (4.6.3)\n    Requirement already satisfied: boto3 in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 2)) (1.17.14)\n    Requirement already satisfied: branca in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 3)) (0.4.2)\n    Requirement already satisfied: folium in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 4)) (0.8.3)\n    Requirement already satisfied: geopandas in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 5)) (0.8.2)\n    Requirement already satisfied: graphviz in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 6)) (0.10.1)\n    Requirement already satisfied: ipython in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (5.5.0)\n    Requirement already satisfied: ipywidgets in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (7.6.3)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 9)) (3.2.2)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 10)) (1.19.5)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 11)) (1.1.5)\n    Requirement already satisfied: pillow in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 12)) (7.0.0)\n    Requirement already satisfied: pingouin in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 13)) (0.3.10)\n    Requirement already satisfied: pydotplus in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 14)) (2.0.2)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 15)) (2.23.0)\n    Requirement already satisfied: s3transfer in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 16)) (0.3.4)\n    Requirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 17)) (0.22.2.post1)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 18)) (1.4.1)\n    Requirement already satisfied: seaborn in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 19)) (0.11.1)\n    Requirement already satisfied: shapely in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 20)) (1.7.1)\n    Requirement already satisfied: statsmodels in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 21)) (0.10.2)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 22)) (1.1.1)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 23)) (4.41.1)\n    Requirement already satisfied: urllib3 in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 24)) (1.24.3)\n    Requirement already satisfied: wordcloud in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 25)) (1.5.0)\n    Requirement already satisfied: xlrd in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 26)) (1.1.0)\n    Requirement already satisfied: botocore<1.21.0,>=1.20.14 in /usr/local/lib/python3.7/dist-packages (from boto3->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 2)) (1.20.14)\n    Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in /usr/local/lib/python3.7/dist-packages (from boto3->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 2)) (0.10.0)\n    Requirement already satisfied: jinja2 in /usr/local/lib/python3.7/dist-packages (from branca->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 3)) (2.11.3)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from folium->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 4)) (1.15.0)\n    Requirement already satisfied: pyproj>=2.2.0 in /usr/local/lib/python3.7/dist-packages (from geopandas->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 5)) (3.0.0.post1)\n    Requirement already satisfied: fiona in /usr/local/lib/python3.7/dist-packages (from geopandas->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 5)) (1.8.18)\n    Requirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.7/dist-packages (from ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (0.8.1)\n    Requirement already satisfied: pexpect; sys_platform != \"win32\" in /usr/local/lib/python3.7/dist-packages (from ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (4.8.0)\n    Requirement already satisfied: pygments in /usr/local/lib/python3.7/dist-packages (from ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (2.6.1)\n    Requirement already satisfied: setuptools>=18.5 in /usr/local/lib/python3.7/dist-packages (from ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (53.0.0)\n    Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.7/dist-packages (from ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (1.0.18)\n    Requirement already satisfied: pickleshare in /usr/local/lib/python3.7/dist-packages (from ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (0.7.5)\n    Requirement already satisfied: traitlets>=4.2 in /usr/local/lib/python3.7/dist-packages (from ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (4.3.3)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.7/dist-packages (from ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (4.4.2)\n    Requirement already satisfied: jupyterlab-widgets>=1.0.0; python_version >= \"3.6\" in /usr/local/lib/python3.7/dist-packages (from ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (1.0.0)\n    Requirement already satisfied: nbformat>=4.2.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (5.1.2)\n    Requirement already satisfied: widgetsnbextension~=3.5.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (3.5.1)\n    Requirement already satisfied: ipykernel>=4.5.1 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (4.10.1)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 9)) (2.8.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 9)) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 9)) (1.3.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 9)) (2.4.7)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 11)) (2018.9)\n    Requirement already satisfied: outdated in /usr/local/lib/python3.7/dist-packages (from pingouin->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 13)) (0.2.0)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pingouin->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 13)) (0.8.8)\n    Requirement already satisfied: pandas-flavor>=0.1.2 in /usr/local/lib/python3.7/dist-packages (from pingouin->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 13)) (0.2.0)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 15)) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 15)) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 15)) (2020.12.5)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 17)) (1.0.1)\n    Requirement already satisfied: patsy>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from statsmodels->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 21)) (0.5.1)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 22)) (1.2.1)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2->branca->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 3)) (1.1.1)\n    Requirement already satisfied: cligj>=0.5 in /usr/local/lib/python3.7/dist-packages (from fiona->geopandas->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 5)) (0.7.1)\n    Requirement already satisfied: attrs>=17 in /usr/local/lib/python3.7/dist-packages (from fiona->geopandas->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 5)) (20.3.0)\n    Requirement already satisfied: click<8,>=4.0 in /usr/local/lib/python3.7/dist-packages (from fiona->geopandas->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 5)) (7.1.2)\n    Requirement already satisfied: click-plugins>=1.0 in /usr/local/lib/python3.7/dist-packages (from fiona->geopandas->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 5)) (1.1.1)\n    Requirement already satisfied: munch in /usr/local/lib/python3.7/dist-packages (from fiona->geopandas->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 5)) (2.5.0)\n    Requirement already satisfied: ptyprocess>=0.5 in /usr/local/lib/python3.7/dist-packages (from pexpect; sys_platform != \"win32\"->ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (0.7.0)\n    Requirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (0.2.5)\n    Requirement already satisfied: ipython-genutils in /usr/local/lib/python3.7/dist-packages (from traitlets>=4.2->ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (0.2.0)\n    Requirement already satisfied: jsonschema!=2.5.0,>=2.4 in /usr/local/lib/python3.7/dist-packages (from nbformat>=4.2.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (2.6.0)\n    Requirement already satisfied: jupyter-core in /usr/local/lib/python3.7/dist-packages (from nbformat>=4.2.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (4.7.1)\n    Requirement already satisfied: notebook>=4.4.1 in /usr/local/lib/python3.7/dist-packages (from widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (5.3.1)\n    Requirement already satisfied: tornado>=4.0 in /usr/local/lib/python3.7/dist-packages (from ipykernel>=4.5.1->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (5.1.1)\n    Requirement already satisfied: jupyter-client in /usr/local/lib/python3.7/dist-packages (from ipykernel>=4.5.1->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (5.3.5)\n    Requirement already satisfied: littleutils in /usr/local/lib/python3.7/dist-packages (from outdated->pingouin->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 13)) (0.2.2)\n    Requirement already satisfied: xarray in /usr/local/lib/python3.7/dist-packages (from pandas-flavor>=0.1.2->pingouin->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 13)) (0.15.1)\n    Requirement already satisfied: Send2Trash in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (1.5.0)\n    Requirement already satisfied: terminado>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (0.9.2)\n    Requirement already satisfied: nbconvert in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (5.6.1)\n    Requirement already satisfied: pyzmq>=13 in /usr/local/lib/python3.7/dist-packages (from jupyter-client->ipykernel>=4.5.1->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (22.0.3)\n    Requirement already satisfied: bleach in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (3.3.0)\n    Requirement already satisfied: testpath in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (0.4.4)\n    Requirement already satisfied: pandocfilters>=1.4.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (1.4.3)\n    Requirement already satisfied: entrypoints>=0.2.2 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (0.3)\n    Requirement already satisfied: defusedxml in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (0.6.0)\n    Requirement already satisfied: mistune<2,>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (0.8.4)\n    Requirement already satisfied: webencodings in /usr/local/lib/python3.7/dist-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (0.5.1)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (20.9)\n\n\n\n```python\n# Importing all the required packages\r\n\r\nimport pandas              as pd # The gold standard of Python data analysis, to create and manipulate tables of data\r\nimport numpy               as np # The Python module for processing arrays which/Pandas is based on\r\nimport seaborn             as sns; sns.set() # A package to make Matplotlib visualizations more aesthetic\r\nimport branca\r\nimport geopandas\r\n\r\nimport matplotlib.pyplot   as plt # The gold standard of Python data visualization, but can be complex to use\r\nfrom matplotlib import cm\r\nfrom matplotlib.colors import ListedColormap, LinearSegmentedColormap\r\nfrom matplotlib.patches import Patch\r\nfrom matplotlib.widgets import Slider, Button, RadioButtons\r\n\r\nimport statsmodels.api as sm\r\nimport statsmodels.formula.api as sfm\r\nfrom statsmodels.formula.api import ols\r\n\r\nimport scipy\r\nfrom scipy import stats\r\nfrom scipy import interp\r\nfrom scipy.optimize import fsolve\r\nfrom scipy.stats import chi2_contingency, ttest_ind, norm # A module for Python machine learning--we'll stick to T-Tests here\r\n\r\nimport sklearn\r\nfrom sklearn.metrics import roc_curve, auc\r\nfrom sklearn.model_selection import StratifiedKFold\r\nfrom sklearn.cluster import KMeans\r\nfrom sklearn.preprocessing import MinMaxScaler, MaxAbsScaler, RobustScaler, StandardScaler\r\nfrom sklearn.tree import export_graphviz\r\nfrom sklearn import tree\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.metrics import roc_curve, auc, accuracy_score\r\nfrom sklearn.model_selection import StratifiedKFold, train_test_split\r\nfrom statsmodels.formula.api import ols\r\n\r\nfrom IPython.display import display\r\nfrom IPython.display import display_html\r\nfrom IPython.display import Image, SVG\r\n\r\nimport folium # package for making maps, please make sure to use a version older than 1.0.0.\r\nfrom folium.plugins import TimeSliderChoropleth\r\n# from time_slider_choropleth import TimeSliderChoropleth\r\n\r\nimport json\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport os\r\nimport pydotplus\r\nfrom io import StringIO\r\nfrom sympy import var, plot_implicit, Eq\r\nfrom graphviz import Source\r\nfrom wordcloud import WordCloud # A package that will allow us to make a wordcloud\r\n\r\n# when executing, the plot will be done\r\n%matplotlib inline\r\nplt.style.use('ggplot')\r\nplt.rcParams[\"figure.figsize\"] = (8,5)\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\n# ignore log(0) and divide by 0 warning\r\nnp.seterr(divide='ignore');\n```\n\n\n```python\n#leyendo los archivos de la base de datos (guardados previamente como csv) y asign\u00e1ndolos a dataframes:\r\ndf_var=pd.read_csv('/content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/data/base_de_datos_prueba_tecnica_csv_vars.csv')\r\ndf=pd.read_csv('/content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/data/base_de_datos_prueba_tecnica_csv_db.csv')\n```\n\n\n```python\n#visualizando los dataframes:\n#Para una base de datos, las variables y su descripci\u00f3n es fundamental\ndf_var\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>VARIABLE</th>\n      <th>DESCRIPCI\u00d3N</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>REGIONAL</td>\n      <td>regional de instalaci\u00f3n del servicio</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>DEPARTAMENTO</td>\n      <td>Departamento de instalaci\u00f3n del servicio</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>TECNOL</td>\n      <td>Tipo de tecnolog\u00eda del servicio</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>GERENCIA</td>\n      <td>Gerencia de venta del servicio</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>CANAL_HOMOLOGADO_MILLICON</td>\n      <td>Canal de venta del servicio</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>tipo_fuerza_venta</td>\n      <td>Tipo de fuerza o equipo que realiz\u00f3 la venta</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>estrato</td>\n      <td>Estrato donde fue instalado el servicio</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>antiguedad_meses</td>\n      <td>Antig\u00fcedad del cliente al momento de solicitar...</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>productos</td>\n      <td>Productos solicitados TV= televisi\u00f3n, TO=Telef...</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>portafolio</td>\n      <td>cantidad de productos adquiridos</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>no_serv_tecnicos</td>\n      <td>Servicios t\u00e9cnicos solicitados en los \u00faltimos ...</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>fallo</td>\n      <td>Tipo de fallo por elq ue solicit\u00f3 el servicio ...</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>asesoria_factura</td>\n      <td>Si la variable asume el valor de 1 es que el c...</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>pedidos_peticiones</td>\n      <td>Si la variable asume el valor de 1 es que el c...</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>reagendamiento</td>\n      <td>Si la variable asume el valor de 1 es que el c...</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>asesoria_servicios</td>\n      <td>Si la variable asume el valor de 1 es que el c...</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>retencion</td>\n      <td>Si la variable asume el valor de 1 es que el c...</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>Otras</td>\n      <td>Si la variable asume el valor de 1 es que el c...</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>quejas_fraude</td>\n      <td>El cliente present\u00f3 una queja de posible fraud...</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>traslado</td>\n      <td>El cliente solicit\u00f3 un traslado del servicio</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>Incumplimiento_pago</td>\n      <td>Variable objetivo, el 1 indica que el cliente ...</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>cliente_id</td>\n      <td>Identificador del cliente</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n#visualizando la info completa de la DESCRIPCI\u00d3N:\ndescripcion=[]\nfor row in range(len(df_var)): \n    descripcion.append(df_var['DESCRIPCI\u00d3N'][row])\ndescripcion    \n```\n\n\n\n\n    ['regional de instalaci\u00f3n del servicio',\n     'Departamento de instalaci\u00f3n del servicio',\n     'Tipo de tecnolog\u00eda del servicio',\n     'Gerencia de venta del servicio',\n     'Canal de venta del servicio',\n     'Tipo de fuerza o equipo que realiz\u00f3 la venta',\n     'Estrato donde fue instalado el servicio',\n     'Antig\u00fcedad del cliente al momento de solicitar el servicio',\n     'Productos solicitados TV= televisi\u00f3n, TO=Telefon\u00eda, BA = Internet',\n     'cantidad de productos adquiridos',\n     'Servicios t\u00e9cnicos solicitados en los \u00faltimos 3 meses',\n     'Tipo de fallo por elq ue solicit\u00f3 el servicio t\u00e9cnico',\n     'Si la variable asume el valor de 1 es que el cliente llamo a pedir una asesor\u00eda en factura',\n     'Si la variable asume el valor de 1 es que el cliente llamo a hacer una petici\u00f3n queja o reclamo',\n     'Si la variable asume el valor de 1 es que el cliente llamo a reagendar un servicio',\n     'Si la variable asume el valor de 1 es que el cliente llamo a pedir una asesor\u00eda en el uso del servicio',\n     'Si la variable asume el valor de 1 es que el cliente llamo a cancelar voluntariamente el servicio',\n     'Si la variable asume el valor de 1 es que el cliente llamo por otros motivos',\n     'El cliente present\u00f3 una queja de posible fraude por suplantaci\u00f3n de identidad',\n     'El cliente solicit\u00f3 un traslado del servicio',\n     'Variable objetivo, el 1 indica que el cliente no pago la primera factura',\n     'Identificador del cliente']\n\n\n\n\n```python\n#Esta es la base de datos como tal con la cual se va a trabajar:\npd.options.display.max_columns = None # para visualizar todas las columnas (variables) de inter\u00e9s\ndf\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>REGIONAL</th>\n      <th>DEPARTAMENTO</th>\n      <th>TECNOL</th>\n      <th>GERENCIA</th>\n      <th>CANAL_HOMOLOGADO_MILLICON</th>\n      <th>tipo_fuerza_venta</th>\n      <th>estrato</th>\n      <th>antiguedad_meses</th>\n      <th>productos</th>\n      <th>portafolio</th>\n      <th>no_serv_tecnicos</th>\n      <th>fallo</th>\n      <th>asesoria_factura</th>\n      <th>pedidos_peticiones</th>\n      <th>reagendamiento</th>\n      <th>asesoria_servicios</th>\n      <th>retencion</th>\n      <th>Otras</th>\n      <th>quejas_fraude</th>\n      <th>traslado</th>\n      <th>Incumplimiento_pago</th>\n      <th>cliente_id</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>COSTA</td>\n      <td>MAGDALENA</td>\n      <td>HFC</td>\n      <td>CONTACT</td>\n      <td>SAC</td>\n      <td>INDIRECTA</td>\n      <td>3</td>\n      <td>19.0</td>\n      <td>TV+BA</td>\n      <td>Duo</td>\n      <td>1.0</td>\n      <td>No funciona l\u00ednea telef\u00f3nica</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1004369760</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>COSTA</td>\n      <td>MAGDALENA</td>\n      <td>HFC</td>\n      <td>CONTACT</td>\n      <td>SAC</td>\n      <td>INDIRECTA</td>\n      <td>3</td>\n      <td>19.0</td>\n      <td>TV+BA</td>\n      <td>Duo</td>\n      <td>1.0</td>\n      <td>No funciona l\u00ednea telef\u00f3nica</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1004369760</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>NOROCCIDENTE</td>\n      <td>ANTIOQUIA</td>\n      <td>HFC</td>\n      <td>CONTACT</td>\n      <td>SAC</td>\n      <td>INDIRECTA</td>\n      <td>1</td>\n      <td>1.0</td>\n      <td>TV</td>\n      <td>Individual</td>\n      <td>1.0</td>\n      <td>No navega</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1004371304</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>COSTA</td>\n      <td>MAGDALENA</td>\n      <td>HFC</td>\n      <td>CONTACT</td>\n      <td>IN BOUND</td>\n      <td>INDIRECTA</td>\n      <td>3</td>\n      <td>7.0</td>\n      <td>TO+TV+BA</td>\n      <td>Trio</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1004382867</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>COSTA</td>\n      <td>MAGDALENA</td>\n      <td>HFC</td>\n      <td>CONTACT</td>\n      <td>IN BOUND</td>\n      <td>INDIRECTA</td>\n      <td>3</td>\n      <td>7.0</td>\n      <td>TO+TV+BA</td>\n      <td>Trio</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1004382867</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>19937</th>\n      <td>NOROCCIDENTE</td>\n      <td>ANTIOQUIA</td>\n      <td>REDCO</td>\n      <td>CONTACT</td>\n      <td>IN BOUND</td>\n      <td>INDIRECTA</td>\n      <td>2</td>\n      <td>NaN</td>\n      <td>TO+BA</td>\n      <td>Duo</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>98589757</td>\n    </tr>\n    <tr>\n      <th>19938</th>\n      <td>NOROCCIDENTE</td>\n      <td>ANTIOQUIA</td>\n      <td>REDCO</td>\n      <td>CONTACT</td>\n      <td>IN BOUND</td>\n      <td>INDIRECTA</td>\n      <td>2</td>\n      <td>NaN</td>\n      <td>TO+BA</td>\n      <td>Duo</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>98589757</td>\n    </tr>\n    <tr>\n      <th>19939</th>\n      <td>NOROCCIDENTE</td>\n      <td>ANTIOQUIA</td>\n      <td>REDCO</td>\n      <td>TIENDAS</td>\n      <td>TIENDAS</td>\n      <td>INDIRECTA</td>\n      <td>2</td>\n      <td>89.0</td>\n      <td>BA</td>\n      <td>Individual</td>\n      <td>1.0</td>\n      <td>Sin se\u00f1al</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>98590638</td>\n    </tr>\n    <tr>\n      <th>19940</th>\n      <td>NOROCCIDENTE</td>\n      <td>ANTIOQUIA</td>\n      <td>HFC</td>\n      <td>CONTACT</td>\n      <td>SAC</td>\n      <td>INDIRECTA</td>\n      <td>2</td>\n      <td>36.0</td>\n      <td>TV</td>\n      <td>Individual</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>98591843</td>\n    </tr>\n    <tr>\n      <th>19941</th>\n      <td>NOROCCIDENTE</td>\n      <td>ANTIOQUIA</td>\n      <td>REDCO</td>\n      <td>CONTACT</td>\n      <td>OUT BOUND</td>\n      <td>INDIRECTA</td>\n      <td>2</td>\n      <td>203.0</td>\n      <td>TV</td>\n      <td>Individual</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>98594003</td>\n    </tr>\n  </tbody>\n</table>\n<p>19942 rows \u00d7 22 columns</p>\n</div>\n\n\n\n\n```python\n#Panorama general de los datos:\ndf.shape # (num_filas, num_cols)\n```\n\n\n\n\n    (19942, 22)\n\n\n\n\n```python\nlist(df.columns)\n```\n\n\n\n\n    ['REGIONAL',\n     'DEPARTAMENTO',\n     'TECNOL',\n     'GERENCIA',\n     'CANAL_HOMOLOGADO_MILLICON',\n     'tipo_fuerza_venta',\n     'estrato',\n     'antiguedad_meses',\n     'productos',\n     'portafolio',\n     'no_serv_tecnicos',\n     'fallo',\n     'asesoria_factura',\n     'pedidos_peticiones',\n     'reagendamiento',\n     'asesoria_servicios',\n     'retencion',\n     'Otras',\n     'quejas_fraude',\n     'traslado',\n     'Incumplimiento_pago',\n     'cliente_id']\n\n\n\n\u00a1Efectivamente son 22 columnas (variables) que ya se han mostrado anteriormente con su descripci\u00f3n, recordando que la **Variable objetivo** es `Incumplimiento_pago` (donde el 1 indica que el cliente no pago la primera factura)!\n\n\n```python\n# Data types and amount of no-null values in dataset\ndf.info()\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 19942 entries, 0 to 19941\n    Data columns (total 22 columns):\n     #   Column                     Non-Null Count  Dtype  \n    ---  ------                     --------------  -----  \n     0   REGIONAL                   19942 non-null  object \n     1   DEPARTAMENTO               19942 non-null  object \n     2   TECNOL                     19942 non-null  object \n     3   GERENCIA                   19942 non-null  object \n     4   CANAL_HOMOLOGADO_MILLICON  19942 non-null  object \n     5   tipo_fuerza_venta          19942 non-null  object \n     6   estrato                    19942 non-null  object \n     7   antiguedad_meses           18264 non-null  float64\n     8   productos                  19942 non-null  object \n     9   portafolio                 19942 non-null  object \n     10  no_serv_tecnicos           6909 non-null   float64\n     11  fallo                      6909 non-null   object \n     12  asesoria_factura           19942 non-null  int64  \n     13  pedidos_peticiones         19942 non-null  int64  \n     14  reagendamiento             19942 non-null  int64  \n     15  asesoria_servicios         19942 non-null  int64  \n     16  retencion                  19942 non-null  int64  \n     17  Otras                      19942 non-null  int64  \n     18  quejas_fraude              19942 non-null  int64  \n     19  traslado                   19942 non-null  int64  \n     20  Incumplimiento_pago        19942 non-null  int64  \n     21  cliente_id                 19942 non-null  int64  \n    dtypes: float64(2), int64(10), object(10)\n    memory usage: 3.3+ MB\n\n\nLos registros de las variables numericas como `antiguedad_meses` y `no_serv_tecnicos` que no tienen informaci\u00f3n deben ser reemplazados por NaN\r\n\r\n**(The most prudent option which will not alter subsequent summary statistics calculations and not skew the distribution of the non-missing data would be to replace all missing values with a standard NaN)**\r\n\r\nSin embargo, los registros sin informaci\u00f3n de la variable categ\u00f3rica `fallo` pueden reemplazarse por SE (\"Sin Especificar\"), similarmente a como lo tiene ya establecido la variable categ\u00f3rica `estrato`\n\n\n```python\n# Another way to see null values per column\ndf.isnull().sum()\n```\n\n\n\n\n    REGIONAL                         0\n    DEPARTAMENTO                     0\n    TECNOL                           0\n    GERENCIA                         0\n    CANAL_HOMOLOGADO_MILLICON        0\n    tipo_fuerza_venta                0\n    estrato                          0\n    antiguedad_meses              1678\n    productos                        0\n    portafolio                       0\n    no_serv_tecnicos             13033\n    fallo                        13033\n    asesoria_factura                 0\n    pedidos_peticiones               0\n    reagendamiento                   0\n    asesoria_servicios               0\n    retencion                        0\n    Otras                            0\n    quejas_fraude                    0\n    traslado                         0\n    Incumplimiento_pago              0\n    cliente_id                       0\n    dtype: int64\n\n\n\n\n```python\n#\u00a0Information about numerical columns (descriptive statistics)\ndf.describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>antiguedad_meses</th>\n      <th>no_serv_tecnicos</th>\n      <th>asesoria_factura</th>\n      <th>pedidos_peticiones</th>\n      <th>reagendamiento</th>\n      <th>asesoria_servicios</th>\n      <th>retencion</th>\n      <th>Otras</th>\n      <th>quejas_fraude</th>\n      <th>traslado</th>\n      <th>Incumplimiento_pago</th>\n      <th>cliente_id</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>18264.000000</td>\n      <td>6909.0</td>\n      <td>19942.000000</td>\n      <td>19942.00000</td>\n      <td>19942.000000</td>\n      <td>19942.000000</td>\n      <td>19942.000000</td>\n      <td>19942.000000</td>\n      <td>19942.000000</td>\n      <td>19942.000000</td>\n      <td>19942.000000</td>\n      <td>1.994200e+04</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>43.136060</td>\n      <td>1.0</td>\n      <td>0.056564</td>\n      <td>0.05185</td>\n      <td>0.022515</td>\n      <td>0.025975</td>\n      <td>0.013690</td>\n      <td>0.006168</td>\n      <td>0.025524</td>\n      <td>0.048240</td>\n      <td>0.143165</td>\n      <td>4.124402e+08</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>60.379264</td>\n      <td>0.0</td>\n      <td>0.231013</td>\n      <td>0.22173</td>\n      <td>0.148356</td>\n      <td>0.159066</td>\n      <td>0.116202</td>\n      <td>0.078295</td>\n      <td>0.157714</td>\n      <td>0.214278</td>\n      <td>0.350250</td>\n      <td>4.993182e+08</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>0.000000</td>\n      <td>1.0</td>\n      <td>0.000000</td>\n      <td>0.00000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>3.978700e+04</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>4.000000</td>\n      <td>1.0</td>\n      <td>0.000000</td>\n      <td>0.00000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>3.225958e+07</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>16.000000</td>\n      <td>1.0</td>\n      <td>0.000000</td>\n      <td>0.00000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>6.697511e+07</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>52.000000</td>\n      <td>1.0</td>\n      <td>0.000000</td>\n      <td>0.00000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1.036623e+09</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>337.000000</td>\n      <td>1.0</td>\n      <td>1.000000</td>\n      <td>1.00000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>8.160082e+09</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nDe la anterior tabla se concluye que **aproximadamente el 14% (exactamnente 14.3165%)** de los clientes (**aprox 2855 de 19942 clientes en total**) est\u00e1 incumpliendo el pago (no ha pagado la primera factura)\n\n\n```python\n0.143165*19942\n```\n\n\n\n\n    2854.9964299999997\n\n\n\n\n```python\n# Information about categorical columns\ndf.describe(include = ['O'])\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>REGIONAL</th>\n      <th>DEPARTAMENTO</th>\n      <th>TECNOL</th>\n      <th>GERENCIA</th>\n      <th>CANAL_HOMOLOGADO_MILLICON</th>\n      <th>tipo_fuerza_venta</th>\n      <th>estrato</th>\n      <th>productos</th>\n      <th>portafolio</th>\n      <th>fallo</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>19942</td>\n      <td>19942</td>\n      <td>19942</td>\n      <td>19942</td>\n      <td>19942</td>\n      <td>19942</td>\n      <td>19942</td>\n      <td>19942</td>\n      <td>19942</td>\n      <td>6909</td>\n    </tr>\n    <tr>\n      <th>unique</th>\n      <td>6</td>\n      <td>22</td>\n      <td>4</td>\n      <td>6</td>\n      <td>11</td>\n      <td>2</td>\n      <td>7</td>\n      <td>7</td>\n      <td>3</td>\n      <td>20</td>\n    </tr>\n    <tr>\n      <th>top</th>\n      <td>NOROCCIDENTE</td>\n      <td>ANTIOQUIA</td>\n      <td>HFC</td>\n      <td>CONTACT</td>\n      <td>SAC</td>\n      <td>INDIRECTA</td>\n      <td>2</td>\n      <td>TO+TV+BA</td>\n      <td>Trio</td>\n      <td>No navega</td>\n    </tr>\n    <tr>\n      <th>freq</th>\n      <td>11640</td>\n      <td>11655</td>\n      <td>15628</td>\n      <td>10075</td>\n      <td>4768</td>\n      <td>18893</td>\n      <td>6413</td>\n      <td>7933</td>\n      <td>7933</td>\n      <td>2845</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf['fallo'].value_counts() #SE= Sin Especificar\n```\n\n\n\n\n    No navega                         2845\n    Sin se\u00f1al                         1307\n    Servicio intermitente             1238\n    No funciona l\u00ednea telef\u00f3nica       573\n    Mala calidad en la imagen          206\n    Navegacion Lenta                   184\n    Problemas Control Remoto           160\n    Falla Masiva                        76\n    L\u00ednea con ruido                     70\n    Problemas wifi                      67\n    Solicitud configuracion tecni       63\n    Fallas en audio/subtitulos          30\n    Problemas paquetes adicionales      23\n    No salen llamadas a X destino       20\n    Problemas con el portal             16\n    Problemas Servicios Especiales       9\n    Ingresa llamada de otra l\u00ednea        9\n    Mala calidad en la voz               5\n    Problemas de correo remoto           5\n    Retenci\u00f3n Clientes                   3\n    Name: fallo, dtype: int64\n\n\n\nEl fallo reportado mas com\u00fan es \"No navega\".\n\n\n```python\n#Contemos por ejemplo los fallos asociados a un tipo de tecnolog\u00eda por departamento:\r\ndf.groupby([\"TECNOL\",\"fallo\",\"DEPARTAMENTO\"])[\"DEPARTAMENTO\"].count().reset_index(name=\"count\").sort_values(by=\"count\", ascending = False).reset_index(drop=True)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>TECNOL</th>\n      <th>fallo</th>\n      <th>DEPARTAMENTO</th>\n      <th>count</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>HFC</td>\n      <td>No navega</td>\n      <td>ANTIOQUIA</td>\n      <td>1222</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>HFC</td>\n      <td>Sin se\u00f1al</td>\n      <td>ANTIOQUIA</td>\n      <td>694</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>REDCO</td>\n      <td>No navega</td>\n      <td>ANTIOQUIA</td>\n      <td>625</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>HFC</td>\n      <td>Servicio intermitente</td>\n      <td>ANTIOQUIA</td>\n      <td>569</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>HFC</td>\n      <td>No funciona l\u00ednea telef\u00f3nica</td>\n      <td>ANTIOQUIA</td>\n      <td>353</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>184</th>\n      <td>HFC</td>\n      <td>Problemas con el portal</td>\n      <td>SANTANDER</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>185</th>\n      <td>GPON</td>\n      <td>L\u00ednea con ruido</td>\n      <td>ANTIOQUIA</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>186</th>\n      <td>HFC</td>\n      <td>Problemas Control Remoto</td>\n      <td>ATLANTICO</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>187</th>\n      <td>GPON</td>\n      <td>Falla Masiva</td>\n      <td>ANTIOQUIA</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>188</th>\n      <td>REDCO</td>\n      <td>Mala calidad en la voz</td>\n      <td>ANTIOQUIA</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n<p>189 rows \u00d7 4 columns</p>\n</div>\n\n\n\n\n```python\n#Generemos una tabla de contingencia entre las variables categoricas DEPARTAMENTO y fallo (permite una visualizaci\u00f3n de la distribuci\u00f3n geogr\u00e1fica de los fallos):\r\npd.crosstab(df[\"DEPARTAMENTO\"],df[\"fallo\"])\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>fallo</th>\n      <th>Falla Masiva</th>\n      <th>Fallas en audio/subtitulos</th>\n      <th>Ingresa llamada de otra l\u00ednea</th>\n      <th>L\u00ednea con ruido</th>\n      <th>Mala calidad en la imagen</th>\n      <th>Mala calidad en la voz</th>\n      <th>Navegacion Lenta</th>\n      <th>No funciona l\u00ednea telef\u00f3nica</th>\n      <th>No navega</th>\n      <th>No salen llamadas a X destino</th>\n      <th>Problemas Control Remoto</th>\n      <th>Problemas Servicios Especiales</th>\n      <th>Problemas con el portal</th>\n      <th>Problemas de correo remoto</th>\n      <th>Problemas paquetes adicionales</th>\n      <th>Problemas wifi</th>\n      <th>Retenci\u00f3n Clientes</th>\n      <th>Servicio intermitente</th>\n      <th>Sin se\u00f1al</th>\n      <th>Solicitud configuracion tecni</th>\n    </tr>\n    <tr>\n      <th>DEPARTAMENTO</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>ANTIOQUIA</th>\n      <td>44</td>\n      <td>14</td>\n      <td>9</td>\n      <td>56</td>\n      <td>141</td>\n      <td>5</td>\n      <td>124</td>\n      <td>476</td>\n      <td>1862</td>\n      <td>9</td>\n      <td>123</td>\n      <td>7</td>\n      <td>6</td>\n      <td>0</td>\n      <td>16</td>\n      <td>35</td>\n      <td>3</td>\n      <td>800</td>\n      <td>935</td>\n      <td>49</td>\n    </tr>\n    <tr>\n      <th>ATLANTICO</th>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>5</td>\n      <td>1</td>\n      <td>60</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>19</td>\n      <td>16</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>ATL\u00c1NTICO</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>0</td>\n      <td>7</td>\n      <td>46</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>24</td>\n      <td>13</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>BOLIVAR</th>\n      <td>6</td>\n      <td>2</td>\n      <td>0</td>\n      <td>2</td>\n      <td>6</td>\n      <td>0</td>\n      <td>4</td>\n      <td>17</td>\n      <td>129</td>\n      <td>2</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>48</td>\n      <td>53</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>CALDAS</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>CAUCA</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>6</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>CESAR</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>6</td>\n      <td>3</td>\n      <td>31</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>9</td>\n      <td>18</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>CORDOBA</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>9</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>7</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>CUNDINAMARCA</th>\n      <td>12</td>\n      <td>0</td>\n      <td>0</td>\n      <td>8</td>\n      <td>13</td>\n      <td>0</td>\n      <td>11</td>\n      <td>24</td>\n      <td>333</td>\n      <td>2</td>\n      <td>10</td>\n      <td>0</td>\n      <td>4</td>\n      <td>0</td>\n      <td>3</td>\n      <td>5</td>\n      <td>0</td>\n      <td>125</td>\n      <td>102</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>HUILA</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>LA GUAJIRA</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>MAGDALENA</th>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>4</td>\n      <td>0</td>\n      <td>3</td>\n      <td>2</td>\n      <td>14</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>17</td>\n      <td>16</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>META</th>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>6</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>3</td>\n      <td>7</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>NORTE DE SANTANDER</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>9</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>10</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>RISARALDA</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>SANTANDER</th>\n      <td>7</td>\n      <td>5</td>\n      <td>0</td>\n      <td>3</td>\n      <td>14</td>\n      <td>0</td>\n      <td>7</td>\n      <td>17</td>\n      <td>168</td>\n      <td>2</td>\n      <td>11</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>0</td>\n      <td>85</td>\n      <td>49</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>SUCRE</th>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>11</td>\n      <td>3</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>2</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>TOLIMA</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>VALLE DEL CAUCA</th>\n      <td>3</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>20</td>\n      <td>0</td>\n      <td>16</td>\n      <td>17</td>\n      <td>166</td>\n      <td>2</td>\n      <td>7</td>\n      <td>2</td>\n      <td>4</td>\n      <td>3</td>\n      <td>3</td>\n      <td>10</td>\n      <td>0</td>\n      <td>96</td>\n      <td>73</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n#numerical variables\nnum_vars=list(df.describe().columns)\nnum_vars\n```\n\n\n\n\n    ['antiguedad_meses',\n     'no_serv_tecnicos',\n     'asesoria_factura',\n     'pedidos_peticiones',\n     'reagendamiento',\n     'asesoria_servicios',\n     'retencion',\n     'Otras',\n     'quejas_fraude',\n     'traslado',\n     'Incumplimiento_pago',\n     'cliente_id']\n\n\n\n\n```python\n#de las num_vars hay que remover cliente_id que no aporta al an\u00e1lisis pues es solo un dato para etiquetar a cada cliente con un n\u00famero identificador:\r\nnum_vars=num_vars.copy()[:-1]\r\nprint(num_vars)\n```\n\n    ['antiguedad_meses', 'no_serv_tecnicos', 'asesoria_factura', 'pedidos_peticiones', 'reagendamiento', 'asesoria_servicios', 'retencion', 'Otras', 'quejas_fraude', 'traslado', 'Incumplimiento_pago']\n\n\n\n```python\n#categorical variables\ncat_vars=list(df.describe(include = ['O']).columns)\ncat_vars\n```\n\n\n\n\n    ['REGIONAL',\n     'DEPARTAMENTO',\n     'TECNOL',\n     'GERENCIA',\n     'CANAL_HOMOLOGADO_MILLICON',\n     'tipo_fuerza_venta',\n     'estrato',\n     'productos',\n     'portafolio',\n     'fallo']\n\n\n\n\n```python\n# Unique values per column excluding null\ndf.nunique()\n```\n\n\n\n\n    REGIONAL                         6\n    DEPARTAMENTO                    22\n    TECNOL                           4\n    GERENCIA                         6\n    CANAL_HOMOLOGADO_MILLICON       11\n    tipo_fuerza_venta                2\n    estrato                          7\n    antiguedad_meses               232\n    productos                        7\n    portafolio                       3\n    no_serv_tecnicos                 1\n    fallo                           20\n    asesoria_factura                 2\n    pedidos_peticiones               2\n    reagendamiento                   2\n    asesoria_servicios               2\n    retencion                        2\n    Otras                            2\n    quejas_fraude                    2\n    traslado                         2\n    Incumplimiento_pago              2\n    cliente_id                   12106\n    dtype: int64\n\n\n\n\n```python\n# Unique values per column including null\ndf.nunique(dropna=False)\n```\n\n\n\n\n    REGIONAL                         6\n    DEPARTAMENTO                    22\n    TECNOL                           4\n    GERENCIA                         6\n    CANAL_HOMOLOGADO_MILLICON       11\n    tipo_fuerza_venta                2\n    estrato                          7\n    antiguedad_meses               233\n    productos                        7\n    portafolio                       3\n    no_serv_tecnicos                 2\n    fallo                           21\n    asesoria_factura                 2\n    pedidos_peticiones               2\n    reagendamiento                   2\n    asesoria_servicios               2\n    retencion                        2\n    Otras                            2\n    quejas_fraude                    2\n    traslado                         2\n    Incumplimiento_pago              2\n    cliente_id                   12106\n    dtype: int64\n\n\n\n### Generando algunas graficas estad\u00edsticas de algunas variables independientes (X) frente a la variable objetico o de inter\u00e9s (Y):\n\n\n```python\n#plotting the histogram of the numerical variables:\r\nsns.histplot(df[num_vars[10]])\r\nplt.title('Histograma de la variable objetivo (Inclumplimiento_pago: binaria 0 no, 1 si)')\r\nplt.show()\n```\n\nCon el anterior histograma se comprueba que el **14.3165% de los clientes (aprox 2855 de 19942 clientes en total** est\u00e1 incumpliendo el pago (no ha pagado la primera factura)\n\nNow that we have looked at the variables of interest in isolation, it makes sense to look at them in relation to `Inclumplimiento_pago`:\n\n\n```python\n#Inspecting Inclumplimiento_pago against another variable of interest (e.g antiguedad_meses):\nplt.figure(figsize=(50, 10))\nsns.boxplot(x = num_vars[0], y=num_vars[10], data = df)\ntitle_string = \"Boxplot of \" + num_vars[10] + \" vs. \" + num_vars[0]\nplt.ylabel(num_vars[10])\nplt.title(title_string)\n```\n\n\n```python\n# We can look out for trends using a line plot \r\nplt.figure(figsize=(15, 8))\r\nax = sns.lineplot(\r\n    x=num_vars[0],\r\n    y=num_vars[10],\r\n    data=df,\r\n)\n```\n\n\n```python\nplt.figure(figsize=(15, 8))\r\nax = sns.lineplot(\r\n    x=cat_vars[6],\r\n    y=num_vars[10],\r\n    data=df,\r\n)\n```\n\n\n```python\nplt.figure(figsize=(15, 8))\r\nax = sns.lineplot(\r\n    x=cat_vars[8],\r\n    y=num_vars[10],\r\n    data=df,\r\n)\n```\n\n## Pre-processing our data\n\nNow that we have an idea of what our dataset consists of, let's transform it so that we can display phase. The types of activities we may engage in during **pre-processing** include:\n\n1. **Deleting columns**\n2. **Enriching (or Transforming)** a data set, adding newly calculated columns in the indices\n3. **Filtering** a subset of the rows or columns of a dataset according to some criteria\n4. **Indexing** a dataset\n5. **Aggregating** data\n6. **Sorting** the rows of a data set according to some criteria\n7. **Merging** the data\n8. **Pivoting** so that data that was originally laid out vertically is laid out horizontally (increasing the number of columns) or vice versa (increasing the number of rows)\n\namong others.\n\n## What is data transformation?\r\n\r\nMany times in real life, you will be working with imperfect datasets with quality issues. **Data transformation** is the process of modifying a dataset in appropriate ways in order to eliminate these quality issues. Some of these activities include:\r\n\r\n- Splitting columns\r\n- Converting dates to `datetime` objects, which are far more easily manipulable using `pandas` libraries\r\n- Encoding categorical variables\r\n- Dealing with and replacing null or missing values\r\n- Creating unique identifiers\r\n\r\nThe `pandas` library has many functions which can help with this task. In addition, you will also be using some other standard libraries like `String`, `base64`, and `sklearn`.\n\n\n```python\n#Let's create a copy of our dataframe before we start changing it so we can refer back to the original values if necessary.\r\ndf_orig = df.copy()\r\ndf_orig.head(1)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>REGIONAL</th>\n      <th>DEPARTAMENTO</th>\n      <th>TECNOL</th>\n      <th>GERENCIA</th>\n      <th>CANAL_HOMOLOGADO_MILLICON</th>\n      <th>tipo_fuerza_venta</th>\n      <th>estrato</th>\n      <th>antiguedad_meses</th>\n      <th>productos</th>\n      <th>portafolio</th>\n      <th>no_serv_tecnicos</th>\n      <th>fallo</th>\n      <th>asesoria_factura</th>\n      <th>pedidos_peticiones</th>\n      <th>reagendamiento</th>\n      <th>asesoria_servicios</th>\n      <th>retencion</th>\n      <th>Otras</th>\n      <th>quejas_fraude</th>\n      <th>traslado</th>\n      <th>Incumplimiento_pago</th>\n      <th>cliente_id</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>COSTA</td>\n      <td>MAGDALENA</td>\n      <td>HFC</td>\n      <td>CONTACT</td>\n      <td>SAC</td>\n      <td>INDIRECTA</td>\n      <td>3</td>\n      <td>19.0</td>\n      <td>TV+BA</td>\n      <td>Duo</td>\n      <td>1.0</td>\n      <td>No funciona l\u00ednea telef\u00f3nica</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1004369760</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nLos registros de las variables numericas como `antiguedad_meses` y `no_serv_tecnicos` que no tienen informaci\u00f3n deben ser reemplazados por NaN\r\n\r\n**(The most prudent option which will not alter subsequent summary statistics calculations and not skew the distribution of the non-missing data would be to replace all missing values with a standard NaN)**\r\n\r\nSin embargo, los registros sin informaci\u00f3n de la variable categ\u00f3rica `fallo` pueden reemplazarse por SE (\"Sin Especificar\"), similarmente a como lo tiene ya establecido la variable categ\u00f3rica `estrato`\n\n\n```python\ndf['antiguedad_meses'].fillna(np.nan, inplace=True)\n```\n\n\n```python\ndf['no_serv_tecnicos'].fillna(np.nan, inplace=True)\n```\n\n\n```python\ndf['fallo'].fillna('SE', inplace=True) #SE=Sin Especificar (similar a cuando no hay info de Estrato)\n```\n\n\n```python\ndf.isnull().sum()\n```\n\n\n\n\n    REGIONAL                         0\n    DEPARTAMENTO                     0\n    TECNOL                           0\n    GERENCIA                         0\n    CANAL_HOMOLOGADO_MILLICON        0\n    tipo_fuerza_venta                0\n    estrato                          0\n    antiguedad_meses              1678\n    productos                        0\n    portafolio                       0\n    no_serv_tecnicos             13033\n    fallo                            0\n    asesoria_factura                 0\n    pedidos_peticiones               0\n    reagendamiento                   0\n    asesoria_servicios               0\n    retencion                        0\n    Otras                            0\n    quejas_fraude                    0\n    traslado                         0\n    Incumplimiento_pago              0\n    cliente_id                       0\n    dtype: int64\n\n\n\nUna vez finalizado el tratamiento de valores faltantes y/o nulos, procedemos con los siguientes pasos del EDA:\n\nExploremos las **correlaciones** de las variables numericas con la variable objetivo (num_vars[10]=`Incumplimiento_pago`):\n\n\n```python\n# Create a correlation matrix\r\ncorr    = df[num_vars].corr()\r\npos_cor = corr[num_vars[10]] >0\r\nneg_cor = corr[num_vars[10]] <0\r\ncorr[num_vars[10]][pos_cor].sort_values(ascending = False)\r\n#This prints out the coefficients that are positively correlated with Incumplimiento_pago:\n```\n\n\n\n\n    Incumplimiento_pago    1.000000\n    Otras                  0.011687\n    quejas_fraude          0.010103\n    Name: Incumplimiento_pago, dtype: float64\n\n\n\n\n```python\ncorr[num_vars[10]][neg_cor].sort_values(ascending = False)\r\n#This prints out the coefficients that are negatively correlated with Incumplimiento_pago:\n```\n\n\n\n\n    pedidos_peticiones   -0.000021\n    traslado             -0.006498\n    reagendamiento       -0.008957\n    retencion            -0.012425\n    asesoria_servicios   -0.019946\n    asesoria_factura     -0.021996\n    antiguedad_meses     -0.150507\n    Name: Incumplimiento_pago, dtype: float64\n\n\n\nDe las resultados anteriores se concluye que:\r\n\r\n- Hay **mas** incumplimiento de pago cuando los clientes llaman por otros motivos y hay quejas de fraude\r\n- Existe **menos** incumplimiento de pago a medida que aumenta la antiguedad en meses\n\n\n```python\n# subdividiendo la columna producto en tres para trabajar los servicios de forma diferenciada:\r\ndf[['productoTO','productoTV','productoBA']] =  df.productos.str.split('+',expand=True,)\n```\n\n\n```python\ndf[['productoTO','productoTV','productoBA']]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>productoTO</th>\n      <th>productoTV</th>\n      <th>productoBA</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>TV</td>\n      <td>BA</td>\n      <td>None</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>TV</td>\n      <td>BA</td>\n      <td>None</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>TV</td>\n      <td>None</td>\n      <td>None</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>TO</td>\n      <td>TV</td>\n      <td>BA</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>TO</td>\n      <td>TV</td>\n      <td>BA</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>19937</th>\n      <td>TO</td>\n      <td>BA</td>\n      <td>None</td>\n    </tr>\n    <tr>\n      <th>19938</th>\n      <td>TO</td>\n      <td>BA</td>\n      <td>None</td>\n    </tr>\n    <tr>\n      <th>19939</th>\n      <td>BA</td>\n      <td>None</td>\n      <td>None</td>\n    </tr>\n    <tr>\n      <th>19940</th>\n      <td>TV</td>\n      <td>None</td>\n      <td>None</td>\n    </tr>\n    <tr>\n      <th>19941</th>\n      <td>TV</td>\n      <td>None</td>\n      <td>None</td>\n    </tr>\n  </tbody>\n</table>\n<p>19942 rows \u00d7 3 columns</p>\n</div>\n\n\n\n\n```python\ndf['productoTO'][19939]\n```\n\n\n\n\n    'BA'\n\n\n\n\n```python\ndf.loc[19939,'productoTO']='valor'\n```\n\n\n```python\ndf['productoTO'][19939]\n```\n\n\n\n\n    'valor'\n\n\n\nCon lo anterior, se procede a hacer un proceso similar a una **codificaci\u00f3n one-hot** de las tres variables categ\u00f3ricas (`productoTO`,`productoTV`,`productoBA`) que se extrajeron de la columna `productos`. Solo queda repartir el valor adecuado en la correspondiente columna (TO, TV, BA) y asignar para cada columna ya organizada, el valor de 1 en caso de que haya producto y 0 cuando no haya:\n\n\n```python\n#usando unas columnas auxiliares en primera instancia:\r\ndf['O']=''\r\ndf['V']=''\r\ndf['A']=''\r\n\n```\n\n\n```python\n#organizando los productos as\u00ed: TO, TV, BA (tipo one-hot-encoding)\r\ncols=['productoTO','productoTV','productoBA']\r\n\r\nfor row in range(0, len(df)):\r\n  for col in cols:\r\n      if df[col][row]=='TO':\r\n        df.loc[row,'O']=1    \r\n      elif df[col][row]=='TV':\r\n        df.loc[row,'V']=1\r\n      elif df[col][row]=='BA':\r\n        df.loc[row,'A']=1       \r\n\n```\n\n\n```python\ndf[['O','V','A']]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>O</th>\n      <th>V</th>\n      <th>A</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td></td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td></td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td></td>\n      <td>1</td>\n      <td></td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>19937</th>\n      <td>1</td>\n      <td></td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>19938</th>\n      <td>1</td>\n      <td></td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>19939</th>\n      <td></td>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <th>19940</th>\n      <td></td>\n      <td>1</td>\n      <td></td>\n    </tr>\n    <tr>\n      <th>19941</th>\n      <td></td>\n      <td>1</td>\n      <td></td>\n    </tr>\n  </tbody>\n</table>\n<p>19942 rows \u00d7 3 columns</p>\n</div>\n\n\n\n\n```python\ndf[['productoTO','productoTV','productoBA']] = df[['O','V','A']]\r\ndf[['productoTO','productoTV','productoBA']]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>productoTO</th>\n      <th>productoTV</th>\n      <th>productoBA</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td></td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td></td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td></td>\n      <td>1</td>\n      <td></td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>19937</th>\n      <td>1</td>\n      <td></td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>19938</th>\n      <td>1</td>\n      <td></td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>19939</th>\n      <td></td>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <th>19940</th>\n      <td></td>\n      <td>1</td>\n      <td></td>\n    </tr>\n    <tr>\n      <th>19941</th>\n      <td></td>\n      <td>1</td>\n      <td></td>\n    </tr>\n  </tbody>\n</table>\n<p>19942 rows \u00d7 3 columns</p>\n</div>\n\n\n\n\n```python\ndf['productoTO'][0]\n```\n\n\n\n\n    ''\n\n\n\n\n```python\n#ya tenemos los valores de 1, ahora falta poner 0 donde est\u00e9 vac\u00edo (''):\r\ncols=['productoTO','productoTV','productoBA']\r\nfor row in range(0, len(df)):\r\n  for col in cols:\r\n      if df[col][row]=='':\r\n        df.loc[row,col]=0    \r\n      \n```\n\n\n```python\ndf[['productoTO','productoTV','productoBA']] #esta es la versi\u00f3n final tipo one-hot-encoding\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>productoTO</th>\n      <th>productoTV</th>\n      <th>productoBA</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>19937</th>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>19938</th>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>19939</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>19940</th>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>19941</th>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n<p>19942 rows \u00d7 3 columns</p>\n</div>\n\n\n\n\n```python\ndf.head(1)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>REGIONAL</th>\n      <th>DEPARTAMENTO</th>\n      <th>TECNOL</th>\n      <th>GERENCIA</th>\n      <th>CANAL_HOMOLOGADO_MILLICON</th>\n      <th>tipo_fuerza_venta</th>\n      <th>estrato</th>\n      <th>antiguedad_meses</th>\n      <th>productos</th>\n      <th>portafolio</th>\n      <th>no_serv_tecnicos</th>\n      <th>fallo</th>\n      <th>asesoria_factura</th>\n      <th>pedidos_peticiones</th>\n      <th>reagendamiento</th>\n      <th>asesoria_servicios</th>\n      <th>retencion</th>\n      <th>Otras</th>\n      <th>quejas_fraude</th>\n      <th>traslado</th>\n      <th>Incumplimiento_pago</th>\n      <th>cliente_id</th>\n      <th>productoTO</th>\n      <th>productoTV</th>\n      <th>productoBA</th>\n      <th>O</th>\n      <th>V</th>\n      <th>A</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>COSTA</td>\n      <td>MAGDALENA</td>\n      <td>HFC</td>\n      <td>CONTACT</td>\n      <td>SAC</td>\n      <td>INDIRECTA</td>\n      <td>3</td>\n      <td>19.0</td>\n      <td>TV+BA</td>\n      <td>Duo</td>\n      <td>1.0</td>\n      <td>No funciona l\u00ednea telef\u00f3nica</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1004369760</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td></td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf.columns\n```\n\n\n\n\n    Index(['REGIONAL', 'DEPARTAMENTO', 'TECNOL', 'GERENCIA',\n           'CANAL_HOMOLOGADO_MILLICON', 'tipo_fuerza_venta', 'estrato',\n           'antiguedad_meses', 'productos', 'portafolio', 'no_serv_tecnicos',\n           'fallo', 'asesoria_factura', 'pedidos_peticiones', 'reagendamiento',\n           'asesoria_servicios', 'retencion', 'Otras', 'quejas_fraude', 'traslado',\n           'Incumplimiento_pago', 'cliente_id', 'productoTO', 'productoTV',\n           'productoBA', 'O', 'V', 'A'],\n          dtype='object')\n\n\n\n\n```python\nnew_cols=['REGIONAL', 'DEPARTAMENTO', 'TECNOL', 'GERENCIA',\r\n       'CANAL_HOMOLOGADO_MILLICON', 'tipo_fuerza_venta', 'estrato',\r\n       'antiguedad_meses', 'productos', 'portafolio', 'no_serv_tecnicos',\r\n       'fallo', 'asesoria_factura', 'pedidos_peticiones', 'reagendamiento',\r\n       'asesoria_servicios', 'retencion', 'Otras', 'quejas_fraude', 'traslado',\r\n       'Incumplimiento_pago', 'cliente_id', 'productoTO', 'productoTV',\r\n       'productoBA']\n```\n\n\n```python\ndf=df[new_cols].copy() #finalmente nos quedamos con las columnas necesarias para el posterior an\u00e1lisis sin tener en cuenta las auxiliares (repetidas)\r\ndf.head(1)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>REGIONAL</th>\n      <th>DEPARTAMENTO</th>\n      <th>TECNOL</th>\n      <th>GERENCIA</th>\n      <th>CANAL_HOMOLOGADO_MILLICON</th>\n      <th>tipo_fuerza_venta</th>\n      <th>estrato</th>\n      <th>antiguedad_meses</th>\n      <th>productos</th>\n      <th>portafolio</th>\n      <th>no_serv_tecnicos</th>\n      <th>fallo</th>\n      <th>asesoria_factura</th>\n      <th>pedidos_peticiones</th>\n      <th>reagendamiento</th>\n      <th>asesoria_servicios</th>\n      <th>retencion</th>\n      <th>Otras</th>\n      <th>quejas_fraude</th>\n      <th>traslado</th>\n      <th>Incumplimiento_pago</th>\n      <th>cliente_id</th>\n      <th>productoTO</th>\n      <th>productoTV</th>\n      <th>productoBA</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>COSTA</td>\n      <td>MAGDALENA</td>\n      <td>HFC</td>\n      <td>CONTACT</td>\n      <td>SAC</td>\n      <td>INDIRECTA</td>\n      <td>3</td>\n      <td>19.0</td>\n      <td>TV+BA</td>\n      <td>Duo</td>\n      <td>1.0</td>\n      <td>No funciona l\u00ednea telef\u00f3nica</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1004369760</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nprint(num_vars)\n```\n\n    ['antiguedad_meses', 'no_serv_tecnicos', 'asesoria_factura', 'pedidos_peticiones', 'reagendamiento', 'asesoria_servicios', 'retencion', 'Otras', 'quejas_fraude', 'traslado', 'Incumplimiento_pago']\n\n\n\n```python\nprint(cat_vars)\n```\n\n    ['REGIONAL', 'DEPARTAMENTO', 'TECNOL', 'GERENCIA', 'CANAL_HOMOLOGADO_MILLICON', 'tipo_fuerza_venta', 'estrato', 'productos', 'portafolio', 'fallo']\n\n\n\n```python\n#redefiniendo las nuevas vars categoricas (no considerar productos como un todo sino las tres tipo one-hot encoding)\r\nnew_cat_vars=['REGIONAL', 'DEPARTAMENTO', 'TECNOL', 'GERENCIA', 'CANAL_HOMOLOGADO_MILLICON', 'tipo_fuerza_venta', 'estrato', 'portafolio', 'fallo', 'productoTO',\t'productoTV',\t'productoBA']\r\nprint(new_cat_vars)\n```\n\n    ['REGIONAL', 'DEPARTAMENTO', 'TECNOL', 'GERENCIA', 'CANAL_HOMOLOGADO_MILLICON', 'tipo_fuerza_venta', 'estrato', 'portafolio', 'fallo', 'productoTO', 'productoTV', 'productoBA']\n\n\n# Observaci\u00f3n:\r\n\r\nPara mi caso personal, por motivos de tiempo limitado y dado que el tratamiento de la informaci\u00f3n se est\u00e1 haciendo con las herramientas proporcionadas por Python (pandas, numpy, etc.) en este cuaderno de Jupyter y usando los recursos de Google Collab, no es necesario que la base de datos quede por ejemplo con todas sus variables y valores en min\u00fasculas, sin tildes, sin caracter\u00e9s especiales, etc, ya que no se va a usar SQL (tampoco se est\u00e1 trabajando en este caso con procesamiento de texto - si dispongo de tiempo, aunque lo dudo, trabajar\u00e9 en NLP con Tweets de Teleperformance). Sin embargo,  es deseable e importante que la base de datos quede de forma apropiada para poner los modelos de ML en producci\u00f3n con el fin de que consuma info de la base de datos y finalmente se muestren los resultados en un Front End espec\u00edfico como Dash o  PowerBI, entre otros.\n\n2. **Construya un modelo estad\u00edstico que calcule la probabilidad de que un cliente no pague la primera factura. Explique por qu\u00e9 escogi\u00f3 las variables con las que va a trabajar y si debi\u00f3 hacer modificaciones de estas.**\r\n\r\nTeniendo en cuenta los resultados del an\u00e1lisis anterior (punto 1), proceder\u00e9 a construir el modelo estad\u00edstico que ser\u00e1 **Regresi\u00f3n Log\u00edstica**.\r\n\r\nPara referencia, en estos dos trabajos hay informaci\u00f3n interesante y pernitente para este caso:\r\n\r\n[1]https://bibdigital.epn.edu.ec/bitstream/15000/9194/3/CD-6105.pdf\r\n\r\n[2]https://repository.eafit.edu.co/bitstream/handle/10784/12870/Adriana_SalamancaArias_JohnAlejandro_BenitezUrrea_2018.pdf?sequence=2\r\n\r\nSeg\u00fan [2], *\"los modelos log\u00edsticos son apropiados para medir la probabilidad de incumplimiento que enfrentan las empresas del sector real, al tener en cuenta su versatilidad para determinar rangos m\u00faltiples de la variable dependiente de manera ordenada, porque trabaja con distribuci\u00f3n probabil\u00edstica que permite que con poca informaci\u00f3n se puedan obtener resultados interesantes con respecto a la probabilidad de incumplimiento\"*\r\n\r\n\n\n\n```python\ndf.index\n```\n\n\n\n\n    RangeIndex(start=0, stop=19942, step=1)\n\n\n\n\n```python\n100*(13033/19942)\r\n\n```\n\n\n\n\n    65.35452813158159\n\n\n\n\n```python\n#para facilitar el an\u00e1lisis, no considerar\u00e9 la columna no_serv_tecnicos debido a la poca informaci\u00f3n que tiene (solo el 35% puesto que el 65% son NULL) reemplazando los NaN por su valor promedio en 'antiguedad_meses'\r\ndf['antiguedad_meses'].fillna(df['antiguedad_meses'].mean(), inplace=True)\r\ndf['no_serv_tecnicos'].fillna(df['no_serv_tecnicos'].mean(), inplace=True) #lo hago solo por llenarla de la misma manera pero esa columna no se considerar\u00e1\r\ndf.info()\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 19942 entries, 0 to 19941\n    Data columns (total 25 columns):\n     #   Column                     Non-Null Count  Dtype  \n    ---  ------                     --------------  -----  \n     0   REGIONAL                   19942 non-null  object \n     1   DEPARTAMENTO               19942 non-null  object \n     2   TECNOL                     19942 non-null  object \n     3   GERENCIA                   19942 non-null  object \n     4   CANAL_HOMOLOGADO_MILLICON  19942 non-null  object \n     5   tipo_fuerza_venta          19942 non-null  object \n     6   estrato                    19942 non-null  object \n     7   antiguedad_meses           19942 non-null  float64\n     8   productos                  19942 non-null  object \n     9   portafolio                 19942 non-null  object \n     10  no_serv_tecnicos           19942 non-null  float64\n     11  fallo                      19942 non-null  object \n     12  asesoria_factura           19942 non-null  int64  \n     13  pedidos_peticiones         19942 non-null  int64  \n     14  reagendamiento             19942 non-null  int64  \n     15  asesoria_servicios         19942 non-null  int64  \n     16  retencion                  19942 non-null  int64  \n     17  Otras                      19942 non-null  int64  \n     18  quejas_fraude              19942 non-null  int64  \n     19  traslado                   19942 non-null  int64  \n     20  Incumplimiento_pago        19942 non-null  int64  \n     21  cliente_id                 19942 non-null  int64  \n     22  productoTO                 19942 non-null  object \n     23  productoTV                 19942 non-null  object \n     24  productoBA                 19942 non-null  object \n    dtypes: float64(2), int64(10), object(13)\n    memory usage: 3.8+ MB\n\n\n\n```python\ndf['estrato'].head(20)\n```\n\n\n\n\n    0      3\n    1      3\n    2      1\n    3      3\n    4      3\n    5      3\n    6     SE\n    7     SE\n    8      3\n    9     SE\n    10    SE\n    11    SE\n    12    SE\n    13    SE\n    14    SE\n    15     4\n    16     4\n    17     4\n    18     2\n    19    SE\n    Name: estrato, dtype: object\n\n\n\n\n```python\n#similarmente en 'estrato' cambio 'SE' por 0 (para luego hacerlo por la parte entera de su valor promedio):\r\nfor i in df.index:\r\n  if df['estrato'][i]=='SE':\r\n      df['estrato'][i]=0\n```\n\n\n```python\ndf['estrato'].head(20)\n```\n\n\n\n\n    0     3\n    1     3\n    2     1\n    3     3\n    4     3\n    5     3\n    6     0\n    7     0\n    8     3\n    9     0\n    10    0\n    11    0\n    12    0\n    13    0\n    14    0\n    15    4\n    16    4\n    17    4\n    18    2\n    19    0\n    Name: estrato, dtype: object\n\n\n\n\n```python\ndf['estrato']=pd.to_numeric(df['estrato'])\r\ndf.info()\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 19942 entries, 0 to 19941\n    Data columns (total 25 columns):\n     #   Column                     Non-Null Count  Dtype  \n    ---  ------                     --------------  -----  \n     0   REGIONAL                   19942 non-null  object \n     1   DEPARTAMENTO               19942 non-null  object \n     2   TECNOL                     19942 non-null  object \n     3   GERENCIA                   19942 non-null  object \n     4   CANAL_HOMOLOGADO_MILLICON  19942 non-null  object \n     5   tipo_fuerza_venta          19942 non-null  object \n     6   estrato                    19942 non-null  int64  \n     7   antiguedad_meses           19942 non-null  float64\n     8   productos                  19942 non-null  object \n     9   portafolio                 19942 non-null  object \n     10  no_serv_tecnicos           19942 non-null  float64\n     11  fallo                      19942 non-null  object \n     12  asesoria_factura           19942 non-null  int64  \n     13  pedidos_peticiones         19942 non-null  int64  \n     14  reagendamiento             19942 non-null  int64  \n     15  asesoria_servicios         19942 non-null  int64  \n     16  retencion                  19942 non-null  int64  \n     17  Otras                      19942 non-null  int64  \n     18  quejas_fraude              19942 non-null  int64  \n     19  traslado                   19942 non-null  int64  \n     20  Incumplimiento_pago        19942 non-null  int64  \n     21  cliente_id                 19942 non-null  int64  \n     22  productoTO                 19942 non-null  object \n     23  productoTV                 19942 non-null  object \n     24  productoBA                 19942 non-null  object \n    dtypes: float64(2), int64(11), object(12)\n    memory usage: 3.8+ MB\n\n\n\n```python\nint(df['estrato'].mean())\n```\n\n\n\n\n    2\n\n\n\n\n```python\n#similarmente en 'estrato' cambio 'SE' por la parte entera de su valor promedio:\r\nfor i in df.index:\r\n  if df['estrato'][i]==0:\r\n      df['estrato'][i]=int(df['estrato'].mean())\r\n\r\ndf['estrato'].head(20)\n```\n\n\n\n\n    0     3\n    1     3\n    2     1\n    3     3\n    4     3\n    5     3\n    6     2\n    7     2\n    8     3\n    9     2\n    10    2\n    11    2\n    12    2\n    13    2\n    14    2\n    15    4\n    16    4\n    17    4\n    18    2\n    19    2\n    Name: estrato, dtype: int64\n\n\n\n\n```python\n#recordemos el conteo de la var objetivo:\r\nsns.countplot(x='Incumplimiento_pago', data = df)\r\nplt.title(\"Incumplimiento_pago\")\n```\n\n\n```python\n#Relaci\u00f3n: Incumplimiento_pago (Y) vs antiguedad_meses(X)\r\nsns.jointplot(df.antiguedad_meses, df.Incumplimiento_pago, kind=\"hex\")\n```\n\n\n```python\nprint(num_vars)\n```\n\n    ['antiguedad_meses', 'no_serv_tecnicos', 'asesoria_factura', 'pedidos_peticiones', 'reagendamiento', 'asesoria_servicios', 'retencion', 'Otras', 'quejas_fraude', 'traslado', 'Incumplimiento_pago']\n\n\n\n```python\n#Y='Incumplimiento_pago' (var DEPENDIENTE)\r\n\r\n#redefiniendo las var INDEPENDIENTES verdaderamente numericas (porque las binarias ser\u00edan categ\u00f3ricas) y que ser\u00e1n insumo para el modelo:\r\nnum_vars_def=['antiguedad_meses', 'estrato'] #SOLO QUEDAN 2\n```\n\n\n```python\nprint(new_cat_vars)\n```\n\n    ['REGIONAL', 'DEPARTAMENTO', 'TECNOL', 'GERENCIA', 'CANAL_HOMOLOGADO_MILLICON', 'tipo_fuerza_venta', 'estrato', 'portafolio', 'fallo', 'productoTO', 'productoTV', 'productoBA']\n\n\nNOTA: \r\n\r\nPor simplicidad, las siguientes var cat no se consideran relevantes para el modelo: \r\n'REGIONAL', 'DEPARTAMENTO', 'TECNOL', 'GERENCIA', 'CANAL_HOMOLOGADO_MILLICON', 'tipo_fuerza_venta', 'portafolio' (est\u00e1 correlacionada con 'productos' que tampoco se considera pues se separ\u00f3 en tres var cat binarias que si se van a considerar en su reemplazo)\n\n\n```python\n#en consecuencia, redefiniendo las var verdaderamente categ\u00f3ricas y que ser\u00e1n insumo para el modelo:\r\ncat_vars_def=['productoTO', 'productoTV', 'productoBA', 'asesoria_factura', 'pedidos_peticiones', 'reagendamiento', 'asesoria_servicios', 'retencion', 'Otras', 'quejas_fraude', 'traslado']#QUEDAN 11\n```\n\nVeamos la matriz de correlaci\u00f3n entre las var numericas definitivas (covariables) y la variable objetivo:\r\n\r\n\n\n\n```python\nnum_vars_def=['antiguedad_meses', 'estrato']\n```\n\n\n```python\ncols=num_vars_def.copy()\r\ncols.append('Incumplimiento_pago')\r\nprint(cols)\n```\n\n    ['antiguedad_meses', 'estrato', 'Incumplimiento_pago']\n\n\n\n```python\n#Visualize the correlation matrix across all numerical features by using the sns.heatmap() command:\r\n\r\n#compute correlation matrix\r\n\r\nData=df[cols].copy()\r\n\r\ndf_correlations = Data.corr()\r\n\r\n#mask the upper half for visualization purposes\r\nmask = np.zeros_like(df_correlations, dtype=np.bool)\r\nmask[np.triu_indices_from(mask)] = True\r\n\r\n# Draw the heatmap with the mask and correct aspect ratio\r\nplt.figure(figsize= (10,10))\r\n\r\ncmap = sns.diverging_palette(220, 10, as_cmap=True)\r\nsns.heatmap(df_correlations,mask=mask,  vmax=1, vmin=-1, cmap=cmap, \r\n            center=0,\r\n            square=True, linewidths=.5, cbar_kws={\"shrink\": .5});\n```\n\nConstruyendo el modelo predictivo: \r\n\r\n...iniciando con un modelo de regresi\u00f3n log\u00edstica est\u00e1ndard...\r\n\r\nUsing the `LogisticRegression()` function from `scikit-learn`, let me write a function named `fit_logistic_regression(X,y)` that fits a logistic regression on the array of covariates `X` and associated response variable `y`.\r\n\r\n\r\n\n\n\n```python\nfrom sklearn.linear_model import LogisticRegression\r\ndef fit_logistic_regression(X,y):\r\n    \"\"\"\r\n    fit a logistic regression with feature matrix X and binary output y\r\n    \"\"\"\r\n    clf = LogisticRegression(solver='lbfgs', tol=10**-4,  \r\n                             fit_intercept=True, \r\n                             multi_class='multinomial').fit(X,y)\r\n    return clf\n```\n\nLet me create a basic [logistic regression model](https://towardsdatascience.com/logistic-regression-detailed-overview-46c4da4303bc) for predicting `Incumplimiento_pago` with only one feature: `antiguedad_meses`.  I will call this model `model1`, using a 70/30 train-test split of the data.\n\n\n```python\n# we will use a 70%/30% split for training/validation\r\nData=df.copy()\r\nn_total = len(Data)\r\nn_train = int(0.7*n_total)\r\n\r\nX, y = Data[[\"antiguedad_meses\"]], Data.Incumplimiento_pago\r\nX_train, y_train = X[:n_train], y[:n_train]\r\nX_test, y_test = X[n_train:], y[n_train:]\n```\n\n\n```python\nmodel1 = fit_logistic_regression(X_train, y_train)  # fit a logistic regression\r\ny_test_pred = model1.predict_proba(X_test)[:,1]     # make probabilistic predictions on test set\n```\n\nPlotting the [ROC curve](https://towardsdatascience.com/understanding-auc-roc-curve-68b2303cc9c5) of `model1` and finding the area under the curve:\n\n\n```python\nfrom sklearn.metrics import roc_curve, auc\r\nfrom sklearn.model_selection import StratifiedKFold\n```\n\n\n```python\nfpr, tpr, _ = roc_curve(y_test, y_test_pred)  #compute FPR/TPR\r\nauc_baseline = auc(fpr, tpr) # compute AUC\r\n\r\nplt.plot(fpr, tpr, \"b-\", label=\"AUC(basline)={:2.2f}\".format(auc_baseline))\r\nplt.xlabel(\"False Positive Rate\")\r\nplt.ylabel(\"True Positive Rate\")\r\nplt.legend(fontsize=15)\r\nplt.plot([0,1], [0,1], \"r--\")\r\nplt.title(\"ROC curve -- Baseline Model\");\n```\n\nOf course this should not be the final model. This is because I have not explored the contribution from other variables, which in addition to containing valuable information could also be confounding the perceived effect of `antiguedad_meses` on the response variable `Incumplimiento_pago`. This under-exploitation of information is called [**underfitting**](https://towardsdatascience.com/what-are-overfitting-and-underfitting-in-machine-learning-a96b30864690). \r\n\r\nOn the other hand:\r\n\r\nLet's instead put all the variables available in the model, so that we are maximally leveraging our available info. This is also a bad idea. If we *blindly* use all of the variables in our model fitting, a phenomenon called [**overfitting**](https://towardsdatascience.com/what-are-overfitting-and-underfitting-in-machine-learning-a96b30864690) occurs. This is when a statistical model \"fits\" too closely to a particular set of data, which may well be noisy and exhibit randomness and therefore fail to predict future, different observations reliably.\r\n\r\nIn most cases, you will be working with datasets with many features that each have their own distribution. Generally, a large amount of time is spent on feature selection with many models being trained during this time. It is extremely rare that you simply plug all the features in and tune it once to get the optimal model. \r\n    \r\nThere are many different techniques associated with feature selection and a comprehensive look into all of them is outside the scope of this case. For simplicity, I will demonstrate model training and testing on single-feature models and then directly move into multi-feature models to show the numerous possible cases you may encounter. \r\n\r\nIn reality, I would apply cross-validation on numerous subsets of features based on domain knowledge of the dataset to see which set of features truly optimizes the model I am trying to create.\r\n\r\n[**Cross-validation**](https://towardsdatascience.com/why-and-how-to-cross-validate-a-model-d6424b45261f) is a set of techniques for assessing how well the results of a model will generalize to an out-of-sample dataset; i.e. in practice or production. It is chiefly used to flag overfitting.\n\n\n```python\nskf = StratifiedKFold(n_splits=5)\r\nfor k, (train_index, test_index) in enumerate( skf.split(X, y) ):\r\n    plt.plot(train_index, [k+1 for _ in train_index], \".\")\r\nplt.ylim(0,6)\r\nplt.ylabel(\"FOLD\")\r\nplt.title(\"CROSS VALIDATION FOLDS\")\n```\n\nThe following code defines a function `compute_AUC(X, y, train_index, test_index)` that computes the AUC of a model trained on \"train_index\" and tested in \"test_index\".\n\n\n```python\ndef compute_AUC(X, y, train_index, test_index):\r\n    \"\"\"\r\n    feature/output: X, y\r\n    dataset split: train_index, test_index\r\n    \"\"\"\r\n    X_train, y_train = X.iloc[train_index], y.iloc[train_index]\r\n    X_test, y_test = X.iloc[test_index], y.iloc[test_index]\r\n\r\n    clf = fit_logistic_regression(X_train, y_train)\r\n    default_proba_test = clf.predict_proba(X_test)[:,1]  \r\n    fpr, tpr, _ = roc_curve(y_test, default_proba_test)\r\n    auc_score = auc(fpr, tpr)\r\n    return auc_score, fpr, tpr\n```\n\nWith the help of the `compute_AUC` function defined above, let me write a function `cross_validation_AUC(X,y,nfold)` that carries out a 10-fold cross-validation and returns a list which contains the area under the curve for each fold of the cross-validation:\n\n\n```python\ndef cross_validation_AUC(X,y, nfold=10):\r\n    \"\"\"\r\n    use a n-fold cross-validation for computing AUC estimates\r\n    \"\"\"\r\n    skf = StratifiedKFold(n_splits=nfold)  #create a cross-validation splitting\r\n    auc_list = [] #this list will contain the AUC estimates associated with each fold\r\n    for k, (train_index, test_index) in enumerate( skf.split(X, y) ):\r\n        auc_score, _, _ = compute_AUC(X, y, train_index, test_index)\r\n        auc_list.append(auc_score)\r\n    return auc_list\n```\n\nI will now estimate and compare, through cross-validation analysis, the performance of all the \"simple models\" that only use one numerical features as input. \n\n\n```python\nprint(num_vars_def)\n```\n\n    ['antiguedad_meses', 'estrato']\n\n\nLet's compute cross-validation estimates of the AUC for each single-feature model:\n\n\n```python\nmodel_perf = pd.DataFrame({}) #this data-frame will contain the AUC estimates\r\nfor key in num_vars_def:\r\n    X_full, y_full = Data[[key]], Data.Incumplimiento_pago\r\n    auc_list = cross_validation_AUC(X_full, y_full, nfold=10)\r\n    model_perf[\"SIMPLE:\" + key] = auc_list\n```\n\nLet me construct a [boxplot](https://towardsdatascience.com/understanding-boxplots-5e2df7bcbd51) which shows the distribution of cross-validation scores of each variable (remember, each variable has 10 total scores): \n\n\n```python\ndef plot_boxplot_ordered(df_model):\r\n    \"\"\"\r\n    display a list of boxplot, ordered by the media values\r\n    \"\"\"\r\n    df = df_model[df_model.median().sort_values().index]\r\n    sns.boxplot(x=\"variable\", y=\"value\", data=pd.melt(df), showfliers=False)\r\n    plt.xticks(rotation=90)\n```\n\n\n```python\nplt.figure(figsize= (10,5))\r\nplot_boxplot_ordered(model_perf)\r\nplt.xlabel(\"Predictive Model with a Single Predictive Feature\")\r\nplt.ylabel(\"AUC\")\n```\n\nAccording to what have been done so far, from the above picture I can conclude:\r\n\r\n- The feature that has the highest predictive power is `antiguedad_meses`\r\n- The feature that has the lowest predictive power is `estrato`\n\nLet me consider the model that consists of using *all* the numerical features (and none of the categorical features). Carrying out a 10-fold cross-validation analysis to determine whether this model has better predictive performance than the best single-feature model. Using the boxplot method again as I did before: \n\n\n```python\nX_full, y_full = Data[num_vars_def], Data.Incumplimiento_pago\r\nauc_list = cross_validation_AUC(X_full, y_full)\r\nmodel_perf[\"ALL_NUMERICAL\"] = auc_list\r\nmodel_perf\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>SIMPLE:antiguedad_meses</th>\n      <th>SIMPLE:estrato</th>\n      <th>ALL_NUMERICAL</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.625454</td>\n      <td>0.429581</td>\n      <td>0.612515</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.592383</td>\n      <td>0.462943</td>\n      <td>0.580514</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.559453</td>\n      <td>0.495811</td>\n      <td>0.547094</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.674187</td>\n      <td>0.497961</td>\n      <td>0.669534</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.690632</td>\n      <td>0.521252</td>\n      <td>0.694829</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>0.581867</td>\n      <td>0.494196</td>\n      <td>0.575197</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>0.659101</td>\n      <td>0.552888</td>\n      <td>0.650529</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>0.671121</td>\n      <td>0.533505</td>\n      <td>0.672244</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>0.680397</td>\n      <td>0.504706</td>\n      <td>0.677434</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>0.642052</td>\n      <td>0.509290</td>\n      <td>0.644907</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nplt.figure(figsize= (10,5))\r\nplot_boxplot_ordered(model_perf)\r\nplt.xlabel(\"Predictive Model with a Single Predictive Feature\")\r\nplt.ylabel(\"AUC\")\n```\n\nI see that the combined model does perform better than the best single-feature model. Thus, I will move forward with it for the rest of this case. Note, however, that best practice would entail iteratively adding features to the best single-feature model until I reach a point where there is no significant improvement, as opposed to throwing all the features in at once. Let me advise and consider to take this more cautious approach when building models (it is a matter of time)\n\n## Incorporating categorical variables:\n\n\n```python\ncat_vars_def # se podr\u00eda decir que estas vars ya est\u00e1n codificadas tipo one-hot para irse a\u00f1adiendo al modelo num\u00e9rico anterior\n```\n\n\n\n\n    ['productoTO',\n     'productoTV',\n     'productoBA',\n     'asesoria_factura',\n     'pedidos_peticiones',\n     'reagendamiento',\n     'asesoria_servicios',\n     'retencion',\n     'Otras',\n     'quejas_fraude',\n     'traslado']\n\n\n\n\n```python\nData.value_counts()\r\nsns.countplot(x='productoTO', data = Data) \r\nplt.xticks(rotation=90)\n```\n\nLet me investigate whether the categorical variable `productoTO` brings any predictive value when added to the current best model (remember again that the  encoding scheme of one-hot type is already there:\n\n\n```python\nplt.figure(figsize= (20,5))\r\n\r\ndf_TO_incump = Data[[\"Incumplimiento_pago\", \"productoTO\"]].groupby(\"productoTO\").mean()\r\ndf_TO_incump = df_TO_incump.sort_values(by=\"Incumplimiento_pago\",axis=0, ascending=False)\r\nsns.barplot(x=df_TO_incump.index[:50], \r\n            y=df_TO_incump[\"Incumplimiento_pago\"][:50].values,\r\n            orient=\"v\")\r\nplt.xticks(rotation=90)\r\n\r\nplt.ylabel(\"Probabilidad de Incumplimiento_pago\")\r\nplt.title(\"Incumplimiento_pago por productoTO\", fontsize=20, verticalalignment='bottom')\n```\n\n\n```python\nprint(num_vars_def)\n```\n\n    ['antiguedad_meses', 'estrato']\n\n\n\n```python\nnew_cols=['antiguedad_meses', 'estrato','productoTO','productoTV','productoBA']\r\n\r\nX_full_productos, y_full = Data[new_cols], Data.Incumplimiento_pago\r\nauc_list = cross_validation_AUC(X_full_productos, y_full)\r\nmodel_perf[\"ALL_NUMERICAL_WITH_productos\"] = auc_list\r\nmodel_perf\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>SIMPLE:antiguedad_meses</th>\n      <th>SIMPLE:estrato</th>\n      <th>ALL_NUMERICAL</th>\n      <th>ALL_NUMERICAL_WITH_productos</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.625454</td>\n      <td>0.429581</td>\n      <td>0.612515</td>\n      <td>0.694596</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.592383</td>\n      <td>0.462943</td>\n      <td>0.580514</td>\n      <td>0.627549</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.559453</td>\n      <td>0.495811</td>\n      <td>0.547094</td>\n      <td>0.587298</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.674187</td>\n      <td>0.497961</td>\n      <td>0.669534</td>\n      <td>0.706750</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.690632</td>\n      <td>0.521252</td>\n      <td>0.694829</td>\n      <td>0.727204</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>0.581867</td>\n      <td>0.494196</td>\n      <td>0.575197</td>\n      <td>0.706316</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>0.659101</td>\n      <td>0.552888</td>\n      <td>0.650529</td>\n      <td>0.745785</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>0.671121</td>\n      <td>0.533505</td>\n      <td>0.672244</td>\n      <td>0.728415</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>0.680397</td>\n      <td>0.504706</td>\n      <td>0.677434</td>\n      <td>0.778226</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>0.642052</td>\n      <td>0.509290</td>\n      <td>0.644907</td>\n      <td>0.724648</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nplt.figure(figsize= (10,5))\r\nplot_boxplot_ordered(model_perf)\r\nplt.xlabel(\"Predictive Model with a Single Predictive Feature\")\r\nplt.ylabel(\"AUC\")\n```\n\nThe difference appears significant as the boxplot for the updated model is almost completely non-overlapping with that of the previous model.\n\n#To finish:\n\nLet me use the rest of the \"cat_vars\" (they are indeed numerical: binary):\n\n\n```python\nprint(cat_vars_def)\n```\n\n    ['productoTO', 'productoTV', 'productoBA', 'asesoria_factura', 'pedidos_peticiones', 'reagendamiento', 'asesoria_servicios', 'retencion', 'Otras', 'quejas_fraude', 'traslado']\n\n\n\n```python\npqrs=['asesoria_factura', 'pedidos_peticiones', 'reagendamiento', 'asesoria_servicios', 'retencion', 'Otras', 'quejas_fraude', 'traslado']\n```\n\n\n```python\nnew_cols_def=['antiguedad_meses', 'estrato','productoTO','productoTV','productoBA', 'asesoria_factura', 'pedidos_peticiones', 'reagendamiento', 'asesoria_servicios', 'retencion', 'Otras', 'quejas_fraude', 'traslado']\r\n\r\nX_full_productos_pqrs, y_full = Data[new_cols_def], Data.Incumplimiento_pago\r\nauc_list = cross_validation_AUC(X_full_productos_pqrs, y_full)\r\nmodel_perf[\"ALL_NUMERICAL_WITH_productos_pqrs\"] = auc_list\r\nmodel_perf\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>SIMPLE:antiguedad_meses</th>\n      <th>SIMPLE:estrato</th>\n      <th>ALL_NUMERICAL</th>\n      <th>ALL_NUMERICAL_WITH_productos</th>\n      <th>ALL_NUMERICAL_WITH_productos_pqrs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.625454</td>\n      <td>0.429581</td>\n      <td>0.612515</td>\n      <td>0.694596</td>\n      <td>0.695431</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.592383</td>\n      <td>0.462943</td>\n      <td>0.580514</td>\n      <td>0.627549</td>\n      <td>0.624117</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.559453</td>\n      <td>0.495811</td>\n      <td>0.547094</td>\n      <td>0.587298</td>\n      <td>0.588349</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.674187</td>\n      <td>0.497961</td>\n      <td>0.669534</td>\n      <td>0.706750</td>\n      <td>0.706378</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.690632</td>\n      <td>0.521252</td>\n      <td>0.694829</td>\n      <td>0.727204</td>\n      <td>0.722031</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>0.581867</td>\n      <td>0.494196</td>\n      <td>0.575197</td>\n      <td>0.706316</td>\n      <td>0.706624</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>0.659101</td>\n      <td>0.552888</td>\n      <td>0.650529</td>\n      <td>0.745785</td>\n      <td>0.745685</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>0.671121</td>\n      <td>0.533505</td>\n      <td>0.672244</td>\n      <td>0.728415</td>\n      <td>0.723830</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>0.680397</td>\n      <td>0.504706</td>\n      <td>0.677434</td>\n      <td>0.778226</td>\n      <td>0.781072</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>0.642052</td>\n      <td>0.509290</td>\n      <td>0.644907</td>\n      <td>0.724648</td>\n      <td>0.730572</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nplt.figure(figsize= (10,5))\r\nplot_boxplot_ordered(model_perf)\r\nplt.xlabel(\"Predictive Model with a Single Predictive Feature\")\r\nplt.ylabel(\"AUC\")\n```\n\n## Conclusions \r\n\r\nOnce I started building models, I started with very simple logistic regressions approaches \u2013 these baseline models were useful for quickly evaluating the predictive power of each individual variable. Next, I employed cross-validation approaches for building more complex models, often exploiting the interactions between the different features. Since the dataset contains a large number of covariates, using cross-validation was revealed to be crucial for avoiding overfitting, choosing the correct number of features and ultimately choosing an appropriate model that balanced complexity with accuracy.\r\n\r\nCross-validation is a robust and flexible technique for evaluating the predictive performance of statistical models. It is especially useful in big data settings where the number of features is large compared to the number of observations. When used appropriately, cross-validation is a powerful method for choosing a model with the correct complexity and best predictive performance. Remember that logistic regression is only one of many classification algorithms and the principles behind cross-validation are not limited to this case alone. \n\n*Quiero finalmente comentar que 2 d\u00edas para mi no son suficientes para terminar completa y exitosamente este caso. Con mas tiempo, seguro lo terminar\u00eda, aunque voy a seguir trabajando en el caso apesar de que el tiempo para entregarlo ya se termin\u00f3. Muchas gracias por la oprtunidad y tambi\u00e9n deseo seguir trabajando en el caso opcional donde ten\u00eda pensado trabajar con NLP (Tweets-TP)*\n\n**Observaci\u00f3n:**\r\n\r\nTodo lo trabajado aqu\u00ed est\u00e1 referenciado al *programa de Ciencia de Datos (DS4A-Colombia 3.0) ofertado por el Ministerio TIC de Colombia en convenio con la Compa\u00f1\u00eda Correlation One.*\r\n\r\nTodo el material puede ser encontrado aqu\u00ed:\r\n\r\nhttps://drive.google.com/drive/folders/1mGiM3lWtdkszSIrv-wpJjftZ_2qWbMNt?usp=sharing\r\n\n", "meta": {"hexsha": "5087add8a3478cd29eb72ce14e5e6843f2fd3799", "size": 749203, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "GCollab_CASO_DE_CONSULTORIA_TP.ipynb", "max_stars_repo_name": "felipeescallon/TP_PruebaTecnica_CientificoDatos", "max_stars_repo_head_hexsha": "8abff7dc4104784832c3b09d5777e68956e88c22", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-20T18:32:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-20T18:32:48.000Z", "max_issues_repo_path": "GCollab_CASO_DE_CONSULTORIA_TP.ipynb", "max_issues_repo_name": "felipeescallon/TP_PruebaTecnica_CientificoDatos", "max_issues_repo_head_hexsha": "8abff7dc4104784832c3b09d5777e68956e88c22", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GCollab_CASO_DE_CONSULTORIA_TP.ipynb", "max_forks_repo_name": "felipeescallon/TP_PruebaTecnica_CientificoDatos", "max_forks_repo_head_hexsha": "8abff7dc4104784832c3b09d5777e68956e88c22", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 749203.0, "max_line_length": 749203, "alphanum_fraction": 0.8544893707, "converted": true, "num_tokens": 35996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491213037224875, "lm_q2_score": 0.10087863016367528, "lm_q1q2_score": 0.038829408445334446}}
{"text": "# Python Analyzer\n\n<br>\n\n---\n\n<br>\n\n\n## Reference\n\n<br>\n\n* \uc8fc\ud53c\ud130 \ub178\ud2b8\ubd81\uc758 \ub2e8\ucd95\uae30\n\n    - 1. Command Mode ( press Esc to enable) \n        - 1. shift-Enter : run cell, select below\n        - 2. Ctrl-Enter : run cell\n        - 3. Alt-Enter : run cell, insert below \n        - 4. Y : to code \n        - 5. M : to markdown\n        - 6. B : insert cell below\n        - 7. X : cut selected cell\n        - 8. C : copy selected cell\n        - 9. Shift-V : paste cell above\n        - 10. V : paste cell below\n        - 11. Z : undo last cell deletion\n        - 12. D,D : delete selected cell\n        - 13. Shift-M : merge cell below\n\n    - 2. Edit Mode ( press Enter to enable)\n        - 1. Shift-Tab : \ud234\ud301\ud45c\uc2dc\n        - 2. Ctrl-] : indent\n        - 3. Ctrl-Shift- : split cell\n\n<br>\n\n* \uc8fc\ud53c\ud130 \ub178\ud2b8\ubd81 \ub9c8\ud06c\ub2e4\uc6b4 \uad00\ub828 \ucc38\uace0 \uc790\ub8cc\n    - 1. https://datanetworkanalysis.github.io/2019/10/12/markdown\n    - 2. https://steemit.com/kr/@nand/markdown\n\n<br>\n\n* Pandas \ub370\uc774\ud130 \ubd84\uc11d\n    - 1. https://stmorse.github.io/journal/tidyverse-style-pandas.html\n    \n<br>\n\n* Python \ud1b5\uacc4 \ubd84\uc11d\n    - 1. https://partrita.github.io/posts/pingouin/\n    - 2. https://pingouin-stats.org/index.html\n    - 3. https://www.marsja.se/repeated-measures-anova-in-r-and-python-afex-pingouin/\n\n## Basic Setting & Package Install\n\n\n* \uacbd\ub85c \uc124\uc815\n\n\n```python\nimport os\ncurrDir = os.getcwd()\n# os.chdir(r'/Users/deepmem/Desktop/working/aniFCnet/anime/results/an_01')\n# os.chdir(r'/Users/deepmem/Desktop/working/aniFCnet/anime/results')\n# os.chdir(r'/Users/deepmem/Desktop/working/aniFCnet/anime/results')\nos.chdir(currDir)\n```\n\n* \ud328\ud0a4\uc9c0 \uc124\uce58\n\n\n```python\n### Data Handling & Analysis\n#!pip install numpy scipy pandas sympy statsmodels pingouin\n#!conda install numpy scipy pandas sympy statsmodels pingouin\n\n### Plot\n#!pip install matplotlib seaborn plotnine bokeh\n#!conda install matplotlib seaborn plotnine bokeh\n\n### ML & DL\n#!pip install scikit-learn tensorflow keras\n#!conda install scikit-learn tensorflow keras\n```\n\n* \ud328\ud0a4\uc9c0 \ubd88\ub7ec\uc624\uae30\n\n\n```python\n# ---------------------------------------------------------------------------\n\n# for Data Processing\nimport pandas as pd\nimport numpy as np\n\n# ---------------------------------------------------------------------------\n\n# for Plotting\n\n## - matplotlib\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport pylab as pl\n\n## - seaborn\nimport seaborn as sns\n\n## - plotnine\nimport plotnine as ggplot\n\n# ---------------------------------------------------------------------------\n\n# for Statistic\n\n## scipy\nfrom scipy import stats\n\n## sympy\nimport sympy as sym\n\n## statmodels\nimport statsmodels as modeling\n\n## pingouin\nimport pingouin as pg\n\n# ---------------------------------------------------------------------------\n\n## for Machine Learning\nimport sklearn\nfrom sklearn import preprocessing, feature_selection, linear_model, svm, metrics, model_selection\n\n## for Deep Learning\n# import tensorflow as tp\n# import keras\n\n\n# ---------------------------------------------------------------------------\n\n# Reference\n\n# ## - preprocessing\n# from sklearn.preprocessing import StandardScaler\n# from sklearn.preprocessing import label_binarize\n\n# ## - feature selection\n# ## * https://scikit-learn.org/stable/modules/feature_selection.html\n# ## * https://datascienceschool.net/03%20machine%20learning/14.03%20%ED%8A%B9%EC%A7%95%20%EC%84%A0%ED%83%9D.html\n# from sklearn.feature_selection import VarianceThreshold\n# from sklearn.feature_selection import SelectKBest\n# from sklearn.feature_selection import chi2\n# from sklearn.feature_selection import f_classif\n# from sklearn.feature_selection import f_regression\n\n# # ---------------------------------------------------------------------------\n\n# ## - model\n# ## * https://scikit-learn.org/stable/modules/linear_model.html\n# from sklearn.linear_model import RidgeClassifier\n# from sklearn.linear_model import LogisticRegression\n\n# ## * https://scikit-learn.org/stable/modules/svm.html\n# from sklearn import svm\n\n# ## * https://xgboost.readthedocs.io/en/latest/\n# from xgboost import XGBClassifier\n\n# # ---------------------------------------------------------------------------\n\n# ## - metric, performance measure\n# ## * https://scikit-learn.org/stable/modules/model_evaluation.html\n# from sklearn.metrics import classification_report\n# from sklearn.metrics import accuracy_score\n# from sklearn.metrics import roc_auc_score\n# from sklearn.metrics import confusion_matrix\n\n# ## * https://scikit-learn.org/stable/auto_examples/model_selection/plot_permutation_tests_for_classification.html#sphx-glr-auto-examples-model-selection-plot-permutation-tests-for-classification-py\n# from sklearn.model_selection import permutation_test_score\n\n# # ---------------------------------------------------------------------------\n\n# ## - model selection & evaluation\n# ## * https://scikit-learn.org/stable/modules/cross_validation.html\n# from sklearn import model_selection\n# from sklearn.model_selection import train_test_split\n# from sklearn.model_selection import KFold, LeaveOneOut\n# from sklearn.model_selection import StratifiedKFold\n# from sklearn.model_selection import cross_val_score #prediction\n# from sklearn.model_selection import cross_val_predict #prediction\n# from sklearn.model_selection import cross_validate #prediction\n```\n\n\n```python\n\n# Global setting\nimport warnings\nwarnings.filterwarnings('ignore')\n\nsns.set_style('white')\n%matplotlib inline\n\n\nimport platform                \n\n# \uc6ec\ub9cc\ud558\uba74 \ud574\uc8fc\ub294 \uac83\uc774 \uc88b\ub2e4.\nfrom matplotlib import font_manager, rc\nplt.rcParams['axes.unicode_minus']= False\n\nif platform.system() == 'Darwin': # \ub9e5os \uc0ac\uc6a9\uc790\uc758 \uacbd\uc6b0\uc5d0\n    plt.style.use('seaborn-darkgrid') \n    rc('font', family = 'AppleGothic')\n    \nelif platform.system() == 'Windows':# \uc708\ub3c4\uc6b0 \uc0ac\uc6a9\uc790\uc758 \uacbd\uc6b0\uc5d0\n    path = 'c:/Windows/Fonts/malgun.ttf'\n    font_name = font_manager.FontProperties(fname=path).get_name()\n    plt.style.use('seaborn-darkgrid') # https://python-graph-gallery.com/199-matplotlib-style-sheets/\n    rc('font', family=font_name)\n\nfont = {'weight' : 'bold',\n        'size'   : 15}\n\nmpl.rc('font', **font)\n```\n\n## Exploratory Data Analysis\n\n### Data Load & Glimpse\n\n\n```python\ndata_dir =  ('%s/%s' % (currDir, 'Sample_Data'))\ndf = pd.read_csv(('%s/conSrep_lme.csv' % (data_dir)), encoding='euc-kr')\n```\n\n\n```python\ndf.head(3)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>subj</th>\n      <th>roi</th>\n      <th>cond</th>\n      <th>ll</th>\n      <th>item</th>\n      <th>comp1</th>\n      <th>comp2</th>\n      <th>z</th>\n      <th>rd_ll</th>\n      <th>rd_cond</th>\n      <th>Zr_1</th>\n      <th>Zr_2</th>\n      <th>Zr_s</th>\n      <th>Zr_m</th>\n      <th>b_1</th>\n      <th>b_2</th>\n      <th>b_s</th>\n      <th>b_m</th>\n      <th>Zr_wm</th>\n      <th>b_wm</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>loc</td>\n      <td>1</td>\n      <td>1</td>\n      <td>10105</td>\n      <td>1</td>\n      <td>5</td>\n      <td>0.667815</td>\n      <td>0.783697</td>\n      <td>0.770063</td>\n      <td>0.241053</td>\n      <td>0.166046</td>\n      <td>0.203550</td>\n      <td>0.223921</td>\n      <td>0.126249</td>\n      <td>0.017386</td>\n      <td>0.071818</td>\n      <td>0.130898</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>loc</td>\n      <td>1</td>\n      <td>1</td>\n      <td>10107</td>\n      <td>1</td>\n      <td>7</td>\n      <td>0.873861</td>\n      <td>0.495769</td>\n      <td>0.486178</td>\n      <td>0.577057</td>\n      <td>0.279873</td>\n      <td>0.428465</td>\n      <td>0.468502</td>\n      <td>0.462390</td>\n      <td>-0.039847</td>\n      <td>0.211272</td>\n      <td>0.387839</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1</td>\n      <td>loc</td>\n      <td>1</td>\n      <td>1</td>\n      <td>10111</td>\n      <td>1</td>\n      <td>11</td>\n      <td>0.893776</td>\n      <td>0.547011</td>\n      <td>0.549124</td>\n      <td>0.513251</td>\n      <td>0.342322</td>\n      <td>0.427786</td>\n      <td>0.518879</td>\n      <td>0.331198</td>\n      <td>0.136710</td>\n      <td>0.233954</td>\n      <td>0.481692</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf.shape\n```\n\n\n\n\n    (38016, 20)\n\n\n\n\n```python\n# \uacb0\uce21\uce58 \uac1c\uc218 \ud30c\uc545\n# \uc140 \uc2e4\ud589 \uacb0\uacfc\ub97c \ub370\uc774\ud130\ud504\ub808\uc784\uc73c\ub85c \ubcf4\uace0 \uc2f6\uc744 \ub54c to_frame()\uacfc pd.DataFrame() \ub450 \uac00\uc9c0\ub97c \uc0ac\uc6a9 \uac00\ub2a5\ndf.isnull().sum().to_frame('nan_count')\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>nan_count</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>subj</th>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>roi</th>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>cond</th>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>ll</th>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>item</th>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>comp1</th>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>comp2</th>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>z</th>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>rd_ll</th>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>rd_cond</th>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>Zr_1</th>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>Zr_2</th>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>Zr_s</th>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>Zr_m</th>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>b_1</th>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>b_2</th>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>b_s</th>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>b_m</th>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>Zr_wm</th>\n      <td>38016</td>\n    </tr>\n    <tr>\n      <th>b_wm</th>\n      <td>38016</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\npd.DataFrame(data=df.isnull().sum()/len(df),columns=['nan_ratio'])\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>nan_ratio</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>subj</th>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>roi</th>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>cond</th>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>ll</th>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>item</th>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>comp1</th>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>comp2</th>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>z</th>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>rd_ll</th>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>rd_cond</th>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>Zr_1</th>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>Zr_2</th>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>Zr_s</th>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>Zr_m</th>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>b_1</th>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>b_2</th>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>b_s</th>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>b_m</th>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>Zr_wm</th>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>b_wm</th>\n      <td>1.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf['subj'].value_counts()\n```\n\n\n\n\n    1     1584\n    2     1584\n    98    1584\n    97    1584\n    96    1584\n    94    1584\n    20    1584\n    19    1584\n    18    1584\n    17    1584\n    16    1584\n    13    1584\n    15    1584\n    14    1584\n    12    1584\n    11    1584\n    10    1584\n    9     1584\n    8     1584\n    7     1584\n    6     1584\n    5     1584\n    3     1584\n    99    1584\n    Name: subj, dtype: int64\n\n\n\n\n```python\ndf['roi'].unique()\n```\n\n\n\n\n    array(['loc', 'lloc', 'rloc', 'pf', 'lpf', 'rpf', 'bhpp', 'lhpp', 'rhpp',\n           'a_hpp', 'p_hpp', 'mpfc'], dtype=object)\n\n\n\n\n```python\ndf.info()\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 38016 entries, 0 to 38015\n    Data columns (total 20 columns):\n     #   Column   Non-Null Count  Dtype  \n    ---  ------   --------------  -----  \n     0   subj     38016 non-null  int64  \n     1   roi      38016 non-null  object \n     2   cond     38016 non-null  int64  \n     3   ll       38016 non-null  int64  \n     4   item     38016 non-null  int64  \n     5   comp1    38016 non-null  int64  \n     6   comp2    38016 non-null  int64  \n     7   z        38016 non-null  float64\n     8   rd_ll    38016 non-null  float64\n     9   rd_cond  38016 non-null  float64\n     10  Zr_1     38016 non-null  float64\n     11  Zr_2     38016 non-null  float64\n     12  Zr_s     38016 non-null  float64\n     13  Zr_m     38016 non-null  float64\n     14  b_1      38016 non-null  float64\n     15  b_2      38016 non-null  float64\n     16  b_s      38016 non-null  float64\n     17  b_m      38016 non-null  float64\n     18  Zr_wm    0 non-null      float64\n     19  b_wm     0 non-null      float64\n    dtypes: float64(13), int64(6), object(1)\n    memory usage: 5.8+ MB\n\n\n\n```python\n# \ubc94\uc8fc\ud615\uc774\uc9c0\ub9cc \uc5f0\uc18d\ud615(int64)\uc73c\ub85c \uc124\uc815\ub418\uc5b4\uc788\ub294 \uacbd\uc6b0 string\uc73c\ub85c \ubc14\uafd4\uc8fc\uae30\ndf['subj']=df['subj'].astype(str)\ndf['cond']=df['cond'].astype(str)\ndf['ll']=df['ll'].astype(str)\ndf['item']=df['item'].astype(str)\ndf['comp1']=df['comp1'].astype(str)\ndf['comp2']=df['comp2'].astype(str)\ndf.dtypes \n```\n\n\n\n\n    subj        object\n    roi         object\n    cond        object\n    ll          object\n    item        object\n    comp1       object\n    comp2       object\n    z          float64\n    rd_ll      float64\n    rd_cond    float64\n    Zr_1       float64\n    Zr_2       float64\n    Zr_s       float64\n    Zr_m       float64\n    b_1        float64\n    b_2        float64\n    b_s        float64\n    b_m        float64\n    Zr_wm      float64\n    b_wm       float64\n    dtype: object\n\n\n\n### Preprocessing\n\n* **tidyverse style pandas**\n    * **tidyr - pandas**\n        * mutate - assign\n        * select - filter\n        * rename - rename\n        * filter - query\n        * arrange - sort_values\n        * group_by - groupby\n        * summarize - agg\n        * gather - melt\n        * spread - pivot\n\n\n```python\ndf.describe(include='all')\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>subj</th>\n      <th>roi</th>\n      <th>cond</th>\n      <th>ll</th>\n      <th>item</th>\n      <th>comp1</th>\n      <th>comp2</th>\n      <th>z</th>\n      <th>rd_ll</th>\n      <th>rd_cond</th>\n      <th>Zr_1</th>\n      <th>Zr_2</th>\n      <th>Zr_s</th>\n      <th>Zr_m</th>\n      <th>b_1</th>\n      <th>b_2</th>\n      <th>b_s</th>\n      <th>b_m</th>\n      <th>Zr_wm</th>\n      <th>b_wm</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>38016</td>\n      <td>38016</td>\n      <td>38016</td>\n      <td>38016</td>\n      <td>38016</td>\n      <td>38016</td>\n      <td>38016</td>\n      <td>38016.000000</td>\n      <td>38016.000000</td>\n      <td>38016.000000</td>\n      <td>38016.000000</td>\n      <td>38016.000000</td>\n      <td>38016.000000</td>\n      <td>38016.000000</td>\n      <td>38016.000000</td>\n      <td>38016.000000</td>\n      <td>38016.000000</td>\n      <td>38016.000000</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>unique</th>\n      <td>24</td>\n      <td>12</td>\n      <td>2</td>\n      <td>4</td>\n      <td>264</td>\n      <td>19</td>\n      <td>19</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>top</th>\n      <td>1</td>\n      <td>loc</td>\n      <td>1</td>\n      <td>1</td>\n      <td>20203</td>\n      <td>1</td>\n      <td>14</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>freq</th>\n      <td>1584</td>\n      <td>3168</td>\n      <td>19008</td>\n      <td>9504</td>\n      <td>216</td>\n      <td>6312</td>\n      <td>4056</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.268370</td>\n      <td>0.890519</td>\n      <td>0.891206</td>\n      <td>0.077718</td>\n      <td>0.077431</td>\n      <td>0.077574</td>\n      <td>0.096636</td>\n      <td>0.046737</td>\n      <td>0.046192</td>\n      <td>0.046465</td>\n      <td>0.095144</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.633812</td>\n      <td>0.144079</td>\n      <td>0.142009</td>\n      <td>0.210166</td>\n      <td>0.210233</td>\n      <td>0.178061</td>\n      <td>0.223164</td>\n      <td>0.159033</td>\n      <td>0.162393</td>\n      <td>0.112774</td>\n      <td>0.229099</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>-5.375781</td>\n      <td>0.275210</td>\n      <td>0.295550</td>\n      <td>-1.166095</td>\n      <td>-1.129066</td>\n      <td>-0.895102</td>\n      <td>-1.154292</td>\n      <td>-1.015663</td>\n      <td>-1.378982</td>\n      <td>-0.683348</td>\n      <td>-1.369066</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>-0.093046</td>\n      <td>0.843164</td>\n      <td>0.846574</td>\n      <td>-0.051240</td>\n      <td>-0.051194</td>\n      <td>-0.030740</td>\n      <td>-0.041172</td>\n      <td>-0.047971</td>\n      <td>-0.047607</td>\n      <td>-0.022167</td>\n      <td>-0.044297</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.206467</td>\n      <td>0.941848</td>\n      <td>0.944719</td>\n      <td>0.057624</td>\n      <td>0.055460</td>\n      <td>0.050731</td>\n      <td>0.067215</td>\n      <td>0.037029</td>\n      <td>0.036473</td>\n      <td>0.034590</td>\n      <td>0.070366</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.574504</td>\n      <td>0.983062</td>\n      <td>0.982577</td>\n      <td>0.185612</td>\n      <td>0.186247</td>\n      <td>0.159385</td>\n      <td>0.208060</td>\n      <td>0.129384</td>\n      <td>0.129994</td>\n      <td>0.104299</td>\n      <td>0.211549</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>4.492980</td>\n      <td>1.302216</td>\n      <td>1.291541</td>\n      <td>1.210359</td>\n      <td>1.481196</td>\n      <td>1.009792</td>\n      <td>1.182038</td>\n      <td>1.132774</td>\n      <td>1.357869</td>\n      <td>0.687433</td>\n      <td>1.689432</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf2 = (df\n .filter(['subj', 'roi', 'cond', 'item', 'z', 'b_m', 'rd_ll'])\n .query('roi == \"loc\" | roi == \"pf\"')\n .rename(columns={'subj':'sn', 'cond':'con', 'z':'Z', 'b_m':'beta', 'rd_ll':'Zr_n'}))\ndf2['con'] = df2['con'].replace(['1','2'], ['cons','imm'])\n```\n\n\n```python\ndf2.info()\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    Int64Index: 6336 entries, 0 to 36959\n    Data columns (total 7 columns):\n     #   Column  Non-Null Count  Dtype  \n    ---  ------  --------------  -----  \n     0   sn      6336 non-null   object \n     1   roi     6336 non-null   object \n     2   con     6336 non-null   object \n     3   item    6336 non-null   object \n     4   Z       6336 non-null   float64\n     5   beta    6336 non-null   float64\n     6   Zr_n    6336 non-null   float64\n    dtypes: float64(3), object(4)\n    memory usage: 396.0+ KB\n\n\n#### Long Format\n\n\n```python\nZ_long = (df2\n          .filter(['sn', 'roi', 'con', 'Z'])\n          .groupby(['sn', 'roi', 'con'])\n          .agg({'Z': ['mean', 'std', 'count']}))\n\nbeta_long = (df2\n             .filter(['sn', 'roi', 'con', 'beta'])\n             .groupby(['sn', 'roi', 'con'])\n             .agg({'beta': ['mean', 'std', 'count']}))\n\nZr_long = (df2\n           .filter(['sn', 'roi', 'con', 'Zr_n'])\n           .assign(Zr=lambda x: 1-x.Zr_n)\n           .filter(['sn', 'roi', 'con', 'Zr'])\n           .groupby(['sn', 'roi', 'con'])\n           .agg({'Zr': ['mean', 'std', 'count']}))\n```\n\n\n```python\nprint(Z_long.head(4))\nprint(beta_long.head(4))\nprint(Zr_long.head(4))\n```\n\n                        Z                \n                     mean       std count\n    sn roi con                           \n    1  loc cons  1.085557  0.591436    66\n           imm   0.895288  0.540499    66\n       pf  cons  0.406269  0.351890    66\n           imm   0.324837  0.348329    66\n                     beta                \n                     mean       std count\n    sn roi con                           \n    1  loc cons  0.394441  0.261579    66\n           imm   0.288257  0.251469    66\n       pf  cons  0.079983  0.161896    66\n           imm   0.074869  0.179356    66\n                       Zr                \n                     mean       std count\n    sn roi con                           \n    1  loc cons  0.441953  0.091241    66\n           imm   0.379559  0.099872    66\n       pf  cons  0.122856  0.070878    66\n           imm   0.105637  0.067683    66\n\n\n#### Wide Format\n\n\n```python\nZ_wide = (Z_long['Z'].reset_index()\n .filter(['sn','roi', 'con', 'mean'])\n .rename(columns={'mean':'Z'})\n .pivot(index=['sn','roi'], columns='con', values='Z'))\n\nbeta_wide = (beta_long['beta'].reset_index()\n .filter(['sn','roi', 'con', 'mean'])\n .rename(columns={'mean':'beta'})\n .pivot(index=['sn','roi'], columns='con', values='beta'))\n\nZr_wide = (Zr_long['Zr'].reset_index()\n .filter(['sn','roi', 'con', 'mean'])\n .rename(columns={'mean':'Zr'})\n .pivot(index=['sn','roi'], columns='con', values='Zr'))\n\n```\n\n\n```python\nprint(Z_wide.head(4))\nprint(beta_wide.head(4))\nprint(Zr_wide.head(4))\n```\n\n    con         cons       imm\n    sn roi                    \n    1  loc  1.085557  0.895288\n       pf   0.406269  0.324837\n    10 loc  0.455391  0.460376\n       pf   0.220089  0.291423\n    con         cons       imm\n    sn roi                    \n    1  loc  0.394441  0.288257\n       pf   0.079983  0.074869\n    10 loc  0.124292  0.134956\n       pf   0.041539  0.070503\n    con         cons       imm\n    sn roi                    \n    1  loc  0.441953  0.379559\n       pf   0.122856  0.105637\n    10 loc  0.162410  0.146782\n       pf   0.070441  0.061856\n\n\n#### Outlier Handling\n\n\n```python\ndf2_Z = (df2\n         .filter(['sn', 'roi', 'con', 'Z']))\ndf2_beta = (df2\n         .filter(['sn', 'roi', 'con', 'beta']))\ndf2_Zr = (df2\n          .filter(['sn', 'roi', 'con', 'Zr_n'])\n          .assign(Zr=lambda x: 1-x.Zr_n)\n          .filter(['sn','roi','con','Zr']))\n```\n\n\n```python\nprint(df2_Z.head(2))\nprint(df2_beta.head(2))\nprint(df2_Zr.head(2))\n```\n\n      sn  roi   con         Z\n    0  1  loc  cons  0.667815\n    1  1  loc  cons  0.873861\n      sn  roi   con      beta\n    0  1  loc  cons  0.130898\n    1  1  loc  cons  0.387839\n      sn  roi   con        Zr\n    0  1  loc  cons  0.216303\n    1  1  loc  cons  0.504231\n\n\n\n```python\n# df2_Z_outliers = (df2_Z\n#                   .groupby(['sn','roi'])\n#                   .Z.transform(lambda x : (x<x.quantile(0.95))&(x>(x.quantile(0.05)))).eq(0))\ndf2_Z_outliers = (df2_Z\n                  .groupby(['sn','roi'])\n                  .Z.transform(lambda x : (x<np.mean(x)+np.std(x)*2)&(x>np.mean(x)-np.std(x)*2)).eq(0))\n\ndf2_Z_outliers = df2_Z_outliers.to_frame().rename(columns={'Z':'out'})\ndf2_Z = pd.concat([df2_Z, df2_Z_outliers], axis=1)\n\n# df2_beta_outliers = (df2_beta\n#                      .groupby(['sn','roi'])\n#                      .beta.transform(lambda x : (x<x.quantile(0.95))&(x>(x.quantile(0.05)))).eq(0))\ndf2_beta_outliers = (df2_beta\n                  .groupby(['sn','roi'])\n                  .beta.transform(lambda x : (x<np.mean(x)+np.std(x)*2)&(x>np.mean(x)-np.std(x)*2)).eq(0))\n\ndf2_beta_outliers = df2_beta_outliers.to_frame().rename(columns={'beta':'out'})\ndf2_beta = pd.concat([df2_beta, df2_beta_outliers], axis=1)\n\n# df2_Zr_outliers = (df2_Zr\n#                    .groupby(['sn','roi'])\n#                    .Zr.transform(lambda x : (x<x.quantile(0.95))&(x>(x.quantile(0.05)))).eq(0))\ndf2_Zr_outliers = (df2_Zr\n                  .groupby(['sn','roi'])\n                  .Zr.transform(lambda x : (x<np.mean(x)+np.std(x)*2)&(x>np.mean(x)-np.std(x)*2)).eq(0))\n\ndf2_Zr_outliers = df2_Zr_outliers.to_frame().rename(columns={'Zr':'out'})\ndf2_Zr = pd.concat([df2_Zr, df2_Zr_outliers], axis=1)\n```\n\n\n```python\nprint('*Z\\n',df2_Z.out.value_counts())\nprint('*beta\\n',df2_beta.out.value_counts())\nprint('*Zr\\n',df2_Zr.out.value_counts())\n```\n\n    *Z\n     False    6036\n    True      300\n    Name: out, dtype: int64\n    *beta\n     False    6012\n    True      324\n    Name: out, dtype: int64\n    *Zr\n     False    6058\n    True      278\n    Name: out, dtype: int64\n\n\n\n```python\nZ_long = (df2_Z\n          .filter(['sn', 'roi', 'con', 'Z'])\n          .groupby(['sn', 'roi', 'con'])\n          .agg({'Z': ['mean', 'std', 'count']}))\n\nbeta_long = (df2_beta\n             .filter(['sn', 'roi', 'con', 'beta'])\n             .groupby(['sn', 'roi', 'con'])\n             .agg({'beta': ['mean', 'std', 'count']}))\n\nZr_long = (df2_Zr\n           .filter(['sn', 'roi', 'con', 'Zr'])\n           .groupby(['sn', 'roi', 'con'])\n           .agg({'Zr': ['mean', 'std', 'count']}))\n```\n\n### Summarize\n\n#### Activation\n\n\n```python\nZ_G = (Z_long['Z'].reset_index()\n       .filter(['sn', 'roi', 'con', 'mean'])\n       .rename(columns={'mean': 'Z'})\n       .groupby(['roi', 'con'])\n       .agg({'Z': ['mean', 'std', 'sem']}))\n\nZ_long_cons = (Z_long['Z'].reset_index()\n               .filter(['sn', 'roi', 'con', 'mean'])\n               .rename(columns={'mean': 'Z'})\n               .query('con ==\"cons\"'))\nZ_long_imm = (Z_long['Z'].reset_index()\n              .filter(['sn', 'roi', 'con', 'mean'])\n              .rename(columns={'mean': 'Z'})\n              .query('con ==\"imm\"'))\n\nci = pd.DataFrame([stats.t.interval(alpha=0.95,\n                                    df=len(\n                                        Z_long_cons[Z_long_cons['roi'] == 'loc'])-1,\n                                    loc=np.mean(\n                                        Z_long_cons[Z_long_cons['roi'] == 'loc'].Z),\n                                    scale=stats.sem(Z_long_cons[Z_long_cons['roi'] == 'loc'].Z)),\n                   stats.t.interval(alpha=0.95, df=len(Z_long_imm[Z_long_imm['roi'] == 'loc'])-1,\n                                    loc=np.mean(\n                                        Z_long_imm[Z_long_imm['roi'] == 'loc'].Z),\n                                    scale=stats.sem(Z_long_imm[Z_long_imm['roi'] == 'loc'].Z)),\n                   stats.t.interval(alpha=0.95,\n                                    df=len(\n                                        Z_long_cons[Z_long_cons['roi'] == 'pf'])-1,\n                                    loc=np.mean(\n                                        Z_long_cons[Z_long_cons['roi'] == 'pf'].Z),\n                                    scale=stats.sem(Z_long_cons[Z_long_cons['roi'] == 'pf'].Z)),\n                   stats.t.interval(alpha=0.95, df=len(Z_long_imm[Z_long_imm['roi'] == 'pf'])-1,\n                                    loc=np.mean(\n                                        Z_long_imm[Z_long_imm['roi'] == 'pf'].Z),\n                                    scale=stats.sem(Z_long_imm[Z_long_imm['roi'] == 'pf'].Z))\n                   ])\n\nZ_G = pd.concat([Z_G.Z.reset_index(), ci], axis=1)  # column bind\nZ_G = (Z_G\n       .rename(columns={0: '95ci_hi', 1: '95ci_lo'}))\nZ_G\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>roi</th>\n      <th>con</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>sem</th>\n      <th>95ci_hi</th>\n      <th>95ci_lo</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>loc</td>\n      <td>cons</td>\n      <td>0.744149</td>\n      <td>0.339561</td>\n      <td>0.069313</td>\n      <td>0.600765</td>\n      <td>0.887533</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>loc</td>\n      <td>imm</td>\n      <td>0.703449</td>\n      <td>0.343071</td>\n      <td>0.070029</td>\n      <td>0.558583</td>\n      <td>0.848315</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>pf</td>\n      <td>cons</td>\n      <td>0.247465</td>\n      <td>0.182439</td>\n      <td>0.037240</td>\n      <td>0.170428</td>\n      <td>0.324502</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>pf</td>\n      <td>imm</td>\n      <td>0.232592</td>\n      <td>0.189177</td>\n      <td>0.038616</td>\n      <td>0.152710</td>\n      <td>0.312475</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n#### Beta\n\n\n```python\nbeta_G = (beta_long['beta'].reset_index()\n          .filter(['sn', 'roi', 'con', 'mean'])\n          .rename(columns={'mean': 'beta'})\n          .groupby(['roi', 'con'])\n          .agg({'beta': ['mean', 'std', 'sem']}))\n\nbeta_long_cons = (beta_long['beta'].reset_index()\n                  .filter(['sn', 'roi', 'con', 'mean'])\n                  .rename(columns={'mean': 'beta'})\n                  .query('con ==\"cons\"'))\nbeta_long_imm = (beta_long['beta'].reset_index()\n                 .filter(['sn', 'roi', 'con', 'mean'])\n                 .rename(columns={'mean': 'beta'})\n                 .query('con ==\"imm\"'))\n\nci = pd.DataFrame([stats.t.interval(alpha=0.95,\n                                    df=len(\n                                        beta_long_cons[beta_long_cons['roi'] == 'loc'])-1,\n                                    loc=np.mean(\n                                        beta_long_cons[beta_long_cons['roi'] == 'loc'].beta),\n                                    scale=stats.sem(beta_long_cons[beta_long_cons['roi'] == 'loc'].beta)),\n                   stats.t.interval(alpha=0.95, df=len(beta_long_imm[beta_long_imm['roi'] == 'loc'])-1,\n                                    loc=np.mean(\n                                        beta_long_imm[beta_long_imm['roi'] == 'loc'].beta),\n                                    scale=stats.sem(beta_long_imm[beta_long_imm['roi'] == 'loc'].beta)),\n                   stats.t.interval(alpha=0.95,\n                                    df=len(\n                                        beta_long_cons[beta_long_cons['roi'] == 'pf'])-1,\n                                    loc=np.mean(\n                                        beta_long_cons[beta_long_cons['roi'] == 'pf'].beta),\n                                    scale=stats.sem(beta_long_cons[beta_long_cons['roi'] == 'pf'].beta)),\n                   stats.t.interval(alpha=0.95, df=len(beta_long_imm[beta_long_imm['roi'] == 'pf'])-1,\n                                    loc=np.mean(\n                                        beta_long_imm[beta_long_imm['roi'] == 'pf'].beta),\n                                    scale=stats.sem(beta_long_imm[beta_long_imm['roi'] == 'pf'].beta))\n                   ])\nbeta_G = pd.concat([beta_G.beta.reset_index(), ci], axis=1)  # column bind\nbeta_G = (beta_G\n          .rename(columns={0: '95ci_hi', 1: '95ci_lo'}))\nbeta_G\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>roi</th>\n      <th>con</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>sem</th>\n      <th>95ci_hi</th>\n      <th>95ci_lo</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>loc</td>\n      <td>cons</td>\n      <td>0.284502</td>\n      <td>0.136095</td>\n      <td>0.027780</td>\n      <td>0.227034</td>\n      <td>0.341970</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>loc</td>\n      <td>imm</td>\n      <td>0.260502</td>\n      <td>0.128566</td>\n      <td>0.026243</td>\n      <td>0.206213</td>\n      <td>0.314790</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>pf</td>\n      <td>cons</td>\n      <td>0.093906</td>\n      <td>0.075034</td>\n      <td>0.015316</td>\n      <td>0.062221</td>\n      <td>0.125590</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>pf</td>\n      <td>imm</td>\n      <td>0.085180</td>\n      <td>0.071422</td>\n      <td>0.014579</td>\n      <td>0.055021</td>\n      <td>0.115339</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n#### Zr\n\n\n```python\nZr_G = (Zr_long['Zr'].reset_index()\n        .filter(['sn', 'roi', 'con', 'mean'])\n        .rename(columns={'mean': 'Zr'})\n        .groupby(['roi', 'con'])\n        .agg({'Zr': ['mean', 'std', 'sem']}))\n\nZr_long_cons = (Zr_long['Zr'].reset_index()\n                .filter(['sn', 'roi', 'con', 'mean'])\n                .rename(columns={'mean': 'Zr'})\n                .query('con ==\"cons\"'))\nZr_long_imm = (Zr_long['Zr'].reset_index()\n               .filter(['sn', 'roi', 'con', 'mean'])\n               .rename(columns={'mean': 'Zr'})\n               .query('con ==\"imm\"'))\n\nci = pd.DataFrame([stats.t.interval(alpha=0.95,\n                                    df=len(\n                                        Zr_long_cons[Zr_long_cons['roi'] == 'loc'])-1,\n                                    loc=np.mean(\n                                        Zr_long_cons[Zr_long_cons['roi'] == 'loc'].Zr),\n                                    scale=stats.sem(Zr_long_cons[Zr_long_cons['roi'] == 'loc'].Zr)),\n                   stats.t.interval(alpha=0.95, df=len(Zr_long_imm[Zr_long_imm['roi'] == 'loc'])-1,\n                                    loc=np.mean(\n                                        Zr_long_imm[Zr_long_imm['roi'] == 'loc'].Zr),\n                                    scale=stats.sem(Zr_long_imm[Zr_long_imm['roi'] == 'loc'].Zr)),\n                   stats.t.interval(alpha=0.95,\n                                    df=len(\n                                        Zr_long_cons[Zr_long_cons['roi'] == 'pf'])-1,\n                                    loc=np.mean(\n                                        Zr_long_cons[Zr_long_cons['roi'] == 'pf'].Zr),\n                                    scale=stats.sem(Zr_long_cons[Zr_long_cons['roi'] == 'pf'].Zr)),\n                   stats.t.interval(alpha=0.95, df=len(Zr_long_imm[Zr_long_imm['roi'] == 'pf'])-1,\n                                    loc=np.mean(\n                                        Zr_long_imm[Zr_long_imm['roi'] == 'pf'].Zr),\n                                    scale=stats.sem(Zr_long_imm[Zr_long_imm['roi'] == 'pf'].Zr))\n                   ])\nZr_G = pd.concat([Zr_G.Zr.reset_index(), ci], axis=1)  # column bind\nZr_G = (Zr_G\n        .rename(columns={0: '95ci_hi', 1: '95ci_lo'}))\nZr_G\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>roi</th>\n      <th>con</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>sem</th>\n      <th>95ci_hi</th>\n      <th>95ci_lo</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>loc</td>\n      <td>cons</td>\n      <td>0.296430</td>\n      <td>0.135909</td>\n      <td>0.027742</td>\n      <td>0.239041</td>\n      <td>0.353819</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>loc</td>\n      <td>imm</td>\n      <td>0.277132</td>\n      <td>0.128406</td>\n      <td>0.026211</td>\n      <td>0.222910</td>\n      <td>0.331353</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>pf</td>\n      <td>cons</td>\n      <td>0.103879</td>\n      <td>0.067542</td>\n      <td>0.013787</td>\n      <td>0.075359</td>\n      <td>0.132400</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>pf</td>\n      <td>imm</td>\n      <td>0.093853</td>\n      <td>0.058852</td>\n      <td>0.012013</td>\n      <td>0.069002</td>\n      <td>0.118704</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n#### Plotting\n\n\n```python\ndf_01 = (Z_long['Z'].reset_index()\n         .rename(columns={'mean':'Z'}))\ndf_02 = (beta_long['beta'].reset_index()\n         .rename(columns={'mean':'beta'}))\ndf_03 = (Zr_long['Zr'].reset_index()\n         .rename(columns={'mean':'Zr'}))\ndf_all = pd.merge(df_01, df_02, how='inner', on=['sn','roi','con'])\ndf_all = pd.merge(df_all, df_03, how='inner', on=['sn','roi','con'])\ndf_all = (df_all\n          .filter(['sn','roi','con','Z','beta','Zr']))\n#df_all \n```\n\n\n```python\n\nfig, axes = plt.subplots(nrows = 2, ncols=3, figsize=(18, 12))\nsns.kdeplot(data=Z_long['Z'].reset_index(), x=\"mean\", hue=\"con\", ax=axes[0,0])\nsns.kdeplot(data=beta_long['beta'].reset_index(), x=\"mean\", hue=\"con\", ax=axes[0,1])\nsns.kdeplot(data=Zr_long['Zr'].reset_index(), x=\"mean\", hue=\"con\", ax=axes[0,2])\n# sns.lmplot(data=df_all, x=\"Z\", y=\"beta\", hue=\"con\", ax=axes[1,0])\n# sns.lmplot(data=df_all, x=\"Z\", y=\"Zr\", hue=\"con\", ax=axes[1,1])\n# sns.lmplot(data=df_all, x=\"beta\", y=\"Zr\", hue=\"con\", ax=axes[1,2])\nsns.scatterplot(data=df_all, x=\"Z\", y=\"beta\", hue=\"con\", ax=axes[1,0])\nsns.scatterplot(data=df_all, x=\"Z\", y=\"Zr\", hue=\"con\", ax=axes[1,1])\nsns.scatterplot(data=df_all, x=\"beta\", y=\"Zr\", hue=\"con\", ax=axes[1,2])\n#sns.stripplot(data=df_all, x=\"con\", y=\"Z\", hue=\"con\", ax=axes[2,0])\n#sns.boxplot(data=df_all, x=\"con\", y=\"Z\", hue=\"con\", dodge=False, ax=axes[2,0])\n#sns.boxplot(data=df_all, x=\"con\", y=\"beta\", hue=\"con\",dodge=False, ax=axes[2,1])\n#sns.boxplot(data=df_all, x=\"con\", y=\"Zr\", hue=\"con\", dodge=False,ax=axes[2,2])\nplt.tight_layout()\nplt.show()\n```\n\n\n```python\ng1 = sns.catplot(data=df_all, x=\"con\", y=\"Z\", hue=\"con\", col = \"roi\", kind='boxen', dodge=False)\ng2 = sns.catplot(data=df_all, x=\"con\", y=\"beta\", hue=\"con\", col = \"roi\", kind='boxen', dodge=False)\ng3 = sns.catplot(data=df_all, x=\"con\", y=\"Zr\", hue=\"con\", col = \"roi\", kind='boxen', dodge=False)\nplt.tight_layout()\nplt.show()\n```\n\n## Statistical Test - rmANOVA & Post-hoc\n\n### Assumption Check\n\n\n```python\npg.homoscedasticity(data=Z_long.Z.reset_index(), dv='mean', group='con',\n                   method='levene')\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>W</th>\n      <th>pval</th>\n      <th>equal_var</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>levene</th>\n      <td>0.005552</td>\n      <td>0.940762</td>\n      <td>True</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nspher, W, chisq, dof, pval = pg.sphericity(data=Z_long.Z.reset_index(), dv='mean', \n              subject='sn', within=['roi','con'], method='mauchly')\nprint(spher, round(W, 3), round(chisq, 3), dof, round(pval, 3))\n```\n\n    True nan nan 1 1.0\n\n\n\n```python\npg.normality(data=Z_long.Z.reset_index(), dv='mean', group='con',\n            method='normaltest') # shapiro\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>W</th>\n      <th>pval</th>\n      <th>normal</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>cons</th>\n      <td>5.957387</td>\n      <td>0.050859</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>imm</th>\n      <td>3.612369</td>\n      <td>0.164280</td>\n      <td>True</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### Object-ness - Activation\n\n\n```python\naov = pg.rm_anova(dv='mean', within=['roi','con'],\n                   subject='sn', data=Z_long.Z.reset_index(), detailed=True)\naov.round(3)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Source</th>\n      <th>SS</th>\n      <th>ddof1</th>\n      <th>ddof2</th>\n      <th>MS</th>\n      <th>F</th>\n      <th>p-unc</th>\n      <th>p-GG-corr</th>\n      <th>np2</th>\n      <th>eps</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>roi</td>\n      <td>5.617</td>\n      <td>1</td>\n      <td>23</td>\n      <td>5.617</td>\n      <td>63.311</td>\n      <td>0.000</td>\n      <td>0.000</td>\n      <td>0.734</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>con</td>\n      <td>0.019</td>\n      <td>1</td>\n      <td>23</td>\n      <td>0.019</td>\n      <td>2.394</td>\n      <td>0.135</td>\n      <td>0.135</td>\n      <td>0.094</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>roi * con</td>\n      <td>0.004</td>\n      <td>1</td>\n      <td>23</td>\n      <td>0.004</td>\n      <td>3.051</td>\n      <td>0.094</td>\n      <td>0.094</td>\n      <td>0.117</td>\n      <td>1.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nfig, axes = plt.subplots(ncols=2, figsize=(12, 4))\nsns.pointplot(x=\"roi\", y=\"mean\", hue=\"con\",\n                    data=Z_long.Z.reset_index(), ax=axes[0])\nsns.pointplot(x=\"con\", y=\"mean\", hue=\"roi\",\n                    data=Z_long.Z.reset_index(), ax=axes[1])\nplt.tight_layout()\nplt.show()\n```\n\n\n```python\n#targ_df = Z_long.Z.reset_index()\n# loc_z = targ_df[targ_df['roi']=='loc'].pairwise_tukey(dv='mean', between='con').round(3)\n# loc_z['roi'] = 'loc'\n# pf_z =  targ_df[targ_df['roi']=='pf'].pairwise_tukey(dv='mean', between='con').round(3)\n# pf_z['roi'] = 'pf'\n# pd.concat([loc_z, pf_z], axis=0)\n\ntarg_df = Z_long.Z.reset_index()\nloc_z = (targ_df[targ_df['roi']=='loc']\n          .pairwise_ttests(dv='mean', within='con', subject='sn', \n                           parametric=True, padjust='bonf', effsize = 'cohen',\n                           return_desc=True)\n          .round(3))\nloc_z['roi'] = 'loc'\npf_z = (targ_df[targ_df['roi']=='pf']\n          .pairwise_ttests(dv='mean', within='con', subject='sn', \n                           parametric=True, padjust='bonf', effsize = 'cohen',\n                           return_desc=True)\n          .round(3))\npf_z['roi'] = 'pf'\nprint_table(pd.concat([loc_z, pf_z], axis=0)\n```\n\n### Constituent Explainability - Beta\n\n\n```python\naov = pg.rm_anova(dv='mean', within=['roi','con'],\n                   subject='sn', data=beta_long.beta.reset_index(), detailed=True)\naov.round(3)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Source</th>\n      <th>SS</th>\n      <th>ddof1</th>\n      <th>ddof2</th>\n      <th>MS</th>\n      <th>F</th>\n      <th>p-unc</th>\n      <th>p-GG-corr</th>\n      <th>np2</th>\n      <th>eps</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>roi</td>\n      <td>0.803</td>\n      <td>1</td>\n      <td>23</td>\n      <td>0.803</td>\n      <td>58.053</td>\n      <td>0.000</td>\n      <td>0.000</td>\n      <td>0.716</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>con</td>\n      <td>0.006</td>\n      <td>1</td>\n      <td>23</td>\n      <td>0.006</td>\n      <td>8.372</td>\n      <td>0.008</td>\n      <td>0.008</td>\n      <td>0.267</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>roi * con</td>\n      <td>0.001</td>\n      <td>1</td>\n      <td>23</td>\n      <td>0.001</td>\n      <td>7.416</td>\n      <td>0.012</td>\n      <td>0.012</td>\n      <td>0.244</td>\n      <td>1.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nfig, axes = plt.subplots(ncols=2, figsize=(12, 4))\nsns.pointplot(x=\"roi\", y=\"mean\", hue=\"con\",\n                    data=beta_long.beta.reset_index(), ax=axes[0])\nsns.pointplot(x=\"con\", y=\"mean\", hue=\"roi\",\n                    data=beta_long.beta.reset_index(), ax=axes[1])\nplt.tight_layout()\nplt.show()\n```\n\n\n```python\ntarg_df = beta_long.beta.reset_index()\nloc_beta = (targ_df[targ_df['roi']=='loc']\n          .pairwise_ttests(dv='mean', within='con', subject='sn', \n                           parametric=True, padjust='bonf', effsize = 'cohen',\n                           return_desc=True)\n          .round(3))\nloc_beta['roi'] = 'loc'\npf_beta = (targ_df[targ_df['roi']=='pf']\n          .pairwise_ttests(dv='mean', within='con', subject='sn', \n                           parametric=True, padjust='bonf', effsize = 'cohen',\n                           return_desc=True)\n          .round(3))\npf_beta['roi'] = 'pf'\npd.concat([loc_beta, pf_beta], axis=0)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Contrast</th>\n      <th>A</th>\n      <th>B</th>\n      <th>mean(A)</th>\n      <th>std(A)</th>\n      <th>mean(B)</th>\n      <th>std(B)</th>\n      <th>Paired</th>\n      <th>Parametric</th>\n      <th>T</th>\n      <th>dof</th>\n      <th>alternative</th>\n      <th>p-unc</th>\n      <th>BF10</th>\n      <th>cohen</th>\n      <th>roi</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>con</td>\n      <td>cons</td>\n      <td>imm</td>\n      <td>0.285</td>\n      <td>0.136</td>\n      <td>0.261</td>\n      <td>0.129</td>\n      <td>True</td>\n      <td>True</td>\n      <td>3.320</td>\n      <td>23.0</td>\n      <td>two-sided</td>\n      <td>0.003</td>\n      <td>13.554</td>\n      <td>0.181</td>\n      <td>loc</td>\n    </tr>\n    <tr>\n      <th>0</th>\n      <td>con</td>\n      <td>cons</td>\n      <td>imm</td>\n      <td>0.094</td>\n      <td>0.075</td>\n      <td>0.085</td>\n      <td>0.071</td>\n      <td>True</td>\n      <td>True</td>\n      <td>1.666</td>\n      <td>23.0</td>\n      <td>two-sided</td>\n      <td>0.109</td>\n      <td>0.714</td>\n      <td>0.119</td>\n      <td>pf</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### Representational Similarity - Zr\n\n\n```python\naov = pg.rm_anova(dv='mean', within=['roi','con'],\n                   subject='sn', data=Zr_long.Zr.reset_index(), detailed=True)\naov.round(3)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Source</th>\n      <th>SS</th>\n      <th>ddof1</th>\n      <th>ddof2</th>\n      <th>MS</th>\n      <th>F</th>\n      <th>p-unc</th>\n      <th>p-GG-corr</th>\n      <th>np2</th>\n      <th>eps</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>roi</td>\n      <td>0.847</td>\n      <td>1</td>\n      <td>23</td>\n      <td>0.847</td>\n      <td>67.664</td>\n      <td>0.000</td>\n      <td>0.000</td>\n      <td>0.746</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>con</td>\n      <td>0.005</td>\n      <td>1</td>\n      <td>23</td>\n      <td>0.005</td>\n      <td>12.181</td>\n      <td>0.002</td>\n      <td>0.002</td>\n      <td>0.346</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>roi * con</td>\n      <td>0.001</td>\n      <td>1</td>\n      <td>23</td>\n      <td>0.001</td>\n      <td>3.134</td>\n      <td>0.090</td>\n      <td>0.090</td>\n      <td>0.120</td>\n      <td>1.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nfig, axes = plt.subplots(ncols=2, figsize=(12, 4))\nsns.pointplot(x=\"roi\", y=\"mean\", hue=\"con\",\n                    data=Zr_long.Zr.reset_index(), ax=axes[0])\nsns.pointplot(x=\"con\", y=\"mean\", hue=\"roi\",\n                    data=Zr_long.Zr.reset_index(), ax=axes[1])\nplt.tight_layout()\nplt.show()\n```\n\n\n```python\ntarg_df = Zr_long.Zr.reset_index()\nloc_Zr = (targ_df[targ_df['roi']=='loc']\n          .pairwise_ttests(dv='mean', within='con', subject='sn', \n                           parametric=True, padjust='bonf', effsize = 'cohen',\n                           return_desc=True)\n          .round(3))\nloc_Zr['roi'] = 'loc'\npf_Zr = (targ_df[targ_df['roi']=='pf']\n          .pairwise_ttests(dv='mean', within='con', subject='sn', \n                           parametric=True, padjust='bonf', effsize = 'cohen',\n                           return_desc=True)\n          .round(3))\npf_Zr['roi'] = 'pf'\npd.concat([loc_Zr, pf_Zr], axis=0)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Contrast</th>\n      <th>A</th>\n      <th>B</th>\n      <th>mean(A)</th>\n      <th>std(A)</th>\n      <th>mean(B)</th>\n      <th>std(B)</th>\n      <th>Paired</th>\n      <th>Parametric</th>\n      <th>T</th>\n      <th>dof</th>\n      <th>alternative</th>\n      <th>p-unc</th>\n      <th>BF10</th>\n      <th>cohen</th>\n      <th>roi</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>con</td>\n      <td>cons</td>\n      <td>imm</td>\n      <td>0.296</td>\n      <td>0.136</td>\n      <td>0.277</td>\n      <td>0.128</td>\n      <td>True</td>\n      <td>True</td>\n      <td>3.227</td>\n      <td>23.0</td>\n      <td>two-sided</td>\n      <td>0.004</td>\n      <td>11.202</td>\n      <td>0.146</td>\n      <td>loc</td>\n    </tr>\n    <tr>\n      <th>0</th>\n      <td>con</td>\n      <td>cons</td>\n      <td>imm</td>\n      <td>0.104</td>\n      <td>0.068</td>\n      <td>0.094</td>\n      <td>0.059</td>\n      <td>True</td>\n      <td>True</td>\n      <td>2.754</td>\n      <td>23.0</td>\n      <td>two-sided</td>\n      <td>0.011</td>\n      <td>4.367</td>\n      <td>0.158</td>\n      <td>pf</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Statistical Test - Correlation & Partial Corr\n\n\n```python\ntarg_df1 = Z_long.Z.reset_index()\nz_df = (targ_df1\n        .filter(['sn','roi','con','mean'])\n        .rename(columns={'mean':'z'}))\n\ntarg_df2 = beta_long.beta.reset_index()\nbeta_df = (targ_df2\n        .filter(['sn','roi','con','mean'])\n        .rename(columns={'mean':'beta'}))\n\ntarg_df3 = Zr_long.Zr.reset_index()\nZr_df = (targ_df3\n        .filter(['sn','roi','con','mean'])\n        .rename(columns={'mean':'Zr'}))\n\ndf_fnl = pd.merge(z_df, beta_df, how='inner', on=['sn','roi','con'])\ndf_fnl = pd.merge(df_fnl, Zr_df, how='inner', on=['sn','roi','con'])\n```\n\n\n```python\ndf_cons = df_fnl[(df_fnl['con'] == 'cons') & (df_fnl['roi']=='loc')]\ndf_imm = df_fnl[(df_fnl['con'] == 'imm')  & (df_fnl['roi']=='loc')]\n```\n\n\n```python\ndf_dff = pd.merge(df_cons, df_imm, how='inner', on=['sn','roi'])\n```\n\n\n```python\ndf_dff = (df_dff\n         .assign(z = lambda x: x.z_x-x.z_y,\n                beta = lambda x: x.beta_x-x.beta_y,\n                Zr = lambda x: x.Zr_x-x.Zr_y)\n         .filter(['sn','roi','z','beta','Zr']))\n```\n\n\n```python\ndf_dff.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>sn</th>\n      <th>roi</th>\n      <th>z</th>\n      <th>beta</th>\n      <th>Zr</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>loc</td>\n      <td>0.190268</td>\n      <td>0.106183</td>\n      <td>0.062394</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>10</td>\n      <td>loc</td>\n      <td>-0.004985</td>\n      <td>-0.010664</td>\n      <td>0.015628</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>11</td>\n      <td>loc</td>\n      <td>0.136077</td>\n      <td>0.005941</td>\n      <td>0.029292</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>12</td>\n      <td>loc</td>\n      <td>0.079221</td>\n      <td>-0.001217</td>\n      <td>0.020856</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>13</td>\n      <td>loc</td>\n      <td>-0.035033</td>\n      <td>0.043352</td>\n      <td>0.050008</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n* Assumption Check\n\n\n```python\npg.multivariate_normality(df_dff[['z', 'beta', 'Zr']])\n```\n\n\n\n\n    HZResults(hz=0.7703488985936779, pval=0.10968901247185164, normal=True)\n\n\n\n### Activation & Beta\n\n\n```python\nsns.jointplot(data=df_dff, x='z', y='beta', kind='reg')\n```\n\n* Pearson Correlation\n\n\n```python\npg.corr(df_dff.z, df_dff.beta,\n        alternative=\"two-sided\",\n        method=\"pearson\") # pearson, spearman, kendall, bicor, percbend, shepherd, skipped\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>n</th>\n      <th>r</th>\n      <th>CI95%</th>\n      <th>p-val</th>\n      <th>BF10</th>\n      <th>power</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>pearson</th>\n      <td>24</td>\n      <td>0.448832</td>\n      <td>[0.06, 0.72]</td>\n      <td>0.027807</td>\n      <td>2.489</td>\n      <td>0.615555</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ng = sns.lmplot(x=\"z\", y=\"beta\",\n           col=\"roi\", data=df_dff);\ng = (g.set_axis_labels(\"z (cons-imm)\", \"beta (cons-imm)\")\n      #.set(xlim=(0, 60), ylim=(0, 12),\n      #     xticks=[10, 30, 50], yticks=[2, 6, 10])\n      .fig.subplots_adjust(wspace=.02))\n```\n\n* Patial Correlation\n\n\n```python\npg.partial_corr(data=df_dff, x='z', y='beta', covar='Zr',\n               alternative='two-sided', method='pearson').round(3)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>n</th>\n      <th>r</th>\n      <th>CI95%</th>\n      <th>p-val</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>pearson</th>\n      <td>24</td>\n      <td>0.283</td>\n      <td>[-0.15, 0.62]</td>\n      <td>0.191</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n\n```\n\n\n```python\nsns.lmplot(x=\"z\", y=\"beta\", hue=\"con\",\n           col=\"roi\", data=df_fnl);\n```\n\n### Activation & Zr\n\n\n```python\nsns.jointplot(data=df_dff, x='z', y='Zr', kind='reg')\n```\n\n* Robust correlation (skipped method)\n\n\n```python\npg.corr(df_dff.z, df_dff.Zr,\n        alternative=\"two-sided\",\n        method=\"skipped\") # pearson, spearman, kendall, bicor, percbend, shepherd, skipped\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>n</th>\n      <th>outliers</th>\n      <th>r</th>\n      <th>CI95%</th>\n      <th>p-val</th>\n      <th>power</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>skipped</th>\n      <td>24</td>\n      <td>1</td>\n      <td>0.307312</td>\n      <td>[-0.12, 0.64]</td>\n      <td>0.153748</td>\n      <td>0.303899</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ng = sns.lmplot(x=\"z\", y=\"Zr\",\n           col=\"roi\", data=df_dff);\ng = (g.set_axis_labels(\"z (cons-imm)\", \"Zr (cons-imm)\")\n      #.set(xlim=(0, 60), ylim=(0, 12),\n      #     xticks=[10, 30, 50], yticks=[2, 6, 10])\n      .fig.subplots_adjust(wspace=.02))\n```\n\n* Patial Correlation\n\n\n```python\npg.partial_corr(data=df_dff, x='z', y='Zr', covar='beta',\n               alternative='two-sided', method='pearson').round(3)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>n</th>\n      <th>r</th>\n      <th>CI95%</th>\n      <th>p-val</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>pearson</th>\n      <td>24</td>\n      <td>0.105</td>\n      <td>[-0.32, 0.5]</td>\n      <td>0.632</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nsns.lmplot(x=\"z\", y=\"Zr\", hue=\"con\",\n           col=\"roi\", data=df_fnl);\n```\n\n### Beta & Zr\n\n\n```python\nsns.jointplot(data=df_dff, x='beta', y='Zr', kind='reg')\n```\n\n* Spearman Correlation\n\n\n```python\npg.corr(df_dff.beta, df_dff.Zr,\n        alternative=\"two-sided\",\n        method=\"spearman\") # pearson, spearman, kendall, bicor, percbend, shepherd, skipped\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>n</th>\n      <th>r</th>\n      <th>CI95%</th>\n      <th>p-val</th>\n      <th>power</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>spearman</th>\n      <td>24</td>\n      <td>0.381739</td>\n      <td>[-0.03, 0.68]</td>\n      <td>0.065663</td>\n      <td>0.466299</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ng = sns.lmplot(x=\"beta\", y=\"Zr\",\n           col=\"roi\", data=df_dff);\ng = (g.set_axis_labels(\"beta (cons-imm)\", \"Zr (cons-imm)\")\n      #.set(xlim=(0, 60), ylim=(0, 12),\n      #     xticks=[10, 30, 50], yticks=[2, 6, 10])\n      .fig.subplots_adjust(wspace=.02))\n```\n\n* Patial Correlation\n\n\n```python\npg.partial_corr(data=df_dff, x='beta', y='Zr', covar='z',\n               alternative='two-sided', method='pearson').round(3)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>n</th>\n      <th>r</th>\n      <th>CI95%</th>\n      <th>p-val</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>pearson</th>\n      <td>24</td>\n      <td>0.624</td>\n      <td>[0.28, 0.82]</td>\n      <td>0.001</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nsns.lmplot(x=\"beta\", y=\"Zr\", hue=\"con\",\n           col=\"roi\", data=df_fnl);\n```\n\n## Statistical Test - Regression & Mediation Analysis\n\n\n```python\ndf_fnl.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>sn</th>\n      <th>roi</th>\n      <th>con</th>\n      <th>z</th>\n      <th>beta</th>\n      <th>Zr</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>loc</td>\n      <td>cons</td>\n      <td>1.085557</td>\n      <td>0.394441</td>\n      <td>0.441953</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>loc</td>\n      <td>imm</td>\n      <td>0.895288</td>\n      <td>0.288257</td>\n      <td>0.379559</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1</td>\n      <td>pf</td>\n      <td>cons</td>\n      <td>0.406269</td>\n      <td>0.079983</td>\n      <td>0.122856</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1</td>\n      <td>pf</td>\n      <td>imm</td>\n      <td>0.324837</td>\n      <td>0.074869</td>\n      <td>0.105637</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>10</td>\n      <td>loc</td>\n      <td>cons</td>\n      <td>0.455391</td>\n      <td>0.124292</td>\n      <td>0.162410</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nlm = pg.linear_regression(X = df_dff[['z', 'Zr']],  y = df_dff['beta' ],\n                         remove_na = True, add_intercept = True,\n                         coef_only = False, relimp=True)\nlm.round(3)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>names</th>\n      <th>coef</th>\n      <th>se</th>\n      <th>T</th>\n      <th>pval</th>\n      <th>r2</th>\n      <th>adj_r2</th>\n      <th>CI[2.5%]</th>\n      <th>CI[97.5%]</th>\n      <th>relimp</th>\n      <th>relimp_perc</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Intercept</td>\n      <td>0.007</td>\n      <td>0.006</td>\n      <td>1.111</td>\n      <td>0.279</td>\n      <td>0.512</td>\n      <td>0.466</td>\n      <td>-0.006</td>\n      <td>0.020</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>z</td>\n      <td>0.070</td>\n      <td>0.052</td>\n      <td>1.352</td>\n      <td>0.191</td>\n      <td>0.512</td>\n      <td>0.466</td>\n      <td>-0.038</td>\n      <td>0.177</td>\n      <td>0.122</td>\n      <td>23.81</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Zr</td>\n      <td>0.728</td>\n      <td>0.199</td>\n      <td>3.658</td>\n      <td>0.001</td>\n      <td>0.512</td>\n      <td>0.466</td>\n      <td>0.314</td>\n      <td>1.141</td>\n      <td>0.390</td>\n      <td>76.19</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nlm.residuals_, lm.df_model_, lm.df_resid_ \n```\n\n\n\n\n    (array([ 0.04037782, -0.02880129, -0.03199547, -0.02904239,  0.00230377,\n            -0.00496017, -0.03976243,  0.02242275,  0.02731909, -0.02331989,\n             0.01746612,  0.04105124, -0.00992838,  0.00840776, -0.02203583,\n            -0.00706285, -0.00563117,  0.0176607 ,  0.0234147 ,  0.00406036,\n            -0.01894301,  0.04231559, -0.0242374 , -0.00107959]),\n     2,\n     21)\n\n\n\n\n```python\npg.qqplot(lm.residuals_, dist='norm')\n```\n\n\n```python\npg.mediation_analysis(data=df_dff, x='z', m='Zr', y='beta', alpha=0.05,\n                   seed=42)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>path</th>\n      <th>coef</th>\n      <th>se</th>\n      <th>pval</th>\n      <th>CI[2.5%]</th>\n      <th>CI[97.5%]</th>\n      <th>sig</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Zr ~ X</td>\n      <td>0.097763</td>\n      <td>0.051329</td>\n      <td>0.069984</td>\n      <td>-0.008687</td>\n      <td>0.204213</td>\n      <td>No</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Y ~ Zr</td>\n      <td>0.828695</td>\n      <td>0.187705</td>\n      <td>0.000219</td>\n      <td>0.439419</td>\n      <td>1.217971</td>\n      <td>Yes</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Total</td>\n      <td>0.141011</td>\n      <td>0.059856</td>\n      <td>0.027807</td>\n      <td>0.016877</td>\n      <td>0.265145</td>\n      <td>Yes</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Direct</td>\n      <td>0.069888</td>\n      <td>0.051678</td>\n      <td>0.190637</td>\n      <td>-0.037582</td>\n      <td>0.177358</td>\n      <td>No</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Indirect</td>\n      <td>0.071123</td>\n      <td>0.047993</td>\n      <td>0.064000</td>\n      <td>0.002036</td>\n      <td>0.183404</td>\n      <td>No</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# \ubaa8\ub4c8 \ubd88\ub7ec\uc624\uae30\nimport statsmodels.api as sm\nimport statsmodels.formula.api as smf\n\n```\n\n\n```python\nlinear_model = smf.ols(formula='beta ~ z + Zr + C(con)', data=df_fnl).fit()\n```\n\n\n```python\nlinear_model.summary2()\n```\n\n\n\n\n<table class=\"simpletable\">\n<tr>\n        <td>Model:</td>               <td>OLS</td>         <td>Adj. R-squared:</td>     <td>0.904</td>  \n</tr>\n<tr>\n  <td>Dependent Variable:</td>       <td>beta</td>              <td>AIC:</td>         <td>-326.3848</td>\n</tr>\n<tr>\n         <td>Date:</td>        <td>2021-11-28 15:50</td>        <td>BIC:</td>         <td>-316.1274</td>\n</tr>\n<tr>\n   <td>No. Observations:</td>         <td>96</td>          <td>Log-Likelihood:</td>    <td>167.19</td>  \n</tr>\n<tr>\n       <td>Df Model:</td>              <td>3</td>           <td>F-statistic:</td>       <td>300.5</td>  \n</tr>\n<tr>\n     <td>Df Residuals:</td>           <td>92</td>        <td>Prob (F-statistic):</td> <td>2.14e-47</td> \n</tr>\n<tr>\n      <td>R-squared:</td>            <td>0.907</td>            <td>Scale:</td>        <td>0.0018762</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n        <td></td>         <th>Coef.</th>  <th>Std.Err.</th>    <th>t</th>     <th>P>|t|</th> <th>[0.025</th>  <th>0.975]</th>\n</tr>\n<tr>\n  <th>Intercept</th>     <td>-0.0026</td>  <td>0.0090</td>  <td>-0.2923</td> <td>0.7708</td> <td>-0.0204</td> <td>0.0152</td>\n</tr>\n<tr>\n  <th>C(con)[T.imm]</th> <td>-0.0023</td>  <td>0.0089</td>  <td>-0.2653</td> <td>0.7914</td> <td>-0.0199</td> <td>0.0152</td>\n</tr>\n<tr>\n  <th>z</th>             <td>0.0045</td>   <td>0.0283</td>  <td>0.1596</td>  <td>0.8736</td> <td>-0.0517</td> <td>0.0608</td>\n</tr>\n<tr>\n  <th>Zr</th>            <td>0.9472</td>   <td>0.0741</td>  <td>12.7876</td> <td>0.0000</td> <td>0.8001</td>  <td>1.0943</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n     <td>Omnibus:</td>     <td>1.899</td>  <td>Durbin-Watson:</td>   <td>1.028</td>\n</tr>\n<tr>\n  <td>Prob(Omnibus):</td>  <td>0.387</td> <td>Jarque-Bera (JB):</td> <td>1.381</td>\n</tr>\n<tr>\n       <td>Skew:</td>     <td>-0.272</td>     <td>Prob(JB):</td>     <td>0.501</td>\n</tr>\n<tr>\n     <td>Kurtosis:</td>    <td>3.222</td>  <td>Condition No.:</td>    <td>22</td>  \n</tr>\n</table>\n\n\n\n\n```python\nNDF = pd.DataFrame()\nNDF['fitted'] = linear_model.fittedvalues  \nNDF['resid'] = linear_model.resid\nNDF['stdresid'] = linear_model.resid_pearson\n```\n\n\n```python\nNDF.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fitted</th>\n      <th>resid</th>\n      <th>stdresid</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.420898</td>\n      <td>-0.026457</td>\n      <td>-0.610800</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.358590</td>\n      <td>-0.070332</td>\n      <td>-1.623721</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.115582</td>\n      <td>-0.035600</td>\n      <td>-0.821867</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.096556</td>\n      <td>-0.021687</td>\n      <td>-0.500668</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.153270</td>\n      <td>-0.028978</td>\n      <td>-0.668998</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nplt.plot(NDF.fitted, NDF.stdresid, 'o')\nplt.axhline(y = 0, color ='grey', linestyle='dashed')\nplt.xlabel('Fitted Value')\nplt.ylabel('Standardized Residual')\nplt.show()\n```\n\n\n```python\nsm.qqplot(NDF.stdresid, line='s')\nplt.show()\n```\n\n\n```python\ndf_fnl_logReg = df_fnl\ndf_fnl_logReg['con'] = df_fnl_logReg['con'].replace(['cons','imm'], ['1','0'])\ndf_fnl_logReg['con'] = df_fnl_logReg['con'].astype(int)\n```\n\n\n```python\nlogreg = pg.logistic_regression(df_fnl_logReg[['z', 'beta', 'Zr']], df_fnl_logReg['con'],\n                             remove_na=True, coef_only=False)\n```\n\n\n```python\nlogreg\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>names</th>\n      <th>coef</th>\n      <th>se</th>\n      <th>z</th>\n      <th>pval</th>\n      <th>CI[2.5%]</th>\n      <th>CI[97.5%]</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Intercept</td>\n      <td>-0.135120</td>\n      <td>0.352751</td>\n      <td>-0.383048</td>\n      <td>0.701684</td>\n      <td>-0.826499</td>\n      <td>0.556258</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>z</td>\n      <td>-0.286458</td>\n      <td>1.312846</td>\n      <td>-0.218196</td>\n      <td>0.827277</td>\n      <td>-2.859589</td>\n      <td>2.286674</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>beta</td>\n      <td>1.307065</td>\n      <td>4.827110</td>\n      <td>0.270776</td>\n      <td>0.786563</td>\n      <td>-8.153896</td>\n      <td>10.768026</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Zr</td>\n      <td>0.190483</td>\n      <td>5.712118</td>\n      <td>0.033347</td>\n      <td>0.973398</td>\n      <td>-11.005062</td>\n      <td>11.386028</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nlogreg['coef'][0]\n```\n\n\n\n\n    -0.1351203794008318\n\n\n\n\n```python\n# log-odd ratio of intercept = -0.135120 / logreg['coef'][0]\n# log-odd ratio of z = -0.286457 / logreg['coef'][1]\n# log-odd ratio of beta = 1.307065 / logreg['coef'][2]\n# log-odd ratio of Zr = 0.190483 / logreg['coef'][3]\n\n# odd ratio of intercept = np.exp(logreg['coef'][0])\n# odd ratio of z = np.exp(logreg['coef'][1])\n# odd ratio of beta = np.exp(logreg['coef'][2])\n# odd ratio of Zr = np.exp(logreg['coef'][3])\nnp.exp(logreg['coef'][0])\nnp.exp(logreg['coef'][1])\nnp.exp(logreg['coef'][2])\nnp.exp(logreg['coef'][3])\n\n# probability\n1/(1+np.exp(-(-logreg['coef'][0])))\n1/(1+np.exp(-(-logreg['coef'][0]+1*logreg['coef'][1])))\n1/(1+np.exp(-(-logreg['coef'][0]+1*logreg['coef'][2])))\n1/(1+np.exp(-(-logreg['coef'][0]+1*logreg['coef'][3])))\n```\n\n\n\n\n    0.5806892448602095\n\n\n", "meta": {"hexsha": "8cc83540f2be98dc05b574070699585d95b9bc28", "size": 912635, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Analyzer.ipynb", "max_stars_repo_name": "thoon4/Statistics_Py", "max_stars_repo_head_hexsha": "c0a3de01f4ae78ca2dd20314387b120a878bd9b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-25T10:40:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T10:40:16.000Z", "max_issues_repo_path": "Analyzer.ipynb", "max_issues_repo_name": "thoon4/Statistics_Py", "max_issues_repo_head_hexsha": "c0a3de01f4ae78ca2dd20314387b120a878bd9b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Analyzer.ipynb", "max_forks_repo_name": "thoon4/Statistics_Py", "max_forks_repo_head_hexsha": "c0a3de01f4ae78ca2dd20314387b120a878bd9b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 173.3399810066, "max_line_length": 174916, "alphanum_fraction": 0.8670761038, "converted": true, "num_tokens": 25514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33458944125318596, "lm_q2_score": 0.11596071978154188, "lm_q1q2_score": 0.03879923243902336}}
{"text": "```python\n#!/usr/bin/env python3\nfrom traitlets.config.manager import BaseJSONConfigManager\nfrom pathlib import Path\npath = Path.home() / \".jupyter\" / \"nbconfig\"\ncm = BaseJSONConfigManager(config_dir=str(path))\ncm.update(\n    \"rise\",\n    {\n        \"theme\": \"white\",\n        \"transition\": \"none\",\n        \"autolaunch\": True,\n    }\n)\n```\n\n\n```python\n%matplotlib inline\n```\n\n<div style=\"float: left; width: 80%;\">\n<h1>Coding as a Service: <br>\nLibrer\u00eda pypsdier, aprendizajes y metodolog\u00eda.</h1>\n<h2>Sebasti\u00e1n Flores</h2>\n<h3>Pycon Argentina 2020</h3>\n</div>\n<div style=\"float: right; width: 20%;\">\n\n</div>\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda.\n### Observaciones:\n\n* @sebastiandres en twitter y github.\n* Opiniones y cr\u00edticas a t\u00edtulo personal.\n* No se necesita conocer de qu\u00edmica, matem\u00e1tica o python avanzado.\n* Presentaci\u00f3n disponible en https://www.github.com/sebastiandres/charlas y realizada con jupyter+RISE.\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda.\n### Autores\n\n<div style=\"float: left; width: 50%;\">\n\n<h4>Sebasti\u00e1n Flores</h4>\nM.Sc. Mathematical and Computational Engineering<br>\nM.Sc. M\u00e9canique Num\u00e9rique<br>\nIngeniero Civil Matem\u00e1tico<br>\nu-planner - Chile\n</div>\n\n<div style=\"float: right; width: 50%;\">\n<h4>Pedro Valencia</h4>\nPh.D Ingenier\u00eda Bioqu\u00edmica<br>\nM.Sc. Ingenier\u00eda Bioqu\u00edmica<br>\nBioqu\u00edmico<br>\nUTFSM - Chile\n</div>\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda\n### Historia\n\n* Origen: \n   * Proyecto de colaboraci\u00f3n en curso de matem\u00e1ticas aplicadas.\n\n* Primeras implementaciones en MATLAB:\n    * Problema: Cada nueva reacci\u00f3n qu\u00edmica requiere una nueva implementaci\u00f3n num\u00e9rica. \n    * Repetici\u00f3n de c\u00f3digo y mantenci\u00f3n tediosa.\n\n* Desarrollo en Python:\n    * C\u00f3digo gen\u00e9rico: librer\u00eda pypsdier. \n    * Interface simple e instalaci\u00f3n por pypi.\n    * Reacciones qu\u00edmicas definidas como funciones.\n    * N\u00famero arbitrario de sustancias (sustratos o productos).\n    * Tama\u00f1o de part\u00edculas definidas por una lista de radios y frecuencias.\n\n* Impacto: \n    * 9 publicaciones.\n    * C\u00f3digo abierto y en constante evoluci\u00f3n.\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda\n### Problema\n\n* Pedro no conoc\u00eda Python. Actualmente, nivel de usuario b\u00e1sico.\n* Sebasti\u00e1n tiene (a\u00fan) conocimientos nulos en bioqu\u00edmica.\n\n**\u00bfC\u00f3mo colaborar de manera eficiente?**\n\nEl problema m\u00e1s general: \n\n**\u00bfCu\u00e1l es la manera m\u00e1s sencilla de entregar \"Coding As A Service\"?**\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda\n### Ejemplo\n\n\u00bfCu\u00e1l es la manera m\u00e1s sencilla de entregar \"Coding As A Service\"?\n\nTiene que ser tan f\u00e1cil que puedas explic\u00e1rselo a tu abuela.\n\n<div style=\"float: left; width: 20%;\"></div>\n<div style=\"float: right; width: 80%;\"></div>\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda\n### Soluci\u00f3n para la abuela\nAbue, vaya a este link y aprete play:\n\n\nhttps://bit.ly/2IetMRn\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda.\n\n### Nuestro problema a resolver\n\n<div style=\"float: right; width: 100%;\"></div>\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda.\n\n### Nuestro problema a resolver\n\n<div style=\"float: right; width: 90%;\"></div>\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda.\n\n### Nuestro problema a resolver\n\nEl problema es obtener $S_b(t)$ y $S(t,r,R_i)$, para $t>0$, $0<r<R_i$. \n\n$$\n   \\frac{\\partial S}{\\partial t}(t,r,R_i) = D_S \\left(\\frac{\\partial^2 S}{\\partial r^2}(t,r,R_i) \n   + \\frac{2}{r}\\frac{\\partial S}{\\partial r}(t,r,R_i)\\right) - V_e\\left(S, r, t \\right)\n$$\n\nCondici\u00f3n de borde en el centro de las part\u00edculas:\n\n\\begin{align}\n   \\frac{\\partial S}{\\partial r}(t, 0, R_i) = 0 \\textrm{ para } t > 0\n\\end{align}\n\nCondiciones de borde en la superficie de la part\u00edcula:\n\n\\begin{align}\nS_b(t)  = S(t, R_i,R_i) \\textrm{ para } t > 0\n\\end{align}\n\n\\begin{align}\n\\frac{d S_b}{d t}(t)  \n   &= - 3 D_S \\frac{V_c}{V_R E \\left[ R^3 \\right] } E \\left[ R^2 \\left. \\frac{\\partial S}{\\partial r} \\right|_{r=R} \\right] \\textrm{ para } t > 0\n\\end{align}\n\nCon la condici\u00f3n inicial\n\n\\begin{align}\nS_b(0) &= S_0 \\\\\nS(0,r, R_i) &= 0 \\textrm{ para } 0 \\leq r < R_i\n\\end{align}\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda.\n\n### Nuestro problema a resolver\n\n<div style=\"float: right; width: 90%;\"></div>\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda.\n### Los Desaf\u00edos\n\nDesaf\u00edos t\u00e9cnicos:\n\n* \u00bfC\u00f3mo discretizar las ecuaciones?\n* \u00bfC\u00f3mo realizar la implementaci\u00f3n num\u00e9rica?\n* \u00bfC\u00f3mo resolver para reacciones qu\u00edmicas distintas y un n\u00famero arbitrario de sustancias y tama\u00f1os de part\u00edculas?\n\nEsta es la parte tiene soluci\u00f3n directa y conocida:\n* Discretizar ecuaciones utilizando diferencias finitas para el tiempo ($\\Delta t$) y espacio ($\\Delta R_i$).\n* Asegurar estabilidad num\u00e9rica dependiendo de los inputs.\n* Implementaci\u00f3n flexible con python + numpy + matplotlib + otros.\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda.\n### Los Desaf\u00edos\n\nDesaf\u00edos organizacionales:\n\n* \u00bfC\u00f3mo colaborar?\n* \u00bfC\u00f3mo distribuir el c\u00f3digo?\n* \u00bfC\u00f3mo hacer f\u00e1cil el uso?\n* \u00bfC\u00f3mo hacer reproducible las simulaciones?\n* \u00bfC\u00f3mo documentar el c\u00f3digo?\n* \u00bfC\u00f3mo almacenar los resultados de las simulaciones?\n\nEsta parte no tiene una soluci\u00f3n directa:\n* No hab\u00eda mucha informaci\u00f3n al respecto.\n* Cada equipo lo resuelve a su manera.\n* Existen muchas herramientas que nos simplifican la vida.\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda\n### Framework: \u00bfQu\u00e9 necesit\u00e1bamos?\n\n(1) Propocionar **instalaci\u00f3n** y **versionamiento** de python, jupyter y librer\u00edas necesarias.\n\n(2) Facilitar **desarrollo incremental** considerando devs y users.\n\n(3) Permitir una buena **documentaci\u00f3n** para desarrolladores y usuarios.\n\n(4)  Exponer una **interface simple** al usuario final, permitiendo ocultar una implementaci\u00f3n num\u00e9rica compleja y con una curva de aprendizaje apropiado.\n\n(5) Permitir **reproducir**, **almacenar** y **compartir** resultados de simulaci\u00f3n.\n\n(6) Permitir el uso de recursos computacionales en la **nube**.\n\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda\n#### Necesidades\n\n(1) Propocionar **instalaci\u00f3n** y **versionamiento** de python, jupyter y librer\u00edas necesarias.\n\n(2) Facilitar **desarrollo incremental** considerando desarrolladores y usuarios.\n\n### Soluci\u00f3n\n\nEstructura de proyecto de python, para instalar con pypi o desde github.\n\n<div style=\"float: left; width: 50%;\">\n\n</div>\n<div style=\"float: right; width: 5%;\">\n</div>\n<div style=\"float: right; width: 50%;\">\n\n</div>\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda\n#### Necesidades\n\n(3) Permitir una buena **documentaci\u00f3n** para desarrolladores y usuarios.\n\n### Soluci\u00f3n\n<div style=\"float: left; width: 50%;\">\n\n</div>\n<div style=\"float: right; width: 50%;\">\n\n</div>\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda\n#### Necesidades\n\n(4) Exponer una **interface simple** al usuario final, permitiendo ocultar una implementaci\u00f3n num\u00e9rica compleja y con una curva de aprendizaje apropiado.\n\n(5) Permitir **reproducir**, **almacenar** y **compartir** resultados de simulaci\u00f3n.\n\n### Soluci\u00f3n\n\n<div style=\"float: right; width: 90%;\"></div>\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda\n### Soluci\u00f3n\n\n(5) Permitir **reproducir**, **almacenar** y **compartir** resultados de simulaci\u00f3n.\n\n(6) Permitir el uso de recursos computacionales en la **nube**.\n\n### Soluci\u00f3n\n<div style=\"float: right; width: 80%;\"></div>\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda\n### Ejemplo de pypsdier\n\nPrimero que nada, instalaremos la librer\u00eda:\n\n\n```python\n#!pip install pypsdier --upgrade\n!pip install git+https://github.com/sebastiandres/pypsdier.git --upgrade\n```\n\n    Collecting git+https://github.com/sebastiandres/pypsdier.git\n      Cloning https://github.com/sebastiandres/pypsdier.git to /private/var/folders/68/v1ds0ld152q_wk4sbcns3ckw0000gn/T/pip-req-build-mm52_b8o\n      Running command git clone -q https://github.com/sebastiandres/pypsdier.git /private/var/folders/68/v1ds0ld152q_wk4sbcns3ckw0000gn/T/pip-req-build-mm52_b8o\n    Building wheels for collected packages: pypsdier\n      Building wheel for pypsdier (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Created wheel for pypsdier: filename=pypsdier-1.1.1-cp37-none-any.whl size=14659 sha256=34556c2c7b1b3be6222355f403a45817e8b5a0154f44037f940a4923711fe71d\n      Stored in directory: /private/var/folders/68/v1ds0ld152q_wk4sbcns3ckw0000gn/T/pip-ephem-wheel-cache-csxbayor/wheels/57/71/0f/2f6f43ab73e6371b622a1e181130163a445c394d19b74a80d1\n    Successfully built pypsdier\n    Installing collected packages: pypsdier\n      Found existing installation: pypsdier 1.1.1\n        Uninstalling pypsdier-1.1.1:\n          Successfully uninstalled pypsdier-1.1.1\n    Successfully installed pypsdier-1.1.1\n\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda\n### Ejemplo\n\nConsideremos un ejemplo de una reacci\u00f3n simple. Definamos los inputs de la simulaci\u00f3n:\n\n\n```python\ndef MichaelisMenten(S, E0, k, K):\n  \"\"\"Definition for Michaelis Menten reaction with inputs E0 [mM], k [1/s] and K [mM]\"\"\"\n  return (-k*E0*S[0]/(K+S[0]), )\n\ninputs = {}\ninputs[\"SimulationTime\"] = 30. # [s]\ninputs[\"SavingTimeStep\"] = 1. # [s]\ninputs[\"CatalystVolume\"] = 0.5 # [mL]\ninputs[\"BulkVolume\"]  = 100.0  # [mL]\ninputs[\"Names\"] = ('Substrat',)  # legend for the xls, reports and plots\ninputs[\"InitialConcentrations\"] = (1.3,)   # [mM]\ninputs[\"EffectiveDiffusionCoefficients\"] = (5.3E-10,)  # [m2/s]\ninputs[\"CatalystParticleRadius\"] = [40.0E-6, 60.0E-6, 80.0E-6] # [m]\ninputs[\"CatalystParticleRadiusFrequency\"] = [0.3, 0.5, 0.2] # []\ninputs[\"ReactionFunction\"] = MichaelisMenten # function \ninputs[\"ReactionParameters\"] = (41 , 0.13)   # [1/s], [mM/s], parameters\ninputs[\"CatalystEnzymeConcentration\"] = 0.35 # [mM]\n```\n\n##### Coding as a Service\n### Ejemplo\nDefinamos ahora opciones de gr\u00e1ficos para la simulaci\u00f3n:\n\n\n```python\nplot_options = {}\nplot_options[\"label_x\"] = \"Tiempo de reacci\u00f3n [s]\"\nplot_options[\"label_y\"] = \"Concentraci\u00f3n [mM]\"\nplot_options[\"title\"] = \"Simulaci\u00f3n de Michaelis Menten para la PyconAr\"\nplot_options[\"ode_kwargs\"] = {'label':'Enzima Libre', 'color':'blue', 'marker':'', 'markersize':6, 'linestyle':'dashed', 'linewidth':2}\nplot_options[\"pde_kwargs\"] = {'label':'Enzima Inmobilizada', 'color':'blue', 'marker':'', 'markersize':6, 'linestyle':'solid', 'linewidth':2}\nplot_options[\"data_kwargs\"] = {'label':'Experimento', 'color':'green', 'marker':'s', 'markersize':8, 'linestyle':'none', 'linewidth':2}\nplot_options[\"data_x\"] = [0.0, 30, 60, 90, 120]\nplot_options[\"data_y\"] = [1.3, 0.65, 0.25, 0.10, 0.0]\n```\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda\n### Ejemplo pypsdier\nTodo est\u00e1 listo para realizar una simulaci\u00f3n (muy sencilla):\n\n\n```python\nimport pypsdier\nSIM1 = pypsdier.SimulationInterface()\nSIM1.new(inputs, plot_options)\n```\n\n\n```python\nSIM1.simulate(\"ode\")\n```\n\n    ODE: Solving without diffusional restriction (simplified problem). No porous particles are present. The substance and the enzyme are assumed to be diluted on the bulk phase\n    Simulation completed.\n\n\n\n```python\nSIM1.simulate(\"pde\")\n```\n\n    PDE: Solving the complete reaction-diffusion problem, considering a single substance and 3 particle radii.\n    Simulated 030 secs out of  30 secs (Remaining time < 1 mins) \n\n\n\n```python\nSIM1.save(\"pycon_saving_example.rde\")\n```\n\n    Saving simulation into file at /Users/sebastiandres/Desktop/Personales/github_repos/charlas/2020_11_XX_pycon_ar_pypsdier/pycon_saving_example.rde\n\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda\n### Ejemplo pypsdier\nPodemos definir funciones espec\u00edficas para exportar en formato excel o graficar\n\n\n```python\nSIM1.export_xls(\"pycon_excel_example.xls\")\n```\n\n    Saving simulation as xls file at /Users/sebastiandres/Desktop/Personales/github_repos/charlas/2020_11_XX_pycon_ar_pypsdier/pycon_excel_example.xls\n\n\n\n```python\nSIM1.plot(figsize=(16,12))\n```\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda\n### Ejemplo pypsdier\n\n\u00bfY la reproducibilidad?\n\nUna simulaci\u00f3n realizada almacena todas las caracter\u00edsticas con las cuales se gener\u00f3. \n\n\n```python\nimport pypsdier\nSIM2 = pypsdier.SimulationInterface()\nSIM2.load(\"pycon_colab_example.rde\") # load instead of new\n```\n\n    Loaded a simulation from /Users/sebastiandres/Desktop/Personales/github_repos/charlas/2020_11_XX_pycon_ar_pypsdier/pycon_colab_example.rde\n\n\n\n```python\nSIM2.status()\n```\n\n    System configuration:\n        environment: google_colab\n        python version: 3.6.9\n        GenericSimulationLibrary version: 1.1.0\n        numpy version: 1.18.5\n        scipy version: 1.4.1\n        xlwt version: 1.3.0\n        matplotlib version: 3.2.2\n        dill version: 0.3.2\n    Inputs:\n        SimulationTime: 120.0\n        SavingTimeStep: 1.0\n        CatalystVolume: 0.5\n        BulkVolume: 100.0\n        Names: ('Substrat',)\n        InitialConcentrations: (1.3,)\n        EffectiveDiffusionCoefficients: (5.3e-10,)\n        CatalystParticleRadius: [4e-05, 6e-05, 8e-05]\n        CatalystParticleRadiusFrequency: [0.3, 0.5, 0.2]\n        ReactionFunction: <function MichaelisMenten at 0x134d50dd0>\n        ReactionParameters: (41, 0.13)\n        CatalystEnzymeConcentration: 0.35\n    Plot Options:\n        title: Simulaci\u00f3n de Michaelis Menten para la PyconAr\n        label_x: Tiempo de reacci\u00f3n [s]\n        label_y: Concentraci\u00f3n [mM]\n        ode_kwargs: {'label': 'ode', 'color': 'black', 'marker': '', 'markersize': 6, 'linestyle': 'dashed', 'linewidth': 2}\n        pde_kwargs: {'label': 'pde', 'color': 'black', 'marker': '', 'markersize': 6, 'linestyle': 'solid', 'linewidth': 2}\n        data_kwargs: {'label': 'exp', 'color': 'red', 'marker': 's', 'markersize': 6, 'linestyle': 'none', 'linewidth': 2}\n        data_x: [0.0, 30, 60, 90, 120]\n        data_y: [1.3, 0.65, 0.25, 0.1, 0.0]\n    Simulations:\n        ODE: yes\n        PDE: yes\n\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda\n### Ejemplo pypsdier\n\nPodemos cargar una simulaci\u00f3n realizada previamente y analizarla (sin necesidad de volver a realizar la simulaci\u00f3n).\n\n\n```python\nSIM2.plot(figsize=(20,12))\n```\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda\n### Framework Propuesto\n\nLa librer\u00eda pypsdier es espec\u00edfica al problema de reacci\u00f3n-difusi\u00f3n para reactores de enzima inmobilizada, con flexibilidad para diferentes modelos de reacci\u00f3n y condiciones de operaci\u00f3n.\n\nSin embargo, se propone un framework de trabajo con las funcionalidades m\u00ednimas: **GenericSimulationLibrary**\n\nDisponible en\nhttps://github.com/sebastiandres/GenericSimulationLibrary:\n\n* En `simulation_interface.py` actualizar los m\u00e9todos: new, load, simulate, save, plot, export. \n* En `docs/source/*.rst` actualizar la documentaci\u00f3n.\n\n##### Coding as a Service: librer\u00eda pypsdier, aprendizajes y metodolog\u00eda\n### Conclusi\u00f3n\n\nTodo lo anterior no es muy distinto a lo que se hace en una librer\u00eda \"formal\".\n\n**Aprendizaje**: \n\nPuedes usar las mismas herramientas e ideas, aunque tu equipo y proyecto sea m\u00e1s peque\u00f1o e informal, porque simplifican y mejoran la colaboraci\u00f3n.\n\n* git + github/bitbucket.\n* readthedocs\n* pypi\n* google colab/mybinder\n* Interface OO\n\n<div style=\"float: left; width: 60%;\">\n<h1>Coding as a Service: <br>\nLibrer\u00eda pypsdier, aprendizajes y metodolog\u00eda.</h1>\n<h2>Sebasti\u00e1n Flores</h2>\n<h3>Pycon Argentina 2020</h3>\n</div>\n<div style=\"float: right; width: 40%;\">\n<br>\nEncuesta: \n<br>\n<a href=\"https://bit.ly/354jhrQ\" style='font-size:150%'>https://bit.ly/354jhrQ</a>\n\n</div>\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "5171f8c16ae39af3314863d6fbefbecbc855b4a4", "size": 119875, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "pycon_ar.ipynb", "max_stars_repo_name": "sebastiandres/talk_2020_11_pycon_argentina", "max_stars_repo_head_hexsha": "ee8a0de7ac4ab9feb4b8477820695f95093bf235", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pycon_ar.ipynb", "max_issues_repo_name": "sebastiandres/talk_2020_11_pycon_argentina", "max_issues_repo_head_hexsha": "ee8a0de7ac4ab9feb4b8477820695f95093bf235", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pycon_ar.ipynb", "max_forks_repo_name": "sebastiandres/talk_2020_11_pycon_argentina", "max_forks_repo_head_hexsha": "ee8a0de7ac4ab9feb4b8477820695f95093bf235", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 112.3477038425, "max_line_length": 55372, "alphanum_fraction": 0.8678373306, "converted": true, "num_tokens": 4892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32082130082460697, "lm_q2_score": 0.12085324357297283, "lm_q1q2_score": 0.03877229481195422}}
{"text": "<!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)\ndoconce format html solutionhw5.do.txt  -->\n<!-- dom:TITLE: PHY321: Classical Mechanics 1 -->\n\n# PHY321: Classical Mechanics 1\n**Homework 5, due Monday  February 22**\n\nDate: **Feb 21, 2022**\n\n### Practicalities about  homeworks and projects\n\n1. You can work in groups (optimal groups are often 2-3 people) or by yourself. If you work as a group you can hand in one answer only if you wish. **Remember to write your name(s)**!\n\n2. Homeworks are available Wednesday/Thursday the week before the deadline. The deadline is at the Friday lecture.\n\n3. How do I(we)  hand in?  You can hand in the paper and pencil exercises as a hand-written document. For this homework this applies to exercises 1-5. Alternatively, you can hand in everyhting (if you are ok with typing mathematical formulae using say Latex) as a jupyter notebook at D2L. The numerical exercise(s) (exercise 6 here) should always be handed in as a jupyter notebook by the deadline at D2L.\n\n### Introduction to homework 5\n\nThis week's sets of classical pen and paper and computational\nexercises are a continuation of the topics from the previous homework set. We keep dealing with simple motion problems and conservation laws; energy, momentum and angular momentum. These conservation laws are central in Physics and understanding them properly lays the foundation for understanding and analyzing more complicated physics problems.\nThe relevant reading background is\n1. chapters 3 and 4 of Taylor (there are many good examples there) and\n\n2. chapters 10-14 of Malthe-S\u00f8renssen.\n\nIn both textbooks there are many nice worked out examples. Malthe-S\u00f8renssen's text contains also several coding examples you may find useful. \n\nThe numerical homework focuses on another motion problem where you can\nuse the code you developed in homework 4, almost entirely. Please take\na look at the posted solution (jupyter-notebook) for homework 4. You\nneed only to change the forces at play.\n\n### Exercise 1 (15 pt), Work-energy theorem and conservation laws\n\nThis exercise was partly discussed during the lectures. You can also find it in the online notes from the week of February 15-19.\nWe will study a classical electron which moves in the $x$-direction along a surface. The force from the surface is\n\n$$\n\\boldsymbol{F}(x)=-F_0\\sin{(\\frac{2\\pi x}{b})}\\boldsymbol{e}_x.\n$$\n\nThe constant $b$ represents the distance between atoms at the surface of the material, $F_0$ is a constant and $x$ is the position of the electron.\n\n* 1a (2pt) Is this a conservative force? And if so, what does that imply?\n\nThis is indeed a conservative force since it depends only on position and its **curl** is zero. This means that energy is conserved and the integral over the work done by the force is independent of the path taken. \n* 1b (4pt) Use the work-energy theorem to find the velocity $v(x)$. \n\nUsing the work-energy theorem we can find the work $W$ done when moving an electron from a position $x_\\\n0$ to a final position $x$ through the integral\n\n$$\nW=\\int_{x_0}^x \\boldsymbol{F}(x')dx' =  -\\int_{x_0}^x F_0\\sin{(\\frac{2\\pi x'}{b})} dx',\n$$\n\nwhich results in\n\n$$\nW=\\frac{F_0b}{2\\pi}\\left[\\cos{(\\frac{2\\pi x}{b})}-\\cos{(\\frac{2\\pi x_0}{b})}\\right].\n$$\n\nSince this is related to the change in kinetic energy we have, with $v_0$ being the initial velocity at a  time $t_0$,\n\n$$\nv  = \\pm\\sqrt{\\frac{2}{m}\\frac{F_0b}{2\\pi}\\left[\\cos{(\\frac{2\\pi x}{b})}-\\cos{(\\frac{2\\pi x_0}{b})}\\right]+v_0^2}.\n$$\n\n* 1c (4pt) With the above expression for the force, find the potential energy.\n\nThe potential energy, due to energy conservation is\n\n$$\nV(x)=V(x_0)+\\frac{1}{2}mv_0^2-\\frac{1}{2}mv^2,\n$$\n\nwith $v$ given by the previous answer. \nWe can now, in order to find a more explicit expression for the potential energy at a given value $x$, define a zero level value for the potential. The potential is defined , using the work-energy theorem , as\n\n$$\nV(x)=V(x_0)+\\int_{x_0}^x (-F(x'))dx',\n$$\n\nand if you recall the definition of the indefinite integral, we can rewrite this as\n\n$$\nV(x)=\\int (-F(x'))dx'+C,\n$$\n\nwhere $C$ is an undefined constant. The force is defined as the gradient of the potential, and in that case the undefined constant vanishes. The constant does not affect the force we derive from the potential.\n\nWe have then\n\n$$\nV(x)=V(x_0)-\\int_{x_0}^x \\boldsymbol{F}(x')dx',\n$$\n\nwhich results in\n\n$$\nV(x)=\\frac{F_0b}{2\\pi}\\left[\\cos{(\\frac{2\\pi x}{b})}-\\cos{(\\frac{2\\pi x_0}{b})}\\right]+V(x_0).\n$$\n\nWe can now define\n\n$$\n\\frac{F_0b}{2\\pi}\\cos{(\\frac{2\\pi x_0}{b})}=V(x_0),\n$$\n\nwhich gives\n\n$$\nV(x)=\\frac{F_0b}{2\\pi}\\left[\\cos{(\\frac{2\\pi x}{b})}\\right].\n$$\n\n* 1d (5pt) Make a plot of the potential energy and discuss the equilibrium points where the force on the electron is zero. Discuss the physical interpretation of stable and unstable equilibrium points. Use energy conservation. \n\nThe following Python code plots the potential\n\n\n```\n%matplotlib inline\n\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\nDeltax = 0.01\n#set up arrays\nxinitial = -2.0\nxfinal = 2.0 \nn = ceil((xfinal-xinitial)/Deltax)\nx = np.zeros(n)\nfor i in range(n):\n    x[i] = xinitial+i*Deltax\nV = np.zeros(n)\n# Setting values for the constants. \nF0 = 1.0; b = 1.0; \n# Defining the potential\nV = F0*b/(2*pi)*np.cos(2*pi*x/b)\n# Plot position as function of time    \nfig, ax = plt.subplots()\nax.set_ylabel('V')\nax.set_xlabel('x')\nax.plot(x, V)\nfig.tight_layout()\nplt.show()\n```\n\nWe have stable equilibrium  points for every minimum of the $\\cos$ function and unstable equilibrium points where it has its maximimum values. At the minimum the particle has the lowest potential energy and the largest kinetic energy whereas at the maxima it has the largest potential energy and lowest kinetic energy.\n\n### Exsercise 2 (15pt), Rocket, Momentum and mass\n\nTaylor exercise 3.11.    This exercise was partly discussed during the lectures, see the notes on [Energy and Momentum etc, see the part on Momentum conservation ](https://mhjensen.github.io/Physics321/doc/pub/energyconserv/html/energyconserv.html). Taylor's chapter 3.2 covers also this example.\n\n* 3.11 a and b\n\nConsider the rocket of mass $M$ moving with velocity $v$. After a\nbrief instant, the velocity of the rocket is $v+\\Delta v$ and the mass\nis $M-\\Delta M$. Momentum conservation gives\n\n$$\n\\begin{eqnarray*}\nMv&=&(M-\\Delta M)(v+\\Delta v)+\\Delta M(v-v_e)\\\\\n0&=&-\\Delta Mv+M\\Delta v+\\Delta M(v-v_e),\\\\\n0&=&M\\Delta v-\\Delta Mv_e.\n\\end{eqnarray*}\n$$\n\nIn the second step we ignored the term $\\Delta M\\Delta v$ since we\nassume it is small. The last equation gives\n\n$$\n\\begin{eqnarray}\n\\Delta v&=&\\frac{v_e}{M}\\Delta M,\\\\\n\\nonumber\n\\frac{dv}{dt}&=&\\frac{v_e}{M}\\frac{dM}{dt}.\n\\end{eqnarray}\n$$\n\nHere we let $\\Delta v\\rightarrow dv$ and $\\Delta M\\rightarrow dM$.\nWe have also assumed that $M(t) = M_0-kt$. \nIntegrating the expression with lower limits $v_0=0$ and $M_0$, one finds\n\n$$\n\\begin{eqnarray*}\nv&=&v_e\\int_{M_0}^M \\frac{dM'}{M'}\\\\\nv&=&v_e\\ln(M/M_0)\\\\\n&=&v_e\\ln[(M_0-k t)/M_0].\n\\end{eqnarray*}\n$$\n\nWe have ignored gravity here. If we add gravity as the external force, we get when integrating an additional terms $-gt$, that is\n\n$$\nv=v_e\\ln[(M_0-k t)/M_0]-gt.\n$$\n\n* 3.11c\n\nInserting numbers $v_e=3000$ m/s, $M_0/M=2$ and $g=9.8$ m/s$^{2}$, we find $v=900$ m/s. With $g=0$ the corresponding number is $2100$ m/s, so gravity reduces the speed acquired in the first two minutes to a little less than half its weight-free value.\n\n* 3.11d\n\nIf the thrust $\\Delta Mv_e$ is less than the weight $mg$, the rocket will just sit on the ground until it has shed enough mass that the thrust can overcome the weight, definitely not a good design.\n\n### Exercise 3 (10pt), More Rockets\n\nTaylor exercises 3.13 (5pt) and 3.14 (5pt). This is a continuation of the previous exercise and most of the relevant background material can be found in Taylor chapter 3.2. \n\nTaking the velocity from the previous exercise and integrating over time we find the height\n\n$$\ny(t) = y(t_0=0)+\\int_0^tv(t')dt',\n$$\n\nwhich gives\n\n$$\ny(t) = v_et\\ln{M_0}-v_e\\int_0^t \\ln{M(t')}dt'-\\frac{1}{2}gt^2.\n$$\n\nTo do the integral over time we recall that $M(t')=M_0-\\Delta M t'$. We assumed that $\\Delta M=k$ is a constant.\nWe use that $M_0-M=kt$ and assume that mass decreases by a constant $k$ times time $t$.\n\nWe obtain then that the integral gives\n\n$$\n\\int_0^t \\ln{M(t')}dt' = \\int_0^t \\ln{(M_0-kt')}dt',\n$$\n\nand defining the variable $u=M_0-kt'$, with $du=-kdt'$ and the new limits $M_0$ when $t=0$ and $M_0-kt$ when time is equal to $t$, we have\n\n$$\n\\int_0^t \\ln{M(t')}dt' = \\int_0^t \\ln{(M_0-kt')}dt'=-\\frac{1}{k}\\int_{M_0}^{M_0-kt} \\ln{(u)}du=-\\frac{1}{k}\\left[u\\ln{(u)}-u\\right]_{M_0}^{M_0-kt},\n$$\n\nand writing out we obtain\n\n$$\n-\\frac{1}{k}\\left[u\\ln{(u)}-u\\right]_{M_0}^{M_0-kt} = \\frac{1}{k}\\left(M_0\\ln{M_0}-M\\ln{M}\\right)-t,\n$$\n\nMulitplying with $-v_e$ we have\n\n$$\n-\\frac{v_e}{k}\\left(M_0\\ln{M_0}-M\\ln{M}\\right)+v_et,\n$$\n\nwhich we can rewrite as, using $M_0=M+kt$,\n\n$$\n-\\frac{v_e}{k}\\left((M+kt)\\ln{M_0}-M\\ln{M}\\right)+v_et=v_et-v_et\\ln{M_0}-\\frac{Mv_e}{k}\\ln{(\\frac{M_0}{M})}.\n$$\n\nInserting into $y(t)$ we obtain then\n\n$$\ny(t) = v_et-\\frac{1}{2}gt^2-\\frac{Mv_e}{k}\\ln{(\\frac{M_0}{M})}.\n$$\n\nUsing the numbers from the previous exercise with $t=2$ min we obtain that $y\\approx 40$ km.\n\nFor exercise 3.14 (5pt) we have the equation of motion which reads $Ma=kv_e-bv$ or\n\n$$\n\\frac{Mdv}{kv_e-bv}=dt.\n$$\n\nWe have that $dM/dt =-k$ (assumed a constant rate for mass change). We can then replace $dt$ by $-dM/k$ and we have\n\n$$\n\\frac{kdv}{kv_e-bv}=-\\frac{dM}{M}.\n$$\n\nIntegrating gives\n\n$$\nv = \\frac{kv_e}{b}\\left[1-(\\frac{M}{M_0})^{b/k}\\right].\n$$\n\n### Exercise 4 (10pt), Center of mass\n\nTaylor exercise 3.20. Here Taylor's chapter 3.3 can be of use. This relation will turn out to be very useful when we discuss systems of many classical particles.\n\nThe definition of the center of mass for $N$ objects can be written as\n\n$$\nM\\boldsymbol{R}=\\sum_{i=1}^Nm_i\\boldsymbol{r}_i,\n$$\n\nwhere $m_i$ and $\\boldsymbol{r}_i$ are the masses and positions of object $i$, respectively.\n\nAssume now that we have a collection of $N_1$ objects with masses $m_{1i}$ and positions $\\boldsymbol{r}_{1i}$\nwith $i=1,\\dots,N_1$ and  a collection of $N_2$ objects with masses $m_{2j}$ and positions $\\boldsymbol{r}_{2j}$\nwith $j=1,\\dots,N_2$.\n\nThe total mass of the two-body system is $M=M_1+M_2=\\sum_{i=1}^{N_1}m_{1i}+\\sum_{j=1}^{N_2}m_{2j}$. The center of mass position $\\boldsymbol{R}$ of the whole system satisfies then\n\n$$\nM\\boldsymbol{R}=\\sum_{i=1}^{N_1}m_{1i}\\boldsymbol{r}_{1i}+\\sum_{j=1}^{N_2}m_{2j}\\boldsymbol{r}_{2j}=M_1\\boldsymbol{R}_1+M_2\\boldsymbol{R}_2,\n$$\n\nwhere $\\boldsymbol{R}_1$ and $\\boldsymbol{R}_2$ are the the center of mass positions of the two separate bodies and the second equality follows from our rewritten definition of the center of mass applied to each body separately. This is the required result.\n\n### Exercise 5 (10pt) and 6 (40pt)\n\n### Answers\n\nWe start with a simpler case first, the Earth-Sun system  in two dimensions only.  The gravitational force $F_G$ on the earth from the sun is\n\n$$\n\\boldsymbol{F}_G=-\\frac{GM_{\\odot}M_E}{r^3}\\boldsymbol{r},\n$$\n\nwhere $G$ is the gravitational constant,\n\n$$\nM_E=6\\times 10^{24}\\mathrm{Kg},\n$$\n\nthe mass of Earth,\n\n$$\nM_{\\odot}=2\\times 10^{30}\\mathrm{Kg},\n$$\n\nthe mass of the Sun and\n\n$$\nr=1.5\\times 10^{11}\\mathrm{m},\n$$\n\nis the distance between Earth and the Sun. The latter defines what we call an astronomical unit **AU**.\nFrom Newton's second law we have then for the $x$ direction\n\n$$\n\\frac{d^2x}{dt^2}=-\\frac{F_{x}}{M_E},\n$$\n\nand\n\n$$\n\\frac{d^2y}{dt^2}=-\\frac{F_{y}}{M_E},\n$$\n\nfor the $y$ direction.\n\nHere we will use  that  $x=r\\cos{(\\theta)}$, $y=r\\sin{(\\theta)}$ and\n\n$$\nr = \\sqrt{x^2+y^2}.\n$$\n\nWe can rewrite these equations\n\n$$\nF_{x}=-\\frac{GM_{\\odot}M_E}{r^2}\\cos{(\\theta)}=-\\frac{GM_{\\odot}M_E}{r^3}x,\n$$\n\nand\n\n$$\nF_{y}=-\\frac{GM_{\\odot}M_E}{r^2}\\sin{(\\theta)}=-\\frac{GM_{\\odot}M_E}{r^3}y,\n$$\n\nas four first-order coupled differential equations\n\n$$\n\\frac{dv_x}{dt}=-\\frac{GM_{\\odot}}{r^3}x,\n$$\n\nand\n\n$$\n\\frac{dx}{dt}=v_x,\n$$\n\nand\n\n$$\n\\frac{dv_y}{dt}=-\\frac{GM_{\\odot}}{r^3}y,\n$$\n\nand\n\n$$\n\\frac{dy}{dt}=v_y.\n$$\n\nThe four coupled differential equations\n\n$$\n\\frac{dv_x}{dt}=-\\frac{GM_{\\odot}}{r^3}x,\n$$\n\nand\n\n$$\n\\frac{dx}{dt}=v_x,\n$$\n\nand\n\n$$\n\\frac{dv_y}{dt}=-\\frac{GM_{\\odot}}{r^3}y,\n$$\n\nand\n\n$$\n\\frac{dy}{dt}=v_y,\n$$\n\ncan be turned into dimensionless equations or we can introduce astronomical units with $1$ AU = $1.5\\times 10^{11}$. \n\nUsing the equations from circular motion (with $r =1\\mathrm{AU}$)\n\n$$\n\\frac{M_E v^2}{r} = F = \\frac{GM_{\\odot}M_E}{r^2},\n$$\n\nwe have\n\n$$\nGM_{\\odot}=v^2r,\n$$\n\nand using that the velocity of Earth (assuming circular motion) is\n$v = 2\\pi r/\\mathrm{yr}=2\\pi\\mathrm{AU}/\\mathrm{yr}$, we have\n\n$$\nGM_{\\odot}= v^2r = 4\\pi^2 \\frac{(\\mathrm{AU})^3}{\\mathrm{yr}^2}.\n$$\n\nThe four coupled differential equations can then be discretized using Euler's method as (with step length $h$)\n\n$$\nv_{x,i+1}=v_{x,i}-h\\frac{4\\pi^2}{r_i^3}x_i,\n$$\n\nand\n\n$$\nx_{i+1}=x_i+hv_{x,i},\n$$\n\nand\n\n$$\nv_{y,i+1}=v_{y,i}-h\\frac{4\\pi^2}{r_i^3}y_i,\n$$\n\nand\n\n$$\ny_{i+1}=y_i+hv_{y,i},\n$$\n\nThe code here implements Euler's method for the Earth-Sun system using a more compact way of representing the vectors. Alternatively, you could have spelled out all the variables $v_x$, $v_y$, $x$ and $y$ as one-dimensional arrays.\n\n\n```\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n    os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n    os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n    os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n    return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n    return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n    plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n\nDeltaT = 0.01\n#set up arrays \ntfinal = 10 # in years\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, a, v, and x\nt = np.zeros(n)\nv = np.zeros((n,2))\nr = np.zeros((n,2))\n# Initial conditions as compact 2-dimensional arrays\nr0 = np.array([1.0,0.0])\nv0 = np.array([0.0,2*pi])\nr[0] = r0\nv[0] = v0\nFourpi2 = 4*pi*pi\n# Start integrating using Euler's method\nfor i in range(n-1):\n    # Set up the acceleration\n    # Here you could have defined your own function for this\n    rabs = sqrt(sum(r[i]*r[i]))\n    a =  -Fourpi2*r[i]/(rabs**3)\n    # update velocity, time and position using Euler's forward method\n    v[i+1] = v[i] + DeltaT*a\n    r[i+1] = r[i] + DeltaT*v[i]\n    t[i+1] = t[i] + DeltaT\n# Plot position as function of time    \nfig, ax = plt.subplots()\n#ax.set_xlim(0, tfinal)\nax.set_xlabel('x[AU]')\nax.set_ylabel('y[AU]')\nax.plot(r[:,0], r[:,1])\nfig.tight_layout()\nsave_fig(\"EarthSunEuler\")\nplt.show()\n```\n\nWe notice here that Euler's method doesn't give a stable orbit with for example $\\Delta t =0.01$. It\nmeans that we cannot trust Euler's method. Euler's method does not conserve energy. It is an\nexample of an integrator which is not\n[symplectic](https://en.wikipedia.org/wiki/Symplectic_integrator).\n\nHere we present thus two methods, which with simple changes allow us\nto avoid these pitfalls. The simplest possible extension is the\nso-called Euler-Cromer method.  The changes we need to make to our\ncode are indeed marginal here.  We need simply to replace\n\n\n```\n    r[i+1] = r[i] + DeltaT*v[i]\n```\n\nin the above code with the velocity at the new time $t_{i+1}$\n\n\n```\n    r[i+1] = r[i] + DeltaT*v[i+1]\n```\n\nBy this simple caveat we get stable orbits.  Below we derive the\nEuler-Cromer method as well as one of the most utlized algorithms for\nsolving the above type of problems, the so-called Velocity-Verlet\nmethod.\n\nLet us repeat Euler's method.\nWe have a differential equation\n\n<!-- Equation labels as ordinary links -->\n<div id=\"_auto1\"></div>\n\n$$\n\\begin{equation}\n  y'(t_i)=f(t_i,y_i)   \n\\label{_auto1} \\tag{1}\n\\end{equation}\n$$\n\nand if we truncate at the first derivative, we have from the Taylor expansion\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:euler\"></div>\n\n$$\n\\begin{equation}\n   y_{i+1}=y(t_i) + (\\Delta t) f(t_i,y_i) + O(\\Delta t^2), \\label{eq:euler} \\tag{2}\n\\end{equation}\n$$\n\nwhich when complemented with $t_{i+1}=t_i+\\Delta t$ forms\nthe algorithm for the well-known Euler method. \nNote that at every step we make an approximation error\nof the order of $O(\\Delta t^2)$, however the total error is the sum over all\nsteps $N=(b-a)/(\\Delta t)$ for $t\\in [a,b]$, yielding thus a global error which goes like\n$NO(\\Delta t^2)\\approx O(\\Delta t)$. \n\nTo make Euler's method more precise we can obviously\ndecrease $\\Delta t$ (increase $N$), but this can lead to loss of numerical precision.\nEuler's method is not recommended for precision calculation,\nalthough it is handy to use in order to get a first\nview on how a solution may look like.\n\nEuler's method is asymmetric in time, since it uses information about the derivative at the beginning\nof the time interval. This means that we evaluate the position at $y_1$ using the velocity\nat $v_0$. A simple variation is to determine $x_{n+1}$ using the velocity at\n$v_{n+1}$, that is (in a slightly more generalized form)\n\n<!-- Equation labels as ordinary links -->\n<div id=\"_auto2\"></div>\n\n$$\n\\begin{equation} \n   y_{n+1}=y_{n}+ v_{n+1}+O(\\Delta t^2)\n\\label{_auto2} \\tag{3}\n\\end{equation}\n$$\n\nand\n\n<!-- Equation labels as ordinary links -->\n<div id=\"_auto3\"></div>\n\n$$\n\\begin{equation}\n   v_{n+1}=v_{n}+(\\Delta t) a_{n}+O(\\Delta t^2).\n\\label{_auto3} \\tag{4}\n\\end{equation}\n$$\n\nThe acceleration $a_n$ is a function of $a_n(y_n, v_n, t_n)$ and needs to be evaluated\nas well. This is the Euler-Cromer method. It is easy to change the above code and see that with the same \ntime step we get stable results.\n\nLet us stay with $x$ (position) and $v$ (velocity) as the quantities we are interested in.\n\nWe have the Taylor expansion for the position given by\n\n$$\nx_{i+1} = x_i+(\\Delta t)v_i+\\frac{(\\Delta t)^2}{2}a_i+O((\\Delta t)^3).\n$$\n\nThe corresponding expansion for the velocity is\n\n$$\nv_{i+1} = v_i+(\\Delta t)a_i+\\frac{(\\Delta t)^2}{2}v^{(2)}_i+O((\\Delta t)^3).\n$$\n\nVia Newton's second law we have normally an analytical expression for the derivative of the velocity, namely\n\n$$\na_i= \\frac{d^2 x}{dt^2}\\vert_{i}=\\frac{d v}{dt}\\vert_{i}= \\frac{F(x_i,v_i,t_i)}{m}.\n$$\n\nIf we add to this the corresponding expansion for the derivative of the velocity\n\n$$\nv^{(1)}_{i+1} = a_{i+1}= a_i+(\\Delta t)v^{(2)}_i+O((\\Delta t)^2)=a_i+(\\Delta t)v^{(2)}_i+O((\\Delta t)^2),\n$$\n\nand retain only terms up to the second derivative of the velocity since our error goes as $O(h^3)$, we have\n\n$$\n(\\Delta t)v^{(2)}_i\\approx a_{i+1}-a_i.\n$$\n\nWe can then rewrite the Taylor expansion for the velocity as\n\n$$\nv_{i+1} = v_i+\\frac{(\\Delta t)}{2}\\left( a_{i+1}+a_{i}\\right)+O((\\Delta t)^3).\n$$\n\nOur final equations for the position and the velocity become then\n\n$$\nx_{i+1} = x_i+(\\Delta t)v_i+\\frac{(\\Delta t)^2}{2}a_{i}+O((\\Delta t)^3),\n$$\n\nand\n\n$$\nv_{i+1} = v_i+\\frac{(\\Delta t)}{2}\\left(a_{i+1}+a_{i}\\right)+O((\\Delta t)^3).\n$$\n\nNote well that the term $a_{i+1}$ depends on the position at $x_{i+1}$. This means that you need to calculate \nthe position at the updated time $t_{i+1}$ before the computing the next velocity.  Note also that the derivative of the velocity at the time\n$t_i$ used in the updating of the position can be reused in the calculation of the velocity update as well. \n\nWe can now easily add the Verlet method to our original code as\n\n\n```\nDeltaT = 0.01\n#set up arrays \ntfinal = 10\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, a, v, and x\nt = np.zeros(n)\nv = np.zeros((n,2))\nr = np.zeros((n,2))\n# Initial conditions as compact 2-dimensional arrays\nr0 = np.array([1.0,0.0])\nv0 = np.array([0.0,2*pi])\nr[0] = r0\nv[0] = v0\nFourpi2 = 4*pi*pi\n# Start integrating using the Velocity-Verlet  method\nfor i in range(n-1):\n    # Set up forces, air resistance FD, note now that we need the norm of the vecto\n    # Here you could have defined your own function for this\n    rabs = sqrt(sum(r[i]*r[i]))\n    a =  -Fourpi2*r[i]/(rabs**3)\n    # update velocity, time and position using the Velocity-Verlet method\n    r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a\n    rabs = sqrt(sum(r[i+1]*r[i+1]))\n    anew = -4*(pi**2)*r[i+1]/(rabs**3)\n    v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n    t[i+1] = t[i] + DeltaT\n# Plot position as function of time    \nfig, ax = plt.subplots()\nax.set_xlabel('x[AU]')\nax.set_ylabel('y[AU]')\nax.plot(r[:,0], r[:,1])\nfig.tight_layout()\nsave_fig(\"EarthSunVV\")\nplt.show()\n```\n\nYou can easily generalize the calculation of the forces by defining a function\nwhich takes in as input the various variables. We leave this as a challenge to you.\n\nRunning the above code for various time steps we see that the Velocity-Verlet is fully stable for various time steps.\n\nWe can also play around with different initial conditions in order to find the escape velocity from an orbit around the sun with distance one astronomical unit, 1 AU. The theoretical value for the escape velocity, is given by\n\n$$\nv = \\sqrt{8\\pi^2}{r},\n$$\n\nand with $r=1$ AU, this means that the escape velocity is $2\\pi\\sqrt{2}$ AU/yr. To obtain this we required that the kinetic energy of Earth equals the potential energy given by the gravitational force.\n\nSetting\n\n$$\n\\frac{1}{2}M_{\\mathrm{Earth}}v^2=\\frac{GM_{\\odot}}{r},\n$$\n\nand with $GM_{\\odot}=4\\pi^2$ we obtain the above relation for the velocity. Setting an initial velocity say equal to $9$ in the above code, yields a planet (Earth) which escapes a stable orbit around the sun, as seen by running the code here.\n\n\n```\nDeltaT = 0.01\n#set up arrays \ntfinal = 100\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, a, v, and x\nt = np.zeros(n)\nv = np.zeros((n,2))\nr = np.zeros((n,2))\n# Initial conditions as compact 2-dimensional arrays\nr0 = np.array([1.0,0.0])\n# setting initial velocity larger than escape velocity\nv0 = np.array([0.0,9.0])\nr[0] = r0\nv[0] = v0\nFourpi2 = 4*pi*pi\n# Start integrating using the Velocity-Verlet  method\nfor i in range(n-1):\n    # Set up forces, air resistance FD, note now that we need the norm of the vecto\n    # Here you could have defined your own function for this\n    rabs = sqrt(sum(r[i]*r[i]))\n    a =  -Fourpi2*r[i]/(rabs**3)\n    # update velocity, time and position using the Velocity-Verlet method\n    r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a\n    rabs = sqrt(sum(r[i+1]*r[i+1]))\n    anew = -4*(pi**2)*r[i+1]/(rabs**3)\n    v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n    t[i+1] = t[i] + DeltaT\n# Plot position as function of time    \nfig, ax = plt.subplots()\nax.set_xlabel('x[AU]')\nax.set_ylabel('y[AU]')\nax.plot(r[:,0], r[:,1])\nfig.tight_layout()\nsave_fig(\"EscapeEarthSunVV\")\nplt.show()\n```\n", "meta": {"hexsha": "f516d79762fa60e8229e1dc907c3fbfde93f9d7a", "size": 47072, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/Homeworks/hw5/solution/solutionhw5.ipynb", "max_stars_repo_name": "Shield94/Physics321", "max_stars_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/Homeworks/hw5/solution/solutionhw5.ipynb", "max_issues_repo_name": "Shield94/Physics321", "max_issues_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/Homeworks/hw5/solution/solutionhw5.ipynb", "max_forks_repo_name": "Shield94/Physics321", "max_forks_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5124875125, "max_line_length": 411, "alphanum_fraction": 0.5212015636, "converted": true, "num_tokens": 7532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12085323882332893, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.03877229328816729}}
{"text": "```python\n#we may need some code in the ../python directory and/or matplotlib styles\nimport sys\nimport os\nsys.path.append('../python/')\n\n#set up matplotlib\nos.environ['MPLCONFIGDIR'] = '../mplstyles'\nprint(os.environ['MPLCONFIGDIR'])\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\n#got smarter about the mpl config: see mplstyles/ directory\nplt.style.use('standard')\nprint(mpl.__version__) \nprint(mpl.get_configdir())\n\n\n#fonts\n# Set the font dictionaries (for plot title and axis titles)\ntitle_font = {'fontname':'Arial', 'size':'16', 'color':'black', 'weight':'normal',\n              'verticalalignment':'bottom'} # Bottom vertical alignment for more space\naxis_font = {'fontname':'Arial', 'size':'32'}\nlegend_font = {'fontname':'Arial', 'size':'22'}\n\n#fonts global settings\nmpl.rc('font',family=legend_font['fontname'])\n\n\n#set up numpy\nimport numpy as np\n```\n\n    ../mplstyles\n    3.0.3\n    /home/phys/villaa/analysis/misc/nrFano_paper2019/mplstyles\n\n\n# Summary\n\nThe purpose of this book is to show how the extracted Fano factor, combined with the expected yield with plus multiple-scatter modification, can predict the trend of the EDELWEISS measured ionization yield width. And, how that final predicted width function can be used to extract the systematic deviation due to the finite binning of the EDELWEISS data. \n\n# Extracted Fano Factor Matching\n\n\n```python\nimport h5py\nfilename = 'data/systematic_error_fits.h5'\n#remove vars\nf = h5py.File(filename,'r')\n#for i in f['mcmc/edwdata_sys_error']:\n#    print(i)\n\n#save the results for the Edw fit\npath='{}/{}/'.format('mcmc','edwdata_sys_error')\n\nCms = np.asarray(f[path+'Cms'])\nslope = np.asarray(f[path+'m'])\na_yield = np.asarray(f[path+'A'])\nb_yield = np.asarray(f[path+'B'])\naH = np.asarray(f[path+'aH'])\nscale = np.asarray(f[path+'scale'])\nsamples = np.asarray(f[path+'samples'])\nsampsize = np.asarray(f[path+'sampsize'])\nxl = np.asarray(f[path+'Er'])\nupvec = np.asarray(f[path+'Csig_u'])\ndnvec = np.asarray(f[path+'Csig_l'])\nSigtot = np.asarray(f[path+'Sigss'])\nSigss = np.sqrt(Sigtot**2 - (Cms+slope*xl)**2)\n\nprint(Cms)\nprint(samples[0:5,:])\nf.close()\n```\n\n    0.040112000594491624\n    [[1.50381624e-02 4.31804341e-02 2.23413626e-05 1.05046922e+00\n      8.18547846e-02 2.04466981e-01]\n     [1.51415346e-02 4.35824578e-02 1.31947144e-05 1.04823979e+00\n      8.24564001e-02 1.90742152e-01]\n     [1.51415346e-02 4.35824578e-02 1.31947144e-05 1.04823979e+00\n      8.24564001e-02 1.90742152e-01]\n     [1.51415346e-02 4.35824578e-02 1.31947144e-05 1.04823979e+00\n      8.24564001e-02 1.90742152e-01]\n     [1.51415346e-02 4.35824578e-02 1.31947144e-05 1.04823979e+00\n      8.24564001e-02 1.90742152e-01]]\n\n\n\n```python\nimport fano_calc as fc\n#recall defaults (filename='test.h5', \n#det='GGA3',band='ER',F=0.00001,V=4.0,alpha=(1/10000.0),aH=0.035,Erv=None,sigv=None,erase=False)\nE,sig = fc.RWCalc(filename='data/res_calc.h5',band='NR',alpha=(1/18.0),F=999)\n#Ebase,sigbase = fc.RWCalc(filename='data/res_calc.h5',band='NR',alpha=(1/18.0),F=000)\n\nimport EdwRes as er\n#instead I should use Amy's Fit\nf = er.get_sig_nuc_func_alt(1.3,1.5,3.1,0.4,2.7,pars={'V':scale*4.0,'eps_eV':3.0,'a':a_yield,'b':b_yield}, \\\n                            aH=aH,C=0,m=0)\nEbase = np.arange(0.1,200,0.1)\nsigbase = f(Ebase)\n```\n\n\n```python\n# import data from Edelweiss\nimport pandas as pds\nres_data = pds.read_csv(\"data/edelweiss_NRwidth_GGA3_data.txt\", skiprows=1, \\\n                       names=['E_recoil', 'sig_NR', 'E_recoil_err', 'sig_NR_err'], \\\n                       delim_whitespace=True)\n\nresER_data = pds.read_csv(\"data/edelweiss_ERwidth_GGA3_data.txt\", skiprows=1, \\\n                         names=['E_recoil', 'sig_ER', 'sig_ER_err'], \\\n                         delim_whitespace=True)\n\nresER_data = resER_data.sort_values(by='E_recoil')\n\nprint (res_data.head(10))\nE_recoil = res_data[\"E_recoil\"]\nsig_NR = res_data[\"sig_NR\"]\nsig_NR_err = res_data['sig_NR_err']\nE_recoil_ER = resER_data[\"E_recoil\"]\nsig_ER = resER_data[\"sig_ER\"]\nsig_ER_err = resER_data['sig_ER_err']\n\n#order those things\nidx = np.argsort(E_recoil)\nE_recoil = E_recoil[idx]\nsig_NR = sig_NR[idx]\nsig_NR_err = sig_NR_err[idx]\n\n#make a selectable version of the minimum index\nminidx = 2\n```\n\n       E_recoil    sig_NR  E_recoil_err  sig_NR_err\n    0   16.1946  0.062345      0.946176    0.001157\n    1   16.4428  0.062345      0.945278    0.001157\n    2   44.2627  0.046528      0.992477    0.001543\n    3   24.5012  0.059397      0.992477    0.001185\n    4   97.7172  0.044847      1.033260    0.002783\n    5   58.4014  0.050082      0.991830    0.002288\n    6   34.2156  0.053417      1.033260    0.001102\n\n\n\n```python\n#set up a 1d plot\nfig,axes = plt.subplots(1,1,figsize=(9.0,8.0),sharex=True)\nax1 = axes\n\nfor aH_em, Cms_em, m_em, scale_em, A_em, B_em in samples[np.random.randint(len(samples), size=100)]:\n    ax1.plot(xl, np.sqrt(Sigss**2+(Cms_em+m_em*xl)**2), color=\"orange\", alpha=0.1)\n\nax1.plot(xl,upvec,color='r',linestyle=\"--\",linewidth=2, \\\n         label='1$\\sigma$ fluct.')\nax1.plot(xl,dnvec,color='r',linestyle=\"--\",linewidth=2, \\\n         label='')\n\n\nax1.plot(xl,np.sqrt(Sigss**2+(Cms+xl*slope)**2),color='g',linestyle=\"-\",linewidth=3, \\\n         label='(C$_0$={:01.3}; m={:01.2E})'.format(Cms,slope))\n\nax1.plot(E,sig,color='b',linestyle=\":\",linewidth=2, \\\n        label = 'Extracted Fano')\n\nax1.errorbar(E_recoil[minidx::],sig_NR[minidx::], yerr=sig_NR_err[minidx::], \\\n         color='k', marker='o', markersize=4,linestyle='none',label='NR Edw. Measurement', linewidth=2)\n\nymin = 0.04\nymax = 0.1\n\n\n\nax1.set_yscale('linear')\n#ax1.set_yscale('log')\nax1.set_xlim(10, 200) \nax1.set_ylim(ymin,ymax)\nax1.set_xlabel(r'recoil energy [keV]',**axis_font)\nax1.set_ylabel('ionization yield width',**axis_font)\nax1.grid(True)\nax1.yaxis.grid(True,which='minor',linestyle='--')\nax1.legend(loc=1,prop={'size':22})\n#ax1.legend(bbox_to_anchor=(1.04,1),borderaxespad=0,prop={'size':22})\n\nfor axis in ['top','bottom','left','right']:\n  ax1.spines[axis].set_linewidth(2)\n\nplt.tight_layout()\n#plt.savefig('figures/figure.png')\nplt.show()\n```\n\n# Binning Systematic\n\nenergy bin|interval (keV)\n:-|:-\n0|\\[5,10)\n1|\\[10,20)\n2|\\[20,30)\n3|\\[30,40)\n4|\\[40,50)\n5|\\[50,70)\n6|\\[70,150)\n\n\n```python\nbins = [5, 10, 20, 30, 40, 50, 70,150]\nbins = np.asarray(bins)\n```\n\nIn order to evaluate the systematic we can approximate that the distribution in ionization yield at each energy is normal. That is it follows the probability distribution function:\n\n\\begin{equation}\nP(Q|E_r) = \\frac{1}{\\sqrt{2\\pi\\sigma_Q(E_r)^2}} \\exp{\\left[\\frac{(Q-\\bar{Q})^2}{2\\sigma_Q(E_r)^2}\\right]},\n\\end{equation}\n\nIs valid for a fixed energy, $E_r$. \n\nUsing the law of conditional probability we can then simply obtain the joint distribution $P(Q,E_r)$ and integrate over the recoil energy bin. We get the following:\n\n\\begin{equation}\nP_i(Q) = \\frac{\\int_{a_i}^{b_i} dE_r P(Q|E_r)P(E_r)}{N},\n\\end{equation}\n\nwhere N is a normalization factor, $P_i(Q)$ is the yield probability distribution over the bin $i$, and $P(E_r)$ is the probability of getting a given recoil energy (approximated throughout this analysis as an exponential with decay coefficient $\\alpha$ = (1/18.0) keV$^{-1}$).\n\nWith this function the _measured_ yield width over a finite bin can be calculated quite simply:\n\n\\begin{equation}\n\\begin{aligned}\n\\langle Q \\rangle &= \\int_{-\\infty}^{\\infty} dQ Q P(Q) \\\\\n\\langle Q^2 \\rangle &= \\int_{-\\infty}^{\\infty} dQ Q^2 P(Q) \\\\\n\\sigma_{Qi} &= \\sqrt{\\langle Q^2 \\rangle - \\langle Q \\rangle^2}\n\\end{aligned}\n\\end{equation}\n\n\n```python\n#let's find the corrections for the best fit points\nimport binning_sys as bsys\n\n\nprint(bins)\ndelta = lambda C,m: bsys.getBinSys(C,m,bins=bins)[1]\ndeltav = np.vectorize(delta)\n\n\ndel110 = deltav(Cms,slope)\ndel110 = np.array(del110)\nprint(del110)\n#print(np.shape(deltav(Candm[:,0],Candm[:,1])))\n#del110 = deltav(Candm[:,0],Candm[:,1])\n#print(delta(Candm[0,0],Candm[0,1]))\n```\n\n    [  5  10  20  30  40  50  70 150]\n    here\n    here\n    [0.95090318 0.93151709 0.97537397 0.98806036 0.99327094 0.98675077\n     0.97495657]\n\n\n\n```python\n#let's make a callable out of the predicted single-scatter resolution\nimport scipy.interpolate as inter\n\nsigQnr_c = inter.InterpolatedUnivariateSpline(Ebase, sigbase, k=3)\nsigQnr_c_v = np.vectorize(sigQnr_c)\n```\n\n\n```python\ndef log_likelihood(theta, x, y, yerr,sigfunc):\n    Cms, m = theta\n    model = np.sqrt(sigfunc(x)**2 + (Cms+m*x)**2)\n    #sigma2 = yerr**2 + model**2*np.exp(2*log_f)\n    sigma2 = yerr**2\n    return -0.5*np.sum((y-model)**2/sigma2 + np.log(sigma2))\n```\n\n\n```python\nfrom scipy.optimize import minimize\nnp.random.seed(42)\nnll = lambda *args: -log_likelihood(*args)\ninitial = np.array([0.0207, 4.73e-5]) + 0.001*np.random.randn(2)\nsoln = minimize(nll, initial, args=(E_recoil[minidx::], sig_NR[minidx::], sig_NR_err[minidx::],sigQnr_c_v))\nCms_ml, m_ml = soln.x\n\n#lmfout = lmf.minimize(residual_const, params, args=(E_recoil[2::], sig_NR[2::], sig_NR_err[2::],sigQnr_c_v))\nprint(\"Maximum likelihood estimates:\")\nprint(\"m = {0:.4f}\".format(Cms_ml))\nprint(\"b = {0:.3e}\".format(m_ml))\n\n```\n\n    Maximum likelihood estimates:\n    m = 0.0401\n    b = 4.113e-05\n\n\n\n```python\n#do correction to data points\nE_edw = E_recoil\nsig_edw = sig_NR*del110\nsig_edw_err = sig_NR_err*del110\nprint(bins)\nprint(del110)\n\nprint(E_edw)\nprint(sig_NR)\nprint(sig_edw)\nprint(sig_edw_err)\n\nnll = lambda *args: -log_likelihood(*args)\ninitial = np.array([0.0207, 4.73e-5]) + 0.001*np.random.randn(2)\nsoln = minimize(nll, initial, args=(E_edw[minidx::], sig_edw[minidx::], sig_edw_err[minidx::],sigQnr_c_v))\nCms_ml, m_ml = soln.x\n\n#lmfout = lmf.minimize(residual_const, params, args=(E_recoil[2::], sig_NR[2::], sig_NR_err[2::],sigQnr_c_v))\nprint(\"Maximum likelihood estimates:\")\nprint(\"m = {0:.4f}\".format(Cms_ml))\nprint(\"b = {0:.3e}\".format(m_ml))\n```\n\n    [  5  10  20  30  40  50  70 150]\n    [0.95090318 0.93151709 0.97537397 0.98806036 0.99327094 0.98675077\n     0.97495657]\n    0    16.1946\n    1    16.4428\n    3    24.5012\n    6    34.2156\n    2    44.2627\n    5    58.4014\n    4    97.7172\n    Name: E_recoil, dtype: float64\n    0    0.062345\n    1    0.062345\n    3    0.059397\n    6    0.053417\n    2    0.046528\n    5    0.050082\n    4    0.044847\n    Name: sig_NR, dtype: float64\n    0    0.059284\n    1    0.058076\n    3    0.057934\n    6    0.052779\n    2    0.046215\n    5    0.049419\n    4    0.043724\n    Name: sig_NR, dtype: float64\n    0    0.001101\n    1    0.001078\n    3    0.001156\n    6    0.001089\n    2    0.001533\n    5    0.002257\n    4    0.002714\n    Name: sig_NR_err, dtype: float64\n    Maximum likelihood estimates:\n    m = 0.0386\n    b = 5.175e-05\n\n\n\n```python\n#set up a 1d plot\nfig,axes = plt.subplots(1,1,figsize=(9.0,8.0),sharex=True)\nax1 = axes\n\nfor aH_em, Cms_em, m_em, scale_em, A_em, B_em in samples[np.random.randint(len(samples), size=100)]:\n    ax1.plot(xl, np.sqrt(Sigss**2+(Cms_em+m_em*xl)**2), color=\"orange\", alpha=0.1)\n\nax1.plot(xl,upvec,color='r',linestyle=\"--\",linewidth=2, \\\n         label='1$\\sigma$ fluct.')\nax1.plot(xl,dnvec,color='r',linestyle=\"--\",linewidth=2, \\\n         label='')\n\n\nax1.plot(xl,np.sqrt(Sigss**2+(Cms+xl*slope)**2),color='g',linestyle=\"-\",linewidth=3, \\\n         label='(C$_0$={:01.3}; m={:01.2E})'.format(Cms,slope))\n\nax1.plot(xl,np.sqrt(Sigss**2+(Cms_ml+xl*m_ml)**2),color='b',linestyle=\"--\",linewidth=3, \\\n         label='bc (C$_0$={:01.3}; m={:01.2E})'.format(Cms_ml,m_ml))\n\nax1.plot(E,sig,color='b',linestyle=\":\",linewidth=2, \\\n        label = 'Extracted Fano')\n\nax1.errorbar(E_recoil[minidx::],sig_edw[minidx::], yerr=sig_edw_err[minidx::], \\\n         color='k', marker='o', markersize=4,linestyle='none',label='NR Edw. Measurement', linewidth=2)\n\nymin = 0.04\nymax = 0.1\n\n\n\nax1.set_yscale('linear')\n#ax1.set_yscale('log')\nax1.set_xlim(10, 200) \nax1.set_ylim(ymin,ymax)\nax1.set_xlabel(r'recoil energy [keV]',**axis_font)\nax1.set_ylabel('ionization yield width',**axis_font)\nax1.grid(True)\nax1.yaxis.grid(True,which='minor',linestyle='--')\nax1.legend(loc=1,prop={'size':22})\n#ax1.legend(bbox_to_anchor=(1.04,1),borderaxespad=0,prop={'size':22})\n\nfor axis in ['top','bottom','left','right']:\n  ax1.spines[axis].set_linewidth(2)\n\nplt.tight_layout()\n#plt.savefig('figures/figure.png')\nplt.show()\n```\n\n\n```python\nimport h5py\nfilename = 'data/test_bs_6par.h5'\n#remove vars\nf = h5py.File(filename,'r')\n\n#save the results for the Edw fit\npath='{}/{}/'.format('mcmc','edwdata_binsys')\n\nbins_binsys = np.asarray(f[path+'bins_binsys'])\nbinsys = np.asarray(f[path+'binsys'])\n\n\n#print(binsys)\nNsamp = np.shape(binsys)[0]\nprint(Nsamp)\nf.close()\n```\n\n    100\n\n\n\n```python\n#set up a 1d plot\nfig,axes = plt.subplots(1,1,figsize=(9.0,8.0),sharex=True)\nax1 = axes\n\nfor di in binsys:\n    #print(di)\n    soln = minimize(nll, initial, args=(E_edw[minidx::], sig_edw[minidx::]*di[minidx::],  \\\n                                        sig_edw_err[minidx::]*di[minidx::],sigQnr_c_v))\n    Cms_mli, m_mli = soln.x\n    #print(Cms_mli,m_mli)\n    ax1.plot(xl, np.sqrt(Sigss**2+(Cms_mli+m_mli*xl)**2), color=\"blue\", alpha=0.1)\n\nax1.plot(xl,upvec,color='r',linestyle=\"--\",linewidth=2, \\\n         label='1$\\sigma$ fluct.')\nax1.plot(xl,dnvec,color='r',linestyle=\"--\",linewidth=2, \\\n         label='')\n\n\nax1.plot(xl,np.sqrt(Sigss**2+(Cms+xl*slope)**2),color='g',linestyle=\"-\",linewidth=3, \\\n         label='(C$_0$={:01.3}; m={:01.2E})'.format(Cms,slope))\n\nax1.plot(xl,np.sqrt(Sigss**2+(Cms_ml+xl*m_ml)**2),color='b',linestyle=\"--\",linewidth=3, \\\n         label='bc (C$_0$={:01.3}; m={:01.2E})'.format(Cms_ml,m_ml))\n\nax1.plot(E,sig,color='b',linestyle=\":\",linewidth=2, \\\n        label = 'Extracted Fano')\n\nax1.errorbar(E_recoil[minidx::],sig_edw[minidx::], yerr=sig_edw_err[minidx::], \\\n         color='k', marker='o', markersize=4,linestyle='none',label='NR Edw. Measurement', linewidth=2)\n\nymin = 0.04\nymax = 0.1\n\n\n\nax1.set_yscale('linear')\n#ax1.set_yscale('log')\nax1.set_xlim(10, 200) \nax1.set_ylim(ymin,ymax)\nax1.set_xlabel(r'recoil energy [keV]',**axis_font)\nax1.set_ylabel('ionization yield width',**axis_font)\nax1.grid(True)\nax1.yaxis.grid(True,which='minor',linestyle='--')\nax1.legend(loc=1,prop={'size':22})\n#ax1.legend(bbox_to_anchor=(1.04,1),borderaxespad=0,prop={'size':22})\n\nfor axis in ['top','bottom','left','right']:\n  ax1.spines[axis].set_linewidth(2)\n\nplt.tight_layout()\n#plt.savefig('figures/figure.png')\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "2d7e59cd5e99b02a0d6920994ab9877325973aed", "size": 539994, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "analysis_notebooks/binning_systematic_Final.ipynb", "max_stars_repo_name": "villano-lab/nrFano_paper2019", "max_stars_repo_head_hexsha": "f44565bfb3e45b2dfbe2a73cba9f620a7120abd7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-04-06T17:27:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T20:38:54.000Z", "max_issues_repo_path": "analysis_notebooks/binning_systematic_Final.ipynb", "max_issues_repo_name": "villano-lab/nrFano_paper2019", "max_issues_repo_head_hexsha": "f44565bfb3e45b2dfbe2a73cba9f620a7120abd7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analysis_notebooks/binning_systematic_Final.ipynb", "max_forks_repo_name": "villano-lab/nrFano_paper2019", "max_forks_repo_head_hexsha": "f44565bfb3e45b2dfbe2a73cba9f620a7120abd7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 792.9427312775, "max_line_length": 195372, "alphanum_fraction": 0.9493031404, "converted": true, "num_tokens": 5152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.07807817318956282, "lm_q1q2_score": 0.0387340999357039}}
{"text": "# Week 3 \n## Introduction to Solid State \n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport subprocess\nfrom polypy.read import History\nfrom polypy.msd import MSD\nfrom polypy import plotting\n\ndef get_diffusion(file, atom):\n    \n    with open(file) as f:\n        y = False\n        for line in f:\n            if str(\"atom        D \") in line:\n                y = True\n            if y == True and str(atom) in line:\n                d = line.split()\n                break\n    return d\n```\n\n# Background#\n\n\nNow that you are familiar with molecular dynamics, you are now going to use it to tackle some real world problems. \n\nThe transport properties of a material determine many properties that are utilised for modern technological applications. For example, solid oxide fuel cell (SOFCs), which are an alternative to batteries, materials are dependent on the movement of charge carriers through the solid electrolyte. Another example are nuclear fuel materials which oxidise and fall apart - this corrosive behaviour is dependent on the diffusion of oxygen into the lattice. \n\nDue to the importance of the transport properties of these materials, scientists and engineers spend large amounts of their time tring to optomise these properties using different stoichiometries, introducing defects and by using different syntheisis techniques.\n\n# Aim and Objectives #\n\nThe **Aim** of the next **five weeks** is to **investigate** the transport properties of a simple fluorite material - CaF$_2$. \n\nThe **first objective** is to **investigate** how the transport properties of CaF$_2$ are affected by temperature\n\nThe **second objective** is to **investigate** how the transport properties of CaF$_2$ are affected by structural defects (Schottky and Frenkel)\n\nThe **third objective** is to **investigate** how the transport properties of CaF$_2$ are affected by chemcial dopants (e.g. different cations)\n\nA rough breakdown looks as follows:\n\n**Week 3** \n-  Molecular dynamics simulations of stoichiomteric CaF$_2$\n\n\n**Week 4**\n-  Molecular dynamics simulations of CaF$_2$ containing Schottky defects \n\n\n**Week 5**\n- Molecular dynamics simulations of CaF$_2$ containing Frenkel defects \n\n\n**Week 6**\n-  Molecular dynamics simulations of CaF$_2$ containing various dopants \n\n\n**Week 7**\n-  Molecular dynamics simulations of CaF$_2$ containing various dopants \n    \n\nBy these **five weeks** you will be able to:\n\n- **Perform** molecular dynamics simulations at different temperatures\n- **Manipulate** the input files\n- **Adjust** the ensemble for the simulation\n- **Examine** the volume and energy of different simulations\n- **Apply** VMD to visualize the simulation cell and evaluate radial distribution - coefficients\n\nThe **Aim** of this **week** (week 3) is to **investigate** the temperature-dependence of the transport properties of a simple fluorite material CaF$_2$ using molecular dynamics (MD). \n\nThe **first objective** is to **familiarise** yourself with the molecular simulation software package <code>DL_POLY</code>\n\nThe **second objective** is to **complete** a tutorial which demonstrates how to calculate diffusion coefficients\n\nThe **third objective** is to is to **complete** a tutorial which demonstrates how to **calculate** the activation energy barrier of F diffusion \n\n## Introduction to DL_POLY\n\n<code>DL_POLY</code> is a molecular dynamics (MD) program maintained by Daresbury laboratories. In contrast to <code>pylj</code>, <code>DL_POLY</code> is a three-dimensional MD code that is used worldwide by computational scientists for molecular simulation, but it should be noted that the theory is exactly the same and any understanding gained from <code>pylj</code> is completely applicable to <code>DL_POLY</code>. \n\nFor the next five weeks you will use <code>DL_POLY</code> to run short MD simulations on CaF$_2$. You first need to understand the input files required for <code>DL_POLY</code>.\n\n<code>**CONTROL**</code>\n\nThis is the file that contains all of the simulation parameters, e.g. simulation temperature, pressure, number of steps etc.\n\n<code>**CONFIG**</code>\n\nThis is the file that contains the structure - i.e. the atomic coordinates of each atom.\n\n<code>**FIELD**</code> \n\nThis is the file that contains the force field or potential model e.g. Lennard-Jones. \n\n# Exercise 1: Setting Up an MD Simulation#\n\nFirst, we will use <code>METADISE</code> to produce <code>DL_POLY</code> input files.\n\nContained within the folder <code>Input/</code> you will find a file called <code>input.txt</code>. \n\nThis is the main file that you will interact with over the next five weeks and is the input file for <code>METADISE</code> which generates the 3 <code>DL_POLY</code> input files: <code>FIELD</code>, <code>CONTROL</code> and <code>CONFIG</code>. \n\nEssentially it is easier to meddle with <code>input.txt</code> than it is to meddle with the 3 <code>DL_POLY</code> files everytime you want to change something. \n\nTo run <code>METADISE</code> we will use the <code>subprocess</code> <code>python</code> module. \n\nTo use <code>subprocess</code> - specify what program you want to run and the file that you want to run it in, you will need to ensure the file path is correct. \n\nTo **generate** the 3 <code>DL_POLY</code> input files: <code>FIELD</code>, <code>CONTROL</code> and <code>CONFIG</code>, **run** the cell below:\n\n#### It is essential that the codes that were downloaded from [here](https://people.bath.ac.uk/chsscp/teach/adv.bho/progs.zip) are in the Codes/ folder in the parent directory, or this following cell will crash. \n\n\n```python\nsubprocess.call('../Codes/metadise.exe', cwd='Input/')\nos.rename('Input/control_o0001.dlp', 'Input/CONTROL')\nos.rename('Input/config__o0001.dlp', 'Input/CONFIG')\nos.rename('Input/field___o0001.dlp', 'Input/FIELD')\n```\n\nNow you should have a <code>CONFIG</code>, <code>CONTROL</code> and <code>FIELD</code> file within the <code>Input/</code> directory. \n\nIn theory you could just call the <code>DL_POLY</code> program in this directory and your simulation would run. \n\nHowever, we need to tweak the <code>CONTROL</code> file in order to set up our desired simulation. \n\n1. **Make** a new subdirectory in the <code>week 3</code> directory named <code>\"Example/\"</code> and copy <code>CONFIG</code>, <code>CONTROL</code> and <code>FIELD</code> to that subdirectory. \n\n2. Now **edit** the <code>CONTROL</code> file to change the following:  \n\n<code>Temperature 300 ---> Temperature 1500  \nSteps 5001 ---> Steps 40000  \nensemble nve ---> ensemble npt hoover 0.1 0.5  \ntrajectory nstraj= 1    istraj=   250 keytrj=0 ---> trajectory nstraj= 0   istraj= 100  keytrj=0</code>  \n\n3.Now your simulation is ready, **check** the structure before you run the simulation. You can view the <code>CONFIG</code> file in three dimensions using the VESTA program \n\nIt is always good to **check** your structure before (<code>CONFIG</code>) and after (<code>REVCON</code>) the simulation. \nYou can view the <code>CONFIG</code> and <code>REVCON</code> files in three dimensions using the <code>VESTA</code> program. <code>VESTA</code> can generate nice pictures which will look very good in a lab report. \n\n<center>\n    <br>\n    \n    <i>Figure 1. Fluorite CaF$_2$ unit cell visualised in VESTA.</i>\n    <br>\n</center>\n\n# Exercise 2: Running an MD Simulation\n\nNow we have <code>DL_POLY</code> input files, we will run an MD simulation using <code>DL_POLY</code>.\n\n1. **Run** <code>DL_POLY</code> from within the notebook use the command below \n\nKeep in mind that this simulation will take 20 or so minutes so be patient. \n\nIf you are not comfortable with running things through this notebook then you can copy and paste the <code>dlpoly_classic.exe</code> executable into the Example/ sub directory and then **double click** the <code>.exe</code> file\n\n\n```python\nsubprocess.call('../Codes/dlpoly_classic.exe', cwd='Example/')\n```\n\n# Exercise 3: Inspecting an MD Simulation\n\nNow we have run an MD simulation using <code>DL_POLY</code> we can analyse the data using the <code>VESTA</code>\n\n\nOnce <code>DL_POLY</code> has completed you will find several files relating to your simulaton. \n\n<code> **HISTORY** </code>\n\nThis file contains the configuration of your system at each step during the simulation, known as a _trajectory_. You can view this as a movie using <code>VMD</code> \n\n<code> **STATIS** </code>\n\nContains the statistics at each step of the simulation.\n\n<code> **OUTPUT** </code>\n\nContains various properties of the simulation. \n\n<code> **REVCON** </code> \n\nThis is the configuration at the end of the simulation.  Can be viewed in <code>VESTA</code>. **Check** to see how it has changed, compare it to the <code>CONFIG</code> file. \n\n\n# Exercise 4: Analysing the Diffusion Properties\n\n\nNow we have inspected the final structure from the simulation, we can calculate the diffusion coefficient.\n\n\n## Mean Squared Displacements - Calculating Diffusion Coefficients\n\nAs we have seen molecules in liquds, gases and solids do not stay in the same place and move constantly. Think about a drop of dye in a glass of water, as time passes the dye distributes throughout the water. This process is called diffusion and is common throughout nature.  \n\nUsing the dye as an example, the motion of a dye molecule is not simple. As it moves it is jostled by collisions with other molecules, preventing it from moving in a straight path. If the path is examined in close detail, it will be seen to be a good approximation to a _random walk_. \n\nIn mathmatics, a random walk is a series of steps, each taken in a random direction. This was analysed by Albert Einstein in a study of _Brownian motion_ and he showed that the mean square of the distance travelled by a particle following a random walk is proportional to the time elapsed, as given by: \n\\begin{align}\n\\Big \\langle r^2 \\big \\rangle & = 6 D_t + C \n\\end{align}\n\nwhere $\\Big \\langle r^2 \\big \\rangle$ is the mean squared distance, t is time, D is the diffusion rate and C is a constant. \n\n## What is the Mean Squared Displacement?\n\nGoing back to the example of the dye in water, lets assume for the sake of simplicity that we are in one dimension. Each step can either be forwards or backwards and we cannot predict which.\nFrom a given starting position, what distance is our dye molecule likely to travel after 1000 steps? This can be determined simply by adding together the steps, taking into account the fact that steps backwards subtract from the total, while steps forward add to the total. Since both forward and backward steps are equally probable, we come to the surprising conclusion that the probable distance travelled sums up to zero.\n\nBy adding the square of the distance we will always be adding positive numbers to our total which now increases linearly with time. Based upon equation 1 it should now be clear that a plot of $\\Big \\langle r^2 \\big \\rangle$ vs time with produce a line, the gradient of which is equal to 6D. Giving us direct access to the diffusion coefficient of the system. \n\nLets try explore this with an example. \n\n1. **Run** a short <code>DL_POLY</code> simulation on the input files provided.\n\nYou will run a small MSD program called <code>MSD.py</code> to analyse your simulation results.\n\nFirst you need to **read** in the data. The <code>HISTORY</code> file contains a list of the atomic coordiantes held by the atoms during the simulation. \n\n2.**Run** the cell below to read the <code>HISTORY</code> file into the <code>Jupyter Notebook</code>\n\n\n```python\n## Provide the path to the simulation and the atom that you want data for.\ndata = History(\"Example/HISTORY\", \"F\")\n```\n\n<code>data</code> is a class object containing information about the trajectory. \nMore information can be found here https://polypy.readthedocs.io/en/latest/reading_data.html and here https://github.com/symmy596/Polypy/blob/master/polypy/read.py .\n\nThe next step is to calculate the MSD. \n\n3.**Run** the cell below to calculate the MSD of the chosen atom throughout the course of the simulation\n\n\n```python\n# Run the MSD calculation\n\nf_msd = MSD(data.trajectory, sweeps=2)\n\noutput = f_msd.msd()\n```\n\nThe MSD calculation function returns an object with imformation about the MSD calculation. \n\nMore information and a full tutorial on this functionality can be found here https://polypy.readthedocs.io/en/latest/msd_tutorial.html\n\n4.**Run** the cell below to give plots of the MSD which have a nice linear relationship. \n\n\n```python\nax = plotting.msd_plot(output)\nplt.show()\n```\n\n\n```python\nprint(\"Three Dimensional Diffusion Coefficient\", output.xyz_diffusion_coefficient())\nprint(\"One Dimensional Diffusion Coefficient in X\", output.x_diffusion_coefficient())\nprint(\"One Dimensional Diffusion Coefficient in Y\", output.y_diffusion_coefficient())\nprint(\"One Dimensional Diffusion Coefficient in Z\", output.z_diffusion_coefficient())\n```\n\n# Exercise 5: The Effect of Simulation Length\n\nNow we have calculated the diffusion coefficient, we can investigate the influence of simulation length on the diffusion coefficient.\n\nIt is important to consider the length of your simulation (the number of steps). \n\n1. **Create** a new folder called <code>\"Example_2/\"</code>\n2. **Copy** the <code>CONFIG</code>, <code>FIELD</code> and <code>CONTROL</code> files from your previous simulation \n3. **Change** the number of steps to 10000\n4. **Rerun** the simulation by **running** the cell below\n\n\n```python\nsubprocess.call('../Codes/dlpoly_classic.exe', cwd='Example_2/')\n```\n\n5.**Run** the cell below to calculate and plot the MSD of the chosen atom throughout the course of the simulation\n\n\n```python\ndata = History(\"Example_2/HISTORY\", \"F\")\n\n# Run the MSD calculation\nf_msd = MSD(data.trajectory, sweeps=2)\n\noutput = f_msd.msd()\nax = plotting.msd_plot(output)\nplt.show()\n```\n\n\n```python\nprint(\"Three Dimensional Diffusion Coefficient\", output.xyz_diffusion_coefficient())\nprint(\"One Dimensional Diffusion Coefficient in X\", output.x_diffusion_coefficient())\nprint(\"One Dimensional Diffusion Coefficient in Y\", output.y_diffusion_coefficient())\nprint(\"One Dimensional Diffusion Coefficient in Z\", output.z_diffusion_coefficient())\n```\n\nYou will hopefully see that your MSD plot has become considerably less linear. This shows that your simulation has not run long enough and your results will be unrealiable. \n\nYou will hopefully also see a change to the value of your diffusion coefficient. \n**The length of your simulation is something that you should keep in mind for the next 5 weeks.** \n\n# Exercise 6: Calculating the Activation Energy\n\nNow we have investigated the influence of simulation length on the diffusion coefficient, we can calculate the activation energy for F diffusion by applying the Arrhenius equation. \n\nTo apply the Arrhensius equation, diffusion coefficients from a range of temperatures are required. \n\nCommon sense and chemical intuition suggest that the higher the temperature, the faster a given chemical reaction will proceed. Quantitatively, this relationship between the rate a reaction proceeds and the temperature is determined by the Arrhenius Equation. \n\nAt higher temperatures, the probability that two molecules will collide is higher. This higher collision rate results in a higher kinetic energy, which has an effect on the activation energy of the reaction. The activation energy is the amount of energy required to ensure that a reaction happens.  \n  \n\\begin{align}\nk = A * e^{(-Ea / RT)}\n\\end{align}\n  \nwhere k is the rate coefficient, A is a constant, Ea is the activation energy, R is the universal gas constant, and T is the temperature (in kelvin).\n\n# Exercise 7: Putting it All Together\n\n\nUsing what you have learned through the tutorials above, your task this week is to calculate the activation energy of F diffusion in CaF$_2$. \n\n1. You will need to **select** a temperature range and carry out simulations at different temperatures within that range. \n\n#### Questions to answer:\n\n- In what temperature range is CaF$_2$ completely solid i.e. no diffusion?\n- In what range is fluorine essentially liquid i.e. fluorine diffusion with no calcium diffusion?\n- What is the melting temperature of CaF$_2$?\n- Plot an Arrhenius plot and determine the activation energies in temperature range - You will need to rearange the equation. \n\n\nYou are encouraged to split the work up within your group and to learn how to view the simulation \"movie\" using VMD (Ask a demonstrator). VMD is a fantastic program that allows you to visualise your simulation, included below is a video showing a short snippet of an MD simulation of CaF$_2$. A single F atom has been highlighted to show that diffusion is occuring. \n\n\n```python\n%%HTML\n<div align=\"middle\">\n</div>\n```\n\nFurthermore, VMD can also be used to generate images showing the entire trajectory of the simulation, e.g.\n\n\n<center>\n    <br>\n    \n    <i>Figure 2. A figure showing all positions occupied by F during an MD simulation at 1500 K. F positions are shown in orange and Ca atoms are shown in green.</i>\n    <br>\n</center>\n  \n\nTo save you time you can use the function declared at the start of this notebook to pull out a diffusion coefficient directly from the simulation output file. <code>MSD.py</code> is a small code to allow visualisation of the MSD plot but it is not neccesary every time you want the diffusion coefficient. \n\nIt is up to you how you organise/create your directories but it is reccomended that you start a new notebook. \n\nUse the commands/functions used in this notebook to: \n1. **Generate** your input files\n2. **Run** <code>DL_POLY</code>\n3. **Extract** the diffusion coefficient of F diffusion \n\nThen write your own code to:\n\n4. **Generate** an Arrhenius plot \n5. **Calculate** the activation energies of F diffusion\n\nIf you finish early then feel free to start the week 4 exercises. \n", "meta": {"hexsha": "cb75a2e0d6e9838de4c09f26e41c14c6467d0885", "size": 24069, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Week_3/week_3.ipynb", "max_stars_repo_name": "MeganStalker/Advanced_Practical_Chemistry_Year_3", "max_stars_repo_head_hexsha": "f4dc048890d59822d1f4041c73e7dcb4aaadb5e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Week_3/week_3.ipynb", "max_issues_repo_name": "MeganStalker/Advanced_Practical_Chemistry_Year_3", "max_issues_repo_head_hexsha": "f4dc048890d59822d1f4041c73e7dcb4aaadb5e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week_3/week_3.ipynb", "max_forks_repo_name": "MeganStalker/Advanced_Practical_Chemistry_Year_3", "max_forks_repo_head_hexsha": "f4dc048890d59822d1f4041c73e7dcb4aaadb5e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-08T09:54:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-08T09:54:46.000Z", "avg_line_length": 42.8274021352, "max_line_length": 461, "alphanum_fraction": 0.6368773111, "converted": true, "num_tokens": 4263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.07921031758803371, "lm_q1q2_score": 0.03867708281434647}}
{"text": "**Notas para contenedor de docker:**\n\nComando de docker para ejecuci\u00f3n de la nota de forma local:\n\nnota: cambiar `dir_montar` por la ruta de directorio que se desea mapear a `/datos` dentro del contenedor de docker.\n\n```\ndir_montar=<ruta completa de mi m\u00e1quina a mi directorio>#aqu\u00ed colocar la ruta al directorio a montar, por ejemplo: \n#dir_montar=/Users/erick/midirectorio.\n```\n\nEjecutar:\n\n```\n$docker run --rm -v $dir_montar:/datos --name jupyterlab_prope_r_kernel_tidyverse -p 8888:8888 -d palmoreck/jupyterlab_prope_r_kernel_tidyverse:3.0.16   \n\n```\n\nIr a `localhost:8888` y escribir el password para jupyterlab: `qwerty`\n\nDetener el contenedor de docker:\n\n```\ndocker stop jupyterlab_prope_r_kernel_tidyverse\n```\n\n\nDocumentaci\u00f3n de la imagen de docker `palmoreck/jupyterlab_prope_r_kernel_tidyverse:3.0.16` en [liga](https://github.com/palmoreck/dockerfiles/tree/master/jupyterlab/prope_r_kernel_tidyverse).\n\n---\n\nPara ejecuci\u00f3n de la nota usar:\n\n[docker](https://www.docker.com/) (instalaci\u00f3n de forma **local** con [Get docker](https://docs.docker.com/install/)) y ejecutar comandos que est\u00e1n al inicio de la nota de forma **local**. \n\nO bien dar click en alguno de los botones siguientes:\n\n[](https://mybinder.org/v2/gh/palmoreck/dockerfiles-for-binder/jupyterlab_prope_r_kernel_tidyerse?urlpath=lab/tree/Propedeutico/Python/clases/3_algebra_lineal/0_definiciones_generales.ipynb) esta opci\u00f3n crea una m\u00e1quina individual en un servidor de Google, clona el repositorio y permite la ejecuci\u00f3n de los notebooks de jupyter.\n\n[](https://repl.it/languages/python3) esta opci\u00f3n no clona el repositorio, no ejecuta los notebooks de jupyter pero permite ejecuci\u00f3n de instrucciones de Python de forma colaborativa con [repl.it](https://repl.it/). Al dar click se crear\u00e1n nuevos ***repl*** debajo de sus users de ***repl.it***.\n\n\n## Lo siguiente est\u00e1 basado en el cap\u00edtulo 2 y ap\u00e9ndice del libro de texto de J. Kiusalaas \"Numerical Methods in Engineering with Python 3\" y el libro de \"A\u0301lgebra Lineal\" de S. Grossman y J. Flores.\n\n**Se sugiere haber revisado la secci\u00f3n 1.5 del libro de texto de J. Kiusalaas \"Numerical Methods in Engineering with Python 3\": uso de numpy**\n\n**Nota: los ejercicios solicitados en esta nota deben realizarlos creando notebooks de jupyterlab.**\n\n# Vectores\n\n## Vector rengl\u00f3n de $n$ componentes \n\nUn vector de $n$ componentes se define como un conjunto **ordenado** de $n$ n\u00fameros escritos de la siguiente forma: $(x_1, x_2, \\dots, x_n)$\n\n## Vector columna  de $n$ componentes \n\nUn vector columna de $n$ componentes es un conjunto **ordenado** de $n$ n\u00fameros escritos de la siguiente forma: \n$\\left( \n\\begin{array}{c}\nx_1\\\\\nx_2\\\\\n\\vdots\\\\\nx_n\n\\end{array}\n\\right)$, $x_k$ se denomina la **k-\u00e9sima** componente del vector y puede estar en alg\u00fan conjunto de n\u00fameros como $\\mathbb{R}$ o $\\mathbb{C}$. T\u00edpicamente si no se especifica el conjunto se supone $\\mathbb{R}$.\n\nLos vectores rengl\u00f3n se encuentran en el conjunto $\\mathbb{R}^{1xn}$ y los vectores columna se encuentran en el conjunto $\\mathbb{R}^{nx1}$ o simplemente $\\mathbb{R}^n$.\n\n---\n\n**Observaci\u00f3n**\n\nEn *NumPy* un *array* se considera tanto columna o rengl\u00f3n y dependiendo del uso se toma uno u otro.\n\n---\n\nSi quisi\u00e9ramos forzar a un manejo de los *NumPy array*'s como renglones o columnas podr\u00edamos utilizar lo siguiente.\n\n\n```python\nimport numpy as np\n```\n\n\n```python\nv = np.array([1,2,3,4,5])\n```\n\n\n```python\nv.reshape(1,5)\n```\n\n\n\n\n    array([[1, 2, 3, 4, 5]])\n\n\n\n\n```python\nv.reshape(1,5).shape\n```\n\n\n\n\n    (1, 5)\n\n\n\n\n```python\nv.reshape(5,1)\n```\n\n\n\n\n    array([[1],\n           [2],\n           [3],\n           [4],\n           [5]])\n\n\n\n\n```python\nv.reshape(5,1).shape\n```\n\n\n\n\n    (5, 1)\n\n\n\n# Matrices\n\nEl arreglo de coeficientes: $$A=\\begin{bmatrix} a_{11} & a_{12} & \\cdots& a_{1n} \\\\ a_{21} & a_{22} & \\cdots& a_{2n} \\\\ &&\\vdots \\\\ a_{m1} & a_{m2} & \\cdots& a_{mn} \\end{bmatrix}$$ \n\nse le nombra matriz de $mxn$. En caso que se tenga un sistema de la forma $Ax=b$ con $b$ vector de constantes conocidas, se le nombra matriz de coeficientes del sistema y al vector $b$ se le nombra lado derecho; la matriz de coeficientes aumentada con el lado derecho se le nombra matriz aumentada: $$ [A|b] = \\left [\\begin{array}{cccc|c} a_{11} & a_{12} & \\cdots& a_{1n} & b_1 \\\\ a_{21} & a_{22} & \\cdots& a_{2n} & b_2 \\\\ && \\vdots& & \\\\ a_{m1} & a_{m2} & \\cdots& a_{mn} & b_m \\end{array} \\right ]$$\n\n---\n\n**Definiciones** \n\nFormalmente un escalar es un n\u00famero real o complejo y una matriz es un arreglo rectangular de escalares y se escribe $A \\in \\mathbb{R}^{mxn}$ o $A \\in \\mathbb{C}^{mxn}$ para denotar que $A$ es un arreglo de dos dimensiones de n\u00fameros reales o de n\u00fameros complejos respectivamente y $A$ tiene dimensiones $mxn$: $m$ renglones y $n$ columnas.\n\nUna matriz se nombra cuadrada si $m=n$ y rectangular si $m \\neq n$.\n\nUna submatriz de una matriz $A$ es un arreglo que se forma al eliminar cualquier combinaci\u00f3n de renglones y columnas de $A$. Por ejemplo, $B = \\begin{bmatrix} 2 &4 \\\\ -3& 7\\end{bmatrix}$ es una submatriz de $A = \\begin{bmatrix} 2 &1& 3& 4 \\\\ 8& 6& 5& -9\\\\ -3& 8& 3& 7 \\end{bmatrix}$.\n\nEl s\u00edmbolo $A_{i*}$ es utilizado para denotar el $i$-\u00e9simo rengl\u00f3n de $A$ y $A_{*j}$ la $j$-\u00e9sima columna de A. Por ejemplo $A_{2*} = \\begin{bmatrix} 8& 6& 5& -9 \\end{bmatrix}$ y $A_{*2} = \\begin{bmatrix} 1 \\\\6\\\\8 \\end{bmatrix}$ en la definici\u00f3n anterior.\n\n---\n\n# Operaciones en el \u00e1lgebra lineal con *NumPy*\n\n## Producto escalar-vector, suma y punto entre vectores\n\n\n```python\nv1 = np.array([6,-3,4])\nv2 = np.array([4,5,0])\nscalar = -1/2\n```\n\n\n```python\nscalar*v1\n```\n\n\n\n\n    array([-3. ,  1.5, -2. ])\n\n\n\n\n```python\nv1.dot(v2)\n```\n\n\n\n\n    9\n\n\n\n\n```python\nv1+v2\n```\n\n\n\n\n    array([10,  2,  4])\n\n\n\n## Producto matriz vector *point wise*\n\n\n```python\nA = np.array([[2,5,0],\n              [3,6,6],\n              [-6,4,-1],\n              [5,4,9]])\nA\n```\n\n\n\n\n    array([[ 2,  5,  0],\n           [ 3,  6,  6],\n           [-6,  4, -1],\n           [ 5,  4,  9]])\n\n\n\n\n```python\nv = np.array([-2,1,4])\nv\n```\n\n\n\n\n    array([-2,  1,  4])\n\n\n\n\n```python\nA*v\n```\n\n\n\n\n    array([[ -4,   5,   0],\n           [ -6,   6,  24],\n           [ 12,   4,  -4],\n           [-10,   4,  36]])\n\n\n\n## Producto matriz-vector\n\n\n```python\nA = np.array([[2,5,0],\n              [3,6,6],\n              [-6,4,-1],\n              [5,4,9]])\nA\n```\n\n\n\n\n    array([[ 2,  5,  0],\n           [ 3,  6,  6],\n           [-6,  4, -1],\n           [ 5,  4,  9]])\n\n\n\n\n```python\nv = np.array([-2,1,4])\nv\n```\n\n\n\n\n    array([-2,  1,  4])\n\n\n\n\n```python\nA.dot(v)\n```\n\n\n\n\n    array([ 1, 24, 12, 30])\n\n\n\n\n```python\nA@v\n```\n\n\n\n\n    array([ 1, 24, 12, 30])\n\n\n\n\n```python\nv = np.array([7,0,-3,2])\nv\n```\n\n\n\n\n    array([ 7,  0, -3,  2])\n\n\n\n\n```python\nv@A\n```\n\n\n\n\n    array([42, 31, 21])\n\n\n\n---\n\n**Observaci\u00f3n** \n\nEn este \u00faltimo ejemplo que no fue necesario indicar que tenemos un vector rengl\u00f3n para realizar por la izquierda la multiplicaci\u00f3n: $vA$.\n\n---\n\n## Suma y producto matriz-matriz *point wise*\n\n\n```python\nA = np.array([[2,5,0],\n              [3,6,6],\n              [-6,4,-1],\n              [5,4,9]])\nA\n```\n\n\n\n\n    array([[ 2,  5,  0],\n           [ 3,  6,  6],\n           [-6,  4, -1],\n           [ 5,  4,  9]])\n\n\n\n\n```python\nB = np.array([[2,-2,3],\n              [1,-1,5],\n              [0,-2,1],\n              [0,0,-3]])\nB\n```\n\n\n\n\n    array([[ 2, -2,  3],\n           [ 1, -1,  5],\n           [ 0, -2,  1],\n           [ 0,  0, -3]])\n\n\n\n\n```python\nA+B\n```\n\n\n\n\n    array([[ 4,  3,  3],\n           [ 4,  5, 11],\n           [-6,  2,  0],\n           [ 5,  4,  6]])\n\n\n\n\n```python\nA*B\n```\n\n\n\n\n    array([[  4, -10,   0],\n           [  3,  -6,  30],\n           [  0,  -8,  -1],\n           [  0,   0, -27]])\n\n\n\n## Producto matriz-matriz\n\n\n```python\nA = np.array([[2,5,0],\n              [3,6,6],\n              [-6,4,-1],\n              [5,4,9]])\nA\n```\n\n\n\n\n    array([[ 2,  5,  0],\n           [ 3,  6,  6],\n           [-6,  4, -1],\n           [ 5,  4,  9]])\n\n\n\n\n```python\nB = np.array([[2,-2,3],\n              [1,-1,5],\n              [0,-2,1]])\nB\n```\n\n\n\n\n    array([[ 2, -2,  3],\n           [ 1, -1,  5],\n           [ 0, -2,  1]])\n\n\n\n\n```python\nA@B\n```\n\n\n\n\n    array([[  9,  -9,  31],\n           [ 12, -24,  45],\n           [ -8,  10,   1],\n           [ 14, -32,  44]])\n\n\n\nVer:\n\n* [numpy-for-matlab-users](https://www.numpy.org/devdocs/user/numpy-for-matlab-users.html)\n* [Quickstart tutorial](https://docs.scipy.org/doc/numpy/user/quickstart.html)\n\n\n## Clase `Matrix` en *SymPy*\n\n\n```python\nimport sympy\n```\n\nUsamos la clase `Matrix` para representar vectores y matrices de forma simb\u00f3lica:\n\n\n```python\nsympy.Matrix([1,2]) #vector columna de tama\u00f1o 2 x 1\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1\\\\2\\end{matrix}\\right]$\n\n\n\n\n```python\nsympy.Matrix([[1,2]]) #matriz de tama\u00f1o 1 x 2\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 2\\end{matrix}\\right]$\n\n\n\n\n```python\nsympy.Matrix([[1,2],\n             [3,4]])\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right]$\n\n\n\n\n```python\nl = [[1,2], [3,4]] \nsympy.Matrix(l)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right]$\n\n\n\n## Matrices con entradas simb\u00f3licas\n\n\n```python\na, b, c, d, e, f = sympy.symbols(\"a, b, c, d, e, f\")\n```\n\n\n```python\nM = sympy.Matrix([[a,b],\n                  [c,d]])\n```\n\n\n```python\nM\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}a & b\\\\c & d\\end{matrix}\\right]$\n\n\n\n\n```python\nv = sympy.Matrix([e, f])\n```\n\n\n```python\nv\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}e\\\\f\\end{matrix}\\right]$\n\n\n\n\n```python\nv.rows\n```\n\n\n\n\n    2\n\n\n\n\n```python\nv.cols\n```\n\n\n\n\n    1\n\n\n\nUna forma para crear vectores en la que no enlistamos a las variables.\n\n\n```python\nvalues = sympy.symbols(\"g, h\")\n```\n\n\n```python\nv = sympy.Matrix(values)\n```\n\n\n```python\nv\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}g\\\\h\\end{matrix}\\right]$\n\n\n\n## Acceder a elementos\n\n\n```python\nv1, v2, w1, w2 = sympy.symbols(\"v1, v2, w1, w2\")\n```\n\n\n```python\nv = sympy.Matrix([v1, v2])\nw = sympy.Matrix([w1, w2])\n```\n\n\n```python\nv\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}v_{1}\\\\v_{2}\\end{matrix}\\right]$\n\n\n\n\n```python\nv[0]\n```\n\n\n\n\n$\\displaystyle v_{1}$\n\n\n\n\n```python\nv[1]\n```\n\n\n\n\n$\\displaystyle v_{2}$\n\n\n\n\n```python\nM\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}a & b\\\\c & d\\end{matrix}\\right]$\n\n\n\n\n```python\nM[0]\n```\n\n\n\n\n$\\displaystyle a$\n\n\n\n\n```python\nM[1]\n```\n\n\n\n\n$\\displaystyle b$\n\n\n\nOtra forma m\u00e1s natural al \u00e1lgebra lineal.\n\n\n```python\nM[0,0]\n```\n\n\n\n\n$\\displaystyle a$\n\n\n\n\n```python\nM[0,1]\n```\n\n\n\n\n$\\displaystyle b$\n\n\n\n\n```python\nM[1,0]\n```\n\n\n\n\n$\\displaystyle c$\n\n\n\n\n```python\nM[1,1]\n```\n\n\n\n\n$\\displaystyle d$\n\n\n\nPrimer rengl\u00f3n, segunda columna de una matriz.\n\n\n```python\nM\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}a & b\\\\c & d\\end{matrix}\\right]$\n\n\n\n\n```python\nM.row(0)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}a & b\\end{matrix}\\right]$\n\n\n\n\n```python\nM.col(1)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}b\\\\d\\end{matrix}\\right]$\n\n\n\n\n```python\nM.rows\n```\n\n\n\n\n    2\n\n\n\n\n```python\nM.cols\n```\n\n\n\n\n    2\n\n\n\n## Algunas matrices comunes\n\n\n```python\nsympy.eye(3)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 0 & 0\\\\0 & 1 & 0\\\\0 & 0 & 1\\end{matrix}\\right]$\n\n\n\n\n```python\nsympy.zeros(4)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}0 & 0 & 0 & 0\\\\0 & 0 & 0 & 0\\\\0 & 0 & 0 & 0\\\\0 & 0 & 0 & 0\\end{matrix}\\right]$\n\n\n\n\n```python\nsympy.ones(5)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 1 & 1 & 1 & 1\\\\1 & 1 & 1 & 1 & 1\\\\1 & 1 & 1 & 1 & 1\\\\1 & 1 & 1 & 1 & 1\\\\1 & 1 & 1 & 1 & 1\\end{matrix}\\right]$\n\n\n\n# Operaciones en el \u00e1lgebra lineal con *SymPy*\n\n## Producto escalar-vector\n\n\n```python\nalpha = sympy.Symbol(\"alpha\")\n```\n\n\n```python\nalpha*v\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\alpha v_{1}\\\\\\alpha v_{2}\\end{matrix}\\right]$\n\n\n\n## Sumas entre vectores\n\n\n```python\nv + w\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}v_{1} + w_{1}\\\\v_{2} + w_{2}\\end{matrix}\\right]$\n\n\n\n## Producto punto\n\n\n```python\nv.dot(w)\n```\n\n\n\n\n$\\displaystyle v_{1} w_{1} + v_{2} w_{2}$\n\n\n\n## Producto Matriz-vector\n\n\n```python\nM*v\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}a v_{1} + b v_{2}\\\\c v_{1} + d v_{2}\\end{matrix}\\right]$\n\n\n\n## Producto Matriz-Matriz\n\n\n```python\nM*M\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}a^{2} + b c & a b + b d\\\\a c + c d & b c + d^{2}\\end{matrix}\\right]$\n\n\n\n## Clase [MatrixSymbol](https://docs.sympy.org/latest/modules/matrices/expressions.html)\n\n\n```python\nM = sympy.MatrixSymbol('M', 2, 2)\n```\n\n\n```python\nM\n```\n\n\n\n\n$\\displaystyle M$\n\n\n\n\n```python\nsympy.Matrix(M)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{array}{cc}M_{0, 0} & M_{0, 1}\\\\M_{1, 0} & M_{1, 1}\\end{array}\\right]$\n\n\n\n\n```python\nM.rows\n```\n\n\n\n\n$\\displaystyle 2$\n\n\n\n\n```python\nM.cols\n```\n\n\n\n\n$\\displaystyle 2$\n\n\n\n\n```python\nsympy.Matrix(M[0,:])\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{array}{cc}M_{0, 0} & M_{0, 1}\\end{array}\\right]$\n\n\n\n\n```python\nsympy.Matrix(M[1,:])\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{array}{cc}M_{1, 0} & M_{1, 1}\\end{array}\\right]$\n\n\n\n\n```python\nM*v\n```\n\n\n\n\n$\\displaystyle M \\left[\\begin{matrix}v_{1}\\\\v_{2}\\end{matrix}\\right]$\n\n\n\n\n```python\n(M*v)[0,0]\n```\n\n\n\n\n$\\displaystyle v_{1} M_{0, 0} + v_{2} M_{0, 1}$\n\n\n\n\n```python\n(M*v)[1,0]\n```\n\n\n\n\n$\\displaystyle v_{1} M_{1, 0} + v_{2} M_{1, 1}$\n\n\n\n# Para m\u00e1s sobre operaciones vectoriales, matriciales y propiedades y definiciones de matrices especiales:\n\n* **Cap\u00edtulo 2** del libro de \"A\u0301lgebra Lineal\" de S. Grossman y J. Flores hasta secci\u00f3n 2.3. De esta secci\u00f3n hasta la 2.7 se trabajan las definiciones de matriz identidad, inversa, sim\u00e9trica y triangular inferior-superior. En el cap\u00edtulo 3 se trabaja con la definici\u00f3n del determinante de una matriz y sus propiedades.\n\n* **Cap\u00edtulo 3** del libro \"Matrix Analysis and Applied Linear Algebra\"de Carl D. Meyer.\n\n# Espacios vectoriales\n\n**Lo siguiente est\u00e1 basado en el cap\u00edtulo 5 del libro \"A\u0301lgebra Lineal\" de S. Grossman y J. Flores.**\n\nComo se vio arriba, las operaciones binarias de (suma, producto por un escalar): $(+,\\cdot)$ se encuentran definidas para el conjunto $\\mathbb{R}^n$ que es el conjunto de tuplas ordenadas de tama\u00f1o $n$ y tales operaciones est\u00e1n bien definidas pues obtenemos elementos del mismo conjunto. Tambi\u00e9n, tales operaciones est\u00e1n bien definidas para el conjunto $\\mathbb{R}^{mxn}$, el cual es el conjunto de matrices de tama\u00f1o $mxn$.\n\nPara aquellos conjuntos $V$ a los que se les define una (suma, producto por un escalar), $(+,\\cdot)$, y el escalar est\u00e1 definido en un conjunto $K$ llamado campo, y cumplen con las siguientes propiedades se les llama *espacios vectoriales* y estos en general son distintos a $\\mathbb{R}^n$ o $\\mathbb{R}^{mxn}$:\n\n1) Si $x \\in V$, $y \\in V$ entonces $x+y \\in V$ (cerradura bajo la suma).\n\n2) $\\forall x,y,z \\in V$ se cumple: $(x+y)+z=x+(y+z)$ (ley asociativa de la suma de vectores).\n\n3) $\\exists 0 \\in V$ tal que para todo $x \\in V$, $x+0=0+x=x$ (el $0$ se llama vector cero).\n\n4) Si $x \\in V$, $\\exists -x \\in V$ tal que $x+(-x)=0$ ($-x$ se llama inverso aditivo de $x$ y $0$ es el elemento descrito por la propiedad 3).\n\n5) Si $x,y \\in V$, entonces $x+y=y+x$ (ley conmutativa de la suma de vectores).\n\n6) Si $x \\in V$, $\\alpha \\in K$ entonces $\\alpha \\cdot x \\in V$ (cerradura bajo la multiplicaci\u00f3n por un escalar).\n\n7) Si $x, y \\in V$, $\\alpha \\in K$ entonces $\\alpha \\cdot (x+y)=\\alpha \\cdot x + \\alpha \\cdot y$ (primera ley distributiva).\n\n8) Si $x \\in V$, $\\alpha, \\beta \\in K$ entonces $(\\alpha + \\beta)\\cdot x = \\alpha \\cdot x + \\beta \\cdot x$ (segunda ley distributiva).\n\n9) Si $x \\in V$, $\\alpha, \\beta \\in K$ entonces $\\alpha(\\beta \\cdot x) = (\\alpha \\beta)\\cdot x$ (ley asociativa de la multiplicaci\u00f3n por escalares).\n\n10) $\\forall x \\in V,$ $\\exists 1 \\in K$ tal que: $1\\cdot x = x$.\n\n## Ejemplos de espacios vectoriales\n\n* $\\mathbb{R}^n, \\mathbb{R}^{mxn}, \\mathbb{C}^n, \\mathbb{C}^{mxn}$.\n\n* $V=\\{0\\}$.\n\n* $V=\\{ (x,y) \\in \\mathbb{R}^2 : y = mx, m \\in \\mathbb{R}, x \\in \\mathbb{R}\\}$.\n\n* $V=\\{ (x,y,z) \\in \\mathbb{R}^3 : ax+by+cz=0, a \\in \\mathbb{R}, b \\in \\mathbb{R}, c\\in \\mathbb{R} \\}$.\n\n* $V = \\{ a_0 + a_1x + a_2x^2 + \\dots a_{n-1}x^{n-1} + a_nx^n : a_0, a_1, \\dots, a_n \\in \\mathbb{R}\\}$.\n\n* $V = \\mathcal{C}([0,1])$.\n\n---\n\n**Observaci\u00f3n** \n\nLos elementos de un espacio vectorial se les nombra *vectores*, por ejemplo un elemento del conjunto $V = \\mathcal{C}([0,1])$ es $f(x)=x^2$ y refiri\u00e9ndose a este elemento, rigurosamente es un *vector* (aunque sea una funci\u00f3n).\n\n---\n\nVer:\n    \n* Fin de la secci\u00f3n $5.1$ y secci\u00f3n $5.2$ del libro de A\u0301lgebra Lineal de S. Grossman y J. Flores, para tema de subespacios vectoriales. \n\n# Combinaci\u00f3n lineal, espacio generado y bases\n\nPara las siguientes definiciones se considera el espacio vectorial $V=\\mathbb{R}^n$. Un vector en este espacio es $x=\\left( \n\\begin{array}{c}\nx_1\\\\\nx_2\\\\\n\\vdots\\\\\nx_n\n\\end{array}\n\\right)$.\n\n## Combinaci\u00f3n lineal\n\nSe nombra combinaci\u00f3n lineal a la siguiente suma ponderada: $\\displaystyle \\sum_{i=1}^n a_ix_i$ con $x_1,\\dots,x_n \\in \\mathbb{R}^n$ y $a_1,\\dots,a_n \\in \\mathbb{R}$.\n\nPor ejemplo, en $\\mathbb{R}^3$ el vector: \n$\\left(\\begin{array}{c}\n-7\\\\\n7\\\\\n7\n\\end{array}\n\\right)$ es una combinaci\u00f3n lineal de:\n$\\left(\\begin{array}{c}\n-1\\\\\n2\\\\\n4\n\\end{array}\n\\right)$ y \n$\\left(\\begin{array}{c}\n5\\\\\n-3\\\\\n1\n\\end{array}\n\\right)$ pues:\n\n$$\n\\begin{array}{l}\n\\left( \\begin{array}{c}\n-7\\\\\n7\\\\\n7\n\\end{array}\n\\right) = 2\\left( \n\\begin{array}{c} \n-1\\\\\n2\\\\\n4\n\\end{array}\n\\right)\n-\\left( \n\\begin{array}{c} \n5\\\\\n-3\\\\\n1\n\\end{array}\n\\right)\n\\end{array} \n$$\n\ny otro ejemplo: \n$-2\\left(\\begin{array}{c}\n3\\\\\n0\\\\\n\\end{array}\n\\right)\n+4\\left(\\begin{array}{c}\n0\\\\\n1\\\\\n\\end{array}\n\\right)$ es una combinaci\u00f3n lineal de \n$\\left(\\begin{array}{c}\n3\\\\\n0\\\\\n\\end{array}\n\\right)$ y\n$\\left(\\begin{array}{c}\n0\\\\\n1\\\\\n\\end{array}\n\\right)$.\n\n## Conjunto generador\n\nLos vectores $x_1, x_2, \\dots,x_n$ generan a $\\mathbb{R}^n$ si todo vector en $\\mathbb{R}^n$ se puede escribir como una combinaci\u00f3n lineal de los mismos. Esto es, si $x \\in \\mathbb{R}^n$ entonces $x = \\displaystyle \\sum_{i=1}^n \\alpha_i x_i$ con $\\alpha_i \\in \\mathbb{R}$. \n\nPor ejemplo, los $n$ vectores can\u00f3nicos que tienen un $1$ en la posici\u00f3n $i$:\n\n$$e_i = \\left(\\begin{array}{c}\n0\\\\\n\\vdots\\\\\n0\\\\\n1\\\\\n0\\\\\n\\vdots\\\\\n0\n\\end{array}\n\\right) \\leftarrow \\text{posici\u00f3n i}$$\n\nson un conjunto generador del espacio $\\mathbb{R}^n$. Por ejemplo, en $\\mathbb{R}^3$:\n\n$$\n\\begin{array}{l}\n\\left( \\begin{array}{c}\n-7\\\\\n7\\\\\n7\n\\end{array}\n\\right) = -7\\left( \n\\begin{array}{c} \n1\\\\\n0\\\\\n0\n\\end{array}\n\\right)\n+7\\left( \n\\begin{array}{c} \n0\\\\\n1\\\\\n0\n\\end{array}\n\\right)\n7\\left( \n\\begin{array}{c} \n0\\\\\n0\\\\\n1\n\\end{array}\n\\right)\n\\end{array} \n$$\n\n\n### Espacio generado\n\nEs el conjunto formado por combinaciones lineales de un conjunto vectores. Por ejemplo, si nuestro conjunto de vectores es $\\{x_1,x_2\\}$ entonces el espacio generado es: $$\\text{gen}\\{x_1,x_2\\}=<x_1,x_2>=\\{\\alpha_1 x_1 + \\alpha_2 x_2 \\}.$$\n\n---\n\n**Observaci\u00f3n** \n\nEste espacio generado es un subespacio vectorial de $\\mathbb{R}^n$.\n\n---\n\n## Independencia/dependencia lineal\n\nEl conjunto $\\{x_1, x_2, \\dots, x_k\\}$ para $k \\in \\mathbb{N}$, es un conjunto con dependencia lineal (o conjunto linealmente dependiente o los vectores $x_1,x_2,\\dots, x_k$ son linealmente dependientes) si alg\u00fan vector en tal conjunto se escribe como combinaci\u00f3n lineal de los restantes. Por ejemplo, los vectores:\n\n\n$$\n\\left( \\begin{array}{c}\n-7\\\\\n7\\\\\n7\n\\end{array}\n\\right), \\left( \n\\begin{array}{c} \n-1\\\\\n2\\\\\n4\n\\end{array}\n\\right), \\left( \n\\begin{array}{c} \n5\\\\\n-3\\\\\n1\n\\end{array}\n\\right)\n$$\n\nson **linealmente dependientes** como se vio arriba.\n\nSi el conjunto $\\{x_1, x_2, \\dots, x_k\\}$ no es linealmente dependiente entonces es **linealmente independiente**. \n\nTambi\u00e9n se utiliza para la definici\u00f3n de independencia lineal que la ecuaci\u00f3n: $$\\alpha_1 x_1 + \\alpha_2 x_2 + \\dots + \\alpha_k x_k = 0$$ con inc\u00f3gnitas $\\alpha_i$'s tiene soluci\u00f3n \u00fanica dada por $\\alpha_1 = \\alpha_2 = \\dots = \\alpha_k = 0$.\n\nComo ejemplos de vectores linealmente independientes se tienen:\n\n* $e_1, e_2, \\dots, e_k$ con k un n\u00famero natural.\n\n* $\\left( \\begin{array}{c}\n1\\\\\n-2\\\\\n3\n\\end{array}\n\\right), \\left( \n\\begin{array}{c} \n2\\\\\n-2\\\\\n0\n\\end{array}\n\\right), \\left( \n\\begin{array}{c} \n0\\\\\n1\\\\\n7\n\\end{array}\n\\right)\n$\n\n---\n\n**Observaci\u00f3n** \n\nen el espacio $\\mathbb{R}^n$ s\u00f3lo se pueden tener a lo m\u00e1s $n$ vectores linealmente independientes. Entonces los vectores: \n$\\left( \\begin{array}{c}\n2\\\\\n-3\\\\\n4\n\\end{array}\n\\right), \\left( \n\\begin{array}{c} \n4\\\\\n7\\\\\n-6\n\\end{array}\n\\right), \\left( \n\\begin{array}{c} \n18\\\\\n-11\\\\\n4\n\\end{array}\n\\right),\n\\left( \n\\begin{array}{c} \n2\\\\\n-7\\\\\n3\n\\end{array}\n\\right)\n$ son linealmente dependientes en $\\mathbb{R}^3$ pues constituyen un conjunto de $4$ vectores de $3$ elementos cada uno. Y esto equivale a escribir que $Ax=0$ tiene soluci\u00f3n $x$ diferente de cero con $A \\in \\mathbb{R}^{3x4}$ formada por las columnas de los vectores anteriores.\n\n---\n\n## Base\n\nLos conjuntos de vectores en $\\mathbb{R}^n$ que son linealmente independientes y su espacio generado es $\\mathbb{R}^n$ se les nombra base. Por ejemplo:\n\n* $e_1, e_2, \\dots, e_k \\in \\mathbb{R}^k$ con $k \\in \\mathbb{N}$ son base de $\\mathbb{R}^k$  y si consideramos $e_1, e_2, \\dots, e_n \\in \\mathbb{R}^n$ entonces estos \u00faltimos son base del espacio $\\mathbb{R}^n$.\n\n* $\\left( \\begin{array}{c}\n1\\\\\n-2\\\\\n3\n\\end{array}\n\\right), \\left( \n\\begin{array}{c} \n2\\\\\n-2\\\\\n0\n\\end{array}\n\\right), \\left( \n\\begin{array}{c} \n0\\\\\n1\\\\\n7\n\\end{array}\n\\right)\n$ son base del espacio $\\mathbb{R}^3$.\n\n---\n\n**Comentarios** \n\n* El conjunto $\\{e_1, e_2, \\dots, e_n\\}$ es nombrada *base can\u00f3nica* de $\\mathbb{R}^n$.\n\n* Si un espacio vectorial tiene una base con un n\u00famero finito de elementos, entonces se le nombra espacio de **dimensi\u00f3n finita**, en otro caso es un espacio vectorial de **dimensi\u00f3n infinita**.\n\n* De las ventajas que existen al trabajar con bases es que cualquier elemento en el espacio vectorial de dimensi\u00f3n finita se puede representar como una combinaci\u00f3n lineal de los vectores en la base.\n\n* Si $V=\\{0\\}$ entonces t\u00edpicamente se considera que $V$ tiene dimensi\u00f3n cero.\n\n---\n\n# Vectores ortogonales\n\nLos vectores $x, y \\in \\mathbb{R}^n$ son ortogonales si $x^Ty=0$. El conjunto $\\{x_1,x_2,\\dots,x_k\\} \\in \\mathbb{R}^n$ es ortogonal si $x_i^Tx_j = 0$ para $i \\neq j$ y si adem\u00e1s $x_i^Tx_i = 1$ (norma igual a uno) entonces se nombra conjunto ortonormal.\n\nNorma 2 o Euclidiana de un vector: si $x \\in \\mathbb{R}^n$ entonces la norma 2 o Euclidiana de $x$, denotada por $||x||_2$ se define como: $||x||_2 = \\sqrt{x^Tx}$.\n\n## Matriz ortogonal\n\nUna matriz $A \\in \\mathbb{R}^{nxn}$ se nombra ortogonal si sus columnas son ortogonales y cada columna es ortonormal. Tal propiedad se puede escribir de forma matricial como $A^TA = I$ donde: $I$ es la matriz identidad.\n\nComo ejemplos de matrices ortogonales en $\\mathbb{R}^{nxn}$ se tienen las matrices de rotaci\u00f3n y reflexi\u00f3n.\n\n### Matriz de rotaci\u00f3n en sentido contrario a las manecillas del reloj en el plano\n\nEst\u00e1 dada por: $$R_{\\theta} = \\begin{bmatrix} cos(\\theta) & -sen(\\theta) \\\\ sen(\\theta)& cos(\\theta)\\end{bmatrix}$$\n\n---\n\n**(Tarea)Ejercicio**\n\n\nUsar esta matriz de rotaci\u00f3n para rotar un \u00e1ngulo de $\\frac{\\pi}{3}$ en sentido contrario a las manecillas del reloj al vector $\\left(\\begin{array}{c}\n-3\\\\\n4\\\\\n\\end{array}\n\\right)$.\n\n---\n\nImports:\n\n\n```python\nimport matplotlib.pyplot as plt\nimport math\n```\n\nDefinici\u00f3n de $v$:\n\n\n```python\nv = np.array([-3,4])\n```\n\nDefinici\u00f3n de matriz $R_\\theta$ con $\\theta = \\pi/3$:\n\n\n```python\ntheta = math.pi/3\nR_theta = np.array([[math.cos(theta), -math.sin(theta)],\n                    [math.sin(theta), math.cos(theta)]])\n```\n\nRealizamos la rotaci\u00f3n para obtener $v_{\\text{rot}}$:\n\n\n```python\nv_rot = R_theta@v\n```\n\n\n```python\nv_rot\n```\n\n\n\n\n    array([-4.96410162, -0.59807621])\n\n\n\nRealizamos la gr\u00e1fica:\n\n\n```python\nA = np.array([[0, 0],\n              v])\n```\n\n\n```python\nA\n```\n\n\n\n\n    array([[ 0,  0],\n           [-3,  4]])\n\n\n\n\n```python\nA2 = np.array([[0, 0],\n               v_rot])\n```\n\n\n```python\nA2\n```\n\n\n\n\n    array([[ 0.        ,  0.        ],\n           [-4.96410162, -0.59807621]])\n\n\n\n\n```python\nplt.plot(A[:,0], A[:,1], '-',\n         A2[:,0], A2[:,1],'r-',\n         )\nplt.legend(['Vector', 'Vector con rotaci\u00f3n'])\nplt.title(\"Hacemos rotaci\u00f3n de $\\pi/3$\")\nplt.show()\n```\n\n### Matriz de reflexi\u00f3n de Householder\n\nEst\u00e1 dada por: $$R_{H} = I - 2 \\frac{uu^T}{u^Tu}$$ con $u \\in \\mathbb{R}^n -\\{0\\}$ y realiza la reflexi\u00f3n respecto al conjunto de vectores ortogonales a $u$. \n\n---\n\n**(Tarea)Ejercicio**\n\n\nReflejar al vector $\\left(\\begin{array}{c}\n1\\\\\n1\\\\\n\\end{array}\n\\right)$ utilizando al vector $\\left(\\begin{array}{c}\n-\\frac{4}{3}\\\\\n\\frac{2}{3}\\\\\n\\end{array}\n\\right)$ para construir a $R_{H}$.\n\n---\n\n## Base ortogonal, ortonormal\n\nUn conjunto de vectores que forma una base de un espacio vectorial que adem\u00e1s es un conjunto ortogonal se le nombra base ortogonal. Si adicionalmente cada vector tiene norma igual a 1 entonces es una base ortonormal.\n\n# Espacio nulo, espacio nulo izquierdo, imagen de una matriz, espacio rengl\u00f3n y espacio columna\n\nEn lo siguiente se considera $A \\in \\mathbb{R}^{mxn}$.\n\n## Espacio nulo\n\n$\\mathcal{N}(A) = \\{x \\in \\mathbb{R}^n : Ax =0\\}$\n\n---\n\n**Observaci\u00f3n** \n\nEs un subespacio de $\\mathbb{R}^n$.\n\n---\n\n**La dimensi\u00f3n de $\\mathcal{N}(A)$ se le nombra nulidad.** Si $\\mathcal{N}(A)$ s\u00f3lo contiene al vector $0$, esto es: $\\mathcal{N}(A) = \\{0\\}$ entonces la nulidad de $\\mathcal{N}(A)$ es igual a 0.\n\n## Espacio nulo izquierdo\n\n$\\mathcal{N}(A^T) = \\{x \\in \\mathbb{R}^m : A^Tx =0\\}$\n\n---\n\n**Observaci\u00f3n** \n\n\nEs un subespacio de $\\mathbb{R}^m$.\n\n---\n\n## Imagen de una matriz\n\n$Im(A) = \\{y \\in \\mathbb{R}^m: y=Ax \\text{ para alguna } x \\in \\mathbb{R}^n\\}$\n\n---\n\n**Observaci\u00f3n** \n\nEs un subespacio de $\\mathbb{R}^m$.\n\n---\n\n**La dimensi\u00f3n de $Im(A)$ se le nombra $rank$**.\n\n## Espacio rengl\u00f3n y espacio columna de una matriz\n\nEl espacio rengl\u00f3n es el conjunto generado por los renglones de $A$ y el espacio columna es el conjunto generado por las columnas de $A$.\n\n---\n\n**Observaci\u00f3n** \n\nSe prueba que el espacio rengl\u00f3n y el espacio columna son iguales a la imagen de la matriz en cuesti\u00f3n y la dimensi\u00f3n de los mismos es igual al *rank*.\n\n---\n\n## Espacio nulo con *SymPy*\n\n\n```python\nM = sympy.Matrix([[1, 2, 3, 0, 0], \n                  [4, 10, 0, 0, 1]])\n```\n\n\n```python\nM\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 2 & 3 & 0 & 0\\\\4 & 10 & 0 & 0 & 1\\end{matrix}\\right]$\n\n\n\n\n```python\nsympy.pprint(M.nullspace())\n```\n\n    \u23a1\u23a1-15\u23a4  \u23a10\u23a4  \u23a1 1  \u23a4\u23a4\n    \u23a2\u23a2   \u23a5  \u23a2 \u23a5  \u23a2    \u23a5\u23a5\n    \u23a2\u23a2 6 \u23a5  \u23a20\u23a5  \u23a2-1/2\u23a5\u23a5\n    \u23a2\u23a2   \u23a5  \u23a2 \u23a5  \u23a2    \u23a5\u23a5\n    \u23a2\u23a2 1 \u23a5, \u23a20\u23a5, \u23a2 0  \u23a5\u23a5\n    \u23a2\u23a2   \u23a5  \u23a2 \u23a5  \u23a2    \u23a5\u23a5\n    \u23a2\u23a2 0 \u23a5  \u23a21\u23a5  \u23a2 0  \u23a5\u23a5\n    \u23a2\u23a2   \u23a5  \u23a2 \u23a5  \u23a2    \u23a5\u23a5\n    \u23a3\u23a3 0 \u23a6  \u23a30\u23a6  \u23a3 1  \u23a6\u23a6\n\n\n## Espacio columna con *SymPy*\n\n\n```python\nM = sympy.Matrix([[1, 1, 2], \n                  [2 ,1 , 3], \n                  [3 , 1, 4]])\n```\n\n\n```python\nsympy.pprint(M.columnspace())\n```\n\n    \u23a1\u23a11\u23a4  \u23a11\u23a4\u23a4\n    \u23a2\u23a2 \u23a5  \u23a2 \u23a5\u23a5\n    \u23a2\u23a22\u23a5, \u23a21\u23a5\u23a5\n    \u23a2\u23a2 \u23a5  \u23a2 \u23a5\u23a5\n    \u23a3\u23a33\u23a6  \u23a31\u23a6\u23a6\n\n\n# Transformaciones lineales\n\nSean $V$ y $W$ espacios vectoriales con campo en $\\mathbb{R}$ entonces una transformaci\u00f3n lineal $T$ de $V$ en $W$, denotada por $T: V \\rightarrow W$, es una funci\u00f3n que asigna a cada vector $v \\in V$ un vector \u00fanico $T(v) \\in W$ y que satisface para cada $u,v \\in V$ y cada escalar $\\alpha \\in \\mathbb{R}$:\n\n\n\n$$\nT(u+v)=T(u)+T(v)\n$$\n\n\n$$\nT(\\alpha v)=\\alpha T(v)\n$$\n\n## Ejemplos\n\n\n\n* $T\\left(\\begin{array}{c}\nx\\\\\ny\\\\\n\\end{array}\n\\right) = \\left(\\begin{array}{c}\nx+y\\\\\nx-y\\\\\n3y\n\\end{array}\n\\right)$\n\n* $T\\left(\\begin{array}{c}\nx\\\\\ny\\\\\n\\end{array}\n\\right)= R_{\\theta}\\left(\\begin{array}{c}\nx\\\\\ny\\\\\n\\end{array}\n\\right)\n$ con $R_{\\theta}$ matriz de rotaci\u00f3n se conoce como transformaci\u00f3n de rotaci\u00f3n.\n\n* $T\\left(\\begin{array}{c}\nx\\\\\ny\\\\\n\\end{array}\n\\right)= \\left(\\begin{array}{c}\n-x\\\\\ny\\\\\n\\end{array}\n\\right)\n$ la cual es una transformaci\u00f3n de reflexi\u00f3n respecto al eje vertical en el plano.\n\n## N\u00facleo e imagen de las transformaciones lineales\n\nSe consideran $V, W$ espacios vectoriales y $T: V \\rightarrow W$ una transformaci\u00f3n lineal. \n\n### N\u00facleo o kernel\n\nSe denota por $nu(T)$ y est\u00e1 dado por $nu(T) = \\{v \\in V : T(v) = 0\\}$.\n\n---\n\n**Observaci\u00f3n**\n\nEste conjunto no es vac\u00edo pues $T(0) = 0$ por lo que $0 \\in nu(T)$. Adem\u00e1s es un subespacio vectorial de $V$ y su dimensi\u00f3n se nombra *nulidad* de $T$.\n\n---\n\n### Imagen\n\nSe denota por $im(T)$ y est\u00e1 dado por $im(T) = \\{w \\in W : w = T(v) \\text{ para alguna } v \\in V\\}$.\n\n---\n\n**Observaci\u00f3n**\n\nEs un subespacio vectorial de $W$ y su dimensi\u00f3n se nombra *rank* de T.\n\n---\n\n### Representaci\u00f3n matricial de una transformaci\u00f3n lineal\n\nSea $T: \\mathbb{R}^n \\rightarrow \\mathbb{R}^m$ una transformaci\u00f3n lineal. Existe entonces una matriz \u00fanica de $mxn$, $A$ tal que: $T(x) = Ax \\quad \\forall x \\in \\mathbb{R}^n$.\n\n---\n\n**Observaci\u00f3n** \n\nLa matriz $A$ del resultado depende de las bases elegidas en $\\mathbb{R}^n, \\mathbb{R}^m$.\n\n---\n\n**(Tarea)Ejercicio**\n\nPara reforzar esta serie de definiciones deben elegir dos ejercicios por cada definici\u00f3n anterior del libro \"A\u0301lgebra Lineal\" de S. Grossman y J. Flores, cap\u00edtulos 5 y 7 y utilizar *NumPy* y *SymPy* para resolver tales ejercicios.\n\n---\n\n## Referencias\n\n\n* [SymPy](https://www.sympy.org/en/index.html) y [Numerical Python by Robert Johansson, Apress](https://www.apress.com/gp/book/9781484242452)\n", "meta": {"hexsha": "d3400593b0ece9dd530094ca7ec751c9400127a3", "size": 84140, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Python/clases/3_algebra_lineal/0_definiciones_generales.ipynb", "max_stars_repo_name": "CarlosJChV/Propedeutico", "max_stars_repo_head_hexsha": "d903192ffa64a7576faace68c2256e69bc11087c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python/clases/3_algebra_lineal/0_definiciones_generales.ipynb", "max_issues_repo_name": "CarlosJChV/Propedeutico", "max_issues_repo_head_hexsha": "d903192ffa64a7576faace68c2256e69bc11087c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/clases/3_algebra_lineal/0_definiciones_generales.ipynb", "max_forks_repo_name": "CarlosJChV/Propedeutico", "max_forks_repo_head_hexsha": "d903192ffa64a7576faace68c2256e69bc11087c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9131506006, "max_line_length": 14560, "alphanum_fraction": 0.5458521512, "converted": true, "num_tokens": 10762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1732882059293266, "lm_q2_score": 0.22270014398423357, "lm_q1q2_score": 0.03859130841123055}}
{"text": "<!-- Slides for FYS-KJM4480 -->\n# Slides from FYS4411/9411 Definitions of the many-body problem\n**Spring 2015**\n\n### Quantum Many-particle Methods\n* Large-scale diagonalization (Iterative methods, Lanczo's method, dimensionalities $10^{10}$ states)\n\n* Coupled cluster theory, favoured method in quantum chemistry, molecular and atomic physics. Applications to ab initio calculations in nuclear physics as well for large nuclei.\n\n* Perturbative many-body methods \n\n* Density functional theories/Mean-field theory and Hartree-Fock theory (covered partly also in FYS-MENA4111)\n\n* Monte-Carlo methods (Only in FYS4411, Computational quantum mechanics)\n\n* Green's function theories (depending on interest)\n\n* and other. The physics of the system hints at which many-body methods to use.\n\n\n\n### Selected Texts and Many-body theory\n* Blaizot and Ripka, *Quantum Theory of Finite systems*, MIT press 1986\n\n* Negele and Orland, *Quantum Many-Particle Systems*, Addison-Wesley, 1987.\n\n* Fetter and Walecka, *Quantum Theory of Many-Particle Systems*, McGraw-Hill, 1971.\n\n* Helgaker, Jorgensen and Olsen, *Molecular Electronic Structure Theory*, Wiley, 2001.\n\n* Mattuck, *Guide to Feynman Diagrams in the Many-Body Problem*, Dover, 1971.\n\n* Dickhoff and Van Neck, *Many-Body Theory Exposed*, World Scientific, 2006.\n\n\n\n\n<!-- !split  -->\n### Definitions\nAn operator is defined as $\\hat{O}$ throughout. Unless otherwise specified the number of particles is\nalways $N$ and $d$ is the dimension of the system.  In nuclear physics\nwe normally define the total number of particles to be $A=N+Z$, where\n$N$ is total number of neutrons and $Z$ the total number of\nprotons. In case of other baryons such isobars $\\Delta$ or various\nhyperons such as $\\Lambda$ or $\\Sigma$, one needs to add their\ndefinitions.  Hereafter, $N$ is reserved for the total number of\nparticles, unless otherwise specificied.\n\n\n\n### Definitions\nThe quantum numbers of a single-particle state in coordinate space are\ndefined by the variable\n\n$$\nx=({\\bf r},\\sigma),\n$$\n\nwhere\n\n$$\n{\\bf r}\\in {\\mathbb{R}}^{d},\n$$\n\nwith $d=1,2,3$ represents the spatial coordinates and $\\sigma$ is the eigenspin of the particle. For fermions with eigenspin $1/2$ this means that\n\n$$\nx\\in {\\mathbb{R}}^{d}\\oplus (\\frac{1}{2}),\n$$\n\nand the integral $\\int dx = \\sum_{\\sigma}\\int d^dr = \\sum_{\\sigma}\\int d{\\bf r}$,\nand\n\n$$\n\\int d^Nx= \\int dx_1\\int dx_2\\dots\\int dx_N.\n$$\n\n### Definitions\nThe quantum mechanical wave function of a given state with quantum numbers $\\lambda$ (encompassing all quantum numbers needed to specify the system), ignoring time, is\n\n$$\n\\Psi_{\\lambda}=\\Psi_{\\lambda}(x_1,x_2,\\dots,x_N),\n$$\n\nwith $x_i=({\\bf r}_i,\\sigma_i)$ and the projection of $\\sigma_i$ takes the values\n$\\{-1/2,+1/2\\}$ for particles with spin $1/2$. \nWe will hereafter always refer to $\\Psi_{\\lambda}$ as the exact wave function, and if the ground state is not degenerate we label it as\n\n$$\n\\Psi_0=\\Psi_0(x_1,x_2,\\dots,x_N).\n$$\n\n### Definitions\nSince the solution $\\Psi_{\\lambda}$ seldomly can be found in closed form, approximations are sought. Here we define an approximative wave function or an ansatz to the exact wave function as\n\n$$\n\\Phi_{\\lambda}=\\Phi_{\\lambda}(x_1,x_2,\\dots,x_N),\n$$\n\nwith\n\n$$\n\\Phi_0=\\Phi_0(x_1,x_2,\\dots,x_N),\n$$\n\nbeing the ansatz to the ground state.\n\n\n\n\n### Definitions\nThe wave function $\\Psi_{\\lambda}$ is sought in the Hilbert space of either symmetric or anti-symmetric $N$-body functions, namely\n\n$$\n\\Psi_{\\lambda}\\in {\\cal H}_N:= {\\cal H}_1\\oplus{\\cal H}_1\\oplus\\dots\\oplus{\\cal H}_1,\n$$\n\nwhere the single-particle Hilbert space $\\hat{H}_1$ is the space of square integrable functions over\n$\\in {\\mathbb{R}}^{d}\\oplus (\\sigma)$\nresulting in\n\n$$\n{\\cal H}_1:= L^2(\\mathbb{R}^{d}\\oplus (\\sigma)).\n$$\n\n### Definitions\nOur Hamiltonian is invariant under the permutation (interchange) of two particles.\nSince we deal with fermions however, the total wave function is antisymmetric.\nLet $\\hat{P}$ be an operator which interchanges two particles.\nDue to the symmetries we have ascribed to our Hamiltonian, this operator commutes with the total Hamiltonian,\n\n$$\n[\\hat{H},\\hat{P}] = 0,\n$$\n\nmeaning that $\\Psi_{\\lambda}(x_1, x_2, \\dots , x_N)$ is an eigenfunction of \n$\\hat{P}$ as well, that is\n\n$$\n\\hat{P}_{ij}\\Psi_{\\lambda}(x_1, x_2, \\dots,x_i,\\dots,x_j,\\dots,x_N)=\n\\beta\\Psi_{\\lambda}(x_1, x_2, \\dots,x_j,\\dots,x_i,\\dots,x_N),\n$$\n\nwhere $\\beta$ is the eigenvalue of $\\hat{P}$. We have introduced the suffix $ij$ in order to indicate that we permute particles $i$ and $j$.\nThe Pauli principle tells us that the total wave function for a system of fermions\nhas to be antisymmetric, resulting in the eigenvalue $\\beta = -1$.\n\n\n\n\n### Definitions and notations\nThe Schrodinger equation reads\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:basicSE1\"></div>\n\n$$\n\\begin{equation}\n\\hat{H}(x_1, x_2, \\dots , x_N) \\Psi_{\\lambda}(x_1, x_2, \\dots , x_N) = \nE_\\lambda  \\Psi_\\lambda(x_1, x_2, \\dots , x_N), \\label{eq:basicSE1} \\tag{1}\n\\end{equation}\n$$\n\nwhere the vector $x_i$ represents the coordinates (spatial and spin) of particle $i$, $\\lambda$ stands  for all the quantum\nnumbers needed to classify a given $N$-particle state and $\\Psi_{\\lambda}$ is the pertaining eigenfunction.  Throughout this course,\n$\\Psi$ refers to the exact eigenfunction, unless otherwise stated.\n\n\n\n### Definitions and notations\nWe write the Hamilton operator, or Hamiltonian,  in a generic way\n\n$$\n\\hat{H} = \\hat{T} + \\hat{V}\n$$\n\nwhere $\\hat{T}$  represents the kinetic energy of the system\n\n$$\n\\hat{T} = \\sum_{i=1}^N \\frac{\\mathbf{p}_i^2}{2m_i} = \\sum_{i=1}^N \\left( -\\frac{\\hbar^2}{2m_i} \\mathbf{\\nabla_i}^2 \\right) =\n\t\t\\sum_{i=1}^N t(x_i)\n$$\n\nwhile the operator $\\hat{V}$ for the potential energy is given by\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:firstv\"></div>\n\n$$\n\\begin{equation}\n\t\\hat{V} = \\sum_{i=1}^N \\hat{u}_{\\mathrm{ext}}(x_i) + \\sum_{ji=1}^N v(x_i,x_j)+\\sum_{ijk=1}^Nv(x_i,x_j,x_k)+\\dots\n\\label{eq:firstv} \\tag{2}\n\\end{equation}\n$$\n\nHereafter we use natural units, viz. $\\hbar=c=e=1$, with $e$ the elementary charge and $c$ the speed of light. This means that momenta and masses\nhave dimension energy.\n\n\n\n\n### Definitions and notations\nIf one does quantum chemistry, after having introduced the  Born-Oppenheimer approximation which effectively freezes out the nucleonic degrees of freedom, the Hamiltonian for $N=n_e$ electrons takes the following form\n\n$$\n\\hat{H} = \\sum_{i=1}^{n_e} t(x_i) - \\sum_{i=1}^{n_e} k\\frac{Z}{r_i} + \\sum_{i < j}^{n_e} \\frac{k}{r_{ij}},\n$$\n\nwith $k=1.44$ eVnm\n\n\n\n\n### Definitions and notations\nWe can rewrite this as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"H1H2\"></div>\n\n$$\n\\begin{equation}\n    \\hat{H} = \\hat{H}_0 + \\hat{H}_I \n    = \\sum_{i=1}^{n_e}\\hat{h}_0(x_i) + \\sum_{i < j}^{n_e}\\frac{1}{r_{ij}},\n\\label{H1H2} \\tag{3}\n\\end{equation}\n$$\n\nwhere  we have defined\n\n$$\nr_{ij}=| {\\bf r}_i-{\\bf r}_j|,\n$$\n\nand\n\n<!-- Equation labels as ordinary links -->\n<div id=\"hi\"></div>\n\n$$\n\\begin{equation}\n  \\hat{h}_0(x_i) =  \\hat{t}(x_i) - \\frac{Z}{x_i}.\n\\label{hi} \\tag{4}\n\\end{equation}\n$$\n\nThe first term of Eq. [(3)](#H1H2), $H_0$, is the sum of the $N$\n*one-body* Hamiltonians $\\hat{h}_0$. Each individual\nHamiltonian $\\hat{h}_0$ contains the kinetic energy operator of an\nelectron and its potential energy due to the attraction of the\nnucleus. The second term, $H_I$, is the sum of the $n_e(n_e-1)/2$\ntwo-body interactions between each pair of electrons. Note that the double sum carries a restriction $i < j$.\n\n\n\n\n### Definitions and notations\nThe potential energy term due to the attraction of the nucleus defines the onebody field $u_i=u_{\\mathrm{ext}}(x_i)$ of Eq. [(2)](#eq:firstv).\nWe have moved this term into the $\\hat{H}_0$ part of the Hamiltonian, instead of keeping  it in $\\hat{V}$ as in  Eq. [(2)](#eq:firstv).\nThe reason is that we will hereafter treat $\\hat{H}_0$ as our non-interacting  Hamiltonian. For a many-body wavefunction $\\Phi_{\\lambda}$ defined by an  \nappropriate single-particle basis, we may solve exactly the non-interacting eigenvalue problem\n\n$$\n\\hat{H}_0\\Phi_{\\lambda}= w_{\\lambda}\\Phi_{\\lambda},\n$$\n\nwith $w_{\\lambda}$ being the non-interacting energy. This energy is defined by the sum over single-particle energies to be defined below.\nFor atoms the single-particle energies could be the hydrogen-like single-particle energies corrected for the charge $Z$. For nuclei and quantum\ndots, these energies could be given by the harmonic oscillator in three and two dimensions, respectively.\n\n\n\n### Definitions and notations\nWe will assume that the interacting part of the Hamiltonian\ncan be approximated by a two-body interaction.\nThis means that our Hamiltonian is written as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"Hnuclei\"></div>\n\n$$\n\\begin{equation}\n    \\hat{H} = \\hat{H}_0 + \\hat{H}_I \n    = \\sum_{i=1}^N \\hat{h}_0(x_i) + \\sum_{i < j}^N V(r_{ij}),\n\\label{Hnuclei} \\tag{5}\n\\end{equation}\n$$\n\nwith\n\n<!-- Equation labels as ordinary links -->\n<div id=\"hinuclei\"></div>\n\n$$\n\\begin{equation}\n  H_0=\\sum_{i=1}^N \\hat{h}_0(x_i) =  \\sum_{i=1}^N\\left(\\hat{t}(x_i) + \\hat{u}_{\\mathrm{ext}}(x_i)\\right).\n\\label{hinuclei} \\tag{6}\n\\end{equation}\n$$\n\nThe onebody part $u_{\\mathrm{ext}}(x_i)$ is normally approximated by a harmonic oscillator potential or the Coulomb interaction an electron feels from the nucleus. However, other potentials are fully possible, such as \none derived from the self-consistent solution of the Hartree-Fock equations.\n\n\n\n\n### Definitions and notations\nOur Hamiltonian is invariant under the permutation (interchange) of two particles. % (exercise here, prove it)\nSince we deal with fermions however, the total wave function is antisymmetric.\nLet $\\hat{P}$ be an operator which interchanges two particles.\nDue to the symmetries we have ascribed to our Hamiltonian, this operator commutes with the total Hamiltonian,\n\n$$\n[\\hat{H},\\hat{P}] = 0,\n$$\n\nmeaning that $\\Psi_{\\lambda}(x_1, x_2, \\dots , x_N)$ is an eigenfunction of \n$\\hat{P}$ as well, that is\n\n$$\n\\hat{P}_{ij}\\Psi_{\\lambda}(x_1, x_2, \\dots,x_i,\\dots,x_j,\\dots,x_N)=\n\\beta\\Psi_{\\lambda}(x_1, x_2, \\dots,x_i,\\dots,x_j,\\dots,x_N),\n$$\n\nwhere $\\beta$ is the eigenvalue of $\\hat{P}$. We have introduced the suffix $ij$ in order to indicate that we permute particles $i$ and $j$.\nThe Pauli principle tells us that the total wave function for a system of fermions\nhas to be antisymmetric, resulting in the eigenvalue $\\beta = -1$.\n\n\n\n### Definitions and notations\nIn our case we assume that  we can approximate the exact eigenfunction with a Slater determinant\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:HartreeFockDet\"></div>\n\n$$\n\\begin{equation}\n   \\Phi(x_1, x_2,\\dots ,x_N,\\alpha,\\beta,\\dots, \\sigma)=\\frac{1}{\\sqrt{N!}}\n\\left| \\begin{array}{ccccc} \\psi_{\\alpha}(x_1)& \\psi_{\\alpha}(x_2)& \\dots & \\dots & \\psi_{\\alpha}(x_N)\\\\\n                            \\psi_{\\beta}(x_1)&\\psi_{\\beta}(x_2)& \\dots & \\dots & \\psi_{\\beta}(x_N)\\\\  \n                            \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n                            \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n                     \\psi_{\\sigma}(x_1)&\\psi_{\\sigma}(x_2)& \\dots & \\dots & \\psi_{\\sigma}(x_N)\\end{array} \\right|, \\label{eq:HartreeFockDet} \\tag{7}\n\\end{equation}\n$$\n\nwhere  $x_i$  stand for the coordinates and spin values of a particle $i$ and $\\alpha,\\beta,\\dots, \\gamma$ \nare quantum numbers needed to describe remaining quantum numbers.\n\n\n\n### Definitions and notations\nThe single-particle function $\\psi_{\\alpha}(x_i)$  are eigenfunctions of the onebody\nHamiltonian $h_i$, that is\n\n$$\n\\hat{h}_0(x_i)=\\hat{t}(x_i) + \\hat{u}_{\\mathrm{ext}}(x_i),\n$$\n\nwith eigenvalues\n\n$$\n\\hat{h}_0(x_i) \\psi_{\\alpha}(x_i)=\\left(\\hat{t}(x_i) + \\hat{u}_{\\mathrm{ext}}(x_i)\\right)\\psi_{\\alpha}(x_i)=\\varepsilon_{\\alpha}\\psi_{\\alpha}(x_i).\n$$\n\nThe energies $\\varepsilon_{\\alpha}$ are the so-called non-interacting single-particle energies, or unperturbed energies. \nThe total energy is in this case the sum over all  single-particle energies, if no two-body or more complicated\nmany-body interactions are present.\n\n\n\n### Definitions and notations\nLet us denote the ground state energy by $E_0$. According to the\nvariational principle we have\n\n$$\nE_0 \\le E[\\Phi] = \\int \\Phi^*\\hat{H}\\Phi d\\mathbf{\\tau}\n$$\n\nwhere $\\Phi$ is a trial function which we assume to be normalized\n\n$$\n\\int \\Phi^*\\Phi d\\mathbf{\\tau} = 1,\n$$\n\nwhere we have used the shorthand $d\\mathbf{\\tau}=d\\mathbf{r}_1d\\mathbf{r}_2\\dots d\\mathbf{r}_N$.\n\n\n\n### Definitions and notations\nIn the Hartree-Fock method the trial function is the Slater\ndeterminant of Eq. [(7)](#eq:HartreeFockDet) which can be rewritten as\n\n$$\n\\Phi(x_1,x_2,\\dots,x_N,\\alpha,\\beta,\\dots,\\nu) = \\frac{1}{\\sqrt{N!}}\\sum_{P} (-)^P\\hat{P}\\psi_{\\alpha}(x_1)\n    \\psi_{\\beta}(x_2)\\dots\\psi_{\\nu}(x_N)=\\sqrt{N!}\\hat{A}\\Phi_H,\n$$\n\nwhere we have introduced the antisymmetrization operator $\\hat{A}$ defined by the \nsummation over all possible permutations of two particles.\n\n\n\n### Definitions and notations\nIt is defined as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"antiSymmetryOperator\"></div>\n\n$$\n\\begin{equation}\n  \\hat{A} = \\frac{1}{N!}\\sum_{p} (-)^p\\hat{P},\n\\label{antiSymmetryOperator} \\tag{8}\n\\end{equation}\n$$\n\nwith $p$ standing for the number of permutations. We have introduced for later use the so-called\nHartree-function, defined by the simple product of all possible single-particle functions\n\n$$\n\\Phi_H(x_1,x_2,\\dots,x_N,\\alpha,\\beta,\\dots,\\nu) =\n  \\psi_{\\alpha}(x_1)\n    \\psi_{\\beta}(x_2)\\dots\\psi_{\\nu}(x_N).\n$$\n\n### Definitions and notations\nBoth $\\hat{H}_0$ and $\\hat{H}_I$ are invariant under all possible permutations of any two particles\nand hence commute with $\\hat{A}$\n\n<!-- Equation labels as ordinary links -->\n<div id=\"commutionAntiSym\"></div>\n\n$$\n\\begin{equation}\n  [H_0,\\hat{A}] = [H_I,\\hat{A}] = 0. \\label{commutionAntiSym} \\tag{9}\n\\end{equation}\n$$\n\nFurthermore, $\\hat{A}$ satisfies\n\n<!-- Equation labels as ordinary links -->\n<div id=\"AntiSymSquared\"></div>\n\n$$\n\\begin{equation}\n  \\hat{A}^2 = \\hat{A},  \\label{AntiSymSquared} \\tag{10}\n\\end{equation}\n$$\n\nsince every permutation of the Slater\ndeterminant reproduces it.\n\n\n\n### Definitions and notations\nThe expectation value of $\\hat{H}_0$\n\n$$\n\\int \\Phi^*\\hat{H}_0\\Phi d\\mathbf{\\tau} \n  = N! \\int \\Phi_H^*\\hat{A}\\hat{H}_0\\hat{A}\\Phi_H d\\mathbf{\\tau}\n$$\n\nis readily reduced to\n\n$$\n\\int \\Phi^*\\hat{H}_0\\Phi d\\mathbf{\\tau} \n  = N! \\int \\Phi_H^*\\hat{H}_0\\hat{A}\\Phi_H d\\mathbf{\\tau},\n$$\n\nwhere we have used Eqs. [(9)](#commutionAntiSym) and\n[(10)](#AntiSymSquared). The next step is to replace the antisymmetrization\noperator by its definition and to\nreplace $\\hat{H}_0$ with the sum of one-body operators\n\n$$\n\\int \\Phi^*\\hat{H}_0\\Phi  d\\mathbf{\\tau}\n  = \\sum_{i=1}^N \\sum_{p} (-)^p\\int \n  \\Phi_H^*\\hat{h}_0\\hat{P}\\Phi_H d\\mathbf{\\tau}.\n$$\n\n### Definitions and notations\nThe integral vanishes if two or more particles are permuted in only one\nof the Hartree-functions $\\Phi_H$ because the individual single-particle wave functions are\northogonal. We obtain then\n\n$$\n\\int \\Phi^*\\hat{H}_0\\Phi  d\\mathbf{\\tau}= \\sum_{i=1}^N \\int \\Phi_H^*\\hat{h}_0\\Phi_H  d\\mathbf{\\tau}.\n$$\n\nOrthogonality of the single-particle functions allows us to further simplify the integral, and we\narrive at the following expression for the expectation values of the\nsum of one-body Hamiltonians\n\n<!-- Equation labels as ordinary links -->\n<div id=\"H1Expectation\"></div>\n\n$$\n\\begin{equation}\n  \\int \\Phi^*\\hat{H}_0\\Phi  d\\mathbf{\\tau}\n  = \\sum_{\\mu=1}^N \\int \\psi_{\\mu}^*(\\mathbf{r})\\hat{h}_0\\psi_{\\mu}(\\mathbf{r})\n  d\\mathbf{r}.\n  \\label{H1Expectation} \\tag{11}\n\\end{equation}\n$$\n\n### Definitions and notations\nWe introduce the following shorthand for the above integral\n\n$$\n\\langle \\mu | \\hat{h}_0 | \\mu \\rangle = \\int \\psi_{\\mu}^*(\\mathbf{r})\\hat{h}_0\\psi_{\\mu}(\\mathbf{r}),\n$$\n\nand rewrite Eq. [(11)](#H1Expectation) as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"H1Expectation1\"></div>\n\n$$\n\\begin{equation}\n  \\int \\Phi^*\\hat{H}_0\\Phi  d\\mathbf{\\tau}\n  = \\sum_{\\mu=1}^N \\langle \\mu | \\hat{h}_0 | \\mu \\rangle.\n  \\label{H1Expectation1} \\tag{12}\n\\end{equation}\n$$\n\n### Definitions and notations\nThe expectation value of the two-body part of the Hamiltonian is obtained in a\nsimilar manner. We have\n\n$$\n\\int \\Phi^*\\hat{H}_I\\Phi d\\mathbf{\\tau} \n  = N! \\int \\Phi_H^*\\hat{A}\\hat{H}_I\\hat{A}\\Phi_H d\\mathbf{\\tau},\n$$\n\nwhich reduces to\n\n$$\n\\int \\Phi^*\\hat{H}_I\\Phi d\\mathbf{\\tau} \n  = \\sum_{i\\le j=1}^N \\sum_{p} (-)^p\\int \n  \\Phi_H^*V(r_{ij})\\hat{P}\\Phi_H d\\mathbf{\\tau},\n$$\n\nby following the same arguments as for the one-body\nHamiltonian.\n\n\n\n### Definitions and notations\nBecause of the dependence on the inter-particle distance $r_{ij}$,  permutations of\nany two particles no longer vanish, and we get\n\n$$\n\\int \\Phi^*\\hat{H}_I\\Phi d\\mathbf{\\tau} \n  = \\sum_{i < j=1}^N \\int  \n  \\Phi_H^*V(r_{ij})(1-P_{ij})\\Phi_H d\\mathbf{\\tau}.\n$$\n\nwhere $P_{ij}$ is the permutation operator that interchanges\nparticle $i$ and particle $j$. Again we use the assumption that the single-particle wave functions\nare orthogonal.\n\n\n\n\n### Definitions and notations\nWe obtain\n\n<!-- Equation labels as ordinary links -->\n<div id=\"H2Expectation\"></div>\n\n$$\n\\begin{equation}\n\\begin{split}\n  \\int \\Phi^*\\hat{H}_I\\Phi d\\mathbf{\\tau} \n  = \\frac{1}{2}\\sum_{\\mu=1}^N\\sum_{\\nu=1}^N\n    &\\left[ \\int \\psi_{\\mu}^*(x_i)\\psi_{\\nu}^*(x_j)V(r_{ij})\\psi_{\\mu}(x_i)\\psi_{\\nu}(x_j)\n    dx_ix_j \\right.\\\\\n  &\\left.\n  - \\int \\psi_{\\mu}^*(x_i)\\psi_{\\nu}^*(x_j)\n  V(r_{ij})\\psi_{\\nu}(x_i)\\psi_{\\mu}(x_j)\n  dx_ix_j\n  \\right]. \\label{H2Expectation} \\tag{13}\n\\end{split}\n\\end{equation}\n$$\n\nThe first term is the so-called direct term. It is frequently also called the  Hartree term, \nwhile the second is due to the Pauli principle and is called\nthe exchange term or just the Fock term.\nThe factor  $1/2$ is introduced because we now run over\nall pairs twice.\n\n\n\n### Definitions and notations\nThe last equation allows us to  introduce some further definitions.  \nThe single-particle wave functions $\\psi_{\\mu}(x)$, defined by the quantum numbers $\\mu$ and $x$\nare defined as the overlap\n\n$$\n\\psi_{\\alpha}(x)  = \\langle x | \\alpha \\rangle .\n$$\n\n### Definitions and notations\nWe introduce the following shorthands for the above two integrals\n\n$$\n\\langle \\mu\\nu|\\hat{v}|\\mu\\nu\\rangle =  \\int \\psi_{\\mu}^*(x_i)\\psi_{\\nu}^*(x_j)V(r_{ij})\\psi_{\\mu}(x_i)\\psi_{\\nu}(x_j)\n    dx_ix_j,\n$$\n\nand\n\n$$\n\\langle \\mu\\nu|\\hat{v}|\\nu\\mu\\rangle = \\int \\psi_{\\mu}^*(x_i)\\psi_{\\nu}^*(x_j)\n  V(r_{ij})\\psi_{\\nu}(x_i)\\psi_{\\mu}(x_j)\n  dx_ix_j.\n$$\n\n### Definitions and notations\nThe direct and exchange matrix elements can be  brought together if we define the antisymmetrized matrix element\n\n$$\n\\langle \\mu\\nu|\\hat{v}|\\mu\\nu\\rangle_{\\mathrm{AS}}= \\langle \\mu\\nu|\\hat{v}|\\mu\\nu\\rangle-\\langle \\mu\\nu|\\hat{v}|\\nu\\mu\\rangle,\n$$\n\nor for a general matrix element\n\n$$\n\\langle \\mu\\nu|\\hat{v}|\\sigma\\tau\\rangle_{\\mathrm{AS}}= \\langle \\mu\\nu|\\hat{v}|\\sigma\\tau\\rangle-\\langle \\mu\\nu|\\hat{v}|\\tau\\sigma\\rangle.\n$$\n\nIt has the symmetry property\n\n$$\n\\langle \\mu\\nu|\\hat{v}|\\sigma\\tau\\rangle_{\\mathrm{AS}}= -\\langle \\mu\\nu|\\hat{v}|\\tau\\sigma\\rangle_{\\mathrm{AS}}=-\\langle \\nu\\mu|\\hat{v}|\\sigma\\tau\\rangle_{\\mathrm{AS}}.\n$$\n\n### Definitions and notations\nThe antisymmetric matrix element is also hermitian, implying\n\n$$\n\\langle \\mu\\nu|\\hat{v}|\\sigma\\tau\\rangle_{\\mathrm{AS}}= \\langle \\sigma\\tau|\\hat{v}|\\mu\\nu\\rangle_{\\mathrm{AS}}.\n$$\n\nWith these notations we rewrite Eq. [(13)](#H2Expectation) as\n\n<!-- Equation labels as ordinary links -->\n<div id=\"H2Expectation2\"></div>\n\n$$\n\\begin{equation}\n  \\int \\Phi^*\\hat{H}_I\\Phi d\\mathbf{\\tau} \n  = \\frac{1}{2}\\sum_{\\mu=1}^N\\sum_{\\nu=1}^N \\langle \\mu\\nu|\\hat{v}|\\mu\\nu\\rangle_{\\mathrm{AS}}.\n\\label{H2Expectation2} \\tag{14}\n\\end{equation}\n$$\n\n### Definitions and notations\nCombining Eqs. [(12)](#H1Expectation1) and\n[(14)](#H2Expectation2) we obtain the energy functional\n\n<!-- Equation labels as ordinary links -->\n<div id=\"FunctionalEPhi\"></div>\n\n$$\n\\begin{equation}\n  E[\\Phi] \n  = \\sum_{\\mu=1}^N \\langle \\mu | \\hat{h}_0 | \\mu \\rangle +\n  \\frac{1}{2}\\sum_{{\\mu}=1}^N\\sum_{{\\nu}=1}^N \\langle \\mu\\nu|\\hat{v}|\\mu\\nu\\rangle_{\\mathrm{AS}}.\n\\label{FunctionalEPhi} \\tag{15}\n\\end{equation}\n$$\n\nwhich we will use as our starting point for the Hartree-Fock calculations later in this course.\n", "meta": {"hexsha": "965a264ee8957ed1c5050526b0366e68866e19b3", "size": 36750, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/pub/basicMB/html/basicMB.ipynb", "max_stars_repo_name": "GabrielSCabrera/ComputationalPhysics2", "max_stars_repo_head_hexsha": "a840b97b651085090f99bf6a11abab57100c2e85", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 87, "max_stars_repo_stars_event_min_datetime": "2015-01-21T08:29:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T07:11:53.000Z", "max_issues_repo_path": "doc/pub/basicMB/html/basicMB.ipynb", "max_issues_repo_name": "GabrielSCabrera/ComputationalPhysics2", "max_issues_repo_head_hexsha": "a840b97b651085090f99bf6a11abab57100c2e85", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-01-18T10:43:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T13:15:42.000Z", "max_forks_repo_path": "doc/pub/basicMB/html/basicMB.ipynb", "max_forks_repo_name": "GabrielSCabrera/ComputationalPhysics2", "max_forks_repo_head_hexsha": "a840b97b651085090f99bf6a11abab57100c2e85", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 54, "max_forks_repo_forks_event_min_datetime": "2015-02-09T10:02:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T10:44:14.000Z", "avg_line_length": 29.5418006431, "max_line_length": 230, "alphanum_fraction": 0.4880272109, "converted": true, "num_tokens": 6649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814055953761018, "lm_q2_score": 0.13660837596589698, "lm_q1q2_score": 0.0384423613720456}}
{"text": "```python\n# This cell is mandatory in all Dymos documentation notebooks.\nmissing_packages = []\ntry:\n    import openmdao.api as om\nexcept ImportError:\n    if 'google.colab' in str(get_ipython()):\n        !python -m pip install openmdao[notebooks]\n    else:\n        missing_packages.append('openmdao')\ntry:\n    import dymos as dm\nexcept ImportError:\n    if 'google.colab' in str(get_ipython()):\n        !python -m pip install dymos\n    else:\n        missing_packages.append('dymos')\ntry:\n    import pyoptsparse\nexcept ImportError:\n    if 'google.colab' in str(get_ipython()):\n        !pip install -q condacolab\n        import condacolab\n        condacolab.install_miniconda()\n        !conda install -c conda-forge pyoptsparse\n    else:\n        missing_packages.append('pyoptsparse')\nif missing_packages:\n    raise EnvironmentError('This notebook requires the following packages '\n                           'please install them and restart this notebook\\'s runtime: {\",\".join(missing_packages)}')\n```\n\n# How do I run two phases parallel-in-time?\n\nComplex models sometimes encounter state variables which are best simulated on different time scales, with some state variables changing quickly (fast variables) and some evolving slowly (slow variables).  \n\nFor instance, and aircraft trajectory optimization which includes vehicle component temperatures might see relatively gradual changes in altitude over the course of a two hour flight while temperatures of some components seem to exhibit step-function-like behavior on the same scale.\n\nTo accommodate both fast and slow variables in the same ODE, one would typically need to use a _dense_ grid (with many segments/higher order segments).\nThis can be unnecessarily burdensome when there are many slow variables or evaluating their rates is particularly expensive.\n\nAs a solution, Dymos allows the user to run two phases over the same range of times, where one phase may have a more sparse grid to accommodate the slow variables, and one has a more dense grid for the fast variables.\n\nTo connect the two phases, state variable values are passed from the first (slow) phase to the second (fast) phase as non-optimal dynamic control variables.\nThese values are then used to evaluate the rates of the fast variables.\nSince outputs from the first phase in generally will not fall on the appropriate grid points to be used by the second phase, interpolation is necessary.  \nThis is one application of the interpolating timeseries component.\n\nIn the following example, we solve the brachistochrone problem but do so to minimize the arclength of the resulting wire instead of the time required for the bead to travel along the wire.  \nThis is a trivial solution which should find a straight line from the starting point to the ending point.\n\nThere are two phases involved, the first utilizes the standard ODE for the brachistochrone problem.\nThe second integrates the arclength (\ud835\udc46) of the wire using the equation:\n\n\\begin{align}\n    S = \\int v \\sin \\theta  \\sqrt{1 + \\frac{1}{\\tan^2 \\theta}} dt\n\\end{align}\n\n## The ODE for the wire arclength\n\n\n```python\nom.display_source('dymos.examples.brachistochrone.doc.test_doc_brachistochrone_tandem_phases.BrachistochroneArclengthODE')\n```\n\nThe trick is that the bead velocity ($v$) is a state variable solved for in the first phase,\nand the wire angle ($\\theta$) is a control variable \"owned\" by the first phase.  In the\nsecond phase they are used as control variables with option ``opt=False`` so that their values are\nexpected as inputs for the second phase.  We need to connect their values from the first phase\nto the second phase, at the `control_input` node subset of the second phase.\n\nIn the following example, we instantiate two phases and add an interpolating timeseries to the first phase\nwhich provides outputs at the `control_input` nodes of the second phase.  Those values are\nthen connected and the entire problem run. The result is that the position and velocity variables\nare solved on a relatively coarse grid while the arclength of the wire is solved on a much denser grid.\n\n\n```python\nclass BrachistochroneArclengthODE(om.ExplicitComponent):\n\n    def initialize(self):\n        self.options.declare('num_nodes', types=int)\n\n    def setup(self):\n        nn = self.options['num_nodes']\n\n        # Inputs\n        self.add_input('v', val=np.zeros(nn), desc='velocity', units='m/s')\n        self.add_input('theta', val=np.zeros(nn), desc='angle of wire', units='rad')\n        self.add_output('Sdot', val=np.zeros(nn), desc='rate of change of arclength', units='m/s')\n\n        # Setup partials\n        arange = np.arange(nn)\n\n        self.declare_partials(of='Sdot', wrt='v', rows=arange, cols=arange)\n        self.declare_partials(of='Sdot', wrt='theta', rows=arange, cols=arange)\n\n    def compute(self, inputs, outputs):\n        theta = inputs['theta']\n        v = inputs['v']\n        outputs['Sdot'] = np.sqrt(1.0 + (1.0/np.tan(theta))**2) * v * np.sin(theta)\n\n    def compute_partials(self, inputs, jacobian):\n        theta = inputs['theta']\n        v = inputs['v']\n        cos_theta = np.cos(theta)\n        sin_theta = np.sin(theta)\n        tan_theta = np.tan(theta)\n        cot_theta = 1.0 / tan_theta\n        csc_theta = 1.0 / sin_theta\n\n        jacobian['Sdot', 'v'] = sin_theta * np.sqrt(1.0 + cot_theta**2)\n        jacobian['Sdot', 'theta'] = v * (cos_theta * (cot_theta**2 + 1) - cot_theta * csc_theta) / \\\n            (np.sqrt(1 + cot_theta**2))\n```\n\n\n```python\nom.display_source('dymos.examples.brachistochrone.brachistochrone_ode')\n```\n\n\n```python\nfrom dymos.examples.brachistochrone.brachistochrone_ode import BrachistochroneODE\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport openmdao.api as om\nimport dymos as dm\n\np = om.Problem(model=om.Group())\n\np.driver = om.pyOptSparseDriver()\np.driver.options['optimizer'] = 'SLSQP'\np.driver.declare_coloring()\n\n# The transcription of the first phase\ntx0 = dm.GaussLobatto(num_segments=10, order=3, compressed=False)\n\n# The transcription for the second phase (and the secondary timeseries outputs from the first phase)\ntx1 = dm.Radau(num_segments=20, order=9, compressed=False)\n\n#\n# First Phase: Integrate the standard brachistochrone ODE\n#\nphase0 = dm.Phase(ode_class=BrachistochroneODE, transcription=tx0)\n\np.model.add_subsystem('phase0', phase0)\n\nphase0.set_time_options(fix_initial=True, duration_bounds=(.5, 10))\n\nphase0.add_state('x', fix_initial=True, fix_final=False)\n\nphase0.add_state('y', fix_initial=True, fix_final=False)\n\nphase0.add_state('v', fix_initial=True, fix_final=False)\n\nphase0.add_control('theta', continuity=True, rate_continuity=True,\n                   units='deg', lower=0.01, upper=179.9)\n\nphase0.add_parameter('g', units='m/s**2', val=9.80665)\n\nphase0.add_boundary_constraint('x', loc='final', equals=10)\nphase0.add_boundary_constraint('y', loc='final', equals=5)\n\n# Add alternative timeseries output to provide control inputs for the next phase\nphase0.add_timeseries('timeseries2', transcription=tx1, subset='control_input')\n\n#\n# Second Phase: Integration of ArcLength\n#\nphase1 = dm.Phase(ode_class=BrachistochroneArclengthODE, transcription=tx1)\n\np.model.add_subsystem('phase1', phase1)\n\nphase1.set_time_options(fix_initial=True, input_duration=True)\n\nphase1.add_state('S', fix_initial=True, fix_final=False,\n                 rate_source='Sdot', units='m')\n\nphase1.add_control('theta', opt=False, units='deg', targets='theta')\nphase1.add_control('v', opt=False, units='m/s', targets='v')\n\n#\n# Connect the two phases\n#\np.model.connect('phase0.t_duration', 'phase1.t_duration')\n\np.model.connect('phase0.timeseries2.controls:theta', 'phase1.controls:theta')\np.model.connect('phase0.timeseries2.states:v', 'phase1.controls:v')\n\n# Minimize arclength at the end of the second phase\nphase1.add_objective('S', loc='final', ref=1)\n\np.model.linear_solver = om.DirectSolver()\np.setup(check=True)\n\np['phase0.t_initial'] = 0.0\np['phase0.t_duration'] = 2.0\n\np.set_val('phase0.states:x', phase0.interp('x', ys=[0, 10]))\np.set_val('phase0.states:y', phase0.interp('y', ys=[10, 5]))\np.set_val('phase0.states:v', phase0.interp('v', ys=[0, 9.9]))\np.set_val('phase0.controls:theta', phase0.interp('theta', ys=[5, 100]))\n\np['phase0.parameters:g'] = 9.80665\n\np['phase1.states:S'] = 0.0\n\ndm.run_problem(p)\n\nfig, (ax0, ax1) = plt.subplots(2, 1)\nfig.tight_layout()\nax0.plot(p.get_val('phase0.timeseries.states:x'), p.get_val('phase0.timeseries.states:y'), '.')\nax0.set_xlabel('x (m)')\nax0.set_ylabel('y (m)')\nax1.plot(p.get_val('phase1.timeseries.time'), p.get_val('phase1.timeseries.states:S'), '+')\nax1.set_xlabel('t (s)')\nax1.set_ylabel('S (m)')\nplt.show()\n```\n\n\n```python\nfrom openmdao.utils.assert_utils import assert_near_equal\n\nexpected = np.sqrt((10-0)**2 + (10 - 5)**2)\nassert_near_equal(p.get_val('phase1.timeseries.states:S')[-1], expected, tolerance=1.0E-3)\n```\n", "meta": {"hexsha": "6a4251ad72a5d9038b69240feeea78e86cead107", "size": 12466, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/dymos_book/faq/tandem_phases.ipynb", "max_stars_repo_name": "yonghoonlee/dymos", "max_stars_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/dymos_book/faq/tandem_phases.ipynb", "max_issues_repo_name": "yonghoonlee/dymos", "max_issues_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-05-24T15:14:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-28T21:12:55.000Z", "max_forks_repo_path": "docs/dymos_book/faq/tandem_phases.ipynb", "max_forks_repo_name": "yonghoonlee/dymos", "max_forks_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8905775076, "max_line_length": 292, "alphanum_fraction": 0.6001123055, "converted": true, "num_tokens": 2285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.08389038240239471, "lm_q1q2_score": 0.03834937398483376}}
{"text": "```python\n%load_ext autoreload\n%autoreload 2\n%matplotlib inline\n```\n\n# Deep Dive into Normalization\n\n\n```python\nfrom pathlib import Path\nfrom IPython.core.debugger import set_trace\nfrom fastai import datasets\nimport pickle, gzip, math, matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport torch\nfrom torch import nn, optim, tensor\nfrom torch.nn import init\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader, SequentialSampler, RandomSampler\n```\n\n\n```python\n# Importing and setting seaborn for improved plots\n#import seaborn as sns; sns.set(style='white')\n# Importing partials module\nfrom functools import partial\n```\n\n## Initial Setup - Taking Previous NBs Into Account\n\n**This is just to illustrate the amount of work that goes into building a customized DL library for experimentation and model building.**\n\n**The best method is to utilize the auto-export script and import all the necessary classes and modules.**\n\n### Exports of NB1\n\n\n```python\nimport operator\n\ndef test(a,b,cmp,cname=None):\n    if cname is None: cname=cmp.__name__\n    assert cmp(a,b),f\"{cname}:\\n{a}\\n{b}\"\n\ndef test_eq(a,b): test(a,b,operator.eq,'==')\n\nfrom pathlib import Path\nfrom IPython.core.debugger import set_trace\nfrom fastai import datasets\nimport pickle, gzip, math, torch, matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom torch import tensor\n\nMNIST_URL='http://deeplearning.net/data/mnist/mnist.pkl'\n\ndef near(a,b): return torch.allclose(a, b, rtol=1e-3, atol=1e-5)\ndef test_near(a,b): test(a,b,near)\n```\n\n### Exports of NB2\n\n\n```python\ndef get_data():\n    path = datasets.download_data(MNIST_URL, ext='.gz')\n    with gzip.open(path, 'rb') as f:\n        ((x_train, y_train), (x_valid, y_valid), _) = pickle.load(f, encoding='latin-1')\n    return map(tensor, (x_train,y_train,x_valid,y_valid))\n\ndef normalize(x, m, s): return (x-m)/s\n\ndef test_near_zero(a,tol=1e-3): assert a.abs()<tol, f\"Near zero: {a}\"\n\nfrom torch.nn import init\n\ndef mse(output, targ): return (output.squeeze(-1) - targ).pow(2).mean()\n\nfrom torch import nn\n```\n\n### Exports of NB3\n\n\n```python\nimport torch.nn.functional as F\n\ndef accuracy(out, yb): return (torch.argmax(out, dim=1)==yb).float().mean()\n\nfrom torch import optim\n\nclass Dataset():\n    def __init__(self, x, y): self.x,self.y = x,y\n    def __len__(self): return len(self.x)\n    def __getitem__(self, i): return self.x[i],self.y[i]\n\nfrom torch.utils.data import DataLoader, SequentialSampler, RandomSampler\n\ndef get_dls(train_ds, valid_ds, bs, **kwargs):\n    return (DataLoader(train_ds, batch_size=bs, shuffle=True, **kwargs),\n            DataLoader(valid_ds, batch_size=bs*2, **kwargs))\n```\n\n### Exports of NB4\n\n\n```python\nclass DataBunch():\n    def __init__(self, train_dl, valid_dl, c=None):\n        self.train_dl,self.valid_dl,self.c = train_dl,valid_dl,c\n\n    @property\n    def train_ds(self): return self.train_dl.dataset\n\n    @property\n    def valid_ds(self): return self.valid_dl.dataset\n    \n\ndef get_model(data, lr=0.5, nh=50):\n    m = data.train_ds.x.shape[1]\n    model = nn.Sequential(nn.Linear(m,nh), nn.ReLU(), nn.Linear(nh,data.c))\n    return model, optim.SGD(model.parameters(), lr=lr)\n\n\nclass Learner():\n    def __init__(self, model, opt, loss_func, data):\n        self.model,self.opt,self.loss_func,self.data = model,opt,loss_func,data\n\n        \nimport re\n\n_camel_re1 = re.compile('(.)([A-Z][a-z]+)')\n_camel_re2 = re.compile('([a-z0-9])([A-Z])')\n\ndef camel2snake(name):\n    s1 = re.sub(_camel_re1, r'\\1_\\2', name)\n    return re.sub(_camel_re2, r'\\1_\\2', s1).lower()\n\nclass Callback():\n    _order=0\n    def set_runner(self, run): self.run=run\n    def __getattr__(self, k): return getattr(self.run, k)\n    @property\n    def name(self):\n        name = re.sub(r'Callback$', '', self.__class__.__name__)\n        return camel2snake(name or 'callback')\n\n    \nfrom typing import *\n\n\ndef listify(o):\n    if o is None: return []\n    if isinstance(o, list): return o\n    if isinstance(o, str): return [o]\n    if isinstance(o, Iterable): return list(o)\n    return [o]\n\n\nclass AvgStats():\n    def __init__(self, metrics, in_train): self.metrics,self.in_train = listify(metrics),in_train\n\n    def reset(self):\n        self.tot_loss,self.count = 0.,0\n        self.tot_mets = [0.] * len(self.metrics)\n\n    @property\n    def all_stats(self): return [self.tot_loss.item()] + self.tot_mets\n    @property\n    def avg_stats(self): return [o/self.count for o in self.all_stats]\n\n    def __repr__(self):\n        if not self.count: return \"\"\n        return f\"{'train' if self.in_train else 'valid'}: {self.avg_stats}\"\n\n    def accumulate(self, run):\n        bn = run.xb.shape[0]\n        self.tot_loss += run.loss * bn\n        self.count += bn\n        for i,m in enumerate(self.metrics):\n            self.tot_mets[i] += m(run.pred, run.yb) * bn\n\n```\n\n\n```python\n\n```\n\n### Exports of NB5\n\n\n```python\ndef create_learner(model_func, loss_func, data):\n    return Learner(*model_func(data), loss_func, data)\n\ndef get_model_func(lr=0.5): return partial(get_model, lr=lr)\n\ndef annealer(f):\n    def _inner(start, end): return partial(f, start, end)\n    return _inner\n\n@annealer\ndef sched_lin(start, end, pos): return start + pos*(end-start)\n\n@annealer\ndef sched_cos(start, end, pos): return start + (1 + math.cos(math.pi*(1-pos))) * (end-start) / 2\n@annealer\ndef sched_no(start, end, pos):  return start\n@annealer\ndef sched_exp(start, end, pos): return start * (end/start) ** pos\n\n#This monkey-patch is there to be able to plot tensors\ntorch.Tensor.ndim = property(lambda x: len(x.shape))\n\ndef combine_scheds(pcts, scheds):\n    assert sum(pcts) == 1.\n    pcts = tensor([0] + listify(pcts))\n    assert torch.all(pcts >= 0)\n    pcts = torch.cumsum(pcts, 0)\n    def _inner(pos):\n        idx = (pos >= pcts).nonzero().max()\n        actual_pos = (pos-pcts[idx]) / (pcts[idx+1]-pcts[idx])\n        return scheds[idx](actual_pos)\n    return _inner\n\nclass Recorder(Callback):\n    def begin_fit(self):\n        self.lrs = [[] for _ in self.opt.param_groups]\n        self.losses = []\n\n    def after_batch(self):\n        if not self.in_train: return\n        for pg,lr in zip(self.opt.param_groups,self.lrs): lr.append(pg['lr'])\n        self.losses.append(self.loss.detach().cpu())\n\n    def plot_lr  (self, pgid=-1): plt.plot(self.lrs[pgid])\n    def plot_loss(self, skip_last=0): plt.plot(self.losses[:len(self.losses)-skip_last])\n\nclass ParamScheduler(Callback):\n    _order=1\n    def __init__(self, pname, sched_funcs): self.pname,self.sched_funcs = pname,sched_funcs\n\n    def begin_fit(self):\n        if not isinstance(self.sched_funcs, (list,tuple)):\n            self.sched_funcs = [self.sched_funcs] * len(self.opt.param_groups)\n\n    def set_param(self):\n        assert len(self.opt.param_groups)==len(self.sched_funcs)\n        for pg,f in zip(self.opt.param_groups,self.sched_funcs):\n            pg[self.pname] = f(self.n_epochs/self.epochs)\n\n    def begin_batch(self):\n        if self.in_train: self.set_param()\n\ndef pg_dicts(pgs): return [{'params':o} for o in pgs]\n\n```\n\n### Exports of NB5b\n\n\n```python\nclass Callback():\n    _order=0\n    def set_runner(self, run): self.run=run\n    def __getattr__(self, k): return getattr(self.run, k)\n\n    @property\n    def name(self):\n        name = re.sub(r'Callback$', '', self.__class__.__name__)\n        return camel2snake(name or 'callback')\n\n    def __call__(self, cb_name):\n        f = getattr(self, cb_name, None)\n        if f and f(): return True\n        return False\n\nclass TrainEvalCallback(Callback):\n    def begin_fit(self):\n        self.run.n_epochs=0.\n        self.run.n_iter=0\n\n    def after_batch(self):\n        if not self.in_train: return\n        self.run.n_epochs += 1./self.iters\n        self.run.n_iter   += 1\n\n    def begin_epoch(self):\n        self.run.n_epochs=self.epoch\n        self.model.train()\n        self.run.in_train=True\n\n    def begin_validate(self):\n        self.model.eval()\n        self.run.in_train=False\n\nclass CancelTrainException(Exception): pass\nclass CancelEpochException(Exception): pass\nclass CancelBatchException(Exception): pass\n\nclass Runner():\n    def __init__(self, cbs=None, cb_funcs=None):\n        self.in_train = False\n        cbs = listify(cbs)\n        for cbf in listify(cb_funcs):\n            cb = cbf()\n            setattr(self, cb.name, cb)\n            cbs.append(cb)\n        self.stop,self.cbs = False,[TrainEvalCallback()]+cbs\n\n    @property\n    def opt(self):       return self.learn.opt\n    @property\n    def model(self):     return self.learn.model\n    @property\n    def loss_func(self): return self.learn.loss_func\n    @property\n    def data(self):      return self.learn.data\n\n    def one_batch(self, xb, yb):\n        try:\n            self.xb,self.yb = xb,yb\n            self('begin_batch')\n            self.pred = self.model(self.xb)\n            self('after_pred')\n            self.loss = self.loss_func(self.pred, self.yb)\n            self('after_loss')\n            if not self.in_train: return\n            self.loss.backward()\n            self('after_backward')\n            self.opt.step()\n            self('after_step')\n            self.opt.zero_grad()\n        except CancelBatchException: self('after_cancel_batch')\n        finally: self('after_batch')\n\n    def all_batches(self, dl):\n        self.iters = len(dl)\n        try:\n            for xb,yb in dl: self.one_batch(xb, yb)\n        except CancelEpochException: self('after_cancel_epoch')\n\n    def fit(self, epochs, learn):\n        self.epochs,self.learn,self.loss = epochs,learn,tensor(0.)\n\n        try:\n            for cb in self.cbs: cb.set_runner(self)\n            self('begin_fit')\n            for epoch in range(epochs):\n                self.epoch = epoch\n                if not self('begin_epoch'): self.all_batches(self.data.train_dl)\n\n                with torch.no_grad():\n                    if not self('begin_validate'): self.all_batches(self.data.valid_dl)\n                self('after_epoch')\n\n        except CancelTrainException: self('after_cancel_train')\n        finally:\n            self('after_fit')\n            self.learn = None\n\n    def __call__(self, cb_name):\n        res = False\n        for cb in sorted(self.cbs, key=lambda x: x._order): res = cb(cb_name) and res\n        return res\n\nclass AvgStatsCallback(Callback):\n    def __init__(self, metrics):\n        self.train_stats,self.valid_stats = AvgStats(metrics,True),AvgStats(metrics,False)\n\n    def begin_epoch(self):\n        self.train_stats.reset()\n        self.valid_stats.reset()\n\n    def after_loss(self):\n        stats = self.train_stats if self.in_train else self.valid_stats\n        with torch.no_grad(): stats.accumulate(self.run)\n\n    def after_epoch(self):\n        print(self.train_stats)\n        print(self.valid_stats)\n\nclass Recorder(Callback):\n    def begin_fit(self):\n        self.lrs = [[] for _ in self.opt.param_groups]\n        self.losses = []\n\n    def after_batch(self):\n        if not self.in_train: return\n        for pg,lr in zip(self.opt.param_groups,self.lrs): lr.append(pg['lr'])\n        self.losses.append(self.loss.detach().cpu())\n\n    def plot_lr  (self, pgid=-1): plt.plot(self.lrs[pgid])\n    def plot_loss(self, skip_last=0): plt.plot(self.losses[:len(self.losses)-skip_last])\n\n    def plot(self, skip_last=0, pgid=-1):\n        losses = [o.item() for o in self.losses]\n        lrs    = self.lrs[pgid]\n        n = len(losses)-skip_last\n        plt.xscale('log')\n        plt.plot(lrs[:n], losses[:n])\n\nclass ParamScheduler(Callback):\n    _order=1\n    def __init__(self, pname, sched_funcs): self.pname,self.sched_funcs = pname,sched_funcs\n\n    def begin_fit(self):\n        if not isinstance(self.sched_funcs, (list,tuple)):\n            self.sched_funcs = [self.sched_funcs] * len(self.opt.param_groups)\n\n    def set_param(self):\n        assert len(self.opt.param_groups)==len(self.sched_funcs)\n        for pg,f in zip(self.opt.param_groups,self.sched_funcs):\n            pg[self.pname] = f(self.n_epochs/self.epochs)\n\n    def begin_batch(self):\n        if self.in_train: self.set_param()\n\nclass LR_Find(Callback):\n    _order=1\n    def __init__(self, max_iter=100, min_lr=1e-6, max_lr=10):\n        self.max_iter,self.min_lr,self.max_lr = max_iter,min_lr,max_lr\n        self.best_loss = 1e9\n\n    def begin_batch(self):\n        if not self.in_train: return\n        pos = self.n_iter/self.max_iter\n        lr = self.min_lr * (self.max_lr/self.min_lr) ** pos\n        for pg in self.opt.param_groups: pg['lr'] = lr\n\n    def after_step(self):\n        if self.n_iter>=self.max_iter or self.loss>self.best_loss*10:\n            raise CancelTrainException()\n        if self.loss < self.best_loss: self.best_loss = self.loss\n```\n\n### Exports of NB6\n\n\n```python\n# Enable CUDA\n#device = torch.device('cuda', 0)\n#torch.cuda.set_device(device)\n```\n\n\n```python\ntorch.set_num_threads(2)\n\ndef normalize_to(train, valid):\n    m,s = train.mean(),train.std()\n    return normalize(train, m, s), normalize(valid, m, s)\n\nclass Lambda(nn.Module):\n    def __init__(self, func):\n        super().__init__()\n        self.func = func\n\n    def forward(self, x): return self.func(x)\n\ndef flatten(x):      return x.view(x.shape[0], -1)\n\nclass CudaCallback(Callback):\n    def begin_fit(self): self.model.cuda()\n    def begin_batch(self): self.run.xb,self.run.yb = self.xb.cuda(),self.yb.cuda()\n\nclass BatchTransformXCallback(Callback):\n    _order=2\n    def __init__(self, tfm): self.tfm = tfm\n    def begin_batch(self): self.run.xb = self.tfm(self.xb)\n\ndef view_tfm(*size):\n    def _inner(x): return x.view(*((-1,)+size))\n    return _inner\n\ndef get_runner(model, data, lr=0.6, cbs=None, opt_func=None, loss_func = F.cross_entropy):\n    if opt_func is None: opt_func = optim.SGD\n    opt = opt_func(model.parameters(), lr=lr)\n    learn = Learner(model, opt, loss_func, data)\n    return learn, Runner(cb_funcs=listify(cbs))\n\ndef children(m): return list(m.children())\n\nclass Hook():\n    def __init__(self, m, f): self.hook = m.register_forward_hook(partial(f, self))\n    def remove(self): self.hook.remove()\n    def __del__(self): self.remove()\n\ndef append_stats(hook, mod, inp, outp):\n    if not hasattr(hook,'stats'): hook.stats = ([],[])\n    means,stds = hook.stats\n    if mod.training:\n        means.append(outp.data.mean())\n        stds .append(outp.data.std())\n\nclass ListContainer():\n    def __init__(self, items): self.items = listify(items)\n    def __getitem__(self, idx):\n        try: return self.items[idx]\n        except TypeError:\n            if isinstance(idx[0],bool):\n                assert len(idx)==len(self) # bool mask\n                return [o for m,o in zip(idx,self.items) if m]\n            return [self.items[i] for i in idx]\n    def __len__(self): return len(self.items)\n    def __iter__(self): return iter(self.items)\n    def __setitem__(self, i, o): self.items[i] = o\n    def __delitem__(self, i): del(self.items[i])\n    def __repr__(self):\n        res = f'{self.__class__.__name__} ({len(self)} items)\\n{self.items[:10]}'\n        if len(self)>10: res = res[:-1]+ '...]'\n        return res\n\nfrom torch.nn import init\n\nclass Hooks(ListContainer):\n    def __init__(self, ms, f): super().__init__([Hook(m, f) for m in ms])\n    def __enter__(self, *args): return self\n    def __exit__ (self, *args): self.remove()\n    def __del__(self): self.remove()\n\n    def __delitem__(self, i):\n        self[i].remove()\n        super().__delitem__(i)\n\n    def remove(self):\n        for h in self: h.remove()\n\ndef get_cnn_layers(data, nfs, layer, **kwargs):\n    nfs = [1] + nfs\n    return [layer(nfs[i], nfs[i+1], 5 if i==0 else 3, **kwargs)\n            for i in range(len(nfs)-1)] + [\n        nn.AdaptiveAvgPool2d(1), Lambda(flatten), nn.Linear(nfs[-1], data.c)]\n\ndef conv_layer(ni, nf, ks=3, stride=2, **kwargs):\n    return nn.Sequential(\n        nn.Conv2d(ni, nf, ks, padding=ks//2, stride=stride), GeneralRelu(**kwargs))\n\nclass GeneralRelu(nn.Module):\n    def __init__(self, leak=None, sub=None, maxv=None):\n        super().__init__()\n        self.leak,self.sub,self.maxv = leak,sub,maxv\n\n    def forward(self, x):\n        x = F.leaky_relu(x,self.leak) if self.leak is not None else F.relu(x)\n        if self.sub is not None: x.sub_(self.sub)\n        if self.maxv is not None: x.clamp_max_(self.maxv)\n        return x\n\ndef init_cnn(m, uniform=False):\n    f = init.kaiming_uniform_ if uniform else init.kaiming_normal_\n    for l in m:\n        if isinstance(l, nn.Sequential):\n            f(l[0].weight, a=0.1)\n            l[0].bias.data.zero_()\n\ndef get_cnn_model(data, nfs, layer, **kwargs):\n    return nn.Sequential(*get_cnn_layers(data, nfs, layer, **kwargs))\n\ndef get_learn_run(nfs, data, lr, layer, cbs=None, opt_func=None, uniform=False, **kwargs):\n    model = get_cnn_model(data, nfs, layer, **kwargs)\n    init_cnn(model, uniform=uniform)\n    return get_runner(model, data, lr=lr, cbs=cbs, opt_func=opt_func)\n\nfrom IPython.display import display, Javascript\ndef nb_auto_export():\n    display(Javascript(\"\"\"{\nconst ip = IPython.notebook\nif (ip) {\n    ip.save_notebook()\n    console.log('a')\n    const s = `!python notebook2script.py ${ip.notebook_name}`\n    if (ip.kernel) { ip.kernel.execute(s) }\n}\n}\"\"\"))\n```\n\n## Building the ConvNet\n\n\n```python\nx_train, y_train, x_valid, y_valid = get_data()\n# Normalizing\nx_train, x_valid = normalize_to(x_train, x_valid)\n# Build Datasets\ntrain_ds, valid_ds = Dataset(x_train, y_train), Dataset(x_valid, y_valid)\n\n# Arch\nnh, bs = 50, 512\nc = y_train.max().item()+1\nloss_func = F.cross_entropy\n\n# Create databunch\ndata = DataBunch(*get_dls(train_ds, valid_ds, bs), c)\n```\n\n\n```python\n# Transforming\nmnist_view = view_tfm(1, 28, 28)\n# Callbacks\ncbfs = [Recorder,\n       partial(AvgStatsCallback, accuracy),\n       CudaCallback,\n       partial(BatchTransformXCallback, mnist_view)]\n```\n\n\n```python\nnfs = [8, 16, 32, 64, 64]\n```\n\n\n```python\nlearn, run = get_learn_run(nfs, data, lr=0.4,\n                           layer=conv_layer, cbs=cbfs)\n```\n\n\n```python\n%time run.fit(2, learn)\n```\n\n    train: [1.6192525, tensor(0.4702, device='cuda:0')]\n    valid: [0.25496630859375, tensor(0.9239, device='cuda:0')]\n    train: [0.310026640625, tensor(0.9089, device='cuda:0')]\n    valid: [0.15269254150390624, tensor(0.9537, device='cuda:0')]\n    CPU times: user 3.1 s, sys: 307 ms, total: 3.4 s\n    Wall time: 2.87 s\n\n\n## Custom BatchNorm\n\n\n```python\nclass BatchNorm(nn.Module):\n    def __init__(self, nf, mom=0.1, eps=1e-5):\n        super().__init__()\n        # NB: pytorch bn mom is opposite of what you'd expect\n        self.mom, self.eps = mom, eps\n        self.mults = nn.Parameter(torch.ones (nf,1,1))\n        self.adds  = nn.Parameter(torch.zeros(nf,1,1))\n        self.register_buffer('vars',  torch.ones(1,nf,1,1))\n        self.register_buffer('means', torch.zeros(1,nf,1,1))\n\n    def update_stats(self, x):\n        m = x.mean((0,2,3), keepdim=True)\n        v = x.var ((0,2,3), keepdim=True)\n        self.means.lerp_(m, self.mom)\n        self.vars.lerp_(v, self.mom)\n        return m,v\n        \n    def forward(self, x):\n        if self.training:\n            with torch.no_grad(): m,v = self.update_stats(x)\n        else: \n            m,v = self.means,self.vars\n            \n        x = (x-m) / (v+self.eps).sqrt()\n        return x*self.mults + self.adds\n```\n\n\n```python\ndef conv_layer(ni, nf, ks=3, stride=2, bn=True, **kwargs):\n    # No bias needed in case of BN\n    layers = [nn.Conv2d(ni, nf, ks, padding=ks//2, stride=stride, bias=not bn),\n              GeneralRelu(**kwargs)]\n    if bn: layers.append(BatchNorm(nf)) #Custom BN\n    return nn.Sequential(*layers)\n```\n\n\n```python\n# Initalize \ndef init_cnn_(m, f):\n    if isinstance(m, nn.Conv2d):\n        f(m.weight, a=0.1)\n        if getattr(m, 'bias', None) is not None: m.bias.data.zero_()\n    for l in m.children():\n        init_cnn_(l, f)\n            \ndef init_cnn(m, uniform=False):\n    f = init.kaiming_uniform_ if uniform else init.kaiming_normal_\n    init_cnn_(m, f)\n    \ndef get_learn_run(nfs, data, lr, layer, cbs=None,\n                  opt_func=None, uniform=False, **kwargs):\n    model = get_cnn_model(data, nfs, layer, **kwargs)\n    init_cnn(model, uniform=uniform)\n    return get_runner(model, data, lr=lr, cbs=cbs, opt_func=opt_func)\n```\n\nUsing this during training to observe how it helps in keeping the activation means to 0 and std to 1.\n\n\n```python\nlearn, run = get_learn_run(nfs, data, lr=0.8, layer=conv_layer, cbs=cbfs)\n```\n\n\n```python\nwith Hooks(learn.model, append_stats) as hooks:\n    run.fit(1, learn)\n    fig,(ax0,ax1) = plt.subplots(1,2, figsize=(10,4))\n    for h in hooks[:-1]:\n        ms,ss = h.stats\n        ax0.plot(ms[:10])\n        ax1.plot(ss[:10])\n        h.remove()\n    plt.legend(range(6));\n    \n    fig,(ax0,ax1) = plt.subplots(1,2, figsize=(10,4))\n    for h in hooks[:-1]:\n        ms,ss = h.stats\n        ax0.plot(ms)\n        ax1.plot(ss)\n```\n\nAfter applying BatchNorm using linear interpolation, we can see the improvement in our standard deviations and means.\n\n\n```python\nlearn, run = get_learn_run(nfs, data, 1.0, conv_layer, cbs=cbfs)\n```\n\n\n```python\n%time run.fit(5, learn)\n```\n\n    train: [0.26607884765625, tensor(0.9183, device='cuda:0')]\n    valid: [0.2518082275390625, tensor(0.9188, device='cuda:0')]\n    train: [0.08462037109375, tensor(0.9741, device='cuda:0')]\n    valid: [0.07879784545898437, tensor(0.9751, device='cuda:0')]\n    train: [0.0603748388671875, tensor(0.9812, device='cuda:0')]\n    valid: [0.11693089599609376, tensor(0.9633, device='cuda:0')]\n    train: [0.0490041064453125, tensor(0.9846, device='cuda:0')]\n    valid: [0.06964392700195313, tensor(0.9784, device='cuda:0')]\n    train: [0.0403047900390625, tensor(0.9866, device='cuda:0')]\n    valid: [0.0707970458984375, tensor(0.9793, device='cuda:0')]\n    CPU times: user 5.89 s, sys: 35.9 ms, total: 5.92 s\n    Wall time: 4.93 s\n\n\n### Comparison to Built-in BatchNorm\n\n\n```python\ndef conv_layer(ni, nf, ks=3, stride=2, bn=True, **kwargs):\n    layers = [nn.Conv2d(ni, nf, ks, padding=ks//2, stride=stride, bias=not bn),\n              GeneralRelu(**kwargs)]\n    if bn: layers.append(nn.BatchNorm2d(nf, eps=1e-5, momentum=0.1))\n    return nn.Sequential(*layers)\n```\n\n\n```python\nlearn, run = get_learn_run(nfs, data, 1.0, conv_layer, cbs=cbfs)\n```\n\n\n```python\n%time run.fit(5, learn)\n```\n\n    train: [0.23452498046875, tensor(0.9251, device='cuda:0')]\n    valid: [0.08072618408203125, tensor(0.9748, device='cuda:0')]\n    train: [0.06257984375, tensor(0.9802, device='cuda:0')]\n    valid: [0.1142558837890625, tensor(0.9642, device='cuda:0')]\n    train: [0.0423348681640625, tensor(0.9868, device='cuda:0')]\n    valid: [0.07078927001953125, tensor(0.9797, device='cuda:0')]\n    train: [0.03153028076171875, tensor(0.9903, device='cuda:0')]\n    valid: [0.057710650634765624, tensor(0.9821, device='cuda:0')]\n    train: [0.02128148681640625, tensor(0.9938, device='cuda:0')]\n    valid: [0.05555340576171875, tensor(0.9835, device='cuda:0')]\n    CPU times: user 5.61 s, sys: 11.9 ms, total: 5.62 s\n    Wall time: 4.63 s\n\n\n### Adding the Scheduler\n\nAdding learning rate annealing:\n\n\n\n```python\nsched = combine_scheds([0.3, 0.7], [sched_lin(0.6, 2.), sched_lin(2., 0.1)])\n```\n\n\n```python\nlearn, run = get_learn_run(nfs, data, 0.9, conv_layer, cbs=cbfs +\n                           [partial(ParamScheduler, 'lr', sched)])\n```\n\n\n```python\nrun.fit(10, learn)\n```\n\n    train: [0.242242890625, tensor(0.9275, device='cuda:0')]\n    valid: [0.1109781005859375, tensor(0.9654, device='cuda:0')]\n    train: [0.07245439453125, tensor(0.9776, device='cuda:0')]\n    valid: [0.07864197387695313, tensor(0.9756, device='cuda:0')]\n    train: [0.05993212890625, tensor(0.9809, device='cuda:0')]\n    valid: [0.10018829345703124, tensor(0.9698, device='cuda:0')]\n    train: [0.03866418701171875, tensor(0.9874, device='cuda:0')]\n    valid: [0.05641264038085937, tensor(0.9833, device='cuda:0')]\n    train: [0.02331113037109375, tensor(0.9927, device='cuda:0')]\n    valid: [0.05662333984375, tensor(0.9840, device='cuda:0')]\n    train: [0.01354578125, tensor(0.9962, device='cuda:0')]\n    valid: [0.048208865356445314, tensor(0.9855, device='cuda:0')]\n    train: [0.0076075390625, tensor(0.9980, device='cuda:0')]\n    valid: [0.04530145263671875, tensor(0.9874, device='cuda:0')]\n    train: [0.004427695922851562, tensor(0.9991, device='cuda:0')]\n    valid: [0.04266683349609375, tensor(0.9886, device='cuda:0')]\n    train: [0.0028356549072265625, tensor(0.9997, device='cuda:0')]\n    valid: [0.0436294677734375, tensor(0.9886, device='cuda:0')]\n    train: [0.0023242259216308594, tensor(0.9998, device='cuda:0')]\n    valid: [0.043790444946289066, tensor(0.9885, device='cuda:0')]\n\n\n## Additional Norms\n\n### Layer Norm\n\nGeneral equation for a norm layer with learnable affine:\n\n$$y = \\frac{x - \\mathrm{E}[x]}{ \\sqrt{\\mathrm{Var}[x] + \\epsilon}} * \\gamma + \\beta$$\n\nThe key difference with BN is:\n1. Don't keep moving averages.\n2. Don't average over the batch dimension but over the hidden dimension. This makes it independent of batch size.\n3. Instead of (0, 2, 3), we now have (1, 2, 3).\n4. Not nearly as good as BN, but works well enough on RNNs since we can't use BN in that scenario.\n\n\n```python\n# This is the code implementation of the equation above\nclass LayerNorm (nn.Module):\n    __constants__ = ['eps']\n    def __init__(self, eps=1e-5):\n        super().__init__()\n        self.eps = eps\n        self.mult = nn.Parameter(tensor(1.))\n        self.add = nn.Parameter(tensor(0.))\n        \n    def forward(self, x):\n        m = x.mean((1, 2, 3), keepdim=True)\n        v = x.var((1, 2, 3), keepdim=True)\n        x = (x - m) / (v+self.eps).sqrt()\n        return x*self.mult + self.add\n```\n\n\n```python\ndef conv_layer_norm(ni, nf, ks=3, stride=2, bn=True, **kwargs):\n    layers = [nn.Conv2d(ni, nf, ks, padding=ks//2, stride=stride, bias=True),\n              GeneralRelu(**kwargs)]\n    if bn: layers.append(LayerNorm())\n    return nn.Sequential(*layers)\n```\n\n\n```python\nlearn, run = get_learn_run(nfs, data, 0.8, conv_layer_norm, cbs=cbfs)\n```\n\n\n```python\n%time run.fit(3, learn)\n```\n\n    train: [nan, tensor(0.1380, device='cuda:0')]\n    valid: [nan, tensor(0.0991, device='cuda:0')]\n    train: [nan, tensor(0.0986, device='cuda:0')]\n    valid: [nan, tensor(0.0991, device='cuda:0')]\n    train: [nan, tensor(0.0986, device='cuda:0')]\n    valid: [nan, tensor(0.0991, device='cuda:0')]\n    CPU times: user 4.09 s, sys: 16.1 ms, total: 4.1 s\n    Wall time: 3.51 s\n\n\n### Instance Norm\n\n|\\begin{equation}\\label{eq:bnorm}\n    y_{tijk} =  \\frac{x_{tijk} - \\mu_{i}}{\\sqrt{\\sigma_i^2 + \\epsilon}},\n    \\quad\n    \\mu_i = \\frac{1}{HWT}\\sum_{t=1}^T\\sum_{l=1}^W \\sum_{m=1}^H x_{tilm},\n    \\quad\n    \\sigma_i^2 = \\frac{1}{HWT}\\sum_{t=1}^T\\sum_{l=1}^W \\sum_{m=1}^H (x_{tilm} - mu_i)^2.\n\\end{equation}\n\nIn order to combine the effects of instance-specific normalization and batch normalization, the authors propose to replace the latter by the *instance normalization* (also known as *contrast normalization*) layer:\n\n\\begin{equation}\\label{eq:inorm}\n    y_{tijk} =  \\frac{x_{tijk} - \\mu_{ti}}{\\sqrt{\\sigma_{ti}^2 + \\epsilon}},\n    \\quad\n    \\mu_{ti} = \\frac{1}{HW}\\sum_{l=1}^W \\sum_{m=1}^H x_{tilm},\n    \\quad\n    \\sigma_{ti}^2 = \\frac{1}{HW}\\sum_{l=1}^W \\sum_{m=1}^H (x_{tilm} - mu_{ti})^2.\n\\end{equation}\n\nThis used for style transfer and **NOT** for image classification. \n\nA graphical depiction of the different types of norms :\n\n\n\n\n```python\nclass InstanceNorm(nn.Module):\n    __constants__ = ['eps']\n    def __init__(self, nf, eps=1e-0):\n        super().__init__()\n        self.eps = eps\n        self.mults = nn.Parameter(torch.ones (nf,1,1))\n        self.adds  = nn.Parameter(torch.zeros(nf,1,1))\n\n    def forward(self, x):\n        m = x.mean((2,3), keepdim=True)\n        v = x.var ((2,3), keepdim=True)\n        res = (x-m) / ((v+self.eps).sqrt())\n        return res*self.mults + self.adds\n```\n\n\n```python\ndef conv_instance_norm(ni, nf, ks=3, stride=2, bn=True, **kwargs):\n    layers = [nn.Conv2d(ni, nf, ks, padding=ks//2, stride=stride, bias=True),\n              GeneralRelu(**kwargs)]\n    if bn: layers.append(InstanceNorm(nf))\n    return nn.Sequential(*layers)\n```\n\n\n```python\nlearn, run = get_learn_run(nfs, data, 0.1, conv_instance_norm, cbs=cbfs)\n```\n\n\n```python\n%time run.fit(3, learn)\n```\n\n    train: [nan, tensor(0.0986, device='cuda:0')]\n    valid: [nan, tensor(0.0991, device='cuda:0')]\n    train: [nan, tensor(0.0986, device='cuda:0')]\n    valid: [nan, tensor(0.0991, device='cuda:0')]\n    train: [nan, tensor(0.0986, device='cuda:0')]\n    valid: [nan, tensor(0.0991, device='cuda:0')]\n    CPU times: user 4.5 s, sys: 19.6 ms, total: 4.52 s\n    Wall time: 3.92 s\n\n\n## Addressing the Issue of Small Batch Sizes\n\n### Problem:\n\nComputing the statistics, i.e. mean and std. deviation, for a BatchNorm Layer on a small batch size gives us a standard deviation very close to 0 due to the lack of sufficient numbers of samples.\n\n\n\n```python\ndata = DataBunch(*get_dls(train_ds, valid_ds, 2), c)\n```\n\n\n```python\ndef conv_layer(ni, nf, ks=3, stride=2 , bn=True, **kwargs):\n    layers = [nn.Conv2d(ni, nf, ks, padding=ks//2, stride=stride, bias=not bn),\n              GeneralRelu(**kwargs)]\n    if bn: layers.append(nn.BatchNorm2d(nf, eps=1e-5, momentum=0.1))\n    return nn.Sequential(*layers)\n```\n\n\n```python\nlearn, run = get_learn_run(nfs, data, 0.4, conv_layer, cbs=cbfs)\n```\n\n\n```python\n%time run.fit(2, learn)\n```\n\n    train: [2.3357021875, tensor(0.1712, device='cuda:0')]\n    valid: [288141.4912, tensor(0.1925, device='cuda:0')]\n    train: [2.32542328125, tensor(0.1792, device='cuda:0')]\n    valid: [38715509.9648, tensor(0.2931, device='cuda:0')]\n    CPU times: user 1min 54s, sys: 775 ms, total: 1min 55s\n    Wall time: 1min 54s\n\n\nExtremely small batch sizes also add to the compute overhead!The performance is abysmal!!\n\n### Solution: Running Batch Norm\n\nAs indicated in the lessons, the solution is to use Running BatchNorm, which employs smoother running mean and variance for the mean and std dev. \n\n\n```python\nclass RunningBatchNorm(nn.Module):\n    def __init__(self, nf, mom=0.1, eps=1e-5):\n        super().__init__()\n        self.mom, self.eps = mom, eps\n        self.mults = nn.Parameter(torch.ones(nf, 1, 1))\n        self.adds = nn.Parameter(torch.ones(nf, 1, 1))\n        self.register_buffer('sums', torch.zeros(1, nf, 1, 1))\n        self.register_buffer('sqrs', torch.zeros(1, nf, 1, 1))\n        self.register_buffer('batch', torch.tensor(0.))\n        self.register_buffer('count', torch.tensor(0.))\n        self.register_buffer('step', torch.tensor(0.))\n        self.register_buffer('dbias', torch.tensor(0.))\n        \n    def update_stats(self, x):\n        bs, nc, *_ = x.shape\n        self.sums.detach_()\n        self.sqrs.detach_()\n        dims = (0, 2, 3)\n        s = x.sum(dims, keepdim=True)\n        ss = (x*x).sum(dims, keepdim=True)\n        c = self.count.new_tensor(x.numel() / nc)\n        mom1 = 1 - (1-self.mom)/math.sqrt(bs-1)\n        self.mom1 = self.dbias.new_tensor(mom1)\n        self.sums.lerp_(s, self.mom1)\n        self.sqrs.lerp_(ss, self.mom1)\n        self.count.lerp_(c, self.mom1)\n        self.dbias = self.dbias*(1-self.mom1) + self.mom1\n        self.batch += bs\n        self.step += 1\n        \n    def forward(self, x):\n        if self.training: self.update_stats(x)\n        sums = self.sums \n        sqrs = self.sqrs\n        c = self.count\n        if self.step < 100:\n            sums = sums / self.dbias\n            sqrs = sqrs / self.dbias\n            c    = c    / self.dbias\n        means = sums / c\n        vars = (sqrs / c).sub_(means*means)\n        if bool(self.batch < 20): vars.clamp_min_(0.01)\n        x = (x - means).div_((vars.add_(self.eps)).sqrt())\n        return x.mul_(self.mults).add_(self.adds)\n```\n\n\n```python\n# Lets apply the Running BatchNorm to a new Conv learner\ndef conv_running_bn(ni, nf, ks=3, stride=2, bn=True, **kwargs):\n    layers = [nn.Conv2d(ni, nf, ks, padding=ks//2, stride=stride,\n                       bias=not bn), GeneralRelu(**kwargs)]\n    if bn: layers.append(RunningBatchNorm(nf))\n    return nn.Sequential(*layers)\n```\n\n\n```python\nlearn, run = get_learn_run(nfs, data, 0.4, conv_running_bn, cbs=cbfs)\n```\n\n\n```python\n%time run.fit(1, learn)\n```\n\n    train: [0.63196484375, tensor(0.8098, device='cuda:0')]\n    valid: [17.473784375, tensor(0.9446, device='cuda:0')]\n    CPU times: user 2min 18s, sys: 387 ms, total: 2min 19s\n    Wall time: 2min 18s\n\n\n### Maxing out the performance in a single epoch\n\nWith a more reasonable batch size...\n\n\n```python\ndata = DataBunch(*get_dls(train_ds, valid_ds, 32), c)\n```\n\n\n```python\nlearn, run = get_learn_run(nfs, data, 0.9, conv_running_bn, cbs=cbfs + \n                          [partial(ParamScheduler, 'lr', sched_lin(1., 0.2))])\n```\n\n\n```python\n%time run.fit(1, learn)\n\n```\n\n    train: [0.246381328125, tensor(0.9263, device='cuda:0')]\n    valid: [372.079275, tensor(0.9726, device='cuda:0')]\n    CPU times: user 9.3 s, sys: 28 ms, total: 9.33 s\n    Wall time: 9.12 s\n\n\n\n```python\n# Changing batch size\ndata = DataBunch(*get_dls(train_ds, valid_ds, 128), c)\n```\n\n\n```python\n#cbfs.append(LR_Find)\n```\n\n\n```python\nlearn, run = get_learn_run(nfs, data, 0.85, conv_running_bn, cbs=cbfs + \n                          [partial(ParamScheduler, 'lr', sched_lin(0.9, 0.10))])\n```\n\n\n```python\n%time run.fit(1, learn)\n```\n\n    train: [0.2676537109375, tensor(0.9299, device='cuda:0')]\n    valid: [0.09938456420898438, tensor(0.9758, device='cuda:0')]\n    CPU times: user 2.42 s, sys: 7.91 ms, total: 2.42 s\n    Wall time: 2.22 s\n\n\n# Layerwise Sequential Unit Variance (LSUV)\n\nManaging to keep the unit variances of our layer outputs in check as the model trains can prove to be quite a \"fiddley\" task, especially if we're adding dropout, or changing activation functions. These variations in outputs get exponentially worse as the model trains over multiple epochs.\n\nLSUV shifts this burden to the computer itself.\n\n\n```python\n# Redefining our architecture\nnh, bs = 50, 512\ndata = DataBunch(*get_dls(train_ds, valid_ds, bs), c)\n```\n\n\n```python\n# Recreating our ConvLayer class\nclass ConvLayer(nn.Module):\n    # Adding a subtraction hyper parameter\n    def __init__(self, ni, nf, ks=3, stride=2, sub=0., **kwargs):\n        super().__init__()\n        self.conv = nn.Conv2d(ni, nf, ks, padding=ks//2, stride=stride, bias=True)\n        self.relu = GeneralRelu(sub=sub, **kwargs)\n        \n    def forward(self, x): return self.relu(self.conv(x))\n    \n    @property\n    def bias(self): return -self.relu.sub \n    @bias.setter\n    def bias(self, v): self.relu.sub = -v\n    @property\n    def weight(self): return self.conv.weight\n    \n```\n\nCreate a learner and runner, without really worrying about how it initializes...\n\n\n```python\nlearn, run = get_learn_run(nfs, data, 0.6, ConvLayer, cbs=cbfs)\n```\n\n\n```python\nrun.fit(2, learn)\n```\n\n    train: [1.433776875, tensor(0.5219, device='cuda:0')]\n    valid: [0.226480224609375, tensor(0.9305, device='cuda:0')]\n    train: [0.30987103515625, tensor(0.9050, device='cuda:0')]\n    valid: [0.1582620849609375, tensor(0.9539, device='cuda:0')]\n\n\nWith the initial performance noted, let's recreate the model, this time with LSUV, and we will define a function which grabs a single mini-batch.\n\n\n```python\nlearn, run = get_learn_run(nfs, data, 0.6, ConvLayer, cbs=cbfs)\n```\n\n\n```python\ndef get_batch(dl, runer):\n    run.xb, run.yb = next(iter(dl))\n    for cb in run.cbs: cb.set_runner(run)\n    run('begin_batch')\n    return run.xb, run.yb\n    \n```\n\n\n```python\nxb, yb = get_batch(data.train_dl, run)\n```\n\nNow that we have our mini-batch, we will use a function which (using recursion) only gives us the outputs of the convolutional layers.\n\n\n```python\ndef find_modules(m, cond):\n    if cond(m): return [m]\n    return sum([find_modules(o, cond) for o in m.children()], [])\n\ndef is_lin_layer(l):\n    lin_layers = (nn.Conv1d, nn.Conv2d, nn.Conv3d, nn.Linear, nn.ReLu)\n    return isinstance(l, lin_layers)\n```\n\n\n```python\nmods = find_modules(learn.model, lambda o: isinstance(o, ConvLayer))\n```\n\n\n```python\nmods\n```\n\n\n\n\n    [ConvLayer(\n       (conv): Conv2d(1, 8, kernel_size=(5, 5), stride=(2, 2), padding=(2, 2))\n       (relu): GeneralRelu()\n     ), ConvLayer(\n       (conv): Conv2d(8, 16, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n       (relu): GeneralRelu()\n     ), ConvLayer(\n       (conv): Conv2d(16, 32, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n       (relu): GeneralRelu()\n     ), ConvLayer(\n       (conv): Conv2d(32, 64, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n       (relu): GeneralRelu()\n     ), ConvLayer(\n       (conv): Conv2d(64, 64, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n       (relu): GeneralRelu()\n     )]\n\n\n\nAdding another helper function to grab the mean and std of the output of a hooked layer.\n\n\n```python\ndef append_stat(hook, mod, inp, outp):\n    d = outp.data\n    hook.mean, hook.std = d.mean().item(), d.std().item()\n```\n\n\n```python\nmdl = learn.model.cuda()\n```\n\n\n```python\nwith Hooks(mods, append_stat) as hooks:\n    mdl(xb)\n    for hook in hooks: print(hook.mean, hook.std)\n```\n\n    0.3897072970867157 0.6319916248321533\n    0.33694127202033997 0.5548509955406189\n    0.2168125957250595 0.3948383331298828\n    0.21095244586467743 0.3277290463447571\n    0.1627117097377777 0.2220781147480011\n\n\nHere, our means are too high and the std. devs. are not close to 1. Therefore, we will adjust the bias terms to make the means 0 and then std. devs. must be adjusted to 1 (with a threshold of 1e-3). \n\n\n```python\ndef lsuv_module(m, xb):\n    h = Hook(m, append_stat)\n    \n    # mdl(xb) is not None exists to pass xb through mdl while computing\n    # all activations in order to update the hooks.\n    \n    while mdl(xb) is not None and abs(h.mean) > 1e-3: m.bias -= h.mean\n    while mdl(xb) is not None and abs(h.std-1)> 1e-3: m.weight.data /= h.std\n        \n    h.remove()\n    return h.mean, h.std\n```\n\nExecuting the initialization on all conv layers in order...\n\n\n```python\nfor m in mods: print(lsuv_module(m, xb))\n```\n\n    (0.22692637145519257, 1.0000001192092896)\n    (0.11001376807689667, 1.0)\n    (0.15807662904262543, 0.9999999403953552)\n    (0.1515551060438156, 1.0000001192092896)\n    (0.2991049587726593, 1.0)\n\n\nNow that our means and std. devs. are much more acceptable, the model will begin training on much better grounds.\n\n\n```python\n%time run.fit(2, learn)\n```\n\n    train: [0.4551003125, tensor(0.8555, device='cuda:0')]\n    valid: [0.1386651123046875, tensor(0.9577, device='cuda:0')]\n    train: [0.113353916015625, tensor(0.9646, device='cuda:0')]\n    valid: [0.10336754150390624, tensor(0.9667, device='cuda:0')]\n    CPU times: user 2.37 s, sys: 0 ns, total: 2.37 s\n    Wall time: 1.97 s\n\n\n**Note** LSUV is very useful for more complex and deeper architectures where initializations are hard to optimize from the get go.\n\n\n```python\n\n```\n", "meta": {"hexsha": "df2e020d8c6a8ff5d41390832822b5f735d1443b", "size": 344482, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "pytorch_NN_mechanics/.ipynb_checkpoints/04_Custom_BatchNorm_and_LSUV-checkpoint.ipynb", "max_stars_repo_name": "bachaudhry/fastai_test_implement", "max_stars_repo_head_hexsha": "7667dd6c5a3ee52dac3701b6757a0e2c3b13fc99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pytorch_NN_mechanics/.ipynb_checkpoints/04_Custom_BatchNorm_and_LSUV-checkpoint.ipynb", "max_issues_repo_name": "bachaudhry/fastai_test_implement", "max_issues_repo_head_hexsha": "7667dd6c5a3ee52dac3701b6757a0e2c3b13fc99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pytorch_NN_mechanics/.ipynb_checkpoints/04_Custom_BatchNorm_and_LSUV-checkpoint.ipynb", "max_forks_repo_name": "bachaudhry/fastai_test_implement", "max_forks_repo_head_hexsha": "7667dd6c5a3ee52dac3701b6757a0e2c3b13fc99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 179.6984872196, "max_line_length": 190100, "alphanum_fraction": 0.8896923497, "converted": true, "num_tokens": 11701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740416, "lm_q2_score": 0.09670579720114003, "lm_q1q2_score": 0.03830208776552488}}
{"text": "# 60 minutos sobre XGBoost\n\n> My confession: I (over)use GBM. When in doubt, use GBM.\n\n-- Owen Zhang, 2015;[ _\"Winning Data Science Competitions\"_ @ NYC Data Science Academy](https://www.youtube.com/watch?v=LgLcfZjNF44)\n\n\n## Israel Z\u00fa\u00f1iga de la Mora | 01/Mar/202 @ Saturdays.ai Mty\n\n\n# Objetivo de esta pl\u00e1tica:\nAprender el uso b\u00e1sico de la biblioteca de Machine Lerning XGBoost para Gradient Boosting en Python.\n\n\n\n\n\n# Que no veremos hoy (AKA: the proof is left as an exercise to the reader):\n- Uso avanzado de XGBoost:\n    - Selecci\u00f3n de features por puntuaci\u00f3n (XGBoost + Scikit-Learn's `SelectFromModel` class)\n    - Monitoreo de performance en entrenamiento y _Early Stopping_\n    - Tuning: Multithreading, Gradient Boosting Estimators, Learning Rate\n    - Stochastic Gradient Boosting\n    - Serializaci\u00f3n de modelos (Pickle/Joblib)\n- Uso y/o despliegue a Producci\u00f3n en AWS/GCP/Azure/Docker/Kubeflow/Polyaxon/MLFlow\n- Comparaci\u00f3n con otras implementaciones similares (Microsoft's LightGBM, Yandex's CatBoost, H2O's GBM)\n- Formalidad en Teor\u00eda Matem\u00e1tica/CompSci sobre algoritmos implementados:\n    - [Kaggle Winning Solution Xgboost algorithm -- Let us learn from its author](https://www.slideshare.net/ShangxuanZhang/kaggle-winning-solution-xgboost-algorithm-let-us-learn-from-its-author)\n    - [Original XGBoost Paper](https://arxiv.org/pdf/1603.02754v3.pdf)\n        - [Slides(Tianqi Chen)](https://homes.cs.washington.edu/~tqchen/data/pdf/BoostedTree.pdf)\n    - [Documentation](https://xgboost.readthedocs.io/en/latest/)\n\n   \n# Outline\n\n- Teor\u00eda\n    - Decision Trees \n    - Gradient Boosting\n    - Tree Boosting\n- XGBoost\n    - Qu\u00e9 es XGBoost?\n    - Caracter\u00edsticas principales\n    - Por qu\u00e9 usar XGBoost?\n- Nuestro primero modelo \ud83e\uddf6\ud83d\udc08\n    - Instalaci\u00f3n (aunque este stand-up no es un tutorial)\n    - Descripci\u00f3n del problema\n    - Carga de datos\n    - Entrenamiento del modelo\n    - Generaci\u00f3n de predicciones ($\\hat{Y}$)\n- Visualizaci\u00f3n de \u00e1rboles de decisi\u00f3n e imporancia de features\n    - Feature Importance plot\n    - Tree Graph\n- Preparaci\u00f3n de datos para GB\n- (si da tiempo: Evaluaci\u00f3n de Modelos)\n\n# Decision Trees\n\n- [A visual introduction to machine learning](http://www.r2d3.us/visual-intro-to-machine-learning-part-1/)\n- [The Mechanics of Machine Learning: How Machine Learning Works](https://mlbook.explained.ai/intro.html)\n\n# Gradient Boosting\n\nGB es una de las t\u00e9cnicas m\u00e1s populares en ML para ganar competencias de Kaggle sobre datos estructurados (y con el feature engineering adecuado), entrenar sobre datasets en los que no tenemos _business expertise_ para descubrir variables con poder predictivo o solucionar casi cualquier problema de aprendiza supervisado y ganar dinero r\u00e1pido.\n\n## Origen de _Boosting_\nLa idea fue articulada por Michael Kearns sobre un clasificador d\u00e9bil (weaker learner\\*) que puede convertirse en eficiente sobre el tiempo:\n\n> ... an efficient algorithm for converting relatively poor hypotheses into very good hypotheses \u2014 Thoughts on Hypothesis Boosting, 1988.\n \n\nHypothesis boosting was the idea of filtering observations, \nleaving those observations that the weak learner can handle\nand focusing on developing new weak learns to handle the remaining difficult observations.\n\n## AdaBoosting\n\nAdaBoost y otros algoritmos relacionados son propuestos como un marco de aprendizaje estad\u00edstico por Leo Breiman como ARCing Algorithms:\n\n> Arcing is an acronym for Adaptive Reweighting and Combining. Each step in an arcing algorithm consists of a weighted minimization followed by a recomputation of [the classifiers] and [weighted input].  \u2014 Prediction Games and Arching Algorithms, 1999\n\n## AdaBoosting\n\nDespu\u00e9s, es extendido en 2001 por Jerome H. Friedman y llamado _Gradient Boosting Machine_ \n\n\nSe establece el GB como un problema de optimizaci\u00f3n donde la funci\u00f3n objetivo es minimizar la p\u00e9rdida del modelo al agregar clasificadores d\u00e9biles mediante gradient descent/descenso de gradiente. Este algoritmo describe un modelo aditivo por etapas:\n\nUn nuevo clasificador d\u00e9bil es agregado a la vez a una estructura de clasificadores que no se modifican.\n\n## AdaBoosting\n\n\nFigura: Wang, Zhuo & Zhang, Jintao & Verma, Naveen. (2015). Realizing Low-Energy Classification Systems by Implementing Matrix Multiplication Directly Within an ADC. IEEE Transactions on Biomedical Circuits and Systems. 9. 1-1. 10.1109/TBCAS.2015.2500101. \n\n## Entonces c\u00f3mo funciona Gradient Boosting?\n\nSe involucran tres elementos:\n\n- Una funci\u00f3n de p\u00e9rdida a ser optimizada\n- Un clasificador d\u00e9bil que hace prediccciones\n- Un modelo aditivo que incrementa sus clasificadores para minimizar la funci\u00f3n de p\u00e9rdida\n\n### Gradient Boosting\n\n- **Weak learner**: es un clasificador que sin importar la distribuci\u00f3n del dataset de entrenamiento, siempre ser\u00e1 mejor que una elecci\u00f3n al azar, cuando intenta etiquetar ($\\hat{Y}$) los datos de una observaci\u00f3n ($X$).\n\n\n### Gradient Boosting\n\n\n- Regularization: Mide la complejidad del modelo\n- Training Loss: Mide que tan bien se ajusta nuestro modelo a los datos \n\n\n### Gradient Boosting\n\n- **Training loss functions**: M\u00e9todos para la evaluaci\u00f3n de que tan bien un algoritmo en particular est\u00e1 modelando las observaciones dadas. \nSi la predicci\u00f3n $\\hat{Y}$ se desv\u00eda demasiado del resultado actual ${Y}$ la funci\u00f3n de p\u00e9rdida otorgar\u00e1 un valor muy alto. Gradualmente, con la ayuda de una funci\u00f3n de optimizaci\u00f3n, la funci\u00f3n de p\u00e9rdida aprende a reducir el error en la predicci\u00f3n) \n\n\n### Gradient Boosting\n\n\n- *Modelo Aditivo*: Es un modelo donde se a\u00f1aden \u00e1rboles a la vez, y los existentes no se modifican. Se usa gradient descent para minimizar la p\u00e9rdida cuando se agrega un nuevo arbol. \n\n> One way to produce a weighted combination of classifiers which optimizes [the cost] is by gradient descent in function space. \u2014 Boosting Algorithms as Gradient Descent in Function Space, 1999. Llew Mason\n\nNormalmente se usa el descenso de gradiente para minimizar par\u00e1metros, p. ej. el coeficiente un una ecuaci\u00f3n de regresi\u00f3n o los pesos de una NN. Despu\u00e9s de calcular el error o la p\u00e9rdida, los pesos internos se actualizan para minimizar ese error.\nEn vez de parametros, los clasificadores d\u00e9biles (decision trees). Despu\u00e9s de calcular la p\u00e9rdidad, para calcular el descenso de gradiente, debemos a\u00f1adir un arbol para minimizar la p\u00e9rdida (seguir el gradiente). Este approach es conocido como functional gradient descent.\n\n## Mejoras al Gradient Boosting\n\nDado que GB es un algoritmo agresivo, puede sobre-entrenar en el dataset. Usando funciones de regularizaci\u00f3n que penalizen a la implementaci\u00f3n del algoritmo:\n\n- Constantes para \u00e1rboles\n- Contracci\u00f3n (shrinkage/learning rate)\n- Random Sampling (Stochastic GB)\n- Penalized Gradient Boosting (Regularized Gradient Boosting:  \ud835\udc3f1 / \ud835\udc3f2 regularization of weights )\n\nTambi\u00e9n hay dos t\u00e9cnicas de regularizaci\u00f3n adicionales para evitar el overfitting. El primero es la contracci\u00f3n (shrinkage), que agrega un factor de escala a los nuevos pesos despu\u00e9s de cada paso de refuerzo. Esto evita que algunos \u00e1rboles individuales dominen el conjunto, dejando espacio para mejorar. La segunda t\u00e9cnica es el submuestreo de caracter\u00edsticas/features (feature subsampling), donde se muestrea una fracci\u00f3n de las observaciones en cada paso, para aumentar la variedad de \u00e1rboles construidos. El submuestreo de caracter\u00edsticas tambi\u00e9n aumenta la velocidad de c\u00e1lculo, permitiendo que XGBoost se escale de manera eficiente.\n\n\n\\begin{equation}\\label{eq:loss}\n\\begin{split}\n\\mathcal{L}(\\phi) =& \\sum_{i} l( \\hat{y}_i, y_i ) + \\sum_{k}\\Omega( f_{k} ) \\\\\n \\mbox{ donde }& \\Omega(f) = \\gamma T + \\frac{1}{2} \\lambda \\|w\\|^2\n \\end{split}\n\\end{equation}\n\n\nL1 regularization of weights. L2 regularization of weights.\nThe additional regularization term helps to smooth the final learnt weights to avoid over-fitting. Intuitively, the regularized objective will tend to select a model employing simple and predictive functions.\n\n# Tree Boosting\n\n## Regularized learning objective\n\nComo en la mayor\u00eda de modelos, minimizar la p\u00e9rdida (la diferencia entre la predicci\u00f3n $\\hat{Y}$ y la etiqueta ${Y}$ ) es la meta principal y queremos que el modelo sea lo m\u00e1s exacto posible. Tambi\u00e9n es importante agregar un t\u00e9rmino de regularizaci\u00f3n ($\\Omega$) para evitar el Overfitting/sobre-entrenamiento.  Expresamos la funci\u00f3n de objetivo de la siguiente forma\n\n$$\n\\begin{equation}\\label{eq:loss}\n\\begin{split}\n\\mathcal{L}(\\phi) =& \\sum_{i} l( \\hat{y}_i, y_i ) + \\sum_{k}\\Omega( f_{k} ) \\\\\n \\end{split}\n\\end{equation}\n$$\n\n\n\n\n\nHere $l$ is a differentiable convex loss function that measures the difference between the prediction $\\hat{y}_i$ and the target $y_i$. The second term $\\Omega$ penalizes the complexity of the model (i.e., the regression tree functions).\nThe additional regularization term helps to smooth the final learnt weights to avoid over-fitting.\nIntuitively, the regularized objective will tend to select a model employing simple and predictive functions.\nA similar regularization technique has been used in Regularized greedy forest~(RGF)~ model.\nOur objective and the corresponding learning algorithm is simpler than RGF and easier to parallelize.\nWhen the regularization parameter is set to zero, the objective falls back to the traditional gradient tree boosting.\n\n\nTambi\u00e9n hay dos t\u00e9cnicas de regularizaci\u00f3n adicionales para evitar el sobreajuste. El primero es la contracci\u00f3n (shrinkage), que agrega un factor de escala a los nuevos pesos despu\u00e9s de cada paso de refuerzo. Esto evita que algunos \u00e1rboles individuales dominen el conjunto, dejando espacio para mejorar. La segunda t\u00e9cnica es el submuestreo de caracter\u00edsticas/features (feature subsampling), donde se muestrea una fracci\u00f3n de las observaciones en cada paso, para aumentar la variedad de \u00e1rboles construidos. El submuestreo de caracter\u00edsticas tambi\u00e9n aumenta la velocidad de c\u00e1lculo, permitiendo que XGBoost se escale de manera eficiente.\n\n\n\\begin{equation}\\label{eq:loss}\n\\begin{split}\n\\mathcal{L}(\\phi) =& \\sum_{i} l( \\hat{y}_i, y_i ) + \\sum_{k}\\Omega( f_{k} ) \\\\\n \\mbox{ donde }& \\Omega(f) = \\gamma T + \\frac{1}{2} \\lambda \\|w\\|^2\n \\end{split}\n\\end{equation}\n\n\n# Tree Boosting\n\n## Gradient tree boosting\n\nCuando entrenamos un modelo, es com\u00fan optimizarlo tomando el gradiente. Sin embargo, esto es dif\u00edcil de realizar en un conjunto de \u00e1rboles. En su lugar, usamos una estrategia aditiva y agregamos un \u00e1rbol nuevo a la vez, de modo que cada \u00e1rbol que agreguemos optimice el objetivo. Esto nos da una funci\u00f3n de puntuaci\u00f3n que podemos usar para evaluar la calidad de una estructura de \u00e1rbol.\n\n\n\nEn pocas palabras, $g_i$ y $h_i$ se ordenan en sus hojas apropiadas, se suman y luego se punt\u00faan.\n\n# Tree Boosting\n\nAhora que tenemos un m\u00e9todo para evaluar la calidad de la estructura de \u00e1rbol, necesitamos aprender la estructura del \u00e1rbol. Es imposible enumerar/completar esto en un solo paso para todos los \u00e1rboles posibles, por lo que se optimiza un nivel de \u00e1rbol a la vez. Comenzando con una divisi\u00f3n en una hoja, calculamos la ganancia, que viene dada por:\n\n\\begin{equation}\\label{eq:gain}\n      \\mathcal{L}_{split} =\\frac{1}{2} \\left[\\frac{(\\sum_{i\\in I_L} g_i)^2}{\\sum_{i\\in I_L} h_i + \\lambda}+\\frac{(\\sum_{i\\in I_R} g_i)^2}{\\sum_{i\\in I_R} h_i + \\lambda} - \\frac{(\\sum_{i\\in I} g_i)^2}{\\sum_{i\\in I} h_i + \\lambda}\\right] - \\gamma\n\\end{equation}\n\n\n---\nDonde $I_j=\\{i|q(x_i)=j\\}$ es el conjunto de instancias de la hoja  $j$\n\n# XGBoost: eXtreme Gradient Boosting\n\nXGBoost es una implementaci\u00f3n **Open Source** de Gradient Boosting Machines/Gradient Boosted Decision Trees creada por Tianqi Chen, en co-autor\u00eda con Carlos Guestrin, (del grupo DMLC https://dmlc.github.io/people.html, tambi\u00e9n creadores de MXNet para Deep Learning). Siendo pensada desde el origen para entrenar con velocidad de c\u00f3mputo y performance.\n\nEscrita en C++, est\u00e1 disponible para los SO m\u00e1s populares (Windows, OS X, Linux) con las siguientes interfaces:\n\n- Command Line Inferface (CLI)\n- C++\n- Python\n- R\n- Julia\n- JVM: Java (Hadoop), Scala (Spark)\n\n## XGBoost Features\n\n## Model Features\nSoporta tres maneras (implementaciones de algoritmos) de Gradient Boosting:\n\n- Gradient Boosting/Gradient Boosting Machine (Learning Rate)\n- Stochastic Gradient Boosting (sub-sampling: row & column)\n- Regularized Gradient Boosting ($L^1$, $L^2$)\n\n\n## System Features\nUso de algoritmos y estructuras de datos optimizados para exprimir nuestro hardware:\n\n- Paralelizaci\u00f3n: Uso de todos los cores durante entrenamiento (construcci\u00f3n de \u00e1rboles)\n- C\u00f3mputo Distribuido (HPC: OpenMP, Spark, Yarn, CUDA/NCCL, Dask, Dask+Kubernetes): Para entrenamiento de modelos en clusters de c\u00f3mputo\n- Out-of-Core Computing: Para datasets que no caben en memoria RAM\n\n\n## Algorithm Features\n\n- Manejo autom\u00e1tico de valores faltantes (Sparsity-aware Split Finding Algorithm)\n- Continued Training: Entrenamiento incremental sobre modelos previos\n\n\n\n## Por qu\u00e9 usar XGBoost?\n\n\nEn resumen, usamos XGBoost por las siguientes razones:\n- F\u00e1cil de usar e instalar\n- Eficiencia\n    - R\u00e1pido\n    - Parelizalizaci\u00f3n sin dolor en una sola computadora o en cluster \\*\n- Exactitud\n    - Buenos resultados para la mayor\u00eda de datasets (Pruning, Gradient Optimization)\n- Personalizaci\u00f3n:\n    - Param\u00e9tros\n    - Cambios en la funci\u00f3n Objetivo y evaluaci\u00f3n\n    \n    \n    \n    \n    \n----\n\\* Sabemos lo que has llorado al implementar en tu lenguaje favorito:\n\n- Concurrency (Threading, Async IO/Cooperative Multitasking)\n- Parallelism (Multiprocessing).\n\n\n### Velocidad de entrenamiento (I)\n\n\n#### [Benchmarking Random Forest Implementations, Szilard Pafka. 2015](http://datascience.la/benchmarking-random-forest-implementations/)\n\n> In our experiments, random forests with 500 trees have been trained in each tool with default hyper-parameter values. The training times and AUC as a function of the dataset size are plotted in the figures below (with more details available on Github).\n------\n\n\n\n> I also tried xgboost, a popular library for boosting which is capable to build random forests as well. It is fast, memory efficient and of high accuracy. Note the different shapes of the AUC and runtime vs dataset sizes for H2O and xgboost, however.\n\n-----\n\n\n\n\n\n### Velocidad de entrenamiento (II)\n\n\n#### [Xgboost: A scalable tree boosting system. T Chen, C Guestrin](https://arxiv.org/abs/1603.02754)\n\n> Figure 12: Comparison of different distributed systems on 32 EC2 nodes for 10 iterations on different subset of criteo data. XGBoost runs more 10x than spark per iteration and 2.2x as H2O\u2019s optimized version (However, H2O is slow in loading the data, getting worse end-to-end time). Note that spark suffers from drastic slow down when running out of memory. XGBoost runs faster and scales smoothly to the full 1.7 billion examples with given resources by utilizing out-of-core computation.\n------\n\n\n\n# Nuestro primero modelo \ud83e\uddf6\ud83d\udc08\n    - Instalaci\u00f3n (aunque este stand-up no es un tutorial)\n    - Descripci\u00f3n del problema\n    - Carga de datos\n    - Entrenamiento del modelo\n    - Generaci\u00f3n de predicciones\n\n\n## Instalaci\u00f3n:\n\n### Anaconda:\n`$ conda install -c conda-forge xgboost`\n\n### PIP:\n`$ pip3 install xgboost`\n\n#### Para compilaci\u00f3n (GCC / Mingw) y soporte de GPU (Linux): https://xgboost.readthedocs.io/en/latest/build.html\n\n## Instalaci\u00f3n (de complementos):\n\n- NumPy\n- SciPy\n- Pandas\n- Scikit-Learn\n- Matplotlib\n- Graphviz (`$ pip install graphviz` / `$ conda install graphviz && conda install python-graphviz`)\n\n## Descripci\u00f3n del problema\n\n### Usando Aprendizaje Supervisado (clasificaci\u00f3n) y el dataset Digits de NIST, entrenaremos un modelo que reconozca digitos escritos a mano.\n\n- 5620 registros por 64 atributos ( cada registro representa una imagen de 8x8 pixeles en el rango de 0 a 16\n- 10 clases \u00fanicas\n\n\n# The process of building a ML product\n\n\n\n# Typical Machine Learning Workflow (I)\n\n\n\n# Typical Machine Learning Workflow (II)\n\n\n\n### Carga de datos (y paquetes)\n\n\n```python\n# Numeric\nimport numpy as np\n\n# DataFrame Support\nimport pandas as pd\n\n#ML Algos\nfrom xgboost import XGBClassifier\n\n# ML toolkit\n\nfrom sklearn.model_selection import train_test_split, KFold, GridSearchCV\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error, median_absolute_error, r2_score\nfrom sklearn.metrics import confusion_matrix\n\n# Feature Viz\nfrom xgboost import to_graphviz, plot_tree, plot_importance\n\n# Graphing\nimport matplotlib.pyplot as plt\n%matplotlib nbagg\n```\n\n\n```python\n# The digits dataset\ndigits = datasets.load_digits()\n\n# To apply a classifier on this data, we need to flatten the image, to\n# turn the data in a (samples, feature) matrix:\nn_samples = len(digits.images)\ndata = digits.images.reshape((n_samples, -1))\n```\n\n\n```python\n# split data into train and test sets\nseed = 42\ntest_size = 0.33\n# Split data into train and test subsets\nX_train, X_test, y_train, y_test = train_test_split(\n    data, digits.target, test_size=0.5, shuffle=False, random_state=seed)\n```\n\n# Entrenamiento del modelo (con un solo core)\n\n\n```python\n# Create a classifier: XGBoostClassifier!\nclassifier = XGBClassifier(nthread=1)\n```\n\n\n```python\n# We learn the digits on the 33% of the digits\nclassifier.fit(X_train, y_train)\n```\n\n\n\n\n    XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=1,\n                  colsample_bynode=1, colsample_bytree=1, gamma=0,\n                  learning_rate=0.1, max_delta_step=0, max_depth=3,\n                  min_child_weight=1, missing=None, n_estimators=100, n_jobs=-1,\n                  nthread=None, objective='multi:softprob', random_state=0,\n                  reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None,\n                  silent=None, subsample=1, verbosity=1)\n\n\n\n# Entrenamiento del modelo (con un todos los cores disponibles)\n\n\n```python\n# Create a classifier: XGBoostClassifier!\nclassifier = XGBClassifier(n_jobs=-1)\n```\n\n\n```python\n# We learn the digits on the 33% of the digits\n%time classifier.fit(X_train, y_train)\n```\n\n    CPU times: user 3.12 s, sys: 13.9 ms, total: 3.14 s\n    Wall time: 3.14 s\n\n\n\n\n\n    XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=1,\n                  colsample_bynode=1, colsample_bytree=1, gamma=0,\n                  learning_rate=0.1, max_delta_step=0, max_depth=3,\n                  min_child_weight=1, missing=None, n_estimators=100, n_jobs=-1,\n                  nthread=None, objective='multi:softprob', random_state=0,\n                  reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None,\n                  silent=None, subsample=1, verbosity=1)\n\n\n\n## Generaci\u00f3n de predicciones ($\\hat{Y}$)\n\n\n```python\n# Now predict the value of the digit on the rest:\npredicted = classifier.predict(X_test)\n```\n\n\n```python\n_, axes = plt.subplots(2, 4)\nimages_and_labels = list(zip(digits.images, digits.target))\nfor ax, (image, label) in zip(axes[0, :], images_and_labels[:4]):\n    ax.set_axis_off()\n    ax.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n    ax.set_title('Training: %i' % label)\n\nimages_and_predictions = list(zip(digits.images[n_samples // 2:], predicted))\nfor ax, (image, prediction) in zip(axes[1, :], images_and_predictions[:4]):\n    ax.set_axis_off()\n    ax.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n    ax.set_title('Prediction: %i' % prediction)\n\nplt.show()\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n\n```python\nprint(\"Classification report for classifier %s:\\n%s\\n\"\n      % (classifier, metrics.classification_report(y_test, predicted)))\ndisp = metrics.plot_confusion_matrix(classifier, X_test, y_test)\ndisp.figure_.suptitle(\"Confusion Matrix\")\nprint(\"Confusion matrix:\\n%s\" % disp.confusion_matrix)\n```\n\n    Classification report for classifier XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=1,\n                  colsample_bynode=1, colsample_bytree=1, gamma=0,\n                  learning_rate=0.1, max_delta_step=0, max_depth=3,\n                  min_child_weight=1, missing=None, n_estimators=100, n_jobs=-1,\n                  nthread=None, objective='multi:softprob', random_state=0,\n                  reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None,\n                  silent=None, subsample=1, verbosity=1):\n                  precision    recall  f1-score   support\n    \n               0       0.93      0.99      0.96        88\n               1       0.86      0.82      0.84        91\n               2       0.96      0.90      0.93        86\n               3       0.86      0.82      0.84        91\n               4       0.96      0.87      0.91        92\n               5       0.89      0.91      0.90        91\n               6       0.93      0.95      0.94        91\n               7       0.98      0.93      0.95        89\n               8       0.86      0.88      0.87        88\n               9       0.80      0.93      0.86        92\n    \n        accuracy                           0.90       899\n       macro avg       0.90      0.90      0.90       899\n    weighted avg       0.90      0.90      0.90       899\n    \n    \n\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n    Confusion matrix:\n    [[87  0  0  0  0  0  0  0  1  0]\n     [ 0 75  0  3  2  0  0  0  1 10]\n     [ 1  0 77  7  0  0  0  0  0  1]\n     [ 0  3  0 75  0  3  0  2  8  0]\n     [ 4  0  0  0 80  0  4  0  0  4]\n     [ 0  1  0  0  0 83  2  0  0  5]\n     [ 0  2  2  1  0  0 86  0  0  0]\n     [ 0  0  1  0  1  3  0 83  1  0]\n     [ 0  6  0  1  0  2  0  0 77  2]\n     [ 2  0  0  0  0  2  0  0  2 86]]\n\n\n## Visualizaci\u00f3n de \u00e1rboles de decisi\u00f3n e imporancia de features\n    - Feature Importance plot\n    - Tree Graph\n\n\n```python\n# Modelo\n# 284,807 registros x  31 columnas\ndataset = pd.read_csv('creditcard.csv')\ndataset.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Time</th>\n      <th>V1</th>\n      <th>V2</th>\n      <th>V3</th>\n      <th>V4</th>\n      <th>V5</th>\n      <th>V6</th>\n      <th>V7</th>\n      <th>V8</th>\n      <th>V9</th>\n      <th>V10</th>\n      <th>V11</th>\n      <th>V12</th>\n      <th>V13</th>\n      <th>V14</th>\n      <th>V15</th>\n      <th>V16</th>\n      <th>V17</th>\n      <th>V18</th>\n      <th>V19</th>\n      <th>V20</th>\n      <th>V21</th>\n      <th>V22</th>\n      <th>V23</th>\n      <th>V24</th>\n      <th>V25</th>\n      <th>V26</th>\n      <th>V27</th>\n      <th>V28</th>\n      <th>Amount</th>\n      <th>Class</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.0</td>\n      <td>-1.359807</td>\n      <td>-0.072781</td>\n      <td>2.536347</td>\n      <td>1.378155</td>\n      <td>-0.338321</td>\n      <td>0.462388</td>\n      <td>0.239599</td>\n      <td>0.098698</td>\n      <td>0.363787</td>\n      <td>0.090794</td>\n      <td>-0.551600</td>\n      <td>-0.617801</td>\n      <td>-0.991390</td>\n      <td>-0.311169</td>\n      <td>1.468177</td>\n      <td>-0.470401</td>\n      <td>0.207971</td>\n      <td>0.025791</td>\n      <td>0.403993</td>\n      <td>0.251412</td>\n      <td>-0.018307</td>\n      <td>0.277838</td>\n      <td>-0.110474</td>\n      <td>0.066928</td>\n      <td>0.128539</td>\n      <td>-0.189115</td>\n      <td>0.133558</td>\n      <td>-0.021053</td>\n      <td>149.62</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.0</td>\n      <td>1.191857</td>\n      <td>0.266151</td>\n      <td>0.166480</td>\n      <td>0.448154</td>\n      <td>0.060018</td>\n      <td>-0.082361</td>\n      <td>-0.078803</td>\n      <td>0.085102</td>\n      <td>-0.255425</td>\n      <td>-0.166974</td>\n      <td>1.612727</td>\n      <td>1.065235</td>\n      <td>0.489095</td>\n      <td>-0.143772</td>\n      <td>0.635558</td>\n      <td>0.463917</td>\n      <td>-0.114805</td>\n      <td>-0.183361</td>\n      <td>-0.145783</td>\n      <td>-0.069083</td>\n      <td>-0.225775</td>\n      <td>-0.638672</td>\n      <td>0.101288</td>\n      <td>-0.339846</td>\n      <td>0.167170</td>\n      <td>0.125895</td>\n      <td>-0.008983</td>\n      <td>0.014724</td>\n      <td>2.69</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1.0</td>\n      <td>-1.358354</td>\n      <td>-1.340163</td>\n      <td>1.773209</td>\n      <td>0.379780</td>\n      <td>-0.503198</td>\n      <td>1.800499</td>\n      <td>0.791461</td>\n      <td>0.247676</td>\n      <td>-1.514654</td>\n      <td>0.207643</td>\n      <td>0.624501</td>\n      <td>0.066084</td>\n      <td>0.717293</td>\n      <td>-0.165946</td>\n      <td>2.345865</td>\n      <td>-2.890083</td>\n      <td>1.109969</td>\n      <td>-0.121359</td>\n      <td>-2.261857</td>\n      <td>0.524980</td>\n      <td>0.247998</td>\n      <td>0.771679</td>\n      <td>0.909412</td>\n      <td>-0.689281</td>\n      <td>-0.327642</td>\n      <td>-0.139097</td>\n      <td>-0.055353</td>\n      <td>-0.059752</td>\n      <td>378.66</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1.0</td>\n      <td>-0.966272</td>\n      <td>-0.185226</td>\n      <td>1.792993</td>\n      <td>-0.863291</td>\n      <td>-0.010309</td>\n      <td>1.247203</td>\n      <td>0.237609</td>\n      <td>0.377436</td>\n      <td>-1.387024</td>\n      <td>-0.054952</td>\n      <td>-0.226487</td>\n      <td>0.178228</td>\n      <td>0.507757</td>\n      <td>-0.287924</td>\n      <td>-0.631418</td>\n      <td>-1.059647</td>\n      <td>-0.684093</td>\n      <td>1.965775</td>\n      <td>-1.232622</td>\n      <td>-0.208038</td>\n      <td>-0.108300</td>\n      <td>0.005274</td>\n      <td>-0.190321</td>\n      <td>-1.175575</td>\n      <td>0.647376</td>\n      <td>-0.221929</td>\n      <td>0.062723</td>\n      <td>0.061458</td>\n      <td>123.50</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>2.0</td>\n      <td>-1.158233</td>\n      <td>0.877737</td>\n      <td>1.548718</td>\n      <td>0.403034</td>\n      <td>-0.407193</td>\n      <td>0.095921</td>\n      <td>0.592941</td>\n      <td>-0.270533</td>\n      <td>0.817739</td>\n      <td>0.753074</td>\n      <td>-0.822843</td>\n      <td>0.538196</td>\n      <td>1.345852</td>\n      <td>-1.119670</td>\n      <td>0.175121</td>\n      <td>-0.451449</td>\n      <td>-0.237033</td>\n      <td>-0.038195</td>\n      <td>0.803487</td>\n      <td>0.408542</td>\n      <td>-0.009431</td>\n      <td>0.798278</td>\n      <td>-0.137458</td>\n      <td>0.141267</td>\n      <td>-0.206010</td>\n      <td>0.502292</td>\n      <td>0.219422</td>\n      <td>0.215153</td>\n      <td>69.99</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# Create X and Y\nX = dataset.values[:,0:29]\n\nY = dataset.values[:,30]\n\n# split data into train and test sets\nseed = 42\ntest_size = 0.33\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=test_size, random_state=seed)\n# fit model with training data\nmodel = XGBClassifier(n_jobs=-1)\nmodel.fit(X_train, y_train)\n```\n\n\n\n\n    XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=1,\n                  colsample_bynode=1, colsample_bytree=1, gamma=0,\n                  learning_rate=0.1, max_delta_step=0, max_depth=3,\n                  min_child_weight=1, missing=None, n_estimators=100, n_jobs=-1,\n                  nthread=None, objective='binary:logistic', random_state=0,\n                  reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None,\n                  silent=None, subsample=1, verbosity=1)\n\n\n\n\n```python\n# make predictions for test data\ny_pred = model.predict(X_test)\npredictions = [round(value) for value in y_pred]\n# evaluate predictions\n\nfrom sklearn.metrics import roc_auc_score, accuracy_score\n\n\naccuracy = accuracy_score(y_test, predictions)\nprint(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n```\n\n    Accuracy: 99.96%\n\n\n\n```python\nroc_auc_score(y_test, y_pred)\n```\n\n\n\n\n    0.9093480181681094\n\n\n\n### Feature importance Plot\n\n\n```python\nplot_importance(model)\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n\n\n\n    <matplotlib.axes._subplots.AxesSubplot at 0x1a2b6a42e8>\n\n\n\n\n```python\nlist(enumerate(dataset.keys()))\n```\n\n\n\n\n    [(0, 'Time'),\n     (1, 'V1'),\n     (2, 'V2'),\n     (3, 'V3'),\n     (4, 'V4'),\n     (5, 'V5'),\n     (6, 'V6'),\n     (7, 'V7'),\n     (8, 'V8'),\n     (9, 'V9'),\n     (10, 'V10'),\n     (11, 'V11'),\n     (12, 'V12'),\n     (13, 'V13'),\n     (14, 'V14'),\n     (15, 'V15'),\n     (16, 'V16'),\n     (17, 'V17'),\n     (18, 'V18'),\n     (19, 'V19'),\n     (20, 'V20'),\n     (21, 'V21'),\n     (22, 'V22'),\n     (23, 'V23'),\n     (24, 'V24'),\n     (25, 'V25'),\n     (26, 'V26'),\n     (27, 'V27'),\n     (28, 'V28'),\n     (29, 'Amount'),\n     (30, 'Class')]\n\n\n\n### Tree Graph\n\n\n```python\nplot_tree(model)\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n\n\n\n    <matplotlib.axes._subplots.AxesSubplot at 0x1a26c3b7f0>\n\n\n\n# Preparaci\u00f3n de datos para GB\n\n\nXGBoost solo considera como entrada valores n\u00famericos, lo que significa que debemos \"codificar\" nuestro dataset  mediante:\n\n- Label Encoding (LabelEncoder)\n- OneHot Encoding (OneHotEncoder)\n- Feature Scaling (StandardScaler \n\n\n```python\n# multiclass classification with Label Encoding\nfrom pandas import read_csv\nfrom xgboost import XGBClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.datasets import load_iris\n# load data\niris = pd.read_csv('iris.csv')\n# split data into X and y\nX = iris.values[:,0:4]\nY = iris.values[:,4]\n# encode string class values as integers\nlabel_encoder = LabelEncoder()\nlabel_encoder = label_encoder.fit(Y)\nlabel_encoded_y = label_encoder.transform(Y)\nseed = 7\ntest_size = 0.33\nX_train, X_test, y_train, y_test = train_test_split(X, label_encoded_y, test_size=test_size, random_state=seed)\n# fit model on training data\nmodel = XGBClassifier() \nmodel.fit(X_train, y_train) \nprint(model)\n```\n\n    XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=1,\n                  colsample_bynode=1, colsample_bytree=1, gamma=0,\n                  learning_rate=0.1, max_delta_step=0, max_depth=3,\n                  min_child_weight=1, missing=None, n_estimators=100, n_jobs=1,\n                  nthread=None, objective='multi:softprob', random_state=0,\n                  reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None,\n                  silent=None, subsample=1, verbosity=1)\n\n\n\n```python\n# make predictions for test data \npredictions = model.predict(X_test) \n# evaluate predictions\naccuracy = accuracy_score(y_test, predictions) \nprint(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n```\n\n    Accuracy: 92.00%\n\n\n\n```python\nY\n```\n\n\n\n\n    array(['Iris-setosa', 'Iris-setosa', 'Iris-setosa', 'Iris-setosa',\n           'Iris-setosa', 'Iris-setosa', 'Iris-setosa', 'Iris-setosa',\n           'Iris-setosa', 'Iris-setosa', 'Iris-setosa', 'Iris-setosa',\n           'Iris-setosa', 'Iris-setosa', 'Iris-setosa', 'Iris-setosa',\n           'Iris-setosa', 'Iris-setosa', 'Iris-setosa', 'Iris-setosa',\n           'Iris-setosa', 'Iris-setosa', 'Iris-setosa', 'Iris-setosa',\n           'Iris-setosa', 'Iris-setosa', 'Iris-setosa', 'Iris-setosa',\n           'Iris-setosa', 'Iris-setosa', 'Iris-setosa', 'Iris-setosa',\n           'Iris-setosa', 'Iris-setosa', 'Iris-setosa', 'Iris-setosa',\n           'Iris-setosa', 'Iris-setosa', 'Iris-setosa', 'Iris-setosa',\n           'Iris-setosa', 'Iris-setosa', 'Iris-setosa', 'Iris-setosa',\n           'Iris-setosa', 'Iris-setosa', 'Iris-setosa', 'Iris-setosa',\n           'Iris-setosa', 'Iris-versicolor', 'Iris-versicolor',\n           'Iris-versicolor', 'Iris-versicolor', 'Iris-versicolor',\n           'Iris-versicolor', 'Iris-versicolor', 'Iris-versicolor',\n           'Iris-versicolor', 'Iris-versicolor', 'Iris-versicolor',\n           'Iris-versicolor', 'Iris-versicolor', 'Iris-versicolor',\n           'Iris-versicolor', 'Iris-versicolor', 'Iris-versicolor',\n           'Iris-versicolor', 'Iris-versicolor', 'Iris-versicolor',\n           'Iris-versicolor', 'Iris-versicolor', 'Iris-versicolor',\n           'Iris-versicolor', 'Iris-versicolor', 'Iris-versicolor',\n           'Iris-versicolor', 'Iris-versicolor', 'Iris-versicolor',\n           'Iris-versicolor', 'Iris-versicolor', 'Iris-versicolor',\n           'Iris-versicolor', 'Iris-versicolor', 'Iris-versicolor',\n           'Iris-versicolor', 'Iris-versicolor', 'Iris-versicolor',\n           'Iris-versicolor', 'Iris-versicolor', 'Iris-versicolor',\n           'Iris-versicolor', 'Iris-versicolor', 'Iris-versicolor',\n           'Iris-versicolor', 'Iris-versicolor', 'Iris-versicolor',\n           'Iris-versicolor', 'Iris-versicolor', 'Iris-versicolor',\n           'Iris-virginica', 'Iris-virginica', 'Iris-virginica',\n           'Iris-virginica', 'Iris-virginica', 'Iris-virginica',\n           'Iris-virginica', 'Iris-virginica', 'Iris-virginica',\n           'Iris-virginica', 'Iris-virginica', 'Iris-virginica',\n           'Iris-virginica', 'Iris-virginica', 'Iris-virginica',\n           'Iris-virginica', 'Iris-virginica', 'Iris-virginica',\n           'Iris-virginica', 'Iris-virginica', 'Iris-virginica',\n           'Iris-virginica', 'Iris-virginica', 'Iris-virginica',\n           'Iris-virginica', 'Iris-virginica', 'Iris-virginica',\n           'Iris-virginica', 'Iris-virginica', 'Iris-virginica',\n           'Iris-virginica', 'Iris-virginica', 'Iris-virginica',\n           'Iris-virginica', 'Iris-virginica', 'Iris-virginica',\n           'Iris-virginica', 'Iris-virginica', 'Iris-virginica',\n           'Iris-virginica', 'Iris-virginica', 'Iris-virginica',\n           'Iris-virginica', 'Iris-virginica', 'Iris-virginica',\n           'Iris-virginica', 'Iris-virginica', 'Iris-virginica',\n           'Iris-virginica', 'Iris-virginica'], dtype=object)\n\n\n\n\n```python\nlabel_encoded_y\n```\n\n\n\n\n    array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n           0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n           0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n           2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n           2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])\n\n\n\n# Evaluaci\u00f3n de modelos\n\n\n```python\nprint(\"Parameter optimization\")\n\nimport numpy as np\n\n# Mean absolute percentage error\ndef mean_absolute_percentage_error(estimator, X, y):\n    y_pred = estimator.predict(X)\n    y_true = y\n    return np.mean(np.abs((y_true - y_pred) / y_true))\n\nestimators = [i for i in range(0, 5000, 500)]\ngammas = [i/10 for i in range(0, 21, 1)]\nmax_depths=[6]\n\n\nscorer = mean_absolute_percentage_error\nxgb_grid_params = dict(n_estimators = estimators, gamma = gammas, max_depth=max_depths)\nxgb = XGBClassifier()\n\nxgb\n```\n\n    Parameter optimization\n\n\n\n\n\n    XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=1,\n                  colsample_bynode=1, colsample_bytree=1, gamma=0,\n                  learning_rate=0.1, max_delta_step=0, max_depth=3,\n                  min_child_weight=1, missing=None, n_estimators=100, n_jobs=1,\n                  nthread=None, objective='binary:logistic', random_state=0,\n                  reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None,\n                  silent=None, subsample=1, verbosity=1)\n\n\n\n\n```python\nclf = GridSearchCV(xgb,\n                   xgb_grid_params, \n                   cv = 10, \n                   scoring=scorer, \n                   n_jobs = -1)\n\n\nclf\n```\n\n\n\n\n    GridSearchCV(cv=10, error_score=nan,\n                 estimator=XGBClassifier(base_score=0.5, booster='gbtree',\n                                         colsample_bylevel=1, colsample_bynode=1,\n                                         colsample_bytree=1, gamma=0,\n                                         learning_rate=0.1, max_delta_step=0,\n                                         max_depth=3, min_child_weight=1,\n                                         missing=None, n_estimators=100, n_jobs=1,\n                                         nthread=None, objective='binary:logistic',\n                                         random_state=0, reg_alpha=0, reg_lambda=1,\n                                         scale_p...\n                                         subsample=1, verbosity=1),\n                 iid='deprecated', n_jobs=-1,\n                 param_grid={'gamma': [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8,\n                                       0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7,\n                                       1.8, 1.9, 2.0],\n                             'max_depth': [6],\n                             'n_estimators': [0, 500, 1000, 1500, 2000, 2500, 3000,\n                                              3500, 4000, 4500]},\n                 pre_dispatch='2*n_jobs', refit=True, return_train_score=False,\n                 scoring=<function mean_absolute_percentage_error at 0x1a426c2d08>,\n                 verbose=0)\n\n\n\n\n```python\n%time clf.fit(X_train, y_train)\nprint(clf.best_score_)\nprint(clf.best_params_)\n```\n\n    Parameter optimization\n    CPU times: user 11.2 s, sys: 676 ms, total: 11.8 s\n    Wall time: 9min 55s\n    nan\n    {'gamma': 0.0, 'max_depth': 6, 'n_estimators': 0}\n\n\n# Fin\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "b81fbab1685ee21b81bbd0512df24d5ce48926d7", "size": 373360, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "saturdays-ai-xgboost_intro/Xgboost Slides.ipynb", "max_stars_repo_name": "israelzuniga/spark_streaming_class", "max_stars_repo_head_hexsha": "45e4245a2a61d933df7872b8cd6b75c28ad89496", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-03-21T19:19:42.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-31T04:14:04.000Z", "max_issues_repo_path": "saturdays-ai-xgboost_intro/Xgboost Slides.ipynb", "max_issues_repo_name": "israelzuniga/spark_streaming_class", "max_issues_repo_head_hexsha": "45e4245a2a61d933df7872b8cd6b75c28ad89496", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "saturdays-ai-xgboost_intro/Xgboost Slides.ipynb", "max_forks_repo_name": "israelzuniga/spark_streaming_class", "max_forks_repo_head_hexsha": "45e4245a2a61d933df7872b8cd6b75c28ad89496", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-02-26T00:26:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-26T00:26:39.000Z", "avg_line_length": 74.3893205818, "max_line_length": 58315, "alphanum_fraction": 0.7114072209, "converted": true, "num_tokens": 11585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.09947020587339866, "lm_q1q2_score": 0.03828729025498824}}
{"text": "# Text Classification with SpaCy\n\nA common task in NLP is **text classification**. This is \"classification\" in the conventional machine learning sense, and it is applied to text. Examples include spam detection, sentiment analysis, and tagging customer queries. \n\nIn this tutorial, you'll learn text classification with spaCy. The classifier will detect spam messages, a common functionality in most email clients. Here is an overview of the data you'll use:\n\n\n```python\nimport pandas as pd\n\n# Loading the spam data\n# ham is the label for non-spam messages\nspam = pd.read_csv('../input/nlp-course/spam.csv')\nspam.head(10)\n```\n\n# Bag of Words\nMachine learning models don't learn from raw text data. Instead, you need to convert the text to something numeric.\n\nThe simplest common representation is a variation of one-hot encoding. You represent each document as a vector of term frequencies for each term in the vocabulary. The vocabulary is built from all the tokens (terms) in the corpus (the collection of documents). \n\nAs an example, take the sentences \"Tea is life. Tea is love.\" and \"Tea is healthy, calming, and delicious.\" as our corpus. The vocabulary then is `{\"tea\", \"is\", \"life\", \"love\", \"healthy\", \"calming\", \"and\", \"delicious\"}` (ignoring punctuation).\n\nFor each document, count up how many times a term occurs, and place that count in the appropriate element of a vector. The first sentence has \"tea\" twice and that is the first position in our vocabulary, so we put the number 2 in the first element of the vector. Our sentences as vectors then look like \n\n$$\n\\begin{align}\nv_1 &= \\left[\\begin{matrix} 2 & 2 & 1 & 1 & 0 & 0 & 0 & 0 \\end{matrix}\\right] \\\\\nv_2 &= \\left[\\begin{matrix} 1 & 1 & 0 & 0 & 1 & 1 & 1 & 1 \\end{matrix}\\right]\n\\end{align}\n$$\n\nThis is called the **bag of words** representation. You can see that documents with similar terms will have similar vectors. Vocabularies frequently have tens of thousands of terms, so these vectors can be very large.\n\nAnother common representation is **TF-IDF (Term Frequency - Inverse Document Frequency)**. TF-IDF is similar to bag of words except that each term count is scaled by the term's frequency in the corpus. Using TF-IDF can potentially improve your models. You won't need it here. Feel free to look it up though!\n\n# Building a Bag of Words model\n\nOnce you have your documents in a bag of words representation, you can use those vectors as input to any machine learning model. spaCy handles the bag of words conversion and building a simple linear model for you with the `TextCategorizer` class.\n\nThe TextCategorizer is a spaCy **pipe**. Pipes are classes for processing and transforming tokens. When you create a spaCy model with `nlp = spacy.load('en_core_web_sm')`, there are default pipes that perform part of speech tagging, entity recognition, and other transformations. When you run text through a model `doc = nlp(\"Some text here\")`, the output of the pipes are attached to the tokens in the `doc` object. The lemmas for `token.lemma_` come from one of these pipes.\n\nYou can remove or add pipes to models. What we'll do here is create an empty model without any pipes (other than a tokenizer, since all models always have a tokenizer). Then, we'll create a TextCategorizer pipe and add it to the empty model.\n\n\n```python\nimport spacy\n\n# Create an empty model\nnlp = spacy.blank(\"en\")\n\n# Create the TextCategorizer with exclusive classes and \"bow\" architecture\ntextcat = nlp.create_pipe(\n              \"textcat\",\n              config={\n                \"exclusive_classes\": True,\n                \"architecture\": \"bow\"})\n\n# Add the TextCategorizer to the empty model\nnlp.add_pipe(textcat)\n```\n\nSince the classes are either ham or spam, we set `\"exclusive_classes\"` to `True`. We've also configured it with the bag of words (`\"bow\"`) architecture. spaCy provides a convolutional neural network architecture as well, but it's more complex than you need for now.\n\nNext we'll add the labels to the model. Here \"ham\" are for the real messages, \"spam\" are spam messages.\n\n\n```python\n# Add labels to text classifier\ntextcat.add_label(\"ham\")\ntextcat.add_label(\"spam\")\n```\n\n# Training a Text Categorizer Model\n\nNext, you'll convert the labels in the data to the form TextCategorizer requires. For each document, you'll create a dictionary of boolean values for each class. \n\nFor example, if a text is \"ham\", we need a dictionary `{'ham': True, 'spam': False}`. The model is looking for these labels inside another dictionary with the key `'cats'`.\n\n\n```python\ntrain_texts = spam['text'].values\ntrain_labels = [{'cats': {'ham': label == 'ham',\n                          'spam': label == 'spam'}} \n                for label in spam['label']]\n```\n\nThen we combine the texts and labels into a single list.\n\n\n```python\ntrain_data = list(zip(train_texts, train_labels))\ntrain_data[:3]\n```\n\nNow you are ready to train the model. First, create an `optimizer` using `nlp.begin_training()`. spaCy uses this optimizer to update the model. In general it's more efficient to train models in small batches. spaCy provides the `minibatch` function that returns a generator yielding minibatches for training. Finally, the minibatches are split into texts and labels, then used with `nlp.update` to update the model's parameters.\n\n\n```python\nfrom spacy.util import minibatch\n\nspacy.util.fix_random_seed(1)\noptimizer = nlp.begin_training()\n\n# Create the batch generator with batch size = 8\nbatches = minibatch(train_data, size=8)\n# Iterate through minibatches\nfor batch in batches:\n    # Each batch is a list of (text, label) but we need to\n    # send separate lists for texts and labels to update().\n    # This is a quick way to split a list of tuples into lists\n    texts, labels = zip(*batch)\n    nlp.update(texts, labels, sgd=optimizer)\n```\n\nThis is just one training loop (or epoch) through the data. The model will typically need multiple epochs. Use another loop for more epochs, and optionally re-shuffle the training data at the begining of each loop. \n\n\n```python\nimport random\n\nrandom.seed(1)\nspacy.util.fix_random_seed(1)\noptimizer = nlp.begin_training()\n\nlosses = {}\nfor epoch in range(10):\n    random.shuffle(train_data)\n    # Create the batch generator with batch size = 8\n    batches = minibatch(train_data, size=8)\n    # Iterate through minibatches\n    for batch in batches:\n        # Each batch is a list of (text, label) but we need to\n        # send separate lists for texts and labels to update().\n        # This is a quick way to split a list of tuples into lists\n        texts, labels = zip(*batch)\n        nlp.update(texts, labels, sgd=optimizer, losses=losses)\n    print(losses)\n```\n\n# Making Predictions\n\nNow that you have a trained model, you can make predictions with the `predict()` method. The input text needs to be tokenized with `nlp.tokenizer`. Then you pass the tokens to the predict method which returns scores. The scores are the probability the input text belongs to the classes.\n\n\n```python\ntexts = [\"Are you ready for the tea party????? It's gonna be wild\",\n         \"URGENT Reply to this message for GUARANTEED FREE TEA\" ]\ndocs = [nlp.tokenizer(text) for text in texts]\n    \n# Use textcat to get the scores for each doc\ntextcat = nlp.get_pipe('textcat')\nscores, _ = textcat.predict(docs)\n\nprint(scores)\n```\n\nThe scores are used to predict a single class or label by choosing the label with the highest probability. You get the index of the highest probability with `scores.argmax`, then use the index to get the label string from `textcat.labels`.\n\n\n```python\n# From the scores, find the label with the highest score/probability\npredicted_labels = scores.argmax(axis=1)\nprint([textcat.labels[label] for label in predicted_labels])\n```\n\nEvaluating the model is straightforward once you have the predictions. To measure the accuracy, calculate how many correct predictions are made on some test data, divided by the total number of predictions.\n\n# Your Turn\nTry it yourself as you **[predict the sentiment of Yelp reviews](#$NEXT_NOTEBOOK_URL$)**.\n", "meta": {"hexsha": "eadb906d084e07516563cd62506c9c2afac6b1b1", "size": 11476, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/nlp/raw/tut2.ipynb", "max_stars_repo_name": "gvvynplaine/learntools", "max_stars_repo_head_hexsha": "0520ada44d0e4990a5a5ae871c1f0654cff20086", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/nlp/raw/tut2.ipynb", "max_issues_repo_name": "gvvynplaine/learntools", "max_issues_repo_head_hexsha": "0520ada44d0e4990a5a5ae871c1f0654cff20086", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/nlp/raw/tut2.ipynb", "max_forks_repo_name": "gvvynplaine/learntools", "max_forks_repo_head_hexsha": "0520ada44d0e4990a5a5ae871c1f0654cff20086", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5100671141, "max_line_length": 487, "alphanum_fraction": 0.6178982224, "converted": true, "num_tokens": 1907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939264921326705, "lm_q2_score": 0.08509904036636974, "lm_q1q2_score": 0.03824288319574965}}
{"text": "```python\n!pip install pylatexenc qiskit[machine-learning]\n```\n\n    Collecting pylatexenc\n      Downloading pylatexenc-2.10.tar.gz (162 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 162 kB 4.6 MB/s \n    \u001b[?25hCollecting qiskit[machine-learning]\n      Downloading qiskit-0.32.0.tar.gz (13 kB)\n    Collecting qiskit-terra==0.18.3\n      Downloading qiskit_terra-0.18.3-cp37-cp37m-manylinux2010_x86_64.whl (6.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.1 MB 18.8 MB/s \n    \u001b[?25hCollecting qiskit-aer==0.9.1\n      Downloading qiskit_aer-0.9.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (17.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 17.9 MB 1.3 MB/s \n    \u001b[?25hCollecting qiskit-ibmq-provider==0.18.0\n      Downloading qiskit_ibmq_provider-0.18.0-py3-none-any.whl (237 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 237 kB 57.7 MB/s \n    \u001b[?25hCollecting qiskit-ignis==0.6.0\n      Downloading qiskit_ignis-0.6.0-py3-none-any.whl (207 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 207 kB 58.3 MB/s \n    \u001b[?25hCollecting qiskit-aqua==0.9.5\n      Downloading qiskit_aqua-0.9.5-py3-none-any.whl (2.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.1 MB 51.1 MB/s \n    \u001b[?25hCollecting qiskit-machine-learning>=0.2.1\n      Downloading qiskit_machine_learning-0.2.1-py3-none-any.whl (96 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 96 kB 5.5 MB/s \n    \u001b[?25hRequirement already satisfied: scipy>=1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.9.1->qiskit[machine-learning]) (1.4.1)\n    Requirement already satisfied: numpy>=1.16.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.9.1->qiskit[machine-learning]) (1.19.5)\n    Collecting docplex>=2.21.207\n      Downloading docplex-2.22.213.tar.gz (634 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 634 kB 68.4 MB/s \n    \u001b[?25hRequirement already satisfied: h5py<3.3.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit[machine-learning]) (3.1.0)\n    Requirement already satisfied: scikit-learn>=0.20.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit[machine-learning]) (1.0.1)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit[machine-learning]) (1.1.5)\n    Collecting dlx<=1.0.4\n      Downloading dlx-1.0.4.tar.gz (5.5 kB)\n    Collecting retworkx>=0.8.0\n      Downloading retworkx-0.10.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.4 MB 41.6 MB/s \n    \u001b[?25hCollecting quandl\n      Downloading Quandl-3.7.0-py2.py3-none-any.whl (26 kB)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit[machine-learning]) (57.4.0)\n    Collecting yfinance>=0.1.62\n      Downloading yfinance-0.1.66-py2.py3-none-any.whl (25 kB)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit[machine-learning]) (5.4.8)\n    Requirement already satisfied: fastdtw<=0.3.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit[machine-learning]) (0.3.4)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit[machine-learning]) (1.7.1)\n    Collecting websocket-client>=1.0.1\n      Downloading websocket_client-1.2.1-py2.py3-none-any.whl (52 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 52 kB 1.1 MB/s \n    \u001b[?25hRequirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.0->qiskit[machine-learning]) (2.23.0)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.0->qiskit[machine-learning]) (2.8.2)\n    Collecting requests-ntlm>=1.1.0\n      Downloading requests_ntlm-1.1.0-py2.py3-none-any.whl (5.7 kB)\n    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.0->qiskit[machine-learning]) (1.24.3)\n    Collecting tweedledum<2.0,>=1.1\n      Downloading tweedledum-1.1.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (943 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 943 kB 61.3 MB/s \n    \u001b[?25hCollecting symengine>0.7\n      Downloading symengine-0.8.1-cp37-cp37m-manylinux2010_x86_64.whl (38.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 38.2 MB 22 kB/s \n    \u001b[?25hCollecting fastjsonschema>=2.10\n      Downloading fastjsonschema-2.15.1-py3-none-any.whl (21 kB)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.18.3->qiskit[machine-learning]) (0.3.4)\n    Collecting ply>=3.10\n      Downloading ply-3.11-py2.py3-none-any.whl (49 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 49 kB 5.7 MB/s \n    \u001b[?25hCollecting python-constraint>=1.4\n      Downloading python-constraint-1.4.0.tar.bz2 (18 kB)\n    Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.18.3->qiskit[machine-learning]) (2.6.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from docplex>=2.21.207->qiskit-aqua==0.9.5->qiskit[machine-learning]) (1.15.0)\n    Requirement already satisfied: cached-property in /usr/local/lib/python3.7/dist-packages (from h5py<3.3.0->qiskit-aqua==0.9.5->qiskit[machine-learning]) (1.5.2)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.0->qiskit[machine-learning]) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.0->qiskit[machine-learning]) (2021.10.8)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.0->qiskit[machine-learning]) (2.10)\n    Collecting cryptography>=1.3\n      Downloading cryptography-35.0.0-cp36-abi3-manylinux_2_24_x86_64.whl (3.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.5 MB 29.5 MB/s \n    \u001b[?25hCollecting ntlm-auth>=1.0.2\n      Downloading ntlm_auth-1.5.0-py2.py3-none-any.whl (29 kB)\n    Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.0->qiskit[machine-learning]) (1.15.0)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.0->qiskit[machine-learning]) (2.21)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.9.5->qiskit[machine-learning]) (1.1.0)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.9.5->qiskit[machine-learning]) (3.0.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-aqua==0.9.5->qiskit[machine-learning]) (1.2.1)\n    Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance>=0.1.62->qiskit-aqua==0.9.5->qiskit[machine-learning]) (0.0.9)\n    Collecting lxml>=4.5.1\n      Downloading lxml-4.6.4-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl (6.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.3 MB 38.4 MB/s \n    \u001b[?25hRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->qiskit-aqua==0.9.5->qiskit[machine-learning]) (2018.9)\n    Collecting inflection>=0.3.1\n      Downloading inflection-0.5.1-py2.py3-none-any.whl (9.5 kB)\n    Requirement already satisfied: more-itertools in /usr/local/lib/python3.7/dist-packages (from quandl->qiskit-aqua==0.9.5->qiskit[machine-learning]) (8.11.0)\n    Building wheels for collected packages: pylatexenc, qiskit, dlx, docplex, python-constraint\n      Building wheel for pylatexenc (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pylatexenc: filename=pylatexenc-2.10-py3-none-any.whl size=136833 sha256=acf28190566cfe29fb12a0c656581fedc07108e8af3ae99f07f9966177e9c0ef\n      Stored in directory: /root/.cache/pip/wheels/f1/8a/f5/33ee79d4473eb201b519fa40f989b842e373237395a3421f52\n      Building wheel for qiskit (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for qiskit: filename=qiskit-0.32.0-py3-none-any.whl size=11773 sha256=0f4cf8d177a14773afb2c7610ec26ad5ce155a148e302c1c126e90d78ea17373\n      Stored in directory: /root/.cache/pip/wheels/95/84/c4/6a084a33c1909266fca66eed2303c3883e03f33c905b1ebed9\n      Building wheel for dlx (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for dlx: filename=dlx-1.0.4-py3-none-any.whl size=5719 sha256=61f3bc1501f21f6d7fc60b708926ab39ed471a1db462c557c206a68ef193e374\n      Stored in directory: /root/.cache/pip/wheels/78/55/c8/dc61e772445a566b7608a476d151e9dcaf4e092b01b0c4bc3c\n      Building wheel for docplex (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for docplex: filename=docplex-2.22.213-py3-none-any.whl size=696881 sha256=2463466a48bc2296b9cfa8bd7fb47688e7a3f940334c3d9a3e72193b078a3721\n      Stored in directory: /root/.cache/pip/wheels/90/69/6b/1375c68a5b7ff94c40263b151c86f58bd72200bf0c465b5ba3\n      Building wheel for python-constraint (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for python-constraint: filename=python_constraint-1.4.0-py2.py3-none-any.whl size=24081 sha256=45bb9cc504979f33e6684516224ec7a9179bc4f108613a0d5a92b5e05731a7bd\n      Stored in directory: /root/.cache/pip/wheels/07/27/db/1222c80eb1e431f3d2199c12569cb1cac60f562a451fe30479\n    Successfully built pylatexenc qiskit dlx docplex python-constraint\n    Installing collected packages: tweedledum, symengine, retworkx, python-constraint, ply, fastjsonschema, qiskit-terra, ntlm-auth, lxml, inflection, cryptography, yfinance, websocket-client, requests-ntlm, quandl, qiskit-ignis, docplex, dlx, qiskit-ibmq-provider, qiskit-aqua, qiskit-aer, qiskit-machine-learning, qiskit, pylatexenc\n      Attempting uninstall: lxml\n        Found existing installation: lxml 4.2.6\n        Uninstalling lxml-4.2.6:\n          Successfully uninstalled lxml-4.2.6\n    Successfully installed cryptography-35.0.0 dlx-1.0.4 docplex-2.22.213 fastjsonschema-2.15.1 inflection-0.5.1 lxml-4.6.4 ntlm-auth-1.5.0 ply-3.11 pylatexenc-2.10 python-constraint-1.4.0 qiskit-0.32.0 qiskit-aer-0.9.1 qiskit-aqua-0.9.5 qiskit-ibmq-provider-0.18.0 qiskit-ignis-0.6.0 qiskit-machine-learning-0.2.1 qiskit-terra-0.18.3 quandl-3.7.0 requests-ntlm-1.1.0 retworkx-0.10.2 symengine-0.8.1 tweedledum-1.1.1 websocket-client-1.2.1 yfinance-0.1.66\n\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom qiskit import Aer, QuantumCircuit\nfrom qiskit.utils import QuantumInstance\nfrom qiskit.circuit import ParameterVector\nfrom qiskit.circuit.parametertable import ParameterView\nfrom qiskit.circuit.library import PauliFeatureMap, EfficientSU2\nfrom qiskit.algorithms.optimizers import COBYLA\n\nfrom qiskit_machine_learning.neural_networks import CircuitQNN\nfrom qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier\n\nimport gensim\nimport torch\nimport torch.nn as nn\nimport pickle\nfrom sklearn.decomposition import PCA\n\nimport itertools\n\nfrom IPython.display import clear_output\n```\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n# Preprocess Word Embeddings\n\n\n```python\nwith open(r\"/content/drive/MyDrive/pre_ft_vectors\", \"rb\") as input_file:\n  embeddings_dict = pickle.load(input_file)\n```\n\n# Preprocess Data\n\n\n```python\nwith open(\"/content/drive/MyDrive/amazon_reviews_data.txt\") as f:\n  raw_corpus = f.readlines()\n```\n\n\n```python\ncorpus = [ { \"sentence\": [''.join(e for e in word if e.isalnum()).lower() for word in sentence.split()[:-1]], \"sentiment\": int(sentence.split()[-1]) }  for sentence in raw_data ]\ncorpus\n```\n\n\n\n\n    [{'sentence': ['so',\n       'there',\n       'is',\n       'no',\n       'way',\n       'for',\n       'me',\n       'to',\n       'plug',\n       'it',\n       'in',\n       'here',\n       'in',\n       'the',\n       'us',\n       'unless',\n       'i',\n       'go',\n       'by',\n       'a',\n       'converter'],\n      'sentiment': 0},\n     {'sentence': ['good', 'case', 'excellent', 'value'], 'sentiment': 1},\n     {'sentence': ['great', 'for', 'the', 'jawbone'], 'sentiment': 1},\n     {'sentence': ['tied',\n       'to',\n       'charger',\n       'for',\n       'conversations',\n       'lasting',\n       'more',\n       'than',\n       '45',\n       'minutesmajor',\n       'problems'],\n      'sentiment': 0},\n     {'sentence': ['the', 'mic', 'is', 'great'], 'sentiment': 1},\n     {'sentence': ['i',\n       'have',\n       'to',\n       'jiggle',\n       'the',\n       'plug',\n       'to',\n       'get',\n       'it',\n       'to',\n       'line',\n       'up',\n       'right',\n       'to',\n       'get',\n       'decent',\n       'volume'],\n      'sentiment': 0},\n     {'sentence': ['if',\n       'you',\n       'have',\n       'several',\n       'dozen',\n       'or',\n       'several',\n       'hundred',\n       'contacts',\n       'then',\n       'imagine',\n       'the',\n       'fun',\n       'of',\n       'sending',\n       'each',\n       'of',\n       'them',\n       'one',\n       'by',\n       'one'],\n      'sentiment': 0},\n     {'sentence': ['if', 'you', 'are', 'razr', 'owneryou', 'must', 'have', 'this'],\n      'sentiment': 1},\n     {'sentence': ['needless', 'to', 'say', 'i', 'wasted', 'my', 'money'],\n      'sentiment': 0},\n     {'sentence': ['what', 'a', 'waste', 'of', 'money', 'and', 'time'],\n      'sentiment': 0},\n     {'sentence': ['and', 'the', 'sound', 'quality', 'is', 'great'],\n      'sentiment': 1},\n     {'sentence': ['he',\n       'was',\n       'very',\n       'impressed',\n       'when',\n       'going',\n       'from',\n       'the',\n       'original',\n       'battery',\n       'to',\n       'the',\n       'extended',\n       'battery'],\n      'sentiment': 1},\n     {'sentence': ['if',\n       'the',\n       'two',\n       'were',\n       'seperated',\n       'by',\n       'a',\n       'mere',\n       '5',\n       'ft',\n       'i',\n       'started',\n       'to',\n       'notice',\n       'excessive',\n       'static',\n       'and',\n       'garbled',\n       'sound',\n       'from',\n       'the',\n       'headset'],\n      'sentiment': 0},\n     {'sentence': ['very', 'good', 'quality', 'though'], 'sentiment': 1},\n     {'sentence': ['the',\n       'design',\n       'is',\n       'very',\n       'odd',\n       'as',\n       'the',\n       'ear',\n       'clip',\n       'is',\n       'not',\n       'very',\n       'comfortable',\n       'at',\n       'all'],\n      'sentiment': 0},\n     {'sentence': ['highly',\n       'recommend',\n       'for',\n       'any',\n       'one',\n       'who',\n       'has',\n       'a',\n       'blue',\n       'tooth',\n       'phone'],\n      'sentiment': 1},\n     {'sentence': ['i', 'advise', 'everyone', 'do', 'not', 'be', 'fooled'],\n      'sentiment': 0},\n     {'sentence': ['so', 'far', 'so', 'good'], 'sentiment': 1},\n     {'sentence': ['works', 'great'], 'sentiment': 1},\n     {'sentence': ['it',\n       'clicks',\n       'into',\n       'place',\n       'in',\n       'a',\n       'way',\n       'that',\n       'makes',\n       'you',\n       'wonder',\n       'how',\n       'long',\n       'that',\n       'mechanism',\n       'would',\n       'last'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'went',\n       'on',\n       'motorolas',\n       'website',\n       'and',\n       'followed',\n       'all',\n       'directions',\n       'but',\n       'could',\n       'not',\n       'get',\n       'it',\n       'to',\n       'pair',\n       'again'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'bought',\n       'this',\n       'to',\n       'use',\n       'with',\n       'my',\n       'kindle',\n       'fire',\n       'and',\n       'absolutely',\n       'loved',\n       'it'],\n      'sentiment': 1},\n     {'sentence': ['the', 'commercials', 'are', 'the', 'most', 'misleading'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'have',\n       'yet',\n       'to',\n       'run',\n       'this',\n       'new',\n       'battery',\n       'below',\n       'two',\n       'bars',\n       'and',\n       'thats',\n       'three',\n       'days',\n       'without',\n       'charging'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'bought',\n       'it',\n       'for',\n       'my',\n       'mother',\n       'and',\n       'she',\n       'had',\n       'a',\n       'problem',\n       'with',\n       'the',\n       'battery'],\n      'sentiment': 0},\n     {'sentence': ['great', 'pocket', 'pc', '', 'phone', 'combination'],\n      'sentiment': 1},\n     {'sentence': ['ive',\n       'owned',\n       'this',\n       'phone',\n       'for',\n       '7',\n       'months',\n       'now',\n       'and',\n       'can',\n       'say',\n       'that',\n       'its',\n       'the',\n       'best',\n       'mobile',\n       'phone',\n       'ive',\n       'had'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'didnt',\n       'think',\n       'that',\n       'the',\n       'instructions',\n       'provided',\n       'were',\n       'helpful',\n       'to',\n       'me'],\n      'sentiment': 0},\n     {'sentence': ['people',\n       'couldnt',\n       'hear',\n       'me',\n       'talk',\n       'and',\n       'i',\n       'had',\n       'to',\n       'pull',\n       'out',\n       'the',\n       'earphone',\n       'and',\n       'talk',\n       'on',\n       'the',\n       'phone'],\n      'sentiment': 0},\n     {'sentence': ['doesnt', 'hold', 'charge'], 'sentiment': 0},\n     {'sentence': ['this',\n       'is',\n       'a',\n       'simple',\n       'little',\n       'phone',\n       'to',\n       'use',\n       'but',\n       'the',\n       'breakage',\n       'is',\n       'unacceptible'],\n      'sentiment': 0},\n     {'sentence': ['this',\n       'product',\n       'is',\n       'ideal',\n       'for',\n       'people',\n       'like',\n       'me',\n       'whose',\n       'ears',\n       'are',\n       'very',\n       'sensitive'],\n      'sentiment': 1},\n     {'sentence': ['it',\n       'is',\n       'unusable',\n       'in',\n       'a',\n       'moving',\n       'car',\n       'at',\n       'freeway',\n       'speed'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'have',\n       'two',\n       'more',\n       'years',\n       'left',\n       'in',\n       'this',\n       'contract',\n       'and',\n       'i',\n       'hate',\n       'this',\n       'phone'],\n      'sentiment': 0},\n     {'sentence': ['car',\n       'charger',\n       'as',\n       'well',\n       'as',\n       'ac',\n       'charger',\n       'are',\n       'included',\n       'to',\n       'make',\n       'sure',\n       'you',\n       'never',\n       'run',\n       'out',\n       'of',\n       'juicehighy',\n       'recommended'],\n      'sentiment': 1},\n     {'sentence': ['you',\n       'need',\n       'at',\n       'least',\n       '3',\n       'mins',\n       'to',\n       'get',\n       'to',\n       'your',\n       'phone',\n       'book',\n       'from',\n       'the',\n       'time',\n       'you',\n       'first',\n       'turn',\n       'on',\n       'the',\n       'phonebattery',\n       'life',\n       'is',\n       'short'],\n      'sentiment': 0},\n     {'sentence': ['it', 'has', 'kept', 'up', 'very', 'well'], 'sentiment': 1},\n     {'sentence': ['poor', 'talk', 'time', 'performance'], 'sentiment': 0},\n     {'sentence': ['the',\n       'case',\n       'is',\n       'great',\n       'and',\n       'works',\n       'fine',\n       'with',\n       'the',\n       '680'],\n      'sentiment': 1},\n     {'sentence': ['worthless', 'product'], 'sentiment': 0},\n     {'sentence': ['it',\n       'has',\n       'a',\n       'great',\n       'camera',\n       'thats',\n       '2mp',\n       'and',\n       'the',\n       'pics',\n       'are',\n       'nice',\n       'and',\n       'clear',\n       'with',\n       'great',\n       'picture',\n       'quality'],\n      'sentiment': 1},\n     {'sentence': ['i', 'was', 'not', 'impressed', 'by', 'this', 'product'],\n      'sentiment': 0},\n     {'sentence': ['nice', 'headset', 'priced', 'right'], 'sentiment': 1},\n     {'sentence': ['i', 'only', 'hear', 'garbage', 'for', 'audio'],\n      'sentiment': 0},\n     {'sentence': ['excellent', 'bluetooth', 'headset'], 'sentiment': 1},\n     {'sentence': ['it', 'has', 'all', 'the', 'features', 'i', 'want'],\n      'sentiment': 1},\n     {'sentence': ['who',\n       'in',\n       'their',\n       'right',\n       'mind',\n       'is',\n       'gonna',\n       'buy',\n       'this',\n       'battery'],\n      'sentiment': 0},\n     {'sentence': ['after',\n       'arguing',\n       'with',\n       'verizon',\n       'regarding',\n       'the',\n       'dropped',\n       'calls',\n       'we',\n       'returned',\n       'the',\n       'phones',\n       'after',\n       'two',\n       'days'],\n      'sentiment': 0},\n     {'sentence': ['this', 'case', 'seems', 'well', 'made'], 'sentiment': 1},\n     {'sentence': ['disappointed', 'with', 'battery'], 'sentiment': 0},\n     {'sentence': ['not',\n       'loud',\n       'enough',\n       'and',\n       'doesnt',\n       'turn',\n       'on',\n       'like',\n       'it',\n       'should'],\n      'sentiment': 0},\n     {'sentence': ['good',\n       'protection',\n       'and',\n       'does',\n       'not',\n       'make',\n       'phone',\n       'too',\n       'bulky'],\n      'sentiment': 1},\n     {'sentence': ['a',\n       'usable',\n       'keyboard',\n       'actually',\n       'turns',\n       'a',\n       'pda',\n       'into',\n       'a',\n       'realworld',\n       'useful',\n       'machine',\n       'instead',\n       'of',\n       'just',\n       'a',\n       'neat',\n       'gadget'],\n      'sentiment': 1},\n     {'sentence': ['this',\n       'phone',\n       'is',\n       'pretty',\n       'sturdy',\n       'and',\n       'ive',\n       'never',\n       'had',\n       'any',\n       'large',\n       'problems',\n       'with',\n       'it'],\n      'sentiment': 1},\n     {'sentence': ['i', 'love', 'this', 'thing'], 'sentiment': 1},\n     {'sentence': ['everything',\n       'about',\n       'it',\n       'is',\n       'fine',\n       'and',\n       'reasonable',\n       'for',\n       'the',\n       'price',\n       'ie'],\n      'sentiment': 1},\n     {'sentence': ['very', 'disappointed'], 'sentiment': 0},\n     {'sentence': ['i',\n       'even',\n       'dropped',\n       'this',\n       'phone',\n       'into',\n       'a',\n       'stream',\n       'and',\n       'it',\n       'was',\n       'submerged',\n       'for',\n       '15',\n       'seconds',\n       'and',\n       'it',\n       'still',\n       'works',\n       'great'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'have',\n       'been',\n       'very',\n       'happy',\n       'with',\n       'the',\n       '510',\n       'and',\n       'have',\n       'had',\n       'no',\n       'complaints',\n       'from',\n       'any',\n       'one',\n       'regarding',\n       'my',\n       'sound',\n       'quality',\n       'on',\n       'their',\n       'end'],\n      'sentiment': 1},\n     {'sentence': ['the', 'buttons', 'for', 'on', 'and', 'off', 'are', 'bad'],\n      'sentiment': 0},\n     {'sentence': ['essentially',\n       'you',\n       'can',\n       'forget',\n       'microsofts',\n       'tech',\n       'support'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'really',\n       'recommend',\n       'this',\n       'faceplates',\n       'since',\n       'it',\n       'looks',\n       'very',\n       'nice',\n       'elegant',\n       'and',\n       'cool'],\n      'sentiment': 1},\n     {'sentence': ['these',\n       'headphones',\n       'were',\n       'a',\n       'great',\n       'find',\n       '',\n       'and',\n       'i',\n       'think',\n       'they',\n       'are',\n       'perhaps',\n       'the',\n       'best',\n       'purchase',\n       'ive',\n       'made',\n       'in',\n       'the',\n       'last',\n       'several',\n       'years',\n       '',\n       'seriously'],\n      'sentiment': 1},\n     {'sentence': ['buy', 'a', 'different', 'phone', '', 'but', 'not', 'this'],\n      'sentiment': 0},\n     {'sentence': ['you',\n       'have',\n       'to',\n       'hold',\n       'the',\n       'phone',\n       'at',\n       'a',\n       'particular',\n       'angle',\n       'for',\n       'the',\n       'other',\n       'party',\n       'to',\n       'hear',\n       'you',\n       'clearly'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'one',\n       'big',\n       'drawback',\n       'of',\n       'the',\n       'mp3',\n       'player',\n       'is',\n       'that',\n       'the',\n       'buttons',\n       'on',\n       'the',\n       'phones',\n       'front',\n       'cover',\n       'that',\n       'let',\n       'you',\n       'pause',\n       'and',\n       'skip',\n       'songs',\n       'lock',\n       'out',\n       'after',\n       'a',\n       'few',\n       'seconds'],\n      'sentiment': 0},\n     {'sentence': ['a',\n       'week',\n       'later',\n       'after',\n       'i',\n       'activated',\n       'it',\n       'it',\n       'suddenly',\n       'died'],\n      'sentiment': 0},\n     {'sentence': ['it',\n       'feels',\n       'more',\n       'comfortable',\n       'than',\n       'most',\n       'headsets',\n       'because',\n       'i',\n       'wear',\n       'glasses',\n       'and',\n       'that',\n       'gets',\n       'in',\n       'the',\n       'way',\n       'sometimes'],\n      'sentiment': 1},\n     {'sentence': ['great', 'for', 'ipods', 'too'], 'sentiment': 1},\n     {'sentence': ['this',\n       'device',\n       'is',\n       'great',\n       'in',\n       'several',\n       'situations1'],\n      'sentiment': 1},\n     {'sentence': ['mic', 'doesnt', 'work'], 'sentiment': 0},\n     {'sentence': ['even',\n       'in',\n       'my',\n       'bmw',\n       '3',\n       'series',\n       'which',\n       'is',\n       'fairly',\n       'quiet',\n       'i',\n       'have',\n       'trouble',\n       'hearing',\n       'what',\n       'the',\n       'other',\n       'person',\n       'is',\n       'saying'],\n      'sentiment': 0},\n     {'sentence': ['great', 'choice'], 'sentiment': 1},\n     {'sentence': ['nice', 'docking', 'station', 'for', 'home', 'or', 'work'],\n      'sentiment': 1},\n     {'sentence': ['this', 'is', 'a', 'beautiful', 'phone'], 'sentiment': 1},\n     {'sentence': ['love', 'this', 'product'], 'sentiment': 1},\n     {'sentence': ['do',\n       'not',\n       'buy',\n       'for',\n       'd807wrongly',\n       'advertised',\n       'for',\n       'd807'],\n      'sentiment': 0},\n     {'sentence': ['this', 'is', 'a', 'great', 'little', 'item'], 'sentiment': 1},\n     {'sentence': ['i',\n       'love',\n       'this',\n       'phone',\n       '',\n       'it',\n       'is',\n       'very',\n       'handy',\n       'and',\n       'has',\n       'a',\n       'lot',\n       'of',\n       'features',\n       ''],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'purchased',\n       'this',\n       'and',\n       'within',\n       '2',\n       'days',\n       'it',\n       'was',\n       'no',\n       'longer',\n       'working'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'wear',\n       'it',\n       'everyday',\n       'and',\n       'it',\n       'holds',\n       'up',\n       'very',\n       'well'],\n      'sentiment': 1},\n     {'sentence': ['not', 'a', 'good', 'bargain'], 'sentiment': 0},\n     {'sentence': ['well',\n       'packaged',\n       'arrived',\n       'on',\n       'time',\n       'and',\n       'works',\n       'as',\n       'intended'],\n      'sentiment': 1},\n     {'sentence': ['the', 'battery', 'runs', 'down', 'quickly'], 'sentiment': 0},\n     {'sentence': ['this',\n       'item',\n       'worked',\n       'great',\n       'but',\n       'it',\n       'broke',\n       'after',\n       '6',\n       'months',\n       'of',\n       'use'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'headsets',\n       'are',\n       'easy',\n       'to',\n       'use',\n       'and',\n       'everyone',\n       'loves',\n       'them'],\n      'sentiment': 1},\n     {'sentence': ['this', 'phone', 'works', 'great'], 'sentiment': 1},\n     {'sentence': ['the', 'construction', 'of', 'the', 'headsets', 'is', 'poor'],\n      'sentiment': 0},\n     {'sentence': ['product',\n       'was',\n       'excellent',\n       'and',\n       'works',\n       'better',\n       'than',\n       'the',\n       'verizon',\n       'one',\n       'and',\n       'boy',\n       'was',\n       'it',\n       'cheaper'],\n      'sentiment': 1},\n     {'sentence': ['the', 'phone', 'loads', 'super'], 'sentiment': 1},\n     {'sentence': ['for',\n       'a',\n       'product',\n       'that',\n       'costs',\n       'as',\n       'much',\n       'as',\n       'this',\n       'one',\n       'does',\n       'i',\n       'expect',\n       'it',\n       'to',\n       'work',\n       'far',\n       'better',\n       'and',\n       'with',\n       'greater',\n       'ease',\n       'than',\n       'this',\n       'thing',\n       'does'],\n      'sentiment': 0},\n     {'sentence': ['made', 'very', 'sturdy'], 'sentiment': 1},\n     {'sentence': ['worked', 'great'], 'sentiment': 1},\n     {'sentence': ['the',\n       'ear',\n       'buds',\n       'only',\n       'play',\n       'music',\n       'in',\n       'one',\n       'ear'],\n      'sentiment': 0},\n     {'sentence': ['dont', 'waste', 'your', 'money'], 'sentiment': 0},\n     {'sentence': ['will', 'order', 'from', 'them', 'again'], 'sentiment': 1},\n     {'sentence': ['if',\n       'you',\n       'plan',\n       'to',\n       'use',\n       'this',\n       'in',\n       'a',\n       'car',\n       'forget',\n       'about',\n       'it'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'found',\n       'this',\n       'product',\n       'to',\n       'be',\n       'waaay',\n       'too',\n       'big'],\n      'sentiment': 0},\n     {'sentence': ['best',\n       'ive',\n       'found',\n       'so',\n       'far',\n       '',\n       'ive',\n       'tried',\n       '2',\n       'other',\n       'bluetooths',\n       'and',\n       'this',\n       'one',\n       'has',\n       'the',\n       'best',\n       'quality',\n       'for',\n       'both',\n       'me',\n       'and',\n       'the',\n       'listener',\n       'as',\n       'well',\n       'as',\n       'ease',\n       'of',\n       'using'],\n      'sentiment': 1},\n     {'sentence': ['im', 'very', 'disappointed', 'with', 'my', 'decision'],\n      'sentiment': 0},\n     {'sentence': ['integrated',\n       'seamlessly',\n       'with',\n       'the',\n       'motorola',\n       'razr',\n       'phone'],\n      'sentiment': 1},\n     {'sentence': ['buyer',\n       'beware',\n       'you',\n       'could',\n       'flush',\n       'money',\n       'right',\n       'down',\n       'the',\n       'toilet'],\n      'sentiment': 0},\n     {'sentence': ['definitely', 'a', 'bargain'], 'sentiment': 1},\n     {'sentence': ['the',\n       'price',\n       'was',\n       'very',\n       'good',\n       'and',\n       'with',\n       'the',\n       'free',\n       'shipping',\n       'and',\n       'all',\n       'it',\n       'was',\n       'a',\n       'good',\n       'purchase'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'received',\n       'my',\n       'supposedly',\n       'new',\n       'motorola',\n       '375',\n       'and',\n       'apparently',\n       'there',\n       'was',\n       'not',\n       'a',\n       'match',\n       'between',\n       'the',\n       'phone',\n       'and',\n       'the',\n       'charger'],\n      'sentiment': 0},\n     {'sentence': ['prosgood',\n       'camera',\n       '',\n       'very',\n       'nice',\n       'pictures',\n       '',\n       'also',\n       'has',\n       'cool',\n       'styles',\n       'like',\n       'black',\n       'and',\n       'white',\n       'and',\n       'more'],\n      'sentiment': 1},\n     {'sentence': ['thats',\n       'a',\n       'huge',\n       'design',\n       'flaw',\n       'unless',\n       'im',\n       'not',\n       'using',\n       'it',\n       'correctly',\n       'which',\n       'i',\n       'dont',\n       'think',\n       'is',\n       'the',\n       'case'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'love',\n       'my',\n       '350',\n       'headset',\n       'my',\n       'jabra350',\n       'bluetooth',\n       'headset',\n       'is',\n       'great',\n       'the',\n       'reception',\n       'is',\n       'very',\n       'good',\n       'and',\n       'the',\n       'ear',\n       'piece',\n       'is',\n       'a',\n       'comfortable',\n       'fit'],\n      'sentiment': 1},\n     {'sentence': ['the',\n       'camera',\n       'although',\n       'rated',\n       'at',\n       'an',\n       'impressive',\n       '13',\n       'megapixels',\n       'renders',\n       'images',\n       'that',\n       'fall',\n       'well',\n       'below',\n       'expectations',\n       'of',\n       'such',\n       'a',\n       'relatively',\n       'high',\n       'resolution'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'purcashed',\n       'this',\n       'for',\n       'the',\n       'car',\n       'charger',\n       'and',\n       'it',\n       'does',\n       'not',\n       'work'],\n      'sentiment': 0},\n     {'sentence': ['sound',\n       'quality',\n       'on',\n       'both',\n       'end',\n       'is',\n       'excellent',\n       'i',\n       'use',\n       'headset',\n       'to',\n       'call',\n       'my',\n       'wife',\n       'and',\n       'ask',\n       'my',\n       'wife',\n       'to',\n       'use',\n       'headset',\n       'to',\n       'call',\n       'me',\n       '2'],\n      'sentiment': 1},\n     {'sentence': ['this',\n       'phone',\n       'is',\n       'slim',\n       'and',\n       'light',\n       'and',\n       'the',\n       'display',\n       'is',\n       'beautiful'],\n      'sentiment': 1},\n     {'sentence': ['its',\n       'a',\n       'little',\n       'geeky',\n       'but',\n       'i',\n       'think',\n       'thats',\n       'its',\n       'sex',\n       'on',\n       'toast',\n       'and',\n       'it',\n       'rocks',\n       'and',\n       'oozes',\n       'sex',\n       'right',\n       'down',\n       'to',\n       'its',\n       'battery',\n       'embedded',\n       'sleek',\n       'stylish',\n       'leather',\n       'case'],\n      'sentiment': 1},\n     {'sentence': ['great', 'product', 'fast', 'shipping'], 'sentiment': 1},\n     {'sentence': ['absolutely', 'great'], 'sentiment': 1},\n     {'sentence': ['the',\n       'keyboard',\n       'is',\n       'a',\n       'nice',\n       'compromise',\n       'between',\n       'a',\n       'full',\n       'qwerty',\n       'and',\n       'the',\n       'basic',\n       'cell',\n       'phone',\n       'number',\n       'keypad'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'got',\n       'this',\n       'phone',\n       'around',\n       'the',\n       'end',\n       'of',\n       'may',\n       'and',\n       'im',\n       'completely',\n       'unhappy',\n       'with',\n       'it'],\n      'sentiment': 0},\n     {'sentence': ['it', 'is', 'very', 'comfortable', 'on', 'the', 'ear'],\n      'sentiment': 1},\n     {'sentence': ['it', 'has', 'been', 'a', 'winner', 'for', 'us'],\n      'sentiment': 1},\n     {'sentence': ['setup', 'couldnt', 'have', 'been', 'simpler'], 'sentiment': 1},\n     {'sentence': ['ive',\n       'tried',\n       'several',\n       'different',\n       'earpieces',\n       'for',\n       'my',\n       'cell',\n       'phone',\n       'and',\n       'this',\n       'jabra',\n       'one',\n       'is',\n       'the',\n       'first',\n       'one',\n       'ive',\n       'found',\n       'that',\n       'fits',\n       'my',\n       'ear',\n       'comfortably'],\n      'sentiment': 1},\n     {'sentence': ['could', 'not', 'get', 'strong', 'enough', 'signal'],\n      'sentiment': 0},\n     {'sentence': ['iam', 'very', 'pleased', 'with', 'my', 'purchase'],\n      'sentiment': 1},\n     {'sentence': ['bad', 'quality'], 'sentiment': 0},\n     {'sentence': ['gets', 'the', 'job', 'done'], 'sentiment': 1},\n     {'sentence': ['great', 'audio'], 'sentiment': 1},\n     {'sentence': ['basically', 'the', 'service', 'was', 'very', 'bad'],\n      'sentiment': 0},\n     {'sentence': ['it',\n       'did',\n       'not',\n       'work',\n       'in',\n       'my',\n       'cell',\n       'phone',\n       'plug',\n       'i',\n       'am',\n       'very',\n       'up',\n       'set',\n       'with',\n       'the',\n       'charger'],\n      'sentiment': 0},\n     {'sentence': ['ive',\n       'only',\n       'had',\n       'my',\n       'bluetooth',\n       'for',\n       'a',\n       'few',\n       'weeks',\n       'but',\n       'i',\n       'really',\n       'like',\n       'it'],\n      'sentiment': 1},\n     {'sentence': ['the', 'bt', 'headset', 'was', 'such', 'a', 'disapoinment'],\n      'sentiment': 0},\n     {'sentence': ['it',\n       'is',\n       'so',\n       'small',\n       'and',\n       'you',\n       'dont',\n       'even',\n       'realize',\n       'that',\n       'it',\n       'is',\n       'there',\n       'after',\n       'a',\n       'while',\n       'of',\n       'getting',\n       'used',\n       'to',\n       'it'],\n      'sentiment': 1},\n     {'sentence': ['the', 'accompanied', 'software', 'is', 'almost', 'brilliant'],\n      'sentiment': 1},\n     {'sentence': ['headset',\n       'works',\n       'great',\n       '',\n       'was',\n       'packaged',\n       'nicely',\n       'to',\n       'avoid',\n       'any',\n       'damage'],\n      'sentiment': 1},\n     {'sentence': ['i', 'definitly', 'recommend'], 'sentiment': 1},\n     {'sentence': ['buyerbe', 'very', 'careful'], 'sentiment': 0},\n     {'sentence': ['the',\n       'majority',\n       'of',\n       'the',\n       'logitech',\n       'earbud',\n       'headsets',\n       'failed'],\n      'sentiment': 0},\n     {'sentence': ['very', 'good', 'stuff', 'for', 'the', 'price'],\n      'sentiment': 1},\n     {'sentence': ['my', 'headset', 'works', 'just', 'peachykeen'],\n      'sentiment': 1},\n     {'sentence': ['in',\n       'my',\n       'house',\n       'i',\n       'was',\n       'getting',\n       'dropped',\n       'coverage',\n       'upstairs',\n       'and',\n       'no',\n       'coverage',\n       'in',\n       'my',\n       'basement'],\n      'sentiment': 0},\n     {'sentence': ['voice', 'recognition', 'is', 'tremendous'], 'sentiment': 1},\n     {'sentence': ['what', 'a', 'waste'], 'sentiment': 0},\n     {'sentence': ['during',\n       'several',\n       'different',\n       '2',\n       'minute',\n       'calls',\n       'i',\n       'experienced',\n       '5',\n       'drops',\n       'and',\n       'it',\n       'was',\n       'in',\n       'an',\n       'area',\n       'that',\n       'had',\n       '5',\n       'bars'],\n      'sentiment': 0},\n     {'sentence': ['i', 'was', 'not', 'happy', 'with', 'this', 'item'],\n      'sentiment': 0},\n     {'sentence': ['very', 'disappointed'], 'sentiment': 0},\n     {'sentence': ['the',\n       'phone',\n       'takes',\n       'forever',\n       'to',\n       'charge',\n       'like',\n       '2',\n       'to',\n       '5',\n       'hours',\n       'literally'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'got',\n       'this',\n       'phone',\n       'on',\n       'reccomendation',\n       'from',\n       'a',\n       'relative',\n       'and',\n       'im',\n       'glad',\n       'i',\n       'did'],\n      'sentiment': 1},\n     {'sentence': ['what', 'a', 'waste', 'of', 'time'], 'sentiment': 0},\n     {'sentence': ['its', 'reception', 'is', 'very', 'very', 'poor'],\n      'sentiment': 0},\n     {'sentence': ['items',\n       'stated',\n       'as',\n       'included',\n       'from',\n       'the',\n       'description',\n       'are',\n       'not',\n       'included'],\n      'sentiment': 0},\n     {'sentence': ['after',\n       '3',\n       'months',\n       'screen',\n       'just',\n       'went',\n       'black',\n       'all',\n       'of',\n       'a',\n       'sudden'],\n      'sentiment': 0},\n     {'sentence': ['i', 'was', 'hoping', 'for', 'more'], 'sentiment': 0},\n     {'sentence': ['audio', 'quality', 'is', 'poor', 'very', 'poor'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'had',\n       'absolutely',\n       'no',\n       'problem',\n       'with',\n       'this',\n       'headset',\n       'linking',\n       'to',\n       'my',\n       '8530',\n       'blackberry',\n       'curve'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'know',\n       'that',\n       'sounds',\n       'funny',\n       'but',\n       'to',\n       'me',\n       'it',\n       'seemed',\n       'like',\n       'sketchy',\n       'technology',\n       'that',\n       'wouldnt',\n       'work',\n       'wellwell',\n       'this',\n       'one',\n       'works',\n       'great'],\n      'sentiment': 1},\n     {'sentence': ['ive',\n       'bought',\n       '5',\n       'wired',\n       'headphones',\n       'that',\n       'sound',\n       'better',\n       'than',\n       'these'],\n      'sentiment': 0},\n     {'sentence': ['this',\n       'phone',\n       'is',\n       'very',\n       'fast',\n       'with',\n       'sending',\n       'any',\n       'kind',\n       'of',\n       'messages',\n       'and',\n       'web',\n       'browsing',\n       'is',\n       'significantly',\n       'faster',\n       'than',\n       'previous',\n       'phones',\n       'i',\n       'have',\n       'used'],\n      'sentiment': 1},\n     {'sentence': ['nice',\n       'quality',\n       'build',\n       'unlike',\n       'some',\n       'cheap',\n       's',\n       'out',\n       'there'],\n      'sentiment': 1},\n     {'sentence': ['this', 'item', 'is', 'fantastic', 'and', 'works', 'perfectly'],\n      'sentiment': 1},\n     {'sentence': ['and', 'i', 'just', 'love', 'the', 'colors'], 'sentiment': 1},\n     {'sentence': ['w810i', 'is', 'just', 'superb'], 'sentiment': 1},\n     {'sentence': ['all',\n       'i',\n       'can',\n       'do',\n       'is',\n       'whine',\n       'on',\n       'the',\n       'internet',\n       'so',\n       'here',\n       'it',\n       'goesthe',\n       'more',\n       'i',\n       'use',\n       'the',\n       'thing',\n       'the',\n       'less',\n       'i',\n       'like',\n       'it'],\n      'sentiment': 0},\n     {'sentence': ['great', 'charger'], 'sentiment': 1},\n     {'sentence': ['this',\n       'is',\n       'essentially',\n       'a',\n       'communications',\n       'tool',\n       'that',\n       'does',\n       'not',\n       'communicate'],\n      'sentiment': 0},\n     {'sentence': ['works',\n       'like',\n       'a',\n       'charm',\n       'it',\n       'work',\n       'the',\n       'same',\n       'as',\n       'the',\n       'one',\n       'i',\n       'got',\n       'with',\n       'the',\n       'phone'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'still',\n       'maintain',\n       'that',\n       'monkeys',\n       'shouldnt',\n       'make',\n       'headphones',\n       'we',\n       'just',\n       'obviously',\n       'dont',\n       'share',\n       'enough',\n       'dna',\n       'to',\n       'copy',\n       'the',\n       'design',\n       'over',\n       'to',\n       'humans'],\n      'sentiment': 0},\n     {'sentence': ['great', 'value'], 'sentiment': 1},\n     {'sentence': ['doesnt',\n       'work',\n       'at',\n       'all',\n       'i',\n       'bougth',\n       'it',\n       'for',\n       'my',\n       'l7c',\n       'and',\n       'its',\n       'not',\n       'working'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'look',\n       'of',\n       'it',\n       'is',\n       'very',\n       'sharp',\n       'and',\n       'the',\n       'screen',\n       'is',\n       'nice',\n       'and',\n       'clear',\n       'with',\n       'great',\n       'graphics'],\n      'sentiment': 1},\n     {'sentence': ['doesnt', 'last', 'long'], 'sentiment': 0},\n     {'sentence': ['one',\n       'thing',\n       'i',\n       'hate',\n       'is',\n       'the',\n       'mode',\n       'set',\n       'button',\n       'at',\n       'the',\n       'side'],\n      'sentiment': 0},\n     {'sentence': ['excellent', 'service'], 'sentiment': 1},\n     {'sentence': ['thank', 'you', 'for', 'wasting', 'my', 'money'],\n      'sentiment': 0},\n     {'sentence': ['how',\n       'can',\n       'that',\n       'bethe',\n       'audio',\n       'quality',\n       'is',\n       'poor'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'igo',\n       'chargers',\n       'and',\n       'tips',\n       'are',\n       'really',\n       'great'],\n      'sentiment': 1},\n     {'sentence': ['the',\n       'file',\n       'browser',\n       'offers',\n       'all',\n       'the',\n       'options',\n       'that',\n       'one',\n       'needshandsfree',\n       'is',\n       'great'],\n      'sentiment': 1},\n     {'sentence': ['superb', 'phone', 'on', 'a', 'great', 'network'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'connected',\n       'my',\n       'wifes',\n       'bluetoothmotorola',\n       'hs850',\n       'to',\n       'my',\n       'phone',\n       'and',\n       'it',\n       'worked',\n       'like',\n       'a',\n       'charm',\n       'whether',\n       'the',\n       'phone',\n       'was',\n       'in',\n       'my',\n       'pocket',\n       'or',\n       'the',\n       'case'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'put',\n       'the',\n       'latest',\n       'os',\n       'on',\n       'it',\n       'v115g',\n       'and',\n       'it',\n       'now',\n       'likes',\n       'to',\n       'slow',\n       'to',\n       'a',\n       'crawl',\n       'and',\n       'lock',\n       'up',\n       'every',\n       'once',\n       'in',\n       'a',\n       'while'],\n      'sentiment': 0},\n     {'sentence': ['it',\n       'only',\n       'recognizes',\n       'the',\n       'phone',\n       'as',\n       'its',\n       'storage',\n       'device'],\n      'sentiment': 0},\n     {'sentence': ['if',\n       'you',\n       'like',\n       'a',\n       'loud',\n       'buzzing',\n       'to',\n       'override',\n       'all',\n       'your',\n       'conversations',\n       'then',\n       'this',\n       'phone',\n       'is',\n       'for',\n       'you'],\n      'sentiment': 0},\n     {'sentence': ['dont', 'buy', 'this', 'product'], 'sentiment': 0},\n     {'sentence': ['ive',\n       'had',\n       'this',\n       'bluetoooth',\n       'headset',\n       'for',\n       'some',\n       'time',\n       'now',\n       'and',\n       'still',\n       'not',\n       'comfortable',\n       'with',\n       'the',\n       'way',\n       'it',\n       'fits',\n       'on',\n       'the',\n       'ear'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'sound',\n       'quality',\n       'is',\n       'good',\n       'and',\n       'functionality',\n       'is',\n       'awesome'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'have',\n       'this',\n       'phone',\n       'and',\n       'it',\n       'is',\n       'a',\n       'thorn',\n       'in',\n       'my',\n       'side',\n       'i',\n       'really',\n       'abhor',\n       'it'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'recently',\n       'had',\n       'problems',\n       'where',\n       'i',\n       'could',\n       'not',\n       'stay',\n       'connected',\n       'for',\n       'more',\n       'than',\n       '10',\n       'minutes',\n       'before',\n       'being',\n       'disconnected'],\n      'sentiment': 0},\n     {'sentence': ['incredible'], 'sentiment': 1},\n     {'sentence': ['design', 'flaw'], 'sentiment': 0},\n     {'sentence': ['great', 'phone'], 'sentiment': 1},\n     {'sentence': ['waste', 'of', '13', 'bucks'], 'sentiment': 0},\n     {'sentence': ['but',\n       'when',\n       'i',\n       'check',\n       'voice',\n       'mail',\n       'at',\n       'night',\n       'the',\n       'keypad',\n       'backlight',\n       'turns',\n       'off',\n       'a',\n       'few',\n       'seconds',\n       'into',\n       'the',\n       'first',\n       'message',\n       'and',\n       'then',\n       'im',\n       'lost'],\n      'sentiment': 0},\n     {'sentence': ['the', 'replacement', 'died', 'in', 'a', 'few', 'weeks'],\n      'sentiment': 0},\n     {'sentence': ['any', 'ring', 'toneoverall', 'good', 'phone', 'to', 'buy'],\n      'sentiment': 1},\n     {'sentence': ['lately',\n       'they',\n       'have',\n       'been',\n       'extremely',\n       'nice',\n       'and',\n       'helpful',\n       'on',\n       'the',\n       'phone'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'have',\n       'had',\n       'problems',\n       'wit',\n       'hit',\n       'dropping',\n       'signal',\n       'and',\n       'more'],\n      'sentiment': 0},\n     {'sentence': ['not', 'impressed'], 'sentiment': 0},\n     {'sentence': ['light',\n       'weight',\n       'i',\n       'hardly',\n       'notice',\n       'it',\n       'is',\n       'there'],\n      'sentiment': 1},\n     {'sentence': ['youll', 'love', 'how', 'thin', 'it', 'is'], 'sentiment': 1},\n     {'sentence': ['bad', 'choice'], 'sentiment': 0},\n     {'sentence': ['the', 'pleather', 'case', 'doesnt', 'fit'], 'sentiment': 0},\n     {'sentence': ['useless', 'phone', 'simply', 'deaf'], 'sentiment': 0},\n     {'sentence': ['the',\n       'color',\n       'is',\n       'even',\n       'prettier',\n       'than',\n       'i',\n       'thought',\n       'it',\n       'would',\n       'be',\n       'and',\n       'the',\n       'graphics',\n       'are',\n       'incredibly',\n       'sharp'],\n      'sentiment': 1},\n     {'sentence': ['all',\n       'in',\n       'all',\n       'i',\n       'think',\n       'it',\n       'was',\n       'a',\n       'good',\n       'investment'],\n      'sentiment': 1},\n     {'sentence': ['it',\n       'makes',\n       'very',\n       'strange',\n       'ticking',\n       'noises',\n       'before',\n       'it',\n       'ends',\n       'the',\n       'call'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'best',\n       'electronics',\n       'of',\n       'the',\n       'available',\n       'fm',\n       'transmitters'],\n      'sentiment': 1},\n     {'sentence': ['battery', 'lasts', 'only', 'a', 'few', 'hours'],\n      'sentiment': 0},\n     {'sentence': ['great', 'headset', 'very', 'impressed', '', 'h500'],\n      'sentiment': 1},\n     {'sentence': ['the',\n       '12',\n       'mega',\n       'pixel',\n       'camera',\n       'being',\n       'a',\n       'part',\n       'of',\n       'a',\n       'phone',\n       'is',\n       'reasonably',\n       'good7'],\n      'sentiment': 1},\n     {'sentence': ['ive',\n       'had',\n       'this',\n       'for',\n       'nearly',\n       '2',\n       'years',\n       'and',\n       'it',\n       'has',\n       'worked',\n       'great',\n       'for',\n       'me'],\n      'sentiment': 1},\n     {'sentence': ['good', 'transmit', 'audio'], 'sentiment': 1},\n     {'sentence': ['we', 'are', 'sending', 'it', 'back'], 'sentiment': 0},\n     {'sentence': ['i',\n       'did',\n       'not',\n       'bother',\n       'contacting',\n       'the',\n       'company',\n       'for',\n       'few',\n       'dollar',\n       'product',\n       'but',\n       'i',\n       'learned',\n       'the',\n       'lesson',\n       'that',\n       'i',\n       'should',\n       'not',\n       'have',\n       'bought',\n       'this',\n       'form',\n       'online',\n       'anyway'],\n      'sentiment': 0},\n     {'sentence': ['if',\n       'you',\n       'hate',\n       'earbugs',\n       'avoid',\n       'this',\n       'phone',\n       'by',\n       'all',\n       'means'],\n      'sentiment': 0},\n     {'sentence': ['great', 'price', 'also'], 'sentiment': 1},\n     {'sentence': ['the',\n       'range',\n       'is',\n       'very',\n       'decent',\n       'ive',\n       'been',\n       'able',\n       'to',\n       'roam',\n       'around',\n       'my',\n       'house',\n       'with',\n       'the',\n       'phone',\n       'in',\n       'the',\n       'living',\n       'room',\n       'with',\n       'no',\n       'receptionsound',\n       'quality',\n       'issues'],\n      'sentiment': 1},\n     {'sentence': ['fast', 'service'], 'sentiment': 1},\n     {'sentence': ['i', 'would', 'highly', 'recommend', 'this'], 'sentiment': 1},\n     {'sentence': ['i', 'would', 'recommend', 'this'], 'sentiment': 1},\n     {'sentence': ['i',\n       'also',\n       'didnt',\n       'like',\n       'the',\n       'on',\n       'button',\n       'it',\n       'felt',\n       'like',\n       'it',\n       'would',\n       'crack',\n       'with',\n       'use'],\n      'sentiment': 0},\n     {'sentence': ['worst', 'phone', 'ever'], 'sentiment': 0},\n     {'sentence': ['im', 'still', 'infatuated', 'with', 'this', 'phone'],\n      'sentiment': 1},\n     {'sentence': ['freezes', 'frequently4'], 'sentiment': 0},\n     {'sentence': ['its',\n       'kind',\n       'of',\n       'embarrassing',\n       'to',\n       'use',\n       'because',\n       'of',\n       'how',\n       'it',\n       'looks',\n       'and',\n       'mostly',\n       'its',\n       'embarrassing',\n       'how',\n       'childlike',\n       'the',\n       'company',\n       'is'],\n      'sentiment': 0},\n     {'sentence': ['simple', 'lightweight', 'and', 'great', 'fit'],\n      'sentiment': 1},\n     {'sentence': ['all',\n       'in',\n       'all',\n       'id',\n       'expected',\n       'a',\n       'better',\n       'consumer',\n       'experience',\n       'from',\n       'motorola'],\n      'sentiment': 0},\n     {'sentence': ['theres',\n       'a',\n       'horrible',\n       'tick',\n       'sound',\n       'in',\n       'the',\n       'background',\n       'on',\n       'all',\n       'my',\n       'calls',\n       'that',\n       'i',\n       'have',\n       'never',\n       'experienced',\n       'before'],\n      'sentiment': 0},\n     {'sentence': ['these',\n       'are',\n       'certainly',\n       'very',\n       'comfortable',\n       'and',\n       'functionality',\n       'is',\n       'decent'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'usually',\n       'dont',\n       'like',\n       'headbands',\n       'but',\n       'this',\n       'one',\n       'is',\n       'very',\n       'lightweight',\n       '',\n       'doesnt',\n       'mess',\n       'up',\n       'my',\n       'hair'],\n      'sentiment': 1},\n     {'sentence': ['im', 'a', 'bit', 'disappointed'], 'sentiment': 0},\n     {'sentence': ['i',\n       'have',\n       'had',\n       'this',\n       'phone',\n       'for',\n       'over',\n       'a',\n       'year',\n       'now',\n       'and',\n       'i',\n       'will',\n       'tell',\n       'you',\n       'its',\n       'not',\n       'that',\n       'great'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'ordered',\n       'this',\n       'for',\n       'sony',\n       'ericsson',\n       'w810i',\n       'but',\n       'i',\n       'think',\n       'it',\n       'only',\n       'worked',\n       'once',\n       'thats',\n       'when',\n       'i',\n       'first',\n       'used',\n       'it'],\n      'sentiment': 0},\n     {'sentence': ['the', 'battery', 'is', 'completely', 'useless', 'to', 'me'],\n      'sentiment': 0},\n     {'sentence': ['what', 'a', 'big', 'waste', 'of', 'time'], 'sentiment': 0},\n     {'sentence': ['dont', 'waste', 'your', '', 'on', 'this', 'one'],\n      'sentiment': 0},\n     {'sentence': ['great', 'sound', 'and', 'service'], 'sentiment': 1},\n     {'sentence': ['really', 'pleased', 'with', 'this', 'product', 'so', 'far'],\n      'sentiment': 1},\n     {'sentence': ['one', 'of', 'my', 'favorite', 'purchases', 'ever'],\n      'sentiment': 1},\n     {'sentence': ['best', 'bluetooth', 'on', 'the', 'market'], 'sentiment': 1},\n     {'sentence': ['authentic',\n       'leather',\n       'with',\n       'nice',\n       'shine',\n       'and',\n       'comfort',\n       'i',\n       'recommend',\n       'you',\n       'this',\n       'case',\n       ''],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'was',\n       'very',\n       'excited',\n       'to',\n       'get',\n       'this',\n       'headset',\n       'because',\n       'i',\n       'thought',\n       'it',\n       'was',\n       'really',\n       'cute'],\n      'sentiment': 1},\n     {'sentence': ['do', 'not', 'make', 'the', 'same', 'mistake', 'as', 'me'],\n      'sentiment': 0},\n     {'sentence': ['big', 'disappointment', 'with', 'calendar', 'sync'],\n      'sentiment': 0},\n     {'sentence': ['the', 'phone', 'was', 'unusable', 'and', 'was', 'not', 'new'],\n      'sentiment': 0},\n     {'sentence': ['worst', 'customer', 'service', 'ever'], 'sentiment': 0},\n     {'sentence': ['no',\n       'additional',\n       'ear',\n       'gels',\n       'provided',\n       'and',\n       'no',\n       'instructions',\n       'whatsoever'],\n      'sentiment': 0},\n     {'sentence': ['it',\n       'defeats',\n       'the',\n       'purpose',\n       'of',\n       'a',\n       'bluetooth',\n       'headset'],\n      'sentiment': 0},\n     {'sentence': ['worth', 'every', 'penny'], 'sentiment': 1},\n     {'sentence': ['excellent', 'wallet', 'type', 'phone', 'case'],\n      'sentiment': 1},\n     {'sentence': ['nice',\n       'headphones',\n       'for',\n       'the',\n       'price',\n       'and',\n       'they',\n       'work',\n       'great'],\n      'sentiment': 1},\n     {'sentence': ['internet', 'is', 'excrutiatingly', 'slow'], 'sentiment': 0},\n     {'sentence': ['it',\n       'is',\n       'very',\n       'comfortable',\n       'to',\n       'wear',\n       'as',\n       'well',\n       'which',\n       'is',\n       'probably',\n       'the',\n       'most',\n       'important',\n       'aspect',\n       'about',\n       'using',\n       'a',\n       'case'],\n      'sentiment': 1},\n     {'sentence': ['its',\n       'fits',\n       'like',\n       'a',\n       'glove',\n       'and',\n       'is',\n       'strong',\n       'secure',\n       'and',\n       'durable'],\n      'sentiment': 1},\n     {'sentence': ['o',\n       'my',\n       'gosh',\n       'the',\n       'best',\n       'phone',\n       'i',\n       'have',\n       'ever',\n       'had'],\n      'sentiment': 1},\n     {'sentence': ['its',\n       'very',\n       'attractive',\n       'and',\n       'appears',\n       'to',\n       'be',\n       'of',\n       'good',\n       'quality'],\n      'sentiment': 1},\n     {'sentence': ['i', 'love', 'all', 'the', 'features', 'and', 'form', 'factor'],\n      'sentiment': 1},\n     {'sentence': ['this',\n       'product',\n       'had',\n       'a',\n       'strong',\n       'rubberpetroleum',\n       'smell',\n       'that',\n       'was',\n       'unbearable',\n       'after',\n       'a',\n       'while',\n       'and',\n       'caused',\n       'me',\n       'to',\n       'return',\n       'it'],\n      'sentiment': 0},\n     {'sentence': ['poor', 'quality', 'and', 'service'], 'sentiment': 0},\n     {'sentence': ['the',\n       'cable',\n       'looks',\n       'so',\n       'thin',\n       'and',\n       'flimsy',\n       'it',\n       'is',\n       'scary'],\n      'sentiment': 0},\n     {'sentence': ['great', 'earpiece'], 'sentiment': 1},\n     {'sentence': ['excellent', 'hands', 'free', 'tool'], 'sentiment': 1},\n     {'sentence': ['great', 'for', 'using', 'with', 'your', 'home', 'stereo'],\n      'sentiment': 1},\n     {'sentence': ['good', 'product', '', 'incredible', 'value'], 'sentiment': 1},\n     {'sentence': ['only',\n       'had',\n       'this',\n       'a',\n       'month',\n       'but',\n       'its',\n       'worked',\n       'flawlessly',\n       'so',\n       'far'],\n      'sentiment': 1},\n     {'sentence': ['works', 'great'], 'sentiment': 1},\n     {'sentence': ['absolutel', 'junk'], 'sentiment': 0},\n     {'sentence': ['that', 'one', 'didnt', 'work', 'either'], 'sentiment': 0},\n     {'sentence': ['battery', 'life', 'is', 'real', 'good'], 'sentiment': 1},\n     {'sentence': ['returned', '8', 'hours', 'later'], 'sentiment': 0},\n     {'sentence': ['its', 'a', 'great', 'item'], 'sentiment': 1},\n     {'sentence': ['dont', 'waste', 'your', 'money'], 'sentiment': 0},\n     {'sentence': ['love', 'this', 'headset'], 'sentiment': 1},\n     {'sentence': ['not',\n       'only',\n       'will',\n       'it',\n       'drain',\n       'your',\n       'player',\n       'but',\n       'may',\n       'also',\n       'potentially',\n       'fry',\n       'it'],\n      'sentiment': 0},\n     {'sentence': ['worked', 'perfectly'], 'sentiment': 1},\n     {'sentence': ['unreliable', '', 'im', 'giving', 'up'], 'sentiment': 0},\n     {'sentence': ['i',\n       'gave',\n       'it',\n       '5',\n       'stars',\n       'because',\n       'of',\n       'the',\n       'sound',\n       'quality'],\n      'sentiment': 1},\n     {'sentence': ['avoid', 'this', 'one', 'if', 'you', 'can'], 'sentiment': 0},\n     {'sentence': ['reversible', 'plug', 'works', 'great'], 'sentiment': 1},\n     {'sentence': ['i',\n       'wasted',\n       'my',\n       'little',\n       'money',\n       'with',\n       'this',\n       'earpiece'],\n      'sentiment': 0},\n     {'sentence': ['very', 'good', 'phone'], 'sentiment': 1},\n     {'sentence': ['best',\n       'of',\n       'all',\n       'is',\n       'the',\n       'rotating',\n       'feature',\n       'very',\n       'helpful'],\n      'sentiment': 1},\n     {'sentence': ['comfort', 'for', 'our', 'whole', 'family'], 'sentiment': 1},\n     {'sentence': ['good', 'product', 'good', 'seller'], 'sentiment': 1},\n     {'sentence': ['i', 'love', 'this', 'bluetooth'], 'sentiment': 1},\n     {'sentence': ['first', 'of', 'all', 'it', 'doesnt', 'wear', 'well'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'am',\n       'very',\n       'impressed',\n       'with',\n       'this',\n       'headset',\n       'from',\n       'plantronics'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'got',\n       'it',\n       'because',\n       'it',\n       'was',\n       'so',\n       'small',\n       'and',\n       'adorable'],\n      'sentiment': 1},\n     {'sentence': ['great', 'phone'], 'sentiment': 1},\n     {'sentence': ['i', 'wouldnt', 'recommend', 'buying', 'this', 'product'],\n      'sentiment': 0},\n     {'sentence': ['piece', 'of', 'junk'], 'sentiment': 0},\n     {'sentence': ['poorly', 'contstruct', 'hinge'], 'sentiment': 0},\n     {'sentence': ['this',\n       'item',\n       'is',\n       'great',\n       'installed',\n       'it',\n       'let',\n       'it',\n       'charged',\n       'up',\n       'overnite',\n       'and',\n       'it',\n       'has',\n       'been',\n       'working',\n       'good',\n       'every',\n       'since',\n       'with',\n       'no',\n       'problems'],\n      'sentiment': 1},\n     {'sentence': ['great', 'phone'], 'sentiment': 1},\n     {'sentence': ['dont', 'buy', 'it'], 'sentiment': 0},\n     {'sentence': ['excellent', 'phone'], 'sentiment': 1},\n     {'sentence': ['do', 'not', 'purchase', 'this', 'phone'], 'sentiment': 0},\n     {'sentence': ['the',\n       'voice',\n       'recognition',\n       'thru',\n       'the',\n       'handset',\n       'is',\n       'excellent'],\n      'sentiment': 1},\n     {'sentence': ['this',\n       'is',\n       'hands',\n       'down',\n       'the',\n       'best',\n       'phone',\n       'ive',\n       'ever',\n       'had'],\n      'sentiment': 1},\n     {'sentence': ['works',\n       'great',\n       'when',\n       'my',\n       'cat',\n       'attacked',\n       'the',\n       'phone',\n       'he',\n       'scratched',\n       'the',\n       'protective',\n       'strip',\n       'instead',\n       'of',\n       'destroying',\n       'the',\n       'screen'],\n      'sentiment': 1},\n     {'sentence': ['this', 'one', 'works', 'and', 'was', 'priced', 'right'],\n      'sentiment': 1},\n     {'sentence': ['customer', 'service', 'was', 'terrible'], 'sentiment': 0},\n     {'sentence': ['battery',\n       'life',\n       'still',\n       'not',\n       'long',\n       'enough',\n       'in',\n       'motorola',\n       'razor',\n       'v3i'],\n      'sentiment': 0},\n     {'sentence': ['sending', 'it', 'back'], 'sentiment': 0},\n     {'sentence': ['now',\n       'i',\n       'know',\n       'that',\n       'i',\n       'made',\n       'a',\n       'wise',\n       'decision'],\n      'sentiment': 1},\n     {'sentence': ['someone', 'shouldve', 'invented', 'this', 'sooner'],\n      'sentiment': 1},\n     {'sentence': ['good', 'price'], 'sentiment': 1},\n     {'sentence': ['everything',\n       'worked',\n       'on',\n       'the',\n       'first',\n       'trythe',\n       'device',\n       'was',\n       'certainly',\n       'engineered',\n       'in',\n       'a',\n       'clever',\n       'way',\n       'and',\n       'the',\n       'construction',\n       'feels',\n       'good'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'received',\n       'it',\n       'quickly',\n       'and',\n       'it',\n       'works',\n       'great'],\n      'sentiment': 1},\n     {'sentence': ['has', 'been', 'working', 'great'], 'sentiment': 1},\n     {'sentence': ['as',\n       'many',\n       'people',\n       'complained',\n       'i',\n       'found',\n       'this',\n       'headsets',\n       'microphone',\n       'was',\n       'very',\n       'weak'],\n      'sentiment': 0},\n     {'sentence': ['my',\n       '5year',\n       'old',\n       'nokia',\n       '2160',\n       'from',\n       'tracfone',\n       'holds',\n       'the',\n       'charge',\n       'a',\n       'lot',\n       'better',\n       'than',\n       'this'],\n      'sentiment': 0},\n     {'sentence': ['they',\n       'do',\n       'not',\n       'care',\n       'about',\n       'the',\n       'consumer',\n       'one',\n       'bit'],\n      'sentiment': 0},\n     {'sentence': ['this',\n       'is',\n       'a',\n       'good',\n       'battery',\n       'and',\n       'it',\n       'got',\n       'here',\n       'really',\n       'fast'],\n      'sentiment': 1},\n     {'sentence': ['the', 'instruction', 'manual', 'is', 'lacking'],\n      'sentiment': 0},\n     {'sentence': ['also',\n       'its',\n       'slim',\n       'enough',\n       'to',\n       'fit',\n       'into',\n       'my',\n       'alarm',\n       'clock',\n       'docking',\n       'station',\n       'without',\n       'removing',\n       'the',\n       'case'],\n      'sentiment': 1},\n     {'sentence': ['phone',\n       'now',\n       'holds',\n       'charge',\n       'like',\n       'it',\n       'did',\n       'when',\n       'it',\n       'was',\n       'new'],\n      'sentiment': 1},\n     {'sentence': ['the',\n       'battery',\n       'is',\n       'unreliable',\n       'as',\n       'well',\n       'as',\n       'the',\n       'service',\n       'use',\n       'antena'],\n      'sentiment': 0},\n     {'sentence': ['its',\n       'uncomfortable',\n       'and',\n       'the',\n       'sound',\n       'quality',\n       'is',\n       'quite',\n       'poor',\n       'compared',\n       'with',\n       'the',\n       'phone',\n       'razr',\n       'or',\n       'with',\n       'my',\n       'previous',\n       'wired',\n       'headset',\n       'that',\n       'plugged',\n       'into',\n       'an',\n       'lg'],\n      'sentiment': 0},\n     {'sentence': ['we',\n       'have',\n       'gotten',\n       'a',\n       'lot',\n       'of',\n       'compliments',\n       'on',\n       'it'],\n      'sentiment': 1},\n     {'sentence': ['this',\n       'is',\n       'definitely',\n       'a',\n       'must',\n       'have',\n       'if',\n       'your',\n       'state',\n       'does',\n       'not',\n       'allow',\n       'cell',\n       'phone',\n       'usage',\n       'while',\n       'driving'],\n      'sentiment': 1},\n     {'sentence': ['i', 'want', 'my', 'money', 'back'], 'sentiment': 0},\n     {'sentence': ['i', 'love', 'this', 'device'], 'sentiment': 1},\n     {'sentence': ['i', 'am', 'also', 'very', 'happy', 'with', 'the', 'price'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'ordered',\n       'this',\n       'product',\n       'first',\n       'and',\n       'was',\n       'unhappy',\n       'with',\n       'it',\n       'immediately'],\n      'sentiment': 0},\n     {'sentence': ['the', 'ngage', 'is', 'still', 'lacking', 'in', 'earbuds'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'was',\n       'able',\n       'to',\n       'do',\n       'voice',\n       'dialing',\n       'in',\n       'the',\n       'car',\n       'with',\n       'no',\n       'problem'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'have',\n       '23',\n       'bars',\n       'on',\n       'my',\n       'cell',\n       'phone',\n       'when',\n       'i',\n       'am',\n       'home',\n       'but',\n       'you',\n       'cant',\n       'not',\n       'hear',\n       'anything'],\n      'sentiment': 0},\n     {'sentence': ['good', 'item', 'low', 'price'], 'sentiment': 1},\n     {'sentence': ['howeverthe',\n       'riingtones',\n       'are',\n       'not',\n       'the',\n       'best',\n       'and',\n       'neither',\n       'are',\n       'the',\n       'games'],\n      'sentiment': 0},\n     {'sentence': ['the', 'plug', 'did', 'not', 'work', 'very', 'well'],\n      'sentiment': 0},\n     {'sentence': ['amazon', 'sucks'], 'sentiment': 0},\n     {'sentence': ['rip', 'off', 'over', 'charge', 'shipping'], 'sentiment': 0},\n     {'sentence': ['very', 'comfortable'], 'sentiment': 1},\n     {'sentence': ['the',\n       'battery',\n       'is',\n       'working',\n       'well',\n       'as',\n       'a',\n       'replacement',\n       'for',\n       'the',\n       'original',\n       'that',\n       'came',\n       'with',\n       'the',\n       'phone',\n       'over',\n       '2',\n       'years',\n       'ago'],\n      'sentiment': 1},\n     {'sentence': ['the', 'reception', 'is', 'excellent'], 'sentiment': 1},\n     {'sentence': ['it',\n       'fits',\n       'comfortably',\n       'in',\n       'either',\n       'ear',\n       'the',\n       'sound',\n       'is',\n       'clear',\n       'and',\n       'loud',\n       'and',\n       'the',\n       'charge',\n       'lasts',\n       'a',\n       'couple',\n       'of',\n       'days'],\n      'sentiment': 1},\n     {'sentence': ['very',\n       'clear',\n       'quality',\n       'sound',\n       'and',\n       'you',\n       'dont',\n       'have',\n       'to',\n       'mess',\n       'with',\n       'the',\n       'sound',\n       'on',\n       'your',\n       'ipod',\n       'since',\n       'you',\n       'have',\n       'the',\n       'sound',\n       'buttons',\n       'on',\n       'the',\n       'headset'],\n      'sentiment': 1},\n     {'sentence': ['1',\n       'long',\n       'lasting',\n       'battery',\n       'you',\n       'dont',\n       'have',\n       'to',\n       'recharge',\n       'it',\n       'as',\n       'frequentyly',\n       'as',\n       'some',\n       'of',\n       'the',\n       'flip',\n       'phones2'],\n      'sentiment': 0},\n     {'sentence': ['obviously',\n       'there',\n       'is',\n       'a',\n       'problem',\n       'with',\n       'the',\n       'adhesive'],\n      'sentiment': 0},\n     {'sentence': ['very', 'disappointing'], 'sentiment': 0},\n     {'sentence': ['it',\n       'was',\n       'an',\n       'inexpensive',\n       'piece',\n       'but',\n       'i',\n       'would',\n       'still',\n       'have',\n       'expected',\n       'better',\n       'quality'],\n      'sentiment': 0},\n     {'sentence': ['it',\n       'is',\n       'practically',\n       'useless',\n       'and',\n       'did',\n       'not',\n       'add',\n       'any',\n       'kind',\n       'of',\n       'boost',\n       'to',\n       'my',\n       'reception',\n       'after',\n       'i',\n       'bought',\n       'it'],\n      'sentiment': 0},\n     {'sentence': ['excellent', 'sound', 'quality'], 'sentiment': 1},\n     {'sentence': ['was', 'not', 'happy'], 'sentiment': 0},\n     {'sentence': ['a',\n       'piece',\n       'of',\n       'junk',\n       'that',\n       'broke',\n       'after',\n       'being',\n       'on',\n       'my',\n       'phone',\n       'for',\n       '2',\n       'days'],\n      'sentiment': 0},\n     {'sentence': ['new', 'battery', 'works', 'great', 'in', 'phone'],\n      'sentiment': 1},\n     {'sentence': ['worst', 'customer', 'service'], 'sentiment': 0},\n     {'sentence': ['ive',\n       'dropped',\n       'my',\n       'phone',\n       'more',\n       'times',\n       'than',\n       'i',\n       'can',\n       'say',\n       'even',\n       'on',\n       'concrete',\n       'and',\n       'my',\n       'phone',\n       'is',\n       'still',\n       'great',\n       'knock',\n       'on',\n       'wood'],\n      'sentiment': 1},\n     {'sentence': ['reception', 'is', 'terrible', 'and', 'full', 'of', 'static'],\n      'sentiment': 0},\n     {'sentence': ['good', 'audio', 'quality'], 'sentiment': 1},\n     {'sentence': ['this',\n       'little',\n       'device',\n       'has',\n       'transformed',\n       'my',\n       'organizational',\n       'capability',\n       'and',\n       'made',\n       'my',\n       'life',\n       'a',\n       'whole',\n       'lot',\n       'easier'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'was',\n       'sitting',\n       'in',\n       'my',\n       'vehicle',\n       'with',\n       'the',\n       'cradle',\n       'on',\n       'my',\n       'belt',\n       'and',\n       'the',\n       'headset',\n       'lost',\n       'signal'],\n      'sentiment': 0},\n     {'sentence': ['were', 'jerks', 'on', 'the', 'phone'], 'sentiment': 0},\n     {'sentence': ['works', 'like', 'a', 'charm', 'works', 'as', 'advertised'],\n      'sentiment': 1},\n     {'sentence': ['comfortable', 'nice', 'range', 'good', 'battery', 'life'],\n      'sentiment': 1},\n     {'sentence': ['their',\n       'network',\n       'coverage',\n       'in',\n       'los',\n       'angeles',\n       'is',\n       'horrible'],\n      'sentiment': 0},\n     {'sentence': ['excellent', 'starter', 'wireless', 'headset'], 'sentiment': 0},\n     {'sentence': ['the',\n       'loudspeaker',\n       'option',\n       'is',\n       'great',\n       'the',\n       'bumpers',\n       'with',\n       'the',\n       'lights',\n       'is',\n       'very',\n       '',\n       'appealing'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'only',\n       'thing',\n       'that',\n       'i',\n       'think',\n       'could',\n       'improve',\n       'is',\n       'the',\n       'sound',\n       'leaks',\n       'out',\n       'from',\n       'the',\n       'headset'],\n      'sentiment': 0},\n     {'sentence': ['first',\n       'off',\n       'the',\n       'reception',\n       'sucks',\n       'i',\n       'have',\n       'never',\n       'had',\n       'more',\n       'than',\n       '2',\n       'bars',\n       'ever'],\n      'sentiment': 0},\n     {'sentence': ['the', 'phone', 'gets', 'extremely', 'hot'], 'sentiment': 0},\n     {'sentence': ['the',\n       'microphone',\n       'also',\n       'works',\n       'well',\n       'but',\n       'according',\n       'to',\n       'people',\n       'i',\n       'have',\n       'called',\n       'it',\n       'applifies',\n       'everything'],\n      'sentiment': 1},\n     {'sentence': ['nice', 'design', 'and', 'quality'], 'sentiment': 1},\n     {'sentence': ['also',\n       'if',\n       'your',\n       'phone',\n       'is',\n       'dropped',\n       'this',\n       'case',\n       'is',\n       'not',\n       'going',\n       'to',\n       'save',\n       'it',\n       'specially',\n       'when',\n       'dropped',\n       'face',\n       'down'],\n      'sentiment': 0},\n     {'sentence': ['it',\n       'is',\n       'light',\n       'easy',\n       'to',\n       'use',\n       'and',\n       'has',\n       'very',\n       'clear',\n       'reception',\n       'and',\n       'transmission'],\n      'sentiment': 1},\n     {'sentence': ['bad', 'fit', 'way', 'too', 'big'], 'sentiment': 0},\n     {'sentence': ['it',\n       'definitely',\n       'was',\n       'not',\n       'as',\n       'good',\n       'as',\n       'my',\n       's11'],\n      'sentiment': 1},\n     {'sentence': ['awesome', 'device'], 'sentiment': 1},\n     {'sentence': ['waste', 'of', 'money'], 'sentiment': 0},\n     {'sentence': ['i',\n       'had',\n       'ordered',\n       'a',\n       'motorola',\n       'data',\n       'cable',\n       'got',\n       'a',\n       'very',\n       'well',\n       'finished',\n       'and',\n       'working',\n       'product'],\n      'sentiment': 1},\n     {'sentence': ['love', 'this', 'phone'], 'sentiment': 1},\n     {'sentence': ['i',\n       'was',\n       'looking',\n       'for',\n       'this',\n       'headset',\n       'for',\n       'a',\n       'long',\n       'time',\n       'and',\n       'now',\n       'that',\n       'ive',\n       'got',\n       'it',\n       'i',\n       'couldnt',\n       'be',\n       'happier'],\n      'sentiment': 1},\n     {'sentence': ['ill',\n       'be',\n       'drivng',\n       'along',\n       'and',\n       'my',\n       'headset',\n       'starts',\n       'ringing',\n       'for',\n       'no',\n       'reason'],\n      'sentiment': 0},\n     {'sentence': ['display',\n       'is',\n       'excellent',\n       'and',\n       'camera',\n       'is',\n       'as',\n       'good',\n       'as',\n       'any',\n       'from',\n       'that',\n       'year'],\n      'sentiment': 1},\n     {'sentence': ['battery', 'life', 'is', 'also', 'great'], 'sentiment': 1},\n     {'sentence': ['the',\n       'worst',\n       'phone',\n       'ive',\n       'ever',\n       'had',\n       'only',\n       'had',\n       'it',\n       'for',\n       'a',\n       'few',\n       'months'],\n      'sentiment': 0},\n     {'sentence': ['not',\n       'a',\n       'good',\n       'item',\n       'it',\n       'worked',\n       'for',\n       'a',\n       'while',\n       'then',\n       'started',\n       'having',\n       'problems',\n       'in',\n       'my',\n       'auto',\n       'reverse',\n       'tape',\n       'player'],\n      'sentiment': 0},\n     {'sentence': ['this',\n       'is',\n       'so',\n       'embarassing',\n       'and',\n       'also',\n       'my',\n       'ears',\n       'hurt',\n       'if',\n       'i',\n       'try',\n       'to',\n       'push',\n       'the',\n       'ear',\n       'plug',\n       'into',\n       'my',\n       'ear'],\n      'sentiment': 0},\n     {'sentence': ['protects', 'the', 'phone', 'on', 'all', 'sides'],\n      'sentiment': 1},\n     {'sentence': ['this',\n       'is',\n       'a',\n       'very',\n       'average',\n       'phone',\n       'with',\n       'bad',\n       'battery',\n       'life',\n       'that',\n       'operates',\n       'on',\n       'a',\n       'weak',\n       'network'],\n      'sentiment': 0},\n     {'sentence': ['clear',\n       'skype',\n       'calls',\n       'long',\n       'battery',\n       'life',\n       'long',\n       'range'],\n      'sentiment': 1},\n     {'sentence': ['soyo', 'technology', 'sucks'], 'sentiment': 0},\n     {'sentence': ['great', 'hands', 'free', 'device'], 'sentiment': 1},\n     {'sentence': ['you',\n       'can',\n       'even',\n       'take',\n       'self',\n       'portraits',\n       'with',\n       'the',\n       'outside',\n       'exterior',\n       'display',\n       'very',\n       'cool'],\n      'sentiment': 1},\n     {'sentence': ['same', 'problem', 'as', 'others', 'have', 'mentioned'],\n      'sentiment': 0},\n     {'sentence': ['after',\n       'trying',\n       'many',\n       'many',\n       'handsfree',\n       'gadgets',\n       'this',\n       'is',\n       'the',\n       'one',\n       'that',\n       'finally',\n       'works',\n       'well'],\n      'sentiment': 1},\n     {'sentence': ['magical', 'help'], 'sentiment': 1},\n     {'sentence': ['the',\n       'worst',\n       'piece',\n       'of',\n       'crap',\n       'ever',\n       'along',\n       'with',\n       'the',\n       'verizon',\n       'customer',\n       'service'],\n      'sentiment': 0},\n     {'sentence': ['poor', 'sound', 'quality'], 'sentiment': 0},\n     {'sentence': ['the', 'best', 'phone', 'in', 'market', ''], 'sentiment': 1},\n     {'sentence': ['it', 'worked', 'very', 'well'], 'sentiment': 1},\n     {'sentence': ['the',\n       'company',\n       'shipped',\n       'my',\n       'product',\n       'very',\n       'promptly',\n       'and',\n       'it',\n       'works',\n       'well'],\n      'sentiment': 1},\n     {'sentence': ['exactly', 'what', 'i', 'wanted'], 'sentiment': 1},\n     {'sentence': ['the',\n       'picture',\n       'resolution',\n       'is',\n       'far',\n       'below',\n       'what',\n       'other',\n       'comparablypriced',\n       'phones',\n       'are',\n       'offering',\n       'today'],\n      'sentiment': 0},\n     {'sentence': ['this', 'is', 'a', 'great', 'deal'], 'sentiment': 1},\n     {'sentence': ['excellent',\n       'product',\n       'i',\n       'am',\n       'very',\n       'satisfied',\n       'with',\n       'the',\n       'purchase'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'highly',\n       'recommend',\n       'these',\n       'and',\n       'encourage',\n       'people',\n       'to',\n       'give',\n       'them',\n       'a',\n       'try'],\n      'sentiment': 1},\n     {'sentence': ['better', 'than', 'youd', 'expect'], 'sentiment': 1},\n     {'sentence': ['using',\n       'all',\n       'earpieces',\n       'left',\n       'or',\n       'right',\n       'this',\n       'thing',\n       'will',\n       'not',\n       'stay',\n       'on',\n       'my',\n       'ear'],\n      'sentiment': 0},\n     {'sentence': ['great', 'product', 'and', 'price'], 'sentiment': 1},\n     {'sentence': ['sounds',\n       'good',\n       'reasonably',\n       'priced',\n       'and',\n       'effective',\n       'its',\n       'that',\n       'simple',\n       ''],\n      'sentiment': 1},\n     {'sentence': ['still',\n       'waiting',\n       'im',\n       'sure',\n       'this',\n       'item',\n       'would',\n       'work',\n       'well',\n       'if',\n       'i',\n       'ever',\n       'recieve',\n       'it'],\n      'sentiment': 0},\n     {'sentence': ['what', 'a', 'disappointment'], 'sentiment': 0},\n     {'sentence': ['very', 'prompt', 'service'], 'sentiment': 1},\n     {'sentence': ['excellent', 'product', 'for', 'the', 'price'], 'sentiment': 1},\n     {'sentence': ['very', 'pleased', 'with', 'this', 'headset'], 'sentiment': 1},\n     {'sentence': ['dont', 'waste', 'your', 'money', 'and', 'time'],\n      'sentiment': 0},\n     {'sentence': ['i', 'especially', 'love', 'the', 'long', 'battery', 'life'],\n      'sentiment': 1},\n     {'sentence': ['its',\n       'so',\n       'stupid',\n       'to',\n       'have',\n       'to',\n       'keep',\n       'buying',\n       'new',\n       'chargers',\n       'car',\n       'chargers',\n       'cradles',\n       'headphones',\n       'and',\n       'car',\n       'kits',\n       'every',\n       'time',\n       'a',\n       'new',\n       'phone',\n       'comes',\n       'out'],\n      'sentiment': 0},\n     {'sentence': ['works', 'great'], 'sentiment': 1},\n     {'sentence': ['plantronics', 'bluetooth', 'excelent', 'buy'], 'sentiment': 1},\n     {'sentence': ['i',\n       'came',\n       'over',\n       'from',\n       'verizon',\n       'because',\n       'cingulair',\n       'has',\n       'nicer',\n       'cell',\n       'phones',\n       'the',\n       'first',\n       'thing',\n       'i',\n       'noticed',\n       'was',\n       'the',\n       'really',\n       'bad',\n       'service'],\n      'sentiment': 0},\n     {'sentence': ['ill', 'be', 'looking', 'for', 'a', 'new', 'earpiece'],\n      'sentiment': 0},\n     {'sentence': ['i', 'highly', 'recommend', 'this', 'device', 'to', 'everyone'],\n      'sentiment': 1},\n     {'sentence': ['jawbone', 'era', 'is', 'awesome', 'too'], 'sentiment': 1},\n     {'sentence': ['we',\n       'received',\n       'a',\n       'white',\n       'colored',\n       'battery',\n       'that',\n       'goes',\n       'dead',\n       'after',\n       'a',\n       'couple',\n       'hoursthe',\n       'original',\n       'used',\n       'to',\n       'last',\n       'a',\n       'week',\n       '',\n       'but',\n       'still',\n       'lasts',\n       'longer',\n       'than',\n       'thereplacement'],\n      'sentiment': 0},\n     {'sentence': ['after',\n       'a',\n       'year',\n       'the',\n       'battery',\n       'went',\n       'completely',\n       'dead',\n       'on',\n       'my',\n       'headset'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'have',\n       'used',\n       'several',\n       'phone',\n       'in',\n       'two',\n       'years',\n       'but',\n       'this',\n       'one',\n       'is',\n       'the',\n       'best'],\n      'sentiment': 1},\n     {'sentence': ['an', 'awesome', 'new', 'look', 'for', 'fall', '2000'],\n      'sentiment': 1},\n     {'sentence': ['this',\n       'is',\n       'the',\n       'first',\n       'phone',\n       'ive',\n       'had',\n       'that',\n       'has',\n       'been',\n       'so',\n       'cheaply',\n       'made'],\n      'sentiment': 0},\n     {'sentence': ['att',\n       'is',\n       'not',\n       'clear',\n       'sound',\n       'is',\n       'very',\n       'distorted',\n       'and',\n       'you',\n       'have',\n       'to',\n       'yell',\n       'when',\n       'you',\n       'talk'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'plastic',\n       'breaks',\n       'really',\n       'easy',\n       'on',\n       'this',\n       'clip'],\n      'sentiment': 0},\n     {'sentence': ['price', 'is', 'good', 'too'], 'sentiment': 1},\n     {'sentence': ['dont', 'make', 'the', 'same', 'mistake', 'i', 'did'],\n      'sentiment': 0},\n     {'sentence': ['oh',\n       'and',\n       'i',\n       'forgot',\n       'to',\n       'also',\n       'mention',\n       'the',\n       'weird',\n       'color',\n       'effect',\n       'it',\n       'has',\n       'on',\n       'your',\n       'phone'],\n      'sentiment': 0},\n     {'sentence': ['im',\n       'using',\n       'it',\n       'with',\n       'an',\n       'iriver',\n       'spinn',\n       'with',\n       'case',\n       'and',\n       'it',\n       'fits',\n       'fine'],\n      'sentiment': 1},\n     {'sentence': ['also',\n       'the',\n       'area',\n       'where',\n       'my',\n       'unit',\n       'broke',\n       'im',\n       'not',\n       'too',\n       'fond',\n       'of',\n       'the',\n       'magnetic',\n       'strap'],\n      'sentiment': 0},\n     {'sentence': ['overall',\n       'i',\n       'am',\n       'psyched',\n       'to',\n       'have',\n       'a',\n       'phone',\n       'which',\n       'has',\n       'all',\n       'my',\n       'appointments',\n       'and',\n       'contacts',\n       'in',\n       'and',\n       'gets',\n       'great',\n       'reception'],\n      'sentiment': 1},\n     {'sentence': ['every',\n       'thing',\n       'on',\n       'phone',\n       'work',\n       'perfectly',\n       'she',\n       'like',\n       'it'],\n      'sentiment': 1},\n     {'sentence': ['another',\n       'note',\n       'about',\n       'this',\n       'phones',\n       'appearance',\n       'is',\n       'that',\n       'it',\n       'really',\n       'looks',\n       'rather',\n       'bland',\n       'especially',\n       'in',\n       'the',\n       'all',\n       'black',\n       'model'],\n      'sentiment': 0},\n     {'sentence': ['its', 'really', 'easy'], 'sentiment': 1},\n     {'sentence': ['my',\n       'sanyo',\n       'has',\n       'survived',\n       'dozens',\n       'of',\n       'drops',\n       'on',\n       'blacktop',\n       'without',\n       'ill',\n       'effect'],\n      'sentiment': 1},\n     {'sentence': ['fantastic', 'earphones'], 'sentiment': 1},\n     {'sentence': ['it',\n       'finds',\n       'my',\n       'cell',\n       'phone',\n       'right',\n       'away',\n       'when',\n       'i',\n       'enter',\n       'the',\n       'car'],\n      'sentiment': 1},\n     {'sentence': ['low', 'quality'], 'sentiment': 0},\n     {'sentence': ['i',\n       'highly',\n       'recommend',\n       'this',\n       'modest',\n       'priced',\n       'cellular',\n       'phone'],\n      'sentiment': 1},\n     {'sentence': ['but',\n       'it',\n       'does',\n       'get',\n       'better',\n       'reception',\n       'and',\n       'clarity',\n       'than',\n       'any',\n       'phone',\n       'ive',\n       'had',\n       'before'],\n      'sentiment': 1},\n     {'sentence': ['warning', '', 'stay', 'away'], 'sentiment': 0},\n     {'sentence': ['i',\n       'wish',\n       'i',\n       'could',\n       'return',\n       'the',\n       'unit',\n       'and',\n       'get',\n       'back',\n       'my',\n       'money'],\n      'sentiment': 0},\n     {'sentence': ['awsome', 'device', 'works', 'great'], 'sentiment': 1},\n     {'sentence': ['i',\n       'used',\n       'to',\n       'talk',\n       'on',\n       'it',\n       'for',\n       '1',\n       '',\n       '1',\n       '12',\n       'hours',\n       'and',\n       'the',\n       'battery',\n       'would',\n       'be',\n       'literally',\n       'drained',\n       'and',\n       'dying'],\n      'sentiment': 0},\n     {'sentence': ['if',\n       'you',\n       'dont',\n       'find',\n       'it',\n       'too',\n       'bad',\n       'as',\n       'again',\n       'the',\n       'unit',\n       'comes',\n       'with',\n       'one',\n       'earpad',\n       'onlyi',\n       'would',\n       'not',\n       'recommend',\n       'this',\n       'to',\n       'anyone'],\n      'sentiment': 0},\n     {'sentence': ['very', 'displeased'], 'sentiment': 0},\n     {'sentence': ['i',\n       'might',\n       'have',\n       'gotten',\n       'a',\n       'defect',\n       'but',\n       'i',\n       'would',\n       'not',\n       'risk',\n       'buying',\n       'it',\n       'again',\n       'because',\n       'of',\n       'the',\n       'built',\n       'quality',\n       'alone'],\n      'sentiment': 0},\n     {'sentence': ['they',\n       'made',\n       'this',\n       'case',\n       'too',\n       'small',\n       'and',\n       'is',\n       'very',\n       'difficult',\n       'to',\n       'install'],\n      'sentiment': 0},\n     {'sentence': ['restored', 'my', 'phone', 'to', 'like', 'new', 'performance'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'would',\n       'recommend',\n       'purchasing',\n       'the',\n       'jabra',\n       'jx10',\n       'series',\n       '2',\n       'which',\n       'works',\n       'flawlessly',\n       'with',\n       'my',\n       'moto',\n       'q',\n       'go',\n       'figure'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'searched',\n       'the',\n       'internet',\n       'and',\n       'found',\n       'this',\n       'one',\n       'to',\n       'be',\n       'the',\n       'best',\n       'value'],\n      'sentiment': 1},\n     {'sentence': ['does', 'not', 'fit'], 'sentiment': 0},\n     {'sentence': ['very', 'happy', 'with', 'this', 'product'], 'sentiment': 1},\n     {'sentence': ['the',\n       'screen',\n       'size',\n       'is',\n       'big',\n       'key',\n       'pad',\n       'lit',\n       'well',\n       'enough',\n       'and',\n       'the',\n       'camera',\n       'quality',\n       'is',\n       'excellent',\n       'for',\n       'a',\n       'camera',\n       'phone'],\n      'sentiment': 1},\n     {'sentence': ['theres',\n       'really',\n       'nothing',\n       'bad',\n       'i',\n       'can',\n       'say',\n       'about',\n       'this',\n       'headset'],\n      'sentiment': 0},\n     {'sentence': ['im',\n       'glad',\n       'i',\n       'found',\n       'this',\n       'product',\n       'on',\n       'amazon',\n       'it',\n       'is',\n       'hard',\n       'to',\n       'find',\n       'it',\n       'wasnt',\n       'high',\n       'priced'],\n      'sentiment': 1},\n     {'sentence': ['portable', 'and', 'it', 'works'], 'sentiment': 1},\n     {'sentence': ['my',\n       'colleague',\n       '',\n       'i',\n       'now',\n       'get',\n       'great',\n       'receptiona',\n       'little',\n       'expensive',\n       'but',\n       'performance',\n       'is',\n       'great'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'even',\n       'fully',\n       'charged',\n       'it',\n       'before',\n       'i',\n       'went',\n       'to',\n       'bed',\n       'and',\n       'turned',\n       'off',\n       'blue',\n       'tooth',\n       'and',\n       'wifi',\n       'and',\n       'noticed',\n       'that',\n       'it',\n       'only',\n       'had',\n       '20',\n       '',\n       'left',\n       'in',\n       'the',\n       'morning'],\n      'sentiment': 0},\n     {'sentence': ['ive',\n       'also',\n       'had',\n       'problems',\n       'with',\n       'the',\n       'phone',\n       'reading',\n       'the',\n       'memory',\n       'card',\n       'in',\n       'which',\n       'i',\n       'always',\n       'turn',\n       'it',\n       'on',\n       'and',\n       'then',\n       'off',\n       'again'],\n      'sentiment': 0},\n     {'sentence': ['not',\n       'good',\n       'when',\n       'wearing',\n       'a',\n       'hat',\n       'or',\n       'sunglasses'],\n      'sentiment': 0},\n     {'sentence': ['timely', 'shipment', 'and', 'quality', 'product'],\n      'sentiment': 1},\n     {'sentence': ['nice', 'solid', 'keyboard'], 'sentiment': 1},\n     {'sentence': ['very',\n       'well',\n       'made',\n       'and',\n       'fits',\n       'my',\n       'surefire',\n       'gx2',\n       'perfectly'],\n      'sentiment': 1},\n     {'sentence': ['horrible', 'phone'], 'sentiment': 0},\n     {'sentence': ['bt50', 'battery', 'junk'], 'sentiment': 0},\n     {'sentence': ['we', 'would', 'recommend', 'these', 'to', 'others'],\n      'sentiment': 1},\n     {'sentence': ['cant',\n       'get',\n       'the',\n       'software',\n       'to',\n       'work',\n       'with',\n       'my',\n       'computer'],\n      'sentiment': 0},\n     {'sentence': ['disappointed'], 'sentiment': 0},\n     {'sentence': ['poor', 'voice', 'clarity'], 'sentiment': 0},\n     {'sentence': ['the', 'battery', 'works', 'great'], 'sentiment': 1},\n     {'sentence': ['no', 'buyers', 'remorse', 'on', 'this', 'one'],\n      'sentiment': 0},\n     {'sentence': ['very', 'disappointed', 'in', 'accessoryone'], 'sentiment': 0},\n     {'sentence': ['i',\n       'find',\n       'this',\n       'inexcusable',\n       'and',\n       'so',\n       'will',\n       'probably',\n       'be',\n       'returning',\n       'this',\n       'phone',\n       'and',\n       'perhaps',\n       'changing',\n       'carriers'],\n      'sentiment': 0},\n     {'sentence': ['looks', 'great', 'and', 'is', 'strong'], 'sentiment': 1},\n     {'sentence': ['i',\n       'have',\n       'had',\n       'tmobile',\n       'service',\n       'for',\n       '2',\n       'or',\n       '3',\n       'years',\n       'now',\n       'and',\n       'i',\n       'am',\n       'pretty',\n       'happy',\n       'with',\n       'it'],\n      'sentiment': 1},\n     {'sentence': ['the',\n       'update',\n       'procedure',\n       'is',\n       'difficult',\n       'and',\n       'cumbersome'],\n      'sentiment': 0},\n     {'sentence': ['disappointment',\n       'i',\n       'hate',\n       'anything',\n       'that',\n       'goes',\n       'in',\n       'my',\n       'ear'],\n      'sentiment': 0},\n     {'sentence': ['great', 'software', 'for', 'motorolas'], 'sentiment': 1},\n     {'sentence': ['the', 'delivery', 'was', 'on', 'time'], 'sentiment': 1},\n     {'sentence': ['very', 'easy', 'to', 'use'], 'sentiment': 1},\n     {'sentence': ['uncomfortable',\n       'in',\n       'the',\n       'ear',\n       'dont',\n       'use',\n       'with',\n       'lg',\n       'vx9900',\n       'env'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'volume',\n       'switch',\n       'rocketed',\n       'out',\n       'of',\n       'the',\n       'unit',\n       'to',\n       'a',\n       'destination',\n       'unknown'],\n      'sentiment': 0},\n     {'sentence': ['it',\n       'holds',\n       'a',\n       'charge',\n       'for',\n       'a',\n       'long',\n       'time',\n       'is',\n       'reasonably',\n       'comfortable',\n       'under',\n       'longwearing',\n       'conditions',\n       'and',\n       'the',\n       'quality',\n       'of',\n       'sound',\n       'is',\n       'tremendous'],\n      'sentiment': 1},\n     {'sentence': ['id', 'like', 'to', 'return', 'it'], 'sentiment': 0},\n     {'sentence': ['the',\n       'keyboard',\n       'is',\n       'really',\n       'worthwhile',\n       'in',\n       'usefulness',\n       'and',\n       'is',\n       'sturdy',\n       'enough',\n       'i',\n       'dont',\n       'expect',\n       'any',\n       'problems'],\n      'sentiment': 1},\n     {'sentence': ['verizons',\n       'bills',\n       'however',\n       'are',\n       'difficult',\n       'to',\n       'understand',\n       'even',\n       'though',\n       'their',\n       'pricing',\n       'plans',\n       'are',\n       'simple'],\n      'sentiment': 0},\n     {'sentence': ['after',\n       'charging',\n       'overnight',\n       'these',\n       'batteries',\n       'work',\n       'great'],\n      'sentiment': 1},\n     {'sentence': ['you', 'wont', 'regret', 'it'], 'sentiment': 1},\n     {'sentence': ['i', 'love', 'this', 'phone'], 'sentiment': 1},\n     {'sentence': ['a', 'disappointment'], 'sentiment': 0},\n     {'sentence': ['its', 'not', 'user', 'friendly'], 'sentiment': 0},\n     {'sentence': ['unfortunately',\n       'the',\n       'ability',\n       'to',\n       'actually',\n       'know',\n       'you',\n       'are',\n       'receiving',\n       'a',\n       'call',\n       'is',\n       'a',\n       'rather',\n       'important',\n       'feature',\n       'and',\n       'this',\n       'phone',\n       'is',\n       'pitiful',\n       'in',\n       'that',\n       'respect'],\n      'sentiment': 0},\n     {'sentence': ['then',\n       'i',\n       'exchanged',\n       'for',\n       'the',\n       'same',\n       'phone',\n       'even',\n       'that',\n       'had',\n       'the',\n       'same',\n       'problem'],\n      'sentiment': 0},\n     {'sentence': ['this',\n       'results',\n       'in',\n       'the',\n       'phone',\n       'being',\n       'either',\n       'stuck',\n       'at',\n       'max',\n       'volume',\n       'or',\n       'mute'],\n      'sentiment': 0},\n     {'sentence': ['this', 'pda', 'rocks'], 'sentiment': 1},\n     {'sentence': ['it',\n       'is',\n       'super',\n       'charged',\n       'up',\n       'for',\n       'use',\n       'as',\n       'a',\n       'small',\n       'hybrid',\n       'palmtopcameracellphone',\n       'and',\n       'excels',\n       'in',\n       'those',\n       'roles'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'would',\n       'definitely',\n       'recommend',\n       'the',\n       'jabra',\n       'bt250v',\n       'for',\n       'those',\n       'who',\n       'are',\n       'looking',\n       'for',\n       'comfort',\n       'clarity',\n       'and',\n       'a',\n       'great',\n       'price'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'had',\n       'verizon',\n       '2',\n       'years',\n       'ago',\n       'and',\n       'really',\n       'liked',\n       'their',\n       'service'],\n      'sentiment': 1},\n     {'sentence': ['pretty', 'piece', 'of', 'junk'], 'sentiment': 0},\n     {'sentence': ['plug', 'was', 'the', 'wrong', 'size'], 'sentiment': 0},\n     {'sentence': ['works', 'as', 'described'], 'sentiment': 1},\n     {'sentence': ['save',\n       'your',\n       'money',\n       'ive',\n       'had',\n       'this',\n       'item',\n       'for',\n       '11',\n       'months',\n       'now'],\n      'sentiment': 0},\n     {'sentence': ['bad', 'purchase'], 'sentiment': 0},\n     {'sentence': ['well', 'im', 'satisfied'], 'sentiment': 1},\n     {'sentence': ['the',\n       'bose',\n       'noise',\n       'cancelling',\n       'is',\n       'amazing',\n       'which',\n       'is',\n       'very',\n       'important',\n       'for',\n       'a',\n       'nyc',\n       'commuter'],\n      'sentiment': 1},\n     {'sentence': ['this', 'battery', 'is', 'an', 'excellent', 'bargain'],\n      'sentiment': 1},\n     {'sentence': ['defective', 'crap'], 'sentiment': 0},\n     {'sentence': ['i',\n       'would',\n       'have',\n       'given',\n       'no',\n       'star',\n       'if',\n       'i',\n       'was',\n       'able'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'wear',\n       'glasses',\n       'and',\n       'it',\n       'fits',\n       'fine',\n       'with',\n       'them'],\n      'sentiment': 1},\n     {'sentence': ['the',\n       'sound',\n       'quality',\n       'for',\n       'the',\n       'device',\n       'is',\n       'unacceptableunless',\n       'you',\n       'are',\n       'in',\n       'a',\n       'really',\n       'quiet',\n       'area',\n       'you',\n       'almost',\n       'hear',\n       'nothing'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'would',\n       'not',\n       'recommend',\n       'this',\n       'item',\n       'to',\n       'anyone'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'holster',\n       'that',\n       'arrived',\n       'did',\n       'not',\n       'match',\n       'the',\n       'photo',\n       'in',\n       'the',\n       'ad'],\n      'sentiment': 0},\n     {'sentence': ['greatno', 'problems', 'at', 'all'], 'sentiment': 1},\n     {'sentence': ['as',\n       'an',\n       'earlier',\n       'review',\n       'noted',\n       'plug',\n       'in',\n       'this',\n       'charger',\n       'and',\n       'nothing',\n       'happens'],\n      'sentiment': 0},\n     {'sentence': ['this',\n       'frog',\n       'phone',\n       'charm',\n       'is',\n       'adorable',\n       'and',\n       'very',\n       'eye',\n       'catching'],\n      'sentiment': 1},\n     {'sentence': ['you',\n       'never',\n       'know',\n       'if',\n       'you',\n       'pushed',\n       'it',\n       'hard',\n       'enough',\n       'or',\n       'the',\n       'right',\n       'number',\n       'of',\n       'times',\n       'for',\n       'the',\n       'function',\n       'you',\n       'want',\n       'or',\n       'not'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'sound',\n       'is',\n       'clear',\n       'and',\n       'the',\n       'people',\n       'i',\n       'talk',\n       'to',\n       'on',\n       'it',\n       'are',\n       'amazed',\n       'at',\n       'the',\n       'quality',\n       'too'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'got',\n       'the',\n       'aluminum',\n       'case',\n       'for',\n       'my',\n       'new',\n       'palm',\n       'vx',\n       'and',\n       'it',\n       'worked',\n       'really',\n       'wellit',\n       'has',\n       'protected',\n       'my',\n       'handheld',\n       'perfectly',\n       'so',\n       'far'],\n      'sentiment': 1},\n     {'sentence': ['very', 'good', 'product', 'well', 'made'], 'sentiment': 1},\n     {'sentence': ['mobile', 'phone', 'tools', 'are', 'a', 'must', 'have'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'am',\n       'very',\n       'impressed',\n       'with',\n       'the',\n       'job',\n       'that',\n       'motorola',\n       'did',\n       'on',\n       'the',\n       'sturdiness',\n       'of',\n       'this',\n       'phone'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'received',\n       'my',\n       'orders',\n       'well',\n       'within',\n       'the',\n       'shipping',\n       'timeframe',\n       'everything',\n       'was',\n       'in',\n       'good',\n       'working',\n       'order',\n       'and',\n       'overall',\n       'i',\n       'am',\n       'very',\n       'excited',\n       'to',\n       'have',\n       'this',\n       'source'],\n      'sentiment': 1},\n     {'sentence': ['the', 'phone', 'is', 'sturdy', 'and', 'waterproof'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'am',\n       'not',\n       'impressed',\n       'with',\n       'this',\n       'and',\n       'i',\n       'would',\n       'not',\n       'recommend',\n       'this',\n       'item',\n       'to',\n       'anyone'],\n      'sentiment': 0},\n     {'sentence': ['my',\n       'only',\n       'complaint',\n       'is',\n       'the',\n       'standard',\n       'sound',\n       'volume',\n       'is',\n       'a',\n       'little',\n       'low',\n       'even',\n       'when',\n       'turned',\n       'up',\n       'to',\n       '5of',\n       '5'],\n      'sentiment': 0},\n     {'sentence': ['thanks',\n       'again',\n       'to',\n       'amazon',\n       'for',\n       'having',\n       'the',\n       'things',\n       'i',\n       'need',\n       'for',\n       'a',\n       'good',\n       'price'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'ended',\n       'up',\n       'sliding',\n       'it',\n       'on',\n       'the',\n       'edge',\n       'of',\n       'my',\n       'pants',\n       'or',\n       'back',\n       'pockets',\n       'instead'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'had',\n       'to',\n       'go',\n       'to',\n       'a',\n       'store',\n       'and',\n       'bought',\n       'a',\n       'new',\n       'nokia',\n       'phone',\n       'which',\n       'is',\n       'working',\n       'great'],\n      'sentiment': 1},\n     {'sentence': ['works', 'great'], 'sentiment': 1},\n     {'sentence': ['really', 'ugly'], 'sentiment': 0},\n     {'sentence': ['horrible', 'had', 'to', 'switch', '3', 'times'],\n      'sentiment': 0},\n     {'sentence': ['the', 'noise', 'shield', 'is', 'incrediable'], 'sentiment': 1},\n     {'sentence': ['no', 'real', 'improvement'], 'sentiment': 0},\n     {'sentence': ['razr', 'battery', '', 'good', 'buy'], 'sentiment': 1},\n     {'sentence': ['keep', 'up', 'the', 'good', 'work', 'amazon'], 'sentiment': 1},\n     {'sentence': ['they', 'refuse', 'to', 'refund', 'or', 'replace'],\n      'sentiment': 0},\n     {'sentence': ['unfortunately',\n       'its',\n       'easy',\n       'to',\n       'accidentally',\n       'activate',\n       'them',\n       'with',\n       'the',\n       'gentletouch',\n       'buttons',\n       'if',\n       'you',\n       'accidentally',\n       'touch',\n       'the',\n       'phone',\n       'to',\n       'your',\n       'face',\n       'while',\n       'listening'],\n      'sentiment': 0},\n     {'sentence': ['so',\n       'i',\n       'basically',\n       'threw',\n       'my',\n       'money',\n       'out',\n       'the',\n       'window',\n       'for',\n       'nothing'],\n      'sentiment': 0},\n     {'sentence': ['great', 'case', 'and', 'price'], 'sentiment': 1},\n     {'sentence': ['all',\n       'it',\n       'took',\n       'was',\n       'one',\n       'drop',\n       'from',\n       'about',\n       '6',\n       'inches',\n       'above',\n       'the',\n       'kitchen',\n       'counter',\n       'and',\n       'it',\n       'was',\n       'crackedi',\n       'am',\n       'not',\n       'impressed',\n       'and',\n       'i',\n       'am',\n       'not',\n       'laughing'],\n      'sentiment': 0},\n     {'sentence': ['bluetooth',\n       'range',\n       'is',\n       'good',\n       '',\n       'a',\n       'few',\n       'days',\n       'ago',\n       'i',\n       'left',\n       'my',\n       'phone',\n       'in',\n       'the',\n       'trunk',\n       'got',\n       'a',\n       'call',\n       'and',\n       'carried',\n       'the',\n       'conversation',\n       'without',\n       'a',\n       'hitch'],\n      'sentiment': 1},\n     {'sentence': ['small',\n       'sleek',\n       'impressive',\n       'looking',\n       'practical',\n       'setup',\n       'with',\n       'ample',\n       'storage',\n       'in',\n       'place'],\n      'sentiment': 1},\n     {'sentence': ['the',\n       'eargels',\n       'channel',\n       'the',\n       'sound',\n       'directly',\n       'into',\n       'your',\n       'ear',\n       'and',\n       'seem',\n       'to',\n       'increase',\n       'the',\n       'sound',\n       'volume',\n       'and',\n       'clarity'],\n      'sentiment': 1},\n     {'sentence': ['none',\n       'of',\n       'the',\n       'new',\n       'ones',\n       'have',\n       'ever',\n       'quite',\n       'worked',\n       'properly'],\n      'sentiment': 0},\n     {'sentence': ['i', 'am', 'glad', 'i', 'purchased', 'it'], 'sentiment': 1},\n     {'sentence': ['ive',\n       'missed',\n       'numerous',\n       'calls',\n       'because',\n       'of',\n       'this',\n       'reason'],\n      'sentiment': 0},\n     {'sentence': ['perhaps',\n       'my',\n       'phone',\n       'is',\n       'defective',\n       'but',\n       'people',\n       'cannot',\n       'hear',\n       'me',\n       'when',\n       'i',\n       'use',\n       'this'],\n      'sentiment': 0},\n     {'sentence': ['dont', 'buy', 'this', 'product'], 'sentiment': 0},\n     {'sentence': ['sucked',\n       'most',\n       'of',\n       'the',\n       'stuff',\n       'does',\n       'not',\n       'work',\n       'with',\n       'my',\n       'phone'],\n      'sentiment': 0},\n     {'sentence': ['no',\n       'shifting',\n       'no',\n       'bubbling',\n       'no',\n       'peeling',\n       'not',\n       'even',\n       'a',\n       'scratch',\n       'nothingi',\n       'couldnt',\n       'be',\n       'more',\n       'happier',\n       'with',\n       'my',\n       'new',\n       'one',\n       'for',\n       'the',\n       'droid'],\n      'sentiment': 1},\n     {'sentence': ['worst',\n       'software',\n       'ever',\n       'used',\n       'if',\n       'i',\n       'could',\n       'give',\n       'this',\n       'zero',\n       'stars',\n       'i',\n       'would'],\n      'sentiment': 0},\n     {'sentence': ['trying',\n       'to',\n       'make',\n       'a',\n       'call',\n       'on',\n       'these',\n       'is',\n       'an',\n       'exercise',\n       'in',\n       'frustration'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'case',\n       'is',\n       'a',\n       'flimsy',\n       'piece',\n       'of',\n       'plastic',\n       'and',\n       'has',\n       'no',\n       'front',\n       'or',\n       'side',\n       'protection',\n       'whatsoever'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'own',\n       'a',\n       'jabra',\n       'earset',\n       'and',\n       'was',\n       'very',\n       'happy',\n       'with',\n       'it',\n       'but',\n       'the',\n       'sound',\n       'quality',\n       'especially',\n       'outgoing',\n       'on',\n       'this',\n       'is',\n       'better'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'love',\n       'the',\n       'camera',\n       'its',\n       'really',\n       'pretty',\n       'good',\n       'quality'],\n      'sentiment': 1},\n     {'sentence': ['thank', 'you', 'for', 'such', 'great', 'service'],\n      'sentiment': 1},\n     {'sentence': ['its', 'a', 'total', 'package'], 'sentiment': 1},\n     {'sentence': ['the',\n       'seller',\n       'is',\n       'very',\n       'understanding',\n       'and',\n       'patient',\n       'i',\n       'would',\n       'definitely',\n       'buy',\n       'from',\n       'them',\n       'again'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'give',\n       'wirefly',\n       '1',\n       'stari',\n       'will',\n       'contact',\n       'cingularatt',\n       'and',\n       'inform',\n       'them',\n       'of',\n       'this',\n       'practice'],\n      'sentiment': 0},\n     {'sentence': ['its', 'aggravating'], 'sentiment': 0},\n     {'sentence': ['great', 'product', 'for', 'the', 'price'], 'sentiment': 1},\n     {'sentence': ['i',\n       'have',\n       'purchased',\n       'these',\n       'for',\n       'both',\n       'family',\n       'and',\n       'friends',\n       'and',\n       'all',\n       'enjoy',\n       'their',\n       'clarity',\n       'and',\n       'ease',\n       'of',\n       'use'],\n      'sentiment': 1},\n     {'sentence': ['virgin',\n       'wireless',\n       'rocks',\n       'and',\n       'so',\n       'does',\n       'this',\n       'cheap',\n       'little',\n       'phone'],\n      'sentiment': 1},\n     {'sentence': ['none', 'of', 'it', 'works', 'just', 'dont', 'buy', 'it'],\n      'sentiment': 0},\n     {'sentence': ['muddy',\n       'low',\n       'quality',\n       'sound',\n       'and',\n       'the',\n       'casing',\n       'around',\n       'the',\n       'wires',\n       'insert',\n       'was',\n       'poorly',\n       'super',\n       'glued',\n       'and',\n       'slid',\n       'off'],\n      'sentiment': 0},\n     {'sentence': ['please', 'dont', 'waste', 'your', 'money'], 'sentiment': 0},\n     {'sentence': ['all',\n       'in',\n       'all',\n       'im',\n       'quite',\n       'satisfied',\n       'with',\n       'this',\n       'purchase'],\n      'sentiment': 1},\n     {'sentence': ['if',\n       'you',\n       'are',\n       'looking',\n       'for',\n       'a',\n       'good',\n       'quality',\n       'motorola',\n       'headset',\n       'keep',\n       'looking',\n       'this',\n       'isnt',\n       'it'],\n      'sentiment': 0},\n     {'sentence': ['yet',\n       'plantronincs',\n       'continues',\n       'to',\n       'use',\n       'the',\n       'same',\n       'flawed',\n       'charger',\n       'design'],\n      'sentiment': 0},\n     {'sentence': ['disapointing', 'results'], 'sentiment': 0},\n     {'sentence': ['cumbersome', 'design'], 'sentiment': 0},\n     {'sentence': ['great',\n       'it',\n       'was',\n       'new',\n       'packaged',\n       'nice',\n       'works',\n       'good',\n       'no',\n       'problems',\n       'and',\n       'it',\n       'came',\n       'in',\n       'less',\n       'time',\n       'then',\n       'i',\n       'expected'],\n      'sentiment': 1},\n     {'sentence': ['great', 'product'], 'sentiment': 1},\n     {'sentence': ['its', 'a', 'piece', 'of', 'crap'], 'sentiment': 0},\n     {'sentence': ['my',\n       'experience',\n       'was',\n       'terrible',\n       'this',\n       'was',\n       'my',\n       'fourth',\n       'bluetooth',\n       'headset',\n       'and',\n       'while',\n       'it',\n       'was',\n       'much',\n       'more',\n       'comfortable',\n       'than',\n       'my',\n       'last',\n       'jabra',\n       'which',\n       'i',\n       'hated'],\n      'sentiment': 0},\n     {'sentence': ['this', 'fixes', 'all', 'the', 'problems'], 'sentiment': 1},\n     {'sentence': ['worst', 'ever'], 'sentiment': 0},\n     {'sentence': ['i', 'am', 'very', 'happy'], 'sentiment': 1},\n     {'sentence': ['ive',\n       'had',\n       'no',\n       'trouble',\n       'accessing',\n       'the',\n       'internet',\n       'downloading',\n       'ringtones',\n       'or',\n       'performing',\n       'any',\n       'of',\n       'the',\n       'functions'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'can',\n       'barely',\n       'ever',\n       'hear',\n       'on',\n       'it',\n       'and',\n       'am',\n       'constantly',\n       'saying',\n       'what'],\n      'sentiment': 0},\n     {'sentence': ['the', 'battery', 'life', 'is', 'highly', 'unacceptable'],\n      'sentiment': 0},\n     {'sentence': ['that', 'company', 'is', 'a', 'joke'], 'sentiment': 0},\n     {'sentence': ['it',\n       'does',\n       'everything',\n       'the',\n       'description',\n       'said',\n       'it',\n       'would'],\n      'sentiment': 1},\n     {'sentence': ['due',\n       'to',\n       'this',\n       'happening',\n       'on',\n       'every',\n       'call',\n       'i',\n       'was',\n       'forced',\n       'to',\n       'stop',\n       'using',\n       'this',\n       'headset'],\n      'sentiment': 0},\n     {'sentence': ['it',\n       'works',\n       'great',\n       'with',\n       'a',\n       'car',\n       'charger',\n       'especially',\n       'if',\n       'you',\n       'cannot',\n       'plug',\n       'in',\n       'two',\n       'adapters',\n       'at',\n       'the',\n       'same',\n       'time'],\n      'sentiment': 1},\n     {'sentence': ['verizon',\n       'tech',\n       'support',\n       'walked',\n       'my',\n       'through',\n       'a',\n       'few',\n       'procedures',\n       'none',\n       'of',\n       'which',\n       'worked',\n       'and',\n       'i',\n       'ended',\n       'up',\n       'having',\n       'to',\n       'do',\n       'a',\n       'hard',\n       'reset',\n       'wiping',\n       'out',\n       'all',\n       'my',\n       'data'],\n      'sentiment': 0},\n     {'sentence': ['voice', 'quality', 'signal', 'strength', 'dropped', 'calls'],\n      'sentiment': 0},\n     {'sentence': ['it',\n       'plays',\n       'louder',\n       'than',\n       'any',\n       'other',\n       'speaker',\n       'of',\n       'this',\n       'size',\n       'the',\n       'price',\n       'is',\n       'so',\n       'low',\n       'that',\n       'most',\n       'would',\n       'think',\n       'the',\n       'quality',\n       'is',\n       'lacking',\n       'however',\n       'its',\n       'not'],\n      'sentiment': 1},\n     {'sentence': ['better', 'than', 'expected'], 'sentiment': 1},\n     {'sentence': ['it',\n       'feels',\n       'poorly',\n       'constructed',\n       'the',\n       'menus',\n       'are',\n       'difficult',\n       'to',\n       'navigate',\n       'and',\n       'the',\n       'buttons',\n       'are',\n       'so',\n       'recessed',\n       'that',\n       'it',\n       'is',\n       'difficult',\n       'to',\n       'push',\n       'them'],\n      'sentiment': 0},\n     {'sentence': ['battery', 'is', 'holding', 'up', 'well'], 'sentiment': 1},\n     {'sentence': ['also',\n       'difficult',\n       'to',\n       'put',\n       'onid',\n       'recommend',\n       'avoiding',\n       'this',\n       'product'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'only',\n       'used',\n       'it',\n       'two',\n       'days',\n       'and',\n       'it',\n       'wasnt',\n       'always',\n       'easy',\n       'to',\n       'hear',\n       'with'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'got',\n       'the',\n       'car',\n       'charger',\n       'and',\n       'not',\n       'even',\n       'after',\n       'a',\n       'week',\n       'the',\n       'charger',\n       'was',\n       'brokeni',\n       'went',\n       'to',\n       'plug',\n       'it',\n       'in',\n       'and',\n       'it',\n       'started',\n       'smoking'],\n      'sentiment': 0},\n     {'sentence': ['sprint', '', 'terrible', 'customer', 'service'],\n      'sentiment': 0},\n     {'sentence': ['linked', 'to', 'my', 'phone', 'without', 'effort'],\n      'sentiment': 1},\n     {'sentence': ['they', 'are', 'so', 'cool'], 'sentiment': 1},\n     {'sentence': ['easy', 'to', 'use'], 'sentiment': 1},\n     {'sentence': ['better', 'than', 'new'], 'sentiment': 1},\n     {'sentence': ['what',\n       'possesed',\n       'me',\n       'to',\n       'get',\n       'this',\n       'junk',\n       'i',\n       'have',\n       'no',\n       'idea'],\n      'sentiment': 0},\n     {'sentence': ['piece', 'of', 'trash'], 'sentiment': 0},\n     {'sentence': ['a', 'pretty', 'good', 'product'], 'sentiment': 1},\n     {'sentence': ['this', 'is', 'a', 'great', 'phone'], 'sentiment': 1},\n     {'sentence': ['for',\n       'the',\n       'price',\n       'on',\n       'amazon',\n       'it',\n       'is',\n       'an',\n       'excellent',\n       'product',\n       'which',\n       'i',\n       'would',\n       'highly',\n       'recommend'],\n      'sentiment': 1},\n     {'sentence': ['their',\n       'research',\n       'and',\n       'development',\n       'division',\n       'obviously',\n       'knows',\n       'what',\n       'theyre',\n       'doing'],\n      'sentiment': 1},\n     {'sentence': ['the',\n       'real',\n       'killer',\n       'is',\n       'the',\n       'volume',\n       'and',\n       'of',\n       'course',\n       'it',\n       'breaking'],\n      'sentiment': 0},\n     {'sentence': ['those', 'phones', 'are', 'working', 'just', 'fine', 'now'],\n      'sentiment': 1},\n     {'sentence': ['i', 'am', 'more', 'than', 'happy', 'with', 'this', 'product'],\n      'sentiment': 1},\n     {'sentence': ['poor', 'construction'], 'sentiment': 0},\n     {'sentence': ['this', 'is', 'infuriating'], 'sentiment': 0},\n     {'sentence': ['overall',\n       'i',\n       'would',\n       'recommend',\n       'this',\n       'phone',\n       'over',\n       'the',\n       'new',\n       'walkman'],\n      'sentiment': 1},\n     {'sentence': ['sprint', 'charges', 'for', 'this', 'service'], 'sentiment': 0},\n     {'sentence': ['it',\n       'is',\n       'cheap',\n       'and',\n       'it',\n       'feel',\n       'and',\n       'look',\n       'just',\n       'as',\n       'cheap'],\n      'sentiment': 0},\n     {'sentence': ['it',\n       'fits',\n       'my',\n       'ear',\n       'well',\n       'and',\n       'is',\n       'comfortable',\n       'on'],\n      'sentiment': 1},\n     {'sentence': ['it', 'doesnt', 'work', 'in', 'europe', 'or', 'asia'],\n      'sentiment': 0},\n     {'sentence': ['clipping',\n       'this',\n       'to',\n       'your',\n       'belt',\n       'will',\n       'deffinitely',\n       'make',\n       'you',\n       'feel',\n       'like',\n       '50',\n       'cents',\n       'upandcoming'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'like',\n       'design',\n       'and',\n       'look',\n       'of',\n       'jabra',\n       'behing',\n       'the',\n       'ear',\n       'headsets',\n       'and',\n       '5020',\n       'is',\n       'pretty',\n       'comfortible',\n       'to',\n       'wear',\n       '24',\n       'hours',\n       'a',\n       'day',\n       'without',\n       'pain',\n       'in',\n       'the',\n       'ear'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'was',\n       'amazed',\n       'at',\n       'the',\n       'quick',\n       'arrival',\n       'of',\n       'the',\n       'two',\n       'original',\n       'lg',\n       'cell',\n       'phone',\n       'batteries',\n       'and',\n       'and',\n       'at',\n       'a',\n       'fraction',\n       'of',\n       'the',\n       'price'],\n      'sentiment': 1},\n     {'sentence': ['the',\n       'worst',\n       'phone',\n       'from',\n       'samsungcrap',\n       'this',\n       'crappy',\n       'samsung',\n       'e715',\n       'is',\n       'the',\n       'worst',\n       'i',\n       'have',\n       'ever',\n       'seeen'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'charger',\n       'worked',\n       'for',\n       'about',\n       'a',\n       'week',\n       'and',\n       'then',\n       'completely',\n       'stopped',\n       'charging',\n       'my',\n       'phone'],\n      'sentiment': 0},\n     {'sentence': ['poor', 'product'], 'sentiment': 0},\n     {'sentence': ['however', 'i', 'needed', 'some', 'better', 'instructions'],\n      'sentiment': 0},\n     {'sentence': ['you',\n       'need',\n       'two',\n       'hands',\n       'to',\n       'operate',\n       'the',\n       'screenthis',\n       'software',\n       'interface',\n       'is',\n       'decade',\n       'old',\n       'and',\n       'cannot',\n       'compete',\n       'with',\n       'new',\n       'software',\n       'designs'],\n      'sentiment': 0},\n     {'sentence': ['worked',\n       'very',\n       'well',\n       'paired',\n       'with',\n       'a',\n       'treo',\n       '700w',\n       'and',\n       'as',\n       'a',\n       'skype',\n       'headset',\n       'on',\n       'my',\n       'pc',\n       'using',\n       'a',\n       'usb',\n       'bluetooth',\n       'transceiver'],\n      'sentiment': 1},\n     {'sentence': ['steer',\n       'clear',\n       'of',\n       'this',\n       'product',\n       'and',\n       'go',\n       'with',\n       'the',\n       'genuine',\n       'palm',\n       'replacementr',\n       'pens',\n       'which',\n       'come',\n       'in',\n       'a',\n       'threepack'],\n      'sentiment': 0},\n     {'sentence': ['do', 'not', 'buy', 'do', 'not', 'buyit', 'sucks'],\n      'sentiment': 0},\n     {'sentence': ['this',\n       'is',\n       'a',\n       'great',\n       'product',\n       'sure',\n       'beats',\n       'using',\n       'your',\n       'fingers'],\n      'sentiment': 1},\n     {'sentence': ['plus',\n       'i',\n       'seriously',\n       'do',\n       'not',\n       'believe',\n       'it',\n       'is',\n       'worth',\n       'its',\n       'steep',\n       'price',\n       'point'],\n      'sentiment': 0},\n     {'sentence': ['all',\n       'the',\n       'other',\n       'cases',\n       'ive',\n       'tried',\n       'normally',\n       'fall',\n       'apart',\n       'after',\n       'a',\n       'few',\n       'months',\n       'but',\n       'this',\n       'one',\n       'seems',\n       'to',\n       'be',\n       'in',\n       'for',\n       'the',\n       'long',\n       'haul'],\n      'sentiment': 1},\n     {'sentence': ['very', 'dissapointing', 'performance'], 'sentiment': 0},\n     {'sentence': ['dont',\n       'make',\n       'the',\n       'same',\n       'mistake',\n       'that',\n       'i',\n       'did',\n       'and',\n       'please',\n       'dont',\n       'buy',\n       'this',\n       'phone'],\n      'sentiment': 0},\n     {'sentence': ['this',\n       'phone',\n       'might',\n       'well',\n       'be',\n       'the',\n       'worst',\n       'ive',\n       'ever',\n       'had',\n       'in',\n       'any',\n       'brand'],\n      'sentiment': 0},\n     {'sentence': ['case',\n       'was',\n       'more',\n       'or',\n       'less',\n       'an',\n       'extra',\n       'that',\n       'i',\n       'originally',\n       'put',\n       'on',\n       'but',\n       'later',\n       'discarded',\n       'because',\n       'it',\n       'scratched',\n       'my',\n       'ear'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'recommend',\n       'igo',\n       'to',\n       'anyone',\n       'with',\n       'different',\n       'brand',\n       'cell',\n       'phonesmp3',\n       'players',\n       'in',\n       'the',\n       'family'],\n      'sentiment': 1},\n     {'sentence': ['dont', 'bother', '', 'go', 'to', 'the', 'store'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'posted',\n       'more',\n       'detailed',\n       'comments',\n       'under',\n       'the',\n       'grey',\n       'or',\n       'black',\n       'phone',\n       'but',\n       'i',\n       'have',\n       'the',\n       'fire',\n       'red',\n       'and',\n       'its',\n       'a',\n       'great',\n       'color'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'did',\n       'not',\n       'have',\n       'any',\n       'problem',\n       'with',\n       'this',\n       'item',\n       'and',\n       'would',\n       'order',\n       'it',\n       'again',\n       'if',\n       'needed'],\n      'sentiment': 1},\n     {'sentence': ['you', 'get', 'what', 'you', 'pay', 'for', 'i', 'guess'],\n      'sentiment': 0},\n     {'sentence': ['not',\n       'only',\n       'did',\n       'the',\n       'software',\n       'do',\n       'a',\n       'great',\n       'job',\n       'of',\n       'this',\n       'i',\n       'could',\n       'also',\n       'make',\n       'my',\n       'own',\n       'ringtones',\n       'form',\n       'my',\n       'existing',\n       'cds',\n       'without',\n       'an',\n       'internet',\n       'connection'],\n      'sentiment': 1},\n     {'sentence': ['im',\n       'surprised',\n       'this',\n       'is',\n       'a',\n       'good',\n       'quality',\n       'car',\n       'charger',\n       'and',\n       'theres',\n       'not',\n       'much',\n       'reviews',\n       'about',\n       'it'],\n      'sentiment': 1},\n     {'sentence': ['these', 'are', 'fabulous'], 'sentiment': 1},\n     {'sentence': ['however',\n       'bt',\n       'headsets',\n       'are',\n       'currently',\n       'not',\n       'good',\n       'for',\n       'real',\n       'time',\n       'games',\n       'like',\n       'firstperson',\n       'shooters',\n       'since',\n       'the',\n       'audio',\n       'delay',\n       'messes',\n       'me',\n       'up'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'used',\n       'bitpim',\n       'a',\n       'free',\n       'program',\n       'you',\n       'can',\n       'find',\n       'on',\n       'the',\n       'internetto',\n       'transfer',\n       'data',\n       'to',\n       'the',\n       'phonethe',\n       'price',\n       'of',\n       'the',\n       'cable',\n       'was',\n       'excellent'],\n      'sentiment': 1},\n     {'sentence': ['disappointing',\n       'accessory',\n       'from',\n       'a',\n       'good',\n       'manufacturer'],\n      'sentiment': 0},\n     {'sentence': ['performed',\n       'awful',\n       '',\n       'muffled',\n       'tinny',\n       'incoming',\n       'sound',\n       'and',\n       'severe',\n       'echo',\n       'for',\n       'those',\n       'on',\n       'the',\n       'other',\n       'end',\n       'of',\n       'the',\n       'call'],\n      'sentiment': 0},\n     {'sentence': ['very', 'windresistant'], 'sentiment': 1},\n     {'sentence': ['obviously',\n       'they',\n       'have',\n       'a',\n       'terrible',\n       'customer',\n       'service',\n       'so',\n       'you',\n       'get',\n       'what',\n       'you',\n       'pay',\n       'for'],\n      'sentiment': 0},\n     {'sentence': ['they',\n       'do',\n       'not',\n       'last',\n       'forever',\n       'but',\n       'is',\n       'not',\n       'overly',\n       'expensive',\n       'to',\n       'replaceeasy',\n       'to',\n       'operate',\n       'and',\n       'the',\n       'sound',\n       'is',\n       'much',\n       'better',\n       'than',\n       'others',\n       'i',\n       'have',\n       'tried'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'contacted',\n       'the',\n       'company',\n       'and',\n       'they',\n       'told',\n       'me',\n       'that',\n       'although',\n       'the',\n       'unit',\n       'was',\n       'still',\n       'under',\n       'warranty',\n       'if',\n       'i',\n       'couldnt',\n       'produce',\n       'my',\n       'receipt',\n       'i',\n       'was',\n       'out',\n       'of',\n       'luck'],\n      'sentiment': 0},\n     {'sentence': ['linksys',\n       'should',\n       'have',\n       'some',\n       'way',\n       'to',\n       'exchange',\n       'a',\n       'bad',\n       'phone',\n       'for',\n       'a',\n       'refurb',\n       'unit',\n       'or',\n       'something'],\n      'sentiment': 0},\n     {'sentence': ['phone',\n       'is',\n       'sturdy',\n       'as',\n       'all',\n       'nokia',\n       'bar',\n       'phones',\n       'are'],\n      'sentiment': 1},\n     {'sentence': ['great', 'phone'], 'sentiment': 1},\n     {'sentence': ['when',\n       'i',\n       'placed',\n       'my',\n       'treo',\n       'into',\n       'the',\n       'case',\n       'not',\n       'only',\n       'was',\n       'it',\n       'not',\n       'snug',\n       'but',\n       'there',\n       'was',\n       'a',\n       'lot',\n       'of',\n       'extra',\n       'room',\n       'on',\n       'the',\n       'sides'],\n      'sentiment': 0},\n     {'sentence': ['im', 'pleased'], 'sentiment': 1},\n     {'sentence': ['battery', 'is', 'terrible'], 'sentiment': 0},\n     {'sentence': ['i',\n       'found',\n       'the',\n       'product',\n       'to',\n       'be',\n       'easy',\n       'to',\n       'set',\n       'up',\n       'and',\n       'use'],\n      'sentiment': 1},\n     {'sentence': ['the',\n       'earpiece',\n       'on',\n       'this',\n       'is',\n       'too',\n       'large',\n       'or',\n       'too',\n       'heavyit',\n       'keeps',\n       'falling',\n       'out',\n       'of',\n       'my',\n       'ear'],\n      'sentiment': 0},\n     {'sentence': ['utter', 'crap', 'sound', 'quality', 'is', 'terrible'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'charger',\n       'arrived',\n       'within',\n       'the',\n       'promised',\n       'timeframe',\n       'but',\n       'it',\n       'did',\n       'not',\n       'work'],\n      'sentiment': 0},\n     {'sentence': ['no',\n       'ear',\n       'loop',\n       'needed',\n       'its',\n       'tiny',\n       'and',\n       'the',\n       'sound',\n       'is',\n       'great'],\n      'sentiment': 1},\n     {'sentence': ['finally',\n       'after',\n       'three',\n       'or',\n       'four',\n       'times',\n       'the',\n       'spring',\n       'of',\n       'the',\n       'latch',\n       'broke',\n       'and',\n       'i',\n       'could',\n       'not',\n       'use',\n       'it',\n       'any',\n       'longer',\n       'on',\n       'the',\n       'visor'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'handsfree',\n       'part',\n       'works',\n       'fine',\n       'but',\n       'then',\n       'the',\n       'car',\n       'tries',\n       'to',\n       'download',\n       'the',\n       'address',\n       'book',\n       'and',\n       'the',\n       'treo',\n       'rebootsoverall',\n       'i',\n       'still',\n       'rate',\n       'this',\n       'device',\n       'high'],\n      'sentiment': 1},\n     {'sentence': ['talk', 'about', 'useless', 'customer', 'service'],\n      'sentiment': 0},\n     {'sentence': ['it', 'felt', 'too', 'light', 'and', 'tinny'], 'sentiment': 0},\n     {'sentence': ['this',\n       'does',\n       'not',\n       'fit',\n       'the',\n       'palm',\n       'tungsten',\n       'e2',\n       'and',\n       'it',\n       'broke',\n       'the',\n       'first',\n       'time',\n       'i',\n       'tried',\n       'to',\n       'plug',\n       'it',\n       'in'],\n      'sentiment': 0},\n     {'sentence': ['im',\n       'happy',\n       'about',\n       'this',\n       'purchase',\n       'good',\n       'quality',\n       'and',\n       'low',\n       'price'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'love',\n       'the',\n       'look',\n       'and',\n       'feel',\n       'of',\n       'samsung',\n       'flipphones'],\n      'sentiment': 1},\n     {'sentence': ['its',\n       'welldesigned',\n       'and',\n       'very',\n       'sharp',\n       '',\n       'the',\n       'blue',\n       'is',\n       'a',\n       'very',\n       'nice',\n       'color'],\n      'sentiment': 1},\n     {'sentence': ['does', 'everything', 'it', 'should', 'and', 'more'],\n      'sentiment': 1},\n     {'sentence': ['i', 'could', 'not', 'recommend', 'these', 'more'],\n      'sentiment': 0},\n     {'sentence': ['nice', 'sound'], 'sentiment': 1},\n     {'sentence': ['looks',\n       'good',\n       'in',\n       'the',\n       'picture',\n       'but',\n       'this',\n       'case',\n       'was',\n       'a',\n       'huge',\n       'disappointment'],\n      'sentiment': 0},\n     {'sentence': ['much',\n       'less',\n       'than',\n       'the',\n       'jawbone',\n       'i',\n       'was',\n       'going',\n       'to',\n       'replace',\n       'it',\n       'with'],\n      'sentiment': 1},\n     {'sentence': ['setup', 'went', 'very', 'smoothly'], 'sentiment': 1},\n     {'sentence': ['its',\n       'extremely',\n       'slow',\n       'and',\n       'takes',\n       'forever',\n       'to',\n       'do',\n       'anything',\n       'with',\n       'it'],\n      'sentiment': 0},\n     {'sentence': ['a',\n       'must',\n       'study',\n       'for',\n       'anyone',\n       'interested',\n       'in',\n       'the',\n       'worst',\n       'sins',\n       'of',\n       'industrial',\n       'design'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'first',\n       'thing',\n       'that',\n       'happened',\n       'was',\n       'that',\n       'the',\n       'tracking',\n       'was',\n       'off'],\n      'sentiment': 0},\n     {'sentence': ['it',\n       'is',\n       'well',\n       'made',\n       'easy',\n       'to',\n       'access',\n       'the',\n       'phone',\n       'and',\n       'has',\n       'a',\n       'handy',\n       'detachable',\n       'belt',\n       'clip'],\n      'sentiment': 1},\n     {'sentence': ['then',\n       'i',\n       'had',\n       'to',\n       'continue',\n       'pairing',\n       'it',\n       'periodically',\n       'since',\n       'it',\n       'somehow',\n       'kept',\n       'dropping'],\n      'sentiment': 0},\n     {'sentence': ['cant', 'upload', 'ringtones', 'from', 'a', 'third', 'party'],\n      'sentiment': 0},\n     {'sentence': ['bluetooth',\n       'does',\n       'not',\n       'work',\n       'phone',\n       'locks',\n       'up',\n       'screens',\n       'just',\n       'flash',\n       'up',\n       'and',\n       'now',\n       'it',\n       'just',\n       'makes',\n       'calls',\n       'randomly',\n       'while',\n       'in',\n       'my',\n       'pocket',\n       'locked'],\n      'sentiment': 0},\n     {'sentence': ['truly', 'awful'], 'sentiment': 0},\n     {'sentence': ['it',\n       'works',\n       'fine',\n       'on',\n       'my',\n       'motorola',\n       '325',\n       'cellphone',\n       'and',\n       'a',\n       'lot',\n       'better',\n       'than',\n       'the',\n       'wornout',\n       'battery',\n       'did'],\n      'sentiment': 1},\n     {'sentence': ['the',\n       'volume',\n       'for',\n       'the',\n       'ringer',\n       'is',\n       'real',\n       'good',\n       'you',\n       'have',\n       'choices',\n       'how',\n       'loud'],\n      'sentiment': 1},\n     {'sentence': ['and', 'none', 'of', 'the', 'tones', 'is', 'acceptable'],\n      'sentiment': 0},\n     {'sentence': ['camera', 'color', 'balance', 'is', 'awful'], 'sentiment': 0},\n     {'sentence': ['this',\n       'product',\n       'is',\n       'clearly',\n       'not',\n       'ready',\n       'for',\n       'prime',\n       'time',\n       'i',\n       'dont',\n       'care',\n       'how',\n       'cool',\n       'it',\n       'looks',\n       'if',\n       'you',\n       'cant',\n       'tell',\n       'a',\n       'call',\n       'is',\n       'coming',\n       'in',\n       'its',\n       'worthless'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'love',\n       'the',\n       'ringtones',\n       'because',\n       'they',\n       'are',\n       'so',\n       'upbeat'],\n      'sentiment': 1},\n     {'sentence': ['chinese', 'forgeries', 'abound'], 'sentiment': 0},\n     {'sentence': ['easy', 'to', 'pair', 'with', 'my', 'samsung', 'cell'],\n      'sentiment': 1},\n     {'sentence': ['the',\n       'instructions',\n       'didnt',\n       'explain',\n       'that',\n       'a',\n       'microphone',\n       'jack',\n       'could',\n       'be',\n       'used'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'would',\n       'advise',\n       'to',\n       'not',\n       'purchase',\n       'this',\n       'item',\n       'it',\n       'never',\n       'worked',\n       'very',\n       'well'],\n      'sentiment': 0},\n     {'sentence': ['too',\n       'bad',\n       'you',\n       'have',\n       'to',\n       'pay',\n       'up',\n       'to',\n       '',\n       'a',\n       'month',\n       'for',\n       'the',\n       'service'],\n      'sentiment': 0},\n     {'sentence': ['works', 'well'], 'sentiment': 1},\n     {'sentence': ['the',\n       'nokia',\n       'ca42',\n       'usb',\n       'cable',\n       'did',\n       'not',\n       'work',\n       'with',\n       'my',\n       'phone'],\n      'sentiment': 0},\n     {'sentence': ['clear', 'crisp', 'sound'], 'sentiment': 1},\n     {'sentence': ['i',\n       'have',\n       'to',\n       'use',\n       'the',\n       'smallest',\n       'earpieces',\n       'provided',\n       'but',\n       'it',\n       'stays',\n       'on',\n       'pretty',\n       'well'],\n      'sentiment': 1},\n     {'sentence': ['the',\n       'biggest',\n       'complaint',\n       'i',\n       'have',\n       'is',\n       'the',\n       'battery',\n       'drains',\n       'superfast'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'design',\n       'might',\n       'be',\n       'ergonomic',\n       'in',\n       'theory',\n       'but',\n       'i',\n       'could',\n       'not',\n       'stand',\n       'having',\n       'these',\n       'in',\n       'my',\n       'ear'],\n      'sentiment': 0},\n     {'sentence': ['do',\n       'not',\n       'buy',\n       'if',\n       'you',\n       'want',\n       'to',\n       'use',\n       'the',\n       'holster'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'phone',\n       'can',\n       'also',\n       'take',\n       'great',\n       'pictures',\n       'and',\n       'even',\n       'video',\n       'clips'],\n      'sentiment': 1},\n     {'sentence': ['it', 'doesnt', 'make', 'you', 'look', 'cool'], 'sentiment': 0},\n     {'sentence': ['because',\n       'both',\n       'ears',\n       'are',\n       'occupied',\n       'background',\n       'is',\n       'not',\n       'distracting',\n       'at',\n       'all'],\n      'sentiment': 1},\n     {'sentence': ['comfortable',\n       'fit',\n       '',\n       'you',\n       'need',\n       'your',\n       'headset',\n       'to',\n       'be',\n       'comfortable',\n       'for',\n       'at',\n       'least',\n       'an',\n       'hour',\n       'at',\n       'a',\n       'time',\n       'if',\n       'not',\n       'for',\n       'an',\n       'entire',\n       'day'],\n      'sentiment': 1},\n     {'sentence': ['also',\n       'the',\n       'phone',\n       'doesnt',\n       'seem',\n       'to',\n       'accept',\n       'anything',\n       'except',\n       'cbr',\n       'mp3s',\n       'preferably',\n       'ripped',\n       'by',\n       'windows',\n       'media',\n       'player'],\n      'sentiment': 0},\n     {'sentence': ['you', 'cant', 'beat', 'the', 'price', 'on', 'these'],\n      'sentiment': 1},\n     {'sentence': ['',\n       'comes',\n       'with',\n       'a',\n       'strong',\n       'light',\n       'that',\n       'you',\n       'can',\n       'use',\n       'to',\n       'light',\n       'up',\n       'your',\n       'camera',\n       'shots',\n       'and',\n       'even',\n       'flash',\n       'sos',\n       'signals',\n       'seriously'],\n      'sentiment': 1},\n     {'sentence': ['lightweight', 'and', 'works', 'well'], 'sentiment': 1},\n     {'sentence': ['so', 'just', 'beware'], 'sentiment': 0},\n     {'sentence': ['i',\n       'love',\n       'this',\n       'cable',\n       '',\n       'it',\n       'allows',\n       'me',\n       'to',\n       'connect',\n       'any',\n       'miniusb',\n       'device',\n       'to',\n       'my',\n       'pc'],\n      'sentiment': 1},\n     {'sentence': ['so',\n       'anyone',\n       'near',\n       'you',\n       'will',\n       'hear',\n       'part',\n       'of',\n       'your',\n       'conversation'],\n      'sentiment': 0},\n     {'sentence': ['this',\n       'is',\n       'cool',\n       'because',\n       'most',\n       'cases',\n       'are',\n       'just',\n       'open',\n       'there',\n       'allowing',\n       'the',\n       'screen',\n       'to',\n       'get',\n       'all',\n       'scratched',\n       'up'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'bought',\n       'this',\n       'phone',\n       'as',\n       'a',\n       'replacement',\n       'for',\n       'my',\n       'startac',\n       'and',\n       'have',\n       'regretted',\n       'it',\n       'since'],\n      'sentiment': 0},\n     {'sentence': ['appears',\n       'to',\n       'actually',\n       'outperform',\n       'the',\n       'original',\n       'battery',\n       'from',\n       'china',\n       'that',\n       'came',\n       'with',\n       'my',\n       'v325i'],\n      'sentiment': 1},\n     {'sentence': ['cant',\n       'store',\n       'anything',\n       'but',\n       'phone',\n       'numbers',\n       'to',\n       'sim'],\n      'sentiment': 0},\n     {'sentence': ['it',\n       'lasts',\n       'less',\n       'than',\n       '3o',\n       'minutes',\n       'if',\n       'i',\n       'actually',\n       'try',\n       'to',\n       'use',\n       'the',\n       'phonemy',\n       'wife',\n       'has',\n       'the',\n       'same',\n       'phone',\n       'with',\n       'the',\n       'same',\n       'problem'],\n      'sentiment': 0},\n     {'sentence': ['poor', 'quality'], 'sentiment': 0},\n     {'sentence': ['jabra', 'ear', 'gels', 'r', 'the', 'best'], 'sentiment': 1},\n     {'sentence': ['not', 'worth', 'it'], 'sentiment': 0},\n     {'sentence': ['the',\n       'phone',\n       'crashed',\n       'completely',\n       'and',\n       'now',\n       'i',\n       'have',\n       'to',\n       'get',\n       'it',\n       'replaced'],\n      'sentiment': 0},\n     {'sentence': ['it',\n       'quit',\n       'working',\n       'after',\n       'id',\n       'used',\n       'it',\n       'for',\n       'about',\n       '18',\n       'months',\n       'so',\n       'i',\n       'just',\n       'purchased',\n       'another',\n       'one',\n       'because',\n       'this',\n       'is',\n       'the',\n       'best',\n       'headset',\n       'ive',\n       'ever',\n       'owned'],\n      'sentiment': 1},\n     {'sentence': ['unfortunately',\n       'it',\n       'will',\n       'not',\n       'recharge',\n       'my',\n       'iphone',\n       '4s',\n       'despite',\n       'connecting',\n       'it',\n       'from',\n       'multiple',\n       'power',\n       'sources',\n       'imac',\n       'external',\n       'battery',\n       'wall',\n       'outlet',\n       'etc'],\n      'sentiment': 0},\n     {'sentence': ['it', 'was', 'a', 'great', 'phone'], 'sentiment': 1},\n     {'sentence': ['if',\n       'you',\n       'simply',\n       'want',\n       'a',\n       'small',\n       'flip',\n       'phone',\n       '',\n       'look',\n       'elsewhere',\n       'as',\n       'the',\n       'extra',\n       'bells',\n       '',\n       'whistles',\n       'are',\n       'mediocre'],\n      'sentiment': 0},\n     {'sentence': ['good',\n       'value',\n       'works',\n       'fine',\n       '',\n       'power',\n       'via',\n       'usb',\n       'car',\n       'or',\n       'wall',\n       'outlet'],\n      'sentiment': 1},\n     {'sentence': ['my',\n       'phone',\n       'doesnt',\n       'slide',\n       'around',\n       'my',\n       'car',\n       'now',\n       'and',\n       'the',\n       'grip',\n       'prevents',\n       'my',\n       'phone',\n       'from',\n       'slipping',\n       'out',\n       'of',\n       'my',\n       'hand'],\n      'sentiment': 1},\n     {'sentence': ['this',\n       'is',\n       'simply',\n       'the',\n       'best',\n       'bluetooth',\n       'headset',\n       'for',\n       'sound',\n       'quality'],\n      'sentiment': 1},\n     {'sentence': ['think',\n       'it',\n       'over',\n       'when',\n       'you',\n       'plan',\n       'to',\n       'own',\n       'this',\n       'onethis',\n       'sure',\n       'is',\n       'the',\n       'last',\n       'moto',\n       'phone',\n       'for',\n       'me'],\n      'sentiment': 0},\n     {'sentence': ['in',\n       'the',\n       'span',\n       'of',\n       'an',\n       'hour',\n       'i',\n       'had',\n       'two',\n       'people',\n       'exclaim',\n       'whoa',\n       '',\n       'is',\n       'that',\n       'the',\n       'new',\n       'phone',\n       'on',\n       'tv'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'have',\n       'always',\n       'used',\n       'corded',\n       'headsets',\n       'and',\n       'the',\n       'freedom',\n       'from',\n       'the',\n       'wireless',\n       'is',\n       'very',\n       'helpful'],\n      'sentiment': 1},\n     {'sentence': ['this',\n       'case',\n       'has',\n       'passed',\n       'the',\n       'one',\n       'year',\n       'mark',\n       'and',\n       'while',\n       'it',\n       'shows',\n       'signs',\n       'of',\n       'wear',\n       'it',\n       'is',\n       '100',\n       'functional'],\n      'sentiment': 1},\n     {'sentence': ['other',\n       'than',\n       'that',\n       'the',\n       'leather',\n       'is',\n       'nice',\n       'and',\n       'soft',\n       'the',\n       'fit',\n       'is',\n       'very',\n       'tight',\n       'the',\n       'cut',\n       'out',\n       'for',\n       'the',\n       'face',\n       'is',\n       'a',\n       'good',\n       'shape'],\n      'sentiment': 1},\n     {'sentence': ['it',\n       'has',\n       'everything',\n       'i',\n       'need',\n       'and',\n       'i',\n       'couldnt',\n       'ask',\n       'for',\n       'more'],\n      'sentiment': 1},\n     {'sentence': ['after',\n       'receiving',\n       'and',\n       'using',\n       'the',\n       'product',\n       'for',\n       'just',\n       '2',\n       'days',\n       'it',\n       'broke'],\n      'sentiment': 0},\n     {'sentence': ['this',\n       'product',\n       'is',\n       'great',\n       'it',\n       'makes',\n       'working',\n       'a',\n       'lot',\n       'easier',\n       'i',\n       'can',\n       'go',\n       'to',\n       'the',\n       'copier',\n       'while',\n       'waiting',\n       'on',\n       'hold',\n       'for',\n       'something'],\n      'sentiment': 1},\n     {'sentence': ['none',\n       'of',\n       'the',\n       'three',\n       'sizes',\n       'they',\n       'sent',\n       'with',\n       'the',\n       'headset',\n       'would',\n       'stay',\n       'in',\n       'my',\n       'ears'],\n      'sentiment': 0},\n     {'sentence': ['tmobile',\n       'has',\n       'the',\n       'best',\n       'customer',\n       'service',\n       'anywhere'],\n      'sentiment': 1},\n     {'sentence': ['arrived',\n       'quickly',\n       'and',\n       'much',\n       'less',\n       'expensive',\n       'than',\n       'others',\n       'being',\n       'sold'],\n      'sentiment': 1},\n     {'sentence': ['we',\n       'have',\n       'tried',\n       '2',\n       'units',\n       'and',\n       'they',\n       'both',\n       'failed',\n       'within',\n       '2',\n       'months',\n       'pros'],\n      'sentiment': 0},\n     {'sentence': ['provides',\n       'good',\n       'protection',\n       'and',\n       'looks',\n       'classy',\n       'too'],\n      'sentiment': 1},\n     {'sentence': ['krussel', 'always', 'good'], 'sentiment': 1},\n     {'sentence': ['the',\n       'tracfonewebsite',\n       'is',\n       'user',\n       'friendly',\n       'and',\n       'makes',\n       'it',\n       'easy',\n       'toactivate',\n       'etc'],\n      'sentiment': 1},\n     {'sentence': ['the', 'design', 'is', 'very', 'good4'], 'sentiment': 1},\n     {'sentence': ['i', 'great', 'reception', 'all', 'the', 'time'],\n      'sentiment': 1},\n     {'sentence': ['i', 'would', 'highly', 'recommend', 'this', 'product'],\n      'sentiment': 1},\n     {'sentence': ['couldnt',\n       'use',\n       'the',\n       'unit',\n       'with',\n       'sunglasses',\n       'not',\n       'good',\n       'in',\n       'texas'],\n      'sentiment': 0},\n     {'sentence': ['it',\n       'dit',\n       'not',\n       'work',\n       'most',\n       'of',\n       'the',\n       'time',\n       'with',\n       'my',\n       'nokia',\n       '5320'],\n      'sentiment': 0},\n     {'sentence': ['bought',\n       'mainly',\n       'for',\n       'the',\n       'charger',\n       'which',\n       'broke',\n       'soon',\n       'after',\n       'purchasing'],\n      'sentiment': 0},\n     {'sentence': ['if',\n       'you',\n       'like',\n       'a',\n       'loud',\n       'buzzing',\n       'to',\n       'override',\n       'all',\n       'your',\n       'conversations',\n       'then',\n       'this',\n       'phone',\n       'is',\n       'for',\n       'you'],\n      'sentiment': 0},\n     {'sentence': ['fantastic',\n       'buy',\n       'and',\n       'will',\n       'get',\n       'again',\n       'for',\n       'whatever',\n       'my',\n       'next',\n       'phone',\n       'is'],\n      'sentiment': 1},\n     {'sentence': ['stay', 'away', 'from', 'this', 'store', 'be', 'careful'],\n      'sentiment': 0},\n     {'sentence': ['this',\n       'blueant',\n       'supertooth',\n       'handsfree',\n       'phone',\n       'speaker',\n       'is',\n       'awesome'],\n      'sentiment': 1},\n     {'sentence': ['does', 'not', 'fit'], 'sentiment': 0},\n     {'sentence': ['',\n       'item',\n       'arrived',\n       'quickly',\n       'and',\n       'works',\n       'great',\n       'with',\n       'my',\n       'metro',\n       'pcs',\n       'samsung',\n       'schr450',\n       'slider',\n       'phone',\n       'and',\n       'sony',\n       'premium',\n       'sound',\n       'in',\n       'ear',\n       'plugs'],\n      'sentiment': 1},\n     {'sentence': ['it',\n       'is',\n       'light',\n       'has',\n       'plenty',\n       'of',\n       'battery',\n       'capacity',\n       'and',\n       'is',\n       'very',\n       'confortable',\n       'to',\n       'wear',\n       'for',\n       'somewhat',\n       'extended',\n       'periods',\n       'of',\n       'time'],\n      'sentiment': 1},\n     {'sentence': ['disappointing'], 'sentiment': 0},\n     {'sentence': ['blue', 'ant', 'is', 'easy', 'to', 'use'], 'sentiment': 1},\n     {'sentence': ['cheap',\n       'but',\n       'hey',\n       'it',\n       'works',\n       'was',\n       'pleasantly',\n       'suprised',\n       'given',\n       'the',\n       'low',\n       'cost',\n       'of',\n       'this',\n       'item'],\n      'sentiment': 1},\n     {'sentence': ['the',\n       'camera',\n       'on',\n       'the',\n       'phone',\n       'may',\n       'be',\n       'used',\n       'as',\n       'a',\n       'dustpan',\n       'when',\n       'indoors',\n       'id',\n       'rather',\n       'be',\n       'using',\n       'a',\n       'disposable',\n       'then',\n       'this'],\n      'sentiment': 0},\n     {'sentence': ['then',\n       'a',\n       'few',\n       'days',\n       'later',\n       'the',\n       'a',\n       'puff',\n       'of',\n       'smoke',\n       'came',\n       'out',\n       'of',\n       'the',\n       'phone',\n       'while',\n       'in',\n       'use'],\n      'sentiment': 0},\n     {'sentence': ['its',\n       'very',\n       'convenient',\n       'and',\n       'simple',\n       'to',\n       'use',\n       '',\n       'gets',\n       'job',\n       'done',\n       '',\n       'makes',\n       'the',\n       'car',\n       'ride',\n       'so',\n       'much',\n       'smoother'],\n      'sentiment': 1},\n     {'sentence': ['the', 'nano', 'stated', 'itmy', 'son', 'was', 'dissapointed'],\n      'sentiment': 0},\n     {'sentence': ['the', 'sound', 'quality', 'is', 'excellent', 'as', 'well'],\n      'sentiment': 1},\n     {'sentence': ['its', 'the', 'best', 'headset', 'i', 'have', 'used'],\n      'sentiment': 1},\n     {'sentence': ['would', 'not', 'reccommend'], 'sentiment': 0},\n     {'sentence': ['they',\n       'have',\n       'been',\n       'around',\n       'for',\n       'years',\n       'and',\n       'carries',\n       'the',\n       'highest',\n       'quality',\n       'of',\n       'antiglare',\n       'screen',\n       'protector',\n       'that',\n       'i',\n       'have',\n       'found',\n       'to',\n       'date'],\n      'sentiment': 1},\n     {'sentence': ['just', 'what', 'i', 'wanted'], 'sentiment': 1},\n     {'sentence': ['this',\n       'particular',\n       'model',\n       'would',\n       'not',\n       'work',\n       'with',\n       'my',\n       'motorola',\n       'q',\n       'smartphone'],\n      'sentiment': 0},\n     {'sentence': ['wont', 'work', 'right', 'or', 'atleast', 'for', 'me'],\n      'sentiment': 0},\n     {'sentence': ['in',\n       'addition',\n       'it',\n       'feels',\n       'amp',\n       'looks',\n       'as',\n       'if',\n       'the',\n       'phone',\n       'is',\n       'all',\n       'lightweight',\n       'cheap',\n       'plastic'],\n      'sentiment': 0},\n     {'sentence': ['but',\n       'now',\n       'that',\n       'it',\n       'is',\n       'out',\n       'of',\n       'warranty',\n       'the',\n       'same',\n       'problems',\n       'reoccurebottom',\n       'line',\n       'put',\n       'your',\n       'money',\n       'somewhere',\n       'else',\n       'cingular',\n       'will',\n       'not',\n       'support',\n       'it'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'really',\n       'wanted',\n       'the',\n       'plantronics',\n       '510',\n       'to',\n       'be',\n       'the',\n       'right',\n       'one',\n       'but',\n       'it',\n       'has',\n       'too',\n       'many',\n       'issues',\n       'for',\n       'methe',\n       'good'],\n      'sentiment': 0},\n     {'sentence': ['great', 'product'], 'sentiment': 1},\n     {'sentence': ['crisp', 'and', 'clear'], 'sentiment': 1},\n     {'sentence': ['after',\n       'the',\n       'first',\n       'charge',\n       'kept',\n       'going',\n       'dead',\n       'after',\n       '12',\n       'minutes'],\n      'sentiment': 0},\n     {'sentence': ['very',\n       'cheap',\n       'plastic',\n       'creaks',\n       'like',\n       'an',\n       'old',\n       'wooden',\n       'floor'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'get',\n       'absolutely',\n       'horrible',\n       'reception',\n       'in',\n       'my',\n       'apartment',\n       'where',\n       'with',\n       'other',\n       'phones',\n       'i',\n       'have',\n       'not',\n       'had',\n       'this',\n       'problem'],\n      'sentiment': 0},\n     {'sentence': ['the', 'reception', 'has', 'been', 'generally', 'good'],\n      'sentiment': 1},\n     {'sentence': ['excellent',\n       'sound',\n       'battery',\n       'life',\n       'and',\n       'inconspicuous',\n       'to',\n       'boot'],\n      'sentiment': 1},\n     {'sentence': ['great', 'bluetooth'], 'sentiment': 1},\n     {'sentence': ['i', 'highly', 'recommend', 'this', 'case'], 'sentiment': 1},\n     {'sentence': ['worthwhile'], 'sentiment': 1},\n     {'sentence': ['this', 'is', 'a', 'great', 'deal'], 'sentiment': 1},\n     {'sentence': ['after',\n       'my',\n       'phone',\n       'got',\n       'to',\n       'be',\n       'about',\n       'a',\n       'year',\n       'old',\n       'its',\n       'been',\n       'slowly',\n       'breaking',\n       'despite',\n       'much',\n       'care',\n       'on',\n       'my',\n       'part'],\n      'sentiment': 0},\n     {'sentence': ['i', 'am', 'sorry', 'i', 'made', 'this', 'purchase'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'bought',\n       'these',\n       'hoping',\n       'i',\n       'could',\n       'make',\n       'my',\n       'bluetooth',\n       'headset',\n       'fit',\n       'better',\n       'but',\n       'these',\n       'things',\n       'made',\n       'it',\n       'impossible',\n       'to',\n       'wear'],\n      'sentiment': 0},\n     {'sentence': ['treo',\n       'and',\n       'tmobile',\n       'refused',\n       'to',\n       'replace',\n       'it',\n       'again',\n       'and',\n       'forced',\n       'me',\n       'to',\n       'buy',\n       'another',\n       'phone',\n       'without',\n       'any',\n       'kind',\n       'of',\n       'upgrade',\n       'discount'],\n      'sentiment': 0},\n     {'sentence': ['it', 'was', 'horrible'], 'sentiment': 0},\n     {'sentence': ['i',\n       'dont',\n       'think',\n       'it',\n       'would',\n       'hold',\n       'it',\n       'too',\n       'securly',\n       'on',\n       'your',\n       'belt'],\n      'sentiment': 0},\n     {'sentence': ['this',\n       'allows',\n       'the',\n       'possibility',\n       'of',\n       'double',\n       'booking',\n       'for',\n       'the',\n       'same',\n       'date',\n       'and',\n       'time',\n       'after',\n       'the',\n       'first'],\n      'sentiment': 0},\n     {'sentence': ['they', 'work', 'about', '2', 'weeks', 'then', 'break'],\n      'sentiment': 0},\n     {'sentence': ['it', 'is', 'simple', 'to', 'use', 'and', 'i', 'like', 'it'],\n      'sentiment': 1},\n     {'sentence': ['its',\n       'a',\n       'great',\n       'tool',\n       'for',\n       'entertainment',\n       'communication',\n       'and',\n       'data',\n       'managementoh',\n       'be',\n       'sure',\n       'to',\n       'use',\n       'activesync',\n       '42',\n       'for',\n       'optimal',\n       'data',\n       'synchronization',\n       'results'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'cant',\n       'use',\n       'this',\n       'case',\n       'because',\n       'the',\n       'smell',\n       'is',\n       'disgusting'],\n      'sentiment': 0},\n     {'sentence': ['not', 'what', 'i', 'wanted'], 'sentiment': 0},\n     {'sentence': ['i',\n       'own',\n       '2',\n       'of',\n       'these',\n       'cases',\n       'and',\n       'would',\n       'order',\n       'another'],\n      'sentiment': 1},\n     {'sentence': ['great', 'phone'], 'sentiment': 1},\n     {'sentence': ['i',\n       'bought',\n       'this',\n       'battery',\n       'with',\n       'a',\n       'coupon',\n       'from',\n       'amazon',\n       'and',\n       'im',\n       'very',\n       'happy',\n       'with',\n       'my',\n       'purchase'],\n      'sentiment': 1},\n     {'sentence': ['the',\n       'internet',\n       'access',\n       'was',\n       'fine',\n       'it',\n       'the',\n       'rare',\n       'instance',\n       'that',\n       'it',\n       'worked'],\n      'sentiment': 0},\n     {'sentence': ['perfect', 'for', 'the', 'ps3'], 'sentiment': 1},\n     {'sentence': ['five', 'star', 'plus', 'plus'], 'sentiment': 1},\n     {'sentence': ['a',\n       'good',\n       'quality',\n       'bargain',\n       'i',\n       'bought',\n       'this',\n       'after',\n       'i',\n       'bought',\n       'a',\n       'cheapy',\n       'from',\n       'big',\n       'lots',\n       'that',\n       'sounded',\n       'awful',\n       'and',\n       'people',\n       'on',\n       'the',\n       'other',\n       'end',\n       'couldnt',\n       'hear',\n       'me'],\n      'sentiment': 1},\n     {'sentence': ['50', 'down', 'the', 'drain'], 'sentiment': 0},\n     {'sentence': ['i',\n       'tried',\n       'talking',\n       'real',\n       'loud',\n       'but',\n       'shouting',\n       'on',\n       'the',\n       'telephone',\n       'gets',\n       'old',\n       'and',\n       'i',\n       'was',\n       'still',\n       'told',\n       'it',\n       'wasnt',\n       'great'],\n      'sentiment': 0},\n     {'sentence': ['good', '', 'works', 'fine'], 'sentiment': 1},\n     {'sentence': ['for', 'the', 'price', 'this', 'was', 'a', 'great', 'deal'],\n      'sentiment': 1},\n     {'sentence': ['great', 'price', 'too'], 'sentiment': 1},\n     {'sentence': ['if',\n       'there',\n       'is',\n       'a',\n       'wind',\n       'it',\n       'is',\n       'completely',\n       'useless'],\n      'sentiment': 0},\n     {'sentence': ['yes',\n       'its',\n       'shiny',\n       'on',\n       'front',\n       'side',\n       '',\n       'and',\n       'i',\n       'love',\n       'it'],\n      'sentiment': 1},\n     {'sentence': ['does', 'not', 'work'], 'sentiment': 0},\n     {'sentence': ['at',\n       'first',\n       'i',\n       'thought',\n       'i',\n       'was',\n       'grtting',\n       'a',\n       'good',\n       'deal',\n       'at',\n       '744',\n       'until',\n       'i',\n       'plugged',\n       'it',\n       'into',\n       'my',\n       'phone',\n       'v3c',\n       'razr'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'reception',\n       'through',\n       'this',\n       'headset',\n       'is',\n       'excellent'],\n      'sentiment': 1},\n     {'sentence': ['2', 'thumbs', 'up', 'to', 'this', 'seller'], 'sentiment': 1},\n     {'sentence': ['i',\n       'have',\n       'a',\n       'verizon',\n       'lg',\n       'phone',\n       'and',\n       'they',\n       'work',\n       'well',\n       'together',\n       'good',\n       'reception',\n       'and',\n       'range',\n       'that',\n       'exceeds',\n       '20',\n       'feet',\n       'line',\n       'of',\n       'sight'],\n      'sentiment': 1},\n     {'sentence': ['improper', 'description', 'i', 'had', 'to', 'return', 'it'],\n      'sentiment': 0},\n     {'sentence': ['1', 'it', 'works', '', '2', 'it', 'is', 'comfortable'],\n      'sentiment': 1},\n     {'sentence': ['battery', 'chargelife', 'is', 'quite', 'long'],\n      'sentiment': 1},\n     {'sentence': ['the', 'jabra', 'eargels', 'fit', 'my', 'ears', 'very', 'well'],\n      'sentiment': 1},\n     {'sentence': ['battery', 'has', 'no', 'life'], 'sentiment': 0},\n     {'sentence': ['i',\n       'checked',\n       'everywhere',\n       'and',\n       'there',\n       'is',\n       'no',\n       'feature',\n       'for',\n       'it',\n       'which',\n       'is',\n       'really',\n       'disappointing'],\n      'sentiment': 0},\n     {'sentence': ['product', 'is', 'exactly', 'as', 'described'], 'sentiment': 1},\n     {'sentence': ['gets',\n       'a',\n       'signal',\n       'when',\n       'other',\n       'verizon',\n       'phones',\n       'wont'],\n      'sentiment': 1},\n     {'sentence': ['doesnt', 'do', 'the', 'job'], 'sentiment': 0},\n     {'sentence': ['i', 'would', 'recommend', 'it'], 'sentiment': 1},\n     {'sentence': ['plan',\n       'on',\n       'ordering',\n       'from',\n       'them',\n       'again',\n       'and',\n       'again'],\n      'sentiment': 1},\n     {'sentence': ['that',\n       'being',\n       'said',\n       'for',\n       'a',\n       'phone',\n       'the',\n       'camera',\n       'is',\n       'very',\n       'nice',\n       'many',\n       'cool',\n       'effects',\n       'to',\n       'play',\n       'with',\n       'and',\n       'video',\n       'is',\n       'decent',\n       'as',\n       'well'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'have',\n       'been',\n       'very',\n       'satisfied',\n       'with',\n       'this',\n       'cell',\n       'phone',\n       'from',\n       'day',\n       'one'],\n      'sentiment': 1},\n     {'sentence': ['they',\n       'keep',\n       'getting',\n       'better',\n       'and',\n       'better',\n       'this',\n       'is',\n       'my',\n       'third',\n       'one',\n       'and',\n       'ive',\n       'had',\n       'numerous',\n       'palms',\n       'too'],\n      'sentiment': 1},\n     {'sentence': ['awkward', 'to', 'use', 'and', 'unreliable'], 'sentiment': 0},\n     {'sentence': ['the', 'shipping', 'time', 'was', 'also', 'very', 'quick'],\n      'sentiment': 1},\n     {'sentence': ['not', 'as', 'good', 'as', 'i', 'had', 'hoped'],\n      'sentiment': 0},\n     {'sentence': ['good', 'case'], 'sentiment': 1},\n     {'sentence': ['doesnt', 'work'], 'sentiment': 0},\n     {'sentence': ['really', 'good', 'product'], 'sentiment': 1},\n     {'sentence': ['unfortunately', 'it', 'did', 'not', 'work'], 'sentiment': 0},\n     {'sentence': ['all',\n       'three',\n       'broke',\n       'within',\n       'two',\n       'months',\n       'of',\n       'use'],\n      'sentiment': 0},\n     {'sentence': ['dont', 'buy', 'it'], 'sentiment': 0},\n     {'sentence': ['my',\n       'father',\n       'has',\n       'the',\n       'v265',\n       'and',\n       'the',\n       'battery',\n       'is',\n       'dying'],\n      'sentiment': 0},\n     {'sentence': ['however',\n       'the',\n       'ear',\n       'pads',\n       'come',\n       'off',\n       'easily',\n       'and',\n       'after',\n       'only',\n       'one',\n       'week',\n       'i',\n       'lost',\n       'one'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'calls',\n       'drop',\n       'the',\n       'phone',\n       'comes',\n       'on',\n       'and',\n       'off',\n       'at',\n       'will',\n       'the',\n       'screen',\n       'goes',\n       'black',\n       'and',\n       'the',\n       'worst',\n       'of',\n       'all',\n       'it',\n       'stops',\n       'ringing',\n       'intermittently'],\n      'sentiment': 0},\n     {'sentence': ['horrible', 'horrible', 'protector'], 'sentiment': 0},\n     {'sentence': ['i', 'dont', 'like', 'this', 'nokia', 'either'],\n      'sentiment': 0},\n     {'sentence': ['reaching',\n       'for',\n       'the',\n       'bottom',\n       'row',\n       'is',\n       'uncomfortable',\n       'and',\n       'the',\n       'send',\n       'and',\n       'end',\n       'keys',\n       'are',\n       'not',\n       'where',\n       'i',\n       'expect',\n       'them',\n       'to',\n       'be3'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'have',\n       'bought',\n       'this',\n       'nokia',\n       'cell',\n       'phone',\n       'a',\n       'few',\n       'weeks',\n       'ago',\n       'and',\n       'it',\n       'was',\n       'a',\n       'nightmare'],\n      'sentiment': 0},\n     {'sentence': ['it',\n       'would',\n       'take',\n       'too',\n       'long',\n       'to',\n       'describe',\n       'how',\n       'bad',\n       'my',\n       'customer',\n       'service',\n       'experience',\n       'has',\n       'been',\n       'with',\n       'amazon'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'only',\n       'very',\n       'disappointing',\n       'thing',\n       'was',\n       'there',\n       'was',\n       'no',\n       'speakerphone'],\n      'sentiment': 0},\n     {'sentence': ['terrible',\n       'my',\n       'car',\n       'will',\n       'not',\n       'accept',\n       'this',\n       'cassette'],\n      'sentiment': 0},\n     {'sentence': ['product',\n       'is',\n       'useless',\n       'since',\n       'it',\n       'does',\n       'not',\n       'have',\n       'enough',\n       'charging',\n       'current',\n       'to',\n       'charge',\n       'the',\n       '2',\n       'cellphones',\n       'i',\n       'was',\n       'planning',\n       'to',\n       'use',\n       'it',\n       'with'],\n      'sentiment': 0},\n     {'sentence': ['its', 'not', 'what', 'it', 'says', 'it', 'is'],\n      'sentiment': 0},\n     {'sentence': ['stay', 'away', 'from', 'the', 'q'], 'sentiment': 0},\n     {'sentence': ['used', 'and', 'dirty'], 'sentiment': 0},\n     {'sentence': ['very', 'unreliable', 'service', 'from', 'tmobile', ''],\n      'sentiment': 0},\n     {'sentence': ['not', 'good', 'enough', 'for', 'the', 'price'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'bought',\n       'two',\n       'of',\n       'them',\n       'and',\n       'neither',\n       'will',\n       'charge'],\n      'sentiment': 0},\n     {'sentence': ['it', 'looks', 'very', 'nice'], 'sentiment': 1},\n     {'sentence': ['this',\n       'is',\n       'an',\n       'excellent',\n       'tool',\n       'especially',\n       'when',\n       'paired',\n       'with',\n       'your',\n       'phones',\n       'autoanswer'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'have',\n       'read',\n       'others',\n       'reviews',\n       'here',\n       'but',\n       'i',\n       'havent',\n       'had',\n       'any',\n       'problem',\n       'with',\n       'it'],\n      'sentiment': 1},\n     {'sentence': ['these',\n       'products',\n       'cover',\n       'up',\n       'the',\n       'important',\n       'light',\n       'sensor',\n       'above',\n       'the',\n       'ear',\n       'outlet'],\n      'sentiment': 0},\n     {'sentence': ['comfortable', 'in', 'my', 'hand'], 'sentiment': 1},\n     {'sentence': ['just', 'does', 'not', 'work'], 'sentiment': 0},\n     {'sentence': ['poor', 'reliability'], 'sentiment': 0},\n     {'sentence': ['it', 'works'], 'sentiment': 1},\n     {'sentence': ['if',\n       'i',\n       'take',\n       'a',\n       'picture',\n       'the',\n       'battery',\n       'drops',\n       'a',\n       'bar',\n       'and',\n       'starts',\n       'beeping',\n       'letting',\n       'me',\n       'know',\n       'its',\n       'dieing'],\n      'sentiment': 0},\n     {'sentence': ['terrible', 'product', 'and', 'waste', 'of', 'money'],\n      'sentiment': 0},\n     {'sentence': ['last', 'time', 'buying', 'from', 'you'], 'sentiment': 0},\n     {'sentence': ['it', 'was', 'a', 'waste', 'of', 'my', 'money'],\n      'sentiment': 0},\n     {'sentence': ['so', 'far', 'it', 'has', 'worked', 'like', 'a', 'charm'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'have',\n       'only',\n       'had',\n       'it',\n       'for',\n       'a',\n       'few',\n       'weeks',\n       'but',\n       'so',\n       'far',\n       'so',\n       'good'],\n      'sentiment': 1},\n     {'sentence': ['but',\n       'in',\n       'any',\n       'case',\n       'the',\n       'best',\n       'part',\n       'is',\n       'you',\n       'can',\n       'download',\n       'these',\n       'pictures',\n       'to',\n       'your',\n       'laptop',\n       'using',\n       'ir',\n       'or',\n       'even',\n       'send',\n       'pictures',\n       'from',\n       'your',\n       'laptop',\n       'to',\n       'the',\n       'phone'],\n      'sentiment': 1},\n     {'sentence': ['would', 'recommend', 'this', 'item'], 'sentiment': 1},\n     {'sentence': ['its',\n       'been',\n       'my',\n       'choice',\n       'headset',\n       'for',\n       'yearsgreat',\n       'sound',\n       'good',\n       'volume',\n       'good',\n       'noise',\n       'cancellation'],\n      'sentiment': 1},\n     {'sentence': ['nice', 'case', 'feels', 'good', 'in', 'your', 'hands'],\n      'sentiment': 1},\n     {'sentence': ['the', 'item', 'received', 'was', 'counterfeit'],\n      'sentiment': 0},\n     {'sentence': ['just',\n       'really',\n       'good',\n       'so',\n       'far',\n       'probably',\n       'the',\n       'best',\n       'bt',\n       'headset',\n       'i',\n       'have',\n       'ever',\n       'had'],\n      'sentiment': 1},\n     {'sentence': ['works', 'fine'], 'sentiment': 1},\n     {'sentence': ['i',\n       'received',\n       'my',\n       'headset',\n       'in',\n       'good',\n       'time',\n       'and',\n       'was',\n       'happy',\n       'with',\n       'it'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'was',\n       'very',\n       'pleased',\n       'to',\n       'see',\n       'that',\n       'i',\n       'could',\n       'replace',\n       'my',\n       'well',\n       'travled',\n       'swivel',\n       'holster',\n       'for',\n       'my',\n       'blackberry',\n       'flip'],\n      'sentiment': 1},\n     {'sentence': ['my',\n       'sister',\n       'has',\n       'one',\n       'also',\n       'and',\n       'she',\n       'loves',\n       'it'],\n      'sentiment': 1},\n     {'sentence': ['good', 'quality'], 'sentiment': 1},\n     {'sentence': ['this',\n       'is',\n       'by',\n       'far',\n       'the',\n       'worst',\n       'purchase',\n       'ive',\n       'made',\n       'on',\n       'amazon'],\n      'sentiment': 0},\n     {'sentence': ['excellent', 'dualpurpose', 'headset'], 'sentiment': 1},\n     {'sentence': ['excellent'], 'sentiment': 1},\n     {'sentence': ['does',\n       'not',\n       'work',\n       'for',\n       'listening',\n       'to',\n       'music',\n       'with',\n       'the',\n       'cingular',\n       '8125'],\n      'sentiment': 0},\n     {'sentence': ['it',\n       'seems',\n       'completely',\n       'secure',\n       'both',\n       'holding',\n       'on',\n       'to',\n       'my',\n       'belt',\n       'and',\n       'keeping',\n       'the',\n       'iphone',\n       'inside'],\n      'sentiment': 1},\n     {'sentence': ['the',\n       'bottowm',\n       'lineanother',\n       'worthless',\n       'cheap',\n       'gimmick',\n       'from',\n       'sprint'],\n      'sentiment': 0},\n     {'sentence': ['having', 'trouble', 'with', 'volume'], 'sentiment': 0},\n     {'sentence': ['the',\n       'only',\n       'good',\n       'thing',\n       'was',\n       'that',\n       'it',\n       'fits',\n       'comfortably',\n       'on',\n       'small',\n       'ears'],\n      'sentiment': 1},\n     {'sentence': ['warning', '', 'do', 'not', 'buy'], 'sentiment': 0},\n     {'sentence': ['i',\n       'am',\n       'pairing',\n       'this',\n       'with',\n       'my',\n       'iphone',\n       'and',\n       'i',\n       'could',\n       'not',\n       'be',\n       'happier',\n       'with',\n       'it',\n       'so',\n       'far'],\n      'sentiment': 1},\n     {'sentence': ['when',\n       'it',\n       'opens',\n       'the',\n       'battery',\n       'connection',\n       'is',\n       'broken',\n       'and',\n       'the',\n       'device',\n       'is',\n       'turned',\n       'off'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'didnt',\n       'want',\n       'the',\n       'clip',\n       'going',\n       'over',\n       'the',\n       'top',\n       'of',\n       'my',\n       'ear',\n       'causing',\n       'discomfort'],\n      'sentiment': 0},\n     {'sentence': ['best', 'headset', 'ever'], 'sentiment': 1},\n     {'sentence': ['dont',\n       'trust',\n       'their',\n       'website',\n       'and',\n       'dont',\n       'expect',\n       'any',\n       'helpful',\n       'support'],\n      'sentiment': 0},\n     {'sentence': ['it',\n       'was',\n       'that',\n       'loudglad',\n       'to',\n       'say',\n       'that',\n       'the',\n       'plantronics',\n       '510',\n       'maintains',\n       'a',\n       'flawless',\n       'connection',\n       'to',\n       'my',\n       'cell',\n       'and',\n       'with',\n       'no',\n       'static',\n       'during',\n       'normal',\n       'use'],\n      'sentiment': 1},\n     {'sentence': ['the',\n       'speaker',\n       'is',\n       'of',\n       'low',\n       'quality',\n       'so',\n       'as',\n       'making',\n       'the',\n       'ring',\n       'tones',\n       'sound',\n       'very',\n       'cheap'],\n      'sentiment': 0},\n     {'sentence': ['fits',\n       'comfortably',\n       'came',\n       'with',\n       'three',\n       'sizes',\n       'of',\n       'earbud',\n       'tips'],\n      'sentiment': 1},\n     {'sentence': ['excellent', 'product', 'for', 'the', 'price'], 'sentiment': 1},\n     {'sentence': ['bad', 'reception'], 'sentiment': 0},\n     {'sentence': ['this',\n       'product',\n       'is',\n       'very',\n       'high',\n       'quality',\n       'chinese',\n       'crap'],\n      'sentiment': 0},\n     {'sentence': ['it', 'was', 'quite', 'comfortable', 'in', 'the', 'ear'],\n      'sentiment': 1},\n     {'sentence': ['great', 'phone'], 'sentiment': 1},\n     {'sentence': ['dont', 'buy', 'this', 'product', '', 'it', 'fails'],\n      'sentiment': 0},\n     {'sentence': ['everything', 'about', 'this', 'product', 'is', 'wrongfirst'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'pairing',\n       'of',\n       'the',\n       'two',\n       'devices',\n       'was',\n       'so',\n       'easy',\n       'it',\n       'barely',\n       'took',\n       'a',\n       'couple',\n       'minutes',\n       'before',\n       'i',\n       'started',\n       'making',\n       'calls',\n       'with',\n       'the',\n       'voice',\n       'dialing',\n       'feature'],\n      'sentiment': 1},\n     {'sentence': ['this',\n       'was',\n       'utterly',\n       'confusing',\n       'at',\n       'first',\n       'which',\n       'caused',\n       'me',\n       'to',\n       'lose',\n       'a',\n       'couple',\n       'of',\n       'very',\n       'very',\n       'important',\n       'contacts'],\n      'sentiment': 0},\n     {'sentence': ['terrible', 'phone', 'holder'], 'sentiment': 0},\n     {'sentence': ['the',\n       'cutouts',\n       'and',\n       'buttons',\n       'are',\n       'placed',\n       'perfectly'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'love',\n       'being',\n       'able',\n       'to',\n       'use',\n       'one',\n       'headset',\n       'for',\n       'both',\n       'by',\n       'landline',\n       'and',\n       'cell'],\n      'sentiment': 1},\n     {'sentence': ['problem',\n       'is',\n       'that',\n       'the',\n       'ear',\n       'loops',\n       'are',\n       'made',\n       'of',\n       'weak',\n       'material',\n       'and',\n       'break',\n       'easily'],\n      'sentiment': 0},\n     {'sentence': ['not',\n       'nearly',\n       'as',\n       'good',\n       'looking',\n       'as',\n       'the',\n       'amazon',\n       'picture',\n       'makes',\n       'it',\n       'look'],\n      'sentiment': 0},\n     {'sentence': ['but',\n       'despite',\n       'these',\n       'few',\n       'flaws',\n       'this',\n       'case',\n       'is',\n       'of',\n       'exceptional',\n       'quality',\n       'and',\n       'well',\n       'worth',\n       'the',\n       'additional',\n       'costs',\n       'of',\n       'owning',\n       'an',\n       'official',\n       'oem',\n       'product'],\n      'sentiment': 1},\n     {'sentence': ['how', 'stupid', 'is', 'that'], 'sentiment': 0},\n     {'sentence': ['i',\n       'can',\n       'hear',\n       'while',\n       'im',\n       'driving',\n       'in',\n       'the',\n       'car',\n       'and',\n       'usually',\n       'dont',\n       'even',\n       'have',\n       'to',\n       'put',\n       'it',\n       'on',\n       'its',\n       'loudest',\n       'setting'],\n      'sentiment': 1},\n     {'sentence': ['seller',\n       'shipped',\n       'quickly',\n       'and',\n       'much',\n       'cheaper',\n       'than',\n       'the',\n       'competitors'],\n      'sentiment': 1},\n     {'sentence': ['good', 'show', 'samsung'], 'sentiment': 1},\n     {'sentence': ['so',\n       'i',\n       'bought',\n       'about',\n       '10',\n       'of',\n       'these',\n       'and',\n       'saved',\n       'alot',\n       'of',\n       'money'],\n      'sentiment': 1},\n     {'sentence': ['it',\n       'always',\n       'cuts',\n       'out',\n       'and',\n       'makes',\n       'a',\n       'beep',\n       'beep',\n       'beep',\n       'sound',\n       'then',\n       'says',\n       'signal',\n       'failed'],\n      'sentiment': 0},\n     {'sentence': ['couldnt', 'figure', 'it', 'out'], 'sentiment': 0},\n     {'sentence': ['my',\n       'phone',\n       'sounded',\n       'ok',\n       '',\n       'not',\n       'great',\n       '',\n       'ok',\n       'but',\n       'my',\n       'wifes',\n       'phone',\n       'was',\n       'almost',\n       'totally',\n       'unintelligible',\n       'she',\n       'couldnt',\n       'understand',\n       'a',\n       'word',\n       'being',\n       'said',\n       'on',\n       'it'],\n      'sentiment': 0},\n     {'sentence': ['so',\n       'i',\n       'had',\n       'to',\n       'take',\n       'the',\n       'battery',\n       'out',\n       'of',\n       'the',\n       'phone',\n       'put',\n       'it',\n       'all',\n       'back',\n       'together',\n       'and',\n       'then',\n       'restart',\n       'it'],\n      'sentiment': 0},\n     {'sentence': ['while',\n       'i',\n       'managed',\n       'to',\n       'bend',\n       'the',\n       'leaf',\n       'spring',\n       'back',\n       'in',\n       'place',\n       'the',\n       'metal',\n       'now',\n       'has',\n       'enough',\n       'stress',\n       'that',\n       'it',\n       'will',\n       'break',\n       'on',\n       'the',\n       'next',\n       'drop'],\n      'sentiment': 0},\n     {'sentence': ['leopard', 'print', 'is', 'wonderfully', 'wild'],\n      'sentiment': 1},\n     {'sentence': ['works', 'for', 'me'], 'sentiment': 1},\n     {'sentence': ['saggy', 'floppy', 'piece', 'of', 'junk'], 'sentiment': 0},\n     {'sentence': ['much', 'better', 'than', 'the', 'hard', 'plastic', 'cases'],\n      'sentiment': 1},\n     {'sentence': ['it', 'also', 'had', 'a', 'new', 'problem'], 'sentiment': 0},\n     {'sentence': ['happy', 'so', 'far'], 'sentiment': 1},\n     {'sentence': ['cool', 'phone'], 'sentiment': 1},\n     {'sentence': ['works', 'good'], 'sentiment': 1},\n     {'sentence': ['motorola',\n       'finally',\n       'got',\n       'the',\n       'voice',\n       'quality',\n       'of',\n       'a',\n       'bluetooth',\n       'headset',\n       'right'],\n      'sentiment': 1},\n     {'sentence': ['it',\n       'looses',\n       'connection',\n       'to',\n       'the',\n       'phone',\n       'even',\n       'when',\n       'it',\n       'is',\n       'within',\n       'a',\n       'couple',\n       'feet',\n       'between',\n       'the',\n       'two'],\n      'sentiment': 0},\n     {'sentence': ['but',\n       'it',\n       'is',\n       'great',\n       'i',\n       'would',\n       'really',\n       'recommend',\n       'it'],\n      'sentiment': 1},\n     {'sentence': ['makes',\n       'it',\n       'easier',\n       'to',\n       'keep',\n       'up',\n       'with',\n       'my',\n       'bluetooth',\n       'when',\n       'im',\n       'not',\n       'wearing',\n       'it'],\n      'sentiment': 0},\n     {'sentence': ['as', 'i', 'said', 'abovepretty', 'useless'], 'sentiment': 0},\n     {'sentence': ['never', 'got', 'it'], 'sentiment': 0},\n     {'sentence': ['this',\n       'pair',\n       'of',\n       'headphones',\n       'is',\n       'the',\n       'worst',\n       'that',\n       'i',\n       'have',\n       'ever',\n       'had',\n       'soundwise'],\n      'sentiment': 0},\n     {'sentence': ['',\n       'down',\n       'the',\n       'drain',\n       'because',\n       'of',\n       'a',\n       'weak',\n       'snap'],\n      'sentiment': 0},\n     {'sentence': ['does',\n       'not',\n       'charge',\n       'the',\n       'cingular',\n       'att',\n       '8525',\n       'phone'],\n      'sentiment': 0},\n     {'sentence': ['you',\n       'get',\n       'extra',\n       'minutes',\n       'so',\n       'that',\n       'you',\n       'can',\n       'carry',\n       'out',\n       'the',\n       'call',\n       'and',\n       'not',\n       'get',\n       'cut',\n       'off'],\n      'sentiment': 1},\n     {'sentence': ['however',\n       'after',\n       'about',\n       'a',\n       'year',\n       'the',\n       'fliptop',\n       'started',\n       'to',\n       'get',\n       'loose',\n       'and',\n       'wobbly',\n       'and',\n       'eventually',\n       'my',\n       'screen',\n       'went',\n       'black',\n       'and',\n       'i',\n       'couldnt',\n       'receive',\n       'and',\n       'place',\n       'calls'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'kept',\n       'catching',\n       'the',\n       'cable',\n       'on',\n       'the',\n       'seat',\n       'and',\n       'i',\n       'had',\n       'to',\n       'pull',\n       'the',\n       'phone',\n       'out',\n       'to',\n       'turn',\n       'it',\n       'on',\n       'an',\n       'off'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'headset',\n       'fulfills',\n       'my',\n       'requirements',\n       'so',\n       'i',\n       'am',\n       'happy',\n       'with',\n       'my',\n       'purchase'],\n      'sentiment': 1},\n     {'sentence': ['logitech', 'bluetooth', 'headset', 'is', 'a', '10'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'like',\n       'the',\n       'fact',\n       'that',\n       'it',\n       'rests',\n       'lightly',\n       'against',\n       'your',\n       'ear',\n       'rather',\n       'than',\n       'inside'],\n      'sentiment': 1},\n     {'sentence': ['a',\n       'lot',\n       'of',\n       'websites',\n       'have',\n       'been',\n       'rating',\n       'this',\n       'a',\n       'very',\n       'good',\n       'phone',\n       'and',\n       'so',\n       'do',\n       'i'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'have',\n       'tried',\n       'these',\n       'cables',\n       'with',\n       'my',\n       'computer',\n       'and',\n       'my',\n       'ipod',\n       'and',\n       'it',\n       'works',\n       'just',\n       'fine'],\n      'sentiment': 1},\n     {'sentence': ['the',\n       'mic',\n       'there',\n       'is',\n       'a',\n       'joke',\n       'and',\n       'the',\n       'volume',\n       'is',\n       'quite',\n       'low'],\n      'sentiment': 0},\n     {'sentence': ['im', 'returning', 'them'], 'sentiment': 0},\n     {'sentence': ['i',\n       'does',\n       'not',\n       'maintain',\n       'a',\n       'connection',\n       'with',\n       'the',\n       'computer',\n       'while',\n       'it',\n       'is',\n       'on',\n       'my',\n       'lap'],\n      'sentiment': 0},\n     {'sentence': ['it',\n       'is',\n       'easy',\n       'to',\n       'turn',\n       'on',\n       'and',\n       'off',\n       'when',\n       'you',\n       'are',\n       'in',\n       'the',\n       'car',\n       'and',\n       'the',\n       'volume',\n       'controls',\n       'are',\n       'quite',\n       'accessable'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'have',\n       'had',\n       'mine',\n       'for',\n       'about',\n       'a',\n       'year',\n       'and',\n       'this',\n       'christmas',\n       'i',\n       'bought',\n       'some',\n       'for',\n       'the',\n       'rest',\n       'of',\n       'the',\n       'family'],\n      'sentiment': 1},\n     {'sentence': ['otherwise',\n       'easy',\n       'to',\n       'install',\n       'and',\n       'use',\n       'clear',\n       'sound'],\n      'sentiment': 1},\n     {'sentence': ['nice', 'leather'], 'sentiment': 1},\n     {'sentence': ['i', 'had', 'to', 'purchase', 'a', 'different', 'case'],\n      'sentiment': 0},\n     {'sentence': ['it', 'is', 'a', 'joy', 'to', 'use'], 'sentiment': 1},\n     {'sentence': ['very', 'much', 'disappointed', 'with', 'this', 'company'],\n      'sentiment': 0},\n     {'sentence': ['very', 'satisifed', 'with', 'that'], 'sentiment': 1},\n     {'sentence': ['it', 'didnt', 'charge', 'for', 'me'], 'sentiment': 0},\n     {'sentence': ['this',\n       'is',\n       'the',\n       'phone',\n       'to',\n       'get',\n       'for',\n       '2005',\n       'i',\n       'just',\n       'bought',\n       'my',\n       's710a',\n       'and',\n       'all',\n       'i',\n       'can',\n       'say',\n       'is',\n       'wow'],\n      'sentiment': 1},\n     {'sentence': ['buttons', 'are', 'too', 'small'], 'sentiment': 0},\n     {'sentence': ['just',\n       'reading',\n       'on',\n       'the',\n       'specs',\n       'alone',\n       'makes',\n       'you',\n       'say',\n       'wow'],\n      'sentiment': 1},\n     {'sentence': ['love', 'it', 'great', 'armband'], 'sentiment': 1},\n     {'sentence': ['i',\n       'really',\n       'like',\n       'this',\n       'product',\n       'over',\n       'the',\n       'motorola',\n       'because',\n       'it',\n       'is',\n       'allot',\n       'clearer',\n       'on',\n       'the',\n       'ear',\n       'piece',\n       'and',\n       'the',\n       'mic'],\n      'sentiment': 1},\n     {'sentence': ['however',\n       'the',\n       'keypads',\n       'are',\n       'so',\n       'tinny',\n       'that',\n       'i',\n       'sometimes',\n       'reach',\n       'the',\n       'wrong',\n       'buttons'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'exchanged',\n       'the',\n       'sony',\n       'ericson',\n       'z500a',\n       'for',\n       'this',\n       'and',\n       'im',\n       'pretty',\n       'happy',\n       'with',\n       'that',\n       'decision'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'was',\n       'very',\n       'impressed',\n       'with',\n       'the',\n       'price',\n       'of',\n       'the',\n       'cases'],\n      'sentiment': 1},\n     {'sentence': ['also', 'makes', 'it', 'easier', 'to', 'hold', 'on', 'to'],\n      'sentiment': 1},\n     {'sentence': ['i',\n       'use',\n       'this',\n       'product',\n       'in',\n       'a',\n       'motor',\n       'control',\n       'center',\n       'where',\n       'there',\n       'is',\n       'a',\n       'lot',\n       'of',\n       'high',\n       'voltage',\n       'humming',\n       'from',\n       'the',\n       'equipment',\n       'and',\n       'it',\n       'works',\n       'great'],\n      'sentiment': 1},\n     {'sentence': ['its', 'pretty', 'easy'], 'sentiment': 1},\n     {'sentence': ['i', 'cannot', 'make', 'calls', 'at', 'certain', 'places'],\n      'sentiment': 0},\n     {'sentence': ['however',\n       'my',\n       'girl',\n       'was',\n       'complain',\n       'that',\n       'some',\n       'time',\n       'the',\n       'phone',\n       'doesnt',\n       'wake',\n       'up',\n       'like',\n       'normal',\n       'phone',\n       'does'],\n      'sentiment': 0},\n     {'sentence': ['beautiful', 'styling', 'though'], 'sentiment': 1},\n     {'sentence': ['this',\n       'company',\n       'charge',\n       'me',\n       'a',\n       'restocking',\n       'fee',\n       'and',\n       'still',\n       'not',\n       'given',\n       'me',\n       'my',\n       'refund',\n       'back'],\n      'sentiment': 0},\n     {'sentence': ['im', 'trying', 'to', 'return', 'it', 'for', 'a', 'refund'],\n      'sentiment': 0},\n     {'sentence': ['i',\n       'plugged',\n       'it',\n       'in',\n       'only',\n       'to',\n       'find',\n       'out',\n       'not',\n       'a',\n       'darn',\n       'thing',\n       'worked'],\n      'sentiment': 0},\n     {'sentence': ['excellent', 'product'], 'sentiment': 1},\n     {'sentence': ['earbud', 'piece', 'breaks', 'easily'], 'sentiment': 0},\n     {'sentence': ['lousy', 'product'], 'sentiment': 0},\n     {'sentence': ['this',\n       'phone',\n       'tries',\n       'very',\n       'hard',\n       'to',\n       'do',\n       'everything',\n       'but',\n       'fails',\n       'at',\n       'its',\n       'very',\n       'ability',\n       'to',\n       'be',\n       'a',\n       'phone'],\n      'sentiment': 0},\n     {'sentence': ['it',\n       'is',\n       'the',\n       'best',\n       'charger',\n       'i',\n       'have',\n       'seen',\n       'on',\n       'the',\n       'market',\n       'yet'],\n      'sentiment': 1},\n     {'sentence': ['sweetest', 'phone'], 'sentiment': 1},\n     {'sentence': ['oh', 'the', 'charger', 'seems', 'to', 'work', 'fine'],\n      'sentiment': 1},\n     {'sentence': ['it',\n       'fits',\n       'so',\n       'securely',\n       'that',\n       'the',\n       'ear',\n       'hook',\n       'does',\n       'not',\n       'even',\n       'need',\n       'to',\n       'be',\n       'used',\n       'and',\n       'the',\n       'sound',\n       'is',\n       'better',\n       'directed',\n       'through',\n       'your',\n       'ear',\n       'canal'],\n      'sentiment': 1},\n     {'sentence': ['not', 'enough', 'volume'], 'sentiment': 0},\n     {'sentence': ['echo', 'problemvery', 'unsatisfactory'], 'sentiment': 0},\n     {'sentence': ['you',\n       'could',\n       'only',\n       'take',\n       '2',\n       'videos',\n       'at',\n       'a',\n       'time',\n       'and',\n       'the',\n       'quality',\n       'was',\n       'very',\n       'poor'],\n      'sentiment': 0},\n     {'sentence': ['dont', 'waste', 'your', 'money'], 'sentiment': 0},\n     {'sentence': ['i',\n       'am',\n       'going',\n       'to',\n       'have',\n       'to',\n       'be',\n       'the',\n       'first',\n       'to',\n       'negatively',\n       'review',\n       'this',\n       'product'],\n      'sentiment': 0},\n     {'sentence': ['adapter',\n       'does',\n       'not',\n       'provide',\n       'enough',\n       'charging',\n       'current'],\n      'sentiment': 0},\n     {'sentence': ['there',\n       'was',\n       'so',\n       'much',\n       'hype',\n       'over',\n       'this',\n       'phone',\n       'that',\n       'i',\n       'assumed',\n       'it',\n       'was',\n       'the',\n       'best',\n       'my',\n       'mistake'],\n      'sentiment': 0},\n     {'sentence': ['you',\n       'also',\n       'cannot',\n       'take',\n       'pictures',\n       'with',\n       'it',\n       'in',\n       'the',\n       'case',\n       'because',\n       'the',\n       'lense',\n       'is',\n       'covered'],\n      'sentiment': 0},\n     {'sentence': ['phone', 'falls', 'out', 'easily'], 'sentiment': 0},\n     {'sentence': ['it',\n       'didnt',\n       'work',\n       'people',\n       'can',\n       'not',\n       'hear',\n       'me',\n       'when',\n       'i',\n       'talk'],\n      'sentiment': 0},\n     {'sentence': ['the',\n       'text',\n       'messaging',\n       'feature',\n       'is',\n       'really',\n       'tricky',\n       'to',\n       'use'],\n      'sentiment': 0},\n     {'sentence': ['im',\n       'really',\n       'disappointed',\n       'all',\n       'i',\n       'have',\n       'now',\n       'is',\n       'a',\n       'charger',\n       'that',\n       'doesnt',\n       'work'],\n      'sentiment': 0},\n     {'sentence': ['painful', 'on', 'the', 'ear'], 'sentiment': 0},\n     {'sentence': ['lasted', 'one', 'day', 'and', 'then', 'blew', 'up'],\n      'sentiment': 0},\n     {'sentence': ['disappointed'], 'sentiment': 0},\n     {'sentence': ['kind', 'of', 'flops', 'around'], 'sentiment': 0},\n     {'sentence': ['the',\n       'screen',\n       'does',\n       'get',\n       'smudged',\n       'easily',\n       'because',\n       'it',\n       'touches',\n       'your',\n       'ear',\n       'and',\n       'face'],\n      'sentiment': 0},\n     {'sentence': ['what',\n       'a',\n       'piece',\n       'of',\n       'junk',\n       'i',\n       'lose',\n       'more',\n       'calls',\n       'on',\n       'this',\n       'phone'],\n      'sentiment': 0},\n     {'sentence': ['item', 'does', 'not', 'match', 'picture'], 'sentiment': 0},\n     {'sentence': ['the',\n       'only',\n       'thing',\n       'that',\n       'disappoint',\n       'me',\n       'is',\n       'the',\n       'infra',\n       'red',\n       'port',\n       'irda'],\n      'sentiment': 0},\n     {'sentence': ['you',\n       'can',\n       'not',\n       'answer',\n       'calls',\n       'with',\n       'the',\n       'unit',\n       'never',\n       'worked',\n       'once'],\n      'sentiment': 0}]\n\n\n\n# qTransformer Model\n\n\n```python\nclass QuantumTransformer:\n    def embed_sentence(self, sentence):\n        embedded_sentence = np.array(\n            [self.embeddings[word] for word in sentence]\n        ).flatten()\n        return np.pad(\n            embedded_sentence, (0, self.sequence_length - embedded_sentence.size)\n        )\n\n    def __init__(\n        self,\n        sequence_length,\n        embedding_dimension,\n        embedding_dict,\n        quantum_instance=Aer.get_backend(\"qasm_simulator\"),\n        reps=1,\n        iterations=200,\n        include_attention=True,\n        include_residual=True,\n    ):\n\n        # Model Layers\n        def attention_pair(i, j, l=0):\n            qc = QuantumCircuit(2)\n            qc.u(*ParameterVector(\"atn_%d_pair_%d%d_0\" % (l, i, j), length=3), 0)\n            qc.u(*ParameterVector(\"atn_%d_pair_%d%d_1\" % (l, i, j), length=3), 1)\n            qc.cx(1, 0)\n            qc.u(*ParameterVector(\"atn_%d_pair_%d%d_2\" % (l, i, j), length=3), 0)\n            qc.u(*ParameterVector(\"atn_%d_pair_%d%d_3\" % (l, i, j), length=3), 1)\n            qc.cx(0, 1)\n            qc.u(*ParameterVector(\"atn_%d_pair_%d%d_4\" % (l, i, j), length=3), 0)\n            qc.u(*ParameterVector(\"atn_%d_pair_%d%d_5\" % (l, i, j), length=3), 1)\n            qc.cx(1, 0)\n            qc.u(*ParameterVector(\"atn_%d_pair_%d%d_6\" % (l, i, j), length=3), 0)\n            qc.u(*ParameterVector(\"atn_%d_pair_%d%d_7\" % (l, i, j), length=3), 1)\n            return qc.to_gate(label=\"Attention(%d, %d)\" % (i, j))\n\n        def attention(n, l=0):\n            qc = QuantumCircuit(n)\n            for pair in itertools.combinations(range(n), 2):\n                qc.append(attention_pair(*pair, l=l), pair)\n            return qc.to_gate(label=\"Attention\")\n\n        def residual(n):\n            qc = QuantumCircuit(2 * n)\n            for i in range(n):\n                qc.cx(n + i, i)\n            return qc.to_gate(label=\"Residual\")\n\n        # Classifier Utilities\n        def parity(x):\n            return \"{:b}\".format(x).count(\"1\") % 2\n\n        def callback_graph(weights, obj_func_eval):\n            clear_output(wait=True)\n            objective_func_vals.append(obj_func_eval)\n            plt.title(\"Objective Function vs. Iteration\")\n            plt.xlabel(\"Iteration\")\n            plt.ylabel(\"Objective Function\")\n            plt.plot(range(len(objective_func_vals)), objective_func_vals)\n            plt.show()\n\n        self.sequence_length = sequence_length\n        self.embedding_dimension = embedding_dimension\n\n        n = self.sequence_length * self.embedding_dimension\n\n        pca = PCA(n_components=self.embedding_dimension)\n        self.embeddings = {}\n        word_to_num = {}\n        embeds_matrix = []\n\n        for i, word in enumerate(embedding_dict.vocab.keys()):\n            word_to_num[word] = i\n            embeds_matrix.append(embedding_dict[word])\n\n        embeds_matrix = np.array(embeds_matrix)\n        embeds_matrix = pca.fit_transform(embeds_matrix)\n        for word in embedding_dict.vocab.keys():\n            self.embeddings[word] = embeds_matrix[word_to_num[word]]\n\n        feature_map = PauliFeatureMap(n)\n        if include_attention:\n            attention_layers = [attention(n, l=i) for i in range(reps)]\n        if include_residual:\n            residual_layers = [residual(n) for _ in range(reps)]\n        feed_forward_layers = [\n            EfficientSU2(n, parameter_prefix=str(i)) for i in range(reps)\n        ]\n\n        self.circuit = QuantumCircuit(2 * n if include_residual else n)\n\n        self.circuit.append(feature_map, range(n))\n        if include_residual:\n            self.circuit.append(feature_map, range(n, 2 * n))\n\n        for i in range(reps):\n            if include_attention:\n                self.circuit.append(attention_layers[i], range(n))\n            if include_residual:\n                self.circuit.append(residual_layers[i], range(2 * n))\n            self.circuit.append(feed_forward_layers[i], range(n))\n\n        self.network = CircuitQNN(\n            circuit=self.circuit,\n            input_params=feature_map.parameters,\n            weight_params=ParameterView(\n                (\n                    [parameter for l in attention_layers for parameter in l.params]\n                    if include_attention\n                    else []\n                )\n                + [parameter for l in feed_forward_layers for parameter in l.parameters]\n            ),\n            interpret=parity,\n            output_shape=2,\n            quantum_instance=quantum_instance,\n        )\n\n        self.classifier = NeuralNetworkClassifier(\n            neural_network=self.network,\n            optimizer=COBYLA(maxiter=iterations),\n            callback=callback_graph,\n        )\n\n    def preprocess_data(self, corpus):\n        filtered_sequences = []\n        for sentence in corpus:\n            sequences = [\n                {\n                    \"sentence\": sentence[\"sentence\"][i : i + self.sequence_length],\n                    \"sentiment\": sentence[\"sentiment\"],\n                }\n                for i in range(0, len(sentence[\"sentence\"]), self.sequence_length)\n            ]\n            for sequence in sequences:\n                if all(word in self.embeddings for word in sequence[\"sentence\"]):\n                    filtered_sequences.append(sequence)\n        filtered_sequences = [\n            sentence for sentence in filtered_sequences if len(sentence[\"sentence\"]) > 2\n        ]\n\n        vocab = []\n        for sequence in filtered_sequences:\n            vocab.extend(sequence[\"sentence\"])\n        vocab = list(set(vocab))\n\n        X = np.array(\n            [\n                self.embed_sentence(sentence[\"sentence\"])\n                for sentence in filtered_sequences\n            ]\n        )\n        Y = np.array(\n            [\n                sentence[\"sentiment\"]\n                for sentence in filtered_sequences\n                if len(sentence[\"sentence\"]) > 2\n            ]\n        )\n\n        return X, Y\n\n    def train(self, X, Y):\n        plt.rcParams[\"figure.figsize\"] = (12, 6)\n        self.classifier.fit(X, Y)\n        plt.rcParams[\"figure.figsize\"] = (6, 4)\n\n    def score(self, X, Y):\n        return self.classifier.score(X, Y)\n\n    def predict(self, sentence):\n        print()\n        return self.classifier.predict(\n            self.embed_sentence(\n                [\n                    \"\".join(e for e in word if e.isalnum()).lower()\n                    for word in sentence.split()\n                ]\n            )\n        )\n\n```\n\n# Performance Evaluation\n\n\n```python\nEMBEDDING_DIMS = 1\nTRAIN_DATA_SIZE = 50\nSEQUENCE_LENGTH = 4\n```\n\n## w/o Attention\n\n\n```python\ntransformer = QuantumTransformer(sequence_length=SEQUENCE_LENGTH, embedding_dimension=EMBEDDING_DIMS, embedding_dict=embeddings_dict, include_attention=0, include_residual=0)\ntransformer.circuit.draw(\"mpl\") \n```\n\n\n```python\nX, Y = transformer.preprocess_data(corpus)\n```\n\n\n```python\nobjective_func_vals = []\nplt.rcParams[\"figure.figsize\"] = (12, 6)\ntransformer.classifier.fit(X[:TRAIN_DATA_SIZE], Y[:TRAIN_DATA_SIZE])\nplt.rcParams[\"figure.figsize\"] = (6, 4)\n```\n\n\n```python\ntransformer.classifier.score(X[:TRAIN_DATA_SIZE], Y[:TRAIN_DATA_SIZE])\n```\n\n\n\n\n    0.78\n\n\n\n\n```python\ntransformer.classifier.score(X[TRAIN_DATA_SIZE:2*TRAIN_DATA_SIZE], Y[TRAIN_DATA_SIZE:2*TRAIN_DATA_SIZE])\n```\n\n\n\n\n    0.52\n\n\n\n## w/ Attention w/o Residual\n\n\n```python\ntransformer = QuantumTransformer(sequence_length=SEQUENCE_LENGTH, embedding_dimension=EMBEDDING_DIMS, embedding_dict=embeddings_dict, reps=1, include_attention=1, include_residual=0)\ntransformer.circuit.draw(\"mpl\") \n```\n\n\n```python\nX, Y = transformer.preprocess_data(corpus)\n```\n\n\n```python\nobjective_func_vals = []\nplt.rcParams[\"figure.figsize\"] = (12, 6)\ntransformer.classifier.fit(X[:TRAIN_DATA_SIZE], Y[:TRAIN_DATA_SIZE])\nplt.rcParams[\"figure.figsize\"] = (6, 4)\n```\n\n\n```python\ntransformer.classifier.score(X[:TRAIN_DATA_SIZE], Y[:TRAIN_DATA_SIZE])\n```\n\n\n\n\n    0.8\n\n\n\n\n```python\ntransformer.classifier.score(X[TRAIN_DATA_SIZE:2*TRAIN_DATA_SIZE], Y[TRAIN_DATA_SIZE:2*TRAIN_DATA_SIZE])\n```\n\n\n\n\n    0.46\n\n\n\n## w/Attention w/Residual\n\n\n```python\ntransformer = QuantumTransformer(sequence_length=SEQUENCE_LENGTH, embedding_dimension=EMBEDDING_DIMS, embedding_dict=embeddings_dict, reps=1, include_attention=1, include_residual=1)\ntransformer.circuit.draw(\"mpl\") \n```\n\n\n```python\nX, Y = transformer.preprocess_data(corpus)\n```\n\n\n```python\nobjective_func_vals = []\nplt.rcParams[\"figure.figsize\"] = (12, 6)\ntransformer.classifier.fit(X[:TRAIN_DATA_SIZE], Y[:TRAIN_DATA_SIZE])\nplt.rcParams[\"figure.figsize\"] = (6, 4)\n```\n\n\n```python\ntransformer.classifier.score(X[:TRAIN_DATA_SIZE], Y[:TRAIN_DATA_SIZE])\n```\n\n\n```python\ntransformer.classifier.score(X[TRAIN_DATA_SIZE:2*TRAIN_DATA_SIZE], Y[TRAIN_DATA_SIZE:2*TRAIN_DATA_SIZE])\n```\n\n# 2x qTransformer Blocks w/ Attention \n\n\n```python\ntransformer = QuantumTransformer(sequence_length=SEQUENCE_LENGTH, embedding_dimension=EMBEDDING_DIMS, embedding_dict=embeddings_dict, reps=2, include_attention=1, include_residual=1)\ntransformer.circuit.draw(\"mpl\") \n```\n\n\n```python\nX, Y = transformer.preprocess_data(corpus)\n```\n\n\n```python\nobjective_func_vals = []\nplt.rcParams[\"figure.figsize\"] = (12, 6)\ntransformer.classifier.fit(X[:TRAIN_DATA_SIZE], Y[:TRAIN_DATA_SIZE])\nplt.rcParams[\"figure.figsize\"] = (6, 4)\n```\n\n\n```python\ntransformer.classifier.score(X[:TRAIN_DATA_SIZE], Y[:TRAIN_DATA_SIZE])\n```\n\n\n```python\ntransformer.classifier.score(X[TRAIN_DATA_SIZE:2*TRAIN_DATA_SIZE], Y[TRAIN_DATA_SIZE:2*TRAIN_DATA_SIZE])\n```\n", "meta": {"hexsha": "4ee74a0f9de2da0e59992a58ab04ed93d2a65c98", "size": 703151, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "qTransformer.ipynb", "max_stars_repo_name": "areeq-hasan/qtransformer", "max_stars_repo_head_hexsha": "fc934879f1733737750731d3d134ea2a2d5736a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-12-25T15:48:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T16:09:22.000Z", "max_issues_repo_path": "qTransformer.ipynb", "max_issues_repo_name": "areeq-hasan/qtransformer", "max_issues_repo_head_hexsha": "fc934879f1733737750731d3d134ea2a2d5736a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qTransformer.ipynb", "max_forks_repo_name": "areeq-hasan/qtransformer", "max_forks_repo_head_hexsha": "fc934879f1733737750731d3d134ea2a2d5736a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-15T16:09:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T16:09:33.000Z", "avg_line_length": 68.3334305151, "max_line_length": 106166, "alphanum_fraction": 0.6009221348, "converted": true, "num_tokens": 58541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216805, "lm_q2_score": 0.092687780519085, "lm_q1q2_score": 0.038104954016401446}}
{"text": "# Practical 4: Reinforcement Learning\n\n## Introduction\nIn this practical we introduce the idea of reinforcement learning, discuss how it differs from supervised and unsupervised learning and then build an agent that learns to play a simple game called \"Catcher\".\n\n## Learning Objectives\n* Understand the relationship between the **environment** and the  **agent**  \n* Understand how a **policy** is used by an agent to select an action\n* Describe how to implement a **run-loop** that controls the interaction between environement and agent.\n* Understand how the **state**, **action** and **reward** are communicated between the agent and the environment.  \n* Be able to implement the a simple **policy-gradient** RL algorithm call **REINFORCE**\n* Discover at least one potential issue with the REINFORCE algorithm.\n\n\n```\n#@title [RUN ME!] Install pre-requisites. { display-mode: \"form\" }\nimport os\nimport sys\nimport math\t\n\n!git clone https://github.com/ntasfi/PyGame-Learning-Environment.git\nos.chdir('PyGame-Learning-Environment')\n!pip -q install -e .\n!pip -q install pygame\nos.chdir('/content')\n\nsys.path.append('/content/PyGame-Learning-Environment')\nos.environ[\"SDL_VIDEODRIVER\"] = \"dummy\"  # prevent trying to open a window\n\n!pip -q install moviepy\n\nprint('Installed pre-requisites...')\n```\n\n\n```\n#@title [RUN ME!] Imports { display-mode: \"form\" }\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport os\nimport moviepy.editor as mpy\nfrom ple import PLE\nfrom ple.games import pong\nfrom ple.games import pixelcopter\nfrom ple.games import flappybird\nfrom ple.games import catcher\nfrom IPython import display\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom collections import deque\nimport seaborn as sns\n\nimport tensorflow as tf\ntry:\n  tf.enable_eager_execution()\n  print('Running Eagerly')\nexcept ValueError:\n  print('Already running Eagerly')\n```\n\n\n```\n#@title [RUN ME!] Helper Functions { display-mode: \"form\" }\n\ndef make_animation(images, fps=60, true_image=False):\n  duration = len(images) / fps\n\n  def make_frame(t):\n    try:\n      x = images[int(len(images) / duration * t)]\n    except:\n      x = images[-1]\n\n    if true_image:\n      return x.astype(np.uint8)\n    else:\n      return ((x + 1) / 2 * 255).astype(np.uint8)\n\n  clip = mpy.VideoClip(make_frame, duration=duration)\n  clip.fps = fps\n  return clip\n\ndef progress(value, max=100, message=''):\n  return display.HTML(\"\"\"\n      <progress\n          value='{value}'\n          max='{max}',\n          style='width: 100%'\n      >\n          {value}\n      </progress>\n      <p>{message}</p>\n  \"\"\".format(value=value, max=max, message=message))\n\ndef plot_rolling_returns(rolling_returns):  \n  sns.tsplot(rolling_returns)\n  plt.title('Rolling Returns')\n  plt.xlabel('# Epsiodes')\n  plt.ylabel('Rolling Return')\n  \ndef state_to_buckets(state, bucket_width=0.25):\n  return tuple(math.ceil(s / bucket_width)-1 for s in state)\n```\n\n## Reinforcement Learning\nSo far we have encountered **supervised learning**, where we have an input and a target value or class that we want to predict. We have also encountered **unsupervised learning** where we are only given an input and look for patterns in that input. In this practical, we look into **reinforcement learning** which can loosely be defined as training an **agent** to maximise a numerical **reward** it obtains through interaction with an **environment**. \n\nThe environment defines a set of **actions** that an agent can take. The agent observes the current **state** of the environment, tries actions and *learns* a **policy** which is a distribution over the possible actions given a state of the environment. \n\nThe following diagram illustrates the interaction between the agent and environment. We will explore each of the terms in more detail throughout this practical. \n\n\n\n\n\n## Outline\nWe will train an agent to play a very simple game called \"Catcher\" which is often used as a test bed for RL algorithms. In the process we will set up all the necessary framework to explore variations of the algorithm or switch to more advanced games! In particular, the steps we will follow in this practical are as follows:\n\n1. Introduce the game environment, explore the states and actions available. \n2. Create a simple agent that takes random actions\n3. Write a run-loop which controls the interaction and manages the communication between the agent and environment\n4. Implement a policy as a feed-forward neural network\n5. Explain and implement the REINFORCE algorithm to learn how to play the game\n\n## The Environment\nThe environment we consider is the game Catcher from the PyGame Learning Environment (PLE) library. The player (agent) controls a paddle that it must use to catch a falling fruit. Each time the game runs, the fruit falls from from the top to the bottom of the screen, starting at a different X coordinate (which doesn't change during the episode) and the paddle starts in a random location along the bottom of the screen. The player wins if they manage to catch the fruit and loses if it falls to the ground. \n\n\n\n### Create the environment using PLE\nFor this game, we'll set things up so that the reward will be non-zero only at the end of each episode, and will be +1 for catching the fruit and -1 for missing it. For all other frames the reward will be zero.\n\n**Note**: PLE has a number of games, which it wraps in a generic \"environment\". \nSo, in this case, both ```evironment``` and ```game``` constitute our environment. ```environment``` allows us to perform actions \nand returns states and rewards, while ```game``` handles the specifics of Catcher (or whichever other game we decide to use)\n\n\n```\n# Create an instance of the catcher game\ngame = catcher.Catcher(init_lives=1)\ngame_height = game.height\ngame_width = game.width\n\nframe_skip = 3  # Skip 3 frames at each step to speed up the game\n\n# Wrap the game in a PLE environment and configure the rewards\nenvironment = PLE(game, display_screen=False, force_fps=True, \n                  reward_values={'win': 1.0, 'loss': -1.0, 'negative': 0.0}, \n                  frame_skip=frame_skip)  \n\n# The reward_values dictionary above allows us to override the default reward structure provided by PLE. \n# win and loss specify the rewards for winning or losing an episode, while positive and negative \n# specify the rewards received for positive or negative events that can occur during the game.\n# If you change the game, start by *removing* the overrides and see what the default is before deciding if\n# you want to modify it. \n\n# Initialise the environment\nenvironment.init()\n```\n\n### What does the state look like?\nThe environment provides a rendering of the virtual 'screen' of the game to an RGB image, by using the method ```getScreenRGB```. For this practical, in the interests of simplicity and quick trianing time, we use the *game state* directly, which provides a summary (in a dictionary) of important peices of information making up the current state of the game. \n\n\n```\nprint('Current game state:', game.getGameState())\n```\n\n    Current game state: {'fruit_x': 8, 'player_vel': 0.0, 'player_x': 26, 'fruit_y': -8}\n\n\n### What actions are available?\nThe following cell prints the actions that are available in the current game, which are represented with numerical codes. The PLE environment wrapper also adds an additional ```None``` action which means \"do nothing\". \n\n\n```\nprint('Game actions:', game.actions)\nprint('Environment actions:', environment.getActionSet())\n```\n\n    Game actions: {'right': 100, 'left': 97}\n    Environment actions: [100, 97, None]\n\n\n\n```\n#@title [RUN ME!] Setup for the next section { display-mode: \"form\" }\n# Maintain some variables for the next task\nenvironment.reset_game()\nobserved_states = []\nobserved_actions = []\nobserved_rewards = []\nobserved_states.append(game.getGameState())\n```\n\n### Exploratory Task\nRun the cell below which defines a function that takes a given action in the environment, using the environment's ```act``` method and then renders both the previous and current game screen. Change the action in the drop-down to the right of the 2nd code cell, which calls this function with the chosen action. Observe what happens to the environment(game) state and reward. By running the cell multiple times (and changing the action) until the game comes to an end (when you either win or lose), you will manually create an **episode**, which is a sequence of states, actions and rewards until a termination condition is reached. If an episode $i$ consists of $T_i$ steps and we denote the state, action and reward at step $t$ in episode $i$ respectively as $s_{i, t}$, $a_{i,t}$ and $r_{i,t}$, then in this task, we create a *trajectory* $\\tau_i = (s_{i, 1}, a_{i, 1}, r_{i, 1}, ..., a_{i, T_i-1}, r_{i, T_i-1}, s_{i, T_i})$\n\n#### Question\nNotice how the paddle sometimes moves even if you take the \"None\" action? Can you think of why this happens? \n\n#### Notes\n* If you want to run another episode, re-run the code cell above titled \"Setup for the next section\" to reset the environment\n* This particular game returns a reward of $0$ at each step and a final reward of $-1$ or $1$ at the end of the episode depending on whether you lose or win. Other games may have different reward structures! \n\n\n```\nprevious_frame = environment.getScreenRGB().transpose([1, 0, 2])\n\ndef take_action(action):\n  global previous_frame\n  \n  # Look up the action code from the description\n  action_code = None if action == 'None' else game.actions[action]\n\n  # Take the selected action in the environment\n  print('Taking action: {} ({})'.format(action, action_code))\n  reward = environment.act(action_code)\n\n  observed_actions.append(action)\n  observed_rewards.append(reward)\n\n  # Print and display the current state and reward\n  state = game.getGameState()\n  print('Game state:', state)\n  print('Reward received: ', reward)\n\n  observed_states.append(state)\n\n  if reward > 0 or environment.game_over():\n    print('Game over, you', 'WON' if reward > 0 else 'LOST')\n    print('The episode trajectory was:')\n    for s, a, r in zip(observed_states, observed_actions, observed_rewards):\n      print('State:', s, 'Action:', a, 'Reward:', r)\n    print('Terminal state:', observed_states[-1])\n  \n  current_frame = environment.getScreenRGB().transpose([1, 0, 2])\n  \n  fig = plt.figure(figsize=(10, 20))\n    \n  ax = plt.subplot(1, 2, 1)\n  plt.imshow(previous_frame)\n  ax.grid(False)\n  ax.set_title('PREVIOUS FRAME')\n  \n  ax = plt.subplot(1, 2, 2)\n  plt.imshow(current_frame)\n  ax.grid(False)\n  ax.set_title('CURRENT FRAME')\n  \n  previous_frame = current_frame\n```\n\n\n```\naction = \"None\"  #@param ['right', 'left', 'None']\ntake_action(action)\n```\n\n## The Agent\nWe now turn to the agent. An agent receives the current state and (previous) reward from the environment, then uses an internal policy to determine an action to take. We implement an agent as a Python [**class**](https://en.wikibooks.org/wiki/A_Beginner%27s_Python_Tutorial/Classes), which is just a logical wrapper of variables and methods (functions) that operate on those variables. The methods our agent will have are the following:\n\n* **Initialisation** (```__init__```):  Initialises the agent the first time it's created. \n* **policy**: The policy is a function that returns a *distribution* over the possible actions, given the current state.\n* **step**: This takes as input, the current state and previous reward from the environment, then uses the internal policy to determine which action to take. Specifically, it does some pre-processing of the state, then samples a single action from the distribution over possible actions obtained from the policy. \n* **reset**: This is called to reset the agent's variables before running it on a new episode\n* **end_episode**: This method signals to the agent that the current episode has come to an end. The agent may do some learning, or clean-up at the end of an episode. \n\n### The Random Agent\n\nTo get a feel for an agent and the methods it has, we implement an agent that just takes a *random* action at every step. For demonstration purposes, we also calculate the **episode return** at the end of an episode. The episode return is the sum of the (discounted) rewards obtained during the episode. If the returns for episode $i$, with trajectory $\\tau_{i}$ are denoted $r_{i, t}$, and the **discount factor** is $\\gamma$, then the episode return is calcuated as: $r(\\tau_i) = \\sum_{t=1}^{T_i} \\gamma^t r_{i,t}$. The discount factor allows us to increase the importance of rewards received quickly and decrease the importance of rewards that take long to receive. It is especially important in environments that could have episodes that are infinitely long. In our particular environment where every episode is of the same length and the only non-zero reward is received at the end of the game, the discount factor doesn't make much difference and so we will ignore it (effectively set it to $1$) for the remainder of this practical. \n\n\n```\nclass RandomAgent(object):\n  \n  def __init__(self, actions, state_size, seed):\n    # When initializing, we let the agent know what actions are available in the \n    # environment, how large the state is (not used in the RandomAgent) and the \n    # current seed to use (also not used in the RandomAgent)\n    self._actions = actions\n    self._rewards = []\n    self._taken_actions = []\n    self._observed_states = []\n \n  def policy(self, state):  \n    # The policy is an internal function that takes a state and returns a distribution over the possible actions. \n    # The random agent just returns a uniform distribution over the actions. \n    n = len(self._actions)  # The number of actions\n    return tf.fill([n], 1./n)  # This returns a vector of length n, with each entry being 1/n\n    \n  def step(self, state_dict, reward):\n    \n    # Pre-process the state to extract the numerical values we're interested in from the state dictionary\n    state = np.array([\n        state_dict['fruit_x'] / game_width,  # Divide by width(or height) to normalise the value to lie between 0 and 1.\n        state_dict['player_x'] / game_width,\n        state_dict['fruit_y'] / (game_height+1),\n        state_dict['player_vel'] / game_width\n    ], dtype=np.float32)\n    \n    self._observed_states.append(state)  # Record that the state was observed during the episode\n    self._rewards.append(reward)  # Keep track of the rewards we've received along the way\n    action_distribution = self.policy(state)  # Use the policy to get the distribution over actions\n    \n    # Sample a single action according to the distribution over actions\n    action = np.random.choice(self._actions, p=action_distribution.numpy())  \n    \n    self._taken_actions.append(action)  # Record that the action was taken during the episode\n    \n    return action\n  \n  def reset(self):\n    # This method is called when a new episode starts, we need to clear the \n    # states, actions and rewards that we tracked during the last episode.\n    self._rewards = [] \n    self._taken_actions = []  \n    self._observed_states = []  \n    \n  def end_episode(self, final_reward):\n    # We just calculate the episode return\n    episode_return = sum(self._rewards) + final_reward\n    return episode_return\n```\n\n## The Run-Loop\nNow that we have an environment and a simple agent, we need a way of controlling the interaction between the agent and environment over multiple episodes. We do so in a **run-loop**. In this simple run-loop, the agent and environment run in lock-step. For each game frame, we get the state from the environment and pass it, along with the previous reward, to the agent. The agent selects an action that it wants to take given the game state. The action is taken in the environment and any reward received is recorded. We run the loop for multiple episodes, each time being careful to reset the game and agent (because they're starting a new game from scratch).\n\n\n```\ndef run_loop(agent_class,                    # Which agent to use\n             num_episodes=1,                 # How many episodes to run for\n             record_every=1,                 # How many episodes to record\n             seed=1234,                      # The random seed used\n             rolling_return_frequency=100,   # The window size used to track the rolling episode return\n             state_size=4):                  # The size of the state\n  \n  # Set the random seeds\n  tf.set_random_seed(seed)\n  np.random.seed(seed)\n  \n  # Initialise the environment\n  environment.init()\n  \n  # Create an agent (this runs the agent's __init__ method)\n  agent = agent_class(environment.getActionSet(), state_size, seed)\n  \n  progress_out = display.display(progress(0, num_episodes), display_id=True)  # Create a progress-bar\n  \n  # Create data structures to store metrics\n  windowed_return = deque()\n  rolling_returns = []\n  frames = []\n  \n  for episode in range(num_episodes):\n    environment.reset_game() # reset the environment\n    agent.reset()  # reset the agent\n    reward = 0\n\n    while reward == 0 and not environment.game_over():   # Loop until the episode terminates      \n      state = game.getGameState()  # Get the current game state\n      action = agent.step(state, reward)  # Pass the current game state and previous reward to the agent, get the action it wants to take\n      reward = environment.act(action)  # Pass the action to the environment and get the reward.\n\n      if episode % record_every == 0:\n        # Store the frames for display later, every `record_every` episodes\n        frames.append(environment.getScreenRGB())\n    \n    info = agent.end_episode(reward)  # Signal to the agent that the episode has come to and end\n    \n    # Store the episode return in the window (in this case, with no discounting, the episode return is the same as the environment's score)\n    windowed_return.append(environment.score())\n    if len(windowed_return) > rolling_return_frequency:\n      windowed_return.popleft()\n    \n    rolling_return = sum(windowed_return) / len(windowed_return)\n    rolling_returns.append(rolling_return)\n    \n    # Update the progress-bar\n    message = 'Episode {}/{} ended with score {}, Rolling Return: {}, {}'.format(\n        episode+1, num_episodes, environment.score(), \n        rolling_return,\n        info if info is not None else '')\n    progress_out.update(progress(episode+1, num_episodes, message))\n  \n  message = 'Finished training, rendering video...'\n  progress_out.update(progress(episode+1, num_episodes, message))\n  \n  # Render a video\n  clip = make_animation(frames, fps=30, true_image=True).rotate(-90)\n  display.display(clip.ipython_display(fps=30, center=False, autoplay=False, loop=False, height=320, width=240, max_duration=1000))\n  \n  message = 'Done...'\n  progress_out.update(progress(episode+1, num_episodes, message))\n  \n  return rolling_returns\n```\n\nWe now run our RandomAgent with the run-loop for 100 episodes to check that everything is working so far. (Note: the blue progress bar shows how many of the ```num_episodes``` episodes we've completed. The small black progress bar is for the video rendering, ignore that one!)\n\n\n```\nrolling_returns = run_loop(RandomAgent, num_episodes=100, record_every=5, rolling_return_frequency=5)\nplot_rolling_returns(rolling_returns)\n```\n\n## A Policy Network\nRemember, the policy is a distribution over the possible actions the agent can take in the environment given the current state of the environment,  denoted $\\pi(a|s)$. In a Deep RL agent, the policy is represented by a neural network with parameters $\\theta$, so we have $\\pi_\\theta(a|s) = NN(s; \\theta)$, where $NN(s; \\theta)$ is some potentially complex function represented by a neural network with parameters $\\theta$. In other words, our neural network takes in the state as input and outputs the appropriate distribution over actions. Let us implement an agent who's policy is defined by a simple feed-forward neural network. We will name the class 'FixedAgent' because this agent will do no learning. As a result the policy network's weights will be fixed and the agent will take random actions as before.\n\nThe ```reset```, ```step``` and ```end_episode``` methods of our fixed agent will be identical to the RandomAgent we built earlier. We'll only change the ```__init__``` and ```policy``` methods. To avoid having to rewrite all that code, we will use Python's **inheritance** to reuse all the methods in RandomAgent except for policy which we *override* here.\n\n\n```\n# Lets build a fixed agent\nclass FixedAgent(RandomAgent):  # Inherit all the methods of RandomAgent\n  \n  def __init__(self, actions, state_size, seed):\n    super(FixedAgent, self).__init__(actions, state_size, seed)\n    \n    # Define the policy network in the initialize method (constructor) because it should persist\n    # through multiple usages over multiple episodes of the agent.\n    # (We change the default weight initialiser to truncated random normal which \n    # works better for the RL algorithm we'll use in this practical.)\n    self._policy_network = tf.keras.Sequential([\n        # Add a hidden layer with 64 neurons\n        tf.keras.layers.Dense(64, input_shape=[state_size], activation=tf.nn.relu, \n                              kernel_initializer=tf.truncated_normal_initializer(seed=seed)),\n        # Add a hidden layer with 32 neurons\n        tf.keras.layers.Dense(32, activation=tf.nn.relu, \n                              kernel_initializer=tf.truncated_normal_initializer(seed=seed)),\n        # Add an output layer with action-many neurons and a softmax activation function\n        tf.keras.layers.Dense(len(actions), activation='softmax'),\n    ])\n  \n  # Override the policy\n  def policy(self, state):\n    layer_input = tf.expand_dims(state, axis=0)  # Add a dummy batch dimension\n    action_distribution = self._policy_network(layer_input)   # Get the distribution over actions from the policy network\n    action_distribution = tf.squeeze(action_distribution, axis=0)  # Remove the dummy batch dimension\n    \n    return action_distribution\n```\n\nLet's test our FixedAgent, this is just to see that it runs, as we don't expect it to perform any better than the RandomAgent because it isn't learning anything yet! \n\n\n```\n# Our fixed-weight agent\nrolling_returns = run_loop(FixedAgent, num_episodes=100, record_every=5, rolling_return_frequency=5)\nplot_rolling_returns(rolling_returns)\n```\n\n## Learning with Policy Gradients\nFinally, let's give our agent some intelligence by making it learn from its experience in interacting with the environment. In order to learn, we need a loss function or *objective*. In RL, the objective is to maximise the expected episode return (rewards) by taking actions in the environment. The actions our agent takes are determined by the policy $\\pi_\\theta(a|s)$, which are in turn determined by the neural network parameters $\\theta$. So, we want to find the neural network parameters $\\theta$ that maximise \n\n$J(\\theta) = \\mathbb{E}_{\\tau}[r(\\tau)]$\n\n**Note:** If the maths in the next section looks intimidating, feel free to skip over it, read the intuition and code and come back to it later! \n\n\n### The derivative of the objective\nWe now turn to our usual tool of stochastic gradient descent to optimise the objective, but there are two complications. Firstly, the term $\\pi_\\theta(a|s)$ represented by our neural network doesn't appear in the equation (or does it?). Secondly, how do we deal with the expectation?\n\nThe first thing is to realise that our trajectories $\\tau$ depend on the policy $\\pi_\\theta(a|s)$ (**Question:** Why?) So we can (informally) write:\n\n\\begin{align}\nJ(\\theta) &= \\mathbb{E}_{\\tau \\sim \\pi_\\theta(\\tau)}  [r(\\tau)] & \\\\\n&= \\int \\pi_\\theta (\\tau) r(\\tau)d\\tau  & (\\text{Definition of expectation}) \\\\\n\\end{align}\n\nThen the gradient is:\n\n\\begin{align}\n\\nabla_\\theta J(\\theta) &= \\nabla_\\theta \\int \\pi_\\theta (\\tau) r(\\tau)d\\tau & \\\\\n&= \\int \\pi_\\theta (\\tau) \\nabla_\\theta log \\pi_\\theta (\\tau) r(\\tau)d\\tau & (\\text{\"Log derivative trick\"}) \\\\\n&= \\mathbb{E}_{\\tau \\sim \\pi_\\theta(\\tau)}[\\nabla_\\theta log \\pi_\\theta (\\tau) r(\\tau)]\n\\end{align}\n\nFinally, since we don't know the true distribution of $\\tau$, we can approximate the expectation using a *monte-carlo* approximation, where the sample trajectories come from $N$ episodes of interaction with the environment. \n\n\\begin{align}\n\\nabla_\\theta J(\\theta) &= \\frac{1}{N} \\sum_{i=1}^N \\nabla_\\theta log \\pi_\\theta (\\tau_i) r(\\tau_i)\n\\end{align}\n\nExpanding this out (and considering that episode $i$ has $T_i$ steps) gives:\n\n\\begin{align}\n\\nabla_\\theta J(\\theta) &= \\frac{1}{N} \\sum_{i=1}^N (\\sum_{t=1}^{T_i} \\nabla_\\theta log(\\pi_\\theta(a_{i,t} | s_{i, t})) \\sum_{t=1}^{T_i} \\gamma^t r_{i,t} )\n\\end{align}\n\nWe skipped a few steps in the maths here for brevity (see chapter 13 of [Sutton and Barto](https://drive.google.com/file/d/1xeUDVGWGUUv1-ccUMAZHJLej2C7aAFWY/view) for all the details if you're interested!). If the maths looks intimidating, don't worry! The important things to realise are the following:\n* We define an objective $J(\\theta)$ that is exactly what we want to do with RL, maximise the expected return.\n* We can run our agent in the environment to generate *trajectories* for multiple episodes\n* When an episode comes to an end and we know the return and trajectory, we can compute a term in (the Monte-carlo approximation to) the objective function. \n* We can use Tensorflow to compute the gradient of an individual term in the monte-carlo approximation and apply it to the parameters of our neural network. To do this, we define the *loss* to minimise as follows (where the sums can be represented by loops and we set $\\gamma = 1$ for simplicity):\n\n\\begin{align}\nL(\\theta) &= -\\sum_{t=1}^{T_i} log(\\pi_\\theta(a_{i,t} | s_{i, t})) \\sum_{t=1}^{T_i} r_{i,t} \n\\end{align}\n\nThe name \"policy gradient\" comes from the fact that we're directly taking the gradient of the policy, rather than the alternative, value-based RL, which uses iterative update rules to calculate the expected return assocated with a state. The particular flavour of policy gradient which uses the loss function above, along with the Monte-carlo approximation of the objective is known as the **REINFORCE** algorithm. \n\n\n\nFinally, we implement the REINFORCE algorithm to optimize the parameters of the neural network. The only things we're changing, compared to our FixedAgent are the ```__init__``` and ```end_episode``` methods, so we use *inheritance* again to automatically \"copy\" all the methods from ```FixedAgent``` and ```RandomAgent```. \n\n**Note:** ```ReinforceAgent``` indirectly inherits the methods from ```RandomAgent``` through ```FixedAgent``` (which directly inherits from ```RandomAgent```).  Both ```RandomAgent``` and ```FixedAgent``` have a ```policy``` method, but the one that gets \"copied\" to ```ReinforceAgent``` is the one from ```FixedAgent``` because it appeared later in the chain.\n\n\n```\nclass ReinforceAgent(FixedAgent):\n  \n  # Override the initialization method because this agent also needs an optimizer\n  # and a variable to track the step\n  def __init__(self, actions, state_size, seed):\n    super(ReinforceAgent, self).__init__(actions, state_size, seed)\n    self._optimizer = tf.train.RMSPropOptimizer(learning_rate=0.001)  \n    self._step_counter = tf.train.get_or_create_global_step()\n  \n  def end_episode(self, final_reward): \n    \"\"\"At the end of an episode, we compute the loss for the episode and take a \n    step in parameter speace in the direction of the gradients.\"\"\"\n    \n    # Compute the return (cumulative discounted reward) for the episode\n    episode_return = sum(self._rewards) + final_reward  # Assuming \\gamma = 1\n\n    with tf.GradientTape() as tape:\n      # Loop over the states and actions making up the episode trajectory\n      loss = 0\n      for state, action in zip(self._observed_states, self._taken_actions):  \n        # Get the probabilities assigned to the actions given the state by the policy\n        action_distribution = self.policy(state)  \n        action_index = self._actions.index(action)\n        # Get the log probability of the chosen action under the policy\n        log_action = tf.log(action_distribution[action_index])\n        # Add to the running total for the episode\n        loss -= log_action * episode_return          # Add your baseline value for TASK 4 here. \n\n    # Compute the gradient of the loss with respect to the variables in the model\n    grads = tape.gradient(loss, self._policy_network.variables) \n    \n    # Use the optimizer to apply the gradient\n    self._optimizer.apply_gradients(\n        zip(grads, self._policy_network.variables), global_step=self._step_counter)\n    \n    return 'Loss: {}'.format(loss)\n```\n\nNotice that during the episode we run only the forward-pass of the policy network (inference). At the end of the episode, we replay the states that occured during the episode and run both the forward and backward pass of the policy network (notice the gradient tape!) because we can only compute the loss once we have the episode return at the end of the episode. If the policy network is very complex, this could be inefficient. In that case you could run both the forward an backward pass during the episode and store intermediate gradients/partial derivatives to use in the update at the end of the episode.\n\nAnd finally we train our **REINFORCE** agent and plot the resulting rolling episode returns (over a window of 100 episodes).\n\n\n```\nrolling_returns = run_loop(ReinforceAgent, num_episodes=2400, record_every=30)\nplot_rolling_returns(rolling_returns)\n```\n\n## Your Tasks\n### Task 1: Learning Objectives [ALL]\nReview the learning objectives and ensure that you understand how the code in this practical relates to them. Ask your tutors if you don't understand anything!\n\n### Task 2: Network Architecture [ALL]\nExperiment with different network architectures and parameters and see how this affects the performance of the agent. What do you notice? Do you think the algorithm is sensitive to the network parameters?  \n\n**HINT**: Modify the code for the policy network in the ```__init__``` method of the ```FixedAgent``` class. \n\n### Task 3: Seed Variance **[ALL]** \nReveal and run the code in the cells below. This code will run the entire training procedure of the REINFORCE agent 10 times (using only 1000 episodes per run to save some time). It will then plot a chart that shows the mean of the rolling returns over the multiple runs along with an estimated *confidence interval* for the mean. You should notice that the confidence interval is fairly wide given that only the random seed is changing. This illustrates a problem with the REINFORCE algorithm: it has **high variance**. (It is however an **unbiased estimator** of the policy gradient!)\n\n### Task 4: Variance Reduction with a Basline **[INTERMEDIATE]** \nRead about value functions and how to approximate them using *Monte-Carlo* methods in [Slides 5 to 7 Here](http://www0.cs.ucl.ac.uk/staff/d.silver/web/Teaching_files/MC-TD.pdf). Then read slides [80, 84 and 85 here](http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture14.pdf). The goal of this task is to use a simple value function $V(s)$ to implement **REINFORCE with a Baseline**, where the loss function per episode changes to: \n\n\\begin{align}\nL(\\theta) &= -\\sum_{t=1}^{T_i} log(\\pi_\\theta(a_{i,t} | s_{i, t})) \\sum_{t=1}^{T_i} [r_{i,t} - V(s_{i, t})]\n\\end{align}\n\nTo do this, add code to the ```end_episode``` method of the ```ReinforceAgent``` class to estimate the value function. Subtract the value estimate for the state from the episode return at each step in the loop that computes the log_action_sum. \n\nRe-run Task 3's code to plot the confidence interval around the mean episode returns to check what effect it has on the variance. \n\n**HINT**: You will need to *discretise* the state-space. We've provided a very crude function called ```state_to_buckets``` that you can use to do this, or implement your own! \n\n**Further Reading (Optional)**: See the section on how to introduce a baseline [here](https://danieltakeshi.github.io/2017/03/28/going-deeper-into-reinforcement-learning-fundamentals-of-policy-gradients/) for more details about how and why this works!\n\n**Further Reading (Optional)**: This [blog post](https://flyyufelix.github.io/2017/10/12/dqn-vs-pg.html) contrasts policy gradient methods with an alternative value-based approach to RL called Deep Q-Networks. It also discusses some approaches to reducing the variance of the policy gradient estimator. \n\n### Task 5: Learning from pixels **[OPTIONAL]**\nThe agent we implemented in this practical uses a simple numerical representation of the state of the environment. In many cases such a representation would not be available. Change the run-loop to instead pass the array of pixel values to the agent. (which you can get by calling ```environment.getScreenRGB()```). Change the agent's policy network to cater for this image-representation of the state. \n\n\n\n### Task 6: Other games **[OPTIONAL]**\nThe PyGame Learning Environment (PLE) has [a number of games built-in](https://pygame-learning-environment.readthedocs.io/en/latest/user/games.html). Change the code in this practical to run on a different game and learn either from pixels or from the state representation provided by PLE. One interesting game you could try is FlappyBird! Remember to remove the reward overrides we set when trying a new game! \n\n## Additional Code for Task 3\nThis might take some time to run, continue reading for Task 4 and ask any questions you have while waiting!\n\n\n```\nall_rolling_returns = []\n\nfor i in range(10):\n  rolling_returns = run_loop(ReinforceAgent, num_episodes=1000, record_every=25, seed=np.random.randint(100000))\n  all_rolling_returns.append(rolling_returns)\n\nplot_rolling_returns(np.array(all_rolling_returns))\n```\n", "meta": {"hexsha": "8e764933f8120d3aad141c7a5f5bd0238b6a0fee", "size": 48488, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "RL.ipynb", "max_stars_repo_name": "Sasha115/indaba-pracs-2019", "max_stars_repo_head_hexsha": "4dc995acabf58dc4399bceee490e0fef83b8d2eb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RL.ipynb", "max_issues_repo_name": "Sasha115/indaba-pracs-2019", "max_issues_repo_head_hexsha": "4dc995acabf58dc4399bceee490e0fef83b8d2eb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RL.ipynb", "max_forks_repo_name": "Sasha115/indaba-pracs-2019", "max_forks_repo_head_hexsha": "4dc995acabf58dc4399bceee490e0fef83b8d2eb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.7481323372, "max_line_length": 1054, "alphanum_fraction": 0.5875061871, "converted": true, "num_tokens": 7961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3665897363221598, "lm_q2_score": 0.1037486240952153, "lm_q1q2_score": 0.03803318075085185}}
{"text": "```python\n# Importing standard Qiskit libraries\nfrom qiskit import QuantumCircuit, transpile, Aer, IBMQ\nfrom qiskit.tools.jupyter import *\nfrom qiskit.visualization import *\nfrom ibm_quantum_widgets import *\n\n# Loading your IBM Quantum account(s)\nprovider = IBMQ.load_account()\n```\n\n    ibmqfactory.load_account:WARNING:2021-07-23 22:20:04,310: Credentials are already in use. The existing account in the session will be replaced.\n\n\n\n```python\n!pip install pennylane\nimport pennylane as qml\n```\n\n    Collecting pennylane\n      Using cached PennyLane-0.16.0-py3-none-any.whl (514 kB)\n    Collecting autoray\n      Using cached autoray-0.2.5-py3-none-any.whl (16 kB)\n    Collecting autograd\n      Using cached autograd-1.3-py3-none-any.whl\n    Requirement already satisfied: toml in /opt/conda/lib/python3.8/site-packages (from pennylane) (0.10.2)\n    Requirement already satisfied: numpy in /opt/conda/lib/python3.8/site-packages (from pennylane) (1.21.0)\n    Requirement already satisfied: scipy in /opt/conda/lib/python3.8/site-packages (from pennylane) (1.7.0)\n    Requirement already satisfied: appdirs in /opt/conda/lib/python3.8/site-packages (from pennylane) (1.4.4)\n    Collecting semantic-version==2.6\n      Using cached semantic_version-2.6.0-py3-none-any.whl (14 kB)\n    Requirement already satisfied: networkx in /opt/conda/lib/python3.8/site-packages (from pennylane) (2.6.1)\n    Collecting future>=0.15.2\n      Using cached future-0.18.2-py3-none-any.whl\n    Requirement already satisfied: matplotlib>=3.3 in /opt/conda/lib/python3.8/site-packages (from networkx->pennylane) (3.4.2)\n    Requirement already satisfied: pandas>=1.1 in /opt/conda/lib/python3.8/site-packages (from networkx->pennylane) (1.3.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /opt/conda/lib/python3.8/site-packages (from matplotlib>=3.3->networkx->pennylane) (1.3.1)\n    Requirement already satisfied: pyparsing>=2.2.1 in /opt/conda/lib/python3.8/site-packages (from matplotlib>=3.3->networkx->pennylane) (2.4.7)\n    Requirement already satisfied: python-dateutil>=2.7 in /opt/conda/lib/python3.8/site-packages (from matplotlib>=3.3->networkx->pennylane) (2.8.1)\n    Requirement already satisfied: pillow>=6.2.0 in /opt/conda/lib/python3.8/site-packages (from matplotlib>=3.3->networkx->pennylane) (8.3.1)\n    Requirement already satisfied: cycler>=0.10 in /opt/conda/lib/python3.8/site-packages (from matplotlib>=3.3->networkx->pennylane) (0.10.0)\n    Requirement already satisfied: six in /opt/conda/lib/python3.8/site-packages (from cycler>=0.10->matplotlib>=3.3->networkx->pennylane) (1.16.0)\n    Requirement already satisfied: pytz>=2017.3 in /opt/conda/lib/python3.8/site-packages (from pandas>=1.1->networkx->pennylane) (2021.1)\n    Installing collected packages: future, semantic-version, autoray, autograd, pennylane\n    Successfully installed autograd-1.3 autoray-0.2.5 future-0.18.2 pennylane-0.16.0 semantic-version-2.6.0\n\n\n\n```python\n!pip install pennylane-qiskit\n```\n\n    Collecting pennylane-qiskit\n      Using cached PennyLane_qiskit-0.16.0-py3-none-any.whl (21 kB)\n    Requirement already satisfied: numpy in /opt/conda/lib/python3.8/site-packages (from pennylane-qiskit) (1.21.0)\n    Requirement already satisfied: pennylane>=0.16 in /opt/conda/lib/python3.8/site-packages (from pennylane-qiskit) (0.16.0)\n    Requirement already satisfied: qiskit>=0.25 in /opt/conda/lib/python3.8/site-packages (from pennylane-qiskit) (0.27.0)\n    Requirement already satisfied: networkx>=2.2 in /opt/conda/lib/python3.8/site-packages (from pennylane-qiskit) (2.6.1)\n    Requirement already satisfied: scipy!=1.6.1,>=1.5 in /opt/conda/lib/python3.8/site-packages (from networkx>=2.2->pennylane-qiskit) (1.7.0)\n    Requirement already satisfied: pandas>=1.1 in /opt/conda/lib/python3.8/site-packages (from networkx>=2.2->pennylane-qiskit) (1.3.0)\n    Requirement already satisfied: matplotlib>=3.3 in /opt/conda/lib/python3.8/site-packages (from networkx>=2.2->pennylane-qiskit) (3.4.2)\n    Requirement already satisfied: cycler>=0.10 in /opt/conda/lib/python3.8/site-packages (from matplotlib>=3.3->networkx>=2.2->pennylane-qiskit) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /opt/conda/lib/python3.8/site-packages (from matplotlib>=3.3->networkx>=2.2->pennylane-qiskit) (1.3.1)\n    Requirement already satisfied: pillow>=6.2.0 in /opt/conda/lib/python3.8/site-packages (from matplotlib>=3.3->networkx>=2.2->pennylane-qiskit) (8.3.1)\n    Requirement already satisfied: pyparsing>=2.2.1 in /opt/conda/lib/python3.8/site-packages (from matplotlib>=3.3->networkx>=2.2->pennylane-qiskit) (2.4.7)\n    Requirement already satisfied: python-dateutil>=2.7 in /opt/conda/lib/python3.8/site-packages (from matplotlib>=3.3->networkx>=2.2->pennylane-qiskit) (2.8.1)\n    Requirement already satisfied: six in /opt/conda/lib/python3.8/site-packages (from cycler>=0.10->matplotlib>=3.3->networkx>=2.2->pennylane-qiskit) (1.16.0)\n    Requirement already satisfied: pytz>=2017.3 in /opt/conda/lib/python3.8/site-packages (from pandas>=1.1->networkx>=2.2->pennylane-qiskit) (2021.1)\n    Requirement already satisfied: autoray in /opt/conda/lib/python3.8/site-packages (from pennylane>=0.16->pennylane-qiskit) (0.2.5)\n    Requirement already satisfied: autograd in /opt/conda/lib/python3.8/site-packages (from pennylane>=0.16->pennylane-qiskit) (1.3)\n    Requirement already satisfied: appdirs in /opt/conda/lib/python3.8/site-packages (from pennylane>=0.16->pennylane-qiskit) (1.4.4)\n    Requirement already satisfied: semantic-version==2.6 in /opt/conda/lib/python3.8/site-packages (from pennylane>=0.16->pennylane-qiskit) (2.6.0)\n    Requirement already satisfied: toml in /opt/conda/lib/python3.8/site-packages (from pennylane>=0.16->pennylane-qiskit) (0.10.2)\n    Requirement already satisfied: qiskit-ibmq-provider==0.14.0 in /opt/conda/lib/python3.8/site-packages (from qiskit>=0.25->pennylane-qiskit) (0.14.0)\n    Requirement already satisfied: qiskit-terra==0.17.4 in /opt/conda/lib/python3.8/site-packages (from qiskit>=0.25->pennylane-qiskit) (0.17.4)\n    Requirement already satisfied: qiskit-aqua==0.9.2 in /opt/conda/lib/python3.8/site-packages (from qiskit>=0.25->pennylane-qiskit) (0.9.2)\n    Requirement already satisfied: qiskit-ignis==0.6.0 in /opt/conda/lib/python3.8/site-packages (from qiskit>=0.25->pennylane-qiskit) (0.6.0)\n    Requirement already satisfied: qiskit-aer==0.8.2 in /opt/conda/lib/python3.8/site-packages (from qiskit>=0.25->pennylane-qiskit) (0.8.2)\n    Requirement already satisfied: pybind11>=2.6 in /opt/conda/lib/python3.8/site-packages (from qiskit-aer==0.8.2->qiskit>=0.25->pennylane-qiskit) (2.6.2)\n    Requirement already satisfied: sympy>=1.3 in /opt/conda/lib/python3.8/site-packages (from qiskit-aqua==0.9.2->qiskit>=0.25->pennylane-qiskit) (1.8)\n    Requirement already satisfied: setuptools>=40.1.0 in /opt/conda/lib/python3.8/site-packages (from qiskit-aqua==0.9.2->qiskit>=0.25->pennylane-qiskit) (57.1.0)\n    Requirement already satisfied: yfinance in /opt/conda/lib/python3.8/site-packages (from qiskit-aqua==0.9.2->qiskit>=0.25->pennylane-qiskit) (0.1.61)\n    Requirement already satisfied: psutil>=5 in /opt/conda/lib/python3.8/site-packages (from qiskit-aqua==0.9.2->qiskit>=0.25->pennylane-qiskit) (5.8.0)\n    Requirement already satisfied: dlx<=1.0.4 in /opt/conda/lib/python3.8/site-packages (from qiskit-aqua==0.9.2->qiskit>=0.25->pennylane-qiskit) (1.0.4)\n    Requirement already satisfied: h5py in /opt/conda/lib/python3.8/site-packages (from qiskit-aqua==0.9.2->qiskit>=0.25->pennylane-qiskit) (3.3.0)\n    Requirement already satisfied: retworkx>=0.8.0 in /opt/conda/lib/python3.8/site-packages (from qiskit-aqua==0.9.2->qiskit>=0.25->pennylane-qiskit) (0.9.0)\n    Requirement already satisfied: scikit-learn>=0.20.0 in /opt/conda/lib/python3.8/site-packages (from qiskit-aqua==0.9.2->qiskit>=0.25->pennylane-qiskit) (0.24.2)\n    Requirement already satisfied: docplex<=2.20.204 in /opt/conda/lib/python3.8/site-packages (from qiskit-aqua==0.9.2->qiskit>=0.25->pennylane-qiskit) (2.20.204)\n    Requirement already satisfied: quandl in /opt/conda/lib/python3.8/site-packages (from qiskit-aqua==0.9.2->qiskit>=0.25->pennylane-qiskit) (3.6.1)\n    Requirement already satisfied: fastdtw<=0.3.4 in /opt/conda/lib/python3.8/site-packages (from qiskit-aqua==0.9.2->qiskit>=0.25->pennylane-qiskit) (0.3.4)\n    Requirement already satisfied: urllib3>=1.21.1 in /opt/conda/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.14.0->qiskit>=0.25->pennylane-qiskit) (1.26.6)\n    Requirement already satisfied: requests-ntlm>=1.1.0 in /opt/conda/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.14.0->qiskit>=0.25->pennylane-qiskit) (1.1.0)\n    Requirement already satisfied: dill>=0.3 in /opt/conda/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.14.0->qiskit>=0.25->pennylane-qiskit) (0.3.4)\n    Requirement already satisfied: websocket-client>=1.0.1 in /opt/conda/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.14.0->qiskit>=0.25->pennylane-qiskit) (1.1.0)\n    Requirement already satisfied: requests>=2.19 in /opt/conda/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.14.0->qiskit>=0.25->pennylane-qiskit) (2.25.1)\n    Requirement already satisfied: python-constraint>=1.4 in /opt/conda/lib/python3.8/site-packages (from qiskit-terra==0.17.4->qiskit>=0.25->pennylane-qiskit) (1.4.0)\n    Requirement already satisfied: ply>=3.10 in /opt/conda/lib/python3.8/site-packages (from qiskit-terra==0.17.4->qiskit>=0.25->pennylane-qiskit) (3.11)\n    Requirement already satisfied: jsonschema>=2.6 in /opt/conda/lib/python3.8/site-packages (from qiskit-terra==0.17.4->qiskit>=0.25->pennylane-qiskit) (3.2.0)\n    Requirement already satisfied: fastjsonschema>=2.10 in /opt/conda/lib/python3.8/site-packages (from qiskit-terra==0.17.4->qiskit>=0.25->pennylane-qiskit) (2.15.1)\n    Requirement already satisfied: pyrsistent>=0.14.0 in /opt/conda/lib/python3.8/site-packages (from jsonschema>=2.6->qiskit-terra==0.17.4->qiskit>=0.25->pennylane-qiskit) (0.18.0)\n    Requirement already satisfied: attrs>=17.4.0 in /opt/conda/lib/python3.8/site-packages (from jsonschema>=2.6->qiskit-terra==0.17.4->qiskit>=0.25->pennylane-qiskit) (21.2.0)\n    Requirement already satisfied: idna<3,>=2.5 in /opt/conda/lib/python3.8/site-packages (from requests>=2.19->qiskit-ibmq-provider==0.14.0->qiskit>=0.25->pennylane-qiskit) (2.10)\n    Requirement already satisfied: chardet<5,>=3.0.2 in /opt/conda/lib/python3.8/site-packages (from requests>=2.19->qiskit-ibmq-provider==0.14.0->qiskit>=0.25->pennylane-qiskit) (4.0.0)\n    Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.8/site-packages (from requests>=2.19->qiskit-ibmq-provider==0.14.0->qiskit>=0.25->pennylane-qiskit) (2021.5.30)\n    Requirement already satisfied: ntlm-auth>=1.0.2 in /opt/conda/lib/python3.8/site-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.14.0->qiskit>=0.25->pennylane-qiskit) (1.5.0)\n    Requirement already satisfied: cryptography>=1.3 in /opt/conda/lib/python3.8/site-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.14.0->qiskit>=0.25->pennylane-qiskit) (3.4.7)\n    Requirement already satisfied: cffi>=1.12 in /opt/conda/lib/python3.8/site-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.14.0->qiskit>=0.25->pennylane-qiskit) (1.14.5)\n    Requirement already satisfied: pycparser in /opt/conda/lib/python3.8/site-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.14.0->qiskit>=0.25->pennylane-qiskit) (2.20)\n    Requirement already satisfied: joblib>=0.11 in /opt/conda/lib/python3.8/site-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.9.2->qiskit>=0.25->pennylane-qiskit) (1.0.1)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /opt/conda/lib/python3.8/site-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.9.2->qiskit>=0.25->pennylane-qiskit) (2.1.0)\n    Requirement already satisfied: mpmath>=0.19 in /opt/conda/lib/python3.8/site-packages (from sympy>=1.3->qiskit-aqua==0.9.2->qiskit>=0.25->pennylane-qiskit) (1.2.1)\n    Requirement already satisfied: future>=0.15.2 in /opt/conda/lib/python3.8/site-packages (from autograd->pennylane>=0.16->pennylane-qiskit) (0.18.2)\n    Requirement already satisfied: inflection>=0.3.1 in /opt/conda/lib/python3.8/site-packages (from quandl->qiskit-aqua==0.9.2->qiskit>=0.25->pennylane-qiskit) (0.5.1)\n    Requirement already satisfied: more-itertools in /opt/conda/lib/python3.8/site-packages (from quandl->qiskit-aqua==0.9.2->qiskit>=0.25->pennylane-qiskit) (8.8.0)\n    Requirement already satisfied: lxml>=4.5.1 in /opt/conda/lib/python3.8/site-packages (from yfinance->qiskit-aqua==0.9.2->qiskit>=0.25->pennylane-qiskit) (4.6.3)\n    Requirement already satisfied: multitasking>=0.0.7 in /opt/conda/lib/python3.8/site-packages (from yfinance->qiskit-aqua==0.9.2->qiskit>=0.25->pennylane-qiskit) (0.0.9)\n    Installing collected packages: pennylane-qiskit\n    Successfully installed pennylane-qiskit-0.16.0\n\n\n\n```python\nfrom pennylane.optimize.gradient_descent import *\nfrom pennylane import numpy as np\n```\n\n\n```python\nOptimizer = qml.QNGOptimizer(0.01, False, 0)\n```\n\n\n```python\nnum_qubits = 4 #4 qubits\n# device\n#dev = qml.device('qiskit.ibmq', wires=num_qubits, backend='ibmq_qasm_simulator', provider=provider)\ndev = qml.device(\"default.qubit\", wires=4, shots=1024)\nparams = np.array([np.pi/2, np.pi/2, np.pi/2])\n\n#user input for rotation gate angles\n\"\"\"\nparams_1 = list(map(float, input().strip().split(' ')))\nparams_2 = list(map(float, input().strip().split(' ')))\nparams_3 = list(map(float, input().strip().split(' ')))\nparams_4 = list(map(float, input().strip().split(' ')))\nparams_5 = list(map(float, input().strip().split(' ')))\nparams_6 = list(map(float, input().strip().split(' ')))\nparams_list = list(map(float, input().strip().split(' ')))\n\"\"\"\n\n\"\"\"params_1 = default_params #[phi, theta, omega]\nparams_2 = default_params #[phi, theta, omega]\nparams_3 = default_params #[phi, theta, omega]\nparams_4 = default_params #[phi, theta, omega]\nparams_5 = default_params #[phi, theta, omega]\nparams_6 = default_params #[phi, theta, omega]\nparams_list = default_params #[phi, theta, omega]\"\"\"\n\n@qml.qnode(dev)\ndef vqc(params, wires=4):\n    #Cluster State\n    qml.Hadamard(wires=0)\n    qml.Hadamard(wires=1)\n    qml.Hadamard(wires=2)\n    qml.Hadamard(wires=3)\n    qml.CNOT(wires=[0,1])\n    qml.CNOT(wires=[1,2])\n    qml.CNOT(wires=[2,3])\n    qml.RY(np.pi, wires=0)\n    qml.RY(np.pi, wires=1)\n    qml.RY(np.pi, wires=2)\n    qml.RY(np.pi, wires=3)\n    qml.CNOT(wires=[0,1])\n    qml.CNOT(wires=[1,2])\n    qml.CNOT(wires=[2,3])\n    #QConvLayer1\n    qml.U3(params[0], params[1], params[2], wires=0)\n    qml.U3(params[0], params[1], params[2], wires=1)\n    qml.U3(params[0], params[1], params[2], wires=2)\n    qml.U3(params[0], params[1], params[2], wires=3)\n    qml.CRot(params[0], params[1], params[2], wires=[0,1])\n    qml.CRot(params[0], params[1], params[2], wires=[2,3])\n    #QConvLayer2\n    qml.CRot(params_list[0], params_list[1], params_list[2], wires=[0,2])\n    return qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliZ(2)), qml.expval(qml.PauliZ(3))\n\n\n```\n\n\n```python\nhelp (qml.Hamiltonian)\n```\n\n    Help on class Hamiltonian in module pennylane.vqe.vqe:\n    \n    class Hamiltonian(builtins.object)\n     |  Hamiltonian(coeffs, observables, simplify=False)\n     |  \n     |  Lightweight class for representing Hamiltonians for Variational Quantum\n     |  Eigensolver problems.\n     |  \n     |  Hamiltonians can be expressed as linear combinations of observables, e.g.,\n     |  :math:`\\sum_{k=0}^{N-1} c_k O_k`.\n     |  \n     |  This class keeps track of the terms (coefficients and observables) separately.\n     |  \n     |  Args:\n     |      coeffs (Iterable[float]): coefficients of the Hamiltonian expression\n     |      observables (Iterable[Observable]): observables in the Hamiltonian expression\n     |      simplify (bool): Specifies whether the Hamiltonian is simplified upon initialization\n     |                       (like-terms are combined). The default value is `False`.\n     |  \n     |  .. seealso:: :class:`~.ExpvalCost`, :func:`~.molecular_hamiltonian`\n     |  \n     |  **Example:**\n     |  \n     |  A Hamiltonian can be created by simply passing the list of coefficients\n     |  as well as the list of observables:\n     |  \n     |  >>> coeffs = [0.2, -0.543]\n     |  >>> obs = [qml.PauliX(0) @ qml.PauliZ(1), qml.PauliZ(0) @ qml.Hadamard(2)]\n     |  >>> H = qml.Hamiltonian(coeffs, obs)\n     |  >>> print(H)\n     |    (-0.543) [Z0 H2]\n     |  + (0.2) [X0 Z1]\n     |  \n     |  The user can also provide custom observables:\n     |  \n     |  >>> obs_matrix = np.array([[0.5, 1.0j, 0.0, -3j],\n     |                             [-1.0j, -1.1, 0.0, -0.1],\n     |                             [0.0, 0.0, -0.9, 12.0],\n     |                             [3j, -0.1, 12.0, 0.0]])\n     |  >>> obs = qml.Hermitian(obs_matrix, wires=[0, 1])\n     |  >>> H = qml.Hamiltonian((0.8, ), (obs, ))\n     |  >>> print(H)\n     |  (0.8) [Hermitian0'1]\n     |  \n     |  Alternatively, the :func:`~.molecular_hamiltonian` function from the\n     |  :doc:`/introduction/chemistry` module can be used to generate a molecular\n     |  Hamiltonian.\n     |  \n     |  .. Warning::\n     |  \n     |      Hamiltonians can be constructed using Pythonic arithmetic operations. For example:\n     |  \n     |      >>> qml.PauliX(0) + 2 * qml.PauliZ(0) @ qml.PauliZ(1)\n     |  \n     |      is equivalent to the following Hamiltonian:\n     |  \n     |      >>> qml.Hamiltonian([1, 2], [qml.PauliX(0), qml.PauliZ(0) @ qml.PauliZ(1)])\n     |  \n     |      When Hamiltonians are defined using arithmetic operations **inside of QNodes**, constituent observables\n     |      may be queued as operations/an error may be thrown. Thus, Hamiltonians must be defined either outside of QNodes,\n     |      or inside of QNodes using the conventional method.\n     |  \n     |      Note that this issue also arises when calling the ``simplify()`` method.\n     |  \n     |  Methods defined here:\n     |  \n     |  __add__(self, H)\n     |      The addition operation between a Hamiltonian and a Hamiltonian/Tensor/Observable.\n     |  \n     |  __iadd__(self, H)\n     |      The inplace addition operation between a Hamiltonian and a Hamiltonian/Tensor/Observable.\n     |  \n     |  __imul__(self, a)\n     |      The inplace scalar multiplication operation between a scalar and a Hamiltonian.\n     |  \n     |  __init__(self, coeffs, observables, simplify=False)\n     |      Initialize self.  See help(type(self)) for accurate signature.\n     |  \n     |  __isub__(self, H)\n     |      The inplace subtraction operation between a Hamiltonian and a Hamiltonian/Tensor/Observable.\n     |  \n     |  __matmul__(self, H)\n     |      The tensor product operation between a Hamiltonian and a Hamiltonian/Tensor/Observable.\n     |  \n     |  __mul__(self, a)\n     |      The scalar multiplication operation between a scalar and a Hamiltonian.\n     |  \n     |  __repr__(self)\n     |      Return repr(self).\n     |  \n     |  __rmul__ = __mul__(self, a)\n     |  \n     |  __str__(self)\n     |      Return str(self).\n     |  \n     |  __sub__(self, H)\n     |      The subtraction operation between a Hamiltonian and a Hamiltonian/Tensor/Observable.\n     |  \n     |  compare(self, H)\n     |      Compares with another :class:`~Hamiltonian`, :class:`~.Observable`, or :class:`~.Tensor`,\n     |      to determine if they are equivalent.\n     |      \n     |      Hamiltonians/observables are equivalent if they represent the same operator\n     |      (their matrix representations are equal), and they are defined on the same wires.\n     |      \n     |      .. Warning::\n     |      \n     |          The compare method does **not** check if the matrix representation\n     |          of a :class:`~.Hermitian` observable is equal to an equivalent\n     |          observable expressed in terms of Pauli matrices, or as a\n     |          linear combination of Hermitians.\n     |          To do so would require the matrix form of Hamiltonians and Tensors\n     |          be calculated, which would drastically increase runtime.\n     |      \n     |      Returns:\n     |          (bool): True if equivalent.\n     |      \n     |      **Examples**\n     |      \n     |      >>> A = np.array([[1, 0], [0, -1]])\n     |      >>> H = qml.Hamiltonian(\n     |      ...     [0.5, 0.5],\n     |      ...     [qml.Hermitian(A, 0) @ qml.PauliY(1), qml.PauliY(1) @ qml.Hermitian(A, 0) @ qml.Identity(\"a\")]\n     |      ... )\n     |      >>> obs = qml.Hermitian(A, 0) @ qml.PauliY(1)\n     |      >>> print(H.compare(obs))\n     |      True\n     |      \n     |      >>> H1 = qml.Hamiltonian([1, 1], [qml.PauliX(0), qml.PauliZ(1)])\n     |      >>> H2 = qml.Hamiltonian([1, 1], [qml.PauliZ(0), qml.PauliX(1)])\n     |      >>> H1.compare(H2)\n     |      False\n     |      \n     |      >>> ob1 = qml.Hamiltonian([1], [qml.PauliX(0)])\n     |      >>> ob2 = qml.Hermitian(np.array([[0, 1], [1, 0]]), 0)\n     |      >>> ob1.compare(ob2)\n     |      False\n     |  \n     |  queue(self)\n     |      Queues a qml.Hamiltonian instance\n     |  \n     |  simplify(self)\n     |      Simplifies the Hamiltonian by combining like-terms.\n     |      \n     |      **Example**\n     |      \n     |      >>> ops = [qml.PauliY(2), qml.PauliX(0) @ qml.Identity(1), qml.PauliX(0)]\n     |      >>> H = qml.Hamiltonian([1, 1, -2], ops)\n     |      >>> H.simplify()\n     |      >>> print(H)\n     |        (-1) [X0]\n     |      + (1) [Y2]\n     |  \n     |  ----------------------------------------------------------------------\n     |  Readonly properties defined here:\n     |  \n     |  coeffs\n     |      Return the coefficients defining the Hamiltonian.\n     |      \n     |      Returns:\n     |          Iterable[float]): coefficients in the Hamiltonian expression\n     |  \n     |  name\n     |  \n     |  ops\n     |      Return the operators defining the Hamiltonian.\n     |      \n     |      Returns:\n     |          Iterable[Observable]): observables in the Hamiltonian expression\n     |  \n     |  terms\n     |      The terms of the Hamiltonian expression :math:`\\sum_{k=0}^{N-1} c_k O_k`\n     |      \n     |      Returns:\n     |          (tuple, tuple): tuples of coefficients and operations, each of length N\n     |  \n     |  wires\n     |      The sorted union of wires from all operators.\n     |      \n     |      Returns:\n     |          (Wires): Combined wires present in all terms, sorted.\n     |  \n     |  ----------------------------------------------------------------------\n     |  Data descriptors defined here:\n     |  \n     |  __dict__\n     |      dictionary for instance variables (if defined)\n     |  \n     |  __weakref__\n     |      list of weak references to the object (if defined)\n    \n\n\n\n```python\ncoeffs = [1,1,1]\nobs = [qml.PauliZ(0), qml.PauliZ(0), qml.PauliZ(0)]\nH = qml.Hamiltonian(coeffs, obs)\n```\n\n\n```python\ncost_fn = qml.ExpvalCost(vqc, H, dev)\n```\n\n\n```python\n%tb\ntheta_new = Optimizer.step(cost_fn, params)\n```\n", "meta": {"hexsha": "7437673243e3c8c5dfc7e91d7d3e74ae450d5d18", "size": 53124, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Testing QNGOptimizer.ipynb", "max_stars_repo_name": "WontonSoup914/TestingQCNN", "max_stars_repo_head_hexsha": "169c016932bb97104f3d7f6611ae2e99cae4b85f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Testing QNGOptimizer.ipynb", "max_issues_repo_name": "WontonSoup914/TestingQCNN", "max_issues_repo_head_hexsha": "169c016932bb97104f3d7f6611ae2e99cae4b85f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Testing QNGOptimizer.ipynb", "max_forks_repo_name": "WontonSoup914/TestingQCNN", "max_forks_repo_head_hexsha": "169c016932bb97104f3d7f6611ae2e99cae4b85f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 89.2840336134, "max_line_length": 1846, "alphanum_fraction": 0.6481251412, "converted": true, "num_tokens": 7582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398147944527615, "lm_q2_score": 0.08756383297503753, "lm_q1q2_score": 0.03800108178040584}}
{"text": "##### Copyright 2020 The OpenFermion Developers\n\n\n```python\n#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# Introduction to OpenFermion\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n  <td>\n    <a target=\"_blank\" href=\"https://www.example.org/openfermion/tutorials/intro_to_openfermion\">View on QuantumLib</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/OpenFermion/blob/master/docs/tutorials/intro_to_openfermion.ipynb\">Run in Google Colab</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://github.com/quantumlib/OpenFermion/blob/master/docs/tutorials/intro_to_openfermion.ipynb\">View source on GitHub</a>\n  </td>\n  <td>\n    <a href=\"https://storage.googleapis.com/tensorflow_docs/OpenFermion/docs/tutorials/intro_to_openfermion.ipynb\">Download notebook</a>\n  </td>\n</table>\n\nNote: The examples below must be run sequentially within a section.\n\n## Setup\n\nInstall the OpenFermion package:\n\n\n```python\ntry:\n    import openfermion\nexcept ImportError:\n    !pip install git+https://github.com/quantumlib/OpenFermion.git@master#egg=openfermion\n```\n\n## Initializing the FermionOperator data structure\n\nFermionic systems are often treated in second quantization where arbitrary operators can be expressed using the fermionic creation and annihilation operators, $a^\\dagger_k$ and $a_k$.  The fermionic ladder operators play a similar role to their qubit ladder operator counterparts, $\\sigma^+_k$ and $\\sigma^-_k$ but are distinguished by the canonical fermionic anticommutation relations, $\\{a^\\dagger_i, a^\\dagger_j\\} = \\{a_i, a_j\\} = 0$ and $\\{a_i, a_j^\\dagger\\} = \\delta_{ij}$. Any weighted sums of products of these operators are represented with the FermionOperator data structure in OpenFermion. The following are examples of valid FermionOperators:\n\n$$\n\\begin{align}\n& a_1 \\nonumber \\\\\n& 1.7 a^\\dagger_3 \\nonumber \\\\\n&-1.7 \\, a^\\dagger_3 a_1 \\nonumber \\\\\n&(1 + 2i) \\, a^\\dagger_4 a^\\dagger_3 a_9 a_1 \\nonumber \\\\\n&(1 + 2i) \\, a^\\dagger_4 a^\\dagger_3 a_9 a_1 - 1.7 \\, a^\\dagger_3 a_1 \\nonumber\n\\end{align}\n$$\n\nThe FermionOperator class is contained in $\\textrm{ops/_fermion_operator.py}$. In order to support fast addition of FermionOperator instances, the class is implemented as hash table (python dictionary). The keys of the dictionary encode the strings of ladder operators and values of the dictionary store the coefficients. The strings of ladder operators are encoded as a tuple of 2-tuples which we refer to as the \"terms tuple\". Each ladder operator is represented by a 2-tuple. The first element of the 2-tuple is an int indicating the tensor factor on which the ladder operator acts. The second element of the 2-tuple is Boole: 1 represents raising and 0 represents lowering. For instance, $a^\\dagger_8$ is represented in a 2-tuple as $(8, 1)$. Note that indices start at 0 and the identity operator is an empty list. Below we give some examples of operators and their terms tuple:\n\n$$\n\\begin{align}\nI & \\mapsto () \\nonumber \\\\\na_1 & \\mapsto ((1, 0),) \\nonumber \\\\\na^\\dagger_3 & \\mapsto ((3, 1),) \\nonumber \\\\\na^\\dagger_3 a_1 & \\mapsto ((3, 1), (1, 0)) \\nonumber \\\\\na^\\dagger_4 a^\\dagger_3 a_9 a_1 & \\mapsto ((4, 1), (3, 1), (9, 0), (1, 0)) \\nonumber\n\\end{align}\n$$\n\nNote that when initializing a single ladder operator one should be careful to add the comma after the inner pair. This is because in python ((1, 2)) = (1, 2) whereas ((1, 2),) = ((1, 2),). The \"terms tuple\" is usually convenient when one wishes to initialize a term as part of a coded routine. However, the terms tuple is not particularly intuitive. Accordingly, OpenFermion also supports another user-friendly, string notation below. This representation is rendered when calling \"print\" on a FermionOperator.\n\n$$\n\\begin{align}\nI & \\mapsto \\textrm{\"\"} \\nonumber \\\\\na_1 & \\mapsto \\textrm{\"1\"} \\nonumber \\\\\na^\\dagger_3 & \\mapsto \\textrm{\"3^\"} \\nonumber \\\\\na^\\dagger_3 a_1 & \\mapsto \\textrm{\"3^}\\;\\textrm{1\"} \\nonumber \\\\\na^\\dagger_4 a^\\dagger_3 a_9 a_1 & \\mapsto \\textrm{\"4^}\\;\\textrm{3^}\\;\\textrm{9}\\;\\textrm{1\"} \\nonumber\n\\end{align}\n$$\n\nLet's initialize our first term! We do it two different ways below.\n\n\n```python\nfrom openfermion.ops import FermionOperator\n\nmy_term = FermionOperator(((3, 1), (1, 0)))\nprint(my_term)\n\nmy_term = FermionOperator('3^ 1')\nprint(my_term)\n```\n\nThe preferred way to specify the coefficient in openfermion is to provide an optional coefficient argument. If not provided, the coefficient defaults to 1. In the code below, the first method is preferred. The multiplication in the second method actually creates a copy of the term, which introduces some additional cost. All inplace operands (such as +=) modify classes whereas binary operands such as + create copies. Important caveats are that the empty tuple FermionOperator(()) and the empty string FermionOperator('') initializes identity. The empty initializer FermionOperator() initializes the zero operator.\n\n\n```python\ngood_way_to_initialize = FermionOperator('3^ 1', -1.7)\nprint(good_way_to_initialize)\n\nbad_way_to_initialize = -1.7 * FermionOperator('3^ 1')\nprint(bad_way_to_initialize)\n\nidentity = FermionOperator('')\nprint(identity)\n\nzero_operator = FermionOperator()\nprint(zero_operator)\n```\n\nNote that FermionOperator has only one attribute: .terms. This attribute is the dictionary which stores the term tuples.\n\n\n```python\nmy_operator = FermionOperator('4^ 1^ 3 9', 1. + 2.j)\nprint(my_operator)\nprint(my_operator.terms)\n```\n\n## Manipulating the FermionOperator data structure\nSo far we have explained how to initialize a single FermionOperator such as $-1.7 \\, a^\\dagger_3 a_1$. However, in general we will want to represent sums of these operators such as $(1 + 2i) \\, a^\\dagger_4 a^\\dagger_3 a_9 a_1 - 1.7 \\, a^\\dagger_3 a_1$. To do this, just add together two FermionOperators! We demonstrate below.\n\n\n```python\nfrom openfermion.ops import FermionOperator\n\nterm_1 = FermionOperator('4^ 3^ 9 1', 1. + 2.j)\nterm_2 = FermionOperator('3^ 1', -1.7)\nmy_operator = term_1 + term_2\nprint(my_operator)\n\nmy_operator = FermionOperator('4^ 3^ 9 1', 1. + 2.j)\nterm_2 = FermionOperator('3^ 1', -1.7)\nmy_operator += term_2\nprint('')\nprint(my_operator)\n```\n\nThe print function prints each term in the operator on a different line. Note that the line my_operator = term_1 + term_2 creates a new object, which involves a copy of term_1 and term_2. The second block of code uses the inplace method +=, which is more efficient. This is especially important when trying to construct a very large FermionOperator. FermionOperators also support a wide range of builtins including, str(), repr(), ==, !=, *=, *, /, /=, +, +=, -, -=, - and **. Note that since FermionOperators involve floats, == and != check for (in)equality up to numerical precision. We demonstrate some of these methods below.\n\n\n```python\nterm_1 = FermionOperator('4^ 3^ 9 1', 1. + 2.j)\nterm_2 = FermionOperator('3^ 1', -1.7)\n\nmy_operator = term_1 - 33. * term_2\nprint(my_operator)\n\nmy_operator *= 3.17 * (term_2 + term_1) ** 2\nprint('')\nprint(my_operator)\n\nprint('')\nprint(term_2 ** 3)\n\nprint('')\nprint(term_1 == 2.*term_1 - term_1)\nprint(term_1 == my_operator)\n```\n\nAdditionally, there are a variety of methods that act on the FermionOperator data structure. We demonstrate a small subset of those methods here.\n\n\n```python\nfrom openfermion.utils import commutator, count_qubits, hermitian_conjugated\nfrom openfermion.transforms import normal_ordered\n\n# Get the Hermitian conjugate of a FermionOperator, count its qubit, check if it is normal-ordered.\nterm_1 = FermionOperator('4^ 3 3^', 1. + 2.j)\nprint(hermitian_conjugated(term_1))\nprint(term_1.is_normal_ordered())\nprint(count_qubits(term_1))\n\n# Normal order the term.\nterm_2 = normal_ordered(term_1)\nprint('')\nprint(term_2)\nprint(term_2.is_normal_ordered())\n\n# Compute a commutator of the terms.\nprint('')\nprint(commutator(term_1, term_2))\n```\n\n## The QubitOperator data structure\nThe QubitOperator data structure is another essential part of openfermion. As the name suggests, QubitOperator is used to store qubit operators in almost exactly the same way that FermionOperator is used to store fermion operators. For instance $X_0 Z_3 Y_4$ is a QubitOperator. The internal representation of this as a terms tuple would be $((0, \\textrm{\"X\"}), (3, \\textrm{\"Z\"}), (4, \\textrm{\"Y\"}))$. Note that one important difference between QubitOperator and FermionOperator is that the terms in QubitOperator are always sorted in order of tensor factor. In some cases, this enables faster manipulation. We initialize some QubitOperators below.\n\n\n```python\nfrom openfermion.ops import QubitOperator\n\nmy_first_qubit_operator = QubitOperator('X1 Y2 Z3')\nprint(my_first_qubit_operator)\nprint(my_first_qubit_operator.terms)\n\noperator_2 = QubitOperator('X3 Z4', 3.17)\noperator_2 -= 77. * my_first_qubit_operator\nprint('')\nprint(operator_2)\n```\n\n## Jordan-Wigner and Bravyi-Kitaev\nopenfermion provides functions for mapping FermionOperators to QubitOperators.\n\n\n```python\nfrom openfermion.ops import FermionOperator\nfrom openfermion.transforms import jordan_wigner, bravyi_kitaev\nfrom openfermion.utils import hermitian_conjugated\nfrom openfermion.linalg import eigenspectrum\n\n# Initialize an operator.\nfermion_operator = FermionOperator('2^ 0', 3.17)\nfermion_operator += hermitian_conjugated(fermion_operator)\nprint(fermion_operator)\n\n# Transform to qubits under the Jordan-Wigner transformation and print its spectrum.\njw_operator = jordan_wigner(fermion_operator)\nprint('')\nprint(jw_operator)\njw_spectrum = eigenspectrum(jw_operator)\nprint(jw_spectrum)\n\n# Transform to qubits under the Bravyi-Kitaev transformation and print its spectrum.\nbk_operator = bravyi_kitaev(fermion_operator)\nprint('')\nprint(bk_operator)\nbk_spectrum = eigenspectrum(bk_operator)\nprint(bk_spectrum)\n```\n\nWe see that despite the different representation, these operators are iso-spectral. We can also apply the Jordan-Wigner transform in reverse to map arbitrary QubitOperators to FermionOperators. Note that we also demonstrate the .compress() method (a method on both FermionOperators and QubitOperators) which removes zero entries.\n\n\n```python\nfrom openfermion.transforms import reverse_jordan_wigner\n\n# Initialize QubitOperator.\nmy_operator = QubitOperator('X0 Y1 Z2', 88.)\nmy_operator += QubitOperator('Z1 Z4', 3.17)\nprint(my_operator)\n\n# Map QubitOperator to a FermionOperator.\nmapped_operator = reverse_jordan_wigner(my_operator)\nprint('')\nprint(mapped_operator)\n\n# Map the operator back to qubits and make sure it is the same.\nback_to_normal = jordan_wigner(mapped_operator)\nback_to_normal.compress()\nprint('')\nprint(back_to_normal)\n```\n\n## Sparse matrices and the Hubbard model\nOften, one would like to obtain a sparse matrix representation of an operator which can be analyzed numerically. There is code in both openfermion.transforms and openfermion.utils which facilitates this. The function get_sparse_operator converts either a FermionOperator, a QubitOperator or other more advanced classes such as InteractionOperator to a scipy.sparse.csc matrix. There are numerous functions in openfermion.utils which one can call on the sparse operators such as \"get_gap\", \"get_hartree_fock_state\", \"get_ground_state\", etc. We show this off by computing the ground state energy of the Hubbard model. To do that, we use code from the openfermion.hamiltonians module which constructs lattice models of fermions such as Hubbard models.\n\n\n```python\nfrom openfermion.hamiltonians import fermi_hubbard\nfrom openfermion.linalg import get_sparse_operator, get_ground_state\nfrom openfermion.transforms import jordan_wigner\n\n\n# Set model.\nx_dimension = 2\ny_dimension = 2\ntunneling = 2.\ncoulomb = 1.\nmagnetic_field = 0.5\nchemical_potential = 0.25\nperiodic = 1\nspinless = 1\n\n# Get fermion operator.\nhubbard_model = fermi_hubbard(\n    x_dimension, y_dimension, tunneling, coulomb, chemical_potential,\n    magnetic_field, periodic, spinless)\nprint(hubbard_model)\n\n# Get qubit operator under Jordan-Wigner.\njw_hamiltonian = jordan_wigner(hubbard_model)\njw_hamiltonian.compress()\nprint('')\nprint(jw_hamiltonian)\n\n# Get scipy.sparse.csc representation.\nsparse_operator = get_sparse_operator(hubbard_model)\nprint('')\nprint(sparse_operator)\nprint('\\nEnergy of the model is {} in units of T and J.'.format(\n    get_ground_state(sparse_operator)[0]))\n```\n\n## Hamiltonians in the plane wave basis\nA user can write plugins to openfermion which allow for the use of, e.g., third-party electronic structure package to compute molecular orbitals, Hamiltonians, energies, reduced density matrices, coupled cluster amplitudes, etc using Gaussian basis sets. We may provide scripts which interface between such packages and openfermion in future but do not discuss them in this tutorial.\n\nWhen using simpler basis sets such as plane waves, these packages are not needed. openfermion comes with code which computes Hamiltonians in the plane wave basis. Note that when using plane waves, one is working with the periodized Coulomb operator, best suited for condensed phase calculations such as studying the electronic structure of a solid. To obtain these Hamiltonians one must choose to study the system without a spin degree of freedom (spinless), one must the specify dimension in which the calculation is performed (n_dimensions, usually 3), one must specify how many plane waves are in each dimension (grid_length) and one must specify the length scale of the plane wave harmonics in each dimension (length_scale) and also the locations and charges of the nuclei. One can generate these models with plane_wave_hamiltonian() found in openfermion.hamiltonians. For simplicity, below we compute the Hamiltonian in the case of zero external charge (corresponding to the uniform electron gas, aka jellium). We also demonstrate that one can transform the plane wave Hamiltonian using a Fourier transform without effecting the spectrum of the operator.\n\n\n```python\nfrom openfermion.hamiltonians import jellium_model\nfrom openfermion.utils import Grid\nfrom openfermion.linalg import eigenspectrum\nfrom openfermion.transforms import jordan_wigner, fourier_transform\n\n# Let's look at a very small model of jellium in 1D.\ngrid = Grid(dimensions=1, length=3, scale=1.0)\nspinless = True\n\n# Get the momentum Hamiltonian.\nmomentum_hamiltonian = jellium_model(grid, spinless)\nmomentum_qubit_operator = jordan_wigner(momentum_hamiltonian)\nmomentum_qubit_operator.compress()\nprint(momentum_qubit_operator)\n\n# Fourier transform the Hamiltonian to the position basis.\nposition_hamiltonian = fourier_transform(momentum_hamiltonian, grid, spinless)\nposition_qubit_operator = jordan_wigner(position_hamiltonian)\nposition_qubit_operator.compress()\nprint('')\nprint (position_qubit_operator)\n\n# Check the spectra to make sure these representations are iso-spectral.\nspectral_difference = eigenspectrum(momentum_qubit_operator) -  eigenspectrum(position_qubit_operator)\nprint('')\nprint(spectral_difference)\n```\n\n## Basics of MolecularData class\n\nData from electronic structure calculations can be saved in an OpenFermion data structure called MolecularData, which makes it easy to access within our library. Often, one would like to analyze a chemical series or look at many different Hamiltonians and sometimes the electronic structure calculations are either expensive to compute or difficult to converge (e.g. one needs to mess around with different types of SCF routines to make things converge). Accordingly, we anticipate that users will want some way to automatically database the results of their electronic structure calculations so that important data (such as the SCF integrals) can be looked up on-the-fly if the user has computed them in the past. OpenFermion supports a data provenance strategy which saves key results of the electronic structure calculation (including pointers to files containing large amounts of data, such as the molecular integrals) in an HDF5 container.\n\nThe MolecularData class stores information about molecules. One initializes a MolecularData object by specifying parameters of a molecule such as its geometry, basis, multiplicity, charge and an optional string describing it. One can also initialize MolecularData simply by providing a string giving a filename where a previous MolecularData object was saved in an HDF5 container. One can save a MolecularData instance by calling the class's .save() method. This automatically saves the instance in a data folder specified during OpenFermion installation. The name of the file is generated automatically from the instance attributes and optionally provided description. Alternatively, a filename can also be provided as an optional input if one wishes to manually name the file.\n\nWhen electronic structure calculations are run, the data files for the molecule can be automatically updated. If one wishes to later use that data they either initialize MolecularData with the instance filename or initialize the instance and then later call the .load() method.\n\nBasis functions are provided to initialization using a string such as \"6-31g\". Geometries can be specified using a simple txt input file (see geometry_from_file function in molecular_data.py) or can be passed using a simple python list format demonstrated below. Atoms are specified using a string for their atomic symbol. Distances should be provided in angstrom. Below we initialize a simple instance of MolecularData without performing any electronic structure calculations.\n\n\n```python\nfrom openfermion.chem import MolecularData\n\n# Set parameters to make a simple molecule.\ndiatomic_bond_length = .7414\ngeometry = [('H', (0., 0., 0.)), ('H', (0., 0., diatomic_bond_length))]\nbasis = 'sto-3g'\nmultiplicity = 1\ncharge = 0\ndescription = str(diatomic_bond_length)\n\n# Make molecule and print out a few interesting facts about it.\nmolecule = MolecularData(geometry, basis, multiplicity,\n                         charge, description)\nprint('Molecule has automatically generated name {}'.format(\n    molecule.name))\nprint('Information about this molecule would be saved at:\\n{}\\n'.format(\n    molecule.filename))\nprint('This molecule has {} atoms and {} electrons.'.format(\n    molecule.n_atoms, molecule.n_electrons))\nfor atom, atomic_number in zip(molecule.atoms, molecule.protons):\n    print('Contains {} atom, which has {} protons.'.format(\n        atom, atomic_number))\n```\n\nIf we had previously computed this molecule using an electronic structure package, we can call molecule.load() to populate all sorts of interesting fields in the data structure. Though we make no assumptions about what electronic structure packages users might install, we assume that the calculations are saved in OpenFermion's MolecularData objects. Currently plugins are available for [Psi4](http://psicode.org/) [(OpenFermion-Psi4)](http://github.com/quantumlib/OpenFermion-Psi4) and [PySCF](https://github.com/sunqm/pyscf) [(OpenFermion-PySCF)](http://github.com/quantumlib/OpenFermion-PySCF), and there may be more in the future. For the purposes of this example, we will load data that ships with OpenFermion to make a plot of the energy surface of hydrogen. Note that helper functions to initialize some interesting chemical benchmarks are found in openfermion.utils.\n\n\n```python\n# Set molecule parameters.\nbasis = 'sto-3g'\nmultiplicity = 1\nbond_length_interval = 0.1\nn_points = 25\n\n# Generate molecule at different bond lengths.\nhf_energies = []\nfci_energies = []\nbond_lengths = []\nfor point in range(3, n_points + 1):\n    bond_length = bond_length_interval * point\n    bond_lengths += [bond_length]\n    description = str(round(bond_length,2))\n    print(description)\n    geometry = [('H', (0., 0., 0.)), ('H', (0., 0., bond_length))]\n    molecule = MolecularData(\n        geometry, basis, multiplicity, description=description)\n    \n    # Load data.\n    molecule.load()\n\n    # Print out some results of calculation.\n    print('\\nAt bond length of {} angstrom, molecular hydrogen has:'.format(\n        bond_length))\n    print('Hartree-Fock energy of {} Hartree.'.format(molecule.hf_energy))\n    print('MP2 energy of {} Hartree.'.format(molecule.mp2_energy))\n    print('FCI energy of {} Hartree.'.format(molecule.fci_energy))\n    print('Nuclear repulsion energy between protons is {} Hartree.'.format(\n        molecule.nuclear_repulsion))\n    for orbital in range(molecule.n_orbitals):\n        print('Spatial orbital {} has energy of {} Hartree.'.format(\n            orbital, molecule.orbital_energies[orbital]))\n    hf_energies += [molecule.hf_energy]\n    fci_energies += [molecule.fci_energy]\n\n# Plot.\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nplt.figure(0)\nplt.plot(bond_lengths, fci_energies, 'x-')\nplt.plot(bond_lengths, hf_energies, 'o-')\nplt.ylabel('Energy in Hartree')\nplt.xlabel('Bond length in angstrom')\nplt.show()\n```\n\nThe geometry data needed to generate MolecularData can also be retreived from the PubChem online database by inputting the molecule's name.\n\n\n```python\nfrom openfermion.chem import geometry_from_pubchem\n\nmethane_geometry = geometry_from_pubchem('methane')\nprint(methane_geometry)\n```\n\n## InteractionOperator and InteractionRDM for efficient numerical representations\n\nFermion Hamiltonians can be expressed as $H = h_0 + \\sum_{pq} h_{pq}\\, a^\\dagger_p a_q + \\frac{1}{2} \\sum_{pqrs} h_{pqrs} \\, a^\\dagger_p a^\\dagger_q a_r a_s$ where $h_0$ is a constant shift due to the nuclear repulsion and $h_{pq}$ and $h_{pqrs}$ are the famous molecular integrals. Since fermions interact pairwise, their energy is thus a unique function of the one-particle and two-particle reduced density matrices which are expressed in second quantization as $\\rho_{pq} = \\left \\langle p \\mid a^\\dagger_p a_q \\mid q \\right \\rangle$ and $\\rho_{pqrs} = \\left \\langle pq \\mid a^\\dagger_p a^\\dagger_q a_r a_s \\mid rs \\right \\rangle$, respectively.\n\nBecause the RDMs and molecular Hamiltonians are both compactly represented and manipulated as 2- and 4- index tensors, we can represent them in a particularly efficient form using  similar data structures. The InteractionOperator data structure can be initialized for a Hamiltonian by passing the constant $h_0$ (or 0), as well as numpy arrays representing $h_{pq}$ (or $\\rho_{pq}$) and $h_{pqrs}$ (or $\\rho_{pqrs}$). Importantly, InteractionOperators can also be obtained by calling MolecularData.get_molecular_hamiltonian() or by calling the function get_interaction_operator() (found in openfermion.transforms) on a FermionOperator. The InteractionRDM data structure is similar but represents RDMs. For instance, one can get a molecular RDM by calling MolecularData.get_molecular_rdm(). When generating Hamiltonians from the MolecularData class, one can choose to restrict the system to an active space.\n\nThese classes inherit from the same base class, PolynomialTensor. This data structure overloads the slice operator [] so that one can get or set the key attributes of the InteractionOperator: $\\textrm{.constant}$, $\\textrm{.one_body_coefficients}$ and $\\textrm{.two_body_coefficients}$ . For instance, InteractionOperator[(p, 1), (q, 1), (r, 0), (s, 0)] would return $h_{pqrs}$ and InteractionRDM would return $\\rho_{pqrs}$. Importantly, the class supports fast basis transformations using the method PolynomialTensor.rotate_basis(rotation_matrix).\nBut perhaps most importantly, one can map the InteractionOperator to any of the other data structures we've described here.\n\nBelow, we load MolecularData from a saved calculation of LiH. We then obtain an InteractionOperator representation of this system in an active space. We then map that operator to qubits. We then demonstrate that one can rotate the orbital basis of the InteractionOperator using random angles to obtain a totally different operator that is still iso-spectral.\n\n\n```python\nfrom openfermion.chem import MolecularData\nfrom openfermion.transforms import get_fermion_operator, jordan_wigner\nfrom openfermion.linalg import get_ground_state, get_sparse_operator\nimport numpy\nimport scipy\nimport scipy.linalg\n\n# Load saved file for LiH.\ndiatomic_bond_length = 1.45\ngeometry = [('Li', (0., 0., 0.)), ('H', (0., 0., diatomic_bond_length))]\nbasis = 'sto-3g'\nmultiplicity = 1\n\n# Set Hamiltonian parameters.\nactive_space_start = 1\nactive_space_stop = 3\n\n# Generate and populate instance of MolecularData.\nmolecule = MolecularData(geometry, basis, multiplicity, description=\"1.45\")\nmolecule.load()\n\n# Get the Hamiltonian in an active space.\nmolecular_hamiltonian = molecule.get_molecular_hamiltonian(\n    occupied_indices=range(active_space_start),\n    active_indices=range(active_space_start, active_space_stop))\n\n# Map operator to fermions and qubits.\nfermion_hamiltonian = get_fermion_operator(molecular_hamiltonian)\nqubit_hamiltonian = jordan_wigner(fermion_hamiltonian)\nqubit_hamiltonian.compress()\nprint('The Jordan-Wigner Hamiltonian in canonical basis follows:\\n{}'.format(qubit_hamiltonian))\n\n# Get sparse operator and ground state energy.\nsparse_hamiltonian = get_sparse_operator(qubit_hamiltonian)\nenergy, state = get_ground_state(sparse_hamiltonian)\nprint('Ground state energy before rotation is {} Hartree.\\n'.format(energy))\n\n# Randomly rotate.\nn_orbitals = molecular_hamiltonian.n_qubits // 2\nn_variables = int(n_orbitals * (n_orbitals - 1) / 2)\nnumpy.random.seed(1)\nrandom_angles = numpy.pi * (1. - 2. * numpy.random.rand(n_variables))\nkappa = numpy.zeros((n_orbitals, n_orbitals))\nindex = 0\nfor p in range(n_orbitals):\n    for q in range(p + 1, n_orbitals):\n        kappa[p, q] = random_angles[index]\n        kappa[q, p] = -numpy.conjugate(random_angles[index])\n        index += 1\n\n    # Build the unitary rotation matrix.\n    difference_matrix = kappa + kappa.transpose()\n    rotation_matrix = scipy.linalg.expm(kappa)\n\n    # Apply the unitary.\n    molecular_hamiltonian.rotate_basis(rotation_matrix)\n\n# Get qubit Hamiltonian in rotated basis.\nqubit_hamiltonian = jordan_wigner(molecular_hamiltonian)\nqubit_hamiltonian.compress()\nprint('The Jordan-Wigner Hamiltonian in rotated basis follows:\\n{}'.format(qubit_hamiltonian))\n\n# Get sparse Hamiltonian and energy in rotated basis.\nsparse_hamiltonian = get_sparse_operator(qubit_hamiltonian)\nenergy, state = get_ground_state(sparse_hamiltonian)\nprint('Ground state energy after rotation is {} Hartree.'.format(energy))\n```\n\n## Quadratic Hamiltonians and Slater determinants\n\nThe general electronic structure Hamiltonian\n$H = h_0 + \\sum_{pq} h_{pq}\\, a^\\dagger_p a_q + \\frac{1}{2} \\sum_{pqrs} h_{pqrs} \\, a^\\dagger_p a^\\dagger_q a_r a_s$ contains terms that act on up to 4 sites, or\nis quartic in the fermionic creation and annihilation operators. However, in many situations\nwe may fruitfully approximate these Hamiltonians by replacing these quartic terms with\nterms that act on at most 2 fermionic sites, or quadratic terms, as in mean-field approximation theory.  \nThese Hamiltonians have a number of\nspecial properties one can exploit for efficient simulation and manipulation of the Hamiltonian, thus\nwarranting a special data structure.  We refer to Hamiltonians which\nonly contain terms that are quadratic in the fermionic creation and annihilation operators\nas quadratic Hamiltonians, and include the general case of non-particle conserving terms as in\na general Bogoliubov transformation.  Eigenstates of quadratic Hamiltonians can be prepared\nefficiently on both a quantum and classical computer, making them amenable to initial guesses for\nmany more challenging problems.\n\nA general quadratic Hamiltonian takes the form\n$$H = \\sum_{p, q} (M_{pq} - \\mu \\delta_{pq}) a^\\dagger_p a_q + \\frac{1}{2} \\sum_{p, q} (\\Delta_{pq} a^\\dagger_p a^\\dagger_q + \\Delta_{pq}^* a_q a_p) + \\text{constant},$$\nwhere $M$ is a Hermitian matrix, $\\Delta$ is an antisymmetric matrix,\n$\\delta_{pq}$ is the Kronecker delta symbol, and $\\mu$ is a chemical\npotential term which we keep separate from $M$ so that we can use it\nto adjust the expectation of the total number of particles.\nIn OpenFermion, quadratic Hamiltonians are conveniently represented and manipulated\nusing the QuadraticHamiltonian class, which stores $M$, $\\Delta$, $\\mu$ and the constant. It is specialized to exploit the properties unique to quadratic Hamiltonians. Like InteractionOperator and InteractionRDM, it inherits from the PolynomialTensor class.\n\nThe BCS mean-field model of superconductivity is a quadratic Hamiltonian. The following code constructs an instance of this model as a FermionOperator, converts it to a QuadraticHamiltonian, and then computes its ground energy:\n\n\n```python\nfrom openfermion.hamiltonians import mean_field_dwave\nfrom openfermion.transforms import get_quadratic_hamiltonian\n\n# Set model.\nx_dimension = 2\ny_dimension = 2\ntunneling = 2.\nsc_gap = 1.\nperiodic = True\n\n# Get FermionOperator.\nmean_field_model = mean_field_dwave(\n    x_dimension, y_dimension, tunneling, sc_gap, periodic=periodic)\n\n# Convert to QuadraticHamiltonian\nquadratic_hamiltonian = get_quadratic_hamiltonian(mean_field_model)\n\n# Compute the ground energy\nground_energy = quadratic_hamiltonian.ground_energy()\nprint(ground_energy)\n```\n\nAny quadratic Hamiltonian may be rewritten in the form\n$$H = \\sum_p \\varepsilon_p b^\\dagger_p b_p + \\text{constant},$$\nwhere the $b_p$ are new annihilation operators that satisfy the fermionic anticommutation relations, and which are linear combinations of the old creation and annihilation operators. This form of $H$ makes it easy to deduce its eigenvalues; they are sums of subsets of the $\\varepsilon_p$, which we call the orbital energies of $H$. The following code computes the orbital energies and the constant:\n\n\n```python\norbital_energies, constant = quadratic_hamiltonian.orbital_energies()\nprint(orbital_energies)\nprint()\nprint(constant)\n```\n\nEigenstates of quadratic hamiltonians are also known as fermionic Gaussian states, and they can be prepared efficiently on a quantum computer. One can use OpenFermion to obtain circuits for preparing these states. The following code obtains the description of a circuit which prepares the ground state (operations that can be performed in parallel are grouped together), along with a description of the starting state to which the circuit should be applied:\n\n\n```python\nfrom openfermion.circuits import gaussian_state_preparation_circuit\n\ncircuit_description, start_orbitals = gaussian_state_preparation_circuit(quadratic_hamiltonian)\nfor parallel_ops in circuit_description:\n    print(parallel_ops)\nprint('')\nprint(start_orbitals)\n```\n\nIn the circuit description, each elementary operation is either a tuple of the form $(i, j, \\theta, \\varphi)$, indicating the operation $\\exp[i \\varphi a_j^\\dagger a_j]\\exp[\\theta (a_i^\\dagger a_j - a_j^\\dagger a_i)]$, which is a Givens rotation of modes $i$ and $j$, or the string 'pht', indicating the particle-hole transformation on the last fermionic mode, which is the operator $\\mathcal{B}$ such that $\\mathcal{B} a_N \\mathcal{B}^\\dagger = a_N^\\dagger$ and leaves the rest of the ladder operators unchanged. Operations that can be performed in parallel are grouped together.\n\nIn the special case that a quadratic Hamiltonian conserves particle number ($\\Delta = 0$), its eigenstates take the form\n$$\\lvert \\Psi_S \\rangle = b^\\dagger_{1}\\cdots b^\\dagger_{N_f}\\lvert \\text{vac} \\rangle,\\qquad\nb^\\dagger_{p} = \\sum_{k=1}^N Q_{pq}a^\\dagger_q,$$\nwhere $Q$ is an $N_f \\times N$ matrix with orthonormal rows. These states are also known as Slater determinants. OpenFermion also provides functionality to obtain circuits for preparing Slater determinants starting with the matrix $Q$ as the input.\n", "meta": {"hexsha": "51a2510c7cb18b08f2f76d02e4fa6a330b3ca379", "size": 42570, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/intro_to_openfermion.ipynb", "max_stars_repo_name": "Emieeel/OpenFermion", "max_stars_repo_head_hexsha": "c19d9667c5970473893f9bc0183556c4cd354dd7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/tutorials/intro_to_openfermion.ipynb", "max_issues_repo_name": "Emieeel/OpenFermion", "max_issues_repo_head_hexsha": "c19d9667c5970473893f9bc0183556c4cd354dd7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/tutorials/intro_to_openfermion.ipynb", "max_forks_repo_name": "Emieeel/OpenFermion", "max_forks_repo_head_hexsha": "c19d9667c5970473893f9bc0183556c4cd354dd7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-11-13T04:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T04:41:01.000Z", "avg_line_length": 46.4737991266, "max_line_length": 1165, "alphanum_fraction": 0.662085976, "converted": true, "num_tokens": 8101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3812195662561499, "lm_q2_score": 0.09947020387122164, "lm_q1q2_score": 0.03791998797519792}}
{"text": "# Bu Tweet Hangi Politik Lidere Ait?\n\nTakvimler \u015fu an 27 Temmuz 2020'yi g\u00f6stermekte. \u00dclkece atlatt\u0131\u011f\u0131m\u0131z son se\u00e7im 31 Mart 2019 tarihinde idi. O tarihten bu yana (se\u00e7im g\u00fcn\u00fc hari\u00e7), T\u00fcrkiye siyasi partilerinden Ak Parti Genel Ba\u015fkan\u0131 ve T\u00fcrkiye Cumhurba\u015fkan\u0131 Recep Tayyip Erdo\u011fan ile Cumhuriyet\u00e7i Halk Partisi Genel Ba\u015fkan\u0131 Kemal K\u0131l\u0131\u00e7daro\u011flu taraf\u0131ndan at\u0131lm\u0131\u015f olan herkese a\u00e7\u0131k Tweet'leri twint mod\u00fcl\u00fcn\u00fc kullanarak scrapeledim. Mod\u00fcl hakk\u0131nda daha fazla bilgi i\u00e7in [buraya](https://github.com/twintproject/twint/wiki) t\u0131klayabilirsiniz. Scraping scriptimi (get_tweets.py) bu repoda bulabilirsiniz.\n\n#### \u00d6zetle, bu projede makine \u00f6\u011frenimi yoluyla Tweetlerin kim taraf\u0131ndan payla\u015f\u0131ld\u0131\u011f\u0131n\u0131 tahmin eden bir s\u0131n\u0131fland\u0131r\u0131c\u0131 yapaca\u011f\u0131z. Daha detayl\u0131 bilgiyi devam eden ba\u015fl\u0131klarda ve a\u00e7\u0131klamalarda sunaca\u011f\u0131m.\n\nElimizdeki veri metin verisi, her iki partinin genel ba\u015fkan\u0131n\u0131n \u015fu ana kadar atm\u0131\u015f olduklar\u0131 Tweetlere dair bilgiler i\u00e7ermekte.\n\nVerilerin yap\u0131land\u0131rmas\u0131 \u015fu \u015fekilde:\n* id: Tweetlerin \u00f6zg\u00fcn kimlik numaralar\u0131\n* created_at: Tweetlerin at\u0131lma zaman\u0131\n* username: Tweet sahibinin kullan\u0131c\u0131 ismi\n* tweet: Tweet i\u00e7eri\u011fi (metin)\n* mentions: Etiketlenen Twitter kullan\u0131c\u0131lar\u0131n\u0131n kullan\u0131c\u0131 isimleri\n* likes_count: Tweet'in ald\u0131\u011f\u0131 like say\u0131s\u0131\n* retweet: Tweet Retweet mi de\u011fil mi? (Boolean)\n* hashtags: Kullan\u0131lan etiketlerin listesi\n\n\u00d6nce kullanaca\u011f\u0131m\u0131z mod\u00fclleri ve elimizdeki verileri i\u00e7e aktararak ba\u015flayal\u0131m:\n\n# 1. Verileri \u0130\u00e7e Aktarma ve Ke\u015ffetme\n\n\n```python\nimport pandas as pd\nimport numpy as np\nimport datetime as dt\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.feature_extraction.text import CountVectorizer\n\n%matplotlib inline\n```\n\n\n```python\nrte_tweetleri = pd.read_csv(\"RTErdogan.csv\")\nkk_tweetleri = pd.read_csv(\"kilicdarogluk.csv\")\n\n#\u0130\u015flem kolayl\u0131\u011f\u0131 i\u00e7in verileri tek veri setinde toplayaca\u011f\u0131z:\ntwt = pd.concat([rte_tweetleri, kk_tweetleri])\n\ntwt.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>id</th>\n      <th>created_at</th>\n      <th>username</th>\n      <th>tweet</th>\n      <th>mentions</th>\n      <th>likes_count</th>\n      <th>retweet</th>\n      <th>hashtags</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1287361340080828418</td>\n      <td>1595765836000</td>\n      <td>rterdogan</td>\n      <td>Mill\u00ee \u0130stihbarat Te\u015fkilat\u0131 \u0130stanbul B\u00f6lge Ba\u015fk...</td>\n      <td>[]</td>\n      <td>42189</td>\n      <td>False</td>\n      <td>[]</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1287043591479664641</td>\n      <td>1595690078000</td>\n      <td>rterdogan</td>\n      <td>Eserleriyle tarihe \u0131\u015f\u0131k tutan \u201chocalar\u0131n hocas...</td>\n      <td>[]</td>\n      <td>50113</td>\n      <td>False</td>\n      <td>[]</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1287016078334398464</td>\n      <td>1595683519000</td>\n      <td>rterdogan</td>\n      <td>T\u00fcrkiye Cumhuriyeti Devleti'ni kurulu\u015funun 100...</td>\n      <td>[]</td>\n      <td>36765</td>\n      <td>False</td>\n      <td>[]</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1286989390846267393</td>\n      <td>1595677156000</td>\n      <td>rterdogan</td>\n      <td>Amasya \u00c7evre Yolu A\u00e7\u0131l\u0131\u015f T\u00f6reni\u2019ne canl\u0131 ba\u011fla...</td>\n      <td>[]</td>\n      <td>33986</td>\n      <td>False</td>\n      <td>[]</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1286603362256003073</td>\n      <td>1595585120000</td>\n      <td>rterdogan</td>\n      <td>\u0130lk cuma namaz\u0131 @AyasofyaCamii https://twitter...</td>\n      <td>['ayasofyacamii']</td>\n      <td>121117</td>\n      <td>False</td>\n      <td>[]</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ntwt.info()\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    Int64Index: 1267 entries, 0 to 397\n    Data columns (total 8 columns):\n     #   Column       Non-Null Count  Dtype \n    ---  ------       --------------  ----- \n     0   id           1267 non-null   int64 \n     1   created_at   1267 non-null   int64 \n     2   username     1267 non-null   object\n     3   tweet        1267 non-null   object\n     4   mentions     1267 non-null   object\n     5   likes_count  1267 non-null   int64 \n     6   retweet      1267 non-null   bool  \n     7   hashtags     1267 non-null   object\n    dtypes: bool(1), int64(3), object(4)\n    memory usage: 80.4+ KB\n\n\nG\u00f6rd\u00fc\u011f\u00fcm\u00fcz \u00fczere hi\u00e7 eksik verimiz yok. Verilerimizin \u00fczerinde \u00e7al\u0131\u015fmaya ba\u015flayabiliriz.\n\n# 2. Verilerin \u0130\u015flenmesi\n\nVerilerimizi makine \u00f6\u011frenimi uygulamadan \u00f6nce temizleyip i\u015flemek zorunday\u0131z. Buna \"created_at\" s\u00fctunundan ba\u015flayaca\u011f\u0131z. Projemize giri\u015fte bu s\u00fctunun Tweetlerin at\u0131ld\u0131\u011f\u0131 zaman\u0131 belirtti\u011fini s\u00f6ylemi\u015ftik. Oysa s\u00fctunumuz \u015fu an integer tipinde. S\u00fctunumuzu daha anla\u015f\u0131l\u0131r hale getirmek i\u00e7in datetime tipine \u00e7evirece\u011fiz. Sonras\u0131nda da \"id\" s\u00fctunumuzu \"tweet_id\" \u015feklinde yeniden isimlendirece\u011fiz.\n\n\n```python\ntwt.created_at = pd.to_datetime(twt.created_at, unit=\"ms\").dt.date #zaman birimi default olarak \"ns\" ayarl\u0131d\u0131r, bu y\u00fczden \"ms\" olarak belirttik.\ntwt.created_at.tail()\n```\n\n\n\n\n    393    2019-04-12\n    394    2019-04-09\n    395    2019-04-08\n    396    2019-04-03\n    397    2019-04-02\n    Name: created_at, dtype: object\n\n\n\n\n```python\ntwt.rename({\"id\": \"tweet_id\"}, axis=1, inplace=True)\ntwt.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>tweet_id</th>\n      <th>created_at</th>\n      <th>username</th>\n      <th>tweet</th>\n      <th>mentions</th>\n      <th>likes_count</th>\n      <th>retweet</th>\n      <th>hashtags</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1287361340080828418</td>\n      <td>2020-07-26</td>\n      <td>rterdogan</td>\n      <td>Mill\u00ee \u0130stihbarat Te\u015fkilat\u0131 \u0130stanbul B\u00f6lge Ba\u015fk...</td>\n      <td>[]</td>\n      <td>42189</td>\n      <td>False</td>\n      <td>[]</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1287043591479664641</td>\n      <td>2020-07-25</td>\n      <td>rterdogan</td>\n      <td>Eserleriyle tarihe \u0131\u015f\u0131k tutan \u201chocalar\u0131n hocas...</td>\n      <td>[]</td>\n      <td>50113</td>\n      <td>False</td>\n      <td>[]</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1287016078334398464</td>\n      <td>2020-07-25</td>\n      <td>rterdogan</td>\n      <td>T\u00fcrkiye Cumhuriyeti Devleti'ni kurulu\u015funun 100...</td>\n      <td>[]</td>\n      <td>36765</td>\n      <td>False</td>\n      <td>[]</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1286989390846267393</td>\n      <td>2020-07-25</td>\n      <td>rterdogan</td>\n      <td>Amasya \u00c7evre Yolu A\u00e7\u0131l\u0131\u015f T\u00f6reni\u2019ne canl\u0131 ba\u011fla...</td>\n      <td>[]</td>\n      <td>33986</td>\n      <td>False</td>\n      <td>[]</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1286603362256003073</td>\n      <td>2020-07-24</td>\n      <td>rterdogan</td>\n      <td>\u0130lk cuma namaz\u0131 @AyasofyaCamii https://twitter...</td>\n      <td>['ayasofyacamii']</td>\n      <td>121117</td>\n      <td>False</td>\n      <td>[]</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nVerilerimizi \u015fimdilik yeterince temizledik. Elimizdeki veri zaten \u00e7ok s\u0131n\u0131rl\u0131 oldu\u011fu i\u00e7in ve hi\u00e7 eksik bilgi i\u00e7ermedi\u011fi i\u00e7in verilerimizi g\u00f6rselle\u015ftirip analiz edebiliriz.\n\n# 3. Verilerin G\u00f6rselle\u015ftirilmesi ve Analizi\n\nVerilerimizi g\u00f6rselle\u015ftirmeye her iki siyasi fig\u00fcr\u00fcn de farkl\u0131 tarihlerde atm\u0131\u015f olduklar\u0131 Tweet say\u0131lar\u0131 ile ba\u015flayaca\u011f\u0131z. Bunu yapmak i\u00e7in de Tweetleri at\u0131ld\u0131klar\u0131 tarihe ve ait olduklar\u0131 politik lidere g\u00f6re gruplayaca\u011f\u0131z.\n\n\n```python\ntwt_grup = twt[[\"created_at\", \"username\", \"tweet_id\"]].groupby([\"created_at\", \"username\"]).count().reset_index() #id k\u0131sm\u0131n\u0131 saya\u00e7 olarak kullanaca\u011f\u0131z.\n\nxticks_list = [] \nfor index in np.arange(0, 588, 13):\n    xticks_list.append(twt_grup.created_at.iloc[index])\n\nfig, ax = plt.subplots(figsize=(16,10))\nsns.lineplot(x=\"created_at\", y=\"tweet_id\", hue=\"username\", data=twt_grup, palette=\"Set2\", ax=ax)\nplt.xticks(xticks_list, rotation=90)\nplt.title(\"Politik Fig\u00fcrlerin Tweet Say\u0131lar\u0131\")\nplt.xlabel(\"Zaman\")\nplt.ylabel(\"Tweet Miktar\u0131\")\n```\n\nTabloya bakt\u0131\u011f\u0131m\u0131zda g\u00f6z\u00fcm\u00fcze ilk \u00e7arpan \u015fey Recep Tayyip Erdo\u011fan (Turuncu renk) ile Kemal K\u0131l\u0131\u00e7daro\u011flu'nun (Ye\u015fil renk) Twitter aktivite s\u0131kl\u0131\u011f\u0131ndaki fark oluyor. G\u00f6zlemlenebilece\u011fi \u00fczere, Kemal K\u0131l\u0131\u00e7daro\u011flu'nun Twitter kullan\u0131m\u0131 \u00e7ok nadiren g\u00fcnl\u00fck 5 Tweet'ten \u00f6teye giderken, Recep Tayyip Erdo\u011fan g\u00f6zle g\u00f6r\u00fcl\u00fcr bir farkla sosyal medya kullan\u0131m\u0131nda \u00e7ok daha aktif. Ayn\u0131 zamanda, Kemal K\u0131l\u0131\u00e7daro\u011flu'nun **Tweet att\u0131\u011f\u0131 g\u00fcnlerde** genelde g\u00fcnl\u00fck 3 civar\u0131 Tweet at\u0131yor oldu\u011fu g\u00f6zlemlebilirken bunu Recep Tayyip Erdo\u011fan i\u00e7in ilk bak\u0131\u015fta hesaplamak \u00e7ok m\u00fcmk\u00fcn g\u00f6r\u00fcnm\u00fcyor. Recep Tayyip Erdo\u011fan'\u0131n Twitter aktivitesine bakt\u0131\u011f\u0131m\u0131zda i\u00e7inde bulundu\u011fumuz haftada (2020, Temmuz sonu) zirve yapm\u0131\u015f bir dalgalanma haline rastl\u0131yoruz. Dilerseniz her iki liderin de 1 Nisan 2019'dan bu yana g\u00fcnl\u00fck ortalama ne kadar tweet atm\u0131\u015f olduklar\u0131n\u0131 bir hesaplayal\u0131m:\n\n\n```python\nrte_ortalama_g\u00fcnl\u00fck = twt_grup[twt_grup[\"username\"] == \"rterdogan\"].tweet_id.mean()\nkk_ortalama_g\u00fcnl\u00fck = twt_grup[twt_grup[\"username\"] == \"kilicdarogluk\"].tweet_id.mean()\nprint(\"Ortalama g\u00fcnl\u00fck Tweet say\u0131s\u0131 RTE i\u00e7in {} iken, KK i\u00e7in {}.\".format(rte_ortalama_g\u00fcnl\u00fck, kk_ortalama_g\u00fcnl\u00fck))\n```\n\n    Ortalama g\u00fcnl\u00fck Tweet say\u0131s\u0131 RTE i\u00e7in 2.641337386018237 iken, KK i\u00e7in 1.5366795366795367.\n\n\nG\u00f6rd\u00fc\u011f\u00fcm\u00fcz \u00fczere, g\u00fcnl\u00fck at\u0131lan ortalama Tweet say\u0131s\u0131 Recep Tayyip Erdo\u011fan i\u00e7in yakla\u015f\u0131k olarak 3 iken Kemal K\u0131l\u0131\u00e7daro\u011flu i\u00e7in 2. Peki, her iki liderin de en \u00e7ok Tweet att\u0131\u011f\u0131 tarihlerde neler konu\u015fulmu\u015f? Bunu analiz etmek i\u00e7in Tweet i\u00e7eriklerine bakaca\u011f\u0131z. \n\n\n```python\nrte_max_gun = list(twt_grup[twt_grup[\"username\"] == \"rterdogan\"].sort_values(\"tweet_id\", ascending=False).created_at)[0]\nkk_max_gun = list(twt_grup[twt_grup[\"username\"] == \"kilicdarogluk\"].sort_values(\"tweet_id\", ascending=False).created_at)[0]\nrte_tweet_icerik = twt[twt[\"created_at\"] == rte_max_gun].tweet\nkk_tweet_icerik = twt[twt[\"created_at\"] == kk_max_gun].tweet\n\nfor i in rte_tweet_icerik:\n    print(\"RTE: \" + i)\nprint(\"\\n\")\nfor i in kk_tweet_icerik:\n    print(\"KK: \" + i)\n```\n\n    RTE: Ge\u00e7mi\u015fte en k\u00fc\u00e7\u00fck sars\u0131nt\u0131da demokrasisiyle, ekonomisiyle, siyasi ve sosyal yap\u0131s\u0131yla adeta yerle yeksan olan bir T\u00fcrkiye\u2019den; b\u00f6lgesel ve k\u00fcresel her t\u00fcrl\u00fc s\u0131namay\u0131 ba\u015far\u0131yla veren bir T\u00fcrkiye\u2019ye geldik. pic.twitter.com/NiKcYIs08t\n    RTE: Cumhurba\u015fkanl\u0131\u011f\u0131 H\u00fck\u00fcmet Sistemi \ud83c\uddf9\ud83c\uddf7 | K\u00dcLT\u00dcR ve TUR\u0130ZM \ud83c\udfa5\ud83c\udfd6\ufe0f\n    #Reform\u0130craatDe\u011fi\u015fim pic.twitter.com/2iYd6AWbud\n    RTE: Cumhurba\u015fkanl\u0131\u011f\u0131 H\u00fck\u00fcmet Sistemi \ud83c\uddf9\ud83c\uddf7 | DI\u015e\u0130\u015eLER\u0130 \ud83c\udf10\n    #Reform\u0130craatDe\u011fi\u015fim pic.twitter.com/qsLMI5UGyW\n    RTE: Cumhurba\u015fkanl\u0131\u011f\u0131 H\u00fck\u00fcmet Sistemi \ud83c\uddf9\ud83c\uddf7 | ENERJ\u0130 \ud83d\udca1\n    #Reform\u0130craatDe\u011fi\u015fim pic.twitter.com/xR2sECuZLV\n    RTE: Cumhurba\u015fkanl\u0131\u011f\u0131 H\u00fck\u00fcmet Sistemi \ud83c\uddf9\ud83c\uddf7 | SANAY\u0130 ve TEKNOLOJ\u0130 \u2699\ufe0f\n    #Reform\u0130craatDe\u011fi\u015fim pic.twitter.com/r5ZBqhSRI8\n    RTE: Cumhurba\u015fkanl\u0131\u011f\u0131 H\u00fck\u00fcmet Sistemi \ud83c\uddf9\ud83c\uddf7 | T\u0130CARET \ud83d\udce6\ud83d\udcb3\n    #Reform\u0130craatDe\u011fi\u015fim pic.twitter.com/ys7ZmPzn15\n    RTE: Cumhurba\u015fkanl\u0131\u011f\u0131 H\u00fck\u00fcmet Sistemi \ud83c\uddf9\ud83c\uddf7 | HAZ\u0130NE ve MAL\u0130YE \ud83c\udfe6\ud83d\udcc8\n    #Reform\u0130craatDe\u011fi\u015fim pic.twitter.com/d7JeBqldBU\n    RTE: Cumhurba\u015fkanl\u0131\u011f\u0131 H\u00fck\u00fcmet Sistemi \ud83c\uddf9\ud83c\uddf7 | TARIM ve ORMAN \ud83c\udf3e\ud83c\udf32\n    #Reform\u0130craatDe\u011fi\u015fim pic.twitter.com/OEGvUSjshu\n    RTE: Cumhurba\u015fkanl\u0131\u011f\u0131 H\u00fck\u00fcmet Sistemi \ud83c\uddf9\ud83c\uddf7 | \u00c7EVRE ve \u015eEH\u0130RC\u0130L\u0130K \ud83c\udf33\n    #Reform\u0130craatDe\u011fi\u015fim pic.twitter.com/OGbayzinlL\n    RTE: Cumhurba\u015fkanl\u0131\u011f\u0131 H\u00fck\u00fcmet Sistemi \ud83c\uddf9\ud83c\uddf7 | A\u0130LE, \u00c7ALI\u015eMA ve SOSYAL H\u0130ZMETLER \ud83c\udfe0\n    #Reform\u0130craatDe\u011fi\u015fim pic.twitter.com/r1lToMmCLx\n    RTE: Cumhurba\u015fkanl\u0131\u011f\u0131 H\u00fck\u00fcmet Sistemi \ud83c\uddf9\ud83c\uddf7 | ULA\u015eTIRMA ve ALTYAPI \ud83d\ude86\ud83d\udee3\ufe0f\ud83d\udef0\ufe0f\n    #Reform\u0130craatDe\u011fi\u015fim pic.twitter.com/6gcxa0vjw0\n    RTE: Cumhurba\u015fkanl\u0131\u011f\u0131 H\u00fck\u00fcmet Sistemi \ud83c\uddf9\ud83c\uddf7 | M\u0130LL\u0130 SAVUNMA \ud83c\udf96\ufe0f\n    #Reform\u0130craatDe\u011fi\u015fim pic.twitter.com/c7M8sJxmvp\n    RTE: Cumhurba\u015fkanl\u0131\u011f\u0131 H\u00fck\u00fcmet Sistemi \ud83c\uddf9\ud83c\uddf7 | \u0130\u00c7\u0130\u015eLER\u0130 \ud83d\ude94\n    #Reform\u0130craatDe\u011fi\u015fim pic.twitter.com/eKE9Vp03MX\n    RTE: Cumhurba\u015fkanl\u0131\u011f\u0131 H\u00fck\u00fcmet Sistemi \ud83c\uddf9\ud83c\uddf7 | ADALET \u2696\ufe0f\n    #Reform\u0130craatDe\u011fi\u015fim pic.twitter.com/38H4Eaybeq\n    RTE: Cumhurba\u015fkanl\u0131\u011f\u0131 H\u00fck\u00fcmet Sistemi \ud83c\uddf9\ud83c\uddf7 | SA\u011eLIK \ud83e\ude7a\n    #Reform\u0130craatDe\u011fi\u015fim pic.twitter.com/dBiAWZmJBZ\n    RTE: Cumhurba\u015fkanl\u0131\u011f\u0131 H\u00fck\u00fcmet Sistemi \ud83c\uddf9\ud83c\uddf7 | GEN\u00c7L\u0130K ve SPOR \ud83c\udfc3\ud83c\udffb pic.twitter.com/rhr7B93vXa\n    RTE: Cumhurba\u015fkanl\u0131\u011f\u0131 H\u00fck\u00fcmet Sistemi \ud83c\uddf9\ud83c\uddf7 | E\u011e\u0130T\u0130M \ud83d\udcda pic.twitter.com/DY8KagwiIQ\n    RTE: Cumhurba\u015fkanl\u0131\u011f\u0131 H\u00fck\u00fcmet Kabinesi \u0130ki Y\u0131ll\u0131k De\u011ferlendirme Toplant\u0131s\u0131 https://twitter.com/i/broadcasts/1BdGYnkVQaBJX\u00a0\u2026\n    RTE: Partimizin TBMM Grup Toplant\u0131s\u0131 https://www.pscp.tv/w/ceVqojEyNTAwNTF8MXlOR2FCd2VrYmxKaskqvmgZNaJztHLhK-QHSHR4izoqL09SW8A7dQObagN-\u00a0\u2026\n    \n    \n    KK: Vefat\u0131n\u0131n 9. y\u0131l\u0131nda rahmetli Erbakan Hocam\u0131za bir kez daha Allah\u2019tan rahmet diliyorum. Rabbim onu cennetiyle, cemaliyle m\u00fc\u015ferref k\u0131ls\u0131n. pic.twitter.com/VzYfyGzkk2\n    KK: AK Parti Siyaset Akademisi A\u00e7\u0131l\u0131\u015f Dersi https://www.pscp.tv/w/cSeeVDFXTEVSb0dabk1RYkR8MVJER2xRYmRxUE9KTHpBQyJsyyJ9q-rQtYMTP8z3i3nelTKotUOz0G_ScQCF\u00a0\u2026\n    KK: Hatay Valimizden gelen ac\u0131 haberle y\u00fcre\u011fimiz da\u011fland\u0131. \u015eehit olan askerlerimize Allah\u2019tan rahmet, ailelerine ve milletimize ba\u015fsa\u011fl\u0131\u011f\u0131 ve sab\u0131r diliyorum. Allah Mehmet\u00e7i\u011fimizi korusun.\n    KK: KRT TV ve Y\u00f6n Radyo ortak yay\u0131n\u0131nda \u201cSayg\u0131 \u00d6zt\u00fcrk ile Sisler Bulvar\u0131\u201d program\u0131n\u0131n canl\u0131 yay\u0131n konu\u011fuyum. https://www.pscp.tv/w/cSf1MjEyNTAwNTF8MW1ueGVRWk9hQXF4WGfrvoTVAxRFEyDoAWPQf7VSg5TFtBxiXZ6nuD9-aQux\u00a0\u2026\n    KK: Yalova Belediyesi'ndeki hukuksuzlu\u011fu ortaya \u00e7\u0131karan, i\u015flem yap\u0131lmas\u0131 i\u00e7in savc\u0131l\u0131\u011fa ba\u015fvuran Belediye Ba\u015fkan\u0131m\u0131z Vefa Salman'\u0131n g\u00f6revden al\u0131nmas\u0131, saray iktidar\u0131n\u0131n hukuk anlay\u0131\u015f\u0131n\u0131n \u00f6zetidir. Milletimiz nezdinde h\u00fckm\u00fc olmayan bu haks\u0131z, hukuksuz karar\u0131 asla kabul etmiyoruz!\n    KK: Saat 20.30\u2019da @krtkulturtv ve @YonRadyo ortak yay\u0131n\u0131nda \u201cSayg\u0131 \u00d6zt\u00fcrk ile Sisler Bulvar\u0131\u201d program\u0131n\u0131n canl\u0131 yay\u0131n konu\u011fu olaca\u011f\u0131m, gazeteci-yazar @saygi_ozturk'\u00fcn sorular\u0131n\u0131 yan\u0131tlayaca\u011f\u0131m, g\u00fcndeme ili\u015fkin de\u011ferlendirmelerde bulunaca\u011f\u0131m. pic.twitter.com/55NfHwwbhW\n    KK: Ba\u015fta \u00fclkemiz olmak \u00fczere t\u00fcm \u0130slam \u00e2leminin #RegaipKandili\u2019ni kutluyorum. Bu m\u00fcbarek kandil gecesinde, herkesin birlik ve beraberlik i\u00e7inde bar\u0131\u015f dolu yar\u0131nlarda ya\u015famas\u0131n\u0131 diliyorum. pic.twitter.com/w4QET4CaPh\n    KK: Hak\u00e7a b\u00f6l\u00fc\u015fmeyi ve adil payla\u015f\u0131m\u0131 siyasetinin merkezinde tutmaktan asla vazge\u00e7meyen, de\u011ferli devlet adam\u0131 ve \u00f6rnek siyaset\u00e7i Prof. Dr. #NecmettinErbakan\u2019\u0131 vefat\u0131n\u0131n 9. y\u0131l\u0131nda rahmetle an\u0131yorum.\n    KK: \u0130dlib'de d\u00fczenlenen hava sald\u0131r\u0131s\u0131 sonucu \u015fehit olan kahraman askerlerimiz Piyade Uzman \u00c7avu\u015f Soner Enes Bayku\u015f ve \u0130stihk\u00e2m Uzman Onba\u015f\u0131 \u015e\u00fckr\u00fc Elibol'a Allah\u2019tan rahmet, ailelerine ba\u015fsa\u011fl\u0131\u011f\u0131 ve sab\u0131r, yaral\u0131 askerlerimize acil \u015fifalar diliyorum. Milletimizin ba\u015f\u0131 sa\u011f olsun!\n\n\nYukar\u0131da Recep Tayyip Erdo\u011fan ve Kemal K\u0131l\u0131\u00e7daro\u011flu'nun son se\u00e7imden bu yana en \u00e7ok Tweet atm\u0131\u015f olduklar\u0131 g\u00fcnlerde att\u0131klar\u0131 Tweetleri g\u00f6r\u00fcyoruz. Bu verilerden \u00e7\u0131kar\u0131mlar\u0131m\u0131z \u015funlar olabilir:\n* Recep Tayyip Erdo\u011fan'\u0131n Tweetlerinden birini aratt\u0131\u011f\u0131m\u0131zda kar\u015f\u0131m\u0131za Ba\u015fkanl\u0131k Sistemi boyunca \u00e7e\u015fitli alanlarda yap\u0131lan icraatler ile ilgili oldu\u011funu g\u00f6r\u00fcyoruz.\n* Kemal K\u0131l\u0131\u00e7daro\u011flu'nun Tweetlerine bakt\u0131\u011f\u0131m\u0131zda o g\u00fcn\u00fcn g\u00fcndemi hakk\u0131nda daha bilgilendirici olduklar\u0131n\u0131 fark etmekteyiz.\n\n\u015eimdi her iki politik fig\u00fcr\u00fcn hashtag kullan\u0131mlar\u0131n\u0131 inceleyelim.\n\n\n```python\nrte_tags = {}\nkk_tags = {}\n\nfor tag in rte_tweetleri[\"hashtags\"]:\n    if tag not in rte_tags:\n        rte_tags[tag] = 1\n    else:\n        rte_tags[tag] += 1\n        \nfor tag in kk_tweetleri[\"hashtags\"]:\n    if tag not in kk_tags:\n        kk_tags[tag] = 1\n    else:\n        kk_tags[tag] += 1\n\nprint(\"RTE En \u00c7ok Kullan\u0131lan 5 Hashtag:\")\nfor index, tag in enumerate(sorted(rte_tags.items(), key=lambda x:x[1], reverse=True)):\n    if index in range(1, 6):\n        print(tag[0] + \": \" + str(tag[1]))\n        \nprint(\"\\nKK En \u00c7ok Kullan\u0131lan 5 Hashtag:\")\nfor index, tag in enumerate(sorted(kk_tags.items(), key=lambda x:x[1], reverse=True)):\n    if index in range(1, 6):\n        print(tag[0] + \": \" + str(tag[1]))\n```\n\n    RTE En \u00c7ok Kullan\u0131lan 5 Hashtag:\n    ['#reformi\u0307craatde\u011fi\u015fim']: 14\n    ['#yenidenyollarad\u00fc\u015fmevakti']: 5\n    ['#15temmuz']: 4\n    ['#29ekim']: 3\n    ['#d\u00fcnya\u00e7evreg\u00fcn\u00fc']: 2\n    \n    KK En \u00c7ok Kullan\u0131lan 5 Hashtag:\n    ['#ayd\u0131n']: 4\n    ['#1may\u0131s']: 3\n    ['#lozanbar\u0131\u015fantla\u015fmas\u0131']: 2\n    ['#erzurumkongresi']: 2\n    ['#s\u00fcleymandemirel']: 2\n\n\nHer iki politik fig\u00fcr\u00fcn de yayg\u0131n kulland\u0131klar\u0131 hashtagleri yukar\u0131da g\u00f6rebilirsiniz. \u015eimdi bu politik ki\u015filiklerin zamanla ald\u0131klar\u0131 like say\u0131s\u0131n\u0131 g\u00f6rselle\u015ftirelim.\n\n\n```python\ntwt_grup_2 = twt[[\"created_at\", \"username\", \"likes_count\"]].groupby([\"created_at\", \"username\"]).sum().reset_index() #id k\u0131sm\u0131n\u0131 saya\u00e7 olarak kullanaca\u011f\u0131z.\n\nfig1, ax1 = plt.subplots(figsize=(16,10))\nsns.lineplot(x=\"created_at\", y=\"likes_count\", hue=\"username\", data=twt_grup_2, palette=\"Set2\", ax=ax1)\n_ = plt.xticks(xticks_list, rotation=90)\nplt.title(\"Politik Fig\u00fcrlerin G\u00fcnl\u00fck Like Miktarlar\u0131\")\nplt.xlabel(\"Zaman\")\nplt.ylabel(\"Like Miktar\u0131\")\n```\n\nYukar\u0131daki tabloya bakt\u0131\u011f\u0131m\u0131zda g\u00f6z\u00fcm\u00fcze \u00e7arpan ilk \u015fey Recep Tayyip Erdo\u011fan'\u0131n be\u011feni miktar\u0131n\u0131n genel olarak Kemal K\u0131l\u0131\u00e7daro\u011flu'nun be\u011fenilerinden daha fazla oldu\u011fu. \u00d6zellikle 2020 senesine bakt\u0131\u011f\u0131m\u0131zda, Recep Tayyip Erdo\u011fan taraf\u0131ndan at\u0131lan tweetlerin like say\u0131lar\u0131n\u0131n son zamanlara do\u011fru b\u00fcy\u00fck bir art\u0131\u015f g\u00f6stermi\u015f oldu\u011funu farkediyoruz.\n\nVerimizi yeterince inceledi\u011fimize g\u00f6re i\u015fin makine \u00f6\u011frenimi olan k\u0131sm\u0131na ge\u00e7ebiliriz.\n\n# 4. Terim A\u011f\u0131rl\u0131kland\u0131rma (Feature Weighting)\n\nBu ad\u0131mda Tweetlerde ge\u00e7en kelimelerin terim frekanslar\u0131n\u0131 baz alarak verimizi makine \u00f6\u011frenimine haz\u0131r bir \u015fekle getirece\u011fiz. Bunu yaparken verilerimizi biri makine \u00f6\u011frenimi esnas\u0131nda, di\u011feri ise hakk\u0131nda sonraki ad\u0131mda daha \u00e7ok bilgi edinebilece\u011finiz do\u011fruluk testi esnas\u0131nda kullan\u0131lmak \u00fczere iki b\u00f6l\u00fcme ay\u0131raca\u011f\u0131z.\n\n\n```python\ntraining_data, testing_data = train_test_split(twt, random_state=1) #\u00e7al\u0131\u015fman\u0131n tekrarlanabilirli\u011fi i\u00e7in seed belirttik.\n\nY_train = training_data[\"username\"].values\nY_test = testing_data[\"username\"].values\n\ndef kelime_sayac\u0131(s\u00fctun, training_set, testing_set):\n\n    cv = CountVectorizer(binary=False, max_df=0.95)\n    cv.fit_transform(training_data[s\u00fctun].values)\n    \n    train_feature_set = cv.transform(training_data[s\u00fctun].values)\n    test_feature_set = cv.transform(testing_data[s\u00fctun].values)\n    \n    return train_feature_set, test_feature_set, cv\n\nX_train, X_test, feature_transformer = kelime_sayac\u0131(\"tweet\", training_data, testing_data)\n```\n\n# 5. Lojistik Regresyon\n\nBu k\u0131s\u0131mda ise haz\u0131rlam\u0131\u015f oldu\u011fumuz veriler ile \u00f6nce modelimizi e\u011fitece\u011fiz, sonras\u0131nda test edip Tweet sahibini ne oranda do\u011fru tahmin edebiliyor ona bakaca\u011f\u0131z. Test i\u00e7in metrik olarak \"Accuracy Score\" kullanaca\u011f\u0131z. Bu metri\u011fin hesaplanmas\u0131 \u015fu \u015fekilde yap\u0131l\u0131r:\n\n\\begin{equation}\n\\text{Accuracy Score} = \\frac{\\text{Do\u011fru Tahminlerin Say\u0131s\u0131}}{\\text{Toplam Tahminlerin Say\u0131s\u0131}}\n\\end{equation}\n\n\n```python\nclassifier = LogisticRegression(solver=\"newton-cg\", C=5, penalty=\"l2\", multi_class=\"multinomial\", max_iter=1000)\nmodel = classifier.fit(X_train, Y_train)\n```\n\n\n```python\npredictions = model.predict(X_test)\naccuracy = accuracy_score(Y_test, predictions, normalize=True)\nprint(\"Modelimizin do\u011frulu\u011fu yakla\u015f\u0131k olarak {}% oran\u0131ndad\u0131r.\".format(round(accuracy, 2) * 100))\n```\n\n    Modelimizin do\u011frulu\u011fu yakla\u015f\u0131k olarak 89.0% oran\u0131ndad\u0131r.\n\n\n# 6. Sonu\u00e7\n\n### Bu projede 04.01.2019 tarihinden bu yana (27.07.2020) iki pop\u00fcler politik lider taraf\u0131ndan at\u0131lan Twitter g\u00f6nderilerini inceledik. Son a\u015famada ise metin s\u0131n\u0131fland\u0131rma i\u015flemlerinde s\u0131k\u00e7a kullan\u0131lan Lojistik Regresyon modelimizi e\u011fittik ve 89% oran\u0131nda do\u011fru tahminler elde ettik.\n", "meta": {"hexsha": "481b23aef67ae612703fe56f1e506ec45b8fabb1", "size": 303006, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "bu_tweet_kimin.ipynb", "max_stars_repo_name": "dilarakarabey/bu-tweet-kimin", "max_stars_repo_head_hexsha": "9bf2ec1789089684457395f351e8d1cc75c9b692", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-28T18:36:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T07:50:17.000Z", "max_issues_repo_path": "bu_tweet_kimin.ipynb", "max_issues_repo_name": "dilarakarabey/bu-tweet-kimin", "max_issues_repo_head_hexsha": "9bf2ec1789089684457395f351e8d1cc75c9b692", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bu_tweet_kimin.ipynb", "max_forks_repo_name": "dilarakarabey/bu-tweet-kimin", "max_forks_repo_head_hexsha": "9bf2ec1789089684457395f351e8d1cc75c9b692", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-30T19:06:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-30T19:06:15.000Z", "avg_line_length": 397.6456692913, "max_line_length": 142300, "alphanum_fraction": 0.9282192432, "converted": true, "num_tokens": 7450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.09138210492306811, "lm_q1q2_score": 0.03791432985906019}}
{"text": "# Digital agro \n\n# Sensitivity analysis of models\n\n# Seminar - 24.04.2020\n\n\n\n\n\n### The scheme and main blocks of the plant growth model\n\n\n\n\n## git clone \n\n\n```python\n!git clone https://github.com/mishagrol/Seminar_Sobol.git\n```\n\n    fatal: destination path 'Seminar_Sobol' already exists and is not an empty directory.\n\n\n\n```python\n!cp -r ./Seminar_Sobol/* .\n```\n\n\n```python\n!ls\n```\n\n    '01 Getting Started with PCSE.ipynb'   README.md\n     batch_output.png\t\t       readme.rst\n     data\t\t\t\t       S1_estimates.npy\n     dataproviders.py\t\t       sample_data\n     default.profraw\t\t       Seminar_24_04_2020_DA.png\n     fishery.py\t\t\t       Seminar_24_04.ipynb\n     head_weather_csv.txt\t\t       Seminar_Sobol\n     HPC.jpg\t\t\t       sensitivity_NPK.py\n     img\t\t\t\t       Sobol_SA.txt\n     indexevolution.png\t\t       Sobol_seq_24_04_2020_DA.png\n     LICENSE\t\t\t       soybean-000-2015.csv\n     monica.png\t\t\t       spring-barley-2012.csv\n     moscow_full_weather.csv\t       start_notebook.bat\n     PCSE_SA.py\t\t\t       ST_estimates.npy\n     Pipeline.png\t\t\t       sugar-beet-2011.csv\n     py3_pcse.yml\t\t\t       sugar-beet-2014.csv\n     __pycache__\t\t\t       sugar-beet-2017.csv\n     quazi-random-sobol-etc.gif\t       tail_weather_csv.txt\n     Radial_All_Crops_final.eps\t       weather_full.csv\n     Radial_all_crops.png\t\t       weather_generator.sh\n    'Radial Convergence Plots.ipynb'       WOFOS.jpg\n     RadialPlot.py\t\t\t       wur-logo.txt\n     rankingevolution.png\n\n\n# Running PCSE/WOFOST with custom input dat\u0444\n\nThis Jupyter notebook will show you how to read inputs from files for running PCSE/WOFOST.\n\nthanks to **Allard de Wit**\n\n**Prerequisites for running this notebook**\n\nSeveral packages need to be installed for running PCSE/WOFOST:\n\n  1. `PCSE` and its dependencies. See the [PCSE user guide](http://pcse.readthedocs.io/en/stable/installing.html) for more information;\n  2. The `pandas` module for processing and storing WOFOST output;\n  3. The `matplotlib` module for generating charts\n\n\n\n\n\n## Introduction\n\nFor running PCSE/WOFOST (and PCSE models in general) with your own data sources you need three different types of inputs:\n\n 1. Model parameters that parameterize the different model components. These parameters usually consist of a set of crop parameters (or multiple sets in case of crop rotations), a set of soil parameters and a set of site parameters. The latter provide ancillary parameters that are specific for a location, for example the initial amount of moisture in the soil.\n 2. Driving variables represented by weather data which can be derived from various sources.\n 3. Agromanagement actions which specify the farm activities that will take place on the field that is simulated by PCSE.\n\nFor this example we will run a simulation for sugar beet in Wageningen (Netherlands) and we will read the input data step by step from several different sources instead of using the pre-configured start_wofost() script. For the example we will assume that data files are in the `data` directory within the directory where this notebook is located. This will be the case if you downloaded the notebooks from github.\n\n## Importing the relevant modules\n\n\n\n```python\n!pip install pcse\n```\n\n    Requirement already satisfied: pcse in /usr/local/lib/python3.6/dist-packages (5.4.2)\n    Requirement already satisfied: numpy>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from pcse) (1.18.2)\n    Requirement already satisfied: pandas>=0.20 in /usr/local/lib/python3.6/dist-packages (from pcse) (1.0.3)\n    Requirement already satisfied: traitlets-pcse==5.0.0.dev in /usr/local/lib/python3.6/dist-packages (from pcse) (5.0.0.dev0)\n    Requirement already satisfied: xlrd>=0.9.3 in /usr/local/lib/python3.6/dist-packages (from pcse) (1.1.0)\n    Requirement already satisfied: SQLAlchemy>=0.8.0 in /usr/local/lib/python3.6/dist-packages (from pcse) (1.3.16)\n    Requirement already satisfied: PyYAML>=3.11 in /usr/local/lib/python3.6/dist-packages (from pcse) (3.13)\n    Requirement already satisfied: xlwt>=1.0.0 in /usr/local/lib/python3.6/dist-packages (from pcse) (1.3.0)\n    Requirement already satisfied: requests>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from pcse) (2.21.0)\n    Requirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.20->pcse) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.20->pcse) (2018.9)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.6/dist-packages (from traitlets-pcse==5.0.0.dev->pcse) (4.4.2)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from traitlets-pcse==5.0.0.dev->pcse) (1.12.0)\n    Requirement already satisfied: ipython-genutils in /usr/local/lib/python3.6/dist-packages (from traitlets-pcse==5.0.0.dev->pcse) (0.2.0)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.0.0->pcse) (3.0.4)\n    Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests>=2.0.0->pcse) (1.24.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests>=2.0.0->pcse) (2020.4.5.1)\n    Requirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.0.0->pcse) (2.8)\n\n\n\n```python\n%matplotlib inline\nimport sys, os\nimport matplotlib\nmatplotlib.style.use(\"ggplot\")\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport yaml\nimport numpy as np\n\ndata_dir = os.path.join(os.getcwd(), \"data\")\nimport pcse\nprint(\"This notebook was built with:\")\nprint(\"python version: %s \" % sys.version)\nprint(\"PCSE version: %s\" %  pcse.__version__)\n```\n\n    This notebook was built with:\n    python version: 3.6.9 (default, Nov  7 2019, 10:44:02) \n    [GCC 8.3.0] \n    PCSE version: 5.4.2\n\n\n## Reading model parameters\n### Crop parameters\n\nThe crop parameters consist of parameter names and the corresponding parameter values that are needed to parameterize the components of the crop simulation model. These are crop-specific values regarding phenology, assimilation, respiration, biomass partitioning, etc. The parameter file for sugar beet is taken from the crop files in the WOFOST Control Centre.\n\nAs many crop models in Wageningen were written in FORTRAN, the crop parameters for many models in Wageningen are often provided in the CABO format that could be read with the TTUTIL FORTRAN library. This CABO format will be gradually phased out and PCSE will move to a new format based on YAML, see [here for an example](https://github.com/ajwdewit/WOFOST_crop_parameters/blob/master/wheat.yaml). However, PCSE tries to be backward compatible as much as possible and provides the `CABOFileReader` for reading parameter files in CABO format. The `CABOFileReader` returns a dictionary with the parameter name/value pairs:\n\n\n```python\nfrom pcse.fileinput import CABOFileReader\ncropfile = os.path.join(data_dir, 'crop', 'SUG0601.crop')\ncropdata = CABOFileReader(cropfile)\n```\n\n\n```python\n# Number of parameters for our crop \nlen(cropdata)\n```\n\n\n\n\n    63\n\n\n\n\n```python\n#cropdata\n!ls ./data/crop\n```\n\n    lintul3_springwheat.crop  MAG201.CAB  POT701.CAB  SUG0601.CAB  SUG0601.crop\n\n\n### Soil parameters\nThe soildata dictionary provides the parameter name/value pairs related to the soil type and soil physical properties. The number of parameters is variable depending on the soil water balance type that is used for the simulation. For this example, we will use the water balance for freely draining soils and use the soil file for medium fine sand: `ec3.soil`. This file is also taken from the soil files in the [WOFOST Control Centre](http://www.wageningenur.nl/wofost).\n\n\n```python\nsoilfile = os.path.join(data_dir, 'soil', 'ec3.soil')\nsoildata = CABOFileReader(soilfile)\n```\n\n\n```python\nlen(soildata)\n```\n\n\n\n\n    16\n\n\n\n\n```python\n#soildata\n```\n\n### Site parameters\n\nThe site parameters provide ancillary parameters that are not related to the crop or the soil. Examples are the initial conditions of the water balance such as the initial soil moisture content (WAV) and the initial and maximum surface storage (SSI, SSMAX). Also the atmospheric $CO_{2}$ \nconcentration is a typical site parameter. For the moment, we can define these parameters directly on the Python commandline as a simple python dictionary. However, it is more convenient to use the `WOFOST71SiteDataProvider` that documents the site parameters and provides sensible defaults:\n\n\n```python\nfrom pcse.util import WOFOST71SiteDataProvider\nsitedata = WOFOST71SiteDataProvider(WAV=100, CO2=360)\nprint(sitedata)\n```\n\n    {'IFUNRN': 0, 'NOTINF': 0, 'SSI': 0.0, 'SSMAX': 0.0, 'WAV': 100.0, 'SMLIM': 0.4, 'CO2': 360.0}\n\n\n### Packaging all parameters\nFinally, we need to pack the different sets of parameters into one variable using the `ParameterProvider`. This is needed because PCSE expects one variable that contains all parameter values. Using this approach has the additional advantage that parameter value can be easily overridden in case of running multiple simulations with slightly different parameter values:\n\n\n```python\nfrom pcse.base import ParameterProvider\nparameters = ParameterProvider(cropdata=cropdata, soildata=soildata, sitedata=sitedata)\n```\n\n## Agromanagement\nThe agromanagement inputs provide the start date of the agricultural campaign, the start_date/start_type of the crop simulation, the end_date/end_type of the crop simulation and the maximum duration of the crop simulation. The latter is included to avoid unrealistically long simulations for example as a results of a too high temperature sum requirement.\n\nThe agromanagement inputs are defined with a special syntax called [YAML](http://yaml.org/) which allows to easily create more complex structures which is needed for defining the agromanagement. The agromanagement file for sugar beet in Wageningen `sugarbeet_calendar.agro` can be read with the `YAMLAgroManagementReader`:\n\n\n```python\nfrom pcse.fileinput import YAMLAgroManagementReader\n#crop rotation for Moscow region\n#agromanagement_file = os.path.join(data_dir, 'agro', 'sugarbeet_calendar_Moscow_short.agro')\nagromanagement_file = os.path.join(data_dir, 'agro', 'sugarbeet_calendar.agro')\nagromanagement = YAMLAgroManagementReader(agromanagement_file)\nprint(agromanagement)\n```\n\n    !!python/object/new:pcse.fileinput.yaml_agro_loader.YAMLAgroManagementReader\n    listitems:\n    - 2006-01-01:\n        CropCalendar:\n          crop_end_date: 2006-10-20\n          crop_end_type: harvest\n          crop_name: sugar-beet\n          crop_start_date: 2006-04-05\n          crop_start_type: emergence\n          max_duration: 300\n          variety_name: sugar-beet-601\n        StateEvents: null\n        TimedEvents: null\n    \n\n\nWe can create a crop rotation in the model\n\n\n\n```python\nK_kg = 60\nP_kg = 60\nN_kg = 120\nyear_date=2019\nyaml_agro = f\"\"\"\n- {year_date}-06-01:\n    CropCalendar:\n        crop_name: 'sugar-beet'\n        variety_name: 'sugar-beet-601'\n        crop_start_date: {year_date}-06-02\n        crop_start_type: emergence\n        crop_end_date: {year_date}-10-15\n        crop_end_type: harvest\n        max_duration: 300\n    TimedEvents:\n    -   event_signal: apply_npk\n        name:  Timed N/P/K application table\n        comment: All fertilizer amounts in kg/ha\n        events_table:\n        - {year_date}-06-22: {{N_amount : {N_kg}, P_amount: {P_kg}, K_amount: {K_kg}}}\n    StateEvents: null\n\"\"\"\n#agromanagement = yaml.safe_load(yaml_agro)\nprint(yaml_agro)\n```\n\n    \n    - 2019-06-01:\n        CropCalendar:\n            crop_name: 'sugar-beet'\n            variety_name: 'sugar-beet-601'\n            crop_start_date: 2019-06-02\n            crop_start_type: emergence\n            crop_end_date: 2019-10-15\n            crop_end_type: harvest\n            max_duration: 300\n        TimedEvents:\n        -   event_signal: apply_npk\n            name:  Timed N/P/K application table\n            comment: All fertilizer amounts in kg/ha\n            events_table:\n            - 2019-06-22: {N_amount : 120, P_amount: 60, K_amount: 60}\n        StateEvents: null\n    \n\n\n## Daily weather observations\nDaily weather variables are needed for running the simulation. There are several data providers in PCSE for reading weather data, see the section on [weather data providers](http://pcse.readthedocs.io/en/stable/reference_guide.html#weather-data-providers) to get an overview.\n\nFor this example we will use weather data from an excel file which provides daily weather data for Wageningen for the period 2004 to 2008. We will read the data from the file using the ExcelWeatherDataProvider:\n\n### NASA Weather Data Provider from NASA [DataBase](https://power.larc.nasa.gov/)\n\n\n```python\n#NASA Weather system\nfrom pcse.db import NASAPowerWeatherDataProvider\n```\n\n    Platform not recognized, using system temp directory for PCSE settings.\n    Platform not recognized, using system temp directory for PCSE settings.\n\n\n\n```python\n#export weather to list\nmoscow_weather = NASAPowerWeatherDataProvider(55.45, 37.36)\nprint(moscow_weather)\n```\n\nWeather loader for __NH__ example\n\n\n```python\nfrom pcse.fileinput import ExcelWeatherDataProvider\nweatherfile = os.path.join(data_dir, 'meteo', 'nl1.xlsx')\nwdp = ExcelWeatherDataProvider(weatherfile)\nprint(wdp)\n```\n\n    Weather data provided by: ExcelWeatherDataProvider\n    --------Description---------\n    Weather data for:\n    Country: Netherlands\n    Station: Wageningen, Location Haarweg\n    Description: Observed data from Station Haarweg in Wageningen\n    Source: Meteorology and Air Quality Group, Wageningen University\n    Contact: Peter Uithol\n    ----Site characteristics----\n    Elevation:    7.0\n    Latitude:  51.970\n    Longitude:  5.670\n    Data available for 2004-01-02 - 2008-12-31\n    Number of missing days: 0\n    \n\n\n## Importing, initializing and running a PCSE model\n\nInternally, PCSE uses a simulation engine to run a crop simulation. This engine takes a configuration file that specifies the components for the crop, the soil and the agromanagement that need to be used for the simulation. So any PCSE model can be started by importing the engine and initializing it with a given configuration file and the corresponding parameters, weather data and agromanagement.\n\nHowever, as many users of PCSE only need a particular configuration (for example the WOFOST model for potential production), preconfigured Engines are provided in `pcse.models`. For the sugarbeet example we will import the WOFOST model for water-limited simulation under freely draining soil conditions:\n\n\n```python\nfrom pcse.models import Wofost71_WLP_FD\n#wofsim = Wofost71_WLP_FD(parameters, moscow_weather, agromanagement)\n```\n\n\n```python\nfrom pcse.models import Wofost71_WLP_FD\nwofsim = Wofost71_WLP_FD(parameters, wdp, agromanagement)\nwofsim.run_till_terminate()\ndf_results = pd.DataFrame(wofsim.get_output())\ndf_results = df_results.set_index(\"day\")\ndf_results.tail()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>DVS</th>\n      <th>LAI</th>\n      <th>TAGP</th>\n      <th>TWSO</th>\n      <th>TWLV</th>\n      <th>TWST</th>\n      <th>TWRT</th>\n      <th>TRA</th>\n      <th>RD</th>\n      <th>SM</th>\n      <th>WWLOW</th>\n    </tr>\n    <tr>\n      <th>day</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2006-10-16</th>\n      <td>2.0</td>\n      <td>1.048787</td>\n      <td>21557.705173</td>\n      <td>14410.185356</td>\n      <td>3408.824045</td>\n      <td>3738.695772</td>\n      <td>2805.686837</td>\n      <td>0.052878</td>\n      <td>120.0</td>\n      <td>0.283340</td>\n      <td>34.000845</td>\n    </tr>\n    <tr>\n      <th>2006-10-17</th>\n      <td>2.0</td>\n      <td>1.055901</td>\n      <td>21628.846417</td>\n      <td>14474.212476</td>\n      <td>3412.381108</td>\n      <td>3742.252834</td>\n      <td>2807.138699</td>\n      <td>0.030516</td>\n      <td>120.0</td>\n      <td>0.282876</td>\n      <td>33.945161</td>\n    </tr>\n    <tr>\n      <th>2006-10-18</th>\n      <td>2.0</td>\n      <td>1.049414</td>\n      <td>21658.771700</td>\n      <td>14501.145230</td>\n      <td>3413.877372</td>\n      <td>3743.749098</td>\n      <td>2807.749419</td>\n      <td>0.030184</td>\n      <td>120.0</td>\n      <td>0.284605</td>\n      <td>34.152545</td>\n    </tr>\n    <tr>\n      <th>2006-10-19</th>\n      <td>2.0</td>\n      <td>1.052133</td>\n      <td>21685.964928</td>\n      <td>14525.619135</td>\n      <td>3415.237033</td>\n      <td>3745.108759</td>\n      <td>2808.304383</td>\n      <td>0.043053</td>\n      <td>120.0</td>\n      <td>0.284840</td>\n      <td>34.180768</td>\n    </tr>\n    <tr>\n      <th>2006-10-20</th>\n      <td>2.0</td>\n      <td>1.043584</td>\n      <td>21717.141971</td>\n      <td>14553.678474</td>\n      <td>3416.795885</td>\n      <td>3746.667611</td>\n      <td>2808.940650</td>\n      <td>0.039061</td>\n      <td>120.0</td>\n      <td>0.284271</td>\n      <td>34.112520</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nWe can then run the simulation and retrieve the time series of daily simulation output using the get_output() method on the WOFOST object. Finally, we convert the simulation results to a pandas dataframe:\n\n\n```python\nsummary_output = wofsim.get_summary_output()\n```\n\n\n```python\nwofsim.get_summary_output()\n```\n\n\n\n\n    [{'CTRAT': 29.87844231452199,\n      'DOA': datetime.date(2006, 6, 15),\n      'DOE': datetime.date(2006, 4, 5),\n      'DOH': datetime.date(2006, 10, 20),\n      'DOM': datetime.date(2006, 9, 17),\n      'DOS': None,\n      'DOV': None,\n      'DVS': 2.0,\n      'LAIMAX': 5.367243094787345,\n      'RD': 120.0,\n      'TAGP': 21717.14197118098,\n      'TWLV': 3416.7958853006903,\n      'TWRT': 2808.940649509448,\n      'TWSO': 14553.678474455044,\n      'TWST': 3746.6676114252446}]\n\n\n\n\n```python\nmsg = \"Reached maturity at {DOM} with total biomass {TAGP} kg/ha \"\\\n\"and a yield of {TWSO} kg/ha.\"\nprint(msg.format(**summary_output[0]))\n```\n\n    Reached maturity at 2006-09-17 with total biomass 21717.14197118098 kg/ha and a yield of 14553.678474455044 kg/ha.\n\n\n# Sensitivity analysis\n\n\n```python\n!pip install SALib\n```\n\n    Collecting SALib\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/f7/33/cee4d64f7c40f33c08cf5ef5c9b1fb5e51f194b5deceefb5567112800b70/SALib-1.3.11.tar.gz (856kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 860kB 3.4MB/s \n    \u001b[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from SALib) (1.18.2)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from SALib) (1.4.1)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.6/dist-packages (from SALib) (3.2.1)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from SALib) (1.0.3)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->SALib) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib->SALib) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->SALib) (1.2.0)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->SALib) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas->SALib) (2018.9)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from cycler>=0.10->matplotlib->SALib) (1.12.0)\n    Building wheels for collected packages: SALib\n      Building wheel for SALib (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for SALib: filename=SALib-1.3.11-py2.py3-none-any.whl size=729664 sha256=31127e559769320d04b8de314c945335f12c6529a8e15594dc56bedfa989bb56\n      Stored in directory: /root/.cache/pip/wheels/62/ed/f9/a0b98754ffb2191b98324b96cbbeb1bd5d9598b39ab996b429\n    Successfully built SALib\n    Installing collected packages: SALib\n    Successfully installed SALib-1.3.11\n\n\n\n```python\nfrom SALib.sample import saltelli\nfrom SALib.analyze import sobol\nfrom SALib.test_functions import Ishigami\nimport numpy as np\n```\n\n__Docs [SALib](https://salib.readthedocs.io/en/latest/#)__\n\nIn this example, we will perform a Sobol\u2019 sensitivity analysis of the _Ishigami_ function, shown below. The _Ishigami_ function is commonly used to test uncertainty and sensitivity analysis methods because it exhibits strong nonlinearity and nonmonotonicity.\n\n$f(x)=\\sin \\left(x_{1}\\right)+ \\text{a}\\, \\operatorname{sin}^{2}\\left(x_{2}\\right)+ \\text{b}\\,  x_{3}^{4} \\sin \\left(x_{1}\\right)$\n\n\n```python\nproblem = {\n  'num_vars': 3,\n  'names': ['x1', 'x2', 'x3'],\n  'bounds': [[-np.pi, np.pi]]*3\n}\n```\n\n\n```python\n# Generate samples\nparam_values = saltelli.sample(problem, 10, calc_second_order=True)\nparam_values.shape\n```\n\n\n\n\n    (80, 3)\n\n\n\nHere, `param_values` is a NumPy matrix. If we run `param_values.shape`, we see that the matrix is **8000 by 3**. The Saltelli sampler generated 8000 samples. The Saltelli sampler generates $N\u2217(2D+2)$ samples, where in this example $N$ is 1000 (the argument we supplied) and $D$ is 3 (the number of model inputs). The keyword argument `calc_second_order=False` will exclude second-order indices, resulting in a smaller sample matrix with $N\u2217(D+2)$ rows instead.\n\n\n\n```python\n# Run model (example)\nY = Ishigami.evaluate(param_values)\n\n# Perform analysis\nSi = sobol.analyze(problem, Y, print_to_console=True)\n# Returns a dictionary with keys 'S1', 'S1_conf', 'ST', and 'ST_conf'\n# (first and total-order indices with bootstrap confidence intervals)\nT_Si, first_Si, (idx, second_Si) = sobol.Si_to_pandas_dict(Si)\n```\n\n    Parameter S1 S1_conf ST ST_conf\n    x1 -0.203434 0.600917 1.345837 1.837833\n    x2 0.838328 0.552777 0.716922 0.573149\n    x3 -0.592087 0.356414 0.459872 0.329910\n    \n    Parameter_1 Parameter_2 S2 S2_conf\n    x1 x2 0.208665 1.084091\n    x1 x3 1.165212 0.855712\n    x2 x3 0.268558 0.730003\n\n\nConsider the model output as\n\\begin{eqnarray*}\nY=f(X)=f\\left(X_{1}, \\ldots, X_{p}\\right),\n\\end{eqnarray*}\nwhere $f$ in our case part of agro-model simulator, $X$ are $p$ varied input parameters and $Y$ is the predicted output. Following the techniques by Sobol we represent the multi-variate random function $f$ using Hoeffding decomposition:\n\\begin{equation}\nf(X_1,\\dots,X_p) = f_0 + \\sum_i^p f_i + \\sum_i^p\\sum_{j>i}^p f_{ij} + \\dots + f_{1\\dots p},\n\\end{equation}\nwhere $f_0$ is a constant term, $f_i = f_i(X_i)$ denotes main effects, $f_{ij} = f_{ij}(X_i, X_j)$ and others describe higher-order interactions. These terms can be written as\n\\begin{equation*}\n\\begin{split}\nf_0 &= E(Y),\\\\\nf_i &= E_{X_{\\sim i}}(Y | X_i) - E(Y),\\\\\nf_{ij} &= E_{X_{\\sim ij}}(Y | X_i, X_j) - f_i - f_j - f_0,\\\\\n\\dots\n\\end{split}\n\\end{equation*}\nwhere $E$ is mathematical expectation and $X_{\\sim i}$ denotes all parameters except $i^\\text{th}$. Under the assumption that the input parameters are independent, total variance $V(Y)$ of the crop yield can be decomposed as follows:\n\\begin{equation*}\nV(Y) = \\sum_i^p V_i + \\sum_i^p\\sum_{j>i}^p V_{ij} + \\dots + V_{12\\dots p},\n\\end{equation*}\nwhere partial variances are\n\\begin{equation*}\n\\begin{split}\nV_i &= V[f_i(X_i)] = V_{X_i}\\left[E_{X_{\\sim i}}(Y | X_i)\\right],\\\\\nV_{ij} &= V[f_{ij}(X_i,X_j)] = V_{X_iX_j}\\left[E_{X_{\\sim ij}}(Y | X_i, X_j)\\right] - V_i - V_j,\\\\\n\\dots\n\\end{split}\n\\end{equation*}\n\n## Sobol index (first order, second order, total index)\n\nThis way, sensitivity indices (SI) can be introduced as \n\\begin{equation}\n\\Large\nS_i = \\frac{V_i}{V(Y)},~S_{ij} = \\frac{V_{ij}}{V(Y)},~\\dots\n\\end{equation}\nIn order to incorporate all of the interactions for a particular parameter, one can compute the total effect index:\n\\begin{equation}\nS_{T_i} = \\frac{E_{X_{\\sim i}}\\left[V_{X_i}(Y|X_{\\sim i})\\right]}{V(Y)} = 1 - \\frac{V_{X_{\\sim i}}\\left[E_{X_i}(Y | X_{\\sim i})\\right]}{V(Y)}\n\\end{equation}\n\n\nFrom this assumption we can conclude:\n\\begin{equation}\n\\Large\n0 \\leq S_i \\leq S_{T_i} \\leq 1\n\\end{equation}\n\n## Sobol\u2019 Sequences versus Random numbers and regular grid\n\n\n\n\n## Modern Quasi-Random Sequences\n\n\n\n\n\nMore -\n* [Wiki](https://en.wikipedia.org/wiki/Sobol_sequence)\n* [Habr](https://habr.com/ru/post/440892/)\n* Feature selection [Skoltech ML 2020](https://github.com/adasegroup/ML2020_lectures/blob/master/lecture9/Lecture_9_Model_Feature_Selection_Sensitivity.pdf)\n\n# Sensitivity analysis of WOFOST model \n\n\n\n## Install modules \n\n\n```python\nfrom SALib.sample import saltelli\nfrom SALib.analyze import sobol\nfrom SALib.test_functions import Ishigami\nimport numpy as np\nimport pandas as pd\n```\n\n## Parameters\n\n\n```python\nNPK = {\n    'num_vars':3,\n    'names':['N_kg', 'P_kg', 'K_kg'],\n    'bounds':[[30., 60.],\n              [60., 90.],\n              [100., 130.]]\n}\n```\n\n\n```python\nSoil_parameters = {\n  'num_vars':5,\n    'names':['SMV', 'SMFCF', 'SM0', 'CRAIRC', 'K0'],\n    'bounds':[[0.7, 1.3],\n              [0.1, 0.5],\n              [0.2, 0.6],\n             [0.04, 0.08],\n             [22.5, 27.5]]}\n```\n\n## Generate input parameters\n\n\n\n\n\n```python\nparam_values = saltelli.sample(Soil_parameters, 10)\n```\n\n$n = N \\times (D \\times 2 +2)$\n\n\n```python\nparam_values.shape\n```\n\n\n\n\n    (120, 5)\n\n\n\n## Loop for yield prediction\n\n\n```python\nfrom pcse.fileinput import YAMLAgroManagementReader\nagromanagement_file = os.path.join(data_dir, 'agro', './sugarbeet_calendar.agro')\nagromanagement = YAMLAgroManagementReader(agromanagement_file)\n#print(agromanagement)\nSoil_parameters = {\n  'num_vars':5,\n    'names':['SMV', 'SMFCF', 'SM0', 'CRAIRC', 'K0'],\n    'bounds':[[0.7, 1.3],\n              [0.1, 0.5],\n              [0.2, 0.6],\n             [0.04, 0.08],\n             [22.5, 27.5]]}\nparam_values = saltelli.sample(Soil_parameters, N=10, calc_second_order=True)\n```\n\nSoil parameters in [PCSE model](https://pcse.readthedocs.io/en/stable/code.html?highlight=K0#pcse.soil.WaterbalanceFD) \n\n\n```python\ndef sensitivity_soil(soil_parameters):\n    SMV, SMFCF, SM0, CRAIRC, K0 = soil_parameters \n    soildata['SMV'] = SMV\n    soildata['SMFCF'] = SMFCF\n    soildata['SM0'] = SM0\n    soildata['CRAIRC'] = CRAIRC\n    soildata['K0'] = K0\n    parameters = ParameterProvider(cropdata=cropdata, soildata=soildata, sitedata=sitedata)\n    wofsim = Wofost71_WLP_FD(parameters, wdp, agromanagement)\n    wofsim.run_till_terminate()\n    #df_results = pd.DataFrame(wofsim.get_output())\n    #df_results = df_results.set_index(\"day\")\n    #df_results.tail()\n    summary_output = wofsim.get_summary_output()\n    yield_list.append(summary_output[0]['TWSO'])\n```\n\n\n```python\n%%time\nyield_list = []\nparam_values = saltelli.sample(Soil_parameters, 10, calc_second_order=True)\nfor st in range(len(param_values)):\n    sensitivity_soil(param_values[st])\n    print('.', end='')\n```\n\n    ........................................................................................................................CPU times: user 1min 14s, sys: 291 ms, total: 1min 15s\n    Wall time: 1min 15s\n\n\n\n```python\nnp_yield = np.array(yield_list)\nSi = sobol.analyze(Soil_parameters, np_yield, print_to_console=False)\n```\n\n\n```python\nSi_dict = dict(Si) \nSi_df = pd.DataFrame()\nSi_df = Si_df.append(pd.Series(Si_dict['S1']), ignore_index=True)\nSi_df = Si_df.append(pd.Series(Si_dict['ST']), ignore_index=True)\nSi_df = Si_df.append(pd.Series(Si_dict['S1_conf']), ignore_index=True)\nSi_df = Si_df.append(pd.Series(Si_dict['ST_conf']), ignore_index=True)\nSi_df = Si_df.T\nSi_df.columns = ['Si', 'ST', 'Si_conf', 'ST_conf']\nSi_df.rename(index={0:'SMV',1:'SMFCF', 2:'SM0', 3:'CRAIRC', 4:'K0'}, inplace=True)\nSi_df\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Si</th>\n      <th>ST</th>\n      <th>Si_conf</th>\n      <th>ST_conf</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>SMV</th>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>SMFCF</th>\n      <td>-0.125075</td>\n      <td>0.433048</td>\n      <td>0.865365</td>\n      <td>0.831111</td>\n    </tr>\n    <tr>\n      <th>SM0</th>\n      <td>0.256621</td>\n      <td>0.377433</td>\n      <td>0.498367</td>\n      <td>0.507346</td>\n    </tr>\n    <tr>\n      <th>CRAIRC</th>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>K0</th>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nIs it ok?\n\n\n\\begin{equation}\n\\Large\n0 \\leq S_i \\leq S_{T_i} \\leq 1\n\\end{equation}\n\n## Visualizing simulation results\n\nFinally, we can generate some figures of WOFOST variables such as the development (DVS), total biomass (TAGP), leaf area index (LAI) and root-zone soil moisture (SM) using the MatPlotLib plotting package:\n\n\n```python\nfig, axes = plt.subplots(nrows=2, ncols=2, figsize=(12,10))\nfor var, ax in zip([\"DVS\", \"TWSO\", \"LAI\", \"SM\"], axes.flatten()):\n    ax.plot_date(df_results.index, df_results[var], 'b-')\n    ax.set_title(var)\nfig.autofmt_xdate()\n```\n\n# Visualization for sensitivity analysis\n\nPlots by [Water programming group](https://waterprogramming.wordpress.com/2019/08/27/a-python-implementation-of-grouped-radial-convergence-plots-to-visualize-sobol-sensitivity-analysis-results/)\n\nHow to repeat: [Repo of SampleVIS](https://github.com/charlesrouge/SampleVis)\n\n\n```python\nimport numpy as np\nfrom SALib.analyze import sobol\nfrom SALib.sample import saltelli\nfrom fishery import fish_game\nimport matplotlib.pyplot as plt\nimport itertools\nimport math\n```\n\n### Why number of samples is important?\n\n\n```python\n# Set up dictionary with system parameters\nproblem = {\n  'num_vars': 6,\n  'names': ['a', 'b', 'c','h',\n            'K','m'],\n  'bounds': [[ 0.002, 2],\n             [0.005, 1],\n             [0.2, 1],\n             [0.001, 1],\n             [100, 5000],\n             [0.1, 1.5]]\n}\n\n# Array with n's to use\nnsamples = np.arange(50, 500, 50)\n\n# Arrays to store the index estimates\nS1_estimates = np.zeros([problem['num_vars'],len(nsamples)])\nST_estimates = np.zeros([problem['num_vars'],len(nsamples)])\n\n# Loop through all n values, create sample, evaluate model and estimate S1 & ST\nfor i in range(len(nsamples)):\n    print('n= '+ str(nsamples[i]))\n    # Generate samples\n    sampleset = saltelli.sample(problem, nsamples[i],calc_second_order=False)\n    # Run model for all samples\n    output = [fish_game(*sampleset[j,:]) for j in range(len(sampleset))]\n    # Perform analysis\n    results = sobol.analyze(problem, np.asarray(output), calc_second_order=False,print_to_console=False)\n    # Store estimates\n    ST_estimates[:,i]=results['ST']\n    S1_estimates[:,i]=results['S1']\n\nnp.save('ST_estimates.npy', ST_estimates)\nnp.save('S1_estimates.npy', S1_estimates)\n\nS1_estimates = np.load('S1_estimates.npy')\nST_estimates = np.load('ST_estimates.npy')\n\n# Generate figure showing evolution of indices\nfig =  plt.figure(figsize=(18,9))\nax1 = fig.add_subplot(1,2,1)\nhandles = []\nfor j in range(problem['num_vars']):\n    handles += ax1.plot(nsamples, S1_estimates[j,:], linewidth=5)\nax1.set_title('Evolution of S1 index estimates', fontsize=20)\nax1.set_ylabel('S1', fontsize=18)\nax1.set_xlabel('Number of samples (n)', fontsize=18)\nax1.tick_params(axis='both', which='major', labelsize=14)\nax2 = fig.add_subplot(1,2,2)\nfor j in range(problem['num_vars']):\n    ax2.plot(nsamples, ST_estimates[j,:], linewidth=5)\nax2.set_title('Evolution of ST index estimates', fontsize=20)\nax2.set_ylabel('ST', fontsize=18)\nax2.tick_params(axis='both', which='major', labelsize=14)\nax2.set_xlabel('Number of samples (n)', fontsize=18)\nfig.legend(handles, problem['names'], loc = 'right', fontsize=11)\nplt.show()\n#plt.savefig('indexevolution.png')\n\n# Calculate parameter rankings\nS1_ranks = np.zeros_like(S1_estimates)\nST_ranks = np.zeros_like(ST_estimates)\nfor i in range(len(nsamples)):\n    orderS1 = np.argsort(S1_estimates[:,i])\n    orderST = np.argsort(ST_estimates[:,i])\n    S1_ranks[:,i] = orderS1.argsort()\n    ST_ranks[:,i] = orderST.argsort()\n    \n# Generate figure showing evolution of ranks\nfig =  plt.figure(figsize=(18,9))\nax1 = fig.add_subplot(1,2,1)\nhandles = []\nfor j in range(problem['num_vars']):\n    handles += ax1.plot(nsamples, S1_ranks[j,:], linewidth=3)\nax1.set_title('Parameter ranking based on S1', fontsize=20)\nax1.set_ylabel('S1', fontsize=18)\nax1.set_xlabel('Number of samples (n)', fontsize=18)\nax1.set_yticklabels(np.arange(problem['num_vars']+1, 0, -1))\nax1.tick_params(axis='both', which='major', labelsize=14)\nax2 = fig.add_subplot(1,2,2)\nfor j in range(problem['num_vars']):\n    ax2.plot(nsamples, ST_ranks[j,:], linewidth=3)\nax2.set_title('Parameter ranking based on ST', fontsize=20)\nax2.set_ylabel('ST', fontsize=18)\nax2.set_yticklabels(np.arange(problem['num_vars']+1, 0, -1))\nax2.tick_params(axis='both', which='major', labelsize=14)\nax2.set_xlabel('Number of samples (n)', fontsize=18)\nfig.legend(handles, problem['names'], loc = 'right', fontsize=14)\n#plt.show()\n#plt.savefig('rankingevolution.png')\n```\n\n## Radial plot for SA\n\n\n```python\nimport numpy as np\nimport itertools\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport math\nfrom numpy import genfromtxt\nimport matplotlib.patches as mpatches\nimport matplotlib.pyplot as plt\nsns.set_style('whitegrid', {'axes_linewidth': 0, 'axes.edgecolor': 'white'})\n```\n\n    /usr/local/lib/python3.6/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.\n      import pandas.util.testing as tm\n\n\n## Plot function\n\n\n```python\ndef is_significant(value, confidence_interval, threshold=\"conf\"):\n    if threshold == \"conf\":\n        return value - abs(confidence_interval) > 0\n    else:\n        return value - abs(float(threshold)) > 0\n \ndef grouped_radial(SAresults, parameters, radSc=2.0, scaling=1, widthSc=0.5, STthick=1, varNameMult=1.3, colors=None, groups=None, gpNameMult=1.5, threshold=\"conf\"):\n    # Derived from https://github.com/calvinwhealton/SensitivityAnalysisPlots\n    fig, ax = plt.subplots(1, 1)\n    color_map = {}\n     \n    # initialize parameters and colors\n    if groups is None:\n         \n        if colors is None:\n            colors = [\"k\"]\n         \n        for i, parameter in enumerate(parameters):\n            color_map[parameter] = colors[i % len(colors)]\n    else:        \n        if colors is None:\n            colors = sns.color_palette(\"deep\", max(3, len(groups)))\n         \n        for i, key in enumerate(groups.keys()):\n            #parameters.extend(groups[key])\n             \n            for parameter in groups[key]:\n                color_map[parameter] = colors[i % len(colors)]\n     \n    n = len(parameters)\n    angles = radSc*math.pi*np.arange(0, n)/n\n    x = radSc*np.cos(angles)\n    y = radSc*np.sin(angles)\n     \n    # plot second-order indices\n    for i, j in itertools.combinations(range(n), 2):\n        #key1 = parameters[i]\n        #key2 = parameters[j]\n         \n        if is_significant(SAresults[\"S2\"][i][j], SAresults[\"S2_conf\"][i][j], threshold):\n            angle = math.atan((y[j]-y[i])/(x[j]-x[i]))\n                 \n            if y[j]-y[i] < 0:\n                angle += math.pi\n                 \n            line_hw = scaling*(max(0, SAresults[\"S2\"][i][j])**widthSc)/2\n                 \n            coords = np.empty((4, 2))\n            coords[0, 0] = x[i] - line_hw*math.sin(angle)\n            coords[1, 0] = x[i] + line_hw*math.sin(angle)\n            coords[2, 0] = x[j] + line_hw*math.sin(angle)\n            coords[3, 0] = x[j] - line_hw*math.sin(angle)\n            coords[0, 1] = y[i] + line_hw*math.cos(angle)\n            coords[1, 1] = y[i] - line_hw*math.cos(angle)\n            coords[2, 1] = y[j] - line_hw*math.cos(angle)\n            coords[3, 1] = y[j] + line_hw*math.cos(angle)\n \n            ax.add_artist(plt.Polygon(coords, color=\"0.75\"))\n         \n    # plot total order indices\n    for i, key in enumerate(parameters):\n        if is_significant(SAresults[\"ST\"][i], SAresults[\"ST_conf\"][i], threshold):\n            ax.add_artist(plt.Circle((x[i], y[i]), scaling*(SAresults[\"ST\"][i]**widthSc)/2, color='w'))\n            ax.add_artist(plt.Circle((x[i], y[i]), scaling*(SAresults[\"ST\"][i]**widthSc)/2, lw=STthick, color='0.4', fill=False))\n     \n    # plot first-order indices\n    for i, key in enumerate(parameters):\n        if is_significant(SAresults[\"S1\"][i], SAresults[\"S1_conf\"][i], threshold):\n            ax.add_artist(plt.Circle((x[i], y[i]), scaling*(SAresults[\"S1\"][i]**widthSc)/2, color='0.4'))\n            \n    # add labels\n    for i, key in enumerate(parameters):                \n        ax.text(varNameMult*x[i], varNameMult*y[i], key, ha='center', va='center',\n                rotation=angles[i]*360/(2*math.pi) - 90,\n                color=color_map[key])\n         \n    if groups is not None:\n        for i, group in enumerate(groups.keys()):\n            print(group)\n            group_angle = np.mean([angles[j] for j in range(n) if parameters[j] in groups[group]])\n             \n            ax.text(gpNameMult*radSc*math.cos(group_angle), gpNameMult*radSc*math.sin(group_angle), group, ha='center', va='center',\n                rotation=group_angle*360/(2*math.pi) - 90,\n                color=colors[i % len(colors)])\n             \n    ax.set_facecolor('white')\n    ax.set_xticks([])\n    ax.set_yticks([])\n#     ax.\n    plt.axis('equal')\n    plt.axis([-2*radSc, 2*radSc, -2*radSc, 2*radSc])\n    #plt.show()\n \n     \n    return fig\n```\n\n## Range of soil parameters\n\n\n```python\nproblem = {\n    'num_vars':6,\n    'names':['SOC', 'Sand', 'Clay', 'pH', 'CN', 'BD'],\n    'bounds':[[2.58, 6.20],\n              [0.01, 0.30],\n              [0.01, 0.30],\n              [4.6, 6.9],\n              [10.9, 12.4],\n              [900, 1350]]\n}\n```\n\n\n```python\n#names for csv files\nlist_of_csv=['soybean-000-2015.csv', 'sugar-beet-2011.csv', 'sugar-beet-2017.csv',\n'spring-barley-2012.csv', 'sugar-beet-2014.csv']\nlist_of_names=['soybean-000-2015', 'sugar-beat-2011', 'sugar-beat-2017',\n'spring-barley-2012', 'sugar-beat-2014']\nlist_of_totals=['total_SI_'+x for x in list_of_names]\nlist_of_first=['fisrt_SI_'+x for x in list_of_names]\nlist_of_second=['second_SI_'+x for x in list_of_names]\nlist_of_SI=['SI_'+x for x in list_of_names]\n```\n\n\n```python\nfor j, i in enumerate(list_of_csv):\n        all_data_csv = genfromtxt('./'+str(i), delimiter=',')\n        output = all_data_csv[:,2]\n        print(i)\n        list_of_SI[j] = sobol.analyze(problem, output, calc_second_order=True, conf_level=0.95, print_to_console=False)\n```\n\n    soybean-000-2015.csv\n    sugar-beet-2011.csv\n    sugar-beet-2017.csv\n    spring-barley-2012.csv\n    sugar-beet-2014.csv\n\n\n\n```python\ngroups={\"Soil physics\" : [\"Sand\", \"Clay\", \"BD\"],\n        \"Soil chemistry\" : [\"pH\", \"SOC\", \"CN\"]}\n \nfig = grouped_radial(list_of_SI[1], ['BD', 'Sand', 'Clay', 'pH', 'CN', 'SOC'], groups=groups, threshold=0.001)\nred_patch = mpatches.Patch(color='red', label='The red data')\nplt.title(list_of_names[3], loc='left')\n\nplt.show()\n```\n\n\n\n\n## Homework\n\nUsefull\n\n__SA and UQ__\n\n\n1) [Rhodium project](https://github.com/Project-Platypus/Rhodium.git)\n\n\n2) [SALib](https://github.com/SALib/SALib)\n\n__Model__\n\n3) [PCSE](https://pcse.readthedocs.io/en/stable/index.html)\n\n4) How to install PCSE at local machine\n    `conda env create -f` [py3_pcse.yml](https://github.com/mishagrol/Seminar_Sobol/blob/master/py3_pcse.yml)\n\n### bonus\n\n__Morris method__\n\n\nGenerate a sample using the Method of Morris\n\nThree variants of Morris' sampling for elementary effects is supported:\n\n- Vanilla Morris\n- Optimised trajectories when ``optimal_trajectories=True`` (using\n    Campolongo's enhancements from 2007 and optionally Ruano's enhancement\n    from 2012; ``local_optimization=True``)\n- Groups with optimised trajectories when ``optimal_trajectories=True`` and\n    the problem definition specifies groups (note that ``local_optimization``\n    must be ``False``)\n\nAt present, optimised trajectories is implemented using either a brute-force\napproach, which can be very slow, especially if you require more than four\ntrajectories, or a local method based which is much faster. Both methods now\nimplement working with groups of factors.\n\nNote that the number of factors makes little difference,\nbut the ratio between number of optimal trajectories and the sample size\nresults in an exponentially increasing number of scores that must be\ncomputed to find the optimal combination of trajectories.  We suggest going\nno higher than 4 from a pool of 100 samples with the brute force approach.\nWith local_optimization = True (which is default),\nit is possible to go higher than the previously suggested 4 from 100.\n\n\n\n\n```python\nimport sys\n\nfrom SALib.analyze import morris\nfrom SALib.sample.morris import sample\nfrom SALib.test_functions import Sobol_G\nfrom SALib.util import read_param_file\nfrom SALib.plotting.morris import horizontal_bar_plot, covariance_plot, \\\n    sample_histograms\nimport matplotlib.pyplot as plt\n\n#sys.path.append('../..')\n\n# Read the parameter range file and generate samples\n#problem = read_param_file('/Users/mikhailgasanov/Documents/GIT/SALib/src/SALib/test_functions/params/Sobol_G.txt')\n# or define manually without a parameter file:\nproblem = {\n 'num_vars': 8,\n 'names': ['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8'],\n 'groups': None,\n 'bounds': [[0.0, 1.0],\n            [0.0, 1.0],\n            [0.0, 1.0],\n            [0.0, 1.0],\n            [0.0, 1.0],\n            [0.0, 1.0],\n            [0.0, 1.0],\n            [0.0, 1.0]]\n}\n# Files with a 4th column for \"group name\" will be detected automatically, e.g.\n# param_file = '../../src/SALib/test_functions/params/Ishigami_groups.txt'\n\n# Generate samples\nparam_values = sample(problem, N=1000, num_levels=4,\n                      optimal_trajectories=None)\n\n# To use optimized trajectories (brute force method),\n# give an integer value for optimal_trajectories\n\n# Run the \"model\" -- this will happen offline for external models\nY = Sobol_G.evaluate(param_values)\n\n# Perform the sensitivity analysis using the model output\n# Specify which column of the output file to analyze (zero-indexed)\nSi = morris.analyze(problem, param_values, Y, conf_level=0.95,\n                    print_to_console=True,\n                    num_levels=4, num_resamples=100)\n# Returns a dictionary with keys 'mu', 'mu_star', 'sigma', and 'mu_star_conf'\n# e.g. Si['mu_star'] contains the mu* value for each parameter, in the\n# same order as the parameter file\n\nfig, (ax1, ax2) = plt.subplots(1, 2)\nhorizontal_bar_plot(ax1, Si, {}, sortby='mu_star', unit=r\"tCO$_2$/year\")\ncovariance_plot(ax2, Si, {}, unit=r\"tCO$_2$/year\")\n\nfig2 = plt.figure()\nsample_histograms(fig2, param_values, problem, {'color': 'y'})\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "03f3d11b777b84b9ef8ee040f888b3412896db8f", "size": 378722, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": ".ipynb_checkpoints/Seminar_24_04_Colab-checkpoint.ipynb", "max_stars_repo_name": "mishagrol/Seminar_Sobol", "max_stars_repo_head_hexsha": "c0500d625fc256cbe821f698feb8ee7983f7ae39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": ".ipynb_checkpoints/Seminar_24_04_Colab-checkpoint.ipynb", "max_issues_repo_name": "mishagrol/Seminar_Sobol", "max_issues_repo_head_hexsha": "c0500d625fc256cbe821f698feb8ee7983f7ae39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": ".ipynb_checkpoints/Seminar_24_04_Colab-checkpoint.ipynb", "max_forks_repo_name": "mishagrol/Seminar_Sobol", "max_forks_repo_head_hexsha": "c0500d625fc256cbe821f698feb8ee7983f7ae39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 139.853028065, "max_line_length": 109024, "alphanum_fraction": 0.8625139284, "converted": true, "num_tokens": 12864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.08151975764828964, "lm_q1q2_score": 0.03789866342866766}}
{"text": "# <span style='color:Blue'>Temple University, Physical Chemistry for Biomolecules (CHEM3405)</span>\n\n### Teaching Assistant: Rob Raddi\n\n\n \n\n\n<style>\n @import url(\"./custom/gtag.js\");\n</style>\n\n\n<style>\n @import url(\"./custom/custom.css\");\n</style>\n\n\n\n#### Textbook: Peter Atkins, Julio de Paula - Physical Chemistry for the Life Sciences\n\n\n#### <span style='color:black'>Table of Contents:</span> \n\n\n| Section # | Topic | Chapter | \n| :--- | :--- | :--: |\n| [1.](#1.)   | Microscopic systems and quantization | 9.1-9.4 |\n| [2.](#2.)   | Spartan I: Introduction to Spartan | 10.9 |\n| [3.](#3.)   | Spartan II: Particle in a Box (PIB) - Polyenes | 9.1-9.4; 10.9 |\n| [4.](#4.)   | Literature Review (Juffmann) | - |\n| [5.](#5.)   | Spartan III: Harmonic Oscillator | 9.6-9.8 |\n| [6.](#6.)   | Midterm Review #1 | 9-11 |\n| [7.](#7.)   | Spartan IV: PES of H2 & Peptide backbone dihedral scan | 10.9; 11.13; 11.17 |\n| [8.](#8.)   | Chimera I: Getting familiar with X-ray and NMR structures (MDM2) | 11.3-11.4 |\n| [9.](#9.)   | Chimera II: Calculating \u2206SASA | - |\n| [10.](#10.) | HW Review | 11 & 12 |\n| [11.](#11.) | Midterm Review #2 | 1; 11; 12 |\n| [12.](#12.) | Simbiology I: binding reactions | 12 |\n| [13.](#13.) | Simbiology II: folding intermediates | 12 |\n| [14.](#14.) | Review for Final | - |\n| [15.](#15.) | Extra | - |\n\n<!--| [2.](#2.)   |  |  |-->\n\n\n#### <span style='color:blue'>1.</span>\n\n\n<!--\n\n-->\n\n**1. To what speed must a proton be accelerated for it to have a wavelength of 3.0 cm?**\n\nKeywords: **proton**, **wavelength**, **speed**\n\nIn 1923 de Broglie says that matter has wave-like properties:\n\n$$ \\lambda = \\frac{h}{p}, $$\n\nwhere $h$ is Plancks constant ($6.626x10^{-34} Js$).  From classical mechanics we know linear momentum is the product of mass and velocity ($ p = mv $).  Then, we solve for velocity:\n\n$$ v = \\frac{h}{\\lambda\\space m_{proton}} = 1.3 x 10^{-5} \\text{m }s^{-1}$$\n\n**2. Calculate the energy per mole of photons for radiation of wavelength (a) 200 nm (ultraviolet), (b) 150 pm (X-ray), (c) 1.00 cm (microwave).**\n\nIn 1900 Bohr and Planck determined that energy is quantized (discrete energy levels).\n\n$$ E = nh\\nu, $$\n\nwhere $c = \\lambda \\nu$ and $n$ is the number of photons ($6.022x10^{23} photons/mole$).\n\nThen,\n\n$$ E = nh \\frac{c}{\\lambda}$$\n\nTherefore, \n\n$E =$ (a) $5.97x10^{5} J$, (a) $7.95x10^{8} J$, (a) $11.6 J$\n\n**3. The work function for metallic rubidium is 2.09 eV. Calculate the kinetic energy and the speed of the electrons ejected by light of wavelength (a) 650 nm, (b) 195 nm.**\n\n\nEinstein published the a paper on the *photoelectric effect* in 1905 (won Nobel Prize in 1921). The main idea is conservation of energy: $$E_{total} =  V + E_{k} $$\n\nHere, $V = \\phi \\equiv \\text{Work Function}$, $E_{total} = h\\nu$ and $ E_{k} = \\frac{1}{2}mv^{2}$.  The work function, $\\phi$ is defined as the amount of energy required to eject an electron, which is also known as ionization energy.\n\n$$h\\nu = \\phi + \\frac{1}{2}m_{e}v^{2},$$\n\nwhere $m_{e}$ is the mass of an electron ($9.11*10^{-31} kg$).\n\n\n\n\nTo calculate kinetic energy, we rearrange for $E_{k}$ to obtain\n\n\n$$E_{k} = \\frac{1}{2}m_{e}v^{2} =  \\phi - h\\nu $$\n\nSolving for velocity gives:\n\n$$ v = \\sqrt{\\frac{2}{m_{e}}(\\frac{hc}{\\lambda} - \\phi)} =  \\sqrt{\\frac{2}{m_{e}}E_{k}}$$\n\nTherefore, \n\nFor $\\lambda = 650 nm$, $E_{k} = -3.00 x 10^{-20} J$, which means the amount of energy is insufficient to eject the electron and $v = 0 m/s$.\n\n\n\n**Side notes:**\n\n- Ionization energy and electron affinity increase as your go $\\uparrow$ and $\\rightarrow$\n\n- Ionization energies are always positive values.\n\n\n\n\n**9.18 An electron is confined to a linear region with a length of the same order as the diameter of an atom (about 100 pm). Calculate the minimum uncertainties in its position and speed.**\n\nIn 1927 Werner Heisenberg devised one of the postulates of quantum mechanics called *Heisenberg's Uncertainty Principle*. This postulate states that complementary observables cannot be measured with absolute certainty i.e., if the position of a particle is certain, then its momentum is uncertain and visa-versa.\n\n$$\\Delta x \\Delta p \\underline{>} \\frac{h}{4\\pi} $$\n\nWe can say that the minimum uncertainty in position is 100 pm, which is $1.0 x 10^{-10} m$. Now, we need to find the minimum uncertainty in speed. Substituting for $\\Delta p = m_{e} \\Delta v$ ($m_{e} = 9.11x10^{-31}kg$) into the inequality above gives \n\n$$ \\Delta p = m_{e} \\Delta v \\underline{>} \\frac{h}{4\\pi \\Delta x } \\implies \\Delta v \\underline{>} \\frac{h}{4\\pi \\Delta x \\space m_{e}}$$\n\nTherefore, \n\n$$\\Delta v \\underline{>} 5.78x10^{5} m/s$$\n\n\n\n#### [Jump to table of contents.](#Table-of-Contents:)\n\n\n# 1-D time-independent $Schr\\ddot{o}dinger$ Equation & 1-D Particle in a Box\n\n\n\nThe wavefunction, $\\psi(x)$\n\n$$ \\psi(x) = Asin(\\frac{n\\pi x}{L}) $$\n\n\n#### Time-Independent $Schr\\ddot{o}dinger$ Equation\n\n$$\\hat{H}\\psi(x) = E\\psi(x)$$\n\n$$ \\text{Operator $\\space f^{\\underline{n}}$ = Eigenvalue $\\space f^{\\underline{n}}$} $$\n\n#### Hamiltonian Operator in 1-D\n\n$$ \\hat{H} = -\\frac{\\hbar^{2}}{2m}(\\frac{\\partial^{2}}{\\partial x^{2}}) + V(x)$$\n\nLet the kinetic energy and the potential energy be defined as the following:\n\n$$ E_{k} = \\frac{1}{2}mv^{2} = \\frac{\\hat{p}^{2}}{2m} = -\\frac{\\hbar^{2}}{2m}(\\frac{\\partial^{2}}{\\partial x^{2}}),$$\n\nand Hooke's law (springs) will define the potential energy of our bonds. \n\n$$F = -K_{f}x,$$\n\nwhere $ F = -\\frac{dV(X)}{dx} \\implies Fdx = dV(x)$\n\n$$ \\int Fdx = \\int -K_{f}xdx = \\int dV(x) $$\n\n$$ V(x) = \\frac{1}{2}k_{f}x^{2} $$\n\nRecall:\n\n\n\n\n\nNow we will operate on the wavefunction, $\\psi(x)$\n\n<br>\n\n\\begin{equation}\n\\begin{aligned}\n  \\hat{H}\\psi(x)\\hspace{0.5cm} = \\hspace{0.5cm} -\\frac{\\hbar^{2}}{2m}(\\frac{\\partial^{2} \\psi(x)}{\\partial x^{2}})\\hspace{0.5cm}&& +\\hspace{0.5cm} V(x)\\psi(x)\\\\\n\\label{aligned:Pn}\n \\text{Kinetic Energy} && \\text{Potential Energy}\n\\end{aligned}\n\\end{equation}\n\n<br>\n\nNow, consider a 1-dimensional (x) box of length, L. The particle has a free path and no potential energy inside the box, but infinite potential energy outside the box. \n\n\n\n\nwe need to plug $Asin(n\\pi x/L)$ in for $\\psi(x)$ and solve.  Note that if we take the derivative of $sin(x)$ with respect to x two times, we get back a -$sin(x)$.  This is called an **eigenfunction of the $\\frac{\\partial^{2}}{\\partial x^{2}}$ operator** because we get back the function sin(x). \n\nOkay, so we let $\\psi(x) = Asin(\\frac{n\\pi x}{L})$ and say:\n\n$$\\hat{H}\\psi(x) = E\\psi(x)$$\n\n$$ \\hat{H}\\psi(x)\\hspace{0.5cm} = \\hspace{0.5cm} -\\frac{\\hbar^{2}}{2m}(\\frac{\\partial^{2} Asin(\\frac{n\\pi x}{L})}{\\partial x^{2}})\\hspace{0.5cm},$$\n\nwhere $\\hbar = h/(2\\pi)$ and we know that \n\n$$(\\frac{\\partial^{2} Asin(\\frac{n\\pi x}{L})}{\\partial x^{2}}) = -\\frac{n^{2}}{L^{2}}Asin(\\frac{n\\pi x}{L}) $$\n\nThen,\n\n\n$$ E\\psi(x) = \\frac{h^{2}n^{2}}{8mL^{2}} Asin(\\frac{n\\pi x}{L}) \\implies E = \\frac{h^{2}n^{2}}{8mL^{2}}$$\n\n\n\n\n\n## Particle in a Box (PIB)\n\n\n\n$$E_{n} = \\frac{h^{2}n^{2}}{8mL^{2}} $$\n\nwhere the # of nodes = n-1, and the wavelength is $2\\times L/n$, the length of the box.\n\n$$ \\lambda = \\frac{2L}{n} $$\n\n\n\n#### [Jump to table of contents.](#Table-of-Contents:)\n\n#### <span style='color:blue'>2.</span>\n\n**Computer lab \\#1 \u2013 Intro to Spartan**\n\n**Goal**: The goal of this exercise is to familiarize yourself with Spartan, and the kind of information you can get using it.\n\n**Introduction**\n\nIn class, we have been discussing wavefunction solutions $\\psi(x)$ to Schr\u00f6dinger\u2019s Equation, $H\\psi = E\\psi$, for an electron as a function of its position $x$. Computational chemistry programs approximate solutions to Schr\u00f6dinger Equation, but for multi-electron systems\u2014atoms and molecules:\n\n$$\\hat{H}\\psi(x_{1}, x_{2},\u2026x_{n}) = E\\psi(x_{1}, x_{2},\u2026x_{n}).$$\n\nIt turns out that if you **assume the electrons do not interact** (i.e. do not feel each others\u2019 repulsion), then the **wave function is separable**, i.e. solutions are products of one-electron wavefunctions $\\psi(x_{1}, x_{2},\u2026x_{n}) = \\psi_{1}(x_{1}) \\psi_{2}(x_{2})\u2026 \\psi_{n}(x_{n})$. The $\\psi_{i}$ are called *orbitals*. \n\n\nQuantum chemistry methods try to solve for $\\psi$ as a product of orbitals, with different ways of approximating the effects of electron interaction. The computed solution is a set of *molecular orbitals* (MOs), each a one-electron wavefunction that can be spread out over the entire molecule.\n\nAs you might imagine, **MOs are complicated entities, but can be represented as a *superposition* (i.e. a sum) of *atomic orbitals* (AOs)**, i.e. wavefunctions of electrons bound to a specific nucleus. For reasons of computational efficiency, **each AO in turn is (usually) represented by superposition of simpler functions called *basis functions***. The more basis functions you use, the better the approximation, but at increased computational cost.\n\nIn this lab we will explore the effects of using different *basis sets* (i.e. groups of basis functions) for an atomic orbital calculation. We will consider three different basis sets, STO-3G, 3-21G, and 6-31G\\* (Figure 1).\n\n--------------------------------------------------\n\n## Introduction to Hartree Fock and Basis Sets:\n\n### Hartree Fock method\n\n- approximation (**variational approach**) for the determination of $\\Psi$ and $E$ of a quantum many-body system in a stationary state\n\nThis does a iterative search for $\\psi$ where $E'$ is smallest compared to the actual E.\n\n$$E'=\\int \\Psi^{*} H\\Psi d\\tau = <\\Psi^{*}|H|\\Psi>$$\n\n\n$$E'=\\int \\Psi^{*} E\\Psi d\\tau = E \\int \\Psi^{*}\\Psi = E$$\n\n$$E\u2032 > E$$\n\n### Slater-Type Orbitals (STO\u2019s)  \n\n#### Abbreviation: STO-nG, where n is an integer that represents the number of primitive Gaussian functions within a single basis function.\n\n- minimal basis set (cheaper computationally)\n\nFor example, consider oxygen\u2019s electronic configuration $1s^2 2s^2 2p^4$. We represent molecular orbitals (MOs) as a superposition of atomic orbitals (AOs):\n\n$$\\mathbf \\Psi_{STO-3G}= \\sum_{i}^{m} C_i\\psi_{(STO-3G)}(i) = C_1\\psi_{STO-3G}(1s) + C_2\\psi_{STO-3G}(2s) + C_3\\psi_{STO-3G}(2p_{x}) + C_4\\psi_{STO-3G}(2p_{y}) + C_5\\psi_{STO-3G}(2p_{z}),$$\n\n\nwhere $n$ primitive Gaussian orbitals are fitted to a single Slater-type orbital (STO).  The core and valence orbitals are represented by the same number of primitive Gaussian functions $\\mathbf \\phi_i$. For example, an STO-3G basis set for the 1s, 2s and 2p orbital of the carbon atom are all linear combination of 3 primitive Gaussian functions. For example, a STO-3G s orbital is given by:\n\n<!--A minimum basis set is where only sufficient orbitals are used to contain all the electrons in the neutral atom. Thus for the hydrogen atom, only a single 1s orbital is needed, while for a carbon atom, 1s, 2s and three 2p orbitals are needed. The core and valence orbitals are represented by the same number of primitive Gaussian functions $\\mathbf \\phi_i$.-->\n\n\n$$\\mathbf \\psi_{STO-3G}(s)= \\sum_{i}^{n} c_i\\phi_i = c_1\\phi_1 + c_2\\phi_2 + c_3\\phi_3 ,$$\n\nwhere\n\n$$\\mathbf \\phi_1 = \\left (\\frac{2\\alpha_1}{\\pi} \\right ) ^{3/4}e^{-\\alpha_1 r^2}$$\n\n$$\\mathbf \\phi_2 = \\left (\\frac{2\\alpha_2}{\\pi} \\right ) ^{3/4}e^{-\\alpha_2 r^2}$$\n\n$$\\mathbf \\phi_3 = \\left (\\frac{2\\alpha_3}{\\pi} \\right ) ^{3/4}e^{-\\alpha_3 r^2}$$\n\n\nThe $\\alpha_i$'s and $c_i$'s are tabulated values for each element and contained in a library within Spartan. The $C_{i}$'s are what is changing iteratively.\n\n\n\n#### For singlet, the method treats electrons as **indistinguishable** (2 electrons in an orbital are not labeled). For triplet, the method labels \u03b1 and \u03b2 electrons to 2 electrons in an orbital (convention is to start from \u03b1 as the lowest energy one).\n\n#### 6-31G the core orbital is a CGTO made of 6 Gaussians, and the valence is described by two orbitals \u2014 one CGTO made of 3 Gaussians, and one single Gaussian.\n\n#### 6-31G* [or 6-31G(d)] is 6-31G with added d polarization functions on non-hydrogen atoms.\n\n\n<!--\n| STO-2G | \u03b11 | c1 | \u03b12 | c2 |\n| :--: | :--: | :--: | :--: | :--: | \n| 1s | 0.151623\t | 0.678914\t| 0.851819 | 0.430129 |\n| 2s | 0.0974545 | 0.963782\t| 0.384244 | 0.0494718 |\n| 2p | 0.0974545 | 0.61282\t| 0.384244 | 0.511541 |\n-->\n\n\n\n--------------------------------------------------\n#### [Jump to table of contents.](#Table-of-Contents:)\n\n**Directions:**\n\n1.  Login to your account by using your tuid and password.\n\n2.  Open Spartan by clicking on its icon on the desktop.\n\n3.  File &gt; New Build (or click icon on upper left)\n\n4.  Build an oxygen **atom**:\n\n    1.  Select oxygen from panel and click anywhere in main window.\n\n    2.  Remove bonds by using delete tool (build &gt; delete, or select eraser icon in the panel. You have to click it each time you want to delete an atom)\n\n5.  Setup &gt; Calculations\u2026 Parameters:\n\n    1.  **Energy** at **ground** state\n\n    2.  With **Hartree-Fock STO-3G** in **vacuum**, total charge: **neutral, zero unpaired electrons**\n\n    3.  Check box for **orbital and energy**\n\n    4.  Check box for **charges and bond orders**\n\n    5.  Submit (it will ask you where to save the data, it is good to give them proper names and save them on Desktop).\n\n    6.  Wait until calculation is done (a few seconds).\n\n6.  Display &gt; orbital energies\n\n    1.  Record approximate HOMO and LUMO energies (click on spectrum to get values)\n\n7.  Display &gt; Surfaces:\n\n    1.  Add HOMO, LUMO and Electrostatic potential map\n\n    2.  Look at different shape of HOMO, LUMO and electrostatic potential map by clicking on boxes next to them (Do this one by one).\n\n    3.  Close this window.\n\n8.  Display &gt; output:\n\n    1.  Record values for Basis set, HOMO, LUMO, and total energy in **Results** section below\n\n9.  Repeat calculations for these basis sets: STO-3G, 3-21G, 6-31G\\* and with these multiplicities: **Singlet** (choose 0 unpaired electrons) and **triplet (**choose 2 unpaired electrons, report \u201ca\u201d and \u201cb\u201d HOMO and LUMOs)\n\n**About energies:** the ground state of H-atom is -13.6 eV = \u00bd hartree.\n\n1 hartree = 27.2 eV\n\n\n\n\n\n**Results:**\n\n\n| Basis set | Unpaired electrons | Multiplicity | HOMO energy  (eV)    | LUMO energy (eV) | Total Energy (eV)  | Total Energy (hartrees) | Total number of Basis $f^{\\underline{n}}$'s |\n| :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |\n| STO-3G    | 0   | singlet  |   -11.10    |  6.39   | -2003.6014 | -73.661817 |   5       |\n| 3-21G     | 0   | singlet  |   -14.96    |  1.24   | -2020.0746 | -74.267450 |   9       |\n| 6-31G\\*   | 0   | singlet  |   -15.67    |  0.16   | -2030.6596 | -74.656604 |   15      |\n| STO-3G    | 2   | triplet  |   $\\alpha,\\beta$ = -12.39, 10.27 | \u2014   | -2007.4729 | -73.804150 |   5       |\n| 3-21G     | 2   | triplet  |   $\\alpha,\\beta$ = -15.93, 4.67 |  $\\alpha,\\beta$ = 44.34, 47.62   | -2023.5075 | -74.393657 |   9       |\n| 6-31G\\*   | 2   | triplet  |   $\\alpha,\\beta$ = -16.44, 3.50  |  $\\alpha,\\beta$ = 23.89, 25.65   | -2034.1230 | -74.783934 |   15      |\n\n\n\n\n<!--\n| Basis set | Unpaired electrons | Multiplicity | HOMO energy  (eV)    | LUMO energy (eV) | Total Energy (eV)  | Total Energy (hartrees) | Total number of Basis $f^{\\underline{n}}$'s |\n| :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |\n| STO-3G    | 0   | singlet  |   -11.10    |  6.39   | -2003.6014 | -73.661817 |   5       |\n| 3-21G     | 0   | singlet  |   -14.96    |  1.24   | -2020.0746 | -74.267450 |   9       |\n| 6-31G\\*   | 0   | singlet  |   -15.67    |  0.16   | -2030.6596 | -74.656604 |   15      |\n| STO-3G    | 2   | triplet  |   -12.39    |  10.27  | -2007.4729 | -73.804150 |   5       |\n| 3-21G     | 2   | triplet  |   -15.93    |  44.34  | -2023.5075 | -74.393657 |   9       |\n| 6-31G\\*   | 2   | triplet  |   -16.44    |  23.89  | -2034.1230 | -74.783934 |   15      |\n## from output: \nJob type: Single point.\nMethod: RHF\nBasis set: STO-3G\nNumber of basis functions: 5\nNumber of electrons: 8\nParallel Job: 4 threads\nSPARTAN '18 (x86/Darwin)    Release 1.4.1_\nFormula:\tO\nJob type:\tEnergy\nMethod:\tHF\nBasis set:\tSTO-3G\nEnergy:\t-73.661817 hartrees\n| Label\t| Energy |\n| :--: | :--: |\n| (ev) | - |\n| LUMO | 6.39 |\n| HOMO | -11.10 |\n| HOMO{-1} | -11.10 |\n| HOMO{-2} | -30.50 |\n-----------------------------------------\n### STO-3G \nLabel\tAlpha Spin \nEnergy \n(ev)\tBeta Spin \nEnergy \n(ev)\nsoHOMO\t-12.39\t10.27\nSOMO\t-14.98\t10.27\nHOMO{-2}\t-14.98\t-9.81\nHOMO{-3}\t-35.19\t-25.81\n### 3-21G\nLabel\tAlpha Spin \nEnergy \n(ev)\tBeta Spin \nEnergy \n(ev)\nLUMO{+2}\t46.22\t50.65\nLUMO{+1}\t44.34\t50.65\nLUMO\t44.34\t47.62\nsoHOMO\t-15.93\t4.67\nSOMO\t-18.31\t4.67\nHOMO{-2}\t-18.31\t-13.38\nHOMO{-3}\t-37.48\t-28.52\n### 6-31G\\*\nLUMO{+2}\t28.20\t34.21\nLUMO{+1}\t28.20\t31.05\nLUMO\t23.89\t25.65\nsoHOMO\t-16.44\t3.50\nSOMO\t-19.06\t3.50\nHOMO{-2}\t-19.06\t-14.02\nHOMO{-3}\t-38.32\t-29.13\n-->\n\nChecklist:\n\n1.  Effect of basis set on calculations.\n\n2.  Effect of multiplicity on calculations.\n\n3.  Relative energies of HUMO and LUMO.\n\n4.  Electron Density (from electrostatic potential map)\n\n\n#### [Jump to table of contents.](#Table-of-Contents:)\n\n\n#### <span style='color:blue'>3.</span>\n\n**Computer lab #2 \u2013 Particle in a Box (PIB) - Polyenes**\n\n**Goal:** The purpose of this lab is to illustrate the applicability of the particle-in-the-box (PIB)\nmodel to conjugated systems of \u03c0-orbitals.\n\n\n**Introduction:**\n\nRefer back to the notes on [1-D time-independent $Schr\\ddot{o}dinger$ Equation & Particle in a Box](#1-D-time-independent-$Schr\\ddot{o}dinger$-Equation-&-1-D-Particle-in-a-Box) for more details.\n\nLet\u2019s recall the PIB model, where the electron is confined to a 1-dimensional box of length L. The possible states of the electron are described by wavefunctions $\\psi_{n}(x)$, for n = 1, 2, 3, ...\n\n\n\n$$\\psi_{n}(x) = \\sqrt{\\frac{2}{L}}sin(\\frac{n\\pi x}{L}),$$\n\nwith respective energies\n\n\n$$ E_{n} = \\frac{h^{2}n^{2}}{8mL^{2}}$$\n\n\n\n\n\n\n\n\n\n\n\n\nData Table:\n\n\n| \"n\" | ${C_{3}H_{5}}^{+}$ (eV) | ${C_{5}H_{7}}^{+}$ (eV) | ${C_{7}H_{9}}^{+}$ (eV) | ${C_{9}H_{11}}^{+}$ (eV) | ${C_{11}H_{13}}^{+}$ (eV) |\n| :---: | :---: | :---: | :---: | :---: | :---: | \n| 6  | -           | -           | -           | -           | LUMO=-4.02 |\n| 5  | -           | -           | -           | LUMO=-4.27  | HOMO=-11.55 |\n| 4  | -           | -           | LUMO=-4.62  | HOMO=-12.38 |  -13.37     |\n| 3  | -           | LUMO=-5.10  | HOMO=-13.53 | -14.49      |  -15.03     |\n| 2  | LUMO=-5.90  | HOMO=-15.20 | -15.97      | -16.26      |  -16.32     |\n| 1  | HOMO=-17.88 |  -18.02     | -17.83      | -17.57      |  -17.32     |\n\n\n\n\n\n\n\nAnalysis\n1. The PIB model predicts that the energy En is proportion to $n^{2}$. Pick one of the columns in Data Table above (for ${C_{5}H_{7}}^{+}$ or larger), and plot the data points on the axes below to see if this is true.\n\n\n\n\n\n\n\n\n\n\n\n\n\n```python\n%matplotlib inline\nimport plot as p\nenergies = [-4.02,-11.55,-13.37,-15.03,-16.32,-17.3][::-1]\nn2 = [float(i**2.) for i in range(1,7)]\nprint(\"Energies = %s\"%energies)\nprint(\"n^{2} = %s\"%n2)\np.simple_plot(n2,energies,xlabel='$n^{2}$',ylabel='Energy, E (eV)',name=None,size=111,Type='scatter',\n        color=False,fig_size=(8,4),invert_x_axis=False,fit=True,order=1)\n```\n\nRecall: The zero-point energy, $E_{1}$ = -13.6 eV for Hydrogen.\n\n**2. Why doesn't PIB do a great job for certain energy levels?**\n\nAs we increase to larger levels i.e., as $n \\rightarrow \\infty$; $\\lambda \\rightarrow 0$ and the [correspondence principle](https://en.wikipedia.org/wiki/Correspondence_principle) states that the particle behaves more classical.\n\n**3. Another prediction of the PIB model is about how the energy gap \u2206E between the HOMO and LUMO levels varies with the \u201cbox\u201d length L.**\n\nNotice that when there k carbons in the molecule, the quantum number of the HOMO is always $n = \\frac{(k-1)}{2}$. So, the HOMO/LUMO gap for $C_{k}H_{k+2}^{+}$ should be\n\n$$ \\Delta E = \\frac{h^{2}}{8mL^{2}}[(n+1)^{2} - n^{2}] = \\frac{h^{2}}{8mL^{2}}(2n+1)= \\frac{h^{2}}{8mL^{2}}k$$\n\nIf we also measure the \u201cbox\u201d length L in terms of the number of carbon atoms, then L = k, and the energy gap should be inversely proportional to the number of carbons,\n\n$$ \\Delta E \\propto \\frac{1}{k}$$\n\n\n\n\n| k | $$(E_{LUMO} - E_{HOMO})\\text{ for }C_{k}H_{k+2}^{+}\\text{ (eV)}$$ |\n| :---: | :---: | \n| 3  | 11.98 |\n| 5  | 10.10 |\n| 7  | 8.91 |\n| 9  | 8.11 |\n| 11 | 7.53 |\n\n\n\n\n\n\n```python\nimport numpy as np\nLUMO = [-5.90,-5.10,-4.62,-4.27,-4.02 ]\nHOMO = [-17.88,-15.20,-13.53,-12.38,-11.55]\nk_inv = np.array([3.,5.,7.,9.,11.])**(-1.)\ndE = [LUMO[i]-HOMO[i] for i in range(len(HOMO))]\np.simple_plot(k_inv,dE,xlabel='$\\\\frac{1}{k}$',ylabel='Energy, $\\\\Delta E$ (eV)',name=None,size=111,Type='scatter',\n        color=False,fig_size=(8,4),invert_x_axis=False,fit=False,order=None)\n```\n\n#### [Jump to table of contents.](#Table-of-Contents:)\n\n#### <span style='color:blue'>4.</span>\n\n**Literature Discussion/Review:**\n\n\n##### Juffmann, Thomas, et al. [Real-time single-molecule imaging of quantum interference](https://www-nature-com.libproxy.temple.edu/articles/nnano.2012.34.pdf) Nature nanotechnology 7.5 (2012): 297.\n\n\n##### [Supplementary Information](https://static-content.springer.com/esm/art%3A10.1038%2Fnnano.2012.34/MediaObjects/41565_2012_BFnnano201234_MOESM583_ESM.pdf)\n\n\n[Applet for double slit](https://phys.libretexts.org/Ancillary_Materials/Visualizations_and_Simulations/PhET_Simulations/PhET%3A_Wave_Interference)\n\n[MIT course notes](http://web.mit.edu/8.02t/www/802TEAL3D/visualizations/coursenotes/modules/guide14.pdf).\n\n<!--\n\n-->\n\n<!--\n\n\n**Figure** Intensity distribution for a single-slit diffraction.\n-->\n\n<!--\nFluorescent dyes: \nphthalocyanine ($PcH_{2}$), $C_{32}H_{18}N_{8}$, mass m = 514 AMU ,  number of atoms N = 58\nphthalocyanine derivative ($F_{24}PcH_{2}$), $C_{48}H_{26}F_{24}N_{8}O_{8}$ , m = 1,298 AMU, N = 114,\n-------------------\n###### Calculating de Broglie Wavelength\n$ sin( \\theta_{n}) = n \\lambda/d, where \\lambda = h/p = h/mv$\nUsing a speed of $v = 150 m \\space s^{-1}$ we can calculate the wavelength for each molecule.\nFor $PcH2$:  $\\lambda = 5.18 pm$\nFor $F_{24}PcH2$:  $\\lambda = 2.05 pm$\n**Very small wavelengths!**\n-->\n\n\n\n<!--\n\n**Figure 4.** Comparison of interference patterns for $PcH2$ and $F_{24}PcH2$.\n**Key points:**\n- \"Spectral coherence is achieved when by sorting the arriving molecules according to their longitudinal velocity and their respective freefall height from earth's gravitational field.\"\n- Molecules with greater speeds will be at the top of figure 4., and slower molecules will be at the bottom.\n- Altering of interference patterns:\n  - Changing the period or width of the slits\n  - changing the distance between grating and window (the $L$ values) in figure 1.\n  - grating thickness (and corresponding van der Waals phase shift)\n-->\n\n\n<!--\nThe van der Waals interaction between the polarizable molecule and the dielectric grating wall was taken into account in the phase of the grating transmission function. The phase term\n$$\\psi = exp(iC3D[1/\\Delta x^{3} + 1/(s \u2013 \\Delta x^{3}]/\\hbar v)$$\n-->\n\n<!--\n\n-->\n\n<!--\n-->\n\n\n#### [Jump to table of contents.](#Table-of-Contents:)\n\n#### <span style='color:blue'>5.</span>\n\n\n**Computer Lab #3 \u2014 Harmonic Oscillator**\n\n\n**Goal:** The purpose of this lab is to investigate the ability of quantum chemical calculations to predict vibrational spectra.\n\n\n**\u201cThe ability of quantum mechanics calculations to predict vibrational spectra.\u201d**\n\nIn lecture, we learned about 1D Harmonic Oscillator solutions to the Schr\u00f6dinger equation, $\\psi_{v}(x)$, $v = 0, 1, 2, ...$, for a particle subjected to a harmonic potential $V(X) = \\frac{1}{2}k_{f}x^{2}$. We found the energies of each vibrational state to be\n\n\n$$ E_{v} = (v + \\frac{1}{2})h\\nu, \\tag{1}$$\n\nwhere h is Planck\u2019s constant, and $\\nu = \\frac{1}{2\\pi}\\sqrt{\\frac{k_{f}}{\\mu}}$ is the harmonic oscillator frequency, which depends on the force constant $k_{f}$ (units N.$m^{-1}$) and the reduced mass $\\mu = \\frac{m_{1}m_{2}}{m_{1}+m_{2}}$ (assuming the vibration is for a two-particle system of masses $m_{1}$ and $m_{2}$). Let\u2019s explore how well this simple harmonic approximation compares to more detailed quantum calculations of diatomic molecules.\n\n<!--\n### Density Functional Theory (DFT)\nA technique that has gained considerable ground in recent years to become one of the most widely used techniques for the calculation of molecular structure is density functional theory (DFT). Its advantages include less demanding computational effort, less computer time, and\u2014in some cases (particularly d-metal complexes)\u2014 better agreement with experimental values than is obtained from Hartree\u2013Fock procedures.\nThe central focus of DFT is the electron density, \u03c1, rather than the wavefunction \u03c8. The \u2018functional\u2019 part of the name comes from the fact that the energy of the molecule is a function of the electron density, written E[\u03c1], and the electron density is itself a function of position, \u03c1(r), and in mathematics a function of a function is called a func- tional. The occupied orbitals are used to construct the electron density from\n$$ \\rho(r) = \\sum_{} | \\psi_{m}(r)|^{2} $$\nand are calculated from the Kohn\u2013Sham equations, which are like the Hartree\u2013Fock equations except for a term VXC, called the exchange\u2013correlation potential:\n$$ \\{ h_{1} + j_{0} \\int \\frac{\\rho(2)}{r_{12}}d\\tau_{2} + V_{XC}(1) \\} \\psi_{m}(1) = \\epsilon_{m}\\psi_{m}(1) $$\nThe first term on the left is the usual one-electron kinetic and potential energy con- tribution and the second term is the potential energy of repulsion between electrons 1 and 2. The challenge in DFT is to construct the exchange\u2013correlation potential and computational chemists use several approximate expressions for VXC.\nThe Kohn\u2013Sham equations are solved iteratively and self-consistently. First, we guess the electron density. For this step it is common to use a superposition of atomic electron densities. Next, the Kohn\u2013Sham equations are solved to obtain an initial set of orbitals. This set of orbitals is used to obtain a better approximation to the electron density and the process is repeated until the density and the exchange\u2013correlation energy are constant to within some tolerance.\n------------------------\nOne of the most important concepts for discussing beam results and calculating the state-to-state collision cross-section is the potential energy surface of a reaction, the potential energy as a function of the relative positions of all the atoms taking part in the reaction. Potential energy surfaces may be constructed from experimental data, with the techniques described in Section 22.6, and from results of quantum chemical calculations. Density functional theory (DFT, Section 10.7c) provides a relatively cheap way of incorporating electron correlation and is increasingly being applied to reactive systems.\n-->\n\n\n\n\n#### **Procedure**\n\n**Part A.** Let\u2019s consider the diatomic molecule CO, carbon monoxide. Spartan has a database of experimental vibrational spectra for a small number of molecules, and CO is one of them. Perform the following steps:\n\n1. Build the molecule, and optimize its geometry\n  \n  a. Build $C \\equiv O$ molecule.\n  \n  b. Setup > Calculations ...\n  \n  c. Calculate Equilibrium Geometry for the Ground State, using <span style='color:Red'><b>DFT-B3LYP</b></span> with a modest basis set <span style='color:Red'><b>6-31G*</b></span>. Set total charge to \u201c<span style='color:Red'><b>Neutral</b></span>\u201d with <span style='color:Red'><b>0</b></span> unpaired electrons, and make sure the checkbox for <span style='color:Red'><b>Vibrational Modes</b></span> is selected.\n\n  d. The calculation should complete quickly.\n\n2. Inspect the calculated vibrational spectra.\n  \n  a. Go to the Display > Spectra menu.\n  \n  b. Click on the plus icon and add the <span style='color:Red'><b>Calculated IR spectrum and Experimental IR spectrum</b></span>. You should see good agreement between the two spectra. Clicking and dragging near the computed spectral peak will \u201clock on\u201d to the peak and display a numerical value for the predicted peak, and animate the bond-stretching vibrational mode. Note that these spectra are reported in wavenumbers ($cm^{-1}$), which is very typical of chemical spectroscopic measurements. The wavenumber  $\\tilde{\\nu}$ is the reciprocal of the wavelength, $\\tilde{\\nu} = \\frac{1}{\\lambda}$. Thus, the frequency in Hz ($s^{-1}$), $\\nu = c\\tilde{\\nu}$, can be obtained simply by multiplying $\\tilde{\\nu}$ by the speed of light, $2.998 x 10^{10} cm.s^{-1}$.\n\n\n$$\\nu = \\frac{c}{\\lambda} = \\tilde{\\nu} c  = (2104\\space cm^{-1}) (2.998 x 10^{10} cm \\space s^{-1}) = 6.308x10^{13} Hz$$\n\n**Part B. Vibrational Modes.** It can be shown that there are **3N-6** and **3N-5** vibrational modes (in which N is the number of atoms in molecule) for non-linear and linear molecules; respectively. For example, we have 1 vibrational mode for CO molecule\u2014as it is a linear molecule and N=2\u2014which corresponds with $C \\equiv O$ bond-stretching.\nFor this part, let\u2019s try to evaluate vibrational modes of $H_{2}O$ and $HCN$ ($H\u2014C\\equiv N$) molecules. To do so, calculate Equilibrium Geometry for the Ground State of these molecules, using <span style='color:Red'><b>DFT- B3LYP</b></span> with a modest basis set <span style='color:Red'><b>6-31G*</b></span>. Set total charge to \u201c<span style='color:Red'><b>Neutral</b></span>\u201d with <span style='color:Red'><b>0</b></span> unpaired electrons, and make sure the checkbox for <span style='color:Red'><b>Vibrational Modes</b></span> is selected.\n\n\n\n<b>Quick Note: <span style='color:Blue'>The most fundamental difference between DFT and MO theory is that DFT optimizes electron density while MO theory optimizes a wave function.</span></b>\n\n\n\n\n#### Questions:\n\n**Part A:** In part A, you found the wavenumber corresponded to CO bond-stretching using DFT method. Convert the wavenumber of the predicted peak to frequency.\nAnswer (from DFT):\n\n\nNow, let\u2019s compare this frequency to the frequency of light we expect to be absorbed for excitation from the v = 0 \u2192 v = 1 states of a Harmonic Oscillator, given in Equation (1). The reported force constant for CO is $k_{f} = 1820\\space N.m^{-1}$. To calculate the reduced mass, assume that the masses of the carbon and oxygen atoms are 12 $m_{p}$ and 16 $m_{p}$, where $m_{p} = 1.672 \u00d7 10^{-27}\\space kg$ is the mass of the proton. Are these results comparable to the quantum mechanical calculations?\nAnswer (from Harmonic Oscillator calculation):\n\n$$ \\mu = \\frac{m_{1}m_{2}}{m_{1}+m_{2}} = 1.147x10^{-26} \\space kg $$\n\nNow, calculating the energy for $v =1$:\n\n$$ E_{v} = (v + \\frac{1}{2})h\\nu = (v + \\frac{1}{2})\\hbar\\sqrt{\\frac{k_{f}}{\\mu}} = 6.302x10^{-20} \\space J,$$\n\n\nwhere $\\tilde{\\nu} = 2115 cm^{-1}$. The value obtained from $CO$'s calculated IR spectrum (Spartan) is $2104\\space cm^{-1}$, which is different by approximately $11 cm^{-1}$. \n\n\n\nThe QM harmonic oscillator models the potential energy through Hooke's Law, $V(X) = \\frac{1}{2}k_{f}x^{2}$ where $k_{f} = m \\omega^2$ and $\\omega = 2\\pi \\nu$. Thinking of the bond as a spring with a mass $m$ attached to the end is a very nice model for the $C=O$ stretch, therefore the answer is (as it should be) close to the DFT calculations from *Spartan*.\n\n\n**Part B: Vibrational Modes.** Based on your results, complete the following table for H2O and HCN molecules.\n\n\n| Molecule | $\\text{Wavenumber},\\space \\tilde{\\nu}\\space (cm^{-1})$ | $$\\text{Which atoms are involved in each vibrational mode?}\\\\ \\text{Also, classify each one in terms of Symmetric-stretch, Asymmetric stretch, and Bending.}$$ |\n| :---: | :---: | :---: |\n| $H_{2}O$ | $\\tilde{\\nu_{1}} = 3554 \\text{ (symmetric stretch)} \\\\ \\tilde{\\nu_{2}} = 1628 \\text{ (bend)} \\\\ \\tilde{\\nu_{3}} = 3669\\text{ (asymmetric stretch)}$ |    |\n| $HCN$ | $\\tilde{\\nu_{1}} = 3313 \\text{ (C-H stretching)} \\\\ \\tilde{\\nu_{2}} = 2109 \\text{ ($C\\equiv N$ stretching)} \\\\ \\tilde{\\nu_{3}} = 731\\text{ ($H-C\\equiv N$ bending)} \\\\ \\tilde{\\nu_{4}} = 731\\text{ ($H-C\\equiv N$ bending)} $ |  -  |\n\n\n#### [Jump to table of contents.](#Table-of-Contents:)\n\n\n<!--\nimport numpy as np\nv = 1.\nmp = 1.672*10**(-27.)\nc = 2.998*10**8. # m/s\nm1 = 12.*mp\nm2 = 16.*mp\nmu = m1*m2/(m1+m2) # kg\nprint(\"mu = %0.4G kg\"%mu)\nh = 6.626*10**(-34.) # J s\nkf = 1820. # N/m\nnu = 1/(2.*np.pi)*np.sqrt(kf/mu)\nprint(\"nu = %0.4G Hz\"%(nu/c))\nE = (v+0.5)*h*nu\nprint(\"E = %0.4G J\"%E)\n###############################\nnu = 6.308*10**(13.) # Hz\nprint(\"E (light) = %0.4G J\"%(nu*h))\n-->\n\n#### <span style='color:blue'>6.</span>\n\n\n\n<h3>Midterm Review #1:</h3>\n\n\n\n<!--\nHW1: Chapter 9: 11, 13, 14, 17, 18\nHW2: Chapter 9: 19, 21, 22, 23, 32, 33 \nHW3: Chapter #9: 27, 35, 36, 41, 42  Chapter #10: 14\nHW4: Chapter #10: 19, 23, 26   Chapter #11: 4\nHW5: Chapter 11: #9, 27, 35, 36, 38, 44\n-->\n\n\n**10.19 Suppose that a molecular orbital has the form N(0.145A+0.844B). Find a linear combination of the orbitals A and B that has <u>zero overlap</u> with this combination.**\n\nIf we are looking for zero overlap, then we are looking for a function that is orthogonal to the function that was given.  Furthermore, we are looking for a molecular orbital that has the same form as $N(0.145A+ 0.844B)$, which would be: $N(aA+ bB)$. \n\n<!--\n\n-->\n\n\n\n$$\\int \\psi\\psi\\prime d\\tau = \\int N(0.145A+ 0.844B)N(aA+ bB) d\\tau = 0$$\n\n$$\\int N^{2} (0.145A+ 0.844B)(aA+ bB) d\\tau = 0$$\n\n$$N^{2} \\int [0.145a \\overbrace{A^{2}}^{1} + 0.145b\\overbrace{AB}^{0} + 0.844a\\overbrace{BA}^{0} + 0.844b\\overbrace{B^{2}}^{1}] d\\tau = 0,$$\n\nwhere we know that the overlap integral goes to zero i.e., $\\int ABd\\tau=0$ and we know: $\\int A^{2}d\\tau=1$, $\\int B^{2}d\\tau=1$.\n\nTherefore, after integration we are left with \n\n$$N^{2}( 0.145a + 0.844b )= 0 $$\n\n$$\\implies a = -\\frac{0.844}{0.145}b$$\n\n\n$$\\therefore \\space N(0.844A - 0.145B) \\text { or } N(-0.844A + 0.145B)$$\n\n\n\n\n#### [Jump to table of contents.](#Table-of-Contents:)\n\n#### Practice Problems:\n\n<!--\nimport numpy as np\nc = 3.00*10**8. # m/s\nh = 6.626*10**(-34.)\nme = 9.109*10**(-31.)\nl = 10**(-10.)\nprint(\"%0.3G\"%(h/(2*np.pi)/(2*10**-9.)))\n-->\n\n\n**1. Draw a picture of a sinusoidal wave $g(x, t)$, annotated with the wavelength $\u03bb$, phase velocity $v$, and amplitude $A$. Write down the mathematical form of the function $g(x, t)$ describing this wave.**\n\n\n$$ g(x,t) = Acos(\\frac{2\\pi}{\\lambda}(x-\\nu t) + \\phi) $$\n\nOr equivlantly, \n\n$$ g(x,t) = Asin(\\frac{2\\pi}{\\lambda}(x-\\nu t)) $$\n\nTherefore, when $\\phi = \\pi$ we get the curve in Figure 1.\n\n\n<p style=\"text-align: center\"><b>Figure 1.</b> $\\psi(x) = Asin(\\frac{2\\pi}{\\lambda}x+\\pi)$</p>\n\n**2. A light wave (with phase velocity c = 3.00 \u00d7 108 m s-1) has a wavelength of 1 \u03bcm.**\n\nNote that the visible region $\\in \\{400,...,700\\}nm$.\n\n**(a) What frequency is the light?**\n\n$$c=\\lambda \\nu \\implies \\nu = \\frac{c}{\\lambda} = 3x10^{14}\\space Hz$$\n\n\n**(b) Is it in the visible range?**\n\n$$\\frac{10^{9}\\space nm }{1\\space m}\\frac{10^{-6} \\space m}{} = 10^{3} nm$$\n\n$ \\therefore$ this wavelength is just outside of the visible region.\n\n\n**3. An electron has a deBroglie wavelength of $1 \u00c5$ = $1 \u00d7 10^{-10}\\space m$.**\n\n**(a) What is its momentum?**\n\n$$p = \\frac{h}{\\lambda} = 7x10^{-24} \\space J.s.m^{-1}$$\n\n**(b) Given the mass of the electron ($m_{e} = 9.109x10^{-31} \\space kg$), what is the electron\u2019s velocity?**\n\nLinear momentum is just:\n\n$$ p = mv \\implies v = \\frac{p}{m} = 7x10^{6} m.s^{-1}$$\n\n\n\n\n**4. Suppose we have confined an electron to a very small space, such that we can measure its position to an uncertainty of $\u2206x = 1 \\space nm$. If we measure the momentum, what is the lower limit in the expected uncertainty $\u2206p$?**\n\nHeisenberg's Uncertainty Principle (1927):\n\n$$\\Delta x \\Delta p \\underline{>} \\frac{\\hbar}{2} \\implies \\Delta p \\underline{>} \\frac{\\hbar}{2 \\Delta x} = 5.27x10^{-26} J.s.m^{-1}$$\n\n\n\n**5. Write down the 1D time-independent Schrodinger equation.** \n\n$$ \\hat{H}\\psi(x) = \\overbrace{-\\frac{\\hbar^{2}}{2m}(\\frac{\\partial^{2} \\psi(x)}{\\partial x^{2}})}^{\\text{Kinetic Energy}} + \\overbrace{V(x)\\psi(x)}^{\\text{Potential Energy}} = E\\psi(x)$$\n\n**6. Write down normalized Particle-In-a-Box (PIB, i.e. $V(x) = 0$ inside a box of length $L$) wavefunctions $\\psi_{n}(x)$ for $n=1, 2 \\space and \\space3$, and their corresponding energies $E_{n}$.**\n\n\nJust plug $n=1, 2 \\space and \\space3$ into the equations below...\n\n$$\\psi(x) = \\sqrt{\\frac{2}{L}}sin(\\frac{n\\pi x}{L}),$$\n\nwhere the eigenvalue of the Hamiltonian operator for PIB is just \n\n$$E = \\frac{h^{2}n^{2}}{8mL^{2}} $$\n\n\n**7. Draw the PIB wavefunctions $\\psi_{n}(x)$ for $n=1, 2 \\space and \\space3$.**\n\n[Click here to see image of PIB wavefunctions](#Particle-in-a-Box-(PIB))\n\n**8. Draw the probability distributions $P_{n}(x)$ for $n=1, 2 \\space and \\space3$.**\n\n[Look at the image of PIB wavefunctions](#Particle-in-a-Box-(PIB)) for $n=1, 2 \\space and \\space3$ and reflect the negative portion of the curve into the positive region.\n\n\n**9. Suppose I give you an unnormalized wavefunction $\\psi(x)$, and the information that $\\int |\\psi(x)|^{2}dx = 0.5$ . What number $c$ will produce a normalized wavefunction $c\\psi(x)$ ?**\n\n\n$$\\int c\\psi(x)^{*}c\\psi(x)dx = 1 \\implies c^{2}\\int |\\psi(x)|^{2}dx = 1$$\n\n$$c^{2}\\int |\\psi(x)|^{2}dx = c^{2} \\frac{1}{2} = 1$$\n\n$$c^{2} =2 \\implies c = \\sqrt{2}$$\n\n\n**10. For PIB wavefunction $\\psi_{n}(x)$, $n=2$, what is the probability that the electron will be found on the right most quarter of the box, i.e. $\\frac{3L}{4} < x < L$? (Hint: draw a picture!)**\n\nDue to symmetry: \n\n$$ P(x) = 0.25$$\n\n**11. A diatomic $C=O$ molecule is excited from a $v=1$ vibrational state to a $v=2$ state by a light wave.** \n**(a) If the harmonic oscillator force constant is $1860 N. m^{-1}$, calculate the frequency of the light. (Hint: you will need to consider the reduced mass $\\mu$).**\n\nThe harmonic oscillator eneergy is just\n\n$$ E_{v} = (v + \\frac{1}{2})\\hbar\\omega,$$\n\nwhere\n\n$$\\omega = \\sqrt{\\frac{k_{f}}{\\mu}},$$\n\nand \n\n$$ \\mu = \\frac{m_{1}m_{2}}{m_{1}+m_{2}} = 1.147x10^{-26} \\space kg $$\n\n\nThe separation between adjacent energy levels is\n\n$$E_{v+1}-E_{v} = \\hbar \\omega $$\n\n\n$$E_{2}-E_{1} = h \\frac{1}{2\\pi}\\sqrt{\\frac{k_{f}}{\\mu}} $$\n\n$\\therefore$\n\n$$ \\nu = 6.31x10^{13} \\space Hz$$\n\n\n\n**(b) Based on the frequency you compute, what kind of light is this (e.g. radio waves, UV, etc...)?**\n\nUV region\n\n**12. State how the energies En of the hydrogen-like wavefunctions depend on quantum numbers n, l and m?**\n\n$$E = -\\frac{13.6 \\space eV}{n^{2}} \\implies E_{n} \\propto -\\frac{1}{n^{2}}$$\n\n$$E_{l,m_{l}} = l(l+1)\\frac{\\hbar^{2}}{2I} = \\frac{|J|^{2}}{2I},$$\n\nwhere \n\n$$ |J| = \\sqrt{l(l+1)}\\hbar$$\n\n**13. The ground state of the hydrogen atom has an ionization energy of 13.6 eV. What is the ionization energy for the ground state of $He^{+}$?**\n\n$$ E_{n} = -\\frac{Z^{2}(13.6 \\space eV)}{n^{2}} = \\frac{-4(13.6)}{1^{2}},$$\n\nwhere \n\n$$I = -E \\implies I = 54.4 \\space eV$$\n\n\n**14. What is the maximum number of electrons that can occupy n=3 states in an atom? (remember to count spin states too!)**\n\nWrite out possible quantum numbers:\n$n = 3, \\space l = \\{0,1,2\\}, \\space m_{l}=\\{-2,-1,0,1,2\\}$\n\nMax number of electrons in subshell is $2(2l+1)$, and the max number of electrons in a shell is $2n^{2}$.\n\nTherefore,\n\n$$\\sum_{i=0}^{2} 2(2l_{i}+1) = 2(2(0)+1)+2(2(1)+1)+2(2(2)+1)= 18$$\n\n$$\\text{or}$$ \n\n$$2(3)^2 = 18$$\n\n**15. The ground-state radial wavefunction for the hydrogen-like atom (i.e. a $1s$ orbital) is $R(r) = 2(\\frac{Z}{a_{0}})^{3/2} exp(-Zr/a_{0})$. What is the most probable radius r for the electron?**\n\n\nThen, we need to find the value of r that maximizes $P(r)$. **Take first derivative and set equal to zero. Solve for r.**\n\n\n$$d P=\\left[\\frac{1}{\\sqrt{\\pi} a_{0}^{3 / 2}} e^{-r / a_{0}}\\right]^{2} 4 \\pi r^{2} d r=\\frac{4}{a_{0}^{3}} r^{2} e^{-2 r / a_{0}} d r$$\n\n\n$$2 r e^{-2 r / a_{0}}-\\frac{2}{a_{0}} r^{2} e^{-2 r / a_{0}}=0$$\n\n\n$$2 r e^{-2 r / a_{0}}[1 - \\frac{r}{a_{0}}] = 0 \\implies r = a_{0} = 0.529 \u00c5$$\n\n-----------------------------------------------------\n\n#### Side Notes for 15.: \n\n$$P(r) = \\int_{0}^{\\pi} \\int_{0}^{2\\pi} \\int R^{2}|\\Psi(\\theta,\\phi)|^{2} r^{2}sin(\\theta)dr d\\theta d\\phi$$\n$$= \\int r^{2} R^{2} dr \\overbrace{ \\int_{0}^{\\pi} \\int_{0}^{2\\pi} \\underbrace{|\\Psi(\\theta,\\phi)|^{2}}_{\\frac{1}{4\\pi}}sin(\\theta) d\\theta d\\phi}^{1},$$\nhence \n\n$$\\int_{0}^{\\pi} \\int_{0}^{2\\pi} sin(\\theta) d\\theta d\\phi = 4\\pi$$\n\nTherefore, the general forms are:\n\n$$P(r) = 4\\pi r^{2} \\psi^{2}$$\n\nand \n\n$$ P(r) = r^{2}R(r)^{2}$$\n\n\n\n\n**16. State the definition of angular momentum.**\n\nThe total angular momentum is defined as \n\n$$ |J| = \\sqrt{l(l+1)}\\hbar,$$\n\nwhere each component can be represented as \n\n$$ |J| = \\sqrt{J_{x}^{2}+J_{y}^{2}+J_{z}^{2}}$$\n\n\n\n\n**17. State how angular momenta terms |J| and Jz are quantized for particle-on-a-ring (in terms of quantum numbers m and l.)**\n\n$$ |J| = \\sqrt{l(l+1)}\\hbar, $$\n\n**Multiples of Plancks constant.**\n\nwhere $l\\in \\{0,1,2,...\\}$,  $J_{z} = {-\\hbar, 0, \\hbar}$ and $m_{l} = \\{-1,0,1\\}$.\n\n**18. What are the key differences between valence bond theory and M.O. theory?**\n\nValance bond theory (VB) says electrons live in sparate valance orbitals $\\psi_{a},\\psi_{b}$. When they overlap a bond is formed. $\\psi_{_{VB}} = \\psi_{a}(1)\\psi_{b}(2)\\pm\\psi_{a}(2)\\psi_{b}(1)$ approximates by considering electrons in A.O valance shell.\n\n\nMolecular orbital theory (M.O.) says that neuclei share electrons and $\\psi$'s are spread over multiple nuclei.  M.O. theory also constructs linear combinations of A.O.'s and is able to predict bond orders, orbital overlap, and make predictions about bond characteristics.\n\n\n\n\n\n**19. Draw a $\\pi$ orbital as a sum of two p-orbitals $(2p_{z})_{a}$ and $(2p_{z})_{b}$, centered on nuclei $a$ and $b$, respectively. Write down a VB wavefunction for this arrangement.**\n\n\n\n\nSuggesting indistinguishable nature of the two electrons (ignoring spin):\n\n$$\\psi_{_{VB}} = (2p_{z})_{a} (1)\\space (2p_{z})_{b}(2)\\pm(2p_{z})_{a}(2)\\space(2p_{z})_{b}(1),$$\n\nwhere electron 1 is found in $(2p_{z})_{a}$ and also found in $(2p_{z})_{b}$.\n\n\n\n\n**20. Discuss why the peptide bond is planar, in terns of the concepts of resonance and hybridization.**\n\n\n\n\n\n**21. Which of the following multiple-electron wavefunctions are valid (i.e. are anti-symmetric)?**\n\nUse the inversion operator: $\\psi(x_{1},x_{2}) = - \\psi(x_{2},x_{1})$\n\n\n\n\n\n**a. $1s_{a}(1) + 1s_{b}(2)$**\n\n$\\psi = 1s_{a}(2) + 1s_{b}(1)$\n\n$\\therefore$ symmetric\n\n\n**b. $1s_{a}(1)\\space 1s_{b}(2) + 1s_{a}(2)\\space 1s_{b}(1)$**\n\n$\\psi = 1s_{a}(2) \\space 1s_{b}(1) + 1s_{a}(1)\\space 1s_{b}(2)$\n\n$\\therefore$ symmetric\n\n**c. $1s_{a}(1)\\space 1s_{b}(2) - 1s_{a}(2)\\space 1s_{b}(1)$**\n\n$\\psi = 1s_{a}(2)\\space 1s_{b}(1) - 1s_{a}(1)\\space 1s_{b}(2) = -(1s_{a}(1)\\space 1s_{b}(2) - 1s_{a}(2)\\space 1s_{b}(1))$\n\n$\\therefore$ antisymmetric\n\n\n\n**22. Is the overlap integral $S$ for the orbitals shown below non-zero? Why or why not? Will these orbitals form a chemical bond? If so, will it be a $\\sigma$ or a $\\pi$ bond? What kind of symmetry will might have, $g$ or $u$?**\n\n\n\n\n\n\n\n\nWhy not? Consider $CH_{4}$!\n\nHint: Look at the shaded regions. \n\n**Answer:**\n\n\n\nNow, consider $1s_{a} + 2(p_{z})_{b} $. Writing as a linear combination for the bonding:\n\n$$ \\psi(1,2) = 1s_{a}(1)\\space 2(p_{z})_{b}(2) + 1s_{a}(2)\\space 2(p_{z})_{b}(1)$$ \n\nApplying the inversion operator:\n\n$$ \\psi(2,1) = 1s_{a}(2)\\space 2(p_{z})_{b}(1) + 1s_{a}(1)\\space 2(p_{z})_{b}(2) = \\psi(1,2)$$ \n\n$\\therefore$ symmetric $\\rightarrow$ even.\n\n$\\sigma$-bond and $\\sigma_{g}$\n\n\n\n\n\n\n\n\n\n#### [Jump to table of contents.](#Table-of-Contents:)\n\n\n\n**11.27 Consider the electrostatic model of the hydrogen bond. The $N\u2013C$ distance of the hydrogen bonded groups in proteins, such as occur in an a helix, is $0.29 nm$. How much energy (in $kJ mol^{\u22121}$) is required to break the hydrogen bond**\n\n**NOTE:** partial charges (Units: $e^{-1}$) can be found in Table 11.2 \u2014\u2014 Atkins.\n\n**(a) in a vacuum ($\u03b5_{r} = 1$)**\n\n\n$$ E = -\\frac{q_{C}q_{H}}{4\\pi \\epsilon_{0}\\epsilon_{r}r_{CH}}+\\frac{q_{C}q_{N}}{4\\pi \\epsilon_{0}\\epsilon_{r}r_{CN}}+\\frac{q_{O}q_{H}}{4\\pi \\epsilon_{0}\\epsilon_{r}r_{OH}}+\\frac{q_{O}q_{N}}{4\\pi \\epsilon_{0}\\epsilon_{r}r_{ON}}$$\n\nNow, we take out $4\\pi \\epsilon_{0}\\epsilon_{r}$ and pull out $e^{2}$ from the numerator.\n\n$$ E = -\\frac{e^{2}}{4\\pi \\epsilon_{0}\\epsilon_{r}/e^{2}}(\\frac{q_{C}q_{H}/e^{2}}{r_{CH}}+\\frac{q_{C}q_{N}/e^{2}}{r_{CN}}+\\frac{q_{O}q_{H}/e^{2}}{r_{OH}}+\\frac{q_{O}q_{N}/e^{2}}{r_{ON}})$$\n\n\n\n$$ E = -\\frac{e^{2}}{4\\pi \\epsilon_{0}\\epsilon_{r}/e^{2}}(\\frac{(0.45)(0.18)/e^{2}}{r_{CH}}+\\frac{(0.45)(-0.36)/e^{2}}{r_{CN}}+\\frac{(-0.38)(0.18)/e^{2}}{r_{OH}}+\\frac{(-0.38)(-0.36)/e^{2}}{r_{ON}}) = 7.93x10^{-20} J$$\n\n$$ E =7.93x10^{-20} J *N_{A} = 47.8 kJ.mol^{-1}$$\n\n\n**(b) in a membrane (essentially a liquid hydrocarbon with $\u03b5_{r} = 2.0$)**\n\nSince $\\epsilon_{r}$ increases by a factor of 2, then the energy should decrease by a factor of 2. \n\n$$ E = 23.9 kJ.mol^{-1}$$\n\n**(c) in water ($\u03b5_{r} = 80.0$)?**\n\nSince $\\epsilon_{r}$ increases by a factor of 80, then the energy should decrease by a factor of 80. \n\n$$ E = 0.60 kJ.mol^{-1}$$\n\n<!--\nimport numpy as np\nqH = 0.18\nqN = -0.36\nqC = 0.45\nqO = -0.38\nrCN = 290\nrCO = 124\nrCH = 190\nrOH = 66\nrON=166\nrNH = 100\ne = 1.6002*10**(-19) # C\n_4pi_ep0 = 1.1127*10**(-10) # J^-1 C^2 m^-1\nNA = 6.0223*10**(23)\nV = e**2./(_4pi_ep0*(10**(-12.)))*(qC*qH/(rCH)+qC*qN/(rCN)+qO*qH/(rOH)+qO*qN/(rON))\nprint(-V)\nprint(-V*NA)\nprint(-V*NA/2)\n-->\n\n**11.44 We can explore bond torsion in ethane to understand the barrier to internal rotation of one bond relative to another in saturated carbon chains, such as those found in lipids. The potential energy of a $CH_{3}$ group in ethane as it is rotated around the $C\u2013C$ bond can be written $V = \\frac{1}{2} V_{0}(1 + cos(3\\phi))$, where f is the azimuthal angle (24) and $V_{0} = 11.6 kJ mol^{\u22121}$.**\n\n**(a) What is the change in potential energy between the trans and fully eclipsed conformations?**\n\n**(b) Show that for small variations in angle, the torsional (twisting) motion around the $C\u2013C$ bond can be expected to be that of a harmonic oscillator.**\n\n\n**(c) Estimate the vibrational frequency of this torsional oscillation.**\n\n\n\n\n#### <span style='color:blue'>7.</span>\n\n<p><strong>Computer Lab \u2013 Spartan 4</strong></p>\n\n<p><strong>Goal</strong>: The purpose of this lab is to illustrate how to use quantum chemical calculations to scan potential energy surfaces to determine molecular force field parameters. We will discuss two examples: (1) deriving the harmonic-oscillator force constant for a chemical bond, and (2) determining the preferred torsional minima for peptides.</p>\n<p><strong>Introduction</strong></p>\n<p>Last week we learned about calculating the energy of a protein as the sum of several pairwise energy terms (i.e. bonded terms, including bond distance, bond angle, and dihedral angle terms; and non-bonded terms, including electrostatics and van der Waals interactions). Such an energy function can be called a <em>force field</em>.</p>\n<p>Here, we will work through two examples illustrating how QM calculations can be used to parameterize bonded interactions. First, we will scan the energy <em>E</em><sup>el</sup>(<em>R</em>) of an H<sub>2</sub> molecule for different internuclear distance <em>R</em>. Then, we will scan peptide backbone dihedral angles to investigate preferred torsional minima for peptides.</p>\n<p><strong>Part 1: Potential energy surface for diatomic H<sub>2</sub>.</strong></p>\n<p>The energy of a bound diatomic molecule AB as a function of internuclear separation is described by its potential energy surface shown in Figure 1. The existence of a minimum of the potential energy surface (PES) implies there is a stable chemical bond between the two atoms. The minimum represents the equilibrium bond length <em>R</em><sub>e</sub> of the molecule.</p>\n\nThe energy of a bound diatomic molecule AB as a function of internuclear separation is described by its potential energy surface shown in Fig.1. The existence of a minimum of\n\n\n\n\n**Figure 1:** Potential energy surface of a diatomic molecule A-B.\n\n\nthe potential energy surface (PES) implies there is a stable chemical bond between the two atoms. The minimum represents the equilibrium bond length Re of the molecule. A molecule however is not completely frozen but can vibrate around the minimum with some vibrational frequency \u03bde. As the internuclear separation increases at values higher than minimum the energy increases also until the bond breaks and the two atoms are separated and they do not interact with each other any more. The energy at the dissociation limit is equal to the sum of the energies of the two atoms. The energy required to break the bond is the dissociation energy De. This potential can be described by a Morse potential\n\n$$E^{el}(R) = D_{e}\\{1 \u2212 exp [\u2212\\alpha(R \u2212 R_{e})]\\}^{2} + C$$\n\nwhere $\\alpha = \\sqrt{\\frac{k_{f}}{2D_{e}}}\udbff\udc00$. $k_{f}$ is the force constant defined as $k_{f} = (\\frac{d^{2}E^{el}}{dR^{2}})_{R=R_{e}}$.  The frequency of vibrational motion is given by:\n\n$$\\nu = \\frac{1}{2\\pi}\\sqrt{\\frac{k_{f}}{\\mu}}$$\n\nThe PES around the minimum can be approximated by a quadratic potential\n\n$$E^{el}(R) = \\frac{1}{2}k_{f}(R \u2212 R_{e})^{2} + c$$\n\nIn this case the vibration of molecules is described by a Harmonic Oscillator.\n\n#### Experimental procedure\n\n[Click here to use the Guest Server!](https://www.webmo.net/demo/index.html)\n\n**Step 1:** As a first step in the study of the diatomic molecule $H_{2}$ you will obtain the equilibrium bond distance. Follow the WebMO instructions to build $H_{2}$ and optimize its structure at the CAS(2,2)/6-31G(d) level of theory. Choose optimization +frequency from the menu. After the calculation is finished report the optimized equilibrium geometry $R_{e}$ and the vibrational frequency $\\nu_{e}$.\n At the minimum of the PES the first derivative of $E^{el}(R)$ with respect to $R$ is zero. The curvature is given by the second derivative $(\\frac{d^{2}E^{el}}{dR^{2}})$ which at a true minimum is positive.\nThe curvature is also related to the force constant and subsequently the vibrational\nfrequency via Eq. 2. The above input will calculate the vibrational frequency after the optimization is finished (keyword: opt freq).\n<span style=\"color: red\"></span>\n\n**Step 2:** a) Use WebMO to calculate the potential energy curve of <span style=\"color: red\">$H_{2}$</span> at the <span style=\"color: red\">CAS(2,2)/6- 31G(d)</span> level. Choose bond lengths starting at <span style=\"color: red\">0.5 \u00c5 and increasing at an interval of 0.1 \u00c5</span>. (0.5, 0.6, 0.7, ...). The input is shown below:\n\n\n<hr>\n\n```\n#N CAS(2,2)/6-31G(d) Scan\n\nH2\n\n0 1\nH\nH 1 B1\n\nB1 0.5 30 0.1\n```\n<hr>\n\n\n$$\\overbrace{B1}^{\\text{coordinate}} \\underbrace{0.5}_{\\text{bond length}} \\overbrace{30}^{\\text{# of calculations}} \\underbrace{0.1}_{\\text{interval}}$$\n\n\nUsing WebMO, build $H_{2}$ and choose a single point calculation at the CAS(2,2)/6- 31G(d) level at the job options window. Then go to the preview window and click on generate to generate the input. You will have to edit the input file so that it resembles the one above. Specifically you will have to change the SP keyword to SCAN. Then you will have to change the last line that gives the value of the coordinate B1. This should be (B1 0.5 30 0.1) as shown above. This line means that 30 single point calculations will be done where the bond length of $H_{2}$ will be varied. The first value will be 0.5 \u00c5 and then it will increase by 0.1 \u00c5 for 30 times. After you change the input submit the calculation. When the calculation is done, open the raw output file. Almost at the end of the file the summary of the calculation will be given. It will report:\n\n<hr>\n\n```\nScan completed.\n\n\nSummary of the potential surface scan: N B1 SCF\n\u2014- \u2014\u2014\u2014 \u2014\u2014\u2014\u2013\n1 0.5000 xxxxxx\n```\n\n<hr>\n\nand all the energies as a function of bond distance will be given. Plot the potential energy curve. Use the energy of the last point on the curve (which is close to the dissociation limit) to obtain the dissociation energy $D_{e}$.\n\n\n#### Questions:\n\n**1. Report the equilibrium geometry Re in \u00c5, vibrational frequency $\\nu_{e}$ in wavenumbers, and dissociation energy De in eV.**\n\n**2. Include a plot of the potential energy surface of $H_{2}$**\n\n\n\n\n#### [Jump to table of contents.](#Table-of-Contents:)\n\n\n```python\n%matplotlib inline\nimport plot as p\nimport numpy as np\nx,y = np.loadtxt(\"scan551933.csv\", skiprows=1, delimiter=\",\").transpose() # Energy is in Hartrees, where 1 Hartree = 27.2114 eV\ny = y*27.2114 # eV\nkf = 576. # N/m (tabulated value)\nmp = 1.672*10**(-27.);m = 1.*mp\nmu = m*m/(m+m) # kg\nDe, Re = (np.max(y)-np.min(y)), x[np.argwhere(y==np.min(y))][0,0]\nnu = 1/(2*np.pi)*np.sqrt(kf/mu) # Get calculated kf by taking second derivative (R=Re)\np.simple_plot(x,y,xlabel='Coordinate ($\\\\AA$)',ylabel='Energy (eV)',Type='line',color=False,fig_size=(8,4),\n              annotate_text=r'$R_{e} = %s \u00c5$'%Re+\"\\n\"+r'$D_{e} = %0.4G eV$'%De+\"\\n\"+r'$\\nu_{e} = %0.4G Hz$'%nu,\n              annotate_x=2.0,annotate_y=-29)\n```\n\n<p><strong>Part 2: Potential energy surface for peptide backbone dihedral angles</strong></p>\n<p><strong>Introduction</strong></p>\n<p>Last week we learned about calculating the energy of a protein as the sum of several pairwise energy terms (i.e. bonded terms, including bond distance, bond angle, and dihedral angle terms; and non-bonded terms, including electrostatics and van der Waals interactions). Such an energy function can be called a <em>force field</em>.</p>\n\n$$V(r)= \\sum_{\\text {bonds}} k_{b}\\left(b-b_{0}\\right)^{2}+\\sum_{\\text {angles }} k_{\\theta}\\left(\\theta-\\theta_{0}\\right)^{2}+\\sum_{\\text {torsions }} k_{\\phi}[\\cos (n \\phi+\\delta)+1] \\\\ +\\sum_{\\text {nonbond }\\\\ \\text{ pairs }}\\left[\\frac{q_{i} q_{j}}{r_{i j}}+\\frac{A_{i j}}{r_{i j}^{12}}-\\frac{C_{i j}}{r_{i j}^{6}}\\right]$$\n\n<p>The backbone dihedral angle (torsional) terms are of particular importance when developing force fields to describe the energetics of peptides. An incorrect torsional potential may bias protein conformations toward physically unrealistic conformations\u2014i.e. too much alpha-helix or too much beta-sheet structure.</p>\n<p>To get it right, all-atom force fields such as AMBER<a href=\"#fn1\" class=\"footnote-ref\" id=\"fnref1\"><sup>1</sup></a> have been parameterized by adjusting the force constants to match quantum mechanical calculations of the total energy of a peptide molecule as a function of \u03c6 and \u03c8 backbone dihedral angles. Our goal today is to perform a dihedral angle scan for the \u03c8 angle of an amino acid residue (alanine, or any of your choice).</p>\n<p>We will consider the following molecule:</p>\n\n<p><strong>Procedure</strong></p>\n<ol type=\"1\">\n<li><p><strong>Build the molecule</strong></p>\n<ol type=\"a\">\n<li><p>Start building a new molecule using <em>New Build</em>. In the right-hand panel, choose the <em>Peptide</em> menu, and click on \u201cAla\u201d (or another residue of your choice). Before adding it to your workspace, notice that you are given a choice of setting the dihedral angles (\u03b1, \u03b2, or Other). Click the \u201cOther\u201d button and set the custom dihedral angles to \u03c8 = -180\u02da, \u03c6= -60\u02da. Then click on the workspace to add the peptide.</p></li>\n<li><p>Next, add capping groups to the peptide. Use the <em>Organic</em> menu on the right-hand side to cap the N-terminus with an acetyl group (C=O)CH<sub>3</sub> and the C-terminus with an NH<sub>2</sub> group.</p></li>\n</ol></li>\n<li><p><strong>Create copies of the molecule at different torsion angles</strong></p>\n<ol start=\"3\" type=\"a\">\n<li><p>Go to Geometry &gt; Set Torsions. Several yellow \u201ccuffs\u201d should show on each rotatable bond. For each dihedral angle except the \u03c8 angle, click on the yellow cuff, and set <em>Conformations</em> to 0-fold = <strong>Off</strong>. Click on the \u03c8 angle and set Conformations to 20-fold (<b>9-fold</b>).</p></li>\n<li><p>Then, click the right-most button (with a black triangle pointing down) and generate a list of these conformers. If it goes well, you should be able to play an animation (left bottom) to see how it scans through.</p></li>\n</ol></li>\n<li><p><strong>Calculate the energy of each conformation</strong></p>\n<ol start=\"5\" type=\"a\">\n<li><p>In Setup &gt; Calculations\u2026 calculate \u201cEnergy\u201d (not Equilibrium Geometry!) at the HF 6-31G* level in Vacuum (This is actually the basis set for the original AMBER parameterization (1994). Click Submit to submit the calculations.</p></li>\n<li><p>It should take a minute or two \u2013 if you\u2019d like you can monitor the job using Options &gt; Local Monitor</p></li>\n</ol></li>\n<li><p><strong>Plot the results</strong></p>\n<ol start=\"7\" type=\"a\">\n<li><p>After the calculation finishes, go to Display &gt; Plots \u2026</p></li>\n<li><p>Click the green \u201c+\u201d to add a plot, with the molecule as the x-axis and E_kcal as the y-axis. Click the Merge button (little black triangle) to super impose the plot with the conformation. Cycle through to animation and see if you can identify the beta-sheet and alpha-helix minima.</p></li>\n</ol></li>\n</ol>\n<p><b>Questions:</b></p>\n    \n<p><b>1. What <b><u>intra</u></b>molecular forces do you think are important in determining these minima?</b></p>\n\n<p>Stabilization of peptide backbone (lowest energy) would take place at most favorable positions of lowest non-bonding interactions. Think about the peptide bond (between the carbonyl group of the first AA and amino group of the second AA) and its partial double bond character due to resonance. Varying $\\psi$ the $C\u2014C_{\\alpha}$ bond clearly shows the non-bonded interactions that play a role between the carbonyl \u2014 $NH_{2}$ as well as the carbonyl \u2014 carbonyl upon rotation. Take note of the proximal changes for each of the rotations.<br><b>Note: The $\\psi$ and $\\phi$ angles are the 2 DOF that allow polypeptides to fold.</b> </p>\n\n\n<p><strong><br />\n</strong></p>\n<p><strong>NOTE: This is the direction your scan should proceed:</strong></p>\n\n\n\n\n\n<br>\n\n\n<p><b>Figure 1.</b> Dihedral scan about the $\\psi$ angle of alanine with <b>N-term capped with aldehyde</b> and <b>C-terminus capped with an NH<sub>2</sub> group</b>.</p>\n\n<section class=\"footnotes\">\n<hr />\n<ol>\n<li id=\"fn1\"><p>Cornell, W. D., Cieplak, P., Bayly, C. I., Gould, I. R., Merz, K. M., Ferguson, D. M., et al. (1995). A second generation force field for the simulation of proteins, nucleic acids, and organic molecules. <em>Journal of the American Chemical Society</em>, <em>117</em>(19), 5179\u20135197. doi:10.1021/ja00124a002<a href=\"#fnref1\" class=\"footnote-back\">\u21a9</a></p></li>\n</ol>\n</section>\n\n\n\n#### [Jump to table of contents.](#Table-of-Contents:)\n\n#### <span style='color:blue'>8.</span>\n\n<p><strong>Computer Lab \u2013 Chimera 1</strong></p>\n<p><strong>Goal</strong>: The purpose of this lab is to get familiar with protein structures determined by X-ray crystallography vs. nuclear magnetic resonance methods.</p>\n<p><strong>Introduction</strong></p>\n<p>In this exercise, we will use a protein called MDM2 as an example. MDM2 is an important protein in cancer\u2014it has the ability to bind the transactivation domain of tumor suppressor protein p53, downregulating its ability to activate transcription. Many researchers have sought to develop anti-cancer drugs that target the binding site of MDM2, blocking p53 from binding, and thus upregulating the tumor suppressor activity of p53. Several of these drugs are currently in clinical trials.<a href=\"#fn_Cornell\" class=\"footnote-ref\" id=\"fnref_Cornell\"><sup>1</sup></a></p>\n<p>The first high-resolution atomic structure of MDM2 bound to p53 came from an X-ray crystal structure by Kussie et al. (1996).<a href=\"#fn_Hoe\" class=\"footnote-ref\" id=\"fnref_Hoe\"><sup>2</sup></a> This structure shows a small helical region of p53 that binds a hydrophobic cleft in MDM2. To get these proteins to co-crystallize well, constructs with only residues 17-125 of MDM2, and residues 15-29 of p53, were used. Only the atomic structures of residues 25-109 could be resolved, however.</p>\n\n\n<p style=\"text-align:center;font-wight:bold;\">The X-ray crystal structure of MDM2-p53 (PDB ID: 1YCR)</p>\n\n<p>In 2005, Uhrinova et al. used 2D NMR spectroscopy to determine the <em>apo</em> structure of MDM2 (\u201c<em>apo</em>\u201d = unbound by ligand).<a href=\"#fn_Kussie\" class=\"footnote-ref\" id=\"fnref_Kussie\"><sup>3</sup></a> This structure contains more residues (1-119) but most of the terminal regions are unstructured.</p>\n\n\n\n<p style=\"text-align:center;font-wight:bold;\">The NMR structure of <em>apo</em>-MDM2 (PDB ID: 1Z1M)</p>\n<p><strong>Viewing and visualizing PDB files</strong></p>\n<p>To find a given PDB structure, open a browser and go to <a href=\"http://pdb.org\">http://pdb.org</a>. In the search window, type in the PDB ID, which will bring you to the entry page. This page has a great deal of useful information about the protein sequence and structure.</p>\n<p>To view the contents of the deposited PDB file containing the atomic coordinates, click on the <strong>Display Files</strong> drop-down in the upper right and choose <strong>PDB File</strong>. The full contents (text) of the PDB file should be viewable in your browser.</p>\n<p>To view the molecular structure in 3D, open the <strong>Chimera</strong> application and choose <strong>File &gt; Fetch</strong> <strong>by ID \u2026</strong> Type the PDB ID into the text field and click <strong>Fetch</strong>. The ribbon structure of the protein should appear, which you can rotate in 3D by clicking and dragging.</p>\n\n<!-- Page 2 -->\n\n<p>Chimera Tips:</p>\n\n<ol type=\"1\">\n<li>\n<p>To view side chain atoms: Actions &gt; Atoms/Bonds &gt; show</p>\n</li>\n<li>\n<p>A number of \u201cpreset\u201d renderings are be found under the Presets menu</p>\n</li>\n<li>\n<p>To select atoms, Control-click</p>\n</li>\n<li>\n<p>To select multiple atoms Shift-Control click</p>\n</li>\n<li>\n<p>Option-click and mouse drag to translate the view</p>\n</li>\n<li>\n<p>If your view gets off-center for any reason, try Action &gt; Focus to recenter.</p>\n</li>\n</ol>\n\n<p><strong>Procedure</strong></p>\n<p>Use (1) the information in the Protein Data Bank (visual inspection of the *.pdb file, and molecular visualization in Chimera), and (2) the original publications (posted on Blackboard) to answer the questions below.</p>\n<p><strong>X-ray crystal structure of MDM2-p53</strong></p>\n<p><strong>PDB</strong>: The atomic coordinates for this structure are deposited in the Protein Data Bank</p>\n<p>under PDB ID: <strong>1YCR</strong>.</p>\n<p><strong>Publication</strong>: Kussie, P. H., Gorina, S., Marechal, V., Elenbaas, B., Moreau, J., Levine, A. J., &amp; Pavletich, N. P. (1996). Structure of the MDM2 oncoprotein bound to the p53 tumor suppressor transactivation domain. <em>Science</em>, <em>274</em>(5289), 948\u2013953.</p>\n<p>Last week we learned about X-ray crystallography, and how it can be used to determine the atomic structure of proteins. Recall that this involves: (1) collecting diffraction data (i.e. the intensities of a large number of diffraction spots and their identification with Miller indices and a unit cell), and (2) using a model of protein electron density to calculate (by Fourier Transform) computed structure factors <em>F</em><sub>c</sub> that can be compared to the observed structure factors |<em>F</em><sub>o</sub>|.<a href=\"#fn_Uhrinova\" class=\"footnote-ref\" id=\"fnref_Uhrinova\"><sup>4</sup></a></p>\n<p>The resolution of the computed electron density depends on the number of diffraction spots (i.e. the number of \u201creflections\u201d). To give you some sense of the resolution of the final model, consider Figure 1 from Kussie et al (1996) below:</p>\n\n\n\n<p><b>Figure.</b> MIR electron density map of the X. laevis MDM2-p53 interface at 3.0 A resolution, contoured at 1.0 a, with the refined 2.3 A resolution atomic model in a stick representation. Stereo view focuses on the interactions of Phe19, Trp23, and Leu26 of p53 (labeled) with the (x2 helix of MDM2.</p>\n<p>As you can see, the final model of the electron density really is \u201cblobby\u201d, but it is high-resolution enough that backbone and side-chain atoms (solid black lines, hard to see, I know) can be fit unambiguously. Some regions of this density may be too diffuse to fit (often the thermally mobile termini). For these regions, the protein structure is typically left undefined (hence, \u201cmissing residues\u201d are common in X-ray crystal structures.)</p>\n\n<!-- Page 3 -->\n\n<ol start=\"4\" type=\"1\">\n<li>\n<p>Note that we are careful here to denote <em>absolute values</em> of <em>F</em><sub>o</sub> because of the so-called \u201cphase problem\u201d in which only <em>intensities</em> can be measured, not phase shifts.</p>\n</li>\n</ol>\n\n\n<p style=\"text-align:center\"><b>Table 1.</b> Statistics from the crystallographic analysis.</p>\n\n\n\n\n\n<!-- Insert Table -->\n\n<p><strong>Questions</strong></p>\n\n<ol type=\"1\">\n<li>\n<p>Consider <strong>Table 1</strong> from Kussie et al. (1996), in which statistics are given for a number of similar crystal structures the authors obtained.</p>\n\n<ol type=\"a\">\n<li>\n<p>Why is the number of unique reflections smaller than the total number?</p>\n</li>\n    <p>The number of unique reflections represents a subset of the total measured reflections. The total number of measured reflections should contain measurements of equivalent symmetry elements.</p>    \n    \n<li>\n<p>Explain the correlation between the number of unique reflections and the resolution of the crystal structure.</p>\n</li>\n<p>The resolution increases with decreasing number of unique reflections.</p>\n</ol></li>\n<li>\n<p>The <em>R</em>-factor is a measure of the quality of the (electron density) model, defined as <em>R</em> = \u03a3|<em>F</em><sub>o</sub> - <em>F</em><sub>c</sub>|/ \u03a3|<em>F</em><sub>o</sub>|, where <em>F</em><sub>o</sub> and <em>F</em><sub>c</sub> are the observed and calculated structure factors, respectively. Because of the iterative refinement of computed structure factors from the observed data, there is a danger of overfitting. A more useful measure is called the <em>R</em><sub>free</sub> value, where 10% of the observed structure factors are left out of the data set, so they can be used for testing the predictions.</p>\n\n<ol start=\"3\" type=\"a\">\n<li>\n<p>Which should have the larger value, <em>R</em> or <em>R</em><sub>free</sub>?</p>\n</li>\n    <p>Rfree should\n<li>\n<p>Based on the reported values for (human) MDM2-p53, do you think overfitting is a problem for this structure?</p>\n</li>\n</ol></li>\n</ol>\n\n<p>3. Why doesn\u2019t this structure have any hydrogens?</p>\n\n<p>Number of electrons are so small for hydrogen, such that the scattering factor is extremely low and will not be detected.</p>\n\n\n<p>In Chimera, go to <strong>Tools</strong> &gt; <strong>Higher-Order Structure</strong> &gt; <strong>Unit Cell</strong>, and click <strong>Outline</strong>. Click on <strong>Make Copies</strong> to see the symmetrical copies of MDM2 inside the unit cell.</p>\n\n<ol start=\"4\" type=\"1\">\n<li>\n<p>What are the unit cell dimensions <em>a</em>, <em>b</em> and <em>c</em>? (in \u00c5, see also <a href=\"http://pdb.org\">http://pdb.org</a>)</p>\n</li>\n     <p>43.414, 100.546, 54.853</p>\n<li>\n<p>What <em>shape</em> is the unit cell?</p>\n</li>\n    <p>Rectangular prism</p>\n<li>\n<p>Visualize the side chains using wire-frame (<strong>Actions</strong> &gt; <strong>Atoms/Bonds</strong> &gt; <strong>Wire</strong>).</p>\n\n<ol type=\"a\">\n<li>\n<p>Based on what you can see, does it look like there are strong interactions between unit cell copies?</p>\n</li>\n<li>\n<p>How careful do you think we need to be about such crystal packing artifacts when interpreting X-ray structures of proteins?</p>\n</li>\n</ol></li>\n</ol>\n\n<p>Recall that the crystallographic B-factor reports how diffuse the model of electronic density is for each atom. It is highly correlated to thermal motion. In Chimera, color the protein by B-factor, using <strong>Actions</strong> &gt; <strong>Color</strong> &gt; <strong>all options\u2026</strong> &gt; <strong>Tools</strong> &gt; <strong>Render by Attribute</strong> (choose bfactor in the pull-down menu for Attribute:, then click Apply)</p>\n<p>7. What parts of the protein have the most thermal motion?</p>\n<p><strong>NMR structure of <em>apo-</em>MDM2</strong></p>\n<p><strong>PDB</strong>: The atomic coordinates for this structure are deposited in the Protein Data Bank</p>\n<p>under PDB ID: <strong>1Z1M</strong>.</p>\n<p><strong>Publication</strong>: Uhrinova, S., Uhrin, D., Powers, H., Watt, K., Zheleva, D., Fischer, P., et al. (2005). Structure of Free MDM2 N-terminal Domain Reveals Conformational Adjustments that Accompany p53-binding. <em>Journal of Molecular Biology</em>, <em>350</em> (3), 587\u2013 598. doi:10.1016/j.jmb.2005.05.010</p>\n<p>Solution structures of proteins are usually determined using 2D NMR spectroscopy. Two-dimensional techniques measure how the magnetization of one kind of nuclei (say, <sup>1</sup>H) is affected by another kind of nuclei (say, <sup>15</sup>N). The first step in 2D NMR is to <em>assign</em> the various magnetic resonances to particular protons. As long as the spectroscopic peaks are disperse (i.e. well-defined and far enough apart to be distinguished from one another), assignment is possible because resonance can only occur for nearby (through-bond) nuclei. For example, Figure 1 in</p>\n<p>Uhrinova et al. (2005) shows HSQC (heteronuclear single quantum coherence) spectra disperse enough to assign (a) backbone NH protons and (b) side-chain protons.</p>\n\n\n\n<p>Figure. Assigned HSQC spectra of MDM2<sup>N</sup>. (a) <sup>1</sup>H,<sup>15</sup>N HSQC spectrum. Folded peaks are shown in grey. <sup>H</sup>N\u2013<sup>N</sup>H assignments are indicated by residue number. (b) A portion of the <sup>1</sup>H,<sup>13</sup>C HSQC spectrum showing methyl groups, with assignments indicated by residue and atom identifier (based on CNS notation).</p>\n\n\n<!-- Page 4 -->\n<p>Once the peaks are assigned, studies of NMR relaxation times can determine the presence of Nuclear Overhauser Effects, or <strong>NOEs</strong>. An NOE is a short-range transfer of nuclear spin polarization from one nuclei to another that occurs through <em>space</em> (rather than through-bond). Like its optical cousin FRET (F\u00f6rster Resonance Energy Transfer), it is an induced-dipole-dipole interaction that falls off as ~1/<em>r</em><sup>6</sup>. If an NOE is observed between two protons, it means that they must be close in three-dimensional space, with the strength of the NOE related to proximity, for example:</p>\n\n<ol type=\"1\">\n<li>\n<p>Strong NOEs: 1.7 \u00c5 to 2.5 \u00c5</p>\n</li>\n<li>\n<p>Medium strong NOEs: 2.5 \u00c5 to 3.5 \u00c5</p>\n</li>\n<li>\n<p>Medium weak NOEs: 3.5 \u00c5 to 4.5 \u00c5</p>\n</li>\n<li>\n<p>Weak NOEs: 4.5 \u00c5 to 5.5 \u00c5</p>\n</li>\n</ol>\n\n<p>A set of measured NOE distances can put enough restraints on the set of possible protein structures, so as to completely determine the solution conformation. A computer is used to explore possible structures that best satisfy the NOE distance restraints, generating an <em>ensemble</em> of different conformations, each equally compatible with the experimental restraints.</p>\n<p><strong>Questions</strong></p>\n<p>In Chimera, load structure <strong>1Z1M</strong>.</p>\n\n<ol type=\"1\">\n<li>\n<p>Why does this structure include protons, whereas the X-ray crystal structure does not?</p>\n</li>\n<li>\n<p>Why are there so many structures in this PDB?</p>\n</li>\n<li>\n<p>Obviously, there are very few NOE distance restraints for the N-terminal region. The modeled ensemble has many possible conformations for this region. How well do you think this represents reality? In other words: how much is the conformational heterogeneity an artifact of the computer models used for structural refinement, versus a real feature of the MDM2 N-terminal region? Can you think of any other experimental biophysical methods that you could use to answer this question?</p>\n</li>\n</ol>\n\n<p>Bonus: Load both the X-ray structure (1YCR) and the NMR structure (1Z1M) into Chimera and align them using <strong>Tools</strong> &gt; <strong>Structure Comparison</strong> &gt; <strong>MatchMaker</strong> (select 1YCR as the reference, and shift-click to select all NMR structures to match).</p>\n<p>4. Can you see any changes in the binding cleft as described by Uhrinova et al.?</p>\n\n<hr>\n<ol>\n<li id=\"fn_Cornell\"><p>Cornell, W. D., Cieplak, P., Bayly, C. I., Gould, I. R., Merz, K. M., Ferguson, D. M., et al. (1995). A second generation force field for the simulation of proteins, nucleic acids, and organic molecules. <em>Journal of the American Chemical Society</em>, <em>117</em>(19), 5179\u20135197. doi:10.1021/ja00124a002<a href=\"#fnref_Cornell\" class=\"footnote-back\">\u21a9</a></p></li>\n<li id=\"fn_Hoe\"><p>Hoe, K. K., Verma, C. S., &amp; Lane, D. P. (2014). Drugging the p53 pathway: understanding the route to clinical efficacy. <em>Nature Reviews Drug Discovery</em>, <em>13</em>(3), 217\u2013236. doi:10.1038/nrd4236<a href=\"#fnref_Hoe\" class=\"footnote-back\">\u21a9</a></p></li>\n<li id=\"fn_Kussie\"><p>Kussie, P. H., Gorina, S., Marechal, V., Elenbaas, B., Moreau, J., Levine, A. J., &amp; Pavletich, N. P. (1996). Structure of the MDM2 oncoprotein bound to the p53 tumor suppressor transactivation domain. <em>Science</em>, <em>274</em>(5289), 948\u2013953.<a href=\"#fnref_Kussie\" class=\"footnote-back\">\u21a9</a></p></li>\n<li id=\"fn_Uhrinova\"><p>Uhrinova, S., Uhrin, D., Powers, H., Watt, K., Zheleva, D., Fischer, P., et al. (2005). Structure of Free MDM2 N-terminal Domain Reveals Conformational Adjustments that Accompany p53-binding. <em>Journal of Molecular Biology</em>, <em>350</em>(3), 587\u2013598. doi:10.1016/j.jmb.2005.05.010<a href=\"#fnref_Uhrinova\" class=\"footnote-back\">\u21a9</a></p></li>\n</ol>\n\n#### [Jump to table of contents.](#Table-of-Contents:)\n\n#### <span style='color:blue'>9.</span>\n\n\n<p><strong>Computer Lab \u2013 Chimera 2</strong></p>\n<p><strong>Goal</strong>: The purpose of this lab is to get familiar analyzing protein-protein interfaces, and examine some of the energetic factors that contribute to favorable binding.</p>\n<p><strong>Introduction</strong></p>\n<p>Recall our friend from the last exercise, the MDM2-p53 complex (PDB ID: 1YCR).</p>\n\n<p style=\"text-align:center;font-wight:bold;\">The X-ray crystal structure of MDM2-p53 (PDB ID: 1YCR)</p>\n<p>Let\u2019s investigate how the p53 helix interacts with the MDM2 receptor.</p>\n<p><strong>Finding interacting residues</strong></p>\n<ol type=\"1\">\n<li><p><u>Load the structure</u> using <strong>File</strong> &gt; <strong>Fetch by ID</strong> \u2026 The ribbon structure of the protein complex should be shown</p></li>\n<li><p><u>Select the p53 helix</u> by Control-clicking (holding the CNTL key and clicking with the mouse) on p53, then press the up-arrow key to select the entire chain.</p></li>\n<li><p><u>Find the receptor residues interacting with p53</u> using <strong>Tools &gt; Surface/Binding Analysis</strong>.</p>\n<ol type=\"a\">\n<li><p>In the \u201cAtoms to Check\u201d panel, click on the \u201cDesignate\u201d buttons with the correct options so as to calculate interactions between the p53 helix (selected) and other atoms in the model.</p></li>\n<li><p>In the \u201cClash/Contact Parameters\u201d panel, click on \u201cContact\u201d (not \u201cClash\u201d). Then click on \u201cApply\u201d below.</p></li>\n<li><p>You should see a number of atoms in the helix and receptor selected. To select the <em>residues</em> involved, press the up-arrow key.</p></li>\n<li><p>Visualize these residues using <strong>Actions</strong> &gt; <strong>Atoms/Bonds</strong> &gt; <strong>show</strong>. It may be helpful to <strong>Actions</strong> &gt; <strong>Color</strong> &gt; <strong>by element</strong>. (rendering as wire with a width of 4 works well too)</p></li>\n</ol></li>\n</ol>\n<p><strong><br />\n</strong></p>\n<p><strong>Questions</strong></p>\n<p><b>1. Which residues of p53 have the most interactions with the MDM2 receptor?</b></p>\n<p><b>2. Which residues would you say are making hydrophobic interactions, and which have polar interactions?</b></p>\n<p><strong>Measuring surface area changes upon binding</strong></p>\n<ol type=\"1\">\n<li><p><span class=\"underline\">Select the entire complex</span> by control-clicking on any residue, and pressing the up-arrow key until the entire structure is selected.</p></li>\n<li><p><span class=\"underline\">Show the entire surface</span> using <strong>Actions</strong> &gt; <strong>Surface &gt; show</strong>.</p></li>\n<li><p><span class=\"underline\">Calculate the total volume and surface area</span> using <strong>Tools &gt; Surface/Binding Analysis &gt; Measure Volume and Area</strong>. The values are reported in units of \u00c5<sup>3</sup> and \u00c5<sup>2</sup>, respectively. Write down these values in the table below.</p></li>\n</ol>\n\n<p>Repeat these calculations for \u2026</p>\n\n<ol type=\"a\">\n<li><p>\u2026 the MDM2 receptor by itself (select the p53 helix and delete it using <strong>Actions</strong> &gt; <strong>Atoms/Bonds</strong> &gt; <strong>delete</strong>.), and</p></li>\n<li><p>\u2026 the p53 helix by itself (reload 1YCR, select MDM2 only and delete it)</p></li>\n</ol>\n\n<hr>\n\n\n\n<h4>Chimera Commands:</h4>\n<p>We can obtain these calculations sing the command line interface:</p>\n<p><strong>Tools</strong> &gt; <strong>General Controls </strong> &gt; <strong>Command Line</strong></p>\n\n<p>We can generate a surface using the following command:</p>\n\n<code>surface</code>\n\n<p>You will need to generate separate surfaces for each chain. To select chain <b>A</b>:<code>sel :.A</code>; To select chain <b>B</b>:<code>sel :.B</code>; To select the surface <code>sel #0:?</code></p>\n<p>Once the surface is generated, measuing the surface area is easily obtained using the <code>measure</code> command:</p>\n\n<code>measure area #0:?</code>\n\n\n<code>measure volume #0:?</code>\n\n<a href=\"https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/measure.html#buriedArea\">Chimera help page for buried surface area calculations</a>\n\n<code>measure buriedArea :.A :.B</code>\n\n\n<a href=\"https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/measure.html#buriedArea\">Chimera help page for buried surface area calculations</a>\n\n\n\n\n\n<hr>\n\n<!--\n<table>\n<thead>\n<tr class=\"header\">\n<th></th>\n<th>1YCR (entire complex)</th>\n<th>MDM2</th>\n<th>p53</th>\n</tr>\n</thead>\n<tbody>\n<tr class=\"odd\">\n<td>Volume (\u00c5<sup>3</sup>)</td>\n<td></td>\n<td></td>\n<td></td>\n</tr>\n<tr class=\"even\">\n<td>Surface Area (\u00c5<sup>2</sup>)</td>\n<td></td>\n<td></td>\n<td></td>\n</tr>\n</tbody>\n</table>\n-->\n\n\n\n<table>\n<thead>\n<tr class=\"header\">\n<th></th>\n<th>1YCR (entire complex)</th>\n<th>MDM2</th>\n<th>p53</th>\n</tr>\n</thead>\n<tbody>\n<tr class=\"odd\">\n<td>Volume (\u00c5<sup>3</sup>)</td>\n<td>$13.07x10^{3}$</td>\n<td>$11.11x10^{3}$</td>\n<td>1531</td>\n</tr>\n<tr class=\"even\">\n<td>Surface Area (\u00c5<sup>2</sup>)</td>\n<td>4556</td>\n<td>4354</td>\n<td>1092</td>\n</tr>\n</tbody>\n</table>\n\n\n<p><strong>Questions</strong></p>\n<p><b>1. What is the total change in surface area upon binding of the p53 helix to MDM2?</b></p>\n\n$$4354 + 1092 \u2013 4556 = 890 \u00c5^{2}$$\n\n<p><b>2. Using the data from Figure 1a of Chen et al. (2013) below, make a rough estimate of the binding affinity of p53 helix (i.e. its dissociation constant <em>K</em><sub>d</sub>). Ask your TA for the actual answer</b></p>\n\n$$ {K_{d}}_{Exp} = 410 nM$$\n\n$${K_{d}}_{Approx} = 10^{log_{10} K_{d}} =  10^{-6}M = 1 uM = 1000 nM$$ \n\n\n\n<p><strong>Figure 1a</strong> from Chen et al. (2013)<a href=\"#fn1\" class=\"footnote-ref\" id=\"fnref1\"><sup>1</sup></a></p>\n<section class=\"footnotes\">\n<hr />\n<ol>\n<li id=\"fn1\"><p>Chen, J., Sawyer, N., &amp; Regan, L. (2013). Protein-protein interactions: General trends in the relationship between binding affinity and interfacial buried surface area. <em>Protein Science</em>, <em>22</em>(4), 510\u2013515. doi:10.1002/pro.2230<a href=\"#fnref1\" class=\"footnote-back\">\u21a9</a></p></li>\n</ol>\n</section>\n\n\n\n#### [Jump to table of contents.](#Table-of-Contents:)\n\n#### <span style='color:blue'>10.</span>\n\n<!--\nHW 7: Chap 12: #10, 11, 12, 14, 19\nHW 8: Chapter 12: #25, 37*, 39, 40**\nChapter 11: #1, 2, 17 (Hint: see equation on p. 408), 20, 22, 25\n-->\n\n\n**HW Review:**\n\n**Chapter 11**\n\n**11.1 What features in an X-ray diffraction pattern suggest a helical conformation for a biological macromolecule?**\n\n*See Notes*\n\n\n**11.2 Describe the phase problem in X-ray diffraction and explain how it may be overcome.**\n\n*See Notes*\n\n<!--\n$$I \\propto |F_{hkl}|^{2}$$\n\nFrom the electron density ditribution $\\rho(r)$ we get \n\n$$|F_{hkl}|^{2} = |F_{hkl}|x|F_{hkl}|e^{-i\\alpha hkl}e^{i\\alpha hkl} = $$\n-->\n\n**11.12 It is observed that the critical micelle concentration of sodium dodecyl sulfate in aqueous solution decreases as the concentration of added sodium chloride increases. Explain this effect.**\n\n\n\nAs $[\\text{Sodium chloride}]$ $\\uparrow$ the partial charge of the dodeyl sulfate heads are shielded by NaCl ions and as a result forms larger miscelles and $[\\text{Sodium dodecyl sulfate}] \\downarrow$.\n\nTherefore, \n\n$$[\\text{Sodium dodecyl sulfate}] \\downarrow as [\\text{Sodium chloride}] \\uparrow$$\n\n<!--\n**11.17 At 20\u00b0C the diffusion coefficient of a macromolecule is found to be 8.3 \u00d7 10\u221211 m2 s\u22121. Its sedimentation constant is 3.2 Sv in a solution of density 1.06 g cm\u22123. The specific volume of the macromolecule is 0.656 cm3 g\u22121. Determine the molar mass of the macromolecule.**\n**11.20 Draw a set of points as a rectangular array base do n unit cells of side a and b, and mark the planes with Miller indices (10), (01), (11), (12), (23), (41), and (41).**\n**11.22 In a certain unit cell, planes cut through the crystal axes at (2a,3b,c), (a,b,c), (6a,3b,3c), and (2a,\u22123b,\u22123c). Identify the Miller indices of the planes.**\n-->\n\n\n**11.25 The glancing angle of a Bragg reflection from a set of crystal planes separated by 97.3 pm is 19.85\u00b0. Calculate the wavelength of the X-rays.**\n\n\n$$\\lambda = 2dsin(\\theta)$$\n\n<!--\n**12.10 When light of wavelength 410 nm passes through 2.5 mm of a solution of the dye responsible for the yellow of daffodils at a concentration 0.433 mmol dm\u22123, the transmission is 71.5 per cent. Calculate the molar absorption coefficient of the coloring matter at this wavelength and express the answer in centimeters squared per mole (cm2 mol\u22121).**\n**12.11 An aqueous solution of a triphosphate derivative of molar mass 602 g mol\u22121 was prepared by dissolving 30.2 mg in 500 cm3 of water and a sample was transferred to a cell of length 1.00 cm. The absorbance was measured as 1.011. (a) Calculate the molar absorption coefficient. (b) Calculate the transmittance, expressed as a percentage, for a solution of twice the concentration.**\n-->\n\n**Chapter 12**\n\n**12.12 A swimmer enters a gloomier world (in one sense) on diving to greater depths. Given that the mean molar absorption coefficient of\nseawater in the visible region is 6.2 \u00d7 10\u22125 dm3 mol\u22121 cm\u22121, calculate the depth at which a diver will experience (a) half the surface intensity of light and (b) one-tenth that intensity.**\n\n\n### Derivation of Beer's Law:\n\nHere is an image of the situation we wish to model:\n\n\n\nThe density of particles, $\\rho$ and the absorption coefficient, $\\alpha$ multiplied by the intensity, I shown in the  1st order differential equation:\n$$ -\\frac{\\partial{I}}{\\partial{x}} = I \\alpha \\rho $$\n\nCombine like-terms to each side of the equation:\n\n$$\\int_{I_{0}}^{I}  \\frac{\\partial{I}}{I} = -\\int_{0}^{x} \\alpha \\rho \\partial{x} $$\n\n\nWe know that $\\int \\frac{1}{x}dx = ln(x)$, so\n\n$$ln(\\frac{I}{I_{0}}) = - \\alpha \\rho x, $$\n\n\n-----------------\n\nTo get the general solution of the D.E we can take the exponential of both sides \n\n$$\\frac{I}{I_{0}} = e^{-\\alpha \\rho x} $$\n\n**General Solution to the D.E**:\n\n$$I (x) = I_{0} e^{-\\alpha \\rho x}$$\n\n--------------------------\n\nOtherwise, to continue deriving Beer's Law we can use the property of logarithms:\n\n$$-ln(\\frac{I}{I_{0}}) = ln(\\frac{I_{0}}{I}) = \\alpha \\rho x, $$\n\n\nand since we know the following\n\n$$log_{10}(x) = \\frac{ln(x)}{ln(10)},$$\n\nthen we can say\n\n$$ log_{10}(\\frac{I_{0}}{I}) = \\frac{\\alpha \\rho x}{ln(10)}$$\n\n\nFinally, we can say that $\\rho \\propto c$.  We can also simplify further by saying $\\epsilon =\\frac{\\alpha}{ln(10)}$, which has units of $M^{-1}cm^{-1}$ and $x = b$, where b is in cm.\n\n$$ A = ln(\\frac{I_{0}}{I}) = \\epsilon b c$$\n\nNow, solving for the path length $b$ gives the following expression with $c_{H_{2}O} = \\rho/MW$ and $I = 0.5I_{0}$.\n\n\n$$ b = \\frac{ln(\\frac{I_{0}}{0.5I_{0}})}{\\epsilon (\\rho/MW)} =  \\frac{0.301}{(6.2 x 10^{-5} dm^{3}. mol^{-1}.cm^{-1}) (55.5 mol.dm^{-3})} = 87 cm $$\n\n**Note**, since the information regarding salt water concentration is not provided in the question we approximated the concentration by with values for $H_{2}O$.\n\n\n<!--\n**12.14 The molar absorption coefficients of tryptophan and tyrosine at 240 nm are 2.00 \u00d7 103 dm3 mol\u22121 cm\u22121 and 1.12 \u00d7 104 dm3 mol\u22121 cm\u22121, respectively, and at 280 nm they are 5.40 \u00d7 103 dm3 mol\u22121 cm\u22121 and 1.50 \u00d7 103 dm3 mol\u22121 cm\u22121. The absorbance of a sample obtained by hydrolysis of a protein was measured in a cell of thickness 1.00 cm and was found to be 0.660 at 240 nm and 0.221 at 280 nm. What are the concentrations of the two amino acids?**\n-->\n\n**12.19 Assume that the electronic states of the p electrons of a conjugated molecule can be approximated by the wavefunctions of a particle in a one-dimensional box and that the dipole moment can be related to the displacement along this length by m = \u2212ex. Show that the transition probability for the transition n = 1 $\\rightarrow$ n = 2 is nonzero, whereas that for n = 1 $\\rightarrow$ n = 3 is zero.**\n\nWe can use **parity** to **show** that the transition probability for the transition n = 1 $\\rightarrow$ n = 2 is nonzero.\n\nLet $\\psi_{n} = \\sqrt{\\frac{2}{L}}sin(\\frac{n\\pi x}{L})$, where\n\n$$\\mu_{fi} = < \\psi_{f} | \\vec{\\mu} | \\psi_{i} > $$\n\n\nNext, let (+) be an even function (does not change sign under inversion transformation) and (-) be an odd function such that:\n\n\n$$(+)(-) = (-) \\implies \u2260 0$$\n\n\n$$(+)(+) = (-)(-) = (+) \\implies = 0$$\n\n\nFor n = 1 $\\rightarrow$ n = 2\n\n$$\\mu_{21} = <\\psi_{2} | \\vec{\\mu} |\\psi_{1} > \\implies (-)(+) = (-) \\implies <\\psi_{2} | \\vec{\\mu} | \\psi_{1} >  \\neq 0$$\n\n\nFor n = 1 $\\rightarrow$ n = 3\n\n$$\\mu_{31} = <\\psi_{3} | \\vec{\\mu} |\\psi_{1} > \\implies (+)(+) = (+) \\implies <\\psi_{3} | \\vec{\\mu} | \\psi_{1} > = 0 $$\n\n\n\n\n**12.25 How many normal modes of vibration are there for (a) $NO_{2}$, (b) $N_{2}O$, (c) cyclohexane, and (d) hexane?**\n\nThere are $3N-6$ and $3N-5$ vibrational modes (in which N is the number of atoms in molecule) for non-linear and linear molecules; respectively.\n\n\n**(a)** $NO_{2}$, Non-linear; $3N-6 = 3(3)-6 = 3$\n\n**(b)** $N_{2}O$, linear; $3N-5 = 3(3)-5 = 4$\n\n**(c)** cyclohexane, non-linear; $3N-6 = 3(18)-6 = 48$\n\n**(d)** hexane, non-linear; $3N-6 = 3(20)-6 = 54$\n\n\n\n-----------------------------------------\n\n**SIDE NOTES:**\n\n### Rates of various processes\n\n| $\\text{Process}$ | $\\text{Timescales (s)}$ | $\\text{Radiative}$ | $\\text{Transition}$ |\n| :--: | :--: | :--: | :--: |\n| IC         | $10^{-14}-10^{-11}$ | N  | $S_{n} \\to S_{1}$ |\n| Vib Relax  | $10^{-14}-10^{-11}$ | N  | ${S_{n}}^{*} \\to S_{n}$  |\n| Abs        | $10^{-15}$          | Y  | $S_{0} \\to S_{n}$ |\n| Fluor      | $10^{-9}-10^{-7}$   | Y  | $S_{1} \\to S_{0}$  |\n| ISC        | $10^{-8}-10^{-3}$   | N  | $S_{1} \\to T_{1}$  |\n| Phos       | $10^{-4}-10^{0}$   | Y  | $T_{1} \\to S_{0}$  |\n\n\n- timescale of FRET are typically in ns \n\n\n-----------------------------------------\n\n\n\n**12.37 When benzophenone is illuminated with ultraviolet radiation, it is excited into a singlet state. This singlet changes rapidly into a triplet, which phosphoresces. Triethylamine acts as a quencher for the triplet. In an experiment in methanol as solvent, the phosphorescence intensity Iphos varied with amine concentration as shown below. A time-resolved laser spectroscopy experiment had also shown that the half-life of the fluorescence in the absence of quencher is 29 ms. What is the value of $k_{Q}$?**\n\n\n| $Species$ | $\\text{}$ | $\\text{}$ | $\\text{}$ |\n| :--: | :--: | :--: | :--: |\n| $[Q]/(mol\\space dm^{\u22123})$ | 0.0010 | 0.0050 | 0.0100 |\n| $I_{phos}/(A.U.)$ | 0.41 | 0.25 | 0.16|\n\n\nFirst, we need to write out the mechanism that is given in the question:\n\n>When benzophenone is illuminated with ultraviolet radiation, it is excited into a singlet state. \n\n$$ M + h\\nu_{i} \\rightarrow M^{*} \\tag{1}$$\n\n>This singlet changes rapidly into a triplet, which phosphoresces.\n\n$$ M^{*} \\rightarrow M + h\\nu_{phos} \\tag{2}$$\n\n>Triethylamine acts as a quencher for the triplet.\n\n$$ M^{*} + Q \\rightarrow M + Q \\tag{3}$$\n\n\n<hr>\n\nTo model this process, we apply the steady state approximation on $[M^{*}]$ to obtain $I_{phos}$... (Do this to get your own \"stern-volmer\" equation that models what the questions provides).\n\n**Steady State** is an assumption that the rate of (production/destruction) is equal to zero i.e., at equilibrium. \n\n$$\\frac{d[M^{*}]}{dt} = I_{abs} - k_{Q}[Q][M^{*}]-k_{phos}[M^{*}]=0$$\n\n$$ \\implies (-k_{Q}[Q]-k_{phos})[M^{*}] = -I_{abs} \\implies [M^{*}] = \\frac{I_{abs}}{k_{Q}[Q]+k_{phos}},$$\n\nand we know that $I_{phos} = k_{phos}[M^{*}]$, so \n\n$$ I_{phos} = k_{phos} \\frac{I_{abs}}{k_{Q}[Q]+k_{phos}}$$\n\nWe can take the inverse of $I_{phos}$ to get the equation in the form of a line:\n\n$$ \\frac{1}{I_{phos}} =  \\frac{1}{I_{abs}}  + \\frac{k_{Q}[Q]}{k_{phos}I_{abs}}$$\n\nNow, we plot the data that was given and extract the slope...\n\n\n```python\n%matplotlib inline\nimport plot as p\nimport numpy as np\nQ = np.array([0.0010,0.0050, 0.0100])\nIphos = np.array([0.41, 0.25, 0.16])\nx,y = Q,1/Iphos\np.simple_plot(x,y,xlabel=r'$[Q]$',ylabel=r'${I_{phos}}^{-1}$',Type='scatter',color=False,fig_size=(8,4),\n              fit=True, order=1, annotate_text=r\"$slope=k_{Q}/(k_{phos}I_{abs})$\",annotate_x=-0.005, annotate_y=5.5)\n```\n\nTherefore, the linear fit gives:\n$$I_{phos}^{-1}=(424.5302 dm^{3} mol )[Q]+(1.966), $$\n\nwhere $\\frac{k_{Q}}{k_{phos}I_{abs}} = 424.5302 dm^{3} mol $. \n\nTherefore,\n\n$$k_{Q} = \\frac{(24.5302 dm^{3} mol)(2.39x10^{4} s^{-1})}{1.97} = 5.2x10^{6} dm^{3} mol^{-1} s^{-1}  $$\n\n<!--\nThe quantum efficiency of fluorescence is $\\phi_{F}$, where \n$$\\phi_{F} = \\frac{\\text{rate of fluor}}{I_{abs}} = \\frac{k_{F} [M^{*}]}{I_{abs}} $$\n$$\\phi_{F} = \\frac{\\text{rate of fluor}}{I_{abs}} $$\nObserved fluorescence lifetime $\\tau_{0}$ is defined as \n$$\\tau_{0} = \\frac{\\phi_{F}}{k_{F}} $$\nThe question gives data for $I_{phos}$, and you need to extract the slope to obtain $k_{Q}$.\n-->\n\n\n\n\n\n\n\n\n\n\n#### [Jump to table of contents.](#Table-of-Contents:)\n\n**12.39 The F\u00f6rster theory of resonance energy transfer and the basis for the FRET technique can be tested by performing fluorescence measurements on a series of compounds in which an energy donor and an energy acceptor are covalently linked by a rigid molecular linker of variable and known length. L. Stryer and R.P. Haugland, Proc. Natl. Acad. Sci. USA 58, 719 (1967), collected the following data on a family of compounds with the general composition dansyl-(l-prolyl)n-naphthyl, in which the distance R between the naphthyl donor and the dansyl acceptor was varied by increasing the number of prolyl units in the linker:**\n\n\n| $\\text{}$ | $\\text{}$ | $\\text{}$ | $\\text{}$ | $\\text{}$ | $\\text{}$ | $\\text{}$ | $\\text{}$ | $\\text{}$ | $\\text{}$ | $\\text{}$ |\n| :--: | :--: | :--: | :--: | :--: | :--: | :--: | :--: | :--: | :--: | :--: | \n| $R/nm$ | 1.2 | 1.5 | 1.8 | 2.8 | 3.1 | 3.4 | 3.7 | 4.0 | 4.3 | 4.6 |\n| $\\eta_{T}$ | 0.99 | 0.94 | 0.97 | 0.82 | 0.74 | 0.65 | 0.40 | 0.28 | 0.24 | 0.16 |\n\n\n\n**Are the data described adequately by the F\u00f6rster theory (eqns 12.26 and 12.27)? If so, what is the value of $R_{0}$ for the naphthyl\u2013dansyl pair?**\n\n##### F\u00f6rster theory:\n\nStates that the efficiency of resonance energy transfer is related to the distance $R$ between donor-acceptor pairs by\n\n$$\\eta_{T} = \\frac{{R_{0}}^{6}}{{R_{0}}^{6} + {R}^{6}}, $$\n\nwhere $R_{0}$ is the distance at which $50 \\%$ of the energy is transfered from donor to acceptor, and $R$ is the distance between donor and acceptor.\n\nFirst, we need to rearrange the F\u00f6rster theory equation into a linearized form. \n\n$$ \\frac{1}{\\eta_{T}} = \\frac{{R_{0}}^{6} + {R}^{6}}{{R_{0}}^{6}} = 1 + (\\frac{R}{R_{0}})^{6}$$\n\nNow, we are able to plot the data:\n\n\n\n```python\n%matplotlib inline\nimport plot as p\nimport numpy as np\nR = np.array([1.2, 1.5, 1.8, 2.8, 3.1, 3.4, 3.7, 4.0, 4.3, 4.6])\nnT = np.array([0.99, 0.94, 0.97, 0.82, 0.74, 0.65, 0.40, 0.28, 0.24, 0.16])\nx,y = R**6,1/nT\np.simple_plot(x,y,xlabel=r'$(R/(nm))^{6}$',ylabel=r'${\\eta_{T}}^{-1}$',Type='scatter',color=False,fig_size=(8,4),fit=True, order=1)\n```\n\n<!--\n**12.40 An amino acid on the surface of a protein was labeled covalently with 1.5-I-AEDANS and another was labeled covalently with FITC. The fluorescence quantum yield of 1.5-I-AEDANS decreased by 10 per cent due to quenching by FITC. What is the distance between the amino acids? Hint: see Table 21.6.**\nF\u00f6rster theory:\n$$\\eta_{T} = \\frac{{R_{0}}^{6}}{{R_{0}}^{6} + {R}^{6}}, $$\nwhere $R_{0} = 4.9 nm$ (from table) and we know that the fluorescence quantum yield is decreased by $10 \\%$ $\\implies \\phi_{F} = 0.9\\phi_{F,0}$. Now, \n$$ \\eta_{T} = 1 - \\frac{\\phi_{F}}{\\phi_{F,0}}  = 1 - \\frac{0.9\\phi_{F,0}$}{\\phi_{F,0}}  = 0.10$$\n-->\n\n\n\n\n#### [Jump to table of contents.](#Table-of-Contents:)\n\n#### <span style='color:blue'>11.</span>\n\n\n<h3>Midterm Review #2:</h3>\n\n\n<!--\n<p><strong>Physical constants</strong></p>\n<p>Boltzmann\u2019s constant <em>k</em><sub>B</sub> = 1.38 \u00d7 10<sup>-23</sup> J K<sup>-1</sup></p>\n<p>Avogadro\u2019s constant <em>N</em><sub>A</sub> = 6.022 \u00d7 10<sup>23</sup> mol<sup>\u22121</sup></p>\n<p>Ideal gas constant <em>R</em> = <em>k</em><sub>B</sub> <em>N</em><sub>A</sub> = 8.314 J\u2009K<sup>-1</sup>\u2009mol<sup>-1</sup></p>\n<p>= 1.987 cal\u2009K<sup>-1</sup>\u2009mol<sup>-1</sup></p>\n<p>bar (pressure) 1 bar = 10,000 Pa. = 10,000 N m<sup>-2</sup></p>\n<p>= 0.987 atm</p>\n<p>Planck\u2019s constant <em>h</em> = 6.626 \u00d7 10<sup>-34</sup> J s</p>\n<p>\u210f = <em>h</em>/2\u03c0 = 1.054 \u00d7 10<sup>-34</sup> J s</p>\n<p>The speed of light <em>c</em> = 3.00 \u00d7 10<sup>8</sup> m s<sup>-1</sup></p>\n<p>Electron charge <em>e</em> = 1.602 \u00d7 10<sup>-19</sup> C</p>\n<p>Electron mass <em>m\u00ad</em><sub>e</sub> = 9.109 \u00d7 10<sup>-31</sup> kg</p>\n<p>Proton mass <em>m\u00ad</em><sub>p</sub> = 1.672 \u00d7 10<sup>-27</sup> kg</p>\n<p>Permittivity of free space \u03b5<sub>0</sub> = 8.854 \u00d7 10<sup>-12</sup> C<sup>2</sup> J<sup>-1</sup> m<sup>-1</sup></p>\n<p>Bohr radius <em>a</em><sub>0</sub> = 4\u03c0\u03b5<sub>0</sub>\u210f<sup>2</sup>/<em>m<sub>e</sub>e</em><sup>2</sup> = 0.529 \u00c5</p>\n<p><strong>Conversions</strong></p>\n<p>1 kcal = 4.184 kJ</p>\n<p>1 \u00c5 = 10<sup>-10</sup> m</p>\n<p>1 T = 1 N s C<sup>-1</sup> m<sup>-1</sup></p>\n<p>1 D (Debye) = 3.335 \u00d7 10<sup>-30</sup> C m</p>\n<p>1 e \u00c5 = 4.8 D</p>\n-->\n\n<hr>\n\n\n<p><b>1. Calculate the dipole moment of formamide (in units D), given the bond lengths and partial charges below:</b></p>\n\n\n$$\\mu = \\sum_{i}q_{i}\\vec{r}_{i},$$\n\n<p>where $r=\\sqrt{x^{2} + y^{2}+z^{2}}$ and so each component is considered in the resultant dipole vector $\\mu = \\sqrt{{\\mu_{x}}^{2} + {\\mu_{y}}^{2}+{\\mu_{z}}^{2}}$.</p>\n\n<p>Here, in this problem we are given a molecule and coordinates in 2-D space, therefore we will only have two components.</p>\n\n$$\\mu_{x} = \\sum_{i}q_{i}x_{i} \\hspace{0.5cm} \\text{and} \\hspace{0.5cm} \\mu_{y} = \\sum_{i}q_{i}y_{i}  \\tag{1}$$\n\n\n$$\\mu = \\sqrt{{\\mu_{x}}^{2} + {\\mu_{y}}^{2}} \\tag{2}$$\n\n<p><u>See Page 428 for more details.</u></p>\n\n<a href=\"https://www.chemistry.mcmaster.ca/adronov/resources/Common_Solvents_for_Organic_Reactions.pdf\">Experimental value for dipole moment of formamide.</a>\n\n\n```python\nimport numpy as np\nimport pandas as pd\n# Creating a dictionary for each of the atoms in the molecule\ne = 1.602*10**(-19.) # C\natoms = {\"H1\":[0.270, (-1.3-0.5,0.86)], # [charge, (x,y)] in e and \u00c5\n        \"O\":[-0.571, (0.5,1.0)],\n        \"N\":[-0.669, (-1.3,0.0)],\n        \"C\":[0.650, (0.0,0.0)],         # deamed to be the origin\n        \"H2\":[0.270, (-1.3-0.5,-0.86)],\n        \"H3\":[0.050, (0.5,-0.86)]} \ndf = pd.DataFrame(atoms)\ndf\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>H1</th>\n      <th>O</th>\n      <th>N</th>\n      <th>C</th>\n      <th>H2</th>\n      <th>H3</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.27</td>\n      <td>-0.571</td>\n      <td>-0.669</td>\n      <td>0.65</td>\n      <td>0.27</td>\n      <td>0.05</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>(-1.8, 0.86)</td>\n      <td>(0.5, 1.0)</td>\n      <td>(-1.3, 0.0)</td>\n      <td>(0.0, 0.0)</td>\n      <td>(-1.8, -0.86)</td>\n      <td>(0.5, -0.86)</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nprint(\"Atoms: %s\"%[atom for atom in atoms.keys()])\nprint(\"Charges: %s\"%[charge[0] for charge in atoms.values()])\nprint(\"Positions: %s\"%[pos[1] for pos in atoms.values()])\nmu_x = sum([atom[1][0]*e*atom[1][1][0]*10**-10. for atom in atoms.items()]) # see eq 1 above\nmu_y = sum([atom[1][0]*e*atom[1][1][1]*10**-10. for atom in atoms.items()]) # see eq 1 above\nprint(\"mu_x,mu_y = %0.4g,%0.4g C m\"%(mu_x,mu_y))\nmu = np.sqrt(mu_x**2 + mu_y**2) # see eq 2 above\nprint(\"mu = %0.4g C m\"%(mu))\nmu = mu/(3.335*10**(-30.))\nprint(\"mu = %0.4g D\"%(mu))\nprint(\"Experimental mu = %s\"%(3.73) # Source given above\n```\n\n    Atoms: ['H1', 'O', 'N', 'C', 'H2', 'H3']\n    Charges: [0.27, -0.571, -0.669, 0.65, 0.27, 0.05]\n    Positions: [(-1.8, 0.86), (0.5, 1.0), (-1.3, 0.0), (0.0, 0.0), (-1.8, -0.86), (0.5, -0.86)]\n    mu_x,mu_y = -5.812e-30,-9.836e-30 C m\n    mu = 1.143e-29 C m\n    mu = 3.426 D\n\n\n<p><b>2. Two equal and opposite charges places 10 \u00c5 apart experience an attractive electrostatic force. Is this force stronger in water or in the gas phase? Why?</b></p>\n\n\n$$V(r) =  \\frac{q_{1}q_{2}}{4 \\pi \\epsilon_{r}\\epsilon_{0} r^{2}}, $$ \n\n\n<p>where $q_{1}$ and $q_{2}$ are equal and opposite charges, the permittivity of free space $\\epsilon_{0}$ = 8.854 \u00d7 10<sup>-12</sup> C<sup>2</sup> J<sup>-1</sup> m<sup>-1</sup>, $r=10 \u00c5$ and the dielectric constant $\\epsilon_{r}$ is different for both cases and depends on the medium. The dielectric constant is related to the effective electric field generated by interactions with the medium.</p> \n<p>Therefore, the potential energy of the two charges separated by bulk water is reduced by nearly two orders of magnitude compared to the value it would have if the charges were separated by a vacuum. <u>See Page 425 for more details.</u></p>\n\n\n<p><b>3. True or False? The dielectric constant of water is 1.0.</b></p>\n\n<p style=\"text-align:center\"><b>False</b>. The dielectric constant of water is 78. The dielectric constant of vacuum is 1.0</p>\n\n\n\n<p><b>4. Are the dielectric properties of polar solvents due mainly to (a) atomic or (b) molecular polarization?</b></p>\n\n<p>The larger the polarizability of the molecule, the greater is the distortion cause by a given strength of electric field.  If the molecule contains large atoms with electrons some distance from the nucleus, the nuclear control is less and the polarizability of the molecule is greater. The polarizability also depends on the orientation of the molecule with respect to the field unless geometrically symmetric ($CH_{4}$, $SF_{6}$, etc.).  <u>See Pages 426-432 for more information.</u></p>\n\n\n\n<p><b>5. Draw the Lennard-Jones potential, labeling the parts that are influenced by the <em>r</em><sup>-12</sup> term and the <em>r</em><sup>-6</sup> term.</b></p>\n\n\n##### Lennard-Jones Potential \n\n$$V(r) = 4\\epsilon[\\overbrace{(\\frac{\\sigma}{r})^{12}}^{\\text{Repulsion}}  - \\overbrace{(\\frac{\\sigma}{r})^{6}}^{\\text{Attraction}}]$$\n\n\n<p> At short ranges, the main contribution from the potential energy function comes from $(\\frac{1}{r})^{12}$, which corresponds to the repulsive interactions (Pauli repulsion due to overlap of electron orbitals).  At long ranges the main contribution from the potential energy function comes from $(\\frac{1}{r})^{6}$,which corresponds to the attractive force (van der Waals force, or dispersion force).</p>\n<p>Recall that the force is related to the potential energy by</p>\n    \n$$F = - \\frac{dV(r)}{dr} $$\n\n    \n<p><b>Find the distance $r$, at which the potential energy reaches a minimum.</b></p>\n\n<p>Set the first derivative of the potential energy function equal to zero and solve for $r$.</p>\n\n<p><b>Find $\\sigma$, the distance $r$ at which the potential energy is <u>zero</u>.</b></p>\n\n\n\n\n\n<p><u>See Page 436 for more details.</u></p>\n\n<p><b>6. True or False: The polymer scaling law <em>R</em><sub>g</sub> ~ <em>N</em><sup>\u03bd</sup> for a protein in a compact globule state has an exponent \u03bd = \u00bd.</b></p>\n\n\n\n\n\n#### [Jump to table of contents.](#Table-of-Contents:)\n\n<p><strong>Spectroscopy</strong></p>\n<p><b>7. The molar absorption coefficient for a dye is \u03f5 = 12000 L/mol/cm for light of wavelength \u03bb = 590 nm. At a dye concentration of 100 mM, what is the cuvette path length necessary to decrease the intensity of light by a factor of 10?</b></p>\n\n\n$$A =  log(\\frac{I_{0}}{I})  =  -log(T) = \\epsilon b c$$\n\n$$ b = -\\frac{log(T)}{\\epsilon c},$$\n\n<p>where the intensity of light transmitted has decreased by a factor of 10, so $T=1-0.1 = 0.90$. Solve.</p>\n\n<p><b>8. What is an isobestic point? What does observing an isobestic point say about the system you are studying?</b></p>\n\n<p>The <b><u>isobestic point</u></b> is a specific wavelength at which the <b>absorbance</b> intensity of a sample is invariant during a chemical reaction and comes about when there are at least two interrelated absorbing species in solution.</p>\n<p>This says that if an isobestic point is to occur, then the two species involved are related linearly by stoichiometry, such that the absorbance is invariant for one particular wavelength. <u>See Page 469 for more details.</u></p>\n<p>Also note that the <b><u>isostillbic</u></b> point is for fluorescence spectra.</p>\n\n<p><b>9. What is a transition dipole moment? Given a ground-state wavefunction \u03c8<sub>0</sub>(<em>x</em>) and an excited-state \u03c8<sub>1</sub>(<em>x</em>), write down the formula for the dipole moment.</b></p>\n\n\n\\begin{align}\n\\mu_{fi} &= < \\psi_{f} | \\vec{\\mu} | \\psi_{i} > \\\\\n\\mu_{10} &= < \\psi_{1} | \\vec{\\mu} | \\psi_{0} > = \\int \\psi_{1}(x) \\space \\vec{\\mu} \\space \\psi_{0}(x) dx,\n\\end{align}\n\n<p>where $\\vec{\\mu}$ is the electric dipole moment operator, and $ \\psi_{i}$ and $ \\psi_{f}$ are the wavefunctions for the initial and final states, respectively.  <u>See Page 469 for more details.</u></p>\n\n<p><b>10. Is N<sub>2</sub> vibrationally active? i.e. can its vibrational modes be studied by IR spectroscopy? Why or why not?</b></p>\n\n\n<p style=\"text-align:center\"><b>No.</b> $N_{2}$ and $O_{2}$ are both infrared inactive since they do not possess vibrational modes that result in a change of dipole moment. <u>See Pages 476-477 for more information.</u></p>\n\n\n<p><b>11. How many vibrational modes are there for the linear molecule NO?</b></p>\n\n\n<p style=\"text-align:center\">Linear molecule: $3N-5$</p>\n<p style=\"text-align:center\">Non-Linear molecule: $3N-6$</p>\n\n\n<p><b>12. UV light is used to optically excite a singlet S<sub>0</sub> state to a S<sub>1</sub> state, which decays to the triplet state T (which is \u201cforbidden\u201d from transition back to S<sub>0</sub>). What emission process does this describe? Over what range of time scales does this process occur?</b></p>\n\n\n<p>Phosphorescent, seconds or fraction of seconds.  For more information, see the table of <a href=\"#Rates-of-various-processes\">Rates of various processes.</a></p>\n\n<p><b>13. What kind of information can be obtained using FRET spectroscopy? What is the distance dependence of the FRET effect?</b></p>\n\n<p>F\u00f6rster resonance energy transfer (FRET) spectroscopy is useful for studying processes involving inter and intra-molecular energy transfer and can be used to measure distances (ranging from 1 to 9 nm) in biological systems.  Furthermore, conformational changes can be studied, and also good for studying bulk distances. Single molecule FRET \u2014create histograms of binned FRET distances, ultimately revealing states.<u>See Pages 500,501 for more information.</u></p>\n\n\n<h5> F\u00f6rster theory:</h5>\n\n<p>States that the efficiency of resonance energy transfer is related to the distance $R$ between donor-acceptor pairs by\n\n$$\\eta_{T} = \\frac{{R_{0}}^{6}}{{R_{0}}^{6} + {R}^{6}}, $$\n\n<p>where $R_{0}$ is the distance at which $50 \\%$ of the energy is transfered from donor to acceptor (<b>known value</b> and varified by experiment), and $R$ is the distance between donor and acceptor. This dependence is related by</p>\n\n$$\\eta_{T} \\propto {R}^{-6} $$\n\n\n\n<p><b>14. The fluorescence lifetime of tryptophan is \u03c4<sub>0</sub> = 2.6 ns. The ratio of fluorescence intensity with quencher (I) and without quencher (I<sub>0</sub>) was measured for a series of quencher concentrations [Q], as shown below. What is the quenching rate <em>k</em><sub>Q</sub> for the quencher? Give correct units(!)</b></p>\n\n\n\n\n\n\n\n<p>Because the fluorecence intensity and lifetime are both proportional to the fluorescence quantum yield, $I_{F,0}/I_{F}$ and $\\tau_{0}/\\tau$ against $[Q]$ should also be linear with the same slope and intercept. Therefore,</p>\n\n$$\\frac{I_{F,0}}{I_{F}} = 1 + \\tau_{0}k_{Q}[Q], $$\n\n<p>where the slope = $\\tau_{0}k_{Q}$. Now, we pick two points and get the slope of the line. </p>\n\n\n$$ slope = m = \\frac{(y_{2} - y_{1})}{(x_{2} - x_{1})} = \\frac{(3 - 1)}{(15 - 0)} = 0.13333 mM^{-1}$$\n\n$$k_{Q} = \\frac{m}{\\tau_{0}} = \\frac{0.13333 mM^{-1}}{2.6 ns}  = 0.0513 mM^{-1}ns^{-1}$$\n\n\n\n<p><u>See Page 498 for more details.</u></p>\n \n\n\n<p><strong>Diffraction and crystallography</strong></p>\n<p><b>15. Draw two or more lines through the 2D lattice of points to show planes corresponding to Miller indices (2,1,0)</b>\n</p>\n\n\n<p>Did this in class...</p>\n$$(2,1,0) = (k,h,l)$$\n$$2(\\frac{1}{2},1,0) = (1,2,0)$$\n\n\n\n\n<p><b>16. The crystal unit cell of MDM2 has dimensions <em>a</em> = 43.4 \u00c5, <em>b</em> = 100.5 \u00c5, <em>c</em> = 54.8 \u00c5. What is the spacing <em>d</em> of diffraction planes with Miller indices (2,1,0)?</b></p>\n<p></p>\n\n\n\n\n\\begin{equation}\n\\frac{1}{d^{2}}=\\frac{h^{2}}{a^{2}}+\\frac{k^{2}}{b^{2}}+\\frac{l^{2}}{c^{2}}\n\\end{equation}\n\n<p><u>See Page 418 for more information.</u></p>\n\n<p><b>17. Describe the \u201cphase problem\u201d in X-ray crystallography, and at least one way the problem can be addressed (or at least circumvented to solve X-ray structures).</b></p>\n\n<p><u>See Page 420 for phase problem, See Page 421 for the way the problem can be addressed.</u></p>\n\n<p><strong>Thermodynamics</strong></p>\n\n\n<p><b>18. What is the First Law of Thermodynamics?</b></p>\n\n\n### [Laws of Thermodynamics](https://robraddi.github.io/TU_Chem/CHEM1035_Chemistry_For_Engineers/CHEM1035-Recitations.html#Laws-of-Thermodynamics:):\n\nThe <u>1st Law</u> is concerned with the internal energy. We postulate that it obeys two properties. The first assumption made is that **internal energy is extensive, which means it is additive.**\n\n$$ U = U_{1} + U_{2} $$\n\nThe second assumption states that **energy is conserved**, states that energy can neither be created nor destroyed; energy can only be transfered or changed from one form to another e.g., $heat \\rightarrow electrical$. Internal energy, $\\Delta U$ of a system is the sum of the heat, $Q$ that flows across the system\u2014surroundings barrier and the work, w done on the system by the surroundings:\n\n$$ \\Delta U = Q + w ,$$\n\nwhere work is defined as organized motion that can transfer energy. \n\nwhere $Q > 0$ is when heat is absorbed by the system, and $Q < 0$ is when heat is transfered from system to surroundings. The previous equation can be summarized in the table below:\n\n\n| Internal Energy, U | Heat, Q | Work, w | Physical Description | \n| :--: | :--: | :--: | :--: |\n| + | + | + | Heat flows into the system & Work done by the surroundings. |\n| +/- | + | - | Heat flows into the system & Work done by the system. |\n| +/- | - | + | Heat flows into the surroundings & Work done by the surroundings. |\n| - | - | - | Heat flows into the surroundings & Work done by the system. |\n\n<h5>Work</h5>\n\n<p>The work term has the general form, $dW = \\int Fdx $ where $F$ is the applied force, and x is a mechanical extensive variable. </p>\n<p>We already know that $P = F/A$, so lets substitute this in for F, and say that area, $A = x^{2}$. Then,</p>\n\n\\begin{align}\ndW &= \\int Fdx = \\int P dx^{3}\\\\\ndW &= \\int_{V_{i}}^{V_{f}}P_{ext}dV = P(V_{f} - V_{i})\n\\end{align}\n\nwhere $V$ is the volume of a bulk system, and $p_{ext}$ is the external pressure. \n\n\n\n\nIn the diagram above, one can see that $w>0$ is related to compression and $w<0$ corresponds to expansion.\n\n\n\n\n<p><b>19. A volume of ideal gas is compressed at <u>constant temperature</u>. Does the internal energy $U$ increase?</b></p>\n\n<h5>Compression work</h5>\n\n<p>The question specifically says <u>constant temperature</u> (isothermal process) for an ideal gas. How can this increase $U$?</p>\n\n<p>At constant temperature, the internal energy of the ideal gas should also be constant.</p>\n\n\n\\begin{align}\n\\Delta U &= Q + w\\\\\n&=  Q - P\\Delta V,\\\\\n\\end{align}\n\n<p>where $\\Delta V = (V_{f} - V_{i}) < 0$ and $w>0$. Futhermore, the amount of heat released is the same as the work due to compression $Q = w$ $\\therefore$  $\\Delta U = 0$. </p>\n\n<p><b>20. An ideal gas is slowly expanded from 1 L to 2 L at standard pressure and temperature.</b></p>\n\n<p><b>(a) What is the work $w$ done on the system? (Make sure you have the correct sign!)</b></p>\n\n<p><b>(b) What is the heat change $Q$ of the system?</b></p>\n\n\n\n<h5>Expansion work @ Constant P,T</h5>\n\n$$-Q = w = -P\\Delta V$$\n\n\n\n\n\n<p><b>21. What is the mechanical work done for free expansion of a gas (say, in a vacuum)?</b></p>\n\n<p style=\"text-align:center\">There is no work done when a system expands freely.</p>\n\n<p> Since $P_{external} = 0$, then $w = -PdV = 0$\n\n\n<p><b>22. Consider the following reaction performed at a constant pressure of 1 bar, at 25\u02da C = 298 K, with all species in the gas phase:</b></p>\n\n\n\n$$2 {NH_{3}}_{(g)} \\rightarrow {N_{2}}_{(g)} + 3 {H_{2}}_{(g)}$$\n\n\n<p>If we assume that all reactants and products behave like ideal gases, what is the expansion work done (in kJ/mol)? (Remember to carefully consider the <em>sign</em> of this value)</p>\n\n\n\n<p><b>23. Draw a picture of the enthalpy <em>H</em> of water as a function of temperature <em>T</em>, from 75 \u02daC to 125 \u02daC (as it passes through the boiling point, <em>T</em><sub>b</sub> = 100 \u02daC). Clearly label the heat of vaporization \u2206<em>H</em><sub>vap</sub>.</b></p>\n\n\n\n\n\n\n$$ \\Delta H_{total} = mC_{ice}\\Delta T_{-25\u00b0C\\rightarrow0\u00b0C} + n\\Delta H_{fusion} + mC_{water} \\Delta T_{0\u00b0C\\rightarrow100\u00b0C} + n \\Delta H_{vaporization} $$\n\n<p>Note that the temperature does not change during a phase change...</p>\n\n<p><b>24. The heat capacity <em>C</em><sub>p</sub> of an unfolded protein is 8.0 kJ\u2009K<sup>-1</sup>\u2009mol<sup>-1</sup> at 350 K. Assuming <em>C</em><sub>p</sub> is relatively temperature-independent, calculate the change in enthalpy \u2206<em>H</em> when the temperature is increased from 350 K to 375 K.</b></p>\n\nThe following expression is derived in problem 25.\n\n$$C_{P} = (\\frac{\\partial H}{\\partial T})_{P} \\implies dH = C_{P} dT$$\n\n$$ \\Delta H = C_{P} \\Delta T$$\n\n\n<p><b>25. True or False? For an ideal gas, <em>C<sub>p</sub></em> + <em>C<sub>V</sub></em> = <em>nR</em></b></p>\n\n<p><b>False.</b></p>\n<p>By definition, heat capactiy is the ratio of the change in heat in an object to the change in temperature.  The frist law of thermodynamics says:</p>\n\n\\begin{align}\ndU &= \\delta Q - \\delta w\\\\\ndU(\\underbrace{S,V}_{\\text{independent}\\\\\\text{variables}}) &= TdS - PdV\n\\end{align}\n\n\n<p>Since $\\delta Q = TdS$ and $\\delta w = -PdV$, then </p>\n    \n\\begin{align}  \ndU &= \\delta Q - PdV\\\\\n\\text{At Constant V:} \\hspace{1cm} (\\frac{\\partial U}{\\partial T})_{V} &= (\\frac{\\partial Q}{\\partial T})_{V} - P \\underbrace{(\\frac{\\partial V}{\\partial T})_{V}}_{\\text{goes to 0}} = C_{V}\n\\end{align}\n\n<p>Use the equation of state for enthalpy to obtain $C_{P}$:</p>\n\n\\begin{align}\ndH &= VdP + TdS\\\\\ndH &= VdP + \\delta Q\\\\\n\\text{At Constant P:} \\hspace{1cm} (\\frac{\\partial H}{\\partial T})_{P} &= V\\underbrace{(\\frac{\\partial P}{\\partial T})_{P}}_{\\text{goes to 0}} + (\\frac{\\partial Q}{\\partial T})_{P} = C_{P}\n\\end{align}\n\n\n<p><b>How do $C_{V}$ and $C_{P}$ relate to eachother?</b></p>\n\n<p style=\"text-align:center\"> $dQ = C_{V}dT+PdV$ $\\hspace{0.5cm}$ <b><u>and</u></b> $\\hspace{0.5cm}$ $dQ = C_{V}dT-VdP$</p>\n\n\n<p><b>For an ideal gas: $PV = nRT$</b></p>\n\n\\begin{align}\nC_{V}dT+PdV &= C_{P}dT - VdP\\\\\nPdV + VdP &= C_{P}dT - C_{V}dT = (C_{P} - C_{V})dT\\\\\nP(\\frac{\\partial V}{\\partial T})_{P} V(\\frac{\\partial P}{\\partial T})_{V} &=  C_{P} - C_{V}\\\\\nnR &\\approx  C_{P} - C_{V}, \\hspace{0.25cm} \\text{and} \\hspace{0.25cm} C_{P} > C_{V}\n\\end{align}\n\n#### <span style='color:blue'>12.</span>\n\n\n\n#### [Jump to table of contents.](#Table-of-Contents:)\n\n#### <span style='color:blue'>13.</span>\n\n\n<p><strong>Computer Lab \u2013 SimBiology 1</strong></p>\n<p><strong>Goal</strong>: The purpose of this lab is to become familiar with SimBiology by modeling a simple ligand binding reaction.</p>\n<p><strong>Introduction</strong></p>\n<p>Consider a binding reaction where ligand (L) binds to a protein receptor (R) to form a loosely bound encounter complex (L\u2219R), and finally a tightly bound product (P).<a href=\"#fn_note1\" class=\"footnote-ref\" id=\"fn_note1\"><sup>1</sup></a></p>\n\n$$L + R \u2942 L\u2219R \\rightarrow P$$\n\n<p>The SimBiology model of this receptor-ligand reaction looks like this (in MATLAB 2012a):</p>\n\n\n\n<p>Let\u2019s walk through the steps of how to build this model in SimBiology.</p>\n<p><strong>Procedure</strong></p>\n<ol class=\"incremental\" type=\"1\">\n<li><p>Open Matlab and type simbiology at command window.</p></li>\n<li><p>Go to Model tap in SimBiology window.</p></li>\n<li><p>Home &gt; add model &gt; create new blank model</p></li>\n<li><p>Model &gt; Full &gt; diagram</p></li>\n<li><p>Rename window\u2019s name to Receptor-Ligand reaction by double clicking on window.</p></li>\n<li><p>Open Tools&gt; Block Library Browser, Drag and drop three species and one reaction to the window.</p></li>\n<li><p>Double click the name of the species and rename species to Ligand, Receptor and ligand-receptor respectively.</p></li>\n<li><p>Rename reaction_1 to binding/unbinding</p></li>\n<li><p>Hold down control key and draw an arrow from Ligand and Receptor to binding/unbinding</p></li>\n<li><p>Draw an arrow from binding/unbinding to ligand-receptor</p></li>\n<li><p>Double click on Ligand and set initial amount to 10.0</p></li>\n<li><p>Double click on Receptor and set initial amount to 5.0</p></li>\n<li><p>Double click on binding/unbinding</p>\n    \n    \n\n<ol class=\"incremental\" type=\"a\">\n<li><p>and check \u201creversible\u201d</p></li>\n<li><p>select \u201cMassAction\u201d for KineticLaw</p>\n<ol class=\"incremental\" type=\"i\">\n<li><p>set \u201cForward Rate Parameter\u201d value to 0.02</p></li>\n<li><p>set \u201cReverse Rate Parameter\u201d value to 0.01</p></li>\n</ol></li>\n</ol></li>\n<li><p>Run the simulation and save the graph.</p></li>\n<li><p>Add another \u201cspecies\u201d and \u201creaction\u201d. Name the species product and reaction as k-prod.</p></li>\n<li><p>Connect ligand-receptor to k-prod and k-prod to product.</p></li>\n<li><p>Select MassAction for kinetic law of k-prod and set value to 0.05.</p></li>\n<li><p>Run simulation.</p>\n<ol class=\"incremental\" start=\"3\" type=\"a\">\n<li><p>Does the reaction reach a steady state?</p></li>\n<li><p>If not, increase simulation time to 100 by going to \u201csimulation setting\u201d (ask your TA if you can\u2019t find it)</p></li>\n</ol></li>\n<li><p>Repeat simulation for following values:</p>\n<ol class=\"incremental\" start=\"5\" type=\"a\">\n<li><p>\u201cForward Rate Parameter\u201d : 0.01 , \u201cReverse Rate Parameter\u201d : 0.02 , \u201ck-prod\u201d : 0.05</p></li>\n<li><p>\u201cForward Rate Parameter\u201d : 0.02, \u201cReverse Rate Parameter\u201d : 0.01 , \u201ck-prod\u201d : 0.5</p></li>\n</ol></li>\n</ol>\n\n<p><strong>Bonus</strong></p>\n<p>This same reaction can be used to describe Michaelis-Menten enzyme kinetics, in which substrate (S) binds a protein enzyme (E) to form an encounter complex (E\u2219S), and then chemically converts to product (E + P).</p>\n\n\n$$E + S \\underset{k_{-1}}{\\stackrel{k_{1}}{\u2942}} E\u2219S \\stackrel{k_{cat}}{\\to} E + P$$\n\n\n\n\n<p>Suppose an enzyme has <em>k</em><sub>1</sub> = 10<sup>7</sup> s<sup>-1</sup>, <em>k</em><sub>-1</sub> = 10<sup>6</sup> s<sup>-1</sup> and <em>k</em><sub>cat</sub> = 10<sup>4</sup> s<sup>-1</sup>. By adjusting parameters in SimBiology, which of these rates constants would you say most sensitively controls the overall rate of catalysis?</p>\n<section class=\"footnotes\">\n<hr>\n<ol>\n<li id=\"fn_note1\"><p>Note that this last kinetic step is \u201cone-way\u201d, which violates thermodynamics (!). Don\u2019t worry about this yet (we\u2019re getting to kinetics soon in the lecture). For now, suffice it to say that here we invoke the assumption that the back rate is very small compared to forward rate.<a href=\"#fn_note1\" class=\"footnote-back\">\u21a9</a></p></li>\n</ol>\n</section>\n\n\n<hr>\n\n<!--\n<p><strong>Part A:</strong></p>\n<table>\n<thead>\n<tr class=\"header\">\n<th><em><strong>Case#</strong></em></th>\n<th><em><strong>K<sub>f</sub></strong></em></th>\n<th><em><strong>K<sub>r</sub></strong></em></th>\n<th><em><strong>K<sub>prod</sub></strong></em></th>\n<th><em><strong>\u0394t(s) to reach steady state</strong></em></th>\n</tr>\n</thead>\n<tbody>\n<tr class=\"odd\">\n<td><strong>1</strong></td>\n<td>0.02</td>\n<td>0.01</td>\n<td>0.05</td>\n<td></td>\n</tr>\n<tr class=\"even\">\n<td><strong>2</strong></td>\n<td>0.01</td>\n<td>0.02</td>\n<td>0.05</td>\n<td></td>\n</tr>\n<tr class=\"odd\">\n<td><strong>3</strong></td>\n<td>0.02</td>\n<td>0.01</td>\n<td>0.5</td>\n<td></td>\n</tr>\n</tbody>\n</table>\n<p><strong>Part B:</strong></p>\n<table>\n<thead>\n<tr class=\"header\">\n<th><em><strong>Case#</strong></em></th>\n<th><em><strong>K<sub>1</sub></strong></em></th>\n<th><em><strong>K<sub>-1</sub></strong></em></th>\n<th><em><strong>K<sub>cat</sub></strong></em></th>\n<th><em><strong>\u0394t(s) to reach steady state</strong></em></th>\n</tr>\n</thead>\n<tbody>\n<tr class=\"odd\">\n<td><strong>1</strong></td>\n<td>1000</td>\n<td>100</td>\n<td>1</td>\n<td></td>\n</tr>\n<tr class=\"even\">\n<td><strong>2</strong></td>\n<td>100</td>\n<td>1000</td>\n<td>1</td>\n<td></td>\n</tr>\n<tr class=\"odd\">\n<td><strong>3</strong></td>\n<td>100</td>\n<td>1</td>\n<td>1000</td>\n<td></td>\n</tr>\n</tbody>\n</table>\n-->\n\n#### [Jump to table of contents.](#Table-of-Contents:)\n\n#### <span style='color:blue'>14.</span>\n\n\n<p><strong>Computer Lab \u2013 SimBiology 2 </strong></p>\n<p><strong>Goal</strong>: The purpose of this lab is to compare two- and three-state models of protein folding kinetics using the steady-state approximation</p>\n<p><strong>Introduction</strong></p>\n<p>This exercise is based on the following paper:</p>\n<blockquote>\n<p>Teilum, K., Maki, K., Kragelund, B. B., Poulsen, F. M., &amp; Roder, H. (2002). Early kinetic intermediate in the folding of acyl-CoA binding protein detected by fluorescence labeling and ultrarapid mixing. Proceedings of the National Academy of Sciences of the United States of America, 99(15), 9807\u20139812. doi:10.1073/pnas.152321499</p>\n</blockquote>\n\n\n\n<p>In this work, the folding kinetics of an 86-residue four helix-bundle protein called ACBP (acyl-CoA binding protein) was measured using time-resolved fluorescence spectroscopy (monitoring UV tryptophan fluorescence at 280 nm), after fast dilution from chemical denaturant (guanidinium hydrochloride, GuHCl) in a capillary mixer. The authors find that their data can be fit to the following kinetic model,</p>\n\n$$ U \\underset{k_{IU}}{\\stackrel{k_{UI}}{\\rightleftharpoons}} I \\underset{k_{NI}}{\\stackrel{k_{IN}}{\\rightleftharpoons}} N $$\n\n\n<p>where U is a highly fluorescent unfolded state, I is a partially folded intermediate, and N is the folded state.</p>\n<p><strong><br />\n</strong></p>\n<p><strong>Procedure</strong></p>\n<p><em>Modeling the three-state mechanism</em></p>\n<p>Use SimBiology to construct a model of the three-state folding kinetics, using the following kinetic rate parameters determined by the authors at 299 K:</p>\n\n$$ U \\underset{k_{IU}= 7000 s^{-1}}{\\stackrel{k_{UI} =  11000 s^{-1}}{\\rightleftharpoons}} I \\underset{k_{NI} =  0.07 s^{-1}}{\\stackrel{k_{IN} =  650 s^{-1}}{\\rightleftharpoons}} N $$\n\n<p>Here is some experimental data that might be helpful in validating your model</p>\n<table>\n<thead>\n<tr class=\"header\">\n<th>Time (ms)</th>\n<th><p>Fluorescence intensity for the U state</p>\n<p>High concentration = more intensity</p></th>\n</tr>\n</thead>\n<tbody>\n<tr class=\"odd\">\n<td>0.2</td>\n<td>1.1</td>\n</tr>\n<tr class=\"even\">\n<td>0.4</td>\n<td>1.0</td>\n</tr>\n<tr class=\"odd\">\n<td>0.6</td>\n<td>0.98</td>\n</tr>\n<tr class=\"even\">\n<td>0.8</td>\n<td>0.96</td>\n</tr>\n<tr class=\"odd\">\n<td>1</td>\n<td>0.91</td>\n</tr>\n<tr class=\"even\">\n<td>2</td>\n<td>0.6</td>\n</tr>\n<tr class=\"odd\">\n<td>20</td>\n<td>0.33</td>\n</tr>\n<tr class=\"even\">\n<td>40</td>\n<td>0.32</td>\n</tr>\n<tr class=\"odd\">\n<td>60</td>\n<td>0.31</td>\n</tr>\n<tr class=\"even\">\n<td>80</td>\n<td>0.29</td>\n</tr>\n</tbody>\n</table>\n\n<p>Using initial concentrations of [U] = 10.0, [I] = 0.0, and [N] = 10.0, visualize the concentrations of each species over time. <strong>Draw or print/plot the results below</strong>.</p>\n<p><strong>Using the results of your SimBiology model, estimate the populations of U and N at equilibrium.</strong></p>\n<p><strong>Estimate from this the equilibrium constant <em>K</em> = [N<sub>equilibrium</sub>]/[U<sub>equilibrium</sub>] and the free energy of folding.</strong></p>\n<p><em><br />\n</em></p>\n\n<p><em><b>Modeling the two-state mechanism</b></em></p>\n<p>Let\u2019s now apply the <span class=\"underline\">steady-state approximation</span> to this three-state model. This approximation is a simplification saying that the concentration of the intermediate [I] is constant throughout the reaction. Since the formation of the intermediate is fast compared to the slower, <span class=\"underline\">rate-limiting</span> step of folding to the native state N, the steady-state approximation is still fairly accurate.</p>\n<p>To find the steady-state approximation, we go through the following steps:</p>\n\n<p><b>1. </b>Write down an expression for <em>d</em>[I]/<em>dt</em> :</p>\n</ol>\n\n$$\\frac{d[I]}{dt} = -k_{IU}[I] - k_{IN}[I] + k_{UI}[U] + k_{NI}[I]$$\n\n<p><b>2. </b>Solve $\\frac{d[I]}{dt} = 0$ (i.e. steady-state conditions) to get $[I]$ as a function of $[U]$ and $[N]$ :</p>\n\n\\begin{align} \n0 &= -k_{IU}[I] - k_{IN}[I] + k_{UI}[U] + k_{NI}[N]\\\\\n[I](k_{IU} + k_{IN}) &= k_{UI}[U] + k_{NI}[N]\\\\\n[I] &= (k_{UI}[U] + k_{NI}[N])/(k_{IU} + k_{IN})\n\\end{align}\n\n\n<p><b>3. </b>Next, we plug this expression for $[I]$ into the rate laws for $[U]$ and $[N]$:</p>\n\n\\begin{align}\n\\frac{d[U]}{dt} &= -k_{UI}[U] + k_{IU}[I]\\\\\n&= -k_{UI}[U] + k_{IU} (k_{UI}[U] + k_{NI}[N])/(k_{IU} + k_{IN})\\\\\n\\frac{d[N]}{dt} &= -k_{NI}[N] + k_{IN}[I]\\\\\n&= -k_{NI}[N] + k_{IN} (k_{UI}[U] + k_{NI}[N])/(k_{IU} + k_{IN})\n\\end{align}\n\n<p><b>4. </b>Finally, to get rates for a two-state $U\\rightleftharpoons N$ model of folding, consider that at equilibrium, $\\frac{d[U]}{dt} = \\frac{d[N]}{dt} = 0$. <strong>Set the two expressions for $\\frac{d[U]}{dt}$ and $\\frac{d[N]}{dt}$ above to be equal to each other, and rearrange the equation to get it in the following form:</strong></p>\n\n$$k_{forward} [U] = k_{backward}[N]$$\n<p><strong>What are your computed values of for $k_{forward}$ and $k_{backward}$?</strong> (Hint: They should be close to the values of $k_{IN}$ and $k_{NI}$, since $I \\to N$ is the rate-limiting step.)</p>\n<p><strong>Estimate from $k_{forward}$ and $k_{backward}$ the equilibrium constant ($K = k_{f}/k_{b}$) and free energy of folding.</strong></p>\n\n<p><strong><br />\n</strong></p>\n\n<!--\n<p><strong>Answer key:</strong></p>\n$$k_{forward} = k_{IN} (\\frac{k_{UI}}{(k_{IU} + k_{IN})} )$$\n$$k_{backward} = k_{NI} (\\frac{k_{IU}}{(k_{IU} + k_{IN})})$$\n<p><strong>NOTE: it takes some simplification to get this</strong></p>\n-->\n\n#### [Jump to table of contents.](#Table-of-Contents:)\n\n#### <span style='color:blue'>15.</span>\n<!-- -->\n**Extra:**\n\n#### [Jump to table of contents.](#Table-of-Contents:)\n\n<!-- -->\n", "meta": {"hexsha": "e330dd21b9439b1761dfa803aeecc33c59e4dc2e", "size": 295447, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "CHEM3405_Physical_Chemistry_Bio/CHEM3405.ipynb", "max_stars_repo_name": "robraddi/tu_chem", "max_stars_repo_head_hexsha": "18b8247d6c00e33f15f040a57a32b5fc2372137a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-29T04:26:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-29T04:26:42.000Z", "max_issues_repo_path": "CHEM3405_Physical_Chemistry_Bio/CHEM3405.ipynb", "max_issues_repo_name": "robraddi/tu_chem", "max_issues_repo_head_hexsha": "18b8247d6c00e33f15f040a57a32b5fc2372137a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CHEM3405_Physical_Chemistry_Bio/CHEM3405.ipynb", "max_forks_repo_name": "robraddi/tu_chem", "max_forks_repo_head_hexsha": "18b8247d6c00e33f15f040a57a32b5fc2372137a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-03T17:47:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-03T17:47:05.000Z", "avg_line_length": 86.1361516035, "max_line_length": 38064, "alphanum_fraction": 0.7406032216, "converted": true, "num_tokens": 40769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245510940225, "lm_q2_score": 0.13846179767920994, "lm_q1q2_score": 0.03766500835735845}}
{"text": "# Memo Series & Knowledgebase \n\n\n## CASA Memos \n\nCASA Memo Series\n\n- [CASA Memo 1: MeasurementSet Definition version 2.0](https://drive.google.com/file/d/1IapBTsFYnUT1qPu_UK09DIFGM81EIZQr/view?usp=sharing) - \n  A.J. Kemball & M.H. Wieringa, v. 01/2000\n\n- [CASA Memo 2: Convention for UVW calculations in CASA](https://drive.google.com/file/d/1a-eUwNrfnYjaUQTjJDfOjJCa8ZaSzZcn/view?usp=sharing) - U. Rau, v. 02/2013\n\n- [CASA Memo 3: MeasurementSet Selection Syntax](https://drive.google.com/file/d/1LXrVu529pI_Di2-J6BJqmlXbgfihc2nf/view?usp=sharing) - S. Bhatnagar, v. 06/2015\n\n- [CASA Memo 4: CASA Imager Paralellization: Measurement and Analysis of Runtime Performance for Continuum Imaging](https://drive.google.com/file/d/14GoBf8kiBCEITfyURnoFuTAAj49_FxXA/view?usp=sharing) - S. Bhatnagar & CASA HPC team, v. 03/2016\n\n- [CASA Memo 5: CASA Performance on Lustre: serial vs parallel and comparison with AIPS](https://drive.google.com/file/d/1J4BxUl_AjxbAiFQwJLl8RZ5MYW3r-if_/view?usp=sharing) - B. Emonts, v. 06/2018\n\n- [CASA Memo 6: User Survey and Helpdesk Statistics 2018](https://drive.google.com/file/d/18OHYERd11S2zZ8Hkx1h6j8e8iqsStkJs/view?usp=sharing) - B. Emonts, v. 11/2018\n\n- [CASA Memo 7: ALMA Mosaicing Imaging Issues Prior to Cycle 6](https://drive.google.com/file/d/1F2LoWnJlRTdq-hRrlPfHfz78sfdhBRzM/view?usp=sharing) - North American ALMA Science Center (NAASC) Software Support Team, v. 09/2018. Copy of NAASC Memo 117 (credit: NAASC).\n\n- [CASA Memo 8: Non-Amnesic CLEAN: A boxless/maskless CLEAN style deconvolution algorithm](https://drive.google.com/file/d/1atGvO-2ehMeWZk3FuoL2OMIKtkxjSYei/view?usp=sharing) - K. Golap, v. 12/2015\n\n- [CASA Memo 9: Improvements to Multi-Scale CLEAN and Multi-Term Multi-Frequency CLEAN](https://drive.google.com/file/d/1_M3f4QNsMw2k-FpxtWSCKwXWC8YTRwgL/view?usp=sharing) - J.-W. Steeb & U. Rau, v. 07/2019\n\n- [CASA Memo 10: Restoring/Common Beam and Flux Scaling in tclean](https://drive.google.com/file/d/1ngPiUsGDazhfno8RxV4MXuPI6SnbLgO0/view?usp=sharing) - J.-W. Steeb & U. Rau, v. 08/2019\n\n- [CASA Memo 11: Heterogeneous Pointing Corrections in AW-Projection](https://drive.google.com/file/d/1Z2BZKTqp0hmQkYFNltY1X0YDWX2gPFG5/view?usp=sharing) - P. Jagannathan & S. Bhatnagar 10/2019\n\n\n\n## CASAcore Memos \n\nCASA's underlying structure is based on [casacore](http://casacore.github.io/).  The [CASAcore Notes](http://casacore.github.io/casacore-notes/) describe some of the most fundamental properties, such as on the table system, data selection syntax, and data model definitions. \n\n\n\n\n## CASA Knowledgebase \n\nThe CASA Knowledgebase pages provide bits of wisdom on CASA that should be preserved, and that may be of use to expert users.\n\n\n\n\n\n### Correcting bad common beam \n\nThis script re-calculates the common beam by discarding certain channels where the point-spread-function (PSF) or \\'beam\\' deviates substantially from those of the other channels.\n\nIt can happen that an MS contains one or more channels for which the point-spread-function (PSF) or 'beam' deviates a lot from those of the other channels. This can be the result of substantial flagging, missing data, or other factors. When making a data cube with *restoringbeam=\\'common\\'*, these \\\"outlier\\\" channels can create a common beam that does not reflect the beam for the bulk of the channels.\n\n[This example_robust_common_beam.py script](https://colab.research.google.com/drive/1ad9GFgd58xwxAxyg4mhAzSR-pAcICjt0?usp=sharing) will correct the common beam by detecting and/or flagging outliers channels in the calculation of the common beam. The outlier channels are identified as those channels for which the area of those beams deviate from the median beam by a user-specified factor in computation of the median area beam. The script will do the following:\n\n-   Run tclean with niter=0\n-   Detect/flag outliers in chan beams\n-   Use the remaining beams with ia.commonbeam() to get a new commonbeam\n-   Specify this explicitly to tclean in the subsequent niter\\>0 run.\n\nThe attach script primarily demonstrates the solution of  iter0 -\\> calc_good_beam -\\> specify_restoringbeam_in_iter1 along with tclean. If the new commonbeam is not larger than all the bad beams, then the iter0 tclean run\\'s restoration step will throw warnings for all channels that cannot be convolved to the new common beam. \n\nThe functionality provided by this script is not yet implemented in the commonbeam method of the image analysis tool (*ia.commonbeam*).\n\nPlease note that the script is based on an ALMA test-data that was used for characterizing the problem in pipeline processing at the NAASC (JIRA ticket PIPE-375). Parameters have to be adjusted for each use case, including heuristics to detect outlier channels and what to substitute the \\'bad\\' beams with.\n\n\n\n\n\n\n### ALMA polarization: XY-phase solver avoids +-45 deg solution \n\nThe XY-phase calibration obtained with CASA task gaical (gaintype=\\'XYf+QU\\') avoids to output +/- 45 degree solutions. This is a subtle consequence of the algorithm used to solve for the cross-hand phase, and should be harmless for the calibration of ALMA full-polarization data.\n\nWhen using the task **gaincal** with parameter *gaintype=\\'XYf+QU\\'*, the solution to solve is a fit for a slope in 2D data (imag vs. real) from data that has noise is *both* dimensions.  In such cases, it is always better to fit a *shallow* (not steep) slope, so if the slope (for imag vs. real) comes out \\>1.0, it flips the axes (to real vs. imag) and re-fits it (and inverts the resulting value to account for the swap).  This minimizes the effect of the real axis noise on the slope calculation. This yields far more accurate solutions when the nominal slope is very large (\\>\\>1.0, e.g., the data nearly parallel to the imag axis == cross-hand phase approaching +/-90 deg). \n\nThe case of slope = 1.0 (which is cross-hand phase of 45 deg) corresponds to the slope at which to pivot the axis swap decision. When plotting the cross-hand phase solutions, a gap appears at +-45 deg (see figure). This gap is a property of the typical spacings between values in the statistical distribution of slope values.  I.e., for a sample of N points filling a distribution with a finite width, there is a characteristic *minimum* spacing between values that is some small *fraction* of the width of the distribution.  Of course, smaller spacings are not forbidden, but they are rare.  The axis swap reveals this property since all of the (nominal) slopes that are \\>1.0 (cross-hand phases \\>45.0 deg) are fit with swapped data and yield the inverse slope (\\<1.0), and than inverted to be \\>1.0 again.  The typical slopes mostly do not get arbitrarily close to exactly 1.0, so the gap appears.  This is essentially an extension of the fact that (for *any* slope), the precise exact value need not be realized in any instance in a sample of solutions for it.  E.g., in a sample of N gaussian-distributed values centered on some specific value the likelihood of any sample having that *precise* central value is vanishingly small. \n\nThe gap should become smaller when either the noise decreases, or the number of channels (for the same noise) increases.\n\nThis feature should be harmless for the calibration of ALMA full-polarization data.\n\n{.image-inline}\n\n \n\n\n### User tips on installing CASA on unsupported OSs \n\nThis document provide tips from users on how to install CASA on unsupported operating systems, like LINUX Ubuntu, Debian, and Fedora.\n\n<div class=\"alert alert-info\">\nDisclaimer: the information in this document is provided by users and not verified by the CASA team. The information does not reflect official CASA recommendations and should be used at your own risk.\n</div>\n\n \nCASA officially supports certain versions of LINUX Redhat and Mac OSX. See the [CASA Download page](https://casa.nrao.edu/casa_obtaining.shtml) for more information.\n\nWe realize that many users wish to try and run CASA on different operating systems. Below are some tips from the user community on installing CASA on unsupported platforms. CASA will not run on Windows.\n\n- **Ubuntu or Debian** - Please see the following PDF: [Installing CASA on Unbuntu or Debian](https://drive.google.com/file/d/1bEJWtvY1qMmr1FH4BtPScyPT6F6zg0qK/view?usp=sharing)\n\n- **Fedora** - Fedora 32 may cause CASA to crash on startup with the error *\\\"code for hash md5 was not found\\\"*. This is caused by changes to libssl.so in the compat-openssl10 package, which prevents the CASA supplied version of this library from loading. An easy fix is to replace the CASA version of libssl.so.10 with the OS version in /lib64 (i.e., libssl.so.1.0.2o).\n\n\n\n\n\n\n### Wideband Mosaic Imaging and Pointing Corrections for the VLA Sky Survey \n\nThis Knowledgebase article describes testing results for wideband mosaic imaging and pointing corrections for VLASS.\n\nThe Very Large Array Sky Survey ([VLASS](https://science.nrao.edu/vlass)) critically depends on accurate wideband mosaicing algorithms for its single epoch imaging and ultimately cumulative imaging. To a large degree, VLASS requirements have driven CASA's development of the AW-projection and related algorithms for [widefield](synthesis_imaging.ipynb#Wide-Field-Imaging) and [wideband](synthesis_imaging.ipynb#Wide-Band-Imaging) imaging in CASA. This Knowledgebase article provides complementary reports on the testing of Wideband Mosaic Imaging and Pointing Corrections for VLASS.\n\n- [ARDG Test Report: Wideband Mosaic Imaging for VLASS](https://drive.google.com/file/d/1JZH9x0KxZTVqMe4hE-xvRgUAZiJ3wPaM/view?usp=sharing)\n\n- [CASA development report: Pointing Corrections for VLASS](https://drive.google.com/file/d/1pq6Xx1AQAFldbWfSXC1An5zysjVnUYGq/view?usp=sharing)\n\n\n\n\n\n\n### Calculation of Weights for Data with Varying Integration Time \n\nKnowledgebase Article: Calculation of Weights for Data with Varying Integration Time\n\n**George Moellenbrock** *Original 18 Dec 2018, latest edited version 04 Nov 2019* \n\nWhen the nominal weights are expected to be uniform (becauseintegration time, channel bandwidth, effective Tsys, collecting area,etc. are all uniform, or the visibilities are normalized), extractingweight information from the apparent statistics of otherwise stablevisibility measurements is a simple matter of calculating the apparentsimple variance in the visibility real and imaginary parts over asufficient local sample of values. The real and imaginary partvariances should be approximately equal, and the inverse of their meanis the correct weight to assign to each of the visibility valueswithin the sample. Here, \\\"stable visibility\\\" means no *systematic*variation of amplitude or phase within the localsample. Noise-dominated visibilities are ideal; otherwise,well-calibrated data with no true visibility variation aredesirable. These conditions are also needed for the more general casedescribed below.\n\nWhen the integration time (aka \\\"exposure\\\") varies within the localsample (such as can be generated by averaging of the datapost-correlation, where the number of samples per averaging bin mayvary, especially at the end of scans), we expect the correct variancefor each visibility to be inversely proportional to the netintegration time, and this complicates the calculation. It isnecessary to determine a weighted variance per unit inverseintegration time, wherein the sample weights for the variancecalculation are the per-visibility integration times, e$_i$. If the onlyreason the underlying variance differs among samples is the variableintegration time, then a uniform normalized variance estimate of thewhole sample may be obtained by scaling the residual data per sampleby the square root of their (known) integration times. Here, residualdata means any underlying visibility signal\\-\\--presumably the averageof the visibility samples, using nominal (proportional to integrationtime, etc.) weights\\-\\--has been subtracted. The simple variance of thisrescaled sample is, in effect, the variance per unit inverseintegration time.\n\nFor visibilities V$_i$, with integration times e$_i$:\n \n\\<var$_{norm}$\\> = Sum (e$_i$ (V$_i$ - \\<V\\>)$^2$ / N    \\[1\\]\n\nwhere \\<V\\> = Sum (w$_i$ V$_i$) / Sum (w$_i$)       \\[1a\\] \n\nand w$_i$ are the nominal data weights presumably proportional tointegration time and other relevant factors. In practice, we couldprobably just use w$_i$ = e$_i$ in equation \\[1a\\] since all of the otherrelevant factors witin w$_i$ are assumed constant within thesample. Note that the units of \\<var$_{norm}$\\> are in squared visibilityamplitude (Jy$^2$, presumably) times seconds. Note also that \\<var$_{norm}$\\>is essentially the simple variance of the ensemble \\sqrt(e[$_i$).dV$_i$\\](where dV$_i$ is (V$_i$-\\<V\\>)), i.e., of the residual visibilities scaledso that their noise is independent of integration time.\n\nThe normalized weight-per-unit-integration time is thus the inverse of\\<var$_{norm}$\\>:\n\nW$_{norm}$ = 1/\\<var$_{norm}$\\>                      \\[2\\]\n\nand per-datum revised weights may be calculated as:\n\nW$_i$ = W$_{norm}$ \\* e$_i$                         \\[3\\]\n\nAnother way of arriving at this result is to calculate a weightedvariance:\n\n\\<var\\> = Sum (e$_i$ (V$_i$ - \\<V\\>)$^2$) / Sum(e$_i$)   \\[4\\]\n \nwhich corresponds to the (simple) mean exposure time, which is:\n\n\\<e\\> = Sum(e$_i$) / N                         \\[5\\]\n\nThe product of these yields \\<var$_{norm}$\\>, as above in \\[1\\]:\n\n\\<var$_{norm}$\\> = \\<var\\>\\<e\\>                      \\[6\\]\n \nand W$_{norm}$ may be formed and applied as in \\[2\\] and \\[3\\] above.\n\nThis calculation should be done for both real and imaginary parts ofthe visibility sample and averaged, or for both parts jointly, and \\[3\\]used to form the revised weights.\n\nNB: In calculating sample variance, it is generally customary toacknowledge the loss of one degree of freedom due to use of the meanvisibility, \\<V\\> in the calculation. Essentially, \\<V\\> will have afinite error that tends to bias the resulting variance downward. Forsimple variance calculations, a factor N/(N-1) is applied to thevariance calculation to unbias it, and this factor can be significantfor modest N. Since a non-trivially weighted mean is used in the above(otherwise simple, non-weighted) variance calculation (eqn \\[1\\]), itmay be appropriate to consider a more carefully weighted calculationfor the N/(N-1) factor. The required factor is:\n\nD = 1 - ( Sum(w$_i$\\^2) / Sum(w$_i$)\\^2 ) \\[9\\]\n\nwhere w$_i$ are the a priori nominal weights used in \\[1a\\] above. This factor can be shown to equal (N-1)/N and so should be *divided* intothe \\<var$_{norm}$\\> result.\n\nHowever, since the nominal error in the variance (and thus theweights) will be \\<10% (an accuracy we are unlikely to achieve ingeneral anyway) for N\\>10, and will be uniform over many sample groupsin the overall statwt execution, we assume that it is adequate to use thesimpler N/(N-1) factor, or omit it entirely.\n\n\n\n\n### Bug affecting polarization visibility data in concatenated data \n\nKnowledgebase Article: characterization of a bug that affected polarization visibility data in concatenated data in CASA versions up to 5.6.\n\n**George Moellenbrock** *Original 17 Apr 2020, latest edited version 12 May 2020*\n\nCASA 5.7/6.1 fixed a bug in **concat** and **importfitsidi** that affected polarization visibility data in concatenated MSs. The problem that occurs in CASA versions earlier than 5.7/6.1 is that the cross-hands may be spuriously mis-ordered on a subset of baselines in the concatenated MS.This Knowledgebase Article describes the main effects that this bug has on concat\\'d data in general, and in particular on the processing of ALMA and VLA data with CASA up to and including version 5.6.A careful analysis has revealed the following effects in concat\\'d MSs in CASA versions prior to 5.7/6.1:\n\n1. *In general,* visibility data cross-hands may be spuriously swapped on some baselines in concat\\'d data when the antenna lists in the input MSs are *partially* different.  The concat task adopts the first (in time order) MS\\'s antenna list for the output MS, and appends unique antennas from later MS(s), typically with larger indices than in their original MSs.  Depending on the original antenna indexing, baselines between these additional antennas and antennas that did occur in the first MS may sometimes require conjugation (reversal of the order of antennas in the baseline) to maintain internal indexing consistency within the output MS (for all baselines in an MS, the first antenna must have an index which is lower than (or same as) the index of the second antenna).   When baselines are conjugated in this way, the sign of the phase of each correlation and the UVWs must be reversed, and the cross-hands swapped (RL or XY will become LR or YX, respectively, and vice-versa).  Prior to CASA 5.7/6.1, the sign reversals were correct, but the cross-hand swap was spuriously omitted.  For successfully calibrated data (i.e., calibrated *prior* to running concat), this means that the sign of the imaginary part of the cross-hand visibilities will be incorrect, and thus the sign Stokes U (for circular feeds) or Stokes V (for linear feeds) will be incorrect on the affected baselines in concat\\'d data. Since the pathology affects only the cross-hands, polarimetry calibration of concat\\'d data may be adversely affected. \n\nFor reconfigurable arrays, note that an antenna\\'s particular position (pad) makes it unique, i.e., a specific physical antenna that has moved is a new unique antenna in this context.  Concatenation of *entirely* disjoint antenna lists are unaffected, since all additional antennas in the concatenation will have uniformly incremented indices, and no baseline conjugation will be required.   Certain unique cases of different antenna lists are immune to this problem, e.g., new unique antennas with already-higher indices than all other common antennas, etc.\n\n2. The concat task initially sorts the MSs into time order (only at whole-MS granularity), so the effect cannot be controlled merely by adjusting the order in which the input MSs are specified in the concat call (i.e., there is no easy user-directed fix).\n\n3. An implicit concat happens in importfitsidi (i.e., VLBI, typically) when specifying multiple FITS-IDI files. Here the antenna re-indexing occurs upon fill, and thus most-likely *before* calibration.  Since ordinary gain calibration uses only the parallel-hands, it will not be affected by the underlying cross-hand swap error.  However, polarimetry calibration will be affected to the extent that there are spuriously swapped cross-hands within the filled MS.  EVN observations consisting of multiple FITS-IDI will have the same antenna table in each file and are therefore unaffected by this bug.\n\n4. Since the pathology affects only the cross-hands, purely Stokes I (total intensity) observations of any kind should not be affected (even if the cross-hand are present and some are affected, and thus technically incorrect).\n\n5. For ALMA and VLA data, calibration typically occurs prior to any potentially pathological use of concat, and the impact will be as follows:\n\n- ALMA:  Total intensity observations of any kind are not affected.  For successfully calibrated (per session) ALMA polarization data not subject to this pathology in the concat of multiple contiguous execblocks within each session\\*, the pathology affects only Stokes V (circular polarization) when concat-ing multiple sessions subject to the baseline conjugation conditions described in item 1 above.  This is because the spurious cross-hand swap effectively sabotages only the sign of the imaginary part of the cross-hands in some baselines, i.e., the apparent Stokes V signal sampled by linear feeds.  The net effect will be to suppress the net Stokes V signal in imaging.   This presumably affects only a very tiny minority of existing ALMA observations.\n\n<div class=\"alert alert-info\">\n* **Note:** In the course of standard scripted ALMA polarimetry calibration, the split task does not remove antennas from the ANTENNA subtable, even when they are fully flagged and keepflags=False.  The data rows are not retained in this case, but the ANTENNA subtable seen by concat remains complete.  Therefore, as long as the execblocks within the contiguous polarization session are uniform as regards to antenna population (as is intended), the polarization calibration within an individual session should not be subject to this this pathology.\n</div>\n\n- VLA: Total intensity observations of any kind are not affected.  For successfully calibrated VLA polarization observations (which typically do not require a prior concat), the pathology affects only Stokes U when concat-ing multiple observations subject to the baseline conjugation conditions described in item 1 above.  By the same logic as for ALMA, the Stokes U (cross-hand imaginary part for circular feeds) will be suppressed.  Since this affects part of the linearly polarized net response, a larger fraction of VLA cases (cf ALMA) may be affected.  The pathological condition arises when antennas are variously removed from the array (typically up to 2 or 3 at any given time) for incidental maintenance, so as to generate datasets with fewer than the full complement of 27 antennas, or when antennas move in and out of the barn (even when there are 27 antennas present in each observation), and when such disparate observations are concat\\'d.    For concats of different VLA configurations, some baselines to antennas that did *not* move (typically \\~12 out of 27 antennas) between the configurations will be affected, even if the total antenna lists (by name/number) have not changed.  This is because antennas that did move (only) are unique new antennas in the concat by virtue of their new positions, and some baselines between them and the stationary antennas must be conjugated in the concat. \n\n6. If observations are combined implicitly in imaging by specifying a list of MSs to tclean, there should be no problem, since the bug is an artifact of the mechanical combination of MSs into a single MS on disk.\n\n\n\n\n\n### Single Dish imaging bug for EBs with different antenna positions in common antenna names and IDs \n\nA bug was found for imaging of single-dish data with the tasks **sdimaging** and **tsdimaging**in CASA versions 5.6 and lower. This bug could cause an inaccurate direction conversion when more than one MS is given and these data contain the same antenna with the same antenna ID but with different location, i.e., station or pad where the antenna is placed. The bug affects the brightness distribution and flux density in the combined image, since the coordinates are not correct for some fraction of the data set.\n\nDetails of this bug can be found in this [Knowledgebase Article](https://drive.google.com/file/d/1Fu8_GGwnxaoNthmwDu4z2BF6_igB-k9-/view?usp=sharing).\n\nThe bug was fixed in CASA 5.7/6.1\n\n\n\n***\n\n\n\n\n\n###CASA Data Repository for developers building from source\n\nFor general users, information on the CASA Data Repository can be found on the [\"External Data\" pages](external-data.ipynb#CASA-Data-Repository \"CASA Data Repository\") in CASA Docs.\n\nFor the build from source, such as those the developers use, the \"casadata\" is taken from a list of directories given in .casa/config.py. For example, for developers at NRAO Charlottesville, the entries in their config.py could look like:\n\n```\ndatapath=['/home/casa/data/master/','/home/casa/data/distro/']\n```\n\nor just this:\n\n```\ndatapath=['/home/casa/data/master/']\n```\n \nwhere:\n/home/casa/data/master/ is the original data repository of CASA that contains all the data from casadata, regression, unittest, etc.\n/home/casa/data/distro/ contains only the \"casadata\" needed to launch CASA and from here it is packaged to be included in the casalith tarballs.\n\nFor CASA build from source, the distro data is found in the following place:\n\n```\ncasa6 build from source: distro is taken from .casa/config.py under:    \ndatapath=['/some-directory/distro/']\n```\n\n```\ncasa5 build from source: distro is taken from under:    \n$CASAPATH/data/\n```\n\n**Warning:** to developers regarding awproject using CASA 6.1 or earlier:\n\nIn CASA 6.2 a bug was fixed in the way that the awproject gridder in tclean calls the data repository in CASA 6. Previously tclean was looking at .casa/config.py for the location of the distro data but only considering the root data directory existence and not checking existence of the data (more specifically, antenna response data) actually used by it. As of CASA 6.2, the logic of checking the data path to look for the antenna response using the awproject gridder in tclean is as follows:\n\n1. It looks for the antenna response data directory by constructing the full path with the root data paths from dataPath(), which returns data paths defined in config.py (for casa6).  The specific data directory to look for varies by telescope (i.e. ALMA vs VLA).\n\n2. If 1 fails, it looks for the data in the path determine by the function, distroDataPath(), which returns the default root data directory path in the case of casalith tarballs.\n\n3. If all above fail, it tries the path defined by CASAPATH (only relevant for casa5)\n\n\n\n## Reference Material \n\nCollection of relevant reference material\n\n\n\n\n### AIPS-CASA Dictionary \n\nCASA tasks equivalent to AIPS tasks\n\n AIPS tasks and their corresponding CASA tasks. Note that this list is not complete and there is also not a one-to-one translation. \n\n   AIPS Task    CASA task/tool               Description\n  ------------ ---------------------------- -----------------------------------------------------------------------------------------------------\n  APROPOS      taskhelp                     List tasks with a short description of their purposes\n  BLCAL        blcal                        Calculate a baseline-based gain calibration solution\n  BLCHN        blcal                        Calculate a baseline-based bandpass calibration solution\n  BPASS        bandpass                     Calibrate bandpasses\n  CALIB        gaincal                      Calibrate gains (amplitudes and phases)\n  CLCAL        applycal                     Apply calibration to data\n  COMB         immath                       Combine images\n  CPASS        bandpass                     Calibrate bandpasses by polynomial fitting\n  CVEL         cvel/mstransform             Regid visibility spectra\n  DBCON        concat/virtualconcat         Concatenate u-v datasets\n  DEFAULT      default                      Load a task with default parameters\n  FILLM        importvla                    Import old-format VLA data\n  FITLD        importuvfits/importfitsidi   Import a u-v dataset which is in FITS format\n  FITLD        importfits                   Import an image which is in FITS format\n  FITTP        exportuvfits                 Write a u-v dataset to FITS format\n  FITTP        exportfits                   Write an image to FITS format\n  FRING        (coming soon)                Calibrate group delays and phase rates\n  GETJY        fluxscale                    Determine flux densities for other cals\n  GO           go                           Run a task\n  HELP         help                         Display the help page for a task (also use [casa.nrao.edu/casadocs](http://casa.nrao.edu/casadocs))\n  IMAGR        clean/tclean                 Image and deconvolve\n  IMFIT        imfit                        Fit gaussian components to an image\n  IMHEAD       vishead                      View header for u-v data\n  IMHEAD       imhead                       View header for an image\n  IMLIN        imcontsub                    Subtract continuum in image plane\n  IMLOD        importfits                   Import a FITS image \n  IMSTAT       imstat                       Measure statistics on an image\n  INP          inp                          View task parameters\n  JMFIT        imfit                        Fit gaussian components to an image\n  LISTR        listobs                      Print basic data\n  MCAT         ls                           List image data files\n  MOMNT        immoments                    Compute moments from an image\n  OHGEO        imregrid                     Regrids an image onto another image's geometry\n  PBCOR        impbcor/widebandpbcor        Correct an image for the primary beam\n  PCAL         polcal                       Calibrate polarization\n  POSSM        plotcal/plotms               Plot bandpass calibration tables\n  POSSM        plotms                       Plot spectra\n  PRTAN        listobs                      Print antenna locations\n  PRTAN        plotants                     Plot antenna locations\n  QUACK        flagdata                     Remove first integrations from scans\n  RENAME       mv                           Rename an image or dataset\n  RFLAG        flagdata                     Auto-flagging\n  SETJY        setjy                        Set flux densities for flux cals\n  SMOTH        imsmooth                     Smooth an image\n  SNPLT        plotcal/plotms               Plot gain calibration tables\n  SPFLG        msview                       Flag raster image of time v. channel\n  SPLIT        split                        Write out u-v files for individual sources\n  STATWT       statwt                       Weigh visibilities based on their noise\n  TASK         inp                          Load a task with current parameters\n  TGET         tget                         Load a task with parameters last used for that task\n  TVALL        imview                       Display image\n  TVFLG        msview                       Flag raster image of time v. baseline\n  UCAT         ls                           List u-v data files\n  UVFIX        fixvis                       Compute u, v, and w coordinates\n  UVFLG        flagdata                     Flag data\n  UVLIN        uvcontsub/mstransform        Subtract continuum from u-v data\n  UVLSF        uvcontsub/mstransform        Subtract continuum from u-v data\n  UVPLT        plotms                       Plot u-v data\n  UVSUB        uvsub                        Subtracts model u-v data from corrected u-v data\n  WIPER        plotms                       Plot and flag u-v data\n  ZAP          rmtables                     Delete data files\n\n \n\n\n\n\n### MIRIAD-CASA Dictionary \n\nCASA tasks equivalent to MIRIAD tasks\n\nThe Table below provides a list of common Miriad tasks, and their equivalent CASA tool or tool function names. The two packages differ in both their architecture and calibration and imaging models, and there is often not a direct correspondence. However, this index does provide a scientific user of CASA who is familiar with MIRIAD, with a simple translation table to map their existing data reduction knowledge to the new package.\n\nIn particular, note that the procedure of imaging and cleaning of visibility data between CASA and MIRIAD differs slightly. In MIRIAD the tasks invert, clean and restor are used in order to attain \\\"CLEAN\\\" images, whereas in CASA the task **clean**/**tclean** achieves the same steps as a single task.\n\n  MIRIAD Task   CASA task/tool                                                    Description\n  ------------- ----------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------\n  atlod         importatca                                                        Import ATCA RPFITS files\n  blflag        plotms/msview                                                     Interactive baseline based editor/flagger\n  cgcurs        imview                                                            Interactive image analysis\n  cgdisp        imview                                                            Image display, overlays\n  clean         clean/tclean                                                      Clean an image\n  delhd         imhead (mode=\\'del\\'), clearcal                                   Delete values in dataset/remove calibration tables \n  fits          importmiriad,importfits, exportfits, importuvfits, exportuvfits   FITS uv/image filler\n  gethd         imhead (mode=\\'get\\')                                             Return values in image header\n  gpboot        fluxscale                                                         Set flux density scale\n  gpcal         gaincal, polcal                                                   Polarization leakage and gain calibration\n  gpcopy        applycal                                                          Copy calibration tables from one source to another\n  gpplt         plotcal, plotms                                                   Plot calibration solutions\n  imcomb        immath                                                            Image combination\n  imfit         imfit                                                             Image-plane component fitter\n  impol         immath (mode=\\'poli\\' or \\'pola\\')                                Manipulate polarization images (see [example](http://www.atnf.csiro.au/computing/software/miriad/userguide/node149.html))\n  imstat        imstat                                                            Image statistics\n  imsub         imsubimage                                                        Extract sub-image\n  invert        clean/tclean                                                      Synthesis imaging/make dirty map\n  linmos        im tool (im.linearmosaic)                                         Linear mosaic combination of images\n  maths         immath                                                            Calculations involving images\n  mfboot        fluxscale                                                         Set flux density scale\n  mfcal         bandpass, gaincal                                                 Bandpass and gain calibration\n  moment        immoments                                                         Calculate image moments\n  prthd         imhead, listobs, vishead                                          Print header of image or uvdata\n  puthd         imhead (mode=\\'put\\')                                             Add/edit values in image header\n  restor        clean                                                             Restore a clean component model\n  selfcal       clean, gaincal, etc.                                              Selfcalibration of visibility data\n  uvplt         plotms                                                            Plot visibility data\n  uvspec        plotms                                                            Plot visibility spectra data\n  uvsplit       split                                                             Split visibility dataset by source/frequency etc\n\n\n\n\n\n### Dan Briggs\\' Dissertation - Robust Weighting \n\nDan Briggs\\' Dissertation on high fidelity imaging with interferometers, including robust (\\'Briggs\\') weighting.\n\nLink to [Dan Briggs' Dissertation](http://www.aoc.nrao.edu/dissertations/dbriggs/) \\([pdf version](https://drive.google.com/file/d/1Q0kCOlRJwXV2aww_Dr9GnGFsq9dCWjMX/view?usp=sharing)\\)\n\n\n\n\n\n### Flux Calibrator Models \n\nDescriptions of flux calibrator models for flux density scaling\n\nThere are two categories of flux calibrator models available to determine flux density scales: compact extra-galactic sources and solar system objects. The models for bright extragalactic sources are described in the form of polynomial expressions for spectral flux densities and clean component images for spatial information. The flux density scales based on the solar system objects are commonly used to establish flux density scales for mm and sub-mm astronomy. These models consist of brightness temperature models and their ephemeris data.\n\n\n\n#### Compact extragalactic sources\n\nFor the VLA, the default source models are customarily point sources defined by the 'Baars', 'Perley 90', 'Perley-Taylor 99', 'Perley-Butler 2010',  'Perley-Butler 2013' (time-variable), \\'Perley-Butler 2017\\' (time-variable) or 'Scaife-Heald 2012' flux density scales ('Perley-Butler 2017' is the current standard by default), or point sources of unit flux density if the flux density is unknown. \\'Stevens-Reynolds 2016\\' currently contains only one source, 1934-638, which is primarily used for flux calibrator for the ACTA.\n\nThe model images (CLEAN component images) are readily available in CASA for the sub set of the sources listed below. The task **setjy** provides listing of the available model images included in the CASA package\\'s data directory. You can find the path to the directory containing your list of VLA Stokes I models by typing (inside CASA) [print os.getenv(\\'CASAPATH\\').split(\\' \\')[\\[0\\]]{.error} + \\'/data/nrao/VLA/CalModels/\\']. The [setjy Description Page](../api/casatasks.rst) in CASA Docs also lists the models that are available in CASA. These models can be plotted in plotms.\n\nAlternatively, the user can provide a model image at the appropriate frequency in Jy/pixel units, typically the .model made by **clean** (which is a list of components per pixel, as required, although the restored .image is in Jy/beam). For unknown calibrators, however, the spectral flux distribution has to be explicitely specified in **setjy**. If you do not specify the correct path to a model (and you have not provided your own model), the default model of a point sources of unit flux density will be adopted. \n\n \n\n  \n  \n3C/Common Name | B1950 Name  | J2000 Name  | Alt. J2000 Name |  Standards\n--- | --- | --- | --- | --- \n -- | -- | -- | J0133-3629 | 9\n3C48 | 0134+329 | 0137+331 | J0137+3309 | 1,2,3,4,5,6,7,9 \nFORNAX X | -- | -- | J0322-3712 | 9 \n3C123 | 0433+295 | 0437+296 | J0437+2940 | 2, 9\n3C138 | 0518+165 | 0521+166 | J0521+1638 | 1,3,4,5,6\nPICTOR A | -- | -- | J0519-4546 | 9\n3C144 (TAURUS A/CRAB) | -- | -- | J0534+2200 | 9\n3C147 | 0538+498 | 0542+498 | J0542+4951  | 1,3,4,5,6,7,9\n3C196 | 0809+483 | 0813+482 | J0813+4813 | 1,2,7,9 \n3C218(HYDRA A) | -- | -- | J0918-1205 | 9\n3C274 (VIRGO A) | -- |  -- | J1230+1223 | 9\n3C286 | 1328+307 | 1331+305 | J1331+3030 | 1,2,3,4,5,6,7,9\n3C295 | 1409+524 | 1411+522 | J1411+5212 | 1,2,3,4,5,6,7,9\n3C438 (HERCULES A) | -- | -- | J1651+0459 | 9\n3C353 | -- | -- | J1720-0059 | 9\n-- | 1934-638 | -- | J1939-6342 | 1,3,4,5,6,8\nC380 | 1828+487 | 1829+487 | J1829+4845  | 7,9\n3C405 (CYGNUS A) | -- |  -- | J1959+4044 | 9\n3C444 | -- | -- | J2214-1701 | 9\n3C461 (CASSIOPEIA A) | -- | -- | J2323+5848 |  9 \n\n\nStandards are: (1) [Perley-Butler 2010](#perley-butler-2010), (2) [Perley-Butler 2013](#perley-butler-2013), (3) [Perley-Taylor 99](#perley-taylor-99), (4) [Perley-Taylor 95](#perley-taylor-95), (5) [Perley 90](#perley-90), (6) [Baars](#baars), (7) [Scaife-Heald 2012](#scaife-heald-2012), (8) [Stevens-Reynolds 2016](#stevens-reynolds-2016) (9) [Perley-Butler 2017](#perley-butler-2017)\n\n\n\n>Known sources and their alternative names recognized by **setjy** task\n  \n\nALMA also uses a few dozen compact QSO as flux standards, monitored 2-4 times a month at bands 3, 6 and 7 (90 - 345 GHz). Due to rapid variability these data are not packaged with CASA, but can be accessed via <https://almascience.eso.org/alma-data/calibrator-catalogue>\n\n \n\n**Baars**\n<a id='baars'></a>\n\nThe only standard to not have the year in the name. It is 1977. The models are second order polynomials in log(\u03bd), valid between 408 MHz and 15 GHz.\n\nReference: Baars et al. (1977) [\\[1\\]](#Bibliography) with a commentary by Kellermann, K. I. (1999) [\\[2\\]](#Bibliography)\n\n**Perley 90** \n\nThis standard also includes 1934-638 from Reynolds (7/94) and 3C138 from Baars et al. (1977) [\\[1\\]](#Bibliography) .\n\nDetails can be found at <http://www.vla.nrao.edu/astro/calib/manual/baars.html>.\n\n**Perley-Taylor 95** \n\nPerley and Taylor (1995.2); plus Reynolds (1934-638; 7/94) Details can be found at <http://www.vla.nrao.edu/astro/calib/manual/baars.html>.\n\n**Perley-Taylor 99**\n\nPerley and Taylor (1999.2); plus Reynolds (1934-638; 7/94) Details can be found at <http://www.vla.nrao.edu/astro/calib/manual/baars.html>.\n\n**Perley-Butler 2010** \n\nA preliminary version of Perley-Butler 2013. This version also has coefficients for sources that showed some degree of variability (see Perley & Butler (2013) [\\[3\\]](#Bibliography)) but they are treated as the steady sources (i.e. no time dependent models are used).\n\n**Perley-Butler 2013**\n\nFlux scale for the constant flux sources 3C123, 3C196, 3C286, and 3C295 as well as variable sources (3C48, 3C138, and 3C147). The models for the variable sources are time-dependent.Reference: Perley & Butler (2013)  [\\[3\\]](#Bibliography) .\n\n**Scaife-Heald 2012**\n\nLow frequency, 30-300MHz, calibrators 3C48, 3C147, 3C196, 3C286, 3C295, and 3C380.\n\nReference: Scaife & Heald (2012)  [\\[4\\]](#Bibliography)\n\n**Stevens-Reynolds 2016**\n\nLow frequency (\\<11GHz) polynomial from Reynolds and updated high frequecy polynomial from Stevens.\n\nReference: Partridge et al. (2016)  [\\[5\\]](#Bibliography)\n\n \n\n**Perley-Butler 2017**\n<a class=\"headerlink\" href=\"#perley-butler-2017\"></a>\n\nThe flux density scale of Perley-Butler 2013 extended downward to \\~50 MHz. Twenty sources were drawn from the Baar, Perley-Butler 2013, and Scaife-Heald 2012. Flux scale for the constant flux sources Fornax A, 3C123, J0444-2809, Pictor A, 3C144, (Taurus A or Crab), 3C196, 3C218 (Hydra A),  3C274 (Virgo A or  M87), 3C286, 3C295,  3C348 (Hercules A), 3C353, 3C380, 3C405 (Cygnus A), 3C444, and 3C461 (Cassiopeia A) as well as variable sources (3C48, 3C138, and 3C147). The models for the variable sources are time-dependent. The frequency range valid for the model for each source is also listed below.\n\n  Source         Valid frequency range in GHz\n  -------------- ------------------------------\n  J0133-3649     0.2-4\n  3C48           0.05-50\n  Fornax X       0.2-0.5\n  3C123          0.06-50\n  J0444-2809     0.2-2.0\n  3C138          0.2-50\n  Pictor A       0.2-4.0\n  Taurus A       0.05-4.0\n  3C147          0.05-50\n  3C196          0.050-50\n  Hydra A        0.05-12\n  Virgo A        0.05-3\n  3C286          0.05-50\n  3C295          0.05-50\n  Hercules A     0.2-12\n  3C353          0.2-4\n  3C380          0.05-4.0\\*\n  Cygnus A       0.05-12\n  3C444          0.2-12\n  Cassiopeia A   0.2-4\n\n\\* The corrected frequency range for 3C380 is noted here based on  B. J.  Butler 2018, private comunication (CAS-9538)Reference: Perley & Butler (2017)  [\\[7\\]](#Bibliography)\n\n \n\n \n\n\n\n#### Solar System objects\n\nThe usual approach in mm and sub-mm regimes is to use models that are, to first order, thermal sources in the Solar System. Their apparent brightness varies in time with their distance from the Earth (and Sun), and orientation if they are not perfect spheres with zero obliquity. However, most of them have almost constant surface properties, so once those properties are measured their apparent brightness distributions, they can in principle be predicted for any time, given an ephemeris. Planets, in particular, have more complex spectra and effects such as atmospheric lines, magnetic fields, seasons, polar caps and surface features that need to be taken into account when they are available and significant. In CASA, the Solar System objects supported by **setjy** are available through the 'Butler-JPL-Horizons 2010', and 'Butler-JPL-Horizons 2012' standards. It is recommended to use \\'Butler-JPL-Horizons 2012\\' as it contains updated models. The 2012 models are described in ALMA Memo 594, which is available on [https://science.nrao.edu/facilities/alma/\\~aboutALMA/Technology/ALMA_Memo_Series/alma594/abs594](https://science.nrao.edu/facilities/alma/aboutALMA/Technology/ALMA_Memo_Series/alma594/abs594) . Models can be found  by typing (in CASA) [print os.getenv(\\'CASAPATH\\').split(\\' \\')[\\[0\\]]{.error} + \\'/data/alma/SolarSystemModels\\'.]\n\nThe following objects are supported based on models from Butler-JPL-Horizons 2012, updated where necessary as mentioned under each object. Please refer ALMA Memo594 for the detailed comparisons with the models in Butler-JPL-Horizons-2010.\n\n**Venus**\n\nThe model spans the frequencies from \\~300MHz to 1THz. No atmospheric lines such as CO,H~2~O~,~ HDO, and etc are included. Modeled based on Clancy et al. (2012)  [\\[6\\]](#Bibliography).\n\n**Mars**\n\nFull implementation of the model of Rudy et al. (1987) [\\[7\\]](#Bibliography), tabulated as a function of time and frequency (30-1000GHz). No atmospheric lines are included.\n\n**Jupiter**\n\nModel for 30-1020GHz (from Glenn Orton, private communication), does not include synchrotron emission.\n\n**Uranus**\n\nModel for 60-1800GHz (from Glenn Orton and Raphael Moreno, private communication), contains no rings or synchrotron.\n\n**Neptune**\n\nModel for 2-2000 GHz (from Glenn Orton and Raphael Moreno, private communication), contains no rings or synchrotron.\n\n**Io**\n\nSpline interpolation of data points from 15 to 29980 GHz (references: please refer to the ALMA memo 594 Table 1).  Strongly not recommended to use for the primary flux calibrator for ALMA observations.\n\n**Europa**\n\nSpline interpolation of data points from 15 to 29980 GHz (references: please refer to the ALMA memo 594 Table 1).  Strongly not recommended to use for the primary flux calibrator for ALMA observations.\n\n**Ganymede**\n\nSpline interpolation of data points from 5 to 29980 GHz (references: please refer to the ALMA memo 594 Table 1).\n\n**Callisto**\n\nSpline interpolation of data points from 5 to 29980 GHz (references: please refer to the ALMA memo 594 Table 1).\n\n**Titan**\n\nModel from Mark Gurwell, from 53.3-\u00ad1024.1 GHz. Contains surface and atmospheric emission. The atmosphere includes N2-\u00adN2 and N2-\u00adCH4 Collision-\u00adInduced Absorption (CIA), and lines from minor species CO, ^13^CO, C^18^O, HCN, H^13^CN and HC^15^N. See, e.g., Gurwell & Muhleman (2000) [\\[8\\]](#Bibliography); Gurwell (2004) [\\[9\\]](#Bibliography).\n\n**Asteroids**\n\nSome asteroids, namely Ceres, Pallas, Vesta, and Juno are included in the Butler-JPL-Horizons 2012. The models consists of the constant brightness temperature in frequency. For Ceres, Pallas, and Vesta, updated models based on thermophysical models (TPM) (T. Mueller, private communication) which are tabulated in time and frequency, are available for the observations taken after January 1st 2015, 0:00 UT. **setjy** task will automatically switch to the new models for the observations taken on and after that date. The TPM are also available for Lutetia but it is not advised to use for the absolute flux calibration for ALMA. Each of the tabulated models contains the flux density at 30, 80, 115, 150, 200, 230, 260, 300, 330, 360, 425, 650, 800, 950, and 1000 GHz. The time resolution is 1 hour for Ceres and 15 min for Lutetia, Pallas, and Vesta. The cubic interpolation is employed to obtain the flux densities at other frequencies.\n\n**Ceres**\n\nModel with a constant $T_b$ = 185K over frequencies (Moullet et al. 2010 [\\[10\\]](#Bibliography), Muller & Lagerros 2002 [\\[11\\]](#Bibliography), Redman et al. 1998 [\\[12\\]](#Bibliography), Altenhoff et al. 1996 [\\[13\\]](#Bibliography)) if time of the observations took place ($t_{obs}$) is before 2015.01.01, 0:00 UT, TPM if $t_{obs}$ $\\ge$ 2015.01.01, 0:00 UT.\n\n**Pallas**\n\nModel with a constant $T_b$ = 189K (Chamberlain et al. 2009 [\\[14\\]](#Bibliography), Altenhoff et al. 1994 [\\[15\\]](#Bibliography)) for $t_{obs}$ $\\lt$ 2015.01.01, 0:00 UT, and TPM for $t_{obs}$ $\\ge$ 2015.01.01, 0:00 UT\n\n**Vesta**\n\nModel with a constant $T_b$ = 155K (Leyrat et al. 2012 [\\[16\\]](#Bibliography), Chamberlain et al. 2009 [\\[14\\]](#Bibliography), Redman et al. 1998 [\\[12\\]](#Bibliography), Altenhoff et al. 1994 [\\[15\\]](#Bibliography)) for $t_{obs}$ $\\lt$ 2015.01.01, 0:00 UT, and TPM for $t_{obs}$ $\\ge$ 2015.01.01, 0:00 UT\n\n**Juno**\n\nModel with a constant $T_b$ = 153K (Chamberlain et al. 2009 [\\[14\\]](#cit), Altenhoff et al. 1994 [\\[15\\]](#cit))\n\n \n\n\n\n#### Bibliography\n\n1. Baars,\\ J.\\ W.\\ M.\\ et\\ al.\\ 1977,\\ A&A,\\ 61,\\ 99\\ [ADS](http://adsabs.harvard.edu/abs/1977A%26A....61...99B)\n2. Kellermann,\\ K.\\ I.\\ 2009*,*\\ A&A\\ 500,\\ 143\\ [ADS](http://adsabs.harvard.edu/abs/2009A%26A...500..143K)\n3. Perley,\\ R.\\ A.,\\ &\\ Butler,\\ B.\\ J.\\ 2013,\\ ApJS,\\ 204,\\ 19\\ [ADS](http://adsabs.harvard.edu/abs/2013ApJS..204...19P)\n4. Scaife,\\ A.\\ M.,\\ &\\ Heald,\\ G.\\ H.\\ 2012,\\ MNRAS,\\ 423,\\ 30\\ [ADS](http://adsabs.harvard.edu/abs/2012MNRAS.423L..30S)\n5. Partridge\\ et\\ al.\\ 2016,\\ ApJ\\ 821,1\\ [ADS](http://adsabs.harvard.edu/abs/2016ApJ...821...61P)\n6. Clancy,\\ R.T.\\ et\\ al.\\ 2012,\\ Icarus,\\ 217,\\ 779\\ [ADS](http://adsabs.harvard.edu/abs/2012Icar..217..779C)\n7. Perley,\\ R.\\ A.\\ &\\ Butler,\\ B.\\ J.\\ 2017,\\ ApJS,\\ 230,7[ADS](http://adsabs.harvard.edu/abs/2017ApJS..230....7P)\n7. Rudy,\\ D.J.\\ et\\ al.\\ 1987,\\ Icarus,\\ 71,\\ 159\\ [ADS](http://adsabs.harvard.edu/abs/1987Icar...71..159R)\n8. Gurwell,\\ M.A.\\ &\\ D.O.\\ Muhleman\\ 2000,\\ Icarus,\\ 145,\\ 65w\\ [ADS](http://adsabs.harvard.edu/abs/2000Icar..145..653G)\n9. Gurwell,\\ M.A.\\ 2004,\\ ApJ,\\ 616,\\ L7\\ [ADS](http://adsabs.harvard.edu/abs/2004ApJ...616L...7G)\n10. Moullet,\\ A.\\ et\\ al.\\ 2010,\\ A&A,\\ 516,\\ L10\\ [ADS](http://adsabs.harvard.edu/abs/2010A%26A...516L..10M)\n11. Muller,\\ T.G.\\ &\\ J.S.V.\\ Lagerros\\ 2002,\\ A&A,\\ 381,\\ 324\\ [ADS](http://adsabs.harvard.edu/abs/2002A%26A...381..324M) \n12. Redman,\\ R.O.\\ et\\ al.\\ 1998,\\ AJ,\\ 116,\\ 1478\\ [ADS](http://adsabs.harvard.edu/abs/1998AJ....116.1478R)\n13. Altenhoff,\\ W.J.\\ et\\ al.\\ 1996,\\ A&A,\\ 309,\\ 953\\ [ADS](http://adsabs.harvard.edu/abs/1996A%26A...309..953A)\n14. Chamberlain,\\ M.A.\\ et\\ al.\\ 2009,\\ Icarus,\\ 202,\\ 487\\ [ADS](http://adsabs.harvard.edu/abs/2009Icar..202..487C)\n15. Altenhoff,\\ W.J.\\ et\\ al.\\ 1994,\\ A&A,\\ 287,\\ 641\\ [ADS](http://adsabs.harvard.edu/abs/1994A%26A...287..641A)\n16. Leyrat,\\ C.\\ et\\ al.\\ 2012,\\ A&A,\\ 539,\\ A154\\ [ADS](http://adsabs.harvard.edu/abs/2012A%26A...539A.154L)\n\n\n\n***\n\n\n\n\n\n### Flux Calibrator Models - Data Formats \n\nConventions and Data Formats\n\nThis section describes the conventions, the formats as well as the locations of the data of the flux density calibrator models used in setjy. The detailed descriptions of specific flux standards and list of the calibrators are found in [Flux Calibrator Models](memo-series.ipynb#flux-calibrator-models) in the Reference Material section.\n\n\n\n#### Extragalactic flux calibrator source models\n\nThe spectral flux density models are expressed in a polynomial in the form$$\\begin{equation} log S[Jy] = a + b*log\\nu + c*log^2\\nu + \u2026 \\end{equation}$$where $\\nu$ is a frequency either in MHz or GHz depending on the standard. In setjy, the point source model is constructed as a *componentlist* scaled by the spectral flux density model. For the standards, Baars, Perley 90, Perley-Taylor 95, Perley-Taylor 99, Perley-Butler 2010, and Stevens-Reynolds 2016,the polynomial coefficients are hard-coded in the code.\n\nFor Perley-Butler 2013 and Scaife-Heald 2012, the coefficients are stored in CASA tables called PerleyButler2013Coeffs and ScaifeHeald2012Coeffs, respectively located in \\~/nrao/VLA/standards/ in the CASA data directory(from CASA prompt, you can find the data root path by typing casa\\['dirs'\\]\\['data'\\]). The separation of the data from the flux calibration code makes the maintenace easy and enable a user to acces the informaiton directly. Your can access these tables using the table tool (**tb**) and **browsetable** task. The list of the column header for PerleyButler2013Coeffs is shown below:\n\n```python\nCASA <8>: tb.colnames\n--------> tb.colnames()\nOut[8]:\n['Epoch',\n'3C48_coeffs',\n'3C48_coefferrs',\n'3C138_coeffs',\n'3C138_coefferrs',\n'3C147_coeffs',\n'3C147_coefferrs',\n'3C286_coeffs',\n'3C286_coefferrs',\n'3C123_coeffs',\n'3C123_coefferrs',\n'3C295_coeffs',\n'3C295_coefferrs',\n'3C196_coeffs',\n'3C196_coefferrs']\n```\n\nThe coefficients of each source are stored in a column as a vector and the corresponding errors are stored in a seperate column. The different row represents the corresponding coefficinets at that epoch for the time variable sources while for the steady sources each row contains identical information. The frequency is assumed in GHz.\n\nThe list of the column header for ScaifeHeald2012Coeffs is shown below:\n\n```python\nCASA <11>: tb.colnames\n---------> tb.colnames()\nOut[11]:\n['Epoch',\n'3C48_coeffs',\n'3C48_coefferrs',\n'3C147_coeffs',\n'3C147_coefferrs',\n'3C196_coeffs',\n'3C196_coefferrs',\n'3C286_coeffs',\n'3C286_coefferrs',can b\n'3C295_coeffs',\n'3C295_coefferrs',\n'3C380_coeffs',\n'3C380_coefferrs']\n```\n\n The reference frequnecy for Scaife-Heald 2012 is 150MHz. \n\n \n\n\n\n#### Solar System objects\n\nFor the solar system object used as a flux calibrator, **setjy** contstruct a model visibiity of the calibrator with the (averaged) brightness temperature model and ephemeris data of the sources as described in [ALMA Memo \\#594](https://library.nrao.edu/public/memos/alma/memo594.pdf \"ALMA Memo #594\"). While the older Bulter-JPL-Horizons 2010 standard, hard-coded the brightness temperature models in the code, the models for Butler-JPL-Horizons 2012 are tabulated in ASCII files (SSobject_name_Tb.dat) located in the CASA data directory under \\~/alma/SolarSystemModels. With an exception of Mars, the data for the brightness temparature models are stored in a simple format: 1st column - source frequency in GHz; 2nd column - the brightness temperature in Kelvin.  The follow example script shows how it can be plotted for Titan.\n\n```\nimport numpy as np\n\nrootdatapath=casa['dirs']['data']\nsource='Titan'\ndatapath=rootdatapath+'/alma/SolarSystemModels/'+source+'_Tb.dat'\ndata=np.genfromtxt(datapath)\ndata=data.transpose()\n\nfreq=data[0]\ntemp=data[1]\npl.plot(freq,temp)\npl.title(source+' Tb model')\npl.xlabel('Frequency (GHz)')\npl.ylabel('Tb (K)')\n\n \n```\n\nAnd the following is the output plot by executing the script above.\n\n{.image-inline}\n\n \n\nThe Tb model for Mars (Mars_Tb.dat) is calculated as a function of time and frequency, with tabulations every hour and at frequencies of: 30, 80, 115, 150, 200, 230, 260, 300, 330, 360, 425, 650, 800, 950, and 1000 GHz. The first line of the file contain frequencies in GHz. The data starts at the second line of the file with the format:    YYYY MM DD HH MJD Tb for at each frequency sepearated by a space.\n\n \n\n**New Asteroid models**\n\nCeres_fd_time.dat, Luthetia_fd_time.dat, Pallas_fd_time.dat, and Vesta_fd_time.dat contain thermophysical models by Th. Mueller (private communication). These time variable models are already converted to flux densities and are tabulated for 30, 80, 115, 150, 200, 230, 260, 300, 330, 360, 425, 650, 800, 950, and 1000 GHz. Time intevals are 1 hr. for Ceres and 15min. for Luthetia, Pallas, and Vesta with the data available from 2015 01 01 0UT to 2021 01 01 0 UT.  In **setjy** task,these models are automatically selected for the data with the observation dates falls within this time range. \n\n\n***\n\n\n\n\n\n### Spectral Frames \n\nSpectral Frames supported in CASA\n\n\n\n#### Spectral Frames\n\nCASA supported spectral frames:\n\n  Frame            Description                                                                                                                                                                                                                                       Definition  \n  ---------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n  REST             rest frequency                                                                                                                                                                                                                                    Lab frame or source frame; cannot be converted to any other frame\n  LSRK             LSR as a kinematic (radio) definition  (J2000) based on average velocity of stars in the Solar neighborhood                                                                                                                                       20km/s in direction of RA, Dec - \\[270,+30\\] deg (B1900.0) (Gordon 1975 [\\[1\\]](#Bibliography) )\n  LSRD             Local Standard of Rest (J2000), dynamical, IAU definition. Solar peculiar velocity in the reference frame of a circular orbit about the Galactic Center, based on average velocity of stars in the Solar neighborhood and solar peculiar motion   U$\\odot$=9kms/s, V$\\odot$=12km/s,W$\\odot$=7km/s. Or 16.552945km/s  towards l,b = 53.13, +25.02 deg (Delhaye 1965 [\\[2\\]](#Bibliography))\n  BARY             Solar System Baryceneter (J2000)                                                                                                                                                                                                                   \n  GEO              Geocentric, referenced to the Earth\\'s center                                                                                                                                                                                                      \n  TOPO             Topocentric                                                                                                                                                                                                                                       Local observatory frame, fixed in observing frequency, no doppler tracking\n  GALACTO          Galactocentric (J2000), referenced to dynamical center of the Galaxy                                                                                                                                                                              220 km/s in the direction l,b = 270, +0 deg.  (Kerr and Lynden-Bell 1986  [\\[3\\]](#Bibliography))\n  LGROUP           Mean motion of Local Group Galaxies with respect to its bary center                                                                                                                                                                               308km/s towards l,b = 105,-7\n  CMB              Cosmic Microwave Background, COBE measurements of dipole anisotropy                                                                                                                                                                               369.5km/s towards l,b = 264.4,48.4. (Kogut et al. 1993 [\\[4\\]](#Bibliography))\n  Undefined                                                                                                                                                                                                                                                           \n\n \n\n \n\n \n\n \n\n\n\n####  Doppler Types \n\nCASA supported Doppler types (velocity conventions) where $f_v$ is the observed frequency and $f_0$ is the rest frame frequency of a given lineand positive velocity V is increasing away from the observer:\n\n  Name           Description\n  -------------- -----------------------------------------------------------------------------------------------------------------------------------\n  RADIO          $$V = c \\frac{(f_0 - f_v)}{f_0}$$\n  Z              $$V=cz$$  $$z = \\frac{(f_0 - f_v)}{f_v}$$\n  RATIO          $$V=c(\\frac{f_v}{f_o})$$\n  BETA           $$V=c\\frac{(1-(\\frac{f_v}{f_0})^2)}{(1+(\\frac{f_v}{f_0})^2)}$$\n  GAMMA          $$ V=c\\frac{(1 + (\\frac{f_v}{f_0})^2)}{2\\frac{f_v}{f_0}}$$\n  OPTICAL        $$V= c\\frac{(f_0 - f_v)}{f_v}$$\n  TRUE           $$V=c\\frac{(1-(\\frac{f_v}{f_0})^2)}{(1+(\\frac{f_v}{f_0})^2)}$$\n  RELATIVISTIC   $$V=c\\frac{(1-(\\frac{f_v}{f_0})^2)}{(1+(\\frac{f_v}{f_0})^2)}$$\n\n \n\n\n\n#### Bibliography\n\n1. Gordon\\ 1975:\\ \\\"**Methods\\ of\\ Experimental\\ Physics:\\ Volume\\ 12:**\\ Astrophysics,\\ Part\\ C:\\ Radio\\ Observations\\\",\\ ed.\\ M.L.Meeks,\\ Academic\\ Press\\ 1976\\ \n2. Delhaye\\ 1965\\ (\n3. Kerr\\ F.\\ J.\\ &\\ Lynden-Bell\\ D.\\ 1986\\ MNRAS,\\ 221,\\ 1023\\ (\n4. Kogut\\ A.\\ et\\ al.\\ 1993\\ (\n^\n\n\n\n***\n\n\n\n\n\n### Time Reference Frames \n\nCASA supported time reference frames: \n \n\n<table><colgroup><col style=\"width: 33%\" /><col style=\"width: 33%\" /><col style=\"width: 33%\" /></colgroup><thead><tr class=\"header\"><th>Acronym</th><th>Name</th><th>Description </th></tr></thead><tbody><tr class=\"odd\"><td>ET</td><td>Ephemeris Time</td><td> The time scale used prior to 1984 as the independent variable in gravitational theories of the solar system. In 1984, ET was replaced by dynamical time (see TDB, TT).</td></tr><tr class=\"even\"><td>GAST</td><td>Greenwich Apparent Sidereal Time</td><td> The Greenwich hour angle of the true equinox <sup><a href=\"#fn1\">[1]</a></sup> of date.</td></tr><tr class=\"odd\"><td>GMST</td><td>Greenwich Mean Sidereal Time</td><td><p>The Greenwich hour angle of the mean equinox <sup><a href=\"#fn1\">[1]</a></sup> of date, defined as the angular distance on the celestial sphere measured westward along the celestial equator from the Greenwich meridian to the hour circle that passes through a celestial object or point.</p><p>GMST (in seconds at UT1=0) = 24110.54841 + 8640184.812866 * T<br />\n+ 0.093104 * T<span class=\"MathJax_Preview\" style=\"color: inherit;\"></span><span class=\"math inline\"><sup>2</sup></span> - 0.0000062 * T<span class=\"MathJax_Preview\" style=\"color: inherit;\"></span><span class=\"math inline\"><sup>3</sup></span><br />\nwhere T is in Julian centuries from 2000 Jan. 1 12h UT1:<br />\nT = d / 36525<br />\nd = JD - 2451545.0</p><p>(<a href=\"http://www.cv.nrao.edu/~rfisher/Ephemerides/times.html\" class=\"external-link\">http://www.cv.nrao.edu/~rfisher/Ephemerides/times.html</a>)</p></td></tr><tr class=\"even\"><td>GMST1</td><td> </td><td> GMST calculated specifically with reference to UT1</td></tr><tr class=\"odd\"><td>IAT</td><td>International Atomic Time (a.k.a. TAI en Francais):</td><td> The continuous time scale resulting from analysis by the Bureau International des Poids et Mesures of atomic time standards in many countries. The fundamental unit of TAI is the SI second <sup><a href=\"#fn2\">[2]</a></sup> on the geoid <sup><a href=\"#fn3\">[3]</a></sup> , and the epoch is 1958 January 1.</td></tr><tr class=\"even\"><td>LAST</td><td>Local Apparent Sidereal Time</td><td><p>LAST is derived from LMST by applying the equation of equinoxes <sup><a href=\"#fn1\">[1]</a></sup> or nutation of the mean pole of the Earth from mean to true position yields LAST.</p><p><a href=\"http://tycho.usno.navy.mil/sidereal.html\" class=\"external-link\">http://tycho.usno.navy.mil/sidereal.html</a></p></td></tr><tr class=\"odd\"><td>LMST</td><td>Local Mean Sidereal Time</td><td><p>Sidereal time is the hour angle of the vernal equinox, the ascending node of the ecliptic on the celestial equator. The daily motion of this point provides a measure of the rotation of the Earth with respect to the stars, rather than the Sun. It corresponds to the coordinate right ascension of a celestial body that is presently on the local meridian.<br />\nLMST is computed from the current GMST plus the local offset in longitude measured positive to the east of Greenwich, (converted to a sidereal offset by the ratio 1.00273790935 of the mean solar day to the mean sidereal day.)<br />\nLMST = GMST + (observer's east longitude)</p><p><a href=\"http://www.cv.nrao.edu/~rfisher/Ephemerides/times.html\" class=\"external-link\">http://www.cv.nrao.edu/~rfisher/Ephemerides/times.html</a><br />\n<a href=\"http://tycho.usno.navy.mil/sidereal.html\" class=\"external-link\">http://tycho.usno.navy.mil/sidereal.html</a></p></td></tr><tr class=\"even\"><td>TAI</td><td>International Atomic Time (a.k.a. TAI en Francais)</td><td>see IAT</td></tr><tr class=\"odd\"><td>TCB</td><td>Barycentric Coordinate Time</td><td> The coordinate time of the Barycentric Celestial Reference System (BCRS), which advances by SI seconds <sup><a href=\"#fn2\">[2]</a></sup> within that system. TCB is related to TCG and TT by relativistic transformations that include a secular term.</td></tr><tr class=\"even\"><td>TCG</td><td> </td><td> </td></tr><tr class=\"odd\"><td>TDB</td><td>Barycentric Dynamical Time</td><td>A time scale defined by the IAU (originally in 1976; named in 1979; revised in 2006) used in barycentric ephemerides and equations of motion. TDB is a linear function of TCB that on average tracks TT over long periods of time; differences between TDB and TT evaluated at the Earth's surface remain under 2 ms for several thousand years around the current epoch. TDB is functionally equivalent to Teph, the independent argument of the JPL planetary and lunar ephemerides DE405/LE405.</td></tr><tr class=\"even\"><td>TDT</td><td>Terrestrial Dynamical Time</td><td> The time scale for apparent geocentric ephemerides defined by a 1979 IAU resolution. In 1991 it was replaced by TT.</td></tr><tr class=\"odd\"><td>TT</td><td>Terrestrial Time</td><td> An idealized form of International Atomic Time (TAI) with an epoch offset; in practice TT = TAI + 32s.184. TT thus advances by SI seconds on the geoid <sup><a href=\"#fn3\">[3]</a></sup></td></tr><tr class=\"even\"><td>UT</td><td>Universal Time</td><td> Loosely, mean solar time on the Greenwich meridian (previously referred to as Greenwich Mean Time). In current usage, UT refers either to UT1 or to UTC.</td></tr><tr class=\"odd\"><td>UT1</td><td> </td><td> UT1 is formally defined by a mathematical expression that relates it to sidereal time. Thus, UT1 is observationally determined by the apparent diurnal motions of celestial bodies, and is affected by irregularities in the Earth's rate of rotation.</td></tr><tr class=\"even\"><td>UT2</td><td> </td><td> <p>Before 1972 the time broadcast services kept their time signals within 0.1 seconds <sup><a href=\"#fn2\">[2]</a></sup> of UT2, which is UT1 with annual and semiannual variations in the earth's rotation removed. The formal relation between UT1 and UT2 is</p><p>UT2 = UT1 + 0.022 * sin(2 * Pi * t) - 0.012 * cos(2 * Pi * t)</p><ul><li>0.006 * sin(4 * Pi * t) + 0.007 * cos(4 * Pi * t)<br />\nwhere<br />\nt = 2000.0 + (MJD - 51544.03) / 365.2422<br />\nis the Besselian day fraction, and MJD is the Modified Julian Date (Julian Date - 2400000.5)<br />\n<a href=\"http://www.cv.nrao.edu/~rfisher/Ephemerides/times.html\" class=\"external-link\">http://www.cv.nrao.edu/~rfisher/Ephemerides/times.html</a></li></ul></td></tr><tr class=\"odd\"><td>UTC</td><td>Coordinated Universal Time</td><td>UTC is based on IAT but is maintained within 0s.9 of UT1 by the introduction of leap seconds when necessary.  </td></tr></tbody></table>\n\n<table class=\"footnote-table\" style=\"height: 217px;\" width=\"828\"><colgroup><col style=\"width: 50%\" /><col style=\"width: 50%\" /></colgroup><tbody><tr class=\"odd\"><td style=\"text-align: left;\">Footnote Number</td><td>1</td></tr><tr class=\"even\"><td style=\"text-align: left;\">Footnote Text</td><td><p>mean equator and equinox v. true equator and equinox: The mean equator and equinox are used for the celestial coordinate system defined by the orientation of the Earth's equatorial plane on some specified date together with the direction of the dynamical equinox on that date, neglecting nutation. Thus, the mean equator and equinox moves in response only to precession. Positions in a star catalog have traditionally been referred to a catalog equator and equinox that approximate the mean equator and equinox of a standard epoch.<br />\nThe true equator and equinox are affected by both precession and nutation. The Equation of the Equinoxes is the difference (apparent sidereal time minus mean sidereal time). Equivalently, the difference between the right ascensions of the true and mean equinoxes, expressed in time units.</p><p> </p><p> </p><p> </p></td></tr></tbody></table>\n\n<table class=\"footnote-table\"><colgroup><col style=\"width: 50%\" /><col style=\"width: 50%\" /></colgroup><tbody><tr class=\"odd\"><td style=\"text-align: left;\"><p>FootnoteNumber</p></td><td>2</td></tr><tr class=\"even\"><td style=\"text-align: left;\">Footnote Text</td><td><p> The Systeme International (SI) second is defined as the duration of 9,192,631,770 cycles of radiation corresponding to the transition between two hyperfine levels of the ground state of caesium 133.</p><p> </p></td></tr></tbody></table>\n\n<table class=\"footnote-table\"><colgroup><col style=\"width: 50%\" /><col style=\"width: 50%\" /></colgroup><tbody><tr class=\"odd\"><td style=\"text-align: left;\">Footnote Number</td><td>3</td></tr><tr class=\"even\"><td style=\"text-align: left;\">Footnote Text</td><td><p>The geoid is an equipotential surface that coincides with mean sea level in the open ocean. On land it is the level surface that would be assumed by water in an imaginary network of frictionless channels connected to the ocean.</p><p> </p><p> </p></td></tr></tbody></table>\n\nFootnote(s)\n\n<div>\n\n^1.\\ mean\\ equator\\ and\\ equinox\\ v.\\ true\\ equator\\ and\\ equinox:\\ The\\ mean\\ equator\\ and\\ equinox\\ are\\ used\\ for\\ the\\ celestial\\ coordinate\\ system\\ defined\\ by\\ the\\ orientation\\ of\\ the\\ Earth\\'s\\ equatorial\\ plane\\ on\\ some\\ specified\\ date\\ together\\ with\\ the\\ direction\\ of\\ the\\ dynamical\\ equinox\\ on\\ that\\ date,\\ neglecting\\ nutation.\\ Thus,\\ the\\ mean\\ equator\\ and\\ equinox\\ moves\\ in\\ response\\ only\\ to\\ precession.\\ Positions\\ in\\ a\\ star\\ catalog\\ have\\ traditionally\\ been\\ referred\\ to\\ a\\ catalog\\ equator\\ and\\ equinox\\ that\\ approximate\\ the\\ mean\\ equator\\ and\\ equinox\\ of\\ a\\ standard\\ epoch.\\ The\\ true\\ equator\\ and\\ equinox\\ are\\ affected\\ by\\ both\\ precession\\ and\\ nutation.\\ The\\ Equation\\ of\\ the\\ Equinoxes\\ is\\ the\\ difference\\ (apparent\\ sidereal\\ time\\ minus\\ mean\\ sidereal\\ time).\\ Equivalently,\\ the\\ difference\\ between\\ the\\ right\\ ascensions\\ of\\ the\\ true\\ and\\ mean\\ equinoxes,\\ expressed\\ in\\ time\\ units.\\  \\  \\  \\ [\u21a9](#ref1 \"Jump back to footnote 1 in the text.\")^\n\n</div>\n\n<div>\n\n^2.\\  The\\ Systeme\\ International\\ (SI)\\ second\\ is\\ defined\\ as\\ the\\ duration\\ of\\ 9,192,631,770\\ cycles\\ of\\ radiation\\ corresponding\\ to\\ the\\ transition\\ between\\ two\\ hyperfine\\ levels\\ of\\ the\\ ground\\ state\\ of\\ caesium\\ 133.\\  \\ [\u21a9](#ref2 \"Jump back to footnote 2 in the text.\")^\n\n</div>\n\n<div>\n\n^3.\\ The\\ geoid\\ is\\ an\\ equipotential\\ surface\\ that\\ coincides\\ with\\ mean\\ sea\\ level\\ in\\ the\\ open\\ ocean.\\ On\\ land\\ it\\ is\\ the\\ level\\ surface\\ that\\ would\\ be\\ assumed\\ by\\ water\\ in\\ an\\ imaginary\\ network\\ of\\ frictionless\\ channels\\ connected\\ to\\ the\\ ocean.\\  \\  \\ [\u21a9](#ref3 \"Jump back to footnote 3 in the text.\")^\n\n</div>\n\n\n\n***\n\n\n\n\n\n### Coordinate Frames \n\n\nCASA supported spatial coordinate frames:\n\n  \n\n  Name        Description\n  ----------- -------------------------------------------------\n  J2000       mean equator and equinox at J2000.0 (FK5)\n  JNAT        geocentric natural frame\n  JMEAN       mean equator and equinox at frame epoch\n  JTRUE       true equator and equinox at frame epoch\n  APP         apparent geocentric position\n  B1950       mean epoch and ecliptic at B1950.0.\n  B1950_VLA   mean epoch (1979.9) and ecliptic at B1950.0\n  BMEAN       mean equator and equinox at frame epoch\n  BTRUE       true equator and equinox at frame epoch\n  GALACTIC    Galactic coordinates\n  HADEC       topocentric HA and declination\n  AZEL        topocentric Azimuth and Elevation (N through E)\n  AZELSW      topocentric Azimuth and Elevation (S through W)\n  AZELNE      topocentric Azimuth and Elevation (N through E)\n  AZELGEO     geodetic Azimuth and Elevation (N through E)\n  AZELSWGEO   geodetic Azimuth and Elevation (S through W)\n  AZELNEGEO   geodetic Azimuth and Elevation (N through E)\n  ECLIPTC     ecliptic for J2000 equator and equinox\n  MECLIPTIC   ecliptic for mean equator of date\n  TECLIPTIC   ecliptic for true equator of date\n  SUPERGAL    supergalactic coordinates\n  ITRF        coordinates wrt ITRF Earth frame\n  TOPO        apparent topocentric position\n  ICRS        International Celestial reference system\n\n\n\n***\n\n\n\n\n\n### Physical Units \n\nCASA regonizes physical units as listed in the following Tables.\n\n  Prefix   Name      Value\n  -------->Physical units: Prefixes\n  \n\n  \n\n  Unit     Name                  Value\n  -------- --------------------- --------------------------\n  \\$       (currency)            1 \\_\n  \\%       (percent)             0.01\n  %%       (permille)            0.001\n  A        (ampere)              1 A\n  AE       (astronomical unit)   149597870659 m\n  AU       (astronomical unit)   149597870659 m\n  Bq       (becquerel)           1 s^\u22121^\n  C        (coulomb)             1 s A\n  F        (farad)               1 m^\u22122^ kg^\u22121^ s^4^ A^2^\n  Gy       (gray)                1 m^2^ s^\u22122^\n  H        (henry)               1 m^2^ kg s^\u22122^ A^\u22122^\n  Hz       (hertz)               1 s^\u22121^\n  J        (joule)               1 m^2^ kg s^\u22122^\n  Jy       (jansky)              10^\u221226^ kg s^\u22122^\n  K        (kelvin)              1 K\n  L        (litre)               0.001 m^3^\n  M0       (solar mass)          1.98891944407\u00d7 10^30^ kg\n  N        (newton)              1 m kg s^\u22122^\n  Ohm      (ohm)                 1 m^2^ kg s^\u22123^ A^\u22122^\n  Pa       (pascal)              1 m^\u22121^ kg s^\u22122^\n  S        (siemens)             1 m^\u22122^ kg^\u22121^ s^3^ A^2^\n  S0       (solar mass)          1.98891944407\u00d7 10^30^ kg\n  Sv       (sievert)             1 m^2^ s^\u22122^\n  T        (tesla)               1 kg s^\u22122^ A^\u22121^\n  UA       (astronomical unit)   149597870659 m\n  V        (volt)                1 m^2^ kg s^\u22123^ A^\u22121^\n  W        (watt)                1 m^2^ kg s^\u22123^\n  Wb       (weber)               1 m^2^ kg s^\u22122^ A^\u22121^\n  \\_       (undimensioned)       1 \\_\n  a        (year)                31557600 s\n  arcmin   (arcmin)              0.000290888208666 rad\n  arcsec   (arcsec)              4.8481368111\u00d710^\u22126^ rad\n  as       (arcsec)              4.8481368111e\u00d710^\u22126^ rad\n  cd       (candela)             1 cd\n  cy       (century)             3155760000 s\n  d        (day)                 86400 s\n  deg      (degree)              0.0174532925199 rad\n  g        (gram)                0.001 kg\n  h        (hour)                3600 s\n  l        (litre)               0.001 m^3^\n  lm       (lumen)               1 cd sr\n  lx       (lux)                 1 m^\u22122^ cd sr\n  m        (metre)               1 m\n  min      (minute)              60 s\n  mol      (mole)                1 mol\n  pc       (parsec)              3.08567758065\u00d710^16^ m\n  rad      (radian)              1 rad\n  s        (second)              1 s\n  sr       (steradian)           1 sr\n  t        (tonne)               1000 kg\n\n>Physical SI Units\n  \n\n \n\n  Unit        Name                           Value\n  ----------- ------------------------------ ----------------------------------------------\n  \\\"          (arcsec)                       4.8481368111\u00d710^\u22126^ rad\n  \\\"\\_2       (square arcsec)                2.35044305391\u00d7 10^\u221211^ sr\n  '           (arcmin)                       0.000290888208666 rad\n  \"           (arcsec)                       4.8481368111\u00d710^\u22126^ rad\n  \"\\_2        (square arcsec)                2.35044305391\u00d710^\u221211^ sr\n  '\\_2        (square arcmin)                8.46159499408\u00d710^\u22128^ sr\n  :           (hour)                         3600 s\n  ::          (minute)                       60 s\n  \n  Ah          (ampere hour)                  3600 s A\n  Angstrom    (angstrom)                     1e-10 m\n  Btu         (British thermal unit (Int))   1055.056 m^2^ kg s^\u22122^\n  CM          (metric carat)                 0.0002 kg\n  Cal         (large calorie (Int))          4186.8 m^2^ kg s^\u22122^\n  FU          (flux unit)                    10^\u221226^ kg s^\u22122^\n  G           (gauss)                        0.0001 kg s^\u22122^ A^\u22121^\n  Gal         (gal)                          0.01 m s^\u22122^\n  Gb          (gilbert)                      0.795774715459 A\n  Mx          (maxwell)                      10^\u22128^ m^2^ kg s^\u22122^ A^\u22121^\n  Oe          (oersted)                      79.5774715459 m^\u22121^ A\n  R           (mile)                         0.000258 kg^\u22121^ s A\n  St          (stokes)                       0.0001 m^2^ s\u22121\n  Torr        (torr)                         133.322368421 m^\u22121^ kg s^\u22122^\n  USfl_oz     (fluid ounce (US))             2.95735295625\u00d710^\u22125^ m^3^\n  USgal       (gallon (US))                  0.003785411784 m^3^\n  WU          (WSRT flux unit)               5\u00d7 10^\u221229^ kg s^\u22122^\n  abA         (abampere)                     10 A\n  abC         (abcoulomb)                    10 s A\n  abF         (abfarad)                      10^9^ m^\u22122^ kg^\u22121^ s^4^ A^2^\n  abH         (abhenry)                      10^\u22129^ m^2^ kg s^\u22122^ A^\u22122^\n  abOhm       (abohm)                        10^\u22129^ m^2^ kg s^\u22123^ A^\u22122^\n  abV         (abvolt)                       10^\u22128^ m^2^ kg s^\u22123^ A^\u22121^\n  ac          (acre)                         4046.8564224 m^2^\n  arcmin_2    (square arcmin)                8.46-2159499408\u00d710^\u22128^ sr\n  arcsec_2    (square arcsec)                2.35044305391\u00d710^\u221211^ sr\n  ata         (technical atmosphere)         98066.5 m^\u22121^.kg.s^\u22122^\n  atm         (standard atmosphere)          101325 m^\u22121^.kg.s^\u22122^\n  bar         (bar)                          100000 m^\u22121^.kg.s^\u22122^\n  beam        (undefined beam area)          1 \\_\n  cal         (calorie (Int))                4.1868 m^2^ kg s^\u22122^\n  count       (count)                        1 \\_\n  cwt         (hundredweight)                50.80234544 kg\n  deg_2       (square degree)                0.000304617419787 sr\n  dyn         (dyne)                         10^\u22125^ m kg s^\u22122^\n  eV          (electron volt)                1.60217733\u00d710^\u221219^ m^2^ kg s^\u22122^\n  erg         (erg)                          10^\u22127^ m^2^ kg s^\u22122^\n  fl_oz       (fluid ounce (Imp))            2.84130488996\u00d710^\u22125^ m^3^\n  ft          (foot)                         0.3048 m\n  fu          (flux unit)                    10^\u221226^ kg s^\u22122^\n  fur         (furlong)                      201.168 m\n  gal         (gallon (Imp))                 0.00454608782394 m^3^\n  ha          (hectare)                      10000 m^2^\n  hp          (horsepower)                   745.7 m^2^ kg s^\u22123^\n  in          (inch)                         0.0254 m\n  kn          (knot (Imp))                   0.514773333333 m s^\u22121^\n  lambda      (lambda)                       1 \\_\n  lb          (pound (avoirdupois))          0.45359237 kg\n  ly          (light year)                   9.46073047\u00d710^15^ m\n  mHg         (metre of mercury)             133322.387415 m^\u22121^ kg s^\u22122^\n  mile        (mile)                         1609.344 m\n  n_mile      (nautical mile (Imp))          1853.184 m\n  oz          (ounce (avoirdupois))          0.028349523125 kg\n  pixel       (pixel)                        1 \\_\n  sb          (stilb)                        10000 m^\u22122^ cd\n  sq_arcmin   (square arcmin)                8.46159499408\u00d710^\u22128^ sr\n  sq_arcsec   (square arcsec)                2.35044305391\u00d710^\u221211^ sr\n  sq_deg      (square degree)                0.000304617419787 sr\n  statA       (statampere)                   3.33564095198\u00d710^\u221210^ A\n  statC       (statcoulomb)                  3.33564095198\u00d710^\u221210^ s A\n  statF       (statfarad)                    1.11188031733\u00d710^\u221212^ m^\u22122^ kg^\u22121^ s^4^ A^2^\n  statH       (stathenry)                    899377374000 m^2^ kg s^\u22122^ A^\u22122^\n  statOhm     (statohm)                      899377374000 m^2^ kg s^\u22123^ A^\u22122^\n  statV       (statvolt)                     299.792458 m^2^ kg s^\u22123^ A^\u22121^\n  u           (atomic mass unit)             1.661\u00d710^\u221227^  kg\n  yd          (yard)                         0.9144 m\n  yr          (year)                         31557600 s\n\n>Custom units available in CASA\n  \n\n\n\n***\n\n\n\n\n\n### Physical Constants \n\nPhysical constants recognized by CASA\n\nThe following physical constants are defined in CASA:\n\n \n\n  Constant   Name                 Value\n  ---------- -------------------- --------------------------------\n  pi         3.14..               3.14159\n  ee         2.71..               2.71828\n  c          speed of light       2.99792\u00d710^8^ m s^\u22121^\n  G          grav. constant       6.67259\u00d710^11^ N m^2^ kg^\u22122^\n  h          Planck constant      6.62608\u00d710^\u221234^ J s\n  HI         HI line frequency    1420.41 MHz\n  R          gas constant         8.31451 J K^\u22121^ mol^\u22121^\n  NA         Avogadro \\#          6.02214\u00d710^23^ mol^\u22121^\n  e          electron charge      1.60218\u00d710^\u221219^ C\n  mp         proton mass          1.67262\u00d710^\u221227^  kg\n  mp_me      mp/me                1836.15\n  mu0        permeability vac.    1.25664\u00d710^\u22126^ H m^\u22121^\n  eps0       permittivity vac.    8.85418782\u00d710^\u221212^ F m^-1^\n  k          Boltzmann constant   1.38066\u00d710^\u221223^ J K^\u22121^\n  F          Faraday constant     96485.3 C mol^\u22121^\n  me         electron mass        9.10939\u00d710^\u221231^  kg\n  re         electron radius      2.8179e\u00d710^\u221215^  m\n  a0         Bohrs radius         5.2918\u00d710^\u221211^  m\n  R0         solar radius         6.9599\u00d710^8^  m\n  k2         IAU grav. const^2^   0.000295912 AU^3^ d^\u22122^ S0^\u22121^\n\n \n\n\n\n***\n\n\n\n\n\n## Resources and Links \n\nUseful supplementary information relevant to CASA\n\n \n\n\n\n### Tutorials\n\n-   [CASAguides](https://casaguides.nrao.edu/) contains the most comprehensive data reduction tutorials for ALMA (including simulations) and the VLA. Tutorials also exist for other telescopes, such as ATCA, SMA, and CARMA. The [CASAguides](https://casaguides.nrao.edu/) wiki is also a great resource for tips and tricks in using CASA and contains user contributed scripts.\n\n\n\n### Workshops\n\n-   [ALMA community days](https://science.nrao.edu/facilities/alma/community1) webpages provide material that was used during workshops\n-   The [2018 VLA data reduction workshop](http://www.cvent.com/events/16th-synthesis-imaging-workshop/event-summary-b36e4bc16b574d5d94229f9d885d0eff.aspx) contains course material\n-   Synthesis Imaging in Radio Astronomy II ([pdf book](https://drive.google.com/file/d/1qOcQ1xR96LVPCssTu2IxYA3ItkGdVMKj/view?usp=sharing) \\([chapters](http://www.aspbooks.org/a/volumes/table_of_contents/?book_id=292)\\)\n\n\n\n### Python\n\n-   [Python documentation](https://casa.nrao.edu/python.shtml)\n\n\n\n### Science Data Model\n\n-   The SDM description and SDM definition document can be found on [this page](casa-fundamentals.ipynb#science-data-model)\n\n\n\n### Dependencies/Libraries\n\n-   [CASA package code libraries and dependencies](https://safe.nrao.edu/wiki/bin/view/Software/CASA/CASADevelopmentToolsAndLibraries)\n\n\n\n### Memos\n\n-   [ALMA](http://library.nrao.edu/alma.shtml)\n-   [VLA](http://www.aoc.nrao.edu/evla/memolist.shtml)\n-   [ngVLA](http://library.nrao.edu/ngvla.shtml)\n\n\n\n### Related Telescopes\n\n-   [ALMA](http://www.almascience.org/)\n-   [VLA](https://public.nrao.edu/telescopes/vla/)\n-   [Greenbank](https://greenbankobservatory.org/science/)\n-   [VLBA](https://www.lbo.us/)\n-   [ATCA](https://www.narrabri.atnf.csiro.au/)\n-   [GMRT](http://www.ncra.tifr.res.in/ncra/gmrt)\n-   [Nobeyama](http://www.nro.nao.ac.jp/~nro45mrt/html/index-e.html)\n-   [SMA](https://www.cfa.harvard.edu/sma/)\n-   [NOEMA](http://iram-institute.org/EN/noema-project.php)\n-   [MeerKAT](https://www.ska.ac.za/gallery/meerkat/)\n-   [Next Generation VLA](http://ngvla.nrao.edu/)\n-   [Square Kilometre Array](https://www.skatelescope.org/)\n", "meta": {"hexsha": "6ee3392b9bea533e597eb218059961e305c80918", "size": 103746, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/notebooks/memo-series.ipynb", "max_stars_repo_name": "dmehring/casadocs", "max_stars_repo_head_hexsha": "fd1bd0c878eb5a1b7edccf7ae6d26eaa4b983edb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/notebooks/memo-series.ipynb", "max_issues_repo_name": "dmehring/casadocs", "max_issues_repo_head_hexsha": "fd1bd0c878eb5a1b7edccf7ae6d26eaa4b983edb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/notebooks/memo-series.ipynb", "max_forks_repo_name": "dmehring/casadocs", "max_forks_repo_head_hexsha": "fd1bd0c878eb5a1b7edccf7ae6d26eaa4b983edb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 72.9578059072, "max_line_length": 2614, "alphanum_fraction": 0.54926455, "converted": true, "num_tokens": 22657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807713748839185, "lm_q2_score": 0.11124120798077021, "lm_q1q2_score": 0.037608109164889644}}
{"text": "```python\nimport tellurium as te\n# install cobra (https://github.com/opencobra/cobrapy)\nte.installPackage('cobra')\n# update cobra to latest version\nte.upgradePackage('cobra')\n# remove cobra\n# te.removePackage('cobra')\n```\n\n    Requirement already satisfied: cobra in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages\n    Requirement already satisfied: swiglpk in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from cobra)\n    Requirement already satisfied: future in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from cobra)\n    Requirement already satisfied: pandas>=0.17.0 in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from cobra)\n    Requirement already satisfied: optlang>=1.2.1 in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from cobra)\n    Requirement already satisfied: ruamel.yaml<0.15 in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from cobra)\n    Requirement already satisfied: numpy>=1.6 in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from cobra)\n    Requirement already satisfied: tabulate in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from cobra)\n    Requirement already satisfied: python-dateutil>=2 in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from pandas>=0.17.0->cobra)\n    Requirement already satisfied: pytz>=2011k in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from pandas>=0.17.0->cobra)\n    Requirement already satisfied: sympy>=1.0.0 in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from optlang>=1.2.1->cobra)\n    Requirement already satisfied: six>=1.9.0 in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from optlang>=1.2.1->cobra)\n    Requirement already satisfied: mpmath>=0.19 in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from sympy>=1.0.0->optlang>=1.2.1->cobra)\n    Requirement already up-to-date: cobra in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages\n    Requirement already up-to-date: swiglpk in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from cobra)\n    Requirement already up-to-date: future in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from cobra)\n    Requirement already up-to-date: pandas>=0.17.0 in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from cobra)\n    Requirement already up-to-date: optlang>=1.2.1 in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from cobra)\n    Requirement already up-to-date: ruamel.yaml<0.15 in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from cobra)\n    Requirement already up-to-date: numpy>=1.6 in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from cobra)\n    Requirement already up-to-date: tabulate in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from cobra)\n    Requirement already up-to-date: python-dateutil>=2 in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from pandas>=0.17.0->cobra)\n    Requirement already up-to-date: pytz>=2011k in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from pandas>=0.17.0->cobra)\n    Requirement already up-to-date: sympy>=1.0.0 in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from optlang>=1.2.1->cobra)\n    Requirement already up-to-date: six>=1.9.0 in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from optlang>=1.2.1->cobra)\n    Requirement already up-to-date: mpmath>=0.19 in /home/poltergeist/.config/Tellurium/telocal/python-3.6.1/lib/python3.6/site-packages (from sympy>=1.0.0->optlang>=1.2.1->cobra)\n\n", "meta": {"hexsha": "8c3ae7f710451ca4edb60ccc2d94857cb2485633", "size": 5557, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/notebooks/core/methods_installing_packages.ipynb", "max_stars_repo_name": "kirichoi/tellurium", "max_stars_repo_head_hexsha": "77cf6e794600587741ebe209644a78051e0db1d5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/notebooks/core/methods_installing_packages.ipynb", "max_issues_repo_name": "kirichoi/tellurium", "max_issues_repo_head_hexsha": "77cf6e794600587741ebe209644a78051e0db1d5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/notebooks/core/methods_installing_packages.ipynb", "max_forks_repo_name": "kirichoi/tellurium", "max_forks_repo_head_hexsha": "77cf6e794600587741ebe209644a78051e0db1d5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 69.4625, "max_line_length": 191, "alphanum_fraction": 0.6611481015, "converted": true, "num_tokens": 1325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.08632347306042909, "lm_q1q2_score": 0.03746278728572489}}
{"text": "```python\nimport os\nfrom IPython.display import HTML\n\nimport ezmarkdown as md\n```\n\n\n```python\ntext_md = r\"\"\"\n##This notebook shows how to use `ezmarkdown` to create standalone HTML documents\n+ Based on a series of examples.\n+ To install, run the following command in your terminal.  \n```pip install ezmarkdown```\n\"\"\"\ntext_html = md.md_to_html(text_md)\nHTML(text_html)\n```\n\n\n\n\n\n    <style>\n\n    /* To position Latex MathJax expressions - otherwise left-aligned by default */\n\n    div.output_area .math_center .MathJax_Display {\n        text-align: center !important;\n    }\n\n    div.output_area .math_right .MathJax_Display {\n        text-align: right !important;\n    }\n\n\n    /* To center markdown table - otherwise left-aligned by default */\n\n    div.output_area .rendered_html .table_center table {\n        margin: auto;\n    }\n\n\n    </style>\n    <h2>This notebook shows how to use <code>ezmarkdown</code> to create standalone HTML documents</h2>\n<ul>\n<li>Based on a series of examples.</li>\n<li>To install, run the following command in your terminal.<br />\n<code>pip install ezmarkdown</code></li>\n</ul>\n\n\n\n###MarkDown input\n+ WARNING: text string must be raw e.g. r'example string'\n\n\n```python\n# path_img1 = 'data/svgclock.svg'\n# path_img2 = 'data/example2.jpg'\n# path_img3 = 'data/example4.png'\n\npath_img1 = 'http://upload.wikimedia.org/wikipedia/commons/f/fd/Ghostscript_Tiger.svg'\npath_img2 = 'http://upload.wikimedia.org/wikipedia/commons/thumb/3/3e/Einstein_1921_by_F_Schmutzer_-_restoration.jpg/220px-Einstein_1921_by_F_Schmutzer_-_restoration.jpg'\npath_img3 = 'http://upload.wikimedia.org/wikipedia/en/thumb/f/f9/Singing_in_the_rain_poster.jpg/220px-Singing_in_the_rain_poster.jpg'\n\n\ntext_md = r\"\"\"\n#Header One\n##Header Two\n###Header Three\n####Header Four\n\n<p><em>Native</em> <strong>HTML</strong> sample</p>\n\n##Caract\u00e8res avec accents  \n+ Un po\u00e8me de Paul Verlaine  \n\nLes sanglots longs  \nDes violons  \nDe l'automne  \nBlessent mon c\u0153ur  \nD'une langueur  \nMonotone.  \n\nTout suffocant  \nEt bl\u00eame, quand  \nSonne l'heure,  \nJe me souviens  \nDes jours anciens  \nEt je pleure  \n\nEt je m'en vais  \nAu vent mauvais  \nQui m'emporte  \nDe\u00e7\u00e0, del\u00e0,  \nPareil \u00e0 la  \nFeuille morte.  \n\n+ Autre example: \u00e7\u00e0 avec accent, symbole de l'Euro \u20ac\n+ Et aussi \u00e9quations Latex inline $\\mu$ ou encore $e^{i\\pi}=-1$\n\n##Multi line Latex examples\n\nA mathjax expression, by default left-aligned.\n$$\n\\frac{n!}{k!(n-k)!} = \\binom{n}{k}\n$$\n\nA mathjax expression, centered.\n<div class=\"math_center\">\n$$\n\\begin{equation} x = a_0 + \\cfrac{1}{a_1 + \\cfrac{1}{a_2 + \\cfrac{1}{a_3 + \\cfrac{1}{a_4} } } } \\end{equation}\n$$\n</div>\n\n\nA mathjax expression, right-aligned.\n<div class=\"math_right\">\n$$\nA_{m,n} = \\begin{pmatrix} a_{1,1} & a_{1,2} & \\cdots & a_{1,n} \\\\ a_{2,1} & a_{2,2} & \\cdots & a_{2,n} \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\ a_{m,1} & a_{m,2} & \\cdots & a_{m,n} \\end{pmatrix}\n$$\n</div>\n\n##List Example\n\nHere is a list of items :\n\n- Item no 1\n- Item no 2\n- etc\n- Very long item that I need to write on 2 lines\nazerty azerty azerty azerty azerty azerty azerty azerty azerty azerty \n\n\n##A block quote\n\n> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\n\n##Tables\n\n**[links](http://example.com)**\n\n4. Apples\n5. Oranges\n6. Pears\n\nA centered table\n<div class=\"table_center\">\n\n| Header 1 | *Header* 2 |\n| -------- | -------- |\n| `Cell 1` | [Cell 2](http://example.com) link |\n| Cell 3 | **Cell 4** |\n\n</div>\n\n\nAnother table, left-aligned by default.\nSee how the mathjax expression can be left-aligned or centered in a table cell.\n\n|title1|title2|\n|-|-|\n||$$\\frac{n!}{k!(n-k)!} = \\binom{n}{k}$$|\n||<div class=\"math_center\">$$\\frac{n!}{k!(n-k)!} = \\binom{n}{k}$$</div>|\n|||\n\n\n###Finally some variables  \n+ %s\n+ %s\n+ %s\n\n\"\"\" % (path_img1,\n       path_img1,\n       path_img2,\n       path_img3,\n       'variableA',\n       'variableB',\n       'variableC')\n\ntext_html = md.md_to_html(text_md)\nHTML(text_html)\n```\n\n\n\n\n\n    <style>\n\n    /* To position Latex MathJax expressions - otherwise left-aligned by default */\n\n    div.output_area .math_center .MathJax_Display {\n        text-align: center !important;\n    }\n\n    div.output_area .math_right .MathJax_Display {\n        text-align: right !important;\n    }\n\n\n    /* To center markdown table - otherwise left-aligned by default */\n\n    div.output_area .rendered_html .table_center table {\n        margin: auto;\n    }\n\n\n    </style>\n    <h1>Header One</h1>\n<h2>Header Two</h2>\n<h3>Header Three</h3>\n<h4>Header Four</h4>\n<p><em>Native</em> <strong>HTML</strong> sample</p>\n\n<h2>Caract\u00e8res avec accents</h2>\n<ul>\n<li>Un po\u00e8me de Paul Verlaine  </li>\n</ul>\n<p>Les sanglots longs<br />\nDes violons<br />\nDe l'automne<br />\nBlessent mon c\u0153ur<br />\nD'une langueur<br />\nMonotone.  </p>\n<p>Tout suffocant<br />\nEt bl\u00eame, quand<br />\nSonne l'heure,<br />\nJe me souviens<br />\nDes jours anciens<br />\nEt je pleure  </p>\n<p>Et je m'en vais<br />\nAu vent mauvais<br />\nQui m'emporte<br />\nDe\u00e7\u00e0, del\u00e0,<br />\nPareil \u00e0 la<br />\nFeuille morte.  </p>\n<ul>\n<li>Autre example: \u00e7\u00e0 avec accent, symbole de l'Euro \u20ac</li>\n<li>Et aussi \u00e9quations Latex inline $\\mu$ ou encore $e^{i\\pi}=-1$</li>\n</ul>\n<h2>Multi line Latex examples</h2>\n<p>A mathjax expression, by default left-aligned.\n$$\n\\frac{n!}{k!(n-k)!} = \\binom{n}{k}\n$$</p>\n<p>A mathjax expression, centered.\n<div class=\"math_center\">\n$$\n\\begin{equation} x = a_0 + \\cfrac{1}{a_1 + \\cfrac{1}{a_2 + \\cfrac{1}{a_3 + \\cfrac{1}{a_4} } } } \\end{equation}\n$$\n</div></p>\n<p>A mathjax expression, right-aligned.\n<div class=\"math_right\">\n$$\nA_{m,n} = \\begin{pmatrix} a_{1,1} &amp; a_{1,2} &amp; \\cdots &amp; a_{1,n} \\\\ a_{2,1} &amp; a_{2,2} &amp; \\cdots &amp; a_{2,n} \\\\\n\\vdots &amp; \\vdots &amp; \\ddots &amp; \\vdots \\\\ a_{m,1} &amp; a_{m,2} &amp; \\cdots &amp; a_{m,n} \\end{pmatrix}\n$$\n</div></p>\n<h2>List Example</h2>\n<p>Here is a list of items :</p>\n<ul>\n<li>Item no 1</li>\n<li>Item no 2</li>\n<li>etc</li>\n<li>Very long item that I need to write on 2 lines\nazerty azerty azerty azerty azerty azerty azerty azerty azerty azerty </li>\n</ul>\n<h2>A block quote</h2>\n<blockquote>\n<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>\n</blockquote>\n<h2>Tables</h2>\n<p><strong><a href=\"http://example.com\">links</a></strong></p>\n<ol>\n<li>Apples</li>\n<li>Oranges</li>\n<li>Pears</li>\n</ol>\n<p>A centered table\n<div class=\"table_center\"></p>\n<table>\n<thead>\n<tr>\n<th>Header 1</th>\n<th><em>Header</em> 2</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>Cell 1</code></td>\n<td><a href=\"http://example.com\">Cell 2</a> link</td>\n</tr>\n<tr>\n<td>Cell 3</td>\n<td><strong>Cell 4</strong></td>\n</tr>\n</tbody>\n</table>\n</div>\n\n<p>Another table, left-aligned by default.\nSee how the mathjax expression can be left-aligned or centered in a table cell.</p>\n<table>\n<thead>\n<tr>\n<th>title1</th>\n<th>title2</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td></td>\n<td>$$\\frac{n!}{k!(n-k)!} = \\binom{n}{k}$$</td>\n</tr>\n<tr>\n<td></td>\n<td><div class=\"math_center\">$$\\frac{n!}{k!(n-k)!} = \\binom{n}{k}$$</div></td>\n</tr>\n<tr>\n<td></td>\n<td></td>\n</tr>\n</tbody>\n</table>\n<h3>Finally some variables</h3>\n<ul>\n<li>variableA</li>\n<li>variableB</li>\n<li>variableC</li>\n</ul>\n\n\n\n###Create HTML document\n+ Save notebook before creating doc\n+ Make sure to update the notebook name if necessary\n+ `selected_cells` is the list of cells that will be written in the html doc\n  + Count cells (i.e. including code **and** markdown cells) starting from 0\n  + A code cell has 2 parts: In[ ] and Out[ ]\n+ Several templates are available, accessible by autocomplete.\n  + TEMPLATE_INPUT_AND_OUTPUT_CELLS:\n  + TEMPLATE_INPUT_CELLS_ONLY\n  + TEMPLATE_OUTPUT_CELLS_ONLY\n  + TEMPLATE_INPUT_CELLS_TOGGLE_OUTPUT_CELLS\n  + TEMPLATE_OUTPUT_CELLS_TOGGLE_INPUT_CELLS\n  + The selected template controls how code cells will be rendered in the HTML doc. Try them out.\n+ The resulting HTML doc is created where variable `output` indicates.\n  + A subdirectory 'saved' is created is necessary.\n\n\n```python\nfname = 'demo_ezmarkdown.ipynb'\noutput = 'saved/output.html'\ntpl = md.template.TEMPLATE_OUTPUT_CELLS_ONLY\nselected_cells = [1, 3]\n\nmd.write_html_doc(fname, output, selected_cells, template=tpl)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "a8ee47a03e1b3f6224d8a573a98e3e412771d264", "size": 15029, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "demo_ezmarkdown.ipynb", "max_stars_repo_name": "oscar6echo/ezmarkdown", "max_stars_repo_head_hexsha": "a26b452fd0e39218ea9d067d50dc83095e8df5a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demo_ezmarkdown.ipynb", "max_issues_repo_name": "oscar6echo/ezmarkdown", "max_issues_repo_head_hexsha": "a26b452fd0e39218ea9d067d50dc83095e8df5a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demo_ezmarkdown.ipynb", "max_forks_repo_name": "oscar6echo/ezmarkdown", "max_forks_repo_head_hexsha": "a26b452fd0e39218ea9d067d50dc83095e8df5a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6219239374, "max_line_length": 593, "alphanum_fraction": 0.5194623727, "converted": true, "num_tokens": 2826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23370634623958197, "lm_q2_score": 0.16026603232776068, "lm_q1q2_score": 0.03745518884163568}}
{"text": "```julia\nusing Pkg\nPkg.activate(\"presentation_ebs\")\nPkg.add([\"BenchmarkTools\", \"MATLAB\", \"LoopVectorization\",\n         \"MarketData\", \"TimeSeries\", \"Distributions\",\n         \"KernelDensity\", \"StatsPlots\", \"ProgressMeter\",\n         \"PyCall\", \"Conda\", \"ARCHModels\"])\nusing Conda\nConda.add(\"arch-py\", channel=\"conda-forge\")\nPkg.update()\n\n```\n\n    \u001b[32m\u001b[1m  Activating\u001b[22m\u001b[39m environment at `C:\\Users\\sabro\\Documents\\julia\\notebooks\\presentation\\presentation_ebs\\Project.toml`\n    \u001b[32m\u001b[1m    Updating\u001b[22m\u001b[39m registry at `C:\\Users\\sabro\\.julia\\registries\\General`\n    \u001b[32m\u001b[1m    Updating\u001b[22m\u001b[39m git-repo `https://github.com/JuliaRegistries/General.git`\n    \u001b[32m\u001b[1m   Resolving\u001b[22m\u001b[39m package versions...\n    \u001b[32m\u001b[1m  No Changes\u001b[22m\u001b[39m to `C:\\Users\\sabro\\Documents\\julia\\notebooks\\presentation\\presentation_ebs\\Project.toml`\n    \u001b[32m\u001b[1m  No Changes\u001b[22m\u001b[39m to `C:\\Users\\sabro\\Documents\\julia\\notebooks\\presentation\\presentation_ebs\\Manifest.toml`\n    \u250c Info: Running `conda install -y -c conda-forge arch-py` in root environment\n    \u2514 @ Conda C:\\Users\\sabro\\.julia\\packages\\Conda\\sNGum\\src\\Conda.jl:128\n\n\n    Collecting package metadata (current_repodata.json): ...working... done\n    Solving environment: ...working... done\n    \n    # All requested packages already installed.\n    \n\n\n    \u001b[32m\u001b[1m    Updating\u001b[22m\u001b[39m registry at `C:\\Users\\sabro\\.julia\\registries\\General`\n    \u001b[32m\u001b[1m    Updating\u001b[22m\u001b[39m git-repo `https://github.com/JuliaRegistries/General.git`\n    \u001b[32m\u001b[1m  No Changes\u001b[22m\u001b[39m to `C:\\Users\\sabro\\Documents\\julia\\notebooks\\presentation\\presentation_ebs\\Project.toml`\n    \u001b[32m\u001b[1m  No Changes\u001b[22m\u001b[39m to `C:\\Users\\sabro\\Documents\\julia\\notebooks\\presentation\\presentation_ebs\\Manifest.toml`\n\n\n##### <p style=\"text-align: center; font-size: 300%\"> The Unreasonable Effectiveness of Julia </p>\n<p style=\"text-align: center; font-size: 200%\"> Simon A. Broda </p>\n<p style=\"text-align: center; font-size: 100%\"> University of Amsterdam and Hochschule Luzern<br>\n<a href=\"mailto:simon.broda@uzh.ch\">s.a.broda@uva.nl</a> </p>\n\n<p style=\"text-align: center; font-size: 100%\"> This project has received funding from the European Research Council (ERC) under the European Union's Horizon 2020 research and innovation program (grant agreement No. 750559). </p>\n\n# Outline\n* The Julia Language\n* Refresher on ARCH Models\n* The `ARCHModels.jl` Package\n   * Usage\n   * Benchmarks\n\n\nThese slides are available at https://github.com/s-broda/presentation.\n\n# The Julia Language\n## General Information\n* New programming language started at MIT.\n* Designed with scientific computing in mind.\n* Version 1.0 released in August 2018 after 9 years of development. Current version is 1.6.\n* Free and open source software. Available at https://julialang.org/.\n* In the words of its creators,\n> We want a language that\u2019s open source, with a liberal license. We want the speed of C with the dynamism of Ruby. We want a\nlanguage that\u2019s homoiconic, with true macros like Lisp, but with obvious, familiar mathematical notation like Matlab. We want\nsomething as usable for general programming as Python, as easy for statistics as R, as natural for string processing as Perl, as\npowerful for linear algebra as Matlab, as good at gluing programs together as the shell. Something that is dirt simple to learn,\nyet keeps the most serious hackers happy. We want it interactive and we want it compiled.\n\n\n\n## Highlights for Scientists\n* Interactive REPL (like Matlab, Python, R, etc.) allows for exploratory analysis, rapid prototyping.\n* Unlike these, Julia is JIT compiled, hence fast (typically within a few percent of C)\n* Syntax superficially similar to Matlab.\n* Rich type system, multiple dispatch.\n* Fast-growing eco-system with many state-of-the-art packages (e.g., `ForwardDiff.jl`, `DifferentialEquations.jl`, `JuMP`, ...).\n\n\n## A Small Taste of Julia\n\n* Let's say we want to implement a function that sums an array:\n\n\n```julia\nfunction mysum(x)\n    s = zero(eltype(x))\n    for i in eachindex(x)\n        s += x[i]\n    end\n    s\nend\nmysum([1., 2., 3.])\n```\n\n\n\n\n    6.0\n\n\n\n* Let's benchmark it:\n\n\n```julia\nx = randn(10^7);\n```\n\n\n```julia\nusing BenchmarkTools\n@btime mysum(x); # @btime runs the code a large number of times\n```\n\n      7.458 ms (1 allocation: 16 bytes)\n\n\n* For comparison, the built-in function:\n\n\n```julia\n@btime sum(x);\n```\n\n      2.680 ms (1 allocation: 16 bytes)\n\n\n* Close, but we are 2-3x slower.\n* But we can do better! 2nd attempt:\n\n\n```julia\nfunction mysum(x)\n    s = zero(eltype(x))\n    @inbounds @simd for i in eachindex(x) # @simd exploits 'single instruction multiple data', a type of parallelism\n        s += x[i]\n    end\n    s\nend\nmysum([1., 2., 3.])\n```\n\n\n\n\n    6.0\n\n\n\n\n```julia\n@btime mysum(x);\n```\n\n      2.638 ms (1 allocation: 16 bytes)\n\n\n* Not bad: by just adding a simple decorator, we now match the speed of the built-in function!\n* This is, in fact, expected: the built-in function is implemented in Julia, like most of the standard library.\n* We can even look at the code:\n\n\n```julia\n@which sum(x)\n```\n\n\n\n\nsum(a::<b>AbstractArray</b>; <i>dims, kw...</i>) in Base at <a href=\"https://github.com/JuliaLang/julia/tree/f9720dc2ebd6cd9e3086365f281e62506444ef37/base/reducedim.jl#L873\" target=\"_blank\">reducedim.jl:873</a>\n\n\n\n## One more thing...\n\n\n```julia\nusing LoopVectorization\nfunction mysum(x)\n    s = zero(eltype(x))\n    @tturbo for i in eachindex(x)\n        s += x[i]\n    end\n    s\nend\nmysum([1., 2., 3.])\n```\n\n\n\n\n    6.0\n\n\n\n\n```julia\n@btime mysum(x);\n```\n\n      948.600 \u03bcs (1 allocation: 16 bytes)\n\n\n* __Wow :o__\n* This difference comes from multi-threading; @tturbo exploits all the cores the machine has available.\n\n# Refresher on ARCH Models\n* Daily financial returns data exhibit a number of *stylized facts*:\n  * Volatility clustering\n  * Non-Gaussianity, fat tails\n  * Leverage effects: negative returns increase future volatility\n* Other types of data (e.g., changes in interest rates) exhibit similar phenomena.\n* These effects are important in many areas in finance, in particular in risk management.\n* [G]ARCH ([**G**eneralized] **A**utoregressive **C**onditional **V**olatility) models are the most popular for modelling them.\n\n## Example: volatility clustering in AAPL returns\n* The `MarketData` package allows us to download historical data from Yahoo Finance. \n\n\n```julia\nusing MarketData, TimeSeries\nr = percentchange(yahoo(:AAPL)[:AdjClose]) # returns a TimeArray\ndata = values(r) # an array containing just the plain data\n\nif !isfile(\"returns.svg\") || !isfile(\"kde.svg\")\n    using Distributions, KernelDensity, StatsPlots\n    plot(r, title=\"Volatility Clustering\", legend=:none, ylabel=\"\\$r_t\\$\")\n    savefig(\"returns.svg\")\n    plot(kde(data), label=\"Kernel Density\", title=\"Fat Tails\")\n    plot!(fit(Normal, data), label=\"Fitted Normal\")\n    savefig(\"kde.svg\")\nend\n```\n\n\n\n\n\n\n\n## (G)ARCH Models\n* Basic setup: given a sample of financial returns $\\{r_t\\}_{t\\in\\{1,\\ldots,T\\}}$, decompose $r_t$ as\n$$\nr_t=\\mu_t+\\sigma_tz_t, \\quad z_t\\stackrel{i.i.d.}{\\sim}(0,1),\n$$\nwhere $\\mu_t\\equiv\\mathbb{E}[r_t\\mid \\mathcal{F}_{t-1}]$ and $\\sigma_t^2\\equiv \\mathbb{E}[(r_t-\\mu_t)^2\\mid \\mathcal{F}_{t-1}]$.\n* Assume $\\mu_t=0$ for simplicity. Focus is on the *volatility* $\\sigma_t$. G(ARCH) models make $\\sigma_t$ a function of *past* returns and variances. Examples: \n\n## Examples\n* ARCH(q) (Engle, Econometrica 1982):\n$$\\sigma_t^2=\\omega+\\sum_{i=1}^q \\alpha_ir_{t-i}^2%,\\quad \\omega,\\alpha_i>0,\\quad \\sum_{i=1}^q\\alpha_i<1.\n$$\n* GARCH(p, q) (Bollerslev, JoE 1986)\n$$\\sigma_t^2=\\omega+ \\sum_{i=1}^p\\beta_{i}\\sigma_{t-i}^2 + \\sum_{i=1}^q\\alpha_ir_{t-i}^2%,\\quad \\omega,\\alpha_i,\\beta_i>0,\\quad \\sum_{i=1}^{\\max p,q} \\alpha_i+\\beta_i<1.\n$$\n* EGARCH(o, p, q) (Nelson, Econometrica 1991)\n$$\\log(\\sigma_t^2)=\\omega+\\sum_{i=1}^o\\gamma_{i}z_{t-i}+\\sum_{i=1}^p\\beta_i\\log(\\sigma_{t-i}^2)+\\sum_{i=1}^q \\alpha_i (|z_t|-\\mathbb{E}|z_t|)%, \\quad \\sum_{i=1}^p \\beta_i<0.\n$$\n* and many (many, many...) others \n  \n\n\n\n## Estimation\n* G(ARCH) models are usually estimated by maximum likelihood: with $f_z$ denoting the density of $z_t$,\n$$\\max \\sum_t \\log f(r_t\\mid \\mathcal{F}_{t-1})=\\max \\sum_t \\log f_z(r_t/\\sigma_t)-\\log \\sigma_t.$$\n* Recursive nature of $\\sigma_t$ means the computation cannot be \"vectorized\" $\\Rightarrow$ loops.\n* Julia is very well suited for this. Matlab (and the `rugarch` package for Python) have to implement the likelihood in C.\n\n\n\n# The `ARCHModels.jl` Package\n## Installation\n* `ARCHModels.jl` is a registered julia package. To install it, just do `using Pkg; Pkg.add(\"ARCHModels\")`\n*  Extensive documentation available at https://s-broda.github.io/ARCHModels.jl/stable/.\n\n## Key Features\n* Supports simulating, estimating, forecasting, and backtesting ARCH models.\n* Currently: ARCH, GARCH, TGARCH, and EGARCH models of arbitrary orders, with Gaussian, Student's $t$, and GED errors.\n* Regression and ARMA models for the mean equation.\n* CCC and DCC models for multivariate returns.\n* Entirely written in Julia.\n* Designed to be easily extensible with new models and distributions (nice thesis project...)\n* Gradients and Hessians (for both numerical maximization of the likelihood and constructing standard errors) are obtained by [automatic differentiation](http://www.autodiff.org/?module=Introduction) via `ForwardDiff.jl`.\n\n## Usage\n\n* The first step in building an ARCH model is usually to test for the presence of volatility clustering.\n* `ARCHModels.jl` provides [Engle's (Econometrica 1982)](https://doi.org/10.2307/1912773) ARCH-LM test for this.\n* The null is that $\\gamma_i=0$ in the auxiliary regression\n$$\nr_t^2=\\alpha+\\gamma_1 r_{t-1}^2+\\gamma_2 r_{t-2}^2+\\cdots+\\gamma_p r_{t-p}^2+\\epsilon_t.\n$$\n\n\n```julia\nusing ARCHModels\nARCHLMTest(data, 4) # p = 4 lags\n```\n\n\n\n\n    ARCH LM test for conditional heteroskedasticity\n    -----------------------------------------------\n    Population details:\n        parameter of interest:   T\u22c5R\u00b2 in auxiliary regression\n        value under h_0:         0\n        point estimate:          147.398\n    \n    Test summary:\n        outcome with 95% confidence: reject h_0\n        p-value:                     <1e-30\n    \n    Details:\n        sample size:                    10205\n        number of lags:                 4\n        LM statistic:                   147.398\n\n\n\n\n* Unsurprisingly, the test rejects.\n\n* Fitting a GARCH model is as simple as\n\n\n```julia\nmodel = fit(GARCH{1, 1}, data)\n```\n\n\n\n\n    \n    GARCH{1, 1} model with Gaussian errors, T=10205.\n    \n    Mean equation parameters:\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n         Estimate    Std.Error  z value  Pr(>|z|)\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u03bc  0.00184929  0.000257205  7.18994    <1e-12\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    Volatility parameters:\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n          Estimate  Std.Error   z value  Pr(>|z|)\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u03c9   5.67925e-6  2.9651e-6   1.91537    0.0554\n    \u03b2\u2081  0.929851    0.0136741  68.0008     <1e-99\n    \u03b1\u2081  0.0674646   0.0176432   3.82384    0.0001\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n\n\n* Alternatively, the (multithreaded!) `selectmodel` method does automatic model selection (i.e., chooses $p$ and $q$ by minimizing the AIC/AICC/BICC).\n\n\n```julia\nmodel2 = selectmodel(GARCH, data; maxlags=3, criterion=bic) # optional keyword arguments\n```\n\n\n\n\n    \n    GARCH{3, 1} model with Gaussian errors, T=10205.\n    \n    Mean equation parameters:\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n         Estimate    Std.Error  z value  Pr(>|z|)\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u03bc  0.00201148  0.000241287  8.33647    <1e-16\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    Volatility parameters:\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n           Estimate   Std.Error      z value  Pr(>|z|)\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u03c9   1.34075e-5   1.42247e-6  9.42551        <1e-20\n    \u03b2\u2081  0.520858     0.088458    5.88819        <1e-08\n    \u03b2\u2082  1.36846e-48  3.42138e-7  3.99972e-42    1.0000\n    \u03b2\u2083  0.358345     0.0886664   4.0415         <1e-04\n    \u03b1\u2081  0.101772     0.0134813   7.54909        <1e-13\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n\n\n* The return value is of type `UnivariateARCHModel`:\n\n\n```julia\ntypeof(model)\n```\n\n\n\n\n    UnivariateARCHModel{Float64, GARCH{1, 1, Float64}, StdNormal{Float64}, Intercept{Float64}}\n\n\n\n* `UnivariateARCHModel` supports many useful methods, such as \n `confint`, `aic`, `bic`, `aicc`, `informationmatrix`, `score`, `vcov`:\n\n\n\n```julia\naic(model)\n```\n\n\n\n\n    -45895.13689151763\n\n\n\n* A `UnivariateARCHModel` essentially consists of a volatility specification (of type `UnivariateVolatilitySpec`),\nan error distribution (of type `StandardizedDistribution`), and a mean specification (of type `MeanSpec`).\n* The following are currently implemented:\n\n\n```julia\nprint.(string.(subtypes(UnivariateVolatilitySpec)) .* \" \");\n```\n\n    EGARCH TGARCH \n\n\n```julia\nprint.(string.(subtypes(StandardizedDistribution))[2:end] .* \" \");\n```\n\n    StdGED StdNormal StdSkewT StdT \n\n\n```julia\nprint.(string.(subtypes(MeanSpec)).* \" \");\n```\n\n    ARMA Intercept NoIntercept Regression \n\n* We can use these to construct an ARCHModel manually:\n\n\n```julia\nT = 10^4\nmydata = zeros(T)\nvolaspec = EGARCH{1, 1, 1}([0.02, .09, .83, .01])\nusing Random; Random.seed!(1)\nmymodel = UnivariateARCHModel(volaspec, mydata; dist=StdT(4.)) # dist is an optional keyword argument\n```\n\n\n\n\n    \n    EGARCH{1, 1, 1} model with Student's t errors, T=10000.\n    \n    \n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                  \u03c9    \u03b3\u2081    \u03b2\u2081    \u03b1\u2081\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Volatility parameters:     0.02  0.09  0.83  0.01\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                 \u03bd\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Distribution parameters:   4.0\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n\n\n* With a `UnivariateARCHModel` in hand, we can do things like\n\n\n```julia\nsimulate!(mymodel) # by convention, the bang indicates that the method modifies its argument\n```\n\n\n\n\n    \n    EGARCH{1, 1, 1} model with Student's t errors, T=10000.\n    \n    \n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                  \u03c9    \u03b3\u2081    \u03b2\u2081    \u03b1\u2081\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Volatility parameters:     0.02  0.09  0.83  0.01\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                 \u03bd\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Distribution parameters:   4.0\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n\n\n\n```julia\nfit!(mymodel)\n```\n\n\n\n\n    \n    EGARCH{1, 1, 1} model with Student's t errors, T=10000.\n    \n    \n    Volatility parameters:\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n           Estimate   Std.Error   z value  Pr(>|z|)\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u03c9    0.0274054   0.00733817   3.73464    0.0002\n    \u03b3\u2081   0.113959    0.0131327    8.67752    <1e-17\n    \u03b2\u2081   0.811765    0.0244774   33.1638     <1e-99\n    \u03b1\u2081  -0.00637894  0.0153358   -0.41595    0.6774\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    Distribution parameters:\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n       Estimate  Std.Error  z value  Pr(>|z|)\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u03bd   3.83768   0.152659   25.139    <1e-99\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n\n\n\n```julia\nARCHLMTest(mymodel) # tests the standardized residuals\n```\n\n\n\n\n    ARCH LM test for conditional heteroskedasticity\n    -----------------------------------------------\n    Population details:\n        parameter of interest:   T\u22c5R\u00b2 in auxiliary regression\n        value under h_0:         0\n        point estimate:          0.0873996\n    \n    Test summary:\n        outcome with 95% confidence: fail to reject h_0\n        p-value:                     0.7675\n    \n    Details:\n        sample size:                    10000\n        number of lags:                 1\n        LM statistic:                   0.0873996\n\n\n\n\n\n```julia\npredict(mymodel, :volatility) # (:volatility | :variance | :return | :VaR)\n```\n\n\n\n\n    0.9582988646322497\n\n\n\n## Value at Risk\n\n* In-sample Value-at-Risk estimates are available via the `VaRs` function\n\n\n```julia\nmodel = fit(GARCH{1, 1}, data)\nvars = VaRs(model, 0.05)\n\nif !isfile(\"VaRplot.svg\")\n    using Plots\n    plot(-data, legend=:none, xlabel=\"\\$t\\$\", ylabel=\"\\$-r_t\\$\", title=\"Value at Risk, In-Sample\")\n    plot!(vars, color=:purple)\n    savefig(\"VaRplot.svg\"); \nend\n```\n\n\n\n* How about out-of-sample (backtesting)?\n* Requires re-estimating the model at each time step.\n* Not built in, but easy to do:\n\n\n```julia\nusing ProgressMeter\n\nT = length(data)\nwindowsize = 1000\nvars = similar(data); fill!(vars, NaN)\n@showprogress \"Fitting $(T-1-windowsize) GARCH models: \" for t = windowsize+1:T-1\n    m = fit(GARCH{1, 1}, data[t-windowsize:t])\n    vars[t+1] = predict(m, :VaR; level=0.05)    \nend\n\nif !isfile(\"VaRplot_oos.svg\")\n    using Plots\n    plot(-data, legend=:none, xlabel=\"\\$t\\$\", ylabel=\"\\$-r_t\\$\", title=\"Value at Risk, Out-of-Sample\")\n    plot!(vars, color=:purple)\n    savefig(\"VaRplot_oos.svg\"); \nend\n```\n\n    \u001b[32mFitting 9204 GARCH models: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| Time: 0:00:24\u001b[39m\n\n\n\n\n* We can backtest these out-of-sample VaR predictions using Engle and Manganelli's (2004) dynamic quantile test.\n* The test is based on a *hit series* \n$$I_t\\equiv\\cases{1, r_t<-VaR_t\\\\0, \\mbox{otherwise.}}$$\n* The null is that $\\alpha=\\beta=\\gamma=0$ in the auxiliary regression\n$$\nI_t-0.05 = \\alpha +\\beta I_{t-1} + \\gamma VaR_t+\\epsilon_t.\n$$\n\n\n```julia\nDQTest(data[windowsize+1:end], vars[windowsize+1:end], 0.05)\n```\n\n\n\n\n    Engle and Manganelli's (2004) DQ test (out of sample)\n    -----------------------------------------------------\n    Population details:\n        parameter of interest:   Wald statistic in auxiliary regression\n        value under h_0:         0\n        point estimate:          35.834\n    \n    Test summary:\n        outcome with 95% confidence: reject h_0\n        p-value:                     <1e-07\n    \n    Details:\n        sample size:                    9205\n        number of lags:                 1\n        VaR level:                      0.05\n        DQ statistic:                   35.834\n\n\n\n\n# Benchmarks\n  * Bollerslev and Ghysels (JBES 1996) data is de facto standard in comparing implementations of GARCH models.\n  * Data consist of daily German mark/British pound exchange rates (1974 observations).\n  * Available in `ARCHModels.jl` as the constant `BG96`.\n\n\n```julia\nif !isfile(\"DMGBP.svg\")\n    using Plots\n    plot(BG96, legend=:none, title=\"Bollerslev and Ghysels (1996) Data\", ylabel=\"\\$r_t\\$\", xlabel=\"\\$t\\$\")\n    savefig(\"DMGBP.svg\")\nend\n```\n\n\n\n## GARCH\n* Fitting in Julia:\n\n\n```julia\nusing BenchmarkTools\n@btime fit(GARCH{1, 1}, $BG96)\n```\n\n      3.208 ms (2546 allocations: 203.33 KiB)\n\n\n\n\n\n    \n    GARCH{1, 1} model with Gaussian errors, T=1974.\n    \n    Mean equation parameters:\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n          Estimate   Std.Error    z value  Pr(>|z|)\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u03bc  -0.00616637  0.00920152  -0.670147    0.5028\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    Volatility parameters:\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n         Estimate   Std.Error   z value  Pr(>|z|)\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u03c9   0.0107606  0.00649303   1.65725    0.0975\n    \u03b2\u2081  0.805875   0.0724765   11.1191     <1e-27\n    \u03b1\u2081  0.153411   0.0536404    2.86       0.0042\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n\n\n* Now Matlab:\n\n\n```julia\nusing MATLAB # this is for calling Matlab from within Julia. I do this because a Jupyter notebook\nmat\"version\" # only supports a single language at a time.\n```\n\n\n\n\n    \"9.10.0.1669831 (R2021a) Update 2\"\n\n\n\n\n```julia\nmat\"\"\"\nestimate(garch('ARCHLags', 1, 'GARCHLags', 1, 'offset', NaN), $BG96); 0;\nf = @()estimate(garch('ARCHLags', 1, 'GARCHLags', 1, 'offset', NaN), $BG96, 'Display', 'off');\nt = timeit(f);\ndisp(['Time per run: ', num2str(t * 1000), ' ms'])\n\"\"\"\n```\n\n     \n        GARCH(1,1) Conditional Variance Model with Offset (Gaussian Distribution):\n     \n                      Value       StandardError    TStatistic      PValue  \n                    __________    _____________    __________    __________\n    \n        Constant      0.010761       0.001323         8.1342     4.1454e-16\n        GARCH{1}       0.80597        0.01656         48.669              0\n        ARCH{1}        0.15313       0.013974         10.959     6.0379e-28\n        Offset      -0.0061904      0.0084336       -0.73402        0.46294\n    \n    Time per run: 33.029 ms\n\n\n\n\n\n    0.0\n\n\n\n* ARCH.jl is faster by a factor of about 10 or more, depending on the machine, despite Matlab calling into compiled C code.\n* Estimates are quite similar, but standard errors and $t$-statistics differ.\n* So which standard errors are correct? Let's compare with the results from Brooks et. al. (Int. J. Fcst. 2001).\n* Brooks et. al. compare implementations of the GARCH(1, 1) model.\n* They give the following estimates (**$t$-stats**) as benchmarks:\n$\\mu=\u22120.00619$ $(\\mathbf{\u22120.67})$, $\\omega=0.0108$ $(\\mathbf{1.66})$, $\\beta_1=0.806$ $(\\mathbf{11.11})$, $\\alpha_1=0.153$ $(\\mathbf{2.86})$.\n* `ARCHModels.jl` is bang on. Not sure what Matlab is doing. Look at those t-stats!\n\n\n* Finally, Python:\n\n\n```julia\nusing PyCall # for calling Python from within Julia\npy\"\"\"import pandas as pd\nimport timeit\nimport functools\nfrom arch.univariate.mean import ConstantMean\nfrom arch.univariate.distribution import Normal\nfrom arch.univariate import GARCH\nam = ConstantMean($BG96, rescale=False)\nam.volatility = GARCH(1, 0, 1)\nN = 100\nprint(am.fit(disp=\"off\"))\nprint(\"Time per run:\", timeit.timeit(functools.partial(am.fit, disp=\"off\"), number=N) / N * 1000, \"ms\") \"\"\"\n```\n\n                         Constant Mean - GARCH Model Results                      \r\n    ==============================================================================\r\n    Dep. Variable:                      y   R-squared:                       0.000\r\n    Mean Model:             Constant Mean   Adj. R-squared:                  0.000\r\n    Vol Model:                      GARCH   Log-Likelihood:               -1104.52\r\n    Distribution:                  Normal   AIC:                           2217.04\r\n    Method:            Maximum Likelihood   BIC:                           2239.39\r\n                                            No. Observations:                 1974\r\n    Date:                Sun, Jun 06 2021   Df Residuals:                     1973\r\n    Time:                        18:42:58   Df Model:                            1\r\n                                      Mean Model                                  \r\n    ==============================================================================\r\n                      coef    std err          t      P>|t|       95.0% Conf. Int.\r\n    ------------------------------------------------------------------------------\r\n    mu         -6.0765e-03  9.197e-03     -0.661      0.509 [-2.410e-02,1.195e-02]\r\n                                   Volatility Model                              \r\n    =============================================================================\r\n                     coef    std err          t      P>|t|       95.0% Conf. Int.\r\n    -----------------------------------------------------------------------------\r\n    omega      9.9151e-03  6.341e-03      1.564      0.118 [-2.512e-03,2.234e-02]\r\n    alpha[1]       0.1455  5.573e-02      2.611  9.039e-03    [3.626e-02,  0.255]\r\n    beta[1]        0.8168  7.445e-02     10.971  5.253e-28      [  0.671,  0.963]\r\n    =============================================================================\r\n    \r\n    Covariance estimator: robust\r\n    Time per run: 17.62993399999914 ms\r\n\n\n# Conclusion\n\n* We beat Matlab by a factor of about 10 and Python's `arch` package by a factor of about 6, all while delivering estimates that are closer to the benchmark. We also beat R's `rugarch` package by a factor of about 30.\n* This is despite the fact that all these packages implement the numerically heavy stuff in C rather than natively.\n* This is the _unreasonable effectiveness of Julia_: it walks like Python and runs like C.\n\n#  TODO\n* More distributions (NIG, $\\alpha$-Stable, ...)\n* More GARCH models (APARCH, RiskMetrics, IGARCH, ...)\n* Portfolio VaR: Compute the VaR of a portfolio, possibly containing derivatives, via the multivariate Delta-Gamma approximation.\n* Made feasible by the results of Broda and Arismendi (Biometrika 2021), under the assumption of a multivariate generalize hyperbolic (MGHyp) distribution.\n* This flexible distribution nests, among others, the Normal, Student's $t$, Variance Gamma, Normal Inverse Gaussian, ...\n* The scary looking expression on the next slide is already available with my Julia package `QuadraticFormsMGHyp.jl`.\n\n\n\n__Theorem__ (Broda and Arismendi, Biometrika 2021) Let $L= a_0+{a}^{T}X+X^{T}{A}X$, where $X\\sim \\mathrm{MGHyp({{\\mu},{C},{\\gamma},\\lambda,\\chi,\\psi})}$. Then\n\\begin{equation}\\label{eq:mghcdf}\n\\mathbb{P}(L\\leq l)=\\frac{1}{2}-\\frac{1}{\\pi}\\int_{0}^{\\infty}\\mathrm{Im}\\left\\{\n\\Xi_{\\lambda}(s,-xs,\\chi,\\psi)\\right\\}\\frac{\\mathrm{d}s}{s},\n\\end{equation}\nwhere $x= l-a_0-{a}^{T}{\\mu}-{\\mu}^{T}{A}{\\mu}$,\n\\begin{gather*}\n\\Xi_{\\lambda}(s,t,\\chi,\\psi)=\\frac{k_\\lambda\\{\\chi-2\\alpha_2(s)-2\\mathrm{i}t,\\psi-2\\alpha_1(s)\\}}{k_\\lambda(\\chi,\\psi)}\\rho(s),\\\\\n\\alpha_1(s)=\\mathrm{i}ks-\\frac{1}{2}s^2\\sum_{j=1}^d\\frac{e_j^2}{1-2\\mathrm{i}s\\lambda_j},\\quad\n\\alpha_2(s)=-\\frac{1}{2}s^2\\sum_{j=1}^d\\frac{d_j^2}{1-2\\mathrm{i}s\\lambda_j},\\\\\n\\rho(s)=\\exp\\left(\\mathrm{i}sc-s^2 \\sum_{j=1}^d\\frac{d_je_j}{1-2\\mathrm{i}s\\lambda_j}\\right)\\prod_{j=1}^d(1-2\\mathrm{i}s\\lambda_j)^{-1/2},\n\\end{gather*}\n$\\lambda_{j}, j \\in\\{1,\\ldots,d\\}$ are the eigenvalues of ${C}^{T}{A}{C}$, ${P}$ is an orthogonal matrix with the corresponding eigenvectors as its columns,\n$c= {a}^{T}{\\gamma}+ 2 {\\mu}^{T}{A}{\\gamma}$, $d_j$ and $e_j$ are the individual elements of ${d}={a}^{T}{CP}+2{\\mu}^{T}{ACP}$ and ${e}= {\\gamma}{ACP}$, and $k={\\gamma}^{T}{A}{\\gamma}$.\n\n\n# References\n* Bollerslev, T (1986). Generalized autoregressive conditional heteroskedasticity. *Journal of Econometrics* **31**, 307\u2013327.\n* Bollerslev, T. & Ghysels, E. (1996). Periodic Autoregressive Conditional Heteroscedasticity. *Journal of Business & Economic Statistics* **14**, 139-151. https://doi.org/10.1080/07350015.1996.10524640.\n* Broda, S.A. & Arismendi Zambrano, J. (2021). On quadratic forms in multivariate generalized hyperbolic\nrandom vectors. *Biometrika* **108**, https://doi.org/413-424.0.1093/biomet/asaa067.\n* __Broda, S.A. & Paolella, M. (2020). `ARCHModels.jl`: Estimating Arch Models in Julia. Available on SSRN. https://dx.doi.org/10.2139/ssrn.3551503__\n* Brooks, C., Burke, S. P., & Persand, G. (2001). Benchmarks and the accuracy of GARCH model estimation. *International Journal of Forecasting* **17**, 45-56. https://doi.org/10.1016/S0169-2070(00)00070-4.\n* Engle, R. F. (1982). Autoregressive Conditional Heteroscedasticity with Estimates of the Variance of United Kingdom Inflation. *Econometrica* **50**, 987-1007. https://doi.org/10.2307/1912773.\n* Engle, R. F., and Manganelli, S. (2004). CAViaR: Conditional Autoregressive Value at Risk by Regression Quantiles. *Journal of Business & Economic Statistics* **22**, 367-381. https://doi.org/10.1198/073500104000000370\n* Nelson, D.B. (1991). Conditional Heteroskedasticity in Asset Returns: A New Approach. *Econometrica* **59**, 347--370. https://doi.org/10.2307/2938260.\n\n\n\n##### <p style=\"text-align: center; font-size: 300%\"> Thank you! Questions? </p>\n", "meta": {"hexsha": "573864082d8e16f42e921d7a34a8e407bf86ba1c", "size": 47521, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "presentation.ipynb", "max_stars_repo_name": "s-broda/presentation", "max_stars_repo_head_hexsha": "747857e40239202e8f285e2f6105a0e4f12b0fe6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "presentation.ipynb", "max_issues_repo_name": "s-broda/presentation", "max_issues_repo_head_hexsha": "747857e40239202e8f285e2f6105a0e4f12b0fe6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "presentation.ipynb", "max_forks_repo_name": "s-broda/presentation", "max_forks_repo_head_hexsha": "747857e40239202e8f285e2f6105a0e4f12b0fe6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1720634921, "max_line_length": 237, "alphanum_fraction": 0.4941183898, "converted": true, "num_tokens": 8440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30074556640652345, "lm_q2_score": 0.12421301159407334, "lm_q1q2_score": 0.03735651252691965}}
{"text": "# Tutorial\n\nThis tutorial is also a Jupyter notebook, which can be found in [the example notebooks directory](https://github.com/annegambrel/xfaster/tree/main/example/notebooks). If you're running the notebook, rather than looking at the documentation produced from it, the links will not work. [Look at the docs for working links](https://annegambrel.github.io/xfaster/notebooks/XFaster_Tutorial.html).\n\nThe notebook reads intermediate output npz files from disk. To instead run the pieces starting from maps, first generate the example maps by running the script `xfaster/example/make_example_maps.py`, and set the checkpoint to something other than None.\n\n## The main ingredients of the XFaster code\n\nBefore we get into the functions that produce each of the components that gets fed into the equations for bandpower deviations, $q_b$ and the Fisher matrix (Equations 17 and 18 in the [Algorithm section](../algorithm.rst)), let's first talk about how XFaster is structured and what it expects as inputs.\n\nThere are two main python modules in XFaster: [xfaster_exec.py](../api.rst#module-xfaster.xfaster_exec) and [xfaster_class.py](../api.rst#module-xfaster.xfaster_class). [xfaster_exec.py](../api.rst#module-xfaster.xfaster_exec) contains two main functions: [xfaster_run](../api.rst#xfaster.xfaster_exec.xfaster_run) and [xfaster_submit](../api.rst#xfaster.xfaster_exec.xfaster_submit). [xfaster_run](../api.rst#xfaster.xfaster_exec.xfaster_run) calls all of the functions to make XFaster happen (all located in [xfaster_class.py](../api.rst#module-xfaster.xfaster_class)) in the order they need to happen. [xfaster_submit](../api.rst#xfaster.xfaster_exec.xfaster_submit) takes arguments for submitting the job to a queue. XFaster is not highly parallelized. However, significant speed-up is gained from using more cores in the simulation pseudo-spectrum calculation through under-the-hood use of OMP. Therefore, if you're starting from a checkpoint after \"sims\", no significant speed-up will be gained when using more cores. \n\nThere are a few other modules you might interact with: \n\n* [parse_tools.py](../api.rst#module-xfaster.parse_tools): contains a bunch of tools for converting between data structures, especially between dictionaries and matrices\n* [spec_tools.py](../api.rst#module-xfaster.spec_tools): contains functions for generating and manipulating model power spectra\n\n## Specifying what data to use\n\nThe top level module you interact with is [xfaster_exec.py](../api.rst#module-xfaster.xfaster_exec), which takes your arguments, and has some reasonable defaults for any you don't provide. In addition to arguments, you must point the code to the inputs you want to run on. The first of these inputs is maps.\n\n### Maps\n\nThe main inputs to the code are maps-- data maps, signal and noise simulations, and masks. Rather than pointing to each map individually, there is a directory structure that the code expects. Its contents look like this:\n\n    <data_root>/\n    \u251c\u2500\u2500 data_<data_type>\n    \u2502   \u251c\u2500\u2500 <data_subset1>\n    \u2502   \u2502   \u251c\u2500\u2500 map_<tag1>.fits\n    \u2502   \u2502   \u251c\u2500\u2500 ...\n    \u2502   \u2502   \u251c\u2500\u2500 map_<tagN>.fits\n    \u2502   \u251c\u2500\u2500 <data_subset2> (same filenames as <data_subset1>)\n    \u2502   \u251c\u2500\u2500 ....\n    \u2502   \u251c\u2500\u2500 <data_subsetM>\n    \u251c\u2500\u2500 signal_<signal_type>\n    \u2502   \u251c\u2500\u2500 spec_signal_<signal_type>.dat\n    \u2502   \u251c\u2500\u2500 <data_subset1>\n    \u2502   \u2502   \u251c\u2500\u2500 map_<tag1>_0000.fits\n    \u2502   \u2502   \u251c\u2500\u2500 ...\n    \u2502   \u2502   \u251c\u2500\u2500 map_<tag1>_####.fits\n    \u2502   \u2502   \u251c\u2500\u2500 ...\n    \u2502   \u2502   \u251c\u2500\u2500 map_<tagN>_0000.fits\n    \u2502   \u2502   \u251c\u2500\u2500 ...\n    \u2502   \u2502   \u251c\u2500\u2500 map_<tagN>_####.fits\n    \u2502   \u251c\u2500\u2500 ....\n    \u2502   \u251c\u2500\u2500 <data_subsetM> (same filenames as <data_subset1>)\n    \u251c\u2500\u2500 noise_<noise_type> (same filenames as signal_<signal_type>)\n    \u251c\u2500\u2500 masks_<mask_type>\n    \u2502   \u251c\u2500\u2500 mask_map_<tag1>.fits\n    \u2502   \u251c\u2500\u2500 ...\n    \u2502   \u251c\u2500\u2500 mask_map_<tagN>.fits\n    [[optional:]]\n    \u251c\u2500\u2500 foreground_<foreground_type_sim> (same filenames as signal_<signal_type>)\n    \u251c\u2500\u2500 templates_<template_type>\n    \u2502   \u251c\u2500\u2500 template1 (same filenames as data_<data_type>)\n    \u2502   \u251c\u2500\u2500 template2 (same filenames as data_<data_type>)\n    \u2514\u2500\u2500 reference_<reference_type>\n        \u251c\u2500\u2500 reference1 (same filenames as data_<data_type>)\n        \u2514\u2500\u2500 reference2 (same filenames as data_<data_type>)\n\nEach of `data`, `signal`, `noise`, and `mask` has a top level directory with a preordained, fixed prefix (`data`, `signal`, `noise`, `mask`) and then some suffix specified by the user which is appended with an underscore. So, for example, to run XFaster on the example set of maps, I need to specify in my arguments: `data_type=raw`, `signal_type=synfast`, `noise_type=gaussian`, `mask_type=rectangle`.\n\nAll maps must be HEALPIX fits files. Data maps must be named `map_<tag>.fits`; simulated signal and noise maps must be named `map_<tag>_####.fits`, where #### is any length numerical tag indicating a sim realization; and masks are labeled `mask_map_<tag>.fits`.\n\nIf using `pol=True`, masks must be 3 x Npix I,Q,U maps. You can use a different mask for intensity and polarization, in which case your mask must be 2 x Npix, where the first row is used for T and the second for P.\n\nTo indicate which maps you want, pass the argument `data_subset` a glob-parseable path relative to the top level data directory-- in this case, `data_raw`. [Glob](https://docs.python.org/3/library/glob.html) works just like the unix shell does for matching file paths, so it is easy to test in advance which maps you're going to get. Just do `ls <path_to_data_maps>/full/*150*` and check that all the maps you want to use are listed. Then, you should set `data_subset` to `full/*150*`, for example.\n\nThis is all implemented in `_get_data_files()` (called by [get_files()](../api.rst#xfaster.xfaster_class.XFaster.get_files)) like so:\n```python\n\n\n# find all map files                                                               \nmap_root = os.path.join(data_root, \"data_{}\".format(data_type))\nmap_files = []\ndata_subset = data_subset.split(\",\")\nfor f in np.atleast_1d(data_subset):\n    files = glob.glob(os.path.join(map_root, \"{}.fits\".format(f)))\n    if not len(files):\n        raise OSError(\"Missing files in data subset {}\".format(f))\n    map_files.extend(files)\ndata_subset = \",\".join(data_subset)\nmap_files = sorted(map_files)\nmap_files = [f for f in map_files if os.path.basename(f).startswith(\"map_\")]\nmap_tags = [\n    os.path.splitext(os.path.basename(f))[0].split(\"_\", 1)[1] for f in map_files\n]\n\n```\nSo you've specified which data maps you want to compute power spectra for. To get the corresponding sim maps, the code takes whatever data maps were found matching data_subset, and tries to match those to maps in the sims directory, with the only difference the sim index tag. Here's what that looks like in the function `_get_sim_files()`:\n```python\n# find all corresponding sims\n# for example, when called for signal sims:\n#     _get_sim_files(\n#         name=\"signal\",\n#         root=\"signal_{}\".format(signal_type),\n#         subset=signal_subset,\n#     )\nroot = os.path.join(data_root, root)\nnum_files = None\nall_files = []\nfor f in map_files:\n    files = sorted(\n        glob.glob(\n            f.replace(map_root, root).replace(\n                \".fits\", \"_{}.fits\".format(subset)\n            )\n        )\n    )\n    nfiles = len(files)\n    if not nfiles:\n        raise OSError(\"Missing {} sims for {}\".format(name, f))\n    ...\n    all_files.append(files)\n```\n\nIt's easy to get errors at the reading files step. XFaster requires that all your maps have the same number of sims, though you are allowed to have a different from of signal and noise sims. If you do not want to use the full set of signal and noise maps in a directory, if you can set the `signal_subset` and `noise_subset` arguments, which default to `'*'`. This glob-parseable tag is applied to the `####` sim index tag. So, if I have a set of sims, eg, `map_95_0000.fits`-`map_95_0099.fits`, as in the example, but for some reason I only want to use the first 50, I can set `signal_subset='00[0-4]*`.\n\n### Other inputs\n\nIn addition to maps, the code also requires a config file. This tells the code everything else it needs to know about your data. Here's the config file for the example:\n\n```python\n\n# Band centers in GHz (needed for foreground fitting) for each map tag.                    \n# Tags listed here should be a superset of tags that may be included in a run.             \n[frequencies]\n95 = 94.7\n150 = 151.0\n\n# A numpy dictionary containing Bl for each map tag.                                       \n# Keys should match those in freqs.                                                        \n# Missing keys should have a fwhm listed below.                                            \n# The value for each key should be a numpy array of dimensions (3, lmax + 1),              \n# for TT, TP and PP beam windows.                                                          \n[beam]\nbeam_product = None\nbeam_error_product = None\n\n# FHWM in arcmin for each map tag, if using Gaussian beam model.                           \n# Keys should match those in freqs.                                                        \n# Missing keys should be in the beam product file.                                         \n[fwhm]\n95 = 41\n150 = 29\n\n# Fractional error on the FWHM for each map tag, if using a Gaussian beam model.           \n# Keys should match those in freqs.                                                        \n# Missing keys should be in the beam product file.                                         \n[fwhm_err]\n95 = 0.001\n150 = 0.001\n\n# Whether to compute transfer function qb parameters for each map tag.                     \n# Keys should match those in freqs.                                                        \n[transfer]\n95 = true\n150 = true\n```\n\nThis is the full list of options that can be specified in the config file. \n\n## Step by step through the functions called in xfaster_exec\n### Setup and checkpoints\n\nNow we'll proceed to stepping through each function in [xfaster_exec](../api.rst#module-xfaster.xfaster_exec). You'll never run the code this way--you'll just call [xfaster_run](../api.rst#xfaster.xfaster_exec.xfaster_run) or [xfaster_submit](../api.rst#xfaster.xfaster_exec.xfaster_submit) with the arguments that then get passed to these functions. But we'll do it this way so we can illustrate some of the intermediate data products as we go.\n\nThis tutorial will follow the example script in [xfaster/example](https://github.com/annegambrel/xfaster/tree/main/example). Note however that becasue maps are not stored in the repository, this notebook is instead reading from the intermediate files written to disk. \n\nFirst, we'll import XFaster and initialize our XFaster class with some arguments.\n\n\n```python\nimport xfaster as xf\nimport matplotlib.pyplot as plt\nfrom matplotlib import colors\nimport numpy as np\n```\n\n\n```python\nX = xf.XFaster(config=\"../../example/config_example.ini\", output_root=\"../../example/outputs_example\", verbose=\"info\",\n              output_tag=\"95x150\", checkpoint=None)\n```\n\nAt the start of an XFaster run, you can specify at what checkpoint to start. The checkpoints are:\n```python\ncheckpoints = [\n\t\"files\", # find all the map files\n\t\"masks\", # load in masks and compute their pseudo-spectra\n\t\"kernels\", # compute mask mode-coupling kernels\n\t\"sims_transfer\", # compute pseudo-spectra for signal sims used for computing the transfer function\n\t\"shape_transfer\", # load in the model spectrum for the transfer function\n\t\"transfer\", # compute the transfer function\n\t\"sims\", # compute pseudo-spectra for noise sims and signal sims if they're different from those used for the transfer function\n    \"beams\", # load in the beam window functions, and apply a pixel window function if pixwin=True\n    \"data\", # compute the pseudo-spectra of the data maps\n    \"template_noise\", # compute the pseudo-spectra of template noise simulations, if using Planck dust templates\n    \"shape\", # load in the model spectrum for bandpower computation\n\t\"bandpowers\", # do the Fisher iteration to compute bandpowers\n\t\"beam_errors\", # start the likelihood over including beam error parameterization\n\t\"likelihood\", # compute the parameter likelihoods\n]\n```\n\nNote that there are options to use different signal simulations for computing the transfer function and for computing other signal terms. This is mainly useful for null tests, as that's the only mode in which signal sims are used for anything other than transfer functions (to compute the expected signal residual that is subtracted from the data pseudo-spectra). If the signal simulations lack sufficient power (eg., for BB), the transfer function may not converge due to lack of measurable power. This is not a problem unique to XFaster, and this option allows the user more flexibility in the choice of sims used for different parts of the algorithm.\n\nMost of the time, `checkpoint` can be set to None, which starts the code from the last checkpoint completed (ie, it successfully wrote its intermediate data to disk). However, if you've made changes to the code or inputs, you may wish to force the code to start from an earlier checkpoint. It will then run that checkpoint and every one after it in the checkpoint tree (given near the top of [the XFaster class](../api.rst#xfaster.xfaster_class.XFaster)).\n\n### get_files\n\nThe first function called after initializing the XFaster class is [get_files()](../api.rst#xfaster.xfaster_class.XFaster.get_files). This takes all your arguments specifying what maps to use and finds them all on disk/checks that they're there.\n\n\n```python\nfile_opts = {\n    \"data_root\": \"../../example/maps_example\",\n    \"data_subset\": \"full/*95,full/*150\",\n    \"data_type\": \"raw\",\n    \"noise_type\": \"gaussian\",\n    \"mask_type\": \"rectangle\",\n    \"signal_type\": \"synfast\",\n}\n\n```\n\n\n```python\nfile_vars = X.get_files(**file_opts)\n```\n\n\n```python\nfile_vars.keys()\n```\n\n`file_vars` is a dictionary returned by `get_files` that is also written to disk to finish the checkpoint. There are a lot of things stored in this dictionary that are mainly used internally by the code and aren't useful to an end user. For example, `num_corr` is the number of crosss-correlations of maps, which is used as a dimension to set up data structures later on. But, some of these things might be useful for debuggin. For example, all of the files found using your glob-parseable file tags are stored here, so you can see exactly what maps are being used for data:\n\n\n```python\nfile_vars['map_files']\n```\n\nOther options you might use here are \n\n* `template_type`, which points to files stored in `templates_<template_type>` for foreground template subtraction\n* `template_noise_type`, which points to files stored in `templates_noise_<template_noise_type>` for subtracting a correlated noise component from the template terms\n* `reference_type`, which points to files stored in `reference_<reference_type>` for reference signal subtraction for debiasing null tests\n* `data_root2`, which is used for null tests. This points to a second full map directory (data, signal and noise sims) for a set of data to be subtracted from the maps in data_root1.\n* `signal_type_sim`/`noise_type_sim`/`foreground_type_sim`/`template_type_sim` -- these are tags corresponding to directories `signal_<signal_type_sim>`, `noise_<noise_type_sim>`, `foreground_<foreground_type_sim>`, `template_<template_type_sim>` that are used when the `sim_data` argument is used in the `data` checkpoint. This mode chooses one of the sims for each each component in place of data maps. It adds the signal, noise, and/or foreground or template sims in alm-space. These options are not required to run in `sim_data` mode-- if they are not set, they default to `signal_type_sim=signal_type`, `noise_type_sim=noise_type`, `foreground_type_sim=None` and `template_type_sim=template_type`.\n\n### get_bin_def\n\nNow we run [get_bin_def()](../api.rst#xfaster.xfaster_class.XFaster.get_bin_def) set up a dictionary that tells where the edges of the CMB bins are for each spectrum. We can also choose whether to fit for noise residuals or foregrounds, which we can set to have different bin widths than the CMB bins.\n\n\n```python\nbd = X.get_bin_def(bin_width=25, lmin=2, lmax=500, tbeb=True, foreground_fit=False, \n                   residual_fit=True, bin_width_res=100)\n```\n\n\n```python\nbd.keys()\n```\n\n\n```python\nbd['cmb_tt']\n```\n\nThis dictionary has a key for each type of spectrum that will be fit, each of which stores the bin edges used for that spectrum fit. Each of these bin edge pairs represents a separate bandpower deviation ($q_b$) that will be fit.\n\nResiduals are fit per map, and by default are fit only for EE and BB, which are constrained to have the same fit parameter. To change this, use the option `res_specs`, which takes a list of the spectra you want to fit residuals for, ie. `[\"TT\", \"EE\", \"BB\"]` if you'd like to fit all of the spectra separately.\n\nThe last option you might wish to use is `weighted_bins`, which changes the default $\\chi_b(\\ell)$ binning operator from a tophat to one that weights by $\\ell(\\ell+1)$.\n\n### get_mask_weights\n\nWe have now finished all the set-up. Now it's time to start calculating things. First, we compute the cross spectra of our masks--which will be needed for computing the $K_{\\ell \\ell^{\\prime}}$ mode-coupling matrix--and the $g_\\ell$ mode-counting factor. This is done with [get_mask_weights()](../api.rst#xfaster.xfaster_class.XFaster.get_mask_weights).\n\nFor the example, we will not apply an empirical correction to $g_\\ell$, the calibration of which is discussed in Section 2.3.2 of the [XFaster paper](https://arxiv.org/abs/2104.01172). Otherwise, we would set `apply_gcorr=True`, and the code would look in the masks directory for this correction file for each map. The `reload_gcorr` option is only useful when doing the empirical calibration; it reloads the file, while by-passing the checkpoint tree that is usually performed after `get_mask_weights`.\n\n\n```python\nw_stuff = X.get_mask_weights(apply_gcorr=False, reload_gcorr=False)\n```\n\n\n```python\nw_stuff.keys()\n```\n\n`w1`, `w2`, and `w4` are the first, second, and fourth moments of the mask. `fsky` is the fraction of sky the mask covers. These are needed for computing the $g_\\ell$ mode-counting term, labeled `gmat` in the outputs. `gmat` includes the $2\\ell+1$ factor and a correction factor, if desired.\n\n`wls`, contains the cross spectra of all the masks. For this and all other pseudo-spectra, the spectrum is computed just as `map2alm`, and then `alm2cl` healpy routines on the maps. If you're doing a polarized spectrum, you'll get three elements, (intensity, pol, intensity x pol). Since our intensity and pol masks are the same, all three elements are the same, and look like this (plotted as $D_\\ell$):\n\n\n```python\nell = np.arange(501)\nlfac = ell * (ell+1) / (2*np.pi)\nplt.plot(lfac * w_stuff['wls']['150:150'][0])\nplt.ylabel(r'$\\frac{\\ell(\\ell+1)}{2\\pi}w_\\ell$')\nplt.xlabel(r'$\\ell$')\n```\n\n**Note:** most of the quantities in XFaster are ordered dictionaries with the following nested structure:\n1. Spectra (either plain ['tt', 'ee'], etc, or ['cmb_tt', 'cmb_ee', ..., 'fg_tt', 'fg_ee', ..., 'res_tt', ...]\n2. Map/map cross. Crosses are indicated with a colon and are in alphabetical order (so 95 comes after 150, for example): ['150:150', '150:95', '95:95']\n3. Stuff. Typically an array, though depending on the data structure, it could be a more deeply nested dictionary.\n\n### get_kernels\n\nThe next step is to compute the kernels for each mask auto and cross spectrum using the function [get_kernels()](../api.rst#xfaster.xfaster_class.XFaster.get_kernels).  In the MASTER formalism, the kernel couples modes to each other on the sky due to the finite dimensions of the mask that is applied to each map that goes into computing a cross spectrum.  That is to say, the measured power at a particular $\\ell$ is a weighted average over several other neighboring modes $\\ell^\\prime$, and $K_{\\ell\\ell^\\prime}$ is the matrix that applies this weighting.\n\nThe kernels are computed from the power spectrum of the mask, computed in the previous step.\n\nLet's plot some of these up.  Because we are using the same mask for all maps, the kernels for each map pair will look identical.\n\n\n```python\nk = X.get_kernels()\nprint(k.keys())\n```\n\n\n```python\nfig, ax = plt.subplots(2, 2, figsize=(12,5.5))\nm = ax[0,0].imshow(k['kern']['150:150'], norm=colors.LogNorm(vmax=0.01, vmin=1e-10))\nax[0,0].set_title('kern')\nax[0,0].set_ylabel('$\\ell$')\nax[0,1].imshow(k['pkern']['150:150'], norm=colors.LogNorm(vmax=0.01, vmin=1e-10))\nax[0,1].set_title('pkern')\nax[1,0].imshow(k['mkern']['150:150'], norm=colors.LogNorm(vmax=0.01, vmin=1e-10))\nax[1,0].set_title('mkern')\nax[1,0].set_ylabel('$\\ell$')\nax[1,0].set_xlabel('$\\ell^\\prime$')\nax[1,1].imshow(np.abs(k['xkern']['150:150']), norm=colors.LogNorm(vmax=0.01, vmin=1e-10))\nax[1,1].set_title('xkern')\nax[1,1].set_xlabel('$\\ell^\\prime$')\nfig.colorbar(m, ax=ax.ravel().tolist());\n```\n\nNote that the shorter dimension ($\\ell$) of each kernel goes up to $\\ell_{max}$, and the longer dimension ($\\ell^\\prime$) extends to $2 \\ell_{max} + 1$.  The kernels are apodized, so that for any row $\\ell$, the kernels are zero for values $\\ell^\\prime > \\ell + \\ell_{max}$.  The longer dimension is summed over in computing the $\\tilde{\\mathcal{C}}_{b\\ell}$ terms.\n\n### get_masked_sims\n\nNow we want to get the ensemble average of all of our signal and noise simulations, which we're going to use to calculate the filter transfer function and the noise shape, respectively. This is done with [get_masked_sims()](../api.rst#xfaster.xfaster_class.XFaster.get_masked_sims). The method will also compute the signal cross noise terms, which are used for null tests, where they can contribute significantly to the expected residuals that are subtracted from the data.\n\nThis function is doing a very simple thing. For each pair of maps of a given sim index, it \n\n1. Applies the mask.\n2. Transforms the maps into $a_{\\ell m}$s using the healpy routine `map2alm`.\n3. Transforms those into $\\tilde{\\mathcal{C}}_\\ell$s for that pair using the healpy routine `alm2cl`.\n4. Adds the $\\tilde{\\mathcal{C}}_\\ell$s to a running average for that particular map cross and spectrum.\n\nIt only does `map2alm` once per map and caches the result for use in other cross spectra since this is the slowest step in the function.\n\nBelow, we call the function with `transfer=True`-- this tells the code to use the sims specified in `signal_type_transfer`, which defaults to being `signal_type` if the former is not specified.\n\n\n```python\nsims = X.get_masked_sims(transfer=True)\nprint(sims.keys())\n```\n\nThe resulting outputs are:\n\n* `cls_signal`: the average of the signal-only cross spectra, used to compute the transfer function\n* `cls_noise`: the average of the noise-only cross spectra, used as the noise model, $N_\\ell$\n* `cls_sim`: the average of the signal+noise spectra, where signal and noise maps are added in $a_{\\ell m}$s and thus the spectra include SxN terms.\n* `cls_med`: the median of the signal+noise spectra-- this is mainly used for debugging potential biases seen in the pipeline\n\nThe rest of the spectra are not symmetrized. For all previously listed spectra, the result is the average of map i x map j and map j x map i, which matters for off-diagonal spectra: TE, TB, EB. Below, we preserve the individual cross spectra as they are needed for the null test model. In this model, at each Fisher iteration, the noise residual fit (per map and per residual spectrum type) is then used to adjust the expectation spectrum subtracted from the data. The expectation spectrum subtracted from, eg, map 1 T x map 2 E is $S_1^T\\times S_2^E + S_1^T \\times N_2^E + N_1^T \\times S_2^E + N_1^T \\times N_2^E$. Each of the last three terms is subject to misestimation of $N$, so we account for that by scaling the following terms by the appropriate noise residual fit.\n\n* `cls_res[\"nxn0\"]`: the average spectrum for noise i x noise j\n* `cls_res[\"nxn1\"]`: the average spectrum for noise j x noise i\n* `cls_res[\"sxn0\"]`: the average spectrum of signal i x noise j\n* `cls_res[\"sxn1\"]`: the average spectrum of noise j x signal i\n* `cls_res[\"nxs0\"]`: the average spectrum of noise i x signal j\n* `cls_res[\"nxs1\"]`: the average spectrum of signal j x noise i\n\n\nThese spectra have all the effects of the masking, filtering, and beam (for signal sims) included. Let's compare a couple of them to get a sense for what they look like.\n\n\n```python\nfig, ax = plt.subplots(1, 2)\nax[0].plot(lfac * sims['cls_signal']['tt']['95:95'], label='95 auto')\nax[0].plot(lfac * sims['cls_signal']['tt']['150:150'], label='150 auto')\nax[0].plot(lfac * sims['cls_signal']['tt']['150:95'], label='95 x 150')\nax[0].legend()\nax[0].set_ylabel(r'$D_\\ell [\\mu \\mathrm{K}^2]$')\nax[0].set_xlabel(r'$\\ell$')\nax[0].set_title('TT')\nax[1].plot(lfac * sims['cls_signal']['ee']['95:95'], label='95 auto')\nax[1].plot(lfac * sims['cls_signal']['ee']['150:150'], label='150 auto')\nax[1].plot(lfac * sims['cls_signal']['ee']['150:95'], label='95 x 150')\nax[1].legend()\nax[1].set_xlabel(r'$\\ell$')\nax[1].set_title('EE')\nfig.suptitle('cls_signal')\n```\n\nIn this example, we use the same idealized transfer function to make both 95 and 150 GHz maps, so their low-$\\ell$ signal is similar. However, for 150 GHz we use a 29 arcmin beam, and for 95 GHz, we use a broader 41 arcmin beam. The difference is evident at high $\\ell$, where the 150 GHz signal spectra recover more power.\n\nSimilarly, we can plot up the noise averages:\n\n\n```python\nfig, ax = plt.subplots(1, 2)\nax[0].plot(lfac * sims['cls_noise']['tt']['95:95'], label='95 auto')\nax[0].plot(lfac * sims['cls_noise']['tt']['150:150'], label='150 auto')\nax[0].plot(lfac * sims['cls_noise']['tt']['150:95'], label='95 x 150')\nax[0].legend()\nax[0].set_ylabel(r'$D_\\ell [\\mu \\mathrm{K}^2]$')\nax[0].set_xlabel(r'$\\ell$')\nax[0].set_title('TT')\nax[1].plot(lfac * sims['cls_noise']['ee']['95:95'], label='95 auto')\nax[1].plot(lfac * sims['cls_noise']['ee']['150:150'], label='150 auto')\nax[1].plot(lfac * sims['cls_noise']['ee']['150:95'], label='95 x 150')\nax[1].legend()\nax[1].set_xlabel(r'$\\ell$')\nax[1].set_title('EE')\nfig.suptitle('cls_noise')\n```\n\nIn making the example maps, we have set the noise amplitude to be a bit higher for 95 GHz, which is evident in the noise auto-spectra. As expected, the cross-spectra is uncorrelated and mean-zero.\n\n### get_beams\n\nThe next component we need for our equations is the beam window function, $B_\\ell$, done with [get_beams()](../api.rst#xfaster.xfaster_class.XFaster.get_beams). XFaster does not solve for this-- you have to tell it what it is. You do this in your config.ini file. You can either specify Gaussian FWHM values (in arcmin) for each map tag, or specify a `.npz` file that contains a dictionary of $B_\\ell$ vectors per map tag. You can mix and match these as well-- the code will first look for the tags in the dictionary file, and if it doesn't find the tag there, it will look for a FWHM field for that tag.\n\nThe only additional option available is `pixwin`, which is default True. This applies an additional pixel window function to your beam window function, corresponding to the $N_{side}$ of the input maps.\n\n\n```python\nbeams = X.get_beams(pixwin=True)\nprint(beams.keys())\n```\n\nWe could have a different beam for intensity and polarization. For this example, we don't, so each of the spectrum fields for beam is the same. Let's plot them for each map.\n\n\n```python\nfor freq in X.map_tags:\n    plt.plot(beams['tt'][freq], label=freq)\nplt.legend()\nplt.ylabel(r'$B_\\ell$')\nplt.xlabel(r'$\\ell$')\n```\n\n### get_signal_shape\n\nLet's check in on our progress of components we've computed. We're trying to build everything to make up our $\\tilde{\\mathcal{C}}^{XY}_{b\\ell}$s, which as a reminder are the following quantity (for TT):\n\n\\begin{equation}\n\\tilde{\\mathcal{C}}^{XY}_{b\\ell} = \\sum_{\\ell^{\\prime}} K_{\\ell \\ell^{\\prime}}^{X Y} F_{\\ell^{\\prime}}^{X Y} B_{\\ell^{\\prime}}^{2} \\mathcal{C}_{\\ell^{\\prime}}^{X Y (S)} \\chi_{b}\\left(\\ell^{\\prime}\\right)\n\\end{equation}\n\nWe have $K_{\\ell, \\ell'}$ and $B_{\\ell}$. For the transfer function calculation, we're going to set $F_\\ell$ to 1 so that we measure $q_b$s as the deviation from a uniform transfer function for our simulations. Binning, $\\chi_b$ has been chosen. All that's left is the full sky signal shape, $\\mathcal{C}_{\\ell'}^{XY (S)}$, loaded with [get_signal_shape()](../api.rst#xfaster.xfaster_class.XFaster.get_signal_shape). \n\nFor calculating the transfer function, this is just the shape spectrum that went into making our simulations. This spectrum can be specified by setting the argument `signal_transfer_spec` to a file containing the spectrum. If not provided, the code will look in the maps directory for the signal sims for a file labeled `spec_signal_<signal_type>.dat`. The file is expected to look like a CAMB output file, as demonstrated in `make_example_maps.py`, which writes such a file to the proper location in the signal sims directory.\n\n\n```python\nsignal_shape = X.get_signal_shape()\nprint(signal_shape.keys())\n```\n\nThese will look familiar to you. Note that they are as long as the long dimension of the $K_{\\ell\\ell'}$, which is 2$\\ell_{max}$ + 1. Also note that EB and TB, expected to be zero, are set to a small flat value.\n\n\n```python\nell2 = np.arange(1001)\nlfac2 = ell2 * (ell2 + 1) / (2*np.pi)\nfig, ax = plt.subplots(2, 3, figsize=(10,7))\nax = ax.flatten()\nfor i, (s, spec) in enumerate(signal_shape.items()):\n    ax[i].plot(lfac2 * spec)\n    ax[i].set_title(s)\n    if i in [0,3]:\n        ax[i].set_ylabel(r'$D_\\ell [\\mu\\mathrm{K}^2]$')\n    if i in [3,4,5]:\n        ax[i].set_xlabel(r'$\\ell$')\n```\n\n### get_transfer\n\nWe now have everything we need to compute the transfer function, which is computed per map per spectrum per CMB bin in [get_transfer()](../api.rst#xfaster.xfaster_class.XFaster.get_transfer). As a refresher, we're trying to get $q_b^{transfer}$, which is the same as our original expression for $q_b$ in [Equation 17 of the Algorithm page](https://annegambrel.github.io/xfaster/algorithm.html#equation-qb), except now we set noise=0, transfer function=1, and instead of using data for our observed signal, we use the ensemble average of our signal sims:\n\n\\begin{equation}\nq_{b}^{transfer}=\\frac{1}{2} \\sum_{b^{\\prime}} \\mathcal{F}_{b b^{\\prime}}^{-1} \\sum_{\\ell} (2 \\ell+1) g_\\ell^k\\left[ \\left(\\tilde{\\mathbf{C}}_{\\ell}^{-1} \\frac{\\partial \\tilde{\\mathbf{S}}_{\\ell}}{\\partial q_{b^{\\prime}}} \\tilde{\\mathbf{C}}_{\\ell}^{-1}\\right)\\tilde{\\mathbf{C}}_{\\ell}^{signal}\\right]_{kk}\n\\label{eq:qb_transfer}\n\\end{equation}\n\nThe expression for the Fisher matrix does not change, other than the fact that its constituents are the same as detailed above for the transfer function.\n\n\nWithin the code, `get_transfer` basically has two steps within the function itself, which it performs per map. \n\n1. Load up the $\\tilde{\\mathcal{C}}_{b\\ell}$: \n```python \ncbl = self.bin_cl_template(map_tag=m0, transfer_run=True)\n```\nThis uses the signal_shape internally that we calculated earlier, `m0` is the map, which is used to select the beam and kernel, and `transfer_run=True` sets the $F_\\ell$ term to 1.\n\n2. Run [fisher_iterate()](../api.rst#xfaster.xfaster_class.XFaster.fisher_iterate).\n```python\nret = self.fisher_iterate(cbl, m0, transfer_run=True,\n                          iter_max=iter_max, converge_criteria=converge_criteria,\n                          save_iters=save_iters, ...)\n```\n\nWe'll talk more in the `get_bandpowers` section about the details that happen from here, but broadly, XFaster takes all the inputs we've calculated and a starting $q_b$ guess (1 for all bins), computes the Fisher matrix, plugs that into the $q_b$ equation to get a new $q_b$, and repeats. Once the maximum of |(qb_new-qb)/qb| < converge_criteria, it stops iterating and saves the result.\n\nOne additional check that `get_transfer` does is to look for transfer function values that are negative. If it finds any, it changes that bin value to the average of the orignal value and the next bin's value. This typically happens due to poor choices of binning or too small a number of signal simulations.\n\nAlso, Only TT, EE, BB, and TE transfer functions are calculated. EB and TB are computed as\n```python\nqb['cmb_eb'] = np.sqrt(np.abs(qb['cmb_ee'] * qb['cmb_bb']))\nqb['cmb_tb'] = np.sqrt(np.abs(qb['cmb_tt'] * qb['cmb_bb']))\n```\n\n\n```python\ntransfer = X.get_transfer()\nprint(transfer.keys())\n```\n\nLet's look at a couple transfer functions.\n\n\n```python\nfig, ax = plt.subplots(1, 2, figsize=(10,7), sharey=True)\nax = ax.flatten()\nplot_inds = {'95': 0, '150': 1}\nfor s, spec in transfer.items():\n    for m, fl in spec.items():\n        ax[plot_inds[m]].plot(fl, label=s.split('_')[-1])\n        if 'tt' in s:\n            ax[plot_inds[m]].set_title(m)\nfor i in range(2):\n    ax[i].set_xlabel('bin')\nfor i in [0]:\n    ax[i].set_ylabel(r'$F_\\ell$')\nax[0].legend()\nax[0].set_ylim(0,1.2)\n```\n\nNote that the BB transfer function (and the EB/TB terms computed from it) start to diverge at high multipole. This is due to the lack of signal power in our input spectrum combined with the reduction in power of the beam. For this reason, you might choose to use a model spectrum with more BB power in computing your BB transfer functions.\n\n### get_masked_data\n\nNow comes the step where we compute the data term using [get_masked_data()](../api.rst#xfaster.xfaster_class.XFaster.get_masked_data). This is once again done just by taking all the pseudo-cross-spectra of all the data maps, using `healpy.map2alm` and `healpy.alm2cls`. This is also the step where the cross spectra of foreground templates is performed, if `template_type` is specified.\n\n\n```python\ncls_data = X.get_masked_data()\nprint(cls_data.keys())\n```\n\n\n```python\nfig, ax = plt.subplots(1, 2)\nax[0].plot(lfac * cls_data['cls_data']['tt']['95:95'], label='95 auto')\nax[0].plot(lfac * cls_data['cls_data']['tt']['150:150'], label='150 auto')\nax[0].plot(lfac * cls_data['cls_data']['tt']['150:95'], label='95 x 150')\nax[0].legend()\nax[0].set_ylabel(r'$D_\\ell [\\mu \\mathrm{K}^2]$')\nax[0].set_xlabel(r'$\\ell$')\nax[0].set_title('TT')\nax[1].plot(lfac * cls_data['cls_data']['ee']['95:95'], label='95 auto')\nax[1].plot(lfac * cls_data['cls_data']['ee']['150:150'], label='150 auto')\nax[1].plot(lfac * cls_data['cls_data']['ee']['150:95'], label='95 x 150')\nax[1].legend()\nax[1].set_xlabel(r'$\\ell$')\nax[1].set_title('EE')\nfig.suptitle('cls_data')\n```\n\nThere are several options for manipulating the constructed data before they are passed to the estimator.\n\n* `template_alpha`: not used for null tests.  This is a dictionary of scalar values, keyed by map tag, to scale foreground templates to be subtracted from the data.  The subtraction is done in alm-space for each tag that is included in the dictionary.\n* If `reference_type` is set at the `files` checkpoint, then some reference signal is subtracted from each half of a null split.  Typically the reference would be something like _Planck_ half-mission datasets, where the _Planck_ instrument noise between the two sets is uncorrelated, such that the cross spectrum of the two reference signals is independent of _Planck_ instrument noise.\n* If `template_noise_type` is set at the `files` checkpoint, then an ensemble of noise simulations is used to construct an estimate of the instrument noise contribution to the template subtraction and remove it from the data.  Typically this is an ensemble of _Planck_ FFP10 simulations, which by construction introduces a slight correlation in the noise between template halves.  This option accounts for that correlation.\n* `template_specs`: A list of spectra for which the template subtraction is applied.  By default, this is done for all spectra that the XFaster estimator is computing.  However, when excluding TT/TE signal from the likelihood, it is necessary to avoid subtracting foreground templates from the TT/TE spectra as well.\n\nNow, computing things for data is typically the final thing you'll be wanting to do. The first way you'll probably run the code is on simulations to make sure things make sense.  The options for doing this are explained below.\n\n### Sim options for get_masked_data\n\nThere are several options to `get_masked_data()` that dictate how to build a simulated data set from an ensemble of components on disk.  Note that these options may be passed to this function differently from `xfaster_run`.  We'll go through all of them here.\n\nFirst, there are three options that determine whether any simulated dataset is to be used at all in place of data.  If these are all `False`, then the data maps are loaded from disk as usual.\n\n* `ensemble_mean`: use `cls_sim` in place of the data spectra. This quantity, computed in [the previous sims step](#get_masked_sims) is the average of the signal+noise sims.\n* `ensemble_median`: use `cls_med`, the median of the signal+noise sims, in place of the data.\n* `sim`: if this option is `True`, the remaining options below are used to determine how the simulated dataset is constructed.  In `xfaster_run`, this option is called `sim_data`.\n\nThe following options control the construction of the dataset when `sim=True`.\n\n* `components`: A list of components to include in the simulation.  These may include `signal`, `noise`, `foreground` or `template`, and require the appropriate `<component>_type_sim` variable to have been set in `get_files()` above.  In `xfaster_run`, this option is called `sim_data_components`.\n* `index`: A dictionary of indices keyed by component name that determine which file from each ensemble to use to construct the data.  For example, `{\"signal\": 0, \"noise\": 10}` uses difference sim indices for the signal and noise components.  A `default` key sets the sim index to use for any component not included in the dictionary.  If no default is given, then `0` is assumed.  NB: in the `xfaster_run` function, this dictionary is constructed from the arguments `sim_index_default`, `sim_index_signal`, `sim_index_noise` and `sim_index_foreground`.\n* `r`: If this is not `None`, then the `signal` component of the simulated data is constructed from a linear combination of a scalar CMB term and a tensor CMB term, with the latter scaled by the value of `r`.  This option was used for SPIDER to run the ensemble of simulations needed for the Feldman-Cousins analysis, and was written to allow for constructing many different $r$-input maps in memory. For this option to work, the `signal_type_sim` argument must be set to `\"r\"`, in which case the `get_files()` function searches for an ensemble of scalar sims in the subdirectory `signal_r0` and tensor sims in the subdirectory `signal_r1tens`.  In `xfaster_run`, this option is called `sim_data_r`.\n* `qb_file`: If this option is not `None`, then it points to a `bandpowers.npz` file on disk, which contains noise residual bandpowers that can be used to scale the noise component of the simulated data.  In `xfaster_run`, this option is called `qb_file_data`.  NB: a similar option, `qb_file_sim`, can be passed to `get_masked_sims()` to instead apply the residual correction to the noise ensemble that goes into the covariance model (e.g. to test for bias or in single-map mode where fitting for noise residuals doesn't work).\n* `template_alpha_sim`: A dictionary similar to `template_alpha` above that handles the _addition_ of foreground templates to the simulated dataset.  In `xfaster_run`, this dictionary is constructed using the arguments `template_alpha_sim` (a list of floats) and `template_alpha_tags_sim` (a list of map tags for each float).\n* `save_sim`: If True, the constructed simulation is stored to disk to avoid rebuilding it later.  The filename is constructed as `data_<...>_xcorr.npz` where a set of tags is built from the components that are included in the simulation.  The output `bandpowers.npz` file corresponding to each such simulation includes the same set of tags in the filename.  This file naming scheme allows running multiple simulations in parallel without rerunning intermediate steps or creating IO conflicts on disk.  In `xfaster_run`, this option is called `save_sim_data`.\n \nFor the example case, we won't use any of these options. They can be super useful for forming expectations for your data outputs, though!\n\n### get_bandpowers\n\nNow we put it all together!  The function [get_bandpowers()](../api.rst#xfaster.xfaster_class.XFaster.get_bandpowers) works just like `get_transfer`, with the transfer function terms no longer set to unity, and instead constructed from the $q_b$s computed by `get_transfer`.\n\n#### Constructing the model spectrum\n\nThe first step is to construct the $\\tilde{\\mathcal{C}}_{b\\ell}$'s including all of the additional components in the model. This is done with [bin_cl_template()](../api.rst#xfaster.xfaster_class.XFaster.bin_cl_template).\n\n\n```python\ncbl = X.bin_cl_template(map_tag=None, transfer_run=False, use_precalc=False)\n```\n\nLet's plot up each set of components individually.  First, the CMB component, which should look familiar.  Each color represents the $\\tilde{\\mathcal{C}}_{b\\ell}$ for a single bin.  The black lines show the total shape of each component in $\\ell$ if the $q_b$ applied to each bin is set to 1 (ie, our signal model is perfectly correct).  This is what we call the *model spectrum* that we are fitting to.  Notice that the EE and BB mixing terms have very broad bins and are very low amplitude.  This is due to the shape of the $_{-}K_{\\ell\\ell^\\prime}$ kernel as a function of $\\ell$.  These shapes will look different for each map cross, due to differences in each transfer function and beam.\n\n\n```python\nfig, axs = plt.subplots(2, 4, figsize=(14,7), sharex=True)\naxs = axs.ravel()\nell = np.arange(501)\nellfac = ell * (ell + 1) / 2.0 / np.pi\ncomps = ['cmb_tt', 'cmb_te', 'cmb_ee', 'cmb_ee_mix', 'cmb_eb', 'cmb_tb', 'cmb_bb', 'cmb_bb_mix']\nfor ax, comp in zip(axs, comps):\n    ax.set_title('150 x 150 {}'.format(comp))\n    cbl1 = cbl[comp]['150:150']\n    d = cbl1.sum(axis=0)\n    ax.plot(d * ellfac, 'k')\n    for d in cbl1:\n        ax.plot(d * ellfac)\nfor i in [0,4]:\n    axs[i].set_ylabel('$D_\\ell$')\nfor i in range(4,8):\n    axs[i].set_xlabel('$\\ell$')\nplt.tight_layout()\n```\n\nThe next model component that we include accounts for residual noise in the auto-spectra.  These $\\tilde{\\mathcal{C}}_{b\\ell}$ terms do not include any transfer functions, beams or mode mixing kernels.  They are derived from the *simulated* noise spectra $\\tilde{N}_\\ell$.  These terms act as corrections to the noise model by adjusting the auto-spectrum noise components to agree with the cross terms.\n\nFor the example, we fit only for the EE and BB components, and we require them to be the same.  That is, each $q_b^{res,EEBB}$ applies to both $\\tilde{\\mathcal{C}}_{b\\ell}^{EE}$ and $\\tilde{\\mathcal{C}}_{b\\ell}^{BB}$ here. \n\nThe residual signal model is thus:\n\n\\begin{equation}\n\\tilde{\\mathbf{S}}_\\ell^{res,ij} = \\delta_{ij}\\,\n\\begin{bmatrix}\n0 & 0 & 0 \\\\ \n0 & \\sum_b q_b^{EEBB} \\tilde{\\mathcal{C}}_{b\\ell}^{EE} & 0 \\\\ \n0 & 0 & \\sum_b q_b^{EEBB} \\tilde{\\mathcal{C}}_{b\\ell}^{BB} \\\\ \n\\end{bmatrix}_{\\,res,ij}\n\\label{eq:signal_res}\n\\end{equation}\n\nand the derivatives are\n\n\\begin{equation}\n\\frac{\\partial \\tilde{\\mathbf{S}}_\\ell}{\\partial q_b^{res,ij,EEBB}} = \\delta_{ij}\\,\n\\begin{bmatrix}\n0 & 0 & 0 \\\\ \n0 & \\tilde{\\mathcal{C}}_{b\\ell}^{EE} & 0 \\\\ \n0 & 0 & \\tilde{\\mathcal{C}}_{b\\ell}^{BB} \\\\ \n\\end{bmatrix}_{\\,res,ij}\n\\label{eq:signal_res_deriv}\n\\end{equation}\n\n\n```python\nfig, axs = plt.subplots(1, 2, sharex=True, figsize=(7,3.5))\naxs = axs.ravel()\nell = np.arange(501)\nellfac = ell * (ell + 1) / 2.0 / np.pi\ncomps = ['res_ee', 'res_bb']\nfor ax, comp in zip(axs, comps):\n    ax.set_title('150 x 150 {}'.format(comp))\n    cbl1 = cbl[comp]['150:150']\n    d = cbl1.sum(axis=0)\n    ax.plot(d * ellfac, 'k')\n    for d in cbl1:\n        ax.plot(d * ellfac)\nfor i in [0]:\n    axs[i].set_ylabel('$D_\\ell$')\nfor i in range(2):\n    axs[i].set_xlabel('$\\ell$')\nplt.tight_layout()\n```\n\nNext we add our actual noise simulations to the model.  The residual noise terms discussed above are designed to account for inaccuracies in this model. For both the fiducial noise model and the noise residuals, we assume 0 average noise in cross-spectra, and so only add them to the auto-terms of the model.\n\nWe often find that the Fisher iterations have trouble converging due to numerical errors that cause the covariance to become singular. To prevent this from happening, we also include a term we call \"conditioning noise\" along the TT/EE/BB diagonals as well.  The conditioning noise is modeled as constant in $\\ell$, where the EE and BB diagonals are set to be `cond_noise` and TT is set to be 10*`cond_noise`. The typical conditioning noise is very small (1e-5 or so), and it is automatically adjusted to be the lowest level possible while still having the algorithm converge. In the final Fisher iteration, the conditioning noise is dropped.\n\nTo plot up both of these model components, along with all of the terms discussed above, let's call an internal function that computes the model spectrum for us, given the $\\tilde{\\mathcal{C}}_{b\\ell}$ terms and some model parameters $q_b$: [get_model_spectra()](../api.rst#xfaster.xfaster_class.XFaster.get_model_spectra).\n\n\n```python\nfrom collections import OrderedDict\n# construct a dummy qb array to compute input model\nqb = OrderedDict([(k, np.ones(len(v))) for k, v in X.bin_def.items()])\ncls_model = X.get_model_spectra(qb, cbl, delta=True, cls_noise=X.cls_noise, cond_noise=1e-5)\n\nfig, axs = plt.subplots(2, 3, figsize=(11,7))\naxs = axs.ravel()\nell = np.arange(501)\nellfac = ell * (ell + 1) / 2.0 / np.pi\nxname = '150:150'\nfor comp in ['cmb', 'noise', 'res', 'cond', 'total']:\n    for ax, spec in zip(axs, ['tt', 'ee', 'bb', 'te', 'eb', 'tb']):\n        stag = '{}_{}'.format(comp, spec)\n        if stag not in cls_model:\n            ax.plot(0, 0, label=comp)\n            continue\n        if comp in ['res', 'total']:\n            ax.plot(ellfac * cls_model[stag][xname], label=comp, linestyle='--')\n        else:\n            ax.plot(ellfac * cls_model[stag][xname], label=comp)\n        ax.set_title('150 x 150 {}'.format(spec))\n        if spec in ['ee', 'bb']:\n            ax.set_ylim(-0.01, 0.175)\naxs[0].legend()\nfor i in [0,3]:\n    axs[i].set_ylabel('$D_\\ell$')\nfor i in range(3,6):\n    axs[i].set_xlabel('$\\ell$')\nplt.tight_layout()\n```\n\n\n```python\nfig, axs = plt.subplots(2, 3, figsize=(11,7))\naxs = axs.ravel()\nell = np.arange(501)\nellfac = ell * (ell + 1) / 2.0 / np.pi\nxname = '150:95'\nfor comp in ['cmb', 'noise', 'res', 'cond', 'total']:\n    for ax, spec in zip(axs, ['tt', 'ee', 'bb', 'te', 'eb', 'tb']):\n        stag = '{}_{}'.format(comp, spec)\n        if stag not in cls_model or xname not in cls_model[stag]:\n            ax.plot(0, 0, label=comp)\n            continue\n        ax.plot(ellfac * cls_model[stag][xname], label=comp)\n        ax.set_title('150 x 95 {}'.format(spec))\naxs[0].legend()\nfor i in [0,3]:\n    axs[i].set_ylabel('$D_\\ell$')\nfor i in range(3,6):\n    axs[i].set_xlabel('$\\ell$')\nplt.tight_layout()\n```\n\nNote that neither conditioning noise nor residual terms are present in the cross-spectra.\n\n#### Computing the Fisher matrix\n\nOk! Now that we have all the pieces in place, all that's left is to do some matrix math and iterate over the equations for [q_b](https://annegambrel.github.io/xfaster/algorithm.html#equation-qb) and the [Fisher matrix]([qb](https://annegambrel.github.io/xfaster/algorithm.html#equation-qb) until the results converge.  The two equations are constructed in the function [fisher_calc()](../api.rst#xfaster.xfaster_class.XFaster.fisher_calc), which is called iteratively by [fisher_iterate()](../api.rst#xfaster.xfaster_class.XFaster.fisher_iterate) until convergence is reached.\n\nIn order to make all the quantities we've computed look like matrices, we have two utility functions, [dict_to_dmat()](../api.rst#xfaster.parse_tools.dict_to_dmat) and [dict_to_dsdqb_mat()](../api.rst#xfaster.parse_tools.dict_to_dsdqb_mat), that convert the dictionaries `Dmat1` (corresponding to $\\mathbf{\\tilde{C}}_\\ell$ in the equations) and `dSdqb_mat1_freq` ($\\partial \\mathbf{\\tilde{S}}_\\ell / \\partial q_b$) into matrices.\n\nThe `Dmat1` matrix has shape `(3 * num_maps, 3 * num_maps, lmax + 1)` and contains the `total` model terms for each map cross spectrum, ordered as [shown here](https://annegambrel.github.io/xfaster/algorithm.html#equation-dell).  The `dSdqb_mat1_freq` matrix has shape `(3 * num_maps, 3 * num_maps, nbins, lmax + 1)` and includes the CMB, residuals and frequency-corrected foreground components for all the crosses. We then compute the quantity\n\n\\begin{equation}\n\\mathbf{\\tilde{C}}^{-1} \\frac{\\partial \\mathbf{\\tilde{S}}}{\\partial q_b} \\mathbf{\\tilde{C}}^{-1}\n\\end{equation}\n\nusing the following code:\n\n```python\nDinv = np.linalg.inv(Dmat1.swapaxes(0, -1)).swapaxes(0, -1)\neye = np.eye(len(gmat))\nmat1 = np.einsum('ij...,jk...->ik...', eye, Dinv)\nmat2 = np.einsum('klm...,ln...->knm...', dSdqb_mat1_freq, Dinv)\nmat = np.einsum('ik...,knm...->inm...', mat1, mat2)\n```\n\nThe first line computes the inverse of $D$, ell-by-ell along the first two dimensions.  The next two lines are necessary due to some quirk of memory access in python; this is just multiplying the first two dimensions of `Dmat1` by the identity matrix.  The last two lines do the matrix multiplication along the first two dimensions of each of the matrices.\n\nNow, we apply the $\\mathbf{g}_\\ell$ mode-counting factor, and at the same time take the trace and sum over ell, computing everything needed for $q_b$ except $\\Sigma_b \\mathcal{F}_{b b^{\\prime}}$:\n```python\nqb_vec = np.einsum(\"iil,ijkl,jil->k\", gmat, mat, Dmat_obs) / 2.0\n```\nThe Fisher matrix is:\n```python\nfisher = np.einsum(\"iil,ijkl,jiml->km\", gmat, mat, dSdqb_mat1_freq) / 2\n```\n\nFinally, we get our updated estimate of $q_b$ and its covaraince, the inverse Fisher matrix, and then convert the former array into a readable dictionary:\n```python\nqb_vec = np.linalg.solve(fisher, qb_vec)\ninv_fish = np.linalg.solve(fisher, np.eye(len(qb_vec)))\nqb_vec = pt.arr_to_dict(qb_vec, qb)\n```\n\nWith each iteration, we compare the new `qb_vec` quantity to the previous one, until the maximum fractional change in any element of the array is less than the convergence criterion (0.005 is typical).\n\n#### Constructing final bandpowers\n\nTo construct bandpowers, we need to convert the $q_b$ parameters to spectrum bandpowers. The function that handles this is [do_qb2cb()](../api.rst#xfaster.xfaster_class.XFaster.do_qb2cb) This is done by first constructing window functions for each $q_b$ parameter (using [fisher_calc()](../api.rst#xfaster.xfaster_class.XFaster.fisher_calc) with the option `windows=True`), then using that to build a matrix that rotates $q_b$ into bandpowers.  For this example, the quantity we want in the end should be in units of $\\mathcal{D}_\\ell = \\ell (\\ell + 1) C_\\ell / 2\\pi$. You can also return bandpowers in units of $C_\\ell$ using `return_cls=True`, which will change the rotation matrix.  Explicitly, we have for the $\\mathcal{D}_b$ bandpowers:\n\n\\begin{equation}\n\\mathcal{D}^{XY}_b = \\sum_B q^{XY}_B \\frac{\\partial\\langle \\mathcal{D}^{XY}_b\\rangle}{\\partial q^{XY}_B} =\n\\sum_B q^{XY}_B \\frac{\\sum_\\ell \\mathcal{N}_\\ell W^{XY(q)}_{b\\ell} \\chi^{XY}_{B \\ell} \\mathcal{D}^{XY(S)}_\\ell} {\\sum_\\ell \\mathcal{N}_\\ell W^{XY(q)}_{b\\ell} }\\,,\n\\end{equation}\n\nwhere the normalization function is\n\n\\begin{equation}\n\\mathcal{N}_\\ell = \\frac{1}{2}\\frac{(2\\ell + 1)}{\\ell (\\ell + 1)}\\,,\n\\end{equation}\n\nand the matrix of derivatives is block-diagonal in the spectrum component $XY$. Similarly, the errors on each bandpower are:\n\n\\begin{equation}\n\\Delta\\mathcal{D}_b = \\left[\\sum_{BB^\\prime} \\mathcal{F}^{-1}_{BB^\\prime} \\frac{\\partial\\langle \\mathcal{D}_b\\rangle}{\\partial q_B} \\frac{\\partial\\langle \\mathcal{D}_{b}\\rangle}{\\partial q_{B^\\prime}}\\right]^{1/2}\\,,\n\\end{equation}\n\nand the window functions for each $\\mathcal{D}_b$ are:\n\n\\begin{equation}\nW_{b\\ell}^{XY(\\mathcal{D})} = \\sum_B W_{B\\ell}^{XY(q)} \\frac{\\partial\\langle \\mathcal{D}^{XY}_b\\rangle}{\\partial q^{XY}_B} \\,,\n\\end{equation}\n\nwith normalization $\\sum_\\ell \\mathcal{N}_\\ell W_{b\\ell}^{(\\mathcal{D})} = 1$.  The bandpowers, errors, $q_b$ window functions and bandpower window functions are all stored in the bandpowers output file.  More details on the bandpower window functions can be found in Section 2.5 of the [XFaster paper](https://arxiv.org/abs/2104.01172).\n\n#### Looking at results\n\nNow we'll just run the function that wraps up all these internal functions, [get_bandpowers()](../api.rst#xfaster.xfaster_class.XFaster.get_bandpowers).\n\n\n```python\nbp = X.get_bandpowers(converge_criteria=0.005, iter_max=200, save_iters=True, cond_noise=1e-5, cond_criteria=5e3)\n```\n\nIn the plot below, we'll plot up the maximum fractional change in $q_b$ with iteration. This information is printed in the logs, but it's helpful to visualize on a plot. You can see it bounce around early on before settling down and ultimately stopping once it gets to the desginated criterion.\n\n\n```python\nimport glob\niters = sorted(glob.glob('../../example/outputs_example/95x150/bandpowers_iter*'))\n### Figure for seeing how convergence looks in fqb\nfig_fqb, ax_fqb = plt.subplots()\nax_fqb.axhline(0.005, label='convergence criterion', color='C1')\nax_fqb.set_title('Max fractional change in qb vs iter')\nax_fqb.set_ylabel('Maximum absolute fqb')\nax_fqb.set_xlabel('Iteration')\nfqb = np.zeros(len(iters))\nfor i, bp0 in enumerate(iters):\n    b = xf.load_and_parse(bp0)\n    fqb[i] = np.max(np.abs(b['fqb']))\nax_fqb.plot(fqb, marker='o')\nax_fqb.legend()\nax_fqb.set_yscale('log')\n```\n\nNow let's see how the total model (summing up the $q_b\\mathcal{C}_{b\\ell}$ terms for every component) to see how it converges to fit the data. Within a few iterations, it's quite close.\n\n\n```python\n### Figure for looking at how sum(qbCbl) changes with iteration to match data\nfigtmp = plt.figure()\ntmpplot = plt.imshow(np.zeros((2,2)), cmap=plt.cm.get_cmap('viridis'),vmin=0, vmax=len(iters))\nplt.close(figtmp)\nfig_dat, ax_dat = plt.subplots(2,3, figsize=(15,10))\nax_dat = ax_dat.flatten()\nspecs = ['tt', 'ee', 'bb', 'te', 'tb', 'eb']\ncolors = plt.cm.get_cmap('viridis', len(iters)).colors\nfor s, spec in enumerate(specs):\n    ax_dat[s].set_title(spec)\nfor i, bp0 in enumerate(iters):\n    b = xf.load_and_parse(bp0)\n    for s, spec in enumerate(specs):\n        if i == 0:\n            # data cls don't change with iter- plot once.\n            ax_dat[s].plot(b['cls_obs'][spec]['150:95'] * lfac, color='gray', label='data')\n        ax_dat[s].plot(b['cls_model']['total_'+spec]['150:95'] * lfac, color=colors[i])\nfor i in [0, 3]:\n    ax_dat[i].set_ylabel(r'$D_\\ell$')\nfor i in range(3,5):\n    ax_dat[i].set_xlabel(r'$\\ell$')\nax_dat[0].legend()\nfig_dat.colorbar(tmpplot, label='Iteration', ax=ax_dat.ravel().tolist(), \n                 orientation='horizontal', shrink=0.5)\n\nfig_dat.suptitle(r'95$\\times$150 GHz total power fit')\n```\n\nNow let's look at just the $q_b$ values for each of the different component and see how they converge as a function of iteration and bin. The lowest bins tend to have the biggest moves, but for all components, everything gets close to its final value within a handful of iterations.\n\n\n```python\n### Figure for looking at how qb for each bandpower changes with iteration\nfigtmp = plt.figure()\ntmpplot = plt.imshow(np.zeros((2,2)), cmap=plt.cm.get_cmap('viridis'),vmin=0, vmax=len(iters))\nplt.close(figtmp)\nspecs = ['tt', 'ee', 'bb', 'te', 'tb', 'eb']\ncolors = plt.cm.get_cmap('viridis', len(iters)).colors\nscatter = 1. / 50.\nfor comp in ['cmb']:\n    fig_dat, ax_dat = plt.subplots(3,2, figsize=(20,15))\n    fig_dat.suptitle(comp+r' $q_b$ vs. iteration')\n    ax_dat = ax_dat.flatten()\n    for s, spec in enumerate(specs):\n        ax_dat[s].set_title(spec)\n        ax_dat[s].axhline(1, color='gray', alpha=0.7)\n    for i, bp0 in enumerate(iters):\n        b = xf.load_and_parse(bp0)\n        for s, spec in enumerate(specs):\n            ax_dat[s].scatter(np.arange(20) + scatter * i, \n                              b['qb'][comp+'_'+spec], color=colors[i], s=4)\n    for i in [0, 2, 4]:\n        ax_dat[i].set_ylabel(r'$q_b$')\n    for i in range(4,5):\n        ax_dat[i].set_xlabel('bin')\n\n    plt.subplots_adjust(wspace=0.05, hspace=0.01)\n    fig_dat.colorbar(tmpplot, label='Iteration', ax=ax_dat.ravel().tolist(), \n                     orientation='horizontal', shrink=0.5)\n\n```\n\nNow we'll look at the noise residuals that were fit. In the script where we make the example maps, we made the \"data\" maps have 15% less noise in them than the those used for the noise model. So, we should expect the total noise, $(1+n_b)\\left<N\\right>$, to be $0.85^2\\left<N\\right>$, where the square comes because we're fitting in the power spectrum. So, $n_b$s should converge to about -0.28. \n\n\n```python\n# Now plot residuals\nfig_dat, ax_dat = plt.subplots(1,2, figsize=(10,8))\nfig_dat.suptitle(r'res $q_b$ vs. iteration')\nax_dat = ax_dat.flatten()\nmaps = [x for x in bp['qb'] if 'res' in x]\nfor s, m0 in enumerate(maps):\n    ax_dat[s].set_title(m0)\n    ax_dat[s].axhline(0, color='gray', alpha=0.7)\n    ax_dat[s].set_ylim(-2,2)\nfor i, bp0 in enumerate(iters):\n    b = xf.load_and_parse(bp0)\n    for s, m0 in enumerate(maps):\n        ax_dat[s].scatter(np.arange(5) + scatter * i, \n                          b['qb'][m0], color=colors[i], s=4)\nfor i in [0]:\n    ax_dat[i].set_ylabel(r'$q_b$')\nfor i in range(2):\n    ax_dat[i].set_xlabel('bin')\n\nplt.subplots_adjust(wspace=0.05, hspace=0.01)\nfig_dat.colorbar(tmpplot, label='Iteration', ax=ax_dat.ravel().tolist(), \n                 orientation='horizontal', shrink=0.5)\n```\n\nNow that everything has converged, let's plot up what the final bandpowers and error bars look like. XFaster saves the binned bandpowers as $D_\\ell$s by default, though they are labeled `cb`. The error bars are in `dcb`, and those are also computed without sample variance in `dcb_nosampvar`. Covariance is in `cov`, and it also has a no sample variance version, `cov_nosampvar`.\n\nTo calculate error bars and covariances without sample variance, XFaster just does one final calculation of the Fisher matrix (after everything has converged), with all the $q_b$s set to a very small number, thereby nulling out the signal. The error bars and covariance without sample variance come from that Fisher matrix.\n\n\n```python\nfor comp in ['cmb']:\n    fig, ax = plt.subplots(3,2, figsize=(20,15))\n    ax = ax.flatten()\n    fig.suptitle('{} final estimated bandpowers'.format(comp))\n    for s, spec in enumerate(specs):\n        sn = '{}_{}'.format(comp, spec)\n        ax[s].set_title(spec)\n        ax[s].plot(lfac * signal_shape[sn][:501], 'k-', label='Model')     \n        ax[s].errorbar(bp['ellb'][sn], bp['cb'][sn], bp['dcb'][sn], label='sampvar') \n        ax[s].errorbar(bp['ellb'][sn]+2, bp['cb'][sn], bp['dcb_nosampvar'][sn], label='no sampvar')\n    ax[0].legend()\n    for i in [0, 2, 4]:\n        ax[i].set_ylabel(r'$D_\\ell$')\n    for i in [4,5]:\n        ax[i].set_xlabel(r'$\\ell$')\n```\n\nThe error bars are just the diagonal of the covariance matrix. Let's look at the covariance matrix with and without sample variance.\n\n\n```python\nfrom matplotlib.colors import LogNorm\nnorm = LogNorm(vmin=10, vmax=1e4)\nfig, ax = plt.subplots(1, 2, figsize=(15,10))\nfig.suptitle('Covariance')\np = ax[0].imshow(np.abs(bp['cov']), norm=norm)\nax[0].set_title('With sample variance')\nax[1].imshow(np.abs(bp['cov_nosampvar']), norm=norm)\nfig_dat.colorbar(p, label='Covariance', ax=ax.ravel().tolist(), \n                 orientation='horizontal', shrink=0.5)\nax[1].set_title('Without sample variance')\n```\n\nThis is a 120 x 120 bin matrix, with each of the 20 CMB bins for each spectrum in order (TT, EE, BB, TE, EB, TB).\n\n### get_likelihood\n\nNow we can compute parameter likelihoods with [get_likelihood()](../api.rst#xfaster.xfaster_class.XFaster.get_likelihood). All of the things we've constructed so far are used, except instead of parameterizing the model with $q_b$ bandpower deviations, we set those to 1, and then make the model a function of cosmological parameters. For the example, we will just use $r$ as our parameter. We then compute the likelihood for the data for each step in a Monte Carlo sampler, where we just vary $r$. For this example, since we're only varying one paramter, we'll do a brute force search: \n\n\n```python\nloglike = X.get_likelihood(qb=bp['qb'], inv_fish=bp['inv_fish'], mcmc=False)\n```\n\n\n```python\nplt.plot(loglike[0], np.exp(loglike[1]-loglike[1].max()))\nplt.ylabel('Likelihood')\nplt.xlabel(r'$r$')\n```\n\nWe can see that we recover something pretty close to 1, our input $r$ value for the example. If we ran this for many signal+noise sims, we should get precisely 1 in the average. \n\nIf you instead are using mcmc=True, the likelihoods file written to disk will have a field called \"samples\". Histogramming that up, or using a program like `getdist`, especially helpful for multiple parameters, will give you the posteriors for your various parameters.\n\nThe likelihoods function sets the CMB qb values to 1 and all others (esp., residuals) to their maximum likelihood values. To instead include these parameters in your fit, you set the `prior` arguments. So:\n\n* `r_prior`: set to [0, 'inf'] to inclue $r$ in the fit (or ['-inf', 'inf'] to impose no physical prior)\n* `alpha_prior`: same as `r_prior`-- set to None to not fit for alpha template scalings.\n* `res_prior`: same as previous-- will vary all $n_b$ parameters as part of the model\n* `beam_prior`: this is different! To account for beam uncertainty, set this to [0, 1], where the first parameter is the Gaussian mean, and the second is the number of standard deviations to use as the width. Here, you must have set the `beam_error_product` in your config file to a dictionary containing the one-sigma error on the beam shape per ell, and then that envelope is varied according to a Gaussian with each step to marginalize over the beam uncertainty.\n\nThat wraps up the example!\n", "meta": {"hexsha": "9d060099a7502e586460cd8fd762bb27dceffb3b", "size": 79620, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/notebooks/XFaster_Tutorial.ipynb", "max_stars_repo_name": "SPIDER-CMB/xfaster", "max_stars_repo_head_hexsha": "1b8e56d775f2c3a8693d1372ae461392c21da7ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/notebooks/XFaster_Tutorial.ipynb", "max_issues_repo_name": "SPIDER-CMB/xfaster", "max_issues_repo_head_hexsha": "1b8e56d775f2c3a8693d1372ae461392c21da7ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-09-06T11:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T01:52:20.000Z", "max_forks_repo_path": "docs/notebooks/XFaster_Tutorial.ipynb", "max_forks_repo_name": "SPIDER-CMB/xfaster", "max_forks_repo_head_hexsha": "1b8e56d775f2c3a8693d1372ae461392c21da7ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.2969046115, "max_line_length": 1035, "alphanum_fraction": 0.6221426777, "converted": true, "num_tokens": 16765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782348444346736, "lm_q2_score": 0.08509903746596331, "lm_q1q2_score": 0.03725835710613323}}
{"text": "Let's start here! If you can directly link to an image relevant to your notebook, such as [canonical logos](https://github.com/numpy/numpy/blob/main/doc/source/_static/numpylogo.svg), do so here at the top of your notebook. You can do this with Markdown syntax,\n\n> ``\n\nor edit this cell to see raw HTML `img` demonstration. This is preferred if you need to shrink your embedded image. **Either way be sure to include `alt` text for any embedded images to make your content more accessible.**\n\n</img>\n\n# Project Pythia Notebook Template\n\nNext, title your notebook appropriately with a top-level Markdown header, `#`. Do not use this level header anywhere else in the notebook. Our book build process will use this title in the navbar, table of contents, etc. Keep it short, keep it descriptive. Follow this with a `---` cell to visually distinguish the transition to the prerequisites section.\n\n---\n\n## Overview\nIf you have an introductory paragraph, lead with it here! Keep it short and tied to your material, then be sure to continue into the required list of topics below,\n\n1. This is a numbered list of the specific topics\n1. These should map approximately to your main sections of content\n1. Or each second-level, `##`, header in your notebook\n1. Keep the size and scope of your notebook in check\n1. And be sure to let the reader know up front the important concepts they'll be leaving with\n\n## Prerequisites\nThis section was inspired by [this template](https://github.com/alan-turing-institute/the-turing-way/blob/master/book/templates/chapter-template/chapter-landing-page.md) of the wonderful [The Turing Way](https://the-turing-way.netlify.app/welcome.html) Jupyter Book.\n\nFollowing your overview, tell your reader what concepts, packages, or other background information they'll **need** before learning your material. Tie this explicitly with links to other pages here in Foundations or to relevant external resources. Remove this body text, then populate the Markdown table, denoted in this cell with `|` vertical brackets, below, and fill out the information following. In this table, lay out prerequisite concepts by explicitly linking to other Foundations material or external resources, or describe generally helpful concepts.\n\nLabel the importance of each concept explicitly as **helpful/necessary**.\n\n| Concepts | Importance | Notes |\n| --- | --- | --- |\n| [Intro to Cartopy](../core/cartopy/cartopy) | Necessary | |\n| [Understanding of NetCDF](some-link-to-external-resource) | Helpful | Familiarity with metadata structure |\n| Project management | Helpful | |\n\n- **Time to learn**: estimate in minutes. For a rough idea, use 5 mins per subsection, 10 if longer; add these up for a total. Safer to round up and overestimate.\n- **System requirements**:\n    - Populate with any system, version, or non-Python software requirements if necessary\n    - Otherwise use the concepts table above and the Imports section below to describe required packages as necessary\n    - If no extra requirements, remove the **System requirements** point altogether\n\n---\n\n## Imports\nBegin your body of content with another `---` divider before continuing into this section, then remove this body text and populate the following code cell with all necessary Python imports **up-front**:\n\n\n```python\nimport sys\n```\n\n## Your first content section\n\nThis is where you begin your first section of material, loosely tied to your objectives stated up front. Tie together your notebook as a narrative, with interspersed Markdown text, images, and more as necessary,\n\n\n```python\n# as well as any and all of your code cells\nprint(\"Hello world!\")\n```\n\n### A content subsection\nDivide and conquer your objectives with Markdown subsections, which will populate the helpful navbar in Jupyter Lab and here on the Jupyter Book!\n\n\n```python\n# some subsection code\nnew = \"helpful information\"\n```\n\n### Another content subsection\nKeep up the good work! A note, *try to avoid using code comments as narrative*, and instead let them only exist as brief clarifications where necessary.\n\n## Your second content section\nHere we can move on to our second objective, and we can demonstrate\n\n### Subsection to the second section\n\n#### a quick demonstration\n\n##### of further and further\n\n###### header levels\n\nas well $m = a * t / h$ text! Similarly, you have access to other $\\LaTeX$ equation [**functionality**](https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Typesetting%20Equations.html) via MathJax (demo below from link),\n\n\\begin{align}\n\\dot{x} & = \\sigma(y-x) \\\\\n\\dot{y} & = \\rho x - y - xz \\\\\n\\dot{z} & = -\\beta z + xy\n\\end{align}\n\nCheck out [**any number of helpful Markdown resources**](https://www.markdownguide.org/basic-syntax/) for further customizing your notebooks and the [**Jupyter docs**](https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Working%20With%20Markdown%20Cells.html) for Jupyter-specific formatting information. Don't hesitate to ask questions if you have problems getting it to look *just right*.\n\n## Last Section\n\nIf you're comfortable, and as we briefly used for our embedded logo up top, you can embed raw html into Jupyter Markdown cells (edit to see):\n\n<div class=\"admonition alert alert-info\">\n    <p class=\"admonition-title\" style=\"font-weight:bold\">Info</p>\n    Your relevant information here!\n</div>\n\nFeel free to copy this around and edit or play around with yourself. Some other `admonitions` you can put in:\n\n<div class=\"admonition alert alert-success\">\n    <p class=\"admonition-title\" style=\"font-weight:bold\">Success</p>\n    We got this done after all!\n</div>\n\n<div class=\"admonition alert alert-warning\">\n    <p class=\"admonition-title\" style=\"font-weight:bold\">Warning</p>\n    Be careful!\n</div>\n\n<div class=\"admonition alert alert-danger\">\n    <p class=\"admonition-title\" style=\"font-weight:bold\">Danger</p>\n    Scary stuff be here.\n</div>\n\nWe also suggest checking out Jupyter Book's [brief demonstration](https://jupyterbook.org/content/metadata.html#jupyter-cell-tags) on adding cell tags to your cells in Jupyter Notebook, Lab, or manually. Using these cell tags can allow you to [customize](https://jupyterbook.org/interactive/hiding.html) how your code content is displayed and even [demonstrate errors](https://jupyterbook.org/content/execute.html#dealing-with-code-that-raises-errors) without altogether crashing our loyal army of machines!\n\n---\n\n## Summary\nAdd one final `---` marking the end of your body of content, and then conclude with a brief single paragraph summarizing at a high level the key pieces that were learned and how they tied to your objectives. Look to reiterate what the most important takeaways were.\n\n### What's next?\nLet Jupyter book tie this to the next (sequential) piece of content that people could move on to down below and in the sidebar. However, if this page uniquely enables your reader to tackle other nonsequential concepts throughout this book, or even external content, link to it here!\n\n## Resources and references\nFinally, be rigorous in your citations and references as necessary. Give credit where credit is due. Also, feel free to link to relevant external material, further reading, documentation, etc. Then you're done! Give yourself a quick review, a high five, and send us a Pull Request. A few final notes:\n - `Kernel > Restart Kernel and Run All Cells...` to confirm that your notebook will cleanly run from start to finish\n - `Kernel > Restart Kernel and Clear All Outputs...` before committing your notebook, our machines will do the heavy lifting\n - Take credit! Provide author contact information if you'd like; if so, consider adding information here at the bottom of your notebook\n - Give credit! Attribute appropriate authorship for referenced code, information, images, etc.\n - Only include what you're legally allowed: **no copyright infringement or plagiarism**\n \nThank you for your contribution!\n", "meta": {"hexsha": "446498c0d24062031bc4c25828c9861e6cfe6778", "size": 12492, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "appendix/template.ipynb", "max_stars_repo_name": "cjcardinale/pythia-foundations", "max_stars_repo_head_hexsha": "a343f94835c63ab42abde97fe8f3e085e5b9cf49", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "appendix/template.ipynb", "max_issues_repo_name": "cjcardinale/pythia-foundations", "max_issues_repo_head_hexsha": "a343f94835c63ab42abde97fe8f3e085e5b9cf49", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "appendix/template.ipynb", "max_forks_repo_name": "cjcardinale/pythia-foundations", "max_forks_repo_head_hexsha": "a343f94835c63ab42abde97fe8f3e085e5b9cf49", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7966573816, "max_line_length": 569, "alphanum_fraction": 0.6131924432, "converted": true, "num_tokens": 1756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.21206879937726766, "lm_q2_score": 0.17553807577999186, "lm_q1q2_score": 0.0372261489756587}}
{"text": "**Todo**\n---\n> 1. Make all the Conv Layers functions <-- did this\n> 2. 2x2 inputs and 4x4 inputs <-- is finished ^\n> 3. Adam Optimizer <-- not important right now\n> 4. 1.6 in tutorial <-- is finished\n> 5. 1.7 in tutorial <-- Saturday\n\n**Installation of Necessary Modules**\n1.   Tensorflow==2.4.1\n2.   Tensorflow-Quantum\n3.   Sympy\n4.   Numpy\n5.   Google Cirq\n6.   Pennylane (Just in Case)\n\n\n\n\n```python\n!pip install -q tensorflow==2.4.1 tensorflow-quantum\n!pip install cirq sympy numpy pennylane\n```\n\n**Importing Modules**\n\n\n1.   Matplotlib.pyplot as plt\n2.   SVGCircuit from Cirq.contrib.svg\n3.   Tensorflow as tf and Tensorflow_Quantum as tfq\n4.   Google Cirq for writing the circuit\n5.   Sympy as sp\n6.   Numpy as np from Pennylane\n7.   Pennylane as qml\n8.   Itertools for efficient iteration\n9.   Math for doing math\n\n\n\n\n```python\n#%tb #full traceback for errors\n%matplotlib inline\nimport tensorflow as tf\nimport tensorflow_quantum as tfq\nimport matplotlib.pyplot as plt\nimport cirq\nfrom cirq.contrib.svg import SVGCircuit\nimport sympy as sp\nimport pennylane\nfrom pennylane import numpy as np\nfrom math import *\nfrom itertools import *\n```\n\n**Abhik's Section**\n\n\n```python\n#Can put code here\n```\n\n**Function which Creates the Circuit and Qubits**\n\n\n```python\nnumOfQubits = 4\n```\n\n\n```python\ndef createCircuit(num_qubits):\n    qubits = cirq.GridQubit.rect(1, num_qubits)\n    circuit = cirq.Circuit()\n    return qubits, circuit\n```\n\n\n```python\nqubits, vqc = createCircuit(numOfQubits)\n```\n\n*If you mess up run the \"I messed up function\"*\n\n\n\n```python\n#I messed up function\n#qubits, vqc = createCircuit(4)\n```\n\n**Cluster State PQC**\n1. Hadamard all Qubit\n2. CNOT each pair of qubits (0,1), (1,2) (2,3), (3,0)\n\n\n```python\ndef Cluster_State_PQC(bits):\n    circuit = cirq.Circuit()\n    circuit.append(cirq.H.on_each(bits))\n    for this_bit, next_bit in zip(bits, bits[1:] + [bits[0]]):\n        circuit.append(cirq.CZ(this_bit, next_bit))\n    return circuit\n```\n\n**Rotation Angle Initialization before perfoming Convolution and Pooling and Gate Functions**\n\n\n```python\ndef InitRot(numOfAngles=74, angle = np.pi/2):\n    return np.array([angle for i in range(numOfAngles)])\n```\n\n\n```python\ndefault = InitRot()\nprint(default)\n```\n\n    [1.57079633 1.57079633 1.57079633 1.57079633 1.57079633 1.57079633\n     1.57079633 1.57079633 1.57079633 1.57079633 1.57079633 1.57079633\n     1.57079633 1.57079633 1.57079633 1.57079633 1.57079633 1.57079633\n     1.57079633 1.57079633 1.57079633 1.57079633 1.57079633 1.57079633\n     1.57079633 1.57079633 1.57079633 1.57079633 1.57079633 1.57079633\n     1.57079633 1.57079633 1.57079633 1.57079633 1.57079633 1.57079633\n     1.57079633 1.57079633 1.57079633 1.57079633 1.57079633 1.57079633\n     1.57079633 1.57079633 1.57079633 1.57079633 1.57079633 1.57079633\n     1.57079633 1.57079633 1.57079633 1.57079633 1.57079633 1.57079633\n     1.57079633 1.57079633 1.57079633 1.57079633 1.57079633 1.57079633\n     1.57079633 1.57079633 1.57079633 1.57079633 1.57079633 1.57079633\n     1.57079633 1.57079633 1.57079633 1.57079633 1.57079633 1.57079633\n     1.57079633 1.57079633]\n\n\n*Rotation angles subject to changes at any time*\n\n\n```python\ndef U3_Gate(bit, params):\n    return cirq.Circuit(\n        cirq.X(bit)**params[0],\n        cirq.Y(bit)**params[1],\n        cirq.Z(bit)**params[2])\n```\n\n\n```python\ndef CU_Gate(other_bit, bit, params):\n    return cirq.Circuit(\n        cirq.X(bit).controlled_by(other_bit)**params[0],\n        cirq.Y(bit).controlled_by(other_bit)**params[1],\n        cirq.Z(bit).controlled_by(other_bit)**params[2])\n```\n\n**Quantum Convolution Layer 1**.  \n*Consists of RY gates with fixed angle of rotation (non-trainable) and CNOT pattern as in the PQC* \n\n\n```python\ndef QConvLayer1(qubits): \n    circuit = cirq.Circuit()\n    for first in qubits:\n        circuit.append(cirq.Ry(rads=np.pi)(first))\n    for first, second in zip(qubits[0::1], qubits[1::1] + [qubits[0]]):\n        circuit.append(cirq.CNOT(first, second))\n    return circuit\n```\n\n**Quantum Convolution Layer 2**  \n*Consists of U3 gates applied to each qubit and CU gates applied in the CNOT pattern*\n\n\n```python\ndef QConvLayer2(qubits, params):\n    circuit = cirq.Circuit()\n    index = 0\n    for qubit in qubits:\n        circuit += U3_Gate(qubit, params[index : index+3])\n        index += 3\n    for first, second in zip(qubits[0::1], qubits[1::1] + [qubits[0]]):\n        circuit += CU_Gate(first, second, params[index : index+3])\n        index += 3\n    return circuit\n```\n\n**Quantum Convolution Layer 3**\n\n\n```python\ndef QConvLayer3(qubits, params):\n    circuit = cirq.Circuit()\n    index=0\n    for qubit in qubits:\n        circuit += U3_Gate(qubit, params[index : index+3])\n        index += 3\n    circuit += cirq.CNOT(control=qubits[0], target=qubits[1])\n    circuit += (cirq.CNOT(control=qubits[3], target=qubits[2]))\n    circuit += U3_Gate(qubits[0], [np.pi, np.pi, np.pi])\n    circuit += U3_Gate(qubits[3], [np.pi/2, np.pi/2, np.pi/2])\n    circuit += cirq.CNOT(control=qubits[0], target=qubits[1])\n    circuit += cirq.CNOT(control=qubits[3], target=qubits[2])\n    return circuit\n```\n\n**Quantum Convolution Layer 4**\n\n\n```python\ndef QConvLayer4(qubits, params):\n    circuit = cirq.Circuit()\n    index = 0\n    circuit += U3_Gate(qubits[0], params[0:3])\n    for first, second in zip(qubits[0::1], qubits[1::1] + [qubits[0]]):\n        circuit += cirq.CNOT(control=first, target=second)\n        circuit += CU_Gate(first, second, params[index:index+3])\n        index += 3\n    return circuit\n```\n\n**Quantum Convolution Layer 5**\n\n\n```python\ndef QConvLayer5(qubits, params):\n    circuit = cirq.Circuit()\n    circuit += U3_Gate(qubits[0], params[0:3])\n    circuit += cirq.CNOT(control=qubits[0], target=qubits[1])\n    circuit += cirq.CNOT(control=qubits[2], target=qubits[3])\n    circuit += U3_Gate(qubits[2], params[3:6])\n    circuit += cirq.CNOT(control = qubits[2], target=qubits[1])\n    circuit += U3_Gate(qubits[1], params[6:9])\n    return circuit\n```\n\n**Quantum Convolution Layer 6**  \n*Same as Layer 4 but CU is CNOT*\n\n\n```python\ndef QConvLayer6(qubits):\n    circuit = cirq.Circuit()\n    for i in range(1, len(qubits)):\n        circuit += cirq.CNOT(qubits[0], qubits[i])\n    circuit += U3_Gate(qubits[3], [np.pi, np.pi/2, np.pi/4])\n    return circuit\n```\n\n**Quantum Pooling Layer**  \n\n\n```python\ndef QPoolLayer(source, sink, params):\n    poolCircuit = cirq.Circuit()\n    sinkBasisSelector = U3_Gate(sink, params[0:3])\n    sourceBasisSelector = U3_Gate(source, params[3:6])\n    poolCircuit.append(sinkBasisSelector)\n    poolCircuit.append(sourceBasisSelector)\n    poolCircuit.append(cirq.CNOT(control=source, target=sink))\n    poolCircuit.append(sinkBasisSelector**-1)\n    return poolCircuit\n```\n\n**1.6 Create Model**\n\n\n```python\ndef createModelCircuit(qubits, symbols=sp.symbols('param0:74')):\n    modelCircuit = cirq.Circuit()\n    modelCircuit += QConvLayer1(qubits)\n    modelCircuit += QConvLayer2(qubits, symbols[0:24])\n    modelCircuit += QConvLayer3(qubits, symbols[24:36])\n    modelCircuit += QPoolLayer(qubits[0], qubits[2], symbols[36:42])\n    modelCircuit += QConvLayer4(qubits, symbols[42:57])\n    modelCircuit += QConvLayer5(qubits, symbols[57:67])\n    modelCircuit += QPoolLayer(qubits[1], qubits[3], symbols[67:74])\n    modelCircuit += QConvLayer6(qubits)\n    return modelCircuit\n```\n\n\n```python\nclusterStateBits = cirq.GridQubit.rect(1, 4)\nreadoutOps = cirq.Z(clusterStateBits[-1])\nexcitationInput = tf.keras.Input(shape=(), dtype=tf.dtypes.string)\nclusterState = tfq.layers.AddCircuit()(excitationInput, prepend=Cluster_State_PQC(clusterStateBits))\nQModel = tfq.layers.PQC(createModelCircuit(clusterStateBits), readoutOps)(clusterState)\nQCNNModel = tf.keras.Model(inputs=[excitationInput], outputs=[QModel])\ntf.keras.utils.plot_model(QCNNModel, show_shapes=True, show_layer_names=True, dpi=70)\n```\n", "meta": {"hexsha": "404bf3f23e63fc10198ed9004f27a302b88297e1", "size": 31800, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "QCNN./TFQ_QCNN.ipynb", "max_stars_repo_name": "PNGNS-Marekos1111/CoolStuff", "max_stars_repo_head_hexsha": "77413554430d39d77767b9c0dc830fce9cef5206", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-01T17:55:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-08T23:57:36.000Z", "max_issues_repo_path": "QCNN./TFQ_QCNN.ipynb", "max_issues_repo_name": "PNGNS-Marekos1111/CoolStuff", "max_issues_repo_head_hexsha": "77413554430d39d77767b9c0dc830fce9cef5206", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QCNN./TFQ_QCNN.ipynb", "max_forks_repo_name": "PNGNS-Marekos1111/CoolStuff", "max_forks_repo_head_hexsha": "77413554430d39d77767b9c0dc830fce9cef5206", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-04T02:59:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-04T02:59:03.000Z", "avg_line_length": 54.8275862069, "max_line_length": 15178, "alphanum_fraction": 0.7106289308, "converted": true, "num_tokens": 2585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.08269734380541847, "lm_q1q2_score": 0.037163577195954985}}
{"text": "```javascript\n%%javascript\n$('#appmode-leave').hide();\n$('#copy-binder-link').hide();\n$('#visit-repo-link').hide();\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n# Bomb Calorimetry\n\n### Video credit: Chris Ambidge - University of Toronto.\n\n\n```python\n# from IPython.display import YouTubeVideo\n# # Video credit: Chris Ambidge - University of Toronto.\n# YouTubeVideo('bm3Tn6DXJrI')\n```\n\n\n## Introduction to the experiment\n\n**Calorimetry** derives from the Latin word _calor_ meaning heat, and the Greek _metry_ meaning to measure. Thus, it is the science of measuring amounts of heat. \nAll calorimetric techniques are based on the measurement of heat generated or consumed by a sample, depending on whether exothermic or endothermic processes are involved.\nA calorimeter can be a simple Styrofoam cup, because it is a container with insulated walls that prevents heat exchange with the environment, or more a complicated device such as a bomb calorimeter \n\n \n<p style=\"text-align: center;\"> Figure 1: Schematic representation of a bomb calorimeter (Image taken taken from chem.libretexts.org) </p>\n\nIn the simplest version of this experiment, in order to measure heats of reactions, we enclose the reactants in a calorimeter, allow the reaction to proceed, and measure the temperature change ($\\Delta$T). Then the heat released or adsorbed in the reaction can be calculated.\nA calorimeter may be used under constant pressure (atmospheric), or constant volume.\nRegardless of the setup, the calorimeter adsorbs some of the released heat and its heat capacity must be measured to calibrate the instrument, which is usually done just before or after the actual measurement of the heats of reaction. \nThis is done by transferring a known amount of heat into the calorimeter and measuring its temperature increase. \nBecause the temperature differences are often very small, sensitive thermometers are preferred for these measurements.\n\n## Theory\nConventionally, in thermodynamics we use two fundamental definitions: the system and the surroundings. \nThe system is what is being measured, observed and investigated while the surroundings are everything else.\nAn isolated system is referred to as adiabatic, which means that there is no exchange of matter or energy between the system and its surroundings. \nThe energy considerations of a reaction include heat (denoted $q$), which is the energy absorbed by the system, and the work done on the system (denoted $w$).\nAs heat is transferred into or out of a system this leads to a change in temperature, and the quantity of energy that causes a temperature change is determined with this equation\n\n\\begin{equation}\nq = \\sum c(T_f-T_i) \\tag{1}\n\\end{equation}\n\nWhere $q$ is the heat of the process, $\\sum c$ is sum of the heat capacities of all the various components of the system, $T_f$ is the final temperature and $T_i$ is the initial temperature. Because it is difficult, if not impossible to separate the different contributions, in the following we will just use an _effective_ heat capacity of the calorimeter, $C_V = \\sum c$. \nRecalling the physical chemistry lectures, the heat capacity is the amount of heat required to raise the temperature of a substance (or of the entire calorimeter) by 1 K.\n\n### Obtaining an Isothermal Enthalpy\nThe enthalpy of any process is the heat absorbed by the system at constant pressure.\nThe enthalpy of a reaction under isothermal conditions can be determined by conducting the experiment adiabatically, and then measuring the temperature change that occurs in the reaction vessel.\nThe isothermal reaction at temperature $T_i$ can be expressed as follows:\n\n\\begin{equation}\n\\mathrm{A(T_i)} + \\mathrm{B(T_i)} \\xrightarrow{\\Delta H_c} \\mathrm{C(T_i)} + \\mathrm{D(T_i)} \\tag{2}\n\\end{equation}\n\nWhere $\\Delta H$ is the enthalpy of the isothermal reaction for each mole of reaction as written.\nIn a calorimeter the system is insulated, and therefore no energy is lost to the surroundings.\nThis is known as an adiabatic system and therefore in the calorimeter the energy of the\nreaction is used to heat the system with no loss.\nThe adiabatic reaction can be expressed as follows:\n\n\\begin{equation}\n\\mathrm{A(T_i)} + \\mathrm{B(T_i)} + \\mathrm{S(T_i)}\\xrightarrow{\\Delta H_I} \\mathrm{C(T_f)} + \\mathrm{D(T_f)} + \\mathrm{S(T_f)} \\tag{3}\n\\end{equation}\n\nWhere $\\Delta H_I$ is the enthalpy of the adiabatic reaction. \nA, B, C and D continue to be the reactants and products respectively and S is the parts of the system (thermometer, solvent, reaction vessel walls etc.) that maintain the same temperature as the reactants and products because of the insulated system.\nEnthalpy however is a state function, and therefore independent of the steps taken to get to the final stage. Thus, the enthalpy of the isothermal reaction will be the sum of the enthalpy of any steps that start and finish in the same state.\nTherefore in order to finish the adiabatic reaction under the same conditions as the isothermal reaction, the system merely needs to be cooled to the initial temperature.\n\n\\begin{equation}\n\\mathrm{A(T_f)} + \\mathrm{B(T_f)} + \\mathrm{S(T_f)}\\xrightarrow{\\Delta H_{II}} \\mathrm{C(T_i)} + \\mathrm{D(T_i)} + \\mathrm{S(T_i)} \\tag{4}\n\\end{equation}\n\n$\\Delta H_{I}$ and $\\Delta H_{II}$ are the enthalpies of the alternate steps taken to go from the initial stage to the final stage of the isothermal reaction, and therefore, as shown in the figure below, the enthalpy of the isothermal reaction is the sum of these two values.\n\n\\begin{equation}\n\\Delta H_c = \\Delta H_{I} + \\Delta H_{II} \\tag{5}\n\\end{equation}\n\nAs stated previously an adiabatic reaction is a reaction contained in an isolated system, i.e. no energy (heat) is transferred out of the system. \nThis means that for the first step in Figure 2, $\\mathrm{d}q$=0 and $\\Delta H=0$ adiabatic step is 0, and therefore $\\Delta H_{I}$ is also 0. \nThe cooling step indicated in Figure 1 need not be performed, but rather the heat of Step II can be calculated as\n\n\\begin{equation}\n\\Delta H_{II} = C_V (T_f - T_i ) \\tag{6}\n\\end{equation}\n\n\n<p style=\"text-align: center;\"> Figure 2. Schematic representation of the working principles of the calorimeter and key equations.</p>\n\n### Reaction Enthalpy Under Standard Conditions\nJust as the isothermal enthalpy can be calculated from results that take a different series of steps, the enthalpy of a reaction under standard conditions can be determined from any isothermal energy of that reaction.\nAn alternative series of steps for the standard reaction to occur is: i) changing the system temperature from standard conditions to the experimental temperature, ii) proceeding with the reaction, iii) changing the temperature back to standard temperature.\nAs these three steps start with the reactants under standard conditions and finish with the products under standard conditions the sum of the enthalpies of these steps is equivalent to the enthalpy of the reaction proceeding under standard conditions. This is presented as\n\n\n<p style=\"text-align: center;\"> Figure 3 </p>\n\n## Bomb calorimetry, the experiment\nIn this *virtual* experiment you will calibrate the calorimeter using benzoic acid and determine the enthalpy of combustion of sucrose and napthalene.\n\nAn adiabatic bomb calorimeter provides a constant volume environment for the measurement of the heat of combustion of compounds. \nThis corresponds to the first step in Figure 2.\n\nAs mentioned before, and important step in any calorimetry experiment is to calibrate the instrument, in order to achieve that you will perform a first experiment with benzoic acid, for which you are given its enthalpy of combustion ($\\Delta H_c=-3228\\ \\mathrm{kJ/mol}$).\n \nThis reaction proceeds as follows within the calorimeter:\n\n\\begin{equation}\n\\mathrm{C_6H_5COOH} + \\frac{15}{2}\\mathrm{O_2(excess)} \\xrightarrow{20\\ atm} \\mathrm{7CO_2(g)} + \\mathrm{3H_2O(l)} \\tag{8}\n\\end{equation}\n\nThe process is carried out under 20 atm of excess oxygen in order to ensure complete and rapid combustion. \n\nThese conditions are not exactly standard temperature nor pressure, and therefore the energy change measured is not the standard heat of reaction. \nCorrections would need to be made to convert to standard conditions, however the experimental uncertainty in this lab accounts for the errors introduced by the non-standard conditions.\nThe change in internal energy of the system is defined in the following fashion:\n\n\\begin{equation}\n\\Delta U = dq - P\\Delta V \\tag{9}\n\\end{equation}\n\nHowever, because the experiment is performed a constant volume this becomes\n\n\\begin{equation}\n\\Delta U = dq_V \\tag{10}\n\\end{equation}\n\nTherefore, by using the calorimeter to measure the change in temperature you can measure the change in internal energy of the system\n\n\\begin{equation}\n\\Delta U = dq_V = C_V(T_f-T_i) \\tag{11}\n\\end{equation}\n\nWhere $C_V$ is the heat capacity of the entire system at constant volume.\nUsing the definition of enthalpy\n\n\\begin{equation}\nH = U + PV \\tag{12}\n\\end{equation}\n\nwe can then write the combustion enthalpy change for a reaction as\n\n\\begin{equation}\n\\Delta H_c = \\Delta U + \\Delta (PV) = \\Delta U + V\\Delta P + P\\Delta V \\tag{13}\n\\end{equation}\n\nAt constant volume, because $P\\Delta V=0$, this becomes\n\n\\begin{equation}\n\\Delta H_c = \\Delta U + \\Delta (nRT) \\tag{14}\n\\end{equation}\n\nwhere we have assumed that the gas is ideal and $V\\Delta P=\\Delta (nRT)$.\nWhere $P$ is the pressure in kPa, $V$ is the volume in litres, $\\Delta n$ is the change in the number of moles of gas particles during the reaction, $R$ is the universal gas constant and $T$ is the isothermal temperature.\n\nThe enthalpy of the combustion reaction in the bomb calorimeter can then be calculated using change of internal energy ($\\Delta U=C_v\\Delta T$) and from the gas stoichiometry of the equation.\n\nThe enthalpy of combustion can also be determined from the formation enthapies of reactants and products\n\n\\begin{equation}\n\\Delta H_c = \\sum \\Delta H_f^{products} - \\sum \\Delta H_f^{reactants} \\tag{15} \n\\end{equation}\n\n### Experimental Factors\nNo experimental configuration is truly adiabatic, and in this case the stirrer adds energy to the system while the thermometer and non-ideal insulation allows heat to escape from the system. These factors produce fairly linear changes in temperature before and after the reaction occurs. In order to accurately account for these effects, the temperature must be measured for a period of time before the reactants are combined and for a period of time after the reaction has proceeded. Plotting this data and recording the relative time the reactants were combined allows the change in temperature to be more accurately determined as shown in the figure below.\n\n\n<p style=\"text-align: center;\"> Figure 4 </p>\n\n<!-- #### Real experiment procedure \n1. Listen to the laboratory technician. The operation of the calorimeter and the powder press will be explained.\n2. \tProduce a compressed tablet of benzoic acid, using the powder-press as directed.\n3. \tAccurately weigh the tablet. Place it in the bomb cup.\n4. \tMeasure out exactly 10 cm of ignition wire, cut to length. Wind each end of the piece of wire around the ignition poles. Secure the wire as demonstrated. Record the energy of combustion of the wire.\n5. \tBend the centre of the ignition wire into the form of an inverted omega ($\\Omega$). Ensure the wire presses on the benzoic acid tablet.\n6. \tSet the ignition cup in the bomb. Seal the bomb, taking care to avoid cross-threading the bomb lid.\n7. \tConnect the bomb inlet to the oxygen cylinder. Fill the bomb with 20 atmospheres of oxygen from the cylinder. Ensure the gas inlet is connected to the proper valve.\n8.\tPlace 2.00 L of water in the calorimeter pail. The calorimeter contains an accurate water dispenser; its operation will be demonstrated.\n9. \tPlace the pail in the body of the calorimeter. Use the tongs provided to position the bomb in the pail. Ensure it is correctly seated on the plateau.\n10. \tConnect the spark leads to the bomb.\n11.\t Close the calorimeter body. Fire the bomb.\n12. \tRecord the change in temperature of the bomb.\n13. \tMake a compressed tablet of sucrose, using the powder-press.\n14. \tAccurately weigh the tablet.\n15.\tPrepare the calorimeter as before. Fire the sucrose tablet.\n16. \tRecord the change in temperature of the bomb.\n17. \tMake a compressed tablet of naphthalene.\n18.\tPrepare the calorimeter as before. Fire the naphthalene tablet.\n19. \tRecord the change in temperature of the bomb.\n20. \tRepeat for each substance. If time permits, a third repetition for each substance is advisable. -->\n\n### Virtual experiment procedure\nIn this virtual lab instead you will have to\n1. Choose your sample (Benzoic acid)\n2. Create a tablet for you sample \n3. \"Perform\" the experiment (obtain temperature inside the bomb calorimeter vs time)\n4. Fit the temperature profile before and after the experiment to obtain the temperature change\n5. Determine the calorimeter heat capacity of the bomb calorimeter to calibrate the instrument\n6. Repeat 1 to 5 to obtain an average value for the heat capacity of the bomb calorimeter\n7. Repeat 1 to 4 for sucrose and naphtalene\n8. Determine the combustion enthalpy and formation enthalpy of Sucrose and Napthalene\n\n#### Assume the wire described in the video releases a negligible amount of heat\n\n## Numerical skills \n\n1. fitting of portions of data\n2. error analysis\n\n## Pre-lab\n\n1. Obtain from literature the standard enthalpies of formation of $O_2$, $H_2O$, $CO_2$, sucrose and naphtalene.\n2. Write the balances combustion reactions for benzoic acid, sucrose and naphtalene\n3. Calculate the expected combustion enthalpy of sucrose and naphtalene\n\n## Post-lab\n3. Use the given combustion enthalpy of benzoic acid to \"calibrate the instrument\"; what is the heat capacity of the bomb calorimeter?\n\n4. Calculate the combustion and formation enthalpies ($\\Delta H_c$ \\& $\\Delta H_f$) of sucrose and naphtalene. Compare with the literature values obtained in the pre lab.\n\n\n\n## Launch virtual experiment\n- [Bomb Calorimetry virtual lab](virtualExperiment.ipynb)\n", "meta": {"hexsha": "a48e4a82c4d8a0898fc21c96a12023c8204d95aa", "size": 18736, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "week_03_bombCalorimetry/bombCalorimetry.ipynb", "max_stars_repo_name": "praiteri/TeachingNotebook", "max_stars_repo_head_hexsha": "75ee8baf8ef81154dffcac556d4739bf73eba712", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "week_03_bombCalorimetry/bombCalorimetry.ipynb", "max_issues_repo_name": "praiteri/TeachingNotebook", "max_issues_repo_head_hexsha": "75ee8baf8ef81154dffcac556d4739bf73eba712", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week_03_bombCalorimetry/bombCalorimetry.ipynb", "max_forks_repo_name": "praiteri/TeachingNotebook", "max_forks_repo_head_hexsha": "75ee8baf8ef81154dffcac556d4739bf73eba712", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-23T11:36:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T11:36:12.000Z", "avg_line_length": 50.3655913978, "max_line_length": 665, "alphanum_fraction": 0.6643360376, "converted": true, "num_tokens": 3413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16451645060750467, "lm_q2_score": 0.2254166158350767, "lm_q1q2_score": 0.03708474154514225}}
{"text": "<a href=\"https://colab.research.google.com/github/Kabongosalomon/AMMI-NLP/blob/master/Part%2002/001_LM/ngram_lm_lab/ngram_lms.ipynb\" target=\"_parent\"></a>\n\n# N-Gram Language Models\n\n<font color='red'>Uncomment the code below if you're on Colab</font>\n\n\n## run code in this section if you're on colab\n\n\n```python\n# !git clone https://github.com/Kabongosalomon/AMMI-NLP.git\n\n# %cd AMMI-NLP/Part\\ 02/001_LM/ngram_lm_lab  \n\n# !sudo apt-get install build-essential libboost-all-dev cmake zlib1g-dev libbz2-dev liblzma-dev\n\n# !wget -O - https://kheafield.com/code/kenlm.tar.gz |tar xz\n# !mkdir kenlm/build\n# %cd kenlm/build\n# !cmake ..\n# !make -j 4\n\n# %cd ..\n\n# ! python setup.py install\n\n# %cd ..\n```\n\n    /content/AMMI-NLP/Part 02/001_LM/ngram_lm_lab\n    Reading package lists... Done\n    Building dependency tree       \n    Reading state information... Done\n    build-essential is already the newest version (12.4ubuntu1).\n    liblzma-dev is already the newest version (5.2.2-1.3).\n    liblzma-dev set to manually installed.\n    zlib1g-dev is already the newest version (1:1.2.11.dfsg-0ubuntu2).\n    zlib1g-dev set to manually installed.\n    libboost-all-dev is already the newest version (1.65.1.0ubuntu1).\n    cmake is already the newest version (3.10.2-1ubuntu2.18.04.1).\n    libbz2-dev is already the newest version (1.0.6-8.1ubuntu0.2).\n    libbz2-dev set to manually installed.\n    0 upgraded, 0 newly installed, 0 to remove and 25 not upgraded.\n    --2020-03-21 00:54:59--  https://kheafield.com/code/kenlm.tar.gz\n    Resolving kheafield.com (kheafield.com)... 35.196.63.85\n    Connecting to kheafield.com (kheafield.com)|35.196.63.85|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 490005 (479K) [application/x-gzip]\n    Saving to: \u2018STDOUT\u2019\n    \n    -                   100%[===================>] 478.52K  1007KB/s    in 0.5s    \n    \n    2020-03-21 00:54:59 (1007 KB/s) - written to stdout [490005/490005]\n    \n    /content/AMMI-NLP/Part 02/001_LM/ngram_lm_lab/kenlm/build\n    -- The C compiler identification is GNU 7.5.0\n    -- The CXX compiler identification is GNU 7.5.0\n    -- Check for working C compiler: /usr/bin/cc\n    -- Check for working C compiler: /usr/bin/cc -- works\n    -- Detecting C compiler ABI info\n    -- Detecting C compiler ABI info - done\n    -- Detecting C compile features\n    -- Detecting C compile features - done\n    -- Check for working CXX compiler: /usr/bin/c++\n    -- Check for working CXX compiler: /usr/bin/c++ -- works\n    -- Detecting CXX compiler ABI info\n    -- Detecting CXX compiler ABI info - done\n    -- Detecting CXX compile features\n    -- Detecting CXX compile features - done\n    -- Looking for pthread.h\n    -- Looking for pthread.h - found\n    -- Looking for pthread_create\n    -- Looking for pthread_create - not found\n    -- Looking for pthread_create in pthreads\n    -- Looking for pthread_create in pthreads - not found\n    -- Looking for pthread_create in pthread\n    -- Looking for pthread_create in pthread - found\n    -- Found Threads: TRUE  \n    -- Boost version: 1.65.1\n    -- Found the following Boost libraries:\n    --   program_options\n    --   system\n    --   thread\n    --   unit_test_framework\n    --   chrono\n    --   date_time\n    --   atomic\n    -- Found ZLIB: /usr/lib/x86_64-linux-gnu/libz.so (found version \"1.2.11\") \n    -- Found BZip2: /usr/lib/x86_64-linux-gnu/libbz2.so (found version \"1.0.6\") \n    -- Looking for BZ2_bzCompressInit\n    -- Looking for BZ2_bzCompressInit - found\n    -- Looking for lzma_auto_decoder in /usr/lib/x86_64-linux-gnu/liblzma.so\n    -- Looking for lzma_auto_decoder in /usr/lib/x86_64-linux-gnu/liblzma.so - found\n    -- Looking for lzma_easy_encoder in /usr/lib/x86_64-linux-gnu/liblzma.so\n    -- Looking for lzma_easy_encoder in /usr/lib/x86_64-linux-gnu/liblzma.so - found\n    -- Looking for lzma_lzma_preset in /usr/lib/x86_64-linux-gnu/liblzma.so\n    -- Looking for lzma_lzma_preset in /usr/lib/x86_64-linux-gnu/liblzma.so - found\n    -- Found LibLZMA: /usr/include (found version \"5.2.2\") \n    -- Could NOT find Eigen3 (missing: EIGEN3_INCLUDE_DIR EIGEN3_VERSION_OK) (Required is at least version \"2.91.0\")\n    CMake Warning at lm/interpolate/CMakeLists.txt:65 (message):\n      Not building interpolation.  Eigen3 was not found.\n    \n    \n    -- To install Eigen3 in your home directory, copy paste this:\n    export EIGEN3_ROOT=$HOME/eigen-eigen-07105f7124f9\n    (cd $HOME; wget -O - https://bitbucket.org/eigen/eigen/get/3.2.8.tar.bz2 |tar xj)\n    rm CMakeCache.txt\n    \n    -- Configuring done\n    -- Generating done\n    -- Build files have been written to: /content/AMMI-NLP/Part 02/001_LM/ngram_lm_lab/kenlm/build\n    \u001b[35m\u001b[1mScanning dependencies of target kenlm_filter\u001b[0m\n    \u001b[35m\u001b[1mScanning dependencies of target kenlm_util\u001b[0m\n    [  1%] \u001b[32mBuilding CXX object lm/filter/CMakeFiles/kenlm_filter.dir/arpa_io.cc.o\u001b[0m\n    [  2%] \u001b[32mBuilding CXX object lm/filter/CMakeFiles/kenlm_filter.dir/phrase.cc.o\u001b[0m\n    [  3%] \u001b[32mBuilding CXX object lm/filter/CMakeFiles/kenlm_filter.dir/vocab.cc.o\u001b[0m\n    [  5%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/double-conversion/bignum-dtoa.cc.o\u001b[0m\n    [  6%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/double-conversion/bignum.cc.o\u001b[0m\n    [  7%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/double-conversion/cached-powers.cc.o\u001b[0m\n    [  8%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/double-conversion/diy-fp.cc.o\u001b[0m\n    [ 10%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/double-conversion/double-conversion.cc.o\u001b[0m\n    [ 11%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/double-conversion/fast-dtoa.cc.o\u001b[0m\n    [ 12%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/double-conversion/fixed-dtoa.cc.o\u001b[0m\n    [ 13%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/double-conversion/strtod.cc.o\u001b[0m\n    [ 15%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/stream/chain.cc.o\u001b[0m\n    [ 16%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/stream/count_records.cc.o\u001b[0m\n    [ 17%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/stream/io.cc.o\u001b[0m\n    [ 18%] \u001b[32m\u001b[1mLinking CXX static library ../../lib/libkenlm_filter.a\u001b[0m\n    [ 18%] Built target kenlm_filter\n    [ 20%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/stream/line_input.cc.o\u001b[0m\n    [ 21%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/stream/multi_progress.cc.o\u001b[0m\n    [ 22%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/stream/rewindable_stream.cc.o\u001b[0m\n    [ 23%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/bit_packing.cc.o\u001b[0m\n    [ 25%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/ersatz_progress.cc.o\u001b[0m\n    [ 26%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/exception.cc.o\u001b[0m\n    [ 27%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/file.cc.o\u001b[0m\n    [ 28%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/file_piece.cc.o\u001b[0m\n    [ 30%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/float_to_string.cc.o\u001b[0m\n    [ 31%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/integer_to_string.cc.o\u001b[0m\n    [ 32%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/mmap.cc.o\u001b[0m\n    [ 33%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/murmur_hash.cc.o\u001b[0m\n    [ 35%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/parallel_read.cc.o\u001b[0m\n    [ 36%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/pool.cc.o\u001b[0m\n    [ 37%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/read_compressed.cc.o\u001b[0m\n    [ 38%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/scoped.cc.o\u001b[0m\n    [ 40%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/spaces.cc.o\u001b[0m\n    [ 41%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/string_piece.cc.o\u001b[0m\n    [ 42%] \u001b[32mBuilding CXX object util/CMakeFiles/kenlm_util.dir/usage.cc.o\u001b[0m\n    [ 43%] \u001b[32m\u001b[1mLinking CXX static library ../lib/libkenlm_util.a\u001b[0m\n    [ 43%] Built target kenlm_util\n    \u001b[35m\u001b[1mScanning dependencies of target probing_hash_table_benchmark\u001b[0m\n    \u001b[35m\u001b[1mScanning dependencies of target kenlm\u001b[0m\n    [ 45%] \u001b[32mBuilding CXX object util/CMakeFiles/probing_hash_table_benchmark.dir/probing_hash_table_benchmark_main.cc.o\u001b[0m\n    [ 46%] \u001b[32mBuilding CXX object lm/CMakeFiles/kenlm.dir/binary_format.cc.o\u001b[0m\n    [ 47%] \u001b[32mBuilding CXX object lm/CMakeFiles/kenlm.dir/config.cc.o\u001b[0m\n    [ 48%] \u001b[32mBuilding CXX object lm/CMakeFiles/kenlm.dir/bhiksha.cc.o\u001b[0m\n    [ 50%] \u001b[32mBuilding CXX object lm/CMakeFiles/kenlm.dir/lm_exception.cc.o\u001b[0m\n    [ 51%] \u001b[32mBuilding CXX object lm/CMakeFiles/kenlm.dir/model.cc.o\u001b[0m\n    [ 52%] \u001b[32mBuilding CXX object lm/CMakeFiles/kenlm.dir/quantize.cc.o\u001b[0m\n    [ 53%] \u001b[32mBuilding CXX object lm/CMakeFiles/kenlm.dir/read_arpa.cc.o\u001b[0m\n    [ 55%] \u001b[32mBuilding CXX object lm/CMakeFiles/kenlm.dir/search_hashed.cc.o\u001b[0m\n    [ 56%] \u001b[32mBuilding CXX object lm/CMakeFiles/kenlm.dir/search_trie.cc.o\u001b[0m\n    [ 57%] \u001b[32mBuilding CXX object lm/CMakeFiles/kenlm.dir/sizes.cc.o\u001b[0m\n    [ 58%] \u001b[32mBuilding CXX object lm/CMakeFiles/kenlm.dir/trie.cc.o\u001b[0m\n    [ 60%] \u001b[32mBuilding CXX object lm/CMakeFiles/kenlm.dir/trie_sort.cc.o\u001b[0m\n    [ 61%] \u001b[32mBuilding CXX object lm/CMakeFiles/kenlm.dir/value_build.cc.o\u001b[0m\n    [ 62%] \u001b[32mBuilding CXX object lm/CMakeFiles/kenlm.dir/virtual_interface.cc.o\u001b[0m\n    [ 63%] \u001b[32mBuilding CXX object lm/CMakeFiles/kenlm.dir/vocab.cc.o\u001b[0m\n    [ 65%] \u001b[32m\u001b[1mLinking CXX executable ../bin/probing_hash_table_benchmark\u001b[0m\n    [ 65%] Built target probing_hash_table_benchmark\n    [ 66%] \u001b[32mBuilding CXX object lm/CMakeFiles/kenlm.dir/common/print.cc.o\u001b[0m\n    [ 67%] \u001b[32mBuilding CXX object lm/CMakeFiles/kenlm.dir/common/model_buffer.cc.o\u001b[0m\n    [ 68%] \u001b[32mBuilding CXX object lm/CMakeFiles/kenlm.dir/common/renumber.cc.o\u001b[0m\n    [ 70%] \u001b[32mBuilding CXX object lm/CMakeFiles/kenlm.dir/common/size_option.cc.o\u001b[0m\n    [ 71%] \u001b[32m\u001b[1mLinking CXX static library ../lib/libkenlm.a\u001b[0m\n    [ 71%] Built target kenlm\n    \u001b[35m\u001b[1mScanning dependencies of target kenlm_benchmark\u001b[0m\n    \u001b[35m\u001b[1mScanning dependencies of target fragment\u001b[0m\n    \u001b[35m\u001b[1mScanning dependencies of target build_binary\u001b[0m\n    \u001b[35m\u001b[1mScanning dependencies of target query\u001b[0m\n    [ 72%] \u001b[32mBuilding CXX object lm/CMakeFiles/fragment.dir/fragment_main.cc.o\u001b[0m\n    [ 73%] \u001b[32mBuilding CXX object lm/CMakeFiles/build_binary.dir/build_binary_main.cc.o\u001b[0m\n    [ 75%] \u001b[32mBuilding CXX object lm/CMakeFiles/kenlm_benchmark.dir/kenlm_benchmark_main.cc.o\u001b[0m\n    [ 76%] \u001b[32mBuilding CXX object lm/CMakeFiles/query.dir/query_main.cc.o\u001b[0m\n    [ 77%] \u001b[32m\u001b[1mLinking CXX executable ../bin/fragment\u001b[0m\n    [ 77%] Built target fragment\n    [ 78%] \u001b[32m\u001b[1mLinking CXX executable ../bin/build_binary\u001b[0m\n    \u001b[35m\u001b[1mScanning dependencies of target kenlm_builder\u001b[0m\n    [ 80%] \u001b[32mBuilding CXX object lm/builder/CMakeFiles/kenlm_builder.dir/adjust_counts.cc.o\u001b[0m\n    [ 80%] Built target build_binary\n    \u001b[35m\u001b[1mScanning dependencies of target phrase_table_vocab\u001b[0m\n    [ 81%] \u001b[32mBuilding CXX object lm/filter/CMakeFiles/phrase_table_vocab.dir/phrase_table_vocab_main.cc.o\u001b[0m\n    [ 82%] \u001b[32m\u001b[1mLinking CXX executable ../bin/query\u001b[0m\n    [ 82%] Built target query\n    \u001b[35m\u001b[1mScanning dependencies of target filter\u001b[0m\n    [ 83%] \u001b[32mBuilding CXX object lm/filter/CMakeFiles/filter.dir/filter_main.cc.o\u001b[0m\n    [ 85%] \u001b[32m\u001b[1mLinking CXX executable ../../bin/phrase_table_vocab\u001b[0m\n    [ 86%] \u001b[32mBuilding CXX object lm/builder/CMakeFiles/kenlm_builder.dir/corpus_count.cc.o\u001b[0m\n    [ 86%] Built target phrase_table_vocab\n    [ 87%] \u001b[32mBuilding CXX object lm/builder/CMakeFiles/kenlm_builder.dir/initial_probabilities.cc.o\u001b[0m\n    [ 88%] \u001b[32mBuilding CXX object lm/builder/CMakeFiles/kenlm_builder.dir/interpolate.cc.o\u001b[0m\n    [ 90%] \u001b[32mBuilding CXX object lm/builder/CMakeFiles/kenlm_builder.dir/output.cc.o\u001b[0m\n    [ 91%] \u001b[32mBuilding CXX object lm/builder/CMakeFiles/kenlm_builder.dir/pipeline.cc.o\u001b[0m\n    [ 92%] \u001b[32m\u001b[1mLinking CXX executable ../bin/kenlm_benchmark\u001b[0m\n    [ 92%] Built target kenlm_benchmark\n    [ 93%] \u001b[32m\u001b[1mLinking CXX executable ../../bin/filter\u001b[0m\n    [ 93%] Built target filter\n    [ 95%] \u001b[32m\u001b[1mLinking CXX static library ../../lib/libkenlm_builder.a\u001b[0m\n    [ 95%] Built target kenlm_builder\n    \u001b[35m\u001b[1mScanning dependencies of target count_ngrams\u001b[0m\n    \u001b[35m\u001b[1mScanning dependencies of target lmplz\u001b[0m\n    [ 97%] \u001b[32mBuilding CXX object lm/builder/CMakeFiles/lmplz.dir/lmplz_main.cc.o\u001b[0m\n    [ 97%] \u001b[32mBuilding CXX object lm/builder/CMakeFiles/count_ngrams.dir/count_ngrams_main.cc.o\u001b[0m\n    [ 98%] \u001b[32m\u001b[1mLinking CXX executable ../../bin/lmplz\u001b[0m\n    [ 98%] Built target lmplz\n    [100%] \u001b[32m\u001b[1mLinking CXX executable ../../bin/count_ngrams\u001b[0m\n    [100%] Built target count_ngrams\n    /content/AMMI-NLP/Part 02/001_LM/ngram_lm_lab/kenlm\n    running install\n    running bdist_egg\n    running egg_info\n    creating kenlm.egg-info\n    writing kenlm.egg-info/PKG-INFO\n    writing dependency_links to kenlm.egg-info/dependency_links.txt\n    writing top-level names to kenlm.egg-info/top_level.txt\n    writing manifest file 'kenlm.egg-info/SOURCES.txt'\n    reading manifest file 'kenlm.egg-info/SOURCES.txt'\n    reading manifest template 'MANIFEST.in'\n    writing manifest file 'kenlm.egg-info/SOURCES.txt'\n    installing library code to build/bdist.linux-x86_64/egg\n    running install_lib\n    running build_ext\n    building 'kenlm' extension\n    creating build/temp.linux-x86_64-3.6\n    creating build/temp.linux-x86_64-3.6/util\n    creating build/temp.linux-x86_64-3.6/lm\n    creating build/temp.linux-x86_64-3.6/util/double-conversion\n    creating build/temp.linux-x86_64-3.6/python\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/integer_to_string.cc -o build/temp.linux-x86_64-3.6/util/integer_to_string.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/parallel_read.cc -o build/temp.linux-x86_64-3.6/util/parallel_read.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/string_piece.cc -o build/temp.linux-x86_64-3.6/util/string_piece.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/float_to_string.cc -o build/temp.linux-x86_64-3.6/util/float_to_string.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/bit_packing.cc -o build/temp.linux-x86_64-3.6/util/bit_packing.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/read_compressed.cc -o build/temp.linux-x86_64-3.6/util/read_compressed.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/spaces.cc -o build/temp.linux-x86_64-3.6/util/spaces.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/murmur_hash.cc -o build/temp.linux-x86_64-3.6/util/murmur_hash.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/file_piece.cc -o build/temp.linux-x86_64-3.6/util/file_piece.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/pool.cc -o build/temp.linux-x86_64-3.6/util/pool.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/scoped.cc -o build/temp.linux-x86_64-3.6/util/scoped.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/exception.cc -o build/temp.linux-x86_64-3.6/util/exception.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/mmap.cc -o build/temp.linux-x86_64-3.6/util/mmap.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/file.cc -o build/temp.linux-x86_64-3.6/util/file.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/usage.cc -o build/temp.linux-x86_64-3.6/util/usage.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/ersatz_progress.cc -o build/temp.linux-x86_64-3.6/util/ersatz_progress.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c lm/vocab.cc -o build/temp.linux-x86_64-3.6/lm/vocab.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c lm/value_build.cc -o build/temp.linux-x86_64-3.6/lm/value_build.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c lm/lm_exception.cc -o build/temp.linux-x86_64-3.6/lm/lm_exception.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c lm/config.cc -o build/temp.linux-x86_64-3.6/lm/config.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c lm/trie.cc -o build/temp.linux-x86_64-3.6/lm/trie.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c lm/binary_format.cc -o build/temp.linux-x86_64-3.6/lm/binary_format.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c lm/model.cc -o build/temp.linux-x86_64-3.6/lm/model.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c lm/sizes.cc -o build/temp.linux-x86_64-3.6/lm/sizes.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c lm/bhiksha.cc -o build/temp.linux-x86_64-3.6/lm/bhiksha.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c lm/read_arpa.cc -o build/temp.linux-x86_64-3.6/lm/read_arpa.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c lm/search_hashed.cc -o build/temp.linux-x86_64-3.6/lm/search_hashed.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c lm/virtual_interface.cc -o build/temp.linux-x86_64-3.6/lm/virtual_interface.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c lm/trie_sort.cc -o build/temp.linux-x86_64-3.6/lm/trie_sort.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c lm/quantize.cc -o build/temp.linux-x86_64-3.6/lm/quantize.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c lm/search_trie.cc -o build/temp.linux-x86_64-3.6/lm/search_trie.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/double-conversion/fixed-dtoa.cc -o build/temp.linux-x86_64-3.6/util/double-conversion/fixed-dtoa.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/double-conversion/strtod.cc -o build/temp.linux-x86_64-3.6/util/double-conversion/strtod.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/double-conversion/bignum-dtoa.cc -o build/temp.linux-x86_64-3.6/util/double-conversion/bignum-dtoa.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/double-conversion/double-conversion.cc -o build/temp.linux-x86_64-3.6/util/double-conversion/double-conversion.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/double-conversion/bignum.cc -o build/temp.linux-x86_64-3.6/util/double-conversion/bignum.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/double-conversion/diy-fp.cc -o build/temp.linux-x86_64-3.6/util/double-conversion/diy-fp.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/double-conversion/cached-powers.cc -o build/temp.linux-x86_64-3.6/util/double-conversion/cached-powers.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c util/double-conversion/fast-dtoa.cc -o build/temp.linux-x86_64-3.6/util/double-conversion/fast-dtoa.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c python/score_sentence.cc -o build/temp.linux-x86_64-3.6/python/score_sentence.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -c python/kenlm.cpp -o build/temp.linux-x86_64-3.6/python/kenlm.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 -DHAVE_ZLIB -DHAVE_BZLIB -DHAVE_XZLIB\n    creating build/lib.linux-x86_64-3.6\n    x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.6/util/integer_to_string.o build/temp.linux-x86_64-3.6/util/parallel_read.o build/temp.linux-x86_64-3.6/util/string_piece.o build/temp.linux-x86_64-3.6/util/float_to_string.o build/temp.linux-x86_64-3.6/util/bit_packing.o build/temp.linux-x86_64-3.6/util/read_compressed.o build/temp.linux-x86_64-3.6/util/spaces.o build/temp.linux-x86_64-3.6/util/murmur_hash.o build/temp.linux-x86_64-3.6/util/file_piece.o build/temp.linux-x86_64-3.6/util/pool.o build/temp.linux-x86_64-3.6/util/scoped.o build/temp.linux-x86_64-3.6/util/exception.o build/temp.linux-x86_64-3.6/util/mmap.o build/temp.linux-x86_64-3.6/util/file.o build/temp.linux-x86_64-3.6/util/usage.o build/temp.linux-x86_64-3.6/util/ersatz_progress.o build/temp.linux-x86_64-3.6/lm/vocab.o build/temp.linux-x86_64-3.6/lm/value_build.o build/temp.linux-x86_64-3.6/lm/lm_exception.o build/temp.linux-x86_64-3.6/lm/config.o build/temp.linux-x86_64-3.6/lm/trie.o build/temp.linux-x86_64-3.6/lm/binary_format.o build/temp.linux-x86_64-3.6/lm/model.o build/temp.linux-x86_64-3.6/lm/sizes.o build/temp.linux-x86_64-3.6/lm/bhiksha.o build/temp.linux-x86_64-3.6/lm/read_arpa.o build/temp.linux-x86_64-3.6/lm/search_hashed.o build/temp.linux-x86_64-3.6/lm/virtual_interface.o build/temp.linux-x86_64-3.6/lm/trie_sort.o build/temp.linux-x86_64-3.6/lm/quantize.o build/temp.linux-x86_64-3.6/lm/search_trie.o build/temp.linux-x86_64-3.6/util/double-conversion/fixed-dtoa.o build/temp.linux-x86_64-3.6/util/double-conversion/strtod.o build/temp.linux-x86_64-3.6/util/double-conversion/bignum-dtoa.o build/temp.linux-x86_64-3.6/util/double-conversion/double-conversion.o build/temp.linux-x86_64-3.6/util/double-conversion/bignum.o build/temp.linux-x86_64-3.6/util/double-conversion/diy-fp.o build/temp.linux-x86_64-3.6/util/double-conversion/cached-powers.o build/temp.linux-x86_64-3.6/util/double-conversion/fast-dtoa.o build/temp.linux-x86_64-3.6/python/score_sentence.o build/temp.linux-x86_64-3.6/python/kenlm.o -lstdc++ -lrt -lz -lbz2 -llzma -o build/lib.linux-x86_64-3.6/kenlm.cpython-36m-x86_64-linux-gnu.so\n    creating build/bdist.linux-x86_64\n    creating build/bdist.linux-x86_64/egg\n    copying build/lib.linux-x86_64-3.6/kenlm.cpython-36m-x86_64-linux-gnu.so -> build/bdist.linux-x86_64/egg\n    creating stub loader for kenlm.cpython-36m-x86_64-linux-gnu.so\n    byte-compiling build/bdist.linux-x86_64/egg/kenlm.py to kenlm.cpython-36.pyc\n    creating build/bdist.linux-x86_64/egg/EGG-INFO\n    copying kenlm.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying kenlm.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying kenlm.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying kenlm.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    writing build/bdist.linux-x86_64/egg/EGG-INFO/native_libs.txt\n    zip_safe flag not set; analyzing archive contents...\n    __pycache__.kenlm.cpython-36: module references __file__\n    creating dist\n    creating 'dist/kenlm-0.0.0-py3.6-linux-x86_64.egg' and adding 'build/bdist.linux-x86_64/egg' to it\n    removing 'build/bdist.linux-x86_64/egg' (and everything under it)\n    Processing kenlm-0.0.0-py3.6-linux-x86_64.egg\n    creating /usr/local/lib/python3.6/dist-packages/kenlm-0.0.0-py3.6-linux-x86_64.egg\n    Extracting kenlm-0.0.0-py3.6-linux-x86_64.egg to /usr/local/lib/python3.6/dist-packages\n    Adding kenlm 0.0.0 to easy-install.pth file\n    \n    Installed /usr/local/lib/python3.6/dist-packages/kenlm-0.0.0-py3.6-linux-x86_64.egg\n    Processing dependencies for kenlm==0.0.0\n    Finished processing dependencies for kenlm==0.0.0\n    /content/AMMI-NLP/Part 02/001_LM/ngram_lm_lab\n\n\n\n```python\n!ls\n```\n\n    data  img  kenlm  models  ngram_lms.ipynb\n\n\n<font color='red'>Please, restard runtime before running the code bellow</font>\n\n#### Preliminaries: Install KenLM\n\n[KenLM](https://kheafield.com/code/kenlm/) is used in the latter part of this lab.\n\nTo install it, run the following commands **in the jupyter terminal** (see screenshot):\n\n    sudo apt-get install build-essential libboost-all-dev cmake zlib1g-dev libbz2-dev liblzma-dev\n    \n    cd /home/jupyter\n    wget -O - https://kheafield.com/code/kenlm.tar.gz |tar xz\n    mkdir kenlm/build\n    cd kenlm/build\n    cmake ..\n    make -j 4\n    \n    cd /home/jupyter/kenlm\n    python setup.py install\n    \n\n\n\n\n\n```python\n# %cd AMMI-NLP/Part\\ 02/001_LM/ngram_lm_lab  \n!pip install jsonlines\n```\n\n    Requirement already satisfied: jsonlines in /home/aims/anaconda3/envs/aims/lib/python3.7/site-packages (1.2.0)\n    Requirement already satisfied: six in /home/aims/anaconda3/envs/aims/lib/python3.7/site-packages (from jsonlines) (1.12.0)\n\n\n\n```python\n%pylab inline\nimport os, sys, glob, json, math\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nfrom pprint import pprint\nfrom collections import defaultdict\npd.set_option('display.max_colwidth', -1)\n```\n\n    Populating the interactive namespace from numpy and matplotlib\n\n\n    /home/aims/anaconda3/envs/aims/lib/python3.7/site-packages/IPython/core/magics/pylab.py:160: UserWarning: pylab import has clobbered these variables: ['f']\n    `%matplotlib` prevents importing * from pylab and numpy\n      \"\\n`%matplotlib` prevents importing * from pylab and numpy\"\n\n\n### N-gram Language Modeling\n\nIn **language modeling** we want to model the probability of variable length sequences, $$\\large p(w_1,\\ldots,w_T)=\\prod_{t=1}^T p(w_t|w_{<t}).$$\n\nAn **n-gram language model** assumes that each word $w_t$ only depends on the preceding $n-1$ words, $$\\large p(w_1,\\ldots,w_T)=\\prod_{t=1}^T p(w_t|w_{t-n+1},\\ldots,w_{t-1}).$$\n\n \n\n#### Example\nFor instance, when modeling the sentence $$\\texttt{the cat sat on the mat .}$$ a 3-gram language model assumes that $$p(\\texttt{mat}|\\texttt{the cat sat on the}) \\approx p(\\texttt{mat}|\\texttt{on the}).$$\n\nThe sub-sequence $(\\texttt{on the mat})$ is a *3-gram* or *trigram*.\n\n\n\n### Count-based Estimation\n\nGiven some dataset $D$ of sequences, we can estimate an n-gram model through counting, derived as follows:\n\n\\begin{align}\np(w_t|w_{t-n+1},\\ldots,w_{t-1}) &= \\frac{p(w_{t-n+1},\\ldots,w_t)}{p(w_{t-n+1},\\ldots,w_{t-1})} & \\text{definition of conditional probability}\\\\\n                       &= \\frac{p(w_{t-n+1},\\ldots,w_t)}{\\sum_{w_{t'}}p(w_{t-n+1},\\ldots,w_{t-1},w_{t'})}\\\\\n                       &\\approx \\frac{\\frac{1}{N}\\text{count}(w_{t-n+1},\\ldots,w_t)}{\\frac{1}{N}\\sum_{w_{t'}}\\text{count}(w_{t-n+1},\\ldots,w_{t-1},w_{t'})}\\\\\n                       &= \\frac{\\text{count}(w_{t-n+1},\\ldots,w_t)}{\\sum_{w_{t'}}\\text{count}(w_{t-n+1},\\ldots,w_{t-1},w_{t'})}\\\\\n                       &= \\frac{\\text{count}(w_{t-n+1},\\ldots,w_t)}{\\text{count}(w_{t-n+1},\\ldots,w_{t-1})},\n\\end{align}\n\nwhere $N$ is the number of $n$-grams in the dataset.\n\nIn Python, we can collect these counts into a dictionary mapping a prefix to a dictionary of counts:\n\n        count[(w_n+1,...,w_t-1)] = {wt1: count of (w_n+1,...,w_t1),\n                                    wt2: count of (w_n+1,...,w_t2),\n                                    ...\n                                   }\n                                   \nand for the denominator, maintain a dictionary of totals:\n\n        total[(w_n+1,...,w_t-1)] = count of w_n+1,...,w_t-1\n\n### Simplified Language\n\nTo get intuition, lets start by modeling a simple language called `ABC`. A word in this language is one of three tokens, $$w\\in \\{\\texttt{A, B, C}\\},$$\nand we'll denote a sentence as $\\textbf{w}=(w_1,\\ldots,w_{|\\textbf{w}|})$.\n\n\nSuppose we are given the following dataset, and want to estimate a **bigram model**: $$p(\\textbf{w})\\approx\\prod_{t=1}^{|\\textbf{w}|}p(w_t|w_{t-1})\\quad\\quad(*)$$\n\n\n```python\ndata_raw = [['A', 'A', 'B', 'B'],\n            ['A', 'A', 'B'],\n            ['A', 'A', 'B', 'C'],\n            ['A', 'A', 'A'],\n            ['A', 'A', 'A', 'A']]\n```\n\nSince our model is a probability distribution, the total probability of all possible strings in the language must sum to 1, i.e.: $$\\sum_{\\textbf{w}}p(\\textbf{w})=1.$$\n\nIn order to satisfy this criterion it turns out that we need an additional **beginning token**, `<bos>`, and **end token**, `<eos>`:\n\n\n```python\ndata = [['<bos>'] + d + ['<eos>'] for d in data_raw]\ndata\n```\n\n\n\n\n    [['<bos>', 'A', 'A', 'B', 'B', '<eos>'],\n     ['<bos>', 'A', 'A', 'B', '<eos>'],\n     ['<bos>', 'A', 'A', 'B', 'C', '<eos>'],\n     ['<bos>', 'A', 'A', 'A', '<eos>'],\n     ['<bos>', 'A', 'A', 'A', 'A', '<eos>']]\n\n\n\nNow let's estimate a bigram model:\n\n\\begin{align}\np(w_t|w_{t-1}) &= \\frac{\\text{count}(w_{t-1}w_{t})}{\\sum_{w_{t'}}\\text{count}(w_{t-1}w_{t'})}\\\\\n               &= \\texttt{count[prefix][wt] / totals[prefix]}\n\\end{align} \n\nwhere $\\texttt{prefix}$ is $w_{t-1}$ in this case.\n\n\n```python\ncount = defaultdict(lambda: defaultdict(float))\ntotal = defaultdict(float)\n\nn = 2\nfor sequence in data:\n    for i in range(len(sequence)-n+1):         # for each ngram\n        ngram = tuple(sequence[i:i+n])\n        prefix, word = ngram[:-1], ngram[-1]\n        count[prefix][word] += 1               # count(w_{t-n+1}...w_t)\n        total[prefix] += 1                     # count(w_{t-n+1}...w_{t-1})\n```\n\nLet's see if the counts and totals make sense:\n\n- How many times did (A, B) occur? What about (B, B)?\n- How many times did (A) occur? What about (C)?\n\n\n```python\nprint(\"Counts:\")\npprint(dict(count))\nprint(\"\\nTotals:\")\npprint(dict(total))\n```\n\n    Counts:\n    {('<bos>',): defaultdict(<class 'float'>, {'A': 5.0}),\n     ('A',): defaultdict(<class 'float'>, {'A': 8.0, 'B': 3.0, '<eos>': 2.0}),\n     ('B',): defaultdict(<class 'float'>, {'B': 1.0, '<eos>': 2.0, 'C': 1.0}),\n     ('C',): defaultdict(<class 'float'>, {'<eos>': 1.0})}\n    \n    Totals:\n    {('<bos>',): 5.0, ('A',): 13.0, ('B',): 4.0, ('C',): 1.0}\n\n\n#### Conditional probability queries\n\nWe can now query a conditional probability:\n\n\\begin{align}\n\\texttt{p(word|prefix)} =&\\ \\texttt{count[prefix][word] / totals[prefix]}\n\\end{align}\n\n\n```python\nqueries = [('<bos>', 'A'),\n           ('B', 'C')]\n\nfor query in queries:\n    prefix, word = query[:-1], query[-1]\n    p = count[prefix][word] / total[prefix]  # We'll discuss the case when `total[prefix] = 0` below.\n    print(\"p( %s | %s) = \\t%.5f\" % (word, ', '.join(prefix), p))\n```\n\n    p( A | <bos>) = \t1.00000\n    p( C | B) = \t0.25000\n\n\n**Exercise**: Look at the training set and convince yourself that these conditional probabilities are correct according to the count-based estimation procedure.\n\n#### Sequence Probability\n\nWe can compute the probability of a sequence using the conditional probabilities along with the chain rule of probability:\n\n\\begin{align}\np(w_1,\\ldots,w_T)&\\approx\\prod_{t=1}^T p(w_t|w_{t-1})\n\\end{align}\n\n(Here $w_0$ is `<bos>` and $w_T$ is `<eos>`)\n\n\n```python\nsequence = ['<bos>', 'A', 'A', 'B', '<eos>']\n\ndef sequence_p(sequence, log=False):\n    total_p = 1\n\n    for i in range(len(sequence)-n+1):\n        ngram = tuple(sequence[i:i+n])\n        prefix = ngram[:-1]\n        word = ngram[-1]\n        p = count[prefix][word] / max(total[prefix], 1)\n        if log:\n            print(\"p(%s | %s) =\\t%.3f\" % (word, ', '.join(prefix), p))\n\n        total_p *= p\n    return total_p\n    \n\nprint(\"\\nProduct: p(%s) = %.3f\" % (''.join(sequence[1:-1]), sequence_p(sequence, log=True)))\n```\n\n    p(A | <bos>) =\t1.000\n    p(A | A) =\t0.615\n    p(B | A) =\t0.231\n    p(<eos> | B) =\t0.500\n    \n    Product: p(AAB) = 0.071\n\n\n### Real Example: Dialogue Utterances\n\nNow lets use the same ideas on a more realistic text corpus.\n\nWe will use utterances from a dialogue dataset called **Persona-Chat**. This dataset is relatively small and centers on a single domain, but it is simple and interpretable for our purposes here.\n\nWe'll also use an off-the-shelf ngram modeling package called `KenLM`.\n\n#### Loading the dataset\n\n\n```python\n!ls\n```\n\n    data  img  kenlm  models  ngram_lms.ipynb\n\n\n\n```python\ntrain = []\nvalid = []\nimport jsonlines\n\nfor ds, name in [(train, 'train'), (valid, 'valid')]:\n    for line in jsonlines.Reader(open('data/personachat/personachat_all_sentences_%s.jsonl' % name, 'r')):\n        ds.append(line['tokens'])\n        \nvocab = list(set([t for ts in train for t in ts]))      \nprint(\"Number of train examples: %d\" % (len(train)))\nprint(\"Number of valid examples: %d\" % (len(valid)))\nprint(\"Vocab size: %d\" % (len(vocab)))\n\nprint(\"\\nExamples:\")\npprint(train[:3])\n```\n\n    Number of train examples: 133176\n    Number of valid examples: 16181\n    Vocab size: 19153\n    \n    Examples:\n    [['i', 'am', 'doing', 'great', 'except', 'for', 'the', 'allergies', '.'],\n     ['i', 'am', 'a', 'woman', 'what', 'about', 'you', '.'],\n     ['i', 'thought', 'you', 'were', 'a', 'college', 'kid', '.']]\n\n\n### KenLM\n\nKenLM estimates n-gram language models using **modified Kneser-Ney smoothing**, and has a fast and memory-efficient implementation. \n- While we won't go into details here, **smoothing** is a technique used to account for ngrams that do not occur in the training corpus. \n- Normally, these ngrams would receive zero-probability mass. Smoothing ensures every ngram receives some probability.\n\n\n\nPlease see page 48 of the [lecture note](https://github.com/nyu-dl/NLP_DL_Lecture_Note/blob/master/lecture_note.pdf) for an overview of Kneser-Ney smoothing, and [[Chen & Goodman 1998]](https://dash.harvard.edu/bitstream/handle/1/25104739/tr-10-98.pdf?sequence=1) for further details.\n\n\n```python\nKENLM_DIR='./kenlm' # for colab and local computers\n# KENLM_DIR='/home/jupyter/kenlm' # for GCP\n```\n\n#### Tokenize data\n\n\n```python\nif not os.path.exists('data/tokenized'):\n    os.makedirs('data/tokenized')\nwith open('data/tokenized/pchat_train', 'w') as f:\n    for line in tqdm(train):\n        f.write(' '.join(line))\n        f.write('\\n')\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 133176/133176 [00:00<00:00, 711179.93it/s]\n\n\n#### Build kenlm n-gram models\n\nThis uses the `kenlm` commands `lmplz` to estimate the language model, then `build_binary` to convert it to an efficient format. We load the resulting model using the `kenlm` python wrapper.\n\nWe do this for n-gram models of order `2,3,4`:\n\n\n```python\nimport kenlm\n\ndata_prefix = 'pchat'\ndataset = 'pchat_train'\nif not os.path.exists('models'):\n    os.makedirs('models')\n\nmodels = {}\nfor n in [2,3,4]:\n    model_temp = 'models/%s_%d.arpa' % (data_prefix, n)\n    model_name = 'models/%s_%d.klm' % (data_prefix, n)\n    ! cat ./data/tokenized/$dataset | $KENLM_DIR/build/bin/lmplz -o $n > $model_temp\n    ! $KENLM_DIR/build/bin/build_binary $model_temp $model_name\n    models[n] = kenlm.LanguageModel(model_name)\n```\n\n    === 1/5 Counting and sorting n-grams ===\n    File stdin isn't normal.  Using slower read() instead of mmap().  No progress bar.\n    Unigram tokens 1602042 types 19156\n    === 2/5 Calculating and sorting adjusted counts ===\n    Chain sizes: 1:229872 2:13355060224\n    /home/aims/Desktop/kenlm/util/scoped.cc:20 in void* util::{anonymous}::InspectAddr(void*, std::size_t, const char*) threw MallocException because `!addr && requested'.\n    Cannot allocate memory for 13355060224 bytes in malloc\n    Aborted\n    Reading models/pchat_2.arpa\n    ----5---10---15---20---25---30---35---40---45---50---55---60---65---70---75---80---85---90---95--100\n    End of file Byte: 0\n    ERROR\n    === 1/5 Counting and sorting n-grams ===\n    File stdin isn't normal.  Using slower read() instead of mmap().  No progress bar.\n    Unigram tokens 1602042 types 19156\n    === 2/5 Calculating and sorting adjusted counts ===\n    Chain sizes: 1:229872 2:4645238272 3:8709822464\n    Statistics:\n    1 19156 D1=0.588857 D2=1.0348 D3+=1.3388\n    2 231267 D1=0.722265 D2=1.09097 D3+=1.44737\n    3 617624 D1=0.798924 D2=1.0703 D3+=1.33013\n    Memory estimate for binary LM:\n    type       kB\n    probing 16763 assuming -p 1.5\n    probing 18193 assuming -r models -p 1.5\n    trie     6683 without quantization\n    trie     3625 assuming -q 8 -b 8 quantization \n    trie     6354 assuming -a 22 array pointer compression\n    trie     3296 assuming -a 22 -q 8 -b 8 array pointer compression and quantization\n    === 3/5 Calculating and sorting initial probabilities ===\n    Chain sizes: 1:229872 2:3700272 3:12352480\n    ----5---10---15---20---25---30---35---40---45---50---55---60---65---70---75---80---85---90---95--100\n    ####################################################################################################\n    === 4/5 Calculating and writing order-interpolated probabilities ===\n    Chain sizes: 1:229872 2:3700272 3:12352480\n    ----5---10---15---20---25---30---35---40---45---50---55---60---65---70---75---80---85---90---95--100\n    ####################################################################################################\n    === 5/5 Writing ARPA model ===\n    ----5---10---15---20---25---30---35---40---45---50---55---60---65---70---75---80---85---90---95--100\n    ****************************************************************************************************\n    Name:lmplz\tVmPeak:13193612 kB\tVmRSS:23260 kB\tRSSMax:3049068 kB\tuser:1.2624\tsys:0.816377\tCPU:2.07881\treal:1.97458\n    Reading models/pchat_3.arpa\n    ----5---10---15---20---25---30---35---40---45---50---55---60---65---70---75---80---85---90---95--100\n    ****************************************************************************************************\n    SUCCESS\n    === 1/5 Counting and sorting n-grams ===\n    File stdin isn't normal.  Using slower read() instead of mmap().  No progress bar.\n    Unigram tokens 1602042 types 19156\n    === 2/5 Calculating and sorting adjusted counts ===\n    Chain sizes: 1:229872 2:2273201664 3:4262253056 4:6819604992\n    Statistics:\n    1 19156 D1=0.588857 D2=1.0348 D3+=1.3388\n    2 231267 D1=0.722265 D2=1.09097 D3+=1.44737\n    3 617624 D1=0.821472 D2=1.14168 D3+=1.40217\n    4 932153 D1=0.863174 D2=1.12888 D3+=1.29333\n    Memory estimate for binary LM:\n    type       kB\n    probing 36767 assuming -p 1.5\n    probing 41816 assuming -r models -p 1.5\n    trie    15838 without quantization\n    trie     8356 assuming -q 8 -b 8 quantization \n    trie    14567 assuming -a 22 array pointer compression\n    trie     7085 assuming -a 22 -q 8 -b 8 array pointer compression and quantization\n    === 3/5 Calculating and sorting initial probabilities ===\n    Chain sizes: 1:229872 2:3700272 3:12352480 4:22371672\n    ----5---10---15---20---25---30---35---40---45---50---55---60---65---70---75---80---85---90---95--100\n    ####################################################################################################\n    === 4/5 Calculating and writing order-interpolated probabilities ===\n    Chain sizes: 1:229872 2:3700272 3:12352480 4:22371672\n    ----5---10---15---20---25---30---35---40---45---50---55---60---65---70---75---80---85---90---95--100\n    ####################################################################################################\n    === 5/5 Writing ARPA model ===\n    ----5---10---15---20---25---30---35---40---45---50---55---60---65---70---75---80---85---90---95--100\n    ****************************************************************************************************\n    Name:lmplz\tVmPeak:13210000 kB\tVmRSS:45052 kB\tRSSMax:2658428 kB\tuser:1.80083\tsys:0.928808\tCPU:2.72967\treal:2.42089\n    Reading models/pchat_4.arpa\n    ----5---10---15---20---25---30---35---40---45---50---55---60---65---70---75---80---85---90---95--100\n    ****************************************************************************************************\n    SUCCESS\n\n\n## Evaluation\n\n### Perplexity\n\nIntuitively, a good model should assign high probabilities to sequences from the 'true' distribution that it is modeling.\n\nA common way of quantifying this is with **perplexity**, a metric inversely-proportional to the probability that the model assigns to a set of sequences, e.g. a 'test set':\n\n\\begin{align}\n\\large \\text{ppl}(p, D) &\\large\\ = 2^{-\\frac{1}{N_{total}}\\log_2 p(D)}\n\\end{align}\n\n\nwhere $D=\\{(w_1,\\ldots,w_{N_i})_i\\}_{i=1}^M$ is a dataset of $M$ sequences with total length $N_{\\text{total}}=\\sum_{i}N_i$.\n\nPerplexity is defined on $[1,\\infty)$, with 1 being a perfect model (assigning probability 1 to $D$), and a 'worse' model as perplexity increases.\n\nIntuitively, _perplexity measures the average rank of the true next-token, when tokens are ordered by the model's conditional probabilities_.\n\n\n<!-- Section 1.3 of [[Chen & Goodman 1998]](https://dash.harvard.edu/bitstream/handle/1/25104739/tr-10-98.pdf?sequence=1) has a concise summary of perplexity and its motivation. !-->\n\n#### Evaluate Perplexity\n\n`kenlm` outputs log probabilities in **log base 10**. For the standard definition of perplexity we need **log base 2**. See the code below:\n\n\n```python\ndef perplexity_kenlm(model, sequences):\n    n_total = 0\n    logp_total = 0\n    for sequence in sequences:\n        text = ' '.join(sequence)\n        logp_total += model.score(text)\n        n_total += len(sequence) + 1  # add 1 for </s>\n        \n    # Convert log10 to log2\n    log2p_total = logp_total / np.log10(2)\n    ppl = 2 ** (- (1.0 / n_total) * log2p_total)\n    return ppl\n```\n\n\n```python\nprint(\"=== Train ===\")\ndf = pd.DataFrame([(n, perplexity_kenlm(models[n], train)) for n in [2, 3, 4]], columns=['n', 'ppl'])\ndf.style.hide_index()\n```\n\n    === Train ===\n\n\n\n\n\n<style  type=\"text/css\" >\n</style><table id=\"T_e5837c9e_6c96_11ea_ad9b_5c879cd0a093\" ><thead>    <tr>        <th class=\"col_heading level0 col0\" >n</th>        <th class=\"col_heading level0 col1\" >ppl</th>    </tr></thead><tbody>\n                <tr>\n                                <td id=\"T_e5837c9e_6c96_11ea_ad9b_5c879cd0a093row0_col0\" class=\"data row0 col0\" >2</td>\n                        <td id=\"T_e5837c9e_6c96_11ea_ad9b_5c879cd0a093row0_col1\" class=\"data row0 col1\" >39.9248</td>\n            </tr>\n            <tr>\n                                <td id=\"T_e5837c9e_6c96_11ea_ad9b_5c879cd0a093row1_col0\" class=\"data row1 col0\" >3</td>\n                        <td id=\"T_e5837c9e_6c96_11ea_ad9b_5c879cd0a093row1_col1\" class=\"data row1 col1\" >15.462</td>\n            </tr>\n            <tr>\n                                <td id=\"T_e5837c9e_6c96_11ea_ad9b_5c879cd0a093row2_col0\" class=\"data row2 col0\" >4</td>\n                        <td id=\"T_e5837c9e_6c96_11ea_ad9b_5c879cd0a093row2_col1\" class=\"data row2 col1\" >8.91961</td>\n            </tr>\n    </tbody></table>\n\n\n\n\n```python\nprint(\"=== Valid ===\")\ndf = pd.DataFrame([(n, perplexity_kenlm(models[n], valid)) for n in [2, 3, 4]], columns=['n', 'ppl'])\ndf.style.hide_index()\n```\n\n    === Valid ===\n\n\n\n\n\n<style  type=\"text/css\" >\n</style><table id=\"T_eb9c1c6c_6c96_11ea_ad9b_5c879cd0a093\" ><thead>    <tr>        <th class=\"col_heading level0 col0\" >n</th>        <th class=\"col_heading level0 col1\" >ppl</th>    </tr></thead><tbody>\n                <tr>\n                                <td id=\"T_eb9c1c6c_6c96_11ea_ad9b_5c879cd0a093row0_col0\" class=\"data row0 col0\" >2</td>\n                        <td id=\"T_eb9c1c6c_6c96_11ea_ad9b_5c879cd0a093row0_col1\" class=\"data row0 col1\" >59.188</td>\n            </tr>\n            <tr>\n                                <td id=\"T_eb9c1c6c_6c96_11ea_ad9b_5c879cd0a093row1_col0\" class=\"data row1 col0\" >3</td>\n                        <td id=\"T_eb9c1c6c_6c96_11ea_ad9b_5c879cd0a093row1_col1\" class=\"data row1 col1\" >44.9771</td>\n            </tr>\n            <tr>\n                                <td id=\"T_eb9c1c6c_6c96_11ea_ad9b_5c879cd0a093row2_col0\" class=\"data row2 col0\" >4</td>\n                        <td id=\"T_eb9c1c6c_6c96_11ea_ad9b_5c879cd0a093row2_col1\" class=\"data row2 col1\" >43.2188</td>\n            </tr>\n    </tbody></table>\n\n\n\n#### Sequence probabilities:\n\\begin{align}\np(w_1,\\ldots,w_T)&\\approx\\prod_{t=1}^T p(w_t|w_{t-2},w_{t-1})\\\\\n&=\\sum_{t=1}^T \\log p(w_t|w_{t-2},w_{t-1}).\n\\end{align}\n\nwhere we use log probabilities in practice to avoid a product of many small numbers.\n\n\n```python\nsentences = [\n    'i like my pet dog .',\n    'i like my pet zebra .',\n    'i like my pet lion .',\n    'i live in the united states .',\n    'i live in the united states of america .'\n]\n\nfor sentence in sentences:\n    print(sentence)\n    for n in [2, 3, 4]:\n        log10p = models[n].score(sentence)\n        log2p = log10p / np.log10(2)\n        print(\"n: %d\\t logp: %.3f\" % (n, log2p))\n    print()\n```\n\n    i like my pet dog .\n    n: 2\t logp: -29.216\n    n: 3\t logp: -28.843\n    n: 4\t logp: -29.219\n    \n    i like my pet zebra .\n    n: 2\t logp: -32.303\n    n: 3\t logp: -31.157\n    n: 4\t logp: -32.101\n    \n    i like my pet lion .\n    n: 2\t logp: -38.352\n    n: 3\t logp: -41.017\n    n: 4\t logp: -42.320\n    \n    i live in the united states .\n    n: 2\t logp: -22.599\n    n: 3\t logp: -20.095\n    n: 4\t logp: -17.854\n    \n    i live in the united states of america .\n    n: 2\t logp: -40.958\n    n: 3\t logp: -26.627\n    n: 4\t logp: -24.311\n    \n\n", "meta": {"hexsha": "03576861c4332e3a836e90daec560b1d5ac4388e", "size": 71365, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Part 02/001_LM/ngram_lm_lab/ngram_lms.ipynb", "max_stars_repo_name": "Kabongosalomon/AMMI-NLP", "max_stars_repo_head_hexsha": "00a0e47399926ad1951b84a11cd936598a9c7c3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-20T15:04:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-20T16:39:37.000Z", "max_issues_repo_path": "Part 02/001_LM/ngram_lm_lab/ngram_lms.ipynb", "max_issues_repo_name": "Kabongosalomon/AMMI-NLP", "max_issues_repo_head_hexsha": "00a0e47399926ad1951b84a11cd936598a9c7c3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Part 02/001_LM/ngram_lm_lab/ngram_lms.ipynb", "max_forks_repo_name": "Kabongosalomon/AMMI-NLP", "max_forks_repo_head_hexsha": "00a0e47399926ad1951b84a11cd936598a9c7c3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.6493967353, "max_line_length": 2332, "alphanum_fraction": 0.6060954249, "converted": true, "num_tokens": 18371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.09138210182990687, "lm_q1q2_score": 0.03687878732322113}}
{"text": "```python\n%matplotlib inline\nfrom IPython.display import display,Math\nfrom sympy import *\ninit_session()\n```\n\n\n```python\nimport datetime\nutime = 0\ndt = datetime.datetime.fromtimestamp(utime,datetime.timezone.utc)\nprint(\"{0:d} \u306b\u5bfe\u5fdc\u3059\u308bUNIX\u6642\u9593\u306f {1:s} \u3067\u3059\uff0e\".format(utime,str(dt)[:-6]))\n```\n\n\n```python\nimport time\nnow = time.time()\nnow_jst = str(datetime.datetime.fromtimestamp(now,datetime.timezone(datetime.timedelta(hours=9))))\nnow_utc = str(datetime.datetime.fromtimestamp(now,datetime.timezone.utc))\nprint(\"\u4eca\u306f{0:s}\u3067\u3059\uff0e\\n(\u65e5\u672c\u6642\u9593{1:s})\\nUNIX\u6642\u9593\u306f {2:d} \u306b\u306a\u308a\u307e\u3059\uff0e\".format(now_utc,now_jst,int(now*10**3)))\n```\n\n\n```python\nimport time\nimport datetime\nfrom IPython.display import HTML\nfrom ipywidgets import interact\nfrom ipywidgets import interact,Dropdown,IntSlider\n@interact\ndef _(n=str(int(time.time()))):\n    n = int(eval(n))\n    dt = datetime.datetime.fromtimestamp(n,datetime.timezone.utc)\n    return HTML(\"{0:d} \u306b\u5bfe\u5fdc\u3059\u308b\u6642\u9593\u306f {1:s}\".format(n,str(dt)[:-6]))\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "70089ea60f0cf981507fb6150ac7d07521d7f7a6", "size": 2655, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "21jk1-0428.ipynb", "max_stars_repo_name": "ritsumei-aoi/21jk1", "max_stars_repo_head_hexsha": "2d49628ef8721a507193a58aa1af4b31a60dfd8b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "21jk1-0428.ipynb", "max_issues_repo_name": "ritsumei-aoi/21jk1", "max_issues_repo_head_hexsha": "2d49628ef8721a507193a58aa1af4b31a60dfd8b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "21jk1-0428.ipynb", "max_forks_repo_name": "ritsumei-aoi/21jk1", "max_forks_repo_head_hexsha": "2d49628ef8721a507193a58aa1af4b31a60dfd8b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3109243697, "max_line_length": 107, "alphanum_fraction": 0.5612052731, "converted": true, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957277, "lm_q2_score": 0.0826973375883307, "lm_q1q2_score": 0.03684410636473956}}
{"text": "[Home](home.ipynb) > Perception biases in networks with Homophily and Preferential Attachment\n\n\n\n### *Notebooks for Social Network Analysis*\n\n# Perception biases in networks with homophily and group sizes\n\nAuthor: [Fariba Karimi](https://www.gesis.org/person/fariba.karimi)\n\nVersion: 0.1 (21.01.2020)\n\nPlease cite as: Karimi, Fariba (2020). Perception biases in networks with homophily and group sizes. *Notebooks for Social Network Analysis*. GESIS. url:xxx\n\n<div class=\"alert alert-info\">\n<big><b>Significance</b></big>\n\nPeople\u2019s perceptions about the size of minority groups in social networks can be biased, often showing systematic over- or\nunderestimation. These social perception biases are often attributed to biased cognitive or motivational processes. Here we\nshow that both over- and underestimation of the size of a minority group can emerge solely from structural properties of social\nnetworks. Using a generative network model, we show that these biases depend on the level of homophily, its asymmetric\nnature and on the size of the minority group. Our model predictions correspond well with empirical data from a cross-cultural\nsurvey and with numerical calculations from six real-world networks. We also identify circumstances under which individuals\ncan reduce their biases by relying on perceptions of their neighbours. \n</div>\n\n### For more information, please visit the following paper\n\n\n\n\n\n\n## Introduction\n\nPeople\u2019s perceptions of their social worlds determine their own\npersonal aspirations1 and willingness to engage in different\nbehaviours, from voting and energy conservation to health\nbehaviour, drinking and smoking. Yet, when forming these perceptions,\npeople seldom have an opportunity to draw representative\nsamples from the overall social network, or from the general\npopulation. Instead, their samples are constrained by the local\nstructure of their personal networks, which can bias their perception\nof the relative frequency of different attributes in the general\npopulation. For example, supporters of different candidates in the\n2016 US presidential election formed relatively isolated Twitter\ncommunities. Such insular communities can overestimate the relative\nfrequency of their own attributes in the overall society. This\nhas been documented in the literature on overestimation effects\nincluding *false consensus*, looking-glass perception and, more generally,\nsocial projection. In an apparent contradiction, it has also\nbeen documented that people holding a particular view sometimes\nunderestimate the frequency of that view, as described in the literature\non *false uniqueness*, pluralistic ignorance and majority\nillusion. These over- and underestimation errors, which we call\nsocial perception biases, affect people\u2019s judgements of minority- and\nmajority-group sizes.\n\nIn this study, we show empirically, analytically and numerically that a\nsimple network model can explain both over- and underestimation\nin social perceptions, without assuming biased motivational or cognitive\nprocesses.\n\n\nAt the individual level, we assume that individuals\u2019 perceptions\nare based on the frequency of an attribute in their personal networks\n(their direct neighbourhoods). We define individual i\u2019s social\nperception bias as follows:\n\n\\begin{equation}\n    B_{indv,i}=1/f_{m}\\frac{\\sum_{j\\in\\delta}{ x_j}}{k_i},\n\\end{equation}\n\n\nwhere $f_m$ denotes the fraction of minority in the whole network, $\\delta$ is the set of $i$'s neighbors, and $k_i$ is the degree of $i$. The group perdception bias is the average perception over all the members of the group. \n\nFigure below describes the concept of the perception bias. The blue node $i$ in the center tends to underestimate the size of the minority nodes (orange nodes) in the homophilic networks and overestimate the size of the minority nodes in the heterophilic network:\n\n\n\n\n\n**In this notebook**, I provide an intuitive walk through the construction of the perception biases in homophilic-preferential attachment network Model (BA-Homophily model). For constructing the BA-Homophily model, please check the other notebook. \n\n\n## Dependencies and Settings\n\n\n```python\n%matplotlib inline\n```\n\n\n```python\nimport numpy as np \nimport matplotlib.pyplot as plt \n```\n\n\n```python\n\n```\n\n## Model\n\n``homophilic_ba_graph(N,m,min_fraction,homophily)`` is the main function to generate the network. This function can be called from ``generate_homophilic_graph_symmetric.py``. \n\nAfter generating the BA-Homophily model, we can measure the perception bias of each node by iterating over each node and calculating the perception bias. Finally, we average the perception bias across each group to calculate the group perception bias. The results are averaged over 20 independet simulations and stored at ``perception_bias/images/Fig2``. \n\n\n\n\n\n### Draw the perception bias versus homophily and minority size\n\nHere we plot perception bias of the minority and the majority group versus homophily and group sizes. \n\n\n```python\n\n\nplt.rcParams[\"font.family\"] = \"sans-serif\"\n\n\nfminor_list = [0.1, 0.2, 0.3, 0.4, 0.5]\nfig = plt.figure(figsize = (10,6))\nha = [i/10. for i in range(11)]\nhb = [1.-temp_h for temp_h in ha]\nax1 = fig.add_subplot(1,2,1)\nax2 = fig.add_subplot(1,2,2)\nax1.axvspan(0.5,1.0,color='lightgrey', edgecolor = 'lightgrey', alpha=0.5)\nax2.axvspan(0.0,0.5, color='lightgrey', edgecolor = 'lightgrey', alpha=0.5)\ncmap = ['Goldenrod', 'coral', 'Pink', 'Firebrick', 'Red']\nfor fi in range(len(fminor_list)) : \n    fminor = fminor_list[fi]\n   \n    ''' Initial data'''\n    Cdata = np.loadtxt('perception_bias/images/Fig2/ctest_fa%s.txt' %(fminor))\n    fa = fminor \n    fb = 1.-fminor \n    \n    minor_data = np.loadtxt('perception_bias/images/Fig2/neterr_minor_fa%s.txt' %(fminor))\n    major_data = np.loadtxt('perception_bias/images/Fig2/neterr_major_fa%s.txt' %(fminor))\n    c = Cdata[:,1]\n\n    ''' Fig1(a) for the minority'''\n    minorh = minor_data[:,0]\n    minor_neterr = minor_data[:,1]\n    minor_analytic_y = [2*((fa*ha[temp_c])/(ha[temp_c]*c[temp_c]+hb[temp_c]*(2.-c[temp_c])) )/fa for temp_c in range(len(c))]\n    norm_minor_neterr = [(merr+fminor)/fminor for merr in minor_neterr]\n    ax1.axhline(y=1, color = 'grey', ls = 'dashed')\n    ax1.scatter(minorh, norm_minor_neterr, marker = 'o', edgecolor = 'black', s= 60,label = '$f_M=%s$' %fminor, facecolor = cmap[fi], zorder = 2)\n    ax1.plot(minorh, minor_analytic_y, label = '',color = cmap[fi])\n    ax1.set_xlabel(r'$h$', fontsize = 25)\n    ax1.set_ylabel(r'$P_{group}$', fontsize = 25,labelpad = -5)\n    ax1.xaxis.set_tick_params(labelsize=20)\n    ax1.yaxis.set_tick_params(labelsize=20)\n    ax1.set_xlim([0.0,1.0])\n    ax1.set_ylim([0.0,10.0])\n    \n\n    \n\n    ''' Fig1(b) for the majority'''\n    majorh = major_data[:,0]\n    major_neterr = major_data[:,1]\n    major_analytic_y = [((fa*hb[temp_c])/(ha[temp_c]*c[temp_c]+hb[temp_c]*(2.-c[temp_c])) + ((c[temp_c]/(2.-c[temp_c]))*(fb*hb[temp_c])/(hb[temp_c]*c[temp_c]+ha[temp_c]*(2.-c[temp_c]))))/ (fa) for temp_c in range(len(c))]\n    norm_major_neterr = [(mjerr+fminor)/fminor for mjerr in major_neterr]\n    ax2.axhline(y=1, color = 'grey', ls = 'dashed')\n    ax2.scatter(majorh, norm_major_neterr, marker = 'o', s = 60, edgecolor = 'black', label = '$f_M=%s$' %fminor, color = cmap[fi], zorder = 2)\n    ax2.plot(majorh, major_analytic_y, label = '',color = cmap[fi])\n    ax2.set_xlabel(r'$h$', fontsize = 25)\n    ax2.xaxis.set_tick_params(labelsize=20)\n    ax2.yaxis.set_tick_params(labelsize=20)\n    ax2.set_xlim(0.0,1.0)\n    ax2.set_ylim(0.0,10.0)\n    \n\n    \n''' Set labels ''' \nax1.text(0.3,10.3, '(a) Minority',fontsize = 20)\nax2.text(0.3,10.3,'(b) Majority', fontsize = 20)\n\nax1.text(0.57,0.4, 'Filter Bubble',fontsize = 14,style='italic')\nax2.text(0.04,0.4, 'Majority Illusion',fontsize = 14,style='italic')\n\nax1.legend(scatterpoints=1, fontsize =17,bbox_to_anchor=(2.2, 1.23), fancybox=True, ncol=5, handletextpad=0.1,columnspacing=0.3)\n\n\n#fig.savefig('Fig2.pdf', bbox_inches = 'tight')\nplt.show()\n\n```\n\n### Reducing the perception bias by asking the neighbors\n\nTo what extent and under what structural conditions can individuals reduce their perception\nbias? To address this question, we consider perception biases of\nindividuals and their neighbours. We aggregated each individual\u2019s\nown perception of frequency of different attributes (ego) with the\naveraged perceptions of the individual\u2019s neighbours. This is similar to *DeGroot\u2019s weighted belief formalization*.\n\n#### Degree growth of the minority and the majority (comparing analytical and numerical analysis)\n\n\n```python\nimport numpy as np \nimport matplotlib.pyplot as plt \nimport os, sys, inspect\nimport math\n\nplt.rcParams[\"font.family\"] = \"sans-serif\"\n\nfminor_list = [0.2]\n\nfig = plt.figure(figsize = (10,6))\nax1 = fig.add_subplot(1,2,1)\nax2 = fig.add_subplot(1,2,2)\n\n\ncmap = [ 'violet','yellowgreen']\nfor fi in range(len(fminor_list)) : \n\n    fminor = fminor_list[fi]\n    fa = fminor \n    fb = 1.-fminor \n\n    minor_data = np.loadtxt('perception_bias/images/Fig5/0hop_neterr_minor_fa%s.txt' %(fminor))\n    major_data = np.loadtxt('perception_bias/images/Fig5/0hop_neterr_major_fa%s.txt' %(fminor))\n\n    minorh = minor_data[:,0]\n    minor_neterr = minor_data[:,1]\n    minor_neterr_std = minor_data[:,2]\n\n    hop_minor_data = np.loadtxt('perception_bias/images/Fig5/1.0_hop_neterr_minor_fa%s_avg_sum.txt' %(fminor))\n    hop_major_data = np.loadtxt('perception_bias/images/Fig5/1.0_hop_neterr_major_fa%s_avg_sum.txt' %(fminor))\n\n    hop_y_min_mean = hop_minor_data[:,1]\n    hop_y_min_std = hop_minor_data[:,2]\n\n    '''Fig.5(a) for the minority ''' \n    ax1.axhline(y= 1, color = 'grey', ls = 'dashed')\n    ax1.plot(minorh, (minor_neterr)/fminor, marker = 'o', label = 'ego', color = cmap[0] , mec = 'black')\n    ax1.errorbar(minorh, (minor_neterr)/fminor, yerr = minor_neterr_std,  color = cmap[0] )\n    ax1.plot(minorh, (hop_y_min_mean)/fminor  , marker = '^', label = '1-hop weighted avg.' , color = cmap[1] , mec = 'black')\n    ax1.errorbar(minorh, (hop_y_min_mean)/fminor, yerr= hop_y_min_std  ,  color = cmap[1] )\n    ax1.xaxis.set_tick_params(labelsize=20)\n    ax1.yaxis.set_tick_params(labelsize=20)\n    ax1.set_xlabel(r'$h$', fontsize = 24)\n    ax1.set_ylabel(r'$P_{indv.}$', fontsize = 24)\n    ax1.legend(numpoints = 1, loc = 'best' ,fontsize = 20)\n\n\n\n    '''Fig.5(b) for the majority'''     \n    hop_y_maj_mean = hop_major_data[:,1]\n    hop_y_maj_std = hop_major_data[:,2]\n    majorh = major_data[:,0]\n    major_neterr = major_data[:,1]\n    major_neterr_std = major_data[:,2]\n    ax2.axhline(y= 1, color = 'grey', ls = 'dashed')\n    ax2.plot(majorh, (major_neterr)/fminor , marker = 'o', label = 'ego' , color = cmap[0] , mec = 'black')\n    ax2.errorbar(minorh, (major_neterr)/fminor, yerr = major_neterr_std,  color = cmap[0] )\n    ax2.plot(majorh, (hop_y_maj_mean)/fminor , marker = '^', label = '1-hop weighted avg.' , color = cmap[1] , mec = 'black')\n    ax2.errorbar(minorh, (hop_y_maj_mean)/fminor, yerr = hop_y_maj_std,  color = cmap[1] )\n    ax2.set_xlabel(r'$h$', fontsize = 24)\n    ax2.xaxis.set_tick_params(labelsize=20)\n    ax2.yaxis.set_tick_params(labelsize=20)\n\n    \n\nax1.xaxis.set_ticks(np.arange(0, 1.2, 0.2))\nax2.xaxis.set_ticks(np.arange(0, 1.2, 0.2))\n\nax1.text(0.28,5.1, '(a) Minority',fontsize = 20)\nax2.text(0.28,5.1, '(b) Majority',fontsize = 20)\n\nax1.legend(numpoints=1, fontsize =17,bbox_to_anchor=(1.6, 1.2), fancybox=True, ncol=5, handletextpad=0.1,columnspacing=0.3)\n\nplt.show()\n#plt.savefig('Fig5.pdf', bbox_inches = 'tight')\n\n```\n\n## Acknowledgments\n\nThe code for plotting perception biases are written by Dr. [Eun Lee](https://www.eunlee.net/).\n\n\n\n## Literature\nLee, E., Karimi, F., Wagner, C., Jo, H. H., Strohmaier, M., & Galesic, M. (2019). Homophily and minority-group size explain perception biases in social networks. Nature human behaviour, 3(10), 1078-1087.\n\nKarimi, F., G\u00e9nois, M., Wagner, C., Singer, P., & Strohmaier, M. (2018). Homophily influences ranking of minorities in social networks. Scientific reports, 8(1), 1-12.(https://www.nature.com/articles/s41598-018-29405-7)\n\nDeGroot, M. H. (1974). Reaching a consensus. Journal of the American Statistical Association, 69(345), 118-121.\n\nCentola, D. (2011). An experimental study of homophily in the adoption of health behavior. Science, 334(6060), 1269-1272.\n\nGalesic, M., de Bruin, W. B., Dumas, M., Kapteyn, A., Darling, J. E., & Meijer, E. (2018). Asking about social circles improves election predictions. Nature Human Behaviour, 2(3), 187-193.\n\n", "meta": {"hexsha": "afbe0501a0a81537abae37968476c8fc7dc18c4c", "size": 203729, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "perception_bias.ipynb", "max_stars_repo_name": "mannbach/homophilic_networks", "max_stars_repo_head_hexsha": "db18452109de84321f590953910badd61b932666", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-09-21T13:21:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T16:44:55.000Z", "max_issues_repo_path": "perception_bias.ipynb", "max_issues_repo_name": "mannbach/homophilic_networks", "max_issues_repo_head_hexsha": "db18452109de84321f590953910badd61b932666", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "perception_bias.ipynb", "max_forks_repo_name": "mannbach/homophilic_networks", "max_forks_repo_head_hexsha": "db18452109de84321f590953910badd61b932666", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-02-17T14:47:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T00:22:31.000Z", "avg_line_length": 428.0021008403, "max_line_length": 105044, "alphanum_fraction": 0.922828856, "converted": true, "num_tokens": 3534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.08632347423570948, "lm_q1q2_score": 0.036801561010399914}}
{"text": "# Python, numpy, and Nifti-images\n\nThis tutorial is about the programming language Python and how to use it for psychology/neuroimaging analysis. Part 2 of this tutorial is a quite extensive recap of basic Python syntax and constructs; this should be doable for students who are comfortable with programming (e.g., from previous experience with other programming languages). If you're *not* comfortable with programming, or you notice during this tutorial that you get stuck often, we recommend working through the [Codecademy](https://www.codecademy.com/learn/python) up to and including unit 8 (`loops`). You *don't* have to do the quizzes (because you need to pay for that).\n\nGiven that you have learned the basics of Python's syntax, this tutorial will recap some of the most important aspects of Python (section 2.: General Python). Then, 'numpy' (Python's scientific computing package) is discussed and explained and followed by a section on 'Matplotlib' (Python's plotting package). Finally, this tutorial ends with a section on how to interact with Nifti-files - the file format used by most (MRI) neuroimaging data.\n\n\n## What this tutorial is about\nThis tutorial will recap some of the most important aspects of Python (section 2: General Python). Then, 'numpy' (Python's numeric computing package) is discussed and explained and followed by a section on 'Matplotlib' (Python's plotting package). Finally, this tutorial ends with a section on how to work with Nifti-files - the file format used by most (MRI) neuroimaging software packages.\n\nAt the end of this tutorial, you are able to implement any computation/routine necessary for complex fMRI analysis using a combination of basic Python and Numpy.\n\n### Contents:\n\n1. Jupyter notebooks\n2. General Python\n3. Numpy\n4. Matplotlib / plotting\n5. Interacting with Nifti-files\n\nBut before anything else, let's get more familiar with the Jupyter notebook environment!\n\n## 1. Jupyter Notebooks\n\nSo, what are Jupyter notebooks, actually? Basically, using Jupyter notebooks is like using the web-browser as a kind of editor from which you can run Python code, similar to the MATLAB interactive editor or RStudio. The cool thing about these notebooks is that they allow you to mix code \"cells\" (see below) and text \"cells\" (such as this one). The (printed) output from code blocks are displayed right below the code blocks themselves. \n\nJupyter notebooks have two **modes**: edit mode and command mode.\n\n- *Command mode* is indicated by a grey cell border with a blue left margin (as is the case now!): When you are in command mode, you are able to edit the notebook as a whole, but not type into individual cells. Most importantly, in command mode, the keyboard is mapped to a set of shortcuts that let you perform notebook and cell actions efficiently (some shortcuts in command mode will be discussed later!). Enter command mode by pressing **Esc** or using the mouse to click outside a cell\u2019s editor area; <br><br>\n- *Edit mode* is indicated by a green cell border and a prompt showing in the editor area: When a cell is in edit mode, you can type into the cell, like a normal text editor. Enter edit mode by pressing Enter or using the mouse to double-click on a cell\u2019s editor area.\n\nWhen you're reading and scrolling through the tutorials, you'll be in the command mode mostly. But once you have to program (or write) stuff yourself, you have to switch to edit mode. But we'll get to that. First, we'll explain something about the two types of cells: code cells and text cells.\n\n### 1.1. Code cells\n\nCode cells are the place to write your Python code, similar to MATLAB 'code sections' (which are usually deliniated by %%). Importantly, unlike the interactive editors in RStudio and MATLAB, a code cell in Jupyter notebooks can only be run all at once. This means you cannot run it line-by-line, but you have to run the entire cell!\n\n#### 1.1.1. Running cells\nLet's look at an example. Below, you see a code-cell with two print-statements. To run the cell, select it (i.e., the cell should have a green or blue frame around it; doesn't matter whether you're in edit or command mode), and click on the \"&#9654; `Run`\" icon or press `ctr+Enter`). Try it with the cell below!\n\nYou can also try it with the cell way at the top where you entered your name and student number...\n\n\n```python\nprint(\"I'm printing Python code\")\nprint(3 + 3)\n```\n\n    I'm printing Python code\n    6\n\n\n(You might be confused because we use the `print` statement with brackets -- `print()` -- while you've learned in Codecademy that you should use `print` without brackets. This is because Codecademy uses an old version of Python, Python2.7, while we use a newer version, Python3.5. In the new version, `print()` should be used with brackets!)\n\n#### 1.1.2. Stop running/execution of cells\nSometimes, you might want to quit the execution of a code-cell because it's taking too long (or worse, you created an infinite loop!). To do so, click the stop icon &#9632; in the top menu!\n\n#### 1.1.3. Restarting the kernel\nSometimes, you accidentally 'crash' the notebook, for example when creating an infinite loop or when loading in too much data. You know your notebook 'crashed' when stopping the cell (&#9632;) does not work and your cell continues its execution, as evident by the `In [*]:` prompt next to the cell. In those cases, you need to completely restart the notebook, or in programming lingo: you need to \"restart the kernel\". To do so, click `Kernel` and `Restart`.\n\nImportantly, when you restart the kernel, it will keep all text/code that you've written, but it will **not** remember all the variables that you defined before restarting the kernel, including the imports. So if you restart the kernel, you will have to re-import everything (e.g. run `import numpy as np` again).\n\n#### 1.1.3. Inserting cells\nAs you can see in the code cell above, you can only run the entire cell (i.e. both print statements). Sometimes, of course, you'd like to organise code across multiple cells. To do this, you can simply add new blocks (cells) by selecting \"Insert --> Insert Cell Below\" on the toolbar (or use the shortcut ctr+B when you're in command mode; \"B\" refers to \"below\"). This will insert a new code cell below the cell you have currently highlighted (the currently highlighted cell has a blue box around it). \n\nTry inserting a cell below and write some code (e.g. `print(10 * 10)`).\n\n\n```python\nprint(\"ctrl + B doesn't work\")\n```\n\n    ctrl + B doesn't work\n\n\n#### 1.1.4. Inline plotting\nAnother cool feature of Jupyter notebooks is that you can display figures in the same notebook! You simply define some plots in a code cell and it'll output the plot below it.\n\nCheck it out by executing (click the \"play\" button or ctr+Enter) the next cell.\n\n\n```python\n# We'll get to what the code means later in the tutorial\nimport matplotlib.pyplot as plt # The plotting package 'Matplotlib' is discussed in section 3!\n\n# This command makes sure that the figure is plotted in the notebook instead of in a separate window!\n%matplotlib inline \n\n# Now, let's plot something\nplt.plot(range(10))\nplt.show()\n```\n\n### 1.2. Text ('markdown') cells\nNext to code cells, jupyter notebooks allow you to write text in so-called \"markdown cells\" (the cell this text is written in is, obviously, also a markdown cell). Markdown cells accept plain text and can be formatted by special markdown-syntax. A couple of examples:\n\n\\# One hash creates a large heading <br>\n\\#\\# Two hashes creates a slightly smaller heading (this goes up to four hashes)\n\nBold text can be created by enclosing text in \\*\\*double asterisks\\*\\* and italicized text can be created by enclosing text in \\*single asterisks\\*. You can even include URLs and insert images from the web; check this [link](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) for a cheatsheet with markdown syntax and options! All the special markdown-syntax and options will be converted to readable text *after running the text cell* (again, by pressing the \"play\" icon in the toolbar or by ctr+Enter).\n\nTo insert a text (markdown) cell, insert a new cell (\"Insert --> Insert Cell Below\" or ctr+B). Then, *while highlighting the new cell*, press \"Cell --> Cell Type --> Markdown\" on the toolbar on top of the notebook (or, while in command mode, press ctr+m; \"m\" refers to \"markdown\"). You should see the prompt (the **`In [ ]`** thingie) disappear. Voil\u00e0, now it's a text cell!\n\nTry it below! Insert a new markdown cell and try to write the following:\n\n\"**OMG**, this is th emost awesome Python tutorial *ever*.\"\n\n\"**OMG**, this is the most awesome Python tutorial *ever*.\"\n\n### 1.3. Getting help\nThroughout this course, you'll encounter situations in which you have to use functions that you'd like to get some more information on, e.g. which inputs it expects. To get help on any python function you'd like to use, you can simply write the function-name appended with a \"?\" and run the cell. This will open a window below with the \"docstring\" (explanation of the function). Take for example the built-in function **`len()`**. To get some more information, simply type `len?` in a code cell and run the cell.\n\nTry it out yourself: create a code cell below, type `len?` and check the output!\n\nIf this method (i.e. appending with \"?\") does not give you enough information, try to google the name of the function together with 'python' and, if you know from which package the function comes, the name of that package. For instance, for len() you could google: ['python len()'](http://lmgtfy.com/?q=python+len), or later when you'll use the numpy package, and you'd like to know how the `numpy.arange` function works you could google: 'python numpy arange'. \n\n** REMEMBER: Google is your friend! Please try to google things first, before you ask your classmates and your tutors! **\n\nThe online python community is huge, so someone definitely already wondered about something you might be struggling with.\n\n\n```python\nlen?\n```\n\n### 1.4. Saving your work & closing down the notebook\nYou're running and actively editing the notebook in a browser, but remember that it's still just a file located on your account on the server (that you're accessing through Jupyterhub). Therefore, for your work to persist, you need to save the notebook once in a while (and definitely before closing the notebook). To save, simply press the floppy-disk image in the top-left (or do ctr+s). If you want to close your notebook, simply close the browser. \n\n*However, when you close the browser, the notebook is still \"running\" in the background in your terminal where you started it!* \n\nTo stop the notebook from running after you've closed it, go to the `Running` tab, and click the `Shutdown` button next to the notebook that you want to stop. \n\nAlright. Now that you've had your first contact with Jupyter notebooks - let's talk about about exercises and assignments.\n\n## A note on exercises (ToDo/ToThink) and assignments\nYou'll encounter different types of exercises throughout the notebook, being:\n\n- <font color='orange'>ToDos</font> : short programming exercises, either zero or for a few points\n- <font color='blue'>ToThinks</font>: questions about the (preceding) text/material, either zero or for a few points\n- <font color='red'>Assignments</font>: a larger programming exercise (sometimes with additional questions), usually for a larger amount of points\n\nWe highly recommend doing/answering the ToDos/ToThinks, not only because they are worth points, but also because they are designed to improve your understanding of the material!\n\nAnyway, a \"ToDo\" would look something like this:\n\n<div class=\"alert alert-warning\">\n<b>ToDo</b> (0 points)\n</div>\nIn the code-cell below, set the variable `x` to 5 and remove the `raise AssertionError` statement below.\n\n\n```python\nx = 5\n```\n\n\n\n\n    5\n\n\n\nThen, *after* each code-cell corresponding to the ToDo, there are one or more code-cell(s) with \"tests\" written by us. These tests may provide you with feedback about whether you implemented the \"ToDo\" correctly, and optionally gives you some hints on how to solve your error(s). If you run this cell and you don't get any errors, you did it correctly and you'll receive the point(s) for that ToDo. If it gives any errors, try to use the information from the error and/or print statements to solve the ToDo. \n\nThese tests are usually implemented as a set of `assert` statements, which 'assert' whether a specific statement is true. If it evaluates to `False`, then that means you've made an error. For example, for the above `ToDo`, we simply evaluated the statement `assert(x == 5)` to check whether you set `x` to 5 correctly, as is shown in the cell below:\n\n\n```python\n''' Checks whether the above ToDo is correct. '''\ntry:\n    assert(x == 5)\nexcept AssertionError as e:\n    print(\"x does not evaluate to 5! Did you replace 'not yet 5' with 5?\")\n    raise(e)\nelse:\n    print(\"Well done!\")\n```\n\n    Well done!\n\n\n**Note**: each *ToDo* is explicitly tested, so you can always check your answer (and continue trying until you get it right). \n\nNow, let's try another one, but this time for real! It's a super simple one, so use this to earn a free point. Note that it is followed by two test-cells, which test different aspects of your implementation (each passed test gives you 0.5 points).\n\n<div class=\"alert alert-warning\">\n<b>ToDo</b> (1 point)\n</div>\nIn the code-cell below, set the variable `y` to `x * 2`, so you have to replace `None` with `x * 2` (yes, this is as easy as it sounds).\n\n\n```python\nx = 2\ny = x*2\n```\n\n\n```python\n''' This tests the above ToDo. '''\ntry:\n    assert(y == x * 2)\nexcept AssertionError as e:\n    print(\"y does not evaluate to x * 2 (i.e., 4)! Did you replace y with x * 2?\")\n    raise(e)\nelse:\n    print(\"Well done!\")\n```\n\n    Well done!\n\n\n\n```python\n''' This tests the above ToDo as well. '''\ntry:\n    assert(isinstance(y, int))\nexcept AssertionError as e:\n    print(\"y doesn't seem to be an integer (it is of type %s; make sure it is!\" % (type(y)))\n    raise(e)\nelse:\n    print(\"Well done!\")\n```\n\n    Well done!\n\n\nThroughout the notebook you'll encounter several 'ToDos' - some are worth points, some don't. In addition to these 'ToDos', you'll also encounter 'ToThinks', which are short questions about the material, meant to make you think about what you're doing. Like the 'ToDos', some of these are worth points, others don't. Each 'ToThink' cell is followed by a markdown-cell in which you can write your answer. Obviously, these answers cannot be automatically tested, so there won't be a test-cell with `asserts`. These 'ToThinks' are later (by us) graded manually. \n\nA typical 'ToThink' may look like this:  \n\n<div class='alert alert-info'>\n<b>ToThink</b> (1 point)\n</div>\nWhat's your name? Please write it in the text-cell below.\n\nAsh\n\nMake sure you actually write your name in the cell above for another free point! (You'll have to double-click the text-cell to go into 'edit mode' and replace 'YOUR ANSWER HERE' with your name.)\n\nNext to 'ToDos' and 'ToThinks', there are Assignments. These are basically just a collection of programming exercises and/or open questions, each with a certain amount of points associated with it. You'll encounter assignments usually at the end of a specific section. Usually, altogether these assignments are worth substantially more points than 'ToDos' or 'ToThinks'. \n\nAn assigment may look like this:\n\n<div class='alert alert-danger'>\n<b>Assignment</b> (5 points)\n</div>\nThis is an example assignment; it's not actually worth any points. In a real assignment, you would see one or more coding assignments or open questions below. \n\nAlright, by now you should known enough to start with section 2: a recap of basic Python syntax! (As we mentioned earlier, if you find this section too difficult, it might help to do the Codecademy Python course, up to and including section 8, before you go on!)\n\n## 2. General Python\nThis section will provide short tutorial on basic Python syntax and concepts (if you've done Codecademy, this should all be familiar).\n\nHere, we will cover:\n\n* Python data types (integers, floats, lists, dictionaries)\n* Python functions\n* Python classes\n* Conditionals (if-then-else)\n* Loops (for-loop, list-comprehensions)\n* Imports\n\n### 2.1. Structure of Python\n\nPython is a multipurpose programming language, meaning it can be used for almost anything. While R is mostly used for statistics, and php is used for web programming only, Python is a general language, specified by the packages you add on to it (using import statements). So, \"pure\" Python provides some basic functionality, but Python's versatility comes from specialized packages for almost any purpose. \n\nFor example:\n* the [scipy](https://www.scipy.org/) package provides functionality for scientific computing (e.g. statistics, signal processing);\n* the [numpy](http://www.numpy.org/) package provides data structures and functionality for (very fast) numeric computing (e.g. multidimensional numeric array computations, some linear algebra);\n* the [matplotlib](http://matplotlib.org/) package provides plotting functions;\n* and various specialied neuroimaging packages provide functionality to work and analyze (f)MRI (e.g. [nibabel](http://nipy.org/nibabel/) and [nipype](http://nipy.org/nipype)) and MEG/EEG (e.g. [MNE](http://www.martinos.org/mne/stable/index.html)).\n\nBasically, there are packages for everything you can think of (also: creating websites, game programming, etc.)! In this course, we will mostly use basic Python in combination with the scientific computing packages ('numpy', 'scipy') and specialized neuroimaging packages ('nibabel', 'nipype').  \n\n#### Import statements\nAs explained above, Python ships with some default functionality. This means that it's already available upon starting a notebook (or any other Python environment) and doesn't need to be imported. An example is the function `len()`.\n\n\n```python\nmy_list = [1, 2, 3]\nprint(len(my_list))\n```\n\n    3\n\n\nHowever, non-built-in packages - such as `numpy` - need to be explicitly imported to access their functionality. After importing, their functions are accessible as: `{package}.{function}`.\n\nFor example:\n\n\n```python\nimport numpy\n\n# Now you can access the numpy function `add()` as numpy.add()\nprint(numpy.add(5, 3)) \n```\n\n    8\n\n\nHowever, writing `numpy` in front of every function you access from it becomes annoying very quickly. Therefore, we usually abbreviate the package name by two or three characters, which can be achieved through:\n\n`import {package} as {abbreviation}` \n\nFor example, people usually abbreviate the numpy import as:\n\n\n```python\nimport numpy as np\n\n# Now you can access numpy functions such as 'add()' as:\nprint(np.add(5, 3))\n```\n\n    8\n\n\nThroughout the tutorials, you'll see different packages (e.g. nibabel and scipy) being imported using abbreviations. \n\nAlso, you don't need to import an *entire* package, but you can also import a specific function or class. This is done as follows:\n\n`from {package} import {function1}, {function2}, {etc}`\n\nAn example:\n\n\n```python\nfrom numpy import add, subtract\n\n# Now I can simply call add() and subtract()\nprint(add(5, 3))\n```\n\n    8\n\n\nNote that some packages have a hierarchical structure with subpackages (also called modules). For example, scipy has a subpackage `ndimage` (with functions for n-dimensional arrays). To import *only* this subpackage, do the following:\n\n\n```python\nfrom scipy import ndimage\n# Now you can call functions from the ndimage subpackage,\n# e.g. gaussian_filter\n\nprint(ndimage.gaussian_filter([10, 5, 4], 2))\n```\n\n    [6 6 5]\n\n\nNote that you can mix and match all of these operations to customize the import to your own liking (see cell below for such a fancy import). In this course, we'll usually just import entire packages (e.g. `import numpy as np`) or specific functions/subpackages (e.g. `from scipy import stats`). \n\n\n```python\n# a fancy import\nfrom scipy.stats import binom_test as omg_binomial_testing_so_cool\n\nprint(omg_binomial_testing_so_cool(0.5, 10))\n```\n\n    0.001953125\n\n\n<div class=\"alert alert-warning\">\n<b>ToDo</b> (1 point)\n</div>\n\nImport the function \"randn\" from the numpy subpackage \"random\" and rename it \"random_normal_generator\".\n\n\n```python\nfrom numpy.random import randn as random_normal_generator\n```\n\n\n```python\n''' Tests the above ToDo. '''\ntry:\n    assert('random_normal_generator' in dir())\nexcept AssertionError as e:\n    print(\"I couldn't find the function 'random_normal_generator'; did you spell it correctly?\")\n    raise(e)\nelse:\n    print(\"Well done!\")\n```\n\n    Well done!\n\n\n\n```python\n''' Another test for the above ToDo. '''\ntry:\n    assert(random_normal_generator.__name__ == 'randn')\nexcept AssertionError as e:\n    print(\"Your 'random_normal_generator' function does not point to the 'randn' numpy.random subpackage!\")\n    raise(e)\nelse:\n    print(\"Well done!\")\n```\n\n    Well done!\n\n\n#### Whitespace for indentation\nIn most programming languages, code blocks (e.g., if-else blocks, or for-loops) are delineated by dedicated symbols (often curly brackets, `{}`). For example, an if-else block in R is written like this:\n\n```\nif (x > 0) {\n   y = x + 5\n} else {\n   y = x - 5\n}\n```\n\nWhile in languages like R and MATLAB whitespace/indentation is used for readability, it is not necessary! The above if-else statement in R can also be written as:\n\n```\nif (x > 0) { y = x + 5 } else { y = x - 5 }\n```\n\nHowever, in Python, whitespace and indentation is important! In Python, indendation - instead of curly braces - delineates code blocks, and if code is incorrectly indented, Python will give an error! For example, an if-else statement in Python must be indented (always with 4 spaces or a tab). If you don't do this, it will give an error, as show below:\n\n\n```python\nx = 0\nif x < 0:\n    y = x + 5\nelse:\n    y = x - 5 \ny\n```\n\n\n\n\n    -5\n\n\n\nIf you make sure the two statements beginning with `y = ...` are indented with 4 spaces/a tab, the error disappears (try it yourself!).\n\n#### Python versions\nAs a side note: there are currently two different supported versions of Python, 2.7 and 3.6. Somewhat confusingly, Python 3.0 introduced many backwards-incompatible changes to the language, so code written for 2.7 may not work under 3.x and vice versa. For this class all code will use Python **3.6** (but 90% of this notebook should be compatible with Python 2.7., we think ...). So if you want to use code from this class on your own computer, make sure you use Python 3.6!\n\n### 2.2 Basic data types\n\"Pure\" (i.e. built-in) Python has mostly the same data types as you might know from MATLAB or R, such as numbers (integers/floats), strings, and lists (cells in MATLAB; lists in R). Also, Python has to data types that might be unknown to MATLAB/R users, such as \"dictionaries\" and \"tuples\", which are explained later. \n\n#### Numbers\nNumbers are represented either as integers (\"whole\" numbers) or floats (numbers with decimals, basically).\n\n\n```python\nx = 3 \nprint(x, type(x)) # use type(variable) to find out of what data-type something is!\n\ny = 3.15\nprint(y, type(y))\n```\n\n    3 <class 'int'>\n    3.15 <class 'float'>\n\n\nLet's try to apply arithmetic to x as defined above with some basic operations:\n\n\n```python\nprint(x + 1)   # Addition;\nprint(x - 1)   # Subtraction;\nprint(x / 2)   # Division;\nprint(x * 2)   # Multiplication;\nprint(x ** 2)  # Exponentiation;\n```\n\n    4\n    2\n    1.5\n    6\n    9\n\n\nThe above commands apply operations to x, but do not *change* x itself. To permanently change x, you have to store the results of the operation (e.g. `x + 1`) into a variable (e.g. `x2 = x + 1`), as shown in the cell below:\n\n\n```python\nx = 3\nx_new = x + 2\n\n# If you simply want to update an existing variable, you can do this in two ways:\nx = x + 1\n\n# ... or:\nx += 1\n\nprint(x)  \n\nx *= 2 # This is the same as: x = x * 2\nprint(x) \n```\n\n    5\n    10\n\n\n\n\n\n    5\n\n\n\n<div class=\"alert alert-warning\">\n<b>ToDo</b> (1 point) \n</div>\n\nIn the cell below, make a new variable, `y`, which should contain x minus 5 and subsequently raised to the 4th power. \n\n\n```python\nx = 8\ny = (x-5)**4\n# your solution here\ny\n```\n\n\n\n\n    81\n\n\n\n\n```python\n''' Tests the above ToDo.'''\n\n# Check if there exists a variable 'y'\ntry:\n    assert('y' in dir())\nexcept AssertionError as e:\n    print(\"The variable 'y' doesn't seem to exist! Did you name it correctly?\")\n    raise(e)\nelse:\n    print(\"Well done! 1 out of tests 2 passed\")\n\n# Check if it has the correct number\ntry:\n    assert(y == 81)\nexcept AssertionError as e:\n    print(\"The variable y does not seem to equal x minus 5, raise to the power 4.\")\n    raise(e)\nelse:\n    print(\"Well done! 2 out of tests 2 passed\")\n```\n\n    Well done! 1 out of tests 2 passed\n    Well done! 2 out of tests 2 passed\n\n\n#### Booleans\nPython implements all of the usual operators for comparisons. Similar to what you might know from other languages, '==' tests equivalence, '!=' for not equivalent, and '<' and '>' for larger/smaller than.\n\nCheck out some examples below:\n\n\n```python\na = 3\nb = 5\nis_a_equal_to_b = a == b\n\nprint(is_a_equal_to_b)\nprint(type(is_a_equal_to_b)) \n```\n\n    False\n    <class 'bool'>\n\n\nHowever, for Boolean logic, python doesn't use operators (such as && for \"and\" and | for \"or\") but uses special (regular English) **words**: \n\n\n```python\nbool_1 = 3 > 5 # False, because 3 is not greater than 5\nbool_2 = 5 == 5 # True, because, well, 5 is 5\n\nprint(bool_1 and bool_2)  # Logical AND, both have to be True\nprint(bool_1 or bool_2)   # Logical OR, either one of them has to be True\nprint(not bool_1)         # Logical NOT, the inverse of bool_1\nprint(bool_1 != bool_2)   # Logical XOR, yields True when bool_1 and bool_2 are not equal\n```\n\n    False\n    True\n    True\n    True\n\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (0 points)\n</div>\nMess around with booleans in the cell below. Try some more complex things, like: `not ((3 > 5) and not (5 < 2))`. \nDo you understand why the result is the way it is? Try to follow the logic in the sequence of statements (not graded, so no tests follow the code block).\n\n\n```python\n# Do your ToDo here:\na=(not((3>5) and not(5<2)))\nb=(1.5==1.5)\nc=(1.2!=1.3)\nprint(a*b)\nprint(type(a*b))\n\n\n```\n\n    1\n    <class 'int'>\n\n\n#### Strings\nStrings in Python are largely the same as in other languages.\n\n\n```python\nh = 'hello'   # String literals can use single quotes\nw = \"world\"   # or double quotes; it does not matter.\n\nprint(h)\nprint(len(h))  # see how many characters in this string\n```\n\n    hello\n    5\n\n\nA very nice feature of Python strings is that they are easy to concatenate: just use '+'!\n\n\n```python\nhw = h + ', ' + w + '!' # String concatenation\nprint(hw)\n```\n\n    hello, world!\n\n\nYou can also create and combine strings with what is called 'string formatting'. This is accomplished by inserting a placeholder in a string, that you can fill with variables. An example is given below:\n\n\n```python\n# Here, we have a string with a placeholder '%s' (the 's' refers to 'string' placeholder)\nmy_string = 'My favorite programming language is: %s'\nprint('Before formatting:')\nprint(my_string)\n\n# Now, to 'fill' the placeholder, do the following:\nmy_fav_language = 'Python'\nmy_string = 'My favorite programming language is: %s' % my_fav_language\n\nprint('After formatting')\nprint(my_string)\n\nmy_blank = 'test'\nmy_fav_language = 'Python'\nmy_string = 'My favorite programming %s language is: %s' % (my_fav_language, my_blank)\n\nprint('After formatting')\nprint(my_string)\n```\n\n    Before formatting:\n    My favorite programming language is: %s\n    After formatting\n    My favorite programming language is: Python\n    After formatting\n    My favorite programming Python language is: test\n\n\nYou can also use specific placeholders for different data types:\n\n\n```python\nweek_no = 1 # integer\nstring1 = 'This is week %i of neuroimaging' % week_no # the %i expects an integer!\nprint(string1)\n\nproject_score = 99.50 # float\nstring2 = 'I will get a %f on my midterm exam!' % project_score\nprint(string2)\n\n# You can also combine different types in a string:\nstring3 = 'In week %i of neuroimaging, %s will get a %f for my lab-assignment' % (week_no, \"I\", 95.00)\nprint(string3)\n```\n\nFor a full list of placeholders see https://docs.python.org/2/library/stdtypes.html#string-formatting-operations\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nUsing the variable `to_print` defined below, print the string:\n\n\"Neuroimaging will be my favorite course 4ever\"\n\nSo you'll have to \"fill\" the \"%\" placeholders using string formatting.\n(This is a manually graded answer, so no tests!)\n\n\n```python\nto_print = \"%s will be my favorite course %iever\"\n# print the to_print variable, with the appropriate string formatters!\nto_print = '%s will be my favorite course %iever' % ('Neuroimaging', 4)\nprint(to_print)\n```\n\n    Neuroimaging will be my favorite course 4ever\n\n\n#### Lists\nA list is the Python equivalent of an array, but can be resized and can contain elements of different types. It is similar to a list in R and a cell in MATLAB. Note that indices in python start with 0! This means that the 3rd element of the list below is accessed through `[2]`.\n\nLet's check out some lists and how to index them!\n\n\n```python\n# Note that list may contain numbers ...\nlist1 = [3, 1, 2]\n\n# ... or strings\nlist2 = ['hello', 'world']\n\n# ... or, actually, anything at all! List lists themselves\nlist3 = ['hello', [3, 1, 2], 'world', 5.3, -999]\nlist3[0]\n```\n\n\n\n\n    'hello'\n\n\n\nWhatever the contents of a list, they are indexed the same way: using square brackets with an integer, e.g. `[0]`:\n\n\n```python\nprint('The first element of list1 is: %i' % list1[0])\nprint('The second element of list2 is: %s' % list2[1])\nprint('The last element of list3 is: %i' % list3[-1])\nprint('The second-to-last element of list3 is: %f' % list3[-2])\n```\n\n    The first element of list1 is: 3\n    The second element of list2 is: world\n    The last element of list3 is: -999\n    The second-to-last element of list3 is: 5.300000\n\n\nNote that you can also use negative indices! Negative indices start indexing from the end of the list, so `[-1]` indexes the last element, `[-2]` indexes the second-to-last element, etc.\n\nWe cannot only 'extract' element from lists using indexing, but we can also replace them! This works as follows:\n\n\n```python\nsome_list = [1, 2, 3, ['A', 'B', 'C']]\n\n# Let's set the first element of some_list to 100:\nsome_list[0] = 100\nprint(some_list)\n\n# Note that indexing a list within a list is done with sequential square brackets,\n# so if we want to index the element 'A' in some_list, we do:\nsome_list[-1][0] = 'ANOTHER STRING'\nprint(some_list)\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nIn the cell below, replace the element 'TO_REPLACE_1' with 'REPLACED' and the element 'TO_REPLACE_2' also with 'REPLACED' in the list `todo_list`.\n\n\n```python\ntodo_list = [1, 'B', 'TO_REPLACE_1', [5, 3, 1038, 'C'], [1, 3, 5, [9, 3, 1, 'TO_REPLACE_2']]]\n\n# your solution here\ntodo_list[2]='REPLACED'\ntodo_list[4][3][3]='REPLACED'\nprint(todo_list)\n```\n\n    [1, 'B', 'REPLACED', [5, 3, 1038, 'C'], [1, 3, 5, [9, 3, 1, 'REPLACED']]]\n\n\n**Note**: the code-cell below as usual tests your ToDo, but we haven't written out the tests in the cell itself. Instead, we wrote the tests in a separate Python module (a file with a collection of functions, objects, etc.), which we import here. (We do this, because writing out the tests here would give you the answer rightaway!)\n\n\n```python\n''' Tests the above ToDo with a custom function. '''\n# Below, we import all our tests (*) \nfrom tests import *\ntest_list_indexing(todo_list)\n```\n\n    Well done!\n\n\nIn addition to accessing list elements one at a time, Python provides concise syntax to access specific parts of a list (sublists); this is known as **slicing**. \n\nLet's look at some slice operations:\n\n\n```python\nnums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nprint(nums)         # Our original list\n\n# Get a slice form index 2 to 4 (exclusive); prints \"[2, 3]\"\nprint(nums[2:4])    \n\n# Get a slice from index 2 to the end; prints \"[2, 3, 4, 5, 6, 7, 8, 9]\"\nprint(nums[2:])  \n\n# Get a slice from the start to index 2 (exclusive); prints \"[0, 1]\"\nprint(nums[:2])     \n\n# Get a slice of the whole list; prints [\"0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\"\nprint(nums[:])\n\n# Slice indices can be negative; prints [\"0, 1, 2, 3, 4, 5, 6, 7, 8]\",\n# so everything up to (but not including) the last element\nprint(nums[:-1])    \n```\n\n    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n    [2, 3]\n    [2, 3, 4, 5, 6, 7, 8, 9]\n    [0, 1]\n    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n    [0, 1, 2, 3, 4, 5, 6, 7, 8]\n\n\nApart from the syntax `[from:to]`, you can also specify a \"stride\" (sort of step-size) of your slice using the syntax `[from:to:stride]`:\n\n\n```python\n# Return values in steps of 2\nprint(nums[::2])    \n\n# Returns values in steps of 3, but starting from the second element\nprint(nums[1::3])   \n```\n\nWith 'normal' indexing of lists, you can only index a subsequently set/replace one element at the time. With slices, however, you can set multiple elements at the same time:\n\n\n```python\nnums[2:4] = [100, 200] # Assign a new sublist to a slice\nprint(nums)         # Prints \"[0, 1, 100, 200, 4, 5, 6, 7, 8, 9]\"\n```\n\nImportantly, slicing in Python is \"end exclusive\", which means that the last index in your slice is not returned. Thus ...\n\n`nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nnums[0:5]` \n\n... returns 0 up till and including 4 (not 5!).\n\nCheck it out below:\n\n\n```python\nnums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nprint(nums[0:5])\n```\n\n<font color='blue'><b>Tip</b></font>: instead of creating sequential lists like:\n\n`num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]`\n\n... we can also create a list using the syntax: \n\n`num = list(range(starting_point, exclusive_end_point))`\n\nFor example, to create a list from 5 to 15, use the following:\n\n`num = list(range(5, 16))` \n\nWe'll use this construction (`list(range(x, y))`, or without the `list`) quite often in this course!\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nFrom the list (`my_list`) below, extract the numbers 2, 3, 4, 5, and 6 using a slice and store it in a new variable named `my_new_list`!\n\n\n```python\nmy_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n# your solution here\nmy_new_list = my_list[1:6]\n```\n\n\n```python\navailable_vars = dir()\nif 'my_new_list' not in available_vars:\n    raise ValueError(\"You did not store the results in a new variable caleld 'my_new_list'!\")\n    \ntest_slicing_1(my_new_list)\n```\n\n    Well done!\n\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point) \n</div>\nFrom the list below (`my_list_2`), extract the values `[5, 7, 9, 11]` using a slice (i.e., in a single operation!) and store it in a new variable named `my_new_list_2`.\n\n\n```python\nmy_list_2 = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21]\n\n# your solution here\nmy_new_list_2 = my_list_2[2:6]\nmy_list_2\n```\n\n\n```python\navailable_vars = dir()\n\nif 'my_new_list_2' not in available_vars:\n    raise ValueError(\"You didn't define the variable 'my_new_list_2'!\")\n\ntest_slicing_2(my_new_list_2)\n```\n\n    Well done!\n\n\n**NOTE**: you can index *strings* the same way as you index lists! Try to see it this way: a string is, quite literally, a *string* (\"list\") of characters. So, to get the first letter of some string s (e.g, 'this is a string'), you simply write: `s[0]`. To get first 5 characters, you write `s[:5]`, etc etc. Remember this!\n\n#### Dictionaries\nDictionaries might be new for those who are used to MATLAB or R. Basically, a dictionary is an **unordered** list in which list entries have a name (which is also referred to as a \"key\"). To get a value from a dictionary, you have to use the \"key\" as index instead of using an integer.\n\nLet's check out such a dictionary and how to index it. We build a dictionary using the following syntax: \n\n`{some_key: value, another_key: another_value, etc: etc}`\n\nThe keys can be anything! Strings, integers, lists ... doesn't matter! Mostly, though, strings are used as keys. \nSo, let's look at an example:\n\n\n```python\nmy_dict = {'cat': 'cute', 'dog': 'furry'}  # Create a new dictionary with some data\n```\n\nTo index a dictionary, we'll use square brackets `[]` again, just like with lists. But now, we can index using the key!\n\n\n```python\nindexed_value = my_dict['cat']\nprint(indexed_value)\n```\n\nAdding new key-value pairs to dictionaries is easy! Just index it with a new key, and assign the value to it:\n\n\n```python\nmy_dict['fish'] = 'wet'     # Set an entry in a dictionary\nprint(my_dict['fish'])      # Prints \"wet\"\n```\n\nLike a list, an entry in a dictionary can be of any data type:\n\n\n```python\nmy_dict['rabbit'] = ['omg', 'so', 'cute']\nprint(my_dict['rabbit'])\n```\n\nIf you try to 'index' a dictionary with a key that doesn't exist, it raises a \"KeyError\", which means you're trying to index something that doesn't exist:\n\n\n```python\nprint(my_dict['monkey'])\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nIn the code cell below, add a new key to the dictionary `my_dict` named `\"rat\"` and with the value `\"nasty\"`.\n\n\n```python\n# Add the key-value pair here!\n\n# your solution here\n\n```\n\n\n```python\n''' Tests the above ToDo. '''\n\ntry:\n    assert('rat' in my_dict)\nexcept AssertionError as e:\n    print(\"There exists no key 'rat' in my_dict!\")\n    raise(e)\n\ntry:\n    assert(my_dict['rat'] == 'nasty')\nexcept AssertionError as e:\n    print(\"The value of key 'rat' is '%s' and NOT 'nasty'\" % my_dict['rat'])\n\nprint('Well done!')\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nValues of dictionaries can be any type of object, even dictionaries themselves! So, add a new key to the dictionary `my_dict` named `\"another_dict\"` with the value of *another* dictionary with the keys `\"a\"` and `\"b\"` and the corresponding values `1` and `2`. Also, try to figure out how to index the value `1` from the 'nested' dictionary (this is not graded, but try it nonetheless!).\n\n\n```python\n# Do the ToDo here\n\n\n```\n\n\n```python\n''' Tests the above ToDo. '''\n\ntry:\n    assert('another_dict' in my_dict)\nexcept AssertionError as e:\n    print(\"There exists no key 'another_dict' in my_dict!\")\n    raise(e)\n\ntry:\n    assert(my_dict['another_dict']['a'] == 1)\n    assert(my_dict['another_dict']['b'] == 2)\nexcept AssertionError as e:\n    print(\"The key 'another_dictionary' should contain a dictionary with keys 'a' and 'b', corresponding\"\n          \"to values 1 and 2, respectively.\")\n    raise(e)\n\nprint('Well done!')\n```\n\n#### tuples\nTuples are very much like lists, but the main difference is that they are immutable. In other words, after creating them, they cannot be modified (their values cannot be replaced/altered):\n\n\n```python\n# A list can be modified ...\nmy_list = [1, 2, 3]\nmy_list[0] = 0\nprint(my_list)\n```\n\n\n```python\n# ... but a tuple cannot.\nmy_tuple = (1, 2, 3)\nprint(my_tuple[0]) # you can print parts of tuple ...\nmy_tuple[0] = 0   # but you cannot modify it!\n```\n\nYou probably won't use tuples a lot, but you might come across them when using and writing functions (but more about that in the next section!).\n\n\n```python\ndef my_epic_function(integer):\n    \n    return integer, integer * 2\n\noutputs = my_epic_function(10)\nprint(outputs)\nprint(type(outputs))\n\n# also, you can unpack tuples (and also lists) as follows:\noutput1, output2 = outputs\nprint(output2)\n```\n\n### 2.3 Functions and methods\n\nIf you followed the Codecademy tutorial, you are familiar with the basic syntax of functions in Python; if you're familiar with other programming languages, you'll see that the syntax of Python functions is quite similar to what you're used to.\n\nA function definition in Python starts with the keyword `def`, followed by the function name and round brackets with the arguments to the function, and finally the contents of the function, like so (note the indentation with four spaces/tab!!!):\n\n```\ndef my_awesome_function(arg_1, arg_2):\n    print(\"Argument 1: %s\" % arg_1)\n    print(\"Argument 2: %s\" % arg_2)\n```\n\nThis dummy-function above prints some stuff, but does not **return** something. Similar to R (but unlike MATLAB), you have to explicitly state what you want to **return** from the function by the \"return\" statement. \n\nSo, suppose you have a function that adds 2 to any number. Let's define it as follows (you have to run the cell to let Python know you've defined this function):\n\n\n```python\ndef add_2_to_a_number(some_number):\n    new_number = some_number + 2\n```\n\nHere, we omitted a **return** statement to return the value of `new_number`. This is a problem, because in Python (like most languages) you cannot 'peek' inside the function after using it! You can only access whatever is returned. \n\nSo, in the function defined above, we cannot access the value of `new_number`, because we didn't return it:\n\n\n```python\n# This will give an error!\nadd_2_to_a_number(5)\nprint(new_number)\n```\n\nSo, to access the *value* of `new_number` (that is, *not* `new_number` itself, but its associated value), we need to return it:\n\n\n```python\ndef add_2_to_a_number_fixed(some_number):\n    new_number = some_number + 2\n    return new_number\n```\n\n\n```python\nvalue_contained_in_new_number = add_2_to_a_number_fixed(5)\nprint(\"Results of function 'add_2_to_a_number' with argument '5': %i\" % value_contained_in_new_number)\n```\n\nImportantly, you can name the variable to which you assign the return value *anyway you like*. This doesn't have to be `new_number`! Like above, we named it `value_contained_in_new_number`, but it really doesn't matter.\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 points) \n</div>\nIn the code cell below, we've started writing a function named `extract_last_element` that takes one input-argument - a list - and returns the last element of the list. Some parts of the function are missing, though, which you need to write! When you're done, run the test-cell below it to check if it's right!\n\n\n```python\ndef extract_last_element(input_list):\n    \n    # your solution here\n    \n```\n\n\n```python\ntry:\n    assert(extract_last_element(input_list=[0, 1, 2]) == 2)\nexcept AssertionError as e:\n    print(\"Your function fails for input [0, 1, 2]\")\n    raise(e)\n\ntry:\n    assert(extract_last_element(input_list=[0]) == 0)\nexcept AssertionError as e:\n    print(\"Your function fails for input [0]\")\n    raise(e)\n\ntry:\n    assert(extract_last_element(input_list=['string1', 'string2', 'string3']) == 'string3')\nexcept AssertionError as e:\n    print(\"Your function fails for input ['string1', 'string2', 'string3']\")\n    raise(e)\n\nprint(\"Well done!\")\n```\n\nAlright, that was probably relatively easy. Let's do a slightly harder one.\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point) \n</div>\nWrite a completely new function named `get_values_from_odd_indices` (so you have to write the `def ...` part!) that takes one input-argument - a list - and returns all values from the odd indices of that list. So, suppose you have a list:\n\n`[2, 100, 25, 48, 92, -5, 12]`\n\n... your function should return: \n\n`[100, 48, -5]`\n\n... i.e, the values from odd indices (here: 1, 3, 5; we exclude index zero!)\n\nHint: slices might be useful here!\n\nWhen you're done, run the test-cell below it to check if it's right!\n\n\n```python\n# Implement your function (called get_values_from_odd_indices) here:\n\n\n```\n\n\n```python\n''' Tests the ToDo above. '''\ntry:\n    assert('get_values_from_odd_indices' in dir())\n    assert(callable(get_values_from_odd_indices))\nexcept AssertionError as e:\n    print(\"Your function 'get_values_from_odd_indices' does not seem to exist!\")\n\ntry:\n    out = get_values_from_odd_indices([0, 1, 2])\n    if out is None:\n        msg = \"ERROR: did you forget the Return statement?\"\n        raise ValueError(msg)\nexcept ValueError as e:\n    raise(e)\n    \nprint(\"Well done (also run the next cell with tests)!\")\n```\n\n\n```python\n''' Some other tests for the ToDo above. '''\ninp = [0, 1, 2]\noutp = get_values_from_odd_indices(inp)\nans = [1]\ntry:\n    assert(outp == ans)\nexcept AssertionError as e:\n    print(\"Your function returned '%r' but I expected '%r'\" % (outp, ans))\n    raise(e)\n\ninp = [5, 7, 9, 11, 13, 15, 18, 20, 21]\noutp = get_values_from_odd_indices(inp)\nans = [7, 11, 15, 20]\ntry:\n    assert(outp == ans)\nexcept AssertionError as e:\n    print(\"Your function returned '%r' but I expected '%r'\" % (outp, ans))\n    raise(e)\n\nprint(\"Well done!\")\n```\n\n**IMPORTANT**: it is possible to return *multiple things* from a function. The function, then, returns these things as a tuple, which can subsequently be \"unpacked\". Let's check out an example using a custom function called `minmax_of_list` which returns both the minimum and maximum of a list:\n\n\n```python\ndef minmax_of_list(some_list):\n    ''' Returns both the minimum and maximum of a list.\n    \n    Parameters\n    ----------\n    some_list : a Python list\n    \n    Returns\n    -------\n    min_value : a float or int\n        The minimum of a list\n    max_value : a float or int\n        The maximum of a list\n    '''\n    min_value = min(some_list)\n    max_value = max(some_list)\n    \n    return min_value, max_value\n```\n\nAs you can see, returning multiple things is a simple as adding more variables after the `return` statement, separated by commas. If we now call the function with a particular list, it gives us back a tuple of size 2 (one value for the minimum, one value for the maximum):\n\n\n```python\noutput_from_function = minmax_of_list([0, 1, 2, 3])\nprint(output_from_function)\nprint(type(output_from_function))\n```\n\nWe can now \"unpack\" the tuple (i.e., extract the separate values) in several ways. One way is to simply index the values:\n\n\n```python\noutput_from_function = minmax_of_list([0, 1, 2, 3])\nminimum = output_from_function[0]\nprint(\"Minimum: %i\" % minimum)\n\nmaximum = output_from_function[1]\nprint(\"Maximum: %i\" % maximum)\n```\n\nAlternatively, we can already \"extract\" one value, let's say the maximum (index 1 of the tuple) right after calling the function, so we can skip dealing with the tuple altogether:\n\n\n```python\nmaximum = minmax_of_list([0, 1, 2, 3])[1]  # The [1] extracts the maximum from the output of the function immediately!\nprint(\"Maximum: %i\" % maximum)\n```\n\nKeep this feature of returning multiple things and tuple unpacking in mind for the rest of the course (you'll definitely encounter it more often!).\n\n#### Methods\nHowever, in Python, functions are not the only things that allow you to 'do' things with data. In others' code, you'll often see function-like expressions written with periods, like this: `some_variable.function()`. These `.function()` parts are called 'methods', which are like functions 'inherent' to a specific type of object. In other words, it is a function that is applied to the object it belongs to. \n\nDifferent type of objects in Python, such as stings and lists, have their own set of methods. For example, the function you defined above (`extract_last_element()`) also exists as a method each list has, called `pop()`! (This is a builtin, standard, method that each list in Python has.) See for yourself in the block below.\n\n\n```python\nmy_list = [0, 5, 10, 15] \nprint(my_list.pop())\n\n# You can also just do the following (i.e. no need to define a variable first!):\nprint([0, 5, 10, 15].pop())\n\n# ... which is the same as:\nprint(extract_last_element([0, 5, 10, 15]))\n```\n\nNot only lists, but also other data-types (such as strings, dictionaries, and, as we'll see later, numpy arrays) have their own methods. How methods work exactly is not really important (this belongs to the topic of 'object-oriented programming'), but it is necessary to know **what** it does, as you'll see them a lot throughout this course. \n\nWe'll show you a couple of (often-used) examples:\n\n\n```python\n# For lists, we have .append()\nx = [0, 10, 15]\nx.append(20) # Add a new element to the end of the list using the append() method!\nprint(x)\n```\n\n**Note**: sometimes, methods modify the object (above: `x`) *in-place*, which means that the method does not return anything, so you don't have to assign it to a new variable. If you accidentally do this, the new object's value is `None`, as you see below: \n\n\n```python\nx = [0, 10, 15]\nx_new = x.append(20)\nprint(x_new)\n```\n\nSome often-used methods for dictionaries:\n\n\n```python\nmy_dict = {'a': 0, 'b': 1, 'c': 2}\n\n# The .values() method returns all the values of the dictionary \nprint(list(my_dict.values()))\n\n# And the .keys() method returns all the keys of the dictionary\nprint(list(my_dict.keys()))\n```\n\n**Note**: these dictionary-methods actually *do* return values! \n\nSome often-used methods for strings:\n\n\n```python\nmy_string = 'neuroimaging is fun!'\n\n# The .upper() method returns the string in uppercase!\nprint(my_string.upper())\n\n# The .count(substring) method returns the number of times a substring occurs in a string\nprint(my_string.count('n'))\n\n# The .replace(old, new) method replaces substrings\nprint(my_string.replace('fun', 'awesome'))\n\n# The .split(separator) splits a string into subparts (returned as a list)\nprint(my_string.split(' '))  # split by whitespace\n```\n\n#### Default arguments in functions/methods\nImportantly, and unlike most (scientific) programming languages, Python supports the use of 'default' arguments in functions. Basically, if you don't specify an optional argument, it uses the default:\n\n\n```python\ndef exponentiate_number(number, power=2):\n    return number ** power\n\nprint(exponentiate_number(2)) # now it uses the default!\nprint(exponentiate_number(2, 10)) # now it \"overwrites\" the default and uses power=10\nprint(exponentiate_number(number=2, power=10)) # also note that you can 'name' arguments \n```\n\n### 2.4 If-statements\nIf-elif-else statements in Python are quite straightforward. An example:\n\n\n```python\nx = 5\n\nif x > 0:\n    print('x is larger than 0')\nelif x < 0:\n    print('x is smaller than 0')\nelse:\n    print('x must be exactly 0!')\n```\n\nIf-statements contain at least an `if` keyword, but optionally also one or more `elif` (\"else if\") statements and an optional `else` statement. We'll practice this (in a `ToDo`) after the section on Loops.\n\n### 2.4 Loops\nLoops in Python (for- and while-loops) are largely similar to MATLAB and R loops, with some minor differences in  their syntax:\n\n\n```python\nanimals = ['cat', 'dog', 'monkey']\nfor animal in animals:\n    print(animal)\n```\n\nBasically, each data type that is also an \"iterable\" (something that you can iterate over) can be used in loops, including lists, dictionaries, and tuples.\n\n\n```python\n# An example of looping over a list\nmy_list = [1, 2, 3]\nfor x in my_list:\n    print(x)\n```\n\nMATLAB users might be used to looping over indices instead of the actual list values, like the following:\n\n```\nfor i=1:100\n    disp(some_list(i));\nend```\n\nIn Python, however, you loop (by default) over the contents of a list:\n\n```\nfor entry in some_list:\n    print(entry)\n```\n    \nIf you want to access for the value **AND** the index, you can use the built-in `enumerate` function:\n\n\n```python\nmy_list = ['a', 'b', 'c']\nfor index, value in enumerate(my_list):\n    \n    print('Loop iteration number (index) = %i, value = %s' % (index, value))\n\n# Don't forget that Python indexing starts at zero!\n```\n\n\n```python\n# Looping over a tuple (exactly the same as looping over a list)\nmy_tuple = (1, 2, 3)\nfor x in my_tuple:\n    print(x)\n```\n\n\n```python\n# Iterating over a dictionary can be done in a couple of ways!\nmy_dict = {'a': 1, 'b': 2, 'c': 3}\n\n# Looping over the keys ONLY\nfor key in my_dict:\n    print(key)\n```\n\n\n```python\n# Looping over both the keys and the entries\nfor key, entry in my_dict.items():\n    print(key, entry)\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (2 points) \n</div>\nComplete the function below - named `extract_values_smaller_than_0` - that takes a single list with numbers as input and returns a new list with *only the values smaller than 0* from the input-list. For example, suppose our input-list is:\n\n```\n[2, -5.3, 1.8, 0.0, -205.1, 6029]\n```\n\n... the function should return:\n\n```\n[-5.3, -205.1]\n```\n\nHint: use an if-statement in combination with the `.append()` method of the empty list we initialized below (`list_to_return`) to fill the `list_to_return` variable in a for-loop. In other words, the function should contain an if-statement in a for-loop (in which you need to use the `.append()` method).\n\n\n```python\n# Complete the function below (make sure to remove raise NotImplementedError!)\ndef extract_values_smaller_than_0(input_list):\n    \n    # We initialize an empty list here (which you need to fill using a for-loop)\n    list_to_return = []\n    \n    # your solution here\n\n    \n    return list_to_return\n```\n\n\n```python\n''' Tests the ToDo above. '''\ninp = [-5, 2, 3, -8]\noutp = extract_values_smaller_than_0(inp)\nans = [-5, -8]\ntry:\n    assert(outp == ans)\nexcept AssertionError as e:\n    print(\"Your function  with input '%r' returned '%r', but I expected '%r'\" % (inp, outp, ans))\n    raise(e)\n    \ninp = [0, 2, -3]\noutp = extract_values_smaller_than_0(inp)\nans = [-3]\ntry:\n    assert(outp == ans)\nexcept AssertionError as e:\n    print(\"Your function  with input '%r' returned '%r', but I expected '%r'\" % (inp, outp, ans))\n    raise(e)\n\ninp = [0, 0, 0]\noutp = extract_values_smaller_than_0(inp)\nans = []\ntry:\n    assert(outp == ans)\nexcept AssertionError as e:\n    print(\"Your function  with input '%r' returned '%r', but I expected '%r'\" % (inp, outp, ans))\n    raise(e)\n\nprint(\"Well done!\")\n```\n\n#### Advanced loops: list comprehensions\nSometimes, writing (and reading!) for-loops can be confusing and lead to \"ugly\" code. Wouldn't it be nice to represent (small) for-loops on a single line? Python has a way to do this: using what is called `list comprehensions`. It does exactly the same thing as a for-loop: it takes a list, iterates over its entries (and does something with each entry), and (optionally) returns a (modified) list. \n\nLet's look at an arbitrary example of a for-loop over a list:\n\n\n```python\nnums = [0, 1, 2, 3, 4]\n\n# Also, check out the way 'enumerate' is used here!\nfor index, x in enumerate(nums):\n    nums[index] = x ** 2\n\nprint(nums)\n```\n\nYou can make this code simpler using a list comprehension:\n\n\n```python\nnums = [0, 1, 2, 3, 4]\nsquares = [x ** 2 for x in nums] # importantly, a list comprehension always returns a (modified) list!\nprint(squares)\n```\n\nAlso, list comprehensions may contain if-statements!\n\n\n```python\nstring_nums = ['one', 'two', 'three']\nstarts_with_t = ['yes' if s[0] == 't' else 'no' for s in string_nums]\nprint(starts_with_t)\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (0 points; optional)\n</div>\nWrite a list comprehension that adds the string '\\_check' to each value in the list `my_list` below, except if the value is 'B'. (This is an optional ToDo to practice list comprehensions.)\n\n\n```python\nmy_list = ['A', 'B', 'C', 'D']\n# Implement your list comprehension here!\n\n\n```\n\nList comprehensions are somewhat of a more advanced Python concept, so if you don't feel comfortable using them (correctly) in your future assignments, use regular for-loops by all means! In the upcoming tutorials, though, we'll definitely use them, so make sure you understand what they do!\n\n## 2. Numpy\nThis section is about Numpy, Python's core library for numeric computing. While the syntax of basic Python (as we've gone over in the previous section) is important to do neuroimaging analysis in Python, knowing numpy is **essential**. Basicially, Numpy is the go-to package whenever you want to do (anything related to) data analysis in Python. Make sure you understand what is going on in this section, as the rest of the course will feature a lot of Numpy-code!\n\nThe most important feature of Numpy is it's core data structure: the numpy *ndarray* (which stands for *n*-dimensional array, referring to the fact that the array may be of any dimension: 1D, 2D, 3D, 180D ... *n*D). This is, just like basic lists/dictionaries/integers/tuples, a data structure with its own syntax, operations, and methods, as we will explain below.\n\n### Python lists vs. numpy arrays\nBasically, numpy arrays are a lot like Python lists. The major difference, however, is that **numpy arrays may contain only a single data-type**, while Python lists may contain different data-types within the same list.\n\nLet check this out:\n\n\n```python\n# Python lists may contain mixed data-types: an integer, a float, a string, a list\npython_list = [1, 2.5, \"whatever\", [3, 4, 5]] \n\nfor value in python_list:\n    \n    print(\"%s is a: %s\" % (str(value), type(value)))\n```\n\nUnlike Python lists, numpy only allows entries of the same data-type. This difference between Python lists and numpy arrays is basically the same as R lists (allow multiple data-types) versus R matrices/arrays (only allow one data type), and is also the same as MATLAB cells (allow multiple data-types) versus MATLAB matrices (only allow one data type).\n\nIn fact, if you try to make a numpy array with different data-types, numpy will force the entries into the same data-type (in a smart way), as is shown in the example below:\n\n\n```python\n# Importantly, you often specify your arrays as Python lists first, and then convert them to numpy\nto_convert_to_numpy = [1, 2, 3.5]               # specify python list ...\nnumpy_array = np.array(to_convert_to_numpy)     # ... and convert ('cast') it to numpy\n\nfor entry in numpy_array:\n    \n    print(entry)\n    print('this is a: %s \\n' % type(entry))\n```\n\nAs you can see, Numpy converted our original list (to_convert_to_numpy), which contained both integers and floats, to an array with only floats! You might think that such a data structure that only allows one single data type is not ideal. However, the very fact that it only contains a single data-type makes operations on numpy arrays extremely fast. For example, loops over numpy arrays are often way faster than loops over python lists. This is because, internally, Python has to check the data-type of each loop entry before doing something with that entry. Because numpy arrays one allow a single data-type, it only has to check for the entries' data type **once**. If you imagine looping over an array or list of length 100,000, you probably understand that the numpy loop is way faster.\n\nLet's check out the speed difference between Python list operations and numpy array operations:\n\n\n```python\n# timeit is a cool 'feature' that you can use in Notebooks (no need to understand how it works)\n# it basically performs a computation that you specify a couple of times and prints how long it took on average\nresults_python = %timeit -o [x * 2 for x in range(0, 100000)] \n```\n\nAnd now let's do the same with numpy:\n\n\n```python\nresults_numpy = %timeit -o np.arange(0, 10000) * 2 \n\nratio = results_python.average / results_numpy.average\nprint(\"Numpy is %i times faster than Python!\" % ratio)\n```\n\nYou see that Numpy 10 times as fast! This really matters when you start doing more complex operations, on, let's say, multidimensional brain images!\n\n### Numpy arrays: creation\nAs shown an earlier example, numpy arrays can be created as follows:\n\n1. Define a Python list (e.g. `my_list = [0, 1, 2]`) \n2. Convert the list to a numpy array (`numpy_array = np.array(my_list)`)\n\nImportantly, a simple Python list will be converted to a 1D numpy array, but a nested Python list will be converted to a 2D (or even higher-dimensional array). Nesting is simply combining different lists, separated by commans, as is shown here:\n\n\n```python\nmy_list = [1, 2, 3]\nmy_array = np.array(my_list)\n\nprint(\"A 1D (or 'flat') array:\")\nprint(my_array, '\\n')\n\nmy_nested_list = [[1, 2, 3],\n                  [4, 5, 6],\n                  [7, 8, 9]]\n\nmy_2D_array = np.array(my_nested_list)\nprint(\"A 2D array:\")\nprint(my_2D_array)\n```\n\nAs you can imagine, creating numpy arrays from nested lists becomes cumbersome if you want to create (large) arrays with more than 2 dimensions. There are, fortunately, a lot of other ways to create ('initialize') large, high-dimensional numpy arrays. One often-used method is to create an array with zeros using the numpy function `np.zeros`. This function takes one (mandatory) argument, which is a tuple with the dimensions of your desired array:\n\n\n```python\nmy_desired_dimensions = (2, 5) # suppose I want to create a matrix with zeros of size 2 by 5\nmy_array = np.zeros(my_desired_dimensions)\n\nprint(my_array)\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nusing the `np.zeros` function, create a five dimensional array of shape $2 \\times 3 \\times 5 \\times 3 \\times 7$ and store it in a variable named `array_5d`.\n\n\n```python\n# Implement your ToDo here\n\n# your solution here\n\n```\n\n\n```python\n''' Tests the above ToDo. '''\navailable_vars = dir()\nif 'array_5d' not in available_vars:\n    raise ValueError(\"You didn't define the variable 'array_5d'!\")\n\ntest_create_array_with_zeros(array_5d)\n```\n\nUsing arrays with zeros is often used in what is called 'pre-allocation', in which you create an 'empty' array with only zeros and for example, 'fill' that array in a loop.\n\nBelow, we show you an example in which we pre-allocate an array with 5 zeros, and fill that in a for-loop with the squares of 1 - 5. Try to understand how it works! (You have to do something similar in the next ToDo!)\n\n\n```python\nmy_array = np.zeros(5)\n\nprint('Original zeros-array')\nprint(my_array)\n\nfor i in range(5):  # notice the range function here! This loop now iterates over [0, 1, 2, 3, 4]\n    number_to_calculate_the_square_of = i + 1\n    my_array[i] = number_to_calculate_the_square_of ** 2\n\nprint('\\nFilled array')\nprint(my_array)\n```\n\n**Important**: realize that loops (not shown above), if-statements and other boolean logic is the same for numpy and python!\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (2 points)\n</div>\nWrite a loop in which you fill each value in the variable `my_array2` with the value 1 divided by the current index plus one. So, suppose the index (usually `i`, like the last example) is 3, then you should fill `my_array2` at index `i` with `1 / (3 + 1)`.\n\n\n```python\nimport numpy as np\nmy_array2 = np.zeros(8)\n\n# your solution here\n\n```\n\n\n```python\n''' Tests the above ToDo. '''\navailable_vars = dir()\nif 'my_array2' not in available_vars:\n    raise ValueError(\"The variable my_array2 does not exist!\")\n    \ntest_fill_array_with_complement(my_array2)\n```\n\nIn addition to `np.zeros`, you can create numpy arrays using other functions, like `np.ones` and `random` from the `np.random` module:\n\n\n```python\nones = np.ones((5, 10)) # create an array with ones\nprint(ones, '\\n')\n\nrndom = np.random.random((5, 10)) # Create an array filled with random values (0 - 1 uniform)\nprint(rndom)\n```\n\n### Numpy: indexing\nIndexing (extracting a single value of an array) and slicing (extracting multiple values - a subset - from an array) of numpy arrays is largely the same as with regular Python lists and data structures from other scientific computing languages such as R and MATLAB. Let's check out a couple of examples of a 1D array:\n\n\n```python\nmy_array = np.arange(10, 21)  # numpy equivalent of list(range(10, 21))\nprint('Full array:')\nprint(my_array, '\\n') \n\nprint(\"Index the first element:\")\nprint(my_array[0], '\\n')\n\nprint(\"Index the second-to-last element:\")\nprint(my_array[-2], '\\n')\n\nprint(\"Slice from 5 until (not including!) 8\")\nprint(my_array[5:8], '\\n') \n\nprint(\"Slice from beginning until 4\")\nprint(my_array[:4])\n```\n\nSetting values in numpy arrays works the same way as lists:\n\n\n```python\nmy_array = np.arange(10, 21)\nmy_array[0] = 10000\nprint(my_array)\n\nmy_array[5:7] = 0\nprint(my_array)\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nIn the array `my_array` below, set all odd indices (i.e., the first element, the third element, the fifth element, etc.) to the value `0.0` *in a single statement using a slice* (i.e., not a for-loop).\n\n\n```python\n# Implement the ToDo here\nmy_array = np.arange(3, 25)\n\n# your solution here\n\n```\n\n\n```python\n''' Tests the above ToDo. '''\ntest_set_odd_indices_to_zero(my_array)\n```\n\n#### Multidimensional indexing\nOften, instead of working on and indexing 1D array, we'll work with multi-dimensional (>1D) arrays. Indexing multi-dimensional arrays is, again, quite similar to other scientific computing languages. \n\nLike indexing Python lists, indexing multidimensional numpy arrays is done with square brackets `[]`, in which you can put as many comma-delimited numbers as there are dimensions in your array. \n\nFor example, suppose you have a 2D array of shape $3 \\times 3$ and you want to index the value in the first row and first column. You would do this as follows:\n\n\n```python\nmy_array = np.zeros((3, 3)) # 3 by 3 array with zeros\nindexed_value = my_array[0, 0]\nprint(\"Value of first row and first column: %.1f\" % indexed_value)\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nUsing multidimensional indexing, set the value in the last row and last column of the 2D array `my_array` to `1.0`. In other words, set the value in the lower-right \"corner\" of the 2D array to 1.0.\n\n\n```python\nimport numpy as np\nmy_array = np.zeros((3, 3))\n\nprint(my_array)\n\n# ToDo: set the value in the lower right corner to 1\n\n# your solution here\n\n```\n\n\n```python\n''' Tests the ToDo above. '''\ntest_set_lower_right_value_to_one(my_array)\n```\n\nIn addition to setting specific slices to specific values, you can also extract sub-arrays using slicing/indexing. An important construct here is that you can use a single colon `:` to select all values from a particular dimension. For example, if you want to select all column-values (second dimension) from only the first row (first dimension), do this:\n\n```\nsome_2d_arr[0, :]\n```\n\nWe'll show you some examples below:\n\n\n```python\nmy_array = np.array([[1, 2, 3],\n                     [4, 5, 6],\n                     [7, 8, 9]])\n\nprint(my_array, '\\n')\n\nall_column_values_from_first_row = my_array[0, :]\nprint('First row')\nprint(all_column_values_from_first_row, '\\n')\n\nall_row_values_from_first_col = my_array[:, 0]\nprint('First column')\nprint(all_row_values_from_first_col)\n```\n\nSo far, we only talked about 2D arrays, which are relatively easy to 'understand'. In neuroimaging, however, we usually work with 3D, 4D, or even higher-dimensional arrays. These arrays are great for organizing data (like 3D brain scans!), but they are somewhat unintuitive. This takes some time to get used to!\n\nTo get you used to thinking in more than 2 (or 3) dimensions, consider the following scenario. A researcher wants to test the efficacy of a particular medicine against high blood pressure. To do so, he/she measures the (average systolic) blood pressure of a group of twenty subjects every hour for 30 days when they're not on the medication. The same subjects are then again measured for another 30 days, but then when they're on medication.\n\nAfter this period of data collection, the researcher has $20\\ (subjects)\\ \\times\\ 24\\ (hours)\\ \\times\\ 30\\ (days)\\ \\times\\ 2\\ (conditions: off/on) = 28800$ measurements! We can then organize the data in a 4D array, in which each factor (subjects/hours/days/conditions) represents a separate dimension (also called \"axis\") of our array!\n\nSo, let's generate some random data (from a normal distribution to generate 'realistic' blood pressure data) that could represent this blood pressure dataset:\n\n\n```python\nnp.random.seed(42)  # this is not important for now\nbp_data = np.random.normal(loc=100, scale=5, size=(20, 24, 30, 2))\n```\n\n(Note that we're not printing the `bp_data` variable here, because it's way too much to visualize/interpret at once anyway!)\n\nNow, suppose I would want to extract the blood pressure of subject 5 at 09.00 (AM) in the morning at day 21 when he/she was *not* on medication. In that case, I would do:\n\n\n```python\n# Note that I count midnight as the first measurement\nthis_particular_datapoint = bp_data[4, 8, 20, 0]\nprint(\"Blood pressure of participant 5 at 09.00 (AM) on day 21 in \"\n      \"the no-medication (off) condition is %.3f\" % this_particular_datapoint)\n\n# Also, remember that Python is zero-based, so e.g. participant 5 is indexed by index 4!\n```\n\nTry to remember this: **in multidimensional arrays, each dimension (axis) represents a different attribute of your data (e.g. subjects, time, condition, etc.)**. This concept will become very important to understand later when we're going to analyze 4D MRI-datasets (with 3 spatial dimensions and 1 time dimension)!\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nConsider the blood-pressure dataset again. In the code-cell below, extract from all participants all data from day 18 in the medication (\"on\") condition. You'll have to use slices with the single `:`! Store the results of your index-operation in the variable `day_18_condition_on`.\n\n\n```python\n# Implement your ToDo here (index the bp_data variable)\n\n# your solution here\n\n```\n\n\n```python\n''' Tests the above ToDo. '''\nif 'day_18_condition_on' not in dir():\n    raise ValueError(\"The variable 'day_18_condition_on' is not defined!\")\n    \ntest_bloodpressure_index(day_18_condition_on)\n```\n\nMultidimensional indexing using slices (especially the single colon `:` slice, i.e., selecting everything) is very common in scientific programming such as neuroimaging analyses. There is, however, yet another way of (multidimensional) indexing called \"boolean indexing\". \n\nIn this type of indexing, you index an array with a boolean array (i.e. array with True and False values) of the same shape. Basically, when you're indexing the array `my_array` with boolean array `bool_array`, you're saying: \"give me all values in `my_array` that are `True` at the same location in `bool_array`!\"\n\nLet's look at an example:\n\n\n```python\nmy_array = np.array([[1, 2, 3],\n                     [4, 5, 6],\n                     [7, 8, 9]])\n\nprint(\"The original array:\\n\")\nprint(my_array, '\\n')\n\nbool_array = np.array([[True, False, True],\n                       [False, True, False],\n                       [True, False, True]])\n\nprint(\"The boolean array:\\n\")\nprint(bool_array, '\\n')\n\nprint('Result of indexing my_array with bool_array:\\n')\nprint(my_array[bool_array])\n```\n\nUsually, you do not write out the boolean array in full (as we did above), but you base it on the data itself to \"filter\" it according to some criterion formalized as a logical statement (i.e., using the boolean operators >, <, ==, or !=). For example, suppose I want to extract only the values above 6 from the `my_array` variable in the above example. \n\nTo do so, I could do the following:\n\n\n```python\nmy_array = np.array([[1, 2, 3],\n                     [4, 5, 6],\n                     [7, 8, 9]])\n\nprint(\"The original array:\\n\")\nprint(my_array, '\\n')\n\nbool_array = my_array > 6\n\nprint(\"The boolean array:\\n\")\nprint(bool_array, '\\n')\n\nprint('Result of indexing my_array with bool_array:\\n')\nprint(my_array[bool_array])\n```\n\nEasy, right? Now try it yourself in the next ToDo!\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nUse a boolean index to extract all values whose square (i.e. $value^2$) is larger than 4 from the array (`my_array`) below. Store the results in a variable with the name `square_is_larger_than_4`.\n\n\n```python\nmy_array = np.array([[0, 1, -1, -2],\n                     [2, -5, 1, 4],\n                     [10, -2, -4, 20]])\n\n# Make a new boolean array below (name it whatever you want) ...\n\n# And use it to index my_array and store it in a variable `square_is_larger_than_4`.\n\n# your solution here\n\n```\n\n\n```python\nif 'square_is_larger_than_4' not in dir():\n    raise ValueError(\"Could not find the variable 'square_is_larger_than_4'; did you name it correctly?\")\n\ntest_boolean_indexing(square_is_larger_than_4)\n```\n\nAgain, it's very important to understand how to (effectively) index multidimensional numpy arrays using slices and boolean indexing, as we'll use it a lot in this course!\n\n### Numpy: data-types\nEvery numpy array is a grid of values of the same type. Numpy provides a large set of numeric datatypes that you can use to construct arrays. Numpy guesses the datatype when you create an array, but functions that construct arrays usually also include an optional argument to explicitly specify the datatype.\n\nHere are a couple of examples:\n\n\n```python\nx1 = np.array([1, 2])  # Let numpy choose the datatype (here: int)\nx2 = np.array([1.0, 2.0])  # Let numpy choose the datatype (here: float)\nx3 = np.array([1, 2], dtype=np.float64)  # Force a particular datatype (input: int, but converted to 64bit float)\nx4 = np.array([-1, 0, 1, 2], dtype=bool)  # Convert ints to booleans! 0 -> False, everthing else -> True \n\nprint('%r (%s)' % (x1, type(x1[0])))\nprint('%r (%s)' % (x2, type(x2[0])))\nprint('%r (%s)' % (x3, type(x3[0])))\nprint('%r (%s)' % (x4, type(x4[0])))\n```\n\n### Numpy: methods vs. functions\nIn the previous section (Basic Python), you've learned that, in addition to functions, 'methods' exist that are like functions of an object. In other words, methods are functions that are applied to the object itself. You've seen examples of list methods, e.g. `my_list.append(1)`, and string methods, e.g. `my_string.replace('a', 'b')`.\n\nLike lists and strings, numpy arrays have a lot of convenient methods that you can call. Again, this is just like a function, but then applied to itself. Often, numpy provides both a function and method for simple operations. \n\nLet's look at an example: \n\n\n```python\nmy_array = np.arange(10)  # creates a numpy array from 0 until (excluding!) 10\nprint(my_array, '\\n')\n\nmean_array = np.mean(my_array)\nprint('The mean of the array is: %f' % mean_array, '\\n')\n\nmean_array2 = my_array.mean() \nprint('The mean of the array (computed by its corresponding method) is: %f' % mean_array2, '\\n')\n\nprint('Is the results from the numpy function the same as '\n      'the corresponding method? Answer: %s' % str(mean_array == mean_array2))\n```\n\nIf there is both a function and a method for the operation you want to apply to the array, it really doesn't matter what you choose! Let's look at some more (often used) methods of numpy ndarrays:\n\n\n```python\nmy_array = np.array([[1, 2, 3],\n                     [4, 5, 6],\n                     [7, 8, 9]])\n\nstd_my_array = my_array.std()  # same as np.std(array)\nprint(\"Standard deviation of my_array: %.3f\" % std_my_array, '\\n')\n\ntranspose_my_array = my_array.T  # same as np.transpose(array)\nprint(\"Transpose of my_array:\\n%r\" % transpose_my_array, '\\n')\n\nmin_my_array = my_array.min()  # same as np.min(array)\nprint(\"Minimum of my_array: %i\" % my_array.min(), '\\n')\n\nmax_my_array = my_array.max()  # same as np.max(array)\nprint(\"Maximum of my_array: %i\" % max_my_array, '\\n')\n\nsum_my_array = my_array.sum()  # same as np.sum(array)\nprint(\"Sum of my_array: %i\" % sum_my_array, '\\n')\n```\n\nImportantly, a method may or may not take arguments (input).\nIf no arguments are given, it just looks like \"object.method()\", i.e. two enclosing brackets with nothing in between.\nHowever, a method may take one or more arguments (like the my_list.append(1) method)! \nThis argument may be named or unnamed - doesn't matter. An example:\n\n\n```python\nmy_array2 = np.random.random((3, 3))\nprint('Original array:')\nprint(my_array2, '\\n')\n\nprint('Use the round() method with the argument 3:')\nprint(my_array2.round(3), '\\n')\n\nprint('Use the round() method with the named argument 5:')\nprint(my_array2.round(decimals=5), '\\n')\n```\n\n**Some methods that you'll see a lot in the upcoming tutorials**. In addition to the methods listed above, you'll probably see the following methods a lot in the rest of this course (make sure you understand them!):\n\nReshaping arrays:\n\n\n```python\nmy_array = np.arange(10)\nprint(my_array.reshape((5, 2))) # reshape to desired shape\n```\n\nRavel (\"flatten\") an array:\n\n\n```python\ntemporary = my_array.reshape((5, 2))\nprint(\"Initial shape: %s\" % (temporary.shape,))\nprint(temporary.ravel()) # unroll multi-dimensional array to single 1D array\nprint(\"Shape after ravel(): %s\" % (temporary.ravel().shape,))\n```\n\n\n```python\n# .dot() does matrix multiplication (dot product: https://en.wikipedia.org/wiki/Dot_product)\n# This linear algebra operation is used very often in neuroimaging research \n# (which depends heavily on the General Linear Model!)\narray1 = np.array([0, 1, 2, 3])\narray2 = np.array([4, 5, 6, 7])\n\ndot_product = array1.dot(array2)\nprint(dot_product)\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nLet's practice writing functions some more. Complete the function below, named `calculate_range`. This function takes  a single input-argument - a 1D numpy array - and subsequently calculates the [range](https://en.wikipedia.org/wiki/Range_(statistics) of the array. The range is the difference between the maximum and minimum of any given array (vector) $x$:\n\n\\begin{align}\nrange(x) = max(x) - min(x)\n\\end{align}\n\nYou may use the corresponding numpy min/max methods or functions in your custom function, doesn't matter. Don't forget to explicitly return the value of the range! \n\nNote: this custom function that implements the *mathematical* formula for a vector's range is completely unrelated to the *Python function* `range` that is often used in for-loops! \n\n\n```python\n# Complete the function below\ndef calculate_range(arr):\n    ''' Calculate the range of an array.\n    \n    Parameters\n    ----------\n    arr : a 1D numpy array\n    \n    Returns\n    -------\n    The range of the input arr\n    '''\n    \n    # your solution here\n\n```\n\n\n```python\n''' Tests the above ToDo. '''\n\noutp = calculate_range(np.array([0, 1, 2, 3]))\nif outp is None:\n    raise ValueError(\"Didn't get any output! Did you explicitly return the range?\")\n\nassert(outp == 3)\nassert(calculate_range(np.array([-1, 0, 1, 2])) == 3)\nassert(calculate_range(np.array([0, 0, 0, 0])) == 0)\n\nprint(\"Well done!\")\n```\n\n### Numpy: methods vs. attributes?\nAlright, by now, if you see a variable followed by a word ending with enclosed brackets, e.g. `my_array.mean()`, you'll know that it's a method! But sometimes you might see something similar, but **without** the brackets, such as `my_array.size`. This `.size` is called an **attribute** of the variable `my_array`. Like a method, it's an integral part of an object (such as a numpy ndarray). The attribute may be of any data-type, like a string, integer, tuple, an array itself. Let's look at an example:\n\n\n```python\nmy_array = np.array([[1, 2, 3],\n                     [4, 5, 6],\n                     [7, 8, 9]])\n\nprint(my_array, '\\n')\nprint('The size (number of element) in the array is:')\nprint(my_array.size, '\\n')\nprint('The .size attribute is of data-type: %s' % type(my_array.size))\n```\n\nAlright, so by now you might be wondering what the difference between a method and an attribute is. Superficially, you can recognize a method by the form `object.method()` (note the brackets!), like `my_array.round()`; an attribute is virtually the same **but without brackets**, in the form of `object.attribute`, like `my_array.size`. \n\nConceptually, you may think of methods as things that **do** something with the array, while attributes **say** something about the array.\n\nFor example, `my_array.size` **does nothing** with the array - it only **says** something about the array (it gives information about its size), while `my_array.mean()` really **does** something (i.e. calculates the mean of the array). \n\nAgain, you might not use attributes a lot during this course, but you'll definitely see them around in the code of the tutorials. Below, some of the common ndarray attributes are listed:\n\n\n```python\nmy_array = np.array([[1, 2, 3],\n                     [4, 5, 6],\n                     [7, 8, 9]])\n\nprint('Size (number of elements) of array:')\nprint(my_array.size, '\\n') # returns an integer\n\nprint('Shape of array:')\nprint(my_array.shape, '\\n') # this is a tuple!\n\nprint('Number of dimensions:')\nprint(my_array.ndim) # this is an integer\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (2 points)\n</div>\nLet's try another one. Complete the function below, named `compute_one_sample_ttest`. This function takes two input arguments:\n\n- arr : a 1D numpy array\n- h0 : a scalar value (single number) that represents the value representing the null-hypothesis\n\nThe function should compute the one-sample t-test, which tests whether the mean of an array is significantly different from a given value representing the null-hypothesis. Formally, for any given array $x$ and null-hypothesis $h_{0}$:\n\n\\begin{align}\nt = \\frac{\\bar{x} - h_{0}}{s\\ / \\sqrt{N}}\n\\end{align}\n\nHere: $\\bar{x}$ represents the mean of $x$, $s$ represents the standard deviation of $x$, and $N$ represents the length ('size') of x. So, in slightly less mathematical notation:\n\n\\begin{align}\nt = \\frac{mean(x) - h_{0}}{std(x)\\ / \\sqrt{length(x)}}\n\\end{align}\n\nMake sure to return the t-value! \n\n**Hint 1**: to compute $N$, you can use the `.size` attribute of an array ... <br>\n**Hint 2**: use the function `np.sqrt(some_number)` to calculate the square root ...\n\n\n```python\n# Complete the function below!\ndef compute_one_sample_ttest(arr, h0):\n    ''' Computes the one-sample t-test for any array and h0. \n    \n    Parameters\n    ----------\n    arr : a 1D numpy array\n    h0 : an int or float\n    \n    Returns\n    -------\n    A single value representing the t-value\n    '''\n    \n    # your solution here\n\n```\n\n\n```python\n''' Tests the ToDo above. '''\narr = np.random.randn(100)\noutp = compute_one_sample_ttest(arr , 0)\n\nif outp is None:\n    raise ValueError(\"Your function didn't return anything! Did you forget the return statement?\")\n\ntest_tvalue_computation(arr, 0, outp)\n\noutp = compute_one_sample_ttest(arr, 5) \ntest_tvalue_computation(arr, 5, outp)\n\noutp = compute_one_sample_ttest(arr, -3) \ntest_tvalue_computation(arr, -3, outp)\n```\n\n### Numpy: array math\nNow you know all the numpy basics necessary to do neuroimaging analysis! As you'll see in the last section (Working with nifti-images), we'll work with 3D (structural MRI images) or 4D (functional MRI images) numpy arrays a lot. Given that you know how the basics about numpy in general and numpy ndarrays in particular, we can utilize some of numpy's best features: (very fast) array math.\n\nBasic mathematical functions operate elementwise on arrays, which means that the operation (e.g. addition) is applied onto each element in the array.\n\nSo, let's initialize a 1D array with ten zeros and let's add 1 to it:\n\n\n```python\nx = np.zeros(10)\nprint(x, '\\n')\nx += 1 # remember: this the same as x = x + 1\nprint(x)\n```\n\nAdditionally, you can also sum two arrays together in an elementwise manner by simply writing: `array_1 + array_2`, given that these two (or more) arrays are of the same shape! Let's look at an example:\n\n\n```python\nx = np.array([[1,2],[3,4]], dtype=np.float64)\ny = np.array([[5,6],[7,8]], dtype=np.float64)\n\nprint(\"x: \\n%r\" % x, '\\n')\nprint(\"y: \\n%r\" % y, '\\n')\nprint(\"x+y: \\n%r\" % (x + y), '\\n')\n```\n\nOften, there exist function-equivalents of the mathematical operators. For example, `x + y` is the same as `np.add(x, y)`. However, it is recommended to use the operators wherever possible to improve readability of your code. See below for an example:\n\n\n```python\nprint(x + y, '\\n')\nprint(np.add(x, y))\n```\n\nNext to addition, we can also do elementwise subtraction, multiplication, divison, square root, and exponentiation:\n\n\n```python\n# Elementwise difference; both produce the array\nprint(x - y, '\\n')\nprint(np.subtract(x, y))  # function-equivalent of above \n```\n\n\n```python\n# Elementwise product; both produce the array\nprint(x * y, '\\n')\nprint(np.multiply(x, y))\n```\n\n\n```python\n# Elementwise division; both produce the array\n# [[ 0.2         0.33333333]\n#  [ 0.42857143  0.5       ]]\nprint(x / y, '\\n')\nprint(np.divide(x, y))\n```\n\n\n```python\n# Elementwise square root; there is no operator-equivalent!\nprint(np.sqrt(x))\n```\n\n\n```python\n# Elementwise exponentiation\nprint(x ** y, '\\n')\nprint(np.power(x, y))\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nDo an elementwise product between the two variables defined below (`arr_A` and `arr_B`) and subsequently add 5 to each element; store the result in a new variable called `result_product_and_sum`.\n\n\n```python\n# Implement the ToDo!\narr_A = np.arange(10).reshape((5, 2))\narr_B = np.arange(10, 20).reshape((5, 2))\n\n# your solution here\n\n```\n\n\n```python\n''' Tests the above ToDo. '''\nif 'result_product_and_sum' not in dir():\n    raise ValueError(\"The variable 'result_product_and_sum' does not seem to exist!\")\n\ntest_array_product_and_sum(result_product_and_sum)    \n```\n\nNote that unlike MATLAB, `*` is elementwise multiplication, not matrix multiplication. We instead use the dot function (or method!) to  compute matrix operations like inner products of vectors, multiplication of a vector by a matrix, and multiplication of two matrices.\n\nThese matrix operations are quite important in this course, because they are used a lot in neuroimaging methods (such as the General Linear Model, the topic of next week!). You're not expected to fully understand these matrix operations, but you'll see them several times in this course, so make sure you're familiar with its implementation in Python/Numpy.\n\nAn example of the inner product (\"dot product\") of two vectors in both the function-format and the method-format:\n\n\n```python\nv = np.array([9,10])\nw = np.array([11, 12])\n\n# Inner product of vectors; both produce 219\nprint(v.dot(w))\nprint(np.dot(v, w))\n```\n\nProbably the most used functions in numpy are the sum() and mean() fuctions (or equivalent methods!). A nice feature is that they can operate on the entire array (this is the default) or they can be applied per dimension (or, in numpy lingo, per \"axis\").\n\nApplying functions along axes is very common in scientific computing! Let's look at an example in which we apply the `sum` function/method across rows and columns:\n\n\n```python\nx = np.array([[1, 2],[3, 4], [5, 6]])\n\nprint('Original array:')\nprint(x, '\\n')\n\nprint('Sum over ALL elements of x:')\nprint(np.sum(x), '\\n')\n\nprint('Sum across rows of x:')\nprint(np.sum(x, axis=0), '\\n')\n\nprint('Sum across columns of x:')\nprint(x.sum(axis=1)) # this is the method form! Is exactly the same as np.sum(x, axis=1) \n```\n\nImportantly, application of functions across axes is much quicker (and more concise) than writing for-loops! Let's look at the speed difference between a for-loop (implemented as a list comprehension) and the numpy-style application of the `sum` function across axes:\n\n\n```python\narr = np.random.random((1000, 100))\nloop_style = %timeit -o [arr[i, :].sum() for i in range(arr.shape[0])]\naxis_style = %timeit -o arr.sum(axis=1)\nprint(\"Using the axis-argument is %.3f times faster than a for-loop!\" % (loop_style.average / axis_style.average))\n```\n\nThis application of functions on entire arrays (in an elementwise manner, like `arr_1 + arr_2`) and application of functions across a certain axis (like `np.sum(arr_1, axis=1)`) is often called **vectorization**. This is an incredibly useful concept and something we'll use a lot in this course! Make sure you understand this. \n\nLet's practice this a bit.\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nRemember the \"range\" function from before? Below, we started writing a function, called `calculate_range_vectorized`, that calculates, for any 2D array, the range of each column (i.e. calculates range **across rows** for each column) in a *vectorized manner* (so without any for loops!).\n\nComplete the function, and make sure to return the result, which should be a 1D vector which values represents the ranges for all columns. So, if the input array would be of shape `(100, 10)`, then the shape of your returned array should be `(10,)`.\n\n\n```python\ndef compute_range_vectorized(arr):\n    ''' Compute the range across rows for each column in a 2D array. \n    \n    Parameters\n    ----------\n    arr : a 2D numpy array\n    \n    Returns\n    -------\n    A 1D vector with the ranges for each column\n    '''\n    \n    # your solution here\n\n```\n\n\n```python\nnp.random.seed(42)\ntest_arr = np.random.random((100, 10))\noutp = compute_range_vectorized(test_arr)\n\nif outp is None:\n    raise ValueError(\"Output is None! Did you forget the Return statement in your function?\")\n\ntest_compute_range_vectorized(test_arr, outp)\n```\n\n### Broadcasting\nBroadcasting is a powerful mechanism that allows numpy to work with arrays of different shapes when performing arithmetic operations. Frequently we have a smaller array and a larger array, and we want to use the smaller array multiple times to perform some operation on the larger array.\n\nFor example, suppose that we want to add a vector to each row of a matrix. We could do it like this:\n\n\n```python\n# We will add the vector v to each row of the matrix x,\n# storing the result in the matrix y\nx = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\n\nprint('x array is of shape: %r' % (x.shape,))\nprint(x, '\\n')\n\nv = np.array([1, 0, 1])\nprint('v vector is of shape: %r (different shape than x!)' % (v.shape,))\nprint(v, '\\n')\n\ny = np.zeros(x.shape)   # Create an empty (zeros) matrix with the same shape as x\nprint('Shape of (pre-allocated) y-matrix: %r' % (y.shape,))\n\n# Add the vector v to each row of the matrix x with an explicit loop\nfor i in range(x.shape[0]): # see how the shape attributes comes in handy in creating loops?\n    y[i, :] = x[i, :] + v\n\nprint('The result of adding v to each row of x, as stored in y:')\nprint(y)\n```\n\nThis works; however when the matrix `x` is very large, computing an explicit for-loop in Python could be slow. Note that adding the vector v to each row of the matrix `x` is equivalent to forming a matrix `vv` by stacking multiple copies of `v` vertically, like this `[[1 0 1], [1 0 1], [1 0 1], [1 0 1]]`, and subsequently elementwise addition of `x + vv`:\n\n\n```python\nvv = np.tile(v, (4, 1)) # i.e. expand vector 'v' 4 times along the row dimension (similar to MATLAB's repmat function)\ny = x + vv  # Add x and vv elementwise\nprint(y)\n```\n\nNumpy **broadcasting** allows us to perform this computation without actually creating multiple copies of v. Consider this version, using broadcasting:\n\n\n```python\n# We will add the vector v to each row of the matrix x,\n# storing the result in the matrix y\nx = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\nv = np.array([1, 0, 1])\ny = x + v  # Add v to each row of x using broadcasting\nprint(y)\n```\n\nThe line `y = x + v` works even though `x` has shape `(4, 3)` and `v` has shape `(3,)` due to broadcasting; this line works as if v actually had shape `(4, 3)`, where each row was a copy of `v`, and the sum was performed elementwise.\n\nThis broadcasting function is really useful, as it prevents us from writing unnessary and by definition slower explicit for-loops. Additionally, it's way easier to read and write than explicit for-loops (which need pre-allocation). Functions that support broadcasting are known as universal functions. You can find the list of all universal functions in the [documentation](http://docs.scipy.org/doc/numpy/reference/ufuncs.html#available-ufuncs).\n\nHere are some applications of broadcasting using different functions:\n\n\n```python\nx = np.array([[1, 2],[3, 4], [5, 6]], dtype=np.float)\nx_sum = x.sum(axis=0)\n\nprint(x / x_sum, '\\n')\n\nx_mean = x.mean(axis=0)\nprint(x / x_mean)\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (2 points)\n</div>\nBelow, we started writing a function called `standardize_columns`, which takes a single input-argument - a 2D numpy array - and should subsequently *standardize* each column such that each column has a mean of zero and a standard deviation of 1. In other words, standardization subtracts the mean (across rows) of each column from the values in that column, and then divides those value with the standard deviation of that column. Formally, for each column $j$ in any 2D array, standardization entails:\n\n\\begin{align}\nx_{j}\\ standardized = \\frac{(x_{j} - \\bar{x_{j}})}{std(x_{j})}\n\\end{align}\n\nStandardization, which is also oftend called \"z-transformation\", is often done in statistics. We'll also see this next week.\n\nSo, in the function below, make sure that it is able to standardize each column in any 2D array. Make sure to use vectorized array computations (i.e, the `np.mean` and `np.std` functions/methods across rows) and broadcasting, so no for-loops! \n\n\n```python\ndef standardize_columns(arr):\n    ''' Standardize each column of a 2D input-array. \n    \n    Parameters\n    ----------\n    arr : a 2D numpy array\n    \n    Returns\n    -------\n    The input-array with standardized columns (should have the same shape as the input-array!)\n    '''\n    \n    # your solution here\n    \n```\n\n\n```python\n''' Tests the above ToDo. '''\n\ntest_arr = np.random.normal(5, 2, size=(100, 10))\noutp = standardize_columns(test_arr)\n\nif outp is None:\n    raise ValueError(\"The output from your function is None; did you forget the Return statement?\")\n\ntry:\n    np.testing.assert_array_almost_equal(outp.mean(axis=0), np.zeros(test_arr.shape[1]))\nexcept AssertionError as e:\n    print(\"The mean of the columns of your standardized array are not 0!\")\n    raise(e)\n\ntry:\n    np.testing.assert_array_almost_equal(outp.std(axis=0), np.ones(test_arr.shape[1]))\nexcept AssertionError as e:\n    print(\"The std of the columns of your standardized array are not 1!\")\n    raise(e)\n    \nprint(\"Well done!\")\n```\n\nNow, you know the most important numpy concepts and functionality that is necessary to do neuroimaging analysis. Surely, there is a lot more to the numpy package that what we've covered here! But for now, let's continue with plotting using Matplotlib!\n\n## 3. Matplotlib\nMatplotlib is Python's main plotting library. In this section give a brief introduction to the `matplotlib.pyplot` module, which provides a plotting system similar to that of MATLAB.\n\n\n```python\nimport matplotlib.pyplot as plt # this is how matplotlib.pyplot is usually imported\nimport numpy as np\n```\n\nBy running this special iPython command, we will be displaying plots inline (instead of in a new window; this is only relevant in Jupyter notebooks!):\n\n\n```python\n%matplotlib inline\n```\n\n### Plotting\nThe most important function in `matplotlib` is **`plot`**, which allows you to plot 1 dimensional data. Here is a simple example:\n\n\n```python\n# Draw a line with coordinates from vectors x and y\nx = np.arange(0, 11)  # 0 - 10\ny = np.arange(0, 11)  # 0 - 10, same as x\n\n# Plot the points using matplotlib\nplt.plot(x, y)\nplt.show()\n```\n\nWith just a little bit of extra work we can easily plot multiple lines at once, and add a title, legend, and axis labels:\n\n\n```python\ny2 = np.ones(x.size)  # vector of ones, i.e., straight line\n\n# Plot the points using matplotlib\nplt.plot(x, y)\nplt.plot(x, y2)\nplt.xlabel('x axis label')\nplt.ylabel('y axis label')\nplt.title('Two lines')\nplt.legend(['Linear increasing line', 'Constant line'])\nplt.show()\n```\n\n### Subplots \nYou can plot different subplots in a single figure using the subplot function. Here is an example:\n\n\n```python\n# Compute the x and y coordinates for points on sine and cosine curves\nx = np.arange(0, 3 * np.pi, 0.1)\ny_sin = np.sin(x)\ny_cos = np.cos(x)\n\n# Set up a subplot grid that has 2 'rows' and 1 'column',\n# and set the first such subplot as active.\nplt.subplot(2, 1, 1)  # the third argument here sets the 'active' plot\n\n# Make the first plot\nplt.plot(x, y_sin)\nplt.title('Sine')\n\n# Set the second subplot as active, and make the second plot.\nplt.subplot(2, 1, 2)\nplt.plot(x, y_cos)\nplt.title('Cosine')\n\n# Show the figure.\nplt.tight_layout() # this prevents plots from overlapping\nplt.show()\n```\n\nAnd we can add text to plots as such:\n\n\n```python\nx = np.arange(-1, 1, 0.01) # array from -1 to 1 in steps of 0.01\n\n# Set up a subplot grid that has 2 'rows' and 1 'column',\n# and set the first such subplot as active.\nplt.subplot(2, 1, 1)\nplt.plot(x, x ** 2)\nplt.title('x squared')\nplt.text(-0.5, 0.4, r\"$y=x^2$\", fontsize=20, color=\"blue\")\n\n# Set the second subplot as active, and make the second plot.\nplt.subplot(2, 1, 2)\nplt.plot(x, x ** 3)\nplt.title('x cubed')\nplt.text(-0.5, 0.4, r\"$y=x^3$\", fontsize=20, color=\"green\")\n\nplt.tight_layout()\nplt.show()\n```\n\nYou can read much more about the `subplot` function in the [documentation](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplot).\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nBelow, we initialized a 2D array of shape `(10, 100)` named `arr_2D`. In a figure with two subplots (across two columns), plot in the left subplot the mean across columns (i.e., 10 values) and in the right subplot plot the standard deviation across columns (also 10 values). **Hint**: these values represent the values on the `y-axis`. You can use `x = np.arange(10)` for the `x-axis`.\n\nAlso, give the subplots labels for the x- and y-axis, and give it a title.\n\nNote: this ToDo is manually graded, so there is no test-cell!\n\n\n```python\narr_2D = np.random.normal(0, 1, size=(10, 100))\n\n# Make your plot below!\n\n# your solution here\n\n```\n\n### Histograms\nNow let's generate some random data using the np.random functionality, and get some histograms of their distributions\n\n\n```python\nrand_uniform = np.random.uniform(size = (1000)) # uniform distribution\nrand_normal = np.random.normal(size = (1000))   # normal distribution\nrand_exponential = np.random.exponential(size = (1000)) # exponential distribution\n```\n\n\n```python\n# Set up a subplot grid that has rows=2 and columns=3,\n# and set the first such subplot as active.\nplt.subplot(1, 3, 1)\n\n# Make the first plot\nplt.hist(rand_uniform, color='g')\nplt.title('uniform')\n\n# Set the second subplot as active, and make the second plot.\nplt.subplot(1, 3, 2)\nplt.hist(rand_normal, color='b')\n\nplt.title('normal')\n\n# Set the second subplot as active, and make the second plot.\nplt.subplot(1, 3, 3)\nplt.hist(rand_exponential, color='r')\nplt.title('exponential')\n\nplt.tight_layout()\nplt.show()\n```\n\n### Images\nSo far, we've been plotting lines. Matplotlib also has easy functionality for plotting two-dimensional data-arrays, such as pictures. This is done using the command `plt.imshow()`. We'll use this feature a lot, because it allows us to visualize 2D slices of MRI-data as well! (Remember, MRI data is essentially just a 3D \"picture\" of the brain.) \n\n\n```python\n# the scipy module includes some pictures, so we can use those:\nfrom scipy import misc\nbw_photo = misc.face(gray=True)\n\n# now we can use the imshow command to plot 2d data:\nplt.imshow(bw_photo,cmap='gray')\nplt.show()\n```\n\nImportanty, photos are just 2D arrays with numbers representing the luminance (in black-and-white pictures) of each pixel. You can see this by printing the loaded image:\n\n\n```python\nprint(\"Shape of photo object: %r\" % (bw_photo.shape,), '\\n')\nprint(bw_photo)\n```\n\nYou can see that it's actually just a bunch of numbers (one number per pixel), and when we plot colorbar with the original picture, we see that high numbers convert to bright shades, and low numbers convert to dark shades. \n\n\n```python\nplt.imshow(bw_photo,cmap='gray')\nplt.colorbar()\nplt.show()\n```\n\nUsing the knowledge that black and white images are nothing more than just 2d-arrays of values, we can also generate our own images:\n\n\n```python\nrand_img = np.random.random((200,200)) # Create an array filled with random values\nprint(rand_img, '\\n')\nplt.imshow(rand_img, cmap='gray')\nplt.colorbar()\nplt.show()\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (0 points, no test-cell)\n</div>\nBelow, we loaded in a 2D array of shape (91, 108) named `mystery_data`. Visualize it using `plt.imshow()` (using the argument `cmap='gray'`) to check out what the data entails!\n\n\n```python\nmystery_data = np.load('mystery_data.npy')\n\n# Visualize it using plt.imshow!\n```\n\nNow that you know some basics of data types, arrays and plotting, it's time to get to work with some fMRI data!\n\n## 3. Neuroimaging analysis with Python\nAlthough (f)MRI data can come in many formats, by far the most used format is **nifti** (nifti has been developed by the **n**euroimaging **i**n**f**ormatics **t**echnology **i**nitiative). Throughout these tutorials you'll work with these nifti-files (also called nifti images), which you can recognize by their extension of **.nii** or its compressed version **.nii.gz**. This file-format is also used by some of the main neuroimaging software packages such as AFNI, nipype, and FSL. (You'll use FSL later in this course!). \n\nHowever, we'd like to inspect and analyze nifti images in Python as well! **Nibabel** is a Python package that allows us to read and load nifti images as numpy arrays in a straightforward manner. Let's look at an example:\n\n\n```python\n# If you haven't done so already, load some other packages we need\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport nibabel as nib # common way of importing nibabel\n```\n\nWe'll load in an fMRI-scan using nibabel below:\n\n\n```python\ndata_path = 'func_data.nii.gz'\ndata = nib.load(data_path)\n```\n\nRight now, we haven't loaded the *actual* data **in memory** yet, but only the meta-data (information **about** the data, such as its shape, dimensions, and some technical MRI acquisition parameters). So, what we've loaded now (in the variable `data`) is **not** a numpy array (yet), but a different object: a `Nifti-object`.\n\nLike a numpy array, this object has some attributes and methods that we can use. \nLet's check out some of this meta-data that is already available through its methods/attributes.\n\nFor example, `Nifti-objects`, like numpy-arrays, also have a `shape` attribute:\n\n\n```python\nprint('Shape of the data:')\nprint(data.shape) # this is one of the attributes of a Nifti-object in Python, just like a numpy array shape attribute!\n```\n\nFrom the shape of the data, we can already infer some things about the file we're working with. Clearly, it has 4 dimensions, which means that it is a functional file: 3 spatial dimensions, and 1 time dimension! Remember the blood-pressure data? This 4D representation of fMRI files is very similar. Here, each axis represents a different feature/factor of the data: \n\n1. the first axis represents the first spatial dimension (the \"saggital\" dimension, usually referred to as $X$)\n2. the second axis represents the second spatial dimension (the \"coronal\" dimension, usually referred to as $Y$)\n3. the third axis represents the third spatial dimension (the \"axial\" dimension, usually referred to as $Z$)\n4. the fourth axis represents the time dimension (usually referred to as $T$, or $N$, \"volumes\", or \"dynamics\")\n\nWe'll practice with this data-organization later.\n\nAnother attribute of this Nifti-object that you might check is the **header** attribute. Perhaps confusingly, the header attribute is another object itself, also with its own methods and attributes. Let's check out some of them: \n\n\n```python\nheader = data.header\nprint('Get the measurements of our dimensions:')\nprint(header.get_zooms())\n```\n\nAbove, the four numbers represent the measurements of the data's four dimensions (3 space dims, 1 time dim). But what the hell do these numbers represent? Millimeters, liters, km/hr?\n\nActually, the units of these dimensions can be accessed through the `header.get_xyzt_units()` (x, y, and z = spatial dims, t = time dims):\n\n\n```python\nprint('Units of our measurements:')\nprint(header.get_xyzt_units())\n# so space is in mm (voxels are 3 x 3 x 3.3 mm in size!) and time is in seconds (time resolution = 2 seconds)\n```\n\nSo now we know that our data reflects activity from 3 x 3 x 3.3 mm voxels across 200 timepoints sampled at a time resolution of 2 seconds. Now, let's dig a little deeper into the data! But remember, we still have to load the actual data in memory. We can do that by the `get_data()` method. This method actually returns a numpy 4D-array we can work with!\n\n\n```python\nfunc_data_in_memory = data.get_data()\nprint(type(func_data_in_memory))  # this is in fact a numpy array!\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nFrom the variable `func_data_in_memory`, extract (i.e., index) all values (across time) from the voxel located at saggital slice number 30, coronal slice number 50, and axial slice number 23. Store these values in the variable `voxel_timeseries`, which should be of shape `(100,)`.\n\n\n```python\n# Implement the ToDo here (remember: Python's indexing is zero-based!)\n\n# your solution here\n\n```\n\n\n```python\n''' Tests the above ToDo. '''\nif 'voxel_timeseries' not in dir():\n    raise ValueError(\"Could not find any variable named 'voxel_timeseries'; did you spell it correctly?\")\n\ntest_extract_voxel_timeseries(func_data_in_memory, voxel_timeseries)\n```\n\nLet's look at some of the data! Because we have $80\\ (X) \\times\\ 80\\ (Y)\\times\\ 37\\ (Z)\\times\\ 100\\ (T) = 23680000$ values in total, let's not look at all data at once. We'll select a [axial](https://en.wikipedia.org/wiki/Anatomical_plane) slice somewhere in the middle of the brain of the first recorded volume (i.e. t = 1).\n\n\n```python\naxial_slice_no = 18\nslice_1 = func_data_in_memory[:, :, axial_slice_no, 0] # the 0 refers to the first timepoint (t = 1)\nprint(slice_1, '\\n')\nprint('Shape of slice_1: %r' % list(slice_1.shape))\n```\n\nHmm, seems like nothing is going on! This is because Python doesn't print out the entire array, because that would clutter the notebook. Here, it is only plotting the first couple of rows and the last couple of rows from slice_1. The fact that we're only seeing zeros is because not all 23680000 values contain brain data! If a data point has value 0, it is very likely that this data point falls outside the recording of the brain.\n\nLet's check whether this is indeed the case. To visualize the entire slice, let's plot is using `imshow`:\n\n\n```python\nplt.imshow(slice_1, cmap='gray')\nplt.axis('off')  # Do not plot the tickmarks of x-axis and y-axis \nplt.show()\n```\n\nAs you can see, only a part of the image is brain data, which is centered in the middle of the image. All completely black locations in the image are represented as zeros in the slice-data. Knowing this, let's select (slice) only a small part of some actual brain data, as visualized below:\n\n\n```python\nimport matplotlib.patches as patches\n\nprint('We will select (index) the region indicated by red square:')\nrect = patches.Rectangle((35, 35), 5, 5, linewidth=2, edgecolor='r', facecolor='none')\nplt.imshow(slice_1, cmap='gray')\nax = plt.gca()\nax.add_patch(rect)\nplt.axis('off')\nplt.show()\n```\n\n\n```python\n# The data corresponding to the red square above\nprint(slice_1[35:41, 35:41])\n```\n\nWhat does this tell you? Well, fMRI data is simply a lot of numbers, with (relatively) higher numbers indicating (relatively) higher activity in functional MRI images.\n\nSo far, we have only looked at some (static) representation of voxel activity of some voxels at one particular timepoint (i.e, $t = 1$, the first volume of the data), ignoring the time-dimension of our data. We can also look at the activity of a single voxel (e.g., $X = 35$, $Y = 35$, $Z=18$) across time.\n\nThis basically amounts to indexing at these X/Y/Z coordinates! We'll show you what this entails conceptually in the code-block below, in which we show you that particular voxel at location X/Y/Z for the first 20 timepoints (not all 100, because that clutters the notebook too much):\n\n\n```python\nvolumes_to_plot = 20\nplt.figure(figsize=(30, 30))\n\n# Loop over the first 20 volumes/timepoints\nfor t in range(volumes_to_plot):\n    \n    plt.subplot(5, 5, (t+1))\n    plt.imshow(func_data_in_memory[:, :, axial_slice_no, t], cmap='gray')  # index with t!\n    rect = patches.Rectangle((35, 35), 1, 1, linewidth=1, edgecolor='r', facecolor='none')\n    ax = plt.gca()\n    ax.add_patch(rect)\n    plt.axis('off')\n    plt.title('t = %i' % (t + 1), fontsize=20)\nplt.show()\n```\n\nIt is really hard to spot whether the image of the slice is actually different between different time points! To the naked eye, it just seems like the same picture. This is because activity fluctations (over time) in fMRI are **very** small - most of the time just 1-3% compared to baseline (average) activity. That's why it's hard to spot activity differences by looking at the pictures alone.\n\nThe activity fluctuations become clearer when you plot the activity of voxels across time in a linegraph (which allows you to see *relative* activity fluctuations better). So, let's plot the activity over time (t = 1:100) for the voxel within the red square in the figure above:\n\n\n```python\nplt.plot(func_data_in_memory[35, 35, axial_slice_no, :])\nplt.title('Activity over time for voxel (35, 35, %i)' % axial_slice_no, fontsize=15)\nplt.xlabel('Time (t)', fontsize=15)\nplt.ylabel('Activity (arbitrary units)', fontsize=15)\n\nplt.show()\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (3 points)\n</div>\n\nLet's practice some of the skills that you learned in this tutorial! For this ToDo, you goal is to **plot an histogram of the average activity value across time for all non-zero voxels in the brain**. So, what you have to do is the following:\n\n1. Average the `func_data_in_memory` variable across time (resulting array should by of shape (80, 80, 37)\n2. Remove all voxels which are zero (use boolean indexing!)\n3. Make a histogram of all the resulting non-zero voxels (use the argument `bins=100` in `plt.hist`)\n\nDo this in the code-cell below. Also, *give the plot sensible labels for the axes*. This is a manually graded ToDo, so there is no test-cell.\n\nThe resulting histogram should show a \"bimodal distribution\" of average activity values - roughly with a peak around $x = 1000$ and a peak round $x = 10,000$. \n\n\n```python\n# Implement to ToDo here\n\n# your solution here\n\n```\n\nAlright, that's it! \n\n\n", "meta": {"hexsha": "94f6d8b99435bde06a8170eb1df16cd2f68c19e1", "size": 189495, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "python_tutorial.ipynb", "max_stars_repo_name": "ajluckman/python_workshop-Basel", "max_stars_repo_head_hexsha": "c64527150a7d2b5eef9e3416271665f581652143", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python_tutorial.ipynb", "max_issues_repo_name": "ajluckman/python_workshop-Basel", "max_issues_repo_head_hexsha": "c64527150a7d2b5eef9e3416271665f581652143", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python_tutorial.ipynb", "max_forks_repo_name": "ajluckman/python_workshop-Basel", "max_forks_repo_head_hexsha": "c64527150a7d2b5eef9e3416271665f581652143", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8868025751, "max_line_length": 10622, "alphanum_fraction": 0.6037151376, "converted": true, "num_tokens": 28648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421498454004374, "lm_q2_score": 0.12421301483609337, "lm_q1q2_score": 0.036545330239673435}}
{"text": "# \u4f7f\u7528Jupyter\u5236\u4f5cSlides\u7684\u4ecb\u7ecd\n\n\u738b\u6210\u519b \n\nwangchengjun@nju.edu.cn\n\n\u8ba1\u7b97\u4f20\u64ad\u7f51 http://computational-communication.com\n\n\n\n\n\n\n\n# RISE: \"Live\" Reveal.js Jupyter/IPython Slideshow Extension\nhttps://github.com/damianavila/RISE\n\n# Installation\n- Downnload from https://github.com/damianavila/RISE\n- open your teminal, cd to the RISE folder, e.g., \n\n    >## cd  /github/RISE/\n\n- To install this nbextension, simply run \n\n    >## python setup.py install\n\nfrom the RISE repository.\n\nIn the notebook toolbar, a new button (\"Enter/Exit Live Reveal Slideshow\") will be available.\n\nThe notebook toolbar also contains a \"Cell Toolbar\" dropdown menu that gives you access to metadata for each cell. If you select the Slideshow preset, you will see in the right corner of each cell a little box where you can select the cell type (similar as for the static reveal slides with nbconvert).\n\n# \u5c06ipynb\u6587\u4ef6\u8f6c\u4e3aslides.html\n- download the reveal.js from Github https://github.com/hakimel/reveal.js\n- generate html using the following code\n- put the generated html into the reveal.js folder\n- open the html using chrome\n\n\n    chengjuns-MacBook-Pro:~ chengjun$ cd github/cjc/code/\n\n    chengjuns-MacBook-Pro:code chengjun$ jupyter nbconvert slides.ipynb --to slides --post serve\n\n# \u6279\u91cf\u751f\u6210slides.html\u00b6\n    chengjuns-MacBook-Pro:~ chengjun$ cd github/cjc/code/\n    \n    chengjuns-MacBook-Pro:code chengjun$ jupyter nbconvert *.ipynb --to slides\n\n# \u6570\u5b66\u516c\u5f0f\n$E = MC^2$\n\n\n```latex\n%%latex\n\\begin{align}\na = \\frac{1}{2}\\\\\n\\end{align}\n```\n\n\n\\begin{align}\na = \\frac{1}{2}\\\\\n\\end{align}\n\n\n# \u7a0b\u5e8f\u4ee3\u7801\n\n\n```python\nprint 'hello world'\n```\n\n    hello world\n\n\n\n```python\nfor i in range(10):\n    print i\n```\n\n    0\n    1\n    2\n    3\n    4\n    5\n    6\n    7\n    8\n    9\n\n\n\n```python\n# get a list of all the available magics\n```\n\n\n```python\n% lsmagic\n```\n\n\n\n\n    Available line magics:\n    %alias  %alias_magic  %autocall  %automagic  %autosave  %bookmark  %cat  %cd  %clear  %colors  %config  %connect_info  %cp  %debug  %dhist  %dirs  %doctest_mode  %ed  %edit  %env  %gui  %hist  %history  %install_default_config  %install_ext  %install_profiles  %killbgscripts  %ldir  %less  %lf  %lk  %ll  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %lx  %macro  %magic  %man  %matplotlib  %mkdir  %more  %mv  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %popd  %pprint  %precision  %profile  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %rep  %rerun  %reset  %reset_selective  %rm  %rmdir  %run  %save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode\n    \n    Available cell magics:\n    %%!  %%HTML  %%SVG  %%bash  %%capture  %%debug  %%file  %%html  %%javascript  %%latex  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile\n    \n    Automagic is ON, % prefix IS NOT needed for line magics.\n\n\n\n\n```python\n% env\n# to list your environment variables.\n```\n\n\n\n\n    {'Apple_PubSub_Socket_Render': '/private/tmp/com.apple.launchd.Cti3IOL0XG/Render',\n     'CLICOLOR': '1',\n     'DISPLAY': '/private/tmp/com.apple.launchd.GQAU1RS6KM/org.macosforge.xquartz:0',\n     'GIT_PAGER': 'cat',\n     'HOME': '/Users/chengjun',\n     'JPY_PARENT_PID': '84860',\n     'LANG': 'en_US.UTF-8',\n     'LC_ALL': 'en_US.UTF-8',\n     'LC_CTYPE': 'UTF-8',\n     'LOGNAME': 'chengjun',\n     'PAGER': 'cat',\n     'PATH': '/Users/chengjun/anaconda/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/git/bin:/usr/texbin',\n     'PWD': '/Users/chengjun',\n     'SECURITYSESSIONID': '186a5',\n     'SHELL': '/bin/bash',\n     'SHLVL': '2',\n     'SSH_AUTH_SOCK': '/private/tmp/com.apple.launchd.VNCcz4m0az/Listeners',\n     'TERM': 'xterm-color',\n     'TERM_PROGRAM': 'Apple_Terminal',\n     'TERM_PROGRAM_VERSION': '343',\n     'TERM_SESSION_ID': 'FDFD985A-CDD6-415E-A3B0-E8A2A05CC9B4',\n     'TMPDIR': '/var/folders/l6/ntr5b4610hx38gy0_2xp7ngh0000gn/T/',\n     'USER': 'chengjun',\n     'XPC_FLAGS': '0x0',\n     'XPC_SERVICE_NAME': '0',\n     '_': '/Users/chengjun/anaconda/python.app/Contents/MacOS/python',\n     '__CF_USER_TEXT_ENCODING': '0x1F5:0x0:0x0'}\n\n\n\n\n```python\n%prun\n```\n\n     \n\n\n```python\n%time range(10)\n```\n\n    CPU times: user 11 \u00b5s, sys: 9 \u00b5s, total: 20 \u00b5s\n    Wall time: 21 \u00b5s\n\n\n\n\n\n    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n\n\n\n```python\n%timeit range(100)\n```\n\n    The slowest run took 295.47 times longer than the fastest. This could mean that an intermediate result is being cached.\n    1000000 loops, best of 3: 748 ns per loop\n\n\n!: to run a shell command. E.g., ! pip freeze | grep pandas to see what version of pandas is installed.\n\n\n\n```python\n! cd /Users/chengjun/github/\n```\n\n\n```python\n% matplotlib inline \n# to show matplotlib plots inline the notebook.\nimport matplotlib.pyplot as plt\n\nplt.plot(range(10), range(10), 'r-o')\nplt.show()\n```\n\n# This is the End. \n\n\n\n## Thanks for your attention. \n", "meta": {"hexsha": "31c652b7a9ed895c6b4b0d3f368a099844c18953", "size": 23952, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "code/01.slides.ipynb", "max_stars_repo_name": "XinyueSha/cjc", "max_stars_repo_head_hexsha": "c20b0dbc929f5fb00dbdbc15ce4e1b1c8657a607", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-06-12T06:21:38.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-17T09:47:06.000Z", "max_issues_repo_path": "code/01.slides.ipynb", "max_issues_repo_name": "XinyueSha/cjc", "max_issues_repo_head_hexsha": "c20b0dbc929f5fb00dbdbc15ce4e1b1c8657a607", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/01.slides.ipynb", "max_forks_repo_name": "XinyueSha/cjc", "max_forks_repo_head_hexsha": "c20b0dbc929f5fb00dbdbc15ce4e1b1c8657a607", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5423197492, "max_line_length": 8340, "alphanum_fraction": 0.664746159, "converted": true, "num_tokens": 1694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.12421300511003351, "lm_q1q2_score": 0.03654532584072969}}
{"text": "```python\ntry:\n    import openmdao.api as om\n    import dymos as dm\nexcept ImportError:\n    !python -m pip install openmdao[notebooks]\n    !python -m pip install dymos[docs]\n    import openmdao.api as om\n    import dymos as dm\n```\n\n# Defining ODEs\n\nOptimal control problems contain ordinary differential equations (ODE) or differential algebraic equations (DAE) that dictate the evolution of the state of the system.\nTypically this evolution occurs in time, and the ODE represents equations of motion (EOM).\nThe equations of motion can define a variety of systems, not just mechanical ones.\nIn other fields they are sometimes referred to as *process equations*.\n\n\\begin{align}\n    \\dot{\\bar{x}} = f_{ode}(\\bar{x},t,\\bar{u},\\bar{d})\n\\end{align}\n\nTo represent EOM, Dymos uses a standard OpenMDAO System (a Group or Component).\nThis System takes some set of variables as input and computes outputs that include the time-derivatives of the state variables $\\bar{x}$.\nThe ODE may also be a function of the current time $t$.\n\nFinally, the dynamics may be subject to some set of controllable parameters.\nIn Dymos these are broken into the dynamic controls $\\bar{u}$ and the static parameters $\\bar{d}$.\n\n##  System Options\n\nODE Systems in Dymos need provide values at numerous points in time we call nodes.\nFor performance reasons, it's best if it can do so using vectorized mathematical operations to compute the values simultaneously rather than using the loop to perform the calculation at each node.\nDifferent optimal control transcriptions will need to have computed ODE values at different numbers of nodes, so each ODE system in Dymos is required to support the option `num_nodes`, which is defined in the `initialize` method.\n\nODE system may define initial options as well.\nSince these options in OpenMDAO are typically provided as arguments to the instantiation of the ODE system, the user has the ability to provide additional input keyword arguments using the `ode_init_kwargs` option on Phase.\n\n## Variables of the Optimal Control Problem\n\nDymos needs to know how state, time, and control variables are to be connected to the System, and needs to know which outputs to use as state time-derivatives.\n\n### Time\n\nThe following time options can be set via the `set_time_options` method of Phase:\n\n\n```python\nfrom IPython.display import display, HTML, IFrame, Code\nfrom dymos.phase.options import TimeOptionsDictionary\nobj = TimeOptionsDictionary()\ndisplay(HTML(obj.to_table(fmt='html')))\n```\n\n### States\n\nStates have the following options set via the `add_state` and `set_state_options` methods of Phase:\n\n\n```python\nfrom dymos.phase.options import StateOptionsDictionary\nobj = StateOptionsDictionary()\ndisplay(HTML(obj.to_table(fmt='html')))\n```\n\n###  Controls\n\nInputs to the ODE which are to be dynamic controls are added via the `add_control` and `set_control_options` methods of Phase. The available options are as follows:\n\n\n```python\nfrom dymos.phase.options import ControlOptionsDictionary\nobj = ControlOptionsDictionary()\ndisplay(HTML(obj.to_table(fmt='html')))\n```\n\n###  Parameters\n\nInputs to the ODE which are non-time-varying can be specified using the `add_parameter` method of Phase.\nParameters may be used as design variables (by setting `opt = True`), or they may be connected to an output external to the Phase or Trajectory.\nThe available options are as follows:\n\n\n```python\nfrom dymos.phase.options import ParameterOptionsDictionary\nobj = ParameterOptionsDictionary()\ndisplay(HTML(obj.to_table(fmt='html')))\n```\n\nBy default, Dymos assumes that the ODE is defined such that a value of the parameter is provided at each node.\nThis makes it easier to define the partials for the ODE in a way such that some inputs may be used interchangeably as either controls or parameters.\nIf an ODE input is only to be used as a static variable (and not sized as `num_nodes` in the first dimension), then the user may specify option `static_target = True` to override this behavior.\n\n### Tagging Variables\n\nDymos will also automatically find and add any states that have been declared in components in the ODE. The syntax\nfor declaring them is as follows.\n\n```python\nself.add_output('vdot', val=np.zeros(nn), desc='acceleration magnitude', units='m/s**2',\n                tags=['dymos.state_rate_source:v', 'dymos.state_units:m/s'])\n```\n\nThe state is defined by adding tags to the state rate's output.\nThe tag 'dymos.state_rate_source:v' declares that 'v' is the state for which this output ('vdot') is the rate source.\nYou can also optionally use a tag in the format 'dymos.state_units:m/s' to define units for that state.\nIf you need to set any other options, then use `set_state_options` at the phase level.\n\nInputs which are sized as 'static' in the ODE (the first dimension is _not_ the number of nodes), must be made known to Dymos when using them as parameters.\nThis is normally accomplished with the 'static_target=True' option when calling add_parameter.\nTo avoid repetitive use of this option, users can add the tag 'dymos.static_target' to any input which should always be considered static.\nWhen connecting to multiple targets, a 'dymos.static_target' tag on one of them will result in all of them being considered static.\nInputs tagged with 'dymos.static_target' cannot be used as controls or polynomial controls.\n\n| Tag                                  | Applies to | Description                                                                                                                                                                                                                 |\n|--------------------------------------|------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| dymos.state_rate_source:{state_name} | Outputs    | Specifies that the tagged output provides the rate used to integrate the state of the given name.                                                                                                                           |\n| dymos.state_units:{units}            | Outputs    | Specifies the default units to be used for the state whose rate is provided by the tagged output. May only be used on outputs also tagged with 'dymos.state_rate_source:{state_name}'.                                      |\n| dymos.static_target                  | Inputs     | Specifies that the input is _not_ shaped with num_nodes as the first dimension. This effects the way in which parameters are connected to the input. Inputs tagged with 'dymos.static_target' cannot be used as controls.   |\n\n## Automatic target detection\n\nDymos will attempt to automatically connect variables to targets in the same name if those targets\nexist at the top-level of the ODE and have the same name as the state, control, parameter, or 'time'.\n\n## Vectorizing the ODE\n\nIn addition to specifying the ODE Options, a system used as an ODE is required to have a metadata\nentry called `num_nodes`.  When evaluating the dynamics, these systems will receive time, states,\ncontrols, and other inputs as *vectorized* values, where item in the vector represents the variable\nvalue at a discrete time in the trajectory.\n\nThe nodes are discretization or collocation locations in the polynomials which represent\neach segment.  The number of nodes in a given phase (to be evaluated by the ODE system) is determined\nby the number of segments in the phase and the polynomial order in each segment.  When Dymos instantiates\nthe ODE system it provides the total number of nodes at which evaluation is required to the ODE system.\nThus, at a minimum, the `initialize` method of components for an ODE system typically look something\nlike this:\n\nThe inputs and outputs of the system are expected to provide a scalar or dimensioned\nvalue *at each node*.  Vectorization of the component via numpy adds a significant performance increase\ncompared to using a for loop to cycle through calculations at each node.  It's important to remember\nthat vectorized data is going to be coming in, this is especially important for defining partials.\nFrom the perspective of the ODE system, the outputs at some time `t` only depend on the values\nof the input variables at time `t`.  When the output variables are scalar at any given time, this\nresults in components whose Jacobian matrices are diagonal.  This large degree of sparsity leads\nto computational advantages when using sparse-aware optimizers like SNOPT.  Users should declare\nthe partial derivatives of their components to be sparse (by specifying nonzero rows and columns)\nwhenever possible.\n\n\n```python\nclass MyODESystem(om.ExplicitComponent):\n\n    def initialize(self):\n        self.metadata.declare('num_nodes', types=int)\n```\n\nFor example, if `MyODEComponent` is to compute the linear function $y = a * x + b$ then the\nsetup, compute, and compute partials methods might look like this:\n\n\n```python\ndef setup(self):\n    nn = self.metadata['num_nodes']\n\n    self.add_input('a', shape=(nn,), units='m')\n    self.add_input('x', shape=(nn,), units='1/s')\n    self.add_input('b', shape=(nn,), units='m/s')\n\n    self.add_output('y', shape=(nn,), units='m/s')\n\n    r = c = np.arange(nn)\n    self.declare_partials(of='y', wrt='a', rows=r, cols=c)\n    self.declare_partials(of='y', wrt='x', rows=r, cols=c)\n    self.declare_partials(of='y', wrt='b', rows=r, cols=c, val=1.0)\n\ndef compute(self, inputs, outputs):\n    a = inputs['a']\n    x = inputs['x']\n    b = inputs['b']\n\n    outputs['y'] = a * x + b\n\ndef compute_partials(self, inputs, outputs, partials):\n    a = inputs['a']\n    x = inputs['x']\n    b = inputs['b']\n\n    partials['y', 'a'] = x\n    partials['y', 'x'] = a\n```\n\nA few things to note here.  We can use the `shape` or `val` argument of `add_input` and `add_output`\nto dimension each variable.  In this case each variable is assumed to be a scalar at each point in\ntime (each node).  We use the `rows` and `cols` arguments of `declare_partials` to provide the sparsity.\nHere using `arange(nn)` for both gives us a diagonal jacobian with `nn` rows and `nn` columns.  Since\nthe number of nonzero values in the jacobian is `nn`, we only need to provide `nn` values in the\n`compute_partials` method.  It will automatically fill them into the sparse jacobian matrix, in\nrow-major order.\n\nIn this example, the partial of `y` with respect to `b` is linear, so we can simply provide it in\nthe `declare_partials` call rather than reassigning it every time `compute_partials` is called.\nThe provided scalar value of `1.0` is broadcast to all `nn` values of the Jacobian matrix.\n\n## Dimensioned Inputs and Outputs\n\nThe above example assumes all inputs and outputs are scalar at each node.  Sometimes the user may\nencounter a situation in which the inputs and/or outputs are vectors, matrices, or tensors at\neach node.  In this case the dimension of the variable is `num_nodes`, with the dimension of the\nvariable at a single node filling out the remaining indices. A 3-vector is thus dimensioned\n`(num_nodes, 3)`, while a 3 x 3 matrix would be sized `(num_nodes, 3, 3)`.\n\n##  Non-Vector Inputs\n\nDeclaring inputs as vectors means that they have the potential to be used either as parameters or as dynamic controls which can assume a different value at each node.\nFor some quantities, such as gravitational acceleration in the Brachistochrone example, we can assume that the value will never need to be dynamic.\nTo accommodate this, parameters can be declared static with the argument `static_target=True`.\nThis prevents Dymos from \"fanning out\" the static value to the *n* nodes in the ODE system.\n\n##  Providing the ODE to the Phase\n\nPhases in Dymos are instantiated with both the `ode_class` and the `transcription` to be used.\nInternally, Dymos needs to instantiate the ODE multiple times.\nThis instantiation takes the form:\n\n```python\node_instance = ode_class(num_nodes=<int>, **ode_init_kwargs)\n```\n\nThis allows an OpenMDAO ExecComp to be used as an ODE via a lambda.\nFor instance, the brachistochrone ODE can be written as:\n\n\n```python\node = lambda num_nodes: om.ExecComp(['vdot = g * cos(theta)',\n                                     'xdot = v * sin(theta)',\n                                     'ydot = -v * cos(theta)'],\n                                    g={'value': 9.80665, 'units': 'm/s**2'},\n                                    v={'shape': (num_nodes,), 'units': 'm/s'},\n                                    theta={'shape': (num_nodes,), 'units': 'rad'},\n                                    vdot={'shape': (num_nodes,),\n                                          'units': 'm/s**2',\n                                          'tags': ['state_rate_source:v']},\n                                    xdot={'shape': (num_nodes,),\n                                          'units': 'm/s',\n                                          'tags': ['state_rate_source:v']},\n                                    ydot={'shape': (num_nodes,),\n                                          'units': 'm/s',\n                                          'tags': ['state_rate_source:v']},\n                                    has_diag_partials=True)\n\nt = dm.Radau(num_segments=10, order=3)\nphase = dm.Phase(ode_class=ode, transcription=t)\n```\n\nNote the use of `has_diag_partials=True` to provide more efficient graph coloring for the derivatives.\n\nIn theory, this also means you can implement Python's `__call__` method for an ODE.\nThe following code will return a copy of the brachistochrone ODE with the appropriate number of nodes.\nNote that the implementation below does not deal with any options provided via the `ode_init_kwargs`.\n\n\n```python\nclass CallableBrachistochroneODE(om.ExplicitComponent):\n\n    def initialize(self):\n        self.options.declare('num_nodes', types=int)\n\n    def __call__(self, num_nodes, **kwargs):\n        from copy import deepcopy\n        ret = deepcopy(self)\n        ret.options['num_nodes'] = num_nodes\n        return ret\n\n    def setup(self):\n        nn = self.options['num_nodes']\n\n        # Inputs\n        self.add_input('v', val=np.zeros(nn), desc='velocity', units='m/s')\n\n        self.add_input('g', val=9.80665, desc='grav. acceleration', units='m/s/s')\n\n        self.add_input('theta', val=np.ones(nn), desc='angle of wire', units='rad')\n\n        self.add_output('xdot', val=np.zeros(nn), desc='velocity component in x', units='m/s',\n                        tags=['state_rate_source:x', 'state_units:m'])\n\n        self.add_output('ydot', val=np.zeros(nn), desc='velocity component in y', units='m/s',\n                        tags=['state_rate_source:y', 'state_units:m'])\n\n        self.add_output('vdot', val=np.zeros(nn), desc='acceleration magnitude', units='m/s**2',\n                        tags=['state_rate_source:v', 'state_units:m/s'])\n\n        self.declare_partials(of='*', wrt='*', method='cs')\n        self.declare_coloring(wrt='*', tol=1.0E-12)\n```\n\nAn instance of the above ODE can then be provided to the phase upon instantiation.\n\n\n```python\node = CallableBrachistochroneODE(num_nodes=1)\nt = dm.Radau(num_segments=10, order=3)\nphase = dm.Phase(ode_class=ode, transcription=t)\n```\n\nThis can potentially lead to unintended behavior if multiple copeis of the ODE are intended to share data.\nSee [the Python docs](https://docs.python.org/3/library/copy.html) for some of the limitations of deepcopy.\n\n", "meta": {"hexsha": "ef789c6c05c144c0566636b7eb06d565e03fb821", "size": 20692, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/getting_started/defining_odes.ipynb", "max_stars_repo_name": "RutvikM3/dymos", "max_stars_repo_head_hexsha": "b445fff6f27d910007dad48c844c9bc538804122", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-19T17:03:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-19T17:03:49.000Z", "max_issues_repo_path": "docs/getting_started/defining_odes.ipynb", "max_issues_repo_name": "RutvikM3/dymos", "max_issues_repo_head_hexsha": "b445fff6f27d910007dad48c844c9bc538804122", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/getting_started/defining_odes.ipynb", "max_forks_repo_name": "RutvikM3/dymos", "max_forks_repo_head_hexsha": "b445fff6f27d910007dad48c844c9bc538804122", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.2887029289, "max_line_length": 284, "alphanum_fraction": 0.586023584, "converted": true, "num_tokens": 3454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31069437044942166, "lm_q2_score": 0.11757214591334526, "lm_q1q2_score": 0.03652900385693435}}
{"text": "--- \nProject Microeconometrics | Summer 2020, M.Sc. Economics, University of Bonn | [Vincent Selz](https://github.com/VincentSelz)\n\n# Replication of \u201cA Structural Analysis of Disappointment Aversion in a Real Effort Competition\u201d by David Gill and Victoria Prowse (2012) <a class=\"tocSkip\"> \n---\n\n### Miscellaneous <a class=\"tocSkip\">\n\nIn this notebook, I replicate the findings of \n\n\n> Gill, David, and Victoria Prowse. 2012. A Structural Analysis of Disappointment Aversion in a Real Effort Competition. *American Economic Review*, 102 (1): 469-503.\n\n\nThe original paper and the corresponding data and code can be found [here](https://www.aeaweb.org/articles?id=10.1257/aer.102.1.469). For their analysis, the authors use Stata and Matlab. \n\nTo view this notebook:\n\n* Recommended, is to clone the repository and to locally view it via jupyter notebook.\n* Unfortunately, the notebook cannot be inspected with mybinder or nbviewer, since rendering it returns an error.\n\n\n\nAside, from the accompanying text, the results are labelled into three categories:\n\n<div class=\"alert alert-block alert-success\">\n    <b>Successful replication:</b> All the results are replicated.\n</div>\n<div class=\"alert alert-block alert-info\">\n    <b>Extension:</b> The results of the paper are expanded.\n</div>\n<div class=\"alert alert-block alert-warning\">\n    <b>Notes:</b> Pointers to the workflow.\n</div>\n    \nGenerally, most code, with the exception of R code, is moved to the auxiliary files to enhance readability. \n\n<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Introduction\" data-toc-modified-id=\"Introduction-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Introduction</a></span></li><li><span><a href=\"#Experimental-Design\" data-toc-modified-id=\"Experimental-Design-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Experimental Design</a></span><ul class=\"toc-item\"><li><span><a href=\"#Slider-Task\" data-toc-modified-id=\"Slider-Task-2.1\"><span class=\"toc-item-num\">2.1&nbsp;&nbsp;</span>Slider Task</a></span></li><li><span><a href=\"#Experimental-Procedure\" data-toc-modified-id=\"Experimental-Procedure-2.2\"><span class=\"toc-item-num\">2.2&nbsp;&nbsp;</span>Experimental Procedure</a></span></li></ul></li><li><span><a href=\"#Theoretical-Predictions\" data-toc-modified-id=\"Theoretical-Predictions-3\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>Theoretical Predictions</a></span><ul class=\"toc-item\"><li><span><a href=\"#Canonical-Model\" data-toc-modified-id=\"Canonical-Model-3.1\"><span class=\"toc-item-num\">3.1&nbsp;&nbsp;</span>Canonical Model</a></span></li><li><span><a href=\"#Disappointment-Aversion\" data-toc-modified-id=\"Disappointment-Aversion-3.2\"><span class=\"toc-item-num\">3.2&nbsp;&nbsp;</span>Disappointment Aversion</a></span></li></ul></li><li><span><a href=\"#Identification-Strategy\" data-toc-modified-id=\"Identification-Strategy-4\"><span class=\"toc-item-num\">4&nbsp;&nbsp;</span>Identification Strategy</a></span></li><li><span><a href=\"#Empirical-Results\" data-toc-modified-id=\"Empirical-Results-5\"><span class=\"toc-item-num\">5&nbsp;&nbsp;</span>Empirical Results</a></span><ul class=\"toc-item\"><li><span><a href=\"#Data-Exploration\" data-toc-modified-id=\"Data-Exploration-5.1\"><span class=\"toc-item-num\">5.1&nbsp;&nbsp;</span>Data Exploration</a></span></li><li><span><a href=\"#Reduced-Form-Analysis\" data-toc-modified-id=\"Reduced-Form-Analysis-5.2\"><span class=\"toc-item-num\">5.2&nbsp;&nbsp;</span>Reduced Form Analysis</a></span><ul class=\"toc-item\"><li><span><a href=\"#Model\" data-toc-modified-id=\"Model-5.2.1\"><span class=\"toc-item-num\">5.2.1&nbsp;&nbsp;</span>Model</a></span></li><li><span><a href=\"#Results\" data-toc-modified-id=\"Results-5.2.2\"><span class=\"toc-item-num\">5.2.2&nbsp;&nbsp;</span>Results</a></span></li><li><span><a href=\"#Fixed-vs.-Random-Effects\" data-toc-modified-id=\"Fixed-vs.-Random-Effects-5.2.3\"><span class=\"toc-item-num\">5.2.3&nbsp;&nbsp;</span>Fixed vs. Random Effects</a></span></li><li><span><a href=\"#Further-Investigation\" data-toc-modified-id=\"Further-Investigation-5.2.4\"><span class=\"toc-item-num\">5.2.4&nbsp;&nbsp;</span>Further Investigation</a></span></li></ul></li><li><span><a href=\"#Structural-Model\" data-toc-modified-id=\"Structural-Model-5.3\"><span class=\"toc-item-num\">5.3&nbsp;&nbsp;</span>Structural Model</a></span><ul class=\"toc-item\"><li><span><a href=\"#Empirical-Specification\" data-toc-modified-id=\"Empirical-Specification-5.3.1\"><span class=\"toc-item-num\">5.3.1&nbsp;&nbsp;</span>Empirical Specification</a></span></li><li><span><a href=\"#Method-of-Simulated-Moments\" data-toc-modified-id=\"Method-of-Simulated-Moments-5.3.2\"><span class=\"toc-item-num\">5.3.2&nbsp;&nbsp;</span>Method of Simulated Moments</a></span></li><li><span><a href=\"#Empirical-Moments\" data-toc-modified-id=\"Empirical-Moments-5.3.3\"><span class=\"toc-item-num\">5.3.3&nbsp;&nbsp;</span>Empirical Moments</a></span></li><li><span><a href=\"#Weighting-Matrix\" data-toc-modified-id=\"Weighting-Matrix-5.3.4\"><span class=\"toc-item-num\">5.3.4&nbsp;&nbsp;</span>Weighting Matrix</a></span></li><li><span><a href=\"#Simulation\" data-toc-modified-id=\"Simulation-5.3.5\"><span class=\"toc-item-num\">5.3.5&nbsp;&nbsp;</span>Simulation</a></span></li><li><span><a href=\"#Further-Steps\" data-toc-modified-id=\"Further-Steps-5.3.6\"><span class=\"toc-item-num\">5.3.6&nbsp;&nbsp;</span>Further Steps</a></span></li></ul></li></ul></li><li><span><a href=\"#Critical-Assessment\" data-toc-modified-id=\"Critical-Assessment-6\"><span class=\"toc-item-num\">6&nbsp;&nbsp;</span>Critical Assessment</a></span></li><li><span><a href=\"#Appendix\" data-toc-modified-id=\"Appendix-7\"><span class=\"toc-item-num\">7&nbsp;&nbsp;</span>Appendix</a></span><ul class=\"toc-item\"><li><span><a href=\"#Effort-Distribution-Per-Round\" data-toc-modified-id=\"Effort-Distribution-Per-Round-7.1\"><span class=\"toc-item-num\">7.1&nbsp;&nbsp;</span>Effort Distribution Per Round</a></span></li><li><span><a href=\"#Prize-Distribution\" data-toc-modified-id=\"Prize-Distribution-7.2\"><span class=\"toc-item-num\">7.2&nbsp;&nbsp;</span>Prize Distribution</a></span></li><li><span><a href=\"#Moment-Computation-Specifications\" data-toc-modified-id=\"Moment-Computation-Specifications-7.3\"><span class=\"toc-item-num\">7.3&nbsp;&nbsp;</span>Moment Computation Specifications</a></span></li></ul></li><li><span><a href=\"#References\" data-toc-modified-id=\"References-8\"><span class=\"toc-item-num\">8&nbsp;&nbsp;</span>References</a></span></li></ul></div>\n\n\n```python\n%load_ext rpy2.ipython\n%load_ext autoreload\n%autoreload 2\n%matplotlib inline\n\n\nfrom datetime import datetime\nfrom IPython.display import HTML\nfrom IPython.display import display\nfrom linearmodels.panel import PanelOLS\nfrom scipy.stats import chisquare\nimport numpy as np\nimport pandas as pd\nimport pandas.io.formats.style\nimport respy as rp\nimport scipy.stats as stats\nimport seaborn as sns\nimport matplotlib as plt\nimport matplotlib.pyplot as pyplt\n\nfrom auxiliary.helper import *\nfrom auxiliary.msm import *\nfrom auxiliary.overview import *\nfrom auxiliary.simulation import *\n\n# Displays floats only to the third decimal \npd.set_option(\"display.precision\", 3)\npd.set_option('display.max_colwidth', -1)\n```\n\n    /Users/vincentselz/opt/anaconda3/lib/python3.7/site-packages/respy/_numba.py:2: NumbaDeprecationWarning: \u001b[1mAn import was requested from a module that has moved location.\n    Import requested from: 'numba.cgutils', please update to use 'numba.core.cgutils' or pin to Numba version 0.48.0. This alias will not be present in Numba version 0.50.0.\u001b[0m\n      from numba import cgutils\n\n\n\n```r\n%%R\n\nlibrary(plm)\nlibrary(haven)\nlibrary(msm)\nlibrary(stargazer)\nlibrary(car)\n```\n\n---\n# Introduction \n---\nGill & Prowse (2012) use a real effort tournament in a laboratory experiment to test experimentally whether agents are disappointment averse. Pairs of subjects need to complete a real effort task sequentially. The payoff is determined by a lottery where the probabilities of winning are linear in the difference in the agent's efforts. Hence, in the standard framework, the effort of the *First Mover* should not impact the choice of effort for the *Second Mover*. Yet, as predicted by Gill & Prowse's model of disappointment aversion, subjects exhibit a discouragement effect, where high effort by the *First Mover*, impacts the effort by the *Second Mover* negatively. Their effort choices are strategic substitutes.\n\nGill & Prowse (2012) use a reduced form **random effects panel regression** to estimate potential effects. Given the substantial variation induced by their experimental design, they subsequently use the **Method of Simulated Moments (MSM)** to estimate the parameters of a structural model of disappointment aversion. This structural model allows them to estimate the strength of disappointment aversion on average but also to estimate the extent of heterogeneity in disappointment aversion across the population. \n\nThis notebook will attempt to replicate the results of Gill & Prowse (2012) and will further add extensions in data exploration and the reduced form analysis. If possible Python is used to replicate the findings, yet if not possible R is used. For instance, the random effects regression with the common Python packages did yield close results but did not reproduce the same numbers reported in the paper. Unfortunately, I was not capable to reproduce the results of the structural estimation. Nonetheless, the steps taken towards the estimation of structural model are outlined. For this implementation, the documentation by [respy](https://respy.readthedocs.io/en/latest/) is closely followed. \n\nIn the following section, the experimental design is shown. Next, the identification strategy is discussed, followed by the theoretical predictions. Then, the empirical analysis and extension thereof are shown. Lastly, the paper will be critically assessed.\n\n---\n#  Experimental Design\n---\nThe six experimental session took place from late February to early March 2009 at the Nuffield Centre for Experimental Social Sciences (CESS) in Oxford. Per session twenty subjects participated in the study, leading to a subject pool of 120 participants in total. Each of them were paid a show-up fee of 4 pounds and went on to earn a further 10 pounds on average.  \n\n## Slider Task \n\nThe slider task consists of a single screen displaying numerous sliders. The number and position of sliders is not varied across subjects or across repetition of the task. At first, the sliders who range from 0 to 100 are placed at 0. It is possible to place the slider at every integer position between 0 and 100. The integer position is displaced next to the slider. The sliders can be adjusted and readjusted an unlimited number of times. The task for the subjects is to position as many sliders as possible at 50 during the time allocated to the subject. The number of sliders positioned at 50 constitutes the **points score**. The points score and the time remaining is displayed to the subject. In this experiment, 48 sliders were displayed and the subjects had 120 seconds to position them. Below, the schematic representation illustrates the task at hand. \n\n\n\n## Experimental Procedure\n\nEach session consists of 10 *First Movers* and 10 *Second Movers*, who stay in their role for the duration of their session. After two practice rounds, the subjects played 10 paying rounds. The prize for each pair was drawn randomly from {0.10,0.20,...3.90} and then revealed to the pair members. The task was completed sequentially, where the *Second Mover* observes the points score of the First Mover. This information is also displayed next to the alloted time and the own points score during the task. The probability to win the ensuing lottery is determined by\n\n\\begin{equation*}\nP_i(e_i,e_j) = \\frac{e_i - e_j + 50}{100}\n\\end{equation*}\n\nwere $e_i$ in this setting corresponds to the points score of player $i$, and respectively $e_j$ for player $j$. Henceforth, effort is used synonymously to the points score. This use of the term is unlike the traditional literature, where effort is the associated cost of action. Here, it directly corresponds to the behavior of the subjects.\n\nAfter each round the subjects were paired with another subjects. To ensure that subjects never meet each other, the *'no contagion'* matching algorithm by Cooper et al. (1996) is used. This prevents strategic action by the subjects, where they collude by decreasing their efforts. In fact, zero effort by both subjects yields the social optimum. \n\n---\n# Theoretical Predictions\n---\n\nThe paired subjects compete with each other to win a fixed prize $v$. First, the first movers works at the slider task and subsequently the second mover chooses his effort. Together the above stated probability to winning prize $v$ is determined. The probabilities are linear in the difference of points scores. For their analysis, the authors only focus on the Second Mover. This leaves them with a pure optimization problem.    \n\n## Canonical Model\n\nFor the canonical model to work, the separability assumption common in tournament literature is used. The assumption states that the utility $U_{2}$ can be separated into the *material utility* $u_{2}(y_{2})$ and the *cost of effort* $C(e_{2})$. This implies cost of effort does not depend on whether the agent wins the prize and the valuation of the prize does not change with increasing effort. This leaves the agent with the expected utility:\n\n\\begin{equation*}\nEU_2(e_2,e_1) = P_2(e_2,e_1)u_2(v) + \\left(1 - P_2(e_1,e_2)\\right) u_2(0) - C_2(e_2)\n\\end{equation*}\n\nGiven the linearity of the winning probabilities in the difference of efforts, the effort $e_1$ of the First Mover has no impact on the Second Mover's effort $e_2$. This leads to the proposition:\n\n**PROPOSITION 1:** *In the canonical model without disappointment aversion the Second Mover\u2019s optimal effort $e_2$ (or set of optimal efforts) does not depend on the First Mover\u2019s effort $e_1$.*\n\nThe relative lack of further structural assumptions makes this model malleable. For instance, the results still holds when risk aversion, inequity aversion (Fehr and Schmidt 1999) or a fixed reference point are webbed into the utility function. \n\n## Disappointment Aversion\n\nThe basis of the model of disappointment aversion is that agents are sensitive to deviations from their expectations.  They suffer a psychological loss when they receive less than what they expect and experience elation when they receive more. For instance, an employee feels disappointed by a raise because she expected the raise to be bigger. These potential psychological losses and gains, in turn, inform the agent in her decision process.\n\nThe agent compares the material utility $u_2(y_2)$ to a reference point $R_2$. She is experiencing a loss when the material utility is less than the reference point and joy when the material utility is above this reference level.  Without further assumptions on the form of this reference point $R_2$, this leaves the agent with the following utility\n\n\\begin{equation*}\nU_2(e_2,R_2,e_1) = u_2(y_2) + I_{u_2(y_2) \\geq R_2}G_2(u_2(y_2) - R_2) + I_{u_2(y_2) \\leq R_2}L_2(u_2(y_2) - R_2) - C_2(e_2)\n\\end{equation*}\n\nThe loss function $L_2(x)$ is strictly negative for all $x < 0$ and the gain function is $G_2(x) \\geq 0$ for $x > 0$. At $x = 0$ both functions equal zero. Loss aversion dictates that $G_2(x) < |L_2(-x)|$ for all $x > 0$. The losses are more painful than equal-sized gains are pleasurable. Traditionally, this reference point is set exogenously (Kahneman and Tversky 1979). Yet, such a fixed reference point does not link the First Mover effort to the Second Mover effort. To model disappointment aversion the reference point must be formed endogenously. K\u00f6szegi and Rabin (2007) propose a *choice-acclimating* reference point, where the reference point is equal to the expected utility. In this implementation the reference point is dependent on the effort of both the Second Mover herself and the First Mover's effort. In contrast to the model by K\u00f6szegi and Rabin, the Second Mover is aware that her effort choice affects the reference point when optimizing her behavior. In this setting this leads to $R_2 = vP_2(e_2,e_1)$. This step is crucial to allow for a possible discouragement effect. \n\nAs is custom in the literature, piece-wise linearity is imposed on the gain-loss utility. $l_2$ is the slope of the loss function and $g_2$ is the slope of the gain function. Loss aversion imposes $l_2 > g_2$ and leads to the (strictly positive) definition of the strength of disappointment aversion\n\n\\begin{equation*}\n\\lambda_2 \\equiv l_2 - g_2.\n\\end{equation*}\n\nThus, the disappointment averse expected utility can be formulated as \n\n\\begin{equation*}\nEU_2(e_2,e_1) = P_2 v + g_2(v - vP_2) + (1 - P_2)(0 + l_2(0 + vP_2) - C_2(e_2) \\\\\n= vP_2 - \\lambda_2vP_2(1 - P_2) - C_2(e_2) \n\\end{equation*}\n\nThe extra term in the middle of the equation is coined the **disappointment deficit** by the authors. This disappointment deficit is proportional to the variance of the Second Mover's two-point distribution of monetary payoffs. Due to disappointment aversion, the Second Mover dislikes variance in her monetary payoff. This is a key distinction to risk aversion, where agents only care about their probability of winning and not about the variance in their potential payoffs. This variance is strictly concave and maximized at $P_2$. When the efforts yield a zero probability for the Second Mover to win, she has a reference point of zero and combined with the probability she can never be disappointed. Yet at this point, small increases in probability lead to large increases in the variance of monetary payoffs. These increases get smaller but continue until $P_2 = \\frac{1}{2}$. At this point the variance reaches its highest point. From this point on increases in $P_2$ reduce the variance of monetary payoffs. This relationship can expressed as: \n\n**PROPOSITION 2:** *When the Second Mover is disappointment averse, higher First Mover effort discourages the Second Mover: the Second Mover\u2019s optimal effort $e_2$ is always (weakly) decreasing in the First Mover\u2019s effort $e_1$.*\n\nIn order to derive an analytical expression, the authors assume a quadratic cost of effort of the form \n\n\\begin{equation*}\nC_2(e_2) = be_2 + \\frac{ce_{2}^{2}}{2}.\n\\end{equation*}\n\nWith this term the Second Mover's reaction function can be expressed. \n\n**PROPOSITION 3:** *Suppose a disappointment averse Second Mover has a quadratic cost function and a strictly concave objective function, i.e., $\\gamma_2c_2 \u2212 \\lambda_2v > 0$. When the action space is continuous, the slope of the Second Mover\u2019s reaction function in the interior is given by*\n\n\\begin{equation*}\n\\frac{de_2}{de_1} = \\frac{-\\lambda_2v}{2\\gamma^2c - \\lambda_2v} < 0\n\\end{equation*}\n\n*which becomes strictly more negative in the strength of disappointment aversion $\\lambda_2$ and the value of the prize $v$. When the action space is discrete, the discrete analog of the reaction function behaves similarly.*\n\n\n\n---\n# Identification Strategy\n---\nIn their paper Gill and Prowse aim to evaluate whether subjects exhibit disappointment aversion. In order to do that, they set up the aforementioned laboratory experiment. The causal graph below illustrates their identification strategy. We can assume that the effort of the Second Mover's $e_2$ is affected by the value of the prize $v$ and the effort of the First Mover $e_1$. In addition to that there can be learning throughout the ten played periods. Strictly speaking this term is inaccurate, since it actually captures to very different ideas of learning. First, the learning of the Slider Task, where the agent improves his/her performance by experience. But second, there can be meta-learning, where the agent gets more selective under which conditions she exerts effort. \n\n\nFigure 2: Causal Graph (This graph is drawn with [draw.io](https://app.diagrams.net/).)\n\nThe advantages of an laboratory experiment are evident in the identification strategy by the authors. As the experimenters have total control over the environmental variables, they can randomize all those links, making for a straightforward identification. The prizes are drawn from a uniform distribution between 0.10 and 3.90 Pounds (with 0.10-steps). This variation also has advantages in the construction of structural equations as will be seen later. The ten playing rounds make it possible to control for individual specific effects and the matching algorithm ensures that there is no feedback back from the Second Mover effort to the First Mover, thus eliminating possible strategic interaction. The learning effect can be, albeit imperfectly, controlled for with round dummies. Thus, all channels can effectively be controlled for.  \n\n---\n# Empirical Results\n---\n## Data Exploration\n\nBefore we are turning to the empirical analysis to estimate the strength of disappointment aversion, we can visually inspect the data to see why the authors pursue their empirical strategy. The data consists of 120 subjects, 60 First and 60 Second Mover that are all observed over 10 rounds. Of the 120 subjects, one subject failed to correctly position any slider during the training or playing rounds. The dataset excluding this subject is called **df_2_pref** and is used mainly for the analysis. The points score is interpreted as the effort choice by the subject. Although still discrete, this gives them a finely gradated measure of effort.\n\nThe variable of interest is the Second Mover's effort and, thus, the authors are performing a conditional analysis of the Second Mover's effort choice. Their reasoning is that this analysis is sufficient for the purpose of identifying and estimating the strength of disappointment aversion. Including the First Mover's effort would make further assumptions necessary and increase the computational complexity substantially. \n\n<div class=\"alert alert-block alert-success\">\n    <b>Replication</b> of Table 1 of the paper.\n</div>\n\n\n```python\ndf_1, df_2, df_2_pref = get_datasets()\nrslt = effort_overview(df_2_pref)\nprint('Table 1: Summary of the First and Second Mover efforts')\nrslt\n```\n\n    Table 1: Summary of the First and Second Mover efforts\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Mean E1</th>\n      <th>SD E1</th>\n      <th>Mean E2</th>\n      <th>SD E2</th>\n      <th>Min E1</th>\n      <th>Min E2</th>\n      <th>Max E1</th>\n      <th>Max E2</th>\n    </tr>\n    <tr>\n      <th>period</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>22.034</td>\n      <td>5.991</td>\n      <td>21.763</td>\n      <td>6.101</td>\n      <td>1</td>\n      <td>0</td>\n      <td>33</td>\n      <td>34</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>22.627</td>\n      <td>6.708</td>\n      <td>23.458</td>\n      <td>4.836</td>\n      <td>0</td>\n      <td>11</td>\n      <td>33</td>\n      <td>33</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>24.763</td>\n      <td>6.075</td>\n      <td>24.831</td>\n      <td>4.875</td>\n      <td>0</td>\n      <td>12</td>\n      <td>37</td>\n      <td>38</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>24.627</td>\n      <td>5.956</td>\n      <td>25.203</td>\n      <td>4.502</td>\n      <td>0</td>\n      <td>16</td>\n      <td>35</td>\n      <td>36</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>24.966</td>\n      <td>6.800</td>\n      <td>25.119</td>\n      <td>5.660</td>\n      <td>0</td>\n      <td>0</td>\n      <td>36</td>\n      <td>35</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>24.729</td>\n      <td>7.508</td>\n      <td>24.898</td>\n      <td>7.039</td>\n      <td>1</td>\n      <td>0</td>\n      <td>37</td>\n      <td>39</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>25.881</td>\n      <td>5.855</td>\n      <td>25.763</td>\n      <td>6.109</td>\n      <td>9</td>\n      <td>0</td>\n      <td>37</td>\n      <td>37</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>26.831</td>\n      <td>5.858</td>\n      <td>26.169</td>\n      <td>5.133</td>\n      <td>9</td>\n      <td>14</td>\n      <td>41</td>\n      <td>35</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>25.593</td>\n      <td>8.550</td>\n      <td>26.254</td>\n      <td>6.702</td>\n      <td>0</td>\n      <td>0</td>\n      <td>38</td>\n      <td>40</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>26.322</td>\n      <td>6.781</td>\n      <td>26.729</td>\n      <td>5.988</td>\n      <td>1</td>\n      <td>0</td>\n      <td>40</td>\n      <td>39</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nOne important inference that can be made is that the maximum of effort is 41 correctly positioned sliders. This is lower than the highest possible maximum of 48 sliders. If, subjects reached this limit, this would suggest that the task is not well suited to identify exerted effort. Another inference that can be made is that the effort choices increase over the rounds, suggesting that learning indeed takes place. \n\n<div class=\"alert alert-block alert-info\">\n<b>Note:</b> The following graphs and charts are extensions to the paper.\n</div>\n\n\n```python\neffort_chart(rslt)\n```\n\nThis chart visualizes Table 1 of the paper. The black bar is indicating the standard deviation of the respective means. Clearly, there appears to be no clear distinction between $e_2$ and $e_1$, when simply inspecting these descriptives. Effort averages are increasing from about 22 correctly positioned sliders to more than 26 over the playing rounds. A closer look at the effort distribution per round shows (Appendix) that there is some variation and a non-neglible amount of subjects are choosing zero effort. Yet, the distribution do appear to behave approximately normal.\n\nHowever, we are also interested in how the effort of the Second Movers responds to the different prizes. This is shown below. Canonically, the increase in incentives increases the willingness to exert effort. This would manifest itself in a strictly monotonous relationship for each individuals. Given prizes are randomly distributed, this should also hold globally. However, this cannot be observed here, suggesting that there are other effects than the monetary incentive at play.  \n\n\n```python\npyplt.plot(df_2_pref.groupby('prize')['e2'].mean())\npyplt.xlabel('Prize')\npyplt.ylabel('Average Second Mover Effort')\npyplt.show()\nprint('Figure 4: Average Second Mover Efforts Per Prize Level \\n')\nstat = df_2_pref['e2'].corr(df_2_pref['prize'])\nprint(f'The correlation between Prize and Second Mover effort is {stat:0.3f}')\n```\n\n\n```python\njoint_effort(df_2_pref)\nprint('Figure 5: Correlation between First and Second Mover Effort')\n```\n\nAs mentioned above, the link the authors want to investigate is whether the effort $e_1$ of the First Mover negatively impacts the choice of effort $e_2$ made by the Second Mover. A naive strategy checks for the correlation between those two effort choices. Where disappointment aversion predicts a negative relationship, the canonical model suggest that there is no link between the effort choices. The correlation indicates that there is little to no correlation, and if at all, the effort choices are positively correlated. This positive relationship is suggested by peer effects (Falk and Ichino 2006), where subjects imitate the behavior of their peers and compete by matching or beating the observed effort levels. \n\nNaturally, this is an insufficient analysis without controlling for any of the other effects on Second Mover effort described in the identification strategy. Next, the authors use a reduced form analysis to examine the Second Mover's behavior.   \n\n## Reduced Form Analysis\n\n### Model\n\nEach subject plays ten rounds resulting in data with a panel structure. Here, proposition 1 predicts that when controlling for prize and round effects, the effort of the Second Mover will not depend on the First Mover's effort. In contrast, disappointment aversion predicts a negative relationship. The model to be estimated is:\n\\begin{equation}\ne_{2,n,r} = \\beta_1 + \\beta_2v_{n,r} + \\beta_3e_{1,n,r} + \\beta_4e_{1,n,r}  *  v_{n,r} + d_r + \\omega_n + \\epsilon_{n,r} \n\\end{equation}\n\nfor   n = 1,...,N and r = 1,...10. Where n denotes the Second Mover and r indicates the paying round. The inclusion of the interaction term is informed by Proposition 3, where the negative effect of the First Mover's effort is larger at higher prizes. Round dummies $d_r$ are included with the first round being the omitted dummy. The round-invariant Second Mover effects are denoted by $\\omega_n$ and are assumed to be identically and independently distributed over Second Movers with a variance of $\\sigma_\\omega^2$. $\\epsilon_{n,r}$ is an observable that varies over Second Movers, it is also assumed to be identically and independently distributed over rounds and Second Movers with variance $\\sigma_\\epsilon^2$.\n\n<div class=\"alert alert-block alert-warning\">\n<b>Note:</b> In the following cells the analysis with R is set up. R is used because using RandomEffects of the linearmodels package does not reproduce the results.  \n</div>\n\n\n```r\n%%R\n\n# import data \ndf <- read_dta(\"data/paper_data/master_data.dta\")\n\n# convert the data frame to a data format recognizable by 'plm' \npdf <- subset(pdata.frame(df, index = c(\"Subject\", \"Period\")))\npdf_pref <- subset(pdf, !Subject==302)\n```\n\n\n```r\n%%R\n\n# Random Effects Regressions\nre <- plm(Effort~e1+prize+E1timesPrize+TT2+TT3+TT4+TT5+TT6+TT7+TT8+TT9+TT10, data = pdf, model = \"random\")\nre_pref <- plm(Effort~e1+prize+E1timesPrize+TT2+TT3+TT4+TT5+TT6+TT7+TT8+TT9+TT10, data = pdf_pref, model = \"random\")\n# Fixed Effects Regressions\nfe <- plm(Effort~e1+prize+E1timesPrize+TT2+TT3+TT4+TT5+TT6+TT7+TT8+TT9+TT10, data = pdf, model = \"within\")\nfe_pref <- plm(Effort~e1+prize+E1timesPrize+TT2+TT3+TT4+TT5+TT6+TT7+TT8+TT9+TT10, data = pdf_pref, model = \"within\")\n\n# Standard Errors of Omega and Epsilon\npref_1 <- round(sqrt(re_pref$ercomp$sigma2[2]),digits=3)\npref_2 <- round(sqrt(re_pref$ercomp$sigma2[1]),digits=3)\nse_re_1 <- round(sqrt(re$ercomp$sigma2[2]),digits=3)\nse_re_2 <- round(sqrt(re$ercomp$sigma2[1]),digits=3)\n```\n\n### Results\n\n<div class=\"alert alert-block alert-success\">\n    <b>Replication</b> of the parameters and standard errors in Table 2 of the paper.\n</div>\n\nFor this model, the theory suggests three hypotheses:\n\n* Second Mover effort does **not** depend on the corresponding First Mover effort, controlling for prize and round effects **(Proposition 1)**.\n\n* Second Mover effort, in fact, depends (negatively) on the respective First Mover effort, with controls for prize and round effects **(Proposition 2)**.\n\n* The negative effect of the First Mover's effort on the Second Mover's effort is larger at higher prices **(Proposition 3)**.\n\n\n```r\n%%R\n\nstargazer(re_pref, re, type=\"text\", title=\"Table 2: Random Effects Regressions\",\n          dep.var.labels=\"Second Mover Effort\",\n          #omit=c(\"TT2\",\"TT3\",\"TT4\",\"TT5\",\"TT6\",\"TT7\",\"TT8\",\"TT9\",\"TT10\"), # unchecking this gives the coefficients reported in the paper.\n          covariate.labels=c(\"First Mover Effort\", \"Prize\", \"Prize x First Mover Effort\"),\n          column.labels=c(\"Preferred Sample\", \"Full Sample\"),\n          add.lines = list(\n            c(\"Standard Error of Omega\", pref_1 , se_re_1),\n            c(\"Standard Error of Epsilon\",pref_2,se_re_2)),\n          no.space=TRUE)\n```\n\n    \n    Table 2: Random Effects Regressions\n    =======================================================\n                                   Dependent variable:     \n                               ----------------------------\n                                   Second Mover Effort     \n                               Preferred Sample Full Sample\n                                     (1)            (2)    \n    -------------------------------------------------------\n    First Mover Effort              0.044          0.047   \n                                   (0.049)        (0.049)  \n    Prize                          1.639***      1.655***  \n                                   (0.602)        (0.592)  \n    Prize x First Mover Effort     -0.049**      -0.050**  \n                                   (0.023)        (0.023)  \n    TT2                            1.689**        1.655**  \n                                   (0.709)        (0.699)  \n    TT3                            3.084***      3.034***  \n                                   (0.713)        (0.702)  \n    TT4                            3.448***      3.369***  \n                                   (0.713)        (0.702)  \n    TT5                            3.322***      3.279***  \n                                   (0.714)        (0.703)  \n    TT6                            3.262***      3.193***  \n                                   (0.713)        (0.701)  \n    TT7                            4.123***      4.043***  \n                                   (0.716)        (0.705)  \n    TT8                            4.567***      4.487***  \n                                   (0.720)        (0.709)  \n    TT9                            4.709***      4.632***  \n                                   (0.716)        (0.704)  \n    TT10                           5.180***      5.066***  \n                                   (0.725)        (0.712)  \n    Constant                      19.777***      19.392*** \n                                   (1.400)        (1.447)  \n    -------------------------------------------------------\n    Standard Error of Omega         4.288          5.342   \n    Standard Error of Epsilon       3.852          3.826   \n    Observations                     590            600    \n    R2                              0.137          0.135   \n    Adjusted R2                     0.119          0.117   \n    F Statistic                   91.452***      91.268*** \n    =======================================================\n    Note:                       *p<0.1; **p<0.05; ***p<0.01\n\n\nProposition 3 can be accepted, the interaction between the First Mover's effort and the prize is significantly negative, suggesting that the effect of the First Mover's effort is larger at higher prices. Furthermore, the interaction term (at the average price) and the First Mover effort together are negative, albeit not significant. This supports Proposition 1 in favor of Proposition 2. Notable but only mentioned in a footnote are the large and highly significant round effects that tend to increase over the rounds. As indicated in Section 4, this can be due to learning. \n\n<div class=\"alert alert-block alert-info\">\nThe following regression shows the fixed effects regression that is mentioned in the text but not explicitly shown. \n</div>\n\n\n```r\n%%R\n\nstargazer(fe_pref,fe, type=\"text\", title=\" Table 3: Fixed Effects Regressions\",\n          dep.var.labels=\"Second Mover Effort\",\n          omit=c(\"TT2\",\"TT3\",\"TT4\",\"TT5\",\"TT6\",\"TT7\",\"TT8\",\"TT9\",\"TT10\"),\n          covariate.labels=c(\"First Mover Effort\", \"Prize\", \"Prize x First Mover effort\",\"Intercept\"),\n          column.labels=c(\"Preferred Sample\", \"Full Sample\"),\n          no.space=TRUE)\n```\n\n    \n    Table 3: Fixed Effects Regressions\n    ==========================================================================\n                                             Dependent variable:              \n                               -----------------------------------------------\n                                             Second Mover Effort              \n                                  Preferred Sample           Full Sample      \n                                         (1)                     (2)          \n    --------------------------------------------------------------------------\n    First Mover Effort                  0.047                   0.050         \n                                       (0.050)                 (0.049)        \n    Prize                             1.716***                1.701***        \n                                       (0.605)                 (0.594)        \n    Prize x First Mover effort        -0.051**                -0.051**        \n                                       (0.024)                 (0.023)        \n    --------------------------------------------------------------------------\n    Observations                         590                     600          \n    R2                                  0.151                   0.148         \n    Adjusted R2                         0.037                   0.034         \n    F Statistic                7.709*** (df = 12; 519) 7.655*** (df = 12; 528)\n    ==========================================================================\n    Note:                                          *p<0.1; **p<0.05; ***p<0.01\n\n\n### Fixed vs. Random Effects\n\nThe authors opt to use a random effects linear regression. Random effect models are closely related to the fixed effects models. Here, the different assumptions made by the two approaches are discussed. This is followed by the replication of the Hausman test that can be found in Table 2 of the paper. \n\nBoth approaches are workhorses when working with panel/cross sectional time series data. The key distinction between the two models are the different assumptions made about the omitted variables. Implicitly, the random effects model assumes that there are no omitted variables correlated with the explanatory variables. The entities are drawn randomly from a population. If this is accurate, the model yields unbiased results and produces the smallest standard errors. In comparison, the fixed effects model makes no such strong assumptions about the correlation of omitted variables with the explanatory variables. In fact, the approach can control for omitted variables bias. The subjects serve as their own controls. For this to hold true, the fixed effects has to be time-invariant. However, being able to control for omitted variable bias comes at the cost of producing higher standard errors. \n\nThe **Hausman test** provides a means for comparing these two models. It tests for the independence of $\\omega_n$ and the explanatory variables $x_{it}$. It looks as follows:\n\\begin{equation}\nW = \\frac{(\\tilde\\beta_{RE} - \\tilde\\beta_{FE})^2}{Var(\\tilde\\beta_{RE}) - Var(\\tilde\\beta_{FE})} \\sim \\chi_1^2\n\\end{equation}\n\nThe null hypothesis $H_0$ is that there is no covariance between the explanatory variables and the specific effects. Making the random effects model a suitable candidate. If this hypothesis is rejected, the $H_1$ leaves us with the fixed effects model coefficients as the only consistent coefficients.    \n\n<div class=\"alert alert-block alert-success\">\n    <b>Replication</b> of the Hausman test in  Table 2 of the paper.\n</div>\n\n\n```r\n%%R\n\n# Hausman Test testing the Random Effects assumption\nhausman <- phtest(fe,re)\nhausman_pref <- phtest(fe_pref,re_pref)\n\nhausman_pref\n```\n\n    \n    \tHausman Test\n    \n    data:  Effort ~ e1 + prize + E1timesPrize + TT2 + TT3 + TT4 + TT5 +  ...\n    chisq = 2.6008, df = 12, p-value = 0.9978\n    alternative hypothesis: one model is inconsistent\n    \n\n\nThe Hausman Test cannot reject $H_0$ and, thus, the use of random effects is supported. This holds true for the preferred sample as well as the full sample.\n\n### Further Investigation\n\nOne advantage of laboratory experiments is that environmental variables can be easily altered in a controlled fashion. However, this often does leave only few covariates to further investigate. Especially with the data provided by the authors, there are only limited options on how to expand their reduced form findings. In an earlier working paper the authors include men and women dummies, unfortunately they were not available in the provided dataset.\n\n<div class=\"alert alert-block alert-info\">\n<b>Extension:</b> The following regressions toggle around with different interaction terms. \n</div>\n\n\n```r\n%%R\n\n# Split interaction term on the first and the last rounds\nnew_split <- pdf_pref\nnew_split$Period <- as.numeric(new_split$Period)\nsplit <- pdf_pref\nsplit$Period <- as.numeric(split$Period)\n\n# Reported split\nsplit$last <- ifelse(split$Period <= 5, 0, split$E1timesPrize)\nsplit$first <- ifelse(split$Period > 5, 0, split$E1timesPrize)\n\n# New Split\nnew_split$last <- ifelse(new_split$Period <= 4, 0, new_split$E1timesPrize)\nnew_split$first <- ifelse(new_split$Period > 4, 0, new_split$E1timesPrize)\n\n# Random Effects regression\nsplit_interaction <- plm(Effort~e1+prize+last+first+TT2+TT3+TT4+TT5+TT6+TT7+TT8+TT9+TT10, data = split, model = \"random\")\nnew_interaction_split <- plm(Effort~e1+prize+last+first+TT2+TT3+TT4+TT5+TT6+TT7+TT8+TT9+TT10, data = new_split, model = \"random\")\n\nstargazer(split_interaction,new_interaction_split, type=\"text\", title=\"Table 4: Interaction Term Round Splits\",\n          dep.var.labels=\"Second Mover Effort\",\n          omit=c(\"TT2\",\"TT3\",\"TT4\",\"TT5\",\"TT6\",\"TT7\",\"TT8\",\"TT9\",\"TT10\"),\n          covariate.labels=c(\"First Mover Effort\", \"Prize\", \"Last\",\"First\",\"Intercept\"),\n          column.labels=c(\"Split at round 5\", \"Split at round 4\"),\n          no.space=TRUE)\n```\n\n    \n    Table 4: Interaction Term Round Splits\n    ====================================================\n                              Dependent variable:       \n                       ---------------------------------\n                              Second Mover Effort       \n                       Split at round 5 Split at round 4\n                             (1)              (2)       \n    ----------------------------------------------------\n    First Mover Effort      0.044            0.043      \n                           (0.049)          (0.050)     \n    Prize                  1.640***         1.619***    \n                           (0.604)          (0.605)     \n    Last                   -0.047**         -0.050**    \n                           (0.024)          (0.024)     \n    First                  -0.050**         -0.046*     \n                           (0.024)          (0.025)     \n    Intercept             19.843***        19.687***    \n                           (1.415)          (1.416)     \n    ----------------------------------------------------\n    Observations             590              590       \n    R2                      0.136            0.136      \n    Adjusted R2             0.117            0.117      \n    F Statistic           90.911***        90.977***    \n    ====================================================\n    Note:                    *p<0.1; **p<0.05; ***p<0.01\n\n\nThe specification where the interaction term is split at round 5 is mentioned in the paper. Using a different break point, where the interaction term the first four rounds is denoted by first and the last six rounds are denoted by last. This follows from the visual inspection of the effort distribution per round that can be found in the Appendix. \n\nThe new split is very similar to the older specification. Nonetheless, the interaction for the first rounds in the new specification is not significant at the 5% level anymore. Yet, further inspecting the coefficients does not lead to any new conclusions. The last rounds have a larger negative effect than the first round but the differences are minor and the test below affirms that the difference is not significant.   \n\n\n```r\n%%R\n\n# Test equality of the interaction term for the first and the last five rounds.\nlinearHypothesis(split_interaction, c(\"first=last\"))\n\n# Test for equality of the split interaction term with a break at round 4\nlinearHypothesis(new_interaction_split, c(\"first=last\"))\n```\n\n    Linear hypothesis test\n    \n    Hypothesis:\n    - last  + first = 0\n    \n    Model 1: restricted model\n    Model 2: Effort ~ e1 + prize + last + first + TT2 + TT3 + TT4 + TT5 + \n        TT6 + TT7 + TT8 + TT9 + TT10\n    \n      Res.Df Df  Chisq Pr(>Chisq)\n    1    577                     \n    2    576  1 0.1868     0.6656\n\n\n\n```r\n%%R\n\n# New dataset.\nnew_interact <- pdf_pref\n\n# Interaction term partioned for prize level\nnew_interact$small <- ifelse(new_interact$prize < 2, new_interact$E1timesPrize, 0)\nnew_interact$medium <- ifelse(new_interact$prize >= 2 & new_interact$prize <= 2.60, new_interact$E1timesPrize, 0)\nnew_interact$high <- ifelse(new_interact$prize >= 2.70, new_interact$E1timesPrize, 0)\n\n# interaction term for different prize level\nnew_spec <- plm(Effort~e1+prize+small+medium+high+TT2+TT3+TT4+TT5+TT6+TT7+TT8+TT9+TT10, data = new_interact, model = \"random\")\n\n# No prize controls\nno_prizes <- plm(Effort~e1+TT2+TT3+TT4+TT5+TT6+TT7+TT8+TT9+TT10, data = pdf_pref, model = \"random\")\n\n# Render the table\nstargazer(no_prizes,new_spec, type=\"text\", title=\"Table 5: New Interaction Term Specifications\",\n          dep.var.labels=\"Second Mover Effort\",\n          omit=c(\"TT2\",\"TT3\",\"TT4\",\"TT5\",\"TT6\",\"TT7\",\"TT8\",\"TT9\",\"TT10\"), # unchecking this gives the coefficients reported in the paper.\n          covariate.labels=c(\"First Mover Effort\", \"Prize\", \"Small\",\"Medium\",\"High\"),\n          column.labels=c(\"No Prize Controls\", \"Interaction per Prize Level\"),\n          no.space=TRUE)\n```\n\n    \n    Table 5: New Interaction Term Specifications\n    ================================================================\n                                    Dependent variable:             \n                       ---------------------------------------------\n                                    Second Mover Effort             \n                       No Prize Controls Interaction per Prize Level\n                              (1)                    (2)            \n    ----------------------------------------------------------------\n    First Mover Effort      -0.036                  0.024           \n                            (0.026)                (0.052)          \n    Prize                                         1.608***          \n                                                   (0.601)          \n    Small                                          -0.032           \n                                                   (0.029)          \n    Medium                                         -0.031           \n                                                   (0.025)          \n    High                                           -0.045*          \n                                                   (0.024)          \n    Constant               22.556***              19.801***         \n                            (0.946)                (1.399)          \n    ----------------------------------------------------------------\n    Observations              590                    590            \n    R2                       0.118                  0.142           \n    Adjusted R2              0.103                  0.122           \n    F Statistic            77.783***              95.534***         \n    ================================================================\n    Note:                                *p<0.1; **p<0.05; ***p<0.01\n\n\nIn the regression table above, two specifications can be seen. The first specification, also reported in the paper, eliminates all prize control and can report a negative but insignificant effect of $e_1$ on $e_2$. The other specification looks as follows:\n\n\\begin{equation}\ne_{2,n,r} = \\beta_1 + \\beta_2v_{n,r} + \\beta_3e_{1,n,r} + \\beta_4Small_{n,r} +\\beta_5Medium_{n,r} + \\beta_6High_{n,r} + d_r + \\omega_n + \\epsilon_{n,r} \n\\end{equation}\nwhere\n* $Small_{n,r} : e_{1,n,r}*v_{n,r}$ for $v_{n,r} < 2$\n* $Medium_{n,r} : e_{1,n,r}*v_{n,r}$ for $2 \\leq v_{n,r} \\leq 2.60$\n* $Large_{n,r} : e_{1,n,r}*v_{n,r}$ for $v_{n,r} > 2.60$\n\ndenote the interaction term for different prize ranges. This can inform whether this relationship is stable throughout the whole prize range. \n\nAs can be seen, the effect decreases with the prize value. Whereas the interaction on Small and Medium prize levels is not significant at any level, the interaction with the high prizes is borderline significant (10%). \n\n\n## Structural Model\n\n\n### Empirical Specification\nAfter not accumulating convincing evidence of disappointment aversion in the reduced form analysis the authors turn to structural estimation strategies. Thanks to the variations induced by the experimental design, the data is well-suited for such an analysis. Beyond, the estimation of disappointment aversion, this approach also allows for the estimation of population-level heterogeneity.\n\nIn order to estimate disappointment aversion the authors use the following specifications:\n\n\\begin{equation}\n\\lambda_{2,n} \\sim N(\\tilde\\lambda_2,\\sigma_\\lambda^2)\n\\end{equation}\nfor n = 1,...,N.\n\nHere, $\\lambda$ is held fixed on the subject-level. It can vary throughout Second Movers but does not vary over rounds. In addition to $\\lambda$ the convexity parameter $c_{n,r}$ is estimated at round and subject-level:\n\n\\begin{equation}\nc_{n,r} = \\kappa + \\delta_r + \\mu_n + \\pi_{n,r}\n\\end{equation}\nfor n = 1,...,N; r = 1,...10.\n\n$\\kappa$ represents a component common across all Second Movers. $\\delta_r$ denotes the round effects that allow the marginal costs of effort to vary over rounds (where $\\delta_1$ is omitted). For instance, if due to learning the tasks gets easier in the later periods $\\delta_r$ is negative and decreasing over rounds. $\\mu_n$ indicates the unobserved differences in the cost of effort on the subject-level that are constant over rounds. $\\pi_{n,r}$ denotes the unobserved differences that vary over rounds and Second Movers. For $\\pi$ and $\\mu$ both scale and shape parameters of a Weibull distribution are estimated. The reasoning for opting for a Weibull distribution is that it has positive support allowing to impose convex cost of effort function on all subjects. In total, this leaves them with the following 17 unknown parameter:\n\n<div class=\"alert alert-block alert-info\">\n    <b>Extension:</b> Description and trial values for the unknown parameters. \n</div>\n\n\n```python\nprint('Table 6: Parameter description')\nparams_description(return_descriptives=True)\n```\n\n    Table 6: Parameter description\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>value</th>\n      <th>comment</th>\n      <th>lower</th>\n      <th>upper</th>\n    </tr>\n    <tr>\n      <th>category</th>\n      <th>name</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">lambda</th>\n      <th>lambda</th>\n      <td>2.00</td>\n      <td>strength of disappointment aversion on average</td>\n      <td>1.0</td>\n      <td>3.0</td>\n    </tr>\n    <tr>\n      <th>std_lambda</th>\n      <td>1.50</td>\n      <td>standard deviation of strength of disappointment aversion</td>\n      <td>0.5</td>\n      <td>2.5</td>\n    </tr>\n    <tr>\n      <th rowspan=\"15\" valign=\"top\">cost_of_effort</th>\n      <th>phi_pi</th>\n      <td>0.35</td>\n      <td>unobserved differences in cost of effort functions that vary over rounds and individuals</td>\n      <td>0.0</td>\n      <td>0.7</td>\n    </tr>\n    <tr>\n      <th>varphi_pi</th>\n      <td>0.85</td>\n      <td>unobserved differences in cost of effort functions that vary over rounds and individuals</td>\n      <td>0.2</td>\n      <td>1.5</td>\n    </tr>\n    <tr>\n      <th>phi_mu</th>\n      <td>0.35</td>\n      <td>unobserved differences in cost of effort functions between individuals, constant over rounds</td>\n      <td>0.0</td>\n      <td>0.7</td>\n    </tr>\n    <tr>\n      <th>varphi_mu</th>\n      <td>0.85</td>\n      <td>unobserved differences in cost of effort functions between individuals, constant over rounds</td>\n      <td>0.2</td>\n      <td>1.5</td>\n    </tr>\n    <tr>\n      <th>kappa</th>\n      <td>1.75</td>\n      <td>common cost parameter</td>\n      <td>1.0</td>\n      <td>2.5</td>\n    </tr>\n    <tr>\n      <th>b</th>\n      <td>-27.50</td>\n      <td>common cost parameter</td>\n      <td>-35.0</td>\n      <td>-20.0</td>\n    </tr>\n    <tr>\n      <th>delta_2</th>\n      <td>0.00</td>\n      <td>round effects for round 2</td>\n      <td>-1.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>delta_3</th>\n      <td>0.00</td>\n      <td>round effects for round 3</td>\n      <td>-1.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>delta_4</th>\n      <td>0.00</td>\n      <td>round effects for round 4</td>\n      <td>-1.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>delta_5</th>\n      <td>0.00</td>\n      <td>round effects for round 5</td>\n      <td>-1.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>delta_6</th>\n      <td>0.00</td>\n      <td>round effects for round 6</td>\n      <td>-1.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>delta_7</th>\n      <td>0.00</td>\n      <td>round effects for round 7</td>\n      <td>-1.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>delta_8</th>\n      <td>0.00</td>\n      <td>round effects for round 8</td>\n      <td>-1.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>delta_9</th>\n      <td>0.00</td>\n      <td>round effects for round 9</td>\n      <td>-1.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>delta_10</th>\n      <td>0.00</td>\n      <td>round effects for round 10</td>\n      <td>-1.0</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nRegarding the selection of the bounds, the authors do not provide any decision rule, however they do run the estimation with different specifications. From their Matlab codes the upper and lower bounds of the values of their preffered specification can be extracted. The bounds are configured for estimation with *estimagic*. Setting bounds is a decisive factor in the success of optimization. Structural models usually provide sufficient information in order to select sensible bounds. The starting trial values are the mean between the bounds with the round effects, set at zero, being the exception. The cost parameter $b$ reported in the table below sticks out but since it is part of the cost of effort function: \n\n\\begin{equation}\nC_2(e_{2,n,r}) = be_{2,n,r} + \\frac{c_{n,r}e_{2,n,r}^{2}}{2}\n\\end{equation}\n\nwhere the mean effort choices are between 20 and 30 correctly positioned sliders, this seems reasonable. \n\n### Method of Simulated Moments\n\nThe parameter of interest are estimated by the **Method of Simulated Moments (MSM)** that was pioneered by McFadden (1989) and by Pakes and Pollard (1989). The idea is, similar to the Generalized Method of Moments (GMM), to use a vector of moments M with $k \\geq 17$, where every included moment is dependent on the endogenous variables. The step that differentiates MSM from GMM is the use of simulated samples. In each of the S simulated sample the Second Mover face the same prizes and First Mover effort as observed in the actual sample. The behavior of the Second Movers in the simulated sample is guided by the trial  $\\theta_t$ values of the unknown parameters $\\theta$. The unobservables $\\mu$ and $\\pi$ are assigned to the Second Movers with the specified distributions. \n\nFor all Second Movers and each round the utility for all 49 possible effort choices is computed and the simulated action corresponds to the effort choice with the highest achieved utility. In order to compare the simulated samples to the experimental sample the vector of moments $M_s(\\theta_t)$ are computed. These moments are used in the following metric:\n\n\\begin{equation*}\nJ(\\theta_t) =  \\left(M - \\frac{1}{S} \\sum\\limits_{S=1}^S M_S(\\theta_t)\\right)'W_N\\left(M - \\frac{1}{S} \\sum\\limits_{S=1}^S M_S(\\theta_t)\\right) \n\\end{equation*}\n\nThis is the core function of the MSM approach. The objective of this metric is $J(\\theta_t): \\hat\\theta = arg min_{\\theta_t} J(\\theta_t)$. It minimizes the distance between the average of the simulated moments and the empirical moments **M**. Thus, the moments induced by the structural parameters have to be as close to the actual moments as possible. $W_N$ is the weighting matrix of $k \\times k$ dimension. For this simulation, the authors specify the diagonal elements of the weigthing matrix as the inverse of N times the bootstrapped variance of the moments and zeroes on the non-diagonal elements. In total, 38 moments are used to estimate the 17 unknown parameters.   \n\n<div class=\"alert alert-block alert-warning\">\n    <b>Note:</b> The following attempt of implementation follows the steps outlined by the respy documentation closely.  \n</div>\n\n### Empirical Moments\n\nIn order to estimate the parameters that are of interest, moments need to be simulated. A dataframe fashioned after Table 4 is provided below. It gives an overview over the moments the authors choose to be estimated. \n\n<div class=\"alert alert-block alert-success\">\n    <b>Replication</b> of the descriptions in Table 4.\n</div>\n\n\n```python\nprint('Table 7: Description of the moments')\nmoments_description()\n```\n\n    Table 7: Description of the moments\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>comment</th>\n    </tr>\n    <tr>\n      <th>name</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>effort_std</th>\n      <td>standard deviation of effort</td>\n    </tr>\n    <tr>\n      <th>autocorrelation_l1</th>\n      <td>autocorrelation with lag 1</td>\n    </tr>\n    <tr>\n      <th>autocorrelation_l2</th>\n      <td>autocorrelation with lag 2</td>\n    </tr>\n    <tr>\n      <th>round_change_std</th>\n      <td>standard deviation of round-round change of effort</td>\n    </tr>\n    <tr>\n      <th>period_average</th>\n      <td>average effort in period i</td>\n    </tr>\n    <tr>\n      <th>cond_corr_e2_prize</th>\n      <td>correlation of e2 and prize, conditional on control effects</td>\n    </tr>\n    <tr>\n      <th>cond_corr_e2_e1</th>\n      <td>correlation of e2 and e1, conditional on control effects</td>\n    </tr>\n    <tr>\n      <th>cond_corr_e2_e1timesprize</th>\n      <td>correlation of e2 and e1 * prize, conditional on control effects</td>\n    </tr>\n    <tr>\n      <th>j_perc_cond_corr_e2_prize</th>\n      <td>jth percentile of cond. correlation e1 and prize of specific effects</td>\n    </tr>\n    <tr>\n      <th>j_perc_cond_corr_e2_e1</th>\n      <td>jth percentile of cond. correlation e1 and e2 of specific effects</td>\n    </tr>\n    <tr>\n      <th>j_perc_cond_corr_e2_e1timesprize</th>\n      <td>jth percentile of cond. correlation e2 and e1 * prize of specific effects</td>\n    </tr>\n    <tr>\n      <th>low_effort_low_prize</th>\n      <td>effort conditional on low e1 and low prizes</td>\n    </tr>\n    <tr>\n      <th>low_effort_high_prize</th>\n      <td>effort conditional on low e1 and high prizes</td>\n    </tr>\n    <tr>\n      <th>high_effort_low_prize</th>\n      <td>effort conditional on high e1 and low prizes</td>\n    </tr>\n    <tr>\n      <th>high_effort_high_prize</th>\n      <td>effort conditional on high e1 and high prizes</td>\n    </tr>\n    <tr>\n      <th>low_effort_prop</th>\n      <td>probability of low effort</td>\n    </tr>\n    <tr>\n      <th>high_effort_prop</th>\n      <td>probability of high effort</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThe functions needed for the estimation of those moments are found in the *auxiliary/msm.py*-file. They are stored in the dictionary to access them later. For all those moments separate functions are used, eventhough some functions have similarities with each other. This was done to follow the guides outlined on the *respy* website as closely as possible. Yet, one difference is that in this situation the moments are computed for the whole sample, whereas the *respy* outline computes them at a period level. \n\n\n```python\ncalc_moments = {\n    'effort_std': effort_std,\n    'corr_round_lag1': pooled_autocorr_lag1,\n    'corr_round_lag2': pooled_autocorr_lag2,\n    'round_change_std': round_change_std,\n    'mean_period_1': period1_average,\n    'mean_period_2': period2_average,\n    'mean_period_3': period3_average,\n    'mean_period_4': period4_average,\n    'mean_period_5': period5_average,\n    'mean_period_6': period6_average,\n    'mean_period_7': period7_average,\n    'mean_period_8': period8_average,\n    'mean_period_9': period9_average,\n    'mean_period_10': period10_average,\n    'cond_corr_e2_prize': cond_corr_e2_prize,\n    'cond_corr_e2_e1': cond_corr_e2_e1,\n    'cond_corr_e2_e1timesprize': cond_corr_e2_e1timesprize,\n    'perc17_cond_corr_e2_prize': perc17_cond_corr_e2_prize,\n    'perc33_cond_corr_e2_prize': perc33_cond_corr_e2_prize,\n    'perc50_cond_corr_e2_prize': perc50_cond_corr_e2_prize,\n    'perc66_cond_corr_e2_prize': perc66_cond_corr_e2_prize,\n    'perc83_cond_corr_e2_prize': perc83_cond_corr_e2_prize,\n    'perc17_cond_corr_e2_e1': perc17_cond_corr_e2_e1,\n    'perc33_cond_corr_e2_e1': perc33_cond_corr_e2_e1,\n    'perc50_cond_corr_e2_e1': perc50_cond_corr_e2_e1,\n    'perc66_cond_corr_e2_e1': perc66_cond_corr_e2_e1,\n    'perc83_cond_corr_e2_e1': perc83_cond_corr_e2_e1,\n    'perc17_cond_corr_e2_e1timesprize': perc17_cond_corr_e2_e1timesprize,\n    'perc33_cond_corr_e2_e1timesprize': perc33_cond_corr_e2_e1timesprize,\n    'perc50_cond_corr_e2_e1timesprize': perc50_cond_corr_e2_e1timesprize,\n    'perc66_cond_corr_e2_e1timesprize': perc66_cond_corr_e2_e1timesprize,\n    'perc83_cond_corr_e2_e1timesprize': perc83_cond_corr_e2_e1timesprize,\n    'low_effort_low_prize': low_effort_low_prize,\n    'low_effort_high_prize': low_effort_high_prize,\n    'high_effort_low_prize': high_effort_low_prize,\n    'high_effort_high_prize': high_effort_high_prize,\n    'low_effort_prop': low_effort_prop,\n    'high_effort_prop': high_effort_prop\n}\n```\n\nThese function, in turn, are used to calculate the empirical moments. These are the moments that are computed with the experimental sample without any simulation. They are found below.  \n\n<div class=\"alert alert-block alert-success\">\n    <b>Replication</b> of the observed moments in Table 5.\n</div>\n\n\n```python\nempirical_moments = observed_moments(df_2_pref)\nempirical_moments\n```\n\n\n\n\n    {'effort_std': 5.8745832443237305,\n     'corr_round_lag1': 0.6523300435833547,\n     'corr_round_lag2': 0.5955089258400272,\n     'round_change_std': 4.82824351834171,\n     'mean_period_1': 21.762712478637695,\n     'mean_period_2': 23.457626342773438,\n     'mean_period_3': 24.830509185791016,\n     'mean_period_4': 25.20339012145996,\n     'mean_period_5': 25.11864471435547,\n     'mean_period_6': 24.898305892944336,\n     'mean_period_7': 25.762712478637695,\n     'mean_period_8': 26.169490814208984,\n     'mean_period_9': 26.25423812866211,\n     'mean_period_10': 26.72881317138672,\n     'cond_corr_e2_prize': 0.12361415759953642,\n     'cond_corr_e2_e1': 0.04149206717166187,\n     'cond_corr_e2_e1timesprize': -0.09501348232241316,\n     'perc17_cond_corr_e2_prize': -0.2749740360569023,\n     'perc33_cond_corr_e2_prize': 0.03305363732319229,\n     'perc50_cond_corr_e2_prize': 0.22225342393899755,\n     'perc66_cond_corr_e2_prize': 0.3876273607645051,\n     'perc83_cond_corr_e2_prize': 0.46911122033916214,\n     'perc17_cond_corr_e2_e1': -0.32799713935543484,\n     'perc33_cond_corr_e2_e1': -0.2179878357116517,\n     'perc50_cond_corr_e2_e1': 0.019100550720606655,\n     'perc66_cond_corr_e2_e1': 0.17869322920672392,\n     'perc83_cond_corr_e2_e1': 0.3609552623371953,\n     'perc17_cond_corr_e2_e1timesprize': -0.1943010508973714,\n     'perc33_cond_corr_e2_e1timesprize': 0.01887267598522453,\n     'perc50_cond_corr_e2_e1timesprize': 0.14626187907883428,\n     'perc66_cond_corr_e2_e1timesprize': 0.2982281135137103,\n     'perc83_cond_corr_e2_e1timesprize': 0.47429080067835255,\n     'low_effort_low_prize': 23.821428298950195,\n     'low_effort_high_prize': 25.485294342041016,\n     'high_effort_low_prize': 25.8360652923584,\n     'high_effort_high_prize': 25.049999237060547,\n     'low_effort_prop': 0.0288135593220339,\n     'high_effort_prop': 0.015254237288135594}\n\n\n\n<div class=\"alert alert-block alert-warning\">\n    <b>Note:</b> Some moments were not precisely specified in Table 4. The different computation specifications for these moments can be found in the Appendix.\n</div>\n\n### Weighting Matrix\n\nThe weighting matrix is important to account for differences in magnitude between the moments. It assigns each moment a different weight and hence controls the importance the optimizing function gives to each moment. In the paper it is specified that the diagonal elements of the weighting matrix are the inverse of N times the variances of the sample moments and zeros elsewhere. 2000 Bootstrap samples with replacement are used to compute $W_n$. For my weighting matrix, I am orienting myself at the example [here](https://respy.readthedocs.io/en/latest/how_to_guides/msm_estimation_exercise.html), where the diagonal elements are the inverse variance of the bootstrapped moments. The function needed to be adapted to suit the objects in this notebook. For example, bootstrap sampling is used with replacement because the observed sample is small. Given cell timeout constraints with Travis CI, only 20 bootstrap samples are used to compute the weighting matrix. I'd suggest running the function with atleast 100 bootstraped samples, if possible.\n\n<div class=\"alert alert-block alert-warning\">\n    <b>Note:</b> The following functions are still at a premature stage.\n</div>\n\n\n```python\nstart = datetime.now()\nweighting_matrix = get_weighting_matrix(\n   data=df_2_pref,\n   empirical_moments=empirical_moments,\n   calc_moments=calc_moments,\n   n_bootstrap_samples=20,\n   n_observations_per_sample=59,\n   replace_missing_variances=None)\nend = datetime.now()\ntime_taken = end - start\nprint(time_taken)\n```\n\n    0:00:32.065119\n\n\n\n```python\nweighting_matrix\n```\n\n\n\n\n    array([[8.04287763e+00, 0.00000000e+00, 0.00000000e+00, ...,\n            0.00000000e+00, 0.00000000e+00, 0.00000000e+00],\n           [0.00000000e+00, 3.60573471e+02, 0.00000000e+00, ...,\n            0.00000000e+00, 0.00000000e+00, 0.00000000e+00],\n           [0.00000000e+00, 0.00000000e+00, 1.60206819e+02, ...,\n            0.00000000e+00, 0.00000000e+00, 0.00000000e+00],\n           ...,\n           [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, ...,\n            7.21242976e-01, 0.00000000e+00, 0.00000000e+00],\n           [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, ...,\n            0.00000000e+00, 1.75150514e+04, 0.00000000e+00],\n           [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, ...,\n            0.00000000e+00, 0.00000000e+00, 2.40707560e+04]])\n\n\n\n### Simulation\n\nAs I mentioned above, I was not able to replicate the Method of Simulated Moments. Yet, I was able to get the simulation running. In the simulation below, first the effort choices are simulated induced by the prespecified trial values. For each subjects and round every possible effort choices is simulated and the utility maximizing choice is drawn. Then, using these choices the moments are computed. Finally, they are added together and divided by the number of simulations.  \n\n\n```python\nparams = params_description()\nsimulated_moments = get_simulated_moments(df=df_2_pref, params=params, calc_moments=calc_moments, empirical_moments=empirical_moments, num_simulation=2, seed=123)\nsimulated_moments.round(3)\n```\n\n    /Users/vincentselz/opt/anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py:205: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame\n    \n    See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      self._setitem_with_indexer(indexer, value)\n\n\n\n\n\n    effort_std                          2.217 \n    corr_round_lag1                     0.457 \n    corr_round_lag2                     0.437 \n    round_change_std                    2.318 \n    mean_period_1                       11.364\n    mean_period_2                       11.203\n    mean_period_3                       11.407\n    mean_period_4                       11.068\n    mean_period_5                       11.212\n    mean_period_6                       11.178\n    mean_period_7                       11.263\n    mean_period_8                       11.025\n    mean_period_9                       11.297\n    mean_period_10                      11.322\n    cond_corr_e2_prize                  0.056 \n    cond_corr_e2_e1                     0.057 \n    cond_corr_e2_e1timesprize          -0.057 \n    perc17_cond_corr_e2_prize          -0.352 \n    perc33_cond_corr_e2_prize          -0.199 \n    perc50_cond_corr_e2_prize          -0.012 \n    perc66_cond_corr_e2_prize           0.173 \n    perc83_cond_corr_e2_prize           0.394 \n    perc17_cond_corr_e2_e1             -0.403 \n    perc33_cond_corr_e2_e1             -0.148 \n    perc50_cond_corr_e2_e1              0.039 \n    perc66_cond_corr_e2_e1              0.196 \n    perc83_cond_corr_e2_e1              0.384 \n    perc17_cond_corr_e2_e1timesprize   -0.377 \n    perc33_cond_corr_e2_e1timesprize   -0.158 \n    perc50_cond_corr_e2_e1timesprize    0.026 \n    perc66_cond_corr_e2_e1timesprize    0.134 \n    perc83_cond_corr_e2_e1timesprize    0.379 \n    low_effort_low_prize                11.167\n    low_effort_high_prize               11.478\n    high_effort_low_prize               11.541\n    high_effort_high_prize              11.281\n    low_effort_prop                     0.931 \n    high_effort_prop                    0.000 \n    dtype: float64\n\n\n\nThankfully, the moments provide a good overview of what went wrong in the simulation. It appears in general the level of efforts are too low in the simulated samples. As can be seen in the last row not even one simulated effort was above 35 correctly placed sliders. In addition to that the variance is lower than in the original sample. To optimize these values is precisely the task of the MSM. It chooses such parameter values that the simulated moments fit the empirical moments as closely as possible. The actual simulation runs 30 times, thus simulating 17,700 pairings. Here, the simulation is run only 2 times because of the cell timeout. I'd suggest using atleast 10 simulations.\n\n### Further Steps\n\nThe framework from above now can be used to construct the criterion function. Here, my contribution ends. In order to elicit the optimal parameter values the above mentioned criterion function $J(\\theta_t)$ is used. The simulation depends on three different random draws, which are held constant throughout the estimation. This ensures that as the parameter values $\\theta_t$ are adjusted, the simulated samples only vary due to changes in $\\theta_t$ and not due to the exogenously induced random draws. Due to the discrete nature of the optimization, the authors opt to use Simulated Annealing (1994) instead of gradient or Hessian-based optimization methods to solve for the MSM estimates.     \n\n---\n# Critical Assessment\n---\nThe saying is that when having a well designed experiment, the following empirical analysis is straight forward. This study turns this saying around and shows that structural models can help overcome difficulties in identifying causal effects. In this experiment, results of the reduced form evidence provided little to no evidence for disappointment aversion. The interaction term between First Mover effort and prize was significant but the main variable of interest, the sole First Mover effort, was not. Here, the use of structural estimation salvaged the situation.   \n\nIn general, I argue that the experiment was not well suited for the identification. The highly significant dummy variables for round effects in the reduced form analysis, suggest that the design did pick up various confounds that were not intended. The significant negative $\\delta_r$ in the structural estimation corroborates that learning, in fact, did take place through the paying rounds. The experimenters set up two training rounds, yet it appears this was not enough. Expanding the training rounds might help filter these confounds out of the experimental sample. \n\nThe empirical analysis by the authors is sound and well justified. Yet, I do not agree with their assessment that the reduced form analysis offers evidence consistent with disappointment aversion. For this to be the case the impact of $e_1$ on $e_2$ has to be significantly lower than zero which is not true. In their structural model they test various specifications that would favor explanations other than disappointment aversion for the observed behavior. Unfortunately, I was not able to reproduce the MSM, else I could have commented more extensively on the intrinsics of those specifications.\n\nFrom a experimenter's perspective the study supplies a novel approach to real effort tasks. The slider task provides a convincing method to elicit finely grained discrete effort choices. Yet, for a sample of N subjects 2N need to be paid, since the First Movers also need to be compensated - this appears to be cost-inefficient. Potentially, similar to the training round, the First Mover effort can be simulated making the double payments redundant. Of course, it remains to be seen whether the knowledge of having a tournament with a real person has an effect on the Second Mover. \n\nThe primary contribution by this paper is twofold. First, it anwers the question what an agent's reference point constitutes. In line with Abeler (2011), their evidence suggests that the reference points is given by the expected reference point as the model of reference-dependent preferences predicts. Furthermore, the structural analysis allows them to estimate the strength of loss-aversion around the reference point and provides estimates about the heterogeneity of disappointment aversion in the underlying population. Since their model does not fix the reference point at the point of optimization, as the parsimonious model of reference-dependent preferences does, this makes the observed behavior applicable to the situation where the agents can affect their probability of success e.g. competing about promotions. Second, the paper contributes to the discussion about how quickly reference points form. Given that the Second Mover almost immediately observes the First Mover's effort choice and optimizes her behavior, it indicates that reference points form instantly.  \n\n---\n# Appendix\n---\n\n## Effort Distribution Per Round\n\n\n```python\neffort_distr_per_round(df_2_pref)\nprint('Figure 6: Effort Distribution Per Round')\n```\n\n## Prize Distribution\n\nThe authors state that the prizes for the tournament are drawn from a uniform distribution. An inspection shows the randomization is successful. The visualization but more importantly the $\\chi^2$-Test confirms that it is not significantly different from a uniform distribution.\n\n\n```python\nprize_distribution(df_2_pref)\nprint('Figure 7: Prize Distribution')\n```\n\n\n```python\nchisquare(df_2_pref['prize'])\n```\n\n\n\n\n    Power_divergenceResult(statistic=361.38135, pvalue=0.9999999999999948)\n\n\n\n## Moment Computation Specifications\n\nAs mentioned above, the description in Table 4 sometimes do not match the used computation methods or the description is not specific enough to replicate the solution. Here, I set out how the original results can still be obtained.  \n\nFirst, the conditional means in the table are misspecified. Whereas Table 4 states that the specified effort and prizes need to be strictly higher or lower, their Matlab function uses non-strict inequality. The respective functions can be found in the subdirectory MatLabCode under moments.m line 168 and following. They use the *sign* function to indicate when prices are higher or efforts are higher thant the respective threshold, then subsequently delete them. Yet, this still leaves the Second Mover efforts that are equal to the threshold in the sample.\n\nSecond, for the autocorrelation the authors use the pooled autocorrelation. First, all differences from round r-1 to round r are computed and then the correlation is calculated. The implicit assumption here is that that the variances on the subject-level are equal. In turn, the pooled sample variance decreases the denominator, leading to higher autocorrelation estimates. The alternative is to compute the autocorrelations separately for each subject and to use the mean of these correlations:  \n\n\n```python\nstat1 = pooled_autocorr_lag1(df_2_pref)\nstat2 = calc_autocorrelation_lag1(df_2_pref)\n\nprint('The different autocorrelation specifications: \\n')\nprint(f'Reported Autocorrelation: {stat1:0.3f} Mean Autocorrelation: {stat2:0.3f}')\n```\n\n    The different autocorrelation specifications: \n    \n    Reported Autocorrelation: 0.652 Mean Autocorrelation: 0.123\n\n\nThird, the reported percentile results are not compatible with the standard behavior by *np.percentile* or *pandas.quantile*. Instead, it needs to be specified that the interpolation method selects the lower of the two value, when the true percentile lies between two values. \n\n# References \n\n* **Abeler, Johannes, Armin Falk, Lorenz Goette, and David Huffman. 2011.** Reference Points and Effort Provision. American Economic Review, 101(2): 470\u201392.\n* **Cooper, Russell, Douglas V. DeJong, Robert Forsythe, and Thomas W. Ross. 1996.** Cooperation without Reputation: Experimental Evidence from Prisoner\u2019s Dilemma Games. \nGames and Economic Behavior, 12(2): 187\u2013218.\n* **Falk, Armin, and Andrea Ichino. 2006.** Clean Evidence on Peer Effects.\u201d Journal of Labor Economics, 24(1): 39\u201357.\n* **Fehr, Ernst and Klaus M. Schmidt. 1999.** A Theory of Fairness, Competition, and Cooperation. The Quarterly Journal of Economics. Volume 114, Issue 3. Pages 817\u2013868\n* **Gabler, Janos and Tobias Raabe. 2020.** respy - A Framework for the Simulation and Estimation of Eckstein-Keane-Wolpin Models. \n[https://github.com/OpenSourceEconomics/respy](https://github.com/OpenSourceEconomics/respy)\n* **Gill, David, and Victoria Prowse. 2012.** A Structural Analysis of Disappointment Aversion in a Real Effort Competition. American Economic Review, 102 (1): 469-503.\n* **Goffe, William L., Gary D. Ferrier, and John Rogers. 1994.** Global Optimization of Statistical Functions with Simulated Annealing. Journal of Econometrics, 60(1\u20132): 65\u201399.\n* **Kahneman, Daniel, and Amos Tversky. 1979.** Prospect Theory: An Analysis of Decision under Risk. Econometrica, 47(2): 263\u201391.\n* **Koszegi, Botond and Matthew Rabin. 2006.** A Model of Reference-Dependent Preferences, \nThe Quarterly Journal of Economics, 121, issue 4, p. 1133-1165. \n* **McFadden, Daniel. 1989.** A Method of Simulated Moments for Estimation of Discrete Response Models Without Numerical Integration. \nEconometrica, 57(5), 995-1026.\n* **Pakes, Ariel and David Pollard. 1989.** Simulation and the Asymptotics of Optimization Estimators. \nEconometrica, 57(5), 1027-1057.\n", "meta": {"hexsha": "5b3cc520c1f20760fa12112ebc05605fdafb1bc6", "size": 258124, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Project-VincentSelz.ipynb", "max_stars_repo_name": "VincentSelz/microeconometrics-course-project-VincentSelz", "max_stars_repo_head_hexsha": "4e34fffdb5a26d0f3d0904bc709ab070c27fe060", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Project-VincentSelz.ipynb", "max_issues_repo_name": "VincentSelz/microeconometrics-course-project-VincentSelz", "max_issues_repo_head_hexsha": "4e34fffdb5a26d0f3d0904bc709ab070c27fe060", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Project-VincentSelz.ipynb", "max_forks_repo_name": "VincentSelz/microeconometrics-course-project-VincentSelz", "max_forks_repo_head_hexsha": "4e34fffdb5a26d0f3d0904bc709ab070c27fe060", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 112.1790525858, "max_line_length": 27568, "alphanum_fraction": 0.785041298, "converted": true, "num_tokens": 20790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.08269733645795115, "lm_q1q2_score": 0.0365251811538421}}
{"text": "# Mammal sleep\n# \u0e28\u0e36\u0e01\u0e29\u0e32\u0e01\u0e32\u0e23\u0e19\u0e2d\u0e19\u0e02\u0e2d\u0e07\u0e2a\u0e31\u0e15\u0e27\u0e4c\u0e40\u0e25\u0e35\u0e49\u0e22\u0e07\u0e25\u0e39\u0e01\u0e14\u0e49\u0e27\u0e22\u0e19\u0e21\nhttps://en.wikipedia.org/wiki/Mammal\n\n\n```python\nfrom IPython.display import HTML, YouTubeVideo, IFrame\n```\n\n\n```python\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\n\n```python\ndf=pd.read_csv('https://github.com/prasertcbs/tutorial/raw/master/msleep.csv', nrows=10)\ndf[:10]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>name</th>\n      <th>genus</th>\n      <th>vore</th>\n      <th>order</th>\n      <th>conservation</th>\n      <th>sleep_total</th>\n      <th>sleep_rem</th>\n      <th>sleep_cycle</th>\n      <th>awake</th>\n      <th>brainwt</th>\n      <th>bodywt</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>Cheetah</td>\n      <td>Acinonyx</td>\n      <td>carni</td>\n      <td>Carnivora</td>\n      <td>lc</td>\n      <td>12.1</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>11.9</td>\n      <td>NaN</td>\n      <td>50.000</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>Owl monkey</td>\n      <td>Aotus</td>\n      <td>omni</td>\n      <td>Primates</td>\n      <td>NaN</td>\n      <td>17.0</td>\n      <td>1.8</td>\n      <td>NaN</td>\n      <td>7.0</td>\n      <td>0.01550</td>\n      <td>0.480</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>Mountain beaver</td>\n      <td>Aplodontia</td>\n      <td>herbi</td>\n      <td>Rodentia</td>\n      <td>nt</td>\n      <td>14.4</td>\n      <td>2.4</td>\n      <td>NaN</td>\n      <td>9.6</td>\n      <td>NaN</td>\n      <td>1.350</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>Greater short-tailed shrew</td>\n      <td>Blarina</td>\n      <td>omni</td>\n      <td>Soricomorpha</td>\n      <td>lc</td>\n      <td>14.9</td>\n      <td>2.3</td>\n      <td>0.133333</td>\n      <td>9.1</td>\n      <td>0.00029</td>\n      <td>0.019</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>Cow</td>\n      <td>Bos</td>\n      <td>herbi</td>\n      <td>Artiodactyla</td>\n      <td>domesticated</td>\n      <td>4.0</td>\n      <td>0.7</td>\n      <td>0.666667</td>\n      <td>20.0</td>\n      <td>0.42300</td>\n      <td>600.000</td>\n    </tr>\n    <tr>\n      <td>5</td>\n      <td>Three-toed sloth</td>\n      <td>Bradypus</td>\n      <td>herbi</td>\n      <td>Pilosa</td>\n      <td>NaN</td>\n      <td>14.4</td>\n      <td>2.2</td>\n      <td>0.766667</td>\n      <td>9.6</td>\n      <td>NaN</td>\n      <td>3.850</td>\n    </tr>\n    <tr>\n      <td>6</td>\n      <td>Northern fur seal</td>\n      <td>Callorhinus</td>\n      <td>carni</td>\n      <td>Carnivora</td>\n      <td>vu</td>\n      <td>8.7</td>\n      <td>1.4</td>\n      <td>0.383333</td>\n      <td>15.3</td>\n      <td>NaN</td>\n      <td>20.490</td>\n    </tr>\n    <tr>\n      <td>7</td>\n      <td>Vesper mouse</td>\n      <td>Calomys</td>\n      <td>NaN</td>\n      <td>Rodentia</td>\n      <td>NaN</td>\n      <td>7.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>17.0</td>\n      <td>NaN</td>\n      <td>0.045</td>\n    </tr>\n    <tr>\n      <td>8</td>\n      <td>Dog</td>\n      <td>Canis</td>\n      <td>carni</td>\n      <td>Carnivora</td>\n      <td>domesticated</td>\n      <td>10.1</td>\n      <td>2.9</td>\n      <td>0.333333</td>\n      <td>13.9</td>\n      <td>0.07000</td>\n      <td>14.000</td>\n    </tr>\n    <tr>\n      <td>9</td>\n      <td>Roe deer</td>\n      <td>Capreolus</td>\n      <td>herbi</td>\n      <td>Artiodactyla</td>\n      <td>lc</td>\n      <td>3.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>21.0</td>\n      <td>0.09820</td>\n      <td>14.800</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Display Web page\n\n\n```python\nIFrame('https://www.yru.ac.th/th', width=800, height=450)\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\nIFrame('https://th.wikipedia.org/wiki/\u0e2a\u0e31\u0e15\u0e27\u0e4c\u0e40\u0e25\u0e35\u0e49\u0e22\u0e07\u0e25\u0e39\u0e01\u0e14\u0e49\u0e27\u0e22\u0e19\u0e49\u0e33\u0e19\u0e21', width=800, height=450)\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\nIFrame('https://en.wikipedia.org/wiki/Mammal', width=800, height=450)\n```\n\n\n\n\n\n\n\n\n\n\n## Display PDF\nhttps://www.datacamp.com/community/data-science-cheatsheets\n\n\n```python\nIFrame('http://www.africau.edu/images/default/sample.pdf', width=800, height=900)\n```\n\n\n\n\n\n\n\n\n\n\n## \u0e40\u0e23\u0e37\u0e2d\u0e1e\u0e23\u0e30\u0e17\u0e35\u0e48\u0e19\u0e31\u0e48\u0e07\u0e2a\u0e38\u0e1e\u0e23\u0e23\u0e13\u0e2b\u0e07\u0e2a\u0e4c\n\n\n\n\n```python\ndf.style.highlight_max(subset=['sleep_total'], color='deepskyblue').highlight_min(subset=['sleep_total'], color='tan')\n```\n\n\n\n\n<style  type=\"text/css\" >\n    #T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow1_col5 {\n            background-color:  deepskyblue;\n            : ;\n        }    #T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow9_col5 {\n            : ;\n            background-color:  tan;\n        }</style><table id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aee\" ><thead>    <tr>        <th class=\"blank level0\" ></th>        <th class=\"col_heading level0 col0\" >name</th>        <th class=\"col_heading level0 col1\" >genus</th>        <th class=\"col_heading level0 col2\" >vore</th>        <th class=\"col_heading level0 col3\" >order</th>        <th class=\"col_heading level0 col4\" >conservation</th>        <th class=\"col_heading level0 col5\" >sleep_total</th>        <th class=\"col_heading level0 col6\" >sleep_rem</th>        <th class=\"col_heading level0 col7\" >sleep_cycle</th>        <th class=\"col_heading level0 col8\" >awake</th>        <th class=\"col_heading level0 col9\" >brainwt</th>        <th class=\"col_heading level0 col10\" >bodywt</th>    </tr></thead><tbody>\n                <tr>\n                        <th id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeelevel0_row0\" class=\"row_heading level0 row0\" >0</th>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow0_col0\" class=\"data row0 col0\" >Cheetah</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow0_col1\" class=\"data row0 col1\" >Acinonyx</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow0_col2\" class=\"data row0 col2\" >carni</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow0_col3\" class=\"data row0 col3\" >Carnivora</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow0_col4\" class=\"data row0 col4\" >lc</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow0_col5\" class=\"data row0 col5\" >12.1</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow0_col6\" class=\"data row0 col6\" >nan</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow0_col7\" class=\"data row0 col7\" >nan</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow0_col8\" class=\"data row0 col8\" >11.9</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow0_col9\" class=\"data row0 col9\" >nan</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow0_col10\" class=\"data row0 col10\" >50</td>\n            </tr>\n            <tr>\n                        <th id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeelevel0_row1\" class=\"row_heading level0 row1\" >1</th>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow1_col0\" class=\"data row1 col0\" >Owl monkey</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow1_col1\" class=\"data row1 col1\" >Aotus</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow1_col2\" class=\"data row1 col2\" >omni</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow1_col3\" class=\"data row1 col3\" >Primates</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow1_col4\" class=\"data row1 col4\" >nan</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow1_col5\" class=\"data row1 col5\" >17</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow1_col6\" class=\"data row1 col6\" >1.8</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow1_col7\" class=\"data row1 col7\" >nan</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow1_col8\" class=\"data row1 col8\" >7</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow1_col9\" class=\"data row1 col9\" >0.0155</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow1_col10\" class=\"data row1 col10\" >0.48</td>\n            </tr>\n            <tr>\n                        <th id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeelevel0_row2\" class=\"row_heading level0 row2\" >2</th>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow2_col0\" class=\"data row2 col0\" >Mountain beaver</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow2_col1\" class=\"data row2 col1\" >Aplodontia</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow2_col2\" class=\"data row2 col2\" >herbi</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow2_col3\" class=\"data row2 col3\" >Rodentia</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow2_col4\" class=\"data row2 col4\" >nt</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow2_col5\" class=\"data row2 col5\" >14.4</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow2_col6\" class=\"data row2 col6\" >2.4</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow2_col7\" class=\"data row2 col7\" >nan</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow2_col8\" class=\"data row2 col8\" >9.6</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow2_col9\" class=\"data row2 col9\" >nan</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow2_col10\" class=\"data row2 col10\" >1.35</td>\n            </tr>\n            <tr>\n                        <th id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeelevel0_row3\" class=\"row_heading level0 row3\" >3</th>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow3_col0\" class=\"data row3 col0\" >Greater short-tailed shrew</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow3_col1\" class=\"data row3 col1\" >Blarina</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow3_col2\" class=\"data row3 col2\" >omni</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow3_col3\" class=\"data row3 col3\" >Soricomorpha</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow3_col4\" class=\"data row3 col4\" >lc</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow3_col5\" class=\"data row3 col5\" >14.9</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow3_col6\" class=\"data row3 col6\" >2.3</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow3_col7\" class=\"data row3 col7\" >0.133333</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow3_col8\" class=\"data row3 col8\" >9.1</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow3_col9\" class=\"data row3 col9\" >0.00029</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow3_col10\" class=\"data row3 col10\" >0.019</td>\n            </tr>\n            <tr>\n                        <th id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeelevel0_row4\" class=\"row_heading level0 row4\" >4</th>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow4_col0\" class=\"data row4 col0\" >Cow</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow4_col1\" class=\"data row4 col1\" >Bos</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow4_col2\" class=\"data row4 col2\" >herbi</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow4_col3\" class=\"data row4 col3\" >Artiodactyla</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow4_col4\" class=\"data row4 col4\" >domesticated</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow4_col5\" class=\"data row4 col5\" >4</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow4_col6\" class=\"data row4 col6\" >0.7</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow4_col7\" class=\"data row4 col7\" >0.666667</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow4_col8\" class=\"data row4 col8\" >20</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow4_col9\" class=\"data row4 col9\" >0.423</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow4_col10\" class=\"data row4 col10\" >600</td>\n            </tr>\n            <tr>\n                        <th id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeelevel0_row5\" class=\"row_heading level0 row5\" >5</th>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow5_col0\" class=\"data row5 col0\" >Three-toed sloth</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow5_col1\" class=\"data row5 col1\" >Bradypus</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow5_col2\" class=\"data row5 col2\" >herbi</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow5_col3\" class=\"data row5 col3\" >Pilosa</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow5_col4\" class=\"data row5 col4\" >nan</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow5_col5\" class=\"data row5 col5\" >14.4</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow5_col6\" class=\"data row5 col6\" >2.2</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow5_col7\" class=\"data row5 col7\" >0.766667</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow5_col8\" class=\"data row5 col8\" >9.6</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow5_col9\" class=\"data row5 col9\" >nan</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow5_col10\" class=\"data row5 col10\" >3.85</td>\n            </tr>\n            <tr>\n                        <th id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeelevel0_row6\" class=\"row_heading level0 row6\" >6</th>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow6_col0\" class=\"data row6 col0\" >Northern fur seal</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow6_col1\" class=\"data row6 col1\" >Callorhinus</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow6_col2\" class=\"data row6 col2\" >carni</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow6_col3\" class=\"data row6 col3\" >Carnivora</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow6_col4\" class=\"data row6 col4\" >vu</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow6_col5\" class=\"data row6 col5\" >8.7</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow6_col6\" class=\"data row6 col6\" >1.4</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow6_col7\" class=\"data row6 col7\" >0.383333</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow6_col8\" class=\"data row6 col8\" >15.3</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow6_col9\" class=\"data row6 col9\" >nan</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow6_col10\" class=\"data row6 col10\" >20.49</td>\n            </tr>\n            <tr>\n                        <th id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeelevel0_row7\" class=\"row_heading level0 row7\" >7</th>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow7_col0\" class=\"data row7 col0\" >Vesper mouse</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow7_col1\" class=\"data row7 col1\" >Calomys</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow7_col2\" class=\"data row7 col2\" >nan</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow7_col3\" class=\"data row7 col3\" >Rodentia</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow7_col4\" class=\"data row7 col4\" >nan</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow7_col5\" class=\"data row7 col5\" >7</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow7_col6\" class=\"data row7 col6\" >nan</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow7_col7\" class=\"data row7 col7\" >nan</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow7_col8\" class=\"data row7 col8\" >17</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow7_col9\" class=\"data row7 col9\" >nan</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow7_col10\" class=\"data row7 col10\" >0.045</td>\n            </tr>\n            <tr>\n                        <th id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeelevel0_row8\" class=\"row_heading level0 row8\" >8</th>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow8_col0\" class=\"data row8 col0\" >Dog</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow8_col1\" class=\"data row8 col1\" >Canis</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow8_col2\" class=\"data row8 col2\" >carni</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow8_col3\" class=\"data row8 col3\" >Carnivora</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow8_col4\" class=\"data row8 col4\" >domesticated</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow8_col5\" class=\"data row8 col5\" >10.1</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow8_col6\" class=\"data row8 col6\" >2.9</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow8_col7\" class=\"data row8 col7\" >0.333333</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow8_col8\" class=\"data row8 col8\" >13.9</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow8_col9\" class=\"data row8 col9\" >0.07</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow8_col10\" class=\"data row8 col10\" >14</td>\n            </tr>\n            <tr>\n                        <th id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeelevel0_row9\" class=\"row_heading level0 row9\" >9</th>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow9_col0\" class=\"data row9 col0\" >Roe deer</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow9_col1\" class=\"data row9 col1\" >Capreolus</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow9_col2\" class=\"data row9 col2\" >herbi</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow9_col3\" class=\"data row9 col3\" >Artiodactyla</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow9_col4\" class=\"data row9 col4\" >lc</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow9_col5\" class=\"data row9 col5\" >3</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow9_col6\" class=\"data row9 col6\" >nan</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow9_col7\" class=\"data row9 col7\" >nan</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow9_col8\" class=\"data row9 col8\" >21</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow9_col9\" class=\"data row9 col9\" >0.0982</td>\n                        <td id=\"T_a2ed77b6_c6ce_11e9_94fb_2016b9d94aeerow9_col10\" class=\"data row9 col10\" >14.8</td>\n            </tr>\n    </tbody></table>\n\n\n\n\n```python\ndf['brain_body_ratio']=df.brainwt / df.bodywt\ndf\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>name</th>\n      <th>genus</th>\n      <th>vore</th>\n      <th>order</th>\n      <th>conservation</th>\n      <th>sleep_total</th>\n      <th>sleep_rem</th>\n      <th>sleep_cycle</th>\n      <th>awake</th>\n      <th>brainwt</th>\n      <th>bodywt</th>\n      <th>brain_body_ratio</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Cheetah</td>\n      <td>Acinonyx</td>\n      <td>carni</td>\n      <td>Carnivora</td>\n      <td>lc</td>\n      <td>12.1</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>11.9</td>\n      <td>NaN</td>\n      <td>50.000</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Owl monkey</td>\n      <td>Aotus</td>\n      <td>omni</td>\n      <td>Primates</td>\n      <td>NaN</td>\n      <td>17.0</td>\n      <td>1.8</td>\n      <td>NaN</td>\n      <td>7.0</td>\n      <td>0.01550</td>\n      <td>0.480</td>\n      <td>0.032292</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Mountain beaver</td>\n      <td>Aplodontia</td>\n      <td>herbi</td>\n      <td>Rodentia</td>\n      <td>nt</td>\n      <td>14.4</td>\n      <td>2.4</td>\n      <td>NaN</td>\n      <td>9.6</td>\n      <td>NaN</td>\n      <td>1.350</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Greater short-tailed shrew</td>\n      <td>Blarina</td>\n      <td>omni</td>\n      <td>Soricomorpha</td>\n      <td>lc</td>\n      <td>14.9</td>\n      <td>2.3</td>\n      <td>0.133333</td>\n      <td>9.1</td>\n      <td>0.00029</td>\n      <td>0.019</td>\n      <td>0.015263</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Cow</td>\n      <td>Bos</td>\n      <td>herbi</td>\n      <td>Artiodactyla</td>\n      <td>domesticated</td>\n      <td>4.0</td>\n      <td>0.7</td>\n      <td>0.666667</td>\n      <td>20.0</td>\n      <td>0.42300</td>\n      <td>600.000</td>\n      <td>0.000705</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>Three-toed sloth</td>\n      <td>Bradypus</td>\n      <td>herbi</td>\n      <td>Pilosa</td>\n      <td>NaN</td>\n      <td>14.4</td>\n      <td>2.2</td>\n      <td>0.766667</td>\n      <td>9.6</td>\n      <td>NaN</td>\n      <td>3.850</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Northern fur seal</td>\n      <td>Callorhinus</td>\n      <td>carni</td>\n      <td>Carnivora</td>\n      <td>vu</td>\n      <td>8.7</td>\n      <td>1.4</td>\n      <td>0.383333</td>\n      <td>15.3</td>\n      <td>NaN</td>\n      <td>20.490</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Vesper mouse</td>\n      <td>Calomys</td>\n      <td>NaN</td>\n      <td>Rodentia</td>\n      <td>NaN</td>\n      <td>7.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>17.0</td>\n      <td>NaN</td>\n      <td>0.045</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Dog</td>\n      <td>Canis</td>\n      <td>carni</td>\n      <td>Carnivora</td>\n      <td>domesticated</td>\n      <td>10.1</td>\n      <td>2.9</td>\n      <td>0.333333</td>\n      <td>13.9</td>\n      <td>0.07000</td>\n      <td>14.000</td>\n      <td>0.005000</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>Roe deer</td>\n      <td>Capreolus</td>\n      <td>herbi</td>\n      <td>Artiodactyla</td>\n      <td>lc</td>\n      <td>3.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>21.0</td>\n      <td>0.09820</td>\n      <td>14.800</td>\n      <td>0.006635</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf.query('vore==\"herbi\"')\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>name</th>\n      <th>genus</th>\n      <th>vore</th>\n      <th>order</th>\n      <th>conservation</th>\n      <th>sleep_total</th>\n      <th>sleep_rem</th>\n      <th>sleep_cycle</th>\n      <th>awake</th>\n      <th>brainwt</th>\n      <th>bodywt</th>\n      <th>brain_body_ratio</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2</th>\n      <td>Mountain beaver</td>\n      <td>Aplodontia</td>\n      <td>herbi</td>\n      <td>Rodentia</td>\n      <td>nt</td>\n      <td>14.4</td>\n      <td>2.4</td>\n      <td>NaN</td>\n      <td>9.6</td>\n      <td>NaN</td>\n      <td>1.35</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Cow</td>\n      <td>Bos</td>\n      <td>herbi</td>\n      <td>Artiodactyla</td>\n      <td>domesticated</td>\n      <td>4.0</td>\n      <td>0.7</td>\n      <td>0.666667</td>\n      <td>20.0</td>\n      <td>0.4230</td>\n      <td>600.00</td>\n      <td>0.000705</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>Three-toed sloth</td>\n      <td>Bradypus</td>\n      <td>herbi</td>\n      <td>Pilosa</td>\n      <td>NaN</td>\n      <td>14.4</td>\n      <td>2.2</td>\n      <td>0.766667</td>\n      <td>9.6</td>\n      <td>NaN</td>\n      <td>3.85</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>Roe deer</td>\n      <td>Capreolus</td>\n      <td>herbi</td>\n      <td>Artiodactyla</td>\n      <td>lc</td>\n      <td>3.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>21.0</td>\n      <td>0.0982</td>\n      <td>14.80</td>\n      <td>0.006635</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf['sleep_total'].hist(grid=False);\n```\n\n\n```python\ndf.vore.value_counts().plot.barh();\n```\n\n\n```python\ndf[['vore', 'sleep_total']].groupby('vore').mean().plot(kind='bar');\n```\n\n## Embed YouTube \n\n\n```python\n# https://www.youtube.com/watch?v=w-nPeOhEoyw\nYouTubeVideo('w-nPeOhEoyw', width=600, height=340)\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\nYouTubeVideo('bWlO_H4vuNw', width=600, height=340)\n```\n\n\n\n\n\n\n\n\n\n\n## LaTeX\n\nQuadratic equation\n$$x=\\frac{-b\\pm\\sqrt{b^2-4ac}}{2a}$$\n\n## Heart curve\nhttp://mathworld.wolfram.com/HeartCurve.html\n$$\\begin{align}\nx&=16sin^3(t)\\\\\ny&=13cos(t)-5cos(2t)-2cos(3t)-cos(4t)\n\\end{align}$$\n\n\n```python\ndef heart():\n    # http://mathworld.wolfram.com/HeartCurve.html\n    t = np.linspace(0, 2 * np.pi, 360)\n    # print(t)\n    x = 16 * np.sin(t) ** 3\n    y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)\n    plt.plot(x, y, color='pink')\n    plt.plot(x + 10, y)\n    plt.show()\n\ndef heart2():\n    # http://mathworld.wolfram.com/HeartCurve.html\n    t = np.linspace(0, 2 * np.pi, 360)\n    # print(t)\n    x = 16 * np.sin(t) ** 3\n    y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)\n    r = np.linspace(.1, 1, 5)\n    plt.text(0, 0, \"I \\u2764 Python\")\n\n    for n in r:\n        # plt.plot(x + n, y)\n        # plt.plot(x * n, y)\n        # plt.plot(x * n / 5, y)\n        plt.plot(x * n / 5, y * n / 5)\n    plt.show()\n```\n\n\n```python\nheart()\n```\n\n\n```python\nheart2()\n```\n", "meta": {"hexsha": "c633a0d40f63da6c80f8e14cb8e8d7e751538392", "size": 196082, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "learn_jupyter/0_jupyter overview.ipynb", "max_stars_repo_name": "langsari/ftu-artificial-intelligence", "max_stars_repo_head_hexsha": "fcfb2864f36639d4276d9519b421105d8ccd09d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "learn_jupyter/0_jupyter overview.ipynb", "max_issues_repo_name": "langsari/ftu-artificial-intelligence", "max_issues_repo_head_hexsha": "fcfb2864f36639d4276d9519b421105d8ccd09d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-06-08T22:21:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:48:11.000Z", "max_forks_repo_path": "learn_jupyter/0_jupyter overview.ipynb", "max_forks_repo_name": "langsari/ftu-artificial-intelligence", "max_forks_repo_head_hexsha": "fcfb2864f36639d4276d9519b421105d8ccd09d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 159.2867587327, "max_line_length": 40300, "alphanum_fraction": 0.8354004957, "converted": true, "num_tokens": 11108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.07921032845635174, "lm_q1q2_score": 0.03651729051321797}}
{"text": "```python\nfrom IPython.core.display import HTML, Image\ncss_file = 'style.css'\nHTML(open(css_file, 'r').read())\n```\n\n\n\n\n<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:100,300,400,500,700,800,900,100italic,300italic,400italic,500italic,700italic,800italic,900italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Arvo:400,700,400italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=PT+Mono' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Shadows+Into+Light' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Philosopher:400,700,400italic,700italic' rel='stylesheet' type='text/css'>\n\n<style>\n\n@font-face {\n    font-family: \"Computer Modern\";\n    src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');\n}\n\n#notebook_panel { /* main background */\n    background: #ddd;\n    color: #000000;\n}\n\n\n\n/* Formatting for header cells */\n.text_cell_render h1 {\n    font-family: 'Philosopher', sans-serif;\n    font-weight: 400;\n    font-size: 2.2em;\n    line-height: 100%;\n    color: rgb(0, 80, 120);\n    margin-bottom: 0.1em;\n    margin-top: 0.1em;\n    display: block;\n}\t\n.text_cell_render h2 {\n    font-family: 'Philosopher', serif;\n    font-weight: 400;\n    font-size: 1.9em;\n    line-height: 100%;\n    color: rgb(200,100,0);\n    margin-bottom: 0.1em;\n    margin-top: 0.1em;\n    display: block;\n}\t\n\n.text_cell_render h3 {\n    font-family: 'Philosopher', serif;\n    margin-top:12px;\n    margin-bottom: 3px;\n    font-style: italic;\n    color: rgb(94,127,192);\n}\n\n.text_cell_render h4 {\n    font-family: 'Philosopher', serif;\n}\n\n.text_cell_render h5 {\n    font-family: 'Alegreya Sans', sans-serif;\n    font-weight: 300;\n    font-size: 16pt;\n    color: grey;\n    font-style: italic;\n    margin-bottom: .1em;\n    margin-top: 0.1em;\n    display: block;\n}\n\n.text_cell_render h6 {\n    font-family: 'PT Mono', sans-serif;\n    font-weight: 300;\n    font-size: 10pt;\n    color: grey;\n    margin-bottom: 1px;\n    margin-top: 1px;\n}\n\n.CodeMirror{\n        font-family: \"PT Mono\";\n        font-size: 100%;\n}\n\n</style>\n\n\n\n\n\n\n```python\nfrom sympy import init_printing, Matrix, symbols, eye\nfrom warnings import filterwarnings\n```\n\n\n```python\ninit_printing(use_latex = 'mathjax')\nfilterwarnings('ignore')\n```\n\n# Similar matrices\n\n## Positive definite matrices\n\n* Remember the following from positive definite matrices\n$$ {x}^{T}{A}{x}>{0}; {x}\\ne{0} $$\n* These always refer to symmetric matrices\n* What do we know about their inverses?\n    * We can't say anything about their pivots\n    * The following is true for their eigenvalues, though\n    $$ {\\lambda}_{{A}^{-1}}=\\frac{1}{{\\lambda}_{A}} $$\n    * The inverse is also positive definite\n* If both A and B are positive definite\n    * We don't know the pivots of (A+B)\n    * We don't know the eigenvalues of (A+B)\n    * We could look at the following (which is true)\n    $$ {x}^{T}\\left({A}+{B}\\right){x}>0 $$\n\n* From least squares the *m*&#215;*n* matrix A (is not square, neither symmetric (for this section, though, we assume rank is *n*)) we used A<sup>T</sup>A, which is square and symmetric, but is it positive definite?\n* Analogous with real numbers, where we ask is the square of any value positive?\n    * Again we don't know is the pivots or eigenvalues\n    * We do look at the following which is always positive (which you can show by grouping some terms)\n    $$ {x}^{T}{A}^{T}{A}{x} \\\\ =\\left({{A}{x}}\\right)^{T}\\left({A}{x}\\right) \\\\ ={ \\left\\| Ax \\right\\|  }^{ 2 } $$\n    * This last statement is just the length of A**x**, which must be positive (or zero; only if **x**=0)\n\n## Similar matrices\n\n* Consider two similar, square matrices A and B (no longer with the requirement that they are symmetric)\n* They have similar sizes, though\n* The similarity lies in the fact that there is some invertible matrix M for which the following holds\n$$ {B}={M}^{-1}{A}{M} $$\n\n* Remember the creation of the diagonal matrix using the eigenvector matrix\n$$ {S}^{-1}{A}{S}={\\Lambda} $$\n* This says A is similar to &Lambda;\n\n* Now we consider some (invertible) matrix M and create a matrix B from M<sup>-1</sup>AM\n* We state that B is then similar to A (it is now part of some family of matrices of A, the *neatest* of which is the diagonal matrix &Lambda; for its creation via the eigenvector matrix of A)\n\n\n```python\nA = Matrix([[2, 1], [1, 2]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}2 & 1\\\\1 & 2\\end{matrix}\\right]$$\n\n\n\n\n```python\nS, D = A.diagonalize() # S is the eigenvector matrix\n```\n\n\n```python\nS.inv() * A * S # The matrix Lambda\n```\n\n\n\n\n$$\\left[\\begin{matrix}1 & 0\\\\0 & 3\\end{matrix}\\right]$$\n\n\n\n* Now let's invent a matrix M\n\n\n```python\nM = Matrix([[1, 4], [0, 1]])\nM\n```\n\n\n\n\n$$\\left[\\begin{matrix}1 & 4\\\\0 & 1\\end{matrix}\\right]$$\n\n\n\n\n```python\nB = M.inv() * A * M\nA, B # Printing both to the screen\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}2 & 1\\\\1 & 2\\end{matrix}\\right], & \\left[\\begin{matrix}-2 & -15\\\\1 & 6\\end{matrix}\\right]\\end{pmatrix}$$\n\n\n\n* What does A and B have in common?\n* The have the same eigenvalues\n\n\n```python\nA.eigenvals(), B.eigenvals() # The solution is in the form {eigenvalue:how many times that that value occur...}\n```\n\n\n\n\n$$\\begin{pmatrix}\\begin{Bmatrix}1 : 1, & 3 : 1\\end{Bmatrix}, & \\begin{Bmatrix}1 : 1, & 3 : 1\\end{Bmatrix}\\end{pmatrix}$$\n\n\n\n* All similar-sized matrices with the same eigenvalues are similar matrices\n* The most *special* member of this family is the diagonal matrix with the eigenvalues on the main diagonal\n\n$$ Ax=\\lambda x\\\\ A{ M }^{ -1 }x=\\lambda { M }^{ -1 }x\\\\ \\because \\quad { M }^{ -1 }M=I\\\\ { M }^{ -1 }AM{ M }^{ -1 }x=\\lambda { M }^{ -1 }x\\\\ \\because \\quad B={ M }^{ -1 }AM\\\\ B{ M }^{ -1 }x=\\lambda { M }^{ -1 }x $$\n\n* The eigenvectors are not the same though\n\n\n```python\nA.eigenvects(), B.eigenvects()\n```\n\n\n\n\n$$\\begin{pmatrix}\\begin{bmatrix}\\begin{pmatrix}1, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}-1\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}3, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}1\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}, & \\begin{bmatrix}\\begin{pmatrix}1, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}-5\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}3, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}-3\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}\\end{pmatrix}$$\n\n\n\n* Remember that we have a problem when eigenvalues are repeated for a matrix\n* If this is so, we might not have a *full set* of eigenvectors and we cannot diagonalize\n\n\n```python\nA1 = Matrix([[4, 0], [0, 4]])\nA2 = Matrix([[4, 1], [0, 4]])\n```\n\n\n```python\nA1.eigenvals()\n```\n\n\n\n\n$$\\begin{Bmatrix}4 : 2\\end{Bmatrix}$$\n\n\n\n\n```python\nA2.eigenvals()\n```\n\n\n\n\n$$\\begin{Bmatrix}4 : 2\\end{Bmatrix}$$\n\n\n\n* Both the two matrices A<sub>1</sub>1 and A<sub>2</sub> have two similar eigenvalues each, namely 4\n* They are not similar, though\n* There is no matrix M to use with A<sub>1</sub> to produce A<sub>2</sub>\n\n* Note that A<sub>1</sub> is 4 multiplied by the identity matrix of size 2\n* It is a small family, with only this member\n* A<sub>2</sub> is the *neatest* member of its much larger family\n* Diagonalizing it is not possible, though, as if it was, it would results in A<sub>2</sub> which is not in the same family, leaving A<sub>1</sub> as the *neatest* family member\n\n* The *nicest* (most diagonal one) is called the **Jordan form** of the family\n\n* Let's find more members of A<sub>1</sub>\n\n* The matrix A<sub>1</sub> is\n$$ \\begin{bmatrix} 4 & 1 \\\\ 0 & 4 \\end{bmatrix} $$\n* The trace is 8, so let's choose 5 and 3\n$$ \\begin{bmatrix} 5 &  \\\\  & 3 \\end{bmatrix} $$\n* The determinant must remain 16, so let's choose 1 and -1\n$$ \\begin{bmatrix} 5 & 1 \\\\ -1 & 3 \\end{bmatrix} $$\n\n\n```python\nA3 = Matrix([[5, 1], [-1, 3]])\nA1.eigenvals() == A3.eigenvals() # Check to see if the eigenvalues are similar\n```\n\n\n\n\n    True\n\n\n\n* So we have to add, similar independent columns of eigenvectors to the definition of similar matrices\n* It's more than that, though\n\n\n```python\nA4 = Matrix([[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0], [0, 0, 0, 0]])\nA4\n```\n\n\n\n\n$$\\left[\\begin{matrix}0 & 1 & 0 & 0\\\\0 & 0 & 1 & 0\\\\0 & 0 & 0 & 0\\\\0 & 0 & 0 & 0\\end{matrix}\\right]$$\n\n\n\n\n```python\nA4.eigenvals() # Four zeros\n```\n\n\n\n\n$$\\begin{Bmatrix}0 : 4\\end{Bmatrix}$$\n\n\n\n\n```python\nA4.eigenvects() # Rank of 2\n```\n\n\n\n\n$$\\begin{bmatrix}\\begin{pmatrix}0, & 4, & \\begin{bmatrix}\\left[\\begin{matrix}1\\\\0\\\\0\\\\0\\end{matrix}\\right], & \\left[\\begin{matrix}0\\\\0\\\\0\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}$$\n\n\n\n\n```python\nA5 = Matrix([[0, 1, 7, 0], [0, 0, 1, 0], [0, 0, 0, 0], [0, 0, 0, 0]])\nA5\n```\n\n\n\n\n$$\\left[\\begin{matrix}0 & 1 & 7 & 0\\\\0 & 0 & 1 & 0\\\\0 & 0 & 0 & 0\\\\0 & 0 & 0 & 0\\end{matrix}\\right]$$\n\n\n\n\n```python\nA5.eigenvals()\n```\n\n\n\n\n$$\\begin{Bmatrix}0 : 4\\end{Bmatrix}$$\n\n\n\n\n```python\nA5.eigenvects()\n```\n\n\n\n\n$$\\begin{bmatrix}\\begin{pmatrix}0, & 4, & \\begin{bmatrix}\\left[\\begin{matrix}1\\\\0\\\\0\\\\0\\end{matrix}\\right], & \\left[\\begin{matrix}0\\\\0\\\\0\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}$$\n\n\n\n\n```python\nA6 = Matrix([[0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 0, 0]])\nA6\n```\n\n\n\n\n$$\\left[\\begin{matrix}0 & 1 & 0 & 0\\\\0 & 0 & 0 & 0\\\\0 & 0 & 0 & 1\\\\0 & 0 & 0 & 0\\end{matrix}\\right]$$\n\n\n\n\n```python\nA6.eigenvals()\n```\n\n\n\n\n$$\\begin{Bmatrix}0 : 4\\end{Bmatrix}$$\n\n\n\n\n```python\nA6.eigenvects()\n```\n\n\n\n\n$$\\begin{bmatrix}\\begin{pmatrix}0, & 4, & \\begin{bmatrix}\\left[\\begin{matrix}1\\\\0\\\\0\\\\0\\end{matrix}\\right], & \\left[\\begin{matrix}0\\\\0\\\\1\\\\0\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}$$\n\n\n\n\n```python\nA4.eigenvects() == A5.eigenvects()\n```\n\n\n\n\n    True\n\n\n\n\n```python\nA4.eigenvects() == A6.eigenvects()\n```\n\n\n\n\n    False\n\n\n\n* Jordan's theorem\n    * Every square matrix A is similar to a Jordan matrix J\n    * There is one eigenvector per block\n    * The eigenvalues sit along the main diagonal\n    * The matrices are not similar if the blocks are not of similar size\n    * See problem 3 below where Jordan blocks are formed (they must actually both be broken down further into true Jordan blocks which will show the blocks to be of unequal size, instead I keep them in non-Jordan form (not correct) and show different number of pivots and thereby different eigenvectors)\n\n## Example problems\n\n### Example problem 1\n\n* If A and B are similar matrices, why are the following similar?\n$$ 2{A}^{3}+{A}-3{I} \\\\ 2{B}^{3}+{B}-3{I} $$\n\n#### Solution\n\n* There is some matrix such that the following is true\n$$ {M}{A}{M}^{-1}={B} $$\n* From this follows\n$$ {M}\\left(2{A}^{3}+{A}-3{I}\\right){M}^{-1} \\\\ =\\quad 2\\left( MA{ M }^{ -1 }MA{ M }^{ -1 }MA{ M }^{ -1 } \\right) +MA{ M }^{ -1 }-3MI{ M }^{ -1 }\\\\ =\\quad 2{ B }^{ 3 }+B-3I  $$\n\n* I.e. if two matrices (A and B) are similar any polynomial involving them (replacing A with B) are similar\n\n### Example problem 2\n\n* Are the two 3&times;3 matrices A and B , with eigenvalues 1, 0, -1 similar?\n\n#### Solution\n\n* Yes, because the eigenvalues are distinct (and diagonalizable)\n\n### Example problem 3\n\n* Are these two matrices similar?\n$$ {J}_{1}=\\begin{bmatrix}-1&1&0\\\\0&-1&1\\\\0&0&-1\\end{bmatrix} \\\\ {J}_{2}=\\begin{bmatrix}-1&1&0\\\\0&-1&0\\\\0&0&-1\\end{bmatrix} $$\n\n#### Solution\n\n* No\n\n\n```python\nJ1 = Matrix([[-1, 1, 0], [0, -1, 1], [0, 0, -1]])\nJ2 = Matrix([[-1, 1, 0], [0, -1, 0], [0, 0, -1]])\nJ1, J2\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}-1 & 1 & 0\\\\0 & -1 & 1\\\\0 & 0 & -1\\end{matrix}\\right], & \\left[\\begin{matrix}-1 & 1 & 0\\\\0 & -1 & 0\\\\0 & 0 & -1\\end{matrix}\\right]\\end{pmatrix}$$\n\n\n\n* Let's create Jordan block from these\n\n\n```python\nJ1 + eye(3), J2 + eye(3)\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}0 & 1 & 0\\\\0 & 0 & 1\\\\0 & 0 & 0\\end{matrix}\\right], & \\left[\\begin{matrix}0 & 1 & 0\\\\0 & 0 & 0\\\\0 & 0 & 0\\end{matrix}\\right]\\end{pmatrix}$$\n\n\n\n* Jordan blocks have zeros on the main diagonal and various forms of 1 just above the main diagonal\n* Note the difference between the Jordan blocks of J<sub>1</sub> and J<sub>2</sub>\n* The first now contains two pivots and the second only 1; they will not have the same number of eigenvectors and cannot be similar\n\n\n```python\n\n```\n", "meta": {"hexsha": "161121a1ce2da49b5f32aeb98e0e6102b14d1bf7", "size": 27016, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_28_Similar_matrices_Jordan_form.ipynb", "max_stars_repo_name": "okara83/Becoming-a-Data-Scientist", "max_stars_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_28_Similar_matrices_Jordan_form.ipynb", "max_issues_repo_name": "okara83/Becoming-a-Data-Scientist", "max_issues_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_28_Similar_matrices_Jordan_form.ipynb", "max_forks_repo_name": "okara83/Becoming-a-Data-Scientist", "max_forks_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-09T15:41:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T07:47:40.000Z", "avg_line_length": 25.6075829384, "max_line_length": 594, "alphanum_fraction": 0.4603568256, "converted": true, "num_tokens": 4248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25982564942392716, "lm_q2_score": 0.14033624409696624, "lm_q1q2_score": 0.03646295576020902}}
{"text": "# Image Style Transfer\u306e\u5b9f\u88c5\n\n--------------------------------\nGatys, Ecker, and Bethge(2016)\u306e\u753b\u50cf\u30b9\u30bf\u30a4\u30eb\u5909\u63db\u3092\u5b9f\u88c5\u3059\u308b\u3002\n\n\u3010\u53c2\u8003\u6587\u732e\u3011  \nL. A. Gatys, A. S. Ecker, and M. Bethge,  \nImage style transfer using convolutional neural networks,  \nIn Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages, 2414-2423, 2016.\n\n\n```python\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\n```\n\n\n```python\nCONTENT_FILE = '/home/ishiyama/image_style_transfer/image/input/test_input_01.JPG'\nSTYLE_FILE = '/home/ishiyama/image_style_transfer/image/style/test_style_01.jpg'\n```\n\n\n```python\nclass Image(np.ndarray):\n\n    \"\"\"\u753b\u50cf\u3092\u6271\u3046\u305f\u3081\u306enumpy.ndarray\n    \n    XXX: \u5b9f\u88c5\u304c\u5927\u5909\u306a\u306e\u3067\u4e00\u65e6\u4fdd\u7559\n         \u753b\u50cf\u306e\u5f62\u72b6\u306e\u60c5\u5831\u3092\u5c5e\u6027\u3067\u53d6\u308a\u51fa\u305b\u308b\u3088\u3046\u306b\u3057\u305f\u3044\n    \"\"\"\n    \n    DATA_FORMAT_CHAR = {\n        'BATCH': 'N',\n        'HEIGHT': 'H',\n        'WIDTH': 'W',\n        'CHANNEL': 'C'\n    }\n\n    def __new__(subtype,\n                shape,\n                dtype=float,\n                buffer=None,\n                offset=0,\n                strides=None,\n                order=None,\n                data_format='NHWC'):\n\n        super(__class__, self).__new__(subtype, shape, dtype, buffer, offset, strides, order)\n\n        self.data_format = data_format\n        num_batch, num_height, num_width, num_channel = self._get_image_shape(data_format=data_format)\n        self.num_batch = num_batch\n        self.num_height = num_height\n        self.num_width = num_width\n        self.num_channel = num_channel\n\n    def _get_image_shape(self, data_format):\n        _image_shape = self.shape\n        idx_batch = self._get_index_data_format(data_format=data_format, data_type='BATCH'),\n        idx_height = self._get_index_data_format(data_format=data_format, data_type='HEIGHT')\n        idx_width = self._get_index_data_format(data_format=data_format, data_type='WIDTH')\n        idx_channel = self._get_index_data_format(data_format=data_format, data_type='CHANNEL')\n        reordered_image_shape = (_image_shape[idx_batch],\n                                 _image_shape[idx_height],\n                                 _image_shape[idx_width],\n                                 _image_shape[idx_channel])\n        return reordered_image_shape\n\n    def _get_index_data_format(self, data_format, data_type):\n        idx = data_format.find(__class__.DATA_FORMAT_CHAR[data_type])\n        if idx == -1:\n            raise ValueError('data type \"{}\" is not available.'.format(data_type))\n\n        return idx\n\n    @classmethod\n    def reshape(self, *args):\n        self = __class__(super(__class__, self).reshape(args))\n\n```\n\n\n```python\ndef read_images_as_jpeg(file):\n    \n    \"\"\"\n    JPEG Image Reader\n    \n    This function reads the content and style images as JPEG format.\n    These image data must be square for now, different height and\n    width will be able to supplied for future.\n    \n    Args:\n        file : str. A path of the image file.\n    \n    Returns:\n        A tuple. Each Elements are Tensor object of the read images.\n    \"\"\"\n    \n    filename_queue = tf.train.string_input_producer([file])\n    reader = tf.WholeFileReader()\n    key, value = reader.read(filename_queue)\n    image = tf.image.decode_jpeg(value)\n\n    # Read image is a Tensor object which tf.nn.conv2d cannot handle,\n    # so convert it to numpy.ndarray.\n    sess = tf.Session()\n    sess.run(tf.global_variables_initializer())\n    tf.train.start_queue_runners(sess)\n    # Returned array's shape will be (height, width, channel).\n    image_array_hwc = sess.run(image)\n    new_shape = [1]\n    new_shape.extend(image_array_hwc.shape)\n\n    # return image_array_chw\n    return image_array_hwc.reshape(new_shape)\n```\n\n\n```python\ncontent_image = read_images_as_jpeg(file=CONTENT_FILE)\nstyle_image = read_images_as_jpeg(file=STYLE_FILE)\n```\n\n# VGG\u3092\u5b9f\u88c5\u3059\u308b\n------------------------\n\u753b\u50cf\u306e\u7279\u5fb4\u91cf\u3092\u62bd\u51fa\u3059\u308b\u30a2\u30eb\u30b4\u30ea\u30ba\u30e0\u306b\u306fSimonyan and Zisserman(2015)\u3067\u63d0\u6848\u3055\u308c\u305fCNN(VGG19)\u306e\u7573\u8fbc\u307f\u5c64\u3068\u30d7\u30fc\u30ea\u30f3\u30b0\u5c64\u304c\u4f7f\u308f\u308c\u3066\u3044\u308b\u3002  \n\u3053\u3053\u3067\u306f\u3001\u300cTensorFlow\u3067\u5b66\u3076\u30c7\u30a3\u30fc\u30d7\u30e9\u30fc\u30cb\u30f3\u30b0\u5165\u9580\u300d\u306e\u591a\u5c64CNN\u306e\u5b9f\u88c5\u3092\u53c2\u8003\u306bVGG19\u3092\u69cb\u7bc9\u3059\u308b\u3002  \n\n\u3010\u53c2\u8003\u6587\u732e\u3011  \nK. Simonyan and A. Zisserman, Very Deep Convolutional Networks For Large-Scale Image Recognition, arXiv: 1409.1556v6, 2015  \n\u4e2d\u4e95\u60a6\u53f8, TensorFlow\u3067\u5b66\u3076\u30c7\u30a3\u30fc\u30d7\u30e9\u30fc\u30cb\u30f3\u30b0\u5165\u9580\u301c\u7573\u307f\u8fbc\u307f\u30cb\u30e5\u30fc\u30e9\u30eb\u30cd\u30c3\u30c8\u30ef\u30fc\u30af\u5fb9\u5e95\u89e3\u8aac, \u30de\u30a4\u30ca\u30d3\u51fa\u7248, 2016\n\n### \u7573\u307f\u8fbc\u307f\u5c64\u3092\u5b9f\u88c5\u3059\u308b\n\n\n```python\nimport tensorflow as tf\nimport numpy as np\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n\ndef calculate_convolutional_layer(x, filter_height, filter_width, output_channels):\n\n    \"\"\"\n    Executeing a convolutional layer task.\n    \n    Args:\n        x                     : An image data.\n        filter_height   (int) : A height of each filters.\n        filter_width    (int) : A width of each filters.\n        output_channels (int) : A number of channels which must be outputed.\n\n    Returns:\n        An activation of an convolutional layer.\n    \"\"\"\n\n    if ((not isinstance(filter_height, int))\n        or (not isinstance(filter_width, int))\n        or (not isinstance(output_channels, int))):\n        raise TypeError('\"filter_height\" and \"filter_width\" and \"output_channels\" '\n                        'must be integer.')\n\n    # TODO: \u5165\u529b\u753b\u50cf\u306e\u7e26\u3001\u6a2a\u3001\u30c1\u30e3\u30f3\u30cd\u30eb\u6570\u3092\u5c5e\u6027\u3067\u53d6\u5f97\u3067\u304d\u308b\u3088\u3046\u306b\u3059\u308b\n    # \u4f8b\uff09 input_channels = x.num_channels\n    input_channels = int(x.shape[-1])\n    filter_value = 1 / float(filter_height * filter_width)\n    epsilon = filter_value / 10.0\n    W = tf.Variable(\n        tf.random_uniform(\n            shape=[filter_height,\n                   filter_width,\n                   input_channels,\n                   output_channels],\n            minval=filter_value - epsilon,\n            maxval=filter_value + epsilon\n        )\n    )\n    h = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n    b = tf.Variable(tf.constant(0.1, shape=[output_channels]))\n    convoluted_image = tf.nn.relu(h + b)\n\n    return convoluted_image\n```\n\n\n```python\nx = tf.placeholder(tf.float32, [1, 477, 477, 3])\ntest_model = calculate_convolutional_layer(\n    x=x,\n    filter_height=3,\n    filter_width=3,\n    output_channels=1\n)\nsess = tf.InteractiveSession()\n# tf.Session()\u3060\u3068\u3001sess.run\u3067\u8fd4\u3063\u3066\u304f\u308b\u884c\u5217\u306e\u8981\u7d20\u304c\u3059\u3079\u30660\u3060\u3063\u305f\u3002\n# TODO: Session\u30e1\u30bd\u30c3\u30c9 \u3068 InteractiveSession\u30e1\u30bd\u30c3\u30c9\u306e\u9055\u3044\u3092\u8abf\u3079\u308b\n# sess = tf.Session()\nsess.run(tf.global_variables_initializer())\ntest_result = sess.run(test_model, feed_dict={x: content_image})\n```\n\n\n```python\ntest_result.shape\n```\n\n\n\n\n    (1, 477, 477, 1)\n\n\n\n\n```python\ntest_result\n```\n\n\n\n\n    array([[[[ 114.27301025],\n             [ 173.50660706],\n             [ 174.29614258],\n             ..., \n             [ 480.10452271],\n             [ 481.24404907],\n             [ 323.35064697]],\n    \n            [[ 166.4135437 ],\n             [ 252.51049805],\n             [ 254.13793945],\n             ..., \n             [ 717.27807617],\n             [ 718.06811523],\n             [ 481.68475342]],\n    \n            [[ 158.3868866 ],\n             [ 241.47108459],\n             [ 244.67269897],\n             ..., \n             [ 718.62445068],\n             [ 718.66595459],\n             [ 481.57723999]],\n    \n            ..., \n            [[ 448.78652954],\n             [ 674.51971436],\n             [ 673.51464844],\n             ..., \n             [ 672.70135498],\n             [ 670.52099609],\n             [ 449.13308716]],\n    \n            [[ 449.70996094],\n             [ 676.00695801],\n             [ 674.76342773],\n             ..., \n             [ 673.22253418],\n             [ 671.83905029],\n             [ 450.01858521]],\n    \n            [[ 297.78442383],\n             [ 444.92471313],\n             [ 443.75894165],\n             ..., \n             [ 443.45913696],\n             [ 442.98733521],\n             [ 296.54943848]]]], dtype=float32)\n\n\n\n### Max\u30d7\u30fc\u30ea\u30f3\u30b0\u5c64\u3092\u5b9f\u88c5\u3059\u308b\n\n\n```python\ndef calculate_max_pooling_layer(x, ksize, strides):\n\n    \"\"\"Wrapper function of tf.nn.max_pool.\n    \n    Args:\n        x       : A Tensor produced by calculate_convolutional_layer.\n        ksize   : A list of ints that has length >= 4. The size of\n                  the window for each dimension of the input tensor.\n        strides : A list of ints that has length >= 4. The stride\n                  of the sliding window for each dimension of the\n                  input tensor.\n    \n    Returns:\n        A pooled image.\n    \"\"\"\n\n    pooled_image = tf.nn.max_pool(x, ksize=ksize, strides=strides, padding='SAME')\n\n    return pooled_image\n```\n\n### \u7573\u8fbc\u307f\u3068\u30d7\u30fc\u30ea\u30f3\u30b0\u51e6\u7406\u306e\u9014\u4e2d\u7d4c\u904e\u3092\u4fdd\u6301\u3059\u308b\u30af\u30e9\u30b9\u3092\u5b9f\u88c5\u3059\u308b\n\n\n```python\nclass FeatureMapHolder(object):\n\n    def __init__(self):\n\n        self.conv = []\n        self.pool = None\n\n    def set_conv(self, mat):\n\n        self.conv.append(mat)\n\n    def get_conv(self, idx):\n\n        if idx is None:\n            raise ValueError('idx is required.')\n\n        if not isinstance(idx, int):\n            raise ValueError('idx must be an integer.')\n\n        return self.conv[idx]\n\n    def set_pool(self, mat):\n\n        self.pool = mat\n\n    def get_pool(self):\n\n        return self.pool\n\n    def get(self, type, idx=None):\n\n        if type == 'pool':\n            return self.get_pool()\n        elif type == 'conv':\n            return self.get_conv(idx)\n```\n\n\n```python\nFILTER_CONF = {\n    'conv': {\n        'height': 3,\n        'width': 3\n    },\n    'maxpool': {\n        'height': 2,\n        'width': 2\n    }\n}\n\n\ndef apply_vgg_network_unit(x, channels, num_conv):\n\n    \"\"\"Apply VGG Network From a Convolutional Layer to Max Pooling Layer.\n\n    Table 1 of Simonyan and Zisserman(2015) is separated by 5 parts,\n    each parts is from an input data or a pooled data at previous part\n    to a maxpool.\n    This function provides to apply a that part.\n    This will apply recursively.\n    \n    Args:\n        x (Tensor)     : An input data or A Max pooled data returned by this function.\n        channels (int) : A number of channels described at Table 1 of\n                         Simonyan and Zisserman(2015).\n        num_conv (int) : A number of applying covolutional layers.\n                         See Simonyan and Zisserman(2015) for detail.\n\n    Returns:\n        A ConvNetProgressHolder object.\n    \"\"\"\n\n    if num_conv < 2:\n        raise ValueError('num_conv must be >= 2.')\n\n    feature_maps = FeatureMapHolder()\n\n    conv = calculate_convolutional_layer(\n        x=x,\n        filter_height=FILTER_CONF['conv']['height'],\n        filter_width=FILTER_CONF['conv']['width'],\n        output_channels=channels\n    )\n    feature_maps.set_conv(conv)\n\n    for i in range(1, num_conv):\n        conv = calculate_convolutional_layer(\n            x=feature_maps.get(type='conv', idx=i-1),\n            filter_height=FILTER_CONF['conv']['height'],\n            filter_width=FILTER_CONF['conv']['width'],\n            output_channels=channels\n        )\n        feature_maps.set_conv(conv)\n\n    pool = calculate_max_pooling_layer(\n        x=feature_maps.get('conv', idx=i-1),\n        ksize=[1, FILTER_CONF['maxpool']['height'], FILTER_CONF['maxpool']['width'], 1],\n        strides=[1, 2, 2, 1]\n    )\n    feature_maps.set_pool(pool)\n\n    return feature_maps\n\n```\n\n### VGG\u306e\u7573\u8fbc\u307f\u3068\u30d7\u30fc\u30ea\u30f3\u30b0\u5c64\u3092\u69cb\u7bc9\u3059\u308b\n\nVGG\u306e\u8ad6\u6587\u306b\u5f93\u3044\u3001\u8907\u6570\u56de\u306e\u7573\u8fbc\u307f\u51e6\u7406\u30681\u56de\u306eMAX\u30d7\u30fc\u30ea\u30f3\u30b0\u51e6\u7406\u30921\u30bb\u30c3\u30c8\u3068\u3057\u3066\u3001\u305d\u308c\u30925\u56de\u7e70\u308a\u8fd4\u3059\u3002  \n\u4eca\u56de\u5b9f\u88c5\u3059\u308b\u753b\u50cf\u5909\u63db\u30a2\u30eb\u30b4\u30ea\u30ba\u30e0\u3067\u306f\u3001\u3053\u306e\u51e6\u7406\u306e\u9014\u4e2d\u7d4c\u904e\u3092\u4f7f\u3046\u305f\u3081\u3001\u4f7f\u3044\u305f\u3044\u90e8\u5206\u3092\u30ea\u30b9\u30c8\u3067\uff11\u3064\u306b\u307e\u3068\u3081\u3066sess.run()\u306b\u6295\u3052\u308b\u3002\n\n\n```python\n# \u4f8b\nx = tf.placeholder(tf.float32, [1, 477, 477, 3])\nunit1 = apply_vgg_network_unit(x=x, channels=2, num_conv=2)\nunit2 = apply_vgg_network_unit(x=unit1.get(type='pool'), channels=4, num_conv=2)\nunit3 = apply_vgg_network_unit(x=unit2.get(type='pool'), channels=8, num_conv=4)\nunit4 = apply_vgg_network_unit(x=unit3.get(type='pool'), channels=16, num_conv=4)\nunit5 = apply_vgg_network_unit(x=unit4.get(type='pool'), channels=32, num_conv=4)\nsess = tf.InteractiveSession()\nsess.run(tf.global_variables_initializer())\n\n# \u4f7f\u3044\u305f\u3044\u904e\u7a0b\u3092\u30ea\u30b9\u30c8\u3067\u307e\u3068\u3081\u3066sess.run\u306b\u6295\u3052\u308b\u3068\u7279\u5fb4\u91cf\u62bd\u51fa\u306e\n# \u9014\u4e2d\u7d4c\u904e\u3092\u53d6\u308a\u51fa\u305b\u308b\nresult_unit2_conv, result_unit5_conv, result_unit5_pool = sess.run(\n    [unit2.get(type='conv', idx=1), unit5.get(type='conv', idx=2), unit5.get(type='pool')],\n    feed_dict={x: content_image}\n)\n```\n\n\n```python\nNETWORK_CONF = {\n    'layer1': {\n        'num_channels': 2,\n        'num_conv': 2\n    },\n    'layer2': {\n        'num_channels': 4,\n        'num_conv': 2\n    },\n    'layer3': {\n        'num_channels': 8,\n        'num_conv': 4\n    },\n    'layer4': {\n        'num_channels': 16,\n        'num_conv': 4\n    },\n    'layer5': {\n        'num_channels': 32,\n        'num_conv': 4\n    }\n}\n```\n\n\n```python\ndef extract_feature_map(image, extract=None, run=True):\n\n    x = tf.placeholder(tf.float32, image.shape)\n\n    layers = []\n\n    layer1 = apply_vgg_network_unit(\n        x=x,\n        channels=NETWORK_CONF['layer1']['num_channels'],\n        num_conv=NETWORK_CONF['layer1']['num_conv']\n    )\n    layers.append(layer1)\n\n    layer2 = apply_vgg_network_unit(\n        x=layer1.get(type='pool'),\n        channels=NETWORK_CONF['layer2']['num_channels'],\n        num_conv=NETWORK_CONF['layer2']['num_conv']\n    )\n    layers.append(layer2)\n    \n    layer3 = apply_vgg_network_unit(\n        x=layer2.get(type='pool'),\n        channels=NETWORK_CONF['layer3']['num_channels'],\n        num_conv=NETWORK_CONF['layer3']['num_conv']\n    )\n    layers.append(layer3)\n    \n    layer4 = apply_vgg_network_unit(\n        x=layer3.get(type='pool'),\n        channels=NETWORK_CONF['layer4']['num_channels'],\n        num_conv=NETWORK_CONF['layer4']['num_conv']\n    )\n    layers.append(layer4)\n    \n    layer5 = apply_vgg_network_unit(\n        x=layer4.get(type='pool'),\n        channels=NETWORK_CONF['layer5']['num_channels'],\n        num_conv=NETWORK_CONF['layer5']['num_conv']\n    )\n    layers.append(layer5)\n\n    # \u30e2\u30c7\u30eb\u306e\u69cb\u7bc9\u306e\u307f\u306e\u5834\u5408(run=True)\u306flayers\u3092\u8fd4\u5374\u3057\u3066\u7d42\u4e86\n    if not run:\n        return layers\n\n    if extract is None:\n        raise ValueError('extract is required if run is True.')\n\n    sess = tf.InteractiveSession()\n    sess.run(tf.global_variables_initializer())\n\n    extract_layers = []\n    for ext in extract:\n        if len(ext) == 2:\n            type, idx_layer = ext\n            extract_layers.append(layers[idx_layer].get(type))\n        elif len(ext) == 3:\n            type, idx_layer, idx_conv = ext\n            extract_layers.append(layers[idx_layer].get(type, idx_conv))\n        else:\n            raise ValueError('Format of extract is not available: {}'.format(ext))\n\n    result_list = sess.run(extract_layers, feed_dict={x: image})\n\n    return result_list\n\n```\n\n\n```python\nconv1_1, conv2_2, pool4 = extract_feature_map(\n    image=content_image,\n    extract=[('conv', 0, 0), ('conv', 1, 1), ('pool', 3)]\n)\n```\n\n# \u753b\u50cf\u3092\u5408\u6210\u3059\u308b\u51e6\u7406\u3092\u4f5c\u308b\nVGG\u306b\u3088\u3063\u3066\u30b9\u30bf\u30a4\u30eb\u3092\u5909\u63db\u3059\u308b\u753b\u50cf\u3068\u30b9\u30bf\u30a4\u30eb\u306e\u30ea\u30d5\u30a1\u30ec\u30f3\u30b9\u3068\u306a\u308b\u753b\u50cf\u306e\u7279\u5fb4\u91cf\u3092\u62bd\u51fa\u3067\u304d\u308b\u3088\u3046\u306b\u306a\u3063\u305f\u3002  \n\u4eca\u5ea6\u306f\u3053\u306e\u7279\u5fb4\u91cf\u3092\u7528\u3044\u3066\u753b\u50cf\u3092\u5b9f\u969b\u306b\u5408\u6210\u3059\u308b\u90e8\u5206\u3092\u4f5c\u3063\u3066\u3044\u304f\u3002  \n\n\u3053\u306e\u30a2\u30eb\u30b4\u30ea\u30ba\u30e0\u306f\u5909\u63db\u3057\u305f\u3044\u30b9\u30bf\u30a4\u30eb\u306b\u5bc4\u305b\u308b\u305f\u3081\u306e\u640d\u5931\u95a2\u6570$L_{style}$\u3068  \n\u5909\u63db\u3059\u308b\u753b\u50cf\u306e\u5185\u5bb9\u306b\u5bc4\u305b\u308b\u305f\u3081\u306e\u640d\u5931\u95a2\u6570$L_{content}$\u3092\u305d\u308c\u305e\u308c\u8a08\u7b97\u3057\u3066\u3001  \n\\begin{equation} L_{total} = \\alpha L_{content} + \\beta L_{style} \\end{equation}\n\u3092\u6700\u9069\u5316\u3059\u308b\u3053\u3068\u3067\u753b\u50cf\u3092\u5408\u6210\u3059\u308b\u3002\n\n----------------------------------------\n# \u5909\u63db\u3057\u305f\u3044\u30b9\u30bf\u30a4\u30eb\u306b\u5bc4\u305b\u308b\u305f\u3081\u306e\u640d\u5931\u95a2\u6570$L_{style}$\u3092\u5b9f\u88c5\u3059\u308b\n\u5909\u63db\u3057\u305f\u3044\u30b9\u30bf\u30a4\u30eb\u306b\u5bc4\u305b\u308b\u305f\u3081\u306e\u640d\u5931\u95a2\u6570$L_{style}$\u306f\u6b21\u3067\u8a08\u7b97\u3059\u308b\uff1a\n\\begin{align}\n    L_{style} &= \\sum_{l=1}^{L} w_{l} E_{l} \\\\\n        E_{l} &= \\frac{1}{4N_{l}^{2}M_{l}^{2}} \\sum_{i=1}^{N_{l}} \\sum_{j=1}^{N_{l}} (G_{ij}^{l} - A_{ij}^{l})^{2}\n\\end{align}\n\u305f\u3060\u3057\u3001$N_{l}$\u306f\u5c64$l$\u306e\u7573\u8fbc\u307f\u30d5\u30a3\u30eb\u30bf\u30fc\u306e\u6570\u3001\n$M_{l}$\u306f\u5c64$l$\u306e\u7573\u8fbc\u307f\u30d5\u30a3\u30eb\u30bf\u30fc\u306e\u30b5\u30a4\u30ba\u3067$M_{l} = \\text{\u30d5\u30a3\u30eb\u30bf\u30fc\u306e\u9ad8\u3055} \\times \\text{\u30d5\u30a3\u30eb\u30bf\u30fc\u306e\u5e45}$\u3001\n$A_{ij}^{l}$\u306f\u30b9\u30bf\u30a4\u30eb\u753b\u50cf\u304b\u3089\u62bd\u51fa\u3057\u305f\u7279\u5fb4\u91cf\u3067\u8a08\u7b97\u3057\u305f\u30b0\u30e9\u30e0\u884c\u5217$A^{l}$\u306e$(i, j)$\u6210\u5206\u3001\n\u540c\u69d8\u306b\u3001$G_{ij}^{l}$\u306f\u5408\u6210\u5f8c\u306e\u753b\u50cf\u304b\u3089\u62bd\u51fa\u3057\u305f\u7279\u5fb4\u91cf\u3067\u8a08\u7b97\u3057\u305f\u30b0\u30e9\u30e0\u884c\u5217$G^{l}$\u306e$(i, j)$\u6210\u5206\u3067\u3042\u308b\u3002\n$G_{ij}^{l}$\u306f\u6b21\u3067\u8a08\u7b97\u3059\u308b\u3002  \n$G^{l}$\u306f$(N_{l}, N_{l})$\u578b\u884c\u5217\u3067\n\\begin{equation}\n    G_{ij}^{l} = \\sum_{k=1}^{M_{l}} F_{ik}^{l}F_{jk}^{l}.\n\\end{equation}\n\n\n```python\ndef convert_nhwc_to_nchw(image):\n    return image.transpose([0, 3, 1, 2])\n```\n\n\n```python\nconverted = convert_nhwc_to_nchw(result_unit5_conv)\nconverted.shape\n```\n\n\n\n\n    (1, 32, 30, 30)\n\n\n\n\n```python\ndef flatten(image):\n    num_batch, num_channel, num_height, num_width = image.shape\n#    if num_batch != 1:\n#        raise ValueError('Not assumed batch size has been ocurred.')\n    return image.reshape([num_batch, num_channel, num_height * num_width])\n```\n\n#### flatten\u306e\u30c6\u30b9\u30c8\n\n\n```python\ntest_data1 = np.arange(1 * 3 * 4 * 2).reshape([1, 3, 4, 2])\ntest_data1\n```\n\n\n\n\n    array([[[[ 0,  1],\n             [ 2,  3],\n             [ 4,  5],\n             [ 6,  7]],\n    \n            [[ 8,  9],\n             [10, 11],\n             [12, 13],\n             [14, 15]],\n    \n            [[16, 17],\n             [18, 19],\n             [20, 21],\n             [22, 23]]]])\n\n\n\n\n```python\nflatten(test_data1)\n```\n\n\n\n\n    array([[[ 0,  1,  2,  3,  4,  5,  6,  7],\n            [ 8,  9, 10, 11, 12, 13, 14, 15],\n            [16, 17, 18, 19, 20, 21, 22, 23]]])\n\n\n\n\n```python\ntest_data2 = np.arange(2 * 3 * 4 * 2).reshape([2, 3, 4, 2])\ntest_data2\n```\n\n\n\n\n    array([[[[ 0,  1],\n             [ 2,  3],\n             [ 4,  5],\n             [ 6,  7]],\n    \n            [[ 8,  9],\n             [10, 11],\n             [12, 13],\n             [14, 15]],\n    \n            [[16, 17],\n             [18, 19],\n             [20, 21],\n             [22, 23]]],\n    \n    \n           [[[24, 25],\n             [26, 27],\n             [28, 29],\n             [30, 31]],\n    \n            [[32, 33],\n             [34, 35],\n             [36, 37],\n             [38, 39]],\n    \n            [[40, 41],\n             [42, 43],\n             [44, 45],\n             [46, 47]]]])\n\n\n\n\n```python\nflatten(test_data2)\n```\n\n\n\n\n    array([[[ 0,  1,  2,  3,  4,  5,  6,  7],\n            [ 8,  9, 10, 11, 12, 13, 14, 15],\n            [16, 17, 18, 19, 20, 21, 22, 23]],\n    \n           [[24, 25, 26, 27, 28, 29, 30, 31],\n            [32, 33, 34, 35, 36, 37, 38, 39],\n            [40, 41, 42, 43, 44, 45, 46, 47]]])\n\n\n\n\n```python\n# \u30b0\u30e9\u30e0\u884c\u5217\u3092\u8a08\u7b97\u3059\u308b\ndef calculate_gram_matrix(x):\n    return np.dot(x, x.T)\n```\n\n\n```python\nflattened = flatten(result_unit5_conv)\nflattened\n```\n\n\n\n\n    array([[[  1.72774497e+12,   1.71310606e+12,   1.71771534e+12, ...,\n               2.04983711e+12,   2.06964392e+12,   2.06642859e+12],\n            [  3.19720443e+12,   3.17136621e+12,   3.17231753e+12, ...,\n               3.36004750e+12,   3.38134932e+12,   3.37660713e+12],\n            [  4.26700073e+12,   4.23316842e+12,   4.23089118e+12, ...,\n               3.69687554e+12,   3.71591007e+12,   3.71104154e+12],\n            ..., \n            [  4.77729286e+12,   4.74064146e+12,   4.73164310e+12, ...,\n               4.39728315e+12,   4.41955333e+12,   4.41371905e+12],\n            [  3.92295009e+12,   3.89338995e+12,   3.88214948e+12, ...,\n               3.65187223e+12,   3.66564449e+12,   3.66082182e+12],\n            [  2.26813621e+12,   2.25203690e+12,   2.23939710e+12, ...,\n               2.12420749e+12,   2.12506536e+12,   2.12239201e+12]]], dtype=float32)\n\n\n\n\n```python\ngram_matrix = calculate_gram_matrix(flattened[0])\n# gram_matrix\n```\n\n\n```python\ngram_matrix.shape\n```\n\n\n\n\n    (30, 30)\n\n\n\n\n```python\ncontent_conv4_2 = extract_feature_map(image=content_image, extract=[('conv', 3, 1)])\nstyle_conv1_1, style_conv2_1, style_conv3_1, style_conv4_1, style_conv5_1 = extract_feature_map(\n    image=style_image,\n    extract=[\n        ('conv', 0, 0),\n        ('conv', 1, 0),\n        ('conv', 2, 0),\n        ('conv', 3, 0),\n        ('conv', 4, 0)\n    ]\n)\n```\n\n#### \u640d\u5931\u95a2\u6570\u3092\u69cb\u6210\u3059\u308b\n\n\n```python\ncreating_image = tf.placeholder(tf.float32, [1, 477, 477, 3])\nfeature_map = extract_feature_map(\n    image=creating_image,\n    run=False\n)\n```\n\n\n```python\nfeature_map[0].get(type='conv', idx=0)\n```\n\n\n\n\n    <tf.Tensor 'Relu_97:0' shape=(1, 477, 477, 2) dtype=float32>\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "b265c73e002bd1dd104c9def4c65794c97cddfc1", "size": 30561, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "dev/image_style_transfer_using_cnn.ipynb", "max_stars_repo_name": "Katsuya-Ishiyama/image_style_transfer", "max_stars_repo_head_hexsha": "3fe41cdaede9c07dd62c80a12314ddd45ecbf93b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dev/image_style_transfer_using_cnn.ipynb", "max_issues_repo_name": "Katsuya-Ishiyama/image_style_transfer", "max_issues_repo_head_hexsha": "3fe41cdaede9c07dd62c80a12314ddd45ecbf93b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dev/image_style_transfer_using_cnn.ipynb", "max_forks_repo_name": "Katsuya-Ishiyama/image_style_transfer", "max_forks_repo_head_hexsha": "3fe41cdaede9c07dd62c80a12314ddd45ecbf93b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6419868791, "max_line_length": 133, "alphanum_fraction": 0.4726612349, "converted": true, "num_tokens": 6203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.07585818419975078, "lm_q1q2_score": 0.03644824006341088}}
{"text": "```python\n# Install qiskit library\n%pip install qiskit\n# Install pylatex in order to make the plots work\n%pip install pylatexenc\n```\n\n    Collecting qiskit\n      Downloading qiskit-0.31.0.tar.gz (13 kB)\n    Collecting qiskit-terra==0.18.3\n      Downloading qiskit_terra-0.18.3-cp37-cp37m-manylinux2010_x86_64.whl (6.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.1 MB 4.0 MB/s \n    \u001b[?25hCollecting qiskit-aer==0.9.1\n      Downloading qiskit_aer-0.9.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (17.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 17.9 MB 114 kB/s \n    \u001b[?25hCollecting qiskit-ibmq-provider==0.17.0\n      Downloading qiskit_ibmq_provider-0.17.0-py3-none-any.whl (236 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 236 kB 73.7 MB/s \n    \u001b[?25hCollecting qiskit-ignis==0.6.0\n      Downloading qiskit_ignis-0.6.0-py3-none-any.whl (207 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 207 kB 76.2 MB/s \n    \u001b[?25hCollecting qiskit-aqua==0.9.5\n      Downloading qiskit_aqua-0.9.5-py3-none-any.whl (2.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.1 MB 27.2 MB/s \n    \u001b[?25hRequirement already satisfied: scipy>=1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.9.1->qiskit) (1.4.1)\n    Requirement already satisfied: numpy>=1.16.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.9.1->qiskit) (1.19.5)\n    Collecting retworkx>=0.8.0\n      Downloading retworkx-0.10.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.4 MB 42.2 MB/s \n    \u001b[?25hRequirement already satisfied: scikit-learn>=0.20.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (0.22.2.post1)\n    Requirement already satisfied: fastdtw<=0.3.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (0.3.4)\n    Requirement already satisfied: h5py<3.3.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (3.1.0)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (5.4.8)\n    Collecting dlx<=1.0.4\n      Downloading dlx-1.0.4.tar.gz (5.5 kB)\n    Collecting quandl\n      Downloading Quandl-3.6.1-py2.py3-none-any.whl (26 kB)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (1.1.5)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (57.4.0)\n    Collecting yfinance>=0.1.62\n      Downloading yfinance-0.1.64.tar.gz (26 kB)\n    Collecting docplex>=2.21.207\n      Downloading docplex-2.22.213.tar.gz (634 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 634 kB 49.5 MB/s \n    \u001b[?25hRequirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (1.7.1)\n    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.17.0->qiskit) (2.23.0)\n    Collecting websocket-client>=1.0.1\n      Downloading websocket_client-1.2.1-py2.py3-none-any.whl (52 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 52 kB 2.0 MB/s \n    \u001b[?25hCollecting requests-ntlm>=1.1.0\n      Downloading requests_ntlm-1.1.0-py2.py3-none-any.whl (5.7 kB)\n    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.17.0->qiskit) (1.24.3)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.17.0->qiskit) (2.8.2)\n    Collecting ply>=3.10\n      Downloading ply-3.11-py2.py3-none-any.whl (49 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 49 kB 8.0 MB/s \n    \u001b[?25hRequirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.18.3->qiskit) (0.3.4)\n    Collecting tweedledum<2.0,>=1.1\n      Downloading tweedledum-1.1.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (943 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 943 kB 34.1 MB/s \n    \u001b[?25hCollecting symengine>0.7\n      Downloading symengine-0.8.1-cp37-cp37m-manylinux2010_x86_64.whl (38.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 38.2 MB 21 kB/s \n    \u001b[?25hCollecting fastjsonschema>=2.10\n      Downloading fastjsonschema-2.15.1-py3-none-any.whl (21 kB)\n    Collecting python-constraint>=1.4\n      Downloading python-constraint-1.4.0.tar.bz2 (18 kB)\n    Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.18.3->qiskit) (2.6.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from docplex>=2.21.207->qiskit-aqua==0.9.5->qiskit) (1.15.0)\n    Requirement already satisfied: cached-property in /usr/local/lib/python3.7/dist-packages (from h5py<3.3.0->qiskit-aqua==0.9.5->qiskit) (1.5.2)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.17.0->qiskit) (2021.5.30)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.17.0->qiskit) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.17.0->qiskit) (3.0.4)\n    Collecting cryptography>=1.3\n      Downloading cryptography-35.0.0-cp36-abi3-manylinux_2_24_x86_64.whl (3.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.5 MB 37.8 MB/s \n    \u001b[?25hCollecting ntlm-auth>=1.0.2\n      Downloading ntlm_auth-1.5.0-py2.py3-none-any.whl (29 kB)\n    Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.17.0->qiskit) (1.14.6)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.17.0->qiskit) (2.20)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.9.5->qiskit) (1.0.1)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-aqua==0.9.5->qiskit) (1.2.1)\n    Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance>=0.1.62->qiskit-aqua==0.9.5->qiskit) (0.0.9)\n    Collecting lxml>=4.5.1\n      Downloading lxml-4.6.3-cp37-cp37m-manylinux2014_x86_64.whl (6.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.3 MB 21.6 MB/s \n    \u001b[?25hRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->qiskit-aqua==0.9.5->qiskit) (2018.9)\n    Requirement already satisfied: more-itertools in /usr/local/lib/python3.7/dist-packages (from quandl->qiskit-aqua==0.9.5->qiskit) (8.10.0)\n    Collecting inflection>=0.3.1\n      Downloading inflection-0.5.1-py2.py3-none-any.whl (9.5 kB)\n    Building wheels for collected packages: qiskit, dlx, docplex, python-constraint, yfinance\n      Building wheel for qiskit (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for qiskit: filename=qiskit-0.31.0-py3-none-any.whl size=11728 sha256=1e84fa48b34a9763740af95639c7fec8a111fba1ec1b3a49ecb108a7437425bc\n      Stored in directory: /root/.cache/pip/wheels/29/dd/b2/1fe1a9ac92aaf75b267d893ae27329ea229f292a293017afc7\n      Building wheel for dlx (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for dlx: filename=dlx-1.0.4-py3-none-any.whl size=5719 sha256=82f67b15af96f3a59ebffdd8a8348f334e53006e1717d67a952b604b6203d353\n      Stored in directory: /root/.cache/pip/wheels/78/55/c8/dc61e772445a566b7608a476d151e9dcaf4e092b01b0c4bc3c\n      Building wheel for docplex (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for docplex: filename=docplex-2.22.213-py3-none-any.whl size=696881 sha256=c131458598b50b288c9e529b71276448520d603459046e4e5f6e6f2837d926d6\n      Stored in directory: /root/.cache/pip/wheels/90/69/6b/1375c68a5b7ff94c40263b151c86f58bd72200bf0c465b5ba3\n      Building wheel for python-constraint (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for python-constraint: filename=python_constraint-1.4.0-py2.py3-none-any.whl size=24081 sha256=ba812ad0bb946d397ae4d888f5f4573fc8495454f48a3d916bcc5ea6b36d338a\n      Stored in directory: /root/.cache/pip/wheels/07/27/db/1222c80eb1e431f3d2199c12569cb1cac60f562a451fe30479\n      Building wheel for yfinance (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for yfinance: filename=yfinance-0.1.64-py2.py3-none-any.whl size=24109 sha256=aadd6d009376dfe92a6cb9c46f70feedb7de119b23fa1995a2d5a94b495a9563\n      Stored in directory: /root/.cache/pip/wheels/86/fe/9b/a4d3d78796b699e37065e5b6c27b75cff448ddb8b24943c288\n    Successfully built qiskit dlx docplex python-constraint yfinance\n    Installing collected packages: tweedledum, symengine, retworkx, python-constraint, ply, fastjsonschema, qiskit-terra, ntlm-auth, lxml, inflection, cryptography, yfinance, websocket-client, requests-ntlm, quandl, qiskit-ignis, docplex, dlx, qiskit-ibmq-provider, qiskit-aqua, qiskit-aer, qiskit\n      Attempting uninstall: lxml\n        Found existing installation: lxml 4.2.6\n        Uninstalling lxml-4.2.6:\n          Successfully uninstalled lxml-4.2.6\n    Successfully installed cryptography-35.0.0 dlx-1.0.4 docplex-2.22.213 fastjsonschema-2.15.1 inflection-0.5.1 lxml-4.6.3 ntlm-auth-1.5.0 ply-3.11 python-constraint-1.4.0 qiskit-0.31.0 qiskit-aer-0.9.1 qiskit-aqua-0.9.5 qiskit-ibmq-provider-0.17.0 qiskit-ignis-0.6.0 qiskit-terra-0.18.3 quandl-3.6.1 requests-ntlm-1.1.0 retworkx-0.10.2 symengine-0.8.1 tweedledum-1.1.1 websocket-client-1.2.1 yfinance-0.1.64\n    Collecting pylatexenc\n      Downloading pylatexenc-2.10.tar.gz (162 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 162 kB 5.0 MB/s \n    \u001b[?25hBuilding wheels for collected packages: pylatexenc\n      Building wheel for pylatexenc (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pylatexenc: filename=pylatexenc-2.10-py3-none-any.whl size=136833 sha256=4156775a6299f6b21491544ef2bff72d2cef11786591eea3ee3854bcfbbbaee7\n      Stored in directory: /root/.cache/pip/wheels/f1/8a/f5/33ee79d4473eb201b519fa40f989b842e373237395a3421f52\n    Successfully built pylatexenc\n    Installing collected packages: pylatexenc\n    Successfully installed pylatexenc-2.10\n\n\n\n```python\n# Import numpy, matplotlib, qiskit\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom qiskit import *\nfrom qiskit.compiler import transpile, assemble\nfrom qiskit.tools.visualization import *\nfrom qiskit.tools.jupyter import *\nfrom qiskit.visualization import *\n\nfrom math import *\n\n# Definition of SPIN correlation with qbits array format in quiskit for more clarity\nSPIN_DOWN = [1,0]\nSPIN_UP = [0,1]\n```\n\n## Circuits\n\nHere we define the functions which return the circuits\n\n\n```python\ndef Nodo_exec_counts(circ, shots=1000):\n  \"\"\"\n  Get the get_count() object of quiskit when execute specific number of shots.\n  Executed in 'qasm_simulator' backend.\n  Args:\n    circ: QuantumCircuit to execute\n    shots: number of executions, default=1000\n\n  Return:\n    get_count() object of quiskit\n  \"\"\"\n  backend = BasicAer.get_backend('qasm_simulator') # the device to run on\n  result = execute(circ, backend, shots=shots).result().get_counts()\n  #print(result)\n  return result\n\ndef Nodo_exec(circ):\n  \"\"\"\n  Get the qbit value in output when executed 1 shot.\n  Executed in 'qasm_simulator' backend.\n  Args:\n    circ: QuantumCircuit to execute\n\n  Return:\n    SPIN_DOWN or SPIN_UP matrix\n  \"\"\"\n  backend = BasicAer.get_backend('qasm_simulator') # the device to run on\n  result = execute(circ, backend, shots=1).result().get_counts()\n  #print(result)\n  return SPIN_DOWN if \"0\" in result and result[\"0\"]==1 else SPIN_UP\n```\n\n### Ising Without Magnetism\n\n\n```python\ndef ISING_GATE():\n  \"\"\"\n  Define the ISING circuit without setting the inputs for be used as sub_circuit\n  or gate in others circuits\n\n  Return:\n    ISING circuite\n\n  \"\"\"\n  circ = QuantumCircuit(5, name=\"ISING\") \n  #circ.initialize(SPIN_DOWN, 3)\n\n  circ.mcx([0,1,2],3)\n  #######\n  circ.barrier()\n  circ.x(0)\n  circ.x(1)\n  circ.x(2)\n  circ.mcx([0,1,2],3)\n  circ.x(0)\n  circ.x(1)\n  circ.x(2)\n  circ.barrier()\n  ######\n  circ.x(3)\n  circ.cx(3,0)\n  circ.x(3)\n  circ.barrier()\n  #######\n  circ.ccx(3,4,0)\n  return circ\n\ndef ISING(S,A,B,P):\n  \"\"\"\n  Define the ISING circuit and setting the inputs for be executed\n  or gate in others circuits. Depends on the Temperature.\n\n  ARGS:\n    S: state of spin to execute and measure\n    A: state of the left neighbour\n    B: state of the right neighbour\n    P: [sqrt(1-P), sqrt(P)]. P depends on T\n\n  Return:\n    ISING circuite with initial states defines\n\n  \"\"\"\n  circ = QuantumCircuit(5, 1, name=\"ISING_GATE\") \n  circ.initialize(SPIN_DOWN, 3)\n  circ.initialize(S, 0)\n  circ.initialize(A,1)\n  circ.initialize(B,2)\n  circ.initialize(P[0],4)\n\n  circ.mcx([0,1,2],3)\n  #######\n  circ.barrier()\n  circ.x(0)\n  circ.x(1)\n  circ.x(2)\n  circ.mcx([0,1,2],3)\n  circ.x(0)\n  circ.x(1)\n  circ.x(2)\n  circ.barrier()\n  ######\n  circ.x(3)\n  circ.cx(3,0)\n  circ.x(3)\n  circ.barrier()\n  #######\n  circ.ccx(3,4,0)\n  circ.measure(0, 0)\n  return circ\n```\n\n\n```python\nP = exp(-4/3)\nP_calc = [sqrt(1-P), sqrt(P)]\ncirc = ISING(SPIN_UP,SPIN_UP,SPIN_UP, [P_calc])\ncirc.draw(output='mpl')\n```\n\n\n```python\nresult = Nodo_exec_counts(circ)\nprint(result)\nplot_histogram(result)\n```\n\n### Ising Magnetism\n\n\n```python\ndef getP_i(T,h):\n  \"\"\"\n  Calculate the hopping probabilities\n\n  ARGS:\n    T: Temperature\n    h: Magnetic field\n\n  Return:\n    P1 = min(1, np.exp(-1*(4-2*h)/T))\n    P2 = min(1, np.exp (  (4-2*h)/T  ))\n    P3 = np.exp(-2*h/T)\n    P4 = np.exp(-1*(4+2*h)/T)\n\n  \"\"\"\n  p1 = min(1, np.exp(-1*(4-2*h)/T))\n  p2 = min(1, np.exp (  (4-2*h)/T  ))\n  p3 = np.exp(-2*h/T)\n  p4 = np.exp(-1*(4+2*h)/T)\n  P1 = [np.sqrt(1-p1), np.sqrt(p1)]\n  P2 = [np.sqrt(1-p2), np.sqrt(p2)]\n  P3 = [np.sqrt(1-p3), np.sqrt(p3)]\n  P4 = [np.sqrt(1-p4), np.sqrt(p4)]\n  return P1, P2, P3, P4\n```\n\n\n```python\ndef ISINH(S,A,B,P1,P2,P3,P4):\n  \"\"\"\n  Define the ISINH circuit and setting the inputs for be executed\n  or gate in others circuits. Depend on the Temperature and Magnetic field \n\n  ARGS:\n    S: state of spin to execute and measure\n    A: state of the left neighbour\n    B: state of the right neighbour\n    P1 = min(1, np.exp(-1*(4-2*h)/T))\n    P2 = min(1, np.exp (  (4-2*h)/T  ))\n    P3 = np.exp(-2*h/T)\n    P4 = np.exp(-1*(4+2*h)/T)\n\n  Return:\n    ISINH circuite with initial states defines\n\n  \"\"\"\n  circ = QuantumCircuit(9, 1) \n \n  circ.initialize(S, 0)\n  circ.initialize(A,1)\n  circ.initialize(B,2)\n  circ.initialize(SPIN_DOWN, 3)\n  circ.initialize(SPIN_DOWN, 4)\n  \n  circ.initialize(P1,5)\n  circ.initialize(P2,6)\n  circ.initialize(P3,7)\n  circ.initialize(P4,8)\n  \n  circ.mcx([0,1,2],3)\n  \n  circ.x(0)\n  circ.x(1)\n  circ.x(2)\n  circ.mcx([0,1,2],3)\n  circ.x(0)\n  circ.x(1)\n  circ.x(2)\n  circ.barrier()\n  ######\n  circ.x(1)\n  circ.mcx([0,1,2], 4)\n  circ.x(1)\n  circ.x(2)\n  circ.mcx([0,1,2], 4)\n  circ.x(2)\n  circ.barrier()\n  ######\n  circ.x(2)\n  circ.mcx([2,3,5],0)\n  circ.x(2)\n  circ.mcx([2,3,8],0)\n\n  circ.barrier()\n  ######\n\n  circ.mcx([4,7], 0)\n\n  circ.x(1)\n  circ.x(2)\n  circ.x(3)\n  circ.mcx([1,2,3,6], 0)\n  circ.x(1)\n  circ.x(2)\n  circ.x(3)\n  circ.barrier()\n\n  ######\n\n  circ.x(3)\n  circ.x(4)\n  circ.mcx([2,3,4],0)\n  circ.x(3)\n  circ.x(4)\n\n  circ.x(3)\n  circ.x(4)\n  circ.mcx([1,3,4],0)\n  circ.x(3)\n  circ.x(4)\n\n  circ.x(3)\n  circ.x(4)\n  circ.mcx([1,2,3,4],0)\n  circ.x(3)\n  circ.x(4)\n\n\n  circ.barrier()\n  ######\n  circ.measure(0, 0)\n  return circ\n```\n\n\n```python\nP1,P2,P3,P4 = getP_i(T=1,h=1)\ncirc = ISINH(SPIN_UP,SPIN_UP,SPIN_UP,P1,P2,P3,P4)\ncirc.draw(output='mpl')\n```\n\n\n```python\nresult = Nodo_exec_counts(circ)\nprint(result)\nplot_histogram(result)\n```\n\n### Isign One Measure\n\n\n```python\ndef ISING_one_measure(S,A,B,P,M,generations=1):\n  \"\"\"\n  Define ISING circuit design specifically to 4 spins and avoid measure in each \n  generation only in the end. We define a cyclic circuite which\n\n  ARGS:\n    S: state of spin to execute and measure\n    A: state of the left neighbour\n    B: state of the right neighbour\n    P1 = min(1, np.exp(-1*(4-2*h)/T))\n    P2 = min(1, np.exp (  (4-2*h)/T  ))\n    P3 = np.exp(-2*h/T)\n    P4 = np.exp(-1*(4+2*h)/T)\n\n  Return:\n    ISINH circuite with initial states defines\n\n  \"\"\"\n  circ = QuantumCircuit(6, 4, name=\"ISING_no_measure\") \n \n  circ.initialize(S, 0)\n  circ.initialize(A,1)\n  circ.initialize(B,2)\n  circ.initialize(SPIN_DOWN, 3)\n  circ.initialize(P,4)\n  circ.initialize(M,5)\n  \n  for i in range(generations):\n    ising = ISING_GATE().to_instruction()\n    circ.append(ising, [0,1,2,3,4])\n    #BLOQUE DE ISING\n    circ.swap(0,5)\n    circ.swap(1,2)\n    circ.append(ising, [0,1,2,3,4])\n    #BLOQUE DE ISING\n    circ.swap(0,1)\n    circ.swap(1,2)\n    circ.swap(1,5)\n    circ.append(ising, [0,1,2,3,4])\n    #BLOQUE ISING\n    circ.swap(1,2)\n    circ.swap(0,5)\n    circ.append(ising, [0,1,2,3,4])\n    #BLOQUE ISING\n    circ.swap(0,2)\n    circ.swap(1,2)\n    circ.swap(2,5)\n\n  ###### Hay que hacer un measure de todos los qubits, importante meterlo al final\n  circ.measure(0, 0)\n  circ.measure(1, 3)\n  circ.measure(2, 1)\n  circ.measure(5, 2)\n  return circ\n```\n\n\n```python\ncirc = ISING_one_measure(SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN, generations=1)\ncirc.draw(output='mpl')\n```\n\n\n```python\ncirc = ISING_one_measure(SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN, generations=2)\ncirc.draw(output='mpl')\n```\n\n## Ising Loop Implementations\n\n\n```python\n# Auxiliar function to print spin as rows\ndef qbit_to_arrow(S):\n  \"\"\"\n  Print qbit or spin in arrow unicode format\n\n  ARGS:\n    S: qbit or spin array format. Ej: [0,0]\n\n  Return:\n    Unicode arrow\n\n  Raise:\n    Exception when the spin is not [0,1] or [1,0]\n  \"\"\"\n  arrows = []\n  for i in S:\n    if i == SPIN_UP:\n      arrows.append(u\"\\u2191\")\n    elif i == SPIN_DOWN:\n      arrows.append(u\"\\u2193\")\n    else:\n      print(i)\n      raise Exception(\"Not SPIN_DOWN or SPIN_UP\")\n\n  return arrows\n```\n\n### Ising 1D\n\n#### Without Magnetism\n\n\n```python\ndef set_neighbours(S):\n  \"\"\"\n  Return:\n    As: Left neightbour\n    As: Left neightbour\n  \"\"\"\n  As = left_neighbours(S)\n  Bs = right_neighbours(S)\n\n  return As, Bs\n\ndef left_neighbours(Ss):\n  left = []\n  for i in range(len(Ss)):\n    left.append(Ss[(i-1)%len(Ss)])\n\n  return left\n\ndef right_neighbours(Ss):\n  right = []\n  for i in range(len(Ss)):\n    right.append(Ss[(i+1)%len(Ss)])\n\n  return right\n```\n\n\n```python\ndef generation_update(circuit_def, Ss, P):\n  As, Bs = set_neighbours(Ss)\n  return {i: circuit_def(Ss[i], As[i], Bs[i], P) for i in range(len(Ss))}\n\ndef Ising(T, Ss=[SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN], generations=10):\n\n  As, Bs = set_neighbours(Ss)\n\n  #print(\"As Bs\", As, Bs)\n\n  P = exp(-4/T)\n  P_calc = [sqrt(1-P), sqrt(P)]\n\n  circuit_def = ISING\n\n  circuitos = generation_update(circuit_def, Ss, [P_calc])\n\n  spin = []\n  #print('Spin Incial:', Ss)\n  for i in range(generations):\n    #print(\"Generation\", i)\n    for j in range(0,len(Ss),2):\n      Ss[j] = Nodo_exec(circuitos[j])\n    circuitos = generation_update(circuit_def, Ss, [P_calc])\n\n    #print('\\tSpin:', Ss)\n\n    for j in range(1,len(Ss),2):\n      Ss[j] = Nodo_exec(circuitos[j])\n    circuitos = generation_update(circuit_def, Ss, [P_calc])\n\n    #print('\\tSpin:', Ss)\n\n    spin.append((sum([k[1] for k in Ss])*1 - sum([k[0] for k in Ss])) / len(Ss))\n\n  return Ss, sum(spin)/generations\n\n  \ndef Ising_with_warmup(T, Ss=[SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN], num_warmup=10, generations=10):\n  Ss, avg_up = Ising(T, Ss, generations=num_warmup) # calentamiento\n  Ss, avg_up = Ising(T, Ss, generations=generations)\n  return Ss, avg_up\n```\n\n\n```python\nS = [SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN]\nspins, avg_up = Ising_with_warmup(T=1, Ss=S, num_warmup=50, generations=50)\n```\n\n\n```python\nprint(spins)\nprint(qbit_to_arrow(spins))\nprint('AVG SPIN_UP:', avg_up)\n```\n\n    [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    ['\u2191', '\u2191', '\u2191', '\u2191', '\u2191', '\u2191', '\u2191', '\u2191']\n    AVG SPIN_UP: 0.25\n\n\n\n```python\nS = [SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN]\navg_up_vec = []\nTs = np.linspace(0.1,2,20)\nfor i in Ts:\n  _ , avg_up = Ising_with_warmup(T=i, Ss=S, num_warmup=50, generations=50)\n  avg_up_vec.append(avg_up)\n```\n\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [0, 1], [0, 1], [0, 1], [1, 0], [1, 0], [1, 0], [1, 0]] [[0, 1], [0, 1], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[0, 1], [0, 1], [0, 1], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[0, 1], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 1]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [1, 0], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [1, 0]]\n    Spin Incial: [[1, 0], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [0, 1], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 1]]\n    Spin Incial: [[0, 1], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [1, 0]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [1, 0], [1, 0]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [1, 0], [1, 0], [1, 0]] [[0, 1], [0, 1], [0, 1], [1, 0], [1, 0], [1, 0], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [1, 0], [1, 0], [1, 0], [0, 1]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 1], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n\n\n\n```python\nplt.plot(Ts, avg_up_vec, '.')\nplt.xlabel(\"Temperature (J/K)\", fontsize = 14)\nplt.ylabel(\"Spin\", fontsize = 14)\nplt.title(\"Spin dependence of temperature\", fontsize = 14)\n```\n\n#### With Magnetism\n\n\n```python\ndef generation_update_mag(circuit_def, Ss, P):\n  As, Bs = set_neighbours(Ss)\n  return {i: circuit_def(Ss[i], As[i], Bs[i], P[0], P[1], P[2], P[3]) for i in range(len(Ss))}\n```\n\n\n```python\ndef Ising_Magnetic(h, T, Ss=[SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN], generations=10):\n\n  As, Bs = set_neighbours(Ss)\n\n  #print(\"As Bs\", As, Bs)\n\n  P1, P2, P3, P4 = getP_i(T,h)\n\n  P = [P1, P2, P3, P4]\n\n  circuit_def = ISINH\n\n  circuitos = generation_update_mag(circuit_def, Ss, P)\n\n  spin = []\n  #print('Spin Incial:', Ss)\n  for i in range(generations):\n    #print(\"Generation\", i)\n    for j in range(0,len(Ss),2):\n      Ss[j] = Nodo_exec(circuitos[j])\n    circuitos = generation_update_mag(circuit_def, Ss, P)\n\n    #print('\\tSpin:', Ss)\n\n    for j in range(1,len(Ss),2):\n      Ss[j] = Nodo_exec(circuitos[j])\n    circuitos = generation_update_mag(circuit_def, Ss, P)\n\n    #print('\\tSpin:', Ss)\n\n    spin.append((sum([k[1] for k in Ss])*1 - sum([k[0] for k in Ss])) / len(Ss))\n\n  return Ss, sum(spin)/generations\n\ndef Ising_Magnetic_with_warmup(h, T, Ss=[SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN], num_warmup=5, generations=10):\n  Ss, _ = Ising_Magnetic(h, T, Ss, generations=num_warmup)\n  Ss, avg_up = Ising_Magnetic(h, T, Ss, generations=generations)\n  return Ss, avg_up\n```\n\n\n```python\nspins, avg_up = Ising_Magnetic(h=1, T=1, Ss=[SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN], generations=10)\n```\n\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0]]\n\n\n\n```python\nprint(spins)\nprint(qbit_to_arrow(spins))\nprint('AVG SPIN_UP:', avg_up)\n```\n\n    [[0, 1], [0, 1], [0, 1], [0, 1]]\n    ['\u2191', '\u2191', '\u2191', '\u2191']\n    AVG SPIN_UP: 0.95\n\n\n\n```python\nspins, avg_up = Ising_Magnetic_with_warmup(h=1, T=1, Ss=[SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN], num_warmup=5, generations=10)\n```\n\n\n```python\nprint(spins)\nprint(qbit_to_arrow(spins))\nprint('AVG SPIN_UP:', avg_up)\n```\n\n    [[0, 1], [0, 1], [0, 1], [0, 1]]\n    ['\u2191', '\u2191', '\u2191', '\u2191']\n    AVG SPIN_UP: 1.0\n\n\n\n```python\n#We use low temperatures to see the how the function becomes step at h=0\nS = [SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN,SPIN_DOWN]\nT_vec = [0.1, 1, 5]\nh_num = 10 \nh_vec = np.linspace(0.3, 2, h_num)\navg_spin_vec = np.zeros([len(T_vec),h_num])\nfor i in range(len(T_vec)):\n  for j in range(h_num):\n    _ , avg_spin_vec[i, j] = Ising_Magnetic_with_warmup(h_vec[j], T_vec[i], Ss=S, \n                                                 num_warmup=5, generations=5)\n```\n\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [1, 0], [1, 0], [1, 0], [0, 1]] [[1, 0], [1, 0], [0, 1], [0, 1], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [1, 0], [1, 0], [1, 0], [0, 1]]\n    As Bs [[1, 0], [0, 1], [1, 0], [0, 1], [1, 0]] [[1, 0], [0, 1], [1, 0], [1, 0], [0, 1]]\n    Spin Incial: [[0, 1], [1, 0], [0, 1], [1, 0], [1, 0]]\n    As Bs [[0, 1], [1, 0], [1, 0], [1, 0], [0, 1]] [[1, 0], [1, 0], [0, 1], [0, 1], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [0, 1], [0, 1]]\n    As Bs [[1, 0], [0, 1], [0, 1], [0, 1], [1, 0]] [[0, 1], [0, 1], [1, 0], [1, 0], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [1, 0], [1, 0]]\n    As Bs [[1, 0], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [1, 0], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [1, 0]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [1, 0], [1, 0], [1, 0], [1, 0]] [[1, 0], [1, 0], [1, 0], [0, 1], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [1, 0], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [1, 0], [0, 1], [0, 1], [1, 0]] [[0, 1], [0, 1], [1, 0], [0, 1], [1, 0]]\n    Spin Incial: [[1, 0], [0, 1], [0, 1], [1, 0], [0, 1]]\n    As Bs [[0, 1], [0, 1], [1, 0], [0, 1], [0, 1]] [[1, 0], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [1, 0], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [1, 0], [1, 0], [1, 0], [0, 1]] [[1, 0], [1, 0], [0, 1], [0, 1], [1, 0]]\n    Spin Incial: [[1, 0], [1, 0], [1, 0], [0, 1], [0, 1]]\n    As Bs [[0, 1], [1, 0], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [1, 0]]\n    Spin Incial: [[1, 0], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [1, 0], [1, 0], [0, 1]] [[1, 0], [1, 0], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [1, 0], [1, 0], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [1, 0], [0, 1], [0, 1]] [[1, 0], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [1, 0], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    Spin Incial: [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]\n    As Bs [[0, 1], [1, 0], [0, 1], [0, 1], [0, 1]] [[0, 1], [0, 1], [0, 1], [0, 1], [1, 0]]\n    Spin Incial: [[1, 0], [0, 1], [0, 1], [0, 1], [0, 1]]\n\n\n\n```python\nfor i in range(len(T_vec)):\n  plt.plot(h_vec, avg_spin_vec[i, :], '.')\nplt.xlabel(\"Magnetic field (J)\", fontsize = 14)\nplt.ylabel(\"Spin\", fontsize = 14)\nplt.title(\"Spin dependence of magnetic field\", fontsize = 14)\nplt.legend([\"T = 0.1\", \"T = 1\", \"T = 5\"])\n```\n", "meta": {"hexsha": "624beae7bbcfcdf5540025eee9d78cb21fb1c3ac", "size": 288448, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "quantum_ising.ipynb", "max_stars_repo_name": "OBouzid/Quantum_Ising", "max_stars_repo_head_hexsha": "b8f9d5722d95a152db73017d0049500ec127bd32", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "quantum_ising.ipynb", "max_issues_repo_name": "OBouzid/Quantum_Ising", "max_issues_repo_head_hexsha": "b8f9d5722d95a152db73017d0049500ec127bd32", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quantum_ising.ipynb", "max_forks_repo_name": "OBouzid/Quantum_Ising", "max_forks_repo_head_hexsha": "b8f9d5722d95a152db73017d0049500ec127bd32", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 288448.0, "max_line_length": 288448, "alphanum_fraction": 0.8819301919, "converted": true, "num_tokens": 20622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3812195803163618, "lm_q2_score": 0.09534947196849916, "lm_q1q2_score": 0.03634908568721795}}
{"text": "# Big Data and Data Science\n\n## Big Data\n\n\u201cEvery day, we create 2.5 quintillion bytes of data\u2014so much that 90% of the data in the world today has been created in the last two years alone.\u201d _IBM. 2012. \u201cWhat is big data?\u201d  Retrieved from [http://www-01.ibm.com/software/data/bigdata/](http://www-01.ibm.com/software/data/bigdata/)_ Due to the growing complexity of digital social networks and the huge quantity of data they produce daily, it\u2019s crucial to  deal with \u201cbig data\u201d efficiently. A number of tools and technologies (Map-Reduce, NoSQL, Hadoop, Hive, cloud computing, parallel processing, clustering, MPP, virtualization, large grid environments, and so on) have been developed to store and process big data. While big-data technologies have established the ability to collect and process large amounts of data, most organizations struggle with understanding the data and taking advantage of its value. According to an Economist report: \u201cExtracting value from big data remains elusive for many organizations. For most companies today, data are abundant and readily available, but not well used.\u201d _Economist. 2012. Economist Intelligence Unit Retrieved from [http://www.eiu.com/](http://www.eiu.com/)_\n\nA central issue with \u201cbig data\u201d is that not all of the data will be relevant or useful in solving a particular problem and will often add noise instead. However, the purpose of the present research is to better measure the system state of social networks, and this knowledge of state can help with a central issue: which data and algorithms are relevant to a particular problem? As our basic algorithm is to find tags in text, look up entropies, and sum, it is easily parallelizable and scales well to \u201cbig data.\u201d \n\nCentral issues with big data:\n\n* Finding the signal in the noise\n* Data silos (isolated non-ingregrated data)\n* Inaccurate data\n* Algorithms that scale\n* Echo-chamber effect (Much of big data comes from the web. Whenever the source of information for a big data analysis is itself a product of big data, opportunities for vicious cycles abound)\n* Too many (spurious) correlations\n* Storage\n* Less structured, heterogenous  \n* Recognition (identifying what's what in the data) \n* Discovery (efficient ways to find the specific data that can solve a particular problem) \n* Semantics (effective and efficient ways to contextualize the \"meaning\"  of the data)\n* Visualization --effective ways to analyze and visualize n-dimensional data\n\n## Data munging\n\nData munging (sometimes referred to as data wrangling) is the process of transforming and mapping data from one \"raw\" data form into another format with the intent of making it more appropriate and valuable for a variety of downstream purposes such as analytics.\n\n## Data cleaning \n\n * Save original data\n * Identify missing data\n * Identify placeholder data (e.g. 0's for NA's) \n * Identify outliers\n * Check for overall plausibility and errors (e.g., typos, unreasonable ranges)\n * Identify highly correlated variables\n * Identify variables with (nearly) no variance\n * Identify variables with strange names or values\n * Check variable classes (eg. Characters vs factors)\n * Remove/transform some variables (maybe your model does not like categorial variables)\n * Rename some variables or values (if not all data is useful)\n * Check some overall pattern (statistical/ numerical summaries)\n * Possibly center/scale variables\n\n# Exploratory Data Analysis\n\nIn the this lesson, we look statistical and graphical techniques summarize their main characteristics of one, two variable, and multi-variable data sets. To find relationships amongst variables and to find the variables which are most interesting for a particular analysis task.\n\nRationale: Exploratory data analysis helps one understand the data, to form and change new theories, and decide which techniques are appropriate for analysis. After a model is finished, exploratory data analysis can look for patterns in these data that may have been missed by the original hypothesis tests. Successful exploratory analyses help the researcher modify theories and refine the analysis.\n\n\n* Suggest hypotheses about the causes of observed phenomena\n * Assess assumptions on which statistical inference will be based\n * Support the selection of appropriate statistical tools and techniques\n * Provide a basis for further data collection through surveys or experiments\n\n_Five methods that are must have_:\n  \n * Five number summaries (mean/median, min, max, q1, q3)\n * Histograms \n * Line charts\n * Box and whisker plots\n * Pairwise scatterplots (scatterplot matrices)\n \n * What values do you see?\n * What distributions do you see?\n * What relationships do you see?\n * What relationships do you think might benefit the prediction problem?\n\n\n* Answer the following questions for the data in each column:\n    * How is the data distributed?\n    * Test distribution assumptions (e.G. Normal distributions or skewed?)\n    * What are the summary statistics?\n    * Are there anomalies/outliers?\n* Identify useful raw data & transforms (e.g. log(x))\n* Identify data quality problems\n* Identify outliers\n* Identify subsets of interest\n* Suggest functional relationships\n\n\n\n```python\n%matplotlib inline \nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats\nimport seaborn as sns\n\n# Make plots larger\nplt.rcParams['figure.figsize'] = (15, 9)\n```\n\n\n```python\niris = sns.load_dataset(\"iris\")\nsns.pairplot(iris, hue=\"species\")\n```\n\n## Probability, random variables and probability distributions\n\n* Probability\n* Random variables\n* Probability distributions\n    * Uniform\n    * Normal\n    * Binomial\n    * Poisson     \n    * Fat Tailed\n    \n## Probability\n\n* Probability is a measure of the likelihood of a random phenomenon or chance behavior.  Probability describes the long-term proportion with which a certain outcome will occur in situations with short-term uncertainty. \n* Probability is expressed in numbers between 0 and 1.  Probability = 0 means the event never happens; probability = 1 means it always happens.\n* The total probability of all possible event always sums to 1. \n\n## Sample Space\n\n* Coin Toss ={head,tail} \n* Two coins S = {HH, HT, TH, TT}\n* Inspecting a part ={good,bad}\n* Rolling a die S ={1,2,3,4,5,6}\n\n## Random Variables\n\nIn probability and statistics, a random variable,  or stochastic variable is a variable whose value is subject to variations due to chance (i.e. it can take on a range of values)\n\n\n* Coin Toss ={head,tail} \n* Rolling a die S ={1,2,3,4,5,6}\n\nDiscrete Random Variables\n\n* Random variables (RVs) which may take on only a countable number of distinct values\nE.g. the total number of tails X you get if you flip 100 coins\n* X is a RV with arity k if it can take on exactly one value out of {x1, \u2026, xk}\nE.g. the possible values that X can take on are 0, 1, 2, \u2026, 100\n\nContinuous Random Variables\n\n* Probability density function (pdf) instead of probability mass function (pmf)\n* A pdf is any function f(x) that describes the probability density in terms of the input variable x.\n\n\n\n## Probability distributions\n\n* We use probability distributions because they model data in real world.\n* They allow us to calculate what to expect and therefore understand what is unusual.\n* They also provide insight in to the process in which real world data may have been generated.\n* Many machine learning algorithms have assumptions based on certain probability distributions.\n\n_Cumulative distribution function_\n\nA probability distribution Pr on the real line is determined by the probability of a scalar random variable X being in a half-open interval (-$\\infty$, x], the probability distribution is completely characterized by its cumulative distribution function:\n\n$$\n F(x) = \\Pr[X \\leq x] \\quad \\forall \\quad x \\in R .\n$$\n\n\n## Uniform Distribution\n\n$$\nX \\equiv U[a,b]\n$$\n\n$$\n f(x) = \\frac{1}{b-a} \\quad for \\quad a \\lt x \\lt b\n$$\n\n$$\n f(x) = 0 \\quad for \\quad a \\leq x  \\quad or  \\quad \\geq b\n$$\n\n$$\n F(x) = \\frac{x-a}{b-a} \\quad for \\quad a \\leq x \\lt b\n$$\n\n$$\nF(x) = 0 \\quad for \\quad x  \\lt a  \\quad \n F(x) = 1 \\quad for \\quad x  \\geq b\n$$\n\n\n\n_Continuous Uniform Distribution_\n\nIn probability theory and statistics, the continuous uniform distribution or rectangular distribution is a family of symmetric probability distributions such that for each member of the family, all intervals of the same length on the distribution's support are equally probable.\n\n- from [Uniform distribution (continuous  Wikipedia)](https://en.wikipedia.org/wiki/Uniform_distribution_(continuous))\n    \n\n\n\n\n_Discrete Uniform Distribution_\n\nIn probability theory and statistics, the discrete uniform distribution is a symmetric probability distribution whereby a finite number of values are equally likely to be observed; every one of n values has equal probability 1/n. Another way of saying \"discrete uniform distribution\" would be \"a known, finite number of outcomes equally likely to happen\".\n\n- from [Uniform distribution (discrete)  Wikipedia)](https://en.wikipedia.org/wiki/Uniform_distribution_(discrete))\n    \n\n\n\n\n## Normal Distribution\n\nIn probability theory, the normal (or Gaussian) distribution is a very common continuous probability distribution. The normal distribution is remarkably useful because of the central limit theorem. In its most general form, under mild conditions, it states that averages of random variables independently drawn from independent distributions are normally distributed. Physical quantities that are expected to be the sum of many independent processes (such as measurement errors) often have distributions that are nearly normal. \n\n- from [Normal Distribution - Wikipedia)](https://en.wikipedia.org/wiki/Normal_distribution)\n   \n\n$$\nX \\sim \\quad N(\\mu, \\sigma^2)\n$$\n\n\n$$\n f(x) = \\frac{1}{\\sigma \\sqrt {2\\pi }} e^{-\\frac{( x - \\mu)^2}{2\\sigma^2}} \\quad \n$$\n\n\n\n\n\n\n\nNormal cumulative distribution function\n\n\n\n_Properties of normal distribution_\n\n- symmetrical, unimodal, and bell-shaped\n- on average, the error component will equal zero, the error above and below the mean will cancel out\n- Z-Score is a statistical measurement is (above/below) the mean of the data\n- important characteristics about z scores:\n  1. mean of z scores is 0\n  2. standard deviation of a standardized variable is always 1\n  3. the linear transformation does not change the _form_ of the distribution\n\n\nThe normal (or Gaussian) distribution was discovered in 1733 by Abraham de Moivre as an approximation to the binomial distribution when the number of trails is large.    \n\n\n\n- from [Abraham de Moivre - Wikipedia)](https://en.wikipedia.org/wiki/Abraham_de_Moivre)\n\nThe Gaussian distribution was derived in 1809 by Carl Friedrich Gauss.    \n\n\n\n- from [Carl Friedrich Gauss - Wikipedia)](https://en.wikipedia.org/wiki/Carl_Friedrich_Gauss)\n\nImportance lies in the Central Limit Theorem, which states that the sum of a large number of independent random variables (binomial, Poisson, etc.) will approximate a normal distribution\n\n\n## Central Limit Theorem\n\nIn probability theory, the central limit theorem (CLT) states that, given certain conditions, the arithmetic mean of a sufficiently large number of iterates of independent random variables, each with a well-defined expected value and well-defined variance, will be approximately normally distributed, regardless of the underlying distribution. The central limit theorem has a number of variants. In its common form, the random variables must be identically distributed. \n\n- from [Central Limit Theorem - Wikipedia)](https://en.wikipedia.org/wiki/Central_limit_theorem)\n   \n\nThe Central Limit Theorem tells us that when the sample size is large the average $\\bar{Y}$ of a random sample follows a normal distribution centered at the population average $\\mu_Y$ and with standard deviation equal to the population standard deviation $\\sigma_Y$, divided by the square root of the sample size $N$. \n\nThis means that if we subtract a constant from a random variable, the mean of the new random variable shifts by that constant. If $X$ is a random variable with mean $\\mu$ and $a$ is a constant, the mean of $X - a$ is $\\mu-a$. \n\nThis property also holds for the spread, if $X$ is a random variable with mean $\\mu$ and SD $\\sigma$, and $a$ is a constant, then the mean and SD of $aX$ are $a \\mu$ and $\\|a\\| \\sigma$ respectively.\nThis implies that if we take many samples of size $N$ then the quantity \n\n$$\n\\frac{\\bar{Y} - \\mu}{\\sigma_Y/\\sqrt{N}}\n$$\n\nis approximated with a normal distribution centered at 0 and with standard deviation 1.\n\n## The t-distribution\n\nIn probability and statistics, Student's t-distribution (or simply the t-distribution) is any member of a family of continuous probability distributions that arises when estimating the mean of a normally distributed population in situations where the sample size is small and population standard deviation is unknown. Whereas a normal distribution describes a full population, t-distributions describe samples drawn from a full population; accordingly, the t-distribution for each sample size is different, and the larger the sample, the more the distribution resembles a normal distribution.\nThe t-distribution plays a role in a number of widely used statistical analyses, including the Student's t-test for assessing the statistical significance of the difference between two sample means, the construction of confidence intervals for the difference between two population means, and in linear regression analysis. The Student's t-distribution also arises in the Bayesian analysis of data from a normal family.\n\n- from [The t-distribution - Wikipedia)](https://en.wikipedia.org/wiki/Student%27s_t-distribution)\n\nWhen the CLT does not apply (i.e. as the number of samples is large), there is another option that does not rely on large samples When a the original population from which a random variable, say $Y$, is sampled is normally distributed with mean 0 then we can calculate the distribution of \n\n\nnumber of variants. In its common form, the random variables must be identically distributed. \n\n\n\n$$\n\\sqrt{N} \\frac{\\bar{Y}}{s_Y}\n$$\n\n\n\n\nNormal cumulative distribution function\n\n\n_Binomial Distribution_\n\nIn probability theory and statistics, the binomial distribution with parameters n and p is the discrete probability distribution of the number of successes in a sequence of n independent yes/no experiments, each of which yields success with probability p. A success/failure experiment is also called a Bernoulli experiment or Bernoulli trial; when n = 1, the binomial distribution is a Bernoulli distribution.\n\n- from [Binomial Distribution - Wikipedia](https://en.wikipedia.org/wiki/Binomial_distribution)\n\n\n   \nBinomial Distribution    \n\n\nBinomial cumulative distribution function\n\n\n\n* The data arise from a sequence of n independent trials.\n* At each trial there are only two possible outcomes, conventionally called success and failure.\n* The probability of success, p, is the same in each trial.\n* The random variable of interest is the number of successes, X, in the n trials.\n* The assumptions of independence and constant p are important. If they are invalid,  so is the binomial distribution\n\n_Bernoulli Random Variables_\n\n* Imagine a simple trial with only two possible outcomes\n    * Success (S) with probabilty p.\n    * Failure (F) with probabilty 1-p.\n\n* Examples\n    * Toss of a coin (heads or tails)\n    * Gender of a newborn (male or female)\n\n## Poisson Distribution\n\n$X$ expresses the number of \"rare\" events\n\n$$\nX \\quad \\sim P( \\lambda )\\quad \\lambda \\gt 0\n$$\n\n$$\n    P(X = x) = \\frac{ \\mathrm{e}^{- \\lambda } \\lambda^x }{x!}  \\quad x=1,2,...,n\n$$\n\n\n_Poisson Distribution_\n\nIn probability theory and statistics, the Poisson distribution, named after French mathematician Sim\u00e9on Denis Poisson, is a discrete probability distribution that expresses the probability of a given number of events occurring in a fixed interval of time and/or space if these events occur with a constant rate per time unit and independently of the time since the last event. The Poisson distribution can also be used for the number of events in other specified intervals such as distance, area or volume.\n\nFor instance, an individual keeping track of the amount of mail they receive each day may notice that they receive an average number of 4 letters per day. If receiving any particular piece of mail doesn't affect the arrival times of future pieces of mail, i.e., if pieces of mail from a wide range of sources arrive independently of one another, then a reasonable assumption is that the number of pieces of mail received per day obeys a Poisson distribution. Other examples that may follow a Poisson: the number of phone calls received by a call center per hour, the number of decay events per second from a radioactive source, or the number of taxis passing a particular street corner per hour.\n\nThe Poisson distribution gives us a probability mass for discrete natural numbers *k* given some mean value &lambda;. Knowing that, on average, &lambda; discrete events occur over some time period, the Poisson distribution gives us the probability of seeing exactly *k* events in that time period.\n\nFor example, if a call center gets, on average, 100 customers per day, the Poisson distribution can tell us the probability of getting exactly 150 customers today.\n\n*k* &isin; **N** (i.e. is a natural number) because, on any particular day, you can't have a fraction of a phone call. The probability of any non-integer number of people calling in is zero. E.g., P(150.5) = 0.\n\n&lambda; &isin; **R** (i.e. is a real number) because, even though any *particular* day must have an integer number of people, the *mean* number of people taken over many days can be fractional (and usually is). It's why the \"average\" number of phone calls per day could be 3.5 even though half a phone call won't occur.\n\n\n- from [Poisson Distribution - Wikipedia)](https://en.wikipedia.org/wiki/Poisson_distribution)\n   \nPoisson Distribution    \n\n\nPoisson cumulative distribution function\n\n\n\n_Properties of Poisson distribution_\n\n* The mean number of successes from n trials is \u00b5 = np\n* If we substitute \u00b5/n for p, and let n tend to infinity, the binomial distribution becomes the Poisson distribution.\n* Poisson distributions are often used to describe the number of occurrences of a \u2018rare\u2019 event. For example\n    * The number of storms in a season\n    * The number of occasions in a season when river levels exceed a certain value\n* The main assumptions are that events occur \n    * at random (the occurrence of an event doesn\u2019t change the probability of  it happening again) \n    *  at a constant rate \n* Poisson distributions also arise as approximations  to  binomials when n is large and p is small.\n* When there is a large number of trials, but a very small probability of success, binomial calculation becomes impractical\n\n## Deriving the Poisson Distribution from the Binomial Distribution\n\nLet\u2019s make this a little more formal. The binomial distribution works when we have a fixed number of events n, each with a constant probability of success p. In the Poisson Distribution, we don't know the number of trials that will happen. Instead, we only know the average number of successes per time period, the rate $\\lambda$. So we know the rate of successes per day, or per minute but not the number of trials n or the probability of success p that was used to estimate to that rate. \n\nIf n is the number of trails in our time period, then np is the success rate or $\\lambda$, that is, $\\lambda$ = np. Solving for p, we get:\n\n$$\np=\\frac{\\lambda}{n} \\quad(1)\n$$\nSince the Binomial distribution is defined as below \n$$\n P(X=k) = \\binom{n}{k} p^k (1-p)^{n-k} \\quad k=1,2,...,n\n\\quad  (2)\n$$\nor equivelently\n$$\n P(X=k) = \\frac{n!}{k!(n-k)!} p^k (1-p)^{n-k} \\quad k=1,2,...,n\n\\quad  (3)\n$$\nBy substituting the above p from (1) into the binomial distribution (3)\n $$\n P(X=k) = \\frac{n!}{k!(n-k)!} {\\frac{\\lambda!}{n}}^k (1-{\\frac{\\lambda!}{n} })^{n-k}  \\quad  (4)\n $$\n\n         \n \nFor n large and p small:\n \n$$\n    P(X = k) \\equiv \\frac{ \\mathrm{e}^{- \\lambda } \\lambda^k }{k!}  \\quad k=1,2,...,n\\quad  (5)\n$$\n                                        \n \nWhich is the probability mass function for the Poisson distribution.\n\n## Fat-Tailed Distribution\n\nIn probability theory, the Fat-Tailed (or Gaussian) distribution is a very common continuous probability distribution. The Fat-Tailed distribution is remarkably useful because of the central limit theorem. In its most general form, under mild conditions, it states that averages of random variables independently drawn from independent distributions are Fat-Tailedly distributed. Physical quantities that are expected to be the sum of many independent processes (such as measurement errors) often have distributions that are nearly Fat-Tailed. \n\n- from [Fat-Tailed Distribution - Wikipedia)](https://en.wikipedia.org/wiki/Fat-Tailed_distribution)\n   \n\n_Properties of Fat-Tailed distribution_\n\n* Power law distributions: \n    * for variables assuming integer values > 0\n    * Prob [X=k] ~ Ck-\u03b1\n    * typically 0 < alpha < 2; smaller a gives heavier tail  \n* For binomial, normal, and Poisson distributions the tail probabilities approach 0 exponentially fast \n* What kind of phenomena does this distribution model?\n* What kind of process would generate it?\n\n## Cauchy Distribution\n\nAn example of a Fat-tailed distribution is the Cauchy distribution.\n\n_Cauchy Distribution_\n\n The Cauchy distribution, named after Augustin Cauchy, is a continuous probability distribution. It is also known, especially among physicists, as the Lorentz distribution (after Hendrik Lorentz), Cauchy\u2013Lorentz distribution, Lorentz(ian) function, or Breit\u2013Wigner distribution. The simplest Cauchy distribution is called the standard Cauchy distribution. It is the distribution of a random variable that is the ratio of two independent standard normal variables and has the probability density function\n\nThe Cauchy distribution is often used in statistics as the canonical example of a \"pathological\" distribution since both its mean and its variance are undefined. (But see the section Explanation of undefined moments below.) The Cauchy distribution does not have finite moments of order greater than or equal to one; only fractional absolute moments exist.[1] The Cauchy distribution has no moment generating function.\n\n- from [Cauchy Distribution - Wikipedia)](https://en.wikipedia.org/wiki/Cauchy_distribution)\n   \nCauchy Distribution    \n\n\nCauchy cumulative distribution function\n\n\n\n\n\n\n## Unsupervised Learning\n\nUnsupervised Learning tries to find hidden structure in unlabeled data. Unsupervised Learning has no feedback. This typically means that the data is not labled. Supervised learning has feedback/labels.\n\nFor example, if we had some e-mail that labbled some e-mail as spam and not-spam we could use a supervised learning algorthm like [Naive Bayes spam filtering](https://en.wikipedia.org/wiki/Naive_Bayes_spam_filtering) to classify any new e-mail as spam or non-spam.\n\nHowever, if we didn't have labeled data (also called training data) we might still be able to cluster spam and non-spam if we could come up with some measure of similarity or distance between words in the e-mails.\n\n\n \n\n*Unsupervised Learning is computational machinary to extract patterns from unlabled data*  \n\nImage courtesy of [clipartist.net](http://clipartist.net/)  \n\n[Clustering](https://en.wikipedia.org/wiki/Cluster_analysis) is probably the most common technique whose goal is to group data into similar groups based on a similarity/distance measure. Most of the focus of this module will be on clustering. We'll discuss and implement clustering in Lesson 2 of this module\n\n#### Types of  Clustering\n\n### Partitioning-based clustering\n\nPartition-based clustering iterativley assigns data to groups based on a [disatnce metric](https://en.wikipedia.org/wiki/Metric_(mathematics)) or [similarity](https://en.wikipedia.org/wiki/Similarity_measure)/dissimilarity measures until the group assignments are stable (i.e. the algorithm converges.)\n\n \n\n\n*K-means clustering*  \n\nImage courtesy of [clipartist.net](http://clipartist.net/)  \n\n\n### Hierarchical clustering  \n\n[Hierarchical clustering](https://en.wikipedia.org/wiki/Hierarchical_clustering) is a method of cluster analysis which builds a hierarchy of clusters either from the \"bottom up\" (agglomerative hierarchical clustering) by combiinimg the two \"closet\" or \"most similar\" points into a cluster then the next two closet, until all points are  merged as one moves up the hierarcy.\n\nConversely the data is split \"top down\" (divisive hierarchical clustering) so that there is the most seperation between the split groups and further splits are performed recursively untl there is a single data point in each group.\n\n \n\n*Hierarchical clustering*  \n\nImage courtesy of [clipartist.net](http://clipartist.net/)  \n\n\n### Density-based clustering\n\nensity-based clustering is based on probabilty distribution models. Clusters are defined as a set of distibutions then assigning points to the distibutions that they are most likely to belong. The most prominent method is known as Gaussian [mixture models](https://en.wikipedia.org/wiki/Mixture_model) that represent the clusters as multivariate normal distributions.  \n\n \n\n$$ p(\\boldsymbol{\\theta}) = \\sum_{i=1}^K\\phi_i \\mathcal{N}(\\boldsymbol{\\mu_i,\\sigma_i}) $$\n\n*Gaussian mixture model*  \n\nImage courtesy of [clipartist.net](http://clipartist.net/)  \n\n\n## Expectation-maximization\n\nThe [Expectation-maximization algorithm](https://en.wikipedia.org/wiki/Expectation%E2%80%93maximization_algorithm) is an iterative method for finding [maximum likelihood](https://en.wikipedia.org/wiki/Maximum_likelihood) or maximum a posteriori (MAP) estimates of parameters in statistical models, where the model depends on unobserved latent variables. We'll discuss and implement association rule learning in Lesson 4 of this module.\n\nGiven a statistica which generates a set $\\mathbf{X}$ of observed data, a set of unobserved latent data or missing values $\\mathbf{Z}$, and a vector of unknown parameters $\\boldsymbol\\theta$, along with a likelihood function $L(\\boldsymbol\\theta; \\mathbf{X}$, $\\mathbf{Z}) = p(\\mathbf{X}$, $\\mathbf{Z}|\\boldsymbol\\theta)$, the maximum likelihood estimate (MLE) of the unknown parameters is determined by the marginal likelihood of the observed data.  \n\n$$ L(\\boldsymbol\\theta; \\mathbf{X}) = p(\\mathbf{X}|\\boldsymbol\\theta) = \\sum_{\\mathbf{Z}} p(\\mathbf{X},\\mathbf{Z}|\\boldsymbol\\theta) $$ \n \nHowever, this quantity is often intractable (e.g. if $\\mathbf{Z}$ is a sequence of events, so that the number of values grows exponentially with the sequence length, making the exact calculation of the sum extremely difficult).  \n\nThe EM algorithm seeks to find the MLE of the marginal likelihood by iteratively applying the following two steps:  \n\n*Expectation step (E step):* Calculate the expected value of the log likelihood function, with respect to the conditional distribution of $\\mathbf{Z}$ given $\\mathbf{X}$ under the current estimate of the parameters\n $$ \n\\boldsymbol\\theta^{(t)}:\nQ(\\boldsymbol\\theta|\\boldsymbol\\theta^{(t)}) = \\operatorname{E}_{\\mathbf{Z}|\\mathbf{X},\\boldsymbol\\theta^{(t)}}\\left[ \\log L (\\boldsymbol\\theta;\\mathbf{X},\\mathbf{Z})  \\right]  $$ \n\n*Maximization step (M step):* Find the parameter that maximizes this quantity:\n $$ \n\\boldsymbol\\theta^{(t+1)} = \\underset{\\boldsymbol\\theta}{\\operatorname{arg\\,max}} \\ Q(\\boldsymbol\\theta|\\boldsymbol\\theta^{(t)}) $$ \n\n\n\n## Linear Discriminant Analysis (LDA)  \n\n[Linear Discriminant Analysis (LDA)](https://en.wikipedia.org/wiki/Linear_discriminant_analysis) which is related to blind signal separation techniques, such as those we've already studied in the dimensionality reduction module like: Principal component analysis, Independent component analysis,Non-negative matrix factorization, and  Singular value decomposition. LDA explicitly attempts to model the difference between the classes of data. That is,  like regression analysis, LDA attempts to express one response variable as a linear combination of other features or measurements. So while the math is similar to PCA and SVD, the intent is similar to regression (especially logistic regression) in that it creates a model. We'll discuss and implement association rule learning in Lesson 4 of this module.\n\nLDA is often based upon s Fisher's linear discriminant. Fisher defined the separation between these two distributions to be the ratio of the variance between the classes to the variance within the classes:\n\n$$ S=\\frac{\\sigma_{\\text{between}}^2}{\\sigma_{\\text{within}}^2}= \\frac{(\\vec w \\cdot \\vec \\mu_1 - \\vec w \\cdot \\vec \\mu_0)^2}{\\vec w^T \\sigma_1 \\vec w + \\vec w^T \\sigma_0 \\vec w} = \\frac{(\\vec w \\cdot (\\vec \\mu_1 - \\vec \\mu_0))^2}{\\vec w^T (\\sigma_0+\\sigma_1) \\vec w} $$\n\nThis measure is, in some sense, a measure of the signal-to-noise ratio for the class labelling. It can be shown that the maximum separation occurs when\n\n$$  \\vec{w} \\propto (\\sigma_0+\\sigma_1)^{-1}(\\vec{\\mu}_1 - \\vec{\\mu}_0) $$ \nWhen the assumptions of LDA are satisfied, the above equation is equivalent to LDA.\n\nIn essence, LDA picks a new basis that gives:\n\n\nTo do this, LDA uses eigenvectors based on between-class and  within-class covariance matrices.\n\n$$ max\\frac{(\\mu_1 - \\mu_2)^2}{\\sigma_1^2 + \\sigma_2^2}  $$\n\n \n\nImage courtesy of [clipartist.net](http://clipartist.net/)  \n\n## Association rule learning  \n\n[Association rule learning](https://en.wikipedia.org/wiki/Association_rule_learning) is an Unsupervised alogorthm interesting relations between variables in a data set. We'll discuss and implement association rule learning in Lesson 5 of this module. Association rule learning aims to discover interesting correlation or other relationships in large databases. It finds a rule of the form:\n\n$$ if\\quad A \\quad and \\quad B \\quad then \\quad C \\quad and \\quad D $$ \n\n  \n\n*Association rule Set Enumeration Tree*  \n\n## Artificial neural networks (ANN)\n\n[Artificial neural networks](https://en.wikipedia.org/wiki/Artificial_neural_network) are a  are a family of statistical learning models inspired by biological neural networks. Some neural network models like \n[Self-organizing map's](https://en.wikipedia.org/wiki/Self-organizing_map),[adaptive resonance theory (ART)](https://en.wikipedia.org/wiki/Adaptive_resonance_theory), [Restricted Boltzmann machines](https://en.wikipedia.org/wiki/Restricted_Boltzmann_machine) and [Hopfield network's](https://en.wikipedia.org/wiki/Hopfield_network). We'll discuss and implement various neural statistical learning models in a module entirely devoted to neural networks. We'll simply note here that some statistical neural learning models are unsupervised and put off discussing the details until the neural network module.\n\n  \n\nAn illustration of the training of a self-organizing map  \n\nArt [\"Somtraining\"](https://commons.wikimedia.org/wiki/File:Somtraining.svg##/media/File:Somtraining.svg) by [Mcld](http://www.mcld.co.uk/). Licensed under [CC BY-SA 3.0](http://creativecommons.org/licenses/by-sa/3.0) \n\n\n  \n\n*An illustration of a stable Hopfield network*   \n\nImage courtesy of [clipartist.net](http://clipartist.net/)  \n\n\n## Big Data and Unsupervised Learning\n\n\u201cEvery day, we create 2.5 quintillion bytes of data\u2014so much that 90% of the data in the world today has been created in the last two years alone.\u201d $[1]$ Due to the growing complexity of digital social networks and the huge quantity of data they produce daily, it\u2019s important that we deal with \u201cbig-data\u201d efficiently. A number of tools and technologies (Map-Reduce, NoSQL, Hadoop, Hive, cloud computing, parallel processing, clustering, MPP, virtualization, large grid environments, and so on) have been developed to store and process big data. While big-data technologies have established the ability to collect and process large amounts of data, most organizations struggle with understanding the data and taking advantage of its value. According to an Economist report: \u201cExtracting value from big data remains elusive for many organizations. For most companies today, data are abundant and readily available, but not well used.\u201d$[2,3]$\n\nA central issue with \u201cbig data\u201d is that not all of the data will labled. As such, there is an expectation that unsupervised learning and research in unsupervised learning will take on an even greater importance in machine learning.  \n\n\n  \n\nImage courtesy of [clipartist.net](http://clipartist.net/)  \n\n\n\n## Clustering\n\nWhat is [Clustering](https://en.wikipedia.org/wiki/Cluster_analysis)?\nClustering is grouping like with like such that:  \n\n* Similar objects are close to one another within the same cluster.  \n* Dissimilar to the objects in other clusters.  \n\n\n\n*cluster analysis*  \n  \n# Distance & Similarity Measures\n\nThere are two primary approaches to measure the \"closeness\" of data, distance and similarity. Distance measures are based in the notion of a [metric space](https://en.wikipedia.org/wiki/Metric_space).\n\n[Similarity measures](https://en.wikipedia.org/wiki/Similarity_measure) s a real-valued function that quantifies the similarity between two objects. While no single definition of a similarity measure exists, they don't necessarily have the constraint of being a metric space.  For example, [cosine similarity](https://en.wikipedia.org/wiki/Cosine_similarity) is a measure of the \"closeness\" of two vectors that is not a metric space.\n\n## Metric Spaces\n\nA *metric space* is an *ordered pair* $(M,d)$ where $M$ is a set and $d$ is a distance (i.e.metric) on $M$, i.e., a function:  \n\n$d \\colon M \\times M \\rightarrow \\mathbb{R}$\n\nsuch that for any $x, y, z \\in M$, the following holds:  \n\n* $d(x,y) \\ge 0 \\quad (non-negative),$  \n* $d(x,y) = 0, \\iff x = y \\quad (identity \\quad of \\quad indiscernibles),$  \n* $d(x,y) = d(y,x), \\quad (symmetry).$  \n* $d(x,z) \\le d(x,y) + d(y,z) \\quad  (triangle \\quad inequality)$  \n\n### Examples of Metric Spaces\n\nExamples of Metric Spaces are [Chebyshev distance](https://en.wikipedia.org/wiki/Chebyshev_distance), [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance), [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance), [Minkowski distance](https://en.wikipedia.org/wiki/Minkowski_distance) and many others.\n \n#### Euclidean distance\n\nEuclidean distance is the most common metric for measuring the distance between two vectors. The is the stadard Cartesian coordinates. That is, if $p = (p_1, p_2,..., p_n)$ and $q = (q_1, q_2,..., q_n)$ are two points in Euclidean n-space, then the distance (d) from p to q, or from q to p is given by the Pythagorean formula:\n\n$$\\begin{align}\\mathrm{d}(\\mathbf{p},\\mathbf{q}) = \\mathrm{d}(\\mathbf{q},\\mathbf{p}) & = \\sqrt{(q_1-p_1)^2 + (q_2-p_2)^2 + \\cdots + (q_n-p_n)^2} \\\\[8pt]\n& = \\sqrt{\\sum_{i=1}^n (q_i-p_i)^2}.\\end{align}$$  \n\n\n## Similarity Measures\n\nSimilarity (or dimilarity measures) measure closeness without the constraints and benefits of being a formal metric space.\n\n### Cosine similarity\n\nThe most common form of the similarity measure is the vector inner product (or [cosine similarity](https://en.wikipedia.org/wiki/Cosine_similarity))\nGiven vectors A and B, the vector inner product can be defined using the [Euclidean dot product](https://en.wikipedia.org/wiki/Euclidean_vector#Dot_product) formula:\n\n$$\\mathbf{a}\\cdot\\mathbf{b}\n=\\left\\|\\mathbf{a}\\right\\|\\left\\|\\mathbf{b}\\right\\|\\cos\\theta$$\n\nThis similarity measure can also be ranged normalized. Alternately, we can normalize this measure by dividing each vector component by the magnitude of the vector.\n\n### Pearson correlation\n\nCorrelation based similarity is usually the [Pearson correlation](https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient). Pearson product-moment correlation coefficient commonly represented by the Greek letter $\\rho$ (rho) and is defined as:\n\n$$ \\rho_{X,Y}= \\frac{\\operatorname{cov}(X,Y)}{\\sigma_X \\sigma_Y} $$\n\nwhere $\\operatorname{cov}$ is the [covariance](https://en.wikipedia.org/wiki/Covariance) and  $\\sigma_X$ is the [standard deviation](https://en.wikipedia.org/wiki/Standard_deviation) of $X$.  \n\nThe formula for $\\rho$can be expressed in terms of mean and expectation.  \n\n$$\\operatorname{cov}(X,Y) = E[(X-\\mu_X)(Y-\\mu_Y)]$$ \n\n\n# Clustering Data Structures\n\n* Data matrix\n\n$$ \nM=\n  \\begin{bmatrix}\n    x_{1,1} & x_{1,2} & x_{1,3} & ...  & x_{1,n} \\\\\n    x_{2,1} & x_{2,2} & x_{2,3} & ...  & x_{2,n} \\\\\n    x_{3,1} & x_{3,2} & x_{3,3} & ...  & x_{3,n} \\\\    \n    .. & .. & .. & ...  & .. \\\\    \n    x_{n,1} & x_{n,2} & x_{n,3} & ...  & x_{n,n} \\\\    \n  \\end{bmatrix}\n$$\n\nDistance matrix\n\n$$ \nM=\n  \\begin{bmatrix}\n    x_{1,1} &   &  &   &  \\\\   \n    x_{2,1} & 0  &  &   &  \\\\   \n    x_{3,1} & x_{3,2} & 0 &   &  \\\\    \n    .. & .. & .. & ...  & .. \\\\    \n    x_{n,1} & x_{n,2} & x_{n,3} & ...  & 0 \\\\    \n  \\end{bmatrix}\n$$\n\n* Dissimilarity/Similarity matrix\n\n\nThe dissimilarity/similarity matrix is calculated by iterating over each element and calculating its dissimilarity/similarity to every other element. Let A be a Dissimilarity Matrix of size $NxN$, and $B$ a set of $N$ elements. $A_{i,j}$ is the dissimilarity/similarity between elements $B_i$ and $B_j$.  \n\n\n```\n\n   for i = 0 to N do\n       for j = 0 to N do\n           Aij = Dissimilarity(Bi,Bj) // or Similarity(Bi,Bj)\n       end-for\n   end-for\n   \n```     \n   \nwhere the dissimilarity/similarity matrix is usually defined as follows:\n\n$$ \nM=\n  \\begin{bmatrix}\n    0 &   &  &   &  \\\\   \n   d(2,1)  & 0  &  &   &  \\\\   \n   d(3,1)  & d(3,2) & 0 &   &  \\\\    \n    .. & .. & .. & ...  & .. \\\\    \n    d(n,1)  & d(n,2) & d(n,3) & ...  & 0 \\\\    \n  \\end{bmatrix}\n$$\n\n\n\n# Types of  Clustering\n\n[Clustering](https://en.wikipedia.org/wiki/Cluster_analysis) (e.g., k-means, mixture models, hierarchical clustering). Cluster analysis or clustering is the task of grouping a set of objects in such a way that objects in the same group (called a cluster) are more similar (in some sense or another) to each other than to those in other groups (clusters). There are various types of cluster analysis.  \n\n* Partitioning-based clustering (K-means and its variants)\n* Hierarchical clustering\n* Density-based clustering\n\n## Partitioning-based clustering (K-means and its variants)\n\nPartitioning algorithms: Construct various partitions and then evaluate them by some criterion\nHierarchy algorithms: Create a hierarchical decomposition of the set of data (or objects) using some criterion\nDensity-based: based on connectivity and density functions\nGrid-based: based on a multiple-level granularity structure\nModel-based: A model is hypothesized for each of the clusters and the idea is to find the best fit of that model to each other\n\n\nPartitioning method: Construct a partition of n documents into a set of K clusters\nGiven: a set of documents and the number K \nFind: a partition of K clusters that optimizes the chosen partitioning criterion\nGlobally optimal\nIntractable for many objective functions\nErgo, exhaustively enumerate all partitions\nEffective heuristic methods: K-means and K-medoids algorithms\n\n\n### K-means\n\nThe term \"k-means\" was first used by James MacQueen in 1967,[1] though the idea goes back to Hugo Steinhaus in 1957. Given a desired $k$ clusters and n data points $X = {x_1, x_2, \u2026, x_n}$: \n\nInitialize centroids $\\mu_1, \\mu_1, ... \\mu_k \\quad \\in \\quad  \\mathbb{R}^n$  (usually randomly)  \n\n\nwhile (not coverged):\n\nStep A (Assignment step):  \n\n  Find the closest cluster to every point in $X = {x_1, x_2, \u2026, x_n}$\n  \n  That is,   \n$$\\underset{\\mathbf{X}} {\\operatorname{arg\\,min}}  \\sum_{i=1}^{k} \\sum_{\\mathbf x \\in X_i} \\left\\| \\mathbf x - \\boldsymbol\\mu_i \\right\\|^2$$\n\nwhere $\\mu_i$ is the mean of points in $X_i$.\n\n$$\nS_i^{(t)} = \\big \\{ x_p : \\big \\| x_p - m^{(t)}_i \\big \\|^2 \\le \\big \\| x_p - m^{(t)}_j \\big \\|^2 \\ \\forall j, 1 \\le j \\le k \\big\\}\n$$  \n\nStep B (Update step): \n\n  Calculate the new means to be the centroids of the observations in the new clusters.\n\n$$\nm^{(t+1)}_i = \\frac{1}{|X^{(t)}_i|} \\sum_{x_j \\in X^{(t)}_i} x_j \n$$\n\nThe [centroid](https://en.wikipedia.org/wiki/Centroid) of a finite set of {k} points  \n\n$$\n\\mathbf{x}_1,\\mathbf{x}_2,\\ldots,\\mathbf{x}_k in \\mathbb{R}^n \\quad is\\quad \n\\mathbf{C} = \\frac{\\mathbf{x}_1+\\mathbf{x}_2+\\cdots+\\mathbf{x}_k}{k}\n$$\n\n\n\n## Supervised Learning\n\n[Supervised learning](https://en.wikipedia.org/wiki/Supervised_learning) is the machine learning task of inferring a function from labeled training data.[1] The training data consist of a set of training examples. In supervised learning, each example is a pair consisting of an input object (typically a vector) and a desired output value (also called the supervisory signal). A supervised learning algorithm analyzes the training data and produces an inferred function, which can be used for mapping new examples. An optimal scenario will allow for the algorithm to correctly determine the class labels for unseen instances. This requires the learning algorithm to generalize from the training data to unseen situations in a \"reasonable\" way.\n\n\n\n\n## Bias\u2013variance tradeoff\n\nThe [Bias\u2013variance tradeoff](https://en.wikipedia.org/wiki/Bias%E2%80%93variance_tradeoff) is the problem of simultaneously minimizing two sources of error that prevent supervised learning algorithms from generalizing beyond their training set:\n\nThe bias is error from erroneous assumptions in the learning algorithm. High bias can cause an algorithm to miss the relevant relations between features and target outputs (underfitting).\n\nThe variance is error from sensitivity to small fluctuations in the training set. High variance can cause an algorithm to model the random noise in the training data, rather than the intended outputs (overfitting).\n\nThe bias\u2013variance decomposition is a way of analyzing a learning algorithm's expected generalization error with respect to a particular problem as a sum of three terms, the bias, variance, and a quantity called the irreducible error, resulting from noise in the problem itself.\nThis tradeoff applies to all forms of supervised learning: classification, regression (function fitting), and structured output learning. It has also been invoked to explain the effectiveness of heuristics in human learning.\n\nThis is the essence of the **bias-variance tradeoff**: You are seeking a model that appropriately balances bias and variance, and thus will generalize to new data (known as \"out-of-sample\" data).\n\n### Overfitting \n\n**What is overfitting?**\n\n- Building a model that matches the training data \"too closely\"\n- Learning from the noise in the data, rather than just the signal\n\n**How does overfitting occur?**\n\n- Evaluating a model by testing it on the same data that was used to train it\n- Creating a model that is \"too complex\"\n\n**What is the impact of overfitting?**\n\n- Model will do well on the training data, but won't generalize to out-of-sample data\n- Model will have low bias, but high variance\n\n## Linear Models and Regression\n\nLinear regression predicts the response variable $y$ assuming it has a linear relationship with predictor variable(s) $x$ or $x_1, x_2, ,,, x_n$.\n\n$$y = \\beta_0 + \\beta_1 x + \\varepsilon .$$\n\n*_Simple regression_* use only one predictor variable $x$. *_Mulitple regression_* uses a set of predictor variables $x_1, x_2, ,,, x_n$.\n\nThe *response variable* $y$ is also called the regressand, forecast, dependent or explained variable. The *predictor variable* $x$ is also called the regressor, independent or explanatory variable.\n\nThe parameters $\\beta_0$ and $\\beta_1$ determine the intercept and the slope of the line respectively. The intercept $\\beta_0$ represents the predicted value of $y$ when $x=0$. The slope $\\beta_1$ represents the predicted increase in $Y$ resulting from a one unit increase in $x$.\n\nNote that the regression equation is just our famliar equation for a line with an error term.\n\nThe equation for a line:  \n$$ Y = bX + a $$\n\n$$y = \\beta_0 + \\beta_1 x $$\n\nThe equation for a line with an error term:  \n\n$$ Y = bX + a + \\varepsilon $$\n\n$$y = \\beta_0 + \\beta_1 x + \\varepsilon .$$\n\n- $b$ = $\\beta_1$ = slope\n- $a$ = $\\beta_0$ = $Y$ intercept\n- $\\varepsilon$ = error term\n\n\nWe can think of each observation $y_i$ consisting of the systematic or explained part of the model, $\\beta_0+\\beta_1x_i$, and the random *error*, $\\varepsilon_i$.\n\n_Zero Slope_\n\nNote that when  $\\beta_1 = 0$ then response does not change as the predictor changes.\n\n\n## The error $\\varepsilon_i$\n\nThe error term is a catch-all for anything that may affect $y_i$ other than $x_i$. We assume that these errors:\n\n* have mean zero; otherwise the forecasts will be systematically biased.\n* statistical independence of the errors (in particular, no correlation between consecutive errors in the case of time series data).\n* homoscedasticity (constant variance) of the errors.\n* normality of the error distribution.\n\nIf any of these assumptions is violated then the robustness of the model to be taken with a grain of salt.\n\n\n## Least squares estimation\n\nIn a linear model, the values of $\\beta_0$ and $\\beta_1$. These need to be estimated from the data. We call this *fitting a model*.\n\nThe least squares method iis the most common way of estimating $\\beta_0$ and $\\beta_1$ by minimizing the sum of the squared errors. The values of $\\beta_0$ and $\\beta_1$ are chosen so that that minimize\n\n$$\\sum_{i=1}^N \\varepsilon_i^2 = \\sum_{i=1}^N (y_i - \\beta_0 - \\beta_1x_i)^2. $$\n\n\nUsing mathematical calculus, it can be shown that the resulting **least squares estimators** are\n\n$$\\hat{\\beta}_1=\\frac{ \\sum_{i=1}^{N}(y_i-\\bar{y})(x_i-\\bar{x})}{\\sum_{i=1}^{N}(x_i-\\bar{x})^2} $$ \n\nand\n\n$$\\hat{\\beta}_0=\\bar{y}-\\hat{\\beta}_1\\bar{x}, $$\n\nwhere $\\bar{x}$ is the average of the $x$ observations and $\\bar{y}$ is the average of the $y$ observations. The estimated line is known as the *regression line*.\n\n\n## Fitted values and residuals\n\nThe response values of $y$ obtained from the observed $x$ values are\ncalled *fitted values*: $\\hat{y}_i=\\hat{\\beta}_0+\\hat{\\beta}_1x_i$, for\n$i=1,\\dots,N$. Each $\\hat{y}_i$ is the point on the regression\nline corresponding to $x_i$.\n\nThe difference between the observed $y$ values and the corresponding fitted values are the *residuals*:\n\n$$e_i = y_i - \\hat{y}_i = y_i -\\hat{\\beta}_0-\\hat{\\beta}_1x_i. $$\n\nThe residuals have some useful properties including the following two:\n\n$$\\sum_{i=1}^{N}{e_i}=0 \\quad\\text{and}\\quad \\sum_{i=1}^{N}{x_ie_i}=0. $$\n\n\nResiduals are the errors that we cannot predict.Residuals are highly useful for studying whether a given regression model is an appropriate statistical technique for analyzing the relationship.\n\n## Regression and correlation\n\nThe correlation coefficient $r$ measures the strength and the direction of the linear relationship between the two variables. The stronger the linear relationship, the closer the observed data points will cluster around a straight line.\n\nThe _Pearson product-moment correlation coefficient_ is the most widely used of all correlation coefficients. In statistics, the Pearson product-moment correlation coefficient (/\u02c8p\u026a\u0259rs\u0268n/) (sometimes referred to as the PPMCC or PCC or Pearson's r) is a measure of the linear correlation (dependence) between two variables X and Y, giving a value between +1 and \u22121 inclusive, where 1 is total positive correlation, 0 is no correlation, and \u22121 is total negative correlation. It is widely used in the sciences as a measure of the degree of linear dependence between two variables. It was developed by Karl Pearson from a related idea introduced by Francis Galton in the 1880s. Early work on the distribution of the sample correlation coefficient was carried out by Anil Kumar Gain and R. A. Fisher from the University of Cambridge.\n\nfrom [Pearson product-moment correlation coefficient](https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient)  \n\nExamples of scatter diagrams with different values of correlation coefficient (\u03c1)\n\nThe value of r is such that -1 < r < +1.  \n\nStrong positive correlation r is close to +1. Strong negative correlation r is close to -1. No correlation r is close to 0.   \n\nThe advantage of a regression model over correlation is that it asserts a predictive relationship between the two variables ($x$ predicts $y$) and quantifies this in a useful way for forecasting.\n\n## The t-statistic and the standard error\n\nThe t-statistic is the coefficient divided by its standard error. For example, a $\\beta_1$ of 38.2 divided by a standard error of 3.4 would give a t value of 11.2.\n\nThe standard error is an estimate of the standard deviation of the coefficient. It can be thought of as the spread between fitted and actual values.\n\n$$s_e=\\sqrt{\\frac{1}{N-2}\\sum_{i=1}^{N}{e_i^2}}.$$\n\n\nIf a coefficient is large compared to its standard error, then we can reject the hypothesis that $\\beta_1$ = 0. Intuitively, we can think of this if the slope is not small and there is a not much spread between fitted and actual values then we can be confident that the true slope $\\hat{\\beta}_1$ is not 0.\n\nA t-statistic (t value) of greater than 2 in magnitude, corresponds to p-values less than 0.05.\n\nThe p-value is a function of the observed sample results (a statistic) that is used for testing a statistical hypothesis. Before the test is performed, a threshold value is chosen, called the significance level of the test, traditionally 5% or 1% and denoted as $\\alpha$.  \n\nIf the p-value is equal to or smaller than the significance level ($\\alpha$), it suggests that the observed data are inconsistent with the assumption that the null hypothesis is true and thus that hypothesis must be rejected (but this does not automatically mean the alternative hypothesis can be accepted as true). When the p-value is calculated correctly, such a test is guaranteed to control the Type I error rate to be no greater than $\\alpha$.\n\nfrom [P-value](https://en.wikipedia.org/wiki/P-value)\n\n## R-squared $R^2$ \n\n[R-squared](https://en.wikipedia.org/wiki/Coefficient_of_determination)   (coefficient of determination) is a statistical measure of how close the data are to the fitted regression line. the coefficient of determination, denoted $R^2$ or $r^2$ and pronounced \"R squared\", is a number that indicates the proportion of the variance in the dependent variable that is predictable from the independent variable(s).\n\nR-squared = Explained variation / Total variation\n\nR-squared is always between 0 and 100%:\n\n* 0% (or 0) indicates that the model explains none of the variability of the response data around its mean.  \n* 100% (or 1) indicates that the model explains all the variability of the response data around its mean. \n\nThe higher the R-squared, the better the model fits your data. \n\nThe better the linear regression fits the data in comparison to the simple average (on the left graph), the closer the value of $R^2$ is to 1. The areas of the blue squares represent the squared residuals with respect to the linear regression. The areas of the red squares represent the squared residuals with respect to the average value.]]\n\nA data set has $n$ values marked $y_1$,...,$y_n$ (collectively known as $y_i$ or as a vector $y = [y_1,..., y_n]^T$), each associated with a predicted (or modeled) value $\\hat{y}_{1},...,\\hat{y}_{n}$.\n\nDefine the residuals as as $e_i = y_i \u2212 \\hat{y}_{i}$ (forming a vector $e$).\n\nIf $\\bar{y}$ is the mean of the observed data:\n\n$$\\bar{y}=\\frac{1}{n}\\sum_{i=1}^n y_i $$\n\nthen the variability of the data set can be measured using three sums of square formulas:\n\n* The total sum of squares (proportional to the variance of the data):\n\n $$SS_\\text{tot}=\\sum_i (y_i-\\bar{y})^2,$$\n\n* The regression sum of squares, also called the explained sum of squares:\n\n$$SS_\\text{reg}=\\sum_i (\\hat{y}_{i} -\\bar{y})^2,$$\n\n* The sum of squares of residuals, also called the residual sum of squares:\n\n$$SS_\\text{res}=\\sum_i (y_i - \\hat{y}_{i})^2=\\sum_i e_i^2\\,$$\n\nThe most general definition of the coefficient of determination is\n\n$$R^2 \\equiv 1 - {SS_{\\rm res}\\over SS_{\\rm tot}}.\\,$$\n\n$R^2$ can be thought of as *the proportion of variation in the forecast variable that is accounted for (or explained) by the regression model*.\n\nIn the definition of $R^2$, $0 \\geq R^2 \\geq 1$ as is similar to he value of $r^2$ (the square of the pearson correlation between $f(x)$ and $x$.\n\n### Adjusted $R^2$  \n\n\nThe use of an adjusted $R^2$ (also called  $$\\bar R^2 $$, pronounced \"R bar squared\" or another is  $$R^2_{\\text{adj}} $$) is an attempt to take account of the phenomenon of the $R^2$   automatically and spuriously increasing when extra explanatory variables are added to the model. It is a modification due to Theil of $R^2$   that adjusts for the number of explanatory variables in a model relative to the number of data points. The adjusted $R^2$   can be negative, and its value will always be less than or equal to that of $R^2$  . Unlike $R^2$  , the adjusted $R^2$   increases only when the increase in $R^2$ (due to the inclusion of a new explanatory variable) is more than one would expect to see by chance. If a set of explanatory variables with a predetermined hierarchy of importance are introduced into a regression one at a time, with the adjusted $R^2$   computed each time, the level at which adjusted $R^2$   reaches a maximum, and decreases afterward, would be the regression with the ideal combination of having the best fit without excess/unnecessary terms. The adjusted $R^2$   is defined as\n\n$$\\bar R^2 = {1-(1-R^2){n-1 \\over n-p-1}} = {R^2-(1-R^2){p \\over n-p-1}} $$\n\nwhere ''p'' is the total number of explanatory variables in the model (not including the constant term), and ''n'' is the sample size.\n\nAdjusted $R^2$   can also be written as\n\n$$\\bar R^2 = {1-{SS_\\text{res}/\\text{df}_e \\over SS_\\text{tot}/\\text{df}_t}} $$\n\nwhere $df_{t}$ is the degrees of freedom ''n''\u2013 1 of the estimate of the population variance of the dependent variable, and $df_{e}$ is the degrees of freedom ''n'' \u2013 ''p'' \u2013 1 of the estimate of the underlying population error variance.\n\nThe principle behind the adjusted $R^2$   statistic can be seen by rewriting the ordinary $R^2$   as\n\n$$R^{2} = {1-{\\textit{VAR}_\\text{res} \\over \\textit{VAR}_\\text{tot}}} $$\n\nwhere  $$\\text{VAR}_\\text{res} = SS_\\text{res}/n $$ and  $$\\text{VAR}_\\text{tot} = SS_\\text{tot}/n $$ are the sample variances of the estimated residuals and the dependent variable respectively, which can be seen as biased estimates of the population variances of the errors and of the dependent variable. These estimates are replaced by statistically unbiased versions: \n\n$$\\text{VAR}_\\text{res} = SS_\\text{res}/(n-p-1) $$ and  $$\\text{VAR}_\\text{tot} = SS_\\text{tot}/(n-1) $$.\n\nAdjusted $R^2$   does not have the same interpretation as $R^2$  \u2014while $R^2$   is a measure of fit, adjusted $R^2$   is instead a comparative measure of suitability of alternative nested sets of explanators.  As such, care must be taken in interpreting and reporting this statistic. Adjusted $R^2$   is particularly useful in the feature selection stage of model building.\n\n## Dimensionality reduction\n\nDimensionality reduction is about converting data of high dimensionality into data of lower dimensionality while keeping most of the information in the data. This allows us to work on larger datasets and identify the data\u2019s most relevant features. Anomaly detection (or outlier detection) is the identification of items, events or observations which do not conform to an expected pattern or other items in a dataset.  In this first lesson, we study the theory of dimensionality reduction and introduce essential concepts and jargon, such as eigenvalues, eigenvectors, linear independence, span, vector, scalar, basis of a subspace and linear combination.   \n\n\n# Dimensionality Reduction\n\nIn machine learning and statistics, [dimensionality reduction](https://en.wikipedia.org/wiki/Dimensionality_reduction) or dimension reduction is the process of reducing the number of random variables under consideration, and can be divided into feature selection and feature extraction.\n\n*Feature selection*  \n\nFeature selection approaches try to find a subset of the original variables (also called features or attributes). In essence, either using domain knowledge and statisitcal tests to prune away some of the original variables\n\n*Feature extraction*  \n\nFeature extraction transforms the data in the high-dimensional space to a space of fewer dimensions.  \n\n\n# Factor Analysis \n\nFactor analysis is a statistical method used to describe variability among observed, correlated variables in terms of a potentially lower number of unobserved variables called factors.  The observed variables are modelled as linear combinations of the potential factors, plus \"error\" terms. \n\nFactor Analysis has was first developed in 1901 by [Karl Pearson](https://en.wikipedia.org/wiki/Karl_Pearson). Pearson posed a model having one factor that was common across his data:\n\n$$\nY_ij = \\alpha_i W_1 + \\varepsilon_{ij}\n$$\n\nOr a general multi-factor factor:\n\n$$\nY_{ij} = \\sum_{k=1}^K \\alpha_{i,k} W_{j,k} + \\varepsilon_{ij}\n$$\n\nWe can use various techniques to estimate $\\mathbf{W}_1,\\dots,\\mathbf{W}_K$. Choosing $k$ (the number of factors) is a challenge that we'll discuss in further sections.\n\nTo illustrate the idea of feature extraction using factors consider the problem of reducing 2D data to 1D.\n\n\n     \n\n   \n\n# Linear Algebra\n\nSo how do we find a good basis to project some data?\n\n## Some Linear Algebra Jargon\n\n### Real coordinate spaces  \n\n$$\\mathbb{R}^2 , \\quad \\mathbb{R}^3, ... , \\quad \\mathbb{R}^N$$\n\n### What is a vector?\n\n* A vector is a quantity having direction as well as magnitude.\n* An element of the real coordinate space $\\mathbb{R}^N$\n\n### Systems of Linear Equations\n\nLinear algebra are used to solve systems of linear equations such as this:\n\n$$\n\\begin{align*}\na + b + c &= 5\\\\\n3a - 2b + c &= 3\\\\\n2a + b  - c &= 1\n\\end{align*}\n$$\n\nWe can rewrite and solve this system using matrix algebra notation:\n\n$$\n\\,\n\\begin{pmatrix}\n1&1&1\\\\\n3&-2&1\\\\\n2&1&-1\n\\end{pmatrix}\n\\begin{pmatrix}\na\\\\\nb\\\\\nc\n\\end{pmatrix} =\n\\begin{pmatrix}\n5\\\\\n3\\\\\n1\n\\end{pmatrix}\n\\implies\n\\begin{pmatrix}\na\\\\\nb\\\\\nc\n\\end{pmatrix} =\n\\begin{pmatrix}\n1&1&1\\\\\n3&-2&1\\\\\n2&1&-1\n\\end{pmatrix}^{-1}\n\\begin{pmatrix}\n5\\\\\n3\\\\\n1\n\\end{pmatrix}\n$$\n\n\n### Multiplying by Vector or Matrix by a Scalar\n\nscalar multiplication of a real Euclidean vector by a positive real number multiplies the magnitude of the vector without changing its direction.\n\n     \n\n\nMultiplying by a negative value changes its direction.\n\n\n     \n  \n\nIf $a$ is scalar and $\\mathbf{X}$ is a matrix then:\n\n$$\na \\mathbf{X} =\n\\begin{pmatrix}\na x_{1,1} & \\dots & a x_{1,p}\\\\\n& \\vdots & \\\\\na x_{N,1} & \\dots & a  x_{N,p}\n\\end{pmatrix}\n$$\n\n\nProperties of Scalar Multiplication  \n\nScalar multiplication obeys the following rules:  \n* Additivity in the scalar: $(c + d)\\vec{v} = c\\vec{v} + d\\vec{v};$  \n* Additivity in the vector: $c(\\vec{v} + \\vec{w}) = c\\vec{v} + c\\vec{w};$  \n* Compatibility of product of scalars with scalar multiplication: $(cd)\\vec{v} = c(d\\vec{v});$  \n* Multiplying by 1 does not change a vector: $1\\vec{v} = \\vec{v};$  \n* Multiplying by 0 gives the zero vector: $0\\vec{v} = 0;$  \n* Multiplying by \u22121 gives the additive inverse: $(\u22121)\\vec{v} = \u2212\\vec{v}.$  \n\n### The Matrix Transpose\n\nThe matrix transpose is an operation that changes columns to rows. We use either a $\\top$ to denote transpose.   \n\n\n$$\n\\mathbf{X} = \\begin{pmatrix}\nx_{1,1}&\\dots & x_{1,p} \\\\\nx_{2,1}&\\dots & x_{2,p} \\\\\n& \\vdots & \\\\\nx_{N,1}&\\dots & x_{N,p}\n\\end{pmatrix} \\implies\n\\mathbf{X}^\\top = \\begin{pmatrix}\nx_{1,1}&\\dots & x_{p,1} \\\\\nx_{1,2}&\\dots & x_{p,2} \\\\\n& \\vdots & \\\\\nx_{1,N}&\\dots & x_{p,N}\n\\end{pmatrix}\n$$\n\n\n### Matrix multiplication\n\n[matrix multiplication](https://en.wikipedia.org/wiki/Matrix_multiplication) is an operation that takes a pair of matrices, and produces another matrix. If A is an n \u00d7 m matrix and B is an m \u00d7 p matrix, their matrix product AB is an n \u00d7 p matrix. The number rows of the first matrix must match the columns of the second.\n\n\n$$\n\\begin{align*}\na + b + c &=5\\\\\n3a - 2b + c &= 3\\\\\n2a + b  - c &= 1\n\\end{align*}\n$$\n\nThe idea is to multiply the rows of the first matrix by the columns of the second.\n\n$$\n\\,\n\\begin{pmatrix}\n1&1&1\\\\\n3&-2&1\\\\\n2&1&-1\n\\end{pmatrix}\n\\begin{pmatrix}\na\\\\\nb\\\\\nc\n\\end{pmatrix}=\n\\begin{pmatrix}\na + b + c \\\\\n3a - 2b + c \\\\\n2a + b  - c\n\\end{pmatrix}\n$$\n\n\n\n#### Adding vectors\n\n\n   \n\n\n### Unit vector\n\nA unit vector in a normed vector space is a vector of length 1. A unit vector is often denoted by a lowercase letter with a \"hat\": i-hat (pronounced \"i-hat\"). The normalized vector or versor \u00fb of a non-zero vector u is the unit vector in the direction of u, i.e.,\n\n$$\\mathbf{\\hat{u}} = \\frac{\\mathbf{u}}{\\|\\mathbf{u}\\|}$$\n\nu-hat equals the vector u divided by its length where ||u|| is the norm (or length) of u. The term normalized vector is sometimes used as a synonym for unit vector.\n\nfrom [Unit vector - Wikipedia](https://en.wikipedia.org/wiki/Unit_vector)\n\n### Linear combinations \n\nWe can represent any vector with a linear combination of other vectors. If $\\vec{V}$ are vectors $v_1,...,v_n$ and A are scalars $a_1,...,a_n$ then the linear combination of those vectors with those scalars as coefficients is\n\n$$ a_1 \\vec{v}_{1} \\quad + \\quad a_2 \\vec{v}_2  \\quad + \\quad  a_3 \\vec{v}_3  \\quad + \\quad  \\cdots  \\quad + \\quad  a_n \\vec{v}_n. $$  \n\nFor example, consider the vectors $\\vec{v}_1 = (1,0,0),  \\quad \\vec{v}_2 = (0,1,0)  \\quad and  \\quad \\vec{v}_3 = (0,0,1)$. Then any vector in $\\mathbb{R}^3$ is a linear combination of $\\vec{v}_1,  \\quad \\vec{v}_2  \\quad and  \\quad \\vec{v}_3$.\nTo see that this is so, take an arbitrary vector (a1,a2,a3) in $\\mathbb{R}^3,$, and write:\n\n$$ ( a_1 , a_2 , a_3) = ( a_1 ,0,0) + (0, a_2 ,0) + (0,0, a_3)   =  a_1 (1,0,0) + a_2 (0,1,0) + a_3 (0,0,1) =  a_1 \\vec{v}_1 +  a_2 \\vec{v}_2 +  a_3 \\vec{v}_3.   $$\n\n   \n\n### Linear Spans and Basis\n\nThe span of S may be defined as the set of all finite linear combinations of elements of S,\n\n$$ \\operatorname{span}(S) =  \\left \\{ {0+\\sum_{i=1}^k \\lambda_i v_i \\Big| k \\in \\mathbb{N}, v_i  \\in S, \\lambda _i  \\in \\mathbf{K}} \\right \\} $$  \n\nA set of vectors in a vector space V is called a [basis](https://en.wikipedia.org/wiki/Basis_(linear_algebra)), or a set of basis vectors, if the vectors are linearly independent and every vector in the vector space is a linear combination of this set. In more general terms, a basis is a linearly independent spanning set.\n\nFor example, the real vector space $\\mathbb{R}^3$ has {(5,0,0), (0,3,0), (0,0,9)} is a spanning set. This particular spanning set is also a basis. \n\nThe set {(1,0,0), (0,1,0), (1,3,0)} is not a spanning set of $\\mathbb{R}^3$ as a vector like (1,3,1) cannot be created from this spanning set.\n\n### Linear subspaces\n\nA [linear subspace](https://en.wikipedia.org/wiki/Linear_subspace) (or vector subspace) is a vector space that is a subset of some other (higher-dimension) vector space. For example, $\\mathbb{R}^2$ is a subspace of $\\mathbb{R}^3$.\n \nLet V be a vector space over the field K, and let W be a subset of V. Then W is a subspace if and only if W satisfies the following three conditions:  \n\n*  The zero vector, 0, is in W.\n*  If u and v are elements of W, then the sum u + v is an element of W;\n*  If u is an element of W and c is a scalar from K, then the product cu is an element of W;\n\n\n### Metric Spaces\n\nA metric space is an ordered pair (M,d) where M is a set and d is a metric on M, i.e., a function * $d \\colon M \\times M \\rightarrow \\mathbb{R}$\nsuch that for any * $x, y, z \\in M$, the following holds:[1]\n\n* $d(x,y) \\ge 0$     (non-negative),  \n* $d(x,y) = 0\\, \\iff x = y\\,$     (identity of indiscernibles),  \n* $d(x,y) = d(y,x)\\,$     (symmetry) and  \n* $d(x,z) \\le d(x,y) + d(y,z) $    (triangle inequality) .  \n\nExamples of metric spaces include  [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance), [Manhattan distance](https://en.wikipedia.org/wiki/Taxicab_geometry), [Chebyshev distance](https://en.wikipedia.org/wiki/Chebyshev_distance), the [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) and many others.\n\n### Vector dot product\n\n*Algebraic definition*\n\nThe dot product of two vectors A = [A1, A2, ..., An] and B = [B1, B2, ..., Bn] is defined as:\n\n$$ \\mathbf{A}\\cdot \\mathbf{B} = \\sum_{i=1}^n A_iB_i = A_1B_1 + A_2B_2 + \\cdots + A_nB_n $$ \n\n\n*Geometric definition*  \n\nhe magnitude of a vector A is denoted by  \\left\\| \\mathbf{A} \\right\\| . The dot product of two Euclidean vectors A and B is:\n\n\n$$\\mathbf A \\cdot \\mathbf B = \\left\\| \\mathbf A \\right\\| \\, \\left\\| \\mathbf B \\right\\| \\cos \\theta ,$$\n\nwhere $\\theta$ is the angle between A and B.\n\n  \n\n\n### Orthogonal and orthonormal\n\nTwo vectors are orthogonal if they are perpendicular, i.e., they form a right angle. Two vectors orthonormal if they are orthogonal and unit vectors. Orthogonal vectors in n-space if their dot product equals zero. That is, if A and B are orthogonal, then the angle between them is 90\u00b0 and $\\mathbf A \\cdot \\mathbf B = 0 .$\n\n\n# Eigenvalues and eigenvectors\n\nIn linear algebra, an eigenvector or characteristic vector of a square matrix is a vector that does not change its direction under the associated linear transformation. In other words\u2014if v is a vector that is not zero, then it is an eigenvector of a square matrix A if Av is a scalar multiple of v. This condition could be written as the equation\n\n$$A\\vec{v} = \\lambda \\vec{v}$$\n \n\nwhere $\\lambda$ is a number (also called a scalar) known as the eigenvalue or characteristic value associated with the eigenvector $\\vec{v}$.   \n\n   \n\nIn this shear mapping the red arrow changes direction but the blue arrow does not. The blue arrow is an eigenvector of this shear mapping because it doesn't change direction, and since its length is unchanged, its eigenvalue is 1.  \n\nFor example, Consider n-dimensional vectors that are formed as a list of n real numbers, such as the three dimensional vectors,\n\n$$ \n\\mathbf{u} = \\begin{Bmatrix}1\\\\3\\\\4\\end{Bmatrix}\\quad\\mbox{and}\\quad \\mathbf{v} = \\begin{Bmatrix}-20\\\\-60\\\\-80\\end{Bmatrix}. $$ \n\nThese vectors are said to be scalar multiples of each other, also parallel or collinear, if there is a scalar \u03bb, such that\n\\mathbf{u}=\\lambda\\mathbf{v}.\n\nIn this case $\\lambda\\$ = \u22121/20.  \n\nNow consider the linear transformation of n-dimensional vectors defined by an n\u00d7n matrix A, that is,\n\n$$\n A\\mathbf{v}=\\mathbf{w},\nor\n\\begin{bmatrix} A_{1,1} & A_{1,2} & \\ldots & A_{1,n} \\\\\nA_{2,1} & A_{2,2} & \\ldots & A_{2,n} \\\\\n\\vdots &  \\vdots &  \\ddots &  \\vdots \\\\\nA_{n,1} & A_{n,2} & \\ldots & A_{n,n} \\\\\n\\end{bmatrix}\n\\begin{Bmatrix} v_1 \\\\ v_2 \\\\ \\vdots \\\\ v_n \\end{Bmatrix} = \\begin{Bmatrix} w_1 \\\\ w_2 \\\\ \\vdots \\\\ w_n \\end{Bmatrix}\nwhere, for each index i,\n w_i = A_{i,1} v_1 + A_{i,2} v_2 + \\cdots + A_{i,n} v_n = \\sum_{j = 1}^{n} A_{i,j} v_j.\n \n $$\nIf it occurs that w and v are scalar multiples, that is if\n$A\\mathbf{v}=\\lambda\\mathbf{v}$,\nthen v is an eigenvector of the linear transformation A and the scale factor $\\lambda\\$ is the eigenvalue corresponding to that eigenvector.\n\n\n   \n\nMatrix A acts by stretching the vector x, not changing its direction, so x is an eigenvector of A.\n\nfrom [Eigenvalues and eigenvectors - Wikipedia](https://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors)\n\n\n# PCA: Principal Component Analyses\n\n[Principal component analysis (PCA)](https://en.wikipedia.org/wiki/Principal_component_analysis) is a statistical procedure that uses an orthogonal transformation to convert a set of observations of possibly correlated variables into a set of values of linearly uncorrelated variables called principal components.\n\nIn Principal component analysis the feature selection is finding a set of linearly uncorrelated vectors (basis selection) of maximal variance. That is, the transformation is defined in such a way that the first principal component has the largest possible variance and each succeeding component in turn has the highest variance possible under the constraint that it is orthogonal to the preceding components. \n\n  \n\n*First component*  \n\nThe first loading vector $\\vec{w}$ thus has to satisfy  \n\n$$\n\\mathbf{w}_{(1)}\n = \\underset{\\Vert \\mathbf{w} \\Vert = 1}{\\operatorname{\\arg\\,max}}\\,\\left\\{ \\sum_i \\left(t_1\\right)^2_{(i)} \\right\\}\n = \\underset{\\Vert \\mathbf{w} \\Vert = 1}{\\operatorname{\\arg\\,max}}\\,\\left\\{ \\sum_i \\left(\\mathbf{x}_{(i)} \\cdot \\mathbf{w} \\right)^2 \\right\\} $$ \n \nEquivalently, writing this in matrix form gives\n\n$$\n\\mathbf{w}_{(1)}\n = \\underset{\\Vert \\mathbf{w} \\Vert = 1}{\\operatorname{\\arg\\,max}}\\, \\{ \\Vert \\mathbf{Xw} \\Vert^2 \\}\n = \\underset{\\Vert \\mathbf{w} \\Vert = 1}{\\operatorname{\\arg\\,max}}\\, \\left\\{ \\mathbf{w}^T \\mathbf{X}^T \\mathbf{X w} \\right\\} $$  \n \n \nSince $\\vec{w}$ has been defined to be a unit vector, it equivalently also satisfies  \n\n$$\n\\mathbf{w}_{(1)} = {\\operatorname{\\arg\\,max}}\\, \\left\\{ \\frac{\\mathbf{w}^T\\mathbf{X}^T \\mathbf{X w}}{\\mathbf{w}^T \\mathbf{w}} \\right\\}\n$$\n\nThe first component is an eigenvector that maximizes the sum of squares\n\n$$(\\mathbf{Yv}_1)^\\top \\mathbf{Yv}_1$$\n\n$\\mathbf{v}_1$ is referred to as the _first principal component_ (PC). Also referred as  _first eigenvector_, $\\mathbf{Yv}_1$ are the projections or coordinates or eigenvalues\n\n*Further components*  \n\nThe kth component can be found by subtracting the first k \u2212 1 principal components from X:\n\n$$\n\\mathbf{\\hat{X}}_{k} = \\mathbf{X} - \\sum_{s = 1}^{k - 1} \\mathbf{X} \\mathbf{w}_{(s)} \\mathbf{w}_{(s)}^{\\rm T} $$  \n\nand then finding the loading vector which extracts the maximum variance from this new data matrix\n\n$$\n\\mathbf{w}_{(k)} = \\underset{\\Vert \\mathbf{w} \\Vert = 1}{\\operatorname{arg\\,max}} \\left\\{ \\Vert \\mathbf{\\hat{X}}_{k} \\mathbf{w} \\Vert^2 \\right\\} = {\\operatorname{\\arg\\,max}}\\, \\left\\{ \\tfrac{\\mathbf{w}^T\\mathbf{\\hat{X}}_{k}^T \\mathbf{\\hat{X}}_{k} \\mathbf{w}}{\\mathbf{w}^T \\mathbf{w}} \\right\\} $$  \n\nIt turns out that this gives the remaining eigenvectors of $X^TX$, with the maximum values for the quantity in brackets given by their corresponding eigenvalues.\n\nThe kth  is the vector that\n\n$$ \\mathbf{v}_{k}^\\top \\mathbf{v}_{k}=1$$\n\n$$ \\mathbf{v}_{k}^\\top \\mathbf{v}_{k-1}=0$$\n\nand maximizes  $$(\\mathbf{rv}_{k})^\\top \\mathbf{rv}_{k}$$\n\n\n### Properties of Principal Components\n\n* The principal components are eigenvectors\n* Maximizes variance in order of the components\n* They are orthogonal (and form a basis)\n* If use all of the principal components  we can get lossless reconstruction \n* N diminsions to M diminsions (each diminsion has an eigenvalue \nthe order (highest eigenvalues have highest  variance)\ni.e. can \"throw away\" the lowest eigenvalues.\nif eigenvalue has 0 value can throw it away without cost.\n* We can readjust to origin 0\n* There are very fast algorithms to compute PCA\n\n*Nota bene*  \nNote that there may be oroblems of interpretation of the components.\nNote that a low variance dimension may be important\n\n\n## LDA: Linear Discriminant Analysis\n\n\nLDA: Linear Discriminant Analysis\n\nAn alternative method to calculate eigenvectors from covariance matrix\n[Linear discriminant analysis (LDA)](https://en.wikipedia.org/wiki/Linear_discriminant_analysis) is a generalization of Fisher's linear discriminant, a method used in statistics, pattern recognition and machine learning to find a linear combination of features that characterizes or separates two or more classes of objects or events.\n\n\nSingular Value Decomposition\n\nIn linear algebra, the [singular value decomposition (SVD)](https://en.wikipedia.org/wiki/Singular_value_decomposition) is a factorization of a real or complex matrix. A  a matrix decomposition or matrix factorization is a factorization of a matrix into a product of matrices.\n\nIf $\\mathbf{M}$ is a m \u00d7 n matrix whose entries come from $\\mathbb{R}$, then the SVD  a factorization, called a singular value decomposition of  $\\mathbf{M}$ , of the form $\\mathbf{M=UDV}^\\top$ gives the factors in columns of $\\mathbf{V}$.\n\nNote that,  \n$\\mathbf{D}$ is a m \u00d7 n diagonal matrix with non-negative real numbers on the diagonal, and  \n$\\mathbf{U}$  is an m \u00d7 m, and $\\mathbf{V}$ is an n \u00d7 n, unitary matrix over $\\mathbb{R}$.\n\nThe diagonal entries, $\\sigma_{i}$, of $D$ are known as the singular values of $\\mathbf{M}$. The singular values are usually listed in descending order.\n\nNote that [Eigendecomposition](https://en.wikipedia.org/wiki/Eigendecomposition_of_a_matrix) is a form of matrix factorization.   \n\n$A=VDV^{-1}$, where D is a diagonal matrix formed from the eigenvalues of A, and the columns of V are the corresponding eigenvectors of A.\n\n### Differences between Principal Component Analysis and Singular-value decomposition\n\nThe singular value decomposition and the eigendecomposition are closely related.  PCA viewpoint requires that one compute the eigenvalues and eigenvectors of the covariance matrix, which is the product $\\mathbf{X}\\mathbf{X^T}$, where $\\mathbf{X}$ is the data matrix and SVD constructs the covariance matrix from this decomposition\n\n$$\\mathbf{X}\\mathbf{X^T}= \\mathbf{(UDV^T)}\\mathbf{(UDV^T)}^T$$\n\n$$\\mathbf{X}\\mathbf{X^T}= \\mathbf{(UDV^T)}\\mathbf{(VDU^T)}$$  \n\nand since $\\mathbf{V}$ is an orthogonal matrix $\\mathbf{V^TV}=\\mathbf{I}$),\n\n$$\\mathbf{X}\\mathbf{X^T}= \\mathbf{U}\\mathbf{D}^2\\mathbf{U^T}$$\n\nThat is,  \n- The left-singular vectors of $\\mathbf{M}$ are eigenvectors of $\\mathbf{M}\\mathbf{M^*}$ .  \n- The right-singular vectors of  $\\mathbf{M}$ are eigenvectors of $\\mathbf{M^*}\\mathbf{M}$.  \n- The non-zero singular values of $\\mathbf{M}$  (found on the diagonal entries of $\\mathbf{D}$) are the square roots of the non-zero eigenvalues of both $\\mathbf{M^*}\\mathbf{M}$ and $\\mathbf{M}\\mathbf{M^*}$. \n\n## Regularization\n\nRegularization, in mathematics and statistics and particularly in the fields of machine learning and inverse problems, is a process of introducing additional information in order to solve an ill-posed problem or to prevent overfitting.\n\n- Regularization is a method for \"constraining\" or \"regularizing\" the **size of the coefficients**, thus \"shrinking\" them towards zero.\n- It reduces model variance and thus **minimizes overfitting**.\n- If the model is too complex, it tends to reduce variance more than it increases bias, resulting in a model that is **more likely to generalize**.\n\n\n### Regularization in linear regression\n\nFor a normal linear regression model, we estimate the coefficients using the least squares criterion, which **minimizes the residual sum of squares (RSS):**\n\nFor a regularized linear regression model, we **minimize the sum of RSS and a \"penalty term\"** that penalizes coefficient size.\n\n**Ridge regression** (or \"L2 regularization\") minimizes: $$\\text{RSS} + \\alpha \\sum_{j=1}^p \\beta_j^2$$\n\n**Lasso regression** (or \"L1 regularization\") minimizes: $$\\text{RSS} + \\alpha \\sum_{j=1}^p |\\beta_j|$$\n\n- $p$ is the **number of features**\n- $\\beta_j$ is a **model coefficient**\n- $\\alpha$ is a **tuning parameter:**\n    - A tiny $\\alpha$ imposes no penalty on the coefficient size, and is equivalent to a normal linear regression model.\n    - Increasing the $\\alpha$ penalizes the coefficients and thus shrinks them.\n\n\n## Cross Validation\n\n[Cross validation](https://en.wikipedia.org/wiki/Cross-validation_(statistics)) is a model validation technique for assessing how the results of a statistical analysis will generalize to an independent data set. It is mainly used in settings where the goal is prediction, and one wants to estimate how accurately a predictive model will perform in practice. \n\n**k-fold cross-validation**  \n\nIn k-fold cross-validation, the original sample is randomly partitioned into k equal sized subsamples. Of the k subsamples, a single subsample is retained as the validation data for testing the model, and the remaining k \u2212 1 subsamples are used as training data. The cross-validation process is then repeated k times (the folds), with each of the k subsamples used exactly once as the validation data. The k results from the folds can then be averaged to produce a single estimation. The advantage of this method over repeated random sub-sampling (see below) is that all observations are used for both training and validation, and each observation is used for validation exactly once. 10-fold cross-validation is commonly used,[7] but in general k remains an unfixed parameter.\n\nFor example, setting k = 2 results in 2-fold cross-validation. In 2-fold cross-validation, we randomly shuffle the dataset into two sets d0 and d1, so that both sets are equal size (this is usually implemented by shuffling the data array and then splitting it in two). We then train on d0 and test on d1, followed by training on d1 and testing on d0.\n\nWhen k = n (the number of observations), the k-fold cross-validation is exactly the leave-one-out cross-validation.\n\nIn stratified k-fold cross-validation, the folds are selected so that the mean response value is approximately equal in all the folds. In the case of a dichotomous classification, this means that each fold contains roughly the same proportions of the two types of class labels.\n\n\n## Time Series  \n\nA [time series](https://en.wikipedia.org/wiki/Time_series) is a sequence of data points, typically consisting of successive measurements made over a time interval. This is a very common type of data as we frequently measure how something varies over time.  usually a time series is an ordered sequence of values of a variable at equally spaced time intervals; but methods exist to deal with irregular sampling.  \n\nExamples of time series include:\n\n* Stock Market\n* The change of weather \n* An electrocardiogram (EKG or ECG), that is, the electrical activity of your heart.\n* The popularity of a celebirty or politician\n* Economic Forecasting  \n\n   \n\n- from https://commons.wikimedia.org/wiki/File:Gold_Spot_Price_per_Gram_from_Jan_1971_to_Jan_2012.svg\n\n\nUnivariate (bivariate, multivariate) time series: collection of observations of one (two, several) state variables, that are made in sequential momentsin time.\n\nThe [sampling](https://en.wikipedia.org/wiki/Sampling_(signal_processing)) frequency (or sample rate) is the number of samples per unit of time. (e.g once per minute).\n\n\n   \n- from https://commons.wikimedia.org/wiki/File:Signal_Sampling.png  \n\n### Nyquist criterion\n\nNyquist criterion, or [Nyquist frequency](https://en.wikipedia.org/wiki/Nyquist_frequency), named after electronic engineer [Harry Nyquist](https://en.wikipedia.org/wiki/Harry_Nyquist), is half of the sampling rate of a discrete signal processing system. In order to correctly determine the frequency spectrum of a signal, the signal must be measured at least twice per period.\n\n### Reconstruction \n\nReconstruction is the opposite of sampling, the process by which a sampled signal is converted into a continuous signal.  \n\n    \nUnder-Sampling  \n\n### Components of Time Series\n\nThe pattern or behavior of the data in a time series can be made up of several components. Theoretically, any time series can be decomposed into:\n\n*Trend*   \n\nThe trend component accounts for the gradual shifting of the time series to relatively higher or lower values over a long period of time.\n\n*Cyclical*\n\nA regular pattern of sequences of values that go above and below the trend line is a cyclical component.\n\n\n*Seasonal*\n\nThe seasonal component accounts for regular patterns of variability within certain time periods, such as a year. While seasons could be modeled using cyclical components. Often within-year, within-month, within-week or within-day cycles are treated as \u201cseasonal\u201d behavior.  \n\n\n*Irregular*  \n\nThe irregular components represent erratic, unsystematic, \u2018residual\u2019 fluctuations. That is, noise.   \n\n\n### Stationary versus Non-stationary time series\n\nNon-stationary time series or have means, variances and covariances that change over time. Whereas while stationary time series have up and down flucutions they have means, variances and covariances.  That is, a [stationary process](https://en.wikipedia.org/wiki/Stationary_process) is a stochastic process whose joint probability distribution does not change when shifted in time. \n\nFor example, we expect financial time series data, to be non-stationary since we would expect a deterministic upward trend in price.\n\nA grown adults weight would more likely be stationary time series unless he or she fundenemtally changes their \"state\".  \n\n     \n*Two simulated time series processes, one stationary the other non-stationary.* \n- from https://commons.wikimedia.org/wiki/File:Stationarycomparison.png   \n\n### Smoothing Methods of Time Series\n\nSmoothing a time series: to eliminate some of short-term fluctuations. Sometimes smoothing is done to remove cyclical or  seasonal fluctuations. (i.e. \"deseasonalize\"\" a time series). Usually smoothing refers to methods for reducing of canceling the effect due to random variation. The simplest smoothing method is just the \"simple\" average of all past data.  Of course, the \"simple\" average or mean of all past observations is only a useful estimate for forecasting when there are no trends. \n\n### Time Series Decomposition\n\nTime Series Decomposition is a procedure to identify the component factors of a time series. That is, to create a model that expresses the time series variable Y in terms of the components T (trend), C (cycle), S (seasonal) and I (iregular).\n\n## Time Series Analysis\n\nTime series analysis generates a model that accounts an internal structure (such as autocorrelation, trend or seasonal variation) of a set of data points taken over time. This is very frequently used for forecasting. That is, predicting and future event in time based on a sequential historical sample.  \n\n\n### Autocorrelation\n\n[Autocorrelation](https://en.wikipedia.org/wiki/Autocorrelation), also known as serial correlation or cross-autocorrelation, is the cross-correlation of a signal with itself at different points in time. It is the correlation between values of the process at different times. Informally, it is the similarity between observations as a function of the time lag between them. It is a mathematical tool for finding repeating patterns, such as the presence of a periodic signal obscured by noise.  \n\nLet X be some repeatable process, and i be some point in time after the start of that process. (i may be an integer for a discrete-time process or a real number for a continuous-time process.) Then $X_i$ is the value (or realization) produced by a given run of the process at time i. Suppose that the process is further known to have defined values for mean \u03bci and variance \u03c3i2 for all times i. Then the definition of the autocorrelation between times s and t is\n\n$$\nR(s,t) = \\frac{\\operatorname{E}[(X_t - \\mu_t)(X_s - \\mu_s)]}{\\sigma_t\\sigma_s}\\, ,\n$$\n\nwhere \"E\" is the expected value operator. Note that this expression is not well-defined for all time series or processes, because the variance may be zero (for a constant process) or infinite (for processes with distribution lacking well-behaved moments, such as certain types of power law).\n\n### Correlogram\n\nIn the analysis of data, a [correlogram](https://en.wikipedia.org/wiki/Correlogram) is an image of correlation statistics. For example, in time series analysis, a correlogram, also known as an autocorrelation plot, is a plot of the sample autocorrelations $r_{h}, r_{h}$, versus $h$ (the time lags).  \n\nIf cross-correlation is used, the result is called a cross-correlogram. The correlogram is a commonly used tool for checking randomness in a data set. This randomness is ascertained by computing autocorrelations for data values at varying time lags. If random, such autocorrelations should be near zero for any and all time-lag separations. If non-random, then one or more of the autocorrelations will be significantly non-zero.\n\n   \n\n[By M. W. Toews - Own work, CC BY 4.0](https://commons.wikimedia.org/w/index.php?curid=2379384)\n\n### Naive & Simple Averaging\n\nNaive or \"simple\" averaging is just the mean (or median) of all past data.  Of course, the \"simple\" average or mean of all past observations is only a useful estimate for forecasting when there are no trends. \n\nFor example, if we have prices are $p_M, p_{M-1},\\dots,p_{M-(n-1)}$ then the formula is\n\n$$\n\\textit{SMA} = { p_M + p_{M-1} + \\cdots + p_{M-(n-1)} \\over n }\n$$\n\n### Moving Averages\n\nA moving average (rolling average or running average) is an average that is updated for a window or history of n events. This is sometimes called the arithmetic moving average the most recent n data values. For an an equally weighted average of the sequence of n values $x_1. \\ldots, x_n$ up to the current time:\n$$\n\\textit{MA}_n = {{x_1 + \\cdots + x_n} \\over n}\\,.\n$$\n\n### Weighted Moving Averages\n\nA weighted moving average places more weight on recent observations.  Sum of the weights needs to equal 1. For example. in technical analysis of financial data, a weighted moving average (WMA) often uses weights that decrease in arithmetical progression. In an n-day WMA the latest day has weight n, the second latest n \u2212 1, etc., down to one.\n\n$$\n\\text{WMA}_{M} = { n p_{M} + (n-1) p_{M-1} + \\cdots + 2 p_{(M-n+2)} + p_{(M-n+1)} \\over n + (n-1) + \\cdots + 2 + 1}\n$$\n\nThat is, the denominator is a triangle number equal to $\\frac{n(n+1)}{2}$.\n\nThere are many other methods for weighting the importance of more recent observations.   \n\n   \n\"Weighted moving average weights N=15\". Licensed under CC BY-SA 3.0 via Commons   \n\n\n### Exponential moving average\n\nExponential moving average (also called Single Exponential Smoothing) continually revises a forecast in light of more recent experiences.  Averaging (smoothing) past values of a series in a decreasing (exponential) manner.  \n\nThe EMA for a series Y may be calculated recursively:\n\n$$\nS_1   Y_1 \\quad for  \\quad t > 1, S_{t} = \\alpha \\cdot Y_{t} + (1-\\alpha) \\cdot S_{t-1}\n$$\n\nWhere:  \n\n* The coefficient $\\alpha$ represents the degree of weighting decrease, a constant smoothing factor between 0 and 1. A higher  $\\alpha$  discounts older observations faster.  \n* $Y_t$ is the value at a time period t.\n* $S_t$ is the value of the EMA at any time period t.\n\nSince the base values of the recursive intial call is undefined. The priming of values such as $S_1$ may be initialized in a number of different ways, most commonly by setting $S_1$ to $Y_1$, or by setting  $S_1$to an average of the first few observations.   \n\n    \n\"Exponential moving average weights N=15\". Licensed under CC BY-SA 3.0 via Commons \n\n### Double exponential smoothing  \n\nHolt-Winters method for exponential smoothing extended Holt\u2019s method to capture seasonality. This is sometimes called \"Double exponential smoothing.\" The Holt-Winters seasonal method comprises the forecast equation and two smoothing equations. e use {$s_t$} to represent the smoothed value for time t, and {$b_t$} is our best estimate of the trend at time t. The output of the algorithm is now written as Ft+m, an estimate of the value of x at time t+m, m>0 based on the raw data up to time t. Double exponential smoothing is given by the formulas\n\n$$\n\\begin{align}\ns_1& = x_1\\\\\nb_1& = x_1 - x_0\\\\\n\\end{align}\n$$\n\nAnd for t > 1 by\n\n$$\n\\begin{align}\ns_{t}& = \\alpha x_{t} + (1-\\alpha)(s_{t-1} + b_{t-1})\\\\\nb_{t}& = \\beta (s_t - s_{t-1}) + (1-\\beta)b_{t-1}\\\\\n\\end{align}\n$$\n\nwhere \u03b1 is the data smoothing factor, 0 < $\\alpha$ < 1, and \u03b2 is the trend smoothing factor, 0 < $\\beta$ < 1. \n\n### Triple exponential smoothing\n\nTriple exponential smoothing account seasonal changes as well as trends using three smoothing equations \u2014 one for the level, one for trend, and one for the seasonal component denoted, with smoothing parameters $\\alpha, \\beta,$ and $\\gamma$. We use a variable $m$ to denote the period of the seasonality, i.e., the number of seasons in a year. For example, for quarterly data m=4, and for monthly data m=12.\n\nThere are two variations to this method that differ in the nature of the seasonal component. The additive method is preferred when the seasonal variations are roughly constant through the series, while the multiplicative method is preferred when the seasonal variations are changing proportional to the level of the series. \n\n\n## Autoregressive integrated moving average (ARIMA)\n\nAn autoregressive integrated moving average (ARIMA or ARMA) model combines an autoregressive component with a moving average component in to a single model.   \n\nAn [autoregressive integrated moving average (ARIMA or ARMA)](https://en.wikipedia.org/wiki/Autoregressive_integrated_moving_average) model is a generalization of an autoregressive moving average (ARMA) model. These models are fitted to time series data either to better understand the data or to predict future points in the series (forecasting). They are applied in some cases where data show evidence of non-stationarity, where an initial differencing step (corresponding to the \"integrated\" part of the model) can be applied to reduce the non-stationarity.\n\nNon-seasonal ARIMA models are generally denoted $ARIMA(p, d, q)$ where parameters $p, d, and q$ are non-negative integers, $p$ is the order of the Autoregressive model, $d$ is the degree of differencing, and $q$ is the order of the Moving-average model.  The he number of differences $d$ is determined using repeated statistical tests. The values of $p$ and $q$ are then chosen by minimizing the AICc after differencing the data $d$ times. \n\nThe ARIMA model uses an iterative three-stage modeling approach:\n\nModel identification and model selection: making sure that the variables are stationary, identifying seasonality in the dependent series (seasonally differencing it if necessary), and using plots of the autocorrelation and partial autocorrelation functions of the dependent time series to decide which (if any) autoregressive or moving average component should be used in the model.   \n\nParameter estimation using computation algorithms to arrive at coefficients that best fit the selected ARIMA model. The most common methods use maximum likelihood estimation or non-linear least-squares estimation.   \n\nModel checking by testing whether the estimated model conforms to the specifications of a stationary univariate process. In particular, the residuals should be independent of each other and constant in mean and variance over time. (Plotting the mean and variance of residuals over time and performing a Ljung-Box test or plotting autocorrelation and partial autocorrelation of the residuals are helpful to identify misspecification.) If the estimation is inadequate, we have to return to step one and attempt to build a better model.   \n\n## Linear Time-Series Model\n\nUsing regression we can model and forecast the trend in time series data by including the time as a predictor variable. Time series processes are often described by multiple linear regression (MLR) models of the form:\n\n$$y_t = X_t \\beta + e_t,$$\n\nNote that the above equation differs from our usual regression in that the predictor variables are a function of time, $t$. As oppossed to the more familair form below:  \n\n$$ Y = \\beta X + e $$\n\nwhere  $y_t$ is an observed response and  $X_t$ includes columns for contemporaneous values of observable predictors. The partial regression coefficients in  $\\beta$ represent the marginal contributions of individual predictors to the variation in  $y_t$ when all of the other predictors are held fixed. A common feature of time series data is a trend. Regressing non-stationary time series can lead to spurious regressions.  \n\nThe error term $\\varepsilon_i$ still has the following assumptions:\n\n* have mean zero; otherwise the forecasts will be systematically biased.\n* statistical independence of the errors (in particular, no correlation between consecutive errors in the case of time series data).\n* homoscedasticity (constant variance) of the errors.\n* normality of the error distribution.  \n\n\n## Text Mining   \n\n[Text mining](https://en.wikipedia.org/wiki/Text_mining), also called text analytics, is the process of deriving high-quality information from text. Given the vast amount of text on the Internet, text mining is one of the most important research areas in machine learning. Text mining includes:\n\n* [Information retrieval](https://en.wikipedia.org/wiki/Information_retrieval) - the process of obtaining structured data from free text.\n* [Entity recognition](https://en.wikipedia.org/wiki/Named-entity_recognition) - identification of nouns (e.g. known people, places and things) in text. \n* Fact extraction - identification of associations among entities and other information in text.\n* [Sentiment analysis](https://en.wikipedia.org/wiki/Sentiment_analysis) is the assocaition of opinion and a topic within text. \n* [Topic modeling](https://en.wikipedia.org/wiki/Topic_model) - identification of \"topics\" in text.\n* Automated Tagging - a process to associate free-form keywords (not necessarily in the text) to index and search text.\n\n\n##  Text corpora and dictionaries  \n\nIn linguistics, a corpus (plural corpora) or text corpus is a large and structured set of texts. They help annotate words.  \n\n* [corpus.byu.edu](http://corpus.byu.edu/) includes:\n     + Hansard Corpus (British Parliament), 1.6 billion words\n     + Global Web-Based English (GloWbE), 1.9 billion words  \n     + Corpus of Contemporary American English (COCA), 450 million words  \n     + TIME Magazine Corpus, 100 million words  \n     + Corpus of American Soap Operas, 100 million words  \n     + British National Corpus (BYU-BNC), 100 million words  \n     + Strathy Corpus (Canada), 100 million words  \n* The [British National Corpus](http://www.natcorp.ox.ac.uk/), extracts from 4124 modern British English texts of all kinds, both spoken and written; over 100 million words.\n* The [Brown University Corpus](http://www.hit.uib.no/icame/brown/bcm.html): Approximately 1,000,000 words of American written English dating from 1960. The genre categories are parallel to those of the LOB corpus.\n* The [LOB Corpus](http://clu.uni.no/icame/manuals/) (The Lancaster-Oslo/Bergen Corpus) is ) is a million-word collection of British English texts which was compiled in the 1970s.\n* [The Kolhapur Corpus](http://www.essex.ac.uk/linguistics/external/clmt/w3c/corpus_ling/content/corpora/list/private/kolhapur.html): Approximately 1,000,000 words of Indian written English dating from 1978.  \n* The (Cambridge International Corpus)[http://uk.cambridge.org/elt/corpus] is a multi-billion word corpus of English language (containing both text corpus and spoken corpus)  \n* [The Longman-Lancaster Corpus](http://www.pearsonlongman.com/dictionaries/corpus/lancaster.html): Approximately 14.5 million words of written English from various geographical locations in the English-speaking world and of various dates and text types.* [WordNet](http://wordnet.princeton.edu/) is a lexical database of English nuns, verbs, adjectives and adverbs which are grouped into sets of cognitive synonyms (synsets). The WordNet synsets are further characterized by hyperonymy, hyponymy or ISA relationships. We downloaded the WordNet database files and parsed them. Permission to use, copy, modify and distribute WordNet for any purpose and without fee or royalty is hereby granted, WordNet provided by WordNet as long as proper attribution is given to WordNet and any derivative products don\u2019t use the WordNet trademark.  \n* [PubMed/Medline](http://www.ncbi.nlm.nih.gov/pubmed) comprises more than 25 million citations for biomedical literature. PubMed XML Data Retrieved from [http://www.nlm.nih.gov/databases/journal.html](http://www.nlm.nih.gov/databases/journal.html). You need to regiester with the National Library of Medicine to download the XML files.    \n* [arXiv](http://arxiv.org/) is an  archive with over 100000 articles in physics, 10000 in mathematics, and 1000 in computer science. arXiv Bulk Data Access Retrieved from [http://arxiv.org/help/bulk_data](http://arxiv.org/help/bulk_data)  \n* AG's news corpus is AG's corpus of news articles. Retrieved from [http://www.di.unipi.it/~gulli/AG_corpus_of_news_articles.html](http://www.di.unipi.it/~gulli/AG_corpus_of_news_articles.html)  \n* Last.fm music tags can be retrieved from [http://www.last.fm/charts/toptags](http://www.last.fm/charts/toptags )   \n* Spambase can be retrieved from [http://archive.ics.uci.edu/ml/datasets/Spambase](http://archive.ics.uci.edu/ml/datasets/Spambase) \n* Wikipedia. The  Wikipedia Data Dump can be retrieved from [http://en.wikipedia.org/wiki/Wikipedia:Database_download](http://en.wikipedia.org/wiki/Wikipedia:Database_download)  \n\n###  Unstructured text data\n\n*  [Common Crawl](http://commoncrawl.org/) is a openly accessible web crawl data that is freely available. [164] As of April 2013 the crawl has 6 billion pages and associated metadata. The crawl data is stored on Amazon\u2019s Public Data Sets, allowing it to be directly accessed for map-reduce processing in EC2. Common Crawl Retrieved from [http://commoncrawl.org/](http://commoncrawl.org/)  \n\n* Twitter data.\n    + Twitter Search API Retrieved from [https://dev.twitter.com/docs/api/1/get/search](https://dev.twitter.com/docs/api/1/get/search)\n    + Twitter Streaming APIs.  Retrieved from [https://dev.twitter.com/docs/streaming-apis](https://dev.twitter.com/docs/streaming-apis)\n    + Twitter\u201cFire hose\u201d real-time stream. See [https://dev.twitter.com/streaming/firehose](https://dev.twitter.com/streaming/firehose)  \n    \n*  Instagram      \n    + API - Instagram [https://instagram.com/developer/](https://instagram.com/developer/)      \n\n###  Writing a web crawler  \n\nA Web crawler (also known as a Web spider or Web robot or  bot) is a pscript which browses the World Wide Web and extracts web pages and links.\n```\nurls=<list of urls>\nwhile (urls)\n{\n  * request url\n  * request document\n  * store text for later processing\n  * parse document for links\n}\n```\n\n\n*Useful web crawling libraries in R*      \n\n*  library(regex) - Regular Expressions as used in R  \n*  library(httr) - Tools for Working with URLs and HTTP  \n*  library(XML) - XML Parser and Generator   \n*  library(RCurl) - RCurl: General Network (HTTP/FTP/...) Client Interface for R  \n*  library(jsonlite) - JSON Parser and Generator for R  \n*  library(stringr) - Simple, Consistent Wrappers for Common String Operations  \n\n## N-grams\n\nAn [n-gram](https://en.wikipedia.org/wiki/N-gram) is a contiguous sequence of n items from a given sequence of text or speech. An n-gram of size 1 is referred to as a \"unigram\"; size 2 is a \"bigram\" (or, less commonly, a \"digram\"); size 3 is a \"trigram\". Larger sizes are sometimes referred to by the value of n, e.g., \"four-gram\", \"five-gram\", and so on.\n\nfor example, bugaboo, nerd, student, data and new are one-grams. Data science, New York are two-grams. Note that New York means something different the the one grams new, and York seperately.\n\n\nNote that if we take a sentence, say\n\n\"You have brains in your head. You have feet in your shoes. You can steer yourself in any direction you choose. You're on your own, and you know what you know. And you are the guy who'll decide where to go.\"  \n\n- Dr. Seuss  \n\nMost of the two-grams aren't meaningful, that is, \"You have,\" \"have brains,\" \"brains in\" don't make sense out of context.\n\n\n## Tagging and Hashtags  \n\nTagging is a process in which end users use free-form keywords to manually index content in an organic and distributed manner. The popularity of tagging has led some to claim that it is the primary classification scheme of the Internet. A tag can be thought of as an informative keyword. A user is very unlikely to tag an article with a word like \u201cthis\u201d because it conveys very little information. Rather, they\u2019ll often tag with a subject or sentiment.  \n\nProblems with tagging are well-known.  Users often present idiosyncrasies, inaccuracies, inconsistencies, and other irregularities when tagging. Specifically, four areas are critical to tagging. The first three areas are straightforward enough:\n\n1. tag misspelling;  \n2. tag heterogeneity, (that is, different tags denoting the same content, such as \u201cZiagen\u201d and \u201cabacavir sulfate,\u201d which both refer to the same drug);  \n3. tag polysemy (i.e. identical tags that denote different meanings, such as, Apple may refer to fruit or a company. and;  \n4. semantic annotation of tags (i.e. abacavir sulfate is a drug).  \n\n\nAn important area of research in text mining is call  \u201csemantic enrichment\u201d is a particularly difficult problem. Lexical resources are often used to annotate terms. For example, lexical databases such as WordNet is often used as a source of tag annotation. \n\n\n*##hashtags*\n\nThe social tagging in is done by placing a hash mark in front of a word or phrase, such as ##BCSM, ##Lyphoma, ##BrainTumorThursday, ##BreastCancer, ##Infertility, ##Diabetes, ##lymphoedema, ##RareDiseaseDay, ##RareDisease, ##ADHD, ##Anorexia, ##MultipleSclerosis. On social media sites (such as Twitter) a word or phrase preceded by a hash or pound sign (##) and used to identify messages on a specific topic. Hastags are essentially tags that in within text and annotated.  As such they are easy to extract from text. \n\n*Stop words*\n\nIn text mining, [stop words](https://en.wikipedia.org/wiki/Stop_words) are words which are filtered out becuase they'll interfer with text analysis. Stop words usually refer to the most common words in a language, such as *the*, *is*, *at*, *which*, and on.   \n\n## Regular expressions\n\nRegular expressions (or RE or regex or regexp or rational expression) is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings, or string matching.\n\nCerain characters have special meaning in regular expressions. \n\n[] - A pair of brackets is used to indicate a set of characters.  \n'\\' - Either escapes special character or signals a special sequence.  \n?\t- The question mark indicates there is zero or one of the preceding   \n'*'\t- The asterisk indicates there is zero or more of the preceding element  . \n+\tThe plus sign indicates there is one or more of the preceding element.  \n'^' (Caret.) Matches the start of the string.    \n'$' Matches the end of the string.  \n{m} (Braces) Specifies that exactly m copies of the previous RE should be matched. \n\n\nFor example, the regexp $[A-Za-z]+$ matches a seuqnece of at least one upper or lower case letters.  The regexp $^[ ]+A-Za-z0-9._-]+@[[A-Za-z0-9.-]+$[ ]+$ matches an e-mail pattern with starting and ending white spaces. There are many excellent books that describe regular expressions in detail.   \n\n## Term-Document matrices  \n\nA [term-document matrix](https://en.wikipedia.org/wiki/Document-term_matrix) is a matrix where the rows correspond to documents in the collection and columns correspond to terms. Creating term-document matrices are created using the [R text mining package tm](https://cran.r-project.org/web/packages/tm/index.html).  \n\nD1 = \"I love R\"   \nD2 = \"I love ice-cream\"   \n\nthen the document-term matrix would be:\n\n$$\nTermDocument=\n  \\begin{bmatrix}\n      & I & love & R & ice-cream \\\\  \n    D1 & 1 & 1 & 1 & 0 \\\\\n    D2 & 1 & 1 & 0 & 1\n  \\end{bmatrix}\n$$\n\nwhich shows which documents contain which terms and how many times they appear.\n\n## Frequency signatures\n\nFor processing larger amounts of text, tag/word counts can be ineffecient using term-document matrices as these are typically very sparse matrices. Especially when one has a large dictionary of tags/words.  \n\nFor larger data we used a \u201cfrequency signature\u201d approach to convert a [bag-of-words](https://en.wikipedia.org/wiki/Bag-of-words_model) output to a format that we can use to calculate tag co-occurrence associations and mutual information. Frequency signatures are described in detail in Stefan Evert\u2019s PhD dissertation \u201cThe Statistics of Word Cooccurrences Word Pairs and Collocations.\u201d   \n\n\nTo calculate tag co-occurrence associations and mutual information for two tags, A and B, we need four items of data. The co-occurrence count of A and B, the count of A but not B, the count of B but not A, and the total number of tags in a corpus. This co-occurrence frequency data for a word pair (A,B) are usually organized in a contingency table show below. The contingency table stores the observed frequencies $O_{11} \u2026 O_{22}$. The table below (adapted from Evert\u2019s dissertation) shows an observed contingency table.\n\nContingency Tables\n\n  \n\n*Contingency table : $O_{11}$ is co-occurrence count of A and B, $O_{12}$ is the count of A but not B, $O_{21}$  is the count of B but not A, and $O_{22}$ is the count of not B and not A.*  \n\n\nHowever, while the co-occurrence count of A and B, and the total number of tags in a corpus are efficiently and easily counted the count of A but not B, the count of B but not A are tricky and computationally expensive. The insight and advantage of frequency signatures is that they calculate the count of A but not B, the count of B but not A by just counting A and B and the co-occurrence count of A and B. That is, the count of A but not B is equal to count of A minus the co-occurrence count of A and B. Likewise, the count of B but not A is equal to count of B minus the co-occurrence count of A and B.   \n\nThe frequency signature of a tag pair (A, B) is usually written as $(f, f_1, f_2,N)$. Where $f$ is the co-occurrence count of A and B, $f_1$ is the count of A but not B, $f_2$ is the count of B but not A, and N is the total counts. Notice that the observed frequencies $O_{11}, ..., O_{22}$ can be directly calculated from the frequency signature by the equations below:  \n\n* $O_{11} = f$   \n* $O_{12} = f_1 \u2212 f$   \n* $O_{21} = f_2 \u2013 f$   \n* $O_{22} = N \u2212 f_1 \u2212 f_2 + f$   \n\nGenerating all of the data tag co-occurrence association and mutual information calculations using this approach can be generated using a single pass of the data and two associative arrays; one of the tag counts and another for the tag co-occurrence counts.\n\nCalculating Associations and Mutual Information from Frequency Signatures\n\nEvert shows the many association and mutual information statistics can be calculated from the observed frequencies $O_{11}, ..., O_{22}$ if we can generate the expected frequencies $E_{11}, ..., E_{22}$. The table below (adapted from Evert\u2019s dissertation) shows the expected versus observed contingency tables.  \n\n  \n*Frequency Signatures*  \n  \nThe sum of all four observed frequencies (called the sample size N) is equal to the total number of pair tokens extracted from the corpus. R1 and R2 are the row totals of the observed contingency table, while C1 and C2 are the corresponding column totals. The expected frequencies can be directly calculated from observed frequencies $O_{11}, ..., O_{22}$ by the equations below:  \n\n* $R1 = O_{11} + O_{12}$    \n* $R2 = O_{21} + O_{22}$    \n* $C1 = O_{11} + O_{21}$   \n* $C2 = O_{12} + O_{22}$   \n* $N = O_{11} + O_{12} + O_{12} + O_{22}$   \n\n\nEvert went on to show that several association measures can be easily calculated once one has the expected and observed contingency tables. For example, the pointwise mutual information (MI) is calculated by below.\n\n$pointwise \\quad mutual \\quad information \\quad MI=\\ln\\frac{O_{11}}{E_{11}}$\n\nThe Likelihood measures that can be calculated using the expected and observed contingency tables are:  \n\n* Multinomial-likelihood   \n* Binomial-likelihood  \n* Poisson-likelihood   \n* Poisson-Stirling approximation    \n* Hypergeometric-likelihood    \n\nThe exact hypothesis tests that can be calculated using the expected and observed contingency tables are:   \n\n* binomial test    \n* Poisson test\n* Fisher's exact test   \n\nThe asymptotic hypothesis tests that can be calculated using the expected and observed contingency tables are:  \n\n* z-score    \n* Yates' continuity correction   \n* t-score (which compares O11 and E11 as random variates)    * Pearson's chi-squared test   \n* Dunning's log-likelihood (a likelihood ratio test)   \n\nThe measures from information theory that can be calculated using the expected and observed contingency tables are:    \n\n* MI (mutual information, mu-value)   \n* logarithmic odds-ratio logarithmic relative-risk    \n* Liddell's difference of proportions   \n* MS (minimum sensitivity)   \n* gmean (geometric mean) coefficient   \n* Dice coefficient (aka. \"mutual expectation\")   \n* Jaccard coefficient   \n* MIconf (a confidence-interval estimate for the mu-value)   \n* MI (pointwise mutual information)   \n* local-MI (contribution to average MI of all co-occurrences)   \n* average-MI (average MI between indicator variables)   \n\nStefan Evert also developed a R library called [UCS toolkit](http://www.collocations.de/software.html) for the statistical analysis of co-occurrence data with association measures and their evaluation in a collocation extraction task.    \n\n\n## tf\u2013idf\n\n[Tf\u2013idf](https://en.wikipedia.org/wiki/Tf%E2%80%93idf) or term frequency\u2013inverse document frequency, is a numerical statistic that is intended to reflect how important a word is to a document.\n\nThe tf-idf value increases proportionally to the number of times a word/tag appears in the document, but is offset by the frequency of the word/tag. It is a measure of jargon. If a word appears frequently in a document, it's important. Give the word a high score. But if a word appears in every documents, it's not specifc to a topic. Give the word a low score.  \n\nIf we want to find jargon, that is, topic or subject specifc words/tags then this is a reasonable metric. Words like 'the', 'a', get low scores as the are in every document. While words/tags like 'Machine Learning', 'Twitter,' or 'Text Mining' get high scores since they are used a lot in specific contexts.  \n\nIf with call $f(t,d)$ the raw frequency of a term in a document, i.e. the number of times that term t occurs in document d and $max(f(t,d))$ the maximum raw frequency of any term in the document, then the term frequency $tf(t,d)$ is:\n\n$$\n\\mathrm{tf}(t,d) = 0.5 + \\frac{0.5 \\times \\mathrm{f}(t, d)}{\\max\\{\\mathrm{f}(t, d):t \\in d\\}}\n$$\n\nThe inverse document frequency is a measure of how much information the word provides, It is the logarithmically scaled fraction of the documents that contain the word, obtained by dividing the total number of documents by the number of documents containing the term, and then taking the logarithm of that quotient.\n\n$$\n \\mathrm{idf}(t, D) =  \\log \\frac{N}{|\\{d \\in D: t \\in d\\}|}\n$$\n\nwith  \n\n* $N$: total number of documents in the corpus $N = {|D|}$   \n* $|\\{d \\in D: t \\in d\\}|$ : number of documents where the term  t  appears (i.e.,  $\\mathrm{tf}(t,d) \\neq 0$). If the term is not in the corpus, this will lead to a division-by-zero. It is therefore common to adjust the denominator to add a single \"pseudocount.\"\n\nMathematically the base of the log function does not matter for these purposes.  \n\nThen tf\u2013idf is calculated as\n\n$$\\mathrm{tf-idf}(t,d,D) = \\mathrm{tf}(t,d) \\times \\mathrm{idf}(t, D)$$\n\nA high weight in tf\u2013idf means a tag/word has high term frequency (in the given document) and a low document frequency of the term in the whole collection of documents.   \n\nFor how this is done in R see [The tf-idf-Statistic For Keyword Extraction](http://www.r-bloggers.com/the-tf-idf-statistic-for-keyword-extraction/)\n\n## Word entropy and entropy rate\n\nIn information theory, entropy is also a measure of the uncertainty in a random variable. Like tf\u2013idf, entropy quantifies the expected value of the information contained in a message (or the expected value of the information of the probability distribution). Typically this is expressed in the number of \u2018bits\u2019 or \u2018nats\u2019 that are required to encode a given message. \n\nIn this sense entropy can be used to estimate (like tf\u2013idf) how much information is in a word or tag. Entropy can also be used to estimate the generating probability distribution for a text document or corpus. The entropy of many languages has been determined. English has 1.65 bits per word, French has 3.02 bits per word, German has 1.08 bits per word, and Spanish has 1.97 bits per word. Given the probability density function of word entropies and the average bits per word of a single tweet we could then assign probabilities that it is English, French, German, or Spanish.\n\n\n### Entropy rate\n\nThe entropy rate (or mean entropy rate) describes the limiting entropy over an entire probability distribution.  This can be thought of as the average entropy over a sufficiently long realization of a stochastic process, whereas the entropy is relevant to a single random variable at a given point in time.  \n\nIn statistics, ergodicity describes a random process wherein the average time for one sufficiently long realization of events is the same as the ensemble average. That is, the ensemble\u2019s statistical properties (such as its mean or entropy) can be deduced from a single, sufficiently long sample of the process. In other words, there are long-term invariant measures that describe the asymptotic properties of the underlying probability distribution, and they can be measured by following any single reprehensive portion if followed long enough. For example, if I look at two particles in an ergodic system at any time, those particles may have very different states; but if I follow those particles long enough, they become statistically indistinguishable from one another. This means that statistical properties of the entire system can be deduced from a single sample of the process if followed for a sufficiently long time.   \n\nStationarity is the property of a random process which guarantees that the aggregate statistical properties of the probability density function, such as the mean value, its moments and variance, remain the same at every point in time. A stationary process, therefore, is one whose probability distribution is the same at all times. Its statistical properties cannot necessarily be deduced from a single sample of the process. There are stochastic processes that exhibit both stationarity and ergodicity called stationary ergodic processes. These are random processes that will not change their statistical properties with time; hence, the properties, including the disorder (entropy) of the system, can be deduced from a single, sufficiently long sample realization of the process. There are weaker forms of the stationary condition in which the first- and second-order moments (that is, the mean and variance) of a stochastic process are constant but other properties of the probability density function can vary. Likewise, there are stationary stochastic processes that are not themselves ergodic but are composed of a mixture of ergodic components.\n\n##### R\u00e9nyi entropies  \n\nThe [R\u00e9nyi entropies](https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy) generalize the Shannon entropy, the Hartley entropy, the min-entropy, and the collision entropy. As such, these entropies as an ensemble are often called the R\u00e9nyi entropies (or the R\u00e9nyi entropy, even though this usually refers to a class of entropies). The difference between these entropies is in the respective value for each of an order parameter called alpha: the values of alpha are greater than or equal to zero but cannot equal one. The Renyi entropy ordering is related to the underlying probability distributions and allows more probable events to be weighted more heavily. As alpha approaches zero, the R\u00e9nyi entropy increasingly weighs all possible events more equally, regardless of their probabilities. A higher alpha (a) weighs more probable events more heavily. The base used to calculate entropies is usually base 2 or Euler's number base e. If the base of the logarithm is 2, then the uncertainty is measured in bits. If it is the natural logarithm, then the unit is nats. \n\n##### R\u00e9nyi entropies\t \n\nThe R\u00e9nyi entropy of order $\\alpha$, where $\\alpha \\geq 0$  and $\\alpha \\neq 1$ , is defined as\n\n$$\nH_\\alpha(X) = \\frac{1}{1-\\alpha}\\log\\Bigg(\\sum_{i=1}^n p_i^\\alpha\\Bigg)\n$$\n\nHere, X is a discrete random variable with possible outcomes 1,2,...,n and corresponding probabilities $p_i \\doteq \\Pr(X=i) for i=1,\\dots,n,$ and the logarithm is base 2. \n\n\n#### Hartley entropy\n\nThe Hartley entropy (Gray, 1990) is the R\u00e9nyi entropy with an alpha of zero. \n\nthe probabilities are nonzero, $H_0$ is the logarithm of the cardinality of X, sometimes called the Hartley entropy of X:  \n\n$$\nH_0 (X) = \\log n = \\log |X|\n$$\n\n#### Shannon entropy \n\nThe Shannon entropy (Gray, 1990) is the R\u00e9nyi entropy with an alpha of one. The Shannon entropy is a simple estimate of the expected value of the information contained in a message. It assumes independence and identically distributed random variables, which is a simplification when applied to word counts. In this sense it is analogous to na\u00efve Bayes, in that it is very commonly used and thought to work well in spite of violating some assumptions upon which it is based.\n\nThe limiting value of $H_\\alpha as \\alpha \\rightarrow 1$ is the Shannon entropy:\n\n$$\nH_1 (X) = - \\sum_{i=1}^n p_i \\log p_i. \n$$\n\n#### collision entropy\n\nThe collision entropy (Gray, 1990) is the R\u00e9nyi entropy with an alpha of two and is sometimes just called \"R\u00e9nyi entropy,\" refers to the case $\\alpha = 2$,\n\n$$\nH_2 (X) = - \\log \\sum_{i=1}^n p_i^2 = - \\log P(X = Y)\n$$\n\nwhere $X$ and $Y$ are independent and identically distributed. \n\n#### min-entropy\n\nThe min-entropy (Gray, 1990) is the R\u00e9nyi entropy as the limit of alpha approaches infinity. The name min-entropy stems from the fact that it is the smallest entropy measure in the R\u00e9nyi family of entropies. In the limit as $\\alpha \\rightarrow \\infty$, the R\u00e9nyi entropy $H_\\alpha converges to the min-entropy H_\\infty$:\n\n$$\nH_\\infty(X) \\doteq \\min_i (-\\log p_i) = -(\\max_i \\log p_i) = -\\log \\max_i p_i\\,.\n$$\n\nEquivalently, the min-entropy $H_\\infty(X)$ is the largest real number b such that all events occur with probability at most $2^{-b}$.\n\n\n#### Kullback-Leibler divergence\n\n[Kullback-Leibler divergence](https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence) (Gray, 1990) is a non-symmetric measure of the difference between two probability distributions. The Kullback-Leibler measure goes by several names: relative entropy, discrimination information, Kullback-Leibler (KL) number, directed divergence, informational divergence, and cross entropy. Kullback-Leibler divergence is a measure of the difference between the observed entropy and its excepted entropy. We calculate the KL divergence by weighting one distribution (like an observed frequency distribution) by the log of probabilities of some other distribution D2. For discrete probability distributions P and Q, the Kullback\u2013Leibler divergence of Q from P is defined to be\n\n$$\nD_{\\mathrm{KL}}(P\\|Q) = \\sum_i P(i) \\, \\ln\\frac{P(i)}{Q(i)}\n$$\n\nIn words, it is the expectation of the logarithmic difference between the probabilities P and Q, where the expectation is taken using the probabilities P.\n\n\n#### Mutual Information\n\n[Mutual information](https://en.wikipedia.org/wiki/Mutual_information) (Gray, 1990) quantifies the mutual dependence of the two random variables. It is a measure of the \u201cstickiness\u201d between two items. It measures how much knowing one of these variables reduces uncertainty about the other. We can use mutual information to quantify the association between two tags. Mutual information (Equation 10) is given by:\n\nthe mutual information of two discrete random variables X and Y can be defined as:\n\n$$\n I(X;Y) = \\sum_{y \\in Y} \\sum_{x \\in X} \n                 p(x,y) \\log{ \\left(\\frac{p(x,y)}{p(x)\\,p(y)}\n                              \\right) }, \\,\\!\n$$                              \n                              \nwhere $p(x,y)$ is the joint probability distribution function of $X$ and $Y$, and $p(x)$ and $p(y)$ are the marginal probability distribution functions of $X$ and $Y$ respectively. In the case of continuous random variables, the summation is replaced by a definite double integral:\n\n$$\n I(X;Y) = \\int_Y \\int_X \n                 p(x,y) \\log{ \\left(\\frac{p(x,y)}{p(x)\\,p(y)}\n                              \\right) } \\; dx \\,dy,\n$$\n \nwhere $p(x,y)$ is now the joint probability density function of $X$ and $Y$, and $p(x$) and $p(y)$ are the marginal probability density functions of $X$ and $Y$ respectively.\n\n\n\n## Zipf's law\n\n[Zipf's law](https://en.wikipedia.org/wiki/Zipf%27s_law) is an empirical law formulated using mathematical statistics, refers to the fact that many types of data studied in the physical and social sciences can be approximated with a Zipfian distribution, one of a family of related discrete power law probability distributions. It states that while only a few words are used very often, many or most are used rarely, \n\n$P_n \\sim 1/n^a$\n\nwhere $P_n$ is the frequency of a word ranked nth and the exponent a is almost 1. This means that the second item occurs approximately 1/2 as often as the first, and the third item 1/3 as often as the first, and so on. The is a so-called \"power law\" distributon.  \n\nThe law is very common when looking a the distributions of words in all lagnuages. In fact, it is named after the American linguist [George Kingsley Zipf](https://en.wikipedia.org/wiki/George_Kingsley_Zipf) when he observed this law in 1935 in his academic studies of word frequency.  \n\n## Text-mining pipeline\n\nCommon Natural language processing tasks, such as tokenization,  stemming, sentence segmentation, part-of-speech tagging, named entity extraction, chunking, parsing, word disamiguation, summarization, and coreference resolution are often done on every new text document before other types of analysis. As such it is common to write a \"pipeline\" (i.e. a sequence of scripts) that automatically perform these tasks.\n\n\n*Tokenization*  \n\n[Tokenization](http://nlp.stanford.edu/IR-book/html/htmledition/tokenization-1.html) is the task of chopping it up into pieces, called tokens. This is often done by throwing away certain characters, such as punctuation.  \n\n*Stemming*\n\n[Stemming](https://en.wikipedia.org/wiki/Stemming) reduces words to their word stem, base or root form. For example, \"argue\", \"argued\", \"argues\", \"arguing\", and \"argus\" reduce to the stem \"argu.\"  The can allow for \"argue\", \"argued\", \"argues\" to be counted as a single word.  \n\n*Sentence segmentation*  \n\n[sentence segmentation](http://www.monlp.com/2012/03/13/segmenting-words-and-sentences/) is the process plitting text into words and sentences. This is often done by looking for certain punctuation (full stop, question mark, exclamation mark, etc.).  \n\n*Part-of-speech tagging*  \n\nGiven some text [part-of-speech tagging](https://en.wikipedia.org/wiki/Part-of-speech_tagging) determines the [part of speech](https://en.wikipedia.org/wiki/Part_of_speech) for each word. (e.g. a noun, verb, adjective. etc.)\n\n\n*Named entity extraction*\n\n[Named entity recognition](https://en.wikipedia.org/wiki/Named-entity_recognition) determines which items in the text map to proper nouns, such as people or places, or things.\n\n*Chunking* \n\nChunking is also called shallow parsing. It is the identification short meaningful n-grams (like noun phrases, named entities, collocations, etc.).  In this processing of a tweet, it could refer to sperating the hashtags, the links and the tweet.  \n\n*Parsing*\n\n[Parsing](https://en.wikipedia.org/wiki/Parsing) or syntactic analysis generates [https://en.wikipedia.org/wiki/Parsing] the parse tree (grammatical analysis) for each sentence or fragment. \n\n*Word-sense disambiguation*  \n\nMany words have more than one meaning. [Word-sense disambiguation](https://en.wikipedia.org/wiki/Word-sense_disambiguation] selectx the meaning which makes the most sense in context.\n\n*Coreference resolution*\n\nGiven a sentence or larger chunk of text, [coreference resolution](https://en.wikipedia.org/wiki/Coreference) determines which words (\"mentions\") refer to the same objects (\"entities\")\n\n*Automatic summarization*\n\nAutomatic summarization produce a readable summary of a chunk of text. The summary need not be grammatical, for example, a [tag cloud](https://en.wikipedia.org/wiki/Tag_cloud) could be thought of as a visual summarization of some text.  \n\n\nWhich elements are part of a Text-mining pipeline depend on the application.  \n\n\n## Small Talk and the Social Web  \n\nOne particularly interesting aspect of the social web is the nature of text made available for public consumption. From the time of the Gutenberg printing press until the advent of Web 2.0, nearly all text presented in public was written by professionals. Whether it was a book, a business or government record, a sermon, a news or opinion article, a scientific paper, or an advertisement, it was written by a professional with the intent to communicate information and/or ideas. Not until the social web and Twitter did musings about what a noncelebrity ate for breakfast or whether someone likes naps was widely available for public consumption.    \n\nMusings about one\u2019s foot fungus or a statement like \u201c Hahahahahaha!!!! You should have come to NKLA!!! So many beautiful pitties! And pittie lovers....\u201d  are what we call small talk. Small talk is light, intimate banter, often understandable only by the authors\u2019 close friends. A lot of the communication on the social web is small talk, even though it was very rare in public writing prior to the social web.  \n\nThis free very unstructured nature of language on the social web should be taken into account when mining these data. It can add a considerable amount of noise and magnifies the importance of good semantic and lexcial resources.\n\n## Ensemble methods  \n\nIn statistics and machine learning, [ensemble methods](https://en.wikipedia.org/wiki/Ensemble_learning) use multiple learning algorithms to obtain better predictive performance than could be obtained from any of the constituent learning algorithms.\n\nEnsemble methods groups a collection of base learners, with each learning according to its arget function. The ensemble then combines their outputs for a final predication. The basic idea is \"two heads are better than one.\n\" (assuming those heads make independent decsisons). This is sometimes called \u201cmeta-learning\u201d.\n\n    \n*Ensemble Learning*\n\nThe basic issue with ensemble learning is:    \n* How can you choose independent learners?    \n* How can you combine learners?    \n\n## Ensemble theory\n\nEnsemble learning build many models and combines them. ensemble methods can be shown both theoretically and empirically to outperform single predictors on a wide range of tasks.\n\n*When does this work?*\n\n* Let p be the probability that a classifier makes an error  \n* Assume that classifier errors are independent    \n* The probability that k of the n classifiers make an error    \n\n$$\n\\binom n k  p^k(1-p)^{n-k}\n$$ \n \nfor k = 0, 1, 2, ..., n, where\n$$\n\\binom n k =\\frac{n!}{k!(n-k)!}\n$$\nis the binomial coefficient, hence the name of the distribution.\n\nTherefore the probability that a majority vote classifier is in error is:   \n\n$$\n \\sum_{k>n/2}^{n} \\binom n k  p^k(1-p)^{n-k}\n$$\n\n\n### Majority Vote Model\n\nIn the majority vote model the ensemble chooses the class predicted by more than $n/2$ the $n$ classifiers. If no agreement then return an error.\n\n\n### When is an Ensemble Better than a Single Learner?\n\n*\u201cNo Free Lunch\u201d Theorem*  \n\nNo single algorithm wins all the time! By combing multiple independent decisions, each of which is at least more accurate than random guessing, random errors cancel each other out and correct decisions are reinforced. Empirically, ensembles tend to yield better results when there is a significant diversity among the models. \n\n*Bias Problem*   \n\nThe hypothesis space made available by a particular classification method does not  include the true hypothesis. The bias is error from erroneous assumptions in the learning algorithm.   \n\n*Variance Problem*  \n\nThe hypothesis space is \u201ctoo large\u201d for the amount of training data \u2013 thus selected hypothesis may be inaccurate on unseen data. The variance is error from sensitivity to small fluctuations in the training set. High variance can cause overfitting: modeling the random noise in the training data, rather than the intended outputs.   \n\nBias and variance usually work in opposition to one other: attempts to reduce the bias component will cause an increase in variance, and vice versa. Many ensemble methods, therefore, seek to promote diversity among the models they combine. Ensembles methods tend to decrease error by decreasing the variance in the results due to unstable learners, algorithms  whose output can change dramatically when the training data is slightly changed. However, these random errors may not cancel and be further reinfornced if the learners all have the same bias.\n\n### Condorcet Jury Theorem\n\n[Condorcet's jury theorem](https://en.wikipedia.org/wiki/Condorcet%27s_jury_theorem) is a political science theorem about the relative probability of a given group of individuals arriving at a correct decision. The theorem was first expressed by the Marquis de Condorcet in his 1785 work Essay on the Application of Analysis to the Probability of Majority Decisions.\n\nIf each voter has an independent probability p of voting for the correct decision then the critical p for which majority voting works is a probability greater than or less than 1/2:   \n\n* If p is greater than 1/2 (each voter is more likely to vote correctly), then adding more voters increases the probability that the majority decision is correct. In the limit, the probability that the majority votes correctly approaches 1 as the number of voters increases.   \n\n* On the other hand, if p is less than 1/2 (each voter is more likely to vote incorrectly), then adding more voters makes things worse: the optimal jury consists of a single voter.   \n\n* It is critical that voter has an independent probability.   \n\nThe probability of a correct majority decision P(n,p) (p close to 1/2), the gain by having n voters grows proportionally to \\sqrt{n}.\n\n$$  \n P(n,p) = 1/2 + c_1 (p-1/2) + c_3 (p-1/2)^3 + O( (p-1/2)^5 ) \n$$   \nwhere\n$$  \n c_1 = {n  \\choose { \\lfloor n/2 \\rfloor}} \\frac{ \\lfloor n/2 \\rfloor +1} { 4^{\\lfloor n/2 \\rfloor}} = \\sqrt{ \\frac{2n+1}{\\pi}} (1 + \\frac{1}{16n^2} + O(n^{-3}) ) \n$$  \n\n### Wisdom of Crowds \n\nThe \"Wisdom of Crowds\" refers to situations in which human ensembles are demonstrably better than individual experts. This has often been observed in situations like:\n\n* How many jelly beans are in the jar?   \n* Who Wants to be a Millionaire:  \u201cAsk the audience\u201d\n* Accurately guessing the weight of an ox\n\nMany examples are given in [James Surowiecki's](https://en.wikipedia.org/wiki/James_Surowiecki) book The [Wisdom of Crowds: Why the Many Are Smarter Than the Few and How Collective Wisdom Shapes Business, Economies, Societies and Nations](https://en.wikipedia.org/wiki/The_Wisdom_of_Crowds), published in 2004.\n\nSurowiecki notes that Not all crowds (groups) are wise.  Charles Mackay's [Extraordinary Popular Delusions and the Madness of Crowds](https://en.wikipedia.org/wiki/Extraordinary_Popular_Delusions_and_the_Madness_of_Crowds), published in 1841, is a history of popular crowd delusions. Rather he states four key criteria separate wise crowds from irrational ones:\n\n* Diversity of opinion - Each person should have private information even if it's just an eccentric interpretation of the known facts.  \n* Independence - People's opinions aren't determined by the opinions of those around them.  \n* Decentralization - People are able to specialize and draw on local knowledge.   \n* Aggregation\tSome mechanism exists for turning private judgments into a collective decision. \n\nFor ensemble learners certainly the following are critical \n\n* Independence\n* Aggregation\n\nand the following certainly helps\n\n* Diversity of learners\n\nIt's not so clear that ensemble learners should specialize and draw on local knowledge; but the effect is related to diversity.    \n\n\n## Common types of ensembles\n\n### Bootstrap aggregating (bagging)\n\nCreate ensembles by [\u201cbootstrap aggregation\u201d](https://en.wikipedia.org/wiki/Bootstrap_aggregating), i.e., repeatedly randomly re-sampling training data. Not that bagging uses the same learner so bias related to the method isn't addressed by this approach. \n\nBootstrap: draw n items from X with replacement\n\nBootstrap aggregating: combines random learners (often with voting, averaging or median) to create a predictor lesss efected by noise. Unstable and/or noisy algorithms often profit from bagging.\n\nBagging's usefulness depends on the stability of the base classifiers.  If small changes in the sample cause small changes in the base-level classifier, then the ensemble will not be much better than the base classifiers. It reduces variance and helps to avoid overfitting. It is often applied to decision tree methods (random forests) and nearest neighbor classifiers, but it can be used with any type of method.  \n\n### Boosting\n\nBoosting involves incrementally building an ensemble by training each new model instance to emphasize the training instances that previous models mis-classified. In these sense it \"learns.\" Unlike bagging, weights may change at the end of boosting round making certain learners more important than others. In some cases, boosting has been shown to yield better accuracy than bagging, but it also tends tp propgate bias from the overweighting winning predictor and is more likely to over-fit the training data. By far, the most common implementation of Boosting is Adaboost.\n\n*Summary of Boosting and Bagging*\n\n* Called \u201chomogenous ensembles\u201d becuase there is a single learner \n* Bagging: Resample training data\n* Boosting: Reweight training data\n\n### AdaBoost\n\n[AdaBoost](https://en.wikipedia.org/wiki/AdaBoost), short for \"Adaptive Boosting.\" AdaBoost refers to a particular method of training a boosted classifier. A boost classifier is a classifier in the form\n\n$$\nF_T(x) = \\sum_{t=1}^T f_t(x)\\,\\!\n$$\n\nwhere each $f_t$ is a weak learner that takes an object $x$ as input and returns a real valued result indicating the class of the object. \n\nEach weak learner produces an output, hypothesis $h(x_i)$, for each sample in the training set. At each iteration t, a weak learner is selected and assigned a coefficient $\\alpha_t$ such that the sum training error $E_t$ of the resulting t-stage boost classifier training error is minimized.    \n\n$E_t = \\sum_i E[F_{t-1}(x_i) + \\alpha_t h(x_i)]$\nHere $F_{t-1}(x)$ is the boosted classifier that has been built up to the previous stage of training, $E(F)$ is some error function and $f_t(x) = \\alpha_t h(x)$ is the weak learner that is being considered for addition to the final classifier.\n\nAdaBoost can be thought of as a form of gradient descent along the error gradient.   \n\n\n### Bayesian parameter averaging\n\nBayesian classifiers are determined by the parameters of the models. Bayesian parameter averagingis an ensemble of all the hypotheses in the hypothesis space. The idea is that the bias of the modelds does not change, but variance decreases by the number of independent models.   \n\n\n### Bucket of models\n\nA \"bucket of models\" is an ensemble in which a model selection algorithm is used to choose the best model for each problem. When tested with only one problem, a bucket of models can produce no better results than the best model in the set, but when evaluated across many problems, it will typically produce much better results, on average, than any model in the set.\n\n```\nFor each model m in the bucket:\n  Do c times: (where 'c' is some constant)\n    Randomly divide the training dataset into two datasets: A, and B.\n    Train m with A\n    Test m with B\nSelect the model that obtains the highest average score\n```\nThis idea can be summed up as, \"try them all with the training set, and pick the one that works best\".\n\n\n### Stacking\n\nStacking (sometimes called stacked generalization) involves training a learning algorithm to combine the predictions of several other learning algorithms.\n\nUnlike a bucket of models it isn't a \"winner take all\" approach. Unlike \u201chomogenous ensembles\u201d like bagging and boosting here we are creating \u201cheterogenous ensembles\u201d and various preictors.     \n\n### Random Forests\n\n[Random forests](https://en.wikipedia.org/wiki/Random_forest) involve bagging multitude of decision trees at training time and outputting the class that is the mode of the classes (classification) or mean prediction (regression) of the individual trees.  \n\n```\nFor i = 1 to T,\n  Take a bootstrap sample (bag)\n  Grow a random decision tree  T_i\n  At each node choose a feature from one of n features (n < total number of features)\n  Grow a full tree (do not prune)\n\nFinal classification is done by majority vote across the T random trees.\n```\n\n## Developing Ensemble Models?\n\nThe main challenge is not to obtain highly accurate base models, very weak predictors with an accuracy of greater than 50% can be used, but rather to obtain base models which make different kinds of errors.   \n\nWhen one resamples or rewights training data, as one does with bagging amd boosting it helps with noisy data but not the predictor itself.\n\nTo generate \u201cheterogenous ensembles\u201d independence between the base classifiers needs to be assessed. Independence between classifiers is often assed by measuring the degree of overlap in misclassifying training examples. Less overlap means more independence between models. The key of designing ensembles is diversity and not necessarily high accuracy of the base classifiers: Members of the ensemble should vary in the examples they misclassify. \n\n\n \n## Probability and Statistics\n\nProbability is a measure of the likelihood of a random phenomenon or chance behavior.  Probability describes the long-term proportion with which a certain outcome will occur in situations with short-term uncertainty. \n\n### The Axioms of Probability\n\n\n##### First axiom - The probability of an event is a non-negative real number:\n$$\nP(E)\\in\\mathbb{R}, P(E)\\geq 0 \\qquad \\forall E\\in F\n$$\nwhere $F$ is the event space\n\n##### Second axiom -  unit measure:\n\nThe probability that some elementary event in the entire sample space will occur is 1.\n\n$$\nP(\\Omega) = 1.\n$$  \n\n##### Third axiom - the assumption of $\\sigma$-additivity:\n\nAny countable sequence of disjoint (synonymous with mutually exclusive) events $E_1, E_2, ...$ satisfies\n\n$$\nP\\left(\\bigcup_{i = 1}^\\infty E_i\\right) = \\sum_{i=1}^\\infty P(E_i).\n$$\n\nThe total probability of all possible event always sums to 1. \n\n### Consequences of these axioms\nThe probability of the empty set:\n$$\nP(\\varnothing)=0.\n$$\n\nMonotonicity   \n$$\n\\quad\\text{if}\\quad A\\subseteq B\\quad\\text{then}\\quad P(A)\\leq P(B).\n$$\n\nThe numeric bound between 0 and 1:  \n\n$$\n0\\leq P(E)\\leq 1\\qquad \\forall E\\in F.\n$$\n\n\n    \n*Probability is expressed in numbers between 0 and 1.*   \n\n\nProbabilty of a certain event is 1:\n\n$$\nP(True) = 1\n$$\n\nProbability = 1 means it always happens.\n\n\nProbabilty of an impossible event is 0:\n\n$$\nP(False) = 0\n$$\n\nProbability = 0 means the event never happens.  \n\nProbabilty of A or B:\n\n$$\nP(A \\quad or \\quad B) = P(A) + P(A) - P(A \\quad and \\quad B) \n$$\n\nor\n\n$$\nP(A \\cup B) = P(A) + P(A) - P(A \\cap B) \n$$\n\n\nProbabilty of not A:\n\n$$\nP(not  \\quad A) = 1- P(A) \n$$\n\n\n## Conditional Probability\n\nIn probability theory, a [conditional probability](https://en.wikipedia.org/wiki/Conditional_probability) measures the probability of an event given that another event has occurred. That is,  \"the conditional probability of A given B.\"   \n\n the conditional probability of A given B is defined as the quotient of the probability of the joint of events A and B, and the probability of B:\n \n$$ \nP(A|B) = \\frac{P(A \\cap B)}{P(B)}\n$$\n\nThis may be visualized using a Venn diagram. \n\n     \n*$P(A \\cap B)$*\n\n### Corollary of Conditional Probability is The Chain Rule\n\nIf we multiply both sides by $P(B)$ then\n\n$$ \nP(A|B) = \\frac{P(A \\cap B)}{P(B)}\n$$\n\nbecomes\n\n$$ \nP(A|B) P(B) = P(A \\cap B) \n$$\n\n\n\n\n\n### Statistical independence\n\nEvents A and B are defined to be statistically independent if:\n\n$$\n\\begin{align}\n             P(A \\cap B) &= P(A) P(B) \\\\\n  \\Leftrightarrow P(A|B) &= P(A) \\\\\n  \\Leftrightarrow P(B|A) &= P(B)\n\\end{align}\n$$\n\nThat is, the occurrence of A does not affect the probability of B, and vice versa\n\n\nProbabilty of A or B for independent events $P(A and B) is 0$:\n\n$$\nP(A or B) = P(A) + P(A) \n$$\n\n## Bayes Rule\n\n[Bayes' theorem](https://en.wikipedia.org/wiki/Bayes%27_theorem) (alternatively Bayes' law or Bayes' rule) describes the probability of an event, given prior events. That is, a conditional probability.\n\n$$\nP(A|B) = \\frac{P(A)\\, P(B | A)}{P(B)},\n$$\n\nwhere A and B are events.\n\n* P(A) and P(B) are the independent probabilities of A and B.  \n* P(A | B), a conditional probability, is the probability of observing event A given that B is true.  \n* P(B | A), is the probability of observing event B given that A is true.  \n\n\n## Bayesian inference\n\n[Bayesian inference](https://en.wikipedia.org/wiki/Bayesian_inference) is a method of statistical inference in which Bayes' theorem is used to update the probability for a hypothesis as evidence. Bayesian inference derives the posterior probability as a consequence of two antecedents, a prior probability and a \"likelihood function\" derived from a statistical model for the observed data. \n\nBayesian inference computes the posterior probability according to Bayes' theorem:\n\n$$\nP(H\\mid E) = \\frac{P(E\\mid H) \\cdot P(H)}{P(E)}\n$$\n\nwhere,    \n\n$P(H\\mid E)$ the posterior probability, denotes a conditional probability of $\\textstyle H$ (the hypothesis) whose probability may be affected by the evidence $\\textstyle E$.   \n\n$\\textstyle P(H)$, the prior probability, is an estimate of the probability that a hypothesis is true, before observing the current evidence.   \n\n$\\textstyle P(E\\mid H)$ is the probability of observing $\\textstyle E$ given $\\textstyle H$. It indicates the compatibility of the evidence with the given hypothesis.   \n\n$\\textstyle P(E)$ is sometimes termed the marginal likelihood or \"model evidence\". This factor is the same for all possible hypotheses being considered. \n\nNote that Bayes' rule can also be written as follows:\n$$\nP(H\\mid E) = \\frac{P(E\\mid H)}{P(E)} \\cdot P(H)\n$$\nwhere the factor $\\textstyle \\frac{P(E\\mid H)}{P(E)}$ represents the impact of $E$ on the probability of $H$.   \n\n## Bayesian probability example\n\nSuppose a certain disease has an incidence rate of 0.01% (that is, it afflicts 0.01% of the population).  A test has been devised to detect this disease.  The test does not produce false negatives (that is, anyone who has the disease will test positive for it), but the false positive rate is 1% (that is, about 1% of people who take the test will test positive, even though they do not have the disease).  Suppose a randomly selected person takes the test and tests positive.  What is the probability that this person actually has the disease?\n\nBayes theorem would ask the question, what is the probability of disease given a postive result, or $P(disease\\mid positive))$. \n\nWhat do we know?  \n\n$P(positive\\mid disease)=1$ (i.e. The test does not produce false negatives.)     \n$P(disease)=0.0001$ (i.e.  1/10,000 have the disease)      \n$P(positive\\mid no disease)=0.01$ (i.e. he false positive rate is 1%. This means 1% of people who take the test will test positive, even though they do not have the disease)      \n\nBayes\u2019 Theorem\n\n$$\nP(A|B) = \\frac{P(A)\\, P(B | A)}{P(B)},\n$$\n\nwhich can be rewritten as  \n\n$$\nP(A|B) = \\frac{P(A)\\, P(B | A)}{P(A)P(B|A)+P(\\bar{A})P(B|\\bar{A})},\n$$\n\nwhich in our example is\n$$\nP(disease|positive) = \\frac{P(disease)\\, P(positive | disease)}{P(disease)P(positive|disease)+P(no \\quad  disease)P(positive|no \\quad disease)},\n$$\n\nplugging in the numbers gives\n\n$$\nP(disease|positive)= \\frac{(0.0001)\\, (1)}{(0.0001)(1)+(0.9999)(0.01)}, \\approx 0.01\n$$\n\nSo even though the test is 99% accurate, of all people who test positive, over 99% do not have the disease.  \n\n\n## Bayesians versus Frequentists\n\n \n[Frequentist inference](https://en.wikipedia.org/wiki/Frequentist_inference) or frequentist statistics is a scheme for making statistical inference based on the frequency or proportion of the data. This effectively requires that conclusions should only be drawn with a set of repetitions.    \n\nFrequentists will only generate statistical inference given a large enough set of repetitions. In contrast, a Bayesian approach to inference does allow probabilities to be associated with unknown parameters.   \n\n   \n*Count Von Count*   \n- from https://en.wikipedia.org/wiki/File:Count_von_Count_kneeling.png  \n\nWhile \"probabilities\" are involved in both approaches to inference, frequentist probability is essentially equivelent to counting. The Bayesian approach allows these estimates of probabilities to be based upon counting but also allows for subjective estimates (i.e. guesses) of prior probabilities.\n\nBayesian probability, also called evidential probability, or subjectivist probability, can be assigned to any statement whatsoever, even when no random process is involved. Evidential probabilities are considered to be degrees of belief, and a Bayesian can even use an un-informative prior (also called a non-informative or Jeffreys prior).\n\nIn Bayesian probability, the [Jeffreys prior](https://en.wikipedia.org/wiki/Jeffreys_prior), named after Sir Harold Jeffreys, is a non-informative (objective) prior distribution for a parameter space.  The crucial idea behind the Jeffreys prior is the Jeffreys posterior. This posterior aims to reflect as best as possible the information about the parameters brought by the data, in effect  \"representing ignorance\" about the prior. This is sometimes called the \"principle of indifference.\" Jeffreys prior is proportional to the square root of the determinant of the Fisher information:\n\n$$\np\\left(\\vec\\theta\\right) \\propto \\sqrt{\\det \\mathcal{I}\\left(\\vec\\theta\\right)}.\\,\n$$\n\nIt has the key feature that it is invariant under reparameterization of the parameter vector $\\vec\\theta.$  \n\nAt its essence the Bayesian can be vague or subjective about an inital guess at a prior probability. and the the posterior probability be updated data point by data point. A Bayesian defines a \"probability\" in the same way that many non-statisticians do - namely an indication of the plausibility or belief of a proposition.\n\nA Frequentist is someone that believes probabilities represent long run frequencies with which events occur; he or she will have a model (e.g. Guassian, uniform, etc.) of how the sample popluation was generated. The observed counts are considered a random sample the estimate the true parameters of the model.   \n\nIt is important to note that most Frequentist methods have a Bayesian equivalent (that is, they give the same results) when there are enough repeated trails. That is, they converge the the same result given enough data.  \n\n\n\n## Genetic Algorithms\n\nA genetic algorithm (GA) is a search heuristic that mimics the process of natural selection. This heuristic is often used to generate useful solutions to optimization and search problems.\n\n\n*Genetic algorithm (GA)*  \n\n### Genetic Algorithm Pseudocode \n\nCreate an initial population, typically random  \n\nWhile the best candidate so far is not a solution:  \n   Create new population using crossover and mutation.  \n   Evaluate the fitness of each candidate in the population.  \n   Replace/delete least-fit population  \n   \nReturn the best candidate found\n\n\n### Genetic Algorithm Basic components\n\n* Candidate representation  \n    + Important to choose this well the form can effect the solution.  \n    + The typical candidate representation is a binary string.  \n* successor functions.  \n    + Mutation, crossover  \n    + Mutation - Given a candidate, return a slightly different candidate.  \n    + Crossover - Given two candidates, produce one that has elements of each.  \n* Fitness function  \n    + The fitness function quantitates estimates how close a candidate is to being a solution.  \n* Solution test  \n    + Check whether the candidate is a solution.\n* Some parameters  \n    + Population size  \n    + Generation limit  \n\n### Pros and Cons\n\n*Pros*  \n*  Fast (and low memory)  \n*  Finding a candidate representation and fitness function are the bulk of the work.  \n\n*Cons*   \n* Randomized (not guaranteed optimal or complete).   \n* Can get stuck on local maxima (crossover is intended to help get out of local maxima)   \n\n\n## Simulated Annealing\n\nA Simulated Annealing (SA) is a  probabilistic search heuristic that mimics the process of cooling in thermodynamic systems. This heuristic is often used to generate useful solutions to optimization and search problems.  The method is an adaptation of the [Metropolis\u2013Hastings algorithm](https://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm), a Monte Carlo method to generate sample states of a thermodynamic system, invented by M.N. Rosenbluth and published in a paper by N. Metropolis et al. in 1953.\n\nBasically simulated annealing perturbs the current solution  and then checks to see whether the new solution is good or not. If its an improvement it will accept it and if the new solution is worse it may accept it with a probability inversely proportional to how much worse the new solution changes the current one. Compared to pure gradient descent the main difference is that SA allows \"uphill\" steps. Simulated annealing also differs from gradient descent in that a move is selected at random.\n\n\n\n*Gradient Descent*    \n\n### Metropolis\u2013Hastings algorithm\n\n[Metropolis algorithm](https://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm) (symmetric proposal distribution)\nLet f(x) be a function that is proportional to the desired probability distribution P(x) \n\n\n\nThis algorithm proceeds by randomly attempting to move about the sample space, sometimes accepting the moves and sometimes remaining in place.\n\n\nPerturb (randomly) the current state to a new state. \n$\\Delta E$ is the difference in energy between current and new state.   \nIf $\\Delta E < 0$ (new state is lower), accept new state as current state\nIf  $\\Delta E > 0$  accept new state with probability inversely proportional to the increase in system energy. Traditionally the change in [Gibbs free energy](https://en.wikipedia.org/wiki/Gibbs_free_energy) is used for thermodynamic free energy systems.\n\nThis can be run for a fixed number of iterations or if the overall system energy can measured then it can be run until the overall system energy settles.\t\t\n\n\n### Simulated Annealing Pseudocode \n\nSimulated Annealing uses the Metropolis\u2013Hastings algorithm with a temperature parameter $T$ that effects the acceptance probability of an \"uphill\" transition. At higher\"temperatures\" accpeting \"uphill\" transitions is more probable. The algorithm starts initially with $T$ set to a high value , and then it is decreased at each step following some annealing schedule\u2014which is often specified by the user, but must end with $T=0$. At $T=0$ there is no chance of accpeting \"uphill\" transitions and so it becomes gradient descent.  \n\nAt a fixed temperature T:  \nPerturb (randomly) the current state to a new state. \n$\\Delta E$ is the difference in energy between current and new state.  \nIf $\\Delta E < 0$ (new state is lower), accept new state as current state\nIf  $\\Delta E > 0$  accept new state with probability inversely proportional to the increase in system energy as a function of T.\n\nEventually the systems evolves into thermal equilibrium at temperature T ; then the formula mentioned before holds When equilibrium is reached, temperature T can be lowered and the process can be repeated.\n\n\n## Travelling Salesman Problem\n\nThe travelling salesman problem (TSP) asks the following question: Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city exactly once and returns to the origin city? It is an NP-hard problem in combinatorial optimization, important in operations research and theoretical computer science.\n\n\n\n\n\n## Self-Organizing Maps (SOM)\n\nA [self-organizing map (SOM)](https://en.wikipedia.org/wiki/Self-organizing_map) or self-organizing feature map (SOFM) is an artificial neural network (ANN) that is trained using unsupervised learning to produce a low-dimensional (typically two-dimensional), discretized representation of the input space of the training samples, called a map. This makes SOMs useful for visualizing low-dimensional views of high-dimensional data. In this sense, SOMs are similar to multidimensional scaling. Self-organizing maps with a small number of nodes behave in a way that is similar to K-means, larger self-organizing maps rearrange data in a way that is fundamentally topological in character.\n\n  \n*SOM Algorithm*  \n\n  \n*SOM Training*  \n\n### SOM neighborhood topology\n\n\n  \n*Square Grid Lattice SOM]* \n\n  \n*Hexoganal Honeycomb Lattice SOM]*  \n\nThe grids have an $x$ dimension and $y$ dimension. The topology of the grid is rectangular or hexagonal. \n\n### SOM neighborhood functions\n\nWhile the neighborhood function $\\theta(u, v, s)$ usually depends on the lattice distance between the BMU (neuron u) and neuron v. Other functions such as a [Gaussian function](https://en.wikipedia.org/wiki/Gaussian_function) or a radius distance centered around the neuron are also common choices.   \n\n### SOM Algorithm  \n\n\nA. Randomize the map's nodes' weight vectors. The weights of the neurons are initialized either to small random values or sampled evenly from the subspace spanned by the two largest principal component eigenvectors.   \n\nB.  Grab an input vector $\\mathbf{D(t)}$. $t$ is the index of the target input data vector in the input data set $\\mathbf{D}$ Each data point, $\\mathbf{D(t)}$, needs to be mapped to a \"neuron.\"\n\nC.  Traverse each node in the map. Use the Euclidean distance or another similarity metric between the input vector $\\mathbf{D(t)}$ and the map's node's weight vector. The node that produces the smallest distance (i.e. the best matching unit, BMU) is associated with that neuron.\n\nD. Update the nodes in the neighborhood of the BMU (including the BMU itself) by pulling them closer to the input vector. This is analogous to updating the new means to be the centroids of the observations in the new clusters the means in [k-means clustering](https://en.wikipedia.org/wiki/K-means_clustering). That is,\n\n$$\nWv(s + 1) = Wv(s) + \\theta(u, v, s) \t\\alpha(s)(D(t) - Wv(s))\n$$\n\nWhere\n\n* $s$ is the current iteration\n* $\\lambda$ is the iteration limit. Sometimes this is called the maximum number of 'epochs'\n* $v$ is the index of the node in the map\n* $\\mathbf{W_v}$ is the current weight vector of node v\n* $u$ is the index of the best matching unit (BMU) in the map\n* $\\Theta (u, v, s)$ is a restraint due to distance from BMU, usually called the neighborhood function,\n* $\\alpha (s)$ is a learning restraint due to iteration progress. Sometimes this is called the learning rate.\n\nE Increase $s$ and repeat from step B while $s < \\lambda$\n\nNote that the neighborhood function $\\Theta (u, v, s)$  depends on the lattice distance between the BMU (neuron u) and neuron v. In the simplest form it is 1 for all neurons close enough to BMU and 0 for others, but a Gaussian function is a common choice, too. Regardless of the functional form, the neighborhood function shrinks with time.  \n\nA variant algorithm:\n\nA. Randomize the map's nodes' weight vectors  \nB. Traverse each input vector in the input data set   \nC. Traverse each node in the map    \nD.  Use the Euclidean distance formula to find the similarity between the input vector and the map's node's weight vector\nE.  Track the node that produces the smallest distance (this node is the best matching unit, BMU)\nUpdate the nodes in the neighborhood of the BMU (including the BMU itself) by pulling them closer to the input vector\n$Wv(s + 1) = Wv(s) + \\theta(u, v, s) \\alpha(s)(D(t) - Wv(s))$\nF. Increase $s$ and repeat from step B while $s < \\lambda$\n\n\nThe kind of training is called *[competitive learning](https://en.wikipedia.org/wiki/Competitive_learning)* n which nodes compete for the right to respond to a subset of the input data.\n\n\n### SOM Usage\n\nUsing Self-Organising Maps are typcially done as follows:\n\nSelect the size and type of the map. The shape can be hexagonal or square. Note that hexagonal grid has six immediate neighbors whereas a square usually has four. This topology determines the number of \"neurons.\"\n\nThe algorithm then \n\nA. Initializes all node weight vectors.  \nB. Chooses a random data point from the training data to present to the SOM.  \nC. Finds the \"Best Matching Unit\" (BMU) in the map.\nDetermine the nodes within the \"neighborhood\" of the BMU.  \nD. The size of the neighborhood decreases with each iteration.  \nE. Adjust weights of nodes (neurons) in the BMU neighborhood  towards a chosen datapoint.\n- The learning rate decreases with each iteration.  \n- The magnitude of the adjustment is proportional to the proximity of the node to the BMU.  \n\n\nRepeat Steps B-E for a fixed number of iterations or until convergence.\n\n### SOM Pros and Cons  \n\nPros:\n\n* Intuitive method.  \n* Simple algorithm.    \n* New data points can be mapped to trained model for predictive purposes.   \n\nCons:\n\n* Requires clean, numeric data.  \n\n\n## SOM Visualization  \n\nThe Self-Organizing Maps projects high-dimensional data onto a two-dimensional map. The projection preserves the topology of the data so that similar data items will be mapped to nearby locations on the map. As such one of its great strengths is high-dimensional data visualization, akin to [multidimensional scaling (MDS)](https://en.wikipedia.org/wiki/Multidimensional_scaling).    \n\n### SOM Cluster Maps\n\n\n  \n*SOM Clusters*   \n- from [Self-Organising Maps for Customer Segmentation using R](http://www.r-bloggers.com/self-organising-maps-for-customer-segmentation-using-r/) via @rbloggers\n\n\n  \n*SOM Clusters with Labels*   \n- from [Self-Organising Maps for Customer Segmentation using R](http://www.r-bloggers.com/self-organising-maps-for-customer-segmentation-using-r/) via @rbloggers\n\n  \n*SOM Clusters on Map*    \n- from [Self-Organising Maps for Customer Segmentation using R](http://www.r-bloggers.com/self-organising-maps-for-customer-segmentation-using-r/) via @rbloggers\n### SOM Heatmaps\n\nA [heat map](https://en.wikipedia.org/wiki/Heat_map) is a graphical representation of data where a gradient of values are represented as colors.\n\n  \n*SOM Heatmap*   \n- from [Self-Organising Maps for Customer Segmentation using R](http://www.r-bloggers.com/self-organising-maps-for-customer-segmentation-using-r/) via @rbloggers\n\n\n## Data pipelines\n\nData Pipeline is an embedded data processing engine. The engine runs inside your applications, APIs, and jobs to filter, transform, and migrate data in an automated way.\n\n## SQL\n\nSQL (pronounced \"ess-que-el\") stands for Structured Query Language. SQL is used to communicate with a [relational database](https://en.wikipedia.org/wiki/Relational_database).  A relational database is a digital database whose organization is based on the relational model of data, as proposed by E. F. Codd in 1970. The various software systems used to maintain relational databases are known as a relational database management system (RDBMS). Virtually all relational database systems use SQL (Structured Query Language) as the language for querying and maintaining the database.\n\n## NoSQL\n\nA [NoSQL](https://en.wikipedia.org/wiki/NoSQL) (originally referring to \"non SQL\" or \"non relational\") database provides a mechanism for storage and retrieval of data that is modeled in means other than the tabular relations used in relational databases. \n\nMotivations for this approach include: simplicity of design, spped, simpler \"horizontal\" scaling to clusters of machines (which is a problem for relational databases), and finer control over availability. The data structures used by NoSQL databases (e.g. key-value, wide column, graph, or document) are different from those used by default in relational databases, making some operations faster in NoSQL. The particular suitability of a given NoSQL database depends on the problem it must solve.\n\n\n## MapReduce\n\n[MapReduce](https://en.wikipedia.org/wiki/MapReduce) is a programming model and an associated implementation for processing and generating big data sets with a parallel, distributed algorithm on a cluster.[\n\nA MapReduce program is composed of a Map() procedure (method) that performs filtering and sorting (such as sorting students by first name into queues, one queue for each name) and a Reduce() method that performs a summary operation (such as counting the number of students in each queue, yielding name frequencies). \n\nThe \"MapReduce System\" (also called \"infrastructure\" or \"framework\") orchestrates the processing by marshalling the distributed servers, running the various tasks in parallel, managing all communications and data transfers between the various parts of the system, and providing for redundancy and fault tolerance.\n\n## Neural Networks\n\nI highly recommend _Deep Learning - Adaptive Computation and Machine Learning series by Ian Goodfellow, Yoshua Bengio,\nand Aaron Courville_ [https://github.com/HFTrader/DeepLearningBook](\nhttps://github.com/HFTrader/DeepLearningBook)\n\n\nand\n\n[6.S191: Introduction to Deep Learning](http://introtodeeplearning.com/)\n\n### Neural Networks\n\n[Artificial neural networks (ANNs)](https://en.wikipedia.org/wiki/Artificial_neural_network) or connectionist systems are computing systems inspired by the biological neural networks that constitute animal brains.\n\n\n\n**Neural networks** consist of:\n\n_Input layer_\n\nNeurons that maps the input to a neural network.\n\n_Output layer_\n\nNeurons that maps the output to a neural network. Often converts to output to a probability.\n\n*\tSoftmax (If you want the outputs of a network to be interpretable as posterior probabilities.)\n*\tCros\n\n_Activation functions_\n\nThe [activation function](https://en.wikipedia.org/wiki/Activation_function) of a node defines the output of that node given an input or set of inputs.\n\n*\tRectified linear unit (ReLU)\n*\tTanH\n*\tLeaky rectified linear unit (Leaky ReLU)\n*\tParameteric rectified linear unit (PReLU)\n*\tRandomized leaky rectified linear unit (RReLU)\n*\tExponential linear unit (ELU)\n*\tScaled exponential linear unit (SELU)\n*\tS*shaped rectified linear activation unit (SReLU)\n*\tIdentity\n*\tBinary step\n*\tLogistic\n*\tArcTan\n*\tSoftsign\n*\tAdaptive piecewise linear (APL)\n*\tSoftPlus\n*\tSoftExponential\n*\tSinusoid\n*\tSinc\n*\tGaussian\n\n_Comparison of activation functions_\n\nSome desirable properties in an activation function include:\n* Nonlinear \u2013 When the activation function is non-linear, then a two-layer neural network can be proven to be a universal function approximator. The identity activation function does not satisfy this property. When multiple layers use the identity activation function, the entire network is equivalent to a single-layer model.  \n* Continuously differentiable \u2013 This property is necessary for enabling gradient-based optimization methods. The binary step activation function is not differentiable at 0, and it differentiates to 0 for all other values, so gradient-based methods can make no progress with it.  \n* Range \u2013 When the range of the activation function is finite, gradient-based training methods tend to be more stable, because pattern presentations significantly affect only limited weights. When the range is infinite, training is generally more efficient because pattern presentations significantly affect most of the weights. In the latter case, smaller learning rates are typically necessary.  \n* Monotonic \u2013 When the activation function is monotonic, the error surface associated with a single-layer model is guaranteed to be convex.\n* Smooth Functions with a Monotonic derivative \u2013 These have been shown to generalize better in some cases. The argument for these properties suggests that such activation functions are more consistent with Occam's razor.  \n* Approximates identity near the origin \u2013 When activation functions have this property, the neural network will learn efficiently when its weights are initialized with small random values. When the activation function does not approximate identity near the origin, special care must be used when initializing the weights.  \n\n_Objective function (cost function or loss function)_\n\nThe objective function estimates the error. (Is minimized during training)\n\n*\tQuadratic cost (mean*square error)\n*\tCross*Entropy\n\n_Back-Propagation_\n\n[Backpropagation](https://en.wikipedia.org/wiki/Backpropagation) is a method used in artificial neural networks to calculate the error contribution of each neuron after a batch of data. This is used by an enveloping optimization algorithm to adjust the weight of each neuron, completing the learning process for that case.\n\nTechnically it calculates the gradient of the loss function. It is commonly used in the gradient descent optimization algorithm. It is also called backward propagation of errors, because the error is calculated at the output and distributed back through the network layers.\n\n_Epochs_\n\nOne epoch = one forward pass and one backward pass. \n\n*\tnumber of epochs\n\n_Gradient estimation_\n\n*\tstochastic gradient descent\n*\tAdagrad\n*\tRMSProp\n*\tADAM\n*\tNAG\n*\tAdadelta\n*\tMomentum\n\n_Batch size_\n\nbatch size = the number of training examples in one forward/backward pass. It's much faster to estimate the gradient on a sample than to calculate it over the entire data set.\n\n_Batch normalization_\n\nNormalization (shifting inputs to zero-mean and unit variance) is often used as a pre-processing step to make the data comparable across features. \n\nBecause a multiplies across the weights over each layer this can change the distribution. This is called _internal covariate shift._ As the data flows through a deep network, the weights and parameters adjust those values, sometimes making the data too big or too small again.\n\nInternal covariate shift refers to the change in the input distribution to a learning system. In the case of deep networks, the input to each layer is affected by parameters in all the input layers.\n\nRather than just performing normalization once in the beginning, you're doing it through the process. \n\n_Regularization_\n\n*\tL1\n*\tL2\n*\tDrop out\n\n\n### Shallow Neural Networks\n\n_Shallow Neural Networks_ refers to neural networks with few hidden layers. \n\n### Deep Learning\n\n_Deep Learning_\n\nDeep feedforward networks feedforward , also often called neural networks, or multilayer perceptrons (MLPs), are the quintessential deep learning models. The goal of a feedforward network is to approximate some function $f(x)$.\n\nEarlier challenges in training deep neural networks were successfully addressed with methods such as unsupervised pre-training, while available computing power increased through the use of GPUs and distributed computing. Neural networks were deployed on a large scale, particularly in image and visual recognition problems. This became known as \"deep learning\", although deep learning is not strictly synonymous with deep neural networks it often refers to th neural networks with many hidden layers. \n\n### Convolutional Networks\n\nA convolutional networks (CNN) consists of an input and an output layer, as well as multiple hidden layers. The hidden layers are either convolutional, pooling or fully connected.\n\nConvolutional layers apply a convolution operation to the input, passing the result to the next layer. The convolution emulates the response of an individual neuron to visual stimuli.\n\nEach convolutional neuron processes data only for its receptive field. Tiling allows CNNs to tolerate translation of the input image (eg. translation, rotation, perspective distortion).\n\nAlthough fully connected feedforward neural networks can be used to learn features as well as classify data, it is not practical to apply this architecture to images. A very high number of neurons would be necessary even in a shallow architecture (opposite of deep). The convolution operation brings a solution to this problem as it reduces the number of free parameters, allowing the network to be deeper with many fewer parameters. In other words, it resolves the vanishing or exploding problems in training traditional multi-layer neural networks with many layers by using backpropagation.\n\n### Sequence Modeling: Recursive neural networks\n\n[Recursive neural networks (RNNs)](https://en.wikipedia.org/wiki/Recursive_neural_network) is a kind of deep neural network created by applying the same set of weights recursively over a structure, to produce a structured prediction over variable-size input structures, or a scalar prediction on it, by traversing a given structure in topological order. RNNs have been successful for instance in learning sequence and tree structures in natural language processing, mainly phrase and sentence continuous representations based on word embedding. RNNs have first been introduced to learn distributed representations of structure, such as logical terms.\n\n\n### Autoencoders\n\nAn autoencoder, autoassociator or Diabolo network is an artificial neural network used for unsupervised learning of efficient codings. The aim of an autoencoder is to learn a representation (encoding) for a set of data, typically for the purpose of dimensionality reduction.\n\nAutoencoder\u2019s though are difficult to interpret of the representation of semantics and aren\u2019t really a generative model.\n\nAutoencoder\ni.\tencoder and dencoder  \nii.\thidden layers\niii.\tbottleneck layer - forces network to learn a compressed latent representation\niv.\treconstruction loss  - forces hidden layer to represent info about the input\n)\n\n### Variational autoencoders (VAEs)\n\nVariational autoencoders are a stochastic variational extension of autoencoders  that allow for a probabilistic representation of the data and amortized inference.\n\nIn a VAE, the encoder becomes a variational inference network that maps the data to the a distribution for the hidden variables, and the decoder becomes a generative network that maps the latent variables back to the data. In just a couple of years, Variational Autoencoders (VAEs) have emerged as one of the most popular approaches to unsupervised learning of complicated distributions.\n\nVariational Autoencoders (VAEs) have some very desirable properties:\n\ni.\tClear semantics as a generative model\nii.\tExtension of autoencoders that allow sampling and estimating probabilities.\niii.\tThis creates a kind of implicit generative model it creates a latent representation thru its probabilities\niv.\t\"Latent variables\" has a fixed prior distribution\nv.\tProbabilistic encoder and dencoder\nvi.\tProbabilistic representation of the data\n\nVariational autoencoders have a clear advantage over autoencoders in that the probabilistic representation of the data is a form of representation learning.\n\n\n_Autoregresstive variational autoencoders_\n\nStandard VAE\u2019s have some issues:\ni.\tThey do not encode what is not useful for them to decode.  This means they don't capture fine details. Subtle features (e.g. small nodules that may be important clinically but don\u2019t represent much of the image space may be missed.)\n\n\nAutoregresstive VAE\u2019s use autoregresstive networks in the encoder and the dencoder to capture more local info in the estimation of the densities.\n\n\n\n### Restricted Boltzmann machines (RBMs)\n\nRestricted Boltzmann machines (RBM)s are a very simple model, just a fully connected bipartite graph with an input layer and a hidden layer. The cost function minimizes an energy function by re-weighting to minimize the difference between the input layer and the hidden layer.\n\n\nLike VAE\u2019s restricted Boltzmann machines can be thought as a form of representation learning.\n\nRestricted Boltzmann machines:\ni.\tClear semantics as a generative model\nii.\tSimple, just a fully connected bipartite graph with an input layer and a hidden layer.\niii.\tMinimizes an energy function (re-weighting to minimize the difference between the input layer and the hidden layer).\niv.\tEnergies can easily be converted to probabilities.\nv.\tCreates a latent representation thru its probabilities.\n\n\n### Deep Generative Models\n\nDeep Generative Models collect a large amount of data in some domain (e.g., think millions of images, sentences, or sounds, etc.) and then train a model to generate data like it. \n\n\nLast update September 5, 2017\n", "meta": {"hexsha": "82ec5715ecaca2899a1e4032def1d4eaaed57685", "size": 347199, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Week_1/NBB_Big Data and Data Science.ipynb", "max_stars_repo_name": "Chau-Xochitl/INFO_7390", "max_stars_repo_head_hexsha": "3ab4a3bf7af5c0b57d9604def26d64dc31405333", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Week_1/NBB_Big Data and Data Science.ipynb", "max_issues_repo_name": "Chau-Xochitl/INFO_7390", "max_issues_repo_head_hexsha": "3ab4a3bf7af5c0b57d9604def26d64dc31405333", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week_1/NBB_Big Data and Data Science.ipynb", "max_forks_repo_name": "Chau-Xochitl/INFO_7390", "max_forks_repo_head_hexsha": "3ab4a3bf7af5c0b57d9604def26d64dc31405333", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-02T06:48:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-02T06:48:30.000Z", "avg_line_length": 104.3579801623, "max_line_length": 134244, "alphanum_fraction": 0.7761571894, "converted": true, "num_tokens": 42176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.26588047309981694, "lm_q2_score": 0.13660838651113866, "lm_q1q2_score": 0.0363215024349842}}
{"text": "# SQL \u5165\u9580\n\n> \u57fa\u672c\u67e5\u8a62\n\n\u90ed\u8000\u4ec1\n\n\n```python\n# \u9023\u7d50\u8cc7\u6599\u5eab\nimport sqlite3\nimport pandas as pd\nfrom test_queries.test_queries_02 import extract_test_queries as etq\n\nconn_twelection = sqlite3.connect('twelection.db')\nconn_nba = sqlite3.connect('nba.db')\n```\n\n## \u6458\u8981\n\n- SQL \u98a8\u683c\u6307\u5357\n- \u8cc7\u6599\u578b\u614b\n- \u5ef6\u7e8c `SELECT` \u548c `FROM`\n- \u96a8\u5802\u7df4\u7fd2\n- \u96a8\u5802\u7df4\u7fd2\u53c3\u8003\u89e3\u7b54\n\n## SQL \u98a8\u683c\u6307\u5357\n\n## \u4ec0\u9ebc\u662f\u98a8\u683c\u6307\u5357\n\n> \u7a0b\u5f0f\u8a9e\u8a00\u7684\u98a8\u683c\u6307\u5357\u662f\u4e00\u4efd\u63cf\u8ff0\u5728\u64b0\u5beb\u6307\u5b9a\u7a0b\u5f0f\u8a9e\u8a00\u98a8\u683c\u898f\u7bc4\u7684\u6587\u4ef6\uff0c\u98a8\u683c\u6307\u5357\u6703\u96a8\u8457\u8a9e\u8a00\u3001\u5718\u968a\u7fd2\u6163\u7684\u4e0d\u540c\uff0c\u800c\u6709\u4e0d\u540c\u7684\u5f62\u5f0f\u8207\u5167\u6db5\u3002\n\n## \u70ba\u4ec0\u9ebc\u98a8\u683c\u6307\u5357\n\n> \u4e00\u500b\u88ab\u90e8\u7f72\u5728\u6b63\u5f0f\u74b0\u5883\u7684\u61c9\u7528\u7a0b\u5f0f\u61c9\u8a72\u8981\u770b\u8d77\u4f86\u50cf\u662f\u7531\u4e00\u4f4d\u8edf\u9ad4\u5de5\u7a0b\u5e2b\u6240\u64b0\u5beb\u51fa\u4f86\u7684\uff0c\u5373\u4fbf\u662f\u7531\u6578\u767e\u540d\u8edf\u9ad4\u5de5\u7a0b\u5e2b\u5408\u529b\u64b0\u5beb\u3002\u9019\u6a23\u7684\u7a0b\u5f0f\u539f\u59cb\u78bc\u80fd\u88ab\u66f4\u826f\u597d\u5730\u7dad\u8b77\u3001\u6e1b\u5c11\u6e9d\u901a\u4e0d\u6548\u7387\u4e26\u964d\u4f4e\u7cfb\u7d71\u51fa\u932f\u7684\u98a8\u96aa\u3002\n\n## \u5982\u679c\u5c0d\u98a8\u683c\u6307\u5357\u4e0d\u6eff\u610f\u8a72\u600e\u9ebc\u8fa6\u624d\u597d\n\n> \u5047\u5982\u525b\u52a0\u5165\u5718\u968a\u6642\u767c\u73fe\u5c0d\u65bc\u98a8\u683c\u6307\u5357\u4e0d\u751a\u6eff\u610f\uff0c\u8acb\u5148\u4fdd\u6301\u975c\u9ed8\uff0c\u7b49\u5230\u904e\u4e86\u4e00\u6bb5\u6642\u9593\u5728\u5718\u968a\u4e2d\u5df2\u7d93\u5efa\u7acb\u7684\u8072\u8b7d\u548c\u4fe1\u8cf4\u611f\uff0c\u518d\u91dd\u5c0d\u5177\u6709\u300c\u660e\u986f\u6548\u76ca\u300d\u7684\u98a8\u683c\u6307\u5357\u63d0\u51fa\u5efa\u8b70\u3002\n\n## \u300c\u666e\u904d\u300d\u7684 SQL \u98a8\u683c\u6307\u5357\n\n\n\nSource: <https://giphy.com/>\n\n## \u8ab2\u7a0b\u5c07\u63a1\u7528 [Simon Holywell](https://www.simonholywell.com/) \u7684 SQL \u98a8\u683c\u6307\u5357\n\nSource: <https://www.sqlstyle.guide/>\n\n## \u5efa\u8b70\u9075\u5b88\u7684\u90e8\u5206\n\n- \u5584\u7528\u300c\u7a7a\u767d\u300d\u8207\u300c\u7e2e\u6392\u300d\u63d0\u5347\u53ef\u8b80\u6027\n- \u4f7f\u7528 ISO-8601 \u7684\u65e5\u671f\u6642\u9593\u683c\u5f0f `YYYY-MM-DD HH:MM:SS.SSSSS`\n- \u70ba\u4e86\u79fb\u690d\u4fbf\u5229\u6027\uff0c\u76e1\u53ef\u80fd\u4f7f\u7528\u6a19\u6e96 SQL \u800c\u975e\u7279\u5b9a DBMS \u7684\u529f\u80fd\u6216\u51fd\u5f0f\n- \u5584\u7528\u8a3b\u89e3\n    - `/**/` \u7528\u4f86\u505a\u591a\u884c\u8a3b\u89e3\n    - `--` \u7528\u4f86\u505a\u55ae\u884c\u8a3b\u89e3\n\n\n\nSource: Google Search\n\n## \u547d\u540d\u7684\u539f\u5247\n\n- \u7531\u82f1\u6587\u5b57\u6bcd\u8d77\u59cb\u4e26\u4e14\u4e0d\u8981\u4ee5\u5e95\u7dda `_` \u7d42\u7d50\n- \u4e0d\u5f97\u4f7f\u7528\u4fdd\u7559\u5b57\n- \u4f7f\u7528\u82f1\u6587\u5b57\u6bcd\u8207\u6578\u5b57\uff0c\u4e26\u4e14\u4ee5\u5e95\u7dda `_` \u5206\u9694\u55ae\u5b57\n- \u4e0d\u8981\u4f7f\u7528\u591a\u500b\u5e95\u7dda\u4f8b\u5982 `__`\n- \u76e1\u91cf\u53ea\u4f7f\u7528\u5f88\u76f4\u89c0\u7684\u7e2e\u5beb\u4f5c\u70ba\u547d\u540d\n\n## \u6a19\u6e96 SQL \u7684\u4fdd\u7559\u5b57\u6709\u54ea\u4e9b\n\n<https://www.w3schools.com/sql/sql_ref_keywords.asp>\n\nSource: <https://www.w3schools.com/>\n\n## \u4ee5\u5168\u5927\u5beb\u4f86\u64b0\u5beb\u4fdd\u7559\u5b57\uff1a`SELECT * FROM table_name`\n\n## \u9700\u8981\u63db\u884c\u7684\u6642\u5019\u63a1\u300c\u9760\u53f3\u5c0d\u9f4a\u300d\n\n\n```python\nsql_query = \"\"\"\nSELECT *\n  FROM teams\n WHERE confName = 'East';\n\"\"\"\n```\n\n\n```python\npd.read_sql(sql_query, conn_nba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>isNBAFranchise</th>\n      <th>isAllStar</th>\n      <th>city</th>\n      <th>altCityName</th>\n      <th>fullName</th>\n      <th>tricode</th>\n      <th>teamId</th>\n      <th>nickname</th>\n      <th>urlName</th>\n      <th>teamShortName</th>\n      <th>confName</th>\n      <th>divName</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Atlanta</td>\n      <td>Atlanta</td>\n      <td>Atlanta Hawks</td>\n      <td>ATL</td>\n      <td>1610612737</td>\n      <td>Hawks</td>\n      <td>hawks</td>\n      <td>Atlanta</td>\n      <td>East</td>\n      <td>Southeast</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Boston</td>\n      <td>Boston</td>\n      <td>Boston Celtics</td>\n      <td>BOS</td>\n      <td>1610612738</td>\n      <td>Celtics</td>\n      <td>celtics</td>\n      <td>Boston</td>\n      <td>East</td>\n      <td>Atlantic</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Cleveland</td>\n      <td>Cleveland</td>\n      <td>Cleveland Cavaliers</td>\n      <td>CLE</td>\n      <td>1610612739</td>\n      <td>Cavaliers</td>\n      <td>cavaliers</td>\n      <td>Cleveland</td>\n      <td>East</td>\n      <td>Central</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Chicago</td>\n      <td>Chicago</td>\n      <td>Chicago Bulls</td>\n      <td>CHI</td>\n      <td>1610612741</td>\n      <td>Bulls</td>\n      <td>bulls</td>\n      <td>Chicago</td>\n      <td>East</td>\n      <td>Central</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Miami</td>\n      <td>Miami</td>\n      <td>Miami Heat</td>\n      <td>MIA</td>\n      <td>1610612748</td>\n      <td>Heat</td>\n      <td>heat</td>\n      <td>Miami</td>\n      <td>East</td>\n      <td>Southeast</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Milwaukee</td>\n      <td>Milwaukee</td>\n      <td>Milwaukee Bucks</td>\n      <td>MIL</td>\n      <td>1610612749</td>\n      <td>Bucks</td>\n      <td>bucks</td>\n      <td>Milwaukee</td>\n      <td>East</td>\n      <td>Central</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Brooklyn</td>\n      <td>Brooklyn</td>\n      <td>Brooklyn Nets</td>\n      <td>BKN</td>\n      <td>1610612751</td>\n      <td>Nets</td>\n      <td>nets</td>\n      <td>Brooklyn</td>\n      <td>East</td>\n      <td>Atlantic</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>True</td>\n      <td>False</td>\n      <td>New York</td>\n      <td>New York</td>\n      <td>New York Knicks</td>\n      <td>NYK</td>\n      <td>1610612752</td>\n      <td>Knicks</td>\n      <td>knicks</td>\n      <td>New York</td>\n      <td>East</td>\n      <td>Atlantic</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Orlando</td>\n      <td>Orlando</td>\n      <td>Orlando Magic</td>\n      <td>ORL</td>\n      <td>1610612753</td>\n      <td>Magic</td>\n      <td>magic</td>\n      <td>Orlando</td>\n      <td>East</td>\n      <td>Southeast</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Indiana</td>\n      <td>Indiana</td>\n      <td>Indiana Pacers</td>\n      <td>IND</td>\n      <td>1610612754</td>\n      <td>Pacers</td>\n      <td>pacers</td>\n      <td>Indiana</td>\n      <td>East</td>\n      <td>Central</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Philadelphia</td>\n      <td>Philadelphia</td>\n      <td>Philadelphia 76ers</td>\n      <td>PHI</td>\n      <td>1610612755</td>\n      <td>76ers</td>\n      <td>sixers</td>\n      <td>Philadelphia</td>\n      <td>East</td>\n      <td>Atlantic</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Toronto</td>\n      <td>Toronto</td>\n      <td>Toronto Raptors</td>\n      <td>TOR</td>\n      <td>1610612761</td>\n      <td>Raptors</td>\n      <td>raptors</td>\n      <td>Toronto</td>\n      <td>East</td>\n      <td>Atlantic</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Washington</td>\n      <td>Washington</td>\n      <td>Washington Wizards</td>\n      <td>WAS</td>\n      <td>1610612764</td>\n      <td>Wizards</td>\n      <td>wizards</td>\n      <td>Washington</td>\n      <td>East</td>\n      <td>Southeast</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Detroit</td>\n      <td>Detroit</td>\n      <td>Detroit Pistons</td>\n      <td>DET</td>\n      <td>1610612765</td>\n      <td>Pistons</td>\n      <td>pistons</td>\n      <td>Detroit</td>\n      <td>East</td>\n      <td>Central</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Charlotte</td>\n      <td>Charlotte</td>\n      <td>Charlotte Hornets</td>\n      <td>CHA</td>\n      <td>1610612766</td>\n      <td>Hornets</td>\n      <td>hornets</td>\n      <td>Charlotte</td>\n      <td>East</td>\n      <td>Southeast</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## \u4f55\u6642\u52a0\u5165\u7a7a\u767d\n\n- \u5728 `=` \u7684\u524d\u5f8c\n- \u5728 `,` \u4e4b\u5f8c\n\n\n```python\nsql_query = \"\"\"\nSELECT *\n  FROM teams\n WHERE divName IN ('Atlantic', 'Southeast');\n\"\"\"\n```\n\n\n```python\npd.read_sql(sql_query, conn_nba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>isNBAFranchise</th>\n      <th>isAllStar</th>\n      <th>city</th>\n      <th>altCityName</th>\n      <th>fullName</th>\n      <th>tricode</th>\n      <th>teamId</th>\n      <th>nickname</th>\n      <th>urlName</th>\n      <th>teamShortName</th>\n      <th>confName</th>\n      <th>divName</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Atlanta</td>\n      <td>Atlanta</td>\n      <td>Atlanta Hawks</td>\n      <td>ATL</td>\n      <td>1610612737</td>\n      <td>Hawks</td>\n      <td>hawks</td>\n      <td>Atlanta</td>\n      <td>East</td>\n      <td>Southeast</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Boston</td>\n      <td>Boston</td>\n      <td>Boston Celtics</td>\n      <td>BOS</td>\n      <td>1610612738</td>\n      <td>Celtics</td>\n      <td>celtics</td>\n      <td>Boston</td>\n      <td>East</td>\n      <td>Atlantic</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Miami</td>\n      <td>Miami</td>\n      <td>Miami Heat</td>\n      <td>MIA</td>\n      <td>1610612748</td>\n      <td>Heat</td>\n      <td>heat</td>\n      <td>Miami</td>\n      <td>East</td>\n      <td>Southeast</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Brooklyn</td>\n      <td>Brooklyn</td>\n      <td>Brooklyn Nets</td>\n      <td>BKN</td>\n      <td>1610612751</td>\n      <td>Nets</td>\n      <td>nets</td>\n      <td>Brooklyn</td>\n      <td>East</td>\n      <td>Atlantic</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>True</td>\n      <td>False</td>\n      <td>New York</td>\n      <td>New York</td>\n      <td>New York Knicks</td>\n      <td>NYK</td>\n      <td>1610612752</td>\n      <td>Knicks</td>\n      <td>knicks</td>\n      <td>New York</td>\n      <td>East</td>\n      <td>Atlantic</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Orlando</td>\n      <td>Orlando</td>\n      <td>Orlando Magic</td>\n      <td>ORL</td>\n      <td>1610612753</td>\n      <td>Magic</td>\n      <td>magic</td>\n      <td>Orlando</td>\n      <td>East</td>\n      <td>Southeast</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Philadelphia</td>\n      <td>Philadelphia</td>\n      <td>Philadelphia 76ers</td>\n      <td>PHI</td>\n      <td>1610612755</td>\n      <td>76ers</td>\n      <td>sixers</td>\n      <td>Philadelphia</td>\n      <td>East</td>\n      <td>Atlantic</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Toronto</td>\n      <td>Toronto</td>\n      <td>Toronto Raptors</td>\n      <td>TOR</td>\n      <td>1610612761</td>\n      <td>Raptors</td>\n      <td>raptors</td>\n      <td>Toronto</td>\n      <td>East</td>\n      <td>Atlantic</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Washington</td>\n      <td>Washington</td>\n      <td>Washington Wizards</td>\n      <td>WAS</td>\n      <td>1610612764</td>\n      <td>Wizards</td>\n      <td>wizards</td>\n      <td>Washington</td>\n      <td>East</td>\n      <td>Southeast</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>True</td>\n      <td>False</td>\n      <td>Charlotte</td>\n      <td>Charlotte</td>\n      <td>Charlotte Hornets</td>\n      <td>CHA</td>\n      <td>1610612766</td>\n      <td>Hornets</td>\n      <td>hornets</td>\n      <td>Charlotte</td>\n      <td>East</td>\n      <td>Southeast</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## \u547d\u540d\u8207\u5225\u540d\n\n- \u8868\u683c\u7684\u547d\u540d\u4ee5\u300c\u8907\u6578\u300d\u540d\u8a5e\u70ba\u4e3b\n- \u8b8a\u6578\u7684\u547d\u540d\u4ee5\u300c\u55ae\u6578\u300d\u540d\u8a5e\u70ba\u4e3b\n- \u5efa\u7acb\u5225\u540d\u6642\u7528 `AS`\n\n\n```python\nsql_query = \"\"\"\nSELECT fullName AS team_name\n  FROM teams\n LIMIT 5;\n\"\"\"\n```\n\n\n```python\npd.read_sql(sql_query, conn_nba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>team_name</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Atlanta Hawks</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Boston Celtics</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Cleveland Cavaliers</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>New Orleans Pelicans</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Chicago Bulls</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## \u8cc7\u6599\u578b\u614b\n\n## \u4f7f\u7528 `PRAGMA TABLE_INFO(table_name)` \u66b8\u89e3\u8868\u683c\u7684\u8cc7\u6599\u578b\u614b\n\n\u6ce8\u610f\uff0c\u9019\u662f SQLite \u8cc7\u6599\u5eab\u7cfb\u7d71\u5c08\u5c6c\u7684\u8a9e\u6cd5\uff0c\u4e0d\u540c\u7684\u8cc7\u6599\u5eab\u7cfb\u7d71\u5177\u6709\u81ea\u5df1\u8a9e\u6cd5\u3002\n\n\n```python\nsql_query = \"\"\"\nPRAGMA TABLE_INFO(careerSummaries);\n\"\"\"\n```\n\n\n```python\npd.read_sql(sql_query, conn_nba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>cid</th>\n      <th>name</th>\n      <th>type</th>\n      <th>notnull</th>\n      <th>dflt_value</th>\n      <th>pk</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0</td>\n      <td>personId</td>\n      <td>INTEGER</td>\n      <td>0</td>\n      <td>None</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>tpp</td>\n      <td>REAL</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2</td>\n      <td>ftp</td>\n      <td>REAL</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>3</td>\n      <td>fgp</td>\n      <td>REAL</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>4</td>\n      <td>ppg</td>\n      <td>REAL</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>5</td>\n      <td>rpg</td>\n      <td>REAL</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>6</td>\n      <td>apg</td>\n      <td>REAL</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>7</td>\n      <td>bpg</td>\n      <td>REAL</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>8</td>\n      <td>mpg</td>\n      <td>REAL</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>9</td>\n      <td>spg</td>\n      <td>REAL</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>10</td>\n      <td>assists</td>\n      <td>INTEGER</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>11</td>\n      <td>blocks</td>\n      <td>INTEGER</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>12</td>\n      <td>steals</td>\n      <td>INTEGER</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>13</td>\n      <td>turnovers</td>\n      <td>INTEGER</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>14</td>\n      <td>offReb</td>\n      <td>INTEGER</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>15</td>\n      <td>defReb</td>\n      <td>INTEGER</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>16</td>\n      <td>totReb</td>\n      <td>INTEGER</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>17</td>\n      <td>fgm</td>\n      <td>REAL</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>18</td>\n      <td>fga</td>\n      <td>REAL</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>19</td>\n      <td>tpm</td>\n      <td>REAL</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>20</td>\n      <td>tpa</td>\n      <td>REAL</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>21</td>\n      <td>ftm</td>\n      <td>REAL</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>22</td>\n      <td>fta</td>\n      <td>REAL</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>23</td>\n      <td>pFouls</td>\n      <td>REAL</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>24</td>\n      <td>points</td>\n      <td>INTEGER</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>25</td>\n      <td>gamesPlayed</td>\n      <td>INTEGER</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>26</td>\n      <td>gamesStarted</td>\n      <td>INTEGER</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>27</td>\n      <td>plusMinus</td>\n      <td>REAL</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>28</td>\n      <td>min</td>\n      <td>REAL</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>29</td>\n      <td>dd2</td>\n      <td>REAL</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>30</th>\n      <td>30</td>\n      <td>td3</td>\n      <td>REAL</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## \u4f7f\u7528 `TYPEOF()` \u51fd\u5f0f\u66b8\u89e3\u6b04\u4f4d\u7684\u8cc7\u6599\u578b\u614b\n\n\u6ce8\u610f\uff0c\u9019\u662f SQLite \u8cc7\u6599\u5eab\u7cfb\u7d71\u5c08\u5c6c\u7684\u51fd\u5f0f\uff0c\u4e0d\u540c\u7684\u8cc7\u6599\u5eab\u7cfb\u7d71\u5177\u6709\u81ea\u5df1\u7684\u5c0d\u61c9\u51fd\u5f0f\u3002\n\n\n```python\nsql_query = \"\"\"\nSELECT TYPEOF(points) AS points_dt,\n       TYPEOF(ppg) AS ppg_dt\n  FROM careerSummaries\n LIMIT 1;\n\"\"\"\npd.read_sql(sql_query, conn_nba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>points_dt</th>\n      <th>ppg_dt</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>integer</td>\n      <td>real</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## \u8cc7\u6599\u578b\u614b\u7684\u5206\u985e\u7531\u8cc7\u6599\u5eab\u7cfb\u7d71\u6c7a\u5b9a\uff0c\u4f46\u5927\u81f4\u90fd\u6709\u5c0d\u61c9\u9019\u4e9b\u578b\u614b\n\n- \u6578\u503c\n- \u6587\u5b57\n- \u907a\u6f0f\u503c\n- \u5e03\u6797\n- \u65e5\u671f\u8207\u6642\u9593\n\n## \u4f7f\u7528 `CAST(column_name AS data_type)` \u5728\u67e5\u8a62\u6642\u8f49\u63db\u6b04\u4f4d\u7684\u8cc7\u6599\u578b\u614b\n\n\n```python\nsql_query = \"\"\"\nSELECT TYPEOF(points) AS points_int,\n       TYPEOF(CAST(points AS REAL)) AS points_real\n  FROM careerSummaries\n LIMIT 1;\n\"\"\"\npd.read_sql(sql_query, conn_nba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>points_int</th>\n      <th>points_real</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>integer</td>\n      <td>real</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## \u67e5\u8a62\u7279\u5b9a\u8cc7\u6599\u5eab\u7cfb\u7d71\u7684\u8cc7\u6599\u578b\u614b\n\n<https://www.sqlite.org/datatype3.html>\n\nSource: <https://www.sqlite.org/>\n\n## \u4e0d\u540c\u8cc7\u6599\u578b\u614b\u80fd\u5920\u5c0d\u61c9\u5404\u81ea\u7684\u904b\u7b97\u7b26\n\n- \u6587\u5b57\u53ef\u4ee5\u4f7f\u7528 `||` \u904b\u7b97\u7b26\u505a\u9023\u7d50\n- \u6578\u503c\u53ef\u4ee5\u4f7f\u7528 `+`, `-`, `*`, `/`, `%`\n\n\n```python\nsql_query = \"\"\"\nSELECT firstName || \" \" || lastName AS full_name\n  FROM players;\n\"\"\"\n```\n\n\n```python\npd.read_sql(sql_query, conn_nba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>full_name</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Vince Carter</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Tyson Chandler</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>LeBron James</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Carmelo Anthony</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Kyle Korver</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>499</th>\n      <td>Matt Thomas</td>\n    </tr>\n    <tr>\n      <th>500</th>\n      <td>Tariq Owens</td>\n    </tr>\n    <tr>\n      <th>501</th>\n      <td>Javonte Green</td>\n    </tr>\n    <tr>\n      <th>502</th>\n      <td>Juwan Morgan</td>\n    </tr>\n    <tr>\n      <th>503</th>\n      <td>Matt Mooney</td>\n    </tr>\n  </tbody>\n</table>\n<p>504 rows \u00d7 1 columns</p>\n</div>\n\n\n\n## \u6578\u503c\u904b\u7b97\u7b26\u7684\u8a08\u7b97\u9806\u5e8f\n\n1. \u5c0f\u62ec\u865f\n2. \u6b21\u65b9\u8207\u6839\u865f\n3. \u4e58\u6cd5\u3001\u9664\u6cd5\u8207\u9918\u6578\n4. \u52a0\u6cd5\u8207\u6e1b\u6cd5\n\n## \u4f8b\u5982\u8a08\u7b97\u8eab\u9ad4\u8cea\u91cf\u6307\u6578\uff08BMI\uff09\u7684\u516c\u5f0f\n\n\\begin{equation}\nBMI = \\frac{weight_{kg}}{height_m^{2}}\n\\end{equation}\n\n\n```python\nsql_query = \"\"\"\nSELECT firstName,\n       lastName,\n       weightKilograms / (heightMeters*heightMeters) AS bmi\n  FROM players\n LIMIT 10;\n\"\"\"\n```\n\n\n```python\npd.read_sql(sql_query, conn_nba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>firstName</th>\n      <th>lastName</th>\n      <th>bmi</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Vince</td>\n      <td>Carter</td>\n      <td>25.456586</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Tyson</td>\n      <td>Chandler</td>\n      <td>23.496220</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>LeBron</td>\n      <td>James</td>\n      <td>26.722594</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Carmelo</td>\n      <td>Anthony</td>\n      <td>26.207867</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Kyle</td>\n      <td>Korver</td>\n      <td>23.811292</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>Udonis</td>\n      <td>Haslem</td>\n      <td>25.868136</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Dwight</td>\n      <td>Howard</td>\n      <td>27.782914</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Andre</td>\n      <td>Iguodala</td>\n      <td>24.869911</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>JR</td>\n      <td>Smith</td>\n      <td>25.456586</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>Trevor</td>\n      <td>Ariza</td>\n      <td>23.659880</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## SQLite \u7684\u5e38\u7528\u51fd\u5f0f\n\n<https://www.sqlitetutorial.net/sqlite-functions/>\n\nSource: <https://www.sqlitetutorial.net/>\n\n## \u5ef6\u7e8c `SELECT` \u548c `FROM`\n\n## \u4f7f\u7528 `ORDER BY` \u6392\u5e8f\u67e5\u8a62\u7d50\u679c\n\n- \u9810\u8a2d\u905e\u589e\uff08`ASC`\uff09\u6392\u5e8f\uff0c\u4e0d\u9700\u8981\u6307\u5b9a\n- \u905e\u6e1b\uff08`DESC`\uff09\u6392\u5e8f\u8981\u6307\u5b9a\n\n\n```python\nsql_query = \"\"\"\nSELECT personId,\n       points\n  FROM careerSummaries\n ORDER BY points;\n\"\"\"\n```\n\n\n```python\npd.read_sql(sql_query, conn_nba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>personId</th>\n      <th>points</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1629007</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1629624</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1629626</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1629685</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1629719</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>499</th>\n      <td>201935</td>\n      <td>20723.0</td>\n    </tr>\n    <tr>\n      <th>500</th>\n      <td>201142</td>\n      <td>22940.0</td>\n    </tr>\n    <tr>\n      <th>501</th>\n      <td>1713</td>\n      <td>25728.0</td>\n    </tr>\n    <tr>\n      <th>502</th>\n      <td>2546</td>\n      <td>26314.0</td>\n    </tr>\n    <tr>\n      <th>503</th>\n      <td>2544</td>\n      <td>34087.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>504 rows \u00d7 2 columns</p>\n</div>\n\n\n\n\n```python\nsql_query = \"\"\"\nSELECT personId,\n       points\n  FROM careerSummaries\n ORDER BY points DESC;\n\"\"\"\npd.read_sql(sql_query, conn_nba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>personId</th>\n      <th>points</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>2544</td>\n      <td>34087.0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2546</td>\n      <td>26314.0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1713</td>\n      <td>25728.0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>201142</td>\n      <td>22940.0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>201935</td>\n      <td>20723.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>499</th>\n      <td>1629624</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>500</th>\n      <td>1629626</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>501</th>\n      <td>1629685</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>502</th>\n      <td>1629719</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>503</th>\n      <td>1629734</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n<p>504 rows \u00d7 2 columns</p>\n</div>\n\n\n\n## \u6392\u5e8f\u4e26\u4e0d\u50c5\u9650\u65bc\u4e00\u500b\u8b8a\u6578\n\n\n```python\nsql_query = \"\"\"\nSELECT firstName,\n       lastName,\n       dateOfBirthUTC\n  FROM players\n ORDER BY firstName,\n          dateOfBirthUTC DESC;\n\"\"\"\n```\n\n\n```python\npd.read_sql(sql_query, conn_nba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>firstName</th>\n      <th>lastName</th>\n      <th>dateOfBirthUTC</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Aaron</td>\n      <td>Holiday</td>\n      <td>1996-09-30</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Aaron</td>\n      <td>Gordon</td>\n      <td>1995-09-16</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Abdel</td>\n      <td>Nader</td>\n      <td>1993-09-25</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Adam</td>\n      <td>Mokoka</td>\n      <td>1998-07-18</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Admiral</td>\n      <td>Schofield</td>\n      <td>1997-03-30</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>499</th>\n      <td>Zach</td>\n      <td>Collins</td>\n      <td>1997-11-19</td>\n    </tr>\n    <tr>\n      <th>500</th>\n      <td>Zach</td>\n      <td>LaVine</td>\n      <td>1995-03-10</td>\n    </tr>\n    <tr>\n      <th>501</th>\n      <td>Zhaire</td>\n      <td>Smith</td>\n      <td>1999-06-04</td>\n    </tr>\n    <tr>\n      <th>502</th>\n      <td>Zion</td>\n      <td>Williamson</td>\n      <td>2000-07-06</td>\n    </tr>\n    <tr>\n      <th>503</th>\n      <td>Zylan</td>\n      <td>Cheatham</td>\n      <td>1995-11-17</td>\n    </tr>\n  </tbody>\n</table>\n<p>504 rows \u00d7 3 columns</p>\n</div>\n\n\n\n## \u4f7f\u7528 `WHERE` \u7be9\u9078\u89c0\u6e2c\u503c\n\n\n```python\nsql_query = \"\"\"\nSELECT fullName\n  FROM teams\n WHERE confName = 'East';\n\"\"\"\n```\n\n\n```python\npd.read_sql(sql_query, conn_nba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fullName</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Atlanta Hawks</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Boston Celtics</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Cleveland Cavaliers</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Chicago Bulls</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Miami Heat</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>Milwaukee Bucks</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Brooklyn Nets</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>New York Knicks</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Orlando Magic</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>Indiana Pacers</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>Philadelphia 76ers</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>Toronto Raptors</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>Washington Wizards</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>Detroit Pistons</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>Charlotte Hornets</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## `=` \u662f\u5b8c\u5168\u76f8\u540c\uff0c\u5176\u4ed6\u7684\u6bd4\u8f03\u904b\u7b97\u7b26\u5c1a\u6709\n\n- `!=`: \u4e0d\u7b49\u65bc\n- `>`, `>=`: \u5927\u65bc\u3001\u5927\u65bc\u7b49\u65bc\n- `<`, `<=`: \u5c0f\u65bc\u3001\u5c0f\u65bc\u7b49\u65bc\n- `BETWEEN`: \u4ecb\u65bc\u4e00\u500b\u7bc4\u570d\n- `IN`: \u5c6c\u65bc\u96c6\u5408\u4e2d\u7684\u503c\n- `LIKE`: \u6a21\u7cca\u6bd4\u5c0d\n- `NOT`: \u975e\n\n\n```python\n# \u4e0d\u7b49\u65bc\nsql_query = \"\"\"\nSELECT fullName\n  FROM teams\n WHERE confName != 'East';\n\"\"\"\npd.read_sql(sql_query, conn_nba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fullName</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>New Orleans Pelicans</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Dallas Mavericks</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Denver Nuggets</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Golden State Warriors</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Houston Rockets</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>LA Clippers</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Los Angeles Lakers</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Minnesota Timberwolves</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Phoenix Suns</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>Portland Trail Blazers</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>Sacramento Kings</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>San Antonio Spurs</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>Oklahoma City Thunder</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>Utah Jazz</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>Memphis Grizzlies</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# \u5927\u65bc\u7b49\u65bc\nsql_query = \"\"\"\nSELECT personId,\n       ppg\n  FROM careerSummaries\n WHERE ppg >= 25;\n\"\"\"\npd.read_sql(sql_query, conn_nba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>personId</th>\n      <th>ppg</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>2544</td>\n      <td>27.1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>201142</td>\n      <td>27.0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>201935</td>\n      <td>25.1</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# \u4ecb\u65bc\u4e00\u500b\u7bc4\u570d\nsql_query = \"\"\"\nSELECT personId,\n       ppg\n  FROM careerSummaries\n WHERE ppg >= 20 AND\n       ppg <= 25;\n\"\"\"\npd.read_sql(sql_query, conn_nba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>personId</th>\n      <th>ppg</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>2546</td>\n      <td>23.6</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>201566</td>\n      <td>23.2</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>201933</td>\n      <td>21.7</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>201939</td>\n      <td>23.5</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>201942</td>\n      <td>20.0</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>202681</td>\n      <td>22.4</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>202689</td>\n      <td>20.0</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>203076</td>\n      <td>24.0</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>203078</td>\n      <td>21.0</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>203081</td>\n      <td>24.0</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>203507</td>\n      <td>20.0</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>203954</td>\n      <td>24.1</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>1626157</td>\n      <td>22.7</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>1626164</td>\n      <td>22.3</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>1628378</td>\n      <td>22.7</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>1629027</td>\n      <td>23.6</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>1629029</td>\n      <td>24.4</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>1629627</td>\n      <td>23.6</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# \u5c6c\u65bc\u96c6\u5408\u4e2d\u7684\u503c\nsql_query = \"\"\"\nSELECT fullName\n  FROM teams\n WHERE divName IN ('Atlantic', 'Pacific');\n\"\"\"\npd.read_sql(sql_query, conn_nba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fullName</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Boston Celtics</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Golden State Warriors</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>LA Clippers</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Los Angeles Lakers</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Brooklyn Nets</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>New York Knicks</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Philadelphia 76ers</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Phoenix Suns</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Sacramento Kings</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>Toronto Raptors</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# \u6a21\u7cca\u6bd4\u5c0d %\nsql_query = \"\"\"\nSELECT firstName,\n       lastName\n  FROM players\n WHERE firstName LIKE 'L%';\n\"\"\"\npd.read_sql(sql_query, conn_nba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>firstName</th>\n      <th>lastName</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>LeBron</td>\n      <td>James</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Lou</td>\n      <td>Williams</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>LaMarcus</td>\n      <td>Aldridge</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Langston</td>\n      <td>Galloway</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Larry</td>\n      <td>Nance Jr.</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>Lonzo</td>\n      <td>Ball</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Lauri</td>\n      <td>Markkanen</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Luke</td>\n      <td>Kennard</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Luke</td>\n      <td>Kornet</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>Landry</td>\n      <td>Shamet</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>Lonnie</td>\n      <td>Walker IV</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>Luka</td>\n      <td>Doncic</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>Luguentz</td>\n      <td>Dort</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>Louis</td>\n      <td>King</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>Luka</td>\n      <td>Samanic</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# \u6a21\u7cca\u6bd4\u5c0d _\nsql_query = \"\"\"\nSELECT firstName,\n       lastName\n  FROM players\n WHERE firstName LIKE 'L___';\n\"\"\"\npd.read_sql(sql_query, conn_nba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>firstName</th>\n      <th>lastName</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Luke</td>\n      <td>Kennard</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Luke</td>\n      <td>Kornet</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Luka</td>\n      <td>Doncic</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Luka</td>\n      <td>Samanic</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# \u975e\nsql_query = \"\"\"\nSELECT fullName\n  FROM teams\n WHERE divName NOT IN ('Atlantic', 'Pacific');\n\"\"\"\npd.read_sql(sql_query, conn_nba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fullName</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Atlanta Hawks</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Cleveland Cavaliers</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>New Orleans Pelicans</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Chicago Bulls</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Dallas Mavericks</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>Denver Nuggets</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Houston Rockets</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Miami Heat</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Milwaukee Bucks</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>Minnesota Timberwolves</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>Orlando Magic</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>Indiana Pacers</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>Portland Trail Blazers</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>San Antonio Spurs</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>Oklahoma City Thunder</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>Utah Jazz</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>Memphis Grizzlies</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>Washington Wizards</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>Detroit Pistons</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>Charlotte Hornets</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## \u4ee5 `AND` \u8207 `OR` \u7d50\u5408 `WHERE` \u689d\u4ef6\n\n- \u4ee5 `AND` \u4ea4\u96c6\u5169\u500b\u4ee5\u4e0a\u7684\u689d\u4ef6\n- \u4ee5 `OR` \u806f\u96c6\u5169\u500b\u4ee5\u4e0a\u7684\u689d\u4ef6\n\n\n```python\nsql_query = \"\"\"\nSELECT firstName,\n       lastName\n  FROM players\n WHERE firstName LIKE 'L%' AND\n       lastName LIKE 'J%';\n\"\"\"\npd.read_sql(sql_query, conn_nba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>firstName</th>\n      <th>lastName</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>LeBron</td>\n      <td>James</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nsql_query = \"\"\"\nSELECT firstName,\n       lastName\n  FROM players\n WHERE firstName LIKE 'L%' OR\n       lastName LIKE 'J%';\n\"\"\"\npd.read_sql(sql_query, conn_nba)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>firstName</th>\n      <th>lastName</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>LeBron</td>\n      <td>James</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Lou</td>\n      <td>Williams</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>LaMarcus</td>\n      <td>Aldridge</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>DeAndre</td>\n      <td>Jordan</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>James</td>\n      <td>Johnson</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>Reggie</td>\n      <td>Jackson</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Cory</td>\n      <td>Joseph</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Nikola</td>\n      <td>Jokic</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Tyler</td>\n      <td>Johnson</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>Langston</td>\n      <td>Galloway</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>Tyus</td>\n      <td>Jones</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>Stanley</td>\n      <td>Johnson</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>Larry</td>\n      <td>Nance Jr.</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>Damian</td>\n      <td>Jones</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>Derrick</td>\n      <td>Jones Jr.</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>Lonzo</td>\n      <td>Ball</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>Josh</td>\n      <td>Jackson</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>Lauri</td>\n      <td>Markkanen</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>Luke</td>\n      <td>Kennard</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>Justin</td>\n      <td>Jackson</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>Frank</td>\n      <td>Jackson</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>Luke</td>\n      <td>Kornet</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>Jaren</td>\n      <td>Jackson Jr.</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>Alize</td>\n      <td>Johnson</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>Landry</td>\n      <td>Shamet</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>Lonnie</td>\n      <td>Walker IV</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>Luka</td>\n      <td>Doncic</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>BJ</td>\n      <td>Johnson</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>DaQuan</td>\n      <td>Jeffries</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>Keldon</td>\n      <td>Johnson</td>\n    </tr>\n    <tr>\n      <th>30</th>\n      <td>Luguentz</td>\n      <td>Dort</td>\n    </tr>\n    <tr>\n      <th>31</th>\n      <td>Ty</td>\n      <td>Jerome</td>\n    </tr>\n    <tr>\n      <th>32</th>\n      <td>Cameron</td>\n      <td>Johnson</td>\n    </tr>\n    <tr>\n      <th>33</th>\n      <td>Louis</td>\n      <td>King</td>\n    </tr>\n    <tr>\n      <th>34</th>\n      <td>Luka</td>\n      <td>Samanic</td>\n    </tr>\n    <tr>\n      <th>35</th>\n      <td>Justin</td>\n      <td>James</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## \u9019\u662f\u76ee\u524d\u6db5\u84cb\u7684\u67e5\u8a62\u4fdd\u7559\u5b57\n\n\u4f7f\u7528 SQL \u8a9e\u6cd5\u6642\uff0c\u4fdd\u7559\u5b57\u9806\u5e8f\u5fc5\u9808\u8981\u9075\u5b88\u3002\n\n```sql\nSELECT DISTINCT CAST(column_name AS data_type) AS alias_name\n  FROM table_name\n WHERE conditions\n ORDER BY column_name DESC\n LIMIT n_obs;\n```\n\n## \u96a8\u5802\u7df4\u7fd2\n\n[\u57fa\u672c\u67e5\u8a62\uff1a\u96a8\u5802\u7df4\u7fd2](https://mybinder.org/v2/gh/yaojenkuo/introduction-to-sql/master?filepath=02-exercises.ipynb)\n\n## \u96a8\u5802\u7df4\u7fd2\uff1a\u4ee5 `||`  \u904b\u7b97\u7b26\u5c07 `presidential2020` \u8868\u683c\u4e2d `county`\u3001`town` \u8207 `village` \u9023\u7d50\u70ba\u4e00\u500b\u65b0\u7684\u6b04\u4f4d\u4e26\u547d\u540d\u70ba `combined_key`\uff0c\u518d\u4ee5 `DISTINCT` \u66b8\u89e3\u53f0\u7063\u7368\u4e00\u7684\u9078\u8209\u5340\u6709\u54ea\u4e9b\n\n\n```python\nexpected_output = pd.read_sql(etq('0201'), conn_twelection)\n```\n\n\n```python\nexpected_output\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>combined_key</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>\u5357\u6295\u7e23\u4e2d\u5bee\u9109\u4e2d\u5bee\u6751</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>\u5357\u6295\u7e23\u4e2d\u5bee\u9109\u5167\u57ce\u6751</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>\u5357\u6295\u7e23\u4e2d\u5bee\u9109\u516b\u4ed9\u6751</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>\u5357\u6295\u7e23\u4e2d\u5bee\u9109\u548c\u8208\u6751</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>\u5357\u6295\u7e23\u4e2d\u5bee\u9109\u5d01\u9802\u6751</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>7732</th>\n      <td>\u9ad8\u96c4\u5e02\u9f13\u5c71\u5340\u9f13\u5ca9\u91cc</td>\n    </tr>\n    <tr>\n      <th>7733</th>\n      <td>\u9ad8\u96c4\u5e02\u9f13\u5c71\u5340\u9f13\u5cf0\u91cc</td>\n    </tr>\n    <tr>\n      <th>7734</th>\n      <td>\u9ad8\u96c4\u5e02\u9f13\u5c71\u5340\u9f8d\u4e95\u91cc</td>\n    </tr>\n    <tr>\n      <th>7735</th>\n      <td>\u9ad8\u96c4\u5e02\u9f13\u5c71\u5340\u9f8d\u5b50\u91cc</td>\n    </tr>\n    <tr>\n      <th>7736</th>\n      <td>\u9ad8\u96c4\u5e02\u9f13\u5c71\u5340\u9f8d\u6c34\u91cc</td>\n    </tr>\n  </tbody>\n</table>\n<p>7737 rows \u00d7 1 columns</p>\n</div>\n\n\n\n## \u96a8\u5802\u7df4\u7fd2\uff1a\u8a08\u7b97 NBA \u7403\u54e1\u7684\u8eab\u9ad4\u8cea\u91cf\u6307\u6578\uff08BMI\uff09\u4e26\u7531\u5927\u5230\u5c0f\u6392\u5e8f\uff0c\u9078\u64c7 `firstName`\u3001`lastName` \u8207 `bmi` \u9019\u4e09\u500b\u8b8a\u6578\n\n\n```python\nexpected_output = pd.read_sql(etq('0202'), conn_nba)\n```\n\n\n```python\nexpected_output\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>firstName</th>\n      <th>lastName</th>\n      <th>bmi</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Zion</td>\n      <td>Williamson</td>\n      <td>32.853790</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Jaylen</td>\n      <td>Adams</td>\n      <td>30.487623</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Jarrell</td>\n      <td>Brantley</td>\n      <td>29.518950</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Eric</td>\n      <td>Paschall</td>\n      <td>29.512295</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Andre</td>\n      <td>Drummond</td>\n      <td>29.262204</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>499</th>\n      <td>Kostas</td>\n      <td>Antetokounmpo</td>\n      <td>20.964312</td>\n    </tr>\n    <tr>\n      <th>500</th>\n      <td>Justin</td>\n      <td>Holiday</td>\n      <td>20.814203</td>\n    </tr>\n    <tr>\n      <th>501</th>\n      <td>Patrick</td>\n      <td>McCaw</td>\n      <td>20.321279</td>\n    </tr>\n    <tr>\n      <th>502</th>\n      <td>Corey</td>\n      <td>Brewer</td>\n      <td>20.100858</td>\n    </tr>\n    <tr>\n      <th>503</th>\n      <td>Isaac</td>\n      <td>Bonga</td>\n      <td>19.801500</td>\n    </tr>\n  </tbody>\n</table>\n<p>504 rows \u00d7 3 columns</p>\n</div>\n\n\n\n## \u96a8\u5802\u7df4\u7fd2\uff1a\u4f7f\u7528 `WHERE` \u5c07 `presidential2020` \u4e2d\u81fa\u5317\u5e02\u7684\u8cc7\u6599\u7be9\u9078\u51fa\u4f86\n\n\n```python\nexpected_output = pd.read_sql(etq('0203'), conn_twelection)\n```\n\n\n```python\nexpected_output\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>county</th>\n      <th>town</th>\n      <th>village</th>\n      <th>office</th>\n      <th>number</th>\n      <th>candidates</th>\n      <th>votes</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>\u81fa\u5317\u5e02</td>\n      <td>\u4e2d\u5c71\u5340</td>\n      <td>\u4e0b\u57e4\u91cc</td>\n      <td>524</td>\n      <td>1</td>\n      <td>\u5b8b\u695a\u745c/\u4f59\u6e58</td>\n      <td>48</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>\u81fa\u5317\u5e02</td>\n      <td>\u4e2d\u5c71\u5340</td>\n      <td>\u4e0b\u57e4\u91cc</td>\n      <td>524</td>\n      <td>2</td>\n      <td>\u97d3\u570b\u745c/\u5f35\u5584\u653f</td>\n      <td>377</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>\u81fa\u5317\u5e02</td>\n      <td>\u4e2d\u5c71\u5340</td>\n      <td>\u4e0b\u57e4\u91cc</td>\n      <td>524</td>\n      <td>3</td>\n      <td>\u8521\u82f1\u6587/\u8cf4\u6e05\u5fb7</td>\n      <td>581</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>\u81fa\u5317\u5e02</td>\n      <td>\u4e2d\u5c71\u5340</td>\n      <td>\u4e0b\u57e4\u91cc</td>\n      <td>525</td>\n      <td>1</td>\n      <td>\u5b8b\u695a\u745c/\u4f59\u6e58</td>\n      <td>53</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>\u81fa\u5317\u5e02</td>\n      <td>\u4e2d\u5c71\u5340</td>\n      <td>\u4e0b\u57e4\u91cc</td>\n      <td>525</td>\n      <td>2</td>\n      <td>\u97d3\u570b\u745c/\u5f35\u5584\u653f</td>\n      <td>342</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>5179</th>\n      <td>\u81fa\u5317\u5e02</td>\n      <td>\u842c\u83ef\u5340</td>\n      <td>\u9a30\u96f2\u91cc</td>\n      <td>1032</td>\n      <td>2</td>\n      <td>\u97d3\u570b\u745c/\u5f35\u5584\u653f</td>\n      <td>528</td>\n    </tr>\n    <tr>\n      <th>5180</th>\n      <td>\u81fa\u5317\u5e02</td>\n      <td>\u842c\u83ef\u5340</td>\n      <td>\u9a30\u96f2\u91cc</td>\n      <td>1032</td>\n      <td>3</td>\n      <td>\u8521\u82f1\u6587/\u8cf4\u6e05\u5fb7</td>\n      <td>456</td>\n    </tr>\n    <tr>\n      <th>5181</th>\n      <td>\u81fa\u5317\u5e02</td>\n      <td>\u842c\u83ef\u5340</td>\n      <td>\u9a30\u96f2\u91cc</td>\n      <td>1033</td>\n      <td>1</td>\n      <td>\u5b8b\u695a\u745c/\u4f59\u6e58</td>\n      <td>43</td>\n    </tr>\n    <tr>\n      <th>5182</th>\n      <td>\u81fa\u5317\u5e02</td>\n      <td>\u842c\u83ef\u5340</td>\n      <td>\u9a30\u96f2\u91cc</td>\n      <td>1033</td>\n      <td>2</td>\n      <td>\u97d3\u570b\u745c/\u5f35\u5584\u653f</td>\n      <td>502</td>\n    </tr>\n    <tr>\n      <th>5183</th>\n      <td>\u81fa\u5317\u5e02</td>\n      <td>\u842c\u83ef\u5340</td>\n      <td>\u9a30\u96f2\u91cc</td>\n      <td>1033</td>\n      <td>3</td>\n      <td>\u8521\u82f1\u6587/\u8cf4\u6e05\u5fb7</td>\n      <td>512</td>\n    </tr>\n  </tbody>\n</table>\n<p>5184 rows \u00d7 7 columns</p>\n</div>\n\n\n\n## \u96a8\u5802\u7df4\u7fd2\uff1a\u4f7f\u7528 `WHERE` \u5c07 `presidential2020` \u8868\u683c\u4e2d\u7684\u516d\u90fd\uff08\u81fa\u5317\u5e02\u3001\u65b0\u5317\u5e02\u3001\u6843\u5712\u5e02\u3001\u81fa\u4e2d\u5e02\u3001\u81fa\u5357\u5e02\u8207\u9ad8\u96c4\u5e02\uff09\u7684\u8cc7\u6599\u7be9\u9078\u51fa\u4f86\n\n\n```python\nexpected_output = pd.read_sql(etq('0204'), conn_twelection)\n```\n\n\n```python\nexpected_output\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>county</th>\n      <th>town</th>\n      <th>village</th>\n      <th>office</th>\n      <th>number</th>\n      <th>candidates</th>\n      <th>votes</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>\u65b0\u5317\u5e02</td>\n      <td>\u4e09\u5cfd\u5340</td>\n      <td>\u4e09\u5cfd\u91cc</td>\n      <td>2010</td>\n      <td>1</td>\n      <td>\u5b8b\u695a\u745c/\u4f59\u6e58</td>\n      <td>11</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>\u65b0\u5317\u5e02</td>\n      <td>\u4e09\u5cfd\u5340</td>\n      <td>\u4e09\u5cfd\u91cc</td>\n      <td>2010</td>\n      <td>2</td>\n      <td>\u97d3\u570b\u745c/\u5f35\u5584\u653f</td>\n      <td>83</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>\u65b0\u5317\u5e02</td>\n      <td>\u4e09\u5cfd\u5340</td>\n      <td>\u4e09\u5cfd\u91cc</td>\n      <td>2010</td>\n      <td>3</td>\n      <td>\u8521\u82f1\u6587/\u8cf4\u6e05\u5fb7</td>\n      <td>124</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>\u65b0\u5317\u5e02</td>\n      <td>\u4e09\u5cfd\u5340</td>\n      <td>\u4e2d\u57d4\u91cc</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>\u5b8b\u695a\u745c/\u4f59\u6e58</td>\n      <td>51</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>\u65b0\u5317\u5e02</td>\n      <td>\u4e09\u5cfd\u5340</td>\n      <td>\u4e2d\u57d4\u91cc</td>\n      <td>2014</td>\n      <td>2</td>\n      <td>\u97d3\u570b\u745c/\u5f35\u5584\u653f</td>\n      <td>364</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>32668</th>\n      <td>\u9ad8\u96c4\u5e02</td>\n      <td>\u9f13\u5c71\u5340</td>\n      <td>\u9f8d\u6c34\u91cc</td>\n      <td>1268</td>\n      <td>2</td>\n      <td>\u97d3\u570b\u745c/\u5f35\u5584\u653f</td>\n      <td>477</td>\n    </tr>\n    <tr>\n      <th>32669</th>\n      <td>\u9ad8\u96c4\u5e02</td>\n      <td>\u9f13\u5c71\u5340</td>\n      <td>\u9f8d\u6c34\u91cc</td>\n      <td>1268</td>\n      <td>3</td>\n      <td>\u8521\u82f1\u6587/\u8cf4\u6e05\u5fb7</td>\n      <td>647</td>\n    </tr>\n    <tr>\n      <th>32670</th>\n      <td>\u9ad8\u96c4\u5e02</td>\n      <td>\u9f13\u5c71\u5340</td>\n      <td>\u9f8d\u6c34\u91cc</td>\n      <td>1269</td>\n      <td>1</td>\n      <td>\u5b8b\u695a\u745c/\u4f59\u6e58</td>\n      <td>39</td>\n    </tr>\n    <tr>\n      <th>32671</th>\n      <td>\u9ad8\u96c4\u5e02</td>\n      <td>\u9f13\u5c71\u5340</td>\n      <td>\u9f8d\u6c34\u91cc</td>\n      <td>1269</td>\n      <td>2</td>\n      <td>\u97d3\u570b\u745c/\u5f35\u5584\u653f</td>\n      <td>520</td>\n    </tr>\n    <tr>\n      <th>32672</th>\n      <td>\u9ad8\u96c4\u5e02</td>\n      <td>\u9f13\u5c71\u5340</td>\n      <td>\u9f8d\u6c34\u91cc</td>\n      <td>1269</td>\n      <td>3</td>\n      <td>\u8521\u82f1\u6587/\u8cf4\u6e05\u5fb7</td>\n      <td>673</td>\n    </tr>\n  </tbody>\n</table>\n<p>32673 rows \u00d7 7 columns</p>\n</div>\n\n\n\n## \u96a8\u5802\u7df4\u7fd2\uff1a\u67e5\u8a62 `careerSummaries` \u751f\u6daf\u5834\u5747\u5f97\u5206 `ppg` \u8d85\u904e 20 \u5206\u7684\u7403\u54e1 ID `personId`\u3001\u5834\u5747\u5f97\u5206 `ppg`\n\n\n```python\nexpected_output = pd.read_sql(etq('0205'), conn_nba)\n```\n\n\n```python\nexpected_output\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>personId</th>\n      <th>ppg</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>2544</td>\n      <td>27.1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2546</td>\n      <td>23.6</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>201142</td>\n      <td>27.0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>201566</td>\n      <td>23.2</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>201933</td>\n      <td>21.7</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>201935</td>\n      <td>25.1</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>201939</td>\n      <td>23.5</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>202681</td>\n      <td>22.4</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>203076</td>\n      <td>24.0</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>203078</td>\n      <td>21.0</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>203081</td>\n      <td>24.0</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>203954</td>\n      <td>24.1</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>1626157</td>\n      <td>22.7</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>1626164</td>\n      <td>22.3</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>1628378</td>\n      <td>22.7</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>1629027</td>\n      <td>23.6</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>1629029</td>\n      <td>24.4</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>1629627</td>\n      <td>23.6</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## \u96a8\u5802\u7df4\u7fd2\uff1a\u5f9e `careerSummaries` \u4e2d\u627e\u51fa\u751f\u6daf\u52a9\u653b\u5931\u8aa4\u6bd4\uff08assists/turnovers\uff09\u6700\u9ad8\u7684\u524d 10 \u500b\u7403\u54e1 ID `personId`\u3001\u52a9\u653b\u5931\u8aa4\u6bd4 `ast_to_ratio`\n\n\\begin{equation}\nast\\_to\\_ratio = \\frac{assists}{turnovers}\n\\end{equation}\n\n\n```python\nexpected_output = pd.read_sql(etq('0206'), conn_nba)\n```\n\n\n```python\nexpected_output\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>personId</th>\n      <th>ast_to_ratio</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1629669</td>\n      <td>6.333333</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1628420</td>\n      <td>5.448980</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1626145</td>\n      <td>4.775862</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1629162</td>\n      <td>4.032258</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1629648</td>\n      <td>4.000000</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>101108</td>\n      <td>3.935682</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>1627853</td>\n      <td>3.539823</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>1629723</td>\n      <td>3.500000</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>1627832</td>\n      <td>3.209964</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>202397</td>\n      <td>3.071053</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## \u96a8\u5802\u7df4\u7fd2\u53c3\u8003\u89e3\u7b54\n\n[\u57fa\u672c\u67e5\u8a62\uff1a\u96a8\u5802\u7df4\u7fd2\u53c3\u8003\u89e3\u7b54](https://mybinder.org/v2/gh/yaojenkuo/introduction-to-sql/master?filepath=02-suggested-answers.ipynb)\n", "meta": {"hexsha": "11f6fe9d4ca2710a4c49d9bae4b2a11d5ea694d5", "size": 128730, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "02-retrieving-data.ipynb", "max_stars_repo_name": "yaojenkuo/introduction-to-sql", "max_stars_repo_head_hexsha": "d94657463ab0685b743ec8d168086e3ab512f626", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "02-retrieving-data.ipynb", "max_issues_repo_name": "yaojenkuo/introduction-to-sql", "max_issues_repo_head_hexsha": "d94657463ab0685b743ec8d168086e3ab512f626", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-01T04:05:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-01T04:05:26.000Z", "max_forks_repo_path": "02-retrieving-data.ipynb", "max_forks_repo_name": "yaojenkuo/introduction-to-sql", "max_forks_repo_head_hexsha": "d94657463ab0685b743ec8d168086e3ab512f626", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0896464646, "max_line_length": 134, "alphanum_fraction": 0.3389497398, "converted": true, "num_tokens": 22739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17553807793655438, "lm_q2_score": 0.20689404392565783, "lm_q1q2_score": 0.036317782807231025}}
{"text": "```python\ngpu_info = !nvidia-smi\ngpu_info = '\\n'.join(gpu_info)\nif gpu_info.find('failed') >= 0:\n  print('Select the Runtime > \"Change runtime type\" menu to enable a GPU accelerator, ')\n  print('and then re-execute this cell.')\nelse:\n  print(gpu_info)\n```\n\n    Thu Jul 15 08:39:53 2021       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 470.42.01    Driver Version: 460.32.03    CUDA Version: 11.2     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  Tesla P100-PCIE...  Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   37C    P0    25W / 250W |      0MiB / 16280MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    |  No running processes found                                                 |\n    +-----------------------------------------------------------------------------+\n\n\n\n```python\nfrom psutil import virtual_memory\nram_gb = virtual_memory().total / 1e9\nprint('Your runtime has {:.1f} gigabytes of available RAM\\n'.format(ram_gb))\n\nif ram_gb < 20:\n  print('To enable a high-RAM runtime, select the Runtime > \"Change runtime type\"')\n  print('menu, and then select High-RAM in the Runtime shape dropdown. Then, ')\n  print('re-execute this cell.')\nelse:\n  print('You are using a high-RAM runtime!')\n```\n\n    Your runtime has 27.3 gigabytes of available RAM\n    \n    You are using a high-RAM runtime!\n\n\n\n```python\n!pip install tensorflow==2.4.1\n!pip install tensorflow-quantum==0.5.1\n\nfrom IPython.display import clear_output\nclear_output()\n```\n\n\n```python\nimport sys\nsys.version\n```\n\n\n\n\n    '3.7.10 (default, May  3 2021, 02:48:31) \\n[GCC 7.5.0]'\n\n\n\n\n```python\n# main dependencies\nimport tensorflow as tf  # 2.4.1\nimport tensorflow_quantum as tfq  # 0.5.1\nimport cirq  # 0.11.0\nimport sympy  # 1.5\nimport numpy as np  # 1.19.5\nfrom functools import reduce\n\n# visualization tools\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom cirq.contrib.svg import SVGCircuit\n\n# data preprocessing\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\n\n# load saved weights\nimport h5py\n\nimport os\n```\n\n## Loading the Dataset\n\n\n```python\nwith h5py.File(\"/content/drive/My Drive/Projects/GSoC 2021/electron-photon-dataset/photon.hdf5\", \"r\") as f:\n  px = np.asarray(f['X'][()], dtype=np.float32)\n  py = np.asarray(f['y'][()], dtype=np.float32)\n  print(\"Loaded photon dataset!\")\n\nwith h5py.File(\"/content/drive/My Drive/Projects/GSoC 2021/electron-photon-dataset/electron.hdf5\", \"r\") as f:\n  ex = np.asarray(f['X'][()], dtype=np.float32)\n  ey = np.asarray(f['y'][()], dtype=np.float32)\n  print(\"Loaded electron dataset!\")\n\nprint(\"Photon dataset shape:\", px.shape, py.shape)\nprint(\"Electron dataset shape:\", ex.shape, ey.shape)\n```\n\n    Loaded photon dataset!\n    Loaded electron dataset!\n    Photon dataset shape: (249000, 32, 32, 2) (249000,)\n    Electron dataset shape: (249000, 32, 32, 2) (249000,)\n\n\n\n```python\n# photon average image\n\nplt.imshow(np.mean(px[:, :, :, 0], axis=0))\n```\n\n\n```python\n# electron average image\n\nplt.imshow(np.mean(ex[:, :, :, 0], axis=0))\n```\n\n\n```python\nmax_photon, min_photon = np.max(px[:, :, :, 0]), np.min(px[:, :, :, 0])\nmax_electron, min_electron = np.max(ex[:, :, :, 0]), np.min(ex[:, :, :, 0])\n\nprint(max_photon, min_photon)\nprint(max_electron, min_electron)\nmax(max_photon, abs(min_photon), max_electron, abs(min_electron))\n```\n\n    1.4849443 0.0\n    1.431813 0.0\n\n\n\n\n\n    1.4849443\n\n\n\n\n```python\nsample_size = 10000\n\nX = np.concatenate((px[:, :, :, 0], ex[:, :, :, 0]), axis=0)\ny = np.concatenate((py[:], ey[:]), axis=0)\n\n_, X, _, y = train_test_split(X, y, test_size=sample_size, random_state=88)\n\nprint(X.shape, y.shape)\n```\n\n    (10000, 32, 32) (10000,)\n\n\n## Dataset Preprocessing\n\nPosition of maximum value pixel.\n\n\n```python\nprint(\"Proton:\", np.argmax(np.mean(px[:, :, :, 0], axis=0)))\nprint(\"Electron:\", np.argmax(np.mean(ex[:, :, :, 0], axis=0)))\n```\n\n    Proton: 528\n    Electron: 528\n\n\nCrop from 32x32 to 8x8, maintaining the maximum value pixel at the center.\n\n\n```python\ncenter = [int(528/32), 528%32]\n\nimg_size = 8\n\nX = X[:, (center[0]-int(img_size/2)):(center[0]+int(img_size/2)), (center[1]-int(img_size/2)):(center[1]+int(img_size/2))]\nX.shape\n```\n\n\n\n\n    (10000, 8, 8)\n\n\n\nTrain-Test Split and Scaling\n\n\n```python\nx_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=2021)\n\nscaler = StandardScaler()\nscaler.fit(x_train.reshape(-1, img_size*img_size))\nx_train = scaler.transform(x_train.reshape(-1, img_size*img_size))\nx_train = x_train.reshape(-1, img_size, img_size)\ny_train = tf.keras.utils.to_categorical(y_train)\n\nx_test = scaler.transform(x_test.reshape(-1, img_size*img_size))\nx_test = x_test.reshape(-1, img_size, img_size)\ny_test = tf.keras.utils.to_categorical(y_test)\n\nprint(\"Train set shape:\", x_train.shape, y_train.shape)\nprint(\"Test set shape:\", x_test.shape, y_test.shape)\n\nplt.plot(scaler.scale_)\n```\n\n\n```python\n# photon average image\n\nplt.imshow(np.mean(X[:int(len(X)/2), :, :], axis=0))\n```\n\n\n```python\n# electron average image\n\nplt.imshow(np.mean(X[int(len(X)/2):, :, :], axis=0))\n```\n\n\n```python\ndel px, py, ex, ey\n```\n\n## Graph-Convolution Preprocessing\n\n### Adjacency Matrix\n\n\n```python\nimg_size = 32\nadjacency = np.zeros((img_size**2, img_size**2), dtype=np.float64)\ngaussian_scale = np.pi\n\n# k = y-axis of the A matrix\n# i = y-axis of the image\n# j = x-axis of the image\nfor k in range(img_size**2):\n    for i in range(img_size):\n        for j in range(img_size):\n            x_1 = k%img_size  # x coordinate of the pixel-k in the A matrix\n            x_2 = j  # x coordinate of the image\n\n            y_1 = int(k/img_size)  # y coordinate of the pixel-k in the A matrix\n            y_2 = i  # y coordinate of the image\n\n            adjacency[k, i*img_size + j] = np.exp(-np.sqrt((x_1-x_2)**2 + (y_1-y_2)**2)/(gaussian_scale**2))\n```\n\n\n```python\nplt.imshow(np.log10(adjacency))\n```\n\n### Average Plot of A^2 X\n\n\n```python\n# photon\n\nplt.imshow((adjacency@adjacency@(np.mean(px[:, :, :, 0], axis=0).reshape(-1,))).reshape(32,32))\n```\n\n\n```python\n# electron\n\nplt.imshow((adjacency@adjacency@(np.mean(ex[:, :, :, 0], axis=0).reshape(-1,))).reshape(32,32))\n```\n\n\n```python\n# photon\n\nfig=plt.figure(figsize=(10, 10))\ncolumns = 5\nrows = 3\nrandom_integer = np.random.randint(0, high=len(px), size=columns*rows)\nfor i in range(1, columns*rows +1):\n    img = (adjacency@adjacency@px[random_integer[i-1], :, :, 0].reshape(-1,)).reshape(32,32)\n    fig.add_subplot(rows, columns, i)\n    plt.imshow(img, cmap='viridis')\nplt.show()\n```\n\n\n```python\nfig=plt.figure(figsize=(10, 10))\ncolumns = 5\nrows = 3\nrandom_integer = np.random.randint(0, high=len(ex), size=columns*rows)\nfor i in range(1, columns*rows +1):\n    img = (adjacency@adjacency@(ex[random_integer[i-1], :, :, 0].reshape(-1,))).reshape(32,32)\n    fig.add_subplot(rows, columns, i)\n    plt.imshow(img, cmap='viridis')\nplt.show()\n```\n\n## Building the Networks\n\n\n```python\ndef one_qubit_rotation(qubit, symbols):\n    \"\"\"\n    Returns Cirq gates that apply a rotation of the bloch sphere about the X,\n    Y and Z axis, specified by the values in `symbols`.\n    \"\"\"\n    return [cirq.rx(symbols[0])(qubit),\n            cirq.ry(symbols[1])(qubit),\n            cirq.rz(symbols[2])(qubit)]\n\n```\n\n\n```python\ndef entangling_layer(qubits):\n    \"\"\"\n    Returns a layer of CZ entangling gates on `qubits` (arranged in a circular topology).\n    \"\"\"\n    cz_ops = [cirq.CZ(q0, q1) for q0, q1 in zip(qubits, qubits[1:])]\n    cz_ops += ([cirq.CZ(qubits[0], qubits[-1])] if len(qubits) != 2 else [])\n    return cz_ops\n```\n\n\n```python\ndef generate_circuit(qubits, n_layers, filter_size, use_entanglement=True):\n    \"\"\"Prepares a data re-uploading circuit on `qubits` with `n_layers` layers.\"\"\"\n    # Number of qubits\n    n_qubits = len(qubits)\n\n    # Number of padding\n    # Zero-pad the inputs and params if it is not a multiple of 3\n    padding = (3 - ((filter_size*filter_size)%3))%3\n\n    # Sympy symbols for weights and bias parameters\n    params = sympy.symbols(f'theta(0:{(filter_size*filter_size + padding)*n_layers*n_qubits})')\n    params = np.asarray(params).reshape((n_layers, n_qubits, (filter_size*filter_size + padding)))\n\n    # Sympy symbols for input features\n    # Repeat the input features for every layer and qubit\n    inputs = sympy.symbols(f'x(0:{(filter_size*filter_size + padding)*n_layers*n_qubits})')\n    inputs = np.asarray(inputs).reshape((n_layers, n_qubits, (filter_size*filter_size + padding)))\n\n    # Define circuit\n    circuit = cirq.Circuit()\n    for l in range(n_layers):\n        for gate in range(int(np.ceil((filter_size*filter_size)/3))):\n            # Encoding layer\n            circuit += cirq.Circuit(one_qubit_rotation(q, inputs[l, i, gate*3:(gate+1)*3]) for i, q in enumerate(qubits))\n            # Variational layer\n            circuit += cirq.Circuit(one_qubit_rotation(q, params[l, i, gate*3:(gate+1)*3]) for i, q in enumerate(qubits))\n\n        if n_qubits >= 2 and (l != (n_layers-1) or n_layers == 1) and use_entanglement:\n            circuit += entangling_layer(qubits)\n\n    return circuit, list(params.flat), list(inputs.flat)\n\n```\n\n\n```python\nn_qubits, n_layers = 3, 3\nfilter_size = 2\n\nqubits = cirq.GridQubit.rect(1, n_qubits)\ncircuit, _, inputs_ex = generate_circuit(qubits, n_layers, filter_size, use_entanglement=True)\nSVGCircuit(circuit)\n```\n\n\n\n\n    \n\n    \n\n\n\n\n\n\n```python\nclass ReUploadingPQC(tf.keras.layers.Layer):\n    def __init__(self, n_qubits, n_layers, filter_size, use_entanglement=True, name=\"re-uploading_PQC\"):\n        super(ReUploadingPQC, self).__init__(name=name)\n        self.n_layers = n_layers\n        self.n_qubits = n_qubits\n        self.filter_size = filter_size\n        self.use_entanglement = use_entanglement\n        self.main_name = name\n\n        self.qubits = cirq.GridQubit.rect(1, n_qubits)\n        self.observables = [cirq.Z(self.qubits[-1])]  # Measure only the last qubit\n\n        # generate the data re-uploading circuit\n        circuit, theta_symbols, input_symbols = generate_circuit(self.qubits, self.n_layers, self.filter_size, use_entanglement=self.use_entanglement)\n\n        # Define explicit symbol order.\n        symbols = [str(symb) for symb in theta_symbols + input_symbols]\n        self.indices = tf.constant([sorted(symbols).index(a) for a in symbols])\n\n        # thetas (bias) initialization\n        thetas_init = tf.random_uniform_initializer(minval=-np.pi/2, maxval=np.pi/2)\n        self.thetas = tf.Variable(\n            initial_value=thetas_init(shape=(1, len(theta_symbols)), dtype=\"float32\"),\n            trainable=True, name=self.main_name + \"-thetas\"\n        )\n        \n        # weights initialization\n        w_init = tf.random_uniform_initializer(minval=-1, maxval=1)\n        self.w = tf.Variable(\n            initial_value=w_init(shape=(1, len(input_symbols)), dtype=\"float32\"),\n            trainable=True, name=self.main_name + \"-weights\"\n        )\n\n        # dummy inputs initialization\n        # using the empty circuits as hacks for ControlledPQC\n        self.empty_circuit = tfq.convert_to_tensor([cirq.Circuit()])\n\n        self.computation_layer = tfq.layers.ControlledPQC(circuit, self.observables)\n\n    def get_config(self):\n\n        config = super().get_config().copy()\n        config.update({\n            'n_qubits': self.n_qubits,\n            'n_layers': self.n_layers,\n            'filter_size': self.filter_size,\n            'use_entanglement': self.use_entanglement,\n            'name': self.main_name,\n        })\n        return config\n    \n    def call(self, inputs):\n        batch_size = tf.shape(inputs)[0]\n\n        # Flatten inputs (from 2D images to 1D array)\n        inputs_flattened = tf.keras.layers.Flatten()(inputs)\n\n        # Pad the inputs if it is not a multiple of 3\n        padding = 3 - inputs_flattened.shape[1]%3\n        if padding%3 != 0:\n            inputs_flattened = tf.pad(inputs_flattened, tf.constant([[0, 0,], [0, padding]]))\n\n        # Repeat the inputs for every layer and qubit\n        inputs_flattened = tf.tile(inputs_flattened, tf.constant([1,self.n_layers*self.n_qubits]))\n        \n        # Weight the inputs\n        inputs_weighted = tf.math.multiply(self.w, inputs_flattened, name=self.main_name + '-weighted_inputs')\n        \n        # Duplicate parameters and dummy inputs\n        # One for every batch\n        thetas_batch = tf.tile(self.thetas, multiples=[batch_size, 1], name=self.main_name + '-tiled_up_thetas')\n        empty_circuit_batch = tf.repeat(self.empty_circuit, repeats=batch_size, name=self.main_name + '-tiled_up_empty_circuits')\n\n        joined_params = tf.concat([thetas_batch, inputs_weighted], axis=-1)\n        joined_params = tf.gather(joined_params, self.indices, axis=-1, name=self.main_name + '-joined_params')\n\n        return self.computation_layer([empty_circuit_batch, joined_params])\n```\n\n\n```python\ndef QConv_layer(n_qubits, n_layers, filter_size, stride, inputs, use_entanglement=True, conv_id='', name=\"QConv_layer\"):\n    iter = int(1+(inputs.shape[1]-filter_size)/stride)\n\n    pqc = ReUploadingPQC(n_qubits, n_layers, filter_size, use_entanglement=True, name=name+conv_id)\n    conv = []\n    for i in range(iter):\n        for j in range(iter):\n            temp = pqc(inputs[:, stride*i:stride*i+filter_size, stride*j:stride*j+filter_size])\n            conv += [temp]\n    output_concat = tf.keras.layers.Concatenate(axis=1)(conv)\n    output_reshape = tf.keras.layers.Reshape((iter, iter))(output_concat)\n\n    return output_reshape\n```\n\n\n```python\nfilter_size = 2\nstride = 1\n\nint(1+(8-filter_size)/stride)\n```\n\n\n\n\n    7\n\n\n\n\n```python\nn_qubits, n_layers = 1, 2\n\ninput_tensor = tf.keras.Input(shape=(8,8, ), dtype=tf.dtypes.float32, name='input')\n\nfilter_size = [3, 2]\nstride = [1, 1]\n\nconv_1 = QConv_layer(n_qubits, n_layers, filter_size[0], stride[0], input_tensor, use_entanglement=True, conv_id='1')\nconv_2 = QConv_layer(n_qubits, n_layers, filter_size[1], stride[1], conv_1, use_entanglement=True, conv_id='2')\n#conv_3 = QConv_layer(qubits, n_layers, observables, filter_size, stride, conv_2, use_entanglement=True, conv_id='3')\n\nconv_output = tf.keras.layers.Flatten()(conv_2)\n\ndense_1 = tf.keras.layers.Dense(8, activation='relu')(conv_output)\ndense_2 = tf.keras.layers.Dense(2, activation='softmax')(dense_1)\n#dense_3 = tf.keras.layers.Dense(2, activation='softmax')(dense_2)\n\nmodel = tf.keras.Model(inputs=[input_tensor], outputs=dense_2)\n```\n\n\n```python\nmodel.summary()\n```\n\n    Model: \"model\"\n    __________________________________________________________________________________________________\n    Layer (type)                    Output Shape         Param #     Connected to                     \n    ==================================================================================================\n    input (InputLayer)              [(None, 8, 8)]       0                                            \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem (Slici (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_1 (Sli (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_2 (Sli (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_3 (Sli (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_4 (Sli (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_5 (Sli (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_6 (Sli (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_7 (Sli (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_8 (Sli (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_9 (Sli (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_10 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_11 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_12 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_13 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_14 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_15 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_16 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_17 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_18 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_19 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_20 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_21 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_22 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_23 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_24 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_25 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_26 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_27 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_28 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_29 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_30 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_31 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_32 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_33 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_34 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_35 (Sl (None, 3, 3)         0           input[0][0]                      \n    __________________________________________________________________________________________________\n    QConv_layer1 (ReUploadingPQC)   (None, 1)            36          tf.__operators__.getitem[0][0]   \n                                                                     tf.__operators__.getitem_1[0][0] \n                                                                     tf.__operators__.getitem_2[0][0] \n                                                                     tf.__operators__.getitem_3[0][0] \n                                                                     tf.__operators__.getitem_4[0][0] \n                                                                     tf.__operators__.getitem_5[0][0] \n                                                                     tf.__operators__.getitem_6[0][0] \n                                                                     tf.__operators__.getitem_7[0][0] \n                                                                     tf.__operators__.getitem_8[0][0] \n                                                                     tf.__operators__.getitem_9[0][0] \n                                                                     tf.__operators__.getitem_10[0][0]\n                                                                     tf.__operators__.getitem_11[0][0]\n                                                                     tf.__operators__.getitem_12[0][0]\n                                                                     tf.__operators__.getitem_13[0][0]\n                                                                     tf.__operators__.getitem_14[0][0]\n                                                                     tf.__operators__.getitem_15[0][0]\n                                                                     tf.__operators__.getitem_16[0][0]\n                                                                     tf.__operators__.getitem_17[0][0]\n                                                                     tf.__operators__.getitem_18[0][0]\n                                                                     tf.__operators__.getitem_19[0][0]\n                                                                     tf.__operators__.getitem_20[0][0]\n                                                                     tf.__operators__.getitem_21[0][0]\n                                                                     tf.__operators__.getitem_22[0][0]\n                                                                     tf.__operators__.getitem_23[0][0]\n                                                                     tf.__operators__.getitem_24[0][0]\n                                                                     tf.__operators__.getitem_25[0][0]\n                                                                     tf.__operators__.getitem_26[0][0]\n                                                                     tf.__operators__.getitem_27[0][0]\n                                                                     tf.__operators__.getitem_28[0][0]\n                                                                     tf.__operators__.getitem_29[0][0]\n                                                                     tf.__operators__.getitem_30[0][0]\n                                                                     tf.__operators__.getitem_31[0][0]\n                                                                     tf.__operators__.getitem_32[0][0]\n                                                                     tf.__operators__.getitem_33[0][0]\n                                                                     tf.__operators__.getitem_34[0][0]\n                                                                     tf.__operators__.getitem_35[0][0]\n    __________________________________________________________________________________________________\n    concatenate (Concatenate)       (None, 36)           0           QConv_layer1[0][0]               \n                                                                     QConv_layer1[1][0]               \n                                                                     QConv_layer1[2][0]               \n                                                                     QConv_layer1[3][0]               \n                                                                     QConv_layer1[4][0]               \n                                                                     QConv_layer1[5][0]               \n                                                                     QConv_layer1[6][0]               \n                                                                     QConv_layer1[7][0]               \n                                                                     QConv_layer1[8][0]               \n                                                                     QConv_layer1[9][0]               \n                                                                     QConv_layer1[10][0]              \n                                                                     QConv_layer1[11][0]              \n                                                                     QConv_layer1[12][0]              \n                                                                     QConv_layer1[13][0]              \n                                                                     QConv_layer1[14][0]              \n                                                                     QConv_layer1[15][0]              \n                                                                     QConv_layer1[16][0]              \n                                                                     QConv_layer1[17][0]              \n                                                                     QConv_layer1[18][0]              \n                                                                     QConv_layer1[19][0]              \n                                                                     QConv_layer1[20][0]              \n                                                                     QConv_layer1[21][0]              \n                                                                     QConv_layer1[22][0]              \n                                                                     QConv_layer1[23][0]              \n                                                                     QConv_layer1[24][0]              \n                                                                     QConv_layer1[25][0]              \n                                                                     QConv_layer1[26][0]              \n                                                                     QConv_layer1[27][0]              \n                                                                     QConv_layer1[28][0]              \n                                                                     QConv_layer1[29][0]              \n                                                                     QConv_layer1[30][0]              \n                                                                     QConv_layer1[31][0]              \n                                                                     QConv_layer1[32][0]              \n                                                                     QConv_layer1[33][0]              \n                                                                     QConv_layer1[34][0]              \n                                                                     QConv_layer1[35][0]              \n    __________________________________________________________________________________________________\n    reshape (Reshape)               (None, 6, 6)         0           concatenate[0][0]                \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_36 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_37 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_38 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_39 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_40 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_41 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_42 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_43 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_44 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_45 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_46 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_47 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_48 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_49 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_50 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_51 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_52 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_53 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_54 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_55 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_56 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_57 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_58 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_59 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    tf.__operators__.getitem_60 (Sl (None, 2, 2)         0           reshape[0][0]                    \n    __________________________________________________________________________________________________\n    QConv_layer2 (ReUploadingPQC)   (None, 1)            24          tf.__operators__.getitem_36[0][0]\n                                                                     tf.__operators__.getitem_37[0][0]\n                                                                     tf.__operators__.getitem_38[0][0]\n                                                                     tf.__operators__.getitem_39[0][0]\n                                                                     tf.__operators__.getitem_40[0][0]\n                                                                     tf.__operators__.getitem_41[0][0]\n                                                                     tf.__operators__.getitem_42[0][0]\n                                                                     tf.__operators__.getitem_43[0][0]\n                                                                     tf.__operators__.getitem_44[0][0]\n                                                                     tf.__operators__.getitem_45[0][0]\n                                                                     tf.__operators__.getitem_46[0][0]\n                                                                     tf.__operators__.getitem_47[0][0]\n                                                                     tf.__operators__.getitem_48[0][0]\n                                                                     tf.__operators__.getitem_49[0][0]\n                                                                     tf.__operators__.getitem_50[0][0]\n                                                                     tf.__operators__.getitem_51[0][0]\n                                                                     tf.__operators__.getitem_52[0][0]\n                                                                     tf.__operators__.getitem_53[0][0]\n                                                                     tf.__operators__.getitem_54[0][0]\n                                                                     tf.__operators__.getitem_55[0][0]\n                                                                     tf.__operators__.getitem_56[0][0]\n                                                                     tf.__operators__.getitem_57[0][0]\n                                                                     tf.__operators__.getitem_58[0][0]\n                                                                     tf.__operators__.getitem_59[0][0]\n                                                                     tf.__operators__.getitem_60[0][0]\n    __________________________________________________________________________________________________\n    concatenate_1 (Concatenate)     (None, 25)           0           QConv_layer2[0][0]               \n                                                                     QConv_layer2[1][0]               \n                                                                     QConv_layer2[2][0]               \n                                                                     QConv_layer2[3][0]               \n                                                                     QConv_layer2[4][0]               \n                                                                     QConv_layer2[5][0]               \n                                                                     QConv_layer2[6][0]               \n                                                                     QConv_layer2[7][0]               \n                                                                     QConv_layer2[8][0]               \n                                                                     QConv_layer2[9][0]               \n                                                                     QConv_layer2[10][0]              \n                                                                     QConv_layer2[11][0]              \n                                                                     QConv_layer2[12][0]              \n                                                                     QConv_layer2[13][0]              \n                                                                     QConv_layer2[14][0]              \n                                                                     QConv_layer2[15][0]              \n                                                                     QConv_layer2[16][0]              \n                                                                     QConv_layer2[17][0]              \n                                                                     QConv_layer2[18][0]              \n                                                                     QConv_layer2[19][0]              \n                                                                     QConv_layer2[20][0]              \n                                                                     QConv_layer2[21][0]              \n                                                                     QConv_layer2[22][0]              \n                                                                     QConv_layer2[23][0]              \n                                                                     QConv_layer2[24][0]              \n    __________________________________________________________________________________________________\n    reshape_1 (Reshape)             (None, 5, 5)         0           concatenate_1[0][0]              \n    __________________________________________________________________________________________________\n    flatten (Flatten)               (None, 25)           0           reshape_1[0][0]                  \n    __________________________________________________________________________________________________\n    dense (Dense)                   (None, 8)            208         flatten[0][0]                    \n    __________________________________________________________________________________________________\n    dense_1 (Dense)                 (None, 2)            18          dense[0][0]                      \n    ==================================================================================================\n    Total params: 286\n    Trainable params: 286\n    Non-trainable params: 0\n    __________________________________________________________________________________________________\n\n\n\n```python\nmodel(x_train[0:3])\n```\n\n\n\n\n    <tf.Tensor: shape=(3, 2), dtype=float32, numpy=\n    array([[0.5060837 , 0.49391624],\n           [0.31334004, 0.68666   ],\n           [0.68182826, 0.31817174]], dtype=float32)>\n\n\n\n\n```python\n# Training parameters\nBATCH_SIZE = 128  # orig paper trained all networks with batch_size=128\nEPOCHS = 200 # 200\n\n# Print parameters for sanity check\nprint(\"Batch size, epochs:\", BATCH_SIZE, EPOCHS)\n```\n\n    Batch size, epochs: 128 200\n\n\n\n```python\ndef lr_schedule(epoch):\n    \"\"\"Learning Rate Schedule\n\n    Learning rate is scheduled to be reduced after 80, 120, 160, 180 epochs.\n    Called automatically every epoch as part of callbacks during training.\n\n    # Arguments\n        epoch (int): The number of epochs\n\n    # Returns\n        lr (float32): learning rate\n    \"\"\"\n    lr = 1e-3\n    if epoch > 180:\n        lr *= 0.5e-3\n    elif epoch > 160:\n        lr *= 1e-3\n    elif epoch > 120:\n        lr *= 1e-2\n    elif epoch > 80:\n        lr *= 1e-1\n    print('Learning rate: ', lr)\n    return lr\n```\n\n\n```python\nopt_adam = tf.keras.optimizers.Adam(lr=lr_schedule(0))\n```\n\n    Learning rate:  0.001\n\n\n\n```python\nmodel.compile(loss='categorical_crossentropy',\n              optimizer=opt_adam,\n              metrics=['accuracy', tf.keras.metrics.AUC()])\n```\n\n\n```python\ncheckpoint_dir = '/content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/1_1 Filter=[2,2] Stride=[1,1]'\ncheckpoint_prefix = os.path.join(checkpoint_dir, \"ckpt\")\ncheckpoint = tf.train.Checkpoint(optimizer=opt_adam,\n                                 model=model)\n\nclass CustomCallback(tf.keras.callbacks.Callback):\n\n    def on_epoch_end(self, epoch, logs=None):\n        checkpoint.save(file_prefix = checkpoint_prefix)\n        print(\"Saved custom checkpoint for epoch {}.\".format(epoch+1))\n```\n\n\n```python\n# Prepare callbacks for model saving and for learning rate adjustment.\nlr_scheduler = tf.keras.callbacks.LearningRateScheduler(lr_schedule)\n\nlr_reducer = tf.keras.callbacks.ReduceLROnPlateau(factor=np.sqrt(0.1),\n                               cooldown=0,\n                               patience=5,\n                               min_lr=0.5e-6)\n\ncp_filepath = \"/content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-{epoch:02d}epoch.h5\"\ncheckpoint_callback_epoch = tf.keras.callbacks.ModelCheckpoint(\n    cp_filepath, monitor='val_loss', verbose=1, save_best_only=False,\n    save_weights_only=True, mode='auto', save_freq='epoch'\n)\n\ncallbacks = [lr_reducer, lr_scheduler, checkpoint_callback_epoch, CustomCallback()]\n```\n\n\n```python\nimport time\n#start_time = time.time()\n\nlast_epoch = 0\n\nH = model.fit(x_train, y_train, initial_epoch=last_epoch,\n              batch_size=BATCH_SIZE,\n              epochs=EPOCHS,\n              validation_data=(x_test, y_test),\n              shuffle=True,\n              callbacks=callbacks)\n\nprint(H.history)\nprint(max(H.history['auc']))\nprint(max(H.history['val_auc']))\n```\n\n    Epoch 1/200\n    Learning rate:  0.001\n    67/67 [==============================] - 232s 3s/step - loss: 0.7322 - accuracy: 0.4804 - auc: 0.4709 - val_loss: 0.7001 - val_accuracy: 0.5000 - val_auc: 0.5110\n    \n    Epoch 00001: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-01epoch.h5\n    Saved custom checkpoint for epoch 1.\n    Epoch 2/200\n    Learning rate:  0.001\n    67/67 [==============================] - 212s 3s/step - loss: 0.6987 - accuracy: 0.5067 - auc: 0.5195 - val_loss: 0.6920 - val_accuracy: 0.5307 - val_auc: 0.5455\n    \n    Epoch 00002: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-02epoch.h5\n    Saved custom checkpoint for epoch 2.\n    Epoch 3/200\n    Learning rate:  0.001\n    67/67 [==============================] - 214s 3s/step - loss: 0.6901 - accuracy: 0.5389 - auc: 0.5551 - val_loss: 0.6924 - val_accuracy: 0.5247 - val_auc: 0.5423\n    \n    Epoch 00003: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-03epoch.h5\n    Saved custom checkpoint for epoch 3.\n    Epoch 4/200\n    Learning rate:  0.001\n    67/67 [==============================] - 212s 3s/step - loss: 0.6859 - accuracy: 0.5448 - auc: 0.5680 - val_loss: 0.6873 - val_accuracy: 0.5440 - val_auc: 0.5634\n    \n    Epoch 00004: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-04epoch.h5\n    Saved custom checkpoint for epoch 4.\n    Epoch 5/200\n    Learning rate:  0.001\n    67/67 [==============================] - 208s 3s/step - loss: 0.6835 - accuracy: 0.5583 - auc: 0.5796 - val_loss: 0.6844 - val_accuracy: 0.5580 - val_auc: 0.5771\n    \n    Epoch 00005: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-05epoch.h5\n    Saved custom checkpoint for epoch 5.\n    Epoch 6/200\n    Learning rate:  0.001\n    67/67 [==============================] - 208s 3s/step - loss: 0.6830 - accuracy: 0.5577 - auc: 0.5822 - val_loss: 0.6857 - val_accuracy: 0.5553 - val_auc: 0.5691\n    \n    Epoch 00006: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-06epoch.h5\n    Saved custom checkpoint for epoch 6.\n    Epoch 7/200\n    Learning rate:  0.001\n    67/67 [==============================] - 208s 3s/step - loss: 0.6819 - accuracy: 0.5607 - auc: 0.5839 - val_loss: 0.6843 - val_accuracy: 0.5507 - val_auc: 0.5749\n    \n    Epoch 00007: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-07epoch.h5\n    Saved custom checkpoint for epoch 7.\n    Epoch 8/200\n    Learning rate:  0.001\n    67/67 [==============================] - 210s 3s/step - loss: 0.6759 - accuracy: 0.5746 - auc: 0.6041 - val_loss: 0.6849 - val_accuracy: 0.5513 - val_auc: 0.5740\n    \n    Epoch 00008: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-08epoch.h5\n    Saved custom checkpoint for epoch 8.\n    Epoch 9/200\n    Learning rate:  0.001\n    67/67 [==============================] - 209s 3s/step - loss: 0.6784 - accuracy: 0.5608 - auc: 0.5974 - val_loss: 0.6813 - val_accuracy: 0.5573 - val_auc: 0.5847\n    \n    Epoch 00009: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-09epoch.h5\n    Saved custom checkpoint for epoch 9.\n    Epoch 10/200\n    Learning rate:  0.001\n    67/67 [==============================] - 197s 3s/step - loss: 0.6745 - accuracy: 0.5755 - auc: 0.6077 - val_loss: 0.6786 - val_accuracy: 0.5573 - val_auc: 0.5950\n    \n    Epoch 00010: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-10epoch.h5\n    Saved custom checkpoint for epoch 10.\n    Epoch 11/200\n    Learning rate:  0.001\n    67/67 [==============================] - 191s 3s/step - loss: 0.6696 - accuracy: 0.5855 - auc: 0.6234 - val_loss: 0.6786 - val_accuracy: 0.5633 - val_auc: 0.5946\n    \n    Epoch 00011: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-11epoch.h5\n    Saved custom checkpoint for epoch 11.\n    Epoch 12/200\n    Learning rate:  0.001\n    67/67 [==============================] - 192s 3s/step - loss: 0.6713 - accuracy: 0.5847 - auc: 0.6188 - val_loss: 0.6770 - val_accuracy: 0.5753 - val_auc: 0.6033\n    \n    Epoch 00012: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-12epoch.h5\n    Saved custom checkpoint for epoch 12.\n    Epoch 13/200\n    Learning rate:  0.001\n    67/67 [==============================] - 193s 3s/step - loss: 0.6710 - accuracy: 0.5918 - auc: 0.6196 - val_loss: 0.6768 - val_accuracy: 0.5693 - val_auc: 0.6010\n    \n    Epoch 00013: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-13epoch.h5\n    Saved custom checkpoint for epoch 13.\n    Epoch 14/200\n    Learning rate:  0.001\n    67/67 [==============================] - 195s 3s/step - loss: 0.6684 - accuracy: 0.5930 - auc: 0.6263 - val_loss: 0.6754 - val_accuracy: 0.5753 - val_auc: 0.6078\n    \n    Epoch 00014: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-14epoch.h5\n    Saved custom checkpoint for epoch 14.\n    Epoch 15/200\n    Learning rate:  0.001\n    67/67 [==============================] - 198s 3s/step - loss: 0.6673 - accuracy: 0.5935 - auc: 0.6305 - val_loss: 0.6752 - val_accuracy: 0.5773 - val_auc: 0.6063\n    \n    Epoch 00015: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-15epoch.h5\n    Saved custom checkpoint for epoch 15.\n    Epoch 16/200\n    Learning rate:  0.001\n    67/67 [==============================] - 197s 3s/step - loss: 0.6681 - accuracy: 0.5923 - auc: 0.6272 - val_loss: 0.6743 - val_accuracy: 0.5833 - val_auc: 0.6109\n    \n    Epoch 00016: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-16epoch.h5\n    Saved custom checkpoint for epoch 16.\n    Epoch 17/200\n    Learning rate:  0.001\n    67/67 [==============================] - 196s 3s/step - loss: 0.6679 - accuracy: 0.5897 - auc: 0.6268 - val_loss: 0.6732 - val_accuracy: 0.5793 - val_auc: 0.6125\n    \n    Epoch 00017: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-17epoch.h5\n    Saved custom checkpoint for epoch 17.\n    Epoch 18/200\n    Learning rate:  0.001\n    67/67 [==============================] - 199s 3s/step - loss: 0.6645 - accuracy: 0.5970 - auc: 0.6350 - val_loss: 0.6729 - val_accuracy: 0.5820 - val_auc: 0.6130\n    \n    Epoch 00018: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-18epoch.h5\n    Saved custom checkpoint for epoch 18.\n    Epoch 19/200\n    Learning rate:  0.001\n    67/67 [==============================] - 196s 3s/step - loss: 0.6637 - accuracy: 0.6061 - auc: 0.6386 - val_loss: 0.6725 - val_accuracy: 0.5807 - val_auc: 0.6150\n    \n    Epoch 00019: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-19epoch.h5\n    Saved custom checkpoint for epoch 19.\n    Epoch 20/200\n    Learning rate:  0.001\n    67/67 [==============================] - 197s 3s/step - loss: 0.6649 - accuracy: 0.6007 - auc: 0.6345 - val_loss: 0.6724 - val_accuracy: 0.5807 - val_auc: 0.6145\n    \n    Epoch 00020: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-20epoch.h5\n    Saved custom checkpoint for epoch 20.\n    Epoch 21/200\n    Learning rate:  0.001\n    67/67 [==============================] - 197s 3s/step - loss: 0.6598 - accuracy: 0.6114 - auc: 0.6479 - val_loss: 0.6716 - val_accuracy: 0.5787 - val_auc: 0.6161\n    \n    Epoch 00021: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-21epoch.h5\n    Saved custom checkpoint for epoch 21.\n    Epoch 22/200\n    Learning rate:  0.001\n    67/67 [==============================] - 196s 3s/step - loss: 0.6650 - accuracy: 0.6060 - auc: 0.6350 - val_loss: 0.6717 - val_accuracy: 0.5820 - val_auc: 0.6150\n    \n    Epoch 00022: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-22epoch.h5\n    Saved custom checkpoint for epoch 22.\n    Epoch 23/200\n    Learning rate:  0.001\n    67/67 [==============================] - 209s 3s/step - loss: 0.6635 - accuracy: 0.5987 - auc: 0.6369 - val_loss: 0.6712 - val_accuracy: 0.5800 - val_auc: 0.6175\n    \n    Epoch 00023: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-23epoch.h5\n    Saved custom checkpoint for epoch 23.\n    Epoch 24/200\n    Learning rate:  0.001\n    67/67 [==============================] - 197s 3s/step - loss: 0.6626 - accuracy: 0.6011 - auc: 0.6400 - val_loss: 0.6704 - val_accuracy: 0.5827 - val_auc: 0.6209\n    \n    Epoch 00024: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-24epoch.h5\n    Saved custom checkpoint for epoch 24.\n    Epoch 25/200\n    Learning rate:  0.001\n    67/67 [==============================] - 195s 3s/step - loss: 0.6635 - accuracy: 0.6032 - auc: 0.6387 - val_loss: 0.6699 - val_accuracy: 0.5853 - val_auc: 0.6211\n    \n    Epoch 00025: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-25epoch.h5\n    Saved custom checkpoint for epoch 25.\n    Epoch 26/200\n    Learning rate:  0.001\n    67/67 [==============================] - 196s 3s/step - loss: 0.6580 - accuracy: 0.6096 - auc: 0.6506 - val_loss: 0.6700 - val_accuracy: 0.5800 - val_auc: 0.6212\n    \n    Epoch 00026: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-26epoch.h5\n    Saved custom checkpoint for epoch 26.\n    Epoch 27/200\n    Learning rate:  0.001\n    67/67 [==============================] - 195s 3s/step - loss: 0.6639 - accuracy: 0.6089 - auc: 0.6386 - val_loss: 0.6691 - val_accuracy: 0.5893 - val_auc: 0.6246\n    \n    Epoch 00027: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-27epoch.h5\n    Saved custom checkpoint for epoch 27.\n    Epoch 28/200\n    Learning rate:  0.001\n    67/67 [==============================] - 198s 3s/step - loss: 0.6539 - accuracy: 0.6158 - auc: 0.6576 - val_loss: 0.6705 - val_accuracy: 0.5833 - val_auc: 0.6204\n    \n    Epoch 00028: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-28epoch.h5\n    Saved custom checkpoint for epoch 28.\n    Epoch 29/200\n    Learning rate:  0.001\n    67/67 [==============================] - 189s 3s/step - loss: 0.6608 - accuracy: 0.6069 - auc: 0.6441 - val_loss: 0.6700 - val_accuracy: 0.5833 - val_auc: 0.6227\n    \n    Epoch 00029: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-29epoch.h5\n    Saved custom checkpoint for epoch 29.\n    Epoch 30/200\n    Learning rate:  0.001\n    67/67 [==============================] - 190s 3s/step - loss: 0.6569 - accuracy: 0.6165 - auc: 0.6513 - val_loss: 0.6688 - val_accuracy: 0.5913 - val_auc: 0.6255\n    \n    Epoch 00030: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-30epoch.h5\n    Saved custom checkpoint for epoch 30.\n    Epoch 31/200\n    Learning rate:  0.001\n    67/67 [==============================] - 192s 3s/step - loss: 0.6573 - accuracy: 0.6192 - auc: 0.6513 - val_loss: 0.6697 - val_accuracy: 0.5927 - val_auc: 0.6239\n    \n    Epoch 00031: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-31epoch.h5\n    Saved custom checkpoint for epoch 31.\n    Epoch 32/200\n    Learning rate:  0.001\n    67/67 [==============================] - 188s 3s/step - loss: 0.6605 - accuracy: 0.6056 - auc: 0.6443 - val_loss: 0.6699 - val_accuracy: 0.5813 - val_auc: 0.6228\n    \n    Epoch 00032: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-32epoch.h5\n    Saved custom checkpoint for epoch 32.\n    Epoch 33/200\n    Learning rate:  0.001\n    67/67 [==============================] - 189s 3s/step - loss: 0.6559 - accuracy: 0.6106 - auc: 0.6526 - val_loss: 0.6706 - val_accuracy: 0.5840 - val_auc: 0.6221\n    \n    Epoch 00033: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-33epoch.h5\n    Saved custom checkpoint for epoch 33.\n    Epoch 34/200\n    Learning rate:  0.001\n    67/67 [==============================] - 190s 3s/step - loss: 0.6549 - accuracy: 0.6138 - auc: 0.6545 - val_loss: 0.6691 - val_accuracy: 0.5913 - val_auc: 0.6251\n    \n    Epoch 00034: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-34epoch.h5\n    Saved custom checkpoint for epoch 34.\n    Epoch 35/200\n    Learning rate:  0.001\n    67/67 [==============================] - 187s 3s/step - loss: 0.6529 - accuracy: 0.6195 - auc: 0.6597 - val_loss: 0.6698 - val_accuracy: 0.5853 - val_auc: 0.6260\n    \n    Epoch 00035: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-35epoch.h5\n    Saved custom checkpoint for epoch 35.\n    Epoch 36/200\n    Learning rate:  0.001\n    67/67 [==============================] - 188s 3s/step - loss: 0.6560 - accuracy: 0.6081 - auc: 0.6510 - val_loss: 0.6694 - val_accuracy: 0.5887 - val_auc: 0.6253\n    \n    Epoch 00036: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-36epoch.h5\n    Saved custom checkpoint for epoch 36.\n    Epoch 37/200\n    Learning rate:  0.001\n    67/67 [==============================] - 188s 3s/step - loss: 0.6573 - accuracy: 0.6078 - auc: 0.6502 - val_loss: 0.6706 - val_accuracy: 0.5887 - val_auc: 0.6229\n    \n    Epoch 00037: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-37epoch.h5\n    Saved custom checkpoint for epoch 37.\n    Epoch 38/200\n    Learning rate:  0.001\n    67/67 [==============================] - 192s 3s/step - loss: 0.6574 - accuracy: 0.6098 - auc: 0.6481 - val_loss: 0.6705 - val_accuracy: 0.5933 - val_auc: 0.6240\n    \n    Epoch 00038: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-38epoch.h5\n    Saved custom checkpoint for epoch 38.\n    Epoch 39/200\n    Learning rate:  0.001\n    67/67 [==============================] - 192s 3s/step - loss: 0.6538 - accuracy: 0.6160 - auc: 0.6569 - val_loss: 0.6693 - val_accuracy: 0.5953 - val_auc: 0.6261\n    \n    Epoch 00039: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-39epoch.h5\n    Saved custom checkpoint for epoch 39.\n    Epoch 40/200\n    Learning rate:  0.001\n    67/67 [==============================] - 193s 3s/step - loss: 0.6521 - accuracy: 0.6149 - auc: 0.6608 - val_loss: 0.6700 - val_accuracy: 0.5900 - val_auc: 0.6232\n    \n    Epoch 00040: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-40epoch.h5\n    Saved custom checkpoint for epoch 40.\n    Epoch 41/200\n    Learning rate:  0.001\n    67/67 [==============================] - 192s 3s/step - loss: 0.6605 - accuracy: 0.5978 - auc: 0.6425 - val_loss: 0.6701 - val_accuracy: 0.5900 - val_auc: 0.6256\n    \n    Epoch 00041: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-41epoch.h5\n    Saved custom checkpoint for epoch 41.\n    Epoch 42/200\n    Learning rate:  0.001\n    67/67 [==============================] - 191s 3s/step - loss: 0.6517 - accuracy: 0.6204 - auc: 0.6607 - val_loss: 0.6701 - val_accuracy: 0.5900 - val_auc: 0.6259\n    \n    Epoch 00042: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-42epoch.h5\n    Saved custom checkpoint for epoch 42.\n    Epoch 43/200\n    Learning rate:  0.001\n    67/67 [==============================] - 190s 3s/step - loss: 0.6526 - accuracy: 0.6157 - auc: 0.6583 - val_loss: 0.6704 - val_accuracy: 0.5807 - val_auc: 0.6256\n    \n    Epoch 00043: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-43epoch.h5\n    Saved custom checkpoint for epoch 43.\n    Epoch 44/200\n    Learning rate:  0.001\n    67/67 [==============================] - 192s 3s/step - loss: 0.6536 - accuracy: 0.6150 - auc: 0.6580 - val_loss: 0.6711 - val_accuracy: 0.5847 - val_auc: 0.6231\n    \n    Epoch 00044: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-44epoch.h5\n    Saved custom checkpoint for epoch 44.\n    Epoch 45/200\n    Learning rate:  0.001\n    67/67 [==============================] - 192s 3s/step - loss: 0.6518 - accuracy: 0.6181 - auc: 0.6616 - val_loss: 0.6710 - val_accuracy: 0.5920 - val_auc: 0.6231\n    \n    Epoch 00045: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-45epoch.h5\n    Saved custom checkpoint for epoch 45.\n    Epoch 46/200\n    Learning rate:  0.001\n    67/67 [==============================] - 192s 3s/step - loss: 0.6534 - accuracy: 0.6165 - auc: 0.6562 - val_loss: 0.6717 - val_accuracy: 0.5873 - val_auc: 0.6223\n    \n    Epoch 00046: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-46epoch.h5\n    Saved custom checkpoint for epoch 46.\n    Epoch 47/200\n    Learning rate:  0.001\n    67/67 [==============================] - 190s 3s/step - loss: 0.6537 - accuracy: 0.6136 - auc: 0.6565 - val_loss: 0.6710 - val_accuracy: 0.5813 - val_auc: 0.6255\n    \n    Epoch 00047: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-47epoch.h5\n    Saved custom checkpoint for epoch 47.\n    Epoch 48/200\n    Learning rate:  0.001\n    67/67 [==============================] - 191s 3s/step - loss: 0.6523 - accuracy: 0.6192 - auc: 0.6592 - val_loss: 0.6720 - val_accuracy: 0.5900 - val_auc: 0.6214\n    \n    Epoch 00048: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-48epoch.h5\n    Saved custom checkpoint for epoch 48.\n    Epoch 49/200\n    Learning rate:  0.001\n    67/67 [==============================] - 197s 3s/step - loss: 0.6521 - accuracy: 0.6148 - auc: 0.6583 - val_loss: 0.6719 - val_accuracy: 0.5927 - val_auc: 0.6224\n    \n    Epoch 00049: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-49epoch.h5\n    Saved custom checkpoint for epoch 49.\n    Epoch 50/200\n    Learning rate:  0.001\n    67/67 [==============================] - 199s 3s/step - loss: 0.6507 - accuracy: 0.6202 - auc: 0.6622 - val_loss: 0.6717 - val_accuracy: 0.5913 - val_auc: 0.6222\n    \n    Epoch 00050: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-50epoch.h5\n    Saved custom checkpoint for epoch 50.\n    Epoch 51/200\n    Learning rate:  0.001\n    67/67 [==============================] - 202s 3s/step - loss: 0.6504 - accuracy: 0.6215 - auc: 0.6628 - val_loss: 0.6722 - val_accuracy: 0.5933 - val_auc: 0.6201\n    \n    Epoch 00051: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-51epoch.h5\n    Saved custom checkpoint for epoch 51.\n    Epoch 52/200\n    Learning rate:  0.001\n    67/67 [==============================] - 203s 3s/step - loss: 0.6545 - accuracy: 0.6099 - auc: 0.6540 - val_loss: 0.6726 - val_accuracy: 0.5913 - val_auc: 0.6207\n    \n    Epoch 00052: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-52epoch.h5\n    Saved custom checkpoint for epoch 52.\n    Epoch 53/200\n    Learning rate:  0.001\n    67/67 [==============================] - 201s 3s/step - loss: 0.6539 - accuracy: 0.6093 - auc: 0.6556 - val_loss: 0.6719 - val_accuracy: 0.5933 - val_auc: 0.6235\n    \n    Epoch 00053: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-53epoch.h5\n    Saved custom checkpoint for epoch 53.\n    Epoch 54/200\n    Learning rate:  0.001\n    67/67 [==============================] - 204s 3s/step - loss: 0.6547 - accuracy: 0.6105 - auc: 0.6538 - val_loss: 0.6700 - val_accuracy: 0.5953 - val_auc: 0.6264\n    \n    Epoch 00054: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-54epoch.h5\n    Saved custom checkpoint for epoch 54.\n    Epoch 55/200\n    Learning rate:  0.001\n    67/67 [==============================] - 205s 3s/step - loss: 0.6559 - accuracy: 0.6098 - auc: 0.6503 - val_loss: 0.6720 - val_accuracy: 0.5953 - val_auc: 0.6239\n    \n    Epoch 00055: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-55epoch.h5\n    Saved custom checkpoint for epoch 55.\n    Epoch 56/200\n    Learning rate:  0.001\n    67/67 [==============================] - 201s 3s/step - loss: 0.6498 - accuracy: 0.6276 - auc: 0.6632 - val_loss: 0.6717 - val_accuracy: 0.5927 - val_auc: 0.6238\n    \n    Epoch 00056: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-56epoch.h5\n    Saved custom checkpoint for epoch 56.\n    Epoch 57/200\n    Learning rate:  0.001\n    67/67 [==============================] - 201s 3s/step - loss: 0.6520 - accuracy: 0.6163 - auc: 0.6585 - val_loss: 0.6710 - val_accuracy: 0.5933 - val_auc: 0.6261\n    \n    Epoch 00057: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-57epoch.h5\n    Saved custom checkpoint for epoch 57.\n    Epoch 58/200\n    Learning rate:  0.001\n    67/67 [==============================] - 200s 3s/step - loss: 0.6574 - accuracy: 0.6053 - auc: 0.6502 - val_loss: 0.6712 - val_accuracy: 0.5947 - val_auc: 0.6253\n    \n    Epoch 00058: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-58epoch.h5\n    Saved custom checkpoint for epoch 58.\n    Epoch 59/200\n    Learning rate:  0.001\n    67/67 [==============================] - 200s 3s/step - loss: 0.6487 - accuracy: 0.6246 - auc: 0.6653 - val_loss: 0.6716 - val_accuracy: 0.5947 - val_auc: 0.6244\n    \n    Epoch 00059: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-59epoch.h5\n    Saved custom checkpoint for epoch 59.\n    Epoch 60/200\n    Learning rate:  0.001\n    67/67 [==============================] - 204s 3s/step - loss: 0.6484 - accuracy: 0.6191 - auc: 0.6659 - val_loss: 0.6706 - val_accuracy: 0.5927 - val_auc: 0.6253\n    \n    Epoch 00060: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-60epoch.h5\n    Saved custom checkpoint for epoch 60.\n    Epoch 61/200\n    Learning rate:  0.001\n    67/67 [==============================] - 200s 3s/step - loss: 0.6501 - accuracy: 0.6211 - auc: 0.6633 - val_loss: 0.6704 - val_accuracy: 0.5940 - val_auc: 0.6268\n    \n    Epoch 00061: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-61epoch.h5\n    Saved custom checkpoint for epoch 61.\n    Epoch 62/200\n    Learning rate:  0.001\n    67/67 [==============================] - 198s 3s/step - loss: 0.6479 - accuracy: 0.6171 - auc: 0.6654 - val_loss: 0.6707 - val_accuracy: 0.5920 - val_auc: 0.6266\n    \n    Epoch 00062: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-62epoch.h5\n    Saved custom checkpoint for epoch 62.\n    Epoch 63/200\n    Learning rate:  0.001\n    67/67 [==============================] - 208s 3s/step - loss: 0.6428 - accuracy: 0.6284 - auc: 0.6755 - val_loss: 0.6712 - val_accuracy: 0.5967 - val_auc: 0.6254\n    \n    Epoch 00063: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-63epoch.h5\n    Saved custom checkpoint for epoch 63.\n    Epoch 64/200\n    Learning rate:  0.001\n    67/67 [==============================] - 206s 3s/step - loss: 0.6458 - accuracy: 0.6241 - auc: 0.6704 - val_loss: 0.6704 - val_accuracy: 0.5947 - val_auc: 0.6273\n    \n    Epoch 00064: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-64epoch.h5\n    Saved custom checkpoint for epoch 64.\n    Epoch 65/200\n    Learning rate:  0.001\n    67/67 [==============================] - 198s 3s/step - loss: 0.6471 - accuracy: 0.6193 - auc: 0.6670 - val_loss: 0.6708 - val_accuracy: 0.5927 - val_auc: 0.6285\n    \n    Epoch 00065: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-65epoch.h5\n    Saved custom checkpoint for epoch 65.\n    Epoch 66/200\n    Learning rate:  0.001\n    67/67 [==============================] - 203s 3s/step - loss: 0.6473 - accuracy: 0.6276 - auc: 0.6697 - val_loss: 0.6705 - val_accuracy: 0.5960 - val_auc: 0.6269\n    \n    Epoch 00066: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-66epoch.h5\n    Saved custom checkpoint for epoch 66.\n    Epoch 67/200\n    Learning rate:  0.001\n    67/67 [==============================] - 205s 3s/step - loss: 0.6445 - accuracy: 0.6249 - auc: 0.6716 - val_loss: 0.6701 - val_accuracy: 0.5980 - val_auc: 0.6289\n    \n    Epoch 00067: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-67epoch.h5\n    Saved custom checkpoint for epoch 67.\n    Epoch 68/200\n    Learning rate:  0.001\n    67/67 [==============================] - 205s 3s/step - loss: 0.6489 - accuracy: 0.6179 - auc: 0.6639 - val_loss: 0.6706 - val_accuracy: 0.5973 - val_auc: 0.6288\n    \n    Epoch 00068: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-68epoch.h5\n    Saved custom checkpoint for epoch 68.\n    Epoch 69/200\n    Learning rate:  0.001\n    67/67 [==============================] - 204s 3s/step - loss: 0.6439 - accuracy: 0.6338 - auc: 0.6740 - val_loss: 0.6708 - val_accuracy: 0.5900 - val_auc: 0.6271\n    \n    Epoch 00069: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-69epoch.h5\n    Saved custom checkpoint for epoch 69.\n    Epoch 70/200\n    Learning rate:  0.001\n    67/67 [==============================] - 203s 3s/step - loss: 0.6457 - accuracy: 0.6254 - auc: 0.6693 - val_loss: 0.6716 - val_accuracy: 0.5967 - val_auc: 0.6281\n    \n    Epoch 00070: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-70epoch.h5\n    Saved custom checkpoint for epoch 70.\n    Epoch 71/200\n    Learning rate:  0.001\n    67/67 [==============================] - 194s 3s/step - loss: 0.6473 - accuracy: 0.6292 - auc: 0.6693 - val_loss: 0.6722 - val_accuracy: 0.5920 - val_auc: 0.6275\n    \n    Epoch 00071: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-71epoch.h5\n    Saved custom checkpoint for epoch 71.\n    Epoch 72/200\n    Learning rate:  0.001\n    67/67 [==============================] - 202s 3s/step - loss: 0.6525 - accuracy: 0.6189 - auc: 0.6596 - val_loss: 0.6701 - val_accuracy: 0.5993 - val_auc: 0.6293\n    \n    Epoch 00072: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-72epoch.h5\n    Saved custom checkpoint for epoch 72.\n    Epoch 73/200\n    Learning rate:  0.001\n    67/67 [==============================] - 195s 3s/step - loss: 0.6468 - accuracy: 0.6236 - auc: 0.6693 - val_loss: 0.6738 - val_accuracy: 0.5967 - val_auc: 0.6247\n    \n    Epoch 00073: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-73epoch.h5\n    Saved custom checkpoint for epoch 73.\n    Epoch 74/200\n    Learning rate:  0.001\n    67/67 [==============================] - 194s 3s/step - loss: 0.6419 - accuracy: 0.6339 - auc: 0.6767 - val_loss: 0.6716 - val_accuracy: 0.6013 - val_auc: 0.6256\n    \n    Epoch 00074: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-74epoch.h5\n    Saved custom checkpoint for epoch 74.\n    Epoch 75/200\n    Learning rate:  0.001\n    67/67 [==============================] - 190s 3s/step - loss: 0.6470 - accuracy: 0.6177 - auc: 0.6667 - val_loss: 0.6714 - val_accuracy: 0.5960 - val_auc: 0.6278\n    \n    Epoch 00075: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-75epoch.h5\n    Saved custom checkpoint for epoch 75.\n    Epoch 76/200\n    Learning rate:  0.001\n    67/67 [==============================] - 187s 3s/step - loss: 0.6525 - accuracy: 0.6144 - auc: 0.6591 - val_loss: 0.6727 - val_accuracy: 0.5973 - val_auc: 0.6282\n    \n    Epoch 00076: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-76epoch.h5\n    Saved custom checkpoint for epoch 76.\n    Epoch 77/200\n    Learning rate:  0.001\n    67/67 [==============================] - 196s 3s/step - loss: 0.6442 - accuracy: 0.6265 - auc: 0.6731 - val_loss: 0.6725 - val_accuracy: 0.5980 - val_auc: 0.6269\n    \n    Epoch 00077: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-77epoch.h5\n    Saved custom checkpoint for epoch 77.\n    Epoch 78/200\n    Learning rate:  0.001\n    67/67 [==============================] - 194s 3s/step - loss: 0.6459 - accuracy: 0.6257 - auc: 0.6706 - val_loss: 0.6726 - val_accuracy: 0.5987 - val_auc: 0.6271\n    \n    Epoch 00078: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-78epoch.h5\n    Saved custom checkpoint for epoch 78.\n    Epoch 79/200\n    Learning rate:  0.001\n    67/67 [==============================] - 202s 3s/step - loss: 0.6478 - accuracy: 0.6313 - auc: 0.6671 - val_loss: 0.6722 - val_accuracy: 0.5980 - val_auc: 0.6276\n    \n    Epoch 00079: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-79epoch.h5\n    Saved custom checkpoint for epoch 79.\n    Epoch 80/200\n    Learning rate:  0.001\n    67/67 [==============================] - 198s 3s/step - loss: 0.6430 - accuracy: 0.6255 - auc: 0.6737 - val_loss: 0.6723 - val_accuracy: 0.5993 - val_auc: 0.6266\n    \n    Epoch 00080: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-80epoch.h5\n    Saved custom checkpoint for epoch 80.\n    Epoch 81/200\n    Learning rate:  0.001\n    67/67 [==============================] - 208s 3s/step - loss: 0.6456 - accuracy: 0.6235 - auc: 0.6707 - val_loss: 0.6722 - val_accuracy: 0.5980 - val_auc: 0.6279\n    \n    Epoch 00081: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-81epoch.h5\n    Saved custom checkpoint for epoch 81.\n    Epoch 82/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 215s 3s/step - loss: 0.6441 - accuracy: 0.6334 - auc: 0.6746 - val_loss: 0.6722 - val_accuracy: 0.5987 - val_auc: 0.6278\n    \n    Epoch 00082: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-82epoch.h5\n    Saved custom checkpoint for epoch 82.\n    Epoch 83/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 194s 3s/step - loss: 0.6415 - accuracy: 0.6299 - auc: 0.6791 - val_loss: 0.6722 - val_accuracy: 0.5973 - val_auc: 0.6279\n    \n    Epoch 00083: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-83epoch.h5\n    Saved custom checkpoint for epoch 83.\n    Epoch 84/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 193s 3s/step - loss: 0.6447 - accuracy: 0.6308 - auc: 0.6736 - val_loss: 0.6722 - val_accuracy: 0.5973 - val_auc: 0.6278\n    \n    Epoch 00084: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-84epoch.h5\n    Saved custom checkpoint for epoch 84.\n    Epoch 85/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 192s 3s/step - loss: 0.6431 - accuracy: 0.6269 - auc: 0.6732 - val_loss: 0.6723 - val_accuracy: 0.5973 - val_auc: 0.6282\n    \n    Epoch 00085: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-85epoch.h5\n    Saved custom checkpoint for epoch 85.\n    Epoch 86/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 194s 3s/step - loss: 0.6366 - accuracy: 0.6409 - auc: 0.6877 - val_loss: 0.6723 - val_accuracy: 0.6013 - val_auc: 0.6278\n    \n    Epoch 00086: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-86epoch.h5\n    Saved custom checkpoint for epoch 86.\n    Epoch 87/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 197s 3s/step - loss: 0.6403 - accuracy: 0.6322 - auc: 0.6793 - val_loss: 0.6722 - val_accuracy: 0.5987 - val_auc: 0.6281\n    \n    Epoch 00087: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-87epoch.h5\n    Saved custom checkpoint for epoch 87.\n    Epoch 88/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 197s 3s/step - loss: 0.6473 - accuracy: 0.6214 - auc: 0.6661 - val_loss: 0.6722 - val_accuracy: 0.5973 - val_auc: 0.6278\n    \n    Epoch 00088: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-88epoch.h5\n    Saved custom checkpoint for epoch 88.\n    Epoch 89/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 197s 3s/step - loss: 0.6421 - accuracy: 0.6311 - auc: 0.6765 - val_loss: 0.6723 - val_accuracy: 0.5987 - val_auc: 0.6280\n    \n    Epoch 00089: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-89epoch.h5\n    Saved custom checkpoint for epoch 89.\n    Epoch 90/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 200s 3s/step - loss: 0.6413 - accuracy: 0.6308 - auc: 0.6779 - val_loss: 0.6722 - val_accuracy: 0.5987 - val_auc: 0.6277\n    \n    Epoch 00090: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-90epoch.h5\n    Saved custom checkpoint for epoch 90.\n    Epoch 91/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 200s 3s/step - loss: 0.6444 - accuracy: 0.6266 - auc: 0.6717 - val_loss: 0.6721 - val_accuracy: 0.5980 - val_auc: 0.6280\n    \n    Epoch 00091: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-91epoch.h5\n    Saved custom checkpoint for epoch 91.\n    Epoch 92/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 199s 3s/step - loss: 0.6418 - accuracy: 0.6243 - auc: 0.6745 - val_loss: 0.6723 - val_accuracy: 0.5973 - val_auc: 0.6278\n    \n    Epoch 00092: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-92epoch.h5\n    Saved custom checkpoint for epoch 92.\n    Epoch 93/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 200s 3s/step - loss: 0.6442 - accuracy: 0.6265 - auc: 0.6724 - val_loss: 0.6721 - val_accuracy: 0.5987 - val_auc: 0.6282\n    \n    Epoch 00093: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-93epoch.h5\n    Saved custom checkpoint for epoch 93.\n    Epoch 94/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 198s 3s/step - loss: 0.6438 - accuracy: 0.6279 - auc: 0.6725 - val_loss: 0.6723 - val_accuracy: 0.5980 - val_auc: 0.6281\n    \n    Epoch 00094: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-94epoch.h5\n    Saved custom checkpoint for epoch 94.\n    Epoch 95/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 204s 3s/step - loss: 0.6410 - accuracy: 0.6360 - auc: 0.6786 - val_loss: 0.6722 - val_accuracy: 0.5973 - val_auc: 0.6279\n    \n    Epoch 00095: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-95epoch.h5\n    Saved custom checkpoint for epoch 95.\n    Epoch 96/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 195s 3s/step - loss: 0.6448 - accuracy: 0.6279 - auc: 0.6723 - val_loss: 0.6723 - val_accuracy: 0.5973 - val_auc: 0.6276\n    \n    Epoch 00096: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-96epoch.h5\n    Saved custom checkpoint for epoch 96.\n    Epoch 97/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 194s 3s/step - loss: 0.6425 - accuracy: 0.6311 - auc: 0.6776 - val_loss: 0.6723 - val_accuracy: 0.5980 - val_auc: 0.6278\n    \n    Epoch 00097: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-97epoch.h5\n    Saved custom checkpoint for epoch 97.\n    Epoch 98/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 189s 3s/step - loss: 0.6462 - accuracy: 0.6285 - auc: 0.6693 - val_loss: 0.6722 - val_accuracy: 0.5987 - val_auc: 0.6277\n    \n    Epoch 00098: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-98epoch.h5\n    Saved custom checkpoint for epoch 98.\n    Epoch 99/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 188s 3s/step - loss: 0.6410 - accuracy: 0.6300 - auc: 0.6773 - val_loss: 0.6722 - val_accuracy: 0.5980 - val_auc: 0.6278\n    \n    Epoch 00099: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-99epoch.h5\n    Saved custom checkpoint for epoch 99.\n    Epoch 100/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 190s 3s/step - loss: 0.6436 - accuracy: 0.6294 - auc: 0.6730 - val_loss: 0.6723 - val_accuracy: 0.5973 - val_auc: 0.6280\n    \n    Epoch 00100: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-100epoch.h5\n    Saved custom checkpoint for epoch 100.\n    Epoch 101/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 190s 3s/step - loss: 0.6425 - accuracy: 0.6345 - auc: 0.6752 - val_loss: 0.6724 - val_accuracy: 0.5967 - val_auc: 0.6280\n    \n    Epoch 00101: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-101epoch.h5\n    Saved custom checkpoint for epoch 101.\n    Epoch 102/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 189s 3s/step - loss: 0.6390 - accuracy: 0.6331 - auc: 0.6801 - val_loss: 0.6722 - val_accuracy: 0.5973 - val_auc: 0.6284\n    \n    Epoch 00102: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-102epoch.h5\n    Saved custom checkpoint for epoch 102.\n    Epoch 103/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 188s 3s/step - loss: 0.6416 - accuracy: 0.6357 - auc: 0.6772 - val_loss: 0.6723 - val_accuracy: 0.5973 - val_auc: 0.6280\n    \n    Epoch 00103: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-103epoch.h5\n    Saved custom checkpoint for epoch 103.\n    Epoch 104/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 189s 3s/step - loss: 0.6439 - accuracy: 0.6310 - auc: 0.6747 - val_loss: 0.6721 - val_accuracy: 0.6007 - val_auc: 0.6283\n    \n    Epoch 00104: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-104epoch.h5\n    Saved custom checkpoint for epoch 104.\n    Epoch 105/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 189s 3s/step - loss: 0.6448 - accuracy: 0.6231 - auc: 0.6689 - val_loss: 0.6724 - val_accuracy: 0.5973 - val_auc: 0.6279\n    \n    Epoch 00105: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-105epoch.h5\n    Saved custom checkpoint for epoch 105.\n    Epoch 106/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 189s 3s/step - loss: 0.6412 - accuracy: 0.6269 - auc: 0.6751 - val_loss: 0.6723 - val_accuracy: 0.5987 - val_auc: 0.6281\n    \n    Epoch 00106: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-106epoch.h5\n    Saved custom checkpoint for epoch 106.\n    Epoch 107/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 189s 3s/step - loss: 0.6432 - accuracy: 0.6318 - auc: 0.6744 - val_loss: 0.6723 - val_accuracy: 0.5987 - val_auc: 0.6284\n    \n    Epoch 00107: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-107epoch.h5\n    Saved custom checkpoint for epoch 107.\n    Epoch 108/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 191s 3s/step - loss: 0.6443 - accuracy: 0.6300 - auc: 0.6721 - val_loss: 0.6723 - val_accuracy: 0.5973 - val_auc: 0.6282\n    \n    Epoch 00108: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-108epoch.h5\n    Saved custom checkpoint for epoch 108.\n    Epoch 109/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 200s 3s/step - loss: 0.6392 - accuracy: 0.6384 - auc: 0.6834 - val_loss: 0.6724 - val_accuracy: 0.5967 - val_auc: 0.6282\n    \n    Epoch 00109: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-109epoch.h5\n    Saved custom checkpoint for epoch 109.\n    Epoch 110/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 205s 3s/step - loss: 0.6387 - accuracy: 0.6369 - auc: 0.6836 - val_loss: 0.6723 - val_accuracy: 0.5993 - val_auc: 0.6283\n    \n    Epoch 00110: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-110epoch.h5\n    Saved custom checkpoint for epoch 110.\n    Epoch 111/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 210s 3s/step - loss: 0.6432 - accuracy: 0.6315 - auc: 0.6745 - val_loss: 0.6724 - val_accuracy: 0.5967 - val_auc: 0.6283\n    \n    Epoch 00111: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-111epoch.h5\n    Saved custom checkpoint for epoch 111.\n    Epoch 112/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 215s 3s/step - loss: 0.6445 - accuracy: 0.6310 - auc: 0.6731 - val_loss: 0.6725 - val_accuracy: 0.5973 - val_auc: 0.6283\n    \n    Epoch 00112: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-112epoch.h5\n    Saved custom checkpoint for epoch 112.\n    Epoch 113/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 205s 3s/step - loss: 0.6456 - accuracy: 0.6232 - auc: 0.6696 - val_loss: 0.6724 - val_accuracy: 0.5993 - val_auc: 0.6284\n    \n    Epoch 00113: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-113epoch.h5\n    Saved custom checkpoint for epoch 113.\n    Epoch 114/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 210s 3s/step - loss: 0.6421 - accuracy: 0.6362 - auc: 0.6764 - val_loss: 0.6724 - val_accuracy: 0.5987 - val_auc: 0.6281\n    \n    Epoch 00114: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-114epoch.h5\n    Saved custom checkpoint for epoch 114.\n    Epoch 115/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 213s 3s/step - loss: 0.6352 - accuracy: 0.6416 - auc: 0.6897 - val_loss: 0.6725 - val_accuracy: 0.5993 - val_auc: 0.6280\n    \n    Epoch 00115: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-115epoch.h5\n    Saved custom checkpoint for epoch 115.\n    Epoch 116/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 216s 3s/step - loss: 0.6395 - accuracy: 0.6321 - auc: 0.6792 - val_loss: 0.6726 - val_accuracy: 0.5980 - val_auc: 0.6282\n    \n    Epoch 00116: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-116epoch.h5\n    Saved custom checkpoint for epoch 116.\n    Epoch 117/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 208s 3s/step - loss: 0.6433 - accuracy: 0.6323 - auc: 0.6746 - val_loss: 0.6724 - val_accuracy: 0.5987 - val_auc: 0.6282\n    \n    Epoch 00117: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-117epoch.h5\n    Saved custom checkpoint for epoch 117.\n    Epoch 118/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 198s 3s/step - loss: 0.6400 - accuracy: 0.6326 - auc: 0.6800 - val_loss: 0.6725 - val_accuracy: 0.6007 - val_auc: 0.6283\n    \n    Epoch 00118: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-118epoch.h5\n    Saved custom checkpoint for epoch 118.\n    Epoch 119/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 197s 3s/step - loss: 0.6358 - accuracy: 0.6410 - auc: 0.6873 - val_loss: 0.6725 - val_accuracy: 0.5980 - val_auc: 0.6284\n    \n    Epoch 00119: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-119epoch.h5\n    Saved custom checkpoint for epoch 119.\n    Epoch 120/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 197s 3s/step - loss: 0.6419 - accuracy: 0.6325 - auc: 0.6769 - val_loss: 0.6725 - val_accuracy: 0.6000 - val_auc: 0.6282\n    \n    Epoch 00120: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-120epoch.h5\n    Saved custom checkpoint for epoch 120.\n    Epoch 121/200\n    Learning rate:  0.0001\n    67/67 [==============================] - 200s 3s/step - loss: 0.6404 - accuracy: 0.6296 - auc: 0.6790 - val_loss: 0.6724 - val_accuracy: 0.6007 - val_auc: 0.6285\n    \n    Epoch 00121: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-121epoch.h5\n    Saved custom checkpoint for epoch 121.\n    Epoch 122/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 201s 3s/step - loss: 0.6391 - accuracy: 0.6341 - auc: 0.6816 - val_loss: 0.6724 - val_accuracy: 0.6007 - val_auc: 0.6286\n    \n    Epoch 00122: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-122epoch.h5\n    Saved custom checkpoint for epoch 122.\n    Epoch 123/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 198s 3s/step - loss: 0.6420 - accuracy: 0.6275 - auc: 0.6764 - val_loss: 0.6724 - val_accuracy: 0.6007 - val_auc: 0.6286\n    \n    Epoch 00123: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-123epoch.h5\n    Saved custom checkpoint for epoch 123.\n    Epoch 124/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 202s 3s/step - loss: 0.6452 - accuracy: 0.6225 - auc: 0.6699 - val_loss: 0.6724 - val_accuracy: 0.6007 - val_auc: 0.6285\n    \n    Epoch 00124: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-124epoch.h5\n    Saved custom checkpoint for epoch 124.\n    Epoch 125/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 204s 3s/step - loss: 0.6359 - accuracy: 0.6339 - auc: 0.6850 - val_loss: 0.6724 - val_accuracy: 0.6000 - val_auc: 0.6285\n    \n    Epoch 00125: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-125epoch.h5\n    Saved custom checkpoint for epoch 125.\n    Epoch 126/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 202s 3s/step - loss: 0.6377 - accuracy: 0.6375 - auc: 0.6836 - val_loss: 0.6724 - val_accuracy: 0.6007 - val_auc: 0.6285\n    \n    Epoch 00126: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-126epoch.h5\n    Saved custom checkpoint for epoch 126.\n    Epoch 127/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 203s 3s/step - loss: 0.6396 - accuracy: 0.6359 - auc: 0.6806 - val_loss: 0.6724 - val_accuracy: 0.6007 - val_auc: 0.6284\n    \n    Epoch 00127: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-127epoch.h5\n    Saved custom checkpoint for epoch 127.\n    Epoch 128/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 199s 3s/step - loss: 0.6484 - accuracy: 0.6211 - auc: 0.6648 - val_loss: 0.6724 - val_accuracy: 0.6000 - val_auc: 0.6285\n    \n    Epoch 00128: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-128epoch.h5\n    Saved custom checkpoint for epoch 128.\n    Epoch 129/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 198s 3s/step - loss: 0.6366 - accuracy: 0.6406 - auc: 0.6860 - val_loss: 0.6724 - val_accuracy: 0.6007 - val_auc: 0.6284\n    \n    Epoch 00129: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-129epoch.h5\n    Saved custom checkpoint for epoch 129.\n    Epoch 130/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 200s 3s/step - loss: 0.6411 - accuracy: 0.6287 - auc: 0.6773 - val_loss: 0.6724 - val_accuracy: 0.6000 - val_auc: 0.6283\n    \n    Epoch 00130: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-130epoch.h5\n    Saved custom checkpoint for epoch 130.\n    Epoch 131/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 196s 3s/step - loss: 0.6461 - accuracy: 0.6239 - auc: 0.6690 - val_loss: 0.6724 - val_accuracy: 0.6000 - val_auc: 0.6283\n    \n    Epoch 00131: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-131epoch.h5\n    Saved custom checkpoint for epoch 131.\n    Epoch 132/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 197s 3s/step - loss: 0.6358 - accuracy: 0.6371 - auc: 0.6862 - val_loss: 0.6724 - val_accuracy: 0.6000 - val_auc: 0.6282\n    \n    Epoch 00132: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-132epoch.h5\n    Saved custom checkpoint for epoch 132.\n    Epoch 133/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 202s 3s/step - loss: 0.6424 - accuracy: 0.6302 - auc: 0.6746 - val_loss: 0.6724 - val_accuracy: 0.6007 - val_auc: 0.6285\n    \n    Epoch 00133: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-133epoch.h5\n    Saved custom checkpoint for epoch 133.\n    Epoch 134/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 209s 3s/step - loss: 0.6420 - accuracy: 0.6289 - auc: 0.6754 - val_loss: 0.6724 - val_accuracy: 0.6000 - val_auc: 0.6284\n    \n    Epoch 00134: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-134epoch.h5\n    Saved custom checkpoint for epoch 134.\n    Epoch 135/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 202s 3s/step - loss: 0.6427 - accuracy: 0.6310 - auc: 0.6741 - val_loss: 0.6724 - val_accuracy: 0.6013 - val_auc: 0.6284\n    \n    Epoch 00135: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-135epoch.h5\n    Saved custom checkpoint for epoch 135.\n    Epoch 136/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 197s 3s/step - loss: 0.6420 - accuracy: 0.6322 - auc: 0.6756 - val_loss: 0.6725 - val_accuracy: 0.5993 - val_auc: 0.6282\n    \n    Epoch 00136: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-136epoch.h5\n    Saved custom checkpoint for epoch 136.\n    Epoch 137/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 197s 3s/step - loss: 0.6451 - accuracy: 0.6292 - auc: 0.6716 - val_loss: 0.6725 - val_accuracy: 0.5993 - val_auc: 0.6284\n    \n    Epoch 00137: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-137epoch.h5\n    Saved custom checkpoint for epoch 137.\n    Epoch 138/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 196s 3s/step - loss: 0.6397 - accuracy: 0.6308 - auc: 0.6799 - val_loss: 0.6725 - val_accuracy: 0.5993 - val_auc: 0.6283\n    \n    Epoch 00138: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-138epoch.h5\n    Saved custom checkpoint for epoch 138.\n    Epoch 139/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 195s 3s/step - loss: 0.6430 - accuracy: 0.6307 - auc: 0.6751 - val_loss: 0.6725 - val_accuracy: 0.5993 - val_auc: 0.6282\n    \n    Epoch 00139: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-139epoch.h5\n    Saved custom checkpoint for epoch 139.\n    Epoch 140/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 196s 3s/step - loss: 0.6461 - accuracy: 0.6199 - auc: 0.6671 - val_loss: 0.6725 - val_accuracy: 0.5993 - val_auc: 0.6284\n    \n    Epoch 00140: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-140epoch.h5\n    Saved custom checkpoint for epoch 140.\n    Epoch 141/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 197s 3s/step - loss: 0.6451 - accuracy: 0.6250 - auc: 0.6710 - val_loss: 0.6725 - val_accuracy: 0.5993 - val_auc: 0.6284\n    \n    Epoch 00141: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-141epoch.h5\n    Saved custom checkpoint for epoch 141.\n    Epoch 142/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 200s 3s/step - loss: 0.6412 - accuracy: 0.6343 - auc: 0.6787 - val_loss: 0.6725 - val_accuracy: 0.5993 - val_auc: 0.6282\n    \n    Epoch 00142: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-142epoch.h5\n    Saved custom checkpoint for epoch 142.\n    Epoch 143/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 198s 3s/step - loss: 0.6416 - accuracy: 0.6317 - auc: 0.6769 - val_loss: 0.6725 - val_accuracy: 0.5993 - val_auc: 0.6282\n    \n    Epoch 00143: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-143epoch.h5\n    Saved custom checkpoint for epoch 143.\n    Epoch 144/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 196s 3s/step - loss: 0.6410 - accuracy: 0.6316 - auc: 0.6784 - val_loss: 0.6725 - val_accuracy: 0.6000 - val_auc: 0.6284\n    \n    Epoch 00144: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-144epoch.h5\n    Saved custom checkpoint for epoch 144.\n    Epoch 145/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 198s 3s/step - loss: 0.6458 - accuracy: 0.6288 - auc: 0.6716 - val_loss: 0.6725 - val_accuracy: 0.6000 - val_auc: 0.6283\n    \n    Epoch 00145: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-145epoch.h5\n    Saved custom checkpoint for epoch 145.\n    Epoch 146/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 202s 3s/step - loss: 0.6404 - accuracy: 0.6294 - auc: 0.6769 - val_loss: 0.6725 - val_accuracy: 0.5993 - val_auc: 0.6283\n    \n    Epoch 00146: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-146epoch.h5\n    Saved custom checkpoint for epoch 146.\n    Epoch 147/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 199s 3s/step - loss: 0.6383 - accuracy: 0.6346 - auc: 0.6841 - val_loss: 0.6725 - val_accuracy: 0.6000 - val_auc: 0.6284\n    \n    Epoch 00147: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-147epoch.h5\n    Saved custom checkpoint for epoch 147.\n    Epoch 148/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 217s 3s/step - loss: 0.6374 - accuracy: 0.6365 - auc: 0.6832 - val_loss: 0.6725 - val_accuracy: 0.6000 - val_auc: 0.6284\n    \n    Epoch 00148: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-148epoch.h5\n    Saved custom checkpoint for epoch 148.\n    Epoch 149/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 217s 3s/step - loss: 0.6392 - accuracy: 0.6417 - auc: 0.6809 - val_loss: 0.6725 - val_accuracy: 0.5993 - val_auc: 0.6283\n    \n    Epoch 00149: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-149epoch.h5\n    Saved custom checkpoint for epoch 149.\n    Epoch 150/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 195s 3s/step - loss: 0.6364 - accuracy: 0.6406 - auc: 0.6858 - val_loss: 0.6725 - val_accuracy: 0.6000 - val_auc: 0.6283\n    \n    Epoch 00150: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-150epoch.h5\n    Saved custom checkpoint for epoch 150.\n    Epoch 151/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 195s 3s/step - loss: 0.6397 - accuracy: 0.6360 - auc: 0.6804 - val_loss: 0.6725 - val_accuracy: 0.5993 - val_auc: 0.6283\n    \n    Epoch 00151: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-151epoch.h5\n    Saved custom checkpoint for epoch 151.\n    Epoch 152/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 195s 3s/step - loss: 0.6442 - accuracy: 0.6288 - auc: 0.6723 - val_loss: 0.6725 - val_accuracy: 0.6000 - val_auc: 0.6284\n    \n    Epoch 00152: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-152epoch.h5\n    Saved custom checkpoint for epoch 152.\n    Epoch 153/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 197s 3s/step - loss: 0.6434 - accuracy: 0.6240 - auc: 0.6732 - val_loss: 0.6725 - val_accuracy: 0.6000 - val_auc: 0.6285\n    \n    Epoch 00153: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-153epoch.h5\n    Saved custom checkpoint for epoch 153.\n    Epoch 154/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 203s 3s/step - loss: 0.6431 - accuracy: 0.6314 - auc: 0.6752 - val_loss: 0.6725 - val_accuracy: 0.6000 - val_auc: 0.6283\n    \n    Epoch 00154: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-154epoch.h5\n    Saved custom checkpoint for epoch 154.\n    Epoch 155/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 196s 3s/step - loss: 0.6458 - accuracy: 0.6276 - auc: 0.6700 - val_loss: 0.6725 - val_accuracy: 0.6000 - val_auc: 0.6284\n    \n    Epoch 00155: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-155epoch.h5\n    Saved custom checkpoint for epoch 155.\n    Epoch 156/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 198s 3s/step - loss: 0.6414 - accuracy: 0.6301 - auc: 0.6765 - val_loss: 0.6725 - val_accuracy: 0.6007 - val_auc: 0.6284\n    \n    Epoch 00156: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-156epoch.h5\n    Saved custom checkpoint for epoch 156.\n    Epoch 157/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 197s 3s/step - loss: 0.6424 - accuracy: 0.6300 - auc: 0.6752 - val_loss: 0.6725 - val_accuracy: 0.6007 - val_auc: 0.6284\n    \n    Epoch 00157: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-157epoch.h5\n    Saved custom checkpoint for epoch 157.\n    Epoch 158/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 200s 3s/step - loss: 0.6430 - accuracy: 0.6324 - auc: 0.6749 - val_loss: 0.6725 - val_accuracy: 0.6000 - val_auc: 0.6283\n    \n    Epoch 00158: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-158epoch.h5\n    Saved custom checkpoint for epoch 158.\n    Epoch 159/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 208s 3s/step - loss: 0.6409 - accuracy: 0.6308 - auc: 0.6768 - val_loss: 0.6725 - val_accuracy: 0.6007 - val_auc: 0.6284\n    \n    Epoch 00159: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-159epoch.h5\n    Saved custom checkpoint for epoch 159.\n    Epoch 160/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 215s 3s/step - loss: 0.6385 - accuracy: 0.6312 - auc: 0.6823 - val_loss: 0.6725 - val_accuracy: 0.6000 - val_auc: 0.6284\n    \n    Epoch 00160: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-160epoch.h5\n    Saved custom checkpoint for epoch 160.\n    Epoch 161/200\n    Learning rate:  1e-05\n    67/67 [==============================] - 208s 3s/step - loss: 0.6377 - accuracy: 0.6332 - auc: 0.6839 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00161: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-161epoch.h5\n    Saved custom checkpoint for epoch 161.\n    Epoch 162/200\n    Learning rate:  1e-06\n    67/67 [==============================] - 195s 3s/step - loss: 0.6411 - accuracy: 0.6311 - auc: 0.6771 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00162: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-162epoch.h5\n    Saved custom checkpoint for epoch 162.\n    Epoch 163/200\n    Learning rate:  1e-06\n    67/67 [==============================] - 195s 3s/step - loss: 0.6433 - accuracy: 0.6295 - auc: 0.6764 - val_loss: 0.6725 - val_accuracy: 0.6007 - val_auc: 0.6284\n    \n    Epoch 00163: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-163epoch.h5\n    Saved custom checkpoint for epoch 163.\n    Epoch 164/200\n    Learning rate:  1e-06\n    67/67 [==============================] - 196s 3s/step - loss: 0.6417 - accuracy: 0.6280 - auc: 0.6772 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00164: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-164epoch.h5\n    Saved custom checkpoint for epoch 164.\n    Epoch 165/200\n    Learning rate:  1e-06\n    67/67 [==============================] - 198s 3s/step - loss: 0.6460 - accuracy: 0.6242 - auc: 0.6686 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00165: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-165epoch.h5\n    Saved custom checkpoint for epoch 165.\n    Epoch 166/200\n    Learning rate:  1e-06\n    67/67 [==============================] - 198s 3s/step - loss: 0.6442 - accuracy: 0.6294 - auc: 0.6730 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6284\n    \n    Epoch 00166: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-166epoch.h5\n    Saved custom checkpoint for epoch 166.\n    Epoch 167/200\n    Learning rate:  1e-06\n    67/67 [==============================] - 197s 3s/step - loss: 0.6394 - accuracy: 0.6333 - auc: 0.6783 - val_loss: 0.6725 - val_accuracy: 0.6007 - val_auc: 0.6284\n    \n    Epoch 00167: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-167epoch.h5\n    Saved custom checkpoint for epoch 167.\n    Epoch 168/200\n    Learning rate:  1e-06\n    67/67 [==============================] - 195s 3s/step - loss: 0.6426 - accuracy: 0.6306 - auc: 0.6765 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00168: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-168epoch.h5\n    Saved custom checkpoint for epoch 168.\n    Epoch 169/200\n    Learning rate:  1e-06\n    67/67 [==============================] - 191s 3s/step - loss: 0.6430 - accuracy: 0.6252 - auc: 0.6738 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00169: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-169epoch.h5\n    Saved custom checkpoint for epoch 169.\n    Epoch 170/200\n    Learning rate:  1e-06\n    67/67 [==============================] - 187s 3s/step - loss: 0.6415 - accuracy: 0.6293 - auc: 0.6762 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6284\n    \n    Epoch 00170: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-170epoch.h5\n    Saved custom checkpoint for epoch 170.\n    Epoch 171/200\n    Learning rate:  1e-06\n    67/67 [==============================] - 188s 3s/step - loss: 0.6436 - accuracy: 0.6285 - auc: 0.6743 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6284\n    \n    Epoch 00171: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-171epoch.h5\n    Saved custom checkpoint for epoch 171.\n    Epoch 172/200\n    Learning rate:  1e-06\n    67/67 [==============================] - 188s 3s/step - loss: 0.6430 - accuracy: 0.6315 - auc: 0.6746 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6284\n    \n    Epoch 00172: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-172epoch.h5\n    Saved custom checkpoint for epoch 172.\n    Epoch 173/200\n    Learning rate:  1e-06\n    67/67 [==============================] - 194s 3s/step - loss: 0.6389 - accuracy: 0.6315 - auc: 0.6831 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6284\n    \n    Epoch 00173: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-173epoch.h5\n    Saved custom checkpoint for epoch 173.\n    Epoch 174/200\n    Learning rate:  1e-06\n    67/67 [==============================] - 196s 3s/step - loss: 0.6378 - accuracy: 0.6361 - auc: 0.6835 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00174: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-174epoch.h5\n    Saved custom checkpoint for epoch 174.\n    Epoch 175/200\n    Learning rate:  1e-06\n    67/67 [==============================] - 195s 3s/step - loss: 0.6398 - accuracy: 0.6346 - auc: 0.6808 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00175: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-175epoch.h5\n    Saved custom checkpoint for epoch 175.\n    Epoch 176/200\n    Learning rate:  1e-06\n    67/67 [==============================] - 195s 3s/step - loss: 0.6403 - accuracy: 0.6352 - auc: 0.6796 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6284\n    \n    Epoch 00176: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-176epoch.h5\n    Saved custom checkpoint for epoch 176.\n    Epoch 177/200\n    Learning rate:  1e-06\n    67/67 [==============================] - 194s 3s/step - loss: 0.6417 - accuracy: 0.6278 - auc: 0.6768 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6284\n    \n    Epoch 00177: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-177epoch.h5\n    Saved custom checkpoint for epoch 177.\n    Epoch 178/200\n    Learning rate:  1e-06\n    67/67 [==============================] - 196s 3s/step - loss: 0.6393 - accuracy: 0.6372 - auc: 0.6836 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00178: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-178epoch.h5\n    Saved custom checkpoint for epoch 178.\n    Epoch 179/200\n    Learning rate:  1e-06\n    67/67 [==============================] - 199s 3s/step - loss: 0.6393 - accuracy: 0.6345 - auc: 0.6807 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00179: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-179epoch.h5\n    Saved custom checkpoint for epoch 179.\n    Epoch 180/200\n    Learning rate:  1e-06\n    67/67 [==============================] - 211s 3s/step - loss: 0.6437 - accuracy: 0.6286 - auc: 0.6758 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00180: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-180epoch.h5\n    Saved custom checkpoint for epoch 180.\n    Epoch 181/200\n    Learning rate:  1e-06\n    67/67 [==============================] - 212s 3s/step - loss: 0.6462 - accuracy: 0.6245 - auc: 0.6698 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6284\n    \n    Epoch 00181: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-181epoch.h5\n    Saved custom checkpoint for epoch 181.\n    Epoch 182/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 213s 3s/step - loss: 0.6479 - accuracy: 0.6209 - auc: 0.6646 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00182: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-182epoch.h5\n    Saved custom checkpoint for epoch 182.\n    Epoch 183/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 204s 3s/step - loss: 0.6410 - accuracy: 0.6319 - auc: 0.6781 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6284\n    \n    Epoch 00183: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-183epoch.h5\n    Saved custom checkpoint for epoch 183.\n    Epoch 184/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 205s 3s/step - loss: 0.6427 - accuracy: 0.6242 - auc: 0.6729 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6284\n    \n    Epoch 00184: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-184epoch.h5\n    Saved custom checkpoint for epoch 184.\n    Epoch 185/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 205s 3s/step - loss: 0.6425 - accuracy: 0.6297 - auc: 0.6748 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6284\n    \n    Epoch 00185: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-185epoch.h5\n    Saved custom checkpoint for epoch 185.\n    Epoch 186/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 220s 3s/step - loss: 0.6418 - accuracy: 0.6328 - auc: 0.6767 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00186: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-186epoch.h5\n    Saved custom checkpoint for epoch 186.\n    Epoch 187/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 222s 3s/step - loss: 0.6421 - accuracy: 0.6342 - auc: 0.6784 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00187: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-187epoch.h5\n    Saved custom checkpoint for epoch 187.\n    Epoch 188/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 202s 3s/step - loss: 0.6438 - accuracy: 0.6289 - auc: 0.6717 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00188: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-188epoch.h5\n    Saved custom checkpoint for epoch 188.\n    Epoch 189/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 203s 3s/step - loss: 0.6398 - accuracy: 0.6352 - auc: 0.6791 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6284\n    \n    Epoch 00189: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-189epoch.h5\n    Saved custom checkpoint for epoch 189.\n    Epoch 190/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 206s 3s/step - loss: 0.6418 - accuracy: 0.6287 - auc: 0.6759 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00190: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-190epoch.h5\n    Saved custom checkpoint for epoch 190.\n    Epoch 191/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 204s 3s/step - loss: 0.6415 - accuracy: 0.6288 - auc: 0.6765 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00191: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-191epoch.h5\n    Saved custom checkpoint for epoch 191.\n    Epoch 192/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 202s 3s/step - loss: 0.6439 - accuracy: 0.6246 - auc: 0.6732 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00192: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-192epoch.h5\n    Saved custom checkpoint for epoch 192.\n    Epoch 193/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 206s 3s/step - loss: 0.6391 - accuracy: 0.6369 - auc: 0.6827 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00193: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-193epoch.h5\n    Saved custom checkpoint for epoch 193.\n    Epoch 194/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 206s 3s/step - loss: 0.6391 - accuracy: 0.6319 - auc: 0.6816 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00194: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-194epoch.h5\n    Saved custom checkpoint for epoch 194.\n    Epoch 195/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 199s 3s/step - loss: 0.6393 - accuracy: 0.6359 - auc: 0.6814 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00195: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-195epoch.h5\n    Saved custom checkpoint for epoch 195.\n    Epoch 196/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 204s 3s/step - loss: 0.6412 - accuracy: 0.6330 - auc: 0.6775 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00196: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-196epoch.h5\n    Saved custom checkpoint for epoch 196.\n    Epoch 197/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 205s 3s/step - loss: 0.6454 - accuracy: 0.6276 - auc: 0.6694 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00197: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-197epoch.h5\n    Saved custom checkpoint for epoch 197.\n    Epoch 198/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 202s 3s/step - loss: 0.6446 - accuracy: 0.6264 - auc: 0.6717 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00198: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-198epoch.h5\n    Saved custom checkpoint for epoch 198.\n    Epoch 199/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 207s 3s/step - loss: 0.6392 - accuracy: 0.6345 - auc: 0.6812 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00199: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-199epoch.h5\n    Saved custom checkpoint for epoch 199.\n    Epoch 200/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 207s 3s/step - loss: 0.6376 - accuracy: 0.6415 - auc: 0.6846 - val_loss: 0.6725 - val_accuracy: 0.6013 - val_auc: 0.6285\n    \n    Epoch 00200: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-200epoch.h5\n    Saved custom checkpoint for epoch 200.\n    {'loss': [0.7192227244377136, 0.6969526410102844, 0.6907368898391724, 0.6870048642158508, 0.6851317286491394, 0.6824196577072144, 0.6805691123008728, 0.6780949234962463, 0.6766244769096375, 0.6749172210693359, 0.6729189157485962, 0.6720675826072693, 0.6707138419151306, 0.6691109538078308, 0.6682166457176208, 0.6671577095985413, 0.6663216352462769, 0.6657128930091858, 0.6645525097846985, 0.6645374298095703, 0.6633859276771545, 0.6630358695983887, 0.6620543599128723, 0.6617375016212463, 0.6610801815986633, 0.6601349115371704, 0.6598512530326843, 0.6594048738479614, 0.6592659950256348, 0.658301055431366, 0.6581798195838928, 0.6575978994369507, 0.6575150489807129, 0.6574325561523438, 0.6565794944763184, 0.6564146280288696, 0.6566113829612732, 0.6559182405471802, 0.6552568078041077, 0.6554313898086548, 0.6550264358520508, 0.6547859907150269, 0.6554132103919983, 0.6542186141014099, 0.6539782285690308, 0.6533822417259216, 0.6530618071556091, 0.6532207727432251, 0.6524564027786255, 0.6518132090568542, 0.6518278121948242, 0.6516987085342407, 0.6512477397918701, 0.6511510014533997, 0.6507332921028137, 0.6507441401481628, 0.6505624055862427, 0.6501687169075012, 0.6500331163406372, 0.6494465470314026, 0.6492754817008972, 0.6487221717834473, 0.6487563252449036, 0.6484537720680237, 0.6480762362480164, 0.6481718420982361, 0.6481096148490906, 0.6476138234138489, 0.6472493410110474, 0.6470701098442078, 0.6466054320335388, 0.6464268565177917, 0.6460250616073608, 0.6458653807640076, 0.6463243961334229, 0.6455521583557129, 0.6452834010124207, 0.6449357271194458, 0.6451233625411987, 0.644340455532074, 0.6441216468811035, 0.6430081129074097, 0.6429328322410583, 0.6428995728492737, 0.6429684162139893, 0.6427977681159973, 0.6427863240242004, 0.6427538990974426, 0.6427420973777771, 0.6426806449890137, 0.6426808834075928, 0.6426887512207031, 0.6426223516464233, 0.6425647735595703, 0.6425737738609314, 0.6425384879112244, 0.6425139307975769, 0.6424831748008728, 0.6424326300621033, 0.6424298286437988, 0.6423637270927429, 0.642393171787262, 0.6423213481903076, 0.6423375010490417, 0.6423072218894958, 0.6422832608222961, 0.6422359943389893, 0.642188310623169, 0.6422012448310852, 0.6421991586685181, 0.6421584486961365, 0.6421325206756592, 0.6421182751655579, 0.6420691609382629, 0.6420169472694397, 0.6420906186103821, 0.6419829726219177, 0.6419853568077087, 0.641944408416748, 0.6419265866279602, 0.6418956518173218, 0.641765296459198, 0.6417573690414429, 0.6417511701583862, 0.6417492628097534, 0.6417419910430908, 0.6417418718338013, 0.6417497992515564, 0.6417382955551147, 0.641730546951294, 0.6417384147644043, 0.6417323350906372, 0.6417226195335388, 0.6417193412780762, 0.6417250633239746, 0.6417253613471985, 0.6417177319526672, 0.641710638999939, 0.6417075395584106, 0.6417092084884644, 0.6417065262794495, 0.6417006850242615, 0.6416999697685242, 0.6417000889778137, 0.6416959166526794, 0.6416914463043213, 0.6416927576065063, 0.641685426235199, 0.6416874527931213, 0.6416854858398438, 0.641677975654602, 0.6416793465614319, 0.6416762471199036, 0.6416705846786499, 0.6416705250740051, 0.6416701078414917, 0.6416676640510559, 0.6416624188423157, 0.6416656374931335, 0.6416609883308411, 0.641653835773468, 0.6416417360305786, 0.6416423320770264, 0.6416411995887756, 0.64164137840271, 0.6416409611701965, 0.6416414976119995, 0.6416404247283936, 0.6416407227516174, 0.641639769077301, 0.6416399478912354, 0.6416398286819458, 0.6416395902633667, 0.641638994216919, 0.6416392922401428, 0.6416390538215637, 0.6416387557983398, 0.6416382193565369, 0.6416379809379578, 0.6416376233100891, 0.6416373252868652, 0.6416366696357727, 0.6416366696357727, 0.6416362524032593, 0.641636312007904, 0.6416361927986145, 0.6416361331939697, 0.6416360139846802, 0.6416357755661011, 0.6416356563568115, 0.6416355967521667, 0.6416355967521667, 0.6416350603103638, 0.6416352391242981, 0.641635537147522, 0.6416351199150085, 0.6416351199150085, 0.6416346430778503, 0.6416345834732056, 0.6416345834732056], 'accuracy': [0.4843529462814331, 0.5180000066757202, 0.5350587964057922, 0.543647050857544, 0.5483529567718506, 0.5535294413566589, 0.5664705634117126, 0.5691764950752258, 0.5668235421180725, 0.5740000009536743, 0.5783529281616211, 0.5848235487937927, 0.5914117693901062, 0.5904706120491028, 0.5914117693901062, 0.5941176414489746, 0.5949411988258362, 0.596823513507843, 0.5988235473632812, 0.6001176238059998, 0.6008235216140747, 0.6032941341400146, 0.6018823385238647, 0.6009411811828613, 0.6081176400184631, 0.6081176400184631, 0.6084705591201782, 0.6094117760658264, 0.6088235378265381, 0.6108235120773315, 0.6103529334068298, 0.609529435634613, 0.609529435634613, 0.6100000143051147, 0.6105882525444031, 0.6084705591201782, 0.6091764569282532, 0.6128235459327698, 0.6100000143051147, 0.6111764907836914, 0.6078823804855347, 0.6137647032737732, 0.6087058782577515, 0.6123529672622681, 0.6134117841720581, 0.6149411797523499, 0.6118823289871216, 0.6162353157997131, 0.6175293922424316, 0.6187058687210083, 0.6158823370933533, 0.6176470518112183, 0.6179999709129333, 0.6175293922424316, 0.6188235282897949, 0.6218823790550232, 0.6170588135719299, 0.6178823709487915, 0.6184706091880798, 0.619882345199585, 0.6203529238700867, 0.6183529496192932, 0.6210588216781616, 0.6201176643371582, 0.6205882430076599, 0.6234117746353149, 0.6225882172584534, 0.62270587682724, 0.6249411702156067, 0.6268235445022583, 0.6258823275566101, 0.6243529319763184, 0.6248235106468201, 0.6245882511138916, 0.6232941150665283, 0.6232941150665283, 0.6252940893173218, 0.6268235445022583, 0.6271764636039734, 0.6275293827056885, 0.6247059106826782, 0.6292940974235535, 0.6275293827056885, 0.6282352805137634, 0.6291764974594116, 0.6296470761299133, 0.6292940974235535, 0.6299999952316284, 0.630117654800415, 0.6295294165611267, 0.630117654800415, 0.6291764974594116, 0.6295294165611267, 0.6297646760940552, 0.6305882334709167, 0.6298823356628418, 0.6302353143692017, 0.6294117569923401, 0.6307058930397034, 0.6302353143692017, 0.6302353143692017, 0.6297646760940552, 0.6303529143333435, 0.6298823356628418, 0.630117654800415, 0.6296470761299133, 0.6303529143333435, 0.6307058930397034, 0.6298823356628418, 0.6303529143333435, 0.630117654800415, 0.6298823356628418, 0.6303529143333435, 0.6307058930397034, 0.6311764717102051, 0.6303529143333435, 0.6305882334709167, 0.6307058930397034, 0.6304705739021301, 0.63082355260849, 0.6305882334709167, 0.6295294165611267, 0.6298823356628418, 0.6297646760940552, 0.630117654800415, 0.630117654800415, 0.6302353143692017, 0.6299999952316284, 0.6303529143333435, 0.6303529143333435, 0.630117654800415, 0.6304705739021301, 0.6304705739021301, 0.6303529143333435, 0.630117654800415, 0.6304705739021301, 0.6305882334709167, 0.6305882334709167, 0.63082355260849, 0.6307058930397034, 0.63082355260849, 0.6305882334709167, 0.63082355260849, 0.6307058930397034, 0.6310588121414185, 0.63082355260849, 0.63082355260849, 0.6305882334709167, 0.6309411525726318, 0.6309411525726318, 0.6307058930397034, 0.63082355260849, 0.6307058930397034, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.6309411525726318, 0.63082355260849, 0.6311764717102051, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849, 0.63082355260849], 'auc': [0.48203757405281067, 0.5276879072189331, 0.550908625125885, 0.5645636916160583, 0.5714666843414307, 0.5823923945426941, 0.5894912481307983, 0.5980960726737976, 0.6027661561965942, 0.607740044593811, 0.6145881414413452, 0.6166718602180481, 0.6216684579849243, 0.6246063709259033, 0.6270978450775146, 0.6300111413002014, 0.6313481330871582, 0.6328409910202026, 0.6354937553405762, 0.634859025478363, 0.6380510330200195, 0.638437807559967, 0.6410351991653442, 0.6413595080375671, 0.6429981589317322, 0.6446729898452759, 0.6452246904373169, 0.6459030508995056, 0.6460015773773193, 0.6481761336326599, 0.6484407186508179, 0.6496096253395081, 0.6491783857345581, 0.6492694616317749, 0.6508486866950989, 0.6514348983764648, 0.6510828733444214, 0.6524503231048584, 0.653304934501648, 0.6531680226325989, 0.6538273096084595, 0.6542485952377319, 0.6526313424110413, 0.6551164984703064, 0.6557536721229553, 0.6570212244987488, 0.6572893857955933, 0.657429039478302, 0.6588811874389648, 0.6600104570388794, 0.6598654985427856, 0.6600585579872131, 0.6608203649520874, 0.6607512831687927, 0.6615232229232788, 0.6618006229400635, 0.6616681814193726, 0.6623057126998901, 0.6625616550445557, 0.6638257503509521, 0.6640731692314148, 0.6650020480155945, 0.6646782159805298, 0.6654795408248901, 0.6662776470184326, 0.6661037802696228, 0.6657811403274536, 0.6668974757194519, 0.6676121354103088, 0.6676272749900818, 0.6687148809432983, 0.6688398122787476, 0.6695358157157898, 0.6697289943695068, 0.6690283417701721, 0.6707476377487183, 0.6706110239028931, 0.6714850664138794, 0.6706271767616272, 0.6724109053611755, 0.6728531122207642, 0.6746780872344971, 0.6747507452964783, 0.6747334599494934, 0.6746527552604675, 0.6750025153160095, 0.6749033331871033, 0.6750293970108032, 0.6751489043235779, 0.6752222776412964, 0.6752694249153137, 0.6751686930656433, 0.675368070602417, 0.6753979921340942, 0.6753919124603271, 0.6754812598228455, 0.6755191683769226, 0.6755763292312622, 0.6756330728530884, 0.6756366491317749, 0.6757560968399048, 0.6757243871688843, 0.6758098602294922, 0.6759003400802612, 0.6757888197898865, 0.6758520007133484, 0.67594313621521, 0.6760295629501343, 0.6759522557258606, 0.6759895086288452, 0.6761336326599121, 0.6762223243713379, 0.6762608885765076, 0.6761995553970337, 0.67631596326828, 0.6760507225990295, 0.6764441728591919, 0.6763685345649719, 0.6763870716094971, 0.6764413714408875, 0.676527738571167, 0.6765783429145813, 0.6766242980957031, 0.6766208410263062, 0.6766796112060547, 0.6766402125358582, 0.6766785383224487, 0.676631510257721, 0.6767333149909973, 0.6767604351043701, 0.6767877340316772, 0.6767579317092896, 0.6767434477806091, 0.6767287850379944, 0.6767203211784363, 0.6767473220825195, 0.6767730712890625, 0.6767723560333252, 0.6767649054527283, 0.6767899394035339, 0.6767683625221252, 0.6767977476119995, 0.6768091917037964, 0.6768143177032471, 0.6767988204956055, 0.6768198609352112, 0.676842212677002, 0.6767993569374084, 0.6767890453338623, 0.6768215894699097, 0.6768587827682495, 0.6768153309822083, 0.6768090724945068, 0.676826000213623, 0.6768451929092407, 0.6768134832382202, 0.6768133640289307, 0.676854133605957, 0.6768584847450256, 0.6767977476119995, 0.6768364310264587, 0.6768884658813477, 0.6768733859062195, 0.6768813729286194, 0.6768872141838074, 0.6768732070922852, 0.6768840551376343, 0.6768844127655029, 0.6768646836280823, 0.6768887639045715, 0.6768847107887268, 0.6768904328346252, 0.6768819093704224, 0.6768767833709717, 0.6768836379051208, 0.676873505115509, 0.6768773794174194, 0.6768733263015747, 0.676860511302948, 0.6768714189529419, 0.6768724322319031, 0.6768777966499329, 0.6768882870674133, 0.6768806576728821, 0.6768873929977417, 0.676901638507843, 0.6768814325332642, 0.6768847107887268, 0.6768805980682373, 0.6768767237663269, 0.6768866181373596, 0.6768944263458252, 0.6768804788589478, 0.676875114440918, 0.6768923997879028, 0.6768782734870911, 0.6768641471862793, 0.6768757700920105, 0.6768727898597717, 0.6768704056739807], 'val_loss': [0.7001472115516663, 0.6920315623283386, 0.6923649311065674, 0.6872780919075012, 0.6844104528427124, 0.685724675655365, 0.68430095911026, 0.6848741769790649, 0.6813239455223083, 0.6786159873008728, 0.6786141991615295, 0.6770142316818237, 0.6768365502357483, 0.6754131317138672, 0.6752451062202454, 0.6743302941322327, 0.6731574535369873, 0.6729417443275452, 0.6724650859832764, 0.6724027395248413, 0.6716288328170776, 0.6717498898506165, 0.6711543202400208, 0.6704498529434204, 0.6699037551879883, 0.6700395345687866, 0.6691251397132874, 0.6704764366149902, 0.6699854135513306, 0.668846845626831, 0.6697219014167786, 0.6698557734489441, 0.6705807447433472, 0.6690817475318909, 0.6698088049888611, 0.6694062948226929, 0.6705821752548218, 0.6704679131507874, 0.6692709922790527, 0.6700254082679749, 0.6701451539993286, 0.670092761516571, 0.670423686504364, 0.6710711121559143, 0.670950174331665, 0.6717463731765747, 0.6709585189819336, 0.6720139384269714, 0.6718791723251343, 0.6717446446418762, 0.6721624135971069, 0.6726205945014954, 0.6719126105308533, 0.6700003147125244, 0.6719544529914856, 0.6716666221618652, 0.6710378527641296, 0.6711843609809875, 0.6715793609619141, 0.6706038117408752, 0.6704044938087463, 0.6707466840744019, 0.6711857318878174, 0.6704333424568176, 0.6707842350006104, 0.6705493330955505, 0.6700688600540161, 0.670583188533783, 0.670795202255249, 0.6715794205665588, 0.6721569299697876, 0.6700839400291443, 0.6738193035125732, 0.6715601086616516, 0.6713632345199585, 0.6726559400558472, 0.6725365519523621, 0.6726077198982239, 0.672249972820282, 0.6723133325576782, 0.6721610426902771, 0.6721891760826111, 0.672209620475769, 0.6722322702407837, 0.6722804307937622, 0.6722710728645325, 0.6722126603126526, 0.6722396016120911, 0.6722977161407471, 0.6722274422645569, 0.6721179485321045, 0.6723257899284363, 0.6721395254135132, 0.6722510457038879, 0.6721908450126648, 0.6723014712333679, 0.6722666621208191, 0.6722383499145508, 0.6721833944320679, 0.6722567677497864, 0.6723993420600891, 0.6722256541252136, 0.6723430752754211, 0.6721376180648804, 0.672442615032196, 0.6723294258117676, 0.6722792983055115, 0.6723355054855347, 0.6724130511283875, 0.6723340153694153, 0.672439455986023, 0.6725174188613892, 0.6724472045898438, 0.6724240779876709, 0.6725184917449951, 0.6725872755050659, 0.6724133491516113, 0.6724574565887451, 0.672529935836792, 0.6725290417671204, 0.672373354434967, 0.6723797917366028, 0.6723788380622864, 0.6723881363868713, 0.6724101305007935, 0.6723949313163757, 0.6724109053611755, 0.672414243221283, 0.6724310517311096, 0.6724332571029663, 0.6724258065223694, 0.6724464893341064, 0.6724396347999573, 0.6724367141723633, 0.6724370121955872, 0.672471821308136, 0.6724523305892944, 0.6724631190299988, 0.6724743843078613, 0.6724715828895569, 0.6724647283554077, 0.6724709272384644, 0.6724687218666077, 0.672500491142273, 0.6724869608879089, 0.6724855899810791, 0.6724835634231567, 0.6724932789802551, 0.6724716424942017, 0.6724929213523865, 0.6724677085876465, 0.6724897027015686, 0.6724914312362671, 0.6724992394447327, 0.6724856495857239, 0.6725000739097595, 0.6724997758865356, 0.67250657081604, 0.6724989414215088, 0.6724829077720642, 0.6725044250488281, 0.6725038290023804, 0.672502338886261, 0.6725035309791565, 0.6725035309791565, 0.6725037693977356, 0.6725050210952759, 0.6725049018859863, 0.672505795955658, 0.6725051403045654, 0.6725045442581177, 0.6725042462348938, 0.6725056767463684, 0.6725038886070251, 0.6725064516067505, 0.6725044846534729, 0.6725071668624878, 0.6725040078163147, 0.6725058555603027, 0.6725047826766968, 0.6725051403045654, 0.6725043654441833, 0.6725050210952759, 0.6725051403045654, 0.672505795955658, 0.6725044846534729, 0.6725053787231445, 0.6725050210952759, 0.6725051999092102, 0.672505259513855, 0.6725056171417236, 0.672505259513855, 0.6725045442581177, 0.6725046038627625, 0.6725053191184998, 0.6725041270256042, 0.672503650188446, 0.6725037097930908, 0.6725040078163147, 0.6725032925605774], 'val_accuracy': [0.5, 0.5306666493415833, 0.5246666669845581, 0.5440000295639038, 0.5580000281333923, 0.5553333163261414, 0.5506666898727417, 0.5513333082199097, 0.5573333501815796, 0.5573333501815796, 0.5633333325386047, 0.5753333568572998, 0.5693333148956299, 0.5753333568572998, 0.5773333311080933, 0.5833333134651184, 0.5793333053588867, 0.5820000171661377, 0.5806666612625122, 0.5806666612625122, 0.5786666870117188, 0.5820000171661377, 0.5799999833106995, 0.5826666951179504, 0.5853333473205566, 0.5799999833106995, 0.5893333554267883, 0.5833333134651184, 0.5833333134651184, 0.5913333296775818, 0.5926666855812073, 0.581333339214325, 0.5839999914169312, 0.5913333296775818, 0.5853333473205566, 0.5886666774749756, 0.5886666774749756, 0.5933333039283752, 0.5953333377838135, 0.5899999737739563, 0.5899999737739563, 0.5899999737739563, 0.5806666612625122, 0.5846666693687439, 0.5920000076293945, 0.5873333215713501, 0.581333339214325, 0.5899999737739563, 0.5926666855812073, 0.5913333296775818, 0.5933333039283752, 0.5913333296775818, 0.5933333039283752, 0.5953333377838135, 0.5953333377838135, 0.5926666855812073, 0.5933333039283752, 0.5946666598320007, 0.5946666598320007, 0.5926666855812073, 0.593999981880188, 0.5920000076293945, 0.596666693687439, 0.5946666598320007, 0.5926666855812073, 0.5960000157356262, 0.5979999899864197, 0.5973333120346069, 0.5899999737739563, 0.596666693687439, 0.5920000076293945, 0.5993333458900452, 0.596666693687439, 0.6013333201408386, 0.5960000157356262, 0.5973333120346069, 0.5979999899864197, 0.5986666679382324, 0.5979999899864197, 0.5993333458900452, 0.5979999899864197, 0.5986666679382324, 0.5973333120346069, 0.5973333120346069, 0.5973333120346069, 0.6013333201408386, 0.5986666679382324, 0.5973333120346069, 0.5986666679382324, 0.5986666679382324, 0.5979999899864197, 0.5973333120346069, 0.5986666679382324, 0.5979999899864197, 0.5973333120346069, 0.5973333120346069, 0.5979999899864197, 0.5986666679382324, 0.5979999899864197, 0.5973333120346069, 0.596666693687439, 0.5973333120346069, 0.5973333120346069, 0.6006666421890259, 0.5973333120346069, 0.5986666679382324, 0.5986666679382324, 0.5973333120346069, 0.596666693687439, 0.5993333458900452, 0.596666693687439, 0.5973333120346069, 0.5993333458900452, 0.5986666679382324, 0.5993333458900452, 0.5979999899864197, 0.5986666679382324, 0.6006666421890259, 0.5979999899864197, 0.6000000238418579, 0.6006666421890259, 0.6006666421890259, 0.6006666421890259, 0.6006666421890259, 0.6000000238418579, 0.6006666421890259, 0.6006666421890259, 0.6000000238418579, 0.6006666421890259, 0.6000000238418579, 0.6000000238418579, 0.6000000238418579, 0.6006666421890259, 0.6000000238418579, 0.6013333201408386, 0.5993333458900452, 0.5993333458900452, 0.5993333458900452, 0.5993333458900452, 0.5993333458900452, 0.5993333458900452, 0.5993333458900452, 0.5993333458900452, 0.6000000238418579, 0.6000000238418579, 0.5993333458900452, 0.6000000238418579, 0.6000000238418579, 0.5993333458900452, 0.6000000238418579, 0.5993333458900452, 0.6000000238418579, 0.6000000238418579, 0.6000000238418579, 0.6000000238418579, 0.6006666421890259, 0.6006666421890259, 0.6000000238418579, 0.6006666421890259, 0.6000000238418579, 0.6013333201408386, 0.6013333201408386, 0.6006666421890259, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6006666421890259, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386, 0.6013333201408386], 'val_auc': [0.5110349059104919, 0.5455288290977478, 0.5422728657722473, 0.5634271502494812, 0.5771453976631165, 0.5691004395484924, 0.5749048590660095, 0.5739942789077759, 0.5846900343894958, 0.5950312614440918, 0.5945642590522766, 0.6033262014389038, 0.6010013818740845, 0.6078413128852844, 0.6062846779823303, 0.6109306216239929, 0.6124671101570129, 0.6130215525627136, 0.614966869354248, 0.6144931316375732, 0.6160726547241211, 0.615035355091095, 0.6174659729003906, 0.6209138035774231, 0.6211057901382446, 0.6212300062179565, 0.6246219873428345, 0.6204468607902527, 0.6226983070373535, 0.6254846453666687, 0.6239336133003235, 0.6227597594261169, 0.6221449375152588, 0.6251204013824463, 0.6260157823562622, 0.6253271698951721, 0.6229053139686584, 0.6240479946136475, 0.6261319518089294, 0.6231846809387207, 0.6256482005119324, 0.6258711218833923, 0.6255944967269897, 0.6231133341789246, 0.6230562329292297, 0.6222853660583496, 0.6254790425300598, 0.6213557720184326, 0.6223582029342651, 0.6222302317619324, 0.6200870871543884, 0.6206821799278259, 0.6234880089759827, 0.6264119744300842, 0.6239361763000488, 0.6237916350364685, 0.6260809302330017, 0.6252555251121521, 0.6244362592697144, 0.6253029108047485, 0.6267617344856262, 0.6265733242034912, 0.6253766417503357, 0.6273451447486877, 0.6285191774368286, 0.6269444227218628, 0.628890872001648, 0.6287621855735779, 0.6270817518234253, 0.628146231174469, 0.6275448799133301, 0.6293240189552307, 0.6246604323387146, 0.6256361603736877, 0.6277786493301392, 0.6282451152801514, 0.6268700361251831, 0.6270688772201538, 0.6276155710220337, 0.6266084313392639, 0.627938449382782, 0.6278463006019592, 0.6279359459877014, 0.627837061882019, 0.6281906366348267, 0.6277827024459839, 0.6280897855758667, 0.6278465390205383, 0.6280373930931091, 0.6277439594268799, 0.6280301809310913, 0.6278455853462219, 0.628153383731842, 0.628118634223938, 0.6279478073120117, 0.6276015639305115, 0.6277857422828674, 0.6277113556861877, 0.6278286576271057, 0.628002941608429, 0.6279568672180176, 0.6283926963806152, 0.6279549598693848, 0.62828129529953, 0.6279224157333374, 0.6281329393386841, 0.6283870935440063, 0.6281620264053345, 0.6281604170799255, 0.6283168792724609, 0.6283249258995056, 0.6283444762229919, 0.6283949613571167, 0.6281246542930603, 0.6280222535133362, 0.6282066106796265, 0.6281977891921997, 0.6282840371131897, 0.6284235119819641, 0.6282039880752563, 0.6285271048545837, 0.6285866498947144, 0.6285585761070251, 0.6285459399223328, 0.6284831762313843, 0.6285004019737244, 0.6284149885177612, 0.6284613013267517, 0.6284215450286865, 0.6282541751861572, 0.6283222436904907, 0.628248929977417, 0.6284675598144531, 0.6283764243125916, 0.6284249424934387, 0.6281691193580627, 0.6284053921699524, 0.6283184289932251, 0.6282106637954712, 0.6283709406852722, 0.6283526420593262, 0.6282210946083069, 0.62822425365448, 0.6283926963806152, 0.6283317804336548, 0.6283151507377625, 0.6283680200576782, 0.6283531188964844, 0.6283155679702759, 0.6282779574394226, 0.6283384561538696, 0.6283944249153137, 0.6284564137458801, 0.6283486485481262, 0.6284021735191345, 0.6283513903617859, 0.6283762454986572, 0.6283422112464905, 0.6283984184265137, 0.6283813118934631, 0.6284895539283752, 0.6284766793251038, 0.6284215450286865, 0.6284958124160767, 0.6284557580947876, 0.6284348964691162, 0.6283788681030273, 0.6284588575363159, 0.6284562349319458, 0.6284410953521729, 0.6284410953521729, 0.6284304857254028, 0.6284300088882446, 0.6284503936767578, 0.6284819841384888, 0.628449559211731, 0.6284455060958862, 0.628467321395874, 0.6284833550453186, 0.6284646987915039, 0.6284455060958862, 0.6284566521644592, 0.6284455060958862, 0.6284455060958862, 0.6284455060958862, 0.628467321395874, 0.6284642219543457, 0.6284500360488892, 0.6284455060958862, 0.6284566521644592, 0.6284753084182739, 0.6284566521644592, 0.628467321395874, 0.628460705280304, 0.6284753084182739, 0.628460705280304, 0.628460705280304, 0.6284522414207458, 0.6284522414207458, 0.628460705280304], 'lr': [0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.0003162278, 0.001, 0.001, 0.001, 0.001, 0.0003162278, 0.001, 0.001, 0.001, 0.001, 0.0003162278, 0.001, 0.001, 0.001, 0.001, 0.0003162278, 0.001, 0.001, 0.001, 0.001, 0.0003162278, 0.001, 0.001, 0.001, 0.001, 0.0003162278, 0.001, 0.001, 0.001, 0.001, 0.0003162278, 0.001, 0.001, 0.001, 0.001, 0.0003162278, 0.001, 0.001, 0.001, 0.001, 0.0003162278, 0.001, 0.001, 0.001, 0.001, 0.0003162278, 0.001, 1e-04, 1e-04, 1e-04, 3.1622774e-05, 1e-04, 1e-04, 1e-04, 1e-04, 3.1622774e-05, 1e-04, 1e-04, 1e-04, 1e-04, 3.1622774e-05, 1e-04, 1e-04, 1e-04, 1e-04, 3.1622774e-05, 1e-04, 1e-04, 1e-04, 1e-04, 3.1622774e-05, 1e-04, 1e-04, 1e-04, 1e-04, 3.1622774e-05, 1e-04, 1e-04, 1e-04, 1e-04, 3.1622774e-05, 1e-04, 1e-04, 1e-04, 1e-04, 3.1622774e-05, 1e-04, 1e-05, 1e-05, 1e-05, 3.1622776e-06, 1e-05, 1e-05, 1e-05, 1e-05, 3.1622776e-06, 1e-05, 1e-05, 1e-05, 1e-05, 3.1622776e-06, 1e-05, 1e-05, 1e-05, 1e-05, 3.1622776e-06, 1e-05, 1e-05, 1e-05, 1e-05, 3.1622776e-06, 1e-05, 1e-05, 1e-05, 1e-05, 3.1622776e-06, 1e-05, 1e-05, 1e-05, 1e-05, 3.1622776e-06, 1e-05, 1e-05, 1e-05, 1e-05, 3.1622776e-06, 1e-05, 1e-06, 1e-06, 1e-06, 5e-07, 1e-06, 1e-06, 1e-06, 1e-06, 5e-07, 1e-06, 1e-06, 1e-06, 1e-06, 5e-07, 1e-06, 1e-06, 1e-06, 1e-06, 5e-07, 1e-06, 5e-07, 5e-07, 5e-07, 5e-07, 5e-07, 5e-07, 5e-07, 5e-07, 5e-07, 5e-07, 5e-07, 5e-07, 5e-07, 5e-07, 5e-07, 5e-07, 5e-07, 5e-07, 5e-07]}\n    0.676901638507843\n    0.6293240189552307\n\n\n\n```python\ncheckpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))\n```\n\n    ERROR:tensorflow:Couldn't match files for checkpoint /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/1_1 Filter=[2,2] Stride=[1,1]/ckpt-200\n\n\n\n\n\n    <tensorflow.python.training.tracking.util.InitializationOnlyStatus at 0x7fa3cf7856d0>\n\n\n\n\n```python\nimport time\n#start_time = time.time()\n\nlast_epoch = 188\n\nH = model.fit(x_train, y_train, initial_epoch=last_epoch,\n              batch_size=BATCH_SIZE,\n              epochs=EPOCHS,\n              validation_data=(x_test, y_test),\n              shuffle=True,\n              callbacks=callbacks)\n\nprint(H.history)\n```\n\n    Epoch 189/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 783s 11s/step - loss: 0.6439 - accuracy: 0.6281 - auc: 0.6742 - val_loss: 0.6595 - val_accuracy: 0.6273 - val_auc: 0.6542\n    \n    Epoch 00189: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-189epoch.h5\n    Saved custom checkpoint for epoch 188.\n    Epoch 190/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 729s 11s/step - loss: 0.6384 - accuracy: 0.6340 - auc: 0.6843 - val_loss: 0.6595 - val_accuracy: 0.6273 - val_auc: 0.6542\n    \n    Epoch 00190: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-190epoch.h5\n    Saved custom checkpoint for epoch 189.\n    Epoch 191/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 698s 10s/step - loss: 0.6438 - accuracy: 0.6263 - auc: 0.6749 - val_loss: 0.6595 - val_accuracy: 0.6273 - val_auc: 0.6542\n    \n    Epoch 00191: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-191epoch.h5\n    Saved custom checkpoint for epoch 190.\n    Epoch 192/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 697s 10s/step - loss: 0.6419 - accuracy: 0.6325 - auc: 0.6801 - val_loss: 0.6595 - val_accuracy: 0.6273 - val_auc: 0.6542\n    \n    Epoch 00192: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-192epoch.h5\n    Saved custom checkpoint for epoch 191.\n    Epoch 193/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 695s 10s/step - loss: 0.6407 - accuracy: 0.6348 - auc: 0.6808 - val_loss: 0.6595 - val_accuracy: 0.6273 - val_auc: 0.6542\n    \n    Epoch 00193: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-193epoch.h5\n    Saved custom checkpoint for epoch 192.\n    Epoch 194/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 687s 10s/step - loss: 0.6385 - accuracy: 0.6369 - auc: 0.6840 - val_loss: 0.6595 - val_accuracy: 0.6273 - val_auc: 0.6542\n    \n    Epoch 00194: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-194epoch.h5\n    Saved custom checkpoint for epoch 193.\n    Epoch 195/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 692s 10s/step - loss: 0.6456 - accuracy: 0.6278 - auc: 0.6722 - val_loss: 0.6595 - val_accuracy: 0.6273 - val_auc: 0.6542\n    \n    Epoch 00195: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-195epoch.h5\n    Saved custom checkpoint for epoch 194.\n    Epoch 196/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 686s 10s/step - loss: 0.6446 - accuracy: 0.6271 - auc: 0.6735 - val_loss: 0.6595 - val_accuracy: 0.6273 - val_auc: 0.6542\n    \n    Epoch 00196: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-196epoch.h5\n    Saved custom checkpoint for epoch 195.\n    Epoch 197/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 694s 10s/step - loss: 0.6412 - accuracy: 0.6321 - auc: 0.6799 - val_loss: 0.6595 - val_accuracy: 0.6273 - val_auc: 0.6542\n    \n    Epoch 00197: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-197epoch.h5\n    Saved custom checkpoint for epoch 196.\n    Epoch 198/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 689s 10s/step - loss: 0.6404 - accuracy: 0.6331 - auc: 0.6818 - val_loss: 0.6595 - val_accuracy: 0.6273 - val_auc: 0.6542\n    \n    Epoch 00198: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-198epoch.h5\n    Saved custom checkpoint for epoch 197.\n    Epoch 199/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 687s 10s/step - loss: 0.6415 - accuracy: 0.6327 - auc: 0.6794 - val_loss: 0.6595 - val_accuracy: 0.6273 - val_auc: 0.6542\n    \n    Epoch 00199: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-199epoch.h5\n    Saved custom checkpoint for epoch 198.\n    Epoch 200/200\n    Learning rate:  5e-07\n    67/67 [==============================] - ETA: 0s - loss: 0.6472 - accuracy: 0.6216 - auc: 0.6684\n\n\n```python\ncheckpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))\n```\n\n\n\n\n    <tensorflow.python.training.tracking.util.CheckpointLoadStatus at 0x7fb57b636f90>\n\n\n\n\n```python\nimport time\n#start_time = time.time()\n\nlast_epoch = 199\n\nH = model.fit(x_train, y_train, initial_epoch=last_epoch,\n              batch_size=BATCH_SIZE,\n              epochs=EPOCHS,\n              validation_data=(x_test, y_test),\n              shuffle=True,\n              callbacks=callbacks)\n\nprint(H.history)\n```\n\n    Epoch 200/200\n    Learning rate:  5e-07\n    67/67 [==============================] - 786s 11s/step - loss: 0.6425 - accuracy: 0.6307 - auc: 0.6772 - val_loss: 0.6595 - val_accuracy: 0.6273 - val_auc: 0.6542\n    \n    Epoch 00200: saving model to /content/drive/MyDrive/Projects/GSoC 2021/Model_Hybrid/QCNN_Type1_L1Q3_10000samples-200epoch.h5\n    Saved custom checkpoint for epoch 199.\n    {'loss': [0.6415966749191284], 'accuracy': [0.6310588121414185], 'auc': [0.6788457632064819], 'val_loss': [0.6594995260238647], 'val_accuracy': [0.6273333430290222], 'val_auc': [0.65424644947052], 'lr': [5e-07]}\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\nQ1\nL1: 0.636, 80s\nL2: 0.666, 170s\nL3: 0.622, 330s\nL4: , 380s\n```\n\n\n```python\n340s 5s/step - loss: 0.6583 - accuracy: 0.6127 - auc: 0.6488 - val_loss: 0.6779 - val_accuracy: 0.5807 - val_auc: 0.6112\n```\n\n\n```python\n\n```\n\n\n```python\n6914 655\n```\n", "meta": {"hexsha": "efc43e2799701adbf5c9f9b990616470ecf0648f", "size": 646325, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "sandbox/QCNN_v1_1.ipynb", "max_stars_repo_name": "eraraya-ricardo/qcnn-hep", "max_stars_repo_head_hexsha": "fbb6c2e1ab10e6059ff6250cf1bac7f714dde08f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-08-30T08:40:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T01:33:48.000Z", "max_issues_repo_path": "sandbox/QCNN_v1_1.ipynb", "max_issues_repo_name": "eraraya-ricardo/qcnn-hep", "max_issues_repo_head_hexsha": "fbb6c2e1ab10e6059ff6250cf1bac7f714dde08f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-06-26T18:42:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-29T09:02:30.000Z", "max_forks_repo_path": "sandbox/QCNN_v1_1.ipynb", "max_forks_repo_name": "eraraya-ricardo/GSoC-QCNN", "max_forks_repo_head_hexsha": "fbb6c2e1ab10e6059ff6250cf1bac7f714dde08f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-08-23T13:02:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T02:27:37.000Z", "avg_line_length": 202.9915201005, "max_line_length": 130373, "alphanum_fraction": 0.8158186671, "converted": true, "num_tokens": 52851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.07369627428358225, "lm_q1q2_score": 0.036272431849204756}}
{"text": "# Building a Spam Filter with Naive Bayes\n\n\nIn this project, we're going to build a spam filter for SMS messages using the multinomial Naive Bayes algorithm. Our goal is to write a program that classifies new messages with an accuracy greater than 80% \u2014 so we expect that more than 80% of the new messages will be classified correctly as spam or ham (non-spam).\n\nTo train the algorithm, we'll use a dataset of 5,572 SMS messages that are already classified by humans. The dataset was put together by Tiago A. Almeida and Jos\u00e9 Mar\u00eda G\u00f3mez Hidalgo, and it can be downloaded from the The [UCI Machine Learning Repository](https://archive.ics.uci.edu/ml/datasets/sms+spam+collection). The data collection process is described in more details on [this page](http://www.dt.fee.unicamp.br/~tiago/smsspamcollection/#composition), where you can also find some of the papers authored by Tiago A. Almeida and Jos\u00e9 Mar\u00eda G\u00f3mez Hidalgo.\n\n\n\n## Exploring the Dataset\n\n\n\n\n```python\nimport pandas as pd\n\nsms_collection = pd.read_csv('SMSSpamCollection', \n                             sep = '\\t', \n                             header = None, \n                             names = ['Label','SMS'])\n```\n\n\n```python\nsms_collection.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Label</th>\n      <th>SMS</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>ham</td>\n      <td>Go until jurong point, crazy.. Available only ...</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>ham</td>\n      <td>Ok lar... Joking wif u oni...</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>spam</td>\n      <td>Free entry in 2 a wkly comp to win FA Cup fina...</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>ham</td>\n      <td>U dun say so early hor... U c already then say...</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>ham</td>\n      <td>Nah I don't think he goes to usf, he lives aro...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nsms_collection.shape\n```\n\n\n\n\n    (5572, 2)\n\n\n\nAs we can see that there are 5572 rows and only 2 columns which are LABEL and SMS column.\n\n\n```python\nsms_collection['Label'].value_counts(normalize=True)* 100\n```\n\n\n\n\n    ham     86.593683\n    spam    13.406317\n    Name: Label, dtype: float64\n\n\n\nThere are about 13.4 % of spam messages in the dataset and about 86.6 % of non spam sms which are labeled as ham. \n\n## Training and Test set\ne're going to keep 80% of our dataset for training, and 20% for testing (we want to train the algorithm on as much data as possible, but we also want to have enough test data). The dataset has 5,572 messages, which means that:\n\n* The training set will have 4,458 messages (about 80% of the dataset).\n* The test set will have 1,114 messages (about 20% of the dataset).\n\nTo better understand the purpose of putting a test set aside, let's begin by observing that all 1,114 messages in our test set are already classified by a human. When the spam filter is ready, we're going to treat these messages as new and have the filter classify them. Once we have the results, we'll be able to compare the algorithm classification with that done by a human, and this way we'll see how good the spam filter really is.\n\n\n```python\n# randomizing the dataset\n'''\nWe will use frac =1 parameter to randomize the entire dataset\nand random_state = 1 to make our results reproducible\n'''\nrandomized_sms = sms_collection.sample(frac = 1, random_state = 1)\n\n#splitting the randomized dataset\n# Calculate index for split\ntraining_test_index = round(len(randomized_sms) * 0.8)\n\n# Training/Test split\ntraining_set = randomized_sms[:training_test_index].reset_index(drop=True)\ntest_set = randomized_sms[training_test_index:].reset_index(drop=True)\n\nprint(training_set.shape)\nprint(test_set.shape)\n```\n\n    (4458, 2)\n    (1114, 2)\n\n\nNow lets Find the percentage of spam and ham in both the training and the test set.\n\n\n```python\ntraining_set['Label'].value_counts(normalize = True)* 100\n```\n\n\n\n\n    ham     86.54105\n    spam    13.45895\n    Name: Label, dtype: float64\n\n\n\n\n```python\ntest_set['Label'].value_counts(normalize = True)* 100\n```\n\n\n\n\n    ham     86.804309\n    spam    13.195691\n    Name: Label, dtype: float64\n\n\n\nThe results look good! We'll now move on to cleaning the dataset.\n\n\n\nThe results look good! We'll now move on to cleaning the dataset.\n\n## Data Cleaning\n\nTo calculate all the probabilities required by the algorithm, we'll first need to perform a bit of data cleaning to bring the data in a format that will allow us to extract easily all the information we need.\n\nEssentially, we want to bring data to this format:\n\n\n\n\n### Letter Case and Punctuation\n\nWe'll begin with removing all the punctuation and bringing every letter to lower case.\n\n\n```python\n# Before cleaning data\ntraining_set.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Label</th>\n      <th>SMS</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>ham</td>\n      <td>Yep, by the pretty sculpture</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>ham</td>\n      <td>Yes, princess. Are you going to make me moan?</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>ham</td>\n      <td>Welp apparently he retired</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>ham</td>\n      <td>Havent.</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>ham</td>\n      <td>I forgot 2 ask \u00fc all smth.. There's a card on ...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# After cleaning data\ntraining_set['SMS'] = training_set['SMS'].str.replace('\\W', ' ')\ntraining_set['SMS'] = training_set['SMS'].str.lower()\ntraining_set.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Label</th>\n      <th>SMS</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>ham</td>\n      <td>yep  by the pretty sculpture</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>ham</td>\n      <td>yes  princess  are you going to make me moan</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>ham</td>\n      <td>welp apparently he retired</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>ham</td>\n      <td>havent</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>ham</td>\n      <td>i forgot 2 ask \u00fc all smth   there s a card on ...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Creating the Vocabulary\n\nLet's now move to creating the vocabulary, which in this context means a list with all the unique words in our training set.\n\n\n```python\ntraining_set['SMS'] = training_set['SMS'].str.split()\n\nvocabulary = []\nfor sms in training_set['SMS']:\n    for word in sms:\n        vocabulary.append(word)\n        \nvocabulary = list(set(vocabulary))\n```\n\n\n```python\nlen(vocabulary)\n```\n\n\n\n\n    7783\n\n\n\nIt looks like there are 7,783 unique words in all the messages of our training set.\n\n## The final Training Set\n\nWe're now going to use the vocabulary we just created to make the data transformation we want\n\n\n```python\nword_counts_per_sms = {unique_word: [0] * len(training_set['SMS']) for unique_word in vocabulary}\n\nfor index, sms in enumerate(training_set['SMS']):\n    for word in sms:\n        word_counts_per_sms[word][index] += 1\n```\n\n\n```python\n#Transformimg into dataframe\nword_counts = pd.DataFrame(word_counts_per_sms)\nword_counts.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>0</th>\n      <th>00</th>\n      <th>000</th>\n      <th>000pes</th>\n      <th>008704050406</th>\n      <th>0089</th>\n      <th>01223585334</th>\n      <th>02</th>\n      <th>0207</th>\n      <th>02072069400</th>\n      <th>...</th>\n      <th>zindgi</th>\n      <th>zoe</th>\n      <th>zogtorius</th>\n      <th>zouk</th>\n      <th>zyada</th>\n      <th>\u00e9</th>\n      <th>\u00fa1</th>\n      <th>\u00fc</th>\n      <th>\u3028ud</th>\n      <th>\u9225</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 7783 columns</p>\n</div>\n\n\n\n\n```python\ntraining_set_clean = pd.concat([training_set, word_counts], axis=1)\ntraining_set_clean.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Label</th>\n      <th>SMS</th>\n      <th>0</th>\n      <th>00</th>\n      <th>000</th>\n      <th>000pes</th>\n      <th>008704050406</th>\n      <th>0089</th>\n      <th>01223585334</th>\n      <th>02</th>\n      <th>...</th>\n      <th>zindgi</th>\n      <th>zoe</th>\n      <th>zogtorius</th>\n      <th>zouk</th>\n      <th>zyada</th>\n      <th>\u00e9</th>\n      <th>\u00fa1</th>\n      <th>\u00fc</th>\n      <th>\u3028ud</th>\n      <th>\u9225</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>ham</td>\n      <td>[yep, by, the, pretty, sculpture]</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>ham</td>\n      <td>[yes, princess, are, you, going, to, make, me,...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>ham</td>\n      <td>[welp, apparently, he, retired]</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>ham</td>\n      <td>[havent]</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>ham</td>\n      <td>[i, forgot, 2, ask, \u00fc, all, smth, there, s, a,...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 7785 columns</p>\n</div>\n\n\n\n## Calculating Constants First\n\nWe're now done with cleaning the training set, and we can begin creating the spam filter. The Naive Bayes algorithm will need to answer these two probability questions to be able to classify new messages:\n\n\\begin{equation}\nP(Spam | w_1,w_2, ..., w_n) \\propto P(Spam) \\cdot \\prod_{i=1}^{n}P(w_i|Spam)\n\\end{equation}\n\n\\begin{equation}\nP(Ham | w_1,w_2, ..., w_n) \\propto P(Ham) \\cdot \\prod_{i=1}^{n}P(w_i|Ham)\n\\end{equation}\n\n\nAlso, to calculate P(w<sub>i</sub>|Spam) and P(w<sub>i</sub>|Ham) inside the formulas above, we'll need to use these equations:\n\n\\begin{equation}\nP(w_i|Spam) = \\frac{N_{w_i|Spam} + \\alpha}{N_{Spam} + \\alpha \\cdot N_{Vocabulary}}\n\\end{equation}\n\n\\begin{equation}\nP(w_i|Ham) = \\frac{N_{w_i|Ham} + \\alpha}{N_{Ham} + \\alpha \\cdot N_{Vocabulary}}\n\\end{equation}\n\n\nSome of the terms in the four equations above will have the same value for every new message. We can calculate the value of these terms once and avoid doing the computations again when a new messages comes in. Below, we'll use our training set to calculate:\n\n- P(Spam) and P(Ham)\n- N<sub>Spam</sub>, N<sub>Ham</sub>, N<sub>Vocabulary</sub>\n\nWe'll also use Laplace smoothing and set $\\alpha = 1$.\n\n\n```python\n#isolating spam and ham messages\nspam_msg = training_set_clean[training_set_clean['Label']=='spam']\nham_msg = training_set_clean[training_set_clean['Label']=='ham']\n```\n\n\n```python\n# p(spam) and p(ham)\np_spam = len(spam_msg) / len(training_set_clean)\np_ham = len(ham_msg) / len(training_set_clean)\nprint('The probability of spam messages is: '+ str(p_spam))\nprint('The probability of non-spam messages is: '+ str(p_ham))\n```\n\n    The probability of spam messages is: 0.13458950201884254\n    The probability of non-spam messages is: 0.8654104979811574\n\n\n\n```python\n# N_Spam\nn_words_per_spam_message = spam_msg['SMS'].apply(len)\nn_spam = n_words_per_spam_message.sum()\n\n# N_Ham\nn_words_per_ham_message = ham_msg['SMS'].apply(len)\nn_ham = n_words_per_ham_message.sum()\n\n# N_Vocabulary\nn_vocabulary = len(vocabulary)\n\n# Laplace smoothing\nalpha = 1\n```\n\n## Calculating Parameters\n\nNow that we have the constant terms calculated above, we can move on with calculating the parameters $P(w_i|Spam)$ and $P(w_i|Ham)$. Each parameter will thus be a conditional probability value associated with each word in the vocabulary.\n\nThe parameters are calculated using the formulas:\n\n\\begin{equation}\nP(w_i|Spam) = \\frac{N_{w_i|Spam} + \\alpha}{N_{Spam} + \\alpha \\cdot N_{Vocabulary}}\n\\end{equation}\n\n\\begin{equation}\nP(w_i|Ham) = \\frac{N_{w_i|Ham} + \\alpha}{N_{Ham} + \\alpha \\cdot N_{Vocabulary}}\n\\end{equation}\n\n\n```python\n# Initiate parameters\nparameters_spam = {unique_word:0 for unique_word in vocabulary}\nparameters_ham = {unique_word:0 for unique_word in vocabulary}\n\n# Calculate parameters\nfor word in vocabulary:\n    n_word_given_spam = spam_msg[word].sum()   # spam_messages already defined in a cell above\n    p_word_given_spam = (n_word_given_spam + alpha) / (n_spam + alpha*n_vocabulary)\n    parameters_spam[word] = p_word_given_spam\n    \n    n_word_given_ham = ham_msg[word].sum()   # ham_messages already defined in a cell above\n    p_word_given_ham = (n_word_given_ham + alpha) / (n_ham + alpha*n_vocabulary)\n    parameters_ham[word] = p_word_given_ham\n```\n\n## Classifying A New Message\n\nNow that we have all our parameters calculated, we can start creating the spam filter. The spam filter can be understood as a function that:\n\n- Takes in as input a new message (w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>n</sub>).\n- Calculates P(Spam|w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>n</sub>) and P(Ham|w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>n</sub>).\n- Compares the values of P(Spam|w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>n</sub>) and P(Ham|w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>n</sub>), and:\n    - If P(Ham|w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>n</sub>) > P(Spam|w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>n</sub>), then the message is classified as ham.\n    - If P(Ham|w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>n</sub>) < P(Spam|w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>n</sub>), then the message is classified as spam.\n    -  If P(Ham|w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>n</sub>) = P(Spam|w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>n</sub>), then the algorithm may request human help.\n\n\n```python\nimport re\n\ndef classify(message):\n    '''\n    message: a string\n    '''\n    \n    message = re.sub('\\W', ' ', message)\n    message = message.lower().split()\n    \n    p_spam_given_message = p_spam\n    p_ham_given_message = p_ham\n\n    for word in message:\n        if word in parameters_spam:\n            p_spam_given_message *= parameters_spam[word]\n            \n        if word in parameters_ham:\n            p_ham_given_message *= parameters_ham[word]\n            \n    print('P(Spam|message):', p_spam_given_message)\n    print('P(Ham|message):', p_ham_given_message)\n    \n    if p_ham_given_message > p_spam_given_message:\n        print('Label: Ham')\n    elif p_ham_given_message < p_spam_given_message:\n        print('Label: Spam')\n    else:\n        print('Equal proabilities, have a human classify this!')\n```\n\n\n```python\nprint(classify('WINNER!! This is the secret code to unlock the money: C3421.'))\n```\n\n    P(Spam|message): 1.3481290211300841e-25\n    P(Ham|message): 1.9368049028589875e-27\n    Label: Spam\n    None\n\n\n\n```python\nprint(classify(\"Sounds good, Tom, then see u there\"))\n```\n\n    P(Spam|message): 2.4372375665888117e-25\n    P(Ham|message): 3.687530435009238e-21\n    Label: Ham\n    None\n\n\n\n```python\n\n```\n\n##  Measuring the Spam Filter's Accuracy\nThe two results above look promising, but let's see how well the filter does on our test set, which has 1,114 messages.\n\nWe'll start by writing a function that returns classification labels instead of printing them.\n\n\n```python\ndef classify_test_set(message):    \n    '''\n    message: a string\n    '''\n    \n    message = re.sub('\\W', ' ', message)\n    message = message.lower().split()\n    \n    p_spam_given_message = p_spam\n    p_ham_given_message = p_ham\n\n    for word in message:\n        if word in parameters_spam:\n            p_spam_given_message *= parameters_spam[word]\n            \n        if word in parameters_ham:\n            p_ham_given_message *= parameters_ham[word]\n    \n    if p_ham_given_message > p_spam_given_message:\n        return 'ham'\n    elif p_spam_given_message > p_ham_given_message:\n        return 'spam'\n    else:\n        return 'needs human classification'\n```\n\nNow that we have a function that returns labels instead of printing them, we can use it to create a new column in our test set.\n\n\n```python\ntest_set['predicted'] = test_set['SMS'].apply(classify_test_set)\ntest_set.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Label</th>\n      <th>SMS</th>\n      <th>predicted</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>ham</td>\n      <td>Later i guess. I needa do mcat study too.</td>\n      <td>ham</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>ham</td>\n      <td>But i haf enuff space got like 4 mb...</td>\n      <td>ham</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>spam</td>\n      <td>Had your mobile 10 mths? Update to latest Oran...</td>\n      <td>spam</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>ham</td>\n      <td>All sounds good. Fingers . Makes it difficult ...</td>\n      <td>ham</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>ham</td>\n      <td>All done, all handed in. Don't know if mega sh...</td>\n      <td>ham</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nNow, we'll write a function to measure the accuracy of our spam filter to find out how well our spam filter does.\n\n\n```python\ncorrect = 0\ntotal = test_set.shape[0]\n    \nfor row in test_set.iterrows():\n    row = row[1]\n    if row['Label'] == row['predicted']:\n        correct += 1\n        \nprint('Correct:', correct)\nprint('Incorrect:', total - correct)\nprint('Accuracy:', correct/total)\n```\n\n    Correct: 1100\n    Incorrect: 14\n    Accuracy: 0.9874326750448833\n\n\nThe accuracy is close to 98.74%, which is really good. Our spam filter looked at 1,114 messages that it hasn't seen in training, and classified 1,100 correctly.\n\n\n```python\n\n```\n", "meta": {"hexsha": "e91d40b993f67078a16136a1318787c834c45797", "size": 43158, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Basics.ipynb", "max_stars_repo_name": "bibekuchiha/Building-a-Spam-Filter-with-Naive-Bayes", "max_stars_repo_head_hexsha": "88dfc6605e33e47e4b7a6cf6adb294805d66aa96", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Basics.ipynb", "max_issues_repo_name": "bibekuchiha/Building-a-Spam-Filter-with-Naive-Bayes", "max_issues_repo_head_hexsha": "88dfc6605e33e47e4b7a6cf6adb294805d66aa96", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Basics.ipynb", "max_forks_repo_name": "bibekuchiha/Building-a-Spam-Filter-with-Naive-Bayes", "max_forks_repo_head_hexsha": "88dfc6605e33e47e4b7a6cf6adb294805d66aa96", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0125173853, "max_line_length": 569, "alphanum_fraction": 0.4208721442, "converted": true, "num_tokens": 7372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936413143782797, "lm_q2_score": 0.10087861732378865, "lm_q1q2_score": 0.03625215669521233}}
{"text": "# Building a ME-model\n\n\n```python\nfrom __future__ import print_function\n\nimport cobrame\nfrom cobrame.util import dogma, building\nimport cobrame.util.building\nimport cobra\nimport cobra.test\nfrom collections import defaultdict\n\n#import warnings\n#warnings.filterwarnings('ignore')\n```\n\n    /home/sbrg-cjlloyd/cobrapy/cobra/io/sbml3.py:24: UserWarning: Install lxml for faster SBML I/O\n      warn(\"Install lxml for faster SBML I/O\")\n    /home/sbrg-cjlloyd/cobrapy/cobra/io/__init__.py:12: UserWarning: cobra.io.sbml requires libsbml\n      warn(\"cobra.io.sbml requires libsbml\")\n\n\n## Overview\n\nCOBRAme is constructed entirely over COBRApy. This means that ME-model reactions will have all of the same properties, methods, and functions as a COBRApy reaction. However, one key difference between M and ME models is that many reactions involved in gene expression are effecively templates that are constructed identically but vary based on characteristics of the gene being expressed. For example, a gene with a given nucleotide sequence is always translated following the same rules provided by the codon table for that organism.\n\nIn order to facilliate the template nature of many gene expression reactions, COBRAme reactions are constructed and their components are manipulated through the use of `ProcessData` classes. These act as information vessels for holding the information assocatied with a cellular process in simple, standard datatypes such as dictionaries and strings. \n\n-----\n\nThis tutorial will go step-by-step through the process of creating a generic enzyme catalyzed reaction (i.e. metabolic reaction):\n\nwhich requires the formation and coupling of **complex\\_ab** in order to proceed.\n\n-------\n\nIn order for this reaction to carry flux in the model we will additionally need to first add the corresponding:\n \n 1. **Transcription reactions**\n 2. **Translation reactions**\n 3. **tRNA charging reactions**\n 4. **Complex formation reactions**\n\nOnce these are added we will add in the synthesis of key macromolecular components (ribosome, RNA polymerase, etc.) and show how they are coupled to their respective reactions. The derived coupling coefficients will also be described. For more on the derivation of the coupling coefficients, reference the supplemental text of [O'brien et. al. 2013](https://www.ncbi.nlm.nih.gov/pubmed/24084808)\n\n## Initializing new ME-Models\n\nWhen applying some constraints in the ME-model, metabolite properties are required. For instance, to calculate the total biomass (by molecular weight) produced by a particular macromolecule, the amino acid, nucleotide, etc. molecular weights are required. To enable these calculations, all metabolites from *i*JO1366, along with their metabolite attributes are added to the newly initialized ME-model.\n\nFurther the reactions from *i*JO1366 will be added to the ME-model to demonstrate ME-model solving procedures.\n\n\n```python\n# create empty ME-model\nme = cobrame.MEModel('test')\nijo = cobra.test.create_test_model('ecoli')\n```\n\n\n```python\n# Add all metabolites and reactions from iJO1366 to the new ME-model\nfor met in ijo.metabolites:\n    me.add_metabolites(met)\nfor rxn in ijo.reactions:\n    me.add_reaction(rxn)\n```\n\nThe ME-model contains a \"global_info\" attribute which stores information used to calculate coupling constraints, along with other functions. The specifics of each of these constraints will be discussed when they are implemented.\n<br>\n<br>\n\n<div class=\"alert alert-info\">\n**Note**: k_deg will initially be set to 0. We will apply RNA degradation later in the tutorial.\n</div>\n\n\n```python\n# \"Translational capacity\" of organism\nme.global_info['kt'] = 4.5  # (in h-1)scott 2010, RNA-to-protein curve fit\nme.global_info['r0'] = 0.087  # scott 2010, RNA-to-protein curve fit\nme.global_info['k_deg'] = 1.0/5. * 60.0  # 1/5 1/min 60 min/h # h-1\n\n# Molecular mass of RNA component of ribosome\nme.global_info['m_rr'] = 1453. # in kDa\n\n# Average molecular mass of an amino acid\nme.global_info['m_aa'] = 109. / 1000.  # in kDa\n\n# Proportion of RNA that is rRNA\nme.global_info['f_rRNA'] = .86\nme.global_info['m_nt'] = 324. / 1000.  # in kDa\nme.global_info['f_mRNA'] = .02\n\n# tRNA associated global information\nme.global_info['m_tRNA'] = 25000. / 1000.  # in kDA\nme.global_info['f_tRNA'] = .12\n\n# Define the types of biomass that will be synthesized in the model\nme.add_biomass_constraints_to_model([\"protein_biomass\", \"mRNA_biomass\", \"tRNA_biomass\", \"rRNA_biomass\",\n                                     \"ncRNA_biomass\", \"DNA_biomass\", \"lipid_biomass\", \"constituent_biomass\",\n                                     \"prosthetic_group_biomass\", \"peptidoglycan_biomass\"])\n```\n\nDefine sequence of gene that will be expressed in tutorial\n\n\n```python\nsequence = (\"ATG\" + \"TTT\" * 12 + \"TAT\" * 12 + \n            \"ACG\" * 12 + \"GAT\" * 12 + \"AGT\" * 12 + \"TGA\")\n```\n\n## Adding Reactions without utility functions\nWe'll first demonstrate how transcription, translation, tRNA charging, complex formation, and metabolic reactions can be added to a model without using any of the utility functions provided in `cobrame.util.building.py`. The second half of the tutorial will show how these utility functions can be used to add these reactions.\n\nThe basic workflow for adding any reaction to a ME-model using COBRAme occurs in three steps:\n\n1. **Create the ProcessData(s) associated with the reaction and populate them with the necessary information**\n2. **Create the MEReaction and link the appropriate ProcessData**\n3. **Execute the MEReaction's update method**\n\n### Add Transcription Reaction\n\n#### Add TranscribedGene metabolite to model\nTranscription reactions is unique in that they occur at a transcription unit level and can code for multiple transcript products. Therefore the nucleotide sequence of both the transcription unit and the RNA transcripts must be defined in order to correctly construct a transcription reaction.\n\n\n```python\ngene = cobrame.TranscribedGene('RNA_a', 'mRNA', sequence)\nme.add_metabolites([gene])\n```\n\nWhen adding the `TranscribedGene` above, the `RNA_type` and `nucleotide_sequence` was assigned to the gene. This sequence cannot be determined from the transcription unit (TU) sequence because a single TU often contains several different RNAs.\n\n#### Add TranscriptionData to model\n\n\n```python\ntranscription_data = cobrame.TranscriptionData('TU_a',me,rna_products={'RNA_a'})\ntranscription_data.nucleotide_sequence = sequence\n```\n\n#### Add TranscriptionReaction to model\nAnd point `TranscriptionReaction` to `TranscriptionData`\n\n\n```python\ntranscription_rxn = cobrame.TranscriptionReaction('transcription_TU_a')\ntranscription_rxn.transcription_data = transcription_data\nme.add_reactions([transcription_rxn])\n```\n\n#### Update TranscriptionReaction\n\n\n```python\ntranscription_rxn.update()\nprint(transcription_rxn.reaction)\n```\n\n    86 atp_c + 38 ctp_c + 12 gtp_c + 50 utp_c --> RNA_a + 59.172286 mRNA_biomass + 186 ppi_c\n\n\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/reaction.py:813 \u001b[1;31mUserWarning\u001b[0m: RNA Polymerase () not found\n\n\n<div class=\"alert alert-info\">\n**Note**: the RNA_polymerase complex is not included in the reaction. This will be added later\n</div>\n\nThis reaction now produces a small amount of the a `mRNA_biomass` metabolite (constraint). This term has a coefficient corresponding to the molecular weight (in $kDA$) of the RNA being transcribed. This constraint will be implemented into a $v_{biomasss\\_dilution}$ reaction with the form: \n$$\\mu \\leq v_{biomass\\_dilution} \\leq \\mu $$\n\nA mathematical description of the `biomass` constraint can be found in *Biomass Dilution Constraints* in **ME-Model Fundamentals**.\n\n<div class=\"alert alert-info\">\n**Note**: This is not a complete picture of transcription because the RNA polymerase is missing.\n</div>\n\n#### Incorporate RNA Polymerase\nFor the purposes of this tutorial, we'll skip the steps required to add the reactions to form the RNA_polymerase. The steps however are identical to those outlined in **add enzyme complexes** below\n\n\n```python\nRNAP = cobrame.RNAP('RNA_polymerase')\nme.add_metabolites(RNAP)\n```\n\nAssociate RNA_polymerase with all `TranscriptionData` and update\n\n\n```python\nfor data in me.transcription_data:\n    data.RNA_polymerase = RNAP.id\nme.reactions.transcription_TU_a.update()\n\nprint(me.reactions.transcription_TU_a.reaction)\n```\n\n    0.00088887053605567*mu + 0.000347992814865795 RNA_polymerase + 86 atp_c + 38 ctp_c + 12 gtp_c + 50 utp_c --> RNA_a + 59.172286 mRNA_biomass + 186 ppi_c\n\n\nThe coefficient for RNA_polymerase is the first instance in this tutorial where a coupling constraint is imposed. In this case the constraint couples the formation of a RNA_polymerase metabolite to its transcription flux. This constraint is formulated as in [O'brien et. al. 2013](https://www.ncbi.nlm.nih.gov/pubmed/24084808), with assumption that $k_{rnap} = 3 \\cdot k_{ribosome}$ based on data from [Proshkin et al. 2010](https://www.ncbi.nlm.nih.gov/pubmed/20413502):\n\n$$\n\\begin{align}\nv_{dilution,RNAP, j} =  \\frac{l_{TU,j}}{3 c_{ribo}\\kappa_{\\tau}} v_{transcription,j} (\\mu+r_0\\kappa_{\\tau}), & \\forall j \\in TU\n\\end{align}\n$$\n\nwhere:\n\n - $\\kappa_{\\tau}$ and $r_0$ are phenomenological parameters from [Scott et. al. 2010](https://www.ncbi.nlm.nih.gov/pubmed/21097934) that describe the linear relationship between the observed RNA/protein ratio of *E. coli* and its growth rate ($\\mu$)\n\n - $c_{ribo} = \\frac{m_{rr}}{f_{rRNA}\\cdot m_{aa}}$ where: $m_{nt}$ is the mass of rRNA per ribosome. $f_{rRNA}$ is the fraction of total RNA that is rRNA $m_{aa}$ is the molecular weight of an average amino acid\n\n - $v_{transcription, j}$ is the rate of transcription for $TU_j$\n \n - $l_{TU, j}$ is number of nucleotides in $TU_j$\n \n----\n### Add Translation Reaction\n#### Add TranslationData to model\nIn order to add a TranslationData object to a ME-model the user must additionally specifify the mRNA id and protein id of the translation reaction that will be added. This information as well as a nucleotide sequence is the only information required to add a translation reaction.\n\n\n```python\ndata = cobrame.TranslationData('a', me, 'RNA_a', 'protein_a')\ndata.nucleotide_sequence = sequence\n```\n\n#### Add TranslationReaction to model\nBy associating the TranslationReaction with its corresponding TranslationData object and running the update function, COBRAme will create a reaction reaction for the nucleotide sequence given based on the organisms codon table and prespecified translation machinery.\n\n\n```python\nrxn = cobrame.TranslationReaction('translation_a')\nrxn.translation_data = data\nme.add_reaction(rxn)\n```\n\n#### Update TranslationReaction\n\n\n```python\nrxn.update()\nprint(rxn.reaction)\n```\n\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/reaction.py:1051 \u001b[1;31mUserWarning\u001b[0m: ribosome not found\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/reaction.py:1094 \u001b[1;31mUserWarning\u001b[0m: RNA_degradosome not found\n\n\n    0.000498399634202103*mu + 0.000195123456790123 + 0.00598079561042524*(mu + 0.3915)/mu RNA_a + 12 asp__L_c + 0.276611796982167*(mu + 0.3915)/mu atp_c + 0.353897348367627*(mu + 0.3915)/mu mRNA_biomass + met__L_c + 12 phe__L_c + 12 ser__L_c + 12 thr__L_c + 12 tyr__L_c --> 0.276611796982167*(mu + 0.3915)/mu adp_c + 0.514348422496571*(mu + 0.3915)/mu amp_c + 0.227270233196159*(mu + 0.3915)/mu cmp_c + 0.0717695473251029*(mu + 0.3915)/mu gmp_c + 60.0 - 0.276611796982167*(mu + 0.3915)/mu h2o_c + 0.276611796982167*(mu + 0.3915)/mu h_c + 0.276611796982167*(mu + 0.3915)/mu pi_c + protein_a + 7.500606 protein_biomass + 0.299039780521262*(mu + 0.3915)/mu ump_c\n\n\nIn this case the constraint couples the formation of a mRNA metabolite to its translation flux. This constraint is formulated as in [O'brien et. al. 2013](https://www.ncbi.nlm.nih.gov/pubmed/24084808):\n\n$$\n\\begin{align}\nv_{dilution,j} = \\frac{3}{\\kappa_{\\tau} c_{mRNA}} \\cdot (\\mu + \\kappa_{\\tau} r_0) v_{translation,j}  , & &  \\forall j \\in mRNA\n\\end{align}\n$$\n\nwhere:\n\n - $\\kappa_{\\tau}$ and $r_0$ are phenomenological parameters from [Scott et. al. 2010](https://www.ncbi.nlm.nih.gov/pubmed/21097934) that describe the linear relationship between the observed RNA/protein ratio of *E. coli* and its growth rate ($\\mu$)\n\n - $c_{mRNA} = \\frac{m_{nt}}{f_{mRNA}\\cdot m_{aa}}$ where: $m_{nt}$ is the molecular weight of an average mRNA nucleotide. $f_{mRNA}$ is the fraction of total RNA that is mRNA $m_{aa}$ is the molecular weight of an average amino acid\n\n - $v_{translation, j}$ is the rate of translation for $mRNA_j$\n\n#### Incorporate Ribosome\n\n\n```python\nribosome = cobrame.Ribosome('ribosome')\nme.add_metabolites([ribosome])\nme.reactions.translation_a.update()\nprint(me.reactions.translation_a.reaction)\n```\n\n    0.000498399634202103*mu + 0.000195123456790123 + 0.00598079561042524*(mu + 0.3915)/mu RNA_a + 12 asp__L_c + 0.276611796982167*(mu + 0.3915)/mu atp_c + 0.353897348367627*(mu + 0.3915)/mu mRNA_biomass + met__L_c + 12 phe__L_c + 0.000874533914506385*mu + 0.00034238002752925 ribosome + 12 ser__L_c + 12 thr__L_c + 12 tyr__L_c --> 0.276611796982167*(mu + 0.3915)/mu adp_c + 0.514348422496571*(mu + 0.3915)/mu amp_c + 0.227270233196159*(mu + 0.3915)/mu cmp_c + 0.0717695473251029*(mu + 0.3915)/mu gmp_c + 60.0 - 0.276611796982167*(mu + 0.3915)/mu h2o_c + 0.276611796982167*(mu + 0.3915)/mu h_c + 0.276611796982167*(mu + 0.3915)/mu pi_c + protein_a + 7.500606 protein_biomass + 0.299039780521262*(mu + 0.3915)/mu ump_c\n\n\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/reaction.py:1094 \u001b[1;31mUserWarning\u001b[0m: RNA_degradosome not found\n\n\nThis imposes a new coupling constraint for the ribosome. In this case the constraint couples the formation of a ribosome to its translation flux. This constraint is formulated as in [O'brien et. al. 2013](https://www.ncbi.nlm.nih.gov/pubmed/24084808):\n\n$$\n\\begin{align}\nv_{dilution,ribo, j} = \\frac{l_{p,j}}{c_{ribo}\\kappa_{\\tau}} v_{translation,j} (\\mu+r_0\\kappa_{\\tau}) , & \\forall j \\in mRNA\n\\end{align}\n$$\n\nwhere:\n\n - $\\kappa_{\\tau}$ and $r_0$ are phenomenological parameters from [Scott et. al. 2010](https://www.ncbi.nlm.nih.gov/pubmed/21097934) that describe the linear relationship between the observed RNA/protein ratio of *E. coli* and its growth rate ($\\mu$)\n\n - $c_{ribo} = \\frac{m_{rr}}{f_{rRNA}\\cdot m_{aa}}$ where: $m_{nt}$ is the mass of rRNA per ribosome. $f_{rRNA}$ is the fraction of total RNA that is rRNA $m_{aa}$ is the molecular weight of an average amino acid\n\n - $v_{translation, j}$ is the rate of translation for $mRNA_j$\n \n - $l_{p, j}$ is number of amino acids in peptide translated from $mRNA_j$\n \n-------\n<div class=\"alert alert-info\">\n**Note**: The above reactions do not provide a complete picture of translation in that it is missing charged tRNAs to facillitate tRNA addition.\n</div>\n\nBelow, we'll correct this by adding in an tRNA charging reaction.\n\n### Add tRNA Charging Reaction\n\n#### Add tRNAData to model\n\n\n```python\n# Must add tRNA metabolite first\ngene = cobrame.TranscribedGene('RNA_d', 'tRNA', sequence)\nme.add_metabolites([gene])\n```\n\n\n```python\ndata = cobrame.tRNAData('tRNA_d_GUA', me, 'val__L_c', 'RNA_d', 'GUA')\n```\n\n#### Add tRNAChargingReaction to model\nAnd point `tRNAChargingReaction` to `tRNAData`\n\n\n```python\nrxn = cobrame.tRNAChargingReaction('charging_tRNA_d_GUA')\nme.add_reaction(rxn)\nrxn.tRNA_data = data\n```\n\n#### Update tRNAChargingReaction\n\n\n```python\n#Setting verbose=False suppresses print statements indicating that new metabolites were created\nrxn.update(verbose=False)\nprint(rxn.reaction)\n```\n\n    0.000116266666666667*mu + 4.55184e-5 RNA_d + 0.000116266666666667*mu + 4.55184e-5 val__L_c --> generic_tRNA_GUA_val__L_c\n\n\nThis reaction creates one ```generic_charged_tRNA``` equivalement that can then be used in a translation reaction\n\nThe coefficient for ```RNA_d``` and ```lys__L_c``` are defined by:\n\n$$\n\\begin{align}\nv_{dilution,j} \\geq \\frac{1}{\\kappa_{\\tau} c_{tRNA,j}} (\\mu + \\kappa_{\\tau} r_0)  v_{charging,j} , & \\forall j \\in tRNA\n\\end{align}\n$$\n\nwhere:\n\n - $\\kappa_{\\tau}$ and $r_0$ are phenomenological parameters from [Scott et. al. 2010](https://www.ncbi.nlm.nih.gov/pubmed/21097934) that describe the linear relationship between the observed RNA/protein ratio of *E. coli* and its growth rate ($\\mu$)\n\n - $c_{tRNA, j} = \\frac{m_{tRNA}}{f_{tRNA}\\cdot m_{aa}}$ where: $m_{tRNA}$ is molecular weight of an average tRNA. $f_{tRNA}$ is the fraction of total RNA that is tRNA $m_{aa}$ is the molecular weight of an average amino acid\n\n - $v_{charging, j}$ is the rate of charging for $tRNA_j$\n \n<div class=\"alert alert-info\">\n**Note**: This tRNA charging reaction is still missing a tRNA synthetase which catalyzes the amino acid addition to the uncharged tRNA.\n</div>\n\n#### Incorporate tRNA Synthetases\n.. autoclass:: cobrame.core.component.Complex\n   :noindex:\n\n```python\nsynthetase = cobrame.Complex('synthetase')\nme.add_metabolites(synthetase)\n```\n\nAssociate synthetase with `tRNAData` and update\n\n\n```python\ndata.synthetase = synthetase.id\nrxn.update()\nprint(rxn.reaction)\n```\n\n    0.000116266666666667*mu + 4.55184e-5 RNA_d + 4.27350427350427e-6*mu*(0.000116266666666667*mu + 1.0000455184) synthetase + 0.000116266666666667*mu + 4.55184e-5 val__L_c --> generic_tRNA_GUA_val__L_c\n\n\nThe synthetase coupling was reformulated from [O'brien et. al. 2013](https://www.ncbi.nlm.nih.gov/pubmed/24084808) enable more modularity in the ME-model. A more complete mathematical description of the tRNA synthetase coupling constraints can be found in the [tRNA.ipynb](tRNA.ipynb)\n\n---\n\n### Add tRNAs to Translation\n\nHere we take advantage of an additional subclass of `ProcessData`, called a `SubreactionData` object. This class is used to lump together processeses that occur as a result of many individual reactions, including translation elongation, ribosome formation, tRNA modification, etc. Since each of these steps often involve an enzyme that requires its own coupling constraint, this process allows these processes to be lumped into one reaction while still enabling each subprocess to be modified.\n\n`TranslationData` objects have an `subreaction_from_sequence` method that returns any subreactions that have been added to the model and are part of translation elongation (i.e. tRNA). Since no tRNA-mediated amino acid addition subreactions have been added to the model, the below call returns nothing.\n\n\n```python\nprint(me.process_data.a.subreactions_from_sequence)\n```\n\n    {}\n\n\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/processdata.py:826 \u001b[1;31mUserWarning\u001b[0m: tRNA addition subreaction phe_addition_at_UUU not in model\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/processdata.py:826 \u001b[1;31mUserWarning\u001b[0m: tRNA addition subreaction tyr_addition_at_UAU not in model\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/processdata.py:826 \u001b[1;31mUserWarning\u001b[0m: tRNA addition subreaction thr_addition_at_ACG not in model\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/processdata.py:826 \u001b[1;31mUserWarning\u001b[0m: tRNA addition subreaction asp_addition_at_GAU not in model\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/processdata.py:826 \u001b[1;31mUserWarning\u001b[0m: tRNA addition subreaction ser_addition_at_AGU not in model\n\n\n`UserWarnings` are returned to indicate that tRNA subreactions have not been added for each codon.\n\nBelow, we add the SubreactionData (excluding enzymes) for the addition of an amino acid using information from the *E. coli* codon table. The charge tRNA does not act as an enzyme in this case because it's coupling is handled in the `tRNAChargingReaction`\n\n#### Add Subreactions for tRNA addition to model\n\n\n```python\ndata = cobrame.SubreactionData('asp_addition_at_GAU', me)\ndata.stoichiometry = {'generic_tRNA_GAU_asp__L_c': -1,\n                      'gtp_c': -1, 'gdp_c': 1, 'h_c': 1,\n                      'pi_c': 1}\n```\n\nNow calling `subreactions_from_sequence` returns the number of tRNA subreactions that should be added to the `TranslationData`\n\n\n```python\ntranslation_subreactions = me.process_data.a.subreactions_from_sequence\nprint(translation_subreactions)\n```\n\n    {'asp_addition_at_GAU': 12}\n\n\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/processdata.py:826 \u001b[1;31mUserWarning\u001b[0m: tRNA addition subreaction phe_addition_at_UUU not in model\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/processdata.py:826 \u001b[1;31mUserWarning\u001b[0m: tRNA addition subreaction tyr_addition_at_UAU not in model\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/processdata.py:826 \u001b[1;31mUserWarning\u001b[0m: tRNA addition subreaction thr_addition_at_ACG not in model\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/processdata.py:826 \u001b[1;31mUserWarning\u001b[0m: tRNA addition subreaction ser_addition_at_AGU not in model\n\n\nUpdating `TranslationData.subreactions` with the tRNA subreactions incorporates this information into the `TranslationReaction`\n\n\n```python\nprint(\"Before adding tRNA subreaction\")\nprint(\"------------------------------\")\nprint(me.reactions.translation_a.reaction)\nprint(\"\")\n# Link tranlation_data to subreactions and update\nfor subreaction, value in translation_subreactions.items():\n    me.process_data.a.subreactions[subreaction] = value\nme.reactions.translation_a.update(verbose=False)\nprint(\"After adding tRNA subreaction\")\nprint(\"-----------------------------\")\nprint(me.reactions.translation_a.reaction)\n```\n\n    Before adding tRNA subreaction\n    ------------------------------\n    0.000498399634202103*mu + 0.000195123456790123 + 0.00598079561042524*(mu + 0.3915)/mu RNA_a + 12 asp__L_c + 0.276611796982167*(mu + 0.3915)/mu atp_c + 0.353897348367627*(mu + 0.3915)/mu mRNA_biomass + met__L_c + 12 phe__L_c + 0.000874533914506385*mu + 0.00034238002752925 ribosome + 12 ser__L_c + 12 thr__L_c + 12 tyr__L_c --> 0.276611796982167*(mu + 0.3915)/mu adp_c + 0.514348422496571*(mu + 0.3915)/mu amp_c + 0.227270233196159*(mu + 0.3915)/mu cmp_c + 0.0717695473251029*(mu + 0.3915)/mu gmp_c + 60.0 - 0.276611796982167*(mu + 0.3915)/mu h2o_c + 0.276611796982167*(mu + 0.3915)/mu h_c + 0.276611796982167*(mu + 0.3915)/mu pi_c + protein_a + 7.500606 protein_biomass + 0.299039780521262*(mu + 0.3915)/mu ump_c\n    \n    After adding tRNA subreaction\n    -----------------------------\n    0.000498399634202103*mu + 0.000195123456790123 + 0.00598079561042524*(mu + 0.3915)/mu RNA_a + 12 asp__L_c + 0.276611796982167*(mu + 0.3915)/mu atp_c + 12.0 generic_tRNA_GAU_asp__L_c + 12.0 gtp_c + 0.353897348367627*(mu + 0.3915)/mu mRNA_biomass + met__L_c + 12 phe__L_c + 0.000874533914506385*mu + 0.00034238002752925 ribosome + 12 ser__L_c + 12 thr__L_c + 12 tyr__L_c --> 0.276611796982167*(mu + 0.3915)/mu adp_c + 0.514348422496571*(mu + 0.3915)/mu amp_c + 0.227270233196159*(mu + 0.3915)/mu cmp_c + 12.0 gdp_c + 0.0717695473251029*(mu + 0.3915)/mu gmp_c + 60.0 - 0.276611796982167*(mu + 0.3915)/mu h2o_c + 12.0 + 0.276611796982167*(mu + 0.3915)/mu h_c + 12.0 + 0.276611796982167*(mu + 0.3915)/mu pi_c + protein_a + 7.500606 protein_biomass + 0.299039780521262*(mu + 0.3915)/mu ump_c\n\n\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/reaction.py:1094 \u001b[1;31mUserWarning\u001b[0m: RNA_degradosome not found\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/processdata.py:229 \u001b[1;31mUserWarning\u001b[0m: No element contribution input for subreaction (asp_addition_at_GAU), calculating based on stoichiometry instead\n\n\n### Add Complex Formation Reaction\n#### Add ComplexData to model\nFor COBRAme models, the reaction gene-protein-reaction rule (GPR) is replaced with a metabolite representing the synthesis of the enzyme(s) catalyzing a reaction. This metabolite is formed explicitly in a ME model by seperate reaction to transcribe the gene(s) and translate the protein(s) the compose the complex. \n\n\n```python\ndata = cobrame.ComplexData('complex_ab', me)\ndata.stoichiometry = {'protein_a': 1, 'protein_b': 1}\n```\n\n#### Add  ComplexFormation reaction to model\nAnd point `ComplexFormation` to `ComplexData`\n.. autoclass:: cobrame.core.reaction.ComplexFormation\n   :noindex:\n\n```python\nrxn = cobrame.ComplexFormation('formation_complex_ab')\nme.add_reaction(rxn)\nrxn.complex_data_id = data.id\nrxn._complex_id = data.id\n```\n\n#### Update ComplexFormation reaction\n\n\n```python\nrxn.update(verbose=False)\nprint(me.reactions.formation_complex_ab.reaction)\n```\n\n    protein_a + protein_b --> complex_ab\n\n\n#### Apply modification to complex formation reaction\nMany enzyme complexes in an ME-model require cofactors or prosthetic groups in order to properly function. Information about such processes are stored as ModificationData.\n\nFor instance, we can add the modification of an iron-sulfur cluster, a common prosthetic group, by doing the following:\n\n\n```python\n# Define the stoichiometry of the modification \nmod_data = cobrame.SubreactionData('mod_2fe2s_c', me)\nmod_data.stoichiometry = {'2fe2s_c': -1}\n# this process can also be catalyzed by a chaperone\nmod_data.enzyme = 'complex_ba'\nmod_data.keff = 65.  # default value\n```\n\nAssociate modification to complex and ```update()``` its formation\n\n\n```python\ncomplex_data = me.process_data.complex_ab\ncomplex_data.subreactions['mod_2fe2s_c'] = 1\n```\n\nUpdate ComplexFormation reaction\n\n\n```python\nprint('Before adding modification')\nprint('--------------------------')\nprint(me.reactions.formation_complex_ab.reaction)\nme.reactions.formation_complex_ab.update()\nprint('\\n')\nprint('After adding modification')\nprint('-------------------------')\nprint(me.reactions.formation_complex_ab.reaction)\n```\n\n    Before adding modification\n    --------------------------\n    protein_a + protein_b --> complex_ab\n    Created <Complex complex_ba at 0x7f4bf69a8b38> in <ComplexFormation formation_complex_ab at 0x7f4bf5f13ef0>\n    \n    \n    After adding modification\n    -------------------------\n    2fe2s_c + 4.27350427350427e-6*mu complex_ba + protein_a + protein_b --> complex_ab + 0.17582 prosthetic_group_biomass\n\n\n### Add Metabolic Reaction\n#### Add StoichiometricData to model\nMetabolicReactions require, at a minimum, one corresponding StoichiometricData. StoichiometricData essentially holds the information contained in an M-model reaction. This includes the metabolite stoichiometry and the upper and lower bound of the reaction. As a best practice, StoichiometricData typically uses an ID equivalent to the M-model reaction ID.\n\nSo first, we will create a StoichiometricData object to define the stoichiometry of the conversion of *a* to *b*. **Only one StoichiometricData object should be created for both reversible and irreversible reactions**\n\n\n```python\n# unique to COBRAme, construct a stoichiometric data object with the reaction information\ndata = cobrame.StoichiometricData('a_to_b', me)\nstoichiometry = {'a':-1, 'b': 1}\ndata._stoichiometry = stoichiometry\ndata.lower_bound = -1000\ndata.upper_bound = 1000\n```\n\n#### Add MetabolicReaction to model\n\nThe StoichiometricData for this reversible reaction is then assigned to two different MetabolicReactions (Due to the enzyme dilution constraint, all enzyme catalyzed reactions must be reverisble; more on this later). The MetabolicReactions require:\n - The associated StoichiometricData\n - The *reverse* flag set to True for reverse reactions, False for forward reactions\n - Enzyme $K_{eff}$ for reaction (discussed later, dafault=65)\n\nThese fields are then processed and the actual model reaction is created using the MetabolicReaction's update() function\n\n\n```python\n# Create a forward ME Metabolic Reaction and associate the stoichiometric data to it\nrxn_fwd = cobrame.MetabolicReaction('a_to_b_FWD_complex_ab')\nme.add_reaction(rxn_fwd)\nrxn_fwd.stoichiometric_data = data\nrxn_fwd.reverse = False\nrxn_fwd.keff = 65.\n\n# Create a reverse ME Metabolic Reaction and associate the stoichiometric data to it\nrxn_rev = cobrame.MetabolicReaction('a_to_b_REV_complex_ab')\nme.add_reaction(rxn_rev)\nrxn_rev.stoichiometric_data = data\nrxn_rev.reverse = True\nrxn_rev.keff = 65.\n```\n\n#### Update MetabolicReactions\n\n\n```python\nrxn_fwd.update(verbose=False)\nrxn_rev.update(verbose=False)\nprint(me.reactions.a_to_b_FWD_complex_ab.reaction)\nprint(me.reactions.a_to_b_REV_complex_ab.reaction)\n```\n\n    a --> b\n    b --> a\n\n\n<div class=\"alert alert-info\">\n**Note**: the $k_{eff}$ and `complex_ab` is not included in the reaction since no complex has been associated to it yet\n</div>\n\n#### Associate enzyme with MetabolicReaction\n\nThe ComplexData object created in the previous cell can be incorporated into the MetabolicReaction using code below. \n\n<div class=\"alert alert-info\">\n**Note**: the update() function is required to apply the change.\n</div>\n\n\n```python\ndata = me.process_data.complex_ab\nme.reactions.a_to_b_FWD_complex_ab.complex_data = data\nprint('Forward reaction (before update): %s' %\n      (me.reactions.a_to_b_FWD_complex_ab.reaction))\nme.reactions.a_to_b_FWD_complex_ab.update()\nprint('Forward reaction (after update): %s' %\n      (me.reactions.a_to_b_FWD_complex_ab.reaction))\nprint('')\n\nme.reactions.a_to_b_REV_complex_ab.complex_data = data\nprint('Reverse reaction (before update): %s' %\n      (me.reactions.a_to_b_REV_complex_ab.reaction))\nme.reactions.a_to_b_REV_complex_ab.update()\nprint('Reverse reaction (after update): %s' %\n      (me.reactions.a_to_b_REV_complex_ab.reaction))\n```\n\n    Forward reaction (before update): a --> b\n    Forward reaction (after update): a + 4.27350427350427e-6*mu complex_ab --> b\n    \n    Reverse reaction (before update): b --> a\n    Reverse reaction (after update): b + 4.27350427350427e-6*mu complex_ab --> a\n\n\nThe coefficient for complex_ab is determined by the expression $$\\frac{\\mu}{k_{eff}}$$ which in its entirety represents the dilution of an enzyme following a cell doubling. The coupling constraint can be summarized as followed\n$$ \n\\begin{align}\n&v_{dilution,j} = \\mu \\sum_{i} \\left( \\frac{1}{k_{eff,i}} v_{usage,i} \\right), & \\forall j \\in Enzyme\n\\end{align}\n$$\n\nWhere \n\n - $v_{usage,i}$ is the flux through the metabolic reaction\n - $k_{eff}$ is the turnover rate for the process and conveys the productivity of the enzyme complex. Physically, it can be thought of as the number of reactions the enzyme can catalyze per cell division. \n\n\nBy default the $k_{eff}$ for a MetabolicReaction is set to 65 but this can be changed using the code below.\n\n#### Different Keff for forward reaction\n\n\n```python\nme.reactions.a_to_b_FWD_complex_ab.keff = .00001\nme.reactions.a_to_b_FWD_complex_ab.update()\n\n# The forward and reverse direction can have differing keffs\nprint('Forward reaction')\nprint('----------------')\nprint(me.reactions.a_to_b_FWD_complex_ab.reaction)\nprint('')\nprint('Reverse reaction')\nprint('----------------')\nprint(me.reactions.a_to_b_REV_complex_ab.reaction)\n```\n\n    Forward reaction\n    ----------------\n    a + 27.7777777777778*mu complex_ab --> b\n    \n    Reverse reaction\n    ----------------\n    b + 4.27350427350427e-6*mu complex_ab --> a\n\n\n## Adding Reactions using utility functions\nAdd reactions using some of the utility functions provided in `cobrame.util.building.py`\n\n### Transcription\nUsing the utility functions to create the TranscribedGene metabolite has the advantage of forcing the assignment of sequence, strand and RNA_type. \n\n\n```python\nbuilding.create_transcribed_gene(me, 'b','tRNA', 'ATCG')\nbuilding.add_transcription_reaction(me, 'TU_b', {'b'}, sequence)\nprint(me.reactions.transcription_TU_b.reaction)\nme.reactions.transcription_TU_b.update()\n```\n\n    86 atp_c + 38 ctp_c + 12 gtp_c + 182 h2o_c + 50 utp_c --> RNA_b + 85 amp_c + 37 cmp_c + 11 gmp_c + 182 h_c + 186 ppi_c + 1.2817349999999998 tRNA_biomass + 49 ump_c\n\n\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/reaction.py:813 \u001b[1;31mUserWarning\u001b[0m: RNA Polymerase () not found\n\n\n### Translation\n`add_translation_reaction` assumes that the RNA and protein have the same locus_id. It creates the appropriate `TranslationData` and `TranslationReaction` instance, links the two together and updates the `TranslationReaction`.\n\n\n```python\nbuilding.add_translation_reaction(me, 'b', dna_sequence=sequence, update=True)\nprint(me.reactions.translation_b.reaction)\n```\n\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/reaction.py:1094 \u001b[1;31mUserWarning\u001b[0m: RNA_degradosome not found\n\n\n    0.000498399634202103*mu + 0.000195123456790123 + 0.00598079561042524*(mu + 0.3915)/mu RNA_b + 12 asp__L_c + 0.00448559670781893*(mu + 0.3915)/mu atp_c + 0.0076657950617284*(mu + 0.3915)/mu mRNA_biomass + met__L_c + 12 phe__L_c + 0.000874533914506385*mu + 0.00034238002752925 ribosome + 12 ser__L_c + 12 thr__L_c + 12 tyr__L_c --> 0.00448559670781893*(mu + 0.3915)/mu adp_c + 0.00598079561042524*(mu + 0.3915)/mu amp_c + 0.00598079561042524*(mu + 0.3915)/mu cmp_c + 0.00598079561042524*(mu + 0.3915)/mu gmp_c + 60.0 - 0.00448559670781893*(mu + 0.3915)/mu h2o_c + 0.00448559670781893*(mu + 0.3915)/mu h_c + 0.00448559670781893*(mu + 0.3915)/mu pi_c + protein_b + 7.500606 protein_biomass + 0.00598079561042524*(mu + 0.3915)/mu ump_c\n\n\n### Complex Formation\nAlternatively, ComplexData has a ```create_complex_formation()``` function to create the sythesis reaction following the naming conventions. It contains an ```update()``` function which incorporates changes in the ComplexData\n\n\n```python\ndata = cobrame.ComplexData('complex_ba', me)\ndata.stoichiometry = {'protein_a': 1, 'protein_b': 1}\ndata.create_complex_formation()\nprint(me.reactions.formation_complex_ba.reaction)\n```\n\n    protein_a + protein_b --> complex_ba\n\n\n### Metabolic Reaction\n\n\n```python\nstoich_data = cobrame.StoichiometricData('b_to_c', me)\nstoich_data._stoichiometry = {'b': -1, 'c': 1}\nstoich_data.lower_bound = 0\nstoich_data.upper_bound = 1000.\nbuilding.add_metabolic_reaction_to_model(me, stoich_data.id, 'forward', complex_id='complex_ab',\n                                         update=True)\nprint('Reaction b_to_c')\nprint('---------------')\nprint(me.reactions.b_to_c_FWD_complex_ab.reaction)\n```\n\n    Created <Metabolite c at 0x7f4bf6abf6d8> in <MetabolicReaction b_to_c_FWD_complex_ab at 0x7f4bf6abf7b8>\n    Reaction b_to_c\n    ---------------\n    b + 4.27350427350427e-6*mu complex_ab --> c\n\n", "meta": {"hexsha": "6d7cea882efda3b0f211c58083a4141d598e124e", "size": 54329, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/building_a_model.ipynb", "max_stars_repo_name": "zakandrewking/cobrame", "max_stars_repo_head_hexsha": "66fc05de462f1aa9ce79c9812f7a24457560510b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/building_a_model.ipynb", "max_issues_repo_name": "zakandrewking/cobrame", "max_issues_repo_head_hexsha": "66fc05de462f1aa9ce79c9812f7a24457560510b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/building_a_model.ipynb", "max_forks_repo_name": "zakandrewking/cobrame", "max_forks_repo_head_hexsha": "66fc05de462f1aa9ce79c9812f7a24457560510b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-07T08:39:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-07T08:39:29.000Z", "avg_line_length": 33.5364197531, "max_line_length": 795, "alphanum_fraction": 0.6128218815, "converted": true, "num_tokens": 9801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.0747700506393715, "lm_q1q2_score": 0.03621712343009316}}
{"text": "# Rich Output\n\nIn Python, objects can declare their textual representation using the `__repr__` method.  IPython expands on this idea and allows objects to declare other, rich representations including:\n\n* HTML\n* JSON\n* PNG\n* JPEG\n* SVG\n* LaTeX\n\nA single object can declare some or all of these representations; all are handled by IPython's **display system**. This Notebook shows how you can use this display system to incorporate a broad range of content into your Notebooks.\n\n## Basic display imports\n\nThe `display` function is a general purpose tool for displaying different representations of objects. Think of it as `print` for these rich representations.\n\n\n```python\nfrom IPython.display import display\n```\n\nA few points:\n\n* Calling `display` on an object will send **all** possible representations to the Notebook.\n* These representations are stored in the Notebook document.\n* In general the Notebook will use the richest available representation.\n\nIf you want to display a particular representation, there are specific functions for that:\n\n\n```python\nfrom IPython.display import (\n    display_pretty, display_html, display_jpeg,\n    display_png, display_json, display_latex, display_svg\n)\n```\n\n## Images\n\nTo work with images (JPEG, PNG) use the `Image` class.\n\n\n```python\nfrom IPython.display import Image\n```\n\n\n```python\ni = Image(filename='./ipython_logo.png')\n```\n\nReturning an `Image` object from an expression will automatically display it:\n\n\n```python\ni\n```\n\nOr you can pass an object with a rich representation to `display`:\n\n\n```python\ndisplay(i)\n```\n\nAn image can also be displayed from raw data or a URL.\n\n\n```python\nImage(url='http://python.org/images/python-logo.gif')\n```\n\n## HTML\n\nPython objects can declare HTML representations that will be displayed in the Notebook. If you have some HTML you want to display, simply use the `HTML` class.\n\n\n```python\nfrom IPython.display import HTML\n```\n\n\n```python\ns = \"\"\"<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\"\"\"\n```\n\n\n```python\nh = HTML(s)\n```\n\n\n```python\ndisplay(h)\n```\n\nYou can also use the `%%html` cell magic to accomplish the same thing.\n\n\n```python\n%%html\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n```\n\n## JavaScript\n\nThe Notebook also enables objects to declare a JavaScript representation. At first, this may seem odd as  output is inherently visual and JavaScript is a programming language. However, this opens the door for rich output that leverages the full power of JavaScript and associated libraries such as [d3.js](http://d3js.org) for output.\n\n\n```python\nfrom IPython.display import Javascript\n```\n\nPass a string of JavaScript source code to the `JavaScript` object and then display it.\n\n\n```python\njs = Javascript('alert(\"hi\")');\n```\n\n\n```python\ndisplay(js)\n```\n\nThe same thing can be accomplished using the `%%javascript` cell magic:\n\n\n```javascript\n%%javascript\n\nalert(\"hi\");\n```\n\n## LaTeX\n\nThe IPython display system also has builtin support for the display of mathematical expressions typeset in LaTeX, which is rendered in the browser using [MathJax](http://mathjax.org).\n\nYou can pass raw LaTeX test as a string to the `Math` object:\n\n\n```python\nfrom IPython.display import Math\nMath(r'F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx')\n```\n\nWith the `Latex` class, you have to include the delimiters yourself.  This allows you to use other LaTeX modes such as `eqnarray`:\n\n\n```python\nfrom IPython.display import Latex\nLatex(r\"\"\"\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\"\"\")\n```\n\nOr you can enter LaTeX directly with the `%%latex` cell magic:\n\n\n```latex\n%%latex\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n```\n\n## Audio\n\nIPython makes it easy to work with sounds interactively. The `Audio` display class allows you to create an audio control that is embedded in the Notebook. The interface is analogous to the interface of the `Image` display class. All audio formats supported by the browser can be used. Note that no single format is presently supported in all browsers.\n\n\n```python\nfrom IPython.display import Audio\nAudio(url=\"http://www.nch.com.au/acm/8k16bitpcm.wav\")\n```\n\nA NumPy array can be auralized automatically. The `Audio` class normalizes and encodes the data and embeds the resulting audio in the Notebook.\n\nFor instance, when two sine waves with almost the same frequency are superimposed a phenomena known as [beats](https://en.wikipedia.org/wiki/Beat_%28acoustics%29) occur. This can be auralised as follows:\n\n\n```python\nimport numpy as np\nmax_time = 3\nf1 = 220.0\nf2 = 224.0\nrate = 8000.0\nL = 3\ntimes = np.linspace(0,L,rate*L)\nsignal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times)\n\nAudio(data=signal, rate=rate)\n```\n\n## Video\n\nMore exotic objects can also be displayed, as long as their representation supports the IPython display protocol.  For example, videos hosted externally on YouTube are easy to load:\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('sjfsUzECqK0')\n```\n\nUsing the nascent video capabilities of modern browsers, you may also be able to display local\nvideos.  At the moment this doesn't work very well in all browsers, so it may or may not work for you;\nwe will continue testing this and looking for ways to make it more robust.  \n\nThe following cell loads a local file called  `animation.m4v`, encodes the raw video as base64 for http\ntransport, and uses the HTML5 video tag to load it. On Chrome 15 it works correctly, displaying a control bar at the bottom with a play/pause button and a location slider.\n\n\n```python\nfrom IPython.display import HTML\nfrom base64 import b64encode\nvideo = open(\"./animation.m4v\", \"rb\").read()\nvideo_encoded = b64encode(video).decode('ascii')\nvideo_tag = '<video controls alt=\"test\" src=\"data:video/x-m4v;base64,{0}\">'.format(video_encoded)\nHTML(data=video_tag)\n```\n\n## External sites\n\nYou can even embed an entire page from another site in an iframe; for example this is today's Wikipedia\npage for mobile users:\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('http://ipython.org', width='100%', height=350)\n```\n\n# Exercises\n\n## Basic display classes\n\n\n```python\nfrom IPython.display import display, Image, HTML, Javascript\n```\n\nTry using the basic display classes in a notebook.\n- Find an image on the internet and display it in a notebook using the Image class. You can either save the image in the notebook's directory or load it by its URL.\n\n\n```python\n\n```\n\n- Use the HTML class and the %%html cell magic to display a snippet of HTML.\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n- Use the JavaScript class and the %%javascript cell magic to run a snippet of JavaScript.\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "4c9815a9d8d4e7fb6b490bf2aedc473885044133", "size": 17023, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "01 - Multimedia.ipynb", "max_stars_repo_name": "isabella232/strata-sv-2015-tutorial", "max_stars_repo_head_hexsha": "7bcd8973bc7825e5e9c4edadbad037945e601f6f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2015-02-12T15:55:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-29T17:04:38.000Z", "max_issues_repo_path": "01 - Multimedia.ipynb", "max_issues_repo_name": "jupyter/strata-sv-2015-tutorial", "max_issues_repo_head_hexsha": "7bcd8973bc7825e5e9c4edadbad037945e601f6f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2015-01-28T22:18:34.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-18T17:51:37.000Z", "max_forks_repo_path": "01 - Multimedia.ipynb", "max_forks_repo_name": "isabella232/strata-sv-2015-tutorial", "max_forks_repo_head_hexsha": "7bcd8973bc7825e5e9c4edadbad037945e601f6f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 43, "max_forks_repo_forks_event_min_datetime": "2015-01-28T22:16:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-03T07:39:08.000Z", "avg_line_length": 25.4835329341, "max_line_length": 359, "alphanum_fraction": 0.5050813605, "converted": true, "num_tokens": 2027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451488696663, "lm_q2_score": 0.1037486254807975, "lm_q1q2_score": 0.036171454975775896}}
{"text": "Name: Aly Baughman and Cynthia Parks|Student ID:1923165, 2303535|Email:baugh107@mail.chapman.edu, cparks@chapman.edu|Course: CS510 Fall 2017 Assignment: Classwork 5\n\n```python\nimport numpy as np    # Numeric python\nimport sympy as sp    # Symbolic python\nimport pandas as pd   # Data processing python\n```\n\n### Critiques of Aly's Code###\nThe organization of Aly's code was clear and done well.  They had docstrings for their functions but could have added a bit more detail.  The primes function was clear and easy to follow.  The algorithm makes sense and is a clear way to find prime numbers in a list.  Their Jupyter notebook was very well designed and clearly labeled with discussions of how the functions worked.  \n\n### Critiques of Cindy's Code ###\n\nThe organization of Cindy's code was great. It was formatted very well, with a very detailed docstrings section for the functions. I was able to follow along with the algorithm for primes. The only issue was that the generator did not run correctly. I really liked how her and her partner added error statements to the main function at the end of their primes.py code. The Jupyter notebook was very clear and easy to follow. The format was very nice and I liked how they implemented code portions in the Jupyter notebook. \n\n\n```python\n\n```\n", "meta": {"hexsha": "f3f11f0fce56d0c5a20212e85207e246caef0c80", "size": 2382, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "critique.ipynb", "max_stars_repo_name": "chapman-cs510-2017f/cw-05-alyandcyndi", "max_stars_repo_head_hexsha": "27baab7afa45095036e8a192326af9bac6390012", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "critique.ipynb", "max_issues_repo_name": "chapman-cs510-2017f/cw-05-alyandcyndi", "max_issues_repo_head_hexsha": "27baab7afa45095036e8a192326af9bac6390012", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "critique.ipynb", "max_forks_repo_name": "chapman-cs510-2017f/cw-05-alyandcyndi", "max_forks_repo_head_hexsha": "27baab7afa45095036e8a192326af9bac6390012", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.775, "max_line_length": 528, "alphanum_fraction": 0.6318219983, "converted": true, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.09947020587339865, "lm_q1q2_score": 0.03610462159874023}}
{"text": "## Arno's Exgram keyboard layout\n\n##### NOTE: README and evaluation tables NOT UPDATED\n\nExgram is a key layout optimized for comfortable and efficient touch typing in English \ncreated by [Arno Klein](https://binarybottle.com), and based on the Engram layout,\nwith [open source code](https://github.com/binarybottle/engram) to create other optimized key layouts.\n\nLetters are optimally arranged according to ergonomics factors that promote reduction of lateral finger movements and more efficient typing of high-frequency letter pairs, by minimizing the number of bigrams consisting of two different letters and typed with the same finger. The most common punctuation marks are logically grouped together in the middle columns and numbers are paired with mathematical and logic symbols (shown as pairs of default and Shift-key-accessed characters):\n\n         [{ 1| 2= 3~ 4+  5<  6>  7^ 8& 9% 0* ]} /\\\n            pP yY oO uU  '(  \")  bB dD lL vV qQ #$ @`\n            cC iI eE aA  ,;  .:  nN tT rR sS zZ\n            gG kK jJ xX  -_  ?!  hH mM wW fF\n            \nLetter frequencies (Norvig, 2012), showing that the Exgram layout emphasizes keys in the home row and typed above the home row by the middle and ring fingers, and below by the index finger:\n\n          P   Y   O   U          B   D   L   V   Q\n          C   I   E   A          N   T   R   S   Z\n          G   K   J   X          H   M   W   F\n\n         76  59 272  97         53 136 145  38   4\n        119 270 445 287        258 331 224 232   3\n         67  19   6   8        180  90  60  86\n\nSee below for a full description and comparisons with other key layouts.\n\n<!--### Standard diagonal keyboard (default and Shift-key layers)\n\n\n### \"Ergonomic\" orthonormal keyboard (default and Shift-key layers)\n\n-->\n\n(c) 2021 Arno Klein, MIT license\n\n----------------\n\n# Contents\n1. [Why a new keyboard layout?](#why)\n2. [How does Exgram compare with other key layouts?](#scores)\n3. [Guiding criteria](#criteria)\n4. Setup:\n    - [Dependencies and functions](#import)\n    - [Speed matrix](#speed)\n    - [Strength matrix](#strength)\n    - [Flow matrix and Engram scoring model](#flow)\n5. Steps:\n    - [Step 1: Define the shape of the key layout to minimize lateral finger movements](#step1)\n    - [Step 2: Arrange the most frequent letters based on comfort and bigram frequencies](#step2)\n    - [Step 3: Optimize assignment of the remaining letters](#step3)\n    - [Step 4: Stability tests](#step4)\n    - [Step 5: Arrange non-letter characters in easy-to-remember places](#step5)\n\n## Why a new keyboard layout? <a name=\"why\">\n\n**Personal history** <br>\nIn the future, I hope to include an engaging rationale for why I took on this challenge.\nSuffice to say I love solving problems, and I have battled repetitive strain injury \never since I worked on an old DEC workstation at the MIT Media Lab while composing \nmy thesis back in the 1990s.\nI have experimented with a wide variety of human interface technologies over the years --\nvoice dictation, one-handed keyboard, keyless keyboard, foot mouse, and ergonomic keyboards \nlike the Kinesis Advantage and [Ergodox](https://configure.ergodox-ez.com/ergodox-ez/layouts/APXBR/latest/0) keyboards with different key switches.\nWhile these technologies can significantly improve comfort and reduce strain, \nif you have to type on a keyboard, it can only help to use a key layout optimized according to sound ergonomics principles. \n\nI have used different key layouts (Qwerty, Dvorak, Colemak, etc.)\nfor communications and for writing and programming projects,\nand have primarily relied on Colemak for the last 10 years. \n**I find that most to all of these key layouts:**\n\n- Demand too much strain on tendons\n    - *strenuous lateral extension of the index and little fingers*\n- Ignore the ergonomics of the human hand\n    - *different finger strengths*\n    - *different finger lengths*\n    - *natural roundedness of the hand*\n    - *easier for shorter fingers to reach below than above longer fingers*\n    - *easier for longer fingers to reach above than below shorter fingers*\n    - *ease of little-to-index finger rolls vs. reverse*\n- Over-emphasize alternation between hands and under-emphasize same-hand, different-finger transitions\n    - *same-row, adjacent finger transitions are easy and comfortable*\n    - *little-to-index finger rolls are easy and comfortable*\n\nWhile I used ergonomics principles outlined below and the accompanying code to help generate the Exgram layout,\nI also relied on massive bigram frequency data for the English language. \nif one were to follow the procedure below and use a different set of bigram frequencies for another language or text corpus,\nthey could create a variant of the Exgram layout, say \"Exgram-French\", better suited to the French language.\n    \n**Why \"Exgram\"?** <br>\nThe name is a pun, referring both to \"n-gram\", letter permutations and their frequencies that are used to compute the Exgram layout, but because this approach and layout is intended in part to minimize same-finger bigrams, we are removing n-grams, hence \"x\"-gram.\n\n## How does Exgram compare with other key layouts? <a name=\"scores\">\n\nDespite the fact that the Exgram layout was designed to reduce strain and discomfort, not specifically to increase speed or reduce finger travel from the home row, it scores higher than all other key layouts (Colemak, Dvorak, QWERTY, etc.) for some large, representative, publicly available data (all text sources are listed below and available on [GitHub](https://github.com/binarybottle/text_data)). Below are tables of different prominent key layouts scored using the Engram Scoring Model (detailed below).\n \n| Layout | Google bigrams | Alice | Romeo | Gita | Memento | 100K tweets | 20K tweets | MASC tweets | MASC spoken | COCA blogs | iweb | Monkey | Coder | Code |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Engram | 75.03 | 74.45 | 74.62 | 74.45 | 75.12 | 75.88 | 75.53 | 75.33 | 74.34 | 75.01 | 75.21 | 75.05 | 75.37 | 75.33 |\n| Halmak | 74.98 | 74.42 | 74.58 | 74.40 | 75.08 | 75.82 | 75.49 | 75.29 | 74.32 | 74.97 | 75.17 | 75.00 | 75.31 | 75.26 |\n| Hieamtsrn | 75.01 | 74.45 | 74.61 | 74.43 | 75.11 | 75.86 | 75.50 | 75.32 | 74.34 | 75.00 | 75.20 | 75.04 | 75.34 | 75.23 |\n| Colemak Mod-DH | 74.95 | 74.40 | 74.55 | 74.39 | 75.05 | 75.77 | 75.43 | 75.25 | 74.29 | 74.94 | 75.14 | 74.98 | 75.28 | 75.19 |\n| Norman | 74.91 | 74.38 | 74.52 | 74.37 | 75.02 | 75.72 | 75.39 | 75.21 | 74.27 | 74.90 | 75.09 | 74.94 | 75.22 | 75.17 |\n| Workman | 74.94 | 74.39 | 74.55 | 74.38 | 75.05 | 75.77 | 75.44 | 75.25 | 74.29 | 74.93 | 75.12 | 74.97 | 75.27 | 75.22 |\n| MTGap 2.0 | 74.94 | 74.39 | 74.54 | 74.38 | 75.05 | 75.75 | 75.42 | 75.23 | 74.28 | 74.92 | 75.12 | 74.96 | 75.27 | 75.18 |\n| QGMLWB | 74.91 | 74.37 | 74.52 | 74.35 | 75.02 | 75.73 | 75.40 | 75.21 | 74.27 | 74.90 | 75.09 | 74.94 | 75.23 | 75.13 |\n| Colemak | 74.93 | 74.37 | 74.53 | 74.37 | 75.02 | 75.75 | 75.40 | 75.24 | 74.27 | 74.92 | 75.12 | 74.96 | 75.26 | 75.20 |\n| Asset | 74.90 | 74.36 | 74.51 | 74.35 | 75.01 | 75.71 | 75.39 | 75.21 | 74.25 | 74.89 | 75.08 | 74.92 | 75.23 | 75.18 |\n| Capewell-Dvorak | 74.90 | 74.37 | 74.52 | 74.35 | 75.01 | 75.73 | 75.39 | 75.21 | 74.27 | 74.90 | 75.08 | 74.93 | 75.22 | 75.15 |\n| Klausler | 74.92 | 74.38 | 74.54 | 74.37 | 75.03 | 75.75 | 75.42 | 75.22 | 74.28 | 74.91 | 75.10 | 74.95 | 75.23 | 75.17 |\n| Dvorak | 74.90 | 74.37 | 74.53 | 74.35 | 75.01 | 75.73 | 75.40 | 75.20 | 74.27 | 74.90 | 75.09 | 74.93 | 75.20 | 75.17 |\n| QWERTY | 74.76 | 74.27 | 74.41 | 74.25 | 74.88 | 75.55 | 75.25 | 75.06 | 74.17 | 74.76 | 74.94 | 74.79 | 75.06 | 75.01 |\n    \n---\n    \n[Keyboard Layout Analyzer](http://patorjk.com/keyboard-layout-analyzer/) (KLA) scores for the same text sources:\n\n> The optimal layout score is based on a weighted calculation that factors in the distance your fingers moved (33%), how often you use particular fingers (33%), and how often you switch fingers and hands while typing (34%).\n\n| Layout | Alice in Wonderland | Romeo Juliet | Bhagavad Gita | Memento screenplay | 100K tweets | 20K tweets | MASC tweets | MASC spoken | COCA blogs | iweb | Monkey | Coder | Software languages |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Engram    | 69.10 | 61.26 | 61.68 | 56.50 | 63.87 | 58.64 | 60.05 | 63.64 | 69.45 | 68.26 | 67.64 | 47.70 | 48.73 |\n| Halmak    | 66.25 | 57.02 | 57.45 | 55.03 | 60.86 | 55.53 | 57.13 | 62.32 | 67.29 | 65.50 | 64.75 | 45.68 | 47.60 |\n| Hieamtsrn | 69.43 | 60.94 | 60.87 | 56.75 | 64.40 | 58.95 | 60.47 | 64.33 | 69.93 | 69.15 | 68.30 | 46.01 | 46.48 | \n| Colemak Mod-DH | 65.74 | 56.05 | 57.52 | 54.91 | 60.75 | 54.94 | 57.15 | 61.29 | 67.12 | 65.98 | 64.85 | 47.35 | 48.50 |\n| Norman    | 62.76 | 53.21 | 53.44 | 52.33 | 57.43 | 53.24 | 53.90 | 59.97 | 62.80 | 60.90 | 59.82 | 43.76 | 46.01 |\n| Workman   | 64.78 | 56.67 | 56.97 | 54.29 | 59.98 | 55.81 | 56.25 | 61.34 | 65.27 | 63.76 | 62.90 | 45.33 | 47.76 |\n| MTGAP 2.0 | 66.13 | 53.98 | 56.57 | 53.78 | 59.87 | 55.30 | 55.81 | 60.32 | 65.68 | 63.81 | 62.74 | 45.38 | 44.34 | \n| QGMLWB    | 65.45 | 55.67 | 55.57 | 54.07 | 60.51 | 56.05 | 56.90 | 62.23 | 66.26 | 64.76 | 63.91 | 46.38 | 45.72 |\n| Colemak   | 65.83 | 56.12 | 57.63 | 54.94 | 60.67 | 54.97 | 57.04 | 61.36 | 67.14 | 66.01 | 64.91 | 47.30 | 48.65 |\n| Asset     | 64.60 | 54.63 | 56.09 | 53.84 | 58.66 | 54.72 | 55.35 | 60.81 | 64.71 | 63.17 | 62.44 | 45.54 | 47.52 |\n| Capewell-Dvorak | 66.94 | 58.31 | 57.39 | 55.66 | 62.14 | 56.85 | 57.99 | 62.83 | 66.95 | 65.23 | 64.70 | 45.30 | 45.62 |\n| Klausler  | 68.24 | 59.91 | 59.71 | 55.75 | 62.57 | 56.45 | 58.34 | 64.04 | 68.34 | 66.89 | 66.31 | 46.83 | 45.66 |\n| Dvorak    | 65.86 | 58.18 | 57.29 | 55.09 | 60.93 | 55.56 | 56.59 | 62.75 | 66.64 | 64.87 | 64.26 | 45.46 | 45.55 | \n| QWERTY    | 53.06 | 43.74 | 44.92 | 44.25 | 48.28 | 44.99 | 44.59 | 51.79 | 52.31 | 50.19 | 49.18 | 38.46 | 39.89 | \n\n---\n\n| Layout | Year | Website |\n| --- | --- | --- |\n| Engram | 2021 | https://engram.dev |\n| [Halmak 2.2](https://keyboard-design.com/letterlayout.html?layout=halmak-2-2.en.ansi) | 2016 | https://github.com/MadRabbit/halmak |\n| [Hieamtsrn](https://www.keyboard-design.com/letterlayout.html?layout=hieamtsrn.en.ansi) | 2014 | https://mathematicalmulticore.wordpress.com/the-keyboard-layout-project/#comment-4976 |\n| [Colemak Mod-DH](https://keyboard-design.com/letterlayout.html?layout=colemak-mod-DH-full.en.ansi) | 2014 | https://colemakmods.github.io/mod-dh/ | \n| [Norman](https://keyboard-design.com/letterlayout.html?layout=norman.en.ansi) | 2013 | https://normanlayout.info/ |\n| [Workman](https://keyboard-design.com/letterlayout.html?layout=workman.en.ansi) | 2010 | https://workmanlayout.org/ | \n| [MTGAP 2.0](https://www.keyboard-design.com/letterlayout.html?layout=mtgap-2-0.en.ansi) | 2010 | https://mathematicalmulticore.wordpress.com/2010/06/21/mtgaps-keyboard-layout-2-0/ |\n| [QGMLWB](https://keyboard-design.com/letterlayout.html?layout=qgmlwb.en.ansi) | 2009 | http://mkweb.bcgsc.ca/carpalx/?full_optimization | \n| [Colemak](https://keyboard-design.com/letterlayout.html?layout=colemak.en.ansi) | 2006 | https://colemak.com/ | \n| [Asset](https://keyboard-design.com/letterlayout.html?layout=asset.en.ansi) | 2006 | http://millikeys.sourceforge.net/asset/ | \n| Capewell-Dvorak | 2004 | http://michaelcapewell.com/projects/keyboard/layout_capewell-dvorak.htm |\n| [Klausler](https://www.keyboard-design.com/letterlayout.html?layout=klausler.en.ansi) | 2002 | https://web.archive.org/web/20031001163722/http://klausler.com/evolved.html |\n| [Dvorak](https://keyboard-design.com/letterlayout.html?layout=dvorak.en.ansi) | 1936 | https://en.wikipedia.org/wiki/Dvorak_keyboard_layout | \n| [QWERTY](https://keyboard-design.com/letterlayout.html?layout=qwerty.en.ansi) | 1873 | https://en.wikipedia.org/wiki/QWERTY |\n\n---\n\n| Text source | Information |\n| --- | --- |\n| \"Alice in Wonderland\" | Alice in Wonderland (Ch.1) |\n| \"Romeo and Juliet\" | [Romeo and Juliet](https://www.fulltextarchive.com/page/Romeo-and-Juliet1/) |\n| \"Bhagavad Gita\" | [Bhagavad Gita](https://www.gutenberg.org/files/2388/2388-h/2388-h.htm) |\n| \"Memento screenplay\" | [Memento screenplay](https://www.dailyscript.com/scripts/memento.html) |\n| \"100K tweets\" | 100,000 tweets from: [Sentiment140 dataset](https://data.world/data-society/twitter-user-data) training data |\n| \"20K tweets\" | 20,000 tweets from [Gender Classifier Data](https://www.kaggle.com/crowdflower/twitter-user-gender-classification) |\n| \"MASC tweets\" | [MASC](http://www.anc.org/data/masc/corpus/) tweets (cleaned of html markup) |\n| \"MASC spoken\" | [MASC](http://www.anc.org/data/masc/corpus/) spoken transcripts (phone and face-to-face: 25,783 words) |\n| \"COCA blogs\" | [Corpus of Contemporary American English](https://www.english-corpora.org/coca/) [blog samples](https://www.corpusdata.org/) |\n| \"Google website\" | [Google homepage](https://google.com) (accessed 10/20/2020) |\n| \"Software languages\" | \"Tower of Hanoi\" (programming languages A-Z from [Rosetta Code](https://rosettacode.org/wiki/Towers_of_Hanoi)) |\n| \"Monkey text\" | Ian Douglas's English-generated [monkey0-7.txt corpus](https://zenodo.org/record/4642460) |\n| \"Coder text\" | Ian Douglas's software-generated [coder0-7.txt corpus](https://zenodo.org/record/4642460) |\n| \"iweb cleaned corpus\" | First 150,000 lines of Shai Coleman's [iweb-corpus-samples-cleaned.txt](https://colemak.com/pub/corpus/iweb-corpus-samples-cleaned.txt.xz) |\n\nReference for Monkey and Coder texts:\nDouglas, Ian. (2021, March 28). Keyboard Layout Analysis: Creating the Corpus, Bigram Chains, and Shakespeare's Monkeys (Version 1.0.0). Zenodo. http://doi.org/10.5281/zenodo.4642460\n\n## Guiding criteria   <a name=\"criteria\">\n\n    1.  Assign letters to keys that don't require lateral finger movements.\n    2.  Promote alternating between hands over uncomfortable same-hand transitions.\n    3.  Assign the most common letters to the most comfortable keys.\n    4.  Arrange letters so that more frequent bigrams are easier to type.\n    5.  Promote little-to-index-finger roll-ins over index-to-little-finger roll-outs.\n    6.  Balance finger loads according to their relative strength.\n    7.  Avoid stretching shorter fingers up and longer fingers down.\n    8.  Avoid using the same finger.\n    9.  Avoid skipping over the home row.\n    10. Assign the most common punctuation to keys in the middle of the keyboard.\n    11. Assign easy-to-remember symbols to the Shift-number keys.\n    \n### Factors used to compute the Exgram layout <a name=\"factors\">\n  - **N-gram letter frequencies** <br>\n    \n    [Peter Norvig's analysis](http://www.norvig.com/mayzner.html) of data from Google's book scanning project\n  - **Flow factors** (transitions between ordered key pairs) <br>\n    These factors are influenced by Dvorak's 11 criteria (1936).\n\n### Import dependencies and functions  <a name=\"import\">\n\n\n```python\n# Import dependencies\nimport xlrd\nimport numpy as np\nfrom sympy.utilities.iterables import multiset_permutations\nimport matplotlib\nimport matplotlib.pyplot as plt    \nimport seaborn as sns\n\n# Print .png figures and .txt text files\nprint_output = False # True\n\n# Apply strength data\napply_strength = True\nmin_strength_factor = 0.9\n\nletters24 = ['E','T','A','O','I','N','S','R','H','L','D','C','U','M','F','P','G','W','Y','B','V','K','X','J']\nkeys24 = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24]\ninstances24 = [4.45155E+11,3.30535E+11,2.86527E+11,2.72277E+11,2.69732E+11,2.57771E+11,\n               2.32083E+11,2.23768E+11,1.80075E+11,1.44999E+11,1.36018E+11,1.19156E+11,\n               97273082907,89506734085,85635440629,76112599849,66615316232,59712390260,\n               59331661972,52905544693,37532682260,19261229433,8369138754,5657910830]                        \n\n\ndef permute_optimize_keys(fixed_letters, fixed_letter_indices, open_letter_indices, \n                          all_letters, keys, data_matrix, bigrams, bigram_frequencies, \n                          verbose=False, ntop=0):\n    \"\"\"\n    Find all permutations of letters, optimize layout, and generate output.\n    \"\"\"\n    matrix_selected = select_keys(data_matrix, keys, verbose=False) \n    \n    unassigned_letters = []\n    for all_letter in all_letters:\n        if all_letter not in fixed_letters:\n            unassigned_letters.append(all_letter)\n            if len(unassigned_letters) == len(open_letter_indices):\n                break\n\n    letter_permutations = permute_letters(unassigned_letters, verbose)\n    top_permutation, scores = optimize_layout(matrix_selected, bigrams, bigram_frequencies, letter_permutations, open_letter_indices, fixed_letters, fixed_letter_indices, verbose)\n\n    if ntop > 0:\n        print_top_scores(letter_permutations, scores, ntop)\n    \n    return top_permutation, letter_permutations, scores\n\n\ndef permute_optimize(letters, all_letters, all_keys, data_matrix, bigrams, bigram_frequencies, verbose=False, ntop=0):\n    \"\"\"\n    Find all permutations of letters, optimize layout, and generate output.\n    \"\"\"\n    matrix_selected = select_keys(data_matrix, all_keys, verbose=False)\n    open_positions = []\n    fixed_positions = [] \n    open_letters = []\n    fixed_letters = []\n    assigned_letters = []\n    for iletter, letter in enumerate(letters):\n        if letter.strip() == \"\":\n            open_positions.append(iletter)\n            for all_letter in all_letters:\n                if all_letter not in letters and all_letter not in assigned_letters:\n                    open_letters.append(all_letter)\n                    assigned_letters.append(all_letter)\n                    break\n        else:\n            fixed_positions.append(iletter)\n            fixed_letters.append(letter)\n    #print(open_positions, fixed_positions, open_letters, fixed_letters)\n    letter_permutations = permute_letters(open_letters, verbose)\n    top_permutation, scores = optimize_layout(matrix_selected, bigrams, bigram_frequencies, letter_permutations, open_positions, fixed_letters, fixed_positions, verbose)\n    if ntop > 0:\n        print_top_scores(letter_permutations, scores, ntop)\n    \n    return top_permutation, letter_permutations, scores\n\n\ndef select_keys(data_matrix, keys, verbose=False):\n    \"\"\"\n    Select keys to quantify pairwise relationships.\n    \"\"\"\n    # Extract pairwise entries for the keys:\n    nkeys = len(keys)\n    Select = np.zeros((nkeys, nkeys))\n    u = 0\n    for i in keys:\n        u += 1\n        v = 0\n        for j in keys:\n            v += 1\n            Select[u-1,v-1] = data_matrix[i-1,j-1]\n\n    # Normalize matrix with min-max scaling to a range with max 1:\n    newMin = np.min(Select) / np.max(Select)\n    newMax = 1.0\n    Select = newMin + (Select - np.min(Select)) * (newMax - newMin) / (np.max(Select) - np.min(Select))\n    \n    if verbose:\n        #print(\"Matrix:\")\n        #np.set_printoptions(precision=2); print(Select)\n\n        # Heatmap of array\n        heatmap(data=Select, title=\"Matrix heatmap\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=False); plt.show()\n    \n    return Select\n\n\ndef permute_letters(letters, verbose=False):\n    \"\"\"\n    Find all permutations of a given set of letters (max: 8-10 letters).\n    \"\"\"\n    letter_permutations = []\n    for p in multiset_permutations(letters):\n        letter_permutations.append(p)\n    letter_permutations = np.array(letter_permutations)\n    #if verbose:\n    #    print(\"First permutation: {0}\".format(letter_permutations[0])) \n    \n    return letter_permutations\n\n\ndef score_layout(data_matrix, letters, bigrams, bigram_frequencies, verbose=False):\n    \"\"\"\n    Compute the score for a given letter-key layout (NOTE normalization step).\n    \"\"\"\n    # Create a matrix of bigram frequencies:\n    nletters = len(letters)\n    F2 = np.zeros((nletters, nletters))\n\n    # Find the bigram frequency for each ordered pair of letters in the permutation:\n    for i1 in range(nletters):\n        for i2 in range(nletters):\n            bigram = letters[i1] + letters[i2]\n            i2gram = np.where(bigrams == bigram)\n            if np.size(i2gram) > 0:\n                F2[i1, i2] = bigram_frequencies[i2gram][0]\n\n    # Normalize matrices with min-max scaling to a range with max 1:\n    newMax = 1\n    minF2 = np.min(F2)\n    maxF2 = np.max(F2)\n    newMin2 = minF2 / maxF2\n    F2 = newMin + (F2 - minF2) * (newMax - newMin2) / (maxF2 - minF2)\n\n    # Compute the score for this permutation:\n    score  = np.average(data_matrix * F2) \n    if verbose:\n        print(\"Score for letter permutation {0}: {1}\".format(letters, score))\n\n    return score\n\n\ndef tally_bigrams(input_text, bigrams, normalize=True, verbose=False):\n    \"\"\"\n    Compute the score for a given letter-key layout (NOTE normalization step).\n    \"\"\"   \n    # Find the bigram frequency for each ordered pair of letters in the input text\n    #input_text = [str.upper(str(x)) for x in input_text]\n    input_text = [str.upper(x) for x in input_text]\n    nchars = len(input_text)\n    F = np.zeros(len(bigrams))\n\n    for ichar in range(0, nchars-1):\n        bigram = input_text[ichar] + input_text[ichar + 1]\n        i2gram = np.where(bigrams == bigram)\n        if np.size(i2gram) > 0:\n            F[i2gram] += 1\n\n    # Normalize matrix with min-max scaling to a range with max 1:\n    if normalize:\n        newMax = 1\n        newMin = np.min(F) / np.max(F)\n        F = newMin + (F - np.min(F)) * (newMax - newMin) / (np.max(F) - np.min(F))\n\n    bigram_frequencies_for_input = F\n\n    if verbose:\n        print(\"Bigram frequencies for input: {0}\".format(bigram_frequencies_for_input))\n\n    return bigram_frequencies_for_input\n\n\ndef tally_layout_samefinger_bigrams(layout, bigrams, bigram_frequencies, verbose=False):\n    \"\"\"\n    Tally the number of same-finger bigrams within (a list of 24 letters representing) a layout:\n    ['P','Y','O','U','C','I','E','A','G','K','J','X','M','D','L','B','R','T','N','S','H','V','W','F']\n    \"\"\"   \n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    same_finger_keys = [[1,5],[5,9],[1,9], [2,6],[6,10],[2,10], \n                        [3,7],[7,11],[3,11], [4,8],[8,12],[4,12],\n                        [13,17],[17,21],[13,21], [14,18],[18,22],[14,22], \n                        [15,19],[19,23],[15,23], [16,20],[20,24],[16,24]] \n\n    layout = [str.upper(x) for x in layout]\n    max_frequency = 1.00273E+11\n\n    samefinger_bigrams = []\n    samefinger_bigram_counts = []\n    for bigram_keys in same_finger_keys:\n        bigram1 = layout[bigram_keys[0]-1] + layout[bigram_keys[1]-1]\n        bigram2 = layout[bigram_keys[1]-1] + layout[bigram_keys[0]-1]\n        i2gram1 = np.where(bigrams == bigram1)\n        i2gram2 = np.where(bigrams == bigram2)\n        if np.size(i2gram1) > 0:\n            samefinger_bigrams.append(bigram1)\n            samefinger_bigram_counts.append(max_frequency * bigram_frequencies[i2gram1] / np.max(bigram_frequencies))\n        if np.size(i2gram2) > 0:\n            samefinger_bigrams.append(bigram2)\n            samefinger_bigram_counts.append(max_frequency * bigram_frequencies[i2gram2] / np.max(bigram_frequencies))\n\n    samefinger_bigrams_total = np.sum(samefinger_bigram_counts)\n\n    if verbose:\n        print(\"    Total same-finger bigram frequencies: {0:15.0f}\".format(samefinger_bigrams_total))\n\n    return samefinger_bigrams, samefinger_bigram_counts, samefinger_bigrams_total \n\n\ndef optimize_layout(data_matrix, bigrams, bigram_frequencies, letter_permutations, open_positions, fixed_letters, fixed_positions=[], verbose=False):\n    \"\"\"\n    Compute scores for all letter-key layouts.\n    \"\"\"\n    iter = 0\n    top_score = 0\n    scores = []\n    use_score_function = False\n\n    nletters = len(open_positions) + len(fixed_positions)\n    top_permutation = np.array(['E' for x in range(nletters)])\n    F2 = np.zeros((nletters, nletters))\n\n    # Loop through the permutations of the selected letters:\n    for p in letter_permutations:\n        letters = np.array(['E' for x in range(nletters)])  # KEEP to initialize!\n        for imove, open_position in enumerate(open_positions):\n            letters[open_position] = p[imove]\n        for ifixed, fixed_position in enumerate(fixed_positions):\n            letters[fixed_position] = fixed_letters[ifixed]\n\n        # Compute the score for this permutation:\n        if use_score_function:\n            score = score_layout(data_matrix, letters, bigrams, bigram_frequencies, verbose=False)\n        else:\n            # Find the bigram frequency for each ordered pair of letters in the permutation:\n            for i1 in range(nletters):\n                for i2 in range(nletters):\n                    bigram = letters[i1] + letters[i2]\n                    i2gram = np.where(bigrams == bigram)\n                    if np.size(i2gram) > 0:\n                        F2[i1, i2] = bigram_frequencies[i2gram][0]\n\n            # Normalize matrices with min-max scaling to a range with max 1:\n            newMax = 1\n            minF2 = np.min(F2)\n            maxF2 = np.max(F2)\n            newMin2 = minF2 / maxF2\n            F = newMin + (F2 - minF2) * (newMax - newMin2) / (maxF2 - minF2)\n\n            # Compute the score for this permutation:\n            score  = np.average(data_matrix * F) \n\n        # Store all scores and the top score and permutation:\n        scores.append(score)\n        if score > top_score:\n            top_score = score\n            top_permutation = letters\n            \n    #print(\"Topmost of {0} permutations: {1}\".format(len(letter_permutations), top_score))\n    if verbose:\n        print(\"{0:0.8f}\".format(top_score))\n        print(*top_permutation)\n        \n    return top_permutation, scores\n\n\ndef exchange_letters(letters, fixed_letter_indices, all_letters, all_keys, data_matrix, \n                     bigrams, bigram_frequencies, verbose=True, ntop=0):\n    \"\"\"\n    Exchange letters, 8 keys at a time (8! = 40,320) selected twice in 32 different ways:\n\n    Indices:\n         0  1  2  3     12 13 14 15\n         4  5  6  7     16 17 18 19\n         8  9 10 11     20 21 22 23 \n\n    1. Top rows\n         0  1  2  3     12 13 14 15\n    2. Bottom rows\n         8  9 10 11     20 21 22 23 \n    3. Top and bottom rows on the right side\n                        12 13 14 15\n                        20 21 22 23 \n    4. Top and bottom rows on the left side \n         0  1  2  3\n         8  9 10 11 \n    5. Top right and bottom left rows\n                        12 13 14 15\n         8  9 10 11 \n    6. Top left and bottom right rows \n         0  1  2  3\n                        20 21 22 23 \n    7. Center of the top and bottom rows on both sides\n            1  2          13 14\n            9 10          21 22\n    8. The eight corners\n         0        3    12       15\n         8       11    20       23 \n    9. Left half of the top and bottom rows on both sides \n         0  1          12 13\n         8  9          20 21\n    10. Right half of the top and bottom rows on both sides\n               2  3          14 15\n              10 11          22 23 \n    11. Left half of non-home rows on the left and right half of the same rows on the right \n         0  1                14 15\n         8  9                22 23 \n    12. Right half of non-home rows on the left and left half of the same rows on the right\n               2  3    12 13\n              10 11    20 21 \n    13. Top center and lower sides\n            1  2           13 14\n         8       11     20       23 \n    14. Top sides and lower center\n         0        3     12       15\n            9 10           21 22   \n    15. Repeat 1-14\n         \n    \"\"\"\n    score = score_layout(data_matrix, letters, bigrams, bigram_frequencies, verbose=False)\n    print('Initial score: {0}'.format(score)) \n    print(*letters) \n    top_permutation = letters\n\n    lists_of_open_indices = [\n        [0,1,2,3,12,13,14,15],\n        [8,9,10,11,20,21,22,23],\n        [12,13,14,15,20,21,22,23],\n        [0,1,2,3,8,9,10,11],\n        [12,13,14,15,8,9,10,11],\n        [0,1,2,3,20,21,22,23],\n        [1,2,13,14,9,10,21,22],\n        [0,3,12,15,8,11,20,23],\n        [0,1,12,13,8,9,20,21],\n        [2,3,14,15,10,11,22,23],\n        [0,1,14,15,8,9,22,23],\n        [2,3,12,13,10,11,20,21],\n        [1,2,8,11,13,14,20,23],\n        [0,3,9,10,12,15,21,22]  \n    ]\n    lists_of_print_statements = [\n        '1. Top rows',\n        '2. Bottom rows',\n        '3. Top and bottom rows on the right side',\n        '4. Top and bottom rows on the left side',\n        '5. Top right and bottom left rows',\n        '6. Top left and bottom right rows',\n        '7. Center of the top and bottom rows on both sides',\n        '8. The eight corners',\n        '9. Left half of the top and bottom rows on both sides',\n        '10. Right half of the top and bottom rows on both sides',\n        '11. Left half of non-home rows on the left and right half of the same rows on the right',\n        '12. Right half of non-home rows on the left and left half of the same rows on the right',\n        '13. Top center and lower sides',\n        '14. Top sides and lower center'\n    ]\n                         \n    for istep in [1,2]:\n        if istep == 1:\n            s = \"First set of 14 letter exchanges: \"\n        elif istep == 2:\n            s = \"Second set of 14 letter exchanges: \"\n\n        for ilist, open_indices in enumerate(lists_of_open_indices):\n            print_statement = lists_of_print_statements[ilist]     \n\n            if verbose:\n                print('{0} {1}'.format(s, print_statement))\n                             \n            for open_index in open_indices:\n                if open_index not in fixed_letter_indices:\n                    top_permutation[open_index] = ''\n                    \n            top_permutation, letter_permutations, scores = permute_optimize(top_permutation, letters24, keys24, data_matrix, bigrams, bigram_frequencies, verbose=True, ntop=0)            \n            top_permutation = top_permutation.tolist()\n        \n    if verbose:\n        print('')\n        print('    -------- DONE --------') \n        print('')\n\n    return top_permutation\n                             \n\ndef rank_within_epsilon(numbers, epsilon, factor=False, verbose=True):\n    \"\"\"\n    numbers = np.array([10,9,8,7,6])\n    epsilon = 1\n    rank_within_epsilon(numbers, epsilon, factor=False, verbose=True) \n    >>> array([1., 1., 2., 2., 3.])\n    numbers = np.array([0.798900824, 0.79899900824, 0.79900824])\n    epsilon = 0.9**8 - 0.9**9\n    factor = ((24**2 - 1) + (1-epsilon)) / (24**2) # 0.999925266109375\n    rank_within_epsilon(numbers, factor, factor=True, verbose=True) \n    >>> array([2., 1., 1.])\n    \"\"\"\n    numbers = np.array(numbers)\n    Isort = np.argsort(-numbers)\n    numbers_sorted = numbers[Isort]\n    count = 1\n    ranks = np.zeros(np.size(numbers))\n    for i, num in enumerate(numbers_sorted):\n        if ranks[i] == 0:\n            if factor:\n                lower_bound = num * epsilon\n            else:\n                lower_bound = num - epsilon\n            bounded_nums1 = num >= numbers_sorted\n            bounded_nums2 = numbers_sorted >= lower_bound\n            bounded_nums = bounded_nums1 * bounded_nums2\n            count += 1\n            for ibounded, bounded_num in enumerate(bounded_nums):\n                if bounded_num == True:\n                    ranks[ibounded] = count\n\n    uranks = np.unique(ranks)\n    nranks = np.size(uranks)\n    new_ranks = ranks.copy()\n    new_count = 0\n    for rank in uranks:\n        new_count += 1\n        same_ranks = ranks == rank\n        for isame, same_rank in enumerate(same_ranks):\n            if same_rank == True:\n                new_ranks[isame] = new_count\n\n    #ranks_sorted = new_ranks[Isort]\n    ranks_sorted = [np.int(x) for x in new_ranks]\n    \n    if verbose:\n        for i, num in enumerate(numbers_sorted):\n            print(\"    ({0})    {1}\".format(np.int(ranks_sorted[i]), num))\n        \n    return numbers_sorted, ranks_sorted, Isort\n```\n\n\n```python\ndef print_top_scores(letter_permutations, scores, ntop):\n    \"\"\"\n    Print top-scored letter permutations.\n    \"\"\"\n    scores_negative = -np.array(scores)\n    isort = np.argsort(scores_negative)[:ntop]\n    sorted_scores = [scores[isort[x]] for x in range(len(isort))]\n    sorted_letter_permutations = [letter_permutations[isort[x]].tolist() for x in range(len(isort))]\n    for ix, x in enumerate(sorted_letter_permutations):\n        print(\"{0:0.8f}\".format(sorted_scores[ix]))\n        print(*x)\n    \ndef print_matrix_info(matrix_data, matrix_label, nkeys, nlines=10):\n    \"\"\"\n    Print matrix output.\n    \"\"\"\n    print(\"{0} min = {1}, max = {2}\".format(matrix_label, np.min(matrix_data), np.max(matrix_data)))\n    matrix_flat = matrix_data.flatten()\n    argsort = np.argsort(matrix_flat)\n    print(\"{0} key number pairs with minimum values:\".format(matrix_label))\n    for x in argsort[0:nlines]:\n        if x % nkeys == 0:\n            min_row = np.int(np.ceil(x / nkeys)) + 1\n            min_col = 1\n        else:\n            min_row = np.int(np.ceil(x / nkeys))\n            min_col = x - nkeys * (min_row-1) + 1                \n        print(\"        {0} -> {1}        ({2})\".format(min_row, min_col, matrix_flat[x]))\n    print(\"{0} key number pairs with maximum values:\".format(matrix_label))\n    max_sort = argsort[-nlines::]\n    for x in max_sort[::-1]:\n        if x % nkeys == 0:\n            max_row = np.int(np.ceil(x / nkeys)) + 1\n            max_col = 1\n        else:\n            max_row = np.int(np.ceil(x / nkeys))\n            max_col = x - nkeys * (max_row-1) + 1                \n        print(\"        {0} -> {1}        ({2})\".format(max_row, max_col, matrix_flat[x]))\n\n\ndef heatmap(data, title=\"\", xlabel=\"\", ylabel=\"\", x_axis_labels=[], y_axis_labels=[], print_output=True):\n    \"\"\"\n    Plot heatmap of matrix.\n    \"\"\"\n    # use heatmap function, set the color as viridis and\n    # make each cell seperate using linewidth parameter\n    plt.figure()\n    sns_plot = sns.heatmap(data, xticklabels=x_axis_labels, yticklabels=y_axis_labels, linewidths=1, \n                           cmap=\"viridis\", square=True, vmin=np.min(data), vmax=np.max(data))\n    plt.title(title)\n    plt.xlabel(xlabel)\n    plt.ylabel(ylabel)\n    sns_plot.set_xticklabels(x_axis_labels)  #, rotation=75) \n    sns_plot.set_yticklabels(y_axis_labels) \n    if print_output:\n        sns_plot.figure.savefig(\"{0}_heatmap.png\".format(title))\n        \n    \ndef histmap(data, title=\"\", print_output=True):\n    \"\"\"\n    Plot histogram.\n    \"\"\"\n    sns.distplot(data)\n    plt.title(title)\n    if print_output:\n        sns_plot.figure.savefig(\"{0}_histogram.png\".format(title))\n        \n        \ndef print_layout24(layout):\n    \"\"\"\n    Print layout.\n    \"\"\"   \n    print('    {0}  {1}'.format(' '.join(layout[0:4]),\n                                ' '.join(layout[12:16])))\n    print('    {0}  {1}'.format(' '.join(layout[4:8]),\n                                ' '.join(layout[16:20])))\n    print('    {0}  {1}'.format(' '.join(layout[8:12]),\n                                ' '.join(layout[20:24])))\n\n\ndef print_layout24_instances(layout, letters24, instances24, bigrams, bigram_frequencies):\n    \"\"\"\n    Print billions of instances per letter (not Z or Q) in layout form.\n    layout = ['P','Y','O','U','C','I','E','A','G','K','J','X','M','D','L','B','R','T','N','S','H','V','W','F']\n    print_layout24_instances(layout, letters24, instances24, bigrams, bigram_frequencies)\n    \"\"\"\n    layout_instances = []\n    layout_instances_strings = []\n    for letter in layout:\n        index = letters24.index(letter)\n        layout_instances.append(instances24[index])\n        layout_instances_strings.append('{0:3.0f}'.format(instances24[index]/1000000000))\n \n    print('    {0}  {1}'.format(' '.join(layout_instances_strings[0:4]),\n                                ' '.join(layout_instances_strings[12:16])))\n    print('    {0}  {1}'.format(' '.join(layout_instances_strings[4:8]),\n                                ' '.join(layout_instances_strings[16:20])))\n    print('    {0}  {1}'.format(' '.join(layout_instances_strings[8:12]),\n                                ' '.join(layout_instances_strings[20:24])))\n    left_sum = np.sum(layout_instances[0:12])/1000000000000\n    right_sum = np.sum(layout_instances[12:24])/1000000000000\n    pL = ''\n    pR = ''\n    if left_sum > right_sum:\n        pL = ' ({0:3.2f}%)'.format(100 * (left_sum - right_sum) / right_sum)\n    elif right_sum > left_sum:\n        pR = ' ({0:3.2f}%)'.format(100 * (right_sum - left_sum) / left_sum)\n    \n    print('\\n    left: {0:3.3f}T{1}  right: {2:3.3f}T{3}'.format(left_sum, pL, \n                                                                 right_sum, pR))\n    \n    tally_layout_samefinger_bigrams(layout, bigrams, bigram_frequencies, verbose=True)\n```\n\n### Bigram frequencies <a name=\"ngrams\">\n\n[Peter Norvig's ngrams table](http://www.norvig.com/mayzner.html](http://www.norvig.com/mayzner.html)\n    \n[NOTE: If you want to compute an optimized layout for another language, or based on another corpus, you can run the tally_bigrams() function above and replace bigram_frequencies below before running the rest of the code.]\n\n\n```python\nload_original_ngram_files = True\nif load_original_ngram_files:\n    ngrams_table = \"data/bigrams-trigrams-frequencies.xlsx\"\n    wb = xlrd.open_workbook(ngrams_table) \n    ngrams_sheet = wb.sheet_by_index(0)\n    # 1-grams and frequencies\n    onegrams = np.array(())\n    onegram_frequencies = np.array(())\n    i = 0\n    start1 = 0\n    stop1 = 0\n    while stop1 == 0:\n        if ngrams_sheet.cell_value(i, 0) == \"2-gram\":\n            stop1 = 1\n        elif ngrams_sheet.cell_value(i, 0) == \"1-gram\":\n            start1 = 1\n        elif start1 == 1:\n            onegrams = np.append(onegrams, ngrams_sheet.cell_value(i, 0))\n            onegram_frequencies = np.append(onegram_frequencies, ngrams_sheet.cell_value(i, 1))\n        i += 1\n    onegram_frequencies = onegram_frequencies / np.sum(onegram_frequencies)\n\n    # 2-grams and frequencies\n    bigrams = np.array(())\n    bigram_frequencies = np.array(())\n    i = 0\n    start1 = 0\n    stop1 = 0\n    while stop1 == 0:\n        if ngrams_sheet.cell_value(i, 0) == \"3-gram\":\n            stop1 = 1\n        elif ngrams_sheet.cell_value(i, 0) == \"2-gram\":\n            start1 = 1\n        elif start1 == 1:\n            bigrams = np.append(bigrams, ngrams_sheet.cell_value(i, 0))\n            bigram_frequencies = np.append(bigram_frequencies, ngrams_sheet.cell_value(i, 1))\n        i += 1\n    bigram_frequencies = bigram_frequencies / np.sum(bigram_frequencies)\n\n    # Save:\n    if print_output:\n        file = open(\"onegrams.txt\", \"w+\")\n        file.write(str(onegrams))\n        file.close()\n        file = open(\"onegram_frequencies.txt\", \"w+\")\n        file.write(str(onegram_frequencies))\n        file.close()\n        file = open(\"bigrams.txt\", \"w+\")\n        file.write(str(bigrams))\n        file.close()\n        file = open(\"bigram_frequencies.txt\", \"w+\")\n        file.write(str(bigram_frequencies))\n        file.close()\n\n    # Print:\n    print(repr(onegrams))\n    print(repr(onegram_frequencies))\n    print(repr(bigrams))\n    print(repr(bigram_frequencies))\n\nelse:\n    onegrams = np.array(['E', 'T', 'A', 'O', 'I', 'N', 'S', 'R', 'H', 'L', 'D', 'C', 'U',\n       'M', 'F', 'P', 'G', 'W', 'Y', 'B', 'V', 'K', 'X', 'J', 'Q', 'Z'],\n      dtype='<U32')\n    onegram_frequencies = np.array([0.12492063, 0.09275565, 0.08040605, 0.07640693, 0.07569278,\n       0.07233629, 0.06512767, 0.06279421, 0.05053301, 0.04068986,\n       0.03816958, 0.03343774, 0.02729702, 0.02511761, 0.02403123,\n       0.02135891, 0.01869376, 0.01675664, 0.0166498 , 0.01484649,\n       0.01053252, 0.00540513, 0.00234857, 0.00158774, 0.00120469,\n       0.00089951])\n    bigrams = np.array(['TH', 'HE', 'IN', 'ER', 'AN', 'RE', 'ON', 'AT', 'EN', 'ND', 'TI',\n       'ES', 'OR', 'TE', 'OF', 'ED', 'IS', 'IT', 'AL', 'AR', 'ST', 'TO',\n       'NT', 'NG', 'SE', 'HA', 'AS', 'OU', 'IO', 'LE', 'VE', 'CO', 'ME',\n       'DE', 'HI', 'RI', 'RO', 'IC', 'NE', 'EA', 'RA', 'CE', 'LI', 'CH',\n       'LL', 'BE', 'MA', 'SI', 'OM', 'UR', 'CA', 'EL', 'TA', 'LA', 'NS',\n       'DI', 'FO', 'HO', 'PE', 'EC', 'PR', 'NO', 'CT', 'US', 'AC', 'OT',\n       'IL', 'TR', 'LY', 'NC', 'ET', 'UT', 'SS', 'SO', 'RS', 'UN', 'LO',\n       'WA', 'GE', 'IE', 'WH', 'EE', 'WI', 'EM', 'AD', 'OL', 'RT', 'PO',\n       'WE', 'NA', 'UL', 'NI', 'TS', 'MO', 'OW', 'PA', 'IM', 'MI', 'AI',\n       'SH', 'IR', 'SU', 'ID', 'OS', 'IV', 'IA', 'AM', 'FI', 'CI', 'VI',\n       'PL', 'IG', 'TU', 'EV', 'LD', 'RY', 'MP', 'FE', 'BL', 'AB', 'GH',\n       'TY', 'OP', 'WO', 'SA', 'AY', 'EX', 'KE', 'FR', 'OO', 'AV', 'AG',\n       'IF', 'AP', 'GR', 'OD', 'BO', 'SP', 'RD', 'DO', 'UC', 'BU', 'EI',\n       'OV', 'BY', 'RM', 'EP', 'TT', 'OC', 'FA', 'EF', 'CU', 'RN', 'SC',\n       'GI', 'DA', 'YO', 'CR', 'CL', 'DU', 'GA', 'QU', 'UE', 'FF', 'BA',\n       'EY', 'LS', 'VA', 'UM', 'PP', 'UA', 'UP', 'LU', 'GO', 'HT', 'RU',\n       'UG', 'DS', 'LT', 'PI', 'RC', 'RR', 'EG', 'AU', 'CK', 'EW', 'MU',\n       'BR', 'BI', 'PT', 'AK', 'PU', 'UI', 'RG', 'IB', 'TL', 'NY', 'KI',\n       'RK', 'YS', 'OB', 'MM', 'FU', 'PH', 'OG', 'MS', 'YE', 'UD', 'MB',\n       'IP', 'UB', 'OI', 'RL', 'GU', 'DR', 'HR', 'CC', 'TW', 'FT', 'WN',\n       'NU', 'AF', 'HU', 'NN', 'EO', 'VO', 'RV', 'NF', 'XP', 'GN', 'SM',\n       'FL', 'IZ', 'OK', 'NL', 'MY', 'GL', 'AW', 'JU', 'OA', 'EQ', 'SY',\n       'SL', 'PS', 'JO', 'LF', 'NV', 'JE', 'NK', 'KN', 'GS', 'DY', 'HY',\n       'ZE', 'KS', 'XT', 'BS', 'IK', 'DD', 'CY', 'RP', 'SK', 'XI', 'OE',\n       'OY', 'WS', 'LV', 'DL', 'RF', 'EU', 'DG', 'WR', 'XA', 'YI', 'NM',\n       'EB', 'RB', 'TM', 'XC', 'EH', 'TC', 'GY', 'JA', 'HN', 'YP', 'ZA',\n       'GG', 'YM', 'SW', 'BJ', 'LM', 'CS', 'II', 'IX', 'XE', 'OH', 'LK',\n       'DV', 'LP', 'AX', 'OX', 'UF', 'DM', 'IU', 'SF', 'BT', 'KA', 'YT',\n       'EK', 'PM', 'YA', 'GT', 'WL', 'RH', 'YL', 'HS', 'AH', 'YC', 'YN',\n       'RW', 'HM', 'LW', 'HL', 'AE', 'ZI', 'AZ', 'LC', 'PY', 'AJ', 'IQ',\n       'NJ', 'BB', 'NH', 'UO', 'KL', 'LR', 'TN', 'GM', 'SN', 'NR', 'FY',\n       'MN', 'DW', 'SB', 'YR', 'DN', 'SQ', 'ZO', 'OJ', 'YD', 'LB', 'WT',\n       'LG', 'KO', 'NP', 'SR', 'NQ', 'KY', 'LN', 'NW', 'TF', 'FS', 'CQ',\n       'DH', 'SD', 'VY', 'DJ', 'HW', 'XU', 'AO', 'ML', 'UK', 'UY', 'EJ',\n       'EZ', 'HB', 'NZ', 'NB', 'MC', 'YB', 'TP', 'XH', 'UX', 'TZ', 'BV',\n       'MF', 'WD', 'OZ', 'YW', 'KH', 'GD', 'BM', 'MR', 'KU', 'UV', 'DT',\n       'HD', 'AA', 'XX', 'DF', 'DB', 'JI', 'KR', 'XO', 'CM', 'ZZ', 'NX',\n       'YG', 'XY', 'KG', 'TB', 'DC', 'BD', 'SG', 'WY', 'ZY', 'AQ', 'HF',\n       'CD', 'VU', 'KW', 'ZU', 'BN', 'IH', 'TG', 'XV', 'UZ', 'BC', 'XF',\n       'YZ', 'KM', 'DP', 'LH', 'WF', 'KF', 'PF', 'CF', 'MT', 'YU', 'CP',\n       'PB', 'TD', 'ZL', 'SV', 'HC', 'MG', 'PW', 'GF', 'PD', 'PN', 'PC',\n       'RX', 'TV', 'IJ', 'WM', 'UH', 'WK', 'WB', 'BH', 'OQ', 'KT', 'RQ',\n       'KB', 'CG', 'VR', 'CN', 'PK', 'UU', 'YF', 'WP', 'CZ', 'KP', 'DQ',\n       'WU', 'FM', 'WC', 'MD', 'KD', 'ZH', 'GW', 'RZ', 'CB', 'IW', 'XL',\n       'HP', 'MW', 'VS', 'FC', 'RJ', 'BP', 'MH', 'HH', 'YH', 'UJ', 'FG',\n       'FD', 'GB', 'PG', 'TK', 'KK', 'HQ', 'FN', 'LZ', 'VL', 'GP', 'HZ',\n       'DK', 'YK', 'QI', 'LX', 'VD', 'ZS', 'BW', 'XQ', 'MV', 'UW', 'HG',\n       'FB', 'SJ', 'WW', 'GK', 'UQ', 'BG', 'SZ', 'JR', 'QL', 'ZT', 'HK',\n       'VC', 'XM', 'GC', 'FW', 'PZ', 'KC', 'HV', 'XW', 'ZW', 'FP', 'IY',\n       'PV', 'VT', 'JP', 'CV', 'ZB', 'VP', 'ZR', 'FH', 'YV', 'ZG', 'ZM',\n       'ZV', 'QS', 'KV', 'VN', 'ZN', 'QA', 'YX', 'JN', 'BF', 'MK', 'CW',\n       'JM', 'LQ', 'JH', 'KJ', 'JC', 'GZ', 'JS', 'TX', 'FK', 'JL', 'VM',\n       'LJ', 'TJ', 'JJ', 'CJ', 'VG', 'MJ', 'JT', 'PJ', 'WG', 'VH', 'BK',\n       'VV', 'JD', 'TQ', 'VB', 'JF', 'DZ', 'XB', 'JB', 'ZC', 'FJ', 'YY',\n       'QN', 'XS', 'QR', 'JK', 'JV', 'QQ', 'XN', 'VF', 'PX', 'ZD', 'QT',\n       'ZP', 'QO', 'DX', 'HJ', 'GV', 'JW', 'QC', 'JY', 'GJ', 'QB', 'PQ',\n       'JG', 'BZ', 'MX', 'QM', 'MZ', 'QF', 'WJ', 'ZQ', 'XR', 'ZK', 'CX',\n       'FX', 'FV', 'BX', 'VW', 'VJ', 'MQ', 'QV', 'ZF', 'QE', 'YJ', 'GX',\n       'KX', 'XG', 'QD', 'XJ', 'SX', 'VZ', 'VX', 'WV', 'YQ', 'BQ', 'GQ',\n       'VK', 'ZJ', 'XK', 'QP', 'HX', 'FZ', 'QH', 'QJ', 'JZ', 'VQ', 'KQ',\n       'XD', 'QW', 'JX', 'QX', 'KZ', 'WX', 'FQ', 'XZ', 'ZX'], dtype='<U32')\n    bigram_frequencies = np.array([3.55620339e-02, 3.07474124e-02, 2.43274529e-02, 2.04826481e-02,\n       1.98515108e-02, 1.85432319e-02, 1.75804642e-02, 1.48673230e-02,\n       1.45424846e-02, 1.35228145e-02, 1.34257882e-02, 1.33939375e-02,\n       1.27653906e-02, 1.20486963e-02, 1.17497528e-02, 1.16812337e-02,\n       1.12842988e-02, 1.12327374e-02, 1.08744953e-02, 1.07489847e-02,\n       1.05347566e-02, 1.04126653e-02, 1.04125115e-02, 9.53014842e-03,\n       9.32114579e-03, 9.25763559e-03, 8.71095073e-03, 8.70002319e-03,\n       8.34931851e-03, 8.29254235e-03, 8.25280566e-03, 7.93859725e-03,\n       7.93006486e-03, 7.64818391e-03, 7.63241814e-03, 7.27618866e-03,\n       7.26724441e-03, 6.98707488e-03, 6.91722265e-03, 6.88165290e-03,\n       6.85633031e-03, 6.51417363e-03, 6.24352184e-03, 5.97765978e-03,\n       5.76571076e-03, 5.76283716e-03, 5.65269345e-03, 5.50057242e-03,\n       5.46256885e-03, 5.42747781e-03, 5.38164098e-03, 5.30301559e-03,\n       5.29886071e-03, 5.27529444e-03, 5.08937452e-03, 4.92966405e-03,\n       4.87753568e-03, 4.84902069e-03, 4.77989185e-03, 4.77282719e-03,\n       4.74470916e-03, 4.64574958e-03, 4.60971757e-03, 4.54257059e-03,\n       4.47772200e-03, 4.42103298e-03, 4.31534618e-03, 4.25820178e-03,\n       4.25013516e-03, 4.15745843e-03, 4.12608242e-03, 4.05151268e-03,\n       4.05075209e-03, 3.97732158e-03, 3.96527277e-03, 3.94413046e-03,\n       3.86884200e-03, 3.85337077e-03, 3.85189513e-03, 3.84646388e-03,\n       3.78793431e-03, 3.77605408e-03, 3.74420703e-03, 3.73663638e-03,\n       3.67956418e-03, 3.65492648e-03, 3.61676413e-03, 3.61373182e-03,\n       3.60899233e-03, 3.47234973e-03, 3.45829494e-03, 3.39212478e-03,\n       3.37488213e-03, 3.36877623e-03, 3.30478042e-03, 3.23572471e-03,\n       3.17759946e-03, 3.17691369e-03, 3.16447752e-03, 3.15240004e-03,\n       3.15172398e-03, 3.11176534e-03, 2.95503911e-03, 2.89966768e-03,\n       2.87848219e-03, 2.86282435e-03, 2.84865969e-03, 2.84585627e-03,\n       2.81484803e-03, 2.69544349e-03, 2.62987083e-03, 2.54961380e-03,\n       2.54906719e-03, 2.54783715e-03, 2.52606379e-03, 2.47740122e-03,\n       2.39175226e-03, 2.36573195e-03, 2.33400171e-03, 2.29786417e-03,\n       2.27503360e-03, 2.27277101e-03, 2.23911052e-03, 2.21754315e-03,\n       2.18017446e-03, 2.17360835e-03, 2.14044590e-03, 2.13767970e-03,\n       2.13188615e-03, 2.10259217e-03, 2.04932647e-03, 2.04724906e-03,\n       2.03256516e-03, 2.02845908e-03, 1.96777866e-03, 1.95449429e-03,\n       1.95410531e-03, 1.91254221e-03, 1.89316385e-03, 1.88234971e-03,\n       1.87652262e-03, 1.84944194e-03, 1.83351654e-03, 1.78086545e-03,\n       1.76468430e-03, 1.75132925e-03, 1.71573739e-03, 1.70683303e-03,\n       1.66405086e-03, 1.63999785e-03, 1.62732115e-03, 1.62613977e-03,\n       1.60361051e-03, 1.54749379e-03, 1.51636562e-03, 1.51067364e-03,\n       1.49901610e-03, 1.49455831e-03, 1.49011351e-03, 1.48460771e-03,\n       1.48077067e-03, 1.47541326e-03, 1.47480347e-03, 1.46316579e-03,\n       1.46204465e-03, 1.43745726e-03, 1.41513491e-03, 1.39980075e-03,\n       1.38382616e-03, 1.36545598e-03, 1.36333253e-03, 1.36012483e-03,\n       1.35189358e-03, 1.32127808e-03, 1.30185876e-03, 1.28328757e-03,\n       1.27907576e-03, 1.26260675e-03, 1.23637099e-03, 1.23094105e-03,\n       1.21386641e-03, 1.20743055e-03, 1.19536134e-03, 1.19032774e-03,\n       1.17626124e-03, 1.16805780e-03, 1.14618533e-03, 1.11559852e-03,\n       1.06597119e-03, 1.05782134e-03, 1.04699320e-03, 1.04540205e-03,\n       1.01153313e-03, 9.97734501e-04, 9.86028683e-04, 9.84491816e-04,\n       9.79174450e-04, 9.78784303e-04, 9.70343472e-04, 9.68322624e-04,\n       9.66708177e-04, 9.60690121e-04, 9.59749105e-04, 9.43900197e-04,\n       9.40242103e-04, 9.28331656e-04, 9.26685761e-04, 9.14014864e-04,\n       9.02555222e-04, 8.92112065e-04, 8.85803335e-04, 8.77507468e-04,\n       8.62646840e-04, 8.57695087e-04, 8.54499050e-04, 8.43925356e-04,\n       8.31382851e-04, 8.23722323e-04, 8.16643644e-04, 7.89875969e-04,\n       7.86444549e-04, 7.42072946e-04, 7.36927617e-04, 7.27646949e-04,\n       7.25004577e-04, 7.11071849e-04, 6.92833068e-04, 6.71807283e-04,\n       6.68638321e-04, 6.56391013e-04, 6.51990243e-04, 6.49048818e-04,\n       6.43397537e-04, 6.43118050e-04, 6.37839069e-04, 6.21864133e-04,\n       6.06367626e-04, 5.99162639e-04, 5.87024289e-04, 5.74860663e-04,\n       5.72519573e-04, 5.68447140e-04, 5.58806800e-04, 5.45711864e-04,\n       5.37896691e-04, 5.34768852e-04, 5.20071483e-04, 5.18874875e-04,\n       5.16054649e-04, 5.14388309e-04, 5.11931727e-04, 5.04227393e-04,\n       5.00890900e-04, 4.97325634e-04, 4.75088970e-04, 4.66605249e-04,\n       4.58324041e-04, 4.29127437e-04, 4.27514542e-04, 4.17186146e-04,\n       4.16199437e-04, 3.94646924e-04, 3.94183167e-04, 3.86306652e-04,\n       3.61812839e-04, 3.50841120e-04, 3.49059129e-04, 3.23402665e-04,\n       3.22604151e-04, 3.11527347e-04, 3.10032877e-04, 3.07611603e-04,\n       2.96010489e-04, 2.88197255e-04, 2.77494857e-04, 2.70735751e-04,\n       2.67122244e-04, 2.64790886e-04, 2.64597695e-04, 2.63237166e-04,\n       2.61362824e-04, 2.59399816e-04, 2.58614910e-04, 2.57579773e-04,\n       2.49143242e-04, 2.49036616e-04, 2.47547306e-04, 2.36748821e-04,\n       2.35282013e-04, 2.32245156e-04, 2.30209194e-04, 2.28229670e-04,\n       2.27822992e-04, 2.20319919e-04, 2.17945603e-04, 2.13543715e-04,\n       1.97145202e-04, 1.90526970e-04, 1.90304866e-04, 1.88393786e-04,\n       1.85754127e-04, 1.85322815e-04, 1.81767370e-04, 1.74089940e-04,\n       1.71644610e-04, 1.71039222e-04, 1.69557657e-04, 1.66839046e-04,\n       1.64718022e-04, 1.59561636e-04, 1.57658164e-04, 1.54026397e-04,\n       1.52211752e-04, 1.51115808e-04, 1.47564559e-04, 1.46841709e-04,\n       1.36432949e-04, 1.35005671e-04, 1.32141796e-04, 1.27573620e-04,\n       1.27432415e-04, 1.26388914e-04, 1.25919175e-04, 1.23965197e-04,\n       1.21174483e-04, 1.18691292e-04, 1.18219114e-04, 1.17637524e-04,\n       1.17526303e-04, 1.13037594e-04, 1.10863960e-04, 1.09331046e-04,\n       1.08837112e-04, 1.06567401e-04, 1.05698197e-04, 1.00512685e-04,\n       1.00106518e-04, 9.85814937e-05, 9.17495595e-05, 9.15174736e-05,\n       9.09807382e-05, 8.79007001e-05, 8.16240791e-05, 7.91627682e-05,\n       7.79158645e-05, 7.56940333e-05, 7.44394656e-05, 7.18101849e-05,\n       6.97589276e-05, 6.81802488e-05, 6.69029567e-05, 6.54143249e-05,\n       6.08786925e-05, 6.07607969e-05, 6.03570614e-05, 5.98994801e-05,\n       5.95001291e-05, 5.94970869e-05, 5.86983574e-05, 5.79700512e-05,\n       5.66119466e-05, 5.50952209e-05, 5.47453912e-05, 5.43839597e-05,\n       5.25861529e-05, 4.89722417e-05, 4.78187439e-05, 4.77415865e-05,\n       4.77107257e-05, 4.62616737e-05, 4.60653783e-05, 4.60409299e-05,\n       4.56730211e-05, 4.54645078e-05, 4.52324283e-05, 4.38982745e-05,\n       4.36906610e-05, 4.33593810e-05, 4.31226640e-05, 4.29912118e-05,\n       4.29446346e-05, 4.17137339e-05, 3.93478837e-05, 3.84895449e-05,\n       3.84390172e-05, 3.81834469e-05, 3.53827628e-05, 3.47222349e-05,\n       3.37168917e-05, 3.18518637e-05, 3.15951703e-05, 3.12905207e-05,\n       3.10605585e-05, 3.02567524e-05, 2.91709879e-05, 2.89567711e-05,\n       2.85652293e-05, 2.82994071e-05, 2.80417376e-05, 2.77861205e-05,\n       2.77303518e-05, 2.76273746e-05, 2.72172235e-05, 2.69880432e-05,\n       2.66503046e-05, 2.66033916e-05, 2.62086568e-05, 2.59259584e-05,\n       2.57640153e-05, 2.56299050e-05, 2.54449453e-05, 2.51909823e-05,\n       2.47409597e-05, 2.46797892e-05, 2.42472084e-05, 2.35748710e-05,\n       2.24438116e-05, 2.24317329e-05, 2.23097275e-05, 2.21249597e-05,\n       2.17815183e-05, 2.15248592e-05, 2.09465192e-05, 2.09125513e-05,\n       1.96913177e-05, 1.95330853e-05, 1.91064697e-05, 1.88952009e-05,\n       1.85746459e-05, 1.81220081e-05, 1.78919334e-05, 1.73267658e-05,\n       1.61874055e-05, 1.60765855e-05, 1.58740992e-05, 1.45486411e-05,\n       1.40812264e-05, 1.36678429e-05, 1.32768479e-05, 1.31460479e-05,\n       1.30872012e-05, 1.29588223e-05, 1.25748548e-05, 1.24146066e-05,\n       1.22821602e-05, 1.22486357e-05, 1.20714645e-05, 1.20448925e-05,\n       1.19866728e-05, 1.18936663e-05, 1.17590888e-05, 1.17001978e-05,\n       1.16346360e-05, 1.11092945e-05, 1.08992577e-05, 1.06740258e-05,\n       1.06735218e-05, 1.06144296e-05, 1.05679067e-05, 1.03656570e-05,\n       1.03317955e-05, 9.98437559e-06, 9.01036943e-06, 8.85768061e-06,\n       8.76035160e-06, 8.60019167e-06, 8.19227801e-06, 7.80479658e-06,\n       7.53516931e-06, 7.44150882e-06, 7.30644125e-06, 7.26777599e-06,\n       7.06747616e-06, 6.95177332e-06, 6.85925126e-06, 6.74132156e-06,\n       6.71322068e-06, 6.70106994e-06, 6.66133186e-06, 6.47626505e-06,\n       6.38130476e-06, 6.29576510e-06, 6.24612583e-06, 5.93271496e-06,\n       5.92132104e-06, 5.83947722e-06, 5.76779879e-06, 5.76465728e-06,\n       5.53187023e-06, 5.47131015e-06, 5.33180695e-06, 5.22417954e-06,\n       5.20732008e-06, 5.15949060e-06, 5.11569104e-06, 4.95336950e-06,\n       4.94557425e-06, 4.73636484e-06, 4.63955858e-06, 4.53340156e-06,\n       4.22935422e-06, 4.19307790e-06, 4.17347414e-06, 4.12142146e-06,\n       4.11855764e-06, 3.80541311e-06, 3.36707879e-06, 3.29563656e-06,\n       3.17577578e-06, 3.05442971e-06, 2.98983688e-06, 2.97762691e-06,\n       2.95066092e-06, 2.91720550e-06, 2.89840858e-06, 2.77497857e-06,\n       2.76265227e-06, 2.74176112e-06, 2.70310579e-06, 2.61648976e-06,\n       2.60275585e-06, 2.56616744e-06, 2.55465117e-06, 2.49712549e-06,\n       2.42815484e-06, 2.37933375e-06, 2.35040476e-06, 2.33914845e-06,\n       2.33036549e-06, 2.32978989e-06, 2.28930419e-06, 2.28804340e-06,\n       2.26346210e-06, 2.24353844e-06, 2.23182640e-06, 2.23165865e-06,\n       2.22696341e-06, 2.22115030e-06, 2.21572164e-06, 2.20668084e-06,\n       2.19243658e-06, 2.17382266e-06, 2.08159887e-06, 2.07762818e-06,\n       1.95415065e-06, 1.88693410e-06, 1.83219245e-06, 1.81431726e-06,\n       1.67631850e-06, 1.67169206e-06, 1.63803449e-06, 1.57770706e-06,\n       1.56577585e-06, 1.53130790e-06, 1.52519015e-06, 1.52439998e-06,\n       1.49350905e-06, 1.47212210e-06, 1.45715861e-06, 1.40331777e-06,\n       1.38641504e-06, 1.29786439e-06, 1.27069447e-06, 1.25613209e-06,\n       1.23105569e-06, 1.22268909e-06, 1.21688094e-06, 1.18065108e-06,\n       1.18060143e-06, 1.16794389e-06, 1.13216621e-06, 1.12716419e-06,\n       1.12418866e-06, 1.12412659e-06, 1.05684621e-06, 1.05049722e-06,\n       1.04986594e-06, 1.03676402e-06, 1.03482230e-06, 9.96847192e-07,\n       9.75926251e-07, 9.54397081e-07, 9.36101632e-07, 9.30100914e-07,\n       9.27467975e-07, 8.92801774e-07, 8.85217179e-07, 8.58891337e-07,\n       7.80484800e-07, 7.67724409e-07, 7.54031637e-07, 7.45052550e-07,\n       7.32511689e-07, 7.06828122e-07, 6.59585949e-07, 6.40055245e-07,\n       6.18628925e-07, 6.17142222e-07, 6.09904832e-07, 6.07242457e-07,\n       5.72270900e-07, 5.49823535e-07, 5.22568859e-07, 5.01838721e-07,\n       4.91372576e-07, 4.82981856e-07, 4.69688423e-07, 4.59727658e-07,\n       4.54795508e-07, 4.22875379e-07, 4.13494116e-07, 3.99834682e-07,\n       3.97288987e-07, 3.87644926e-07, 3.84245584e-07, 3.81268632e-07,\n       3.67029696e-07, 3.57267536e-07, 3.52642869e-07, 3.51058992e-07,\n       3.44112772e-07, 3.36167495e-07, 3.24215712e-07, 3.23810344e-07,\n       3.21814716e-07, 3.21505459e-07, 3.10936465e-07, 2.88018831e-07,\n       2.86309762e-07, 2.76140106e-07, 2.63218703e-07, 2.56899508e-07,\n       2.51244222e-07, 2.25386521e-07, 2.15766576e-07, 2.03018243e-07,\n       1.99078411e-07, 1.97551987e-07, 1.96981706e-07, 1.92415912e-07,\n       1.84391194e-07, 1.81253585e-07, 1.78663913e-07, 1.77747846e-07,\n       1.59541769e-07, 1.38003378e-07, 1.36499298e-07, 1.22889160e-07,\n       1.22576357e-07, 1.19711121e-07, 1.09597855e-07, 9.97477409e-08,\n       9.65292710e-08, 9.36271510e-08, 9.35785637e-08, 9.34540807e-08,\n       8.40270671e-08, 7.82629028e-08, 7.54898762e-08, 6.64058115e-08,\n       5.96748649e-08, 5.79118882e-08, 5.73650143e-08, 5.65688198e-08,\n       5.34673852e-08, 5.34237630e-08, 5.29956976e-08, 4.84174907e-08,\n       3.83818937e-08])\n```\n\n    array(['E', 'T', 'A', 'O', 'I', 'N', 'S', 'R', 'H', 'L', 'D', 'C', 'U',\n           'M', 'F', 'P', 'G', 'W', 'Y', 'B', 'V', 'K', 'X', 'J', 'Q', 'Z'],\n          dtype='<U32')\n    array([0.12492063, 0.09275565, 0.08040605, 0.07640693, 0.07569278,\n           0.07233629, 0.06512767, 0.06279421, 0.05053301, 0.04068986,\n           0.03816958, 0.03343774, 0.02729702, 0.02511761, 0.02403123,\n           0.02135891, 0.01869376, 0.01675664, 0.0166498 , 0.01484649,\n           0.01053252, 0.00540513, 0.00234857, 0.00158774, 0.00120469,\n           0.00089951])\n    array(['TH', 'HE', 'IN', 'ER', 'AN', 'RE', 'ON', 'AT', 'EN', 'ND', 'TI',\n           'ES', 'OR', 'TE', 'OF', 'ED', 'IS', 'IT', 'AL', 'AR', 'ST', 'TO',\n           'NT', 'NG', 'SE', 'HA', 'AS', 'OU', 'IO', 'LE', 'VE', 'CO', 'ME',\n           'DE', 'HI', 'RI', 'RO', 'IC', 'NE', 'EA', 'RA', 'CE', 'LI', 'CH',\n           'LL', 'BE', 'MA', 'SI', 'OM', 'UR', 'CA', 'EL', 'TA', 'LA', 'NS',\n           'DI', 'FO', 'HO', 'PE', 'EC', 'PR', 'NO', 'CT', 'US', 'AC', 'OT',\n           'IL', 'TR', 'LY', 'NC', 'ET', 'UT', 'SS', 'SO', 'RS', 'UN', 'LO',\n           'WA', 'GE', 'IE', 'WH', 'EE', 'WI', 'EM', 'AD', 'OL', 'RT', 'PO',\n           'WE', 'NA', 'UL', 'NI', 'TS', 'MO', 'OW', 'PA', 'IM', 'MI', 'AI',\n           'SH', 'IR', 'SU', 'ID', 'OS', 'IV', 'IA', 'AM', 'FI', 'CI', 'VI',\n           'PL', 'IG', 'TU', 'EV', 'LD', 'RY', 'MP', 'FE', 'BL', 'AB', 'GH',\n           'TY', 'OP', 'WO', 'SA', 'AY', 'EX', 'KE', 'FR', 'OO', 'AV', 'AG',\n           'IF', 'AP', 'GR', 'OD', 'BO', 'SP', 'RD', 'DO', 'UC', 'BU', 'EI',\n           'OV', 'BY', 'RM', 'EP', 'TT', 'OC', 'FA', 'EF', 'CU', 'RN', 'SC',\n           'GI', 'DA', 'YO', 'CR', 'CL', 'DU', 'GA', 'QU', 'UE', 'FF', 'BA',\n           'EY', 'LS', 'VA', 'UM', 'PP', 'UA', 'UP', 'LU', 'GO', 'HT', 'RU',\n           'UG', 'DS', 'LT', 'PI', 'RC', 'RR', 'EG', 'AU', 'CK', 'EW', 'MU',\n           'BR', 'BI', 'PT', 'AK', 'PU', 'UI', 'RG', 'IB', 'TL', 'NY', 'KI',\n           'RK', 'YS', 'OB', 'MM', 'FU', 'PH', 'OG', 'MS', 'YE', 'UD', 'MB',\n           'IP', 'UB', 'OI', 'RL', 'GU', 'DR', 'HR', 'CC', 'TW', 'FT', 'WN',\n           'NU', 'AF', 'HU', 'NN', 'EO', 'VO', 'RV', 'NF', 'XP', 'GN', 'SM',\n           'FL', 'IZ', 'OK', 'NL', 'MY', 'GL', 'AW', 'JU', 'OA', 'EQ', 'SY',\n           'SL', 'PS', 'JO', 'LF', 'NV', 'JE', 'NK', 'KN', 'GS', 'DY', 'HY',\n           'ZE', 'KS', 'XT', 'BS', 'IK', 'DD', 'CY', 'RP', 'SK', 'XI', 'OE',\n           'OY', 'WS', 'LV', 'DL', 'RF', 'EU', 'DG', 'WR', 'XA', 'YI', 'NM',\n           'EB', 'RB', 'TM', 'XC', 'EH', 'TC', 'GY', 'JA', 'HN', 'YP', 'ZA',\n           'GG', 'YM', 'SW', 'BJ', 'LM', 'CS', 'II', 'IX', 'XE', 'OH', 'LK',\n           'DV', 'LP', 'AX', 'OX', 'UF', 'DM', 'IU', 'SF', 'BT', 'KA', 'YT',\n           'EK', 'PM', 'YA', 'GT', 'WL', 'RH', 'YL', 'HS', 'AH', 'YC', 'YN',\n           'RW', 'HM', 'LW', 'HL', 'AE', 'ZI', 'AZ', 'LC', 'PY', 'AJ', 'IQ',\n           'NJ', 'BB', 'NH', 'UO', 'KL', 'LR', 'TN', 'GM', 'SN', 'NR', 'FY',\n           'MN', 'DW', 'SB', 'YR', 'DN', 'SQ', 'ZO', 'OJ', 'YD', 'LB', 'WT',\n           'LG', 'KO', 'NP', 'SR', 'NQ', 'KY', 'LN', 'NW', 'TF', 'FS', 'CQ',\n           'DH', 'SD', 'VY', 'DJ', 'HW', 'XU', 'AO', 'ML', 'UK', 'UY', 'EJ',\n           'EZ', 'HB', 'NZ', 'NB', 'MC', 'YB', 'TP', 'XH', 'UX', 'TZ', 'BV',\n           'MF', 'WD', 'OZ', 'YW', 'KH', 'GD', 'BM', 'MR', 'KU', 'UV', 'DT',\n           'HD', 'AA', 'XX', 'DF', 'DB', 'JI', 'KR', 'XO', 'CM', 'ZZ', 'NX',\n           'YG', 'XY', 'KG', 'TB', 'DC', 'BD', 'SG', 'WY', 'ZY', 'AQ', 'HF',\n           'CD', 'VU', 'KW', 'ZU', 'BN', 'IH', 'TG', 'XV', 'UZ', 'BC', 'XF',\n           'YZ', 'KM', 'DP', 'LH', 'WF', 'KF', 'PF', 'CF', 'MT', 'YU', 'CP',\n           'PB', 'TD', 'ZL', 'SV', 'HC', 'MG', 'PW', 'GF', 'PD', 'PN', 'PC',\n           'RX', 'TV', 'IJ', 'WM', 'UH', 'WK', 'WB', 'BH', 'OQ', 'KT', 'RQ',\n           'KB', 'CG', 'VR', 'CN', 'PK', 'UU', 'YF', 'WP', 'CZ', 'KP', 'DQ',\n           'WU', 'FM', 'WC', 'MD', 'KD', 'ZH', 'GW', 'RZ', 'CB', 'IW', 'XL',\n           'HP', 'MW', 'VS', 'FC', 'RJ', 'BP', 'MH', 'HH', 'YH', 'UJ', 'FG',\n           'FD', 'GB', 'PG', 'TK', 'KK', 'HQ', 'FN', 'LZ', 'VL', 'GP', 'HZ',\n           'DK', 'YK', 'QI', 'LX', 'VD', 'ZS', 'BW', 'XQ', 'MV', 'UW', 'HG',\n           'FB', 'SJ', 'WW', 'GK', 'UQ', 'BG', 'SZ', 'JR', 'QL', 'ZT', 'HK',\n           'VC', 'XM', 'GC', 'FW', 'PZ', 'KC', 'HV', 'XW', 'ZW', 'FP', 'IY',\n           'PV', 'VT', 'JP', 'CV', 'ZB', 'VP', 'ZR', 'FH', 'YV', 'ZG', 'ZM',\n           'ZV', 'QS', 'KV', 'VN', 'ZN', 'QA', 'YX', 'JN', 'BF', 'MK', 'CW',\n           'JM', 'LQ', 'JH', 'KJ', 'JC', 'GZ', 'JS', 'TX', 'FK', 'JL', 'VM',\n           'LJ', 'TJ', 'JJ', 'CJ', 'VG', 'MJ', 'JT', 'PJ', 'WG', 'VH', 'BK',\n           'VV', 'JD', 'TQ', 'VB', 'JF', 'DZ', 'XB', 'JB', 'ZC', 'FJ', 'YY',\n           'QN', 'XS', 'QR', 'JK', 'JV', 'QQ', 'XN', 'VF', 'PX', 'ZD', 'QT',\n           'ZP', 'QO', 'DX', 'HJ', 'GV', 'JW', 'QC', 'JY', 'GJ', 'QB', 'PQ',\n           'JG', 'BZ', 'MX', 'QM', 'MZ', 'QF', 'WJ', 'ZQ', 'XR', 'ZK', 'CX',\n           'FX', 'FV', 'BX', 'VW', 'VJ', 'MQ', 'QV', 'ZF', 'QE', 'YJ', 'GX',\n           'KX', 'XG', 'QD', 'XJ', 'SX', 'VZ', 'VX', 'WV', 'YQ', 'BQ', 'GQ',\n           'VK', 'ZJ', 'XK', 'QP', 'HX', 'FZ', 'QH', 'QJ', 'JZ', 'VQ', 'KQ',\n           'XD', 'QW', 'JX', 'QX', 'KZ', 'WX', 'FQ', 'XZ', 'ZX'], dtype='<U32')\n    array([3.55620339e-02, 3.07474124e-02, 2.43274529e-02, 2.04826481e-02,\n           1.98515108e-02, 1.85432319e-02, 1.75804642e-02, 1.48673230e-02,\n           1.45424846e-02, 1.35228145e-02, 1.34257882e-02, 1.33939375e-02,\n           1.27653906e-02, 1.20486963e-02, 1.17497528e-02, 1.16812337e-02,\n           1.12842988e-02, 1.12327374e-02, 1.08744953e-02, 1.07489847e-02,\n           1.05347566e-02, 1.04126653e-02, 1.04125115e-02, 9.53014842e-03,\n           9.32114579e-03, 9.25763559e-03, 8.71095073e-03, 8.70002319e-03,\n           8.34931851e-03, 8.29254235e-03, 8.25280566e-03, 7.93859725e-03,\n           7.93006486e-03, 7.64818391e-03, 7.63241814e-03, 7.27618866e-03,\n           7.26724441e-03, 6.98707488e-03, 6.91722265e-03, 6.88165290e-03,\n           6.85633031e-03, 6.51417363e-03, 6.24352184e-03, 5.97765978e-03,\n           5.76571076e-03, 5.76283716e-03, 5.65269345e-03, 5.50057242e-03,\n           5.46256885e-03, 5.42747781e-03, 5.38164098e-03, 5.30301559e-03,\n           5.29886071e-03, 5.27529444e-03, 5.08937452e-03, 4.92966405e-03,\n           4.87753568e-03, 4.84902069e-03, 4.77989185e-03, 4.77282719e-03,\n           4.74470916e-03, 4.64574958e-03, 4.60971757e-03, 4.54257059e-03,\n           4.47772200e-03, 4.42103298e-03, 4.31534618e-03, 4.25820178e-03,\n           4.25013516e-03, 4.15745843e-03, 4.12608242e-03, 4.05151268e-03,\n           4.05075209e-03, 3.97732158e-03, 3.96527277e-03, 3.94413046e-03,\n           3.86884200e-03, 3.85337077e-03, 3.85189513e-03, 3.84646388e-03,\n           3.78793431e-03, 3.77605408e-03, 3.74420703e-03, 3.73663638e-03,\n           3.67956418e-03, 3.65492648e-03, 3.61676413e-03, 3.61373182e-03,\n           3.60899233e-03, 3.47234973e-03, 3.45829494e-03, 3.39212478e-03,\n           3.37488213e-03, 3.36877623e-03, 3.30478042e-03, 3.23572471e-03,\n           3.17759946e-03, 3.17691369e-03, 3.16447752e-03, 3.15240004e-03,\n           3.15172398e-03, 3.11176534e-03, 2.95503911e-03, 2.89966768e-03,\n           2.87848219e-03, 2.86282435e-03, 2.84865969e-03, 2.84585627e-03,\n           2.81484803e-03, 2.69544349e-03, 2.62987083e-03, 2.54961380e-03,\n           2.54906719e-03, 2.54783715e-03, 2.52606379e-03, 2.47740122e-03,\n           2.39175226e-03, 2.36573195e-03, 2.33400171e-03, 2.29786417e-03,\n           2.27503360e-03, 2.27277101e-03, 2.23911052e-03, 2.21754315e-03,\n           2.18017446e-03, 2.17360835e-03, 2.14044590e-03, 2.13767970e-03,\n           2.13188615e-03, 2.10259217e-03, 2.04932647e-03, 2.04724906e-03,\n           2.03256516e-03, 2.02845908e-03, 1.96777866e-03, 1.95449429e-03,\n           1.95410531e-03, 1.91254221e-03, 1.89316385e-03, 1.88234971e-03,\n           1.87652262e-03, 1.84944194e-03, 1.83351654e-03, 1.78086545e-03,\n           1.76468430e-03, 1.75132925e-03, 1.71573739e-03, 1.70683303e-03,\n           1.66405086e-03, 1.63999785e-03, 1.62732115e-03, 1.62613977e-03,\n           1.60361051e-03, 1.54749379e-03, 1.51636562e-03, 1.51067364e-03,\n           1.49901610e-03, 1.49455831e-03, 1.49011351e-03, 1.48460771e-03,\n           1.48077067e-03, 1.47541326e-03, 1.47480347e-03, 1.46316579e-03,\n           1.46204465e-03, 1.43745726e-03, 1.41513491e-03, 1.39980075e-03,\n           1.38382616e-03, 1.36545598e-03, 1.36333253e-03, 1.36012483e-03,\n           1.35189358e-03, 1.32127808e-03, 1.30185876e-03, 1.28328757e-03,\n           1.27907576e-03, 1.26260675e-03, 1.23637099e-03, 1.23094105e-03,\n           1.21386641e-03, 1.20743055e-03, 1.19536134e-03, 1.19032774e-03,\n           1.17626124e-03, 1.16805780e-03, 1.14618533e-03, 1.11559852e-03,\n           1.06597119e-03, 1.05782134e-03, 1.04699320e-03, 1.04540205e-03,\n           1.01153313e-03, 9.97734501e-04, 9.86028683e-04, 9.84491816e-04,\n           9.79174450e-04, 9.78784303e-04, 9.70343472e-04, 9.68322624e-04,\n           9.66708177e-04, 9.60690121e-04, 9.59749105e-04, 9.43900197e-04,\n           9.40242103e-04, 9.28331656e-04, 9.26685761e-04, 9.14014864e-04,\n           9.02555222e-04, 8.92112065e-04, 8.85803335e-04, 8.77507468e-04,\n           8.62646840e-04, 8.57695087e-04, 8.54499050e-04, 8.43925356e-04,\n           8.31382851e-04, 8.23722323e-04, 8.16643644e-04, 7.89875969e-04,\n           7.86444549e-04, 7.42072946e-04, 7.36927617e-04, 7.27646949e-04,\n           7.25004577e-04, 7.11071849e-04, 6.92833068e-04, 6.71807283e-04,\n           6.68638321e-04, 6.56391013e-04, 6.51990243e-04, 6.49048818e-04,\n           6.43397537e-04, 6.43118050e-04, 6.37839069e-04, 6.21864133e-04,\n           6.06367626e-04, 5.99162639e-04, 5.87024289e-04, 5.74860663e-04,\n           5.72519573e-04, 5.68447140e-04, 5.58806800e-04, 5.45711864e-04,\n           5.37896691e-04, 5.34768852e-04, 5.20071483e-04, 5.18874875e-04,\n           5.16054649e-04, 5.14388309e-04, 5.11931727e-04, 5.04227393e-04,\n           5.00890900e-04, 4.97325634e-04, 4.75088970e-04, 4.66605249e-04,\n           4.58324041e-04, 4.29127437e-04, 4.27514542e-04, 4.17186146e-04,\n           4.16199437e-04, 3.94646924e-04, 3.94183167e-04, 3.86306652e-04,\n           3.61812839e-04, 3.50841120e-04, 3.49059129e-04, 3.23402665e-04,\n           3.22604151e-04, 3.11527347e-04, 3.10032877e-04, 3.07611603e-04,\n           2.96010489e-04, 2.88197255e-04, 2.77494857e-04, 2.70735751e-04,\n           2.67122244e-04, 2.64790886e-04, 2.64597695e-04, 2.63237166e-04,\n           2.61362824e-04, 2.59399816e-04, 2.58614910e-04, 2.57579773e-04,\n           2.49143242e-04, 2.49036616e-04, 2.47547306e-04, 2.36748821e-04,\n           2.35282013e-04, 2.32245156e-04, 2.30209194e-04, 2.28229670e-04,\n           2.27822992e-04, 2.20319919e-04, 2.17945603e-04, 2.13543715e-04,\n           1.97145202e-04, 1.90526970e-04, 1.90304866e-04, 1.88393786e-04,\n           1.85754127e-04, 1.85322815e-04, 1.81767370e-04, 1.74089940e-04,\n           1.71644610e-04, 1.71039222e-04, 1.69557657e-04, 1.66839046e-04,\n           1.64718022e-04, 1.59561636e-04, 1.57658164e-04, 1.54026397e-04,\n           1.52211752e-04, 1.51115808e-04, 1.47564559e-04, 1.46841709e-04,\n           1.36432949e-04, 1.35005671e-04, 1.32141796e-04, 1.27573620e-04,\n           1.27432415e-04, 1.26388914e-04, 1.25919175e-04, 1.23965197e-04,\n           1.21174483e-04, 1.18691292e-04, 1.18219114e-04, 1.17637524e-04,\n           1.17526303e-04, 1.13037594e-04, 1.10863960e-04, 1.09331046e-04,\n           1.08837112e-04, 1.06567401e-04, 1.05698197e-04, 1.00512685e-04,\n           1.00106518e-04, 9.85814937e-05, 9.17495595e-05, 9.15174736e-05,\n           9.09807382e-05, 8.79007001e-05, 8.16240791e-05, 7.91627682e-05,\n           7.79158645e-05, 7.56940333e-05, 7.44394656e-05, 7.18101849e-05,\n           6.97589276e-05, 6.81802488e-05, 6.69029567e-05, 6.54143249e-05,\n           6.08786925e-05, 6.07607969e-05, 6.03570614e-05, 5.98994801e-05,\n           5.95001291e-05, 5.94970869e-05, 5.86983574e-05, 5.79700512e-05,\n           5.66119466e-05, 5.50952209e-05, 5.47453912e-05, 5.43839597e-05,\n           5.25861529e-05, 4.89722417e-05, 4.78187439e-05, 4.77415865e-05,\n           4.77107257e-05, 4.62616737e-05, 4.60653783e-05, 4.60409299e-05,\n           4.56730211e-05, 4.54645078e-05, 4.52324283e-05, 4.38982745e-05,\n           4.36906610e-05, 4.33593810e-05, 4.31226640e-05, 4.29912118e-05,\n           4.29446346e-05, 4.17137339e-05, 3.93478837e-05, 3.84895449e-05,\n           3.84390172e-05, 3.81834469e-05, 3.53827628e-05, 3.47222349e-05,\n           3.37168917e-05, 3.18518637e-05, 3.15951703e-05, 3.12905207e-05,\n           3.10605585e-05, 3.02567524e-05, 2.91709879e-05, 2.89567711e-05,\n           2.85652293e-05, 2.82994071e-05, 2.80417376e-05, 2.77861205e-05,\n           2.77303518e-05, 2.76273746e-05, 2.72172235e-05, 2.69880432e-05,\n           2.66503046e-05, 2.66033916e-05, 2.62086568e-05, 2.59259584e-05,\n           2.57640153e-05, 2.56299050e-05, 2.54449453e-05, 2.51909823e-05,\n           2.47409597e-05, 2.46797892e-05, 2.42472084e-05, 2.35748710e-05,\n           2.24438116e-05, 2.24317329e-05, 2.23097275e-05, 2.21249597e-05,\n           2.17815183e-05, 2.15248592e-05, 2.09465192e-05, 2.09125513e-05,\n           1.96913177e-05, 1.95330853e-05, 1.91064697e-05, 1.88952009e-05,\n           1.85746459e-05, 1.81220081e-05, 1.78919334e-05, 1.73267658e-05,\n           1.61874055e-05, 1.60765855e-05, 1.58740992e-05, 1.45486411e-05,\n           1.40812264e-05, 1.36678429e-05, 1.32768479e-05, 1.31460479e-05,\n           1.30872012e-05, 1.29588223e-05, 1.25748548e-05, 1.24146066e-05,\n           1.22821602e-05, 1.22486357e-05, 1.20714645e-05, 1.20448925e-05,\n           1.19866728e-05, 1.18936663e-05, 1.17590888e-05, 1.17001978e-05,\n           1.16346360e-05, 1.11092945e-05, 1.08992577e-05, 1.06740258e-05,\n           1.06735218e-05, 1.06144296e-05, 1.05679067e-05, 1.03656570e-05,\n           1.03317955e-05, 9.98437559e-06, 9.01036943e-06, 8.85768061e-06,\n           8.76035160e-06, 8.60019167e-06, 8.19227801e-06, 7.80479658e-06,\n           7.53516931e-06, 7.44150882e-06, 7.30644125e-06, 7.26777599e-06,\n           7.06747616e-06, 6.95177332e-06, 6.85925126e-06, 6.74132156e-06,\n           6.71322068e-06, 6.70106994e-06, 6.66133186e-06, 6.47626505e-06,\n           6.38130476e-06, 6.29576510e-06, 6.24612583e-06, 5.93271496e-06,\n           5.92132104e-06, 5.83947722e-06, 5.76779879e-06, 5.76465728e-06,\n           5.53187023e-06, 5.47131015e-06, 5.33180695e-06, 5.22417954e-06,\n           5.20732008e-06, 5.15949060e-06, 5.11569104e-06, 4.95336950e-06,\n           4.94557425e-06, 4.73636484e-06, 4.63955858e-06, 4.53340156e-06,\n           4.22935422e-06, 4.19307790e-06, 4.17347414e-06, 4.12142146e-06,\n           4.11855764e-06, 3.80541311e-06, 3.36707879e-06, 3.29563656e-06,\n           3.17577578e-06, 3.05442971e-06, 2.98983688e-06, 2.97762691e-06,\n           2.95066092e-06, 2.91720550e-06, 2.89840858e-06, 2.77497857e-06,\n           2.76265227e-06, 2.74176112e-06, 2.70310579e-06, 2.61648976e-06,\n           2.60275585e-06, 2.56616744e-06, 2.55465117e-06, 2.49712549e-06,\n           2.42815484e-06, 2.37933375e-06, 2.35040476e-06, 2.33914845e-06,\n           2.33036549e-06, 2.32978989e-06, 2.28930419e-06, 2.28804340e-06,\n           2.26346210e-06, 2.24353844e-06, 2.23182640e-06, 2.23165865e-06,\n           2.22696341e-06, 2.22115030e-06, 2.21572164e-06, 2.20668084e-06,\n           2.19243658e-06, 2.17382266e-06, 2.08159887e-06, 2.07762818e-06,\n           1.95415065e-06, 1.88693410e-06, 1.83219245e-06, 1.81431726e-06,\n           1.67631850e-06, 1.67169206e-06, 1.63803449e-06, 1.57770706e-06,\n           1.56577585e-06, 1.53130790e-06, 1.52519015e-06, 1.52439998e-06,\n           1.49350905e-06, 1.47212210e-06, 1.45715861e-06, 1.40331777e-06,\n           1.38641504e-06, 1.29786439e-06, 1.27069447e-06, 1.25613209e-06,\n           1.23105569e-06, 1.22268909e-06, 1.21688094e-06, 1.18065108e-06,\n           1.18060143e-06, 1.16794389e-06, 1.13216621e-06, 1.12716419e-06,\n           1.12418866e-06, 1.12412659e-06, 1.05684621e-06, 1.05049722e-06,\n           1.04986594e-06, 1.03676402e-06, 1.03482230e-06, 9.96847192e-07,\n           9.75926251e-07, 9.54397081e-07, 9.36101632e-07, 9.30100914e-07,\n           9.27467975e-07, 8.92801774e-07, 8.85217179e-07, 8.58891337e-07,\n           7.80484800e-07, 7.67724409e-07, 7.54031637e-07, 7.45052550e-07,\n           7.32511689e-07, 7.06828122e-07, 6.59585949e-07, 6.40055245e-07,\n           6.18628925e-07, 6.17142222e-07, 6.09904832e-07, 6.07242457e-07,\n           5.72270900e-07, 5.49823535e-07, 5.22568859e-07, 5.01838721e-07,\n           4.91372576e-07, 4.82981856e-07, 4.69688423e-07, 4.59727658e-07,\n           4.54795508e-07, 4.22875379e-07, 4.13494116e-07, 3.99834682e-07,\n           3.97288987e-07, 3.87644926e-07, 3.84245584e-07, 3.81268632e-07,\n           3.67029696e-07, 3.57267536e-07, 3.52642869e-07, 3.51058992e-07,\n           3.44112772e-07, 3.36167495e-07, 3.24215712e-07, 3.23810344e-07,\n           3.21814716e-07, 3.21505459e-07, 3.10936465e-07, 2.88018831e-07,\n           2.86309762e-07, 2.76140106e-07, 2.63218703e-07, 2.56899508e-07,\n           2.51244222e-07, 2.25386521e-07, 2.15766576e-07, 2.03018243e-07,\n           1.99078411e-07, 1.97551987e-07, 1.96981706e-07, 1.92415912e-07,\n           1.84391194e-07, 1.81253585e-07, 1.78663913e-07, 1.77747846e-07,\n           1.59541769e-07, 1.38003378e-07, 1.36499298e-07, 1.22889160e-07,\n           1.22576357e-07, 1.19711121e-07, 1.09597855e-07, 9.97477409e-08,\n           9.65292710e-08, 9.36271510e-08, 9.35785637e-08, 9.34540807e-08,\n           8.40270671e-08, 7.82629028e-08, 7.54898762e-08, 6.64058115e-08,\n           5.96748649e-08, 5.79118882e-08, 5.73650143e-08, 5.65688198e-08,\n           5.34673852e-08, 5.34237630e-08, 5.29956976e-08, 4.84174907e-08,\n           3.83818937e-08])\n\n\n## Speed matrix  <a name=\"speed\">\n### 24x24 relative Speed matrix between key pair (averaged for left/right symmetry)\n\n  - does not take into account order of key pairs (see Flow24x24 matrix)\n  - the original version was constructed with data from right-handed people\n  - 24 keys that don't require extending index or little fingers (\"home block keys\")\n\n### Home block keys\n\n        Left:            Right:\n     1  2  3  4       13 14 15 16 \n     5  6  7  8       17 18 19 20\n     9 10 11 12       21 22 23 24\n\nInterkey stroke times in milliseconds from Table 3 of <br>\n\"Estimation of digraph costs for keyboard layout optimization\", <br>\nA Iseri, Ma Eksioglu, International Journal of Industrial Ergonomics, 48, 127-138, 2015. <br>\nKey numbering in article and in spreadsheet:\n\n         Left:           Right:\n     1 4 7 10 13   16 19 22 25 28 31\n     2 5 8 11 14   17 20 23 26 29 32\n     3 6 9 12 15   18 21 24 27 30\n     \n### Load table of interkey speeds\n\n\n```python\nload_original_interkey_timings_table = False\nif load_original_interkey_timings_table:\n\n    interkey_table = \"data/interkey-timings.xlsx\"\n    wb = xlrd.open_workbook(interkey_table) \n    interkey_sheet = wb.sheet_by_index(0)\n\n    # Convert interkey stroke times table to array:\n    Time32x32 = np.zeros((32,32))\n    for i in range(1,33):\n        for j in range(1,33):\n            if interkey_sheet.cell_value(i,j):\n                Time32x32[i-1,j-1] = interkey_sheet.cell_value(i,j)\n\n    # Fill empty (symmetric) portion of the array:\n    for i in range(1,33):\n        for j in range(1,33):\n            if interkey_sheet.cell_value(i,j):\n                Time32x32[j-1,i-1] = interkey_sheet.cell_value(i,j)\n\n    # Extract pairwise entries for the 24 vertical range keys:\n    table_24_positions = [1,4,7,10, 2,5,8,11, 3,6,9,12,  19,22,25,28, 20,23,26,29, 21,24,27,30]\n    Time24x24 = np.zeros((24, 24))\n    u = 0\n    for i in table_24_positions:\n        u += 1\n        v = 0\n        for j in table_24_positions:\n            v += 1\n            Time24x24[u-1,v-1] = Time32x32[i-1,j-1]\n\n    # Save:\n    if print_output:\n        file = open(\"Time24x24.txt\", \"w+\")\n        file.write(str(Time24x24))\n        file.close()\n\n    # Print:\n    print(repr(Time24x24))\n\nelse:\n    Time24x24 = np.array([[196., 225., 204., 164., 266., 258., 231., 166., 357., 325., 263.,\n        186., 169., 176., 178., 186., 156., 156., 158., 163., 171., 175., 177., 185.],\n       [225., 181., 182., 147., 239., 245., 196., 150., 289., 296., 229.,\n        167., 162., 169., 170., 178., 148., 148., 150., 155., 163., 167., 169., 177.],\n       [204., 182., 170., 149., 196., 194., 232., 155., 237., 214., 263.,\n        166., 157., 164., 165., 173., 143., 143., 145., 150., 158., 163., 164., 172.],\n       [164., 147., 149., 169., 160., 161., 157., 226., 165., 185., 234.,\n        257., 154., 162., 163., 171., 141., 141., 143., 148., 156., 160., 162., 170.],\n       [266., 239., 196., 160., 196., 240., 208., 166., 271., 267., 208.,\n        169., 143., 150., 151., 160., 129., 129., 132., 137., 145., 149., 151., 159.],\n       [258., 245., 194., 161., 240., 181., 183., 149., 245., 256., 184.,\n        150., 138., 145., 146., 154., 124., 124., 126., 131., 139., 144., 145., 153.],\n       [231., 196., 232., 157., 208., 183., 170., 149., 201., 215., 239.,\n        151., 134., 141., 142., 150., 120., 120., 122., 127., 135., 140., 141., 149.],\n       [166., 150., 155., 226., 166., 149., 149., 169., 160., 147., 170.,\n        221., 133., 140., 141., 150., 119., 119., 122., 126., 135., 139., 141., 149.],\n       [357., 289., 237., 165., 271., 245., 201., 160., 196., 236., 194.,\n        161., 171., 178., 179., 188., 157., 157., 160., 164., 173., 177., 179., 187.],\n       [325., 296., 214., 185., 267., 256., 215., 147., 236., 181., 184.,\n        157., 166., 173., 174., 182., 152., 152., 154., 159., 167., 172., 173., 181.],\n       [263., 229., 263., 234., 208., 184., 239., 170., 194., 184., 170.,\n        150., 159., 166., 167., 176., 145., 145., 148., 153., 161., 165., 167., 175.],\n       [186., 167., 166., 257., 169., 150., 151., 221., 161., 157., 150.,\n        169., 153., 160., 161., 169., 139., 139., 141., 146., 154., 159., 160., 168.],\n       [169., 162., 157., 154., 143., 138., 134., 133., 171., 166., 159.,\n        153., 151., 147., 141., 145., 188., 151., 142., 164., 213., 204., 162., 145.],\n       [176., 169., 164., 162., 150., 145., 141., 140., 178., 173., 166.,\n        160., 147., 151., 189., 209., 137., 207., 191., 206., 149., 227.,  208., 226.],\n       [178., 170., 165., 163., 151., 146., 142., 141., 179., 174., 167.,\n        161., 141., 189., 157., 253., 136., 188., 210., 231., 155., 226.,   239., 225.],\n       [186., 178., 173., 171., 160., 154., 150., 150., 188., 182., 176.,\n        169., 145., 209., 253., 170., 147., 206., 251., 233., 164., 268.,  362., 236.],\n       [156., 148., 143., 141., 129., 124., 120., 119., 157., 152., 145.,\n        139., 188., 137., 136., 147., 151., 133., 138., 152., 192., 149.,  139., 143.],\n       [156., 148., 143., 141., 129., 124., 120., 119., 157., 152., 145.,\n        139., 151., 207., 188., 206., 133., 151., 179., 183., 145., 204.,  183., 194.],\n       [158., 150., 145., 143., 132., 126., 122., 122., 160., 154., 148.,\n        141., 142., 191., 210., 251., 138., 179., 157., 240., 145., 185.,  208., 235.],\n       [163., 155., 150., 148., 137., 131., 127., 126., 164., 159., 153.,\n        146., 164., 206., 231., 233., 152., 183., 240., 170., 160., 220.,  293., 230.],\n       [171., 163., 158., 156., 145., 139., 135., 135., 173., 167., 161.,\n        154., 213., 149., 155., 164., 192., 145., 145., 160., 151., 140.,  142., 175.],\n       [175., 167., 163., 160., 149., 144., 140., 139., 177., 172., 165.,\n        159., 204., 227., 226., 268., 149., 204., 185., 220., 140., 151.,  175., 265.],\n       [177., 169., 164., 162., 151., 145., 141., 141., 179., 173., 167.,\n        160., 162., 208., 239., 362., 139., 183., 208., 293., 142., 175.,  157., 265.],\n       [185., 177., 172., 170., 159., 153., 149., 149., 187., 181., 175.,\n        168., 145., 226., 225., 236., 143., 194., 235., 230., 175., 265.,  265., 170.]])\n\n# Left/right symmetric version of the Time24x24 matrix\n# (The original version was constructed with data from right-handed people.)\nTimeSymmetric24x24 = np.ones((24,24))\n\n#        Left:            Right:\n#     1  2  3  4       13 14 15 16 \n#     5  6  7  8       17 18 19 20\n#     9 10 11 12       21 22 23 24\n\nI = [1,2,3,4, 5,6,7,8, 9,10,11,12,  16,15,14,13, 20,19,18,17, 24,23,22,21]\nJ = [16,15,14,13, 20,19,18,17, 24,23,22,21,  1,2,3,4, 5,6,7,8, 9,10,11,12]\n\nfor i1, I1 in enumerate(I):\n    for i2, I2 in enumerate(I):\n        J1 = J[i1] - 1\n        J2 = J[i2] - 1\n        #print(i1,i2,I1-1,I2-1,J1,J2)\n        avgvalue = (Time24x24[I1-1,I2-1] + Time24x24[J1,J2]) / 2 \n        TimeSymmetric24x24[I1-1,I2-1] = avgvalue\n        TimeSymmetric24x24[J1,J2] = avgvalue\n\n# Normalize matrix with min-max scaling to a range with maximum = 1:\nnewMin = np.min(TimeSymmetric24x24) / np.max(TimeSymmetric24x24)\nnewMax = 1.0\nTimeSymmetric24x24 = newMin + (TimeSymmetric24x24 - np.min(TimeSymmetric24x24)) * (newMax - newMin) / (np.max(TimeSymmetric24x24) - np.min(TimeSymmetric24x24))\n\n# Convert relative interkey stroke times to relative speeds by subtracting from 1:\nSpeed24x24 = 1 - TimeSymmetric24x24 + np.min(TimeSymmetric24x24)\n\n# Print:\nprint_matrix_info(matrix_data=Speed24x24, matrix_label=\"Speed24x24\", nkeys=24, nlines=50)\nheatmap(data=Speed24x24, title=\"Speed24x24\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n# Print:\n#print(repr(Speed24x24))\n\n# Save:\nif print_output:\n    file = open(\"Speed24x24.txt\", \"w+\")\n    file.write(str(Speed24x24))\n    file.close()\n\n```\n\n\n```python\n# Histogram\nsns_plot = sns.distplot(Speed24x24)\nif print_output:\n    sns_plot.figure.savefig(\"{0}_histogram.png\".format(\"Speed24x24\"))\n```\n\nOutput:\n\n        Left:            Right:\n     1  2  3  4       13 14 15 16 \n     5  6  7  8       17 18 19 20\n     9 10 11 12       21 22 23 24\n\n    Speed24x24 min = 0.34643377001455605, max = 1.0\n    Speed24x24 key number pairs with minimum values:\n        10 -> 1        (0.34643377001455605)\n        16 -> 23        (0.34643377001455605)\n        1 -> 10        (0.34643377001455605)\n        23 -> 16        (0.34643377001455605)\n        1 -> 9        (0.4832605531295488)\n        16 -> 24        (0.4832605531295488)\n        9 -> 1        (0.4832605531295488)\n        24 -> 16        (0.4832605531295488)\n        20 -> 23        (0.5312954876273654)\n        23 -> 20        (0.5312954876273654)\n        10 -> 5        (0.5312954876273654)\n        5 -> 10        (0.5312954876273654)\n        15 -> 23        (0.5676855895196506)\n        23 -> 15        (0.5676855895196506)\n        10 -> 2        (0.5676855895196506)\n        2 -> 10        (0.5676855895196506)\n        11 -> 1        (0.5735080058224165)\n        22 -> 16        (0.5735080058224165)\n        16 -> 22        (0.5735080058224165)\n        1 -> 11        (0.5735080058224165)\n        9 -> 2        (0.5982532751091705)\n        15 -> 24        (0.5982532751091705)\n        2 -> 9        (0.5982532751091705)\n        24 -> 15        (0.5982532751091705)\n        19 -> 16        (0.6055312954876275)\n        1 -> 6        (0.6055312954876275)\n        16 -> 19        (0.6055312954876275)\n        6 -> 1        (0.6055312954876275)\n        20 -> 24        (0.6171761280931587)\n        10 -> 9        (0.6171761280931587)\n        24 -> 23        (0.6171761280931587)\n        5 -> 9        (0.6171761280931587)\n        23 -> 24        (0.6171761280931587)\n        9 -> 10        (0.6171761280931587)\n        9 -> 5        (0.6171761280931587)\n        24 -> 20        (0.6171761280931587)\n        5 -> 1        (0.6200873362445416)\n        20 -> 16        (0.6200873362445416)\n        16 -> 20        (0.6200873362445416)\n        1 -> 5        (0.6200873362445416)\n        3 -> 11        (0.6331877729257642)\n        14 -> 22        (0.6331877729257642)\n        22 -> 14        (0.6331877729257642)\n        11 -> 3        (0.6331877729257642)\n        6 -> 5        (0.6477438136826783)\n        6 -> 9        (0.6477438136826783)\n        19 -> 24        (0.6477438136826783)\n        20 -> 19        (0.6477438136826783)\n        19 -> 20        (0.6477438136826783)\n        24 -> 19        (0.6477438136826783)\n    Speed24x24 key number pairs with maximum values:\n        17 -> 8        (1.0)\n        8 -> 17        (1.0)\n        17 -> 7        (0.9985443959243085)\n        18 -> 8        (0.9985443959243085)\n        7 -> 17        (0.9985443959243085)\n        8 -> 18        (0.9985443959243085)\n        7 -> 18        (0.9970887918486171)\n        18 -> 7        (0.9970887918486171)\n        17 -> 6        (0.9883551673944688)\n        7 -> 19        (0.9883551673944688)\n        18 -> 6        (0.9883551673944688)\n        19 -> 8        (0.9883551673944688)\n        6 -> 18        (0.9883551673944688)\n        19 -> 7        (0.9883551673944688)\n        6 -> 17        (0.9883551673944688)\n        8 -> 19        (0.9883551673944688)\n        6 -> 19        (0.9796215429403203)\n        19 -> 6        (0.9796215429403203)\n        17 -> 5        (0.975254730713246)\n        5 -> 17        (0.975254730713246)\n        20 -> 8        (0.975254730713246)\n        8 -> 20        (0.975254730713246)\n        5 -> 18        (0.9737991266375545)\n        7 -> 20        (0.9737991266375545)\n        20 -> 7        (0.9737991266375545)\n        18 -> 5        (0.9737991266375545)\n        6 -> 20        (0.9636098981077148)\n        19 -> 5        (0.9636098981077148)\n        5 -> 19        (0.9636098981077148)\n        20 -> 6        (0.9636098981077148)\n        20 -> 5        (0.9475982532751093)\n        8 -> 13        (0.9475982532751093)\n        21 -> 8        (0.9475982532751093)\n        21 -> 7        (0.9475982532751093)\n        18 -> 12        (0.9475982532751093)\n        17 -> 12        (0.9475982532751093)\n        8 -> 21        (0.9475982532751093)\n        7 -> 21        (0.9475982532751093)\n        13 -> 8        (0.9475982532751093)\n        17 -> 4        (0.9475982532751093)\n        5 -> 20        (0.9475982532751093)\n        12 -> 17        (0.9475982532751093)\n        12 -> 18        (0.9475982532751093)\n        4 -> 17        (0.9475982532751093)\n        4 -> 18        (0.9461426491994178)\n        18 -> 4        (0.9461426491994178)\n        13 -> 7        (0.9461426491994178)\n        7 -> 13        (0.9461426491994178)\n        21 -> 6        (0.9388646288209608)\n        19 -> 12        (0.9388646288209608)\n\n\n## Strength matrix  <a name=\"strength\">\n\n### 24x24 relative finger position STRENGTH matrix\n\nFinger strengths are based on peak keyboard reaction forces (in newtons) from Table 4 of <br>\n\"Keyboard Reaction Force and Finger Flexor Electromyograms during Computer Keyboard Work\" <br>\nBJ Martin, TJ Armstrong, JA Foulke, S Natarajan, Human Factors,1996,38(4),654-664:\n   \n    middle     2.36\n    index      2.26\n    ring       2.02\n    little     1.84\n    \n    index/middle:  0.9576271186440678\n    ring/middle:   0.8559322033898306\n    little/middle: 0.7796610169491526\n\nFor reference, Table 1 of \"Ergonomic keyboard layout designed for the Filipino language\", 2016 (doi: 10.1007/978-3-319-41694-6_41) presents \"average finger strength of Filipinos [n=30, ages 16-36] measured in pounds\":\n   \n                L       R\n    little     3.77   4.27\n    ring       4.54   5.08\n    middle     5.65   6.37\n    index      6.09   6.57\n    \n    6.57/4.27 = 1.54\n    6.09/3.77 = 1.62\n    6.37/5.08 = 1.25\n    5.65/4.54 = 1.24\n    \nWe won't use these results as I don't feel they represent relative strength relevant for typing: \"Respondents were asked to sit in upright position, with their wrists resting on a flat surface. A pinch gauge was placed within each finger's reach. The respondents were asked to exert maximum pressure on the device.\"\n    \nThe following does not take into account order of key pairs (see Flow matrix).\n\n\n\n```python\nif apply_strength:\n\n    # Normalize by the highest peak force (middle finger):\n    middle_force = 2.36\n    index_force = 2.26\n    ring_force = 2.02\n    little_force = 1.84\n    middle_norm = 1.0\n    index_norm = index_force / middle_force\n    ring_norm = ring_force / middle_force\n    little_norm = little_force / middle_force\n    print('index/middle: {0}'.format(index_norm))\n    print('ring/middle: {0}'.format(ring_norm))\n    print('little/middle: {0}'.format(little_norm))\n    \n    # Relative left/right hand strength (assume equal):\n    lf = 1.0\n    rf = 1.0\n    \n    strengths24 = np.array((\n                        lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                        lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                        lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                        rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm,\n                        rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm,\n                        rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm))\n\n    # Create a finger-pair position strength matrix by adding pairs of strength values:\n    Strength24x24 = np.zeros((24, 24))\n    for i in range(24):\n        Strength24x24[i,:] = strengths24\n    Strength24x24 = (Strength24x24 + Strength24x24.transpose())\n\n    # Normalize matrix with min-max scaling to a range with maximum = 1:\n    #newMin = strength_factor\n    newMin = min_strength_factor  # np.min(Strength24x24) / np.max(Strength24x24)\n    newMax = 1.0\n    Strength24x24 = newMin + (Strength24x24 - np.min(Strength24x24)) * (newMax - newMin) / (np.max(Strength24x24) - np.min(Strength24x24))\n\n    # Print:\n    print_matrix_info(matrix_data=Strength24x24, matrix_label=\"Strength24x24\", nkeys=24, nlines=10)\n    heatmap(data=Strength24x24, title=\"Strength24x24\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n    # Save:\n    if print_output:\n        file = open(\"Strength24x24.txt\", \"w+\")\n        file.write(str(Strength24x24))\n        file.close()\n```\n\n\n```python\nif apply_strength:\n\n    # Histogram\n    sns_plot = sns.distplot(Strength24x24)\n    if print_output:\n        sns_plot.figure.savefig(\"{0}_histogram.png\".format(\"Strength24x24\"))\n```\n\n\n```python\nif apply_strength:\n\n    penalty = 1.0  # Penalty for lateral (index, little) finger placement (1 = no penalty)\n\n    strengths32 = np.array((lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                            lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                            lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                            rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm,\n                            rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm,\n                            rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm,\n                            lf * index_norm * penalty, lf * index_norm * penalty, lf * index_norm * penalty,\n                            rf * index_norm * penalty, rf * index_norm * penalty, rf * index_norm * penalty,\n                            rf * little_norm * penalty, rf * little_norm * penalty))\n\n    # Create a finger-pair position strength matrix by adding pairs of strength values:\n    Strength32x32 = np.zeros((32, 32))\n    for i in range(32):\n        Strength32x32[i,:] = strengths32\n    Strength32x32 = (Strength32x32 + Strength32x32.transpose())\n\n    # Normalize matrix with min-max scaling to a range with maximum = 1:\n    newMin = np.min(Strength32x32) / np.max(Strength32x32)\n    newMax = 1.0\n    Strength32x32 = newMin + (Strength32x32 - np.min(Strength32x32)) * (newMax - newMin) / (np.max(Strength32x32) - np.min(Strength32x32))\n\n    # Print:\n    print_matrix_info(matrix_data=Strength32x32, matrix_label=\"Strength32x32\", nkeys=32, nlines=10)\n    heatmap(data=Strength32x32, title=\"Strength32x32\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n    # Save:\n    if print_output:\n        file = open(\"Strength32x32.txt\", \"w+\")\n        file.write(str(Strength32x32))\n        file.close()\n```\n\n\n```python\nif apply_strength:\n\n    # Histogram\n    sns_plot = sns.distplot(Strength32x32)\n    if print_output:\n        sns_plot.figure.savefig(\"{0}_histogram.png\".format(\"Strength32x32\"))\n```\n\n### Strength output\n\n    index/middle: 0.9576271186440678\n    ring/middle: 0.8559322033898306\n    little/middle: 0.7796610169491526\n\n        Left:            Right:\n     1  2  3  4       13 14 15 16 \n     5  6  7  8       17 18 19 20\n     9 10 11 12       21 22 23 24\n\n    Strength24x24 min = 0.7796610169491526, max = 1.0\n    Strength24x24 key number pairs with minimum values:\n        1 -> 1        (0.7796610169491526)\n        5 -> 9        (0.7796610169491526)\n        5 -> 16        (0.7796610169491526)\n        5 -> 20        (0.7796610169491526)\n        5 -> 24        (0.7796610169491526)\n        9 -> 1        (0.7796610169491526)\n        9 -> 5        (0.7796610169491526)\n        9 -> 9        (0.7796610169491526)\n        9 -> 16        (0.7796610169491526)\n        9 -> 20        (0.7796610169491526)\n    Strength24x24 key number pairs with maximum values:\n        18 -> 11        (1.0)\n        22 -> 14        (1.0)\n        3 -> 14        (1.0)\n        7 -> 18        (1.0)\n        18 -> 7        (1.0)\n        18 -> 14        (1.0)\n        3 -> 18        (1.0)\n        18 -> 18        (1.0)\n        22 -> 22        (1.0)\n        18 -> 22        (1.0)\n    Strength32x32 min = 0.7796610169491526, max = 1.0\n    Strength32x32 key number pairs with minimum values:\n        1 -> 1        (0.7796610169491526)\n        20 -> 5        (0.7796610169491526)\n        20 -> 1        (0.7796610169491526)\n        32 -> 31        (0.7796610169491526)\n        16 -> 31        (0.7796610169491526)\n        16 -> 24        (0.7796610169491526)\n        16 -> 20        (0.7796610169491526)\n        16 -> 16        (0.7796610169491526)\n        16 -> 9        (0.7796610169491526)\n        16 -> 5        (0.7796610169491526)\n    Strength32x32 key number pairs with maximum values:\n        22 -> 3        (1.0)\n        18 -> 22        (1.0)\n        3 -> 22        (1.0)\n        22 -> 7        (1.0)\n        11 -> 11        (1.0)\n        7 -> 18        (1.0)\n        11 -> 14        (1.0)\n        7 -> 22        (1.0)\n        11 -> 18        (1.0)\n        14 -> 18        (1.0)\n\n## Flow matrix and Engram scoring model  <a name=\"flow\">\n\nThe Flow24x24 matrix takes into account ease of transition between ordered pairs of keys.\n    \nOur optimization algorithm finds every permutation of a given set of letters, maps these letter permutations to a set of keys, and ranks these letter-key mappings according to a score reflecting ease of typing key pairs and frequency of letter pairs (bigrams). The score is the average of the scores for all possible bigrams in this arrangement. The score for each bigram is a product of the frequency of occurrence of that bigram, the frequency of each of the bigram\u2019s characters, and flow, strength (and optional speed) factors for the key pair.\n\n#### Dvorak et al. (1936) defined eleven criteria for the design and evaluation of keyboard layouts:\n1.  Deviation from the balance of hand and finger loads should be as low as possible.\n2.  Percentage of tapping with the same fingers should be as low as possible.\n3.  Percentage of tapping that includes top row should be as low as possible.\n4.  Percentage of tapping that includes bottom row should be as low as possible.\n5.  Percentage of tapping in the home row should be as high as possible.\n6.  Percentage of tapping by alternating hands should be as high as possible.\n7.  Percentage of hurdles with the same finger should be as low as possible.\n8.  Percentage of hurdles with adjacent offset fingers should be as low as possible.\n9.  Percentage of hurdles with remote fingers should be as low as possible.\n10. Percentage of reach with the same finger should be as low as possible.\n11. Percentage of reach with adjacent offset fingers should be as low as possible.\n\n#### Synopsis of above criteria for pairwise key presses when touch typing:\n1. Alternate between hands.\n2. Balance finger loads, and avoid using the same finger.\n3. Avoid the upper and lower rows, and avoid skipping over the home row.\n4. Avoid tapping adjacent offset rows with the same or adjacent offset fingers.\n    \n### Factors to penalize strenuous key transitions\n\nDirection:\n    \n    - outward = 0.9: outward roll of fingers from the index to little finger (same hand)\n\nDexterity:\n    \n    - side_above_3away = 0.9\n        - index and little finger type two keys, one or more rows apart (same hand)\n    - side_above_2away = 0.9^2 = 0.81\n        - index finger types key a row or two above ring finger key, or\n        - little finger types key a row or two above middle finger key (same hand)\n    - side_above_1away = 0.9^3 = 0.729\n        - index finger types key a row or two above middle finger key, or\n        - little finger types key a row or two above ring finger key (same hand)\n    - middle_above_ring = 0.9\n        - middle finger types key a row or two above ring finger key (same hand)\n    - ring_above_middle = 0.9^3 = 0.729\n        - ring finger types key a row or two above middle finger key (same hand)\n    - lateral = 0.9\n        - lateral movement of (index or little) finger outside of 8 vertical columns\n    \nDistance:\n    \n    - skip_row_3away = 0.9       \n        - index and little fingers type two keys that skip over home row (same hand)\n        - (e.g., one on bottom row, the other on top row)\n    - skip_row_2away = 0.9^3 = 0.729\n        - little and middle or index and ring fingers type two keys that skip over home row (same hand)\n    - skip_row_1away = 0.9^5 = 0.59049\n        - little and ring or middle and index fingers type two keys that skip over home row (same hand)\n\nRepetition:\n \n    - skip_row_0away = 0.9^4 = 0.6561\n        - same finger types two keys that skip over home row\n    - same_finger = 0.9^5 = 0.59049\n        - use same finger again for a different key\n        - cannot accompany outward, side_above, or adjacent_shorter_above \n\nStrength: Accounted for by the strength matrix (minimum value for the little finger = 0.9)    \n\n### Example flow values for left side home block\n   \nNo penalty (for same hand, both keys in the same row in an inward roll or repeating the same key):\n\n    2=>2, 2=>3, 3=>4, 2=>4, 1=>4\n\n    1  2  3  4\n    5  6  7  8\n    9 10 11 12\n\nPenalty = 0.9:\n\n    outward: 2=>1, 3=>1, 3=>2, 4=>1, 4=>2, 4=>3, 6=>5, 7=>6, 7=>5, 8=>7, 8=>6, 8=>5,... \n    middle_above_ring: 6=>3, 10=>7 \n    side_above_3away: 1=>8, 5=>4, 5=>12, 9=>8\n    index_above: 1=>4, 2=>4, 3=>4, 4=>4\n\nPenalty = 0.9^2:\n\n    middle_above_ring * outward: 3=>6, 7=>10\n    side_above_3away * outward: 8=>1, 4=>5, 12=>5, 8=>9\n    side_above_2away: 1=>7, 6=>4, 5=>11, 10=>8    \n    skip_row_3away * side_above_3away: 1=>12, 9=>4\n    skip_row_2away: 2=>12, 9=>3\n    ring_above_middle 2=>7, 6=>11\n    side_above_2away * outward: 7=>1, 4=>6, 11=>5, 8=>10\n    side_above_1away: 1=>6, 7=>4, 5=>10, 11=>8\n\nPenalty = 0.9^3:\n\n    skip_row_3away * side_above_3away * outward: 12=>1, 4=>9\n\nPenalty = 0.9^4:\n\n    ring_above_middle * outward: 7=>2, 11=>6\n    side_above_1away * outward: 4=>7, 6=>1, 10=>5, 4=>7\n\nPenalty = 0.9^5:\n\n    same_finger: 4=>8, 8=>4, 1=>5, 5=>1, 5=>9, 9=>5, 2=>6, 6=>2,...\n    skip_row_2away * side_above_2away: 10=>4, 1=>11\n    skip_row_1away: 1=>10, 9=>2, 3=>12\n\nPenalty = 0.9^6:\n\n    skip_row_2away * side_above_2away * outward: 4=>10, 11=>1\n    skip_row_1away * outward: 10=>1, 2=>9, 12=>3\n\nPenalty = 0.9^8\n\n    skip_row_1away * ring_above_middle: 2=>11\n    skip_row_1away * side_above_1away: 1=>10, 11=>4\n\nPenalty = 0.9^9\n\n    skip_row_1away * ring_above_middle * outward: 11=>2\n    skip_row_0away * same_finger: 1=>9, 9=>1, 4=>12, 12=>4, 2=>10, 10=>2, 3=>11, 11=>3     \n    skip_row_1away * side_above_1away * outward: 10=>1, 4=>11\n\n#### 24 keys:\n\n\n```python\ndef create_24x24_flow_matrix(not_home_row, side_top, side_above_3away, side_above_2away, side_above_1away, \n                             middle_above_ring, ring_above_middle, outward, skip_row_3away, \n                             skip_row_2away, skip_row_1away, skip_row_0away, same_finger, lateral, \n                             same_hand, shorter_above, adjacent_offset, inside_top, index_above):\n\n    all_24_keys = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24]\n\n    # Create a matrix and multiply by flow factors that promote easy interkey transitions:\n    T = np.ones((24, 24))\n\n    # 7.  Promote alternating between hands over uncomfortable transitions with the same hand.\n    if same_hand < 1.0:\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n        for i in range(0,12):\n            for j in range(0,12):\n                T[i,j] *= same_hand\n        for i in range(12,24):\n            for j in range(12,24):\n                T[i,j] *= same_hand\n\n    # 8.  Promote little-to-index-finger roll-ins over index-to-little-finger outwards.\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    if outward < 1.0:\n\n        # same-row roll-outs:\n        roll_ins = [[1,2],[2,3],[3,4], [5,6],[6,7],[7,8], [9,10],[10,11],[11,12],\n                    [16,15],[15,14],[14,13], [20,19],[19,18],[18,17], [24,23],[23,22],[22,21]]\n        for x in roll_ins:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # same-row roll-outs, skipping keys:\n        roll_ins_skip_keys = [[1,3],[2,4],[1,4], [5,7],[6,8],[5,8], [9,11],[10,12],[9,12],\n                              [16,14],[15,13],[16,13], [20,18],[19,17],[20,17], [24,22],[23,21],[24,21]]\n        for x in roll_ins_skip_keys:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # adjacent-row roll-outs:\n        roll_ins_adj_rows = [[1,6],[1,7],[1,8],[2,7],[2,8],[3,8], [5,2],[5,3],[5,4],[6,3],[6,4],[7,4],\n                             [5,10],[5,11],[5,12],[6,11],[6,12],[7,12], [9,6],[9,7],[9,8],[10,7],[10,8],[11,8],\n                             [16,19],[16,18],[16,17],[15,18],[15,17],[14,17], [20,15],[20,14],[20,13],[19,14],[19,13],[18,13],\n                             [20,23],[20,22],[20,21],[19,22],[19,21],[18,21], [24,19],[24,18],[24,17],[23,18],[23,17],[22,17]]\n        for x in roll_ins_adj_rows:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # upper<->lower row roll-outs:\n        roll_ins_skip_home = [[1,10],[1,11],[1,12],[2,11],[2,12],[3,12], [9,2],[9,3],[9,4],[10,3],[10,4],[11,4],\n                              [16,23],[16,22],[16,21],[15,22],[15,21],[14,21], [24,15],[24,14],[24,13],[23,14],[23,13],[22,13]]\n        for x in roll_ins_skip_home:\n            T[x[1]-1, x[0]-1] *= outward\n\n    # 9.  Avoid stretching shorter fingers up and longer fingers down.\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    if index_above < 1.0:\n        for x in [4]:\n            for y in [4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n        for x in [13]:\n            for y in [1,2,3,4,5,6,7,8,9,10,11,12,13,17,18,19,20,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n    if inside_top < 1.0:\n        for x in [4,13]:\n            for j in range(0,24):\n                T[x-1, j] *= inside_top\n                T[j, x-1] *= inside_top\n    if side_top < 1.0:\n        for x in [1,4,13,16]:\n            for j in range(0,24):\n                T[x-1, j] *= side_top\n                T[j, x-1] *= side_top\n    if side_above_1away < 1.0:\n        for x in [1]:\n            for y in [6,10]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [5]:\n            for y in [10]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [4]:\n            for y in [7,11]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [8]:\n            for y in [11]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [13]:\n            for y in [18,22]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [17]:\n            for y in [22]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [16]:\n            for y in [19,23]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [20]:\n            for y in [23]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n    if side_above_2away < 1.0:\n        for x in [1]:\n            for y in [7,11]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [5]:\n            for y in [11]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [4]:\n            for y in [6,10]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [8]:\n            for y in [10]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [13]:\n            for y in [19,23]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [17]:\n            for y in [23]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [16]:\n            for y in [18,22]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [20]:\n            for y in [22]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n    if side_above_3away < 1.0:\n        for x in [1]:\n            for y in [8,12]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [5]:\n            for y in [12]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [4]:\n            for y in [5,9]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [8]:\n            for y in [9]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [13]:\n            for y in [20,24]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [17]:\n            for y in [24]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [16]:\n            for y in [17,21]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [20]:\n            for y in [21]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n    if shorter_above < 1.0:\n        for x in [1]:\n            for y in [6,7,8,10,11,12]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [2]:\n            for y in [7,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [4]:\n            for y in [6,7,10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [5]:\n            for y in [10,11,12]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [6]:\n            for y in [11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [8]:\n            for y in [10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [16]:\n            for y in [17,18,19,21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [15]:\n            for y in [18,22]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [13]:\n            for y in [18,19,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [20]:\n            for y in [21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [19]:\n            for y in [22]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [17]:\n            for y in [22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n    if ring_above_middle < 1.0:\n        ring_above_middles =  [[2,7],[6,11],[2,11],\n                            [15,18],[19,22],[15,22]]\n        for x in ring_above_middles:\n            T[x[0]-1, x[1]-1] *= ring_above_middle\n            T[x[1]-1, x[0]-1] *= ring_above_middle\n\n    if middle_above_ring < 1.0:\n        middle_above_rings =  [[6,3],[10,7],[10,3],\n                            [19,14],[23,18],[23,14]]\n        for x in middle_above_rings:\n            T[x[0]-1, x[1]-1] *= middle_above_ring\n            T[x[1]-1, x[0]-1] *= middle_above_ring\n\n    # 10. Avoid using the same finger.\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    if same_finger < 1.0:\n        same_fingers = [[1,5],[5,9],[1,9], [2,6],[6,10],[2,10], [3,7],[7,11],[3,11], [4,8],[8,12],[4,12],\n                        [13,17],[17,21],[13,21], [14,18],[18,22],[14,22], [15,19],[19,23],[15,23], [16,20],[20,24],[16,24]] \n        for x in same_fingers:\n            T[x[0]-1, x[1]-1] *= same_finger\n            T[x[1]-1, x[0]-1] *= same_finger\n\n    # 11. Avoid the upper and lower rows.\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    if not_home_row < 1.0:\n        not_home_row_keys = [1,2,3,4, 9,10,11,12, 13,14,15,16, 21,22,23,24]\n        for x in not_home_row_keys:\n            for j in range(0,23):\n                T[x-1, j] *= not_home_row\n                T[j, x-1] *= not_home_row\n\n    # 12. Avoid skipping over the home row.\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    if skip_row_0away < 1.0:\n        skip_top = [1, 2, 3, 4, 13,14,15,16] \n        skip_bot = [9,10,11,12, 21,22,23,24] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_0away\n            T[y-1, x-1] *= skip_row_0away\n    if skip_row_1away < 1.0:\n        skip_top = [1, 2, 2, 3, 3, 4, 13,14,14,15,15,16] \n        skip_bot = [10,9,11,10,12,11, 22,21,23,22,24,23] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_1away\n            T[y-1, x-1] *= skip_row_1away\n    if skip_row_2away < 1.0:\n        skip_top = [1,  2,3, 4, 13,14,15,16] \n        skip_bot = [11,12,9,10, 23,24,21,22] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_2away\n            T[y-1, x-1] *= skip_row_2away\n    if skip_row_3away < 1.0:\n        skip_top = [1, 4, 13,16] \n        skip_bot = [12,9, 24,21] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_3away\n            T[y-1, x-1] *= skip_row_3away\n\n    Flow24x24 = T\n\n    # Normalize matrix with min-max scaling to a range with maximum = 1:\n    newMin = np.min(Flow24x24) / np.max(Flow24x24)\n    newMax = 1.0\n    Flow24x24 = newMin + (Flow24x24 - np.min(Flow24x24)) * (newMax - newMin) / (np.max(Flow24x24) - np.min(Flow24x24))\n\n    return Flow24x24\n\nFlow24x24 = create_24x24_flow_matrix(not_home_row, side_top, \n    side_above_3away, side_above_2away, side_above_1away, middle_above_ring, ring_above_middle, outward, \n    skip_row_3away, skip_row_2away, skip_row_1away, skip_row_0away, same_finger, lateral, same_hand, \n    shorter_above, adjacent_offset, inside_top, index_above)\n\n# Print:\nprint_matrix_info(matrix_data=Flow24x24, matrix_label=\"Flow24x24\", nkeys=24, nlines=30)\nheatmap(data=Flow24x24, title=\"Flow24x24\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n# Save:\nif print_output:\n    file = open(\"Flow24x24.txt\", \"w+\")\n    file.write(str(Flow24x24))\n    file.close()\n\n#    1  2  3  4   13 14 15 16  \n#    5  6  7  8   17 18 19 20 \n#    9 10 11 12   21 22 23 24\n```\n\n\n```python\n# Histogram\nsns_plot = sns.distplot(Flow24x24)\nif print_output:\n    sns_plot.figure.savefig(\"{0}_histogram.png\".format(\"Flow24x24\"))\n```\n\n#### 32 keys:\n\n         Left:             Right:\n     1  2  3  4 25   28 13 14 15 16 31 \n     5  6  7  8 26   29 17 18 19 20 32\n     9 10 11 12 27   30 21 22 23 24\n\n\n\n```python\n# Penalizing factors for 24 keys  (1 = no penalty; set to less than 1 to penalize):\n\n# Dexterity\nside_above_3away = 0.9     # index and little finger type two keys, one or more rows apart (same hand)\nside_above_2away = 0.81    # index finger types key a row or two above ring finger key, or\n                           # little finger types key a row or two above middle finger key (same hand)\nside_above_1away = 0.729   # index finger types key a row or two above middle finger key, or\n                           # little finger types key a row or two above ring finger key (same hand)\nmiddle_above_ring = 0.9    # middle finger types key a row or two above ring finger key (same hand)\nring_above_middle = 0.729  # ring finger types key a row or two above middle finger key (same hand)\nlateral = 0.9              # lateral movement of (index or little) finger outside of 8 vertical columns\n\n# Direction\noutward = 0.9              # outward roll of fingers from the index to little finger (same hand)\n\n# Distance\nskip_row_3away = 0.9       # index and little fingers type two keys that skip over home row (same hand)\n                           # (e.g., one on bottom row, the other on top row)\nskip_row_2away = 0.729     # little and middle or index and ring fingers type two keys that skip over home row (same hand)\nskip_row_1away = 0.59049   # little and ring or middle and index fingers type two keys that skip over home row (same hand)\n\n# Repetition\nskip_row_0away = 0.6561    # same finger types two keys that skip over home row\nsame_finger = 0.59049      # use same finger again for a different key\n\n\n# Unused or redundant parameters\nsame_hand = 1.0            # (addressed by splitting up the most frequent letters across left/right sides above)\nnot_home_row = 1.0         # at least one key not on home row\nside_top = 1.0             # index or little finger types top corner key\nshorter_above = 1.0        # (taken care of by side_above_[1,2,3]away parameters)\nadjacent_offset = 1.0      # (taken care of by side_above_1away, middle_above_ring, ring_above_middle parameters)\ninside_top = 1.0           # index finger types top corner key (taken care of by side_above_1away parameter)\nindex_above = 1.0          # index finger types top corner key (unless other bigram key is in the top row for the same hand)\n                           # (taken care of by side_above_[1,2,3]away parameters)\n```\n\n\n```python\ndef create_32x32_flow_matrix(not_home_row, side_top, side_above_3away, side_above_2away, side_above_1away, \n                             middle_above_ring, ring_above_middle, outward, skip_row_3away, \n                             skip_row_2away, skip_row_1away, skip_row_0away, same_finger, lateral, \n                             same_hand, shorter_above, adjacent_offset, inside_top, index_above):\n\n    all_32_keys = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, \n                   25,26,27, 28,29,30, 31,32]\n\n    # Create a matrix and multiply by flow factors that promote easy interkey transitions:\n    T = np.ones((32, 32))\n\n    if lateral < 1.0:\n        for x in all_32_keys:\n            for y in [25,26,27, 28,29,30, 31,32]:\n                T[x-1, y-1] *= lateral\n                T[y-1, x-1] *= lateral    \n\n    # 7.  Promote alternating between hands over uncomfortable transitions with the same hand.\n    if same_hand < 1.0:\n        for i in [1,2,3,4,5,6,7,8,9,10,11,12, 25,26,27]:\n            for j in [1,2,3,4,5,6,7,8,9,10,11,12, 25,26,27]:\n                T[i-1,j-1] *= same_hand\n        for i in [13,14,15,16,17,18,19,20,21,22,23,24, 28,29,30,31,32]:\n            for j in [13,14,15,16,17,18,19,20,21,22,23,24, 28,29,30,31,32]:\n                T[i-1,j-1] *= same_hand\n\n    # 8.  Promote little-to-index-finger roll-ins over index-to-little-finger outsward rolls.\n    # Penalize (index, little) finger lateral movements:\n    #  1  2  3  4 25   28 13 14 15 16 31 \n    #  5  6  7  8 26   29 17 18 19 20 32\n    #  9 10 11 12 27   30 21 22 23 24\n    if outward < 1.0:\n\n        # same-row roll-outs:\n        roll_ins = [[1,2],[2,3],[3,4], [5,6],[6,7],[7,8], [9,10],[10,11],[11,12],\n                    [4,25],[8,26],[12,27],\n                    [16,15],[15,14],[14,13], [20,19],[19,18],[18,17], [24,23],[23,22],[22,21],\n                    [13,28],[17,29],[21,30], [31,16],[32,20]]\n        for x in roll_ins:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # same-row roll-outs, skipping keys:\n        roll_ins_skip_keys = [[1,3],[2,4],[1,4], [5,7],[6,8],[5,8], [9,11],[10,12],[9,12],\n                              [1,25],[2,25],[3,25],\n                              [5,26],[6,26],[7,26],\n                              [9,27],[10,27],[11,27],\n                              [16,14],[15,13],[16,13], [20,18],[19,17],[20,17], [24,22],[23,21],[24,21],\n                              [16,28],[15,28],[14,28],\n                              [20,29],[19,29],[18,29],\n                              [24,30],[23,30],[22,30],\n                              [31,15],[31,14],[31,13],[31,28],\n                              [32,19],[32,18],[32,17],[32,29]]\n        for x in roll_ins_skip_keys:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # adjacent-row roll-outs:\n        #  1  2  3  4 25   28 13 14 15 16 31 \n        #  5  6  7  8 26   29 17 18 19 20 32\n        #  9 10 11 12 27   30 21 22 23 24\n        roll_ins_adj_rows = [[1,6],[1,7],[1,8],[2,7],[2,8],[3,8], \n                             [5,2],[5,3],[5,4],[6,3],[6,4],[7,4],\n                             [5,10],[5,11],[5,12],[6,11],[6,12],[7,12], \n                             [9,6],[9,7],[9,8],[10,7],[10,8],[11,8],\n                             [5,25],[6,25],[7,25],[8,25],\n                             [5,27],[6,27],[7,27],[8,27],\n                             [1,26],[2,26],[3,26],[4,26],\n                             [9,26],[10,26],[11,26],[12,26],\n                             [16,19],[16,18],[16,17],[15,18],[15,17],[14,17], \n                             [20,15],[20,14],[20,13],[19,14],[19,13],[18,13],\n                             [20,23],[20,22],[20,21],[19,22],[19,21],[18,21], \n                             [24,19],[24,18],[24,17],[23,18],[23,17],[22,17],\n                             [16,29],[15,29],[14,29],[13,29],\n                             [24,29],[23,29],[22,29],[21,29],\n                             [20,28],[19,28],[18,28],[17,28],\n                             [20,30],[19,30],[18,30],[17,30],\n                             [31,20],[31,19],[31,18],[31,17],[31,29],\n                             [32,16],[32,15],[32,14],[32,13],[32,28],\n                             [32,24],[32,23],[32,22],[32,21],[32,30]]\n        for x in roll_ins_adj_rows:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # upper<->lower row roll-outs:\n        roll_ins_skip_home = [[1,10],[1,11],[1,12],[1,27],[2,11],[2,12],[2,27],[3,12],[3,27],[4,27], \n                              [9,2],[9,3],[9,4],[9,25],[10,3],[10,4],[10,25],[11,4],[11,25],[12,25],\n                              [16,23],[16,22],[16,21],[16,30],[15,22],[15,21],[15,30],[14,21],[14,30],[13,30],\n                              [24,15],[24,14],[24,13],[24,28],[23,14],[23,13],[23,28],[22,13],[22,28],[21,28],\n                              [31,24],[31,23],[31,22],[31,21],[31,30]]\n        for x in roll_ins_skip_home:\n            T[x[1]-1, x[0]-1] *= outward\n\n    # 9.  Avoid stretching shorter fingers up and longer fingers down.\n    #  1  2  3  4 25   28 13 14 15 16 31 \n    #  5  6  7  8 26   29 17 18 19 20 32\n    #  9 10 11 12 27   30 21 22 23 24\n    if index_above < 1.0:\n        for x in [4]:\n            for y in [4,5,6,7,8,26,9,10,11,12,27,28,13,14,15,16,31,29,17,18,19,20,32,30,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n        for x in [25]:\n            for y in [25,5,6,7,8,26,9,10,11,12,27,28,13,14,15,16,31,29,17,18,19,20,32,30,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n        for x in [13]:\n            for y in [1,2,3,4,25,5,6,7,8,26,9,10,11,12,27,13,29,17,18,19,20,32,30,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n        for x in [28]:\n            for y in [1,2,3,4,25,5,6,7,8,26,9,10,11,12,27,28,29,17,18,19,20,32,30,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n    if inside_top < 1.0:\n        for x in [4,25,28,13]:\n            for j in range(0,32):\n                T[x-1, j] *= inside_top\n                T[j, x-1] *= inside_top\n    if side_top < 1.0:\n        for x in [1,4,25,28,13,16,31]:\n            for j in range(0,32):\n                T[x-1, j] *= side_top\n                T[j, x-1] *= side_top\n    if side_above_1away < 1.0:\n        for x in [1]:\n            for y in [6,10]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [5]:\n            for y in [10]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [4,25]:\n            for y in [7,11]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [8,26]:\n            for y in [11]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [13,28]:\n            for y in [18,22]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [17,29]:\n            for y in [22]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [16,31]:\n            for y in [19,23]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [20,32]:\n            for y in [23]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n    if side_above_2away < 1.0:\n        for x in [1]:\n            for y in [7,11]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [5]:\n            for y in [11]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [4,25]:\n            for y in [6,10]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [8,26]:\n            for y in [10]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [13,28]:\n            for y in [19,23]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [17,29]:\n            for y in [23]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [16,31]:\n            for y in [18,22]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [20,32]:\n            for y in [22]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n    if side_above_3away < 1.0:\n        for x in [1]:\n            for y in [8,12,26,27]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [5]:\n            for y in [12,27]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [4,25]:\n            for y in [5,9]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [8,26]:\n            for y in [9]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [13,28]:\n            for y in [20,24,32]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [17,29]:\n            for y in [24]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [16,31]:\n            for y in [17,21,29,30]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [20,32]:\n            for y in [21,30]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n\n\n    #  1  2  3  4 25   28 13 14 15 16 31 \n    #  5  6  7  8 26   29 17 18 19 20 32\n    #  9 10 11 12 27   30 21 22 23 24\n    if shorter_above < 1.0:\n        for x in [1]:\n            for y in [6,7,8,26,10,11,12,27]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [2]:\n            for y in [7,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [4]:\n            for y in [6,7,10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [25]:\n            for y in [6,7,10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [5]:\n            for y in [10,11,12,27]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [6]:\n            for y in [11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [8]:\n            for y in [10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [26]:\n            for y in [10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [16]:\n            for y in [29,17,18,19,30,21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [31]:\n            for y in [29,17,18,19,30,21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [15]:\n            for y in [18,22]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [13]:\n            for y in [18,19,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [28]:\n            for y in [18,19,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [20]:\n            for y in [30,21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [32]:\n            for y in [30,21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [19]:\n            for y in [22]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [17]:\n            for y in [22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [29]:\n            for y in [22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n    if ring_above_middle < 1.0:\n        ring_above_middles =  [[2,7],[6,11],[2,11],\n                            [15,18],[19,22],[15,22]]\n        for x in ring_above_middles:\n            T[x[0]-1, x[1]-1] *= ring_above_middle\n            T[x[1]-1, x[0]-1] *= ring_above_middle\n\n    if middle_above_ring < 1.0:\n        middle_above_rings =  [[6,3],[10,7],[10,3],\n                            [19,14],[23,18],[23,14]]\n        for x in middle_above_rings:\n            T[x[0]-1, x[1]-1] *= middle_above_ring\n            T[x[1]-1, x[0]-1] *= middle_above_ring\n\n    # 10. Avoid using the same finger.\n    #  1  2  3  4 25   28 13 14 15 16 31 \n    #  5  6  7  8 26   29 17 18 19 20 32\n    #  9 10 11 12 27   30 21 22 23 24\n    if same_finger < 1.0:\n        same_fingers = [[1,5],[5,9],[1,9], [2,6],[6,10],[2,10], \n                        [3,7],[7,11],[3,11], [4,8],[8,12],[4,12],\n                        [25,26],[26,27],[25,27], [28,29],[29,30],[28,30], [31,32],\n                        [4,25],[4,26],[4,27], [8,25],[8,26],[8,27], [12,25],[12,26],[12,27],\n                        [13,28],[13,29],[13,30], [17,28],[17,29],[17,30], [21,28],[21,29],[21,30],\n                        [31,16],[31,20],[31,24], [32,16],[32,20],[32,24],\n                        [13,17],[17,21],[13,21], [14,18],[18,22],[14,22], \n                        [15,19],[19,23],[15,23], [16,20],[20,24],[16,24]] \n        for x in same_fingers:\n            T[x[0]-1, x[1]-1] *= same_finger\n            T[x[1]-1, x[0]-1] *= same_finger\n\n    # 11. Avoid the upper and lower rows.\n    if not_home_row < 1.0:\n        not_home_row_keys = [1,2,3,4,25, 9,10,11,12,27, 28,13,14,15,16,31, 30,21,22,23,24]\n        for x in not_home_row_keys:\n            for j in range(0,32):\n                T[x-1, j] *= not_home_row\n                T[j, x-1] *= not_home_row\n                \n    # 12. Avoid skipping over the home row.\n    #  1  2  3  4 25   28 13 14 15 16 31 \n    #  5  6  7  8 26   29 17 18 19 20 32\n    #  9 10 11 12 27   30 21 22 23 24\n    if skip_row_0away < 1.0:\n        skip_top = [1, 2, 3, 4, 4,25,25, 28,28,13,13,14,15,16,31] \n        skip_bot = [9,10,11,12,27,12,27, 30,21,30,21,22,23,24,24] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_0away\n            T[y-1, x-1] *= skip_row_0away\n    if skip_row_1away < 1.0:\n        skip_top = [1, 2, 2, 3, 3, 4, 4,25, 28,13,13,14,14,15,15,16,31] \n        skip_bot = [10,9,11,10,12,11,27,11, 22,30,22,21,23,22,24,23,23] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_1away\n            T[y-1, x-1] *= skip_row_1away\n    if skip_row_2away < 1.0:\n        skip_top = [1,  2,3, 4,25, 28,13,14,15,16,31] \n        skip_bot = [11,12,9,10,10, 23,23,24,21,22,22] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_2away\n            T[y-1, x-1] *= skip_row_2away\n    if skip_row_3away < 1.0:\n        skip_top = [1, 4,25, 28,13,16,16,31,31] \n        skip_bot = [12,9, 9, 24,24,21,30,21,30] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_3away\n            T[y-1, x-1] *= skip_row_3away\n                \n    Flow32x32 = T\n\n    # Normalize matrix with min-max scaling to a range with maximum = 1:\n    newMin = np.min(Flow32x32) / np.max(Flow32x32)\n    newMax = 1.0\n    Flow32x32 = newMin + (Flow32x32 - np.min(Flow32x32)) * (newMax - newMin) / (np.max(Flow32x32) - np.min(Flow32x32))\n\n    return Flow32x32\n\nFlow32x32 = create_32x32_flow_matrix(not_home_row, side_top, \n    side_above_3away, side_above_2away, side_above_1away, middle_above_ring, ring_above_middle, outward, \n    skip_row_3away, skip_row_2away, skip_row_1away, skip_row_0away, same_finger, lateral, same_hand, \n    shorter_above, adjacent_offset, inside_top, index_above)\n\n# Print:\nprint_matrix_info(matrix_data=Flow32x32, matrix_label=\"Flow32x32\", nkeys=32, nlines=30)\nheatmap(data=Flow32x32, title=\"Flow32x32\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n# Save:\nif print_output:\n    file = open(\"Flow32x32.txt\", \"w+\")\n    file.write(str(Flow32x32))\n    file.close()\n\n#  1  2  3  4 25   28 13 14 15 16 31 \n#  5  6  7  8 26   29 17 18 19 20 32\n#  9 10 11 12 27   30 21 22 23 24\n```\n\n\n```python\n# Histogram\nsns_plot = sns.distplot(Flow32x32)\nif print_output:\n    sns_plot.figure.savefig(\"{0}_histogram.png\".format(\"Flow32x32\"))\n```\n\n### Flow output\n\n        Left:            Right:\n     1  2  3  4       13 14 15 16 \n     5  6  7  8       17 18 19 20\n     9 10 11 12       21 22 23 24\n\n    Flow24x24 min = 0.387420489, max = 1.0\n    Flow24x24 key number pairs with minimum values:\n        2 -> 10        (0.387420489)\n        10 -> 1        (0.387420489)\n        3 -> 11        (0.387420489)\n        10 -> 2        (0.387420489)\n        14 -> 22        (0.387420489)\n        24 -> 16        (0.387420489)\n        15 -> 23        (0.387420489)\n        13 -> 21        (0.387420489)\n        16 -> 24        (0.387420489)\n        21 -> 13        (0.387420489)\n        4 -> 11        (0.387420489)\n        13 -> 22        (0.387420489)\n        1 -> 9        (0.387420489)\n        4 -> 12        (0.387420489)\n        22 -> 15        (0.387420489)\n        22 -> 14        (0.387420489)\n        9 -> 1        (0.387420489)\n        12 -> 4        (0.387420489)\n        11 -> 2        (0.387420489)\n        11 -> 3        (0.387420489)\n        23 -> 15        (0.387420489)\n        23 -> 16        (0.387420489)\n        11 -> 4        (0.43046720999999993)\n        2 -> 11        (0.43046720999999993)\n        1 -> 10        (0.43046720999999993)\n        22 -> 13        (0.43046720999999993)\n        16 -> 23        (0.43046720999999993)\n        15 -> 22        (0.43046720999999993)\n        3 -> 10        (0.4782969)\n        14 -> 23        (0.4782969)\n    Flow24x24 key number pairs with maximum values:\n        24 -> 24        (1.0)\n        8 -> 15        (1.0)\n        10 -> 12        (1.0)\n        10 -> 13        (1.0)\n        10 -> 14        (1.0)\n        10 -> 15        (1.0)\n        10 -> 16        (1.0)\n        10 -> 17        (1.0)\n        10 -> 18        (1.0)\n        10 -> 19        (1.0)\n        10 -> 20        (1.0)\n        10 -> 21        (1.0)\n        10 -> 22        (1.0)\n        10 -> 23        (1.0)\n        10 -> 24        (1.0)\n        11 -> 11        (1.0)\n        11 -> 12        (1.0)\n        11 -> 13        (1.0)\n        11 -> 14        (1.0)\n        11 -> 15        (1.0)\n        11 -> 16        (1.0)\n        11 -> 17        (1.0)\n        11 -> 18        (1.0)\n        11 -> 19        (1.0)\n        11 -> 20        (1.0)\n        11 -> 21        (1.0)\n        11 -> 22        (1.0)\n        10 -> 11        (1.0)\n        10 -> 10        (1.0)\n        9 -> 24        (1.0)\n        \n        Left:            Right:\n    1  2  3  4 25   28 13 14 15 16 31 \n    5  6  7  8 26   29 17 18 19 20 32\n    9 10 11 12 27   30 21 22 23 24    \n\n    Flow32x32 min = 0.18530201888518408, max = 1.0\n    Flow32x32 key number pairs with minimum values:\n        30 -> 13        (0.18530201888518408)\n        27 -> 4        (0.18530201888518408)\n        4 -> 27        (0.205891132094649)\n        13 -> 30        (0.205891132094649)\n        30 -> 28        (0.31381059609)\n        28 -> 30        (0.31381059609)\n        24 -> 31        (0.31381059609)\n        28 -> 21        (0.31381059609)\n        25 -> 12        (0.31381059609)\n        27 -> 25        (0.31381059609)\n        25 -> 27        (0.31381059609)\n        25 -> 11        (0.34867844010000004)\n        31 -> 24        (0.34867844010000004)\n        23 -> 31        (0.34867844010000004)\n        12 -> 25        (0.34867844010000004)\n        28 -> 22        (0.34867844010000004)\n        21 -> 28        (0.34867844010000004)\n        4 -> 11        (0.387420489)\n        2 -> 10        (0.387420489)\n        24 -> 16        (0.387420489)\n        23 -> 16        (0.387420489)\n        23 -> 15        (0.387420489)\n        22 -> 28        (0.387420489)\n        22 -> 15        (0.387420489)\n        22 -> 14        (0.387420489)\n        31 -> 23        (0.387420489)\n        4 -> 12        (0.387420489)\n        3 -> 11        (0.387420489)\n        10 -> 2        (0.387420489)\n        1 -> 9        (0.387420489)\n    Flow32x32 key number pairs with maximum values:\n        1 -> 1        (1.0)\n        24 -> 4        (1.0)\n        23 -> 23        (1.0)\n        9 -> 21        (1.0)\n        9 -> 22        (1.0)\n        9 -> 23        (1.0)\n        17 -> 17        (1.0)\n        7 -> 8        (1.0)\n        7 -> 7        (1.0)\n        24 -> 1        (1.0)\n        24 -> 2        (1.0)\n        24 -> 3        (1.0)\n        24 -> 5        (1.0)\n        23 -> 21        (1.0)\n        24 -> 6        (1.0)\n        24 -> 7        (1.0)\n        24 -> 8        (1.0)\n        24 -> 9        (1.0)\n        24 -> 10        (1.0)\n        24 -> 11        (1.0)\n        24 -> 12        (1.0)\n        9 -> 24        (1.0)\n        17 -> 12        (1.0)\n        17 -> 11        (1.0)\n        23 -> 22        (1.0)\n        7 -> 12        (1.0)\n        16 -> 2        (1.0)\n        23 -> 7        (1.0)\n        7 -> 22        (1.0)\n        7 -> 21        (1.0)\n\n## Combine Strength and Flow matrices  <a name=\"strengthflow\">\n\n\n```python\n# 24 keys:\nFactors24x24 = Flow24x24\nif apply_strength:\n    Factors24x24 = Strength24x24 * Factors24x24\n\n# Print:\nprint_matrix_info(matrix_data=Factors24x24, matrix_label=\"Factors24x24\", nkeys=24, nlines=30)\nheatmap(data=Factors24x24, title=\"Factors24x24\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n# Save:\nif print_output:\n    file = open(\"Factors24x24.txt\", \"w+\")\n    file.write(str(Factors24x24))\n    file.close()\n```\n\n\n```python\n# Histogram\nsns_plot = sns.distplot(Factors24x24)\nif print_output:\n    sns_plot.figure.savefig(\"{0}_histogram.png\".format(\"Factors24x24\"))\n```\n\n\n```python\n# 32 keys:\nFactors32x32 = Flow32x32\nif apply_strength:\n    Factors32x32 = Strength32x32 * Factors32x32\n\n# Print:\nprint_matrix_info(matrix_data=Factors32x32, matrix_label=\"Factors32x32\", nkeys=32, nlines=30)\nheatmap(data=Factors32x32, title=\"Factors32x32\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n# Save:\nif print_output:\n    file = open(\"Factors32x32.txt\", \"w+\")\n    file.write(str(Factors32x32))\n    file.close()\n```\n\n\n```python\n# Histogram\nsns_plot = sns.distplot(Factors32x32)\nif print_output:\n    sns_plot.figure.savefig(\"{0}_histogram.png\".format(\"Factors32x32\"))\n```\n\n### Combined output\n\n        Left:            Right:\n     1  2  3  4       13 14 15 16 \n     5  6  7  8       17 18 19 20\n     9 10 11 12       21 22 23 24\n\n    Factors24x24 min = 0.3486784401, max = 1.0\n    Factors24x24 key number pairs with minimum values:\n        9 -> 1        (0.3486784401)\n        1 -> 9        (0.3486784401)\n        24 -> 16        (0.3486784401)\n        16 -> 24        (0.3486784401)\n        10 -> 1        (0.3553837947173077)\n        23 -> 16        (0.3553837947173077)\n        2 -> 10        (0.3620891493346154)\n        23 -> 15        (0.3620891493346154)\n        15 -> 23        (0.3620891493346154)\n        10 -> 2        (0.3620891493346154)\n        22 -> 15        (0.3747548191673077)\n        11 -> 2        (0.3747548191673077)\n        21 -> 13        (0.37997009498076917)\n        12 -> 4        (0.37997009498076917)\n        13 -> 21        (0.37997009498076917)\n        4 -> 12        (0.37997009498076917)\n        13 -> 22        (0.3836952919903846)\n        4 -> 11        (0.3836952919903846)\n        22 -> 14        (0.387420489)\n        14 -> 22        (0.387420489)\n        11 -> 3        (0.387420489)\n        3 -> 11        (0.387420489)\n        16 -> 23        (0.39487088301923073)\n        1 -> 10        (0.39487088301923073)\n        15 -> 22        (0.4163942435192307)\n        2 -> 11        (0.4163942435192307)\n        11 -> 4        (0.4263281022115384)\n        22 -> 13        (0.4263281022115384)\n        3 -> 10        (0.4626602705769231)\n        14 -> 23        (0.4626602705769231)\n    Factors24x24 key number pairs with maximum values:\n        18 -> 7        (1.0)\n        14 -> 11        (1.0)\n        14 -> 7        (1.0)\n        11 -> 14        (1.0)\n        14 -> 3        (1.0)\n        11 -> 18        (1.0)\n        3 -> 22        (1.0)\n        3 -> 18        (1.0)\n        11 -> 22        (1.0)\n        22 -> 22        (1.0)\n        18 -> 3        (1.0)\n        22 -> 11        (1.0)\n        18 -> 11        (1.0)\n        22 -> 7        (1.0)\n        22 -> 3        (1.0)\n        18 -> 18        (1.0)\n        3 -> 3        (1.0)\n        11 -> 11        (1.0)\n        3 -> 14        (1.0)\n        7 -> 7        (1.0)\n        14 -> 14        (1.0)\n        7 -> 14        (1.0)\n        7 -> 22        (1.0)\n        7 -> 18        (1.0)\n        21 -> 11        (0.9903846153846154)\n        22 -> 21        (0.9903846153846154)\n        8 -> 18        (0.9903846153846154)\n        18 -> 4        (0.9903846153846154)\n        21 -> 7        (0.9903846153846154)\n        18 -> 8        (0.9903846153846154)\n        \n         Left:             Right:\n     1  2  3  4 25   28 13 14 15 16 31 \n     5  6  7  8 26   29 17 18 19 20 32\n     9 10 11 12 27   30 21 22 23 24\n\n    Factors32x32 min = 0.17745023842394747, max = 1.0\n    Factors32x32 key number pairs with minimum values:\n        30 -> 13        (0.17745023842394747)\n        27 -> 4        (0.17745023842394747)\n        4 -> 27        (0.19716693158216386)\n        13 -> 30        (0.19716693158216386)\n        24 -> 31        (0.24466588847694917)\n        31 -> 24        (0.2718509871966102)\n        23 -> 31        (0.28514804635296614)\n        27 -> 25        (0.3005135369336441)\n        30 -> 28        (0.3005135369336441)\n        25 -> 27        (0.3005135369336441)\n        28 -> 30        (0.3005135369336441)\n        25 -> 12        (0.3005135369336441)\n        28 -> 21        (0.3005135369336441)\n        1 -> 9        (0.302056652440678)\n        16 -> 24        (0.302056652440678)\n        9 -> 1        (0.302056652440678)\n        24 -> 16        (0.302056652440678)\n        10 -> 1        (0.3168311626144068)\n        23 -> 16        (0.3168311626144068)\n        31 -> 23        (0.3168311626144068)\n        2 -> 10        (0.3316056727881356)\n        10 -> 2        (0.3316056727881356)\n        23 -> 15        (0.3316056727881356)\n        15 -> 23        (0.3316056727881356)\n        21 -> 28        (0.3339039299262712)\n        12 -> 25        (0.3339039299262712)\n        28 -> 22        (0.34129118501313566)\n        25 -> 11        (0.34129118501313566)\n        16 -> 23        (0.3520346251271186)\n        1 -> 10        (0.3520346251271186)\n    Factors32x32 key number pairs with maximum values:\n        14 -> 11        (1.0)\n        3 -> 18        (1.0)\n        11 -> 14        (1.0)\n        11 -> 11        (1.0)\n        18 -> 3        (1.0)\n        14 -> 14        (1.0)\n        18 -> 7        (1.0)\n        7 -> 22        (1.0)\n        18 -> 11        (1.0)\n        22 -> 11        (1.0)\n        22 -> 22        (1.0)\n        18 -> 18        (1.0)\n        14 -> 7        (1.0)\n        7 -> 18        (1.0)\n        3 -> 22        (1.0)\n        22 -> 7        (1.0)\n        11 -> 22        (1.0)\n        3 -> 3        (1.0)\n        3 -> 14        (1.0)\n        7 -> 14        (1.0)\n        7 -> 7        (1.0)\n        22 -> 3        (1.0)\n        14 -> 3        (1.0)\n        11 -> 18        (1.0)\n        3 -> 21        (0.978813559322034)\n        8 -> 18        (0.978813559322034)\n        8 -> 22        (0.978813559322034)\n        17 -> 11        (0.978813559322034)\n        13 -> 3        (0.978813559322034)\n        11 -> 17        (0.978813559322034)\n\n## Four steps\n\nWe will assign letters to keys by choosing the arrangement with the highest score according to our scoring model. However, there are over four hundred septillion, or four hundred trillion trillion (26! = 403,291,461,126,605,635,584,000,000, or 4.032914611 E+26) possible arrangements of 26 letters (24! = 6.204484017 E+23), so we will arrange the letters in four steps, based on ergonomics principles. These consist of (Step 1) assigning the eight most frequent letters to different keys, optimizing assignment of the remaining (Step 2) eight most frequent letters, and (Step 3) eight least frequent letters (besides Z and Q), and (Step 4) exchanging letters. \n\n## Step 1: Define the shape of the key layout to minimize lateral finger movements<a name=\"step1\">\n\nWe will assign 24 letters to 8 columns of keys separated by two middle columns reserved for punctuation. These 8 columns require no lateral finger movements when touch typing, since there is one column per finger. The most comfortable keys include the left and right home rows (keys 5-8 and 17-20), the top-center keys (2,3 and 14,15) that allow the longer middle and ring fingers to uncurl upwards, as well as the bottom corner keys (9,12 and 21,24) that allow the shorter fingers to curl downwards. We will assign the two least frequent letters, Z and Q (or J), to the two hardest-to-reach keys lying outside the 24-key columns in the upper right (25 and 26):\n\n        Left:            Right:\n     1  2  3  4       13 14 15 16 25\n     5  6  7  8       17 18 19 20 26\n     9 10 11 12       21 22 23 24\n\nWe will consider the most comfortable keys to be those typed by either hand on the home row, by the ring and middle finger above the home row, and by the index and little finger below the home row, with a preference for the strongest (index and middle) fingers:\n    \n     -  2  3  -        - 14 15  -  \n     5  6  7  8       17 18 19 20  \n     9  -  - 12       21  -  - 24\n\n## Step 2: Arrange the most frequent letters based on comfort and bigram frequencies  <a name=\"step2\">\n\nIn prior experiments, all vowels consistently automatically clustered together. Below, we will arrange vowels on one side and the most frequent consonants to the other side to encourage balance and alternation across hands. Since aside from the letters Z and Q there is symmetry across left and right sides, we will decide later which side the vowels and which side the most frequent consonants should go.\n\n### Vowels\n    \n**E**, T, **A, O, I**, N, S, R, H, L, D, C, U, M, F, P, G, W, Y, B, V, K, X, J, Q, Z\n\nThe highest frequency bigrams that contain two vowels are listed below in bold, with more than 10 billion instances in Peter Norvig's analysis of Google data:\n\n**OU, IO, EA, IE**, AI, IA, EI, UE, UA, AU, UI, OI, EO, OA, OE \n    \n     OU  24,531,132,241\n     IO  23,542,263,265\n     EA  19,403,941,063\n     IE  10,845,731,320\n     AI   8,922,759,715\n     IA   8,072,199,471   \n     EI   5,169,898,489\n     UE   4,158,448,570       \n     UA   3,844,138,094   \n     AU   3,356,322,923\n     UI   2,852,182,384\n     OI   2,474,275,212\n     EO   2,044,268,477\n     OA   1,620,913,259\n     OE   1,089,254,517 \n   \nWe will assign the most frequent vowels with over 100 billion instances in Norvig's analysis (E,A,O,I) to four of the six most comfortable keys on the left side of the keyboard (keys 2,3,5,6,7,8). We will assign the letter E, the most frequent in the English language, to either of the strongest (index and middle) fingers on the home row, and assign the other three vowels such that (1) the home row keys typed by the index and middle fingers are not left vacant, and any top-frequency bigram (more than 10 billion instances in Norvig's analysis) (1) does not use the same finger and (2) reads from left to right (ex: EA, not AE) for ease of typing (roll-in from little to index finger vs. roll-out from index to little finger). These constraints lead to three arrangements of the four vowels:\n\n    - - O -    - - O -    - - - -    \n    - I E A    I - E A    I O E A\n    - - - -    - - - -    - - - -\n\n### Consonants\n\nThe top-frequency bigrams (more than 10 billion instances in Norvig's analysis) include: TH, ND, ST, NT, CH, NS, CT, TR, RS, NC, and RT (below 10 billion instances these bigrams start to occur in reverse, such as RT and TS): \n    \n    TH 100,272,945,963  3.56% \n    ND  38,129,777,631  1.35%\n    ST  29,704,461,829  1.05%\n    NT  29,359,771,944  1.04%\n    CH  16,854,985,236  0.60%\n    NS  14,350,320,288   \n    CT  12,997,849,406\n    TR  12,006,693,396       \n    RS  11,180,732,354   \n    NC  11,722,631,112\n    RT  10,198,055,461  \n    TS \t9,516,029,773\n    SH\t8,888,705,287\n    LD\t7,122,648,226\n    RD\t5,338,083,783\n    RN\t4,521,640,992\n    SC\t4,363,410,770\n    CR\t4,214,150,542\n    CL\t4,201,617,719\n    LS\t3,990,203,351\n    HT\t3,670,802,795\n    DS\t3,560,125,353\n    LT\t3,486,149,365\n    RC\t3,422,694,015\n    TL\t2,775,935,006\n    RL\t2,432,373,251\n    DR\t2,409,399,231\n    HR\t2,379,584,978\n    NL\t1,798,491,132\n    SL\t1,575,646,777\n\nOn the right side of the keyboard, we will assign the four most frequent consonants (with over 200 billion instances in Norvig's analysis: T, N, S, and R) to the four home row keys. We will assign the letter T, the most frequent consonant in the English language, to either of the strongest (index and middle) fingers on the home row, resulting in 12 possible sequences of the four consonants:\n\n    - - - -    - - - -    - - - -    - - - -    - - - -    - - - -\n    T N S R    T N R S    T R N S    T R S N    T S N R    T S R N\n    - - - -    - - - -    - - - -    - - - -    - - - -    - - - -\n    \n    - - - -    - - - -    - - - -    - - - -    - - - -    - - - -\n    N T S R    N T R S    R T N S    R T S N    S T N R    S T R N\n    - - - -    - - - -    - - - -    - - - -    - - - -    - - - -\n\nWe will then assign the next four most frequent consonants (H, L, D, and C), accounting for half of the alphabet, to comfortable keys that do not require the same finger to type a high-frequency bigram (greater than 1 billion instances). This forces C to occupy a vacant key on or above the left home row, H to occupy the key below the right home row typed by the index finger (only when the right index finger types either R or N on the home row and not T or S), and L and D to occupy the keys typed by the middle and ring fingers above the right home row (only when L is paired with N or R and not T or S, and only when D is paired with T). \n    \nThe resulting eight initial layouts, each with 11 unassigned keys, are represented below, with \"NR\" representing a key that could be assigned either the letter N or R, and three \"+\" signs to indicate more comfortable positions than the eight \"-\" signs:\n    \n        Left           Right\n    \n     -  +  O  U     -  D   L  -\n     C  I  E  A    NR  T  NR  S\n     +  -  -  -     H  -   -  +\n    \n     -  +  O  U     -  D   L  -\n     I  C  E  A    NR  T  NR  S\n     +  -  -  -     H  -   -  +\n    \n     -  D  O  U     -  +   L  -\n     I  C  E  A    NR  T  NR  S\n     +  -  -  -     H  -   -  +\n    \n     -  C  O  U     -  +   L  -\n     I  D  E  A    NR  T  NR  S\n     +  -  -  -     H  -   -  +\n\nSince we want to assign the most frequent remaining consonants (M, F, P,...) to the most comfortable remaining positions, we need to match higher frequency consonants with the letters I, C, S, and T that form low-frequency bigrams. The only remaining consonants that form low-frequency bigrams when combined with the letter I are the letters Y and the lowest frequency letters (X, J, Q, and Z). The letter F, lower frequency letters W and V, and the same lowest frequency letters form low-frequency bigrams with the letter S. We will therefore assign Y to the vacancy above or below I, and F to the vacancy below S. The letters M, G, B, V, K, J, Q, and Z (in descending order of frequency) form low-frequency bigrams with the letter T, so we will assign M (the most frequent remaining consonant) to the vacancy above T. All of the remaining consonants except for Y and K form low-frequency bigrams with the letter C, so we will not commit to a letter assignment to any vacancy above or below C. The assignment of these three letters results in the following eight layouts:\n    \n     -  Y  O  U     -  D   L  -\n     C  I  E  A    NR  T  NR  S\n     +  -  -  -     H  -   -  F\n    \n     -  +  O  U     -  D   L  -\n     I  C  E  A    NR  T  NR  S\n     Y  -  -  -     H  -   -  F\n    \n     -  D  O  U     -  M   L  -\n     I  C  E  A    NR  T  NR  S\n     Y  -  -  -     H  -   -  F\n    \n     -  C  O  U     -  M   L  -\n     I  D  E  A    NR  T  NR  S\n     Y  -  -  -     H  -   -  F\n\n## Step 3: Optimize assignment of the remaining letters <a name=\"step3\">\n    \nWe want to assign letters to the nine unassigned keys in each of the above eight layouts based on our scoring model. That would mean scoring all 362,880 (9!) possible arrangements for each layout and choosing the arrangement with the highest score.\n\n\n```python\n\"\"\"\nNOTE: This procedure takes hours.\n\n     -  Y  O  U     -  D   L  -\n     C  I  E  A    NR  T  NR  S\n     +  -  -  -     H  -   -  F\n    \n     -  +  O  U     -  D   L  -\n     I  C  E  A    NR  T  NR  S\n     Y  -  -  -     H  -   -  F\n    \n     -  D  O  U     -  -   L  -\n     I  C  E  A    NR  T  NR  S\n     Y  -  -  -     H  -   -  F\n    \n     -  C  O  U     -  -   L  -\n     I  D  E  A    NR  T  NR  S\n     Y  -  -  -     H  -   -  F\n    \n\"\"\"\nfixed_letter_lists = [\n    ['Y','O','U', 'C','I','E','A',      'D','L', 'N','T','R','S', 'H','F'],\n    ['Y','O','U', 'C','I','E','A',      'D','L', 'R','T','N','S', 'H','F'],\n    [    'O','U', 'I','C','E','A', 'Y', 'D','L', 'N','T','R','S', 'H','F'],\n    [    'O','U', 'I','C','E','A', 'Y', 'D','L', 'R','T','N','S', 'H','F'],\n    ['D','O','U', 'I','C','E','A', 'Y',     'L', 'N','T','R','S', 'H','F'],\n    ['D','O','U', 'I','C','E','A', 'Y',     'L', 'R','T','N','S', 'H','F'],\n    ['C','O','U', 'I','D','E','A', 'Y',     'L', 'N','T','R','S', 'H','F'],\n    ['C','O','U', 'I','D','E','A', 'Y',     'L', 'R','T','N','S', 'H','F']]\n\n# Indices for step 1:\n#     -  0  1  2        -  7  8  -\n#     3  4  5  6        9 10 11 12\n#     -  -  -  -       13  -  - 14\nfixed_letter_index_lists = [[1,2,3, 4,5,6,7,    13,14, 16,17,18,19, 20,23],\n                            [1,2,3, 4,5,6,7,    13,14, 16,17,18,19, 20,23],\n                            [  2,3, 4,5,6,7, 8, 13,14, 16,17,18,19, 20,23],\n                            [  2,3, 4,5,6,7, 8, 13,14, 16,17,18,19, 20,23],\n                            [1,2,3, 4,5,6,7, 8,    14, 16,17,18,19, 20,23],\n                            [1,2,3, 4,5,6,7, 8,    14, 16,17,18,19, 20,23],\n                            [1,2,3, 4,5,6,7, 8,    14, 16,17,18,19, 20,23],\n                            [1,2,3, 4,5,6,7, 8,    14, 16,17,18,19, 20,23]]\nopen_letter_index_lists  = [[0,   8,9,10,11, 12,15,    21,22],\n                            [0,   8,9,10,11, 12,15,    21,22],\n                            [0,1,   9,10,11, 12,15,    21,22],\n                            [0,1,   9,10,11, 12,15,    21,22],\n                            [0,     9,10,11, 12,13,15, 21,22],\n                            [0,     9,10,11, 12,13,15, 21,22],\n                            [0,     9,10,11, 12,13,15, 21,22],\n                            [0,     9,10,11, 12,13,15, 21,22]]\n\n# Loop through initialized layouts with assigned vowels and consonants \ntop_layouts = []\nnlists = len(fixed_letter_lists)\nfor ilist, fixed_letters in enumerate(fixed_letter_lists):\n  if ilist in [0,1]:\n    fixed_letter_indices = fixed_letter_index_lists[ilist]\n    open_letter_indices = open_letter_index_lists[ilist]\n    #fixed_letter_indices2 = fixed_letter_index_lists2[ilist]\n\n    print('Layout {0}'.format(nlists))\n    print(*fixed_letters)\n\n    # Optimize remaining letters\n    top_permutation1, letter_permutations1, scores1 = permute_optimize_keys(fixed_letters, fixed_letter_indices, \n                                                        open_letter_indices, letters24, keys24, Factors24x24, \n                                                        bigrams, bigram_frequencies, verbose=True, ntop=0)\n\n    # Further optimize layouts by exchanging more letters\n    #top_permutation2 = exchange_letters(top_permutation1, fixed_letter_indices2, letters24, keys24, \n    #                                    Factors24x24, bigrams, bigram_frequencies, verbose=True, ntop=0)\n\n    top_layouts.append(top_permutation1)\n\n```\n\n    Layout 8\n    Y O U C I E A D L N T R S H F\n    Layout 8\n    Y O U C I E A D L R T N S H F\n\n\n### Import optimized layouts\n\n\n```python\nload_layouts = True\nprint_layouts = False\n\nif load_layouts:\n    top_layouts = [\n        ['P','Y','O','U','C','I','E','A','G','K','J','X','M','D','L','B','N','T','R','S','H','V','W','F'],\n        ['P','Y','O','U','C','I','E','A','G','K','J','X','M','D','L','B','R','T','N','S','H','V','W','F'],\n        ['P','G','O','U','I','C','E','A','Y','K','J','X','M','D','L','B','N','T','R','S','H','V','W','F'],\n        ['P','G','O','U','I','C','E','A','Y','K','J','X','M','D','L','B','R','T','N','S','H','V','W','F'],\n        ['G','D','O','U','I','C','E','A','Y','X','J','K','M','P','L','B','N','T','R','S','H','V','W','F'],\n        ['G','D','O','U','I','C','E','A','Y','X','J','K','M','P','L','B','R','T','N','S','H','V','W','F'],\n        ['K','C','O','U','I','D','E','A','Y','X','J','G','M','P','L','B','N','T','R','S','H','V','W','F'],\n        ['K','C','O','U','I','D','E','A','Y','X','J','G','M','P','L','B','R','T','N','S','H','V','W','F']]\nif print_layouts:\n    print('Layouts:\\n')\n    for layout in top_layouts:\n        print(layout)\n        #print(*layout)\n```\n\n### Rank optimized layouts\n\n\n```python\nlayout_strings = []\nscores = []\nfor layout in top_layouts:\n    layout_string = ' '.join(layout)\n    score = score_layout(Factors24x24, layout, bigrams, bigram_frequencies, verbose=False)\n    #print('    {0}    {1}'.format(layout_string, score))\n    layout_strings.append(layout_string)\n    scores.append(score)\n\n# Establish which layouts are within a small difference of the top-scoring layout \n#    - half of the smallest difference between two flow penalties, ignoring strength: (0.9^9 - 0.9^10)/2\n#    - divided by the number of key pairs: 24^2\ndelta_flow = (0.9**8 - 0.9**9)\nfactor = ((24**2 - 1) + (1-delta_flow)) / (24**2)\nprint('    The smallest difference between two flow penalties: (0.9^8 - 0.9^9) = {0}'.format(delta_flow))\nprint('    ...divided by the number of key pairs (24^2) = {0}'.format(factor))\nscores_sorted, ranks_sorted, Isort = rank_within_epsilon(scores, factor, factor=True, verbose=False)\nlayouts_sorted = []\nlayout_strings_sorted = []\nfor i in Isort:\n    layouts_sorted.append(top_layouts[i])\n    layout_strings_sorted.append(layout_strings[i])\nprint('\\nRank:   Layout                                             Score\\n')\nfor i, rank in enumerate(ranks_sorted):\n    print('    {0}:  {1}    {2}'.format(rank, layout_strings_sorted[i], scores_sorted[i]))\n\nprint('\\nLayouts tied for first place, with letter frequencies:\\n')\nprint('Rank:   Layout                                             Score\\n')\nfirst_ranks = []\nfirst_layouts = []\nfirst_layout_strings = []\nfirst_scores = []\nfor i, rank in enumerate(ranks_sorted):\n    if rank == 1:\n        first_ranks.append(rank)\n        first_layouts.append(layout_strings_sorted[i])\n        first_layout_strings.append(layouts_sorted[i])\n        first_scores.append(scores_sorted[i])    \nIsort2 = np.argsort([-x for x in first_scores])\nfirst_ranks_sorted = []\nfirst_layouts_sorted = []\nfirst_layout_strings_sorted = []\nfirst_scores_sorted = []\nfor i in Isort2:\n    first_ranks_sorted.append(first_ranks[i])\n    first_layouts_sorted.append(first_layouts[i])\n    first_layout_strings_sorted.append(first_layout_strings[i])\n    first_scores_sorted.append(first_scores[i])\nfor i, first_layout in enumerate(first_layouts):\n    print('    {0}:  {1}    {2}'.format(first_ranks_sorted[i], \n                                        first_layout,  # first_layout_strings_sorted[i], \n                                        first_scores_sorted[i]))\n# Print layouts:\nfor i, layout_string in enumerate(first_layout_strings_sorted):\n    layout = first_layouts_sorted[i]\n    print('')\n    print_layout24(layout_string)\n    print('')\n    print_layout24_instances(layout_string, letters24, instances24, bigrams, bigram_frequencies)\n    print('')\n```\n\n        The smallest difference between two flow penalties: (0.9^8 - 0.9^9) = 0.04304672100000001\n        ...divided by the number of key pairs (24^2) = 0.999925266109375\n    \n    Rank:   Layout                                             Score\n    \n        1:  P Y O U C I E A G K J X M D L B R T N S H V W F    0.7077803780948864\n        1:  P Y O U C I E A G K J X M D L B N T R S H V W F    0.7077696228120799\n        2:  P G O U I C E A Y K J X M D L B R T N S H V W F    0.7076873763504207\n        2:  P G O U I C E A Y K J X M D L B N T R S H V W F    0.7076766210676143\n        3:  K C O U I D E A Y X J G M P L B R T N S H V W F    0.7075559555554859\n        3:  K C O U I D E A Y X J G M P L B N T R S H V W F    0.707511073547672\n        4:  G D O U I C E A Y X J K M P L B R T N S H V W F    0.707442288762278\n        4:  G D O U I C E A Y X J K M P L B N T R S H V W F    0.7073974067544642\n    \n    Layouts tied for first place, with letter frequencies:\n    \n    Rank:   Layout                                             Score\n    \n        1:  P Y O U C I E A G K J X M D L B R T N S H V W F    0.7077803780948864\n        1:  P Y O U C I E A G K J X M D L B N T R S H V W F    0.7077696228120799\n    \n        P Y O U  M D L B\n        C I E A  R T N S\n        G K J X  H V W F\n    \n         76  59 272  97   90 136 145  53\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  38  60  86\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     36557845858\n    \n    \n        P Y O U  M D L B\n        C I E A  N T R S\n        G K J X  H V W F\n    \n         76  59 272  97   90 136 145  53\n        119 270 445 287  258 331 224 232\n         67  19   6   8  180  38  60  86\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     30378108061\n    \n\n\n### Optimized layouts\n\nRanking factor:\n\n    The smallest difference between two flow penalties: (0.9^8 - 0.9^9) = 0.04304672100000001\n    ...divided by the number of key pairs (24^2) = 0.999925266109375\n\nRank:   Layout                                             Score\n\n    1:  P Y O U C I E A G K J X M D L B R T N S H V W F    0.7077803780536206\n    1:  P Y O U C I E A G K J X M D L B N T R S H V W F    0.7077696227710919\n    2:  P G O U I C E A Y K J X M D L B R T N S H V W F    0.7076873763091379\n    2:  P G O U I C E A Y K J X M D L B N T R S H V W F    0.7076766210266091\n    3:  K C O U I D E A Y X J G M P L B R T N S H V W F    0.7075559555141423\n    3:  K C O U I D E A Y X J G M P L B N T R S H V W F    0.7075110735066311\n    4:  G D O U I C E A Y X J K M P L B R T N S H V W F    0.707442288720322\n    4:  G D O U I C E A Y X J K M P L B N T R S H V W F    0.7073974067128108\n\n    P Y O U  M D L B     76  59 272  97   90 136 145  53\n    C I E A  R T N S    119 270 445 287  224 331 258 232\n    G K J X  H V W F     67  19   6   8  180  38  60  86\n\n    P Y O U  M D L B     76  59 272  97   90 136 145  53\n    C I E A  N T R S    119 270 445 287  258 331 224 232\n    G K J X  H V W F     67  19   6   8  180  38  60  86\n\n    Hand balance: left: 1.725T  right: 1.831T (6.09%)\n    Total same-finger bigram frequencies: 36,557,845,830 (1st), 30,378,108,025 (2nd)\n       \nThe two layouts tied for first place differ only by the sequence of consonants in the right home row. The first layout permits more inward rolls for high-frequency bigrams than the second (ND, NT, TR, and DR, but not RN). The second has fewer high-frequency same-finger bigrams (>15B vs. >24B, because the first has RM and WN), and shifts the greater load from the right ring to the stronger right index finger. \n\nFor comparison with prior (Engram) experiments, the layouts below were generated without the above constraints related to placement of letters L, D, or C, and optimized placement of 15 letters in two stages, rather than 9 letters in one stage. It did require the four-consonant sequence on the right home row to consist of three high-frequency bigrams (such as NSTR = NS + ST + TR) and so permits one more inward-rolling, high-frequency bigram (NS) than the second layout above. The top-scoring layouts from the above and below approaches are identical on the left side and differ by the positions of seven letters on the right side (M, L, N, S, V, W, and F). The second layout below is identical to Engram v2.0.\n\n    Rank                                                   Score\n    1:  P Y O U C I E A G K J X L D F B R T S N H M V W    0.7079134589554652\n    1:  B Y O U C I E A G X J K L D W V H T S N R M F P    0.7078676989043136\n    2:  J G O U I C E A B X Y K L D F V R T S N H M W P    0.7078208372363046\n    2:  B Y O U H I E A V K J X L D G F R T S N C M W P    0.7078164910125013\n    2:  J G O U I C E A B X Y K L D W V H T S N R M F P    0.7077802597858632\n    3:  P Y O U C I E A G K J X M L F B H T S R N D V W    0.707765513186795\n    3:  J P O U I H E A B K Y X L D G F R T S N C M V W    0.7077426951024633\n    4:  P G O U I C E A K X J Y M L F B H T S R N D V W    0.7076779754232723\n    5:  J P O U S I E A G K Y X M C W V H T N R D L F B    0.707608035505442\n    6:  J G U K I O E A P X Y F L D V B R T S N H M C W    0.707560090465515\n    6:  W Y O U R I E A G X J K L D C B H T S N M F V P    0.7075589351593826\n    6:  J G O U I S E A P X K Y M C W V H T N R D L F B    0.707549787929756\n    6:  J G U X I O E A W K Y F L D C B H T S N R M V P    0.7075212659110061\n    7:  J W O U I R E A G X K Y L D C B H T S N M F V P    0.7074562433695609\n    7:  J P O U I N E A B X K Y M C G V H T S R L D F W    0.7074435243752765\n    7:  J P O U N I E A B K Y X M C G V H T S R L D F W    0.707432984110794\n    7:  J G U K I O E A P X Y F M L B W H T S R N D V C    0.7074108195944783\n             \n    P Y O U  L D F B     76  59 272  97  145 136  86  53\n    C I E A  R T S N    119 270 445 287  224 331 232 258\n    G K J X  H M V W     67  19   6   8  180  90  38  60\n\n### Optional: rank variations of top-scoring layouts\n\nAs an alternative to simply choosing the top-scoring layout, we can generate variations of this layout and find those variants within a small difference of one another and select from among these variants. For this, we select keys to vary, compute scores for every combination of the letters assigned to these keys, and select among those that are tied for first place. Below we vary those keys with different letters in the two layouts tied for first place above and three additional letters assigned to uncomfortable keys.\n\n\n```python\nrank_variations = True\nif rank_variations:\n\n    #  P Y O U  M D L B\n    #  C I E A  R T N S\n    #  G K J X  H V W F\n\n    #  - Y O U  - D L -\n    #  C I E A  - T - S\n    #  G K J X  H - - -\n\n    #letters = ['P','Y','O','U','C','I','E','A','G','K','J','X','M','D','L','B','R','T','N','S','H','V','W','F']\n    fixed_letters = ['Y','O','U', 'C','I','E','A', 'G','K','J','X', 'D','L', 'T','S', 'H']\n    fixed_letter_indices = [1,2,3, 4,5,6,7, 8,9,10,11, 13,14, 17,19, 20]\n    open_letter_indices  = [0, 12,15, 16,18, 21,22,23]\n\n    top_permutation, letter_permutations, scores = permute_optimize_keys(fixed_letters, fixed_letter_indices, \n                                                        open_letter_indices, letters24, keys24, Factors24x24, \n                                                        bigrams, bigram_frequencies, verbose=False, ntop=0)\n    nletters = len(fixed_letter_indices) + len(open_letter_indices)\n    layout_variants = []\n    for ipermutation, letter_permutation in enumerate(letter_permutations):\n        letters = np.array(['E' for x in range(nletters)])  # KEEP to initialize!\n        for imove, open_letter_index in enumerate(open_letter_indices):\n            letters[open_letter_index] = letter_permutation[imove]\n        for ifixed, fixed_letter_index in enumerate(fixed_letter_indices):\n            letters[fixed_letter_index] = fixed_letters[ifixed]\n        layout_variants.append(letters)\n\n    layout_strings = []\n    for layout in layout_variants:\n        layout_string = ' '.join(layout)\n        layout_strings.append(layout_string)\n\n    scores_sorted, ranks_sorted, Isort = rank_within_epsilon(scores, factor, factor=True, verbose=False)\n    layouts_sorted = []\n    layout_strings_sorted = []\n    for i in Isort:\n        layouts_sorted.append(layout_strings[i])\n        layout_strings_sorted.append(layout_variants[i])\n\n    print('Rank:   Layout                                             Score\\n')\n    for i, rank in enumerate(ranks_sorted):\n        if rank == 1:\n            print('    {0}:  {1}    {2}'.format(rank, layouts_sorted[i], scores_sorted[i]))\n\n    # Print layouts:\n    Ifirst_place = []\n    layouts_first_place = []\n    layout_strings_first_place = []\n    for i, rank in enumerate(ranks_sorted):\n        if rank == 1:\n            layout_string = layout_strings_sorted[i]\n            layout = layouts_sorted[i]\n            print('')\n            print_layout24(layout_string)\n            print('')\n            print_layout24_instances(layout_string, letters24, instances24, bigrams, bigram_frequencies)\n            Ifirst_place.append(i)\n            layouts_first_place.append(layout)\n            layout_strings_first_place.append(layout_string)\n```\n\n    Rank:   Layout                                             Score\n    \n        1:  P Y O U C I E A G K J X M D L B R T N S H F V W    0.7077818057116185\n        1:  P Y O U C I E A G K J X M D L B R T N S H V W F    0.7077803780536207\n        1:  P Y O U C I E A G K J X F D L B R T N S H M V W    0.7077798033933657\n        1:  P Y O U C I E A G K J X M D L B R T N S H V F W    0.7077794525908389\n        1:  P Y O U C I E A G K J X V D L B R T N S H M W F    0.7077787741093243\n        1:  P Y O U C I E A G K J X V D L B R T N S H M F W    0.7077781057237986\n        1:  P Y O U C I E A G K J X M D L B R T N S H F W V    0.7077747150460763\n        1:  P Y O U C I E A G K J X M D L B R T N S H W V F    0.7077742244130669\n        1:  P Y O U C I E A G K J X F D L B R T N S H M W V    0.707772661556241\n        1:  P Y O U C I E A G K J X M D L B N T R S H V W F    0.7077696227710919\n        1:  P Y O U C I E A G K J X M D L B R T N S H W F V    0.7077661460024984\n        1:  P Y O U C I E A G K J X V D L B N T R S H M W F    0.7077596943431474\n        1:  P Y O U C I E A G K J X B D L F R T N S H M V W    0.7077592801213322\n        1:  P Y O U C I E A G K J X M D L B N T R S H W V F    0.707759191453331\n        1:  P Y O U C I E A G K J X V D L F R T N S H M W B    0.7077577907825605\n        1:  P Y O U C I E A G K J X F D L B N T R S H M W V    0.7077551748734543\n        1:  P Y O U C I E A G K J X F D L B N T R S H M V W    0.7077542134014241\n        1:  P Y O U C I E A G K J X B D L F R T N S H M W V    0.7077526034466854\n        1:  P Y O U C I E A G K J X B D L V R T N S H M W F    0.7077503203600539\n        1:  P Y O U C I E A G K J X V D L F R T N S H M B W    0.7077500948346779\n        1:  P Y O U C I E A G K J X B D L V R T N S H M F W    0.7077497507892488\n        1:  P Y O U C I E A G K J X F D L V R T N S H M W B    0.707749429250204\n        1:  P Y O U C I E A G K J X B D L V N T R S H M W F    0.7077478765448684\n        1:  P Y O U C I E A G K J X M D L B N T R S H F W V    0.7077477888266053\n        1:  P Y O U C I E A G K J X M D L B N T R S H F V W    0.707746776182993\n        1:  P Y O U C I E A G K J X F D L V N T R S H M W B    0.7077456965787586\n        1:  P Y O U C I E A G K J X F D L V R T N S H M B W    0.7077422593554563\n        1:  P Y O U C I E A G K J X V D L B R T N S H F M W    0.7077402962916755\n        1:  P Y O U C I E A G K J X F D L B R T N S H V M W    0.7077395224274426\n        1:  P Y O U C I E A G K J X M D L F R T N S H V W B    0.7077382228893154\n        1:  B Y O U C I E A G K J X M D L P R T N S H F V W    0.7077355553339657\n        1:  P Y O U C I E A G K J X M D L B N T R S H V F W    0.7077354301289264\n        1:  B Y O U C I E A G K J X M D L P R T N S H V W F    0.7077338112865781\n        1:  B Y O U C I E A G K J X M D L P R T N S H V F W    0.7077328900501446\n        1:  P Y O U C I E A G K J X V D L F N T R S H M W B    0.7077324321983025\n        1:  P Y O U C I E A G K J X M D L F R T N S H W V B    0.7077323473880455\n        1:  P Y O U C I E A G K J X V D L B R T N S H W M F    0.7077320798107325\n        1:  P Y O U C I E A G K J X B D L F R T N S H V M W    0.7077309803243578\n        1:  P Y O U C I E A G K J X B D L F N T R S H M W V    0.7077301268020774\n    \n        P Y O U  M D L B\n        C I E A  R T N S\n        G K J X  H F V W\n    \n         76  59 272  97   90 136 145  53\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  86  38  60\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     38857951315\n    \n        P Y O U  M D L B\n        C I E A  R T N S\n        G K J X  H V W F\n    \n         76  59 272  97   90 136 145  53\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  38  60  86\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     36557845830\n    \n        P Y O U  F D L B\n        C I E A  R T N S\n        G K J X  H M V W\n    \n         76  59 272  97   86 136 145  53\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  90  38  60\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     39209124821\n    \n        P Y O U  M D L B\n        C I E A  R T N S\n        G K J X  H V F W\n    \n         76  59 272  97   90 136 145  53\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  38  86  60\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     39665456634\n    \n        P Y O U  V D L B\n        C I E A  R T N S\n        G K J X  H M W F\n    \n         76  59 272  97   38 136 145  53\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  90  60  86\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     33876968307\n    \n        P Y O U  V D L B\n        C I E A  R T N S\n        G K J X  H M F W\n    \n         76  59 272  97   38 136 145  53\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  90  86  60\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     36984579110\n    \n        P Y O U  M D L B\n        C I E A  R T N S\n        G K J X  H F W V\n    \n         76  59 272  97   90 136 145  53\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  86  60  38\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     38038787387\n    \n        P Y O U  M D L B\n        C I E A  R T N S\n        G K J X  H W V F\n    \n         76  59 272  97   90 136 145  53\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  60  38  86\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     38100586465\n    \n        P Y O U  F D L B\n        C I E A  R T N S\n        G K J X  H M W V\n    \n         76  59 272  97   86 136 145  53\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  90  60  38\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     38389960893\n    \n        P Y O U  M D L B\n        C I E A  N T R S\n        G K J X  H V W F\n    \n         76  59 272  97   90 136 145  53\n        119 270 445 287  258 331 224 232\n         67  19   6   8  180  38  60  86\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     30378108025\n    \n        P Y O U  M D L B\n        C I E A  R T N S\n        G K J X  H W F V\n    \n         76  59 272  97   90 136 145  53\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  60  86  38\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     40389033341\n    \n        P Y O U  V D L B\n        C I E A  N T R S\n        G K J X  H M W F\n    \n         76  59 272  97   38 136 145  53\n        119 270 445 287  258 331 224 232\n         67  19   6   8  180  90  60  86\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     31185165545\n    \n        P Y O U  B D L F\n        C I E A  R T N S\n        G K J X  H M V W\n    \n         76  59 272  97   53 136 145  86\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  90  38  60\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     35409585570\n    \n        P Y O U  M D L B\n        C I E A  N T R S\n        G K J X  H W V F\n    \n         76  59 272  97   90 136 145  53\n        119 270 445 287  258 331 224 232\n         67  19   6   8  180  60  38  86\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     33591926771\n    \n        P Y O U  V D L F\n        C I E A  R T N S\n        G K J X  H M W B\n    \n         76  59 272  97   38 136 145  86\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  90  60  53\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     33876968307\n    \n        P Y O U  F D L B\n        C I E A  N T R S\n        G K J X  H M W V\n    \n         76  59 272  97   86 136 145  53\n        119 270 445 287  258 331 224 232\n         67  19   6   8  180  90  60  38\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     31190926573\n    \n        P Y O U  F D L B\n        C I E A  N T R S\n        G K J X  H M V W\n    \n         76  59 272  97   86 136 145  53\n        119 270 445 287  258 331 224 232\n         67  19   6   8  180  90  38  60\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     33681168612\n    \n        P Y O U  B D L F\n        C I E A  R T N S\n        G K J X  H M W V\n    \n         76  59 272  97   53 136 145  86\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  90  60  38\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     34468365028\n    \n        P Y O U  B D L V\n        C I E A  R T N S\n        G K J X  H M W F\n    \n         76  59 272  97   53 136 145  38\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  90  60  86\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     34468365028\n    \n        P Y O U  V D L F\n        C I E A  R T N S\n        G K J X  H M B W\n    \n         76  59 272  97   38 136 145  86\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  90  53  60\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     37828913779\n    \n        P Y O U  B D L V\n        C I E A  R T N S\n        G K J X  H M F W\n    \n         76  59 272  97   53 136 145  38\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  90  86  60\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     37548340069\n    \n        P Y O U  F D L V\n        C I E A  R T N S\n        G K J X  H M W B\n    \n         76  59 272  97   86 136 145  38\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  90  60  53\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     38389960893\n    \n        P Y O U  B D L V\n        C I E A  N T R S\n        G K J X  H M W F\n    \n         76  59 272  97   53 136 145  38\n        119 270 445 287  258 331 224 232\n         67  19   6   8  180  90  60  86\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     28566588010\n    \n        P Y O U  M D L B\n        C I E A  N T R S\n        G K J X  H F W V\n    \n         76  59 272  97   90 136 145  53\n        119 270 445 287  258 331 224 232\n         67  19   6   8  180  86  60  38\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     31859049582\n    \n        P Y O U  M D L B\n        C I E A  N T R S\n        G K J X  H F V W\n    \n         76  59 272  97   90 136 145  53\n        119 270 445 287  258 331 224 232\n         67  19   6   8  180  86  38  60\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     34349291620\n    \n        P Y O U  F D L V\n        C I E A  N T R S\n        G K J X  H M W B\n    \n         76  59 272  97   86 136 145  38\n        119 270 445 287  258 331 224 232\n         67  19   6   8  180  90  60  53\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     31190926573\n    \n        P Y O U  F D L V\n        C I E A  R T N S\n        G K J X  H M B W\n    \n         76  59 272  97   86 136 145  38\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  90  53  60\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     42192213989\n    \n        P Y O U  V D L B\n        C I E A  R T N S\n        G K J X  H F M W\n    \n         76  59 272  97   38 136 145  53\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  86  90  60\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     34787800759\n    \n        P Y O U  F D L B\n        C I E A  R T N S\n        G K J X  H V M W\n    \n         76  59 272  97   86 136 145  53\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  38  90  60\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     37819851788\n    \n        P Y O U  M D L F\n        C I E A  R T N S\n        G K J X  H V W B\n    \n         76  59 272  97   90 136 145  86\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  38  60  53\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     36557845830\n    \n        B Y O U  M D L P\n        C I E A  R T N S\n        G K J X  H F V W\n    \n         53  59 272  97   90 136 145  76\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  86  38  60\n    \n        left: 1.702T  right: 1.854T (8.90%)\n        Total same-finger bigram frequencies:     44287627524\n    \n        P Y O U  M D L B\n        C I E A  N T R S\n        G K J X  H V F W\n    \n         76  59 272  97   90 136 145  53\n        119 270 445 287  258 331 224 232\n         67  19   6   8  180  38  86  60\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     39664028497\n    \n        B Y O U  M D L P\n        C I E A  R T N S\n        G K J X  H V W F\n    \n         53  59 272  97   90 136 145  76\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  38  60  86\n    \n        left: 1.702T  right: 1.854T (8.90%)\n        Total same-finger bigram frequencies:     42006196645\n    \n        B Y O U  M D L P\n        C I E A  R T N S\n        G K J X  H V F W\n    \n         53  59 272  97   90 136 145  76\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  38  86  60\n    \n        left: 1.702T  right: 1.854T (8.90%)\n        Total same-finger bigram frequencies:     45095132843\n    \n        P Y O U  V D L F\n        C I E A  N T R S\n        G K J X  H M W B\n    \n         76  59 272  97   38 136 145  86\n        119 270 445 287  258 331 224 232\n         67  19   6   8  180  90  60  53\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     31185165545\n    \n        P Y O U  M D L F\n        C I E A  R T N S\n        G K J X  H W V B\n    \n         76  59 272  97   90 136 145  86\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  60  38  53\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     38100586465\n    \n        P Y O U  V D L B\n        C I E A  R T N S\n        G K J X  H W M F\n    \n         76  59 272  97   38 136 145  53\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  60  90  86\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     34030435909\n    \n        P Y O U  B D L F\n        C I E A  R T N S\n        G K J X  H V M W\n    \n         76  59 272  97   53 136 145  86\n        119 270 445 287  224 331 258 232\n         67  19   6   8  180  38  90  60\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     34020312538\n    \n        P Y O U  B D L F\n        C I E A  N T R S\n        G K J X  H M W V\n    \n         76  59 272  97   53 136 145  86\n        119 270 445 287  258 331 224 232\n         67  19   6   8  180  90  60  38\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     28566588010\n\n\nRank:   Layout                                             Score\n\n    1:  P Y O U C I E A G K J X M D L B R T N S H F V W    0.7077818057116185\n    1:  P Y O U C I E A G K J X M D L B R T N S H V W F    0.7077803780536207\n    1:  P Y O U C I E A G K J X F D L B R T N S H M V W    0.7077798033933657\n    1:  P Y O U C I E A G K J X M D L B R T N S H V F W    0.7077794525908389\n    1:  P Y O U C I E A G K J X V D L B R T N S H M W F    0.7077787741093243\n    1:  P Y O U C I E A G K J X V D L B R T N S H M F W    0.7077781057237986\n    1:  P Y O U C I E A G K J X M D L B R T N S H F W V    0.7077747150460763\n    1:  P Y O U C I E A G K J X M D L B R T N S H W V F    0.7077742244130669\n    1:  P Y O U C I E A G K J X F D L B R T N S H M W V    0.707772661556241\n    1:  P Y O U C I E A G K J X M D L B N T R S H V W F    0.7077696227710919\n    1:  P Y O U C I E A G K J X M D L B R T N S H W F V    0.7077661460024984\n    1:  P Y O U C I E A G K J X V D L B N T R S H M W F    0.7077596943431474\n    1:  P Y O U C I E A G K J X B D L F R T N S H M V W    0.7077592801213322\n    1:  P Y O U C I E A G K J X M D L B N T R S H W V F    0.707759191453331\n    1:  P Y O U C I E A G K J X V D L F R T N S H M W B    0.7077577907825605\n    1:  P Y O U C I E A G K J X F D L B N T R S H M W V    0.7077551748734543\n    1:  P Y O U C I E A G K J X F D L B N T R S H M V W    0.7077542134014241\n    1:  P Y O U C I E A G K J X B D L F R T N S H M W V    0.7077526034466854\n    1:  P Y O U C I E A G K J X B D L V R T N S H M W F    0.7077503203600539\n    1:  P Y O U C I E A G K J X V D L F R T N S H M B W    0.7077500948346779\n    1:  P Y O U C I E A G K J X B D L V R T N S H M F W    0.7077497507892488\n    1:  P Y O U C I E A G K J X F D L V R T N S H M W B    0.707749429250204\n    1:  P Y O U C I E A G K J X B D L V N T R S H M W F    0.7077478765448684\n    1:  P Y O U C I E A G K J X M D L B N T R S H F W V    0.7077477888266053\n    1:  P Y O U C I E A G K J X M D L B N T R S H F V W    0.707746776182993\n    1:  P Y O U C I E A G K J X F D L V N T R S H M W B    0.7077456965787586\n    1:  P Y O U C I E A G K J X F D L V R T N S H M B W    0.7077422593554563\n    1:  P Y O U C I E A G K J X V D L B R T N S H F M W    0.7077402962916755\n    1:  P Y O U C I E A G K J X F D L B R T N S H V M W    0.7077395224274426\n    1:  P Y O U C I E A G K J X M D L F R T N S H V W B    0.7077382228893154\n    1:  B Y O U C I E A G K J X M D L P R T N S H F V W    0.7077355553339657\n    1:  P Y O U C I E A G K J X M D L B N T R S H V F W    0.7077354301289264\n    1:  B Y O U C I E A G K J X M D L P R T N S H V W F    0.7077338112865781\n    1:  B Y O U C I E A G K J X M D L P R T N S H V F W    0.7077328900501446\n    1:  P Y O U C I E A G K J X V D L F N T R S H M W B    0.7077324321983025\n    1:  P Y O U C I E A G K J X M D L F R T N S H W V B    0.7077323473880455\n    1:  P Y O U C I E A G K J X V D L B R T N S H W M F    0.7077320798107325\n    1:  P Y O U C I E A G K J X B D L F R T N S H V M W    0.7077309803243578\n    1:  P Y O U C I E A G K J X B D L F N T R S H M W V    0.7077301268020774\n\nOriginal:\n\n    P Y O U  M D L B\n    C I E A  R T N S\n    G K J X  H V W F\n\nShared across all layouts:\n\n    P Y O U  - D L -\n    C I E A  - T - S\n    G K J X  H - - -\n\nLayouts tied for first place -- only those with decreasing same-finger bigram counts included:\n\n    P Y O U  M D L B\n    C I E A  R T N S\n    G K J X  H F V W\n\n     76  59 272  97   90 136 145  53\n    119 270 445 287  224 331 258 232\n     67  19   6   8  180  86  38  60\n\n    Total same-finger bigram frequencies:     38,857,951,315\n\n    P Y O U  M D L B\n    C I E A  R T N S\n    G K J X  H V W F\n\n     76  59 272  97   90 136 145  53\n    119 270 445 287  224 331 258 232\n     67  19   6   8  180  38  60  86\n\n    Total same-finger bigram frequencies:     36,557,845,830\n\n    P Y O U  V D L B\n    C I E A  R T N S\n    G K J X  H M W F\n\n     76  59 272  97   38 136 145  53\n    119 270 445 287  224 331 258 232\n     67  19   6   8  180  90  60  86\n\n    Total same-finger bigram frequencies:     33,876,968,307\n\n    P Y O U  M D L B\n    C I E A  N T R S\n    G K J X  H V W F\n\n     76  59 272  97   90 136 145  53\n    119 270 445 287  258 331 224 232\n     67  19   6   8  180  38  60  86\n\n    Total same-finger bigram frequencies:     30,378,108,025\n\n    P Y O U  B D L V\n    C I E A  N T R S\n    G K J X  H M W F\n\n     76  59 272  97   53 136 145  38\n    119 270 445 287  258 331 224 232\n     67  19   6   8  180  90  60  86\n\n    Total same-finger bigram frequencies:     28,566,588,010\n\nWe will choose this bottom-most layout tied for first place as our candidate winner, since it only differs from the original and above layouts by five letter assignments, but has the lowest number of same-finger bigrams as well as a load distribution that better matches our comfortable keys as defined above.\n\n## Step 4: Stability Tests <a name=\"step4\">\n    \nWe will run three stability tests on the winning layout variants tied for first place:\n    \n    1. Compare ranking of all final layouts after removing each scoring parameter\n    2. Compare ranking of all final layouts based on interkey speed\n\nIn the first test we remove each scoring parameter one at a time and rescore all of the final layouts to see if this affects their ranking. In the second test, we rescore all of the final layouts, replacing the factor matrix with either the flow matrix or the inter-key speed matrix to see if this affects their ranking.\n\n### Stability Test 1: Compare ranking of all final layouts after removing each scoring parameter\n\n\n```python\nuse_variants = True\nif use_variants:\n    test_layouts = layout_strings_first_place\n    test_layout_strings = layouts_first_place\nelse:\n    test_layouts = layouts_sorted\n    test_layout_strings = layout_strings_sorted\n\nparams0 = [side_above_3away, side_above_2away, side_above_1away, middle_above_ring, ring_above_middle, \n           outward, skip_row_3away, skip_row_2away, skip_row_1away, skip_row_0away, same_finger]\nparam_names = ['side_above_3away', 'side_above_2away', 'side_above_1away', \n               'middle_above_ring', 'ring_above_middle', 'outward', 'skip_row_3away', \n               'skip_row_2away', 'skip_row_1away', 'skip_row_0away', 'same_finger']\nparams_lists = []\nfor i in range(len(params0)):\n    params_list = params0.copy()\n    params_list[i] = 1.0\n    params_lists.append(params_list)\n\nfor iparam, P in enumerate(params_lists):\n\n    print('\\nRemove parameter {0}:'.format(param_names[iparam]))\n\n    data_matrix_param = create_24x24_flow_matrix(not_home_row, side_top,\n                                                 P[0],P[1],P[2],P[3],P[4],P[5],P[6],P[7],P[8],P[9],P[10],\n                                                 1,1,1,1,1,1)\n    if apply_strength:\n        data_matrix_param = Strength24x24 * data_matrix_param\n\n    param_scores = []\n    if use_variants:\n        for letters in layout_strings_first_place:\n            score = score_layout(data_matrix_param, letters, bigrams, bigram_frequencies, verbose=False);\n            param_scores.append(score)\n    else:\n        for letters in top_layouts:\n            score = score_layout(data_matrix_param, letters, bigrams, bigram_frequencies, verbose=False);\n            param_scores.append(score)\n            \n    param_scores_sorted, param_ranks_sorted, Isort_param = rank_within_epsilon(param_scores, factor, factor=True, verbose=False)\n    param_layouts_sorted = []\n    param_layout_strings_sorted = []\n    for i in Isort_param:\n        if use_variants:\n            param_layouts_sorted.append(layouts_first_place[i])\n            param_layout_strings_sorted.append(layout_strings_first_place[i])\n        else:\n            param_layouts_sorted.append(test_layouts[i])\n            param_layout_strings_sorted.append(test_layout_strings[i])\n\n    print('Rank:   Layout                                             Score\\n')\n    for i, rank in enumerate(param_ranks_sorted):\n        if rank == 1:\n            if use_variants:\n                print('    {0}:  {1}    {2}'.format(rank, layouts_first_place[i], param_scores_sorted[i]))\n            else:\n                print('    {0}:  {1}    {2}'.format(rank, layout_strings_sorted[i], param_scores_sorted[i]))\n```\n\n    \n    Remove parameter side_above_3away:\n    Rank:   Layout                                             Score\n    \n        1:  P Y O U C I E A G K J X M D L B R T N S H F V W    0.710691034989887\n        1:  P Y O U C I E A G K J X M D L B R T N S H V W F    0.7106848813493216\n        1:  P Y O U C I E A G K J X F D L B R T N S H M V W    0.7106831782038915\n        1:  P Y O U C I E A G K J X M D L B R T N S H V F W    0.7106825158777715\n        1:  P Y O U C I E A G K J X V D L B R T N S H M W F    0.7106808250830903\n        1:  P Y O U C I E A G K J X V D L B R T N S H M F W    0.7106769997706761\n        1:  P Y O U C I E A G K J X M D L B R T N S H F W V    0.7106753708237136\n        1:  P Y O U C I E A G K J X M D L B R T N S H W V F    0.7106726649520392\n        1:  P Y O U C I E A G K J X F D L B R T N S H M W V    0.710669120934822\n        1:  P Y O U C I E A G K J X M D L B N T R S H V W F    0.7106684307270651\n        1:  P Y O U C I E A G K J X M D L B R T N S H W F V    0.7106660045842162\n        1:  P Y O U C I E A G K J X V D L B N T R S H M W F    0.7106615755173085\n        1:  P Y O U C I E A G K J X B D L F R T N S H M V W    0.7106608479129732\n        1:  P Y O U C I E A G K J X M D L B N T R S H W V F    0.7106559459198573\n        1:  P Y O U C I E A G K J X V D L F R T N S H M W B    0.7106555732664435\n        1:  P Y O U C I E A G K J X F D L B N T R S H M W V    0.7106552265521447\n        1:  P Y O U C I E A G K J X F D L B N T R S H M V W    0.7106527348724131\n        1:  P Y O U C I E A G K J X B D L F R T N S H M W V    0.7106520791181199\n        1:  P Y O U C I E A G K J X B D L V R T N S H M W F    0.710649433042617\n        1:  P Y O U C I E A G K J X V D L F R T N S H M B W    0.7106491609884795\n        1:  P Y O U C I E A G K J X B D L V R T N S H M F W    0.710648405523252\n        1:  P Y O U C I E A G K J X F D L V R T N S H M W B    0.7106462036168384\n        1:  P Y O U C I E A G K J X B D L V N T R S H M W F    0.7106457572996695\n        1:  P Y O U C I E A G K J X M D L B N T R S H F W V    0.7106457402394089\n        1:  P Y O U C I E A G K J X M D L B N T R S H F V W    0.7106457068458685\n        1:  P Y O U C I E A G K J X F D L V N T R S H M W B    0.7106449372838913\n        1:  P Y O U C I E A G K J X F D L V R T N S H M B W    0.7106441251431348\n        1:  P Y O U C I E A G K J X V D L B R T N S H F M W    0.7106433765830329\n        1:  P Y O U C I E A G K J X F D L B R T N S H V M W    0.7106430225219769\n        1:  P Y O U C I E A G K J X M D L F R T N S H V W B    0.7106412188950628\n    \n    Remove parameter side_above_2away:\n    Rank:   Layout                                             Score\n    \n        1:  P Y O U C I E A G K J X M D L B R T N S H F V W    0.712988053119612\n        1:  P Y O U C I E A G K J X M D L B R T N S H V W F    0.7129752198882028\n        1:  P Y O U C I E A G K J X F D L B R T N S H M V W    0.7129709541885679\n        1:  P Y O U C I E A G K J X M D L B R T N S H V F W    0.7129700780678659\n        1:  P Y O U C I E A G K J X V D L B R T N S H M W F    0.7129664753855269\n        1:  P Y O U C I E A G K J X V D L B R T N S H M F W    0.712966325836343\n        1:  P Y O U C I E A G K J X M D L B R T N S H F W V    0.7129620931114837\n        1:  P Y O U C I E A G K J X M D L B R T N S H W V F    0.712961300302908\n        1:  P Y O U C I E A G K J X F D L B R T N S H M W V    0.7129586867699282\n        1:  P Y O U C I E A G K J X M D L B N T R S H V W F    0.7129578556441535\n        1:  P Y O U C I E A G K J X M D L B R T N S H W F V    0.7129571944851177\n        1:  P Y O U C I E A G K J X V D L B N T R S H M W F    0.7129532356870116\n        1:  P Y O U C I E A G K J X B D L F R T N S H M V W    0.7129530764976783\n        1:  P Y O U C I E A G K J X M D L B N T R S H W V F    0.7129516016532901\n        1:  P Y O U C I E A G K J X V D L F R T N S H M W B    0.712950752739089\n        1:  P Y O U C I E A G K J X F D L B N T R S H M W V    0.712950254329926\n        1:  P Y O U C I E A G K J X F D L B N T R S H M V W    0.7129500046068539\n        1:  P Y O U C I E A G K J X B D L F R T N S H M W V    0.7129493952653113\n        1:  P Y O U C I E A G K J X B D L V R T N S H M W F    0.7129489809721066\n        1:  P Y O U C I E A G K J X V D L F R T N S H M B W    0.7129486473736829\n        1:  P Y O U C I E A G K J X B D L V R T N S H M F W    0.7129435350866493\n        1:  P Y O U C I E A G K J X F D L V R T N S H M W B    0.7129415693935539\n        1:  P Y O U C I E A G K J X B D L V N T R S H M W F    0.7129384203074116\n        1:  P Y O U C I E A G K J X M D L B N T R S H F W V    0.7129371323270438\n        1:  P Y O U C I E A G K J X M D L B N T R S H F V W    0.7129361010463354\n    \n    Remove parameter side_above_1away:\n    Rank:   Layout                                             Score\n    \n        1:  P Y O U C I E A G K J X M D L B R T N S H F V W    0.7147771451315443\n        1:  P Y O U C I E A G K J X M D L B R T N S H V W F    0.7147763366421485\n        1:  P Y O U C I E A G K J X F D L B R T N S H M V W    0.7147712300020337\n        1:  P Y O U C I E A G K J X M D L B R T N S H V F W    0.7147703703410553\n        1:  P Y O U C I E A G K J X V D L B R T N S H M W F    0.7147659762159919\n        1:  P Y O U C I E A G K J X V D L B R T N S H M F W    0.7147612437968827\n        1:  P Y O U C I E A G K J X M D L B R T N S H F W V    0.7147610980520591\n        1:  P Y O U C I E A G K J X M D L B R T N S H W V F    0.7147582566372672\n        1:  P Y O U C I E A G K J X F D L B R T N S H M W V    0.7147559281451338\n        1:  P Y O U C I E A G K J X M D L B N T R S H V W F    0.7147558396990816\n        1:  P Y O U C I E A G K J X M D L B R T N S H W F V    0.7147554730587253\n        1:  P Y O U C I E A G K J X V D L B N T R S H M W F    0.7147532671409009\n        1:  P Y O U C I E A G K J X B D L F R T N S H M V W    0.714752022421496\n        1:  P Y O U C I E A G K J X M D L B N T R S H W V F    0.7147519769146324\n        1:  P Y O U C I E A G K J X V D L F R T N S H M W B    0.7147517496841845\n        1:  P Y O U C I E A G K J X F D L B N T R S H M W V    0.7147516842039716\n        1:  P Y O U C I E A G K J X F D L B N T R S H M V W    0.7147493608271949\n        1:  P Y O U C I E A G K J X B D L F R T N S H M W V    0.7147471805681523\n        1:  P Y O U C I E A G K J X B D L V R T N S H M W F    0.7147459897061802\n        1:  P Y O U C I E A G K J X V D L F R T N S H M B W    0.7147447332664509\n        1:  P Y O U C I E A G K J X B D L V R T N S H M F W    0.7147443833177041\n        1:  P Y O U C I E A G K J X F D L V R T N S H M W B    0.7147431765273823\n        1:  P Y O U C I E A G K J X B D L V N T R S H M W F    0.7147431668625788\n        1:  P Y O U C I E A G K J X M D L B N T R S H F W V    0.7147414401987634\n        1:  P Y O U C I E A G K J X M D L B N T R S H F V W    0.7147413783838252\n        1:  P Y O U C I E A G K J X F D L V N T R S H M W B    0.7147387351289186\n        1:  P Y O U C I E A G K J X F D L V R T N S H M B W    0.7147373065945722\n        1:  P Y O U C I E A G K J X V D L B R T N S H F M W    0.7147346451140214\n        1:  P Y O U C I E A G K J X F D L B R T N S H V M W    0.714734083564061\n        1:  P Y O U C I E A G K J X M D L F R T N S H V W B    0.7147336289950732\n        1:  B Y O U C I E A G K J X M D L P R T N S H F V W    0.7147316976941598\n        1:  P Y O U C I E A G K J X M D L B N T R S H V F W    0.7147297007517059\n        1:  B Y O U C I E A G K J X M D L P R T N S H V W F    0.7147260556193432\n    \n    Remove parameter middle_above_ring:\n    Rank:   Layout                                             Score\n    \n        1:  P Y O U C I E A G K J X M D L B R T N S H F V W    0.7091932886603218\n        1:  P Y O U C I E A G K J X M D L B R T N S H V W F    0.7091924304907777\n        1:  P Y O U C I E A G K J X F D L B R T N S H M V W    0.7091916847160251\n        1:  P Y O U C I E A G K J X M D L B R T N S H V F W    0.7091911492983065\n        1:  P Y O U C I E A G K J X V D L B R T N S H M W F    0.7091910836237381\n        1:  P Y O U C I E A G K J X V D L B R T N S H M F W    0.7091891469800482\n        1:  P Y O U C I E A G K J X M D L B R T N S H F W V    0.7091876256528137\n        1:  P Y O U C I E A G K J X M D L B R T N S H W V F    0.7091855721629726\n        1:  P Y O U C I E A G K J X F D L B R T N S H M W V    0.7091835679997055\n        1:  P Y O U C I E A G K J X M D L B N T R S H V W F    0.709179123902424\n        1:  P Y O U C I E A G K J X M D L B R T N S H W F V    0.7091707013891726\n        1:  P Y O U C I E A G K J X V D L B N T R S H M W F    0.7091686237079559\n        1:  P Y O U C I E A G K J X B D L F R T N S H M V W    0.7091655140533581\n        1:  P Y O U C I E A G K J X M D L B N T R S H W V F    0.7091632309667246\n        1:  P Y O U C I E A G K J X V D L F R T N S H M W B    0.7091627286891588\n        1:  P Y O U C I E A G K J X F D L B N T R S H M W V    0.709162339856845\n        1:  P Y O U C I E A G K J X F D L B N T R S H M V W    0.7091599465575852\n        1:  P Y O U C I E A G K J X B D L F R T N S H M W V    0.709152111078393\n        1:  P Y O U C I E A G K J X B D L V R T N S H M W F    0.7091511334959135\n        1:  P Y O U C I E A G K J X V D L F R T N S H M B W    0.7091507584047894\n        1:  P Y O U C I E A G K J X B D L V R T N S H M F W    0.7091499845405504\n        1:  P Y O U C I E A G K J X F D L V R T N S H M W B    0.7091467218932246\n        1:  P Y O U C I E A G K J X B D L V N T R S H M W F    0.709145867950029\n        1:  P Y O U C I E A G K J X M D L B N T R S H F W V    0.7091448989205996\n        1:  P Y O U C I E A G K J X M D L B N T R S H F V W    0.7091425419237951\n        1:  P Y O U C I E A G K J X F D L V N T R S H M W B    0.7091416909745809\n        1:  P Y O U C I E A G K J X F D L V R T N S H M B W    0.7091414424374147\n    \n    Remove parameter ring_above_middle:\n    Rank:   Layout                                             Score\n    \n        1:  P Y O U C I E A G K J X M D L B R T N S H F V W    0.71134781474929\n        1:  P Y O U C I E A G K J X M D L B R T N S H V W F    0.7113407240837462\n        1:  P Y O U C I E A G K J X F D L B R T N S H M V W    0.7113386250031604\n        1:  P Y O U C I E A G K J X M D L B R T N S H V F W    0.7113376995403947\n        1:  P Y O U C I E A G K J X V D L B R T N S H M W F    0.7113353278924294\n        1:  P Y O U C I E A G K J X V D L B R T N S H M F W    0.7113349620808336\n        1:  P Y O U C I E A G K J X M D L B R T N S H F W V    0.7113342986083553\n        1:  P Y O U C I E A G K J X M D L B R T N S H W V F    0.7113338351608329\n        1:  P Y O U C I E A G K J X F D L B R T N S H M W V    0.7113336302228467\n        1:  P Y O U C I E A G K J X M D L B N T R S H V W F    0.7113334255552046\n        1:  P Y O U C I E A G K J X M D L B R T N S H W F V    0.711332822517217\n        1:  P Y O U C I E A G K J X V D L B N T R S H M W F    0.7113301638975735\n        1:  P Y O U C I E A G K J X B D L F R T N S H M V W    0.711328906085541\n        1:  P Y O U C I E A G K J X M D L B N T R S H W V F    0.7113281860553029\n        1:  P Y O U C I E A G K J X V D L F R T N S H M W B    0.7113279446135077\n        1:  P Y O U C I E A G K J X F D L B N T R S H M W V    0.7113268836702797\n        1:  P Y O U C I E A G K J X F D L B N T R S H M V W    0.7113216077568871\n        1:  P Y O U C I E A G K J X B D L F R T N S H M W V    0.7113194277907479\n        1:  P Y O U C I E A G K J X B D L V R T N S H M W F    0.711315265275107\n        1:  P Y O U C I E A G K J X V D L F R T N S H M B W    0.7113148046203369\n        1:  P Y O U C I E A G K J X B D L V R T N S H M F W    0.711313315281503\n        1:  P Y O U C I E A G K J X F D L V R T N S H M W B    0.7113081279456884\n        1:  P Y O U C I E A G K J X B D L V N T R S H M W F    0.7113063053293005\n        1:  P Y O U C I E A G K J X M D L B N T R S H F W V    0.711306163410263\n        1:  P Y O U C I E A G K J X M D L B N T R S H F V W    0.7113058448590548\n        1:  P Y O U C I E A G K J X F D L V N T R S H M W B    0.7113056193335807\n        1:  P Y O U C I E A G K J X F D L V R T N S H M B W    0.7113052752882675\n        1:  P Y O U C I E A G K J X V D L B R T N S H F M W    0.7113049537491752\n        1:  P Y O U C I E A G K J X F D L B R T N S H V M W    0.7113038580140971\n        1:  P Y O U C I E A G K J X M D L F R T N S H V W B    0.7113015643715831\n        1:  B Y O U C I E A G K J X M D L P R T N S H F V W    0.7112977838543885\n        1:  P Y O U C I E A G K J X M D L B N T R S H V F W    0.7112977693769674\n        1:  B Y O U C I E A G K J X M D L P R T N S H V W F    0.7112964698387519\n        1:  B Y O U C I E A G K J X M D L P R T N S H V F W    0.7112959712554168\n    \n    Remove parameter outward:\n    Rank:   Layout                                             Score\n    \n        1:  P Y O U C I E A G K J X M D L B R T N S H F V W    0.720194675425853\n        1:  P Y O U C I E A G K J X M D L B R T N S H V W F    0.7201925450288541\n        1:  P Y O U C I E A G K J X F D L B R T N S H M V W    0.7201911162614038\n        1:  P Y O U C I E A G K J X M D L B R T N S H V F W    0.7201873771545405\n        1:  P Y O U C I E A G K J X V D L B R T N S H M W F    0.7201850538960122\n        1:  P Y O U C I E A G K J X V D L B R T N S H M F W    0.720182952413453\n        1:  P Y O U C I E A G K J X M D L B R T N S H F W V    0.7201827018819257\n        1:  P Y O U C I E A G K J X M D L B R T N S H W V F    0.7201823459380235\n        1:  P Y O U C I E A G K J X F D L B R T N S H M W V    0.7201777343466697\n        1:  P Y O U C I E A G K J X M D L B N T R S H V W F    0.7201737546789003\n        1:  P Y O U C I E A G K J X M D L B R T N S H W F V    0.7201575867100397\n        1:  P Y O U C I E A G K J X V D L B N T R S H M W F    0.7201574932226783\n    \n    Remove parameter skip_row_3away:\n    Rank:   Layout                                             Score\n    \n        1:  P Y O U C I E A G K J X M D L B R T N S H F V W    0.7086635192180479\n        1:  P Y O U C I E A G K J X M D L B R T N S H V W F    0.7086621951423652\n        1:  P Y O U C I E A G K J X F D L B R T N S H M V W    0.7086615250850334\n        1:  P Y O U C I E A G K J X M D L B R T N S H V F W    0.7086611660972467\n        1:  P Y O U C I E A G K J X V D L B R T N S H M W F    0.7086604240949753\n        1:  P Y O U C I E A G K J X V D L B R T N S H M F W    0.7086597540309213\n        1:  P Y O U C I E A G K J X M D L B R T N S H F W V    0.7086563772394919\n        1:  P Y O U C I E A G K J X M D L B R T N S H W V F    0.7086560415017996\n        1:  P Y O U C I E A G K J X F D L B R T N S H M W V    0.7086543116508013\n        1:  P Y O U C I E A G K J X M D L B N T R S H V W F    0.7086514398595587\n        1:  P Y O U C I E A G K J X M D L B R T N S H W F V    0.7086478081958807\n        1:  P Y O U C I E A G K J X V D L B N T R S H M W F    0.7086413443285475\n        1:  P Y O U C I E A G K J X B D L F R T N S H M V W    0.7086410085417859\n        1:  P Y O U C I E A G K J X M D L B N T R S H W V F    0.7086408657884\n        1:  P Y O U C I E A G K J X V D L F R T N S H M W B    0.7086394837345122\n        1:  P Y O U C I E A G K J X F D L B N T R S H M W V    0.7086368249677625\n        1:  P Y O U C I E A G K J X F D L B N T R S H M V W    0.7086359350928348\n        1:  P Y O U C I E A G K J X B D L F R T N S H M W V    0.7086342808822307\n        1:  P Y O U C I E A G K J X B D L V R T N S H M W F    0.7086317892024989\n        1:  P Y O U C I E A G K J X V D L F R T N S H M B W    0.708631627221611\n        1:  P Y O U C I E A G K J X B D L V R T N S H M F W    0.708631257713741\n        1:  P Y O U C I E A G K J X F D L V R T N S H M W B    0.7086308975618477\n        1:  P Y O U C I E A G K J X B D L V N T R S H M W F    0.7086294510197404\n        1:  P Y O U C I E A G K J X M D L B N T R S H F W V    0.7086293453870545\n        1:  P Y O U C I E A G K J X M D L B N T R S H F V W    0.7086284896891366\n        1:  P Y O U C I E A G K J X F D L V N T R S H M W B    0.7086271648901434\n        1:  P Y O U C I E A G K J X F D L V R T N S H M B W    0.7086237863843592\n        1:  P Y O U C I E A G K J X V D L B R T N S H F M W    0.708623239270598\n        1:  P Y O U C I E A G K J X F D L B R T N S H V M W    0.7086219445987727\n        1:  P Y O U C I E A G K J X M D L F R T N S H V W B    0.7086212441190632\n        1:  B Y O U C I E A G K J X M D L P R T N S H F V W    0.708618499384722\n        1:  P Y O U C I E A G K J X M D L B N T R S H V F W    0.7086173637693166\n        1:  B Y O U C I E A G K J X M D L P R T N S H V W F    0.7086171436350491\n        1:  B Y O U C I E A G K J X M D L P R T N S H V F W    0.7086168589196489\n        1:  P Y O U C I E A G K J X V D L F N T R S H M W B    0.7086158341008788\n        1:  P Y O U C I E A G K J X M D L F R T N S H W V B    0.7086141251499952\n        1:  P Y O U C I E A G K J X V D L B R T N S H W M F    0.7086137297963239\n        1:  P Y O U C I E A G K J X B D L F R T N S H V M W    0.7086125659913864\n        1:  P Y O U C I E A G K J X B D L F N T R S H M W V    0.7086118042373624\n    \n    Remove parameter skip_row_2away:\n    Rank:   Layout                                             Score\n    \n        1:  P Y O U C I E A G K J X M D L B R T N S H F V W    0.7126328009006637\n        1:  P Y O U C I E A G K J X M D L B R T N S H V W F    0.7126311029606389\n        1:  P Y O U C I E A G K J X F D L B R T N S H M V W    0.7126307757280029\n        1:  P Y O U C I E A G K J X M D L B R T N S H V F W    0.7126266616444469\n        1:  P Y O U C I E A G K J X V D L B R T N S H M W F    0.7126262850620145\n        1:  P Y O U C I E A G K J X V D L B R T N S H M F W    0.7126246761672937\n        1:  P Y O U C I E A G K J X M D L B R T N S H F W V    0.7126243528941103\n        1:  P Y O U C I E A G K J X M D L B R T N S H W V F    0.7126201465939322\n        1:  P Y O U C I E A G K J X F D L B R T N S H M W V    0.7126177996520684\n        1:  P Y O U C I E A G K J X M D L B N T R S H V W F    0.7126135976113039\n        1:  P Y O U C I E A G K J X M D L B R T N S H W F V    0.7126119221749251\n        1:  P Y O U C I E A G K J X V D L B N T R S H M W F    0.7126116959615751\n        1:  P Y O U C I E A G K J X B D L F R T N S H M V W    0.7126091749614081\n        1:  P Y O U C I E A G K J X M D L B N T R S H W V F    0.7126072109084651\n        1:  P Y O U C I E A G K J X V D L F R T N S H M W B    0.712604464992624\n        1:  P Y O U C I E A G K J X F D L B N T R S H M W V    0.7126027666920547\n        1:  P Y O U C I E A G K J X F D L B N T R S H M V W    0.7126018719901841\n        1:  P Y O U C I E A G K J X B D L F R T N S H M W V    0.7125983851168124\n        1:  P Y O U C I E A G K J X B D L V R T N S H M W F    0.7125953182470579\n        1:  P Y O U C I E A G K J X V D L F R T N S H M B W    0.7125942314735533\n        1:  P Y O U C I E A G K J X B D L V R T N S H M F W    0.7125939041870735\n        1:  P Y O U C I E A G K J X F D L V R T N S H M W B    0.7125933110842476\n        1:  P Y O U C I E A G K J X B D L V N T R S H M W F    0.7125932203741807\n        1:  P Y O U C I E A G K J X M D L B N T R S H F W V    0.7125914603716288\n        1:  P Y O U C I E A G K J X M D L B N T R S H F V W    0.7125912555331032\n        1:  P Y O U C I E A G K J X F D L V N T R S H M W B    0.7125895784125432\n        1:  P Y O U C I E A G K J X F D L V R T N S H M B W    0.7125867387212961\n        1:  P Y O U C I E A G K J X V D L B R T N S H F M W    0.7125849412091111\n        1:  P Y O U C I E A G K J X F D L B R T N S H V M W    0.7125847781516593\n        1:  P Y O U C I E A G K J X M D L F R T N S H V W B    0.7125847774598402\n        1:  B Y O U C I E A G K J X M D L P R T N S H F V W    0.7125825044051926\n        1:  P Y O U C I E A G K J X M D L B N T R S H V F W    0.7125820543129809\n        1:  B Y O U C I E A G K J X M D L P R T N S H V W F    0.7125806537050962\n        1:  B Y O U C I E A G K J X M D L P R T N S H V F W    0.7125800957707126\n        1:  P Y O U C I E A G K J X V D L F N T R S H M W B    0.7125797682711806\n    \n    Remove parameter skip_row_1away:\n    Rank:   Layout                                             Score\n    \n        1:  P Y O U C I E A G K J X M D L B R T N S H F V W    0.71810565714906\n        1:  P Y O U C I E A G K J X M D L B R T N S H V W F    0.718105163871471\n        1:  P Y O U C I E A G K J X F D L B R T N S H M V W    0.7181040745782368\n        1:  P Y O U C I E A G K J X M D L B R T N S H V F W    0.7181029124343701\n        1:  P Y O U C I E A G K J X V D L B R T N S H M W F    0.7180999220495582\n        1:  P Y O U C I E A G K J X V D L B R T N S H M F W    0.7180971672628078\n        1:  P Y O U C I E A G K J X M D L B R T N S H F W V    0.7180964438062574\n        1:  P Y O U C I E A G K J X M D L B R T N S H W V F    0.7180949018662536\n        1:  P Y O U C I E A G K J X F D L B R T N S H M W V    0.7180934345911034\n        1:  P Y O U C I E A G K J X M D L B N T R S H V W F    0.7180901732890714\n        1:  P Y O U C I E A G K J X M D L B R T N S H W F V    0.7180876741947388\n        1:  P Y O U C I E A G K J X V D L B N T R S H M W F    0.7180873924053797\n        1:  P Y O U C I E A G K J X B D L F R T N S H M V W    0.718086736748605\n        1:  P Y O U C I E A G K J X M D L B N T R S H W V F    0.7180852303792942\n        1:  P Y O U C I E A G K J X V D L F R T N S H M W B    0.7180849047679467\n        1:  P Y O U C I E A G K J X F D L B N T R S H M W V    0.7180848890895444\n        1:  P Y O U C I E A G K J X F D L B N T R S H M V W    0.7180838326679423\n        1:  P Y O U C I E A G K J X B D L F R T N S H M W V    0.7180824913455095\n        1:  P Y O U C I E A G K J X B D L V R T N S H M W F    0.7180819296424894\n        1:  P Y O U C I E A G K J X V D L F R T N S H M B W    0.7180807088278925\n        1:  P Y O U C I E A G K J X B D L V R T N S H M F W    0.7180798052869541\n        1:  P Y O U C I E A G K J X F D L V R T N S H M W B    0.7180752838218998\n        1:  P Y O U C I E A G K J X B D L V N T R S H M W F    0.7180739642516542\n        1:  P Y O U C I E A G K J X M D L B N T R S H F W V    0.7180726623860667\n        1:  P Y O U C I E A G K J X M D L B N T R S H F V W    0.7180698856502057\n        1:  P Y O U C I E A G K J X F D L V N T R S H M W B    0.7180695175865061\n        1:  P Y O U C I E A G K J X F D L V R T N S H M B W    0.7180690450493254\n        1:  P Y O U C I E A G K J X V D L B R T N S H F M W    0.718068230665415\n        1:  P Y O U C I E A G K J X F D L B R T N S H V M W    0.7180650046624706\n        1:  P Y O U C I E A G K J X M D L F R T N S H V W B    0.7180645832968727\n        1:  B Y O U C I E A G K J X M D L P R T N S H F V W    0.7180610880449253\n        1:  P Y O U C I E A G K J X M D L B N T R S H V F W    0.718059098100305\n        1:  B Y O U C I E A G K J X M D L P R T N S H V W F    0.7180572766323395\n        1:  B Y O U C I E A G K J X M D L P R T N S H V F W    0.7180572391164309\n        1:  P Y O U C I E A G K J X V D L F N T R S H M W B    0.7180528071770316\n    \n    Remove parameter skip_row_0away:\n    Rank:   Layout                                             Score\n    \n        1:  P Y O U C I E A G K J X M D L B R T N S H F V W    0.7119962209823048\n        1:  P Y O U C I E A G K J X M D L B R T N S H V W F    0.7119935642944918\n        1:  P Y O U C I E A G K J X F D L B R T N S H M V W    0.7119892839423186\n        1:  P Y O U C I E A G K J X M D L B R T N S H V F W    0.7119886755944055\n        1:  P Y O U C I E A G K J X V D L B R T N S H M W F    0.7119877706404508\n        1:  P Y O U C I E A G K J X V D L B R T N S H M F W    0.7119857618293355\n        1:  P Y O U C I E A G K J X M D L B R T N S H F W V    0.7119824544766817\n        1:  P Y O U C I E A G K J X M D L B R T N S H W V F    0.7119823857288415\n        1:  P Y O U C I E A G K J X F D L B R T N S H M W V    0.7119817320888235\n        1:  P Y O U C I E A G K J X M D L B N T R S H V W F    0.7119801676153732\n        1:  P Y O U C I E A G K J X M D L B R T N S H W F V    0.7119779203115991\n        1:  P Y O U C I E A G K J X V D L B N T R S H M W F    0.7119768731404442\n        1:  P Y O U C I E A G K J X B D L F R T N S H M V W    0.7119690823253852\n        1:  P Y O U C I E A G K J X M D L B N T R S H W V F    0.7119675838494293\n        1:  P Y O U C I E A G K J X V D L F R T N S H M W B    0.711967421516668\n        1:  P Y O U C I E A G K J X F D L B N T R S H M W V    0.7119666820629079\n        1:  P Y O U C I E A G K J X F D L B N T R S H M V W    0.7119655905051163\n        1:  P Y O U C I E A G K J X B D L F R T N S H M W V    0.7119647785024833\n        1:  P Y O U C I E A G K J X B D L V R T N S H M W F    0.7119626809323344\n        1:  P Y O U C I E A G K J X V D L F R T N S H M B W    0.7119621806482522\n        1:  P Y O U C I E A G K J X B D L V R T N S H M F W    0.711960059760336\n        1:  P Y O U C I E A G K J X F D L V R T N S H M W B    0.7119577766737023\n        1:  P Y O U C I E A G K J X B D L V N T R S H M W F    0.7119569353092454\n        1:  P Y O U C I E A G K J X M D L B N T R S H F W V    0.7119553328582577\n        1:  P Y O U C I E A G K J X M D L B N T R S H F V W    0.711954805869072\n        1:  P Y O U C I E A G K J X F D L V N T R S H M W B    0.7119542544134073\n        1:  P Y O U C I E A G K J X F D L V R T N S H M B W    0.7119532026375411\n        1:  P Y O U C I E A G K J X V D L B R T N S H F M W    0.7119521985201072\n        1:  P Y O U C I E A G K J X F D L B R T N S H V M W    0.7119496994234624\n        1:  P Y O U C I E A G K J X M D L F R T N S H V W B    0.7119468270301366\n        1:  B Y O U C I E A G K J X M D L P R T N S H F V W    0.7119465204299971\n        1:  P Y O U C I E A G K J X M D L B N T R S H V F W    0.7119458020572118\n        1:  B Y O U C I E A G K J X M D L P R T N S H V W F    0.7119430745465182\n    \n    Remove parameter same_finger:\n    Rank:   Layout                                             Score\n    \n        1:  P Y O U C I E A G K J X M D L B R T N S H F V W    0.7305088903561365\n        1:  P Y O U C I E A G K J X M D L B R T N S H V W F    0.7305088221062968\n        1:  P Y O U C I E A G K J X F D L B R T N S H M V W    0.7305045321906731\n        1:  P Y O U C I E A G K J X M D L B R T N S H V F W    0.7304978064616833\n        1:  P Y O U C I E A G K J X V D L B R T N S H M W F    0.7304972592611988\n        1:  P Y O U C I E A G K J X V D L B R T N S H M F W    0.7304970664600646\n        1:  P Y O U C I E A G K J X M D L B R T N S H F W V    0.7304969470386422\n        1:  P Y O U C I E A G K J X M D L B R T N S H W V F    0.7304961549948569\n        1:  P Y O U C I E A G K J X F D L B R T N S H M W V    0.7304925889326935\n        1:  P Y O U C I E A G K J X M D L B N T R S H V W F    0.7304909945455306\n        1:  P Y O U C I E A G K J X M D L B R T N S H W F V    0.7304855511000388\n        1:  P Y O U C I E A G K J X V D L B N T R S H M W F    0.7304791252459462\n        1:  P Y O U C I E A G K J X B D L F R T N S H M V W    0.7304783376899074\n        1:  P Y O U C I E A G K J X M D L B N T R S H W V F    0.7304737147325145\n        1:  P Y O U C I E A G K J X V D L F R T N S H M W B    0.7304717563776391\n        1:  P Y O U C I E A G K J X F D L B N T R S H M W V    0.7304621381081373\n        1:  P Y O U C I E A G K J X F D L B N T R S H M V W    0.7304617119382155\n        1:  P Y O U C I E A G K J X B D L F R T N S H M W V    0.730459455194779\n        1:  P Y O U C I E A G K J X B D L V R T N S H M W F    0.730458612760396\n        1:  P Y O U C I E A G K J X V D L F R T N S H M B W    0.7304554966702766\n\n\n###### Stability Test 1 results: \nWe removed each of 12 scoring parameters one by one and ranked the new scores for the top-scoring layouts for the eight initialized layouts, and the candidate layout was included in all cases except when the outward parameter was removed.\n\n###### Stability Test 2: Compare ranking of all final layouts based on strength and interkey speed\n\nThe strength matrix is calculated above and references a publication documenting \nmeasured finger strengths relevant for typing.\n\nThe speed matrix contains left-right averaged versions of the normalized interkey stroke times derived from the study (averaged to compensate for right-handedness of participants in the study):\n\n\"Estimation of digraph costs for keyboard layout optimization\", \nA Iseri, Ma Eksioglu, International Journal of Industrial Ergonomics, 48, 127-138, 2015.\n\nTo establish which layouts are within a negligible difference of each other after replacing Factors24x24 with the speed matrix, we define an epsilon of 24.3 ms for a single bigram (of the 24^2 possible bigrams), one tenth of the range of times recorded in the study above, which is less than a quarter of the fastest measured digraph tapping speed (30,000/228 = 131.58 ms) recorded in that study:\n\n    \"Digraph-tapping rate changes dramatically across the digraph types. The range is between 82 and 228 taps per 30 s. The difference is nearly three times between the slowest and the fastest digraphs. From this result it can be concluded that the assignment of letter pairs on the correct digraph keys on the keyboard can have a high impact on the typing speed.\"\n\n\n```python\ndata_matrix_strength = Strength24x24\nstrength_scores = []\nfor letters in test_layouts:\n    score = score_layout(data_matrix_strength, letters, bigrams, bigram_frequencies, verbose = False) \n    strength_scores.append(score)\n\nstrength_scores_sorted, strength_ranks_sorted, Isort_strength = rank_within_epsilon(strength_scores, \n                                                                    factor, factor=True, verbose=False)\nprint('\\nRank:   Layout                                             Strength score        Score\\n')\nfor i, rank in enumerate(strength_ranks_sorted):\n    if rank == 1:\n        print('    {0}:  {1}    {2}'.format(rank, test_layout_strings[Isort_strength[i]], \n                                            strength_scores_sorted[i]))\n```\n\n    \n    Rank:   Layout                                             Strength score        Score\n    \n        1:  P Y O U C I E A G K J X F D L V N T R S H M W B    0.790552296798888\n        1:  P Y O U C I E A G K J X F D L B N T R S H M W V    0.790552296798888\n        1:  P Y O U C I E A G K J X F D L B N T R S H M V W    0.790551128272413\n        1:  P Y O U C I E A G K J X M D L B N T R S H F W V    0.7905469726348827\n        1:  P Y O U C I E A G K J X M D L B N T R S H F V W    0.7905458041084077\n        1:  P Y O U C I E A G K J X F D L B R T N S H M W V    0.7905337486626018\n        1:  P Y O U C I E A G K J X F D L V R T N S H M W B    0.7905337486626018\n        1:  P Y O U C I E A G K J X F D L V R T N S H M B W    0.790533595213282\n        1:  P Y O U C I E A G K J X F D L B R T N S H M V W    0.7905325801361268\n        1:  P Y O U C I E A G K J X M D L B R T N S H F W V    0.7905284244985965\n        1:  P Y O U C I E A G K J X B D L V N T R S H M W F    0.790528285570626\n        1:  P Y O U C I E A G K J X B D L F N T R S H M W V    0.7905282855706259\n        1:  B Y O U C I E A G K J X M D L P R T N S H F V W    0.7905272559721213\n        1:  P Y O U C I E A G K J X M D L B R T N S H F V W    0.7905272559721213\n        1:  P Y O U C I E A G K J X V D L B N T R S H M W F    0.7905259170572635\n        1:  P Y O U C I E A G K J X V D L F N T R S H M W B    0.7905259170572635\n        1:  P Y O U C I E A G K J X M D L B N T R S H V F W    0.7905244490794734\n        1:  P Y O U C I E A G K J X B D L V R T N S H M F W    0.7905198745114179\n        1:  P Y O U C I E A G K J X V D L B R T N S H M F W    0.7905175059980556\n        1:  P Y O U C I E A G K J X M D L B N T R S H W V F    0.7905165192190705\n        1:  P Y O U C I E A G K J X M D L B N T R S H V W F    0.7905143120023952\n        1:  P Y O U C I E A G K J X B D L F R T N S H M W V    0.7905097374343397\n        1:  P Y O U C I E A G K J X B D L V R T N S H M W F    0.7905097374343397\n        1:  P Y O U C I E A G K J X M D L B R T N S H W F V    0.7905092766863375\n        1:  P Y O U C I E A G K J X B D L F R T N S H M V W    0.7905085689078645\n        1:  P Y O U C I E A G K J X V D L F R T N S H M W B    0.7905073689209774\n        1:  P Y O U C I E A G K J X V D L B R T N S H M W F    0.7905073689209774\n        1:  P Y O U C I E A G K J X V D L F R T N S H M B W    0.7905072154716575\n        1:  B Y O U C I E A G K J X M D L P R T N S H V F W    0.7905059009431872\n        1:  P Y O U C I E A G K J X M D L B R T N S H V F W    0.7905059009431871\n        1:  P Y O U C I E A G K J X V D L B R T N S H F M W    0.7904994038404374\n        1:  P Y O U C I E A G K J X M D L B R T N S H W V F    0.7904979710827842\n        1:  P Y O U C I E A G K J X M D L F R T N S H W V B    0.7904979710827842\n        1:  P Y O U C I E A G K J X M D L F R T N S H V W B    0.7904957638661089\n        1:  P Y O U C I E A G K J X M D L B R T N S H V W F    0.7904957638661089\n        1:  B Y O U C I E A G K J X M D L P R T N S H V W F    0.7904957638661089\n\n\n\n```python\ndata_matrix_speed = Speed24x24\ntime_range = 243  # ms\nnorm_range = np.max(data_matrix_speed) - np.min(data_matrix_speed)\nms_norm = norm_range / time_range\nepsilon = time_range/10 * ms_norm / (24**2)\n#epsilon = 131.58/2 * ms_norm / (24**2)\nprint('norm_range = {0}'.format(norm_range))  # norm_range = 0.6535662299854439\nprint('ms_norm    = {0}'.format(ms_norm))     # ms_norm    = 0.0026895729629030614\nprint('epsilon    = {0}'.format(epsilon))     # epsilon    = 0.0001134663593724729\nspeed_scores = []\nfor letters in test_layouts:\n    score = score_layout(data_matrix_speed, letters,  bigrams, bigram_frequencies, verbose = False) \n    speed_scores.append(score)\n\nspeed_scores_sorted, speed_ranks_sorted, Isort_speed = rank_within_epsilon(speed_scores, epsilon, factor=False, verbose=False)\n\nprint('\\nRank:   Layout                                             Speed score           Score\\n')\nfor i, rank in enumerate(speed_ranks_sorted):\n    if rank == 1:\n        print('    {0}:  {1}    {2}'.format(rank, test_layout_strings[Isort_speed[i]], \n                                            speed_scores_sorted[i]))\n```\n\n    norm_range = 0.6535662299854439\n    ms_norm    = 0.0026895729629030614\n    epsilon    = 0.0001134663593724729\n    \n    Rank:   Layout                                             Speed score           Score\n    \n        1:  P Y O U C I E A G K J X M D L B N T R S H F W V    0.6954818005723056\n        1:  P Y O U C I E A G K J X M D L B N T R S H F V W    0.6954776917392944\n        1:  P Y O U C I E A G K J X F D L V N T R S H M W B    0.695466646336039\n        1:  P Y O U C I E A G K J X F D L B N T R S H M W V    0.6954648396735867\n        1:  P Y O U C I E A G K J X F D L B N T R S H M V W    0.6954607777198766\n        1:  P Y O U C I E A G K J X M D L B N T R S H V F W    0.6954564343453831\n        1:  P Y O U C I E A G K J X B D L V N T R S H M W F    0.6954538139540986\n        1:  P Y O U C I E A G K J X M D L B N T R S H W V F    0.6954517862512457\n        1:  P Y O U C I E A G K J X M D L B N T R S H V W F    0.6954517061935317\n        1:  P Y O U C I E A G K J X B D L F N T R S H M W V    0.6954496753151306\n        1:  P Y O U C I E A G K J X V D L B N T R S H M W F    0.6954055727283879\n        1:  P Y O U C I E A G K J X V D L F N T R S H M W B    0.695403240751872\n        1:  P Y O U C I E A G K J X M D L B R T N S H F W V    0.6953872779243981\n        1:  P Y O U C I E A G K J X M D L B R T N S H W F V    0.6953860310064606\n        1:  P Y O U C I E A G K J X M D L B R T N S H F V W    0.6953832112060686\n        1:  P Y O U C I E A G K J X M D L B R T N S H W V F    0.6953770804298869\n        1:  P Y O U C I E A G K J X M D L B R T N S H V F W    0.6953764935511715\n        1:  P Y O U C I E A G K J X M D L B R T N S H V W F    0.6953716096929274\n        1:  P Y O U C I E A G K J X M D L F R T N S H W V B    0.6953713093074937\n\n\n#### Stability Test 2 results: \n\nThe candidate layout is tied for first place after replacing Factors24x24 with the strength matrix or the speed matrix and re-ranking the top-scoring layouts for the eight initialized layouts.\n\n\n```python\nwinner24 = ['P','Y','O','U', 'C','I','E','A', 'G','K','J','X', 'B','D','L','V', 'N','T','R','S', 'H','M','W','F']\n\nprint_layout24(winner24)\nprint('')\nprint_layout24_instances(winner24, letters24, instances24, bigrams, bigram_frequencies)\n```\n\n        P Y O U  B D L V\n        C I E A  N T R S\n        G K J X  H M W F\n    \n         76  59 272  97   53 136 145  38\n        119 270 445 287  258 331 224 232\n         67  19   6   8  180  90  60  86\n    \n        left: 1.725T  right: 1.831T (6.09%)\n        Total same-finger bigram frequencies:     28566588041\n\n\n### Optional Stability Test 3. Compare score of the winning layout after rearranging random letters\n\n\n```python\nrun_test3 = False\nif run_test3:\n    original_score = score_layout(Factors24x24, winner24, bigrams, bigram_frequencies, verbose=False) \n    nunber_of_tests = 1000\n    size_random_set = 8\n    indices = [0,1, 8,9,10,11, 12,15, 20,21,22,23]\n    #  0  1  -  -       12  -  - 15\n    #  -  -  -  -        -  -  -  -\n    #  8  9 10 11        - 21 22 23\n\n    print(original_score)\n\n    for i in range(nunber_of_tests):\n        letters_copy = winner24.copy()    \n        random_indices = []\n        while np.size(random_indices) < size_random_set:\n            random_index = indices[np.int( np.round( (np.size(indices) - 1) * np.random.random(1) )[0])]\n            if random_index not in random_indices:\n                random_indices.append(random_index)   \n        for irand in random_indices:\n            letters_copy[np.int(irand)] = ''\n\n        top_permutation_test1, letter_permutations_test1, scores_test1 = permute_optimize(letters_copy, \n                            letters24, keys24, Factors24x24, bigrams, bigram_frequencies, verbose=False, ntop=0)\n\n        print(i)\n        if ''.join(top_permutation_test1) != ''.join(winner24) and max(scores_test1) > original_score:\n            print(max(scores_test1))\n            print(*top_permutation_test1)\n```\n\n### Stability Test results\n    \nTest 1: We removed each of 12 scoring parameters one by one and ranked the new scores for the top-scoring layouts for the eight initialized layouts, and the candidate layout was included in all cases except when the outward parameter was removed.\n\nTest 2: The candidate layout is tied for first place after replacing Factors24x24 with the strength matrix or the speed matrix and re-ranking the top-scoring layouts for the eight initialized layouts.\n\n### Assign letters Z and Q and test left/right swap\n\nTest to see if equal or higher scores are obtained for the following:\n\n    1. Assign Z and Q to keys 112 and 113\n    2. Swap left and right sides\n\n\n```python\nlayouts_26letters = [\n    ['P','Y','O','U', 'C','I','E','A', 'G','K','J','X', 'B','D','L','V', 'R','T','N','S', 'H','M','W','F', \"'\",',','-', '\"','.','?', 'Z','Q'],\n    ['P','Y','O','U', 'C','I','E','A', 'G','K','J','X', 'B','D','L','V', 'R','T','N','S', 'H','M','W','F', \"'\",',','-', '\"','.','?', 'Q','Z'],\n    ['V','L','D','B', 'S','N','T','R', 'F','W','M','H', 'U','O','Y','P', 'A','E','I','C', 'X','J','K','G', \"'\",',','-', '\"','.','?', 'Z','Q'],\n    ['V','L','D','B', 'S','N','T','R', 'F','W','M','H', 'U','O','Y','P', 'A','E','I','C', 'X','J','K','G', \"'\",',','-', '\"','.','?', 'Q','Z']]\ndata_matrix = Factors32x32\nscores_26letters = []\nfor layout_26letters in layouts_26letters:\n    scores_26letters.append(score_layout(data_matrix, layout_26letters, bigrams, bigram_frequencies, verbose=False))\n\nscores_26letters_sorted, ranks_26letters_sorted, Isort_26letters = rank_within_epsilon(scores_26letters, \n                                                                        factor, factor=True, verbose=False)\nprint('\\nRank:   Layout                                             Score\\n')\nfor i, rank in enumerate(ranks_26letters_sorted):\n    layout = ' '.join(layouts_26letters[Isort_26letters[i]])\n    print('    {0}:  {1}    {2}'.format(rank, layout, scores_26letters_sorted[i]))\n```\n\n    \n    Rank:   Layout                                             Score\n    \n        1:  P Y O U C I E A G K J X B D L V R T N S H M W F ' , - \" . ? Q Z    0.6168126351406974\n        1:  P Y O U C I E A G K J X B D L V R T N S H M W F ' , - \" . ? Z Q    0.6168125360150648\n        1:  V L D B S N T R F W M H U O Y P A E I C X J K G ' , - \" . ? Q Z    0.6168072831782996\n        1:  V L D B S N T R F W M H U O Y P A E I C X J K G ' , - \" . ? Z Q    0.6168001137557619\n\n\nLeft/right swapped:\n\n    V L D B  U O Y P Q\n    S N T R  A E I C Z\n    F W M H  X J K G\n    \nAll layouts tied for first place:\n\n    Rank                                                                   Score\n    1:  P Y O U C I E A G K J X B D L V R T N S H M W F ' , - \" . ? Q Z    0.6168126351406974\n    1:  P Y O U C I E A G K J X B D L V R T N S H M W F ' , - \" . ? Z Q    0.6168125360150648\n    1:  V L D B S N T R F W M H U O Y P A E I C X J K G ' , - \" . ? Q Z    0.6168072831782996\n    1:  V L D B S N T R F W M H U O Y P A E I C X J K G ' , - \" . ? Z Q    0.6168001137557619\n    \nFinal set of letters:\n\n    P Y O U  B D L V Q\n    C I E A  N T R S Z\n    G K J X  H M W F\n\n     76  59 272  97   53 136 145  38\n    119 270 445 287  258 331 224 232\n     67  19   6   8  180  90  60  86\n\n    left: 1.725T  right: 1.831T (6.09%)\n    Total same-finger bigram frequencies:  28,566,588,041\n\n## Step 5: Arrange non-letter characters in easy-to-remember places <a name=\"step5\">\n    \nNow that we have all 26 letters accounted for, we turn our attention to non-letter characters, taking into account frequency of punctuation and ease of recall.\n\n### Frequency of punctuation marks\n\n  - Statistical values of punctuation frequency in 20 English-speaking countries (Table 1): <br>\nSun, Kun & Wang, Rong. (2018). Frequency Distributions of Punctuation Marks in English: Evidence from Large-scale Corpora. English Today. 10.1017/S0266078418000512. <br> \nhttps://www.researchgate.net/publication/328512136_Frequency_Distributions_of_Punctuation_Marks_in_English_Evidence_from_Large-scale_Corpora\n  <br>\"frequency of punctuation marks attested for twenty English-speaking countries and regions... The data were acquired through GloWbE.\"\n  \"The corpus of GloWbE (2013) is a large English corpus collecting international English from the internet, containing about 1.9 billion words of text from twenty different countries. For further information on the corpora used, see https://corpus.byu.edu/.\"\n  \n  - Google N-grams and Twitter analysis: <br>\n\"Punctuation Input on Touchscreen Keyboards: Analyzing Frequency of Use and Costs\" <br>\nS Malik, L Findlater - College Park: The Human-Computer Interaction Lab. 2013 <br>\nhttps://www.cs.umd.edu/sites/default/files/scholarly_papers/Malik.pdf <br>\n \"the Twitter corpora included substantially higher punctuation use than the Google corpus,  <br>\n comprising 7.5% of characters in the mobile tweets and 7.6% in desktop versus only 4.4%...  <br>\nWith the Google corpus,only 6 punctuation symbols (. -\u2019 ( ) \u201c) appeared more frequently than [q]\"\n\n  - \"Frequencies for English Punctuation Marks\" by Vivian Cook <br>\nhttp://www.viviancook.uk/Punctuation/PunctFigs.htm  <br>\n \"Based on a writing system corpus some 459 thousand words long.  <br> \n This includes three novels of different types (276 thousand words),  <br>\n selections of articles from two newspapers (55 thousand), <br> \none bureaucratic report (94 thousand), and assorted academic papers <br>\non language topics (34 thousand). More information is in <br>\nCook, V.J. (2013) \u2018Standard punctuation and the punctuation of the street\u2019 <br>\nin M. Pawlak and L. Aronin (eds.), Essential Topics in Applied Linguistics and Multilingualism,  <br>\n Springer International Publishing Switzerland (2013), 267-290\"\n\n  - \"A Statistical Study of Current Usage in Punctuation\": <br>\nRuhlen, H., & Pressey, S. (1924). A Statistical Study of Current Usage in Punctuation. The English Journal, 13(5), 325-331. doi:10.2307/802253\n\n  - \"Computer Languages Character Frequency\"\nby Xah Lee.  <br>\nDate: 2013-05-23. Last updated: 2020-06-29. <br>\nhttp://xahlee.info/comp/computer_language_char_distribution.html <br>\nNOTE: biased toward C (19.8%) and Py (18.5%), which have high use of \"_\".\n\nFrequency: \n\n             Sun:     Malik:   Ruhlen:    Cook:            Xah:\n              /1M   N-gram %   /10,000   /1,000       All%  JS%   Py%\n\n    .    42840.02      1.151       535     65.3       6.6   9.4  10.3\n    ,    44189.96                  556     61.6       5.8   8.9   7.5\n    \"                  2.284        44     26.7       3.9   1.6   6.2\n    '     2980.35      0.200        40     24.3       4.4   4.0   8.6\n    -     9529.78      0.217        21     15.3       4.1   1.9   3.0\n    ()    4500.81      0.140         7                7.4   9.8   8.1\n    ;     1355.22      0.096        22      3.2       3.8   8.6\n    z                  0.09                   -         -\n    :     3221.82      0.087        11      3.4       3.5   2.8   4.7\n    ?     4154.78      0.032        14      5.6       0.3\n    /                  0.019                          4.0   4.9   1.1\n    !     2057.22      0.013         3      3.3       0.4\n    _                  0.001                         11.0   2.9  10.5\n    =                                                 4.4  10.7   5.4\n    *                                                 3.6   2.1\n    >                                                 3.0         1.4\n    $                                                 2.7   1.6\n    #                                                 2.2         3.2\n    {}                                                1.9   4.2\n    <                                                 1.3\n    &                                                 1.3\n    \\                                                 1.2         1.1\n    []                                                0.9   1.9   1.2\n    @                                                 0.8\n    |                                                 0.6\n    +                                                 0.6   1.9\n    %                                                 0.4\n\n### Add punctuation keys and number keys\n\nWe will assign the most frequent punctuation according to Sun, et al (2018) to the six keys in the middle two columns:  . , \" ' - ? ; : () ! _\n\n            P Y O U  '   \"   B D L V Q\n            C I E A  ,   .   N T R S Z\n            G K J X  -   ?   H M W F\n\nWe will use the Shift key to group similar punctuation marks (separating and joining marks in the left middle column and closing marks in the right middle column):\n\n            P Y O U  '(  \")  B D L V Q\n            C I E A  ,;  .:  N T R S Z\n            G K J X  -_  ?!  H M W F\n \n**Separating marks (left)**: The comma separates text in lists; the semicolon can be used in place of the comma to separate items in a list (especially if these items contain commas); open parenthesis sets off an explanatory word, phrase, or sentence. \n\n**Joining marks (left)**: The apostrophe joins words as contractions; the hyphen joins words as compounds; the underscore joins words in cases where whitespace characters are not permitted (such as in variables or file names). \n\n**Closing marks (right)**: A sentence usually ends with a period, question mark, or exclamation mark. The colon ends one statement but precedes the following: an explanation, quotation, list, etc. Double quotes and close parenthesis closes a word, clause, or sentence separated by an open parenthesis.\n\n**Number keys**: \nThe numbers are flanked to the left and right by [square brackets], and {curly brackets} accessed by the Shift key. Each of the numbers is paired with a mathematical or logic symbol accessed by the Shift key:\n    \n    { | = ~ +   <  >   ^ & % * } \\\n    [ 1 2 3 4   5  6   7 8 9 0 ] /\n\n    1: | (vertical bar or \"pipe\" represents the logical OR operator: 1 stroke, looks like the number one)\n    2: = (equal: 2 strokes, like the Chinese character for \"2\")\n    3: ~ (tilde: \"almost equal\", often written with 3 strokes, like the Chinese character for \"3\")\n    4: + (plus: has four quadrants; resembles \"4\")\n    5 & 6: < > (\"less/greater than\"; these angle brackets are directly above the other bracket keys)\n    7: ^ (caret for logical XOR operator as well as exponentiation; resembles \"7\")\n    8: & (ampersand: logical AND operator; resembles \"8\")\n    9: % (percent: related to division; resembles \"9\")\n    0: * (asterisk: for multiplication; resembles \"0\") \n\nThe three remaining keys in many common keyboards (flanking the upper right hand corner Backspace key) are displaced in special keyboards, such as the Kinesis Advantage and Ergodox. For the top right key, we will assign the forward slash and backslash: / \\\\. For the remaining two keys, we will assign two symbols that in modern usage have significance in social media: the hash/pound sign and the \"at sign\". The hash or hashtag identifies digital content on a specific topic (the Shift key accesses the dollar sign). The \"at sign\" identifies a location or affiliation (such as in email addresses) and acts as a \"handle\" to identify users in popular social media platforms and online forums.\n\nThe resulting Exgram layout:\n\n          { | = ~ +   <  >   ^ & % * } \\\n          [ 1 2 3 4   5  6   7 8 9 0 ] /\n\n            P Y O U  '(  \")  B D L V Q\n            C I E A  ,;  .:  N T R S Z\n            G K J X  -_  ?!  H M W F\n\n\n```python\n\n```\n", "meta": {"hexsha": "000e4c11d07083f1ec8dbd67d1a5089a62385e90", "size": 489213, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "exgram_layout_v1.0.ipynb", "max_stars_repo_name": "sunaku/engram", "max_stars_repo_head_hexsha": "f0a532112e5f03b2e906532c5b72c4fc9bc26eba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exgram_layout_v1.0.ipynb", "max_issues_repo_name": "sunaku/engram", "max_issues_repo_head_hexsha": "f0a532112e5f03b2e906532c5b72c4fc9bc26eba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exgram_layout_v1.0.ipynb", "max_forks_repo_name": "sunaku/engram", "max_forks_repo_head_hexsha": "f0a532112e5f03b2e906532c5b72c4fc9bc26eba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 79.4048044149, "max_line_length": 16340, "alphanum_fraction": 0.6424154714, "converted": true, "num_tokens": 94586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.0769608420473065, "lm_q1q2_score": 0.03607852136904018}}
{"text": "# Wrapping up our CNN\n\nFirst of all, don't worry: this is meant to take a while!\n\nAlso we cover software engineering because we think that data scientists should be good software engineers.\n\nToday we're going to start to move from a minimal training loop to something that is SoTA on ImageNet, things we'll cover:\n\n- Cuda\n- Convolutions\n- Hooks\n- Normalization\n- Transforms\n- Data Blocks\n- Label Smoothing\n- Optimization\n- Weight Decay\n- Skip Connection Architectures\n\n\n```python\n%load_ext autoreload\n%autoreload 2\n%matplotlib inline\n```\n\n\n```python\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n```\n\n\n```python\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n```\n\n## Callbacks\n\n### Callbacks as GUI events\n\n\n```python\nimport ipywidgets as widgets\n```\n\n\n```python\ndef f(o):\n    print('hi')\n```\n\n\n```python\nw = widgets.Button(description='Click Me')\n```\n\n\n```python\nw\n```\n\n\n    Button(description='Click Me', style=ButtonStyle())\n\n\n\n```python\nw.on_click(f)\n```\n\nMeaning, when a click event occurs, **callback** to the function f.\n\n### Creating Your Own Callback\n\n\n```python\nfrom time import sleep\n```\n\n\n```python\ndef slow_calculation():\n    res = 0\n    for i in range(5):\n        res += i*i\n        sleep(1)\n    return res\n```\n\n\n```python\nslow_calculation()\n```\n\n\n\n\n    30\n\n\n\nImagine yourself training a deep learning model, you really want to know how it's going. We simulated slow loops by writing `slow_calculation()` and now we're going to inject a call back to check how it's doing while running:\n\n\n```python\ndef slow_calculation(cb=None):\n    res = 0\n    for i in range(5):\n        res += i*i\n        sleep(1)\n        if cb:\n            cb(i)\n    return res\n```\n\n\n```python\ndef show_progress(epoch):\n    print(f\"Awesome! We've finished epoch {epoch}!\")\n```\n\n\n```python\nslow_calculation(show_progress)\n```\n\n    Awesome! We've finished epoch 0!\n    Awesome! We've finished epoch 1!\n    Awesome! We've finished epoch 2!\n    Awesome! We've finished epoch 3!\n    Awesome! We've finished epoch 4!\n\n\n\n\n\n    30\n\n\n\n### Lambdas & Partials\n\n\n```python\nslow_calculation(lambda epoch: print(f\"Awesome! We've finished epoch {epoch}!\"))\n```\n\n    Awesome! We've finished epoch 0!\n    Awesome! We've finished epoch 1!\n    Awesome! We've finished epoch 2!\n    Awesome! We've finished epoch 3!\n    Awesome! We've finished epoch 4!\n\n\n\n\n\n    30\n\n\n\n\n```python\ndef show_progress(exclamation, epoch):\n    print(f\"{exclamation} We've finished epoch {epoch}!\")\n```\n\n\n```python\nslow_calculation(lambda epoch: show_progress(\"OK I guess\", epoch))\n```\n\n    OK I guess We've finished epoch 0!\n    OK I guess We've finished epoch 1!\n    OK I guess We've finished epoch 2!\n    OK I guess We've finished epoch 3!\n    OK I guess We've finished epoch 4!\n\n\n\n\n\n    30\n\n\n\n\n```python\ndef make_show_progress(exclamation):\n    _inner = lambda epoch: print(f\"{exclamation}! We've finished epoch {epoch}!\")\n    return _inner\n```\n\n\n```python\nslow_calculation(make_show_progress(\"Nice\"))\n```\n\n    Nice! We've finished epoch 0!\n    Nice! We've finished epoch 1!\n    Nice! We've finished epoch 2!\n    Nice! We've finished epoch 3!\n    Nice! We've finished epoch 4!\n\n\n\n\n\n    30\n\n\n\nYou might see it done like this instead:\n\n\n```python\ndef make_show_progress(exclamation):\n    def _inner(epoch):\n        print(f\"{exclamation}! We've finished epoch {epoch}!\")\n    return _inner\n```\n\n\n```python\nslow_calculation(make_show_progress(\"Nice\"))\n```\n\n    Nice! We've finished epoch 0!\n    Nice! We've finished epoch 1!\n    Nice! We've finished epoch 2!\n    Nice! We've finished epoch 3!\n    Nice! We've finished epoch 4!\n\n\n\n\n\n    30\n\n\n\n\n```python\nslow_calculation(make_show_progress(\"Amazing\"))\n```\n\n    Amazing! We've finished epoch 0!\n    Amazing! We've finished epoch 1!\n    Amazing! We've finished epoch 2!\n    Amazing! We've finished epoch 3!\n    Amazing! We've finished epoch 4!\n\n\n\n\n\n    30\n\n\n\nBecause this feature is used soo much, python has `partials`:\n\n\n```python\nfrom functools import partial\n```\n\n\n```python\nslow_calculation(partial(show_progress, \"OK I guess\"))\n```\n\n    OK I guess We've finished epoch 0!\n    OK I guess We've finished epoch 1!\n    OK I guess We've finished epoch 2!\n    OK I guess We've finished epoch 3!\n    OK I guess We've finished epoch 4!\n\n\n\n\n\n    30\n\n\n\n\n```python\nf2 = partial(show_progress, \"OK I guess\")\n```\n\n\n```python\nslow_calculation(f2)\n```\n\n    OK I guess We've finished epoch 0!\n    OK I guess We've finished epoch 1!\n    OK I guess We've finished epoch 2!\n    OK I guess We've finished epoch 3!\n    OK I guess We've finished epoch 4!\n\n\n\n\n\n    30\n\n\n\n### Callbacks as Callable Classes\n\n\n```python\nclass ProgressShowingCallback():\n    def __init__(self, exclamation=\"Awesome\"):\n        self.exclamation = exclamation\n    \n    def __call__(self, epoch):\n        print(f\"{self.exclamation}! We've finished epoch {epoch}!\")\n```\n\n\n```python\ncb = ProgressShowingCallback(\"Just Super\")\n```\n\n\n```python\nslow_calculation(cb)\n```\n\n    Just Super! We've finished epoch 0!\n    Just Super! We've finished epoch 1!\n    Just Super! We've finished epoch 2!\n    Just Super! We've finished epoch 3!\n    Just Super! We've finished epoch 4!\n\n\n\n\n\n    30\n\n\n\n### Multiple callback funcs; `*args` and `**kwargs`\n\n\n```python\ndef f(*args, **kwargs):\n    print(f\"args: {args}; kwargs: {kwargs}\")\n```\n\n\n```python\nf(3, 'a', thing1='Hello')\n```\n\n    args: (3, 'a'); kwargs: {'thing1': 'Hello'}\n\n\n\n```python\ndef slow_calculation(cb=None):\n    res = 0\n    for i in range(5):\n        if cb:\n            cb.before_calc(i)\n        res += i*i\n        sleep(1)\n        if cb:\n            cb.after_calc(i, val=res)\n    return res\n```\n\nLet's create a callback class for the function:\n\n\n```python\nclass PrintStepCallBack():\n    def __init__(self):\n        pass\n    \n    def before_calc(self, *args, **kwargs):\n        print(f\"About to start\")\n    \n    def after_calc(self, *args, **kwargs):\n        print(f\"Done step\")\n```\n\n\n```python\nslow_calculation(PrintStepCallBack())\n```\n\n    About to start\n    Done step\n    About to start\n    Done step\n    About to start\n    Done step\n    About to start\n    Done step\n    About to start\n    Done step\n\n\n\n\n\n    30\n\n\n\nIn the previous example we didn't get an error because we used `*args` and `**kwargs`, effectively ignoring the passed parameters.\n\nLet's now use them:\n\n\n```python\nclass PrintStatusCallBack():\n    def __init__(self):\n        pass\n    \n    def before_calc(self, epoch, **kwargs):\n        print(f\"About to start: {epoch}\")\n    \n    def after_calc(self, epoch, val, **kwargs):\n        print(f\"Done step {epoch}: {val}\")\n```\n\n\n```python\nslow_calculation(PrintStatusCallBack())\n```\n\n    About to start: 0\n    Done step 0: 0\n    About to start: 1\n    Done step 1: 1\n    About to start: 2\n    Done step 2: 5\n    About to start: 3\n    Done step 3: 14\n    About to start: 4\n    Done step 4: 30\n\n\n\n\n\n    30\n\n\n\n`**kwargs` are kept because we might add other parameters in the future and we don't want to break if the user added non-existing parameters, it makes the class more resilient.\n\n### Modifying Behavior\n\n\n```python\ndef slow_calculation(cb=None):\n    res = 0\n    for i in range(5):\n        if cb and hasattr(cb, \"before_calc\"):\n            cb.before_calc(i)\n        res += i*i\n        sleep(1)\n        if cb and hasattr(cb, \"after_calc\"):\n            if cb.after_calc(i, val=res):\n                print(\"Stopping early\")\n                break\n    return res\n```\n\n\n```python\nclass PrintAfterCallBack():\n    def after_calc(self, epoch, val, **kwargs):\n        print(f\"Done step {epoch}: {val}\")\n        if val > 10:\n            return True\n```\n\n\n```python\nslow_calculation(PrintAfterCallBack())\n```\n\n    Done step 0: 0\n    Done step 1: 1\n    Done step 2: 5\n    Done step 3: 14\n    Stopping early\n\n\n\n\n\n    14\n\n\n\nNext, we want to alter the calculation itself:\n\n\n```python\nclass SlowCalculator():\n    def __init__(self, cb=None):\n        self.cb = cb\n        self.res = 0\n    \n    def callback(self, cb_name, *args):\n        if not self.cb:\n            return\n        cb = getattr(self.cb, cb_name, None)\n        if cb:\n            return cb(self, *args)\n    \n    def calc(self):\n        for i in range(5):\n            self.callback('before_calc', i)\n            self.res += i*i\n            sleep(1)\n            if self.callback('after_calc', i):\n                print(\"Stopping Early\")\n                break\n```\n\n\n```python\nclass ModifyingCallBack():\n    def after_calc(self, calc, epoch):\n        print(f\"After epoch {epoch}: {calc.res}\")\n        if calc.res > 10:\n            return True\n        if calc.res < 3:\n            calc.res = calc.res*2\n```\n\n\n```python\ncalculator = SlowCalculator(ModifyingCallBack())\n```\n\n\n```python\ncalculator.calc()\n```\n\n    After epoch 0: 0\n    After epoch 1: 1\n    After epoch 2: 6\n    After epoch 3: 15\n    Stopping Early\n\n\nThis represent the extend of our callback functionalities that we use in FastAI.\n\n### `__dunder__` thingies\n\n\n```python\nclass SloppyAdder():\n    def __init__(self, o):\n        self.o = o\n    \n    def __add__(self, b):\n        return SloppyAdder(self.o + b.o + 0.01)\n    \n    def __repr__(self):\n        return str(self.o)\n```\n\n\n```python\na = SloppyAdder(1)\nb = SloppyAdder(2)\na + b\n```\n\n\n\n\n    3.01\n\n\n\nSpecial Methods I should know:\n\n- [x] __getitem__\n- [ ] __getattr__\n- [ ] __setattr__\n- [ ] __del__\n- [x] __init__\n- [ ] __new__\n- [ ] __enter__\n- [ ] __exit__\n- [x] __len__\n- [x] __repr__\n- [ ] __str__\n\n## Browsing Source Code\n\nLearn to do these things in our editor of choice:\n\n- [ ] Jump to tag/symbol by with (with completion)\n    - Symbol: class/fucntion/...\n- [ ] Jump to current tag\n    - By clicking on the tag\n- [ ] Jump to library tags\n- [ ] Go back\n    - To the place you were working in (in the file)\n- [ ] Search\n- [ ] Outlining/Folding\n\n## Variance & Stuff\n\n### Variance\n\nVariance is the average of how far each data point is from the mean $\\mu$.\n\n\n```python\nt = torch.Tensor([1., 2., 4., 18.])\n```\n\n\n```python\nm = t.mean(); m\n```\n\n\n\n\n    tensor(6.2500)\n\n\n\n\n```python\n(t-m).mean()\n```\n\n\n\n\n    tensor(0.)\n\n\n\nWe can't do that because all of the negative/positive differences cancel-out, so we can fix that in one of two ways:\n\n\n```python\n(t-m).pow(2).mean()\n```\n\n\n\n\n    tensor(47.1875)\n\n\n\nThe **mean absolute deviation**:\n\n\n```python\n# Or..\n(t-m).abs().mean()\n```\n\n\n\n\n    tensor(5.8750)\n\n\n\nLet's undo the squaring that happened for the first solution, we present the **standard deviation**:\n\n\n```python\n(t-m).pow(2).mean().sqrt()\n```\n\n\n\n\n    tensor(6.8693)\n\n\n\nthey're still different, why?\n\nBecause of the squaring mechanism, standard deviation is more sensitive to outliers.\n\nHere's a useful thing to note about variance:\n\n\n```python\n(t-m).pow(2).mean(), (t*t).mean() - (m*m)\n```\n\n\n\n\n    (tensor(47.1875), tensor(47.1875))\n\n\n\nOr:\n\n$$Var(X)=\\frac{1}{m}\\sum_{i=1}^{m}x_{i}^{2}-\\mu^2=E[X^2]-E[X]^2$$\n\nThe important thing is that this formula is much more easier to work with. In particular, you only have to track two things:\n\n1. The sum of the data\n2. The sum of squares of the data\n\nWhereas in the original formula you have to go through all of the data twice, once to calculate the mean & once to calculate the variance.\n\n### Covariance & Correlation \n\nHere's how wikipedia defines covariance:\n\n$$Cov(X,Y)=E[(X-E[X])(Y-E[Y])]$$\n\n\n```python\nt\n```\n\n\n\n\n    tensor([ 1.,  2.,  4., 18.])\n\n\n\nLet's see that in code, So now we need two vectors:\n\n\n```python\n# `u` is twice as `t` plus a little bit of randomness\nu = t * 2 \nu += torch.randn_like(t)/10+0.95\n```\n\n\n```python\nplt.scatter(t, u)\n```\n\n\n```python\nprod = (t-t.mean())*(u-u.mean())\nprod\n```\n\n\n\n\n    tensor([ 54.6310,  36.4790,  10.1660, 276.2119])\n\n\n\n\n```python\nprod.mean()\n```\n\n\n\n\n    tensor(94.3720)\n\n\n\nLet's compare the previous average with the next:\n\n\n```python\nv = torch.randn_like(t)\n```\n\n\n```python\nplt.scatter(t, v)\n```\n\n\n```python\nprod = (t-t.mean())*(v-v.mean())\nprod\n```\n\n\n\n\n    tensor([-0.5332,  2.9161, -0.4431,  4.5549])\n\n\n\n\n```python\nprod.mean()\n```\n\n\n\n\n    tensor(1.6237)\n\n\n\nCovariance tells you how random variables vary jointly, you can also calculate it as follows:\n\n$$Cov(X,Y)=E[XY]-E[X]E[Y]$$\n\n\n```python\ncov = (t*u).mean() - (t.mean()*u.mean())\ncov\n```\n\n\n\n\n    tensor(94.3720)\n\n\n\nFinally, here is the pearson correlation coefficient:\n\n$$p_{X,Y}=\\frac{Cov(X,Y)}{\\sigma_{X}\\sigma_{Y}}$$\n\n\n```python\ncov / (t.std() * u.std())\n```\n\n\n\n\n    tensor(0.7500)\n\n\n\nThis is just a scaled version so that the output is $\\in [-1,1]$.\n\nRemember that Covariance and its pearson coefficient describe **linear** variations.\n\n## Softmax\n\nHere's our final `logsoftmax` definition:\n\n\n```python\ndef log_softmax(x):\n    return x - x.exp().sum(-1, keepdim=True).log()\n```\n\nWhich is:\n\n$$logsoftmax(x)_i=x_i - log\\sum_{j}e^{x_j}$$\n\nAnd our cross entropy loss is:\n\n$$-log(p_i)$$\n\nA big problem with softmax is that it **must** pick something, so even if the activation values of the last layer are negative (signaling the absence of all classes from an example image) the softmax function will force a probability distribution that sum up to one so that a class can be picked.\n\nAnother problem that happens is when you have multiple classes present in the image, in this case even the present classes will get minimized by the softmax function in favor of the class associated with the highest activation to be picked.\n\nMeaning, softmax is terrible except if you definately know that, per image, you have only one and no more or less than one \"class\" present in the image.\n\nIf your not sure, use this:\n\n$$S(x)=\\frac{e^x}{1+{e^x}}$$\n\nAnd because, for the most part, you won't be sure, **don't use softmax**. \n\n---\n\n# Early Stopping\n\n\n## Better callback cancelation\n\n\n```python\nfrom fastai import datasets\nfrom torch import tensor\nfrom torch.utils.data import Dataset, DataLoader\nimport gzip, pickle\nfrom torch import optim\nimport re\n```\n\n\n```python\ndef get_data(MNIST_URL = 'http://deeplearning.net/data/mnist/mnist.pkl'):\n    path = datasets.download_data(MNIST_URL, ext='.gz')\n    with gzip.open(path, 'rb') as f:\n        ((X_train, y_train), (X_val, y_val), _) = pickle.load(f, encoding='latin-1')\n    return map(tensor, (X_train, y_train, X_val, y_val))\n\ndef normalize(x, m, s):\n    return (x-m)/s\n```\n\n\n```python\nX_train, y_train, X_valid, y_valid = get_data()\n```\n\n\n```python\ndatasets.download_data??\n```\n\n\n```python\nclass Dataset():\n    def __init__(self, x, y):\n        self.x = x\n        self.y = y\n    \n    def __len__(self):\n        return len(self.x)\n    \n    def __getitem__(self, idx):\n        return self.x[idx], self.y[idx]\n```\n\n\n```python\ntrain_ds, val_ds = Dataset(X_train, y_train), Dataset(X_valid, y_valid)\n```\n\n\n```python\nnh, bs = 50, 512\n```\n\n\n```python\nc = y_train.max().item() + 1\n```\n\n\n```python\nloss_func = F.cross_entropy\n```\n\n\n```python\ndef get_dls(train_ds, valid_ds, bs, **kwargs):\n    \"\"\"Returns the dataloaders for both the training and validation sets\"\"\"\n    return (DataLoader(train_ds, batch_size=bs, shuffle=True, **kwargs),\n            DataLoader(valid_ds, batch_size=bs*2, **kwargs))\n\n\nclass DataBunch():\n    def __init__(self, train_dl, val_dl, c=None):\n        self.train_dl, self.val_dl, self.c = train_dl, val_dl, c\n    \n    @property\n    def train_ds(self):\n        return self.train_dl.dataset\n    \n    @property\n    def valid_ds(self):\n        return self.val_dl.dataset\n```\n\n\n```python\ndata = DataBunch(*get_dls(train_ds, val_ds, bs), c)\n```\n\n\n```python\nclass Callback():\n    _order=0\n    def set_runner(self, run): self.run=run\n    def __getattr__(self, k): return getattr(self.run, k)\n    @property\n    def name(self):\n        name = re.sub(r'Callback$', '', self.__class__.__name__)\n        return camel2snake(name or 'callback')\n    \n    def __call__(self, cb_name):\n        f = getattr(self, cb_name, None)\n        if f and f():\n            return True\n        return False\n\nclass TrainEvalCallback(Callback):\n    def begin_fit(self):\n        self.run.n_epochs=0.\n        self.run.n_iter=0\n    \n    def after_batch(self):\n        if not self.in_train: return\n        self.run.n_epochs += 1./self.iters\n        self.run.n_iter   += 1\n        \n    def begin_epoch(self):\n        self.run.n_epochs=self.epoch\n        self.model.train()\n        self.run.in_train=True\n\n    def begin_validate(self):\n        self.model.eval()\n        self.run.in_train=False\n        \nclass CancelTrainException(Exception):\n    pass\nclass CancelEpochException(Exception):\n    pass\nclass CancelBatchException(Exception):\n    pass\n```\n\n\n```python\nclass Runner():\n    def __init__(self, cbs=None, cb_funcs=None):\n        cbs = listify(cbs)\n        for cbf in listify(cb_funcs):\n            cb = cbf()\n            setattr(self, cb.name, cb)\n            cbs.append(cb)\n        self.stop,self.cbs = False,[TrainEvalCallback()]+cbs\n\n    @property\n    def opt(self):       return self.learn.opt\n    @property\n    def model(self):     return self.learn.model\n    @property\n    def loss_func(self): return self.learn.loss_func\n    @property\n    def data(self):      return self.learn.data\n\n    def one_batch(self, xb, yb):\n        self.xb,self.yb = xb,yb\n        if self('begin_batch'): return\n        self.pred = self.model(self.xb)\n        if self('after_pred'): return\n        self.loss = self.loss_func(self.pred, self.yb)\n        if self('after_loss') or not self.in_train: return\n        self.loss.backward()\n        if self('after_backward'): return\n        self.opt.step()\n        if self('after_step'): return\n        self.opt.zero_grad()\n\n    def all_batches(self, dl):\n        self.iters = len(dl)\n        for xb,yb in dl:\n            if self.stop: break\n            self.one_batch(xb, yb)\n            self('after_batch')\n        self.stop=False\n        \n    def fit(self, epochs, learn):\n        self.epochs,self.learn = epochs,learn\n\n        try:\n            for cb in self.cbs: cb.set_runner(self)\n            if self('begin_fit'): return\n            for epoch in range(epochs):\n                self.epoch = epoch\n                if not self('begin_epoch'): self.all_batches(self.data.train_dl)\n\n                with torch.no_grad(): \n                    if not self('begin_validate'): self.all_batches(self.data.val_dl)\n                if self('after_epoch'): break\n\n        except CancelTrainException:\n            self('after_cancel_train')\n        finally:\n            self('after_fit')\n            self.learn = None\n\n    def __call__(self, cb_name):\n        for cb in sorted(self.cbs, key=lambda x: x._order):\n            f = getattr(cb, cb_name, None)\n            if f and f(): return True\n        return False\n```\n\n\n```python\ndef create_learner(model_func, loss_func, data):\n    return Learner(*model_func(data), loss_func, data)\n\ndef get_model(data, lr=0.5, nh=50):\n    n = data.train_ds.x.shape[1]\n    model = nn.Sequential(nn.Linear(n, nh), nn.ReLU(), nn.Linear(nh, data.c))\n    return model, optim.SGD(model.parameters(), lr=lr)\n\nclass Learner():\n    def __init__(self, model, opt, loss_func, data):\n        self.model, self.opt, self.loss_func, self.data = model, opt, loss_func, data\n```\n\n\n```python\nlearn = create_learner(get_model, loss_func, data)\n```\n\n\n```python\nfrom typing import *\n\ndef listify(o):\n    if o is None: return []\n    if isinstance(o, list): return o\n    if isinstance(o, str): return [o]\n    if isinstance(o, Iterable): return list(o)\n    return [o]\n\nclass TestCallBack(Callback):\n    _order=1\n    \n    def after_step(self):\n        print(self.n_iter)\n        if self.n_iter >= 10:\n            raise CancelTrainException()\n```\n\n\n```python\n_camel_re1 = re.compile('(.)([A-Z][a-z]+)')\n_camel_re2 = re.compile('([a-z0-9])([A-Z])')\ndef camel2snake(name):\n    s1 = re.sub(_camel_re1, r'\\1_\\2', name)\n    return re.sub(_camel_re2, r'\\1_\\2', s1).lower()\n```\n\n\n```python\nrun = Runner(cb_funcs=TestCallBack)\n```\n\n\n```python\nrun.fit(3, learn)\n```\n\n    0\n    1\n    2\n    3\n    4\n    5\n    6\n    7\n    8\n    9\n    10\n\n\n## Other Callbacks\n\n### LR Finder\n\n\n```python\nclass LR_Find(Callback):\n    _order = 1\n    def __init__(self, max_iter=100, min_lr=1e-6, max_lr=10):\n        self.max_iter, self.min_lr, self.max_lr = max_iter, min_lr, max_lr\n        self.best_loss = 1e9\n    \n    def begin_batch(self):\n        if not self.in_train:\n            return\n        pos = self.n_iter/self.max_iter\n        lr = self.min_lr * (self.max_lr/self.min_lr) ** pos\n        for pg in self.opt.param_groups:\n            pg['lr'] = lr\n    \n    def after_step(self):\n        if self.n_iter >= self.max_iter or self.loss > self.best_loss * 10:\n            raise CancelTrainException()\n        if self.loss < self.best_loss:\n            self.best_loss = self.loss\n\n\nclass Recorder(Callback):\n    def begin_fit(self): self.lrs,self.losses = [],[]\n\n    def after_batch(self):\n        if not self.in_train: return\n        self.lrs.append(self.opt.param_groups[-1]['lr'])\n        self.losses.append(self.loss.detach().cpu())        \n\n    def plot_lr  (self): plt.plot(self.lrs)\n    def plot_loss(self): plt.plot(self.losses)\n```\n\n\n```python\nlearn = create_learner(get_model, loss_func, data)\n```\n\n\n```python\nrun = Runner(cb_funcs=[LR_Find, Recorder])\n```\n\n\n```python\nrun.fit(2, learn)\n```\n\n\n```python\nrun.recorder.plot_loss()\n```\n\n\n```python\nrun.recorder.plot_lr()\n```\n\n---\n\n# ConvNet\n\n\n```python\nX_train, y_train, X_val, y_val = get_data()\n```\n\nHelper function to quickly normalize with the mean and standard deviation of our training set:\n\n\n```python\ndef normalize_to(train, valid):\n    m, s = train.mean(), train.std()\n    return normalize(train, m, s), normalize(valid, m, s)\n```\n\n\n```python\nX_train, X_val = normalize_to(X_train, X_valid)\ntrain_ds, val_ds = Dataset(X_train, y_train), Dataset(X_val, y_val)\n```\n\n\n```python\nX_train.mean(), X_train.std(), X_val.mean(), X_val.std()\n```\n\n\n\n\n    (tensor(-3.0466e-06), tensor(1.), tensor(-0.0059), tensor(0.9924))\n\n\n\n\n```python\nnh, bs = 50, 512\n```\n\n\n```python\nc = y_train.max().item() + 1\n```\n\n\n```python\nloss_func = F.cross_entropy\n```\n\n\n```python\ndata = DataBunch(*get_dls(train_ds, val_ds, bs), c)\n```\n\nTo refactor layers, It's useful to have a Lambda layer that can take a basic function and convert it to a layer you can put in `nn.Sequential`.\n\n\n```python\nclass Lambda(nn.Module):\n    def __init__(self, func):\n        super().__init__()\n        self.func = func\n    \n    def forward(self, x):\n        return self.func(x)\n\ndef flatten(x):\n    return x.view(x.shape[0], -1)\n```\n\n\n```python\ndef mnist_resize(x):\n    return x.view(-1, 1, 28, 28)\n```\n\nWe can now define a simple CNN:\n\n\n```python\ndef get_cnn_model(data):\n    return nn.Sequential(\n        Lambda(mnist_resize),\n        nn.Conv2d(1, 8, 5, padding=2, stride=2), nn.ReLU(),\n        nn.Conv2d(8, 16, 3, padding=1, stride=2), nn.ReLU(),\n        nn.Conv2d(16, 32, 3, padding=1, stride=2), nn.ReLU(),\n        nn.Conv2d(32, 32, 3, padding=1, stride=2), nn.ReLU(),\n        nn.AdaptiveAvgPool2d(1),\n        Lambda(flatten),\n        nn.Linear(32, data.c)\n    )\n```\n\n\n```python\nmodel = get_cnn_model(data)\n```\n\nLet's get our callback functions:\n\n\n```python\nclass AvgStats():\n    def __init__(self, metrics, in_train): \n        self.metrics, self.in_train = listify(metrics), in_train\n    \n    def reset(self):\n        self.tot_loss,self.count = 0.,0\n        self.tot_mets = [0.] * len(self.metrics)\n        \n    @property\n    def all_stats(self): \n        return [self.tot_loss.item()] + self.tot_mets\n    \n    @property\n    def avg_stats(self): \n        return [o/self.count for o in self.all_stats]\n    \n    def __repr__(self):\n        if not self.count: return \"\"\n        return f\"{'train' if self.in_train else 'valid'}: {self.avg_stats}\"\n\n    def accumulate(self, run):\n        bn = run.xb.shape[0]\n        self.tot_loss += run.loss * bn\n        self.count += bn\n        for i,m in enumerate(self.metrics):\n            self.tot_mets[i] += m(run.pred, run.yb) * bn\n\n\nclass AvgStatsCallback(Callback):\n    def __init__(self, metrics):\n        self.train_stats, self.valid_stats = AvgStats(metrics, True), AvgStats(metrics, False)\n        \n    def begin_epoch(self):\n        self.train_stats.reset()\n        self.valid_stats.reset()\n        \n    def after_loss(self):\n        stats = self.train_stats if self.in_train else self.valid_stats\n        with torch.no_grad(): stats.accumulate(self.run)\n    \n    def after_epoch(self):\n        print(self.train_stats)\n        print(self.valid_stats)\n\ndef accuracy(out, yb):\n    return (torch.argmax(out, dim=1) == yb).float().mean()\n```\n\n\n```python\ncbfs = [Recorder, partial(AvgStatsCallback, accuracy)]\n```\n\n\n```python\nopt = optim.SGD(model.parameters(), lr=0.4)\n```\n\n\n```python\nlearn = Learner(model, opt, loss_func, data)\n```\n\n\n```python\nrun = Runner(cb_funcs=cbfs)\n```\n\n\n```python\n%time run.fit(1, learn)\n```\n\n    train: [2.01694859375, tensor(0.2951)]\n    valid: [1.0925693359375, tensor(0.6162)]\n    CPU times: user 15.5 s, sys: 27.1 s, total: 42.6 s\n    Wall time: 5.91 s\n\n\n## CUDA\n\nThis took a long time to run, It's time to use a GPUs.\n\nA simple callback can make sure the model, inputs, and targets are all on the same device.\n\n\n```python\ndevice = torch.device('cuda', 0)\n```\n\n\n```python\nclass CudaCallBack(Callback):\n    def __init__(self, device):\n        self.device = device\n    \n    def begin_fit(self):\n        self.model.to(self.device)\n    \n    def begin_batch(self):\n        self.run.xb, self.run.yb = self.xb.to(self.device), self.yb.to(self.device)\n```\n\n\n```python\n# Somewhat less flexible, but quite convenient\ntorch.cuda.set_device(device)\n```\n\n\n```python\nclass CudaCallBack(Callback):\n    def begin_fit(self):\n        self.model.cuda()\n    \n    def begin_batch(self):\n        self.run.xb, self.run.yb = self.xb.cuda(), self.yb.cuda()\n```\n\n\n```python\ncbfs.append(CudaCallBack)\n```\n\n\n```python\nmodel = get_cnn_model(data)\n```\n\n\n```python\nopt = optim.SGD(model.parameters(), lr=0.4)\nlearn = Learner(model, opt, loss_func, data)\nrun = Runner(cb_funcs=cbfs)\n```\n\n\n```python\n%time run.fit(3, learn)\n```\n\n    train: [2.093578125, tensor(0.2432, device='cuda:0')]\n    valid: [1.6709130859375, tensor(0.4680, device='cuda:0')]\n    train: [0.5412753515625, tensor(0.8273, device='cuda:0')]\n    valid: [0.2072068603515625, tensor(0.9403, device='cuda:0')]\n    train: [0.20172669921875, tensor(0.9391, device='cuda:0')]\n    valid: [0.1400499755859375, tensor(0.9577, device='cuda:0')]\n    CPU times: user 4.89 s, sys: 992 ms, total: 5.88 s\n    Wall time: 5.92 s\n\n\n## Refactor Model\n\nfirst we can regroup all of the conv/relu into a single function:\n\n\n```python\ndef conv2d(ni, nf, ks=3, stride=2):\n    return nn.Sequential(\n        nn.Conv2d(ni, nf, ks, padding=ks//2, stride=stride), nn.ReLU())\n```\n\n\n```python\nclass BatchTransformXCallback(Callback):\n    _order=2\n    def __init__(self, tfm): self.tfm = tfm\n    def begin_batch(self): self.run.xb = self.tfm(self.xb)\n\ndef view_tfm(*size):\n    def _inner(x): return x.view(*((-1,)+size))\n    return _inner\n```\n\n\n```python\nmnist_view = view_tfm(1,28,28)\ncbfs.append(partial(BatchTransformXCallback, mnist_view))\n```\n\n\n```python\nnfs = [8,16,32,32]\n```\n\n\n```python\ndef get_cnn_layers(data, nfs):\n    nfs = [1] + nfs\n    return [\n        conv2d(nfs[i], nfs[i+1], 5 if i==0 else 3)\n        for i in range(len(nfs)-1)\n    ] + [nn.AdaptiveAvgPool2d(1), Lambda(flatten), nn.Linear(nfs[-1], data.c)]\n\ndef get_cnn_model(data, nfs): return nn.Sequential(*get_cnn_layers(data, nfs))\n```\n\n\n```python\ndef get_runner(model, data, lr=0.6, cbs=None, opt_func=None, loss_func = F.cross_entropy):\n    if opt_func is None: opt_func = optim.SGD\n    opt = opt_func(model.parameters(), lr=lr)\n    learn = Learner(model, opt, loss_func, data)\n    return learn, Runner(cb_funcs=listify(cbs))\n```\n\n\n```python\nmodel = get_cnn_model(data, nfs)\nlearn,run = get_runner(model, data, lr=0.4, cbs=cbfs)\n```\n\n\n```python\nmodel\n```\n\n\n\n\n    Sequential(\n      (0): Sequential(\n        (0): Conv2d(1, 8, kernel_size=(5, 5), stride=(2, 2), padding=(2, 2))\n        (1): ReLU()\n      )\n      (1): Sequential(\n        (0): Conv2d(8, 16, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n        (1): ReLU()\n      )\n      (2): Sequential(\n        (0): Conv2d(16, 32, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n        (1): ReLU()\n      )\n      (3): Sequential(\n        (0): Conv2d(32, 32, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n        (1): ReLU()\n      )\n      (4): AdaptiveAvgPool2d(output_size=1)\n      (5): Lambda()\n      (6): Linear(in_features=32, out_features=10, bias=True)\n    )\n\n\n\n\n```python\nrun.fit(3, learn)\n```\n\n    train: [2.1856284375, tensor(0.1983, device='cuda:0')]\n    valid: [1.62301279296875, tensor(0.5182, device='cuda:0')]\n    train: [0.75375609375, tensor(0.7618, device='cuda:0')]\n    valid: [0.288960205078125, tensor(0.9110, device='cuda:0')]\n    train: [0.245807734375, tensor(0.9241, device='cuda:0')]\n    valid: [0.1788814208984375, tensor(0.9489, device='cuda:0')]\n\n\n## Hooks\n\nOur next goal is to see what's \"going on inside the model\"!\n\n### Manual Insertion\n\n\n```python\nclass SequentialModel(nn.Module):\n    def __init__(self, *layers):\n        super().__init__()\n        self.layers = nn.ModuleList(layers)\n        self.act_means = [[] for _ in layers]\n        self.act_stds  = [[] for _ in layers]\n        \n    def __call__(self, x):\n        for i,l in enumerate(self.layers):\n            x = l(x)\n            self.act_means[i].append(x.data.mean())\n            self.act_stds [i].append(x.data.std ())\n        return x\n    \n    def __iter__(self): \n        return iter(self.layers)\n```\n\n\n```python\nmodel =  SequentialModel(*get_cnn_layers(data, nfs))\nlearn, run = get_runner(model, data, lr=0.9, cbs=cbfs)\n```\n\n\n```python\nrun.fit(2, learn)\n```\n\n    train: [2.36338, tensor(0.1185, device='cuda:0')]\n    valid: [2.3014935546875, tensor(0.1064, device='cuda:0')]\n    train: [2.015745, tensor(0.2740, device='cuda:0')]\n    valid: [1.50768828125, tensor(0.4716, device='cuda:0')]\n\n\nNow we can have a look at the means and stds of the activations at the beginning of training.\n\n\n```python\nfor l in model.act_means: \n    plt.plot(l)\nplt.legend(range(6));\n```\n\nThis is somewhat bad because we have sharp vibrations, ideally we want the means to be smooth and near $0$. Let's try to change that.\n\n\n```python\nfor l in model.act_stds: plt.plot(l)\nplt.legend(range(6));\n```\n\nLet's look at the first 10 batches for each layer at each step:\n\n\n```python\nfor l in model.act_means: plt.plot(l[:10])\nplt.legend(range(6));\n```\n\nLooks good, fairly close to 0.\n\nLet's also take a look at the standard deviation of all layers for their 10 first batches of training: \n\n\n```python\nfor l in model.act_stds: \n    plt.plot(l[:10])\nplt.legend(range(6));\n```\n\nThis is not good, the first layers `std`s are somewhat close to $1$ but all other layers are very close to 0.\n\nWe have an idea on how to solve this problem, we have to use good initialization techniques.\n\n### PyTorch Hooks\n\nHooks are PyTorch objects you can add to any `nn.Module`. A Hook will be called when the layer it is registered to, is executed during the forward or backward passes.\n\nHooks don't require us to re-write the model.\n\n\n```python\nmodel = get_cnn_model(data, nfs)\nlearn,run = get_runner(model, data, lr=0.5, cbs=cbfs)\n```\n\n\n```python\nact_means = [[] for _ in model]\nact_stds  = [[] for _ in model]\n```\n\nA hook is attached to a layer, and needs to have a function that takes three arguments: **module, input, output**.\n\nHere we store the mean and standard deviation of the output in the correct position of our list.\n\n\n```python\ndef append_stats(i, mod, inp, outp):\n    act_means[i].append(outp.data.mean())\n    act_stds [i].append(outp.data.std())\n```\n\n\n```python\nfor i, m in enumerate(model): \n    m.register_forward_hook(partial(append_stats, i))\n```\n\n\n```python\nrun.fit(1, learn)\n```\n\n    train: [2.06755140625, tensor(0.2570, device='cuda:0')]\n    valid: [0.8275548828125, tensor(0.7102, device='cuda:0')]\n\n\n\n```python\nfor o in act_means: plt.plot(o)\nplt.legend(range(5));\n```\n\n### Hook Class\n\n\n```python\ndef children(m): \n    return list(m.children())\n\nclass Hook():\n    def __init__(self, m, f): \n        self.hook = m.register_forward_hook(partial(f, self))\n    \n    def remove(self): \n        self.hook.remove()\n    \n    def __del__(self): \n        self.remove()\n\ndef append_stats(hook, mod, inp, outp):\n    if not hasattr(hook,'stats'): \n        hook.stats = ([],[])\n    \n    means, stds = hook.stats\n    means.append(outp.data.mean())\n    stds.append(outp.data.std())\n```\n\n\n```python\nmodel = get_cnn_model(data, nfs)\nlearn,run = get_runner(model, data, lr=0.5, cbs=cbfs)\n```\n\n\n```python\nhooks = [Hook(l, append_stats) for l in children(model[:4])]\n```\n\n\n```python\nrun.fit(1, learn)\n```\n\n    train: [1.809714375, tensor(0.3575, device='cuda:0')]\n    valid: [0.574386962890625, tensor(0.7817, device='cuda:0')]\n\n\n\n```python\nfor h in hooks:\n    plt.plot(h.stats[0])\n    h.remove()\nplt.legend(range(4));\n```\n\n### A Hooks Class\n\n\n```python\nclass ListContainer():\n    def __init__(self, items): \n        self.items = listify(items)\n    \n    def __getitem__(self, idx):\n        if isinstance(idx, (int,slice)): \n            return self.items[idx]\n        \n        if isinstance(idx[0],bool):\n            assert len(idx)==len(self) # bool mask\n            return [o for m,o in zip(idx,self.items) if m]\n        return [self.items[i] for i in idx]\n    \n    def __len__(self): \n        return len(self.items)\n    def __iter__(self): \n        return iter(self.items)\n    def __setitem__(self, i, o): \n        self.items[i] = o\n    def __delitem__(self, i): \n        del(self.items[i])\n    def __repr__(self):\n        res = f'{self.__class__.__name__} ({len(self)} items)\\n{self.items[:10]}'\n        if len(self)>10: res = res[:-1]+ '...]'\n        return res\n```\n\n\n```python\nListContainer(range(10))\n```\n\n\n\n\n    ListContainer (10 items)\n    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n\n\n\n```python\nListContainer(range(100))\n```\n\n\n\n\n    ListContainer (100 items)\n    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9...]\n\n\n\n\n```python\nt = ListContainer(range(10))\nt[[1,2]], t[[False]*8 + [True,False]]\n```\n\n\n\n\n    ([1, 2], [8])\n\n\n\n\n```python\nfrom torch.nn import init\n\nclass Hooks(ListContainer):\n    def __init__(self, ms, f): super().__init__([Hook(m, f) for m in ms])\n    def __enter__(self, *args): return self\n    def __exit__ (self, *args): self.remove()\n    def __del__(self): self.remove()\n\n    def __delitem__(self, i):\n        self[i].remove()\n        super().__delitem__(i)\n        \n    def remove(self):\n        for h in self: h.remove()\n```\n\n\n```python\nmodel = get_cnn_model(data, nfs).cuda()\nlearn, run = get_runner(model, data, lr=0.9, cbs=cbfs)\n```\n\n\n```python\nhooks = Hooks(model, append_stats)\nhooks\n```\n\n\n\n\n    Hooks (7 items)\n    [<__main__.Hook object at 0x7fbc9c927a90>, <__main__.Hook object at 0x7fbc9c927fd0>, <__main__.Hook object at 0x7fbc9c927978>, <__main__.Hook object at 0x7fbc9c927160>, <__main__.Hook object at 0x7fbc9c927e48>, <__main__.Hook object at 0x7fbc9c927908>, <__main__.Hook object at 0x7fbc9c9270f0>]\n\n\n\n\n```python\nhooks.remove()\n```\n\n\n```python\nx, y = next(iter(data.train_dl))\nx = mnist_resize(x).cuda()\n```\n\n\n```python\nx.mean(),x.std()\n```\n\n\n\n\n    (tensor(0.0038, device='cuda:0'), tensor(1.0046, device='cuda:0'))\n\n\n\n\n```python\np = model[0](x)\np.mean(), p.std()\n```\n\n\n\n\n    (tensor(0.1495, device='cuda:0', grad_fn=<MeanBackward0>),\n     tensor(0.3377, device='cuda:0', grad_fn=<StdBackward0>))\n\n\n\n\n```python\nfor l in model:\n    if isinstance(l, nn.Sequential):\n        init.kaiming_normal_(l[0].weight)\n        l[0].bias.data.zero_()\n```\n\n\n```python\np = model[0](x)\np.mean(), p.std()\n```\n\n\n\n\n    (tensor(0.3787, device='cuda:0', grad_fn=<MeanBackward0>),\n     tensor(0.7844, device='cuda:0', grad_fn=<StdBackward0>))\n\n\n\n\n```python\nwith Hooks(model, append_stats) as hooks:\n    run.fit(2, learn)\n    fig,(ax0,ax1) = plt.subplots(1,2, figsize=(10,4))\n    for h in hooks:\n        ms,ss = h.stats\n        ax0.plot(ms[:10])\n        ax1.plot(ss[:10])\n    plt.legend(range(6));\n    \n    fig,(ax0,ax1) = plt.subplots(1,2, figsize=(10,4))\n    for h in hooks:\n        ms,ss = h.stats\n        ax0.plot(ms)\n        ax1.plot(ss)\n    plt.legend(range(6));\n```\n\n### Other Statistics\n\nLet's store more than the means and stds and plot histograms of our activations now.\n\n\n```python\ndef append_stats(hook, mod, inp, outp):\n    if not hasattr(hook,'stats'): hook.stats = ([],[],[])\n    means,stds,hists = hook.stats\n    means.append(outp.data.mean().cpu())\n    stds .append(outp.data.std().cpu())\n    hists.append(outp.data.cpu().histc(40,0,10)) #histc isn't implemented on the GPU\n```\n\n\n```python\nmodel = get_cnn_model(data, nfs).cuda()\nlearn, run = get_runner(model, data, lr=0.9, cbs=cbfs)\n```\n\n\n```python\nfor l in model:\n    if isinstance(l, nn.Sequential):\n        init.kaiming_normal_(l[0].weight)\n        l[0].bias.data.zero_()\n```\n\n\n```python\nwith Hooks(model, append_stats) as hooks: run.fit(1, learn)\n```\n\n    train: [1.77242171875, tensor(0.3911, device='cuda:0')]\n    valid: [0.657517041015625, tensor(0.7820, device='cuda:0')]\n\n\n\n```python\n# Thanks to @ste for initial version of histgram plotting code\ndef get_hist(h): \n    return torch.stack(h.stats[2]).t().float().log1p()\n```\n\n\n```python\nfig,axes = plt.subplots(2,2, figsize=(15,6))\nfor ax,h in zip(axes.flatten(), hooks[:4]):\n    ax.imshow(get_hist(h), origin='lower')\n    ax.axis('off')\nplt.tight_layout()\n```\n\nLet's investigate our activations being zero.\n\nFrom the histograms, we can easily get more informations like the min or max of the activations\n\n\n```python\ndef get_min(h):\n    h1 = torch.stack(h.stats[2]).t().float()\n    return h1[:2].sum(0)/h1.sum(0)\n```\n\n\n```python\n# fig,axes = plt.subplots(2,2, figsize=(15,6))\n# for ax,h in zip(axes.flatten(), hooks[:4]):\n#     ax.plot(get_min(h))\n#     ax.set_ylim(0,1)\n# plt.tight_layout()\n```\n\nAlmost 90% of our activations are zero and we don't want that.\n\n## Generalized ReLU\n\n\n```python\ndef get_cnn_layers(data, nfs, layer, **kwargs):\n    nfs = [1] + nfs\n    return [layer(nfs[i], nfs[i+1], 5 if i==0 else 3, **kwargs)\n            for i in range(len(nfs)-1)] + [\n        nn.AdaptiveAvgPool2d(1), Lambda(flatten), nn.Linear(nfs[-1], data.c)]\n\ndef conv_layer(ni, nf, ks=3, stride=2, **kwargs):\n    return nn.Sequential(\n        nn.Conv2d(ni, nf, ks, padding=ks//2, stride=stride), GeneralRelu(**kwargs))\n\nclass GeneralRelu(nn.Module):\n    def __init__(self, leak=None, sub=None, maxv=None):\n        super().__init__()\n        self.leak,self.sub,self.maxv = leak,sub,maxv\n\n    def forward(self, x): \n        x = F.leaky_relu(x,self.leak) if self.leak is not None else F.relu(x)\n        if self.sub is not None: x.sub_(self.sub)\n        if self.maxv is not None: x.clamp_max_(self.maxv)\n        return x\n\ndef init_cnn(m, uniform=False):\n    f = init.kaiming_uniform_ if uniform else init.kaiming_normal_\n    for l in m:\n        if isinstance(l, nn.Sequential):\n            f(l[0].weight, a=0.1)\n            l[0].bias.data.zero_()\n\ndef get_cnn_model(data, nfs, layer, **kwargs):\n    return nn.Sequential(*get_cnn_layers(data, nfs, layer, **kwargs))\n```\n\n\n```python\ndef append_stats(hook, mod, inp, outp):\n    if not hasattr(hook,'stats'): hook.stats = ([],[],[])\n    means,stds,hists = hook.stats\n    means.append(outp.data.mean().cpu())\n    stds .append(outp.data.std().cpu())\n    hists.append(outp.data.cpu().histc(40,-7,7))\n```\n\n\n```python\nmodel =  get_cnn_model(data, nfs, conv_layer, leak=0.1, sub=0.4, maxv=6.)\ninit_cnn(model)\nlearn,run = get_runner(model, data, lr=0.9, cbs=cbfs)\n```\n\n\n```python\nwith Hooks(model, append_stats) as hooks:\n    run.fit(1, learn)\n    fig,(ax0,ax1) = plt.subplots(1,2, figsize=(10,4))\n    for h in hooks:\n        ms,ss,hi = h.stats\n        ax0.plot(ms[:10])\n        ax1.plot(ss[:10])\n        h.remove()\n    plt.legend(range(5));\n    \n    fig,(ax0,ax1) = plt.subplots(1,2, figsize=(10,4))\n    for h in hooks:\n        ms,ss,hi = h.stats\n        ax0.plot(ms)\n        ax1.plot(ss)\n    plt.legend(range(5));\n```\n\n\n```python\nfig,axes = plt.subplots(2,2, figsize=(15,6))\nfor ax,h in zip(axes.flatten(), hooks[:4]):\n    ax.imshow(get_hist(h), origin='lower')\n    ax.axis('off')\nplt.tight_layout()\n```\n\n\n```python\nfig,axes = plt.subplots(2,2, figsize=(15,6))\nfor ax,h in zip(axes.flatten(), hooks[:4]):\n    ax.plot(get_min(h))\n    ax.set_ylim(0,1)\nplt.tight_layout()\n```\n\n\n```python\ndef get_min(h):\n    h1 = torch.stack(h.stats[2]).t().float()\n    return h1[19:22].sum(0)/h1.sum(0)\n```\n\n\n```python\nfig,axes = plt.subplots(2,2, figsize=(15,6))\nfor ax,h in zip(axes.flatten(), hooks[:4]):\n    ax.plot(get_min(h))\n    ax.set_ylim(0,1)\nplt.tight_layout()\n```\n\n\n```python\ndef get_learn_run(nfs, data, lr, layer, cbs=None, opt_func=None, uniform=False, **kwargs):\n    model = get_cnn_model(data, nfs, layer, **kwargs)\n    init_cnn(model, uniform=uniform)\n    return get_runner(model, data, lr=lr, cbs=cbs, opt_func=opt_func)\n```\n\n\n```python\ndef combine_scheds(pcts, scheds):\n    assert sum(pcts) == 1.\n    pcts = tensor([0] + listify(pcts))\n    assert torch.all(pcts >= 0)\n    pcts = torch.cumsum(pcts, 0)\n    def _inner(pos):\n        idx = (pos >= pcts).nonzero().max()\n        actual_pos = (pos-pcts[idx]) / (pcts[idx+1]-pcts[idx])\n        return scheds[idx](actual_pos)\n    return _inner\n```\n\n\n```python\nimport math\n\ndef annealer(f):\n    def _inner(start, end): \n        return partial(f, start, end)\n    return _inner\n\n@annealer\ndef sched_lin(start, end, pos): \n    return start + pos*(end-start)\n@annealer\ndef sched_cos(start, end, pos): return start + (1 + math.cos(math.pi*(1-pos))) * (end-start) / 2\n@annealer\ndef sched_no(start, end, pos):  return start\n@annealer\ndef sched_exp(start, end, pos): return start * (end/start) ** pos\n\ndef cos_1cycle_anneal(start, high, end):\n    return [sched_cos(start, high), sched_cos(high, end)]\n\n#This monkey-patch is there to be able to plot tensors\ntorch.Tensor.ndim = property(lambda x: len(x.shape))\n\nclass Recorder(Callback):\n    def begin_fit(self): self.lrs,self.losses = [],[]\n\n    def after_batch(self):\n        if not self.in_train: return\n        self.lrs.append(self.opt.param_groups[-1]['lr'])\n        self.losses.append(self.loss.detach().cpu())        \n\n    def plot_lr  (self): plt.plot(self.lrs)\n    def plot_loss(self): plt.plot(self.losses)\n\nclass ParamScheduler(Callback):\n    _order=1\n    def __init__(self, pname, sched_func): self.pname,self.sched_func = pname,sched_func\n\n    def set_param(self):\n        for pg in self.opt.param_groups:\n            pg[self.pname] = self.sched_func(self.n_epochs/self.epochs)\n            \n    def begin_batch(self): \n        if self.in_train: self.set_param()\n```\n\n\n```python\nsched = combine_scheds([0.5, 0.5], [sched_cos(0.2, 1.), sched_cos(1., 0.1)]) \n```\n\n\n```python\nlearn,run = get_learn_run(nfs, data, 1., conv_layer, cbs=cbfs+[partial(ParamScheduler,'lr', sched)])\n```\n\n\n```python\nrun.fit(8, learn)\n```\n\n    train: [1.060915234375, tensor(0.6694, device='cuda:0')]\n    valid: [0.493050634765625, tensor(0.8412, device='cuda:0')]\n    train: [0.32353591796875, tensor(0.9018, device='cuda:0')]\n    valid: [0.1593845947265625, tensor(0.9519, device='cuda:0')]\n    train: [0.2440578515625, tensor(0.9274, device='cuda:0')]\n    valid: [0.13114432373046875, tensor(0.9624, device='cuda:0')]\n    train: [0.11478775390625, tensor(0.9652, device='cuda:0')]\n    valid: [0.11049580078125, tensor(0.9680, device='cuda:0')]\n    train: [0.0975326953125, tensor(0.9700, device='cuda:0')]\n    valid: [0.08416253051757812, tensor(0.9740, device='cuda:0')]\n    train: [0.05666337890625, tensor(0.9827, device='cuda:0')]\n    valid: [0.0691174072265625, tensor(0.9798, device='cuda:0')]\n    train: [0.0409935302734375, tensor(0.9870, device='cuda:0')]\n    valid: [0.062134423828125, tensor(0.9820, device='cuda:0')]\n    train: [0.03323422119140625, tensor(0.9896, device='cuda:0')]\n    valid: [0.06214251708984375, tensor(0.9826, device='cuda:0')]\n\n\nUniform init may provide added value since it doesn't put many weights at 0 like normal init:\n\n\n```python\nlearn,run = get_learn_run(nfs, data, 1., conv_layer, uniform=True,\n                          cbs=cbfs+[partial(ParamScheduler,'lr', sched)])\n```\n\n\n```python\nrun.fit(8, learn)\n```\n\n    train: [1.253315546875, tensor(0.5888, device='cuda:0')]\n    valid: [0.36798681640625, tensor(0.8881, device='cuda:0')]\n    train: [0.3452720703125, tensor(0.8970, device='cuda:0')]\n    valid: [0.19749097900390625, tensor(0.9400, device='cuda:0')]\n    train: [0.24668892578125, tensor(0.9262, device='cuda:0')]\n    valid: [0.1775989501953125, tensor(0.9451, device='cuda:0')]\n    train: [0.129861171875, tensor(0.9596, device='cuda:0')]\n    valid: [0.089367822265625, tensor(0.9743, device='cuda:0')]\n    train: [0.0806864111328125, tensor(0.9745, device='cuda:0')]\n    valid: [0.07527806396484375, tensor(0.9782, device='cuda:0')]\n    train: [0.055491279296875, tensor(0.9824, device='cuda:0')]\n    valid: [0.06677013549804688, tensor(0.9803, device='cuda:0')]\n    train: [0.0411886376953125, tensor(0.9877, device='cuda:0')]\n    valid: [0.05997559204101562, tensor(0.9825, device='cuda:0')]\n    train: [0.0339090625, tensor(0.9901, device='cuda:0')]\n    valid: [0.0596075439453125, tensor(0.9827, device='cuda:0')]\n\n\n---\n\n# ConvNet\n\n\n```python\nx_train,y_train,x_valid,y_valid = get_data()\nx_train,x_valid = normalize_to(x_train,x_valid)\ntrain_ds,valid_ds = Dataset(x_train, y_train),Dataset(x_valid, y_valid)\nnh,bs = 50,512\nc = y_train.max().item()+1\nloss_func = F.cross_entropy\ndata = DataBunch(*get_dls(train_ds, valid_ds, bs), c)\n```\n\n\n```python\nmnist_view = view_tfm(1,28,28)\ncbfs = [Recorder,\n        partial(AvgStatsCallback,accuracy),\n        CudaCallBack,\n        partial(BatchTransformXCallback, mnist_view)]\n```\n\n\n```python\nnfs = [8,16,32,64,64]\n```\n\n\n```python\nlearn, run = get_learn_run(nfs, data, 0.4, conv_layer, cbs=cbfs)\n```\n\n\n```python\n%time run.fit(2, learn)\n```\n\n    train: [1.48314390625, tensor(0.5126, device='cuda:0')]\n    valid: [0.2979984619140625, tensor(0.9098, device='cuda:0')]\n    train: [0.2393195703125, tensor(0.9277, device='cuda:0')]\n    valid: [0.16126219482421875, tensor(0.9515, device='cuda:0')]\n    CPU times: user 2.05 s, sys: 680 ms, total: 2.73 s\n    Wall time: 2.4 s\n\n\n## Batchnorm\n\nLet's start by building our own `Batchnorm` layer from scratch.\n\n\n```python\nclass BatchNorm(nn.Module):\n    def __init__(self, nf, mom=0.1, eps=1e-5):\n        super().__init__()\n        # NB: pytorch bn mom is opposite of what you'd expect\n        self.mom,self.eps = mom,eps\n        self.mults = nn.Parameter(torch.ones (nf,1,1))\n        self.adds  = nn.Parameter(torch.zeros(nf,1,1))\n        self.register_buffer('vars',  torch.ones(1,nf,1,1))\n        self.register_buffer('means', torch.zeros(1,nf,1,1))\n\n    def update_stats(self, x):\n        m = x.mean((0,2,3), keepdim=True)\n        v = x.var ((0,2,3), keepdim=True)\n        self.means.lerp_(m, self.mom)\n        self.vars.lerp_ (v, self.mom)\n        return m,v\n        \n    def forward(self, x):\n        if self.training:\n            with torch.no_grad(): m,v = self.update_stats(x)\n        else: m,v = self.means,self.vars\n        x = (x-m) / (v+self.eps).sqrt()\n        return x*self.mults + self.adds\n```\n\n\n```python\ndef conv_layer(ni, nf, ks=3, stride=2, bn=True, **kwargs):\n    # No bias needed if using bn\n    layers = [nn.Conv2d(ni, nf, ks, padding=ks//2, stride=stride, bias=not bn),\n              GeneralRelu(**kwargs)]\n    if bn: layers.append(BatchNorm(nf))\n    return nn.Sequential(*layers)\n```\n\n\n```python\ndef init_cnn_(m, f):\n    if isinstance(m, nn.Conv2d):\n        f(m.weight, a=0.1)\n        if getattr(m, 'bias', None) is not None: m.bias.data.zero_()\n    for l in m.children(): init_cnn_(l, f)\n\ndef init_cnn(m, uniform=False):\n    f = init.kaiming_uniform_ if uniform else init.kaiming_normal_\n    init_cnn_(m, f)\n\ndef get_learn_run(nfs, data, lr, layer, cbs=None, opt_func=None, uniform=False, **kwargs):\n    model = get_cnn_model(data, nfs, layer, **kwargs)\n    init_cnn(model, uniform=uniform)\n    return get_runner(model, data, lr=lr, cbs=cbs, opt_func=opt_func)\n```\n\nWe can then use it in training and see how it helps keep the activations means to 0 and the std to 1.\n\n\n```python\nlearn, run = get_learn_run(nfs, data, 0.9, conv_layer, cbs=cbfs)\n```\n\n\n```python\n# with Hooks(learn.model, append_stats) as hooks:\n#     run.fit(1, learn)\n#     fig,(ax0,ax1) = plt.subplots(1,2, figsize=(10,4))\n#     for h in hooks[:-1]:\n#         ms,ss = h.stats\n#         ax0.plot(ms[:10])\n#         ax1.plot(ss[:10])\n#         h.remove()\n#     plt.legend(range(6));\n    \n#     fig,(ax0,ax1) = plt.subplots(1,2, figsize=(10,4))\n#     for h in hooks[:-1]:\n#         ms,ss = h.stats\n#         ax0.plot(ms)\n#         ax1.plot(ss)\n```\n\n\n```python\nlearn,run = get_learn_run(nfs, data, 1.0, conv_layer, cbs=cbfs)\n```\n\n\n```python\n%time run.fit(3, learn)\n```\n\n    train: [0.25269798828125, tensor(0.9219, device='cuda:0')]\n    valid: [0.1530221435546875, tensor(0.9537, device='cuda:0')]\n    train: [0.0849437109375, tensor(0.9734, device='cuda:0')]\n    valid: [0.09541368408203126, tensor(0.9688, device='cuda:0')]\n    train: [0.0598129296875, tensor(0.9810, device='cuda:0')]\n    valid: [0.1203537109375, tensor(0.9625, device='cuda:0')]\n    CPU times: user 3.45 s, sys: 412 ms, total: 3.86 s\n    Wall time: 3.88 s\n\n\n### Builtin Batchnorm\n\n\n```python\ndef conv_layer(ni, nf, ks=3, stride=2, bn=True, **kwargs):\n    layers = [nn.Conv2d(ni, nf, ks, padding=ks//2, stride=stride, bias=not bn),\n              GeneralRelu(**kwargs)]\n    if bn: layers.append(nn.BatchNorm2d(nf, eps=1e-5, momentum=0.1))\n    return nn.Sequential(*layers)\n```\n\n\n```python\nlearn,run = get_learn_run(nfs, data, 1., conv_layer, cbs=cbfs)\n```\n\n\n```python\n%time run.fit(3, learn)\n```\n\n    train: [0.26425353515625, tensor(0.9214, device='cuda:0')]\n    valid: [0.10408934326171874, tensor(0.9680, device='cuda:0')]\n    train: [0.074472373046875, tensor(0.9769, device='cuda:0')]\n    valid: [0.07626646118164063, tensor(0.9767, device='cuda:0')]\n    train: [0.0511612646484375, tensor(0.9843, device='cuda:0')]\n    valid: [0.069636962890625, tensor(0.9786, device='cuda:0')]\n    CPU times: user 3.07 s, sys: 460 ms, total: 3.53 s\n    Wall time: 3.55 s\n\n\n### With Scheduler\n\nNow let's add the usual warmup/annealing:\n\n\n```python\nsched = combine_scheds([0.3, 0.7], [sched_lin(0.6, 2.), sched_lin(2., 0.1)]) \n```\n\n\n```python\nlearn,run = get_learn_run(nfs, data, 0.9, conv_layer, cbs=cbfs\n                          +[partial(ParamScheduler,'lr', sched)])\n```\n\n\n```python\nrun.fit(8, learn)\n```\n\n    train: [0.3423046484375, tensor(0.8957, device='cuda:0')]\n    valid: [0.13684195556640624, tensor(0.9587, device='cuda:0')]\n    train: [0.104302275390625, tensor(0.9666, device='cuda:0')]\n    valid: [0.0806655029296875, tensor(0.9770, device='cuda:0')]\n    train: [0.0663425537109375, tensor(0.9785, device='cuda:0')]\n    valid: [0.06987247924804688, tensor(0.9783, device='cuda:0')]\n    train: [0.0442214599609375, tensor(0.9863, device='cuda:0')]\n    valid: [0.07664190673828125, tensor(0.9768, device='cuda:0')]\n    train: [0.0299293212890625, tensor(0.9907, device='cuda:0')]\n    valid: [0.05306869506835937, tensor(0.9820, device='cuda:0')]\n    train: [0.01963597412109375, tensor(0.9944, device='cuda:0')]\n    valid: [0.04799787902832031, tensor(0.9851, device='cuda:0')]\n    train: [0.012680633544921875, tensor(0.9968, device='cuda:0')]\n    valid: [0.044890817260742184, tensor(0.9867, device='cuda:0')]\n    train: [0.00894314697265625, tensor(0.9982, device='cuda:0')]\n    valid: [0.04442623291015625, tensor(0.9873, device='cuda:0')]\n\n\nBatchnorm is really quite fantastic.\n\n## More Norms\n\n### Layer Norm\n\nBatch norm has the following deficiencies:\n\n- How do we handle very small batch size (where variance converges to 0).\n- How do we use BatchNorm in RNNs.\n\n\n```python\nclass LayerNorm(nn.Module):\n    __constants__ = ['eps']\n    def __init__(self, eps=1e-5):\n        super().__init__()\n        self.eps = eps\n        self.mult = nn.Parameter(tensor(1.))\n        self.add  = nn.Parameter(tensor(0.))\n\n    def forward(self, x):\n        m = x.mean((1,2,3), keepdim=True)\n        v = x.var ((1,2,3), keepdim=True)\n        x = (x-m) / ((v+self.eps).sqrt())\n        return x*self.mult + self.add\n```\n\nWe remove all of the running averages. We're not taking the mean of the batch anymore, every image has its own mean and standard diviation.\n\n\n```python\ndef conv_ln(ni, nf, ks=3, stride=2, bn=True, **kwargs):\n    layers = [nn.Conv2d(ni, nf, ks, padding=ks//2, stride=stride, bias=True),\n              GeneralRelu(**kwargs)]\n    if bn: layers.append(LayerNorm())\n    return nn.Sequential(*layers)\n```\n\n\n```python\nlearn,run = get_learn_run(nfs, data, 0.8, conv_ln, cbs=cbfs)\n```\n\n\n```python\n%time run.fit(3, learn)\n```\n\n    train: [nan, tensor(0.1123, device='cuda:0')]\n    valid: [nan, tensor(0.0991, device='cuda:0')]\n    train: [nan, tensor(0.0986, device='cuda:0')]\n    valid: [nan, tensor(0.0991, device='cuda:0')]\n    train: [nan, tensor(0.0986, device='cuda:0')]\n    valid: [nan, tensor(0.0991, device='cuda:0')]\n    CPU times: user 3.86 s, sys: 496 ms, total: 4.35 s\n    Wall time: 4.37 s\n\n\nLayer norm is not as good as batchnorm but it's the only option you have for online learning or RNN networks.\n\n### Instance Norm\n\nThe key difference between **contrast** and batch normalization is that the latter applies the normalization to a  whole batch of images instead for single ones:\n\n\\begin{equation}\\label{eq:bnorm}\n    y_{tijk} =  \\frac{x_{tijk} - \\mu_{i}}{\\sqrt{\\sigma_i^2 + \\epsilon}},\n    \\quad\n    \\mu_i = \\frac{1}{HWT}\\sum_{t=1}^T\\sum_{l=1}^W \\sum_{m=1}^H x_{tilm},\n    \\quad\n    \\sigma_i^2 = \\frac{1}{HWT}\\sum_{t=1}^T\\sum_{l=1}^W \\sum_{m=1}^H (x_{tilm} - mu_i)^2.\n\\end{equation}\n\nIn order to combine the effects of instance-specific normalization and batch normalization, we propose to replace the latter by the *instance normalization* (also known as *contrast normalization*) layer:\n\n\\begin{equation}\\label{eq:inorm}\n    y_{tijk} =  \\frac{x_{tijk} - \\mu_{ti}}{\\sqrt{\\sigma_{ti}^2 + \\epsilon}},\n    \\quad\n    \\mu_{ti} = \\frac{1}{HW}\\sum_{l=1}^W \\sum_{m=1}^H x_{tilm},\n    \\quad\n    \\sigma_{ti}^2 = \\frac{1}{HW}\\sum_{l=1}^W \\sum_{m=1}^H (x_{tilm} - mu_{ti})^2.\n\\end{equation}\n\n\n```python\nclass InstanceNorm(nn.Module):\n    __constants__ = ['eps']\n    def __init__(self, nf, eps=1e-0):\n        super().__init__()\n        self.eps = eps\n        self.mults = nn.Parameter(torch.ones (nf,1,1))\n        self.adds  = nn.Parameter(torch.zeros(nf,1,1))\n\n    def forward(self, x):\n        m = x.mean((2,3), keepdim=True)\n        v = x.var ((2,3), keepdim=True)\n        res = (x-m) / ((v+self.eps).sqrt())\n        return res*self.mults + self.adds\n```\n\n\n```python\ndef conv_in(ni, nf, ks=3, stride=2, bn=True, **kwargs):\n    layers = [nn.Conv2d(ni, nf, ks, padding=ks//2, stride=stride, bias=True),\n              GeneralRelu(**kwargs)]\n    if bn: layers.append(InstanceNorm(nf))\n    return nn.Sequential(*layers)\n```\n\n\n```python\nlearn,run = get_learn_run(nfs, data, 0.1, conv_in, cbs=cbfs)\n```\n\n\n```python\n%time run.fit(3, learn)\n```\n\n    train: [nan, tensor(0.0986, device='cuda:0')]\n    valid: [nan, tensor(0.0991, device='cuda:0')]\n    train: [nan, tensor(0.0986, device='cuda:0')]\n    valid: [nan, tensor(0.0991, device='cuda:0')]\n    train: [nan, tensor(0.0986, device='cuda:0')]\n    valid: [nan, tensor(0.0991, device='cuda:0')]\n    CPU times: user 3.85 s, sys: 516 ms, total: 4.36 s\n    Wall time: 4.38 s\n\n\n### Group Norm\n\nA more general way of doing activation normalization.\n\n`GroupNorm(num_groups, num_channels, eps=1e-5, affine=True)`\n\nThe input channels are separated into `num_groups` groups, each containing\n``num_channels / num_groups`` channels. The mean and standard-deviation are calculated\nseparately over the each group. $\\gamma$ and $\\beta$ are learnable\nper-channel affine transform parameter vectorss of size `num_channels` if\n`affine` is ``True``.\n\nThis layer uses statistics computed from input data in both training and\nevaluation modes.\n\nArgs:\n-    num_groups (int): number of groups to separate the channels into\n-    num_channels (int): number of channels expected in input\n-    eps: a value added to the denominator for numerical stability. Default: 1e-5\n-    affine: a boolean value that when set to ``True``, this module\n        has learnable per-channel affine parameters initialized to ones (for weights)\n        and zeros (for biases). Default: ``True``.\n\nShape:\n- Input: `(N, num_channels, *)`\n- Output: `(N, num_channels, *)` (same shape as input)\n\nExamples::\n\n    >>> input = torch.randn(20, 6, 10, 10)\n    >>> # Separate 6 channels into 3 groups\n    >>> m = nn.GroupNorm(3, 6)\n    >>> # Separate 6 channels into 6 groups (equivalent with InstanceNorm)\n    >>> m = nn.GroupNorm(6, 6)\n    >>> # Put all 6 channels into a single group (equivalent with LayerNorm)\n    >>> m = nn.GroupNorm(1, 6)\n    >>> # Activating the module\n    >>> output = m(input)\n\n## Fix small batch sizes\n\n### What's the Problem\n\nAs the batch size gets smaller, its variance converges to 0 (the data points get closer to the mean).  \n\n\n```python\ndata = DataBunch(*get_dls(train_ds, valid_ds, 2), c)\n```\n\n\n```python\ndef conv_layer(ni, nf, ks=3, stride=2, bn=True, **kwargs):\n    layers = [nn.Conv2d(ni, nf, ks, padding=ks//2, stride=stride, bias=not bn),\n              GeneralRelu(**kwargs)]\n    if bn: layers.append(nn.BatchNorm2d(nf, eps=1e-5, momentum=0.1))\n    return nn.Sequential(*layers)\n```\n\n\n```python\nlearn,run = get_learn_run(nfs, data, 0.4, conv_layer, cbs=cbfs)\n```\n\n\n```python\n%time run.fit(1, learn)\n```\n\n    train: [2.34630625, tensor(0.1759, device='cuda:0')]\n    valid: [61394.6176, tensor(0.2345, device='cuda:0')]\n    CPU times: user 1min 28s, sys: 552 ms, total: 1min 28s\n    Wall time: 1min 30s\n\n\n### Running Batchnorm\n\nTo solve this problem we introduce a Running BatchNorm that uses smoother running mean and variance for the mean and std.\n\n\n```python\nclass RunningBatchNorm(nn.Module):\n    def __init__(self, nf, mom=0.1, eps=1e-5):\n        super().__init__()\n        self.mom,self.eps = mom,eps\n        self.mults = nn.Parameter(torch.ones (nf,1,1))\n        self.adds = nn.Parameter(torch.zeros(nf,1,1))\n        self.register_buffer('sums', torch.zeros(1,nf,1,1))\n        self.register_buffer('sqrs', torch.zeros(1,nf,1,1))\n        self.register_buffer('batch', tensor(0.))\n        self.register_buffer('count', tensor(0.))\n        self.register_buffer('step', tensor(0.))\n        self.register_buffer('dbias', tensor(0.))\n\n    def update_stats(self, x):\n        bs,nc,*_ = x.shape\n        self.sums.detach_()\n        self.sqrs.detach_()\n        dims = (0,2,3)\n        s = x.sum(dims, keepdim=True)\n        ss = (x*x).sum(dims, keepdim=True)\n        c = self.count.new_tensor(x.numel()/nc)\n        mom1 = 1 - (1-self.mom)/math.sqrt(bs-1)\n        self.mom1 = self.dbias.new_tensor(mom1)\n        self.sums.lerp_(s, self.mom1)\n        self.sqrs.lerp_(ss, self.mom1)\n        self.count.lerp_(c, self.mom1)\n        self.dbias = self.dbias*(1-self.mom1) + self.mom1\n        self.batch += bs\n        self.step += 1\n\n    def forward(self, x):\n        if self.training: self.update_stats(x)\n        sums = self.sums\n        sqrs = self.sqrs\n        c = self.count\n        if self.step<100:\n            sums = sums / self.dbias\n            sqrs = sqrs / self.dbias\n            c    = c    / self.dbias\n        means = sums/c\n        vars = (sqrs/c).sub_(means*means)\n        if bool(self.batch < 20): vars.clamp_min_(0.01)\n        x = (x-means).div_((vars.add_(self.eps)).sqrt())\n        return x.mul_(self.mults).add_(self.adds)\n```\n\n\n```python\ndef conv_rbn(ni, nf, ks=3, stride=2, bn=True, **kwargs):\n    layers = [nn.Conv2d(ni, nf, ks, padding=ks//2, stride=stride, bias=not bn),\n              GeneralRelu(**kwargs)]\n    if bn: layers.append(RunningBatchNorm(nf))\n    return nn.Sequential(*layers)\n```\n\n\n```python\nlearn,run = get_learn_run(nfs, data, 0.4, conv_rbn, cbs=cbfs)\n```\n\n\n```python\n%time run.fit(1, learn)\n```\n\n    train: [0.5531725390625, tensor(0.8519, device='cuda:0')]\n    valid: [0.232340380859375, tensor(0.9525, device='cuda:0')]\n    CPU times: user 3min 42s, sys: 1.25 s, total: 3min 43s\n    Wall time: 3min 45s\n\n\n## What can we do in a single epoch?\n\nNow let's see with a decent batch size what can we get.\n\n\n```python\ndata = DataBunch(*get_dls(train_ds, valid_ds, 32), c)\n```\n\n\n```python\nlearn,run = get_learn_run(nfs, data, 0.9, conv_rbn, cbs=cbfs\n                          +[partial(ParamScheduler,'lr', sched_lin(1., 0.2))])\n```\n\n\n```python\n%time run.fit(1, learn)\n```\n\n---\n", "meta": {"hexsha": "7a2d4891a57c11c65d2b7573781170bd686b4f5c", "size": 745683, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "02.ipynb", "max_stars_repo_name": "Akramz/Impractical-DL", "max_stars_repo_head_hexsha": "ff909e369fb765c0857800925e39c433057ae8ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "02.ipynb", "max_issues_repo_name": "Akramz/Impractical-DL", "max_issues_repo_head_hexsha": "ff909e369fb765c0857800925e39c433057ae8ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "02.ipynb", "max_forks_repo_name": "Akramz/Impractical-DL", "max_forks_repo_head_hexsha": "ff909e369fb765c0857800925e39c433057ae8ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 159.5043850267, "max_line_length": 94204, "alphanum_fraction": 0.893289776, "converted": true, "num_tokens": 18270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.07807816943541052, "lm_q1q2_score": 0.03599534620771426}}
{"text": "```python\nimport os\n```\n\n\n```python\nfrom pathlib import Path\n```\n\n\n```python\nPath(os.curdir).resolve()\n```\n\n\n\n\n    WindowsPath('C:/Users/owner/OneDrive/Documents/GitHub/gcv-lab')\n\n\n\n\n```python\nfrom copy import deepcopy\nfrom io import StringIO\nfrom math import *\nimport numpy as np\nfrom pathlib import Path\nimport pickle\nfrom pprint import pformat as pf, pprint as pp\nimport re\nfrom sympy import *\ninit_printing()\nimport sys\nimport warnings\n```\n\n\n```python\nos.listdir()\n```\n\n\n\n\n    ['.git',\n     '.gitignore',\n     '.ipynb_checkpoints',\n     'data',\n     'gc',\n     'gcv',\n     'LICENSE',\n     'ncv',\n     'notes',\n     'README.md',\n     'Untitled.ipynb']\n\n\n\n\n```python\nexec((Path('ncv/ncv/startup.py').read_text()))\n```\n\n    hello world\n\n\n\n```python\nls()\n```\n\n    data  gc  gcv  LICENSE  ncv  notes  README.md  Untitled.ipynb\n\n\n\n```python\n! dir\n```\n\n     Volume in drive C has no label.\n     Volume Serial Number is 8A3F-F6F5\n    \n     Directory of C:\\Users\\owner\\OneDrive\\Documents\\GitHub\\gcv-lab\n    \n    08/09/2020  04:51 PM    <DIR>          .\n    08/09/2020  04:51 PM    <DIR>          ..\n    08/02/2020  06:40 AM             1,928 .gitignore\n    08/09/2020  04:51 PM    <DIR>          .ipynb_checkpoints\n    08/02/2020  06:42 AM    <DIR>          data\n    08/05/2020  03:43 AM    <DIR>          gc\n    08/09/2020  02:57 PM    <DIR>          gcv\n    08/02/2020  06:40 AM             1,089 LICENSE\n    08/02/2020  07:03 AM    <DIR>          ncv\n    08/09/2020  02:53 PM    <DIR>          notes\n    08/02/2020  06:40 AM               109 README.md\n    08/05/2020  04:17 AM             2,719 Untitled.ipynb\n                   4 File(s)          5,845 bytes\n                   8 Dir(s)  892,644,352,000 bytes free\n\n\n\n```python\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection\nimport numpy as np\n```\n\n\n```python\nfig = plt.figure()\nax = fig.gca(projection='3d')\nnphi, nz = 12,20\nr=1\nphi = np.linspace(0, 360, nphi)/180.0*np.pi\nz = np.linspace(0,1.0,nz)\nprint(z)\nfacecolors = ['r','g','b','y']\ncols = []\nverts2 = []\nfor i in range(len(phi)-1):\n    cp0 = r*np.cos(phi[i])\n    cp1 = r*np.cos(phi[i+1])\n    sp0 = r*np.sin(phi[i])\n    sp1 = r*np.sin(phi[i+1])\n    \n    for j in range(len(z)-1):\n        z0=z[j]\n        z1=z[j+1]\n        verts=[]\n        verts.append((cp0, sp0, z0))\n        verts.append((cp1, sp1, z0))\n        verts.append((cp1, sp1, z1))\n        verts.append((cp0, sp0, z1))\n        verts2.append(verts)\n        value=np.random.rand()\n        print(value)\n        col = plt.cm.bwr(value)\n        print(col)\n        cols.append(col)\n        \npoly3 = Poly3DCollection(verts2, facecolor=cols)\npoly3.set_alpha(0.8)\nax.add_collection3d(poly3)\nax.set_xlabel('X')\nax.set_xlim3d(-1,1)\nax.set_ylabel('Y')\nax.set_ylim3d(-1,1)\nax.set_zlabel('Z')\nax.set_zlim3d(0,1)\nplt.show()\n```\n\n\n```python\n[s for s in dir(mp3d.art3d) if not s.startswith('_')]\n```\n\n\n\n\n    ['Line3D',\n     'Line3DCollection',\n     'LineCollection',\n     'Normalize',\n     'Patch',\n     'Patch3D',\n     'Patch3DCollection',\n     'PatchCollection',\n     'Path3DCollection',\n     'PathCollection',\n     'PathPatch3D',\n     'Poly3DCollection',\n     'PolyCollection',\n     'Text3D',\n     'artist',\n     'get_dir_vector',\n     'juggle_axes',\n     'line_2d_to_3d',\n     'line_collection_2d_to_3d',\n     'lines',\n     'math',\n     'mcolors',\n     'mpath',\n     'mtext',\n     'np',\n     'patch_2d_to_3d',\n     'patch_collection_2d_to_3d',\n     'pathpatch_2d_to_3d',\n     'poly_collection_2d_to_3d',\n     'proj3d',\n     'rotate_axes',\n     'text_2d_to_3d']\n\n\n\n\n```python\nhelp(mp3d.art3d.patch_2d_to_3d)\n```\n\n    Help on function patch_2d_to_3d in module mpl_toolkits.mplot3d.art3d:\n    \n    patch_2d_to_3d(patch, z=0, zdir='z')\n        Convert a Patch to a Patch3D object.\n    \n\n\n\n```python\n[s for s in dir(mp3d.art3d.Patch3DCollection) if not s.startswith('_')]\n```\n\n\n\n\n    ['add_callback',\n     'add_checker',\n     'autoscale',\n     'autoscale_None',\n     'axes',\n     'changed',\n     'check_update',\n     'contains',\n     'convert_xunits',\n     'convert_yunits',\n     'do_3d_projection',\n     'draw',\n     'findobj',\n     'format_cursor_data',\n     'get_agg_filter',\n     'get_alpha',\n     'get_animated',\n     'get_array',\n     'get_capstyle',\n     'get_children',\n     'get_clim',\n     'get_clip_box',\n     'get_clip_on',\n     'get_clip_path',\n     'get_cmap',\n     'get_contains',\n     'get_cursor_data',\n     'get_dashes',\n     'get_datalim',\n     'get_ec',\n     'get_edgecolor',\n     'get_edgecolors',\n     'get_facecolor',\n     'get_facecolors',\n     'get_fc',\n     'get_figure',\n     'get_fill',\n     'get_gid',\n     'get_hatch',\n     'get_in_layout',\n     'get_joinstyle',\n     'get_label',\n     'get_linestyle',\n     'get_linestyles',\n     'get_linewidth',\n     'get_linewidths',\n     'get_ls',\n     'get_lw',\n     'get_offset_position',\n     'get_offset_transform',\n     'get_offsets',\n     'get_path_effects',\n     'get_paths',\n     'get_picker',\n     'get_pickradius',\n     'get_rasterized',\n     'get_sketch_params',\n     'get_snap',\n     'get_tightbbox',\n     'get_transform',\n     'get_transformed_clip_path_and_affine',\n     'get_transforms',\n     'get_url',\n     'get_urls',\n     'get_visible',\n     'get_window_extent',\n     'get_zorder',\n     'have_units',\n     'is_transform_set',\n     'mouseover',\n     'pchanged',\n     'pick',\n     'pickable',\n     'properties',\n     'remove',\n     'remove_callback',\n     'set',\n     'set_3d_properties',\n     'set_aa',\n     'set_agg_filter',\n     'set_alpha',\n     'set_animated',\n     'set_antialiased',\n     'set_antialiaseds',\n     'set_array',\n     'set_capstyle',\n     'set_clim',\n     'set_clip_box',\n     'set_clip_on',\n     'set_clip_path',\n     'set_cmap',\n     'set_color',\n     'set_contains',\n     'set_dashes',\n     'set_ec',\n     'set_edgecolor',\n     'set_edgecolors',\n     'set_facecolor',\n     'set_facecolors',\n     'set_fc',\n     'set_figure',\n     'set_gid',\n     'set_hatch',\n     'set_in_layout',\n     'set_joinstyle',\n     'set_label',\n     'set_linestyle',\n     'set_linestyles',\n     'set_linewidth',\n     'set_linewidths',\n     'set_ls',\n     'set_lw',\n     'set_norm',\n     'set_offset_position',\n     'set_offsets',\n     'set_path_effects',\n     'set_paths',\n     'set_picker',\n     'set_pickradius',\n     'set_rasterized',\n     'set_sketch_params',\n     'set_snap',\n     'set_sort_zpos',\n     'set_transform',\n     'set_url',\n     'set_urls',\n     'set_visible',\n     'set_zorder',\n     'stale',\n     'sticky_edges',\n     'to_rgba',\n     'update',\n     'update_dict',\n     'update_from',\n     'update_scalarmappable',\n     'zorder']\n\n\n\n\n```python\nhelp(ax.add_patch)\n```\n\n    Help on method add_patch in module matplotlib.axes._base:\n    \n    add_patch(p) method of matplotlib.axes._subplots.Axes3DSubplot instance\n        Add a `~.Patch` to the axes' patches; return the patch.\n    \n\n\n\n```python\nhelp(mp3d.art3d.Patch3DCollection)\n```\n\n    Help on class Patch3DCollection in module mpl_toolkits.mplot3d.art3d:\n    \n    class Patch3DCollection(matplotlib.collections.PatchCollection)\n     |  Patch3DCollection(*args, zs=0, zdir='z', depthshade=True, **kwargs)\n     |  \n     |  A collection of 3D patches.\n     |  \n     |  Method resolution order:\n     |      Patch3DCollection\n     |      matplotlib.collections.PatchCollection\n     |      matplotlib.collections.Collection\n     |      matplotlib.artist.Artist\n     |      matplotlib.cm.ScalarMappable\n     |      builtins.object\n     |  \n     |  Methods defined here:\n     |  \n     |  __init__(self, *args, zs=0, zdir='z', depthshade=True, **kwargs)\n     |      Create a collection of flat 3D patches with its normal vector\n     |      pointed in *zdir* direction, and located at *zs* on the *zdir*\n     |      axis. 'zs' can be a scalar or an array-like of the same length as\n     |      the number of patches in the collection.\n     |      \n     |      Constructor arguments are the same as for\n     |      :class:`~matplotlib.collections.PatchCollection`. In addition,\n     |      keywords *zs=0* and *zdir='z'* are available.\n     |      \n     |      Also, the keyword argument \"depthshade\" is available to\n     |      indicate whether or not to shade the patches in order to\n     |      give the appearance of depth (default is *True*).\n     |      This is typically desired in scatter plots.\n     |  \n     |  do_3d_projection(self, renderer)\n     |  \n     |  set_3d_properties(self, zs, zdir)\n     |  \n     |  set_sort_zpos(self, val)\n     |      Set the position to use for z-sorting.\n     |  \n     |  ----------------------------------------------------------------------\n     |  Methods inherited from matplotlib.collections.PatchCollection:\n     |  \n     |  set_paths(self, patches)\n     |  \n     |  ----------------------------------------------------------------------\n     |  Methods inherited from matplotlib.collections.Collection:\n     |  \n     |  contains(self, mouseevent)\n     |      Test whether the mouse event occurred in the collection.\n     |      \n     |      Returns ``bool, dict(ind=itemlist)``, where every item in itemlist\n     |      contains the event.\n     |  \n     |  draw(self, renderer)\n     |      Draw the Artist (and its children) using the given renderer.\n     |      \n     |      This has no effect if the artist is not visible (`.Artist.get_visible`\n     |      returns False).\n     |      \n     |      Parameters\n     |      ----------\n     |      renderer : `.RendererBase` subclass.\n     |      \n     |      Notes\n     |      -----\n     |      This method is overridden in the Artist subclasses.\n     |  \n     |  get_capstyle(self)\n     |  \n     |  get_dashes(self)\n     |      Alias for `get_linestyle`.\n     |  \n     |  get_datalim(self, transData)\n     |  \n     |  get_ec(self)\n     |      Alias for `get_edgecolor`.\n     |  \n     |  get_edgecolor(self)\n     |  \n     |  get_edgecolors(self)\n     |      Alias for `get_edgecolor`.\n     |  \n     |  get_facecolor(self)\n     |  \n     |  get_facecolors(self)\n     |      Alias for `get_facecolor`.\n     |  \n     |  get_fc(self)\n     |      Alias for `get_facecolor`.\n     |  \n     |  get_fill(self)\n     |      Return whether fill is set.\n     |  \n     |  get_hatch(self)\n     |      Return the current hatching pattern.\n     |  \n     |  get_joinstyle(self)\n     |  \n     |  get_linestyle(self)\n     |  \n     |  get_linestyles(self)\n     |      Alias for `get_linestyle`.\n     |  \n     |  get_linewidth(self)\n     |  \n     |  get_linewidths(self)\n     |      Alias for `get_linewidth`.\n     |  \n     |  get_ls(self)\n     |      Alias for `get_linestyle`.\n     |  \n     |  get_lw(self)\n     |      Alias for `get_linewidth`.\n     |  \n     |  get_offset_position(self)\n     |      [*Deprecated*] Return how offsets are applied for the collection.  If\n     |      *offset_position* is 'screen', the offset is applied after the\n     |      master transform has been applied, that is, the offsets are in\n     |      screen coordinates.  If offset_position is 'data', the offset\n     |      is applied before the master transform, i.e., the offsets are\n     |      in data coordinates.\n     |      \n     |      Notes\n     |      -----\n     |      .. deprecated:: 3.3\n     |  \n     |  get_offset_transform(self)\n     |  \n     |  get_offsets(self)\n     |      Return the offsets for the collection.\n     |  \n     |  get_paths(self)\n     |  \n     |  get_pickradius(self)\n     |  \n     |  get_transforms(self)\n     |  \n     |  get_urls(self)\n     |      Return a list of URLs, one for each element of the collection.\n     |      \n     |      The list contains *None* for elements without a URL. See\n     |      :doc:`/gallery/misc/hyperlinks_sgskip` for an example.\n     |  \n     |  get_window_extent(self, renderer)\n     |      Get the axes bounding box in display space.\n     |      \n     |      The bounding box' width and height are nonnegative.\n     |      \n     |      Subclasses should override for inclusion in the bounding box\n     |      \"tight\" calculation. Default is to return an empty bounding\n     |      box at 0, 0.\n     |      \n     |      Be careful when using this function, the results will not update\n     |      if the artist window extent of the artist changes.  The extent\n     |      can change due to any changes in the transform stack, such as\n     |      changing the axes limits, the figure size, or the canvas used\n     |      (as is done when saving a figure).  This can lead to unexpected\n     |      behavior where interactive figures will look fine on the screen,\n     |      but will save incorrectly.\n     |  \n     |  set_aa(self, aa)\n     |      Alias for `set_antialiased`.\n     |  \n     |  set_alpha(self, alpha)\n     |      Set the alpha value used for blending - not supported on all backends.\n     |      \n     |      Parameters\n     |      ----------\n     |      alpha : float or None\n     |  \n     |  set_antialiased(self, aa)\n     |      Set the antialiasing state for rendering.\n     |      \n     |      Parameters\n     |      ----------\n     |      aa : bool or list of bools\n     |  \n     |  set_antialiaseds(self, aa)\n     |      Alias for `set_antialiased`.\n     |  \n     |  set_capstyle(self, cs)\n     |      Set the capstyle for the collection (for all its elements).\n     |      \n     |      Parameters\n     |      ----------\n     |      cs : {'butt', 'round', 'projecting'}\n     |          The capstyle.\n     |  \n     |  set_color(self, c)\n     |      Set both the edgecolor and the facecolor.\n     |      \n     |      Parameters\n     |      ----------\n     |      c : color or list of rgba tuples\n     |      \n     |      See Also\n     |      --------\n     |      Collection.set_facecolor, Collection.set_edgecolor\n     |          For setting the edge or face color individually.\n     |  \n     |  set_dashes(self, ls)\n     |      Alias for `set_linestyle`.\n     |  \n     |  set_ec(self, c)\n     |      Alias for `set_edgecolor`.\n     |  \n     |  set_edgecolor(self, c)\n     |      Set the edgecolor(s) of the collection.\n     |      \n     |      Parameters\n     |      ----------\n     |      c : color or list of colors or 'face'\n     |          The collection edgecolor(s).  If a sequence, the patches cycle\n     |          through it.  If 'face', match the facecolor.\n     |  \n     |  set_edgecolors(self, c)\n     |      Alias for `set_edgecolor`.\n     |  \n     |  set_facecolor(self, c)\n     |      Set the facecolor(s) of the collection. *c* can be a color (all patches\n     |      have same color), or a sequence of colors; if it is a sequence the\n     |      patches will cycle through the sequence.\n     |      \n     |      If *c* is 'none', the patch will not be filled.\n     |      \n     |      Parameters\n     |      ----------\n     |      c : color or list of colors\n     |  \n     |  set_facecolors(self, c)\n     |      Alias for `set_facecolor`.\n     |  \n     |  set_fc(self, c)\n     |      Alias for `set_facecolor`.\n     |  \n     |  set_hatch(self, hatch)\n     |      Set the hatching pattern\n     |      \n     |      *hatch* can be one of::\n     |      \n     |        /   - diagonal hatching\n     |        \\   - back diagonal\n     |        |   - vertical\n     |        -   - horizontal\n     |        +   - crossed\n     |        x   - crossed diagonal\n     |        o   - small circle\n     |        O   - large circle\n     |        .   - dots\n     |        *   - stars\n     |      \n     |      Letters can be combined, in which case all the specified\n     |      hatchings are done.  If same letter repeats, it increases the\n     |      density of hatching of that pattern.\n     |      \n     |      Hatching is supported in the PostScript, PDF, SVG and Agg\n     |      backends only.\n     |      \n     |      Unlike other properties such as linewidth and colors, hatching\n     |      can only be specified for the collection as a whole, not separately\n     |      for each member.\n     |      \n     |      Parameters\n     |      ----------\n     |      hatch : {'/', '\\\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}\n     |  \n     |  set_joinstyle(self, js)\n     |      Set the joinstyle for the collection (for all its elements).\n     |      \n     |      Parameters\n     |      ----------\n     |      js : {'miter', 'round', 'bevel'}\n     |          The joinstyle.\n     |  \n     |  set_linestyle(self, ls)\n     |      Set the linestyle(s) for the collection.\n     |      \n     |      ===========================   =================\n     |      linestyle                     description\n     |      ===========================   =================\n     |      ``'-'`` or ``'solid'``        solid line\n     |      ``'--'`` or  ``'dashed'``     dashed line\n     |      ``'-.'`` or  ``'dashdot'``    dash-dotted line\n     |      ``':'`` or ``'dotted'``       dotted line\n     |      ===========================   =================\n     |      \n     |      Alternatively a dash tuple of the following form can be provided::\n     |      \n     |          (offset, onoffseq),\n     |      \n     |      where ``onoffseq`` is an even length tuple of on and off ink in points.\n     |      \n     |      Parameters\n     |      ----------\n     |      ls : str or tuple or list thereof\n     |          Valid values for individual linestyles include {'-', '--', '-.',\n     |          ':', '', (offset, on-off-seq)}. See `.Line2D.set_linestyle` for a\n     |          complete description.\n     |  \n     |  set_linestyles(self, ls)\n     |      Alias for `set_linestyle`.\n     |  \n     |  set_linewidth(self, lw)\n     |      Set the linewidth(s) for the collection.  *lw* can be a scalar\n     |      or a sequence; if it is a sequence the patches will cycle\n     |      through the sequence\n     |      \n     |      Parameters\n     |      ----------\n     |      lw : float or list of floats\n     |  \n     |  set_linewidths(self, lw)\n     |      Alias for `set_linewidth`.\n     |  \n     |  set_ls(self, ls)\n     |      Alias for `set_linestyle`.\n     |  \n     |  set_lw(self, lw)\n     |      Alias for `set_linewidth`.\n     |  \n     |  set_offset_position(self, offset_position)\n     |      [*Deprecated*] Set how offsets are applied.  If *offset_position* is 'screen'\n     |      (default) the offset is applied after the master transform has\n     |      been applied, that is, the offsets are in screen coordinates.\n     |      If offset_position is 'data', the offset is applied before the\n     |      master transform, i.e., the offsets are in data coordinates.\n     |      \n     |      Parameters\n     |      ----------\n     |      offset_position : {'screen', 'data'}\n     |      \n     |      Notes\n     |      -----\n     |      .. deprecated:: 3.3\n     |  \n     |  set_offsets(self, offsets)\n     |      Set the offsets for the collection.\n     |      \n     |      Parameters\n     |      ----------\n     |      offsets : array-like (N, 2) or (2,)\n     |  \n     |  set_pickradius(self, pr)\n     |      Set the pick radius used for containment tests.\n     |      \n     |      Parameters\n     |      ----------\n     |      d : float\n     |          Pick radius, in points.\n     |  \n     |  set_urls(self, urls)\n     |      Parameters\n     |      ----------\n     |      urls : list of str or None\n     |      \n     |      Notes\n     |      -----\n     |      URLs are currently only implemented by the SVG backend. They are\n     |      ignored by all other backends.\n     |  \n     |  update_from(self, other)\n     |      Copy properties from other to self.\n     |  \n     |  update_scalarmappable(self)\n     |      Update colors from the scalar mappable array, if it is not None.\n     |  \n     |  ----------------------------------------------------------------------\n     |  Methods inherited from matplotlib.artist.Artist:\n     |  \n     |  __getstate__(self)\n     |  \n     |  add_callback(self, func)\n     |      Add a callback function that will be called whenever one of the\n     |      `.Artist`'s properties changes.\n     |      \n     |      Parameters\n     |      ----------\n     |      func : callable\n     |          The callback function. It must have the signature::\n     |      \n     |              def func(artist: Artist) -> Any\n     |      \n     |          where *artist* is the calling `.Artist`. Return values may exist\n     |          but are ignored.\n     |      \n     |      Returns\n     |      -------\n     |      int\n     |          The observer id associated with the callback. This id can be\n     |          used for removing the callback with `.remove_callback` later.\n     |      \n     |      See Also\n     |      --------\n     |      remove_callback\n     |  \n     |  convert_xunits(self, x)\n     |      Convert *x* using the unit type of the xaxis.\n     |      \n     |      If the artist is not in contained in an Axes or if the xaxis does not\n     |      have units, *x* itself is returned.\n     |  \n     |  convert_yunits(self, y)\n     |      Convert *y* using the unit type of the yaxis.\n     |      \n     |      If the artist is not in contained in an Axes or if the yaxis does not\n     |      have units, *y* itself is returned.\n     |  \n     |  findobj(self, match=None, include_self=True)\n     |      Find artist objects.\n     |      \n     |      Recursively find all `.Artist` instances contained in the artist.\n     |      \n     |      Parameters\n     |      ----------\n     |      match\n     |          A filter criterion for the matches. This can be\n     |      \n     |          - *None*: Return all objects contained in artist.\n     |          - A function with signature ``def match(artist: Artist) -> bool``.\n     |            The result will only contain artists for which the function\n     |            returns *True*.\n     |          - A class instance: e.g., `.Line2D`. The result will only contain\n     |            artists of this class or its subclasses (``isinstance`` check).\n     |      \n     |      include_self : bool\n     |          Include *self* in the list to be checked for a match.\n     |      \n     |      Returns\n     |      -------\n     |      list of `.Artist`\n     |  \n     |  format_cursor_data(self, data)\n     |      Return a string representation of *data*.\n     |      \n     |      .. note::\n     |          This method is intended to be overridden by artist subclasses.\n     |          As an end-user of Matplotlib you will most likely not call this\n     |          method yourself.\n     |      \n     |      The default implementation converts ints and floats and arrays of ints\n     |      and floats into a comma-separated string enclosed in square brackets.\n     |      \n     |      See Also\n     |      --------\n     |      get_cursor_data\n     |  \n     |  get_agg_filter(self)\n     |      Return filter function to be used for agg filter.\n     |  \n     |  get_alpha(self)\n     |      Return the alpha value used for blending - not supported on all\n     |      backends.\n     |  \n     |  get_animated(self)\n     |      Return whether the artist is animated.\n     |  \n     |  get_children(self)\n     |      Return a list of the child `.Artist`\\s of this `.Artist`.\n     |  \n     |  get_clip_box(self)\n     |      Return the clipbox.\n     |  \n     |  get_clip_on(self)\n     |      Return whether the artist uses clipping.\n     |  \n     |  get_clip_path(self)\n     |      Return the clip path.\n     |  \n     |  get_contains(self)\n     |      [*Deprecated*] Return the custom contains function of the artist if set, or *None*.\n     |      \n     |      See Also\n     |      --------\n     |      set_contains\n     |      \n     |      Notes\n     |      -----\n     |      .. deprecated:: 3.3\n     |  \n     |  get_cursor_data(self, event)\n     |      Return the cursor data for a given event.\n     |      \n     |      .. note::\n     |          This method is intended to be overridden by artist subclasses.\n     |          As an end-user of Matplotlib you will most likely not call this\n     |          method yourself.\n     |      \n     |      Cursor data can be used by Artists to provide additional context\n     |      information for a given event. The default implementation just returns\n     |      *None*.\n     |      \n     |      Subclasses can override the method and return arbitrary data. However,\n     |      when doing so, they must ensure that `.format_cursor_data` can convert\n     |      the data to a string representation.\n     |      \n     |      The only current use case is displaying the z-value of an `.AxesImage`\n     |      in the status bar of a plot window, while moving the mouse.\n     |      \n     |      Parameters\n     |      ----------\n     |      event : `matplotlib.backend_bases.MouseEvent`\n     |      \n     |      See Also\n     |      --------\n     |      format_cursor_data\n     |  \n     |  get_figure(self)\n     |      Return the `.Figure` instance the artist belongs to.\n     |  \n     |  get_gid(self)\n     |      Return the group id.\n     |  \n     |  get_in_layout(self)\n     |      Return boolean flag, ``True`` if artist is included in layout\n     |      calculations.\n     |      \n     |      E.g. :doc:`/tutorials/intermediate/constrainedlayout_guide`,\n     |      `.Figure.tight_layout()`, and\n     |      ``fig.savefig(fname, bbox_inches='tight')``.\n     |  \n     |  get_label(self)\n     |      Return the label used for this artist in the legend.\n     |  \n     |  get_path_effects(self)\n     |  \n     |  get_picker(self)\n     |      Return the picking behavior of the artist.\n     |      \n     |      The possible values are described in `.set_picker`.\n     |      \n     |      See Also\n     |      --------\n     |      set_picker, pickable, pick\n     |  \n     |  get_rasterized(self)\n     |      Return whether the artist is to be rasterized.\n     |  \n     |  get_sketch_params(self)\n     |      Return the sketch parameters for the artist.\n     |      \n     |      Returns\n     |      -------\n     |      tuple or None\n     |      \n     |          A 3-tuple with the following elements:\n     |      \n     |          - *scale*: The amplitude of the wiggle perpendicular to the\n     |            source line.\n     |          - *length*: The length of the wiggle along the line.\n     |          - *randomness*: The scale factor by which the length is\n     |            shrunken or expanded.\n     |      \n     |          Returns *None* if no sketch parameters were set.\n     |  \n     |  get_snap(self)\n     |      Return the snap setting.\n     |      \n     |      See `.set_snap` for details.\n     |  \n     |  get_tightbbox(self, renderer)\n     |      Like `.Artist.get_window_extent`, but includes any clipping.\n     |      \n     |      Parameters\n     |      ----------\n     |      renderer : `.RendererBase` subclass\n     |          renderer that will be used to draw the figures (i.e.\n     |          ``fig.canvas.get_renderer()``)\n     |      \n     |      Returns\n     |      -------\n     |      `.Bbox`\n     |          The enclosing bounding box (in figure pixel coordinates).\n     |  \n     |  get_transform(self)\n     |      Return the `.Transform` instance used by this artist.\n     |  \n     |  get_transformed_clip_path_and_affine(self)\n     |      Return the clip path with the non-affine part of its\n     |      transformation applied, and the remaining affine part of its\n     |      transformation.\n     |  \n     |  get_url(self)\n     |      Return the url.\n     |  \n     |  get_visible(self)\n     |      Return the visibility.\n     |  \n     |  get_zorder(self)\n     |      Return the artist's zorder.\n     |  \n     |  have_units(self)\n     |      Return *True* if units are set on any axis.\n     |  \n     |  is_transform_set(self)\n     |      Return whether the Artist has an explicitly set transform.\n     |      \n     |      This is *True* after `.set_transform` has been called.\n     |  \n     |  pchanged(self)\n     |      Call all of the registered callbacks.\n     |      \n     |      This function is triggered internally when a property is changed.\n     |      \n     |      See Also\n     |      --------\n     |      add_callback\n     |      remove_callback\n     |  \n     |  pick(self, mouseevent)\n     |      Process a pick event.\n     |      \n     |      Each child artist will fire a pick event if *mouseevent* is over\n     |      the artist and the artist has picker set.\n     |      \n     |      See Also\n     |      --------\n     |      set_picker, get_picker, pickable\n     |  \n     |  pickable(self)\n     |      Return whether the artist is pickable.\n     |      \n     |      See Also\n     |      --------\n     |      set_picker, get_picker, pick\n     |  \n     |  properties(self)\n     |      Return a dictionary of all the properties of the artist.\n     |  \n     |  remove(self)\n     |      Remove the artist from the figure if possible.\n     |      \n     |      The effect will not be visible until the figure is redrawn, e.g.,\n     |      with `.FigureCanvasBase.draw_idle`.  Call `~.axes.Axes.relim` to\n     |      update the axes limits if desired.\n     |      \n     |      Note: `~.axes.Axes.relim` will not see collections even if the\n     |      collection was added to the axes with *autolim* = True.\n     |      \n     |      Note: there is no support for removing the artist's legend entry.\n     |  \n     |  remove_callback(self, oid)\n     |      Remove a callback based on its observer id.\n     |      \n     |      See Also\n     |      --------\n     |      add_callback\n     |  \n     |  set(self, **kwargs)\n     |      A property batch setter.  Pass *kwargs* to set properties.\n     |  \n     |  set_agg_filter(self, filter_func)\n     |      Set the agg filter.\n     |      \n     |      Parameters\n     |      ----------\n     |      filter_func : callable\n     |          A filter function, which takes a (m, n, 3) float array and a dpi\n     |          value, and returns a (m, n, 3) array.\n     |      \n     |          .. ACCEPTS: a filter function, which takes a (m, n, 3) float array\n     |              and a dpi value, and returns a (m, n, 3) array\n     |  \n     |  set_animated(self, b)\n     |      Set the artist's animation state.\n     |      \n     |      Parameters\n     |      ----------\n     |      b : bool\n     |  \n     |  set_clip_box(self, clipbox)\n     |      Set the artist's clip `.Bbox`.\n     |      \n     |      Parameters\n     |      ----------\n     |      clipbox : `.Bbox`\n     |  \n     |  set_clip_on(self, b)\n     |      Set whether the artist uses clipping.\n     |      \n     |      When False artists will be visible outside of the axes which\n     |      can lead to unexpected results.\n     |      \n     |      Parameters\n     |      ----------\n     |      b : bool\n     |  \n     |  set_clip_path(self, path, transform=None)\n     |      Set the artist's clip path.\n     |      \n     |      Parameters\n     |      ----------\n     |      path : `.Patch` or `.Path` or `.TransformedPath` or None\n     |          The clip path. If given a `.Path`, *transform* must be provided as\n     |          well. If *None*, a previously set clip path is removed.\n     |      transform : `~matplotlib.transforms.Transform`, optional\n     |          Only used if *path* is a `.Path`, in which case the given `.Path`\n     |          is converted to a `.TransformedPath` using *transform*.\n     |      \n     |      Notes\n     |      -----\n     |      For efficiency, if *path* is a `.Rectangle` this method will set the\n     |      clipping box to the corresponding rectangle and set the clipping path\n     |      to ``None``.\n     |      \n     |      For technical reasons (support of `~.Artist.set`), a tuple\n     |      (*path*, *transform*) is also accepted as a single positional\n     |      parameter.\n     |      \n     |      .. ACCEPTS: Patch or (Path, Transform) or None\n     |  \n     |  set_contains(self, picker)\n     |      [*Deprecated*] Define a custom contains test for the artist.\n     |      \n     |      The provided callable replaces the default `.contains` method\n     |      of the artist.\n     |      \n     |      Parameters\n     |      ----------\n     |      picker : callable\n     |          A custom picker function to evaluate if an event is within the\n     |          artist. The function must have the signature::\n     |      \n     |              def contains(artist: Artist, event: MouseEvent) -> bool, dict\n     |      \n     |          that returns:\n     |      \n     |          - a bool indicating if the event is within the artist\n     |          - a dict of additional information. The dict should at least\n     |            return the same information as the default ``contains()``\n     |            implementation of the respective artist, but may provide\n     |            additional information.\n     |      \n     |      Notes\n     |      -----\n     |      .. deprecated:: 3.3\n     |  \n     |  set_figure(self, fig)\n     |      Set the `.Figure` instance the artist belongs to.\n     |      \n     |      Parameters\n     |      ----------\n     |      fig : `.Figure`\n     |  \n     |  set_gid(self, gid)\n     |      Set the (group) id for the artist.\n     |      \n     |      Parameters\n     |      ----------\n     |      gid : str\n     |  \n     |  set_in_layout(self, in_layout)\n     |      Set if artist is to be included in layout calculations,\n     |      E.g. :doc:`/tutorials/intermediate/constrainedlayout_guide`,\n     |      `.Figure.tight_layout()`, and\n     |      ``fig.savefig(fname, bbox_inches='tight')``.\n     |      \n     |      Parameters\n     |      ----------\n     |      in_layout : bool\n     |  \n     |  set_label(self, s)\n     |      Set a label that will be displayed in the legend.\n     |      \n     |      Parameters\n     |      ----------\n     |      s : object\n     |          *s* will be converted to a string by calling `str`.\n     |  \n     |  set_path_effects(self, path_effects)\n     |      Set the path effects.\n     |      \n     |      Parameters\n     |      ----------\n     |      path_effects : `.AbstractPathEffect`\n     |  \n     |  set_picker(self, picker)\n     |      Define the picking behavior of the artist.\n     |      \n     |      Parameters\n     |      ----------\n     |      picker : None or bool or callable\n     |          This can be one of the following:\n     |      \n     |          - *None*: Picking is disabled for this artist (default).\n     |      \n     |          - A boolean: If *True* then picking will be enabled and the\n     |            artist will fire a pick event if the mouse event is over\n     |            the artist.\n     |      \n     |          - A function: If picker is callable, it is a user supplied\n     |            function which determines whether the artist is hit by the\n     |            mouse event::\n     |      \n     |              hit, props = picker(artist, mouseevent)\n     |      \n     |            to determine the hit test.  if the mouse event is over the\n     |            artist, return *hit=True* and props is a dictionary of\n     |            properties you want added to the PickEvent attributes.\n     |      \n     |          - *deprecated*: For `.Line2D` only, *picker* can also be a float\n     |            that sets the tolerance for checking whether an event occurred\n     |            \"on\" the line; this is deprecated.  Use `.Line2D.set_pickradius`\n     |            instead.\n     |  \n     |  set_rasterized(self, rasterized)\n     |      Force rasterized (bitmap) drawing in vector backend output.\n     |      \n     |      Defaults to None, which implies the backend's default behavior.\n     |      \n     |      Parameters\n     |      ----------\n     |      rasterized : bool or None\n     |  \n     |  set_sketch_params(self, scale=None, length=None, randomness=None)\n     |      Sets the sketch parameters.\n     |      \n     |      Parameters\n     |      ----------\n     |      scale : float, optional\n     |          The amplitude of the wiggle perpendicular to the source\n     |          line, in pixels.  If scale is `None`, or not provided, no\n     |          sketch filter will be provided.\n     |      length : float, optional\n     |           The length of the wiggle along the line, in pixels\n     |           (default 128.0)\n     |      randomness : float, optional\n     |          The scale factor by which the length is shrunken or\n     |          expanded (default 16.0)\n     |      \n     |          .. ACCEPTS: (scale: float, length: float, randomness: float)\n     |  \n     |  set_snap(self, snap)\n     |      Set the snapping behavior.\n     |      \n     |      Snapping aligns positions with the pixel grid, which results in\n     |      clearer images. For example, if a black line of 1px width was\n     |      defined at a position in between two pixels, the resulting image\n     |      would contain the interpolated value of that line in the pixel grid,\n     |      which would be a grey value on both adjacent pixel positions. In\n     |      contrast, snapping will move the line to the nearest integer pixel\n     |      value, so that the resulting image will really contain a 1px wide\n     |      black line.\n     |      \n     |      Snapping is currently only supported by the Agg and MacOSX backends.\n     |      \n     |      Parameters\n     |      ----------\n     |      snap : bool or None\n     |          Possible values:\n     |      \n     |          - *True*: Snap vertices to the nearest pixel center.\n     |          - *False*: Do not modify vertex positions.\n     |          - *None*: (auto) If the path contains only rectilinear line\n     |            segments, round to the nearest pixel center.\n     |  \n     |  set_transform(self, t)\n     |      Set the artist transform.\n     |      \n     |      Parameters\n     |      ----------\n     |      t : `.Transform`\n     |  \n     |  set_url(self, url)\n     |      Set the url for the artist.\n     |      \n     |      Parameters\n     |      ----------\n     |      url : str\n     |  \n     |  set_visible(self, b)\n     |      Set the artist's visibility.\n     |      \n     |      Parameters\n     |      ----------\n     |      b : bool\n     |  \n     |  set_zorder(self, level)\n     |      Set the zorder for the artist.  Artists with lower zorder\n     |      values are drawn first.\n     |      \n     |      Parameters\n     |      ----------\n     |      level : float\n     |  \n     |  update(self, props)\n     |      Update this artist's properties from the dict *props*.\n     |      \n     |      Parameters\n     |      ----------\n     |      props : dict\n     |  \n     |  ----------------------------------------------------------------------\n     |  Readonly properties inherited from matplotlib.artist.Artist:\n     |  \n     |  sticky_edges\n     |      ``x`` and ``y`` sticky edge lists for autoscaling.\n     |      \n     |      When performing autoscaling, if a data limit coincides with a value in\n     |      the corresponding sticky_edges list, then no margin will be added--the\n     |      view limit \"sticks\" to the edge. A typical use case is histograms,\n     |      where one usually expects no margin on the bottom edge (0) of the\n     |      histogram.\n     |      \n     |      This attribute cannot be assigned to; however, the ``x`` and ``y``\n     |      lists can be modified in place as needed.\n     |      \n     |      Examples\n     |      --------\n     |      >>> artist.sticky_edges.x[:] = (xmin, xmax)\n     |      >>> artist.sticky_edges.y[:] = (ymin, ymax)\n     |  \n     |  ----------------------------------------------------------------------\n     |  Data descriptors inherited from matplotlib.artist.Artist:\n     |  \n     |  __dict__\n     |      dictionary for instance variables (if defined)\n     |  \n     |  __weakref__\n     |      list of weak references to the object (if defined)\n     |  \n     |  axes\n     |      The `~.axes.Axes` instance the artist resides in, or *None*.\n     |  \n     |  mouseover\n     |      If this property is set to *True*, the artist will be queried for\n     |      custom context information when the mouse cursor moves over it.\n     |      \n     |      See also :meth:`get_cursor_data`, :class:`.ToolCursorPosition` and\n     |      :class:`.NavigationToolbar2`.\n     |  \n     |  stale\n     |      Whether the artist is 'stale' and needs to be re-drawn for the output\n     |      to match the internal state of the artist.\n     |  \n     |  ----------------------------------------------------------------------\n     |  Data and other attributes inherited from matplotlib.artist.Artist:\n     |  \n     |  zorder = 0\n     |  \n     |  ----------------------------------------------------------------------\n     |  Methods inherited from matplotlib.cm.ScalarMappable:\n     |  \n     |  add_checker(self, checker)\n     |      [*Deprecated*] \n     |      \n     |      Notes\n     |      -----\n     |      .. deprecated:: 3.3\n     |         \\\n     |  \n     |  autoscale(self)\n     |      Autoscale the scalar limits on the norm instance using the\n     |      current array\n     |  \n     |  autoscale_None(self)\n     |      Autoscale the scalar limits on the norm instance using the\n     |      current array, changing only limits that are None\n     |  \n     |  changed(self)\n     |      Call this whenever the mappable is changed to notify all the\n     |      callbackSM listeners to the 'changed' signal.\n     |  \n     |  check_update(self, checker)\n     |      [*Deprecated*] \n     |      \n     |      Notes\n     |      -----\n     |      .. deprecated:: 3.3\n     |         \\\n     |  \n     |  get_array(self)\n     |      Return the data array.\n     |  \n     |  get_clim(self)\n     |      Return the values (min, max) that are mapped to the colormap limits.\n     |  \n     |  get_cmap(self)\n     |      Return the `.Colormap` instance.\n     |  \n     |  set_array(self, A)\n     |      Set the image array from numpy array *A*.\n     |      \n     |      Parameters\n     |      ----------\n     |      A : ndarray\n     |  \n     |  set_clim(self, vmin=None, vmax=None)\n     |      Set the norm limits for image scaling.\n     |      \n     |      Parameters\n     |      ----------\n     |      vmin, vmax : float\n     |           The limits.\n     |      \n     |           The limits may also be passed as a tuple (*vmin*, *vmax*) as a\n     |           single positional argument.\n     |      \n     |           .. ACCEPTS: (vmin: float, vmax: float)\n     |  \n     |  set_cmap(self, cmap)\n     |      Set the colormap for luminance data.\n     |      \n     |      Parameters\n     |      ----------\n     |      cmap : `.Colormap` or str or None\n     |  \n     |  set_norm(self, norm)\n     |      Set the normalization instance.\n     |      \n     |      Parameters\n     |      ----------\n     |      norm : `.Normalize` or None\n     |      \n     |      Notes\n     |      -----\n     |      If there are any colorbars using the mappable for this norm, setting\n     |      the norm of the mappable will reset the norm, locator, and formatters\n     |      on the colorbar to default.\n     |  \n     |  to_rgba(self, x, alpha=None, bytes=False, norm=True)\n     |      Return a normalized rgba array corresponding to *x*.\n     |      \n     |      In the normal case, *x* is a 1-D or 2-D sequence of scalars, and\n     |      the corresponding ndarray of rgba values will be returned,\n     |      based on the norm and colormap set for this ScalarMappable.\n     |      \n     |      There is one special case, for handling images that are already\n     |      rgb or rgba, such as might have been read from an image file.\n     |      If *x* is an ndarray with 3 dimensions,\n     |      and the last dimension is either 3 or 4, then it will be\n     |      treated as an rgb or rgba array, and no mapping will be done.\n     |      The array can be uint8, or it can be floating point with\n     |      values in the 0-1 range; otherwise a ValueError will be raised.\n     |      If it is a masked array, the mask will be ignored.\n     |      If the last dimension is 3, the *alpha* kwarg (defaulting to 1)\n     |      will be used to fill in the transparency.  If the last dimension\n     |      is 4, the *alpha* kwarg is ignored; it does not\n     |      replace the pre-existing alpha.  A ValueError will be raised\n     |      if the third dimension is other than 3 or 4.\n     |      \n     |      In either case, if *bytes* is *False* (default), the rgba\n     |      array will be floats in the 0-1 range; if it is *True*,\n     |      the returned rgba array will be uint8 in the 0 to 255 range.\n     |      \n     |      If norm is False, no normalization of the input data is\n     |      performed, and it is assumed to be in the range (0-1).\n     |  \n     |  ----------------------------------------------------------------------\n     |  Readonly properties inherited from matplotlib.cm.ScalarMappable:\n     |  \n     |  update_dict\n    \n\n\n\n```python\nimport matplotlib.collections as mplcol\nimport matplotlib.patches as patches\nimport matplotlib.path\nimport matplotlib.pyplot as plt\nimport mpl_toolkits.mplot3d\nplt.ion()\n```\n\n\n```python\nhelp(mplcol.PatchCollection)\n```\n\n    Help on class PatchCollection in module matplotlib.collections:\n    \n    class PatchCollection(Collection)\n     |  PatchCollection(patches, match_original=False, **kwargs)\n     |  \n     |  A generic collection of patches.\n     |  \n     |  This makes it easier to assign a color map to a heterogeneous\n     |  collection of patches.\n     |  \n     |  This also may improve plotting speed, since PatchCollection will\n     |  draw faster than a large number of patches.\n     |  \n     |  Method resolution order:\n     |      PatchCollection\n     |      Collection\n     |      matplotlib.artist.Artist\n     |      matplotlib.cm.ScalarMappable\n     |      builtins.object\n     |  \n     |  Methods defined here:\n     |  \n     |  __init__(self, patches, match_original=False, **kwargs)\n     |      *patches*\n     |          a sequence of Patch objects.  This list may include\n     |          a heterogeneous assortment of different patch types.\n     |      \n     |      *match_original*\n     |          If True, use the colors and linewidths of the original\n     |          patches.  If False, new colors may be assigned by\n     |          providing the standard collection arguments, facecolor,\n     |          edgecolor, linewidths, norm or cmap.\n     |      \n     |      If any of *edgecolors*, *facecolors*, *linewidths*, *antialiaseds* are\n     |      None, they default to their `.rcParams` patch setting, in sequence\n     |      form.\n     |      \n     |      The use of `~matplotlib.cm.ScalarMappable` functionality is optional.\n     |      If the `~matplotlib.cm.ScalarMappable` matrix ``_A`` has been set (via\n     |      a call to `~.ScalarMappable.set_array`), at draw time a call to scalar\n     |      mappable will be made to set the face colors.\n     |  \n     |  set_paths(self, patches)\n     |  \n     |  ----------------------------------------------------------------------\n     |  Methods inherited from Collection:\n     |  \n     |  contains(self, mouseevent)\n     |      Test whether the mouse event occurred in the collection.\n     |      \n     |      Returns ``bool, dict(ind=itemlist)``, where every item in itemlist\n     |      contains the event.\n     |  \n     |  draw(self, renderer)\n     |      Draw the Artist (and its children) using the given renderer.\n     |      \n     |      This has no effect if the artist is not visible (`.Artist.get_visible`\n     |      returns False).\n     |      \n     |      Parameters\n     |      ----------\n     |      renderer : `.RendererBase` subclass.\n     |      \n     |      Notes\n     |      -----\n     |      This method is overridden in the Artist subclasses.\n     |  \n     |  get_capstyle(self)\n     |  \n     |  get_dashes(self)\n     |      Alias for `get_linestyle`.\n     |  \n     |  get_datalim(self, transData)\n     |  \n     |  get_ec(self)\n     |      Alias for `get_edgecolor`.\n     |  \n     |  get_edgecolor(self)\n     |  \n     |  get_edgecolors(self)\n     |      Alias for `get_edgecolor`.\n     |  \n     |  get_facecolor(self)\n     |  \n     |  get_facecolors(self)\n     |      Alias for `get_facecolor`.\n     |  \n     |  get_fc(self)\n     |      Alias for `get_facecolor`.\n     |  \n     |  get_fill(self)\n     |      Return whether fill is set.\n     |  \n     |  get_hatch(self)\n     |      Return the current hatching pattern.\n     |  \n     |  get_joinstyle(self)\n     |  \n     |  get_linestyle(self)\n     |  \n     |  get_linestyles(self)\n     |      Alias for `get_linestyle`.\n     |  \n     |  get_linewidth(self)\n     |  \n     |  get_linewidths(self)\n     |      Alias for `get_linewidth`.\n     |  \n     |  get_ls(self)\n     |      Alias for `get_linestyle`.\n     |  \n     |  get_lw(self)\n     |      Alias for `get_linewidth`.\n     |  \n     |  get_offset_position(self)\n     |      [*Deprecated*] Return how offsets are applied for the collection.  If\n     |      *offset_position* is 'screen', the offset is applied after the\n     |      master transform has been applied, that is, the offsets are in\n     |      screen coordinates.  If offset_position is 'data', the offset\n     |      is applied before the master transform, i.e., the offsets are\n     |      in data coordinates.\n     |      \n     |      Notes\n     |      -----\n     |      .. deprecated:: 3.3\n     |  \n     |  get_offset_transform(self)\n     |  \n     |  get_offsets(self)\n     |      Return the offsets for the collection.\n     |  \n     |  get_paths(self)\n     |  \n     |  get_pickradius(self)\n     |  \n     |  get_transforms(self)\n     |  \n     |  get_urls(self)\n     |      Return a list of URLs, one for each element of the collection.\n     |      \n     |      The list contains *None* for elements without a URL. See\n     |      :doc:`/gallery/misc/hyperlinks_sgskip` for an example.\n     |  \n     |  get_window_extent(self, renderer)\n     |      Get the axes bounding box in display space.\n     |      \n     |      The bounding box' width and height are nonnegative.\n     |      \n     |      Subclasses should override for inclusion in the bounding box\n     |      \"tight\" calculation. Default is to return an empty bounding\n     |      box at 0, 0.\n     |      \n     |      Be careful when using this function, the results will not update\n     |      if the artist window extent of the artist changes.  The extent\n     |      can change due to any changes in the transform stack, such as\n     |      changing the axes limits, the figure size, or the canvas used\n     |      (as is done when saving a figure).  This can lead to unexpected\n     |      behavior where interactive figures will look fine on the screen,\n     |      but will save incorrectly.\n     |  \n     |  set_aa(self, aa)\n     |      Alias for `set_antialiased`.\n     |  \n     |  set_alpha(self, alpha)\n     |      Set the alpha value used for blending - not supported on all backends.\n     |      \n     |      Parameters\n     |      ----------\n     |      alpha : float or None\n     |  \n     |  set_antialiased(self, aa)\n     |      Set the antialiasing state for rendering.\n     |      \n     |      Parameters\n     |      ----------\n     |      aa : bool or list of bools\n     |  \n     |  set_antialiaseds(self, aa)\n     |      Alias for `set_antialiased`.\n     |  \n     |  set_capstyle(self, cs)\n     |      Set the capstyle for the collection (for all its elements).\n     |      \n     |      Parameters\n     |      ----------\n     |      cs : {'butt', 'round', 'projecting'}\n     |          The capstyle.\n     |  \n     |  set_color(self, c)\n     |      Set both the edgecolor and the facecolor.\n     |      \n     |      Parameters\n     |      ----------\n     |      c : color or list of rgba tuples\n     |      \n     |      See Also\n     |      --------\n     |      Collection.set_facecolor, Collection.set_edgecolor\n     |          For setting the edge or face color individually.\n     |  \n     |  set_dashes(self, ls)\n     |      Alias for `set_linestyle`.\n     |  \n     |  set_ec(self, c)\n     |      Alias for `set_edgecolor`.\n     |  \n     |  set_edgecolor(self, c)\n     |      Set the edgecolor(s) of the collection.\n     |      \n     |      Parameters\n     |      ----------\n     |      c : color or list of colors or 'face'\n     |          The collection edgecolor(s).  If a sequence, the patches cycle\n     |          through it.  If 'face', match the facecolor.\n     |  \n     |  set_edgecolors(self, c)\n     |      Alias for `set_edgecolor`.\n     |  \n     |  set_facecolor(self, c)\n     |      Set the facecolor(s) of the collection. *c* can be a color (all patches\n     |      have same color), or a sequence of colors; if it is a sequence the\n     |      patches will cycle through the sequence.\n     |      \n     |      If *c* is 'none', the patch will not be filled.\n     |      \n     |      Parameters\n     |      ----------\n     |      c : color or list of colors\n     |  \n     |  set_facecolors(self, c)\n     |      Alias for `set_facecolor`.\n     |  \n     |  set_fc(self, c)\n     |      Alias for `set_facecolor`.\n     |  \n     |  set_hatch(self, hatch)\n     |      Set the hatching pattern\n     |      \n     |      *hatch* can be one of::\n     |      \n     |        /   - diagonal hatching\n     |        \\   - back diagonal\n     |        |   - vertical\n     |        -   - horizontal\n     |        +   - crossed\n     |        x   - crossed diagonal\n     |        o   - small circle\n     |        O   - large circle\n     |        .   - dots\n     |        *   - stars\n     |      \n     |      Letters can be combined, in which case all the specified\n     |      hatchings are done.  If same letter repeats, it increases the\n     |      density of hatching of that pattern.\n     |      \n     |      Hatching is supported in the PostScript, PDF, SVG and Agg\n     |      backends only.\n     |      \n     |      Unlike other properties such as linewidth and colors, hatching\n     |      can only be specified for the collection as a whole, not separately\n     |      for each member.\n     |      \n     |      Parameters\n     |      ----------\n     |      hatch : {'/', '\\\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}\n     |  \n     |  set_joinstyle(self, js)\n     |      Set the joinstyle for the collection (for all its elements).\n     |      \n     |      Parameters\n     |      ----------\n     |      js : {'miter', 'round', 'bevel'}\n     |          The joinstyle.\n     |  \n     |  set_linestyle(self, ls)\n     |      Set the linestyle(s) for the collection.\n     |      \n     |      ===========================   =================\n     |      linestyle                     description\n     |      ===========================   =================\n     |      ``'-'`` or ``'solid'``        solid line\n     |      ``'--'`` or  ``'dashed'``     dashed line\n     |      ``'-.'`` or  ``'dashdot'``    dash-dotted line\n     |      ``':'`` or ``'dotted'``       dotted line\n     |      ===========================   =================\n     |      \n     |      Alternatively a dash tuple of the following form can be provided::\n     |      \n     |          (offset, onoffseq),\n     |      \n     |      where ``onoffseq`` is an even length tuple of on and off ink in points.\n     |      \n     |      Parameters\n     |      ----------\n     |      ls : str or tuple or list thereof\n     |          Valid values for individual linestyles include {'-', '--', '-.',\n     |          ':', '', (offset, on-off-seq)}. See `.Line2D.set_linestyle` for a\n     |          complete description.\n     |  \n     |  set_linestyles(self, ls)\n     |      Alias for `set_linestyle`.\n     |  \n     |  set_linewidth(self, lw)\n     |      Set the linewidth(s) for the collection.  *lw* can be a scalar\n     |      or a sequence; if it is a sequence the patches will cycle\n     |      through the sequence\n     |      \n     |      Parameters\n     |      ----------\n     |      lw : float or list of floats\n     |  \n     |  set_linewidths(self, lw)\n     |      Alias for `set_linewidth`.\n     |  \n     |  set_ls(self, ls)\n     |      Alias for `set_linestyle`.\n     |  \n     |  set_lw(self, lw)\n     |      Alias for `set_linewidth`.\n     |  \n     |  set_offset_position(self, offset_position)\n     |      [*Deprecated*] Set how offsets are applied.  If *offset_position* is 'screen'\n     |      (default) the offset is applied after the master transform has\n     |      been applied, that is, the offsets are in screen coordinates.\n     |      If offset_position is 'data', the offset is applied before the\n     |      master transform, i.e., the offsets are in data coordinates.\n     |      \n     |      Parameters\n     |      ----------\n     |      offset_position : {'screen', 'data'}\n     |      \n     |      Notes\n     |      -----\n     |      .. deprecated:: 3.3\n     |  \n     |  set_offsets(self, offsets)\n     |      Set the offsets for the collection.\n     |      \n     |      Parameters\n     |      ----------\n     |      offsets : array-like (N, 2) or (2,)\n     |  \n     |  set_pickradius(self, pr)\n     |      Set the pick radius used for containment tests.\n     |      \n     |      Parameters\n     |      ----------\n     |      d : float\n     |          Pick radius, in points.\n     |  \n     |  set_urls(self, urls)\n     |      Parameters\n     |      ----------\n     |      urls : list of str or None\n     |      \n     |      Notes\n     |      -----\n     |      URLs are currently only implemented by the SVG backend. They are\n     |      ignored by all other backends.\n     |  \n     |  update_from(self, other)\n     |      Copy properties from other to self.\n     |  \n     |  update_scalarmappable(self)\n     |      Update colors from the scalar mappable array, if it is not None.\n     |  \n     |  ----------------------------------------------------------------------\n     |  Methods inherited from matplotlib.artist.Artist:\n     |  \n     |  __getstate__(self)\n     |  \n     |  add_callback(self, func)\n     |      Add a callback function that will be called whenever one of the\n     |      `.Artist`'s properties changes.\n     |      \n     |      Parameters\n     |      ----------\n     |      func : callable\n     |          The callback function. It must have the signature::\n     |      \n     |              def func(artist: Artist) -> Any\n     |      \n     |          where *artist* is the calling `.Artist`. Return values may exist\n     |          but are ignored.\n     |      \n     |      Returns\n     |      -------\n     |      int\n     |          The observer id associated with the callback. This id can be\n     |          used for removing the callback with `.remove_callback` later.\n     |      \n     |      See Also\n     |      --------\n     |      remove_callback\n     |  \n     |  convert_xunits(self, x)\n     |      Convert *x* using the unit type of the xaxis.\n     |      \n     |      If the artist is not in contained in an Axes or if the xaxis does not\n     |      have units, *x* itself is returned.\n     |  \n     |  convert_yunits(self, y)\n     |      Convert *y* using the unit type of the yaxis.\n     |      \n     |      If the artist is not in contained in an Axes or if the yaxis does not\n     |      have units, *y* itself is returned.\n     |  \n     |  findobj(self, match=None, include_self=True)\n     |      Find artist objects.\n     |      \n     |      Recursively find all `.Artist` instances contained in the artist.\n     |      \n     |      Parameters\n     |      ----------\n     |      match\n     |          A filter criterion for the matches. This can be\n     |      \n     |          - *None*: Return all objects contained in artist.\n     |          - A function with signature ``def match(artist: Artist) -> bool``.\n     |            The result will only contain artists for which the function\n     |            returns *True*.\n     |          - A class instance: e.g., `.Line2D`. The result will only contain\n     |            artists of this class or its subclasses (``isinstance`` check).\n     |      \n     |      include_self : bool\n     |          Include *self* in the list to be checked for a match.\n     |      \n     |      Returns\n     |      -------\n     |      list of `.Artist`\n     |  \n     |  format_cursor_data(self, data)\n     |      Return a string representation of *data*.\n     |      \n     |      .. note::\n     |          This method is intended to be overridden by artist subclasses.\n     |          As an end-user of Matplotlib you will most likely not call this\n     |          method yourself.\n     |      \n     |      The default implementation converts ints and floats and arrays of ints\n     |      and floats into a comma-separated string enclosed in square brackets.\n     |      \n     |      See Also\n     |      --------\n     |      get_cursor_data\n     |  \n     |  get_agg_filter(self)\n     |      Return filter function to be used for agg filter.\n     |  \n     |  get_alpha(self)\n     |      Return the alpha value used for blending - not supported on all\n     |      backends.\n     |  \n     |  get_animated(self)\n     |      Return whether the artist is animated.\n     |  \n     |  get_children(self)\n     |      Return a list of the child `.Artist`\\s of this `.Artist`.\n     |  \n     |  get_clip_box(self)\n     |      Return the clipbox.\n     |  \n     |  get_clip_on(self)\n     |      Return whether the artist uses clipping.\n     |  \n     |  get_clip_path(self)\n     |      Return the clip path.\n     |  \n     |  get_contains(self)\n     |      [*Deprecated*] Return the custom contains function of the artist if set, or *None*.\n     |      \n     |      See Also\n     |      --------\n     |      set_contains\n     |      \n     |      Notes\n     |      -----\n     |      .. deprecated:: 3.3\n     |  \n     |  get_cursor_data(self, event)\n     |      Return the cursor data for a given event.\n     |      \n     |      .. note::\n     |          This method is intended to be overridden by artist subclasses.\n     |          As an end-user of Matplotlib you will most likely not call this\n     |          method yourself.\n     |      \n     |      Cursor data can be used by Artists to provide additional context\n     |      information for a given event. The default implementation just returns\n     |      *None*.\n     |      \n     |      Subclasses can override the method and return arbitrary data. However,\n     |      when doing so, they must ensure that `.format_cursor_data` can convert\n     |      the data to a string representation.\n     |      \n     |      The only current use case is displaying the z-value of an `.AxesImage`\n     |      in the status bar of a plot window, while moving the mouse.\n     |      \n     |      Parameters\n     |      ----------\n     |      event : `matplotlib.backend_bases.MouseEvent`\n     |      \n     |      See Also\n     |      --------\n     |      format_cursor_data\n     |  \n     |  get_figure(self)\n     |      Return the `.Figure` instance the artist belongs to.\n     |  \n     |  get_gid(self)\n     |      Return the group id.\n     |  \n     |  get_in_layout(self)\n     |      Return boolean flag, ``True`` if artist is included in layout\n     |      calculations.\n     |      \n     |      E.g. :doc:`/tutorials/intermediate/constrainedlayout_guide`,\n     |      `.Figure.tight_layout()`, and\n     |      ``fig.savefig(fname, bbox_inches='tight')``.\n     |  \n     |  get_label(self)\n     |      Return the label used for this artist in the legend.\n     |  \n     |  get_path_effects(self)\n     |  \n     |  get_picker(self)\n     |      Return the picking behavior of the artist.\n     |      \n     |      The possible values are described in `.set_picker`.\n     |      \n     |      See Also\n     |      --------\n     |      set_picker, pickable, pick\n     |  \n     |  get_rasterized(self)\n     |      Return whether the artist is to be rasterized.\n     |  \n     |  get_sketch_params(self)\n     |      Return the sketch parameters for the artist.\n     |      \n     |      Returns\n     |      -------\n     |      tuple or None\n     |      \n     |          A 3-tuple with the following elements:\n     |      \n     |          - *scale*: The amplitude of the wiggle perpendicular to the\n     |            source line.\n     |          - *length*: The length of the wiggle along the line.\n     |          - *randomness*: The scale factor by which the length is\n     |            shrunken or expanded.\n     |      \n     |          Returns *None* if no sketch parameters were set.\n     |  \n     |  get_snap(self)\n     |      Return the snap setting.\n     |      \n     |      See `.set_snap` for details.\n     |  \n     |  get_tightbbox(self, renderer)\n     |      Like `.Artist.get_window_extent`, but includes any clipping.\n     |      \n     |      Parameters\n     |      ----------\n     |      renderer : `.RendererBase` subclass\n     |          renderer that will be used to draw the figures (i.e.\n     |          ``fig.canvas.get_renderer()``)\n     |      \n     |      Returns\n     |      -------\n     |      `.Bbox`\n     |          The enclosing bounding box (in figure pixel coordinates).\n     |  \n     |  get_transform(self)\n     |      Return the `.Transform` instance used by this artist.\n     |  \n     |  get_transformed_clip_path_and_affine(self)\n     |      Return the clip path with the non-affine part of its\n     |      transformation applied, and the remaining affine part of its\n     |      transformation.\n     |  \n     |  get_url(self)\n     |      Return the url.\n     |  \n     |  get_visible(self)\n     |      Return the visibility.\n     |  \n     |  get_zorder(self)\n     |      Return the artist's zorder.\n     |  \n     |  have_units(self)\n     |      Return *True* if units are set on any axis.\n     |  \n     |  is_transform_set(self)\n     |      Return whether the Artist has an explicitly set transform.\n     |      \n     |      This is *True* after `.set_transform` has been called.\n     |  \n     |  pchanged(self)\n     |      Call all of the registered callbacks.\n     |      \n     |      This function is triggered internally when a property is changed.\n     |      \n     |      See Also\n     |      --------\n     |      add_callback\n     |      remove_callback\n     |  \n     |  pick(self, mouseevent)\n     |      Process a pick event.\n     |      \n     |      Each child artist will fire a pick event if *mouseevent* is over\n     |      the artist and the artist has picker set.\n     |      \n     |      See Also\n     |      --------\n     |      set_picker, get_picker, pickable\n     |  \n     |  pickable(self)\n     |      Return whether the artist is pickable.\n     |      \n     |      See Also\n     |      --------\n     |      set_picker, get_picker, pick\n     |  \n     |  properties(self)\n     |      Return a dictionary of all the properties of the artist.\n     |  \n     |  remove(self)\n     |      Remove the artist from the figure if possible.\n     |      \n     |      The effect will not be visible until the figure is redrawn, e.g.,\n     |      with `.FigureCanvasBase.draw_idle`.  Call `~.axes.Axes.relim` to\n     |      update the axes limits if desired.\n     |      \n     |      Note: `~.axes.Axes.relim` will not see collections even if the\n     |      collection was added to the axes with *autolim* = True.\n     |      \n     |      Note: there is no support for removing the artist's legend entry.\n     |  \n     |  remove_callback(self, oid)\n     |      Remove a callback based on its observer id.\n     |      \n     |      See Also\n     |      --------\n     |      add_callback\n     |  \n     |  set(self, **kwargs)\n     |      A property batch setter.  Pass *kwargs* to set properties.\n     |  \n     |  set_agg_filter(self, filter_func)\n     |      Set the agg filter.\n     |      \n     |      Parameters\n     |      ----------\n     |      filter_func : callable\n     |          A filter function, which takes a (m, n, 3) float array and a dpi\n     |          value, and returns a (m, n, 3) array.\n     |      \n     |          .. ACCEPTS: a filter function, which takes a (m, n, 3) float array\n     |              and a dpi value, and returns a (m, n, 3) array\n     |  \n     |  set_animated(self, b)\n     |      Set the artist's animation state.\n     |      \n     |      Parameters\n     |      ----------\n     |      b : bool\n     |  \n     |  set_clip_box(self, clipbox)\n     |      Set the artist's clip `.Bbox`.\n     |      \n     |      Parameters\n     |      ----------\n     |      clipbox : `.Bbox`\n     |  \n     |  set_clip_on(self, b)\n     |      Set whether the artist uses clipping.\n     |      \n     |      When False artists will be visible outside of the axes which\n     |      can lead to unexpected results.\n     |      \n     |      Parameters\n     |      ----------\n     |      b : bool\n     |  \n     |  set_clip_path(self, path, transform=None)\n     |      Set the artist's clip path.\n     |      \n     |      Parameters\n     |      ----------\n     |      path : `.Patch` or `.Path` or `.TransformedPath` or None\n     |          The clip path. If given a `.Path`, *transform* must be provided as\n     |          well. If *None*, a previously set clip path is removed.\n     |      transform : `~matplotlib.transforms.Transform`, optional\n     |          Only used if *path* is a `.Path`, in which case the given `.Path`\n     |          is converted to a `.TransformedPath` using *transform*.\n     |      \n     |      Notes\n     |      -----\n     |      For efficiency, if *path* is a `.Rectangle` this method will set the\n     |      clipping box to the corresponding rectangle and set the clipping path\n     |      to ``None``.\n     |      \n     |      For technical reasons (support of `~.Artist.set`), a tuple\n     |      (*path*, *transform*) is also accepted as a single positional\n     |      parameter.\n     |      \n     |      .. ACCEPTS: Patch or (Path, Transform) or None\n     |  \n     |  set_contains(self, picker)\n     |      [*Deprecated*] Define a custom contains test for the artist.\n     |      \n     |      The provided callable replaces the default `.contains` method\n     |      of the artist.\n     |      \n     |      Parameters\n     |      ----------\n     |      picker : callable\n     |          A custom picker function to evaluate if an event is within the\n     |          artist. The function must have the signature::\n     |      \n     |              def contains(artist: Artist, event: MouseEvent) -> bool, dict\n     |      \n     |          that returns:\n     |      \n     |          - a bool indicating if the event is within the artist\n     |          - a dict of additional information. The dict should at least\n     |            return the same information as the default ``contains()``\n     |            implementation of the respective artist, but may provide\n     |            additional information.\n     |      \n     |      Notes\n     |      -----\n     |      .. deprecated:: 3.3\n     |  \n     |  set_figure(self, fig)\n     |      Set the `.Figure` instance the artist belongs to.\n     |      \n     |      Parameters\n     |      ----------\n     |      fig : `.Figure`\n     |  \n     |  set_gid(self, gid)\n     |      Set the (group) id for the artist.\n     |      \n     |      Parameters\n     |      ----------\n     |      gid : str\n     |  \n     |  set_in_layout(self, in_layout)\n     |      Set if artist is to be included in layout calculations,\n     |      E.g. :doc:`/tutorials/intermediate/constrainedlayout_guide`,\n     |      `.Figure.tight_layout()`, and\n     |      ``fig.savefig(fname, bbox_inches='tight')``.\n     |      \n     |      Parameters\n     |      ----------\n     |      in_layout : bool\n     |  \n     |  set_label(self, s)\n     |      Set a label that will be displayed in the legend.\n     |      \n     |      Parameters\n     |      ----------\n     |      s : object\n     |          *s* will be converted to a string by calling `str`.\n     |  \n     |  set_path_effects(self, path_effects)\n     |      Set the path effects.\n     |      \n     |      Parameters\n     |      ----------\n     |      path_effects : `.AbstractPathEffect`\n     |  \n     |  set_picker(self, picker)\n     |      Define the picking behavior of the artist.\n     |      \n     |      Parameters\n     |      ----------\n     |      picker : None or bool or callable\n     |          This can be one of the following:\n     |      \n     |          - *None*: Picking is disabled for this artist (default).\n     |      \n     |          - A boolean: If *True* then picking will be enabled and the\n     |            artist will fire a pick event if the mouse event is over\n     |            the artist.\n     |      \n     |          - A function: If picker is callable, it is a user supplied\n     |            function which determines whether the artist is hit by the\n     |            mouse event::\n     |      \n     |              hit, props = picker(artist, mouseevent)\n     |      \n     |            to determine the hit test.  if the mouse event is over the\n     |            artist, return *hit=True* and props is a dictionary of\n     |            properties you want added to the PickEvent attributes.\n     |      \n     |          - *deprecated*: For `.Line2D` only, *picker* can also be a float\n     |            that sets the tolerance for checking whether an event occurred\n     |            \"on\" the line; this is deprecated.  Use `.Line2D.set_pickradius`\n     |            instead.\n     |  \n     |  set_rasterized(self, rasterized)\n     |      Force rasterized (bitmap) drawing in vector backend output.\n     |      \n     |      Defaults to None, which implies the backend's default behavior.\n     |      \n     |      Parameters\n     |      ----------\n     |      rasterized : bool or None\n     |  \n     |  set_sketch_params(self, scale=None, length=None, randomness=None)\n     |      Sets the sketch parameters.\n     |      \n     |      Parameters\n     |      ----------\n     |      scale : float, optional\n     |          The amplitude of the wiggle perpendicular to the source\n     |          line, in pixels.  If scale is `None`, or not provided, no\n     |          sketch filter will be provided.\n     |      length : float, optional\n     |           The length of the wiggle along the line, in pixels\n     |           (default 128.0)\n     |      randomness : float, optional\n     |          The scale factor by which the length is shrunken or\n     |          expanded (default 16.0)\n     |      \n     |          .. ACCEPTS: (scale: float, length: float, randomness: float)\n     |  \n     |  set_snap(self, snap)\n     |      Set the snapping behavior.\n     |      \n     |      Snapping aligns positions with the pixel grid, which results in\n     |      clearer images. For example, if a black line of 1px width was\n     |      defined at a position in between two pixels, the resulting image\n     |      would contain the interpolated value of that line in the pixel grid,\n     |      which would be a grey value on both adjacent pixel positions. In\n     |      contrast, snapping will move the line to the nearest integer pixel\n     |      value, so that the resulting image will really contain a 1px wide\n     |      black line.\n     |      \n     |      Snapping is currently only supported by the Agg and MacOSX backends.\n     |      \n     |      Parameters\n     |      ----------\n     |      snap : bool or None\n     |          Possible values:\n     |      \n     |          - *True*: Snap vertices to the nearest pixel center.\n     |          - *False*: Do not modify vertex positions.\n     |          - *None*: (auto) If the path contains only rectilinear line\n     |            segments, round to the nearest pixel center.\n     |  \n     |  set_transform(self, t)\n     |      Set the artist transform.\n     |      \n     |      Parameters\n     |      ----------\n     |      t : `.Transform`\n     |  \n     |  set_url(self, url)\n     |      Set the url for the artist.\n     |      \n     |      Parameters\n     |      ----------\n     |      url : str\n     |  \n     |  set_visible(self, b)\n     |      Set the artist's visibility.\n     |      \n     |      Parameters\n     |      ----------\n     |      b : bool\n     |  \n     |  set_zorder(self, level)\n     |      Set the zorder for the artist.  Artists with lower zorder\n     |      values are drawn first.\n     |      \n     |      Parameters\n     |      ----------\n     |      level : float\n     |  \n     |  update(self, props)\n     |      Update this artist's properties from the dict *props*.\n     |      \n     |      Parameters\n     |      ----------\n     |      props : dict\n     |  \n     |  ----------------------------------------------------------------------\n     |  Readonly properties inherited from matplotlib.artist.Artist:\n     |  \n     |  sticky_edges\n     |      ``x`` and ``y`` sticky edge lists for autoscaling.\n     |      \n     |      When performing autoscaling, if a data limit coincides with a value in\n     |      the corresponding sticky_edges list, then no margin will be added--the\n     |      view limit \"sticks\" to the edge. A typical use case is histograms,\n     |      where one usually expects no margin on the bottom edge (0) of the\n     |      histogram.\n     |      \n     |      This attribute cannot be assigned to; however, the ``x`` and ``y``\n     |      lists can be modified in place as needed.\n     |      \n     |      Examples\n     |      --------\n     |      >>> artist.sticky_edges.x[:] = (xmin, xmax)\n     |      >>> artist.sticky_edges.y[:] = (ymin, ymax)\n     |  \n     |  ----------------------------------------------------------------------\n     |  Data descriptors inherited from matplotlib.artist.Artist:\n     |  \n     |  __dict__\n     |      dictionary for instance variables (if defined)\n     |  \n     |  __weakref__\n     |      list of weak references to the object (if defined)\n     |  \n     |  axes\n     |      The `~.axes.Axes` instance the artist resides in, or *None*.\n     |  \n     |  mouseover\n     |      If this property is set to *True*, the artist will be queried for\n     |      custom context information when the mouse cursor moves over it.\n     |      \n     |      See also :meth:`get_cursor_data`, :class:`.ToolCursorPosition` and\n     |      :class:`.NavigationToolbar2`.\n     |  \n     |  stale\n     |      Whether the artist is 'stale' and needs to be re-drawn for the output\n     |      to match the internal state of the artist.\n     |  \n     |  ----------------------------------------------------------------------\n     |  Data and other attributes inherited from matplotlib.artist.Artist:\n     |  \n     |  zorder = 0\n     |  \n     |  ----------------------------------------------------------------------\n     |  Methods inherited from matplotlib.cm.ScalarMappable:\n     |  \n     |  add_checker(self, checker)\n     |      [*Deprecated*] \n     |      \n     |      Notes\n     |      -----\n     |      .. deprecated:: 3.3\n     |         \\\n     |  \n     |  autoscale(self)\n     |      Autoscale the scalar limits on the norm instance using the\n     |      current array\n     |  \n     |  autoscale_None(self)\n     |      Autoscale the scalar limits on the norm instance using the\n     |      current array, changing only limits that are None\n     |  \n     |  changed(self)\n     |      Call this whenever the mappable is changed to notify all the\n     |      callbackSM listeners to the 'changed' signal.\n     |  \n     |  check_update(self, checker)\n     |      [*Deprecated*] \n     |      \n     |      Notes\n     |      -----\n     |      .. deprecated:: 3.3\n     |         \\\n     |  \n     |  get_array(self)\n     |      Return the data array.\n     |  \n     |  get_clim(self)\n     |      Return the values (min, max) that are mapped to the colormap limits.\n     |  \n     |  get_cmap(self)\n     |      Return the `.Colormap` instance.\n     |  \n     |  set_array(self, A)\n     |      Set the image array from numpy array *A*.\n     |      \n     |      Parameters\n     |      ----------\n     |      A : ndarray\n     |  \n     |  set_clim(self, vmin=None, vmax=None)\n     |      Set the norm limits for image scaling.\n     |      \n     |      Parameters\n     |      ----------\n     |      vmin, vmax : float\n     |           The limits.\n     |      \n     |           The limits may also be passed as a tuple (*vmin*, *vmax*) as a\n     |           single positional argument.\n     |      \n     |           .. ACCEPTS: (vmin: float, vmax: float)\n     |  \n     |  set_cmap(self, cmap)\n     |      Set the colormap for luminance data.\n     |      \n     |      Parameters\n     |      ----------\n     |      cmap : `.Colormap` or str or None\n     |  \n     |  set_norm(self, norm)\n     |      Set the normalization instance.\n     |      \n     |      Parameters\n     |      ----------\n     |      norm : `.Normalize` or None\n     |      \n     |      Notes\n     |      -----\n     |      If there are any colorbars using the mappable for this norm, setting\n     |      the norm of the mappable will reset the norm, locator, and formatters\n     |      on the colorbar to default.\n     |  \n     |  to_rgba(self, x, alpha=None, bytes=False, norm=True)\n     |      Return a normalized rgba array corresponding to *x*.\n     |      \n     |      In the normal case, *x* is a 1-D or 2-D sequence of scalars, and\n     |      the corresponding ndarray of rgba values will be returned,\n     |      based on the norm and colormap set for this ScalarMappable.\n     |      \n     |      There is one special case, for handling images that are already\n     |      rgb or rgba, such as might have been read from an image file.\n     |      If *x* is an ndarray with 3 dimensions,\n     |      and the last dimension is either 3 or 4, then it will be\n     |      treated as an rgb or rgba array, and no mapping will be done.\n     |      The array can be uint8, or it can be floating point with\n     |      values in the 0-1 range; otherwise a ValueError will be raised.\n     |      If it is a masked array, the mask will be ignored.\n     |      If the last dimension is 3, the *alpha* kwarg (defaulting to 1)\n     |      will be used to fill in the transparency.  If the last dimension\n     |      is 4, the *alpha* kwarg is ignored; it does not\n     |      replace the pre-existing alpha.  A ValueError will be raised\n     |      if the third dimension is other than 3 or 4.\n     |      \n     |      In either case, if *bytes* is *False* (default), the rgba\n     |      array will be floats in the 0-1 range; if it is *True*,\n     |      the returned rgba array will be uint8 in the 0 to 255 range.\n     |      \n     |      If norm is False, no normalization of the input data is\n     |      performed, and it is assumed to be in the range (0-1).\n     |  \n     |  ----------------------------------------------------------------------\n     |  Readonly properties inherited from matplotlib.cm.ScalarMappable:\n     |  \n     |  update_dict\n    \n\n\n\n```python\n[s for s in dir(patches) if not s.startswith('_')]\n```\n\n\n\n\n    ['Arc',\n     'Arrow',\n     'ArrowStyle',\n     'BoxStyle',\n     'Circle',\n     'CirclePolygon',\n     'ConnectionPatch',\n     'ConnectionStyle',\n     'Ellipse',\n     'FancyArrow',\n     'FancyArrowPatch',\n     'FancyBboxPatch',\n     'NonIntersectingPathException',\n     'Number',\n     'Patch',\n     'Path',\n     'PathPatch',\n     'Polygon',\n     'Rectangle',\n     'RegularPolygon',\n     'Shadow',\n     'Wedge',\n     'artist',\n     'bbox_artist',\n     'cbook',\n     'colors',\n     'contextlib',\n     'docstring',\n     'draw_bbox',\n     'functools',\n     'get_cos_sin',\n     'get_intersection',\n     'get_parallels',\n     'inside_circle',\n     'inspect',\n     'k',\n     'make_wedged_bezier2',\n     'math',\n     'mlines',\n     'mpl',\n     'np',\n     'patchdoc',\n     'split_bezier_intersecting_with_closedpath',\n     'split_path_inout',\n     'textwrap',\n     'transforms']\n\n\n\n\n```python\nhelp(patches.Circle)\n```\n\n    Help on class Circle in module matplotlib.patches:\n    \n    class Circle(Ellipse)\n     |  Circle(xy, radius=5, **kwargs)\n     |  \n     |  A circle patch.\n     |  \n     |  Method resolution order:\n     |      Circle\n     |      Ellipse\n     |      Patch\n     |      matplotlib.artist.Artist\n     |      builtins.object\n     |  \n     |  Methods defined here:\n     |  \n     |  __init__(self, xy, radius=5, **kwargs)\n     |      Create a true circle at center *xy* = (*x*, *y*) with given *radius*.\n     |      \n     |      Unlike `CirclePolygon` which is a polygonal approximation, this uses\n     |      Bezier splines and is much closer to a scale-free circle.\n     |      \n     |      Valid keyword arguments are:\n     |      \n     |      Properties:\n     |          agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array\n     |          alpha: float or None\n     |          animated: bool\n     |          antialiased or aa: unknown\n     |          capstyle: {'butt', 'round', 'projecting'}\n     |          clip_box: `.Bbox`\n     |          clip_on: bool\n     |          clip_path: Patch or (Path, Transform) or None\n     |          color: color\n     |          contains: unknown\n     |          edgecolor or ec: color or None or 'auto'\n     |          facecolor or fc: color or None\n     |          figure: `.Figure`\n     |          fill: bool\n     |          gid: str\n     |          hatch: {'/', '\\\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}\n     |          in_layout: bool\n     |          joinstyle: {'miter', 'round', 'bevel'}\n     |          label: object\n     |          linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}\n     |          linewidth or lw: float or None\n     |          path_effects: `.AbstractPathEffect`\n     |          picker: None or bool or callable\n     |          rasterized: bool or None\n     |          sketch_params: (scale: float, length: float, randomness: float)\n     |          snap: bool or None\n     |          transform: `.Transform`\n     |          url: str\n     |          visible: bool\n     |          zorder: float\n     |  \n     |  __str__(self)\n     |      Return str(self).\n     |  \n     |  get_radius(self)\n     |      Return the radius of the circle.\n     |  \n     |  set_radius(self, radius)\n     |      Set the radius of the circle.\n     |      \n     |      Parameters\n     |      ----------\n     |      radius : float\n     |  \n     |  ----------------------------------------------------------------------\n     |  Data descriptors defined here:\n     |  \n     |  radius\n     |      Return the radius of the circle.\n     |  \n     |  ----------------------------------------------------------------------\n     |  Methods inherited from Ellipse:\n     |  \n     |  get_angle(self)\n     |      Return the angle of the ellipse.\n     |  \n     |  get_center(self)\n     |      Return the center of the ellipse.\n     |  \n     |  get_height(self)\n     |      Return the height of the ellipse.\n     |  \n     |  get_patch_transform(self)\n     |      Return the `~.transforms.Transform` instance mapping patch coordinates\n     |      to data coordinates.\n     |      \n     |      For example, one may define a patch of a circle which represents a\n     |      radius of 5 by providing coordinates for a unit circle, and a\n     |      transform which scales the coordinates (the patch coordinate) by 5.\n     |  \n     |  get_path(self)\n     |      Return the path of the ellipse.\n     |  \n     |  get_width(self)\n     |      Return the width of the ellipse.\n     |  \n     |  set_angle(self, angle)\n     |      Set the angle of the ellipse.\n     |      \n     |      Parameters\n     |      ----------\n     |      angle : float\n     |  \n     |  set_center(self, xy)\n     |      Set the center of the ellipse.\n     |      \n     |      Parameters\n     |      ----------\n     |      xy : (float, float)\n     |  \n     |  set_height(self, height)\n     |      Set the height of the ellipse.\n     |      \n     |      Parameters\n     |      ----------\n     |      height : float\n     |  \n     |  set_width(self, width)\n     |      Set the width of the ellipse.\n     |      \n     |      Parameters\n     |      ----------\n     |      width : float\n     |  \n     |  ----------------------------------------------------------------------\n     |  Data descriptors inherited from Ellipse:\n     |  \n     |  angle\n     |      Return the angle of the ellipse.\n     |  \n     |  center\n     |      Return the center of the ellipse.\n     |  \n     |  height\n     |      Return the height of the ellipse.\n     |  \n     |  width\n     |      Return the width of the ellipse.\n     |  \n     |  ----------------------------------------------------------------------\n     |  Methods inherited from Patch:\n     |  \n     |  contains(self, mouseevent, radius=None)\n     |      Test whether the mouse event occurred in the patch.\n     |      \n     |      Returns\n     |      -------\n     |      (bool, empty dict)\n     |  \n     |  contains_point(self, point, radius=None)\n     |      Return whether the given point is inside the patch.\n     |      \n     |      Parameters\n     |      ----------\n     |      point : (float, float)\n     |          The point (x, y) to check, in target coordinates of\n     |          ``self.get_transform()``. These are display coordinates for patches\n     |          that are added to a figure or axes.\n     |      radius : float, optional\n     |          Add an additional margin on the patch in target coordinates of\n     |          ``self.get_transform()``. See `.Path.contains_point` for further\n     |          details.\n     |      \n     |      Returns\n     |      -------\n     |      bool\n     |      \n     |      Notes\n     |      -----\n     |      The proper use of this method depends on the transform of the patch.\n     |      Isolated patches do not have a transform. In this case, the patch\n     |      creation coordinates and the point coordinates match. The following\n     |      example checks that the center of a circle is within the circle\n     |      \n     |      >>> center = 0, 0\n     |      >>> c = Circle(center, radius=1)\n     |      >>> c.contains_point(center)\n     |      True\n     |      \n     |      The convention of checking against the transformed patch stems from\n     |      the fact that this method is predominantly used to check if display\n     |      coordinates (e.g. from mouse events) are within the patch. If you want\n     |      to do the above check with data coordinates, you have to properly\n     |      transform them first:\n     |      \n     |      >>> center = 0, 0\n     |      >>> c = Circle(center, radius=1)\n     |      >>> plt.gca().add_patch(c)\n     |      >>> transformed_center = c.get_transform().transform(center)\n     |      >>> c.contains_point(transformed_center)\n     |      True\n     |  \n     |  contains_points(self, points, radius=None)\n     |      Return whether the given points are inside the patch.\n     |      \n     |      Parameters\n     |      ----------\n     |      points : (N, 2) array\n     |          The points to check, in target coordinates of\n     |          ``self.get_transform()``. These are display coordinates for patches\n     |          that are added to a figure or axes. Columns contain x and y values.\n     |      radius : float, optional\n     |          Add an additional margin on the patch in target coordinates of\n     |          ``self.get_transform()``. See `.Path.contains_point` for further\n     |          details.\n     |      \n     |      Returns\n     |      -------\n     |      length-N bool array\n     |      \n     |      Notes\n     |      -----\n     |      The proper use of this method depends on the transform of the patch.\n     |      See the notes on `.Patch.contains_point`.\n     |  \n     |  draw(self, renderer)\n     |      Draw the Artist (and its children) using the given renderer.\n     |      \n     |      This has no effect if the artist is not visible (`.Artist.get_visible`\n     |      returns False).\n     |      \n     |      Parameters\n     |      ----------\n     |      renderer : `.RendererBase` subclass.\n     |      \n     |      Notes\n     |      -----\n     |      This method is overridden in the Artist subclasses.\n     |  \n     |  get_aa(self)\n     |      Alias for `get_antialiased`.\n     |  \n     |  get_antialiased(self)\n     |      Return whether antialiasing is used for drawing.\n     |  \n     |  get_capstyle(self)\n     |      Return the capstyle.\n     |  \n     |  get_data_transform(self)\n     |      Return the `~.transforms.Transform` mapping data coordinates to\n     |      physical coordinates.\n     |  \n     |  get_ec(self)\n     |      Alias for `get_edgecolor`.\n     |  \n     |  get_edgecolor(self)\n     |      Return the edge color.\n     |  \n     |  get_extents(self)\n     |      Return the `Patch`'s axis-aligned extents as a `~.transforms.Bbox`.\n     |  \n     |  get_facecolor(self)\n     |      Return the face color.\n     |  \n     |  get_fc(self)\n     |      Alias for `get_facecolor`.\n     |  \n     |  get_fill(self)\n     |      Return whether the patch is filled.\n     |  \n     |  get_hatch(self)\n     |      Return the hatching pattern.\n     |  \n     |  get_joinstyle(self)\n     |      Return the joinstyle.\n     |  \n     |  get_linestyle(self)\n     |      Return the linestyle.\n     |  \n     |  get_linewidth(self)\n     |      Return the line width in points.\n     |  \n     |  get_ls(self)\n     |      Alias for `get_linestyle`.\n     |  \n     |  get_lw(self)\n     |      Alias for `get_linewidth`.\n     |  \n     |  get_transform(self)\n     |      Return the `~.transforms.Transform` applied to the `Patch`.\n     |  \n     |  get_verts(self)\n     |      Return a copy of the vertices used in this patch.\n     |      \n     |      If the patch contains Bezier curves, the curves will be interpolated by\n     |      line segments.  To access the curves as curves, use `get_path`.\n     |  \n     |  get_window_extent(self, renderer=None)\n     |      Get the axes bounding box in display space.\n     |      \n     |      The bounding box' width and height are nonnegative.\n     |      \n     |      Subclasses should override for inclusion in the bounding box\n     |      \"tight\" calculation. Default is to return an empty bounding\n     |      box at 0, 0.\n     |      \n     |      Be careful when using this function, the results will not update\n     |      if the artist window extent of the artist changes.  The extent\n     |      can change due to any changes in the transform stack, such as\n     |      changing the axes limits, the figure size, or the canvas used\n     |      (as is done when saving a figure).  This can lead to unexpected\n     |      behavior where interactive figures will look fine on the screen,\n     |      but will save incorrectly.\n     |  \n     |  set_aa(self, aa)\n     |      Alias for `set_antialiased`.\n     |  \n     |  set_alpha(self, alpha)\n     |      Set the alpha value used for blending - not supported on all backends.\n     |      \n     |      Parameters\n     |      ----------\n     |      alpha : float or None\n     |  \n     |  set_antialiased(self, aa)\n     |      Set whether to use antialiased rendering.\n     |      \n     |      Parameters\n     |      ----------\n     |      b : bool or None\n     |  \n     |  set_capstyle(self, s)\n     |      Set the capstyle.\n     |      \n     |      Parameters\n     |      ----------\n     |      s : {'butt', 'round', 'projecting'}\n     |  \n     |  set_color(self, c)\n     |      Set both the edgecolor and the facecolor.\n     |      \n     |      Parameters\n     |      ----------\n     |      c : color\n     |      \n     |      See Also\n     |      --------\n     |      Patch.set_facecolor, Patch.set_edgecolor\n     |          For setting the edge or face color individually.\n     |  \n     |  set_ec(self, color)\n     |      Alias for `set_edgecolor`.\n     |  \n     |  set_edgecolor(self, color)\n     |      Set the patch edge color.\n     |      \n     |      Parameters\n     |      ----------\n     |      color : color or None or 'auto'\n     |  \n     |  set_facecolor(self, color)\n     |      Set the patch face color.\n     |      \n     |      Parameters\n     |      ----------\n     |      color : color or None\n     |  \n     |  set_fc(self, color)\n     |      Alias for `set_facecolor`.\n     |  \n     |  set_fill(self, b)\n     |      Set whether to fill the patch.\n     |      \n     |      Parameters\n     |      ----------\n     |      b : bool\n     |  \n     |  set_hatch(self, hatch)\n     |      Set the hatching pattern.\n     |      \n     |      *hatch* can be one of::\n     |      \n     |        /   - diagonal hatching\n     |        \\   - back diagonal\n     |        |   - vertical\n     |        -   - horizontal\n     |        +   - crossed\n     |        x   - crossed diagonal\n     |        o   - small circle\n     |        O   - large circle\n     |        .   - dots\n     |        *   - stars\n     |      \n     |      Letters can be combined, in which case all the specified\n     |      hatchings are done.  If same letter repeats, it increases the\n     |      density of hatching of that pattern.\n     |      \n     |      Hatching is supported in the PostScript, PDF, SVG and Agg\n     |      backends only.\n     |      \n     |      Parameters\n     |      ----------\n     |      hatch : {'/', '\\\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}\n     |  \n     |  set_joinstyle(self, s)\n     |      Set the joinstyle.\n     |      \n     |      Parameters\n     |      ----------\n     |      s : {'miter', 'round', 'bevel'}\n     |  \n     |  set_linestyle(self, ls)\n     |      Set the patch linestyle.\n     |      \n     |      ===========================   =================\n     |      linestyle                     description\n     |      ===========================   =================\n     |      ``'-'`` or ``'solid'``        solid line\n     |      ``'--'`` or  ``'dashed'``     dashed line\n     |      ``'-.'`` or  ``'dashdot'``    dash-dotted line\n     |      ``':'`` or ``'dotted'``       dotted line\n     |      ===========================   =================\n     |      \n     |      Alternatively a dash tuple of the following form can be provided::\n     |      \n     |          (offset, onoffseq)\n     |      \n     |      where ``onoffseq`` is an even length tuple of on and off ink in points.\n     |      \n     |      Parameters\n     |      ----------\n     |      ls : {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}\n     |          The line style.\n     |  \n     |  set_linewidth(self, w)\n     |      Set the patch linewidth in points.\n     |      \n     |      Parameters\n     |      ----------\n     |      w : float or None\n     |  \n     |  set_ls(self, ls)\n     |      Alias for `set_linestyle`.\n     |  \n     |  set_lw(self, w)\n     |      Alias for `set_linewidth`.\n     |  \n     |  update_from(self, other)\n     |      Copy properties from *other* to *self*.\n     |  \n     |  ----------------------------------------------------------------------\n     |  Data descriptors inherited from Patch:\n     |  \n     |  fill\n     |      Return whether the patch is filled.\n     |  \n     |  ----------------------------------------------------------------------\n     |  Data and other attributes inherited from Patch:\n     |  \n     |  validCap = ('butt', 'round', 'projecting')\n     |  \n     |  validJoin = ('miter', 'round', 'bevel')\n     |  \n     |  zorder = 1\n     |  \n     |  ----------------------------------------------------------------------\n     |  Methods inherited from matplotlib.artist.Artist:\n     |  \n     |  __getstate__(self)\n     |  \n     |  add_callback(self, func)\n     |      Add a callback function that will be called whenever one of the\n     |      `.Artist`'s properties changes.\n     |      \n     |      Parameters\n     |      ----------\n     |      func : callable\n     |          The callback function. It must have the signature::\n     |      \n     |              def func(artist: Artist) -> Any\n     |      \n     |          where *artist* is the calling `.Artist`. Return values may exist\n     |          but are ignored.\n     |      \n     |      Returns\n     |      -------\n     |      int\n     |          The observer id associated with the callback. This id can be\n     |          used for removing the callback with `.remove_callback` later.\n     |      \n     |      See Also\n     |      --------\n     |      remove_callback\n     |  \n     |  convert_xunits(self, x)\n     |      Convert *x* using the unit type of the xaxis.\n     |      \n     |      If the artist is not in contained in an Axes or if the xaxis does not\n     |      have units, *x* itself is returned.\n     |  \n     |  convert_yunits(self, y)\n     |      Convert *y* using the unit type of the yaxis.\n     |      \n     |      If the artist is not in contained in an Axes or if the yaxis does not\n     |      have units, *y* itself is returned.\n     |  \n     |  findobj(self, match=None, include_self=True)\n     |      Find artist objects.\n     |      \n     |      Recursively find all `.Artist` instances contained in the artist.\n     |      \n     |      Parameters\n     |      ----------\n     |      match\n     |          A filter criterion for the matches. This can be\n     |      \n     |          - *None*: Return all objects contained in artist.\n     |          - A function with signature ``def match(artist: Artist) -> bool``.\n     |            The result will only contain artists for which the function\n     |            returns *True*.\n     |          - A class instance: e.g., `.Line2D`. The result will only contain\n     |            artists of this class or its subclasses (``isinstance`` check).\n     |      \n     |      include_self : bool\n     |          Include *self* in the list to be checked for a match.\n     |      \n     |      Returns\n     |      -------\n     |      list of `.Artist`\n     |  \n     |  format_cursor_data(self, data)\n     |      Return a string representation of *data*.\n     |      \n     |      .. note::\n     |          This method is intended to be overridden by artist subclasses.\n     |          As an end-user of Matplotlib you will most likely not call this\n     |          method yourself.\n     |      \n     |      The default implementation converts ints and floats and arrays of ints\n     |      and floats into a comma-separated string enclosed in square brackets.\n     |      \n     |      See Also\n     |      --------\n     |      get_cursor_data\n     |  \n     |  get_agg_filter(self)\n     |      Return filter function to be used for agg filter.\n     |  \n     |  get_alpha(self)\n     |      Return the alpha value used for blending - not supported on all\n     |      backends.\n     |  \n     |  get_animated(self)\n     |      Return whether the artist is animated.\n     |  \n     |  get_children(self)\n     |      Return a list of the child `.Artist`\\s of this `.Artist`.\n     |  \n     |  get_clip_box(self)\n     |      Return the clipbox.\n     |  \n     |  get_clip_on(self)\n     |      Return whether the artist uses clipping.\n     |  \n     |  get_clip_path(self)\n     |      Return the clip path.\n     |  \n     |  get_contains(self)\n     |      [*Deprecated*] Return the custom contains function of the artist if set, or *None*.\n     |      \n     |      See Also\n     |      --------\n     |      set_contains\n     |      \n     |      Notes\n     |      -----\n     |      .. deprecated:: 3.3\n     |  \n     |  get_cursor_data(self, event)\n     |      Return the cursor data for a given event.\n     |      \n     |      .. note::\n     |          This method is intended to be overridden by artist subclasses.\n     |          As an end-user of Matplotlib you will most likely not call this\n     |          method yourself.\n     |      \n     |      Cursor data can be used by Artists to provide additional context\n     |      information for a given event. The default implementation just returns\n     |      *None*.\n     |      \n     |      Subclasses can override the method and return arbitrary data. However,\n     |      when doing so, they must ensure that `.format_cursor_data` can convert\n     |      the data to a string representation.\n     |      \n     |      The only current use case is displaying the z-value of an `.AxesImage`\n     |      in the status bar of a plot window, while moving the mouse.\n     |      \n     |      Parameters\n     |      ----------\n     |      event : `matplotlib.backend_bases.MouseEvent`\n     |      \n     |      See Also\n     |      --------\n     |      format_cursor_data\n     |  \n     |  get_figure(self)\n     |      Return the `.Figure` instance the artist belongs to.\n     |  \n     |  get_gid(self)\n     |      Return the group id.\n     |  \n     |  get_in_layout(self)\n     |      Return boolean flag, ``True`` if artist is included in layout\n     |      calculations.\n     |      \n     |      E.g. :doc:`/tutorials/intermediate/constrainedlayout_guide`,\n     |      `.Figure.tight_layout()`, and\n     |      ``fig.savefig(fname, bbox_inches='tight')``.\n     |  \n     |  get_label(self)\n     |      Return the label used for this artist in the legend.\n     |  \n     |  get_path_effects(self)\n     |  \n     |  get_picker(self)\n     |      Return the picking behavior of the artist.\n     |      \n     |      The possible values are described in `.set_picker`.\n     |      \n     |      See Also\n     |      --------\n     |      set_picker, pickable, pick\n     |  \n     |  get_rasterized(self)\n     |      Return whether the artist is to be rasterized.\n     |  \n     |  get_sketch_params(self)\n     |      Return the sketch parameters for the artist.\n     |      \n     |      Returns\n     |      -------\n     |      tuple or None\n     |      \n     |          A 3-tuple with the following elements:\n     |      \n     |          - *scale*: The amplitude of the wiggle perpendicular to the\n     |            source line.\n     |          - *length*: The length of the wiggle along the line.\n     |          - *randomness*: The scale factor by which the length is\n     |            shrunken or expanded.\n     |      \n     |          Returns *None* if no sketch parameters were set.\n     |  \n     |  get_snap(self)\n     |      Return the snap setting.\n     |      \n     |      See `.set_snap` for details.\n     |  \n     |  get_tightbbox(self, renderer)\n     |      Like `.Artist.get_window_extent`, but includes any clipping.\n     |      \n     |      Parameters\n     |      ----------\n     |      renderer : `.RendererBase` subclass\n     |          renderer that will be used to draw the figures (i.e.\n     |          ``fig.canvas.get_renderer()``)\n     |      \n     |      Returns\n     |      -------\n     |      `.Bbox`\n     |          The enclosing bounding box (in figure pixel coordinates).\n     |  \n     |  get_transformed_clip_path_and_affine(self)\n     |      Return the clip path with the non-affine part of its\n     |      transformation applied, and the remaining affine part of its\n     |      transformation.\n     |  \n     |  get_url(self)\n     |      Return the url.\n     |  \n     |  get_visible(self)\n     |      Return the visibility.\n     |  \n     |  get_zorder(self)\n     |      Return the artist's zorder.\n     |  \n     |  have_units(self)\n     |      Return *True* if units are set on any axis.\n     |  \n     |  is_transform_set(self)\n     |      Return whether the Artist has an explicitly set transform.\n     |      \n     |      This is *True* after `.set_transform` has been called.\n     |  \n     |  pchanged(self)\n     |      Call all of the registered callbacks.\n     |      \n     |      This function is triggered internally when a property is changed.\n     |      \n     |      See Also\n     |      --------\n     |      add_callback\n     |      remove_callback\n     |  \n     |  pick(self, mouseevent)\n     |      Process a pick event.\n     |      \n     |      Each child artist will fire a pick event if *mouseevent* is over\n     |      the artist and the artist has picker set.\n     |      \n     |      See Also\n     |      --------\n     |      set_picker, get_picker, pickable\n     |  \n     |  pickable(self)\n     |      Return whether the artist is pickable.\n     |      \n     |      See Also\n     |      --------\n     |      set_picker, get_picker, pick\n     |  \n     |  properties(self)\n     |      Return a dictionary of all the properties of the artist.\n     |  \n     |  remove(self)\n     |      Remove the artist from the figure if possible.\n     |      \n     |      The effect will not be visible until the figure is redrawn, e.g.,\n     |      with `.FigureCanvasBase.draw_idle`.  Call `~.axes.Axes.relim` to\n     |      update the axes limits if desired.\n     |      \n     |      Note: `~.axes.Axes.relim` will not see collections even if the\n     |      collection was added to the axes with *autolim* = True.\n     |      \n     |      Note: there is no support for removing the artist's legend entry.\n     |  \n     |  remove_callback(self, oid)\n     |      Remove a callback based on its observer id.\n     |      \n     |      See Also\n     |      --------\n     |      add_callback\n     |  \n     |  set(self, **kwargs)\n     |      A property batch setter.  Pass *kwargs* to set properties.\n     |  \n     |  set_agg_filter(self, filter_func)\n     |      Set the agg filter.\n     |      \n     |      Parameters\n     |      ----------\n     |      filter_func : callable\n     |          A filter function, which takes a (m, n, 3) float array and a dpi\n     |          value, and returns a (m, n, 3) array.\n     |      \n     |          .. ACCEPTS: a filter function, which takes a (m, n, 3) float array\n     |              and a dpi value, and returns a (m, n, 3) array\n     |  \n     |  set_animated(self, b)\n     |      Set the artist's animation state.\n     |      \n     |      Parameters\n     |      ----------\n     |      b : bool\n     |  \n     |  set_clip_box(self, clipbox)\n     |      Set the artist's clip `.Bbox`.\n     |      \n     |      Parameters\n     |      ----------\n     |      clipbox : `.Bbox`\n     |  \n     |  set_clip_on(self, b)\n     |      Set whether the artist uses clipping.\n     |      \n     |      When False artists will be visible outside of the axes which\n     |      can lead to unexpected results.\n     |      \n     |      Parameters\n     |      ----------\n     |      b : bool\n     |  \n     |  set_clip_path(self, path, transform=None)\n     |      Set the artist's clip path.\n     |      \n     |      Parameters\n     |      ----------\n     |      path : `.Patch` or `.Path` or `.TransformedPath` or None\n     |          The clip path. If given a `.Path`, *transform* must be provided as\n     |          well. If *None*, a previously set clip path is removed.\n     |      transform : `~matplotlib.transforms.Transform`, optional\n     |          Only used if *path* is a `.Path`, in which case the given `.Path`\n     |          is converted to a `.TransformedPath` using *transform*.\n     |      \n     |      Notes\n     |      -----\n     |      For efficiency, if *path* is a `.Rectangle` this method will set the\n     |      clipping box to the corresponding rectangle and set the clipping path\n     |      to ``None``.\n     |      \n     |      For technical reasons (support of `~.Artist.set`), a tuple\n     |      (*path*, *transform*) is also accepted as a single positional\n     |      parameter.\n     |      \n     |      .. ACCEPTS: Patch or (Path, Transform) or None\n     |  \n     |  set_contains(self, picker)\n     |      [*Deprecated*] Define a custom contains test for the artist.\n     |      \n     |      The provided callable replaces the default `.contains` method\n     |      of the artist.\n     |      \n     |      Parameters\n     |      ----------\n     |      picker : callable\n     |          A custom picker function to evaluate if an event is within the\n     |          artist. The function must have the signature::\n     |      \n     |              def contains(artist: Artist, event: MouseEvent) -> bool, dict\n     |      \n     |          that returns:\n     |      \n     |          - a bool indicating if the event is within the artist\n     |          - a dict of additional information. The dict should at least\n     |            return the same information as the default ``contains()``\n     |            implementation of the respective artist, but may provide\n     |            additional information.\n     |      \n     |      Notes\n     |      -----\n     |      .. deprecated:: 3.3\n     |  \n     |  set_figure(self, fig)\n     |      Set the `.Figure` instance the artist belongs to.\n     |      \n     |      Parameters\n     |      ----------\n     |      fig : `.Figure`\n     |  \n     |  set_gid(self, gid)\n     |      Set the (group) id for the artist.\n     |      \n     |      Parameters\n     |      ----------\n     |      gid : str\n     |  \n     |  set_in_layout(self, in_layout)\n     |      Set if artist is to be included in layout calculations,\n     |      E.g. :doc:`/tutorials/intermediate/constrainedlayout_guide`,\n     |      `.Figure.tight_layout()`, and\n     |      ``fig.savefig(fname, bbox_inches='tight')``.\n     |      \n     |      Parameters\n     |      ----------\n     |      in_layout : bool\n     |  \n     |  set_label(self, s)\n     |      Set a label that will be displayed in the legend.\n     |      \n     |      Parameters\n     |      ----------\n     |      s : object\n     |          *s* will be converted to a string by calling `str`.\n     |  \n     |  set_path_effects(self, path_effects)\n     |      Set the path effects.\n     |      \n     |      Parameters\n     |      ----------\n     |      path_effects : `.AbstractPathEffect`\n     |  \n     |  set_picker(self, picker)\n     |      Define the picking behavior of the artist.\n     |      \n     |      Parameters\n     |      ----------\n     |      picker : None or bool or callable\n     |          This can be one of the following:\n     |      \n     |          - *None*: Picking is disabled for this artist (default).\n     |      \n     |          - A boolean: If *True* then picking will be enabled and the\n     |            artist will fire a pick event if the mouse event is over\n     |            the artist.\n     |      \n     |          - A function: If picker is callable, it is a user supplied\n     |            function which determines whether the artist is hit by the\n     |            mouse event::\n     |      \n     |              hit, props = picker(artist, mouseevent)\n     |      \n     |            to determine the hit test.  if the mouse event is over the\n     |            artist, return *hit=True* and props is a dictionary of\n     |            properties you want added to the PickEvent attributes.\n     |      \n     |          - *deprecated*: For `.Line2D` only, *picker* can also be a float\n     |            that sets the tolerance for checking whether an event occurred\n     |            \"on\" the line; this is deprecated.  Use `.Line2D.set_pickradius`\n     |            instead.\n     |  \n     |  set_rasterized(self, rasterized)\n     |      Force rasterized (bitmap) drawing in vector backend output.\n     |      \n     |      Defaults to None, which implies the backend's default behavior.\n     |      \n     |      Parameters\n     |      ----------\n     |      rasterized : bool or None\n     |  \n     |  set_sketch_params(self, scale=None, length=None, randomness=None)\n     |      Sets the sketch parameters.\n     |      \n     |      Parameters\n     |      ----------\n     |      scale : float, optional\n     |          The amplitude of the wiggle perpendicular to the source\n     |          line, in pixels.  If scale is `None`, or not provided, no\n     |          sketch filter will be provided.\n     |      length : float, optional\n     |           The length of the wiggle along the line, in pixels\n     |           (default 128.0)\n     |      randomness : float, optional\n     |          The scale factor by which the length is shrunken or\n     |          expanded (default 16.0)\n     |      \n     |          .. ACCEPTS: (scale: float, length: float, randomness: float)\n     |  \n     |  set_snap(self, snap)\n     |      Set the snapping behavior.\n     |      \n     |      Snapping aligns positions with the pixel grid, which results in\n     |      clearer images. For example, if a black line of 1px width was\n     |      defined at a position in between two pixels, the resulting image\n     |      would contain the interpolated value of that line in the pixel grid,\n     |      which would be a grey value on both adjacent pixel positions. In\n     |      contrast, snapping will move the line to the nearest integer pixel\n     |      value, so that the resulting image will really contain a 1px wide\n     |      black line.\n     |      \n     |      Snapping is currently only supported by the Agg and MacOSX backends.\n     |      \n     |      Parameters\n     |      ----------\n     |      snap : bool or None\n     |          Possible values:\n     |      \n     |          - *True*: Snap vertices to the nearest pixel center.\n     |          - *False*: Do not modify vertex positions.\n     |          - *None*: (auto) If the path contains only rectilinear line\n     |            segments, round to the nearest pixel center.\n     |  \n     |  set_transform(self, t)\n     |      Set the artist transform.\n     |      \n     |      Parameters\n     |      ----------\n     |      t : `.Transform`\n     |  \n     |  set_url(self, url)\n     |      Set the url for the artist.\n     |      \n     |      Parameters\n     |      ----------\n     |      url : str\n     |  \n     |  set_visible(self, b)\n     |      Set the artist's visibility.\n     |      \n     |      Parameters\n     |      ----------\n     |      b : bool\n     |  \n     |  set_zorder(self, level)\n     |      Set the zorder for the artist.  Artists with lower zorder\n     |      values are drawn first.\n     |      \n     |      Parameters\n     |      ----------\n     |      level : float\n     |  \n     |  update(self, props)\n     |      Update this artist's properties from the dict *props*.\n     |      \n     |      Parameters\n     |      ----------\n     |      props : dict\n     |  \n     |  ----------------------------------------------------------------------\n     |  Readonly properties inherited from matplotlib.artist.Artist:\n     |  \n     |  sticky_edges\n     |      ``x`` and ``y`` sticky edge lists for autoscaling.\n     |      \n     |      When performing autoscaling, if a data limit coincides with a value in\n     |      the corresponding sticky_edges list, then no margin will be added--the\n     |      view limit \"sticks\" to the edge. A typical use case is histograms,\n     |      where one usually expects no margin on the bottom edge (0) of the\n     |      histogram.\n     |      \n     |      This attribute cannot be assigned to; however, the ``x`` and ``y``\n     |      lists can be modified in place as needed.\n     |      \n     |      Examples\n     |      --------\n     |      >>> artist.sticky_edges.x[:] = (xmin, xmax)\n     |      >>> artist.sticky_edges.y[:] = (ymin, ymax)\n     |  \n     |  ----------------------------------------------------------------------\n     |  Data descriptors inherited from matplotlib.artist.Artist:\n     |  \n     |  __dict__\n     |      dictionary for instance variables (if defined)\n     |  \n     |  __weakref__\n     |      list of weak references to the object (if defined)\n     |  \n     |  axes\n     |      The `~.axes.Axes` instance the artist resides in, or *None*.\n     |  \n     |  mouseover\n     |      If this property is set to *True*, the artist will be queried for\n     |      custom context information when the mouse cursor moves over it.\n     |      \n     |      See also :meth:`get_cursor_data`, :class:`.ToolCursorPosition` and\n     |      :class:`.NavigationToolbar2`.\n     |  \n     |  stale\n     |      Whether the artist is 'stale' and needs to be re-drawn for the output\n     |      to match the internal state of the artist.\n    \n\n\n\n```python\nfig, ax = mp3d.subplots(111, projection='3d', xlim=(0, 6), ylim=(0, 6))\n# ax.plot([1.0,2.0,3.0],[4.0,5.0,6.0])\nc = patches.Circle((2,3),1)\n# mp3d.art3d.patch_2d_to_3d(c)\n# col = mp3d.art3d.Patch3DCollection([c])\nax.add_artist(c)\nplt.show()\n```\n\n\n```python\nax.plot(1.0,2.0,3.0)\n```\n\n\n\n\n    [<mpl_toolkits.mplot3d.art3d.Line3D at 0x56f0d48>]\n\n\n\n\n```python\n[s for s in dir(ax) if not s.startswith('_')]\n```\n\n\n\n\n    ['M',\n     'acorr',\n     'add_artist',\n     'add_callback',\n     'add_child_axes',\n     'add_collection',\n     'add_collection3d',\n     'add_container',\n     'add_contour_set',\n     'add_contourf_set',\n     'add_image',\n     'add_line',\n     'add_patch',\n     'add_table',\n     'angle_spectrum',\n     'annotate',\n     'apply_aspect',\n     'arrow',\n     'artists',\n     'auto_scale_xyz',\n     'autoscale',\n     'autoscale_view',\n     'axes',\n     'axhline',\n     'axhspan',\n     'axis',\n     'axison',\n     'axline',\n     'axvline',\n     'axvspan',\n     'azim',\n     'bar',\n     'bar3d',\n     'barbs',\n     'barh',\n     'bbox',\n     'boxplot',\n     'broken_barh',\n     'button_pressed',\n     'bxp',\n     'callbacks',\n     'can_pan',\n     'can_zoom',\n     'change_geometry',\n     'child_axes',\n     'cla',\n     'clabel',\n     'clear',\n     'clipbox',\n     'cohere',\n     'colNum',\n     'collections',\n     'containers',\n     'contains',\n     'contains_point',\n     'contour',\n     'contour3D',\n     'contourf',\n     'contourf3D',\n     'convert_xunits',\n     'convert_yunits',\n     'convert_zunits',\n     'csd',\n     'dataLim',\n     'disable_mouse_rotation',\n     'dist',\n     'drag_pan',\n     'draw',\n     'draw_artist',\n     'elev',\n     'end_pan',\n     'errorbar',\n     'eventplot',\n     'eventson',\n     'eye',\n     'figbox',\n     'figure',\n     'fill',\n     'fill_between',\n     'fill_betweenx',\n     'findobj',\n     'fmt_xdata',\n     'fmt_ydata',\n     'fmt_zdata',\n     'format_coord',\n     'format_cursor_data',\n     'format_xdata',\n     'format_ydata',\n     'format_zdata',\n     'get_adjustable',\n     'get_agg_filter',\n     'get_alpha',\n     'get_anchor',\n     'get_animated',\n     'get_aspect',\n     'get_autoscale_on',\n     'get_autoscalex_on',\n     'get_autoscaley_on',\n     'get_autoscalez_on',\n     'get_axes_locator',\n     'get_axis_position',\n     'get_axisbelow',\n     'get_box_aspect',\n     'get_children',\n     'get_clip_box',\n     'get_clip_on',\n     'get_clip_path',\n     'get_contains',\n     'get_cursor_data',\n     'get_data_ratio',\n     'get_data_ratio_log',\n     'get_default_bbox_extra_artists',\n     'get_facecolor',\n     'get_fc',\n     'get_figure',\n     'get_frame_on',\n     'get_geometry',\n     'get_gid',\n     'get_gridspec',\n     'get_images',\n     'get_in_layout',\n     'get_label',\n     'get_legend',\n     'get_legend_handles_labels',\n     'get_lines',\n     'get_navigate',\n     'get_navigate_mode',\n     'get_path_effects',\n     'get_picker',\n     'get_position',\n     'get_proj',\n     'get_rasterization_zorder',\n     'get_rasterized',\n     'get_renderer_cache',\n     'get_shared_x_axes',\n     'get_shared_y_axes',\n     'get_sketch_params',\n     'get_snap',\n     'get_subplotspec',\n     'get_tightbbox',\n     'get_title',\n     'get_transform',\n     'get_transformed_clip_path_and_affine',\n     'get_url',\n     'get_visible',\n     'get_w_lims',\n     'get_window_extent',\n     'get_xaxis',\n     'get_xaxis_text1_transform',\n     'get_xaxis_text2_transform',\n     'get_xaxis_transform',\n     'get_xbound',\n     'get_xgridlines',\n     'get_xlabel',\n     'get_xlim',\n     'get_xlim3d',\n     'get_xmajorticklabels',\n     'get_xminorticklabels',\n     'get_xscale',\n     'get_xticklabels',\n     'get_xticklines',\n     'get_xticks',\n     'get_yaxis',\n     'get_yaxis_text1_transform',\n     'get_yaxis_text2_transform',\n     'get_yaxis_transform',\n     'get_ybound',\n     'get_ygridlines',\n     'get_ylabel',\n     'get_ylim',\n     'get_ylim3d',\n     'get_ymajorticklabels',\n     'get_yminorticklabels',\n     'get_yscale',\n     'get_yticklabels',\n     'get_yticklines',\n     'get_yticks',\n     'get_zaxis',\n     'get_zbound',\n     'get_zgridlines',\n     'get_zlabel',\n     'get_zlim',\n     'get_zlim3d',\n     'get_zmajorticklabels',\n     'get_zminorticklabels',\n     'get_zorder',\n     'get_zscale',\n     'get_zticklabels',\n     'get_zticklines',\n     'get_zticks',\n     'grid',\n     'has_data',\n     'have_units',\n     'hexbin',\n     'hist',\n     'hist2d',\n     'hlines',\n     'ignore_existing_data_limits',\n     'images',\n     'imshow',\n     'in_axes',\n     'indicate_inset',\n     'indicate_inset_zoom',\n     'initial_azim',\n     'initial_elev',\n     'inset_axes',\n     'invert_xaxis',\n     'invert_yaxis',\n     'invert_zaxis',\n     'is_first_col',\n     'is_first_row',\n     'is_last_col',\n     'is_last_row',\n     'is_transform_set',\n     'label_outer',\n     'legend',\n     'legend_',\n     'lines',\n     'locator_params',\n     'loglog',\n     'magnitude_spectrum',\n     'margins',\n     'matshow',\n     'minorticks_off',\n     'minorticks_on',\n     'mouse_init',\n     'mouseover',\n     'name',\n     'numCols',\n     'numRows',\n     'patch',\n     'patches',\n     'pchanged',\n     'pcolor',\n     'pcolorfast',\n     'pcolormesh',\n     'phase_spectrum',\n     'pick',\n     'pickable',\n     'pie',\n     'plot',\n     'plot3D',\n     'plot_date',\n     'plot_surface',\n     'plot_trisurf',\n     'plot_wireframe',\n     'properties',\n     'psd',\n     'quiver',\n     'quiver3D',\n     'quiverkey',\n     'redraw_in_frame',\n     'relim',\n     'remove',\n     'remove_callback',\n     'reset_position',\n     'rowNum',\n     'scatter',\n     'scatter3D',\n     'secondary_xaxis',\n     'secondary_yaxis',\n     'semilogx',\n     'semilogy',\n     'set',\n     'set_adjustable',\n     'set_agg_filter',\n     'set_alpha',\n     'set_anchor',\n     'set_animated',\n     'set_aspect',\n     'set_autoscale_on',\n     'set_autoscalex_on',\n     'set_autoscaley_on',\n     'set_autoscalez_on',\n     'set_axes_locator',\n     'set_axis_off',\n     'set_axis_on',\n     'set_axisbelow',\n     'set_box_aspect',\n     'set_clip_box',\n     'set_clip_on',\n     'set_clip_path',\n     'set_contains',\n     'set_facecolor',\n     'set_fc',\n     'set_figure',\n     'set_frame_on',\n     'set_gid',\n     'set_in_layout',\n     'set_label',\n     'set_navigate',\n     'set_navigate_mode',\n     'set_path_effects',\n     'set_picker',\n     'set_position',\n     'set_proj_type',\n     'set_prop_cycle',\n     'set_rasterization_zorder',\n     'set_rasterized',\n     'set_sketch_params',\n     'set_snap',\n     'set_subplotspec',\n     'set_title',\n     'set_top_view',\n     'set_transform',\n     'set_url',\n     'set_visible',\n     'set_xbound',\n     'set_xlabel',\n     'set_xlim',\n     'set_xlim3d',\n     'set_xmargin',\n     'set_xscale',\n     'set_xticklabels',\n     'set_xticks',\n     'set_ybound',\n     'set_ylabel',\n     'set_ylim',\n     'set_ylim3d',\n     'set_ymargin',\n     'set_yscale',\n     'set_yticklabels',\n     'set_yticks',\n     'set_zbound',\n     'set_zlabel',\n     'set_zlim',\n     'set_zlim3d',\n     'set_zmargin',\n     'set_zorder',\n     'set_zscale',\n     'set_zticklabels',\n     'set_zticks',\n     'sharex',\n     'sharey',\n     'specgram',\n     'spines',\n     'spy',\n     'stackplot',\n     'stale',\n     'stale_callback',\n     'start_pan',\n     'stem',\n     'step',\n     'sticky_edges',\n     'streamplot',\n     'table',\n     'tables',\n     'text',\n     'text2D',\n     'text3D',\n     'texts',\n     'tick_params',\n     'ticklabel_format',\n     'title',\n     'titleOffsetTrans',\n     'transAxes',\n     'transData',\n     'transLimits',\n     'transScale',\n     'tricontour',\n     'tricontourf',\n     'tripcolor',\n     'triplot',\n     'tunit_cube',\n     'tunit_edges',\n     'twinx',\n     'twiny',\n     'unit_cube',\n     'update',\n     'update_datalim',\n     'update_datalim_bounds',\n     'update_from',\n     'update_params',\n     'use_sticky_edges',\n     'viewLim',\n     'view_init',\n     'violin',\n     'violinplot',\n     'vlines',\n     'voxels',\n     'vvec',\n     'w_xaxis',\n     'w_yaxis',\n     'w_zaxis',\n     'xaxis',\n     'xaxis_date',\n     'xaxis_inverted',\n     'xcorr',\n     'xy_dataLim',\n     'xy_viewLim',\n     'yaxis',\n     'yaxis_date',\n     'yaxis_inverted',\n     'zaxis',\n     'zaxis_date',\n     'zaxis_inverted',\n     'zorder',\n     'zz_dataLim',\n     'zz_viewLim']\n\n\n\n\n```python\nplt.show()\n```\n\n\n```python\nhelp(ax.patch)\n```\n\n    Help on Rectangle in module matplotlib.patches object:\n    \n    class Rectangle(Patch)\n     |  Rectangle(xy, width, height, angle=0.0, **kwargs)\n     |  \n     |  A rectangle defined via an anchor point *xy* and its *width* and *height*.\n     |  \n     |  The rectangle extends from ``xy[0]`` to ``xy[0] + width`` in x-direction\n     |  and from ``xy[1]`` to ``xy[1] + height`` in y-direction. ::\n     |  \n     |    :                +------------------+\n     |    :                |                  |\n     |    :              height               |\n     |    :                |                  |\n     |    :               (xy)---- width -----+\n     |  \n     |  One may picture *xy* as the bottom left corner, but which corner *xy* is\n     |  actually depends on the the direction of the axis and the sign of *width*\n     |  and *height*; e.g. *xy* would be the bottom right corner if the x-axis\n     |  was inverted or if *width* was negative.\n     |  \n     |  Method resolution order:\n     |      Rectangle\n     |      Patch\n     |      matplotlib.artist.Artist\n     |      builtins.object\n     |  \n     |  Methods defined here:\n     |  \n     |  __init__(self, xy, width, height, angle=0.0, **kwargs)\n     |      Parameters\n     |      ----------\n     |      xy : (float, float)\n     |          The anchor point.\n     |      width : float\n     |          Rectangle width.\n     |      height : float\n     |          Rectangle height.\n     |      angle : float, default: 0\n     |          Rotation in degrees anti-clockwise about *xy*.\n     |      \n     |      Other Parameters\n     |      ----------------\n     |      **kwargs : `.Patch` properties\n     |          Properties:\n     |          agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array\n     |          alpha: float or None\n     |          animated: bool\n     |          antialiased or aa: unknown\n     |          capstyle: {'butt', 'round', 'projecting'}\n     |          clip_box: `.Bbox`\n     |          clip_on: bool\n     |          clip_path: Patch or (Path, Transform) or None\n     |          color: color\n     |          contains: unknown\n     |          edgecolor or ec: color or None or 'auto'\n     |          facecolor or fc: color or None\n     |          figure: `.Figure`\n     |          fill: bool\n     |          gid: str\n     |          hatch: {'/', '\\\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}\n     |          in_layout: bool\n     |          joinstyle: {'miter', 'round', 'bevel'}\n     |          label: object\n     |          linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}\n     |          linewidth or lw: float or None\n     |          path_effects: `.AbstractPathEffect`\n     |          picker: None or bool or callable\n     |          rasterized: bool or None\n     |          sketch_params: (scale: float, length: float, randomness: float)\n     |          snap: bool or None\n     |          transform: `.Transform`\n     |          url: str\n     |          visible: bool\n     |          zorder: float\n     |  \n     |  __str__(self)\n     |      Return str(self).\n     |  \n     |  get_bbox(self)\n     |      Return the `.Bbox`.\n     |  \n     |  get_height(self)\n     |      Return the height of the rectangle.\n     |  \n     |  get_patch_transform(self)\n     |      Return the `~.transforms.Transform` instance mapping patch coordinates\n     |      to data coordinates.\n     |      \n     |      For example, one may define a patch of a circle which represents a\n     |      radius of 5 by providing coordinates for a unit circle, and a\n     |      transform which scales the coordinates (the patch coordinate) by 5.\n     |  \n     |  get_path(self)\n     |      Return the vertices of the rectangle.\n     |  \n     |  get_width(self)\n     |      Return the width of the rectangle.\n     |  \n     |  get_x(self)\n     |      Return the left coordinate of the rectangle.\n     |  \n     |  get_xy(self)\n     |      Return the left and bottom coords of the rectangle as a tuple.\n     |  \n     |  get_y(self)\n     |      Return the bottom coordinate of the rectangle.\n     |  \n     |  set_bounds(self, *args)\n     |      Set the bounds of the rectangle as *left*, *bottom*, *width*, *height*.\n     |      \n     |      The values may be passed as separate parameters or as a tuple::\n     |      \n     |          set_bounds(left, bottom, width, height)\n     |          set_bounds((left, bottom, width, height))\n     |      \n     |      .. ACCEPTS: (left, bottom, width, height)\n     |  \n     |  set_height(self, h)\n     |      Set the height of the rectangle.\n     |  \n     |  set_width(self, w)\n     |      Set the width of the rectangle.\n     |  \n     |  set_x(self, x)\n     |      Set the left coordinate of the rectangle.\n     |  \n     |  set_xy(self, xy)\n     |      Set the left and bottom coordinates of the rectangle.\n     |      \n     |      Parameters\n     |      ----------\n     |      xy : (float, float)\n     |  \n     |  set_y(self, y)\n     |      Set the bottom coordinate of the rectangle.\n     |  \n     |  ----------------------------------------------------------------------\n     |  Data descriptors defined here:\n     |  \n     |  xy\n     |      Return the left and bottom coords of the rectangle as a tuple.\n     |  \n     |  ----------------------------------------------------------------------\n     |  Methods inherited from Patch:\n     |  \n     |  contains(self, mouseevent, radius=None)\n     |      Test whether the mouse event occurred in the patch.\n     |      \n     |      Returns\n     |      -------\n     |      (bool, empty dict)\n     |  \n     |  contains_point(self, point, radius=None)\n     |      Return whether the given point is inside the patch.\n     |      \n     |      Parameters\n     |      ----------\n     |      point : (float, float)\n     |          The point (x, y) to check, in target coordinates of\n     |          ``self.get_transform()``. These are display coordinates for patches\n     |          that are added to a figure or axes.\n     |      radius : float, optional\n     |          Add an additional margin on the patch in target coordinates of\n     |          ``self.get_transform()``. See `.Path.contains_point` for further\n     |          details.\n     |      \n     |      Returns\n     |      -------\n     |      bool\n     |      \n     |      Notes\n     |      -----\n     |      The proper use of this method depends on the transform of the patch.\n     |      Isolated patches do not have a transform. In this case, the patch\n     |      creation coordinates and the point coordinates match. The following\n     |      example checks that the center of a circle is within the circle\n     |      \n     |      >>> center = 0, 0\n     |      >>> c = Circle(center, radius=1)\n     |      >>> c.contains_point(center)\n     |      True\n     |      \n     |      The convention of checking against the transformed patch stems from\n     |      the fact that this method is predominantly used to check if display\n     |      coordinates (e.g. from mouse events) are within the patch. If you want\n     |      to do the above check with data coordinates, you have to properly\n     |      transform them first:\n     |      \n     |      >>> center = 0, 0\n     |      >>> c = Circle(center, radius=1)\n     |      >>> plt.gca().add_patch(c)\n     |      >>> transformed_center = c.get_transform().transform(center)\n     |      >>> c.contains_point(transformed_center)\n     |      True\n     |  \n     |  contains_points(self, points, radius=None)\n     |      Return whether the given points are inside the patch.\n     |      \n     |      Parameters\n     |      ----------\n     |      points : (N, 2) array\n     |          The points to check, in target coordinates of\n     |          ``self.get_transform()``. These are display coordinates for patches\n     |          that are added to a figure or axes. Columns contain x and y values.\n     |      radius : float, optional\n     |          Add an additional margin on the patch in target coordinates of\n     |          ``self.get_transform()``. See `.Path.contains_point` for further\n     |          details.\n     |      \n     |      Returns\n     |      -------\n     |      length-N bool array\n     |      \n     |      Notes\n     |      -----\n     |      The proper use of this method depends on the transform of the patch.\n     |      See the notes on `.Patch.contains_point`.\n     |  \n     |  draw(self, renderer)\n     |      Draw the Artist (and its children) using the given renderer.\n     |      \n     |      This has no effect if the artist is not visible (`.Artist.get_visible`\n     |      returns False).\n     |      \n     |      Parameters\n     |      ----------\n     |      renderer : `.RendererBase` subclass.\n     |      \n     |      Notes\n     |      -----\n     |      This method is overridden in the Artist subclasses.\n     |  \n     |  get_aa(self)\n     |      Alias for `get_antialiased`.\n     |  \n     |  get_antialiased(self)\n     |      Return whether antialiasing is used for drawing.\n     |  \n     |  get_capstyle(self)\n     |      Return the capstyle.\n     |  \n     |  get_data_transform(self)\n     |      Return the `~.transforms.Transform` mapping data coordinates to\n     |      physical coordinates.\n     |  \n     |  get_ec(self)\n     |      Alias for `get_edgecolor`.\n     |  \n     |  get_edgecolor(self)\n     |      Return the edge color.\n     |  \n     |  get_extents(self)\n     |      Return the `Patch`'s axis-aligned extents as a `~.transforms.Bbox`.\n     |  \n     |  get_facecolor(self)\n     |      Return the face color.\n     |  \n     |  get_fc(self)\n     |      Alias for `get_facecolor`.\n     |  \n     |  get_fill(self)\n     |      Return whether the patch is filled.\n     |  \n     |  get_hatch(self)\n     |      Return the hatching pattern.\n     |  \n     |  get_joinstyle(self)\n     |      Return the joinstyle.\n     |  \n     |  get_linestyle(self)\n     |      Return the linestyle.\n     |  \n     |  get_linewidth(self)\n     |      Return the line width in points.\n     |  \n     |  get_ls(self)\n     |      Alias for `get_linestyle`.\n     |  \n     |  get_lw(self)\n     |      Alias for `get_linewidth`.\n     |  \n     |  get_transform(self)\n     |      Return the `~.transforms.Transform` applied to the `Patch`.\n     |  \n     |  get_verts(self)\n     |      Return a copy of the vertices used in this patch.\n     |      \n     |      If the patch contains Bezier curves, the curves will be interpolated by\n     |      line segments.  To access the curves as curves, use `get_path`.\n     |  \n     |  get_window_extent(self, renderer=None)\n     |      Get the axes bounding box in display space.\n     |      \n     |      The bounding box' width and height are nonnegative.\n     |      \n     |      Subclasses should override for inclusion in the bounding box\n     |      \"tight\" calculation. Default is to return an empty bounding\n     |      box at 0, 0.\n     |      \n     |      Be careful when using this function, the results will not update\n     |      if the artist window extent of the artist changes.  The extent\n     |      can change due to any changes in the transform stack, such as\n     |      changing the axes limits, the figure size, or the canvas used\n     |      (as is done when saving a figure).  This can lead to unexpected\n     |      behavior where interactive figures will look fine on the screen,\n     |      but will save incorrectly.\n     |  \n     |  set_aa(self, aa)\n     |      Alias for `set_antialiased`.\n     |  \n     |  set_alpha(self, alpha)\n     |      Set the alpha value used for blending - not supported on all backends.\n     |      \n     |      Parameters\n     |      ----------\n     |      alpha : float or None\n     |  \n     |  set_antialiased(self, aa)\n     |      Set whether to use antialiased rendering.\n     |      \n     |      Parameters\n     |      ----------\n     |      b : bool or None\n     |  \n     |  set_capstyle(self, s)\n     |      Set the capstyle.\n     |      \n     |      Parameters\n     |      ----------\n     |      s : {'butt', 'round', 'projecting'}\n     |  \n     |  set_color(self, c)\n     |      Set both the edgecolor and the facecolor.\n     |      \n     |      Parameters\n     |      ----------\n     |      c : color\n     |      \n     |      See Also\n     |      --------\n     |      Patch.set_facecolor, Patch.set_edgecolor\n     |          For setting the edge or face color individually.\n     |  \n     |  set_ec(self, color)\n     |      Alias for `set_edgecolor`.\n     |  \n     |  set_edgecolor(self, color)\n     |      Set the patch edge color.\n     |      \n     |      Parameters\n     |      ----------\n     |      color : color or None or 'auto'\n     |  \n     |  set_facecolor(self, color)\n     |      Set the patch face color.\n     |      \n     |      Parameters\n     |      ----------\n     |      color : color or None\n     |  \n     |  set_fc(self, color)\n     |      Alias for `set_facecolor`.\n     |  \n     |  set_fill(self, b)\n     |      Set whether to fill the patch.\n     |      \n     |      Parameters\n     |      ----------\n     |      b : bool\n     |  \n     |  set_hatch(self, hatch)\n     |      Set the hatching pattern.\n     |      \n     |      *hatch* can be one of::\n     |      \n     |        /   - diagonal hatching\n     |        \\   - back diagonal\n     |        |   - vertical\n     |        -   - horizontal\n     |        +   - crossed\n     |        x   - crossed diagonal\n     |        o   - small circle\n     |        O   - large circle\n     |        .   - dots\n     |        *   - stars\n     |      \n     |      Letters can be combined, in which case all the specified\n     |      hatchings are done.  If same letter repeats, it increases the\n     |      density of hatching of that pattern.\n     |      \n     |      Hatching is supported in the PostScript, PDF, SVG and Agg\n     |      backends only.\n     |      \n     |      Parameters\n     |      ----------\n     |      hatch : {'/', '\\\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}\n     |  \n     |  set_joinstyle(self, s)\n     |      Set the joinstyle.\n     |      \n     |      Parameters\n     |      ----------\n     |      s : {'miter', 'round', 'bevel'}\n     |  \n     |  set_linestyle(self, ls)\n     |      Set the patch linestyle.\n     |      \n     |      ===========================   =================\n     |      linestyle                     description\n     |      ===========================   =================\n     |      ``'-'`` or ``'solid'``        solid line\n     |      ``'--'`` or  ``'dashed'``     dashed line\n     |      ``'-.'`` or  ``'dashdot'``    dash-dotted line\n     |      ``':'`` or ``'dotted'``       dotted line\n     |      ===========================   =================\n     |      \n     |      Alternatively a dash tuple of the following form can be provided::\n     |      \n     |          (offset, onoffseq)\n     |      \n     |      where ``onoffseq`` is an even length tuple of on and off ink in points.\n     |      \n     |      Parameters\n     |      ----------\n     |      ls : {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}\n     |          The line style.\n     |  \n     |  set_linewidth(self, w)\n     |      Set the patch linewidth in points.\n     |      \n     |      Parameters\n     |      ----------\n     |      w : float or None\n     |  \n     |  set_ls(self, ls)\n     |      Alias for `set_linestyle`.\n     |  \n     |  set_lw(self, w)\n     |      Alias for `set_linewidth`.\n     |  \n     |  update_from(self, other)\n     |      Copy properties from *other* to *self*.\n     |  \n     |  ----------------------------------------------------------------------\n     |  Data descriptors inherited from Patch:\n     |  \n     |  fill\n     |      Return whether the patch is filled.\n     |  \n     |  ----------------------------------------------------------------------\n     |  Data and other attributes inherited from Patch:\n     |  \n     |  validCap = ('butt', 'round', 'projecting')\n     |  \n     |  validJoin = ('miter', 'round', 'bevel')\n     |  \n     |  zorder = 1\n     |  \n     |  ----------------------------------------------------------------------\n     |  Methods inherited from matplotlib.artist.Artist:\n     |  \n     |  __getstate__(self)\n     |  \n     |  add_callback(self, func)\n     |      Add a callback function that will be called whenever one of the\n     |      `.Artist`'s properties changes.\n     |      \n     |      Parameters\n     |      ----------\n     |      func : callable\n     |          The callback function. It must have the signature::\n     |      \n     |              def func(artist: Artist) -> Any\n     |      \n     |          where *artist* is the calling `.Artist`. Return values may exist\n     |          but are ignored.\n     |      \n     |      Returns\n     |      -------\n     |      int\n     |          The observer id associated with the callback. This id can be\n     |          used for removing the callback with `.remove_callback` later.\n     |      \n     |      See Also\n     |      --------\n     |      remove_callback\n     |  \n     |  convert_xunits(self, x)\n     |      Convert *x* using the unit type of the xaxis.\n     |      \n     |      If the artist is not in contained in an Axes or if the xaxis does not\n     |      have units, *x* itself is returned.\n     |  \n     |  convert_yunits(self, y)\n     |      Convert *y* using the unit type of the yaxis.\n     |      \n     |      If the artist is not in contained in an Axes or if the yaxis does not\n     |      have units, *y* itself is returned.\n     |  \n     |  findobj(self, match=None, include_self=True)\n     |      Find artist objects.\n     |      \n     |      Recursively find all `.Artist` instances contained in the artist.\n     |      \n     |      Parameters\n     |      ----------\n     |      match\n     |          A filter criterion for the matches. This can be\n     |      \n     |          - *None*: Return all objects contained in artist.\n     |          - A function with signature ``def match(artist: Artist) -> bool``.\n     |            The result will only contain artists for which the function\n     |            returns *True*.\n     |          - A class instance: e.g., `.Line2D`. The result will only contain\n     |            artists of this class or its subclasses (``isinstance`` check).\n     |      \n     |      include_self : bool\n     |          Include *self* in the list to be checked for a match.\n     |      \n     |      Returns\n     |      -------\n     |      list of `.Artist`\n     |  \n     |  format_cursor_data(self, data)\n     |      Return a string representation of *data*.\n     |      \n     |      .. note::\n     |          This method is intended to be overridden by artist subclasses.\n     |          As an end-user of Matplotlib you will most likely not call this\n     |          method yourself.\n     |      \n     |      The default implementation converts ints and floats and arrays of ints\n     |      and floats into a comma-separated string enclosed in square brackets.\n     |      \n     |      See Also\n     |      --------\n     |      get_cursor_data\n     |  \n     |  get_agg_filter(self)\n     |      Return filter function to be used for agg filter.\n     |  \n     |  get_alpha(self)\n     |      Return the alpha value used for blending - not supported on all\n     |      backends.\n     |  \n     |  get_animated(self)\n     |      Return whether the artist is animated.\n     |  \n     |  get_children(self)\n     |      Return a list of the child `.Artist`\\s of this `.Artist`.\n     |  \n     |  get_clip_box(self)\n     |      Return the clipbox.\n     |  \n     |  get_clip_on(self)\n     |      Return whether the artist uses clipping.\n     |  \n     |  get_clip_path(self)\n     |      Return the clip path.\n     |  \n     |  get_contains(self)\n     |      [*Deprecated*] Return the custom contains function of the artist if set, or *None*.\n     |      \n     |      See Also\n     |      --------\n     |      set_contains\n     |      \n     |      Notes\n     |      -----\n     |      .. deprecated:: 3.3\n     |  \n     |  get_cursor_data(self, event)\n     |      Return the cursor data for a given event.\n     |      \n     |      .. note::\n     |          This method is intended to be overridden by artist subclasses.\n     |          As an end-user of Matplotlib you will most likely not call this\n     |          method yourself.\n     |      \n     |      Cursor data can be used by Artists to provide additional context\n     |      information for a given event. The default implementation just returns\n     |      *None*.\n     |      \n     |      Subclasses can override the method and return arbitrary data. However,\n     |      when doing so, they must ensure that `.format_cursor_data` can convert\n     |      the data to a string representation.\n     |      \n     |      The only current use case is displaying the z-value of an `.AxesImage`\n     |      in the status bar of a plot window, while moving the mouse.\n     |      \n     |      Parameters\n     |      ----------\n     |      event : `matplotlib.backend_bases.MouseEvent`\n     |      \n     |      See Also\n     |      --------\n     |      format_cursor_data\n     |  \n     |  get_figure(self)\n     |      Return the `.Figure` instance the artist belongs to.\n     |  \n     |  get_gid(self)\n     |      Return the group id.\n     |  \n     |  get_in_layout(self)\n     |      Return boolean flag, ``True`` if artist is included in layout\n     |      calculations.\n     |      \n     |      E.g. :doc:`/tutorials/intermediate/constrainedlayout_guide`,\n     |      `.Figure.tight_layout()`, and\n     |      ``fig.savefig(fname, bbox_inches='tight')``.\n     |  \n     |  get_label(self)\n     |      Return the label used for this artist in the legend.\n     |  \n     |  get_path_effects(self)\n     |  \n     |  get_picker(self)\n     |      Return the picking behavior of the artist.\n     |      \n     |      The possible values are described in `.set_picker`.\n     |      \n     |      See Also\n     |      --------\n     |      set_picker, pickable, pick\n     |  \n     |  get_rasterized(self)\n     |      Return whether the artist is to be rasterized.\n     |  \n     |  get_sketch_params(self)\n     |      Return the sketch parameters for the artist.\n     |      \n     |      Returns\n     |      -------\n     |      tuple or None\n     |      \n     |          A 3-tuple with the following elements:\n     |      \n     |          - *scale*: The amplitude of the wiggle perpendicular to the\n     |            source line.\n     |          - *length*: The length of the wiggle along the line.\n     |          - *randomness*: The scale factor by which the length is\n     |            shrunken or expanded.\n     |      \n     |          Returns *None* if no sketch parameters were set.\n     |  \n     |  get_snap(self)\n     |      Return the snap setting.\n     |      \n     |      See `.set_snap` for details.\n     |  \n     |  get_tightbbox(self, renderer)\n     |      Like `.Artist.get_window_extent`, but includes any clipping.\n     |      \n     |      Parameters\n     |      ----------\n     |      renderer : `.RendererBase` subclass\n     |          renderer that will be used to draw the figures (i.e.\n     |          ``fig.canvas.get_renderer()``)\n     |      \n     |      Returns\n     |      -------\n     |      `.Bbox`\n     |          The enclosing bounding box (in figure pixel coordinates).\n     |  \n     |  get_transformed_clip_path_and_affine(self)\n     |      Return the clip path with the non-affine part of its\n     |      transformation applied, and the remaining affine part of its\n     |      transformation.\n     |  \n     |  get_url(self)\n     |      Return the url.\n     |  \n     |  get_visible(self)\n     |      Return the visibility.\n     |  \n     |  get_zorder(self)\n     |      Return the artist's zorder.\n     |  \n     |  have_units(self)\n     |      Return *True* if units are set on any axis.\n     |  \n     |  is_transform_set(self)\n     |      Return whether the Artist has an explicitly set transform.\n     |      \n     |      This is *True* after `.set_transform` has been called.\n     |  \n     |  pchanged(self)\n     |      Call all of the registered callbacks.\n     |      \n     |      This function is triggered internally when a property is changed.\n     |      \n     |      See Also\n     |      --------\n     |      add_callback\n     |      remove_callback\n     |  \n     |  pick(self, mouseevent)\n     |      Process a pick event.\n     |      \n     |      Each child artist will fire a pick event if *mouseevent* is over\n     |      the artist and the artist has picker set.\n     |      \n     |      See Also\n     |      --------\n     |      set_picker, get_picker, pickable\n     |  \n     |  pickable(self)\n     |      Return whether the artist is pickable.\n     |      \n     |      See Also\n     |      --------\n     |      set_picker, get_picker, pick\n     |  \n     |  properties(self)\n     |      Return a dictionary of all the properties of the artist.\n     |  \n     |  remove(self)\n     |      Remove the artist from the figure if possible.\n     |      \n     |      The effect will not be visible until the figure is redrawn, e.g.,\n     |      with `.FigureCanvasBase.draw_idle`.  Call `~.axes.Axes.relim` to\n     |      update the axes limits if desired.\n     |      \n     |      Note: `~.axes.Axes.relim` will not see collections even if the\n     |      collection was added to the axes with *autolim* = True.\n     |      \n     |      Note: there is no support for removing the artist's legend entry.\n     |  \n     |  remove_callback(self, oid)\n     |      Remove a callback based on its observer id.\n     |      \n     |      See Also\n     |      --------\n     |      add_callback\n     |  \n     |  set(self, **kwargs)\n     |      A property batch setter.  Pass *kwargs* to set properties.\n     |  \n     |  set_agg_filter(self, filter_func)\n     |      Set the agg filter.\n     |      \n     |      Parameters\n     |      ----------\n     |      filter_func : callable\n     |          A filter function, which takes a (m, n, 3) float array and a dpi\n     |          value, and returns a (m, n, 3) array.\n     |      \n     |          .. ACCEPTS: a filter function, which takes a (m, n, 3) float array\n     |              and a dpi value, and returns a (m, n, 3) array\n     |  \n     |  set_animated(self, b)\n     |      Set the artist's animation state.\n     |      \n     |      Parameters\n     |      ----------\n     |      b : bool\n     |  \n     |  set_clip_box(self, clipbox)\n     |      Set the artist's clip `.Bbox`.\n     |      \n     |      Parameters\n     |      ----------\n     |      clipbox : `.Bbox`\n     |  \n     |  set_clip_on(self, b)\n     |      Set whether the artist uses clipping.\n     |      \n     |      When False artists will be visible outside of the axes which\n     |      can lead to unexpected results.\n     |      \n     |      Parameters\n     |      ----------\n     |      b : bool\n     |  \n     |  set_clip_path(self, path, transform=None)\n     |      Set the artist's clip path.\n     |      \n     |      Parameters\n     |      ----------\n     |      path : `.Patch` or `.Path` or `.TransformedPath` or None\n     |          The clip path. If given a `.Path`, *transform* must be provided as\n     |          well. If *None*, a previously set clip path is removed.\n     |      transform : `~matplotlib.transforms.Transform`, optional\n     |          Only used if *path* is a `.Path`, in which case the given `.Path`\n     |          is converted to a `.TransformedPath` using *transform*.\n     |      \n     |      Notes\n     |      -----\n     |      For efficiency, if *path* is a `.Rectangle` this method will set the\n     |      clipping box to the corresponding rectangle and set the clipping path\n     |      to ``None``.\n     |      \n     |      For technical reasons (support of `~.Artist.set`), a tuple\n     |      (*path*, *transform*) is also accepted as a single positional\n     |      parameter.\n     |      \n     |      .. ACCEPTS: Patch or (Path, Transform) or None\n     |  \n     |  set_contains(self, picker)\n     |      [*Deprecated*] Define a custom contains test for the artist.\n     |      \n     |      The provided callable replaces the default `.contains` method\n     |      of the artist.\n     |      \n     |      Parameters\n     |      ----------\n     |      picker : callable\n     |          A custom picker function to evaluate if an event is within the\n     |          artist. The function must have the signature::\n     |      \n     |              def contains(artist: Artist, event: MouseEvent) -> bool, dict\n     |      \n     |          that returns:\n     |      \n     |          - a bool indicating if the event is within the artist\n     |          - a dict of additional information. The dict should at least\n     |            return the same information as the default ``contains()``\n     |            implementation of the respective artist, but may provide\n     |            additional information.\n     |      \n     |      Notes\n     |      -----\n     |      .. deprecated:: 3.3\n     |  \n     |  set_figure(self, fig)\n     |      Set the `.Figure` instance the artist belongs to.\n     |      \n     |      Parameters\n     |      ----------\n     |      fig : `.Figure`\n     |  \n     |  set_gid(self, gid)\n     |      Set the (group) id for the artist.\n     |      \n     |      Parameters\n     |      ----------\n     |      gid : str\n     |  \n     |  set_in_layout(self, in_layout)\n     |      Set if artist is to be included in layout calculations,\n     |      E.g. :doc:`/tutorials/intermediate/constrainedlayout_guide`,\n     |      `.Figure.tight_layout()`, and\n     |      ``fig.savefig(fname, bbox_inches='tight')``.\n     |      \n     |      Parameters\n     |      ----------\n     |      in_layout : bool\n     |  \n     |  set_label(self, s)\n     |      Set a label that will be displayed in the legend.\n     |      \n     |      Parameters\n     |      ----------\n     |      s : object\n     |          *s* will be converted to a string by calling `str`.\n     |  \n     |  set_path_effects(self, path_effects)\n     |      Set the path effects.\n     |      \n     |      Parameters\n     |      ----------\n     |      path_effects : `.AbstractPathEffect`\n     |  \n     |  set_picker(self, picker)\n     |      Define the picking behavior of the artist.\n     |      \n     |      Parameters\n     |      ----------\n     |      picker : None or bool or callable\n     |          This can be one of the following:\n     |      \n     |          - *None*: Picking is disabled for this artist (default).\n     |      \n     |          - A boolean: If *True* then picking will be enabled and the\n     |            artist will fire a pick event if the mouse event is over\n     |            the artist.\n     |      \n     |          - A function: If picker is callable, it is a user supplied\n     |            function which determines whether the artist is hit by the\n     |            mouse event::\n     |      \n     |              hit, props = picker(artist, mouseevent)\n     |      \n     |            to determine the hit test.  if the mouse event is over the\n     |            artist, return *hit=True* and props is a dictionary of\n     |            properties you want added to the PickEvent attributes.\n     |      \n     |          - *deprecated*: For `.Line2D` only, *picker* can also be a float\n     |            that sets the tolerance for checking whether an event occurred\n     |            \"on\" the line; this is deprecated.  Use `.Line2D.set_pickradius`\n     |            instead.\n     |  \n     |  set_rasterized(self, rasterized)\n     |      Force rasterized (bitmap) drawing in vector backend output.\n     |      \n     |      Defaults to None, which implies the backend's default behavior.\n     |      \n     |      Parameters\n     |      ----------\n     |      rasterized : bool or None\n     |  \n     |  set_sketch_params(self, scale=None, length=None, randomness=None)\n     |      Sets the sketch parameters.\n     |      \n     |      Parameters\n     |      ----------\n     |      scale : float, optional\n     |          The amplitude of the wiggle perpendicular to the source\n     |          line, in pixels.  If scale is `None`, or not provided, no\n     |          sketch filter will be provided.\n     |      length : float, optional\n     |           The length of the wiggle along the line, in pixels\n     |           (default 128.0)\n     |      randomness : float, optional\n     |          The scale factor by which the length is shrunken or\n     |          expanded (default 16.0)\n     |      \n     |          .. ACCEPTS: (scale: float, length: float, randomness: float)\n     |  \n     |  set_snap(self, snap)\n     |      Set the snapping behavior.\n     |      \n     |      Snapping aligns positions with the pixel grid, which results in\n     |      clearer images. For example, if a black line of 1px width was\n     |      defined at a position in between two pixels, the resulting image\n     |      would contain the interpolated value of that line in the pixel grid,\n     |      which would be a grey value on both adjacent pixel positions. In\n     |      contrast, snapping will move the line to the nearest integer pixel\n     |      value, so that the resulting image will really contain a 1px wide\n     |      black line.\n     |      \n     |      Snapping is currently only supported by the Agg and MacOSX backends.\n     |      \n     |      Parameters\n     |      ----------\n     |      snap : bool or None\n     |          Possible values:\n     |      \n     |          - *True*: Snap vertices to the nearest pixel center.\n     |          - *False*: Do not modify vertex positions.\n     |          - *None*: (auto) If the path contains only rectilinear line\n     |            segments, round to the nearest pixel center.\n     |  \n     |  set_transform(self, t)\n     |      Set the artist transform.\n     |      \n     |      Parameters\n     |      ----------\n     |      t : `.Transform`\n     |  \n     |  set_url(self, url)\n     |      Set the url for the artist.\n     |      \n     |      Parameters\n     |      ----------\n     |      url : str\n     |  \n     |  set_visible(self, b)\n     |      Set the artist's visibility.\n     |      \n     |      Parameters\n     |      ----------\n     |      b : bool\n     |  \n     |  set_zorder(self, level)\n     |      Set the zorder for the artist.  Artists with lower zorder\n     |      values are drawn first.\n     |      \n     |      Parameters\n     |      ----------\n     |      level : float\n     |  \n     |  update(self, props)\n     |      Update this artist's properties from the dict *props*.\n     |      \n     |      Parameters\n     |      ----------\n     |      props : dict\n     |  \n     |  ----------------------------------------------------------------------\n     |  Readonly properties inherited from matplotlib.artist.Artist:\n     |  \n     |  sticky_edges\n     |      ``x`` and ``y`` sticky edge lists for autoscaling.\n     |      \n     |      When performing autoscaling, if a data limit coincides with a value in\n     |      the corresponding sticky_edges list, then no margin will be added--the\n     |      view limit \"sticks\" to the edge. A typical use case is histograms,\n     |      where one usually expects no margin on the bottom edge (0) of the\n     |      histogram.\n     |      \n     |      This attribute cannot be assigned to; however, the ``x`` and ``y``\n     |      lists can be modified in place as needed.\n     |      \n     |      Examples\n     |      --------\n     |      >>> artist.sticky_edges.x[:] = (xmin, xmax)\n     |      >>> artist.sticky_edges.y[:] = (ymin, ymax)\n     |  \n     |  ----------------------------------------------------------------------\n     |  Data descriptors inherited from matplotlib.artist.Artist:\n     |  \n     |  __dict__\n     |      dictionary for instance variables (if defined)\n     |  \n     |  __weakref__\n     |      list of weak references to the object (if defined)\n     |  \n     |  axes\n     |      The `~.axes.Axes` instance the artist resides in, or *None*.\n     |  \n     |  mouseover\n     |      If this property is set to *True*, the artist will be queried for\n     |      custom context information when the mouse cursor moves over it.\n     |      \n     |      See also :meth:`get_cursor_data`, :class:`.ToolCursorPosition` and\n     |      :class:`.NavigationToolbar2`.\n     |  \n     |  stale\n     |      Whether the artist is 'stale' and needs to be re-drawn for the output\n     |      to match the internal state of the artist.\n    \n\n\n\n```python\nnp.random.seed(2016)\ndata = np.random.rand(12,20)\nh, w = data.shape\ntheta, z = np.linspace(0, 2 * np.pi, w), np.linspace(0, 1, h)\nTHETA, Z = np.meshgrid(theta, z)\nX = np.cos(THETA)\nY = np.sin(THETA)\nfig = plt.figure()\nax = fig.add_subplot(1,1,1, projection='3d')\ncmap = plt.get_cmap('bwr')\nplot = ax.plot_surface(X,Y,Z, rstride=1, cstride=1,\n#                        facecolors=cmap(data),\n                       linewidth=0,\n                       antialiased=False,\n                       alpha=0.75)\nplt.show()\n```\n\n\n```python\nhelp(np.meshgrid)\n```\n\n    Help on function meshgrid in module numpy:\n    \n    meshgrid(*xi, **kwargs)\n        Return coordinate matrices from coordinate vectors.\n        \n        Make N-D coordinate arrays for vectorized evaluations of\n        N-D scalar/vector fields over N-D grids, given\n        one-dimensional coordinate arrays x1, x2,..., xn.\n        \n        .. versionchanged:: 1.9\n           1-D and 0-D cases are allowed.\n        \n        Parameters\n        ----------\n        x1, x2,..., xn : array_like\n            1-D arrays representing the coordinates of a grid.\n        indexing : {'xy', 'ij'}, optional\n            Cartesian ('xy', default) or matrix ('ij') indexing of output.\n            See Notes for more details.\n        \n            .. versionadded:: 1.7.0\n        sparse : bool, optional\n            If True a sparse grid is returned in order to conserve memory.\n            Default is False.\n        \n            .. versionadded:: 1.7.0\n        copy : bool, optional\n            If False, a view into the original arrays are returned in order to\n            conserve memory.  Default is True.  Please note that\n            ``sparse=False, copy=False`` will likely return non-contiguous\n            arrays.  Furthermore, more than one element of a broadcast array\n            may refer to a single memory location.  If you need to write to the\n            arrays, make copies first.\n        \n            .. versionadded:: 1.7.0\n        \n        Returns\n        -------\n        X1, X2,..., XN : ndarray\n            For vectors `x1`, `x2`,..., 'xn' with lengths ``Ni=len(xi)`` ,\n            return ``(N1, N2, N3,...Nn)`` shaped arrays if indexing='ij'\n            or ``(N2, N1, N3,...Nn)`` shaped arrays if indexing='xy'\n            with the elements of `xi` repeated to fill the matrix along\n            the first dimension for `x1`, the second for `x2` and so on.\n        \n        Notes\n        -----\n        This function supports both indexing conventions through the indexing\n        keyword argument.  Giving the string 'ij' returns a meshgrid with\n        matrix indexing, while 'xy' returns a meshgrid with Cartesian indexing.\n        In the 2-D case with inputs of length M and N, the outputs are of shape\n        (N, M) for 'xy' indexing and (M, N) for 'ij' indexing.  In the 3-D case\n        with inputs of length M, N and P, outputs are of shape (N, M, P) for\n        'xy' indexing and (M, N, P) for 'ij' indexing.  The difference is\n        illustrated by the following code snippet::\n        \n            xv, yv = np.meshgrid(x, y, sparse=False, indexing='ij')\n            for i in range(nx):\n                for j in range(ny):\n                    # treat xv[i,j], yv[i,j]\n        \n            xv, yv = np.meshgrid(x, y, sparse=False, indexing='xy')\n            for i in range(nx):\n                for j in range(ny):\n                    # treat xv[j,i], yv[j,i]\n        \n        In the 1-D and 0-D case, the indexing and sparse keywords have no effect.\n        \n        See Also\n        --------\n        index_tricks.mgrid : Construct a multi-dimensional \"meshgrid\"\n                         using indexing notation.\n        index_tricks.ogrid : Construct an open multi-dimensional \"meshgrid\"\n                         using indexing notation.\n        \n        Examples\n        --------\n        >>> nx, ny = (3, 2)\n        >>> x = np.linspace(0, 1, nx)\n        >>> y = np.linspace(0, 1, ny)\n        >>> xv, yv = np.meshgrid(x, y)\n        >>> xv\n        array([[0. , 0.5, 1. ],\n               [0. , 0.5, 1. ]])\n        >>> yv\n        array([[0.,  0.,  0.],\n               [1.,  1.,  1.]])\n        >>> xv, yv = np.meshgrid(x, y, sparse=True)  # make sparse output arrays\n        >>> xv\n        array([[0. ,  0.5,  1. ]])\n        >>> yv\n        array([[0.],\n               [1.]])\n        \n        `meshgrid` is very useful to evaluate functions on a grid.\n        \n        >>> import matplotlib.pyplot as plt\n        >>> x = np.arange(-5, 5, 0.1)\n        >>> y = np.arange(-5, 5, 0.1)\n        >>> xx, yy = np.meshgrid(x, y, sparse=True)\n        >>> z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)\n        >>> h = plt.contourf(x,y,z)\n        >>> plt.show()\n    \n\n\n\n```python\n\n```\n", "meta": {"hexsha": "7d43f9b6715ae702410a579a5ae59062b3caa0d5", "size": 334481, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "gcv/notes/cylinders.ipynb", "max_stars_repo_name": "fuzzyklein/gcv-lab", "max_stars_repo_head_hexsha": "9d2c552b8226350dd6f4d5c38a42d1b90d3c3ca7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gcv/notes/cylinders.ipynb", "max_issues_repo_name": "fuzzyklein/gcv-lab", "max_issues_repo_head_hexsha": "9d2c552b8226350dd6f4d5c38a42d1b90d3c3ca7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gcv/notes/cylinders.ipynb", "max_forks_repo_name": "fuzzyklein/gcv-lab", "max_forks_repo_head_hexsha": "9d2c552b8226350dd6f4d5c38a42d1b90d3c3ca7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.9814310051, "max_line_length": 61612, "alphanum_fraction": 0.6103246522, "converted": true, "num_tokens": 41725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.07159119894934293, "lm_q1q2_score": 0.035795599474671466}}
{"text": "# Assignment 4: Chatbot\n\n \n\nWelcome to the last assignment of Course 4. Before you get started, we want to congratulate you on getting here. It is your 16th programming assignment in this Specialization and we are very proud of you! In this assignment, you are going to use the [Reformer](https://arxiv.org/abs/2001.04451), also known as the efficient Transformer, to generate a dialogue between two bots. You will feed conversations to your model and it will learn how to understand the context of each one. Not only will it learn how to answer questions but it will also know how to ask questions if it needs more info. For example, after a customer asks for a train ticket, the chatbot can ask what time the said customer wants to leave. You can use this concept to automate call centers, hotel receptions, personal trainers, or any type of customer service. By completing this assignment, you will:\n\n* Understand how the Reformer works\n* Explore the [MultiWoz](https://arxiv.org/abs/1810.00278) dataset\n* Process the data to feed it into the model\n* Train your model\n* Generate a dialogue by feeding a question to the model\n\n\n## Outline\n- [Part 1:   Exploring the MultiWoz dataset](#1)\n\t- [Exercise 01](#ex01)\n- [Part 2:   Processing the data for Reformer inputs](#2)\n    - [2.1   Tokenizing, batching with bucketing](#2.1)\n- [Part 3:   Reversible layers](#3)\n\t- [Exercise 02](#ex02)\n\t- [Exercise 03](#ex03)\n    - [3.1   Reversible layers and randomness](#3.1)\n- [Part 4:   ReformerLM Training](#4)\n\t- [Exercise 04](#ex04)\n\t- [Exercise 05](#ex05)\n- [Part 5:   Decode from a pretrained model](#5)\n\t- [Exercise 06](#ex06)\n\n\n<a name=\"1\"></a>\n# Part 1:   Exploring the MultiWoz dataset\n\nYou will start by exploring the MultiWoz dataset. The dataset you are about to use has more than 10,000 human annotated dialogues and spans multiple domains and topics. Some dialogues include multiple domains and others include single domains. In this section, you will load and explore this dataset, as well as develop a function to extract the dialogues.\n\nLet's first import the modules we will be using:\n\n\n```python\nimport json\nimport random\nimport numpy as np\nfrom termcolor import colored\n\nimport trax   \nfrom trax import layers as tl\nfrom trax.supervised import training\n!pip list | grep trax\n```\n\n    INFO:tensorflow:tokens_length=568 inputs_length=512 targets_length=114 noise_density=0.15 mean_noise_span_length=3.0 \n    trax                     1.3.4\n    \u001b[33mWARNING: You are using pip version 20.1.1; however, version 20.2.3 is available.\n    You should consider upgrading via the '/opt/conda/bin/python3 -m pip install --upgrade pip' command.\u001b[0m\n\n\nLet's also declare some constants we will be using in the exercises.\n\n\n```python\n# filename of the MultiWOZ dialogue dataset\nDATA_FILE = 'data.json'\n\n# data directory\nDATA_DIR = './data'\n\n# dictionary where we will load the dialogue dataset\nDIALOGUE_DB = {}\n\n# vocabulary filename\nVOCAB_FILE = 'en_32k.subword'\n\n# vocabulary file directory\nVOCAB_DIR = 'data/vocabs'\n```\n\nLet's now load the MultiWOZ 2.1 dataset. We have already provided it for you in your workspace. It is in JSON format so we should load it as such:\n\n\n```python\n# help function to load a JSON file\ndef load_json(directory, file):\n    with open(f'{directory}/{file}') as file: \n        db = json.load(file)\n    return db\n\n# load the dialogue data set into our dictionary\nDIALOGUE_DB = load_json(DATA_DIR, DATA_FILE)\n```\n\nLet's see how many dialogues we have in the dictionary. 1 key-value pair is one dialogue so we can just get the dictionary's length.\n\n\n```python\nprint(f'The number of dialogues is: {len(DIALOGUE_DB)}')\n```\n\n    The number of dialogues is: 10438\n\n\nThe dialogues are composed of multiple files and the filenames are used as keys in our dictionary. Those with multi-domain dialogues have \"MUL\" in their filenames while single domain dialogues have either \"SNG\" or \"WOZ\".\n\n\n```python\n# print 7 keys from the dataset to see the filenames\nprint(list(DIALOGUE_DB.keys())[0:7]) \n```\n\n    ['SNG01856.json', 'SNG0129.json', 'PMUL1635.json', 'MUL2168.json', 'SNG0073.json', 'SNG01445.json', 'MUL2105.json']\n\n\nAs you can see from the cells above, there are 10,438 conversations, each in its own file.  You will train your model on all those conversations. Each file is also loaded into a dictionary and each has two keys which are the following:\n\n\n```python\n# get keys of the fifth file in the list above\nprint(DIALOGUE_DB['SNG0073.json'].keys())\n```\n\n    dict_keys(['goal', 'log'])\n\n\nThe `goal` also points to a dictionary and it contains several keys pertaining to the objectives of the conversation. For example below, we can see that the conversation will be about booking a taxi.\n\n\n```python\nDIALOGUE_DB['SNG0073.json']['goal']\n```\n\n\n\n\n    {'taxi': {'info': {'leaveAt': '17:15',\n       'destination': 'pizza hut fen ditton',\n       'departure': \"saint john's college\"},\n      'reqt': ['car type', 'phone'],\n      'fail_info': {}},\n     'police': {},\n     'hospital': {},\n     'hotel': {},\n     'attraction': {},\n     'train': {},\n     'message': [\"You want to book a <span class='emphasis'>taxi</span>. The taxi should go to <span class='emphasis'>pizza hut fen ditton</span> and should depart from <span class='emphasis'>saint john's college</span>\",\n      \"The taxi should <span class='emphasis'>leave after 17:15</span>\",\n      \"Make sure you get <span class='emphasis'>car type</span> and <span class='emphasis'>contact number</span>\"],\n     'restaurant': {}}\n\n\n\nThe `log` on the other hand contains the dialog. It is a list of dictionaries and each element of this list contains several descriptions as well. Let's look at an example:\n\n\n```python\n# get first element of the log list\nDIALOGUE_DB['SNG0073.json']['log'][0]\n```\n\n\n\n\n    {'text': \"I would like a taxi from Saint John's college to Pizza Hut Fen Ditton.\",\n     'metadata': {},\n     'dialog_act': {'Taxi-Inform': [['Dest', 'pizza hut fen ditton'],\n       ['Depart', \"saint john 's college\"]]},\n     'span_info': [['Taxi-Inform', 'Dest', 'pizza hut fen ditton', 11, 14],\n      ['Taxi-Inform', 'Depart', \"saint john 's college\", 6, 9]]}\n\n\n\nFor this assignment, we are only interested in the conversation which is in the `text` field.\nThe conversation goes back and forth between two persons. Let's call them 'Person 1' and 'Person 2'. This implies that\ndata['SNG0073.json']['log'][0]['text'] is 'Person 1' and\ndata['SNG0073.json']['log'][1]['text'] is 'Person 2' and so on. The even offsets are 'Person 1' and the odd offsets are 'Person 2'.\n\n\n```python\nprint(' Person 1: ', DIALOGUE_DB['SNG0073.json']['log'][0]['text'])\nprint(' Person 2: ',DIALOGUE_DB['SNG0073.json']['log'][1]['text'])\n```\n\n     Person 1:  I would like a taxi from Saint John's college to Pizza Hut Fen Ditton.\n     Person 2:  What time do you want to leave and what time do you want to arrive by?\n\n\n<a name=\"ex01\"></a>\n### Exercise 01\n\nYou will now implement the `get_conversation()` function that will extract the conversations from the dataset's file.\n\n**Instructions:** Implement a function to extract conversations from the input file.   \nAs described above, the conversation is in the `text` field in each of the elements in the `log` list of the file. If the log list has `x` number of elements, then the function will get the `text` entries of each of those elements. Your function should return the conversation, prepending each field with either ' Person 1: ' if 'x' is even or ' Person 2: ' if 'x' is odd. You can use the Python modulus operator '%' to help select the even/odd entries. Important note: Do not print a newline character (i.e. `\\n`) when generating the string. For example, in the code cell above, your function should output something like:\n\n```\n Person 1: I would like a taxi from Saint John's college to Pizza Hut Fen Ditton. Person 2: What time do you want to leave and what time do you want to arrive by?\n```\n\nand **not**:\n\n```\n Person 1:  I would like a taxi from Saint John's college to Pizza Hut Fen Ditton.\n Person 2:  What time do you want to leave and what time do you want to arrive by?\n```\n\n\n```python\n# UNQ_C1\n# GRADED FUNCTION: get_conversation\ndef get_conversation(file, data_db):\n    '''\n    Args:\n        file (string): filename of the dialogue file saved as json\n        data_db (dict): dialogue database\n    \n    Returns:\n        string: A string containing the 'text' fields of  data[file]['log'][x]\n    '''\n    \n    # initialize empty string\n    result = ''\n    \n    # get length of file's log list\n    len_msg_log = len(data_db[file]['log'])\n    \n    # set the delimiter strings\n    delimiter_1 = ' Person 1: '\n    delimiter_2 = ' Person 2: '\n    \n    # loop over the file's log list\n    for i in range(len_msg_log):\n        \n    ### START CODE HERE (REPLACE INSTANCES OF 'None' WITH YOUR CODE) ###\n    \n        # get i'th element of file log list\n        cur_log = data_db[file]['log'][i]\n        \n        # check if i is even\n        if i%2 == 0:                   \n            # append the 1st delimiter string\n            result += delimiter_1\n        else: \n            # append the 2nd delimiter string\n            result += delimiter_2\n        \n        # append the message text from the log\n        result += cur_log['text']\n    \n    ### END CODE HERE ###\n\n    return result\n```\n\n\n```python\n# BEGIN UNIT TEST\nimport w4_unittest\nw4_unittest.test_get_conversation(get_conversation)\n# END UNIT TEST\n```\n\n    \u001b[92m All tests passed\n\n\n\n```python\nfile = 'SNG01856.json'\nconversation = get_conversation(file, DIALOGUE_DB)\n\n# print raw output\nprint(conversation)\n```\n\n     Person 1: am looking for a place to to stay that has cheap price range it should be in a type of hotel Person 2: Okay, do you have a specific area you want to stay in? Person 1: no, i just need to make sure it's cheap. oh, and i need parking Person 2: I found 1 cheap hotel for you that includes parking. Do you like me to book it? Person 1: Yes, please. 6 people 3 nights starting on tuesday. Person 2: I am sorry but I wasn't able to book that for you for Tuesday. Is there another day you would like to stay or perhaps a shorter stay? Person 1: how about only 2 nights. Person 2: Booking was successful.\n    Reference number is : 7GAWK763. Anything else I can do for you? Person 1: No, that will be all. Good bye. Person 2: Thank you for using our services.\n\n\n**Expected Result:**\n```\nPerson 1: am looking for a place to to stay that has cheap price range it should be in a type of hotel Person 2: Okay, do you have a specific area you want to stay in? Person 1: no, i just need to make sure it's cheap. oh, and i need parking Person 2: I found 1 cheap hotel for you that includes parking. Do you like me to book it? Person 1: Yes, please. 6 people 3 nights starting on tuesday. Person 2: I am sorry but I wasn't able to book that for you for Tuesday. Is there another day you would like to stay or perhaps a shorter stay? Person 1: how about only 2 nights. Person 2: Booking was successful.\nReference number is : 7GAWK763. Anything else I can do for you? Person 1: No, that will be all. Good bye. Person 2: Thank you for using our services.\n```\n\nWe can have a utility pretty print function just so we can visually follow the conversation more easily.\n\n\n```python\ndef print_conversation(conversation):\n    \n    delimiter_1 = 'Person 1: '\n    delimiter_2 = 'Person 2: '\n    \n    split_list_d1 = conversation.split(delimiter_1)\n    \n    for sublist in split_list_d1[1:]:\n        split_list_d2 = sublist.split(delimiter_2)\n        print(colored(f'Person 1: {split_list_d2[0]}', 'red'))\n        \n        if len(split_list_d2) > 1:\n            print(colored(f'Person 2: {split_list_d2[1]}', 'green'))\n\n            \nprint_conversation(conversation)\n```\n\n    \u001b[31mPerson 1: am looking for a place to to stay that has cheap price range it should be in a type of hotel \u001b[0m\n    \u001b[32mPerson 2: Okay, do you have a specific area you want to stay in? \u001b[0m\n    \u001b[31mPerson 1: no, i just need to make sure it's cheap. oh, and i need parking \u001b[0m\n    \u001b[32mPerson 2: I found 1 cheap hotel for you that includes parking. Do you like me to book it? \u001b[0m\n    \u001b[31mPerson 1: Yes, please. 6 people 3 nights starting on tuesday. \u001b[0m\n    \u001b[32mPerson 2: I am sorry but I wasn't able to book that for you for Tuesday. Is there another day you would like to stay or perhaps a shorter stay? \u001b[0m\n    \u001b[31mPerson 1: how about only 2 nights. \u001b[0m\n    \u001b[32mPerson 2: Booking was successful.\n    Reference number is : 7GAWK763. Anything else I can do for you? \u001b[0m\n    \u001b[31mPerson 1: No, that will be all. Good bye. \u001b[0m\n    \u001b[32mPerson 2: Thank you for using our services.\u001b[0m\n\n\nFor this assignment, we will just use the outputs of the calls to `get_conversation` to train the model. But just to expound, there are also other information in the MultiWoz dataset that can be useful in other contexts. Each element of the log list has more information about it. For example, above, if you were to look at the other fields for the following, \"am looking for a place to stay that has cheap price range it should be in a type of hotel\", you will get the following. \n\n\n```python\nDIALOGUE_DB['SNG01856.json']['log'][0]\n```\n\n\n\n\n    {'text': 'am looking for a place to to stay that has cheap price range it should be in a type of hotel',\n     'metadata': {},\n     'dialog_act': {'Hotel-Inform': [['Type', 'hotel'], ['Price', 'cheap']]},\n     'span_info': [['Hotel-Inform', 'Type', 'hotel', 20, 20],\n      ['Hotel-Inform', 'Price', 'cheap', 10, 10]]}\n\n\n\nThe dataset also comes with hotel, hospital, taxi, train, police, and restaurant databases. For example, in case you need to call a doctor, or a hotel, or a taxi, this will allow you to automate the entire conversation. Take a look at the files accompanying the data set.\n\n\n```python\n# this is an example of the attractions file\nattraction_file = open('data/attraction_db.json')\nattractions = json.load(attraction_file)\nprint(attractions[0])\n```\n\n    {'address': 'pool way, whitehill road, off newmarket road', 'area': 'east', 'entrance fee': '?', 'id': '1', 'location': [52.208789, 0.154883], 'name': 'abbey pool and astroturf pitch', 'openhours': '?', 'phone': '01223902088', 'postcode': 'cb58nt', 'pricerange': '?', 'type': 'swimmingpool'}\n\n\n\n```python\n# this is an example of the hospital file\nhospital_file = open('data/hospital_db.json')\nhospitals = json.load(hospital_file)\nprint(hospitals[0]) # feel free to index into other indices\n```\n\n    {'department': 'neurosciences critical care unit', 'id': 0, 'phone': '01223216297'}\n\n\n\n```python\n# this is an example of the hotel file\nhotel_file = open('data/hotel_db.json')\nhotels = json.load(hotel_file)\nprint(hotels[0]) # feel free to index into other indices\n```\n\n    {'address': '124 tenison road', 'area': 'east', 'internet': 'yes', 'parking': 'no', 'id': '0', 'location': [52.1963733, 0.1987426], 'name': 'a and b guest house', 'phone': '01223315702', 'postcode': 'cb12dp', 'price': {'double': '70', 'family': '90', 'single': '50'}, 'pricerange': 'moderate', 'stars': '4', 'takesbookings': 'yes', 'type': 'guesthouse'}\n\n\n\n```python\n# this is an example of the police file\npolice_file = open('data/police_db.json')\npolice = json.load(police_file)\nprint(police[0]) # feel free to index into other indices\n```\n\n    {'name': 'Parkside Police Station', 'address': 'Parkside, Cambridge', 'id': 0, 'phone': '01223358966'}\n\n\n\n```python\n# this is an example of a restuarant file\nrestaurant_file = open('data/restaurant_db.json')\nrestaurants = json.load(restaurant_file)\nprint(restaurants[0]) # feel free to index into other indices\n```\n\n    {'address': 'Regent Street City Centre', 'area': 'centre', 'food': 'italian', 'id': '19210', 'introduction': 'Pizza hut is a large chain with restaurants nationwide offering convenience pizzas pasta and salads to eat in or take away', 'location': [52.20103, 0.126023], 'name': 'pizza hut city centre', 'phone': '01223323737', 'postcode': 'cb21ab', 'pricerange': 'cheap', 'type': 'restaurant'}\n\n\nFor more information about the multiwoz 2.1 data set, please run the cell below to read the `ReadMe.txt` file. Feel free to open any other file to explore it. \n\n\n```python\nwith open('data/README') as file:\n    print(file.read())\n```\n\n    #####################################################\n    #####################################################\n    #  Copyright Cambridge Dialogue Systems Group, 2018 #\n    #####################################################\n    #####################################################\n    \n    Dataset contains the following files:\n    1. data.json: the woz dialogue dataset, which contains the conversation  users and wizards, as well as a set of coarse labels for each user turn. This file contains both system and user dialogue acts annotated at the turn level. Files with multi-domain dialogues have \"MUL\" in their names. Single domain dialogues have either \"SNG\" or \"WOZ\" in their names.\n    2. restaurant_db.json: the Cambridge restaurant database file, containing restaurants in the Cambridge UK area and a set of attributes.\n    3. attraction_db.json: the Cambridge attraction database file, contining attractions in the Cambridge UK area and a set of attributes.\n    4. hotel_db.json: the Cambridge hotel database file, containing hotels in the Cambridge UK area and a set of attributes.\n    5. train_db.json: the Cambridge train (with artificial connections) database file, containing trains in the Cambridge UK area and a set of attributes.\n    6. hospital_db.json: the Cambridge hospital database file, contatining information about departments.\n    7. police_db.json: the Cambridge police station information.\n    8. taxi_db.json: slot-value list for taxi domain.\n    9. valListFile.txt: list of dialogues for validation.\n    10. testListFile.txt: list of dialogues for testing.\n    11. system_acts.json:\n      There are 6 domains ('Booking', 'Restaurant', 'Hotel', 'Attraction', 'Taxi', 'Train') and 1 dummy domain ('general').\n      A domain-dependent dialogue act is defined as a domain token followed by a domain-independent dialogue act, e.g. 'Hotel-inform' means it is an 'inform' act in the Hotel domain.\n      Dialogue acts which cannot take slots, e.g., 'good bye', are defined under the 'general' domain.\n      A slot-value pair defined as a list with two elements. The first element is slot token and the second one is its value.\n      If a dialogue act takes no slots, e.g., dialogue act 'offer booking' for an utterance 'would you like to take a reservation?', its slot-value pair is ['none', 'none']\n      There are four types of values:\n      1) If a slot takes a binary value, e.g., 'has Internet' or 'has park', the value is either 'yes' or 'no'.\n      2) If a slot is under the act 'request', e.g., 'request' about 'area', the value is expressed as '?'.\n      3) The value that appears in the utterance e.g., the name of a restaurant.\n      4) If for some reason the turn does not have an annotation then it is labeled as \"No Annotation.\"\n    12. ontology.json: Data-based ontology containing all the values for the different slots in the domains.\n    13. slot_descriptions.json: A collection of human-written slot descriptions for each slot in the dataset. Each slot has at least two descriptions.\n    14. tokenization.md: A description of the tokenization preprocessing we had to perform to maintain consistency between the dialogue act annotations of DSTC 8 Track 1 and the existing MultiWOZ 2.0 data. \n    \n\n\nAs you can see, there are many other aspects of the MultiWoz dataset. Nonetheless, you'll see that even with just the conversations, your model will still be able to generate useful responses. This concludes our exploration of the dataset. In the next section, we will do some preprocessing before we feed it into our model for training.\n\n<a name=\"2\"></a>\n# Part 2:   Processing the data for Reformer inputs\n\nYou will now use the `get_conversation()` function to process the data. The Reformer expects inputs of this form: \n\n**Person 1: Why am I so happy? Person 2: Because you are learning NLP Person 1: ... Person 2: ...***\n\nAnd the conversation keeps going with some text. As you can see 'Person 1' and 'Person 2' act as delimiters so the model automatically recognizes the person and who is talking. It can then come up with the corresponding text responses for each person. Let's proceed to process the text in this fashion for the Reformer. First, let's grab all the conversation strings from all dialogue files and put them in a list.\n\n\n```python\n# the keys are the file names\nall_files = DIALOGUE_DB.keys()\n\n# initialize empty list\nuntokenized_data = []\n\n# loop over all files\nfor file in all_files:\n    # this is the graded function you coded\n    # returns a string delimited by Person 1 and Person 2\n    result = get_conversation(file, DIALOGUE_DB)\n    \n    # append to the list\n    untokenized_data.append(result)\n\n# print the first element to check if it's the same as the one we got before\nprint(untokenized_data[0])\n```\n\n     Person 1: am looking for a place to to stay that has cheap price range it should be in a type of hotel Person 2: Okay, do you have a specific area you want to stay in? Person 1: no, i just need to make sure it's cheap. oh, and i need parking Person 2: I found 1 cheap hotel for you that includes parking. Do you like me to book it? Person 1: Yes, please. 6 people 3 nights starting on tuesday. Person 2: I am sorry but I wasn't able to book that for you for Tuesday. Is there another day you would like to stay or perhaps a shorter stay? Person 1: how about only 2 nights. Person 2: Booking was successful.\n    Reference number is : 7GAWK763. Anything else I can do for you? Person 1: No, that will be all. Good bye. Person 2: Thank you for using our services.\n\n\nNow let us split the list to a train and eval dataset.\n\n\n```python\n# shuffle the list we generated above\nrandom.shuffle(untokenized_data)\n\n# define a cutoff (5% of the total length for this assignment)\n# convert to int because we will use it as a list index\ncut_off = int(len(untokenized_data) * .05)\n\n# slice the list. the last elements after the cut_off value will be the eval set. the rest is for training. \ntrain_data, eval_data = untokenized_data[:-cut_off], untokenized_data[-cut_off:]\n\nprint(f'number of conversations in the data set: {len(untokenized_data)}')\nprint(f'number of conversations in train set: {len(train_data)}')\nprint(f'number of conversations in eval set: {len(eval_data)}')\n```\n\n    number of conversations in the data set: 10438\n    number of conversations in train set: 9917\n    number of conversations in eval set: 521\n\n\n<a name=\"2.1\"></a>\n## 2.1   Tokenizing, batching with bucketing\nWe can now proceed in generating tokenized batches of our data. Let's first define a utility generator function to yield elements from our data sets:\n\n\n```python\ndef stream(data):\n    # loop over the entire data\n    while True:\n        # get a random element\n        d = random.choice(data)\n        \n        # yield a tuple pair of identical values \n        # (i.e. our inputs to the model will also be our targets during training)\n        yield (d, d)\n```\n\nNow let's define our data pipeline for tokenizing and batching our data. As in the previous assignments, we will bucket by length and also have an upper bound on the token length.\n\n\n```python\n# trax allows us to use combinators to generate our data pipeline\ndata_pipeline = trax.data.Serial(\n    # randomize the stream\n    trax.data.Shuffle(),\n    \n    # tokenize the data\n    trax.data.Tokenize(vocab_dir=VOCAB_DIR,\n                       vocab_file=VOCAB_FILE),\n    \n    # filter too long sequences\n    trax.data.FilterByLength(2048),\n    \n    # bucket by length\n    trax.data.BucketByLength(boundaries=[128, 256,  512, 1024],\n                             batch_sizes=[16,    8,    4,   2, 1]),\n    \n    # add loss weights but do not add it to the padding tokens (i.e. 0)\n    trax.data.AddLossWeights(id_to_mask=0)\n)\n\n# apply the data pipeline to our train and eval sets\ntrain_stream = data_pipeline(stream(train_data))\neval_stream = data_pipeline(stream(eval_data))\n```\n\nPeek into the train stream.\n\n\n```python\n# the stream generators will yield (input, target, weights). let's just grab the input for inspection\ninp, _, _ = next(train_stream)\n\n# print the shape. format is (batch size, token length)\nprint(\"input shape: \", inp.shape)\n\n# detokenize the first element\nprint(trax.data.detokenize(inp[0], vocab_dir=VOCAB_DIR, vocab_file=VOCAB_FILE))\n```\n\n    input shape:  (4, 512)\n     Person 1: I love the centre of Cambridge but I always spend too much, are there cheap places to eat there so I can stay within my budget? Person 2: Yes, there are several. Charlie Chan serves Chinese food, there's Mahal of Cambridge for Indian, La Raza has Spanish cuisine, and there are a few others. Would you like more? Person 1: restaurant should serve indian food is what I need  Person 2: There are three cheap Indian restaurants in the centre: Kohinoor, The Gandhi, and Mahal of Cambridge. Would you like to make a reservation at one? Person 1: HOw about mahal and can you give their phone number and postcode? Person 2: Their phone number is 01223360409 and their postal code is cb21rq. Person 1: Great.  I'm also looking for a train.  I need to leave after 16:15 from London Liverpool Street. Person 2: Which day would you like to travel by train? Person 1: I'll need it to be on Tuesday. I'm going to Cambridge.  Person 2: TR2855 will leave at 17:39, would that work for you? Person 1: make a booking for 1 people.\n    Make sure you get the reference number Person 2: I have booked the ticket for you, reference 4O9ZT5ZD. Person 1: thank you very much. Person 2: Is there anything else I can assist you with today?  Person 1: That is all, make it a great day! Person 2: Thanks! You have a great day as well!\n\n\n<a name=\"3\"></a>\n# Part 3:   Reversible layers\n\nWhen running large deep models, you will often run out of memory as each layer allocates memory to store activations for use in backpropagation. To save this resource, you need to be able to recompute these activations during the backward pass without storing them during the forward pass. Take a look first at the leftmost diagram below. \n\n\n\nThis is how the residual networks are implemented in the standard Transformer. It follows that, given `F()` is Attention and `G()` is Feed-forward(FF). \n: \n\n\\begin{align}  \n\\mathrm{y}_\\mathrm{a} &= \\mathrm{x} + \\mathrm{F}\\left(\\mathrm{x}\\right)\\tag{1} \\\\\n\\mathrm{y}_{b}&=\\mathrm{y}_{a}+\\mathrm{G}\\left(\\mathrm{y}_{a}\\right)\\tag{2}\\\\\n\\end{align}\n\n\nAs you can see, it requires that $\\mathrm{x}$ and $\\mathrm{y}_{a}$ be saved so it can be used during backpropagation. We want to avoid this to conserve memory and this is where reversible residual connections come in. They are shown in the middle and rightmost diagrams above. The key idea is that we will start with two copies of the input to the model and at each layer we will only update one of them. The activations that we *don\u2019t* update are the ones that will be used to compute the residuals. \n\nNow in this reversible set up you get the following instead: \n\n\\begin{align}  \n\\mathrm{y}_{1}&=\\mathrm{x}_{1}+\\mathrm{F}\\left(\\mathrm{x}_{2}\\right)\\tag{3}\\\\\n\\mathrm{y}_{2}&=\\mathrm{x}_{2}+\\mathrm{G}\\left(\\mathrm{y}_{1}\\right)\\tag{4}\\\\\n\\end{align}\nTo recover $\\mathrm{(x_1,x_2)}$ from $\\mathrm{(y_1, y_2)}$ \n\n\\begin{align}  \n\\mathrm{x}_{2}&=\\mathrm{y}_{2}-\\mathrm{G}\\left(\\mathrm{y}_{1}\\right)\\tag{5}\\\\\n\\mathrm{x}_{1}&=\\mathrm{y}_{1}-\\mathrm{F}\\left(\\mathrm{x}_{2}\\right)\\tag{6}\\\\\n\\end{align}\n\nWith this configuration, we\u2019re now able to run the network fully in reverse. You'll notice that during the backward pass, $\\mathrm{x2}$ and $\\mathrm{x1}$ can be recomputed based solely on the values of $\\mathrm{y2}$ and $\\mathrm{y1}$. No need to save it during the forward pass.\n\n<a name=\"ex02\"></a>\n### Exercise 02\n**Instructions:** You will implement the `reversible_layer_forward` function using equations 3 and 4 above. This function takes in the input vector `x` and the functions `f` and `g` and returns the concatenation of $y_1 and y_2$. For this exercise, we will be splitting `x` before going through the reversible residual steps$\\mathrm{^1}$.  We can then use those two vectors for the `reversible_layer_reverse` function. Utilize `np.concatenate()` to form the output being careful to match the axis of the `np.split()`.\n\n$\\mathrm{^1}$*Take note that this is just for demonstrating the concept in this exercise and there are other ways of processing the input. As you'll see in the Reformer architecture later, the initial input (i.e. `x`) can instead be duplicated instead of split.*\n\n\n```python\n# UNQ_C2\n# GRADED FUNCTION: reversible_layer_forward\ndef reversible_layer_forward(x, f, g):\n    \"\"\"\n    Args: \n        x (np.array): an input vector or matrix\n        f (function): a function which operates on a vector/matrix\n        g (function): a function which operates on a vector/matrix\n    Returns: \n        y (np.array): an output vector or matrix whose form is determined by 'x', f and g\n    \"\"\"\n    # split the input vector into two (* along the last axis because it is the depth dimension)\n    x1, x2 = np.split(x, 2, axis=-1) \n    \n    ### START CODE HERE (REPLACE INSTANCES OF 'None' WITH YOUR CODE) ###\n    \n    # get y1 using equation 3\n    y1 = x1 + f(x2)\n    \n    # get y2 using equation 4\n    y2 = x2 + g(y1)\n    \n    # concatenate y1 and y2 along the depth dimension. be sure output is of type np.ndarray\n    y = np.concatenate([y1, y2], axis=-1)\n    \n    ### END CODE HERE ### \n    return y\n```\n\n\n```python\n# BEGIN UNIT TEST\nw4_unittest.test_reversible_layer_forward(reversible_layer_forward)\n# END UNIT TEST\n```\n\n    \u001b[92m All tests passed\n\n\n<a name=\"ex03\"></a>\n### Exercise 03\n\nYou will now implement the `reversible_layer_reverse` function  which is possible because at every time step you have $x_1$ and $x_2$ and $y_2$ and $y_1$, along with the function `f`, and `g`. Where `f` is the attention and `g` is the feedforward. This allows you to compute equations 5 and 6.\n\n\n**Instructions:** Implement the `reversible_layer_reverse`. Your function takes in the output vector from  `reversible_layer_forward` and functions f and g. Using equations 5 and 6 above, it computes the inputs to the layer,  $x_1$ and $x_2$.  The output, x, is the concatenation of  $x_1, x_2$. Utilize `np.concatenate()`  to form the output being careful to match the axis of the `np.split()`.\n\n\n```python\n# UNQ_C3\n# GRADED FUNCTION: reversible_layer_reverse\ndef reversible_layer_reverse(y, f, g):\n    \"\"\"\n    Args: \n        y (np.array): an input vector or matrix\n        f (function): a function which operates on a vector/matrix of the form of 'y'\n        g (function): a function which operates on a vector/matrix of the form of 'y'\n    Returns: \n        y (np.array): an output vector or matrix whose form is determined by 'y', f and g\n    \"\"\"\n    \n    # split the input vector into two (* along the last axis because it is the depth dimension)\n    y1, y2 = np.split(y, 2, axis=-1)\n    \n    ### START CODE HERE (REPLACE INSTANCES OF 'None' WITH YOUR CODE) ###\n    \n    # compute x2 using equation 5\n    x2 = y2 - g(y1)\n    \n    # compute x1 using equation 6\n    x1 = y1 - f(x2)\n    \n    # concatenate x1 and x2 along the depth dimension\n    x = np.concatenate([x1, x2], axis=-1) \n    \n    \n    ### END CODE HERE ### \n    return x\n\n\n```\n\n\n```python\n# BEGIN UNIT TEST\nw4_unittest.test_reversible_layer_reverse(reversible_layer_reverse)\n# END UNIT TEST\n```\n\n    \u001b[92m All tests passed\n\n\n\n```python\n# UNIT TEST COMMENT: assert at the end can be used in grading as well\nf = lambda x: x + 2\ng = lambda x: x * 3\ninput_vector = np.random.uniform(size=(32,))\n\noutput_vector = reversible_layer_forward(input_vector, f, g)\nreversed_vector = reversible_layer_reverse(output_vector, f, g)\n\nassert np.allclose(reversed_vector, input_vector)\n```\n\n<a name=\"3.1\"></a>\n## 3.1   Reversible layers and randomness\n\nThis is why we were learning about fastmath's random functions and keys in Course 3 Week 1. Utilizing the same key, `trax.fastmath.random.uniform()` will return the same values. This is required for the backward pass to return the correct layer inputs when random noise is introduced in the layer.\n\n\n```python\n# Layers like dropout have noise, so let's simulate it here:\nf = lambda x: x + np.random.uniform(size=x.shape)\n\n# See that the above doesn't work any more:\noutput_vector = reversible_layer_forward(input_vector, f, g)\nreversed_vector = reversible_layer_reverse(output_vector, f, g)\n\nassert not np.allclose(reversed_vector, input_vector)  # Fails!!\n\n# It failed because the noise when reversing used a different random seed.\n\nrandom_seed = 27686\nrng = trax.fastmath.random.get_prng(random_seed)\nf = lambda x: x + trax.fastmath.random.uniform(key=rng, shape=x.shape)\n\n# See that it works now as the same rng is used on forward and reverse.\noutput_vector = reversible_layer_forward(input_vector, f, g)\nreversed_vector = reversible_layer_reverse(output_vector, f, g)\n\nassert np.allclose(reversed_vector, input_vector,  atol=1e-07) \n```\n\n<a name=\"4\"></a>\n# Part 4:   ReformerLM Training\n\nYou will now proceed to training your model. Since you have already know the two main components that differentiates it from the standard Transformer, LSH in Course 1 and reversible layers above, you can just use the pre-built model already implemented in Trax. It will have this architecture:\n\n\n\nSimilar to the Transformer you learned earlier, you want to apply an attention and feed forward layer to your inputs. For the Reformer, we improve the memory efficiency by using **reversible decoder blocks** and you can picture its implementation in Trax like below:\n\n\n\nYou can see that it takes the initial inputs `x1` and `x2` and does the first equation of the reversible networks you learned in Part 3. As you've also learned, the reversible residual has two equations for the forward-pass so doing just one of them will just constitute half of the reversible decoder block. Before doing the second equation (i.e. second half of the reversible residual), it first needs to swap the elements to take into account the stack semantics in Trax. It simply puts `x2` on top of the stack so it can be fed to the add block of the half-residual layer. It then swaps the two outputs again so it can be fed to the next layer of the network. All of these arrives at the two equations in Part 3 and it can be used to recompute the activations during the backward pass.\n\nThese are already implemented for you in Trax and in the following exercise, you'll get to practice how to call them to build your network.\n\n<a name=\"ex04\"></a>\n### Exercise 04\n**Instructions:** Implement a wrapper function that returns a Reformer Language Model. You can use Trax's [ReformerLM](https://trax-ml.readthedocs.io/en/latest/trax.models.html#trax.models.reformer.reformer.ReformerLM) to do this quickly. It will have the same architecture as shown above.\n\n\n```python\n# UNQ_C4\n# GRADED FUNCTION\ndef ReformerLM(vocab_size=33000, n_layers=2, mode='train', attention_type=tl.SelfAttention):\n    \"\"\"\n    Args: \n        vocab_size (int): size of the vocabulary\n        n_layers (int): number of decoder layers\n        mode (string): setting of the model which can be 'train', 'eval', or 'predict' \n        attention_type(class): attention class to use \n    Returns: \n        model (ReformerLM): a reformer language model implemented in Trax\n    \"\"\"    \n    \n    ### START CODE HERE (REPLACE INSTANCES OF 'None' WITH YOUR CODE) ###\n    # initialize an instance of Trax's ReformerLM class\n    model = trax.models.reformer.ReformerLM( \n        # set vocab size\n        vocab_size=vocab_size,\n        # set number of layers\n        n_layers=n_layers,\n        # set mode\n        mode=mode,\n        # set attention type\n        attention_type=attention_type\n    )\n    \n    ### END CODE HERE ###\n    return model\n```\n\n\n```python\n# display the model\ntemp_model = ReformerLM('train')\nprint(str(temp_model))\n\n# free memory\ndel temp_model \n```\n\n    Serial[\n      ShiftRight(1)\n      Embedding_train_512\n      Dropout\n      PositionalEncoding\n      Dup_out2\n      ReversibleSerial_in2_out2[\n        ReversibleHalfResidualV2_in2_out2[\n          Serial[\n            LayerNorm\n          ]\n          SelfAttention\n        ]\n        ReversibleSwap_in2_out2\n        ReversibleHalfResidualV2_in2_out2[\n          Serial[\n            LayerNorm\n            Dense_2048\n            Dropout\n            FastGelu\n            Dense_512\n            Dropout\n          ]\n        ]\n        ReversibleSwap_in2_out2\n        ReversibleHalfResidualV2_in2_out2[\n          Serial[\n            LayerNorm\n          ]\n          SelfAttention\n        ]\n        ReversibleSwap_in2_out2\n        ReversibleHalfResidualV2_in2_out2[\n          Serial[\n            LayerNorm\n            Dense_2048\n            Dropout\n            FastGelu\n            Dense_512\n            Dropout\n          ]\n        ]\n        ReversibleSwap_in2_out2\n      ]\n      Concatenate_in2\n      LayerNorm\n      Dropout\n      Dense_train\n      LogSoftmax\n    ]\n\n\n\n```python\n# BEGIN UNIT TEST\nw4_unittest.test_ReformerLM(ReformerLM)\n# END UNIT TEST\n```\n\n    \u001b[92m All tests passed\n\n\n<a name=\"ex05\"></a>\n### Exercise 05\nYou will now write a function that takes in your model and trains it. \n\n**Instructions:** Implement the `training_loop` below to train the neural network above. Here is a list of things you should do:\n\n- Create `TrainTask` and `EvalTask`\n- Create the training loop `trax.supervised.training.Loop`\n- Pass in the following depending to train_task :\n    - `labeled_data=train_gen`\n    - `loss_layer=tl.CrossEntropyLoss()`\n    - `optimizer=trax.optimizers.Adam(0.01)`\n    - `lr_schedule=lr_schedule`\n    - `n_steps_per_checkpoint=10`  \n\nYou will be using your CrossEntropyLoss loss function with Adam optimizer. Please read the [trax](https://trax-ml.readthedocs.io/en/latest/trax.optimizers.html?highlight=adam#trax.optimizers.adam.Adam) documentation to get a full understanding. \n\n- Pass in the following to eval_task:\n     - `labeled_data=eval_gen`\n     - `metrics=[tl.CrossEntropyLoss(), tl.Accuracy()]`\n\n\n\nThis function should return a `training.Loop` object. To read more about this check the [docs](https://trax-ml.readthedocs.io/en/latest/trax.supervised.html?highlight=loop#trax.supervised.training.Loop).\n\n\n```python\n# UNQ_C5\n# GRADED FUNCTION: train_model\ndef training_loop(ReformerLM, train_gen, eval_gen, output_dir = \"./model/\"):\n    \"\"\"\n    Args:\n        ReformerLM:  the Reformer language model you are building\n        train_gen (generator): train data generator.\n        eval_gen (generator): Validation generator. \n        output_dir (string): Path to save the model output. Defaults to './model/'.\n\n    Returns:\n        trax.supervised.training.Loop: Training loop for the model.\n    \"\"\"\n\n    # use the warmup_and_rsqrt_decay learning rate schedule\n    lr_schedule = trax.lr.warmup_and_rsqrt_decay(\n        n_warmup_steps=1000, max_value=0.01)\n\n    ### START CODE HERE (REPLACE INSTANCES OF 'None' WITH YOUR CODE) ###\n    \n    # define the train task\n    train_task = training.TrainTask(            \n        # labeled data\n        labeled_data=train_gen,\n        # loss layer\n        loss_layer=tl.CrossEntropyLoss(),\n        # optimizer\n        optimizer=trax.optimizers.Adam(0.01),\n        # lr_schedule\n        lr_schedule=lr_schedule,\n        # n_steps\n        n_steps_per_checkpoint=10\n    )\n\n    # define the eval task\n    eval_task = training.EvalTask(                      \n        # labeled data\n        labeled_data=eval_gen,\n        # metrics\n        metrics=[tl.CrossEntropyLoss(), tl.Accuracy()]\n    )\n\n    ### END CODE HERE ###\n    loop = training.Loop(ReformerLM(mode='train'),\n                         train_task,\n                         eval_tasks=[eval_task],\n                         output_dir=output_dir)\n    return loop\n```\n\n\n```python\n# UNIT TEST COMMENT: Use the train task and eval task for grading train_model\ntest_loop = training_loop(ReformerLM, train_stream, eval_stream)\ntrain_task = test_loop._task\neval_task = test_loop._eval_task\n\nprint(train_task)\nprint(eval_task)\n```\n\n    <trax.supervised.training.TrainTask object at 0x7fa279760050>\n    <trax.supervised.training.EvalTask object at 0x7fa279aba550>\n\n\n\n```python\n# BEGIN UNIT TEST\nw4_unittest.test_tasks(train_task, eval_task)\n# END UNIT TEST\n```\n\n    \u001b[92m All tests passed\n\n\n\n```python\n# we will now test your function\n!rm -f model/model.pkl.gz\nloop = training_loop(ReformerLM, train_stream, eval_stream)\nloop.run(10)\n```\n\n    \n    Step      1: Ran 1 train steps in 58.85 secs\n    Step      1: train CrossEntropyLoss |  10.44030952\n    Step      1: eval  CrossEntropyLoss |  10.42661381\n    Step      1: eval          Accuracy |  0.00000000\n    \n    Step     10: Ran 9 train steps in 133.20 secs\n    Step     10: train CrossEntropyLoss |  10.27762985\n    Step     10: eval  CrossEntropyLoss |  9.91913414\n    Step     10: eval          Accuracy |  0.12019914\n\n\n**Approximate Expected output:**  \n\n```\n\nStep      1: Ran 1 train steps in 55.73 secs\nStep      1: train CrossEntropyLoss |  10.41907787\nStep      1: eval  CrossEntropyLoss |  10.41005802\nStep      1: eval          Accuracy |  0.00000000\n\nStep     10: Ran 9 train steps in 108.21 secs\nStep     10: train CrossEntropyLoss |  10.15449715\nStep     10: eval  CrossEntropyLoss |  9.63478279\nStep     10: eval          Accuracy |  0.16350447\n``` \n\n<a name=\"5\"></a>\n# Part 5:   Decode from a pretrained model\n\nWe will now proceed on decoding using the model architecture you just implemented. As in the previous weeks, we will be giving you a pretrained model so you can observe meaningful output during inference. You will be using the [autoregressive_sample_stream()](https://trax-ml.readthedocs.io/en/latest/trax.supervised.html#trax.supervised.decoding.autoregressive_sample_stream) decoding method from Trax to do fast inference. Let's define a few parameters to initialize our model.\n\n\n```python\n# define the `predict_mem_len` and `predict_drop_len` of tl.SelfAttention\ndef attention(*args, **kwargs):\n    # number of input positions to remember in a cache when doing fast inference. \n    kwargs['predict_mem_len'] = 120\n    # number of input elements to drop once the fast inference input cache fills up.\n    kwargs['predict_drop_len'] = 120\n    # return the attention layer with the parameters defined above\n    return tl.SelfAttention(*args, **kwargs)\n\n# define the model using the ReformerLM function you implemented earlier.\nmodel = ReformerLM(\n    vocab_size=33000,\n    n_layers=6,\n    mode='predict',\n    attention_type=attention,\n)\n\n# define an input signature so we can initialize our model. shape will be (1, 1) and the data type is int32.\nshape11 = trax.shapes.ShapeDtype((1, 1), dtype=np.int32)\n```\n\nWe can now initialize our model from a file containing the pretrained weights. We will save this starting state so we can reset the model state when we generate a new conversation. This will become clearer in the `generate_dialogue()` function later.\n\n\n```python\n# initialize from file\nmodel.init_from_file('chatbot_model1.pkl.gz',\n                     weights_only=True, input_signature=shape11)\n\n# save the starting state\nSTARTING_STATE = model.state\n```\n\nLet's define a few utility functions as well to help us tokenize and detokenize. We can use the [tokenize()](https://trax-ml.readthedocs.io/en/latest/trax.data.html#trax.data.tf_inputs.tokenize) and [detokenize()](https://trax-ml.readthedocs.io/en/latest/trax.data.html#trax.data.tf_inputs.detokenize) from `trax.data.tf_inputs` to do this.\n\n\n```python\ndef tokenize(sentence, vocab_file, vocab_dir):\n    return list(trax.data.tokenize(iter([sentence]), vocab_file=vocab_file, vocab_dir=vocab_dir))[0]\n\ndef detokenize(tokens, vocab_file, vocab_dir):\n    return trax.data.detokenize(tokens, vocab_file=vocab_file, vocab_dir=vocab_dir)\n```\n\nWe are now ready to define our decoding function. This will return a generator that yields that next symbol output by the model. It will be able to predict the next words by just feeding it a starting sentence.\n\n<a name=\"ex06\"></a>\n### Exercise 06\n**Instructions:** Implement the function below to return a generator that predicts the next word of the conversation.\n\n\n```python\n# UNQ_C6\n# GRADED FUNCTION\ndef ReformerLM_output_gen(ReformerLM, start_sentence, vocab_file, vocab_dir, temperature):\n    \"\"\"\n    Args:\n        ReformerLM:  the Reformer language model you just trained\n        start_sentence (string): starting sentence of the conversation\n        vocab_file (string): vocabulary filename\n        vocab_dir (string): directory of the vocabulary file\n        temperature (float): parameter for sampling ranging from 0.0 to 1.0.\n            0.0: same as argmax, always pick the most probable token\n            1.0: sampling from the distribution (can sometimes say random things)\n\n    Returns:\n        generator: yields the next symbol generated by the model\n    \"\"\"\n    \n    ### START CODE HERE (REPLACE INSTANCES OF 'None' WITH YOUR CODE) ###\n    \n    # Create input tokens using the the tokenize function\n    input_tokens = tokenize(start_sentence, vocab_file=vocab_file, vocab_dir=vocab_dir)\n    \n    # Add batch dimension to array. Convert from (n,) to (x, n) where \n    # x is the batch size. Default is 1. (hint: you can use np.expand_dims() with axis=0)\n    input_tokens_with_batch = np.array(input_tokens)[None, :]\n    \n    # call the autoregressive_sample_stream function from trax\n    output_gen = trax.supervised.decoding.autoregressive_sample_stream( \n        # model\n        ReformerLM,\n        # inputs will be the tokens with batch dimension\n        inputs=input_tokens_with_batch,\n        # temperature\n        temperature=temperature\n    )\n    \n    ### END CODE HERE ###\n    \n    return output_gen\n```\n\n\n```python\n# BEGIN UNIT TEST\nimport pickle\n\nWEIGHTS_FROM_FILE = ()\n\nwith open('weights', 'rb') as file:\n    WEIGHTS_FROM_FILE = pickle.load(file)\n\nshape11 = trax.shapes.ShapeDtype((1, 1), dtype=np.int32)\n\ndef attention(*args, **kwargs):\n    kwargs['predict_mem_len'] = 120\n    kwargs['predict_drop_len'] = 120\n    return tl.SelfAttention(*args, **kwargs)\n\ntest_model = ReformerLM(vocab_size=5, n_layers=1, mode='predict', attention_type=attention)\n\ntest_output_gen = ReformerLM_output_gen(test_model, \"test\", vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR, temperature=0)\n\ntest_model.init_weights_and_state(shape11)\n\ntest_model.weights = WEIGHTS_FROM_FILE\n\noutput = []\n\nfor i in range(6):\n    output.append(next(test_output_gen)[0])\n\nprint(output)\n\n# free memory\ndel test_model \ndel WEIGHTS_FROM_FILE\ndel test_output_gen\n# END UNIT TEST\n```\n\n    [1, 0, 4, 3, 0, 4]\n\n\n***Expected value:***\n\n[1, 0, 4, 3, 0, 4]\n\nGreat! Now you will be able to see the model in action. The utility function below will call the generator you just implemented and will just format the output to be easier to read. \n\n\n```python\nshape11 = trax.shapes.ShapeDtype((1, 1), dtype=np.int32)\n\ndef attention(*args, **kwargs):\n    kwargs['predict_mem_len'] = 120  # max length for predictions\n    kwargs['predict_drop_len'] = 120  # never drop old stuff\n    return tl.SelfAttention(*args, **kwargs)\n\nmodel = ReformerLM(\n    vocab_size=33000,\n    n_layers=6,\n    mode='predict',\n    attention_type=attention,\n)\n```\n\n\n```python\nmodel.init_from_file('chatbot_model1.pkl.gz',\n                     weights_only=True, input_signature=shape11)\n\nSTARTING_STATE = model.state\n```\n\n\n```python\ndef generate_dialogue(ReformerLM, model_state, start_sentence, vocab_file, vocab_dir, max_len, temperature):\n    \"\"\"\n    Args:\n        ReformerLM:  the Reformer language model you just trained\n        model_state (np.array): initial state of the model before decoding\n        start_sentence (string): starting sentence of the conversation\n        vocab_file (string): vocabulary filename\n        vocab_dir (string): directory of the vocabulary file\n        max_len (int): maximum number of tokens to generate \n        temperature (float): parameter for sampling ranging from 0.0 to 1.0.\n            0.0: same as argmax, always pick the most probable token\n            1.0: sampling from the distribution (can sometimes say random things)\n\n    Returns:\n        generator: yields the next symbol generated by the model\n    \"\"\"  \n    \n    # define the delimiters we used during training\n    delimiter_1 = 'Person 1: ' \n    delimiter_2 = 'Person 2: '\n    \n    # initialize detokenized output\n    sentence = ''\n    \n    # token counter\n    counter = 0\n    \n    # output tokens. we insert a ': ' for formatting\n    result = [tokenize(': ', vocab_file=vocab_file, vocab_dir=vocab_dir)]\n    \n    # reset the model state when starting a new dialogue\n    ReformerLM.state = model_state\n    \n    # calls the output generator implemented earlier\n    output = ReformerLM_output_gen(ReformerLM, start_sentence, vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR, temperature=temperature)\n    \n    # print the starting sentence\n    print(start_sentence.split(delimiter_2)[0].strip())\n    \n    # loop below yields the next tokens until max_len is reached. the if-elif is just for prettifying the output.\n    for o in output:\n        \n        result.append(o)\n        \n        sentence = detokenize(np.concatenate(result, axis=0), vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR)\n        \n        if sentence.endswith(delimiter_1):\n            sentence = sentence.split(delimiter_1)[0]\n            print(f'{delimiter_2}{sentence}')\n            sentence = ''\n            result.clear()\n        \n        elif sentence.endswith(delimiter_2):\n            sentence = sentence.split(delimiter_2)[0]\n            print(f'{delimiter_1}{sentence}')\n            sentence = ''\n            result.clear()\n\n        counter += 1\n        \n        if counter > max_len:\n            break    \n\n\n```\n\nWe can now feed in different starting sentences and see how the model generates the dialogue. You can even input your own starting sentence. Just remember to ask a question that covers the topics in the Multiwoz dataset so you can generate a meaningful conversation.\n\n\n```python\nsample_sentence = ' Person 1: Are there theatres in town? Person 2: '\ngenerate_dialogue(ReformerLM=model, model_state=STARTING_STATE, start_sentence=sample_sentence, vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR, max_len=120, temperature=0.2)\n```\n\n    Person 1: Are there theatres in town?\n    Person 2: : There are 4 theatres in town. Do you have a preference on area? \n    Person 1: No, I don't care. Which one do you recommend? \n    Person 2: I recommend the Mumford Theatre. It's located in the east at Anglia Ruskin Enterprise, east road. Would you like more information? \n    Person 1: Yes, could I get the postcode and phone number please? \n    Person 2: The phone number is 08451962320 and expensive. Which one would you prefer? \n\n\n\n```python\nsample_sentence = ' Person 1: Is there a hospital nearby? Person 2: '\ngenerate_dialogue(ReformerLM=model, model_state=STARTING_STATE, start_sentence=sample_sentence, vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR, max_len=120, temperature=0.2)\n```\n\n    Person 1: Is there a hospital nearby?\n    Person 2: : Addensbrookes Hospital is located at Hills Rd, Cambridge, postcode CB20QQ. Do you need anything else? \n    Person 1: No, that's all. Thank you! \n    Person 2: You're welcome. Have a good day.m.Thanks for contacting the Cambridge TownInfo centre. Goodbye.\n    Person 1: Thanks again. Goodbye. \n\n\n\n```python\nsample_sentence = ' Person 1: Can you book a taxi? Person 2: '\ngenerate_dialogue(ReformerLM=model, model_state=STARTING_STATE, start_sentence=sample_sentence, vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR, max_len=120, temperature=0.2)\n```\n\n    Person 1: Can you book a taxi?\n    Person 2: : I sure can. When would you like to leave? \n    Person 1: I need to leave after 21:45. \n    Person 2: I'm sorry I have no trains leaving from that day. Could you change your request? \n    Person 1: How about a college? \n    Person 2: I have 13 colleges in the center of town. Downing College is in the center of town. \n\n\n\n```python\nsample_sentence = ' Person 1: What is the most popular food in Canada? Person 2: '\ngenerate_dialogue(ReformerLM=model, model_state=STARTING_STATE, start_sentence=sample_sentence, vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR, max_len=120, temperature=0.2)\n```\n\n    Person 1: What is the most popular food in Canada?\n    Person 2: : There are no restaurants that match your request. Would you like to try a different cuisine? \n    Person 1: How about Chinese food? \n    Person 2: There are several Chinese restaurants in town. Do you have a price range in mind? \n    Person 1: Yes, I'd like to eat Chinese food. \n    Person 2: There are several Chinese restaurants in town. Do you have a price range in mind? \n    Person 1: I would like to eat in the centre of town. Person:  i i i want  \n\n\n**Congratulations! You just wrapped up the final assignment of this course and the entire specialization!**\n", "meta": {"hexsha": "3be993d075fe38c5b142c157c3d1be34a39e4e9f", "size": 77817, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chatbot with Reformer.ipynb", "max_stars_repo_name": "fangyiyu/Natural_Language_Processing", "max_stars_repo_head_hexsha": "2d081e8baece1612d95d00f3d108608ac012d56c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-04T21:02:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T21:02:55.000Z", "max_issues_repo_path": "Chatbot with Reformer.ipynb", "max_issues_repo_name": "fangyiyu/Natural_Language_Processing", "max_issues_repo_head_hexsha": "2d081e8baece1612d95d00f3d108608ac012d56c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chatbot with Reformer.ipynb", "max_forks_repo_name": "fangyiyu/Natural_Language_Processing", "max_forks_repo_head_hexsha": "2d081e8baece1612d95d00f3d108608ac012d56c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3223021583, "max_line_length": 1036, "alphanum_fraction": 0.5862343704, "converted": true, "num_tokens": 13652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414330889797, "lm_q2_score": 0.13296422817269313, "lm_q1q2_score": 0.03575959007433418}}
{"text": "##### Copyright 2021 The Cirq Developers\n\n\n```\n#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n\n```\n# Fourier Checking Problem\n```\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n  <td>\n    <a target=\"_blank\" href=\"https://quantumai.google/cirq/tutorial/fourier_checking>\">View on QuantumAI</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/Cirq/blob/master/docs/tutorial/fourier_checking.ipynb\">Run in Google Colab</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://github.com/quantumlib/Cirq/blob/master/docs/fourier_checking.ipynb\">View source on GitHub</a>\n  </td>\n  <td>\n    <a href=\"https://storage.googleapis.com/tensorflow_docs/Cirq/docs/fourier_checking.ipynb\">Download notebook</a>\n  </td>\n</table>\n\n\n```\ntry:\n    import cirq\nexcept:\n    print(\"installing cirq...\")\n    !pip install --quiet cirq\n    print(\"installed cirq.\")\n    import cirq\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nnp.random.seed(2021)\nnp.set_printoptions(precision=3, suppress=True, linewidth=200)\n```\n\n# Introduction\n\n\nIn past decades, there is ample evidence suggesting that quantum computers can be exponentially more powerful in solving certain computational tasks than their classical couterparts. The *black-box* or *query* model, such as Grover\u2019s search, Deutsch-Jozsa\u2019s algorithm, etc., offers a concrete setting to show such exponential speedups. Normally, one provides \"black-box access\" to a function $f$, meaning that the quantum algorithm can apply a unitary\ntransformation that maps basis states of the form $|x, y \\rangle$ to to basis states of the form $|x, y \\oplus f(x)\\rangle $ or $|x\\rangle$ to $(-1)^{f(x)} |x\\rangle$ if $f$ is Boolean. Then, a natural question is asked:\n\n> What is the maximal possible separation between quantum and classical query complexities?\n\nFor example, could there be a function of $N$ bits with a quantum query\ncomplexity of 1, but a classical randomized query complexity of $\\Omega(\\sqrt{N})$ or $\\Omega(N)$?\nSpecifically, [Buhrman et al. from 2002](https://www.sciencedirect.com/science/article/pii/S030439750100144X) asked whether there is any\nproperty of $N-$bit strings that exhibits a **\u201cmaximal\u201d** separation: that is, one that requires $\\Omega(N)$\nqueries to test classically, but only O (1) quantumly.\n\n**Fourier Checking** is a problem that provides a separation between quantum  and classical computers -- $O(1)$ VS $\\tilde{\\Omega}(\\sqrt{N})$, which can be proved as optimal. Currently it only has theoretical importance - but, as it falls into the category of small quantum algorithms, it can be used to demonstrate query complexity and oracle synthesis in Cirq.\n\nGoal of this notebook is to introduce\n\n1. What is Forrelation and the Fourier Checking problem and why we are interested in it?\n2. What is bounded-error quantum polynomial time (BQP) and why does the Fourier Checking problem belong to it?\n3. How to implement the Fourier Checking algorithm and an oracle function in Cirq?\n\nWe won't include the formal proofs and argument. However, we do give sketches of the derivation for intuition and encourage the reader to check the corresponding lemmas and theorems in the original paper.\n\n\n# Preliminary\n\nBefore we present the Fourier Checking problem, three preliminary concepts, 1) BPP and BQP 2) Fourier Transform over $Z_2^n$ and 3) Forrelation, are introduced first.\n\n\n## Bounded-error Probabilistic Polynomial time (BPP)\n\nIn computational complexity theory, [bounded-error probabilistic polynomial time (BPP)](https://en.wikipedia.org/wiki/BPP_(complexity)) is the class of decision problems solvable by a [probabilistic Turing machine](https://en.wikipedia.org/wiki/Probabilistic_Turing_machine) in polynomial time with an error probability bounded away from 1/3 for all instances:\n\n| &nbsp; &nbsp;&nbsp;&nbsp;&nbsp; Anwser Provided  <br />  <br /> Correct Anwser| Yes <br /> <br /> &nbsp; | No <br /> <br /> &nbsp;|\n|:---------------|------|-------|\n| Yes           | $\\geq$ 2/3 | $\\leq$ 1/3 |\n| No            | $\\leq$ 1/3 | $\\geq$ 2/3 |\n\nThe choice of 1/3 in the definition is arbitrary. It can be any constant between 0 and \u200b1/2 (exclusive) and the set BPP will be unchanged.\n\nTo understand this better, let's consider a simple example.\n\n**Problem**: Supposing we have a boolean function $f: \\{0, 1\\}^n \\rightarrow\\{-1, 1\\}$. The function is drawn either from distribution $\\mathcal{B}$ or $\\mathcal{C}$. Under the distribution $\\mathcal{B}$, the function $f$ is balanced, i.e., $\\sum_{x} f(x) = 0$. Under the distribution $\\mathcal{C}$, the function $f$ is constant, i.e., function is always equal to $+1$ or $-1$. The problem is to accept the function if it is drawn from $\\mathcal{B}$ or reject it otherwise.\n\nFor example, consider the case that $n=2$. There are only four possible functions listed in following table\n\n|x   | f_0(x)| f_1(x)| f_2(x)| f_3(x)|\n|----|----:|----:|----:|----:|\n| 0  | +1 | -1 | +1 | -1 |\n| 1  | -1 | +1 | +1 | -1 |\n\nClearly, $f_0$ and $f_1$ belongs to $\\mathcal{B}$ and $f_2$ and $f_3$ belongs to $\\mathcal{C}$.\n\n**Deterministic Algorithm**:  We evaluate the outputs of function of $2^{n-1}+1$ different inputs. If the results contain both $+1$ and $-1$ value, the function must be drawn from distribution $\\mathcal{B}$. Otherwise, it must come from $\\mathcal{C}$.\n\nRemembering that the function is guaranteed to be either balanced or constant, not somewhere in between. So above algorithm is guaranteed to be always correct. However, the query complexity is $O(N)$, denoting $N=2^n$. Here we are interested in the query complexity instead of computation complexity. Namely, how many times we have to evaluate $f$ -- which you can imagine being a very costly function. If the bounded-error probability is acceptable for solving the problem, we can achieve better algorithm in terms of query complexity.\n\n**Randomized Algorithm**: Randomly select $K$ different inputs and evaluate the corresponding outputs. If both $+1$ and $-1$ are observed, we accept it. Otherwise, it reject it.\n\nThe complexity of algorithm depends on the choice of $K$. For this problem, selecting fixed number is sufficient, i.e. $O(1)$ query complexity. It is worth to remark that $O(1)$ means no matter the fixed number is independent of the input size of function $N$. Consider the $K=2$ case, it is not hard to establish the following confusion matrix regardless of $N$:\n\n| Randomized Algorithm (K=2):  | Accept  | Reject |\n|---------------|---------|-------|\n| Drawn from $\\mathcal{B}$ | 1/2 | 1/2  |\n| Drawn from $\\mathcal{C}$ | 0 | 1 |\n\nThis is not sufficient to solve it. However, if we select $K>2$ entries, the  probability of correctness will boost. Let's use the code to exam it.\n\n\n```\ndef gen_balanced_function(N):\n    half_size = N // 2\n    f = np.ones(N)\n    flip_loc = np.random.permutation(N)[:half_size]\n    f[flip_loc] = -1\n    return f\n\n\ndef gen_constant_function(N):\n    flip = np.random.random() > 0.5\n    f = np.ones(N) if flip else -1 * np.ones(N)\n    return f\n```\n\n\n```\ndef randomized_alg(f, sample_size):\n    N = len(f)\n    sample_index = np.random.choice(N, size=sample_size)\n    if len(set(f[sample_index])) == 2:\n        return \"accept\"\n    return \"reject\"\n```\n\n\n```\nN = 128\nK = 3\nsamples = 1000\n\nres = pd.DataFrame()\nfor _ in range(samples):\n    if np.random.rand() > 0.5:\n        f = gen_balanced_function(N)\n        dist = \"B\"\n    else:\n        f = gen_constant_function(N)\n        dist = \"C\"\n    decision = randomized_alg(f, K)\n    res = res.append({\n        \"Distribution\": dist,\n        \"Decision\": decision,\n        \"Count\": 1\n    }, ignore_index=True)\nconfusion = res.pivot_table(index=\"Distribution\",\n                            columns=\"Decision\",\n                            values=\"Count\",\n                            aggfunc=\"sum\")\n# Translate the counts into percentage\nconfusion.div(confusion.sum(axis=1), axis=0).apply(lambda x: round(x, 4) * 100)\n```\n\nRecall that the B in BPP means *bounded-error*. Actually, you can achieve arbitary small error rate under the same query complexity order. Say, you set an acceptable error rate $\\epsilon$. Then the key is that we can run the algorithm multiple times. Repeat it as many times as you want until the error rate is lower than $\\epsilon$. It is crucial to note that the error rate for this particular problem does not depend on the size of the input but only on the size of the sample and the reptitation. For this reason, in order to get to a bounded probability error, it is sufficient to just adjust the sample size and/or repetitions to a given constant - which means that the \"query complexity\" of the algorithm will stay $O(1)$. For example, let's run previous algorithms 3 times and make the final decision based on the majority of the decision of each term. You should verify that the probability of error indeed decreased and independent of $N$.\n\n\n```\nN = 128\nK = 3\nrepetitions = 3\nsamples = 1000\n\nres = pd.DataFrame()\nfor _ in range(samples):\n    if np.random.rand() > 0.5:\n        f = gen_balanced_function(N)\n        dist = \"B\"\n    else:\n        f = gen_constant_function(N)\n        dist = \"C\"\n    accept_minus_reject_count = 0\n    for _ in range(repetitions):\n        decision = randomized_alg(f, K)\n        accept_minus_reject_count += 1 if decision == \"accept\" else -1\n    final_decision = \"accept\" if accept_minus_reject_count > 0 else \"reject\"\n    res = res.append(\n        {\n            \"Distribution\": dist,\n            \"Decision\": final_decision,\n            \"Count\": 1\n        }, ignore_index=True)\nconfusion = res.pivot_table(index=\"Distribution\",\n                            columns=\"Decision\",\n                            values=\"Count\",\n                            aggfunc=\"sum\")\n# Translate the counts into percentage\nconfusion.div(confusion.sum(axis=1), axis=0).apply(lambda x: round(x, 4) * 100)\n```\n\nIf you try the algorithm with more repetitions, you will observe the error rate decreases rapidly. You can also try different values of $K, N, $ and/or repetitions to see how the confusion matrix changes according.\n\nAfter you understand the concept of BPP, it is easy to understand [bounded-error quantum polynomial time (BQP)](https://en.wikipedia.org/wiki/BQP) now. BQP is the class of decision problems solvable by a quantum computer in polynomial time, with an error probability of at most 1/3 for all instances. It is the quantum analogue to the complexity class BPP. Actually, under quantum computer, previous problem can be solved through [Deutsch\u2013Jozsa algorithm](https://en.wikipedia.org/wiki/Deutsch%E2%80%93Jozsa_algorithm) with a single query while guaranteed to be correct always. The Fourier Checking problem that will be introduced later is belong to BQP as well.\n\n## Fourier Transform over $\\mathbb{Z}^n_2$\nIn this colab, we are interested in the boolean function of the form $f : \\{0, 1\\}^n \\rightarrow\\{-1, 1\\}$. In this case, the Fourier transform of $f$ over $\\mathbb{Z}^n_2$ is defined as\n$$\n  \\hat{f}(y) := \\frac{1}{\\sqrt{N}} \\sum_{x\\in\\{0,1\\}^n} (-1)^{x \\cdot y} f\n  (x).\n$$\nwhere $x \\cdot y$ means the bit-wise inner product between $x$ and $y$. Note this is not the standard discrete Fourier transform definition over $\\mathbb{Z}_N$. According to the Parseval's identity, we have\n\n$$\n  \\sum_{x\\in\\{0,1\\}^n} f(x)^2 = \\sum_{y\\in\\{0,1\\}^n} \\hat{f}(y)^2  = N .\n$$\n\n\n```\ndef bitwise_dot(x, y):\n    \"\"\"Compute the dot product of two integers bitwise.\"\"\"\n\n    def bit_parity(i):\n        n = bin(i).count(\"1\")\n        return int(n % 2)\n\n    return bit_parity(x & y)\n\n\ndef fourier_transform_over_z2(v):\n    \"\"\"Fourier transform function over z_2^n group.\n\n    Args:\n        v: an array with 2**n elements.\n\n    Returns:\n        vs: a numpy array with same length as input.\n    \"\"\"\n    assert len(v) & (len(v) - 1) == 0  # make sure v is 2**n long vector\n    N = len(v)\n    v_hat = np.array([0.0] * N)\n    for y in range(N):\n        for x in range(N):\n            v_hat[y] += ((-1)**bitwise_dot(x, y)) * v[x]\n    return v_hat / np.sqrt(N)\n```\n\nLet's have some examples in $\\mathbb{Z}^2_2$. You should verify that both functions have same energy 4.\n\n\n```\nf = np.array([1, -1, 1, -1])\nf_hat = fourier_transform_over_z2(f)\nprint(f\"f: {list(f)} f_hat: {list(f_hat)}\")\n\nf = np.array([1, 1, 1, -1])\nf_hat = fourier_transform_over_z2(f)\nprint(f\"f: {list(f)} f_hat: {list(f_hat)}\")\n\nf = np.array([1, -1, -1, 1])\nf_hat = fourier_transform_over_z2(f)\nprint(f\"f: {list(f)} f_hat: {list(f_hat)}\")\n```\n\n## Forrelation\n\nThe concept of *forrelation* is the key concept in the Fourier checking problem, which is a combination of the words \"Fourier Transform\" and \"Correlation\".\nRecall the classical correlation between two vectors $u$ and $v$ is defined as\n$$\n  {\\rm correlation}(u,v) = \\frac{ \\langle u, v \\rangle }{\\|u\\| \\|v\\|}.\n$$\nThen, the forrelation between two vectors $u$ and $v$ is just the correlation between $u$ and the Fourier trasformed of $v$ -- denoted as $\\widehat{v}$:\n\\begin{align}\n  {\\rm forrelation}(u, v) =& \\frac{\\langle u, \\widehat{v} \\rangle }{\\|u\\| \\|\\widehat{v}\\|},\\\\\n  =& \\frac{ \\langle u, \\widehat{v} \\rangle }{\\|u\\| \\|v\\|}.\n\\end{align}\nwhere the second equality is due to the Parseval's identity.\nSince in this tutorial we are interesed in Boolean function, we replace the arbitary vector $u$ and $v$ by the output of Boolean function $f$ and $g$. Now we can further simplify the above definition:\n\\begin{align}\n  {\\rm forrelation}(f, g) =& \\frac{\\langle f, \\widehat{g} \\rangle }{\\|f\\| \\|g\\|}\\\\\n  =& \\frac{1}{N} \\langle f, \\widehat{g}\\rangle  \\\\\n  =& \\frac{1}{N} \\sum_{x \\in \\{0,1\\}^n}f(x)\\widehat{g}(x)\\\\\n  =& \\frac{1}{N^{3/2}} \\sum_{x, y \\in \\{0,1\\}^n}f(x)(-1)^{x \\cdot y}g(y)\n\\end{align}\n\n\n\n```\ndef get_correlation(f, g):\n    return f.dot(g) / np.linalg.norm(f) / np.linalg.norm(g)\n\n\ndef get_forrelation(f, g):\n    g_hat = fourier_transform_over_z2(g)\n    return f.dot(g_hat) / np.linalg.norm(f) / np.linalg.norm(g)\n```\n\n\n```\n# let's see some examples to gain some insights of forrelation\nf = np.array([1, -1, 1, -1]) \ng = np.array([1, -1, 1, -1])\nprint(f\"Correlation: {get_correlation(f,g)}  Forrelation: {get_forrelation(f,g)}\")\n\nf = np.array([1, 1, 1, -1])\ng = np.array([-1, -1, -1, 1])\nprint(f\"Correlation: {get_correlation(f,g)}  Forrelation: {get_forrelation(f,g)}\")\n\nf = np.array([1, -1, -1, 1])\ng = np.array([1, 1, 1, 1])\nprint(f\"Correlation: {get_correlation(f,g)}  Forrelation: {get_forrelation(f,g)}\")\n```\n\n# Fourier Checking Problem\n\nNow we are prepared to discuss the *Fourier Checking* problem. Here we are given oracle access to two Boolean functions $f,g : \\{0, 1\\}^n \\rightarrow\\{-1, 1\\}$. We are promised that one of the following two cases is true:\n\n- $\\langle f, g \\rangle$ was drawn from the uniform distribution $\\mathcal{U}$.\n- $\\langle f, g \\rangle$ was drawn from the forrelated distribution $\\mathcal{F}$ (Will be explained in more details later).\n\nThe problem is a decision problem that accepts the $\\langle f, g \\rangle$ if it was drawn from $\\mathcal{F}$ and rejects $\\langle f, g \\rangle$ if it was drawn from $\\mathcal{U}$.\n\n*Note: Since $\\mathcal{F}$ and $\\mathcal{U}$ overlap slightly, we can only hope to succeed with overwhelming probability over the choice of  $\\langle f, g \\rangle$ , not for every  $\\langle f, g \\rangle$  pair.*\n\n\n## Generate functions $f$ and $g$ from distribution $\\mathcal U$ and $\\mathcal F$\nThe forrelated distribution $\\mathcal{F}$ is generated as followings.\nFirst\nchoose a random real vector $v=(v_x)_{x\\in\\{0, 1\\}^n} \\in \\mathbb{R}^N$, by drawing each entry independently from Gaussian distribution with zero-mean and variance 1. Then set $f(x) := {\\rm sgn}(v_x)$ and $g(x) := {\\rm sgn}(\\widehat{v}_x)$, where $\\widehat{v}_x$ the Fourier Transform of $v$ is\n$$\n  \\widehat{v}_y := \\frac{1}{\\sqrt{N}} \\sum_{x\\in\\{0,1\\}^n} (-1)^{x\\cdot y}v_x,\n$$\nand \n$$\n  {\\rm sgn}(\\alpha) := \\left\\{\n  \\begin{aligned}\n    1 \\;\\;\\; &{\\rm if}\\; \\alpha \\geq 0 \\\\\n    -1 \\;\\;\\;&{\\rm if}\\; \\alpha < 0\n  \\end{aligned}\\right.\n$$\nNotice, $f$ and $g$ *individually* are still uniformly random, but they are no longer independent. Now $f$ is forrelated with $g$.\nFor simplicity, we only consider the *PROMISE FOURIER CHECKING* problem. Under this situation, we are promised that the quatity:\n\n\\begin{align}\n  p(f,g) := \\left[{\\rm forrelation}(f, g)\\right]^2 = \\frac{1}{N^3} \\left(\\sum_{x, y \\in \\{0,1\\}^n}f(x)(-1)^{x \\cdot y}g(y)\\right)^2\n\\end{align}\n\nis either at least 0.05 or at most 0.01.\n\n\n```\nn = 6\nN = 2 ** n\n```\n\n\n```\n# We can find a forrelated pair \"as promised\" through while-loop\ndef draw_two_distribution_from_f_set(N):\n    sgn = lambda x: 1 if x >= 0 else -1\n    forrelation = 0.2\n    while (abs(forrelation)**2 < 0.05) and (abs(forrelation)**2 > 0.01):\n        vs = np.array([np.random.normal() for _ in range(N)])\n        vs_hat = fourier_transform_over_z2(vs)\n        fs = np.array([sgn(v) for v in vs])\n        gs = np.array([sgn(v_hat) for v_hat in vs_hat])\n        forrelation = get_forrelation(fs, gs)\n        correlation = get_correlation(fs, gs)\n    return fs, gs, forrelation, correlation\n\n\ndef draw_two_distribution_from_u_set(N):\n    sgn = lambda x: 1 if x >= 0 else -1\n    forrelation = 0.2\n    while (abs(forrelation)**2 < 0.05) and (abs(forrelation)**2 > 0.01):\n        vs = np.array([np.random.normal() for _ in range(N)])\n        fs = np.array([sgn(v) for v in vs])\n        us = np.array([np.random.normal() for _ in range(N)])\n        gs = np.array([sgn(u) for u in us])\n        forrelation = get_forrelation(fs, gs)\n        correlation = get_correlation(fs, gs)\n    return fs, gs, forrelation, correlation\n```\n\n\n```\nfs, gs, forrelation, correlation = draw_two_distribution_from_u_set(N)\nprint(f\"fs: {list(fs)}\")\nprint(f\"gs: {list(gs)}\")\n\nplt.figure(figsize=(15, 5))\nplt.stem(fs, use_line_collection=True)\nplt.stem(gs, linefmt='--r', markerfmt='ro', use_line_collection=True)\nplt.title(f\"Correlation: {correlation} Forrelation: {forrelation}\")\n```\n\n\n```\nfs, gs, forrelation, correlation = draw_two_distribution_from_f_set(N)\nprint(f\"fs: {list(fs)}\")\nprint(f\"gs: {list(gs)}\")\nplt.figure(figsize=(15, 5))\nplt.stem(fs, use_line_collection=True)\nplt.stem(gs, linefmt='--r', markerfmt=\"ro\", use_line_collection=True)\nplt.title(f\"Correlation: {correlation} Forrelation: {forrelation}\")\n```\n\nTypically, $\\mathcal{U}$ and $\\mathcal{F}$ is not obviously different from each other even after we plot the whole functions information together. However, it is not hard to show that Fourier Checking is in BQP: basically, one can prepare a uniform superposition over all $x\\in\\{0,1\\}^n$, then query $f$, apply a quantum Fourier transform, query $g$, and\ncheck whether one has recovered something close to the uniform superposition. On the other hand, being forrelated seems like an extremely \u201cglobal\u201d property of $f$ and $g$: one that would not be apparent from querying any small number of $f$ and $g$ values, regardless of the outcomes of those queries.\n\n# Quantum Algorithm for Fourier Checking\n\nNow, we present the quantum algorithm for Fourier Checking, which is quite simple actually.\nIt can achieve the constant error probability with $O(1)$ query complexity.\n\n**Algorithm Description:**\n\nFirst, we prepare a uniform superposition over all $x \\in \\{0, 1\\}^n$. Then query $f$ in superposition, to create the state\n$$\n  \\frac{1}{\\sqrt{N}} \\sum_{x \\in \\{0, 1\\}^n} f(x) |x\\rangle\n$$\nApplying Hadmard gates to all $n$ qubits, to create the state\n$$\n  \\frac{1}{N} \\sum_{x,y  \\in \\{0, 1\\}^n} f(x) (-1)^{x\\cdot y} |y\\rangle\n$$\nThen query $g$ in superposition, to create the state\n$$\n  \\frac{1}{N} \\sum_{x,y  \\in \\{0, 1\\}^n} f(x) (-1)^{x\\cdot y}g(y) |y\\rangle\n$$\nThen apply Hadmard gates to all $n$ qubits again, to create the state\n$$\n  \\frac{1}{N^{3/2}} \\sum_{x,y  \\in \\{0, 1\\}^n} f(x) (-1)^{x\\cdot y} g(y) (-1)^{y \\cdot z}|z\\rangle\n$$\nFinally, measure in the computational basis, and \"accept\" if and only if the outcome $|0\\rangle^{\\otimes n}$is observed.\n\nIf needed, repeat the whole algorithm $O(1)$ times to boost the success probability.\n\nIt is clear that the probablity of observation $|0\\rangle^{\\otimes n}$ equals the quantity:\n\\begin{align}\n  p(f,g) := \\frac{1}{N^3} \\left(\\sum_{x, y \\in \\{0,1\\}^n}f(x)(-1)^{x \\cdot y}g(y)\\right)^2\n\\end{align}\n\nIt is shown in the [paper](https://arxiv.org/pdf/0910.4698.pdf) that\n\n\\begin{align}\n   {\\rm Pr}_{\\langle f, g \\rangle \\sim \\mathcal{U}} [p(f,g) \\geq 0.01] \\leq& \\; \\frac{100}{N} \\\\\n   {\\rm Pr}_{\\langle f, g \\rangle \\sim \\mathcal{F}} [p(f,g) \\geq 0.05] \\geq&\\;\\frac{1}{50} \\\\\n\\end{align}\nThis implies that the probability of the forrelation square between two functions drawing from uniform  distribution $\\mathcal{U}$ having larger than 0.01  will decaying quickly when we have more number of qubits. Hence, the Promise Fourier Checking problem can be solved through simply accepting when $p(f,g) \\geq 0.05$ and rejecting when $p(f,g) \\leq 0.01$ with constant error probability, using $O(1)$ queries to $f$ and $g$.\n\n## Implementation in Cirq\n\nAbove algorithm is simple and straightforward to implement. It only involves with Hadmard gates and function oracles. Implementation of oracles based on truth table in Cirq is just simple diagnal gates. To see that, let's use a oracle defined over $\\mathbb{Z}_2^2$ as example:\n\n\\begin{align}\n  \\sum_{x\\in \\{0, 1\\}^2} f(x)|x\\rangle\n  =&\\frac{1}{2}\\Big(f(0,0)|00\\rangle + f(0,1)|01\\rangle+f(1,0)|10\\rangle + f(1,1) |11\\rangle\\Big)\\\\\n  =&\\;\\;\\left[ \\begin{array}{cccc}\n    f(0,0)   & & & \\\\ \n    &  f(1,0)  & & \\\\\n    &   &  f(1,0)  & \\\\\n    &  & &   f(1,1) \\\\\n  \\end{array} \\right]\n  \\left[ \\begin{array}{c}\n  1/2\\\\\n  1/2\\\\\n  1/2\\\\\n  1/2\n  \\end{array} \\right]\n\\end{align}\n\nIt is crucial to note that the output of $f$ is either 1 or -1, so the diagonal matrix is unitary.\n\n\n```\ndef oracle(fs, qubits):\n    return cirq.MatrixGate(np.diag(fs).astype(complex))(*qubits)\n\n\ndef fourier_checking_algorithm(qubits, fs, gs):\n    \"\"\"Returns the circuit for Fourier Checking algorithm given an input.\"\"\"\n    yield cirq.ParallelGateOperation(cirq.H, qubits)\n    yield oracle(fs, qubits)\n    yield cirq.ParallelGateOperation(cirq.H, qubits)\n    yield oracle(gs, qubits)\n    yield cirq.ParallelGateOperation(cirq.H, qubits)\n    yield cirq.measure(*qubits)\n\n\nqubits = cirq.LineQubit.range(n)\nfs, gs, forrelation, correlation = draw_two_distribution_from_f_set(N)\ncircuit = cirq.Circuit(fourier_checking_algorithm(qubits, fs, gs))\nprint(circuit)\n```\n\nWe derived that the square forrelation between $f$ and $g$ is the same as the state of final state in circuit so we can use cirq to check it. Just remember the final state is *never* able to be obtained in reality. In simulation, it is completely doable through `final_state_vector` or the `dirac_notation` of each moment step: \n\n\n```\nassert np.isclose(circuit.final_state_vector()[0], forrelation)\n\ns = cirq.Simulator()\nfor step in s.simulate_moment_steps(circuit):\n    print(step.dirac_notation())\n    print(\"|0> state probability to observe: \",\n          np.abs(step.state_vector()[0])**2)\n```\n\n\n```\nfinal_state = circuit.final_state_vector()\nplt.fill_between(np.arange(len(final_state)),\n                 np.abs(final_state)**2)\nplt.xlabel(\"State of qubits\")\nplt.ylabel(\"Probability\")\nplt.show()\n```\n\nIn reality, we can measure the state of qubits only. Each measurement will only produce one state. In order to eastimate the probability, we can do 100 repeitations and use frequency of showing 0 state as the approximation of the probability of state 0.\n\n\n```\nrepetitions = 100\nobs = s.run(circuit, repetitions=repetitions)\nqubits_name = ','.join(str(i) for i in range(n))\ntimes_zero_was_measured = len(obs.data[obs.data[qubits_name] == 0])\nprint(\n    f\"times zero state was measured from {repetitions} measurements:\" +\n    f\"{times_zero_was_measured} - {float(times_zero_was_measured/repetitions)*100}%\"\n)\nif float(times_zero_was_measured / repetitions) > 0.05:\n    print(\"fs and gs is forrelated!\")\n```\n\nLast, we can randomly draw the functions from either $\\mathcal{U}$ or $\\mathcal{F}$ set to evaluate the confusion matrix of the Fourier Checking algorithm. With the confusion matrix, you should be confident that quantum algorithm instead can solve the Fourier Checking in $O(1)$ time -- even though we need to measure 100 or 1000 times to evaluate the probability, it is irrelevant to the number of states or qubits.\n\n\n```\nres = pd.DataFrame()\nrepetitions = 100\nnum_rounds = 1000\nfor _ in range(num_rounds):\n    if np.random.rand() > 0.5:\n        fs, gs, _, _ = draw_two_distribution_from_f_set(N)\n        source = \"F set\"\n    else:\n        fs, gs, _, _ = draw_two_distribution_from_u_set(N)\n        source = \"U set\"\n\n    circuit = cirq.Circuit(fourier_checking_algorithm(qubits, fs, gs))\n    obs = s.run(circuit, repetitions=repetitions)\n    times_zero_was_measured = len(obs.data[obs.data[','.join(\n        str(i) for i in range(n))] == 0])\n    if times_zero_was_measured / repetitions > 0.05:\n        res = res.append({\n            \"Source\": source,\n            \"Decision\": \"accept\",\n            \"Count\": 1\n        }, ignore_index=True)\n    else:\n        res = res.append({\n            \"Source\": source,\n            \"Decision\": \"reject\",\n            \"Count\": 1\n        }, ignore_index=True)\nconfusion = res.pivot_table(index=\"Source\", columns=\"Decision\", values=\"Count\", aggfunc=\"sum\")\n# Translate the counts into percentage\nconfusion.div(confusion.sum(axis=1), axis=0).apply(lambda x: round(x, 4) * 100)\n```\n\n# Query Complexity of Quantum Algorithm Versus the Classical one\n\nAfter we present the quantum algorithm, it is time to look back to classical algorithm for comparison. It is not hard to give a classical algorithm that solves Fourier Checking using $O(\\sqrt{N}) = O(2^{n/2})$ queries, which is similar as we did in the BPP section.\n\nFor some $K=\\Theta(\\sqrt{N})$, first choose sets $X=\\{x_1,\\ldots, x_K\\}$ and $Y = \\{y_1, \\ldots, y_K\\}$ of $n-$bit strings uniformly at random. Then query $f(x_i)$ and $g(y_i)$ for all $i \\in [K]$. Finally, compute\n$$\n  Z := \\sum_{i,j=1}^K f(x_i) (-1)^{x_i\\cdot y_j} g(y_j)\n$$\naccept if $|Z|$ is greater than some cutoff $cK$, and reject otherwise. For suitable $K$ and $c$, one can show that this algorithm accepts a forrelated $\\langle f, g \\rangle$ pair with probability at least $2/3$. Comparing this with $O(1)$ complexity in quantum query, we can see an exponential speedup by using quantum computer.\n\n<!-- Maybe we can find a better classical algorithm for forrelation problem, but it is proved that the lower bound on the classical query complexity is at least $\\Omega\\left(\\sqrt[4]{N}\\right) = \\Omega\\left(2^{n/4}\\right)$. -->\n\n\n# Further reading\n\nThe Forrelation problem was originally introduced in [1]. Later, a **$k$-fold Forrelation** problem was introduced in [2], which considered the forrelation between $k$ oracle functions. In that paper, it also improved the proof about the seperation of forrelation problem from $\\Omega\\left(\\sqrt[4]{N}\\right)$ to $\\tilde{\\Omega}\\left(\\sqrt{N}\\right)$, which can not be further improved. Thus, resolving an open question of Buhrman et al., there is NO partial\nBoolean function whose quantum query complexity is constant and whose randomized query complexity is linear. \n\n[1] *Scott Aaronson. BQP and the Polynomial Hierarchy. STOC \u201910, page 141\u2013150, New York, NY, USA, 2010.* [arXiv](https://arxiv.org/pdf/0910.4698.pdf)\n\n[2] *Scott Aaronson and Andris Ambainis. Forrelation: A problem that optimally separates quantum\nfrom classical computing. SIAM J. Comput., 47(3):982\u20131038, 2018.* [arXiv]( https://arxiv.org/pdf/1411.5729.pdf)\n", "meta": {"hexsha": "5d9e12d76f1cc3440aac11349085cb3be53640bd", "size": 38650, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/fourier_checking.ipynb", "max_stars_repo_name": "Saibaba-Alapati/Cirq", "max_stars_repo_head_hexsha": "782efcd04c3bbf73a0d630306a3d1cfd9966521d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3326, "max_stars_repo_stars_event_min_datetime": "2018-07-18T23:17:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:28:24.000Z", "max_issues_repo_path": "docs/tutorials/fourier_checking.ipynb", "max_issues_repo_name": "resduo/Cirq", "max_issues_repo_head_hexsha": "680f897345eb1c71c9242515edda8f04b8594319", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3443, "max_issues_repo_issues_event_min_datetime": "2018-07-18T21:07:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:23:21.000Z", "max_forks_repo_path": "docs/tutorials/fourier_checking.ipynb", "max_forks_repo_name": "resduo/Cirq", "max_forks_repo_head_hexsha": "680f897345eb1c71c9242515edda8f04b8594319", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 865, "max_forks_repo_forks_event_min_datetime": "2018-07-18T23:30:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:43:23.000Z", "avg_line_length": 43.0400890869, "max_line_length": 959, "alphanum_fraction": 0.5806468305, "converted": true, "num_tokens": 8084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22541662624228417, "lm_q2_score": 0.1581743467959293, "lm_q1q2_score": 0.03565512761281543}}
{"text": "```python\n%matplotlib inline\n```\n\n\nAdvanced: Making Dynamic Decisions and the Bi-LSTM CRF\n======================================================\n\nDynamic versus Static Deep Learning Toolkits\n--------------------------------------------\n\nPytorch is a *dynamic* neural network kit. Another example of a dynamic\nkit is `Dynet <https://github.com/clab/dynet>`__ (I mention this because\nworking with Pytorch and Dynet is similar. If you see an example in\nDynet, it will probably help you implement it in Pytorch). The opposite\nis the *static* tool kit, which includes Theano, Keras, TensorFlow, etc.\nThe core difference is the following:\n\n* In a static toolkit, you define\n  a computation graph once, compile it, and then stream instances to it.\n* In a dynamic toolkit, you define a computation graph *for each\n  instance*. It is never compiled and is executed on-the-fly\n\nWithout a lot of experience, it is difficult to appreciate the\ndifference. One example is to suppose we want to build a deep\nconstituent parser. Suppose our model involves roughly the following\nsteps:\n\n* We build the tree bottom up\n* Tag the root nodes (the words of the sentence)\n* From there, use a neural network and the embeddings\n  of the words to find combinations that form constituents. Whenever you\n  form a new constituent, use some sort of technique to get an embedding\n  of the constituent. In this case, our network architecture will depend\n  completely on the input sentence. In the sentence \"The green cat\n  scratched the wall\", at some point in the model, we will want to combine\n  the span $(i,j,r) = (1, 3, \\text{NP})$ (that is, an NP constituent\n  spans word 1 to word 3, in this case \"The green cat\").\n\nHowever, another sentence might be \"Somewhere, the big fat cat scratched\nthe wall\". In this sentence, we will want to form the constituent\n$(2, 4, NP)$ at some point. The constituents we will want to form\nwill depend on the instance. If we just compile the computation graph\nonce, as in a static toolkit, it will be exceptionally difficult or\nimpossible to program this logic. In a dynamic toolkit though, there\nisn't just 1 pre-defined computation graph. There can be a new\ncomputation graph for each instance, so this problem goes away.\n\nDynamic toolkits also have the advantage of being easier to debug and\nthe code more closely resembling the host language (by that I mean that\nPytorch and Dynet look more like actual Python code than Keras or\nTheano).\n\nBi-LSTM Conditional Random Field Discussion\n-------------------------------------------\n\nFor this section, we will see a full, complicated example of a Bi-LSTM\nConditional Random Field for named-entity recognition. The LSTM tagger\nabove is typically sufficient for part-of-speech tagging, but a sequence\nmodel like the CRF is really essential for strong performance on NER.\nFamiliarity with CRF's is assumed. Although this name sounds scary, all\nthe model is is a CRF but where an LSTM provides the features. This is\nan advanced model though, far more complicated than any earlier model in\nthis tutorial. If you want to skip it, that is fine. To see if you're\nready, see if you can:\n\n-  Write the recurrence for the viterbi variable at step i for tag k.\n-  Modify the above recurrence to compute the forward variables instead.\n-  Modify again the above recurrence to compute the forward variables in\n   log-space (hint: log-sum-exp)\n\nIf you can do those three things, you should be able to understand the\ncode below. Recall that the CRF computes a conditional probability. Let\n$y$ be a tag sequence and $x$ an input sequence of words.\nThen we compute\n\n\\begin{align}P(y|x) = \\frac{\\exp{(\\text{Score}(x, y)})}{\\sum_{y'} \\exp{(\\text{Score}(x, y')})}\\end{align}\n\nWhere the score is determined by defining some log potentials\n$\\log \\psi_i(x,y)$ such that\n\n\\begin{align}\\text{Score}(x,y) = \\sum_i \\log \\psi_i(x,y)\\end{align}\n\nTo make the partition function tractable, the potentials must look only\nat local features.\n\nIn the Bi-LSTM CRF, we define two kinds of potentials: emission and\ntransition. The emission potential for the word at index $i$ comes\nfrom the hidden state of the Bi-LSTM at timestep $i$. The\ntransition scores are stored in a $|T|x|T|$ matrix\n$\\textbf{P}$, where $T$ is the tag set. In my\nimplementation, $\\textbf{P}_{j,k}$ is the score of transitioning\nto tag $j$ from tag $k$. So:\n\n\\begin{align}\\text{Score}(x,y) = \\sum_i \\log \\psi_\\text{EMIT}(y_i \\rightarrow x_i) + \\log \\psi_\\text{TRANS}(y_{i-1} \\rightarrow y_i)\\end{align}\n\n\\begin{align}= \\sum_i h_i[y_i] + \\textbf{P}_{y_i, y_{i-1}}\\end{align}\n\nwhere in this second expression, we think of the tags as being assigned\nunique non-negative indices.\n\nIf the above discussion was too brief, you can check out\n`this <http://www.cs.columbia.edu/%7Emcollins/crf.pdf>`__ write up from\nMichael Collins on CRFs.\n\nImplementation Notes\n--------------------\n\nThe example below implements the forward algorithm in log space to\ncompute the partition function, and the viterbi algorithm to decode.\nBackpropagation will compute the gradients automatically for us. We\ndon't have to do anything by hand.\n\nThe implementation is not optimized. If you understand what is going on,\nyou'll probably quickly see that iterating over the next tag in the\nforward algorithm could probably be done in one big operation. I wanted\nto code to be more readable. If you want to make the relevant change,\nyou could probably use this tagger for real tasks.\n\n\n\n\n```python\n# Author: Robert Guthrie\n\nimport torch\nimport torch.autograd as autograd\nimport torch.nn as nn\nimport torch.optim as optim\n\ntorch.manual_seed(1)\n```\n\nHelper functions to make the code more readable.\n\n\n\n\n```python\ndef argmax(vec):\n    # return the argmax as a python int\n    _, idx = torch.max(vec, 1)\n    return idx.item()\n\n\ndef prepare_sequence(seq, to_ix):\n    idxs = [to_ix[w] for w in seq]\n    return torch.tensor(idxs, dtype=torch.long)\n\n\n# Compute log sum exp in a numerically stable way for the forward algorithm\ndef log_sum_exp(vec):\n    max_score = vec[0, argmax(vec)]\n    max_score_broadcast = max_score.view(1, -1).expand(1, vec.size()[1])\n    return max_score + \\\n        torch.log(torch.sum(torch.exp(vec - max_score_broadcast)))\n```\n\nCreate model\n\n\n\n\n```python\nclass BiLSTM_CRF(nn.Module):\n\n    def __init__(self, vocab_size, tag_to_ix, embedding_dim, hidden_dim):\n        super(BiLSTM_CRF, self).__init__()\n        self.embedding_dim = embedding_dim\n        self.hidden_dim = hidden_dim\n        self.vocab_size = vocab_size\n        self.tag_to_ix = tag_to_ix\n        self.tagset_size = len(tag_to_ix)\n\n        self.word_embeds = nn.Embedding(vocab_size, embedding_dim)\n        self.lstm = nn.LSTM(embedding_dim, hidden_dim // 2,\n                            num_layers=1, bidirectional=True)\n\n        # Maps the output of the LSTM into tag space.\n        self.hidden2tag = nn.Linear(hidden_dim, self.tagset_size)\n\n        # Matrix of transition parameters.  Entry i,j is the score of\n        # transitioning *to* i *from* j.\n        self.transitions = nn.Parameter(\n            torch.randn(self.tagset_size, self.tagset_size))\n\n        # These two statements enforce the constraint that we never transfer\n        # to the start tag and we never transfer from the stop tag\n        self.transitions.data[tag_to_ix[START_TAG], :] = -10000\n        self.transitions.data[:, tag_to_ix[STOP_TAG]] = -10000\n\n        self.hidden = self.init_hidden()\n\n    def init_hidden(self):\n        return (torch.randn(2, 1, self.hidden_dim // 2),\n                torch.randn(2, 1, self.hidden_dim // 2))\n\n    def _forward_alg(self, feats):\n        # Do the forward algorithm to compute the partition function\n        init_alphas = torch.full((1, self.tagset_size), -10000.)\n        # START_TAG has all of the score.\n        init_alphas[0][self.tag_to_ix[START_TAG]] = 0.\n\n        # Wrap in a variable so that we will get automatic backprop\n        forward_var = init_alphas\n\n        # Iterate through the sentence\n        for feat in feats:\n            alphas_t = []  # The forward tensors at this timestep\n            for next_tag in range(self.tagset_size):\n                # broadcast the emission score: it is the same regardless of\n                # the previous tag\n                emit_score = feat[next_tag].view(\n                    1, -1).expand(1, self.tagset_size)\n                # the ith entry of trans_score is the score of transitioning to\n                # next_tag from i\n                trans_score = self.transitions[next_tag].view(1, -1)\n                # The ith entry of next_tag_var is the value for the\n                # edge (i -> next_tag) before we do log-sum-exp\n                next_tag_var = forward_var + trans_score + emit_score\n                # The forward variable for this tag is log-sum-exp of all the\n                # scores.\n                alphas_t.append(log_sum_exp(next_tag_var).view(1))\n            forward_var = torch.cat(alphas_t).view(1, -1)\n        terminal_var = forward_var + self.transitions[self.tag_to_ix[STOP_TAG]]\n        alpha = log_sum_exp(terminal_var)\n        return alpha\n\n    def _get_lstm_features(self, sentence):\n        self.hidden = self.init_hidden()\n        embeds = self.word_embeds(sentence).view(len(sentence), 1, -1)\n        lstm_out, self.hidden = self.lstm(embeds, self.hidden)\n        lstm_out = lstm_out.view(len(sentence), self.hidden_dim)\n        lstm_feats = self.hidden2tag(lstm_out)\n        return lstm_feats\n\n    def _score_sentence(self, feats, tags):\n        # Gives the score of a provided tag sequence\n        score = torch.zeros(1)\n        tags = torch.cat([torch.tensor([self.tag_to_ix[START_TAG]], dtype=torch.long), tags])\n        for i, feat in enumerate(feats):\n            score = score + \\\n                self.transitions[tags[i + 1], tags[i]] + feat[tags[i + 1]]\n        score = score + self.transitions[self.tag_to_ix[STOP_TAG], tags[-1]]\n        return score\n\n    def _viterbi_decode(self, feats):\n        backpointers = []\n\n        # Initialize the viterbi variables in log space\n        init_vvars = torch.full((1, self.tagset_size), -10000.)\n        init_vvars[0][self.tag_to_ix[START_TAG]] = 0\n\n        # forward_var at step i holds the viterbi variables for step i-1\n        forward_var = init_vvars\n        for feat in feats:\n            bptrs_t = []  # holds the backpointers for this step\n            viterbivars_t = []  # holds the viterbi variables for this step\n\n            for next_tag in range(self.tagset_size):\n                # next_tag_var[i] holds the viterbi variable for tag i at the\n                # previous step, plus the score of transitioning\n                # from tag i to next_tag.\n                # We don't include the emission scores here because the max\n                # does not depend on them (we add them in below)\n                next_tag_var = forward_var + self.transitions[next_tag]\n                best_tag_id = argmax(next_tag_var)\n                bptrs_t.append(best_tag_id)\n                viterbivars_t.append(next_tag_var[0][best_tag_id].view(1))\n            # Now add in the emission scores, and assign forward_var to the set\n            # of viterbi variables we just computed\n            forward_var = (torch.cat(viterbivars_t) + feat).view(1, -1)\n            backpointers.append(bptrs_t)\n\n        # Transition to STOP_TAG\n        terminal_var = forward_var + self.transitions[self.tag_to_ix[STOP_TAG]]\n        best_tag_id = argmax(terminal_var)\n        path_score = terminal_var[0][best_tag_id]\n\n        # Follow the back pointers to decode the best path.\n        best_path = [best_tag_id]\n        for bptrs_t in reversed(backpointers):\n            best_tag_id = bptrs_t[best_tag_id]\n            best_path.append(best_tag_id)\n        # Pop off the start tag (we dont want to return that to the caller)\n        start = best_path.pop()\n        assert start == self.tag_to_ix[START_TAG]  # Sanity check\n        best_path.reverse()\n        return path_score, best_path\n\n    def neg_log_likelihood(self, sentence, tags):\n        feats = self._get_lstm_features(sentence)\n        forward_score = self._forward_alg(feats)\n        gold_score = self._score_sentence(feats, tags)\n        return forward_score - gold_score\n\n    def forward(self, sentence):  # dont confuse this with _forward_alg above.\n        # Get the emission scores from the BiLSTM\n        lstm_feats = self._get_lstm_features(sentence)\n\n        # Find the best path, given the features.\n        score, tag_seq = self._viterbi_decode(lstm_feats)\n        return score, tag_seq\n```\n\nRun training\n\n\n\n\n```python\nSTART_TAG = \"<START>\"\nSTOP_TAG = \"<STOP>\"\nEMBEDDING_DIM = 5\nHIDDEN_DIM = 4\n\n# Make up some training data\ntraining_data = [(\n    \"the wall street journal reported today that apple corporation made money\".split(),\n    \"B I I I O O O B I O O\".split()\n), (\n    \"georgia tech is a university in georgia\".split(),\n    \"B I O O O O B\".split()\n)]\n\nword_to_ix = {}\nfor sentence, tags in training_data:\n    for word in sentence:\n        if word not in word_to_ix:\n            word_to_ix[word] = len(word_to_ix)\n\ntag_to_ix = {\"B\": 0, \"I\": 1, \"O\": 2, START_TAG: 3, STOP_TAG: 4}\n\nmodel = BiLSTM_CRF(len(word_to_ix), tag_to_ix, EMBEDDING_DIM, HIDDEN_DIM)\noptimizer = optim.SGD(model.parameters(), lr=0.01, weight_decay=1e-4)\n\n# Check predictions before training\nwith torch.no_grad():\n    precheck_sent = prepare_sequence(training_data[0][0], word_to_ix)\n    precheck_tags = torch.tensor([tag_to_ix[t] for t in training_data[0][1]], dtype=torch.long)\n    print(model(precheck_sent))\n\n# Make sure prepare_sequence from earlier in the LSTM section is loaded\nfor epoch in range(\n        300):  # again, normally you would NOT do 300 epochs, it is toy data\n    for sentence, tags in training_data:\n        # Step 1. Remember that Pytorch accumulates gradients.\n        # We need to clear them out before each instance\n        model.zero_grad()\n\n        # Step 2. Get our inputs ready for the network, that is,\n        # turn them into Tensors of word indices.\n        sentence_in = prepare_sequence(sentence, word_to_ix)\n        targets = torch.tensor([tag_to_ix[t] for t in tags], dtype=torch.long)\n\n        # Step 3. Run our forward pass.\n        loss = model.neg_log_likelihood(sentence_in, targets)\n\n        # Step 4. Compute the loss, gradients, and update the parameters by\n        # calling optimizer.step()\n        loss.backward()\n        optimizer.step()\n\n# Check predictions after training\nwith torch.no_grad():\n    precheck_sent = prepare_sequence(training_data[0][0], word_to_ix)\n    print(model(precheck_sent))\n# We got it!\n```\n\nExercise: A new loss function for discriminative tagging\n--------------------------------------------------------\n\nIt wasn't really necessary for us to create a computation graph when\ndoing decoding, since we do not backpropagate from the viterbi path\nscore. Since we have it anyway, try training the tagger where the loss\nfunction is the difference between the Viterbi path score and the score\nof the gold-standard path. It should be clear that this function is\nnon-negative and 0 when the predicted tag sequence is the correct tag\nsequence. This is essentially *structured perceptron*.\n\nThis modification should be short, since Viterbi and score\\_sentence are\nalready implemented. This is an example of the shape of the computation\ngraph *depending on the training instance*. Although I haven't tried\nimplementing this in a static toolkit, I imagine that it is possible but\nmuch less straightforward.\n\nPick up some real data and do a comparison!\n\n\n\n", "meta": {"hexsha": "b66f766f8d3837d2578b1377a98ff2b5dfa91dc6", "size": 17800, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "beginner_source/nlp/5 advanced_tutorial.ipynb", "max_stars_repo_name": "davidlove/pytorch_tutorials", "max_stars_repo_head_hexsha": "72cccf8754bf799ac1270a1ad9e05f8006b39e21", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "beginner_source/nlp/5 advanced_tutorial.ipynb", "max_issues_repo_name": "davidlove/pytorch_tutorials", "max_issues_repo_head_hexsha": "72cccf8754bf799ac1270a1ad9e05f8006b39e21", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "beginner_source/nlp/5 advanced_tutorial.ipynb", "max_forks_repo_name": "davidlove/pytorch_tutorials", "max_forks_repo_head_hexsha": "72cccf8754bf799ac1270a1ad9e05f8006b39e21", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 154.7826086957, "max_line_length": 6455, "alphanum_fraction": 0.6579775281, "converted": true, "num_tokens": 3730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926197162523, "lm_q2_score": 0.07921032736951987, "lm_q1q2_score": 0.035596536525170495}}
{"text": "```python\nimport sympy as sp\nfrom sympy.parsing.sympy_parser import parse_expr\nimport pandas as pd\n```\n\n\n```python\ndef get_lines(filename):\n    file = open(filename, 'r+')\n    lines = file.readlines()\n    #\n    lines = map(lambda line : line[:-1],lines)\n    file.close()\n    return lines\n```\n\n\n```python\nlines = get_lines('./tests/ejercicio1.txt')\n```\n\n\n```python\nsyntax = pd.DataFrame(data=lines, columns=['line'])\nsyntax.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>line</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Inicio</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Lea n</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Para i=1,n,+1</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Para j=1,n,+1</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Lea A(i,,j)</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nsyntax[\"length\"] = syntax[\"line\"].map(lambda line: len(line))\nsyntax.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>line</th>\n      <th>length</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Inicio</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Lea n</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Para i=1,n,+1</td>\n      <td>13</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Para j=1,n,+1</td>\n      <td>13</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Lea A(i,,j)</td>\n      <td>11</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndef get_type(line):\n    #If not line.lower().find('x') returns true if x starts at line[0] \n    if not line.lower().find('inicio'):\n        return \"inicio\"\n    if not line.lower().find('pare'):\n        return \"pare\"\n    if not line.lower().find('para'):\n        return \"para\"\n    if not line.lower().find('lea'):\n        return \"lea\"\n    if not line.lower().find('esc'):\n        return \"esc\"\n    if not line.lower().find('fpara'):\n        return \"fpara\"\n    if not line.lower().find('sino'):\n        return \"sino\"\n    if not line.lower().find('si'):\n        return \"si\"\n    if not line.lower().find('fsi'):\n        return \"fsi\"\n    if line.lower().find('='):\n        return \"assignment\"\n    return \"Indefinite so far\"\n\nsyntax[\"type\"] = syntax[\"line\"].map(get_type)\nsyntax.head(len(syntax))\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>line</th>\n      <th>length</th>\n      <th>type</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Inicio</td>\n      <td>6</td>\n      <td>inicio</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Lea n</td>\n      <td>5</td>\n      <td>lea</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Para i=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Para j=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Lea A(i,,j)</td>\n      <td>11</td>\n      <td>lea</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Para i=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Para j=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>Lea B(i,,j)</td>\n      <td>11</td>\n      <td>lea</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>s=0</td>\n      <td>3</td>\n      <td>assignment</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>Para i=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>X=x+A(i,i)</td>\n      <td>10</td>\n      <td>assignment</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>x=0</td>\n      <td>3</td>\n      <td>assignment</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>Para i=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>Para j=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>Si (i==j)</td>\n      <td>9</td>\n      <td>si</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>x=x+B(i,j)</td>\n      <td>10</td>\n      <td>assignment</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>Fsi</td>\n      <td>3</td>\n      <td>fsi</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>Si (x&gt;s)</td>\n      <td>8</td>\n      <td>si</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>Esc \u201cx es mayor\u201d</td>\n      <td>16</td>\n      <td>esc</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>Esc x</td>\n      <td>5</td>\n      <td>esc</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>sino</td>\n      <td>4</td>\n      <td>sino</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>Esc \u201cx no es mayor\u201d</td>\n      <td>19</td>\n      <td>esc</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>Fsi</td>\n      <td>3</td>\n      <td>fsi</td>\n    </tr>\n    <tr>\n      <th>30</th>\n      <td>Pare</td>\n      <td>4</td>\n      <td>pare</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndef process_for(line):\n        raw_data = line[line.index('=')+1:]\n        split_data = raw_data.split(',')\n        print(split_data)\n        lower_bound = parse_expr(split_data[0])\n        upper_bound = parse_expr(split_data[1])\n        increment = parse_expr(split_data[2])\n        return {\n            'lower_b' : lower_bound,\n            'upper_b' : upper_bound,\n            'inc' : increment\n        }\n```\n\n\n```python\ntest_for_line = 'Para i=100,a+b,-10'\nprocess_for(test_for_line)\n```\n\n    ['100', 'a+b', '-10']\n\n\n\n\n\n    {'lower_b': 100, 'upper_b': a + b, 'inc': -10}\n\n\n\n\n```python\ndef process_if(line):\n    comparisons = [pos for pos, char in enumerate(line) if char == '(']\n    return {\n        'comparisons' : len(comparisons)\n    }\n```\n\n\n```python\n\ndef new_get_statement_runtime(syntax):\n    lines_dict_list = lines = syntax.to_dict('records')\n    order = 0\n    for index in range(len(lines_dict_list)):\n        line = lines[index]\n        # print(line['type'])\n        line_type = line['type']\n        if line_type in ('inicio','pare','sino'):\n            #order does not change\n            line['runtime'] = 0\n            # line['data'] = 'Control statement'\n            line['order'] = order\n        elif line_type in (\"assignment\",'lea','esc'):\n            line['runtime'] = 1\n            # line['data'] = 'Assignment i/o'\n            line['order'] = order\n        elif  line_type in ('fsi','fpara'):\n            order -= 1\n            line['runtime'] = 0\n            # line['data'] = 'End of block'\n            line['order'] = order\n            \n        elif line_type is 'para':\n            line['runtime'] = 'Nan'\n            line['data'] = process_for(line['line'])\n            line['order'] = order\n            order += 1\n        elif line_type is 'si':\n            line['runtime'] = 'Nan' #Number of comparisons + instructions inside\n            line['data'] = process_if(line['line'])\n            line['order'] = order\n            order +=1\n        # print(f'Line : {line}')\n\n    \n    return pd.DataFrame.from_dict(lines)\n            \n\n        \n\n\n\n\n```\n\n\n```python\nnew_syntax = new_get_statement_runtime(syntax)\nnew_syntax.head(len(new_syntax))\n```\n\n    ['1', 'n', '+1']\n    ['1', 'n', '+1']\n    ['1', 'n', '+1']\n    ['1', 'n', '+1']\n    ['1', 'n', '+1']\n    ['1', 'n', '+1']\n    ['1', 'n', '+1']\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>line</th>\n      <th>length</th>\n      <th>type</th>\n      <th>runtime</th>\n      <th>order</th>\n      <th>data</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Inicio</td>\n      <td>6</td>\n      <td>inicio</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Lea n</td>\n      <td>5</td>\n      <td>lea</td>\n      <td>1</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Para i=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n      <td>Nan</td>\n      <td>0</td>\n      <td>{'lower_b': 1, 'upper_b': n, 'inc': 1}</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Para j=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n      <td>Nan</td>\n      <td>1</td>\n      <td>{'lower_b': 1, 'upper_b': n, 'inc': 1}</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Lea A(i,,j)</td>\n      <td>11</td>\n      <td>lea</td>\n      <td>1</td>\n      <td>2</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n      <td>0</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Para i=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n      <td>Nan</td>\n      <td>0</td>\n      <td>{'lower_b': 1, 'upper_b': n, 'inc': 1}</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Para j=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n      <td>Nan</td>\n      <td>1</td>\n      <td>{'lower_b': 1, 'upper_b': n, 'inc': 1}</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>Lea B(i,,j)</td>\n      <td>11</td>\n      <td>lea</td>\n      <td>1</td>\n      <td>2</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n      <td>0</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>s=0</td>\n      <td>3</td>\n      <td>assignment</td>\n      <td>1</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>Para i=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n      <td>Nan</td>\n      <td>0</td>\n      <td>{'lower_b': 1, 'upper_b': n, 'inc': 1}</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>X=x+A(i,i)</td>\n      <td>10</td>\n      <td>assignment</td>\n      <td>1</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>x=0</td>\n      <td>3</td>\n      <td>assignment</td>\n      <td>1</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>Para i=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n      <td>Nan</td>\n      <td>0</td>\n      <td>{'lower_b': 1, 'upper_b': n, 'inc': 1}</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>Para j=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n      <td>Nan</td>\n      <td>1</td>\n      <td>{'lower_b': 1, 'upper_b': n, 'inc': 1}</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>Si (i==j)</td>\n      <td>9</td>\n      <td>si</td>\n      <td>Nan</td>\n      <td>2</td>\n      <td>{'comparisons': 1}</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>x=x+B(i,j)</td>\n      <td>10</td>\n      <td>assignment</td>\n      <td>1</td>\n      <td>3</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>Fsi</td>\n      <td>3</td>\n      <td>fsi</td>\n      <td>0</td>\n      <td>2</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n      <td>0</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>Si (x&gt;s)</td>\n      <td>8</td>\n      <td>si</td>\n      <td>Nan</td>\n      <td>0</td>\n      <td>{'comparisons': 1}</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>Esc \u201cx es mayor\u201d</td>\n      <td>16</td>\n      <td>esc</td>\n      <td>1</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>Esc x</td>\n      <td>5</td>\n      <td>esc</td>\n      <td>1</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>sino</td>\n      <td>4</td>\n      <td>sino</td>\n      <td>0</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>Esc \u201cx no es mayor\u201d</td>\n      <td>19</td>\n      <td>esc</td>\n      <td>1</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>Fsi</td>\n      <td>3</td>\n      <td>fsi</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>30</th>\n      <td>Pare</td>\n      <td>4</td>\n      <td>pare</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nnew_line = 'Si (i==j) y (j==1)'\nprocess_if(new_line)\n```\n\n\n\n\n    {'comparisons': 2}\n\n\n\n\n```python\ndef get_if_block_runtime(block_lines):\n    runtime = 0\n    for line in block_lines:\n        runtime += line['runtime']\n    return runtime\n```\n\n\n```python\ndef get_if_blocks_runtime(syntax):\n    lines_dict_list = lines = syntax.to_dict('records')\n    if_indices = [pos for pos, line in enumerate(lines) if line['type'] is 'si']\n    else_indices = [pos for pos, line in enumerate(lines) if line['type'] is 'sino']\n    end_if_indices = [pos for pos, line in enumerate(lines) if line['type'] is 'fsi']\n    # done = False\n\n    #Let's begin by processing the ifs statements\n    if_statements = []\n    for x, if_index in enumerate(if_indices):\n        #Find closing endif\n        end_if_index = end_if_indices[x]\n        #Is there an else?\n        else_index = False\n        for line_index in range(if_index,end_if_index):\n            if  line_index in else_indices:\n                else_index = line_index\n                break\n        # print((if_index,else_index,end_if_index))\n        comparisons = lines[if_index]['data']['comparisons']\n        if_runtime = comparisons\n        if else_index:\n            block_a = lines[if_index+1:else_index]\n            block_b = lines[else_index+1: end_if_index]\n            bloc_a_runtime = get_if_block_runtime(block_a)\n            bloc_b_runtime = get_if_block_runtime(block_b)\n            if_runtime += max(bloc_a_runtime,bloc_b_runtime)\n        else:\n            block = lines[if_index+1:end_if_index]\n            bloc_runtime = get_if_block_runtime(block)\n            if_runtime += bloc_runtime\n        print((if_index,else_index,end_if_index,if_runtime))\n        lines[if_index]['runtime'] = if_runtime\n    return pd.DataFrame.from_dict(lines)\n\n\n            \n\n    # print('para',for_indices)\n    # print('fpara',end_for_indices)\n    # print('si',if_indices)\n    # print('sino',else_indices)\n    # print('fsi',end_if_indices)\n\n\n```\n\n\n```python\nsyntax_with_ifs = get_if_blocks_runtime(new_syntax)\nsyntax_with_ifs.head(len(syntax_with_ifs))\n```\n\n    (19, False, 21, 2)\n    (24, 27, 29, 3)\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>line</th>\n      <th>length</th>\n      <th>type</th>\n      <th>runtime</th>\n      <th>order</th>\n      <th>data</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Inicio</td>\n      <td>6</td>\n      <td>inicio</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Lea n</td>\n      <td>5</td>\n      <td>lea</td>\n      <td>1</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Para i=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n      <td>Nan</td>\n      <td>0</td>\n      <td>{'lower_b': 1, 'upper_b': n, 'inc': 1}</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Para j=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n      <td>Nan</td>\n      <td>1</td>\n      <td>{'lower_b': 1, 'upper_b': n, 'inc': 1}</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Lea A(i,,j)</td>\n      <td>11</td>\n      <td>lea</td>\n      <td>1</td>\n      <td>2</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n      <td>0</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Para i=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n      <td>Nan</td>\n      <td>0</td>\n      <td>{'lower_b': 1, 'upper_b': n, 'inc': 1}</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Para j=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n      <td>Nan</td>\n      <td>1</td>\n      <td>{'lower_b': 1, 'upper_b': n, 'inc': 1}</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>Lea B(i,,j)</td>\n      <td>11</td>\n      <td>lea</td>\n      <td>1</td>\n      <td>2</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n      <td>0</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>s=0</td>\n      <td>3</td>\n      <td>assignment</td>\n      <td>1</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>Para i=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n      <td>Nan</td>\n      <td>0</td>\n      <td>{'lower_b': 1, 'upper_b': n, 'inc': 1}</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>X=x+A(i,i)</td>\n      <td>10</td>\n      <td>assignment</td>\n      <td>1</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>x=0</td>\n      <td>3</td>\n      <td>assignment</td>\n      <td>1</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>Para i=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n      <td>Nan</td>\n      <td>0</td>\n      <td>{'lower_b': 1, 'upper_b': n, 'inc': 1}</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>Para j=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n      <td>Nan</td>\n      <td>1</td>\n      <td>{'lower_b': 1, 'upper_b': n, 'inc': 1}</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>Si (i==j)</td>\n      <td>9</td>\n      <td>si</td>\n      <td>2</td>\n      <td>2</td>\n      <td>{'comparisons': 1}</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>x=x+B(i,j)</td>\n      <td>10</td>\n      <td>assignment</td>\n      <td>1</td>\n      <td>3</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>Fsi</td>\n      <td>3</td>\n      <td>fsi</td>\n      <td>0</td>\n      <td>2</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n      <td>0</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>Si (x&gt;s)</td>\n      <td>8</td>\n      <td>si</td>\n      <td>3</td>\n      <td>0</td>\n      <td>{'comparisons': 1}</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>Esc \u201cx es mayor\u201d</td>\n      <td>16</td>\n      <td>esc</td>\n      <td>1</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>Esc x</td>\n      <td>5</td>\n      <td>esc</td>\n      <td>1</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>sino</td>\n      <td>4</td>\n      <td>sino</td>\n      <td>0</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>Esc \u201cx no es mayor\u201d</td>\n      <td>19</td>\n      <td>esc</td>\n      <td>1</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>Fsi</td>\n      <td>3</td>\n      <td>fsi</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>30</th>\n      <td>Pare</td>\n      <td>4</td>\n      <td>pare</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# orders = []\n# for line in lines:\n#     orders.append(line['order'])\n# max_order = max(orders)\n# if max_order is 3:\n#There exists at least a combination of two nested loops with an if\n# for_indices = [pos for pos, line in enumerate(lines) if line['type'] is 'para']\n# end_for_indices = [pos for pos, line in enumerate(lines) if line['type'] is 'fpara']\n```\n\n\n```python\ndef for_runtime_formula(for_data,content_runtime):\n    lower_bound = for_data['lower_b']\n    upper_bound = for_data['upper_b']\n    try:\n        lower_bound = int(lower_bound)\n    except TypeError:\n        lower_bound = lower_bound\n    try: \n        upper_bound = int(upper_bound)\n    except TypeError:\n        upper_bound = upper_bound\n\n    increment = parse_expr(str(for_data['inc']))\n    ceil = sp.Function('ceil')\n    iterations = (ceil((upper_bound-lower_bound+1)/increment)*(content_runtime +2)) + 2\n    return iterations \n```\n\n\n```python\nint(parse_expr('8'))\n```\n\n\n\n\n    8\n\n\n\n\n```python\nlower_bound = parse_expr('n-1')\nupper_bound = parse_expr('8')\ntry:\n    lb = int(lower_bound)\nexcept TypeError:\n    lb = lower_bound\nlb + 2\n\n\n```\n\n\n\n\n$\\displaystyle n + 1$\n\n\n\n\n```python\ndef get_for_blocks_runtime(syntax):\n    lines_dict_list = lines = syntax.to_dict('records')\n    for_indices = [pos for pos, line in enumerate(lines) if line['type'] is 'para']\n    print('for_indices',for_indices)\n    endfor_indices = [pos for pos,line in enumerate(lines) if line['type'] is 'fpara']\n    print('endfor_indices',endfor_indices)\n    #get for blocks and their orders\n    block_orders = []\n    for x ,for_index in enumerate(for_indices):\n        if x < len(for_indices) -1 :\n            next_end_for = endfor_indices[x]\n            next_for = for_indices[x+1]\n            if next_for < next_end_for:\n                block_orders.append((for_index,0))\n            else:\n                block_orders.append((for_index,1))\n        else:\n            block_orders.append((for_index,1))\n    # print(block_orders)\n\n    #get inner for runtime\n    for for_index in [bloc_order[0] for bloc_order in block_orders if bloc_order[1] is 1]:\n        # print(for_index)\n        for end_for in endfor_indices:\n            if end_for > for_index:\n                break\n        for_order = lines[for_index]['order']\n        instruction_order = for_order + 1\n        inner_instructions = lines[for_index+1:end_for]\n        content_runtime = 0 #placeholder\n        for line in inner_instructions:\n            if(line['order'] is instruction_order):\n                content_runtime+= line['runtime']\n        for_runtime = for_runtime_formula(lines[for_index]['data'],content_runtime)\n        lines[for_index]['runtime'] = for_runtime\n    \n\n    #get outer for runtimes\n    for for_index in [bloc_order[0] for bloc_order in block_orders if bloc_order[1] is 0]:\n        for x, end_for in enumerate(endfor_indices):\n            if lines[end_for]['order'] == lines[for_index]['order'] and end_for >for_index:\n                break\n        for_order = lines[for_index]['order']\n        instruction_order = for_order + 1\n        inner_instructions = lines[for_index+1:end_for]\n        content_runtime = \"\" #placeholder\n        for line in inner_instructions:\n            if(line['order'] is instruction_order):\n                content_runtime += '+'+str(line['runtime'])\n        for_runtime =for_runtime_formula(lines[for_index]['data'],parse_expr(str(content_runtime)))\n        lines[for_index]['runtime'] = for_runtime \n    return pd.DataFrame.from_dict(lines)\n        \n\n\n            \n```\n\n\n```python\nsyntax_complete = get_for_blocks_runtime(syntax_with_ifs)\nsyntax_complete.head(len(syntax_complete))\n```\n\n    for_indices [2, 3, 7, 8, 13, 17, 18]\n    endfor_indices [5, 6, 10, 11, 15, 22, 23]\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>line</th>\n      <th>length</th>\n      <th>type</th>\n      <th>runtime</th>\n      <th>order</th>\n      <th>data</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Inicio</td>\n      <td>6</td>\n      <td>inicio</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Lea n</td>\n      <td>5</td>\n      <td>lea</td>\n      <td>1</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Para i=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n      <td>(3*ceil(n) + 4)*ceil(n) + 2</td>\n      <td>0</td>\n      <td>{'lower_b': 1, 'upper_b': n, 'inc': 1}</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Para j=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n      <td>3*ceil(n) + 2</td>\n      <td>1</td>\n      <td>{'lower_b': 1, 'upper_b': n, 'inc': 1}</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Lea A(i,,j)</td>\n      <td>11</td>\n      <td>lea</td>\n      <td>1</td>\n      <td>2</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n      <td>0</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Para i=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n      <td>(3*ceil(n) + 4)*ceil(n) + 2</td>\n      <td>0</td>\n      <td>{'lower_b': 1, 'upper_b': n, 'inc': 1}</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Para j=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n      <td>3*ceil(n) + 2</td>\n      <td>1</td>\n      <td>{'lower_b': 1, 'upper_b': n, 'inc': 1}</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>Lea B(i,,j)</td>\n      <td>11</td>\n      <td>lea</td>\n      <td>1</td>\n      <td>2</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n      <td>0</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>s=0</td>\n      <td>3</td>\n      <td>assignment</td>\n      <td>1</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>Para i=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n      <td>3*ceil(n) + 2</td>\n      <td>0</td>\n      <td>{'lower_b': 1, 'upper_b': n, 'inc': 1}</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>X=x+A(i,i)</td>\n      <td>10</td>\n      <td>assignment</td>\n      <td>1</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>x=0</td>\n      <td>3</td>\n      <td>assignment</td>\n      <td>1</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>Para i=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n      <td>(4*ceil(n) + 4)*ceil(n) + 2</td>\n      <td>0</td>\n      <td>{'lower_b': 1, 'upper_b': n, 'inc': 1}</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>Para j=1,n,+1</td>\n      <td>13</td>\n      <td>para</td>\n      <td>4*ceil(n) + 2</td>\n      <td>1</td>\n      <td>{'lower_b': 1, 'upper_b': n, 'inc': 1}</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>Si (i==j)</td>\n      <td>9</td>\n      <td>si</td>\n      <td>2</td>\n      <td>2</td>\n      <td>{'comparisons': 1}</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>x=x+B(i,j)</td>\n      <td>10</td>\n      <td>assignment</td>\n      <td>1</td>\n      <td>3</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>Fsi</td>\n      <td>3</td>\n      <td>fsi</td>\n      <td>0</td>\n      <td>2</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n      <td>0</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>Fpara</td>\n      <td>5</td>\n      <td>fpara</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>Si (x&gt;s)</td>\n      <td>8</td>\n      <td>si</td>\n      <td>3</td>\n      <td>0</td>\n      <td>{'comparisons': 1}</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>Esc \u201cx es mayor\u201d</td>\n      <td>16</td>\n      <td>esc</td>\n      <td>1</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>Esc x</td>\n      <td>5</td>\n      <td>esc</td>\n      <td>1</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>sino</td>\n      <td>4</td>\n      <td>sino</td>\n      <td>0</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>Esc \u201cx no es mayor\u201d</td>\n      <td>19</td>\n      <td>esc</td>\n      <td>1</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>Fsi</td>\n      <td>3</td>\n      <td>fsi</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>30</th>\n      <td>Pare</td>\n      <td>4</td>\n      <td>pare</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ntest_for_data = {'lower_b': parse_expr('1'), 'upper_b': parse_expr('n'), 'inc': parse_expr(str(1))}\nfor_runtime_formula(test_for_data,2)\n```\n\n\n\n\n$\\displaystyle 4 \\operatorname{ceil}{\\left(n \\right)} + 2$\n\n\n\n\n```python\nceil = sp.Function('ceil')\nupper_bound = parse_expr('n')\nlower_bound = parse_expr('3')\nincrement = parse_expr('2')\niterations = ceil((upper_bound-lower_bound)/increment)\niterations\n```\n\n\n\n\n$\\displaystyle \\operatorname{ceil}{\\left(\\frac{n}{2} - \\frac{3}{2} \\right)}$\n\n\n\n\n```python\ndef get_runtime(syntax_complete):\n    lines = syntax_complete.to_dict('records')\n    runtime = parse_expr('0')\n    for line in lines:\n        if line['order'] is 0:\n            runtime += line['runtime']\n    return runtime\n```\n\n\n```python\nstr(sp.simplify(get_runtime(syntax_complete)))\n```\n\n\n\n\n    '10*ceil(n)**2 + 15*ceil(n) + 14'\n\n\n", "meta": {"hexsha": "cb32bc3adcbd8f2224af82f19f3a7cfe064cdf0f", "size": 56778, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "parser.ipynb", "max_stars_repo_name": "gaabgonca/pseudocode_parser", "max_stars_repo_head_hexsha": "b8c75856ca6fe2d213a681c966ba2f7a1f9f8524", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "parser.ipynb", "max_issues_repo_name": "gaabgonca/pseudocode_parser", "max_issues_repo_head_hexsha": "b8c75856ca6fe2d213a681c966ba2f7a1f9f8524", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "parser.ipynb", "max_forks_repo_name": "gaabgonca/pseudocode_parser", "max_forks_repo_head_hexsha": "b8c75856ca6fe2d213a681c966ba2f7a1f9f8524", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.877076412, "max_line_length": 5969, "alphanum_fraction": 0.3753390398, "converted": true, "num_tokens": 11836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.07585817427579646, "lm_q1q2_score": 0.035561601053473425}}
{"text": "# Announcements\n\n* Chart of the Nuclides \n* Let's talk about what submitting with a jupyter notebook would look like\n* For future homeworks, you do not need to submit each problem as a separate page. Instead, make sure to tag *each problem* with the page it is associated with. That is, if you solved problems 3, 4, and 5 on page 2 of your homework, each one needs to be tagged as being on page 2. \n* Number density problem! \n* A quick review on the end of lecture on Monday\n\n# Nuclear Energetics\n\n## Learning Objectives\n\n- Define: exothermic and endothermic reactions\n- Differentiate exothermic and endothermic reactions\n- Calculate binding energies\n- Recognize the noation for various binary reactions\n- Recognize the physics in common binary reactions\n- Define the relationship between the Q value, mass, and energy in a reaction\n- Explain the role of energy conservation in binary reactions\n- Explain the role of charge conservation in binary reactions\n- Calculate Q values for various reactions\n\n\n## Endothermic and Exothermic Reactions\n\nIn any reaction (nuclear, mechanical, chemical) energy can be either emitted or absorbed.\n\n- When energy is emitted by the reaction, this is called **_exothermic_**.\n- When energy is absorbed into the reaction, this is called **_endothermic_**.\n\nIf we consider the energy in relation to mass via Einstein's equivalence, then it's very clear that a change in the mass of reactants will result in a change in energy ($\\Delta E = \\Delta M c^2$).\n\n\\begin{align}\n\\mbox{reactants} &\\rightarrow \\mbox{products}\\\\\nA + B + \\cdots &\\rightarrow C + D + \\cdots\\\\\n\\Delta M = (M_A + M_B + \\cdots) &- (M_C + M_D + \\cdots)\\\\\n\\implies \\Delta E &= \\left[(M_A + M_B + \\cdots) - (M_C + M_D + \\cdots)\\right]c^2\\\\\n\\end{align}\n\n\n\n<center>(credit: BBC)</center>\n\n## Exercise: Think-pair-share\n\nWhich of the following are exothermic and which are endothermic?\n\n- Boiling Water\n- Lighting a match\n- Freezing an ice cube\n- Melting an ice cube\n- Snow formation in the clouds\n- Conversion of frost to water vapor on the grass\n\nHarder ones: \n- Formation of ion pairs (exothermic)\n- Separation of ion pairs (endothermic)\n\nThe most important one:\n- nuclear fission\n\n# Nuclear Reactions\n\nWhen we talk about nuclear reactions, we use a similar notation in chemistry with the reactants (our initial state) on the left and the products (after the reaction) on the right. \n\n\\begin{align}\n\\mbox{reactants} &\\rightarrow \\mbox{products}\\\\\nA + B &\\rightarrow C + D\\\\\n\\end{align}\n\nThere are four fundamental rules that must be followed to satisfy these reactions:\n1. *Conservation of nucleons*\n2. *Conservation of charge*\n3. *Conservation of moomentum*\n4. *Conservation of energy* - this includes kinetic and rest mass energy\n\n\n### Exercise: Think-pair-share\n\nWhy do you think rule 1 is conservation of nucleons and not explicitly conservation of neutrons and protons? \n\n# Binding Energy\n\nLast lecture, we discussed how the binding energy tells us how *tightly bound* nucleons are in the nucleus. All nuclei will have a mass slightly less than their constituent parts. This represents the energy needed to keep the nucleons bound in the nucleus. The term we use for this is the binding energy. \n\n## Binding Energy of the nucleus\n\nA nucleus, with Z protons and N=A-Z neutrons will have a formation reaction that looks like:\n\n\\begin{align}\nZ \\mbox{ protons } + (A \u2212 Z) \\mbox{ neutrons }\\rightarrow \\mbox{ nucleus}\\left(^A_ZX\\right) + BE.\n\\end{align}\n\nIt can be helpful to define the term $BE/c^2$:\n\n\\begin{align}\n\\frac{BE}{c^2} &=Zm_p +(A\u2212Z)m_n \u2212 m\\left(^A_ZX\\right)\\\\\n\\end{align}\n\nSo, this means the binding energy is the difference between the constituent parts of the atom and its measured mass. \n\nWe also know that there exists a mass energy equivalence, so we can convert from this mass difference to an energy difference. \n\nThus, we can arrive at the nuclear binding energy from this:\n\n\n\\begin{align}\nBE\\left(^A_ZX\\right) = \\left[ZM(\\left(^1_1H\\right) + (A-Z)m_n - M\\left(^A_ZX\\right)\\right]c^2\n\\end{align}\n\n### Exercise: Nuclear binding energy \n\nFrom your book, example 4.1: What is the binding energy of an alpha particle?\n\nWhen calculating Q values and Binding Energies, make sure that your proton and electron masses *always* balance. This is why you'll see $M(^1_1H)$ rather than the proton mass in our balancing equations. \n\nThere are three ways one might choose:\n\\begin{align}\nBE\\left(^4_2 He\\right) &= \\left[2m_p + 2m_n\\right]-m\\left(^4_2He\\right)\\\\\nBE\\left(^4_2 He\\right) &= \\left[2m_p + 2m_n\\right]-M\\left(^4_2He\\right)\\\\\nBE\\left(^4_2 He\\right) &= \\left[2M\\left(^1_1H\\right) + 2m_n\\right]-M\\left(^4_2He\\right)\\\\\n\\end{align}\n\n**Think pair share**\nTwo of these are correct and one isn't. Which ones are which? \n\n\n\nLet us proceed with the final method in our above equations\n\n\\begin{align}\n\\frac{BE}{c^2} &=Zm_p +(A\u2212Z)m_n \u2212 m\\left(^A_ZX\\right)\\\\\n\\implies\\frac{BE}{c^2} &=\\left[ZM(\\left(^1_1H\\right) + (A-Z)m_n - M\\left(^A_ZX\\right)\\right]\\\\\n &=\\left[2M(\\left(^1_1H\\right) + 2m_n - M\\left(^4_2He\\right)\\right]\\\\\n &=\\left[2\\left(1.0078250\\right) + 2\\left(1.0086649\\right) - 4.0026032\\right]\\\\\n\\end{align}\n\nThus:\n\n\\begin{align}\nBE\\left(^4_2 He\\right) &= \\frac{BE}{c^2}\\times 931.5 (MeV/u) \\\\\n&= 28.30 MeV.\n\\end{align}\n\n## Binding Energy per nucleon\n\nThe BE/A versus A curve immediately suggests two ways to extract energy from the nucleus.\n\n\n\nBinding energy curve **(average binding energy per nucleon in MeV against number of nucleons in nucleus)** for a number of relatively common (abundant) isotopes (not chosen systematically; almost anything with an occurence of over .2 was chosen though a few exceptions are in there, such as U235). A few important ones for the purposes of nuclear fusion and nuclear fission are marked, as well as iron-56, which sits at the highest point on this graph and cannot yield energy from fusion or fission.\n\nFrom your book (Shultis and Faw)\n\n> Most isotopes of an element are radioactive, i.e., their nuclei are unstable. To better understand what makes a nucleus stable, it is instructive to plot the BE per nucleon, BE/A, of all the isotopes of an element. For example, if one calculates the BE/A for all the isotopes of calcium (Z = 20), as is done in Example 4.2 for one isotope, and plots BE/A versus the neutron number N, a plot like that shown in Fig. 4.2 is obtained. The BE/A rapidly rises as N increase from A = 14 and reaches a broad maximum before rapidly decreasing as N increases above 30. It is in the broad maximum where the BE/A is highest that one finds the stable isotopes. The reason for the zig-zag shape in the maximum region is due to the fact that an isotope with an even number of neutrons tends to have a higher BE/A compared\n\n### Fusion\n\n**Two light nuclei $\\longrightarrow$ one heavy nucleus**\n\n\\begin{align}\n^{2}_1H + ^2_1H \\longrightarrow ^{4}_2He\n\\end{align}\n\n\n### Fission\n**One heavy nucleus $\\longrightarrow$ two lighter nuclei**\n\n\\begin{align}\n^{235}_{92}U + ^1_0n \\longrightarrow \\left(^{236}_{92}U\\right)^*  \\longrightarrow ^{139}_{56}Ba +  ^{94}_{36}Kr + 3^1_0n\n\\end{align}\n\n<a title=\"JWB at en.wikipedia [CC BY 3.0 \n (https://creativecommons.org/licenses/by/3.0\n) or GFDL (http://www.gnu.org/copyleft/fdl.html)], via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File:ThermalFissionYield.svg\"></a>\n\n\n## Nucleon Separation Energy\n\nThe energy required to remove a single nucleon from a nucleus is called \"separation energy\". Consider the addition of a single neutron to form the nucleus of $^A_ZX$, i.e.,\n\n\\begin{align}\n^{A-1}_ZX + ^1_0n \\rightarrow ^{A}_ZX.\n\\end{align}\n\n$S_n\\left(^A_ZX\\right)$ is the energy released in this reaction and is equivalent to the energy required to remove (or separate) a single neutron from the nucleus $^A_ZX$. \n\n\\begin{align}\nS_n\\left(^A_ZX\\right) &= [m\\left(^{A-1}_ZX\\right) + m_n \u2212 m\\left(^{A}_ZX\\right)]c^2 \\\\\n &\\simeq [M\\left(^{A-1}_ZX\\right) + m_n \u2212 M\\left(^{A}_ZX\\right)]c^2.\t\n\\end{align}\n\nIf we make the substition for nuclear binding energy, where binding energy is:\n\n\n\\begin{align}\nBE\\left(^A_ZX\\right) = \\left[ZM(\\left(^1_1H\\right) + (A-Z)m_n - M\\left(^A_ZX\\right)\\right]c^2\n\\end{align}\n\nWe can see that the separation energy is the difference between the binding energies of the initial and final nucleons:\n\n\\begin{align}\nS_n\\left(^A_ZX\\right) &= BE\\left(^A_ZX\\right) - BE\\left(^{A-1}_ZX\\right)\n\\end{align}\n\n### $S_p$\n\nThe equation for the separation energy of the proton is very similar to the separation energy of the neutron.\n\n\\begin{align}\nS_p\\left(^{A}_ZX\\right) &= [m\\left(^{A-1}_{Z-1}X\\right) + m_p \u2212 m\\left(^{A}_ZX\\right)]c^2 \\\\\n &\\simeq [M\\left(^{A-1}_{Z-1}X\\right) + M\\left(^1_1H\\right) \u2212 M\\left(^{A}_ZX\\right)]c^2\\\\\t\n\\end{align}\n\n\n## Exercise: Nucleon Separation Energy\n(Example 4.3 in Shultis and Faw)\n\nWhat is the binding energy of the last neutron in $^{16}_8O$? This is the energy released in the reaction: \n\\begin{align}\n^{15}_8O + ^1_0n \\rightarrow ^{16}_8O\n\\end{align}\n\nSo, we can use the equation above and plug in the mass values we can find in the book appendix.\n\n\\begin{align}\nS_n\\left(^{A}_ZX\\right) &= [m\\left(^{A-1}_ZX\\right) + m_n \u2212 m\\left(^{A}_ZX\\right)]c^2 \\\\\n &\\simeq [M\\left(^{A-1}_ZX\\right) + m_n \u2212 M\\left(^{A}_ZX\\right)]c^2\\\\\t\n\\implies S_n &= [m\\left(^{15}_8O\\right) + m_n \u2212 m\\left(^{16}_8O\\right)]c^2 \\\\\n &\\simeq [M\\left(^{15}_8X\\right) + m_n \u2212 M\\left(^{16}_8X\\right)]c^2\\\\\n &=[15.0030654 + 1.00866492 \u2212 15.9949146] u \\times 931.5 MeV/u\\\\\n &= 15.66 MeV.\n\\end{align}\n\nThis is a very high value for a single nucleon. \n\n### Think-Pair-Share\n\nWhat does this high value mean about the comparative stability of $^{16}_8O$ and $^{15}_8O$?\n\n### Think-Pair-Share\n\nAs engineers, why should we care about high neutron separation energies in materials? \n\n## Binary Nuclear Reactions\n\nWe will refer to the reaction $x+X\\longrightarrow Y+ y$ as :\n\n\\begin{align}\n(x, y)\n\\end{align}\n\nwhich is shorthand for $X(x,y)Y$. The very long form of this reaction is:\n\n\n\\begin{align}\n^{A}_{Z}X + ^{A}_{Z}x \\longrightarrow ^{A}_{Z}Y + ^{A}_{Z}y\n\\end{align}\n\n\n\n### $(\\alpha, p)$\n\nThis  was first seen in air by Rutherford. Protons were produced when alpha particles were absorbed by nitrogen in the air to make oxygen. That example follows.\n\n\\begin{align}\n\\alpha + ^{14}_{7}N \\longrightarrow ^{17}_{8}O + ^{1}_{1}H\n\\end{align}\n\n### $(\\alpha, n)$\n\nThis  was first seen with beryllium by Chadwick. Neutrons were produced when alpha particles were absorbed by beryllium in the air to make carbon. That example follows.\n\n\n\\begin{align}\n\\alpha + ^{9}_{4}Be \\longrightarrow ^{12}_{6}C + ^{1}_{0}n\n\\end{align}\n\n\n\n### $(\\gamma, n)$\n\nNeutrons can also be produced when very energetic photons strike a nucleus. An example follows.\n\n\\begin{align}\n\\gamma + ^{2}_{1}H \\longrightarrow ^{1}_{1}H + ^{1}_{0}n\n\\end{align}\n\n\n\n### $(p, \\gamma)$\n\nThis is typically called \"radiative capture\" of a proton.  An example follows.\n\n\\begin{align}\n^1_1p + ^{7}_{3}Li \\longrightarrow ^{8}_{4}Be + \\gamma\n\\end{align}\n\nInterestingly, in this example, the resulting beryllium nucleus is poorly bound and becomes two alphas.\n\n\n\n\n### $(\\gamma, \\alpha n)$\n\nSometimes, more than two products can be produced. An example follows.\n\n\\begin{align}\n\\gamma + ^{17}_{8}O \\longrightarrow ^{12}_{6}C + ^{4}_{2}He + ^{1}_{0}n\n\\end{align}\n\n\n\n\n### $(n, p)$\n\nFast neutrons are very common in nculear reactor cores and can produce liberate protons.  An example follows.\n\n\\begin{align}\n^{1}_{0}n + ^{16}_{8}O \\longrightarrow ^{16}_{7}N + ^{1}_{1}p\n\\end{align}\n\n\n### $(n, \\gamma)$\n\nMost free neutrons in a reactor are fated to be radiatively captured.\n\n\\begin{align}\n^{1}_{0}n + ^{238}_{92}U \\longrightarrow ^{239}_{92}U + \\gamma\n\\end{align}\n\n\n\n\n\n## Q-Value For a Reaction\n\nEnergy is conserved in nuclear reactions. Specifically, the _total energy_ is conserved.\n\nThe total energy, recall, includes rest mass energy as well as kinetic energy.\n\n\\begin{align}\n\\sum_i \\left[E_i + m_ic^2\\right] &= \\sum_i\\left[E'_i + m'_ic^2\\right]\\\\\n\\mbox{where }&\\\\\nE_i &= \\mbox{the kinetic energy of the ith initial particle }\\\\\nE'_i &=\\mbox{the kinetic energy of the ith final particle }\\\\\nm_i &= \\mbox{rest mass of the ith initial particle}\\\\\nm'_i &= \\mbox{rest mass of the ith final particle}\\\\\n\\end{align}\n\nChanges in kinetic energy between the initial and final states must be balanced by equivalent changes in total rest mass. **The Q-value is the kinetic energy gained in the reaction.**\n\n\n\\begin{align}\nQ &= (\\mbox{KE of final particles}) \u2212 (\\mbox{KE of initial particles})\\\\\n &= \\left(\\sum_iE'_i\\right) \u2212 \\left(\\sum_iE_i\\right) \\\\\n\\end{align}\n\n**The Q-value is equivalently the rest mass energy lost in the reaction.**\n\n\\begin{align}\nQ &= (\\mbox{rest mass of initial particles})c^2 \u2212 (\\mbox{rest mass of final particles})c^2\\\\\n  &= \\left(\\sum_im_i\\right)c^2 \u2212 \\left(\\sum_im'_i\\right)c^2 \\\\\n\\end{align}\n\n### Think-pair-share: Exothermic or Endothermic\n\nIf $Q<0$, is the reaction exothermic or endothermic?\n\n\n### Q-value in binary reactions\n\nFor an $X(x, y)Y$ reaction: \n\n\\begin{align}\nQ &= \\left(E_y + E_Y \\right) \u2212 \\left(E_x + E_X\\right) \\\\\n  &= \\left( m_x + m_X\\right)c^2 \u2212 \\left( m_y + m_Y\\right)c^2 \\\\\n\\end{align}\n\n**If proton numbers (and therefore electron masses) are conserved,** we can use the neutral atom masses and simplify this to:\n\n\\begin{align}\nQ &= \\left(E_y + E_Y \\right) \u2212 \\left(E_x + E_X\\right) \\\\\n  &= \\left( M_x + M_X\\right)c^2 \u2212 \\left( M_y + M_Y\\right)c^2 \\\\\n\\end{align}\n\n### Q-value in decay reactions\nFor a radioactive decay reaction:\n\n\\begin{align}\nX\\longrightarrow Y+ y\n\\end{align}\n\nThe corresponding Q-value is:\n\\begin{align}\nQ&=(E_y +E_Y)\\\\\n&=[m_X \u2212(m_y +m_Y )]c^2 \\\\\n\\end{align}\n\nNote that radioactive decay, being spontaneous, is **always exothermic**. So, $Q>0$ for all decay reactions. \n\n### Total Charge Conservation\n\nCharge is always conserved in nuclear reactions. Thus, we might get into trouble with reactions that drive a change in electron number. The mass of the electron should be managed carefully in these cases. In an $n, p$ reaction, a proton is ejected from the nucleus by the incident neutron. During this process, an orbital electron is usually also lost from the resulting product atom.  Thus, we must include an extra electron in the equation. \n\n**Does the electron $_{-1}^0e$ belong on the right hand side (products) or the left hand side (reactants) of the following reaction?**\n\n\\begin{align}\n^1_0n + ^{16}_8O \\longrightarrow ^{16}_7N + ^1_1p\n\\end{align}\n\n\n\n### Special case for changing proton number\n\nThe above procedure is further complicated in cases when the number of protons and the number of neutrons are not conserved. These reactions involve the nuclear weak force.\n\n**The nuclear _weak force_ alters neutrons into protons and vice versa, usually inside the nucleus.**\n\nThe details are provided in an example in your book. Effectively, the neutrinos which moderate this reaction must be considered among the products and reactants. This is why we have neutrinos in $\\beta$ decay equations (which we will talk about next week)\n\n## Special case for excited products\n\nMany of the reactions we're  most interested in as nuclear engineers involve an intermediate excited compound nucleus. \n\nLet's consider Example 4.6 in your book regarding the reaction $^{10}B + ^1_0n \\longrightarrow \\left(^7Li\\right)^*$. In short hand, this is an $(n,\\alpha)$ reaction. Specifically,  $^{10}B(n,\\alpha)^7Li^\u2217$. The product, $\\left(^7Li\\right)^*$ is left in an excited state. Specifically it is left 0.48 MeV above its ground state.\n\nThe ordinary neutral atomic masses approach would look like this:\n\n\\begin{align}\nQ &= \\left[m_n + M\\left(^{10}_5B\\right) \u2212  M\\left(^{4}_2He\\right) - M\\left(^{7}_3Li\\right)^*\\right]c^2 \\\\\n\\end{align}\n\n\nBut, the mass tabulated for $M\\left(^{7}_3Li\\right)$ is the ground state mass. So if we want to use that ground state mass to arrive at the solution, the extra energy contributing to the excited state needs to be accounted for.\n\n\n\\begin{align}\nQ &= \\left[m_n + M\\left(^{10}_5B\\right) \u2212  M\\left(^{4}_2He\\right) - M\\left(^{7}_3Li\\right)\\right]c^2 -0.48MeV\\\\\n\\end{align}\n\n\n\n\n\n## Some final thoughts on density changes\n\n\n```python\n\n```\n", "meta": {"hexsha": "d6606b77fe59cb0fe153ce57d42fb8125a7a45f3", "size": 23093, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "10.04-energetics/00-energetics.ipynb", "max_stars_repo_name": "npre247/npre247", "max_stars_repo_head_hexsha": "2960184fbd3caef6c052dc22bf6f62bab81af21b", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-01-31T17:44:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T19:54:50.000Z", "max_issues_repo_path": "10.04-energetics/00-energetics.ipynb", "max_issues_repo_name": "npre247/npre247", "max_issues_repo_head_hexsha": "2960184fbd3caef6c052dc22bf6f62bab81af21b", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2022-01-28T20:32:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T17:43:54.000Z", "max_forks_repo_path": "10.04-energetics/00-energetics.ipynb", "max_forks_repo_name": "npre247/npre247", "max_forks_repo_head_hexsha": "2960184fbd3caef6c052dc22bf6f62bab81af21b", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2022-01-24T16:47:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T04:09:25.000Z", "avg_line_length": 39.884283247, "max_line_length": 818, "alphanum_fraction": 0.5845061274, "converted": true, "num_tokens": 4856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25683199138751883, "lm_q2_score": 0.13846179412408713, "lm_q1q2_score": 0.03556141831597795}}
{"text": "##### Copyright 2020 The Cirq Developers\n\n\n```\n#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# Cirq basics\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n  <td>\n    <a target=\"_blank\" href=\"https://quantumai.google/cirq/tutorials/basics\">View on QuantumAI</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/Cirq/blob/master/docs/tutorials/basics.ipynb\">Run in Google Colab</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://github.com/quantumlib/Cirq/blob/master/docs/tutorials/basics.ipynb\">View source on GitHub</a>\n  </td>\n  <td>\n    <a href=\"https://storage.googleapis.com/tensorflow_docs/Cirq/docs/tutorials/basics.ipynb\">Download notebook</a>\n  </td>\n</table>\n\nThis tutorial will teach the basics of how to use Cirq.  This tutorial will walk through how to use qubits, gates, and operations to create and simulate your first quantum circuit using Cirq.  It will briefly introduce devices, unitary matrices, decompositions, and optimizers.\n\nThis tutorial isn\u2019t a quantum computing 101 tutorial, we assume familiarity of quantum computing at about the level of the textbook \u201cQuantum Computation and Quantum Information\u201d by Nielsen and Chuang.\n\nFor more in-depth examples closer to those found in current work, check out our tutorials page.\n\nTo begin, please follow the instructions for [installing Cirq](../install.md).\n\nNote: this notebook relies on unreleased Cirq features. If you want to try these features, make sure you install cirq via `pip install cirq --pre`.\n\n\n```\ntry:\n    import cirq\nexcept ImportError:\n    print(\"installing cirq...\")\n    !pip install --quiet cirq --pre\n    print(\"installed cirq.\")\n```\n\n## Qubits\n\nThe first part of creating a quantum circuit is to define a set of qubits (also known as a quantum registers) to act on.\n\nCirq has three main ways of defining qubits:\n\n*   `cirq.NamedQubit`: used to label qubits by an abstract name\n*   `cirq.LineQubit`: qubits labelled by number in a linear array \n*   `cirq.GridQubit`: qubits labelled by two numbers in a rectangular lattice.\n\nHere are some examples of defining each type of qubit.\n\n\n```\nimport cirq\nimport cirq_google\n\n# Using named qubits can be useful for abstract algorithms\n# as well as algorithms not yet mapped onto hardware.\nq0 = cirq.NamedQubit('source')\nq1 = cirq.NamedQubit('target')\n\n# Line qubits can be created individually\nq3 = cirq.LineQubit(3)\n\n# Or created in a range\n# This will create LineQubit(0), LineQubit(1), LineQubit(2)\nq0, q1, q2 = cirq.LineQubit.range(3)\n\n# Grid Qubits can also be referenced individually\nq4_5 = cirq.GridQubit(4,5)\n\n# Or created in bulk in a square\n# This will create 16 qubits from (0,0) to (3,3)\nqubits = cirq.GridQubit.square(4)\n```\n\nThere are also pre-packaged sets of qubits called [Devices](../devices.md).  These are qubits along with a set of rules of how they can be used.  A `cirq.Device` can be used to apply adjacency rules and other hardware constraints to a quantum circuit.  For our example, we will use the `cirq_google.Foxtail` device that comes with cirq.  It is a 2x11 grid that mimics early hardware released by Google.\n\n\n```\nprint(cirq_google.Foxtail)\n```\n\n    (0, 0)\u2500\u2500\u2500(0, 1)\u2500\u2500\u2500(0, 2)\u2500\u2500\u2500(0, 3)\u2500\u2500\u2500(0, 4)\u2500\u2500\u2500(0, 5)\u2500\u2500\u2500(0, 6)\u2500\u2500\u2500(0, 7)\u2500\u2500\u2500(0, 8)\u2500\u2500\u2500(0, 9)\u2500\u2500\u2500(0, 10)\n    \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502\n    \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502\n    (1, 0)\u2500\u2500\u2500(1, 1)\u2500\u2500\u2500(1, 2)\u2500\u2500\u2500(1, 3)\u2500\u2500\u2500(1, 4)\u2500\u2500\u2500(1, 5)\u2500\u2500\u2500(1, 6)\u2500\u2500\u2500(1, 7)\u2500\u2500\u2500(1, 8)\u2500\u2500\u2500(1, 9)\u2500\u2500\u2500(1, 10)\n\n\n## Gates and operations\n\nThe next step is to use the qubits to create operations that can be used in our circuit.  Cirq has two concepts that are important to understand here:\n\n*   A `Gate` is an effect that can be applied to a set of qubits.  \n*   An `Operation` is a gate applied to a set of qubits.\n\nFor instance, `cirq.H` is the quantum [Hadamard](https://en.wikipedia.org/wiki/Quantum_logic_gate#Hadamard_(H)_gate) and is a `Gate` object.  `cirq.H(cirq.LineQubit(1))` is an `Operation` object and is the Hadamard gate applied to a specific qubit (line qubit number 1).\n\nMany textbook gates are included within cirq.  `cirq.X`, `cirq.Y`, and `cirq.Z` refer to the single-qubit Pauli gates.  `cirq.CZ`, `cirq.CNOT`, `cirq.SWAP` are a few of the common two-qubit gates.  `cirq.measure` is a macro to apply a `MeasurementGate` to a set of qubits.  You can find more, as well as instructions on how to creats your own custom gates, on the [Gates documentation](../gates.ipynb) page.\n\nMany arithmetic operations can also be applied to gates.  Here are some examples:\n\n\n```\n# Example gates\nnot_gate = cirq.CNOT\npauli_z = cirq.Z\n\n# Using exponentiation to get square root gates\nsqrt_x_gate = cirq.X**0.5\n\n# Some gates can also take parameters\nsqrt_sqrt_y = cirq.YPowGate(exponent=0.25)\n\n# Example operations\nq0, q1 = cirq.LineQubit.range(2)\nz_op = cirq.Z(q0)\nnot_op = cirq.CNOT(q0, q1)\nsqrt_iswap_op = cirq.SQRT_ISWAP(q0, q1)\n```\n\n## Circuits and moments\n\nWe are now ready to construct a quantum circuit.  A `Circuit` is a collection of `Moment`s. A `Moment` is a collection of `Operation`s that all act during the same abstract time slice.  Each `Operation` must have a disjoint set of qubits from the other `Operation`s in the `Moment`.  A `Moment` can be thought of as a vertical slice of a quantum circuit diagram.\n\nCircuits can be constructed in several different ways.  By default, cirq will attempt to slide your operation into the earliest possible `Moment` when you insert it.\n\n\n\n```\ncircuit = cirq.Circuit()\n# You can create a circuit by appending to it\ncircuit.append(cirq.H(q) for q in cirq.LineQubit.range(3))\n# All of the gates are put into the same Moment since none overlap\nprint(circuit)\n```\n\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\n    \n    1: \u2500\u2500\u2500H\u2500\u2500\u2500\n    \n    2: \u2500\u2500\u2500H\u2500\u2500\u2500\n\n\n\n```\n# We can also create a circuit directly as well:\nprint(cirq.Circuit(cirq.SWAP(q, q+1) for q in cirq.LineQubit.range(3)))\n```\n\n    0: \u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n          \u2502\n    1: \u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n              \u2502\n    2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\n                  \u2502\n    3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\n\n\nSometimes, you may not want cirq to automatically shift operations all the way to the left.  To construct a circuit without doing this, you can create the circuit moment-by-moment or use a different `InsertStrategy`, explained more in the [Circuit documentation](../circuits.ipynb).\n\n\n```\n# Creates each gate in a separate moment.\nprint(cirq.Circuit(cirq.Moment([cirq.H(q)]) for q in cirq.LineQubit.range(3)))\n```\n\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\n\n\n### Circuits and devices\n\nOne important consideration when using real quantum devices is that there are often hardware constraints on the circuit.  Creating a circuit with a `Device` will allow you to capture some of these requirements.  These `Device` objects will validate the operations you add to the circuit to make sure that no illegal operations are added.\n\nLet's look at an example using the Foxtail device.\n\n\n```\nq0 = cirq.GridQubit(0, 0)\nq1 = cirq.GridQubit(0, 1)\nq2 = cirq.GridQubit(0, 2)\nadjacent_op = cirq.CZ(q0, q1)\nnonadjacent_op = cirq.CZ(q0, q2)\n\n# This is an unconstrained circuit with no device\nfree_circuit = cirq.Circuit()\n# Both operations are allowed:\nfree_circuit.append(adjacent_op)\nfree_circuit.append(nonadjacent_op)\nprint('Unconstrained device:')\nprint(free_circuit)\nprint()\n\n# This is a circuit on the Foxtail device\n# only adjacent operations are allowed.\nprint('Foxtail device:')\nfoxtail_circuit = cirq.Circuit(device=cirq_google.Foxtail)\nfoxtail_circuit.append(adjacent_op)\ntry:\n    # Not allowed, will throw exception\n    foxtail_circuit.append(nonadjacent_op)\nexcept ValueError as e:\n    print('Not allowed. %s' % e)\n\n```\n\n    Unconstrained device:\n    (0, 0): \u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500\n               \u2502   \u2502\n    (0, 1): \u2500\u2500\u2500@\u2500\u2500\u2500\u253c\u2500\u2500\u2500\n                   \u2502\n    (0, 2): \u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\n    \n    Foxtail device:\n    Not allowed. Non-local interaction: cirq.CZ.on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 2)).\n\n\n## Simulation\n\nThe results of the application of a quantum circuit can be calculated by a `Simulator`.  Cirq comes bundled with a simulator that can calculate the results of circuits up to about a limit of 20 qubits.  It can be initialized with `cirq.Simulator()`.\n\nThere are two different approaches to using a simulator:\n\n*   `simulate()`:  Since we are classically simulating a circuit, a simulator can directly access and view the resulting wave function.  This is useful for debugging, learning, and understanding how circuits will function.  \n*   `run()`:  When using actual quantum devices, we can only access the end result of a computation and must sample the results to get a distribution of results.  Running the simulator as a sampler mimics this behavior and only returns bit strings as output.\n\nLet's try to simulate a 2-qubit \"Bell State\":\n\n\n```\n# Create a circuit to generate a Bell State:\n# 1/sqrt(2) * ( |00\u27e9 + |11\u27e9 )\nbell_circuit = cirq.Circuit()\nq0, q1 = cirq.LineQubit.range(2)\nbell_circuit.append(cirq.H(q0))\nbell_circuit.append(cirq.CNOT(q0,q1))\n\n# Initialize Simulator\ns=cirq.Simulator()\n\nprint('Simulate the circuit:')\nresults=s.simulate(bell_circuit)\nprint(results)\nprint()\n\n# For sampling, we need to add a measurement at the end\nbell_circuit.append(cirq.measure(q0, q1, key='result'))\n\nprint('Sample the circuit:')\nsamples=s.run(bell_circuit, repetitions=1000)\n# Print a histogram of results\nprint(samples.histogram(key='result'))\n```\n\n    Simulate the circuit:\n    measurements: (no measurements)\n    output vector: 0.707|00\u27e9 + 0.707|11\u27e9\n    \n    Sample the circuit:\n    Counter({3: 537, 0: 463})\n\n\n### Using parameter sweeps\n\nCirq circuits allow for gates to have symbols as free parameters within the circuit.  This is especially useful for variational algorithms, which vary parameters within the circuit in order to optimize a cost function, but it can be useful in a variety of circumstances.\n\nFor parameters, cirq uses the library `sympy` to add `sympy.Symbol` as parameters to gates and operations.  \n\nOnce the circuit is complete, you can fill in the possible values of each of these parameters with a `Sweep`.  There are several possibilities that can be used as a sweep:\n\n*   `cirq.Points`: A list of manually specified values for one specific symbol as a sequence of floats\n*   `cirq.Linspace`: A linear sweep from a starting value to an ending value.\n*   `cirq.ListSweep`: A list of manually specified values for several different symbols, specified as a list of dictionaries.\n*   `cirq.Zip` and `cirq.Product`: Sweeps can be combined list-wise by zipping them together or through their Cartesian product.\n\nA parameterized circuit and sweep together can be run using the simulator or other sampler by changing `run()` to `run_sweep()` and adding the sweep as a parameter.\n\nHere is an example of sweeping an exponent of a X gate:\n\n\n```\nimport matplotlib.pyplot as plt\nimport sympy\n\n# Perform an X gate with variable exponent\nq = cirq.GridQubit(1,1)\ncircuit = cirq.Circuit(cirq.X(q) ** sympy.Symbol('t'),\n                       cirq.measure(q, key='m'))\n\n# Sweep exponent from zero (off) to one (on) and back to two (off)\nparam_sweep = cirq.Linspace('t', start=0, stop=2, length=200)\n\n# Simulate the sweep\ns = cirq.Simulator()\ntrials = s.run_sweep(circuit, param_sweep, repetitions=1000)\n\n# Plot all the results\nx_data = [trial.params['t'] for trial in trials]\ny_data = [trial.histogram(key='m')[1] / 1000.0 for trial in trials]\nplt.scatter('t','p', data={'t': x_data, 'p': y_data})\n\n```\n\n## Unitary matrices and decompositions\n\nMost quantum operations have a unitary matrix representation.  This matrix can be accessed by applying `cirq.unitary()`.  This can be applied to gates, operations, and circuits that support this protocol and will return the unitary matrix that represents the object.\n\n\n```\nprint('Unitary of the X gate')\nprint(cirq.unitary(cirq.X))\n\nprint('Unitary of SWAP operator on two qubits.')\nq0, q1 = cirq.LineQubit.range(2)\nprint(cirq.unitary(cirq.SWAP(q0, q1)))\n\nprint('Unitary of a sample circuit')\nprint(cirq.unitary(cirq.Circuit(cirq.X(q0), cirq.SWAP(q0, q1))))\n```\n\n    Unitary of the X gate\n    [[0.+0.j 1.+0.j]\n     [1.+0.j 0.+0.j]]\n    Unitary of SWAP operator on two qubits.\n    [[1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 1.+0.j 0.+0.j]\n     [0.+0.j 1.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 1.+0.j]]\n    Unitary of a sample circuit\n    [[0.+0.j 0.+0.j 1.+0.j 0.+0.j]\n     [1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 1.+0.j]\n     [0.+0.j 1.+0.j 0.+0.j 0.+0.j]]\n\n\n### Decompositions \n\nMany gates can be decomposed into an equivalent circuit with simpler operations and gates.  This is called decomposition and can be accomplished with the `cirq.decompose` protocol.  \n\nFor instance, a Hadamard H gate can be decomposed into X and Y gates:\n\n\n```\nprint(cirq.decompose(cirq.H(cirq.LineQubit(0))))\n```\n\n    [(cirq.Y**0.5).on(cirq.LineQubit(0)), cirq.XPowGate(exponent=1.0, global_shift=-0.25).on(cirq.LineQubit(0))]\n\n\nAnother example is the 3-qubit Toffoli gate, which is equivalent to a controlled-controlled-X gate.  Many devices do not support a three qubit gate, so it is important \n\n\n```\nq0, q1, q2 = cirq.LineQubit.range(3)\nprint(cirq.Circuit(cirq.decompose(cirq.TOFFOLI(q0, q1, q2))))\n```\n\n    0: \u2500\u2500\u2500T\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                           \u2502                                 \u2502                             \u2502                            \u2502\n    1: \u2500\u2500\u2500T\u2500\u2500\u2500\u2500\u2500\u2500\u2500Y^-0.5\u2500\u2500\u2500@\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500\u2500@\u2500\u2500\u2500T^-1\u2500\u2500\u2500\u2500Y^-0.5\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500@\u2500\u2500\u2500Y^-0.5\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500\u2500@\u2500\u2500\u2500Y^-0.5\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                        \u2502                                     \u2502                            \u2502                            \u2502\n    2: \u2500\u2500\u2500Y^0.5\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500T\u2500\u2500\u2500Y^-0.5\u2500\u2500\u2500@\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500T\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500Y^-0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500\u2500T^-1\u2500\u2500\u2500Y^-0.5\u2500\u2500\u2500@\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500\u2500T^-1\u2500\u2500\u2500Y^-0.5\u2500\u2500\u2500@\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500X\u2500\u2500\u2500\n\n\nThe above decomposes the Toffoli into a simpler set of one-qubit gates and CZ gates at the cost of lengthening the circuit considerably.\n\nSome devices will automatically decompose gates that they do not support.  For instance, if we use the `Foxtail` device from above, we can see this in action by adding an unsupported SWAP gate:\n\n\n```\nswap = cirq.SWAP(cirq.GridQubit(0, 0), cirq.GridQubit(0, 1))\nprint(cirq.Circuit(swap, device=cirq_google.Foxtail))\n```\n\n    (0, 0): \u2500\u2500\u2500S^-1\u2500\u2500\u2500Y^-0.5\u2500\u2500\u2500@\u2500\u2500\u2500S^-1\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500X^0.5\u2500\u2500\u2500@\u2500\u2500\u2500S^-1\u2500\u2500\u2500X^-0.5\u2500\u2500\u2500@\u2500\u2500\u2500S^-1\u2500\u2500\u2500Z\u2500\u2500\u2500\n                               \u2502                          \u2502                   \u2502\n    (0, 1): \u2500\u2500\u2500Z\u2500\u2500\u2500\u2500\u2500\u2500Y^-0.5\u2500\u2500\u2500@\u2500\u2500\u2500S^-1\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500X^0.5\u2500\u2500\u2500@\u2500\u2500\u2500S^-1\u2500\u2500\u2500X^-0.5\u2500\u2500\u2500@\u2500\u2500\u2500S^-1\u2500\u2500\u2500S\u2500\u2500\u2500\n\n\n### Optimizers\n\nThe last concept in this tutorial is the optimizer.  An optimizer can take a circuit and modify it.  Usually, this will entail combining or modifying operations to make it more efficient and shorter, though an optimizer can, in theory, do any sort of circuit manipulation.\n\nFor example, the `cirq.merge_single_qubit_gates_to_phxz` optimizer will take consecutive single-qubit operations and merge them into a single `PhasedXZ` operation.\n\n\n```\nq=cirq.GridQubit(1, 1)\nc=cirq.Circuit(cirq.X(q) ** 0.25, cirq.Y(q) ** 0.25, cirq.Z(q) ** 0.25)\nprint(c)\nc = cirq.merge_single_qubit_gates_to_phxz(c)\nprint(c)\n```\n\n    (1, 1): \u2500\u2500\u2500X^0.25\u2500\u2500\u2500Y^0.25\u2500\u2500\u2500T\u2500\u2500\u2500\n               \u250c                           \u2510\n    (1, 1): \u2500\u2500\u2500\u2502 0.5  +0.707j -0.   -0.5j  \u2502\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n               \u2502 0.354+0.354j  0.146+0.854j\u2502\n               \u2514                           \u2518\n\n\nOther optimizers can assist in transforming a circuit into operations that are native operations on specific hardware devices.  You can find more about optimizers and how to create your own elsewhere in the documentation.\n\n## Next steps\n\nAfter completing this tutorial, you should be able to use gates and operations to construct your own quantum circuits, simulate them, and to use sweeps.  It should give you a brief idea of the commonly used \n\nThere is much more to learn and try out for those who are interested:\n\n* Learn about the variety of [Gates](../gates.ipynb) available in cirq and more about the different ways to construct [Circuits](../circuits.ipynb)\n* Learn more about [Simulations](../simulation.ipynb) and how it works.\n* Learn about [Noise](../noise.ipynb) and how to utilize multi-level systems using [Qudits](../qudits.ipynb)\n* Dive into some [Examples](_index.yaml) and some in-depth tutorials of how to use cirq.\n\nAlso, join our [cirq-announce mailing list](https://groups.google.com/forum/#!forum/cirq-announce) to hear about changes and releases or go to the [cirq github](https://github.com/quantumlib/Cirq/) to file issues.\n", "meta": {"hexsha": "284c21a0dae66c9233564bd4a12ca143d50b08b2", "size": 38068, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/basics.ipynb", "max_stars_repo_name": "mkeshita/Cirq", "max_stars_repo_head_hexsha": "06b5a5bd929757bf4bafe32b16bc4fabb36f3390", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/tutorials/basics.ipynb", "max_issues_repo_name": "mkeshita/Cirq", "max_issues_repo_head_hexsha": "06b5a5bd929757bf4bafe32b16bc4fabb36f3390", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/tutorials/basics.ipynb", "max_forks_repo_name": "mkeshita/Cirq", "max_forks_repo_head_hexsha": "06b5a5bd929757bf4bafe32b16bc4fabb36f3390", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.6323337679, "max_line_length": 11754, "alphanum_fraction": 0.6847483451, "converted": true, "num_tokens": 5061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3106943959796865, "lm_q2_score": 0.11436853070975536, "lm_q1q2_score": 0.03553366156795167}}
{"text": "```python\n%matplotlib inline\nfrom jocument import *\nimport IPython\nimport time\nimport numpy\nimport pandas\nimport matplotlib.pyplot as plt\nfrom matplotlib import colors\n\n# Create the references objects\ntables = Labels('Table')\nfigures = Labels('Figure')\ncitations = Citations()\nfootnotes = Footnotes()\n\n# Create some footnotes\nfootnotes.add(\"most_footnotes\",\n'''Most footnotes will be defined in the same cell as the footnotes object is created.''')\nfootnotes.add(\"links\",\n'''You can add links in a footnote like\n<a href=https://www.youtube.com/watch?v=dQw4w9WgXcQ target=_blank>this</a>.  Important to note that\nyou don't use single or double quotes in the definition of the href attribute\n''')\nfootnotes.add('math',\n'''It's perfectly possible to add math in a footnote too.  For example $e^{i\\pi} + 1 = 0$''')\n\n# Create some citations\ncitations.reference('Darwin C', '<a href=http://graphics8.nytimes.com/packages/images/nytint/docs/charles-darwin-on-the-origin-of-species/original.pdf>On The Origin Of Species</a>', 'London (1859)')\ncitations.reference('Einstein, A', 'On The Influence of Gravity on the Propagation of Light', 'Annalen der Physik, <strong>35</strong>: 898-908 (1911)')\n\n\n```\n\n## Jocument Tutorial Notebook\n\nThis notebook is a tutorial on how to use the `jocument` classes and functions to produce nice\nlooking reports and presentations.\n\n#### Prerequisites\n-   Make sure you jave `jocument` installed.\n-   You should also install the standard set of notebook extensions\n-   Make sure that `python markdown` is enabled and (for presentations) that you've installed Rise.\n-   Run all the cells in this notebook  before getting started.\n\n\n### Getting started\n\nYou can use this notebook as a guide or create a new notebook and follow the instructions as we go along.\n\nThe first thing you need is to create a code cell at the top of your notebook which contains (at a minimum)\nthe following code.\n\n```python\nfrom jocument import *\n```\n\nIn general, there are going to be a number of other things you'll need in your notebook and in this\nnotebook (like so many others) the first cell\nshould contain\n\n```python\n%matplotlib inline\nfrom jocument import *\nimport IPython\nimport time\nimport numpy\nimport pandas\nimport matplotlib.pyplot as plt\nfrom matplotlib import colors\n```\n\nIn the next cell (or the same cell), add the following four lines of code\n\n```python\ntables = Labels('Table')\nfigures = Labels('Figure')\ncitations = Citations()\nfootnotes = Footnotes()\n```\n\nThis creates four global variables in the notebook.  \n\n-   `tables` which is a `jocument.Label` object.  This will be used to store the labels for the tables that we create\n-   `figures` which is also a `jocument.Label` object.  This will be used to store the labels for the figures we create\n-   `citations` which is a `jocument.Citations` object.  This object handles citations (references).\n-   `footnotes` which is a `jocument.Footnotes` object.  This object will handle our footnotes.\n\nBelow the definition of the footnotes variable, we are going to add our citations and footnotes in this cell\nat the top of the notebook.  Note that the citations and footnotes can be added anywhere in the notebook\nbut defining them in the same cell as the creation of the objects avoids having to run cells in a particular\norder.\n\nLet's define some footnotes.  In the same cell as the `footnotes` object is created, add the following\n```python\nfootnotes.add(\"most_footnotes\",\n'''Most footnotes will be defined in the same cell as the footnotes object is created.''')\nfootnotes.add(\"links\",\n'''You can add links in a footnote like\n<a href=https://www.youtube.com/watch?v=dQw4w9WgXcQ target=_blank>this</a>.  Important to note that\nyou don't use single or double quotes in the definition of the href attribute\n''')\nfootnotes.add('math',\n'''It's perfectly possible to add math in a footnote too.  For example $e^{i\\pi} + 1 = 0$''')\n```\n\nAnd while we're at it, let's add some citations too\n```python\ncitations.reference('Darwin C', '<a href=http://graphics8.nytimes.com/packages/images/nytint/docs/charles-darwin-on-the-origin-of-species/original.pdf>On The Origin Of Species</a>', 'London (1859)')\ncitations.reference('Einstein, A', 'On The Influence of Gravity on the Propagation of Light', 'Annalen der Physik, <strong>35</strong>: 898-908 (1911)')\n```\n\nNow how do we do something with this?  Well in a mark down cell, if you write\n```markdown\n    ### Introduction to footnotes\n    It is possible to add a footnote in a markdown cell by using the python \n    markdown functionality.  This allows you to insert and run any python within\n    double curly braces inside a markdown cell.  For the first note, we will\n    use a footnote which is defined in the first\n    cell{{print(\"{\"+\"{\" + \"footnotes.ref('most_footnotes')\" + \"}\"+\"}\")}}.  There\n    are other features of footnotes which are generally\n    useful{{print(\"{\"+\"{\" + \"footnotes.ref('links')\" + \"}\"+\"}\")}} and some which\n    are more useful in mathematical\n    papers{{print(\"{\"+\"{\" + \"footnotes.ref('math')\" + \"}\"+\"}\")}}\n    \n    Note that we are referring to each footnote by its \"friendly name\".  Sometimes\n    you want to refer to footnotes by their number and in this case you refer\n    to Footnote {{print(\"{\"+\"{\" + \"footnotes.num('most_footnotes')\" + \"}\"+\"}\")}}.\n```\n\nHaving inserted this in a markdown cell, you also need to output the footnotes somewhere so\nfor the moment insert a code cell after the markdown cell and insert the line\n\n```python\nIPython.display.HTML(footnotes.output())\n```\n\nGenerally, of course, this cell will go right at the end of your document.  This is what you should get:\n\n\n> ### Introduction to footnotes\n> It is possible to add a footnote in a markdown cell by using the python \n>  markdown functionality.  This allows you to insert and run any python within\n>  double curly braces inside a markdown cell.  For the first note, we will\n>  use a footnote which is defined in the first\n> cell{{footnotes.ref('most_footnotes')}}.  There\n> are other features of footnotes which are generally\n> useful{{footnotes.ref('links')}} and some which\n> are more useful in mathematical\n> papers{{footnotes.ref('math')}}\n\n> Note that we are referring to each footnote by its \"friendly name\".  Sometimes\n> you want to refer to footnotes by their number and in this case you refer\n> to Footnote {{footnotes.num('most_footnotes')}}.\n\n\n```python\nIPython.display.HTML(footnotes.output())\n```\n\n\n\n\n<ol><li id=fn_1>Most footnotes will be defined in the same cell as the footnotes object is created.<a href=#fnret_1>&#8629;</a></li><li id=fn_2>You can add links in a footnote like <a href=https://www.youtube.com/watch?v=dQw4w9WgXcQ target=_blank>this</a>.  Important to note that you don't use single or double quotes in the definition of the href attribute <a href=#fnret_2>&#8629;</a></li><li id=fn_3>It's perfectly possible to add math in a footnote too.  For example $e^{i\\pi} + 1 = 0$<a href=#fnret_3>&#8629;</a></li></ol>\n\n\n\nThis is the default styling of footnotes and if you don't like it, there's a way of changing it which\nwe will be investigating later.\n\nThe footnotes are hyperlinks to where the footnotes are output at the bottom of this \n\n$$\n\\begin{equation}\\label{eq:1}\n\ne = \\sin{\\theta}\n\n\\end{equation}\n$$\n\n\\begin{theorem}\\label{theo:1}\n\nThe theorem is that $e = \\sqrt{-1}$\n\n\\end{theorem}\n\n\\begin{remark}\\label{rem:1}\n\nThis is a remark\n\n\\end{remark}\n\n\n## Introduction\n\nSystematic trading (or algorithmic, quant, model driven, computerised...) is often characterised as \"complicated\" or\n\"complex\".  Indeed, much of the commentary by the press and by investors focuses on this perceived complexity.  In some\nineffable way, the fact that systematic trading is complicated indicates that there is something unsavoury or \nunderhand about it.  Complicated trading strategies cause market chaos, excess volatility, flash \ncrashes (both down and up)...there is just something \"wrong\" about them.\n\nWhilst we would naturally strongly disagree with the characterisation of systematic trading as \"wrong\", in this\npost, we would like to take issue with the conflating of two terms.  In the press and in the industry, the words\n\"complex\" and \"complicated\" are often used interchangably but they are strictly not the same thing and by\nunderstanding the difference, we may have more insight into the nature of systematic trading and how \nit interacts with the financial ecosystem.\n\n## Complicated\n\nHow do we define something as complicated?  If you're a dog then an alarm clock is complicated and incomprehensible.  If you've \nnever seen American Football before, it seems complicated and incomprehensible. The Space Shuttle, \nan iPhone, Quantum Mechanics, the ISDA Credit Default swap conventions are all complicated.  However, they're not incomprehensible. \n**Somebody** understands them or at least understands the some of the components and understands how the components work \ntogether.  If you repeat inputs into the Shuttle, your iPhone and Credit Default Swaps, they behave the same way every\ntime.{{footnotes.ref(\"most_of_the_time\")}}\n\nIs being complicated an undesirable property of a process or system?  This mostly depends on what the system\nis.  Making something unnecessarily complicated might not be a good idea.  We could open cans of beans using computer controlled\nlaser beams or enter into full legal multi-party debt obligation documentation when one buys a round of drinks at the pub\nbut that would be stupidly complicated compared to a can opener or just informally assuming everybody buys a round eventually. \n\nHowever, excessive simplicity might not be good either.  Managing air traffic around an airport by having a person on top of a tall building with a pair of binoculars is pretty simple compared to the current system of ADS-B{{footnotes.ref('adsb')}}, RADAR and a centralised air traffic control{{footnotes.ref('airtraffic')}} infrastructure.  But does anybody want a non-complicated air traffic control?  Leeches are a simpler solution to illness than MRI scanners.\n\nSo in some cases complicated systems are either a good thing or, even more often, they are a result of the requirements for the system.  A example of this is telephony.  When telephony first started, users had a box in their house with a microphone and speaker.  This box\nwas connected by a length of copper wire to a local exchange which was manned (or more precisely wommaned) by operators.  You pressed\nthe receiver hook a few times to speak to the operator and told them who you wanted to speak to.  The operator connected your line\ndirectly to somebody else's line using a patch cable with a 1/4 inch jack plug{{footnotes.ref('guitar')}} and there was effectively\na copper wire directly connecting your microphone to the speaker at the other end and a wire connecting your speaker to\ntheir microphone.  Simple.\n\nHowever, there are a number of problems\n\n-   This isn't very scalable.  Imagine how many jack plug holes one would need for London or Manhattan.\n-   As the local systems get connected to each other both within a country and internationally, setting up calls can\n    be exceptionally difficult and time consuming.\n-   Whilst one often wants to phone a location when one is making a business call (\"Hello is that British Airways?\"),\n    for personal calls, I want to call a person, not a location (\"Hello, is that Brian's house?  I'd like to speak to Brian.\")\n    \nOver approximately 130 years{{footnotes.ref('firstexchange')}} telephony has become much more complicated.  Mechanical (and then electronic) direct dial exchanges and multiple undersea cables have connected together all the fixed line phones in the world.\nDigital signal processing techniques allowed multiplexing{{footnotes.ref('multiplex')}} many conversations on a single wire or fiber.\n\nIn the early 1980s, mobile telephony took off and mobile telephony is astonishingly complicated.  Identifying how to\ncontact a single phone (which potentially could be in any location in the world) and setting up the connection,\nnegotiating protocols, and billing is extremely complicated.\n\nThe advances in the telephony have been required handsets to become more and more complicated.  A microphone,\na speaker and a bell has evolved into the iPhone X.  Gigabytes of operating system and application code run by a microprocessor containing nearly 7 billion transistors.  It is debatable whether or not any single person can completely\nunderstand an iPhone given how complicated it is.  Is being complicated bad in this case?  For those of you who sometimes struggle\nwith new features and interfaces, it may seem like a bad thing but overall the complication has added astonishing functionality\nto telephony which is considered desirable and (probably) good.\n\nAlthough all this is very complicated -- too complicated for anybody to understand -- these types of highly complicated\nsystems have certain characteristics\n\n-   The complicated system can be subdivided into smaller less complicated parts.\n-   This subdivision can be done almost indefinitely until the small component is easily understandable.  For example, a single line\n    of computer code or a single transistor.\n-   When these simple functional \"atoms\" are combined, they work together in well defined and predictable ways\n-   Feedback between components is limited, predictable and often linear.\n-   The reaction of the complicated system to identical inputs are identical and predictable.{{footnotes.ref('randomness')}}\n\nLet's look at a mathematical example.  Here's an equation which describes a curve:\n\n$$\n\\left(\\left(\\frac x7\\right)^2\\sqrt{\\frac{||x|-3|}{|x|-3}}+\\left(\\frac y3\\right)^2\\sqrt{\\frac{\\left|y+\\frac{3\\sqrt{33}}7\\right|}{y+\\frac{3\\sqrt{33}}7}}-1 \\right)\n$$\n\n$$\n\\qquad \\qquad \\left(\\left|\\frac x2\\right|-\\left(\\frac{3\\sqrt{33}-7}{112}\\right)x^2-3+\\sqrt{1-(||x|-2|-1)^2}-y \\right)\n$$\n\n$$\n\\qquad \\qquad \\left(3\\sqrt{\\frac{|(|x|-1)(|x|-.75)|}{(1-|x|)(|x|-.75)}}-8|x|-y\\right)\\left(3|x|+.75\\sqrt{\\frac{|(|x|-.75)(|x|-.5)|}{(.75-|x|)(|x|-.5)}}-y \\right)\n$$\n\n$$\n\\qquad \\qquad \\left(2.25\\sqrt{\\frac{(x-.5)(x+.5)}{(.5-x)(.5+x)}}-y \\right)\n$$\n\n$$\n\\qquad \\qquad \\left(\\frac{6\\sqrt{10}}7+(1.5-.5|x|)\\sqrt{\\frac{||x|-1|}{|x|-1}} -\\frac{6\\sqrt{10}}{14}\\sqrt{4-(|x|-1)^2}-y\\right)=0\n$$\n\nThere's no doubt that this is a pretty complicated equation.  In fact, I doubt anybody could look at this equation and work\nout what this equation describes.  However, the thing it describes isn't very complex.  It's this:\n\n\n```python\nx = np.linspace(0, 2*np.pi, 50)\ny = np.sin(x)\ny2 = y + 0.1 * np.random.normal(size=x.shape)\n\nfig, ax = plt.subplots()\nax.plot(x, y, 'k--')\nax.plot(x, y2, 'ro')\n\n# set ticks and tick labels\nax.set_xlim((0, 2*np.pi))\nax.set_xticks([0, np.pi, 2*np.pi])\nax.set_xticklabels(['0', '$\\pi$', '2$\\pi$'])\nax.set_ylim((-1.5, 1.5))\nax.set_yticks([-1, 0, 1])\n\n# Only draw spine between the y-ticks\nax.spines['left'].set_bounds(-1, 1)\n# Hide the right and top spines\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\n# Only show ticks on the left and bottom spines\nax.yaxis.set_ticks_position('left')\nax.xaxis.set_ticks_position('bottom')\n\nplt;\n```\n\n{{figures.add('batman', 'The Batman Curve')}}\n\nThe result of that complicated equation isn't actually that complicated.  \n\n## Complex\n\nComplex systems are different.  Whilst there are formal definitions of complexity{{footnotes.ref('complexity')}} there are\ncomplex systems all around us.  Complex systems are sometimes hard to understand.  The components interact in strange\nunpredictable ways, they're difficult or impossible to forecast even though they're easy to describe.\n\nThe classic example of a complex system is weather.  Whilst it is easy to describe the state of the weather at any one time,\nforecasting the weather is a notoriously difficult problem.  Indeed, even with almost unlimited computing power, any forecast\nbeyond 10 days is little better than using the historical average of temperature and precipitation.  Butterflies flapping their\ntiny hurricane-causing wings is a tired old clich\u00e9 but does try to encapsulate a sensitivity of the weather to initial\nconditions.  Another way of thinking about this sensitivity is as a lack of long term memory.{{footnotes.ref('chaos')}}\n\n\n\nSo let's compare our complicated equation above to this simple equation\n\n\\begin{equation}\nz_{n+1} = z^{2}_{n} + c\n\\end{equation}\n\nHow does this equation work?  The numbers $z$ and $c$ are complex{{footnotes.ref('complexnum')}} and they define a\nplane.  For each value of $c$ (basically an $x,y$ pair) we start with $z_0=0 + i0$ and the next value $z_1$ is found from the equation.  For the first iteration, it is obviously $c$.  Now we use the equation again to get $z_2 = c^2 + c$.  As we keep going, there are two things that can happen to $z$\n\n-   $z$ can end up going to infinity.\n-   $z$ remains bounded.\n\nSo we can classify each $c$ as either one which leads to an infinite $z$ or one which leads to a bounded $z$.  This should be pretty simple right?  If $c$ is a normal positive *real* number then this classification is very simple.  If $c$ > 0.25 or $c$ < -2.0\nthen the equation is unbounded.  If $c$ is between -2 and 0.25 then it's bounded.  Simple...\n\nBut, when we make the imaginary part of the number non zero, something very complex indeed happens.{{footnotes.ref('zoom')}}\n\n\n```python\n\"\"\"\n===================================\nShaded & power normalized rendering\n===================================\n\nThe Mandelbrot set rendering can be improved by using a normalized recount\nassociated with a power normalized colormap (gamma=0.3). Rendering can be\nfurther enhanced thanks to shading.\n\nThe `maxiter` gives the precision of the computation. `maxiter=200` should\ntake a few seconds on most modern laptops.\n\"\"\"\nimport numpy as np\n\n\ndef mandelbrot_set(xmin, xmax, ymin, ymax, xn, yn, maxiter, horizon=2.0):\n    X = np.linspace(xmin, xmax, xn, dtype=np.float32)\n    Y = np.linspace(ymin, ymax, yn, dtype=np.float32)\n    C = X + Y[:, None]*1j\n    N = np.zeros(C.shape, dtype=int)\n    Z = np.zeros(C.shape, np.complex64)\n    for n in range(maxiter):\n        I = np.less(abs(Z), horizon)\n        N[I] = n\n        Z[I] = Z[I]**2 + C[I]\n    N[N == maxiter-1] = 0\n    return Z, N\n\n\nfrom matplotlib import colors\n\n\nxmin, xmax, xn = -2.25, +0.75, 1500\nymin, ymax, yn = -1.25, +1.25, 1250\nmaxiter = 200\nhorizon = 2.0 ** 40\nlog_horizon = np.log(np.log(horizon))/np.log(2)\nZ, N = mandelbrot_set(xmin, xmax, ymin, ymax, xn, yn, maxiter, horizon)\n\n# Normalized recount as explained in:\n# https://linas.org/art-gallery/escape/smooth.html\n# https://www.ibm.com/developerworks/community/blogs/jfp/entry/My_Christmas_Gift\n\n# This line will generate warnings for null values but it is faster to\n# process them afterwards using the nan_to_num\nwith np.errstate(invalid='ignore'):\n    M = np.nan_to_num(N + 1 -\n                      np.log(np.log(abs(Z)))/np.log(2) +\n                      log_horizon)\n\ndpi = 72\nwidth = 7\nheight = 10*yn/xn\nfig = plt.figure(figsize=(width, height), dpi=dpi)\nax = fig.add_axes([0.0, 0.0, 1.0, 1.0], frameon=False, aspect=1)\n\n# Shaded rendering\nlight = colors.LightSource(azdeg=315, altdeg=10)\nM = light.shade(M, cmap=plt.cm.gray, vert_exag=20.0,\n                norm=colors.PowerNorm(0.3), blend_mode='hsv')\nplt.imshow(M, extent=[xmin, xmax, ymin, ymax], interpolation=\"bicubic\")\nax.set_xticks([])\nax.set_yticks([])\nplt.show()\n```\n\n{{figures.add('hello', 'The hello')}}\n\n{{figures.add('mandelbrot', 'The Mandelbrot Set')}}\nThis sort of emergent complexity arising from relatively simple rules has been an area of active research for \nmore than 30 years and not only generates some beautiful pictures but also has provided some deep insight into dynamical\nsystems.\n\n## What's this got to do with finance?\n\nWe've produced some pretty graphs{{footnotes.ref('batman')}} but what, if anything, has this to do with Systematic Trading,\nfinance or algorithms?\n\nVery often when investors, commentators and practitioners are thinking about or discussing systematic trading\nthe two concepts of being complicated or being complex are used interchangeably and incorrectly.\n\n#### Some things in finance are complicated\nSystematic trading is very complicated.  Or, at least, it **should** be very complicated.    Writing computer code libraries,\ncombining them into systems and then connecting these systems both to themselves and to market venues thousands of\nmiles away is a very complicated task.  This is not an endeavour where an Excel spreadsheet and a couple of VBA\nmacros is going to work very well.  Whilst a single model running on a single stock in a simple brokerage account\n*may* be able to be work reliably with a simple system, it's rare that a simple model running on one asset really\nis an investable proposition.\n\nAs the number of assets, the number of models and the number of funds increases, the system necessarily becomes more\ncomplicated.  However, the individual components don't necessarily become more complicated.  They remain \nunderstandable and predictable.  Of course, there is always the chance that a bug is introduced into the\nsystem or individual components can interact in counter-intuitive ways but careful and rigorous \nregression testing before adding a new component, vehicle, model or asset to the system can\ndeal with these problems before they create issues in a live running system.\n\nThere are other examples of complicated things in finance being considered.  Vanilla European options were considered complicated\nand scary for many years.  Only the *cognoscenti* could trade them and anybody who understood what \"the greeks\" were was thought\nof as a mega-brain geek.  There was nothing complex about options, they were just a little complicated.  Tranched credit products\nare sometimes complicated.  \n\nInvestors, journalists and even some practitioners find these complicated systems daunting and worrying.  The term\n\"Black Box\" is used in a very pejorative way.  Some worry that complicated systems which they don't understand\nare causing market volatility{{footnotes.ref('neverup')}} in some complicated way which they can't really \nexplain.  \n\nIt appears that there is something uniquely scary about things in finance where the \"complicated\" part\ninvolves mathematics, statistics or computer code.  Many private or public equity transactions involve astonishingly\ncomplicated legal documents.  It is likely that no one person understands all of the \ndocumentation {{footnotes.ref('barely')}} but for some reason this causes less consternation and fear than a \nfew lines of mathematics which a mathematically competent 14 year old could understand.\n\n#### Some things in finance are complex\n\nIn contrast to complicated things, complex things are very hard (and often impossible) to forecast.  First and foremost of the complex things\nin finance is \"the market\".  We aren't talking about any specific market like the NYSE or the CME Eurodollar market.  We're talking\nabout an idealised market which could just as easily refer to high frequency trading in IBM on the NASDAQ to an open outcry\nmarket in 17th century Amsterdam.  What characteristics do these idealised markets have?\n\n-   Multiple participants both on the buy and sell side\n-   Participants are generally heterogeneous.  Some may be market makers, some may be hedgers, some may be speculators\n-   Each participant has a goal which is generally known only to them\n-   Some proportion of the market participants are \"uninformed\" or \"noise traders\"\n-   A single security is (generally) traded in a single location\n-   Arbitrage{{footnotes.ref('arbitrage')}} opportunities between identical securities are \"rapidly\" arbitraged away.\n\nThese rather simple characteristics generate extremely complex behaviour.  To a very good approximation for the\nvast majority of participants in the market, it is impossible to forecast the market dynamics over a few seconds,\nminutes, hours or days.\n\nTo give an indication of why it's unlikely that anybody can forecast a market in the short term, let's assume that\na participant in the market can forecast just the direction of the market move tomorrow.  All this person knows\nis whether or not the market will go up or down tomorrow.  She doesn't know how much the move is, she just knows the direction\nof the move in the SP500 tomorrow. If the prediction is up, she buys the SP500 on the close of the previous day, holds for one\nday and then changes\nher position at the end of the following day on the basis of whether or not the market will go up or down on the following day.\n\nIf our super trader starts with \\\\$1 on the 1st of January 2000 then by the end of 2018 our trader has something slightly\nover \\\\${{'{:,.0f}'.format(super_trader_wealth)}} and will have had a Sharpe ratio of {{'{:,.0f}'.format(super_trader_sharpe)}}.\nThe trader's wealth of {{'{:,.0f} petadollars'.format(super_trader_wealth/1E15)}} is approximately\n200 times the total global wealth{{footnotes.ref('totalwealth')}} in the world.  Since very few, if any, people have 18 year track records this good{{footnotes.ref('problems')}}, we can conclude\nthat even forecasting up or down is really really difficult.\n\nThis is a direct result of the complexity of market dynamics.  Complex systems are difficult to forecast due to their\nextreme dependence on initial conditions and non-linear relationships between the components.\n\nSo is any trading or financial process doomed to failure?  Does complexity ensure that the efficient market hypothesis is\ntrue?  Slightly surprisingly, the answer to this is no.\n\n## Complexity requires complicated processes\n\nFor our final example, let's assume that we have a very poor quality forecast of whether or not a security will \nrise or fall over a year.  The probability that this forecast is right is 51%.  Making some simple assumptions{{footnotes.ref('assumptions')}} about the nature of the security, our forecast would enable us to make about 0.25% \nannually.  At its heart, this poor performance is a \ndirect result of the near complete randomness of markets which is a direct result of the highly complex nature of \nmarkets in general.  Obviously, the process to actually trade this single forecast isn't very complicated.  The \"system\"\nmakes the forecast on the 1st of January (up/down) and on the basis of this, you buy or sell.  Then ignore the market,\ntake the position off on the 31st of December and see what your profit or loss is.\n\nEven the most ardent advocate of high quality systems and software in the financial world would agree that there\nis little need for complicated systems to trade this forecast.\n\nHowever, for our forecasting technique to be useful, it will have to generate higher returns than half a percent a year.  An\nobvious way to do this is to apply the same forecasting technique to other assets.  If we can make forecasts on \n5000 uncorrelated stocks (this is a big if) then our return rises to 17% with the same level of risk.\n\nLeaving aside how likely it is that you can make 5000 uncorrelated forecasts, making use of very imperfect forecasting\ntechniques on many securities theoretically looks like a good idea.  Indeed, this is often referred to as the *Fundamental\nLaw Of Active Management*.  If you have a certain degree of \"skill\" then you should apply that skill to as many things\nas possible.\n\nThe problem of managing one position is a lot easier than the problem of managing 5000.  Firstly, of course, one\nhas to collect all the data for each of the 5000 securities.  Then one has to make the forecast on these 5000\nsecurities.  Then a decision has to be made about how much risk (or assets) should be assigned to each\nof the securities.  This could be as simple as 1/5000 or could be a complicated optimisation procedure with multiple \nconstraints and which will require a forecast covariance matrix.  \nThen the resulting portfolio needs to be analysed to understand its risk characteristics and\nexposures to various risk factors (which themselves have to be defined and analysed).  Once the 5000 trades have\nbeen done, things get a little less complicated although it is highly likely that there will be thousands\nof corporate actions like dividend payments, stock splits, bankruptcies and mergers to handle over the course\nof the year.  If the securities are not all denominated in the domestic currency then currency hedges and\nrebalances will have to be done.  Finally, on the 31st of December, all the trades and currency hedges \nwill have to be unwound.\n\nThis whole process is complicated.  So complicated that it requires a significant amount of \"specialist\" \nmathematical, statistical and financial quantitative knowledge.  If the investment process is going to be\nrobust then it also requires a significant amount of immensely complicated software and arrays of \ncomputers and storage to analyse, manage and retain all the information.  This may run to millions\nof lines of code.  Writing, testing, managing and deploying these millions of lines of code is also a\ncomplicated process requiring specialist knowledge and experience.  At Cantab we are\nvery keen to explain what we do and how we do it to our investors (\"a glass box not a black box\") but\nnecessarily, these explanations have to elide over some of the critical and complicated details.\n\nSo why do we need all these complicated (and hard to explain) techniques and processes?  We need complicated processes\nprecisely because the markets and the securities which we trade are complex.  They are difficult to forecast and\ndifficult to understand in detail.  The markets, the securities and the people who trade in these markets interact\nin complex non-linear ways.  There is the impact of unexpected news events arriving at random times which\ncan have unpredictable (literally) effects on the prices of securities.  All this complexity needs to be \"factored out\"\nfrom the securities to (hopefully) generate a reasonable forecast of how the security will behave over the next\nminute or the next year.  \n\nIt is complicated and there is no simple way to explain it.\n\n\n## Conclusion\n\nInvestors often describe systematic investment processes as \"complex\" and worry that they can't understand \"the complexity\".  This\nis a category error.  Markets are complex.  Investors suffer from exposure to complexity in both systematic and discretionary\ninvestments.  \n\nHowever, if investors describe systematic investment processes as complicated then they are correct and something which is\ncomplicated should not be something to fear.  Investors should initially ignore how complicated the investment process is\nand concentrate on what the output of the process is.  Investors should also accept that at some level they\nwill never understand a complicated systematic investment process.  Not because they specifically aren't capable of that (many\nof our investors are very smart indeed) but because it's unlikely that *any* one person can understand it all.  Whilst\neach individual component is fully explicable and systematic, the ability to understand every single part of \na systematic investment process is probably beyond any one person.\n\nConversely, the press and broadcast media are full of glib simple explanations of\nthe dynamics of highly complex markets.  Investors would find it instructive to worry more about overly simple\ndescriptions of unfathomable complexity than about investment processes which are complicated.\n\n#### Footnotes\n{{footnotes.output()}}\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "5433eb741df35e9a2b390da2dfb2289441108be7", "size": 185044, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorial.ipynb", "max_stars_repo_name": "ewankirk/jocument", "max_stars_repo_head_hexsha": "914a29c2cdfeb27c056f75102c95af8f4dfca4aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorial.ipynb", "max_issues_repo_name": "ewankirk/jocument", "max_issues_repo_head_hexsha": "914a29c2cdfeb27c056f75102c95af8f4dfca4aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorial.ipynb", "max_forks_repo_name": "ewankirk/jocument", "max_forks_repo_head_hexsha": "914a29c2cdfeb27c056f75102c95af8f4dfca4aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 202.6768893757, "max_line_length": 127908, "alphanum_fraction": 0.8892101338, "converted": true, "num_tokens": 7531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17553807793655435, "lm_q2_score": 0.2018132126589859, "lm_q1q2_score": 0.035425903452359485}}
{"text": "# ECO 701: Microeconomic Theory, Fall 2017\n\n## Jonathan Conning\n\n**Office Hours: HW1504A\nAfter class, Tue, Wed 11-12pm and by appt.**\n\njconning@hunter.cuny.edu\n\n**Teaching Assistant:** Chuxin Liu\n\n## Textbook\n**Nicholson & Snyder, *Microeconomic Theory: Basic Principles and Extensions*.**   11th edition (10th or 12th acceptable).\n\n\n### Jupyter notebook materials\n  - These lecture slides, problem sets and other handouts prepared as Jupyter notebooks \n\n  - Cells use markdown for text and math and python (or other language) code for interactive simulations and visualizations.\n\n  - Notebooks can be rendered in different formats. Depending on how you access, you may be viewing:\n     - Interactive notebook (.ipynb) that can be viewed an modified on jupyter server on own computer or cloud. Interactive widgets work.\n     - Static HTML or PDF rendering. Cannot edit and interactive widgets do not work or display.\n     - Slideshow from notebook displays only pre-selected cells. May be static or interactive (alt-r)\n\n  - Promising but still evolving technology, so this is an experiment ! \n    - Please suggest ways to improve content and user experience.\n\n### The Eco 701 notebook library\n  - class notebooks stored in a library on Microsoft's Azure Notebooks server, a free cloud server: [notebooks.azure.com/jhconning/libraries/eco701](https://notebooks.azure.com/jhconning/libraries/eco701)  \n    - Follow link create account/login to view notebooks/slideshows. \n    - 'Clone' library to your own account if you wish to interact/modify notebooks or download to own machine if you have local  jupyter notebooks and python installation.\n\n- [Eco 701 repository] on github also has content and will be used for issue tracking (i.e.your post corrections/suggestions welcomed here).\n\n  - You are encouraged but not required to use Jupyter notebooks interactively.\n  - Many good intros for learning to use jupyter and python including [on Azure](https://notebooks.azure.com/Microsoft/libraries/samples/html/Introduction%20to%20Python.ipynb) and at the [Quantecon project](https://lectures.quantecon.org/py/)\n\n- ### Blackboard or google classroom \n     - for communications and grades\n\n# Course Grading\n  - ## 25% Problem sets/participation\t \n  - ## 45% higher of midterm or final\n  - ## 30% lower of midterm or final\n      - **Final:** TBA \n      - **Midterm:** TBA \n\n### Problem sets\n - Usually 4 in the semester. ~ 2 weeks to complete\n - Can work in groups but you must write up your own answers.\n\nThere are just 12 lecture sessions (excluding midterm), so problem sets and outside reading are important.\n\n# What are the questions?\n\n## How do individuals and societies allocate resources? \n## What are the alternatives?\n\n\n - Far more than the study of demand and supply choices in \u2018markets\u2019  \n - how do agents (individuals, households, firms, groups) choose to associate and contract and the rules of the game they play by. \n   - strategies, contracts, organizations, property rights, institutions and policy. Supply and demand decisions.\n   - Judging outcomes: Conflict or cooperation?  Efficient, equitable, just?\n\n## Methods and Assumptions\n - Methodological individualism  and instrumental rationality\n - Optimization subject to constraints and marginal analysis\n - Feedback, interactions and equilibrium\n - *Ceteribus paribus* and 'what-if' comparative statics\n - Modern challenges to behavioral and other assumptions\n - Theory and Evidence\n\n## What is neo-classical economics ... and why bother with it?\n\nPaul Krugman ([8/28/12](https://krugman.blogs.nytimes.com/2012/08/28/neo-fights-slightly-wonkish-and-vague/?mcubz=0&_r=0)):\n\n>... maximization-with-equilibrium. We imagine an economy consisting of rational, self-interested players, and suppose that economic outcomes reflect a situation in which each player is doing the best he, she, or it can given the actions of all the other players. If nobody has market power, this comes down to the textbook picture of perfectly competitive markets with all the marginal whatevers equal.\n\n>... Some economists really really believe that life is like this \u2014 and they have a significant impact on our discourse. \n\n> But the rest of us are well aware that this is nothing but a metaphor! [we take]... the maximization-and-equilibrium world as a starting point or baseline, which is then modified \u2014 but not too much \u2014 in the direction of realism.\n\n\n## Mathematical Preliminaries\n\n### (brief note on Jupyter notebooks)\n\nJupyter notebooks are made up of cells that are either markdown cells or code cells.  A Jupyter slideshow is typically created by marking many code cells to be 'skipped' in order to not clutter the presentation. \n\nI'd typically hide a code cell like the following, but will reveal it here to illustrate how we are importing additional python libraries to extend the standard python library.  matplotlib and numpy are for plotting and matrix algebra. \n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n```\n\n## Calculus for Optimization\n\nCost function: $$C(q) = F + q^2$$\n\nProfit function: \n\\begin{align}\n \\Pi(q) & = P \\cdot q - C(q)  \\\\\n        &= P\\cdot q - A - q^2 \n\\end{align}\n\n\nFirst-order necessary condition: $\\frac{d\\Pi}{dq} = P - 2q = 0$\n\nSolve for $q$:  $q^* =\\frac{P}{2} $\n\nProfit maximizing output level is independent of fixed cost $F$ \n\n\n```python\nF = 10\nP = 10\n\ndef C(q, F=F):\n    return F + q**2\n\ndef profit(q, P=P, F=F):\n    return P*q - C(q, F)\n\ndef opt(P, F):\n    return P/2, profit(P/2, P, F)\n\nq = np.linspace(0,10,20)\n```\n\n\n```python\nqe, pre = opt(P,F)\n\nplt.figure(figsize=(12,5))\nplt.plot(q, profit(q))\nplt.scatter(qe,pre)\nplt.plot([qe,qe],[0,pre],linestyle=':')\nplt.gca().spines['bottom'].set_position('zero')\nplt.gca().spines['right'].set_visible(False)\nplt.gca().spines['top'].set_visible(False)\nplt.xlabel(r'$q - output$');\n```\n\n### Next Lecture: [Constrained Optimization](01_Constrained_Optimization.ipynb)\n", "meta": {"hexsha": "774a3db836efd1806f01b2d4c87ae634bf558383", "size": 35010, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/micro/00_Introduction.ipynb", "max_stars_repo_name": "jhconning/teaching", "max_stars_repo_head_hexsha": "d89d29465e97cbb3bcb99c82f20af68bb2361ace", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-02-03T06:04:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T07:14:28.000Z", "max_issues_repo_path": "notebooks/micro/00_Introduction.ipynb", "max_issues_repo_name": "jhconning/teaching", "max_issues_repo_head_hexsha": "d89d29465e97cbb3bcb99c82f20af68bb2361ace", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-02-01T01:34:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-21T16:43:02.000Z", "max_forks_repo_path": "notebooks/micro/00_Introduction.ipynb", "max_forks_repo_name": "jhconning/teaching", "max_forks_repo_head_hexsha": "d89d29465e97cbb3bcb99c82f20af68bb2361ace", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-08-17T17:38:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T01:39:31.000Z", "avg_line_length": 71.3034623218, "max_line_length": 22352, "alphanum_fraction": 0.8280205656, "converted": true, "num_tokens": 1454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17553806499717958, "lm_q2_score": 0.20181322226037882, "lm_q1q2_score": 0.03542590252643263}}
{"text": "11/24/2018\n# Learning and Exploring Artificial Neural Networks\nI've always been interested in technology and exploring how the body works from since I can remember.  Simulating the entire human body in a computer is the ultimate goal of mine, but the practicallity of that is years off in the future.  I'm mostly interested in simulating the human mind, not because it would be a great scientific feat, but for the very fact that it can be maniuplated.  This interest of mine landed me on the font door step of artificial intelligence (AI).  Before I sat down and started studying about AI, I wanted to get an appreciation for the subject matter.  I've started to look at a lot of video's that were informative about AI at the 10,000ft level over the course of a couple months.  This appreciation period made me realize that I wanted to study deep learning.  Deep learning is part of machine learning and machine learning is part of AI. I also wanted to figure out where to start my study, top down or bottom up.  Even though a top down approach would of allowed me to get started doing real practical work, I'm the type of person who enjoys starting from the bottom up and learning the fundamentals.  Therefore, I decided to start as far back as practically possible, the history of the perceptron.\n\n<figure style=\"text-align:center;\">\n  \n  <figcaption>Artificial Intelligence, Machine Learning, and Deep Learning Relationship</figcaption>\n</figure> \n\n# Brief History Overview\nArtificial Neural Networks (ANN's) are inspired by the brain, a biological neural network.  Neural networks are made up of connected neurons to carry out specific functions/computations when activated.  [Warren Sturgis McCulloch](https://en.wikipedia.org/wiki/Warren_Sturgis_McCulloch), a neurophysiologist, and [Walter Pitts](https://en.wikipedia.org/wiki/Walter_Pitts), a logician, worked in the field of computational neuroscience and created computational models based on mathematical algorithms called threshold logic.  [Frank Rosenblatt](https://en.wikipedia.org/wiki/Frank_Rosenblatt) introduced the perceptron in 1958 inspired by the earlier work of Warren McCulloch.  There was an optimism about the power of the perceptron. In the 1960's the optimism came to a halt after [Marvin Minksy's](https://en.wikipedia.org/wiki/Marvin_Minsky) and [Seymour Papert's](https://en.wikipedia.org/wiki/Seymour_Papert) 1969 book, [Perceptrons](https://www.amazon.com/Perceptrons-Introduction-Computational-Geometry-Expanded/dp/0262631113), was published.  The book showed there're severe limitations to what the perceptron can do and that Frank's claims were exaggerated.  One of the limitations of the perceptron is its inability to solve a simple function called, the [exclusive disjunction (XOR)](https://en.wikipedia.org/wiki/Exclusive_or).  This had a negative effect of the research community and research in connectionism stopped for 10 years.  To learn more about the building blocks the perceptron is built on, read the book, [Neural Networks. A Systematic Introduction](https://www.semanticscholar.org/paper/Neural-Networks-A-Systematic-Introduction-Rojas/0ab5e90d14264b7faf406c15615a4f08cc945f27).\n\n# What is a Neuron?\nThe neuron is the basic working unit of the brain, a specialized cell designed to transmit information to other nerve, muscle, or gland cells.  It was estimated that a human brain has approximately 100 billion neurons, but no one knew where this number came from.  Brazilian researcher, [Dr. Suzana Herculano-Houzel](https://en.wikipedia.org/wiki/Suzana_Herculano-Houzel), decided to find out where this number originated, but didn't have much luck.  She decided to count them herself and discovered a method to do just that.  She discovered the human brain has approximately 86 billion neurons in total.  This may seem like a small difference from 100 billion, so to provide more context around this number, the following is a list of other animals and the number of neurons they have:\n\n- Fruit fly: 100 thousand neurons\n- Cockroach: One million neurons\n- Mouse: 75 million neurons\n- Cat: One billion neurons\n- Chimpanzee: 7 billion neurons\n- Elephant: 23 billion neurons\n\nMost neurons have a cell body, an axon, and dendrites. The cell body contains the nucleus and cytoplasm. The axon extends from the cell body and often gives rise to many smaller branches before ending at nerve terminals. Dendrites extend from the neuron cell body and receive messages from other neurons. Synapses are the contact points where one neuron communicates with another. The dendrites are covered with synapses formed by the ends of axons from other neurons.  \n<br>\n<br>\n<figure style=\"text-align:center;\">\n  \n  <figcaption>Real Neuron (credit: Blake Richards)</figcaption>\n</figure> \n<br>\n<br>\n<figure style=\"text-align:center;\">\n  \n  <figcaption>Biological Neuron</figcaption>\n</figure> \n<br>\n<br>\n\n# Perceptron\nA perceptron is an algorithm that is inspired by a single biological neuron. There has been a lot of research over the years inventing the building blocks of the perceptron.  Read [Threshold Logic](ThresholdLogic.ipynb) to get a perspective on what it took to get here. The perceptron algorithm is more formally called a binary classifier, a type of linear classifier. A classifier separates data into categories, and in this case, the perceptron is designed to predict the inputs category.  Our brains do this without much effort, such as classifying mammales and reptiles, fruit and vegtables, and ect.  The perceptron simply takes some inputs and performs a mathematical process and spits out an output/classification/prediction.  In order to look into this mathematical process in more detail, let's look at a more detailed graph.\n\n<figure style=\"text-align:center;\">\n  \n  <figcaption>Formal Perceptron Structure - Details</figcaption>\n</figure> \n\nThe perceptrons' algorithm computes the output in two steps and they're described in the blue circle.  The first step is to compute the weighted sum of the inputs, called $z$.  The second step computes the activation function with the input $z$.  This two step process, is called the Feed Forward process. In the machine learning field, the output of a perceptron is called a prediction.\n\n<ol>\n  <li>Weighted Sum of the Inputs<br>\n      This is the sum of all inputs multiplied by their weighted connections.\n  </li>\n  <li>Activation Function<br>\n      There're many different types of activation functions and they translate the output to be within a desired range. This is an important concept in neural network based machine learning.  \n  </li>\n</ol>\n\nLet's look at a perceptron with 2 inputs.  The inputs and outputs of a perceptron are just numbers. The activation function of a binary classifier takes some inputs and produces a binary output (i.e. {-1, 1}). What mathematical function can turn any number (i.e. weighted sum) into a binary output?  The Sign function is one such function, and it will be used as the activation function in the implementation.  Simply, the Sign function takes any number as an input and then outputs a binary value, i.e {-1, 1}.  The formal Sign function is defined in the equation below.\n\n\\begin{equation}\n  sgn(x)=\\begin{cases}\n    -1, & \\text{if $x<0$},\\\\\n    0, & \\text{if $x=0$},\\\\\n    1, & \\text{if $x>0$}\n  \\end{cases}\n\\end{equation}\n\nI said we need a activation function that outputs a binary value, but the above Sign equation outputs three values {-1, 0, 1}.  We have to simplify it for implementation purposes, and the modified definition is shown below.  Take notice that it now outputs two values {-1, 1}.\n\n\\begin{equation}\n  sgn(x)=\\begin{cases}\n    -1, & \\text{if $x<0$},\\\\\n    1, & \\text{if $x\\geq0$}\n  \\end{cases}\n\\end{equation}\n\nNow that we have an appropriate activation function, the perceptron looks like the following computational graph below.  You can see the two computational steps, weighted sum and activation function, described in the blue circle.  The computation is also written out in mathematical notation.\n\n<figure style=\"text-align:center;\">\n  \n  <figcaption>Formal Perceptron Structure - Details</figcaption>\n</figure> \n<br>\n\n$$prediction = sgn(x_1 \\cdot w_1+x_2 \\cdot w_2)$$  \n<br>\n\nLet's take a minute to look at what we are trying to do again.  We want our perceptron to predict what category our set of inputs, $x_1$ and $x_2$, belong to.  The categories are not known at this point, but we will cover that later.  $x_1$ and $x_2$ are the inputs that will be fed into an equation to compute a prediction, but what are the weights, $w_1$ and $w_2$?  These weights will need to be **learned** using a supervised learning algorithm.  The learning process will find the optimum weights to correctly categorize the inputs.  Before the learning process starts, these weights will be set to random values. Initializing the weights of a perceptron can be more sophisticated than randomly assigning values, but it's not in the scope of this paper.  If you want to read more about it, check out this notebook, [Initialization Notebook](NeuralNetworkInitialization.ipynb).\n\nA perceptron learns by training it with training data.  Training data is a set of inputs and outputs.  The outputs are typically called labels in a training set.  I know this sounds very vauge, so let's walk-thru an analogy.  Let's imagine a kid is trying to learn the difference between dog and cat pictures.  The kid might have a set of dog and cat pictures with the answers on the back.  The kid would look at each picture, guess whether it's a picture of a dog or cat, and then look at the answers on the back to determine if the guess was correct.  If the kid guessed correctly, he does nothing.  If the kid guessed incorrectly, he'll make the appropriate adjustments in his mind.  For instance, maybe the kid didn't know cats can be bigger than dogs and might classify a large cat as a dog.  The kid will remember that some cats are bigger than dogs so next time he doesn't make the same mistake.  With enough time, the kid will be able to classify all the pictures correctly.  In this analogy, the set of pictures is considered the training data where the pictures would be the inputs and the answers on the back would be the lables/outputs.  Once a perceptron is trained, it should be able to correctly classify dog and cat pictures that it hasn't seen before.\n\nUsing the same analogy, we can imagine that if the kid did classify a picture incorrectly, he'll be able to tell you how much he was off.  For instance, classifying a Pitbull as a cat is much more incorrect than classifying a Chihuahua as a cat.  This is very important for perceptrons because if the error can be computed then the algorithm can be adjusted accordingly.  With a prediction and a label, an error can be computed.  The error is computed by subtracting the prediction from the label.\n\n$$error = label - prediction$$\n\nThe above $error$ function computes the cost for one training example, but we need to compute the cost/error for all training examples.  Before we do this, let's use standard mathematical notation.  For each value $i$ in the training example, we can say that $t^{(i)}$ is the target value for the $i^{th}$ training example and $y^{(i)}$ is the guess produced by the current set of weights in the perceptron.  Let's look at the above $error$ function again using this new notation.\n\n$$E = t^{(i)} - y^{(i)}$$\n\nTherefore, the cumulative error/cost for the training data is defined below.  If you're familiar with statistics, you'll recognize the formula as the [Mean Squared Error (MSE)](https://en.wikipedia.org/wiki/Mean_squared_error).\n\n$$E=\\dfrac{1}{2}\\sum_i(t^{(i)}-y^{(i)})^{2}$$\n\nAll possible error values for a perceptron are  in the table below.\n\n| label | prediction | error |\n| :---: | :---: | :---: |\n| -1 | -1 | 0 |\n| -1 | 1 | -2 |\n| 1 | -1 | 2 |\n|  1 | 1 | 0 |\n\nOnce the error can be computed, then how is the algorithm adjusted so that it learns not to make the same mistake in the future.  As stated above, the weights, $w_1$ and $w_2$, need to be adjusted up or down relative to the magnitude of the error.  The amount $w_1$ and $w_2$ change is defined by the mathemtatical terms $\\Delta w_1$ and $\\Delta w_2$.  These terms can be read as \"the change in $w_1$ and the change in $w_2$\".  For instance, if it's determined that the weights need to be changed by 2, then $w_1$ and $w_2$ will decrease by 2. $\\Delta w_1$ and $\\Delta w_2$ do not have to be the same value, but they can be different.  Below are the equations that represent how to change the weights.\n\n$$w_1 = w_1 - \\Delta w_1$$\n$$w_2 = w_2 - \\Delta w_2$$\n\n$$\\text{Generically, } w_n = w_n - \\Delta w_n$$\n\nNow that we have the equations to adjust the weights, how are the delta's, $\\Delta w_n$, computed? The $\\Delta w_n$ will be computed using a process called gradient descent.  Gradient descent is not in the scope of this article, because there's already so much information on the internet about it, for instance, [Gradient Decent](https://en.wikipedia.org/wiki/Gradient_descent). \n\nDiscuss exactly how and why the equations are the way they are.  Why multiply the error to the input?  What does it mean to multiply an error to an input?\n\nThe learningRate is a configurable parameter to adjust how fast to move down the gradient.  The $\\Delta w_n$ can be computed using gradient descent as follows,\n\n$$\\Delta w_1 = error \\cdot x_1 \\cdot learningRate$$\n$$\\Delta w_2 = error \\cdot x_2 \\cdot learningRate$$\n\n$$\\text{Generically, }\\Delta w_n = error \\cdot x_n \\cdot learningRate$$\n\nNow that the feed forward algorithm and gradient descent can be computed, lets look at the entire supervised learning algorithm and then implement it in code.\n\n1. Initialize a perceptron with random weights\n2. Provide the perceptron with training data and the labels\n3. Ask the perceptron to compute a prediction with a $sgn(x)$ function (a function that return's -1 or 1)\n4. Compute the error (Did the perceptron get the answer right or wrong?)\n5. Adjust weights with respect to the error\n6. Return to step 2 and repeat\n\n<figure>\n  \n</figure> \n\nThere is a problem with the above perceptron.  Imagine if $x_1$ and $x_2$ are both 0, then it wouldn't matter what $w_1$ and $w_2$ are because they would always end up being 0 too.  To fix this problem, another input is added called the bias and the bias is always 1.  The algorithm will work the same, but instead of 2 inputs, it will work with three inputes with bias always being 1.  The bias will ensure that at least one input is not 0.  The figure below illustrates this concept.\n\n<figure>\n  \n</figure> \n\nTherefore, if a perceptron represents a liner line $y=mx+b$, then the line can be described as, ($x_3$ is the bias)\n\n$$w_1 \\cdot x_1 + w_2 \\cdot x_2 + w_3 \\cdot x_3 = 0$$\n$$w_2 \\cdot x_2 = -w_1 \\cdot x_1 - w_3 \\cdot x_3$$\n$$x_2 = \\dfrac{-w_1}{w_2} \\cdot x_1 - \\dfrac{w_3}{w_2} \\cdot x_3$$\n\n\nLet's jump right into the implementation. First let's add some library references that we'll need\n\n\n```python\n%matplotlib inline\nimport plotly.offline as plt\nimport plotly.graph_objs as go\nimport numpy as np\n```\n\nTo start, object-oriented programming will be used for better understanding.  The object that needs to be implemented is Perceptron. The Perceptron class is implemented as follows...\n\n\n```python\n# ---------------------------\n# class: Perceptron\n# This perceptron has three inputs (including bias) and one output\n# ---------------------------\nclass Perceptron:\n    def __init__(self, numberOfFeatures, learningRate, bias, epochs):\n        # create (numberOfFeatures) random weights (float) between -1 and 1\n        # create an additional weight for the bias\n        self.weights = np.random.uniform(-1, 1, numberOfFeatures + 1)\n        self.learningRate = learningRate\n        self.error = []\n        self.bias = bias\n        self.epochs = epochs\n    \n    # ---------------------------\n    # Feed forward algorithm that takes inputs \n    # and produces and outputs \n    # ---------------------------\n    def predict(self, inputs):\n        weightedSum = 0\n        \n        # compute the weighted sum\n        # first handle the bias\n        weightedSum += self.bias * self.weights[0]\n        # second, use dot product to calculated a weighted sum of the inputs and weights\n        weightedSum = np.dot(inputs, self.weights[1:])\n        \n        # pass the weighted sum to the sign function (activation function)\n        output = self.sign(weightedSum)\n        \n        #return output\n        return output\n    \n    # ---------------------------\n    # Activation Function - Basic step function\n    # Return 1 if n is 1 or greater, else -1\n    # ---------------------------\n    def sign(self, n):\n        if n >= 0:\n            return 1\n        else:\n            return -1\n    \n    # ---------------------------\n    # Trains the perceptron by determining the outputs\n    # error and progating it backwards through the perceptron\n    # ---------------------------\n    def train(self, inputs, labels):\n\n        for epoch in range(self.epochs):\n            e = 0\n            for inpt, label in zip(inputs, labels):\n                guess = self.predict(inpt)\n                error = label - guess\n\n                #Adjust all the weights\n                self.weights[0] += self.learningRate * error * self.bias\n                self.weights[1:] += self.learningRate * error * inpt\n\n                e += int((error * self.learningRate) != 0.0)\n               \n            self.error.append(e)\n        \n\n```\n\nBelow is an arbitrary data set plotted on a graph with a line through them.  The goal of this perceptron is to classify what points are below and above a given line.  What it means for a perceptron to learn to classify is that it learns a mathematical function to separate the two groups.  The mathematical function it will learn is represented by the line below.  Therefore, a perceptron or neural network is call a \"Univesral Function Approximater\".  The data points below represent training data for the perceptron.  Once the perceptron is trained it will be able to take in data points not listed in the graph below and predict if the point is below or above the line.  The perceptron that will be implemented will be trained using supervised learning and takes in inputs and outputs a 1 above the line and -1 for below the line.  The supervised learning approach means the training data below will be fed into the perceptron one-by-one and if it predicts the wrong category the perceptron will be penalized by tweaking it's algorithm programmatically.  Tweaking of the algorithm is known as gradient decent.  If the perceptron predicts the correct category, no penalty.  After training, the perceptron should be able to predict the correct category for data points not in the training set.\n\nThe formula for a line is represented like, $y=mx+b$.  The line that our perceptron will try to approximate below is $y=0.5x+20$.  As indicated in the graph below, the line passes through the y-intercept at 20 and has a slope of 0.5.\n\nLet's create some random points\n\n\n```python\n# Set number of points\nnumberOfPoints = 500\n\n# Initialize the points and labels array\npoints = np.zeros(shape=(numberOfPoints, 2))\nlabels = []\n\n# Initialize random points between 1 and 100\nfor i in range(numberOfPoints):\n    x = np.random.randint(-250, 250)\n    y = np.random.randint(-250, 250)\n    label = 1 if (x>y) else -1\n    points[i] = [x,y]\n    labels.append(label)\n```\n\nNow let's plot the random points on a graph\n\n\n```python\n# Create scatter plot points using the random points created above\n# All x-coordinates go into one array and all y-coordinates into another\ngraphPoints = go.Scatter(\n    x = points[:, [0]].flatten(),\n    y = points[:, [1]].flatten(),\n    mode = 'markers',\n    marker = dict(\n        symbol = 'circle'\n    ),\n    name = 'Random Data'\n    \n)\n\nlayout = go.Layout(\n    title='Random Data Points',\n    xaxis=dict(\n        title='$x-axis\\\\text{ }(x_1)$'\n    ),\n    yaxis=dict(\n        title='$y-axis\\\\text{ }(x_2)$'\n    )\n)\n\nfig = go.Figure(data=[graphPoints], layout=layout)\nplt.iplot(fig)\n\n```\n\nLet's graph a line through the points in which we want to perdict\n\n\n```python\n# Plot a line y=mx+b\nx = np.linspace(-250,250,2)\nm = 0.5\nb = 20\ny = m*x+b\n\nline = go.Scatter(\n    x = x,\n    y = y,\n    name = 'Seperate Categories'\n)\n\nlayout.title = 'Line to Seperate Categories'\nfig = go.Figure(data=[graphPoints, line], layout=layout)\nplt.iplot(fig)\n```\n\nNow let's create a Perceptron and use it to guess if the points are above the line or below the line\n\n\n```python\n# \n# 1. Using the untrained perceptron, guess if the data points are above or below the line\n# 2. Train the perceptron\n# 3. Using the trained perceptron, guess if the data points are above or below the line\n#\n# Note: Green points mean a correct prediction and red points mean an incorrect prediction.\n# After the perceptron is trained, all points should be green\n#\n\n# Create a Perceptron\nnumberOfFeatures = 2\nlearningRate = 0.001\nbias = 1\nepochs = 100\nperceptron = Perceptron(numberOfFeatures, learningRate, bias, epochs)\n\n# Display the Perceptrons' predictions\n# The predictions are incorrect because the perceptron hasn't been trained\n# \nc = np.empty(shape=(0, 2))\nw = np.empty(shape=(0, 2))\n\nfor point, label in zip(points, labels):\n    guess = perceptron.predict(point)\n    \n    if guess == label:\n        c = np.append(c, np.array([point]), axis=0)\n    else:\n        w = np.append(w, np.array([point]), axis=0)\n\ncorrect = go.Scatter(\n    x = c[:, [0]].flatten(),\n    y = c[:, [1]].flatten(),\n    mode = 'markers',\n    marker = dict(\n        symbol = 'circle',\n        color = 'rgb(0, 255, 0)'\n    ),\n    name = 'Perceptron Guessed Right'   \n)\n\nwrong = go.Scatter(\n    x = w[:, [0]].flatten(),\n    y = w[:, [1]].flatten(),\n    mode = 'markers',\n    marker = dict(\n        symbol = 'circle',\n        color = 'rgb(255, 0, 0)'\n    ),\n    name = 'Perceptron Guessed Wrong'  \n)\n\nlayout.title = 'Untrained'\nfig = go.Figure(data=[correct, wrong, line], layout=layout)\nplt.iplot(fig)\n```\n\nThe perceptron does poorly at guess which points are above and below the line.  The green points indicate a correct guess by the perceptron and red otherwise.\n\nNext, let's train the perceptron.\n\n\n```python\n# Train the Perceptron\nperceptron.train(points, labels)\n```\n\nNow let's see how the perceptron performs now\n\n\n```python\nc = np.empty(shape=(0, 2))\nw = np.empty(shape=(0, 2))\n\n# Display the Perceptrons' predictions\n# The predictions are correct because the perceptrons has been trained\nfor point, label in zip(points, labels):\n    guess = perceptron.predict(point)\n    \n    if guess == label:\n        c = np.append(c, np.array([point]), axis=0)\n    else:\n        w = np.append(w, np.array([point]), axis=0)\n\ncorrect = go.Scatter(\n    x = c[:, [0]].flatten(),\n    y = c[:, [1]].flatten(),\n    mode = 'markers',\n    marker = dict(\n        symbol = 'circle',\n        color = 'rgb(0, 255, 0)'\n    ),\n    name = 'Perceptron Guessed Right'   \n)\n\nwrong = go.Scatter(\n    x = w[:, [0]].flatten(),\n    y = w[:, [1]].flatten(),\n    mode = 'markers',\n    marker = dict(\n        symbol = 'circle',\n        color = 'rgb(255, 0, 0)'\n    ),\n    name = 'Perceptron Guessed Wrong'  \n)\n\nlayout.title = 'Trained'\nfig = go.Figure(data=[correct, wrong, line], layout=layout)\nplt.iplot(fig)   \n```\n\nIt's good to always view how well your algorithm does over time.  Looking at the loss/error can give us a good indication that the algorithm is working and getting better with each iteration.  This will be very important when implementing multi-layer neural networks. The error should be minimized to zero for perfect solution.  These parameters\n\n    numberOfFeatures = 2\n    learningRate = 0.001\n    bias = 1\n    epochs = 100\n\ncan be experimented with to see how it affects the algorithms performance.  For instance, with a small learning rate and a large feature set, the algorithm error function should converge to zero relatively slowely.\n\n\n```python\nprint(perceptron.error)\n```\n\n    [21, 7, 15, 15, 15, 12, 12, 12, 12, 12, 12, 12, 12, 8, 10, 10, 10, 10, 9, 10, 9, 9, 10, 9, 9, 10, 9, 9, 9, 10, 9, 9, 9, 9, 6, 6, 9, 6, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n\n\n\n```python\nerrorGraphPoints = go.Scatter(\n    x = np.linspace(0, len(perceptron.error), len(perceptron.error)),\n    y = perceptron.error,\n    mode = 'lines',\n    marker = dict(\n        symbol = 'circle',\n        color = 'rgb(0, 255, 0)'\n    ),\n    name = 'Loss'   \n)\n\nlayout = go.Layout(\n    title='Loss',\n    xaxis=dict(\n        title='Epochs'\n    ),\n    yaxis=dict(\n        title='Error'\n    )\n)\n\nfig = go.Figure(data=[errorGraphPoints], layout=layout)\nplt.iplot(fig)   \n```\n", "meta": {"hexsha": "f5459094922405c1569af6aae2895757d208dc81", "size": 531553, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": ".ipynb_checkpoints/Perceptron-checkpoint.ipynb", "max_stars_repo_name": "deflagg/ArtificialNeuralNetworkStudy", "max_stars_repo_head_hexsha": "d52360b47e2ee18214ec254cd3fb37cc001cbea5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-12-22T17:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-15T10:29:19.000Z", "max_issues_repo_path": ".ipynb_checkpoints/Perceptron-checkpoint.ipynb", "max_issues_repo_name": "deflagg/ArtificialNeuralNetworkStudy", "max_issues_repo_head_hexsha": "d52360b47e2ee18214ec254cd3fb37cc001cbea5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": ".ipynb_checkpoints/Perceptron-checkpoint.ipynb", "max_forks_repo_name": "deflagg/ArtificialNeuralNetworkStudy", "max_forks_repo_head_hexsha": "d52360b47e2ee18214ec254cd3fb37cc001cbea5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 102.6164092664, "max_line_length": 105353, "alphanum_fraction": 0.8429752066, "converted": true, "num_tokens": 6399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.08151975374329136, "lm_q1q2_score": 0.03537806213996668}}
{"text": "# Analysis of the Cicero corpus & comparison to other authors and works\n\n\n```python\nimport os.path\nfrom collections import Counter\nfrom glob import glob\nimport inspect\nimport os\nimport pickle\nimport sys\nfrom typing import List, Dict, Tuple\n\nfrom cltk.corpus.latin.phi5_index import PHI5_INDEX\nfrom cltk.corpus.readers import get_corpus_reader\nfrom cltk.stem.latin.j_v import JVReplacer\nfrom cltk.stem.lemma import LemmaReplacer\nfrom cltk.tokenize.latin.sentence import SentenceTokenizer\nfrom cltk.tokenize.word import WordTokenizer\nfrom random import sample\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MaxNLocator\nplt.style.use('fivethirtyeight')\n\n\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\nsys.path.insert(0,parentdir)\n \nfrom mlyoucanuse.aeoe_replacer import AEOEReplacer\nfrom mlyoucanuse.text_cleaners import ( normalize_accents, disappear_angle_brackets,\n                                        drop_punct, disappear_round_brackets,\n                                        truecase, dehyphenate, accept_editorial,\n                                        swallow_braces, swallow_obelized_words,\n                                        swallow_square_brackets)\n```\n\n\n```python\nfrom scipy.optimize import curve_fit\nimport numpy as np\n```\n\n\n```python\nimport cltk\ncltk.__version__\n```\n\n\n\n\n    '0.1.121'\n\n\n\n## Text Cleaning\nfrom http://udallasclassics.org/wp-content/uploads/maurer_files/APPARATUSABBREVIATIONS.pdf\n\n[...] Square brackets, or in recent editions wavy brackets \u02ba{...}\u02ba, enclose words etc. that an editor thinks should be deleted (see \u02badel.\u02ba) or marked as out of place (see \u02basecl.\u02ba).\n\n[...] Square  brackets  in  a  papyrus  text, or in an  inscription,  enclose  places  where words have been lost through physical damage.  If this happens in mid-line, editors  use  \u02ba[...]\u02ba.    If  only  the  end  of  the  line  is  missing,  they  use  a  single  bracket \u02ba[...\u02ba      If  the  line\u02b9s  beginning  is  missing,  they  use  \u02ba...]\u02ba    Within  the  brackets, often each dot represents one missing letter.\n\n[[...]] Double brackets enclose letters or words deleted by the medieval copyist himself.\n\n(...) Round  brackets  are  used  to  supplement  words  abbreviated  by  the  original  copyist; e.g. in an inscription: \u02batrib(unus) mil(itum) leg(ionis) III\u02ba\n\n<...> diamond  (  =  elbow  =  angular)  brackets  enclose  words  etc.  that  an  editor  has  added (see \u02basuppl.\u02ba)\n\n\u2020   An obelus (pl. obeli) means that the word(s etc.) is very plainly corrupt, but the editor  cannot  see  how  to  emend.    If  only  one  word  is  corrupt,  there  is  only  one obelus, which precedes the word; if two or more words are corrupt, two obeli  enclose  them.    (Such  at  least  is  the  rule--but  that  rule  is  often  broken,  especially  in  older  editions,  which  sometimes  dagger  several  words  using  only one obelus.)  To dagger words in this way is to \u02baobelize\u02ba them.\n\n## Load/Build Truecasing dictionary; count all cased tokens, use to normalize cases later\n\n\n```python\ntruecase_file = 'truecase_counter.latin.final.pkl'\n\nif os.path.exists(truecase_file):\n    with open(truecase_file, 'rb') as fin:        \n        case_counts = pickle.load(fin)\nelse:\n    tesserae = get_corpus_reader(corpus_name='latin_text_tesserae', language='latin')\n    case_counts = Counter()\n    jv_replacer = JVReplacer()\n    aeoe_replacer = AEOEReplacer()\n    toker = WordTokenizer('latin')\n    sent_toker = SentenceTokenizer()\n    lemmatizer = LemmaReplacer('latin')\n    \n    for file in tqdm(tesserae.fileids(), total=len(tesserae.fileids())):\n        for sent in tesserae.sents(file):\n            sent = aeoe_replacer.replace(jv_replacer.replace(drop_punct(sent)))\n            sent = normalize_accents(sent)\n            sent = accept_editorial(sent)\n            for idx, token in enumerate(toker.tokenize(sent)):\n                if idx ==0: # skip the first word, it almost always capitalized\n                    continue\n                case_counts.update({token:1})\n                \n    with open(truecase_file, 'wb') as fout:        \n        pickle.dump(case_counts, fout) \n\nlen(case_counts)\n# 344393, 322711  \n# 318451\n# 316722\n# 311399\n# 310384\n# 310567\n# 309529\n```\n\n\n\n\n    309529\n\n\n\n\n```python\nprint(sample(list(case_counts.items()), 25))\n```\n\n    [('ligula', 1), ('inponerent', 4), ('oblidere', 1), ('stridebit', 2), ('Hectorem', 12), ('obtemperabat', 4), ('Gabathites', 1), ('terreant', 5), ('corrupimus', 1), ('uigentes', 7), ('saepedicto', 1), ('coniugio', 61), ('\u03bc\u03bf\u03bd\u03bf\u03c4\u03bf\u03bd\u03b9\u0301\u03b1', 1), ('skai', 1), ('sationibus', 5), ('Suffusus', 1), ('\u03b5\u0313\u0301\u03b3\u03b3\u03b9\u03bf\u03bd', 1), ('\u03bf\u1f50\u03c1\u03b1\u03bd\u1f78\u03c2', 3), ('adhereret', 1), ('supercrepitante', 1), ('coli', 92), ('adolet', 3), ('discessisset', 20), ('Comploratum', 1), ('Decumo', 1)]\n\n\n\n```python\ndef get_word_counts(files:List[str])->Tuple[Dict[str, int], Dict[str, int]]:\n    \"\"\"\n    Given a list of files, \n    clean & tokenize the documents\n    returns: Tuple(counter of lemmatized words, counter of inflected words)\n    \"\"\"\n    lemma_word_counter = Counter()\n    inflected_word_counter = Counter()\n    jv_replacer = JVReplacer()\n    aeoe_replacer = AEOEReplacer()\n    toker = WordTokenizer('latin')\n    sent_toker = SentenceTokenizer()\n    lemmatizer = LemmaReplacer('latin')\n\n    for file in files: # , total=len(files), unit='files'):\n        with open(file, 'rt') as fin:\n            text = fin.read()\n            text = text.replace(\"-\\n\", \"\")\n            text = text.replace(\"\\n\", \" \")\n            text = aeoe_replacer.replace(jv_replacer.replace( text))\n            for sent in sent_toker.tokenize(text):\n                sent = dehyphenate(sent) # because it's Phi5\n                sent = swallow_braces(sent)\n                sent = swallow_square_brackets(sent)\n                sent = disappear_round_brackets(sent)\n                sent = swallow_obelized_words(sent)\n                sent = disappear_angle_brackets(sent)            \n                sent = drop_punct(sent)\n                sent = normalize_accents(sent)            \n                # lemmatizer prefers lower \n    #             sent = lemmatizer.lemmatize(sent.lower(), return_string=True)\n                for word in toker.tokenize(sent):\n                    if word.isnumeric():\n                        continue\n                    inflected_word_counter.update({truecase(word, case_counts) : 1})                    \n                    word = lemmatizer.lemmatize(word.lower(), return_string=True)\n                    # normalize capitals\n                    lemma_word_counter.update({truecase(word, case_counts) : 1})\n    return  inflected_word_counter, lemma_word_counter\n```\n\n\n```python\ndef word_stats(author:str,\n               inflected_counter:Counter,\n                lemma_counter:Counter)->Tuple[float, float]:\n    \"\"\"\n    Compute statistics for an author's corpus\n    \"\"\"\n    nw = sum(lemma_counter.values())\n    print(f\"Total count of all word tokens in {author} corpus: {nw:,}\")\n    print(f\"Total number of distinct, inflected words/tokens in {author} corpus: {len(inflected_counter):,}\")\n    print(f\"Total number of lemmatized words/tokens in {author} corpus {len(lemma_counter):,}\")\n    # Count of inflected unigrams occuring only once\n    ciw1 = sum([1 for key, val in inflected_counter.items() if val == 1]) \n    print(f\"Count of inflected tokens only occuring once {ciw1:,}\")\n    # Count of lemmatized unigrams occuring only once\n    cw1 = sum([1 for key, val in lemma_counter.items() if val == 1])\n    print(f\"Count of lemmatized tokens only occuring once {cw1:,}\")\n    Piu_one = round(ciw1 / nw,3)\n    print(f\"Probability of a single count unigram occuring in the {author} corpus: {Piu_one:.3f}\") \n    Plu_one = round(cw1 / nw, 3)\n    print(f\"Probability of a single count lemmatized unigram in a novel form occuring in the {author} corpus: {Plu_one:.3f}\") \n    return (Piu_one, Plu_one)\n```\n\n\n```python\n# Cicero works\ncicero_files = glob(f\"{os.path.expanduser('~')}/cltk_data/latin/text/phi5/individual_works/LAT0474.TXT-0*.txt\")\nlen (cicero_files)              \n```\n\n\n\n\n    75\n\n\n\n\n```python\ncicero_lemmas_counter_file = 'cicero_lemmas_counter.pkl'\ncicero_inflected_counter_file = 'cicero_inflected_counter.pkl'\n\nif os.path.exists(cicero_lemmas_counter_file) and os.path.exists(cicero_inflected_counter_file):\n    with open(cicero_lemmas_counter_file, 'rb') as fin:\n        cicero_lemmas = pickle.load(fin)\n    with open(cicero_inflected_counter_file, 'rb') as fin:\n        cicero_inflected_words = pickle.load(fin)\nelse:\n    cicero_inflected_words, cicero_lemmas  = get_word_counts(cicero_files)\n```\n\n\n```python\nif not os.path.exists(cicero_lemmas_counter_file):\n    with open(cicero_lemmas_counter_file, 'wb') as fout:\n        pickle.dump(cicero_lemmas, fout)\nif not os.path.exists(cicero_inflected_counter_file):\n    with open(cicero_inflected_counter_file, 'wb') as fout:\n        pickle.dump(cicero_inflected_words, fout)\n```\n\n\n```python\nword_stats(author='Cicero',           \n            inflected_counter=cicero_inflected_words,\n            lemma_counter=cicero_lemmas)\n```\n\n    Total count of all word tokens in Cicero corpus: 1,196,512\n    Total number of distinct, inflected words/tokens in Cicero corpus: 75,705\n    Total number of lemmatized words/tokens in Cicero corpus 23,345\n    Count of inflected tokens only occuring once 34,608\n    Count of lemmatized tokens only occuring once 10,656\n    Probability of a single count unigram occuring in the Cicero corpus: 0.029\n    Probability of a single count lemmatized unigram in a novel form occuring in the Cicero corpus: 0.009\n\n\n\n\n\n    (0.029, 0.009)\n\n\n\n\n```python\nword_counts =  sorted(cicero_inflected_words.items(), key=lambda x:x[1], reverse=True)\n# words, counts = zip(*word_counts)\n\n```\n\n\n```python\ntop_label, side_label, bottom_label = ('Frequency Rank',\n                                       'Occurences',\n                                       'Word Frequency Distributions of the Cicero Corpus')\nfig = plt.figure(figsize=(7,5))\nplt.xlabel(top_label)\nplt.ylabel(side_label)\nplt.title(bottom_label)\nax = fig.gca()\nplt.yscale('log')\nindices, values = zip(*word_counts)\n# plt.bar(range(len(values)), values)\nplt.loglog(range(len(values)), values, label='word frequencies')\n# plt.axvline(x=np.mean(all_vals), color='k', linestyle='-', label='mean')\n# plt.axvline(x=np.mean(all_vals) + np.std(all_vals), color='b', linestyle='-', label='std')\n# plt.axvline(x=np.mean(all_vals) + (2 * np.std(all_vals)), color='m', linestyle='-', label='std2')\nplt.legend(loc='upper right')\nplt.tight_layout(pad=0.5, w_pad=20, h_pad=0.5)\n# plt.show()\nplt.savefig('cicero_frequency_distributions.png')\n```\n\n\n```python\nword_counts[:5]\n```\n\n\n\n\n    [('et', 27952), ('in', 23862), ('non', 18471), ('est', 16045), ('ut', 14957)]\n\n\n\n\n```python\nword_counts[-5:]\n```\n\n\n\n\n    [('adaequatus', 1),\n     ('obfuerint', 1),\n     ('ignorauit', 1),\n     ('erudiri', 1),\n     ('adprobarunt', 1)]\n\n\n\n\n```python\nfirst_last = word_counts[:5] +word_counts[-5:]\n```\n\n\n```python\ntop_label, side_label, bottom_label = ('Word',\n                                       'Count',\n                                       'Top 5 Cicero Words')\nfig = plt.figure(figsize=(4,5))\nplt.xlabel(top_label)\nplt.ylabel(side_label)\nplt.title(bottom_label)\nax = fig.gca()\n# plt.yscale('log')\n# word_counts[:5] +word_counts[-5:]\nindices, values = zip(*word_counts[:5])\nplt.bar(indices , values)\n# plt.loglog(range(len(values)), values, label='word frequencies')\n# plt.axvline(x=np.mean(all_vals), color='k', linestyle='-', label='mean')\n# plt.axvline(x=np.mean(all_vals) + np.std(all_vals), color='b', linestyle='-', label='std')\n# plt.axvline(x=np.mean(all_vals) + (2 * np.std(all_vals)), color='m', linestyle='-', label='std2')\nplt.legend(loc='upper right')\nplt.tight_layout(pad=0.5, w_pad=20, h_pad=0.5)\n# plt.show()\nplt.savefig('cicero_top5_words.png')\n```\n\n\n```python\nnum_f1 = sum([1 for tmp, cnt in cicero_inflected_words.items() if cnt == 1])\nnum_f2 = sum([1 for tmp, cnt in cicero_inflected_words.items() if cnt == 2])\nnum_f3 = sum([1 for tmp, cnt in cicero_inflected_words.items() if cnt == 3])\nnum_f4 = sum([1 for tmp, cnt in cicero_inflected_words.items() if cnt == 4])\nnum_f5 = sum([1 for tmp, cnt in cicero_inflected_words.items() if cnt == 5])\nvalues=[num_f5, num_f4, num_f3, num_f2, num_f1 ]\n```\n\n\n```python\nvalues\n```\n\n\n\n\n    [2622, 3936, 6095, 11858, 34608]\n\n\n\n\n```python\np0 = round(34608 / sum(cicero_inflected_words.values()),3)\np0\n```\n\n\n\n\n    0.029\n\n\n\n\n```python\nsum(cicero_inflected_words.values())\n```\n\n\n\n\n    1196512\n\n\n\n\n```python\nfor i in range(1,20):\n    print(i, sum([1 for tmp, cnt in cicero_inflected_words.items() if cnt == i]))\n```\n\n    1 34608\n    2 11858\n    3 6095\n    4 3936\n    5 2622\n    6 2018\n    7 1572\n    8 1260\n    9 1018\n    10 837\n    11 705\n    12 600\n    13 525\n    14 467\n    15 433\n    16 367\n    17 319\n    18 316\n    19 275\n\n\n\n```python\n\n```\n\n\n```python\ntop_label, side_label, bottom_label = ('Occurences',\n                                       'Counts',\n                                       'Last 5 Cicero Word Frequencies')\nfig = plt.figure(figsize=(5,5))\nplt.xlabel(top_label)\nplt.ylabel(side_label)\nplt.title(bottom_label)\nax = fig.gca()\nplt.yscale('linear')\n# indices, values = zip(*word_counts[-5:])\nvalues = [num_f1, num_f2, num_f3, num_f4, num_f5]\nplt.bar(range(1,len(values)+1), values, label='frequency counts')\n# plt.loglog(range(len(values)), values, label='word frequencies')\n# plt.axvline(x=np.mean(all_vals), color='k', linestyle='-', label='mean')\n# plt.axvline(x=np.mean(all_vals) + np.std(all_vals), color='b', linestyle='-', label='std')\n# plt.axvline(x=np.mean(all_vals) + (2 * np.std(all_vals)), color='m', linestyle='-', label='std2')\nplt.legend(loc='upper right')\nplt.tight_layout(pad=0.5, w_pad=20, h_pad=0.5)\n# plt.show()\nplt.savefig('cicero_last_five_word_frequencies.png')\n```\n\n\n```python\n# Calc lemmatized\n```\n\n\n```python\n# Probability of a single count unigram occuring in the Cicero corpus: 0.029\n# Probability of a single count lemmatized unigram in a novel form occuring in the Cicero corpus: 0.009\n# (0.029, 0.009)\n# With Curve fitting\n# Probability of encountering a new inflected word in new Cicero 0.054 (according to curve fitting)\n# Probability of encountering a new lemmatized word form in new Cicero 0.017 (according to curve fitting)\n# (0.054, 0.017)\n```\n\n\n```python\nfreq_vals = []\nnum_samples =10\nfor i in range(num_samples,0,-1):\n    freq_vals.append( (i, sum([1 for tmp, cnt in cicero_lemmas.items() if cnt == i])))\n\nX,y = zip(*freq_vals)\n# We will reverse the scale to predict the next number according to a Power Law distribution\nX =list(reversed(X))\n\ndef func_powerlaw(x, m, c, c0):\n    return c0 + x**m * c\n  \npopt, pcov = curve_fit(func_powerlaw, X, y, maxfev=2000)\nexpected_unk_count  = round(func_powerlaw(num_samples + 1 , *popt)) \nplt.figure(figsize=(5,4))\nplt.plot(X, func_powerlaw(X, *popt), '--', label='predicted counts')\nplt.plot(X[-1] + 1, func_powerlaw(X[-1]+1, *popt), '*', label='predicted unk')\nplt.plot(X, y, 'ro', label='actual counts')\nplt.title(\"Cicero Lemmatized word forms\")\nplt.xlabel(\"Frequency group\" )\nplt.ylabel(\"Count\")\nlocs, labels = plt.xticks()  \nplt.xticks(range(12), ['']+ [str(tmp) for tmp in range(10,0,-1)] +['unk']) \nplt.legend()\n# plt.show()\nplt.tight_layout(pad=0.5, w_pad=20, h_pad=0.5)\nplt.savefig('cicero_lemmatized_words_unk_prob_curve_fit.png')\n\nexpected_unk_count  = round(func_powerlaw(num_samples + 1, *popt) ) \nP_new_lemma_word = expected_unk_count / sum(cicero_lemmas.values())\nprint(f\"Expected unknown count {expected_unk_count:,}\")\nprint(f\"Probability of encountering a new lemmatized word form in new Cicero {round(P_new_lemma_word,3)} (according to curve fitting)\")\nprint(freq_vals)\n```\n\n\n```python\nfreq_vals = []\nnum_samples = 10\nfor i in range(num_samples,0,-1):\n    freq_vals.append( (i, sum([1 for tmp, cnt in cicero_inflected_words.items() if cnt == i])))\n\nX,y = zip(*freq_vals)\n# We will reverse the scale to predict the next number according to a Power Law distribution\nX =list(reversed(X))\n\ndef func_powerlaw(x, m, c, c0):\n    return c0 + x**m * c\n \npopt, pcov = curve_fit(func_powerlaw, X, y, maxfev=2000)\nexpected_unk_count  = round(func_powerlaw(num_samples + 1 , *popt)) \nplt.figure(figsize=(5,4))\nplt.plot(X, func_powerlaw(X, *popt), '--', label='predicted counts')\nplt.plot(X[-1] + 1, func_powerlaw(X[-1]+1, *popt), '*', label='predicted unk')\nplt.plot(X, y, 'ro', label='actual counts')\nplt.title(\"Cicero inflected word forms\")\nplt.xlabel(\"Frequency group\" )\nplt.ylabel(\"Count\")\nlocs, labels = plt.xticks()  \nplt.xticks(range(12), ['']+ [str(tmp) for tmp in range(10,0,-1)] +['unk']) \nplt.legend()\n# plt.show()\nplt.tight_layout(pad=0.5, w_pad=20, h_pad=0.5)\nplt.savefig('cicero_inflected_words_unk_prob_curve_fit.png')\n\nexpected_unk_count  = round(func_powerlaw(num_samples + 1 , *popt)) \nP_new_word = expected_unk_count / sum(cicero_inflected_words.values())\nprint(f\"Expected unknown count {expected_unk_count:,}\")\nprint(f\"Probability of encountering a new word in new Cicero {round(P_new_word,3)} (according to curve fitting)\")\nprint(freq_vals)\n```\n\n\n```python\n# Probability of a single count unigram occuring in the Cicero corpus: 0.029\n# Probability of a single count lemmatized unigram in a novel form occuring in the Cicero corpus: 0.009\n# (0.029, 0.009)\n# With Curve fitting\n# Probability of encountering a new inflected word in new Cicero 0.054 (according to curve fitting)\n# Probability of encountering a new lemmatized word form in new Cicero 0.017 (according to curve fitting)\n# (0.054, 0.017)\n# With Power Law Curve fitting\n# (0.074, 0.027)\n# Probability of encountering a new inflected word in a new page of Cicero: 0.074\n# Probability of encountering a new form of lemma in Cicero's use: 0.027\n\n#  So, if you found a new page of Cicero with a 100 words\n# we would expect 7 of the words to be new/hitherto/unseen in the Cicero corpus\n# we would expect 3 of the words to be words that Cicero had used before, but now in novel forms of the lemmas \n```\n\n### Good-Turing Frequency Estimation\n\\begin{align}\np_{0}={\\frac {N_{1}}{N}}\n\\end{align}\nThe probability of an unseen element is equivalent to the the probability of elements seen only once.\n\n\n```python\n88198/  1196512\n```\n\n\n\n\n    0.07371259126527774\n\n\n\n\n```python\nmalum_potest = -127.67892735847873\npotest_malum = -127.61667828754315\n```\n\n\n```python\nmalum_potest - potest_malum\n```\n\n\n\n\n    -0.06224907093557874\n\n\n\n\n```python\npotest_malum - malum_potest\n```\n\n\n\n\n    0.06224907093557874\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\nauthor_index = {val:key for key,val in PHI5_INDEX.items()  \n                if val != 'Marcus Tullius Cicero, Cicero, Tully'}\n```\n\n\n```python\ndef get_phi5_author_files(author_name, author_index):\n    stub = author_index[author_name]\n    return glob(os.path.expanduser(f'~/cltk_data/latin/text/phi5/individual_works/{stub}*.txt'))\n```\n\n## Visualization of our corpus comparison: \nIf you took one page from one author and placed it into Cicero, how surprising would it be?\n\nIf the other author's vocabulary was substantially different, it would be noticeable. We can quantify this.\n\nAs a result, since we want to predict as close as possible to the author, we should only train a language model where the underlying corpus vocabularies are within a reasonable window of surprise.\n\n\n```python\nresults = []\n# The following code assumes this is in memory:\n# cicero_lemmas, cicero_inflected_words = get_word_counts(cicero_files)    \n\nfor author in author_index:\n    files = get_phi5_author_files(author, author_index)\n    # Get a counter of all the author's distinct words & counter of words collapsed by lemmas\n    author_inflected_words, author_lemmas  = get_word_counts(files)        \n    # Calculate the overlap & find the differences; lemmas:\n    author_words = set(author_lemmas.keys())\n    cicero_words = set(cicero_lemmas.keys())\n    common = author_words & cicero_words\n    author_uniq = author_words - common \n    P_lemma_unigram_unk = len(author_uniq) / sum(author_lemmas.values())\n    # now inflected forms: \n    author_words = set(author_inflected_words.keys())\n    cicero_words = set(cicero_inflected_words.keys())\n    common = author_words & cicero_words\n    author_uniq = author_words - common \n    P_inflected_unigram_unk = len(author_uniq) / sum(author_inflected_words.values())\n    results.append((author, round(P_inflected_unigram_unk, 3), round(P_lemma_unigram_unk, 3)))\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.30files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.01s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 8/8 [00:03<00:00,  2.45files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 346.64files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 400.30files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 435.14files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 333.65files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 93.23files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:03<00:00,  3.34s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 553.41files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 588.26files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 162.91files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 144.78files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 385.29files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 428.38files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 337.38files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 175.68files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 42.95files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 196.96files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  6.68files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 94.37files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 160.28files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 154.58files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 311.33files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 10/10 [00:04<00:00,  2.24files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 13.25files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 21.29files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 10.06files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00,  3.55files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 132.55files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 418.76files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3/3 [00:00<00:00,  4.01files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 681.11files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 235.57files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 36.81files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 338.88files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 68.87files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 13.43files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 391.84files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 138.65files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 419.14files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 14.99files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 110.75files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 505.58files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 26.63files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 405.93files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 230.68files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 545.78files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4/4 [00:00<00:00, 32.93files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 345.07files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 165.49files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 549.32files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 8/8 [00:00<00:00, 29.88files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 483.83files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:01<00:00,  1.42files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 25.56files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 134.21files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.21files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 618.45files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.53files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4/4 [00:04<00:00,  1.05s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 495.31files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:02<00:00,  1.30s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 513.19files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 227.17files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00,  5.79files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 34.44files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 461.93files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 170.15files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3/3 [00:00<00:00, 12.41files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.17files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 594.85files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 212.18files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 205.94files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  6.78files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 221.29files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 165.29files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 252.33files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 516.22files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 142.81files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 7/7 [00:00<00:00, 28.17files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 207.52files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3/3 [00:03<00:00,  1.19s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 200.04files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  6.50files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 723.65files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 454.37files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 149.48files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.25s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.67files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 539.11files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 55.75files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 272.09files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 32.61files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 540.02files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 170.05files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 82.01files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 15/15 [00:09<00:00,  1.52files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.66files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 199.40files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.24s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 337.16files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 113.34files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 7/7 [00:00<00:00, 79.83files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 278.20files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 8/8 [00:00<00:00, 39.43files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 260.55files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:01<00:00,  1.65files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  5.70files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 11.07files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 155.33files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.95s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 18.50files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 483.10files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 70.45files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.53s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.59s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 26.74files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 406.31files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 464.02files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 591.66files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 372.00files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 143.16files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 178.92files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 123.05files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:05<00:00,  5.15s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 404.04files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 295.29files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.24files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 30/30 [00:04<00:00,  6.54files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 412.91files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 146.87files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 395.54files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 710.78files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 304.00files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.09s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.44s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 289.26files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6/6 [00:02<00:00,  2.23files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3/3 [00:04<00:00,  1.40s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 604.98files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6/6 [00:03<00:00,  1.84files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 10.68files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 217.82files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 17/17 [00:03<00:00,  4.69files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 132.00files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 374.42files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 14/14 [00:00<00:00, 21.05files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 472.81files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:04<00:00,  2.33s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 95.21files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.11files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 318.73files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 94.91files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:03<00:00,  3.29s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 696.50files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 220.45files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 221.60files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 286.05files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 28.34files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 261.38files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 117.98files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5/5 [00:01<00:00,  4.29files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 7/7 [00:03<00:00,  2.03files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 313.38files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 110.35files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 324.52files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.64files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 144.39files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 545.28files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 296.40files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 520.58files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 168.55files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3/3 [00:00<00:00, 21.32files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.51files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.05s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 7/7 [00:00<00:00, 21.93files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 351.49files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 628.55files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 341.78files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 498.25files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 115.50files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 574.01files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 219.97files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 108.28files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 124.44files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 321.01files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 392.32files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6/6 [00:00<00:00, 162.36files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00,  3.95files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 256.42files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 651.39files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 787.37files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 140.67files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  5.53files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.27files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 172.26files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 378.21files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 376.91files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 645.97files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 530.52files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 409.34files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 252.85files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 237.58files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 204.91files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 564.36files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 827.77files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 27.41files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 216.08files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5/5 [00:06<00:00,  1.34s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 49.64files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 537.59files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 406.54files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 619.54files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4/4 [00:21<00:00,  5.40s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 363.65files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4/4 [00:04<00:00,  1.06s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 341.75files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 257.78files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 56.50files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 111.74files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6/6 [00:01<00:00,  3.30files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 408.01files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 240.44files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.94files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 87.60files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4/4 [00:00<00:00, 212.32files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 508.09files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00,  3.88files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 8/8 [00:01<00:00,  4.09files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3/3 [00:03<00:00,  1.24s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 91.32files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 360.86files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 287.28files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3/3 [00:13<00:00,  4.47s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 116.51files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5/5 [00:00<00:00,  8.99files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 129.28files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 22.04files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 69.91files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 288.89files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 123.57files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 332.43files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 416.18files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.56files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3/3 [00:02<00:00,  1.48files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 264.69files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3/3 [00:00<00:00, 11.03files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.04s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 16.61files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 315.96files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 13.66files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 392.14files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 244.67files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00,  7.04files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 573.46files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 705.64files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 167.17files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 394.35files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 345.67files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3/3 [00:01<00:00,  1.51files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4/4 [00:00<00:00, 20.77files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 13.22files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 458.74files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  6.79files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 392.52files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 338.63files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 359.47files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 728.18files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 313.87files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 138.18files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 398.55files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3/3 [00:00<00:00, 96.26files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 259.81files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 15.52files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 544.93files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 17/17 [00:01<00:00,  9.50files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19/19 [00:00<00:00, 232.62files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 297.81files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00,  8.88files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 159.94files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4/4 [00:00<00:00, 59.36files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 444.41files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 13.35files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.54files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 465.31files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 138.83files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 694.88files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 181.13files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 569.03files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 333.09files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 93.23files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 41/41 [00:00<00:00, 327.61files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 206.62files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 302.21files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 92.11files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 681.67files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 353.37files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 11.39files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 12/12 [00:00<00:00, 12.65files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6/6 [00:01<00:00,  3.77files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 161.58files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 463.00files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 194.66files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 18/18 [00:15<00:00,  1.18files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 309.22files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 133.66files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 436.86files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 10.80files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00,  6.28files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 435.55files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 832.70files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 351.02files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 606.73files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 538.77files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 687.70files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 667.56files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 93.63files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 146.09files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:17<00:00,  8.71s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 346.04files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 140.33files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:03<00:00,  3.10s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 343.88files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 270.48files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 538.77files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 22/22 [00:08<00:00,  2.56files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 172.30files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 533.56files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 583.11files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 13.06files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 237.03files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 368.18files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 462.59files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:02<00:00,  1.08s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 117.40files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 180.99files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 260.56files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 305.82files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 171.15files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 68.87files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 241.19files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 7/7 [00:15<00:00,  2.20s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  5.30files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 536.77files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 164.21files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:35<00:00, 35.27s/files]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 191.46files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 576.93files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 237.03files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 170.13files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 322.89files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 397.79files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 412.54files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5/5 [00:00<00:00,  7.18files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 243.90files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 130.31files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [00:00<00:00, 699.05files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 70.47files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 147.18files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.98files/s]\n\n\n\n```python\nresults_map = {key: (val, val2) for key,val,val2 in results}\n```\n\n\n```python\nresults = sorted(results, key=lambda x:x[2])\n```\n\n\n```python\nfor tmp in results:\n    print(tmp)\n```\n\n    ('Publius Cominius', 0.0, 0.0)\n    ('Publius Cornelius Dolabella', 0.0, 0.0)\n    ('Gaius Calpurnius Piso', 0.0, 0.0)\n    ('Publius Saturius', 0.0, 0.0)\n    ('Lucius Cassius Longinus', 0.0, 0.0)\n    ('Gaius Memmius', 0.0, 0.0)\n    ('Passienus Crispus', 0.0, 0.0)\n    ('Marcus Antonius', 0.0, 0.0)\n    ('Caecilius Metellus', 0.0, 0.0)\n    ('Gaius Aurelius Cotta', 0.0, 0.0)\n    ('Gaius Scribonius Curio avus', 0.0, 0.0)\n    ('Vibius Crispus', 0.0, 0.0)\n    ('Gallus Antipater', 0.0, 0.0)\n    ('Lucius Herennius Balbus', 0.0, 0.0)\n    ('Marcus Antonius triumvir', 0.0, 0.0)\n    ('Sevius Nicanor', 0.0, 0.0)\n    ('Gaius Papirius Carbo Arvina', 0.0, 0.0)\n    ('Gaius vel Lucius Caepasius', 0.0, 0.0)\n    ('Titus Labienus', 0.0, 0.0)\n    ('Lucius Quinctius', 0.0, 0.0)\n    ('Q. Lutatius Catulus iunior', 0.0, 0.0)\n    ('Gaius Servilius Glaucia', 0.0, 0.0)\n    ('Gaius Aquilius Gallus', 0.0, 0.0)\n    ('Lucius Marcius Philippus', 0.0, 0.0)\n    ('Iulius Africanus', 0.0, 0.0)\n    ('Marcus Porcius Cato Uticensis', 0.0, 0.0)\n    ('Publius Clodius Pulcher', 0.0, 0.0)\n    ('Vagellius', 0.0, 0.0)\n    ('Publius Mucius Scaevola', 0.0, 0.0)\n    ('Marullus', 0.0, 0.0)\n    ('Gaius Papirius Carbo', 0.0, 0.0)\n    ('Gaius Erucius', 0.0, 0.0)\n    ('Lucius Cincius Alimentus', 0.0, 0.0)\n    ('Marcus Iuventius Laterensis', 0.0, 0.012)\n    ('Laelius Felix', 0.0, 0.016)\n    ('Lucius Cornelius Sulla', 0.017, 0.017)\n    ('P. Cornel. Scipio Nasica Ser.', 0.0, 0.018)\n    ('Lucius Licinius Crassus', 0.005, 0.02)\n    ('Iustinianus, Justinian, Digest', 0.007, 0.02)\n    ('Cn. Cornel. Lentulus Marcell.', 0.0, 0.021)\n    ('Trabea', 0.0, 0.022)\n    ('P. Cornel. Scipio Afr. ma.', 0.023, 0.023)\n    ('Q. Caecilius Metellus Maced.', 0.0, 0.024)\n    ('Gaius Asinius Gallus', 0.029, 0.029)\n    ('Aufidius Bassus', 0.0, 0.03)\n    ('Quintus Asconius Pedianus', 0.01, 0.03)\n    ('Publilius Syrus', 0.007, 0.032)\n    ('Quintus Tullius Cicero', 0.008, 0.034)\n    ('Lucilius iunior', 0.034, 0.034)\n    ('Gaius, iur., Gaius', 0.011, 0.035)\n    ('Aurelius Augustinus', 0.0, 0.037)\n    ('Titus Livius, Livy', 0.011, 0.039)\n    ('Marcus Iunius Brutus [iur.]', 0.0, 0.04)\n    ('Marcus Iunius Brutus [tyr.]', 0.04, 0.04)\n    ('Q. Caecilius Metellus Numid.', 0.021, 0.041)\n    ('Marcus Fabius Quintilianus', 0.009, 0.042)\n    ('Sentius Augurinus', 0.043, 0.043)\n    ('Quintus Lutatius Catulus', 0.03, 0.045)\n    ('Gaius Iulius Caesar, Caesar', 0.016, 0.046)\n    ('Cornelius Nepos', 0.018, 0.047)\n    ('Gaius Trebatius Testa', 0.008, 0.048)\n    ('M. Valerius Messalla Rufus', 0.027, 0.048)\n    ('Atilius', 0.048, 0.048)\n    ('Gaius Laelius Sapiens', 0.048, 0.048)\n    ('Lucius Annaeus Seneca senior', 0.016, 0.052)\n    ('Lucius Annaeus Seneca iunior', 0.013, 0.054)\n    ('Hyginus Astronomus', 0.024, 0.054)\n    ('Precatio Omnium Herbarum', 0.009, 0.055)\n    ('Publius Rutilius Lupus', 0.02, 0.055)\n    ('Q. Mucius Scaevola [pontifex]', 0.031, 0.055)\n    ('Aulus Cornelius Celsus', 0.017, 0.056)\n    ('Bellum Alexandrinum [Anonymous]', 0.018, 0.057)\n    ('Bellum Africum [Anonymous]', 0.019, 0.057)\n    ('Volcacius Sedigitus', 0.025, 0.057)\n    ('Calpurnius Flaccus', 0.01, 0.058)\n    ('Gaius Sempronius Gracchus', 0.025, 0.058)\n    ('Aulus Hirtius', 0.019, 0.059)\n    ('Gaius Sallustius Crispus', 0.021, 0.059)\n    ('Maurus Servius Honoratus, Servius', 0.025, 0.059)\n    ('Publius Terentius Afer, Terence', 0.029, 0.059)\n    ('Cornelia, mater Gracchorum', 0.012, 0.06)\n    ('Bellum Hispaniense [Anonymous]', 0.021, 0.061)\n    ('Bruttedius Niger', 0.016, 0.062)\n    ('Titus Maccius Plautus', 0.027, 0.062)\n    ('Sempronius Asellio', 0.03, 0.064)\n    ('Carmen Devotionis', 0.018, 0.065)\n    ('Publius Ovidius Naso', 0.024, 0.065)\n    ('C. Plinius Caecilius Secundus, Pliny', 0.017, 0.066)\n    ('Aulus Cascellius', 0.0, 0.067)\n    ('Marcus Porcius Cato M.f.M.n.', 0.033, 0.067)\n    ('Titus Lucretius Carus', 0.022, 0.068)\n    ('Sabidius', 0.023, 0.068)\n    ('Lucius Calpurnius Piso Frugi', 0.037, 0.07)\n    ('Titus Annius Luscus', 0.0, 0.071)\n    ('Pupius (?)', 0.0, 0.071)\n    ('Scriptores Historiae Augustae', 0.032, 0.071)\n    ('Publius Cannutius', 0.071, 0.071)\n    ('Turranius Niger', 0.071, 0.071)\n    ('Valerius Maximus', 0.02, 0.073)\n    ('Lucius Annaeus Cornutus', 0.028, 0.073)\n    ('Velleius Paterculus', 0.026, 0.074)\n    ('Quintus Curtius Rufus', 0.021, 0.075)\n    ('Helvius Mancia', 0.033, 0.075)\n    ('Siculus Flaccus', 0.02, 0.076)\n    ('Cornelius Tacitus', 0.025, 0.076)\n    ('Arbonius Silo', 0.0, 0.077)\n    ('Gnaeus Tremelius Scrofa', 0.0, 0.077)\n    ('Aulus Gellius', 0.038, 0.077)\n    ('Aemilius Sura', 0.058, 0.077)\n    ('Publius Alfenus Varus', 0.039, 0.078)\n    ('Gaius Caesius Bassus', 0.04, 0.08)\n    ('Quintus Remmius Palaemon', 0.033, 0.081)\n    ('Lucius Iulius Caesar', 0.0, 0.083)\n    ('Marcus Manilius, Manilius', 0.02, 0.083)\n    ('Aulus Cremutius Cordus', 0.025, 0.083)\n    ('Gaius Aelius Gallus', 0.029, 0.083)\n    ('Hyginus Gromaticus', 0.029, 0.083)\n    ('Marcus Cornelius Fronto', 0.036, 0.084)\n    ('Marcus Valerius Probus', 0.038, 0.084)\n    ('Pseudo-Varro', 0.03, 0.085)\n    ('Terentianus Maurus', 0.036, 0.085)\n    ('Valerius Aedituus', 0.042, 0.085)\n    ('Velius Longus', 0.042, 0.086)\n    ('Cn. Arulenus Caelius Sabinus', 0.048, 0.086)\n    ('P. Cornel. Scipio Aem. Afr.', 0.041, 0.087)\n    ('Tabulae Censoriae', 0.052, 0.087)\n    ('Aulus Caecina', 0.087, 0.087)\n    ('Appius Claudius Caecus', 0.087, 0.087)\n    ('Marcus Tullius Tiro', 0.046, 0.088)\n    ('Anonymi Grammatici', 0.036, 0.089)\n    ('Gaius Asinius Pollio', 0.036, 0.09)\n    ('Lucius Volusius Maecianus', 0.037, 0.09)\n    ('Gaius Plinius Secundus, Pliny', 0.044, 0.09)\n    ('Publilius Optatianus Porfyrius', 0.0, 0.091)\n    ('Carmen Evocationis', 0.01, 0.091)\n    ('Lucius Novius', 0.03, 0.091)\n    ('Annius Florus', 0.038, 0.091)\n    ('Aufustius', 0.045, 0.091)\n    ('Commentarius Anquisit. Sergii', 0.05, 0.091)\n    ('Turnus', 0.091, 0.091)\n    ('Aulus Postumius Albinus', 0.091, 0.091)\n    ('Precatio Terrae', 0.014, 0.092)\n    ('Vitruvius', 0.037, 0.092)\n    ('Quintus Terentius Scaurus', 0.047, 0.092)\n    ('Zeno of Verona', 0.026, 0.093)\n    ('Sextus Iulius Frontinus', 0.03, 0.093)\n    ('Publius Vergilius Maro, Virgil, Vergil', 0.033, 0.093)\n    ('Pomponius Porphyrio', 0.04, 0.093)\n    ('Valerius Antias', 0.058, 0.093)\n    ('Servius Sulpicius Rufus', 0.024, 0.094)\n    ('Marcus Terentius Varro, Varro', 0.046, 0.094)\n    ('Gaius Suetonius Tranquillus', 0.034, 0.096)\n    ('Anonymi de Differentiis [Fronto]', 0.031, 0.097)\n    ('Marcus Annaeus Lucanus', 0.032, 0.098)\n    ('Scribonius Largus', 0.049, 0.098)\n    ('Phaedrus', 0.026, 0.099)\n    ('Ticidas', 0.0, 0.1)\n    ('Publius Rutilius Rufus', 0.0, 0.1)\n    ('Caelius Apicius', 0.044, 0.1)\n    ('Gaius Fannius', 0.064, 0.1)\n    ('Luscius Lanuvinus', 0.1, 0.1)\n    ('Anonymi Fragmenta de Iure Fisci', 0.049, 0.101)\n    ('L. Iunius Moderatus Columella', 0.029, 0.102)\n    ('Publius Papinius Statius', 0.037, 0.102)\n    ('Quintus Claudius Quadrigarius', 0.056, 0.102)\n    ('Aquilius, comoed.', 0.044, 0.103)\n    ('Pompeius Trogus', 0.075, 0.103)\n    ('Silius Italicus', 0.035, 0.104)\n    ('Gaius Ateius Capito', 0.037, 0.104)\n    ('Anonymi Comici et Tragici', 0.06, 0.104)\n    ('Antonius Panurgus', 0.053, 0.105)\n    ('Porcius Licinus', 0.028, 0.106)\n    ('Gaius Valerius Flaccus', 0.042, 0.106)\n    ('Balbus, grom.', 0.036, 0.107)\n    ('Fenestella', 0.038, 0.107)\n    ('Marcus Valerius Martialis', 0.048, 0.107)\n    ('Granius Licinianus', 0.074, 0.107)\n    ('Altercatio Hadr. et Epicteti', 0.06, 0.108)\n    ('M. Valerius Messalla Corvinus', 0.077, 0.108)\n    ('Hyginus, myth.', 0.074, 0.109)\n    ('Publius Nigidius Figulus', 0.054, 0.11)\n    ('Granius Flaccus', 0.077, 0.11)\n    ('M. Aemilius Lepidus Porcina', 0.0, 0.111)\n    ('Tullius Laurea', 0.016, 0.111)\n    ('Sextus Pomponius', 0.111, 0.111)\n    ('Albius Tibullus', 0.033, 0.112)\n    ('Sextus Propertius', 0.045, 0.114)\n    ('Favorinus', 0.039, 0.117)\n    ('Petronius', 0.043, 0.118)\n    ('Lucius Cincius', 0.058, 0.118)\n    ('Commentarii Consulares', 0.051, 0.119)\n    ('Gaius Licinius Macer Calvus', 0.057, 0.119)\n    ('Marcus Aemilius Scaurus', 0.075, 0.119)\n    ('Quintus Ennius', 0.057, 0.12)\n    ('Aemilius Asper', 0.078, 0.12)\n    ('Apuleius Madaurensis', 0.04, 0.121)\n    ('Lucius Coelius Antipater', 0.075, 0.121)\n    ('Lucius Ampelius', 0.084, 0.121)\n    ('Gaius Cornelius Gallus, Gallus', 0.089, 0.122)\n    ('Quintus Horatius Flaccus, Horace', 0.045, 0.123)\n    ('Homerus Latinus', 0.054, 0.124)\n    ('L. Aurel. Avianius Symmachus', 0.07, 0.126)\n    ('Gaius Iulius Hyginus', 0.085, 0.126)\n    ('Claudius Caesar Germanicus', 0.04, 0.129)\n    ('L. Aemilius L.f.M.n. Paulus', 0.037, 0.13)\n    ('Marcus Porcius Cato, Cato', 0.061, 0.131)\n    ('Gavius Bassus', 0.08, 0.131)\n    ('Gaius Titius', 0.017, 0.132)\n    ('Decimus Iunius Iuvenalis, Juvenal', 0.052, 0.133)\n    ('Sulpicia, Caleni uxor', 0.052, 0.133)\n    ('Sextus Pompeius Festus', 0.079, 0.133)\n    ('Gaius Valerius Catullus', 0.056, 0.134)\n    ('Parthenius Presbyter', 0.072, 0.134)\n    ('Lucius Arruntius', 0.027, 0.135)\n    ('Marcus Furius Bibaculus', 0.073, 0.136)\n    ('Didascaliae et Per. in Terentium', 0.078, 0.136)\n    ('Albinovanus Pedo', 0.034, 0.137)\n    ('Marcus Iunius Gracchanus', 0.092, 0.137)\n    ('Albinus, poet.', 0.069, 0.138)\n    ('Sextus Turpilius', 0.064, 0.139)\n    ('Fragmenta Bobiensia', 0.074, 0.139)\n    ('Appendix Vergiliana', 0.05, 0.142)\n    ('Caecilius Statius', 0.083, 0.142)\n    ('Marcus Duronius', 0.024, 0.143)\n    ('Lucius Verginius Rufus', 0.071, 0.143)\n    ('Mummius', 0.071, 0.143)\n    ('Lucius Neratius Priscus', 0.095, 0.143)\n    ('Mimi Poetarum Incertorum', 0.112, 0.143)\n    ('Marcus Calidius', 0.143, 0.143)\n    ('Lucius Varius Rufus', 0.061, 0.144)\n    ('Argum. Aen. et Tetrast.', 0.071, 0.144)\n    ('Gaius Lucilius', 0.08, 0.144)\n    ('Gaius Licinius Macer', 0.081, 0.145)\n    ('Iulius Atherianus', 0.081, 0.145)\n    ('Lucius Afranius', 0.069, 0.147)\n    ('Pomponius Mela', 0.094, 0.147)\n    ('Hostius', 0.074, 0.148)\n    ('Didascaliae et Argum. in Plautum', 0.077, 0.148)\n    ('Marianus', 0.05, 0.15)\n    ('Lucius Cornelius Sisenna', 0.075, 0.15)\n    ('Marcus Antistius Labeo', 0.103, 0.15)\n    ('Laus Pisonis', 0.047, 0.152)\n    ('Hilarius Arelatensis', 0.077, 0.154)\n    ('Vita Iuvenalis', 0.083, 0.154)\n    ('Gaius Cassius Hemina', 0.084, 0.155)\n    ('Paulus Quaestor', 0.105, 0.158)\n    ('Gaius Memmius L. f.', 0.045, 0.159)\n    ('Philumenus medicus', 0.085, 0.159)\n    ('Domitius Marsus', 0.128, 0.16)\n    ('Sextus (vel Spurius) Ennius', 0.113, 0.161)\n    ('Priapea', 0.076, 0.162)\n    ('Quintus Aelius Tubero', 0.037, 0.163)\n    ('Bucolica Einsidlensia', 0.067, 0.166)\n    ('Lucius Accius', 0.085, 0.166)\n    ('Publius Aufidius Namusa', 0.0, 0.167)\n    ('Manius Manilius', 0.076, 0.167)\n    ('Ninnius Crassus', 0.083, 0.167)\n    ('Quintus Servilius Caepio', 0.111, 0.167)\n    ('Quintus Valerius Soranus', 0.172, 0.172)\n    ('Titus Calpurnius Siculus', 0.065, 0.174)\n    ('Grattius', 0.071, 0.175)\n    ('Marcus Verrius Flaccus', 0.128, 0.179)\n    ('Marcus Pacuvius', 0.095, 0.181)\n    ('Q. Pompeius Q.f.Q.n. Rufus', 0.0, 0.182)\n    ('Marcus Caelius Rufus', 0.067, 0.187)\n    ('Decimus Iunius Silanus', 0.083, 0.19)\n    ('Anonymi Epici et Lyrici', 0.097, 0.192)\n    ('Publius Pomponius Secundus', 0.135, 0.192)\n    ('Papinius, epigram.', 0.192, 0.192)\n    ('Aulus Persius Flaccus', 0.082, 0.194)\n    ('Chalcidius', 0.063, 0.198)\n    ('Titinius', 0.1, 0.198)\n    ('Flavius Caper', 0.115, 0.198)\n    ('Saserna', 0.086, 0.2)\n    ('Ablabius', 0.1, 0.2)\n    ('Gaius Scribonius Curio pater', 0.1, 0.2)\n    ('Gaius Oppius', 0.163, 0.2)\n    ('C. Iul. Caes. Augustus Octavianus', 0.168, 0.205)\n    ('Caesellius Vindex', 0.169, 0.205)\n    ('Quintus Serenus (Sammonicus)', 0.075, 0.206)\n    ('Gnaeus Naevius', 0.117, 0.206)\n    ('Iulius Valerius', 0.111, 0.207)\n    ('Sacra Argeorum', 0.174, 0.209)\n    ('Caelius Aurelianus', 0.105, 0.211)\n    ('Hadrianus', 0.087, 0.212)\n    ('Alfius Avitus', 0.095, 0.214)\n    ('Q. Fabius Maximus Servilianus', 0.143, 0.214)\n    ('Licinius Imbrex', 0.214, 0.214)\n    ('Cornelius Severus', 0.102, 0.215)\n    ('Numitorius', 0.174, 0.217)\n    ('Veranius', 0.119, 0.218)\n    ('Sinnius Capito', 0.136, 0.22)\n    ('Lucius Pomponius Bononiensis', 0.129, 0.221)\n    ('Pompilius', 0.056, 0.222)\n    ('Annianus', 0.133, 0.222)\n    ('P. Terentius Varro Atacinus', 0.117, 0.224)\n    ('Tarquitius Priscus', 0.134, 0.224)\n    ('Decimus Laberius', 0.155, 0.225)\n    ('Commentarii Augurum', 0.205, 0.227)\n    ('Iulius Modestus', 0.138, 0.231)\n    ('Novius, comoed.', 0.142, 0.232)\n    ('Gnaeus Gellius', 0.181, 0.236)\n    ('Q. Aurelius Memmius Symmachus', 0.127, 0.24)\n    ('Santra', 0.13, 0.241)\n    ('Q. Pompeius Q.f.A.n. Rufus', 0.0, 0.25)\n    ('Marcus Aurelius', 0.0, 0.25)\n    ('Titus Quinctius Atta', 0.098, 0.25)\n    ('Valerius, comoed.', 0.125, 0.25)\n    ('Lucius Livius Andronicus', 0.146, 0.25)\n    ('Carmen Arvale', 0.185, 0.25)\n    ('Gaius Valgius Rufus', 0.143, 0.255)\n    ('Iuventius, comoed.', 0.163, 0.256)\n    ('Gaius Iulius Caesar Strabo', 0.16, 0.26)\n    ('Quintus Hortensius Hortalus', 0.158, 0.263)\n    ('Aemilius Macer', 0.117, 0.266)\n    ('Carmen de Bello Aegyptiaco', 0.248, 0.274)\n    ('Fabius Pictor', 0.195, 0.276)\n    ('Gracchus, trag.', 0.0, 0.278)\n    ('Aulus Furius Antias', 0.194, 0.278)\n    ('Dorcatius', 0.071, 0.286)\n    ('Manilius, poet.', 0.095, 0.286)\n    ('Cornificius Gallus', 0.143, 0.286)\n    ('Gnaeus Matius', 0.148, 0.287)\n    ('Egnatius', 0.235, 0.294)\n    ('Septimius Serenus', 0.189, 0.3)\n    ('Lucius Orbilius Pupillus', 0.2, 0.3)\n    ('Gaius Helvius Cinna', 0.195, 0.301)\n    ('Sueius', 0.204, 0.32)\n    ('Gaius Cilnius Maecenas', 0.187, 0.327)\n    ('Cornelius Epicadus', 0.0, 0.333)\n    ('Cn. Cornel. Lentulus Gaetulicus', 0.167, 0.333)\n    ('Rabirius', 0.233, 0.333)\n    ('Gnaeus Marcius vates', 0.25, 0.333)\n    ('Clodius Tuscus', 0.333, 0.333)\n    ('Laevius', 0.236, 0.348)\n    ('Quintus Cornificius', 0.143, 0.357)\n    ('Servius Clodius', 0.156, 0.375)\n    ('Aprissius (?)', 0.25, 0.375)\n    ('Iulius Montanus', 0.108, 0.378)\n    ('Cornificius Longus', 0.323, 0.387)\n    ('Gaius Clodius Licinus', 0.056, 0.389)\n    ('L. Aelius Praeconinus Stilo', 0.312, 0.396)\n    ('Aurelius Opillus', 0.349, 0.397)\n    ('Gnaeus Domitius Ahenobarbus', 0.0, 0.4)\n    ('Naevius, iunior', 0.1, 0.4)\n    ('Quintus Mucius Scaevola', 0.4, 0.4)\n    ('Imp. Marcus Ulpius Traianus, Trajan', 0.4, 0.4)\n    ('Gannius', 0.158, 0.421)\n    ('Sextilius Ena', 0.143, 0.429)\n    ('Imperator Nero', 0.294, 0.441)\n    ('Staberius Eros', 0.222, 0.444)\n    ('Gaius Licinius Mucianus', 0.333, 0.481)\n    ('Fabius Dossennus', 0.25, 0.5)\n    ('Attius Labeo', 0.333, 0.5)\n    ('Lentulus, mimus', 0.357, 0.5)\n    ('Titius, gram.', 0.5, 0.5)\n    ('Volumnius', 0.5, 0.5)\n    ('Sextus Paconianus', 0.4, 0.55)\n    ('Cloatius Verus', 0.525, 0.57)\n    ('Lucius Ateius Praetextatus', 0.429, 0.571)\n    ('Scaevus Memor', 0.167, 0.667)\n\n\n\n```python\nauthor_results = []\nfor author in author_index:\n    files = get_phi5_author_files(author, author_index)\n    if len(files) >= 3:\n#     print(author, results_map[author])\n        author_results.append((author, results_map[author]) )\n\nauthor_results.sort(key=lambda x: x[1][1])    \nfor tmp in author_results:\n    print(tmp)\n    \n# the values analogous to Cicero are: (0.02892407263780054, 0.008905886443261747)    \n# ~ 0.03  and  0.01 # we can tolerate some distance above this baseline, 2x, 3x, depends\n# Results are mapped into Cicero's Vocabulary space\n# Table below:\n# Author\n# Probability of encountering a word once that we've seen in the author previously in a different lemmatized form\n# Probability of seeing a truly new word once in this authors corpus \n```\n\n    ('Quintus Asconius Pedianus', (0.01, 0.03))\n    ('Gaius, iur., Gaius', (0.011, 0.035))\n    ('Titus Livius, Livy', (0.011, 0.039))\n    ('Marcus Fabius Quintilianus', (0.009, 0.042))\n    ('Gaius Iulius Caesar, Caesar', (0.016, 0.046))\n    ('Lucius Annaeus Seneca senior', (0.016, 0.052))\n    ('Lucius Annaeus Seneca iunior', (0.013, 0.054))\n    ('Aulus Cornelius Celsus', (0.017, 0.056))\n    ('Publius Terentius Afer, Terence', (0.029, 0.059))\n    ('Gaius Sallustius Crispus', (0.021, 0.059))\n    ('Maurus Servius Honoratus, Servius', (0.025, 0.059))\n    ('Titus Maccius Plautus', (0.027, 0.062))\n    ('Publius Ovidius Naso', (0.024, 0.065))\n    ('C. Plinius Caecilius Secundus, Pliny', (0.017, 0.066))\n    ('Titus Lucretius Carus', (0.022, 0.068))\n    ('Scriptores Historiae Augustae', (0.032, 0.071))\n    ('Cornelius Tacitus', (0.025, 0.076))\n    ('Gaius Caesius Bassus', (0.04, 0.08))\n    ('Hyginus Gromaticus', (0.029, 0.083))\n    ('Marcus Valerius Probus', (0.038, 0.084))\n    ('Marcus Cornelius Fronto', (0.036, 0.084))\n    ('Gaius Asinius Pollio', (0.036, 0.09))\n    ('Annius Florus', (0.038, 0.091))\n    ('Quintus Terentius Scaurus', (0.047, 0.092))\n    ('Publius Vergilius Maro, Virgil, Vergil', (0.033, 0.093))\n    ('Pomponius Porphyrio', (0.04, 0.093))\n    ('Sextus Iulius Frontinus', (0.03, 0.093))\n    ('Marcus Terentius Varro, Varro', (0.046, 0.094))\n    ('Gaius Suetonius Tranquillus', (0.034, 0.096))\n    ('Caelius Apicius', (0.044, 0.1))\n    ('Publius Papinius Statius', (0.037, 0.102))\n    ('Anonymi Comici et Tragici', (0.06, 0.104))\n    ('Quintus Ennius', (0.057, 0.12))\n    ('Apuleius Madaurensis', (0.04, 0.121))\n    ('Quintus Horatius Flaccus, Horace', (0.045, 0.123))\n    ('Claudius Caesar Germanicus', (0.04, 0.129))\n    ('Marcus Porcius Cato, Cato', (0.061, 0.131))\n    ('Didascaliae et Per. in Terentium', (0.078, 0.136))\n    ('Fragmenta Bobiensia', (0.074, 0.139))\n    ('Appendix Vergiliana', (0.05, 0.142))\n    ('Argum. Aen. et Tetrast.', (0.071, 0.144))\n    ('Didascaliae et Argum. in Plautum', (0.077, 0.148))\n    ('Lucius Accius', (0.085, 0.166))\n    ('Anonymi Epici et Lyrici', (0.097, 0.192))\n    ('C. Iul. Caes. Augustus Octavianus', (0.168, 0.205))\n    ('Gnaeus Naevius', (0.117, 0.206))\n    ('Lucius Livius Andronicus', (0.146, 0.25))\n\n\n#### Translating the statistics:\n* Cicero: # ~ 0.03  and  0.01  \n* Gaius Iulius Caesar, Caesar (0.016170899832329378, 0.0464137117307334)\n\n#### If one were to find a new page (100 words) of Cicero, one would expect to find: \n* 3 words that Cicero had previously used, but in novel inflected forms \n    * (root words that we know have been used by Cicero, but without previous examples of that particular inflection)\n* 1 word hapax legomena to the author\n    * Not a global hapax legomena, but one that we have no record of occuring in Cicero before (in any inflected form).\n#### if one were to take a page from Caesar and claim it was a new page of Cicero, one would expect to find:\n* 2 words that Cicero had previously used but now in a novel inflected form.\n* 5 words that Cicero had never used (in any inflected form).\n\n\n\n```python\n# Let's look at Cicero's near contemporaries, and see if the individual works come closer to \n# matching Cicero's language in terms of Probability Distributions\ncandidates = ['Gaius Iulius Caesar, Caesar', \n'C. Iul. Caes. Augustus Octavianus',  \n'Publius Vergilius Maro, Virgil, Vergil',  \n'Gaius Suetonius Tranquillus', \n'Marcus Terentius Varro, Varro', \n'Cornelius Tacitus', \n'Titus Livius, Livy', \n'Lucius Annaeus Seneca senior', \n'Quintus Horatius Flaccus, Horace',  \n'Gaius Sallustius Crispus', \n'Titus Lucretius Carus', \n'Lucius Annaeus Seneca iunior']\n```\n\n\n```python\nresults = []\n\nfor author in candidates:\n    files = get_phi5_author_files(author, author_index)\n    #     cicero_lemmas, cicero_inflected_words = get_word_counts(cicero_files)    \n    for file in files:\n        author_inflected_words, author_lemmas = get_word_counts([file])    \n        author_words = set(author_lemmas.keys())\n        cicero_words = set(cicero_lemmas.keys())\n        common = author_words & cicero_words\n        author_uniq  = author_words - common \n        P_one_x_lemma_unigram = round(len(author_uniq) / sum(author_lemmas.values()),3)\n        author_words = set(author_inflected_words.keys())\n        cicero_words = set(cicero_inflected_words.keys())\n        common = author_words & cicero_words\n        author_uniq  = author_words - common \n        P_one_x_inflected_unigram = round(len(author_uniq) / sum(author_inflected_words.values()), 3)\n        results.append((author, file, sum(author_inflected_words.values()), P_one_x_inflected_unigram, P_one_x_lemma_unigram))\n```\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n```python\nfor author, _, count, P_one_x_inflected_unigram, P_one_x_lemma_unigram in results:\n    if P_one_x_lemma_unigram != 0.0:\n        print (author, count, P_one_x_inflected_unigram, P_one_x_lemma_unigram)\n# Cicero's values for:\n# Probability of unigrams that occur once, Probability of a lemmatized unigram occurring once\n# (0.02892407263780054, 0.008905886443261747)  Cicero's values for\n```\n\n    Gaius Iulius Caesar, Caesar 286 0.0034965034965034965 0.006993006993006993\n    Gaius Iulius Caesar, Caesar 134 0.08955223880597014 0.13432835820895522\n    Gaius Iulius Caesar, Caesar 386 0.0025906735751295338 0.0025906735751295338\n    Gaius Iulius Caesar, Caesar 49 0.061224489795918366 0.20408163265306123\n    Gaius Iulius Caesar, Caesar 33437 0.014923587642432037 0.0506923468014475\n    Gaius Iulius Caesar, Caesar 179 0.027932960893854747 0.061452513966480445\n    Gaius Iulius Caesar, Caesar 46014 0.018603033859260223 0.05059329769200678\n    C. Iul. Caes. Augustus Octavianus 2398 0.26980817347789826 0.2964970809007506\n    C. Iul. Caes. Augustus Octavianus 85 0.07058823529411765 0.12941176470588237\n    C. Iul. Caes. Augustus Octavianus 1424 0.07935393258426966 0.12289325842696629\n    C. Iul. Caes. Augustus Octavianus 33 0.030303030303030304 0.12121212121212122\n    C. Iul. Caes. Augustus Octavianus 69 0.11594202898550725 0.21739130434782608\n    C. Iul. Caes. Augustus Octavianus 338 0.08875739644970414 0.1301775147928994\n    C. Iul. Caes. Augustus Octavianus 767 0.07953063885267275 0.1290743155149935\n    Publius Vergilius Maro, Virgil, Vergil 67238 0.03246675986793182 0.09195692911746334\n    Publius Vergilius Maro, Virgil, Vergil 14849 0.05912856084584821 0.16149235638763554\n    Publius Vergilius Maro, Virgil, Vergil 5781 0.05794845182494378 0.13527071440927174\n    Gaius Suetonius Tranquillus 4317 0.0463284688441047 0.09520500347463516\n    Gaius Suetonius Tranquillus 2274 0.06904133685136324 0.14160070360598065\n    Gaius Suetonius Tranquillus 596 0.07885906040268456 0.12583892617449666\n    Gaius Suetonius Tranquillus 1660 0.03855421686746988 0.09397590361445783\n    Gaius Suetonius Tranquillus 92 0.08695652173913043 0.18478260869565216\n    Gaius Suetonius Tranquillus 72536 0.03228741590382707 0.09651759126502703\n    Marcus Terentius Varro, Varro 360 0.23055555555555557 0.3055555555555556\n    Marcus Terentius Varro, Varro 1347 0.06087602078693393 0.11729769858945806\n    Marcus Terentius Varro, Varro 36323 0.039451587148638605 0.09470583376923712\n    Marcus Terentius Varro, Varro 115 0.034782608695652174 0.06086956521739131\n    Marcus Terentius Varro, Varro 354 0.08757062146892655 0.1327683615819209\n    Marcus Terentius Varro, Varro 167 0.11976047904191617 0.16167664670658682\n    Marcus Terentius Varro, Varro 40767 0.04623837908111953 0.08455368312605784\n    Marcus Terentius Varro, Varro 16 0.0625 0.125\n    Marcus Terentius Varro, Varro 6577 0.11038467386346358 0.1947696518169378\n    Marcus Terentius Varro, Varro 134 0.1044776119402985 0.15671641791044777\n    Marcus Terentius Varro, Varro 1052 0.03136882129277566 0.06844106463878327\n    Marcus Terentius Varro, Varro 99 0.1111111111111111 0.15151515151515152\n    Marcus Terentius Varro, Varro 108 0.08333333333333333 0.1111111111111111\n    Marcus Terentius Varro, Varro 1990 0.07135678391959799 0.13919597989949747\n    Marcus Terentius Varro, Varro 34 0.029411764705882353 0.058823529411764705\n    Marcus Terentius Varro, Varro 880 0.09659090909090909 0.15454545454545454\n    Cornelius Tacitus 6889 0.03512846566990855 0.1029176948758891\n    Cornelius Tacitus 9421 0.016771043413650356 0.0633690691009447\n    Cornelius Tacitus 5689 0.04605378801195289 0.11706802601511689\n    Cornelius Tacitus 91347 0.02934962286665134 0.0882897084742794\n    Cornelius Tacitus 52847 0.030313925104547088 0.09620224421443034\n    Titus Livius, Livy 1284 0.14330218068535824 0.16978193146417445\n    Titus Livius, Livy 20763 0.034484419399894044 0.06530848143331888\n    Titus Livius, Livy 1275 0.054901960784313725 0.10823529411764705\n    Titus Livius, Livy 516063 0.010702181710372571 0.039026242919953574\n    Lucius Annaeus Seneca senior 68556 0.01849582822801797 0.05808390221133088\n    Lucius Annaeus Seneca senior 19571 0.012365234275203106 0.057227530529865615\n    Lucius Annaeus Seneca senior 10322 0.030323580701414454 0.08002325130788607\n    Lucius Annaeus Seneca senior 24 0.041666666666666664 0.08333333333333333\n    Quintus Horatius Flaccus, Horace 14601 0.044517498801451956 0.11910143140880762\n    Quintus Horatius Flaccus, Horace 10120 0.04189723320158103 0.12282608695652174\n    Quintus Horatius Flaccus, Horace 3214 0.04169259489732421 0.12258867454884878\n    Quintus Horatius Flaccus, Horace 337 0.06528189910979229 0.1572700296735905\n    Quintus Horatius Flaccus, Horace 3084 0.07652399481193256 0.19649805447470817\n    Quintus Horatius Flaccus, Horace 13669 0.06511083473553296 0.16826395493452337\n    Gaius Sallustius Crispus 1210 0.05206611570247934 0.11735537190082644\n    Gaius Sallustius Crispus 4223 0.026284631778356618 0.07861709685058016\n    Gaius Sallustius Crispus 212 0.15566037735849056 0.20754716981132076\n    Gaius Sallustius Crispus 4080 0.015931372549019607 0.050490196078431374\n    Gaius Sallustius Crispus 4047 0.05114899925871016 0.12725475660983446\n    Gaius Sallustius Crispus 21650 0.01861431870669746 0.05796766743648961\n    Gaius Sallustius Crispus 10866 0.01582919197496779 0.05135284373274434\n    Gaius Sallustius Crispus 720 0.0125 0.05\n    Titus Lucretius Carus 703 0.05689900426742532 0.09103840682788052\n    Titus Lucretius Carus 67 0.08955223880597014 0.208955223880597\n    Titus Lucretius Carus 50559 0.02177653830178603 0.06762396408156807\n    Lucius Annaeus Seneca iunior 7208 0.04869589345172031 0.14983351831298558\n    Lucius Annaeus Seneca iunior 3037 0.057951926243002966 0.10997695093842608\n    Lucius Annaeus Seneca iunior 5261 0.02033833871887474 0.08705569283406196\n    Lucius Annaeus Seneca iunior 5686 0.048012662680267326 0.1429827646851917\n    Lucius Annaeus Seneca iunior 76269 0.012403466677155856 0.06980555664817947\n    Lucius Annaeus Seneca iunior 5959 0.04967276388655815 0.15774458801812385\n    Lucius Annaeus Seneca iunior 5592 0.0536480686695279 0.14914163090128754\n    Lucius Annaeus Seneca iunior 45899 0.011459944661103727 0.0556439138107584\n    Lucius Annaeus Seneca iunior 4147 0.027489751627682663 0.10851217747769472\n    Lucius Annaeus Seneca iunior 6853 0.03896103896103896 0.11688311688311688\n    Lucius Annaeus Seneca iunior 48052 0.01783484558395072 0.07446100058270207\n    Lucius Annaeus Seneca iunior 8316 0.015993265993265993 0.06962481962481963\n    Lucius Annaeus Seneca iunior 120945 0.014089048741163339 0.058663028649386086\n    Lucius Annaeus Seneca iunior 7736 0.03968459152016546 0.13094622543950363\n    Lucius Annaeus Seneca iunior 11471 0.04010112457501525 0.11550867404759829\n    Lucius Annaeus Seneca iunior 6320 0.034968354430379746 0.13069620253164557\n\n\n\n```python\naquinas = glob(\"../data/aquinas/*.txt\")\nlen(aquinas)\n```\n\n\n\n\n    612\n\n\n\n\n```python\nresults = []\nauthor='aquinas'\nfor file in tqdm(aquinas):\n    author_inflected_words, author_lemmas = get_word_counts([file])    \n    author_words = set(author_lemmas.keys())\n    cicero_words = set(cicero_lemmas.keys())\n    common = author_words & cicero_words\n    author_uniq  = author_words - common \n    P_one_x_lemma_unigram = len(author_uniq) / sum(author_lemmas.values())\n    author_words = set(author_inflected_words.keys())\n    cicero_words = set(cicero_inflected_words.keys())\n    common = author_words & cicero_words\n    author_uniq  = author_words - common \n    P_one_x_inflected_unigram = len(author_uniq) / sum(author_inflected_words.values())\n    results.append((author, file, sum(author_inflected_words.values()), P_one_x_inflected_unigram, P_one_x_lemma_unigram))\n```\n\n      0%|          | 0/612 [00:00<?, ?it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 17.58files/s]\n      0%|          | 1/612 [00:00<06:01,  1.69it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  8.81files/s]\u001b[A\n      0%|          | 2/612 [00:01<06:18,  1.61it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  8.69files/s]\u001b[A\n      0%|          | 3/612 [00:01<06:29,  1.56it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.79files/s]\u001b[A\n      1%|          | 4/612 [00:02<07:04,  1.43it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.15files/s]\u001b[A\n      1%|          | 5/612 [00:03<08:05,  1.25it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 11.87files/s]\n      1%|          | 6/612 [00:04<07:24,  1.36it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.34files/s]\u001b[A\n      1%|          | 7/612 [00:05<09:10,  1.10it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.39files/s]\u001b[A\n      1%|\u258f         | 8/612 [00:06<09:20,  1.08it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.29s/files]\u001b[A\n      1%|\u258f         | 9/612 [00:09<15:20,  1.53s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.12files/s]\u001b[A\n      2%|\u258f         | 10/612 [00:10<14:57,  1.49s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.56files/s]\u001b[A\n      2%|\u258f         | 11/612 [00:11<13:07,  1.31s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 28.38files/s]\n      2%|\u258f         | 12/612 [00:12<10:49,  1.08s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.87files/s]\u001b[A\n      2%|\u258f         | 13/612 [00:13<10:08,  1.02s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.76s/files]\u001b[A\n      2%|\u258f         | 14/612 [00:15<13:54,  1.40s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  9.99files/s]\n      2%|\u258f         | 15/612 [00:16<11:37,  1.17s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.53s/files]\u001b[A\n      3%|\u258e         | 16/612 [00:18<14:13,  1.43s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 16.63files/s]\n      3%|\u258e         | 17/612 [00:18<11:38,  1.17s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.76files/s]\u001b[A\n      3%|\u258e         | 18/612 [00:19<11:21,  1.15s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.69files/s]\u001b[A\n      3%|\u258e         | 19/612 [00:20<10:12,  1.03s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 30.72files/s]\n      3%|\u258e         | 20/612 [00:21<08:49,  1.12it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.14files/s]\u001b[A\n      3%|\u258e         | 21/612 [00:22<10:22,  1.05s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  7.40files/s]\u001b[A\n      4%|\u258e         | 22/612 [00:23<09:12,  1.07it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.97files/s]\u001b[A\n      4%|\u258d         | 23/612 [00:24<09:06,  1.08it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.33files/s]\u001b[A\n      4%|\u258d         | 24/612 [00:25<10:09,  1.04s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.85s/files]\u001b[A\n      4%|\u258d         | 25/612 [00:27<14:12,  1.45s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 49.74files/s]\n      4%|\u258d         | 26/612 [00:28<11:28,  1.17s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 52.54files/s]\n      4%|\u258d         | 27/612 [00:28<09:34,  1.02it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.41files/s]\u001b[A\n      5%|\u258d         | 28/612 [00:29<09:03,  1.07it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.47s/files]\u001b[A\n      5%|\u258d         | 29/612 [00:32<15:06,  1.55s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.67files/s]\u001b[A\n      5%|\u258d         | 30/612 [00:33<13:54,  1.43s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.96files/s]\u001b[A\n      5%|\u258c         | 31/612 [00:34<12:14,  1.26s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.83files/s]\u001b[A\n      5%|\u258c         | 32/612 [00:35<12:16,  1.27s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.53files/s]\u001b[A\n      5%|\u258c         | 33/612 [00:37<12:58,  1.34s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 30.20files/s]\n      6%|\u258c         | 34/612 [00:38<10:54,  1.13s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.26s/files]\u001b[A\n      6%|\u258c         | 35/612 [00:39<13:07,  1.36s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.30s/files]\u001b[A\n      6%|\u258c         | 36/612 [00:42<15:07,  1.57s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.29files/s]\u001b[A\n      6%|\u258c         | 37/612 [00:43<14:24,  1.50s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.07s/files]\u001b[A\n      6%|\u258c         | 38/612 [00:46<17:35,  1.84s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.61s/files]\u001b[A\n      6%|\u258b         | 39/612 [00:48<18:28,  1.93s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.11s/files]\u001b[A\n      7%|\u258b         | 40/612 [00:50<20:31,  2.15s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.02files/s]\u001b[A\n      7%|\u258b         | 41/612 [00:51<17:24,  1.83s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.47s/files]\u001b[A\n      7%|\u258b         | 42/612 [00:53<17:54,  1.89s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 21.13files/s]\n      7%|\u258b         | 43/612 [00:54<14:09,  1.49s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 43.58files/s]\n      7%|\u258b         | 44/612 [00:55<11:31,  1.22s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.32s/files]\u001b[A\n      7%|\u258b         | 45/612 [00:57<13:35,  1.44s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.45files/s]\u001b[A\n      8%|\u258a         | 46/612 [00:57<11:51,  1.26s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  7.58files/s]\u001b[A\n      8%|\u258a         | 47/612 [00:58<10:08,  1.08s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.39files/s]\u001b[A\n      8%|\u258a         | 48/612 [00:59<09:47,  1.04s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.16files/s]\u001b[A\n      8%|\u258a         | 49/612 [01:00<10:43,  1.14s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.11s/files]\u001b[A\n      8%|\u258a         | 50/612 [01:03<14:52,  1.59s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.42s/files]\u001b[A\n      8%|\u258a         | 51/612 [01:05<15:51,  1.70s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.20files/s]\u001b[A\n      8%|\u258a         | 52/612 [01:06<14:58,  1.60s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.43files/s]\u001b[A\n      9%|\u258a         | 53/612 [01:08<13:54,  1.49s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.22s/files]\u001b[A\n      9%|\u2589         | 54/612 [01:09<14:36,  1.57s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.68s/files]\u001b[A\n      9%|\u2589         | 55/612 [01:12<16:24,  1.77s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.04files/s]\u001b[A\n      9%|\u2589         | 56/612 [01:13<15:35,  1.68s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  8.74files/s]\u001b[A\n      9%|\u2589         | 57/612 [01:14<12:42,  1.37s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.46files/s]\u001b[A\n      9%|\u2589         | 58/612 [01:15<11:11,  1.21s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.16s/files]\u001b[A\n     10%|\u2589         | 59/612 [01:16<12:34,  1.36s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.09files/s]\u001b[A\n     10%|\u2589         | 60/612 [01:18<12:46,  1.39s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.44files/s]\u001b[A\n     10%|\u2589         | 61/612 [01:19<12:18,  1.34s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 40.41files/s]\n     10%|\u2588         | 62/612 [01:19<10:06,  1.10s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.04s/files]\u001b[A\n     10%|\u2588         | 63/612 [01:21<11:21,  1.24s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.87files/s]\u001b[A\n     10%|\u2588         | 64/612 [01:22<10:21,  1.13s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.06files/s]\u001b[A\n     11%|\u2588         | 65/612 [01:23<11:13,  1.23s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.16files/s]\u001b[A\n     11%|\u2588         | 66/612 [01:25<11:38,  1.28s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.28files/s]\u001b[A\n     11%|\u2588         | 67/612 [01:26<10:15,  1.13s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.02files/s]\u001b[A\n     11%|\u2588         | 68/612 [01:27<11:15,  1.24s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.53files/s]\u001b[A\n     11%|\u2588\u258f        | 69/612 [01:28<10:19,  1.14s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.99files/s]\u001b[A\n     11%|\u2588\u258f        | 70/612 [01:29<09:31,  1.05s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.03files/s]\u001b[A\n     12%|\u2588\u258f        | 71/612 [01:30<08:53,  1.01it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 35.91files/s]\n     12%|\u2588\u258f        | 72/612 [01:30<07:39,  1.18it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.08files/s]\u001b[A\n     12%|\u2588\u258f        | 73/612 [01:31<08:06,  1.11it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.54files/s]\u001b[A\n     12%|\u2588\u258f        | 74/612 [01:32<07:37,  1.17it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 113.62files/s]\n     12%|\u2588\u258f        | 75/612 [01:32<06:43,  1.33it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.24s/files]\u001b[A\n     12%|\u2588\u258f        | 76/612 [01:34<09:25,  1.06s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 10.35files/s]\n     13%|\u2588\u258e        | 77/612 [01:35<08:13,  1.09it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.19s/files]\u001b[A\n     13%|\u2588\u258e        | 78/612 [01:37<10:18,  1.16s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.22files/s]\u001b[A\n     13%|\u2588\u258e        | 79/612 [01:37<09:45,  1.10s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.93s/files]\u001b[A\n     13%|\u2588\u258e        | 80/612 [01:40<13:19,  1.50s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.09files/s]\u001b[A\n     13%|\u2588\u258e        | 81/612 [01:41<13:08,  1.49s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.41files/s]\u001b[A\n     13%|\u2588\u258e        | 82/612 [01:43<12:25,  1.41s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.15files/s]\u001b[A\n     14%|\u2588\u258e        | 83/612 [01:44<11:14,  1.27s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.54files/s]\u001b[A\n     14%|\u2588\u258e        | 84/612 [01:45<10:54,  1.24s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.32files/s]\u001b[A\n     14%|\u2588\u258d        | 85/612 [01:46<10:04,  1.15s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  5.26files/s]\u001b[A\n     14%|\u2588\u258d        | 86/612 [01:46<08:55,  1.02s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.23files/s]\u001b[A\n     14%|\u2588\u258d        | 87/612 [01:47<08:46,  1.00s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.62files/s]\u001b[A\n     14%|\u2588\u258d        | 88/612 [01:48<08:00,  1.09it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 20.23files/s]\n     15%|\u2588\u258d        | 89/612 [01:49<07:02,  1.24it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 10.94files/s]\n     15%|\u2588\u258d        | 90/612 [01:49<06:26,  1.35it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.78files/s]\u001b[A\n     15%|\u2588\u258d        | 91/612 [01:50<07:16,  1.19it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 15.78files/s]\n     15%|\u2588\u258c        | 92/612 [01:51<06:39,  1.30it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.46files/s]\u001b[A\n     15%|\u2588\u258c        | 93/612 [01:52<06:37,  1.31it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.60s/files]\u001b[A\n     15%|\u2588\u258c        | 94/612 [01:54<10:04,  1.17s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.01s/files]\u001b[A\n     16%|\u2588\u258c        | 95/612 [01:55<10:56,  1.27s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.61files/s]\u001b[A\n     16%|\u2588\u258c        | 96/612 [01:56<09:30,  1.11s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.21files/s]\u001b[A\n     16%|\u2588\u258c        | 97/612 [01:57<09:11,  1.07s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.30files/s]\u001b[A\n     16%|\u2588\u258c        | 98/612 [01:58<09:42,  1.13s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  9.45files/s]\u001b[A\n     16%|\u2588\u258c        | 99/612 [01:59<08:20,  1.03it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.72files/s]\u001b[A\n     16%|\u2588\u258b        | 100/612 [02:00<07:46,  1.10it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.70s/files]\u001b[A\n     17%|\u2588\u258b        | 101/612 [02:02<11:07,  1.31s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.20s/files]\u001b[A\n     17%|\u2588\u258b        | 102/612 [02:04<12:08,  1.43s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.91s/files]\u001b[A\n     17%|\u2588\u258b        | 103/612 [02:06<14:38,  1.73s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.04files/s]\u001b[A\n     17%|\u2588\u258b        | 104/612 [02:07<12:24,  1.47s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 144.77files/s]\n     17%|\u2588\u258b        | 105/612 [02:07<10:02,  1.19s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.27files/s]\u001b[A\n     17%|\u2588\u258b        | 106/612 [02:09<10:18,  1.22s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  9.60files/s]\u001b[A\n     17%|\u2588\u258b        | 107/612 [02:09<08:44,  1.04s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.33files/s]\u001b[A\n     18%|\u2588\u258a        | 108/612 [02:10<07:57,  1.05it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.56s/files]\u001b[A\n     18%|\u2588\u258a        | 109/612 [02:13<13:17,  1.59s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.16files/s]\u001b[A\n     18%|\u2588\u258a        | 110/612 [02:14<12:44,  1.52s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.03files/s]\u001b[A\n     18%|\u2588\u258a        | 111/612 [02:15<10:49,  1.30s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.05files/s]\u001b[A\n     18%|\u2588\u258a        | 112/612 [02:16<10:03,  1.21s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.87s/files]\u001b[A\n     18%|\u2588\u258a        | 113/612 [02:20<15:32,  1.87s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.87s/files]\u001b[A\n     19%|\u2588\u258a        | 114/612 [02:23<19:16,  2.32s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.29files/s]\u001b[A\n     19%|\u2588\u2589        | 115/612 [02:24<16:38,  2.01s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 20.30files/s]\n     19%|\u2588\u2589        | 116/612 [02:25<13:01,  1.58s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.27s/files]\u001b[A\n     19%|\u2588\u2589        | 117/612 [02:27<13:30,  1.64s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  9.42files/s]\u001b[A\n     19%|\u2588\u2589        | 118/612 [02:27<10:58,  1.33s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.88s/files]\u001b[A\n     19%|\u2588\u2589        | 119/612 [02:30<13:32,  1.65s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.17s/files]\u001b[A\n     20%|\u2588\u2589        | 120/612 [02:31<13:39,  1.66s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.92files/s]\u001b[A\n     20%|\u2588\u2589        | 121/612 [02:32<12:06,  1.48s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.99s/files]\u001b[A\n     20%|\u2588\u2589        | 122/612 [02:36<16:58,  2.08s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 13.66files/s]\n     20%|\u2588\u2588        | 123/612 [02:36<13:15,  1.63s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  8.43files/s]\u001b[A\n     20%|\u2588\u2588        | 124/612 [02:37<10:58,  1.35s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.09files/s]\u001b[A\n     20%|\u2588\u2588        | 125/612 [02:39<11:09,  1.38s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.27s/files]\u001b[A\n     21%|\u2588\u2588        | 126/612 [02:41<14:34,  1.80s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  5.23files/s]\u001b[A\n     21%|\u2588\u2588        | 127/612 [02:42<11:48,  1.46s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.03files/s]\u001b[A\n     21%|\u2588\u2588        | 128/612 [02:44<11:51,  1.47s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 564.97files/s]\n     21%|\u2588\u2588        | 129/612 [02:44<09:31,  1.18s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.34s/files]\u001b[A\n     21%|\u2588\u2588        | 130/612 [02:46<11:07,  1.38s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.53s/files]\u001b[A\n     21%|\u2588\u2588\u258f       | 131/612 [02:48<12:38,  1.58s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.36s/files]\u001b[A\n     22%|\u2588\u2588\u258f       | 132/612 [02:51<15:45,  1.97s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.26s/files]\u001b[A\n     22%|\u2588\u2588\u258f       | 133/612 [02:53<15:21,  1.92s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.88files/s]\u001b[A\n     22%|\u2588\u2588\u258f       | 134/612 [02:54<13:15,  1.66s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.90files/s]\u001b[A\n     22%|\u2588\u2588\u258f       | 135/612 [02:54<10:55,  1.37s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.96s/files]\u001b[A\n     22%|\u2588\u2588\u258f       | 136/612 [02:57<13:31,  1.71s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.63files/s]\u001b[A\n     22%|\u2588\u2588\u258f       | 137/612 [02:58<11:32,  1.46s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.53files/s]\u001b[A\n     23%|\u2588\u2588\u258e       | 138/612 [02:58<09:47,  1.24s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.53files/s]\u001b[A\n     23%|\u2588\u2588\u258e       | 139/612 [02:59<08:44,  1.11s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.30s/files]\u001b[A\n     23%|\u2588\u2588\u258e       | 140/612 [03:01<10:21,  1.32s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 17.93files/s]\n     23%|\u2588\u2588\u258e       | 141/612 [03:02<08:33,  1.09s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 10.44files/s]\n     23%|\u2588\u2588\u258e       | 142/612 [03:02<07:23,  1.06it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.12s/files]\u001b[A\n     23%|\u2588\u2588\u258e       | 143/612 [03:04<08:58,  1.15s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.10files/s]\u001b[A\n     24%|\u2588\u2588\u258e       | 144/612 [03:05<08:09,  1.05s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.30files/s]\u001b[A\n     24%|\u2588\u2588\u258e       | 145/612 [03:06<07:50,  1.01s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 16.77files/s]\n     24%|\u2588\u2588\u258d       | 146/612 [03:06<06:44,  1.15it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.07files/s]\u001b[A\n     24%|\u2588\u2588\u258d       | 147/612 [03:08<08:03,  1.04s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.01files/s]\u001b[A\n     24%|\u2588\u2588\u258d       | 148/612 [03:09<09:05,  1.18s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.10s/files]\u001b[A\n     24%|\u2588\u2588\u258d       | 149/612 [03:12<12:23,  1.61s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.05s/files]\u001b[A\n     25%|\u2588\u2588\u258d       | 150/612 [03:13<12:14,  1.59s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.11s/files]\u001b[A\n     25%|\u2588\u2588\u258d       | 151/612 [03:15<12:19,  1.60s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.93s/files]\u001b[A\n     25%|\u2588\u2588\u258d       | 152/612 [03:17<14:16,  1.86s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.39s/files]\u001b[A\n     25%|\u2588\u2588\u258c       | 153/612 [03:20<16:34,  2.17s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.19files/s]\u001b[A\n     25%|\u2588\u2588\u258c       | 154/612 [03:22<14:40,  1.92s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.19s/files]\u001b[A\n     25%|\u2588\u2588\u258c       | 155/612 [03:23<14:09,  1.86s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.48files/s]\u001b[A\n     25%|\u2588\u2588\u258c       | 156/612 [03:24<11:46,  1.55s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.72files/s]\u001b[A\n     26%|\u2588\u2588\u258c       | 157/612 [03:25<10:13,  1.35s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.59s/files]\u001b[A\n     26%|\u2588\u2588\u258c       | 158/612 [03:27<11:53,  1.57s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.16s/files]\u001b[A\n     26%|\u2588\u2588\u258c       | 159/612 [03:30<14:20,  1.90s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.53files/s]\u001b[A\n     26%|\u2588\u2588\u258c       | 160/612 [03:31<12:04,  1.60s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 10.26files/s]\n     26%|\u2588\u2588\u258b       | 161/612 [03:31<09:46,  1.30s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 23.75files/s]\n     26%|\u2588\u2588\u258b       | 162/612 [03:32<08:03,  1.07s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 294.44files/s]\n     27%|\u2588\u2588\u258b       | 163/612 [03:32<06:47,  1.10it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 25.57files/s]\n     27%|\u2588\u2588\u258b       | 164/612 [03:33<05:54,  1.26it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 11.39files/s]\n     27%|\u2588\u2588\u258b       | 165/612 [03:33<05:26,  1.37it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.71files/s]\u001b[A\n     27%|\u2588\u2588\u258b       | 166/612 [03:34<05:31,  1.34it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  7.01files/s]\u001b[A\n     27%|\u2588\u2588\u258b       | 167/612 [03:35<05:20,  1.39it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.18s/files]\u001b[A\n     27%|\u2588\u2588\u258b       | 168/612 [03:37<07:29,  1.01s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.85files/s]\u001b[A\n     28%|\u2588\u2588\u258a       | 169/612 [03:38<07:33,  1.02s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.00s/files]\u001b[A\n     28%|\u2588\u2588\u258a       | 170/612 [03:40<10:51,  1.47s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 695.92files/s]\n     28%|\u2588\u2588\u258a       | 171/612 [03:41<08:43,  1.19s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.58files/s]\u001b[A\n     28%|\u2588\u2588\u258a       | 172/612 [03:41<07:48,  1.07s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.11files/s]\u001b[A\n     28%|\u2588\u2588\u258a       | 173/612 [03:43<08:31,  1.17s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.48files/s]\u001b[A\n     28%|\u2588\u2588\u258a       | 174/612 [03:44<08:33,  1.17s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.25files/s]\u001b[A\n     29%|\u2588\u2588\u258a       | 175/612 [03:45<08:48,  1.21s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.17files/s]\u001b[A\n     29%|\u2588\u2588\u2589       | 176/612 [03:47<09:12,  1.27s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.59s/files]\u001b[A\n     29%|\u2588\u2588\u2589       | 177/612 [03:49<10:59,  1.52s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.13files/s]\u001b[A\n     29%|\u2588\u2588\u2589       | 178/612 [03:50<09:45,  1.35s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.61files/s]\u001b[A\n     29%|\u2588\u2588\u2589       | 179/612 [03:50<08:23,  1.16s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.31files/s]\u001b[A\n     29%|\u2588\u2588\u2589       | 180/612 [03:51<07:27,  1.03s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.49files/s]\u001b[A\n     30%|\u2588\u2588\u2589       | 181/612 [03:52<07:10,  1.00it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  5.39files/s]\u001b[A\n     30%|\u2588\u2588\u2589       | 182/612 [03:53<06:29,  1.10it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.08files/s]\u001b[A\n     30%|\u2588\u2588\u2589       | 183/612 [03:54<06:20,  1.13it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.03s/files]\u001b[A\n     30%|\u2588\u2588\u2588       | 184/612 [03:55<07:43,  1.08s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 13.27files/s]\n     30%|\u2588\u2588\u2588       | 185/612 [03:56<06:37,  1.07it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.19files/s]\u001b[A\n     30%|\u2588\u2588\u2588       | 186/612 [03:57<06:12,  1.14it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.32s/files]\u001b[A\n     31%|\u2588\u2588\u2588       | 187/612 [03:58<08:15,  1.17s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.77files/s]\u001b[A\n     31%|\u2588\u2588\u2588       | 188/612 [03:59<08:04,  1.14s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 58.83files/s]\n     31%|\u2588\u2588\u2588       | 189/612 [04:00<06:44,  1.05it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.11files/s]\u001b[A\n     31%|\u2588\u2588\u2588       | 190/612 [04:01<07:40,  1.09s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.13files/s]\u001b[A\n     31%|\u2588\u2588\u2588       | 191/612 [04:02<07:09,  1.02s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.21files/s]\u001b[A\n     31%|\u2588\u2588\u2588\u258f      | 192/612 [04:03<06:45,  1.04it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.04files/s]\u001b[A\n     32%|\u2588\u2588\u2588\u258f      | 193/612 [04:05<07:46,  1.11s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.63files/s]\u001b[A\n     32%|\u2588\u2588\u2588\u258f      | 194/612 [04:05<07:03,  1.01s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  8.38files/s]\u001b[A\n     32%|\u2588\u2588\u2588\u258f      | 195/612 [04:06<06:13,  1.12it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  5.34files/s]\u001b[A\n     32%|\u2588\u2588\u2588\u258f      | 196/612 [04:07<05:46,  1.20it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.34s/files]\u001b[A\n     32%|\u2588\u2588\u2588\u258f      | 197/612 [04:08<07:51,  1.14s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.64files/s]\u001b[A\n     32%|\u2588\u2588\u2588\u258f      | 198/612 [04:10<07:47,  1.13s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  5.38files/s]\u001b[A\n     33%|\u2588\u2588\u2588\u258e      | 199/612 [04:10<06:51,  1.00it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  8.93files/s]\u001b[A\n     33%|\u2588\u2588\u2588\u258e      | 200/612 [04:11<06:03,  1.13it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.38s/files]\u001b[A\n     33%|\u2588\u2588\u2588\u258e      | 201/612 [04:13<08:04,  1.18s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.92files/s]\u001b[A\n     33%|\u2588\u2588\u2588\u258e      | 202/612 [04:13<07:05,  1.04s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.08s/files]\u001b[A\n     33%|\u2588\u2588\u2588\u258e      | 203/612 [04:15<08:13,  1.21s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.08s/files]\u001b[A\n     33%|\u2588\u2588\u2588\u258e      | 204/612 [04:17<09:00,  1.32s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.55files/s]\u001b[A\n     33%|\u2588\u2588\u2588\u258e      | 205/612 [04:18<08:06,  1.19s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  9.05files/s]\u001b[A\n     34%|\u2588\u2588\u2588\u258e      | 206/612 [04:18<06:54,  1.02s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.06files/s]\u001b[A\n     34%|\u2588\u2588\u2588\u258d      | 207/612 [04:20<07:45,  1.15s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.51s/files]\u001b[A\n     34%|\u2588\u2588\u2588\u258d      | 208/612 [04:22<09:28,  1.41s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.99files/s]\u001b[A\n     34%|\u2588\u2588\u2588\u258d      | 209/612 [04:22<08:19,  1.24s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.87s/files]\u001b[A\n     34%|\u2588\u2588\u2588\u258d      | 210/612 [04:26<12:37,  1.88s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 12.87files/s]\n     34%|\u2588\u2588\u2588\u258d      | 211/612 [04:26<09:58,  1.49s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.10files/s]\u001b[A\n     35%|\u2588\u2588\u2588\u258d      | 212/612 [04:28<09:46,  1.47s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.46files/s]\u001b[A\n     35%|\u2588\u2588\u2588\u258d      | 213/612 [04:29<08:40,  1.31s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 29.54files/s]\n     35%|\u2588\u2588\u2588\u258d      | 214/612 [04:29<07:07,  1.07s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  5.29files/s]\u001b[A\n     35%|\u2588\u2588\u2588\u258c      | 215/612 [04:30<06:21,  1.04it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 39.17files/s]\n     35%|\u2588\u2588\u2588\u258c      | 216/612 [04:31<05:30,  1.20it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.04files/s]\u001b[A\n     35%|\u2588\u2588\u2588\u258c      | 217/612 [04:32<06:44,  1.02s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.39files/s]\u001b[A\n     36%|\u2588\u2588\u2588\u258c      | 218/612 [04:33<07:10,  1.09s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.07files/s]\u001b[A\n     36%|\u2588\u2588\u2588\u258c      | 219/612 [04:35<07:58,  1.22s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  9.44files/s]\u001b[A\n     36%|\u2588\u2588\u2588\u258c      | 220/612 [04:35<06:45,  1.03s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  8.36files/s]\u001b[A\n     36%|\u2588\u2588\u2588\u258c      | 221/612 [04:36<05:55,  1.10it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  6.78files/s]\u001b[A\n     36%|\u2588\u2588\u2588\u258b      | 222/612 [04:37<05:24,  1.20it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.09files/s]\u001b[A\n     36%|\u2588\u2588\u2588\u258b      | 223/612 [04:37<05:22,  1.21it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.45s/files]\u001b[A\n     37%|\u2588\u2588\u2588\u258b      | 224/612 [04:39<07:34,  1.17s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 13.09files/s]\n     37%|\u2588\u2588\u2588\u258b      | 225/612 [04:40<06:24,  1.01it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.15files/s]\u001b[A\n     37%|\u2588\u2588\u2588\u258b      | 226/612 [04:41<06:28,  1.01s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.40s/files]\u001b[A\n     37%|\u2588\u2588\u2588\u258b      | 227/612 [04:43<08:10,  1.27s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 20.83files/s]\n     37%|\u2588\u2588\u2588\u258b      | 228/612 [04:44<06:46,  1.06s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.31files/s]\u001b[A\n     37%|\u2588\u2588\u2588\u258b      | 229/612 [04:45<07:10,  1.12s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.67s/files]\u001b[A\n     38%|\u2588\u2588\u2588\u258a      | 230/612 [04:47<09:10,  1.44s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.90s/files]\u001b[A\n     38%|\u2588\u2588\u2588\u258a      | 231/612 [04:49<10:58,  1.73s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.22files/s]\u001b[A\n     38%|\u2588\u2588\u2588\u258a      | 232/612 [04:51<10:12,  1.61s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.59s/files]\u001b[A\n     38%|\u2588\u2588\u2588\u258a      | 233/612 [04:54<12:59,  2.06s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.06s/files]\u001b[A\n     38%|\u2588\u2588\u2588\u258a      | 234/612 [04:56<13:53,  2.21s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.40files/s]\u001b[A\n     38%|\u2588\u2588\u2588\u258a      | 235/612 [04:57<11:24,  1.82s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.55s/files]\u001b[A\n     39%|\u2588\u2588\u2588\u258a      | 236/612 [04:59<11:50,  1.89s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.36s/files]\u001b[A\n     39%|\u2588\u2588\u2588\u258a      | 237/612 [05:01<11:44,  1.88s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  6.05files/s]\u001b[A\n     39%|\u2588\u2588\u2588\u2589      | 238/612 [05:02<09:26,  1.51s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 175.13files/s]\n     39%|\u2588\u2588\u2588\u2589      | 239/612 [05:02<07:32,  1.21s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.42s/files]\u001b[A\n     39%|\u2588\u2588\u2588\u2589      | 240/612 [05:05<10:42,  1.73s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.65s/files]\u001b[A\n     39%|\u2588\u2588\u2588\u2589      | 241/612 [05:07<11:29,  1.86s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.90files/s]\u001b[A\n     40%|\u2588\u2588\u2588\u2589      | 242/612 [05:08<09:36,  1.56s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.36s/files]\u001b[A\n     40%|\u2588\u2588\u2588\u2589      | 243/612 [05:10<10:09,  1.65s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.63files/s]\u001b[A\n     40%|\u2588\u2588\u2588\u2589      | 244/612 [05:11<09:08,  1.49s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 10.23files/s]\n     40%|\u2588\u2588\u2588\u2588      | 245/612 [05:12<07:30,  1.23s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 126.34files/s]\n     40%|\u2588\u2588\u2588\u2588      | 246/612 [05:12<06:09,  1.01s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.18files/s]\u001b[A\n     40%|\u2588\u2588\u2588\u2588      | 247/612 [05:13<06:05,  1.00s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.04files/s]\u001b[A\n     41%|\u2588\u2588\u2588\u2588      | 248/612 [05:15<06:57,  1.15s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  6.55files/s]\u001b[A\n     41%|\u2588\u2588\u2588\u2588      | 249/612 [05:16<06:05,  1.01s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.21s/files]\u001b[A\n     41%|\u2588\u2588\u2588\u2588      | 250/612 [05:17<07:28,  1.24s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.40s/files]\u001b[A\n     41%|\u2588\u2588\u2588\u2588      | 251/612 [05:20<10:27,  1.74s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 11.81files/s]\n     41%|\u2588\u2588\u2588\u2588      | 252/612 [05:21<08:23,  1.40s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  6.45files/s]\u001b[A\n     41%|\u2588\u2588\u2588\u2588\u258f     | 253/612 [05:22<07:03,  1.18s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.50files/s]\u001b[A\n     42%|\u2588\u2588\u2588\u2588\u258f     | 254/612 [05:22<06:19,  1.06s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  7.56files/s]\u001b[A\n     42%|\u2588\u2588\u2588\u2588\u258f     | 255/612 [05:23<05:32,  1.07it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.45files/s]\u001b[A\n     42%|\u2588\u2588\u2588\u2588\u258f     | 256/612 [05:24<05:17,  1.12it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 25.75files/s]\n     42%|\u2588\u2588\u2588\u2588\u258f     | 257/612 [05:24<04:37,  1.28it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.56files/s]\u001b[A\n     42%|\u2588\u2588\u2588\u2588\u258f     | 258/612 [05:25<05:17,  1.12it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.65s/files]\u001b[A\n     42%|\u2588\u2588\u2588\u2588\u258f     | 259/612 [05:28<07:30,  1.28s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 26.73files/s]\n     42%|\u2588\u2588\u2588\u2588\u258f     | 260/612 [05:28<06:12,  1.06s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.10s/files]\u001b[A\n     43%|\u2588\u2588\u2588\u2588\u258e     | 261/612 [05:30<07:09,  1.22s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.01files/s]\u001b[A\n     43%|\u2588\u2588\u2588\u2588\u258e     | 262/612 [05:31<07:41,  1.32s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.17s/files]\u001b[A\n     43%|\u2588\u2588\u2588\u2588\u258e     | 263/612 [05:33<08:18,  1.43s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  9.42files/s]\u001b[A\n     43%|\u2588\u2588\u2588\u2588\u258e     | 264/612 [05:34<06:51,  1.18s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.44files/s]\u001b[A\n     43%|\u2588\u2588\u2588\u2588\u258e     | 265/612 [05:35<06:52,  1.19s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.19s/files]\u001b[A\n     43%|\u2588\u2588\u2588\u2588\u258e     | 266/612 [05:36<07:46,  1.35s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.05s/files]\u001b[A\n     44%|\u2588\u2588\u2588\u2588\u258e     | 267/612 [05:39<09:51,  1.71s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.77files/s]\u001b[A\n     44%|\u2588\u2588\u2588\u2588\u258d     | 268/612 [05:40<08:13,  1.43s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  5.48files/s]\u001b[A\n     44%|\u2588\u2588\u2588\u2588\u258d     | 269/612 [05:41<06:57,  1.22s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.56files/s]\u001b[A\n     44%|\u2588\u2588\u2588\u2588\u258d     | 270/612 [05:41<06:22,  1.12s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.29files/s]\u001b[A\n     44%|\u2588\u2588\u2588\u2588\u258d     | 271/612 [05:43<06:38,  1.17s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.34s/files]\u001b[A\n     44%|\u2588\u2588\u2588\u2588\u258d     | 272/612 [05:45<07:48,  1.38s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.44files/s]\u001b[A\n     45%|\u2588\u2588\u2588\u2588\u258d     | 273/612 [05:46<07:30,  1.33s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.22s/files]\u001b[A\n     45%|\u2588\u2588\u2588\u2588\u258d     | 274/612 [05:49<09:51,  1.75s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 246.80files/s]\n     45%|\u2588\u2588\u2588\u2588\u258d     | 275/612 [05:49<07:44,  1.38s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.23s/files]\u001b[A\n     45%|\u2588\u2588\u2588\u2588\u258c     | 276/612 [05:52<09:57,  1.78s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.09s/files]\u001b[A\n     45%|\u2588\u2588\u2588\u2588\u258c     | 277/612 [05:53<09:38,  1.73s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.99s/files]\u001b[A\n     45%|\u2588\u2588\u2588\u2588\u258c     | 278/612 [05:56<10:55,  1.96s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.85s/files]\u001b[A\n     46%|\u2588\u2588\u2588\u2588\u258c     | 279/612 [05:58<11:32,  2.08s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.70files/s]\u001b[A\n     46%|\u2588\u2588\u2588\u2588\u258c     | 280/612 [05:59<09:49,  1.77s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 32.71files/s]\n     46%|\u2588\u2588\u2588\u2588\u258c     | 281/612 [06:00<07:44,  1.40s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.55s/files]\u001b[A\n     46%|\u2588\u2588\u2588\u2588\u258c     | 282/612 [06:02<08:47,  1.60s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.12s/files]\u001b[A\n     46%|\u2588\u2588\u2588\u2588\u258c     | 283/612 [06:04<08:48,  1.61s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.14files/s]\u001b[A\n     46%|\u2588\u2588\u2588\u2588\u258b     | 284/612 [06:04<07:45,  1.42s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.69files/s]\u001b[A\n     47%|\u2588\u2588\u2588\u2588\u258b     | 285/612 [06:06<07:16,  1.34s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.51s/files]\u001b[A\n     47%|\u2588\u2588\u2588\u2588\u258b     | 286/612 [06:08<08:21,  1.54s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.75s/files]\u001b[A\n     47%|\u2588\u2588\u2588\u2588\u258b     | 287/612 [06:10<09:30,  1.76s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.85files/s]\u001b[A\n     47%|\u2588\u2588\u2588\u2588\u258b     | 288/612 [06:11<07:49,  1.45s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 24.15files/s]\n     47%|\u2588\u2588\u2588\u2588\u258b     | 289/612 [06:11<06:23,  1.19s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.90s/files]\u001b[A\n     47%|\u2588\u2588\u2588\u2588\u258b     | 290/612 [06:14<08:20,  1.55s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.85files/s]\u001b[A\n     48%|\u2588\u2588\u2588\u2588\u258a     | 291/612 [06:15<07:31,  1.41s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.28files/s]\u001b[A\n     48%|\u2588\u2588\u2588\u2588\u258a     | 292/612 [06:16<07:19,  1.37s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.73s/files]\u001b[A\n     48%|\u2588\u2588\u2588\u2588\u258a     | 293/612 [06:18<08:39,  1.63s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  5.95files/s]\u001b[A\n     48%|\u2588\u2588\u2588\u2588\u258a     | 294/612 [06:19<07:05,  1.34s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.38s/files]\u001b[A\n     48%|\u2588\u2588\u2588\u2588\u258a     | 295/612 [06:21<07:56,  1.50s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 43.68files/s]\n     48%|\u2588\u2588\u2588\u2588\u258a     | 296/612 [06:21<06:22,  1.21s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  6.21files/s]\u001b[A\n     49%|\u2588\u2588\u2588\u2588\u258a     | 297/612 [06:22<05:28,  1.04s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.84files/s]\u001b[A\n     49%|\u2588\u2588\u2588\u2588\u258a     | 298/612 [06:23<05:03,  1.04it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 10.38files/s]\n     49%|\u2588\u2588\u2588\u2588\u2589     | 299/612 [06:23<04:27,  1.17it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.27s/files]\u001b[A\n     49%|\u2588\u2588\u2588\u2588\u2589     | 300/612 [06:26<07:26,  1.43s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.38s/files]\u001b[A\n     49%|\u2588\u2588\u2588\u2588\u2589     | 301/612 [06:28<08:06,  1.56s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  8.52files/s]\u001b[A\n     49%|\u2588\u2588\u2588\u2588\u2589     | 302/612 [06:29<06:36,  1.28s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 10.93files/s]\n     50%|\u2588\u2588\u2588\u2588\u2589     | 303/612 [06:29<05:31,  1.07s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.48s/files]\u001b[A\n     50%|\u2588\u2588\u2588\u2588\u2589     | 304/612 [06:31<06:56,  1.35s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.10s/files]\u001b[A\n     50%|\u2588\u2588\u2588\u2588\u2589     | 305/612 [06:34<08:51,  1.73s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.81files/s]\u001b[A\n     50%|\u2588\u2588\u2588\u2588\u2588     | 306/612 [06:35<07:47,  1.53s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.10s/files]\u001b[A\n     50%|\u2588\u2588\u2588\u2588\u2588     | 307/612 [06:36<07:51,  1.55s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  8.39files/s]\u001b[A\n     50%|\u2588\u2588\u2588\u2588\u2588     | 308/612 [06:37<06:25,  1.27s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 33.25files/s]\n     50%|\u2588\u2588\u2588\u2588\u2588     | 309/612 [06:38<05:17,  1.05s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.72files/s]\u001b[A\n     51%|\u2588\u2588\u2588\u2588\u2588     | 310/612 [06:39<05:17,  1.05s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.08files/s]\u001b[A\n     51%|\u2588\u2588\u2588\u2588\u2588     | 311/612 [06:40<05:49,  1.16s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 36.22files/s]\n     51%|\u2588\u2588\u2588\u2588\u2588     | 312/612 [06:41<04:51,  1.03it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 37.26files/s]\n     51%|\u2588\u2588\u2588\u2588\u2588     | 313/612 [06:41<04:11,  1.19it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.70s/files]\u001b[A\n     51%|\u2588\u2588\u2588\u2588\u2588\u258f    | 314/612 [06:43<06:12,  1.25s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.98files/s]\u001b[A\n     51%|\u2588\u2588\u2588\u2588\u2588\u258f    | 315/612 [06:44<05:34,  1.13s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.64files/s]\u001b[A\n     52%|\u2588\u2588\u2588\u2588\u2588\u258f    | 316/612 [06:45<05:30,  1.12s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  5.24files/s]\u001b[A\n     52%|\u2588\u2588\u2588\u2588\u2588\u258f    | 317/612 [06:46<04:50,  1.01it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.61files/s]\u001b[A\n     52%|\u2588\u2588\u2588\u2588\u2588\u258f    | 318/612 [06:47<04:27,  1.10it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.17files/s]\u001b[A\n     52%|\u2588\u2588\u2588\u2588\u2588\u258f    | 319/612 [06:48<05:03,  1.04s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.01s/files]\u001b[A\n     52%|\u2588\u2588\u2588\u2588\u2588\u258f    | 320/612 [06:51<07:11,  1.48s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.88s/files]\u001b[A\n     52%|\u2588\u2588\u2588\u2588\u2588\u258f    | 321/612 [06:53<08:29,  1.75s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 225.09files/s]\n     53%|\u2588\u2588\u2588\u2588\u2588\u258e    | 322/612 [06:53<06:39,  1.38s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.38files/s]\u001b[A\n     53%|\u2588\u2588\u2588\u2588\u2588\u258e    | 323/612 [06:55<06:25,  1.33s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 216.59files/s]\n     53%|\u2588\u2588\u2588\u2588\u2588\u258e    | 324/612 [06:55<05:11,  1.08s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.80files/s]\u001b[A\n     53%|\u2588\u2588\u2588\u2588\u2588\u258e    | 325/612 [06:56<05:08,  1.08s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.31files/s]\u001b[A\n     53%|\u2588\u2588\u2588\u2588\u2588\u258e    | 326/612 [06:57<04:45,  1.00it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.34s/files]\u001b[A\n     53%|\u2588\u2588\u2588\u2588\u2588\u258e    | 327/612 [07:00<07:23,  1.56s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.40files/s]\u001b[A\n     54%|\u2588\u2588\u2588\u2588\u2588\u258e    | 328/612 [07:01<06:11,  1.31s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.57files/s]\u001b[A\n     54%|\u2588\u2588\u2588\u2588\u2588\u258d    | 329/612 [07:02<05:54,  1.25s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.08s/files]\u001b[A\n     54%|\u2588\u2588\u2588\u2588\u2588\u258d    | 330/612 [07:03<06:20,  1.35s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.68s/files]\u001b[A\n     54%|\u2588\u2588\u2588\u2588\u2588\u258d    | 331/612 [07:05<07:29,  1.60s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.49s/files]\u001b[A\n     54%|\u2588\u2588\u2588\u2588\u2588\u258d    | 332/612 [07:07<08:01,  1.72s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.25s/files]\u001b[A\n     54%|\u2588\u2588\u2588\u2588\u2588\u258d    | 333/612 [07:09<08:02,  1.73s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.07s/files]\u001b[A\n     55%|\u2588\u2588\u2588\u2588\u2588\u258d    | 334/612 [07:12<09:11,  1.98s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.42files/s]\u001b[A\n     55%|\u2588\u2588\u2588\u2588\u2588\u258d    | 335/612 [07:13<07:30,  1.63s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.35s/files]\u001b[A\n     55%|\u2588\u2588\u2588\u2588\u2588\u258d    | 336/612 [07:15<07:51,  1.71s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 210.03files/s]\n     55%|\u2588\u2588\u2588\u2588\u2588\u258c    | 337/612 [07:15<06:10,  1.35s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 80.76files/s]\n     55%|\u2588\u2588\u2588\u2588\u2588\u258c    | 338/612 [07:16<05:00,  1.10s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.79s/files]\u001b[A\n     55%|\u2588\u2588\u2588\u2588\u2588\u258c    | 339/612 [07:18<06:36,  1.45s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.04s/files]\u001b[A\n     56%|\u2588\u2588\u2588\u2588\u2588\u258c    | 340/612 [07:19<06:43,  1.48s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.29s/files]\u001b[A\n     56%|\u2588\u2588\u2588\u2588\u2588\u258c    | 341/612 [07:21<07:06,  1.57s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.09s/files]\u001b[A\n     56%|\u2588\u2588\u2588\u2588\u2588\u258c    | 342/612 [07:23<07:08,  1.59s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 161.99files/s]\n     56%|\u2588\u2588\u2588\u2588\u2588\u258c    | 343/612 [07:23<05:38,  1.26s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.29files/s]\u001b[A\n     56%|\u2588\u2588\u2588\u2588\u2588\u258c    | 344/612 [07:25<05:39,  1.27s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.74s/files]\u001b[A\n     56%|\u2588\u2588\u2588\u2588\u2588\u258b    | 345/612 [07:27<06:56,  1.56s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.44s/files]\u001b[A\n     57%|\u2588\u2588\u2588\u2588\u2588\u258b    | 346/612 [07:29<07:25,  1.68s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.12files/s]\u001b[A\n     57%|\u2588\u2588\u2588\u2588\u2588\u258b    | 347/612 [07:30<06:28,  1.46s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.33s/files]\u001b[A\n     57%|\u2588\u2588\u2588\u2588\u2588\u258b    | 348/612 [07:33<08:14,  1.87s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.78files/s]\u001b[A\n     57%|\u2588\u2588\u2588\u2588\u2588\u258b    | 349/612 [07:33<06:54,  1.58s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.92files/s]\u001b[A\n     57%|\u2588\u2588\u2588\u2588\u2588\u258b    | 350/612 [07:35<06:14,  1.43s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.02files/s]\u001b[A\n     57%|\u2588\u2588\u2588\u2588\u2588\u258b    | 351/612 [07:35<05:38,  1.30s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 208.04files/s]\n     58%|\u2588\u2588\u2588\u2588\u2588\u258a    | 352/612 [07:36<04:36,  1.06s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.10s/files]\u001b[A\n     58%|\u2588\u2588\u2588\u2588\u2588\u258a    | 353/612 [07:38<05:14,  1.21s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 50.63files/s]\n     58%|\u2588\u2588\u2588\u2588\u2588\u258a    | 354/612 [07:38<04:19,  1.01s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.82s/files]\u001b[A\n     58%|\u2588\u2588\u2588\u2588\u2588\u258a    | 355/612 [07:41<07:16,  1.70s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.01files/s]\u001b[A\n     58%|\u2588\u2588\u2588\u2588\u2588\u258a    | 356/612 [07:43<06:58,  1.63s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.46s/files]\u001b[A\n     58%|\u2588\u2588\u2588\u2588\u2588\u258a    | 357/612 [07:45<07:19,  1.72s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.28s/files]\u001b[A\n     58%|\u2588\u2588\u2588\u2588\u2588\u258a    | 358/612 [07:47<07:20,  1.74s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 27.71files/s]\n     59%|\u2588\u2588\u2588\u2588\u2588\u258a    | 359/612 [07:47<05:48,  1.38s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 73.06files/s]\n     59%|\u2588\u2588\u2588\u2588\u2588\u2589    | 360/612 [07:48<04:41,  1.12s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  9.71files/s]\u001b[A\n     59%|\u2588\u2588\u2588\u2588\u2588\u2589    | 361/612 [07:48<04:02,  1.04it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 19.03files/s]\n     59%|\u2588\u2588\u2588\u2588\u2588\u2589    | 362/612 [07:49<03:30,  1.19it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.86files/s]\u001b[A\n     59%|\u2588\u2588\u2588\u2588\u2588\u2589    | 363/612 [07:50<03:46,  1.10it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.05s/files]\u001b[A\n     59%|\u2588\u2588\u2588\u2588\u2588\u2589    | 364/612 [07:52<05:48,  1.41s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.83s/files]\u001b[A\n     60%|\u2588\u2588\u2588\u2588\u2588\u2589    | 365/612 [07:55<06:55,  1.68s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 14.58files/s]\n     60%|\u2588\u2588\u2588\u2588\u2588\u2589    | 366/612 [07:55<05:31,  1.35s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 13.55files/s]\n     60%|\u2588\u2588\u2588\u2588\u2588\u2589    | 367/612 [07:56<04:34,  1.12s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 20.08files/s]\n     60%|\u2588\u2588\u2588\u2588\u2588\u2588    | 368/612 [07:57<03:55,  1.04it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.41files/s]\u001b[A\n     60%|\u2588\u2588\u2588\u2588\u2588\u2588    | 369/612 [07:57<03:39,  1.10it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.59s/files]\u001b[A\n     60%|\u2588\u2588\u2588\u2588\u2588\u2588    | 370/612 [07:59<05:02,  1.25s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 13.37files/s]\n     61%|\u2588\u2588\u2588\u2588\u2588\u2588    | 371/612 [08:00<04:12,  1.05s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.08s/files]\u001b[A\n     61%|\u2588\u2588\u2588\u2588\u2588\u2588    | 372/612 [08:01<04:48,  1.20s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.42files/s]\u001b[A\n     61%|\u2588\u2588\u2588\u2588\u2588\u2588    | 373/612 [08:03<04:46,  1.20s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.18files/s]\u001b[A\n     61%|\u2588\u2588\u2588\u2588\u2588\u2588    | 374/612 [08:03<04:15,  1.07s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 75.47files/s]\n     61%|\u2588\u2588\u2588\u2588\u2588\u2588\u258f   | 375/612 [08:04<03:33,  1.11it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.08files/s]\u001b[A\n     61%|\u2588\u2588\u2588\u2588\u2588\u2588\u258f   | 376/612 [08:05<04:09,  1.06s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.33files/s]\u001b[A\n     62%|\u2588\u2588\u2588\u2588\u2588\u2588\u258f   | 377/612 [08:07<04:20,  1.11s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.52files/s]\u001b[A\n     62%|\u2588\u2588\u2588\u2588\u2588\u2588\u258f   | 378/612 [08:07<03:54,  1.00s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 20.37files/s]\n     62%|\u2588\u2588\u2588\u2588\u2588\u2588\u258f   | 379/612 [08:08<03:19,  1.17it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.73files/s]\u001b[A\n     62%|\u2588\u2588\u2588\u2588\u2588\u2588\u258f   | 380/612 [08:09<03:33,  1.09it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.01files/s]\u001b[A\n     62%|\u2588\u2588\u2588\u2588\u2588\u2588\u258f   | 381/612 [08:10<04:12,  1.09s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  5.62files/s]\u001b[A\n     62%|\u2588\u2588\u2588\u2588\u2588\u2588\u258f   | 382/612 [08:11<03:42,  1.03it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.74s/files]\u001b[A\n     63%|\u2588\u2588\u2588\u2588\u2588\u2588\u258e   | 383/612 [08:13<05:08,  1.35s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  6.47files/s]\u001b[A\n     63%|\u2588\u2588\u2588\u2588\u2588\u2588\u258e   | 384/612 [08:14<04:18,  1.13s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.47files/s]\u001b[A\n     63%|\u2588\u2588\u2588\u2588\u2588\u2588\u258e   | 385/612 [08:15<04:01,  1.06s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.85files/s]\u001b[A\n     63%|\u2588\u2588\u2588\u2588\u2588\u2588\u258e   | 386/612 [08:16<03:58,  1.05s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.31files/s]\u001b[A\n     63%|\u2588\u2588\u2588\u2588\u2588\u2588\u258e   | 387/612 [08:17<04:11,  1.12s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.59s/files]\u001b[A\n     63%|\u2588\u2588\u2588\u2588\u2588\u2588\u258e   | 388/612 [08:19<05:14,  1.40s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.08files/s]\u001b[A\n     64%|\u2588\u2588\u2588\u2588\u2588\u2588\u258e   | 389/612 [08:20<04:43,  1.27s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 117.39files/s]\n     64%|\u2588\u2588\u2588\u2588\u2588\u2588\u258e   | 390/612 [08:21<03:50,  1.04s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.84s/files]\u001b[A\n     64%|\u2588\u2588\u2588\u2588\u2588\u2588\u258d   | 391/612 [08:23<05:14,  1.42s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.69files/s]\u001b[A\n     64%|\u2588\u2588\u2588\u2588\u2588\u2588\u258d   | 392/612 [08:24<04:36,  1.26s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.13files/s]\u001b[A\n     64%|\u2588\u2588\u2588\u2588\u2588\u2588\u258d   | 393/612 [08:25<04:42,  1.29s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.30s/files]\u001b[A\n     64%|\u2588\u2588\u2588\u2588\u2588\u2588\u258d   | 394/612 [08:27<05:15,  1.45s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.15files/s]\u001b[A\n     65%|\u2588\u2588\u2588\u2588\u2588\u2588\u258d   | 395/612 [08:28<05:08,  1.42s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.03files/s]\u001b[A\n     65%|\u2588\u2588\u2588\u2588\u2588\u2588\u258d   | 396/612 [08:29<04:26,  1.23s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.76files/s]\u001b[A\n     65%|\u2588\u2588\u2588\u2588\u2588\u2588\u258d   | 397/612 [08:30<04:00,  1.12s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.06s/files]\u001b[A\n     65%|\u2588\u2588\u2588\u2588\u2588\u2588\u258c   | 398/612 [08:32<04:27,  1.25s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.51s/files]\u001b[A\n     65%|\u2588\u2588\u2588\u2588\u2588\u2588\u258c   | 399/612 [08:34<05:13,  1.47s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  5.57files/s]\u001b[A\n     65%|\u2588\u2588\u2588\u2588\u2588\u2588\u258c   | 400/612 [08:34<04:21,  1.23s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.18s/files]\u001b[A\n     66%|\u2588\u2588\u2588\u2588\u2588\u2588\u258c   | 401/612 [08:36<04:47,  1.36s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.38s/files]\u001b[A\n     66%|\u2588\u2588\u2588\u2588\u2588\u2588\u258c   | 402/612 [08:38<05:18,  1.52s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 70.79files/s]\n     66%|\u2588\u2588\u2588\u2588\u2588\u2588\u258c   | 403/612 [08:38<04:13,  1.21s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.51files/s]\u001b[A\n     66%|\u2588\u2588\u2588\u2588\u2588\u2588\u258c   | 404/612 [08:39<04:07,  1.19s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  6.12files/s]\u001b[A\n     66%|\u2588\u2588\u2588\u2588\u2588\u2588\u258c   | 405/612 [08:40<03:32,  1.03s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.65s/files]\u001b[A\n     66%|\u2588\u2588\u2588\u2588\u2588\u2588\u258b   | 406/612 [08:42<04:39,  1.36s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.31s/files]\u001b[A\n     67%|\u2588\u2588\u2588\u2588\u2588\u2588\u258b   | 407/612 [08:44<05:06,  1.49s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.86s/files]\u001b[A\n     67%|\u2588\u2588\u2588\u2588\u2588\u2588\u258b   | 408/612 [08:46<05:57,  1.75s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 43.35files/s]\n     67%|\u2588\u2588\u2588\u2588\u2588\u2588\u258b   | 409/612 [08:47<04:44,  1.40s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.87files/s]\u001b[A\n     67%|\u2588\u2588\u2588\u2588\u2588\u2588\u258b   | 410/612 [08:48<04:11,  1.24s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.31files/s]\u001b[A\n     67%|\u2588\u2588\u2588\u2588\u2588\u2588\u258b   | 411/612 [08:49<03:46,  1.13s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.72files/s]\u001b[A\n     67%|\u2588\u2588\u2588\u2588\u2588\u2588\u258b   | 412/612 [08:50<03:42,  1.11s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 26.36files/s]\n     67%|\u2588\u2588\u2588\u2588\u2588\u2588\u258b   | 413/612 [08:50<03:07,  1.06it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.76s/files]\u001b[A\n     68%|\u2588\u2588\u2588\u2588\u2588\u2588\u258a   | 414/612 [08:53<04:25,  1.34s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.78files/s]\u001b[A\n     68%|\u2588\u2588\u2588\u2588\u2588\u2588\u258a   | 415/612 [08:53<03:51,  1.17s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.86files/s]\u001b[A\n     68%|\u2588\u2588\u2588\u2588\u2588\u2588\u258a   | 416/612 [08:54<03:24,  1.04s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.05files/s]\u001b[A\n     68%|\u2588\u2588\u2588\u2588\u2588\u2588\u258a   | 417/612 [08:55<03:06,  1.04it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 33.17files/s]\n     68%|\u2588\u2588\u2588\u2588\u2588\u2588\u258a   | 418/612 [08:55<02:40,  1.21it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 11.76files/s]\n     68%|\u2588\u2588\u2588\u2588\u2588\u2588\u258a   | 419/612 [08:56<02:29,  1.29it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.16s/files]\u001b[A\n     69%|\u2588\u2588\u2588\u2588\u2588\u2588\u258a   | 420/612 [08:59<04:17,  1.34s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.35files/s]\u001b[A\n     69%|\u2588\u2588\u2588\u2588\u2588\u2588\u2589   | 421/612 [09:00<03:45,  1.18s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.18s/files]\u001b[A\n     69%|\u2588\u2588\u2588\u2588\u2588\u2588\u2589   | 422/612 [09:02<05:11,  1.64s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.30files/s]\u001b[A\n     69%|\u2588\u2588\u2588\u2588\u2588\u2588\u2589   | 423/612 [09:03<04:30,  1.43s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.27files/s]\u001b[A\n     69%|\u2588\u2588\u2588\u2588\u2588\u2588\u2589   | 424/612 [09:05<04:21,  1.39s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.04files/s]\u001b[A\n     69%|\u2588\u2588\u2588\u2588\u2588\u2588\u2589   | 425/612 [09:06<04:23,  1.41s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  7.96files/s]\u001b[A\n     70%|\u2588\u2588\u2588\u2588\u2588\u2588\u2589   | 426/612 [09:07<03:38,  1.17s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.24files/s]\u001b[A\n     70%|\u2588\u2588\u2588\u2588\u2588\u2588\u2589   | 427/612 [09:08<03:44,  1.21s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.49files/s]\u001b[A\n     70%|\u2588\u2588\u2588\u2588\u2588\u2588\u2589   | 428/612 [09:09<03:26,  1.12s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 37.55files/s]\n     70%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588   | 429/612 [09:09<02:52,  1.06it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  7.90files/s]\u001b[A\n     70%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588   | 430/612 [09:10<02:32,  1.19it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  5.19files/s]\u001b[A\n     70%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588   | 431/612 [09:11<02:24,  1.26it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.64s/files]\u001b[A\n     71%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588   | 432/612 [09:13<03:36,  1.20s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.07files/s]\u001b[A\n     71%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588   | 433/612 [09:14<03:47,  1.27s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.62files/s]\u001b[A\n     71%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588   | 434/612 [09:15<03:16,  1.10s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.28files/s]\u001b[A\n     71%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588   | 435/612 [09:16<03:23,  1.15s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 24.05files/s]\n     71%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588   | 436/612 [09:17<02:49,  1.04it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 12.53files/s]\n     71%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f  | 437/612 [09:17<02:27,  1.19it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 224.46files/s]\n     72%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f  | 438/612 [09:18<02:09,  1.34it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.87s/files]\u001b[A\n     72%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f  | 439/612 [09:20<03:35,  1.25s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.37files/s]\u001b[A\n     72%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f  | 440/612 [09:21<03:33,  1.24s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.18files/s]\u001b[A\n     72%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f  | 441/612 [09:23<03:37,  1.27s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.46s/files]\u001b[A\n     72%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f  | 442/612 [09:25<04:11,  1.48s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.97files/s]\u001b[A\n     72%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f  | 443/612 [09:26<03:48,  1.35s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.11s/files]\u001b[A\n     73%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e  | 444/612 [09:27<04:00,  1.43s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.30files/s]\u001b[A\n     73%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e  | 445/612 [09:29<03:52,  1.39s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.00files/s]\u001b[A\n     73%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e  | 446/612 [09:30<03:56,  1.42s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.28files/s]\u001b[A\n     73%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e  | 447/612 [09:31<03:48,  1.38s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.96files/s]\u001b[A\n     73%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e  | 448/612 [09:32<03:28,  1.27s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.28files/s]\u001b[A\n     73%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e  | 449/612 [09:33<03:11,  1.17s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 96.65files/s]\n     74%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e  | 450/612 [09:34<02:38,  1.02it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 61.03files/s]\n     74%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e  | 451/612 [09:34<02:14,  1.20it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 39.48files/s]\n     74%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d  | 452/612 [09:35<01:58,  1.34it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.78files/s]\u001b[A\n     74%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d  | 453/612 [09:36<01:58,  1.34it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  6.16files/s]\u001b[A\n     74%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d  | 454/612 [09:36<01:53,  1.39it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.46s/files]\u001b[A\n     74%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d  | 455/612 [09:38<02:51,  1.09s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.12files/s]\u001b[A\n     75%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d  | 456/612 [09:39<02:47,  1.08s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 15.92files/s]\n     75%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d  | 457/612 [09:40<02:23,  1.08it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.36s/files]\u001b[A\n     75%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d  | 458/612 [09:43<03:54,  1.52s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.50s/files]\u001b[A\n     75%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c  | 459/612 [09:45<04:15,  1.67s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.65s/files]\u001b[A\n     75%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c  | 460/612 [09:47<04:35,  1.81s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.12s/files]\u001b[A\n     75%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c  | 461/612 [09:50<05:13,  2.08s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.24s/files]\u001b[A\n     75%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c  | 462/612 [09:52<05:40,  2.27s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 13.05files/s]\n     76%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c  | 463/612 [09:53<04:23,  1.77s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 122.52files/s]\n     76%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c  | 464/612 [09:54<03:25,  1.39s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  5.73files/s]\u001b[A\n     76%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c  | 465/612 [09:54<02:51,  1.17s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 17.66files/s]\n     76%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c  | 466/612 [09:55<02:23,  1.02it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.33s/files]\u001b[A\n     76%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b  | 467/612 [09:58<03:42,  1.53s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.47files/s]\u001b[A\n     76%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b  | 468/612 [09:59<03:26,  1.44s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 31.20files/s]\n     77%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b  | 469/612 [09:59<02:45,  1.16s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.68files/s]\u001b[A\n     77%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b  | 470/612 [10:00<02:41,  1.14s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.52files/s]\u001b[A\n     77%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b  | 471/612 [10:02<02:41,  1.14s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 49.73files/s]\n     77%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b  | 472/612 [10:02<02:13,  1.05it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 19.39files/s]\n     77%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b  | 473/612 [10:03<01:54,  1.21it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 10.19files/s]\n     77%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b  | 474/612 [10:03<01:44,  1.32it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.25files/s]\u001b[A\n     78%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a  | 475/612 [10:04<01:43,  1.32it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 13.77files/s]\n     78%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a  | 476/612 [10:05<01:35,  1.42it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  8.04files/s]\u001b[A\n     78%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a  | 477/612 [10:05<01:30,  1.48it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.93files/s]\u001b[A\n     78%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a  | 478/612 [10:06<01:43,  1.29it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.35s/files]\u001b[A\n     78%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a  | 479/612 [10:08<02:24,  1.09s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.32s/files]\u001b[A\n     78%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a  | 480/612 [10:10<02:52,  1.31s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 62.00files/s]\n     79%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a  | 481/612 [10:10<02:20,  1.07s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 73.70files/s]\n     79%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589  | 482/612 [10:11<01:56,  1.12it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.11files/s]\u001b[A\n     79%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589  | 483/612 [10:12<01:57,  1.09it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.35s/files]\u001b[A\n     79%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589  | 484/612 [10:14<02:32,  1.19s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.81files/s]\u001b[A\n     79%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589  | 485/612 [10:14<02:13,  1.05s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  9.30files/s]\u001b[A\n     79%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589  | 486/612 [10:15<01:55,  1.09it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 17.51files/s]\n     80%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589  | 487/612 [10:15<01:40,  1.25it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.36s/files]\u001b[A\n     80%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589  | 488/612 [10:17<02:18,  1.11s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.03files/s]\u001b[A\n     80%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589  | 489/612 [10:19<02:29,  1.22s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.26s/files]\u001b[A\n     80%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588  | 490/612 [10:20<02:47,  1.37s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  6.01files/s]\u001b[A\n     80%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588  | 491/612 [10:21<02:19,  1.16s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 25.30files/s]\n     80%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588  | 492/612 [10:22<01:55,  1.03it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.06files/s]\u001b[A\n     81%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588  | 493/612 [10:23<01:55,  1.03it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  5.21files/s]\u001b[A\n     81%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588  | 494/612 [10:23<01:44,  1.13it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.37files/s]\u001b[A\n     81%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588  | 495/612 [10:25<01:55,  1.01it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 115.87files/s]\n     81%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588  | 496/612 [10:25<01:37,  1.19it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.18files/s]\u001b[A\n     81%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588  | 497/612 [10:26<01:40,  1.14it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.67files/s]\u001b[A\n     81%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f | 498/612 [10:27<01:46,  1.07it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.06s/files]\u001b[A\n     82%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f | 499/612 [10:29<02:06,  1.12s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.07files/s]\u001b[A\n     82%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f | 500/612 [10:30<02:16,  1.21s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 77.58files/s]\n     82%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f | 501/612 [10:31<01:51,  1.00s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.09s/files]\u001b[A\n     82%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f | 502/612 [10:32<02:09,  1.18s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 38.80files/s]\n     82%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f | 503/612 [10:33<01:46,  1.02it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.36files/s]\u001b[A\n     82%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f | 504/612 [10:33<01:36,  1.12it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  6.18files/s]\u001b[A\n     83%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e | 505/612 [10:34<01:28,  1.21it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  6.57files/s]\u001b[A\n     83%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e | 506/612 [10:35<01:21,  1.30it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.25files/s]\u001b[A\n     83%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e | 507/612 [10:36<01:36,  1.08it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 18.23files/s]\n     83%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e | 508/612 [10:36<01:24,  1.24it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.17files/s]\u001b[A\n     83%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e | 509/612 [10:38<01:39,  1.03it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 46.71files/s]\n     83%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e | 510/612 [10:38<01:24,  1.21it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.35files/s]\u001b[A\n     83%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e | 511/612 [10:40<01:35,  1.06it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  7.07files/s]\u001b[A\n     84%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e | 512/612 [10:40<01:24,  1.18it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.08s/files]\u001b[A\n     84%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d | 513/612 [10:42<01:45,  1.06s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  9.17files/s]\u001b[A\n     84%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d | 514/612 [10:42<01:30,  1.09it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 10.18files/s]\n     84%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d | 515/612 [10:43<01:19,  1.22it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 45.32files/s]\n     84%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d | 516/612 [10:43<01:09,  1.39it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.30files/s]\u001b[A\n     84%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d | 517/612 [10:44<01:11,  1.33it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.87files/s]\u001b[A\n     85%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d | 518/612 [10:45<01:18,  1.21it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.78files/s]\u001b[A\n     85%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d | 519/612 [10:46<01:19,  1.18it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 202.66files/s]\n     85%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d | 520/612 [10:47<01:08,  1.34it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  7.25files/s]\u001b[A\n     85%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c | 521/612 [10:47<01:05,  1.39it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.38files/s]\u001b[A\n     85%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c | 522/612 [10:48<01:18,  1.15it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.78files/s]\u001b[A\n     85%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c | 523/612 [10:49<01:13,  1.21it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.15s/files]\u001b[A\n     86%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c | 524/612 [10:51<01:33,  1.07s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.15files/s]\u001b[A\n     86%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c | 525/612 [10:52<01:40,  1.16s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.22files/s]\u001b[A\n     86%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c | 526/612 [10:54<01:43,  1.21s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.47files/s]\u001b[A\n     86%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c | 527/612 [10:55<01:41,  1.20s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  7.67files/s]\u001b[A\n     86%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b | 528/612 [10:55<01:25,  1.02s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.87files/s]\u001b[A\n     86%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b | 529/612 [10:56<01:24,  1.02s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.69s/files]\u001b[A\n     87%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b | 530/612 [10:58<01:51,  1.36s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 27.18files/s]\n     87%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b | 531/612 [10:59<01:30,  1.11s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.37files/s]\u001b[A\n     87%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b | 532/612 [11:00<01:31,  1.14s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.20s/files]\u001b[A\n     87%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b | 533/612 [11:03<02:09,  1.64s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.08files/s]\u001b[A\n     87%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b | 534/612 [11:04<02:03,  1.58s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 35.88files/s]\n     87%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b | 535/612 [11:05<01:37,  1.27s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.18files/s]\u001b[A\n     88%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a | 536/612 [11:06<01:37,  1.29s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.25files/s]\u001b[A\n     88%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a | 537/612 [11:08<01:36,  1.29s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.94files/s]\u001b[A\n     88%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a | 538/612 [11:08<01:22,  1.12s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.41s/files]\u001b[A\n     88%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a | 539/612 [11:10<01:39,  1.36s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 32.01files/s]\n     88%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a | 540/612 [11:11<01:19,  1.10s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.86files/s]\u001b[A\n     88%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a | 541/612 [11:11<01:09,  1.02it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.86s/files]\u001b[A\n     89%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a | 542/612 [11:14<01:37,  1.39s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 143.00files/s]\n     89%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a | 543/612 [11:14<01:17,  1.13s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.41files/s]\u001b[A\n     89%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589 | 544/612 [11:16<01:17,  1.15s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.02files/s]\u001b[A\n     89%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589 | 545/612 [11:17<01:23,  1.24s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.04files/s]\u001b[A\n     89%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589 | 546/612 [11:18<01:26,  1.30s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  5.78files/s]\u001b[A\n     89%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589 | 547/612 [11:19<01:12,  1.11s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  9.66files/s]\u001b[A\n     90%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589 | 548/612 [11:20<01:01,  1.03it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 87.98files/s]\n     90%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589 | 549/612 [11:20<00:51,  1.21it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.93files/s]\u001b[A\n     90%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589 | 550/612 [11:21<00:48,  1.28it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.03files/s]\u001b[A\n     90%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 | 551/612 [11:22<00:59,  1.02it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  6.09files/s]\u001b[A\n     90%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 | 552/612 [11:23<00:52,  1.14it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.81files/s]\u001b[A\n     90%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 | 553/612 [11:24<00:54,  1.08it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.68files/s]\u001b[A\n     91%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 | 554/612 [11:25<00:56,  1.03it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 165.40files/s]\n     91%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 | 555/612 [11:26<00:46,  1.21it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 63.36files/s]\n     91%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 | 556/612 [11:26<00:40,  1.38it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 30.60files/s]\n     91%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 | 557/612 [11:27<00:36,  1.51it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.44files/s]\u001b[A\n     91%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 | 558/612 [11:27<00:37,  1.44it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.57files/s]\u001b[A\n     91%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f| 559/612 [11:28<00:43,  1.21it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.61files/s]\u001b[A\n     92%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f| 560/612 [11:30<00:47,  1.10it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.83files/s]\u001b[A\n     92%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f| 561/612 [11:30<00:45,  1.12it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.01s/files]\u001b[A\n     92%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f| 562/612 [11:32<00:53,  1.08s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.55files/s]\u001b[A\n     92%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f| 563/612 [11:33<00:53,  1.09s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  5.08files/s]\u001b[A\n     92%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f| 564/612 [11:34<00:46,  1.03it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.15s/files]\u001b[A\n     92%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f| 565/612 [11:35<00:55,  1.17s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  6.79files/s]\u001b[A\n     92%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f| 566/612 [11:36<00:46,  1.02s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 96.67files/s]\n     93%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e| 567/612 [11:37<00:38,  1.16it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.51files/s]\u001b[A\n     93%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e| 568/612 [11:38<00:41,  1.06it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  6.81files/s]\u001b[A\n     93%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e| 569/612 [11:38<00:36,  1.17it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 67.82files/s]\n     93%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e| 570/612 [11:39<00:31,  1.34it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.43s/files]\u001b[A\n     93%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e| 571/612 [11:42<00:57,  1.40s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 16.88files/s]\n     93%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e| 572/612 [11:42<00:45,  1.14s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 18.10files/s]\n     94%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e| 573/612 [11:43<00:37,  1.03it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.25files/s]\u001b[A\n     94%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d| 574/612 [11:44<00:40,  1.07s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  4.66files/s]\u001b[A\n     94%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d| 575/612 [11:45<00:35,  1.03it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.48s/files]\u001b[A\n     94%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d| 576/612 [11:47<00:45,  1.27s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.78files/s]\u001b[A\n     94%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d| 577/612 [11:48<00:39,  1.12s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.44s/files]\u001b[A\n     94%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d| 578/612 [11:50<00:46,  1.36s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  8.79files/s]\u001b[A\n     95%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d| 579/612 [11:50<00:37,  1.14s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.06files/s]\u001b[A\n     95%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d| 580/612 [11:52<00:39,  1.23s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  7.40files/s]\u001b[A\n     95%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d| 581/612 [11:52<00:32,  1.06s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 53.23files/s]\n     95%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c| 582/612 [11:53<00:26,  1.12it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.18files/s]\u001b[A\n     95%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c| 583/612 [11:54<00:26,  1.11it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 407.13files/s]\n     95%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c| 584/612 [11:54<00:21,  1.28it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 92.87files/s]\n     96%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c| 585/612 [11:55<00:18,  1.44it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.83files/s]\u001b[A\n     96%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c| 586/612 [11:56<00:20,  1.25it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 49.19files/s]\n     96%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c| 587/612 [11:56<00:17,  1.40it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 10.12files/s]\n     96%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c| 588/612 [11:57<00:16,  1.47it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.98files/s]\u001b[A\n     96%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c| 589/612 [11:58<00:16,  1.43it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.19files/s]\u001b[A\n     96%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b| 590/612 [11:59<00:19,  1.13it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 46.62files/s]\n     97%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b| 591/612 [11:59<00:16,  1.30it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  9.10files/s]\u001b[A\n     97%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b| 592/612 [12:00<00:14,  1.40it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.87s/files]\u001b[A\n     97%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b| 593/612 [12:02<00:22,  1.21s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.93files/s]\u001b[A\n     97%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b| 594/612 [12:03<00:19,  1.10s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.28s/files]\u001b[A\n     97%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b| 595/612 [12:05<00:22,  1.30s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.77files/s]\u001b[A\n     97%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b| 596/612 [12:06<00:19,  1.22s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.20files/s]\u001b[A\n     98%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a| 597/612 [12:07<00:18,  1.25s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.39files/s]\u001b[A\n     98%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a| 598/612 [12:09<00:17,  1.25s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 11.53files/s]\n     98%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a| 599/612 [12:09<00:13,  1.04s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.07s/files]\u001b[A\n     98%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a| 600/612 [12:11<00:14,  1.20s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.14files/s]\u001b[A\n     98%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a| 601/612 [12:12<00:12,  1.12s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.53s/files]\u001b[A\n     98%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a| 602/612 [12:14<00:13,  1.39s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.69files/s]\u001b[A\n     99%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a| 603/612 [12:14<00:10,  1.20s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 84.01files/s]\n     99%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a| 604/612 [12:15<00:07,  1.01it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 24.00files/s]\n     99%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589| 605/612 [12:15<00:05,  1.18it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  3.76files/s]\u001b[A\n     99%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589| 606/612 [12:16<00:04,  1.23it/s]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.12s/files]\u001b[A\n     99%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589| 607/612 [12:18<00:05,  1.05s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.01s/files]\u001b[A\n     99%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589| 608/612 [12:19<00:04,  1.19s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:01<00:00,  1.13s/files]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589| 609/612 [12:21<00:03,  1.32s/it]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00, 13.31files/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589| 610/612 [12:21<00:02,  1.09s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  2.38files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589| 611/612 [12:22<00:01,  1.03s/it]\n      0%|          | 0/1 [00:00<?, ?files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:00<00:00,  1.72files/s]\u001b[A\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 612/612 [12:23<00:00,  1.22s/it]\n\n\n\n```python\nresults[:3]\n```\n\n\n\n\n    [('aquinas',\n      '../data/aquinas/ccm0.txt',\n      1134,\n      0.03262786596119929,\n      0.06437389770723104),\n     ('aquinas',\n      '../data/aquinas/cmt00b.txt',\n      2132,\n      0.06894934333958724,\n      0.11538461538461539),\n     ('aquinas',\n      '../data/aquinas/cih00.txt',\n      2813,\n      0.04550302168503377,\n      0.0810522573764664)]\n\n\n\n\n```python\nauthors, files, sizes, lemma_counts, inflected_counts = zip(*results)\n```\n\n\n```python\nimport numpy as np\n```\n\n\n```python\n np.mean(inflected_counts), np.std(inflected_counts)\n```\n\n\n\n\n    (0.040614957083179186, 0.07611207700363683)\n\n\n\n\n```python\nimport matplotlib.pyplot as plt\n```\n\n\n```python\n \nplt.hist( inflected_counts, bins=10)\n```\n\n\n```python\nplt.hist(lemma_counts, bins=10)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "6750c8b22a11668e275ec8c1abbfe7ad12ac25bb", "size": 337429, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "probabilistic_language_modeling/cicero_corpus_counts.ipynb", "max_stars_repo_name": "todd-cook/ML-You-Can-Use", "max_stars_repo_head_hexsha": "45c86d6f70b7d216c421ea005e022f5d6f5501cd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2019-02-25T09:57:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T17:25:43.000Z", "max_issues_repo_path": "probabilistic_language_modeling/cicero_corpus_counts.ipynb", "max_issues_repo_name": "todd-cook/ML-You-Can-Use", "max_issues_repo_head_hexsha": "45c86d6f70b7d216c421ea005e022f5d6f5501cd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-01-09T08:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T00:07:08.000Z", "max_forks_repo_path": "probabilistic_language_modeling/cicero_corpus_counts.ipynb", "max_forks_repo_name": "todd-cook/ML-You-Can-Use", "max_forks_repo_head_hexsha": "45c86d6f70b7d216c421ea005e022f5d6f5501cd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-01-28T18:35:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T21:11:08.000Z", "avg_line_length": 64.0769084694, "max_line_length": 25272, "alphanum_fraction": 0.6102735687, "converted": true, "num_tokens": 81020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.08509904500702024, "lm_q1q2_score": 0.03530749555181998}}
{"text": "<font size = \"5\"> **Chapter 5: [Instrument](CH5_00-Instrument.ipynb)** </font>\n\n\n<hr style=\"height:1px;border-top:4px solid #FF8200\" />\n\n\n# Apertures, Deflectors, and Magnetic Lenses\n\n[Download](https://raw.githubusercontent.com/gduscher/MSE672-Introduction-to-TEM//main/Instrument/CH5_03-Lenses.ipynb)\n \n[](\n    https://colab.research.google.com/github/gduscher/MSE672-Introduction-to-TEM/blob/main/Instrument/CH5_03-Lenses.ipynb)\n\n\n\npart of \n\n<font size = \"5\"> **[MSE672:  Introduction to Transmission Electron Microscopy](../_MSE672_Intro_TEM.ipynb)**</font>\n\nby Gerd Duscher, Spring 2021\n\nMicroscopy Facilities<br>\nJoint Institute of Advanced Materials<br>\nMaterials Science & Engineering<br>\nThe University of Tennessee, Knoxville\n\nBackground and methods to analysis and quantification of data acquired with transmission electron microscopes.\n\n\n## Magnetic Lenses\nElectro--magnetic lenses are different from optical lenses: You can change the focal length.\n\nFor a deeper understanding and a better operation of the TEM, we have to discuss the details.\n\nElectro--static lenses are not common anymore, because the long term stability is hard to achieve.\nMagnetic lenses are much easier to keep stable.\n\n\n\nThe cut through a magnetic lens. Please note that all lenses must be radial symmetric.\\\\\n\n\n\nThe coil produces a strong magnetic field (up to 1 Tesla or higher), which is concentrated at the pole piece.\nThis pole piece consists of soft iron to achieve a maximal inhomogeneous magnetic field (2.1 Tesla). \nAt room temperature  you cannot achieve a higher field than the maximum magnetic field of iron. \n\n\nBecause pure iron is a very soft material, this pole piece has to be handled with extreme care. \nAny scratch, inhomogeneity or dirt (results from magnetic samples which FLY to the pole piece) destroy \nthe radial symmetry and induce optical errors.\n\n\nThe gap is needed to place apertures and the sample close to the focal planes. \nThis gap doesn't cause a problem at weak lenses, but at strong lenses (objective lens) this gap induces optical errors.\nThe focal length of a strong lens is also short, and the sample has o be paced inside the objective lens. High resolution lenses always exhibit a small gap to minimize optical errors which results in limited sample tilt.\n\n\nTEM manufactures invest a lot of money and time to develop new designs of the pole pieces and lens designs.\n\nThe coils are made of wires with a low but still some resistance. this resistance heats the lenses and water pipes are integrated for cooling. \n\nTEM manufactures invest a lot of money and time to develop new designs of the pole pieces and lens designs.\n\n\n```python\n\n```\n\n### Electrons in a Magnetic Field\n\nThe main equation which describes the motion of an electron in an electro-magnetic field is: \n$$\n\\begin{equation}\\Large \\label{magnetic force}\n\\vec{F} = q (\\vec{E} + \\vec{v} \\times \\vec{B}) = e(\\vec{v} \\times \\vec{B})\n\\end{equation}\n$$\nThe force $\\vec{F}$ on an electron with charge $q=e$ depends on the electric field $\\vec{E}$ and the vector cross product ($\\times$) of velocity $\\vec{v}$ and magnetic field $\\vec{B}$ (measured in Tesla).  \n\nFor magnetic fields we can ignore the effect of the electric field. The effect of the magnetic field is described by the left hand rule as pictured below.\n\n\n\nThe forefinger points in the direction of the magnetic field $\\vec{B}$, the second finger in the direction the electron flies initially and the thumb will give you the direction of the thrust.\n\nThis left hand rule shows immediately that for a $\\theta$ of 0$\\rm ^o$ and 180$\\rm ^o$, we do not know what to do and really there is no thrust. The thrust is maximum for a $\\theta$ of 90$\\rm ^o$.\n\nFor small deviation angles we can make the approximation for the magnitude of the force:\n$$\nF =  e v B \\sin \\theta \\approx e v B = \\frac{mv^2}{r}\n$$\nThe smaller the distance from the optic axis $r$ the higher is the force. The higher the velocity of the electrons the stronger the lens has to be.\n\nFor 100 keV electrons and a lens diameter of 1 mm, the magnetic field $B$ has to be in the order of 1 Tesla.\n\n\nAny direction of the beam can be split in a motion parallel $\\vec{v}_{\\|}$ and perpendicular $\\vec{v}_{\\bot}$ to the magnetic field direction. \n$$\n\\Large\n\\vec{v}_{\\|} = v \\sin \\theta\n$$\n$$\n\\Large\n\\vec{v}_{\\bot} = v \\cos \\theta\n$$\n\nThe parallel motion is undisturbed while the perpendicular motion will result in a circle.\nThe radius of this  circle is $$\\Large r=\\frac{mv}{eB}$$. \n\t\n\nBoth motions together result in a spiral motion with the frequency $$ \\Large \\omega_c = \\frac{2\\pi}{T_c}=\\frac{eB}{m}\\not\\approx v$$.\n\nMathematical, we can write for the near axis motion the paraxial ray equations.\n$$\n\\frac{d^2r}{dz2}+\\frac {\\eta B^2 r}{2V^{\\frac{1}{2}}} = 0\n$$\n$$\n\\frac{d\\theta}{dz}=\\frac {\\eta B}{2V^{\\frac{1}{2}}} = 0\n$$\n\nwith \n$$\n\\eta = \\sqrt{\\frac{e}{2m_0c^2}}\n$$\n\nThis results in a smaller $\\Delta r$ for higher energetic electrons (higher acceleration Voltage $V$), and therefore in the need to increase the magnetic field.\n\nBecause real lenses are not indefinite thin, but have a certain length, there will always be spiral motion and therefore an image rotation associated with a magnetic lens. The TEM manufactures have a variety of lens settings for different magnifications, which can minimize or cancel image rotation.\n\n\n\n\n## Apertures\n\nAs you know you can put apertures in and out, also you can move them, so that they are aligned with respect to the optic axis.\nThese apertures are little plates with small hopefully round holes in it; they are called diaphragm. The holes are about 10 $\\mu$m to 100 $\\mu$m in diameter.\n\n\nThe diaphragm are made of molybdenum, copper or gold.\nThe gold apertures have a self cleaning effect, if you hit them with an intense electron beam and are therefore preferable in a TEM. You cannot use them in a dedicated STEM, where the beam current is much lower.\n\n## Electron Beam Deflection\n\n\n\nAligning the microscope means to bring all the optical elements (electron source, apertures, lenses, ...) onto the same optical axis. To do this a rough alignment is done mechanically. The lenses are pushed and tilted close to a common optic axis. The day to day alignment of the TEM is done electronically with deflectors. These alignment deflectors (with long time stability) are normally magnetic. \n\nIn a scanning TEM (or SEM), where the beam has to be moved around, electro--static deflectors are used. \nAlso other deflectors, which have to be fast (beam blanker), use electro--static forces.\nWhile a magnetic deflector need a few microseconds, a electro--static one can do in a split of a microsecond.\n\n\n\nFor the magnetic deflectors, the deflection angle $\\epsilon$ is give by:\n\\begin{equation}\\Large\n\\epsilon = \\frac{eLB}{mv}\n\\end{equation}\n\nFor a 5$^{\\rm o}$ deflection of 100keV electrons we need 0.01 Tesla. That means 100 turn coil with 0.2 A.\n\nWe will go a little bit more in detail with the electro--static deflection.\\\\\n\nWe have the following equations:\n$$ \\Large v=\\frac{dz}{dt};$$$$ \\Large p_z=mv;$$$$ \\Large T=\\frac{L}{v}$$\n\n\n\t\n\n\t\nDeflection of an electron in an electro--static field $\\vec{E}$\n\t\n\n\nFor the momentum in x direction we get:\n\\begin{equation}\\Large \np_x = \\int_0^T F dt= e \\int_0^T E dt = \\frac{e}{v} \\int_0^L E dz = \\frac{eEL}{v}\n\\end{equation}\n\nFor 100 keV electrons in a deflector (capacitor) need an electric field of 20000 V/cm to be deflected by 0.1 rad (5$\\rm o$)  For that you have to apply a Voltage of 4000V to a deflector with a length $L$ of 1cm and a width $d$ of 2mm.\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "8ae614ed68530e4a921477b3c8de8c6c6b178efd", "size": 10729, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Instrument/CH5_03-Lenses.ipynb", "max_stars_repo_name": "ahoust17/MSE672-Introduction-to-TEM", "max_stars_repo_head_hexsha": "6b412a3ad07ee273428a95a7158aa09058d7e2ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-01-22T18:09:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T20:17:34.000Z", "max_issues_repo_path": "Instrument/CH5_03-Lenses.ipynb", "max_issues_repo_name": "ahoust17/MSE672-Introduction-to-TEM", "max_issues_repo_head_hexsha": "6b412a3ad07ee273428a95a7158aa09058d7e2ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Instrument/CH5_03-Lenses.ipynb", "max_forks_repo_name": "ahoust17/MSE672-Introduction-to-TEM", "max_forks_repo_head_hexsha": "6b412a3ad07ee273428a95a7158aa09058d7e2ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2021-01-26T16:10:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T14:53:16.000Z", "avg_line_length": 42.5753968254, "max_line_length": 410, "alphanum_fraction": 0.6226116134, "converted": true, "num_tokens": 1958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798742624020279, "lm_q2_score": 0.14223190228178134, "lm_q1q2_score": 0.035271723376106984}}
{"text": "# Feed-forward and Recurrent Language Models\n\n### Preliminaries\n\n\n```python\n%pylab inline\n%load_ext autoreload\n%autoreload 2\n```\n\n    Populating the interactive namespace from numpy and matplotlib\n\n\n\n```python\n# !pip install jsonlines tqdm\n```\n\n    Requirement already satisfied: jsonlines in /home/aims/anaconda3/envs/aims/lib/python3.7/site-packages (1.2.0)\n    Requirement already satisfied: tqdm in /home/aims/anaconda3/envs/aims/lib/python3.7/site-packages (4.37.0)\n    Requirement already satisfied: six in /home/aims/anaconda3/envs/aims/lib/python3.7/site-packages (from jsonlines) (1.12.0)\n\n\n\n```python\n# download pretrained models and data\n### DOWNLOADING THE FILES\nimport os\n\n### persona chat dataset\nif not os.path.exists('personachat_all_sentences_train.jsonl'):\n    !wget \"https://nyu.box.com/shared/static/q4nvswb0szelivhgyx87vd1056ttqfyi.jsonl\" -O 'personachat_all_sentences_train.jsonl'\nif not os.path.exists('personachat_all_sentences_valid.jsonl'):\n    !wget \"https://nyu.box.com/shared/static/8krcizo8sms1m0ppy7uiwfcx4a3l5nsq.jsonl\" -O 'personachat_all_sentences_valid.jsonl'\nif not os.path.exists('personachat_all_sentences_test.jsonl'):\n    !wget \"https://nyu.box.com/shared/static/im7we9k2gcf8kslqnfamsimicgosuw9y.jsonl\" -O 'personachat_all_sentences_test.jsonl'\n\n## wikitext-2 dataset\nif not os.path.exists('wikitext2-sentencized.json'):\n    !wget \"https://nyu.box.com/shared/static/9kb7l7ci30hb6uahhbssjlq0kctr5ii4.json\" -O 'wikitext2-sentencized.json'\n\n### pretrained ffnn model\nif not os.path.exists('personachat_ffnn_lm.pt'):\n    !wget \"https://nyu.box.com/shared/static/looczvct7ssh30x0gwqmvencple8xok9.pt\" -O 'personachat_ffnn_lm.pt'\n\n### pretrained rnn model\nif not os.path.exists('personachat_rnn_lm.pt'):\n    !wget \"https://nyu.box.com/shared/static/3jl9erctnvbefnczgmetkdil0xwpcxzb.pt\" -O 'personachat_rnn_lm.pt'\n```\n\n    --2020-03-22 23:46:58--  https://nyu.box.com/shared/static/q4nvswb0szelivhgyx87vd1056ttqfyi.jsonl\n    Resolving nyu.box.com (nyu.box.com)... 185.235.236.197\n    Connecting to nyu.box.com (nyu.box.com)|185.235.236.197|:443... connected.\n    HTTP request sent, awaiting response... 301 Moved Permanently\n    Location: /public/static/q4nvswb0szelivhgyx87vd1056ttqfyi.jsonl [following]\n    --2020-03-22 23:46:59--  https://nyu.box.com/public/static/q4nvswb0szelivhgyx87vd1056ttqfyi.jsonl\n    Reusing existing connection to nyu.box.com:443.\n    HTTP request sent, awaiting response... 301 Moved Permanently\n    Location: https://nyu.app.box.com/public/static/q4nvswb0szelivhgyx87vd1056ttqfyi.jsonl [following]\n    --2020-03-22 23:47:00--  https://nyu.app.box.com/public/static/q4nvswb0szelivhgyx87vd1056ttqfyi.jsonl\n    Resolving nyu.app.box.com (nyu.app.box.com)... 185.235.236.199\n    Connecting to nyu.app.box.com (nyu.app.box.com)|185.235.236.199|:443... connected.\n    HTTP request sent, awaiting response... 302 Found\n    Location: https://public.boxcloud.com/d/1/b1!YIeGz5LZnD3LgCNn1HqoEC8Z3wwOag3NruX5bLV_WvuiRA-wJsKRUqmcjXJBITAwm5CDA46N7KZq75j_SZNEUSijo_GLd4cMYeefLVgo7StgVgwbZtwAXpPFRRYBeoZewz-4ZZchsuLpehwLIOSKa3sdVxFohzPCAXIwUF2mlbT-SuuvsRFQxlxpPAnYvTuHJfa8gWcn6FIiWIR97xBOCAZ8uIk12LtbUJdB-K3PsGhdrnRsHFi-E3D0oSjg0TQeBN895B83FWijqdP6nvLPrIi2s8ReRxUmRCXPpFI5OzulAsK6MUAFfGGhyFjwiyvawW120MO33gYREppWP13fPfu_Xlh0bsUmbxfhb6NmhG7BJf62fU22HQpprbU3EUfPlbMCE-EhAFsNfzEOABdYqEQRcqnaSJctfxNgQQTrVGwYLHL8hGYdFJxgCQYKNH9x6U7QXyKeNyPcmeqb0U05CKnEn4dHD_RohHvJdft_kF-_2y_mErYmolMrFP30i84A42Z82PttWsZOXazC-Pzp6YibzC15oJt6INbMUcd4_B77GFJ4m_0gSs3aAOa5UaaJluqNV0k2BOAh8UkV6IhrT8abCemnIAzbbMPVGeHNv5nok4kZ8wnqVhxsgbpSVH3zbZ8hC6QsI0oTsgXxcgNKgJ9mFiNtU_oIeJhpkxwU4hX-iEfS6RUrKcGMwDeeo9vz6_5obubppTjqU9A_JWlNEzSZSWNfORmGvgXSBARjEUstgwPy8UuRozwUkZA1CYR531xA5XYiIkbZlFKcu7rQgx2SQRxdL0FKtbkVih7I_QeBZ2qArE22J42j8TPX0s25IiE2FyWbRJb0UQy7WFwTWecve3kKK_m8aEj_hHPooicUMdmQcpttKI0kO4J5vnRC3732KdGkfvKd5K4zlPnHvNoRr5AIhF6AXV_JA0BAehtKMu3Y8v6fVqZXjdsACxHxrjRrBVTSkOirrYYydQYF2DgS4iRex4bBglXWDYFs-Et8HVz_kJk6Ui0S7C-R3DvBeEr0JGL_6mmDbiJ7BZMhMn1OMdAb3uzYZ8UOEi3JFXB4YRj29Y9psPW6ynmsLf7Fx-tkiww-V_SSmskec4ybw1VHJGnGydcFVPdhoE_lHpUN9rbZThk1WL9KHg8j51f8HkcvEFW0aXvdqkDGDHlXiEwAq2UrywjOrgEPXQJN9DO_nPZoQdfYJkuBN22Q5SWbOVtEUwcJ2_DCZCZK1YEm5VBE6hPuorackebXYTI9lmNUZqR_msFzjQ4Uh7C3U6qSejbhyKQsTnZ0VpC_0XAikX9OdyXIecej3aVqrIeG9KBtrE_8C1QKnu2QekCaIfrQyANpLM3WvC3-vvO0gojf-dsWS0rDKyVmcnlmACdfnmJagRsd9V8H7vE755JONSKQIR4NU5kX2BGi8APSzTA2i9rN73tp1Q../download [following]\n    --2020-03-22 23:47:01--  https://public.boxcloud.com/d/1/b1!YIeGz5LZnD3LgCNn1HqoEC8Z3wwOag3NruX5bLV_WvuiRA-wJsKRUqmcjXJBITAwm5CDA46N7KZq75j_SZNEUSijo_GLd4cMYeefLVgo7StgVgwbZtwAXpPFRRYBeoZewz-4ZZchsuLpehwLIOSKa3sdVxFohzPCAXIwUF2mlbT-SuuvsRFQxlxpPAnYvTuHJfa8gWcn6FIiWIR97xBOCAZ8uIk12LtbUJdB-K3PsGhdrnRsHFi-E3D0oSjg0TQeBN895B83FWijqdP6nvLPrIi2s8ReRxUmRCXPpFI5OzulAsK6MUAFfGGhyFjwiyvawW120MO33gYREppWP13fPfu_Xlh0bsUmbxfhb6NmhG7BJf62fU22HQpprbU3EUfPlbMCE-EhAFsNfzEOABdYqEQRcqnaSJctfxNgQQTrVGwYLHL8hGYdFJxgCQYKNH9x6U7QXyKeNyPcmeqb0U05CKnEn4dHD_RohHvJdft_kF-_2y_mErYmolMrFP30i84A42Z82PttWsZOXazC-Pzp6YibzC15oJt6INbMUcd4_B77GFJ4m_0gSs3aAOa5UaaJluqNV0k2BOAh8UkV6IhrT8abCemnIAzbbMPVGeHNv5nok4kZ8wnqVhxsgbpSVH3zbZ8hC6QsI0oTsgXxcgNKgJ9mFiNtU_oIeJhpkxwU4hX-iEfS6RUrKcGMwDeeo9vz6_5obubppTjqU9A_JWlNEzSZSWNfORmGvgXSBARjEUstgwPy8UuRozwUkZA1CYR531xA5XYiIkbZlFKcu7rQgx2SQRxdL0FKtbkVih7I_QeBZ2qArE22J42j8TPX0s25IiE2FyWbRJb0UQy7WFwTWecve3kKK_m8aEj_hHPooicUMdmQcpttKI0kO4J5vnRC3732KdGkfvKd5K4zlPnHvNoRr5AIhF6AXV_JA0BAehtKMu3Y8v6fVqZXjdsACxHxrjRrBVTSkOirrYYydQYF2DgS4iRex4bBglXWDYFs-Et8HVz_kJk6Ui0S7C-R3DvBeEr0JGL_6mmDbiJ7BZMhMn1OMdAb3uzYZ8UOEi3JFXB4YRj29Y9psPW6ynmsLf7Fx-tkiww-V_SSmskec4ybw1VHJGnGydcFVPdhoE_lHpUN9rbZThk1WL9KHg8j51f8HkcvEFW0aXvdqkDGDHlXiEwAq2UrywjOrgEPXQJN9DO_nPZoQdfYJkuBN22Q5SWbOVtEUwcJ2_DCZCZK1YEm5VBE6hPuorackebXYTI9lmNUZqR_msFzjQ4Uh7C3U6qSejbhyKQsTnZ0VpC_0XAikX9OdyXIecej3aVqrIeG9KBtrE_8C1QKnu2QekCaIfrQyANpLM3WvC3-vvO0gojf-dsWS0rDKyVmcnlmACdfnmJagRsd9V8H7vE755JONSKQIR4NU5kX2BGi8APSzTA2i9rN73tp1Q../download\n    Resolving public.boxcloud.com (public.boxcloud.com)... 185.235.236.200\n    Connecting to public.boxcloud.com (public.boxcloud.com)|185.235.236.200|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 13403897 (13M) [application/octet-stream]\n    Saving to: \u2018personachat_all_sentences_train.jsonl\u2019\n    \n    personachat_all_sen 100%[===================>]  12.78M  7.56MB/s    in 1.7s    \n    \n    2020-03-22 23:47:04 (7.56 MB/s) - \u2018personachat_all_sentences_train.jsonl\u2019 saved [13403897/13403897]\n    \n    --2020-03-22 23:47:04--  https://nyu.box.com/shared/static/8krcizo8sms1m0ppy7uiwfcx4a3l5nsq.jsonl\n    Resolving nyu.box.com (nyu.box.com)... 185.235.236.197\n    Connecting to nyu.box.com (nyu.box.com)|185.235.236.197|:443... connected.\n    HTTP request sent, awaiting response... 301 Moved Permanently\n    Location: /public/static/8krcizo8sms1m0ppy7uiwfcx4a3l5nsq.jsonl [following]\n    --2020-03-22 23:47:05--  https://nyu.box.com/public/static/8krcizo8sms1m0ppy7uiwfcx4a3l5nsq.jsonl\n    Reusing existing connection to nyu.box.com:443.\n    HTTP request sent, awaiting response... 301 Moved Permanently\n    Location: https://nyu.app.box.com/public/static/8krcizo8sms1m0ppy7uiwfcx4a3l5nsq.jsonl [following]\n    --2020-03-22 23:47:05--  https://nyu.app.box.com/public/static/8krcizo8sms1m0ppy7uiwfcx4a3l5nsq.jsonl\n    Resolving nyu.app.box.com (nyu.app.box.com)... 185.235.236.199\n    Connecting to nyu.app.box.com (nyu.app.box.com)|185.235.236.199|:443... connected.\n    HTTP request sent, awaiting response... 302 Found\n    Location: https://public.boxcloud.com/d/1/b1!P7f2tWjqhlo7S-r0GmhNqvqLPhS8TMjKniY0i8CA8cO2WwRHWu_MD9GBqc0N9oqIiBOZoA6hd2f-_epLsWslDXUNfwlSRbhs97rRZopfuZPjfS9QMIQhq5j8BkIiAaNQV15MHpSsVubGqEokWZrX-7bOEqCb2TXf11UPompaji9ZgpDHYF3WC2FPu4MgG5YeBJAN9Or4BI2F3aAzLqnPBy80yngPHe3qah0-GelRpKI7v7F-6IG8QbQPkRAhch6T8CUt3aegjreytJK8vO3gOn0hqec-9sVaduo0q98JJX6VB_jvO6eX0Jy_nfi2jvqkPaol2xqUHtaKboHypvS5j2ix26-HG_QrCnVifeJFlnHe4_lPlKxo96hyCr6kIjiTdGN0N4aZABKnFEIarI333HKqqULDKiucdXYpPown83h2n4oMDDUZrDSsyJmAKGOAkJaJQUgsIMX8nY7Tk5BndEgCzaMSDJMW5McO5pLQOMWFOWQ5gGKLjyP-IBci8A0JgqyQX_noGfZ-s1SRt_ZIojohnaaYw1wYWcwObblSCB6QLukZlewhD__7ZhaG9Xy-ljjTjC3UHgpIOMo2FPb304noQpGl9ywYEF4uyuHbGEIfDbV6JQ__OUlsFQH7OXeTd06gRyJdTFTuRvnhjAoJEBYIP8RCfBCtoegoZaRJfqBMMDYJ7_s5jbtsRVLyZMlwaz4St4oDuYpHr1lWN9BToRqhhE7glHghs_S4s-4sl-XCjVNmiYXMQ82UfFwcPHroqsyqKr-bBDQ1VOipNeIku5d0GgnuV6fLjbk9R2Gjjzcjh13cN68m_d5iry1lsWZwIYd7Sggkz3TAn8DruogG7w8TSATWaTy4exFRN3ZFnyFKHfok_2Mx49RnZnBG1aJAY_EZBatkCj9WLoLAXWXUcFoTtRwCks8AOkPFSQKWE3YuTUPAlRckTDims_JQ0t9f_Lj-rO_-65C_HbNymtYKtdK6edYV7IdEadvM2sHksmN73LrcAbCaV884OKALNyEbBEyE0INpZgJsC0Yn9avAVytvnrGCxXev_E0tpspk0cL6TV1RQ5jqSCogv7mVsWeZ1a4Oo0nuTou3C49c845gInctU2s-RI19Cyqcry-MfbKtfohvquuBTLMRfWy1NpmjiMHAEht-zafOCuWj1ILpv8XQIdwjNAF64Xq2XMU1cfHCImn5oUodN61DHH8dMPQAiDOrKoewY__UtSX-BSaxceA439qxgpHHViLtgE3Gk2GD9S1ZLr5oiXb-oa7y7NcYM726-pnUJX5ZNinqUqOVUvN0Es3Tpe9iSOlc6lUdD8MQksvlu7G2vRAxh-KaabCbIy4_kxOlMaqfIsBg7NFoebTM_ZzVyaz0IVgbNHqN5sGMYQv6m4Df3-o2kwwd-i7MRFHlOVscJjBnvT6s2pGyONMbGGI9/download [following]\n    --2020-03-22 23:47:06--  https://public.boxcloud.com/d/1/b1!P7f2tWjqhlo7S-r0GmhNqvqLPhS8TMjKniY0i8CA8cO2WwRHWu_MD9GBqc0N9oqIiBOZoA6hd2f-_epLsWslDXUNfwlSRbhs97rRZopfuZPjfS9QMIQhq5j8BkIiAaNQV15MHpSsVubGqEokWZrX-7bOEqCb2TXf11UPompaji9ZgpDHYF3WC2FPu4MgG5YeBJAN9Or4BI2F3aAzLqnPBy80yngPHe3qah0-GelRpKI7v7F-6IG8QbQPkRAhch6T8CUt3aegjreytJK8vO3gOn0hqec-9sVaduo0q98JJX6VB_jvO6eX0Jy_nfi2jvqkPaol2xqUHtaKboHypvS5j2ix26-HG_QrCnVifeJFlnHe4_lPlKxo96hyCr6kIjiTdGN0N4aZABKnFEIarI333HKqqULDKiucdXYpPown83h2n4oMDDUZrDSsyJmAKGOAkJaJQUgsIMX8nY7Tk5BndEgCzaMSDJMW5McO5pLQOMWFOWQ5gGKLjyP-IBci8A0JgqyQX_noGfZ-s1SRt_ZIojohnaaYw1wYWcwObblSCB6QLukZlewhD__7ZhaG9Xy-ljjTjC3UHgpIOMo2FPb304noQpGl9ywYEF4uyuHbGEIfDbV6JQ__OUlsFQH7OXeTd06gRyJdTFTuRvnhjAoJEBYIP8RCfBCtoegoZaRJfqBMMDYJ7_s5jbtsRVLyZMlwaz4St4oDuYpHr1lWN9BToRqhhE7glHghs_S4s-4sl-XCjVNmiYXMQ82UfFwcPHroqsyqKr-bBDQ1VOipNeIku5d0GgnuV6fLjbk9R2Gjjzcjh13cN68m_d5iry1lsWZwIYd7Sggkz3TAn8DruogG7w8TSATWaTy4exFRN3ZFnyFKHfok_2Mx49RnZnBG1aJAY_EZBatkCj9WLoLAXWXUcFoTtRwCks8AOkPFSQKWE3YuTUPAlRckTDims_JQ0t9f_Lj-rO_-65C_HbNymtYKtdK6edYV7IdEadvM2sHksmN73LrcAbCaV884OKALNyEbBEyE0INpZgJsC0Yn9avAVytvnrGCxXev_E0tpspk0cL6TV1RQ5jqSCogv7mVsWeZ1a4Oo0nuTou3C49c845gInctU2s-RI19Cyqcry-MfbKtfohvquuBTLMRfWy1NpmjiMHAEht-zafOCuWj1ILpv8XQIdwjNAF64Xq2XMU1cfHCImn5oUodN61DHH8dMPQAiDOrKoewY__UtSX-BSaxceA439qxgpHHViLtgE3Gk2GD9S1ZLr5oiXb-oa7y7NcYM726-pnUJX5ZNinqUqOVUvN0Es3Tpe9iSOlc6lUdD8MQksvlu7G2vRAxh-KaabCbIy4_kxOlMaqfIsBg7NFoebTM_ZzVyaz0IVgbNHqN5sGMYQv6m4Df3-o2kwwd-i7MRFHlOVscJjBnvT6s2pGyONMbGGI9/download\n    Resolving public.boxcloud.com (public.boxcloud.com)... 185.235.236.200\n    Connecting to public.boxcloud.com (public.boxcloud.com)|185.235.236.200|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 1640194 (1.6M) [application/octet-stream]\n    Saving to: \u2018personachat_all_sentences_valid.jsonl\u2019\n    \n    personachat_all_sen 100%[===================>]   1.56M  2.06MB/s    in 0.8s    \n    \n    2020-03-22 23:47:13 (2.06 MB/s) - \u2018personachat_all_sentences_valid.jsonl\u2019 saved [1640194/1640194]\n    \n    --2020-03-22 23:47:13--  https://nyu.box.com/shared/static/im7we9k2gcf8kslqnfamsimicgosuw9y.jsonl\n    Resolving nyu.box.com (nyu.box.com)... 185.235.236.197\n    Connecting to nyu.box.com (nyu.box.com)|185.235.236.197|:443... connected.\n    HTTP request sent, awaiting response... 301 Moved Permanently\n    Location: /public/static/im7we9k2gcf8kslqnfamsimicgosuw9y.jsonl [following]\n    --2020-03-22 23:47:14--  https://nyu.box.com/public/static/im7we9k2gcf8kslqnfamsimicgosuw9y.jsonl\n    Reusing existing connection to nyu.box.com:443.\n    HTTP request sent, awaiting response... 301 Moved Permanently\n    Location: https://nyu.app.box.com/public/static/im7we9k2gcf8kslqnfamsimicgosuw9y.jsonl [following]\n    --2020-03-22 23:47:14--  https://nyu.app.box.com/public/static/im7we9k2gcf8kslqnfamsimicgosuw9y.jsonl\n    Resolving nyu.app.box.com (nyu.app.box.com)... 185.235.236.199\n    Connecting to nyu.app.box.com (nyu.app.box.com)|185.235.236.199|:443... connected.\n    HTTP request sent, awaiting response... 302 Found\n    Location: https://public.boxcloud.com/d/1/b1!G-57BfL6LiaVX-qmwd_xcPWOYxTJyG_g-9tAGRgwR1D3ghnIluLMiB189SCWw6x_oS45ajbKq2ON3SDnLdN_uen9tH7mGGKJiGUaTb6tYd-oCVwZR1rbo5UE60N12etNPt-RCCawzFBkxiZQqDM_7TR1mHiyESmKE9zC54OYtaD77UQX2AW5G9E8_kePMgCJHg7KQfcQKbll3rvYov_1CoYowRvbr_BlMTECx8JPcU107RB9wQrK3iiKq7gWVxKavkp8CyMfYw0D_9CmhrjMsEo4q4AmxHNsI6m_60r3UcnyIf_hDP3DSZ0iv0FhNunQnuaWPjFGwOaQVgOHQIjNSCejdIVjmuDw6Sf75t7aE4ddfI_T2EijAPPEWWMJ33EPr6jY0wsh6Gq7fZWYdpC-lPHOWMGwGWBv7Iz3k3hkLQ6wJlV_PNP1yDxixnE1IXf-TFuuEUpt9m2rcVn_mVLg_6utMYFY21_gWtZa2hJmaho74i0JdFQZsGAThtsvfiHHVqoFOdGuniBNrbYECMYj7umAzVUy8KTz8kJlb5oqfsKg88Rx3R2iw0GOWeVOGBZbnpkr1-q2lec-RjZTe6MUrIfNoSyuqayCW-x8Bg_GSElI31rBzfhVp_rV6nwyet2byUbo-vkFCY-62NS21dTXp1MszSxHpPb_XSSMtt1WougXAjOAY2QfKOpeDeQ_gk4UlUytzQ7D4h-1ir97fKeeFQcPbVVvPrPLera9tBpPKvtG04sG6LrWtAm9gGX3M7XdHu6ZZaSJqlOCQSsb9liVktcqB-69KS0IhJQ0NXj3U-EOZf-FiQ8ExyRYAYKKJzJkn3aCOJe2N8zf3-ZhAgaEIzfuw27XB0L0o-RwI4Y3oXviaeQDvt41welX7gogVAKQJFs_UsHdDJJptZjiXlQRfX5rxgMqC0GPZ8KAdjKT1RLwJKf1jx66Q7wjVYAVus7famqbq7MJbb_7U7XtqsSLzf7aw7n2cpmgoah0iRpcevkm8HdYCIvRcvE5BYuASBSm8hmNgsVxUDFoscaMqnOUQDITlRDBUIq2cKiiCvwfLRajzRJ1JQcNkVlUTiPwcGi_Zkd-W1eJI5jAE6xgNJq9JOkrYbN_tbntzS8bP3ekmo4_8WiOBEXOJD3zQI8ocXorxNIKLwvoXYYucGiaUAU3XdVR4jwIbzjUBAblRfgxS1sC010cUFoRKQkXDaC7lWBrhRzuX3BWq2Lba9QWjGi1_2UVb0vFEmt2SVvGFrbMXrE35it3HeGxfVsKj21-4Xokkryoc3jqzdMrNkVtRipa5Odq9nPRv6VjNm2fqYcrtY_Mdn0U5lzzjkmJ4_rT9VBvihLSizlBA4dP--kx3TIjqTyYjRFV2zArRNd8IqlFwy1OqHF1lPog4Q_P1FFNQ_uVKDlhCkd4m8fsSrXFlDr6I5AUTJU./download [following]\n    --2020-03-22 23:47:15--  https://public.boxcloud.com/d/1/b1!G-57BfL6LiaVX-qmwd_xcPWOYxTJyG_g-9tAGRgwR1D3ghnIluLMiB189SCWw6x_oS45ajbKq2ON3SDnLdN_uen9tH7mGGKJiGUaTb6tYd-oCVwZR1rbo5UE60N12etNPt-RCCawzFBkxiZQqDM_7TR1mHiyESmKE9zC54OYtaD77UQX2AW5G9E8_kePMgCJHg7KQfcQKbll3rvYov_1CoYowRvbr_BlMTECx8JPcU107RB9wQrK3iiKq7gWVxKavkp8CyMfYw0D_9CmhrjMsEo4q4AmxHNsI6m_60r3UcnyIf_hDP3DSZ0iv0FhNunQnuaWPjFGwOaQVgOHQIjNSCejdIVjmuDw6Sf75t7aE4ddfI_T2EijAPPEWWMJ33EPr6jY0wsh6Gq7fZWYdpC-lPHOWMGwGWBv7Iz3k3hkLQ6wJlV_PNP1yDxixnE1IXf-TFuuEUpt9m2rcVn_mVLg_6utMYFY21_gWtZa2hJmaho74i0JdFQZsGAThtsvfiHHVqoFOdGuniBNrbYECMYj7umAzVUy8KTz8kJlb5oqfsKg88Rx3R2iw0GOWeVOGBZbnpkr1-q2lec-RjZTe6MUrIfNoSyuqayCW-x8Bg_GSElI31rBzfhVp_rV6nwyet2byUbo-vkFCY-62NS21dTXp1MszSxHpPb_XSSMtt1WougXAjOAY2QfKOpeDeQ_gk4UlUytzQ7D4h-1ir97fKeeFQcPbVVvPrPLera9tBpPKvtG04sG6LrWtAm9gGX3M7XdHu6ZZaSJqlOCQSsb9liVktcqB-69KS0IhJQ0NXj3U-EOZf-FiQ8ExyRYAYKKJzJkn3aCOJe2N8zf3-ZhAgaEIzfuw27XB0L0o-RwI4Y3oXviaeQDvt41welX7gogVAKQJFs_UsHdDJJptZjiXlQRfX5rxgMqC0GPZ8KAdjKT1RLwJKf1jx66Q7wjVYAVus7famqbq7MJbb_7U7XtqsSLzf7aw7n2cpmgoah0iRpcevkm8HdYCIvRcvE5BYuASBSm8hmNgsVxUDFoscaMqnOUQDITlRDBUIq2cKiiCvwfLRajzRJ1JQcNkVlUTiPwcGi_Zkd-W1eJI5jAE6xgNJq9JOkrYbN_tbntzS8bP3ekmo4_8WiOBEXOJD3zQI8ocXorxNIKLwvoXYYucGiaUAU3XdVR4jwIbzjUBAblRfgxS1sC010cUFoRKQkXDaC7lWBrhRzuX3BWq2Lba9QWjGi1_2UVb0vFEmt2SVvGFrbMXrE35it3HeGxfVsKj21-4Xokkryoc3jqzdMrNkVtRipa5Odq9nPRv6VjNm2fqYcrtY_Mdn0U5lzzjkmJ4_rT9VBvihLSizlBA4dP--kx3TIjqTyYjRFV2zArRNd8IqlFwy1OqHF1lPog4Q_P1FFNQ_uVKDlhCkd4m8fsSrXFlDr6I5AUTJU./download\n    Resolving public.boxcloud.com (public.boxcloud.com)... 185.235.236.200\n    Connecting to public.boxcloud.com (public.boxcloud.com)|185.235.236.200|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 1559597 (1.5M) [application/octet-stream]\n    Saving to: \u2018personachat_all_sentences_test.jsonl\u2019\n    \n    personachat_all_sen 100%[===================>]   1.49M  1.88MB/s    in 0.8s    \n    \n    2020-03-22 23:47:22 (1.88 MB/s) - \u2018personachat_all_sentences_test.jsonl\u2019 saved [1559597/1559597]\n    \n    --2020-03-22 23:47:22--  https://nyu.box.com/shared/static/looczvct7ssh30x0gwqmvencple8xok9.pt\n    Resolving nyu.box.com (nyu.box.com)... 185.235.236.197\n    Connecting to nyu.box.com (nyu.box.com)|185.235.236.197|:443... connected.\n    HTTP request sent, awaiting response... 301 Moved Permanently\n    Location: /public/static/looczvct7ssh30x0gwqmvencple8xok9.pt [following]\n    --2020-03-22 23:47:23--  https://nyu.box.com/public/static/looczvct7ssh30x0gwqmvencple8xok9.pt\n    Reusing existing connection to nyu.box.com:443.\n    HTTP request sent, awaiting response... 301 Moved Permanently\n    Location: https://nyu.app.box.com/public/static/looczvct7ssh30x0gwqmvencple8xok9.pt [following]\n    --2020-03-22 23:47:23--  https://nyu.app.box.com/public/static/looczvct7ssh30x0gwqmvencple8xok9.pt\n    Resolving nyu.app.box.com (nyu.app.box.com)... 185.235.236.199\n    Connecting to nyu.app.box.com (nyu.app.box.com)|185.235.236.199|:443... connected.\n    HTTP request sent, awaiting response... 302 Found\n    Location: https://public.boxcloud.com/d/1/b1!VtbaRlDyF7vktjP1LUIcGOcNz2yDhBKTN_hjswBUfYMVYyX8S7kBxGFL2FByo9-x6ZyxELKOd1YLPYbzVCDlwZxf9c9ZmImbf4NVDfAg9LD0W5tjGk0iRowuCd6VWB_LvQv9rphgFgX92bRNEE-1sOe6Khs_VYEz_ciUJamdzLVPfzmNi3TqhlcuaPosKggQ9eOrpGpJ9Ilq0F_utKhqIkEgIhDbdxq2UslewdNdgFl-UKjpitqXduto4KxAKnP9nkSuKaJm3the1_BwaEySSIbBAlzM2Z-T5U3LE1w5Xr40t6-5ASxwpj-he-PLraXCJ6nqbJYUYJBIfXCJ9SlZSqbjx3nCmsXpLtz7ThjHE5N5tr7U32wustpw-w_dPRwbHOLcxFu0Z6h0RegOU8CdLOu70ngZV1F1OirmIUpR_e7cYb_b-JqNOku6tJbtDRYlokIteWBlvUCDPYBtfferdsqN_ZwsFBZ2ZbGhb7muBzfxyTpXm_salPbuda6m5rN66y-OkFjqVmVUEjmUN4e438xstcmXssjoOx4GZ1d4AvNiqcqgzWEJ3kFKshXp5eljuCSOXjjc5B2GZARgC_42y_mnPOdOdo10HWln3EpOHKNVwuaaDwo2E3MIsQ5pMjsTWJJKzBvul6usvVg5YZWxJaqMmyX0yFD9uyuW7-SjCD0d0d9c8BlpGAWnaxUXaKC7lpo1jGEPlbOL2UfNTwQiH9RYvwzjc7CvScXP6hDzxoK09GV_-wbezZX8YLeledA5U1vRStGsKGuNFPrb9QEjpx5Y-yRTBEJys23Ckn2TSfeTVlp2nRDowoDDUSLeXFxzAkErhSUuzt8fEUbl5DlTMNnbj-J8rwFZt6Zxe1gVdqbVuv59njsr54aw2Ebb3BElS1L1pL1vGPywYkvYzSIIp8CLWq1wBZJlyrO3O1ZVa95Rjv4f4HPTYF0d7CklGKSMjOOYRqrQH8mJla45Crg07Uy_29_ZE9zoa09RL-yriQvdlBeaQkU8woHe9mCMT7UsK6MFNoVe8c0CuBqKAnz7iUijfQyWOme8jeul3A28ckL1IZB_AzTzzsUGjlfX0-QVOszqW-d9BYmQ-cBnP8IlBoVQKLca1h76R2N7sQBhZnxtjxkApLlNzhtlFKGRBEiXj1oYvsn7WbKN0pWy60f2Vsqf9wIu_4DqFS6vqk5X97UImE98v_8XfnwxIpuZKzReYdeFh-G6HlvPN8ORKE8WMFynToPgBCPnmTHfVEHe8Ibd4G3EFP_oJ5H994wMoGE-5FFe-ow6pugyj9ZjeTcVBSAJuWp6b96xupfQDhrRL9SNhmmjUFtyGCXIrVcCVyqljgEEEq-9FgV8b28S60P9ZGe1xu_IIl77bMikswI8iCs5o2vnnpX0dFYX_F2V9M1K8vAP/download [following]\n    --2020-03-22 23:47:24--  https://public.boxcloud.com/d/1/b1!VtbaRlDyF7vktjP1LUIcGOcNz2yDhBKTN_hjswBUfYMVYyX8S7kBxGFL2FByo9-x6ZyxELKOd1YLPYbzVCDlwZxf9c9ZmImbf4NVDfAg9LD0W5tjGk0iRowuCd6VWB_LvQv9rphgFgX92bRNEE-1sOe6Khs_VYEz_ciUJamdzLVPfzmNi3TqhlcuaPosKggQ9eOrpGpJ9Ilq0F_utKhqIkEgIhDbdxq2UslewdNdgFl-UKjpitqXduto4KxAKnP9nkSuKaJm3the1_BwaEySSIbBAlzM2Z-T5U3LE1w5Xr40t6-5ASxwpj-he-PLraXCJ6nqbJYUYJBIfXCJ9SlZSqbjx3nCmsXpLtz7ThjHE5N5tr7U32wustpw-w_dPRwbHOLcxFu0Z6h0RegOU8CdLOu70ngZV1F1OirmIUpR_e7cYb_b-JqNOku6tJbtDRYlokIteWBlvUCDPYBtfferdsqN_ZwsFBZ2ZbGhb7muBzfxyTpXm_salPbuda6m5rN66y-OkFjqVmVUEjmUN4e438xstcmXssjoOx4GZ1d4AvNiqcqgzWEJ3kFKshXp5eljuCSOXjjc5B2GZARgC_42y_mnPOdOdo10HWln3EpOHKNVwuaaDwo2E3MIsQ5pMjsTWJJKzBvul6usvVg5YZWxJaqMmyX0yFD9uyuW7-SjCD0d0d9c8BlpGAWnaxUXaKC7lpo1jGEPlbOL2UfNTwQiH9RYvwzjc7CvScXP6hDzxoK09GV_-wbezZX8YLeledA5U1vRStGsKGuNFPrb9QEjpx5Y-yRTBEJys23Ckn2TSfeTVlp2nRDowoDDUSLeXFxzAkErhSUuzt8fEUbl5DlTMNnbj-J8rwFZt6Zxe1gVdqbVuv59njsr54aw2Ebb3BElS1L1pL1vGPywYkvYzSIIp8CLWq1wBZJlyrO3O1ZVa95Rjv4f4HPTYF0d7CklGKSMjOOYRqrQH8mJla45Crg07Uy_29_ZE9zoa09RL-yriQvdlBeaQkU8woHe9mCMT7UsK6MFNoVe8c0CuBqKAnz7iUijfQyWOme8jeul3A28ckL1IZB_AzTzzsUGjlfX0-QVOszqW-d9BYmQ-cBnP8IlBoVQKLca1h76R2N7sQBhZnxtjxkApLlNzhtlFKGRBEiXj1oYvsn7WbKN0pWy60f2Vsqf9wIu_4DqFS6vqk5X97UImE98v_8XfnwxIpuZKzReYdeFh-G6HlvPN8ORKE8WMFynToPgBCPnmTHfVEHe8Ibd4G3EFP_oJ5H994wMoGE-5FFe-ow6pugyj9ZjeTcVBSAJuWp6b96xupfQDhrRL9SNhmmjUFtyGCXIrVcCVyqljgEEEq-9FgV8b28S60P9ZGe1xu_IIl77bMikswI8iCs5o2vnnpX0dFYX_F2V9M1K8vAP/download\n    Resolving public.boxcloud.com (public.boxcloud.com)... 185.235.236.200\n    Connecting to public.boxcloud.com (public.boxcloud.com)|185.235.236.200|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 63894321 (61M) [application/octet-stream]\n    Saving to: \u2018personachat_ffnn_lm.pt\u2019\n    \n    personachat_ffnn_lm 100%[===================>]  60.93M  8.61MB/s    in 8.8s    \n    \n    2020-03-22 23:47:35 (6.90 MB/s) - \u2018personachat_ffnn_lm.pt\u2019 saved [63894321/63894321]\n    \n    --2020-03-22 23:47:35--  https://nyu.box.com/shared/static/3jl9erctnvbefnczgmetkdil0xwpcxzb.pt\n    Resolving nyu.box.com (nyu.box.com)... 185.235.236.197\n    Connecting to nyu.box.com (nyu.box.com)|185.235.236.197|:443... connected.\n    HTTP request sent, awaiting response... 301 Moved Permanently\n    Location: /public/static/3jl9erctnvbefnczgmetkdil0xwpcxzb.pt [following]\n    --2020-03-22 23:47:35--  https://nyu.box.com/public/static/3jl9erctnvbefnczgmetkdil0xwpcxzb.pt\n    Reusing existing connection to nyu.box.com:443.\n    HTTP request sent, awaiting response... 301 Moved Permanently\n    Location: https://nyu.app.box.com/public/static/3jl9erctnvbefnczgmetkdil0xwpcxzb.pt [following]\n    --2020-03-22 23:47:36--  https://nyu.app.box.com/public/static/3jl9erctnvbefnczgmetkdil0xwpcxzb.pt\n    Resolving nyu.app.box.com (nyu.app.box.com)... 185.235.236.199\n    Connecting to nyu.app.box.com (nyu.app.box.com)|185.235.236.199|:443... connected.\n    HTTP request sent, awaiting response... 302 Found\n    Location: https://public.boxcloud.com/d/1/b1!CyLZtFf4saVvid5ZDvNRKfunVN0hx-Ls2eJmvuf44UDk5s1WCizYxz3mng51iSfOh7zdkvhl46QJxy6UtJN1MVLWlvHvVKHpZ5d4PJ51YVP1ww1NUC5KtpGeFEWKGmzOklmzzLjCvNgYuH-ArvTt3ogB_sjpfdJjBvN8WvaFnOwWUpKSYxxIg8DSgY34FYGlPbvV8-EOdsy3x3wAfKiWOpouBlj-jcMlhMUf0lSxRBSdapFhDtY8Z8miRS6IJJ2lY5zUV-hODqsf0hmgXrhvVsZJYwUH0yIc_a4lW6K18u7hLzy2qfjjdqIRirTdzm8wQIYvIQaIQGOjzqziB0-eV7hiKz7XiaiPwpGfHaCnBVp7vcA8q0ysolCCRmJorLGjozy1yhwYFWbxWllFxNnxWjxuPY5GUQlI_LIS1lw_oDEgsxVzeVtLjnDBU3G1gHNhaiDr-OicMYjDUwhZlHeUF2YgPzbVTYFMbO_vg0m5iwchS7pw9gXSwpXqLeHmrvrTx2ATkFAizX5jkokGU1hs0yLYINk3nxHJe2ftN7BONeYMjWY2nbxxCTDYXox6MHwY8aYOGQvJDJqKbCXbQNAH-uppP0LB7zw9VW7OGnLncHd_6JvhUo2akFXR9X0yGeLSRrYmYwolGk1NO1tV_cwBsVIxfOcribXbnK1fN0cz3OR3xp3Feyh49lCSQ0vM8mPMV7NtsxG4sCv8oE7WIOhqsEg9kct7S4adJ_GMXYPeKmh0z0owDYXgkVUAMIzPXiFEYKkz5zp31PjEY4QjM3PqUhrahe9KRoZsKEQzIQvS1j5EiUz2lfbUwAML4xvZv34EB7aVCMsr23cPNV0PNXpl0QK-8G57mcvH0gDPe_mQhOW9d59GxT8xd6LTK6_jINennOY_SPClvRGx2N36yFtVRR6xxjERhbtfuItYo2GvCdgQvJnFCQEIigW6_up2RjGjQor9JARHyPuBfvn7BQNEDUu2fvMXy2SucM44rL4bF9YOPjC0LlbMWt5Y9_7_khKS5sVCSDlmwmHpApgFRQtptn-TMTHYhmeicTT90w1Z_sTQUcSVqzOPIOiB30g3G58Ldvy07GB3MrXaHMRC5zYouzyigNXaCPqIw38fbqLBY2rUyFBmqktbm86pWrg1LipnFznx5cnEVU-ZGstxTK0VPADKeQ7RqjHo4npdDaN3RrmQIGu4FbK7TY8uzZsGCYaygbsItnFzSChN57x6AB0wym62lce1ivc4me2CCiBN_CigLITmQ4PtqrapVm3gqCjP1L6wr-sB9wnkY1dbxnoFONzqruuqKSpY6EBn-vqkPQE5bRoQtPPJbtS_YsSHV0AHbQaq6nD69R7K7Au1qQiEhojh5O4Fkc2pNDHnnlhlgzWT1tE3bRG9icY1-xKcC-O-iig./download [following]\n    --2020-03-22 23:47:37--  https://public.boxcloud.com/d/1/b1!CyLZtFf4saVvid5ZDvNRKfunVN0hx-Ls2eJmvuf44UDk5s1WCizYxz3mng51iSfOh7zdkvhl46QJxy6UtJN1MVLWlvHvVKHpZ5d4PJ51YVP1ww1NUC5KtpGeFEWKGmzOklmzzLjCvNgYuH-ArvTt3ogB_sjpfdJjBvN8WvaFnOwWUpKSYxxIg8DSgY34FYGlPbvV8-EOdsy3x3wAfKiWOpouBlj-jcMlhMUf0lSxRBSdapFhDtY8Z8miRS6IJJ2lY5zUV-hODqsf0hmgXrhvVsZJYwUH0yIc_a4lW6K18u7hLzy2qfjjdqIRirTdzm8wQIYvIQaIQGOjzqziB0-eV7hiKz7XiaiPwpGfHaCnBVp7vcA8q0ysolCCRmJorLGjozy1yhwYFWbxWllFxNnxWjxuPY5GUQlI_LIS1lw_oDEgsxVzeVtLjnDBU3G1gHNhaiDr-OicMYjDUwhZlHeUF2YgPzbVTYFMbO_vg0m5iwchS7pw9gXSwpXqLeHmrvrTx2ATkFAizX5jkokGU1hs0yLYINk3nxHJe2ftN7BONeYMjWY2nbxxCTDYXox6MHwY8aYOGQvJDJqKbCXbQNAH-uppP0LB7zw9VW7OGnLncHd_6JvhUo2akFXR9X0yGeLSRrYmYwolGk1NO1tV_cwBsVIxfOcribXbnK1fN0cz3OR3xp3Feyh49lCSQ0vM8mPMV7NtsxG4sCv8oE7WIOhqsEg9kct7S4adJ_GMXYPeKmh0z0owDYXgkVUAMIzPXiFEYKkz5zp31PjEY4QjM3PqUhrahe9KRoZsKEQzIQvS1j5EiUz2lfbUwAML4xvZv34EB7aVCMsr23cPNV0PNXpl0QK-8G57mcvH0gDPe_mQhOW9d59GxT8xd6LTK6_jINennOY_SPClvRGx2N36yFtVRR6xxjERhbtfuItYo2GvCdgQvJnFCQEIigW6_up2RjGjQor9JARHyPuBfvn7BQNEDUu2fvMXy2SucM44rL4bF9YOPjC0LlbMWt5Y9_7_khKS5sVCSDlmwmHpApgFRQtptn-TMTHYhmeicTT90w1Z_sTQUcSVqzOPIOiB30g3G58Ldvy07GB3MrXaHMRC5zYouzyigNXaCPqIw38fbqLBY2rUyFBmqktbm86pWrg1LipnFznx5cnEVU-ZGstxTK0VPADKeQ7RqjHo4npdDaN3RrmQIGu4FbK7TY8uzZsGCYaygbsItnFzSChN57x6AB0wym62lce1ivc4me2CCiBN_CigLITmQ4PtqrapVm3gqCjP1L6wr-sB9wnkY1dbxnoFONzqruuqKSpY6EBn-vqkPQE5bRoQtPPJbtS_YsSHV0AHbQaq6nD69R7K7Au1qQiEhojh5O4Fkc2pNDHnnlhlgzWT1tE3bRG9icY1-xKcC-O-iig./download\n    Resolving public.boxcloud.com (public.boxcloud.com)... 185.235.236.200\n    Connecting to public.boxcloud.com (public.boxcloud.com)|185.235.236.200|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 67576905 (64M) [application/octet-stream]\n    Saving to: \u2018personachat_rnn_lm.pt\u2019\n    \n    personachat_rnn_lm. 100%[===================>]  64.45M  10.8MB/s    in 17s     \n    \n    2020-03-22 23:47:55 (3.69 MB/s) - \u2018personachat_rnn_lm.pt\u2019 saved [67576905/67576905]\n    \n\n\n## N-gram modeling as classification\n\nIn the previous n-gram language models lab, the probability of a word given a history ('prefix') was computed using n-gram **counts**.\n\nIn this lab, our goal will be the same: modeling the probability of variable length sequences, $$p(x_1,\\ldots,x_T)=\\prod_{t=1}^T p(x_t|x_{<t}),$$\n\nby assuming that each word $x_t$ only depends on the preceding $n-1$ words, $$p(x_1,\\ldots,x_T)=\\prod_{t=1}^T p(x_t|x_{t-n+1},\\ldots,x_{t-1}).$$\n\n\nHowever, _instead of counts_, we will now use a **neural network** to **classify** each history, where each class is the next word.\n\n\n\n[Diagram: modified from the [NLP Lecture Note](https://github.com/nyu-dl/NLP_DL_Lecture_Note/blob/master/lecture_note.pdf) by Kyunghyun Cho]\n\n## Modeling chat utterances\n\nWe will build a **feed-forward neural n-gram model** to model chat utterances.\n\n### 1. Prepare the data\n\nTo load and preprocess the data, we'll use utility functions from `data.py`.\n\n\n```python\nimport data as data_utils\n```\n\n\n```python\ndatasets = data_utils.load_personachat('./')\ndictionary = data_utils.Dictionary(datasets, include_valid=True)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 133176/133176 [00:17<00:00, 7738.66it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 16181/16181 [00:03<00:00, 4905.39it/s]\n\n\nLet's look at an example from the dataset (note that in addition to `train` we also have `valid`, `test` splits):\n\n\n```python\nindex = 0\nsplit = 'train'\nencoded = dictionary.encode_token_seq(datasets[split][index])\ndecoded = dictionary.decode_idx_seq(encoded)\n\nprint(\"Dataset size %d (train), %d (valid), %d (test).\\n\" %\n     (len(datasets['train']), \n      len(datasets['valid']), \n      len(datasets['test'])))\nprint(' '.join(datasets[split][index]))\nprint(f'\\n word indices - {encoded}')\nprint(f'\\n words - {decoded}')\n```\n\n    Dataset size 133176 (train), 16181 (valid), 15608 (test).\n    \n    i am doing great except for the allergies .\n    \n     word indices - [4, 5, 6, 7, 8, 9, 10, 11, 12]\n    \n     words - ['i', 'am', 'doing', 'great', 'except', 'for', 'the', 'allergies', '.']\n\n\nNow we add `<bos>`, `<eos>`, and turn each **sequence** into **n-grams**:\n\n\n```python\nngram_order = 5\ntokenized_datasets = data_utils.tokenize_dataset(\n    datasets, dictionary, ngram_order\n)\nngram_datasets = data_utils.slice_into_ngrams(\n    tokenized_datasets, ngram_order\n)\n\nfor i in range(10):\n    decoded = dictionary.decode_idx_seq(ngram_datasets[split][index+i])\n    print(f'\\n {i} - {decoded}')\n```\n\n    \n     0 - ['<bos>', '<bos>', '<bos>', '<bos>', 'i']\n    \n     1 - ['<bos>', '<bos>', '<bos>', 'i', 'am']\n    \n     2 - ['<bos>', '<bos>', 'i', 'am', 'doing']\n    \n     3 - ['<bos>', 'i', 'am', 'doing', 'great']\n    \n     4 - ['i', 'am', 'doing', 'great', 'except']\n    \n     5 - ['am', 'doing', 'great', 'except', 'for']\n    \n     6 - ['doing', 'great', 'except', 'for', 'the']\n    \n     7 - ['great', 'except', 'for', 'the', 'allergies']\n    \n     8 - ['except', 'for', 'the', 'allergies', '.']\n    \n     9 - ['for', 'the', 'allergies', '.', '<eos>']\n\n\n\n```python\ndecoded\n```\n\n\n\n\n    ['for', 'the', 'allergies', '.', '<eos>']\n\n\n\nFinally, we create a **Pytorch** `Dataset` and `DataLoader` that can be used for training a neural network.\n\n\n```python\nfrom torch.utils.data import DataLoader\n\ndatasets = {}\ndataloaders = {}\nfor split, dataset in ngram_datasets.items():\n    dataset_ = data_utils.NgramDataset(dataset)\n    datasets[split] = dataset_\n    dataloaders[split] = DataLoader(\n        dataset_, \n        batch_size=2048, \n        shuffle=(split == 'train'), \n        collate_fn=data_utils.batchify\n    )\n```\n\n### 2. Defining the model\n\n\n#### How do we represent the input $x_t$? \n\nEach $x_t$ is an **integer** (token id), and we transform it into a **vector** $f_{\\text{embed}}(x_t)\\in\\mathbb{R}^d$ using an `Embedding` layer.\n\nAn embedding layer serves as a differentiable look-up table. Given an integer token id, it returns a vector representation which we call an **embedding**.\n\n\n```python\nimport torch\nfrom torch.nn import Embedding\n# Embedding??\n```\n\n<div style=\"text-align:center\"><span style=\"color:red; font-family:Georgia; font-size:2em;\">#############################################################</div>\n\n\n## Embedding understanding\n\nExamples 1 :\n\n        >>> # an Embedding module containing 10 tensors of size 3\n        >>> embedding = nn.Embedding(10, 3)\n        >>> # a batch of 2 samples of 4 indices each\n        >>> input = torch.LongTensor([[1,2,4,5],[4,3,2,9]])\n        >>> embedding(input)\n        tensor([[[-0.0251, -1.6902,  0.7172],\n                 [-0.6431,  0.0748,  0.6969],\n                 [ 1.4970,  1.3448, -0.9685],\n                 [-0.3677, -2.7265, -0.1685]],\n\n                [[ 1.4970,  1.3448, -0.9685],\n                 [ 0.4362, -0.4004,  0.9400],\n                 [-0.6431,  0.0748,  0.6969],\n                 [ 0.9124, -2.3616,  1.1151]]])\n\n\n        >>> # example with padding_idx\n        >>> embedding = nn.Embedding(10, 3, padding_idx=0)\n        >>> input = torch.LongTensor([[0,2,0,5]])\n        >>> embedding(input)\n        tensor([[[ 0.0000,  0.0000,  0.0000],\n                 [ 0.1535, -2.0309,  0.9315],\n                 [ 0.0000,  0.0000,  0.0000],\n                 [-0.1655,  0.9897,  0.0635]]])\n        \nExample 2 :\n\n        >>> # FloatTensor containing pretrained weights\n        >>> weight = torch.FloatTensor([[1, 2.3, 3], [4, 5.1, 6.3]])\n        >>> embedding = nn.Embedding.from_pretrained(weight)\n        >>> # Get embeddings for index 1\n        >>> input = torch.LongTensor([1])\n        >>> embedding(input)\n        tensor([[ 4.0000,  5.1000,  6.3000]])\n\n\n```python\n>>> # an Embedding module containing 10 tensors of size 3 \n>>> embedding = Embedding(10, 3) # every number from 0-9 has an unique vector of size 3 as embedding\n>>> # a batch of 2 samples of 4 indices each\n>>> input = torch.LongTensor([[1,2,4,5],[4,3,2,9]])\n>>> print(embedding(input))\n>>> print(embedding(input).shape)\n```\n\n    tensor([[[ 0.2339, -1.4586,  0.9286],\n             [ 1.2614, -0.8096,  0.9579],\n             [-1.6218,  2.0938, -2.4359],\n             [ 0.2904, -0.1651,  0.4570]],\n    \n            [[-1.6218,  2.0938, -2.4359],\n             [ 1.4508,  1.4126,  1.1867],\n             [ 1.2614, -0.8096,  0.9579],\n             [ 0.3698, -0.4603, -0.0109]]], grad_fn=<EmbeddingBackward>)\n    torch.Size([2, 4, 3])\n\n\n\n```python\n>>> # example with padding_idx\n>>> embedding = Embedding(10, 3, padding_idx=0)\n>>> input = torch.LongTensor([[0,2,0,5]])\n>>> embedding(input)\n```\n\n\n\n\n    tensor([[[ 0.0000,  0.0000,  0.0000],\n             [-0.1574,  0.2488,  0.0292],\n             [ 0.0000,  0.0000,  0.0000],\n             [-1.1507,  0.2455,  0.7681]]], grad_fn=<EmbeddingBackward>)\n\n\n\n\n```python\n>>> # FloatTensor containing pretrained weights\n>>> weight = torch.FloatTensor([[1, 2.3, 3], [4, 5.1, 6.3]]) # we load our own embedding\n>>> embedding = Embedding.from_pretrained(weight)\n>>> # Get embeddings for index 1 and 0\n>>> input = torch.LongTensor([1, 0, 1])\n>>> embedding(input)\n```\n\n\n\n\n    tensor([[4.0000, 5.1000, 6.3000],\n            [1.0000, 2.3000, 3.0000],\n            [4.0000, 5.1000, 6.3000]])\n\n\n\n<div style=\"text-align:center\"><span style=\"color:red; font-family:Georgia; font-size:2em;\">#############################################################</div>\n\n\n```python\nlookup = Embedding(\n    num_embeddings=len(dictionary), \n    embedding_dim=16, \n    padding_idx=dictionary.get_id('<pad>')\n)\n```\n\n\n```python\nlookup.weight.size()\n```\n\n\n\n\n    torch.Size([20089, 16])\n\n\n\n\n```python\ninput_ = dictionary.encode_token_seq(['hello', 'world'])\nprint(f'token ids: {[input_]}')\n\ninput_embedded = lookup(torch.tensor([input_], dtype=torch.long))\nprint(f'tokens embedding size: {input_embedded.size()}')\n\nprint(f\"embedding for 'hello' ({input_[0]}):\")\nprint(input_embedded[0, 0].data)\n\nprint(f\"\\nembedding for 'world' ({input_[1]}):\")\ninput_embedded[0, 1].data\n```\n\n    token ids: [[179, 373]]\n    tokens embedding size: torch.Size([1, 2, 16])\n    embedding for 'hello' (179):\n    tensor([-0.7419, -1.8968,  1.2170,  0.1180,  2.2437, -0.6516,  0.7949, -0.9582,\n            -1.0196, -0.3526,  0.8856, -0.5736,  0.8464, -0.1362, -0.5174, -0.7914])\n    \n    embedding for 'world' (373):\n\n\n\n\n\n    tensor([-0.6392, -0.5286, -0.8954, -2.1456,  0.8496,  1.5555,  1.1416, -0.9123,\n             0.0053, -0.9957, -0.8532,  1.6187,  1.0987, -0.3596,  1.0180, -2.0651])\n\n\n\n### Defining the neural network\n\nThere are three components:\n1. `Embedding` $$\\large f_{embed}:\\text{vocab}\\rightarrow \\mathbb{R}^d$$\n2. Hidden layer $$\\large f_{hidden}: \\mathbb{R}^{nd}\\rightarrow \\mathbb{R}^h$$\n3. Projection $$\\large f_{project}: \\mathbb{R}^{h}\\rightarrow \\mathbb{R}^{|vocab|}$$\n\nThe conditional distribution is then: $$\\large p(x_t|x_{t-1},\\ldots,x_{t-n-1})=\\text{softmax}(f_{project}(f_{hidden}(f_{embed}(x_{t-1},\\ldots,x_{t-n-1}))).$$\n\n\nWe implement the hidden layer and projection with Pytorch `nn.Linear` layers:\n\n\n```python\nimport torch\nimport torch.nn as nn\n\nclass NeuralNgramLM(nn.Module):\n    def __init__(self, options):\n        super().__init__()\n        self.lookup = nn.Embedding(\n            num_embeddings=options['num_embeddings'], \n            embedding_dim=options['embedding_dim']\n        )\n        self.hidden_layer = nn.Linear(\n            options['input_size'],  # input\n            options['hidden_size'], # output \n            bias=True\n        )\n        self.projection = nn.Linear(\n            options['hidden_size'],   # input\n            options['num_embeddings'] # output\n        )\n\n    def forward(self, inp):\n        embedded = self.lookup(inp) \n        embedded_timeflat = embedded.view(embedded.size(0), -1)\n        hidden_out = self.hidden_layer(embedded_timeflat)\n        hidden_out = torch.tanh(hidden_out)\n        logits = self.projection(hidden_out)\n        return logits\n```\n\n### 3. Train the model\n\n#### Initialize the model, criterion (loss), and optimizer\n\n\n```python\nimport os\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nload_pretrained = True\n\nnum_gpus = torch.cuda.device_count()\nif num_gpus > 0:\n    current_device = 'cuda'\nelse:\n    current_device = 'cpu'\n\nif load_pretrained:\n    if not os.path.exists('personachat_ffnn_lm.pt'):\n        raise EOFError('No model downloaded!')\n    model_dict = torch.load(\n        'personachat_ffnn_lm.pt',\n        map_location=torch.device(current_device)\n    )\n    \n    options = model_dict['options']\n    model = NeuralNgramLM(options).to(current_device)\n    model.load_state_dict(\n        model_dict['model_dict']\n    )\n    \nelse:\n    embedding_size = 256\n    ngram_order = 4\n    input_size = embedding_size * ngram_order\n    hidden_size = 512\n\n    options = {\n        'num_embeddings': len(persona_dict),\n        'embedding_dim': embedding_size,\n        'input_size': input_size,\n        'hidden_size': hidden_size,\n    }\n    model = NeuralNgramLM(options).to(current_device)\n\ncriterion = nn.CrossEntropyLoss(\n    ignore_index=dictionary.get_id('<pad>'), \n    reduction='sum'\n)\n\nmodel_parameters = [p for p in model.parameters() if p.requires_grad]\noptimizer = optim.SGD(model_parameters, lr=0.01, momentum=0.99)\n```\n\n#### Training Loop\n\n\n```python\nplot_cache = []\n\nif not load_pretrained:\n    for epoch_number in range(10):\n        avg_loss = -1\n\n        # -- Training\n        model.train()\n\n        train_loss_cache = 0\n        train_non_pad_tokens_cache = 0\n\n        # == Iterate through batches from the dataset.\n        for i, (inp, target) in enumerate(dataloaders['train']):\n            optimizer.zero_grad()\n            inp = inp.to(current_device)\n            target = target.to(current_device)\n\n            # == Forward pass.\n            logits = model(inp)\n\n            # == Computed (summed) loss.\n            loss = criterion(logits.view(-1, logits.size(-1)), target.view(-1))\n            train_loss_cache += loss.item()\n\n            # == Compute the number of non `<pad>` tokens in the target.\n            non_pad_tokens = target.view(-1).ne(dictionary.get_id('<pad>')).sum().item()\n\n            # == Normalize the (summed) loss so that it is an average.\n            loss /= non_pad_tokens  \n            loss.backward()\n            optimizer.step()\n\n            train_non_pad_tokens_cache += non_pad_tokens\n            if i % 100 == 0:\n                avg_loss = train_loss_cache/train_non_pad_tokens_cache\n                print('Step {} avg train loss = {:.{prec}f}'.format(i, avg_loss, prec=4))\n\n        # -- Validation\n        valid_loss_cache = 0\n        valid_non_pad_tokens_cache = 0\n\n        model.eval()\n        with torch.no_grad():\n            non_pad_tokens = 0\n            for i, (inp, target) in enumerate(dataloaders['valid']):\n                inp = inp.to(current_device)\n                target = target.to(current_device)\n\n                # == Forward pass and loss\n                logits = model(inp)\n                loss = criterion(logits.view(-1, logits.size(-1)), target.view(-1))\n                valid_loss_cache += loss.item()            \n\n                # == Normalize the loss\n                non_pad_tokens = target.view(-1).ne(dictionary.get_id('<pad>')).sum().item()\n                valid_non_pad_tokens_cache += non_pad_tokens\n\n            avg_val_loss = valid_loss_cache / valid_non_pad_tokens_cache\n            print('Validation loss after {} epoch = {:.{prec}f}'.format(epoch_number, avg_val_loss, prec=4))\n\n        plot_cache.append((avg_loss, avg_val_loss))\n```\n\n\n```python\nif load_pretrained:\n    plot_cache = model_dict['loss_cache']\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy\n\nepochs = numpy.array(list(range(len(plot_cache))))\nplt.plot(epochs, [i[0] for i in plot_cache], label='Train loss')\nplt.plot(epochs, [i[1] for i in plot_cache], label='Valid loss')\n\nplt.legend()\nplt.title('Loss curves')\nplt.show()\n```\n\n### 4. Evaluate the model\n\n#### Recap: Perplexity\nRecall **perplexity** from the preceding lab:\n\n\\begin{align}\n\\large \\text{ppl}(p, D) &\\large = 2^{-\\frac{1}{N_{total}}\\log_2 p(D)}\n\\end{align}\n\nwhere $D=\\{(w_1,\\ldots,w_{N_i})_i\\}_{i=1}^M$ is a dataset of $M$ sequences with total length $N_{\\text{total}}=\\sum_{i}N_i$.\n\n#### Computing perplexity\n\nOur model's loss is the (negative) log probability of every token in the output sequence, which can be used to compute perplexity.\n\nWe define perplexity using the **base 2** logarithm. By default `torch.log` uses base `e`. \n\nTo **convert to base 2** we use: `log_2 p = log_e p / log_e 2`.\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy\n\nepochs = numpy.array(list(range(len(plot_cache))))\nplt.plot(epochs, [2**(i[0]/numpy.log(2)) for i in plot_cache], label='Train ppl')\nplt.plot(epochs, [2**(i[1]/numpy.log(2)) for i in plot_cache], label='Valid ppl')\n\nplt.legend()\nplt.title('PPL curves')\nplt.show()\n```\n\n\n```python\n# Saving the model\nif False:\n    torch.save({\n        'options': options,\n        'loss_cache': plot_cache,\n        'model_dict': model.state_dict()\n    }, './persona_ffnn_lm.pt')\n```\n\n#### Conditional probability queries\nWe can now query the model for conditional probabilities:\n\n\\begin{align}\n\\large p(x_t|x_{t-1},\\ldots,x_{t-4}) \n\\end{align} \n\n\n```python\nimport torch\n\ndef next_token_probabilities(prefix, token):\n    inp = dictionary.encode_token_seq(prefix.split(' '))\n    with torch.no_grad():\n        model.eval()\n        logits = model(\n            torch.tensor([inp], dtype=torch.long).to(current_device)\n        )\n    token_id = dictionary.get_id(token)\n    p_next_token = torch.softmax(logits, dim=-1)\n    return p_next_token[0, token_id]\n\nprefix = '<bos> i have a'\n\nfor w in ['dog', 'zebra', 'donut', 'velociraptor']:\n    prob = next_token_probabilities(prefix, w)\n    print('p( %s  | %s )\\t= %.3E' % (w, prefix, prob))\n    \n```\n\n    p( dog  | <bos> i have a )\t= 7.468E-02\n    p( zebra  | <bos> i have a )\t= 1.473E-04\n    p( donut  | <bos> i have a )\t= 7.881E-06\n    p( velociraptor  | <bos> i have a )\t= 1.323E-06\n\n\n\n\nAnd sort by the highest probability next-tokens:\n\n$\\large \\texttt{sort}(p(\\cdot|\\underbrace{x_{<t}}_{\\text{prefix}}))$\n\n\n```python\ndef get_top_token_given_prefix(prefix, top=10):\n    inp = dictionary.encode_token_seq(prefix.split(' '))\n    with torch.no_grad():\n        model.eval()\n        logits = model(\n            torch.tensor([inp], dtype=torch.long).to(current_device)\n        )\n        \n    p_next_token = torch.softmax(logits, dim=-1)\n    sorted_probs, sorted_token_ids = torch.topk(p_next_token[0], top)\n\n    for i in range(sorted_token_ids.size(0)):\n        print('p( %s  | %s )\\t= %.5f' % \n              (dictionary.decode_idx_seq([sorted_token_ids[i]])[0], \n               prefix, \n               sorted_probs[i])\n        )\n\nget_top_token_given_prefix('<bos> i have a')  # '<bos> the weather is'  '<bos> <bos> <bos> hello'\n```\n\n    p( dog  | <bos> i have a )\t= 0.07468\n    p( cat  | <bos> i have a )\t= 0.04418\n    p( lot  | <bos> i have a )\t= 0.04310\n    p( job  | <bos> i have a )\t= 0.03759\n    p( couple  | <bos> i have a )\t= 0.03458\n    p( few  | <bos> i have a )\t= 0.02293\n    p( black  | <bos> i have a )\t= 0.01704\n    p( little  | <bos> i have a )\t= 0.01618\n    p( hard  | <bos> i have a )\t= 0.01604\n    p( very  | <bos> i have a )\t= 0.01478\n\n\n# Recurrent neural network language model\nRecall that in **language modeling**, we want to model the probability of variable length sequences, $$p(x_1,\\ldots,x_T)=\\prod_{t=1}^T p(x_t|x_{<t}).$$\n\n*Unlike n-gram models*, we will now define a model that allows a **full history** $x_{<t}$.\n\nTo do so, we will use a function called a **recurrent neural network** to compute each distribution $p(x_t|x_{<t})$:\n\\begin{align}\nh_t &= f^{\\text{RNN}}_{\\theta}(x_{t-1}, h_{t-1}) & \\mathbb{R}^d\\\\\ns_t &= Wh_t & \\mathbb{R}^{\\text{|vocab|}}\\\\\np_{\\theta}(x_t|x_{<t}) &= \\text{softmax}(s_t) & [0,1]^{\\text{|vocab|}}\n\\end{align}\n\nwhere $h_t$ is an internal (hidden) state of the model at time step $t$, and $x_t$ is an input at time step $t$.\n\n\n\n\nIn the simplest form used in practice, $f_{\\theta}^{\\text{RNN}}$ is defined as:\n $$f_{\\theta}^{\\text{RNN}}(x_{t-1}, h_{t-1}) = \\text{tanh}(a_t)\\\\ a_t = b + W \\cdot h_{t-1} + U \\cdot x_{t-1},$$\n \nbut there are other variants (e.g. [GRU](https://arxiv.org/pdf/1406.1078.pdf), [LSTM](https://www.bioinf.jku.at/publications/older/2604.pdf)).\n\nSimilar to the n-gram neural network above, the goal at time $t$ is to **predict the next token $x_t$**.\n\n### Pytorch implementation: `RNNCell`\n\n\n```python\nfrom torch.nn import RNNCell\n# RNNCell??\n```\n\n\n```python\nimport torch\nhidden_size = 16\nembedding_dim = 8\n\nrnn_cell = RNNCell(embedding_dim, hidden_size)\n```\n\n\n```python\nhidden = torch.zeros(1, hidden_size)\nprint(hidden)\nprint(hidden.size())\n```\n\n    tensor([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])\n    torch.Size([1, 16])\n\n\n\n```python\nrandom_input = torch.rand(1, embedding_dim)\nprint(random_input)\nprint(random_input.size())\n```\n\n    tensor([[0.6630, 0.1265, 0.1560, 0.5926, 0.8322, 0.5431, 0.9106, 0.5570]])\n    torch.Size([1, 8])\n\n\n\n```python\nhidden = rnn_cell(random_input, hidden)\nprint(hidden)\nprint(hidden.size())\n```\n\n    tensor([[-0.2780,  0.0610, -0.1174, -0.2919, -0.4712,  0.0316, -0.2864, -0.0774,\n             -0.4569,  0.2362,  0.1223,  0.3585, -0.0390, -0.1081,  0.4882, -0.1864]],\n           grad_fn=<TanhBackward>)\n    torch.Size([1, 16])\n\n\n### Pytorch implementation: `RNN`\n\n`RNNCell` is a building block of an RNN model. The Pytorch `RNN` model supports multi-layer networks by creating separate `RNNCell`s for every layer. \n\n`RNN` can also process a whole sequence of data by iteratively applying `RNNCell`.\n\n\n```python\nfrom torch.nn import RNNBase, RNN\n# RNNBase.__init__??\n# RNN.__init__??\n```\n\n### 1. Define the model\n\n\n```python\nimport torch.nn as nn\n\nclass RNNLanguageModel(nn.Module):\n    def __init__(self, options):\n        super().__init__()\n        \n        self.lookup = nn.Embedding(\n            num_embeddings=options['num_embeddings'], \n            embedding_dim=options['embedding_dim'], \n            padding_idx=options['padding_idx']\n        )\n        self.rnn = nn.RNN(\n            options['input_size'], \n            options['hidden_size'], \n            options['num_layers'], \n            dropout=options['rnn_dropout'], \n            batch_first=True\n        )\n        self.projection = nn.Linear(\n            options['hidden_size'], \n            options['num_embeddings']\n        )\n        \n    def forward(self, token_ids):\n        embeddings = self.lookup(token_ids)\n        output, hidden = self.rnn(embeddings)\n        logits = self.projection(output) \n        return logits\n```\n\n### 2. Prepare the data\n\n#### Dataset and Dataloader\n\nSee `data_utils.py` for the implementation. \n\n\n```python\ndatasets_ = data_utils.load_personachat('./')\ndictionary = data_utils.Dictionary(datasets_, include_valid=True)\ndatasets_ = data_utils.tokenize_dataset(datasets_, dictionary)\n\ndatasets = {}\nfor split, dataset in datasets_.items():\n    datasets[split] = data_utils.TensoredDataset(dataset, dictionary.get_id('<pad>'))\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 133176/133176 [00:18<00:00, 7382.82it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 16181/16181 [00:03<00:00, 4807.32it/s]\n\n\n- The **input** is now a **full sequence**.\n- The **output** is the **next token** for each position of the input:\n\n\n```python\ninp, out = datasets['train'][0]\n\nprint(\"Input: \\n\\t%s\\n\\t(%s)\" %\n      (inp.data[0], dictionary.decode_idx_seq(inp.data[0])))\n\nprint(\"Output: \\n\\t%s\\n\\t(%s)\" %\n      (out.data[0], dictionary.decode_idx_seq(out.data[0])))\n```\n\n    Input: \n    \ttensor([ 0,  4,  5,  6,  7,  8,  9, 10, 11, 12])\n    \t(['<bos>', 'i', 'am', 'doing', 'great', 'except', 'for', 'the', 'allergies', '.'])\n    Output: \n    \ttensor([ 4,  5,  6,  7,  8,  9, 10, 11, 12,  1])\n    \t(['i', 'am', 'doing', 'great', 'except', 'for', 'the', 'allergies', '.', '<eos>'])\n\n\n#### Pytorch dataloader\n\n\n```python\ndataloaders = {}\nbatch_size = 128\n\nfor split, dataset in datasets.items():\n    dataloaders[split] = DataLoader(\n        dataset, \n        batch_size=batch_size, \n        shuffle=True, \n        collate_fn=dataset.pad_collate_fn  # pads the sequences in the batch\n    )\n```\n\n#### Padding to handle variable sequence lengths:\n\n\n```python\ninp, target = next(dataloaders['train'].__iter__())\n\nprint(\"Batch size %s\" % str(inp.shape))\nprint(\"Batch element 1: \\n\\t%s\\n\\t(%s)\" %\n      (inp.data[0], ' '.join(dictionary.decode_idx_seq(inp.data[0]))))\nprint(\"Batch element 2: \\n\\t%s\\n\\t(%s)\" %\n      (inp.data[1], ' '.join(dictionary.decode_idx_seq(inp.data[1]))))\n```\n\n    Batch size torch.Size([128, 25])\n    Batch element 1: \n    \ttensor([ 0,  4,  5, 44, 13, 21, 12,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,\n             2,  2,  2,  2,  2,  2,  2])\n    \t(<bos> i am just a kid . <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad>)\n    Batch element 2: \n    \ttensor([   0,  625, 3468,  122, 1791,   78,    4,  113,   86, 1178,   12,    2,\n               2,    2,    2,    2,    2,    2,    2,    2,    2,    2,    2,    2,\n               2])\n    \t(<bos> everyone calls me mary and i live in colorado . <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad>)\n\n\n### 3. Train the model\n\n#### Initializing model, criterion, and optimizer (similar to the feedforward model)\n\n\n```python\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nload_pretrained = True\n\nnum_gpus = torch.cuda.device_count()\nif num_gpus > 0:\n    current_device = 'cuda'\nelse:\n    current_device = 'cpu'\n\nif load_pretrained:\n    if not os.path.exists('personachat_rnn_lm.pt'):\n        raise EOFError('Download pretrained model!')\n    model_dict = torch.load(\n        'personachat_rnn_lm.pt',\n        map_location=torch.device(current_device)\n    )\n    \n    options = model_dict['options']\n    model = RNNLanguageModel(options).to(current_device)\n    model.load_state_dict(model_dict['model_dict'])\n    \nelse:\n    embedding_size = 256\n    hidden_size = 512\n    num_layers = 3\n    rnn_dropout = 0.3\n\n    options = {\n        'num_embeddings': len(dictionary),\n        'embedding_dim': embedding_size,\n        'padding_idx': dictionary.get_id('<pad>'),\n        'input_size': embedding_size,\n        'hidden_size': hidden_size,\n        'num_layers': num_layers,\n        'rnn_dropout': rnn_dropout,\n    }\n    model = RNNLanguageModel(options).to(current_device)\n    \n\ncriterion = nn.CrossEntropyLoss(\n    ignore_index=dictionary.get_id('<pad>'), \n    reduction='sum'\n)\n\nmodel_parameters = [p for p in model.parameters() if p.requires_grad]\noptimizer = optim.SGD(model_parameters, lr=0.001, momentum=0.999)\n```\n\n\n```python\nmodel\n```\n\n\n\n\n    RNNLanguageModel(\n      (lookup): Embedding(20089, 256, padding_idx=2)\n      (rnn): RNN(256, 512, num_layers=3, batch_first=True, dropout=0.3)\n      (projection): Linear(in_features=512, out_features=20089, bias=True)\n    )\n\n\n\n#### Training loop (same as the feedforward model)\n\n\n```python\nplot_cache = []\n\nif not load_pretrained:\n    for epoch_number in range(100):\n        avg_loss = 0\n        model.train()\n\n        train_loss_cache = 0\n        train_non_pad_tokens_cache = 0\n\n        for i, (inp, target) in enumerate(persona_loaders['train']):\n            optimizer.zero_grad()\n            inp = inp.to(current_device)\n            target = target.to(current_device)\n            logits = model(inp)\n\n            loss = criterion(logits.view(-1, logits.size(-1)), target.view(-1))\n            train_loss_cache += loss.item()  # still sum here\n\n            non_pad_tokens = target.view(-1).ne(persona_dict.get_id('<pad>')).sum().item()            \n            train_non_pad_tokens_cache += non_pad_tokens\n\n            loss /= non_pad_tokens \n\n            loss.backward()\n            optimizer.step()\n\n            if i % 100 == 0:\n                avg_loss = train_loss_cache / train_non_pad_tokens_cache\n                print('Step {} avg train loss = {:.{prec}f}'.format(i, avg_loss, prec=4))\n                train_log_cache = []\n\n        valid_loss_cache = 0\n        valid_non_pad_tokens_cache = 0\n\n        model.eval()\n        with torch.no_grad():\n            for i, (inp, target) in enumerate(persona_loaders['valid']):\n                inp = inp.to(current_device)\n                target = target.to(current_device)\n                logits = model(inp)\n\n                loss = criterion(logits.view(-1, logits.size(-1)), target.view(-1))\n                valid_loss_cache += loss.item()  # still sum here\n                non_pad_tokens = target.view(-1).ne(persona_dict.get_id('<pad>')).sum().item()\n\n                valid_non_pad_tokens_cache += non_pad_tokens\n\n            avg_val_loss = valid_loss_cache / valid_non_pad_tokens_cache\n\n            print('Validation loss after {} epoch = {:.{prec}f}'.format(epoch_number, avg_val_loss, prec=4))\n\n        plot_cache.append((avg_loss, avg_val_loss))\n\n```\n\n\n```python\nif load_pretrained:\n    plot_cache = model_dict['loss_cache']\n```\n\n### 4. Evaluation\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy\n\nepochs = numpy.array(list(range(len(plot_cache))))\nplt.plot(epochs, [i[0] for i in plot_cache], label='Train loss')\nplt.plot(epochs, [i[1] for i in plot_cache], label='Valid loss')\n\nplt.legend()\nplt.title('Loss curves')\nplt.show()\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy\n\nepochs = numpy.array(list(range(len(plot_cache))))\nplt.plot(epochs, [2**(i[0]/numpy.log(2)) for i in plot_cache], label='Train ppl')\nplt.plot(epochs, [2**(i[1]/numpy.log(2)) for i in plot_cache], label='Valid ppl')\n\nplt.legend()\nplt.title('PPL curves')\nplt.show()\n```\n\n### Conditional probability queries\n\nWe can query different probabilities:\n\n$\\large p(\\underbrace{x_t}_{\\text{token}}|\\underbrace{x_{<t}}_{\\text{prefix}})$\n\n\n```python\nimport torch\n\ndef next_token_probabilities(prefix, token):\n    inp = dictionary.encode_token_seq(prefix.split(' '))\n    with torch.no_grad():\n        model.eval()\n        logits = model(\n            torch.tensor([inp], dtype=torch.long).to(current_device)\n        )\n        \n    token_id = dictionary.get_id(token)\n    p_next_token = torch.softmax(logits[0, -1], dim=-1)\n    return p_next_token[token_id]\n\nprefix = '<bos> i have a'\n\nfor w in ['dog', 'zebra', 'donut', 'velociraptor']:\n    prob = next_token_probabilities(prefix, w)\n    print('p( %s  | %s )\\t= %.3E' % (w, prefix, prob))\n    \n```\n\n    p( dog  | <bos> i have a )\t= 6.960E-02\n    p( zebra  | <bos> i have a )\t= 1.633E-04\n    p( donut  | <bos> i have a )\t= 1.039E-05\n    p( velociraptor  | <bos> i have a )\t= 2.267E-07\n\n\n\n\nAnd sort by the highest probability next-tokens:\n\n$\\large \\texttt{sort}(p(\\cdot|\\underbrace{x_{<t}}_{\\text{prefix}}))$\n\n\n```python\ndef get_top_token_given_prefix(prefix, top=10):\n    inp = dictionary.encode_token_seq(prefix.split(' '))\n    with torch.no_grad():\n        model.eval()\n        logits = model(\n            torch.tensor([inp], dtype=torch.long).to(current_device)\n        )\n        \n    p_next_token = torch.softmax(logits[0, -1], dim=-1)\n    sorted_probs, sorted_token_ids = torch.topk(p_next_token, top)\n\n    for i in range(sorted_token_ids.size(0)):\n        print('p( %s  | %s )\\t= %.5f' % \n              (dictionary.decode_idx_seq([sorted_token_ids[i]])[0], \n               prefix, \n               sorted_probs[i])\n        )\n\nget_top_token_given_prefix('<bos> the weather is')\n```\n\n    p( great  | <bos> the weather is )\t= 0.09953\n    p( nice  | <bos> the weather is )\t= 0.07859\n    p( beautiful  | <bos> the weather is )\t= 0.06185\n    p( fun  | <bos> the weather is )\t= 0.05039\n    p( good  | <bos> the weather is )\t= 0.04573\n    p( awesome  | <bos> the weather is )\t= 0.04308\n    p( cool  | <bos> the weather is )\t= 0.04212\n    p( my  | <bos> the weather is )\t= 0.03604\n    p( a  | <bos> the weather is )\t= 0.02892\n    p( so  | <bos> the weather is )\t= 0.02230\n\n\n### Generation (Sampling)\n\nFinally, we can generate sentences using the model's conditional distribution:\n\n            context = [<bos>]\n            until <eos> is generated:\n                wt ~ p(wt | context)\n                context += [wt]\n                \n                \nHere, the `~` symbol stands for sampling from a categorical distribution. \n\n\n```python\nimport torch\n\ndef sample(model, prefix, num_samples, temperature=1.0, max_len=50):\n    inp = torch.tensor([\n        dictionary.encode_token_seq(prefix.split(' '))\n    ], dtype=torch.long).to(current_device).repeat([num_samples, 1])\n\n    sampled = [prefix.split(' ') for _ in range(num_samples)]\n    done = torch.tensor([False for _ in range(num_samples)])\n    hidden = None\n    \n    with torch.no_grad():\n        model.eval()\n        for t in range(max_len):\n            logits, hidden = step(model, inp, hidden)\n            logits_ = (logits[:, -1, :] / temperature)\n            inp = logits_.softmax(-1).multinomial(1)            \n            for i in range(num_samples):\n                tok_ti = dictionary.get_token(inp[i, 0].item())\n                if tok_ti == '<eos>' and not done[i]:\n                    done[i] = True\n                    sampled[i].append(tok_ti)\n                elif not done[i]:\n                    sampled[i].append(tok_ti)\n                else:\n                    pass\n            if done.sum() == num_samples:\n                break\n        \n    return sampled\n\ndef step(rnn, token_ids, hidden):\n    embeddings = rnn.lookup(token_ids)\n    output, hidden = rnn.rnn(embeddings, hidden)\n    logits = rnn.projection(output) \n    return logits, hidden\n\n\nprefix = '<bos> i have a'\n\nfor temp in [1.0, 0.5, 0.1]:\n    print(\"Temperature %.2f\" % temp)\n    samples = sample(model, prefix, 5, temperature=temp)\n    for s in samples:\n        print(' '.join(s))\n    print()\n```\n\n    Temperature 1.00\n    <bos> i have a cat named toto named after mah . <eos>\n    <bos> i have a book named killswitch and trump my bf . are you married ? <eos>\n    <bos> i have a huge belt play with globe tea listening to music . <eos>\n    <bos> i have a lot of jokes to share . any hobbies ? <eos>\n    <bos> i have a moped . <eos>\n    \n    Temperature 0.50\n    <bos> i have a dog named toto . <eos>\n    <bos> i have a lot of friends . <eos>\n    <bos> i have a cat named cow . <eos>\n    <bos> i have a dog . <eos>\n    <bos> i have a lot of friends . <eos>\n    \n    Temperature 0.10\n    <bos> i have a cat named cow . <eos>\n    <bos> i have a cat named cow . <eos>\n    <bos> i have a cat named cow . <eos>\n    <bos> i have a cat named cow . <eos>\n    <bos> i have a dog named toto . <eos>\n    \n\n\n\n```python\n# Saving the model\nif False:\n    torch.save({\n        'options': options,\n        'loss_cache': plot_cache,\n        'model_dict': model.state_dict()\n    }, './static_files/persona_rnn_lm.pt')\n```\n\n## Large-scale Language Modeling: GPT-2\n\nThe language model above is relatively small in terms of the number of parameters, and is trained on a (very) small dataset.\n\nRecently, researchers have trained **large-scale language models** on **large amounts of data**, resulting in improved language modeling and generation ability. \n\nA representative example is **GPT-2** [[paper](https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf)], [[blog](https://openai.com/blog/better-language-models/)]. We won't currently discuss the details of this model, but we can easily **use a pre-trained version to generate text**:\n\n\n```python\n!pip install transformers\n```\n\n    Requirement already satisfied: transformers in /opt/anaconda3/lib/python3.7/site-packages (2.5.1)\n    Requirement already satisfied: requests in /opt/anaconda3/lib/python3.7/site-packages (from transformers) (2.22.0)\n    Requirement already satisfied: filelock in /opt/anaconda3/lib/python3.7/site-packages (from transformers) (3.0.12)\n    Requirement already satisfied: tokenizers==0.5.2 in /opt/anaconda3/lib/python3.7/site-packages (from transformers) (0.5.2)\n    Requirement already satisfied: boto3 in /opt/anaconda3/lib/python3.7/site-packages/boto3-1.9.246-py3.7.egg (from transformers) (1.9.246)\n    Requirement already satisfied: tqdm>=4.27 in /opt/anaconda3/lib/python3.7/site-packages (from transformers) (4.42.0)\n    Requirement already satisfied: numpy in /opt/anaconda3/lib/python3.7/site-packages (from transformers) (1.18.1)\n    Requirement already satisfied: regex!=2019.12.17 in /opt/anaconda3/lib/python3.7/site-packages (from transformers) (2019.8.19)\n    Requirement already satisfied: sentencepiece in /opt/anaconda3/lib/python3.7/site-packages (from transformers) (0.1.85)\n    Requirement already satisfied: sacremoses in /opt/anaconda3/lib/python3.7/site-packages (from transformers) (0.0.38)\n    Requirement already satisfied: idna<2.9,>=2.5 in /opt/anaconda3/lib/python3.7/site-packages (from requests->transformers) (2.8)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/anaconda3/lib/python3.7/site-packages (from requests->transformers) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /opt/anaconda3/lib/python3.7/site-packages (from requests->transformers) (2019.11.28)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/anaconda3/lib/python3.7/site-packages (from requests->transformers) (1.24.2)\n    Requirement already satisfied: botocore<1.13.0,>=1.12.246 in /opt/anaconda3/lib/python3.7/site-packages/botocore-1.12.246-py3.7.egg (from boto3->transformers) (1.12.246)\n    Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in /opt/anaconda3/lib/python3.7/site-packages/jmespath-0.9.5-py3.7.egg (from boto3->transformers) (0.9.5)\n    Requirement already satisfied: s3transfer<0.3.0,>=0.2.0 in /opt/anaconda3/lib/python3.7/site-packages/s3transfer-0.2.1-py3.7.egg (from boto3->transformers) (0.2.1)\n    Requirement already satisfied: joblib in /opt/anaconda3/lib/python3.7/site-packages (from sacremoses->transformers) (0.14.1)\n    Requirement already satisfied: six in /opt/anaconda3/lib/python3.7/site-packages (from sacremoses->transformers) (1.12.0)\n    Requirement already satisfied: click in /opt/anaconda3/lib/python3.7/site-packages (from sacremoses->transformers) (7.0)\n    Requirement already satisfied: docutils<0.16,>=0.10 in /opt/anaconda3/lib/python3.7/site-packages (from botocore<1.13.0,>=1.12.246->boto3->transformers) (0.15.2)\n    Requirement already satisfied: python-dateutil<3.0.0,>=2.1 in /opt/anaconda3/lib/python3.7/site-packages (from botocore<1.13.0,>=1.12.246->boto3->transformers) (2.8.1)\n\n\n#### Load the model and tokenizer\n\n\n```python\nimport torch\nfrom transformers import (\n    GPT2LMHeadModel,\n    GPT2Tokenizer\n)\n\ndevice = torch.device('cpu') if not torch.cuda.is_available() else torch.device('cuda:0')\n\ntokenizer = GPT2Tokenizer.from_pretrained(\"gpt2\")\nmodel = GPT2LMHeadModel.from_pretrained(\"gpt2\")\nmodel.to(device);\n```\n\n\n    HBox(children=(FloatProgress(value=0.0, description='Downloading', max=1042301.0, style=ProgressStyle(descript\u2026\n\n\n    \n\n\n\n    HBox(children=(FloatProgress(value=0.0, description='Downloading', max=456318.0, style=ProgressStyle(descripti\u2026\n\n\n    \n\n\n\n    HBox(children=(FloatProgress(value=0.0, description='Downloading', max=224.0, style=ProgressStyle(description_\u2026\n\n\n    \n\n\n\n    HBox(children=(FloatProgress(value=0.0, description='Downloading', max=548118077.0, style=ProgressStyle(descri\u2026\n\n\n    \n\n\n#### Generate (Sampling)\n\nWe'll talk about other ways to generate later in the course.\n\n\n```python\nprefix = 'My favorite food is'\n\nmax_length = 100\nnum_samples = 5\n\ninp = torch.tensor([tokenizer.encode(prefix)], device=device).repeat(num_samples, 1)\n\nout = model.generate(\n    input_ids=inp,\n    do_sample=True,\n    max_length=max_length\n)\n\nfor i in range(num_samples):\n    sample = tokenizer.decode(out[i])\n    print(sample)\n    print('---------------------------------------------------')\n```\n\n    My favorite food is not pizza\u2026it is your meal!\"\n    \n    \"Wanna try me out? I should really start by asking for a discount. It's awesome!\"\n    \n    \"I'm here today with my buddy John to talk about this great recipe for Pizza Noodles.\"\n    \n    Thank you so much for stopping by! We wanted to introduce you to John for lunch and dinner.\n    \n    I like pizza. I've never had pizza in my life. The reason I have a\n    ---------------------------------------------------\n    My favorite food is the prawns from the island of Tanga. It's very cheap and easy to get for the price of one and then again for the rice with the traditional pork chop and chicken prawns. And they also tend to be great with pork or pork ribs if you can find them locally, that's very special.\n    \n    But how do you buy any special vegetables in Tonga?\n    \n    The pinyon sauce in Tonga is made with a bamboo straw and\n    ---------------------------------------------------\n    My favorite food is probably The Bistro, which is packed with the best, most savory food I've ever had. I love their sandwiches or the ones on the menu, especially if they're gluten free, they're filled with tasty things like tofu that you can use as sauce, you can use as bread, and I love the fact they provide you with something to spend more time with. The best thing about this place are the prices to pick up from: you can pay less than\n    ---------------------------------------------------\n    My favorite food is my family's favorite. It's so good!\n    \n    When it is easy to find some, it actually makes the whole family more fun. Our family goes to the park at Christmas time every day. I have our favorite food, it isn't as bad as the other foods but it is much more salty.\n    \n    We love this shop for all the wonderful things you can find there, including \"Pizza\". I haven't experienced anything that you might not know about it\n    ---------------------------------------------------\n    My favorite food is rice, and it tastes like rice. I use so many to make my dishes (they take a lot of time and work well), and I use lots more rice than I did last week on the restaurant's food roll. The menu has different flavors like chicken casserole, pasta, and seafood. The salad gets really spicy, and the bread is always greasy and greasy. I love its comfort food, and it doesn't bite.\n    \n    \n    If you think you\n    ---------------------------------------------------\n\n", "meta": {"hexsha": "7190e4713db8f1f176eb8bebd8d0e5a9e0847b1e", "size": 161375, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Part 02/001_LM/ff_rnn_lm_lab/ff_rnnlms.ipynb", "max_stars_repo_name": "Kabongosalomon/AMMI-NLP", "max_stars_repo_head_hexsha": "00a0e47399926ad1951b84a11cd936598a9c7c3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-20T15:04:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-20T16:39:37.000Z", "max_issues_repo_path": "Part 02/001_LM/ff_rnn_lm_lab/ff_rnnlms.ipynb", "max_issues_repo_name": "Kabongosalomon/AMMI-NLP", "max_issues_repo_head_hexsha": "00a0e47399926ad1951b84a11cd936598a9c7c3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Part 02/001_LM/ff_rnn_lm_lab/ff_rnnlms.ipynb", "max_forks_repo_name": "Kabongosalomon/AMMI-NLP", "max_forks_repo_head_hexsha": "00a0e47399926ad1951b84a11cd936598a9c7c3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 68.2924248836, "max_line_length": 18124, "alphanum_fraction": 0.7562757552, "converted": true, "num_tokens": 25331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.07585818315512395, "lm_q1q2_score": 0.035266588550347436}}
{"text": "# Please download the new class notes.\n### Step 1 : Navigate to the directory where your files are stored.  \nOpen a terminal. \n\nUsing `cd`, navigate to *inside* the ILAS_Python_for_everyone folder on your computer. \n\n### Step 3 : Update the course notes by downloading the changes\nIn the terminal type:\n\n>`git add -A`\n\n>`git commit -m \"commit\"`\n\n>`git fetch upstream`\n\n>`git merge -X theirs upstream/master`\n\n\n# Introduction to Data Structures and Imported Libraries (Pygame)\n\n<br> <a href='#DataStructures'>Data Structures</a>\n<br> <a href='#Lists'>Lists</a> \n\t<br> &emsp;&emsp; <a href='#Indexing'>__Indexing__</a> \n    <br> &emsp;&emsp; <a href='#MutipleUserInputs'>Multiple User Inputs</a> \n\t<br> &emsp;&emsp; <a href='#ManipulatingLists'>Manipulating Lists</a> \n\t<br> &emsp;&emsp; &emsp;&emsp; <a href='#FindingLengthList'>FindingLengthList</a> \n    <br> &emsp;&emsp; &emsp;&emsp; <a href='#SortingLists'>SortingLists</a> \n    <br> &emsp;&emsp; &emsp;&emsp; <a href='#RemovingItemList'>Removing an Item from a List</a> \n    <br> &emsp;&emsp; &emsp;&emsp; <a href='#AddingItemList'>Adding an Item to a List</a> \n    <br> &emsp;&emsp; &emsp;&emsp; <a href='#ChangingListEntry'>Changing a List Entry</a> \n\t<br> &emsp;&emsp; <a href='#NestedDataStructures'>__Nested Data Structures__</a> \n\t<br> &emsp;&emsp; <a href='#IteratingLists'>__Iterating over Lists__</a> \n    <br> &emsp;&emsp; <a href='#IndexingIterating'>__Indexing when Iterating over Lists__</a> \n\t<br> &emsp;&emsp; <a href='#enumerate'>`enumerate`</a> \n    <br> &emsp;&emsp; <a href='#zip'>__`zip`__</a> \n\t<br> &emsp;&emsp; <a href='#ExampleChangingPosition'>__Example: Changing Position__ </a> \n<br> <a href='#Libraries'>Libraries</a> \n    <br> &emsp;&emsp; <a href='#StandardLibrary'>__The Standard Library__</a> \n\t<br> &emsp;&emsp; <a href='#Packages'>__Packages__ </a> \n        <br> &emsp;&emsp; &emsp;&emsp; <a href='#ImportingPackage'>__Importing a Package__</a> \n        <br> &emsp;&emsp; &emsp;&emsp; <a href='#PackageFunctions'>__Using Package Functions__</a> \n        <br> &emsp;&emsp; &emsp;&emsp; <a href='#ReadingFunctionDocumentation'>__Reading Function Documentation__</a> \n        <br> &emsp;&emsp; &emsp;&emsp; <a href='#Examplemathpow'>__Example: `math.pow`__</a> \n        <br> &emsp;&emsp; &emsp;&emsp; <a href='#Namespaces'>Namespaces</a> \n        <br> &emsp;&emsp; &emsp;&emsp; <a href='#ImportingFunction'>__Importing a Function__</a> \n    <br> &emsp;&emsp; <a href='#Optimise'>__Using Package Functions to Optimise your Code__</a> \n     <br> &emsp;&emsp; <a href='#DataStructuresFunctionArguments'>__Data Structures as Function Arguments__</a> \n<br> <a href='#StackingFunctions'>__Stacking Functions__</a>\n<br> <a href='#StackingFunctions'>__Installing Pygame__</a>\n<br> <a href='#Summary'>Summary</a> \n<br> <a href='#Test-YourselfExercises'>Test-Yourself Exercises</a> \n<br> <a href='#ReviewExercises'>Review Exercises</a> \n\n\n\n\n\n\n<a id='Summary'></a>\n# Summary of Information Needed to Understand Today's Examples\nFor more information refer to the Primer Notebooks for this class __02ClassMaterial__DataStructures_Libraries.ipynb__\n\n\n###### Data Structures\n\n- Python has an extensive __standard library__ of built-in functions. \n- More specialised libraries of functions and constants are available. We call these __packages__. \n- Packages are imported using the keyword `import`\n- The function documentation tells is what it does and how to use it.\n- When calling a library function it must be prefixed with a __namespace__ is used to show from which package it should be called.  \n- The magic function `%timeit` can be used to time the execution of a function. \n\n\n\n###### Libraries\n- Python has an extensive __standard library__ of built-in functions. \n- More specialised libraries of functions and constants are available. We call these __packages__. \n- Packages are imported using the keyword `import`\n- The function documentation tells is what it does and how to use it.\n- When calling a library function it must be prefixed with a __namespace__ is used to show from which package it should be called.  \n- The magic function `%timeit` can be used to time the execution of a function. \n\n### Lesson Goal\n\n- Build a guessing game.\n- Build the game 0 and Xs or tic-tac-toe.\n\n<p align=\"center\">\n  \n</p>\n\n\n\n### Fundamental programming concepts\n - Importing existing code to use in your program\n - Storing and representing data e.g. a grid with 0 and X in each grid cell\n\n<a id='DataStructures'></a>\n## Data Structures\n\nIn the last seminar we learnt to generate a range of numbers for use in control flow of  a program, using the function `range()`:\n\n\n       for j in range(20):\n           ...\n    \n        \nOften we want to manipulate data that is more meaningful than ranges of numbers.\n\nThese collections of variables might include:\n - the results of an experiment\n - a list of names\n - the components of a vector\n - a telephone directory with names and associated numbers.\n    \n\nPython has different __data structures__ that can be used to store and manipulate these values.\n\nLike variable types (`string`, `int`,`float`...) different data structures behave in different ways.\n\nToday we will learn to use `list`s \n\nA list is a container with compartments in which we can store data:\n<p align=\"center\">\n  \n</p>\n\nExample\n\nIf we want to store the names of students in a laboratory group, \nrather than representing each students using an individual string variable, we could use a list of names. \n\n\n\n\n```python\nlab_group0 = [\"Yukari\", \"Sajid\", \"Hemma\", \"Ayako\"]\nlab_group1 = [\"Sara\", \"Mari\", \"Quang\", \"Sam\", \"Ryo\", \"Nao\", \"Takashi\"]\n\nprint(lab_group0)\nprint(lab_group1)\n```\n\n    ['Yukari', 'Sajid', 'Hemma', 'Ayako']\n    ['Sara', 'Mari', 'Quang', 'Sam', 'Ryo', 'Nao', 'Takashi']\n\n\nThis is useful because we can perform operations on lists such as:\n - checking its length (number of students in a lab group)\n - sorting the names in the list into alphabetical order\n - making a list of lists (we call this a *nested list*):\n\n\n\n```python\nlab_groups = [lab_group0, lab_group1]\n```\n\n<a id='ExampleChangePosition'></a>\n### Example: Change in Position: (Representing Vectors using Lists)\n\n__Vector:__ A quantity with magnitude and direction.\n\nThe position of a point in 2D space (e.g. the position of a character in a game), can be expressed in terms of horizontal (x) and vertical (y) conrdinates. \n\nThe movement to a new position can be expressed as a change in x and y. \n\nThis change is known as the velocity with which the point moves. \n\n\n\n[Daniel Schiffman, The Nature of Code]\n\n\nWe can conveniently express the position $\\mathbf{r}$ in matrix (or basis vector) form using the coefficients $x$ and  $y$: \n$$\n\\mathbf{r} = [r_x, r_y]\n$$\n\n\n__...which looks a lot like a Python list!__\n\n\nWhen we move a character in a game, we change it's position. \n<br>The change in position with each time-step is the __velocity__ of the character.\n\n$$\n\\mathbf{v} = [v_x, v_y]\n$$\n\n\n\nTo get the position at the next time step we simply add the x and y component of the veclocity to the x and y component of the initial position vector:\n\n \n \n\n\n\\begin{align}\n      {\\displaystyle {\\begin{aligned}\\ \n      \\mathbf{r}(t=t+1)\n      &=\\mathbf{r} + \\mathbf{v}\\\\\n      &=[(r_x(t)+v_x),\\;\\;   (r_y(t)+v_y)] \\\\ \\end{aligned}}} \n\\end{align}\n\n\n\nFor example, let's find the position at the next timestep where:\n - initial position,  $\\mathbf{r} = [5, 2]$\n - velocity,  $\\mathbf{v} = [3, 4]$\n \n \n \n [Daniel Schiffman, The Nature of Code]\n\n\n```python\n# Example: Change in Position\n\n```\n\n\n```python\n# Example Solution: Change in Position\n\nr = [5, 2]\nv = [3, 4]\n\nr = [r[0] + v[0], \n     r[1] + v[1]]\n\nprint(r)\n```\n\n    [8, 6]\n\n\n(Solution in 02_DataStructures_LibraryFunctions_SOLS.ipynb)\n\nArranging the code on seperate lines:\n - makes the code more readable\n - does not effect how the code works\n \nLine breaks can only be used within code that is enclosed by at elast one set of brackets (), []. \n\n__Check Your Solution:__ \n\n\n$ \\mathbf{r} = [5, 2]$\n<br> $ \\mathbf{v} = [3, 4]$\n\n\n\\begin{align}\n      {\\displaystyle {\\begin{aligned}\\ \n      \\mathbf{r} + \\mathbf{v}\n      &=[5, 2]+ [3, 4]\\\\\n      &=[(5+3), \\quad (2+4)] \\\\\n      & = [8, 6] \\end{aligned}}} \n\\end{align}\n\n<a id='ExampleTicTacToe'></a>\n## Example : Tic-tac-toe\nA list of lists can be used to represent a discrete set of positions the a player can occupy.\n\n<br>For example, we can construct a very primitive version of the game tic-tac-toe, using a list of lists and some of the other porgramming skills we have learned so far.\n\nThis example will combine the topics we have studied so far.\n\n<p align=\"center\">\n  \n</p>\n\n\n```python\n# tic-tac-toe \n```\n\n\n```python\n# tic-tac-toe \n#\n# Board positions:\n#\n# 00   01   02\n# 10   11   12\n# 20   21   22\n\n\n# Example solution\n\n# # use a for loop to set-up the 3x3 grid \nboard = []\nfor row in range(3):\n    #board.append(['_', '_', '_'])\n    board.append(['_']*3)\n    \n    \n# display the output nicely       \nfor row in board:\n    for column in row:\n        print(column, end='\\t')\n    # new line at end of row\n    print() \n\n    \n# choose who goes first, X or 0    \nplayer = 'X'\n\n# keep playing the game until told to quit\nwhile(1):\n    # use if and else to take turns at adding input from each player to the board\n    if player == 'X':\n        position = input('Player X, choose position: ')\n        board[int(position[0])][int(position[1])] = 'X'\n        player = '0'\n        \n    else: \n        position = input('Player 0, choose position: ')\n        board[int(position[0])][int(position[1])] = '0'\n        player = 'X'\n        \n        \n    #board[int(position[0])][int(position[1])] = player\n        \n    \n    # display the output nicely       \n    for row in board:\n        for column in row:\n            print(column, end='\\t')\n        # new line at end of row\n        print() \n        \n    print('\\nnext turn \\n')\n        \n        \n    game_over = input('Game over?(Y/N): ')\n    if game_over == 'Y':\n        break\n```\n\n    _\t_\t_\t\n    _\t_\t_\t\n    _\t_\t_\t\n    Player X, choose position: 20\n    _\t_\t_\t\n    _\t_\t_\t\n    X\t_\t_\t\n    \n    next turn \n    \n    Game over?(Y/N): N\n    Player 0, choose position: 21\n    _\t_\t_\t\n    _\t_\t_\t\n    X\t0\t_\t\n    \n    next turn \n    \n    Game over?(Y/N): N\n    Player X, choose position: 11\n    _\t_\t_\t\n    _\tX\t_\t\n    X\t0\t_\t\n    \n    next turn \n    \n    Game over?(Y/N): N\n    Player 0, choose position: 00\n    0\t_\t_\t\n    _\tX\t_\t\n    X\t0\t_\t\n    \n    next turn \n    \n    Game over?(Y/N): N\n    Player X, choose position: 02\n    0\t_\tX\t\n    _\tX\t_\t\n    X\t0\t_\t\n    \n    next turn \n    \n    Game over?(Y/N): Y\n\n\n<a id='Libraries'></a>\n## Libraries\n\nOne of the most important concepts in good programming is to reuse code and avoid repetitions.\n\nPython, like other modern programming languages, has an extensive *library* of built-in functions. \n\nThese functions are designed, tested and optimised by the developers of the Python langauge.  \n\nWe can use these functions to make our code shorter, faster and more reliable.\n\n   \n\n<a id='StandardLibrary'></a>\n## The Standard Library\n\nPython has a large standard library. \n\ne.g. `print()` takes the __input__ in the parentheses and __outputs__ a visible representation.\n\nThey are listed on the Python website:\nhttps://docs.python.org/3/library/functions.html\n\nWe could write our own code to find the minimum of a group of numbers\n\n\n\n\n\n```python\nx0 = 1\nx1 = 2\nx2 = 4\n\nx_min = x0\nif x1 < x_min:\n    x_min = x1\nif x2 < x_min:\n    x_min = x2\n        \nprint(x_min)\n```\n\n    1\n\n\nHowever, it is much faster to use the build in function:\n\n\n```python\nprint(min(1,2,4))\n```\n\n    1\n\n\nThe built-in functions can be found in (.py) files called 'modules'.\n\nThe files are neatly arranged into a system of __sub-packages__ (sub-folders) and __modules__ (files).\n\nThese files are stored on the computer you are using.\n\nA quick google search for \"python function to sum all the numbers in a list\"...\n\nhttps://www.google.co.jp/search?q=python+function+to+sum+all+the+numbers+in+a+list&rlz=1C5CHFA_enJP751JP751&oq=python+function+to+sum+&aqs=chrome.0.0j69i57j0l4.7962j0j7&sourceid=chrome&ie=UTF-8\n\n...returns the function `sum()`.\n\n`sum()` finds the sum of the values in a data structure.\n\n\n\n\n\n\n```python\nprint(sum([1,2,3,4,5]))\n\nprint(sum((1,2,3,4,5)))\n\na = [1,2,3,4,5]\nprint(sum(a))\n```\n\n    15\n    15\n    15\n\n\nThe function `max()` finds the maximum value in data structure.\n\n<a id='Packages'></a>\n## Packages\n\nThe standard library tools are available in any Python environment.\n\nMore specialised libraries, called packages, are available for more specific tasks \n<br>e.g. solving trigonometric functions.\n\nPackages contain functions and constants.  \n\nWe install the packages to use them.   \n\n\n\n__Pygame__\n<br>For a large part of this course we will use functions from a package called `Pygame`.\n<br>`Pygame` is a set of Python modules designed for writing computer games, graphics and sound projects. \n<br>Instructions for how install pygame will be given later in today's seminar.\n\n__math__\n<br>`math` is already installed and allows you to use convenient mathematical functions and operators.\n\n \n\nA package is a collection of Python modules: \n- a __module__ is a single Python file\n- a __package__ is a directory of Python modules.<br>(It contains an __init__.py file, to distinguish it from folders that are not libraries).\n\nThe files that are stored on your computer when Pygame is installed:\n<br>https://github.com/pygame/pygame\n\n<a id='ImportingPackage'></a>\n### Importing a Package\n\nTo use an installed package, we  simply `import` it.\n\nWe only need to import the package once.\n<br>The `import` statement must appear before the use of the package in the code so all packages are usually imported at the start of the program. \n\n        import numpy \n\nWe can then use variable and functions defined within that package by prefixing them with the name of the package:\n\n\n```python\nimport math\n```\n\nAfter this, any constant, variable or function from the package can be used by prefixing it with the name of the package:\n\nAny constant in `math` can be called as:\n\n        `math.constant`.\n        \n\nAny function in `numpy` can be called as:\n\n        `math.function()`\n        \n\n\n\n\n\n```python\n# pi\nprint(math.pi)\n\nx = 1\n\n# Trigonometric functions e.g. cosine\ny = math.cos(x)\nprint(y)\n```\n\n    3.141592653589793\n    0.5403023058681398\n\n\n<a id='UsingPackageFunctions'></a>\n## Using Package Functions. \n\nLet's learn to use `math` functions in our programs...\n\n\n\n\n\n\n```python\n# Some examples math functions with their definitions (as given in the documentation)\n\nx = 1\n\n# Return the sine of x radians.\nprint(math.sin(x))\n\n# Return the tangent of x radians.\nprint(math.tan(x))\n\n# Return the inverse hyperbolic tangent of x.\nprint(math.atan(x))\n\n\n```\n\n    0.8414709848078965\n    1.557407724654902\n    0.7853981633974483\n\n\n\n```python\nx = 1\n\n# Convert angle x from radians to degrees.\ndegrees = math.degrees(x)\nprint(degrees)\n\n# Convert angle x from degrees to radians.\nradians = math.radians(degrees)\nprint(radians)   \n```\n\n    57.29577951308232\n    1.0\n\n\n<a id='ReadingFunctionDocumentation'></a>\n## Reading Function Documentation\n\nOnline documentation can be used to find out: \n- what to include in the () parentheses\n- allowable data types to use as arguments\n- the order in which arguments should be given \n\n\nA google search for 'python math documentation' returns:\n\nhttps://docs.python.org/3/library/math.html\n\n(this list is not exhaustive). \n\n### Try it yourself:\n<br> Find a function in the Python math documentation (https://docs.python.org/3/library/math.html) that can be used to solve the following problem:   \n\n##### Return, $\\left| x \\right|$, the absolute value of x  \n\n\nWrite your answer in the cell below:\n\n\n```python\n# Return the absolute value of x.\n```\n\n<a id='Examplemathpow'></a>\n### Example : math.pow ($x^y$)\nDocumentation : https://docs.python.org/3/library/math.html#hyperbolic-functions\n\n \n\nThe documentation tells us the following information...\n\n##### What arguments to input:\n\"math.pow(x, y)\"\n\n##### What the function returns:\n\"Return x raised to the power y.\"\n\n##### The format of the returend argument:\nmath.pow() converts both its arguments to type float\n\n\n\n<a id='Optimise'></a>\n## Using Package Functions to Optimise your Code\nA fundamental purpose of using imported functions is to make your code shorter and neater.\n<br>For example, when designing a game it can be very useful to generate (pseudo) random numbers so that the challenges and problems for the user to solve are not identical every time the game is played.\n\nWriting your own algorithm to generate random numbers is unecessarily time-consuming.\n\n\n\n`random` is a python module that implements pseudo-random number generators for various distributions.\n\nThe documentation of the functions in this package can be found here:\n<br>https://docs.python.org/3/library/random.html#\n\nImport random to use functions from this package:\n\n\n```python\nimport random\n```\n\nHere are some examples of functions from `random`...\n\n\n```python\n# random.randint(a, b) \n# Return a random integer N such that a <= N <= b. \nrandom.randint(1, 15)\n\n```\n\n\n\n\n    13\n\n\n\n\n```python\n# random.sample(population, k)\n# Return a k length list of unique elements chosen from the population sequence or set. \n# Used for random sampling without replacement.\nrandom.sample([1,2,3,4,5,6,7,8], 4)\n```\n\n\n\n\n    [5, 7, 8, 2]\n\n\n\nRandom numbers can be used to introduce an element of uncertainty to your programs.\n\nThis makes a game more intersting as the outcome may be different every time it is played.\n\nFor example, an adventure game may have a different outcome depending on a random variable.\n\n\n```python\nprint(\"Inside the castle you see a giant spider.\")\nanswer = input(\"Do you fight the spider?  (Yes/No) \")\n        \n    \nif answer == 'Yes':\n    print(\"you defeat the spider. \\nYou win!\")\n        \nelse:\n    print(\"The spider eats you. \\nYou lose!\")\n```\n\n    Inside the castle you see a giant spider.\n    Do you fight the spider?  (Yes/No) no\n    The spider eats you. \n    You lose!\n\n\nAn adventure game where the outcome is random can be more interesting.\n\n\n```python\nprint(\"Inside the castle you see a giant spider.\")\nanswer = input(\"Do you fight the spider?  (Yes/No) \")\n        \n    \nif answer == 'Yes':\n    number = int(random.randint(0, 2))\n    if number < 2:\n        print(\"The spider defeats you. \\nYou lose!\")\n    else:\n        print(\"you defeat the spider. \\nYou win!\")\n        \n\nelse:\n    print(\"The spider eats you. \\nYou lose!\")\n```\n\n    Inside the castle you see a giant spider.\n    Do you fight the spider?  (Yes/No) Yes\n    The spider defeats you. \n    You lose!\n\n\nRandom, computer generated values can also be used to build a game of rock, paper scissors where the user plays against the computer.\n\nThe code section below shows the case that the player choses *rock*.\n\n```python\n\ncomputer = int(random.randint(0, 2))\n        if computer == 0:\n            c_choice = \"rock\"\n        elif computer == 1:\n            c_choice = \"paper\"\n        else:\n            c_choice = \"scissors\"\n```\n\n\nThe full version of the code is given in example program: Examples/02_RockPaperScissors.py\n\nTry running this from the terminal by typing `python3 02_RockPaperScissors.py` from within the __PyEv2019/Examples__ directory.\n\n<a id='InstallingPygame'></a>\n## Installing Pygame\nInstall Pygame now. We will begin using this package in next week's class.\n\n##### On Windows \n\n1. Open the Anaconda Prompt from the terminal.\n<p align=\"center\">\n  \n</p>\n\n1. The window that opens will look like the command line. In the window type the following code then press 'Enter':\n>`conda install -c anaconda pip`\n\n1. When the installation completes type the following code then press 'Enter':\n>`pip install pygame`\n\n##### On mac\n\n1. Open a terminal. \n\n1. Type the following code then press 'Enter':\n>`conda install -c anaconda pip`\n\n1. When the installation completes type the following code then press 'Enter':\n>`pip install pygame`\n\n\n\nTo check the installation has worked type:\n>`import pygame` \n\nin a Jupyter notebook cell and run the cell. If no error is generated you have installed pygame successfully. \n\n<a id='TestYourselfExercises'></a>\n# Review Exercises\n\nCompete the exercise below.\n\nSave your answers as .py files and email them to:\n<br>philamore.hemma.5s@kyoto-u.ac.jp\n\n## Review Exercise : Guessing Game\n__(A)__\n<br>\nWrite a game that:\n- chooses a random number between 1 and 10\n- asks the user to guess what it is\n- exits when the user guesses the right number\n\nUse:\n- a while loop\n- a break statement (to break out of the while loop)\n- a random number generator (from the package, `random`)\n\n\n\n<br>\nExample : The output from your game might look like this:\n\n```\n    I'm thinking of a random number between 1 and 10.\n    Can you guess what it is?\n\n    Guess what number I am thinking of: 5\n\n    Guess what number I am thinking of: 2\n\n    Guess what number I am thinking of: 1\n\n    Guess what number I am thinking of: 9\n\n    You win! I was thinking of 9.\n```\n\n*Hint: Remember that the function `input` returns a string even when a numerical value is entered.* \n\n\n```python\n# Guessing Game\n```\n\n__(B)__\n<br>Use `if` and `else` to generate a __clue__ for the player gets the answer wrong \n\n<br>\nThe output from your game might look like this:\n```\n    I'm thinking of a random number between 1 and 10.\n    Can you guess what it is?\n\n    Guess what number I am thinking of: 1\n    Too low.\n\n    Guess what number I am thinking of: 5\n    Too low.\n\n    Guess what number I am thinking of: 9\n\n    You win! I was thinking of 9.\n    ```\n\n\n```python\n# Guessing Game with Clues\n```\n\n__(C)__\n<br>Use `break` to quit the game if the user makes three consecutive wrong guesses.\n\n<br>\nThe output from your game might look something like this:\n\n    I'm thinking of a random number between 1 and 10.\n    Can you guess what it is? You have 3 guesses...\n\n    Guess what number I am thinking of: 1\n    Too low.\n\n    Guess what number I am thinking of: 2\n    Too low.\n\n    Guess what number I am thinking of: 5\n    \n    You lose! I was thinking of 9.\n\n\n```python\n# Guessing game with maximum number of tries\n\n```\n\n\n```python\n# Guessing game with maximum number of tries\n# Example Solution\n\nimport random \nimport math\n\nnum = random.randint(1, 10)\n\nprint(\"I'm thinking of a random number between 1 and 10.\")\nprint(\"Can you guess what it is?\")\n\nfor i in range(3):\n    guess = int(input(\"Guess what number I am thinking of: \"))\n    \n    if guess == num:\n        print(f\"You win! I was thinking of {num}\")\n        break\n        \n    elif guess < num:\n        print(\"Too low\")\n        \n    else: \n        print(\"Too high\")\n        \nprint(f\"You lose! I was thinking of {num}.\")\n```\n\n    I'm thinking of a random number between 1 and 10.\n    Can you guess what it is?\n    Guess what number I am thinking of: 8\n    Too high\n    Guess what number I am thinking of: 3\n    Too low\n    Guess what number I am thinking of: 5\n    Too low\n    You lose! I was thinking of 6.\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "59be0d1d1ea362c5dfe0fc932b13b1cb59bf5bc0", "size": 41063, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": ".ipynb_checkpoints 2/02ClassMaterial__DataStructures_Libraries-checkpoint.ipynb", "max_stars_repo_name": "hphilamore/ILAS_PyEv2019", "max_stars_repo_head_hexsha": "b3c8ebe00d6795f67879a50ce6ef517353b069c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": ".ipynb_checkpoints 2/02ClassMaterial__DataStructures_Libraries-checkpoint.ipynb", "max_issues_repo_name": "hphilamore/ILAS_PyEv2019", "max_issues_repo_head_hexsha": "b3c8ebe00d6795f67879a50ce6ef517353b069c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": ".ipynb_checkpoints 2/02ClassMaterial__DataStructures_Libraries-checkpoint.ipynb", "max_forks_repo_name": "hphilamore/ILAS_PyEv2019", "max_forks_repo_head_hexsha": "b3c8ebe00d6795f67879a50ce6ef517353b069c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0552030457, "max_line_length": 212, "alphanum_fraction": 0.5226603025, "converted": true, "num_tokens": 6148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17553807793655435, "lm_q2_score": 0.19930799077007072, "lm_q1q2_score": 0.034986141617174726}}
{"text": "# DISTIL Usage Example: CIFAR-10 with Out-of-Distribution Points\n\nOccasionally, a labeled dataset may not have enough data to yield good model performance. The easiest fix is to add more data by selecting and labeling unlabeled instances from a large pool of unlabeled data. However, the relative ease of acquiring unlabeled data in certain instances makes it very easy to accrue some out-of-distribution (OOD) examples. Inadvertently selecting OOD points from the unlabeled data constitutes a waste of effort since these points are not added to the labeled dataset. So, how do we select examples from the unlabeled pool that are not OOD? Here, we show how to use DISTIL's implementation of [SIMILAR](https://arxiv.org/abs/2107.00717) to avoid selecting OOD data.\n\n# Preparation\n\n## Installation and Imports\n\n\n```python\n# Get DISTIL\n!git clone https://github.com/decile-team/distil.git\n!pip install -r distil/requirements/requirements.txt\n\nimport copy\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport sys\nimport torch\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nfrom torch import nn\nfrom torch.autograd import Variable\nfrom torch.utils.data import Dataset, Subset, ConcatDataset, DataLoader\nfrom torchvision import transforms\nfrom torchvision.datasets import cifar\n\nsys.path.append('distil/')\nfrom distil.active_learning_strategies import SCMI, GLISTER, BADGE, EntropySampling, RandomSampling   # All active learning strategies showcased in this example\nfrom distil.utils.models.resnet import ResNet18                                                       # The model used in our image classification example\nfrom distil.utils.train_helper import data_train                                                      # A utility training class provided by DISTIL\nfrom distil.utils.utils import LabeledToUnlabeledDataset                                              # A utility wrapper class that removes labels from labeled PyTorch dataset objects\n```\n\n    fatal: destination path 'distil' already exists and is not an empty directory.\n    Looking in indexes: https://test.pypi.org/simple/, https://pypi.org/simple/\n    Requirement already satisfied: sphinxcontrib-bibtex>=2.3.0 in /usr/local/lib/python3.7/dist-packages (from -r distil/requirements/requirements.txt (line 1)) (2.4.1)\n    Requirement already satisfied: multipledispatch==0.6.0 in /usr/local/lib/python3.7/dist-packages (from -r distil/requirements/requirements.txt (line 2)) (0.6.0)\n    Requirement already satisfied: scikit-learn==0.23.0 in /usr/local/lib/python3.7/dist-packages (from -r distil/requirements/requirements.txt (line 3)) (0.23.0)\n    Requirement already satisfied: numpy>=1.14.2 in /usr/local/lib/python3.7/dist-packages (from -r distil/requirements/requirements.txt (line 4)) (1.19.5)\n    Requirement already satisfied: scipy>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from -r distil/requirements/requirements.txt (line 5)) (1.4.1)\n    Requirement already satisfied: torch>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from -r distil/requirements/requirements.txt (line 6)) (1.10.0+cu111)\n    Requirement already satisfied: tqdm>=4.24.0 in /usr/local/lib/python3.7/dist-packages (from -r distil/requirements/requirements.txt (line 7)) (4.62.3)\n    Requirement already satisfied: numba>=0.43.0 in /usr/local/lib/python3.7/dist-packages (from -r distil/requirements/requirements.txt (line 8)) (0.51.2)\n    Requirement already satisfied: submodlib in /usr/local/lib/python3.7/dist-packages (from -r distil/requirements/requirements.txt (line 11)) (1.1.5)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from -r distil/requirements/requirements.txt (line 12)) (1.1.5)\n    Requirement already satisfied: torchvision in /usr/local/lib/python3.7/dist-packages (from -r distil/requirements/requirements.txt (line 13)) (0.11.1+cu111)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from multipledispatch==0.6.0->-r distil/requirements/requirements.txt (line 2)) (1.15.0)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn==0.23.0->-r distil/requirements/requirements.txt (line 3)) (3.0.0)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn==0.23.0->-r distil/requirements/requirements.txt (line 3)) (1.1.0)\n    Requirement already satisfied: pybtex-docutils>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (1.0.1)\n    Requirement already satisfied: docutils>=0.8 in /usr/local/lib/python3.7/dist-packages (from sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (0.17.1)\n    Requirement already satisfied: Sphinx>=2.1 in /usr/local/lib/python3.7/dist-packages (from sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (4.3.1)\n    Requirement already satisfied: pybtex>=0.20 in /usr/local/lib/python3.7/dist-packages (from sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (0.24.0)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch>=1.4.0->-r distil/requirements/requirements.txt (line 6)) (3.10.0.2)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from numba>=0.43.0->-r distil/requirements/requirements.txt (line 8)) (57.4.0)\n    Requirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba>=0.43.0->-r distil/requirements/requirements.txt (line 8)) (0.34.0)\n    Requirement already satisfied: latexcodec>=1.0.4 in /usr/local/lib/python3.7/dist-packages (from pybtex>=0.20->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (2.0.1)\n    Requirement already satisfied: PyYAML>=3.01 in /usr/local/lib/python3.7/dist-packages (from pybtex>=0.20->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (3.13)\n    Requirement already satisfied: sphinxcontrib-jsmath in /usr/local/lib/python3.7/dist-packages (from Sphinx>=2.1->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (1.0.1)\n    Requirement already satisfied: sphinxcontrib-serializinghtml>=1.1.5 in /usr/local/lib/python3.7/dist-packages (from Sphinx>=2.1->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (1.1.5)\n    Requirement already satisfied: sphinxcontrib-applehelp in /usr/local/lib/python3.7/dist-packages (from Sphinx>=2.1->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (1.0.2)\n    Requirement already satisfied: alabaster<0.8,>=0.7 in /usr/local/lib/python3.7/dist-packages (from Sphinx>=2.1->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (0.7.12)\n    Requirement already satisfied: imagesize in /usr/local/lib/python3.7/dist-packages (from Sphinx>=2.1->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (1.3.0)\n    Requirement already satisfied: requests>=2.5.0 in /usr/local/lib/python3.7/dist-packages (from Sphinx>=2.1->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (2.23.0)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from Sphinx>=2.1->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (21.3)\n    Requirement already satisfied: sphinxcontrib-devhelp in /usr/local/lib/python3.7/dist-packages (from Sphinx>=2.1->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (1.0.2)\n    Requirement already satisfied: sphinxcontrib-qthelp in /usr/local/lib/python3.7/dist-packages (from Sphinx>=2.1->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (1.0.3)\n    Requirement already satisfied: Pygments>=2.0 in /usr/local/lib/python3.7/dist-packages (from Sphinx>=2.1->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (2.6.1)\n    Requirement already satisfied: babel>=1.3 in /usr/local/lib/python3.7/dist-packages (from Sphinx>=2.1->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (2.9.1)\n    Requirement already satisfied: sphinxcontrib-htmlhelp>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from Sphinx>=2.1->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (2.0.0)\n    Requirement already satisfied: snowballstemmer>=1.1 in /usr/local/lib/python3.7/dist-packages (from Sphinx>=2.1->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (2.2.0)\n    Requirement already satisfied: Jinja2>=2.3 in /usr/local/lib/python3.7/dist-packages (from Sphinx>=2.1->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (2.11.3)\n    Requirement already satisfied: pytz>=2015.7 in /usr/local/lib/python3.7/dist-packages (from babel>=1.3->Sphinx>=2.1->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (2018.9)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from Jinja2>=2.3->Sphinx>=2.1->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (2.0.1)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.5.0->Sphinx>=2.1->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.5.0->Sphinx>=2.1->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (2021.10.8)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests>=2.5.0->Sphinx>=2.1->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.5.0->Sphinx>=2.1->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (2.10)\n    Requirement already satisfied: sklearn in /usr/local/lib/python3.7/dist-packages (from submodlib->-r distil/requirements/requirements.txt (line 11)) (0.0)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->-r distil/requirements/requirements.txt (line 12)) (2.8.2)\n    Requirement already satisfied: pillow!=8.3.0,>=5.3.0 in /usr/local/lib/python3.7/dist-packages (from torchvision->-r distil/requirements/requirements.txt (line 13)) (7.1.2)\n    Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->Sphinx>=2.1->sphinxcontrib-bibtex>=2.3.0->-r distil/requirements/requirements.txt (line 1)) (3.0.6)\n\n\n## Preparing CIFAR-10 with OOD Data\n\nThe CIFAR10 dataset contains 60,000 32x32 color images in 10 different classes.The 10 different classes represent airplanes, cars, birds, cats, deer, dogs, frogs, horses, ships, and trucks. There are 6,000 images of each class. The training set contains 50,000 images, and the test set contains 10,000 images. Here, we do a simple setup of the CIFAR10 dataset that we will use in this example. More importantly, we define a split on CIFAR10's training set into an initial labeled seed set and an unlabeled set. For the purposes of this example, we will treat the non-animal classes (0, 1, 8, and 9) as OOD classes.\n\n\n```python\n# Define the name of the dataset and the path that PyTorch should use when downloading the data\ndata_set_name = 'CIFAR10'\ndownload_path = '.'\n\n# Define the number of classes in our modified CIFAR10, which is 6. We also define our ID classes\nnclasses = 6\nid_classes = [2,3,4,5,6,7]\n\n# Define transforms on the dataset splits of CIFAR10. Here, we use random crops and horizontal flips for training augmentations.\n# Both the train and test sets are converted to PyTorch tensors and are normalized around the mean/std of CIFAR-10.\ncifar_training_transform = transforms.Compose([transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))])\ncifar_test_transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))])\n\n# To adapt to our setting, we must also fix the nature of the labels. Here, we remap ID labels to [0,1,2,...]\n# and OOD labels to len(id_classes).\nlabel_map = {id_classes[i]: i for i in range(len(id_classes))}\ncifar_label_transform = lambda x: label_map[x] if x in label_map else len(id_classes)\n\n# Get the dataset objects from PyTorch. Here, CIFAR10 is downloaded, and the transform is applied when points \n# are retrieved.\ncifar10_full_train = cifar.CIFAR10(download_path, train=True, download=True, transform=cifar_training_transform, target_transform=cifar_label_transform)\ncifar10_test = cifar.CIFAR10(download_path, train=False, download=True, transform=cifar_test_transform, target_transform=cifar_label_transform)\n\n# Get the dimension of the images. Here, we simply take the very first image of CIFAR10 \n# and query its dimension.\ndim = np.shape(cifar10_full_train[0][0])\n\n# We now define a train-unlabeled split for the sake of the experiment. Here, the initial train dataset\n# contains only in-distribution points\nnum_train_examples_id_per_class = 200\n\n# The unlabeled dataset will be composed of both in-distribution points and OOD points.\nnum_unlabeled_examples_id_per_class = 250\nnum_unlabeled_examples_ood_per_class = 750\n\n# We assume that we have access to some OOD points initially. If we do not, then we can accrue them from the \n# unlabeled dataset iteratively after discovering them.\nnum_held_out_ood_per_class = 10\n\n# Create the dataset splits using the above configuration\ntrain_idx = []\nunlabeled_idx = []\ntest_idx = []\nheld_out_ood_idx = []\n\nfor class_idx in range(10):\n\n    # Retrieve all the indices of the elements in CIFAR-10 whose label matches class_idx\n    full_idx_class = torch.where(torch.Tensor(cifar10_full_train.targets) == class_idx)[0].cpu().numpy()\n\n    # Determine how many points to add for this class depending on the OOD flag of the class\n    if class_idx not in id_classes:\n        \n        # Choose indices for the unlabeled OOD points and the held-out OOD points for this class\n        class_unlabeled_idx = np.random.choice(full_idx_class, size=num_unlabeled_examples_ood_per_class, replace=False)\n        remaining_class_idx = np.array(list(set(full_idx_class) - set(class_unlabeled_idx)))\n        held_out_class_idx = np.random.choice(remaining_class_idx, size=num_held_out_ood_per_class, replace=False)\n\n        unlabeled_idx.extend(class_unlabeled_idx)\n        held_out_ood_idx.extend(held_out_class_idx)\n\n    else:\n\n        # Choose indices for the labeled ID points and the unlabeled ID points for this class\n        class_train_idx = np.random.choice(full_idx_class, size=num_train_examples_id_per_class, replace=False)\n        remaining_class_idx = np.array(list(set(full_idx_class) - set(class_unlabeled_idx)))\n        class_unlabeled_idx = np.random.choice(remaining_class_idx, size=num_unlabeled_examples_id_per_class, replace=False)\n\n        train_idx.extend(class_train_idx)\n        unlabeled_idx.extend(class_unlabeled_idx)\n\n    # Lastly, we need to update the test dataset as well since we only want to evaluate on ID points.\n    if class_idx in id_classes:\n        test_idx_class = torch.where(torch.Tensor(cifar10_test.targets) == class_idx)[0].cpu().numpy()\n        test_idx.extend(test_idx_class)\n\n# Create the train and unlabeled subsets based on the index lists above. While the unlabeled set constructed here technically has labels, they \n# are only used when querying for labels. Hence, they only exist here for the sake of experimental design.\ncifar10_train = Subset(cifar10_full_train, train_idx)\ncifar10_unlabeled = Subset(cifar10_full_train, unlabeled_idx)\ncifar10_ood = Subset(cifar10_full_train, held_out_ood_idx)\ncifar10_test = Subset(cifar10_test, test_idx)\n```\n\n    Files already downloaded and verified\n    Files already downloaded and verified\n\n\n## Preparing the Model\n\nHere, we use DISTIL's provided implementation of the [ResNet-18](https://arxiv.org/abs/1512.03385) architecture. We also create a model directory to store trained models in this example.\n\n\n```python\n# Use nclasses + 1. We care about the first 6 classes; the last one is not trained since we add no OOD training examples.\n# We use nclasses + 1 to avoid issues in the embedding computation used by SIMILAR.\nnet = ResNet18(num_classes=nclasses + 1)  \n```\n\n# Initial Round\n\n## Training\n\nNow that we have prepared the training data and the model, we can begin training an initial model. We use DISTIL's provided [training loop](https://github.com/decile-team/distil/blob/main/distil/utils/train_helper.py) to do training.\n\n\n```python\n# Define the training arguments to use.\nargs = {'n_epoch':      300,    # Stop training after 300 epochs.\n        'lr':           0.01,   # Use a learning rate of 0.01\n        'batch_size':   20,     # Update the parameters using training batches of size 20\n        'max_accuracy': 0.99,   # Stop training once the training accuracy has exceeded 0.99\n        'optimizer':    'sgd',  # Use the stochastic gradient descent optimizer\n        'device':       \"cuda\" if torch.cuda.is_available() else \"cpu\"  # Use a GPU if one is available\n        }\n\n# Create the training loop using our training dataset, provided model, and training arguments.\n# Train an initial model.\ndt = data_train(cifar10_train, net, args)\ntrained_model = dt.train()\n```\n\n    Training..\n    Epoch: 120 Training accuracy: 0.991\n\n\n## Evaluation\n\nHow does our initial model do on the test set?\n\n\n```python\n# Get the full test accuracy\nfull_test_accuracy = dt.get_acc_on_set(cifar10_test)\nprint(F\"Full Test Accuracy: {full_test_accuracy}\")\n```\n\n    Full Test Accuracy: 0.6238333333333334\n\n\nThe test performance could use improving. Can we add in-distribution points to help the learned model generalize better?\n\n# Selecting In-Distribution Points\n\n## Preparing a Query Set and a Conditioning Set\n\nIn this example, we know that there are OOD examples in the unlabeled dataset that can help us improve the accuracy of the model. How do we avoid selecting these points if we do not know *where* they are in the unlabeled dataset? Here, we use [SIMILAR](https://arxiv.org/abs/2107.00717) to select in-distribution examples from the unlabeled set. SIMILAR requires access to a query set of points that it uses to choose unlabeled points that are similar to it. It also requires access to a conditioning (private) set of points that it uses to choose unlabeled points that are dissimilar to it. In this fashion, we can formulate a query set of in-distribution points and a conditioning set of OOD points to effectively choose in-distribution points.\n\nWhere do we get the query set? Luckily, we already have a couple points in our training dataset to choose. We will use the held-out OOD points for our conditioning set.\n\n\n```python\n# Create a query set that contains the in-distribution examples of the training dataset\nquery_set = cifar10_train\n\n# Use the held-out points for the private set\nprivate_set = cifar10_ood\n```\n\n## Using DISTIL's SIMILAR Implementation: SCMI\n\nNow that we have the query and private sets, we are ready to use DISTIL's implementation of SIMILAR. In particular, we use the submodular conditional mutual information [strategy](https://github.com/decile-team/distil/blob/main/distil/active_learning_strategies/smi.py) that is detailed in [SIMILAR](https://arxiv.org/abs/2107.00717). This will allow us to select a set of points to label within a specified budget $k$.\n\nSpecifically, the strategy attempts to maximize the [submodular conditional mutual information](https://arxiv.org/abs/2006.15412) between a subset $\\mathcal{A}$ of size no greater than $k$ of the unlabeled dataset $\\mathcal{U}$ and the query set $\\mathcal{Q}$ given the conditioning set $\\mathcal{P}$:\n\n\\begin{align}\n\\text{argmax}_{\\mathcal{A} \\subseteq \\mathcal{U}, |\\mathcal{A}|\\leq k} I_F(\\mathcal{A};\\mathcal{Q}|\\mathcal{P})\n\\end{align}\n\nwhere $F$ is a submodular set function.\n\n\n```python\n# Define arguments for SCMI\nselection_strategy_args = {'device':        args['device'],       # Use the device used in training\n                           'batch_size':    args['batch_size'],   # Use the batch size used in training\n                           'scmi_function':  'flcmi',              # Use a facility location function, which captures representation information\n                           'metric':        'cosine',             # Use cosine similarity when determining the likeness of two data points\n                           'optimizer':     'LazyGreedy'          # When doing submodular maximization, use the lazy greedy optimizer\n                          }\n\n# Create the SCMI selection strategy. Note: We remove the labels from the unlabeled portion of CIFAR-10 that we created earlier.\n# In a practical application, one would not have these labels a priori. Note: Since the OOD private set has class len(id_classes), we need to add 1 to nclasses.\nselection_strategy = SCMI(cifar10_train, LabeledToUnlabeledDataset(cifar10_unlabeled), query_set, private_set, trained_model, nclasses + 1, selection_strategy_args)\n\n# Disable the augmentations used in the training dataset. Since all augmentations come from the cifar10_full_train object, we set its transform to the \n# transform used by the test set.\ncifar10_full_train.transform = cifar_test_transform\n\n# Do the selection, which will return the indices of the selected points with respect to the unlabeled dataset.\nbudget = 400\nselected_idx = selection_strategy.select(budget)\n\n# Re-enable augmentations\ncifar10_full_train.transform = cifar_training_transform\n```\n\n## Labeling the Points\n\nNow that we know which points should be labeled, we can present them to human labelers for annotation. Here, we can do so automatically since we already know their labels for the sake of the example.\n\n\n```python\n# Form a labeled subset of the unlabeled dataset. Again, we already have the labels, \n# so we simply take a subset. Note, however, that the selection was done without the \n# use of the labels and that we would normally not have these labels. Hence, the \n# following statement would usually require human effort to complete.\nscmi_human_labeled_dataset = Subset(cifar10_unlabeled, selected_idx)\n```\n\n## Characterizing the Selection\n\nNow that we have selected and labeled these new points, we can add them to the training dataset and retrain our model. Before that, how many points did we select that actually were in-distribution points?\n\n\n```python\n# Go over the newly labeled dataset, tallying the number of points seen in each class.\nin_distribution_points = 0\nfor _, label in scmi_human_labeled_dataset:\n    if label != len(id_classes):\n        in_distribution_points += 1\n\n# Print total ID count\nprint(F\"Total In-Distribution Points: {in_distribution_points}\")\nprint(F\"Fraction of Budget: {in_distribution_points / budget}\")\n```\n\n    Total In-Distribution Points: 208\n    Fraction of Budget: 0.52\n\n\nWe were able to get a good number of in-distribution points. For comparison sake, how many in-distribution points would we get using some of DISTIL's other strategies?\n\n**BADGE**\n\n\n```python\n# Repeat the previous steps\nselection_strategy = BADGE(cifar10_train, LabeledToUnlabeledDataset(cifar10_unlabeled), trained_model, nclasses + 1, selection_strategy_args)\n\ncifar10_full_train.transform = cifar_test_transform\nbudget = 400\nselected_idx = selection_strategy.select(budget)\ncifar10_full_train.transform = cifar_training_transform\n\nbadge_human_labeled_dataset = Subset(cifar10_unlabeled, selected_idx)\n\nin_distribution_points = 0\nfor _, label in badge_human_labeled_dataset:\n    if label != len(id_classes):\n        in_distribution_points += 1\n\n# Print total ID count\nprint(F\"Total In-Distribution Points: {in_distribution_points}\")\nprint(F\"Fraction of Budget: {in_distribution_points / budget}\")\n```\n\n    Total In-Distribution Points: 103\n    Fraction of Budget: 0.2575\n\n\n**Random**\n\n\n```python\n# Repeat the previous steps\nselection_strategy = RandomSampling(cifar10_train, LabeledToUnlabeledDataset(cifar10_unlabeled), trained_model, nclasses + 1, selection_strategy_args)\n\ncifar10_full_train.transform = cifar_test_transform\nbudget = 400\nselected_idx = selection_strategy.select(budget)\ncifar10_full_train.transform = cifar_training_transform\n\nrandom_human_labeled_dataset = Subset(cifar10_unlabeled, selected_idx)\n\nin_distribution_points = 0\nfor _, label in random_human_labeled_dataset:\n    if label != len(id_classes):\n        in_distribution_points += 1\n\n# Print total ID count\nprint(F\"Total In-Distribution Points: {in_distribution_points}\")\nprint(F\"Fraction of Budget: {in_distribution_points / budget}\")\n```\n\n    Total In-Distribution Points: 145\n    Fraction of Budget: 0.3625\n\n\n**Entropy**\n\n\n```python\n# Repeat the previous steps\nselection_strategy = EntropySampling(cifar10_train, LabeledToUnlabeledDataset(cifar10_unlabeled), trained_model, nclasses + 1, selection_strategy_args)\n\ncifar10_full_train.transform = cifar_test_transform\nbudget = 400\nselected_idx = selection_strategy.select(budget)\ncifar10_full_train.transform = cifar_training_transform\n\nentropy_human_labeled_dataset = Subset(cifar10_unlabeled, selected_idx)\n\nin_distribution_points = 0\nfor _, label in entropy_human_labeled_dataset:\n    if label != len(id_classes):\n        in_distribution_points += 1\n\n# Print total ID count\nprint(F\"Total In-Distribution Points: {in_distribution_points}\")\nprint(F\"Fraction of Budget: {in_distribution_points / budget}\")\n```\n\n    Total In-Distribution Points: 80\n    Fraction of Budget: 0.2\n\n\nHence, we can see that SCMI does comparatively better at selecting in-distribution instances.\n\n# Improving Performance\n\n## Re-Training\n\nLet us re-train our model using the newly selected points. Note, however, that we only want to add the in-distribution points.\n\n\n```python\n# Create a new training dataset by concatenating what we have with the newly labeled in-distribution points.\nin_distribution_selected_idx = []\nfor index, (_, label) in enumerate(scmi_human_labeled_dataset):\n    if label != len(id_classes):\n        in_distribution_selected_idx.append(index)\nin_distribution_scmi_human_labeled_dataset = Subset(scmi_human_labeled_dataset, in_distribution_selected_idx)\n\nnew_training_dataset = ConcatDataset([cifar10_train, in_distribution_scmi_human_labeled_dataset])\nprint(\"New Training Dataset Length:\", len(new_training_dataset))\nnew_dt = data_train(new_training_dataset, copy.deepcopy(net), args)\nnew_trained_model = new_dt.train()\n```\n\n    New Training Dataset Length: 1408\n    Training..\n    Epoch: 123 Training accuracy: 0.991\n\n\n## Evaluation\n\nNow, let us see the accuracy improvement.\n\n\n```python\n# Get the full test accuracy\nfull_test_accuracy_before = dt.get_acc_on_set(cifar10_test)\nfull_test_accuracy_after = new_dt.get_acc_on_set(cifar10_test)\n\nprint(F\"Full Test Accuracy Improvement: {full_test_accuracy_before} to {full_test_accuracy_after}\")\n```\n\n    Full Test Accuracy Improvement: 0.6238333333333334 to 0.6513333333333333\n\n\n## Comparison\n\nWhat would the accuracy improvement look like if we had used the other methods?\n\n**BADGE**\n\n\n```python\n# Repeat the process\nin_distribution_selected_idx = []\nfor index, (_, label) in enumerate(badge_human_labeled_dataset):\n    if label != len(id_classes):\n        in_distribution_selected_idx.append(index)\nin_distribution_badge_human_labeled_dataset = Subset(badge_human_labeled_dataset, in_distribution_selected_idx)\n\nnew_training_dataset = ConcatDataset([cifar10_train, in_distribution_badge_human_labeled_dataset])\nprint(\"New Training Dataset Length:\", len(new_training_dataset))\nnew_dt = data_train(new_training_dataset, copy.deepcopy(net), args)\nnew_trained_model = new_dt.train()\n\nfull_test_accuracy_before = dt.get_acc_on_set(cifar10_test)\nfull_test_accuracy_after = new_dt.get_acc_on_set(cifar10_test)\n\nprint(F\"Full Test Accuracy Improvement: {full_test_accuracy_before} to {full_test_accuracy_after}\")\n```\n\n    New Training Dataset Length: 1303\n    Training..\n    Epoch: 145 Training accuracy: 0.992\n    Full Test Accuracy Improvement: 0.6238333333333334 to 0.6311666666666667\n\n\n**Random**\n\n\n```python\n# Repeat the process\nin_distribution_selected_idx = []\nfor index, (_, label) in enumerate(random_human_labeled_dataset):\n    if label != len(id_classes):\n        in_distribution_selected_idx.append(index)\nin_distribution_random_human_labeled_dataset = Subset(random_human_labeled_dataset, in_distribution_selected_idx)\n\nnew_training_dataset = ConcatDataset([cifar10_train, in_distribution_random_human_labeled_dataset])\nprint(\"New Training Dataset Length:\", len(new_training_dataset))\nnew_dt = data_train(new_training_dataset, copy.deepcopy(net), args)\nnew_trained_model = new_dt.train()\n\nfull_test_accuracy_before = dt.get_acc_on_set(cifar10_test)\nfull_test_accuracy_after = new_dt.get_acc_on_set(cifar10_test)\n\nprint(F\"Full Test Accuracy Improvement: {full_test_accuracy_before} to {full_test_accuracy_after}\")\n```\n\n    New Training Dataset Length: 1345\n    Training..\n    Epoch: 130 Training accuracy: 0.99\n    Full Test Accuracy Improvement: 0.6238333333333334 to 0.6201666666666666\n\n\n**Entropy**\n\n\n```python\n# Repeat the process\nin_distribution_selected_idx = []\nfor index, (_, label) in enumerate(entropy_human_labeled_dataset):\n    if label != len(id_classes):\n        in_distribution_selected_idx.append(index)\nin_distribution_entropy_human_labeled_dataset = Subset(entropy_human_labeled_dataset, in_distribution_selected_idx)\n\nnew_training_dataset = ConcatDataset([cifar10_train, in_distribution_entropy_human_labeled_dataset])\nprint(\"New Training Dataset Length:\", len(new_training_dataset))\nnew_dt = data_train(new_training_dataset, copy.deepcopy(net), args)\nnew_trained_model = new_dt.train()\n\nfull_test_accuracy_before = dt.get_acc_on_set(cifar10_test)\nfull_test_accuracy_after = new_dt.get_acc_on_set(cifar10_test)\n\nprint(F\"Full Test Accuracy Improvement: {full_test_accuracy_before} to {full_test_accuracy_after}\")\n```\n\n    New Training Dataset Length: 1280\n    Training..\n    Epoch: 131 Training accuracy: 0.993\n    Full Test Accuracy Improvement: 0.6238333333333334 to 0.6231666666666666\n\n", "meta": {"hexsha": "457954b9273d52fd32bbea4de21175a360c998da", "size": 47219, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorials/image_classification/realistic_scenarios/DISTIL_Example_OOD_CIFAR10.ipynb", "max_stars_repo_name": "ansunsujoe/distil", "max_stars_repo_head_hexsha": "cf6cae2b88ef129d09c159aae0569978190e9f98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 83, "max_stars_repo_stars_event_min_datetime": "2021-01-06T06:50:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:16:32.000Z", "max_issues_repo_path": "tutorials/image_classification/realistic_scenarios/DISTIL_Example_OOD_CIFAR10.ipynb", "max_issues_repo_name": "ansunsujoe/distil", "max_issues_repo_head_hexsha": "cf6cae2b88ef129d09c159aae0569978190e9f98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2021-02-27T06:09:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-23T11:03:36.000Z", "max_forks_repo_path": "tutorials/image_classification/realistic_scenarios/DISTIL_Example_OOD_CIFAR10.ipynb", "max_forks_repo_name": "ansunsujoe/distil", "max_forks_repo_head_hexsha": "cf6cae2b88ef129d09c159aae0569978190e9f98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2021-03-05T18:26:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T01:53:17.000Z", "avg_line_length": 46.384086444, "max_line_length": 759, "alphanum_fraction": 0.5960947924, "converted": true, "num_tokens": 7926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.07159119746371433, "lm_q1q2_score": 0.03495679297087698}}
{"text": "```python\n#remove cell visibility\nfrom IPython.display import HTML\ntag = HTML('''\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.''')\ndisplay(tag)\n```\n\n\n\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.\n\n\n\n```python\n%matplotlib inline\nimport control\nimport numpy\nimport sympy as sym\nfrom IPython.display import display, Markdown\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\n\n\n#print a matrix latex-like\ndef bmatrix(a):\n     \"\"\"Returns a LaTeX bmatrix - by Damir Arbula (ICCT project)\n\n     :a: numpy array\n     :returns: LaTeX bmatrix as a string\n     \"\"\"\n     if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n     lines = str(a).replace('[', '').replace(']', '').splitlines()\n     rv = [r'\\begin{bmatrix}']\n     rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n     rv +=  [r'\\end{bmatrix}']\n     return '\\n'.join(rv)\n\n\n# Display formatted matrix: \ndef vmatrix(a):\n    if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n    lines = str(a).replace('[', '').replace(']', '').splitlines()\n    rv = [r'\\begin{vmatrix}']\n    rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n    rv +=  [r'\\end{vmatrix}']\n    return '\\n'.join(rv)\n\n\n#matrixWidget is a matrix looking widget built with a VBox of HBox(es) that returns a numPy array as value !\nclass matrixWidget(widgets.VBox):\n    def updateM(self,change):\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.M_[irow,icol] = self.children[irow].children[icol].value\n                #print(self.M_[irow,icol])\n        self.value = self.M_\n\n    def dummychangecallback(self,change):\n        pass\n    \n    \n    def __init__(self,n,m):\n        self.n = n\n        self.m = m\n        self.M_ = numpy.matrix(numpy.zeros((self.n,self.m)))\n        self.value = self.M_\n        widgets.VBox.__init__(self,\n                             children = [\n                                 widgets.HBox(children = \n                                              [widgets.FloatText(value=0.0, layout=widgets.Layout(width='90px')) for i in range(m)]\n                                             ) \n                                 for j in range(n)\n                             ])\n        \n        #fill in widgets and tell interact to call updateM each time a children changes value\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        #value = Unicode('example@example.com', help=\"The email value.\").tag(sync=True)\n        self.observe(self.updateM, names='value', type= 'All')\n        \n    def setM(self, newM):\n        #disable callbacks, change values, and reenable\n        self.unobserve(self.updateM, names='value', type= 'All')\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].unobserve(self.updateM, names='value')\n        self.M_ = newM\n        self.value = self.M_\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        self.observe(self.updateM, names='value', type= 'All')        \n\n                #self.children[irow].children[icol].observe(self.updateM, names='value')\n\n             \n#overlaod class for state space systems that DO NOT remove \"useless\" states (what \"professor\" of automatic control would do this?)\nclass sss(control.StateSpace):\n    def __init__(self,*args):\n        #call base class init constructor\n        control.StateSpace.__init__(self,*args)\n    #disable function below in base class\n    def _remove_useless_states(self):\n        pass\n```\n\n## Krmiljenje globina avtonomnega podvodnega vozila (AUV)\n\nDinamiko nagiba avtonomnega podvodnega vozila (AUV) okoli pre\u010dne osi $\\theta$ lahko modeliramo z:  \n$$\nJ_y\\ddot{\\theta}=\u2212D\\dot{\\theta}+CV\\gamma,\n$$\nkjer so $J_y=8.333$ kg$\\text{m}^2$ vztrajnostni moment vozila glede na pre\u010dno os, $D = 30$ Nms koeficient upora, $C=45$ Ns koeficient u\u010dinkovitost repnih povr\u0161in, $\\gamma$ kot vi\u0161inskega krmila (izra\u017een v radianih; njegova vrednost mora biti znotraj intervala $\\pm10\u00b0$), in $V$ trenutno hitrost gibanja v m/s. \n\nVertikalno (navpi\u010dno) hitrost $w$ AUV lahko pribli\u017eno modeliramo z: \n$$\nw = V\\theta.\n$$\n\nIz varnostnih razlogov, nagib AUV okoli pre\u010dne osi ne sme presegati vrednosti $\\pm20\u00b0$ med obratovanjem. Nagib AUV okoli pre\u010dne osi in globina ($z$) sta merjena s pomo\u010djo navigacijskega filtra.\n\nSistem lahko v prostoru stanj popi\u0161emo z\n\\begin{cases}\n    \\dot{x} = \\begin{bmatrix} -D/J_y & 0 & 0 \\\\ 1 & 0 & 0 \\\\ 0 & V & 0 \\end{bmatrix}x + \\begin{bmatrix} CV/J_y \\\\ 0 \\\\ 0 \\end{bmatrix}u\\\\\n    y = \\begin{bmatrix} 0 & 1 & 0 \\\\ 0 & 0 & 1 \\end{bmatrix}x,\n\\end{cases}\n\npri \u010demer velja $x=\\begin{bmatrix} x_1 & x_2 & x_3 \\end{bmatrix}^T=\\begin{bmatrix} \\dot{\\theta} & \\theta & z \\end{bmatrix}^T$ in $u=\\gamma$.\n\nOb upo\u0161tevanju konstante hitrosti $V=1$ m/s, \u017eelimo na\u010drtovati regulator globine $z$, ki bo omogo\u010dal ni\u010den odstopek v stacionarnem stanju v odzivu na pomik v obliki kora\u010dne funkcije.\n\n### Na\u010drtovanje regulatorja\n#### Na\u010drtovanje krmilnika\n\nDa izpolnimo vse zahteve, najprej dodajmo novo spremenljivko stanj:\n$$\n\\dot{x_4} = z-y_d = x_3 - y_d\n$$\nRaz\u0161irjen sistem je tako:\n\\begin{cases}\n    \\dot{x_a} = \\begin{bmatrix} -D/J_y & 0 & 0 & 0 \\\\ 1 & 0 & 0 & 0 \\\\ 0 & V & 0 & 0 \\\\ 0 & 0 & 1 & 0 \\end{bmatrix}x_a + \\begin{bmatrix} CV/J_y & 0 \\\\ 0 & 0 \\\\ 0 & 0 \\\\ 0 & -1 \\end{bmatrix} \\begin{bmatrix} u \\\\ y_d \\end{bmatrix}\\\\\n    y = \\begin{bmatrix} 0 & 1 & 0 & 0 \\\\ 0 & 0 & 1 & 0 \\\\ 0 & 0 & 0 & 1 \\end{bmatrix}x_a,\n\\end{cases}\n\nkjer velja $x_a = \\begin{bmatrix} x_1 & x_2 & x_3 & x_4 \\end{bmatrix}^T = \\begin{bmatrix} \\dot{\\theta} & \\theta & z & x_4 \\end{bmatrix}^T$.\n\nS prvim vhodom $u$, ker je sistem vodljiv, razporedimo pole tako, da stabiliziramo sistem in upo\u0161tevamo omejitvi, povezani z $u$ ($\\pm10\u00b0$) in $\\theta$ ($\\pm20\u00b0$), ko je vhod kora\u010dna funkcija vrednosti $y_d=1$ m. Mo\u017ena re\u0161itev je, da razporedimo pole v $-5.9$, $-0.9$ in $-0.63\\pm0.70i$.\n\n#### Na\u010drtovanje spoznavalnika\n\nNa voljo imamo meritve $x_2$, $x_3$ in $x_4$, kar pomeni, da moramo oceniti le $x_1$. V ta namen lahko vzamemo podsistem \n$x_l =\\begin{bmatrix} x_1 & x_2 \\end{bmatrix}^T$, $\\dot{x_l}=A_lx_l + B_lu$ and $y_l = x_2 = C_lx_l$. Ob upo\u0161tevanju $L=\\begin{bmatrix} l_1 & l_2 \\end{bmatrix}^T$ lahko izra\u010dunamo lastni vrednosti $\\lambda_1$ in $\\lambda_2$ matrike $A_l-LC_l$ in dolo\u010dimo re\u0161itev za $l_1$ in $l_2$:\n\\begin{cases}\nl_1 = \\lambda_1\\lambda_2 + D\\lambda_1/J_y + D\\lambda_2/J_y + D^2/J_y^2 \\\\\nl_2 = -\\lambda_1 - \\lambda_2 - D/J_y \\, .\n\\end{cases}\n\nIzberemo naslednji lastni vrednosti $\\lambda_1 = \\lambda_2 = -15$.\n\n### Kako upravljati s tem interaktivnim primerom?\n- V primeru, da velja $V = 0.75$ m/s., poizkusi slediti zahtevam na na\u010din, da spremeni\u0161 lokacije polov krmilnika.\n- Opazuj delovanje regulatorja, v prisotnosti za\u010detne napake ocene stanj, in ga poizkusi izbolj\u0161ati.\n\n\n```python\n# Preparatory cell\n\nX0 = numpy.matrix('0.0')\nK = numpy.matrix([0,0,0,0])\nL = numpy.matrix([[0],[0]])\n\nX0w = matrixWidget(1,1)\nX0w.setM(X0)\nKw = matrixWidget(1,4)\nKw.setM(K)\nLw = matrixWidget(2,1)\nLw.setM(L)\n\n\neig1c = matrixWidget(1,1)\neig2c = matrixWidget(2,1)\neig3c = matrixWidget(1,1)\neig4c = matrixWidget(2,1)\neig1c.setM(numpy.matrix([-5.7])) \neig2c.setM(numpy.matrix([[-0.63],[-0.70]]))\neig3c.setM(numpy.matrix([-0.9]))\neig4c.setM(numpy.matrix([[-0.63],[-0.70]]))\n\neig1o = matrixWidget(1,1)\neig2o = matrixWidget(2,1)\neig1o.setM(numpy.matrix([-15.])) \neig2o.setM(numpy.matrix([[-15.],[0.]]))\n```\n\n\n```python\n# Misc\n\n#create dummy widget \nDW = widgets.FloatText(layout=widgets.Layout(width='0px', height='0px'))\n\n#create button widget\nSTART = widgets.Button(\n    description='Test',\n    disabled=False,\n    button_style='', # 'success', 'info', 'warning', 'danger' or ''\n    tooltip='Test',\n    icon='check'\n)\n                       \ndef on_start_button_clicked(b):\n    #This is a workaround to have intreactive_output call the callback:\n    #   force the value of the dummy widget to change\n    if DW.value> 0 :\n        DW.value = -1\n    else: \n        DW.value = 1\n    pass\nSTART.on_click(on_start_button_clicked)\n\n# Define type of method \nselm = widgets.Dropdown(\n    options= ['Nastavi K in L', 'Nastavi lastne vrednosti'],\n    value= 'Nastavi lastne vrednosti',\n    description='',\n    disabled=False\n)\n\n# Define the number of complex eigenvalues\nselec = widgets.Dropdown(\n    options= ['brez kompleksnih lastnih vrednosti', 'dve kompleksni lastni vrednosti', '\u0161tiri kompleksne lastne vrednosti'],\n    value= 'dve kompleksni lastni vrednosti',\n    description='Kompleksne lastne vrednosti krmilnika:',\n    disabled=False\n)\nseleo = widgets.Dropdown(\n    options= ['brez kompleksnih lastnih vrednosti', 'dve kompleksni lastni vrednosti'],\n    value= 'brez kompleksnih lastnih vrednosti',\n    description='Kompleksne lastne vrednosti spoznavalnika:',\n    disabled=False\n)\n\n#define type of ipout \nselu = widgets.Dropdown(\n    options=['impulzna funkcija', 'kora\u010dna funkcija', 'sinusoidna funkcija', 'kvadratni val'],\n    value='kora\u010dna funkcija',\n    description='Vhod:',\n    style = {'description_width': 'initial'},\n    disabled=False\n)\n# Define the values of the input\nu = widgets.FloatSlider(\n    value=1,\n    min=0,\n    max=4,\n    step=0.1,\n    description='',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.1f',\n)\nv = widgets.FloatSlider(\n    value=1,\n    min=0.5,\n    max=4,\n    step=0.1,\n    description=r'$V$:',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.1f',\n)\nperiod = widgets.FloatSlider(\n    value=0.5,\n    min=0.001,\n    max=10,\n    step=0.001,\n    description='Perioda: ',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.2f',\n)\n\nsimTime = widgets.FloatText(\n    value=10,\n    description='',\n    disabled=False\n)\n```\n\n\n```python\n# Support functions\n\ndef eigen_choice(selec,seleo):\n    if selec == 'brez kompleksnih lastnih vrednosti':\n        eig1c.children[0].children[0].disabled = False\n        eig2c.children[1].children[0].disabled = True\n        eig3c.children[0].children[0].disabled = False\n        eig4c.children[0].children[0].disabled = False\n        eig4c.children[1].children[0].disabled = True\n        eigc = 0\n    if seleo == 'brez kompleksnih lastnih vrednosti':\n        eig1o.children[0].children[0].disabled = False\n        eig2o.children[1].children[0].disabled = True\n        eigo = 0\n    if selec == 'dve kompleksni lastni vrednosti':\n        eig1c.children[0].children[0].disabled = False\n        eig2c.children[1].children[0].disabled = False\n        eig3c.children[0].children[0].disabled = False\n        eig4c.children[0].children[0].disabled = True\n        eig4c.children[1].children[0].disabled = True\n        eigc = 2\n    if seleo == 'dve kompleksni lastni vrednosti':\n        eig1o.children[0].children[0].disabled = True\n        eig2o.children[1].children[0].disabled = False\n        eigo = 2\n    if selec == '\u0161tiri kompleksne lastne vrednosti':\n        eig1c.children[0].children[0].disabled = True\n        eig2c.children[1].children[0].disabled = False\n        eig3c.children[0].children[0].disabled = True\n        eig4c.children[0].children[0].disabled = False\n        eig4c.children[1].children[0].disabled = False\n        eigc = 4\n    return eigc, eigo\n\ndef method_choice(selm):\n    if selm == 'Nastavi K in L':\n        method = 1\n        selec.disabled = True\n        seleo.disabled = True\n    if selm == 'Nastavi lastne vrednosti':\n        method = 2\n        selec.disabled = False\n        seleo.disabled = False\n    return method\n```\n\n\n```python\nD = 30\nc = 45\nV = 1\nJy = 8.333\n\nA = numpy.matrix([[-D/Jy, 0, 0, 0],\n                  [1, 0, 0, 0],\n                  [0, V, 0, 0],\n                  [0, 0, 1, 0]])\nBu = numpy.matrix([[c*V/Jy],[0],[0],[0]])\nBref = numpy.matrix([[0],[0],[0],[-1]])\nC = numpy.matrix([0,0,1,0])\n\nAl = numpy.matrix([[-D/Jy, 0],\n                  [1, 0]])\nCl = numpy.matrix([0,1])\n\ndef main_callback2(v, X0w, K, L, eig1c, eig2c, eig3c, eig4c, eig1o, eig2o, u, period, selm, selec, seleo, selu, simTime, DW):\n    eigc, eigo = eigen_choice(selec,seleo)\n    method = method_choice(selm)\n    \n    A = numpy.matrix([[-D/Jy, 0, 0, 0],\n                  [1, 0, 0, 0],\n                  [0, v, 0, 0],\n                  [0, 0, 1, 0]])\n    Bu = numpy.matrix([[c*v/Jy],[0],[0],[0]])\n    \n    if method == 1:\n        solc = numpy.linalg.eig(A-Bu*K)\n        solo = numpy.linalg.eig(Al-L*Cl)\n    if method == 2:\n        if eig1c[0,0]==eig2c[0,0] or eig1c[0,0]==eig3c[0,0] or eig1c[0,0]==eig4c[0,0]:\n            eig1c[0,0] -= 0.0001\n        if eig2c[0,0]==eig3c[0,0] or eig2c[0,0]==eig4c[0,0]:\n            eig3c[0,0] -= 0.0002\n        if eigc == 0:\n            K = control.acker(A, Bu, [eig1c[0,0], eig2c[0,0], eig3c[0,0], eig4c[0,0]])\n            Kw.setM(K)\n        if eigc == 2:\n            K = control.acker(A, Bu, [eig3c[0,0],\n                                      eig1c[0,0],\n                                      numpy.complex(eig2c[0,0], eig2c[1,0]), \n                                      numpy.complex(eig2c[0,0],-eig2c[1,0])])\n            Kw.setM(K)\n        if eigc == 4:\n            K = control.acker(A, Bu, [numpy.complex(eig4c[0,0], eig4c[1,0]), \n                                      numpy.complex(eig4c[0,0],-eig4c[1,0]),\n                                      numpy.complex(eig2c[0,0], eig2c[1,0]), \n                                      numpy.complex(eig2c[0,0],-eig2c[1,0])])\n            Kw.setM(K)\n        if eigo == 0:\n            temp1 = eig1o[0,0]\n            temp2 = eig2o[0,0]\n            L = numpy.matrix([[temp1*temp2 + D*temp1/Jy + D*temp2/Jy + D**2/Jy**2], [-temp1 - temp2 - D/Jy]]) \n            Lw.setM(L)\n        if eigo == 2:\n            temp1 = numpy.complex(eig2o[0,0], eig2o[1,0])\n            temp2 = numpy.complex(eig2o[0,0],-eig2o[1,0])\n            L = numpy.matrix([[temp1*temp2 + D*temp1/Jy + D*temp2/Jy + D**2/Jy**2], [-temp1 - temp2 - D/Jy]]) \n            L = numpy.real(L)\n            Lw.setM(L)\n            \n    sys = sss(A,numpy.hstack((Bu,Bref)),[[0,1,0,0],[0,0,1,0],[0,0,0,1]],[[0,0],[0,0],[0,0]])\n    syse = sss(Al-L*Cl,numpy.hstack((Bu[0:2],L)),[1,0],[0,0])\n    sysc = sss(0,[0,0,0,0],0,-K)\n    sys_append = control.append(sys,syse,sysc)\n    sys_CL = control.connect(sys_append,\n                             [[1,5],[3,5],[4,1],[5,4],[6,1],[7,2],[8,3]],\n                             [2],\n                             [2,5])\n    \n    X0w1 = numpy.zeros((6,1))\n    X0w1[4,0] = X0w\n    if simTime != 0:\n        T = numpy.linspace(0, simTime, 10000)\n    else:\n        T = numpy.linspace(0, 1, 10000)\n      \n    if selu == 'impulzna funkcija': #selu\n        U = [0 for t in range(0,len(T))]\n        U[0] = u\n        T, yout, xout = control.forced_response(sys_CL,T,U,X0w1)\n    if selu == 'kora\u010dna funkcija':\n        U = [u for t in range(0,len(T))]\n        T, yout, xout = control.forced_response(sys_CL,T,U,X0w1)\n    if selu == 'sinusoidna funkcija':\n        U = u*numpy.sin(2*numpy.pi/period*T)\n        T, yout, xout = control.forced_response(sys_CL,T,U,X0w1)\n    if selu == 'kvadratni val':\n        U = u*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n        T, yout, xout = control.forced_response(sys_CL,T,U,X0w1)\n    \n    try:\n        step_info_dict = control.step_info(sys_CL[0,0],SettlingTimeThreshold=0.05,T=T)\n        print('Informacije o odzivu sistema: \\n\\t\u010cas vzpona [s] =',step_info_dict['RiseTime'],'\\n\\t\u010cas ustalitve (5%) [s] =',step_info_dict['SettlingTime'],'\\n\\tPrenihaj [%]=',step_info_dict['Overshoot'])\n        print('Maksimalna vrednost x_2 (dele\u017e od 20\u00b0)=', max(abs(xout[1]))/(numpy.pi/180*20)*100)\n        print('Maksimalna vrednost u (dele\u017e od 10\u00b0)=', max(abs(yout[1]))/(numpy.pi/180*10)*100)\n    except:\n        print(\"Napaka v izra\u010dunu informacij o odzivu sistema.\")\n    \n    fig = plt.figure(num='Simulation1', figsize=(14,12))\n    \n    fig.add_subplot(221)\n    plt.title('Odziv sistema')\n    plt.ylabel('Izhod')\n    plt.plot(T,yout[0],T,U,'r--')\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$y$','Referenca'])\n    plt.grid()\n    \n    fig.add_subplot(222)\n    plt.title('Vhod')\n    plt.ylabel('$u$')\n    plt.plot(T,yout[1])\n    plt.plot(T,[numpy.pi/180*10 for i in range(len(T))],'r--')\n    plt.plot(T,[-numpy.pi/180*10 for i in range(len(T))],'r--')\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(223)\n    plt.title('Odzivi stanj')\n    plt.ylabel('Stanja')\n    plt.plot(T,xout[0],\n             T,xout[1],\n             T,xout[2],\n             T,xout[3],\n             T,[numpy.pi/180*20 for i in range(len(T))],'r--',\n             T,[-numpy.pi/180*20 for i in range(len(T))],'r--')\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$x_{1}$','$x_{2}$','$x_{3}$','$x_{4}$','+lim $x_2$','-lim $x_2$'])\n    plt.grid()\n    \n    fig.add_subplot(224)\n    plt.title('Napaka ocene stanj')\n    plt.ylabel('Napaka ocene stanj')\n    plt.plot(T,xout[4]-xout[0])\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$e_{1}$'])\n    plt.grid()\n    #plt.tight_layout()\n   \nalltogether2 = widgets.VBox([widgets.HBox([selm, \n                                          selec,\n                                          seleo,\n                                          selu]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.VBox([widgets.Label('K:',border=3), Kw, \n                                                        widgets.Label('Lastne vrednosti:',border=3),\n                                                        widgets.HBox([eig1c, \n                                                                      eig2c, \n                                                                      eig3c,\n                                                                      eig4c])]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.VBox([widgets.HBox([widgets.Label('L:',border=3), Lw, widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Lastne vrednosti:',border=3), \n                                          eig1o, \n                                          eig2o,\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('X0 est.:',border=3), X0w]),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                                       widgets.HBox([\n                                          widgets.VBox([widgets.Label('Simulacijski \u010das [s]:',border=3)]),\n                                          widgets.VBox([simTime])])])]),\n                                          widgets.Label(' ',border=3)]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.Label('Referenca [m]:',border=3),u,\n                                          v]),\n                            widgets.HBox([period,START])])\nout2 = widgets.interactive_output(main_callback2, {'v':v, 'X0w':X0w, 'K':Kw, 'L':Lw,\n                                                   'eig1c':eig1c, 'eig2c':eig2c, 'eig3c':eig3c, 'eig4c':eig4c, \n                                                   'eig1o':eig1o, 'eig2o':eig2o, \n                                                   'u':u, 'period':period, 'selm':selm, 'selec':selec, 'seleo':seleo, 'selu':selu, 'simTime':simTime, 'DW':DW})\nout2.layout.height = '880px'\ndisplay(out2, alltogether2)\n```\n\n\n    Output(layout=Layout(height='880px'))\n\n\n\n    VBox(children=(HBox(children=(Dropdown(index=1, options=('Nastavi K in L', 'Nastavi lastne vrednosti'), value=\u2026\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "0cd1da319e9b4cd40e3abafa8a49a15b666d9499", "size": 28214, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_si/examples/04/SS-50-AUV_krmiljenje_globine.ipynb", "max_stars_repo_name": "ICCTerasmus/ICCT", "max_stars_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-22T18:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:10:22.000Z", "max_issues_repo_path": "ICCT_si/examples/04/SS-50-AUV_krmiljenje_globine.ipynb", "max_issues_repo_name": "ICCTerasmus/ICCT", "max_issues_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICCT_si/examples/04/SS-50-AUV_krmiljenje_globine.ipynb", "max_forks_repo_name": "ICCTerasmus/ICCT", "max_forks_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-24T11:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T16:36:18.000Z", "avg_line_length": 42.4270676692, "max_line_length": 322, "alphanum_fraction": 0.47214149, "converted": true, "num_tokens": 6619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158249943831703, "lm_q2_score": 0.10230471131390213, "lm_q1q2_score": 0.03494549899491816}}
{"text": "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Quick-Introduction-to-Okapi-BM25\" data-toc-modified-id=\"Quick-Introduction-to-Okapi-BM25-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Quick Introduction to Okapi BM25</a></span><ul class=\"toc-item\"><li><span><a href=\"#Gaining-Intuition-for-Okapi-BM25\" data-toc-modified-id=\"Gaining-Intuition-for-Okapi-BM25-1.1\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;</span>Gaining Intuition for Okapi BM25</a></span></li><li><span><a href=\"#Implementation\" data-toc-modified-id=\"Implementation-1.2\"><span class=\"toc-item-num\">1.2&nbsp;&nbsp;</span>Implementation</a></span></li><li><span><a href=\"#ElasticSearch-BM25\" data-toc-modified-id=\"ElasticSearch-BM25-1.3\"><span class=\"toc-item-num\">1.3&nbsp;&nbsp;</span>ElasticSearch BM25</a></span></li></ul></li><li><span><a href=\"#Reference\" data-toc-modified-id=\"Reference-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Reference</a></span></li></ul></div>\n\n\n```python\n# code for loading the format for the notebook\nimport os\n\n# path : store the current path to convert back to it later\npath = os.getcwd()\nos.chdir(os.path.join('..', 'notebook_format'))\n\nfrom formats import load_style\nload_style(plot_style=False)\n```\n\n\n\n\n<style>\n@import url('http://fonts.googleapis.com/css?family=Source+Code+Pro');\n@import url('http://fonts.googleapis.com/css?family=Vollkorn');\n@import url('http://fonts.googleapis.com/css?family=Arimo');\n@import url('http://fonts.googleapis.com/css?family=Fira_sans');\n\n    div.cell {\n        width: 1000px;\n        margin-left: 0% !important;\n        margin-right: auto;\n    }\n    div.text_cell code {\n        background: transparent;\n        color: #000000;\n        font-weight: 600;\n        font-size: 12pt;\n        font-style: bold;\n        font-family:  'Source Code Pro', Consolas, monocco, monospace;\n    }\n    h1 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n\t}\n\n    div.input_area {\n        background: #F6F6F9;\n        border: 1px solid #586e75;\n    }\n\n    .text_cell_render h1 {\n        font-weight: 200;\n        font-size: 30pt;\n        line-height: 100%;\n        color:#c76c0c;\n        margin-bottom: 0.5em;\n        margin-top: 1em;\n        display: block;\n        white-space: wrap;\n        text-align: left;\n    } \n    h2 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n        text-align: left;\n    }\n    .text_cell_render h2 {\n        font-weight: 200;\n        font-size: 16pt;\n        font-style: italic;\n        line-height: 100%;\n        color:#c76c0c;\n        margin-bottom: 0.5em;\n        margin-top: 1.5em;\n        display: block;\n        white-space: wrap;\n        text-align: left;\n    } \n    h3 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n    }\n    .text_cell_render h3 {\n        font-weight: 200;\n        font-size: 14pt;\n        line-height: 100%;\n        color:#d77c0c;\n        margin-bottom: 0.5em;\n        margin-top: 2em;\n        display: block;\n        white-space: wrap;\n        text-align: left;\n    }\n    h4 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n    }\n    .text_cell_render h4 {\n        font-weight: 100;\n        font-size: 14pt;\n        color:#d77c0c;\n        margin-bottom: 0.5em;\n        margin-top: 0.5em;\n        display: block;\n        white-space: nowrap;\n    }\n    h5 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n    }\n    .text_cell_render h5 {\n        font-weight: 200;\n        font-style: normal;\n        color: #1d3b84;\n        font-size: 16pt;\n        margin-bottom: 0em;\n        margin-top: 0.5em;\n        display: block;\n        white-space: nowrap;\n    }\n    div.text_cell_render{\n        font-family: 'Fira sans', verdana,arial,sans-serif;\n        line-height: 125%;\n        font-size: 115%;\n        text-align:justify;\n        text-justify:inter-word;\n    }\n    div.output_wrapper{\n        margin-top:0.2em;\n        margin-bottom:0.2em;\n    }\n\n    code{\n      font-size: 70%;\n    }\n    .rendered_html code{\n    background-color: transparent;\n    }\n    ul{\n        margin: 2em;\n    }\n    ul li{\n        padding-left: 0.5em; \n        margin-bottom: 0.5em; \n        margin-top: 0.5em; \n    }\n    ul li li{\n        padding-left: 0.2em; \n        margin-bottom: 0.2em; \n        margin-top: 0.2em; \n    }\n    ol{\n        margin: 2em;\n    }\n    ol li{\n        padding-left: 0.5em; \n        margin-bottom: 0.5em; \n        margin-top: 0.5em; \n    }\n    ul li{\n        padding-left: 0.5em; \n        margin-bottom: 0.5em; \n        margin-top: 0.2em; \n    }\n    a:link{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:visited{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:hover{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:focus{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:active{\n       font-weight: bold;\n       color:#447adb;\n    }\n    .rendered_html :link {\n       text-decoration: underline; \n    }\n    .rendered_html :hover {\n       text-decoration: none; \n    }\n    .rendered_html :visited {\n      text-decoration: none;\n    }\n    .rendered_html :focus {\n      text-decoration: none;\n    }\n    .rendered_html :active {\n      text-decoration: none;\n    }\n    .warning{\n        color: rgb( 240, 20, 20 )\n    } \n    hr {\n      color: #f3f3f3;\n      background-color: #f3f3f3;\n      height: 1px;\n    }\n    blockquote{\n      display:block;\n      background: #fcfcfc;\n      border-left: 5px solid #c76c0c;\n      font-family: 'Open sans',verdana,arial,sans-serif;\n      width:680px;\n      padding: 10px 10px 10px 10px;\n      text-align:justify;\n      text-justify:inter-word;\n      }\n      blockquote p {\n        margin-bottom: 0;\n        line-height: 125%;\n        font-size: 100%;\n      }\n</style>\n\n\n\n\n\n\n```python\nos.chdir(path)\n\nimport math\nimport json\nimport requests\n\n# 1. magic to print version\n# 2. magic so that the notebook will reload external python modules\n%load_ext watermark\n%load_ext autoreload\n%autoreload 2\n%watermark -a 'Ethen' -d -t -v -p requests\n```\n\n    Ethen 2018-11-17 17:24:06 \n    \n    CPython 3.6.4\n    IPython 6.4.0\n    \n    requests 2.20.1\n\n\n# Quick Introduction to Okapi BM25\n\nThe problem that **BM25 (Best Match 25)** tries to solve is similar to that of [TFIDF (Term Frequency, Inverse Document Frequency)](http://nbviewer.jupyter.org/github/ethen8181/machine-learning/blob/master/clustering/tfidf/tfidf.ipynb), that is representing our text in a vector space (it can be applied to field outside of text, but text is where it has the biggest presence) so we can search/find similar documents for a given document or query.\n\nThe gist behind TFIDF is that is relies on two main factors to determine whether a document is similar to our query.\n\n- Term Frequency aka tf: how often does the term occur in the document? 3 times? 10 times?\n- Inverse Document Frequency aka idf: measures how many documents the term appeared in. Inverse document frequency (1/df) then measures how special the term is. Is the term a very rare (occurs in just one doc) word? Or a relatively common one (occurs in nearly all the docs)?\n\nUsing these two factors, TFIDF measures the relative concentration of a term in a given piece of document. If the term is common in this article, but relatively rare elsewhere, then the TFIDF score will be high, and documents that have higher TFIDF score would be considered as very relevant to the search term.\n\nBM25 improves upon TFIDF by casting relevance as a probability problem. A relevance score, according to probabilistic information retrieval, ought to reflect the probability a user will consider the result relevant. Instead of going through how the formula was derived, here we'll take a look a the formula and try to digest it to see why it makes some kind of sense.\n\n## Gaining Intuition for Okapi BM25\n\n**BM25 (Best Match 25)** function scores each document in a corpus according to the document's relevance to a particular text query. For a query $Q$, with terms $q_1, \\ldots, q_n$, the BM25 score for document $D$ is:\n\n\n\\begin{align}\n\\mbox{BM25}(D, Q) = \\sum_{i=1}^n IDF(q_i, D) \\frac{f(q_i, D) \\cdot (k_1 + 1)}{f(q_i) + k_1 \\cdot (1-b + b \\cdot |D|/d_{avg}))}\n\\end{align}\n\nwhere:\n\n- $f(q_i, D)$ is the number of times term $q_i$ occurs in document $D$.\n- $|D|$ is the number of words in document $D$.\n- $d_{avg}$ is the average number of words per document.\n- $b$ and $k_1$ are hyperparameters for BM25.\n\nLet's break the formula down into smaller components to see why it makes sense.\n\n- First of all, there's $f(q_i, D)$ and $k_1$. $f(q_i, D)$ should match our intuition, as this means the more times the query term appears in the document, the higher the document's score will be. The interesting part is the **parameter $k_1$, which determines the term frequency saturation characteristic. The higher the value, the slower the saturation.** And when we say saturation, we are referring to the fact that if terms occurring extra times add extra score. We can observe this diminishing return in term frequency from the graph below.\n\n\n\n- Then $|D|/d_{avg}$ part in the denominator means a document that is longer than the average documents will result in a bigger denominator, resulting in a decrease in the score. The intuition is that the more terms in the document that does not match our input query - the lower the document's score should be. In other words, if a 300 page long document mentions the query term once, it's less likely to have as much to do with the query compared to a short tweet which mentions query once.\n\n\n\nFrom the graph above, we can see that shorter documents hit the asymptote much faster. Hopefully, this resembles our intuition as the more matches we have on shorter documents, the more certain we are about the relevance, whereas, for a lengthy book, it might take us longer to get to a point where we feel confident that the book is indeed relevant to the given query.\n\n- The parameter $b$ (bound 0.0 ~ 1.0) in the denominator is multiplied by the ratio of the document length we just discussed. **If $b$ is bigger, the effects of the document length compared to the average length are more amplified.** We can imagine if we set $b$ to 0, the effect of the length ratio would be completely nullified.\n\nAs for the inverse document frequency part, ${IDF}(q_i, D)$. For a corpus with $N$ documents, inverse document frequency for term $q_i$ is computed as follows:\n\n\\begin{align}\n\\mbox{IDF}(q_i, D) = \\log \\frac{N - N(q_i) + 0.5}{N(q_i) + 0.5}\n\\end{align}\n\nwhere\n\n- $N(q_i)$ is the number of documents in the corpus that contain term $q_i$.\n\nThe inverse document frequency part is very similar to that of TFIDF, whose role is to make sure that rarer words will have a higher score and contribute more to the final score.\n\nPlease note that the IDF formula listed above has a drawback when using it for terms appearing in more than half of the corpus since the value would come out as negative value, resulting in the overall score to become negative. e.g. if we have 10 documents in the corpus, and the term \"the\" appeared in 6 of them, its IDF would be $log(10 - 6 + 0.5 / 6 + 0.5) = log(4.5 / 6.5)$. Although we can argue that our implementation should have already removed these frequently appearing words as these words are mostly used to form a complete sentence and carry little meaning of note, different softwares/packages still make different adjustments to prevent a negative score from ever occurring. e.g.\n\n- Add a 1 to the equation.\n\n\\begin{align}\n\\mbox{IDF}(q_i) = \\log \\big( 1 + \\frac{N - N(q_i) + 0.5}{N(q_i) + 0.5} \\big)\n\\end{align}\n\n- For term that resulted in a negative IDF value, swap it with an small positive value, usually denoted as $\\epsilon$\n\nLike all hyperparameters in general, the default ones are usually a good starting point, and we should probably focus on tweaking other stuff before jumping into the rabbit hole of hyperparameter tuning. In the context of search, it might be making sure our ranking scores older documents lower in application such as news ranking. But if we were to start tuning, remember to always measure the performance of various settings and the following questions are general starting points that we can reference to.\n\n- For $k_1$, we should be asking, \"when do we think a term is likely to be saturated?\" For very long documents like books, it's very likely to have a lot of different terms appear several times in a work, even when the term isn't the primary subject of the document. We may not want terms to be saturated as quickly in this situation, so the suggestion is that $k_1$ should generally trend toward larger numbers when the text is a lot longer and more diverse. On the opposite side of things, it's been suggested to set $k_1$ on the lower side. It's very unlikely that a collection of short tweets would have a term multiple times without being highly related to that term.\n- For $b$, we should be asking, \"when do we think a document is likely to be very long, and when should that hinder its relevance to a term?\" Documents which are highly specific like engineering specifications or patents are lengthy in order to be more specific about a subject. Their length is unlikely to be detrimental to the relevance and lower $b$ may be more appropriate. On the other end of the spectrum, documents which touch on several different topics in a broad way \u2014 news articles (a political article may touch on economics, international affairs, and certain corporations), user reviews, etc. \u2014 often benefit by choosing a larger $b$ so that irrelevant topics to a user's search, including spam and the like, are penalized.\n\n## Implementation\n\n\n```python\n# we'll generate some fake texts to experiment with\ncorpus = [\n    'Human machine interface for lab abc computer applications',\n    'A survey of user opinion of computer system response time',\n    'The EPS user interface management system',\n    'System and human system engineering testing of EPS',\n    'Relation of user perceived response time to error measurement',\n    'The generation of random binary unordered trees',\n    'The intersection graph of paths in trees',\n    'Graph minors IV Widths of trees and well quasi ordering',\n    'Graph minors A survey'\n]\n\n# remove stop words and tokenize them (we probably want to do some more\n# preprocessing with our text in a real world setting, but we'll keep\n# it simple here)\nstopwords = set(['for', 'a', 'of', 'the', 'and', 'to', 'in'])\ntexts = [\n    [word for word in document.lower().split() if word not in stopwords]\n    for document in corpus\n]\n\n# build a word count dictionary so we can remove words that appear only once\nword_count_dict = {}\nfor text in texts:\n    for token in text:\n        word_count = word_count_dict.get(token, 0) + 1\n        word_count_dict[token] = word_count\n\ntexts = [[token for token in text if word_count_dict[token] > 1] for text in texts]\ntexts\n```\n\n\n\n\n    [['human', 'interface', 'computer'],\n     ['survey', 'user', 'computer', 'system', 'response', 'time'],\n     ['eps', 'user', 'interface', 'system'],\n     ['system', 'human', 'system', 'eps'],\n     ['user', 'response', 'time'],\n     ['trees'],\n     ['graph', 'trees'],\n     ['graph', 'minors', 'trees'],\n     ['graph', 'minors', 'survey']]\n\n\n\n\n```python\nclass BM25:\n    \"\"\"\n    Best Match 25.\n\n    Parameters\n    ----------\n    k1 : float, default 1.5\n\n    b : float, default 0.75\n\n    Attributes\n    ----------\n    tf_ : list[dict[str, int]]\n        Term Frequency per document. So [{'hi': 1}] means\n        the first document contains the term 'hi' 1 time.\n\n    df_ : dict[str, int]\n        Document Frequency per term. i.e. Number of documents in the\n        corpus that contains the term.\n\n    idf_ : dict[str, float]\n        Inverse Document Frequency per term.\n\n    doc_len_ : list[int]\n        Number of terms per document. So [3] means the first\n        document contains 3 terms.\n\n    corpus_ : list[list[str]]\n        The input corpus.\n\n    corpus_size_ : int\n        Number of documents in the corpus.\n\n    avg_doc_len_ : float\n        Average number of terms for documents in the corpus.\n    \"\"\"\n\n    def __init__(self, k1=1.5, b=0.75):\n        self.b = b\n        self.k1 = k1\n\n    def fit(self, corpus):\n        \"\"\"\n        Fit the various statistics that are required to calculate BM25 ranking\n        score using the corpus given.\n\n        Parameters\n        ----------\n        corpus : list[list[str]]\n            Each element in the list represents a document, and each document\n            is a list of the terms.\n\n        Returns\n        -------\n        self\n        \"\"\"\n        tf = []\n        df = {}\n        idf = {}\n        doc_len = []\n        corpus_size = 0\n        for document in corpus:\n            corpus_size += 1\n            doc_len.append(len(document))\n\n            # compute tf (term frequency) per document\n            frequencies = {}\n            for term in document:\n                term_count = frequencies.get(term, 0) + 1\n                frequencies[term] = term_count\n\n            tf.append(frequencies)\n\n            # compute df (document frequency) per term\n            for term, _ in frequencies.items():\n                df_count = df.get(term, 0) + 1\n                df[term] = df_count\n\n        for term, freq in df.items():\n            idf[term] = math.log(1 + (corpus_size - freq + 0.5) / (freq + 0.5))\n\n        self.tf_ = tf\n        self.df_ = df\n        self.idf_ = idf\n        self.doc_len_ = doc_len\n        self.corpus_ = corpus\n        self.corpus_size_ = corpus_size\n        self.avg_doc_len_ = sum(doc_len) / corpus_size\n        return self\n\n    def search(self, query):\n        scores = [self._score(query, index) for index in range(self.corpus_size_)]\n        return scores\n\n    def _score(self, query, index):\n        score = 0.0\n\n        doc_len = self.doc_len_[index]\n        frequencies = self.tf_[index]\n        for term in query:\n            if term not in frequencies:\n                continue\n\n            freq = frequencies[term]\n            numerator = self.idf_[term] * freq * (self.k1 + 1)\n            denominator = freq + self.k1 * (1 - self.b + self.b * doc_len / self.avg_doc_len_)\n            score += (numerator / denominator)\n\n        return score\n```\n\n\n```python\n# query our corpus to see which document is more relevant\nquery = 'The intersection of graph survey and trees'\nquery = [word for word in query.lower().split() if word not in stopwords]\n\nbm25 = BM25()\nbm25.fit(texts)\nscores = bm25.search(query)\n\nfor score, doc in zip(scores, corpus):\n    score = round(score, 3)\n    print(str(score) + '\\t' + doc)\n```\n\n    0.0\tHuman machine interface for lab abc computer applications\n    1.025\tA survey of user opinion of computer system response time\n    0.0\tThe EPS user interface management system\n    0.0\tSystem and human system engineering testing of EPS\n    0.0\tRelation of user perceived response time to error measurement\n    1.462\tThe generation of random binary unordered trees\n    2.485\tThe intersection graph of paths in trees\n    2.161\tGraph minors IV Widths of trees and well quasi ordering\n    2.507\tGraph minors A survey\n\n\nIn the code chunk above, we printed each corpus's BM25 relevance score along with the original text, note that this isn't sorted in decreasing order of the relevance score yet, which is usually what we want to do in a real world setting. That is to find the more relevant document, sort them in decreasing order and present them to the user. Also here, we are computing the scores for every document, this becomes computationally expensive when we start have a large corpus size. Thus search engine uses **inverted index** to speed things up. An inverted index consists of a list of all the unique words that appear in any document, and for each word, a list of the documents in which it appears, this allows us to quickly find the documents that contains the term in our query and only then do we compute the relevance score for this smaller recall set. This [link](https://www.elastic.co/guide/en/elasticsearch/guide/master/inverted-index.html) contains a good high level description of this concept. \n\n## ElasticSearch BM25\n\nWe can see BM25 in action to rank documents using ElasticSearch, this notebook isn't an ElasticSearch tutorial, so hopefully, the reader are some what familiar with the tool, if not, each code chunk contains links to some helpful references.\n\nWe will follow the standard process of creating the index to store our documents, add some sample documents to the index and provide a query against the index to return the relevant documents sorted in decreasing order based on the relevance score, which will be based on BM25.\n\n\n```python\n# installation instructions\n# https://www.elastic.co/guide/en/elasticsearch/reference/current/_installation.html\n\n# creating an index\n# https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html\nsettings = {\n    'settings': {\n        'index': {\n            'number_of_shards': 1,\n            'number_of_replicas': 1,\n\n            # configure our default similarity algorithm explicitly to use bm25,\n            # this allows it to use it for all the fields\n            'similarity': {\n                'default': {\n                    'type': 'BM25'\n                }\n            }\n        }\n    },\n    # we will be indexing our documents in the title field using the English analyzer,\n    # which removes stop words for us, the default standard analyzer doesn't have\n    # this preprocessing step\n    # https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis.html\n    'mappings': {\n        # this key is the \"type\", which will be explained in the next code chunk\n        '_doc': {\n            'properties': {\n                'title': {\n                    'type': 'text',\n                    'analyzer': 'english'\n                }\n            }\n        }\n    }\n}\nheaders = {'Content-Type': 'application/json'}\nresponse = requests.put('http://localhost:9200/experiment', data=json.dumps(settings), headers=headers)\nresponse\n```\n\n\n\n\n    <Response [200]>\n\n\n\n\n```python\n# indexing document\n# https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html\n# https://www.elastic.co/guide/en/elasticsearch/guide/master/index-doc.html\n\n# a document is uniquely identified by the index, the type and id\n# it's worth noting that there's a note on removing the capabilities of\n# having multiple types under one index, and going forward the type will\n# just to set to '_doc'\n# https://www.elastic.co/guide/en/elasticsearch/reference/current/removal-of-types.html\nurl = 'http://localhost:9200/experiment/_doc'\n\nfor document in corpus:\n    # we insert the document into the 'title' field\n    data = {'title': document}\n    response = requests.post(url, data=json.dumps(data), headers=headers)\n    \nresponse\n```\n\n\n\n\n    <Response [201]>\n\n\n\n\n```python\ndef search(query, headers):\n    url = 'http://localhost:9200/experiment/_doc/_search'\n    response = requests.get(url, data=json.dumps(query), headers=headers)\n    \n    # the response contains other information, such as time it took to\n    # give the response back, here we are only interested in the matched\n    # results, which are stored under 'hits'\n    search_hits = json.loads(response.text)['hits']['hits']\n\n    print('Num\\tRelevance Score\\tTitle')\n    for idx, hit in enumerate(search_hits):\n        print('%s\\t%s\\t%s' % (idx + 1, hit['_score'], hit['_source']['title']))\n```\n\n\n```python\n# match query\n# https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html\nquery = {\n    'query': {\n        'match': {\n            # search against the 'title' field\n            'title': 'The intersection of graph survey and trees'\n        }\n    }\n}\nsearch(query, headers={'Content-Type': 'application/json'})\n```\n\n    Num\tRelevance Score\tTitle\n    1\t4.572298\tThe intersection graph of paths in trees\n    2\t3.0325541\tGraph minors A survey\n    3\t1.814194\tGraph minors IV Widths of trees and well quasi ordering\n    4\t1.2758815\tA survey of user opinion of computer system response time\n    5\t1.1110051\tThe generation of random binary unordered trees\n\n\n\n```python\n# we can delete this experimental index to prevent occupying space\nresponse = requests.delete('http://localhost:9200/experiment')\nresponse\n```\n\n\n\n\n    <Response [200]>\n\n\n\n# Reference\n\n- [Wiki: Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25)\n- [Blog: BM25 The Next Generation of Lucene Relevance](https://opensourceconnections.com/blog/2015/10/16/bm25-the-next-generation-of-lucene-relevation/)\n- [Blog: Practical BM25 - Part 1: How Shards Affect Relevance Scoring in Elasticsearch](https://www.elastic.co/blog/practical-bm25-part-1-how-shards-affect-relevance-scoring-in-elasticsearch)\n- [Blog: Practical BM25 - Part 2: The BM25 Algorithm and its Variables](https://www.elastic.co/blog/practical-bm25-part-2-the-bm25-algorithm-and-its-variables)\n- [Blog: Practical BM25 - Part 3: Considerations for Picking b and k1 in Elasticsearch](https://www.elastic.co/blog/practical-bm25-part-3-considerations-for-picking-b-and-k1-in-elasticsearch)\n", "meta": {"hexsha": "52124fbbcd2e82fdb8d7184962b516bfce7f4746", "size": 36341, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "search/bm25_intro.ipynb", "max_stars_repo_name": "certara-ShengnanHuang/machine-learning", "max_stars_repo_head_hexsha": "d21dfbeabf2876ffe49fcef444ca4516c4d36df0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2104, "max_stars_repo_stars_event_min_datetime": "2016-04-15T13:35:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T10:39:51.000Z", "max_issues_repo_path": "search/bm25_intro.ipynb", "max_issues_repo_name": "certara-ShengnanHuang/machine-learning", "max_issues_repo_head_hexsha": "d21dfbeabf2876ffe49fcef444ca4516c4d36df0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-04-07T14:25:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-18T03:16:15.000Z", "max_forks_repo_path": "search/bm25_intro.ipynb", "max_forks_repo_name": "certara-ShengnanHuang/machine-learning", "max_forks_repo_head_hexsha": "d21dfbeabf2876ffe49fcef444ca4516c4d36df0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 539, "max_forks_repo_forks_event_min_datetime": "2015-12-10T04:23:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:15:28.000Z", "avg_line_length": 40.9706877114, "max_line_length": 1009, "alphanum_fraction": 0.5446190253, "converted": true, "num_tokens": 6362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3174262655876759, "lm_q2_score": 0.10970577096716554, "lm_q1q2_score": 0.03482349319152423}}
{"text": "# Python part (Jupyter notebook) for the text in $\\LaTeX$\n\n__Closed tasks__\n1. Define input data\n1. Section of all algorithms (functions)\n1. Implicit calculations of global variables changed into functions\n1. Unit testing\n1. Function ```f_update_nodes_edges(d_TS)``` that updates ```df_node``` and ```df_edge``` with t_theta(v) = 0 and t_theta(e) = 0\n1. Prepare different input data, different input files for ```d_TS_H```\n1. Input data and expected results\n1. Tested function ```f_test_weight_redesign```\n1. Tested function ```f_TP_min_deduplication```\n1. Tested function ```f_TP_max_deduplication```\n1. f_draw_TP_max_deduplication : unit test\n1. f_draw_TP_min_deduplication : unit test\n1. Draw all vertices in test phase. ```df_node``` defines vertices over definition of test phase\n1.  ```f_test_weight_redesign``` : \n1. Algorithm 2 Test Weights Redesign\n1. General\n    - [x] Is singleton allowed?\n        * *Answer*: Singleton is functionality with unit testing that is not a part of *testing*\n    - [x] If edges are removed, what about nodes?\n        * *Answer*: Nodes should not be removed.\n1. ```f_test_weight_redesign_wrapper``` : add argument for test suite\n1. Soft result in function ```f_TP_min_deduplication```\n1. Soft result in function ```f_TP_max_deduplication```\n1.  Add ```d_position``` to file and to parameter\n1. Check reading test suites and test phase from file\n1. f_draw_TP_max_deduplication : various results\n\n---\n__References__\n1. https://www.tutorialspoint.com/jupyter/jupyter_notebook_editing.htm\n1. https://matplotlib.org/3.1.1/gallery/color/named_colors.html\n1. https://networkx.github.io/documentation/stable/auto_examples/drawing/plot_labels_and_colors.html\n1. https://networkx.github.io/documentation/stable/reference/generated/networkx.drawing.nx_pylab.draw_networkx_labels.html\n1. https://networkx.github.io/documentation/stable/auto_examples/drawing/plot_weighted_graph.html?highlight=weights\n1. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.tolist.html\n1. https://www.datacamp.com/community/tutorials/tutorial-jupyter-notebook\n1. https://github.com/jupyter/jupyter/wiki/A-gallery-of-interesting-Jupyter-Notebooks\n\n-----\n\n{\n\u201c@context\u201d: \u201chttp://schema.org\u201d,\n\u201c@type\u201d: \u201cPerson\u201d,\n\u201cname\u201d: \u201cDaniel S. Katz\u201d,\n\u201c@id\u201d: \u201chttp://orcid.org/0000-0001-5934-7525\u201d\n}\n\n## Introduction and basic definitions\n\n### Execution time measurement\n\n\n```python\n# Masure Time\nimport time\nimport datetime\nnotebook_start_time = time.time()\n```\n\n### Ignore Mathlab Warnings\nError example:\n```\nC:\\ProgramData\\Anaconda3\\lib\\site-packages\\networkx\\drawing\\nx_pylab.py:579: MatplotlibDeprecationWarning: \nThe iterable function was deprecated in Matplotlib 3.1 and will be removed in 3.3. Use np.iterable instead.\n  if not cb.iterable(width):\n```\n\n\n```python\n#\n# to avoid Mathlab warning\n#\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=UserWarning)\n```\n\n### Unit testing\n\n\n```python\nimport unittest\n```\n\n### Debug\n\n\n```python\nfrom IPython.core.debugger import set_trace\n\n```\n\n### Logging\n\n\n```python\nimport logging\n\n# name for the logging (logger) and handler to the logger\nlogger = logging.getLogger(__name__)\n\n# the logger's level\n#    10 DEBUG: Detailed debug information, typically of interest only when diagnosing problems\n#    20 INFO: Confirmation that things are working as expected\n#    30 WARNING: An indication that something unexpected happened, or indicative of some problem in the near future (e.g. \u2018disk space low\u2019). The software is still working as expected\n#    40 ERROR: Due to a more serious problem, the software has not been able to perform some function\n#    50 CRITICAL: A serious error, indicating that the program itself may be unable to continue running\nlogger.setLevel(logging.WARNING)\n\n# logger file\nfile_handler = logging.FileHandler('MinImplCosts.log')\nlogger.addHandler(file_handler)\n\n# format - see https://docs.python.org/3/library/logging.html#logging.LogRecord\nformatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')\nfile_handler.setFormatter(formatter)\n\n#\n# Debug individual cell ONLY\n#\ncell_log_level = logging.WARNING\n\n#\n# Debug individual section ONLY\n#\nsection_log_level = logging.DEBUG\nsection_log_level = logging.WARNING\n\n```\n\n\n```python\n#\n# Draw test suites condition to \"draw graphs\"\n#\nbool_draw_TS = True\n# bool_draw_TS = False\n\n#\n# print to console\n#\n\n#ch = logging.StreamHandler()\n#ch.setLevel(logging.DEBUG)\n#ch.setFormatter(formatter)\n#logger.addHandler(ch)\n```\n\n### Basic Imports\n\n\n```python\n#\n# Imports\n#\n\nimport pandas\nimport networkx\nfrom matplotlib import pyplot\nimport matplotlib\n```\n\n\n```python\n# To create directory\nimport errno\nimport os\n```\n\n\n```python\n#\n# to get display function for Python without Jupyter notebook\n#\nfrom IPython.display import display, Math\n```\n\n\n```python\n#\n# to display wide columns\n#\n\npandas.set_option('display.max_columns', None)  \npandas.set_option('display.expand_frame_repr', False)\npandas.set_option('max_colwidth', -1)\n\n```\n\n    C:\\Users\\gregor.CT\\.conda\\envs\\oip\\lib\\site-packages\\ipykernel_launcher.py:7: FutureWarning: Passing a negative integer is deprecated in version 1.0 and will not be supported in future version. Instead, use None to not limit the column width.\n      import sys\n\n\n### Note about Representation Error\n\nOn the https://docs.python.org/3/tutorial/floatingpoint.html:\n\n_Also, since the 0.1 cannot get any closer to the exact value of 1/10 and 0.3 cannot get any closer to the exact value of 3/10, then pre-rounding with ```round()``` function cannot help:_\n\n```python\n>>> round(.1, 1) + round(.1, 1) + round(.1, 1) == round(.3, 1)\nFalse\n```\n\n\n```python\nstr(datetime.timekappa(seconds=666))\nprint(\"Notebook execution: \" + str(datetime.timekappa(seconds=(time.time()-notebook_start_time)))) \n```\n\n## Input Data\n\n### Constants\n\n\n```python\n# constant for \"Excel\" file delimiter\ns_c_graph_data_delimiter = ',';\n```\n\n\n```python\n# folder for results for article\ns_c_results = 'results/';\n# folder for other results not needed for article\ns_c_results_other = 'pdf/';\n```\n\n\n```python\n# constants for figure dimensions (t_c ... tuple constant)\nt_c_test_phase_dim = (50,6);\nt_c_test_phase_dim = (110,6);\nt_c_test_phase_dim = (70,7);\n```\n\n### Create output directories\n\n\n```python\nos.makedirs(s_c_results, exist_ok=True);\nos.makedirs(s_c_results+s_c_results_other, exist_ok=True);\n```\n\n### Definition ```d_position```\n\nVariable d_position is (should be) written in a file for definition of graph nodes\n\n\n```python\n# Explicitly defined positions\n# d_position = {1: (0,0), 2: (1,0), 3: (1,1), 4: (0,1), 5: (-0.5,0.5), 6:(1.5,0.5)}\n```\n\n### Definition ```d_node_label```\n\nDone: add d_node_label to file - ```f_read_data_from_files``` generates globals: ```d_edge_label```,  ```d_node_label```\n# labels for nodes in LaTeX math\n# Raw string format r'string' assures that all backslashes are left in the string\nd_node_label = {};\nd_node_label[1] = r'$v_1$';\nd_node_label[2] = r'$v_2$';\nd_node_label[3] = r'$v_3$';\nd_node_label[4] = r'$v_4$';\nd_node_label[5] = r'$v_5$';\nd_node_label[6] = r'$v_6$';\n\n# graph values for labels for nodes\n# d_node_label = df_node[\"delta\"]\n### Definition ```d_edge_label```\n\nDone: add d_edge_label to file - ```f_read_data_from_files``` generates globals: ```d_edge_label```,  ```d_node_label```\n# labels for edges in LaTeX math\n# d_edge_label = {};\nd_edge_label={\n    (1,2):r'$e_{1,2}$',\n    (1,3):r'$e_{1,3}$',\n    (1,4):r'$e_{1,4}$',\n    (2,3):r'$e_{2,3}$',\n    (3,4):r'$e_{3,4}$',\n};\n\nd_edge_label={\n    (1,2):r'$e_1$',\n    (1,3):r'$e_2$',\n    (1,4):r'$e_5$',\n    (2,3):r'$e_3$',\n    (3,4):r'$e_4$',\n};\n\nd_edge_label={\n    (1,2):r'$e_1$',\n    (1,3):r'$e_2$',\n    (1,4):r'$e_5$',\n    (2,3):r'$e_3$',\n    (3,4):r'$e_4$',\n    (5,2):r'$e_6$',\n    (5,4):r'$e_7$',\n    (6,2):r'$e_8$',\n    (6,4):r'$e_9$',\n};\n\n# graph values for labels for edges\n# d_edge_label=df_edge[\"delta\"];\n### Definition ```n_font_size```\nSize of font for drawing.\n\n\n```python\n# Font size for labels\n# n_font_size = 36;\nn_font_size = 50;\n```\n\n\n```python\nstr(datetime.timedelta(seconds=666))\nprint(\"Notebook execution: \" + str(datetime.timedelta(seconds=(time.time()-notebook_start_time)))) \n```\n\n## Definition of Functions\n\nUnit testing\n* [f_draw_TP_min_deduplication](#f_draw_TP_min_deduplication)\n\n\n### Function ```f_debug_start_with_function``` ```f_debug_end_with_function```\n\n\n```python\ndef f_debug_start_with_function(s_function_name):\n    logger.info('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~> ' + str(s_function_name))\n```\n\n\n```python\ndef f_debug_end_with_function(s_function_name):\n    logger.info('<.......................................................... ' + str(s_function_name))\n```\n\n### Function ```f_set_from_list_list```\n\n\n```python\n#\n# Function f_set_from_list_list\n#\n# Input\n#  list of lists\n#\n# Return\n#  Set of elemetns from flatten list for 1 level\n#\nf_set_from_list_list = lambda l: set(\n    [\n        item\n        for sublist in l\n        for item in sublist\n    ]\n)\n```\n\n### Function ```f_set_nodes(d_TP, s_suite_name)```\n\n\n```python\n#\n# Function f_set_nodes\n#\n# Input\n#   d_TP         .. test phases presented as a dictionary of test suites\n#   s_suite_name .. test suite name\n#\n# Return\n#  Set of nodes in test suite\n#\ndef f_set_nodes(d_TP, s_suite_name):\n    return(\n        set.union(*list(map(set,d_TP[s_suite_name])))\n    )\n```\n\n### Function ```f_list_nodes(d_TP, s_suite_name)```\n\n\n```python\n#\n# Function f_list_nodes\n#\n# Input\n#   d_TP         .. test phases presented as a dictionary of test suites\n#   s_suite_name .. test suite name\n#\n# Return\n#  List of nodes in test suite\n#\ndef f_list_nodes(d_TP, s_suite_name):\n    l_tmp_list = [];\n    \n    l_tmp_list = list(map(set,d_TP[s_suite_name]));\n    \n    # check empty list\n    if not l_tmp_list:\n        return(l_tmp_list);\n    else:\n        return(\n            list(set.union(*l_tmp_list))\n        )\n```\n\n### Function ```f_set_edges(d_TP, s_suite_name)```\n\n\n```python\n#\n# Function f_set_edges\n#\n# Input\n#   d_TP         .. test phases presented as a dictionary of test suites\n#   s_suite_name .. test suite name\n#\n# Return\n#  Set of edges in test suite\n#\ndef f_set_edges(d_TP, s_suite_name):\n    return(\n        set(d_TP[s_suite_name])\n    )\n```\n\n### Function ```f_list_edges(d_TP, s_suite_name)```\n\n\n```python\n#\n# Function f_list_edges\n#\n# Input\n#   d_TP         .. test phases presented as a dictionary of test suites\n#   s_suite_name .. test suite name\n#\n# Return\n#  List of edges in test suite\n#\ndef f_list_edges(d_TP, s_suite_name):\n    return(\n        d_TP[s_suite_name]\n    )\n```\n\n### Function ```f_get_TS_weight```\n\nNote about the implementation: Warning referenced to __Returning a view versus a copy__\n\nSolution:\nReference to an element in data frame ```df.at['line','column']``` and not ```df['column'].loc[line]``` or ```df['column']['line']```\n\n\n\n```python\n#\n# f_get_TS_weight\n#\n# Results:\n#  1. Creates data frame with weighted TS that defines test phase\n#  4. Dictionary weights values for test phase\n#\n# GLOBAL results:\n#  2. In df_node and df_edge update (or add) values (columns)\n#   - delta\n#   - epsilon    \n#  3. In df_node and df_edge set values to 0 for t_kappa and t_theta for nodes and edges\n#     that are not a part of d_TP\n\n# 2019-12-18\n# problem: access to df_edge['kappa']\n\n\ndef f_get_TS_weight(d_TP):\n    global df_node\n    global df_edge\n    f_debug_start_with_function(\"f_get_TS_weight\")\n\n    # set_trace()\n    \n    # -----------------------------------------\n    # 1.\n    # Add (or update) values for \n    #    delta\n    #    epsilon    \n    f_get_graph_weights(df_node,df_edge)\n    #\n    # -----------------------------------------\n    \n    # -----------------------------------------\n    # 2.\n    \n    # create data frame with set of TS\n    df_TPs_weight = f_get_dataframe_from_dictionary(d_TP)\n\n    logger.debug(\"df_TPs_weight from dictionary d_TP:\")\n    logger.debug(df_TPs_weight)\n    \n    # Definition of columns\n    df_TPs_weight[\"kappa\"] = 0\n    df_TPs_weight[\"theta\"] = 0\n    df_TPs_weight[\"delta\"] = 0\n    df_TPs_weight[\"epsilon\"] = 0.0 # IMPORTANT: define float64 data type\n    df_TPs_weight[\"size\"] = 0\n\n    # kappa measure for test suite = kappa measure for test phase\n#    n_TP_kappa = f_kappa_measure(d_TP)\n\n    for s_TS_name in list(d_TP.keys()):\n        logger.debug(str(s_TS_name) + \":\")\n        df_TPs_weight.at[s_TS_name,'theta'  ]=     f_theta_measure(d_TP, s_TS_name)\n        df_TPs_weight.at[s_TS_name,'delta']=f_delta_measure_TS(d_TP, s_TS_name)\n\n        # 2020-04-25\n        df_TPs_weight.at[s_TS_name,'epsilon']=   f_epsilon_measure(d_TP, s_TS_name)\n        df_TPs_weight.at[s_TS_name,'kappa'  ]=     f_kappa_measure(d_TP, s_TS_name)\n        \n        # add weight \"size of TP\" (it is number of edges)\n        df_TPs_weight.at[s_TS_name, 'size']=len(df_TPs_weight['TS_edges'].loc[s_TS_name])\n        logger.debug(\" edges=\"+str(df_TPs_weight['size'].loc[s_TS_name]))\n\n    # kappa measure for test suite = kappa measure for test phase\n#    for s_TS_name in list(d_TP.keys()):\n#        df_TPs_weight.at[s_TS_name,'kappa'  ]=n_TP_kappa\n    \n    logger.debug(\"df_TPs_weight with calculated weights:\")\n    logger.debug(df_TPs_weight)\n    \n    #\n    # -----------------------------------------\n    \n    # -----------------------------------------\n    # 3.\n    #\n    # Nodes and edges that are not a part of ```d_TP```\n    # should have a special value for test (implementation) status: 0\n    # It means that they should not be developed and should not be tested - they are out of scope.\n    #\n    \n    #\n    # get set of edges from dictionary ```d_TS_H```\n    #\n    set_edges_d_TS = f_set_from_list_list(\n        list(d_TS_H.values())\n    )\n\n    #\n    # get set of edges from data frame ```df_edge```\n    #\n    set_edges_df_edge = set((list(df_edge.to_dict().values())[0]).keys())\n\n    #\n    # get set of edges from data frame ```df_edge``` and not from dictionary ```d_TS_H```\n    #\n    set_edges_only_df_edge = set_edges_df_edge - set_edges_d_TS\n    \n    #\n    # update data frame ```df_edge``` according to edges that are not in ```d_TS_H```\n    #\n    for t_the_edge in set_edges_only_df_edge:\n        logger.debug(\"t_theta(\"+str(t_the_edge)+\") = 0\")\n        df_edge.at[t_the_edge,'t_theta'] = 0\n        logger.debug(\"t_kappa(\"+str(t_the_edge)+\") = 0\")\n        df_edge.at[t_the_edge,'t_kappa'] = 0\n\n    #\n    # get set of nodes from dictionary ```d_TS_H```\n    #\n    set_nodes_d_TS = f_set_from_list_list(set_edges_d_TS)\n#    f_print_var_value('set_nodes_d_TS')\n    \n    #\n    # get set of nodes from data frame ```df_node```\n    #\n    set_nodes_df_node = set((list(df_node.to_dict().values())[0]).keys())\n#    f_print_var_value('set_nodes_df_node')\n    \n    #\n    # get set of nodes from data frame ```df_node``` and not from dictionary ```d_TS_H```\n    #\n    set_nodes_only_df_node = set_nodes_df_node - set_nodes_d_TS\n#    f_print_var_value('set_nodes_only_df_node')\n    #\n    # update data frame ```df_node``` according to nodes that are not in ```d_TS_H```\n    #\n    for n_the_node in set_nodes_only_df_node:\n        logger.debug(\"t_theta(\"+str(n_the_node)+\") = 0\")\n        df_node.at[n_the_node,'t_theta'] = 0\n        logger.debug(\"t_kappa(\"+str(n_the_node)+\") = 0\")\n        df_node.at[n_the_node,'t_kappa'] = 0\n    #\n    # -----------------------------------------\n\n    # -----------------------------------------\n    # 4.\n    # Add a special row named TP_WEIGHT = \"TP_weight\" for measure values for test phase\n    # kappa measure for test suite = kappa measure for test phase\n    # d_TP_weight\n    \n    d_TP_weight = {}\n    \n    # 'kappa' weights for all/each test suites are the same: take/get the first one\n#    d_TP_weight['kappa'] = n_TP_kappa\n    \n    d_TP_weight['theta'] = 0\n    for s_TS_name in list(d_TP.keys()):\n        d_TP_weight['theta'] += df_TPs_weight.at[s_TS_name,'theta']\n\n    d_TP_weight['delta'] = f_delta_measure_TP(d_TP)\n                                                    \n    d_TP_weight['epsilon'] = 0\n    for n_e in df_edge['epsilon']:\n        d_TP_weight['epsilon'] += n_e\n    for n_v in df_node['epsilon']:\n        d_TP_weight['epsilon'] += n_v\n    \n    #\n    # -----------------------------------------\n\n    f_debug_end_with_function(\"f_get_TS_weight\")\n    return(df_TPs_weight,d_TP_weight)\n```\n\n### Function ```f_get_dataframe_from_dictionary(d_x)```\nFunction ```f_get_dataframe_from_dictionary``` creates test phase presented as data frame with test suites from ```d_x```.\n\n\n```python\n#\n# f_get_dataframe_from_dictionary\n#\n# Create data frame with set of test suites defined in dictionary d_x\n#\n# input\n#  d_x\n#\n# output/return\n#  df_TP_edges_H with infos about graph edges\n#\n\ndef f_get_dataframe_from_dictionary(d_x):\n    f_debug_start_with_function(\"f_get_dataframe_from_dictionary\")\n    \n    #\n    # Definition of dataframe ```df_TP_edges_H``` reate local variabl\n    #\n    df_TP_edges_H = pandas.DataFrame(index=d_x)\n\n    #\n    # Add column 'TS_edges' to data frame\n    #\n    df_TP_edges_H['TS_edges'] = list(d_x.values())\n\n    f_debug_end_with_function(\"f_get_dataframe_from_dictionary\")\n    return(df_TP_edges_H)\n```\n\n### Function ```f_draw_graph_TP_pure(.,.,.,.,.,.,.)```\n\n\n```python\n#\n# input parameter:\n# * Hx ... index (string, name) to supbraph edges in d_TS_H[] dictionary\n# * d_TS_H ... edges for TS stored as Python dictionary Output\n# * df_edge ... graph edges for functionality graph\n# * d_node_label ... labels for all nodes\n# * d_edge_label ... labels for all edges\n# * n_font_size ... font size\n# * my_base_file_name\n# * d_position ... dictionary for possition of drawing\n#\ndef f_draw_graph_TP_pure(\n    my_Hx,\n    d_TS_H,\n    df_edge,\n    d_local_node_label,\n    d_local_edge_label,\n    n_font_size,\n    d_position,\n    s_node_color,\n    s_edge_color,\n    n_alpha=1,\n    t_c_test_phase_dim=t_c_test_phase_dim,\n    bool_print_to_terminal = True\n):\n    f_debug_start_with_function(\"f_draw_graph_TP_pure\")\n    \n    logger.debug(str(type(d_TS_H)))\n    \n    n_graph_node_size = 8000\n    \n    # sub graph and complement to sub graph\n    nxg_G = networkx.Graph(df_edge.index.tolist())\n    nxg_sub_graph = networkx.Graph(df_edge.index.tolist()).edge_subgraph(d_TS_H[my_Hx])\n    nxg_complementary_sub_graph = nxg_G.edge_subgraph(list(set(df_edge.index.tolist()) - set(d_TS_H[my_Hx])))\n    \n    # specify the size (and the proportion)\n    pyplot.figure(1,figsize=t_c_test_phase_dim)\n    \n    '''\n    logger.debug('TP (nodes - edges):' +\n          str(nxg_sub_graph.nodes) + '-' +\n          str(nxg_sub_graph.edges)\n    )\n    logger.debug('Complementary TP (nodes - edges):' +\n          str(nxg_complementary_sub_graph.nodes) + '-' +\n          str(nxg_complementary_sub_graph.edges)\n    )\n    '''\n    d_pos = d_position;\n    \n    # -------------------------------------------------\n    # draw TP edges - blue 99%\n    \n#     Gedges = networkx.Graph()\n#     Gedges.add_edges_from(nxg_G)\n    # draw edges and nodes - no need to draw nodes (TODO: don't draw nodes)\n    networkx.draw(\n        nxg_sub_graph,\n        d_pos,\n        labels={},\n        node_color=s_node_color, #'lightskyblue',\n#        edge_color='lightskyblue',\n        edge_color = s_edge_color, #'aliceblue', #'lightbluegrey',\n        width=8,\n        node_size=n_graph_node_size*0.8,\n        alpha=n_alpha, # transparency (default=1.0)\n    );\n    \n    # draw complementary graph edges - silver 100%\n    networkx.draw(\n        nxg_complementary_sub_graph,\n        d_pos,\n        labels={},\n        node_color='silver',\n        edge_color='silver',\n        style='dotted', # (solid|dashed|dotted|dashdot)\n        width=8,\n        node_size=n_graph_node_size,\n        # alpha=0.4,\n    );\n\n    # draw all nodes silver 99%, alpha=1\n    # noded only from TP\n    Gnodes = networkx.Graph()\n    Gnodes.add_nodes_from(nxg_G)    \n    networkx.draw(\n        Gnodes,\n        d_pos,\n        labels={},\n        node_color = 'silver',\n        edge_color = 'silver',\n        node_size=n_graph_node_size*1,\n        # alpha=0.4,\n    );\n    \n    '''\n    # 2019-12-17: no complementary graph nodes\n    # draw complementary graph nodes 80%\n    Gnodes = networkx.Graph()\n    # Gnodes.add_nodes_from(nxg_complementary_sub_graph)    \n    Gnodes.add_nodes_from(nxg_G)\n    networkx.draw(\n        Gnodes,\n        d_pos,\n        labels={},\n        node_color = 'white',\n        node_size=n_graph_node_size*0.8,\n        # alpha=0.4,\n    );\n    '''\n    \n    # draw TP graph nodes 80%\n    Gnodes = networkx.Graph()\n    # 2019-12-17: Gnodes.add_nodes_from(nxg_sub_graph)\n    Gnodes.add_nodes_from(nxg_G) # 2019-12-17\n    networkx.draw(\n        Gnodes,\n        d_pos,\n        labels={},\n        font_size = n_font_size,\n        font_color = 'black',\n#        node_color = 'lightskyblue',\n#        node_color = '#B7C9E2', #'lightbluegrey',\n        node_color = s_node_color, #'aliceblue', #'lightbluegrey',\n        node_size=n_graph_node_size*0.8,\n        alpha=n_alpha, # transparency (default=1.0)\n    );\n    \n    # -------------------------------------------------\n    # Labels\n    # Problem: cannot draw labels for TS only\n    # -------------------------------------------------\n    \n    #\n    # remove labels from 'd_local_node_label' for nodes that are not in TP 'nxg_sub_graph'\n    #\n    logger.debug('d_local_node_label = ' + str(d_local_node_label))\n    d_node_label_copy = d_local_node_label.copy()\n    logger.debug('d_node_label_copy = ' + str(d_node_label_copy))\n    for n_v in d_local_node_label:\n        if n_v not in nxg_sub_graph.nodes:\n            logger.debug(n_v)\n            #d_local_node_label = d_local_node_label.drop(labels=n_v)    \n            del d_node_label_copy[n_v]\n    \n    # node labels\n    networkx.draw_networkx_labels(\n        # 2019-12-17: no complementary graph nodes\n        # 2019-12-17: nxg_sub_graph, # TP\n        nxg_G,\n        #Gnodes, # all graphs\n        d_pos,\n        font_family = 'Times New Roman',\n        # 2019-12-17: no complementary graph nodes\n        # 2019-12-17: labels=d_node_label_copy,\n        labels=d_local_node_label,\n        font_size = n_font_size,\n        font_color = 'black',\n    );\n    \n    #\n    # remove labels from 'd_local_edge_label' for nodes that are not in TP 'nxg_sub_graph'\n    #\n    logger.debug('d_local_edge_label = ' + str(d_local_edge_label))\n    d_edge_label_copy = d_local_edge_label.copy()\n    logger.debug('d_edge_label_copy = ' + str(d_edge_label_copy))\n    for n_e in d_local_edge_label:\n        if n_e not in nxg_sub_graph.edges:\n            logger.debug(n_e)\n            #d_local_edge_label = d_local_edge_label.drop(labels=n_e)\n            del d_edge_label_copy[n_e]\n\n    # edge labels\n    networkx.draw_networkx_edge_labels(\n        nxg_sub_graph, # TP\n        #Gnodes, # all graphs\n#        nxg_G,\n        d_pos,\n        d_edge_label_copy,\n        0.5, # label_pos (float) \u2013 Position of edge label along edge (0=head, 0.5=center, 1=tail)\n        font_size = n_font_size,\n        font_family = 'Times New Roman',\n        bbox=dict(boxstyle=\"circle,pad=0.1\",fc=\"w\",ec=\"w\"), # style for edge labels\n    );\n    # valid strings are ['dejavusans', 'dejavuserif', 'cm', 'stix', 'stixsans', 'custom']\n    pyplot.rcParams['mathtext.fontset'] = 'stix';\n    \n    f_debug_end_with_function(\"f_draw_graph_TP_pure\")\n```\n\n\n```python\n#\n# input parameter:\n# * Hx ... index (string, name) to supbraph edges in d_TS_H[] dictionary\n# * d_TS_H ... edges for TS stored as Python dictionary Output\n# * df_edge ... graph edges for functionality graph\n# * d_node_label ... labels for all nodes\n# * d_edge_label ... labels for all edges\n# * n_font_size ... font size\n# * my_base_file_name\n# * d_position ... dictionary for possition of drawing\n#\n# 2020-07-31\n#\ndef f_draw_graph_TP_pure(\n    my_Hx,\n    d_TS_H,\n    df_edge,\n    d_local_node_label,\n    d_local_edge_label,\n    n_font_size,\n    d_position,\n    s_node_color,\n    s_edge_color,\n    n_alpha=1,\n    t_c_test_phase_dim=t_c_test_phase_dim,\n    bool_print_to_terminal = True\n):\n    f_debug_start_with_function(\"f_draw_graph_TP_pure\")\n    \n    logger.debug(str(type(d_TS_H)))\n    \n    n_graph_node_size = 8000\n    \n    # sub graph and complement to sub graph\n    nxg_G = networkx.Graph(df_edge.index.tolist())\n    nxg_sub_graph = networkx.Graph(df_edge.index.tolist()).edge_subgraph(d_TS_H[my_Hx])\n    nxg_complementary_sub_graph = nxg_G.edge_subgraph(list(set(df_edge.index.tolist()) - set(d_TS_H[my_Hx])))\n    \n    # specify the size (and the proportion)\n    pyplot.figure(1,figsize=t_c_test_phase_dim)\n    \n    '''\n    logger.debug('TP (nodes - edges):' +\n          str(nxg_sub_graph.nodes) + '-' +\n          str(nxg_sub_graph.edges)\n    )\n    logger.debug('Complementary TP (nodes - edges):' +\n          str(nxg_complementary_sub_graph.nodes) + '-' +\n          str(nxg_complementary_sub_graph.edges)\n    )\n    '''\n    d_pos = d_position;\n    \n    # -------------------------------------------------\n    # (1) draw graph that presents not TC\n    # Node color: silver for border color\n    # Edge stype: dotted\n    networkx.draw(\n        nxg_complementary_sub_graph,\n        d_pos,\n        labels={},\n        edge_color='silver',\n        style='dotted', # (solid|dashed|dotted|dashdot)\n        width=8,\n        node_size=n_graph_node_size,\n        node_color = 'silver',\n    );\n\n    \n    # -------------------------------------------------\n    # (2) draw nodes from TS black = border color\n    # draw nodes - no need to draw edges: edgelist ={}\n    Gnodes = networkx.Graph()\n    Gnodes.add_nodes_from(nxg_sub_graph)    \n    networkx.draw(\n        Gnodes,\n        d_pos,\n        labels={},\n        node_color = 'black',\n        node_size=n_graph_node_size*1,\n        edgelist ={}, # no need to draw edges\n    );\n    \n    # -------------------------------------------------\n    # (3) draw graph nodes from not TC - inside color, 80% of node size\n    Gnodes = networkx.Graph()\n    Gnodes.add_nodes_from(nxg_complementary_sub_graph) # 2020-07-31\n    networkx.draw(\n        Gnodes,\n        d_pos,\n        labels={},\n        font_size = n_font_size,\n        font_color = 'black',\n        node_color = 'aliceblue', #'lightbluegrey',\n        node_size=n_graph_node_size*0.8,\n        alpha=n_alpha, # transparency (default=1.0)\n    );\n    \n    # -------------------------------------------------\n    # (4) draw graph nodes and edges from TC - inside blue color, 80% of node size\n    networkx.draw(\n        nxg_sub_graph,\n        d_pos,\n        labels={},\n        node_color = s_node_color,\n        edge_color = s_edge_color, #'aliceblue', #'lightbluegrey',\n        width=8,\n        node_size=n_graph_node_size*0.8,\n        alpha=n_alpha, # transparency (default=1.0)\n    );\n    \n    # -------------------------------------------------\n    # Labels\n    # Problem: cannot draw labels for TS only\n    # -------------------------------------------------\n    \n    #\n    # remove labels from 'd_local_node_label' for nodes that are not in TP 'nxg_sub_graph'\n    #\n    logger.debug('d_local_node_label = ' + str(d_local_node_label))\n    d_node_label_copy = d_local_node_label.copy()\n    logger.debug('d_node_label_copy = ' + str(d_node_label_copy))\n    for n_v in d_local_node_label:\n        if n_v not in nxg_sub_graph.nodes:\n            logger.debug(n_v)\n            #d_local_node_label = d_local_node_label.drop(labels=n_v)    \n            del d_node_label_copy[n_v]\n    \n    # -------------------------------------------------\n    # (5) print node labels\n    networkx.draw_networkx_labels(\n        # 2019-12-17: no complementary graph nodes\n        # 2019-12-17: nxg_sub_graph, # TP\n        nxg_G,\n        #Gnodes, # all graphs\n        d_pos,\n        font_family = 'Times New Roman',\n        # 2019-12-17: no complementary graph nodes\n        # 2019-12-17: labels=d_node_label_copy,\n        labels=d_local_node_label,\n        font_size = n_font_size,\n        nodelist = {},\n        font_color = 'black',\n    );\n    \n    #\n    # remove labels from 'd_local_edge_label' for nodes that are not in TP 'nxg_sub_graph'\n    #\n    logger.debug('d_local_edge_label = ' + str(d_local_edge_label))\n    d_edge_label_copy = d_local_edge_label.copy()\n    logger.debug('d_edge_label_copy = ' + str(d_edge_label_copy))\n    for n_e in d_local_edge_label:\n        if n_e not in nxg_sub_graph.edges:\n            logger.debug(n_e)\n            #d_local_edge_label = d_local_edge_label.drop(labels=n_e)\n            del d_edge_label_copy[n_e]\n\n    # -------------------------------------------------\n    # (6) edge labels\n    networkx.draw_networkx_edge_labels(\n        nxg_sub_graph, # TP\n        #Gnodes, # all graphs\n#        nxg_G,\n        d_pos,\n        d_edge_label_copy,\n        0.5, # label_pos (float) \u2013 Position of edge label along edge (0=head, 0.5=center, 1=tail)\n        font_size = n_font_size,\n        font_family = 'Times New Roman',\n        nodelist = {},\n        bbox=dict(boxstyle=\"circle,pad=0.1\",fc=\"w\",ec=\"w\"), # style for edge labels\n    );\n    # valid strings are ['dejavusans', 'dejavuserif', 'cm', 'stix', 'stixsans', 'custom']\n    pyplot.rcParams['mathtext.fontset'] = 'stix';\n    \n    f_debug_end_with_function(\"f_draw_graph_TP_pure\")\n```\n\nf_draw_graph_TP_pure(\n            'H3', # supbraph (string name) of edges in d_TS_H[] dictionary\n            df_TP.to_dict()['TS_edges'],\n            df_edge,\n            d_local_node_label,\n            d_local_edge_label,\n            n_font_size,\n            d_position,\n            'lightskyblue',\n            'lightskyblue',\n            t_c_test_phase_dim = (10,5)\n        );\n\n### Function ```f_get_graph_weights(dfN,dfE)```\n\nCalculating graph weights\n* implementation cost (delta $\\lambda$)\n* value (epsilon $\\epsilon$)\n\nIt is important not to use variable name ```lambda``` - it is used for lambda function in Python. Instead of ```lambda``` variable name is ```delta```, *graph* lambda.\n\nThe function is included in f_get_TS_weight\n\n\n```python\n#\n# f_get_graph_weights\n#\n# Creates data frame with new columns\n#  delta\n#  epsilon\n#\n# input data frames\n#  df_node\n#  df_edge\n#\n# output\n#  df_node with new columns\n#  df_edge with new columns\n#\ndef f_get_graph_weights(dfN,dfE):\n    f_debug_start_with_function(\"f_get_graph_weights\")\n    # Nodes\n    dfN[\"delta\"] = (dfN[\"kappa\"] * abs(dfN[\"t_kappa\"])) + (dfN[\"theta\"] * abs(dfN[\"t_theta\"]))\n    dfN[\"epsilon\"] = abs(dfN[\"t_kappa\"] * dfN[\"t_theta\"]) * dfN[\"sigma\"]\n\n    #Edges\n    dfE[\"delta\"] = (dfE[\"kappa\"] * abs(dfE[\"t_kappa\"])) + (dfE[\"theta\"] * abs(dfE[\"t_theta\"]))\n    dfE[\"epsilon\"] = abs(dfE[\"t_kappa\"] * dfE[\"t_theta\"]) * dfE[\"sigma\"]\n    \n    f_debug_end_with_function(\"f_get_graph_weights\")\n```\n\n### Function ```f_draw_TS```\n\n\n```python\n# Input algorithm:\n#   f_draw_set_TS ... draw set of TS with a use of f_draw_graph_TP_pure\n#\n# Input data:\n#   d_TP  ... dictionary of TS\n#   s_weight      ... OPTIONAL: string - given graph weight name for in \"df_node\"\n#   fig_file_name ... OPTIONAL: string - file name of the output file of drawing\n#   s_title       ... OPTIONAL: string - title of drawing\n#\ndef f_draw_TS(\n    d_TP, \n    s_weight=\"\", \n    s_file_name=\"\", \n    s_title=\"\",\n    bool_print_to_terminal = True,\n    t_test_phase_dim=t_c_test_phase_dim\n):\n    global bool_draw_TS;\n    \n    f_debug_start_with_function(\"f_draw_TS\")\n#    print(type(d_TS_H))\n\n    #\n    # Draw test suites condition.\n    #  bool_draw_TS\n    #\n    if bool_draw_TS:\n    \n        d_local_node_label = d_node_label.copy()\n        d_local_edge_label = d_edge_label.copy()\n\n        if s_weight:\n            # there is given graph weight name for in \"df_node\"\n\n            # update values to format it as LaTeX number\n            for key in d_node_label:\n                d_local_node_label[key]=\"$\"+str(df_node[s_weight].to_dict()[key])+\"$\"\n\n            for key in d_edge_label:\n                d_local_edge_label[key]=\"$\"+str(df_edge[s_weight].to_dict()[key])+\"$\"\n\n        logger.debug(\"f_draw_TS :\" + str(s_weight))\n#        display(d_local_node_label)\n#        display(d_local_edge_label)\n\n        #\n        # original TP definitnion 'd_TS_H'\n        #\n        pyplot.figure(figsize=t_test_phase_dim); # different figsize proportion for on screen and to file\n        f_draw_set_TS(\n            d_TP,\n            df_edge,\n            d_local_node_label,\n            d_local_edge_label,\n            n_font_size,\n            d_position,\n            s_file_name,\n            s_title,\n            bool_print_to_terminal\n        )\n        \n    f_debug_end_with_function(\"f_draw_TS\")\n```\n\n### Function ```f_draw_set_TS(.,.,.,.,.,.,.)```\n\n\n```python\n# Input algorithm:\n#   f_draw_set_TS ... draw TS on the default figure (with a use of f_draw_graph_TP_pure)\n#\n# Input data:\n#   d_TP    ... dictionary of TS\n#   fig_file_name ... OPTIONAL: string - file name of the output file of drawing\n#   s_title       ... OPTIONAL: string - title of drawing\n#\ndef f_draw_set_TS(\n    d_TP,\n    df_edge,\n    d_local_node_label,\n    d_local_edge_label,\n    n_font_size,\n    d_position,\n    fig_file_name = \"\",\n    s_title = \"\",\n    bool_print_to_terminal = True\n):\n    f_debug_start_with_function(\"f_draw_set_TS\")\n    \n    # adjust space between graphs - remove vertical space between figures\n    pyplot.subplots_adjust(wspace=0);\n       \n    # size (width) of test phase figure, where hight is 1\n    n_tp_fig_cols = len(d_TP);\n\n    #\n    i = 0\n    for s_TS in d_TP:\n        i=i+1\n#        print(s_TS,i)\n#        print(type(s_TS))\n#        print(s_TS.index)\n        pyplot.subplot(1, n_tp_fig_cols, i); # subplot(nrows, ncols, index,)\n#        pyplot.title(\"Title:\")\n        f_draw_graph_TP_pure(\n            s_TS, # supbraph (string name) of edges in d_TS_H[] dictionary\n            d_TP,\n            df_edge,\n            d_local_node_label,\n            d_local_edge_label,\n            n_font_size,\n            d_position,\n            'lightskyblue',\n            'lightskyblue'\n        );\n    \n    if fig_file_name:\n        # https://matplotlib.org/api/_as_gen/matplotlib.pyplot.savefig.html\n        pyplot.savefig(s_c_results+fig_file_name, transparent=True, optimize=True, bbox_inches='tight');# PDF\n   \n    pyplot.suptitle(s_title, fontsize=36)\n    if bool_print_to_terminal:\n#        print(\"bool_print_to_terminal =\", bool_print_to_terminal);\n        pyplot.show();\n    else:\n#        print(\"bool_print_to_terminal =\", bool_print_to_terminal);\n        pyplot.close();\n            \n    f_debug_end_with_function(\"f_draw_set_TS\")\n```\n\n### Function ```f_TS_nodes(d_TS_local,s_TS_local)```\n\n\n```python\n#\n# create set of nodes for test suite s_TS_local\n#\n# 2019-12-01: Fix - added parameter d_TS_local (and not d_TS_H)\n#\ndef f_TS_nodes(d_TS_local,s_TS_local):\n    f_debug_start_with_function(\"f_TS_nodes\")\n    \n    set_nodes = set()\n    for elt in d_TS_local[s_TS_local]:\n        set_nodes.add(elt[0])\n        set_nodes.add(elt[1])\n\n    f_debug_end_with_function(\"f_TS_nodes\")\n    return(set_nodes)\n```\n\n### Function ```f_kappa_measure(d_sH)``` - development cost\n\n$\\kappa$ .. _the **development** cost for test phase $\\mathcal H$:\n \t\\begin{eqnarray}\n\t\t&& \\kappa(H) = \n\t\t\\!\\!\\!\\! \\sum_{v_j\\in V(H)} \\kappa(v_j)\\;\\tilde{\\kappa}_{vj} +\n\t\t\\!\\!\\!\\! \\sum_{e_j\\in E(H)} \\kappa(e_j)\\;\\tilde{\\kappa}_{ej}\n\t\\end{eqnarray}\n$\\kappa$ .. the **development cost** for test phase $\\mathcal H$:\n\t\\begin{eqnarray}\n\t\t&& \\kappa({\\mathcal H}) =\n\t\t\\!\\!\\!\\! \\sum_{v_j\\in V({\\mathcal H})} \\kappa(v_j)\\;\\tilde{\\kappa}_{vj} +\n\t\t\\!\\!\\!\\! \\sum_{e_j\\in E({\\mathcal H})} \\kappa(e_j)\\;\\tilde{\\kappa}_{ej}\n\t\\end{eqnarray}\n\n\n```python\n#\n# Test Cost value (kappa) 2020-04-25\n#\ndef f_kappa_measure(\n    d_TS_H,\n    s_TS_name\n):\n    f_debug_start_with_function(\"f_kappa_measure\")\n    global df_edge\n    global df_node\n    \n    n_kappa = sum(\n        df_edge[\"kappa\"][f_list_edges(d_TS_H,s_TS_name)] * df_edge[\"t_kappa\"][f_list_edges(d_TS_H,s_TS_name)]\n    ) + sum(\n        df_node[\"kappa\"][f_list_nodes(d_TS_H,s_TS_name)] * df_node[\"t_kappa\"][f_list_nodes(d_TS_H,s_TS_name)] +\n        df_node[\"theta\"][f_list_nodes(d_TS_H,s_TS_name)] * df_node[\"t_theta\"][f_list_nodes(d_TS_H,s_TS_name)]\n    );\n\n    logger.debug(\" n_kappa(nodes,edges)=(\"+str(n_kappa)+\")\" )\n    f_debug_end_with_function(\"f_kappa_measure\")\n    return(n_kappa)\n\n```\n\n```python\n#\n# Development cost value (kappa) for test suite\n# Important: \"kappa for test suite\" = \"kappa for test phase\"\n#\ndef f_kappa_measure(\n    d_TS_H\n):\n    f_debug_start_with_function(\"f_kappa_measure\")\n    # set debug: set_strace()\n    # set_trace()\n    \n    #\n    # Create set of edges and set of nodes from all TS in dictionary\n    #\n    set_edge = set()\n    set_node = set()\n    for l_i in list(d_TS_H.values()): # get list of edges from test suite\n        logger.debug(\"list of edges from test suite = \"+str(l_i))\n        for t_i in l_i: #  get tuple (edge) from list of edges\n            logger.debug(\"  \"+str(t_i)+\"  -  \"+str(t_i[0])+\",\"+str(t_i[1]))\n            set_edge.add(t_i)\n            set_node.add(t_i[0])\n            set_node.add(t_i[1])\n    logger.debug(\"Set of all edges in test phase =\"+str(set_edge))\n    logger.debug(\"Set od all nodes in test phase =\"+str(set_node))\n\n    #\n    # Sum of kappa measures for vertices and edges\n    # and sum of theta measure for vertices (unit tests are part of development)\n    #\n    n_kappa_nodes = 0\n    n_theta_nodes = 0\n    for n_i in set_node:\n        logger.debug(\"kappa(\"+str(n_i)+\")=\"+str(df_node[\"kappa\"][n_i])+\",\n                     theta(\"+str(n_i)+\")=\"+str(df_node[\"theta\"][n_i]))\n        n_kappa_nodes += df_node[\"kappa\"][n_i] * abs(df_node[\"t_kappa\"][n_i])\n        n_theta_nodes += df_node[\"theta\"][n_i] * abs(df_node[\"t_theta\"][n_i])\n    logger.debug(\"n_kappa_n=\"+str(n_kappa_nodes))\n    logger.debug(\"n_theta_n=\"+str(n_theta_nodes))\n    n_kappa_edges = 0\n    for t_i in set_edge:\n        logger.debug(\"kappa(\"+str(t_i[0])+\",\"+str(t_i[1])+\")=\"+str(df_edge[\"kappa\"][t_i]))\n        n_kappa_edges += df_edge[\"kappa\"][t_i] * abs(df_edge[\"t_kappa\"][t_i])\n    logger.debug(\"n_kappa_edges=\"+str(n_kappa_edges))\n    \n    n_sum = n_kappa_nodes + n_theta_nodes + n_kappa_edges\n    logger.debug(\" n_kappa(nodes,edges)=(\"+str(n_kappa_nodes)+\",\"+str(n_theta_nodes)+\",\n                 \"+str(n_kappa_edges)+\")\" + str(n_sum))\n    f_debug_end_with_function(\"f_kappa_measure\")\n    return(n_sum)\n```\n\n### Function ```f_theta_measure(d_sH,s_TS)``` - test cost\n\n$\\theta$ .. _the test cost for test suite_ $H$ and _test phase_ $\\mathcal H$:\n \t\\begin{eqnarray}\n\t\t% \\label{eq:PhaseTestingCost}\n\t\t \\theta(H) = \\!\\!\\!\\! \\sum_{e\\in E(H)} \\theta(e)\\;|\\tilde{\\theta}(e)| \n\t\t % + \\sum_{v\\in V(H)} \\theta(v)\\;|\\tilde{\\theta}(v)| \\!\\!\\! % \\\\\n\t\t \\quad \\textrm{ and } \\quad \\theta({\\mathcal H}) = \\sum_{H^i \\in {\\mathcal H}} \\theta(H^i). % \\nonumber\n   \\end{eqnarray}\n\n\n\n```python\n#\n# Test Cost value (theta)\n#\ndef f_theta_measure(\n    d_TS_H,\n    s_TS_name\n):\n    f_debug_start_with_function(\"f_theta_measure\")\n    global df_edge\n\n    n_theta_edges = sum(\n        df_edge[\"theta\"][d_TS_H[s_TS_name]] * abs(df_edge[\"t_theta\"][d_TS_H[s_TS_name]])\n    )\n\n    logger.debug(\" n_theta(nodes,edges)=(\"+str(n_theta_edges)+\")\" )\n    f_debug_end_with_function(\"f_theta_measure\")\n    return(n_theta_edges)\n\n```\n\n### Function ```f_delta_measure_T[S|P](d_sH[,s_TS])``` - implementation cost\n\n$\\lambda$ .. the _implementation cost for test suite_ $H$ and _test phase_ $\\mathcal H$:\n \t\\begin{eqnarray}\n\t\\label{eq:ImplementationCost}\n\t  \\lambda(H)=\\sum_{v\\in V(\\mathcal H)} \\lambda(v) + \\sum_{e\\in E(H)} \\lambda(e) \\quad \\textrm{ and } \\quad % \\\\\n\t  \\lambda(\\mathcal H)=\\sum_{v\\in V(\\mathcal H)} \\lambda(v) + \\sum_{H\\in V(\\mathcal H)}\\sum_{e\\in E(H)} \\lambda(e). % \\nonumber\n\t\\end{eqnarray}\n\n\nFunction \"delta\" ($\\lambda$) is a sum of measures \"kappa\" and \"theta\" for vertices and edges:\n\t\\begin{equation}\n\t\\label{eq:ImplementationCostVerticesEdges}\n\t\\begin{aligned}\n\t& \\lambda : V(G^P)\\cup E(G^P)\\to{\\mathbb R}^+ \\cup \\{0\\} \\\\\n\t& \\lambda(v)=\\kappa(v)+\\theta(v) \\quad \\textrm{ and } \\quad\n\t     \\lambda(e)=\\kappa(e)+\\theta(e).\n\t\\end{aligned}\n\t\\end{equation}\n\n\n\n```python\n#\n# Implementation cost value (lambda) for test suite\n#\ndef f_delta_measure_TS(\n    d_TS_H,\n    s_TS_name\n):\n    f_debug_start_with_function(\"f_delta_measure_TS\")\n    global df_edge\n    global df_node\n\n    n_delta_v = df_node['delta'][f_list_nodes(d_TS_H,s_TS_name)].sum()\n    n_delta_e = df_edge['delta'][f_list_edges(d_TS_H,s_TS_name)].sum()\n    n_delta_test_suite = n_delta_v + n_delta_e\n\n    logger.debug(\" n_delta_test_suite(test_suite)=(\"+str(n_delta_v)+\"+\"+str(n_delta_e)+\")\" )\n    f_debug_end_with_function(\"f_delta_measure_TS\")\n    return(n_delta_test_suite)\n\n```\n\n\n```python\n#\n# Implementation cost value (lambda) for test phase\n#\ndef f_delta_measure_TP(\n    d_TS_H\n):\n    f_debug_start_with_function(\"f_delta_measure_TP\")\n    global df_edge\n    global df_node\n\n    n_delta_v = df_node['delta'].sum()\n    \n    n_delta_e = 0\n    for s_H in d_TS_H:\n        n_tmp_delta_H = df_edge['delta'][d_TS_H[s_H]].sum()\n        logger.debug(\"  delta(\"+str(s_H)+\")=\"+str(n_tmp_delta_H))\n        n_delta_e += n_tmp_delta_H\n    \n    n_delta_test_suite = n_delta_v + n_delta_e\n\n    logger.debug(\" n_delta_test_suite(test_suite)=(\"+str(n_delta_v)+\"+\"+str(n_delta_e)+\")\" )\n    f_debug_end_with_function(\"f_delta_measure_TP\")\n    return(n_delta_test_suite)\n\n```\n\n### Function ```f_epsilon_measure(d_TS_H,s_TS_name)``` - implementation value\n\n$\\epsilon$ .. the _implementation value for test suite_ $H$ and _test phase_ $\\mathcal H$:\n\t\\begin{eqnarray}\n\t\\epsilon(H) = \\!\\!\\!\\! \\sum_{v\\in V(H)} \\epsilon(v) + \\!\\!\\!\\sum_{e\\in E(H)} \\epsilon(e)\n\t\\quad \\textrm{ and } \\quad\n\t\\epsilon({\\mathcal H}) = \\!\\!\\!\\! \\sum_{v\\in V({{G^P}})} \\epsilon(v) + \\!\\!\\!\\sum_{e\\in E({{\\mathcal H}})} \\epsilon(e).  \n\t\\end{eqnarray}\n    where\n\t\\begin{eqnarray}\n    \t& \\epsilon(v)=|\\tilde{\\theta}(v)\\cdot\\tilde{\\kappa}(v)|\\cdot \\sigma(v) \\quad \\textrm{ and } \\quad % \\in V({\\mathcal H})\\cup E({\\mathcal H})\n\t   \\epsilon(e)=|\\tilde{\\theta}(e)\\cdot\\tilde{\\kappa}(e)|\\cdot \\sigma(e) %, \\quad \\in V({\\mathcal H})\\cup E({\\mathcal H})\n\t\\end{eqnarray}\n\n\n```python\n#\n# Test Cost value (epsilon) 2020-04-25\n#\ndef f_epsilon_measure(\n    d_TS_H,\n    s_TS_name\n):\n    f_debug_start_with_function(\"f_epsilon_measure\")\n    global df_edge\n    global df_node\n    \n    n_epsilon = sum(\n        df_edge[\"epsilon\"][f_list_edges(d_TS_H,s_TS_name)]\n    ) + sum(\n        df_node[\"epsilon\"][f_list_nodes(d_TS_H,s_TS_name)]\n    );\n\n    logger.debug(\" n_epsilon(nodes,edges)=(\"+str(n_epsilon)+\")\" )\n    f_debug_end_with_function(\"f_epsilon_measure\")\n    return(n_epsilon)\n\n```\n\n```python\n#\n# Implementation cost value (epsilon)\n#\ndef f_epsilon_measure(\n    d_TS_H,\n    s_TS_name\n):\n    global df_node\n    global df_edge\n    \n    f_debug_start_with_function(\"f_epsilon_measure\")\n\n    #\n    # Create set of edges and set of nodes from all TS in dictionary\n    #\n    set_edge = set()\n    set_node = set()\n    for l_i in list(d_TS_H.values()): # get list of edges from test suite\n        logger.debug(\"list of edges from test suite = \"+str(l_i))\n        for t_i in l_i: #  get tuple (edge) from list of edges\n            logger.debug(\"  \"+str(t_i)+\"  -  \"+str(t_i[0])+\",\"+str(t_i[1]))\n            set_edge.add(t_i)\n            set_node.add(t_i[0])\n            set_node.add(t_i[1])\n    logger.debug(\"Set of all edges in test phase =\"+str(set_edge))\n    logger.debug(\"Set od all nodes in test phase =\"+str(set_node))\n\n    #\n    # Sum of kappa measures for vertices and edges\n    # and sum of theta measure for vertices (unit tests are part of development)\n    #\n    n_epsilon_nodes = 0\n    for n_i in set_node:\n        n_epsilon_nodes += df_node[\"epsilon\"][n_i]\n        logger.debug(\"epsilon(\"+str(n_i)+\")=\"+str(df_node[\"epsilon\"][n_i]))\n    logger.debug(\"n_epsilon_nodes=\"+str(n_epsilon_nodes))\n    n_epsilon_edges = 0\n    for t_i in set_edge:\n        logger.debug(\"epsilon(\"+str(t_i[0])+\",\"+str(t_i[1])+\")=\"+str(df_edge[\"epsilon\"][t_i]))\n        n_epsilon_edges += df_edge[\"epsilon\"][t_i]\n    logger.debug(\"n_epsilon_edges=\"+str(n_epsilon_edges))\n    \n    # nodes that are endnodes of edges in test suite, ONLY\n#     n_epsilon_nodes = sum(\n#         df_node[\"epsilon\"][list(f_TS_nodes(d_TS_H,s_TS_name))]\n#     )\n    n_sum = n_epsilon_nodes + n_epsilon_edges\n    logger.debug(\" n_epsilon(nodes,edges)=(\"+str(n_epsilon_nodes)+\",\"+str(n_epsilon_edges)+\")=\" + str(n_sum))\n    f_debug_end_with_function(\"f_epsilon_measure\")\n    return(n_sum)\n```\n\n### Function ```f_sort_TS_in_TP(df_TP,s_weight,d_TS_H,ascending)```\nFunction ```f_sort_TS_in_TP``` creates TP presented as data frame with TS from ```d_TS_H``` __sorted__ by given weight ```s_weight```.\n\n\n```python\n#\n# f_sort_TS_in_TP\n#\n#\n# input\n#  df_TP\n#  s_weight\n#  d_TS_H\n#\n# output\n#  df_TP with infos about graph edges\n#\n# return\n#  data frame sorted by \"l_weight\" (list of weights)\n#\n\ndef f_sort_TS_in_TP(df_TP,l_weight,d_TS_H,bool_local_sort_order_ascending=True):\n\n    f_debug_start_with_function(\"f_sort_TS_in_TP\")\n    logger.debug(d_TS_H)\n    #\n    # Add column 'TS_edges' to data frame\n    #\n    df_loc_sorted_TS_H = df_TP # create local variable\n##    df_loc_sorted_TS_H['TS_edges'] = list(d_TS_H.values())\n    logger.debug(\"df_loc_sorted_TS_H (with edges from d_subgraps_H):\")\n    logger.debug(df_loc_sorted_TS_H)\n\n    #\n    # Sort data frame by 'delta'\n    #\n    df_loc_sorted_TS_H = df_loc_sorted_TS_H.sort_values(by=l_weight,ascending=bool_local_sort_order_ascending)\n    logger.debug(\"df_loc_sorted_TS_H (sorted by s_weight):\")\n    logger.debug(df_loc_sorted_TS_H)\n    \n    #\n    # Update TP names (indexes): lambda(H1) <= lambda(H2) ...\n    #\n    df_loc_sorted_TS_H.index = list(d_TS_H.keys())\n    logger.debug(\"df_loc_sorted_TS_H (updated indexes):\")\n    logger.debug(df_loc_sorted_TS_H)\n\n    f_debug_end_with_function(\"f_sort_TS_in_TP\")\n    return(df_loc_sorted_TS_H)\n```\n\n### Function ```f_rename_df_index_values(df_TP_sorted,s_old_name,s_new_name)```\nFunction ```f_rename_df_index_values()``` renames index values ```s_old_name``` with ```s_new_name```.\n\n\n```python\n#\n# Create new df with new TP names\n#\n# Input\n#  df_TP_sorted\n#  s_old_name\n#  s_new_name\n#\n# Output\n#  df_wgraphs_M\n#\ndef f_rename_df_index_values(df_TP_sorted,s_old_name,s_new_name):\n    f_debug_start_with_function(\"f_rename_df_index_values\")\n    \n    # create new data frame\n    df_wgraphs_M = df_TP_sorted\n    \n    # replace name in existing index ```list(df_TP_sorted.index)```\n    l_new_TS_names = [s_i.replace(s_old_name,s_new_name) for s_i in list(df_TP_sorted.index)]\n    \n    # create new index with l_new_TS_names\n    df_wgraphs_M[\"new_index\"]=l_new_TS_names\n    \n    # set index as the column \"new_index\"\n    df_wgraphs_M = df_wgraphs_M.set_index('new_index')\n    \n    # clear index name\n    df_wgraphs_M.index.name = ''\n    \n    f_debug_end_with_function(\"f_rename_df_index_values\")\n    return(df_wgraphs_M)\n```\n\n### Function ```f_remove_common_edges(df_TP,s_Hi,s_Hj)```\n\n* Input data:\n * __data frame```df_TP```__\n * __TP ```H_i```__\n * __TP ```H_j```__\n\n* Output\n * Implicit output: __new TP ```df_TP['TS_edges'][M_i]```__\n * Return value: __list of removed edges__\n\n\n```python\n#\n# From the s_Hi removes edges that are in s_Hj from dataframe df_TP, where size(s_Hi) >= 1.\n# \n# Input: df_TP_, s_Hi, s_Hj\n#\n# Return:\n#     Value is the \"list\" of edges in s_Hi as a result of after edges removal\n#     OR return an empty list [] if \"no edges removed\"\n#     As function argument is data frame df_TP_ and it is a 'reference' to data frame,\n#     data frame is updated with this function. Test cases (edges) are removed from test suites in test phase.\n#\n\n# %pixie_debugger\n\ndef f_remove_common_edges(df_TP_,s_Hi,s_Hj,\n                            bool_sort_order_ascending=False,\n                            bool_allow_empty=True):\n    f_debug_start_with_function(\"f_remove_common_edges\")\n    \n    if bool_allow_empty:\n        if (len(df_TP_['TS_edges'][s_Hi]) <= 1):\n            logger.debug(\"no edges removed - size of \" + str(s_Hi) + \" is too small\")\n            return(list())\n    set_Hi = sorted(df_TP_['TS_edges'][s_Hi],key=None,reverse=bool_sort_order_ascending)\n    set_Hj = set(df_TP_['TS_edges'][s_Hj])\n    for elt in set_Hi.copy(): # iterating over a copy of set_Hi to allow chnage of set_Hi\n        if bool_allow_empty:\n            if (len(set_Hi) <= 1):\n                logger.debug(\"stop edge removal - size of \" + str(set_Hi) + \" is too small\")\n                break\n        if elt in set_Hj:\n            set_Hi.remove(elt)\n            logger.debug('*' + str(elt) + '* ')\n    # Remove edges also in the graph df_TP_\n    #  Wrong: df_TP_['TS_edges'][s_Hi] = set_Hi\n    #  Wrong: df_TP_.loc[:,('TS_edges')][s_Hi] = list(set_Hi)\n    #  Correct: Use the format \".at\"\n    df_TP_.at[s_Hi,'TS_edges'] = list(set_Hi)\n    f_debug_end_with_function(\"f_remove_common_edges\")\n    return(list(set_Hi))\n```\n\n### Function ```f_leave_one_edge(df_TP,s_Hi)```\n\nLeave exactly one edge on ```H_i``` and return that one edge\n\n* Input data:\n * __data frame```df_TP```__\n * __TP ```H_i```__\n\n* Output\n * Return value: __the one remaining edge__ - the edge is remainder after deletion of more than one edges in the TP ```H_i```\n\n\n```python\n#\n# \n# Input: df_TP, s_Hi\n#\n# In the s_Hi not more than one edge.\n# Return value is the one remaining edge in Hi. The format of the edge is tuple.\n#\n\ndef f_leave_one_edge(df_TP,s_Hi):\n    f_debug_start_with_function(\"f_leave_one_edge\")\n    # set_trace()\n    set_Hi = set(df_TP['TS_edges'][s_Hi])\n    for elt in set_Hi.copy(): # iterating over a copy of set_Hi to allow chnage of set_Hi\n        logger.debug(len(set_Hi))\n        if len(set_Hi) < 2:\n            break\n            logger.debug(\"One\")\n        set_Hi.remove(elt)\n        logger.debug(\"*\" + str(elt) + \"* \")\n    # remove edges also in the graph df_TP\n    # Use the format \".at\"\n    df_TP.at[s_Hi,'TS_edges'] = list(set_Hi)\n    # df_TP.loc[:,('TS_edges')][s_Hi] = list(set_Hi)\n    # print(df_TP.at[s_Hi,'TS_edges'])\n    \n    # there should be only 1 elt in the set_Hi\n    # Two ways to get the elt from set\n    # 1. next(iter(set_Hi))\n    # 2. list(set_Hi)[0]\n    \n    f_debug_end_with_function(\"f_leave_one_edge\")\n    return(next(iter(set_Hi)))\n```\n\n### Support functions ```f_size_Hx``` and ```f_TS_Hx```, ```f_read_data_from_files```, ```f_print_var_value```\nThese support functions are needed for ```f_TP_min_deduplication``` and ```f_TP_max_deduplication```\n\n\n```python\n#\n# Return size of graph s_Hx - it is number of edges\n#\ndef f_size_Hx(df_TP,s_Hx):\n    f_debug_start_with_function(\"f_size_Hx\")\n    \n    return(\n        len(\n            df_TP.truncate(before=s_Hx, after=s_Hx).to_dict()['TS_edges'][s_Hx]\n        )\n    )\n```\n\n\n```python\n#\n# Return 'TS_edges' for s_Hx from df_TP\n#\ndef f_TS_Hx(df_TP,s_Hx):\n    f_debug_start_with_function(\"f_TS_Hx\")\n    \n    return(\n        df_TP.truncate(\n            before=s_Hx, after=s_Hx)\n        .to_dict()['TS_edges']\n    )\n```\n\n\n```python\n#\n# Read all data about testing from files\n#\n# Input\n#  s_file_graphN\n#  s_file_graphE\n#  s_file_TS\n#\n# Return \n#   df_TP\n#   d_TP_weight\n#\n# Return values as 'global' variables:\n#   df_node\n#   df_edge\n#   d_TS_H\n#   d_position\n#   d_node_label\n#   d_edge_label\n#\ndef f_read_data_from_files(s_file_graphN, s_file_graphE, s_file_TS):\n    global df_node\n    global df_edge\n    global d_TS_H\n    global d_position\n    global d_node_label;\n    global d_edge_label;\n    \n    f_debug_start_with_function(\"f_read_data_from_files\")\n    \n    # Read Graph nodes from File\n    df_node = pandas.read_csv(\"data/\"+s_file_graphN, sep=s_c_graph_data_delimiter, index_col = 0)\n\n    logger.debug(df_node)\n    \n    # are there data for node position in the df_node\n    if(('x_position' and 'y_position') in df_node.columns):\n        d_xpos = df_node['x_position'].to_dict()\n        d_ypos = df_node['y_position'].to_dict()\n\n        d_position = {}\n        for key in d_xpos.keys():\n            d_position[key] = tuple(d_position[key] for d_position in [d_xpos,d_ypos])\n        # global variable d_position is updated\n\n    # Read Graph edges from File\n    df_edge = pandas.read_csv(\"data/\"+s_file_graphE, sep=s_c_graph_data_delimiter, index_col = [0,1])\n\n    logger.debug(df_edge)\n    \n    #\n    # Read dictionary from file with error checking\n    # Raise error to stop execution - cannot continue without data.\n    #\n    try:\n        d_TS_H = eval(open(\"data/\"+s_file_TS, 'r').read())\n    except:\n        logger.exception(\"Error reading file: \" + s_file_TS)\n        raise ValueError(\"Error reading file: \" + s_file_TS)\n        d_TS_H = {}\n\n    logger.debug(d_TS_H);\n    \n    #\n    # create global variable d_edge_label\n    #\n    logger.debug(\"Generated edge labels:\");\n    d_edge_label = {};\n    n_edge_label = 1;\n    for n_e,_ in df_edge.iterrows():\n        # edge label in a form 'e_(u,v)'\n    #    d_edge_label[n_e] = r'$e_{('+str(n_e[0])+','+str(n_e[1]) +')}$';\n        # edge label in a form 'e_x'\n        d_edge_label[n_e] = r'$e_{'+str(n_edge_label) +'}$';\n        n_edge_label = n_edge_label+1;\n\n        logger.debug(d_edge_label[n_e]);\n\n    #\n    # create global variable d_node_label\n    #\n    logger.debug(\"Generated node labels:\");\n    d_node_label = {};\n    for n_v,_ in df_node.iterrows():\n        d_node_label[n_v] = r'$v_'+str(n_v)+'$';\n\n        logger.debug(d_node_label[n_v]);\n        \n    f_debug_end_with_function(\"f_read_data_from_files\")\n    # Create and return data frame of TS with weights for all TS.\n    return(\n        f_get_TS_weight(d_TS_H)\n    )\n```\n\n\n```python\n#\n# Print variable value with heading line\n# The 2nd parameter for variable description is optional.\n#\ndef f_print_var_value(*s_all_var_names):\n    # print(s_all_var_names,len(s_all_var_names));\n    s_var_name = s_all_var_names[0];\n    if len(s_all_var_names) == 2:\n        if s_var_name:\n            print((' '+s_var_name+' .. \\''+s_all_var_names[1]+'\\' ').center(127, '='));\n        else:\n            print((' \\''+s_all_var_names[1]+'\\' ').center(127, '='));\n    else:\n        print((' '+s_var_name+' ').center(127, '='));\n\n    #\n    # print s_var_name value only if the first argument is not an empty string\n    #\n    if s_var_name:\n        if isinstance(eval(s_var_name),pandas.DataFrame):\n            display(eval(s_var_name));\n        else:\n            print(eval(s_var_name));\n```\n\n### Function ```f_TP_max_deduplication```\n\n2020-07-30: min --> small number of test suites\n\n\n```python\n#\n# Test Phase Deduplication\n#\n#\n# input\n#  df_TP_sorted ... TP test phase (test suites are in dataframe rows) with test suite names in the format \"Hn\"\n#                   Test suites have to be sorted by \"glabmda\" and \"size\"\n#  bool_ij      ... Remove common edges from (H_i,H_j) or from (H_j,H_i)\n#\n\n\ndef f_TP_max_deduplication(\n    df_TP_sorted,\n    bool_ij = True,\n):\n    \n    f_debug_start_with_function(\"f_TP_max_deduplication\")\n    \n    # create data frame local to function domain\n    df_TP_local = df_TP_sorted.copy()\n    \n    logger.debug(\"s_Hi s_Hj\")\n    logger.debug(\"---------\")\n\n#    time.sleep(1)\n    for s_Hi in df_TP_local.index:\n#        time.sleep(1)\n        for s_Hj in df_TP_local.truncate(s_Hi).iloc[1:].index:\n            if bool_ij:\n                l_edges_new = f_remove_common_edges(df_TP_local,s_Hi,s_Hj,\n                                                  bool_sort_order_ascending=False,\n                                                  bool_allow_empty=False);\n            else:\n                l_edges_new = f_remove_common_edges(df_TP_local,s_Hj,s_Hi,\n                                                  bool_sort_order_ascending=False,\n                                                  bool_allow_empty=False);\n\n#            time.sleep(1)\n            logger.debug(str(s_Hi) + \" \" + str(s_Hj) + \" : Current edges \")\n            logger.debug(str(l_edges_new))\n\n            \n\n    # rename dataframe index (row labels) from \"H\" to \"M\"\n    df_TP_local = f_rename_df_index_values(df_TP_local,\"H\",\"M\")\n    \n#    # data frame has upodated column 'TS_edges' and not columns 'kappa', 'theta', 'delta', 'epsilon', 'size'\n#    # df_updated_wTP has updated all columns - all weights\n#    df_updated_wTP, d_TP_weight = f_get_TS_weight(df_TP_local.to_dict()['TS_edges'])\n#\n#    # Sort set of test suites (df_updated_wTP) with info about test phase (df_updated_wTP)\n#    df_TP_Min_sorted = f_sort_TS_in_TP(\n#        df_updated_wTP,\n#        ['delta'],\n#        df_updated_wTP.to_dict()['TS_edges'],\n#        bool_local_sort_order_ascending=False\n#    );\n#\n    f_debug_end_with_function(\"f_TP_max_deduplication\")\n#    return(df_TP_Min_sorted);\n    return(df_TP_local);\n\n```\n\n\n```python\ndef f_TP_max_deduplication_ij(\n    df_TP_sorted\n):\n    return(\n        f_TP_max_deduplication(\n            df_TP_sorted,\n            bool_ij = True\n        )\n    )\n```\n\n\n```python\ndef f_TP_max_deduplication_ji(\n    df_TP_sorted\n):\n    return(\n        f_TP_max_deduplication(\n            df_TP_sorted,\n            bool_ij = False\n        )\n    )\n```\n\n### Function ```f_TP_min_deduplication```\n\n2019-11-26: removed debug print - ## before debug prints\n\n\n```python\n#\n# Test Phase Min Deduplication\n#\n#\n# input\n#  df_TP_sorted ... TP test phase (test suites are in dataframe rows) with test suite names in the format \"Hn\"\n#                   Test suites have to be sorted by \"glabmda\" and \"size\"\n#\n#                   Example:\n#                       TS_edges                                                  kappa  theta  delta  epsilon  size\n#                   H1  [(1, 3)]                                                  85     40     125      0.15     1   \n#                   H2  [(1, 4), (1, 3), (3, 4), (5, 4)]                          176    80     256      0.68     4   \n#                   H3  [(1, 2), (1, 4), (2, 3), (6, 4), (6, 2)]                  274    81     355      1.35     5   \n#                   H4  [(1, 3), (1, 4), (2, 3), (5, 4), (5, 2), (6, 4), (6, 2)]  327    149    476      1.61     7   \n#\n# output\n#  df_TP_Min_sorted ... TP with test suites with deduplicated test cases\n#\n#                   Example:\n#                       TS_edges                                                  kappa  theta  delta  epsilon  size\n#                   M1  [(1, 3), (1, 4), (2, 3), (5, 4), (5, 2), (6, 4), (6, 2)]  327    149    476      1.61     7   \n#                   M2  [(1, 2)]                                                  91     2      93       0.25     1   \n#                   M3  [(3, 4)]                                                  47     0      47       0.30     1   \n#                   M4  []                                                        0      0      0        0.00     0   \n\n\ndef f_TP_min_deduplication(df_TP_sorted):\n    f_debug_start_with_function(\"f_TP_min_deduplication\")\n    \n    # create data frame local to function domain\n    df_TP_local = df_TP_sorted.copy()\n    \n    logger.debug(\"s_Hi s_Hj\")\n    logger.debug(\"---------\")\n\n#    time.sleep(1)\n    for s_Hi in df_TP_local.index:\n#        time.sleep(1)\n        for s_Hj in df_TP_local.truncate(s_Hi).iloc[1:].index:\n            l_edges_new = f_remove_common_edges(df_TP_local,s_Hi,s_Hj,\n                                                  bool_sort_order_ascending=False,\n                                                  bool_allow_empty=False);\n\n#            time.sleep(1)\n            logger.debug(str(s_Hi) + \" \" + str(s_Hj) + \" : Current edges \")\n            logger.debug(str(l_edges_new))\n\n            \n\n    # rename dataframe index (row labels) from \"H\" to \"M\"\n    df_TP_local = f_rename_df_index_values(df_TP_local,\"H\",\"M\")\n    \n#    # data frame has upodated column 'TS_edges' and not columns 'kappa', 'theta', 'delta', 'epsilon', 'size'\n#    # df_updated_wTP has updated all columns - all weights\n#    df_updated_wTP, d_TP_weight = f_get_TS_weight(df_TP_local.to_dict()['TS_edges'])\n#\n#    # Sort set of test suites (df_updated_wTP) with info about test phase (df_updated_wTP)\n#    df_TP_Min_sorted = f_sort_TS_in_TP(\n#        df_updated_wTP,\n#        ['delta'],\n#        df_updated_wTP.to_dict()['TS_edges'],\n#        bool_local_sort_order_ascending=False\n#    );\n#\n    f_debug_end_with_function(\"f_TP_min_deduplication\")\n#    return(df_TP_Min_sorted);\n    return(df_TP_local);\n\n```\n\n### Function ```f_draw_TP_min_deduplication```\n<a id='f_draw_TP_min_deduplication'></a>\n\n\n\n```python\ndef f_draw_TP_min_deduplication(s_TS_file_name):\n    '''\n    Unit testing\n    \n    Testing TS_H_001.txt\n    >>> f_draw_TP_min_deduplication(\"H_001.TestSuites\")\n    {'M1': [(1, 2), (1, 3), (1, 4), (2, 3)], 'M2': [(3, 4)], 'M3': [], 'M4': [], 'M5': [], 'M6': []}\n    \n    Testing TS_H_002.txt\n    >>> f_draw_TP_min_deduplication(\"H_002.TestSuites\")\n    {'M1': [(1, 2), (1, 3), (1, 4), (2, 3), (3, 4)], 'M2': [], 'M3': [], 'M4': [], 'M5': [], 'M6': []}\n    \n    Testing TS_H_003.txt\n    >>> f_draw_TP_min_deduplication(\"H_003.TestSuites\")\n    {'M1': [(1, 2), (1, 3), (1, 4), (2, 3), (3, 4)], 'M2': [], 'M3': [], 'M4': [], 'M5': [], 'M6': []}\n    \n    Testing TS_H_004.txt\n    >>> f_draw_TP_min_deduplication(\"H_004.TestSuites\")\n    {'M1': [(3, 4)], 'M2': [], 'M3': [], 'M4': [], 'M5': [], 'M6': []}\n    \n    Testing TS_H_005.txt\n    >>> f_draw_TP_min_deduplication(\"H_005.TestSuites\")\n    {'M1': [(1, 3)], 'M2': [(1, 4)], 'M3': [(2, 3)], 'M4': [], 'M5': [], 'M6': []}\n    \n    Testing TS_H_006.txt\n    >>> f_draw_TP_min_deduplication(\"H_006.TestSuites\")\n    {'M1': [(1, 2), (1, 3)], 'M2': [(1, 4)], 'M3': [], 'M4': [], 'M5': [], 'M6': []}\n    \n    Testing TS_H_007.txt\n    >>> f_draw_TP_min_deduplication(\"H_007.TestSuites\")\n    {'M1': [(1, 2), (1, 3), (2, 3)], 'M2': [], 'M3': [], 'M4': [], 'M5': [], 'M6': []}\n    \n    Testing TS_H_008.txt\n    >>> f_draw_TP_min_deduplication(\"H_008.TestSuites\")\n    {'M1': [(1, 2), (1, 3), (1, 4), (2, 3), (3, 4)], 'M2': [], 'M3': [], 'M4': [], 'M5': [], 'M6': []}\n    \n    Testing TS_H_009.txt\n    >>> f_draw_TP_min_deduplication(\"H_008.TestSuites\")\n    {'M1': [(1, 2), (1, 3), (1, 4), (2, 3), (3, 4)], 'M2': [], 'M3': [], 'M4': [], 'M5': [], 'M6': []}\n    '''\n    f_debug_start_with_function(\"f_draw_TP_min_deduplication\")\n    \n    logger.info(s_TS_file_name)\n    \n    #\n    # Read data frame\n    #\n    df_TP, d_TP_weight = f_read_data_from_files(\"graphV.csv\", \"graphE.csv\", s_TS_file_name)\n\n    #\n    # Sort data frame: bool_sort_order_ascending=True - 2020-01-20 it has to by ascending sorted = True\n    #\n    df_TP_sorted = f_sort_TS_in_TP(\n        df_TP,\n        ['delta','size'],\n        d_TS_H,\n        bool_local_sort_order_ascending=True\n    );\n    \n    #\n    # Execute Test Phase Max Deduplication\n    #\n    df_TP_Min_raw = f_TP_min_deduplication(df_TP_sorted)\n\n    #\n    # Sort resulted data frame df_TP_Max_raw as 'bool_sort_order_ascending=False'\n    #\n    df_TP_Min = f_sort_TS_in_TP(\n        df_TP_Min_raw,\n        ['delta','size'],\n        d_TS_H,\n        bool_local_sort_order_ascending=False\n    );\n    #\n    # Draw data frames\n    #\n    f_draw_TS(df_TP.to_dict()['TS_edges'], \"delta\", \"\", s_TS_file_name + \": source graphs for min_dedupe\")\n    f_draw_TS(df_TP_sorted.to_dict()['TS_edges'], \"delta\", \"\", s_TS_file_name + \": source graphs sorted for min_dedupe\")\n    f_draw_TS(df_TP_Min.to_dict()['TS_edges'], \"delta\", \"\", s_TS_file_name + \": minimal test suites\")\n\n    #\n    # Return value: dictionary with test suite edges\n    #\n    d_return_TS_edges = df_TP_Min['TS_edges'].to_dict()\n    \n    f_debug_end_with_function(\"f_draw_TP_min_deduplication\")\n    return(d_return_TS_edges)\n```\n\n### Function ```f_generate_fun_graph```\n<a id='f_test_weight_redesign_wrapper'></a>\n\n\n```python\n#\n# Generate functionality graph from given test suites.\n# Generated functionality graph is in a form of 1 test suite.\n#\n\ndef f_generate_fun_graph(\n    d_TS_H\n):\n    \n    f_debug_start_with_function(\"f_generate_fun_graph\");\n\n    #\n    # Loop through KEY of dictionary\n    #\n\n    l_test_cases = [];\n\n    for key in d_TS_H:\n        logger.debug(\" \", key, d_TS_H[key]);\n        l_test_cases = list(set(l_test_cases + d_TS_H[key]));\n        logger.debug(\"  - list: \", l_test_cases);\n\n    d_new_TP = {'TP':l_test_cases};\n    \n    f_debug_end_with_function(\"f_generate_fun_graph\");\n    return(d_new_TP)\n```\nd_my_new_TP = f_generate_fun_graph(d_TS_H);d_my_new_TP\n\n```python\nstr(datetime.timedelta(seconds=666))\nprint(\"Notebook execution: \" + str(datetime.timedelta(seconds=(time.time()-notebook_start_time)))) \n```\n\n    Notebook execution: 0:00:00.752115\n\n\n### Function ```f_dynamic01Knapsack```\n\n\n```python\n#\n# temp function for f_dynamic01Knapsack debugging\n#\ndef f_printTableK(K):\n    print(\"Table K[i][w]\")\n    for i in range(n + 1):\n        for w in range(W +1 ):\n            print(K[i][w],end=\" \");\n        print(\"\");\n        \n#\n# 0-1 Knapsack solution with dynamic programming\n#\n# Input:\n#  W   .. knapsack weight capacity\n#  wt  .. items weights (sorted increasingly)\n#  val .. items values (sorted increasingly)\n#  n   .. number of items (should be distinct)\n#\n# Output:\n#  knVal .. sum of weights in knapsack\n#  knit  .. knit[i] = 1 .. item i is included\n#\ndef f_dynamic01Knapsack(W, wt, val, n):\n    # knit ... knapsack items\n    # knit[i] = 1 if item i is in knapsack\n    # default: no items in knapsack\n    knit = [0 for i in range(n)];\n    \n    # Initialize table K[n][W]\n    K = [[0 for w in range(W + 1)]\n            for i in range(n + 1)];\n    \n#    f_printTableK(K);\n        \n    # Build table K[n][W] for weight W\n    # and number of items n in bottom\n    # up manner\n    for i in range(n + 1):\n        for w in range(W + 1):\n#            print(\"i =\",i,\" w =\",w,\": \", end=\"\")\n#            f_printTableK(K);\n            if i == 0 or w == 0:\n                K[i][w] = 0\n            elif wt[i - 1] <= w:\n                K[i][w] = max(val[i - 1]\n                  + K[i - 1][w - wt[i - 1]],\n                               K[i - 1][w])\n            else:\n                K[i][w] = K[i - 1][w]\n \n    # stores the result of Knapsack\n    knVal = K[n][W]\n#    print(knVal)\n     \n    # input is knapsack full of items\n    w = W\n    # check items from largest to smallest\n    for i in range(n, 0, -1):\n        # all items are removed from knapsack\n        if knVal <= 0:\n            break\n        # either the result comes from the\n        # top (K[i-1][w]) or from (val[i-1]\n        # + K[i-1] [w-wt[i-1]]) as in Knapsackb\n        # table. If it comes from the latter\n        # one/ it means the item is included.\n        if knVal == K[i - 1][w]:\n            continue\n        else:\n \n            # This item is included.\n            knit[i-1] = 1;\n#            print(\"wt[\",i-1,\"] =\",wt[i - 1])\n             \n            # Since this weight is included\n            # its value is deducted\n            knVal = knVal - val[i - 1]\n            w = w - wt[i - 1]\n            \n    return(knVal, knit)\n```\n\n\n```python\n# Driver code\nl_val = [ 60, 100, 120 ]\nl_wt = [ 1, 2, 4 ]\nn_W = 5\nn = len(l_val)\n     \nf_dynamic01Knapsack(n_W, l_wt, l_val, n)\n```\n\n\n\n\n    (0, [1, 0, 1])\n\n\n\n* To stop here change this cell to __Code__\n* To continue change this cell to __Markdown__\n\n## Definitions overview\n\n\n```python\n#\n# Extra information about each variable (int, str, bool, float, tuple, dict, module, function, DataFrame, ...)\n#\n\n%whos\n```\n\n    Variable                          Type           Data/Info\n    ----------------------------------------------------------\n    Math                              type           <class 'IPython.core.display.Math'>\n    W                                 int            5\n    bool_draw_TS                      bool           True\n    cell_log_level                    int            30\n    d_TS_H                            dict           n=6\n    d_edge_label                      dict           n=9\n    d_node_label                      dict           n=6\n    d_position                        dict           n=6\n    d_xpos                            dict           n=6\n    d_ypos                            dict           n=6\n    datetime                          module         <module 'datetime' from '<...>\\\\oip\\\\lib\\\\datetime.py'>\n    df_edge                           DataFrame           delta  t_delta  thet<...>    27     1        0.25 \n    df_node                           DataFrame         kappa  t_kappa  theta <...>   2.8         1         \n    display                           function       <function display at 0x000002268C2FB318>\n    dynamic01Knapsack                 function       <function dynamic01Knapsa<...>ck at 0x000002269FF5C3A8>\n    errno                             module         <module 'errno' (built-in)>\n    f_TP_max_deduplication            function       <function f_TP_max_dedupl<...>on at 0x000002269FF63828>\n    f_TP_max_deduplication_ij         function       <function f_TP_max_dedupl<...>ij at 0x000002269FF63D38>\n    f_TP_max_deduplication_ji         function       <function f_TP_max_dedupl<...>ji at 0x000002269FF45168>\n    f_TP_min_deduplication            function       <function f_TP_min_dedupl<...>on at 0x000002269FF45318>\n    f_TS_Hx                           function       <function f_TS_Hx at 0x000002269FC2D438>\n    f_TS_nodes                        function       <function f_TS_nodes at 0x000002269FF51048>\n    f_debug_end_with_function         function       <function f_debug_end_wit<...>on at 0x000002269FC111F8>\n    f_debug_start_with_function       function       <function f_debug_start_w<...>on at 0x000002269FC11C18>\n    f_delta_measure                   function       <function f_delta_measure at 0x000002269FC714C8>\n    f_delta_measure_TP                function       <function f_delta_measure<...>TP at 0x000002269FF51F78>\n    f_delta_measure_TS                function       <function f_delta_measure<...>TS at 0x000002269FF51C18>\n    f_draw_TP_min_deduplication       function       <function f_draw_TP_min_d<...>on at 0x000002269FF458B8>\n    f_draw_TS                         function       <function f_draw_TS at 0x000002269FF35558>\n    f_draw_graph_TP_pure              function       <function f_draw_graph_TP<...>re at 0x000002269FDCC0D8>\n    f_draw_set_TS                     function       <function f_draw_set_TS at 0x000002269FF35CA8>\n    f_epsilon_measure                 function       <function f_epsilon_measu<...>re at 0x000002269FCC05E8>\n    f_generate_fun_graph              function       <function f_generate_fun_<...>ph at 0x000002269FF45DC8>\n    f_get_TS_weight                   function       <function f_get_TS_weight at 0x000002269FCB7318>\n    f_get_dataframe_from_dictionary   function       <function f_get_dataframe<...>ry at 0x000002269FCB7B88>\n    f_get_graph_weights               function       <function f_get_graph_wei<...>ts at 0x000002269FF351F8>\n    f_glambda_measure_TP              function       <function f_glambda_measu<...>TP at 0x000002269FCB7288>\n    f_glambda_measure_TS              function       <function f_glambda_measu<...>TS at 0x000002269FC71DC8>\n    f_kappa_measure                   function       <function f_kappa_measure at 0x000002269FF51288>\n    f_leave_one_edge                  function       <function f_leave_one_edge at 0x000002269FC11558>\n    f_list_edges                      function       <function f_list_edges at 0x00000226904668B8>\n    f_list_nodes                      function       <function f_list_nodes at 0x000002268E2B0C18>\n    f_print_var_value                 function       <function f_print_var_val<...>ue at 0x000002269FF63438>\n    f_read_data_from_files            function       <function f_read_data_fro<...>es at 0x000002269FF63168>\n    f_remove_common_edges             function       <function f_remove_common<...>es at 0x000002269FCB7E58>\n    f_rename_df_index_values          function       <function f_rename_df_ind<...>es at 0x000002269FF15E58>\n    f_set_edges                       function       <function f_set_edges at 0x000002269FC11288>\n    f_set_from_list_list              function       <function <lambda> at 0x000002269FC11EE8>\n    f_set_nodes                       function       <function f_set_nodes at 0x000002269FC23048>\n    f_size_Hx                         function       <function f_size_Hx at 0x000002269FC115E8>\n    f_sort_TS_in_TP                   function       <function f_sort_TS_in_TP at 0x000002269FF35438>\n    f_theta_measure                   function       <function f_theta_measure at 0x000002269FF51708>\n    f_tmp_dump_file                   function       <function f_tmp_dump_file at 0x000002269FCB7678>\n    file_handler                      FileHandler    <FileHandler C:\\Users\\gre<...>inImplCosts.log (NOTSET)>\n    formatter                         Formatter      <logging.Formatter object at 0x000002269FF2C248>\n    key                               int            6\n    logger                            Logger         <Logger __main__ (WARNING)>\n    logging                           module         <module 'logging' from 'C<...>b\\\\logging\\\\__init__.py'>\n    matplotlib                        module         <module 'matplotlib' from<...>matplotlib\\\\__init__.py'>\n    n                                 int            3\n    n_font_size                       int            50\n    networkx                          module         <module 'networkx' from '<...>\\\\networkx\\\\__init__.py'>\n    notebook_start_time               float          1627149804.8853343\n    os                                module         <module 'os' from 'C:\\\\Us<...>\\\\envs\\\\oip\\\\lib\\\\os.py'>\n    pandas                            module         <module 'pandas' from 'C:<...>es\\\\pandas\\\\__init__.py'>\n    printTableK                       function       <function printTableK at 0x000002269FF5C318>\n    pyplot                            module         <module 'matplotlib.pyplo<...>\\\\matplotlib\\\\pyplot.py'>\n    s_c_graph_data_delimiter          str            ,\n    s_c_results                       str            results/\n    s_c_results_other                 str            pdf/\n    s_file_TS                         str            H_010.TestSuites\n    s_file_graphE                     str            graphE.csv\n    s_file_graphN                     str            graphV.csv\n    section_log_level                 int            30\n    set_trace                         function       <function set_trace at 0x000002268C1B5798>\n    t_c_test_phase_dim                tuple          n=2\n    time                              module         <module 'time' (built-in)>\n    unittest                          module         <module 'unittest' from '<...>\\\\unittest\\\\__init__.py'>\n    val                               list           n=3\n    warnings                          module         <module 'warnings' from '<...>\\\\oip\\\\lib\\\\warnings.py'>\n    wt                                list           n=3\n\n\n\n## Read data from file\n\n### Content of input data\n\n\n```python\n# local variables for file names\ns_file_graphN = \"graphV.csv\";\ns_file_graphE = \"graphE.csv\";\ns_file_TS     = \"H_010.TestSuites\";\n```\n\n\n```python\ndef f_tmp_dump_file(s_file_name):\n    tmp_file = open(\"data/\"+s_file_name, \"r\");\n\n    print(\"Content of the file \\\"\"+s_file_name+\"\\\"\");\n    print(\"------------------------------------------------------------------------------\")\n    print(tmp_file.read())\n\n```\n\n\n```python\nf_tmp_dump_file(s_file_graphN);\nf_tmp_dump_file(s_file_graphE);\nf_tmp_dump_file(s_file_TS);\n```\n\n    Content of the file \"graphV.csv\"\n    ------------------------------------------------------------------------------\n    v,kappa,t_kappa,theta,t_theta,sigma,x_position,y_position\n    1,30,1,10,0,0.15,1,1\n    2,25,1,8,1,0.15,1.5,0\n    3,15,1,5,1,0.1,2,1\n    4,20,1,7,1,0.2,1.5,2\n    5,20,1,6,1,0.15,0.2,1\n    6,35,1,12,1,0.25,2.8,1\n    \n    Content of the file \"graphE.csv\"\n    ------------------------------------------------------------------------------\n    u,v,delta,t_delta,theta,t_theta,sigma\n    1,2,28,1,2,1,0.1\n    1,3,35,1,40,1,0.05\n    2,3,27,1,11,0,0.07\n    3,4,15,0,10,0,0.07\n    1,4,28,1,25,1,0.1\n    5,2,10,1,15,1,0.08\n    5,4,10,1,15,1,0.08\n    6,2,17,1,27,1,0.2\n    6,4,17,1,27,1,0.25\n    \n    Content of the file \"H_010.TestSuites\"\n    ------------------------------------------------------------------------------\n    {\n    \t'H1': [(1, 3), (5,4), (5,2)],\n    \t'H2': [(1, 4), (1, 3), (3, 4)],\n    \t'H3': [(3, 4), (6,2)],\n    \t'H4': [(1, 2), (1, 3), (1, 4), (2, 3), (3, 4)],\n    \t'H5': [(1, 2), (1, 4), (2, 3)],\n    \t'H6': [(2, 3), (3, 4)],\n    }\n\n\n\n```python\n# Read graph nodes from File\ndf_node = pandas.read_csv(\"data/\"+s_file_graphN, sep=s_c_graph_data_delimiter, index_col = 0)\n# Results in global variables\n#   global df_node\n#   global df_edge\n#   global d_TS_H\n#   global d_position\n#   global d_node_label;\n#   global d_edge_label;\n\n# are there data for node position in the df_node\nif(('x_position' and 'y_position') in df_node.columns):\n    d_xpos = df_node['x_position'].to_dict()\n    d_ypos = df_node['y_position'].to_dict()\n\n    d_position = {}\n    for key in d_xpos.keys():\n        d_position[key] = tuple(d_position[key] for d_position in [d_xpos,d_ypos])\n    # global variable d_position is updated\n\n# Read graph edges from File\ndf_edge = pandas.read_csv(\"data/\"+s_file_graphE, sep=s_c_graph_data_delimiter, index_col = [0,1])\n\n```\n\n\n```python\ndf_node\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>kappa</th>\n      <th>t_kappa</th>\n      <th>theta</th>\n      <th>t_theta</th>\n      <th>sigma</th>\n      <th>x_position</th>\n      <th>y_position</th>\n    </tr>\n    <tr>\n      <th>v</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>30</td>\n      <td>1</td>\n      <td>10</td>\n      <td>0</td>\n      <td>0.15</td>\n      <td>1.0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>25</td>\n      <td>1</td>\n      <td>8</td>\n      <td>1</td>\n      <td>0.15</td>\n      <td>1.5</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>15</td>\n      <td>1</td>\n      <td>5</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>2.0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>20</td>\n      <td>1</td>\n      <td>7</td>\n      <td>1</td>\n      <td>0.20</td>\n      <td>1.5</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>20</td>\n      <td>1</td>\n      <td>6</td>\n      <td>1</td>\n      <td>0.15</td>\n      <td>0.2</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>35</td>\n      <td>1</td>\n      <td>12</td>\n      <td>1</td>\n      <td>0.25</td>\n      <td>2.8</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf_node\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>kappa</th>\n      <th>t_kappa</th>\n      <th>theta</th>\n      <th>t_theta</th>\n      <th>sigma</th>\n      <th>x_position</th>\n      <th>y_position</th>\n    </tr>\n    <tr>\n      <th>v</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>30</td>\n      <td>1</td>\n      <td>10</td>\n      <td>0</td>\n      <td>0.15</td>\n      <td>1.0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>25</td>\n      <td>1</td>\n      <td>8</td>\n      <td>1</td>\n      <td>0.15</td>\n      <td>1.5</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>15</td>\n      <td>1</td>\n      <td>5</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>2.0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>20</td>\n      <td>1</td>\n      <td>7</td>\n      <td>1</td>\n      <td>0.20</td>\n      <td>1.5</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>20</td>\n      <td>1</td>\n      <td>6</td>\n      <td>1</td>\n      <td>0.15</td>\n      <td>0.2</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>35</td>\n      <td>1</td>\n      <td>12</td>\n      <td>1</td>\n      <td>0.25</td>\n      <td>2.8</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf_edge\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>delta</th>\n      <th>t_delta</th>\n      <th>theta</th>\n      <th>t_theta</th>\n      <th>sigma</th>\n    </tr>\n    <tr>\n      <th>u</th>\n      <th>v</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">1</th>\n      <th>2</th>\n      <td>28</td>\n      <td>1</td>\n      <td>2</td>\n      <td>1</td>\n      <td>0.10</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>35</td>\n      <td>1</td>\n      <td>40</td>\n      <td>1</td>\n      <td>0.05</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <th>3</th>\n      <td>27</td>\n      <td>1</td>\n      <td>11</td>\n      <td>0</td>\n      <td>0.07</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <th>4</th>\n      <td>15</td>\n      <td>0</td>\n      <td>10</td>\n      <td>0</td>\n      <td>0.07</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <th>4</th>\n      <td>28</td>\n      <td>1</td>\n      <td>25</td>\n      <td>1</td>\n      <td>0.10</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">5</th>\n      <th>2</th>\n      <td>10</td>\n      <td>1</td>\n      <td>15</td>\n      <td>1</td>\n      <td>0.08</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>10</td>\n      <td>1</td>\n      <td>15</td>\n      <td>1</td>\n      <td>0.08</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">6</th>\n      <th>2</th>\n      <td>17</td>\n      <td>1</td>\n      <td>27</td>\n      <td>1</td>\n      <td>0.20</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>17</td>\n      <td>1</td>\n      <td>27</td>\n      <td>1</td>\n      <td>0.25</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nd_position\n```\n\n\n\n\n    {1: (1.0, 1), 2: (1.5, 0), 3: (2.0, 1), 4: (1.5, 2), 5: (0.2, 1), 6: (2.8, 1)}\n\n\n\n### Read data from file with ```f_read_data_from_files```\n\n\n```python\n#\n# with a use of function f_read_data_from_files\n#\n\ndf_TP, d_TP_weight = f_read_data_from_files(s_file_graphN, s_file_graphE, s_file_TS)\n```\n\n\n```python\ndf_node\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>kappa</th>\n      <th>t_kappa</th>\n      <th>theta</th>\n      <th>t_theta</th>\n      <th>sigma</th>\n      <th>x_position</th>\n      <th>y_position</th>\n      <th>delta</th>\n      <th>epsilon</th>\n    </tr>\n    <tr>\n      <th>v</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>30</td>\n      <td>1</td>\n      <td>10</td>\n      <td>0</td>\n      <td>0.15</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>30</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>25</td>\n      <td>1</td>\n      <td>8</td>\n      <td>1</td>\n      <td>0.15</td>\n      <td>1.5</td>\n      <td>0</td>\n      <td>33</td>\n      <td>0.15</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>15</td>\n      <td>1</td>\n      <td>5</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>2.0</td>\n      <td>1</td>\n      <td>20</td>\n      <td>0.10</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>20</td>\n      <td>1</td>\n      <td>7</td>\n      <td>1</td>\n      <td>0.20</td>\n      <td>1.5</td>\n      <td>2</td>\n      <td>27</td>\n      <td>0.20</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>20</td>\n      <td>1</td>\n      <td>6</td>\n      <td>1</td>\n      <td>0.15</td>\n      <td>0.2</td>\n      <td>1</td>\n      <td>26</td>\n      <td>0.15</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>35</td>\n      <td>1</td>\n      <td>12</td>\n      <td>1</td>\n      <td>0.25</td>\n      <td>2.8</td>\n      <td>1</td>\n      <td>47</td>\n      <td>0.25</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf_node\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>kappa</th>\n      <th>t_kappa</th>\n      <th>theta</th>\n      <th>t_theta</th>\n      <th>sigma</th>\n      <th>x_position</th>\n      <th>y_position</th>\n      <th>delta</th>\n      <th>epsilon</th>\n    </tr>\n    <tr>\n      <th>v</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>30</td>\n      <td>1</td>\n      <td>10</td>\n      <td>0</td>\n      <td>0.15</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>30</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>25</td>\n      <td>1</td>\n      <td>8</td>\n      <td>1</td>\n      <td>0.15</td>\n      <td>1.5</td>\n      <td>0</td>\n      <td>33</td>\n      <td>0.15</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>15</td>\n      <td>1</td>\n      <td>5</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>2.0</td>\n      <td>1</td>\n      <td>20</td>\n      <td>0.10</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>20</td>\n      <td>1</td>\n      <td>7</td>\n      <td>1</td>\n      <td>0.20</td>\n      <td>1.5</td>\n      <td>2</td>\n      <td>27</td>\n      <td>0.20</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>20</td>\n      <td>1</td>\n      <td>6</td>\n      <td>1</td>\n      <td>0.15</td>\n      <td>0.2</td>\n      <td>1</td>\n      <td>26</td>\n      <td>0.15</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>35</td>\n      <td>1</td>\n      <td>12</td>\n      <td>1</td>\n      <td>0.25</td>\n      <td>2.8</td>\n      <td>1</td>\n      <td>47</td>\n      <td>0.25</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf_edge\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>kappa</th>\n      <th>t_kappa</th>\n      <th>theta</th>\n      <th>t_theta</th>\n      <th>sigma</th>\n      <th>delta</th>\n      <th>epsilon</th>\n    </tr>\n    <tr>\n      <th>u</th>\n      <th>v</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">1</th>\n      <th>2</th>\n      <td>28</td>\n      <td>1</td>\n      <td>2</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>30</td>\n      <td>0.10</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>35</td>\n      <td>1</td>\n      <td>40</td>\n      <td>1</td>\n      <td>0.05</td>\n      <td>75</td>\n      <td>0.05</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <th>3</th>\n      <td>27</td>\n      <td>1</td>\n      <td>11</td>\n      <td>0</td>\n      <td>0.07</td>\n      <td>27</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <th>4</th>\n      <td>15</td>\n      <td>0</td>\n      <td>10</td>\n      <td>0</td>\n      <td>0.07</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <th>4</th>\n      <td>28</td>\n      <td>1</td>\n      <td>25</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>53</td>\n      <td>0.10</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">5</th>\n      <th>2</th>\n      <td>10</td>\n      <td>1</td>\n      <td>15</td>\n      <td>1</td>\n      <td>0.08</td>\n      <td>25</td>\n      <td>0.08</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>10</td>\n      <td>1</td>\n      <td>15</td>\n      <td>1</td>\n      <td>0.08</td>\n      <td>25</td>\n      <td>0.08</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">6</th>\n      <th>2</th>\n      <td>17</td>\n      <td>1</td>\n      <td>27</td>\n      <td>1</td>\n      <td>0.20</td>\n      <td>44</td>\n      <td>0.20</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>17</td>\n      <td>0</td>\n      <td>27</td>\n      <td>0</td>\n      <td>0.25</td>\n      <td>44</td>\n      <td>0.25</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nd_TS_H\n```\n\n\n\n\n    {'H1': [(1, 3), (5, 4), (5, 2)],\n     'H2': [(1, 4), (1, 3), (3, 4)],\n     'H3': [(3, 4), (6, 2)],\n     'H4': [(1, 2), (1, 3), (1, 4), (2, 3), (3, 4)],\n     'H5': [(1, 2), (1, 4), (2, 3)],\n     'H6': [(2, 3), (3, 4)]}\n\n\n\n\n```python\nd_position\n```\n\n\n\n\n    {1: (1.0, 1), 2: (1.5, 0), 3: (2.0, 1), 4: (1.5, 2), 5: (0.2, 1), 6: (2.8, 1)}\n\n\n\n\n```python\nd_node_label\n```\n\n\n\n\n    {1: '$v_1$', 2: '$v_2$', 3: '$v_3$', 4: '$v_4$', 5: '$v_5$', 6: '$v_6$'}\n\n\n\n\n```python\nd_edge_label\n```\n\n\n\n\n    {(1, 2): '$e_{1}$',\n     (1, 3): '$e_{2}$',\n     (2, 3): '$e_{3}$',\n     (3, 4): '$e_{4}$',\n     (1, 4): '$e_{5}$',\n     (5, 2): '$e_{6}$',\n     (5, 4): '$e_{7}$',\n     (6, 2): '$e_{8}$',\n     (6, 4): '$e_{9}$'}\n\n\n\n## Presentation of input data\n\n\n```python\n#\n# Read all data about Test Suites, Test Cases, and implicitly Functionality Graph from file\n#\n#logger.setLevel(logging.DEBUG)\n\ndf_TP, d_TP_weight = f_read_data_from_files(\"graphV.csv\", \"graphE.csv\", \"H_000.TestSuites\");\n# Return values as 'global' variables:\n#   df_node\n#   df_edge\n#   d_TS_H\n#   d_position\n#   d_node_label\n#   d_edge_label\n\n#logger.setLevel(cell_log_level)\n\nf_print_var_value('df_TP');\nf_print_var_value('d_TP_weight');\nf_print_var_value('df_node');\nf_print_var_value('df_edge');\nf_print_var_value('d_TS_H');\nf_print_var_value('d_position');\nf_print_var_value('d_node_label');\nf_print_var_value('d_edge_label');\n```\n\n    ============================================================ df_TP ============================================================\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>TS_edges</th>\n      <th>kappa</th>\n      <th>theta</th>\n      <th>delta</th>\n      <th>epsilon</th>\n      <th>size</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H1</th>\n      <td>[(1, 2), (1, 4), (2, 3), (6, 4), (6, 2)]</td>\n      <td>274</td>\n      <td>81</td>\n      <td>355</td>\n      <td>1.35</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>H2</th>\n      <td>[(1, 4), (1, 3), (3, 4), (5, 4)]</td>\n      <td>176</td>\n      <td>80</td>\n      <td>256</td>\n      <td>0.68</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>H3</th>\n      <td>[(1, 3)]</td>\n      <td>85</td>\n      <td>40</td>\n      <td>125</td>\n      <td>0.15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>H4</th>\n      <td>[(1, 3), (1, 4), (2, 3), (5, 4), (5, 2), (6, 4), (6, 2)]</td>\n      <td>327</td>\n      <td>149</td>\n      <td>476</td>\n      <td>1.61</td>\n      <td>7</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    ========================================================= d_TP_weight =========================================================\n    {'theta': 350, 'delta': 902, 'epsilon': 1.71}\n    =========================================================== df_node ===========================================================\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>kappa</th>\n      <th>t_kappa</th>\n      <th>theta</th>\n      <th>t_theta</th>\n      <th>sigma</th>\n      <th>x_position</th>\n      <th>y_position</th>\n      <th>delta</th>\n      <th>epsilon</th>\n    </tr>\n    <tr>\n      <th>v</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>30</td>\n      <td>1</td>\n      <td>10</td>\n      <td>0</td>\n      <td>0.15</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>30</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>25</td>\n      <td>1</td>\n      <td>8</td>\n      <td>1</td>\n      <td>0.15</td>\n      <td>1.5</td>\n      <td>0</td>\n      <td>33</td>\n      <td>0.15</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>15</td>\n      <td>1</td>\n      <td>5</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>2.0</td>\n      <td>1</td>\n      <td>20</td>\n      <td>0.10</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>20</td>\n      <td>1</td>\n      <td>7</td>\n      <td>1</td>\n      <td>0.20</td>\n      <td>1.5</td>\n      <td>2</td>\n      <td>27</td>\n      <td>0.20</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>20</td>\n      <td>1</td>\n      <td>6</td>\n      <td>1</td>\n      <td>0.15</td>\n      <td>0.2</td>\n      <td>1</td>\n      <td>26</td>\n      <td>0.15</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>35</td>\n      <td>1</td>\n      <td>12</td>\n      <td>1</td>\n      <td>0.25</td>\n      <td>2.8</td>\n      <td>1</td>\n      <td>47</td>\n      <td>0.25</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    =========================================================== df_edge ===========================================================\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>kappa</th>\n      <th>t_kappa</th>\n      <th>theta</th>\n      <th>t_theta</th>\n      <th>sigma</th>\n      <th>delta</th>\n      <th>epsilon</th>\n    </tr>\n    <tr>\n      <th>u</th>\n      <th>v</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">1</th>\n      <th>2</th>\n      <td>28</td>\n      <td>1</td>\n      <td>2</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>30</td>\n      <td>0.10</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>35</td>\n      <td>1</td>\n      <td>40</td>\n      <td>1</td>\n      <td>0.05</td>\n      <td>75</td>\n      <td>0.05</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <th>3</th>\n      <td>27</td>\n      <td>1</td>\n      <td>11</td>\n      <td>0</td>\n      <td>0.07</td>\n      <td>27</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <th>4</th>\n      <td>15</td>\n      <td>0</td>\n      <td>10</td>\n      <td>0</td>\n      <td>0.07</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <th>4</th>\n      <td>28</td>\n      <td>1</td>\n      <td>25</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>53</td>\n      <td>0.10</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">5</th>\n      <th>2</th>\n      <td>10</td>\n      <td>1</td>\n      <td>15</td>\n      <td>1</td>\n      <td>0.08</td>\n      <td>25</td>\n      <td>0.08</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>10</td>\n      <td>1</td>\n      <td>15</td>\n      <td>1</td>\n      <td>0.08</td>\n      <td>25</td>\n      <td>0.08</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">6</th>\n      <th>2</th>\n      <td>17</td>\n      <td>1</td>\n      <td>27</td>\n      <td>1</td>\n      <td>0.20</td>\n      <td>44</td>\n      <td>0.20</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>17</td>\n      <td>1</td>\n      <td>27</td>\n      <td>1</td>\n      <td>0.25</td>\n      <td>44</td>\n      <td>0.25</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    ============================================================ d_TS_H ===========================================================\n    {'H1': [(1, 2), (1, 4), (2, 3), (6, 4), (6, 2)], 'H2': [(1, 4), (1, 3), (3, 4), (5, 4)], 'H3': [(1, 3)], 'H4': [(1, 3), (1, 4), (2, 3), (5, 4), (5, 2), (6, 4), (6, 2)]}\n    ========================================================== d_position =========================================================\n    {1: (1.0, 1), 2: (1.5, 0), 3: (2.0, 1), 4: (1.5, 2), 5: (0.2, 1), 6: (2.8, 1)}\n    ========================================================= d_node_label ========================================================\n    {1: '$v_1$', 2: '$v_2$', 3: '$v_3$', 4: '$v_4$', 5: '$v_5$', 6: '$v_6$'}\n    ========================================================= d_edge_label ========================================================\n    {(1, 2): '$e_{1}$', (1, 3): '$e_{2}$', (2, 3): '$e_{3}$', (3, 4): '$e_{4}$', (1, 4): '$e_{5}$', (5, 2): '$e_{6}$', (5, 4): '$e_{7}$', (6, 2): '$e_{8}$', (6, 4): '$e_{9}$'}\n\n\n\n```python\n#\n# Requred input data: data frame of test suites (test phase)\n#\n#df_TP_fun_graph, d_TP_weight_fun_graph = f_read_data_from_files(\"graphV.csv\", \"graphE.csv\", \"Fun_graph.TestSuites\")\n\ndf_TP_fun_graph = f_generate_fun_graph(d_TS_H);\nf_print_var_value('df_TP_fun_graph');\n```\n\n    ======================================================= df_TP_fun_graph =======================================================\n    {'TP': [(1, 2), (6, 4), (5, 4), (1, 3), (5, 2), (1, 4), (6, 2), (2, 3), (3, 4)]}\n\n\n## Graphs generated for the article\n\n### Functionality Graph\n\n\n```python\n#\n# Draw functionality graph\n#\n\n#\n# Read all data about Test Suites, Test Cases, and implicitly Functionality Graph from file\n#\n#logger.setLevel(logging.DEBUG)\n\ndf_TP, d_TP_weight = f_read_data_from_files(\"graphV.csv\", \"graphE.csv\", \"H_000.TestSuites\");\n# Return values as 'global' variables:\n#   df_node\n#   df_edge\n#   d_TS_H\n#   d_position\n#   d_node_label\n#   d_edge_label\n\n#\n# Requred input data: data frame of test suites (test phase)\n#\n#df_TP_fun_graph, d_TP_weight_fun_graph = f_read_data_from_files(\"graphV.csv\", \"graphE.csv\", \"Fun_graph.TestSuites\")\n\ndf_TP_fun_graph = f_generate_fun_graph(d_TS_H);\n\n#\n# Draw\n#\nf_draw_TS(df_TP_fun_graph, \"\", \"fun-graph.eps\", \"\", True, (15,8));\n\n```\n\n\n```python\n#\n# Draw functionality graph\n#\n\n#\n# Read all data about Test Suites, Test Cases, and implicitly Functionality Graph from file\n#\n#logger.setLevel(logging.DEBUG)\n\ndf_TP, d_TP_weight = f_read_data_from_files(\"graphV.csv\", \"graphE.csv\", \"H_000.TestSuites\");\n\n#\n# Requred input data: data frame of test suites (test phase)\n#\n#df_TP_fun_graph, d_TP_weight_fun_graph = f_read_data_from_files(\"graphV.csv\", \"graphE.csv\", \"Fun_graph.TestSuites\")\n\ndf_TP_fun_graph = f_generate_fun_graph(d_TS_H);\n\n#\n# Draw\n#\ndisplay(Math('\\\\textbf{Article Figure:}\\\\textrm{ Example of the functionality graph } G^P.\\\n              \\\\textrm{Vertices } v_1, ..., v_6 \\\\textrm{ present six functionalities, edges } e_1, ..., e_9\\\n              \\\\textrm{ present nine f-influences.}'));\n\n# without name/title \"Functionality graph\" on the figure\n# f_draw_TS(df_TP_fun_graph, \"\", s_c_results_other+\"fun-graph.pdf\", \"\", True, (15,10));\n# f_draw_TS(df_TP_fun_graph, \"\", s_c_results_other+\"fun-graph.pdf\", \"Functionality graph\", (17,7));\n# f_draw_TS(df_TP_fun_graph.to_dict()['TS_edges'], \"\", \"fun-graph.svg\", \"Functionality graph\", (17,7));\n# f_print_var_value('','Functionality graph (EPS)')\n# generate eps file for the article\nf_draw_TS(df_TP_fun_graph, \"\", \"fun-graph.eps\", \"\", True, (15,8));\nf_draw_TS(df_TP_fun_graph, \"\", s_c_results_other+\"fun-graph.pdf\", \"\", False, (15,8));\n\n```\n\n### Test phase\n\n\n```python\n#\n# Read data frame\n#\n#logger.setLevel(logging.DEBUG)\ndf_TP, d_TP_weight = f_read_data_from_files(\"graphV.csv\", \"graphE.csv\", \"H_000.TestSuites\")\n#logger.setLevel(cell_log_level)\n\n#\n# Draw data frames\n#\ndisplay(Math('\\\\textbf{Article Figure:}\\\\textrm{ Example of a test phase } \\mathcal H = \\{{^i}\\!H\\}_{i=1}^4'))\nf_draw_TS(df_TP.to_dict()['TS_edges'], \"\", s_c_results_other+\"test-phase-H.pdf\",\"\",False, (50,10))\nf_draw_TS(df_TP.to_dict()['TS_edges'], \"\", \"test-phase-H.eps\",\"Example of a test phase\",True, (50,10))\n\n```\n\n### Test Phase Min Deduplication: $A_{1a}$\n\n\n```python\n# Store the original log level into 'notebook_log_level'\nnotebook_log_level = logger.getEffectiveLevel()\n```\n\n\n```python\n#\n# To display test suites graphs set logging level to DEBUG\n#\n\nlogger.setLevel(section_log_level)\n```\n\n\n```python\nt_c_test_phase_dim=(70,7)\n```\n\n\n```python\n#\n# Read data frame\n#\ndf_TP, d_TP_weights = f_read_data_from_files(\"graphV.csv\", \"graphE.csv\", \"H_000.TestSuites\")\n\n#\n# Sort data frame\n#\ndf_TP_sorted = f_sort_TS_in_TP(df_TP,['delta','size'],d_TS_H,bool_local_sort_order_ascending=True)\n\n#logger.setLevel(logging.DEBUG)\n#\n# Execute Test Phase Min Deduplication\n#\ndf_TP_Min = f_TP_min_deduplication(df_TP_sorted)\n\n#\n# Draw data frames\n#\n#\n# To display graphs set logging level to DEBUG\n#\nlogger.setLevel(cell_log_level)\ndisplay(Math('\\\\textbf{Article Figure:}\\\\textrm{ Subgraphs } {^{1}\\!M},{^{2}\\!M},{^{3}\\!M},{^{4}\\!M}\\\n              \\\\textrm{ as the result of} \\\\textit{ Test Phase Deduplication Algorithm } A_{1a}'));\n\nf_draw_TS(df_TP_Min.to_dict()['TS_edges'], \"delta\", \"min-dedupe-weights.eps\",\"\",True,t_c_test_phase_dim)\n\n      \n```\n\n### Test Phase Max Deduplication: $A_{1b}$\n\n\n```python\n#\n# Read data frame\n#\n#logger.setLevel(logging.DEBUG)\ndf_TP, d_TP_weight = f_read_data_from_files(\"graphV.csv\", \"graphE.csv\", \"H_000.TestSuites\")\n#logger.setLevel(cell_log_level)\n\nf_print_var_value('df_TP','Test phase (as a set of test suites)');\n\n#\n# Sort Test Suites - Ascending\n#\nbool_sort_order_ascending = False;\ndf_TP_sorted = f_sort_TS_in_TP(df_TP,['delta','size'],d_TS_H,bool_local_sort_order_ascending=bool_sort_order_ascending)\nf_print_var_value('df_TP_sorted','Sort data frame - for max deduplication: bool_sort_order_ascending='+str(bool_sort_order_ascending))\n\n#logger.setLevel(logging.DEBUG)\n#\n# Execute Test Phase Max Deduplication\n#\ndf_TP_Large_num = f_TP_max_deduplication(df_TP_sorted)\nf_print_var_value('df_TP_Large_num','Result from Test Phase Max Deduplication');\n\n#logger.setLevel(cell_log_level)\n\n#\n# Draw data frames\n#\ndisplay(Math('\\\\textbf{Article Figure:}\\\\textrm{ Subgraphs } {^{1}\\!M},{^{2}\\!M},{^{3}\\!M},{^{4}\\!M}\\\n              \\\\textrm{ as the result of} \\\\textit{ Test Phase Deduplication Algorithm } A_{1b}'));\n## f_draw_TS(df_TP_Large_num.to_dict()['TS_edges'], \"delta\", s_c_results_other+\"max-dedupe-weights-nosort.pdf\",s_title=\"\", bool_print_to_terminal=False)\nf_draw_TS(df_TP_Large_num.to_dict()['TS_edges'], \"delta\", s_c_results_other+\"max-dedupe-weights-nosort.pdf\", \"\", False)\nf_draw_TS(df_TP_Large_num.to_dict()['TS_edges'], \"delta\", \"max-dedupe-weights-nosort.eps\", \"\")\n\n```\n\n### Algorithm $A_2$ for software testing optimization\n\n\n```python\ndf_node\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>kappa</th>\n      <th>t_kappa</th>\n      <th>theta</th>\n      <th>t_theta</th>\n      <th>sigma</th>\n      <th>x_position</th>\n      <th>y_position</th>\n      <th>delta</th>\n      <th>epsilon</th>\n    </tr>\n    <tr>\n      <th>v</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>30</td>\n      <td>1</td>\n      <td>10</td>\n      <td>0</td>\n      <td>0.15</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>30</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>25</td>\n      <td>1</td>\n      <td>8</td>\n      <td>1</td>\n      <td>0.15</td>\n      <td>1.5</td>\n      <td>0</td>\n      <td>33</td>\n      <td>0.15</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>15</td>\n      <td>1</td>\n      <td>5</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>2.0</td>\n      <td>1</td>\n      <td>20</td>\n      <td>0.10</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>20</td>\n      <td>1</td>\n      <td>7</td>\n      <td>1</td>\n      <td>0.20</td>\n      <td>1.5</td>\n      <td>2</td>\n      <td>27</td>\n      <td>0.20</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>20</td>\n      <td>1</td>\n      <td>6</td>\n      <td>1</td>\n      <td>0.15</td>\n      <td>0.2</td>\n      <td>1</td>\n      <td>26</td>\n      <td>0.15</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>35</td>\n      <td>1</td>\n      <td>12</td>\n      <td>1</td>\n      <td>0.25</td>\n      <td>2.8</td>\n      <td>1</td>\n      <td>47</td>\n      <td>0.25</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf_edge\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>kappa</th>\n      <th>t_kappa</th>\n      <th>theta</th>\n      <th>t_theta</th>\n      <th>sigma</th>\n      <th>delta</th>\n      <th>epsilon</th>\n    </tr>\n    <tr>\n      <th>u</th>\n      <th>v</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">1</th>\n      <th>2</th>\n      <td>28</td>\n      <td>1</td>\n      <td>2</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>30</td>\n      <td>0.10</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>35</td>\n      <td>1</td>\n      <td>40</td>\n      <td>1</td>\n      <td>0.05</td>\n      <td>75</td>\n      <td>0.05</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <th>3</th>\n      <td>27</td>\n      <td>1</td>\n      <td>11</td>\n      <td>0</td>\n      <td>0.07</td>\n      <td>27</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <th>4</th>\n      <td>15</td>\n      <td>0</td>\n      <td>10</td>\n      <td>0</td>\n      <td>0.07</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <th>4</th>\n      <td>28</td>\n      <td>1</td>\n      <td>25</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>53</td>\n      <td>0.10</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">5</th>\n      <th>2</th>\n      <td>10</td>\n      <td>1</td>\n      <td>15</td>\n      <td>1</td>\n      <td>0.08</td>\n      <td>25</td>\n      <td>0.08</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>10</td>\n      <td>1</td>\n      <td>15</td>\n      <td>1</td>\n      <td>0.08</td>\n      <td>25</td>\n      <td>0.08</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">6</th>\n      <th>2</th>\n      <td>17</td>\n      <td>1</td>\n      <td>27</td>\n      <td>1</td>\n      <td>0.20</td>\n      <td>44</td>\n      <td>0.20</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>17</td>\n      <td>1</td>\n      <td>27</td>\n      <td>1</td>\n      <td>0.25</td>\n      <td>44</td>\n      <td>0.25</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n#\n# p_j ... l_pj\n# w_j ... l_wj\n#\nl_pj = list(map(lambda x,y: x*y ,df_edge['kappa'].tolist(), df_edge['sigma'].tolist()))\nl_wj = df_edge['kappa'].tolist()\n```\n\n\n```python\nl_pj\n```\n\n\n\n\n    [2.8000000000000003,\n     1.75,\n     1.8900000000000001,\n     1.05,\n     2.8000000000000003,\n     0.8,\n     0.8,\n     3.4000000000000004,\n     4.25]\n\n\n\n\n```python\nl_wj\n```\n\n\n\n\n    [28, 35, 27, 15, 28, 10, 10, 17, 17]\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\nstr(datetime.timedelta(seconds=666))\nprint(\"Notebook execution: \" + str(datetime.timedelta(seconds=(time.time()-notebook_start_time)))) \n```\n\n    Notebook execution: 0:00:56.237823\n\n\n## The end ---------------------------------------\n", "meta": {"hexsha": "14a2c00dfe3f8d33bc00094c3bfa4e79c8579271", "size": 1024081, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "MinImplCosts.ipynb", "max_stars_repo_name": "molan/Optimal-Implementation-Phase", "max_stars_repo_head_hexsha": "fae29df9a8a37d51b85904981c101ae7cfc46db4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MinImplCosts.ipynb", "max_issues_repo_name": "molan/Optimal-Implementation-Phase", "max_issues_repo_head_hexsha": "fae29df9a8a37d51b85904981c101ae7cfc46db4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MinImplCosts.ipynb", "max_forks_repo_name": "molan/Optimal-Implementation-Phase", "max_forks_repo_head_hexsha": "fae29df9a8a37d51b85904981c101ae7cfc46db4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 178.847537548, "max_line_length": 232384, "alphanum_fraction": 0.8673415482, "converted": true, "num_tokens": 33498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936415888237616, "lm_q2_score": 0.0967057848352487, "lm_q1q2_score": 0.0347525930263792}}
{"text": "11/24/2018\n# Learning and Exploring Artificial Neural Networks\nI've always been interested in technology and exploring how the body works from since I can remember.  Simulating the entire human body in a computer is the ultimate goal of mine, but the practicallity of that is years off in the future.  I'm mostly interested in simulating the human mind, not because it would be a great scientific feat, but for the very fact that it can be maniuplated.  This interest of mine landed me on the front door step of artificial intelligence (AI).  Before I sat down and started studying about AI, I wanted to get an appreciation for the subject matter.  I've started to look at a lot of video's that were informative about AI at the 10,000ft level over the course of a couple months.  This appreciation period made me realize that I wanted to study deep learning.  Deep learning is part of machine learning and machine learning is part of AI. I also wanted to figure out where to start my study, top down or bottom up.  Even though a top down approach would of allowed me to get started doing real practical work, I'm the type of person who enjoys starting from the bottom up and learning the fundamentals.  Therefore, I decided to start as far back as practically possible, the history of the perceptron.\n\n<figure style=\"text-align:center;\">\n  \n  <figcaption>Artificial Intelligence, Machine Learning, and Deep Learning Relationship</figcaption>\n</figure> \n\n# Brief History Overview\nArtificial Neural Networks (ANN's) are inspired by the brain, a biological neural network.  Neural networks are made up of connected neurons to carry out specific functions/computations when activated.  [Warren Sturgis McCulloch](https://en.wikipedia.org/wiki/Warren_Sturgis_McCulloch), a neurophysiologist, and [Walter Pitts](https://en.wikipedia.org/wiki/Walter_Pitts), a logician, worked in the field of computational neuroscience and created computational models based on mathematical algorithms called threshold logic.  [Frank Rosenblatt](https://en.wikipedia.org/wiki/Frank_Rosenblatt) introduced the perceptron in 1958 inspired by the earlier work of Warren McCulloch.  There was an optimism about the power of the perceptron. In the 1960's the optimism came to a halt after [Marvin Minksy's](https://en.wikipedia.org/wiki/Marvin_Minsky) and [Seymour Papert's](https://en.wikipedia.org/wiki/Seymour_Papert) 1969 book, [Perceptrons](https://www.amazon.com/Perceptrons-Introduction-Computational-Geometry-Expanded/dp/0262631113), was published.  The book showed there're severe limitations to what the perceptron can do and that Frank's claims were exaggerated.  One of the limitations of the perceptron is its inability to solve a simple function called, the [exclusive disjunction (XOR)](https://en.wikipedia.org/wiki/Exclusive_or).  This had a negative effect of the research community and research in connectionism stopped for 10 years.  To learn more about the building blocks the perceptron is built on, read the book, [Neural Networks. A Systematic Introduction](https://www.semanticscholar.org/paper/Neural-Networks-A-Systematic-Introduction-Rojas/0ab5e90d14264b7faf406c15615a4f08cc945f27).\n\n# What is a Neuron?\nA neuron is a cell which is the basic working unit of the brain.  It is a specialized cell designed to transmit information to other nerve, muscle, or gland cells.  It was estimated that a human brain has approximately 100 billion neurons, but no one knew where this number came from.  Brazilian researcher, [Dr. Suzana Herculano-Houzel](https://en.wikipedia.org/wiki/Suzana_Herculano-Houzel), decided to find out where this number originated, but didn't have much luck.  She decided to count them herself and discovered a method to do just that.  She discovered the human brain has approximately 86 billion neurons in total.  This may seem like a small difference from 100 billion, so to provide more context around this number, the following is a list of other animals and the number of neurons they have:\n\n- Fruit fly: 100 thousand neurons\n- Cockroach: One million neurons\n- Mouse: 75 million neurons\n- Cat: One billion neurons\n- Chimpanzee: 7 billion neurons\n- Elephant: 23 billion neurons\n\nCells typcially have a body containing a liquid called cytoplasm, a nucleus containing DNA, and other organelles. Think of a cells organelles like the organs in your body that perform specific tasks to keep the body alive. Most neurons have a cell body, an axon, and dendrites. \n<br>\n<br>\n<figure style=\"text-align:center;\">\n  \n  <figcaption>Graphical Neuron</figcaption>\n</figure> \n<br>\n<br>\nThe axon extends from the cell body and often gives rise to many smaller branches before ending at nerve terminals. Dendrites extend from the neuron cell body and receive messages from other neurons. Synapses are the contact points where one neuron communicates with another. The dendrites are covered with synapses formed by the ends of axons from other neurons.  \n<br>\n<br>\n<figure style=\"text-align:center;\">\n  \n  <figcaption>Biological Neuron (credit: Blake Richards)</figcaption>\n</figure> \n<br>\n<br>\n\n# Perceptron\nA perceptron is inspired by a single biological neuron. There has been a lot of research over the years inventing the building blocks of the perceptron. Read [Threshold Logic](ThresholdLogic.ipynb) to get a perspective on what it took to get here. The perceptron is more formally called a binary classifier, a type of linear classifier. A classifier separates data into categories, and in this case, the perceptron is designed to predict the inputs category.  Our brains do this without much effort, such as classifying mammales and reptiles, fruit and vegtables, and ect.  The perceptron simply takes some inputs and performs a mathematical process and spits out an output/classification/prediction.  In order to look into this mathematical process in more detail, let's look at a more detailed graph.\n\n<figure style=\"text-align:center;\">\n  \n  <figcaption>Formal Perceptron Structure - Details</figcaption>\n</figure> \n\nThe perceptrons' algorithm computes the output in two steps and they're described in the blue circle.  The first step is to compute the weighted sum of the inputs, called $z$.  The second step computes the activation function with the input $z$.  This two step process, is called the Feed Forward process. In the machine learning field, the output of a perceptron is called a prediction.\n\n<ol>\n  <li>Weighted Sum of the Inputs<br>\n      This is the sum of all inputs multiplied by their weighted connections.\n  </li>\n  <li>Activation Function<br>\n      There're many different types of activation functions and they translate the output to be within a desired range. This is an important concept in neural network based machine learning.  \n  </li>\n</ol>\n\nLet's look at a perceptron with 2 inputs.  The inputs and outputs of a perceptron are just numbers. The activation function of a binary classifier takes some inputs and produces a binary output (i.e. {-1, 1}). What mathematical function can turn any number (i.e. weighted sum) into a binary output?  The Sign function is one such function, and it will be used as the activation function in the implementation.  Simply, the Sign function takes any number as an input and then outputs a binary value, i.e {-1, 1}.  The formal Sign function is defined in the equation below.\n\n\\begin{equation}\n  sgn(x)=\\begin{cases}\n    -1, & \\text{if $x<0$},\\\\\n    0, & \\text{if $x=0$},\\\\\n    1, & \\text{if $x>0$}\n  \\end{cases}\n\\end{equation}\n\nI said we need a activation function that outputs a binary value, but the above Sign equation outputs three values {-1, 0, 1}.  We have to simplify it for implementation purposes, and the modified definition is shown below.  Take notice that it now outputs two values {-1, 1}.\n\n\\begin{equation}\n  sgn(x)=\\begin{cases}\n    -1, & \\text{if $x<0$},\\\\\n    1, & \\text{if $x\\geq0$}\n  \\end{cases}\n\\end{equation}\n\nNow that we have an appropriate activation function, the perceptron looks like the following computational graph below.  You can see the two computational steps, weighted sum and activation function, described in the blue circle.  The computation is also written out in mathematical notation.\n\n<figure style=\"text-align:center;\">\n  \n  <figcaption>Formal Perceptron Structure - Details</figcaption>\n</figure> \n<br>\n\n$$prediction = sgn(x_1 \\cdot w_1+x_2 \\cdot w_2)$$  \n<br>\n\nLet's take a minute to look at what we are trying to do again.  We want our perceptron to predict what category our set of inputs, $x_1$ and $x_2$, belong to.  The categories are not known at this point, but we will cover that later.  $x_1$ and $x_2$ are the inputs that will be fed into an equation to compute a prediction, but what are the weights, $w_1$ and $w_2$?  These weights will need to be **learned** using a supervised learning algorithm.  The learning process will find the optimum weights to correctly categorize the inputs.  Before the learning process starts, these weights will be set to random values. Initializing the weights of a perceptron can be more sophisticated than randomly assigning values, but it's not in the scope of this paper.  If you want to read more about it, check out this notebook, [Neural Network Initialization](NeuralNetworkInitialization.ipynb).\n\nA perceptron learns by training it with training data.  Training data is a set of inputs and outputs.  The outputs are typically called labels in a training set.  I know this sounds very vauge, so let's walk-thru an analogy.  Let's imagine a kid is trying to learn the difference between dog and cat pictures.  The kid might have a set of dog and cat pictures with the answers on the back.  The kid would look at each picture, guess whether it's a picture of a dog or cat, and then look at the answers on the back to determine if the guess was correct.  If the kid guessed correctly, he does nothing.  If the kid guessed incorrectly, he'll make the appropriate adjustments in his mind.  For instance, maybe the kid didn't know cats can be bigger than dogs and might classify a large cat as a dog.  The kid will remember that some cats are bigger than dogs so next time he doesn't make the same mistake.  With enough time, the kid will be able to classify all the pictures correctly.  In this analogy, the set of pictures is considered the training data where the pictures would be the inputs and the answers on the back would be the lables/outputs.  Once a perceptron is trained, it should be able to correctly classify dog and cat pictures that it hasn't seen before.\n\nUsing the same analogy, we can imagine that if the kid did classify a picture incorrectly, he'll be able to tell you how much he was off.  For instance, classifying a Pitbull as a cat is much more incorrect than classifying a Chihuahua as a cat.  This is very important for perceptrons because if the error can be computed then the algorithm can be adjusted accordingly.  With a prediction and a label, an error can be computed.  The error is computed by subtracting the prediction from the label.\n\n$$error = label - prediction$$\n\nThe above $error$ function computes the cost for one training example, but we need to compute the cost/error for all training examples.  Before we do this, let's use standard mathematical notation.  For each value $i$ in the training example, we can say that $t^{(i)}$ is the target value for the $i^{th}$ training example and $y^{(i)}$ is the guess produced by the current set of weights in the perceptron.  Let's look at the above $error$ function again using this new notation.\n\n$$E = t^{(i)} - y^{(i)}$$\n\nTherefore, the cumulative error/cost for the training data is defined below.  If you're familiar with statistics, you'll recognize the formula as the [Mean Squared Error (MSE)](https://en.wikipedia.org/wiki/Mean_squared_error).\n\n$$E=\\dfrac{1}{2}\\sum_i(t^{(i)}-y^{(i)})^{2}$$\n\nAll possible error values for a perceptron are  in the table below.\n\n| label | prediction | error |\n| :---: | :---: | :---: |\n| -1 | -1 | 0 |\n| -1 | 1 | -2 |\n| 1 | -1 | 2 |\n|  1 | 1 | 0 |\n\nOnce the error can be computed, then how is the algorithm adjusted so that it learns not to make the same mistake in the future.  As stated above, the weights, $w_1$ and $w_2$, need to be adjusted up or down relative to the magnitude of the error.  The amount $w_1$ and $w_2$ change is defined by the mathemtatical terms $\\Delta w_1$ and $\\Delta w_2$.  These terms can be read as \"the change in $w_1$ and the change in $w_2$\".  For instance, if it's determined that the weights need to be changed by 2, then $w_1$ and $w_2$ will decrease by 2. $\\Delta w_1$ and $\\Delta w_2$ do not have to be the same value, but they can be different.  Below are the equations that represent how to change the weights.\n\n$$w_1 = w_1 - \\Delta w_1$$\n$$w_2 = w_2 - \\Delta w_2$$\n\n$$\\text{Generically, } w_n = w_n - \\Delta w_n$$\n\nNow that we have the equations to adjust the weights, how are the delta's, $\\Delta w_n$, computed? The $\\Delta w_n$ will be computed using a process called gradient descent.  Gradient descent is not in the scope of this article, because there's already so much information on the internet about it, for instance, [Gradient Decent](https://en.wikipedia.org/wiki/Gradient_descent). \n\nDiscuss exactly how and why the equations are the way they are.  Why multiply the error to the input?  What does it mean to multiply an error to an input?\n\nThe learningRate is a configurable parameter to adjust how fast to move down the gradient.  The $\\Delta w_n$ can be computed using gradient descent as follows,\n\n$$\\Delta w_1 = error \\cdot x_1 \\cdot learningRate$$\n$$\\Delta w_2 = error \\cdot x_2 \\cdot learningRate$$\n\n$$\\text{Generically, }\\Delta w_n = error \\cdot x_n \\cdot learningRate$$\n\nNow that the feed forward algorithm and gradient descent can be computed, lets look at the entire supervised learning algorithm and then implement it in code.\n\n1. Initialize a perceptron with random weights\n2. Provide the perceptron with training data and the labels\n3. Ask the perceptron to compute a prediction with a $sgn(x)$ function (a function that return's -1 or 1)\n4. Compute the error (Did the perceptron get the answer right or wrong?)\n5. Adjust weights with respect to the error\n6. Return to step 2 and repeat\n\n<figure>\n  \n</figure> \n\nThere is a problem with the above perceptron.  Imagine if $x_1$ and $x_2$ are both 0, then it wouldn't matter what $w_1$ and $w_2$ are because they would always end up being 0 too.  To fix this problem, another input is added called the bias and the bias is always 1.  The algorithm will work the same, but instead of 2 inputs, it will work with three inputs with bias always being 1.  The bias will ensure that at least one input is not 0.  The figure below illustrates this concept.\n\n<figure>\n  \n</figure> \n\nTherefore, if a perceptron represents a liner line $y=mx+b$, then the line can be described as, ($x_3$ is the bias)\n\n$$w_1 \\cdot x_1 + w_2 \\cdot x_2 + w_3 \\cdot x_3 = 0$$\n$$w_2 \\cdot x_2 = -w_1 \\cdot x_1 - w_3 \\cdot x_3$$\n$$x_2 = \\dfrac{-w_1}{w_2} \\cdot x_1 - \\dfrac{w_3}{w_2} \\cdot x_3$$\n\n\nLet's jump right into the implementation. First let's add some library references that we'll need\n\n\n```python\n%matplotlib inline\nimport plotly.offline as plt\nimport plotly.graph_objs as go\nimport numpy as np\n```\n\nTo start, object-oriented programming will be used for better understanding.  The object that needs to be implemented is Perceptron. The Perceptron class is implemented as follows...\n\n\n```python\n# ---------------------------\n# class: Perceptron\n# This perceptron has three inputs (including bias) and one output\n# ---------------------------\nclass Perceptron:\n    def __init__(self, numberOfFeatures, learningRate, bias, epochs):\n        # create (numberOfFeatures) random weights (float) between -1 and 1\n        # create an additional weight for the bias\n        self.weights = np.random.uniform(-1, 1, numberOfFeatures + 1)\n        self.learningRate = learningRate\n        self.error = []\n        self.bias = bias\n        self.epochs = epochs\n    \n    # ---------------------------\n    # Feed forward algorithm that takes inputs \n    # and produces and outputs \n    # ---------------------------\n    def predict(self, inputs):\n        weightedSum = 0\n        \n        # compute the weighted sum\n        # first handle the bias\n        weightedSum += self.bias * self.weights[0]\n        # second, use dot product to calculated a weighted sum of the inputs and weights\n        weightedSum = np.dot(inputs, self.weights[1:])\n        \n        # pass the weighted sum to the sign function (activation function)\n        output = self.sign(weightedSum)\n        \n        #return output\n        return output\n    \n    # ---------------------------\n    # Activation Function - Basic step function\n    # Return 1 if n is 1 or greater, else -1\n    # ---------------------------\n    def sign(self, n):\n        if n >= 0:\n            return 1\n        else:\n            return -1\n    \n    # ---------------------------\n    # Trains the perceptron by determining the outputs\n    # error and progating it backwards through the perceptron\n    # ---------------------------\n    def train(self, inputs, labels):\n\n        for epoch in range(self.epochs):\n            e = 0\n            for inpt, label in zip(inputs, labels):\n                guess = self.predict(inpt)\n                error = label - guess\n\n                #Adjust all the weights\n                self.weights[0] += self.learningRate * error * self.bias\n                self.weights[1:] += self.learningRate * error * inpt\n\n                e += int((error * self.learningRate) != 0.0)\n               \n            self.error.append(e)\n        \n\n```\n\nBelow is an arbitrary data set plotted on a graph with a line through them.  The goal of this perceptron is to classify what points are below and above a given line.  What it means for a perceptron to learn to classify is that it learns a mathematical function to separate the two groups.  The mathematical function it will learn is represented by the line below.  Therefore, a perceptron or neural network is call a \"Univesral Function Approximater\".  The data points below represent training data for the perceptron.  Once the perceptron is trained it will be able to take in data points not listed in the graph below and predict if the point is below or above the line.  The perceptron that will be implemented will be trained using supervised learning and takes in inputs and outputs a 1 above the line and -1 for below the line.  The supervised learning approach means the training data below will be fed into the perceptron one-by-one and if it predicts the wrong category the perceptron will be penalized by tweaking it's algorithm programmatically.  Tweaking of the algorithm is known as gradient decent.  If the perceptron predicts the correct category, no penalty.  After training, the perceptron should be able to predict the correct category for data points not in the training set.\n\nThe formula for a line is represented like, $y=mx+b$.  The line that our perceptron will try to approximate below is $y=0.5x+20$.  As indicated in the graph below, the line passes through the y-intercept at 20 and has a slope of 0.5.\n\nLet's create some random points\n\n\n```python\n# Set number of points\nnumberOfPoints = 500\n\n# Initialize the points and labels array\npoints = np.zeros(shape=(numberOfPoints, 2))\nlabels = []\n\n# Initialize random points between 1 and 100\nfor i in range(numberOfPoints):\n    x = np.random.randint(-250, 250)\n    y = np.random.randint(-250, 250)\n    label = 1 if (x>y) else -1\n    points[i] = [x,y]\n    labels.append(label)\n```\n\nNow let's plot the random points on a graph\n\n\n```python\n# Create scatter plot points using the random points created above\n# All x-coordinates go into one array and all y-coordinates into another\ngraphPoints = go.Scatter(\n    x = points[:, [0]].flatten(),\n    y = points[:, [1]].flatten(),\n    mode = 'markers',\n    marker = dict(\n        symbol = 'circle'\n    ),\n    name = 'Random Data'\n    \n)\n\nlayout = go.Layout(\n    title='Random Data Points',\n    xaxis=dict(\n        title='$x-axis\\\\text{ }(x_1)$'\n    ),\n    yaxis=dict(\n        title='$y-axis\\\\text{ }(x_2)$'\n    )\n)\n\nfig = go.Figure(data=[graphPoints], layout=layout)\nplt.iplot(fig)\n\n```\n\nLet's graph a line through the points in which we want to perdict\n\n\n```python\n# Plot a line y=mx+b\nx = np.linspace(-250,250,2)\nm = 0.5\nb = 20\ny = m*x+b\n\nline = go.Scatter(\n    x = x,\n    y = y,\n    name = 'Seperate Categories'\n)\n\nlayout.title = 'Line to Seperate Categories'\nfig = go.Figure(data=[graphPoints, line], layout=layout)\nplt.iplot(fig)\n```\n\nNow let's create a Perceptron and use it to guess if the points are above the line or below the line\n\n\n```python\n# \n# 1. Using the untrained perceptron, guess if the data points are above or below the line\n# 2. Train the perceptron\n# 3. Using the trained perceptron, guess if the data points are above or below the line\n#\n# Note: Green points mean a correct prediction and red points mean an incorrect prediction.\n# After the perceptron is trained, all points should be green\n#\n\n# Create a Perceptron\nnumberOfFeatures = 2\nlearningRate = 0.001\nbias = 1\nepochs = 100\nperceptron = Perceptron(numberOfFeatures, learningRate, bias, epochs)\n\n# Display the Perceptrons' predictions\n# The predictions are incorrect because the perceptron hasn't been trained\n# \nc = np.empty(shape=(0, 2))\nw = np.empty(shape=(0, 2))\n\nfor point, label in zip(points, labels):\n    guess = perceptron.predict(point)\n    \n    if guess == label:\n        c = np.append(c, np.array([point]), axis=0)\n    else:\n        w = np.append(w, np.array([point]), axis=0)\n\ncorrect = go.Scatter(\n    x = c[:, [0]].flatten(),\n    y = c[:, [1]].flatten(),\n    mode = 'markers',\n    marker = dict(\n        symbol = 'circle',\n        color = 'rgb(0, 255, 0)'\n    ),\n    name = 'Perceptron Guessed Right'   \n)\n\nwrong = go.Scatter(\n    x = w[:, [0]].flatten(),\n    y = w[:, [1]].flatten(),\n    mode = 'markers',\n    marker = dict(\n        symbol = 'circle',\n        color = 'rgb(255, 0, 0)'\n    ),\n    name = 'Perceptron Guessed Wrong'  \n)\n\nlayout.title = 'Untrained'\nfig = go.Figure(data=[correct, wrong, line], layout=layout)\nplt.iplot(fig)\n```\n\nThe perceptron does poorly at guessing which points are above and below the line.  The green points indicate a correct guess by the perceptron and red otherwise.\n\nNext, let's train the perceptron.\n\n\n```python\n# Train the Perceptron\nperceptron.train(points, labels)\n```\n\nNow let's see how the perceptron performs now\n\n\n```python\nc = np.empty(shape=(0, 2))\nw = np.empty(shape=(0, 2))\n\n# Display the Perceptrons' predictions\n# The predictions are correct because the perceptrons has been trained\nfor point, label in zip(points, labels):\n    guess = perceptron.predict(point)\n    \n    if guess == label:\n        c = np.append(c, np.array([point]), axis=0)\n    else:\n        w = np.append(w, np.array([point]), axis=0)\n\ncorrect = go.Scatter(\n    x = c[:, [0]].flatten(),\n    y = c[:, [1]].flatten(),\n    mode = 'markers',\n    marker = dict(\n        symbol = 'circle',\n        color = 'rgb(0, 255, 0)'\n    ),\n    name = 'Perceptron Guessed Right'   \n)\n\nwrong = go.Scatter(\n    x = w[:, [0]].flatten(),\n    y = w[:, [1]].flatten(),\n    mode = 'markers',\n    marker = dict(\n        symbol = 'circle',\n        color = 'rgb(255, 0, 0)'\n    ),\n    name = 'Perceptron Guessed Wrong'  \n)\n\nlayout.title = 'Trained'\nfig = go.Figure(data=[correct, wrong, line], layout=layout)\nplt.iplot(fig)   \n```\n\nIt's good to always view how well your algorithm does over time.  Looking at the loss/error can give us a good indication that the algorithm is working and getting better with each iteration.  This will be very important when implementing multi-layer neural networks. The error should be minimized to zero for perfect solution.  These parameters\n\n    numberOfFeatures = 2\n    learningRate = 0.001\n    bias = 1\n    epochs = 100\n\ncan be experimented with to see how it affects the algorithms performance.  For instance, with a small learning rate and a large feature set, the algorithm error function should converge to zero relatively slowly.\n\n\n```python\nprint(perceptron.error)\n```\n\n    [21, 16, 10, 11, 10, 8, 8, 14, 11, 14, 11, 14, 7, 11, 9, 7, 6, 11, 8, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n\n\n\n```python\nerrorGraphPoints = go.Scatter(\n    x = np.linspace(0, len(perceptron.error), len(perceptron.error)),\n    y = perceptron.error,\n    mode = 'lines',\n    marker = dict(\n        symbol = 'circle',\n        color = 'rgb(0, 255, 0)'\n    ),\n    name = 'Loss'   \n)\n\nlayout = go.Layout(\n    title='Loss',\n    xaxis=dict(\n        title='Epochs'\n    ),\n    yaxis=dict(\n        title='Error'\n    )\n)\n\nfig = go.Figure(data=[errorGraphPoints], layout=layout)\nplt.iplot(fig)   \n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "40b06ee50acd62d23e8672a8979196267f5f2edb", "size": 625622, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Perceptron.ipynb", "max_stars_repo_name": "deflagg/ArtificialNeuralNetworkStudy", "max_stars_repo_head_hexsha": "d52360b47e2ee18214ec254cd3fb37cc001cbea5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-12-22T17:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-15T10:29:19.000Z", "max_issues_repo_path": "Perceptron.ipynb", "max_issues_repo_name": "deflagg/ArtificialNeuralNetworkStudy", "max_issues_repo_head_hexsha": "d52360b47e2ee18214ec254cd3fb37cc001cbea5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Perceptron.ipynb", "max_forks_repo_name": "deflagg/ArtificialNeuralNetworkStudy", "max_forks_repo_head_hexsha": "d52360b47e2ee18214ec254cd3fb37cc001cbea5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 120.8230977211, "max_line_length": 128609, "alphanum_fraction": 0.862199539, "converted": true, "num_tokens": 6449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647596, "lm_q2_score": 0.07696083940093962, "lm_q1q2_score": 0.03458563436900752}}
{"text": "```python\nfrom IPython.core.display import HTML\nfrom IPython.display import Image\nHTML(\"\"\"\n<style>\n.output_png {\n    display: table-cell;\n    text-align: center;\n    vertical-align: middle;\n}\n</style>\n\"\"\")\n```\n\n\n\n\n\n<style>\n.output_png {\n    display: table-cell;\n    text-align: center;\n    vertical-align: middle;\n}\n</style>\n\n\n\n\n# *Circuitos El\u00e9tricos I - Semana 8*\n\n# Circuitos de segunda ordem\n\n## Circuito RLC em paralelo\n\n\n\nSimula\u00e7\u00e3o: https://tinyurl.com/ycnkjnot\n\n### Aplica\u00e7\u00e3o das Leis de Kirchhoff \n\n$$\\begin{align}\n   i_R + i_L + i_C &= i_s\\\\\n   \\frac{v}{R} + i_L + C\\frac{d v}{d t} &= i_s\\nonumber\\\\\n    \\frac{1}{R}\\left[L\\frac{d i_L}{d t}\\right] + i_L + C \\frac{d}{d t}\\left[L\\frac{d i_L}{d t}\\right]  &= i_s\\nonumber\\\\\n    \\frac{d^{2} i_L}{d t^{2}}+\\frac{1}{RC} \\frac{d i_L}{d t}+\\frac{1}{L C} i_L &=\\frac{i_s}{LC}\n   \\end{align}\n$$\n\ncom $\\alpha = \\frac{1}{2RC}$ e $\\omega_0 = \\frac{1}{\\sqrt{LC}}$, temos\n\n$$ \n\\begin{equation}\\label{EDO1} \n\\frac{d^{2} i_L}{d t^{2}}+2\\alpha \\frac{d i_L}{d t}+\\omega_0^2 i_L=i_{\\mathrm{s}}\\omega_0^2 \n\\end{equation} \n$$\n\nA equa\u00e7\u00e3o \\ref{EDO1} \u00e9 uma EDO de segunda ordem, linear e de coeficientes constantes.\n\nEqua\u00e7\u00e3o caracter\u00edstica:\n\n$$\\begin{equation} s^2+2\\alpha s + \\omega_0^2=0 \\end{equation} $$\n\nRa\u00edzes da equa\u00e7\u00e3o caracter\u00edstica:\n\n$$\n\\begin{align}\ns_1 &=-\\alpha +\\sqrt{\\alpha^2-\\omega_0^2}\\\\\ns_2 &=-\\alpha -\\sqrt{\\alpha^2-\\omega_0^2}\n\\end{align}\n$$\n\n### Resposta total \n\nA resposta transiente de circuitos RLC em paralelo, seja ela natural ($i_L(\\infty)=0$) ou ao degrau ($i_L(\\infty)=i_s$), pode ser classificada nas tr\u00eas casos seguintes. Em todos os casos, assume-se que o transiente teve in\u00edcio no instante $t_0$ (instante do chaveamento).\n\n#### Caso superamortecido ($\\alpha>\\omega_0\\Rightarrow \\text{ra\u00edzes reais e distintas}$):\n\nSolu\u00e7\u00e3o geral da EDO:\n\n$$ \\begin{equation} i_L(t) =A_{1} e^{s_{1} (t-t_0)}+A_{2} e^{s_{2} (t-t_0)}+i_L(\\infty) \\end{equation}$$\n\nCondi\u00e7\u00f5es iniciais para $i_L(t)$:\n\n$$\n\\begin{align}\ni_L(t_0^+) &=A_1 + A_2 + i_L(\\infty)\\\\\n\\frac{di_L(t_0^+)}{dt} &=s_1A_1 + s_2A_2 = \\frac{1}{L} v_C(t_0^+)\n\\end{align}\n$$\n\nSolu\u00e7\u00e3o do sistema em $A_1$ e $A_2$:\n\n$$\n\\begin{align}\nA_{1} &=\\frac{\\frac{1}{L} v_C(t_0^+)-s_{2}\\left[i_L(t_0^+)-i_L(\\infty)\\right]}{s_{1}-s_{2}} \\\\\nA_{2} &=\\frac{-\\frac{1}{L} v_C(t_0^+)+s_{1}\\left[i_L(t_0^+)-i_L(\\infty)\\right]}{s_{1}-s_{2}}\n\\end{align}\n$$\n\n#### Caso subamortecido ($ \\alpha<\\omega_0\\Rightarrow\\text{ra\u00edzes complexas e conjugadas} $):\n\nFazendo $\\omega_d = \\sqrt{\\omega_0^2-\\alpha^2}$ temos $s_1 = -\\alpha +j\\omega_d$ e $s_2 = -\\alpha -j\\omega_d$.\n\nSolu\u00e7\u00e3o geral da EDO:\n\n$$\\begin{equation} i_L(t) = e^{-\\alpha(t-t_0)}\\left\\lbrace B_{1}\\cos[\\omega_d (t-t_0)] + B_{2}\\sin[\\omega_d (t-t_0)]  \\right\\rbrace + i_L(\\infty) \\end{equation}$$\n\nCondi\u00e7\u00f5es iniciais para $i_L(t)$:\n\n$$\n\\begin{align}\ni_L(t_0^+) &=B_1 + i_L(\\infty)\\\\\n\\frac{di_L(t_0^+)}{dt} &= -\\alpha B_1 +\\omega_d B_2 = \\frac{1}{L} v_C(t_0^+)\n\\end{align}\n$$\n\nSolu\u00e7\u00e3o do sistema em $B_1$ e $B_2$:\n\n$$\n\\begin{align}\nB_{1} &=i_L(t_0^+)-i_L(\\infty) \\\\\nB_{2} &=\\frac{\\frac{1}{L} v_C(t_0^+)+\\alpha\\left[i_L(t_0^+)-i_L(\\infty)\\right]}{\\omega_d}\n\\end{align}\n$$\n\n#### Caso criticamente amortecido ($\\alpha=\\omega_0\\Rightarrow \\text{ra\u00edzes reais e id\u00eanticas } s_1=s_2=-\\alpha$):\n\nSolu\u00e7\u00e3o geral da EDO:\n\n$$ \\begin{equation} i_L(t) =D_{1} e^{-\\alpha(t-t_0)}+D_{2}(t-t_0) e^{-\\alpha(t-t_0)}+i_L(\\infty) \\end{equation}$$\n\nCondi\u00e7\u00f5es iniciais para $i_L(t)$:\n\n$$\n\\begin{align}\ni_L(t_0^+) &=D_1 + i_L(\\infty)\\\\\n\\frac{di_L(t_0^+)}{dt} &=-\\alpha D_1 + D_2 = \\frac{1}{L} v_C(t_0^+)\n\\end{align}\n$$\n\nSolu\u00e7\u00e3o do sistema em $D_1$ e $D_2$:\n\n$$\n\\begin{align}\nD_{1} &=i_L(t_0^+)-i_L(\\infty) \\\\\nD_{2} &= \\frac{1}{L} v_C(t_0^+)+\\alpha\\left[i_L(t_0^+)-i_L(\\infty)\\right]\n\\end{align}\n$$\n\n### Problema 1\n\nPara o circuito a seguir, as chaves $ch1$ e $ch2$ estiveram abertas por um longo intervalo de tempo. \n\n\n\n\na. Considerando que apenas $ch1$ fecha em $t_0=0$s, determine a tens\u00e3o sobre o capacitor $v_C(t)$ para $t\\geq 0^+$.\\\nb. Qual o m\u00e1ximo valor (absoluto) atingido pela tens\u00e3o aplicada aos terminais do capacitor para $t\\geq 0^+$? Em que instante ele ocorre?\\\nc. Considerando que apenas $ch2$ fecha em $t_0=0$s, determine a tens\u00e3o sobre o capacitor $v_C(t)$ para $t\\geq 0^+$.\n\nLink para a simula\u00e7\u00e3o do circuito: https://tinyurl.com/yf8pj57t\n\n\n```python\nimport numpy as np\nimport sympy as sp\nfrom utils import round_expr, symdisp, symplot\n```\n\n### Resolvendo o problema com o Python\n\n**Resolu\u00e7\u00e3o item (a):**\n\n**Calcula $\\alpha$ e $\\omega_0$**\n\n\n```python\n# Par\u00e2metros do circuito:\nR = 1.64\nL = 6e-3\nC = 0.5e-3\n\n# calculando \u03b1 e \u03c90\n\u03b1  = 1/(2*R*C)       # Frequ\u00eancia de Neper do circuito RLC em paralelo\n\u03c90 = 1/np.sqrt(L*C)  # Frequ\u00eancia de resson\u00e2ncia do circuito RLC\n\nsymdisp('\u03b1 =', round(\u03b1, 2), ' rad/s')\nsymdisp('\u03c9_0 =', round(\u03c90, 2), ' rad/s')\n```\n\n\n$\\displaystyle \u03b1 =609.76\\; rad/s$\n\n\n\n$\\displaystyle \u03c9_0 =577.35\\; rad/s$\n\n\n**Define os valores iniciais $v_c(t_0^+)$ e $i_L(t_0^+)$ e o valor final $i_L(\\infty)$ (obtidos da an\u00e1lise do circuito)**\n\n\n```python\n# informa\u00e7\u00f5es obtidas pela an\u00e1lise do circuito\n\nt0 = 0 # instante do chaveamento\n\niL_inf = -4 # valor final da corrente no indutor\niL_t0 = 2   # valor inicial da corrente no indutor\nvc_t0 = 0   # valor inicial da tens\u00e3o no capcitor\n```\n\n**Calcula as ra\u00edzes da equa\u00e7\u00e3o caracter\u00edstica $s_1$ e $s_2$**\n\n\n```python\n# ra\u00edzes da equa\u00e7\u00e3o caracter\u00edstica\ns1 = -\u03b1 + np.sqrt(\u03b1**2-\u03c90**2)\ns2 = -\u03b1 - np.sqrt(\u03b1**2-\u03c90**2)\n\nprint('Ra\u00edzes da equa\u00e7\u00e3o caracter\u00edstica:')\nsymdisp('s_1 =', round(s1, 2), ' rad/s')\nsymdisp('s_2 =', round(s2, 2), ' rad/s')\n\n# define vari\u00e1veis da solu\u00e7\u00e3o geral\nt, A1, A2 = sp.symbols('t, A1, A2')\n\n# express\u00e3o geral da resposta superamortecida\niL = A1*sp.exp(s1*(t-t0)) + A2*sp.exp(s2*(t-t0)) + iL_inf\n\nprint('Forma geral da solu\u00e7\u00e3o:')\nsymdisp('i_L(t) = ', round_expr(iL,2), 'A')\n```\n\n    Ra\u00edzes da equa\u00e7\u00e3o caracter\u00edstica:\n\n\n\n$\\displaystyle s_1 =-413.62\\; rad/s$\n\n\n\n$\\displaystyle s_2 =-805.89\\; rad/s$\n\n\n    Forma geral da solu\u00e7\u00e3o:\n\n\n\n$\\displaystyle i_L(t) = A_{1} e^{- 413.62 t} + A_{2} e^{- 805.89 t} - 4\\;A$\n\n\n**Resolve o sistema de equa\u00e7\u00f5es para determina\u00e7\u00e3o das constantes $A_1$ e $A_2$**\n\n\n```python\n# define os sistema de equa\u00e7\u00f5es com as condi\u00e7\u00f5es iniciais\neq1 = sp.Eq(   A1 +    A2 + iL_inf, iL_t0)             \neq2 = sp.Eq(s1*A1 + s2*A2,        vc_t0/L)  \n\nprint('Sistema de equa\u00e7\u00f5es:')\nsymdisp('(I): ', round_expr(eq1, 2),' ')\nsymdisp('(II): ', round_expr(eq2, 2),' ')\n```\n\n    Sistema de equa\u00e7\u00f5es:\n\n\n\n$\\displaystyle (I): A_{1} + A_{2} - 4 = 2\\; $\n\n\n\n$\\displaystyle (II): - 413.62 A_{1} - 805.89 A_{2} = 0.0\\; $\n\n\n\n```python\n# resolve o sistema\nsoluc = sp.solve((eq1, eq2), dict=True)\nA1 = np.array([sol[A1] for sol in soluc])\nA2 = np.array([sol[A2] for sol in soluc])\n\nA1 = A1[0]\nA2 = A2[0]\n\nprint('Solu\u00e7\u00e3o do sistema:')\nsymdisp('A_1 =', round(A1, 2), ' A')\nsymdisp('A_2 =', round(A2, 2), ' A')\n```\n\n    Solu\u00e7\u00e3o do sistema:\n\n\n\n$\\displaystyle A_1 =12.33\\; A$\n\n\n\n$\\displaystyle A_2 =-6.33\\; A$\n\n\n**Determina a express\u00e3o final para $i_L(t)$**\n\n\n```python\n# express\u00e3o geral da resposta subamortecida\niL = A1*sp.exp(s1*(t-t0)) + A2*sp.exp(s2*(t-t0)) + iL_inf\n\nsymdisp('i_L(t) = ', round_expr(iL,2), 'A')\n```\n\n\n$\\displaystyle i_L(t) = -4 - 6.33 e^{- 805.89 t} + 12.33 e^{- 413.62 t}\\;A$\n\n\n**Plota gr\u00e1fico de $i_L(t)$**\n\n\n```python\n# plota gr\u00e1fico da fun\u00e7\u00e3o\nintervalo = np.linspace(t0,t0+0.02,100)\nsymplot(t,iL, intervalo, 'iL(t)')\n```\n\n**Determina $v_C(t)$ a partir de $i_L(t)$**\n\n\n```python\n# tens\u00e3o aplicada sobre o capacitor (= tens\u00e3o sobre o indutor)\nvC = L*sp.diff(iL, t)\n\nsymdisp('v_C(t) = ', round_expr(vC, 2), ' V')\n```\n\n\n$\\displaystyle v_C(t) = 30.59 e^{- 805.89 t} - 30.59 e^{- 413.62 t}\\; V$\n\n\n**Plota gr\u00e1fico de $v_C(t)$**\n\n\n```python\n# plota gr\u00e1fico da fun\u00e7\u00e3o\nintervalo = np.linspace(t0,t0+0.02,100)\nsymplot(t, vC, intervalo, 'vC(t)')\n```\n\n**Resolu\u00e7\u00e3o item (b):**\n\n$$\\frac{dv_C}{dt} = 0$$\n\n\n```python\n# define a equa\u00e7\u00e3o dvC/dt = 0\neq1 = sp.Eq(sp.diff(vC, t),0)  \n\nround_expr(eq1, 2)\n```\n\n\n\n\n$\\displaystyle - 24653.1 e^{- 805.89 t} + 12653.1 e^{- 413.62 t} = 0$\n\n\n\n\n```python\n# resolve a equa\u00e7\u00e3o em t\nts = sp.solveset(eq1, t).args[0]\n\n# calcula o valor de vC(t) para t = ts\nvC_ts = vC.evalf(subs={t:ts})\n\nsymdisp('t_s = ', round(ts*1000,2), 'ms')\nsymdisp('v_C(t_s) = ', round(vC_ts,2), 'V')\n```\n\n\n$\\displaystyle t_s = 1.7\\;ms$\n\n\n\n$\\displaystyle v_C(t_s) = -7.37\\;V$\n\n\n**Resolu\u00e7\u00e3o item (c):**\n\n\n```python\n# Par\u00e2metros do circuito:\nR = 6\nL = 6e-3\nC = 0.5e-3\n\n# calculando \u03b1 e \u03c90\n\u03b1  = 1/(2*R*C)       # Frequ\u00eancia de Neper do circuito RLC em paralelo\n\u03c90 = 1/np.sqrt(L*C)  # Frequ\u00eancia de resson\u00e2ncia do circuito RLC\n\nsymdisp('\u03b1 =', round(\u03b1, 2), ' rad/s')\nsymdisp('\u03c9_0 =', round(\u03c90, 2), ' rad/s')\n```\n\n\n$\\displaystyle \u03b1 =166.67\\; rad/s$\n\n\n\n$\\displaystyle \u03c9_0 =577.35\\; rad/s$\n\n\n\n```python\n# informa\u00e7\u00f5es obtidas pela an\u00e1lise do circuito\niL_inf = 0  # valor final da corrente no indutor\niL_t0 = 2   # valor inicial da corrente no indutor\nvc_t0 = 0   # valor inicial da tens\u00e3o no capcitor\n\nt0 = 0 # instante do chaveamento\n```\n\n\n```python\n# define a frequ\u00eancia de oscila\u00e7\u00e3o amortecida\n\u03c9d = np.sqrt(\u03c90**2 - \u03b1**2)\n\nprint('Frequ\u00eancia de oscila\u00e7\u00e3o amortercida:')\nsymdisp('\u03c9_d =', round(\u03c9d, 2), ' rad/s')\n\n# define vari\u00e1veis da solu\u00e7\u00e3o geral\nt, B1, B2 = sp.symbols('t, B1, B2')\n\n# express\u00e3o geral da resposta subamortecida\niL = sp.exp(-\u03b1*(t-t0))*(B1*sp.cos(\u03c9d*(t-t0)) + B2*sp.sin(\u03c9d*(t-t0))) + iL_inf\n\nprint('Forma geral da solu\u00e7\u00e3o:')\nsymdisp('i_L(t) = ', round_expr(iL,2), ' A')\n```\n\n    Frequ\u00eancia de oscila\u00e7\u00e3o amortercida:\n\n\n\n$\\displaystyle \u03c9_d =552.77\\; rad/s$\n\n\n    Forma geral da solu\u00e7\u00e3o:\n\n\n\n$\\displaystyle i_L(t) = \\left(B_{1} \\cos{\\left(552.77 t \\right)} + B_{2} \\sin{\\left(552.77 t \\right)}\\right) e^{- 166.67 t}\\; A$\n\n\n\n```python\n# define os sistema de equa\u00e7\u00f5es com as condi\u00e7\u00f5es iniciais\neq1 = sp.Eq(   B1 + iL_inf, iL_t0)             \neq2 = sp.Eq(-\u03b1*B1 + \u03c9d*B2,  vc_t0/L)  \n\nprint('Sistema de equa\u00e7\u00f5es:')\nsymdisp('(I): ', round_expr(eq1, 2),' ')\nsymdisp('(II): ', round_expr(eq2, 2),' ')\n```\n\n    Sistema de equa\u00e7\u00f5es:\n\n\n\n$\\displaystyle (I): B_{1} = 2\\; $\n\n\n\n$\\displaystyle (II): - 166.67 B_{1} + 552.77 B_{2} = 0.0\\; $\n\n\n\n```python\n# resolve o sistema\nsoluc = sp.solve((eq1, eq2), dict=True)\nB1 = np.array([sol[B1] for sol in soluc])\nB2 = np.array([sol[B2] for sol in soluc])\n\nB1 = B1[0]\nB2 = B2[0]\n\nprint('Solu\u00e7\u00e3o do sistema:')\nsymdisp('B_1 =', round(B1, 2), ' A')\nsymdisp('B_2 =', round(B2, 2), ' A')\n```\n\n    Solu\u00e7\u00e3o do sistema:\n\n\n\n$\\displaystyle B_1 =2.0\\; A$\n\n\n\n$\\displaystyle B_2 =0.6\\; A$\n\n\n\n```python\n# express\u00e3o geral da resposta subamortecida\niL = sp.exp(-\u03b1*(t-t0))*(B1*sp.cos(\u03c9d*(t-t0))+B2*sp.sin(\u03c9d*(t-t0))) + iL_inf\n\nsymdisp('i_L(t) = ', round_expr(iL,2), 'A')\n```\n\n\n$\\displaystyle i_L(t) = \\left(0.6 \\sin{\\left(552.77 t \\right)} + 2.0 \\cos{\\left(552.77 t \\right)}\\right) e^{- 166.67 t}\\;A$\n\n\n\n```python\n# plota gr\u00e1fico da fun\u00e7\u00e3o\nintervalo = np.linspace(t0,t0+0.05,100)\nsymplot(t, iL, intervalo, 'iL(t)')\n```\n\n\n```python\n# tens\u00e3o aplicada sobre o capacitor (= tens\u00e3o sobre o indutor)\nvC = L*sp.diff(iL, t)\nvC = sp.simplify(vC)\n\nsymdisp('v_C(t) = ', round_expr(vC, 2), ' V')\n```\n\n\n$\\displaystyle v_C(t) = - 7.24 e^{- 166.67 t} \\sin{\\left(552.77 t \\right)}\\; V$\n\n\n\n```python\n# plota gr\u00e1fico da fun\u00e7\u00e3o\nintervalo = np.linspace(t0,t0+0.05,100)\nsymplot(t, vC, intervalo, 'vC(t)')\nsymplot(t, [iL, vC], intervalo, ['iL(t)', 'vC(t)'])\n```\n\n## Circuito RLC em s\u00e9rie\n\n\n\n### Aplica\u00e7\u00e3o das Leis de Kirchhoff \n\n$$\\begin{align}\n   v_R + v_L + v_C &= v_s\\\\\n   R i + L\\frac{d i}{dt}+v_C &= v_s\\nonumber\\\\\n   R\\left[C\\frac{dv_C}{dt}\\right] + L\\frac{d}{dt}\\left[C\\frac{dv_C}{dt} \\right] + v_C &= v_s\\nonumber\\\\\n    \\frac{d^{2} v_{\\mathrm{C}}}{d t^{2}}+\\frac{R}{L} \\frac{d v_{\\mathrm{C}}}{d t}+\\frac{1}{L C}   v_{\\mathrm{C}} &=\\frac{v_{\\mathrm{s}}}{LC}\n   \\end{align} \n$$\n\ncom $ \\alpha = \\frac{R}{2L}$ e $\\omega_0 = \\frac{1}{\\sqrt{LC}}$, temos\n\n$$ \\begin{equation}\\label{EDO2} \\frac{d^{2} v_{\\mathrm{C}}}{d t^{2}}+2\\alpha \\frac{d v_{\\mathrm{C}}}{d t}+\\omega_0^2 v_{\\mathrm{C}}=v_{\\mathrm{s}}\\omega_0^2 \\end{equation} $$\n\nA equa\u00e7\u00e3o \\ref{EDO2} \u00e9 uma EDO de segunda ordem, linear e de coeficientes constantes.\n\nEqua\u00e7\u00e3o caracter\u00edstica:\n\n$$\\begin{equation} s^2+2\\alpha s + \\omega_0^2=0 \\end{equation}$$\n\nRa\u00edzes da equa\u00e7\u00e3o caracter\u00edstica:\n\n$$\n\\begin{align}\ns_1 &=-\\alpha +\\sqrt{\\alpha^2-\\omega_0^2}\\\\\ns_2 &=-\\alpha -\\sqrt{\\alpha^2-\\omega_0^2}\n\\end{align}\n$$\n\n### Resposta total \n\nA resposta transiente de circuitos RLC em s\u00e9rie, seja ela natural ($v_C(\\infty)=0$) ou ao degrau ($v_C(\\infty)=v_s$), pode ser classificada nas tr\u00eas casos seguintes. Em todos os casos, assume-se que o transiente teve in\u00edcio no instante $t_0$ (instante do chaveamento).\n\n#### Caso superamortecido ($\\alpha>\\omega_0\\Rightarrow \\text{ra\u00edzes reais e distintas}$):\n\nSolu\u00e7\u00e3o geral da EDO:\n\n$$\\begin{equation} v_{\\mathrm{C}}(t) =A_{1} e^{s_{1} (t-t_0)}+A_{2} e^{s_{2} (t-t_0)}+v_{\\mathrm{C}}(\\infty) \\end{equation}$$\n\nCondi\u00e7\u00f5es iniciais para $v_{\\mathrm{C}}(t)$:\n\n$$\n\\begin{align}\nv_{\\mathrm{C}}(t_0^+) &=A_1 + A_2 + v_{\\mathrm{C}}(\\infty)\\\\\n\\frac{dv_{\\mathrm{C}}(t_0^+)}{dt} &=s_1A_1 + s_2A_2 = \\frac{1}{C} i_{\\mathrm{L}}(t_0^+)\n\\end{align}\n$$\n\nSolu\u00e7\u00e3o do sistema em $A_1$ e $A_2$:\n\n$$\n\\begin{align}\nA_{1} &=\\frac{\\frac{1}{C} i_{\\mathrm{L}}(t_0^+)-s_{2}\\left[v_{\\mathrm{C}}(t_0^+)-v_{\\mathrm{C}}(\\infty)\\right]}{s_{1}-s_{2}} \\\\\nA_{2} &=\\frac{-\\frac{1}{C} i_{\\mathrm{L}}(t_0^+)+s_{1}\\left[v_{\\mathrm{C}}(t_0^+)-v_{\\mathrm{C}}(\\infty)\\right]}{s_{1}-s_{2}}\n\\end{align}\n$$\n\n#### Caso subamortecido ($\\alpha<\\omega_0\\Rightarrow \\text{ra\u00edzes complexas e conjugadas}$):\n\nFazendo $\\omega_d = \\sqrt{\\omega_0^2-\\alpha^2}$ temos $s_1 = -\\alpha +j\\omega_d$ e $s_2 = -\\alpha -j\\omega_d$.\n\nSolu\u00e7\u00e3o geral da EDO:\n\n$$\\begin{equation} v_{\\mathrm{C}}(t) = e^{-\\alpha(t-t_0)}\\left\\lbrace B_{1}\\cos[\\omega_d (t-t_0)] + B_{2}\\sin[\\omega_d (t-t_0)]  \\right\\rbrace + v_{\\mathrm{C}}(\\infty) \\end{equation}$$\n\nCondi\u00e7\u00f5es iniciais para $v_{\\mathrm{C}}(t)$:\n\n$$\n\\begin{align}\nv_{\\mathrm{C}}(t_0^+) &=B_1 + v_{\\mathrm{C}}(\\infty)\\\\\n\\frac{dv_{\\mathrm{C}}(t_0^+)}{dt} &= -\\alpha B_1 +\\omega_d B_2 = \\frac{1}{C} i_{\\mathrm{L}}(t_0^+)\n\\end{align}\n$$\n\nSolu\u00e7\u00e3o do sistema em $B_1$ e $B_2$:\n\n$$\n\\begin{align}\nB_{1} &=v_{\\mathrm{C}}(t_0^+)-v_{\\mathrm{C}}(\\infty) \\\\\nB_{2} &=\\frac{\\frac{1}{C} i_{\\mathrm{L}}(t_0^+)+\\alpha\\left[v_{\\mathrm{C}}(t_0^+)-v_{\\mathrm{C}}(\\infty)\\right]}{\\omega_d}\n\\end{align}\n$$\n\n#### Caso criticamente amortecido ($\\alpha=\\omega_0\\Rightarrow \\text{ra\u00edzes reais e id\u00eanticas } s_1=s_2=-\\alpha$):\n\nSolu\u00e7\u00e3o geral da EDO:\n\n$$ \\begin{equation} v_{\\mathrm{C}}(t) =D_{1} e^{-\\alpha(t-t_0)}+D_{2}(t-t_0) e^{-\\alpha(t-t_0)}+v_{\\mathrm{C}}(\\infty) \\end{equation}$$\n\nCondi\u00e7\u00f5es iniciais para $v_{\\mathrm{C}}(t)$:\n\n$$\n\\begin{align}\nv_{\\mathrm{C}}(t_0^+) &=D_1 + v_{\\mathrm{C}}(\\infty)\\\\\n\\frac{dv_{\\mathrm{C}}(t_0^+)}{dt} &=-\\alpha D_1 + D_2 = \\frac{1}{C} i_{\\mathrm{L}}(t_0^+)\n\\end{align}\n$$\n\nSolu\u00e7\u00e3o do sistema em $D_1$ e $D_2$:\n\n$$\n\\begin{align}\nD_{1} &=v_{\\mathrm{C}}(t_0^+)-v_{\\mathrm{C}}(\\infty) \\\\\nD_{2} &= \\frac{1}{C} i_{\\mathrm{L}}(t_0^+)+\\alpha\\left[v_{\\mathrm{C}}(t_0^+)-v_{\\mathrm{C}}(\\infty)\\right]\n\\end{align}\n$$\n\n### Problema 2\n\nNo circuito da figura a seguir, a chave $ch1$ estive aberta por um longo intervalo de tempo antes de fechar, no instante $t_0=0$s.\n\n\n\na. Para qual valor de $R_x$ o circuito exibe uma resposta criticamente amortecida para $t\\geq 0^+$?\\\nb. Considerando que $R_x$ vale exatamente o valor calculado em (a), determine a tens\u00e3o sobre o capacitor $v_C(t)$ para $t\\geq 0^+$.\\\nc. Considerando que $R_x$ vale um d\u00e9cimo do valor calculado em (a), determine a tens\u00e3o sobre o capacitor $v_C(t)$ para $t\\geq 0^+$.\n\nLink para a simula\u00e7\u00e3o deste circuito: https://tinyurl.com/yjgkkzhu\n\nResolu\u00e7\u00e3o item (b):\n\n\n```python\n# Par\u00e2metros do circuito:\nR = \nL = \nC = \n\n# calculando \u03b1 e \u03c90\n\u03b1  = R/(2*L)\n\u03c90 = 1/np.sqrt(L*C)\n\nsymdisp('\u03b1 =', round(\u03b1, 2), ' rad/s')\nsymdisp('\u03c9_0 =', round(\u03c90, 2), ' rad/s')\n```\n\n\n```python\n# informa\u00e7\u00f5es obtidas pela an\u00e1lise do circuito\nvC_inf =    # valor final da tens\u00e3o sobre o capacitor\niL_t0 =   # valor inicial da corrente no indutor\nvC_t0 =     # valor inicial da tens\u00e3o sobre o capacitor\n\nt0 = 0 # instante do chaveamento\n```\n\n\n```python\n# ra\u00edzes da equa\u00e7\u00e3o caracter\u00edstica\ns1 = -\u03b1\ns2 = -\u03b1\n\n# define vari\u00e1veis da solu\u00e7\u00e3o geral\nt, D1, D2 = sp.symbols('t, D1, D2')\n\n# express\u00e3o geral da resposta \nvC = D1*sp.exp(s1*(t-t0)) + D2*(t-t0)*sp.exp(s2*(t-t0)) + vC_inf\n\nsymdisp('v_C(t) = ', round_expr(vC, 2), ' V')\n```\n\n\n```python\n# define os sistema de equa\u00e7\u00f5es com as condi\u00e7\u00f5es iniciais\neq1 = sp.Eq()             \neq2 = sp.Eq()  \n\nprint('Sistema de equa\u00e7\u00f5es:')\nsymdisp('(I): ', round_expr(eq1, 2),' ')\nsymdisp('(II): ', round_expr(eq2, 2),' ')\n```\n\n\n```python\n# resolve o sistema\nsoluc = sp.solve((eq1, eq2), dict=True)\nD1 = np.array([sol[D1] for sol in soluc])\nD2 = np.array([sol[D2] for sol in soluc])\n\nD1 = D1[0]\nD2 = D2[0]\n\nprint('Solu\u00e7\u00e3o do sistema:')\nsymdisp('D_1 =', round(D1, 2), ' V')\nsymdisp('D_2 =', round(D2, 2), ' V')\n```\n\n\n```python\n# express\u00e3o geral da resposta \nvC = D1*sp.exp(s1*(t-t0)) + D2*(t-t0)*sp.exp(s2*(t-t0)) + vC_inf\n\nsymdisp('v_C(t) = ', round_expr(vC, 2), ' V')\n```\n\n\n```python\n# corrente passando pelo indutor\niL = C*sp.diff(vC, t)\n\nsymdisp('i_L(t) = ', round_expr(iL,2), 'A')\n```\n\n\n```python\n# plota gr\u00e1fico da fun\u00e7\u00e3o\nintervalo = np.linspace(t0,t0+0.05,100)\nsymplot(t, vC, intervalo, 'vC(t)')\n```\n\n\n```python\n# plota gr\u00e1fico da fun\u00e7\u00e3o\nintervalo = np.linspace(t0,t0+0.05,100)\nsymplot(t, iL, intervalo, 'iL(t)')\n```\n\nResolu\u00e7\u00e3o item (c):\n\n\n```python\n# Par\u00e2metros do circuito:\nR = 65.02\nL = 1\nC = 100e-6\n\n# calculando \u03b1 e \u03c90\n\u03b1  = R/(2*L)\n\u03c90 = 1/np.sqrt(L*C)\n\nsymdisp('\u03b1 =', round(\u03b1, 2), ' rad/s')\nsymdisp('\u03c9_0 =', round(\u03c90, 2), ' rad/s')\n```\n\n\n```python\n# informa\u00e7\u00f5es obtidas pela an\u00e1lise do circuito\nvC_inf = 75.84   # valor final da tens\u00e3o sobre o capacitor\niL_t0 = 0        #  valor inicial da corrente no indutor\nvC_t0 = 21.3     # valor inicial da tens\u00e3o sobre o capacitor\n\nt0 = 0 # instante do chaveamento\n```\n\n\n```python\n# define a frequ\u00eancia de oscila\u00e7\u00e3o amortecida\n\u03c9d =np.sqrt(\u03c90**2-\u03b1**2)\n\nsymdisp('\u03c9_d =', round(\u03c9d, 2), ' rad/s')\n\n# define vari\u00e1veis da solu\u00e7\u00e3o geral\nt, B1, B2 = sp.symbols('t, B1, B2')\n\n# express\u00e3o geral da resposta subamortecida\nvC = sp.exp(-\u03b1*(t-t0))*(B1*sp.cos(\u03c9d*(t-t0)) + B2*sp.sin(\u03c9d*(t-t0))) + vC_inf\n\nsymdisp('v_C(t) = ', round_expr(vC, 2), ' V')\n```\n\n\n```python\n# define os sistema de equa\u00e7\u00f5es com as condi\u00e7\u00f5es iniciais\neq1 = sp.Eq(   B1 + vC_inf, vC_t0)             \neq2 = sp.Eq(-\u03b1*B1 + \u03c9d*B2,  iL_t0/C)  \n\nprint('Sistema de equa\u00e7\u00f5es:')\nsymdisp('(I): ', round_expr(eq1, 2),' ')\nsymdisp('(II): ', round_expr(eq2, 2),' ')\n```\n\n\n```python\n# resolve o sistema\nsoluc = sp.solve((eq1, eq2), dict=True)\nB1 = np.array([sol[B1] for sol in soluc])\nB2 = np.array([sol[B2] for sol in soluc])\n\nB1 = B1[0]\nB2 = B2[0]\n\nprint('Solu\u00e7\u00e3o do sistema:')\nsymdisp('B_1 =', round(B1, 2), ' V')\nsymdisp('B_2 =', round(B2, 2), ' V')\n```\n\n\n```python\n# express\u00e3o geral da resposta subamortecida\nvC = sp.exp(-\u03b1*(t-t0))*(B1*sp.cos(\u03c9d*(t-t0)) + B2*sp.sin(\u03c9d*(t-t0))) + vC_inf\n\nsymdisp('v_C(t) = ', round_expr(vC, 2), ' V')\n```\n\n\n```python\n# corrente passando pelo indutor\niL = C*sp.diff(vC, t)\n\nsymdisp('i_L(t) = ', round_expr(iL.simplify(),5), 'A')\n```\n\n\n```python\n# plota gr\u00e1fico da fun\u00e7\u00e3o\nintervalo = np.linspace(t0,t0+0.25,100)\nsymplot(t, vC, intervalo, 'vC(t)')\n```\n\n\n```python\n# plota gr\u00e1fico da fun\u00e7\u00e3o\nintervalo = np.linspace(t0,t0+0.25,100)\nsymplot(t, iL, intervalo, 'iL(t)')\n```\n", "meta": {"hexsha": "7c477863e490ec5622858b5d8dafd5145c2f141f", "size": 105363, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Jupyter notebooks/Circuitos Eletricos I - Semana 8.2.ipynb", "max_stars_repo_name": "Jefferson-Lopes/ElectricCircuits", "max_stars_repo_head_hexsha": "bf2075dc0731cacece75f7b0b378c180630bdf85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Jupyter notebooks/Circuitos Eletricos I - Semana 8.2.ipynb", "max_issues_repo_name": "Jefferson-Lopes/ElectricCircuits", "max_issues_repo_head_hexsha": "bf2075dc0731cacece75f7b0b378c180630bdf85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Jupyter notebooks/Circuitos Eletricos I - Semana 8.2.ipynb", "max_forks_repo_name": "Jefferson-Lopes/ElectricCircuits", "max_forks_repo_head_hexsha": "bf2075dc0731cacece75f7b0b378c180630bdf85", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.2931937173, "max_line_length": 18052, "alphanum_fraction": 0.7664360354, "converted": true, "num_tokens": 7945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18952109590739918, "lm_q2_score": 0.18242552158390102, "lm_q1q2_score": 0.03457348477205983}}
{"text": "# COVID-19 - An\u00e1lise dos dados \n##  Para esta an\u00e1lise est\u00e3o sendo usadas as bases de dados do COVID-19 fornecidas pela universidade [Johns Hopkins], ser\u00e3o usadas as bases de dados por categoria ( [Confirmed], [Recovered], [Deaths]) assim como a base de [reporte diario].\n\n## As bases de dados  por categoria s\u00e3o composta por:\n- Province/State - Prov\u00edncia/estado que foi registrado a ocorr\u00eancia\n- Country/Region - Continente/regi\u00e3o que foi registrado a ocorr\u00eancia\n- Lat - latitude da regi\u00e3o\n- Long - longitude da regi\u00e3o\n- data - colunas que representam a data di\u00e1rio das ocorr\u00eancias\n\n## A base de dados  de reporte di\u00e1rio \u00e9 composta por:\n- Province/State - Provincia/estado que foi registrado a ocorr\u00eancia\n- Country/Region - Continente/regi\u00e3o que foi registrado a ocorr\u00eancia\n- Last Update - Data da \u00faltima atualiza\u00e7\u00e3o\n- Confirmed - Quantidade de casos confirmados\n- Deaths - Quantidade de mortes\n- Recovered - quantidade de recupera\u00e7\u00f5es\n- Lat - latitude da regi\u00e3o\n- Long - longitude da regi\u00e3o\n- data - colunas que representam a data di\u00e1rio das ocorr\u00eancias\n\n\n### obs: todas as bases de dados usadas s\u00e3o atualizadas diariamente.\n\n\n[Johns Hopkins]: <https://github.com/CSSEGISandData>\n[Confirmed]: <https://github.com/CSSEGISandData/COVID-19/blob/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv>\n[Recovered]: <https://github.com/CSSEGISandData/COVID-19/blob/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Recovered.csv>\n[Deaths]: <https://github.com/CSSEGISandData/COVID-19/blob/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Deaths.csv>\n[reporte diario]: <https://github.com/CSSEGISandData/COVID-19/tree/master/csse_covid_19_data/csse_covid_19_daily_reports>\n\n\n\n```python\n# importes necess\u00e1rios\nimport pandas as pd\nimport altair as alt\nimport numpy as np\nfrom datetime import date\nfrom vega_datasets import data\n```\n\n\n```python\n# Constantes\nprefixo_taxa = 'taxa_aumento_'\ndata_formato = '%m-%d-%Y'\ndata_atual = date.today()\ndata_atual_formatada = data_atual.strftime(data_formato)\ndata_ultima_checagem_confirmada = '03-21-2020'\nURL_covid_confirmed_for_day = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/{0}.csv'\n```\n\n### Importe das b\u00e1ses de dados por categoria\n\n\n```python\ncovid_confirmed = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv')\ncovid_recovered = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv')\ncovid_deaths = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv')\ncovid_deaths.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Province/State</th>\n      <th>Country/Region</th>\n      <th>Lat</th>\n      <th>Long</th>\n      <th>1/22/20</th>\n      <th>1/23/20</th>\n      <th>1/24/20</th>\n      <th>1/25/20</th>\n      <th>1/26/20</th>\n      <th>1/27/20</th>\n      <th>...</th>\n      <th>3/19/20</th>\n      <th>3/20/20</th>\n      <th>3/21/20</th>\n      <th>3/22/20</th>\n      <th>3/23/20</th>\n      <th>3/24/20</th>\n      <th>3/25/20</th>\n      <th>3/26/20</th>\n      <th>3/27/20</th>\n      <th>3/28/20</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>NaN</td>\n      <td>Afghanistan</td>\n      <td>33.0000</td>\n      <td>65.0000</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>2</td>\n      <td>4</td>\n      <td>4</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>NaN</td>\n      <td>Albania</td>\n      <td>41.1533</td>\n      <td>20.1683</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2</td>\n      <td>2</td>\n      <td>2</td>\n      <td>2</td>\n      <td>4</td>\n      <td>5</td>\n      <td>5</td>\n      <td>6</td>\n      <td>8</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>NaN</td>\n      <td>Algeria</td>\n      <td>28.0339</td>\n      <td>1.6596</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>9</td>\n      <td>11</td>\n      <td>15</td>\n      <td>17</td>\n      <td>17</td>\n      <td>19</td>\n      <td>21</td>\n      <td>25</td>\n      <td>26</td>\n      <td>29</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>NaN</td>\n      <td>Andorra</td>\n      <td>42.5063</td>\n      <td>1.5218</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>3</td>\n      <td>3</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>NaN</td>\n      <td>Angola</td>\n      <td>-11.2027</td>\n      <td>17.8739</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 71 columns</p>\n</div>\n\n\n\n## Importe da b\u00e1se de dados de reporte di\u00e1rio, caso n\u00e3o seja encontrado a base relacionada ao dia atual ser\u00e1 carregado uma base de data pr\u00e9 definida\n\n\n```python\ncovid_reports_for_day = []\n\ntry:\n    covid_reports_for_day = pd.read_csv(URL_covid_confirmed_for_day.format(data_atual_formatada))\nexcept:\n    covid_reports_for_day = pd.read_csv(URL_covid_confirmed_for_day.format(data_ultima_checagem_confirmada))\n    \ncovid_reports_for_day.tail()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Province/State</th>\n      <th>Country/Region</th>\n      <th>Last Update</th>\n      <th>Confirmed</th>\n      <th>Deaths</th>\n      <th>Recovered</th>\n      <th>Latitude</th>\n      <th>Longitude</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>299</th>\n      <td>NaN</td>\n      <td>Jersey</td>\n      <td>2020-03-17T18:33:03</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>49.1900</td>\n      <td>-2.110</td>\n    </tr>\n    <tr>\n      <th>300</th>\n      <td>NaN</td>\n      <td>Puerto Rico</td>\n      <td>2020-03-17T16:13:14</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>18.2000</td>\n      <td>-66.500</td>\n    </tr>\n    <tr>\n      <th>301</th>\n      <td>NaN</td>\n      <td>Republic of the Congo</td>\n      <td>2020-03-17T21:33:03</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>-1.4400</td>\n      <td>15.556</td>\n    </tr>\n    <tr>\n      <th>302</th>\n      <td>NaN</td>\n      <td>The Bahamas</td>\n      <td>2020-03-19T12:13:38</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>24.2500</td>\n      <td>-76.000</td>\n    </tr>\n    <tr>\n      <th>303</th>\n      <td>NaN</td>\n      <td>The Gambia</td>\n      <td>2020-03-18T14:13:56</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>13.4667</td>\n      <td>-16.600</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### \u00c9 criado uma base de dados para an\u00e1lise da s\u00e9rie temporal a partir da uni\u00e3o das bases de dados por categoria.\n\n\n```python\ntodal_casos_morte_por_dia = np.sum(covid_deaths.iloc[ : , 4 : covid_deaths.shape[1]])\ntodal_casos_confirmacao_por_dia = np.sum(covid_confirmed.iloc[ : , 4 : covid_confirmed.shape[1]])\ntodal_casos_recuperacao_por_dia = np.sum(covid_recovered.iloc[ : , 4 : covid_recovered.shape[1]])\n\ncovid_serie_temporal = pd.DataFrame([todal_casos_confirmacao_por_dia, todal_casos_recuperacao_por_dia, todal_casos_morte_por_dia]).T\ncovid_serie_temporal.reset_index(inplace = True)\ncovid_serie_temporal.columns = ['data','confirmacao', 'recuperacao', 'mortes']\ncovid_serie_temporal['data'] = pd.to_datetime(covid_serie_temporal['data'])\n\ncovid_serie_temporal.tail()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>data</th>\n      <th>confirmacao</th>\n      <th>recuperacao</th>\n      <th>mortes</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>62</th>\n      <td>2020-03-24</td>\n      <td>418045</td>\n      <td>108000</td>\n      <td>18625</td>\n    </tr>\n    <tr>\n      <th>63</th>\n      <td>2020-03-25</td>\n      <td>467653</td>\n      <td>113787</td>\n      <td>21181</td>\n    </tr>\n    <tr>\n      <th>64</th>\n      <td>2020-03-26</td>\n      <td>529591</td>\n      <td>122150</td>\n      <td>23970</td>\n    </tr>\n    <tr>\n      <th>65</th>\n      <td>2020-03-27</td>\n      <td>593291</td>\n      <td>130915</td>\n      <td>27198</td>\n    </tr>\n    <tr>\n      <th>66</th>\n      <td>2020-03-28</td>\n      <td>660706</td>\n      <td>139415</td>\n      <td>30652</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### M\u00e9todo ira criar uma nova coluna do dataset a partir de um prefixo e o nome da coluna, essa nova coluna representa a taxa de cr\u00e9scimento di\u00e1rio da coluna. A taxa de crescimento \u00e9 c\u00e1lculada pela seguinte f\u00f3rmula:\n\n\\begin{align}\n\\text{taxa_crescimento} ={\\frac  {({\\text{valor_presente}})-({\\text{valor_passado}})}{({\\text{valor_passado}})}} \n\\end{align}\n\n\n```python\ndef taxa_de_crescimento(data, colum):\n    dimensao = data[colum].shape[0]\n    resultados =[]\n    for i in range (dimensao - 1):\n        resultados.append(data[colum][i+1] - data[colum][i])\n        if(i == dimensao - 2):\n            resultados.append(np.nan)\n        \n    data[prefixo_taxa + colum] = resultados\n```\n\n### aplica o m\u00e9todo `taxa_de_crescimento` aos campos da an\u00e1lise\n\n\n```python\ntaxa_de_crescimento(covid_serie_temporal, 'confirmacao')\ntaxa_de_crescimento(covid_serie_temporal, 'recuperacao')\ntaxa_de_crescimento(covid_serie_temporal, 'mortes')\ncovid_serie_temporal.tail()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>data</th>\n      <th>confirmacao</th>\n      <th>recuperacao</th>\n      <th>mortes</th>\n      <th>taxa_aumento_confirmacao</th>\n      <th>taxa_aumento_recuperacao</th>\n      <th>taxa_aumento_mortes</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>62</th>\n      <td>2020-03-24</td>\n      <td>418045</td>\n      <td>108000</td>\n      <td>18625</td>\n      <td>49608.0</td>\n      <td>5787.0</td>\n      <td>2556.0</td>\n    </tr>\n    <tr>\n      <th>63</th>\n      <td>2020-03-25</td>\n      <td>467653</td>\n      <td>113787</td>\n      <td>21181</td>\n      <td>61938.0</td>\n      <td>8363.0</td>\n      <td>2789.0</td>\n    </tr>\n    <tr>\n      <th>64</th>\n      <td>2020-03-26</td>\n      <td>529591</td>\n      <td>122150</td>\n      <td>23970</td>\n      <td>63700.0</td>\n      <td>8765.0</td>\n      <td>3228.0</td>\n    </tr>\n    <tr>\n      <th>65</th>\n      <td>2020-03-27</td>\n      <td>593291</td>\n      <td>130915</td>\n      <td>27198</td>\n      <td>67415.0</td>\n      <td>8500.0</td>\n      <td>3454.0</td>\n    </tr>\n    <tr>\n      <th>66</th>\n      <td>2020-03-28</td>\n      <td>660706</td>\n      <td>139415</td>\n      <td>30652</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### O gr\u00e1fico demonstra a evolu\u00e7\u00e3o dos casos de infec\u00e7\u00e3o pelo COVID-19, o gr\u00e1fico inferior demonstra o comparativo de crescimento no decorrer do tempo para os casos de confirma\u00e7\u00e3o, recupera\u00e7\u00e3o e morte. J\u00e1 os gr\u00e1ficos superiores demonstram a evolu\u00e7\u00e3o de acordo com o respectivos status: confirma\u00e7\u00e3o, recupera\u00e7\u00e3o e morte. Sendo poss\u00edvel selecionar um per\u00edodo de tempo ao clicar e arrastar o mouse.\n\n\n```python\nbrush = alt.selection_interval(encodings=['x'])\n\ncard_principal = alt.Chart(covid_serie_temporal).mark_area(\n    color=\"lightyellow\",\n    line=True\n).encode(\n    alt.X(\"data:T\",),\n    alt.Y('confirmacao:Q'),\n    tooltip = [\"data:T\", 'confirmacao:Q']\n).properties(width=800,height=200, title='Ocorr\u00eancias do COVID-19 ao decorrer do tempo.').add_selection(brush)\n\n\nconfirmacao = alt.Chart(covid_serie_temporal).mark_area(\n    color=\"lightyellow\",\n    line=True\n).encode(\n    alt.X(\"data:T\", scale=alt.Scale(domain=brush)),\n    alt.Y('confirmacao:Q', title= 'Quantidade de pessoas')\n).properties(width=200,height=200, title=['Casos confirmados de infec\u00e7\u00e3o', 'pelo COVID-19']).transform_filter(brush)\n\nrecuperacao = alt.Chart(covid_serie_temporal).mark_area(\n    color=\"lightgreen\",\n    line=True\n).encode(\n    alt.X(\"data:T\"),\n    alt.Y('recuperacao:Q', title= 'Quantidade de pessoas')\n).properties(width=200,height=200, title=['Casos confirmados de recupera\u00e7\u00e3o', 'do COVID-19']).transform_filter(brush)\n\nmorte = alt.Chart(covid_serie_temporal).mark_area(\n    color=\"red\",\n    line=True\n).encode(\n    alt.X(\"data:T\"),\n    alt.Y('mortes:Q', title= 'Quantidade de pessoas')\n).properties(width=200,height=200, title=['Casos confirmados de morte' ,'pelo COVID-19']).transform_filter(brush)\n\nevolucao_COVID = (confirmacao | recuperacao | morte) & (card_principal.encode(alt.Y('confirmacao', title= 'Quantidade de pessoas')) + recuperacao + morte)\n\nevolucao_COVID.save('plots/evolucao_COVID_19.html')\n\nevolucao_COVID\n```\n\n\n\n\n\n<div id=\"altair-viz-a036cac8376f401b86c5286a87717c88\"></div>\n\n\n\n\n### O gr\u00e1fico demonstra a taxa de crescimento dos casos de infec\u00e7\u00e3o pelo COVID-19, o gr\u00e1fico inferior demonstra o comparativo de crescimento no decorrer do tempo para os casos de confirma\u00e7\u00e3o, recupera\u00e7\u00e3o e morte. J\u00e1 os gr\u00e1ficos superiores demonstram a taxa de evolu\u00e7\u00e3o de acordo com o respectivos status: confirma\u00e7\u00e3o, recupera\u00e7\u00e3o e morte. Sendo poss\u00edvel selecionar um per\u00edodo de tempo ao clicar e arrastar o mouse.\n\n\n```python\nbrush = alt.selection_interval(encodings=['x'])\n\ncard_principal = alt.Chart(covid_serie_temporal.dropna()).mark_area(\n    color=\"lightyellow\",\n    line=True\n).encode(\n    alt.X(\"data:T\",),\n    alt.Y('taxa_aumento_confirmacao:Q'),\n    tooltip = [\"data:T\", 'taxa_aumento_confirmacao:Q']\n).properties(width=800,height=300, title='Taxa de crescimento do cont\u00e1gio pelo COVID-19 ao decorrer do tempo.').add_selection(brush)\n\n\nconfirmacao = alt.Chart(covid_serie_temporal.dropna()).mark_area(\n    color=\"lightyellow\",\n    line=True\n).encode(\n    alt.X(\"data:T\", scale=alt.Scale(domain=brush)),\n    alt.Y('taxa_aumento_confirmacao:Q', title= 'Quantidade de pessoas')\n).properties(width=200,height=200, title=['Taxa de crescimento de casos', 'confirmados de infec\u00e7\u00e3o pelo COVID-19']).transform_filter(brush)\n\nrecuperacao = alt.Chart(covid_serie_temporal.dropna()).mark_area(\n    color=\"lightgreen\",\n    line=True\n).encode(\n    alt.X(\"data:T\"),\n    alt.Y('taxa_aumento_recuperacao:Q', title= 'Quantidade de pessoas')\n).properties(width=200,height=200, title=['Taxa de crescimento de casos','confirmados de recupera\u00e7\u00e3o do COVID-19']).transform_filter(brush)\n\nmorte = alt.Chart(covid_serie_temporal.dropna()).mark_area(\n    color=\"red\",\n    line=True\n).encode(\n    alt.X(\"data:T\"),\n    alt.Y('taxa_aumento_mortes:Q', title= 'Quantidade de pessoas')\n).properties(width=200,height=200, title=['Taxa de crescimento de casos','confirmados de morte pelo COVID-19']).transform_filter(brush)\n\ntaxa_aumento_contagio = (confirmacao | recuperacao | morte) & (card_principal.encode(alt.Y('taxa_aumento_confirmacao', title= 'Quantidade de pessoas')) + recuperacao + morte)\n\ntaxa_aumento_contagio.save('plots/taxa_de_aumento_no_contagio_COVID_19.html')\n\ntaxa_aumento_contagio\n```\n\n\n\n\n\n<div id=\"altair-viz-64511eeb5a8347989f01b588e4850525\"></div>\n\n\n\n\n\n```python\ncovid_reports_for_day.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Province/State</th>\n      <th>Country/Region</th>\n      <th>Last Update</th>\n      <th>Confirmed</th>\n      <th>Deaths</th>\n      <th>Recovered</th>\n      <th>Latitude</th>\n      <th>Longitude</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Hubei</td>\n      <td>China</td>\n      <td>2020-03-21T10:13:08</td>\n      <td>67800</td>\n      <td>3139</td>\n      <td>58946</td>\n      <td>30.9756</td>\n      <td>112.2707</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>NaN</td>\n      <td>Italy</td>\n      <td>2020-03-21T17:43:03</td>\n      <td>53578</td>\n      <td>4825</td>\n      <td>6072</td>\n      <td>41.8719</td>\n      <td>12.5674</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>NaN</td>\n      <td>Spain</td>\n      <td>2020-03-21T13:13:30</td>\n      <td>25374</td>\n      <td>1375</td>\n      <td>2125</td>\n      <td>40.4637</td>\n      <td>-3.7492</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>NaN</td>\n      <td>Germany</td>\n      <td>2020-03-21T20:43:02</td>\n      <td>22213</td>\n      <td>84</td>\n      <td>233</td>\n      <td>51.1657</td>\n      <td>10.4515</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>NaN</td>\n      <td>Iran</td>\n      <td>2020-03-21T11:13:12</td>\n      <td>20610</td>\n      <td>1556</td>\n      <td>7635</td>\n      <td>32.4279</td>\n      <td>53.6880</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### O mapa demonstra a situa\u00e7\u00e3o de cont\u00e1gio pelo COVID-19 dos Pa\u00edses/Estados, podendo-se interagir com o mapa ao passar o mouse nas regi\u00f5es em vermelho, onde ir\u00e1 ser demonstrado respectivamente:\n- Quantidade de confirma\u00e7\u00f5es;\n- Quantidade de mortes;\n- Quantidade de recupera\u00e7\u00f5es;\n- Prov\u00edncia/Estado selecionado;\n- Pa\u00eds selecionado;\n- Data da \u00faltima atualiza\u00e7\u00e3o.\n\n\n\n```python\nsource = alt.topo_feature(data.world_110m.url, 'countries')\nsphere = alt.sphere()\ngraticule = alt.graticule()\n\nprojections = 'equirectangular'\n\nsize = alt.Size('Confirmed:N', legend=None)\n\ncircles = alt.Chart(covid_reports_for_day).mark_circle(color='#FE2E2E', opacity = 0.4).encode(\n    longitude=\"Longitude:Q\",\n    latitude=\"Latitude:Q\",\n    size = size,\n    tooltip = ['Confirmed:Q', 'Deaths:Q', 'Recovered:Q', 'Province/State:N', 'Country/Region:N', 'Last Update:T']\n)\n\ngeo_shape = alt.layer(\n    alt.Chart(sphere).mark_geoshape(fill='lightblue', stroke = \"invert ? '#777' : '#bbb'\"),\n    alt.Chart(graticule).mark_geoshape(stroke='white', strokeWidth=0),\n    alt.Chart(source).mark_geoshape(fill='#F5F3A6', stroke='black') \n).properties(\n    width=800,\n    height=400\n).project(projections).properties(title='Mapa mundi')\n\nfig = alt.layer(\n    geo_shape,\n    circles,\n)\n\nfig.save('plots/situa\u00e7\u00e3o_COVID_19.html')\n\nfig\n```\n\n\n\n\n\n<div id=\"altair-viz-17fd5422f8c645e7ace69b9534ede996\"></div>\n\n\n\n", "meta": {"hexsha": "3947dc3ceffc95e5599521b31d5cb00243679ff0", "size": 141948, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "COVID-19/COVID-19.ipynb", "max_stars_repo_name": "DoglasProg/Ciencia-de-dados", "max_stars_repo_head_hexsha": "eab55738d8250279c14a5a6f7ce57ebc4d3a4818", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "COVID-19/COVID-19.ipynb", "max_issues_repo_name": "DoglasProg/Ciencia-de-dados", "max_issues_repo_head_hexsha": "eab55738d8250279c14a5a6f7ce57ebc4d3a4818", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "COVID-19/COVID-19.ipynb", "max_forks_repo_name": "DoglasProg/Ciencia-de-dados", "max_forks_repo_head_hexsha": "eab55738d8250279c14a5a6f7ce57ebc4d3a4818", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 121.3230769231, "max_line_length": 64588, "alphanum_fraction": 0.5582255474, "converted": true, "num_tokens": 6777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473339755162, "lm_q2_score": 0.08035746937280606, "lm_q1q2_score": 0.034565551215731724}}
{"text": "<a href=\"https://colab.research.google.com/github/praveentn/ml-repos/blob/master/Notebooks/QML/003-Cirq-Quantum_Hybrid_Model_Training_1.ipynb\" target=\"_parent\"></a>\n\n### Generating & training hybrid models\n\nI hand you a quantum circuit with some free parameters and then I hand you some samples from that quantum circuit at specific parameter values, but I don't tell you what the parameter values are and then your goal is to try and determine what the parameter values are via some optimization or ML type algorithm that takes the samples I gave you as input.\n\n\n```python\n# must have tensorflow, tensorflow-gpu, tensorflow_quantum in the list\n# tensorflow==2.4.1\n# tensorflow-gpu==2.4.1\n!pip list\n```\n\n    Package                       Version\n    ----------------------------- --------------\n    absl-py                       0.12.0\n    alabaster                     0.7.12\n    albumentations                0.1.12\n    altair                        4.1.0\n    appdirs                       1.4.4\n    argcomplete                   1.12.3\n    argon2-cffi                   21.1.0\n    arviz                         0.11.4\n    astor                         0.8.1\n    astropy                       4.3.1\n    astunparse                    1.6.3\n    atari-py                      0.2.9\n    atomicwrites                  1.4.0\n    attrs                         20.3.0\n    audioread                     2.1.9\n    autograd                      1.3\n    Babel                         2.9.1\n    backcall                      0.2.0\n    beautifulsoup4                4.6.3\n    bleach                        4.1.0\n    blis                          0.4.1\n    bokeh                         2.3.3\n    Bottleneck                    1.3.2\n    branca                        0.4.2\n    bs4                           0.0.1\n    CacheControl                  0.12.6\n    cached-property               1.5.2\n    cachetools                    4.2.4\n    catalogue                     1.0.0\n    certifi                       2021.5.30\n    cffi                          1.14.6\n    cftime                        1.5.1\n    chardet                       3.0.4\n    charset-normalizer            2.0.6\n    cirq                          0.11.0\n    cirq-aqt                      0.13.0\n    cirq-core                     0.11.0\n    cirq-google                   0.11.0\n    cirq-ionq                     0.13.0\n    cirq-pasqal                   0.13.0\n    cirq-rigetti                  0.13.0\n    cirq-web                      0.13.0\n    clang                         5.0\n    click                         7.1.2\n    cloudpickle                   1.3.0\n    cmake                         3.12.0\n    cmdstanpy                     0.9.5\n    colorcet                      2.0.6\n    colorlover                    0.3.0\n    community                     1.0.0b1\n    contextlib2                   0.5.5\n    convertdate                   2.3.2\n    coverage                      3.7.1\n    coveralls                     0.5\n    crcmod                        1.7\n    cufflinks                     0.17.3\n    cupy-cuda111                  9.4.0\n    cvxopt                        1.2.7\n    cvxpy                         1.0.31\n    cycler                        0.10.0\n    cymem                         2.0.5\n    Cython                        0.29.24\n    daft                          0.0.4\n    dask                          2.12.0\n    datascience                   0.10.6\n    debugpy                       1.0.0\n    decorator                     4.4.2\n    defusedxml                    0.7.1\n    descartes                     1.1.0\n    dill                          0.3.4\n    distributed                   1.25.3\n    dlib                          19.18.0\n    dm-tree                       0.1.6\n    docopt                        0.6.2\n    docutils                      0.17.1\n    dopamine-rl                   1.0.5\n    duet                          0.2.2\n    earthengine-api               0.1.284\n    easydict                      1.9\n    ecos                          2.0.7.post1\n    editdistance                  0.5.3\n    en-core-web-sm                2.2.5\n    entrypoints                   0.3\n    ephem                         4.1\n    et-xmlfile                    1.1.0\n    fa2                           0.3.5\n    fastai                        1.0.61\n    fastdtw                       0.3.4\n    fastprogress                  1.0.0\n    fastrlock                     0.6\n    fbprophet                     0.7.1\n    feather-format                0.4.1\n    filelock                      3.3.0\n    firebase-admin                4.4.0\n    fix-yahoo-finance             0.0.22\n    Flask                         1.1.4\n    flatbuffers                   1.12\n    folium                        0.8.3\n    future                        0.16.0\n    gast                          0.3.3\n    GDAL                          2.2.2\n    gdown                         3.6.4\n    gensim                        3.6.0\n    geographiclib                 1.52\n    geopy                         1.17.0\n    gin-config                    0.4.0\n    glob2                         0.7\n    google                        2.0.3\n    google-api-core               1.21.0\n    google-api-python-client      1.12.8\n    google-auth                   1.18.0\n    google-auth-httplib2          0.0.4\n    google-auth-oauthlib          0.4.6\n    google-cloud-bigquery         1.21.0\n    google-cloud-bigquery-storage 1.1.0\n    google-cloud-core             1.0.3\n    google-cloud-datastore        1.8.0\n    google-cloud-firestore        1.7.0\n    google-cloud-language         1.2.0\n    google-cloud-storage          1.18.1\n    google-cloud-translate        1.5.0\n    google-colab                  1.0.0\n    google-pasta                  0.2.0\n    google-resumable-media        0.4.1\n    googleapis-common-protos      1.52.0\n    googledrivedownloader         0.4\n    graphviz                      0.10.1\n    greenlet                      1.1.2\n    grpcio                        1.32.0\n    gspread                       3.0.1\n    gspread-dataframe             3.0.8\n    gym                           0.17.3\n    h11                           0.9.0\n    h5py                          2.10.0\n    HeapDict                      1.0.1\n    hijri-converter               2.2.2\n    holidays                      0.10.5.2\n    holoviews                     1.14.6\n    html5lib                      1.0.1\n    httpcore                      0.11.1\n    httpimport                    0.5.18\n    httplib2                      0.17.4\n    httplib2shim                  0.0.3\n    httpx                         0.15.5\n    humanize                      0.5.1\n    hyperopt                      0.1.2\n    ideep4py                      2.0.0.post3\n    idna                          2.10\n    imageio                       2.4.1\n    imagesize                     1.2.0\n    imbalanced-learn              0.4.3\n    imblearn                      0.0\n    imgaug                        0.2.9\n    importlib-metadata            3.10.1\n    importlib-resources           5.2.2\n    imutils                       0.5.4\n    inflect                       2.1.0\n    iniconfig                     1.1.1\n    intel-openmp                  2021.4.0\n    intervaltree                  2.1.0\n    ipykernel                     4.10.1\n    ipython                       5.5.0\n    ipython-genutils              0.2.0\n    ipython-sql                   0.3.9\n    ipywidgets                    7.6.5\n    iso8601                       0.1.16\n    itsdangerous                  1.1.0\n    jax                           0.2.21\n    jaxlib                        0.1.71+cuda111\n    jdcal                         1.4.1\n    jedi                          0.18.0\n    jieba                         0.42.1\n    Jinja2                        2.11.3\n    joblib                        1.0.1\n    jpeg4py                       0.1.4\n    jsonschema                    2.6.0\n    jupyter                       1.0.0\n    jupyter-client                5.3.5\n    jupyter-console               5.2.0\n    jupyter-core                  4.8.1\n    jupyterlab-pygments           0.1.2\n    jupyterlab-widgets            1.0.2\n    kaggle                        1.5.12\n    kapre                         0.3.5\n    keras                         2.6.0\n    Keras-Preprocessing           1.1.2\n    keras-vis                     0.4.1\n    kiwisolver                    1.3.2\n    korean-lunar-calendar         0.2.1\n    lark                          0.11.3\n    librosa                       0.8.1\n    lightgbm                      2.2.3\n    llvmlite                      0.34.0\n    lmdb                          0.99\n    LunarCalendar                 0.0.9\n    lxml                          4.2.6\n    Markdown                      3.3.4\n    MarkupSafe                    2.0.1\n    matplotlib                    3.2.2\n    matplotlib-inline             0.1.3\n    matplotlib-venn               0.11.6\n    missingno                     0.5.0\n    mistune                       0.8.4\n    mizani                        0.6.0\n    mkl                           2019.0\n    mlxtend                       0.14.0\n    more-itertools                8.10.0\n    moviepy                       0.2.3.5\n    mpmath                        1.2.1\n    msgpack                       0.6.2\n    multiprocess                  0.70.12.2\n    multitasking                  0.0.9\n    murmurhash                    1.0.5\n    music21                       5.5.0\n    natsort                       5.5.0\n    nbclient                      0.5.4\n    nbconvert                     5.6.1\n    nbformat                      5.1.3\n    nest-asyncio                  1.5.1\n    netCDF4                       1.5.7\n    networkx                      2.6.3\n    nibabel                       3.0.2\n    nltk                          3.2.5\n    notebook                      5.3.1\n    numba                         0.51.2\n    numexpr                       2.7.3\n    numpy                         1.19.5\n    nvidia-ml-py3                 7.352.0\n    oauth2client                  4.1.3\n    oauthlib                      3.1.1\n    okgrade                       0.4.3\n    opencv-contrib-python         4.1.2.30\n    opencv-python                 4.1.2.30\n    openpyxl                      2.5.9\n    opt-einsum                    3.3.0\n    osqp                          0.6.2.post0\n    packaging                     21.0\n    palettable                    3.3.0\n    pandas                        1.1.5\n    pandas-datareader             0.9.0\n    pandas-gbq                    0.13.3\n    pandas-profiling              1.4.1\n    pandocfilters                 1.5.0\n    panel                         0.12.1\n    param                         1.11.1\n    parso                         0.8.2\n    pathlib                       1.0.1\n    patsy                         0.5.2\n    pep517                        0.11.0\n    pexpect                       4.8.0\n    pickleshare                   0.7.5\n    Pillow                        7.1.2\n    pip                           21.1.3\n    pip-tools                     6.2.0\n    plac                          1.1.3\n    plotly                        4.4.1\n    plotnine                      0.6.0\n    pluggy                        0.7.1\n    pooch                         1.5.1\n    portpicker                    1.3.9\n    prefetch-generator            1.0.1\n    preshed                       3.0.5\n    prettytable                   2.2.1\n    progressbar2                  3.38.0\n    prometheus-client             0.11.0\n    promise                       2.3\n    prompt-toolkit                1.0.18\n    protobuf                      3.13.0\n    psutil                        5.4.8\n    psycopg2                      2.7.6.1\n    ptyprocess                    0.7.0\n    py                            1.10.0\n    pyarrow                       3.0.0\n    pyasn1                        0.4.8\n    pyasn1-modules                0.2.8\n    pycocotools                   2.0.2\n    pycparser                     2.20\n    pyct                          0.4.8\n    pydantic                      1.8.2\n    pydata-google-auth            1.2.0\n    pydot                         1.3.0\n    pydot-ng                      2.0.0\n    pydotplus                     2.0.2\n    PyDrive                       1.3.1\n    pyemd                         0.5.1\n    pyerfa                        2.0.0\n    pyglet                        1.5.0\n    Pygments                      2.6.1\n    pygobject                     3.26.1\n    PyJWT                         1.7.1\n    pymc3                         3.11.4\n    PyMeeus                       0.5.11\n    pymongo                       3.12.0\n    pymystem3                     0.2.0\n    PyOpenGL                      3.1.5\n    pyparsing                     2.4.7\n    pyquil                        3.0.1\n    pyrsistent                    0.18.0\n    pysndfile                     1.3.8\n    PySocks                       1.7.1\n    pystan                        2.19.1.1\n    pytest                        3.6.4\n    python-apt                    0.0.0\n    python-chess                  0.23.11\n    python-dateutil               2.8.2\n    python-louvain                0.15\n    python-rapidjson              1.5\n    python-slugify                5.0.2\n    python-utils                  2.5.6\n    pytz                          2018.9\n    pyviz-comms                   2.1.0\n    PyWavelets                    1.1.1\n    PyYAML                        3.13\n    pyzmq                         22.3.0\n    qcs-api-client                0.8.0\n    qdldl                         0.1.5.post0\n    qtconsole                     5.1.1\n    QtPy                          1.11.2\n    regex                         2019.12.20\n    requests                      2.23.0\n    requests-oauthlib             1.3.0\n    resampy                       0.2.2\n    retry                         0.9.2\n    retrying                      1.3.3\n    rfc3339                       6.2\n    rfc3986                       1.5.0\n    rpcq                          3.9.2\n    rpy2                          3.4.5\n    rsa                           4.7.2\n    ruamel.yaml                   0.17.16\n    ruamel.yaml.clib              0.2.6\n    scikit-image                  0.16.2\n    scikit-learn                  0.22.2.post1\n    scipy                         1.7.1\n    screen-resolution-extra       0.0.0\n    scs                           2.1.4\n    seaborn                       0.11.2\n    semver                        2.13.0\n    Send2Trash                    1.8.0\n    setuptools                    57.4.0\n    setuptools-git                1.2\n    Shapely                       1.7.1\n    simplegeneric                 0.8.1\n    six                           1.15.0\n    sklearn                       0.0\n    sklearn-pandas                1.8.0\n    smart-open                    5.2.1\n    sniffio                       1.2.0\n    snowballstemmer               2.1.0\n    sortedcontainers              2.4.0\n    SoundFile                     0.10.3.post1\n    spacy                         2.2.4\n    Sphinx                        1.8.5\n    sphinxcontrib-serializinghtml 1.1.5\n    sphinxcontrib-websupport      1.2.4\n    SQLAlchemy                    1.4.25\n    sqlparse                      0.4.2\n    srsly                         1.0.5\n    statsmodels                   0.10.2\n    sympy                         1.5\n    tables                        3.4.4\n    tabulate                      0.8.9\n    tblib                         1.7.0\n    tensorboard                   2.6.0\n    tensorboard-data-server       0.6.1\n    tensorboard-plugin-wit        1.8.0\n    tensorflow                    2.4.1\n    tensorflow-datasets           4.0.1\n    tensorflow-estimator          2.4.0\n    tensorflow-gcs-config         2.6.0\n    tensorflow-gpu                2.4.1\n    tensorflow-hub                0.12.0\n    tensorflow-metadata           1.2.0\n    tensorflow-probability        0.14.1\n    tensorflow-quantum            0.5.1\n    termcolor                     1.1.0\n    terminado                     0.12.1\n    testpath                      0.5.0\n    text-unidecode                1.3\n    textblob                      0.15.3\n    Theano-PyMC                   1.1.2\n    thinc                         7.4.0\n    tifffile                      2021.8.30\n    toml                          0.10.2\n    tomli                         1.2.1\n    toolz                         0.11.1\n    torch                         1.9.0+cu111\n    torchsummary                  1.5.1\n    torchtext                     0.10.0\n    torchvision                   0.10.0+cu111\n    tornado                       5.1.1\n    tqdm                          4.62.3\n    traitlets                     5.1.0\n    tweepy                        3.10.0\n    typeguard                     2.7.1\n    typing-extensions             3.7.4.3\n    tzlocal                       1.5.1\n    uritemplate                   3.0.1\n    urllib3                       1.24.3\n    vega-datasets                 0.9.0\n    wasabi                        0.8.2\n    wcwidth                       0.2.5\n    webencodings                  0.5.1\n    Werkzeug                      1.0.1\n    wheel                         0.37.0\n    widgetsnbextension            3.5.1\n    wordcloud                     1.5.0\n    wrapt                         1.12.1\n    xarray                        0.18.2\n    xgboost                       0.90\n    xkit                          0.0.0\n    xlrd                          1.1.0\n    xlwt                          1.3.0\n    yellowbrick                   0.9.1\n    zict                          2.0.0\n    zipp                          3.6.0\n\n\n\n```python\ntry:\n    import cirq\nexcept ImportError:\n    print(\"installing cirq...\")\n    !pip install --quiet cirq\n    print(\"installed cirq.\")\n```\n\n\n```python\nimport cirq\n\ncirq.__version__\n```\n\n\n\n\n    '0.11.0'\n\n\n\n\n```python\ntry:\n    import tensorflow as tf\n    if tf.__version__ != '2.4.1':\n        !pip uninstall --quiet tensorflow\n        !pip uninstall --quiet tensorflow-gpu\n        !pip install --quiet tensorflow==2.4.1\n        !pip install --quiet tensorflow-gpu==2.4.1\nexcept ImportError:\n    !pip uninstall --quiet tensorflow-gpu\n    !pip uninstall --quiet tensorflow\n    !pip install --quiet tensorflow==2.4.1\n    !pip install --quiet tensorflow-gpu==2.4.1\n```\n\n\n```python\nimport tensorflow as tf\n\ntf.__version__\n```\n\n\n\n\n    '2.4.1'\n\n\n\n\n```python\n# !pip uninstall tensorflow-gpu\n# !pip install --quiet tensorflow-gpu==2.4.1\n```\n\n\n```python\n# !pip install --quiet tensorflow-quantum=='0.5.1'\n```\n\n\n```python\ntry:\n    import tensorflow_quantum as tfq\n    if tfq.__version__ != '0.5.1':\n        !pip uninstall --quiet tensorflow-quantum\n        !pip install --quiet tensorflow-quantum=='0.5.1'\nexcept ImportError:\n    !pip install --quiet tensorflow-quantum=='0.5.1'\n```\n\n\n```python\nimport tensorflow_quantum as tfq\n\ntfq.__version__\n```\n\n\n\n\n    '0.5.1'\n\n\n\n\n```python\n# !pip install tensorflow-quantum\n```\n\n\n```python\n# hopefully not required\n# !pip uninstall tensorflow\n# !pip install tensorflow\n# !pip install --upgrade pip\n# !pip install --upgrade tensorflow\n# !pip install tensorflow-gpu\n```\n\n\n```python\n# Update package resources to account for version changes.\nimport importlib, pkg_resources\nimportlib.reload(pkg_resources)\n```\n\n\n\n\n    <module 'pkg_resources' from '/usr/local/lib/python3.7/dist-packages/pkg_resources/__init__.py'>\n\n\n\n\n```python\nimport cirq\nimport cirq_google\nimport numpy as np\nimport sympy as sp\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport tensorflow_quantum as tfq\nfrom math import sqrt, pi\n```\n\n\n```python\n# set random seed\ntf.random.set_seed(42)\n```\n\n\n```python\n# define two qubits\nq0 = cirq.GridQubit(0, 0)\nq1 = cirq.GridQubit(0, 1)\n\n# make a Pauli Sum gate that will return [1] if the state is a bell state b00 (|00\u27e9)\nz0 = cirq.Z(q0)\nz1 = cirq.Z(q1)\nz00 = (((1+z0)/2)*((1+z1)/2))\n\n# define three parameters, phi will be varied, alpha & beta are fixed\nphi = sp.Symbol('phi')\nalpha = sp.Symbol('alpha')\nbeta = sp.Symbol('beta')\n\n# create a circuit with the following gates RX, RY, H, CNOT etc.\n# the circuit has three parameters: phi, alpha & beta\ncircuit = cirq.Circuit([\n                cirq.rx(phi)(q0),\n                cirq.ry(-2*phi)(q1),\n                cirq.H(q0),\n                cirq.CNOT(q0,q1),\n                cirq.rx(alpha)(q0),\n                cirq.ry(beta)(q1),\n                ])\ncircuit\n```\n\n\n\n\n<pre style=\"overflow: auto; white-space: pre;\">(0, 0): \u2500\u2500\u2500Rx(phi)\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500Rx(alpha)\u2500\u2500\u2500\n                            \u2502\n(0, 1): \u2500\u2500\u2500Ry(-2*phi)\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500Ry(beta)\u2500\u2500\u2500\u2500</pre>\n\n\n\n\n```python\n# get the qasm code\ncircuit.to_qasm\n```\n\n\n\n\n    <bound method AbstractCircuit.to_qasm of cirq.Circuit([\n        cirq.Moment(\n            cirq.Rx(rads=sympy.Symbol('phi')).on(cirq.GridQubit(0, 0)),\n            cirq.Ry(rads=sympy.Mul(sympy.Integer(-1), sympy.Integer(2), sympy.Symbol('phi'))).on(cirq.GridQubit(0, 1)),\n        ),\n        cirq.Moment(\n            cirq.H(cirq.GridQubit(0, 0)),\n        ),\n        cirq.Moment(\n            cirq.CNOT(cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)),\n        ),\n        cirq.Moment(\n            cirq.Rx(rads=sympy.Symbol('alpha')).on(cirq.GridQubit(0, 0)),\n            cirq.Ry(rads=sympy.Symbol('beta')).on(cirq.GridQubit(0, 1)),\n        ),\n    ])>\n\n\n\n### Expectation\n\n\n```python\n# If we fix the values of alpha and beta, and perform a scan over phi\n# from [0, 2\u03c0], we can generate a distribution of the number of times\n# the system is measured in state |00\u27e9\n\n# fix two values of alpha and beta\na = 1/sqrt(2)\nb = pi/3\n\n# loop over phi from -5 to 5\nx_values = np.arange(-5, 5, 0.05)\ny_expectations = []\n\nfor j in x_values:\n    # resolve the circuit for different values of phi\n    resolver = cirq.ParamResolver({'alpha': a, 'beta': b, 'phi': j})\n\n    # calcuclate the expectation value\n    result = cirq.Simulator().simulate(cirq.resolve_parameters(circuit, resolver))\n    e = z00.expectation_from_state_vector(result.final_state_vector, {q0:0, q1:1})\n    y_expectations.append(e)\n\nprint(result)\nprint(e)\n\nplt.scatter(x_values, y_expectations, label=f'Expected, $\\\\alpha$={round(a,3)}, $\\\\beta$={round(b,3)}')\nplt.xlabel('$\\phi$')\nplt.ylabel('Expectation')\nplt.legend()\nplt.show()\n```\n\n\n```python\nz00\n```\n\n\n\n\n    cirq.PauliSum(cirq.LinearDict({frozenset({(cirq.GridQubit(0, 1), cirq.Z), (cirq.GridQubit(0, 0), cirq.Z)}): (0.25+0j), frozenset({(cirq.GridQubit(0, 0), cirq.Z)}): (0.25+0j), frozenset({(cirq.GridQubit(0, 1), cirq.Z)}): (0.25+0j), frozenset(): (0.25+0j)}))\n\n\n\n\n```python\nz00.expectation_from_state_vector(result.final_state_vector, {q0:0, q1:1})\n```\n\n\n\n\n    (0.130918700248003+0j)\n\n\n\n\n```python\nresult.final_state_vector\n```\n\n\n\n\n    array([ 0.25667757+0.25502023j, -0.39576927-0.2607826j ,\n           -0.33476508+0.24268252j, -0.50486577+0.4675345j ], dtype=complex64)\n\n\n\n### Decomposing the circuit\n\n\n```python\n# Input qubits with rotations by the angle \\phi\ninput_circuit = cirq.Circuit([\n                cirq.rx(phi)(q0),\n                cirq.ry(-2*phi)(q1)\n                ])\ninput_circuit\n```\n\n\n\n\n<pre style=\"overflow: auto; white-space: pre;\">(0, 0): \u2500\u2500\u2500Rx(phi)\u2500\u2500\u2500\u2500\u2500\u2500\n\n(0, 1): \u2500\u2500\u2500Ry(-2*phi)\u2500\u2500\u2500</pre>\n\n\n\n\n```python\n# The circuit that is going to be my model\n# a.k.a given some inputs (rotated qubits) these will be entangled and\n# rotated by fixed values that we want to learn\nmodel_circuit = cirq.Circuit([\n                cirq.H(q0),\n                cirq.CNOT(q0,q1),\n                cirq.rx(alpha)(q0),\n                cirq.ry(beta)(q1),\n              ])\nmodel_circuit\n```\n\n\n\n\n<pre style=\"overflow: auto; white-space: pre;\">(0, 0): \u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500Rx(alpha)\u2500\u2500\u2500\n               \u2502\n(0, 1): \u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500Ry(beta)\u2500\u2500\u2500\u2500</pre>\n\n\n\n\n```python\n# building a keras model\n# the input is the input_circuit \n# Parameterized Quantum Circuit - PQC\n# the PQC outputs the expectation to be in state |00> from the model circuit, given the input circuit\nmodel = tf.keras.Sequential([\n    tf.keras.layers.Input(shape=(), dtype=tf.string),\n    tfq.layers.PQC(model_circuit, z00),\n])\n```\n\n\n```python\nmodel.summary()\n```\n\n    Model: \"sequential\"\n    _________________________________________________________________\n    Layer (type)                 Output Shape              Param #   \n    =================================================================\n    pqc (PQC)                    (None, 1)                 2         \n    =================================================================\n    Total params: 2\n    Trainable params: 2\n    Non-trainable params: 0\n    _________________________________________________________________\n\n\n\n```python\nmodel.trainable_variables\n```\n\n\n\n\n    [<tf.Variable 'parameters:0' shape=(2,) dtype=float32, numpy=array([4.175567 , 2.7709274], dtype=float32)>]\n\n\n\n\n```python\n# convert the input circuits (one circuit per value of phi) into tensors\n# generate a series of input circuits, with different x values (values of phi)\ninput_circuits =  tfq.convert_to_tensor([cirq.resolve_parameters(input_circuit, cirq.ParamResolver({'phi': x}))] for x in x_values)\nprint(input_circuits[:3])\n```\n\n    tf.Tensor(\n    [[b'\\n\\x0e\\n\\x0ctfq_gate_set\\x12\\x99\\x02\\x08\\x01\\x12\\x94\\x02\\n\\x87\\x01\\n\\x04\\n\\x02XP\\x12\\x16\\n\\x0econtrol_qubits\\x12\\x04\\n\\x02\\x1a\\x00\\x12\\x13\\n\\x08exponent\\x12\\x07\\n\\x05\\r\\xe1\\xb7\\xcb\\xbf\\x12\\x17\\n\\x0cglobal_shift\\x12\\x07\\n\\x05\\r\\x00\\x00\\x00\\xbf\\x12\\x16\\n\\x0econtrol_values\\x12\\x04\\n\\x02\\x1a\\x00\\x12\\x1a\\n\\x0fexponent_scalar\\x12\\x07\\n\\x05\\r\\x00\\x00\\x80?\\x1a\\x05\\x12\\x030_0\\n\\x87\\x01\\n\\x04\\n\\x02YP\\x12\\x16\\n\\x0econtrol_qubits\\x12\\x04\\n\\x02\\x1a\\x00\\x12\\x17\\n\\x0cglobal_shift\\x12\\x07\\n\\x05\\r\\x00\\x00\\x00\\xbf\\x12\\x16\\n\\x0econtrol_values\\x12\\x04\\n\\x02\\x1a\\x00\\x12\\x13\\n\\x08exponent\\x12\\x07\\n\\x05\\r\\xe5\\xb7K@\\x12\\x1a\\n\\x0fexponent_scalar\\x12\\x07\\n\\x05\\r\\x00\\x00\\x80?\\x1a\\x05\\x12\\x030_1']\n     [b'\\n\\x0e\\n\\x0ctfq_gate_set\\x12\\x99\\x02\\x08\\x01\\x12\\x94\\x02\\n\\x87\\x01\\n\\x04\\n\\x02XP\\x12\\x1a\\n\\x0fexponent_scalar\\x12\\x07\\n\\x05\\r\\x00\\x00\\x80?\\x12\\x16\\n\\x0econtrol_values\\x12\\x04\\n\\x02\\x1a\\x00\\x12\\x13\\n\\x08exponent\\x12\\x07\\n\\x05\\r`\\xae\\xc9\\xbf\\x12\\x17\\n\\x0cglobal_shift\\x12\\x07\\n\\x05\\r\\x00\\x00\\x00\\xbf\\x12\\x16\\n\\x0econtrol_qubits\\x12\\x04\\n\\x02\\x1a\\x00\\x1a\\x05\\x12\\x030_0\\n\\x87\\x01\\n\\x04\\n\\x02YP\\x12\\x13\\n\\x08exponent\\x12\\x07\\n\\x05\\r`\\xaeI@\\x12\\x17\\n\\x0cglobal_shift\\x12\\x07\\n\\x05\\r\\x00\\x00\\x00\\xbf\\x12\\x1a\\n\\x0fexponent_scalar\\x12\\x07\\n\\x05\\r\\x00\\x00\\x80?\\x12\\x16\\n\\x0econtrol_qubits\\x12\\x04\\n\\x02\\x1a\\x00\\x12\\x16\\n\\x0econtrol_values\\x12\\x04\\n\\x02\\x1a\\x00\\x1a\\x05\\x12\\x030_1']\n     [b'\\n\\x0e\\n\\x0ctfq_gate_set\\x12\\x99\\x02\\x08\\x01\\x12\\x94\\x02\\n\\x87\\x01\\n\\x04\\n\\x02XP\\x12\\x13\\n\\x08exponent\\x12\\x07\\n\\x05\\r\\xd7\\xa4\\xc7\\xbf\\x12\\x17\\n\\x0cglobal_shift\\x12\\x07\\n\\x05\\r\\x00\\x00\\x00\\xbf\\x12\\x16\\n\\x0econtrol_qubits\\x12\\x04\\n\\x02\\x1a\\x00\\x12\\x16\\n\\x0econtrol_values\\x12\\x04\\n\\x02\\x1a\\x00\\x12\\x1a\\n\\x0fexponent_scalar\\x12\\x07\\n\\x05\\r\\x00\\x00\\x80?\\x1a\\x05\\x12\\x030_0\\n\\x87\\x01\\n\\x04\\n\\x02YP\\x12\\x13\\n\\x08exponent\\x12\\x07\\n\\x05\\r\\xdb\\xa4G@\\x12\\x17\\n\\x0cglobal_shift\\x12\\x07\\n\\x05\\r\\x00\\x00\\x00\\xbf\\x12\\x16\\n\\x0econtrol_values\\x12\\x04\\n\\x02\\x1a\\x00\\x12\\x16\\n\\x0econtrol_qubits\\x12\\x04\\n\\x02\\x1a\\x00\\x12\\x1a\\n\\x0fexponent_scalar\\x12\\x07\\n\\x05\\r\\x00\\x00\\x80?\\x1a\\x05\\x12\\x030_1']], shape=(3, 1), dtype=string)\n\n\n\n```python\nx_values[:5]\n```\n\n\n\n\n    array([-5.  , -4.95, -4.9 , -4.85, -4.8 ])\n\n\n\n\n```python\nlen(x_values)\n```\n\n\n\n\n    200\n\n\n\n\n```python\ninput_circuits.shape\n```\n\n\n\n\n    TensorShape([200, 1])\n\n\n\n\n```python\n# test the model with randomly initialised values of alpha and beta given the input circuits\ny_test = model([input_circuits]).numpy()\n\n# plot how a randomly initiated model compares with the expected\nplt.plot(x_values, y_expectations, lw=4, label=f'Expected, $\\\\alpha$={round(a,3)}, $\\\\beta$={round(b,3)}')\nplt.plot(x_values, y_test,'ro', label='NN output')\nplt.xlabel('$\\phi$')\nplt.ylabel('Expectation')\nplt.legend()\nplt.show()\n```\n\n\n```python\n# compile the model, using a basic Adam optimizer and MSE loss\noptimizer = tf.keras.optimizers.Adam(learning_rate=0.01)\nloss = tf.keras.losses.MeanSquaredError()\nmodel.compile(optimizer=optimizer, loss=loss)\nmodel.summary()\n```\n\n    Model: \"sequential\"\n    _________________________________________________________________\n    Layer (type)                 Output Shape              Param #   \n    =================================================================\n    pqc (PQC)                    (None, 1)                 2         \n    =================================================================\n    Total params: 2\n    Trainable params: 2\n    Non-trainable params: 0\n    _________________________________________________________________\n\n\n\n```python\n# model can be fitted given now the y_expected from the original expectations\n# (this could easily be the original 'measurements' distribution instead)\ny_expected = np.array(y_expectations)\nhistory = model.fit(input_circuits, y_expected,\n                    epochs=25, verbose=1)\ntype(history)\n```\n\n    Epoch 1/25\n    7/7 [==============================] - 1s 8ms/step - loss: 0.0769\n    Epoch 2/25\n    7/7 [==============================] - 0s 11ms/step - loss: 0.0806\n    Epoch 3/25\n    7/7 [==============================] - 0s 10ms/step - loss: 0.0692\n    Epoch 4/25\n    7/7 [==============================] - 0s 9ms/step - loss: 0.0669\n    Epoch 5/25\n    7/7 [==============================] - 0s 9ms/step - loss: 0.0639\n    Epoch 6/25\n    7/7 [==============================] - 0s 9ms/step - loss: 0.0704\n    Epoch 7/25\n    7/7 [==============================] - 0s 11ms/step - loss: 0.0614\n    Epoch 8/25\n    7/7 [==============================] - 0s 9ms/step - loss: 0.0598\n    Epoch 9/25\n    7/7 [==============================] - 0s 9ms/step - loss: 0.0514\n    Epoch 10/25\n    7/7 [==============================] - 0s 10ms/step - loss: 0.0474\n    Epoch 11/25\n    7/7 [==============================] - 0s 10ms/step - loss: 0.0453\n    Epoch 12/25\n    7/7 [==============================] - 0s 10ms/step - loss: 0.0400\n    Epoch 13/25\n    7/7 [==============================] - 0s 9ms/step - loss: 0.0328\n    Epoch 14/25\n    7/7 [==============================] - 0s 9ms/step - loss: 0.0248\n    Epoch 15/25\n    7/7 [==============================] - 0s 11ms/step - loss: 0.0200\n    Epoch 16/25\n    7/7 [==============================] - 0s 9ms/step - loss: 0.0142\n    Epoch 17/25\n    7/7 [==============================] - 0s 9ms/step - loss: 0.0107\n    Epoch 18/25\n    7/7 [==============================] - 0s 11ms/step - loss: 0.0065\n    Epoch 19/25\n    7/7 [==============================] - 0s 11ms/step - loss: 0.0049\n    Epoch 20/25\n    7/7 [==============================] - 0s 9ms/step - loss: 0.0032\n    Epoch 21/25\n    7/7 [==============================] - 0s 9ms/step - loss: 0.0023\n    Epoch 22/25\n    7/7 [==============================] - 0s 9ms/step - loss: 0.0017\n    Epoch 23/25\n    7/7 [==============================] - 0s 9ms/step - loss: 0.0013\n    Epoch 24/25\n    7/7 [==============================] - 0s 10ms/step - loss: 0.0010\n    Epoch 25/25\n    7/7 [==============================] - 0s 9ms/step - loss: 7.4552e-04\n\n\n\n\n\n    tensorflow.python.keras.callbacks.History\n\n\n\n\n```python\nhistory.params\n```\n\n\n\n\n    {'epochs': 25, 'steps': 7, 'verbose': 1}\n\n\n\n\n```python\n# test the model \ny_test = model([input_circuits]).numpy()\n\n# plot how a randomly initiated model compares with the expected\nplt.plot(x_values, y_expected, lw=4, label=f'Expected, $\\\\alpha$={round(a,3)}, $\\\\beta$={round(b,3)}')\nplt.plot(x_values, y_test,'ro', label='NN output')\nplt.xlabel('$\\phi$')\nplt.ylabel('Expectation')\nplt.legend()\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "ebb5a3403694ebac6c02480ba375b9fb984c9211", "size": 135697, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Notebooks/QML/003-Cirq-Quantum_Hybrid_Model_Training_1.ipynb", "max_stars_repo_name": "praveentn/ml-repos", "max_stars_repo_head_hexsha": "066bddf1393bef2704d64eadf72947e44f406139", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-07-20T17:33:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-02T03:25:54.000Z", "max_issues_repo_path": "Notebooks/QML/003-Cirq-Quantum_Hybrid_Model_Training_1.ipynb", "max_issues_repo_name": "praveentn/ml-repos", "max_issues_repo_head_hexsha": "066bddf1393bef2704d64eadf72947e44f406139", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Notebooks/QML/003-Cirq-Quantum_Hybrid_Model_Training_1.ipynb", "max_forks_repo_name": "praveentn/ml-repos", "max_forks_repo_head_hexsha": "066bddf1393bef2704d64eadf72947e44f406139", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 88.0577547047, "max_line_length": 30510, "alphanum_fraction": 0.708770275, "converted": true, "num_tokens": 9533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.07369626258544089, "lm_q1q2_score": 0.03454811711744104}}
{"text": " #### Quantum Machine Learning: Uma Introdu\u00e7\u00e3o\n\n##### Quantum Computing for All! (A Poetic Introduction)\n\nDear coleagues, it's been a while since I started reading about Quantum Computing. In the mean time, I have also developed some courses on what is called now Machine Learning. Ten, fifteen years ago Machine Learning was called Statistics. Then, the CSVs files started becoming huge, with millions of rows and hundreds, thousands of columns. Statistics became Big Data. \n\nSome statistics rules for selecting which column (variable) to use, like p-value became difficult to be explained to customers, specially executives, which need something that can be quickly learned, easily remembered and  effortlessly applied on a daily basis. \n\nP-value also started giving strange answers when used in these colossal tables (after all, if 5% of your data is a 100.000 rows with 100 columns, who knows what will appear in this subset of your data???). \n\nIt was at this moment that somebody \"remembered\" that p-values had been developed originally with way much more simpler tables, tables in which you were forced to use all the rows and columns in the development of your model. In this context p-values were a way of estimating the other data that was \"out there\". But with tables made of millions of rows you could just separate 500.000 of them to be the \"world out there\", use the 4.500.000 to develop (train) your model and afterwards see (\"test\") what would happen in the real world when your model was put to work. Statistics that had became Big Data was now renamed also to Machine Learning.\n\nThe algorithms were still being used to model simple phenomena. Phenomena that could be described with straight lines. Science, the scientific revolution started 500 years ago when a group of geniuses tried to apply simple rules to simple phenomena. It worked for quite a while (astonishing well), but the rule was always: simple phenomena that can be described preferably with straight lines, at most with a parabola. \n\nThe world is incredibly complex, but nonetheless our minds are capable of dealing with all kinds of phenomena, be they describable by straight lines or not. And then somebody tried to apply a method of finding non linear patterns in the data called neural networks. Statistics, now mingled with computer science became Deep Learning.\n\nBut all this has a cost. The cost of dealing with millions of rows, thousands of columns, to train, validade and test our models. And this cost is paid in the most precious commoditty that a human being can spend: TIME! Our computers are becoming overwhelmed by this combination of Big Data, Machine Learning and Deep Learning that has accomplished a lot of things but needs an ever increasing ammount of data to be processed.\n\nIt was then that another technology appeared. A technology that is still in its infancy, but is promising us with a future when computers will be able to digest an unthinkable ammount of data in a matter of seconds, process it and tell us where the results are. This technology is called Quantum Computing.\n\nWhat is Quantum Computing and how it can be used in the Machine Learning way of finding the utmost complex patterns in mountains of data is the purpose of a field now called Quantum Machine Learning.\n\nThis field blends together two of my mostly cherished areas of study: Computing and Physics (and of course, the possibility of making some money along the line, after all, bills doesn't stop arriving each month for us to have them paid...). And this group of Jupyter Notebooks is my attempt to make this area of study better know by as many people as possible. \n\nQuantum Machine Learning. This is the Holly Grail of my knowledge dreams. Understand this dream, make it available to others, is the objective of this and other Jupyter Notebooks that I will try writing in the near future.\n\nIn this journey, Python will be our driver, and Qiskit our compass. The destiny: translating to the world of Quantum Computing the Machine Learning algorithms that have made us devise a future with Intelligent Machines at our disposal.\n\nHope you enjoy the ride. It will be bumpy, sometimes frustating, but if we keep our focus and always remember why we are here, I promise you that there will be a pot of gold at the end of the rainbow waiting for us. \n\nHappy Journey! And Let Quantum Machine Learning BE!\n\n##### Python setup\n\nThree libraries will be heavily used in this course: `pandas`, `scikit-learn` and `qiskit`. It is also interesting to import support libraries `numpy` and `matplotlib` object plotting library `pyplot`. The qiskit library and visualization tools need to be installed from `pip` each time the jupyter notebook is runned in Google Colab. The option `-q` installs qiskit silently.\n\n\n```python\n!pip install qiskit -q\n!pip install qiskit[visualization] -q\n\nimport numpy as np\nnp.set_printoptions(precision=3, suppress=True)\nfrom matplotlib import pyplot as plt\n%matplotlib inline\n\nimport pandas as pd\nimport sklearn as sk\nimport qiskit as qk\n```\n\n##### Python (very) Short Review\n\nIn the cell below there's a very short summary of what is needed to be remembered from Python: `numpy` arrays and basic `matplotlib` plots.\n\n\n```python\nimport numpy as np\nfrom matplotlib import pyplot as plt\nx = np.linspace(0, 2*np.pi, 1000)\ny1 = np.sin(x)\ny2 = np.cos(x)\n\nfig, ax = plt.subplots(nrows=1, ncols=2)\nax[0].scatter(x=x, y=y1)\nax[0].scatter(x=x, y=y2)\nax[0].set_title(\"Gr\u00e1fico 1\")\nax[1].plot(x,y1)\nax[1].plot(x,y2)\nax[1].set_title(\"Gr\u00e1fico 2\")\nplt.tight_layout();\n```\n\n##### \u00c1lgebra Linear com Numpy e Sympy\n\nPara trabalhar com Data Science \u00e9 essencial uma boa no\u00e7\u00e3o de \u00c1lgebra Linear incluindo o uso de n\u00fameros complexos. A seguir s\u00e3o resolvidos exerc\u00edcios envolvendo o uso de matrizes e n\u00fameros complexos, tanto de forma puramente num\u00e9rica (pelo uso da `numpy`) quanto de forma simb\u00f3lica (pelo uso da `sympy`). Os exerc\u00edcios foram retirados de **QCE**: Quantum Computing Explained, David Mcmahon e **CSE**: Computer Science and Engineering, Gilbert Strang.\n\n###### Produto Matricial\n\n**Ex.:** Calcule o produto matricial $X.T$ e $T.X$ das matrizes X e T\n\n\n```python\nimport sympy as sp\nX = sp.Matrix([[0,1],[1,0]])\nT = sp.Matrix([[1,1],[1,-1]])\nX*T, T*X\n```\n\n\n\n\n\n\n\n\n$$\\left ( \\left[\\begin{matrix}1 & -1\\\\1 & 1\\end{matrix}\\right], \\quad \\left[\\begin{matrix}1 & 1\\\\-1 & 1\\end{matrix}\\right]\\right )$$\n\n\n\n###### Matriz Sim\u00e9trica\n\n**Ex.:** Uma matriz \u00e9 considerada sim\u00e9trica quando ela for igual a sua transposta. Prove que a matriz \n$$ K_4 = \n\\begin{bmatrix} 2 & -1 & 0 & 0 \\\\ \n          -1 & 2 & -1 & 0 \\\\ \n           0 & -1 & 2 & -1 \\\\ \n           0 & 0 & -1 & 2 \n\\end{bmatrix}$$ \u00e9 uma matriz sim\u00e9trica.\n\n\n```python\nimport numpy as np\n```\n\n\n```python\nK4 = np.array([[2,-1,0,0],[-1,2,-1,0],[0,-1,2,-1],[0,0,-1,2]])\nK4\n```\n\n\n\n\n    array([[ 2, -1,  0,  0],\n           [-1,  2, -1,  0],\n           [ 0, -1,  2, -1],\n           [ 0,  0, -1,  2]])\n\n\n\n\n```python\n(K4 == K4.T).all()\n```\n\n\n\n\n    True\n\n\n\n\n```python\nimport sympy as sp\nfrom IPython.display import Math\n```\n\n\n```python\nK4 = sp.Matrix([[2,-1,0,0],[-1,2,-1,0],[0,-1,2,-1],[0,0,-1,2]])\nMath(\"K_4 = \" + sp.latex(K4) + \" , \" + \"{K_4}^T = \" + sp.latex(K4.transpose()))\n```\n\n\n\n\n$$K_4 = \\left[\\begin{matrix}2 & -1 & 0 & 0\\\\-1 & 2 & -1 & 0\\\\0 & -1 & 2 & -1\\\\0 & 0 & -1 & 2\\end{matrix}\\right] , {K_4}^T = \\left[\\begin{matrix}2 & -1 & 0 & 0\\\\-1 & 2 & -1 & 0\\\\0 & -1 & 2 & -1\\\\0 & 0 & -1 & 2\\end{matrix}\\right]$$\n\n\n\n\n```python\nK4 == K4.transpose()\n```\n\n\n\n\n    True\n\n\n\n###### Matriz Inversa\n\n**Ex.:** Calcule a matriz inversa da matriz T3 (abaixo)\n\n\n```python\nimport numpy as np\nT3 = np.array([[3,2,2],[2,2,1],[1,1,1]])\nT3\n```\n\n\n\n\n    array([[3, 2, 2],\n           [2, 2, 1],\n           [1, 1, 1]])\n\n\n\n\n```python\nnp.linalg.inv(T3)\n```\n\n\n\n\n    array([[ 1.,  0., -2.],\n           [-1.,  1.,  1.],\n           [ 0., -1.,  2.]])\n\n\n\n\n```python\nimport sympy as sp\nT3sp = sp.Matrix(T3)\nMath(\"T_3 = \" + sp.latex(T3sp) + \" , \\\\ \\\\ \" + \\\n     \"{T_3}^{-1} = \" + sp.latex(T3sp.inv()))\n```\n\n\n\n\n$$T_3 = \\left[\\begin{matrix}3 & 2 & 2\\\\2 & 2 & 1\\\\1 & 1 & 1\\end{matrix}\\right] , \\ \\ {T_3}^{-1} = \\left[\\begin{matrix}1 & 0 & -2\\\\-1 & 1 & 1\\\\0 & -1 & 2\\end{matrix}\\right]$$\n\n\n\n###### Matrizes Especiais K1, K2, K3, K4 (CSE)\n\n**Ex.:** Prove que as matrizes K apresentadas abaixo s\u00e3o sim\u00e9tricas para $K_1$, $K_2$, $K_3$ e $K_4$\n\n\n```python\nimport numpy as np\n```\n\n\n```python\nK1 = np.array([[2]])\nK2 = np.array([[2,-1],[-1,2]])\nK3 = np.array([[2,-1,0],[-1,2,-1],[0,-1,2]])\nK4 = np.array([[2,-1,0,0],[-1,2,-1,0],[0,-1,2,-1],[0,0,-1,2]])\nK4\n```\n\n\n\n\n    array([[ 2, -1,  0,  0],\n           [-1,  2, -1,  0],\n           [ 0, -1,  2, -1],\n           [ 0,  0, -1,  2]])\n\n\n\n\n```python\nK1 - K1.T\n```\n\n\n\n\n    array([[0]])\n\n\n\n\n```python\nK2 - K2.T\n```\n\n\n\n\n    array([[0, 0],\n           [0, 0]])\n\n\n\n\n```python\nK3 - K3.T\n```\n\n\n\n\n    array([[0, 0, 0],\n           [0, 0, 0],\n           [0, 0, 0]])\n\n\n\n\n```python\nK4 - K4.T\n```\n\n\n\n\n    array([[0, 0, 0, 0],\n           [0, 0, 0, 0],\n           [0, 0, 0, 0],\n           [0, 0, 0, 0]])\n\n\n\n\n```python\nT3_inv = np.array([[3,2,2],[2,2,1],[1,1,1]])\nT3_inv\n```\n\n\n\n\n    array([[3, 2, 2],\n           [2, 2, 1],\n           [1, 1, 1]])\n\n\n\n\n```python\nnp.linalg.inv(T3_inv)\n```\n\n\n\n\n    array([[ 1.,  0., -2.],\n           [-1.,  1.,  1.],\n           [ 0., -1.,  2.]])\n\n\n\n###### Espa\u00e7os Vetoriais\n\n**Ex.:** De um exemplo onde a combina\u00e7\u00e3o linear de tr\u00eas vetores n\u00e3o nulos do $R^4$ produza o vetor nulo. Confirme o resultado criando com estes tr\u00eas vetores uma matriz A e multiplicando a mesma por um vetor x apropriado para gerar o vetor nulo. Indique tamb\u00e9m as dimens\u00f5es de A, x e do vetor nulo.\n\n\n```python\nfrom IPython.display import Math\nimport numpy as np\nimport sympy as sp\nx1 = np.array([1,1,1,1]).reshape(-1,1)\nx2 = np.array([2,3,4,5]).reshape(-1,1)\nx3 = np.array([3,4,5,6]).reshape(-1,1)\nA = np.concatenate([x1,x2,x3],axis=1)\nx = np.array([1,1,-1]).reshape(-1,1)\nR = A.dot(x)\nprint('A =', A.shape, ', x =', x.shape, ', R =', R.shape) \nexpr = sp.latex('A =') + sp.latex(sp.Matrix(A)) + sp.latex(\",\") + \\\n       sp.latex('x =') + sp.latex(sp.Matrix(x)) + sp.latex(\",\") + \\\n       sp.latex('R =') + sp.latex(sp.Matrix(R))\nMath(expr)\n```\n\n    A = (4, 3) , x = (3, 1) , R = (4, 1)\n\n\n\n\n\n$$\\mathtt{\\text{A =}}\\left[\\begin{matrix}1 & 2 & 3\\\\1 & 3 & 4\\\\1 & 4 & 5\\\\1 & 5 & 6\\end{matrix}\\right]\\mathtt{\\text{,}}\\mathtt{\\text{x =}}\\left[\\begin{matrix}1\\\\1\\\\-1\\end{matrix}\\right]\\mathtt{\\text{,}}\\mathtt{\\text{R =}}\\left[\\begin{matrix}0\\\\0\\\\0\\\\0\\end{matrix}\\right]$$\n\n\n\n**Ex.:** Suponha uma matriz com vetores no $R^{4}$ onde existam duas colunas em que cada uma seja combina\u00e7\u00e3o linear de outras duas colunas. Com base nesta afirma\u00e7\u00e3o encontre duas solu\u00e7\u00f5es distintas x e y para Az=0 (isto \u00e9 vetores x e y tais que Ax=0 e Ay=0)\n\n\n```python\nx1 = np.array([1, 2, 3, 4]).reshape(-1,1)\nx2 = np.array([2, 3, 5, 1]).reshape(-1,1)\nx3 = np.array([3, 5, 8, 5]).reshape(-1,1)\nx4 = np.array([1, 1, 2,-3]).reshape(-1,1)\n\nA = np.concatenate([x1,x2,x3,x4], axis=1)\nx = np.array([1,1,-1,0]).reshape(-1,1)\nAx = A.dot(x)\n\ny = np.array([1,-1,0,1]).reshape(-1,1)\nAy = A.dot(y)\n\nexpr = \"A =\" + sp.latex(sp.Matrix(A)) + \",\" + \\\n       \"x =\" + sp.latex(sp.Matrix(x)) + \",\" + \"A.x =\" + sp.latex(sp.Matrix(Ax)) + \",\" + \\\n       \"y =\" + sp.latex(sp.Matrix(y)) + \",\" + \"A.y =\" + sp.latex(sp.Matrix(Ay))\nmview(expr)\n```\n\n\n\n\n\n\n\n\n$$A =\\left[\\begin{matrix}1 & 2 & 3 & 1\\\\2 & 3 & 5 & 1\\\\3 & 5 & 8 & 2\\\\4 & 1 & 5 & -3\\end{matrix}\\right],x =\\left[\\begin{matrix}1\\\\1\\\\-1\\\\0\\end{matrix}\\right],A.x =\\left[\\begin{matrix}0\\\\0\\\\0\\\\0\\end{matrix}\\right],y =\\left[\\begin{matrix}1\\\\-1\\\\0\\\\1\\end{matrix}\\right],A.y =\\left[\\begin{matrix}0\\\\0\\\\0\\\\0\\end{matrix}\\right]$$\n\n\n\n**Ex.:** Suponha uma matriz de uns (3x3). Encontre dois vetores independentes que sejam solu\u00e7\u00e3o de Az=0. Existe um 3o vetor independente? N\u00e3o! O espa\u00e7o das colunas de A tem dimens\u00e3o 1. A dimens\u00e3o de A \u00e9 3. Logo o espa\u00e7o nulo de A tem dimens\u00e3o 2. Tendo dimens\u00e3o 2 temos apenas dois vetores independentes que podem ser solu\u00e7\u00e3o de A.z = 0.\n\n\n```python\nimport numpy as np\nA = np.ones([3,3]).astype('int32')\nx = np.array([1,-1,0]).reshape(-1,1)\nAx = A.dot(x)\ny = np.array([1,0,-1]).reshape(-1,1)\nAy = A.dot(y)\n\nexpr = \"A =\" + sp.latex(sp.Matrix(A)) + \" ,\" + \\\n       \"x =\" + sp.latex(sp.Matrix(x)) + \" ,\" + \" A.x =\" + sp.latex(sp.Matrix(Ax)) + \\\n       \"y =\" + sp.latex(sp.Matrix(y)) + \" ,\" + \" A.y =\" + sp.latex(sp.Matrix(Ay))\nmview(expr)\n```\n\n\n\n\n\n\n\n\n$$A =\\left[\\begin{matrix}1 & 1 & 1\\\\1 & 1 & 1\\\\1 & 1 & 1\\end{matrix}\\right] ,x =\\left[\\begin{matrix}1\\\\-1\\\\0\\end{matrix}\\right] , A.x =\\left[\\begin{matrix}0\\\\0\\\\0\\end{matrix}\\right]y =\\left[\\begin{matrix}1\\\\0\\\\-1\\end{matrix}\\right] , A.y =\\left[\\begin{matrix}0\\\\0\\\\0\\end{matrix}\\right]$$\n\n\n\n**Ex.:** Os vetores $v = (1,1,0)$ e $w = (0,1,1)$ formam um plano no $R^3$. Encontre um vetor z perpendicular a este plano. Solu\u00e7\u00e3o: se este vetor for chamado de $z$ teremos $(c\\vec{v}+d\\vec{w}).z=0$. Logo $c = -z_1$, $d = -z_3$ e $c+d=-z_2$. Logo o vetor z perpendicular ao plano formado por $v$ e $w$ ter\u00e1 o formato $z_1 + z_3 = z_2$. Um exemplo seria $z = (1,2,1)$\n\n\n```python\nimport numpy as np\nT4 = np.array([[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,1]]).astype('int32')\nT4_inv = np.linalg.inv(T4).astype('int32')\nexpr = sp.latex('T_4 =') + sp.latex(sp.Matrix(T4)) + \" , \" + sp.latex(\"{T_4}^{-1} =\") + sp.latex(sp.Matrix(T4_inv)) \nmview(expr)\n```\n\n\n\n\n\n\n\n\n$$T_4 =\\left[\\begin{matrix}4 & 3 & 2 & 1\\\\3 & 3 & 2 & 1\\\\2 & 2 & 2 & 1\\\\1 & 1 & 1 & 1\\end{matrix}\\right] , {T_4}^{-1} =\\left[\\begin{matrix}1 & -1 & 0 & 0\\\\-1 & 2 & -1 & 0\\\\0 & 0 & 2 & -1\\\\0 & 0 & -1 & 2\\end{matrix}\\right]$$\n\n\n\n###### Pot\u00eancias de $i$\n\n**Ex.:** Calcule $\\sqrt{-1}$, $i^3$ e $i^{15}$\n\n\n```python\nimport numpy as np\nnp.sqrt(-1+0j), (1j)**3, (1j)**15\n```\n\n\n\n\n    (1j, (-0-1j), (-0-1j))\n\n\n\n\n```python\nfrom IPython.display import Math\nimport sympy as sp\nMath(\"\\sqrt{-1} = \" + sp.latex(sp.sqrt(-1)) + \" , \\\\ \\\\ \" + \n     \"i^{3} = \" + sp.latex(sp.I**3) + \" , \\\\ \\\\ \" + \n     \"i^{15} = \" + sp.latex(sp.I**15))\n```\n\n\n\n\n$$\\sqrt{-1} = i , \\ \\ i^{3} = - i , \\ \\ i^{15} = - i$$\n\n\n\n###### Forma retangular e polar de um n\u00famero complexo\n\n**Ex.:** Dado $c=3+4j$ apresente a parte real, imagin\u00e1ria, o conjugado, m\u00f3dulo e \u00e2ngulo do mesmo.\n\n\n\n\n```python\nimport numpy as np\nc = 3+4j\nc, c.real, c.imag, c.conjugate(), np.abs(c), np.angle(c)\n```\n\n\n\n\n    ((3+4j), 3.0, 4.0, (3-4j), 5.0, 0.9272952180016122)\n\n\n\n\n```python\nimport sympy as sp\nc = sp.symbols(\"c\")\nc = 3 + 4*sp.I\ndisplay(Math(\"c = \" + sp.latex(c)))\ndisplay(Math(sp.latex(\"Parte Real de \") + \"c = \" + sp.latex(sp.re(c))))\ndisplay(Math(sp.latex(\"Parte Imagin\u00e1ria de \") + \"c = \" + sp.latex(sp.im(c))))\ndisplay(Math(\"c^* = \" + sp.latex(sp.conjugate(c))))\ndisplay(Math(\"|c| = \" + sp.latex(sp.Abs(c))))\ndisplay(Math(\"\\\\theta = \" + sp.latex(sp.arg(c))))\n```\n\n\n$$c = 3 + 4 i$$\n\n\n\n$$\\mathtt{\\text{Parte Real de }}c = 3$$\n\n\n\n$$\\mathtt{\\text{Parte Imagin\u00e1ria de }}c = 4$$\n\n\n\n$$c^* = 3 - 4 i$$\n\n\n\n$$|c| = 5$$\n\n\n\n$$\\theta = \\operatorname{atan}{\\left(\\frac{4}{3} \\right)}$$\n\n\n###### Ra\u00edzes de um n\u00famero complexo\n\n**Ex.:** Encontre as raizes c\u00fabicas de $c=(1+j)$\n\nAs ra\u00edzes c\u00fabicas de $-1+j$ podem ser expressas como a solu\u00e7\u00e3o da equa\u00e7\u00e3o:\n\n\n```python\ndisplay(Math(\"x^3 = 1 + j\"))\ndisplay(Math(\"x^3 - (1+j) = 0\"))\ndisplay(Math(\"x^3 + 0.x^2 + 0.x - (1+j) = 0\"))\n```\n\n\n$$x^3 = 1 + j$$\n\n\n\n$$x^3 - (1+j) = 0$$\n\n\n\n$$x^3 + 0.x^2 + 0.x - (1+j) = 0$$\n\n\nEsta equa\u00e7\u00e3o pode ser resolvida via `numpy` atrav\u00e9s dos comandos abaixo:\n\n\n```python\nimport numpy as np\ncoef = [1,0,0,-(1+1j)]\nnp.roots(coef)\n```\n\n\n\n\n    array([-0.79370053+0.79370053j, -0.29051456-1.08421508j,\n            1.08421508+0.29051456j])\n\n\n\nE atrav\u00e9s da `sympy` via os comandos a seguir:\n\n\n```python\nimport sympy as sp\nx = sp.symbols(\"x\")\nsols = sp.solve(x**3 - (1+sp.I),x)\nsols = list(map(sp.simplify, sols))\nMath(\"x = \" + sp.latex(sols))\n```\n\n\n\n\n$$x = \\left[ \\frac{2^{\\frac{2}{3}} \\left(-1 + i\\right)}{2}, \\  \\frac{2^{\\frac{2}{3}} \\left(1 + i\\right) \\left(\\sqrt{3} - i\\right)}{4}, \\  - \\frac{2^{\\frac{2}{3}} \\left(1 + i\\right) \\left(\\sqrt{3} + i\\right)}{4}\\right]$$\n\n\n\n###### Autovalores, autovetores e tra\u00e7o de uma matriz quadrada\n\n**Ex.:** Calcule os autovalores, autovetores e o tra\u00e7o (soma dos autovalores) da matriz \n$$X = \n\\begin{bmatrix}\n0 & 1 \\\\\n1 & 0 \n\\end{bmatrix}$$\n\n\n\n\n```python\nimport numpy as np\nXnum = np.array([[0,1],[1,0]])\nXnum\n```\n\n\n\n\n    array([[0, 1],\n           [1, 0]])\n\n\n\n\n```python\nimport sympy as sp\nXsym = sp.symbols(\"X\")\nXsym = sp.Matrix([[0,1],[1,0]])\nMath(sp.latex(Xsym))\n```\n\n\n\n\n$$\\left[\\begin{matrix}0 & 1\\\\1 & 0\\end{matrix}\\right]$$\n\n\n\nNeste caso os autovalores s\u00e3o todos reais\n\n\n```python\nnp.linalg.eig(Xnum)[0]\n```\n\n\n\n\n    array([ 1., -1.])\n\n\n\nA `sympy` apresenta os autovalores no fomato : [autovalor, multiplicadade do mesmo]\n\n\n```python\nXsym.eigenvals()\n```\n\n\n\n\n    {-1: 1, 1: 1}\n\n\n\nObserve que a `numpy` apresenta os autovetores normalizados (com m\u00f3dulo igual a 1)\n\n\n```python\nnp.linalg.eig(Xnum)[1]\n```\n\n\n\n\n    array([[ 0.70710678, -0.70710678],\n           [ 0.70710678,  0.70710678]])\n\n\n\nA `sympy` apresenta os mesmos de forma mais elaborada. Primeiro o autovalor, depois a multiplicidade do mesmo e por \u00faltimo o autovetor associado, mas na forma mais simples poss\u00edvel, sem ser normalizado.\n\n\n```python\nMath(sp.latex(Xsym.eigenvects()))\n```\n\n\n\n\n$$\\left[ \\left( -1, \\  1, \\  \\left[ \\left[\\begin{matrix}-1\\\\1\\end{matrix}\\right]\\right]\\right), \\  \\left( 1, \\  1, \\  \\left[ \\left[\\begin{matrix}1\\\\1\\end{matrix}\\right]\\right]\\right)\\right]$$\n\n\n\nNo caso do tra\u00e7o, ambas as bibliotecas tem um m\u00e9todo similar.\n\n\n```python\nXnum.trace(), Xsym.trace()\n```\n\n\n\n\n    (0, 0)\n\n\n\n###### Sistemas de Equa\u00e7\u00f5es Lineares com coeficientes complexos\n\n**Ex.:** Dadas as matrizes $A = \\begin{bmatrix} 2 & i \\\\ 3 & 5i \\end{bmatrix}$ e $B = \\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$ resolva para $a$ e $b$ o sistema de equa\u00e7\u00f5es formado pela express\u00e3o $A.B - B.A = 0$\n\n\n```python\na,b,c,d = sp.symbols([\"a\",\"b\",\"c\",\"d\"])\nA = sp.Matrix([[2,sp.I],[3,5*sp.I]])\nB = sp.Matrix([[a,b],[c,d]])\ninstr = \"A = {0}, B = {1}\".format(sp.latex(A), sp.latex(B))\nMath(instr)\n```\n\n\n\n\n$$A = \\left[\\begin{matrix}2 & i\\\\3 & 5 i\\end{matrix}\\right], B = \\left[\\begin{matrix}a & b\\\\c & d\\end{matrix}\\right]$$\n\n\n\n\n```python\nR = A*B - B*A\nZ = sp.Matrix.zeros(2,2)\nEquacoes = [R[0,0], R[0,1], R[1,0], R[1,1]]\nres = sp.linsolve(Equacoes, a,b,c,d)\ninstr = \"R = A.B - B.A = {0} = {1}\".format(sp.latex(R), sp.latex(Z))\nMath(instr)\n```\n\n\n\n\n$$R = A.B - B.A = \\left[\\begin{matrix}- 3 b + i c & - i a + 2 b - 5 i b + i d\\\\3 a - 2 c + 5 i c - 3 d & 3 b - i c\\end{matrix}\\right] = \\left[\\begin{matrix}0 & 0\\\\0 & 0\\end{matrix}\\right]$$\n\n\n\n\n```python\ninstr = \"a = {0},\\\\\\ \\ \\\\\\ b = {1}\".format(sp.latex(res.args[0][0]), \n                                     sp.latex(res.args[0][1]))\nMath(instr)\n```\n\n\n\n\n$$a = c \\left(\\frac{2}{3} - \\frac{5 i}{3}\\right) + d,\\\\ \\ \\\\ b = \\frac{i c}{3}$$\n\n\n\n###### Propriedades do m\u00f3dulo de dois n\u00fameros complexos\n\n**Ex.:** Prove que, dados dois n\u00fameros complexos $c_1$ and $c_2$, $|c_1||c_2|=|c_1c_2|$.\n\n$$c_1 = a + bj , |c_1| = \\sqrt{a^2+b^2}$$\n$$ $$\n$$c_2 = c + dj , |c_2| = \\sqrt{c^2+d^2}$$\n$$ $$\n$$|c_1|*|c_2| = \\sqrt{{a^2c^2}+{b^2c^2}+{a^2d^2}+{b^2d^2}}$$\n$$ $$\n$$|c_1|*|c_2| = \\sqrt{{a^2c^2}-{2abcd}+{b^2d^2}+{b^2c^2}+{2abcd}+{a^2d^2}}$$\n$$ $$\n$$|c_1|*|c_2| = \\sqrt{(ac-bd)^2+(bc+ad)^2}$$\n$$ $$\n$$|c_1*c_2| = \\sqrt{(ac-bd)^2+(bc+ad)^2} $$\n$$Q.E.D.$$\n\n\n```python\nimport sympy as sp\nx, y, z, w = sp.symbols(\"x y z w\", real = True)\nc1, c2 = sp.symbols(\"c1 c2\", complex = True)\nc1 = x + y*sp.I\nc2 = z + w*sp.I\nsp.simplify( sp.Abs(c1*c2) - sp.Abs(c1)*sp.Abs(c2) ) == 0\n```\n\n\n\n\n    True\n\n\n\n**Ex.:** Prove que |c1 + c2| <= |c1| + |c2|\n\nA express\u00e3o dentro da raiz cont\u00e9m o termo $(wy)^2$. Isto torna a raiz pelo menos igual a $-wy$. Ela cont\u00e9m tamb\u00e9m $(xz)^2$. Isto torna a raiz pelo menos tamb\u00e9m igual a $-xz$. Sobram ainda os termos cruzados $(wx)^2$ e $(zy)^2$ dentro da raiz o que torna ela maior que $-(wy)-(xz)$, logo a express\u00e3o \u00e9 maior do que $0$ o que mostra que $|c1|+|c2| >= |c1+c2|$\n\n\n```python\nexpr1 = sp.Abs(c1+c2)**2\nexpr2 = (sp.Abs(c1)+sp.Abs(c2))**2\nMath(sp.latex(sp.simplify(expr2-expr1)/2))\n```\n\n\n\n\n$$- w y - x z + \\sqrt{w^{2} + z^{2}} \\sqrt{x^{2} + y^{2}}$$\n\n\n\n###### Produto Tensorial\n\n**Ex.:** Calcule o produto tensorial $a*c$ das matrizes a e c\n\n\n```python\na = sp.Matrix([[1],[2]])\nc = sp.Matrix([[3],[4]])\nfrom sympy.physics.quantum.tensorproduct import TensorProduct\nTensorProduct(a,c)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}3\\\\4\\\\6\\\\8\\end{matrix}\\right]$\n\n\n\n**Ex.:** Calcule o produto tensorial da matriz $a$ com a adjunta da matriz $c$\n\n\n```python\nimport sympy as sp\na = sp.Matrix([[1],[2]])\nc = sp.Matrix([[3],[4]])\nfrom sympy.physics.quantum.tensorproduct import TensorProduct\ndisplay(TensorProduct(a,c))\nprint()\ndisplay(TensorProduct(a.adjoint(),c.adjoint()))\n```\n\n\n$\\displaystyle \\left[\\begin{matrix}3\\\\4\\\\6\\\\8\\end{matrix}\\right]$\n\n\n    \n\n\n\n$\\displaystyle \\left[\\begin{matrix}3 & 4 & 6 & 8\\end{matrix}\\right]$\n\n\n**Ex.:** Calcule o produto tensorial $X*Y$ das matrizes X e Y\n\n\n```python\nimport sympy as sp\nfrom sympy.physics.quantum.tensorproduct import TensorProduct\nX = sp.Matrix([[0,1],[1,0]])\nY = sp.Matrix([[0,-sp.I],[sp.I,0]])\nTensorProduct(X,Y)\n```\n\n\n\n\n\n\n\n\n$$\\left[\\begin{matrix}0 & 0 & 0 & - i\\\\0 & 0 & i & 0\\\\0 & - i & 0 & 0\\\\i & 0 & 0 & 0\\end{matrix}\\right]$$\n\n\n\n###### Matrizes Unit\u00e1rias\n\n**Ex.:** Uma matriz quadrada composta de n\u00fameros complexos \u00e9 unit\u00e1ria se sua transposta conjugada ${U}^{*}$ \u00e9 tamb\u00e9m sua inversa. Prove que a matriz a seguir \u00e9 unit\u00e1ria\n\n\n```python\nimport numpy as np\nU = sp.Matrix([[1/sp.sqrt(2), 1/sp.sqrt(2),0],\n              [-sp.I/sp.sqrt(2),sp.I/sp.sqrt(2),0],\n              [0,0,sp.I]])\nUd = U.conjugate().transpose()\nexpr1 = sp.latex(U)\nexpr2 = sp.latex(Ud)\nexpr3 = sp.latex(U*Ud)\nexpr = expr1 + expr2 + expr3\nMath(expr)\n```\n\n\n\n\n$$\\left[\\begin{matrix}\\frac{\\sqrt{2}}{2} & \\frac{\\sqrt{2}}{2} & 0\\\\- \\frac{\\sqrt{2} i}{2} & \\frac{\\sqrt{2} i}{2} & 0\\\\0 & 0 & i\\end{matrix}\\right]\\left[\\begin{matrix}\\frac{\\sqrt{2}}{2} & \\frac{\\sqrt{2} i}{2} & 0\\\\\\frac{\\sqrt{2}}{2} & - \\frac{\\sqrt{2} i}{2} & 0\\\\0 & 0 & - i\\end{matrix}\\right]\\left[\\begin{matrix}1 & 0 & 0\\\\0 & 1 & 0\\\\0 & 0 & 1\\end{matrix}\\right]$$\n\n\n\n###### Hadamard Product de Duas Matrizes (Elemento a Elemento)\n\n**Ex.:** Calcule o produto elemento a elemento da matriz Theta\n\n\n```python\ntheta = sp.symbols(\"theta\")\nU = sp.Matrix([[sp.cos(theta), -sp.sin(theta), 0],\n               [sp.sin(theta),  sp.cos(theta), 0],\n               [            0,              0, 1]])\nMath(U)\n```\n\n\n\n\n\n\n\n\n$$\\left[\\begin{matrix}\\cos{\\left (\\theta \\right )} & - \\sin{\\left (\\theta \\right )} & 0\\\\\\sin{\\left (\\theta \\right )} & \\cos{\\left (\\theta \\right )} & 0\\\\0 & 0 & 1\\end{matrix}\\right]$$\n\n\n\n\n```python\nMath(U.multiply_elementwise(sp.conjugate(U)))\n```\n\n\n\n\n\n\n\n\n$$\\left[\\begin{matrix}\\cos{\\left (\\theta \\right )} \\cos{\\left (\\overline{\\theta} \\right )} & \\sin{\\left (\\theta \\right )} \\sin{\\left (\\overline{\\theta} \\right )} & 0\\\\\\sin{\\left (\\theta \\right )} \\sin{\\left (\\overline{\\theta} \\right )} & \\cos{\\left (\\theta \\right )} \\cos{\\left (\\overline{\\theta} \\right )} & 0\\\\0 & 0 & 1\\end{matrix}\\right]$$\n\n\n\n##### Machine Learning\n\nMachine learning is the process of tagging data in a data frame. The first thing that needs to be choosen is a target variable. Depending on whether you have examples of your target variable or not, the task can fall in one of two main categories: \n\n1.   **Supervised Learning**: when you have past examples of your input and output data. Depending on whether your output variable is categorical (discrete) or continuous, the supervised learning task can be called:\n      1. **Classification**: when your output variable is discrete (categorical). Logistic regression is the main example of classification technique.\n      2. **Regression**: when your output variable is continuous. Linear regression is the main example.\n\n2.   **Unsupervised Learning**: when you don't have past examples of your output variable or not even know what it could be. In this case you want the machine to group your data so you can try finding some pattern in it. Depending on wether you want to group the rows or the columns of you data frame, this task can be called: \n      1. **Clustering**: when you want the machine to tag (group) the rows of your data frame. This tagging can become in the future your output variable to be used in a supervised learning classification problem.\n      2. **PCA**: when you want the machine to tag (group) the columns of your data frame. In this case you want a new column that will replace some of the original ones through a simple formula.\n\nThe process of solving a problem using Machine Learning usually involves five steps: \n\n1.   **Problem Definition**: decide which variable will be predicted. This will be called your output variable. \n2.   **Data Preparation**: decide which variables you need to try predicting your output variable. These variables will be called input variables. In this step you will also find examples of your variables and have them cleaned and ready to be used.\n3.   **Model Development**: Based on your output variable type availability you will decide if you're going to develop a classification, regression, clustering or PCA model.\n4.   **Results Analysis**: When you link the math results from trainning and testing the model developed in stage 3 with your business objectives and present your results for both a technical and a business oriented audience.\n5.   **Model Deployment**: When your model goes live. Here usually you deal with problems of interfacing your model with real people (managerial issues) or with other systems in your client (a task usually called data engineering).\n\n##### Quantum Computing\n\nThe idea behind quantum computing is based in three concepts:\n\n1.   **Superposition of states**: the Qubit is neither in the $|0 \\rangle$ or $|1 \\rangle$ state but in a mixed state called superposition of states. Bare in mind that the notion that it is at the same time in the $|0 \\rangle$ and $|1 \\rangle$ state is wrong. The system is in a state that is formed from the basis states $|0 \\rangle$ and $|1 \\rangle$. \n2.   **Interference**: is the possibility of making states interact with one another (or with themselves) in such a way that the desired pattern (the one that holds the answer for our problem) is reinforced while the other patterns are cancelled out.\n3.   **Entanglement**: an extremely strong correlation between states that cannot happen in classical physics. Because of it, two particles when they interact with one another remain entangled (\"amarradas\" in portuguese) after that. This entangled state means that their states are grouped in such a way that they cannot be represented individually. \n\n\n\n\nOs conceitos apresentados acima s\u00e3o aprofundados a seguir:\n\n**Nota\u00e7\u00e3o de Dirac**: atrav\u00e9s dela podemos representar a sobreposi\u00e7\u00e3o de $n$ estados e amplitudes em um sistema $\\psi$ conforme segue: $\\psi = c_0|x_0 \\rangle + c_1 | x_1 \\rangle + ... + \\ c_{n-1}|x_{n-1} \\rangle$\n\n**Colapso da Fun\u00e7\u00e3o de Onda**: s\u00f3 podemos saber \"o que se passa\" com uma part\u00edcula subat\u00f4mica (um f\u00f3ton de luz por exemplo) se tentarmos medir o seu estado. Neste momento a part\u00edcula ir\u00e1 nos \"responder\" com qualquer dos poss\u00edveis estados $x_i$ acima. Neste momento a part\u00edcula \"interrompe\" sua sobreposi\u00e7\u00e3o e nos mostra uma fotografia moment\u00e2nea de si mesma. Damos o nome a este fen\u00f4meno de colapso da fun\u00e7\u00e3o de onda associada \u00e0 part\u00edcula. \n\n**Amplitudes $c_0$ ... $c_{n-1}$** e **probabilidades de medi\u00e7\u00e3o dos estados $x_0$ ... $x_{n-1}$** de uma **part\u00edcula**: Cada estado pass\u00edvel de ser medido $x_0$ ... $x_{n-1}$ tem uma amplitude $c_i$ associada ao mesmo. Esta amplitude pode ser um n\u00famero complexo qualquer, com qualquer valor (negativo, nulo ou positivo) tanto na sua parte real quanto na parte imagin\u00e1ria.\n\nA probabilidade de obtermos como resposta a uma medi\u00e7\u00e3o do estado de uma part\u00edcula o valor $x_i$ est\u00e1 associada com o produto $c_i.c_i^{*}$ associado a amplitude $c_i$ do estado $x_i$.\n\nUma vez que o valor num\u00e9rico $c_i$ pode ser um n\u00famero complexo qualquer, devemos lembrar que $c_i^{*}$ \u00e9 o seu complexo conjugado (o n\u00famero obtido trocando a parte imagin\u00e1ria do mesmo de sinal). Por exemplo se $c_i = 3 + 4i$, seu complexo conjugado $c_i^{*}$ ser\u00e1 igual a $c_i^{*} = 3 - 4i$.\n\nPor\u00e9m observe que o produto $c_i.c_i^{*}$ sempre ser\u00e1 um n\u00famero real. Se supusermos que a soma de todos os produtos $c_i.c_i^{*}$ para $i$ indo de $0$ a $n-1$ seja igual a $1$, podemos dizer que cada produto $c_i.c_i^{*}$ representar\u00e1 a probabilidade de obtermos o estado $x_i$ associado em uma medida qualquer.\n\nToda a \"estranheza\" da Mec\u00e2nica Qu\u00e2ntica decorre da possibilidade destas $n$ amplitudes $c_i$ serem constituidas de qualquer n\u00famero poss\u00edvel. Podendo misturar valores positivos com negativos podemos obter como resultado para uma combina\u00e7\u00e3o de $c_i$s distintos at\u00e9 mesmo o valor 0. Isto significa que o estado $x_i$ associado \u00e0 amplitude $c_i$ ter\u00e1 probabilidade 0% de ser medido, o que significa que n\u00e3o vamos medi-lo. Dizemos portanto que aquele resultado \"desapareceu\" de nossas medidas, em outras palavras, naquela situa\u00e7\u00e3o a part\u00edcula \"sumiu\". Dado que tal soma com resultado nulo s\u00f3 pode aparecer decorrente da intera\u00e7\u00e3o de outros estados, dizemos que ocorreu um fen\u00f4meno de **interfer\u00eancia** da part\u00edcula. Por\u00e9m somos levados a concluir que, dados os estados da part\u00edcula interagirem entre s\u00ed (enquanto a mesma est\u00e1 em sobreposi\u00e7\u00e3o), a part\u00edcula est\u00e1 interindo **consigo pr\u00f3pria**.\n\nDo ponto de vista filos\u00f3fico, isto pode gerar (alias tem gerado a mais de cem anos) uma enorme confus\u00e3o, com grandes nomes da ci\u00eancia tentando dar voltas de pensamento e executando verdadeiros malabarismos mentais para encontrar formas de explicar tais fen\u00f4menos. De nossa parte, o que nos interessa \u00e9 que a sobreposi\u00e7\u00e3o e suas consequ\u00eancias podem ser facilmente analisadas atrav\u00e9s da maquinaria dos n\u00fameros complexos e da \u00e1lgebra linear. Seguiremos aqui a linha *filos\u00f3fica* muito bem descrita por uma frase pronunciada pelo f\u00edsico David Mermin a um de seus orientandos quando o mesmo come\u00e7ou a gerar as famosas perguntas sem resposta que todo professor de Mec\u00e2nica Qu\u00e2ntica j\u00e1 se acostumou em responder com um sorriso enigm\u00e1tico. A frase simplesmente foi (em ingl\u00eas no original): *Shut Up and Calculate*. \n\nPelo estilo da mesma, ela foi atribuida ao f\u00edsico ganhador do Nobel, Richard Feynman. Ele n\u00e3o pronunciou a mesma, mas parafraseando as palavras de um grande humorista brasileiro Dias Gomes, criador do inesquec\u00edvel prefeito de Sucupira Odorico Paraguassu: \"Se n\u00e3o disse, deveria ter dito\".\n\nA partir deste momento, nossas part\u00edculas elementares passar\u00e3o a se constituir de entes abstratos chamados de **Qubits**. Tais elementos ter\u00e3o a capacidade de entrar em sobreposi\u00e7\u00e3o de seus estados fundamentais *x_i* e ser\u00e3o retirados dela quando forem medidos, momento no qual nos apresentar\u00e3o como resultado um dos $x_i$ poss\u00edveis. A probabilidade de medirmos o resultado $x_i$ ser\u00e1 dada pelo produto $c_i.c_i^{*}$. Estaremos interessados apenas com as situa\u00e7\u00f5es nas quais a soma de todos os produtos $c_i.c_i^*$ dar\u00e1 1 (100%).   \n\n**NISQ: Noisy Intermediate Scale Quantum Computing**: Quantum computing today is based in a technique called **NISQ**. This technology uses both classical and quantum computers. Classical computers handle the machine learning problem the same way they usually do. The task of \"crunching\" the numbers (get the parameters for the machine learning model and having it tested) is handled by the quantum counterpart. The algorithms that handle the problem this way are called **Variational Quantum-Classical Algorithms**\n\n##### \u00c1lgebra Linear: Exerc\u00edcios Avan\u00e7ados\n\n###### Estados Qu\u00e2nticos\n\n**Ex.(QCE 0.3):** Apresente a representa\u00e7\u00e3o da sobreposi\u00e7\u00e3o das amplitudes e dos estados de um sistema $\\psi$ com $n$ estados poss\u00edveis?\n\n\n```python\nfrom sympy import latex\nfrom IPython.display import Math\nexpr = \"\\psi =\"\nexpr = expr + \"c_0|x_0\\\\rangle\" + \" + \" + \"c_1|x_1\\\\rangle\"\nexpr = expr + \" \\ + \\ \" + \"...\" + \" \\ + \\ \" + \"c_{n-1}|x_{n-1}\\\\rangle\"\nMath(expr)\n```\n\n\n\n\n$$\\psi =c_0|x_0\\rangle + c_1|x_1\\rangle \\ + \\ ... \\ + \\ c_{n-1}|x_{n-1}\\rangle$$\n\n\n\n**Ex.:** Calcule a probabilidade dos sistemas abaixo, ao serem medidos, indicarem o estado $|1 \\rangle$\n\n\n```python\nimport numpy as np\np_e = lambda vetor,x : (np.linalg.norm(vetor[x])/np.linalg.norm(vetor))**2\n\npsi = [1/np.sqrt(3), np.sqrt(2/3)]\nphi = [1j/2, np.sqrt(3)/2]\nchi = [(1+1j)/np.sqrt(3), -1j/np.sqrt(3)]\n\n[float(x.__format__('.3f')) for x in [p_e(psi,1), p_e(phi,1), p_e(chi,1)]]\n```\n\n\n\n\n    [0.667, 0.75, 0.333]\n\n\n\n**Ex.:** Qual a probabilidade do sistema Phi estar no $3^o$ estado?\n\n\n```python\nimport numpy as np\nimport sympy as sp\nPhi = sp.Matrix([-3 - sp.I, -2*sp.I, sp.I, 2])\nnum = (Phi[2] * Phi[2].conjugate()) \nden = sp.sqrt(sum(sp.matrix_multiply_elementwise(Phi,Phi.conjugate())))\nP = sp.simplify((num/den)**2)\nP\n```\n\n\n\n\n$\\displaystyle \\frac{1}{19}$\n\n\n\n**Ex.:** Dadas as amplitudes $c_{up} = 3-4j$ e $c_{down} = 7 + 2j$ aplicadas \u00e0 uma base ortonormal, calcule as probabilidades associadas a cada uma das amplitudes.\n\n\n```python\nimport numpy as np\nc_up = 3-4j\nc_down = 7+2j\nket = np.array([c_up,c_down]).reshape(-1,1)\np_up = np.linalg.norm(c_up)**2/np.linalg.norm(ket)**2\np_down = np.linalg.norm(c_down)**2/np.linalg.norm(ket)**2\n[float(x) for x in [p_up.__format__('.3f'), p_down.__format__('.3f')]]\n```\n\n\n\n\n    [0.321, 0.679]\n\n\n\n**Ex.:** Apresente a representa\u00e7\u00e3o $ket$ do vetor $\\psi$ com valores $2-i, 2i, 1-i, 1, -2i, 2$\n\n\n```python\nimport numpy as np\nimport sympy as sp\npsi = sp.Matrix([2 - sp.I, 2*sp.I, 1 - sp.I, 1, -2*sp.I, 2])\nexpr = \"| \\\\psi \\\\rangle =\" + sp.latex(psi)\nMath(expr)\n```\n\n\n\n\n$$| \\psi \\rangle =\\left[\\begin{matrix}2 - i\\\\2 i\\\\1 - i\\\\1\\\\- 2 i\\\\2\\end{matrix}\\right]$$\n\n\n\n**Ex.:** Apresente a representa\u00e7\u00e3o $bra$ do vetor $\\psi$ com valores $2-i, 2i, 1-i, 1, -2i, 2$\n\n\n```python\npsiT = sp.conjugate(sp.Matrix.transpose(psi))\nexpr = \"\\\\langle \\\\psi | =\" + sp.latex(psiT)\nMath(expr)\n```\n\n\n\n\n\n\n\n\n$$\\langle \\psi | =\\left[\\begin{matrix}2 + i & - 2 i & 1 + i & 1 & 2 i & 2\\end{matrix}\\right]$$\n\n\n\n**Ex.:** Apresente a representa\u00e7\u00e3o $ket$ do vetor $\\psi$ com valores $1/2, -i/2, \\sqrt{2}/2$, a representa\u00e7\u00e3o $bra$ associada e o produto da representa\u00e7\u00e3o $bra$ com a matriz $A$ (vide abaixo) e com a representa\u00e7\u00e3o $ket$.\n\n\n```python\npsi_ket = sp.Matrix([[sp.Rational(1,2)],\n                      [-sp.I/2],\n                      [1/sp.sqrt(2)]])\npsi_ket\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\frac{1}{2}\\\\- \\frac{i}{2}\\\\\\frac{\\sqrt{2}}{2}\\end{matrix}\\right]$\n\n\n\n\n```python\npsi_bra = psi_ket.adjoint()\npsi_bra\n```\n\n\n\n\n\n\n\n\n$$\\left[\\begin{matrix}\\frac{1}{2} & \\frac{i}{2} & \\frac{\\sqrt{2}}{2}\\end{matrix}\\right]$$\n\n\n\n\n```python\nA = sp.Matrix([[0,1/sp.sqrt(2),0],\n                [1,1/sp.sqrt(2),0],\n                [0,0,0]])\npsi_bra, A, psi_ket, (psi_bra * A * psi_ket).expand(complex=True)\n```\n\n\n\n\n\n\n\n\n$$\\left ( \\left[\\begin{matrix}\\frac{1}{2} & \\frac{i}{2} & \\frac{\\sqrt{2}}{2}\\end{matrix}\\right], \\quad \\left[\\begin{matrix}0 & \\frac{\\sqrt{2}}{2} & 0\\\\1 & \\frac{\\sqrt{2}}{2} & 0\\\\0 & 0 & 0\\end{matrix}\\right], \\quad \\left[\\begin{matrix}\\frac{1}{2}\\\\- \\frac{i}{2}\\\\\\frac{\\sqrt{2}}{2}\\end{matrix}\\right], \\quad \\left[\\begin{matrix}\\frac{\\sqrt{2}}{8} - \\frac{\\sqrt{2} i}{8} + \\frac{i}{4}\\end{matrix}\\right]\\right )$$\n\n\n\n\n**Ex.:** Calcule o m\u00f3dulo do vetor $\\psi$\n\n\n```python\nexpr = sp.simplify(psiT.multiply(psi))\nMath(expr)\n```\n\n\n\n\n\n\n\n\n$$\\left[\\begin{matrix}20\\end{matrix}\\right]$$\n\n\n\n**Ex.:** Prove que os vetores $|\\psi_1 \\rangle = [1 + i, i]^T$ e $\\psi_2 \\rangle = [2 + 4i, 3i \u2212 1]^T$ diferem pelo fator $3+i$\n\n\n```python\npsi1 = np.array([1+1j,1j]).reshape(2,1)\npsi2 = np.array([2+4j,3j-1]).reshape(2,1)\npsi2/psi1\n```\n\n\n\n\n    array([[3.+1.j],\n           [3.+1.j]])\n\n\n\n**Ex.:** Os vetores $| \\psi_1 \\rangle = [1 + i, 2 \u2212 i]^T$ e $| \\psi_2 \\rangle = [2 + 2i, 1 \u2212 2i]^T$ podem representar o mesmo estado? RESP: N\u00e3o, pois suas componentes diferem por valores distintos.\n\n\n```python\npsi1 = np.array([1+1j,2-1j]).reshape(-1,1)\npsi2 = np.array([2+2j,1-2j]).reshape(-1,1)\npsi2/psi1\n```\n\n\n\n\n\n\n\n\n    array([[2. +0.j ],\n           [0.8-0.6j]])\n\n\n\n**Ex.:** Qual \u00e9 o comprimento do vetor $| \\psi \\rangle = [2 \u2212 3i,1 + 2i]^T$?\n\n\n```python\npsi1 = np.array([2-3j,1+2j]).reshape(-1,1)\nprint(np.sqrt(psi1.conjugate().T.dot(psi1)[0,0]).real)\nnp.linalg.norm(psi1)\n```\n\n**Ex.:** Normalize o ket $| \\psi \\rangle = [3 \u2212 i, 2 + 6i,7 \u2212 8i,6.3 + 4.9i, 13i,0,21.1]^T$\n\n\n```python\npsi1 = np.array([3-1j, 2+6j, 7-8j, 6.3+4.9j, 13j, 0, 21.1]).reshape(-1,1)\npsi1_norm = (psi1 / np.linalg.norm(psi1))\npsi1_norm\n```\n\n\n\n\n\n\n\n\n    array([[0.103-0.034j],\n           [0.069+0.207j],\n           [0.241-0.276j],\n           [0.217+0.169j],\n           [0.   +0.448j],\n           [0.   +0.j   ],\n           [0.728+0.j   ]])\n\n\n\n**Ex.:** Verifique que os dois estados: $x_1 = [\\frac{\\sqrt 2}{2},\\frac{\\sqrt 2}{2}]^T$ e $x_2 = [\\frac{\\sqrt 2}{2},-\\frac{\\sqrt 2}{2}]^T$ tem m\u00f3dulo igual a 1 e apresente o vetor que representa a sobreposi\u00e7\u00e3o destes estados.\n\nO vetor \u00e9: $| \\psi \\rangle = c_1 | x_1 \\rangle + c_2 | x_2 \\rangle$\n\n\n```python\nimport numpy as np\nx1 = np.array([np.sqrt(2)/2,np.sqrt(2)/2]).reshape(-1,1)\nx2 = np.array([np.sqrt(2)/2,-np.sqrt(2)/2]).reshape(-1,1)\nprint(np.linalg.norm(x1), np.linalg.norm(x2))\n```\n\n\n\n\n\n    1.0 1.0\n\n\n**Ex.:** Apresente a matrix hermitiana de $\\Omega$ apresentada a seguir\n\n\n```python\nomega = np.array([[-1,-1j],\n                  [1j, 1]])\nMath(sp.Matrix(omega))\n```\n\n\n\n\n\n\n\n\n$$\\left[\\begin{matrix}-1.0 & - 1.0 i\\\\1.0 i & 1.0\\end{matrix}\\right]$$\n\n\n\n\n```python\nMath(sp.Matrix(np.matrix(omega).getH()))\n```\n\n\n\n\n\n\n\n\n$$\\left[\\begin{matrix}-1.0 & - 1.0 i\\\\1.0 i & 1.0\\end{matrix}\\right]$$\n\n\n\n**Ex.:** Calcule o vetor resultante da atua\u00e7\u00e3o do operador $\\Omega$ em $\\psi$ \n\n\n```python\npsi = np.array([-1+0j,-1-1j])\nomega = np.array([[-1,-1j],\n                  [1j, 1]])\nexpr = \"\\Omega =\" + sp.latex(sp.Matrix(omega))\nexpr = expr + sp.latex('\\psi =') + sp.latex(sp.Matrix(psi))\nexpr = expr + sp.latex('\\Omega . \\psi =') + sp.latex(sp.Matrix(omega.dot(psi)))\nMath(expr)\n```\n\n\n\n\n\n\n\n\n$$\\Omega =\\left[\\begin{matrix}-1.0 & - 1.0 i\\\\1.0 i & 1.0\\end{matrix}\\right]\\psi =\\left[\\begin{matrix}-1.0\\\\-1.0 - 1.0 i\\end{matrix}\\right]\\Omega . \\psi =\\left[\\begin{matrix}1.0 i\\\\-1.0 - 2.0 i\\end{matrix}\\right]$$\n\n\n\n**Ex.:** Calcule as opera\u00e7\u00f5es a seguir\n\n\n```python\nX = sp.Matrix([[0,1],[1,0]])\npsi_bra = sp.Matrix([[1/sp.sqrt(3),sp.sqrt(sp.Rational(2,3))]]) # sp.Rational(2,3) = 2/3\npsi_ket = psi_bra.T\npsi_bra * X * psi_ket\n```\n\n\n\n\n\n\n\n\n$$\\left[\\begin{matrix}\\frac{2 \\sqrt{2}}{3}\\end{matrix}\\right]$$\n\n\n\n\n```python\nexp_X = psi_bra * X * psi_ket\nexp_X2 = psi_bra * X * X * psi_ket # X squared expectation\nexp_X_2 = exp_X ** 2 # X expectation squared\ndesv_X = sp.sqrt(exp_X2[0] - exp_X_2[0]) # X standard deviation\nexp_X2, exp_X_2, desv_X\n```\n\n\n\n\n\n\n\n\n$$\\left ( \\left[\\begin{matrix}1\\end{matrix}\\right], \\quad \\left[\\begin{matrix}\\frac{8}{9}\\end{matrix}\\right], \\quad \\frac{1}{3}\\right )$$\n\n\n\n**Ex.:** Using the dynamics given in Equation (3.4), determine what the state of the system would be if you start with the state $[5, 5, 0, 2, 0, 15]^T$. The Dinamics is given by matrix M below:\n\n\n```python\nimport sympy as sp\nM = sp.Matrix([[0,0,0,0,0,0],\n               [0,0,0,0,0,0],\n               [0,1,0,0,0,1],\n               [0,0,0,1,0,0],\n               [0,0,1,0,0,0],\n               [1,0,0,0,1,0]])\nX = (sp.Matrix([5,5,0,2,0,15]))\nMath(\"M =\" + sp.latex(M) + \"X =\" + sp.latex(X) + \"M.X =\" + sp.latex(M*X))\n```\n\n\n\n\n$$M =\\left[\\begin{matrix}0 & 0 & 0 & 0 & 0 & 0\\\\0 & 0 & 0 & 0 & 0 & 0\\\\0 & 1 & 0 & 0 & 0 & 1\\\\0 & 0 & 0 & 1 & 0 & 0\\\\0 & 0 & 1 & 0 & 0 & 0\\\\1 & 0 & 0 & 0 & 1 & 0\\end{matrix}\\right]X =\\left[\\begin{matrix}5\\\\5\\\\0\\\\2\\\\0\\\\15\\end{matrix}\\right]M.X =\\left[\\begin{matrix}0\\\\0\\\\20\\\\2\\\\0\\\\5\\end{matrix}\\right]$$\n\n\n\n**Ex.:** For the matrix M given in Equation (3.4), calculate $M^6$. If all the marbles start at vertex 2, where will all the marbles end up after 6 time steps?\n\n\n```python\nMn = lambda M,n : [\"M\"+str(n)+\" =\", M**n]\nn = 6\nexpr1 = \"M^{} =\".format(n) + sp.latex(M**n)\nexpr2 = \"X =\" + sp.latex(X)\nexpr3 = \"M^{}.X =\".format(n) + sp.latex((M**n)*X)\nexpr = expr1 + expr2 + expr3\nMath(expr)\n```\n\n\n\n\n$$M^6 =\\left[\\begin{matrix}0 & 0 & 0 & 0 & 0 & 0\\\\0 & 0 & 0 & 0 & 0 & 0\\\\0 & 0 & 1 & 0 & 0 & 0\\\\0 & 0 & 0 & 1 & 0 & 0\\\\1 & 0 & 0 & 0 & 1 & 0\\\\0 & 1 & 0 & 0 & 0 & 1\\end{matrix}\\right]X =\\left[\\begin{matrix}5\\\\5\\\\0\\\\2\\\\0\\\\15\\end{matrix}\\right]M^6.X =\\left[\\begin{matrix}0\\\\0\\\\0\\\\2\\\\5\\\\20\\end{matrix}\\right]$$\n\n\n\n**Ex.:** Consider the following graph representing city streets. Singleheaded arrows (\u2212\u2192) correspond to one-way streets and double-headed arrows (\u2190\u2192) correspond to two-way streets. Imagine that it takes one time click to traverse an arrow. You may assume that everyone must move at every time click. If every corner starts with exactly one person, where will everyone be after one time click? After two time clicks? After four time clicks?\n\n\n```python\nM = sp.Matrix([[0,1,0,0,0,0,0,0,0],\n               [1,0,0,0,0,0,0,0,0],\n               [0,0,0,0,0,0,0,0,0],\n               [0,0,0,1,0,0,0,0,0],\n               [0,0,0,0,0,0,0,0,0],\n               [0,0,1,0,0,0,0,0,0],\n               [0,0,0,0,0,0,0,0,0],\n               [0,0,0,0,0,0,1,0,0],\n               [0,0,0,0,0,1,0,1,1]])\nX = sp.Matrix([1,1,1,1,1,1,1,1,1])\nexpr1 = M*X\nexpr2 = (M**2)*X\nexpr4 = (M**4)*X\nexpr = \"X_1 =\" + sp.latex(expr1) + \"X_2 =\" + \\\n       sp.latex(expr2) + \"X_4 =\" + sp.latex(expr4)\nMath(expr)\n```\n\n\n\n\n\n\n\n\n$$X_1 =\\left[\\begin{matrix}1\\\\1\\\\0\\\\1\\\\0\\\\1\\\\0\\\\1\\\\3\\end{matrix}\\right]X_2 =\\left[\\begin{matrix}1\\\\1\\\\0\\\\1\\\\0\\\\0\\\\0\\\\0\\\\5\\end{matrix}\\right]X_4 =\\left[\\begin{matrix}1\\\\1\\\\0\\\\1\\\\0\\\\0\\\\0\\\\0\\\\5\\end{matrix}\\right]$$\n\n\n\n**Ex.:** Suponha a matriz de transi\u00e7\u00e3o de estados M apresentada abaixo. Calcule o produto elemento a elemento da matriz M com sua transposta conjugada.\n\n\n```python\nimport sympy as sp\nM = sp.Matrix([[           0,                   0,0,0,0,0,0,0],\n               [1/sp.sqrt(2),                   0,0,0,0,0,0,0],\n               [1/sp.sqrt(2),                   0,0,0,0,0,0,0],\n               [           0,(-1+sp.I)/sp.sqrt(6),                   0,1,0,0,0,0],\n               [           0,(-1-sp.I)/sp.sqrt(6),                   0,0,1,0,0,0],\n               [           0,(+1-sp.I)/sp.sqrt(6),(-1+sp.I)/sp.sqrt(6),0,0,1,0,0],\n               [           0,                   0,(-1-sp.I)/sp.sqrt(6),0,0,0,1,0],\n               [           0,                   0,(+1-sp.I)/sp.sqrt(6),0,0,0,0,1]]) \n\nX1 = sp.Matrix([1,0,0,0,0,0,0,0])\nexpr = \"M =\" + sp.latex(M) + \"X_1 =\" + sp.latex(X1)\nMath(expr)\n```\n\n\n\n\n\n\n\n\n$$M =\\left[\\begin{matrix}0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\\\\\frac{\\sqrt{2}}{2} & 0 & 0 & 0 & 0 & 0 & 0 & 0\\\\\\frac{\\sqrt{2}}{2} & 0 & 0 & 0 & 0 & 0 & 0 & 0\\\\0 & \\frac{\\sqrt{6}}{6} \\left(-1 + i\\right) & 0 & 1 & 0 & 0 & 0 & 0\\\\0 & \\frac{\\sqrt{6}}{6} \\left(-1 - i\\right) & 0 & 0 & 1 & 0 & 0 & 0\\\\0 & \\frac{\\sqrt{6}}{6} \\left(1 - i\\right) & \\frac{\\sqrt{6}}{6} \\left(-1 + i\\right) & 0 & 0 & 1 & 0 & 0\\\\0 & 0 & \\frac{\\sqrt{6}}{6} \\left(-1 - i\\right) & 0 & 0 & 0 & 1 & 0\\\\0 & 0 & \\frac{\\sqrt{6}}{6} \\left(1 - i\\right) & 0 & 0 & 0 & 0 & 1\\end{matrix}\\right]X_1 =\\left[\\begin{matrix}1\\\\0\\\\0\\\\0\\\\0\\\\0\\\\0\\\\0\\end{matrix}\\right]$$\n\n\n\n\n```python\nP1 = sp.simplify(sp.matrix_multiply_elementwise(M,M.conjugate()))\nexpr = \"P_1 =\" + sp.latex(P1)\nMath(expr)\n```\n\n\n\n\n\n\n\n\n$$P_1 =\\left[\\begin{matrix}0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\\\\\frac{1}{2} & 0 & 0 & 0 & 0 & 0 & 0 & 0\\\\\\frac{1}{2} & 0 & 0 & 0 & 0 & 0 & 0 & 0\\\\0 & \\frac{1}{3} & 0 & 1 & 0 & 0 & 0 & 0\\\\0 & \\frac{1}{3} & 0 & 0 & 1 & 0 & 0 & 0\\\\0 & \\frac{1}{3} & \\frac{1}{3} & 0 & 0 & 1 & 0 & 0\\\\0 & 0 & \\frac{1}{3} & 0 & 0 & 0 & 1 & 0\\\\0 & 0 & \\frac{1}{3} & 0 & 0 & 0 & 0 & 1\\end{matrix}\\right]$$\n\n\n\n\n```python\nM2 = sp.simplify(M*M)\nexpr = \"M_2 =\" + sp.latex(M2)\nMath(expr)\n```\n\n\n\n\n\n\n\n\n$$M_2 =\\left[\\begin{matrix}0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\\\0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\\\0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\\\\\frac{\\sqrt{3}}{6} \\left(-1 + i\\right) & \\frac{\\sqrt{6}}{6} \\left(-1 + i\\right) & 0 & 1 & 0 & 0 & 0 & 0\\\\- \\frac{\\sqrt{3}}{6} \\left(1 + i\\right) & - \\frac{\\sqrt{6}}{6} \\left(1 + i\\right) & 0 & 0 & 1 & 0 & 0 & 0\\\\0 & \\frac{\\sqrt{6}}{6} \\left(1 - i\\right) & \\frac{\\sqrt{6}}{6} \\left(-1 + i\\right) & 0 & 0 & 1 & 0 & 0\\\\- \\frac{\\sqrt{3}}{6} \\left(1 + i\\right) & 0 & - \\frac{\\sqrt{6}}{6} \\left(1 + i\\right) & 0 & 0 & 0 & 1 & 0\\\\\\frac{\\sqrt{3}}{6} \\left(1 - i\\right) & 0 & \\frac{\\sqrt{6}}{6} \\left(1 - i\\right) & 0 & 0 & 0 & 0 & 1\\end{matrix}\\right]$$\n\n\n\n###### Interfer\u00eancia e Sobreposi\u00e7\u00e3o\n\nIf the weights are real numbers, the probabilities associated with them can only increase when they are added. \n\nIn contrast, if the weights are complex numbers, the probabilities are associated with their modulus squared. Therefore if you add two weights that are complex numbers, the probability can either increase, add up to 0 or decrease.\n\nWhen two complex numbers are added and cancel each other (they add up to 0) this is referred to as **interference**.\n\nLet the state of the system be given by $X = [c_0, c_1,..., c_{n\u22121}], T \u2208 C_n$. It is incorrect to say that the\nprobability of the photon\u2019s being in position $k$ is $|c_k|$\n\nRather, to be in state $X$ means that the particle is in some sense in all positions simultaneously. The photon passes through the top slit and the bottom slit simultaneously, and when it exits both slits, it can cancel itself out. A photon is not in a single position, rather it is in many positions, a **superposition**.\n\nMatrix below shows the probability of starting in column $j$ a photon will end up in row $i$ after 2 time periods (or 2 ticks of clock).\n\nFor instance, if a photon is in state $0$ (first column), after two time periods it will end up in state $3$ (forth row) with probability $\\frac{1}{6}$.\n\nNow look at the element $P_2[5,0]$. It is equal to $0$. This means that the probability of a photon being in state $0$ in instant $0$ and in state $5$ in instant $2$ is $0$, so there will be no photon at all there.\n\nThis is caused by **interference**.\n\nThe difficult thing to understand (to accept would be a better term) is that it is wrong to say that there's a probability for the photon to be in a state. In reality the photon is itself in all states, and each state has a definite probability associated with it.\n\nProbability of what? Of us, when trying to measure where the photon \"is\" will find it in that state at that time.\n\nBUT, when we're not looking (i.e.trying to measure it), photon is in a **superposition** of states. In other words: it is simultaneously in all states at the same time!\n\n\n```python\nP2 = sp.simplify(sp.matrix_multiply_elementwise(M2,M2.conjugate()))\nexpr = \"P_2 =\" + sp.latex(P2)\nMath(expr)\n```\n\n\n\n\n\n\n\n\n$$P_2 =\\left[\\begin{matrix}0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\\\0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\\\0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\\\\\frac{1}{6} & \\frac{1}{3} & 0 & 1 & 0 & 0 & 0 & 0\\\\\\frac{1}{6} & \\frac{1}{3} & 0 & 0 & 1 & 0 & 0 & 0\\\\0 & \\frac{1}{3} & \\frac{1}{3} & 0 & 0 & 1 & 0 & 0\\\\\\frac{1}{6} & 0 & \\frac{1}{3} & 0 & 0 & 0 & 1 & 0\\\\\\frac{1}{6} & 0 & \\frac{1}{3} & 0 & 0 & 0 & 0 & 1\\end{matrix}\\right]$$\n\n\n\nA classical computer can be in one state at a time (0 or 1). A quantum computer uses the superposition phenomenon to be in all classical states at the same time. In other words: a quantum computer is the ultimate idea in parallel processing.\n\nBoth matter and light manifest a particle-like and a wave-like behavior\n\nAssembling Systems: Calcule o produto tensorial de M com N. O que ele representa em termos de circuitos qu\u00e2nticos?\n\n\n```python\nimport sympy as sp\nfrom sympy.physics.quantum import TensorProduct\nM = sp.Matrix([[0,               sp.Rational(1,6),sp.Rational(5,6)],\n               [sp.Rational(1,3),sp.Rational(1,2),sp.Rational(1,6)],\n               [sp.Rational(2,3),sp.Rational(1,3),               0]])\n\nN = sp.Matrix([[sp.Rational(1,3),sp.Rational(2,3)],\n               [sp.Rational(2,3),sp.Rational(1,3)]])\nMxN = TensorProduct(M,N)\nexpr1 = sp.latex('M = ') + sp.latex(M)\nexpr2 = sp.latex('N = ') + sp.latex(N)\nexpr3 = sp.latex('M x N = ') + sp.latex(MxN)\nexpr = expr1 + expr2 + expr3\nMath(expr)\n```\n\n\n\n\n\n\n\n\n$$M = \\left[\\begin{matrix}0 & \\frac{1}{6} & \\frac{5}{6}\\\\\\frac{1}{3} & \\frac{1}{2} & \\frac{1}{6}\\\\\\frac{2}{3} & \\frac{1}{3} & 0\\end{matrix}\\right]N = \\left[\\begin{matrix}\\frac{1}{3} & \\frac{2}{3}\\\\\\frac{2}{3} & \\frac{1}{3}\\end{matrix}\\right]M x N = \\left[\\begin{matrix}0 & 0 & \\frac{1}{18} & \\frac{1}{9} & \\frac{5}{18} & \\frac{5}{9}\\\\0 & 0 & \\frac{1}{9} & \\frac{1}{18} & \\frac{5}{9} & \\frac{5}{18}\\\\\\frac{1}{9} & \\frac{2}{9} & \\frac{1}{6} & \\frac{1}{3} & \\frac{1}{18} & \\frac{1}{9}\\\\\\frac{2}{9} & \\frac{1}{9} & \\frac{1}{3} & \\frac{1}{6} & \\frac{1}{9} & \\frac{1}{18}\\\\\\frac{2}{9} & \\frac{4}{9} & \\frac{1}{9} & \\frac{2}{9} & 0 & 0\\\\\\frac{4}{9} & \\frac{2}{9} & \\frac{2}{9} & \\frac{1}{9} & 0 & 0\\end{matrix}\\right]$$\n\n\n\n##### The Bancalvo Dataset\n\n\n```python\nsite = \"https://github.com/\"\ndiretorio = \"gustavomirapalheta/classes_datasets/blob/master/\"\narquivo = \"bancalvo.xlsx?raw=true\"\nlink = site + diretorio + arquivo\ntrain = pd.read_excel(link)\n\nlista = list(train['UF'].unique())\nlista.remove('SP')\ntrain['novaUF'] = train['UF'].replace(lista, 'NOSP')\ntrain['lRENDA'] = np.log10(train['RENDA'])\ntrain = train.drop(['IDENTIDADE','UF','RENDA'], axis=1)\ntrain = pd.get_dummies(train, drop_first=True)\nX = train.drop('STATUS_inad', axis=1).copy()\ny = train['STATUS_inad'].copy()\n\nfrom sklearn.model_selection import train_test_split\nXtrain, Xtest, ytrain, ytest = train_test_split(X, y, random_state = 53, test_size = 0.20)\nXtrain.shape, Xtest.shape, ytrain.shape, ytest.shape\n```\n\n\n\n\n    ((20000, 18), (5000, 18), (20000,), (5000,))\n\n\n\n#### Meu primeiro programa com Qubits\n\n**Introdu\u00e7\u00e3o** O objetivo desta se\u00e7\u00e3o \u00e9 demonstrar a execu\u00e7\u00e3o de um pequeno programa baseado em Qubits. O programa ser\u00e1 projetado na forma de um circuito com portas l\u00f3gicas qu\u00e2nticas. Utilizaremos a linguagem Qiskit da IBM, a partir de um programa Python, criado em um Jupyter Notebook no ambiente Google Colab \n\n**Cria\u00e7\u00e3o de Um Circuito com Qubits** Nosso circuito ser\u00e1 composto de dois Qubits, os quais ser\u00e3o inicializados no estado $|{0}\\rangle$. O primeiro Qubit passar\u00e1 por um Hadamart gate (colocando-o em sobreposi\u00e7\u00e3o dos estados $|{0}\\rangle$ e $|{1}\\rangle$. Em seguida \u00e9 aplicado um CNOT gate ao conjunto o que os colocar\u00e1 em entrela\u00e7amento e sobreposi\u00e7\u00e3o, nos estados $|{00}\\rangle$ e $|{11}\\rangle$. Por \u00faltimo medimos o estado de ambos os Qubits. A forma gr\u00e1fica do circuito \u00e9 apresentada no \u00faltimo comando da c\u00e9lula abaixo. Observe que o c\u00f3digo aqui apresentado apenas cria o circuito sem no entando executa-lo.\n\n\n```python\n# Criamos os Qubits\nq = qk.QuantumRegister(2)\n\n# Criamos os Bits\nc = qk.ClassicalRegister(2)\n\n# Criamos o circuito (com Qubits e Bits)\ncircuit = qk.QuantumCircuit(q, c)\n\n# Resetamos o primeiro Qubit para o estado |0>\ncircuit.reset(q[0])\n\n# Resetamos o segundo Qubit para o estado |0>\ncircuit.reset(q[1])\n\n# Aplicamos um Hadamart Gate no Qubit[0]\ncircuit.h(q[0])\n\n# e um CNOT Gate na saida do Hadamart (Qubit[0], Qubit[1])\n#  A primeira posi\u00e7\u00e3o \u00e9 do controle e a segunda do servo\ncircuit.cx(q[0],q[1])\n\n# Medimos o estado do Qubit\ncircuit.measure(q, c)\n\n# Visualizamos o circuito\ncircuit.draw('mpl')\n```\n\n**Execu\u00e7\u00e3o de Um Circuito com Qubits** A computa\u00e7\u00e3o qu\u00e2ntica \u00e9 essencialmente probabil\u00edstica. Pense nela como uma simula\u00e7\u00e3o de Monte Carlo em planilha, onde ao inv\u00e9s do comando `aleatorio()` do Excel (em Portugu\u00eas) voc\u00ea tem o circuito qu\u00e2ntico. Sendo assim, cada vez que o circuito for executado, ser\u00e1 gerada uma amostra dos poss\u00edveis resultados. Observe no entando que neste tipo de simula\u00e7\u00e3o, os resultados s\u00e3o sempre **discretos** isto \u00e9 n\u00fameros inteiros que representam os estados que o circuito \"decidiu\" nos apresentar quando tentamos medi-lo.\n\nTemos ent\u00e3o que criar o equivalente \u00e0 tabela de dados da simula\u00e7\u00e3o de Monte Carlo no Excel. Esta \"tabela\" \u00e9 gerada enviando o circuito para um dos *backends* que a IBM disponibiliza. O m\u00e9todo mais r\u00e1pido de executar a simula\u00e7\u00e3o \u00e9 atrav\u00e9s do simulador `BasicAer` o que nada mais \u00e9 que um simulador de Qubits que roda na pr\u00f3pria m\u00e1quina local. Este tipo de simula\u00e7\u00e3o \u00e9 pseudo-aleat\u00f3ria, tal como qualquer simula\u00e7\u00e3o baseada em algoritmos cl\u00e1ssicos (baseados em bits). \n\nO `BasicAer` \u00e9 o ambiente local que ir\u00e1 rodar a simula\u00e7\u00e3o. A simula\u00e7\u00e3o em si precisa de um ambiente `backend`. Pense que ela roda em modo batch. O `BasicAer` precisa enviar o circuito para um *motor* rodar a mesma. No caso deste exemplo o *motor* ou *backend* \u00e9 o `qasm_simulator`. Sendo assim, primeiro instanciamos a classe `BasicAer`, criando um objeto chamado `simulator` o qual ir\u00e1 rodar a simula\u00e7\u00e3o no backend `qasm_simulator`. \n\nCom o circuito (objeto de nome `circuit`) e o simulator (objeto de nome `simulator`) criados (isto \u00e9 com as respectivas classes instanciadas), pedimos para o `circuit` ser executado pelo `simulator` um determinado n\u00famero de vezes (`shots`, neste caso 1.000) atrav\u00e9s do comando qiskit `execute`.\n\nNeste caso estamos interessados nas contagens, para determinar que os Qubits entrela\u00e7ados mostraram apenas os estados $|{00}\\rangle$ e $|{11}\\rangle$ quando medidos. Sendo assim poder\u00edamos ter obtido o dicion\u00e1rio python com os resultados fazendo diretamente: `job.result().get_counts(circuit)`\n\n\n```python\n# Instanciando o simulador Qiskit Aer's Qasm\n# Observe que este simulador roda na sua m\u00e1quina local\nsimulator = qk.BasicAer.get_backend('qasm_simulator')\n\n# Executando a simula\u00e7\u00e3o (1000 medidas)\njob = qk.execute(circuit, simulator, shots=1000)\n\n# Capturando os resultados\nresult = job.result()\n\n# Obtendo as contagens dos estados medidos\ncounts = result.get_counts(circuit)\n\n# Apresentando os resultados\nprint(counts)\n```\n\n    {'11': 485, '00': 515}\n\n\n**Execu\u00e7\u00e3o do Circuito em Uma M\u00e1quina Real** Vamos agora executar nosso circuito em uma m\u00e1quina qu\u00e2ntica real. A c\u00e9lula abaixo precisa ser executada apenas se a `qiskit` ainda n\u00e3o estiver instalada no Google Colab (o que precisa ser feito uma vez por sess\u00e3o). Por isso deixei a c\u00e9lula a seguir comentada.\n\n\n```python\n#!pip install qiskit[visualization]\n```\n\n\n```python\n# Vamos usar um computador qu\u00e2ntico real\nimport qiskit as qk\n```\n\nPrimeiro devemos ir no site `https://quantum-computing.ibm.com`, nos registrar e obter a nossa API para c\u00f3digo python. Ela \u00e9 a \"assinatura\" para as m\u00e1quinas da IBM que o \"job\" foi enviado por um usu\u00e1rio registrado. Por quest\u00f5es de privacidade eliminei o valor da chave deste Jupyter Notebook. Como a mesma j\u00e1 foi salva na \u00e1rea do meu ambiente Colab (atrav\u00e9s do comando `qk.IBMQ.load_account(chave)`), posso apenas carrega-la com `qk.IBMQ.load_account`. Por isso a c\u00e9lula abaixo est\u00e1 comentada. \n\n\n```python\n# Obter a chave para uso da API IBM em : https://quantum-computing.ibm.com\n# chave = 'A minha chave j\u00e1 foi salva neste ambiente uma vez'\n# qk.IBMQ.save_account(chave)\n```\n\n    configrc.store_credentials:WARNING:2021-05-28 19:51:33,376: Credentials already present. Set overwrite=True to overwrite.\n\n\n\n```python\n# Carregar a conta na sess\u00e3o atual\nqk.IBMQ.load_account()\n```\n\n    ibmqfactory.load_account:WARNING:2021-05-28 21:37:16,733: Credentials are already in use. The existing account in the session will be replaced.\n\n\n\n\n\n    <AccountProvider for IBMQ(hub='ibm-q', group='open', project='main')>\n\n\n\nCarregamos nosso usu\u00e1rio na c\u00e9lula anterior. Agora precisamos indicar um provedor de servi\u00e7o. O provedor de servi\u00e7o default \u00e9 apresentado a seguir apenas por uma quest\u00e3o did\u00e1tica, pois ele j\u00e1 foi carregado pelo comando `qk.IBMQ.load_account()`. Para tornar nosso trabalho mais estruturado definimos este provedor como `provider_1`. O provedor precisa de um backend (uma m\u00e1quina) tal como no caso anterior. Usaremos para o provedor default (`provider_1`) o backend do simulador da IBM `ibmq_qasm_simulator`. Observe que agora o simulador roda na nuvem.\n\n\n```python\n# O provedor default (p\u00fablico) \u00e9 hub='ibm-q', group='open, project='main'\n# O c\u00f3digo abaixo \u00e9 executado para conhecimento\nprovider_1 = qk.IBMQ.get_provider(hub='ibm-q', group='open', project='main')\n\n# No provedor p\u00fablico vamos utilizar o simulador de nuvem\nbackend_1 = provider_1.get_backend('ibmq_qasm_simulator')\n```\n\nUtilizarei tamb\u00e9m o provedor de servi\u00e7os para institui\u00e7\u00f5es de ensino da IBM. Os dados podem ser vistos a seguir. Neste caso chamaremos este provedor de `provider_2`. Para o caso do `provider_2` vamos utilizar como backend uma m\u00e1quina real, por exemplo a `ibmq_jakarta`. Outras m\u00e1quinas poderiam ter sido utilizadas. Para uma lista completa, devemos olhar as m\u00e1quinas dispon\u00edveis para a nossa conta em `https://quantum-computing.ibm.com`.\n\n\n```python\n# Utilizaremos tamb\u00e9m o provedor abaixo, o qual tem jobs ilimitados\nprovider_2 = qk.IBMQ.get_provider(hub='ibm-q-education', group='fgv-1', project='ml-business-app')\n\n# Para este provedor utilizaremos a m\u00e1quina ibmq_jakarta\nbackend_2 = provider_2.get_backend('ibmq_jakarta')\n```\n\nNeste segundo exemplo vamos criar um circuito um pouco distinto. Vamos gerar um n\u00famero ao acaso entre 0 e 7. Para isso precisamos de 3 Qubits. Cada Qubit vai gerar um n\u00famero 0 ou 1 ao acaso. Ao final combinamos os 3 n\u00fameros bin\u00e1rios de 1 d\u00edgito em um n\u00famero bin\u00e1rio de 3 d\u00edgitos e convertemos o mesmo para base decimal. O circuito pode ser visto a seguir.\n\n\n```python\n# Com n Qubits pode-se gerar um n\u00famero aleat\u00f3rio entre 0 e 2^n - 1\nn = 3\n\nq = qk.QuantumRegister(n)\nc = qk.ClassicalRegister(n)\ncirc = qk.QuantumCircuit(q, c)\n\n# Aplicando um Hadamart nos 3 Qubits\nfor i in range(n):\n  circ.h(q[i])\n\n# Efetuando a medida\ncirc.measure(q,c)\n\n# Visualisando o circuito\ncirc.draw('mpl') \n```\n\nO comando a seguir envia o pedido de uma amostra (um \"shot\") para o backend escolhido (`ibmq_jakarta`) atrav\u00e9s do nosso provedor (`provider_2`). Se olharmos a nossa fila, na nossa conta, no site `https://quantum-computing.ibm.com` veremos que temos um *job* enviado para a m\u00e1quina `ibmq_jakarta`. \n\n\n```python\n# qk.execute envia para o backend. Conferindo no iqmq explorer aparece o job\nnew_job = qk.execute(circ, backend_2, shots=1)\n```\n\nDepois que o c\u00f3digo for executado, o resultado \u00e9 devolvido da mesma forma que na simula\u00e7\u00e3o local atrav\u00e9s de um dicion\u00e1rio python. Observe que no caso da simula\u00e7\u00e3o que gerou este arquivo, a m\u00e1quina devolveu `110:1`, ou seja uma contagem (uma medi\u00e7\u00e3o) e o resultado desta \u00fanica medi\u00e7\u00e3o foi o estado `110` do conjunto de tr\u00eas qubits. Observe que neste caso cada Qubit estava em sobreposi\u00e7\u00e3o apenas consigo mesmo, ou seja os Qubits n\u00e3o estavam entrela\u00e7ados entre si.\n\n\n```python\n# este resultado fica armazenado local. Por\u00e9m s\u00f3 estar\u00e1 dispon\u00edvel depois \n#  do job ter sido executado. Ele retorna um dicion\u00e1rio python.\nnew_job.result().get_counts()\n```\n\n\n\n\n    {'110': 1}\n\n\n\nA partir deste ponto s\u00e3o mostradas as etapas em linguagem python para converter a chave `110` deste dicion\u00e1rio python de resultados em um n\u00famero decimal. A parte \"qu\u00e2ntica\" do nosso programa Python terminou aqui.\n\n\n```python\n# Extraimos as chaves deste dicion\u00e1rio python\nnew_job.result().get_counts().keys()\n```\n\n\n\n\n    dict_keys(['110'])\n\n\n\n\n```python\n# Convertemos as chaves em uma lista\nlist(new_job.result().get_counts().keys())\n```\n\n\n\n\n    ['110']\n\n\n\n\n```python\n# Obtemos o primeiro elemento da lista\nlist(new_job.result().get_counts().keys())[0]\n```\n\n\n\n\n    '110'\n\n\n\n\n```python\n# Convertemos em um n\u00famero inteiro decimal\nint(list(new_job.result().get_counts().keys())[0])\n```\n\n\n\n\n    110\n\n\n\n\n```python\n# Convertemos em um n\u00famero inteiro bin\u00e1rio e obtemos sua representa\u00e7\u00e3o decimal\nint(list(new_job.result().get_counts().keys())[0],2)\n```\n\n\n\n\n    6\n\n\n\nObtivemos ent\u00e3o como resultado o n\u00famero 6.\n\n#### Exerc\u00edcios de Cria\u00e7\u00e3o e Execu\u00e7\u00e3o de Programas em Qiskit\n\nPara manter as se\u00e7\u00f5es independentes, apresentamos abaixo o c\u00f3digo para setup do ambiente. A parte de setup da qiskit \u00e9 mantida inativa para evitar a instala\u00e7\u00e3o repetida em um mesmo jupyter notebook.\n\n\n```python\nexecuta = False\n\nif executa:\n  !pip install qiskit -q\n  !pip install qiskit[visualization] -q\n\nimport numpy as np\nnp.set_printoptions(precision=3, suppress=True)\nfrom matplotlib import pyplot as plt\n%matplotlib inline\n\nimport pandas as pd\nimport sklearn as sk\nimport qiskit as qk\n```\n\n##### Parte I: Obten\u00e7\u00e3o de contagens\n\n**1o Circuito** Cria\u00e7\u00e3o, Execu\u00e7\u00e3o e Obten\u00e7\u00e3o de Contagens\n\n\n```python\nfrom qiskit import QuantumCircuit\ncircuit = QuantumCircuit(2, 2)\ncircuit.h(0)\ncircuit.cx(0,1)\ncircuit.measure([0,1], [0,1])\ndisplay(circuit.draw('mpl'))\n\nfrom qiskit.providers.aer import AerSimulator\nAerSimulator().run(circuit, shots=1000).result().get_counts()\n```\n\n**1o Circuito - 2a Simula\u00e7\u00e3o** Execu\u00e7\u00e3o e Obten\u00e7\u00e3o de Contagens\n\n\n```python\nAerSimulator().run(circuit, shots = 1000).result().get_counts()\n```\n\n\n\n\n    {'00': 521, '11': 479}\n\n\n\n**2o Circuito** Cria\u00e7\u00e3o, Execu\u00e7\u00e3o e Obten\u00e7\u00e3o de Contagens\n\n\n```python\nfrom qiskit import QuantumCircuit\ncircuito = QuantumCircuit(3,3)\nfor i in range(3):\n  circuito.h(i)\n  circuito.measure(i,i)\ndisplay(circuito.draw('mpl'))\n\nfrom qiskit.providers.aer import AerSimulator\nAerSimulator().run(circuito, shots = 1).result().get_counts()\n```\n\n**3o Circuito** Cria\u00e7\u00e3o, Execu\u00e7\u00e3o e Obten\u00e7\u00e3o de Contagens\n\n\n```python\nfrom qiskit import QuantumCircuit\nqc = QuantumCircuit(4,4)\nqc.x([0,1])\nqc.cx([0,1],[2,2])\nqc.ccx(0,1,3)\nqc.measure([0,1,2,3],[0,1,2,3])\ndisplay(qc.draw(output='mpl'))\n\nfrom qiskit.providers.aer import AerSimulator\nAerSimulator().run(qc, shots = 2048).result().get_counts()\n```\n\n**4o Circuito** Cria\u00e7\u00e3o, Execu\u00e7\u00e3o e Obten\u00e7\u00e3o de Contagens\n\n\n```python\nfrom qiskit import QuantumCircuit\nqc = QuantumCircuit(1,1)\nqc.x(0)\nqc.h(0)\nqc.h(0)\nqc.measure(0,0)\ndisplay(qc.draw(output='mpl'))\n\nfrom qiskit.providers.aer import AerSimulator\nAerSimulator().run(qc, shots=1).result().get_counts()\n```\n\n##### Parte II: Observa\u00e7\u00e3o do Vetor de Estados de um Circuito Qu\u00e2ntico\n\n**Exerc\u00edcio 1** Cria\u00e7\u00e3o de um circuito com um Qubit (registrador qu\u00e2ntico), um Bit (registrador cl\u00e1ssico), um gate NOT e uma medida. Determina\u00e7\u00e3o do vetor de estados do Qubit, da matriz de transforma\u00e7\u00e3o do circuito (antes da medida) e do resultado de 1.000 medidas efetuadas no Qubit.\n\n\n```python\n# Importa\u00e7\u00e3o da biblioteca qiskit\nimport qiskit as qk\n\n# Cria\u00e7\u00e3o de um registrador qu\u00e2ntico\nqr = qk.QuantumRegister(1)\n\n# Cria\u00e7\u00e3o de um registrador cl\u00e1ssico\ncr = qk.ClassicalRegister(1)\n\n# Cria\u00e7\u00e3o de um circuito qu\u00e2ntico composto de um registrador tipo \n#  Qubit e um registrador tipo Bit.\ncircuito = qk.QuantumCircuit(qr, cr)\nprint(\"Circuito 1 - Apenas os Registradores\")\nprint(circuito.draw())\n```\n\n    Circuito 1 - Apenas os Registradores\n            \n    q815_0: \n            \n     c98: 1/\n            \n\n\n\n```python\n# Executar a c\u00e9lula anterior\n# Inser\u00e7\u00e3o de uma porta l\u00f3gica x (NOT Gate) no circuito\ncircuito.x(qr)\nprint(\"Circuito 1 - Registradores e gate X no registrador qu\u00e2ntico\")\nprint(circuito.draw())\n```\n\n    Circuito 1 - Registradores e gate X no registrador qu\u00e2ntico\n            \u250c\u2500\u2500\u2500\u2510\n    q815_0: \u2524 X \u251c\n            \u2514\u2500\u2500\u2500\u2518\n     c98: 1/\u2550\u2550\u2550\u2550\u2550\n                 \n\n\n\n```python\n# Executar a c\u00e9lula anterior\n# Determina\u00e7\u00e3o do vetor de estados do registrador qu\u00e2ntico\njob = qk.execute(experiments = circuito, \n                 backend = qk.BasicAer.get_backend('statevector_simulator'))\nprint(\"Vetor de Estado do Registrador Qu\u00e2ntico\")\nfrom qiskit.tools.visualization import plot_bloch_multivector\ndisplay(plot_bloch_multivector(job.result().get_statevector()))\n```\n\n\n```python\n# Executar a c\u00e9lula anterior\n# Determina\u00e7\u00e3o da matriz de transforma\u00e7\u00e3o do circuito (at\u00e9 este vetor de estados)\njob = qk.execute(experiments = circuito,\n                 backend = qk.BasicAer.get_backend('unitary_simulator'))\nprint(\"Matriz de Transforma\u00e7\u00e3o (at\u00e9 este ponto)\")\nprint(job.result().get_unitary())\n```\n\n    Matriz de Transforma\u00e7\u00e3o (at\u00e9 este ponto)\n    [[0.+0.j 1.+0.j]\n     [1.+0.j 0.+0.j]]\n\n\n\n```python\n# Executar a c\u00e9lula anterior\n# Inser\u00e7\u00e3o de uma medida no registrador qu\u00e2ntico\ncircuito.measure(qr, cr)\nprint(\"Circuito 1 - Registradores, gate X e medida no registrador qu\u00e2ntico\")\nprint(circuito.draw())\n```\n\n    Circuito 1 - Registradores, gate X e medida no registrador qu\u00e2ntico\n            \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2510\n    q815_0: \u2524 X \u251c\u2524M\u251c\n            \u2514\u2500\u2500\u2500\u2518\u2514\u2565\u2518\n     c98: 1/\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\n                  0 \n\n\n\n```python\n# Executar a c\u00e9lula anterior\n# Execu\u00e7\u00e3o de mil medidas no registrador qu\u00e2ntico\nprint(\"Mil medidas do estado do registrador qu\u00e2ntico\")\njob = qk.execute(experiments = circuito, \n                 backend = qk.BasicAer.get_backend('qasm_simulator'),\n                 shots = 1000)\n```\n\n    Mil medidas do estado do registrador qu\u00e2ntico \n    \n\n\n\n```python\n# Executar a c\u00e9lula anterior\n# Contagem dos resultados das medidas no registrador qu\u00e2ntico\nprint(\"Contagem dos Resultados\")\nprint(job.result().get_counts())\n```\n\n    Contagem dos Resultados\n    {'1': 1000}\n\n\n\n```python\n# Executar a c\u00e9lula anterior\n# Histograma dos resultados das medidas no registrador qu\u00e2ntico\nprint(\"Histograma dos Resultados\")\nfrom qiskit.tools.visualization import plot_histogram\nplot_histogram(data = job.result().get_counts(), figsize=(4,3))\n```\n\n**Exerc\u00edcio 2** Teletransporte do estado de um Qubit para outro.\n\n\n```python\nqk.BasicAer.backends()\n```\n\n\n\n\n    [<QasmSimulatorPy('qasm_simulator')>,\n     <StatevectorSimulatorPy('statevector_simulator')>,\n     <UnitarySimulatorPy('unitary_simulator')>]\n\n\n\n\n```python\nimport qiskit as qk\n\ncircuito = qk.QuantumCircuit(2,2)\n#circuito.h(0)\ncircuito.cnot(0,1)\ncircuito.barrier()\nprint(circuito.draw())\njob = qk.execute(experiments = circuito,\n                 backend = qk.BasicAer.get_backend('unitary_simulator'))\n\nimport numpy as np\nnp.set_printoptions(precision=2) \ndisplay(np.real(job.result().get_unitary()))\n```\n\n               \u2591 \n    q_0: \u2500\u2500\u25a0\u2500\u2500\u2500\u2591\u2500\n         \u250c\u2500\u2534\u2500\u2510 \u2591 \n    q_1: \u2524 X \u251c\u2500\u2591\u2500\n         \u2514\u2500\u2500\u2500\u2518 \u2591 \n    c: 2/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n                 \n\n\n\n    array([[1., 0., 0., 0.],\n           [0., 0., 0., 1.],\n           [0., 0., 1., 0.],\n           [0., 1., 0., 0.]])\n\n\n##### Parte III: Circuitos com v\u00e1rias portas l\u00f3gicas qu\u00e2nticas\n\n\n```python\n!pip install qiskit\nimport qiskit as qk\n\nprovider0 = qk.BasicAer\nbackend0 = provider0.get_backend('qasm_simulator')\n\n# Chave de APIs obtida em https://quantum-computing.ibm.com\nchave1 = '4ae468408574abb7fd53a78dd2e0a256b2be7cd68be45c0741e7c670c0947e57eb8'\nchave2 = 'd71706bd6280aa83ec5ffb15137ba2f61ba77273bd12c9eaf196d00fabbe7'\nchave = chave1 + chave2\nqk.IBMQ.save_account(chave)\n\nqk.IBMQ.load_account()\n\nprovider1 = qk.IBMQ.get_provider(hub='ibm-q', group='open', \n                                 project='main')\nbackend1 = provider1.get_backend('ibmq_qasm_simulator')\n\nprovider2 = qk.IBMQ.get_provider(hub='ibm-q-education', group='fgv-1', \n                                 project='ml-business-app')\nbackend2 = provider2.get_backend('ibmq_jakarta')\n```\n\n\n```python\nlist(qk.__qiskit_version__.items())\n```\n\n\n\n\n    [('qiskit-terra', '0.17.4'),\n     ('qiskit-aer', '0.8.2'),\n     ('qiskit-ignis', '0.6.0'),\n     ('qiskit-ibmq-provider', '0.13.1'),\n     ('qiskit-aqua', '0.9.1'),\n     ('qiskit', None),\n     ('qiskit-nature', None),\n     ('qiskit-finance', None),\n     ('qiskit-optimization', None),\n     ('qiskit-machine-learning', None)]\n\n\n\nO primeiro circuito ser\u00e1 composto de um Qubit e um bit. O Qubit \u00e9 inicializado no estado $|{0}\\rangle$, passa por uma porta X (NOT gate) e em seguida \u00e9 feita uma medida. \n\n\n\n```python\nq = qk.QuantumRegister(1)\nc = qk.ClassicalRegister(1)\ncircuito1 = qk.QuantumCircuit(q, c)\ncircuito1.reset(q[0])\ncircuito1.measure(q, c)\nprint(circuito1)\n```\n\n               \u250c\u2500\u2510\n    q0_0: \u2500|0>\u2500\u2524M\u251c\n               \u2514\u2565\u2518\n    c0: 1/\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\n                0 \n\n\nAbaixo executamos 10 amostras (*shots*) do circuito, no `backend2` o qual foi configurado para corresponder \u00e0 maquina `ibmq_jakarta`. \n\n\n```python\njobBackend2 = qk.execute(circuito1, backend2, shots=10)\n```\n\nLembre-se que neste caso, a impress\u00e3o dos resultados deve ficar em outra c\u00e9lula, caso contr\u00e1rio o Jupyter notebook ficar\u00e1 \"travado\", a espera do job ser executado na m\u00e1quina f\u00edsica correspondente.\n\n\n```python\njobBackend2.result().get_counts()\n```\n\n\n\n\n    {'0': 8, '1': 2}\n\n\n\nPara os demais circuitos e simula\u00e7\u00f5es deste Jupyter notebook vamos executa-las no simulador local `BasicAer`, o qual foi configurado com o nome de `backend0`. \n\n\n```python\njobLocal0 = qk.execute(circuito1, backend0, shots=1000)\ncounts = jobLocal0.result().get_counts(circuito1)\nprint(counts)\n```\n\n    {'0': 1000}\n\n\n\n```python\nq = qk.QuantumRegister(2)\nc = qk.ClassicalRegister(2)\ncircuito2 = qk.QuantumCircuit(q, c)\ncircuito2.reset(q[0])\ncircuito2.measure(q[0], c[0])\n\ncircuito2.reset(q[1])\ncircuito2.measure(q[1], c[1])\ncircuito2.draw()\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">            \u250c\u2500\u2510   \nq22_0: \u2500|0>\u2500\u2524M\u251c\u2500\u2500\u2500\n            \u2514\u2565\u2518\u250c\u2500\u2510\nq22_1: \u2500|0>\u2500\u2500\u256b\u2500\u2524M\u251c\n             \u2551 \u2514\u2565\u2518\nc10: 2/\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\n             0  1 </pre>\n\n\n\n\n```python\njob2 = qk.execute(circuito2, backend0, shots=1000)\njob2.result().get_counts()\n```\n\n\n\n\n    {'00': 1000}\n\n\n\n\n```python\nq = qk.QuantumRegister(1)\nc = qk.ClassicalRegister(1)\ncircuito3 = qk.QuantumCircuit(q, c)\ncircuito3.reset(q[0])\ncircuito3.h(q[0])\ncircuito3.measure(q[0],c[0])\nprint(circuito3.draw())\njob3 = qk.execute(circuito3, backend0, shots=1000)\njob3.result().get_counts()\n```\n\n                \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2510\n    q40_0: \u2500|0>\u2500\u2524 H \u251c\u2524M\u251c\n                \u2514\u2500\u2500\u2500\u2518\u2514\u2565\u2518\n    c13: 1/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\n                      0 \n\n\n\n\n\n    {'0': 492, '1': 508}\n\n\n\n\n```python\nq = qk.QuantumRegister(1)\nc = qk.ClassicalRegister(1)\ncircuito4 = qk.QuantumCircuit(q, c)\ncircuito4.reset(q[0])\ncircuito4.x(q[0])\ncircuito4.h(q[0])\ncircuito4.h(q[0])\ncircuito4.measure(q[0], c[0])\nprint(circuito4)\njob4 = qk.execute(circuito4, backend0, shots=1000)\njob4.result().get_counts()\n```\n\n                \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2510\n    q60_0: \u2500|0>\u2500\u2524 X \u251c\u2524 H \u251c\u2524 H \u251c\u2524M\u251c\n                \u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2565\u2518\n    c16: 1/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\n                                0 \n\n\n\n\n\n    {'1': 1000}\n\n\n\n\n```python\nq = qk.QuantumRegister(2)\nc = qk.ClassicalRegister(2)\ncircuito5 = qk.QuantumCircuit(q,c)\ncircuito5.reset(q)\ncircuito5.h(q)\ncircuito5.measure(q,c)\nprint(circuito5)\njob5 = qk.execute(circuito5, backend0, shots=1000)\njob5.result().get_counts()\n```\n\n                \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2510   \n    q93_0: \u2500|0>\u2500\u2524 H \u251c\u2524M\u251c\u2500\u2500\u2500\n                \u251c\u2500\u2500\u2500\u2524\u2514\u2565\u2518\u250c\u2500\u2510\n    q93_1: \u2500|0>\u2500\u2524 H \u251c\u2500\u256b\u2500\u2524M\u251c\n                \u2514\u2500\u2500\u2500\u2518 \u2551 \u2514\u2565\u2518\n    c28: 2/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\n                      0  1 \n\n\n\n\n\n    {'00': 253, '01': 247, '10': 240, '11': 260}\n\n\n\n\n```python\nq = qk.QuantumRegister(2)\nc = qk.ClassicalRegister(2)\ncircuito6 = qk.QuantumCircuit(q, c)\ncircuito6.reset(q)\ncircuito6.h(q[0])\ncircuito6.cnot(q[0],q[1])\ncircuito6.measure(q,c)\nprint(circuito6)\njob6 = qk.execute(circuito6, backend0, shots=1000)\njob6.result().get_counts()\n```\n\n                 \u250c\u2500\u2500\u2500\u2510     \u250c\u2500\u2510   \n    q107_0: \u2500|0>\u2500\u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524M\u251c\u2500\u2500\u2500\n                 \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2534\u2500\u2510\u2514\u2565\u2518\u250c\u2500\u2510\n    q107_1: \u2500|0>\u2500\u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\u2500\u256b\u2500\u2524M\u251c\n                      \u2514\u2500\u2500\u2500\u2518 \u2551 \u2514\u2565\u2518\n     c33: 2/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\n                            0  1 \n\n\n\n\n\n    {'00': 511, '11': 489}\n\n\n\n##### Parte IV: Circuito de \"tele-transporte\" (do estado de Qubit para outro)\n\n\n```python\n# Instala\u00e7\u00e3o do Pacote Qiskit (executar uma vez por sess\u00e3o)\n!pip install qiskit\n```\n\n\n```python\n# Importa\u00e7\u00e3o da Biblioteca\nimport qiskit as qk\n```\n\n\n```python\n# Cria\u00e7\u00e3o de um circuito com 3 Qubits e 3 Bits\ncircuito = qk.QuantumCircuit(3,3)\n```\n\n\n```python\n# Desenho do circuito at\u00e9 o momento\nprint(circuito.draw())\n```\n\n         \n    q_0: \n         \n    q_1: \n         \n    q_2: \n         \n    c: 3/\n         \n\n\n\n```python\n# Cria\u00e7\u00e3o de um backend para simula\u00e7\u00e3o do vetor de estados\nsim_estados = qk.BasicAer.get_backend(\"statevector_simulator\")\n```\n\n\n```python\n# Cria\u00e7\u00e3o de um job para visualiza\u00e7\u00e3o do vetor de estados neste\n#  ponto do circuito\nresultado = qk.execute(experiments = circuito,\n                       backend = sim_estados).result()\n```\n\n\n```python\n# Ajuste do formato de impress\u00e3o da numpy\nimport numpy as np\nnp.set_printoptions(precision=3, suppress=True)\n```\n\n\n```python\n# Impress\u00e3o dos poss\u00edveis estados dos tr\u00eas qubits e\n#  do vetor de estados correspondente. Observe que\n#  o estado '000' aparece com o valor 1\nprint([np.binary_repr(x, width=3) for x in range(8)])\nprint(resultado.get_statevector(circuito))\n```\n\n    ['000', '001', '010', '011', '100', '101', '110', '111']\n    [1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n\n\n\n```python\n# Importa\u00e7\u00e3o da fun\u00e7\u00e3o para desenho da Bloch Sphere \nfrom qiskit.tools.visualization import plot_bloch_multivector\n```\n\n\n```python\n# Apresentamos as esferas de Bloch com a ordem dos Qubits \n#  invertida (mais significativo \u00e0 esquerda), para tornar\n#  mais f\u00e1cil a visualiza\u00e7\u00e3o da sequ\u00eancia de estados\nprint(\"Representa\u00e7\u00e3o do vetor de estados pela Bloch Sphere\")\nplot_bloch_multivector(resultado.get_statevector(circuito),\n                               reverse_bits=True)\n```\n\n\n```python\n# Inser\u00e7\u00e3o de uma porta X (NOT gate) no Qubit 0\ncircuito.x(0)\n```\n\n\n\n\n    <qiskit.circuit.instructionset.InstructionSet at 0x7fdabc35be90>\n\n\n\n\n```python\ncircuito.draw()\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">     \u250c\u2500\u2500\u2500\u2510\nq_0: \u2524 X \u251c\n     \u2514\u2500\u2500\u2500\u2518\nq_1: \u2500\u2500\u2500\u2500\u2500\n\nq_2: \u2500\u2500\u2500\u2500\u2500\n\nc: 3/\u2550\u2550\u2550\u2550\u2550\n          </pre>\n\n\n\n\n```python\n# Inser\u00e7\u00e3o de uma barreira. Serve para preservar o circuito\n# entre compila\u00e7\u00f5es e execu\u00e7\u00f5es.\ncircuito.barrier()\n```\n\n\n\n\n    <qiskit.circuit.instructionset.InstructionSet at 0x7fdabc353350>\n\n\n\n\n```python\ncircuito.draw()\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">     \u250c\u2500\u2500\u2500\u2510 \u2591 \nq_0: \u2524 X \u251c\u2500\u2591\u2500\n     \u2514\u2500\u2500\u2500\u2518 \u2591 \nq_1: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\n           \u2591 \nq_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\n           \u2591 \nc: 3/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n             </pre>\n\n\n\n\n```python\n# Vetor de estado do circuito ap\u00f3s o gate X ser aplicado no\n#  Qubit 0. \nresultado = qk.execute(experiments = circuito,\n                       backend = sim_estados).result()\nprint([np.binary_repr(x,width=3) for x in range(8)])\nprint(resultado.get_statevector())\n```\n\n    ['000', '001', '010', '011', '100', '101', '110', '111']\n    [0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n\n\n\n```python\n#Observe a altera\u00e7\u00e3o do vetor na Bloch Sphere correspondente.\nresultado = qk.execute(experiments = circuito, \n                       backend = sim_estados).result()\nplot_bloch_multivector(resultado.get_statevector(), reverse_bits=True)\n```\n\n\n```python\n# Colocar o Qubit 1 em superposi\u00e7\u00e3o atrav\u00e9s de\n#  um Hadamard Gate\ncircuito.h(1)\n```\n\n\n\n\n    <qiskit.circuit.instructionset.InstructionSet at 0x7fdabc3ad390>\n\n\n\n\n```python\ncircuito.draw()\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">     \u250c\u2500\u2500\u2500\u2510 \u2591      \nq_0: \u2524 X \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\n     \u2514\u2500\u2500\u2500\u2518 \u2591 \u250c\u2500\u2500\u2500\u2510\nq_1: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524 H \u251c\n           \u2591 \u2514\u2500\u2500\u2500\u2518\nq_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\n           \u2591      \nc: 3/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n                  </pre>\n\n\n\n\n```python\n# Vetor de Estados do Circuito ap\u00f3s a coloca\u00e7\u00e3o do Qubit\n#  1 em sobreposi\u00e7\u00e3o.\nresultado = qk.execute(experiments = circuito,\n                       backend = sim_estados).result()\nprint(resultado.get_statevector())\n```\n\n    [0.   +0.j 0.707+0.j 0.   +0.j 0.707+0.j 0.   +0.j 0.   +0.j 0.   +0.j\n     0.   +0.j]\n\n\n\n```python\n# Apresentando o statevector com valores inteiros.\n#  Observe que a sobreposi\u00e7\u00e3o no Qubit 1 faz com\n#  que o vetor de estados tenha 1 nas posi\u00e7\u00f5es do \n#  vetor relativas aos estados \"001\" e \"011\".\n#  Lembre-se:\n#  1o) As posi\u00e7\u00f5es dos estados s\u00e3o: q2, q1, q0 e\n#  2o) Os Qubits q2 e q0 est\u00e3o em |0> e |1>\n#  3o) O Qubit q1 est\u00e1 em sobreposi\u00e7\u00e3o de |0> e |1>\nresultado = qk.execute(experiments = circuito, \n                       backend = sim_estados).result()\nprint([np.binary_repr(x,width=3) for x in range(8)])\nprint(resultado.get_statevector()*np.sqrt(2))\n```\n\n    ['000', '001', '010', '011', '100', '101', '110', '111']\n    [0.+0.j 1.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n\n\n\n```python\nplot_bloch_multivector(resultado.get_statevector(),\n                       reverse_bits=True)\n```\n\n\n```python\n# Entrela\u00e7amento entre os qubits 1 e 2 atrav\u00e9s de um\n#  CNOT gate com controle em q1 e alvo em q2. \ncircuito.cnot(1,2)\n```\n\n\n```python\ncircuito.draw()\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">     \u250c\u2500\u2500\u2500\u2510 \u2591           \nq_0: \u2524 X \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n     \u2514\u2500\u2500\u2500\u2518 \u2591 \u250c\u2500\u2500\u2500\u2510     \nq_1: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\n           \u2591 \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2534\u2500\u2510\nq_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\n           \u2591      \u2514\u2500\u2500\u2500\u2518\nc: 3/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n                       </pre>\n\n\n\n\n```python\n# O entrela\u00e7amento faz os qubits q2 e q1 irem para |00> \n#  ou |11>. O qubit q0 continua em |1>. Logo os estados\n#  do conjunto ficam |001> e |111>\nresultado = qk.execute(circuito, sim_estados).result()\nprint([np.binary_repr(x, width=3) for x in range(8)])\nprint((resultado.get_statevector()*np.sqrt(2)))\n```\n\n    ['000', '001', '010', '011', '100', '101', '110', '111']\n    [0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j]\n\n\n\n```python\n# Tal como era de se esperar, n\u00e3o \u00e9 mais poss\u00edvel mostrar\n#  o estado de cada Qubit entrela\u00e7ado de forma individual\n#  Observe que o Qubit 2 por exemplo n\u00e3o est\u00e1 mais no \n#  estado individual |0> em conjunto com o estado |0> do\n#  Qubit 1. Os Qubits 2 e 1 formam agora um bloco \n#  indivis\u00edvel o qual est\u00e1 em sobreposi\u00e7\u00e3o de |00> e |11>\nresultado = qk.execute(circuito, sim_estados).result()\nplot_bloch_multivector(resultado.get_statevector(),\n                       reverse_bits=True)\n```\n\n\n```python\n# CNOT gate entre o Qubit q0 (controle) e\n#  o Qubit q1 (alvo)\ncircuito.cnot(0,1)\n```\n\n\n```python\ncircuito.draw()\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">     \u250c\u2500\u2500\u2500\u2510 \u2591                \nq_0: \u2524 X \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\n     \u2514\u2500\u2500\u2500\u2518 \u2591 \u250c\u2500\u2500\u2500\u2510     \u250c\u2500\u2534\u2500\u2510\nq_1: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 X \u251c\n           \u2591 \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2534\u2500\u2510\u2514\u2500\u2500\u2500\u2518\nq_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\u2500\u2500\u2500\u2500\u2500\n           \u2591      \u2514\u2500\u2500\u2500\u2518     \nc: 3/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n                            </pre>\n\n\n\n\n```python\n# Observe agora o resultado da aplica\u00e7\u00e3o de um CNOT \n#  gate em q0 (controle) e q1 (alvo). O estado inicial\n#  era |q2, q1, q0> = |001> e |111>.  O CNOT com controle\n#  em q0 inverte o estado de q1. Isto vai gerar como \n#  resultado |011> e |101>. O interessante aqui \u00e9 que \n#  foi alterado o estado de um dos Qubits previamente\n#  entrela\u00e7ados, mas isto n\u00e3o se refletiu no Qubit q2.\n\n# Isto \u00e9 importante. Pode-se afetar o estado de um dos\n#  Qubits entrela\u00e7ado. Isto n\u00e3o vai se refletir no \n#  estado do 2o Qubit. O entrela\u00e7amento s\u00f3 \"aparece\"\n#  quando efetuamos uma medida. Isto quer dizer que\n#  caso tiv\u00e9ssemos feito uma medida agora, o \n#  entrela\u00e7amento entre q1 e q2 iria se manifestar \n#  pelos estados 01 e 10, os \u00fanicos que iriam\n#  aparecer na saida.\n\nresultado = qk.execute(circuito, sim_estados).result()\nprint([np.binary_repr(x,width=3) for x in range(8)])\nprint(resultado.get_statevector()*np.sqrt(2))\n```\n\n    ['000', '001', '010', '011', '100', '101', '110', '111']\n    [0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j]\n\n\n\n```python\n# Aplica\u00e7\u00e3o de um Hadamard gate em q0\ncircuito.h(0)\n```\n\n\n\n\n    <qiskit.circuit.instructionset.InstructionSet at 0x7fdabbb69610>\n\n\n\n\n```python\ncircuito.draw()\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">     \u250c\u2500\u2500\u2500\u2510 \u2591                \u250c\u2500\u2500\u2500\u2510\nq_0: \u2524 X \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 H \u251c\n     \u2514\u2500\u2500\u2500\u2518 \u2591 \u250c\u2500\u2500\u2500\u2510     \u250c\u2500\u2534\u2500\u2510\u2514\u2500\u2500\u2500\u2518\nq_1: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 X \u251c\u2500\u2500\u2500\u2500\u2500\n           \u2591 \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2534\u2500\u2510\u2514\u2500\u2500\u2500\u2518     \nq_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n           \u2591      \u2514\u2500\u2500\u2500\u2518          \nc: 3/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n                                 </pre>\n\n\n\n\n```python\ncircuito.barrier()\n```\n\n\n\n\n    <qiskit.circuit.instructionset.InstructionSet at 0x7fdabbad6850>\n\n\n\n\n```python\ncircuito.draw()\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">     \u250c\u2500\u2500\u2500\u2510 \u2591                \u250c\u2500\u2500\u2500\u2510 \u2591 \nq_0: \u2524 X \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 H \u251c\u2500\u2591\u2500\n     \u2514\u2500\u2500\u2500\u2518 \u2591 \u250c\u2500\u2500\u2500\u2510     \u250c\u2500\u2534\u2500\u2510\u2514\u2500\u2500\u2500\u2518 \u2591 \nq_1: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 X \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\n           \u2591 \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2534\u2500\u2510\u2514\u2500\u2500\u2500\u2518      \u2591 \nq_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\n           \u2591      \u2514\u2500\u2500\u2500\u2518           \u2591 \nc: 3/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n                                    </pre>\n\n\n\n\n```python\n# Cria\u00e7\u00e3o de uma fun\u00e7\u00e3o lambda para gera\u00e7\u00e3o dos\n#  estados bin\u00e1rios poss\u00edveis dos tr\u00eas qubits\nestados = lambda n : [np.binary_repr(x, width=n) for x in range(2**n)]\nestados(3)\n```\n\n\n\n\n    ['000', '001', '010', '011', '100', '101', '110', '111']\n\n\n\n\n```python\nresultado = qk.execute(circuito,\n               qk.BasicAer.get_backend('statevector_simulator')).result()\nprint(estados(3))\nprint(resultado.get_statevector()*2)\n```\n\n    ['000', '001', '010', '011', '100', '101', '110', '111']\n    [ 0.+0.j  0.+0.j  1.-0.j -1.+0.j  1.-0.j -1.+0.j  0.+0.j  0.+0.j]\n\n\n\n```python\n# Duas medidas, em q0 e q1\ncircuito.measure(0,0)\n```\n\n\n\n\n    <qiskit.circuit.instructionset.InstructionSet at 0x7fdabb6e9cd0>\n\n\n\n\n```python\ncircuito.draw()\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">     \u250c\u2500\u2500\u2500\u2510 \u2591                \u250c\u2500\u2500\u2500\u2510 \u2591 \u250c\u2500\u2510\nq_0: \u2524 X \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 H \u251c\u2500\u2591\u2500\u2524M\u251c\n     \u2514\u2500\u2500\u2500\u2518 \u2591 \u250c\u2500\u2500\u2500\u2510     \u250c\u2500\u2534\u2500\u2510\u2514\u2500\u2500\u2500\u2518 \u2591 \u2514\u2565\u2518\nq_1: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 X \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u256b\u2500\n           \u2591 \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2534\u2500\u2510\u2514\u2500\u2500\u2500\u2518      \u2591  \u2551 \nq_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u256b\u2500\n           \u2591      \u2514\u2500\u2500\u2500\u2518           \u2591  \u2551 \nc: 3/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\n                                     0 </pre>\n\n\n\n\n```python\ncircuito.measure(1,1)\n```\n\n\n\n\n    <qiskit.circuit.instructionset.InstructionSet at 0x7fdabb38f1d0>\n\n\n\n\n```python\ncircuito.draw()\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">     \u250c\u2500\u2500\u2500\u2510 \u2591                \u250c\u2500\u2500\u2500\u2510 \u2591 \u250c\u2500\u2510   \nq_0: \u2524 X \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 H \u251c\u2500\u2591\u2500\u2524M\u251c\u2500\u2500\u2500\n     \u2514\u2500\u2500\u2500\u2518 \u2591 \u250c\u2500\u2500\u2500\u2510     \u250c\u2500\u2534\u2500\u2510\u2514\u2500\u2500\u2500\u2518 \u2591 \u2514\u2565\u2518\u250c\u2500\u2510\nq_1: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 X \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2524M\u251c\n           \u2591 \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2534\u2500\u2510\u2514\u2500\u2500\u2500\u2518      \u2591  \u2551 \u2514\u2565\u2518\nq_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u256b\u2500\n           \u2591      \u2514\u2500\u2500\u2500\u2518           \u2591  \u2551  \u2551 \nc: 3/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\n                                     0  1 </pre>\n\n\n\n\n```python\ncircuito.barrier()\n```\n\n\n\n\n    <qiskit.circuit.instructionset.InstructionSet at 0x7fdabb391410>\n\n\n\n\n```python\ncircuito.draw()\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">     \u250c\u2500\u2500\u2500\u2510 \u2591                \u250c\u2500\u2500\u2500\u2510 \u2591 \u250c\u2500\u2510    \u2591 \nq_0: \u2524 X \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 H \u251c\u2500\u2591\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u2591\u2500\n     \u2514\u2500\u2500\u2500\u2518 \u2591 \u250c\u2500\u2500\u2500\u2510     \u250c\u2500\u2534\u2500\u2510\u2514\u2500\u2500\u2500\u2518 \u2591 \u2514\u2565\u2518\u250c\u2500\u2510 \u2591 \nq_1: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 X \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u2591\u2500\n           \u2591 \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2534\u2500\u2510\u2514\u2500\u2500\u2500\u2518      \u2591  \u2551 \u2514\u2565\u2518 \u2591 \nq_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2591\u2500\n           \u2591      \u2514\u2500\u2500\u2500\u2518           \u2591  \u2551  \u2551  \u2591 \nc: 3/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2550\u2550\n                                     0  1    </pre>\n\n\n\n\n```python\n# Para avaliar os resultados das medidas nos qubits q0 e q1\n#  criamos um novo simulador, agora de medidas\nsim_valores = qk.BasicAer.get_backend('qasm_simulator')\n```\n\n\n```python\n# Para apresentar os resultados das medi\u00e7\u00f5es, vamos utilizar\n#  outro recurso gr\u00e1fico da Qiskit: os histogramas de resultados\nfrom qiskit.tools.visualization import plot_histogram\n```\n\n\n```python\nresultado = qk.execute(circuito, sim_valores, shots=1000).result()\nplot_histogram(resultado.get_counts(), figsize=(5,3))\n```\n\n\n```python\n# Em seguida acrescentamos um CNOT em (1,2)\n#  1 = controle, 2 = alvo\ncircuito.cnot(1,2)\n```\n\n\n```python\ncircuito.draw()\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">     \u250c\u2500\u2500\u2500\u2510 \u2591                \u250c\u2500\u2500\u2500\u2510 \u2591 \u250c\u2500\u2510    \u2591      \nq_0: \u2524 X \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 H \u251c\u2500\u2591\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\n     \u2514\u2500\u2500\u2500\u2518 \u2591 \u250c\u2500\u2500\u2500\u2510     \u250c\u2500\u2534\u2500\u2510\u2514\u2500\u2500\u2500\u2518 \u2591 \u2514\u2565\u2518\u250c\u2500\u2510 \u2591      \nq_1: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 X \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u2591\u2500\u2500\u2500\u25a0\u2500\u2500\n           \u2591 \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2534\u2500\u2510\u2514\u2500\u2500\u2500\u2518      \u2591  \u2551 \u2514\u2565\u2518 \u2591 \u250c\u2500\u2534\u2500\u2510\nq_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2591\u2500\u2524 X \u251c\n           \u2591      \u2514\u2500\u2500\u2500\u2518           \u2591  \u2551  \u2551  \u2591 \u2514\u2500\u2500\u2500\u2518\nc: 3/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n                                     0  1         </pre>\n\n\n\n\n```python\n # Com sempre vamos observar o vetor de estados\n resultado = qk.execute(circuito, sim_estados).result()\n print(estados(3))\n print(resultado.get_statevector())\n```\n\n    ['000', '001', '010', '011', '100', '101', '110', '111']\n    [ 0.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j -1.+0.j  0.+0.j  0.+0.j]\n\n\n\n```python\nplot_bloch_multivector(resultado.get_statevector(),\n                       reverse_bits = True)\n```\n\n\n```python\n# Por \u00faltimo incluimos um Z gate entre as portas \n#  q0 e q2 ...\ncircuito.cz(0,2)\n```\n\n\n\n\n    <qiskit.circuit.instructionset.InstructionSet at 0x7fdabb1afa90>\n\n\n\n\n```python\ncircuito.draw()\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">     \u250c\u2500\u2500\u2500\u2510 \u2591                \u250c\u2500\u2500\u2500\u2510 \u2591 \u250c\u2500\u2510    \u2591         \nq_0: \u2524 X \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 H \u251c\u2500\u2591\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\n     \u2514\u2500\u2500\u2500\u2518 \u2591 \u250c\u2500\u2500\u2500\u2510     \u250c\u2500\u2534\u2500\u2510\u2514\u2500\u2500\u2500\u2518 \u2591 \u2514\u2565\u2518\u250c\u2500\u2510 \u2591       \u2502 \nq_1: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 X \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u2591\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u253c\u2500\n           \u2591 \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2534\u2500\u2510\u2514\u2500\u2500\u2500\u2518      \u2591  \u2551 \u2514\u2565\u2518 \u2591 \u250c\u2500\u2534\u2500\u2510 \u2502 \nq_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2591\u2500\u2524 X \u251c\u2500\u25a0\u2500\n           \u2591      \u2514\u2500\u2500\u2500\u2518           \u2591  \u2551  \u2551  \u2591 \u2514\u2500\u2500\u2500\u2518   \nc: 3/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n                                     0  1            </pre>\n\n\n\n\n```python\n# ... e uma medida em no Qubit 2\ncircuito.measure(2,2)\n```\n\n\n\n\n    <qiskit.circuit.instructionset.InstructionSet at 0x7fdabb1867d0>\n\n\n\n\n```python\ncircuito.draw()\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">     \u250c\u2500\u2500\u2500\u2510 \u2591                \u250c\u2500\u2500\u2500\u2510 \u2591 \u250c\u2500\u2510    \u2591            \nq_0: \u2524 X \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 H \u251c\u2500\u2591\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\n     \u2514\u2500\u2500\u2500\u2518 \u2591 \u250c\u2500\u2500\u2500\u2510     \u250c\u2500\u2534\u2500\u2510\u2514\u2500\u2500\u2500\u2518 \u2591 \u2514\u2565\u2518\u250c\u2500\u2510 \u2591       \u2502    \nq_1: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 X \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u2591\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\n           \u2591 \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2534\u2500\u2510\u2514\u2500\u2500\u2500\u2518      \u2591  \u2551 \u2514\u2565\u2518 \u2591 \u250c\u2500\u2534\u2500\u2510 \u2502 \u250c\u2500\u2510\nq_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2591\u2500\u2524 X \u251c\u2500\u25a0\u2500\u2524M\u251c\n           \u2591      \u2514\u2500\u2500\u2500\u2518           \u2591  \u2551  \u2551  \u2591 \u2514\u2500\u2500\u2500\u2518   \u2514\u2565\u2518\nc: 3/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\n                                     0  1             2 </pre>\n\n\n\n\n```python\n# Executando o circuito e obtendo as medidas\nresultado = qk.execute(circuito, sim_valores, shots=1000).result()\nplot_histogram(resultado.get_counts())\n```\n\n#### Qiskit - Fourier Checking\n\n\n```python\nimport qiskit.quantum_info as qi\nfrom qiskit.circuit.library import FourierChecking\nfrom qiskit.visualization import plot_histogram\n```\n\n\n```python\nf = [1,-1,-1,-1]\ng = [1,1,-1,-1]\n```\n\n\n```python\ncirc = FourierChecking(f=f, g=g)\ncirc.draw()\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">     \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\nq_0: \u2524 H \u251c\u25240                      \u251c\u2524 H \u251c\u25240                     \u251c\u2524 H \u251c\n     \u251c\u2500\u2500\u2500\u2524\u2502  DIAGONAL(1,-1,-1,-1) \u2502\u251c\u2500\u2500\u2500\u2524\u2502  DIAGONAL(1,1,-1,-1) \u2502\u251c\u2500\u2500\u2500\u2524\nq_1: \u2524 H \u251c\u25241                      \u251c\u2524 H \u251c\u25241                     \u251c\u2524 H \u251c\n     \u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518</pre>\n\n\n\n\n```python\nzero = qi.Statevector.from_label('00')\nsv = zero.evolve(circ)\nprobs = sv.probabilities_dict()\nplot_histogram(probs)\n```\n", "meta": {"hexsha": "24628692629cc5e5c54d7aed07b12e4347460ec4", "size": 947409, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "QML_Full.ipynb", "max_stars_repo_name": "gustavomirapalheta/Quantum-Computing-with-Qiskit", "max_stars_repo_head_hexsha": "53de694455d097cda0181779a5e5988ebb5d27fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-11T01:16:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T10:29:21.000Z", "max_issues_repo_path": "QML_Full.ipynb", "max_issues_repo_name": "gustavomirapalheta/Quantum-Computing-with-Qiskit", "max_issues_repo_head_hexsha": "53de694455d097cda0181779a5e5988ebb5d27fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QML_Full.ipynb", "max_forks_repo_name": "gustavomirapalheta/Quantum-Computing-with-Qiskit", "max_forks_repo_head_hexsha": "53de694455d097cda0181779a5e5988ebb5d27fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 947409.0, "max_line_length": 947409, "alphanum_fraction": 0.9070169272, "converted": true, "num_tokens": 30702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861801254413963, "lm_q2_score": 0.08882029722399612, "lm_q1q2_score": 0.03451716738076913}}
{"text": "<a id='logbook'></a>\n# Report\nThis is the notebook that created the report.\n\n\n```python\n%matplotlib inline\n%load_ext autoreload\n%autoreload 2\n\nimport warnings\nwarnings.filterwarnings('ignore')\n```\n\n    Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 462 ('figure.figsize   : 5, 3   ## figure size in inches')\n    Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 463 ('figure.dpi       : 100        ## figure dots per inch')\n\n\n\n```python\nimport os\nimport matplotlib.pyplot as plt\nimport pandas as pd\npd.options.display.max_rows = 999\npd.options.display.max_columns = 999\npd.set_option(\"display.max_columns\", None)\nimport sympy as sp\n\nimport pandas as pd\nimport numpy as np\n\nif os.name == 'nt':\n    plt.style.use('paper.mplstyle')  # Windows\n\nimport statsmodels.api as sm\nfrom statsmodels.sandbox.regression.predstd import wls_prediction_std\nfrom sklearn.metrics import r2_score\nfrom scipy.integrate import solve_ivp\nimport seaborn as sns\n\nfrom copy import deepcopy\nimport sys\nsys.path.append('../../')\nfrom src.equation import Equation,equation_dict\nfrom src import equations,symbols\nimport reports.paper_writing\nfrom src.df_to_latex import LateXTable\n\n## Examples:\n\n```\n\n    Duplicate key in file 'paper.mplstyle', line 462 ('figure.figsize   : 5, 3   ## figure size in inches')\n    Duplicate key in file 'paper.mplstyle', line 463 ('figure.dpi       : 100        ## figure dots per inch')\n\n\n\n```python\nfrom IPython.display import set_matplotlib_formats\nset_matplotlib_formats('pdf','png')\n\nfrom IPython.display import HTML, Markdown, Image\nfrom src.df_to_latex import LateXTable\n```\n\n# Abstract\nShort abstract of report\n\n# Introduction\n\n<a id='fig_rolldecay_example>'></a>\n\n\n```python\nfig,ax=plt.subplots()\ndf = pd.DataFrame(data=np.random.normal(size=(1000,2)))\ndf.plot(ax=ax);\n```\n\nThe oscillating motion can be described by a spring-mass-damper system as seen in Fig.[(below)](#fig_spring_mass_damper).\n\n<a id=\"fig_spring_mass_damper\"></a>\n\n\n```python\nImage('../figures/220px-Mass_spring_damper.svg.png')\n```\n\nThis system can me described as the following equation [(below)](#eq_equation1):\n\n<a id=\"eq_equation1\"></a>\n\n\n```python\neq = r'$E=m \\dot c^2 $'\nEquation(eq, label='equation1')\n```\n\n\n\n\n$\\displaystyle \n\\begin{equation}\n$E=m \\dot c^2 $\n\\label{eq:equation1}\n\\end{equation}\n$\n\n\n\n\n```python\nA,r = sp.symbols('A r')\neq = sp.Eq(A,\n          r**2*sp.pi)\nEquation(eq, label='equation2')\n```\n\n\n\n\n$\\displaystyle \n\\begin{equation}\nA = \\pi r^{2}\n\\label{eq:equation2}\n\\end{equation}\n$\n\n\n\n# Data\nThe data used in this study is described in Tab.[(below)](#tab_data_files). There is one result with a pure FNPF simulation at 0 knots. For model test results, two tests are available at 0 knots and one test at 15.5 knots. There is also a result at 15.5 with a hybrid method, where semi empirical viscosity has been injected into the FNPF calculations.\n\n<a id=\"tab_data_files\"></a>\n\n\n```python\ncontent = pd.read_csv('../../data/external/content.csv', sep=';')\ntable_parameters = content.round(decimals=3)\ncontent.set_index('file', inplace=True)\n\nrename = {}\nunits = {\n    'Ship speed' : r'$[kts]$',\n}\n\ntable_parameters['data file'] = table_parameters['data file'].apply(lambda x : x.replace('_',r' '))\n\n\nlt = LateXTable(table_parameters, units=units, rename=rename, caption='Data files', label='data_files')\nlt\n```\n\n\n\n\n<table><tr><td>file</td><td>data file</td><td>Ship speed</td><td>Method</td></tr><tr><td></td><td></td><td>$[kts]$</td><td></td></tr><tr><td>1</td><td>fnpf kvlcc2 rolldecay 0kn.csv</td><td>0.0</td><td>FNPF</td></tr><tr><td>2</td><td>model test 21337.csv</td><td>0.0</td><td>model test</td></tr><tr><td>3</td><td>model test 21338.csv</td><td>0.0</td><td>model test</td></tr><tr><td>4</td><td>model test 21340.csv</td><td>15.5</td><td>model test</td></tr><tr><td>5</td><td>fnpf kvlcc2 rolldecay 15-5kn ikeda dev.csv</td><td>15.5</td><td>hybrid</td></tr></table>\n\n\n\n# Analysis\n\n# Conclusions\n  \n\n\n\n\n# References\n<div class=\"cite2c-biblio\"></div>\n", "meta": {"hexsha": "81c1f1e0124efd674589e3d937806453d75685a0", "size": 259715, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "reports/report/01.1.report.ipynb", "max_stars_repo_name": "martinlarsalbert/project", "max_stars_repo_head_hexsha": "a52368f8640374a910226b7a656feb16b1808cbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reports/report/01.1.report.ipynb", "max_issues_repo_name": "martinlarsalbert/project", "max_issues_repo_head_hexsha": "a52368f8640374a910226b7a656feb16b1808cbb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reports/report/01.1.report.ipynb", "max_forks_repo_name": "martinlarsalbert/project", "max_forks_repo_head_hexsha": "a52368f8640374a910226b7a656feb16b1808cbb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 232.5111906893, "max_line_length": 154905, "alphanum_fraction": 0.9097549237, "converted": true, "num_tokens": 1200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.09138209873674573, "lm_q1q2_score": 0.03450045867324915}}
{"text": "# pAPRika tutorial 6 - APR/Gromacs with Plumed restraints\n\nIn this tutorial, we will perform APR calculations for the butane (BUT)--cucurbit[6]uril (CB6) host-guest system. This tutorial is similar to [tutorial 5](05-tutorial-cb6-but-plumed.ipynb) where `Plumed` will be used for the restraints but we will be using the `GROMACS` MD engine instead. One other difference in this tutorial is that we will be performing the simulation with periodic boundary condition (PBC) and explicit water molecules. This is because `GROMACS` does not support implicit solvent calculations.\n\n## Initialize\n\n### <ins>Before you start</ins>\n<a id='start'></a>\nWe will run the simulations in this tutorial using `GROMACS` and `Plumed`. `GROMACS` will need to be installed before you can run the [simulation](#simulate) part of this tutorial. `Plumed`, however, should be installed in your `conda` environment if you installed *pAPRika* though the `conda` route. To use `Plumed` we first need to make sure the `PLUMED_KERNEL` environment variable is loaded (the library is called `libplumedKernel.so`). *pAPRika* should load the `Plumed` kernel automatically but let's make sure it is loaded and run the cell below.\n\n\n```python\nimport os\n'PLUMED_KERNEL' in os.environ.keys()\n```\n\n\n\n\n    True\n\n\n\nIf it does not exists we will load the environment in this Jupyter Notebook. Since `Plumed` is installed through `conda` the kernel will be located in your conda environment library folder. If you are running this on a MacOS, replace the kernel library in the cell below to `libplumedKernel.dylib`. If you compiled `Plumed` yourself and then you will need to change the path below.\n\n\n```python\nos.environ['PLUMED_KERNEL'] = f\"{os.environ['CONDA_PREFIX']}/lib/libplumedKernel.so\"\n```\n\nFor running `Plumed` outside of this notebook it might be better to export the `PLUMED_KERNEL` variable into your `.bashrc` file.\n\n<font size=\"4\"><ins>**Note:**</ins></font> we can run `Plumed` with `GROMACS` *versions 2020.2* but the user is required to patch the source code. Unlike `AMBER` and `LAMMPS`, `GROMACS` does not come with a patched code out-of-the-box and the `conda-forge` repository also do not contain a patched version of `GROMACS`. See the `Plumed` documentation for more details on how to patch and recompile the `GROMACS` code https://www.plumed.org/doc-v2.6/user-doc/html/index.html.\n\n<font size=\"4\"><ins>**Note:**</ins></font> We will be running the CB6-BUT host-guest system in explicit solvent because `GROMACS` does not support implicit solvent calculation. Thus, we recommend running the simulation on a GPU.\n\n\ud83d\udd35 Since we have a prepared the host-guest-dummy setup from the first tutorial, we will skip the initial tleap steps and go right into initializing the restraints. If you haven't completed [tutorial 1](01-tutorial-cb6-but.ipynb) please go back and run the notebook to generate the starting structure.\n\n### Define names\nWe will store the files created in this tutorial in a folder called `gromacs-plumed` so we don't mix files with the previous tutorial.\n\n\n```python\nbase_name = \"cb6-but-dum\"\nwork_dir = \"gromacs-plumed\"\ncomplex_dir = \"complex\"\ndata = \"../../../paprika/data/cb6-but\"\n```\n\n## Configure APR Restraints\n\n### Define anchor atoms\nSee [tutorial 1](01-tutorial-cb6-but.ipynb) for the choice of selection\n\n\n```python\n# Guest atoms\nG1 = \":BUT@C\"\nG2 = \":BUT@C3\"\n\n# Host atoms\nH1 = \":CB6@C\"\nH2 = \":CB6@C31\"\nH3 = \":CB6@C18\"\n\n# Dummy atoms\nD1 = \":DM1\"\nD2 = \":DM2\"\nD3 = \":DM3\"\n```\n\n### Determine the number of windows\nBefore we add the restraints, it is helpful to set the $\\lambda$ fractions that control the strength of the force constants during attach and release, and to define the distances for the pulling phase.\n\nThe attach fractions go from 0 to 1 and we place more points at the bottom of the range to sample the curvature of $dU/d \\lambda$. Next, we generally apply a distance restraint until the guest is ~18 Angstroms away from the host, in increments of 0.4 Angstroms. This distance should be at least twice the Lennard-Jones cutoff in the system. These values have worked well for us, but this is one aspect that should be carefully checked for new systems.\n\n\n```python\nimport numpy as np\n```\n\n\n```python\nattach_string = \"0.00 0.40 0.80 1.60 2.40 4.00 5.50 8.65 11.80 18.10 24.40 37.00 49.60 74.80 100.00\"\nattach_fractions = [float(i) / 100 for i in attach_string.split()]\n\ninitial_distance = 6.0\npull_distances = np.arange(0.0 + initial_distance, 18.0 + initial_distance, 1.0)\n\nrelease_fractions = []\n\nwindows = [len(attach_fractions), len(pull_distances), len(release_fractions)]\nprint(f\"There are {windows} windows in this attach-pull-release calculation.\")\n```\n\n    There are [15, 18, 0] windows in this attach-pull-release calculation.\n\n\n### Load structure\n\n\n```python\nimport parmed as pmd\n```\n\n* Load complex structure\n\n\n```python\nstructure = pmd.load_file(\n    os.path.join(complex_dir, f\"{base_name}.prmtop\"),\n    os.path.join(complex_dir, f\"{base_name}.rst7\"),\n    structure = True,\n) \n```\n\n### Host Static Restraints\nSee [tutorial 1](01-tutorial-cb6-but.ipynb#host_static) for an explanation of the static restraints.\n\n\n```python\nimport paprika.restraints as restraints\n```\n\n\n```python\nstatic_restraints = []\n```\n\n\n```python\nr = restraints.static_DAT_restraint(restraint_mask_list = [D1, H1],\n                                    num_window_list = windows,\n                                    ref_structure = structure,\n                                    force_constant = 5.0,\n                                    amber_index=True)\n\nstatic_restraints.append(r)\n```\n\n\n```python\nr = restraints.static_DAT_restraint(restraint_mask_list = [D2, D1, H1],\n                                    num_window_list = windows,\n                                    ref_structure = structure,\n                                    force_constant = 100.0,\n                                    amber_index=True)\n\nstatic_restraints.append(r)\n```\n\n\n```python\nr = restraints.static_DAT_restraint(restraint_mask_list = [D3, D2, D1, H1],\n                                    num_window_list = windows,\n                                    ref_structure = structure,\n                                    force_constant = 100.0,\n                                    amber_index=True)\n\nstatic_restraints.append(r)\n```\n\n\n```python\nr = restraints.static_DAT_restraint(restraint_mask_list = [D1, H1, H2],\n                                    num_window_list = windows,\n                                    ref_structure = structure,\n                                    force_constant = 100.0,\n                                    amber_index=True)\n\nstatic_restraints.append(r)\n```\n\n\n```python\nr = restraints.static_DAT_restraint(restraint_mask_list = [D2, D1, H1, H2],\n                                    num_window_list = windows,\n                                    ref_structure = structure,\n                                    force_constant = 100.0,\n                                    amber_index=True)\n\nstatic_restraints.append(r)\n```\n\n\n```python\nr = restraints.static_DAT_restraint(restraint_mask_list = [D1, H1, H2, H3],\n                                    num_window_list = windows,\n                                    ref_structure = structure,\n                                    force_constant = 100.0,\n                                    amber_index=True)\n\nstatic_restraints.append(r)\n```\n\n### Guest translational and rotational restraints\nSee [tutorial 1](01-tutorial-cb6-but.ipynb#guest) for an explanation of the guest restraints\n\n\n```python\nguest_restraints = []\n```\n\n\n```python\nr = restraints.DAT_restraint()\nr.mask1 = D1\nr.mask2 = G1\nr.topology = structure\nr.auto_apr = True\nr.continuous_apr = True\nr.amber_index = True\n\nr.attach[\"target\"] = pull_distances[0]          # Angstroms\nr.attach[\"fraction_list\"] = attach_fractions\nr.attach[\"fc_final\"] = 5.0                      # kcal/mol/Angstroms**2\n\nr.pull[\"target_final\"] = 24.0                   # Angstroms\nr.pull[\"num_windows\"] = windows[1]\n\nr.initialize()\nguest_restraints.append(r)\n```\n\n\n```python\nr = restraints.DAT_restraint()\nr.mask1 = D2\nr.mask2 = D1\nr.mask3 = G1\nr.topology = structure\nr.auto_apr = True\nr.continuous_apr = True\nr.amber_index = True\n\nr.attach[\"target\"] = 180.0                      # Degrees\nr.attach[\"fraction_list\"] = attach_fractions\nr.attach[\"fc_final\"] = 100.0                    # kcal/mol/radian**2\n\nr.pull[\"target_final\"] = 180.0                  # Degrees\nr.pull[\"num_windows\"] = windows[1]\n\nr.initialize()\nguest_restraints.append(r)\n```\n\n\n```python\nr = restraints.DAT_restraint()\nr.mask1 = D1\nr.mask2 = G1\nr.mask3 = G2\nr.topology = structure\nr.auto_apr = True\nr.continuous_apr = True\nr.amber_index = True\n\nr.attach[\"target\"] = 180.0                      # Degrees\nr.attach[\"fraction_list\"] = attach_fractions\nr.attach[\"fc_final\"] = 100.0                    # kcal/mol/radian**2\n\nr.pull[\"target_final\"] = 180.0                  # Degrees\nr.pull[\"num_windows\"] = windows[1]\n\nr.initialize()\nguest_restraints.append(r)\n```\n\n### Create APR windows\nWe use the guest restraints to create a list of windows with the appropriate names and then create the directories.\n\n\n```python\nfrom paprika.restraints.restraints import create_window_list\n```\n\n\n```python\nwindow_list = create_window_list(guest_restraints)\n```\n\n\n```python\nif not os.path.isdir(work_dir):\n    os.makedirs(work_dir)\n    \nfor window in window_list:\n    folder = os.path.join(work_dir, window)\n    if not os.path.isdir(folder):\n        os.makedirs(os.path.join(work_dir, window))\n```\n\n### Write APR restraints to Plumed format\nIn this section we create an instance of `Plumed()` from `paprika.restraints.plumed`, which is a class to generate the `Plumed` restraint files. We need to specify the list of restraints used throughout the APR calculations and the corresponding windows list. In this tutorial we will print the **host static** restraints and the **guest** restraints. The `Plumed` class includes a method to add restraints to dummy atoms (`add_dummy_atoms_to_file`). We will add the positional restraints on the dummy atoms after solvation of the host-guest complex.\n\n<font size='4'><ins>**Note**</ins></font>: be careful when specifying the force constants in `DAT_restraints`. We follow the AMBER (and CHARMM) convention where the force constant is already multiplied by a factor of 1/2 but `Plumed` requires the user to specify the force constant without this factor, i.e.\n\n$$\n\\begin{align}\nU_{amber} &= K_{amber} (r-r_{0})^2 \\\\\nU_{plumed} &= \\frac{1}{2} k_{plumed} (r - r_{0})^2 \n\\end{align}\n$$\n\nthus $k_{plumed} = 2 \\times  K_{amber}$. If AMBER force constants was used in generating the `DAT_restraints` (the case in this tutorial) we need to set the variable `uses_legacy_k` to `True` (this is on by default).\n\n\n```python\nfrom paprika.restraints.plumed import Plumed\n```\n\n\n```python\nrestraints_list = (static_restraints + guest_restraints)\n\nplumed = Plumed()\nplumed.file_name = 'plumed.dat'\nplumed.path = work_dir\nplumed.window_list = window_list\nplumed.restraint_list = restraints_list\nplumed.uses_legacy_k = True\n\nplumed.dump_to_file()\n```\n\n## Prepare host-guest system\n\n### Translate guest molecule\nFor the attach windows, we will use the initial, bound coordinates for the host-guest complex. Only the force constants change during this phase, so a single set of coordinates is sufficient. For the pull windows, we will translate the guest to the target value of the restraint before solvation, and for the release windows, we will use the coordinates from the final pull window.\n\n\n```python\nimport shutil\n```\n\n\n```python\nfor window in window_list:\n    if window[0] == \"a\":\n        shutil.copy(os.path.join(complex_dir, f\"{base_name}.prmtop\"),\n                    os.path.join(work_dir, window, f\"{base_name}.prmtop\"))\n        shutil.copy(os.path.join(complex_dir, f\"{base_name}.rst7\"),\n                    os.path.join(work_dir, window, f\"{base_name}.rst7\"))\n\n    elif window[0] == \"p\":\n        structure = pmd.load_file(\n            os.path.join(complex_dir, f\"{base_name}.prmtop\"), \n            os.path.join(complex_dir, f\"{base_name}.rst7\"), \n            structure = True\n        )\n        target_difference = guest_restraints[0].phase['pull']['targets'][int(window[1:])] -\\\n                            guest_restraints[0].pull['target_initial']\n        print(f\"In window {window} we will translate the guest {target_difference.magnitude:0.1f}.\")\n        \n        for atom in structure.atoms:\n            if atom.residue.name == \"BUT\":\n                atom.xz += target_difference.magnitude\n                \n        structure.save(os.path.join(work_dir, window, f\"{base_name}.prmtop\"), overwrite=True)\n        structure.save(os.path.join(work_dir, window, f\"{base_name}.rst7\"), overwrite=True)\n```\n\n    In window p000 we will translate the guest 0.0 Angstroms.\n    In window p001 we will translate the guest 1.1 Angstroms.\n    In window p002 we will translate the guest 2.1 Angstroms.\n    In window p003 we will translate the guest 3.2 Angstroms.\n    In window p004 we will translate the guest 4.2 Angstroms.\n    In window p005 we will translate the guest 5.3 Angstroms.\n    In window p006 we will translate the guest 6.4 Angstroms.\n    In window p007 we will translate the guest 7.4 Angstroms.\n    In window p008 we will translate the guest 8.5 Angstroms.\n    In window p009 we will translate the guest 9.5 Angstroms.\n    In window p010 we will translate the guest 10.6 Angstroms.\n    In window p011 we will translate the guest 11.6 Angstroms.\n    In window p012 we will translate the guest 12.7 Angstroms.\n    In window p013 we will translate the guest 13.8 Angstroms.\n    In window p014 we will translate the guest 14.8 Angstroms.\n    In window p015 we will translate the guest 15.9 Angstroms.\n    In window p016 we will translate the guest 16.9 Angstroms.\n    In window p017 we will translate the guest 18.0 Angstroms.\n\n\n### Solvate the host-guest system\nHere we will solvate the host-guest system in each window with 2000 water molecules. Since `Gromacs` cannot read in `Amber` topology and coordinates files we will have to convert them to the appropriate formats. `TLeap` has a built-in function called `TLeap.convert_to_gromacs()`, which will convert the `Amber` files to `Gromacs`. We also need to add positional restraints on dummy atoms to the `plumed.dat` file and this is done by invoking the function `plumed.add_dummy_atoms_to_file`\n\n\n```python\nfrom paprika.build.system import TLeap\n```\n\n\n```python\nfor window in window_list:\n    print(f\"Solvating system in {window}.\")\n    \n    structure = pmd.load_file(\n        os.path.join(work_dir, window, f\"{base_name}.prmtop\"),\n        os.path.join(work_dir, window, f\"{base_name}.rst7\"),\n        structure=True,\n    )\n    \n    if not os.path.exists(os.path.join(work_dir, window, f\"{base_name}.pdb\")):\n        structure.save(os.path.join(work_dir, window, f\"{base_name}.pdb\"))\n    \n    system = TLeap()\n    system.output_path = os.path.join(work_dir, window)\n    system.output_prefix = f\"{base_name}-sol\"\n    \n    system.target_waters = 2000\n    system.neutralize = True\n    system.add_ions = [\"Na+\", 6, \"Cl-\", 6]\n    system.pbc_type = \"rectangular\"\n    system.template_lines = [\n        \"source leaprc.gaff\",\n        \"source leaprc.water.tip3p\",\n        f\"loadamberparams {data}/cb6.frcmod\",\n        \"loadamberparams ../../complex/dummy.frcmod\",\n        f\"CB6 = loadmol2 {data}/cb6.mol2\",\n        f\"BUT = loadmol2 {data}/but.mol2\",\n        \"DM1 = loadmol2 ../../complex/dm1.mol2\",\n        \"DM2 = loadmol2 ../../complex/dm2.mol2\",\n        \"DM3 = loadmol2 ../../complex/dm3.mol2\",\n        \"model = loadpdb cb6-but-dum.pdb\",\n    ]\n    system.build()\n    \n    # Convert Amber to Gromacs\n    system.convert_to_gromacs(overwrite=True)\n\n    # Add dummy atom restraints - load in the Gromacs files instead \n    # of the amber files because the coordinates a shifted.\n    structure = pmd.load_file(\n        os.path.join(work_dir, window, f\"{base_name}-sol.top\"),\n        xyz=os.path.join(work_dir, window, f\"{base_name}-sol.gro\"), \n        structure=True\n    )\n    plumed.add_dummy_atoms_to_file(structure,window=window)\n```\n\n    Solvating system in a000.\n    Solvating system in a001.\n    Solvating system in a002.\n    Solvating system in a003.\n    Solvating system in a004.\n    Solvating system in a005.\n    Solvating system in a006.\n    Solvating system in a007.\n    Solvating system in a008.\n    Solvating system in a009.\n    Solvating system in a010.\n    Solvating system in a011.\n    Solvating system in a012.\n    Solvating system in a013.\n    Solvating system in p000.\n    Solvating system in p001.\n    Solvating system in p002.\n    Solvating system in p003.\n    Solvating system in p004.\n    Solvating system in p005.\n    Solvating system in p006.\n    Solvating system in p007.\n    Solvating system in p008.\n    Solvating system in p009.\n    Solvating system in p010.\n    Solvating system in p011.\n    Solvating system in p012.\n    Solvating system in p013.\n    Solvating system in p014.\n    Solvating system in p015.\n    Solvating system in p016.\n    Solvating system in p017.\n\n\n## Simulation\n<a id='simulate'></a>\nNow that we have a solvated structure and a `plumed.dat` file with dummy atoms position restraints, we have everything ready to go. **pAPRika** has a `GROMACS` wrapper module that can help setting default parameters for the simulation. There are some high level options that we set directly, like `simulation.path`, and then we call the function `config_pbc_min()` to setup reasonable default simulation parameters for a minimization and production run. See the `pAPRika` documentation for more details.\n\n`GROMACS`, unlike `AMBER` and `OpenMM`, have a higher dependency on CPUs, so more than one processor for every GPU is preferred to deliver better speed. Setting the number of processors requires using different keyword depending on how `GROMACS` was compiled. The cells below were run using `GROMACS` that is compiled with MPI and hence the suffix, i.e., `gmx_mpi` (for a non-MPI version, the executable is usually called `gmx`). We set the number of processors with `simulation.n_threads = 8` and the GPU device with `simulation.gpu_devices = 0`.\n\n<font size='4'><ins>**Note**</ins></font>: For host-guest systems I find that the non-MPI version is considerably much faster. Also, 12 CPUs with a single GPU seems to be a good combination with a non-MPI version.\n\nBy default, `pAPRika` will use `-ntomp` to specify the number of CPUs when executing `mdrun` if the executable is `gmx_mpi` and `-nt` for `gmx`. If these default settings do not work with the `GROMACS` currently installed then we can use `simulation.custom_mdrun_command` to override the default, e.g.,\n```python\nsimulation.custom_mdrun_command = \"-ntmpi 8 -gpu_id 1\"\n```\nor\n```python\nsimulation.custom_mdrun_command = \"mpirun -np 4 gmx_mpi mdrun -ntomp 8 -gpu_id 4\"\n```\n\n\n<font size='4'><ins>**Note**</ins></font>: We do not need to run `grompp` beforehand because the simulation wrapper in `pAPRika` takes care of this automatically when we call the `simulation.run()` method. We also set `simulation.grompp_maxwarn = 5` to ignore warnings about the total charge of the system (the total charge is slightly off from neutral).\n\n<font size='4'><ins>**Note**</ins></font>: as explained at the [start](#start) of this tutorial, make sure that the `PLUMED_KERNEL` environment variable is set otherwise the simulation will fail to run.\n\n\n```python\nfrom paprika.simulate import GROMACS\n```\n\nInitialize logger\n\n\n```python\nimport logging\nfrom importlib import reload\nreload(logging)\n\nlogger = logging.getLogger()\nlogging.basicConfig(\n    format='%(asctime)s %(message)s',\n    datefmt='%Y-%m-%d %I:%M:%S %p',\n    level=logging.INFO\n)\n```\n\n### Energy Minimization\n\n\n```python\nfor window in window_list:\n    simulation = GROMACS()\n    simulation.executable = \"gmx_mpi\"\n    simulation.n_threads = 8\n    simulation.gpu_devices = 0\n#     simulation.custom_mdrun_command = \"-ntomp 8 -gpu_id 6\"\n    simulation.path = os.path.join(work_dir, window)\n    simulation.maxwarn = 5\n    \n    simulation.prefix = \"minimize\"\n    simulation.topology = f\"{base_name}-sol.top\"\n    simulation.coordinates = f\"{base_name}-sol.gro\"\n    simulation.plumed_file = \"plumed.dat\"\n    \n    simulation.config_pbc_min()\n    \n    logging.info(f\"Running minimization in window {window}...\")\n    simulation.run(overwrite=True)\n```\n\n    2020-09-25 05:22:17 PM Running minimization in window a000...\n    2020-09-25 05:22:36 PM Running minimization in window a001...\n    2020-09-25 05:22:56 PM Running minimization in window a002...\n    2020-09-25 05:23:15 PM Running minimization in window a003...\n    2020-09-25 05:23:37 PM Running minimization in window a004...\n    2020-09-25 05:23:56 PM Running minimization in window a005...\n    2020-09-25 05:24:16 PM Running minimization in window a006...\n    2020-09-25 05:24:33 PM Running minimization in window a007...\n    2020-09-25 05:24:52 PM Running minimization in window a008...\n    2020-09-25 05:25:12 PM Running minimization in window a009...\n    2020-09-25 05:25:32 PM Running minimization in window a010...\n    2020-09-25 05:25:50 PM Running minimization in window a011...\n    2020-09-25 05:26:10 PM Running minimization in window a012...\n    2020-09-25 05:26:29 PM Running minimization in window a013...\n    2020-09-25 05:26:49 PM Running minimization in window p000...\n    2020-09-25 05:27:08 PM Running minimization in window p001...\n    2020-09-25 05:27:28 PM Running minimization in window p002...\n    2020-09-25 05:27:46 PM Running minimization in window p003...\n    2020-09-25 05:28:05 PM Running minimization in window p004...\n    2020-09-25 05:28:24 PM Running minimization in window p005...\n    2020-09-25 05:28:46 PM Running minimization in window p006...\n    2020-09-25 05:29:04 PM Running minimization in window p007...\n    2020-09-25 05:29:23 PM Running minimization in window p008...\n    2020-09-25 05:29:41 PM Running minimization in window p009...\n    2020-09-25 05:30:01 PM Running minimization in window p010...\n    2020-09-25 05:30:20 PM Running minimization in window p011...\n    2020-09-25 05:30:39 PM Running minimization in window p012...\n    2020-09-25 05:30:58 PM Running minimization in window p013...\n    2020-09-25 05:31:18 PM Running minimization in window p014...\n    2020-09-25 05:31:37 PM Running minimization in window p015...\n    2020-09-25 05:31:56 PM Running minimization in window p016...\n    2020-09-25 05:32:15 PM Running minimization in window p017...\n\n\n### NVT - Equilibration\nHere, we will perform 50,000 steps of equilibration with the NVT ensemble.\n\n\n```python\nfor window in window_list:\n    simulation = GROMACS()\n    simulation.executable = \"gmx_mpi\"\n    simulation.n_threads = 8\n    simulation.gpu_devices = 0\n#     simulation.custom_mdrun_command = \"-ntomp 8 -gpu_id 6\"\n    simulation.path = os.path.join(work_dir, window)\n    simulation.maxwarn = 5\n    \n    simulation.prefix = \"equilibration\"\n    simulation.topology = f\"{base_name}-sol.top\"\n    simulation.coordinates = \"minimize.gro\"\n    simulation.plumed_file = \"plumed.dat\"\n    \n    simulation.config_pbc_md(ensemble='nvt')\n    simulation.control[\"nsteps\"] = 50000\n    \n    logging.info(f\"Running equilibration in window {window}...\")\n    simulation.run(overwrite=True)\n```\n\n    2020-09-25 05:41:42 PM Running equilibration in window a000...\n    2020-09-25 05:42:26 PM Running equilibration in window a001...\n    2020-09-25 05:43:07 PM Running equilibration in window a002...\n    2020-09-25 05:43:49 PM Running equilibration in window a003...\n    2020-09-25 05:44:33 PM Running equilibration in window a004...\n    2020-09-25 05:45:17 PM Running equilibration in window a005...\n    2020-09-25 05:46:01 PM Running equilibration in window a006...\n    2020-09-25 05:46:36 PM Running equilibration in window a007...\n    2020-09-25 05:47:13 PM Running equilibration in window a008...\n    2020-09-25 05:47:54 PM Running equilibration in window a009...\n    2020-09-25 05:48:36 PM Running equilibration in window a010...\n    2020-09-25 05:49:12 PM Running equilibration in window a011...\n    2020-09-25 05:49:56 PM Running equilibration in window a012...\n    2020-09-25 05:50:31 PM Running equilibration in window a013...\n    2020-09-25 05:51:11 PM Running equilibration in window p000...\n    2020-09-25 05:51:53 PM Running equilibration in window p001...\n    2020-09-25 05:52:36 PM Running equilibration in window p002...\n    2020-09-25 05:53:20 PM Running equilibration in window p003...\n    2020-09-25 05:54:02 PM Running equilibration in window p004...\n    2020-09-25 05:54:44 PM Running equilibration in window p005...\n    2020-09-25 05:55:26 PM Running equilibration in window p006...\n    2020-09-25 05:56:09 PM Running equilibration in window p007...\n    2020-09-25 05:56:44 PM Running equilibration in window p008...\n    2020-09-25 05:57:27 PM Running equilibration in window p009...\n    2020-09-25 05:58:05 PM Running equilibration in window p010...\n    2020-09-25 05:58:48 PM Running equilibration in window p011...\n    2020-09-25 05:59:31 PM Running equilibration in window p012...\n    2020-09-25 06:00:14 PM Running equilibration in window p013...\n    2020-09-25 06:00:59 PM Running equilibration in window p014...\n    2020-09-25 06:01:41 PM Running equilibration in window p015...\n    2020-09-25 06:02:20 PM Running equilibration in window p016...\n    2020-09-25 06:03:02 PM Running equilibration in window p017...\n\n\n### Production Run\nWe will run the production phase for 50,000 steps. <font size='3'><ins>**Note**</ins></font>: a proper production run would require simulation in the tens of nanoseconds per window.\n\n\n```python\nfor window in window_list:\n    simulation = GROMACS()\n    simulation.executable = \"gmx_mpi\"\n    simulation.n_threads = 8\n    simulation.gpu_devices = 0\n#     simulation.custom_mdrun_command = \"-ntomp 8 -gpu_id 6\"\n    simulation.path =  os.path.join(work_dir, window)\n    simulation.maxwarn = 5\n    \n    simulation.prefix = \"production\"\n    simulation.topology = f\"{base_name}-sol.top\"\n    simulation.coordinates = \"equilibration.gro\"\n    simulation.checkpoint = \"equilibration.cpt\"\n    simulation.plumed_file = \"plumed.dat\"\n    \n    simulation.config_pbc_md(ensemble='npt')\n    simulation.control[\"nsteps\"] = 50000\n    \n    logging.info(f\"Running production in window {window}...\")\n    simulation.run(overwrite=True)\n```\n\n    2020-09-25 06:04:07 PM Running production in window a000...\n    2020-09-25 06:04:49 PM Running production in window a001...\n    2020-09-25 06:05:33 PM Running production in window a002...\n    2020-09-25 06:06:17 PM Running production in window a003...\n    2020-09-25 06:07:02 PM Running production in window a004...\n    2020-09-25 06:07:45 PM Running production in window a005...\n    2020-09-25 06:08:30 PM Running production in window a006...\n    2020-09-25 06:09:14 PM Running production in window a007...\n    2020-09-25 06:09:56 PM Running production in window a008...\n    2020-09-25 06:10:37 PM Running production in window a009...\n    2020-09-25 06:11:22 PM Running production in window a010...\n    2020-09-25 06:12:04 PM Running production in window a011...\n    2020-09-25 06:12:49 PM Running production in window a012...\n    2020-09-25 06:13:39 PM Running production in window a013...\n    2020-09-25 06:14:23 PM Running production in window p000...\n    2020-09-25 06:15:07 PM Running production in window p001...\n    2020-09-25 06:15:50 PM Running production in window p002...\n    2020-09-25 06:16:35 PM Running production in window p003...\n    2020-09-25 06:17:20 PM Running production in window p004...\n    2020-09-25 06:18:03 PM Running production in window p005...\n    2020-09-25 06:18:55 PM Running production in window p006...\n    2020-09-25 06:19:40 PM Running production in window p007...\n    2020-09-25 06:20:24 PM Running production in window p008...\n    2020-09-25 06:21:13 PM Running production in window p009...\n    2020-09-25 06:21:57 PM Running production in window p010...\n    2020-09-25 06:22:43 PM Running production in window p011...\n    2020-09-25 06:23:28 PM Running production in window p012...\n    2020-09-25 06:24:16 PM Running production in window p013...\n    2020-09-25 06:24:58 PM Running production in window p014...\n    2020-09-25 06:25:43 PM Running production in window p015...\n    2020-09-25 06:26:24 PM Running production in window p016...\n    2020-09-25 06:27:06 PM Running production in window p017...\n\n\n## Analysis\n\nOnce the simulation is completed, we can using the `Analysis` module to determine the binding free energy. We supply the location of the parameter information, a string or list for the file names (wildcards supported), the location of the windows, and the restraints on the guest.\n\nIn this example, we use the method `ti-block` which determines the free energy using **t**hermodynamic **i**integration and then estimates the standard error of the mean at each data point using blocking analysis. Bootstrapping it used to determine the uncertainty of the  full thermodynamic integral for each phase.\n\nAfter running `compute_free_energy()`, a dictionary called `results` will be populated, that contains the free energy and SEM for each phase of the simulation.\n\n\n```python\nimport paprika.analysis as analysis\n```\n\n\n```python\nfree_energy = analysis.fe_calc()\nfree_energy.topology = \"cb6-but-dum-sol.pdb\"\nfree_energy.trajectory = 'production*.trr'\nfree_energy.path = work_dir\nfree_energy.restraint_list = guest_restraints\nfree_energy.collect_data()\nfree_energy.methods = ['ti-block']\nfree_energy.ti_matrix = \"full\"\nfree_energy.bootcycles = 1000\nfree_energy.compute_free_energy()\n```\n\nWe also need to calculate the free-energy cost of releasing the restraints on the guest molecule.\n\n\n```python\nfree_energy.compute_ref_state_work([\n    guest_restraints[0], guest_restraints[1], None, None,\n    guest_restraints[2], None\n])\n```\n\nThen we add the free-energies together and combine the uncertainties to get the binding-free energy\n\n\n```python\nbinding_affinity = -1 * (\n    free_energy.results[\"attach\"][\"ti-block\"][\"fe\"] + \\\n    free_energy.results[\"pull\"][\"ti-block\"][\"fe\"] + \\\n    free_energy.results[\"ref_state_work\"]\n)\n\nsem = np.sqrt(\n    free_energy.results[\"attach\"][\"ti-block\"][\"sem\"]**2 + \\\n    free_energy.results[\"pull\"][\"ti-block\"][\"sem\"]**2\n)\n```\n\n\n```python\nprint(f\"The binding affinity of butane to cucurbit[6]uril = {binding_affinity.magnitude:0.2f} +/- {sem.magnitude:0.2f} kcal/mol\")\n```\n\n    The binding affinity of butane to cucurbit[6]uril = -7.55 +/- 1.58 kcal/mol\n\n", "meta": {"hexsha": "db846290338c6343e437ecbf6439f6d69483f38f", "size": 43730, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/06-tutorial-cb6-but-gromacs.ipynb", "max_stars_repo_name": "jaketanderson/pAPRika", "max_stars_repo_head_hexsha": "5376f44ee1f7a0785f712b3b6c7bfa4c698ca65e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-04-19T23:46:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T19:47:02.000Z", "max_issues_repo_path": "docs/tutorials/06-tutorial-cb6-but-gromacs.ipynb", "max_issues_repo_name": "jaketanderson/pAPRika", "max_issues_repo_head_hexsha": "5376f44ee1f7a0785f712b3b6c7bfa4c698ca65e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 154, "max_issues_repo_issues_event_min_datetime": "2017-04-20T16:05:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T21:07:18.000Z", "max_forks_repo_path": "docs/tutorials/06-tutorial-cb6-but-gromacs.ipynb", "max_forks_repo_name": "jaketanderson/pAPRika", "max_forks_repo_head_hexsha": "5376f44ee1f7a0785f712b3b6c7bfa4c698ca65e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2017-07-06T07:55:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T05:05:44.000Z", "avg_line_length": 35.8442622951, "max_line_length": 559, "alphanum_fraction": 0.5768808598, "converted": true, "num_tokens": 8396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.07477003723826106, "lm_q1q2_score": 0.03447024175664504}}
{"text": "```python\n%matplotlib inline\n```\n\n\n# Kuka Reinforcement Learning (DQN)\n\n\nThis notebook shows how to train a Deep Q Learning (DQN) agent\non the pyBullet Kuka environment based on:\nhttps://pytorch.org/tutorials/intermediate/reinforcement_q_learning.html\n\n**Task**\nThe agent has to decide between seven (2+2+2+1) actions - moving the manipulator \nin $x$ (2), or $y$ (2) directions by vertical angle offset (2) or not moving at all (1) - so that the manipulator can grasp an object. We assume that the velocity for each directions equal and there is a \"height hack\" where the gripper automatically moves down for each action.\n\nAs the agent observes the current state of the environment and chooses\nan action, the environment *transitions* to a new state, and also\nreturns a reward that indicates the consequences of the action. In this\ntask, the reward is 1 if one of the objects is above height .2 at the end \nof the episode.\n\nThe pyBullet Kuka is designed so that the inputs to the agent are (48, 48, 3) images\nrepresenting the environment state.\nNeural networks can solve the task purely by looking at the\nscene, so we'll use stack of consecutive screens as an input. In this way, we are hoping to capture the dynamics of the environment.\n\n**Packages**\n\nFirst, let's import needed packages. Firstly, we need gym\n(Install using `pip install gym`) and pyBullet (Install using `pip install pybullet`.\nWe'll also use the following from PyTorch:\n\n-  neural networks (``torch.nn``)\n-  optimization (``torch.optim``)\n-  automatic differentiation (``torch.autograd``)\n-  utilities for vision tasks (``torchvision`` - `a separate\n   package <https://github.com/pytorch/vision>`__).\n\n\nAlso for display the average reward and agent progress we are going to use tensorboarX (`pip install tensorboardX`.) To run tensorboard web server, you need to install it using `pip install tensorboard`.\n\n\n\n\n```python\n!pip install pybullet\n!pip install tensorboardX\nimport gym\nimport math\nimport random\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom collections import namedtuple\nimport collections\nfrom itertools import count\nimport timeit\nfrom datetime import timedelta\nfrom PIL import Image\nfrom tensorboardX import SummaryWriter\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torchvision.transforms as T\n\n\nfrom pybullet_envs.bullet.kuka_diverse_object_gym_env import KukaDiverseObjectEnv\nfrom gym import spaces\nimport pybullet as p\n\nenv = KukaDiverseObjectEnv(renders=False, isDiscrete=True, removeHeightHack=False, maxSteps=20)\nenv.cid = p.connect(p.DIRECT)\n\n# set up matplotlib\nis_ipython = 'inline' in matplotlib.get_backend()\nif is_ipython:\n    from IPython import display\n\nplt.ion()\n\n# if gpu is to be used\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n```\n\n    Requirement already satisfied: pybullet in /home/monster/anaconda3/envs/python36/lib/python3.6/site-packages (2.6.1)\n    Requirement already satisfied: tensorboardX in /home/monster/anaconda3/envs/python36/lib/python3.6/site-packages (2.0)\n    Requirement already satisfied: six in /home/monster/anaconda3/envs/python36/lib/python3.6/site-packages (from tensorboardX) (1.13.0)\n    Requirement already satisfied: numpy in /home/monster/anaconda3/envs/python36/lib/python3.6/site-packages (from tensorboardX) (1.17.4)\n    Requirement already satisfied: protobuf>=3.8.0 in /home/monster/anaconda3/envs/python36/lib/python3.6/site-packages (from tensorboardX) (3.11.2)\n    Requirement already satisfied: setuptools in /home/monster/anaconda3/envs/python36/lib/python3.6/site-packages (from protobuf>=3.8.0->tensorboardX) (42.0.2.post20191203)\n    current_dir=/home/monster/anaconda3/envs/python36/lib/python3.6/site-packages/pybullet_envs/bullet\n\n\n# Replay Memory\n\n\nWe'll be using experience replay memory for training our DQN. It stores\nthe transitions that the agent observes, allowing us to reuse this data\nlater. By sampling from it randomly, the transitions that build up a\nbatch are decorrelated. It has been shown that this greatly stabilizes\nand improves the DQN training procedure.\n\nFor this, we're going to need two classses:\n\n-  ``Transition`` - a named tuple representing a single transition in\n   our environment. It essentially maps (state, action) pairs\n   to their (next_state, reward) result, with the state being the\n   consecutive stacked screens image as described later on.\n-  ``ReplayMemory`` - a cyclic buffer of bounded size that holds the\n   transitions observed recently. It also implements a ``.sample()``\n   method for selecting a random batch of transitions for training.\n\n\n\n\n\n```python\nTransition = namedtuple('Transition',\n                        ('state', 'action', 'next_state', 'reward'))\n\n\nclass ReplayMemory(object):\n\n    def __init__(self, capacity):\n        self.capacity = capacity\n        self.memory = []\n        self.position = 0\n\n    def push(self, *args):\n        \"\"\"Saves a transition.\"\"\"\n        if len(self.memory) < self.capacity:\n            self.memory.append(None)\n        self.memory[self.position] = Transition(*args)\n        self.position = (self.position + 1) % self.capacity\n\n    def sample(self, batch_size):\n        return random.sample(self.memory, batch_size)\n\n    def __len__(self):\n        return len(self.memory)\n```\n\nNow, let's define our model. But first, let's quickly recap what a DQN is.\n\n# DQN algorithm\n\n\nOur aim will be to train a policy that tries to maximize the discounted,\ncumulative reward\n$R_{t_0} = \\sum_{t=t_0}^{\\infty} \\gamma^{t - t_0} r_t$, where\n$R_{t_0}$ is also known as the *return*. The discount,\n$\\gamma$, should be a constant between $0$ and $1$\nthat ensures the sum converges. It makes rewards from the uncertain far\nfuture less important for our agent than the ones in the near future\nthat it can be fairly confident about.\n\nThe main idea behind Q-learning is that if we had a function\n$Q^*: State \\times Action \\rightarrow \\mathbb{R}$, that could tell\nus what our return would be, if we were to take an action in a given\nstate, then we could easily construct a policy that maximizes our\nrewards:\n\n\\begin{align}\\pi^*(s) = \\arg\\!\\max_a \\ Q^*(s, a)\\end{align}\n\nHowever, we don't know everything about the world, so we don't have\naccess to $Q^*$. But, since neural networks are universal function\napproximators, we can simply create one and train it to resemble\n$Q^*$.\n\nFor our training update rule, we'll use a fact that every $Q$\nfunction for some policy obeys the Bellman equation:\n\n\\begin{align}Q^{\\pi}(s, a) = r + \\gamma Q^{\\pi}(s', \\pi(s'))\\end{align}\n\nThe difference between the two sides of the equality is known as the\ntemporal difference error, $\\delta$:\n\n\\begin{align}\\delta = Q(s, a) - (r + \\gamma \\max_a Q(s', a))\\end{align}\n\nTo minimise this error, we will use the `Huber\nloss <https://en.wikipedia.org/wiki/Huber_loss>`__. The Huber loss acts\nlike the mean squared error when the error is small, but like the mean\nabsolute error when the error is large - this makes it more robust to\noutliers when the estimates of $Q$ are very noisy. We calculate\nthis over a batch of transitions, $B$, sampled from the replay\nmemory:\n\n\\begin{align}\\mathcal{L} = \\frac{1}{|B|}\\sum_{(s, a, s', r) \\ \\in \\ B} \\mathcal{L}(\\delta)\\end{align}\n\n\\begin{align}\\text{where} \\quad \\mathcal{L}(\\delta) = \\begin{cases}\n     \\frac{1}{2}{\\delta^2}  & \\text{for } |\\delta| \\le 1, \\\\\n     |\\delta| - \\frac{1}{2} & \\text{otherwise.}\n   \\end{cases}\\end{align}\n\n## Q-network\n\n\nOur model will be a convolutional neural network that takes in the\nstacked screen patches. It has seven\noutputs, representing $Q(s, d_x = d_v)$, $Q(s, d_x = -d_v)$, $Q(s, d_y = d_v)$, $Q(s, d_y = -d_v)$, $Q(s, d_a=0.25)$, \nand $Q(s, d_a=-0.25)$ (where $d_v=0.06$ is the velocity in PyBullet, $d_a$ is vertical angle offset for the gripper, and $s$ is the input to the\nnetwork). This discretization of action is based on the continuous action which is a 5-vector parameterizing XYZ offset, vertical angle offset (radians), and grasp angle (radians). The continuous action (5-vector) is discretized as follows with \"height hack\" where the gripper automatically moves down for each action, and grasp angle in PyBullet is set to 0.3:\n```\n        dx = [0, -dv, dv, 0, 0, 0, 0][action]\n        dy = [0, 0, 0, -dv, dv, 0, 0][action]\n        dz = -dv\n        da = [0, 0, 0, 0, 0, -0.25, 0.25][action]\n        \n        action_continuous = [dx, dy, dz, da, 0.3]\n```\nIn effect, the network is trying to predict the *expected return* of\ntaking each action given the current input. In order to capture the dynamics of the environment, we stack 5 consecutive screens of the environment after each step together and then feed them to the network.\n\n\n```python\nSTACK_SIZE = 5\n```\n\n\n```python\nclass DQN(nn.Module):\n    def __init__(self, h, w, outputs):\n        super(DQN, self).__init__()  \n        self.conv1 = nn.Conv2d(STACK_SIZE, 32, kernel_size=8, stride=4)\n        self.bn1 = nn.BatchNorm2d(32)\n        self.conv2 = nn.Conv2d(32, 64, kernel_size=4, stride=2)\n        self.bn2 = nn.BatchNorm2d(64)\n        self.conv3 = nn.Conv2d(64, 64, kernel_size=3, stride=1)\n\n        # Number of Linear input connections depends on output of conv2d layers\n        # and therefore the input image size, so compute it.\n        def conv2d_size_out(size, kernel_size = 5, stride = 2):\n            return (size - (kernel_size - 1) - 1) // stride  + 1\n        convw = conv2d_size_out(conv2d_size_out(conv2d_size_out(w,8,4),4,2),3,1)\n        convh = conv2d_size_out(conv2d_size_out(conv2d_size_out(h,8,4),4,2),3,1)\n        linear_input_size = convw * convh * 64\n        self.linear = nn.Linear(linear_input_size, 512)\n        self.head = nn.Linear(512, outputs)\n\n    # Called with either one element to determine next action, or a batch\n    # during optimization. Returns tensor([[left0exp,right0exp]...]).\n    def forward(self, x):\n        x = F.relu(self.bn1(self.conv1(x)))\n        x = F.relu(self.bn2(self.conv2(x)))\n        x = F.relu(self.conv3(x))\n        x = F.relu(self.linear(x.view(x.size(0), -1)))\n        return self.head(x)\n```\n\n## Input extraction\n\n\nThe code below are utilities for extracting and processing rendered\nimages from the environment. It uses the ``torchvision`` package, which\nmakes it easy to compose image transforms. Once you run the cell it will\ndisplay an example patch that it extracted.\n\n\n\n\n\n```python\npreprocess = T.Compose([T.ToPILImage(),\n                    T.Grayscale(num_output_channels=1),\n                    T.Resize(40, interpolation=Image.CUBIC),\n                    T.ToTensor()])\n\ndef get_screen():\n    global stacked_screens\n    # Returned screen requested by gym is 400x600x3, but is sometimes larger\n    # such as 800x1200x3. Transpose it into torch order (CHW).\n    screen = env._get_observation().transpose((2, 0, 1))\n    # Convert to float, rescale, convert to torch tensor\n    # (this doesn't require a copy)\n    \n    screen = np.ascontiguousarray(screen, dtype=np.float32) / 255\n    screen = torch.from_numpy(screen)\n    # Resize, and add a batch dimension (BCHW)\n    return preprocess(screen).unsqueeze(0).to(device)\n\n\nenv.reset()\nplt.figure()\nplt.imshow(get_screen().cpu().squeeze(0)[-1].numpy(),cmap='Greys',\n           interpolation='none')\nplt.title('Example extracted screen')\nplt.show()\n```\n\n# Training\n\n\n## Hyperparameters and utility function\n\nThis cell instantiates our model and its optimizer, and defines the\nutility function:\n\n-  ``select_action`` - will select an action accordingly to an epsilon\n   greedy policy. Simply put, we'll sometimes use our model for choosing\n   the action, and sometimes we'll just sample one uniformly. The\n   probability of choosing a random action will start at ``EPS_START``\n   and will decay exponentially towards ``EPS_END``. ``EPS_DECAY``\n   controls the rate of the decay.\n\n\n\n```python\nBATCH_SIZE = 32\nGAMMA = 0.99\nEPS_START = 0.9\nEPS_END = 0.1\nEPS_DECAY = 200\nEPS_DECAY_LAST_FRAME = 10**4\nTARGET_UPDATE = 1000\nLEARNING_RATE = 1e-4\n\n# Get screen size so that we can initialize layers correctly based on shape\n# returned from pybullet (48, 48, 3).  \ninit_screen = get_screen()\n_, _, screen_height, screen_width = init_screen.shape\n\n# Get number of actions from gym action space\nn_actions = env.action_space.n\n\npolicy_net = DQN(screen_height, screen_width, n_actions).to(device)\ntarget_net = DQN(screen_height, screen_width, n_actions).to(device)\ntarget_net.load_state_dict(policy_net.state_dict())\ntarget_net.eval()\n\noptimizer = optim.Adam(policy_net.parameters(), lr=LEARNING_RATE)\nmemory = ReplayMemory(10000)\n\n\neps_threshold = 0\n\ndef select_action(state, i_episode):\n    global steps_done\n    global eps_threshold\n    sample = random.random()\n    eps_threshold = max(EPS_END, EPS_START - i_episode / EPS_DECAY_LAST_FRAME)\n    if sample > eps_threshold:\n        with torch.no_grad():\n            # t.max(1) will return largest column value of each row.\n            # second column on max result is index of where max element was\n            # found, so we pick action with the larger expected reward.\n            return policy_net(state).max(1)[1].view(1, 1)\n    else:\n        return torch.tensor([[random.randrange(n_actions)]], device=device, dtype=torch.long)\n\n```\n\n# Training loop\n\nFinally, the code for training our model.\n\nHere, you can find an ``optimize_model`` function that performs a\nsingle step of the optimization. It first samples a batch, concatenates\nall the tensors into a single one, computes $Q(s_t, a_t)$ and\n$V(s_{t+1}) = \\max_a Q(s_{t+1}, a)$, and combines them into our\nloss. By defition we set $V(s) = 0$ if $s$ is a terminal\nstate. We also use a target network to compute $V(s_{t+1})$ for\nadded stability. The target network has its weights kept frozen most of\nthe time, but is updated with the policy network's weights every so often.\nThis is usually a set number of steps but we shall use episodes for\nsimplicity.\n\n\n\n\n\n```python\ndef optimize_model():\n    if len(memory) < BATCH_SIZE:\n        return\n    transitions = memory.sample(BATCH_SIZE)\n    # Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for\n    # detailed explanation). This converts batch-array of Transitions\n    # to Transition of batch-arrays.\n    batch = Transition(*zip(*transitions))\n\n    # Compute a mask of non-final states and concatenate the batch elements\n    # (a final state would've been the one after which simulation ended)\n    non_final_mask = torch.tensor(tuple(map(lambda s: s is not None,\n                                          batch.next_state)), device=device, dtype=torch.bool)\n    non_final_next_states = torch.cat([s for s in batch.next_state\n                                                if s is not None])\n    state_batch = torch.cat(batch.state)\n    action_batch = torch.cat(batch.action)\n    reward_batch = torch.cat(batch.reward)\n\n    # Compute Q(s_t, a) - the model computes Q(s_t), then we select the\n    # columns of actions taken. These are the actions which would've been taken\n    # for each batch state according to policy_net\n    state_action_values = policy_net(state_batch).gather(1, action_batch)\n\n    # Compute V(s_{t+1}) for all next states.\n    # Expected values of actions for non_final_next_states are computed based\n    # on the \"older\" target_net; selecting their best reward with max(1)[0].\n    # This is merged based on the mask, such that we'll have either the expected\n    # state value or 0 in case the state was final.\n    next_state_values = torch.zeros(BATCH_SIZE, device=device)\n    next_state_values[non_final_mask] = target_net(non_final_next_states).max(1)[0].detach()\n    # Compute the expected Q values\n    expected_state_action_values = (next_state_values * GAMMA) + reward_batch\n\n    # Compute Huber loss\n    loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1))\n\n    # Optimize the model\n    optimizer.zero_grad()\n    loss.backward()\n    for param in policy_net.parameters():\n        param.grad.data.clamp_(-1, 1)\n    optimizer.step()\n```\n\nBelow, you can find the main training loop. At the beginning we reset\nthe environment and initialize the ``state`` Tensor. Then, we sample\nan action, execute it, observe the next screen and the reward (always\n1), and optimize our model once. When the episode ends (our model\nfails), we restart the loop.\n\n\n```python\nPATH = 'policy_dqn.pt'\n```\n\n\n```python\nnum_episodes = 10000000\nwriter = SummaryWriter()\ntotal_rewards = []\nten_rewards = 0\nbest_mean_reward = None\nstart_time = timeit.default_timer()\nfor i_episode in range(num_episodes):\n    # Initialize the environment and state\n    env.reset()\n    state = get_screen()\n    stacked_states = collections.deque(STACK_SIZE*[state],maxlen=STACK_SIZE)\n    for t in count():\n        stacked_states_t =  torch.cat(tuple(stacked_states),dim=1)\n        # Select and perform an action\n        action = select_action(stacked_states_t, i_episode)\n        _, reward, done, _ = env.step(action.item())\n        reward = torch.tensor([reward], device=device)\n\n        # Observe new state\n        next_state = get_screen()\n        if not done:\n            next_stacked_states = stacked_states\n            next_stacked_states.append(next_state)\n            next_stacked_states_t =  torch.cat(tuple(next_stacked_states),dim=1)\n        else:\n            next_stacked_states_t = None\n            \n        # Store the transition in memory\n        memory.push(stacked_states_t, action, next_stacked_states_t, reward)\n\n        # Move to the next state\n        stacked_states = next_stacked_states\n        \n        # Perform one step of the optimization (on the target network)\n        optimize_model()\n        if done:\n            reward = reward.cpu().numpy().item()\n            ten_rewards += reward\n            total_rewards.append(reward)\n            mean_reward = np.mean(total_rewards[-100:])*100\n            writer.add_scalar(\"epsilon\", eps_threshold, i_episode)\n            if (best_mean_reward is None or best_mean_reward < mean_reward) and i_episode > 100:\n                # For saving the model and possibly resuming training\n                torch.save({\n                        'policy_net_state_dict': policy_net.state_dict(),\n                        'target_net_state_dict': target_net.state_dict(),\n                        'optimizer_policy_net_state_dict': optimizer.state_dict()\n                        }, PATH)\n                if best_mean_reward is not None:\n                    print(\"Best mean reward updated %.1f -> %.1f, model saved\" % (best_mean_reward, mean_reward))\n                best_mean_reward = mean_reward\n            break\n            \n    if i_episode%10 == 0:\n            writer.add_scalar('ten episodes average rewards', ten_rewards/10.0, i_episode)\n            ten_rewards = 0\n    \n    # Update the target network, copying all weights and biases in DQN\n    if i_episode % TARGET_UPDATE == 0:\n        target_net.load_state_dict(policy_net.state_dict())\n    if i_episode>=200 and mean_reward>50:\n        print('Environment solved in {:d} episodes!\\tAverage Score: {:.2f}'.format(i_episode+1, mean_reward))\n        break\n\n\nprint('Average Score: {:.2f}'.format(mean_reward))\nelapsed = timeit.default_timer() - start_time\nprint(\"Elapsed time: {}\".format(timedelta(seconds=elapsed)))\nwriter.close()\nenv.close()\n```\n\n    Best mean reward updated 36.0 -> 37.0, model saved\n    Best mean reward updated 37.0 -> 38.0, model saved\n    Best mean reward updated 38.0 -> 39.0, model saved\n    Best mean reward updated 39.0 -> 40.0, model saved\n    Best mean reward updated 40.0 -> 41.0, model saved\n    Best mean reward updated 41.0 -> 42.0, model saved\n    Best mean reward updated 42.0 -> 43.0, model saved\n    Best mean reward updated 43.0 -> 44.0, model saved\n    Best mean reward updated 44.0 -> 45.0, model saved\n    Best mean reward updated 45.0 -> 46.0, model saved\n    Best mean reward updated 46.0 -> 47.0, model saved\n    Best mean reward updated 47.0 -> 48.0, model saved\n    Best mean reward updated 48.0 -> 49.0, model saved\n    Best mean reward updated 49.0 -> 50.0, model saved\n    Best mean reward updated 50.0 -> 51.0, model saved\n    Environment solved in 7412 episodes!\tAverage Score: 51.00\n    Average Score: 51.00\n    Elapsed time: 3:11:17.312433\n\n\nActions are chosen either randomly or based on a policy, getting the next\nstep sample from the gym environment. We record the results in the\nreplay memory and also run optimization step on every iteration.\nOptimization picks a random batch from the replay memory to do training of the\nnew policy. \"Older\" target_net is also used in optimization to compute the\nexpected Q values; it is updated occasionally to keep it current.\n\n## Evaluation\n\n\n```python\nepisode = 10\nscores_window = collections.deque(maxlen=100)  # last 100 scores\nenv = KukaDiverseObjectEnv(renders=False, isDiscrete=True, removeHeightHack=False, maxSteps=20, isTest=True)\nenv.cid = p.connect(p.DIRECT)\n# load the model\ncheckpoint = torch.load(PATH)\npolicy_net.load_state_dict(checkpoint['policy_net_state_dict'])\n\n# evaluate the model\nfor i_episode in range(episode):\n    env.reset()\n    state = get_screen()\n    stacked_states = collections.deque(STACK_SIZE*[state],maxlen=STACK_SIZE)\n    for t in count():\n        stacked_states_t =  torch.cat(tuple(stacked_states),dim=1)\n        # Select and perform an action\n        action = policy_net(stacked_states_t).max(1)[1].view(1, 1)\n        _, reward, done, _ = env.step(action.item())\n        # Observe new state\n        next_state = get_screen()\n        stacked_states.append(next_state)\n        if done:\n            break\n    print(\"Episode: {0:d}, reward: {1}\".format(i_episode+1, reward), end=\"\\n\")\n```\n\n    Episode: 1, reward: 1\n    Episode: 2, reward: 0\n    Episode: 3, reward: 0\n    Episode: 4, reward: 1\n    Episode: 5, reward: 0\n    Episode: 6, reward: 1\n    Episode: 7, reward: 0\n    Episode: 8, reward: 1\n    Episode: 9, reward: 0\n    Episode: 10, reward: 1\n\n", "meta": {"hexsha": "6302267194534c4d5194ae038e35e257e3b7a33c", "size": 41888, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "kuka_rl.ipynb", "max_stars_repo_name": "pankhurivanjani/kuka_rl", "max_stars_repo_head_hexsha": "e70c08620f74965b524b2fed39e03cc4242aaf40", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 58, "max_stars_repo_stars_event_min_datetime": "2019-10-29T14:20:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T07:46:44.000Z", "max_issues_repo_path": "kuka_rl.ipynb", "max_issues_repo_name": "7Savage/kuka_rl", "max_issues_repo_head_hexsha": "e6bcda980ab38a77ce18954bec1ae5cc703fe8e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-04-11T12:20:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T11:36:59.000Z", "max_forks_repo_path": "kuka_rl.ipynb", "max_forks_repo_name": "7Savage/kuka_rl", "max_forks_repo_head_hexsha": "e6bcda980ab38a77ce18954bec1ae5cc703fe8e5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2020-01-28T07:00:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T15:41:32.000Z", "avg_line_length": 58.9142053446, "max_line_length": 12736, "alphanum_fraction": 0.7008928571, "converted": true, "num_tokens": 5640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.07921032084852898, "lm_q1q2_score": 0.03437581106943139}}
{"text": "## Chapter 8\n\n\n```python\nimport sys\nsys.path.append(\"..\")\nfrom importlib import reload\n```\n\n\n```python\nimport Ch6.utilities as ch6_utils\nreload(ch6_utils)\n```\n\n\n\n\n    <module 'Ch6.utilities' from '../Ch6/utilities.py'>\n\n\n\n\n```python\nimport Ch7.utilities as ch7_utils\nreload(ch7_utils)\n```\n\n\n\n\n    <module 'Ch7.utilities' from '../Ch7/utilities.py'>\n\n\n\n\n```python\nimport Ch8.utilities as ch8_utils\nreload(ch8_utils)\n```\n\n\n\n\n    <module 'Ch8.utilities' from '../Ch8/utilities.py'>\n\n\n\n\n```python\nimport numpy as np\nfrom sympy import *\ninit_printing(use_latex='mathjax')\nimport control\nimport matplotlib.pyplot as plt\n```\n\n### Problem 8.1\n\nIt is given that\n\n\\begin{eqnarray}\n\\Phi_c (s) \\triangleq [ \\Phi^{-1}(s) + BG ]^{-1}.\n\\end{eqnarray}\n\nDo algebraic manipulations to get rid of the $\\Phi^{-1}$ on the RHS:\n\n\\begin{eqnarray}\n[ \\Phi^{-1}(s) + BG ] \\Phi_c (s) &=& I \\\\\n\\Phi(s) [ \\Phi^{-1}(s) + BG ] \\Phi_c(s) &=& \\Phi(s) \\\\\n[ I + \\Phi(s) BG] \\Phi_c(s) &=& \\Phi(s) \\\\\n\\Phi_c(s) &=& [ I + \\Phi(s) BG]^{-1} \\Phi(s).\n\\end{eqnarray}\n\nNow, it remains to show that:\n\n\\begin{eqnarray}\n\\Phi(s) - \\Phi(s) B [ \\Phi(s) + G \\Phi(s) B]^{-1} G \\Phi(s) &=& [ I + \\Phi(s) BG]^{-1} \\Phi(s) \\\\\n\\implies I - \\Phi(s) B [ \\Phi(s) + G \\Phi(s) B]^{-1} G &=& [ I + \\Phi(s) BG]^{-1}\n\\end{eqnarray}\n\nUsing the hint about block-diagram manipulations, it can be shown that $\\Phi(s) B [ \\Phi(s) + G \\Phi(s) B]^{-1} = [ \\Phi(s) + \\Phi(s) B G]^{-1} \\Phi(s) B$:\n\nNow, plug in the above to the previous relation:\n\\begin{eqnarray}\nI - [\\Phi(s) + \\Phi(s) B G]^{-1} \\Phi(s) B G &=& [ I + \\Phi(s) BG]^{-1}\n\\end{eqnarray}\n\nLeft-multiply both sides by $I + \\Phi(s) BG$:\n\\begin{eqnarray}\n(I + \\Phi(s) BG) \\bigl ( I - [\\Phi(s) + \\Phi(s) B G]^{-1} \\Phi(s) B G \\bigr ) &=& I \\\\\n(I + \\Phi(s) BG) - \\Phi(s) B G &=& I \\\\\nI &=& I\n\\end{eqnarray}\n\nSo, through algebraic reductions, a tautology is reached.  Therefore, it is true that\n\n\\begin{eqnarray}\n\\Phi_c (s) \\triangleq [ \\Phi^{-1}(s) + BG ]^{-1} = \\Phi(s) - \\Phi(s) B [ \\Phi(s) + G \\Phi(s) B]^{-1} G \\Phi(s)\n\\end{eqnarray}\n\n### Problem 8.2\n\nTransform the system of equations from $\\mathbf{\\hat x}$ to $\\mathbf{\\hat w}$, where $\\mathbf{\\hat x} = P \\mathbf{\\hat w}_1 + Q \\mathbf{\\hat w}_2$, and $\\mathbf{w}_1 = C \\mathbf{x}$ and $\\mathbf{w}_2 = M \\mathbf{x}$.\n\nThe feedback law $u = -G \\mathbf{\\hat x}$ becomes:\n\\begin{eqnarray}\nu &=& -G (P \\mathbf{\\hat w}_1 + Q \\mathbf{\\hat w}_2) \\\\\n&=& -G P \\mathbf{\\hat w}_1 - G Q \\mathbf{\\hat w}_2 \\\\\n&\\triangleq& -\\bar G_1 \\mathbf{\\hat w}_1 -  \\bar G_2 \\mathbf{\\hat w}_2.\n\\end{eqnarray}\n\nThe dynamics of the closed-loop transformed system is:\n\\begin{eqnarray}\n\\mathbf{\\dot w} &=& \\bar A \\mathbf{w} + \\bar B u \\\\\n&=& \\bar A \\mathbf{w} - \\bar B ( \\bar G_1 \\mathbf{\\hat w}_1 + \\bar G_2 \\mathbf{\\hat w}_2 ) \n\\end{eqnarray}\n\nNow, follow the steps leading up to Eqn. 8.27:  $\\mathbf{e} = \\mathbf{w} - \\mathbf{\\hat w} \\implies \\mathbf{\\hat w} = \\mathbf{w} - \\mathbf{e}$:\n\n\\begin{eqnarray}\n\\mathbf{\\dot w} &=& \\bar A \\mathbf{w} - \\bar B \\bigl [ \\bar G_1 (\\mathbf{w}_1 - \\mathbf{e}_1) + \\bar G_2 (\\mathbf{w}_2 - \\mathbf{e}_2) \\bigr ] \\\\\n&=& (\\bar A - \\bar B \\bar G) \\mathbf{w} + \\bar B( \\bar G_1 \\mathbf{e}_1 + \\bar G_2 \\mathbf{e_2}).\n\\end{eqnarray}\n\nThe remainder of the derivation for the transformed system follows _exactly_ the same steps in deriving Eqn. 8.27:\n\n\\begin{eqnarray}\n\\mathbf{w}(s) &=& (sI - \\mathbf{\\bar A}_c)^{-1} \\bar B \\bar G_2 \\mathbf{e}_2(s) + (sI - \\mathbf{\\bar A}_c)^{-1} \\mathbf{w}(0) \\\\\n\\mathbf{e}_2 &=& (sI - \\bar F)^{-1} \\mathbf{e}_2(0) \\\\\n\\implies \\mathbf{w}(s) &=& (sI - \\mathbf{\\bar A}_c)^{-1} \\bar B \\bar G_2 (sI - \\bar F)^{-1} \\mathbf{e}_2(0) + (sI - \\mathbf{\\bar A}_c)^{-1} \\mathbf{w}(0) \\\\\n&=& \\frac{\\text{adj}(sI - \\mathbf{\\bar A}_c) \\bar B \\bar G_2 \\text{adj}(sI - \\bar F)}{|sI - \\mathbf{\\bar A}_c| |sI - \\bar F|} \\mathbf{e}_2(0) + (sI - \\mathbf{\\bar A}_c)^{-1} \\mathbf{w}(0)\n\\end{eqnarray}\n\nThe characteristic equation is then $|sI - \\mathbf{\\bar A}_c||sI - \\bar F| = 0$, with\n\n\\begin{eqnarray}\n\\bar A &=& \\begin{pmatrix}\nCAP & CAQ \\\\\nMAP & MAQ\n\\end{pmatrix}\\\\\n\\bar B &=& \\begin{pmatrix}\nCB \\\\\nMB\n\\end{pmatrix} \\\\\n\\bar F &=& (M - LC)AQ \\\\\n\\mathbf{\\bar A}_c &=& \\bar A - \\bar B \\bar G,\n\\end{eqnarray}\n\nwith $\\bar G \\triangleq [\\bar G_1 | \\bar G_2]$.\n\n### Problem 8.3\n\n#### a)\nThe reduced order observer is defined by the matrices $F, \\bar {\\bar G}, H$:\n\\begin{eqnarray}\nF &\\triangleq& A_{uu} - L C_a A_{au} = -\\alpha - L \\times 1 \\times 1 = -\\alpha - L \\\\\n\\bar {\\bar G} &\\triangleq& (A_{ua} - L C_a A_{aa}) C_a^{-1} = 0 - L \\times 1 \\times 0 \\times 1 = 0 \\\\\nH &\\triangleq& B_u - L \\times C_a \\times B_a = \\beta - L \\times 1 \\times 0 = \\beta\n\\end{eqnarray}\n\nThe observability matrix for the available subsystem, $C_a$, is just unity ($=1$).\n\n#### b)\nThe gains from example 8B are:\n\\begin{eqnarray}\nG_1 &=& \\frac{\\bar a_2}{\\beta} \\\\\nG_2 &=& \\frac{\\bar a_1 - \\alpha}{\\beta}\n\\end{eqnarray}\n\nThe feedback law using these gains is:\n\\begin{eqnarray}\nu &=& -G_1 \\hat \\theta - G_2 \\hat \\omega \\\\\n&=& -G_1 y - G_2 (Ly + z),\n\\end{eqnarray}\n\nThe second equality above follows from the fact that $\\theta$ is the measurement from which the reduced order observer for $\\hat \\omega$ is built.\n\nNow, it remains to find the transfer function that takes measurement $y(s)$ to $z(s)$.  Plugging in the control found above into the equation for $z$, $\\dot z = F z + \\bar {\\bar G} y + Hu$, leads to the closed-loop system:\n\\begin{eqnarray}\n\\dot z &=& (F - H G_2) z + (\\bar {\\bar G} - HG_1 C_a^{-1} - H G_2 L) y \\\\\n&\\equiv& \\mathbf{F}_c z + \\mathbf{\\bar G} y \n\\end{eqnarray}\n\nwhich has transfer function representation (see Ch. 3):\n\\begin{eqnarray}\nz(s) = (sI - \\mathbf{F}_c)^{-1} \\mathbf{\\bar G} y(s)\n\\end{eqnarray}\n\nThe feedback law can then be written in the Laplace domain as:\n\\begin{eqnarray}\nu(s) &=& -(G_1 + G_2 L + (sI - \\mathbf{F}_c)^{-1} \\mathbf{\\bar G}) y(s)\n\\end{eqnarray}\n\nPutting this in the form $u(s) = -D(s)y(s)$ gives the compensator:\n\\begin{eqnarray}\nD(s) = G_1 + G_2 L + (sI - \\mathbf{F}_c)^{-1} \\mathbf{\\bar G}.\n\\end{eqnarray}\n\n#### c)\n\nExample 8B gives $\\bar a_1 = 4$ and $\\bar a_2 = 8$.  Plugging these values into $D(s)$ found in the previous section gives:\n\n\n```python\n# use sympy to do reduction\na1, a2, l, s = symbols('a1 a2 l s')\np = a2 + (a1 - 1)*l + ((a1 - 1)*(1-a1)*l - a2)/(s+l+a1)\npprint(simplify(p))\n# the beta term cancels regardless of choice of L\na2 = 8.\na1 = 4.\nq = (-a2 - l*(a1-1.)**2 + (a2 + l*(a1-1.))*(a1 + l + s)) / (s+l+a1)\npprint(simplify(q))\n```\n\n                    2                                 \n    -a\u2082 - l\u22c5(a\u2081 - 1)  + (a\u2082 + l\u22c5(a\u2081 - 1))\u22c5(a\u2081 + l + s)\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                        a\u2081 + l + s                    \n    -9.0\u22c5l + (3.0\u22c5l + 8.0)\u22c5(l + s + 4.0) - 8.0\n    \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   l + s + 4.0                \n\n\nUse `sympy` reduction above:\n\\begin{eqnarray}\nD(s) = \\frac{(3L+8)s + 3L^2 + 3L + 32}{\\beta (s + L + 4)}.\n\\end{eqnarray}\n\n\n```python\nG = control.TransferFunction(np.array([1.]), np.array([1., 1., 0.]))\nL = 1.0\nnum = np.array([3.*L+8., 3.*L**2 + 3.*L+32.])\nden = np.array([1., L+4])\nD = control.TransferFunction(num, den)\ncontrol.root_locus(D*G, PrintGain=False, Plot=True)\n#_, _, _ = control.nyquist_plot(D*G, Plot=True, PrintGain=False)\nplt.show()\n```\n\nFor $L \\ge 0$, the system has infinite gain margin.  As hinted at in Example 8B, this seems to indicate that a compensator derived with a reduced order observer can have simplified form and better performance characteristics.  Nyquist plots don't make much sense to me, but here it is because the problem asked for it.\n\n\n```python\n_, _, _ = control.nyquist_plot(D*G, Plot=True)\nplt.show()\n```\n\n### Problem 8.4\n\n#### a)\nThe gains from Problems 6.1 (regulator) and 7.2 (full-order observer) are:\n\\begin{eqnarray}\nG &=& \\begin{pmatrix}\n-326.53061224, \\ \n-226.32653061, \\\n-812.09061224, \\\n-242.32653061\n\\end{pmatrix}\\\\\nK &=& \\begin{pmatrix}\n-11.935 \\\\\n394.510 \\\\\n-452.006 \\\\\n-1993.619\n\\end{pmatrix}\n\\end{eqnarray}\n\nThe form of the compensator is $D(s) = G (sI - A + BG + KC)^{-1} K$:\n\n\n```python\nA = np.array([[0., 1., 0., 0.], [0., -25., -0.98, 0.], [0., 0., 0., 1.], [0., 25., 10.78, 0.]]).astype('float')\nB = np.array([[0.], [0.5], [0.], [-0.5]]).reshape((4,1)).astype('float')\nC = np.array([[1., 0., 0., 0.]]).reshape((1, 4)).astype('float')\nD = np.zeros((1, 1)).astype('float')\ndesiredPolesCtrl = np.array([-25., -4., np.complex(-2., 2.*np.sqrt(3)), np.complex(-2., -2.*np.sqrt(3))])\nw0 = 5.\ndesiredPolesObsv = np.roots(np.array([1.0, 2.613*w0, (2.+np.sqrt(2))*w0**2, 2.613*w0**3, w0**4]))\ntfD = ch8_utils.fullOrderCompensator(A, B, C, D, desiredPolesCtrl, desiredPolesObsv)\npprint('D(s) = {}'.format(tfD))\nsysplant = control.StateSpace(A, B, C, D)\ntfplant = control.ss2tf(sysplant)\npprint('H(s) = {}'.format(tfplant))\n```\n\n                            D(s) =                         \n    7.648e+05 s^3 + 2.153e+07 s^2 + 5.963e+07 s - 2.041e+05\n    -------------------------------------------------------\n      s^4 + 21.07 s^3 + 232.7 s^2 - 3.807e+05 s - 1.197e+06\n                      H(s) =                    \n                0.5 s^2 + 2.012e-15 s - 4.9     \n    --------------------------------------------\n    s^4 + 25 s^3 - 10.78 s^2 - 245 s + 1.981e-14\n\n\nThe return difference has the desired form for $K=1$ (unity loop gain).\n\n#### b)\nThe return difference $T(s) = 1 + K D(s) H(s)$ is the denominator of the closed-loop transfer function. As shown above, the zeros of $T(s)$ will be the poles of the closed-loop system.  We can find the range of K for which the closed-loop system is stable by the Hurwitz criteria (see Ch. 4), or just use the `zero` method of `python-control` to find some numeric range for $K$.\n\n\n```python\n# T(s) = 1 + Kb*D(s)*H(s) (Kb != K from above!)\nk = np.linspace(0.998, 1.002, 101)\nkStable = ch8_utils.stabilityRange(tfD, tfplant, k)\nif kStable is not None:\n    print('{min} <= k <= {max} defines the range of stable gains.'.format(min=kStable[0], max=kStable[1]))\nelse:\n    print('no stable gains were found in the range provided')\n```\n\n    0.99972 <= k <= 1.001 defines the range of stable gains.\n\n\n#### c)\n\nThe closed-loop compensator was shown to achieve the desired closed-loop poles, but with very slight gain margin.  This is not a good sign. Hopefully, the reduced order observer results in a simpler system and more robust system.\n\n### Problem 8.5\n#### a)\n\n\n```python\nA = np.array([[0., 1., 0., 0.], [0., -25., -0.98, 0.], [0., 0., 0., 1.], [0., 25., 10.78, 0.]]).astype('float')\nB = np.array([[0.], [0.5], [0.], [-0.5]]).reshape((4,1)).astype('float')\nC = np.array([[1., 0., 0., 0.]]).reshape((1, 4)).astype('float')\nD = np.zeros((1, 1)).astype('float')\n\n### Controller ###\ndesiredPolesCtrl = np.array([-25., -4., np.complex(-2., 2.*np.sqrt(3)), np.complex(-2., -2.*np.sqrt(3))])\nG = ch6_utils.bassGura(A, B, desiredPolesCtrl)\n            \n### Observer ###\ndesiredPolesObsv = np.roots(np.array([1.0, 2.*5., 2.*5.**2, 5.**3]))\nAaa = np.array(A[0, 0]).reshape((1, 1))\nAau = np.array(A[0, 1:]).reshape((1, 3))\nAua = np.array(A[1:, 0]).reshape((3, 1))\nAuu = np.array(A[1:, 1:]).reshape((3, 3))\nBa = np.array(B[0]).reshape((1, 1))\nBu = np.array(B[1:]).reshape((3, 1))\nCa = np.array([[1]]).reshape((1, 1)).astype('float')\nL, Gbb, H = ch7_utils.reducedOrderObserver(Aaa, Aau, Aua, Auu, Ba, Bu, Ca, desiredPolesObsv)\n\n### Compensator ###\nG1 = G[0, 0].reshape((1, 1))\nG2 = G[0, 1:].reshape((1, 3))\nF = Auu - L@Aau\nAr = F-H@G2\nBr = Ar@L + Gbb - H@G1\nCr = G2\nDr = G1+G2@L\nsysD = control.StateSpace(Ar, Br, Cr, Dr)\ntfD = control.ss2tf(sysD)\npprint('D(s) = {}'.format(tfD))\nsysplant = control.StateSpace(A, B, C, D)\ntfplant = control.ss2tf(sysplant)\npprint('H(s) = {}'.format(tfplant))\n```\n\n                            D(s) =                         \n    1.049e+05 s^3 + 2.955e+06 s^2 + 8.202e+06 s - 4.082e+04\n    -------------------------------------------------------\n                  s^3 + 18 s^2 - 5.23e+04 s - 1.648e+05    \n                      H(s) =                    \n                0.5 s^2 + 2.012e-15 s - 4.9     \n    --------------------------------------------\n    s^4 + 25 s^3 - 10.78 s^2 - 245 s + 1.981e-14\n\n\nThe return difference has the desired form for $K=1$ (unity loop gain).\n\n#### b)\n\n\n```python\n# T(s) = 1 + Kb*D(s)*H(s) (Kb != K from above!)\nk = np.linspace(0.998, 1.002, 101)\nkStable = ch8_utils.stabilityRange(tfD, tfplant, k)\nif kStable is not None:\n    print('{min} <= k <= {max} defines the range of stable gains.'.format(min=kStable[0], max=kStable[1]))\nelse:\n    print('no stable gains were found in the range provided')\n```\n\n    0.99948 <= k <= 1.00112 defines the range of stable gains.\n\n\n#### c)\nThe compensated system has slightly better stability margins and with lower order.  This would be preferable to the controller from the previous problem.\n\n### Problem 8.6\n\n#### a)\nI'm not drawing any more block diagrams.  As for the compensator:\n\nThe gains found in Problem 6.8 were $G = [0, \\ 6.5, \\ 6.5]$, and for Problem 7.8 was $K = [42.5, \\ 16.5, \\ 2.]$.\n\n\n```python\nR, _C = 2., 1.\nA = np.array([[-3./(R*_C), 1./(R*_C), 0.],[1./(R*_C), -2./(R*_C), 1./(R*_C)], [0., 1./(R*_C), -3./(R*_C)]]).reshape((3, 3)).astype('float')\nB = np.array([[2. / (R*_C)], [0.], [0.]]).reshape((3, 1)).astype('float')\nC = np.array([[0., 0., 1.]]).reshape((1, 3)).astype('float')\nD = np.zeros((1, 1)).astype('float')\ndesiredPolesCtrl = np.roots(np.array([1., 4., 8., 8.]))\nw0 = 3.\ndesiredPolesObsv = np.roots(np.array([1.0, 2.*w0, 2.*w0**2, w0**3]))\ntfD = ch8_utils.fullOrderCompensator(A, B, C, D, desiredPolesCtrl, desiredPolesObsv)\npprint('D(s) = {}'.format(tfD))\nsysplant = control.StateSpace(A, B, C, D)\ntfplant = control.ss2tf(sysplant)\npprint('H(s) = {}'.format(tfplant))\n```\n\n             D(s) =           \n    120.3 s^2 + 552.5 s + 624 \n    --------------------------\n    s^3 + 6 s^2 + 21.25 s + 40\n             H(s) =           \n                    0.25      \n    --------------------------\n    s^3 + 4 s^2 + 4.75 s + 1.5\n\n\n$0$ is not a zero of the return difference, so then it is not a pole of the closed-loop transfer function.  This means that the compensator does _not_ provide true integral control.\n\n#### b)\n\n_(omitted)_\n\n#### c)\n\n\n```python\nH = tfD*tfplant\ncontrol.root_locus(H, Plot=True, PrintGain=False)\nplt.show()\n```\n\n\n```python\ncontrol.bode_plot(H)\nplt.show()\ngm, pm, _, _ = control.margin(H)\nprint('Gain margin (dB): {}'.format(control.mag2db(gm)))\nprint('Phase margin (dB): {}'.format(control.mag2db(pm)))\n```\n\n### Problem 8.7\n\n#### a)\n\n\n```python\n# with K, M, k, R, r = 40, 1, 2, 100, 0.02\nA = np.array([[0, 0, 1, 0], [0, 0, 0, 1], [-40, 40, -100, 0], [40, -40, 0, -100]]).astype('float')\nB = np.array([[0], [0], [1], [0]]).astype('float')\nC = np.array([1, 0, 0, 0]).astype('float').reshape((1, 4))\nD = np.zeros((1, 1)).astype('float')\n\n## from Problem 6.3\nclosedLoopPoles = np.array([np.complex(-1., -1.), np.complex(-1., 1.), np.complex(-100., -100.), np.complex(-100., 100.)])\nG = ch6_utils.bassGura(A, B, closedLoopPoles)\n\nH = control.ss2tf(control.StateSpace(A, B, C, D))\nN = control.zero(H)\npoly1 = np.poly(N)\n\n# place 2 remaining observer poles in a butterworth pattern order 2 -> z**2 + sqrt(2)*z + 1\n# z = s/w0\nw0 = 2\np2 = np.poly(np.roots([1., 1.414*w0, w0**2]))\np = np.polymul(poly1, p2)\n\nK = ch7_utils.obsBassGura(A, C, np.roots(p))\npprint('K = ')\npprint(K)\n```\n\n    K = \n    [[-9.7172000e+01] \n     [ 1.8189894e-11] \n     [ 9.6812000e+03] \n     [ 4.0000000e+01]]\n\n\n#### b) and c)\n\n\n```python\nAbarc = A - B.dot(G) - K.dot(C)\nsysD = control.StateSpace(Abarc, K, G, np.zeros((1, 1)))\ntfD = control.ss2tf(sysD)\npprint('D(s) = {}'.format(tfD))\nsysplant = control.StateSpace(A, B, C, np.zeros((1, 1)))\ntfplant = control.ss2tf(sysplant)\npprint('H(s) = {}'.format(tfplant))\n\nH = tfD*tfplant\n\ngm, pm, _, _ = control.margin(H)\nprint('Gain margin (dB): {}'.format(control.mag2db(gm)))\nprint('Phase margin: {}'.format(pm))\n\ncontrol.root_locus(H, Plot=True, PrintGain=False)\nplt.show()\n```\n\nThe gain and phase margins here suck!  Maybe the design will be better in the next problem.\n\n### Problem 8.8\n\n#### a)\n\n\n```python\n# with K, M, k, R, r = 40, 1, 2, 100, 0.02\nA = np.array([[0, 0, 1, 0], [0, 0, 0, 1], [-40, 40, -100, 0], [40, -40, 0, -100]]).astype('float')\nB = np.array([[0], [0], [1], [0]]).astype('float')\nC = np.array([0, 1, 0, 0]).astype('float').reshape((1, 4))\nD = np.zeros((1, 1)).astype('float')\n\n## from Problem 6.3\nclosedLoopPoles = np.array([np.complex(-1., -1.), np.complex(-1., 1.), np.complex(-100., -100.), np.complex(-100., 100.)])\nG = ch6_utils.bassGura(A, B, closedLoopPoles)\n\nH = control.ss2tf(control.StateSpace(A, B, C, D))\nN = control.zero(H)\npoly1 = np.poly(N)\n\n# place 4 remaining observer poles in a butterworth pattern order 4\n# z = s/w0\nw0 = 2\np2 = np.poly(np.roots([1., 2.613*w0, (2.+np.sqrt(2.))*w0**2, 2.613*w0**3, w0**4]))\np = np.polymul(poly1, p2)\nK = ch7_utils.obsBassGura(A, C, np.roots(p))\npprint('K = ')\npprint(K)\n```\n\n    K = \n     [[-2.35323455e+04]\n      [-1.94774000e+02]\n      [ 2.34382390e+06]\n     [ 2.88884569e+04]]\n\n\n#### b) and c)\n\n\n```python\nAbarc = A - B.dot(G) - K.dot(C)\nsysD = control.StateSpace(Abarc, K, G, np.zeros((1, 1)))\ntfD = control.ss2tf(sysD)\npprint('D(s) = {}'.format(tfD))\nsysplant = control.StateSpace(A, B, C, np.zeros((1, 1)))\ntfplant = control.ss2tf(sysplant)\npprint('H(s) = {}'.format(tfplant))\n\nH = tfD*tfplant\n\ngm, pm, _, _ = control.margin(H)\nprint('Gain margin (dB): {}'.format(control.mag2db(gm)))\nprint('Phase margin: {}'.format(pm))\n\ncontrol.root_locus(H, Plot=True, PrintGain=False)\n#plt.axis([-10, 10, -10, 10])\nplt.show()\n```\n\n##### Similarities to 8.7\n* Compensators have similar form (3 zeros vs. 4 poles)\n\n##### Differences to 8.7\n* worse gain/phase margins\n* greater freedom of placing observer poles\n* qualitatively different pole/zero migration indicated by root locus plots\n\n### Problem 8.9\n#### a)\nSee Problem 4.4:\n\n\\begin{eqnarray}\nA_{aa} &=& \\begin{pmatrix}\n-0.746 & 0.387 & 0 \\\\\n0.024 & -0.0174 & 0 \\\\\n0 & 0 & 0 \\\\\n\\end{pmatrix},\nA_{au} = \\begin{pmatrix}\n-12.9 & 0 \\\\\n4.31 & 0 \\\\\n0 & 0 \\\\\n\\end{pmatrix}, \\\\\nA_{ua} &=& \\begin{pmatrix}\n0.006 & 0.001 & 0 \\\\\n-1 & 0 & 1 \\\\\n\\end{pmatrix},\nA_{uu} = \\begin{pmatrix}\n-0.746 & 0.0369 \\\\\n0 & 0 \\\\\n\\end{pmatrix},\\\\\nB_{a} &=& \\begin{pmatrix}\n6.05 & 0.952 \\\\\n-0.416 & -1.76 \\\\\n0 & 0 \\\\\n\\end{pmatrix},\\\\\nB_{u} &=& \\begin{pmatrix}\n0.0012 & 0.0092 \\\\\n0 & 0 \\\\\n\\end{pmatrix}\n\\end{eqnarray}\n\n#### b)\n\nAs I've said before, I am not doing any more block-diagrams.\n\n#### c)\n\nCondition 8.86 is $B_u - L C_a B_a = \\mathbf{0}$.  $B_u$ is $2 \\times 2$, while $C_a$ is $3 \\times 3$ and $B_a$ is $3 \\times 2$.  This means that $L$ must be $2 \\times 3$ just by size requirements.  Let:\n\\begin{eqnarray}\nL = \\begin{pmatrix}\nl_1 & l_2 & l_3 \\\\\nl_4 & l_5 & l_6\n\\end{pmatrix},\n\\end{eqnarray}\nand then see if is a way to satisfy Condition 8.86.\n\n\n```python\nBa = Matrix([[6.05, .952], [-.416, -1.76], [0, 0]])\nBu = Matrix([[.0012, .0092], [0, 0]])\nCa = eye(3)\nl = symbols(\"l1:7\")\nL = Matrix([[l[0], l[1], l[2]], [l[3], l[4], l[5]]])\npprint(L*Ba)\npprint(' = ')\npprint(Bu)\n```\n\n    \u23a16.05\u22c5l\u2081 - 0.416\u22c5l\u2082  0.952\u22c5l\u2081 - 1.76\u22c5l\u2082\u23a4\n    \u23a2                                      \u23a5\n    \u23a36.05\u22c5l\u2084 - 0.416\u22c5l\u2085  0.952\u22c5l\u2084 - 1.76\u22c5l\u2085\u23a6\n     = \n    \u23a10.0012  0.0092\u23a4\n    \u23a2              \u23a5\n    \u23a3  0       0   \u23a6\n\n\nThis is a linear system with $\\mathbf{x} = [l_1 \\ l_2 \\ l_4 \\ l_5]^T$.  \n\n\n```python\nAs = np.array([[6.05, -.416, 0, 0], [.952, 1.76, 0, 0], [0, 0, 6.05, -.416], [0, 0, 0.952, -1.76]]).astype('float').reshape((4, 4))\nbs = np.array([[.0012], [.0092], [0], [0]]).astype('float').reshape((4, 1))\nxs = np.linalg.solve(As, bs)\npprint('[[l1], [l2], [l4], [l5]]\\' = ')\npprint(xs)\n```\n\n    [[l1], [l2], [l4], [l5]]' = \n     [[ 0.00053777]\n      [ 0.00493639]\n      [ 0.        ]\n     [-0.        ]]\n\n\nThe gain matrix $L$ can be made to meet Condition 8.86 when:\n\\begin{eqnarray}\nL = \\begin{pmatrix}\n0.000538 & 0.00494 & l_3 \\\\\n0 & 0 & l_6 \\\\\n\\end{pmatrix}\n\\end{eqnarray}\n\nThe parameters $l_3$ and $l_6$ can be chosen freely to meet other observer design objectives; e.g. pole-placement.\n\nBut what about the suitability of the pole-placement?  The observer poles are determined by the characteristic polynomial of $F$.\n\n\n```python\nAuu = Matrix([[-0.746, 0.0369], [0, 0]])\nAau = Matrix([[-12.9, 0], [4.31, 0], [0, 0]])\nL = Matrix([[5.37777e-4, 4.93639e-3, l[2]], [0, 0, l[5]]])\nF = Auu - L*Aau\npprint(F)\n```\n\n    \u23a1-0.7603385176  0.0369\u23a4\n    \u23a2                     \u23a5\n    \u23a3      0          0   \u23a6\n\n\nClearly, $F$ has a pole at $s=0$, so the closed-loop dynamics will not be asymptotically stable.  Because of this one pole, every pole is not at a desirable location.\n\n#### d)\nWe have two free gains, $l_3$ and $l_6$.  The reduced-order observer will have two singular values, because it is order 2.  Therefore, we can place the remaining poles to cancel transmission zeros of the (unavailable) process.\n\n### Problem 8.10\n\n#### a)\nWe have a reduced order observer from Problem 7.5, and a control law from 6.9.  At this point, the methods of Problem 8.5 above can be used to find each compensator in terms of the gains $g_i$, $l_i$ for $i = 1, 2, 3 ,4$.  This would be kind of tedious, so I'm not going to do it.\n\n#### b)\nBlock-diagram omitted.\n\n### Problem 8.11\n_Omitted because of bogus exogenous method_\n\n### Problem 8.12\n#### a)\nGet $G$ from Problem 6.6.  The problem specifically calls out a fourth-order observer, so the reference $h_0$ and the airspeed $V$ are discarded in the subsequent treatment.\n\n\n```python\nA = np.array([[-1, 1, 0, 0], [-5, -.5, 0, 0], [0, 1, 0, 0], [-1, 0, 1, 0]]).astype('float').reshape((4, 4))\nB = np.array([[-.1], [-9], [0], [0]]).astype('float').reshape((4, 1))\nC = np.array([[0., 0., 0., 1.]]).astype('float').reshape((1, 4))\nD = np.zeros((1, 1))\nclosedLoopPoles = np.array(2.5*np.array([np.complex(-0.5, 0.5*np.sqrt(3.)), np.complex(-0.5, -0.5*np.sqrt(3.)),\n                                         np.complex(-0.5*np.sqrt(3.), 0.5), np.complex(-0.5*np.sqrt(3.), -0.5)]))\ndesiredObsPoles = np.array([np.complex(-2., np.sqrt(3)*2.), np.complex(-2., -np.sqrt(3)*2.),\n                      np.complex(-np.sqrt(3)*2., 2.), np.complex(-np.sqrt(3)*2., -2.)])\ntfComp = ch8_utils.fullOrderCompensator(A, B, C, D, closedLoopPoles, desiredObsPoles)\nprint('D(s) = {}'.format(tfComp))\nsysPlant = control.StateSpace(A, B, C, D)\ntfPlant = control.ss2tf(sysPlant)\nH = tfComp*tfPlant\n```\n\n    D(s) = \n       -339.8 s^3 - 725.8 s^2 - 2096 s - 1176\n    --------------------------------------------\n    s^4 + 16.26 s^3 + 127.8 s^2 + 633.2 s + 1786\n    \n\n\n#### b)\n\n\n```python\ncontrol.root_locus(H, Plot=True, PrintGain=False)\nplt.show()\nk = np.linspace(1, 2, 101)\nkStable = ch8_utils.stabilityRange(tfComp, tfPlant, k)\nif kStable is not None:\n    print('{min} <= k <= {max} defines the range of stable gains.'.format(min=kStable[0], max=kStable[1]))\nelse:\n    print('no stable gains were found in the range provided')\n```\n\n### Problem 8.13\n#### a)\nWe can reuse a lot from Problem 8.12.  However, the system needs to be rearranged so that $h$. which is measurable, is the first state.\n\n\n```python\nA = np.array([[0, -1, 0, 1], [0, -1, 1, 0], [0, -5, -.5, 0], [0, 0, 1, 0]]).astype('float').reshape((4, 4))\nB = np.array([[0], [-.1], [-9], [0]]).astype('float').reshape((4, 1))\nC = np.array([[1, 0, 0, 0]]).astype('float').reshape((1, 4))\nD = np.zeros((1, 1))\nsysPlant = control.StateSpace(A, B, C, D)\n\n### Controller ###\nclosedLoopPoles = np.array(2.5*np.array([np.complex(-0.5, 0.5*np.sqrt(3.)), np.complex(-0.5, -0.5*np.sqrt(3.)),\n                                         np.complex(-0.5*np.sqrt(3.), 0.5), np.complex(-0.5*np.sqrt(3.), -0.5)]))\nG = ch6_utils.bassGura(A, B, closedLoopPoles)\n\n### Observer ###\ndesiredObsPoles = np.array([np.complex(-4., 0.), np.complex(-2.*np.sqrt(2), 2.*np.sqrt(2)),\n                            np.complex(-2.*np.sqrt(2), -2.*np.sqrt(2))])\nAaa = np.array([A[0, 0]]).reshape((1, 1))\nAau = np.array(A[0, 1:]).reshape((1, 3))\nAua = np.array(A[1:, 0]).reshape((3, 1))\nAuu = np.array(A[1:, 1:]).reshape((3, 3))\nBa = np.array([0]).reshape((1, 1))\nBu = np.array(B[1:]).reshape((3, 1))\nCa = np.array([[1]])\nL, Gbb, H = ch7_utils.reducedOrderObserver(Aaa, Aau, Aua, Auu, Ba, Bu, Ca, desiredObsPoles)\nF = Auu - L@Aau\n\n### Compensator ###\nG1 = np.array([G[0, 0]]).reshape((1, 1))\nG2 = np.array(G[0, 1:]).reshape((1, 3))\nAr = F-H@G2\nBr = Ar@L + Gbb - H@G1\nCr = G2\nDr = G1+G2@L\nsysComp = control.StateSpace(Ar, Br, Cr, Dr)\ntfComp = control.ss2tf(sysComp)\nprint('D(s) = {}'.format(tfComp))\ntfPlant = control.ss2tf(sysPlant)\nH = tfComp*tfPlant\n```\n\n    D(s) = \n    -81.66 s^3 - 178.9 s^2 - 500.7 s - 294.1\n    ----------------------------------------\n        s^3 + 14.99 s^2 + 108.1 s + 373.2\n    \n     [-2.82842712+2.82842712j -2.82842712-2.82842712j -4.        +0.j \n     -1.25      +2.16506351j -1.25      -2.16506351j -2.16506351+1.25j\n                         -2.16506351-1.25j      ]                     \n\n\n#### b)\n\n\n```python\ncontrol.root_locus(H, Plot=True, PrintGain=False)\nplt.show()\n# T(s) = 1 + Kb*D(s)*H(s) (Kb != K from above!)\nk = np.linspace(1, 2.5, 101)\nkStable = ch8_utils.stabilityRange(tfComp, tfPlant, k)\nif kStable is not None:\n    print('{min} <= k <= {max} defines the range of stable gains.'.format(min=kStable[0], max=kStable[1]))\nelse:\n    print('no stable gains were found in the range provided')\n```\n\nThe margins for the compensator with reduced-order observer is significantly better.  The root locus indicates some nice pole-zero cancellation (dots are very near x's near the line $y=0$ above).  There is the same number of poles as zeros in the reduced order observer case.  This compensator is lower order with better closed-loop stability properties.  This is pretty cool, I think.\n", "meta": {"hexsha": "a363fdc3d1d5b2cd08e0a99594aa877cbfd2fac9", "size": 174644, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Ch8/FriedlandCh8.ipynb", "max_stars_repo_name": "jwdinius/friedland-csd-solutions", "max_stars_repo_head_hexsha": "2d7fec1b6055ea9777dc931bc1cf0f0df6c8ed7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-03-24T12:06:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-21T17:56:51.000Z", "max_issues_repo_path": "Ch8/FriedlandCh8.ipynb", "max_issues_repo_name": "jwdinius/friedland-csd-solutions", "max_issues_repo_head_hexsha": "2d7fec1b6055ea9777dc931bc1cf0f0df6c8ed7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-31T04:19:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T21:16:28.000Z", "max_forks_repo_path": "Ch8/FriedlandCh8.ipynb", "max_forks_repo_name": "jwdinius/friedland-csd-solutions", "max_forks_repo_head_hexsha": "2d7fec1b6055ea9777dc931bc1cf0f0df6c8ed7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-10-05T04:23:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T21:17:17.000Z", "avg_line_length": 132.5068285281, "max_line_length": 22732, "alphanum_fraction": 0.8473236985, "converted": true, "num_tokens": 9825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263216071250873, "lm_q2_score": 0.08035747322699913, "lm_q1q2_score": 0.034258127130645445}}
{"text": "```python\nfrom IPython.core.display import HTML, Image\ncss_file = 'style.css'\nHTML(open(css_file, 'r').read())\n```\n\n\n\n\n<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:100,300,400,500,700,800,900,100italic,300italic,400italic,500italic,700italic,800italic,900italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Arvo:400,700,400italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=PT+Mono' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Shadows+Into+Light' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Philosopher:400,700,400italic,700italic' rel='stylesheet' type='text/css'>\n\n<style>\n\n@font-face {\n    font-family: \"Computer Modern\";\n    src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');\n}\n\n#notebook_panel { /* main background */\n    background: #ddd;\n    color: #000000;\n}\n\n\n\n/* Formatting for header cells */\n.text_cell_render h1 {\n    font-family: 'Philosopher', sans-serif;\n    font-weight: 400;\n    font-size: 2.2em;\n    line-height: 100%;\n    color: rgb(0, 80, 120);\n    margin-bottom: 0.1em;\n    margin-top: 0.1em;\n    display: block;\n}\t\n.text_cell_render h2 {\n    font-family: 'Philosopher', serif;\n    font-weight: 400;\n    font-size: 1.9em;\n    line-height: 100%;\n    color: rgb(200,100,0);\n    margin-bottom: 0.1em;\n    margin-top: 0.1em;\n    display: block;\n}\t\n\n.text_cell_render h3 {\n    font-family: 'Philosopher', serif;\n    margin-top:12px;\n    margin-bottom: 3px;\n    font-style: italic;\n    color: rgb(94,127,192);\n}\n\n.text_cell_render h4 {\n    font-family: 'Philosopher', serif;\n}\n\n.text_cell_render h5 {\n    font-family: 'Alegreya Sans', sans-serif;\n    font-weight: 300;\n    font-size: 16pt;\n    color: grey;\n    font-style: italic;\n    margin-bottom: .1em;\n    margin-top: 0.1em;\n    display: block;\n}\n\n.text_cell_render h6 {\n    font-family: 'PT Mono', sans-serif;\n    font-weight: 300;\n    font-size: 10pt;\n    color: grey;\n    margin-bottom: 1px;\n    margin-top: 1px;\n}\n\n.CodeMirror{\n        font-family: \"PT Mono\";\n        font-size: 100%;\n}\n\n</style>\n\n\n\n\n\n\n```python\nfrom sympy import init_printing, symbols, eye, Matrix, Rational\nfrom warnings import filterwarnings\n```\n\n\n```python\ninit_printing(use_latex = 'mathjax')\nfilterwarnings('ignore')\n```\n\n# Equations for the inverse of a matrix\n\n# Cramer's rule\n\n# The volume of a box\n\n## Deriving an equation for the inverse of a matrix\n\n* The equation for the inverse of a matrix\n$$ {A}^{-1}=\\frac{1}{\\left| A \\right|}{C}^{T} $$\n* With arithmetic alteration we have the following\n$$ \\therefore {A}{C}^{T}=\\left|A\\right|I $$\n* Writing out the left-hand side we have\n$$ \\begin{bmatrix} {a}_{11} & {a}_{12} & \\dots & {a}_{1n} \\\\ {a}_{21} & {a}_{22} & \\dots & {a}_{2n} \\\\  \\vdots & \\vdots & \\dots & \\vdots \\\\ {a}_{n1} & {a}_{n2} & \\dots & {a}_{nn} \\end{bmatrix} \\begin{bmatrix} { C }_{ 11 } & { C }_{ 21 } & \\dots  & { C }_{ n1 } \\\\ { C }_{ 12 } & { C }_{ 22 } & \\dots  & { C }_{ n2 } \\\\ \\vdots  & \\vdots  & \\dots  & \\vdots  \\\\ { C }_{ 1n } & { C }_{ 2n } & \\dots  & { C }_{ nn } \\end{bmatrix} $$\n\n* From the previous lecture we had the equation for the determinant (using cofactors), which correlates with the above (looking at row 1 times column 1 (*i*=1)\n$$ \\left|A\\right|={a}_{i1}{C}_{i1} + {a}_{i2}{C}_{i2} \\dots {a}_{in}{C}_{in}$$\n* Alas we have to get |A| only on the main diagonal for the right-hand side above\n* It follows, though that i.e. for position row 1, column 2 we do get a zero\n* Look at the 2&#215;2 matrix\n$$ { \\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix} }^{ -1 }=\\frac { 1 }{ \\left| A \\right|  } { C }^{ T }\\\\ { \\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix} }^{ -1 }=\\frac { 1 }{ \\left| A \\right|  } { \\begin{bmatrix} d & -c \\\\ -b & a \\end{bmatrix} }^{ T }\\\\ { \\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix} }^{ -1 }=\\frac { 1 }{ \\left| A \\right|  } { \\begin{bmatrix} d & -b \\\\ -c & a \\end{bmatrix} } $$\n* So for AC<sup>T</sup> we would have the following (note, though what happens if we try and get row 1, column 2\n$$ \\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}{ \\begin{bmatrix} d & -b \\\\ -c & a \\end{bmatrix} }=\\begin{bmatrix} ad-bc & -ab+ab \\\\ cd-cd & ad-bc \\end{bmatrix}=\\begin{bmatrix} ad-bc & 0 \\\\ 0 & ad-bc \\end{bmatrix}=\\begin{bmatrix} \\left| A \\right|  & 0 \\\\ 0 & \\left| A \\right|  \\end{bmatrix}=\\left| A \\right| \\begin{bmatrix} 1 & 0 \\\\ 0 & 1 \\end{bmatrix} $$\n* ... and that's so cool!\n\n## Cramer's rule\n\n* From A**x**=**b** we have **x**=A<sup>-1</sup>**b**, which gives us the following\n$$ \\underline { x } =\\frac { 1 }{ \\left| A \\right|  } { C }^{ T }\\underline { b } $$\n$$ \\therefore \\begin{bmatrix} { x }_{ 1 } \\\\ { x }_{ 2 } \\\\ \\vdots  \\\\ { x }_{ n } \\end{bmatrix}=\\frac { 1 }{ \\left| A \\right|  } \\begin{bmatrix} { C }_{ 11 } & { C }_{ 21 } & \\dots  & { C }_{ n1 } \\\\ { C }_{ 12 } & { C }_{ 22 } & \\dots  & { C }_{ n2 } \\\\ \\vdots  & \\vdots  & \\dots  & \\vdots  \\\\ { C }_{ 1n } & { C }_{ 2n } & \\dots  & { C }_{ nn } \\end{bmatrix}\\begin{bmatrix} { b }_{ 1 } \\\\ { b }_{ 2 } \\\\ \\vdots  \\\\ { b }_{ n } \\end{bmatrix} $$\n\n* This is difficult to see, but we successively replace each column in A with the column vector **b**, whic creates a bunch of new matrices B<sub>j</sub>, such that the following applies\n$$  \\begin{bmatrix} { x }_{ 1 } \\\\ { x }_{ 2 } \\\\ \\vdots  \\\\ { x }_{ n } \\end{bmatrix}=\\begin{bmatrix} \\frac { \\left| { B }_{ 1 } \\right|  }{ \\left| A \\right|  }  \\\\ \\frac { \\left| { B }_{ 2 } \\right|  }{ \\left| A \\right|  }  \\\\ \\vdots  \\\\ \\frac { \\left| { B }_{ n } \\right|  }{ \\left| A \\right|  }  \\end{bmatrix} $$\n\n## The volume of a box (parallelepiped )\n\n* Consider a box in three dimensions (each side is a parallelogram)\n* Make one corner coincide with origin\n* The vector coordinate of the three sides that emanate from this corner become the rows of a square matrix, 3&#215;3 in this case\n* The volume is then the determinant of this matrix\n\n### Consider a square box of sides of unit length one\n\n\n```python\nA = eye(3)\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}1 & 0 & 0\\\\0 & 1 & 0\\\\0 & 0 & 1\\end{matrix}\\right]$$\n\n\n\n\n```python\nA.det()\n```\n\n\n\n\n$$1$$\n\n\n\n* This proves the first property of determinants\n\n### What about the orthogonal matrix\n\n* Here we have the three edges being orthonormal\n* We know that Q<sup>T</sup>Q = I\n\n$$ \\left| { Q }^{ T }Q \\right| =\\left| I \\right| \\\\ \\left| { Q }^{ T } \\right| \\left| Q \\right| =\\left| I \\right| \\\\ \\because \\quad \\left| { Q }^{ T } \\right| =\\left| Q \\right| \\\\ \\therefore \\quad \\left| Q \\right| \\left| Q \\right| =\\left| I \\right| \\\\ { \\left| Q \\right|  }^{ 2 }=\\left| I \\right| =1\\\\ \\therefore \\quad \\left| Q \\right| =\\pm 1 $$\n\n### A rectangular box (edges square)\n\n* Doubling an edge doubles the volume\n* This is akin to a single row multiplied by a scalar\n* Thus determinant will increase by this scalar (multiplication)\n\n### Area of  parallelogram and a triangle\n\n* The area of a parallelogram is just the determinant of a 2&#215;2 matrix with the rows being row vectors of two sides from the origin\n* The area of a triangle is simply half of this\n\n* For the triangle that is not at the origin, with three angles at (*x*<sub>1</sub>, *y*<sub>1</sub>), (*x*<sub>2</sub>, *y*<sub>2</sub>) and (*x*<sub>3</sub>, *y*<sub>3</sub>), we simply subtract values along the axes from each other\n* That is akin to getting the determinant of this matrix\n$$ \\begin{vmatrix} { x }_{ 1 } & { y }_{ 1 } & 1 \\\\ { x }_{ 2 } & { y }_{ 2 } & 1 \\\\ { x }_{ 3 } & { y }_{ 3 } & 1 \\end{vmatrix} $$\n* Simple row reduction is equivalent to moving the triangle by the subtraction above\n$$ \\begin{vmatrix} { x }_{ 1 } & { y }_{ 1 } & 1 \\\\ { x }_{ 2 }-{ x }_{ 1 } & { y }_{ 2 }-{ y }_{ 1 } & 0 \\\\ { x }_{ 3 }-{ x }_{ 1 } & { y }_{ 3 }-{ y }_{ 1 } & 0 \\end{vmatrix} $$\n\n## Example problems\n\n### Example problem 1\n\n* Calculate the volume of the tetrahedron with vertices being the following vectors\n    * **a**<sub>1</sub>=(2,2,-1), **a**<sub>2</sub>=(1,3,0), **a**<sub>3</sub>=(-1,1,4)\n* Also calculate the volume if **a**<sub>3</sub>=(-201,-199,104)\n\n#### Solution\n\n\n```python\nA = Matrix([[2, 2, -1], [1, 3, 0], [-1, 1, 4]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}2 & 2 & -1\\\\1 & 3 & 0\\\\-1 & 1 & 4\\end{matrix}\\right]$$\n\n\n\n* The volume of a tetrahedron is a third times the area of the (any) base and the height from the (chosen) base\n* The volume of a parallelepiped is the area of the base times the height\n* If we keep the base of the two the same and the apex the same, we note that the base is twice the area of the triangle that forms the base of the tetrahedron\n* We thus have that the volume of the tetrahedron is a 6<sup>th</sup> of the volume of the parallelepiped\n\n\n```python\nA.det()\n```\n\n\n\n\n$$12$$\n\n\n\n\n```python\nRational(1, 6) * A.det()\n```\n\n\n\n\n$$2$$\n\n\n\n\n```python\nA_new = Matrix([[2, 2, -1], [1, 3, 0], [-201, -199, 104]])\nA_new\n```\n\n\n\n\n$$\\left[\\begin{matrix}2 & 2 & -1\\\\1 & 3 & 0\\\\-201 & -199 & 104\\end{matrix}\\right]$$\n\n\n\n\n```python\nRational(1, 6) * A_new.det()\n```\n\n\n\n\n$$2$$\n\n\n\n* By the second part of the third property of determinants we know, though, that a constant multiple of a row subtracted from another (one of the elementary row operations) does not change the determinant\n* In this case we subtracted 100 times row 1 from row 3\n\n* In effect, the height is not changing; the apex is moving away parallel to **a**<sub>1</sub>\n\n\n```python\n\n```\n", "meta": {"hexsha": "54f7f2428146acd6b31ed6815ef1b986dea0f72c", "size": 16911, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_20_Equations_for_the_inverse_Cramer_rule_Volume_of_a_box.ipynb", "max_stars_repo_name": "okara83/Becoming-a-Data-Scientist", "max_stars_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_20_Equations_for_the_inverse_Cramer_rule_Volume_of_a_box.ipynb", "max_issues_repo_name": "okara83/Becoming-a-Data-Scientist", "max_issues_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_20_Equations_for_the_inverse_Cramer_rule_Volume_of_a_box.ipynb", "max_forks_repo_name": "okara83/Becoming-a-Data-Scientist", "max_forks_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-09T15:41:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T07:47:40.000Z", "avg_line_length": 29.6164623468, "max_line_length": 489, "alphanum_fraction": 0.4808113063, "converted": true, "num_tokens": 3291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567937024021, "lm_q2_score": 0.12252321091611636, "lm_q1q2_score": 0.03409291582364169}}
{"text": "```python\n%matplotlib inline\n```\n\n\n.. currentmodule:: dgl\n\nGraph Classification Tutorial\n=============================\n\n**Author**: `Mufei Li <https://github.com/mufeili>`_,\n`Minjie Wang <https://jermainewang.github.io/>`_,\n`Zheng Zhang <https://shanghai.nyu.edu/academics/faculty/directory/zheng-zhang>`_.\n\nIn this tutorial, you learn how to use DGL to batch multiple graphs of variable size and shape. The \ntutorial also demonstrates training a graph neural network for a simple graph classification task.\n\nGraph classification is an important problem\nwith applications across many fields, such as bioinformatics, chemoinformatics, social\nnetwork analysis, urban computing, and cybersecurity. Applying graph neural\nnetworks to this problem has been a popular approach recently. This can be seen in the following reserach references: \n`Ying et al., 2018 <https://arxiv.org/abs/1806.08804>`_,\n`Cangea et al., 2018 <https://arxiv.org/abs/1811.01287>`_,\n`Knyazev et al., 2018 <https://arxiv.org/abs/1811.09595>`_,\n`Bianchi et al., 2019 <https://arxiv.org/abs/1901.01343>`_,\n`Liao et al., 2019 <https://arxiv.org/abs/1901.01484>`_,\n`Gao et al., 2019 <https://openreview.net/forum?id=HJePRoAct7>`_).\n\n\nSimple graph classification task\n--------------------------------\nIn this tutorial, you learn how to perform batched graph classification\nwith DGL. The example task objective is to classify eight types of topologies shown here.\n\n\n\n    :align: center\n\nImplement a synthetic dataset :class:`data.MiniGCDataset` in DGL. The dataset has eight \ndifferent types of graphs and each class has the same number of graph samples.\n\n\n\n\n```python\nfrom dgl.data import MiniGCDataset\nimport matplotlib.pyplot as plt\nimport networkx as nx\n# A dataset with 80 samples, each graph is\n# of size [10, 20]\ndataset = MiniGCDataset(80, 10, 20)\ngraph, label = dataset[0]\nfig, ax = plt.subplots()\nnx.draw(graph.to_networkx(), ax=ax)\nax.set_title('Class: {:d}'.format(label))\nplt.show()\n```\n\nForm a graph mini-batch\n-----------------------\nTo train neural networks efficiently, a common practice is to batch\nmultiple samples together to form a mini-batch. Batching fixed-shaped tensor\ninputs is common. For example, batching two images of size 28 x 28\ngives a tensor of shape 2 x 28 x 28. By contrast, batching graph inputs\nhas two challenges:\n\n* Graphs are sparse.\n* Graphs can have various length. For example, number of nodes and edges.\n\nTo address this, DGL provides a :func:`dgl.batch` API. It leverages the idea that\na batch of graphs can be viewed as a large graph that has many disjointed \nconnected components. Below is a visualization that gives the general idea.\n\n\n\n    :width: 400pt\n    :align: center\n\nDefine the following ``collate`` function to form a mini-batch from a given\nlist of graph and label pairs.\n\n\n\n\n```python\nimport dgl\nimport torch\n\ndef collate(samples):\n    # The input `samples` is a list of pairs\n    #  (graph, label).\n    graphs, labels = map(list, zip(*samples))\n    batched_graph = dgl.batch(graphs)\n    return batched_graph, torch.tensor(labels)\n```\n\nThe return type of :func:`dgl.batch` is still a graph. In the same way, \na batch of tensors is still a tensor. This means that any code that works\nfor one graph immediately works for a batch of graphs. More importantly,\nbecause DGL processes messages on all nodes and edges in parallel, this greatly\nimproves efficiency.\n\nGraph classifier\n----------------\nGraph classification proceeds as follows.\n\n\n\n\nFrom a batch of graphs, perform message passing and graph convolution\nfor nodes to communicate with others. After message passing, compute a\ntensor for graph representation from node (and edge) attributes. This step might \nbe called readout or aggregation. Finally, the graph \nrepresentations are fed into a classifier $g$ to predict the graph labels.\n\nGraph convolution layer can be found in the ``dgl.nn.<backend>`` submodule.\n\n\n\n\n```python\nfrom dgl.nn.pytorch import GraphConv\n```\n\nReadout and classification\n--------------------------\nFor this demonstration, consider initial node features to be their degrees.\nAfter two rounds of graph convolution, perform a graph readout by averaging\nover all node features for each graph in the batch.\n\n\\begin{align}h_g=\\frac{1}{|\\mathcal{V}|}\\sum_{v\\in\\mathcal{V}}h_{v}\\end{align}\n\nIn DGL, :func:`dgl.mean_nodes` handles this task for a batch of\ngraphs with variable size. You then feed the graph representations into a\nclassifier with one linear layer to obtain pre-softmax logits.\n\n\n\n\n```python\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass Classifier(nn.Module):\n    def __init__(self, in_dim, hidden_dim, n_classes):\n        super(Classifier, self).__init__()\n        self.conv1 = GraphConv(in_dim, hidden_dim)\n        self.conv2 = GraphConv(hidden_dim, hidden_dim)\n        self.classify = nn.Linear(hidden_dim, n_classes)\n\n    def forward(self, g):\n        # Use node degree as the initial node feature. For undirected graphs, the in-degree\n        # is the same as the out_degree.\n        h = g.in_degrees().view(-1, 1).float()\n        # Perform graph convolution and activation function.\n        h = F.relu(self.conv1(g, h))\n        h = F.relu(self.conv2(g, h))\n        g.ndata['h'] = h\n        # Calculate graph representation by averaging all the node representations.\n        hg = dgl.mean_nodes(g, 'h')\n        return self.classify(hg)\n```\n\nSetup and training\n------------------\nCreate a synthetic dataset of $400$ graphs with $10$ ~\n$20$ nodes. $320$ graphs constitute a training set and\n$80$ graphs constitute a test set.\n\n\n\n\n```python\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\n\n# Create training and test sets.\ntrainset = MiniGCDataset(320, 10, 20)\ntestset = MiniGCDataset(80, 10, 20)\n# Use PyTorch's DataLoader and the collate function\n# defined before.\ndata_loader = DataLoader(trainset, batch_size=32, shuffle=True,\n                         collate_fn=collate)\n\n# Create model\nmodel = Classifier(1, 256, trainset.num_classes)\nloss_func = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.001)\nmodel.train()\n\nepoch_losses = []\nfor epoch in range(80):\n    epoch_loss = 0\n    for iter, (bg, label) in enumerate(data_loader):\n        prediction = model(bg)\n        loss = loss_func(prediction, label)\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n        epoch_loss += loss.detach().item()\n    epoch_loss /= (iter + 1)\n    print('Epoch {}, loss {:.4f}'.format(epoch, epoch_loss))\n    epoch_losses.append(epoch_loss)\n```\n\nThe learning curve of a run is presented below.\n\n\n\n\n```python\nplt.title('cross entropy averaged over minibatches')\nplt.plot(epoch_losses)\nplt.show()\n```\n\nThe trained model is evaluated on the test set created. To deploy\nthe tutorial, restrict the running time to get a higher\naccuracy ($80$ % ~ $90$ %) than the ones printed below.\n\n\n\n\n```python\nmodel.eval()\n# Convert a list of tuples to two lists\ntest_X, test_Y = map(list, zip(*testset))\ntest_bg = dgl.batch(test_X)\ntest_Y = torch.tensor(test_Y).float().view(-1, 1)\nprobs_Y = torch.softmax(model(test_bg), 1)\nsampled_Y = torch.multinomial(probs_Y, 1)\nargmax_Y = torch.max(probs_Y, 1)[1].view(-1, 1)\nprint('Accuracy of sampled predictions on the test set: {:.4f}%'.format(\n    (test_Y == sampled_Y.float()).sum().item() / len(test_Y) * 100))\nprint('Accuracy of argmax predictions on the test set: {:4f}%'.format(\n    (test_Y == argmax_Y.float()).sum().item() / len(test_Y) * 100))\n```\n\nThe animation here plots the probability that a trained model predicts the correct graph type.\n\n\n\n\nTo understand the node and graph representations that a trained model learned,\nwe use `t-SNE, <https://lvdmaaten.github.io/tsne/>`_ for dimensionality reduction\nand visualization.\n\n\n\n    :align: center\n\n\n\n    :align: center\n\nThe two small figures on the top separately visualize node representations after one and two\nlayers of graph convolution. The figure on the bottom visualizes\nthe pre-softmax logits for graphs as graph representations.\n\nWhile the visualization does suggest some clustering effects of the node features,\nyou would not expect a perfect result. Node degrees are deterministic for\nthese node features. The graph features are improved when separated.\n\nWhat's next?\n------------\nGraph classification with graph neural networks is still a new field.\nIt's waiting for people to bring more exciting discoveries. The work requires \nmapping different graphs to different embeddings, while preserving\ntheir structural similarity in the embedding space. To learn more about it, see \n`How Powerful Are Graph Neural Networks? <https://arxiv.org/abs/1810.00826>`_ a research paper  \npublished for the International Conference on Learning Representations 2019.\n\nFor more examples about batched graph processing, see the following:\n\n* Tutorials for `Tree LSTM <https://docs.dgl.ai/tutorials/models/2_small_graph/3_tree-lstm.html>`_ and `Deep Generative Models of Graphs <https://docs.dgl.ai/tutorials/models/3_generative_model/5_dgmg.html>`_\n* An example implementation of `Junction Tree VAE <https://github.com/dmlc/dgl/tree/master/examples/pytorch/jtnn>`_\n\n\n", "meta": {"hexsha": "6266297de22b13028479809010383ae600a75c26", "size": 12444, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "DGL/get started/4_batch.ipynb", "max_stars_repo_name": "AiRanthem/GNN", "max_stars_repo_head_hexsha": "f10b2f85d50efce1bd069517d07f33d84f25d099", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DGL/get started/4_batch.ipynb", "max_issues_repo_name": "AiRanthem/GNN", "max_issues_repo_head_hexsha": "f10b2f85d50efce1bd069517d07f33d84f25d099", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DGL/get started/4_batch.ipynb", "max_forks_repo_name": "AiRanthem/GNN", "max_forks_repo_head_hexsha": "f10b2f85d50efce1bd069517d07f33d84f25d099", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 70.7045454545, "max_line_length": 1876, "alphanum_fraction": 0.6522822244, "converted": true, "num_tokens": 2239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702253925955866, "lm_q2_score": 0.09138210121127464, "lm_q1q2_score": 0.03383197429715379}}
{"text": "Run the below cell to import all relevant notebooks.\n\n\n```python\nimport io, os, sys, types\nfrom IPython import get_ipython\nfrom nbformat import read\nfrom IPython.core.interactiveshell import InteractiveShell\n\ndef find_notebook(fullname, path=None):\n    \"\"\"find a notebook, given its fully qualified name and an optional path\n\n    This turns \"foo.bar\" into \"foo/bar.ipynb\"\n    and tries turning \"Foo_Bar\" into \"Foo Bar\" if Foo_Bar\n    does not exist.\n    \"\"\"\n    name = fullname.rsplit('.', 1)[-1]\n    if not path:\n        path = ['']\n    for d in path:\n        nb_path = os.path.join(d, name + \".ipynb\")\n        #print('searching: %s'%nb_path)\n        if os.path.isfile(nb_path):\n            return nb_path\n        # let import Notebook_Name find \"Notebook Name.ipynb\"\n        nb_path = nb_path.replace(\"_\", \" \")\n        #print('searching: %s' % nb_path)\n        if os.path.isfile(nb_path):\n            return nb_path\n\nclass NotebookLoader(object):\n    \"\"\"Module Loader for Jupyter Notebooks\"\"\"\n    def __init__(self, path=None):\n        self.shell = InteractiveShell.instance()\n        self.path = path\n\n    def load_module(self, fullname):\n        \"\"\"import a notebook as a module\"\"\"\n        path = find_notebook(fullname, self.path)\n\n        print (\"importing Jupyter notebook from %s\" % path)\n\n        # load the notebook object\n        with io.open(path, 'r', encoding='utf-8') as f:\n            nb = read(f, 4)\n\n\n        # create the module and add it to sys.modules\n        # if name in sys.modules:\n        #    return sys.modules[name]\n        mod = types.ModuleType(fullname)\n        mod.__file__ = path\n        mod.__loader__ = self\n        mod.__dict__['get_ipython'] = get_ipython\n        sys.modules[fullname] = mod\n\n        # extra work to ensure that magics that would affect the user_ns\n        # actually affect the notebook module's ns\n        save_user_ns = self.shell.user_ns\n        self.shell.user_ns = mod.__dict__\n\n        #print('Found %d cells'%len(nb.cells))\n        try:\n          for cell in nb.cells:\n            if cell.cell_type == 'code':\n                # transform the input to executable Python\n                code = self.shell.input_transformer_manager.transform_cell(cell.source)\n                # run the code in themodule\n                exec(code, mod.__dict__)\n        finally:\n            self.shell.user_ns = save_user_ns\n        return mod\n\nclass NotebookFinder(object):\n    \"\"\"Module finder that locates Jupyter Notebooks\"\"\"\n    def __init__(self):\n        self.loaders = {}\n\n    def find_module(self, fullname, path=None):\n        nb_path = find_notebook(fullname, path)\n        if not nb_path:\n            return\n\n        key = path\n        if path:\n            # lists aren't hashable\n            key = os.path.sep.join(path)\n\n        if key not in self.loaders:\n            self.loaders[key] = NotebookLoader(path)\n        return self.loaders[key]\n\n\n#  register the NotebookFinder with sys.meta_path\nprint('running importer')\nsys.meta_path.append(NotebookFinder())\n```\n\n    running importer\n\n\n\n```python\n!pip install -U gif\n```\n\n    Requirement already up-to-date: gif in /home/avani/anaconda3/lib/python3.8/site-packages (3.0.0)\r\n    Requirement already satisfied, skipping upgrade: Pillow>=7.1.2 in /home/avani/anaconda3/lib/python3.8/site-packages (from gif) (7.2.0)\r\n\n\n\n```python\n# Import all relevant functions\nfrom sklearn import datasets\nfrom sklearn.datasets import make_classification\nfrom sklearn.model_selection import train_test_split\n\nfrom utils import plot_decision_boundary, multi_class_signum, get_accuracy, get_prediction\nfrom utils import plot_2D_input_datapoints, generate_gifs, normalize, signum\n\nimport matplotlib.pyplot as plt\nimport random\nimport numpy as np\nimport seaborn as sns; sns.set();\nimport pandas as pd\nimport math\nimport gif\nimport warnings\nwarnings.filterwarnings('ignore')\n```\n\n# Introduction to Perceptron Algorithm\n\nThe Perceptron Algorithm is a supervised learning algorithm of binary classifiers. A binary classifier is a function that decides whether an input data vector belongs to a specific class. In our case, we define our output class $\\mathbf{y} = \\{-1, +1\\}$, where $+1$ denotes positive class and $-1$ denotes negative class.\n\nPerceptron algorithm makes a fundamental assumption i.e., all datapoints are linearly separable.\n\nIn our perceptron algorithm problem, our goal is to classify a set of points into two classes in n-dimensional space. This classification is done by a hyperplane defined by a hypothesis function, $h_{\\mathbf{w}}$ as follows:\n\n\\begin{equation}\n\\mathbf{X}: \\mathbf{w^{\\top}X + b} = 0\n\\end{equation}\n\nwhere,\n*   $\\mathbf{m}  $ Number of examples/datapoints.\n*   $\\mathbf{d}  $ Number of features/dimensions.\n*   $\\mathbf{n}  $ Number of output categories.\n*   $\\mathbf{X} \\in \\mathbf{R^{m \\times d}}$\n*   $\\mathbf{w} \\in \\mathbf{R^{d \\times n}}$, Weights of the hyperplane\n*   $\\mathbf{b} \\in \\mathbf{R^n} $, Bias of the hyperplane\n\nInstead of finding both $\\mathbf{w}$ and $\\mathbf{b}$, we make the following modifications to the above equation:\n\n\\begin{equation}\n\\mathbf{x_i} \\rightarrow\n\\begin{bmatrix}\n\\mathbf{x_i} \\\\ 1\n\\end{bmatrix},\n\\mathbf{w} \\rightarrow\n\\begin{bmatrix}\n\\mathbf{w} \\\\ \\mathbf{b}\n\\end{bmatrix}\n\\end{equation}\n\nWhen we generalize this modification for $\\mathbf{X}$, our hyperplane necessarily goes through origin, which simplifies our hypothesis function as follows:\n\n\\begin{equation}\nh_{\\mathbf{w}} = \\mathbf{w^{\\top} X}\n\\end{equation}\n\nDepending on the sign of this hypothesis function, it can predict three situations,\n\n\\begin{equation}\nsign(h_{\\mathbf{w}}) = sign(\\mathbf{w^{\\top} X}) = \\left\\{\n  \\begin{array}{ll}\n    \\text{1 if } \\; \\mathbf{w^{\\top} X} \\text{ > 0}\\\\\n    \\text{-1 if } \\; \\mathbf{w^{\\top} X} \\text{ <= 0}\n  \\end{array}\n  \\right.\n\\end{equation}\n\nIn our binary classification problem, the hypothesis function, $h_{\\mathbf{w}}$, classifies a particular datapoint $(x_i, y_i)$ correctly if,\n\n\\begin{equation}\nsign(\\mathbf{w^{\\top}x_i}) = \\mathbf{y_i} \\equiv \\mathbf{y_i \\cdot w^{\\top} x_i > 0}\n\\end{equation}\n\nOn the other hand, $h_{\\mathbf{w}}$ incorrectly classifies a datapoint $(x_i, y_i)$ if,\n\n\\begin{equation}\nsign(\\mathbf{w^{\\top}x_i}) \\neq \\mathbf{y_i} \\equiv \\mathbf{y_i \\cdot w^{\\top} x_i \\leq 0}\n\\end{equation}\n\n$\\;$\n\n\n\n$\\;$\n\nThe quantity, $\\mathbf{y \\cdot w^{\\top} X}$, is the margin or the distance between the datapoints in $\\mathbf{X}$ and the hyperplane.\n\nConsider our desired behavior: we would like to have $\\mathbf{y \\cdot w^{\\top} X > 0}$ for all training examples, and penalize those $\\mathbf{w}$ where $\\mathbf{y \\cdot w^{\\top} X \\leq 0}$.\n\nIntuitively, we would like to have our loss function defined only for misclassified training datapoints. For the correctly classified ones, we define zero loss.\n\nHence, our loss function is as follows:\n\n\\begin{equation}\nJ = \\sum_{x_i \\in \\varepsilon} - \\mathbf{y_i \\cdot w^{\\top} x_i}\n\\end{equation}\n\nwhere $\\varepsilon$ is the set of misclassified samples i.e.,\n\n\\begin{equation}\n\\varepsilon = \\{\\mathbf{x_i | w^{\\top} x_i < 0 }\\}\n\\end{equation}\n\nThis loss is differentiable. For a batch of samples, we can now write our gradient descent update rule as follows:\n\n\\begin{equation}\n\\mathbf{w^{k+1} \\leftarrow w^k} + \\eta \\sum_{x_i \\in \\varepsilon} \\mathbf{y_i x_i}\n\\end{equation}\n\nNow that we have seen an introduction on how the Perceptron model works, we will dive into the code implementations. Also, we will answer some open-ended questions such as:\n\n1.   Effect of weight initialization\n2.   Do we need biases?\n3.   What happens if we have non-linearly separable dataset, like XOR problem?\n4.   Training perceptron model on a partially separable dataset\n\n# Example 1 - Toy dataset\n\n\n```python\n# Setting the seed to ensure reproducibility of experiments\nnp.random.seed(10)\n\n# Getting only linearly separable dataset\nseparable = False\nwhile not separable:\n  samples = make_classification(n_samples=1000, n_features=2, n_redundant=0, n_informative=1, n_clusters_per_class=1, flip_y=-1)\n  red = samples[0][samples[1] == 0]\n  blue = samples[0][samples[1] == 1]\n  separable = any([red[:, k].max() < blue[:, k].min() or red[:, k].min() > blue[:, k].max() for k in range(2)])\n\nX, y = samples\n\n# Adding column of ones to absorb bias b of the hyperplane into X\nbias_ones = np.ones((len(X), 1))\nX = np.hstack((X, bias_ones))\n\n# Setting y from {0,1} to {-1, 1}\ny[y == 0] = -1\ny = y.reshape(-1, 1)\n```\n\n\n```python\nplot_2D_input_datapoints(X[:, :2], y)\n```\n\n\n```python\ny.shape\n```\n\n\n\n\n    (1000, 1)\n\n\n\n\n```python\n# Train-Val-Test split\nX_train_val, X_test, Y_train_val, Y_test = train_test_split(X, y, shuffle=True, test_size = 0.2)\nX_train, X_val, Y_train, Y_val = train_test_split(X_train_val, Y_train_val, test_size = 0.125)\n\nprint(\"Training dataset: \", X_train.shape)\nprint(\"Validation dataset: \", X_val.shape)\nprint(\"Test dataset: \", X_test.shape)\n```\n\n    Training dataset:  (700, 3)\n    Validation dataset:  (100, 3)\n    Test dataset:  (200, 3)\n\n\n\n```python\n# Normalizing X_train and absorbing weight b of the hyperplane\nX_normalized_train = normalize(X_train[:, :2])\n\nb_ones = np.ones((len(X_normalized_train), 1))\nX_normalized_train = np.hstack((X_normalized_train, b_ones))\n```\n\nNote above that 1st and 2nd column are input data features and the 3rd column effectively translates to the bias column. Adding column of ones to the input data helps in easier matrix multiplication between the input data $X$ and weights $w$.\n\nThe pseudo-code for our perceptron algorithm is as follows:\n\n\n\n\n```python\n# Perceptron training algorithm\ndef train(X_train, Y_train, weights, learning_rate=1, total_epochs=100):\n\n  \"\"\"Training method for Perceptron.\n  \n  Parameters\n  -----------\n\n  X_train: ndarray (num_examples(rows) vs num_features(columns))\n    Input dataset which perceptron will use to learn optimal weights\n  \n  Y_train: ndarray (num_examples(rows) vs class_labels(columns))\n    Class labels for input data\n\n  weights: ndarray (num_features vs n_output)\n    Weights used to train the network and predict on test set\n\n  learning_rate: int\n    Learning rate use to learn and update weights\n  \n  total_epochs: int\n    Max number of epochs to train the perceptron model\n  \"\"\"\n\n  n_samples, _ = np.shape(X_train)\n  history_weights = []\n  epoch = 1\n\n  # Number of missclassified points we would like to see in the train set.\n  # While training, its value will change every epoch. If m==0, our training \n  # error will be zero.\n  m = 1\n\n  # If the most recent weights gave 0 misclassifications, break the loop.\n  # Else continue until total_epochs is completed.\n  while m != 0 and epoch <= total_epochs:\n    m = 0\n\n    # Compute weighted inputs and predict class labels on training set.\n    weights_transpose_x = np.dot(X_train, weights)\n    weights_transpose_x = signum(weights_transpose_x)\n    y_train_out = np.multiply(Y_train, weights_transpose_x)\n    epoch += 1\n    \n    # Collecting misclassified indexes and count them\n    y_miscls_idxs = np.argwhere(y_train_out <= 0)[:, 0]\n    y_miscls_idxs = np.unique(y_miscls_idxs)\n    m = len(y_miscls_idxs)\n\n    # Calculate gradients and update weights\n    dweights = np.dot((X_train[y_miscls_idxs]).T, Y_train[y_miscls_idxs])\n    weights += (learning_rate/n_samples) * dweights\n    weights = np.round(weights, decimals=4)\n\n    # Append weights to visualize decision boundary later\n    history_weights.append(weights)\n\n  if m == 0 and epoch <= total_epochs:\n    print(\"Training has stabilized with all points classified: \", epoch)\n  else:\n    print(f'Training completed at {epoch-1} epochs. {m} misclassified points remain.')\n\n  return history_weights\n```\n\n\n```python\n# Initializing weights to zero\n_, n_features = np.shape(X_normalized_train)\n_, n_outputs = np.shape(Y_train)\nprint(n_outputs)\nweights = np.zeros((n_features, n_outputs))\n```\n\n    1\n\n\n\n```python\nprint(X_normalized_train.shape,Y_train.shape,weights.shape)\n```\n\n    (700, 3) (700, 1) (3, 1)\n\n\n\n```python\ntrained_weights = train(X_normalized_train, Y_train, weights, learning_rate=0.05, total_epochs=50)\n```\n\n    Training completed at 50 epochs. 2 misclassified points remain.\n\n\nVisualizing decision boundary for training set\n\n\n\n```python\ngenerate_gifs(X_train, Y_train, trained_weights, 'train', path='content/training_decision_boundary.gif')\n```\n\n    Gif/image generated\n\n\n\n\n\n```python\nbest_weights = trained_weights[-1]\ntrain_acc, _ = get_prediction(X_train, Y_train, best_weights, get_acc=True)\nval_acc, _ = get_prediction(X_val, Y_val, best_weights, get_acc=True)\ntest_acc, _ = get_prediction(X_test, Y_test, best_weights, get_acc=True)\n\nprint(\"Evaluation results\")\nprint(\"Training accuracy: {:.3f}\" .format(train_acc))\nprint(\"Validation accuracy: {:.3f}\" .format(val_acc))\nprint(\"Test accuracy: {:.3f}\" .format(test_acc))\n```\n\n    Evaluation results\n    Training accuracy: 99.571\n    Validation accuracy: 99.000\n    Test accuracy: 99.500\n\n\n\n```python\nplot_decision_boundary(X_test, Y_test, best_weights, dataset_type='test')\n```\n\n## Effect of weight initialization\n\nPreviously, we had initialized our weights to zero. What would have happened if we had initialized our weights too large? Let's check that too.\n\n\n```python\n# Initializing large weights\nweights = np.ones((n_features, n_outputs)) * 3\n```\n\n\n```python\ntrained_weights = train(X_normalized_train, Y_train, weights, learning_rate=0.05, total_epochs=1000)\n```\n\n    Training completed at 1000 epochs. 9 misclassified points remain.\n\n\nWe see a similar effect. After 1000 epochs, training has still not converged. Let's see when does it converge.\n\n\n```python\ntrained_weights = train(X_normalized_train, Y_train, weights, learning_rate=0.05, total_epochs=10000)\n```\n\n    Training completed at 10000 epochs. 4 misclassified points remain.\n\n\nWe shall see about better strategies of weight initializations later in the course.\n\n## Effect of biases\n\nBias are additional constants attached neurons and added to the weighted input before the activation function is applied.\n\nLet's visualize this effect of adding and removing biases in perceptron. The characteristics of biases found here is broadly applicable to other neural networks algorithms.\n\nWe know that an equation of the line can be described as such: $y = w \\times x + b$. From this equation we know that intercept $b$ allows our equation to translate in our 2D plane.\n\nW.r.t our perceptron model, we had derived a similar analogy: $Y_{prediction} = \\text{signum_activation}(weights \\times X_{input} + bias$).\n\nLet us define an equation of line as follows: $0.25x - 0.85y + 3 = 0$. If we consider this line as our decision boundary, our optimal weights $=[0.25, -0.85]$ and bias $=[3]$. We will generate a random set of points on either side of line but not on it (for simplicity).\n\n\n```python\nimport numpy as np\n```\n\n\n```python\n# Setting the seed to ensure reproducibility of experiments\nnp.random.seed(10)\n\nX = np.random.randint(-10, 10, size=(1000, 2))\n\n# Adding column of ones to absorb bias b of the hyperplane into X\nbias_ones = np.ones((len(X), 1))\nX = np.hstack((X, bias_ones))\n```\n\n\n```python\n# our optimal weights\nbest_weights = np.array([[0.25], [-0.85], [3]])\n```\n\n\n```python\n# Method to generate random set of points on either side of line but not on it.\ndef get_relevant_points(X, weights):\n  y_pred = np.dot(X, weights)\n  y_pred[y_pred < 0] = -1\n  y_pred[y_pred > 0] = 1\n  relevant_idxs = np.argwhere(y_pred != 0)[:, 0]\n  on_the_line_idxs = np.argwhere(y_pred == 0)[:, 0]\n  return y_pred, relevant_idxs, on_the_line_idxs\n```\n\n\n```python\ny_pred, relevant_idxs, on_the_line_idxs = get_relevant_points(X, best_weights)\n\nX_on_the_line = X[on_the_line_idxs]\ny_on_the_line = y[on_the_line_idxs]\n\nX = X[relevant_idxs]\ny = y_pred[relevant_idxs]\n```\n\n\n```python\nplot_decision_boundary(X, y, best_weights, dataset_type='test', bias='on', class_label_01_form='off', model_type='perceptron')\n```\n\n\n```python\n# Removing the column of ones\nX = X[:, :2]\nX.shape\n```\n\n\n\n\n    (995, 2)\n\n\n\nNote that after generating the samples above, we aren't appending a column of ones in $X$. Hence, when we multiply $X$ with weights $w$, we are not including the bias term.\n\n\n```python\n# Initializing weights to zero\n_, n_features = np.shape(X)\n_, n_outputs = np.shape(y)\n\nnon_bias_weights = np.zeros((n_features, n_outputs))\n```\n\n\n```python\nnon_bias_weights.shape\n```\n\n\n\n\n    (2, 1)\n\n\n\n\n```python\n# Removing bias term and training the network only with weights.\ntrained_weights = train(X, y, non_bias_weights, learning_rate=0.1)\n```\n\n    Training completed at 100 epochs. 181 misclassified points remain.\n\n\n\n```python\ngenerate_gifs(X, y, trained_weights, 'train', path='content/training_decision_boundary_with_non_bias_weights.gif', bias='off')\n```\n\n    Gif/image generated\n\n\n\n\nFrom the above gif, we can see that the decision boundary (or line equation) always passes through $0$ and is of the form: $\\text{const1} \\times x + \\text{const2} \\times y = 0$. What happens if we include the bias term while training the perceptron model? Let's see.\n\n\n```python\n# Adding column of ones to absorb bias b of the hyperplane into X\nbias_ones = np.ones((len(X), 1))\nX = np.hstack((X, bias_ones))\n```\n\n\n```python\n# Initializing weights to zero\n_, n_features = np.shape(X)\n_, n_outputs = np.shape(y)\n\nweights_with_bias = np.zeros((n_features, n_outputs))\n```\n\n\n```python\nweights_with_bias.shape\n```\n\n\n\n\n    (3, 1)\n\n\n\n\n```python\n# Adding bias term and training the network only with weights.\ntrained_weights = train(X, y, weights_with_bias, learning_rate=0.1, total_epochs=1000)\n```\n\n    Training has stabilized with all points classified:  616\n\n\n\n```python\n# Taking last 50 weights since creating gif files can take too much time\nif len(trained_weights) > 100:\n  last_50_trained_weights = trained_weights[len(trained_weights)-50:]\n```\n\n\n```python\ngenerate_gifs(X, y, last_50_trained_weights, 'train', path='content/training_decision_boundary_weights_with_bias.gif', bias='on')\n```\n\n    Gif/image generated\n\n\n\n\nFrom the above gif, we can see that bias helps translate the decision boundary by representing pattern that don't necessarily pass through zero. In effect, a bias value lets you to shift the activation function by learning an appropriate threshold. One bias unit is always sufficient since it will affect each neuron differently based on its weight with each unit. Generally, to successfully learn an ML model, it almost always helpful to assign bias to every non-input since without bias, weights would have thresholds that will always be zero.\n\n## Partially separable dataset\n\nLet's see how the perceptron learns the decision boundary on a partially separable dataset.\n\n\n```python\n# Initializing weights to zero\n_, n_features = np.shape(X)\n_, n_outputs = np.shape(y)\n\nweights_with_bias = np.zeros((n_features, n_outputs))\n```\n\n\n```python\nweights_with_bias.shape, X.shape, y.shape\n```\n\n\n\n\n    ((3, 1), (995, 3), (995, 1))\n\n\n\n\n```python\n# Collecting all indexes with class label = 1. Ramdomly sampling 5 indexes\n# and setting class labels = -1\nnp.random.seed(10)\nidxs_class_labels_one = np.argwhere(y == 1)[:, 0]\nidxs_class_labels_one = random.sample(idxs_class_labels_one.tolist(), 5)\ny[idxs_class_labels_one] = -1\n```\n\n\n```python\n# Adding bias term and training the network only with weights.\ntrained_weights = train(X, y, weights_with_bias, learning_rate=0.1, total_epochs=1000)\n```\n\n    Training completed at 1000 epochs. 59 misclassified points remain.\n\n\n\n```python\n# Taking last 50 weights since creating gif files can take too much time\nif len(trained_weights) > 100:\n  last_50_trained_weights = trained_weights[len(trained_weights)-50:]\n```\n\n\n```python\ngenerate_gifs(X, y, last_50_trained_weights, 'train', path='content/training_decision_boundary_partially_separable_dataset.gif')\n```\n\n    Gif/image generated\n\n\n\n\n# Perceptron learning and the XOR problem\n\n\n```python\n# Setting the seed to ensure reproducibility of experiments\nnp.random.seed(10)\n\n# Set the input data\nX = np.array([[0, 0], [0, 1],\n              [1, 0], [1, 1]])\n\n# Set the labels, the correct results for the xor operation\ny = np.array([[0], [1], [1], [0]])\n\n# Adding column of ones to absorb bias b of the hyperplane into X\nbias_ones = np.ones((len(X), 1))\nX = np.hstack((X, bias_ones))\n```\n\n\n```python\n# Initializing weights from uniform distribution\nnp.random.seed(312)\nn_samples, n_features = np.shape(X)\n_, n_outputs = np.shape(y)\n\nlimit = 1 / math.sqrt(n_features)\nweights = np.random.uniform(-limit, limit, (n_features, n_outputs))\nweights[-1] = 0\n```\n\n\n```python\n# Train the network with the above weights\ntrained_weights = train(X, y, weights, learning_rate=0.1, total_epochs=50)\n```\n\n    Training completed at 50 epochs. 2 misclassified points remain.\n\n\n\n```python\ngenerate_gifs(X, y, trained_weights, 'train', path='content/xor_training_decision_boundary.gif')\n```\n\n    Gif/image generated\n\n\n\n\nBy training the perceptron model for 10 epochs we can clearly see from the gif above, that at a time, atleast 2 to atmost 3 of the points are missclassified. \n\nThis characteristic persists even if we train the perceptron model for higher number of epochs. The perceptron is unable to classify all the points correctly. Theoretically, the perceptron is unable to converge on a XOR dataset. Why do you think this is the case? The reason is because the classes in XOR are not linearly separable.\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "e5d3649b841abca279eb759c429fe3da9f411607", "size": 283983, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "HW7/Linear Perceptron Tutorial.ipynb", "max_stars_repo_name": "avani17101/SMAI-Assignments", "max_stars_repo_head_hexsha": "8d408911f964768bf50d965f881d10d37ac8f7f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-03-05T12:28:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-05T12:28:44.000Z", "max_issues_repo_path": "HW7/Linear Perceptron Tutorial.ipynb", "max_issues_repo_name": "avani17101/Statistical-Methods-in-AI", "max_issues_repo_head_hexsha": "8d408911f964768bf50d965f881d10d37ac8f7f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW7/Linear Perceptron Tutorial.ipynb", "max_forks_repo_name": "avani17101/Statistical-Methods-in-AI", "max_forks_repo_head_hexsha": "8d408911f964768bf50d965f881d10d37ac8f7f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-05T12:21:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-05T12:21:26.000Z", "avg_line_length": 136.5302884615, "max_line_length": 93860, "alphanum_fraction": 0.8830422948, "converted": true, "num_tokens": 5665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735801686526387, "lm_q2_score": 0.1097057796995814, "lm_q1q2_score": 0.03371895088712086}}
{"text": "# General Announcements\n\n* HW2 and Quiz 3 are now posted on Canvas\n* Nataly has posted a poll about office hours on Canvas. We will switch them if there is strong availability at another time.\n* Today's lecture supplements from the following texts:\n  * Krane, Kenneth S. Introductory nuclear physics. John Wiley & Sons, 1991. (Sections 3.3 and Ch5) \n  * Martin, James E. Physics for radiation protection: a handbook. John Wiley & Sons, 2006. (Sections 2.4-2.6) \n\n\n```python\n%matplotlib notebook\n%matplotlib inline\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\n```\n\n# Nuclear Models\n\n## Learning objectives\n\n- Summarize the history of atomic theory development.\n- Recognize the radiation signatures that drove early atomic theory.\n- List atomic models: Plum Pudding, Rutherford, Bohr, Bohr with Elliptical Orbits, Quantum Mechanical\n- Differentiate various atomic models by name and physics.\n- List nuclear models: Proton-electron, Proton-neutron, Liquid-Drop, Shell\n- Differentiate nuclear models by name and physics.\n- Identify the physics captured by various nuclear models.\n- Explain the reason for the structure of most likely decays in the chart of the nuclides\n\n## Discovery of Radioactivity\n\n1896: Becquerel found that some U salts emitted \"X-Rays\" that fogged photographic plates. \n\n1898: The Curies also found two elements that had these properties -- Radium and Polonium \n\n\n\nExperiments with electrically charged plates impose a magnetic field (out of the page). Three types of radiation appeared to exist from various elements. \n\n\n\n21.3 Radioactive Decay by Rice University is licensed under a Creative Commons Attribution 4.0 International License, except where otherwise noted. (https://opentextbc.ca/chemistry/chapter/21-3-radioactive-decay/)\n\n\n- Alpha $(\\alpha)$ particles are attracted to the negative plate and deflected by a relatively small amount.\n- Beta $(\\beta)$ particles are attracted to the positive plate and deflected by a larger amount.\n- Gamma $(\\gamma)$ particles seem to be unaffected.\n\n### Exercise: Think-pair-share\n\nBased on these experimental results:\n\n1. What can one determine about the charges of the alpha, beta, and gamma particles?\n2. What can one determine about the weights of the particles?\n\n\n### Knowledge of the atom\n\nWhat we've talked about in the last few lectures contributed to vital insights about the atom and its structure and how various components relate to one another.  \n\n- Quantized energy could be emitted from atoms\n- Electrons can be broken off of atoms, and look the same regardless of what element they come from\n- There must exist a positively charged component, because atoms are electrically neutral until electrons are removed. \n\n### Plum Pudding Model\n\nJ.J. Thomson correctly identified the beta rays as electrons. \nSo, electrons must be somewhere in the atom. However, atoms seemed be generally electrically neutral. \nBeing british, J.J. Thomson equated this to plum pudding (year 1904):\n\n\n\n\nHe had no reason to believe that the charges were not uniformly distributed.\n\n\n\n\nExplains:\n\n- electrically neutral atoms\n- size of the atom $(10^{-8} cm)$\n- an ion is an atom from which an electron has been lost\n- charge of a singly ionized atom is exactly one negative charge of an electron  \n- number of electrons equals approximately half of the atomic weight of the atom\n\nIssues: \n- Does not explain frequencies observed in optical spectra\n- Where the rest of the mass comes from (electrons only account for small fraction of mass\n\n\n### Rutherford Model\n\nGold foil experiment by Geiger (same one associated with the Geiger counter) and Marsden. Alpha particles bombarded a very thin gold sheet/foil. Reflected alphas were very unlikely to be observed if the Thomson model was correct.\n\n<a title=\"By Kurzon [CC BY-SA 3.0 \n (https://creativecommons.org/licenses/by-sa/3.0\n)], from Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File:Geiger-Marsden_experiment_expectation_and_result.svg\"></a>\n\n\nIn **1911** Rutherford surmised that a dense, positively charged thing must be at the center of the atom, perhaps with a diameter of $10^{-14}m$ or less. Rutherford also postulated a \"neutral\" particle may help contribute to this (it helped explain discrepencies between mass and charge)\n\nDeficiency of Rutherford\u2019s model:\nAccording to classical electromagnetic theory, an accelerating charge must emit electromagnetic waves. Thus, an electron circling the nucleus (electron) would radiate away their kinetic energy, r would slowly decrease, and the atom will collapse. \n\n\n### Bohr Model\n\nIn the 1880s, Balmer, Rydberg, and others had observed **discrete lines** in the wavelength spectrum of atomic hydrogen when atoms are excited.\n\n<a title=\"By Merikanto, Adrignola (File:Emission spectrum-H.png) [CC0], via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File:Emission_spectrum-H.svg\"></a>\n\nThe equation explaining these emission lines was well known by the early 1900s.\n\n\\begin{align}\n\\frac{1}{\\lambda} &= R_H \\left[\\frac{1}{n_o^2} - \\frac{1}{n^2} \\right]\\\\\n\\mbox{where  }&\\\\\n\\lambda &= \\mbox{the wavelength of electromagnetic radiation emitted in vacuum}\\\\\nR_H &= \\mbox{the Rydberg constant } \\\\\n&\\simeq  1.097373156850865 \\times 10^7 m^{-1} \\\\\n\\implies \\frac{1}{R} &=912 \\mbox{ angstrom}\\\\\n\\end{align}\n\nIn the Bohr model, then, electrons were allowed only in certain orbits. Bohr's model had three postulates: \n1) An electron in an atom can move about the nucleus in discrete stationary states without radiating. \n\n2) The allowed stationary states of orbiting electrons are specifically only those orbits whose angular momentum is an integral multiple of $h/2\\pi$ \n\nand satisfied the following relation:\n\n\\begin{align}\n\\frac{m_ev^2}{r} &= \\frac{Ze^2}{4\\pi\\epsilon_or^2}\\\\\nL &\\equiv m_evr = n\\frac{h}{2\\pi}\\\\\n\\mbox{where }&\\\\\nn&=1,2,3...\\\\\nL&=\\mbox{angular momentum}\\\\\nv&=\\mbox{velocity of the electron}\\\\\nr&=\\mbox{radius of the electron orbit}\\\\\n\\epsilon_o&=\\mbox{permittivity of free space}\\\\\n&= 8.85418782 \\times 10^{-12} m^{-3} kg^{-1} s^4 A^2\n\\end{align}\n\nSolving those relations for $r$ and $v$ :\n\n\\begin{align}\nv_n &= \\frac{Ze^2}{2\\epsilon_onh}\\\\\nr_n &= \\frac{n^2h^2\\epsilon_o}{\\pi m_e Z e^2}\n\\end{align}\n\nAnd finally, \n\n3) An electron can jump from a higher energy state $E_2$ to a lower enegy orbit $E_1$ by emitting electromagnetic radiation of energy $h\\nu$\n\nThis explained the discreteness, as electrons might radiate energy only when moving from one allowed orbit to another.\n\n<a title=\"JabberWok [GFDL (http://www.gnu.org/copyleft/fdl.html) or CC-BY-SA-3.0 (http://creativecommons.org/licenses/by-sa/3.0/)], via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File:Bohr-atom-PAR.svg\"></a>\n\n\nElectron\u2019s total energy under a certain orbit:\n\n\\begin{align}\nE_n &= \\frac{-m_e(Ze^2)^2}{8\\epsilon_o^2 n^2 h^2}\\\\\n\\end{align}\n\n\nEnergy difference between two allowed orbits:\n\n\\begin{align}\n\\Delta E_{n\\rightarrow n_o} &= h\\nu_{n\\rightarrow n_o} \\\\\n &=  \\frac{-m_e(Ze^2)^2}{8\\epsilon_o^2 h^2}\\left[\\frac{1}{n_o^2} - \\frac{1}{n^2}\\right]\\\\\n\\end{align}\n\n\nThis model explained a lot.\n\n<a title=\"By A_hidrogen_szinkepei.jpg: User:Szdori\nderivative work: OrangeDog (talk \u2022 contribs) (A_hidrogen_szinkepei.jpg) [CC BY 2.5 \n (https://creativecommons.org/licenses/by/2.5\n), GFDL (http://www.gnu.org/copyleft/fdl.html) or CC-BY-SA-3.0 (http://creativecommons.org/licenses/by-sa/3.0/)], via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File:Hydrogen_transitions.svg\"></a>\n\n### Bohr Model : Elliptic Orbits\n\nFine structure: Spectral lines are consisted of a number of lines very close together.\n\n- Except the quantum number $n$, there are some energy levels lying close to one another. \n- Sommerfeld postulated elliptic orbits as well as circular orbits and introduced another quantum number to describe the **angular momentum** of orbits. \n\nThis helped explain the fine structure that was observed. However, Sommerfeld\u2019s theory predicted more lines than were observed in experiments.\n\nThus, a new quantum number  $n$  needed an _ad hoc_ selection rule to limit the number of predicted lines.\n\n\n<a title=\"By Pieter Kuiper [Public domain], from Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File:Sommerfeld_ellipses.svg\"></a>\n\n\nSplitting of the spectral lines was observed: A third quantum number $m$ needed to be introduced to revise Bohr\u2019s model. also predicted more lines\n\nThe theory failed to applied to more complicated atoms (multiplet structure is observed).\n\nFurther change of Bohr\u2019s theory can no longer resolve the difficulties. \n\n### Quantum Mechanical Model\n\nThe electrons are no longer modeled as particles moving in orbits. Instead, they are modeled as a standing wave around the nucleus. The magnitude of that wave reflects the probability of finding the electron in that locations.\n\n- Schrodinger\u2019s new approach:  **the wave function**\n- The electrons are no longer point particles; they are visualized as a standing wave around the nucleus.\n\nThe three quantum numbers ($n$, $l$ , $m$) arose from the theory naturally - no ad hoc selection rules were needed. \n\nA fourth quantum number $m_s$ was introduced to explain:\n- Multiple fine-line structure\n- Splitting of lines in a strong magnetic field ( the **anomalous Zeeman effect**)\n\n<a title=\"By Danski14 [CC BY-SA 3.0 \n (https://creativecommons.org/licenses/by-sa/3.0\n)], from Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File:Breit-rabi-Zeeman.png\"></a>\n\nThe $m_s$ quantum number accounted for the inherent angular momentum of the electron equal to $\\pm\\frac{h}{2\\pi}$. Later, in 1928, Dirac would show that this fourth quantum number also arises from the wave equation.\n\n## Nuclear Models\n\n\n### Fundamental properties of the nucleus \n\nSome simple facts were determined about the mass of the nucleus.\n\n1. The **masses of atoms** were very nearly whole numbers if one defines the atomic mass unit as:\n\\begin{align}\n1 u = \\frac{1}{12}M(^{12}C)\n\\end{align}\n2. The **mass contribution from electrons** is quite **small**\n  - In $^{12}C$, the six electrons together only weigh $0.00329u$\n  \n  \nAlso, electron scattering experiments yielded details about the density of the nucleus and its components.\n**The density of protons** inside the spherical nuclei was well understood to be a function of the radius, dropping off appreciably at the boundary of the nucleus.\n\n\\begin{align}\n\\rho_p(r) &= \\frac{\\rho_p^o}{1+e^{\\frac{(r-R)}{a}}} \\left[\\frac{\\mbox{protons}}{fm^3}\\right]\\\\\n\\mbox{where }&\\\\\nr &= \\mbox{distance to center of nucleus}\\\\\nR &= \\mbox{total 'radius' of the nucleus}\\\\\na &= \\mbox{surface thickness}\\\\\n\\rho_p^o &= \\int\\int\\int \\rho_p(r)dV\\\\\n&= 4\\pi\\int_0^\\infty r^2\\rho_p(r)dr\\\\\n&= Z\n\\end{align}\n\nAlso, the R value, the radius of the nucleus was seen empirically to be proportional to $A^{1/3}$.\n\n\n```python\ndef rho_p(r, rho_po, radius, a):\n    denom = 1 + math.exp((r - radius)/a)\n    return rho_po/denom\n```\n\n\n```python\n# For 16O (from table 3.2)\no_rho_po = 0.156 # fm^{-3}\no_radius = 2.61 # fm\no_a = 0.513\n\n# For 109Ag (from table 3.2)\nag_rho_po = 0.157 # fm^{-3}\nag_radius = 5.33 # fm\nag_a = 0.523\n\n# For 208Pb (from table 3.2)\npb_rho_po = 0.159 # fm^{-3}\npb_radius = 6.65 # fm\npb_a = 0.526\n\nr = np.arange(0, 10, 0.1)\nto_plot_o = np.arange(0., 100.)\nto_plot_ag = np.arange(0., 100.)\nto_plot_pb = np.arange(0., 100.)\n\nfor i in range(0, 100):\n    to_plot_o[i]  = rho_p(r[i], o_rho_po, o_radius, o_a)\n    to_plot_ag[i] = rho_p(r[i], ag_rho_po, ag_radius, ag_a)\n    to_plot_pb[i] = rho_p(r[i], pb_rho_po, pb_radius, pb_a)\n\nplt.plot(r, to_plot_o, label=\"$^{16}O$\")\nplt.plot(r, to_plot_ag, label=\"$^{109}Ag$\")\nplt.plot(r, to_plot_pb, label=\"$^{208}Pb$\")\nplt.ylabel(\"Proton density ($fm^{-3}$)\")\nplt.xlabel(\"distance from center $(fm)$\")\nplt.legend()\n```\n\n# Review from last lecture \n\n### Proton Electron Model\n\nThis model sought primarily to explain the wholeness of mass numbers. To do so, it simply assumed that all heavier nuclei were composed of multiples of the hydrogen nucleus (assumed to be a single proton), which has the smallest mass(1 amu).\n\nFor this to match what was known about atomic charge, electrons would need to be in the nucleus to cancel some, but not all, of the positive charge from the protons.\n\n**In this model** an atom $^A_ZX$ would have a nucleus containing A protons and (A \u2212 Z) electrons with Z electrons surrounding the nucleus. This postulated extra electrons -- to explain it, the mass of the electrons was assumed to make a negligible contribution.\n\nTwo difficulties with this P-E Model:\n\n1. Predicted angular momentum (spin) of the nuclei did not always agree with experiment. \n   **Protons and electrons both have half integer spin**, so when an even number are combined, whole integer spin should result. For example, **the model predicted integer spin for Beryllium, while experiments predicted half-integer spin.** Similarly, **the model predicted half-integer spin in nitrogen but experimental results show nitrogen has integer spin.**\n\n2. Uncertainty Principle \n\n\\begin{align}\n\\Delta p \\Delta x &\\ge \\frac{h}{4\\pi}\n\\end{align}\n   \n\nIf an electron is in the nucleus, then $\\Delta x\\simeq10^{-14}m$. Accordingly:\n\\begin{align}\nmin(\\Delta_p) = 1.1\\times 10^{-20}J m^{-1}s\n\\end{align}\nSince the electron\u2019s total energy is\n\\begin{align}\nE &= T +m_oc^2 \\\\\n&=\t\\sqrt{p^2c^2 +m^2_oc^4}\\\\\n\\implies &\\\\\n&\\forall p = \\Delta p : E \\simeq T = 20 MeV\\\\\n\\end{align}\n\nSince the electron's rest-mass energy is 0.51 MeV and beta particles emitted by atoms seldom have energies above a few MeV, something was wrong with this calculation.\n\nYou can do the same calculation for the proton. Because it has a much higher mass, there is no discrepancy. The energy of a free proton confined to a nucleus is its rest-mass energy (931 MeV), with $T<1MeV$.\n\n### 1932: Chadwick discovers the neutron\n\nChadwick discovers the existence of a chargeless particle with a mass just slightly greater than that of the proton.\n\n\\begin{align}\nm_n &= 1.008665 u\\\\\nm_p &= 1.007276 u\n\\end{align}\n\n\n\n### Proton-Neutron Model\n\n- **1932** Chadwick discovered the neutron. \n- **1932** Heisenberg first suggested every nucleus is composed of only protons and neutrons.\n\n**In this model**, a nucleus with a mass number A contains Z protons and N = A \u2212 Z neutrons. \n\n- This P-N Model avoids the failures of the P-E model. \n- Also is consistent with experimental results regarding radioactivity \n- Since the neutron has half-integral spin, the A neutrons and protons give appropriate spin for the total atom in all cases.\n\nChallenges for this model:\n\n- Because of Coulombic repulsive forces in the nucleus, a 'nuclear force' must hold the nucleus together\n- To hold the protons and neutrons together: \n      nuclear force : p-n , n-n , p-p\n      1.  inside the nucleus: nuclear force (attractive)\n      2. outside the nucleus: Coulombic force (repulsive)\n\nThe energy needed to separate nucleus into $p_s$ & $n_s$ : binding energy\n\n\nIn the image below, the nuclear potential well is shown.\n\n\n**The above image was reproduced from Shultis, J. K. and Faw, R. E. \u201cFundamentals of Nuclear Science and Engineering\u201d (2016).**\n\n## Nuclear Stability\n\n<a title=\"By Table_isotopes.svg: Napy1kenobi\nderivative work: Sjlegg (Table_isotopes.svg) [CC BY-SA 3.0 \n (https://creativecommons.org/licenses/by-sa/3.0\n) or GFDL (http://www.gnu.org/copyleft/fdl.html)], via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File:Table_isotopes_en.svg\"></a>\n\n**Figure** Graph of isotopes by type of nuclear decay. Orange and blue nuclides are unstable, with the black squares between these regions representing stable nuclides. The unbroken line passing below many of the nuclides represents the theoretical position on the graph of nuclides for which proton number is the same as neutron number. The graph shows that elements with more than 20 protons must have more neutrons than protons, in order to be stable.\n\n\n\n**The above image was reproduced from Shultis, J. K. and Faw, R. E. \u201cFundamentals of Nuclear Science and Engineering\u201d (2016).**\n\n- many more stable isotopes with even N and/or Z\n- in a heavy nucleus, the neutrons and protons tend to group themselves into subunits of 2 neutrons and 2 protons.\n- when either Z or N equals 8, 20, 50, 82, or 126, there are relatively greater numbers of stable nuclides. \n\n### Shell Model\n\nRecall from your chemistry class how ionization energy for electrons varies at it fills orbital shells. \n\n\n**The above image was reproduced from Figure 5.1 in Krane, K. \u201cIntroductory Nuclear Physics\u201d (1988).**\n\nWe also see strong effects on the atomic radius based on filled electron orbital shells. This implies a stable structure when shells are filled. \n\nTo remove a single proton or neutron from the nucleus, we use a term called the \"separation energy\". That is, the energy needed to remove that nucleon from the nucleus. Below, let's look at the two proton and two neutron separation energies for some nucleons of constant N (isotones). \n\n\n**The above image was reproduced from Figure 5.2 in Krane, K. \u201cIntroductory Nuclear Physics\u201d (1988).**\n\nThe liquid drop model cannot explain the abnormal high stable nuclides(magic numbers:2,8,20,28,50,82,126). Thus, the nuclear shell model is another attempt at explaining the structure of the nucleus. \n\n\n**The above image was reproduced from Figure 5.7 in Krane, K. \u201cIntroductory Nuclear Physics\u201d (1988).**\n\n> The filling of shells in $^{15}O$ and $^{17}O$. The filled proton shells do not contribute to the structure; the properties of the ground state are determined by the odd neutron. \n\nWe can see effects of the nucleon shells in the chart of the nuclides too. These help explain the stable isotopes that exist on magic number lines as well as \"islands of stability\". \n\n<a title=\"By Table_isotopes.svg: Napy1kenobi\nderivative work: Sjlegg (Table_isotopes.svg) [CC BY-SA 3.0 \n (https://creativecommons.org/licenses/by-sa/3.0\n) or GFDL (http://www.gnu.org/copyleft/fdl.html)], via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File:Table_isotopes_en.svg\"></a>\n\n**The shell model assumes**: (Shrodinger\u2019s wave eq.)\nEach nucleon moves independently.\nEach nucleon moves in a potential well.\n\nWhen the model\u2019s quantum-mechanical wave eq. is solved, the nucleons are found to distribute themselves into a number of energy levels.\nFilled shells are indicated by large gaps between each adjacent energy level.\n\n\n### Bringing them all together: the semiemperical mass formula\n\n\nLet us attempt to summarize our current understanding of the atom by combining various terms that we know are important to the structure of the nucleus. \n\nFirst, we are going to express this concept in terms of binding energy per nucleon. We are starting with the concept that the binding energy B is proportional to the increase in nucleons, A. \n\n$\nB = [Zm(^{1}H) + Nm_{n} - m(^{A}X)]c^2\n$\n\nIf we can come up with an approach to determine B, we can predict the mass of $^{A}X$\n\nFirst, \n1. volume term: volume binding energy is proportional to the number of nucleons (i.e. # of nucleons.) **liquid drop**\n\nVolume Term = $a_{v}A$\n\n2. Surface term: Nucleons near the surface of the nucleus are not completely surrounded by other nucleons as interior nucleons. **liquid drop**\n\nSurface Term = $a_{s}A^{2/3}$\n\n(this is because the surface area of the nuclueus is proportional to $R^{2}$, or $A^{2/3}$ since $R \\propto A$) \n\n3. Coulomb term: Coulombic repulsive force decrease the stability of nucleons (reduces the BE ). **liquid drop** \n\nCoulomb Term = $a_{c}Z(Z-1)A^{1/3}$\n\n4. Symmetry term: a departure from symmetry (N=Z) tends to reduce nuclear stability. (Fig.3.10 ) **shell model**\n\nSymmetry Term = $a_{sym}\\frac{(A-2Z)^2}{A}$\n\n\n5. pairing term : pairing neutrons and protons are more stable. (even N or Z; odd N or Z ; even N (Z), odd Z (N)) (Fig.3.11 & Fig.3.12) **shell model**\n\nPairing Term = $a_{p}A^{-3/4}$\n\n\n<a title=\"By Daniel FR [CC BY-SA 3.0 \n (https://creativecommons.org/licenses/by-sa/3.0\n)], via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File:Liquid_drop_model.svg\"></a>\n\nCombining all the five terms we've discussed... \n\n\\begin{align}\nBE &= a_{v}A - a_{s}A^{2/3} - a_{c}Z(Z-1)A^{-1/3} - a_{sym}\\frac{(A-2Z)^2}{A} \\pm a_{p}A^{-3/4}\n\\end{align}\n\nwhere \n* $a_{v}$ = 15.5MeV\n* $a_{s}$ = 16.8MeV\n* $a_{c}$ = 0.72MeV\n* $a_{sym}$ = 23MeV\n* $a_{p}$ = 34 MeV\n\nHigher binding energy $\\implies$ a more stable nuclide.\n\n\n**The above image was reproduced from Figure 3.17 in Krane, K. \u201cIntroductory Nuclear Physics\u201d (1988).**\n> The contributions of the various terms in the semiemperical mass formula to the binding energy per nucleon\n\nIn our next lecture, we will discuss binding energy calculations. However, if we know that the difference between the constituent parts of the atom and its measured mass is the binding energy, we can use our binding energy formula to calculate a **semiemperical mass**. \n\n\\begin{align}\nM(Z,A) &= Zm(^{1}H)-Nm_{n}-B(Z,A)/c^{2}\n\\end{align}\n\nThis is the **semiemperical mass formula**\n\nFor constant A, we will see a parabola dependent on Z and M. \n\n### Exercise: Think-pair-share \n\nGiven a constant A of several isotopes, what do you think a lower mass says about the binding energy? \n\n\n**The above image was reproduced from Figure 3.18 in Krane, K. \u201cIntroductory Nuclear Physics\u201d (1988).**\n> Mass chains for A=125 and A=128. For A=125, note how the energy differences between neighboring isotopes increase as we go further from the stable member at the energy minimum. For A=128, note the effect of the pairing term; in particular $^{128}I$ can decay in either direction and it is energetically possible for $^{128}Te$ to decay directly to $^{128}Xe$ by the process known as double $\\beta$ decay. \n\n<a title=\"By Fujnky [CC BY-SA 4.0 \n (https://creativecommons.org/licenses/by-sa/4.0\n)], from Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File:Semi-empirical_mass_formula.png\"></a>\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "979b90169da99c4c68d81893b3d828bb3b0ecf0a", "size": 31379, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "10.03-nuclear_models/00-nuclear-models.ipynb", "max_stars_repo_name": "npre247/npre247", "max_stars_repo_head_hexsha": "2960184fbd3caef6c052dc22bf6f62bab81af21b", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-01-31T17:44:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T19:54:50.000Z", "max_issues_repo_path": "10.03-nuclear_models/00-nuclear-models.ipynb", "max_issues_repo_name": "npre247/npre247", "max_issues_repo_head_hexsha": "2960184fbd3caef6c052dc22bf6f62bab81af21b", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2022-01-28T20:32:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T17:43:54.000Z", "max_forks_repo_path": "10.03-nuclear_models/00-nuclear-models.ipynb", "max_forks_repo_name": "npre247/npre247", "max_forks_repo_head_hexsha": "2960184fbd3caef6c052dc22bf6f62bab81af21b", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2022-01-24T16:47:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T04:09:25.000Z", "avg_line_length": 47.5439393939, "max_line_length": 463, "alphanum_fraction": 0.6323018579, "converted": true, "num_tokens": 5884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16238002855971878, "lm_q2_score": 0.2068940439256578, "lm_q1q2_score": 0.03359546076148402}}
{"text": "```python\n# This cell is added by sphinx-gallery\n# It can be customized to whatever you like\n%matplotlib inline\n```\n\n.. role:: html(raw)\n   :format: html\n\nUnderstanding the Haar Measure\n==============================\n\n.. meta::\n    :property=\"og:description\": Learn all about the Haar measure and how to randomly sample quantum states.\n\n    :property=\"og:image\": https://pennylane.ai/qml/_images/spherical_int_dtheta.png\n\n.. related::\n\n    quantum_volume Quantum volume\n    qsim_beyond_classical Beyond classical computing with qsim\n    tutorial_barren_plateaus Barren plateaus\n\n\n*Author: PennyLane dev team. Posted: 22 March 2021. Last updated: 22 March 2021.*\n\nIf you've ever dug into the literature about random quantum circuits,\nvariational ansatz structure, or anything related to the structure and\nproperties of unitary operations, you've likely come across a statement like the\nfollowing: \"Assume that $U$ is sampled uniformly at random from the Haar\nmeasure\".  In this demo, we're going to unravel this cryptic statement and take\nan in-depth look at what it means. You'll gain an understanding of the general\nconcept of *measure*, the Haar measure and its special properties, and you'll\nlearn how to sample from it using tools available in PennyLane and other\nscientific computing frameworks. By the end of this demo, you'll be able to\ninclude that important statement in your own work with confidence!\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>To get the most out of this demo, it is helpful if you are familiar with\n   `integration of multi-dimensional functions\n   <https://en.wikipedia.org/wiki/Multiple_integral>`__, the `Bloch sphere\n   <https://en.wikipedia.org/wiki/Bloch_sphere>`__, and the conceptual ideas\n   behind `decompositions\n   <https://en.wikipedia.org/wiki/Matrix_decomposition>`__ and factorizations of\n   unitary matrices (see, e.g., 4.5.1 and 4.5.2 of [#NandC2000]_).</p></div>\n\nMeasure\n-------\n\n`Measure theory <https://en.wikipedia.org/wiki/Measure_(mathematics)>`__ is a\nbranch of mathematics that studies things that are measurable---think length,\narea, or volume, but generalized to mathematical spaces and even higher\ndimensions. Loosely, the measure tells you about how \"stuff\" is distributed and\nconcentrated in a mathematical set or space. An intuitive way to understand\nmeasure is to think about a sphere. An arbitrary point on a sphere can be\nparametrized by three numbers---depending on what you're doing, you may use\nCartesian coordinates $(x, y, z)$, or it may be more convenient to use\nspherical coordinates $(\\rho, \\phi, \\theta)$.\n\nSuppose you wanted to compute the volume of a solid sphere with radius\n$r$.  This can be done by integrating over the three coordinates\n$\\rho, \\phi$, and $\\theta$. Your first thought here may be to simply\nintegrate each parameter over its full range, like so:\n\n\\begin{align}V = \\int_0^{r} \\int_0^{2\\pi} \\int_0^{\\pi} d\\rho~ d\\phi~ d\\theta = 2\\pi^2 r\\end{align}\n\nBut, we know that the volume of a sphere of radius $r$ is\n$\\frac{4}{3}\\pi r^3$, so what we got from this integral is clearly wrong!\nTaking the integral naively like this doesn't take into account the structure of\nthe sphere with respect to the parameters. For example, consider\ntwo small, infinitesimal elements of area with the same difference in\n$\\theta$ and $\\phi$, but at different values of $\\theta$:\n\n.. figure:: /demonstrations/haar_measure/spherical_int_dtheta.png\n    :align: center\n    :width: 50%\n\n    |\n\nEven though the differences $d\\theta$ and $d\\phi$ themselves are the\nsame, there is way more \"stuff\" near the equator of the sphere than there is\nnear the poles. We must take into account the value of $\\theta$ when\ncomputing the integral! Specifically, we multiply by the function\n$\\sin\\theta$---the properties of the $\\sin$ function mean that the\nmost weight will occur around the equator where $\\theta=\\pi/2$, and the\nleast weight near the poles where $\\theta=0$ and $\\theta=\\pi$.\n\nSimilar care must be taken for $\\rho$.  The contribution to volume of\nparts of the sphere with a large $\\rho$ is far more than for a small\n$\\rho$---we should expect the contribution to be proportional to\n$\\rho^2$, given that the surface area of a sphere of radius $r$ is\n$4\\pi r^2$.\n\nOn the other hand, for a fixed $\\rho$ and $\\theta$, the length of\nthe $d\\phi$ is the same all around the circle. If put all these facts\ntogether, we find that the actual expression for the integral should look like\nthis:\n\n\\begin{align}V = \\int_0^r \\int_0^{2\\pi} \\int_0^{\\pi} \\rho^2 \\sin \\theta~ d\\rho~ d\\phi~\n    d\\theta = \\frac{4}{3}\\pi r^3\\end{align}\n\nThese extra terms that we had to add to the integral, $\\rho^2 \\sin\n\\theta$, constitute the *measure*. The measure weights portions of the sphere\ndifferently depending on where they are in the space. While we need to know the\nmeasure to properly integrate over the sphere, knowledge of the measure also\ngives us the means to perform another important task, that of sampling points in\nthe space uniformly at random. We can't simply sample each parameter from the\nuniform distribution over its domain---as we experienced already, this doesn't\ntake into account how the sphere is spread out over space. The measure describes\nthe distribution of each parameter and gives a recipe for sampling them in order\nto obtain something properly uniform.\n\nThe Haar measure\n----------------\n\nOperations in quantum computing are described by unitary matrices.\nUnitary matrices, like points on a sphere, can be expressed in terms of a fixed\nset of coordinates, or parameters. For example, the most general single-qubit rotation\nimplemented in PennyLane (:class:`~.pennylane.Rot`) is expressed in terms of three\nparameters like so,\n\n\\begin{align}U(\\phi, \\theta, \\omega) = \\begin{pmatrix} e^{-i(\\phi + \\omega)/2}\n                        \\cos(\\theta/2) & -e^{i(\\phi - \\omega)/2} \\sin(\\theta/2)\n                        \\\\ e^{-i(\\phi - \\omega)/2} \\sin(\\theta/2) & e^{i(\\phi +\n                        \\omega)/2} \\cos(\\theta/2) \\end{pmatrix}.\\end{align}\n\nFor every dimension $N$, the unitary matrices of size $N \\times N$\nconstitute the *unitary group* $U(N)$. We can perform operations on\nelements of this group, such as apply functions to them, integrate over them, or\nsample uniformly over them, just as we can do to points on a sphere. When we do\nsuch tasks with respect to the sphere, we have to add the measure in order to\nproperly weight the different regions of space. The *Haar measure* provides the\nanalogous terms we need for working with the unitary group.\n\nFor an $N$-dimensional system, the Haar measure, often denoted by\n$\\mu_N$, tells us how to weight the elements of $U(N)$. For\nexample, suppose $f$ is a function that acts on elements of $U(N)$,\nand we would like to take its integral over the group. We must write this\nintegral with respect to the Haar measure, like so:\n\n\\begin{align}\\int_{V \\in U(N)} f(V) d\\mu_N(V).\\end{align}\n\nAs with the measure term of the sphere, $d\\mu_N$ itself can be broken down\ninto components depending on individual parameters.  While the Haar\nmeasure can be defined for every dimension $N$, the mathematical form gets\nquite hairy for larger dimensions---in general, an $N$-dimensional unitary\nrequires at least $N^2 - 1$ parameters, which is a lot to keep track of!\nTherefore we'll start with the case of a single qubit $(N=2)$, then show\nhow things generalize.\n\nSingle-qubit Haar measure\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe single-qubit case provides a particularly nice entry point because we can\ncontinue our comparison to spheres by visualizing single-qubit states on the\nBloch sphere. As expressed above, the measure provides a recipe for sampling\nelements of the unitary group in a properly uniform manner, given the structure\nof the group. One useful consequence of this is that it provides a method to\nsample quantum *states* uniformly at random---we simply generate Haar-random\nunitaries, and apply them to a fixed basis state such as $\\vert 0\\rangle$.\n\nWe'll see how this works in good time. First, we'll take a look at what happens\nwhen we ignore the measure and do things *wrong*. Suppose we sample quantum\nstates by applying unitaries obtained by the parametrization above, but sample\nthe angles $\\omega, \\phi$, and $\\theta$ from the flat uniform\ndistribution between $[0, 2\\pi)$ (fun fact: there is a measure implicit in\nthis kind of sampling too! It just has a constant value, because each point is\nequally likely to be sampled).\n\n\n\n```python\nimport pennylane as qml\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# set the random seed\nnp.random.seed(42)\n\n# Use the mixed state simulator to save some steps in plotting later\ndev = qml.device('default.mixed', wires=1)\n\n@qml.qnode(dev)\ndef not_a_haar_random_unitary():\n    # Sample all parameters from their flat uniform distribution\n    phi, theta, omega = 2 * np.pi * np.random.uniform(size=3)\n    qml.Rot(phi, theta, omega, wires=0)\n    return qml.state()\n\nnum_samples = 2021\n\nnot_haar_samples = [not_a_haar_random_unitary() for _ in range(num_samples)]\n```\n\nIn order to plot these on the Bloch sphere, we'll need to do one more\nstep, and convert the quantum states into Bloch vectors.\n\n\n\n\n\n```python\nX = np.array([[0, 1], [1, 0]])\nY = np.array([[0, -1j], [1j, 0]])\nZ = np.array([[1, 0], [0, -1]])\n\n# Used the mixed state simulator so we could have the density matrix for this part!\ndef convert_to_bloch_vector(rho):\n    \"\"\"Convert a density matrix to a Bloch vector.\"\"\"\n    ax = np.trace(np.dot(rho, X)).real\n    ay = np.trace(np.dot(rho, Y)).real\n    az = np.trace(np.dot(rho, Z)).real\n    return [ax, ay, az]\n\nnot_haar_bloch_vectors = np.array([convert_to_bloch_vector(s) for s in not_haar_samples])\n```\n\nWith this done, let's find out where our \"uniformly random\" states ended up:\n\n\n\n\n```python\ndef plot_bloch_sphere(bloch_vectors):\n    \"\"\" Helper function to plot vectors on a sphere.\"\"\"\n    fig = plt.figure(figsize=(6, 6))\n    ax = fig.add_subplot(111, projection='3d')\n    fig.subplots_adjust(left=0, right=1, bottom=0, top=1)\n\n    ax.grid(False)\n    ax.set_axis_off()\n    ax.view_init(30, 45)\n    ax.dist = 7\n\n    # Draw the axes (source: https://github.com/matplotlib/matplotlib/issues/13575)\n    x, y, z = np.array([[-1.5,0,0], [0,-1.5,0], [0,0,-1.5]])\n    u, v, w = np.array([[3,0,0], [0,3,0], [0,0,3]])\n    ax.quiver(x, y, z, u, v, w, arrow_length_ratio=0.05, color=\"black\", linewidth=0.5)\n\n    ax.text(0, 0, 1.7, r\"|0\u27e9\", color=\"black\", fontsize=16)\n    ax.text(0, 0, -1.9, r\"|1\u27e9\", color=\"black\", fontsize=16)\n    ax.text(1.9, 0, 0, r\"|+\u27e9\", color=\"black\", fontsize=16)\n    ax.text(-1.7, 0, 0, r\"|\u2013\u27e9\", color=\"black\", fontsize=16)\n    ax.text(0, 1.7, 0, r\"|i+\u27e9\", color=\"black\", fontsize=16)\n    ax.text(0,-1.9, 0, r\"|i\u2013\u27e9\", color=\"black\", fontsize=16)\n\n    ax.scatter(\n        bloch_vectors[:,0], bloch_vectors[:,1], bloch_vectors[:, 2], c='#e29d9e', alpha=0.3\n    )\n\nplot_bloch_sphere(not_haar_bloch_vectors)\n```\n\nYou can see from this plot that even though our parameters were sampled from a\nuniform distribution, there is a noticeable amount of clustering around the poles\nof the sphere. Despite the input parameters being uniform, the output is very\nmuch *not* uniform. Just like the regular sphere, the measure is larger near\nthe equator, and if we just sample uniformly, we won't end up populating that\narea as much. To take that into account we will need to sample from the proper\nHaar measure, and weight the different parameters appropriately.\n\nFor a single qubit, the Haar measure looks much like the case of a sphere,\nminus the radial component. Intuitively, all qubit state vectors have length\n1, so it makes sense that this wouldn't play a role here. The parameter that\nwe will have to weight differently is $\\theta$, and in fact the\nadjustment in measure is identical to that we had to do with the polar axis of\nthe sphere, i.e., $\\sin \\theta$. In order to sample the $\\theta$\nuniformly at random in this context, we must sample from the distribution\n$\\hbox{Pr}(\\theta) = \\sin \\theta$. We can accomplish this by setting up\na custom probability distribution with \n`rv_continuous <https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_continuous.html#scipy.stats.rv_continuous>`__\nin ``scipy``.\n\n\n\n\n```python\nfrom scipy.stats import rv_continuous\n\nclass sin_prob_dist(rv_continuous):\n    def _pdf(self, theta):\n        # The 0.5 is so that the distribution is normalized\n        return 0.5 * np.sin(theta)\n\n# Samples of theta should be drawn from between 0 and pi\nsin_sampler = sin_prob_dist(a=0, b=np.pi)\n\n@qml.qnode(dev)\ndef haar_random_unitary():\n    phi, omega = 2 * np.pi * np.random.uniform(size=2) # Sample phi and omega as normal\n    theta = sin_sampler.rvs(size=1) # Sample theta from our new distribution\n    qml.Rot(phi, theta, omega, wires=0)\n    return qml.state()\n\nhaar_samples = [haar_random_unitary() for _ in range(num_samples)]\nhaar_bloch_vectors = np.array([convert_to_bloch_vector(s) for s in haar_samples])\n\nplot_bloch_sphere(haar_bloch_vectors)\n```\n\nWe see that when we use the correct measure, our qubit states are now\nmuch better distributed over the sphere. Putting this information together,\nwe can now write the explicit form for the single-qubit Haar measure:\n\n\\begin{align}d\\mu_2 = \\sin \\theta d\\theta \\cdot d\\omega \\cdot d\\phi.\\end{align}\n\nShow me more math!\n~~~~~~~~~~~~~~~~~~\n\nWhile we can easily visualize the single-qubit case, this is no longer\npossible when we increase the number of qubits. Regardless, we can still\nobtain a mathematical expression for the Haar measure in arbitrary\ndimensions. In the previous section, we expressed the Haar measure in terms of\na set of parameters that can be used to specify the unitary group\n$U(2)$. Such a parametrization is not unique, and in fact there are\nmultiple ways to *factorize*, or decompose an $N$-dimensional unitary\noperation into a set of parameters.\n\nMany of these parametrizations come to us from the study of photonics.  Here,\narbitrary operations are broken down into elementary operations involving only\na few parameters which correspond directly to parameters of the physical\napparatus used to implement them (beamsplitters and phase shifts). Rather than\nqubits, such operations act on modes, or *qumodes*. They are expressed as\nelements of the $N$-dimensional `special unitary group\n<https://en.wikipedia.org/wiki/Special_unitary_group>`__. This group, written\nas $SU(N)$, is the continuous group consisting of all $N \\times N$\nunitary operations with determinant 1 (essentially like $U(N)$, minus\na potential global phase).\n\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>Elements of $SU(N)$ and $U(N)$ can still be considered as\n    multi-qubit operations in the cases where $N$ is a power of 2, but\n    they must be translated from continuous-variable operations into qubit\n    operations. (In PennyLane, this can be done by feeding the unitaries to\n    the :class:`~.pennylane.QubitUnitary` operation directly. Alternatively,\n    one can use *quantum compilation* to express the operations as a sequence\n    of elementary gates such as Pauli rotations and CNOTs.)</p></div>\n\n.. admonition:: Tip\n\n   If you haven't had many opportunities to work in terms of qumodes, the\n   `Strawberry Fields documentation\n   <https://strawberryfields.ai/photonics/concepts/photonics.html>`__ is a\n   good starting point.\n\nFor example, we saw already above that for $N=2$, we can write\n\n\\begin{align}U(\\phi, \\theta, \\omega) = \\begin{pmatrix} e^{-i(\\phi + \\omega)/2}\n                       \\cos(\\theta/2) & -e^{i(\\phi - \\omega)/2} \\sin(\\theta/2)\n                       \\\\ e^{-i(\\phi - \\omega)/2} \\sin(\\theta/2) & e^{i(\\phi +\n                       \\omega)/2} \\cos(\\theta/2) \\end{pmatrix}.\\end{align}\n\n\nThis unitary can be factorized as follows: \n\n\\begin{align}U(\\phi, \\theta, \\omega) =\n       \\begin{pmatrix}\n         e^{-i\\omega/2} & 0 \\\\ 0 & e^{i\\omega/2}\n       \\end{pmatrix}\n       \\begin{pmatrix}\n         \\cos(\\theta/2) & -\\sin(\\theta/2) \\\\ \\sin(\\theta/2) & \\cos(\\theta/2)\n       \\end{pmatrix}\n      \\begin{pmatrix}\n         e^{-i\\phi/2} & 0 \\\\ 0 & e^{i\\phi/2}\n       \\end{pmatrix}\\end{align}\n\nThe middle operation is a beamsplitter; the other two operations are phase\nshifts.  We saw earlier that for $N=2$, $d\\mu_2 = \\sin\\theta\nd\\theta d\\omega d\\phi$---note how the parameter in the beamsplitter\ncontributes to the measure in a different way than those of the phase\nshifts. As mentioned above, for larger values of $N$ there are multiple\nways to decompose the unitary. Such decompositions rewrite elements in\n$SU(N)$ acting on $N$ modes as a sequence of operations acting\nonly on 2 modes, $SU(2)$, and single-mode phase shifts.  Shown below are\nthree examples [#deGuise2018]_, [#Clements2016]_, [#Reck1994]_:\n\n.. figure:: /demonstrations/haar_measure/unitaries.png\n   :align: center\n   :width: 95%\n\n\nIn these graphics, every wire is a different mode. Every box represents an\noperation on one or more modes, and the number in the box indicates the number\nof parameters.  The boxes containing a ``1`` are simply phase shifts on\nindividual modes. The blocks containing a ``3`` are $SU(2)$ transforms\nwith 3 parameters, such as the $U(\\phi, \\theta, \\omega)$ above. Those\ncontaining a ``2`` are $SU(2)$ transforms on pairs of modes with 2\nparameters, similar to the 3-parameter ones but with $\\omega = \\phi$.\n\nAlthough the decompositions all produce the same set of operations, their\nstructure and parametrization may have consequences in practice.  The first [#deGuise2018]_\nhas a particularly convenient form that leads to a recursive definition\nof the Haar measure. The decomposition is formulated recursively such that an\n$SU(N)$ operation can be implemented by sandwiching an $SU(2)$\ntransformation between two $SU(N-1)$ transformations, like so:\n\n|\n\n.. figure:: /demonstrations/haar_measure/sun.svg\n   :align: center\n   :width: 80%\n\n|\n\nThe Haar measure is then constructed recursively as a product of 3\nterms. The first term depends on the parameters in the first $SU(N-1)$\ntransformation; the second depends on the parameters in the lone $SU(2)$\ntransformation; and the third term depends on the parameters in the other\n$SU(N-1)$ transformation.\n\n$SU(2)$ is the \"base case\" of the recursion---we simply have the Haar measure\nas expressed above.\n\n|\n\n.. figure:: /demonstrations/haar_measure/su2_haar.svg\n   :align: center\n   :width: 25%\n\n|\n\nMoving on up, we can write elements of $SU(3)$ as a sequence of three\n$SU(2)$ transformations. The Haar measure $d\\mu_3$ then consists\nof two copies of $d\\mu_2$, with an extra term in between to take into\naccount the middle transformation.\n\n|\n\n.. figure:: /demonstrations/haar_measure/su3_haar.svg\n   :align: center\n   :width: 80%\n\n|\n\nFor $SU(4)$ and upwards, the form changes slightly, but still follows\nthe pattern of two copies of $d\\mu_{N-1}$ with a term in between.\n\n|\n\n.. figure:: /demonstrations/haar_measure/su4_premerge.svg\n   :align: center\n   :width: 90%\n\n|\n\nFor larger systems, however, the recursive composition allows for some of the\n$SU(2)$ transformations on the lower modes to be grouped. We can take\nadvantage of this and aggregate some of the parameters:\n\n|\n\n.. figure:: /demonstrations/haar_measure/su4_triangle_merge.svg\n   :align: center\n   :width: 100%\n\n|\n\nThis leads to one copy of $d\\mu_{N-1}$, which we'll denote as\n$d\\mu_{N-1}^\\prime$, containing only a portion of the full set of terms\n(as detailed in [#deGuise2018]_, this is called a *coset measure*).\n\n|\n\n.. figure:: /demonstrations/haar_measure/su4_haar.svg\n   :align: center\n   :width: 100%\n\n|\n\nPutting everything together, we have that\n\n\\begin{align}d\\mu_N = d\\mu_{N-1}^\\prime \\times \\sin \\theta_{N-1}\n   \\sin^{2(N-2)}\\left(\\frac{\\theta_{N-1}}{2}\\right) d\\theta_{N-1} d\\omega_{N-1} \\times d\\mu_{N-1}\\end{align}\n\nThe middle portion depends on the value of $N$, and the parameters\n$\\theta_{N-1}$ and $\\omega_{N-1}$ contained in the $(N-1)$'th\n$SU(N)$ transformation. This is thus a convenient, systematic way to\nconstruct the $N$-dimensional Haar measure for the unitary group. As a\nfinal note, even though unitaries can be parametrized in different ways, the\nunderlying Haar measure is *unique*. This is a consequence of it being an\ninvariant measure, as will be shown later.\n\nHaar-random matrices from the $QR$ decomposition\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nNice-looking math aside, sometimes you just need to generate a large number of\nhigh-dimensional Haar-random matrices. It would be very cumbersome to sample\nand keep track of the distributions of so many parameters; furthermore, the\nmeasure above requires you to parametrize your operations in a fixed way.\nThere is a much quicker way to perform the sampling by taking a (slightly\nmodified) `QR decomposition\n<https://en.wikipedia.org/wiki/QR_decomposition>`__ of complex-valued\nmatrices.  This algorithm is detailed in [#Mezzadri2006]_, and consists of the\nfollowing steps:\n\n1. Generate an $N \\times N$ matrix $Z$ with complex numbers $a+bi$\n   where both $a$ and $b$ are normally distributed with mean 0 and variance 1\n   (this is sampling from the distribution known as the *Ginibre ensemble*).\n2. Compute a QR decomposition $Z = QR$.\n3. Compute the diagonal matrix $\\Lambda = \\hbox{diag}(R_{ii}/|R_{ii}|)$.\n4. Compute $Q^\\prime = Q \\Lambda$, which will be Haar-random.\n\n\n\n\n\n\n```python\nfrom numpy.linalg import qr\n\ndef qr_haar(N):\n    \"\"\"Generate a Haar-random matrix using the QR decomposition.\"\"\"\n    # Step 1\n    A, B = np.random.normal(size=(N, N)), np.random.normal(size=(N, N))\n    Z = A + 1j * B\n\n    # Step 2\n    Q, R = qr(Z)\n\n    # Step 3\n    Lambda = np.diag([R[i, i] / np.abs(R[i, i]) for i in range(N)])\n\n    # Step 4\n    return np.dot(Q, Lambda)\n```\n\nLet's check that this method actually generates Haar-random unitaries\nby trying it out for $N=2$ and plotting on the Bloch sphere.\n\n\n\n\n\n```python\n@qml.qnode(dev)\ndef qr_haar_random_unitary():\n    qml.QubitUnitary(qr_haar(2), wires=0)\n    return qml.state()\n\nqr_haar_samples = [qr_haar_random_unitary() for _ in range(num_samples)]\nqr_haar_bloch_vectors = np.array([convert_to_bloch_vector(s) for s in qr_haar_samples])\nplot_bloch_sphere(qr_haar_bloch_vectors)\n```\n\nAs expected, we find our qubit states are distributed uniformly over the\nsphere.  This particular method is what's implemented in packages like\n``scipy``'s `unitary_group\n<https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.unitary_group.html>`__\nfunction.\n\nNow, it's clear that this method works, but it is also important to\nunderstand *why* it works.  Step 1 is fairly straightforward---the base of our\nsamples is a matrix full of complex values chosen from a typical\ndistribution. This isn't enough by itself, since unitary matrices also\nhave constraints---their rows and columns must be orthonormal.\nThese constraints are where step 2 comes in---the outcome of a generic\nQR decomposition consists of an *orthonormal* matrix $Q$, and and upper\ntriangular matrix $R$. Since our original matrix was complex-valued, we end\nup with a $Q$ that is in fact already unitary. But why not stop there? Why\ndo we then perform steps 3 and 4?\n\nSteps 3 and 4 are needed because, while the QR decomposition yields a unitary,\nit is not a unitary that is properly Haar-random. In [#Mezzadri2006]_, it is\nexplained that a uniform distribution over unitary matrices should also yield\na uniform distribution over the *eigenvalues* of those matrices, i.e., every\neigenvalue should be equally likely. Just using the QR decomposition out of\nthe box produces an *uneven* distribution of eigenvalues of the unitaries!\nThis discrepancy stems from the fact that the QR decomposition is not unique.\nWe can take any unitary diagonal matrix $\\Lambda$, and re-express the decomposition\nas $QR = Q\\Lambda \\Lambda^\\dagger R = Q^\\prime R^\\prime$. Step 3 removes this\nredundancy by fixing a $\\Lambda$ that depends on $R$, leading to a unique\nvalue of $Q^\\prime = Q \\Lambda$, and a uniform distribution of eigenvalues.\n\n.. admonition:: Try it!\n\n   Use the ``qr_haar`` function above to generate random unitaries and construct\n   a distribution of their eigenvalues. Then, comment out the lines for steps 3 and\n   4 and do the same---you'll find that the distribution is no longer uniform.\n   Check out reference [#Mezzadri2006]_ for additional details and examples.\n\n\n\nFun (and not-so-fun) facts\n--------------------------\n\nWe've now learned what the Haar measure is, and both an analytical and\nnumerical means of sampling quantum states and unitary operations uniformly at\nrandom. The Haar measure also has many neat properties that play a role in\nquantum computing.\n\nInvariance of the Haar measure\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nEarlier, we showed that the Haar measure is used when integrating functions over\nthe unitary group:\n\n\\begin{align}\\int_{V \\in U(N)} f(V) d\\mu_N(V).\\end{align}\n\nOne of the defining features of the Haar measure is that it is both left and\nright *invariant* under unitary transformations. That is,\n\n\\begin{align}\\int_{V \\in U(N)} f(\\color{red}{W}V) d\\mu_N(V) =  \\int_{V \\in U(N)} f(V\\color{red}{W}) d\\mu_N(V) =  \\int_{V \\in U(N)} f(V) d\\mu_N(V).\\end{align}\n\nThis holds true for *any* other $N\\times N$ unitary $W$! A\nconsequence of such invariance is that if $V$ is Haar-random, then so is\n$V^T,$ $V^\\dagger,$ and any product of another unitary matrix and\n$V$ (where the product may be taken on either side).\n\nAnother consequence of this invariance has to do with the structure of the entries\nthemselves: they must all come from the same distribution. This is because the\nmeasure remains invariant under permutations, since permutations are unitary---\nthe whole thing still has to be Haar random no matter how the entries are ordered,\nso all distributions must be the same.  The specific distribution is complex\nnumbers $a+bi$ where both $a$ and $b$ has mean 0 and variance\n$1/N$ [#Meckes2014]_ (so, much like Ginibre ensemble we used in the QR decomposition\nabove, but with a different variance and constraints due to orthonormality).\n\nConcentration of measure\n~~~~~~~~~~~~~~~~~~~~~~~~\n\nAn unfortunate (although interesting) property of the Haar measure is that it\nsuffers from the phenomenon of `concentration of measure\n<https://en.wikipedia.org/wiki/Concentration_of_measure>`__. Most of the\n\"stuff\" in the space concentrates around a certain area, and this gets worse\nas the size of the system increases. You can see the beginnings of by looking\nat the sphere. For the 3-dimensional sphere, we saw graphically how there is\nconcentration around the equator, and how the measure takes that into account\nwith the additional factor of $\\sin \\theta$. This property becomes\nincreasingly prominent for `higher-dimensional spheres\n<https://en.wikipedia.org/wiki/N-sphere>`__.\n\n.. important::\n\n   The concentration described here is not referring to what we witnessed\n   earlier on, when we sampled quantum states (points on the Bloch sphere)\n   incorrectly and found that they clustered around the poles. However, that\n   is not unrelated. Concentration of measure refers to where the measure\n   itself is concentrated, and which parts of the space should be more heavily\n   weighted. For the case of the sphere, it is the equatorial area, and when\n   we didn't sample properly and take that concentration into account, we\n   obtained an uneven distribution.\n\nLet's consider an $N$-dimensional unit sphere. Points on the sphere, or\nvectors in this space, are parametrized by $N-1$ real coordinates.\nSuppose we have some function $f$ that maps points on that sphere to\nreal numbers. Sample a point $x$ on that sphere from the uniform\nmeasure, and compute the value of $f(x)$. How close do you think the\nresult will be to the mean value of the function, $E[f]$, over the\nentire sphere?\n\nA result called `Levy's lemma\n<https://en.wikipedia.org/wiki/Concentration_of_measure#Concentration_on_the_sphere>`__\n[#Gerken2013]_, [#Hayden2006]_ expresses how likely it is that $f(x)$ is a specific\ndistance away from the mean. It states that, for an $x$ selected\nuniformly at random, the probability that $f(x)$ deviates from\n$E[f]$ by some amount $\\epsilon$ is bounded by:\n\n\\begin{align}\\hbox{Pr}(|f(x) - E[f]| \\ge \\epsilon) \\leq 2 \\exp\\left[-\\frac{N\\epsilon^2}{9\\pi^3 \\eta^2}\\right].\\end{align}\n\nA constraint on the function $f$ is that it must be `Lipschitz\ncontinuous <https://en.wikipedia.org/wiki/Lipschitz_continuity>`__, where\n$\\eta$ is the *Lipschitz constant* of the function. The important aspect\nhere is the likelihood of deviating significantly from the mean by an amount\n$\\epsilon$ decreases exponentially with $\\epsilon.$ Furthermore,\nincreasing the dimension $N$ also makes the deviation exponentially less\nlikely.\n\nNow, this result seems unrelated to quantum states---it concerns higher-\ndimensional spheres. However, recall that a quantum state vector is a complex\nvector whose squared values sum to 1, similar to vectors on a sphere. If you\n\"unroll\" a quantum state vector of dimension $N = 2^n$ by stacking its\nreal and complex parts, you end with a vector of length $2 \\cdot 2^{n}$\nwhich ends up behaving just like a unit vector on the sphere in this\ndimension. Given that measure concentrates on spheres, and quantum state\nvectors can be converted to vectors on spheres, functions on random quantum\nstates will also demonstrate concentration.\n\nThis is bad news! To do useful things in quantum computing, we need a lot of\nqubits. But the more qubits we have, the more our randomly sampled states will\nlook the same (specifically, random states will concentrate around the\nmaximally entangled state [#Hayden2006]_). This has important consequences for\nnear-term algorithms (as detailed in the next section), and any algorithm that\ninvolves uniform sampling of quantum states and operations.\n\nHaar measure and barren plateaus\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nSuppose you are venturing out to solve a new problem using an algorithm such\nas the :doc:`variational quantum eigensolver </demos/tutorial_vqe>`. A\ncritical component of such methods is the choice of :doc:`variational ansatz\n</glossary/circuit_ansatz>`. Having now learned a bit about the properties of\nthe Haar measure, you may think it would make sense to use this for the\nparametrization. Variational ansaetze are, after all, parametrized quantum\ncircuits, so why not choose an ansatz that corresponds directly to a\nparametrization for Haar-random unitaries?  The initial parameter selection\nwill give you a state in the Hilbert space uniformly at random. Then, since\nthis ansatz spans the entire Hilbert space, you're guaranteed to be able to\nrepresent the target ground state with your ansatz, and it should be able to\nfind it with no issue ... right?\n\nUnfortunately, while such an ansatz is extremely *expressive* (i.e., it is\ncapable of representing any possible state), these ansaetze actually suffer\nthe most from the barren plateau problem [#McClean2018]_, [#Holmes2021]_.\n:doc:`Barren plateaus </demos/tutorial_barren_plateaus>` are regions in the\ncost landscape of a parametrized circuit where both the gradient and its\nvariance approach 0, leading the optimizer to get stuck in a local minimum.\nThis was explored recently in the work of [#Holmes2021]_, wherein closeness to\nthe Haar measure was actually used as a metric for expressivity. The closer\nthings are to the Haar measure, the more expressive they are, but they are\nalso more prone to exhibiting barren plateaus.\n\n\n.. figure:: /demonstrations/haar_measure/holmes-costlandscapes.png\n   :align: center\n   :width: 50%\n\n   Image source: [#Holmes2021]_. A highly expressive ansatz that can access\n   much of the space of possible unitaries (i.e., an ansatz capable of\n   producing unitaries in something close to a Haar-random manner) is very\n   likely to have flat cost landscapes and suffer from the barren plateau\n   problem.\n\nIt turns out that the types of ansaetze know as *hardware-efficient ansaetze*\nalso suffer from this problem if they are \"random enough\" (this notion will be\nformalized in a future demo). It was shown in [#McClean2018]_ that this is a\nconsequence of the concentration of measure phenomenon described above. The\nvalues of gradients and variances can be computed for classes of circuits on\naverage by integrating with respect to the Haar measure, and it is shown that\nthese values decrease exponentially in the number of qubits, and thus huge\nswaths of the cost landscape are simply and fundamentally flat.\n\nConclusion\n----------\n\nThe Haar measure plays an important role in quantum computing---anywhere\nyou might be dealing with sampling random circuits, or averaging over\nall possible unitary operations, you'll want to do so with respect\nto the Haar measure.\n\nThere are two important aspects of this that we have yet to touch upon,\nhowever. The first is whether it is efficient to sample from the Haar measure---given\nthat the number of parameters to keep track of is exponential in the\nnumber of qubits, certainly not. But a more interesting question is do we\n*need* to always sample from the full Haar measure?  The answer to this is\n\"no\" in a very interesting way. Depending on the task at hand, you may be able\nto take a shortcut using something called a *unitary design*. In an upcoming\ndemo, we will explore the amazing world of unitary designs and their\napplications!\n\nReferences\n----------\n\n.. [#NandC2000]\n\n    M. A. Nielsen, and I. L. Chuang (2000) \"Quantum Computation and Quantum Information\",\n    Cambridge University Press.\n\n.. [#deGuise2018]\n\n    H. de Guise, O. Di Matteo, and L. L. S\u00e1nchez-Soto. (2018) \"Simple factorization\n    of unitary transformations\", `Phys. Rev. A 97 022328\n    <https://journals.aps.org/pra/abstract/10.1103/PhysRevA.97.022328>`__.\n    (`arXiv <https://arxiv.org/abs/1708.00735>`__)\n\n.. [#Clements2016]\n\n    W. R. Clements, P. C. Humphreys, B. J. Metcalf, W. S. Kolthammer, and\n    I. A. Walmsley (2016) \u201cOptimal design for universal multiport\n    interferometers\u201d, \\ `Optica 3, 1460\u20131465\n    <https://www.osapublishing.org/optica/fulltext.cfm?uri=optica-3-12-1460&id=355743>`__.\n    (`arXiv <https://arxiv.org/abs/1603.08788>`__)\n\n.. [#Reck1994]\n\n   M. Reck, A. Zeilinger, H. J. Bernstein, and P. Bertani (1994) \u201cExperimental\n   realization of any discrete unitary operator\u201d, `Phys. Rev. Lett.73, 58\u201361\n   <https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.73.58>`__.\n\n.. [#Mezzadri2006]\n\n    F. Mezzadri (2006) \"How to generate random matrices from the classical compact groups\".\n    (`arXiv <https://arxiv.org/abs/math-ph/0609050>`__)\n\n.. [#Meckes2014]\n\n    E. Meckes (2019) `\"The Random Matrix Theory of the Classical Compact Groups\"\n    <https://case.edu/artsci/math/esmeckes/Haar_book.pdf>`_, Cambridge University Press.\n\n.. [#Gerken2013]\n\n    M. Gerken (2013) \"Measure concentration: Levy's Lemma\"\n    (`lecture notes <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.679.2560>`__).\n\n\n.. [#Hayden2006]\n\n    P. Hayden, D. W. Leung, and A. Winter (2006) \"Aspects of generic\n    entanglement\", `Comm. Math. Phys. Vol. 265, No. 1, pp. 95-117\n    <https://link.springer.com/article/10.1007%2Fs00220-006-1535-6>`__.\n    (`arXiv <https://arxiv.org/abs/quant-ph/0407049>`__)\n\n.. [#McClean2018]\n\n    J. R. McClean, S. Boixo, V. N. Smelyanskiy, R. Babbush, and H. Neven\n    (2018) \"Barren plateaus in quantum neural network training\n    landscapes\", `Nature Communications, 9(1)\n    <http://dx.doi.org/10.1038/s41467-018-07090-4>`__.\n    (`arXiv <https://arxiv.org/abs/1803.11173>`__)\n\n.. [#Holmes2021]\n\n    Z. Holmes, K. Sharma, M. Cerezo, and P. J. Coles (2021) \"Connecting ansatz\n    expressibility to gradient magnitudes and barren plateaus\". (`arXiv\n    <https://arxiv.org/abs/2101.02138>`__)\n\n\n\n\n", "meta": {"hexsha": "72a06c2c0071ac42ae8c0677070e148ba15044f2", "size": 48381, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "etc/tutorial_haar_measure.ipynb", "max_stars_repo_name": "String137/PQC", "max_stars_repo_head_hexsha": "dfadef9cff115679d1987adb492cade5be72b823", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-13T12:27:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-13T12:27:51.000Z", "max_issues_repo_path": "etc/tutorial_haar_measure.ipynb", "max_issues_repo_name": "String137/PQC", "max_issues_repo_head_hexsha": "dfadef9cff115679d1987adb492cade5be72b823", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "etc/tutorial_haar_measure.ipynb", "max_forks_repo_name": "String137/PQC", "max_forks_repo_head_hexsha": "dfadef9cff115679d1987adb492cade5be72b823", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.7026143791, "max_line_length": 183, "alphanum_fraction": 0.5769826998, "converted": true, "num_tokens": 9556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20946968133032526, "lm_q2_score": 0.16026603032235007, "lm_q1q2_score": 0.03357087429969891}}
{"text": "```python\nfrom IPython.display import HTML\nfrom IPython.display import display\n\ndisplay(HTML(\"<style>.container { width:70% !important; }</style>\"))\n```\n\n\n<style>.container { width:70% !important; }</style>\n\n\n\n```python\n%matplotlib inline\nimport numpy as np, scipy, scipy.stats as stats, pandas as pd, matplotlib.pyplot as plt, seaborn as sns\nimport statsmodels, statsmodels.api as sm\nimport sympy, sympy.stats\nimport pymc3 as pm\nimport daft\n\npd.set_option('display.max_columns', 500)\npd.set_option('display.width', 1000)\n# pd.set_option('display.float_format', lambda x: '%.2f' % x)\nnp.set_printoptions(edgeitems=10)\nnp.set_printoptions(linewidth=1000)\nnp.set_printoptions(suppress=True)\nnp.core.arrayprint._line_width = 180\n\nSEED = 42\nnp.random.seed(SEED)\n\nsns.set()\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n```\n\nThis blog post is part of the [Series: Monte Carlo Methods](https://weisser-zwerg.dev/posts/series-monte-carlo-methods/).\n\nYou can find this blog post on [weisser-zwerg.dev](https://weisser-zwerg.dev/posts/monte-carlo-fundamental-concepts/) or on [github](https://github.com/cs224/blog-series-monte-carlo-methods) as either [html](https://rawcdn.githack.com/cs224/blog-series-monte-carlo-methods/main/0010-fundamental-concepts.html) or via [nbviewer](https://nbviewer.jupyter.org/github/cs224/blog-series-monte-carlo-methods/blob/main/0010-fundamental-concepts.ipynb?flush_cache=true).\n\n# Monte Carlo Fundamental Concepts\n\n<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Boundary-between-statistics-and-machine-learning-/-AI\" data-toc-modified-id=\"Boundary-between-statistics-and-machine-learning-/-AI-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Boundary between statistics and machine learning / AI</a></span></li><li><span><a href=\"#Monte-Carlo-sampling-methodology\" data-toc-modified-id=\"Monte-Carlo-sampling-methodology-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Monte Carlo sampling methodology</a></span><ul class=\"toc-item\"><li><span><a href=\"#A-word-of-caution-about-the-picture-of-&quot;Bayes-updating&quot;\" data-toc-modified-id=\"A-word-of-caution-about-the-picture-of-&quot;Bayes-updating&quot;-2.1\"><span class=\"toc-item-num\">2.1&nbsp;&nbsp;</span>A word of caution about the picture of \"Bayes updating\"</a></span></li></ul></li><li><span><a href=\"#Statistical-Models\" data-toc-modified-id=\"Statistical-Models-3\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>Statistical Models</a></span><ul class=\"toc-item\"><li><span><a href=\"#Quality-of-a-model:--model-comparison,-model-selection,-model-averaging\" data-toc-modified-id=\"Quality-of-a-model:--model-comparison,-model-selection,-model-averaging-3.1\"><span class=\"toc-item-num\">3.1&nbsp;&nbsp;</span>Quality of a model:  model comparison, model selection, model averaging</a></span></li></ul></li><li><span><a href=\"#How-to-construct-models:-keep-the-Bayes'-theorem-and-the-law-of-total-probability-(extending-the-conversation)-always-in-mind\" data-toc-modified-id=\"How-to-construct-models:-keep-the-Bayes'-theorem-and-the-law-of-total-probability-(extending-the-conversation)-always-in-mind-4\"><span class=\"toc-item-num\">4&nbsp;&nbsp;</span>How to construct models: keep the Bayes' theorem and the law of total probability (extending the conversation) always in mind</a></span><ul class=\"toc-item\"><li><span><a href=\"#Bayes'-theorem\" data-toc-modified-id=\"Bayes'-theorem-4.1\"><span class=\"toc-item-num\">4.1&nbsp;&nbsp;</span>Bayes' theorem</a></span></li><li><span><a href=\"#Law-of-total-probability-(extending-the-conversation)\" data-toc-modified-id=\"Law-of-total-probability-(extending-the-conversation)-4.2\"><span class=\"toc-item-num\">4.2&nbsp;&nbsp;</span>Law of total probability (extending the conversation)</a></span></li></ul></li><li><span><a href=\"#What-is-the-&quot;right&quot;-representation-of-(multi-dimensional)-probability-distributions?\" data-toc-modified-id=\"What-is-the-&quot;right&quot;-representation-of-(multi-dimensional)-probability-distributions?-5\"><span class=\"toc-item-num\">5&nbsp;&nbsp;</span>What is the \"right\" representation of (multi-dimensional) probability distributions?</a></span></li><li><span><a href=\"#Operations-on-probability-distributions:-marginalization-and-conditional-probability\" data-toc-modified-id=\"Operations-on-probability-distributions:-marginalization-and-conditional-probability-6\"><span class=\"toc-item-num\">6&nbsp;&nbsp;</span>Operations on probability distributions: marginalization and conditional probability</a></span></li><li><span><a href=\"#Calculations-with-random-variables:-convolutions-and-other-nasty-stuff\" data-toc-modified-id=\"Calculations-with-random-variables:-convolutions-and-other-nasty-stuff-7\"><span class=\"toc-item-num\">7&nbsp;&nbsp;</span>Calculations with random variables: convolutions and other nasty stuff</a></span></li><li><span><a href=\"#Density-Estimation\" data-toc-modified-id=\"Density-Estimation-8\"><span class=\"toc-item-num\">8&nbsp;&nbsp;</span>Density Estimation</a></span></li><li><span><a href=\"#The-algorithm-has-to-always-perform-the-same-heavy-lifting:-there-is-no-ancestral-sampling\" data-toc-modified-id=\"The-algorithm-has-to-always-perform-the-same-heavy-lifting:-there-is-no-ancestral-sampling-9\"><span class=\"toc-item-num\">9&nbsp;&nbsp;</span>The algorithm has to always perform the same heavy lifting: there is no ancestral sampling</a></span></li><li><span><a href=\"#Appendix\" data-toc-modified-id=\"Appendix-10\"><span class=\"toc-item-num\">10&nbsp;&nbsp;</span>Appendix</a></span><ul class=\"toc-item\"><li><span><a href=\"#Examples-of-mixed-discrete-continuous-probability-functions\" data-toc-modified-id=\"Examples-of-mixed-discrete-continuous-probability-functions-10.1\"><span class=\"toc-item-num\">10.1&nbsp;&nbsp;</span>Examples of mixed discrete continuous probability functions</a></span><ul class=\"toc-item\"><li><span><a href=\"#Two-independent-coin-tosses\" data-toc-modified-id=\"Two-independent-coin-tosses-10.1.1\"><span class=\"toc-item-num\">10.1.1&nbsp;&nbsp;</span>Two independent coin tosses</a></span></li><li><span><a href=\"#Two-component-mixture-model\" data-toc-modified-id=\"Two-component-mixture-model-10.1.2\"><span class=\"toc-item-num\">10.1.2&nbsp;&nbsp;</span>Two component mixture model</a></span></li></ul></li></ul></li></ul></div>\n\n## Boundary between statistics and machine learning / AI\n\nOnly very recently I found the work of 2010 [Turing Award](https://en.wikipedia.org/wiki/Turing_Award) winner [Leslie Valiant](https://en.wikipedia.org/wiki/Leslie_Valiant). In his book [Probably Approximately Correct](https://www.amazon.com/Probably-Approximately-Correct-Algorithms-Prospering/dp/0465060722/) he defines the two concepts **theoryful** and **theoryless**. This would be the place where I would draw the line between statistics and machine learning.\n\nTheoryful: a human has to provide a model and there may be some data that helps to tune the model. A good example would be Newtonian motion of the planets around the sun where Newton's laws provide the model and the data helps to pinpoint the [gravitational constant](https://en.wikipedia.org/wiki/Gravitational_constant).\n\nTheoryless: you take a very generic algorithm and a lot of data and the algorithm figures out the rest. A good example would be a [multilayer perceptron](https://en.wikipedia.org/wiki/Multilayer_perceptron) and pictures of objects, where the algorithm learns via data to identify the objects. The same multilayer perceptron architecture could be used to pilot a self-driving car.\n\n## Monte Carlo sampling methodology\n\nThe general Monte Carlo sampling methodology relies on 2 ingredients:\n* The model (a total/joint probability density function)\n* A sampling algorithm, where there are in principle only 2 core building blocks:\n    * [Importance Sampling](https://en.wikipedia.org/wiki/Importance_sampling) and its variations / synonyms like Sequential Importance Sampling (SIS), Sequential Monte Carlo (SMC), Particle Filters, ...\n    * [Markov chain Monte Carlo (MCMC)](https://en.wikipedia.org/wiki/Markov_chain_Monte_Carlo) and its variations like Metropolis-Hastings (MH), Hamiltonian (or Hybrid) Monte Carlo (HMC, NUTS), Gibbs sampling, ...\n\nThe construction of sampling algorithms based on fine-grained composable abstractions\n([FCA](https://web.archive.org/web/20130117175652/http://blog.getprismatic.com/blog/2012/4/5/software-engineering-at-prismatic.html)) will be the main focus of this blog post series.\n\nIn the case of Importance Sampling, you could argue that there is not only a single model, but a sequence of related models that form a \"bridge\" from something simple to the target model of interest. But we will get there in the course of this blog post series.\n\n### A word of caution about the picture of \"Bayes updating\"\n\nInitially, when I started to read about the Bayesian method of statistics and its inference methodology, I often heard the term [Bayes updating](https://statswithr.github.io/book/the-basics-of-bayesian-statistics.html#bayes-updating). The picture that this terminology evoked in me was that there is a sequential process of taking a prior, a likelihood for a single event and then perform \"Bayes updating\" to receive the posterior, with that posterior becoming the new prior for the next data-point from where the process continuous until all data-items are consumed.\n\n$\n\\displaystyle\n\\begin{array}{rcl}\nd_i&\\in&\\{d_1, d_2, ..., d_N\\}\\\\\np(d_1,\\theta)&=&p_0(\\theta)\\cdot p(d_1\\,|\\,\\theta)\\\\\np(\\theta\\,|\\,d_1)&=&\\displaystyle \\frac{p(d_1,\\theta)}{\\int p(d_1,\\theta)\\,\\mathrm{d}\\theta}=p_1(\\theta)\\\\\np(d_2,\\theta)&=&p_1(\\theta)\\cdot p(d_2\\,|\\,\\theta)\\\\\np(\\theta\\,|\\,d_2)&=&\\displaystyle \\frac{p(d_2,\\theta)}{\\int p(d_2,\\theta)\\,\\mathrm{d}\\theta}=p_2(\\theta)\\\\\n&...&\\\\\n&=&p_N(\\theta)\n\\end{array}\n$\n\nWhile this picture is of course correct and is what you would do if you calculated the posterior manually by using (for example) [conjugate priors](https://en.wikipedia.org/wiki/Conjugate_prior), this picture prevented me from understanding what is going on in especially MCMC methods, but also in SMC methods and I found it much more useful to think of the model as the (immutable &ndash; without updating) total joint probability including all data-points, e.g.:\n\n$\n\\displaystyle\n\\begin{array}{rcl}\np(d_1,d_2,...,d_N,\\theta)&=&p_0(\\theta)\\cdot p(d_1\\,|\\,\\theta)\\cdot p(d_2\\,|\\,\\theta)\\cdot ... \\cdot p(d_N\\,|\\,\\theta)\\\\\n\\end{array}\n$\n\nThat is all you need for the main Monte Carlo sampling methods, because they only depend on an unnormalized probability density function and if you take $p(d_1=d_1,d_2=d_2,...,d_N=d_N,\\theta)$ (you simply take the total joint probability function and [partially apply](https://en.wikipedia.org/wiki/Partial_application) its data arguments so that you receive a function of the set of unknown parameters $\\theta$ alone, e.g. $f(\\theta)=p(d_1=d_1,d_2=d_2,...,d_N=d_N,\\theta)$) then you are ready to go, because $f(\\theta)\\propto p(\\theta\\,|\\,d_1=d_1,d_2=d_2,...,d_N=d_N)=\\frac{f(\\theta)}{Z}$ where $Z$ (the so called [partition function](https://en.wikipedia.org/wiki/Partition_function_(mathematics))) is independent from $\\theta$ and therefore a constant for the concrete data-set you're looking at.\n\n## Statistical Models\n\nIn (Bayesian) statistics a model is basically a **total** [probability mass function](https://en.wikipedia.org/wiki/Probability_mass_function) (PMF; in the discrete case) or a [probability density function](https://en.wikipedia.org/wiki/Probability_density_function) (PDF; in the continuous case). It comes often in the form of a [probabilistic graphical model](https://en.wikipedia.org/wiki/Graphical_model) (PGM; also see [Bayesian hierarchical model](https://en.wikipedia.org/wiki/Bayesian_hierarchical_modeling)). As an example, you see below the graphical representation of multiple coin tosses using the same coin:\n\n\n```python\npgm = daft.PGM(grid_unit=3.0, node_unit=1.5)\n\npgm.add_node(\"theta\", r\"$\\theta$\", 0, 2)\npgm.add_node(\"d\", r\"$d_i$\", 0, 1, observed=True)\npgm.add_plate([-0.5, 0.5, 1.0, 1.0], label=r\"$i = 1, \\cdots, N$\")#, shift=-0.1\n\npgm.add_edge(\"theta\", \"d\")\n\npgm.render(dpi=100);\n```\n\nIn standard mathematical notation this would be:\n\n$\\displaystyle\n\\begin{array}{rcl}\np(\\theta) &=& \\mathrm{Beta}(\\alpha=1,\\beta=1) \\\\\np(X_i=d_i\\,|\\,\\theta) &=& \\mathrm{Bernoulli}(X_i=d_i;p=\\theta) \\\\\n\\displaystyle p(X_1=d_1, X_2 = d_2, ..., X_n = d_n, \\theta)&=& \\displaystyle p(\\theta) \\cdot\\prod_{i=1}^N p(X_i=d_i\\,|\\,\\theta)\n\\end{array}\n$\n\nWhere on the left hand side you have the total probability and on the right hand side you have the prior probability $p(\\theta)$ (here given as a [Beta distribution](https://en.wikipedia.org/wiki/Beta_distribution)) multiplied by the [conditional probabilities](https://en.wikipedia.org/wiki/Conditional_probability) $p(X_i=d_i\\,|\\,\\theta)$ (here given as a [Bernoulli distribution](https://en.wikipedia.org/wiki/Bernoulli_distribution)). The important point to remember is **YOU NEED THE TOTAL PROBABILITY FUNCTION**. How you get it does not matter. The total probability function is a **scalar function**, e.g. once you provide all arguments you get a scalar.\n\nFor pure continuous probability density functions and pure discrete probability mass functions this is straight forward. In the pure continuous case you typically have a function like a product of Gauss/Normal:\n$f(x_1,x_2;\\mu,\\sigma)=\\frac{1}{\\sqrt{2\\pi}\\sigma}e^{-\\frac{1}{2}\\frac{(x_1-\\mu)^2}{\\sigma^2} }\\frac{1}{\\sqrt{2\\pi}\\sigma}e^{-\\frac{1}{2}\\frac{(x_2-\\mu)^2}{\\sigma^2} }$. In the pure discrete case, you get a multi-dimensional array like for two dice rolls:\n\n\n```python\nA = sympy.ones(6,6)/36\nA\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36}\\\\\\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36}\\\\\\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36}\\\\\\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36}\\\\\\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36}\\\\\\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36} & \\frac{1}{36}\\end{matrix}\\right]$\n\n\n\nFor mixed cases I often got confused and therefore I elaborated two examples in painstaking detail in the appendix:\n* a model for [two independent coin tosses](#Two-independent-coin-tosses) and \n* a [two-component mixture model](#Two-component-mixture-model) with two observations.\n\n### Quality of a model:  model comparison, model selection, model averaging\n\nWhile this topic is beyond the scope of this blog post series, I nevertheless wanted to mention it. Once you have several models that are supposed to describe the same observations how do you then decide which model is actually the \"best\" model?\n\nThe landmark rule is that a model is only as good as it is able to describe/predict future/unseen data-points. An approximation of that characteristic can be obtained via [cross-validation](https://en.wikipedia.org/wiki/Cross-validation_(statistics%29), where one variant is [leave-one-out cross-validation](https://en.wikipedia.org/wiki/Cross-validation_(statistics%29#Leave-one-out_cross-validation) (LOOCV). You can either apply this directly or use some approximation like an [information criterion](https://docs.displayr.com/wiki/Information_Criteria). In \"[Statistical Rethinking](https://www.amazon.com/-/de/dp/036713991X): A Bayesian Course with Examples in R and STAN\" in chapter 7. \"Ulysses' Compass\" Richard McElreath proposes to use [Pareto-Smoothed Importance Sampling Cross-Validation](https://arxiv.org/abs/1507.02646) (PSIS) or the [Widely Applicable Information Criterion](https://en.wikipedia.org/wiki/Watanabe%E2%80%93Akaike_information_criterion) (WAIC). He adds a word of caution, though: [Deviance](https://en.wikipedia.org/wiki/Deviance_(statistics%29) is an assessment of predictive accuracy, not of truth!\n\nJohn Kruschke proposes in \"[Doing Bayesian Data Analysis](https://www.amazon.com/-/de/dp/0124058884/): A Tutorial with R, JAGS, and Stan\" to use the [Bayes factor](https://en.wikipedia.org/wiki/Bayes_factor) (see for example my earlier blog post: [Model Comparison via Bayes Factor](https://weisser-zwerg.dev/posts/model-comparison-via-bayes-factor/)) or to create a mixture model out of the different competing (sub-)models and then simply apply the machinery of the Monte Carlo sampling methodology to get probabilities for each sub-model as $p_1, p_2, ..., p_M$. The idea then is to say that the model with the highest probability describes the data best. This approach is also the basis for [model averaging](https://en.wikipedia.org/wiki/Ensemble_learning#Bayesian_model_averaging) to create a new and better model by simply using this mixture model for your predictions.\n\n## How to construct models: keep the Bayes' theorem and the law of total probability (extending the conversation) always in mind\n\n### Bayes' theorem \n\n$\n\\displaystyle\np(x,y)=p(y|x)p(x)=p(x|y)p(y)\n$\n\nThis is how you typically construct ([generative](https://en.wikipedia.org/wiki/Generative_model)) models. You basically say: if I knew $x$ then knowing $y$ would be simple. Let's take a physical example like throwing a ball. In a vacuum the trajectory of the ball would be a parabola. Under realistic conditions you have wind and other disturbances. But if you say, if I know where the ball measured by location $x$ (a 3 dimensional vector) was at $t=t_0$ then I could tell where the ball would be at $t=t_1$: \n\n$\n\\displaystyle\n\\begin{array}{rcl}\nx_1& = & x_0+v(t_1-t_0)+(g/2)(t_1-t_0)^2+\\varepsilon_m;\\quad\\text{with }\\varepsilon_m\\sim\\mathcal{N}(0,\\sigma_m)\\\\\n\\Rightarrow p(x_1\\,|\\,x_0) & = &\\mathcal{N}(x_1; x_0+v(t_1-t_0)+(g/2)(t_1-t_0)^2,\\sigma_m)\n\\end{array}\n$\n\nIf you then in addition say that at time $t_0$ the ball was roughly at $\\mu_0+\\varepsilon_l$ with $\\varepsilon_l\\sim\\mathcal{N}(0,\\sigma_l)$, e.g. $p(x_0) = \\mathcal{N}(x_0; \\mu_0,\\sigma_l)$ then you can tell the probability distribution of $p(x_1)$ by:\n\n$\n\\displaystyle\n\\begin{array}{rcl}\np(x_0,x_1) &=& p(x_0)\\cdot p(x_1\\,|\\,x_0) = \\mathcal{N}(x_0; \\mu_0,\\sigma_l)\\cdot\\mathcal{N}(x_1; x_0+v(t_1-t_0)+(g/2)(t_1-t_0)^2,\\sigma_m)\\\\\np(x_1)&=&\\int p(x_0,x_1)\\mathrm{d}x_0\n\\end{array}\n$\n\n### Law of total probability (extending the conversation)\n\nInitially, when I saw the [law of total probability](https://en.wikipedia.org/wiki/Law_of_total_probability) for the first time I neglected it, because it looks like redundant to the Bayes' theorem:\n\n$\np(x)=\\int p(x\\,|\\,y)\\cdot p(y)\\,\\mathrm{d}y\n$\n\nI only learned to appreciate this law really when reading chapter 1.3.6 \"The Law of Total Probability\" in [Causal Inference in Statistics - A Primer](https://www.amazon.com/Causal-Inference-Statistics-Judea-Pearl/dp/1119186846) by Judea Pearl ([Turing Award](https://en.wikipedia.org/wiki/Turing_Award) winner 2011), Madelyn Glymour and Nicholas P. Jewell. There they also presented it under different synonymous names like \"the law of alternatives\" or \"extending the conversation\". In the book they call it \"conditionalizing on y\", but the term \"extending the conversation\" was what stuck with me.\n\nSometimes you just don't know how to get to $p(x)$, but if you knew $y$ you also would know how to get to $x$, e.g. you know $p(x\\,|\\,y)$. You're \"extending the conversation\" to include $y$ in addition to $x$. And often getting to a $p(y)$ is also possible.\n\nIt is basically the reverse idea from above in the example with the motion of the ball. If you just said I want to know $p(x_1)$ I would not know how to get there, but if you introduce $p(x_1\\,|\\,x_0)$ this opens up the path for a recursive calculation to the point where the ball was thrown and at that point you either know the position exactly, e.g. $p(x)=\\delta(x = x_\\text{start})$ (where the $\\delta$ is the [Dirac delta](https://en.wikipedia.org/wiki/Dirac_delta_function)) or you give it some uncertainty, e.g. $p(x)=\\mathcal{N}(x; x_\\text{start},\\sigma_l)$. Eitherway, you can construct a generative model.\n\n## What is the \"right\" representation of (multi-dimensional) probability distributions?\n\nThat is another point that took me some time to digest. The names like probability-density-function (PDF) or probability-mass-function (PMF) suggest a mathematical form like a function. The typical example is the Gauss bell shape:\n\n\n```python\nplt.figure(figsize=(6, 3), dpi=80, facecolor='w', edgecolor='k')\nax = plt.subplot(1, 1, 1)\nx = np.linspace(-3.0,3.0,100)\ny = stats.norm(0,1).pdf(x)\nax.plot(x,y);\n```\n\nIn this case the probability density function can be given as a mathematical function:\n\n$\\displaystyle\n\\frac{1}{\\sqrt{2\\pi}\\sigma}e^{- \\frac{\\left(x - \\mu\\right)^{2}}{2 \\sigma^{2}}}\n$\n\nBut in most cases that is not possible. So what should you do then?\n\nI cannot remember anymore in which source I've read it, but the author said that for probability distributions the \"right\" representation might actually be collections of samples.\n\nLet's look at a toy example. We sample 1000 values from a normal distribution with mean 0 and standard deviation 1. Then we act as if we would only know that the samples are drawn from a normal distribution, but with unknown $\\mu$ and $\\sigma$. In PyMC3 this example looks like this:\n\n\n```python\nsamples = stats.norm(0,1).rvs([1000])\n\nwith pm.Model() as model:\n    mu = pm.Normal(\"mu\", 0.0, 10.0)\n    sigma = pm.Gamma('sigma', alpha=3.0, beta=1.0)\n    x = pm.Normal(\"x\", mu=mu, sigma=sigma, observed=samples)\n    trace = pm.sample(return_inferencedata=True)\n```\n\n    Auto-assigning NUTS sampler...\n    Initializing NUTS using jitter+adapt_diag...\n    Multiprocess sampling (4 chains in 4 jobs)\n    NUTS: [sigma, mu]\n\n\n\n\n<div>\n    <style>\n        /* Turns off some styling */\n        progress {\n            /* gets rid of default border in Firefox and Opera. */\n            border: none;\n            /* Needs to be in here for Safari polyfill so background images work as expected. */\n            background-size: auto;\n        }\n        .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {\n            background: #F44336;\n        }\n    </style>\n  <progress value='8000' class='' max='8000' style='width:300px; height:20px; vertical-align: middle;'></progress>\n  100.00% [8000/8000 00:01<00:00 Sampling 4 chains, 0 divergences]\n</div>\n\n\n\n    Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 2 seconds.\n\n\nJust as a reminder and to make the link to what we said above (about the model) more clear, let's be explicit and give the probability density function in sympy for two data-points instead of the 1000. All that PyMC3 does is to construct such a total joint probability density function and evaluate it at the given data-points. So in our example $x_1$ and $x_2$ are given and $\\mu$ and $\\sigma$ are \"free\" variables.\n\nAs another remark: the [Gamma distribution](https://en.wikipedia.org/wiki/Gamma_distribution) is sometimes parametrized via $\\alpha, \\beta$ and sometimes via $k, \\theta$: $\\alpha = k; \\beta=1/\\theta$\n\n\n```python\nsmu, sx = sympy.symbols(r'\\mu x')\nsx1, sx2 = sympy.symbols(r'x1:3')\nssigma = sympy.Symbol(\"\\sigma\", positive=True)\n\nprior_mu = sympy.stats.crv_types.NormalDistribution(0, 10).pdf(smu)\nprior_sigma = sympy.stats.crv_types.GammaDistribution(3, 1).pdf(ssigma)\nlikelihood = sympy.stats.crv_types.NormalDistribution(smu, ssigma).pdf(sx1)*sympy.stats.crv_types.NormalDistribution(smu, ssigma).pdf(sx2)\ntotal = sympy.UnevaluatedExpr(prior_mu)*sympy.UnevaluatedExpr(prior_sigma)*sympy.UnevaluatedExpr(likelihood)\nsympy.Matrix([prior_mu, prior_sigma, likelihood])\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\frac{\\sqrt{2} e^{- \\frac{\\mu^{2}}{200}}}{20 \\sqrt{\\pi}}\\\\\\frac{\\sigma^{2} e^{- \\sigma}}{2}\\\\\\frac{e^{- \\frac{\\left(- \\mu + x_{1}\\right)^{2}}{2 \\sigma^{2}}} e^{- \\frac{\\left(- \\mu + x_{2}\\right)^{2}}{2 \\sigma^{2}}}}{2 \\pi \\sigma^{2}}\\end{matrix}\\right]$\n\n\n\n\n```python\ntotal\n```\n\n\n\n\n$\\displaystyle \\frac{\\sqrt{2} e^{- \\frac{\\mu^{2}}{200}}}{20 \\sqrt{\\pi}} \\frac{\\sigma^{2} e^{- \\sigma}}{2} \\frac{e^{- \\frac{\\left(- \\mu + x_{1}\\right)^{2}}{2 \\sigma^{2}}} e^{- \\frac{\\left(- \\mu + x_{2}\\right)^{2}}{2 \\sigma^{2}}}}{2 \\pi \\sigma^{2}}$\n\n\n\nPyMC3 created a trace object containing samples of the \"free\"/unknown variables. We can look at them as follows:\n\n\n```python\ntrace_df = trace['posterior'].to_dataframe()\ntrace_df\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>mu</th>\n      <th>sigma</th>\n    </tr>\n    <tr>\n      <th>chain</th>\n      <th>draw</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">0</th>\n      <th>0</th>\n      <td>-0.025535</td>\n      <td>0.995429</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>-0.000475</td>\n      <td>0.982951</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.036382</td>\n      <td>0.960661</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.069528</td>\n      <td>0.960479</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.052084</td>\n      <td>0.957739</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">3</th>\n      <th>995</th>\n      <td>0.014148</td>\n      <td>1.015268</td>\n    </tr>\n    <tr>\n      <th>996</th>\n      <td>-0.010790</td>\n      <td>0.948807</td>\n    </tr>\n    <tr>\n      <th>997</th>\n      <td>0.061342</td>\n      <td>1.008478</td>\n    </tr>\n    <tr>\n      <th>998</th>\n      <td>0.041587</td>\n      <td>1.006843</td>\n    </tr>\n    <tr>\n      <th>999</th>\n      <td>0.046756</td>\n      <td>0.997424</td>\n    </tr>\n  </tbody>\n</table>\n<p>4000 rows \u00d7 2 columns</p>\n</div>\n\n\n\nIf we would want to know $\\mu$ and $\\sigma$ we could take the mean:\n\n\n```python\ntrace_df.mean().to_frame()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>0</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>mu</th>\n      <td>0.019798</td>\n    </tr>\n    <tr>\n      <th>sigma</th>\n      <td>0.981421</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThere is a built-in PyMC3 method that gives us more details in addition to the mean values:\n\n\n```python\npm.summary(trace)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>mean</th>\n      <th>sd</th>\n      <th>hdi_3%</th>\n      <th>hdi_97%</th>\n      <th>mcse_mean</th>\n      <th>mcse_sd</th>\n      <th>ess_bulk</th>\n      <th>ess_tail</th>\n      <th>r_hat</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>mu</th>\n      <td>0.020</td>\n      <td>0.031</td>\n      <td>-0.038</td>\n      <td>0.074</td>\n      <td>0.001</td>\n      <td>0.0</td>\n      <td>3294.0</td>\n      <td>3168.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>sigma</th>\n      <td>0.981</td>\n      <td>0.023</td>\n      <td>0.941</td>\n      <td>1.024</td>\n      <td>0.000</td>\n      <td>0.0</td>\n      <td>3464.0</td>\n      <td>2734.0</td>\n      <td>1.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThe *hdi* stands for [Highest (Posterior) Density Interval](https://en.wikipedia.org/wiki/Credible_interval) and gives the range in which credible values are located. As you can see, our real values 0.0 for $\\mu$ and 1.0 for $\\sigma$ are within those hdi invervals.\n\nTo get a better idea of the plausible parameter values we'll have a look at a [density plot](https://www.statsmodels.org/stable/examples/notebooks/generated/kernel_density.html).\n\n\n```python\n# list(statsmodels.nonparametric.kde.kernel_switch.keys())\n```\n\n\n```python\ndef kdeplot(lds, parameter_name=None, x_min = None, x_max = None, ax=None, kernel='gau'):\n    if parameter_name is None and isinstance(lds, pd.Series):\n        parameter_name = lds.name\n    kde = sm.nonparametric.KDEUnivariate(lds)\n    kde.fit(kernel=kernel, fft=False, gridsize=2**10)\n    if x_min is None:\n        x_min = kde.support.min()\n    else:\n        x_min = min(kde.support.min(), x_min)\n    if x_max is None:\n        x_max = kde.support.max()\n    else:\n        x_max = max(kde.support.max(),  x_max)\n    x = np.linspace(x_min, x_max,100)\n    y = kde.evaluate(x)\n    if ax is None:\n        plt.figure(figsize=(6, 3), dpi=80, facecolor='w', edgecolor='k')\n        ax = plt.subplot(1, 1, 1)\n    ax.plot(x, y, lw=2)\n    ax.set_xlabel(parameter_name)\n    ax.set_ylabel('Density')\n```\n\n\n```python\nkdeplot(trace_df['mu'], x_min=-0.5, x_max=0.5)\n```\n\n\n```python\nkdeplot(trace_df['sigma'], x_min=0.75, x_max=1.2)\n```\n\nWe will talk about it in more detail below, but what we did above is that we looked at the marginal likelihood of only $\\mu$ or only $\\sigma$. If your probability density function is given as samples then marginalizing out other parameters is trivial. You only take the parameter(s) (the columns in the sample dataframe) you're interested in.\n\nIt is important to understand that the samples, e.g. each row in the sample dataframe, are **jointly plausible**, e.g. they represent the joint probability distribution. If two parameters would be correlated you would see that in the pairsplot like below. In our example the two parameters are obviously uncorrelated.\n\n\n```python\nsns.pairplot(trace_df, height=3);\n```\n\n## Operations on probability distributions: marginalization and conditional probability\n\nWhile the marginalization and conditional probability operations are quite involved when you have to deal with probability distributions in their mathematical functions form these operations are *trivial* if you have samples representing the probability distributions.\n\nLet's start with marginalization. Let's assume you have a joint probability density function $p(x,y)$ for two random variables $X$ and $Y$. Then you marginalize out $y$ by integrating over all values of $y$:\n\n$\n\\displaystyle\n\\begin{array}{rcl}\np(x)&=&\\displaystyle\\int p(x,y)\\,\\mathrm{d}y\n\\end{array}\n$\n\nThis integration may be quite involved even in simple cases like a [multi-variate normal distribution](https://en.wikipedia.org/wiki/Multivariate_normal_distribution). Have a look at [Bayes\u2019 Theorem for Gaussians](http://web4.cs.ucl.ac.uk/staff/C.Bracegirdle/bayesTheoremForGaussians.pdf) by Chris Bracegirdle for details.\n\nIn the case of samples, on the other hand, marginalization is *trivial*! You simply project (in the sense of an [SQL projection](https://en.wikipedia.org/wiki/Projection_%28relational_algebra%29)) on the column(s) you're interested in and you get the marginal distribution for that parameter set.\n\nThe conditional probability is defined as:\n\n$\n\\displaystyle\n\\begin{array}{rcl}\np(x,y)&=&\\displaystyle p(y\\,|\\, x)p(x) \\\\\n\\Rightarrow p(y\\,|\\, x=x_0)&=&\\displaystyle \\frac{p(x_0,y)}{p(x_0)}\\\\\n&=&\\displaystyle \\frac{p(x=x_0,y)}{\\int p(x=x_0,y)\\mathrm{d}y} \\text{ you simply normalize the function} f(y)=p(x=x_0,y)\n\\end{array}\n$\n\nYou have to divide two distributions and often have to calculate integrals. I also show the variation where you use the marginalization $\\int p(x=x_0,y)\\mathrm{d}y$, because sometimes that's useful to remember. $p(x=x_0,y)$ is no probability distribution in $y$ any longer, because $\\int p(x=x_0,y)\\mathrm{d}y < 1$.\n\nIf you are in the world of samples then the conditional probability is calculated like an [SQL *where* clause](https://en.wikipedia.org/wiki/Relational_algebra#Selection_%28%CF%83%29), e.g. you sub-select the dataframe for values where $x=x_0$. For continuous variables this condition is nearly never true. Therefore you have to sub-select with a *where* condition like $x_0-\\delta<x<x_0+\\delta$. Finally you only keep the columns (SQL projection) of the variables that are on the left hand side of the conditional probability bar ($(\\cdot\\,|\\,\\cdot)$), e.g. $y$ in our example.\n\n## Calculations with random variables: convolutions and other nasty stuff\n\nCalculating with random variables when their distribution is given as mathematical functions is just painfully difficult. The book [The algebra of random variables](https://www.amazon.com/algebra-variables-probability-mathematical-statistics/dp/0471014060) by Melvine Dale Springer gives a detailed overview. But even the simplest example like adding two random variables like $X=X_1+X_2$ where $X_1\\sim p_1(x_1)$ and $X_2\\sim p_2(x_2)$ involves [convolutions](https://en.wikipedia.org/wiki/Convolution), e.g. $X\\sim p(x)= \\int p_1(x-x_2)p_2(x_2)\\,\\mathrm{d}x_2$. The library [PaCal](https://github.com/jszymon/pacal) (ProbAbilistic Calculator) or [SymPy](https://docs.sympy.org/latest/modules/stats.html) may help. Nevertheless it is just best to avoid these intricate calculations completely.\n\nLuckily, in the world of samples, all of that is simple again! Imagine you have a distribution given as samples from $x_1$ and $x_2$. You then construct samples of $x_1+x_2$ by simply adding them up for every row in your samples dataframe, e.g. you create a new column $x$ by row-wise calculating $x = x_1 + x_2$. And there you are, you have samples of the random variable $X$!\n\nAnother example might be like above, like [when we calculated the trajectory of the ball](#Bayes'-theorem). You could also see that example as $X_1 = X_0 + \\Delta X$, where $\\Delta X$ would be a distribution depending on the time delta $t_2-t_1$, the velocity $v$ and the acceleration $g$. In such cases it is typically easiest to see one of the variables as the starting point, e.g. $X_0$ and then use the law of total probability to construct $p(x_0, x_1)=p(x_0)p(x_1\\,|\\,x_0)$ and then calculate on the \"conditional\" side of $p(x_1\\,|\\,x_0)$, e.g. \n\n$\n\\displaystyle\np(x_1\\,|\\,x_0) = \\mathcal{N}(x_1; x_0+v(t_1-t_0)+(g/2)(t_1-t_0)^2,\\sigma_m)\n$\n\nAs you can see, on the \"conditional\" side of $p(x_1\\,|\\,x_0)$ (the side involving $x_0$) we simply calculate like normal! We simply add, subtract, multiply and whatever else we want to do. We also avoid the convolution by sampling from the total joint probability distribution $p(x_0, x_1)$ and marginalizing on the samples by simply dropping the $x_0$ column if we really wanted to. **No convolutions and no other difficult operations on distributions**! Just normal math and sampling on the extended joint space.\n\n## Density Estimation\n\nIn the past, whenever I was dealing with machine learning methods, I always felt disappointed; disappointed about the lack of \"insight\" and \"understanding\" and that machine learning methods only give me a uni-directional way of reasoning.\n\nLet's take regression or classification for example. Even the recent really impressive success stories like [object detection](https://en.wikipedia.org/wiki/Object_detection) and [image segmentation](https://en.wikipedia.org/wiki/Image_segmentation) only give you a way from an input to an output. If you wanted to know the most distinguishing features of a dog vs. a cat you're out of luck (there may be ways, but no straight-forward ones).\n\nIn my first encounter with [Bayesian networks](https://en.wikipedia.org/wiki/Bayesian_network) I was so impressed with the fact that you can not only reason forward from disease to symptoms, but also backward like given the symptoms of a patient, what are the most likely root causes, e.g. which disease might be the root cause and which actions/drugs might be the best way forward.\n\nIt took me quite some time to understand \"what I really wanted\". I wanted \"all the answers\", not only partial answers. And again some more time went by until I found the \"term\" that refers to what I want: [density estimation](https://en.wikipedia.org/wiki/Density_estimation). This term is often accompanied by other terms like [unsupervised learning](https://en.wikipedia.org/wiki/Unsupervised_learning) and recent advances in machine learning are also targeting density estimation directly via [deep generative models](https://en.wikipedia.org/wiki/Generative_model#Deep_generative_models). In the end it all boils down to \"discovering\" the [causal network](https://en.wikipedia.org/wiki/Causal_model) of the world, so that in the end you can answer any question you'd come up with, not only the ones the designer of the \"system\" wanted you to ask.\n\n## The algorithm has to always perform the same heavy lifting: there is no ancestral sampling\n\nWhen I read the paper [Mixed Hamiltonian Monte Carlo for Mixed Discrete and Continuous Variables](https://arxiv.org/abs/1909.04852) by Guangyao Zhou he used an exmaple of a [24 dimensional Gaussian Mixture Model](https://github.com/StannisZhou/mixed_hmc/blob/master/momentum/potential/simple_gmm.py) **without observations** to show the power of his approach. Initially, I felt as if this was cheating, because in the end [forward/ancestral](https://ermongroup.github.io/cs228-notes/inference/sampling) sampling is trival in that case. I had to remind myself that the MCMC algorithm he invented has to perform the same heavy lifting in the given example without observations as it has to perform in a situation that involves observations and the same number of free variables. The probabilistic programming languages and frameworks like [Stan](https://mc-stan.org/) or [PyMC3](https://docs.pymc.io/) do not employ any additional intelligence to decide which method might be most appropriate in which case.\n\n> You always take a model in the form of a scalar valued function representing the (unnormalized) total joint probability function and then you always apply the same hammer like an [SMC](https://www.amazon.com/-/de/dp-0387951466/dp/0387951466/) or [MCMC](https://www.amazon.com/-/de/dp-B008GXJVF8/dp/B008GXJVF8/) algorithm.\n\nIf you want to be smart on that level you have to do it yourself as a human with your own brain.\n\n## Appendix\n\n### Examples of mixed discrete continuous probability functions\n\nBelow I am exaggerating the level of explicitness at each step of the calculation and the level to which I use [SymPy](https://www.sympy.org/en/index.html) to achieve maximum clarity. I hope that this will help you to avoid a similar level of confusion that I found myself in. In addition you might learn to appreciate to use [SymPy](https://www.sympy.org/en/index.html), which is really great for symbolic algebra.\n\n#### Two independent coin tosses\n\nThe first example is about two independent coin tosses where we don't know $\\theta\\in[0,1]$, the probability for heads coming up. The total joint probability function (I only say \"probability function\" and avoid the terms *densite* or *mass*, because in the mixed case it is not clear in which situation we are) is then given by: $p(d_1,d_2,\\theta)=p(X_0=d_0\\,|\\,\\theta)\\cdot p(X_1=d_1\\,|\\,\\theta)\\cdot p(\\theta)$. If we take $p(\\theta)=\\mathrm{Beta}(1,1)=1$ for $\\theta\\in[0,1]$ then we get for each coin a one dimensional matrix with two entries:\n\n\n```python\nstheta = sympy.var(r'\\theta')\nD1 = sympy.Matrix([[(1-stheta)], [stheta]])\nD1\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 - \\theta\\\\\\theta\\end{matrix}\\right]$\n\n\n\nThe entry with index 0 belongs to the case where we observe \"tail\" and the entry with index 1 belongs to the case where we observe \"head\". We can index into that vector like so:\n\n\n```python\ndisplay(D1[0]),display(D1[1]);\n```\n\n\n$\\displaystyle 1 - \\theta$\n\n\n\n$\\displaystyle \\theta$\n\n\nAnd the indexing operation can be seen as a function that takes an integer and returns a scalar value. Exactly what we need for a probability function.\n\nFor the second coin we take a 2x1 matrix (a horizontal lying vector), so that when we multiply the two we will get a 2x2 matrix for the 2x2 combinations of tail and head for each coin:\n\n\n```python\nD2 = sympy.Matrix([[(1-stheta), stheta]])\nD2\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 - \\theta & \\theta\\end{matrix}\\right]$\n\n\n\n\n```python\nD = D1*D2\nD\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\left(1 - \\theta\\right)^{2} & \\theta \\left(1 - \\theta\\right)\\\\\\theta \\left(1 - \\theta\\right) & \\theta^{2}\\end{matrix}\\right]$\n\n\n\nWe said above that a probability function needs to be a function that takes as arguments the values of all random variables and delivers a scalar. In python this would look like:\n\n\n```python\ndef two_coin_tosses_probability_function(theta, d1, d2):\n    v = D.subs(stheta, theta)\n    v = v[d1,d2] # we use indexing to access a concrete slot in the multi dimensional array\n    return v\n```\n\nIf we then wanted to know the probability of one head and one tail for a fair coin we would get:\n\n\n```python\ntheta = sympy.Integer(1)/2\ndisplay(theta)\ntwo_coin_tosses_probability_function(theta, 1, 0)\n```\n\n\n$\\displaystyle \\frac{1}{2}$\n\n\n\n\n\n$\\displaystyle \\frac{1}{4}$\n\n\n\nThe other way we could have done this would be to use the [Kronecker delta](https://en.wikipedia.org/wiki/Kronecker_delta) instead of vector/matrix indexing and using the fact that any number to the power of $0$ is $1$: $x^0=1 \\quad\\forall x\\in \\mathbb{R}\\setminus 0$, e.g. we receive the neutral element for our product of probability functions.\n\n\n```python\nsd1, sd2 = sympy.symbols('d1:3') # we define two new sympy symbols for d1 and d2\nsd1, sd2\n```\n\n\n\n\n    (d1, d2)\n\n\n\nBelow, the first $1$ is to remind us of the $p(\\theta)=\\mathrm{Beta}(1,1)=1$. In case that we used another prior this would be a different factor.\n\n\n```python\nD_ = 1*(1-stheta)**sympy.KroneckerDelta(0,sd1)*stheta**sympy.KroneckerDelta(1,sd1)*(1-stheta)**sympy.KroneckerDelta(0,sd2)*stheta**sympy.KroneckerDelta(1,sd2)\nD_\n```\n\n\n\n\n$\\displaystyle \\theta^{\\delta_{1 d_{1}}} \\theta^{\\delta_{1 d_{2}}} \\left(1 - \\theta\\right)^{\\delta_{0 d_{1}}} \\left(1 - \\theta\\right)^{\\delta_{0 d_{2}}}$\n\n\n\n\n```python\ndef two_coin_tosses_probability_function_(theta, d1, d2):\n    v = D_.subs(stheta, theta)\n    v = v.subs(sd1,d1)\n    v = v.subs(sd2,d2)\n    return v\n```\n\nAnd of course you get the same result:\n\n\n```python\ntwo_coin_tosses_probability_function(theta, 1, 0)\n```\n\n\n\n\n$\\displaystyle \\frac{1}{4}$\n\n\n\nThe Kronecker delta variant looks more like a function, but a computer works better with an index lookup in a matrix. Finally we could use an **if-then-else** structure, but many probabilistic programming environments behave clumsy when it comes to if-then-else constructs.\n\n#### Two component mixture model\n\nThe second example is a two component mixture model. In most cases people will show a mixture of two Gaussians, but with two Gaussians you can get away with using an array of $\\mu$ and $\\sigma$. Let's look at mixing one Gaussian with one Exponential distribution:\n\n\n```python\nsmu, sx = sympy.symbols(r'\\mu x')\nsx1, sx2 = sympy.symbols(r'x1:3')\nsi, sj = sympy.symbols('i j', integer=True)\nsp0, sp1 = sympy.symbols(r'p:2')\nssigma = sympy.Symbol(\"\\sigma\", positive=True)\nslambda = sympy.Symbol(\"\\lambda\", positive=True)\nsympy.Matrix([smu, ssigma, slambda, sx, sx1, sx2, si, sj, sp0, sp1]).T # just for displaying the symbols\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\mu & \\sigma & \\lambda & x & x_{1} & x_{2} & i & j & p_{0} & p_{1}\\end{matrix}\\right]$\n\n\n\n\n```python\nsympy.stats.crv_types.NormalDistribution(smu, ssigma).pdf(sx)\n```\n\n\n\n\n$\\displaystyle \\frac{\\sqrt{2} e^{- \\frac{\\left(- \\mu + x\\right)^{2}}{2 \\sigma^{2}}}}{2 \\sqrt{\\pi} \\sigma}$\n\n\n\n\n```python\nsympy.stats.crv_types.ExponentialDistribution(slambda).pdf(sx)\n```\n\n\n\n\n$\\displaystyle \\lambda e^{- \\lambda x}$\n\n\n\nFor the mixture to work we use a mixture indicator $i\\in\\{0,1\\}$. If $i$ is 0 then we draw from the Exponential distribution and when $i$ is 1 we draw from the normal distribution. \n\n\n```python\nsympy.stats.frv_types.BernoulliDistribution(sp1, 1, 0).pmf(si)\n```\n\n\n\n\n$\\displaystyle \\begin{cases} p_{1} & \\text{for}\\: i = 1 \\\\1 - p_{1} & \\text{for}\\: i = 0 \\\\0 & \\text{otherwise} \\end{cases}$\n\n\n\n\n```python\n# print(sympy.latex(sympy.stats.frv_types.BernoulliDistribution(sp1, 1, 0).pmf(sx)))\n```\n\n\n```python\nsympy.stats.frv_types.BernoulliDistribution(sp1, 1, 0).pmf(1)\n```\n\n\n\n\n$\\displaystyle p_{1}$\n\n\n\n\n```python\nsympy.stats.frv_types.BernoulliDistribution(sp1, 1, 0).pmf(0)\n```\n\n\n\n\n$\\displaystyle 1 - p_{1}$\n\n\n\nFor a single observation the total joint probability function would look as follows:\n\n$\n\\displaystyle\np(p_1,i,\\lambda,\\mu,\\sigma,x)=p(p_1)p(i\\,|\\,p_1)\\begin{cases}p(\\lambda)p(x\\,|\\,\\lambda) & \\text{for}\\: i = 0\\\\ p(\\mu)p(\\sigma)p(x\\,|\\,\\mu,\\sigma) & \\text{for}\\: i = 1 \\\\0 & \\text{otherwise} \\end{cases}\n$\n\nBelow we're using SymPy to construct the total joint probability function for two observations:\n\n\n```python\nsprior_exponential = sympy.stats.crv_types.ExponentialDistribution(1).pdf(slambda)\nsprior_normal = sympy.stats.crv_types.ExponentialDistribution(1).pdf(ssigma)*sympy.stats.crv_types.NormalDistribution(0, 100).pdf(smu)\nsprior_mixture_components = sprior_normal*sympy.stats.crv_types.BetaDistribution(1,1).pdf(sp1)\nsprior = sprior_exponential*sprior_normal*sprior_mixture_components\nsmixture_likelihood = \\\n    (sympy.stats.frv_types.BernoulliDistribution(sp1, 1, 0).pmf(0)*sympy.stats.crv_types.ExponentialDistribution(slambda).pdf(sx1))**sympy.KroneckerDelta(0,si) * \\\n    (sympy.stats.frv_types.BernoulliDistribution(sp1, 1, 0).pmf(1)*sympy.stats.crv_types.NormalDistribution(smu, ssigma).pdf(sx1))**sympy.KroneckerDelta(1,si) * \\\n    (sympy.stats.frv_types.BernoulliDistribution(sp1, 1, 0).pmf(0)*sympy.stats.crv_types.ExponentialDistribution(slambda).pdf(sx2))**sympy.KroneckerDelta(0,sj) * \\\n    (sympy.stats.frv_types.BernoulliDistribution(sp1, 1, 0).pmf(1)*sympy.stats.crv_types.NormalDistribution(smu, ssigma).pdf(sx2))**sympy.KroneckerDelta(1,sj)\nsmixture = sprior * smixture_likelihood\nsmixture \n```\n\n\n\n\n$\\displaystyle \\frac{\\left(\\lambda \\left(1 - p_{1}\\right) e^{- \\lambda x_{1}}\\right)^{\\delta_{0 i}} \\left(\\lambda \\left(1 - p_{1}\\right) e^{- \\lambda x_{2}}\\right)^{\\delta_{0 j}} \\left(\\frac{\\sqrt{2} p_{1} e^{- \\frac{\\left(- \\mu + x_{1}\\right)^{2}}{2 \\sigma^{2}}}}{2 \\sqrt{\\pi} \\sigma}\\right)^{\\delta_{1 i}} \\left(\\frac{\\sqrt{2} p_{1} e^{- \\frac{\\left(- \\mu + x_{2}\\right)^{2}}{2 \\sigma^{2}}}}{2 \\sqrt{\\pi} \\sigma}\\right)^{\\delta_{1 j}} e^{- \\lambda} e^{- \\frac{\\mu^{2}}{10000}} e^{- 2 \\sigma}}{20000 \\pi}$\n\n\n\nOften, when you ask how to model a mixture model in a probabilistic programming system like Stan or PyMC3, people will recommend that you marginalize out the discrete variables like $i$ and $j$ above. Systems like Stan cannot deal with discrete free random variables at all. PyMC3 can deal with them, but sampling will be slow and hard, so that this recommendation actually makes sense.\n\nLet's use SymPy to marginalize out the discrete variables $i$ and $j$. Marginalizing out discrete variables means summing over them:\n\n\n```python\nsmixture_marginal_1 = sympy.summation(smixture, (si, 0, 1), (sj, 0, 1))\nsmixture_marginal_1\n```\n\n\n\n\n$\\displaystyle \\frac{\\left(\\lambda \\left(1 - p_{1}\\right) e^{- \\lambda x_{1}} + \\frac{\\sqrt{2} p_{1} e^{- \\frac{\\left(- \\mu + x_{1}\\right)^{2}}{2 \\sigma^{2}}}}{2 \\sqrt{\\pi} \\sigma}\\right) \\left(\\lambda \\left(1 - p_{1}\\right) e^{- \\lambda x_{2}} + \\frac{\\sqrt{2} p_{1} e^{- \\frac{\\left(- \\mu + x_{2}\\right)^{2}}{2 \\sigma^{2}}}}{2 \\sqrt{\\pi} \\sigma}\\right) e^{- \\lambda} e^{- \\frac{\\mu^{2}}{10000}} e^{- 2 \\sigma}}{20000 \\pi}$\n\n\n\nFor clarity we may only look at the likelihood part without the prior components:\n\n\n```python\nsympy.summation(smixture_likelihood, (si, 0, 1), (sj, 0, 1))\n```\n\n\n\n\n$\\displaystyle \\left(\\lambda \\left(1 - p_{1}\\right) e^{- \\lambda x_{1}} + \\frac{\\sqrt{2} p_{1} e^{- \\frac{\\left(- \\mu + x_{1}\\right)^{2}}{2 \\sigma^{2}}}}{2 \\sqrt{\\pi} \\sigma}\\right) \\left(\\lambda \\left(1 - p_{1}\\right) e^{- \\lambda x_{2}} + \\frac{\\sqrt{2} p_{1} e^{- \\frac{\\left(- \\mu + x_{2}\\right)^{2}}{2 \\sigma^{2}}}}{2 \\sqrt{\\pi} \\sigma}\\right)$\n\n\n\nObviously, we can do the same in the matrix picture rather than using Kronecker deltas:\n\n\n```python\nM1 = sympy.Matrix([\n    sympy.stats.frv_types.BernoulliDistribution(sp1, 1, 0).pmf(0)*sympy.stats.crv_types.ExponentialDistribution(slambda).pdf(sx1), \n    sympy.stats.frv_types.BernoulliDistribution(sp1, 1, 0).pmf(1)*sympy.stats.crv_types.NormalDistribution(smu, ssigma).pdf(sx1)])\nM2 = sympy.Matrix([[\n    sympy.stats.frv_types.BernoulliDistribution(sp1, 1, 0).pmf(0)*sympy.stats.crv_types.ExponentialDistribution(slambda).pdf(sx2), \n    sympy.stats.frv_types.BernoulliDistribution(sp1, 1, 0).pmf(1)*sympy.stats.crv_types.NormalDistribution(smu, ssigma).pdf(sx2)]])\nM = M1 * M2\nE = sprior * sympy.UnevaluatedExpr(M)\nE\n```\n\n\n\n\n$\\displaystyle \\frac{e^{- \\lambda} e^{- \\frac{\\mu^{2}}{10000}} e^{- 2 \\sigma} \\left[\\begin{matrix}\\lambda^{2} \\left(1 - p_{1}\\right)^{2} e^{- \\lambda x_{1}} e^{- \\lambda x_{2}} & \\frac{\\sqrt{2} \\lambda p_{1} \\left(1 - p_{1}\\right) e^{- \\lambda x_{1}} e^{- \\frac{\\left(- \\mu + x_{2}\\right)^{2}}{2 \\sigma^{2}}}}{2 \\sqrt{\\pi} \\sigma}\\\\\\frac{\\sqrt{2} \\lambda p_{1} \\left(1 - p_{1}\\right) e^{- \\lambda x_{2}} e^{- \\frac{\\left(- \\mu + x_{1}\\right)^{2}}{2 \\sigma^{2}}}}{2 \\sqrt{\\pi} \\sigma} & \\frac{p_{1}^{2} e^{- \\frac{\\left(- \\mu + x_{1}\\right)^{2}}{2 \\sigma^{2}}} e^{- \\frac{\\left(- \\mu + x_{2}\\right)^{2}}{2 \\sigma^{2}}}}{2 \\pi \\sigma^{2}}\\end{matrix}\\right]}{20000 \\pi}$\n\n\n\n\n```python\nE_ = E.doit()\n```\n\nWe can receive concrete values for a situation like if we assume that both data-points are from the exponential distribution:\n\n\n```python\nE_[0,0]\n```\n\n\n\n\n$\\displaystyle \\frac{\\lambda^{2} \\left(1 - p_{1}\\right)^{2} e^{- \\lambda} e^{- \\frac{\\mu^{2}}{10000}} e^{- 2 \\sigma} e^{- \\lambda x_{1}} e^{- \\lambda x_{2}}}{20000 \\pi}$\n\n\n\nThe marginalization works again by summing over the discrete variables. This time we have to use `sympy.Add` rather than `sympy.summation`, because we don't perform a symbolic summation:\n\n\n```python\nsmixture_marginal_2 = sympy.Add(*[E_[i, j] for i in range(2) for j in range(2)])\nsmixture_marginal_2\n```\n\n\n\n\n$\\displaystyle \\frac{\\lambda^{2} \\left(1 - p_{1}\\right)^{2} e^{- \\lambda} e^{- \\frac{\\mu^{2}}{10000}} e^{- 2 \\sigma} e^{- \\lambda x_{1}} e^{- \\lambda x_{2}}}{20000 \\pi} + \\frac{\\sqrt{2} \\lambda p_{1} \\left(1 - p_{1}\\right) e^{- \\lambda} e^{- \\frac{\\mu^{2}}{10000}} e^{- 2 \\sigma} e^{- \\lambda x_{2}} e^{- \\frac{\\left(- \\mu + x_{1}\\right)^{2}}{2 \\sigma^{2}}}}{40000 \\pi^{\\frac{3}{2}} \\sigma} + \\frac{\\sqrt{2} \\lambda p_{1} \\left(1 - p_{1}\\right) e^{- \\lambda} e^{- \\frac{\\mu^{2}}{10000}} e^{- 2 \\sigma} e^{- \\lambda x_{1}} e^{- \\frac{\\left(- \\mu + x_{2}\\right)^{2}}{2 \\sigma^{2}}}}{40000 \\pi^{\\frac{3}{2}} \\sigma} + \\frac{p_{1}^{2} e^{- \\lambda} e^{- \\frac{\\mu^{2}}{10000}} e^{- 2 \\sigma} e^{- \\frac{\\left(- \\mu + x_{1}\\right)^{2}}{2 \\sigma^{2}}} e^{- \\frac{\\left(- \\mu + x_{2}\\right)^{2}}{2 \\sigma^{2}}}}{40000 \\pi^{2} \\sigma^{2}}$\n\n\n\nIn this form it is not immediately obvious that the two expressions are actually the same, but we can let SymPy answer that by subtracting the two terms and showing that the result is 0:\n\n\n```python\nsympy.simplify(smixture_marginal_1 - smixture_marginal_2)\n```\n\n\n\n\n$\\displaystyle 0$\n\n\n", "meta": {"hexsha": "681e5bdb663d8b19167aa5ccbcf2aa8f2bebccd1", "size": 228817, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "0010-fundamental-concepts.ipynb", "max_stars_repo_name": "cs224/blog-series-monte-carlo-methods", "max_stars_repo_head_hexsha": "5300dc80077a64433b02954f648b9cf43f4573c9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-12T04:06:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T04:06:34.000Z", "max_issues_repo_path": "0010-fundamental-concepts.ipynb", "max_issues_repo_name": "cs224/blog-series-monte-carlo-methods", "max_issues_repo_head_hexsha": "5300dc80077a64433b02954f648b9cf43f4573c9", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0010-fundamental-concepts.ipynb", "max_forks_repo_name": "cs224/blog-series-monte-carlo-methods", "max_forks_repo_head_hexsha": "5300dc80077a64433b02954f648b9cf43f4573c9", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 119.5491118077, "max_line_length": 93948, "alphanum_fraction": 0.8305763995, "converted": true, "num_tokens": 15237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2094696714602651, "lm_q2_score": 0.16026602631152878, "lm_q1q2_score": 0.033570871877718136}}
{"text": "#Install dependencies (Qiskit)\n\n\n```\n# install dependencies (Qiskit)\n!pip install --upgrade qiskit==0.19.6 \n!pip install --upgrade metakernel\n!pip install --upgrade portalocker\n!pip install --upgrade matplotlib\n!pip install git+https://github.com/qiskit-community/qiskit-textbook.git#subdirectory=qiskit-textbook-src\n```\n\n    Requirement already up-to-date: qiskit==0.19.6 in /usr/local/lib/python3.6/dist-packages (0.19.6)\n    Requirement already satisfied, skipping upgrade: qiskit-ibmq-provider==0.7.2 in /usr/local/lib/python3.6/dist-packages (from qiskit==0.19.6) (0.7.2)\n    Requirement already satisfied, skipping upgrade: qiskit-aer==0.5.2 in /usr/local/lib/python3.6/dist-packages (from qiskit==0.19.6) (0.5.2)\n    Requirement already satisfied, skipping upgrade: qiskit-terra==0.14.2 in /usr/local/lib/python3.6/dist-packages (from qiskit==0.19.6) (0.14.2)\n    Requirement already satisfied, skipping upgrade: qiskit-ignis==0.3.3 in /usr/local/lib/python3.6/dist-packages (from qiskit==0.19.6) (0.3.3)\n    Requirement already satisfied, skipping upgrade: qiskit-aqua==0.7.3 in /usr/local/lib/python3.6/dist-packages (from qiskit==0.19.6) (0.7.3)\n    Requirement already satisfied, skipping upgrade: requests>=2.19 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit==0.19.6) (2.23.0)\n    Requirement already satisfied, skipping upgrade: numpy>=1.13 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit==0.19.6) (1.18.5)\n    Requirement already satisfied, skipping upgrade: python-dateutil>=2.8.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit==0.19.6) (2.8.1)\n    Requirement already satisfied, skipping upgrade: nest-asyncio!=1.1.0,>=1.0.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit==0.19.6) (1.4.0)\n    Requirement already satisfied, skipping upgrade: requests-ntlm>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit==0.19.6) (1.1.0)\n    Requirement already satisfied, skipping upgrade: urllib3>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit==0.19.6) (1.24.3)\n    Requirement already satisfied, skipping upgrade: websockets<8,>=7 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit==0.19.6) (7.0)\n    Requirement already satisfied, skipping upgrade: pybind11>=2.4 in /usr/local/lib/python3.6/dist-packages (from qiskit-aer==0.5.2->qiskit==0.19.6) (2.5.0)\n    Requirement already satisfied, skipping upgrade: cython>=0.27.1 in /usr/local/lib/python3.6/dist-packages (from qiskit-aer==0.5.2->qiskit==0.19.6) (0.29.21)\n    Requirement already satisfied, skipping upgrade: scipy>=1.0; python_version > \"3.5\" in /usr/local/lib/python3.6/dist-packages (from qiskit-aer==0.5.2->qiskit==0.19.6) (1.4.1)\n    Requirement already satisfied, skipping upgrade: dill>=0.3 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit==0.19.6) (0.3.2)\n    Requirement already satisfied, skipping upgrade: fastjsonschema>=2.10 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit==0.19.6) (2.14.4)\n    Requirement already satisfied, skipping upgrade: marshmallow<4,>=3 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit==0.19.6) (3.7.1)\n    Requirement already satisfied, skipping upgrade: retworkx>=0.3.2 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit==0.19.6) (0.4.0)\n    Requirement already satisfied, skipping upgrade: jsonschema>=2.6 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit==0.19.6) (2.6.0)\n    Requirement already satisfied, skipping upgrade: python-constraint>=1.4 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit==0.19.6) (1.4.0)\n    Requirement already satisfied, skipping upgrade: networkx>=2.2; python_version > \"3.5\" in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit==0.19.6) (2.4)\n    Requirement already satisfied, skipping upgrade: marshmallow-polyfield<6,>=5.7 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit==0.19.6) (5.9)\n    Requirement already satisfied, skipping upgrade: psutil>=5 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit==0.19.6) (5.4.8)\n    Requirement already satisfied, skipping upgrade: ply>=3.10 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit==0.19.6) (3.11)\n    Requirement already satisfied, skipping upgrade: sympy>=1.3 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit==0.19.6) (1.6.2)\n    Requirement already satisfied, skipping upgrade: scikit-learn>=0.17 in /usr/local/lib/python3.6/dist-packages (from qiskit-ignis==0.3.3->qiskit==0.19.6) (0.22.2.post1)\n    Requirement already satisfied, skipping upgrade: setuptools>=40.1.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-ignis==0.3.3->qiskit==0.19.6) (49.2.0)\n    Requirement already satisfied, skipping upgrade: h5py in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit==0.19.6) (2.10.0)\n    Requirement already satisfied, skipping upgrade: fastdtw in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit==0.19.6) (0.3.4)\n    Requirement already satisfied, skipping upgrade: dlx in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit==0.19.6) (1.0.4)\n    Requirement already satisfied, skipping upgrade: docplex in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit==0.19.6) (2.15.194)\n    Requirement already satisfied, skipping upgrade: pyscf; sys_platform != \"win32\" in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit==0.19.6) (1.7.4)\n    Requirement already satisfied, skipping upgrade: quandl in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit==0.19.6) (3.5.2)\n    Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.7.2->qiskit==0.19.6) (2020.6.20)\n    Requirement already satisfied, skipping upgrade: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.7.2->qiskit==0.19.6) (3.0.4)\n    Requirement already satisfied, skipping upgrade: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.7.2->qiskit==0.19.6) (2.10)\n    Requirement already satisfied, skipping upgrade: six>=1.5 in /usr/local/lib/python3.6/dist-packages (from python-dateutil>=2.8.0->qiskit-ibmq-provider==0.7.2->qiskit==0.19.6) (1.15.0)\n    Requirement already satisfied, skipping upgrade: ntlm-auth>=1.0.2 in /usr/local/lib/python3.6/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit==0.19.6) (1.5.0)\n    Requirement already satisfied, skipping upgrade: cryptography>=1.3 in /usr/local/lib/python3.6/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit==0.19.6) (3.0)\n    Requirement already satisfied, skipping upgrade: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx>=2.2; python_version > \"3.5\"->qiskit-terra==0.14.2->qiskit==0.19.6) (4.4.2)\n    Requirement already satisfied, skipping upgrade: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy>=1.3->qiskit-terra==0.14.2->qiskit==0.19.6) (1.1.0)\n    Requirement already satisfied, skipping upgrade: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn>=0.17->qiskit-ignis==0.3.3->qiskit==0.19.6) (0.16.0)\n    Requirement already satisfied, skipping upgrade: inflection>=0.3.1 in /usr/local/lib/python3.6/dist-packages (from quandl->qiskit-aqua==0.7.3->qiskit==0.19.6) (0.5.0)\n    Requirement already satisfied, skipping upgrade: more-itertools in /usr/local/lib/python3.6/dist-packages (from quandl->qiskit-aqua==0.7.3->qiskit==0.19.6) (8.4.0)\n    Requirement already satisfied, skipping upgrade: pandas>=0.14 in /usr/local/lib/python3.6/dist-packages (from quandl->qiskit-aqua==0.7.3->qiskit==0.19.6) (1.0.5)\n    Requirement already satisfied, skipping upgrade: cffi!=1.11.3,>=1.8 in /usr/local/lib/python3.6/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit==0.19.6) (1.14.1)\n    Requirement already satisfied, skipping upgrade: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.14->quandl->qiskit-aqua==0.7.3->qiskit==0.19.6) (2018.9)\n    Requirement already satisfied, skipping upgrade: pycparser in /usr/local/lib/python3.6/dist-packages (from cffi!=1.11.3,>=1.8->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit==0.19.6) (2.20)\n    Requirement already up-to-date: metakernel in /usr/local/lib/python3.6/dist-packages (0.24.4)\n    Requirement already satisfied, skipping upgrade: pexpect>=4.2 in /usr/local/lib/python3.6/dist-packages (from metakernel) (4.8.0)\n    Requirement already satisfied, skipping upgrade: ipykernel in /usr/local/lib/python3.6/dist-packages (from metakernel) (4.10.1)\n    Requirement already satisfied, skipping upgrade: ptyprocess>=0.5 in /usr/local/lib/python3.6/dist-packages (from pexpect>=4.2->metakernel) (0.6.0)\n    Requirement already satisfied, skipping upgrade: ipython>=4.0.0 in /usr/local/lib/python3.6/dist-packages (from ipykernel->metakernel) (5.5.0)\n    Requirement already satisfied, skipping upgrade: jupyter-client in /usr/local/lib/python3.6/dist-packages (from ipykernel->metakernel) (5.3.5)\n    Requirement already satisfied, skipping upgrade: tornado>=4.0 in /usr/local/lib/python3.6/dist-packages (from ipykernel->metakernel) (5.1.1)\n    Requirement already satisfied, skipping upgrade: traitlets>=4.1.0 in /usr/local/lib/python3.6/dist-packages (from ipykernel->metakernel) (4.3.3)\n    Requirement already satisfied, skipping upgrade: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.6/dist-packages (from ipython>=4.0.0->ipykernel->metakernel) (1.0.18)\n    Requirement already satisfied, skipping upgrade: decorator in /usr/local/lib/python3.6/dist-packages (from ipython>=4.0.0->ipykernel->metakernel) (4.4.2)\n    Requirement already satisfied, skipping upgrade: setuptools>=18.5 in /usr/local/lib/python3.6/dist-packages (from ipython>=4.0.0->ipykernel->metakernel) (49.2.0)\n    Requirement already satisfied, skipping upgrade: pickleshare in /usr/local/lib/python3.6/dist-packages (from ipython>=4.0.0->ipykernel->metakernel) (0.7.5)\n    Requirement already satisfied, skipping upgrade: simplegeneric>0.8 in /usr/local/lib/python3.6/dist-packages (from ipython>=4.0.0->ipykernel->metakernel) (0.8.1)\n    Requirement already satisfied, skipping upgrade: pygments in /usr/local/lib/python3.6/dist-packages (from ipython>=4.0.0->ipykernel->metakernel) (2.1.3)\n    Requirement already satisfied, skipping upgrade: pyzmq>=13 in /usr/local/lib/python3.6/dist-packages (from jupyter-client->ipykernel->metakernel) (19.0.2)\n    Requirement already satisfied, skipping upgrade: jupyter-core>=4.6.0 in /usr/local/lib/python3.6/dist-packages (from jupyter-client->ipykernel->metakernel) (4.6.3)\n    Requirement already satisfied, skipping upgrade: python-dateutil>=2.1 in /usr/local/lib/python3.6/dist-packages (from jupyter-client->ipykernel->metakernel) (2.8.1)\n    Requirement already satisfied, skipping upgrade: ipython-genutils in /usr/local/lib/python3.6/dist-packages (from traitlets>=4.1.0->ipykernel->metakernel) (0.2.0)\n    Requirement already satisfied, skipping upgrade: six in /usr/local/lib/python3.6/dist-packages (from traitlets>=4.1.0->ipykernel->metakernel) (1.15.0)\n    Requirement already satisfied, skipping upgrade: wcwidth in /usr/local/lib/python3.6/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython>=4.0.0->ipykernel->metakernel) (0.2.5)\n    Requirement already up-to-date: portalocker in /usr/local/lib/python3.6/dist-packages (2.0.0)\n    Requirement already up-to-date: matplotlib in /usr/local/lib/python3.6/dist-packages (3.3.1)\n    Requirement already satisfied, skipping upgrade: certifi>=2020.06.20 in /usr/local/lib/python3.6/dist-packages (from matplotlib) (2020.6.20)\n    Requirement already satisfied, skipping upgrade: pillow>=6.2.0 in /usr/local/lib/python3.6/dist-packages (from matplotlib) (7.0.0)\n    Requirement already satisfied, skipping upgrade: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib) (0.10.0)\n    Requirement already satisfied, skipping upgrade: python-dateutil>=2.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib) (2.8.1)\n    Requirement already satisfied, skipping upgrade: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3 in /usr/local/lib/python3.6/dist-packages (from matplotlib) (2.4.7)\n    Requirement already satisfied, skipping upgrade: numpy>=1.15 in /usr/local/lib/python3.6/dist-packages (from matplotlib) (1.18.5)\n    Requirement already satisfied, skipping upgrade: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib) (1.2.0)\n    Requirement already satisfied, skipping upgrade: six in /usr/local/lib/python3.6/dist-packages (from cycler>=0.10->matplotlib) (1.15.0)\n    Collecting git+https://github.com/qiskit-community/qiskit-textbook.git#subdirectory=qiskit-textbook-src\n      Cloning https://github.com/qiskit-community/qiskit-textbook.git to /tmp/pip-req-build-v11l3b5p\n      Running command git clone -q https://github.com/qiskit-community/qiskit-textbook.git /tmp/pip-req-build-v11l3b5p\n    Requirement already satisfied: qiskit in /usr/local/lib/python3.6/dist-packages (from qiskit-textbook==0.1.0) (0.19.6)\n    Requirement already satisfied: ipython in /usr/local/lib/python3.6/dist-packages (from qiskit-textbook==0.1.0) (5.5.0)\n    Requirement already satisfied: ipywidgets in /usr/local/lib/python3.6/dist-packages (from qiskit-textbook==0.1.0) (7.5.1)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from qiskit-textbook==0.1.0) (1.18.5)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.6/dist-packages (from qiskit-textbook==0.1.0) (3.3.1)\n    Requirement already satisfied: qiskit-aer==0.5.2 in /usr/local/lib/python3.6/dist-packages (from qiskit->qiskit-textbook==0.1.0) (0.5.2)\n    Requirement already satisfied: qiskit-terra==0.14.2 in /usr/local/lib/python3.6/dist-packages (from qiskit->qiskit-textbook==0.1.0) (0.14.2)\n    Requirement already satisfied: qiskit-aqua==0.7.3 in /usr/local/lib/python3.6/dist-packages (from qiskit->qiskit-textbook==0.1.0) (0.7.3)\n    Requirement already satisfied: qiskit-ignis==0.3.3 in /usr/local/lib/python3.6/dist-packages (from qiskit->qiskit-textbook==0.1.0) (0.3.3)\n    Requirement already satisfied: qiskit-ibmq-provider==0.7.2 in /usr/local/lib/python3.6/dist-packages (from qiskit->qiskit-textbook==0.1.0) (0.7.2)\n    Requirement already satisfied: pickleshare in /usr/local/lib/python3.6/dist-packages (from ipython->qiskit-textbook==0.1.0) (0.7.5)\n    Requirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.6/dist-packages (from ipython->qiskit-textbook==0.1.0) (0.8.1)\n    Requirement already satisfied: traitlets>=4.2 in /usr/local/lib/python3.6/dist-packages (from ipython->qiskit-textbook==0.1.0) (4.3.3)\n    Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.6/dist-packages (from ipython->qiskit-textbook==0.1.0) (1.0.18)\n    Requirement already satisfied: pexpect; sys_platform != \"win32\" in /usr/local/lib/python3.6/dist-packages (from ipython->qiskit-textbook==0.1.0) (4.8.0)\n    Requirement already satisfied: pygments in /usr/local/lib/python3.6/dist-packages (from ipython->qiskit-textbook==0.1.0) (2.1.3)\n    Requirement already satisfied: setuptools>=18.5 in /usr/local/lib/python3.6/dist-packages (from ipython->qiskit-textbook==0.1.0) (49.2.0)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.6/dist-packages (from ipython->qiskit-textbook==0.1.0) (4.4.2)\n    Requirement already satisfied: widgetsnbextension~=3.5.0 in /usr/local/lib/python3.6/dist-packages (from ipywidgets->qiskit-textbook==0.1.0) (3.5.1)\n    Requirement already satisfied: ipykernel>=4.5.1 in /usr/local/lib/python3.6/dist-packages (from ipywidgets->qiskit-textbook==0.1.0) (4.10.1)\n    Requirement already satisfied: nbformat>=4.2.0 in /usr/local/lib/python3.6/dist-packages (from ipywidgets->qiskit-textbook==0.1.0) (5.0.7)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->qiskit-textbook==0.1.0) (2.8.1)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->qiskit-textbook==0.1.0) (1.2.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3 in /usr/local/lib/python3.6/dist-packages (from matplotlib->qiskit-textbook==0.1.0) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib->qiskit-textbook==0.1.0) (0.10.0)\n    Requirement already satisfied: pillow>=6.2.0 in /usr/local/lib/python3.6/dist-packages (from matplotlib->qiskit-textbook==0.1.0) (7.0.0)\n    Requirement already satisfied: certifi>=2020.06.20 in /usr/local/lib/python3.6/dist-packages (from matplotlib->qiskit-textbook==0.1.0) (2020.6.20)\n    Requirement already satisfied: pybind11>=2.4 in /usr/local/lib/python3.6/dist-packages (from qiskit-aer==0.5.2->qiskit->qiskit-textbook==0.1.0) (2.5.0)\n    Requirement already satisfied: scipy>=1.0; python_version > \"3.5\" in /usr/local/lib/python3.6/dist-packages (from qiskit-aer==0.5.2->qiskit->qiskit-textbook==0.1.0) (1.4.1)\n    Requirement already satisfied: cython>=0.27.1 in /usr/local/lib/python3.6/dist-packages (from qiskit-aer==0.5.2->qiskit->qiskit-textbook==0.1.0) (0.29.21)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit->qiskit-textbook==0.1.0) (1.6.2)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit->qiskit-textbook==0.1.0) (0.3.2)\n    Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit->qiskit-textbook==0.1.0) (2.6.0)\n    Requirement already satisfied: python-constraint>=1.4 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit->qiskit-textbook==0.1.0) (1.4.0)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit->qiskit-textbook==0.1.0) (5.4.8)\n    Requirement already satisfied: fastjsonschema>=2.10 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit->qiskit-textbook==0.1.0) (2.14.4)\n    Requirement already satisfied: retworkx>=0.3.2 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit->qiskit-textbook==0.1.0) (0.4.0)\n    Requirement already satisfied: networkx>=2.2; python_version > \"3.5\" in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit->qiskit-textbook==0.1.0) (2.4)\n    Requirement already satisfied: marshmallow-polyfield<6,>=5.7 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit->qiskit-textbook==0.1.0) (5.9)\n    Requirement already satisfied: ply>=3.10 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit->qiskit-textbook==0.1.0) (3.11)\n    Requirement already satisfied: marshmallow<4,>=3 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit->qiskit-textbook==0.1.0) (3.7.1)\n    Requirement already satisfied: dlx in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit->qiskit-textbook==0.1.0) (1.0.4)\n    Requirement already satisfied: fastdtw in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit->qiskit-textbook==0.1.0) (0.3.4)\n    Requirement already satisfied: pyscf; sys_platform != \"win32\" in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit->qiskit-textbook==0.1.0) (1.7.4)\n    Requirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit->qiskit-textbook==0.1.0) (2.10.0)\n    Requirement already satisfied: scikit-learn>=0.20.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit->qiskit-textbook==0.1.0) (0.22.2.post1)\n    Requirement already satisfied: quandl in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit->qiskit-textbook==0.1.0) (3.5.2)\n    Requirement already satisfied: docplex in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit->qiskit-textbook==0.1.0) (2.15.194)\n    Requirement already satisfied: websockets<8,>=7 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit->qiskit-textbook==0.1.0) (7.0)\n    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit->qiskit-textbook==0.1.0) (1.24.3)\n    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit->qiskit-textbook==0.1.0) (2.23.0)\n    Requirement already satisfied: requests-ntlm>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit->qiskit-textbook==0.1.0) (1.1.0)\n    Requirement already satisfied: nest-asyncio!=1.1.0,>=1.0.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit->qiskit-textbook==0.1.0) (1.4.0)\n    Requirement already satisfied: ipython-genutils in /usr/local/lib/python3.6/dist-packages (from traitlets>=4.2->ipython->qiskit-textbook==0.1.0) (0.2.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from traitlets>=4.2->ipython->qiskit-textbook==0.1.0) (1.15.0)\n    Requirement already satisfied: wcwidth in /usr/local/lib/python3.6/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython->qiskit-textbook==0.1.0) (0.2.5)\n    Requirement already satisfied: ptyprocess>=0.5 in /usr/local/lib/python3.6/dist-packages (from pexpect; sys_platform != \"win32\"->ipython->qiskit-textbook==0.1.0) (0.6.0)\n    Requirement already satisfied: notebook>=4.4.1 in /usr/local/lib/python3.6/dist-packages (from widgetsnbextension~=3.5.0->ipywidgets->qiskit-textbook==0.1.0) (5.3.1)\n    Requirement already satisfied: tornado>=4.0 in /usr/local/lib/python3.6/dist-packages (from ipykernel>=4.5.1->ipywidgets->qiskit-textbook==0.1.0) (5.1.1)\n    Requirement already satisfied: jupyter-client in /usr/local/lib/python3.6/dist-packages (from ipykernel>=4.5.1->ipywidgets->qiskit-textbook==0.1.0) (5.3.5)\n    Requirement already satisfied: jupyter-core in /usr/local/lib/python3.6/dist-packages (from nbformat>=4.2.0->ipywidgets->qiskit-textbook==0.1.0) (4.6.3)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy>=1.3->qiskit-terra==0.14.2->qiskit->qiskit-textbook==0.1.0) (1.1.0)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.7.3->qiskit->qiskit-textbook==0.1.0) (0.16.0)\n    Requirement already satisfied: inflection>=0.3.1 in /usr/local/lib/python3.6/dist-packages (from quandl->qiskit-aqua==0.7.3->qiskit->qiskit-textbook==0.1.0) (0.5.0)\n    Requirement already satisfied: pandas>=0.14 in /usr/local/lib/python3.6/dist-packages (from quandl->qiskit-aqua==0.7.3->qiskit->qiskit-textbook==0.1.0) (1.0.5)\n    Requirement already satisfied: more-itertools in /usr/local/lib/python3.6/dist-packages (from quandl->qiskit-aqua==0.7.3->qiskit->qiskit-textbook==0.1.0) (8.4.0)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.7.2->qiskit->qiskit-textbook==0.1.0) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.7.2->qiskit->qiskit-textbook==0.1.0) (3.0.4)\n    Requirement already satisfied: ntlm-auth>=1.0.2 in /usr/local/lib/python3.6/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit->qiskit-textbook==0.1.0) (1.5.0)\n    Requirement already satisfied: cryptography>=1.3 in /usr/local/lib/python3.6/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit->qiskit-textbook==0.1.0) (3.0)\n    Requirement already satisfied: nbconvert in /usr/local/lib/python3.6/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->qiskit-textbook==0.1.0) (5.6.1)\n    Requirement already satisfied: Send2Trash in /usr/local/lib/python3.6/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->qiskit-textbook==0.1.0) (1.5.0)\n    Requirement already satisfied: terminado>=0.8.1 in /usr/local/lib/python3.6/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->qiskit-textbook==0.1.0) (0.8.3)\n    Requirement already satisfied: jinja2 in /usr/local/lib/python3.6/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->qiskit-textbook==0.1.0) (2.11.2)\n    Requirement already satisfied: pyzmq>=13 in /usr/local/lib/python3.6/dist-packages (from jupyter-client->ipykernel>=4.5.1->ipywidgets->qiskit-textbook==0.1.0) (19.0.2)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.14->quandl->qiskit-aqua==0.7.3->qiskit->qiskit-textbook==0.1.0) (2018.9)\n    Requirement already satisfied: cffi!=1.11.3,>=1.8 in /usr/local/lib/python3.6/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit->qiskit-textbook==0.1.0) (1.14.1)\n    Requirement already satisfied: defusedxml in /usr/local/lib/python3.6/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->qiskit-textbook==0.1.0) (0.6.0)\n    Requirement already satisfied: mistune<2,>=0.8.1 in /usr/local/lib/python3.6/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->qiskit-textbook==0.1.0) (0.8.4)\n    Requirement already satisfied: entrypoints>=0.2.2 in /usr/local/lib/python3.6/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->qiskit-textbook==0.1.0) (0.3)\n    Requirement already satisfied: bleach in /usr/local/lib/python3.6/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->qiskit-textbook==0.1.0) (3.1.5)\n    Requirement already satisfied: pandocfilters>=1.4.1 in /usr/local/lib/python3.6/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->qiskit-textbook==0.1.0) (1.4.2)\n    Requirement already satisfied: testpath in /usr/local/lib/python3.6/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->qiskit-textbook==0.1.0) (0.4.4)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.6/dist-packages (from jinja2->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->qiskit-textbook==0.1.0) (1.1.1)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.6/dist-packages (from cffi!=1.11.3,>=1.8->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit->qiskit-textbook==0.1.0) (2.20)\n    Requirement already satisfied: webencodings in /usr/local/lib/python3.6/dist-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->qiskit-textbook==0.1.0) (0.5.1)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.6/dist-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->qiskit-textbook==0.1.0) (20.4)\n    Building wheels for collected packages: qiskit-textbook\n      Building wheel for qiskit-textbook (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for qiskit-textbook: filename=qiskit_textbook-0.1.0-cp36-none-any.whl size=16672 sha256=91226ef6dcb84513a75902c1b5c02760c5a1e7d33ec74aa39fbd1e03042fc31f\n      Stored in directory: /tmp/pip-ephem-wheel-cache-o72zdjj6/wheels/0c/57/26/1c12886a219af04a38ca1e674fdeeff40b8a5963326ba3c71a\n    Successfully built qiskit-textbook\n    Installing collected packages: qiskit-textbook\n    Successfully installed qiskit-textbook-0.1.0\n\n\n#Import Basic Quantum Circuit \n#\u5f15\u5165\u57fa\u672c\u7684\u91cf\u5b50\u96fb\u8def\n\n\n# Single Quantum Gate - XGate \n# \u55ae\u91cf\u5b50\u9598-X\u9598\n\n\n\n```\n#XGate\n\n#Importing QuantumCircuit from qikit\nfrom qiskit import QuantumCircuit\n\n#Creating a quantum cicuit with 1 Qubit\nqc = QuantumCircuit(1)\n\n#Creating XGate for q0\nqc.x(0)\n\n#Drawing the quantum circuit\nqc.draw('mpl')\n```\n\n# Single Quantum Gate - HGate \n# \u55ae\u91cf\u5b50\u9598-H\u9598\n\n\n\n```\n#Importing QuantumCircuit from qikit\nfrom qiskit import QuantumCircuit\n\n#Creating a quantum cicuit with 1 Qubit\nqc = QuantumCircuit(1)\n\n#Creating XGate for q0\nqc.h(0)\n\n#Drawing the quantum circuit\nqc.draw('mpl')\n```\n\n#Combining Two Quantum Gates in 1 Qubit\n#\u4ee51 Qubit\u7d44\u5408\u5169\u500b\u91cf\u5b50\u9598\n\n\n\n```\n#Importing QuantumCircuit from qikit\nfrom qiskit import QuantumCircuit\n\n#Creating a quantum cicuit with 1 Qubit\nqc = QuantumCircuit(1)\n\n#Creating XGate for q0\nqc.x(0)\nqc.h(0)\n\n#Drawing the quantum circuit\nqc.draw('mpl')\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">     \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\nq_0: \u2524 X \u251c\u2524 H \u251c\n     \u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518</pre>\n\n\n\n# Two or more Quantum Gates - Bell State\n\uff03\u5169\u500b\u6216\u66f4\u591a\u91cf\u5b50\u9598-\u8c9d\u723e\u72c0\u614b\n\uff03HGate + CNOTx\n# H\u9598 + \u53d7\u63a7\u53cd\u9598\n\n\n```\n#Importing QuantumCircuit from qikit\nfrom qiskit import QuantumCircuit\n\n#Creating a quantum cicuit with 2 Qubits and 2 Classical Bits\nqc = QuantumCircuit(2,2)\n\n#Creating HGate for q0\nqc.h(0)\n\n#Creating CNOTx Gate (Control:q0 and Target: q1)\nqc.cx(0,1)\n\n#Drawing the quantum circuit\nqc.draw()\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">     \u250c\u2500\u2500\u2500\u2510     \nq_0: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\n     \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2534\u2500\u2510\nq_1: \u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\n          \u2514\u2500\u2500\u2500\u2518\nc_0: \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\nc_1: \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n               </pre>\n\n\n\n# XGate Simulator with default initial state, |0> \n# \u5177\u6709|0>\u521d\u59cb\u72c0\u614b\u7684X\u9598\u6a21\u64ec\u5668\n\n\n```\n\u53e3\u53e3#XGate\nfrom qiskit import QuantumCircuit, Aer, execute\n#Nice Latex Arrary\nfrom qiskit_textbook.tools import array_to_latex\n\n#Creating a quantum cicuit with 1 Qubit\nqc = QuantumCircuit(1)\n\n#Creating XGate for q0\nqc.x(0)\n\n\n# Let's see the result:\nbackend = Aer.get_backend('statevector_simulator')\nfinal_state = execute(qc,backend).result().get_statevector()\n# Print the statevector neatly:\narray_to_latex(final_state, pretext=\"\\\\text{Statevector = }\")\n```\n\n\n$$\n\\text{Statevector = }\\begin{bmatrix}\n0 \\\\\n1\n\\end{bmatrix}\n$$\n\n\n# XGate Simulator with initial state, |1> \n# \u5177\u6709|1>\u521d\u59cb\u72c0\u614b\u7684X\u9598\u6a21\u64ec\u5668\n\n\n```\n#XGate\nfrom qiskit import QuantumCircuit, Aer, execute\n#Nice Latex Arrary\nfrom qiskit_textbook.tools import array_to_latex\n\n#Creating a quantum cicuit with 1 Qubit\nqc = QuantumCircuit(1)\n\n# Define initial_state as |1>\ninitial_state = [0,1]\n\n# Apply initialisation operation to the 0th qubit\nqc.initialize(initial_state, 0) \n\n#Creating XGate for q0\nqc.x(0)\n\n# Let's see the result:\nbackend = Aer.get_backend('statevector_simulator')\nfinal_state = execute(qc,backend).result().get_statevector()\n# Print the statevector neatly:\narray_to_latex(final_state, pretext=\"\\\\text{Statevector = }\")\n```\n\n\n$$\n\\text{Statevector = }\\begin{bmatrix}\n1 \\\\\n0\n\\end{bmatrix}\n$$\n\n", "meta": {"hexsha": "22c7a5676e12f8430fae2e3cc7fddcae14dcaf40", "size": 44459, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Cheatsheet.ipynb", "max_stars_repo_name": "dr-data/Qiskit_CheatSheet", "max_stars_repo_head_hexsha": "d527876899707534b1faedd9339d4627908abf5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cheatsheet.ipynb", "max_issues_repo_name": "dr-data/Qiskit_CheatSheet", "max_issues_repo_head_hexsha": "d527876899707534b1faedd9339d4627908abf5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cheatsheet.ipynb", "max_forks_repo_name": "dr-data/Qiskit_CheatSheet", "max_forks_repo_head_hexsha": "d527876899707534b1faedd9339d4627908abf5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 73.607615894, "max_line_length": 1406, "alphanum_fraction": 0.6359792168, "converted": true, "num_tokens": 10796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814055953761019, "lm_q2_score": 0.11920291889306492, "lm_q1q2_score": 0.033544368361672114}}
{"text": "# Circuit\n\n\n```python\nfrom discopy import grammar\nfrom pytket.qasm import circuit_to_qasm_str\nfrom pytket.circuit.display import render_circuit_jupyter\n\nfrom lambeq.ccg2discocat import DepCCGParser\nfrom lambeq.circuit import IQPAnsatz\nfrom lambeq.core.types import AtomicType\n\nN = AtomicType.NOUN\nS = AtomicType.SENTENCE\n```\n\n\n```python\ndepccg_parser = DepCCGParser()\ndiagram = depccg_parser.sentence2diagram('Alice runs')\ndiagram.draw()\n```\n\n\n```python\nansatz = IQPAnsatz({N: 1, S: 1}, n_layers=2)\ndiscopy_circuit = ansatz(diagram)\ndiscopy_circuit.draw(figsize=(10, 15))\n```\n\n\n```python\ntket_circuit = ansatz(diagram).to_tk()\n\nrender_circuit_jupyter(tket_circuit)\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n\n<style>\nbody {\n    font-family: \"roboto\", system-ui, sans-serif;\n}\n\n/* FOR DISPLAYING CIRCUITS */\n/* Main preview container */\n.circuit-preview{\n    width: 100%;\n    height: 100%;\n    padding: 20px;\n    text-align: center;\n\n    /* Define some variables */\n    --box-height: 40px;\n    --wire-col: black;\n    --c-wire-col: grey;\n}\n.circuit-preview.condensed{\n    overflow: auto;\n}\n\n.circuit-container{\n    max-width: 100%;\n    display: flex;\n    flex-flow: row wrap;\n    justify-content: center;\n    align-content: flex-start;\n    margin: auto;\n    width: fit-content;\n    background: rgba(255, 255, 255, 1);\n}\n.circuit-preview.condensed > .circuit-container{\n    flex-wrap: nowrap;\n    min-width: fit-content;\n}\n.circuit-container.nested{\n    position: relative;\n    flex-wrap: nowrap;\n    margin: -2px 0;\n}\n.nested-circuit-container{\n    display: flex;\n    overflow: auto;\n    max-width: 400px;\n    background: rgba(130,255,140,0.2);\n    outline: 1px solid darkseagreen;\n    outline-offset: -1px;\n}\n.nested-circuit-container::-webkit-scrollbar {\n    height: 0;\n    width: 0;\n}\n.nested-circuit-container > *{\n    margin: auto;\n}\n.circuit-end{\n    width: 2px;\n    height: auto;\n    border: 2px solid black;\n    margin: calc(var(--box-height)/2) 0 calc(var(--box-height)/2 + 20px);\n}\n.circuit-layer{\n    min-width: 40px;\n    width: max-content;\n    display: flex;\n    flex-flow: column nowrap;\n    flex-grow: 1;\n    justify-content: space-between;\n    align-items: stretch;\n    margin-bottom: 20px;\n}\n.circuit-container:not(.nested) > .circuit-layer:nth-child(2),\n.circuit-container:not(.nested) > .circuit-layer:nth-last-child(2),\n.circuit-container.nested > .circuit-layer:nth-child(2),\n.circuit-container.nested > .circuit-layer:nth-last-child(2),\n.gate_container.nested > .circuit-layer:first-child,\n.gate_container.nested > .circuit-layer:last-child{\n    min-width: 10px;\n}\n.nested .circuit-layer{\n    margin-bottom: 0px;\n}\n.circuit-layer.hover-highlight:not(:first-child):not(:last-child):hover{\n    background: rgba(0, 0, 0, 0.05);\n}\n.flex_wire{\n    flex-grow: 1;\n}\n/* Display qubit names at start of circuit */\n.circuit-layer.qubits{\n    flex-grow: 0;\n    color: black;\n}\n.qubit{\n    height: calc(var(--box-height) - 20px);\n    padding: 10px;\n    text-align: center;\n    font-family: monospace;\n    box-sizing: content-box;\n}\n.wire{\n    height: 0;\n    border: 1px solid var(--wire-col);\n    background: var(--wire-col);\n    margin: calc(var(--box-height)/2) 0;\n}\n.wire.transparent-wire{\n    border-color: transparent;\n    background: transparent;\n}\n\n/* Generic base for our gates */\n.gate_container{\n    position: relative;\n    min-width: fit-content;\n}\n.gate_container.nested{\n    display: flex;\n    flex-wrap: nowrap;\n}\n.gate_container.nested:after{\n    display: flex;\n    flex-wrap: nowrap;\n}\n.gate_container .classical{\n    border-color: var(--c-wire-col);\n    background: var(--c-wire-col) !important;\n}\n.gate{\n    position: relative;\n    height: calc(var(--box-height) - 16px);\n    margin: 0 9px;\n    padding: 9px 5px;\n    border: 1px solid darkseagreen;\n    border-bottom: none;\n    border-top: none;\n    text-align: left;\n    background: darkseagreen;\n    z-index: 2;\n    display: flex;\n    box-sizing: content-box;\n}\n.wire-label{\n    color: green;\n    padding: 10px 0;\n    width: fit-content;\n    height: calc(var(--box-height) - 18px);\n}\n.gate_top > .wire-label,\n.gate_bottom > .wire-label {\n    padding-top: 0;\n}\n.nested-label-layer{\n    background: darkseagreen;\n    padding: 0 5px;\n}\n\n/* Multi-qubit gates */\n.gate_bottom{\n    height: calc(var(--box-height) - 18px);\n    margin-bottom: 10px;\n    padding-bottom: 0;\n    border-bottom: 1px solid darkseagreen;\n}\n.gate_top{\n    height: calc(var(--box-height) - 18px);\n    margin-top: 10px;\n    padding-top: 0;\n    border-top: 1px solid darkseagreen;\n}\n.gate_name{\n    text-align: center;\n    flex-grow: 1;\n    color: black;\n}\n/* Single qubit gate*/\n.gate_box{\n    height: calc(var(--box-height) - 20px);\n    margin: 10px;\n    padding: 0 5px;\n    border: 1px solid darkseagreen !important;\n    text-align: center;\n}\n\n/* Special gates */\n.gate_connection {\n    position: absolute;\n    top: -3px;\n    left: -1px;\n    border: none;\n    margin: calc(var(--box-height)/2) calc(50% - 5px);\n    padding: 0;\n}\n.gate_swap {\n    height: 20px;\n    width: 20px;\n    margin: calc(var(--box-height)/2 - 6px) calc(50% - 9px);\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%270%200%2064%2064%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27currentcolor%27%3E%0A%20%20%3Cpath%20d%3D%27M60%200%20L32%2028%20L4%200%20L0%204%20L28%2032%20L0%2060%20L4%2064%20L32%2036%20L60%2064%20L64%2060%20L36%2032%20L64%204%27%20/%3E%0A%3C/svg%3E\n) center;\n    background-size: cover;\n}\n.gate_measure {\n    height: 20px;\n    width: 25px;\n    margin: calc(var(--box-height)/2 - 10px) calc(50% - 11px);\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%27-10%20-10%2084%2084%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27white%27%0A%20%20stroke%3D%22black%22%0A%20%20stroke-width%3D%224px%22%0A%3E%0A%20%20%3Cpath%20d%3D%27M63%2C63%20C63%2C32%2048%2C16%2032%2C16%20C16%2C16%201%2C32%201%2C63%20L63%2C63%27%20/%3E%0A%20%20%3Cpath%20d%3D%22M32%2C63%20L56%2C16%22%20/%3E%0A%3C/svg%3E\n) center;\n    background-size: cover;\n}\n.gate_control {\n    position: absolute;\n    top: 0;\n    left: 0;\n    border-radius: 50%;\n    width: 6px;\n    height: 6px;\n    margin: calc(var(--box-height)/2 - 3px) calc(50% - 5px);\n    padding: 0;\n    border: 2px solid black;\n    background: black;\n}\n.gate_x {\n    top: -10px;\n    left: -6px;\n    border-radius: 50%;\n    border-color: black !important;\n    width: 20px;\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%270%200%2064%2064%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27currentcolor%27%3E%0A%20%20%3Cpath%20d%3D%27M36%2064%20L36%2036%20L64%2036%20L64%2028%20L36%2028%20L36%200%20L28%200%20L28%2028%20L0%2028%20L0%2036%20L28%2036%20L28%2064%27%20/%3E%0A%3C/svg%3E\n) center;\n    background-size: cover;\n}\n.gate_reset{\n    margin: 11px 10px;\n    padding: 0 15px;\n    border: none !important;\n    border-left: 2px solid black !important;\n    background: url(\ndata:image/svg+xml;utf8,%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%27-30%200%20104%2064%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%22none%22%0A%20%20stroke%3D%22black%22%0A%20%20stroke-width%3D%224px%22%0A%3E%0A%20%20%3Cpath%20fill%3D%22darkseagreen%22%20stroke%3D%22none%22%20d%3D%22M%20-30%2032%20A%201%201%2090%200%201%2074%2032%20A%201%201%2090%200%201%20-30%2032%20Z%22/%3E%0A%20%20%3Cpath%20d%3D%22M%202%200%20L%202%2064%20Z%20M%2024%201%20L%2058%2032%20L%2024%2063%20M%2034%2034%22%20/%3E%0A%20%20%3Cpath%20d%3D%22M%2032%2034%20A%201%201%2090%200%201%2014%2034%20L%2014%2030%20A%201%201%2090%200%201%2032%2030%20Z%22%20/%3E%0A%3C/svg%3E\n) right no-repeat transparent;\n    background-size: contain;\n}\n\n/* Add wire sections coming in and out of the gate */\n.gate_in:before, .gate_in:after{\n    content: '';\n    position: absolute;\n    display: block;\n    top: calc(50% - 1px);\n    border: 1px solid var(--wire-col);\n    width: 9px;\n    height: 0;\n    background: var(--wire-col);\n    box-sizing: content-box;\n}\n.gate_in:before.classical,\n.gate_in:after.classical{\n    border-color: var(--c-wire-col);\n}\n\n.gate_in:before{\n    left: -12px;\n}\n.gate_out:after{\n    right: -12px;\n}\n.gate_top.gate_in:before, .gate_top.gate_out:after{\n    top:calc(50% - 6.5px)\n}\n.gate_bottom.gate_in:before, .gate_bottom.gate_out:after{\n    top:calc(50% + 4.5px)\n}\n\n\n.link-bottom, .link-top {\n    height: var(--box-height);\n    width: 0;\n    border: 1px solid black;\n    background: black;\n    position: absolute;\n    display: block;\n    left: calc(50% - 1px);\n    box-sizing: content-box;\n}\n.link-top{\n    top: calc(0px - var(--box-height)/2);\n}\n.link-bottom{\n    top: calc(var(--box-height)/2)\n}\n.half-link {\n    height: calc(var(--box-height) - 9px);\n}\n.half-link.link-bottom{\n    top: calc(var(--box-height)/2 + 11px)\n}\n.half-link.link-top{\n    top: calc(-2px - var(--box-height)/2);\n}\n.link-bottom.measurement{\n    width: 1px;\n    background: white;\n    border-top: none;\n    border-bottom: none;\n    height: calc(var(--box-height) + 2px);\n    z-index: 1;\n}\n</style>\n\n\n</head>\n<body>\n    <div >\n        <div class=\"circuit-preview condensed\">\n    <div class=\"circuit-container nested\">\n        <div class=\"circuit-layer qubits\">\n\n            <div class=\"qubit\">q[0]</div>\n\n            <div class=\"qubit\">q[1]</div>\n\n            <div class=\"qubit\">q[2]</div>\n\n\n            <div class=\"qubit bit\">c[0]</div>\n\n            <div class=\"qubit bit\">c[1]</div>\n\n    </div>\n\n            <div class=\"circuit-layer hover-highlight\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n        </div>\n\n            <div class=\"circuit-layer hover-highlight\">\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rx(2*Alice__n_0)</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n        </div>\n\n            <div class=\"circuit-layer hover-highlight\">\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rz(2*Alice__n_1)</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n                <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n                <div class=\"gate gate_control \"></div>\n\n            </div>\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rz(2*runs__n.r@s_0)</span>\n                </div>\n\n\n\n                <div class=\"link-top\"></div>\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n        </div>\n\n            <div class=\"circuit-layer hover-highlight\">\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rx(2*Alice__n_2)</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n        </div>\n\n            <div class=\"circuit-layer hover-highlight\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n                <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n                <div class=\"gate gate_control \"></div>\n\n            </div>\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rz(2*runs__n.r@s_1)</span>\n                </div>\n\n\n\n                <div class=\"link-top\"></div>\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n        </div>\n\n            <div class=\"circuit-layer hover-highlight\">\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n                <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n                <div class=\"gate gate_control \"></div>\n\n            </div>\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                    <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n                <div class=\"gate gate_box gate_connection gate_x\"></div>\n\n\n\n                <div class=\"link-top\"></div>\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n        </div>\n\n            <div class=\"circuit-layer hover-highlight\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n        <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection gate_measure\"></div>\n    </div>\n\n            <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n    </div>\n\n            <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n    </div>\n\n        <div class=\"gate_container\">\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n        </div>\n\n            <div class=\"circuit-layer hover-highlight\">\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n        </div>\n\n            <div class=\"circuit-layer hover-highlight\">\n\n\n\n\n\n\n        <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection gate_measure\"></div>\n    </div>\n\n            <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n    </div>\n\n            <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n    </div>\n\n        <div class=\"gate_container\">\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n        </div>\n\n            <div class=\"circuit-layer hover-highlight\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n        </div>\n\n        <div class=\"circuit-layer qubits\">\n\n            <div class=\"qubit\">q[0]</div>\n\n            <div class=\"qubit\">q[1]</div>\n\n            <div class=\"qubit\">q[2]</div>\n\n\n            <div class=\"qubit bit\">c[0]</div>\n\n            <div class=\"qubit bit\">c[1]</div>\n\n    </div>\n    </div>\n</div>\n    </div>\n</body>\n</html>\n\n\n\n```python\nfrom sympy import default_sort_key\n\n# Make sure you sort your symbols as they are returned as a set.\nparameters = sorted(tket_circuit.free_symbols(), key=default_sort_key)\n\nparam_dict = {p: i * 0.001 for i, p in enumerate(parameters)}\nparam_dict\n```\n\n\n\n\n    {Alice__n_0: 0.0,\n     Alice__n_1: 0.001,\n     Alice__n_2: 0.002,\n     runs__n.r@s_0: 0.003,\n     runs__n.r@s_1: 0.004}\n\n\n\n\n```python\ntket_circuit.symbol_substitution(param_dict)\nrender_circuit_jupyter(tket_circuit)\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n\n<style>\nbody {\n    font-family: \"roboto\", system-ui, sans-serif;\n}\n\n/* FOR DISPLAYING CIRCUITS */\n/* Main preview container */\n.circuit-preview{\n    width: 100%;\n    height: 100%;\n    padding: 20px;\n    text-align: center;\n\n    /* Define some variables */\n    --box-height: 40px;\n    --wire-col: black;\n    --c-wire-col: grey;\n}\n.circuit-preview.condensed{\n    overflow: auto;\n}\n\n.circuit-container{\n    max-width: 100%;\n    display: flex;\n    flex-flow: row wrap;\n    justify-content: center;\n    align-content: flex-start;\n    margin: auto;\n    width: fit-content;\n    background: rgba(255, 255, 255, 1);\n}\n.circuit-preview.condensed > .circuit-container{\n    flex-wrap: nowrap;\n    min-width: fit-content;\n}\n.circuit-container.nested{\n    position: relative;\n    flex-wrap: nowrap;\n    margin: -2px 0;\n}\n.nested-circuit-container{\n    display: flex;\n    overflow: auto;\n    max-width: 400px;\n    background: rgba(130,255,140,0.2);\n    outline: 1px solid darkseagreen;\n    outline-offset: -1px;\n}\n.nested-circuit-container::-webkit-scrollbar {\n    height: 0;\n    width: 0;\n}\n.nested-circuit-container > *{\n    margin: auto;\n}\n.circuit-end{\n    width: 2px;\n    height: auto;\n    border: 2px solid black;\n    margin: calc(var(--box-height)/2) 0 calc(var(--box-height)/2 + 20px);\n}\n.circuit-layer{\n    min-width: 40px;\n    width: max-content;\n    display: flex;\n    flex-flow: column nowrap;\n    flex-grow: 1;\n    justify-content: space-between;\n    align-items: stretch;\n    margin-bottom: 20px;\n}\n.circuit-container:not(.nested) > .circuit-layer:nth-child(2),\n.circuit-container:not(.nested) > .circuit-layer:nth-last-child(2),\n.circuit-container.nested > .circuit-layer:nth-child(2),\n.circuit-container.nested > .circuit-layer:nth-last-child(2),\n.gate_container.nested > .circuit-layer:first-child,\n.gate_container.nested > .circuit-layer:last-child{\n    min-width: 10px;\n}\n.nested .circuit-layer{\n    margin-bottom: 0px;\n}\n.circuit-layer.hover-highlight:not(:first-child):not(:last-child):hover{\n    background: rgba(0, 0, 0, 0.05);\n}\n.flex_wire{\n    flex-grow: 1;\n}\n/* Display qubit names at start of circuit */\n.circuit-layer.qubits{\n    flex-grow: 0;\n    color: black;\n}\n.qubit{\n    height: calc(var(--box-height) - 20px);\n    padding: 10px;\n    text-align: center;\n    font-family: monospace;\n    box-sizing: content-box;\n}\n.wire{\n    height: 0;\n    border: 1px solid var(--wire-col);\n    background: var(--wire-col);\n    margin: calc(var(--box-height)/2) 0;\n}\n.wire.transparent-wire{\n    border-color: transparent;\n    background: transparent;\n}\n\n/* Generic base for our gates */\n.gate_container{\n    position: relative;\n    min-width: fit-content;\n}\n.gate_container.nested{\n    display: flex;\n    flex-wrap: nowrap;\n}\n.gate_container.nested:after{\n    display: flex;\n    flex-wrap: nowrap;\n}\n.gate_container .classical{\n    border-color: var(--c-wire-col);\n    background: var(--c-wire-col) !important;\n}\n.gate{\n    position: relative;\n    height: calc(var(--box-height) - 16px);\n    margin: 0 9px;\n    padding: 9px 5px;\n    border: 1px solid darkseagreen;\n    border-bottom: none;\n    border-top: none;\n    text-align: left;\n    background: darkseagreen;\n    z-index: 2;\n    display: flex;\n    box-sizing: content-box;\n}\n.wire-label{\n    color: green;\n    padding: 10px 0;\n    width: fit-content;\n    height: calc(var(--box-height) - 18px);\n}\n.gate_top > .wire-label,\n.gate_bottom > .wire-label {\n    padding-top: 0;\n}\n.nested-label-layer{\n    background: darkseagreen;\n    padding: 0 5px;\n}\n\n/* Multi-qubit gates */\n.gate_bottom{\n    height: calc(var(--box-height) - 18px);\n    margin-bottom: 10px;\n    padding-bottom: 0;\n    border-bottom: 1px solid darkseagreen;\n}\n.gate_top{\n    height: calc(var(--box-height) - 18px);\n    margin-top: 10px;\n    padding-top: 0;\n    border-top: 1px solid darkseagreen;\n}\n.gate_name{\n    text-align: center;\n    flex-grow: 1;\n    color: black;\n}\n/* Single qubit gate*/\n.gate_box{\n    height: calc(var(--box-height) - 20px);\n    margin: 10px;\n    padding: 0 5px;\n    border: 1px solid darkseagreen !important;\n    text-align: center;\n}\n\n/* Special gates */\n.gate_connection {\n    position: absolute;\n    top: -3px;\n    left: -1px;\n    border: none;\n    margin: calc(var(--box-height)/2) calc(50% - 5px);\n    padding: 0;\n}\n.gate_swap {\n    height: 20px;\n    width: 20px;\n    margin: calc(var(--box-height)/2 - 6px) calc(50% - 9px);\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%270%200%2064%2064%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27currentcolor%27%3E%0A%20%20%3Cpath%20d%3D%27M60%200%20L32%2028%20L4%200%20L0%204%20L28%2032%20L0%2060%20L4%2064%20L32%2036%20L60%2064%20L64%2060%20L36%2032%20L64%204%27%20/%3E%0A%3C/svg%3E\n) center;\n    background-size: cover;\n}\n.gate_measure {\n    height: 20px;\n    width: 25px;\n    margin: calc(var(--box-height)/2 - 10px) calc(50% - 11px);\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%27-10%20-10%2084%2084%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27white%27%0A%20%20stroke%3D%22black%22%0A%20%20stroke-width%3D%224px%22%0A%3E%0A%20%20%3Cpath%20d%3D%27M63%2C63%20C63%2C32%2048%2C16%2032%2C16%20C16%2C16%201%2C32%201%2C63%20L63%2C63%27%20/%3E%0A%20%20%3Cpath%20d%3D%22M32%2C63%20L56%2C16%22%20/%3E%0A%3C/svg%3E\n) center;\n    background-size: cover;\n}\n.gate_control {\n    position: absolute;\n    top: 0;\n    left: 0;\n    border-radius: 50%;\n    width: 6px;\n    height: 6px;\n    margin: calc(var(--box-height)/2 - 3px) calc(50% - 5px);\n    padding: 0;\n    border: 2px solid black;\n    background: black;\n}\n.gate_x {\n    top: -10px;\n    left: -6px;\n    border-radius: 50%;\n    border-color: black !important;\n    width: 20px;\n    background: url(\ndata:image/svg+xml;utf8,%0A%3C%21--%20Generated%20with%20http%3A//jxnblk.com/paths%20--%3E%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%270%200%2064%2064%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%27currentcolor%27%3E%0A%20%20%3Cpath%20d%3D%27M36%2064%20L36%2036%20L64%2036%20L64%2028%20L36%2028%20L36%200%20L28%200%20L28%2028%20L0%2028%20L0%2036%20L28%2036%20L28%2064%27%20/%3E%0A%3C/svg%3E\n) center;\n    background-size: cover;\n}\n.gate_reset{\n    margin: 11px 10px;\n    padding: 0 15px;\n    border: none !important;\n    border-left: 2px solid black !important;\n    background: url(\ndata:image/svg+xml;utf8,%0A%3Csvg%0A%20%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%0A%20%20viewBox%3D%27-30%200%20104%2064%27%0A%20%20width%3D%2764%27%20height%3D%2764%27%0A%20%20fill%3D%22none%22%0A%20%20stroke%3D%22black%22%0A%20%20stroke-width%3D%224px%22%0A%3E%0A%20%20%3Cpath%20fill%3D%22darkseagreen%22%20stroke%3D%22none%22%20d%3D%22M%20-30%2032%20A%201%201%2090%200%201%2074%2032%20A%201%201%2090%200%201%20-30%2032%20Z%22/%3E%0A%20%20%3Cpath%20d%3D%22M%202%200%20L%202%2064%20Z%20M%2024%201%20L%2058%2032%20L%2024%2063%20M%2034%2034%22%20/%3E%0A%20%20%3Cpath%20d%3D%22M%2032%2034%20A%201%201%2090%200%201%2014%2034%20L%2014%2030%20A%201%201%2090%200%201%2032%2030%20Z%22%20/%3E%0A%3C/svg%3E\n) right no-repeat transparent;\n    background-size: contain;\n}\n\n/* Add wire sections coming in and out of the gate */\n.gate_in:before, .gate_in:after{\n    content: '';\n    position: absolute;\n    display: block;\n    top: calc(50% - 1px);\n    border: 1px solid var(--wire-col);\n    width: 9px;\n    height: 0;\n    background: var(--wire-col);\n    box-sizing: content-box;\n}\n.gate_in:before.classical,\n.gate_in:after.classical{\n    border-color: var(--c-wire-col);\n}\n\n.gate_in:before{\n    left: -12px;\n}\n.gate_out:after{\n    right: -12px;\n}\n.gate_top.gate_in:before, .gate_top.gate_out:after{\n    top:calc(50% - 6.5px)\n}\n.gate_bottom.gate_in:before, .gate_bottom.gate_out:after{\n    top:calc(50% + 4.5px)\n}\n\n\n.link-bottom, .link-top {\n    height: var(--box-height);\n    width: 0;\n    border: 1px solid black;\n    background: black;\n    position: absolute;\n    display: block;\n    left: calc(50% - 1px);\n    box-sizing: content-box;\n}\n.link-top{\n    top: calc(0px - var(--box-height)/2);\n}\n.link-bottom{\n    top: calc(var(--box-height)/2)\n}\n.half-link {\n    height: calc(var(--box-height) - 9px);\n}\n.half-link.link-bottom{\n    top: calc(var(--box-height)/2 + 11px)\n}\n.half-link.link-top{\n    top: calc(-2px - var(--box-height)/2);\n}\n.link-bottom.measurement{\n    width: 1px;\n    background: white;\n    border-top: none;\n    border-bottom: none;\n    height: calc(var(--box-height) + 2px);\n    z-index: 1;\n}\n</style>\n\n\n</head>\n<body>\n    <div >\n        <div class=\"circuit-preview condensed\">\n    <div class=\"circuit-container nested\">\n        <div class=\"circuit-layer qubits\">\n\n            <div class=\"qubit\">q[0]</div>\n\n            <div class=\"qubit\">q[1]</div>\n\n            <div class=\"qubit\">q[2]</div>\n\n\n            <div class=\"qubit bit\">c[0]</div>\n\n            <div class=\"qubit bit\">c[1]</div>\n\n    </div>\n\n            <div class=\"circuit-layer hover-highlight\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n        </div>\n\n            <div class=\"circuit-layer hover-highlight\">\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rx(0.0)</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n        </div>\n\n            <div class=\"circuit-layer hover-highlight\">\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rz(0.002)</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n                <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n                <div class=\"gate gate_control \"></div>\n\n            </div>\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rz(0.006)</span>\n                </div>\n\n\n\n                <div class=\"link-top\"></div>\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n        </div>\n\n            <div class=\"circuit-layer hover-highlight\">\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rx(0.004)</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n        </div>\n\n            <div class=\"circuit-layer hover-highlight\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n                <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n                <div class=\"gate gate_control \"></div>\n\n            </div>\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">Rz(0.008)</span>\n                </div>\n\n\n\n                <div class=\"link-top\"></div>\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n        </div>\n\n            <div class=\"circuit-layer hover-highlight\">\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n                <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n                <div class=\"gate gate_control \"></div>\n\n            </div>\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                    <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n                <div class=\"gate gate_box gate_connection gate_x\"></div>\n\n\n\n                <div class=\"link-top\"></div>\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n        </div>\n\n            <div class=\"circuit-layer hover-highlight\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n        <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection gate_measure\"></div>\n    </div>\n\n            <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n    </div>\n\n            <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n    </div>\n\n        <div class=\"gate_container\">\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n        </div>\n\n            <div class=\"circuit-layer hover-highlight\">\n\n\n\n\n\n\n\n            <div class=\"gate_container nested\">\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n        <div class=\"gate_container\">\n\n                <div class=\"gate gate_box gate_in gate_out \">\n                    <span class=\"gate_name\">H</span>\n                </div>\n\n\n\n        </div>\n        <div class=\"flex_wire\">\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        </div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n        </div>\n\n            <div class=\"circuit-layer hover-highlight\">\n\n\n\n\n\n\n        <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection gate_measure\"></div>\n    </div>\n\n            <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n    </div>\n\n            <div class=\"gate_container\">\n\n            <div class=\"link-bottom measurement\"></div>\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n    </div>\n\n        <div class=\"gate_container\">\n\n\n\n        <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n        <div class=\"gate gate_connection \"></div>\n    </div>\n\n\n\n\n\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n        </div>\n\n            <div class=\"circuit-layer hover-highlight\">\n\n\n\n\n\n\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire \"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n            <div class=\"gate_container\">\n        <div class=\"wire classical\"></div>\n\n    </div>\n\n\n\n\n\n\n\n        </div>\n\n        <div class=\"circuit-layer qubits\">\n\n            <div class=\"qubit\">q[0]</div>\n\n            <div class=\"qubit\">q[1]</div>\n\n            <div class=\"qubit\">q[2]</div>\n\n\n            <div class=\"qubit bit\">c[0]</div>\n\n            <div class=\"qubit bit\">c[1]</div>\n\n    </div>\n    </div>\n</div>\n    </div>\n</body>\n</html>\n\n", "meta": {"hexsha": "22dfda63de00e761df7c77ee0c8793237330faed", "size": 127390, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/examples/circuit.ipynb", "max_stars_repo_name": "y-richie-y/binder-test", "max_stars_repo_head_hexsha": "7d08d3892d204d382903ccadf6c9a8d4d7c0f35e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/examples/circuit.ipynb", "max_issues_repo_name": "y-richie-y/binder-test", "max_issues_repo_head_hexsha": "7d08d3892d204d382903ccadf6c9a8d4d7c0f35e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/examples/circuit.ipynb", "max_forks_repo_name": "y-richie-y/binder-test", "max_forks_repo_head_hexsha": "7d08d3892d204d382903ccadf6c9a8d4d7c0f35e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.0556760665, "max_line_length": 33656, "alphanum_fraction": 0.5099301358, "converted": true, "num_tokens": 12864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.07263670234578153, "lm_q1q2_score": 0.033486738575319544}}
{"text": "```python\n# This cell is mandatory in all Dymos documentation notebooks.\nmissing_packages = []\ntry:\n    import openmdao.api as om\nexcept ImportError:\n    if 'google.colab' in str(get_ipython()):\n        !python -m pip install openmdao[notebooks]\n    else:\n        missing_packages.append('openmdao')\ntry:\n    import dymos as dm\nexcept ImportError:\n    if 'google.colab' in str(get_ipython()):\n        !python -m pip install dymos\n    else:\n        missing_packages.append('dymos')\ntry:\n    import pyoptsparse\nexcept ImportError:\n    if 'google.colab' in str(get_ipython()):\n        !pip install -q condacolab\n        import condacolab\n        condacolab.install_miniconda()\n        !conda install -c conda-forge pyoptsparse\n    else:\n        missing_packages.append('pyoptsparse')\nif missing_packages:\n    raise EnvironmentError('This notebook requires the following packages '\n                           'please install them and restart this notebook\\'s runtime: {\",\".join(missing_packages)}')\n```\n\n# Constraints\n\nNow that we've shown how to add degrees of freedom to a system with variables in the form of\ntime, states, and controls, we need to look at how to constrain the system.  In optimal control,\nconstraints typically come in two flavors:  boundary constraints and path constraints.\n\nAs OpenMDAO components, outputs of Dymos Phases can be constrained using OpenMDAO's `add_constraint` method, but Dymos Phases provide their own methods to make defining these constraints somewhat simpler.\n\n##  Boundary Constraints\n\nBoundary constraints are constraints on a variable value at the start or end of a phase.  There\nare a few different ways to impose these in Dymos, each with slightly different behavior.\n\nLet's consider that we want to solve for the elevation angle that results in the maximum possible\nrange flown by a cannonball.  In this situation we have some set of initial conditions that are\nfixed.\n\n\\begin{align}\n    t_0 &= 0 \\, \\mathrm{s} \\\\\n    x_0 &= 0 \\, \\mathrm{m} \\\\\n    y_0 &= 0 \\, \\mathrm{m} \\\\\n    v_0 &= 100 \\, \\frac{\\mathrm{m}}{\\mathrm{s}}\n\\end{align}\n\nThe first, most obvious way to constrain fixed values is to remove them from the optimization problem altogether.\n\nFor time, this is done using the `fix_initial` or `fix_duration` arguments to `set_time_options`.\nThis also allows `t_initial` and `t_duration` to be provided from an external source via connection, if so desired.\n\nFor states and controls, the situation is slightly different.\nRather than providing initial and final values, similar to the way time is handled, the implicit simulation techniques must\nbe provided state values at the state discretization nodes and control values at *all* nodes.\nInstead, for states and controls, the user specifies `fix_initial=True` or `fix_final=True`.\n\nRemoving constrained values from the optimization has the following pros and cons.\nOn the pro side, we're making the optimization problem smaller by omitting them.\nOn the con side, the optimizer has absolutely no freedom to move these values around even a little.\nThis can sometimes lead to failure modes that aren't necessarily obvious, especially to new users.\n\nThe following example solves the brachistochrone problem by omitting the initial time and initial state, as well as the final position state from the optimization.\n\nThe second method for bounding initial/final time, states, or controls is to leave them in the\noptimization problem but to constrain only their initial or final values.  For time, this is\naccomplished with the options `initial_bounds` and `duration_bounds`.  Each of these takes a tuple\nof `(lower, upper)` values that the optimizer must obey when providing new variable values.  Note\nthat since states and controls may be vector valued, lower and upper may themselves be iterable.\nTo *pin* the value of a state, time, or control to a value just set lower and upper to the same\nvalue.\n\nAs for the pros and cons of this technique, its largely similar to that for the first technique,\nbut it's somewhat optimizer dependent.  Some optimizers *may* allow bounds on design variables to\nbe violated slightly (to some small tolerance).  In theory this could alleviate some of the issues\nwith omitting a design variable altogether, but in practice that's unlikely.\n\nThe first two options work by imposing bounds (or by not providing a variable to the optimizer\naltogether).  The third option is to pose bound constraints as actual constraints on the NLP.\nThis is accomplished with the `add_boundary_constraint` method on Phases.\n\nThe downside of this technique is that it makes the NLP problem larger, though not by much.  On\nthe plus side, this method allows the user to constrain any output within the ODE.  If the user\nneeds to constrain an auxiliary output, this is the only option.  It may also behave somewhat better\nin certain circumstances.  Depending on scaling, the NLP may ensure that collocation defects are\nsatisfied before forcing an infeasible boundary constraint to be satisfied, for instance.\n\nIn conclusion, while using `fix_initial=True` for problems with fixed initial conditions is not a bad solution, the generality of `add_boundary_constraint`, especially for terminal constraints that risk being over-constrained, makes it a good first-choice in those situations.\nIn forward-shooting phases (`solve_segments='forward'`) only the initial values of the states are design variables for the optimizer.\nAs such, simple bounds on final state values are not possible in those situations, and `add_boundary_constraint` must be used instead.\n\n##  Path Constraints\n\nThe second class of constraints supported by Dymos are *path* constraints, so called because they are imposed throughout the entire phase.\nLike bound constraints, path constraints can be imposed on design variables using simple bounds.\nThis is accomplished using the `lower` and `upper` arguments to `add_state`, `add_control`, and `add_parameter`.\n(Since time is monotonically increasing or decreasing the notion of a path constraint is irrelevant for it).\n\nFor vector-valued states and controls, lower/upper should be dimensioned the same as state or control.\nIf given as a scalar, it will be applied to all values in the state or control.\n\n```{Note}\nBounds on states in Gauss-Lobatto Phases are **not** equivalent to path constraints.\nThe values of states in Gauss-Lobatto phases are provided at only the state-transcription nodes and then interpolated to the collocation nodes.\nTherefore, the bounds will have no impact on these interpolated values which therefore may not satisfy the bounds, as one might expect.\n``` \n\nPhases also support the `add_path_constraint` method, which imposes path constraints as constraints in the NLP problem.\nAs with `add_bound_constraint`, the `add_path_constraint` method is the only option for path constraining an output of the ODE.\n\nThe downside of path constraints is that they add a considerable number of constraints to the NLP problem and thus may negatively impact performance, although this is generally minor for many problems.\n\n", "meta": {"hexsha": "b3b0f288b3391275e8081dfb08af1b8fc8c17f25", "size": 9018, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/dymos_book/features/phases/constraints.ipynb", "max_stars_repo_name": "yonghoonlee/dymos", "max_stars_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/dymos_book/features/phases/constraints.ipynb", "max_issues_repo_name": "yonghoonlee/dymos", "max_issues_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-05-24T15:14:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-28T21:12:55.000Z", "max_forks_repo_path": "docs/dymos_book/features/phases/constraints.ipynb", "max_forks_repo_name": "yonghoonlee/dymos", "max_forks_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.7368421053, "max_line_length": 285, "alphanum_fraction": 0.6733200266, "converted": true, "num_tokens": 1522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30074557894124154, "lm_q2_score": 0.11124120282447522, "lm_q1q2_score": 0.033455299945566876}}
{"text": "```python\nfrom IPython.display import Image \nImage('../../../python_for_probability_statistics_and_machine_learning.jpg')\n```\n\n\n\n\n    \n\n    \n\n\n\n[Python for Probability, Statistics, and Machine Learning](https://www.springer.com/fr/book/9783319307152)\n\n# Conditional Expectation as Projection\n\nNow that we understand projection methods geometrically, we can apply\nthem to conditional probability. This is the *key* concept that ties\nprobability to geometry, optimization, and linear algebra. \n\n### Inner Product for Random Variables\n\n From our previous work on projection for vectors in\n$\\mathbb{R}^n$, we have a good geometric grasp on how projection is related to\nMinimum Mean Squared Error (MMSE). By one abstract step, we can carry\nall of our geometric interpretations to the space of random variables.\nFor example, we previously noted that at the point of projection, we had the\nfollowing orthogonal (i.e.,  perpendicular vectors) condition,\n\n$$\n( \\mathbf{y} - \\mathbf{v}_{opt} )^T \\mathbf{v} = 0\n$$\n\n which by noting the inner product slightly more abstractly as\n$\\langle\\mathbf{x},\\mathbf{y} \\rangle = \\mathbf{x}^T \\mathbf{y}$, we can\nexpress as\n\n$$\n\\langle \\mathbf{y} - \\mathbf{v}_{opt},\\mathbf{v} \\rangle = 0\n$$\n\n and by defining the inner product for the random variables\n$X$ and $Y$ as\n\n$$\n\\langle X,Y \\rangle = \\mathbb{E}(X Y)\n$$\n\n we have the same relationship:\n\n$$\n\\langle X-h_{opt}(Y),Y \\rangle = 0\n$$\n\n which holds not for vectors in $\\mathbb{R}^n$, but for random\nvariables $X$ and $Y$ and functions of those random variables. Exactly why this\nis true is technical, but it turns out that one can build up the *entire theory\nof probability* this way [[edward1987radically]](#edward1987radically), by using the expectation as\nan inner product.\n\nFurthermore, by abstracting out the inner product concept, we have connected\nminimum-mean-squared-error (MMSE) optimization problems, geometry, and random\nvariables.  That's  a lot of mileage to get a out of an abstraction and it\nenables us to shift between these interpretations to address real problems.\nSoon, we'll do this with some examples, but first we collect the most important\nresult that flows naturally from this abstraction.\n\n### Conditional Expectation as Projection\n\nThe conditional expectation is the minimum mean squared error (MMSE) solution\nto the following problem [^proof]:\n\n$$\n\\min_h \\int_{\\mathbb{R}} (x - h(y) )^2 dx\n$$\n\n with the minimizing $h_{opt}(Y) $ as\n\n$$\nh_{opt}(Y) = \\mathbb{E}(X|Y)\n$$\n\n[^proof]: See appendix for proof using the Cauchy-Schwarz inequality.\n\n which is another way of saying that among all possible functions\n$h(Y)$, the one that minimizes the MSE is $ \\mathbb{E}(X|Y)$. From our previous discussion on projection, we noted that\nthese MMSE solutions can be thought of as projections onto a subspace that\ncharacterizes $Y$. For example, we previously noted that at the point of\nprojection, we have perpendicular terms,\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:ortho\"></div>\n\n$$\n\\begin{equation}\n\\langle X-h_{opt}(Y),Y \\rangle = 0\n\\end{equation}\n\\label{eq:ortho} \\tag{1}\n$$\n\n but since we know that the MMSE solution\n\n$$\nh_{opt}(Y) = \\mathbb{E}(X|Y)\n$$\n\n we have by direct substitution,\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:ortho_001\"></div>\n\n$$\n\\begin{equation}\n\\mathbb{E}(X-\\mathbb{E}(X|Y),Y) = 0\n\\end{equation}\n\\label{eq:ortho_001} \\tag{2}\n$$\n\n That last step seems pretty innocuous, but it ties MMSE to\nconditional expectation to the inner project abstraction, and in so doing,\nreveals the conditional expectation to be a projection operator for random\nvariables. Before we develop this further, let's grab some quick dividends.\nFrom the previous equation, by linearity of the expectation, we obtain,\n\n$$\n\\mathbb{E}(X Y) =  \\mathbb{E}(Y \\mathbb{E}(X|Y))\n$$\n\n which is the so-called *tower property* of the expectation. Note that\nwe could have found this by using the formal definition of conditional\nexpectation,\n\n$$\n\\mathbb{E}(X|Y) = \\int_{\\mathbb{R}^2} x \\frac{f_{X,Y}(x,y)}{f_Y(y)} dx dy\n$$\n\n and brute-force direct integration,\n\n$$\n\\mathbb{E}(Y \\mathbb{E}(X|Y)) = \\int_{\\mathbb{R}} y \\int_{\\mathbb{R}} x \\frac{f_{X,Y}(x,y)}{f_Y(y)}  f_Y(y) dx dy\n$$\n\n$$\n\\\n                              =\\int_{\\mathbb{R}^2} x y f_{X,Y}(x,y) dx dy\n$$\n\n$$\n\\\n                              =\\mathbb{E}( X Y)\n$$\n\n which is not very geometrically intuitive. This lack of geometric\nintuition makes it hard to apply these concepts and keep track of these\nrelationships. \n\nWe can keep pursuing this analogy and obtain the length of the error term \nfrom the orthogonality property of the MMSE solution as,\n\n$$\n\\langle X-h_{opt}(Y),X-h_{opt}(Y)\\rangle = \\langle X,X  \\rangle - \\langle h_{opt}(Y),h_{opt}(Y)  \\rangle\n$$\n\n and then by substituting all the notation we obtain\n\n$$\n\\mathbb{E}(X-  \\mathbb{E}(X|Y))^2 = \\mathbb{E}(X)^2 - \\mathbb{E}(\\mathbb{E}(X|Y) )^2\n$$\n\n which would be tough to compute by direct integration.  \n\nTo formally establish that $\\mathbb{E}(X|Y)$ *is* in fact *a projection operator* we\nneed to show idempotency.  Recall that idempotency means that once we project\nsomething onto a subspace, further projections do nothing. In the space of\nrandom variables, $\\mathbb{E}(X|\\cdot$) is the idempotent projection as we can\nshow by noting that\n\n$$\nh_{opt} = \\mathbb{E}(X|Y)\n$$\n\n is purely a function of $Y$, so that\n\n$$\n\\mathbb{E}(h_{opt}(Y)|Y) = h_{opt}(Y)\n$$\n\n because $Y$ is fixed, this verifies idempotency. Thus, conditional\nexpectation is the corresponding projection operator for random variables. We\ncan continue to carry over our geometric interpretations of projections for\nvectors ($\\mathbf{v}$) into random variables ($X$).  With this important\nresult, let's consider some examples of conditional expectations obtained by\nusing brute force to find the optimal MMSE function $h_{opt}$ as well as by\nusing our new perspective on conditional expectation.\n\n**Example.** Suppose we have a random variable, $X$, then what constant is closest to $X$ in\nthe sense of the mean-squared-error (MSE)? In other words, which $c \\in\n\\mathbb{R}$ minimizes the following mean squared error:\n\n$$\n\\mbox{MSE} = \\mathbb{E}( X - c )^2\n$$\n\n we can work this out many ways. First, using calculus-based optimization,\n\n$$\n\\mathbb{E}(X-c)^2=\\mathbb{E}(c^2-2 c X + X^2)=c^2-2 c \\mathbb{E}(X) + \\mathbb{E}(X^2)\n$$\n\n and then take the first derivative with respect to $c$ and solve:\n\n$$\nc_{opt}=\\mathbb{E}(X)\n$$\n\n Remember that $X$ may potentially take on many values, but this says\nthat the closest number to $X$ in the MSE sense is $\\mathbb{E}(X)$.  This is\nintuitively pleasing.  Coming at this same problem using our inner product,\nfrom Equation ref{eq:ortho_001} we know that at the point of projection\n\n$$\n\\mathbb{E}((X-c_{opt}) 1) = 0\n$$\n\n  where the $1$ represents the space of constants \nwe are projecting onto. By linearity of the expectation, gives\n\n$$\nc_{opt}=\\mathbb{E}(X)\n$$\n\n Using the projection approach, because $\\mathbb{E}(X|Y)$ is\nthe projection operator, with $Y=\\Omega$ (the entire underlying\nprobability space), we have, using the definition of conditional\nexpectation:\n\n$$\n\\mathbb{E}(X|Y=\\Omega) = \\mathbb{E}(X)\n$$\n\n This is because of the subtle fact that a random variable over the entire\n$\\Omega$ space can only be a constant.  Thus, we just worked the same problem\nthree ways (optimization, orthogonal inner products, projection).\n\n**Example.** Let's consider the following example with probability density\n$f_{X,Y}= x + y $ where $(x,y) \\in [0,1]^2$ and compute the conditional\nexpectation straight from the definition:\n\n$$\n\\mathbb{ E}(X|Y) = \\int_0^1 x \\frac{f_{X,Y}(x,y)}{f_Y(y)} dx=  \\int_0^1 x \\frac{x+y}{y+1/2} dx =\\frac{3 y + 2}{6 y + 3}\n$$\n\n That was pretty easy because the density function was so simple. Now,\nlet's do it the hard way by going directly for the MMSE solution $h(Y)$. Then,\n\n$$\n\\mbox{ MSE } = \\underset{h}\\min \\int_0^1\\int_0^1 (x - h(y) )^2 f_{X,Y}(x,y)dx dy\n$$\n\n$$\n\\\n             = \\underset{h}\\min \\int_0^1 y h^2 {\\left (y \\right )} - y h{\\left (y \\right )} + \\frac{1}{3} y + \\frac{1}{2} h^{2}{\\left (y \\right )} - \\frac{2}{3} h{\\left (y \\right )} + \\frac{1}{4} dy\n$$\n\n Now we have to find a function $h$ that is going to minimize this.\nSolving for a function, as opposed to solving for a number, is generally very,\nvery hard, but because we are integrating over a finite interval, we can use\nthe Euler-Lagrange method from variational calculus to take the derivative of\nthe integrand with respect to the function $h(y)$ and set it to zero. Using\nEuler-Lagrange methods, we obtain the following result,\n\n$$\n2 y h{\\left (y \\right )} - y + h{\\left (y \\right )} - \\frac{2}{3} =0\n$$\n\n Solving this gives\n\n$$\nh_{opt}(y)= \\frac{3 y + 2}{6 y + 3}\n$$\n\n  which is what we obtained before. Finally, we can solve this\nusing our inner product in Equation ref{eq:ortho} as\n\n$$\n\\mathbb{E}((X-h(Y)) Y)=0\n$$\n\n  Writing this out gives,\n\n$$\n\\int_0^1\\int_0^1 (x-h(y))y(x+y) dx dy = \\int_0^1\\frac{1}{6}y(-3(2 y+1) h(y)+3 y+2) dy=0\n$$\n\n and the integrand must be zero,\n\n$$\n2 y + 3 y^2 - 3 y h(y) - 6 y^2 h(y)=0\n$$\n\n and solving this for $h(y)$ gives the same solution:\n\n$$\nh_{opt}(y)= \\frac{3 y + 2}{6 y + 3}\n$$\n\n Thus, doing it by the brute force integration from the definition,\noptimization, or inner product gives us the same answer; but, in general, no\nmethod is necessarily easiest because they both involve potentially difficult\nor impossible integration, optimization, or functional equation solving.  The\npoint is that now that we have a deep toolbox, we can pick and choose which\ntools we want to apply for different problems.\n\nBefore we leave this example, let's use Sympy to verify the length of the error\nfunction we found earlier for this example:\n\n$$\n\\mathbb{E}(X-\\mathbb{E}(X|Y))^2=\\mathbb{E}(X)^2-\\mathbb{E}(\\mathbb{E}(X|Y))^2\n$$\n\n that is based on the Pythagorean theorem. First, we \nneed to compute the marginal densities,\n\n\n```python\nfrom sympy.abc import y,x\nfrom sympy import integrate, simplify\nfxy = x + y                 # joint density\nfy = integrate(fxy,(x,0,1)) # marginal density\nfx = integrate(fxy,(y,0,1)) # marginal density\n```\n\n Then, we need to write out the conditional expectation,\n\n\n```python\nEXY = (3*y+2)/(6*y+3) # conditional expectation\n```\n\n Next, we can compute the left side, $\\mathbb{E}(X-\\mathbb{E}(X|Y))^2$,\nas the following,\n\n\n```python\n# from the definition\nLHS=integrate((x-EXY)**2*fxy,(x,0,1),(y,0,1)) \nLHS # left-hand-side\n```\n\n\n\n\n    -log(216)/144 + log(72)/144 + 1/12\n\n\n\n We can similarly compute the right side, $\\mathbb{E}(X)^2-\\mathbb{E}(\\mathbb{E}(X|Y))^2$,\nas the following,\n\n\n```python\n# using Pythagorean theorem\nRHS=integrate((x)**2*fx,(x,0,1))-integrate((EXY)**2*fy,(y,0,1))\nRHS # right-hand-side\n```\n\n\n\n\n    -log(216)/144 + log(72)/144 + 1/12\n\n\n\n Finally, we can verify that the left and right sides match,\n\n\n```python\nprint simplify(LHS-RHS)==0\n```\n\n    True\n\n\nIn this section, we have pulled together all the projection and least-squares\noptimization ideas from the previous sections to connect geometric notions of\nprojection from vectors in $\\mathbb{R}^n$ to random variables. This resulted in\nthe remarkable realization that the conditional expectation is in fact a\nprojection operator for random variables.  Knowing this allows to approach\ndifficult problems in multiple ways, depending on which way is more intuitive\nor tractable in a particular situation. Indeed, finding the right problem to\nsolve is the hardest part, so having many ways of looking at the same concepts\nis crucial.\n\nFor much more detailed development, the book by Mikosch\n[[mikosch1998elementary]](#mikosch1998elementary) has some excellent sections covering much of this\nmaterial with a similar geometric interpretation. Kobayashi\n[[kobayashi2011probability]](#kobayashi2011probability) does too.  Nelson [[edward1987radically]](#edward1987radically) also\nhas a similar presentation based on hyper-real numbers.\n\n## Appendix\n\nWe want to prove that we the conditional expectation is the\nminimum mean squared error minimizer of the following:\n\n$$\nJ= \\min_h \\int_{ \\mathbb{R}^2 } \\lvert X - h(Y) \\rvert^2 f_{X,Y}(x,y) dx dy\n$$\n\n We can expand this as follows,\n\n$$\n\\begin{multline*}\nJ=\\min_h \\int_{ \\mathbb{R}^2 } \\lvert X \\rvert^2 f_{X,Y}(x,y) dx dy + \\int_{ \\mathbb{R}^2 } \\lvert h(Y) \\rvert^2 f_{X,Y}(x,y) dx dy \\\\\\\n- \\int_{ \\mathbb{R}^2 } 2 X h(Y) f_{X,Y}(x,y) dx dy\n\\end{multline*}\n$$\n\n To minimize this, we have to maximize the following:\n\n$$\nA=\\max_h \\int_{ \\mathbb{R}^2 }  X h(Y) f_{X,Y}(x,y) dx dy\n$$\n\n Breaking up the integral using the definition of conditional expectation\n\n<!-- Equation labels as ordinary links -->\n<div id=\"_auto1\"></div>\n\n$$\n\\begin{equation}\nA =\\max_h \\int_\\mathbb{R} \\left(\\int_\\mathbb{R} X  f_{X|Y}(x|y) dx \\right)h(Y) f_Y(y) dy \n\\label{_auto1} \\tag{3}\n\\end{equation}\n$$\n\n<!-- Equation labels as ordinary links -->\n<div id=\"_auto2\"></div>\n\n$$\n\\begin{equation} \\\n=\\max_h \\int_\\mathbb{R} \\mathbb{E}(X|Y) h(Y)f_Y(Y) dy \n\\label{_auto2} \\tag{4}\n\\end{equation}\n$$\n\n From properties of the Cauchy-Schwarz inequality, we know that the\nmaximum happens when $h_{opt}(Y) = \\mathbb{E}(X|Y)$, so we have found the\noptimal $h(Y)$ function as:\n\n$$\nh_{opt}(Y) = \\mathbb{E}(X|Y)\n$$\n\n which shows that the optimal function is the conditional expectation.\n\n\n```python\n\n```\n", "meta": {"hexsha": "0a1cf781eeaab536e2a1f9cdec217dcb6d65a46f", "size": 138989, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapters/probability/notebooks/Conditional_Expectation_Projection.ipynb", "max_stars_repo_name": "nsydn/Python-for-Probability-Statistics-and-Machine-Learning", "max_stars_repo_head_hexsha": "d3e0f8ea475525a694a975dbfd2bf80bc2967cc6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 570, "max_stars_repo_stars_event_min_datetime": "2016-05-05T19:08:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:09:19.000Z", "max_issues_repo_path": "chapters/probability/notebooks/Conditional_Expectation_Projection.ipynb", "max_issues_repo_name": "crlsmcl/https-github.com-unpingco-Python-for-Probability-Statistics-and-Machine-Learning", "max_issues_repo_head_hexsha": "6fd69459a28c0b76b37fad79b7e8e430d09a86a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-05-12T22:18:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-06T14:37:06.000Z", "max_forks_repo_path": "chapters/probability/notebooks/Conditional_Expectation_Projection.ipynb", "max_forks_repo_name": "crlsmcl/https-github.com-unpingco-Python-for-Probability-Statistics-and-Machine-Learning", "max_forks_repo_head_hexsha": "6fd69459a28c0b76b37fad79b7e8e430d09a86a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 276, "max_forks_repo_forks_event_min_datetime": "2016-05-27T01:42:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T11:20:27.000Z", "avg_line_length": 144.7802083333, "max_line_length": 114721, "alphanum_fraction": 0.8869191087, "converted": true, "num_tokens": 4037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2309197735148081, "lm_q2_score": 0.14414884935602926, "lm_q1q2_score": 0.03328681964571447}}
{"text": "The associated codes to run this notebook can be found [here](https://github.com/prodipta/tictactoe). Clone the repo, and open this notebook (notebooks/tic_tac_toe.ipynb).\n\n## Reinforcement Learning: An Introduction\n\nReinforcement learning is a machine learning algorithm for general purpose decision making. But before we understand and appreciate this, let's review our decision making process\n\n### Exhibit 1: Evaluating decisions based on outcome\n\n\n`World T20 Final 2007`: Ace spinner **Harbhajan Singh** had an over left but Dhoni chose medium-pacer **Joginder Sharma** to bowl the last over. **Misbah-ul-Haq** was strong at crease.\n\n\n\n\n`World Cup 2011 India vs South Africa`: Ace spinner **Harbhajan Singh** had an over left but Dhoni chose medium-pacer **Ashish Nehra** to bowl the last over. **Robin Peterson** was strong at crease.\n\n\n\nSports critics and media absolutely loved the first decision, and similarly totally rejected the second one.\n\n\nToo often we evaluate our past decisions based on the outcomes. We completely forget the situations we were in when the decisions were taken, and the information we had till at the point. The above two decisions are, arguably, very similar. They had very different outcome. And were judged very differently by the public.\n\n### Exhibit 2: Short Term or Long term Rewards?\n\n`The Standford Marshmallow Experiment`: The [experiment](https://en.wikipedia.org/wiki/Stanford_marshmallow_experiment#Original_Stanford_experiment) was first carried out in 1972 in Standford University. 32 children, under isolation with little distractions, were offered a treat (cookies or five pretzel sticks). The researchers explained to the children that they could eat the treat now and leave the room. But if they waited 15 minutes without eating the immedeate treat, they would get another.\n\n\n\nOften the rewards are realized in the future, but we need to act now. This is known as `delayed gratification` in economics and behavioural science. The above is a simple two period case. In real life, everyday we face a continuous choice of multi-period version of this game\n\n- Stock has rallied (sold-off) significantly, shall I sell now at a small profit (loss) now, or wait for larger profit in future?\n- Shall I drink 10 rupess tea now, or let go for a month and pay off my loan shark?\n\nSince rewards can realize over different time horizon, we need a way to compare them consistently **now**. A standard way of doing it is through discounting (usually time-consistent discounting i.e. `exponential` discounting, but in real life we also see `hyperbolic` discounting). This is also known as time-preference or temporal preference in economics or behavioural science. This time discouting is the bedrock of all our financial system - NPV\n\n- bonus: what is the fundamental underlying assumption for discounting in financial markets (e.g. asset pricing, discount cashflow valuation, NPV project valuation etc.)?\n\n\n### Exhibit 3: Risk vs Reward\n\nYou are managing a risky project<sup>[1]</sup> at work. If it works out well, you can get a good promotion. The chances are, if it gets derailed, you may get sidelined. How you make your decisions?\n\n\n\n- In a knock-out round of a poker tournament, do you jam your small pocket pairs against a button raiser? What if you go bust?\n- how to balance risk vs. reward\n\nThe balancing of risk and rewards under uncertainty is another major criteria for a good decision making process\n\n### Exhibit 4: Multi-armed bandits\n\nA gambler is deciding to play a row of slot machines - each with unknown, but different characteristics (win probability, payout etc.). The problem is how to distribute time and capital among different machines to try and find the best. This is a classifc decision making problem - exploration vs. exploitation\n\n\n\n- To settle down with the current person you are dating or look for another?\n- To select the current candidate who is good enough, or interview more for a better fit\n\n### How to make a good decisions\n\n- Evaluate (both prospectively and retrospectively) your decisions based on `information you have at the time of decision`\n- For multi-period delayed rewards, define a `discouting function` to be able to compare and chose temoporally distributed rewards\n- For uncertain environments, define a `reward function` to balance risk and reward.\n- For uncertain environments, device a strategy to balance `exploration` against `exploitation`.\n\n\n\n## General Problem Statement\n\nYou are interacting with a `system`. At each `state` of the system, you must choose an allowed `action`. After each such `action`, you may or may not receive an immediate `reward` (or penalty, a negative reward). After an uncertain n `steps` (or `state` changes), the `system` reaches its final `state` and you realize the final `reward` (or penalty).\n\n- In financial investing, the `system` is the market itself. Your `action` is either buy, sell or hold of the stocks in the universe, and rewards are profit and loss.\n\n- In a game of poker, the `system` is your opponents collectively, (only one in heads-up poker, a mathematically easier version). Your `actions` are fold, bet, call, raise or re-raise. Your rewards are realized only after each hands (or at the end of the whole game if it is a tournament)\n\n- In a game of chess, the `system` is the board and the opponent. The `state` is the current configuration of the board. Your `actions` are defined by the chess rules and your remaining chess pieces. The `reward` is received only when the game is over.\n\nAll these decision making problems are similar in nature, although they vary greatly with each parameters - `state`, `actions` and `rewards`. \n\nFor example, in tic-tac-toe, the `state` are finite and relatively small. In chess, `states` are much more numerous, but they are still somewhat manageable. In poker, `states` are never known fully and can only be guessed - you do not get to see your opponents hand. In markets `state` is infinite - an endless combinations of varius market factors, prices and sentiments etc.\n\nWe aim to find a generalized approach to solve such problems. We try to crack the tic-tac-toe game.\n\n## Tic-Tac-Toe: A demo for reinforcement learning\n\nfrom [wikipedia](https://en.wikipedia.org/wiki/Tic-tac-toe): Tic-tac-toe (American English), noughts and crosses (Commonwealth English), or Xs and Os is a paper-and-pencil game for two players, X and O, who take turns marking the spaces in a 3\u00d73 grid. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row is the winner.\n\n### The decision making problem\n\nSuppose we start with the 'X'. The decision problem is choose a series of action that leads to a potential win. The `reward` - win, loss, or a draw, comes at the end of the game. To get there, we need to make a series of decisions where we do not get immedeate clue if our decision was correct or wrong. What are the way(s) to create an algorithm to win?\n\n### A common man's approach\n\nStart with a random choice, say top corner. Then, each time it is our turn to play, do the following in order:\n\n- block an impending triad completion of our opponent, if any\n- Else, we put a 'X' to that makes `possible for us to complete a triad in the next move` in case our opponent does not notice it.\n\nThis is probably be a decent strategy for a beginner.\n\n### A mathametical approach\n\nProposed in 1972, by [Newell and Simon](https://en.wikipedia.org/wiki/Tic-tac-toe#Strategy). It is a collection of heuristics that relies on combinatorics. The [game complexity](https://en.wikipedia.org/wiki/Game_complexity#:~:text=For%20tic%2Dtac%2Dtoe%2C,have%20a%20row%20of%20three.) is relatively mild - total 19,683 possible configuration - reduces drastically if we remove invalid configurations (e.g.  five crosses and no noughts).\n\n### What about variations\n\nThis strategies quickly become more complicated as we expand the game - say `nxn` board with first `k` to finish is a winner. It can also be complicated, e.g. instead of only two characters what if we have 8, each with different rules (chess!). Or say the two players are playing on private boards not visible to each other (not a very good example in this case, these types of games are called `incomplete information`).\n\n### Can we come up with something more general\n\nRemeber the theme of `ML and AI`. We do not want to solve each problems with specialized algorithms. Rather we want to use standardized algorithms to solve many problems (of similar class) with different inputs. And this class of problems are general decision making problems with delayed reward\n\n## The one-size-fits-all ML pipeline\n\nWhat if we use the standardized ML approach. We generate random simulations for many many games and tabulate each board configuration and the action taken, and label it if it was positive or negative. Then we use this labelled dataset to fit a supervised model. Then use the model to decide for us.\n\n\n\n### Design questions\n\n- how to capture the data? How we capture the board configuration (it is a 3X3 matrix)\n- how to label the data? We do not know the immedeate reward at each action step\n- how to select features?\n- how to choose the algorithm? What should be a good loss function? What should be the estimator (that fits the data to the observations, e.g. a `random forest`, or `svm` model or a `deep NN`?\n\n## Generating Input data\n\nHow can we generate input data for our current problem? If we know what data we need, we can look for a vendor that supplies such data. What data we need?\n\n### What data we need\n\nFor our problem we need labelled set of data that tells us what was the board configuration at a certain step when we had the turn, what actions we took, and what was the reward. No one unfortunately sells such data. The good news is, we can easily generate it ourselves by simulation\n\n### Developing the Simulation\n\nTo simulate a tic-tac-toe game, we can code the game in a Python class. The features that we are looking for is something like below:\n\n```python\nclass Board():\n    \"\"\"\n        A board class to simulate our tic-tac-toe game. We need to identify the players, say 'X' is the first player, 'O' is the second player.\n    \"\"\"\n    def __init__(self, player1='X', player2='O', blank=' '):\n        pass\n    \n    @property\n    def state(self):\n        \"\"\" returns the current configuration of the board. \"\"\"\n        pass\n    \n    @property\n    def winner(self):\n        \"\"\" returns the winner if any, or `None`. \"\"\"\n        pass\n    \n    @property\n    def moves(self):\n        \"\"\" returns the current available moves left in the board.\"\"\"\n        pass\n    \n    @property\n    def game_over(self):\n        \"\"\" if the game is over. \"\"\"\n        pass\n        \n    def step(self, player, move):\n        \"\"\" simulate the game, taking input from `player` and generating random move from the other player. \"\"\"\n        pass\n```\n\nWe have already coded such a class in the `board.py` file. So let's import and simulate games to generate some data. We need to store the input board configuration, the action and the reward. The board can be represented as a three lines of 3 cells each. We will store the configuration as `flattened` version of this 3x3 matrix (so 3x3 matrix becomes a 1x9 vector). Similarly, action identifies a particular cell to mark - it is a combination of a (row, column) `tuple`. We will store this as a 1x2 vector. So these two stacked together horizontally, our features vector become 1x11.\n\nFor the rewards, we will mark +100 if we won in that step, -100 if we lost in that step, otherwise (game not over, or it is a draw) we will mark 0.\n\nLet's see the simulation code. We start with setting our paths and importing the classes we will need.\n\n\n```python\nimport os\nimport sys\nimport_path = os.path.abspath(os.path.join('..'))\nif import_path not in sys.path:\n    sys.path.append(import_path)\n\nimport numpy as np\nimport pandas as pd\nfrom tictactoe.board import Board\nfrom tictactoe.agent import Agent\n```\n\n## Play some games\n\nLet's simulate some games using the `Board` class we just generated. Below we instantiate a `Board` object (the `board` variable). We choose to play player `X` (first mover). Then we `step` through the board simulation till the game is over.\n\nIn the next cell, we generate the data as we discussed before.\n\n\n```python\nboard = Board('X','O', ' ')\nplayer = 'X'\nwhile not board.game_over:\n    board.step(player, None)\n    \nprint('the winner is {}\\n'.format(board.winner))\nprint(board)\n```\n\n    the winner is O\n    \n      X  |  X  |  O  \n    -----+-----+-----\n      X  |  O  |  O  \n    -----+-----+-----\n         |  X  |  O  \n    \n\n\n## A quick benchmark\n\nBefore we start creating the data and model for our ML tic-tac-toe player, let's establish a benchmark to evaluate it against. If we play randomly (and the board plays against us randomly as well), we should have approx 1/3 changes of win, losses and draws. Since we are the first-mover, we will have slight advantage in a game like tic-tac-toe (and chess and similar full-information games). Let's simulate a games and score it when both players play randomly.\n\n\n```python\n## CAUTION: it may take a while to run, we simulate a large number of games\n\nplayer = 'X'\nN = 10000\nwins = draws = losses = 0\n        \nfor i in range(N):\n    board = Board('X','O', ' ')\n    if player != 'X':\n        board.make_random_move()\n\n    while not board.game_over:\n        choice = board.random_move()\n        _, reward, terminated = board.step(player, choice)\n        if terminated:\n            if reward == 0:\n                draws = draws + 1\n            elif reward > 0:\n                wins = wins + 1\n            else:\n                losses = losses + 1\n                    \nprint(round(wins/N,2), round(draws/N,2), round(losses/N,2))\n```\n\n    0.33 0.35 0.32\n\n\nSo, the random bench mark gives us a slight advantange (33% win against 32% loss). Let's see if we can do better with our ML model.\n\n\n```python\n### Generate the data\nplayer = 'X'\nN = 10000\nX = np.zeros((N,(9+2)))\ny = np.zeros(N)\n\nfor i in range(N):\n    board = Board('X','O', ' ')\n    if player != 'X':\n        board.make_random_move()\n\n    while not board.game_over:\n        config = np.zeros(board.board.shape)\n        config[board.board=='X'] = 1\n        config[board.board=='O'] = 0\n        config[board.board==' '] = -1\n        action = board.random_move()\n        _, reward, _ = board.step(player, action)\n        X[i,0:9] = config.flatten()\n        X[i,9:12] = np.array(action).flatten()\n        y[i] = np.sign(reward)\n        \nprint(f'X is of shape {X.shape}, y is of shape {y.shape}')\n```\n\n    X is of shape (10000, 11), y is of shape (10000,)\n\n\n## Create the model\n\nNext step is to create the model. Notice we have a `categorical` reward function. The rewards 100, -100 or 0 probably indicates levels (or classes) rather than actual (monetary) value. If this assumption is true, we have a case of `classification` problem at hand. We abhor losses more than anything, so we mark negative reward as -1, and a win or a draw is +1. This is a case of `binary classification`.\n\nWe choose a [binary cross-entropy](https://en.wikipedia.org/wiki/Cross_entropy) loss function, along with a `Random Forest` classifier. We could also have chosen a `DNN`. We split the whole data set to 70-30 as our train vs. test data.\n\n\n```python\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\nrf = RandomForestClassifier(n_estimators=500, max_depth=5, random_state=42)\nrf.fit(X_train,y_train)\nrf.score(X_test, y_test)\n```\n\n\n\n\n    0.6326666666666667\n\n\n\n## Evaluate the model\n\nNow that we have our model ready, we can run game scenarios to evaluate. We simulate each game to completion, and each turn, evaluate the predicted reward based on all possible actions (the last two in the features columns) and choose the one that does the best. Then over `N` different games we score how many we lost, won or drew.\n\n\n```python\n## CUATION: This may take a long time to run!\n\nplayer = 'X'\nN = 100\nwins = draws = losses = 0\n        \nfor i in range(N):\n    board = Board('X','O', ' ')\n    if player != 'X':\n        board.make_random_move()\n\n    while not board.game_over:\n        config = np.zeros(board.board.shape)\n        config[board.board=='X'] = 1\n        config[board.board=='O'] = 0\n        config[board.board==' '] = -1\n        \n        moves = board.moves\n        choice = board.random_move()\n        features = np.hstack([config.flatten(), np.array(choice).flatten()])\n        best = rf.predict(features.reshape(1,11))\n        for move in moves:\n            features = np.hstack([config.flatten(), np.array(move).flatten()])\n            predict = rf.predict(features.reshape(1,11))\n            if predict > best:\n                best = predict\n                choice = move\n                \n        _, reward, terminated = board.step(player, choice)\n        if terminated:\n            if reward == 0:\n                draws = draws + 1\n            elif reward > 0:\n                wins = wins + 1\n            else:\n                losses = losses + 1\n                    \nprint(round(wins/N,2), round(draws/N,2), round(losses/N,2))\n```\n\n    0.56 0.27 0.17\n\n\nThis is definitely better. But is it good enough? Can we do better?\n\n## What is the problem here?\n\nIt is not nearly good enough. Given the fact that our opponent is playing randomly, we expected to do a lot better than just 56% wins! The main problem here is our decisions are quite `myopic`, we have trained the model thus. It is not a good way to solve decision problems with delayed rewards. All our input samples were independentl. But in reality, our decisions form a chain and the reward is at the end of it. All actions in a particular game are related. We failed to capture that. This motivates us to look at these decision making problems differently\n\n## Building a decision making framework\n\nWe take a fresh approach to solve this problem. Recall our three points in good decision making: \n\n- we take decision based on the currently available information\n- we use discounting to normalize delayed rewards \n- we use risk-reward balance for risky games and\n- we follow a strategy to balance exploitation vs. exploration\n\nWhat should be our objective for decision making\n\n### Maximize the value of our decision\n\nOne good approach is to choose a series of `actions` that try and maximize the expected `reward` (expected immediate and future rewards based on current information, or mathematically, conditioned on current `state`)\n\n\\begin{align}\nV_{0}^\\pi(s) = \\mathbb E[R_{0}(s_{0},a_{0}) + \\gamma.R_{1}(s_{1},a_{1}) + \\gamma^2.R_{2}(s_{2},a_{2}) ....|s_{0}=s,\\pi]\n\\end{align}\n\nOr in other words\n\n\\begin{align}\nV_{0}^\\pi(s) = \\mathbb E\\Bigl[\\sum_n(\\gamma^n.R_{n}(s_{n},a_{n}))|s_{0}=s,\\pi\\Bigr]\n\\end{align}\n\nWe aim to find `policy` such that we maximize this expression. One issue with the above expression is that it tells us what is the expected worth of our actions, but does not tell us what to do. So let's recast the above such that the `action` is a parameter as well, not just `state`.\n\n\\begin{align}\nV_{0}^\\pi(s,a) = \\mathbb E\\Bigl[\\sum_n(\\gamma^n.R_{n}(s_{n},a_{n}))|s_{0}=s, a_{0}=a,\\pi\\Bigr]\n\\end{align}\n\nThis makes the first term deterministic, so we take this out and the expression becomes\n\n\\begin{align}\nQ_{0}^\\pi(s,a) = R_{0}(s,a) + \\mathbb E\\Bigl[\\sum_{n=1}(\\gamma^n.R_{n}(s_{n},a_{n}))|s_{0}=s, a_{0}=a,\\pi\\Bigr]\n\\end{align}\n\n### The Bellman Equation\n\nNext, we do two simple changes - first, we change the subscript of the value Q to variable time, to make the equation dynamic explicitly. Then, we notice that the second part of the above equation is just gamma times the value Q itself. So we recast a dynamic version of the above equation as follows:\n\n\\begin{align}\nQ_{t}^\\pi(s,a) = R_{t}(s,a) + \\gamma.Q_{t+1}^\\pi(s,a)\n\\end{align}\n\nFrom the above, and from Bellman's [principle of optimality](https://en.wikipedia.org/wiki/Bellman_equation), we claim that to maximize the value we must choose Q such that:\n\n\\begin{align}\nQ_{t}^\\pi(s,a) = R_{t}(s,a) + \\gamma.Max(Q_{t+1}^\\pi(s,a))\n\\end{align}\n\n### Q-learning\n\nFrom the above, we get an interesting insight. An algorithm can be developed on the following line:\n\n- We create a table (called `Q-table`) that will map our evaluations of each allowed `actions` at each `state`. We start with all zero values.\n\n- Next, at initial state, to chose our action `a`, we randomly try all allowed actions and chose the one that provides maximum immediate benifit in the next step.\n\n- We remember this favourable action by making an entry in the Q-table, and take the chosen action to move to the next step\n\n- Repeat\n\nIf we do it large enough number of times, we will have enough samples for each `(s,a)` combinations that will allow us average the value computation over and get an expected value. And if these values converge to a limit, we are done. We have created a Q-table, that has seen too many games and memorized all moves to make best judgement best on its memory.\n\nWhat we have done so far is: we have taken care of our first two principles of good decision making process - using the current information to best use, and using discounting function (`gamma`) to compare rewards across time.\n\n### The problem - being myopic \n\nNotice in the above example we consider only the immediate rewards. Since all actions in a game are connected, that means we may have chosen to leave behind some paths that had low immediate rewards but high final rewards. We were too exploitive and forgot to explore. This risks settling down on a local minima instead of a global one. \n\nOne way to avoid this is to introduce a new parameter `epsilon`. It is a fraction between 0 to 1. While choosing the next action, now we will not always choose the best on immediate rewards. With a probability of `epsilon`, we will now choose a random action. And only with probability `(1-epsilon)` we will choose the best. This gives us enough randomness in search to explore good paths that reward later. Also, we can have a high value of `epsilon` at the beginning of learning (`explorative`), and reduce (more `expoliting`) towards the end. A popular way to do this is to introduce an exponential decay of `epslion` between each batch of training.\n\nFinally, we can also have a parameter `nu` or `learning-rate`, that we use to balance between the old and new values of updates of the Q-table. Instead of overwriting the past learned value each time, we can use a fraction `nu` of the new value and `(1-nu)` of the old value for the final update. This smoothens out our learning process.\n\nHow to apply all these to our tic-tac-toe problem.\n\n\n### The Game-Agent Model\n\nThe best way to implement this is the agent mode. We already modelled the game. Now we model an `agent` or a player. We store the Q-table and let the `agent` interact with the environment to learn. In each leaning episode, the `agent` play a complete game, choosing actions based on the algorithm above and updating Q-table at each step. In the next episode, it starts with the existing Q-table and carries out further updates and learnings. Under certain [cicumstances](https://en.wikipedia.org/wiki/Markov_decision_process) this gurantess a convergence. \n\nWe have already implemented an agent in the file `agent.py`. Let's run a training on this.\n\n\n```python\na = Agent()\na.train(player='X', n=100000)\n```\n\n\n```python\na.score()\n```\n\n\n\n\n    (0.9, 0.02, 0.08)\n\n\n\nThis is a whooping improvement than the last. Our win rate is 90% compared to 56% based on the brute-force machine learning!\n\n### So where is the catch!\n\nReinforcement learning is a great method. What we discussed today is a particular version called `Q-learning`. If you followed the algorithm, you would have figured our already where we may have difficulties\n\n- First, we made assumption on convergece. This is not a big issue as such and we can always test for it. The problem is as the total `state space` (all possible states or configuration of the game) becomes larger, this also gets more difficult to ascertain\n\n- We assumed complete information about the `state space` and current `state`. This is true for tic-tac-toe. This is even true for chess. But in a game like poker, it is difficult to evaluate the states and the rewards as a large and important parts (opponets' hands) are hidden. We have only a limited visibility to the actual `state` at any given point in time.\n\n- At least in poker, the states may be hidden, but finite. That is not the case for financial markets. There is an endless possible combinations of market factors, and the `state space` is essentially infinite, in addition of being partially hidden.\n\nIn such scenarios, we cannot simply update the Q-table following the above method. However, if make parameterized version of it (i.e. moving from a table to a parameterized functions), we can train a ML estimator (like a deep neural network) learn the parameters and predict the Q-value updates.\n\nIf these predictions are good enough, we can then follow the rest of the algorithm to develop our decision bot. When we combine the `DNN` with `Q-learning`, we get what is known as `Deep Q-learning`.\n\n\n### The butterfly effect\n\n\n\nNote, we cannot pick and fit any ML model to parametrize the Q-values. If a linear parametrization fits the bill, it is all good. But for delayed rewards scenario, they will hardly do. Using non-linear parameterization can cause stability issues.\n\nQ-learning is essentially operates on a dynamic system. A characteristic of non-linear dynamic program is what is called chaos. A small change in Q can significantly change subsequent learnings and policy. This can be due to correlations between observations, and that between Q and the target (we are learning both, in a way). This can also be due to inherent random noise in a noise system (a random poker player, and of course, the market.\n\n### Tic-tac-toe vs Trading\n\nAs we noted, application of Q-learning or reinforcement learning in general, in finance is possible but not straight forward. \n\nThe first thing we need to do is to figure out a way to represent our `state space`. We can never have a complete description, like in tic-tac-toe. But we can choose a set of features (say, price moves, technical indicators and fundamental ratios, sentiments and economic data) to represent the market set. \n\nThe second thing we need to do is to define a reward function. Playing tic-tac-toe is arguably not a risky business. And games may last a few rounds. So we had a low discount rate, and considered only the rewards, not any risk (say, variance in rewards). In finance, doing that we can go bust. So it is very important to design a proper reward function. Possibly candidates are percentage returns (no risk consideration), Sharpe ratio, Return to variance ration (Kelly ratio) etc.\n\nFinally, we need to define what is an episode, i.e. what completes a `game`. Unlike tic-tac-toe, there is no natural concept of `end` here. Depending on our investment objective and horizon, we need to define the episode. It can be time-based, i.e. say a week of trading. It can be event-based, e.g. hitting a predefined profit or stoploss. There are other possibilities too.\n\nFor a more complete discussion on reinforcement learning in trading, check out the upcoming course on reinforcement learning on [Quantra](https://quantra.quantinsti.com/) \n\n_______________________________________________________________________________________________________________________________\n\n- [1] from upcoming Reinforcement Learning course on [Quantra](https://quantra.quantinsti.com/)\n- [2]. All images sourced from google\n- [3]. Disclaimer: [Quantra](https://quantra.quantinsti.com/) is from [Quantinsti](https://www.quantinsti.com/), where I work.\n\n", "meta": {"hexsha": "b0be764268dce41751c94d1c4721b6f9656e0d5d", "size": 35345, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/tic_tac_toe.ipynb", "max_stars_repo_name": "prodipta/tictactoe", "max_stars_repo_head_hexsha": "137e6f92da50ee11e5fe3061b51901bcc8536cfe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/tic_tac_toe.ipynb", "max_issues_repo_name": "prodipta/tictactoe", "max_issues_repo_head_hexsha": "137e6f92da50ee11e5fe3061b51901bcc8536cfe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/tic_tac_toe.ipynb", "max_forks_repo_name": "prodipta/tictactoe", "max_forks_repo_head_hexsha": "137e6f92da50ee11e5fe3061b51901bcc8536cfe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.9910044978, "max_line_length": 661, "alphanum_fraction": 0.6362993351, "converted": true, "num_tokens": 6636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33458944125318596, "lm_q2_score": 0.09947021121253753, "lm_q1q2_score": 0.03328168239093932}}
{"text": "```python\n#remove cell visibility\nfrom IPython.display import HTML\ntag = HTML('''\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.''')\ndisplay(tag)\n```\n\n\n\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.\n\n\n\n```python\n%matplotlib inline\nimport control\nimport numpy\nimport sympy as sym\nfrom IPython.display import display, Markdown\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\n\n\n#print a matrix latex-like\ndef bmatrix(a):\n     \"\"\"Returns a LaTeX bmatrix - by Damir Arbula (ICCT project)\n\n     :a: numpy array\n     :returns: LaTeX bmatrix as a string\n     \"\"\"\n     if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n     lines = str(a).replace('[', '').replace(']', '').splitlines()\n     rv = [r'\\begin{bmatrix}']\n     rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n     rv +=  [r'\\end{bmatrix}']\n     return '\\n'.join(rv)\n\n\n# Display formatted matrix: \ndef vmatrix(a):\n    if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n    lines = str(a).replace('[', '').replace(']', '').splitlines()\n    rv = [r'\\begin{vmatrix}']\n    rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n    rv +=  [r'\\end{vmatrix}']\n    return '\\n'.join(rv)\n\n\n#matrixWidget is a matrix looking widget built with a VBox of HBox(es) that returns a numPy array as value !\nclass matrixWidget(widgets.VBox):\n    def updateM(self,change):\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.M_[irow,icol] = self.children[irow].children[icol].value\n                #print(self.M_[irow,icol])\n        self.value = self.M_\n\n    def dummychangecallback(self,change):\n        pass\n    \n    \n    def __init__(self,n,m):\n        self.n = n\n        self.m = m\n        self.M_ = numpy.matrix(numpy.zeros((self.n,self.m)))\n        self.value = self.M_\n        widgets.VBox.__init__(self,\n                             children = [\n                                 widgets.HBox(children = \n                                              [widgets.FloatText(value=0.0, layout=widgets.Layout(width='90px')) for i in range(m)]\n                                             ) \n                                 for j in range(n)\n                             ])\n        \n        #fill in widgets and tell interact to call updateM each time a children changes value\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        #value = Unicode('example@example.com', help=\"The email value.\").tag(sync=True)\n        self.observe(self.updateM, names='value', type= 'All')\n        \n    def setM(self, newM):\n        #disable callbacks, change values, and reenable\n        self.unobserve(self.updateM, names='value', type= 'All')\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].unobserve(self.updateM, names='value')\n        self.M_ = newM\n        self.value = self.M_\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        self.observe(self.updateM, names='value', type= 'All')        \n\n                #self.children[irow].children[icol].observe(self.updateM, names='value')\n\n             \n#overlaod class for state space systems that DO NOT remove \"useless\" states (what \"professor\" of automatic control would do this?)\nclass sss(control.StateSpace):\n    def __init__(self,*args):\n        #call base class init constructor\n        control.StateSpace.__init__(self,*args)\n    #disable function below in base class\n    def _remove_useless_states(self):\n        pass\n```\n\n## Krmiljenje glave trdega diska\n\n\n\nRo\u010dica trdega diska, ki podpira bralno glavo, se vrti na viskoznem le\u017eaju, poganja pa jo poganja elektromotor; povratna vzmet s torzijske togosti $ k $ nasprotuje njenemu gibanju. Le\u017eaj ima rahlo viskozno trenje, ki je sorazmerno hitrosti vrtenja glave, s konstanto trenja $ b $. Aktuator (ro\u010dica) lahko ustvari navor $ T $ linearno sorazmeren s tokom $ I $, ki te\u010de znotraj tuljave: $ T = k_iI $. Vztrajnost ro\u010dice je $ J $. Senzor meri kotni polo\u017eaj ro\u010dice $ \\ theta $. \n\nKonstante sistema so:\n- $J = 0.001$ kg$\\text{m}^2$,\n- $k_i = 500$ Nm/A,\n- $k = 1$ Nm/rad,\n- $b = 0.04$ Nm/(rad/s).\n\nCilj je na\u010drtovali regulator pomika ro\u010dice ob upo\u0161tevanju danih zahtev:\n- brez prenihaja, \n- \u010das ustalitve manj kot 50 ms (dose\u017eena vrednost izhoda naj se razlikuje od tiste v stacionarnem stanju za **2%**). \n- brez odstopka v stacionarnem stanju v odzivu na spremembo zahtevanega pomika ro\u010dice z uporabo kora\u010dne funkcije, \n- vhodni el. tok ne sme presegati 5 A v odzivu na vhodno kora\u010dno funkcijo z vrednostjo 30 stopinj.\n\nEna\u010dba sistema je:\n$$\nJ\\ddot{\\theta} = k_iI - b\\dot{\\theta} - k\\theta\n$$\n\nOb upo\u0161tevanju vektorja stanj $x=\\begin{bmatrix}x_1 & x_2\\end{bmatrix}^T=\\begin{bmatrix}\\theta & \\dot{\\theta}\\end{bmatrix}^T$ in $u=I$, lahko zgornjo ena\u010dbo zapi\u0161emo v obliki prostora stanj:\n\n\\begin{cases}\n\\dot{x} = \\begin{bmatrix} 0 & 1 \\\\ -k & -b \\end{bmatrix}x + \\begin{bmatrix} 0 \\\\ k_i \\end{bmatrix}u \\\\\ny = \\begin{bmatrix} 1 & 0 \\end{bmatrix}x\n\\end{cases}\n\nZ namenom dosega ni\u010delnega odstopka v stacionarnem stanju, raz\u0161irimo objekt z novo spremenljivko stanja $\\dot{x_3}=y-y_d=x_1-y_d$. Posledi\u010dno sistem popi\u0161emo z naslednjo ena\u010dbo:\n\n\\begin{cases}\n\\dot{x_a} = \\begin{bmatrix} 0 & 1 & 0 \\\\ -k & -b & 0 \\\\ 1 & 0 & 0 \\end{bmatrix}x_a + \\begin{bmatrix} 0 & 0 \\\\ k_i & 0 \\\\ 0 & -1 \\end{bmatrix}\\begin{bmatrix} u \\\\ y_d \\end{bmatrix} \\\\\ny = \\begin{bmatrix} 1 & 0 & 0 \\\\ 0 & 0 & 1 \\end{bmatrix}x\n\\end{cases}\n\nVodljivostna matrika $\\mathcal{C}$, ob upo\u0161tevanju zgolj vhoda $u$, je\n\n\n```python\nA = numpy.matrix('0 1 0; -1 -0.04 0; 1 0 0')\nB = numpy.matrix('0 0; 500 0; 0 -1')\nC = numpy.matrix('1 0 0; 0 0 1')\nD = numpy.matrix('0 0; 0 0')\n\nCM = control.ctrb(A,B[:,0])\ndisplay(Markdown(bmatrix(CM)))\n# print(numpy.linalg.matrix_rank(CM))\n```\n\n\n\\begin{bmatrix}\n  0. & 500. & -20.\\\\\n  500. & -20. & -499.2\\\\\n  0. & 0. & 500.\\\\\n\\end{bmatrix}\n\n\nin ima rang enak 3, kar pomeni, da je sistem vodljiv.\nSpoznavnostna matrika $\\mathcal{O}$ je\n\n\n```python\nOM = control.obsv(A,C)\ndisplay(Markdown(bmatrix(OM)))\n# print(numpy.linalg.matrix_rank(OM))\n```\n\n\n\\begin{bmatrix}\n  1. & 0. & 0.\\\\\n  0. & 0. & 1.\\\\\n  0. & 1. & 0.\\\\\n  1. & 0. & 0.\\\\\n  -1. & -0.04 & 0.\\\\\n  0. & 1. & 0.\\\\\n\\end{bmatrix}\n\n\nin ima rang enak 3, kar pomeni, da je sistem spoznaven.\n\n### Na\u010drtovanje regulatorja\n#### Na\u010drtovanje krmilnika\n\nOja\u010danje povratne zveze stanj dolo\u010dimo zgolj na podlagi vhoda $u$, medtem ko za referenco uporabimo $y_d$. Zahtevam, povezanim s prehodnim pojavom, lahko zadostimo, \u010de dominantna pola zaprtozan\u010dnega sistema razporedimo v $-100.02\\pm101i$, tretji pol npr. v $-100$ (slednji pol naj vsaj ne bo po\u010dasnej\u0161i od dominantnih dveh). To dose\u017eemo z naslednjo matriko oja\u010danj: \n$$\nK = \\begin{bmatrix} 80.416 & 0.6 & 4041.0 \\end{bmatrix}.\n$$\n\n#### Na\u010drtovanje spoznavalnika\nZ namenom dosega dobre ocene stanja in s tem hitro konvergenco napake ocene stanj k vrednosti 0, razporedimo pole spoznavalnika v $-151$, $-152$ in $-153$ (poli so hitrej\u0161i od polov krmiljenega sistema). \nMatrika oja\u010danj spoznavalnika je tako:\n$$\nL = \\begin{bmatrix} 300.96 & 3.028e-12 \\\\\n 2.264e+04 & 4.55e-10 \\\\\n 1.0 & 150.0 \\end{bmatrix}.\n$$\n\nOpomba: z raz\u0161irjenim vektorjem stanj zagotovimo, da je oja\u010danje zaprtozan\u010dnega sistema vedno enako 1.\n\n### Kako upravljati s tem interaktivnim primerom?\n- Poizkusi izbolj\u0161ati odziv sistema v primeru prisotnosi majhne za\u010detne napake (npr. 0.05), s spreminjanjem prvih dve elementov za\u010detnih pogojev, vezanih na spoznavalnik (gl. parameter X0 est.).\n- **Opomba:** Vklju\u010ditev za\u010detne napake v tretjo spremenljivko ocenjenega stanja nima smisla, saj tretje stanje izra\u017ea dinamiko, ki smo jo sami dolo\u010dili. Spoznavalnik bi lahko na\u010drtovalu tudi samo za $ x_2 $, saj $ x_1 $ merimo, $ x_3 $ pa poznamo.\n\n\n```python\n# Preparatory cell\n\nX0 = numpy.matrix('0.0; 0.0; 0.0')\nK = numpy.matrix([8/15,-4.4,-4])\nL = numpy.matrix([[300, 3.028E-12],[2.264E+04, 4.55E-10],[1, 150]])\n\nAw = matrixWidget(3,3)\nAw.setM(A)\nBw = matrixWidget(3,1)\nBw.setM(B)\nCw = matrixWidget(1,3)\nCw.setM(C)\nX0w = matrixWidget(3,1)\nX0w.setM(X0)\nKw = matrixWidget(1,3)\nKw.setM(K)\nLw = matrixWidget(3,2)\nLw.setM(L)\n\n\neig1c = matrixWidget(1,1)\neig2c = matrixWidget(2,1)\neig3c = matrixWidget(1,1)\neig1c.setM(numpy.matrix([-100.])) \neig2c.setM(numpy.matrix([[-100.02],[-101.]]))\neig3c.setM(numpy.matrix([-100.]))\n\neig1o = matrixWidget(1,1)\neig2o = matrixWidget(2,1)\neig3o = matrixWidget(1,1)\neig1o.setM(numpy.matrix([-150.])) \neig2o.setM(numpy.matrix([[-151.],[0.]]))\neig3o.setM(numpy.matrix([-152.]))\n```\n\n\n```python\n# Misc\n\n#create dummy widget \nDW = widgets.FloatText(layout=widgets.Layout(width='0px', height='0px'))\n\n#create button widget\nSTART = widgets.Button(\n    description='Test',\n    disabled=False,\n    button_style='', # 'success', 'info', 'warning', 'danger' or ''\n    tooltip='Test',\n    icon='check'\n)\n                       \ndef on_start_button_clicked(b):\n    #This is a workaround to have intreactive_output call the callback:\n    #   force the value of the dummy widget to change\n    if DW.value> 0 :\n        DW.value = -1\n    else: \n        DW.value = 1\n    pass\nSTART.on_click(on_start_button_clicked)\n\n# Define type of method \nselm = widgets.Dropdown(\n    options= ['Nastavi K in L', 'Nastavi lastne vrednosti'],\n    value= 'Nastavi lastne vrednosti',\n    description='',\n    disabled=False\n)\n\n# Define the number of complex eigenvalues\nsele = widgets.Dropdown(\n    options= ['brez kompleksnih lastnih vrednosti', 'dve kompleksni lastni vrednosti'],\n    value= 'dve kompleksni lastni vrednosti',\n    description='Kompleksne lastne vrednosti:',\n    style = {'description_width': 'initial'},\n    disabled=False\n)\n\n#define type of ipout \nselu = widgets.Dropdown(\n    options=['impulzna funkcija', 'kora\u010dna funkcija', 'sinusoidna funkcija', 'kvadratni val'],\n    value='kora\u010dna funkcija',\n    description='Vhod:',\n    style = {'description_width': 'initial'},\n    disabled=False\n)\n# Define the values of the input\nu = widgets.FloatSlider(\n    value=30*numpy.pi/180,\n    min=0,\n    max=45*numpy.pi/180,\n    step=0.05,\n    description='Referenca:',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.1f',\n)\nperiod = widgets.FloatSlider(\n    value=0.5,\n    min=0.001,\n    max=10,\n    step=0.001,\n    description='Perioda: ',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.2f',\n)\n\ngain_w2 = widgets.FloatText(\n    value=1.,\n    description='',\n    disabled=True\n)\n\nsimTime = widgets.FloatText(\n    value=0.5,\n    description='',\n    disabled=False\n)\n```\n\n\n```python\n# Support functions\n\ndef eigen_choice(sele):\n    if sele == 'brez kompleksnih lastnih vrednosti':\n        eig1c.children[0].children[0].disabled = False\n        eig2c.children[1].children[0].disabled = True\n        eig1o.children[0].children[0].disabled = False\n        eig2o.children[1].children[0].disabled = True\n        eig = 0\n    if sele == 'dve kompleksni lastni vrednosti':\n        eig1c.children[0].children[0].disabled = True\n        eig2c.children[1].children[0].disabled = False\n        eig1o.children[0].children[0].disabled = True\n        eig2o.children[1].children[0].disabled = False\n        eig = 2\n    return eig\n\ndef method_choice(selm):\n    if selm == 'Nastavi K in L':\n        method = 1\n        sele.disabled = True\n    if selm == 'Nastavi lastne vrednosti':\n        method = 2\n        sele.disabled = False\n    return method\n```\n\n\n```python\nnumU = 1\n\ndef main_callback2(Aw, Bw, X0w, K, L, eig1c, eig2c, eig3c, eig1o, eig2o, eig3o, u, period, selm, sele, selu, simTime, DW):\n    eige = eigen_choice(sele)\n    method = method_choice(selm)\n    \n    if method == 1:\n        solc = numpy.linalg.eig(A-B[:,0:numU]*K)\n        solo = numpy.linalg.eig(A-L*C)\n    if method == 2:\n        if eige == 0:\n            K = control.acker(A, B[:,0:numU], [eig1c[0,0], eig2c[0,0], eig3c[0,0]])\n            Kw.setM(K)\n            L = control.place(A.T, C.T, [eig1o[0,0], eig2o[0,0], eig3o[0,0]]).T\n            Lw.setM(L)\n        if eige == 2:\n            K = control.acker(A, B[:,0:numU], [eig3c[0,0], \n                                     numpy.complex(eig2c[0,0],eig2c[1,0]), \n                                     numpy.complex(eig2c[0,0],-eig2c[1,0])])\n            Kw.setM(K)\n            L = control.place(A.T, C.T, [eig3o[0,0], \n                                         numpy.complex(eig2o[0,0],eig2o[1,0]), \n                                         numpy.complex(eig2o[0,0],-eig2o[1,0])]).T\n            Lw.setM(L)\n            \n    \n    sys = control.ss(A,B,numpy.vstack((C,numpy.zeros((B.shape[1],C.shape[1])))),numpy.vstack((D,numpy.eye(B.shape[1]))))\n    sysC = control.ss(numpy.zeros((1,1)),\n                      numpy.zeros((1,numpy.shape(A)[0])),\n                      numpy.zeros((numpy.shape(B[:,0:numU])[1],1)),\n                      -K)\n    \n    sysE = control.ss(A-L*C,\n                      numpy.hstack((L,B-L*D)),\n                      numpy.eye(numpy.shape(A)[0]),\n                      numpy.zeros((A.shape[0],C.shape[0]+B.shape[1])))\n    \n    sys_append = control.append(sys, sysE, sysC, control.ss(A,B,numpy.eye(A.shape[0]),numpy.zeros((A.shape[0],B.shape[1]))))\n    Q = []\n    # y in ingresso a sysE\n    for i in range(C.shape[0]):\n        Q.append([B.shape[1]+i+1, i+1])\n    # u in ingresso a sysE\n    for i in range(B.shape[1]):\n        Q.append([B.shape[1]+C.shape[0]+i+1, C.shape[0]+i+1])\n    # u in ingresso a sys\n    for i in range(B[:,0:numU].shape[1]):\n        Q.append([i+1, C.shape[0]+B.shape[1]+A.shape[0]+i+1])\n    # u in ingresso al sistema che ha come uscite gli stati reali\n    for i in range(B.shape[1]):\n        Q.append([2*B.shape[1]+C.shape[0]+A.shape[0]+i+1, C.shape[0]+i+1])\n    # xe in ingresso a sysC\n    for i in range(A.shape[0]):\n        Q.append([2*B.shape[1]+C.shape[0]+i+1, C.shape[0]+B.shape[1]+i+1])\n        \n    inputv = [i+numU+1 for i in range(B[:,numU:].shape[1])]\n    outputv = [i+1 for i in range(numpy.shape(sys_append.C)[0])]\n    # in order to avoid singular value exception\n    try:\n        sys_CL = control.connect(sys_append, Q, inputv, outputv)\n    except:\n        sys_CL = control.connect(sys_append, Q, inputv, outputv)\n    \n    dcgain = control.dcgain(sys_CL[0,0])\n    gain_w2.value = dcgain\n    if dcgain != 0:\n        u1 = u/gain_w2.value\n    else:\n        print('Nastavljena vrednost vnaprej\u0161njega oja\u010danja je bila nastavljena na 0 in je bila zato sprememnjena na 1')\n        u1 = u/1\n    print('Stati\u010dno oja\u010danje zaprtozan\u010dnega sistema (od vhoda do izhoda) je: %.5f' %dcgain)\n    \n    X0w1 = numpy.zeros((A.shape[0],1))\n    for j in range(A.shape[0]):\n        X0w1 = numpy.vstack((X0w1,X0w[j]))\n    X0w1 = numpy.vstack((X0w1,numpy.zeros((A.shape[0],1))))\n    if simTime != 0:\n        T = numpy.linspace(0, simTime, 10000)\n    else:\n        T = numpy.linspace(0, 1, 10000)\n      \n    if selu == 'impulzna funkcija': #selu\n        U = [0 for t in range(0,len(T))]\n        U[0] = u\n        U1 = [0 for t in range(0,len(T))]\n        U1[0] = u1\n        T, yout, xout = control.forced_response(sys_CL[:,0],T,U1,X0w1)\n    if selu == 'kora\u010dna funkcija':\n        U = [u for t in range(0,len(T))]\n        U1 = [u1 for t in range(0,len(T))]\n        T, yout, xout = control.forced_response(sys_CL[:,0],T,U1,X0w1)\n    if selu == 'sinusoidna funkcija':\n        U = u*numpy.sin(2*numpy.pi/period*T)\n        U1 = u1*numpy.sin(2*numpy.pi/period*T)\n        T, yout, xout = control.forced_response(sys_CL[:,0],T,U1,X0w1)\n    if selu == 'kvadratni val':\n        U = u*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n        U1 = u1*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n        T, yout, xout = control.forced_response(sys_CL[:,0],T,U1,X0w1)\n    # N.B. i primi 3 stati di xout sono quelli del sistema, mentre gli ultimi 3 sono quelli dell'osservatore\n    \n    step_info_dict = control.step_info(sys_CL[0,0],SettlingTimeThreshold=0.02,T=T)\n    print('Informacija o odzivu sistema: \\n\\t\u010cas vzpona [s] =',step_info_dict['RiseTime'],'\\n\\t\u010cas ustalitve (2%) [s] =',step_info_dict['SettlingTime'],'\\n\\tPrenihaj [%]=',step_info_dict['Overshoot'])\n    print('Maksimalna vrednost U (dele\u017e od 5 A)=', max(abs(yout[C.shape[0]]))/(5)*100)\n    \n    fig = plt.figure(num='Simulacija 1', figsize=(14,12))\n    \n    fig.add_subplot(221)\n    plt.title('Odziv sistema')\n    plt.ylabel('Izhod')\n    plt.plot(T,yout[0],T,U,'r--')\n    plt.xlabel('$t$ [s]')\n    plt.legend(['$y$','Referenca'])\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(222)\n    plt.title('Vhod')\n    plt.ylabel('$u$')\n    plt.plot(T,yout[C.shape[0]],T,[5 for i in range(len(T))],'r--')\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(223)\n    plt.title('Odziv stanj')\n    plt.ylabel('Stanje')\n    plt.plot(T,yout[C.shape[0]+B.shape[1]+B[:,numU:].shape[1]+A.shape[0]],\n             T,yout[C.shape[0]+B.shape[1]+B[:,numU:].shape[1]+A.shape[0]+1],\n             T,yout[C.shape[0]+B.shape[1]+B[:,numU:].shape[1]+A.shape[0]+2])\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$x_{1}$','$x_{2}$','$x_{3}$'])\n    plt.grid()\n    \n    fig.add_subplot(224)\n    plt.title('Napaka ocene stanj')\n    plt.ylabel('Napaka ocene stanj')\n    plt.plot(T,yout[C.shape[0]+B.shape[1]+B[:,numU:].shape[1]+A.shape[0]]-yout[C.shape[0]+B.shape[1]],\n             T,yout[C.shape[0]+B.shape[1]+B[:,numU:].shape[1]+A.shape[0]+1]-yout[C.shape[0]+B.shape[1]+1],\n             T,yout[C.shape[0]+B.shape[1]+B[:,numU:].shape[1]+A.shape[0]+2]-yout[C.shape[0]+B.shape[1]+2])\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$e_{1}$','$e_{2}$','$e_{3}$'])\n    plt.grid()\n    #plt.tight_layout()\n   \nalltogether2 = widgets.VBox([widgets.HBox([selm, \n                                          sele,\n                                          selu]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.Label('K:',border=3), Kw, \n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Lastne vrednosti:',border=3), \n                                          eig1c, \n                                          eig2c, \n                                          eig3c,\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('X0 est.:',border=3), X0w]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.Label('L:',border=3), Lw, \n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Lastne vrednosti:',border=3), \n                                          eig1o, \n                                          eig2o, \n                                          eig3o,\n                                          widgets.Label(' ',border=3)]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.VBox([widgets.Label('Inverzna vrednost oja\u010danja reference:',border=3),\n                            widgets.Label('Simulacijski \u010das [s]:',border=3)]),\n                            widgets.VBox([gain_w2,simTime])]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([u, \n                                          period, \n                                          START])])\nout2 = widgets.interactive_output(main_callback2, {'Aw':Aw, 'Bw':Bw, 'X0w':X0w, 'K':Kw, 'L':Lw,\n                                                 'eig1c':eig1c, 'eig2c':eig2c, 'eig3c':eig3c, 'eig1o':eig1o, 'eig2o':eig2o, 'eig3o':eig3o, \n                                                 'u':u, 'period':period, 'selm':selm, 'sele':sele, 'selu':selu, 'simTime':simTime, 'DW':DW})\nout2.layout.height = '870px'\ndisplay(out2, alltogether2)\n```\n\n\n    Output(layout=Layout(height='870px'))\n\n\n\n    VBox(children=(HBox(children=(Dropdown(index=1, options=('Nastavi K in L', 'Nastavi lastne vrednosti'), value=\u2026\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "3e85055416c5fcbcca6bbd72e819cf7dff443fd8", "size": 29571, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_si/examples/04/SS-43-Krmiljenje_glave_trdega_diska.ipynb", "max_stars_repo_name": "ICCTerasmus/ICCT", "max_stars_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-22T18:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:10:22.000Z", "max_issues_repo_path": "ICCT_si/examples/04/SS-43-Krmiljenje_glave_trdega_diska.ipynb", "max_issues_repo_name": "ICCTerasmus/ICCT", "max_issues_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICCT_si/examples/04/SS-43-Krmiljenje_glave_trdega_diska.ipynb", "max_forks_repo_name": "ICCTerasmus/ICCT", "max_forks_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-24T11:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T16:36:18.000Z", "avg_line_length": 40.3975409836, "max_line_length": 482, "alphanum_fraction": 0.4874031991, "converted": true, "num_tokens": 6809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451488696663, "lm_q2_score": 0.09534946554178127, "lm_q1q2_score": 0.03324312860845745}}
{"text": "# Open Systems\nAll of the examples in the previous two chapters were closed systems. The ultimate state of closed, chemically reacting systems is chemical equilibrium. Living systems are characterized by mass and energy flow across their boundaries that keep them away from equilibrium. We now discuss open systems, which allow molecules to enter and leave. Open systems ultimately reach a steady state that is often close to a homeostatic state of interest. \n\n**MASSpy** will be used to demonstrate some of the topics in this chapter. \n\n\n```python\nfrom mass import (\n    MassModel, MassMetabolite, MassReaction, Simulation, MassSolution)\nfrom mass.visualization import plot_time_profile, plot_phase_portrait\n```\n\nOther useful packages are also imported at this time.\n\n\n```python\nimport matplotlib.pyplot as plt\n```\n\n## Basic Concepts\nThere are several fundamental concepts that need to be understood when one considers open systems. We discuss the more significant ones in this section. \n\n### The system boundary  \nImplicit in the term 'open system' is the notion of an inside and an outside, the division of the world into two domains. The separation between the two is the _system boundary,_ which thus defines what is inside a system and belongs to it, and what is outside. \n\nThe definition of a boundary can be physical. An example of a physical boundary may be the cell wall, that clearly defines what is inside and what is outside. Similarly, the outer membrane of the mitochondria can serve as a clearly defined physical system boundary. Thus, systems can have hard, immovable boundaries or soft, flexible ones. In the latter case, the volume of the system may be changing. \n\nThe definition of a boundary can also be virtual. For instance, we can define a pathway, such as the TCA cycle, as a system, or the amino acid biosynthetic pathways in a cell as a system. In both cases we might draw dashed lines around it on the metabolic map to indicate the system boundary. \n\n### Crossing the boundary: inputs and outputs  \nOnce a system boundary has been established, we can identify and define interactions across it. They are the _inputs_ and _outputs_ of the system. In most cases, we will be considering mass flows in and out of a system; molecules coming and going. Such flows are normally amenable to experimental determination. \n\nThere may be other quantities crossing the system boundary. For instance, if we are considering photosynthesis, photons are crossing the system boundary providing a net influx of energy. Forces can also act on the system boundary. For instance, if the number of molecules coming into and leaving a system through a coupled transport mechanism is not balanced, then osmotic pressure may be generated across the system boundary. Cells have sodium-potassium pumps that displace an uneven number of two types of cations to deal with osmotic imbalances. \n\n### Perturbations and boundaries  \nIn most analyses of living systems, we are concerned about changes in the environment. The temperature may change, substrate availability may change, and so on. Such changes in the environment can be thought of as forcing functions to which the living system responds. These are one-way interactions, from the environment to the system. In most cases, we consider the system to be small (relative to the environment) and that the environment buffers the activities of the system. For instance, the environment may provide an infinite sink for cellular waste products. \n\nIn other cases, the activities of the system influence the state of the environment. In batch fermentation, for example, the metabolic activities will substantially change the chemical composition of the medium during the course of the fermentation. On a global scale, we are now becoming more concerned about the impact that human activities have on the climate and the larger environment of human socio-economic activities. In such cases, there are two-way interactions between the system and the environment that need to be described. \n\n### Inside the boundary: the internal network  \nThe definition of a system boundary determines what is inside. Once we know what is inside the system, we can determine the network of chemical transformations that takes place. This network has topology and its links have kinetic properties. \n\nIn most cases, it is hard to measure the internal state of a system. There typically are only a few non-invasive measurements available. Occasionally, there are probes that we can use to observe the internal activities. Tracers, such as $^{13}C$ atoms strategically placed in substrates, can be used to trace input to output and allow us to determine pieces of the internal state of a system. Tearing a system apart to enumerate its components is of course possible, but the system is destroyed in the process. Thus, we are most often in the situation where we cannot fully experimentally determine the internal state of a system, and may have to be satisfied with only partial knowledge. \n\n### From networks to system models  \nMathematical models may help us to simulate or estimate the internal state of the system. Sometimes we are able to bracket its state based on the inputs and outputs and our knowledge of the internal network. \n\nFull dynamic simulation requires extensive knowledge about the internal properties of a system. Detailed models that describe the dynamic state of a system require the definition of the system boundary, the inputs and outputs, the structure of the internal network, and the kinetic properties of the links in the network. We can then simulate the response of the system to various perturbations, such as changes in the environmental conditions. \n\n### The functional state  \nOnce a system model has been formulated, it can be used to compute the functional state of the system for a given set of conditions. Closed systems will eventually go to chemical equilibrium. However, open systems are fundamentally different. Due to continuous interactions with the environment, they have internal states that are either dynamic or steady. A system that has fast internal time constants relative to changes in the environment will reach a steady state, or a quasi-steady state. For a biological system, such functional states are called _homeostatic states_. Such states are maintained through energy dissipation. The flow of energy in has to exceed the energy leaving the system. This difference allows living systems to reach a functional homeostatic state. \n\n\n\n**Figure 6.1:** Open systems. (a) example production of ATP from pyruvate by mitochondria (Prepared by Nathan Lewis). (b) Basic definitions associated with an open system.\n\n## Reversible reaction in an Open Environment\nIn an open environment, the simple reaction of Eq. (4.1)  has an inflow $(b_1)$ of $x_1$ and an outflow $(b_2)$ of $x_2$: \n\n$$\\begin{equation} \\stackrel{b_1}{\\rightarrow} x_1 \\underset{v_{-1}}{\\stackrel{v_1}{\\rightleftharpoons}} x_2 \\stackrel{b_2}{\\rightarrow} \\tag{6.1} \\end{equation}$$\n\nThe input is fixed by the environment and there is a first-order rate for the product to leave the system and thus we have \n\n$$\\begin{equation} b_1 = \\text{constant and}\\ b_2 = k_2x_2 \\end{equation}$$\n\nThis defines the system boundary, and the inputs and outputs. \n\nThe stoichiometric matrix is \n\n$$\\begin{equation} \\textbf{S} = \\begin{pmatrix} {1} & {-1} & {1} & {0} \\\\ {0} & {1} & {-1} & {-1} \\\\ \\end{pmatrix} \\end{equation}$$\n$$\\tag{6.2}$$\n\nwhere $\\textbf{x} = (x_1,\\  x_2)$ and $\\textbf{v} = (b_1, \\ k_1x_1, \\  k_{-1}x_2, \\  k_2x_2)$ The stoichiometric matrix has a rank of 2 and is thus a two-dimensional dynamic system. The differential equations that will need to be solved are: \n\n$$\\begin{equation} \\frac{dx_1}{dt} = b_1 - k_1x_1 + k_{-1}x_2, \\ \\frac{dx_2}{dt} = k_1x_1 - k_{-1}x_2 - k_2x_2 \\tag{6.3} \\end{equation}$$\n\nThere are no conservation quantities. \n\n### The steady states  \nThere are three properties of the steady state of interest. We can find first the steady state fluxes and second the steady state concentrations. Third, we can determine the difference between the steady state and the equilibrium state of this open system. \n\n#### Steady state fluxes:  \nThe steady state of the fluxes is given by \n\n$$\\begin{equation} \\textbf{Sv}_{ss} = 0 \\tag{6.4} \\end{equation}$$\n\nand thus $\\textbf{v}_{ss}$ resides in the null space of $\\textbf{S}$. For this matrix, the null space is two dimensional; $\\text{Dim}(\\text{Null}(\\textbf{S}))=n-r=4-2=2$, where $n=4$ is the number of fluxes and the rank is $r=2$. The null space is spanned by two pathway vectors: (1,1,0,1) and (0,1,1,0). The former is the path through the system while the latter corresponds to the reversible reaction. These are known as type 1 and type 3 extreme pathways, respectively\u00a0(_Systems Biology: Properties of Reconstructed Networks_). All steady state flux states of the system are a non-negative combination of these two vectors. \n\n$$\\begin{align} \\textbf{v}_{ss} &= (b_1, \\ k_1x_{1, ss}, \\ k_{-1}x_{2, ss}, \\ k_2x_{2, ss})  \\tag{6.5} \\\\ &= a(1, 1, 0, 1) + b(0, 1, 1, 0), \\ a \\geq 0, \\ b \\geq 0 \\tag{6.6} \\end{align}$$\n\n#### Steady state concentrations:  \nThe concentrations in the steady state can be evaluated from \n\n$$\\begin{equation} 0 = b_1 - k_1x_1 + k_{-1}x_2, \\ 0 = k_1x_1 - k_{-1}x_2 - k_2x_2 \\end{equation}$$ $$\\tag{6.7}$$\n\nIf we add these equations we find that $x_{2, ss} = b_1 / k_2$. This concentration can then be substituted into either of the two equations to show that $x_{1, ss} = (1 + k_{-1}/k_2)(b_1/k_1)$. Thus, the steady state concentration vector is \n\n$$\\begin{equation} \\textbf{x}_{ss} = \\begin{pmatrix} {x_{1, ss}} \\\\ {x_{2, ss}} \\end{pmatrix} = (\\frac{b_1}{k_2})\\begin{pmatrix} {\\frac{k_2 + k_{-1}}{k_1}} \\\\ {1} \\end{pmatrix} \\end{equation}$$ $$\\tag{6.8}$$\n\nThese steady state concentrations can be substituted into the steady state flux vector to get \n\n$$\\begin{align} \\textbf{v}_{ss} &= b_1(1, 1+(\\frac{k_{-1}}{k_2}), \\ (\\frac{k_{-1}}{k_2}), \\ 1)  \\tag{6.9} \\\\ &= a(1, 1, 0, 1) + b(0, 1, 1, 0), \\ a = b_1, \\ b = (\\frac{b_1k_{-1}}{k_2}) \\end{align}$$\n\nTherefore, the steady state flux distribution is a summation of the straight through pathway and the discounted flux through the reversible reaction. The key quantity is $k_{-1} / k_2$ that measures the relative rate of $x_2$ reacting back to form $x_1$ versus the rate at which it leaves the system. \n\n#### The distance from the equilibrium state:  \nThe difference between the steady state and the equilibrium state can be measured by: \n\n$$\\begin{equation} \\frac{x_{2, ss}/x_{1, ss}}{x_{2, eq}/x_{1, eq}} = \\frac{1}{1 + k_2/k_{-1}} \\stackrel{k_2 << k_{-1}}{\\longrightarrow} 1 \\tag{6.11} \\end{equation}$$\n\nThus, when $k_2 << k_{-1}$, the steady state approaches the equilibrium state (recall that $(x_{2, ss}/x_{1, ss})/(x_{2, eq}/x_{1, eq}) = \\Gamma/K_{eq}$ Section\u00a02.2). If the exchange with the environment is slow relative to the internal reaction rates, the internal system approaches that of an equilibrium state. \n\n### Dynamic states for reversible reactions\nThe dynamic states are computed from the dynamic mass balances for a given condition. We are interested in two dynamic states: the approach to the steady state, and the response to a change in the input flux, $b_1$\n\n#### A two-phase transient response:  \nSimulation of this system with an input rate of $b_1 = 0.01$ and a slow removal rate, $k_2 = 0.1$, from an initial state of $x_1(0) = 1.0$ and $x_2(0) = 0$ is shown in Figure\u00a06.2. There are two discernible time scales: a rapid motion of the equilibrating reaction, and a slow removal of $x_2$ from the system, Figure\u00a06.2b. A phase portrait shows a rapid movement along a line with a negative slope of 1, showing the existence of a conservation quantity $(x_1 + x_2)$ on a fast time scale, followed by a slow motion down a quasi-equilibrium line with a slope of 1/2 to a steady state point. Note the difference from Figure 4.4c. \n\n\n```python\n# Create MassModel\nmodel = MassModel('Linear_Reversible_Open')\n# Generate the MassMetabolites \nx1 = MassMetabolite(\"x1\")\nx2 = MassMetabolite(\"x2\")\n\n# Generate the MassReactions \nb1 = MassReaction(\"b1\", reversible=False)\nv1 = MassReaction(\"v1\")\nb2 = MassReaction(\"b2\", reversible=False)\n# Add metabolites to the reaction, add reaction to the model\nb1.add_metabolites({x1: 1})\nv1.add_metabolites({x1: -1, x2: 1})\nb2.add_metabolites({x2: -1})\nmodel.add_reactions([b1, v1, b2])\n# Set parameters\nb1.kf = 0.01\nv1.kf, v1.kr = (1, 2)\nb2.kf = 0.1\n\n# Set initial conditions for model\nx1.ic = 1\nx2.ic = 0\n# Utilize type 2 rate law for kf and kr parameters defined\nmodel.get_rate_expressions(rate_type=2, update_reactions=True)\n\n# Set a custom rate for b1 to remove substrate concentration dependence\nmodel.add_custom_rate(reaction=b1, custom_rate=b1.kf_str)\n```\n\n    Set parameter Username\n\n\n\n```python\nt0 = 0\ntf = 150\n\nsim = Simulation(model, verbose=True)\nconc_sol, flux_sol = sim.simulate(model, time=(t0, tf),\n                                  interpolate=True,\n                                  verbose=True)\n```\n\n    \u001b[93mWARNING:\u001b[0m \u001b[93mNo compartments found in model. Therefore creating compartment 'compartment' for entire model.\u001b[0m\n\n\n    Successfully loaded MassModel 'Linear_Reversible_Open' into RoadRunner.\n    Getting time points\n    Setting output selections\n    Setting simulation values for 'Linear_Reversible_Open'\n    Simulating 'Linear_Reversible_Open'\n    Simulation for 'Linear_Reversible_Open' successful\n    Adding 'Linear_Reversible_Open' simulation solutions to output\n    Updating stored solutions\n\n\n\n```python\nfig_6_2 = plt.figure(figsize=(13, 5))\ngs = fig_6_2.add_gridspec(nrows=1, ncols=2, width_ratios=[1, 1.5])\n\nax1 = fig_6_2.add_subplot(gs[0, 0])\nax2 = fig_6_2.add_subplot(gs[0, 1])\n\nplot_phase_portrait(\n    conc_sol, x=x1, y=x2, ax=ax1,\n    xlabel=x1.id, ylabel=x2.id, xlim=(-.05, 1.2), ylim=(-.05, 0.5),\n    title=(\"(a) Phase portrait of x1 vs. x2\", {\"size\": \"large\"}),\n    annotate_time_points=[t0, 1e0, 1e1, tf],\n    annotate_time_points_color=[\"red\"],\n    annotate_time_points_labels=True);\n\nax1.annotate(\n    'motion towards\\n  a qe state', \n    xy=(conc_sol[x1.id](0.5), conc_sol[x2.id](0.5)), \n    xytext=(conc_sol[x1.id](0.3), conc_sol[x2.id](0.3)));\n\nax1.annotate(\n    'motion of a\\n  qe state', \n    xy=(conc_sol[x1.id](tf), conc_sol[x2.id](tf)), \n    xytext=(conc_sol[x1.id](tf) + 0.05, conc_sol[x2.id](tf) + 0.15));\n\nplot_time_profile(\n    conc_sol, ax=ax2, legend=\"right outside\", \n    xlabel=\"Time\", ylabel=\"Concentrations\",\n    title=(\"(b) Concentration Profiles\", {\"size\": \"large\"}));\nfig_6_2.tight_layout()\n```\n\n**Figure 6.2:** The concentration time profiles for the reaction system $\\rightarrow x_1 \\rightleftharpoons x_2 \\rightarrow$ for $k_1 = 1$, $k_{-1} = 2$, $x_1(0) = 0$, and $b_1 = 0.01$. (a) The phase portrait of $x_1$ and $x_2$ (b) The concentrations as a function of time.\n\nThe same pools can be formed as defined in Eq. (4.9):\n\n$$\\begin{equation}\\begin{pmatrix} {p_1} \\\\ {p_2} \\end{pmatrix} = \\begin{pmatrix} {1} & {-1/K_1} \\\\ {1} & {1} \\end{pmatrix} = \\begin{pmatrix} {x_1} \\\\ {x_2} \\end{pmatrix} \\end{equation}$$\n$$\\tag{6.12}$$\n\nThis matrix can be used to post-process the concentrations and the results can be graphed, Figure\u00a06.3. The pool transformation leads to dynamic decoupling and is clearly illustrated in this figure. The disequilibrium pool relaxes very quickly, while the conservation pool moves slowly, Figure\u00a06.3b. The phase portrait formed by the pools thus has an L shape (Figure\u00a06.3a), illustrating the dynamic decoupling. Note that: \n\n* There is first a vertical motion where $x_1 + x_2$ is essentially a constant, followed by a slow horizontal motion where the disequilibrium variable $x_1 - x_2 /K_1$ is a constant. \n\n* These two separate motions correspond to forming the pathways found in the steady state. \n\n* The disequilibrium aggregate is not zero, as it is forced away from equilibrium by the input and settling in a steady state. \n\n\n```python\n# Define pools\npools = [\"x1 - x2 / Keq_v1\", \"x1 + x2\"]\nfor i, equation_str in enumerate(pools):\n    pool_id = \"p\" + str(i + 1)\n    conc_sol.make_aggregate_solution(\n        pool_id, equation=equation_str, \n        parameters={v1.Keq_str: v1.kf/v1.kr}, update=True)\n\nfig_6_3 = plt.figure(figsize=(11, 4))\ngs = fig_6_3.add_gridspec(nrows=1, ncols=2, width_ratios=[1, 1.5])\n\nax1 = fig_6_3.add_subplot(gs[0, 0])\nax2 = fig_6_3.add_subplot(gs[0, 1])\n\nplot_phase_portrait(\n    conc_sol, x=\"p2\", y=\"p1\", ax=ax1,\n    xlabel=\"p2 (inventory)\", ylabel=\"p1 (distance from equilibrium)\",\n    xlim=(-.05, 2.1), ylim=(-.05, 1.05),\n    title=(\"(a) Phase portrait of p2 vs. p1\", {\"size\": \"large\"}),\n    annotate_time_points=[t0, 1e0, 1e1, tf],\n    annotate_time_points_color=[\"red\"],\n    annotate_time_points_labels=True);\n\nax1.annotate(\n    'motion towards\\n  a qe state', \n    xy=(conc_sol[\"p2\"](0.5), conc_sol[\"p1\"](0.5)), \n    xytext=(conc_sol[\"p2\"](0.3), conc_sol[\"p1\"](0.3)));\n\nax1.annotate(\n    'motion of a\\n  qe state', \n    xy=(conc_sol[\"p2\"](tf), conc_sol[\"p1\"](tf)), \n    xytext=(conc_sol[\"p2\"](tf) + 0.05, conc_sol[\"p1\"](tf) + 0.1));\n\nplot_time_profile(\n    conc_sol, observable=[\"p1\", \"p2\"], ax=ax2, legend=\"right outside\", \n    xlabel=\"Time\", ylabel=\"Concentrations\",\n    title=(\"(b) Pool Profiles\", {\"size\": \"large\"}));\nfig_6_3.tight_layout()\n```\n\n**Figure 6.3:** The time profiles of the pools involved in reaction system $\\rightarrow x_1 \\rightleftharpoons x_2 \\rightarrow$ for the same conditions as in Figure 6.2. (a) The phase portrait of $p_2$ and $p_1$. (b) The pools as a function of time.\n\n#### External disturbance:  \nThe previous simulation represents a biologically unrealistic situation. An internal concentration cannot suddenly deviate from its value independent of what else happens in the system. A much more realistic situation is one where we start out at a steady state and an environmental change is observed. In our case, the only environmental parameter is $b_1$. \n\nIn Figure\u00a06.4 we change the input flux, $b_1$, from 0.01 to 0.02 at time zero, when the system is initially in a steady state (the endpoint in Figure\u00a06.4). We make three observations:  \n\n* We see that the fast motion is not activated. \n\n* The 'inventory' or the pool of $x_1 + x_2$ moves from one steady state to another. It increases, as the forcing function was stepped up. \n\n* The 'distance from equilibrium' \n\n$$\\begin{equation} x_{1, ss} - \\frac{x_{2, ss}}{K_1} = x_{1, ss} - \\frac{x_{2, ss}}{x_{2, eq}/x_{1, eq}} = x_{1, ss}(1 - \\frac{\\Gamma}{K_1}) \\tag{6.13} \\end{equation}$$\n\nis close to zero in both steady states. The higher throughput, however, does push the system farther from equilibrium. \n\n\n```python\n# Ensure model starts simulation at a steady state.\nsim.find_steady_state(model, strategy=\"simulate\", update_values=True, verbose=True);\n\n# Simulate model with disturbance from steady state\nconc_sol, flux_sol = sim.simulate(\n    model, time=(t0, tf), perturbations={\"kf_b1\": 0.02},\n    interpolate=True, verbose=True)\n\n# Determine pools\nfor i, equation_str in enumerate(pools):\n    pool_id = \"p\" + str(i + 1)\n    conc_sol.make_aggregate_solution(\n        pool_id, equation=equation_str, \n        parameters={v1.Keq_str: v1.kf/v1.kr}, update=True)\n```\n\n    \u001b[93mWARNING:\u001b[0m \u001b[93mNo compartments found in model. Therefore creating compartment 'compartment' for entire model.\u001b[0m\n\n\n    Setting output selections\n    Setting simulation values for 'Linear_Reversible_Open'\n    Setting output selections\n    Getting time points\n    Simulating 'Linear_Reversible_Open'\n    Found steady state for 'Linear_Reversible_Open'.\n    Updating 'Linear_Reversible_Open' values\n    Adding 'Linear_Reversible_Open' simulation solutions to output\n    Getting time points\n    Parsing perturbations\n    Setting output selections\n    Setting simulation values for 'Linear_Reversible_Open'\n    Simulating 'Linear_Reversible_Open'\n    Simulation for 'Linear_Reversible_Open' successful\n    Adding 'Linear_Reversible_Open' simulation solutions to output\n    Updating stored solutions\n\n\n\n```python\nfig_6_4 = plt.figure(figsize=(11, 4))\ngs = fig_6_4.add_gridspec(nrows=1, ncols=2, width_ratios=[1, 1.5])\n\nax1 = fig_6_4.add_subplot(gs[0, 0])\nax2 = fig_6_4.add_subplot(gs[0, 1])\n\nplot_phase_portrait(\n    conc_sol, x=\"p2\", y=\"p1\", ax=ax1,\n    xlabel=\"p2 (inventory)\", ylabel=\"p1 (distance from equilibrium)\",\n    xlim=(0, 1), ylim=(0, 0.03),\n    title=(\"(a) Phase portrait of p2 vs. p1\", {\"size\": \"large\"}),\n    annotate_time_points=[t0, 1e0, 1e1, tf],\n    annotate_time_points_color=[\"red\"],\n    annotate_time_points_labels=True);\n\nplot_time_profile(\n    conc_sol,  observable=[\"p1\", \"p2\"], ax=ax2, legend=\"right outside\", \n    xlabel=\"Time\", ylabel=\"Concentrations\",\n    title=(\"(b) Pool Profiles\", {\"size\": \"large\"}));\nfig_6_4.tight_layout()\n```\n\n**Figure 6.4:** The time profiles of the pools involved in reaction system $\\rightarrow x_1 \\rightleftharpoons x_2 \\rightarrow$ where the system starts out at equilibrium and the input rate, $b_1$, is changed from 0.01 to 0.02 at time zero. (a) The phase portrait of $p_2$ and $p_1$; (b) The pools as a function of time. Note the small numerical change in $p_1$ relative to $p_2$. Parameter values as in Figures\u00a06.2 and Figure\u00a06.3.\n\n## Michaelis-Menten Kinetics in an Open Environment\nWe now consider the case when the Michaelis-Menten reaction mechanism operates in an open environment (Figure\u00a06.5). The substrate enters the system and the product leaves. The enzyme stays internal to the system. \n\n\n\n**Figure 6.5:** The Michaelis-Menten reaction mechanisms in an open setting. The substrate and the product enter and leave the system, while the enzyme stays inside.\n\n### Dynamic description  \nThe mass action kinetic model is \n\n$$\\begin{align} \\frac{ds}{dt} &= b_1 - k_1es + k_{-1}x, \\ &s(t=0) &= s_0 &\\tag{6.14a} \\\\ \\frac{dx}{dt} &= k_1es - (k_{-1} + k_2)x, \\ &x(t=0) &= x_0 &\\tag{6.14b}\\\\ \\frac{de}{dt} &= -k_1es + (k_{-1} + k_2)x, \\ &e(t=0) &= e_0 &\\tag{6.14c} \\\\ \\frac{dp}{dt} &= k_2x + k_3p, \\ &p(t=0) &= p_0 &\\tag{6.14d} \\\\ \\end{align}$$\n\nThe initial conditions would normally be the steady state conditions. The stoichiometric matrix is \n\n$$\\begin{equation} \\textbf{S} = \\begin{pmatrix} {1} & {-1} & {1} & {0} & {0} \\\\ {0} & {-1} & {1} & {1} & {0} \\\\ {0} & {1} & {-1} & {-1} & {0} \\\\ {0} & {0} & {0} & {1} & {-1} \\\\ \\end{pmatrix} \\end{equation}$$\n$$\\tag{6.15}$$\n\nwhere $\\textbf{x}=(s,\\ e, \\ x, \\ p)$ and $\\textbf{v} = (b_1, \\ k_1es, \\ k_{-1}x, \\ k_2x, \\ k_3p)$\n\n### The steady state  \nAs in the previous section, we can compute the steady state fluxes and concentrations. We can also compute how the parameters determine the distance from equilibrium, and here we also run into an additional issue: capacity constraints that result from a conservation quantity. \n\n#### The steady state fluxes:  \nThe rank of $\\textbf{S}$ is 3, thus the dimension of the null space is 5-3=2. The null space of $\\textbf{S}$ is spanned by two vectors, (1,1,0,1,1) and (0,1,1,0,0), that correspond to a pathway through the system and an internal reversible reaction. The steady state fluxes are given by \n\n$$\\begin{align} \\textbf{v}_{ss} &= (b_1, \\ k_1e_{ss}s_{ss}, \\ k_{-1}x_{ss}, \\ k_2x_{ss}, \\ k_3p_{ss}) \\tag{6.16} \\\\ &= a(1, \\ 1, \\ 0, \\ 1, \\ 1) + b(0, 1, 1, 0, 0), \\ a \\geq 0, \\ b \\geq 0 \\tag{6.17} \\\\ \\end{align}$$\n\n\n#### The steady state concentrations:  \nThe dimension of the left null space is 4-3=1. The left null space has one conservation quantity ($e+x$), which can readily be seen from the fact that the second and third row of $\\textbf{S}$ add up to zero. The steady state flux balances for this system are \n\n$$\\begin{equation} b_1 = v_1 - v_{-1} = v_2 = v_3 \\tag{6.18} \\end{equation}$$\n\nThus, the incoming flux and the kinetic parameters immediately set the concentrations for $X$, $P$, and $E$ as \n\n$$\\begin{equation} x_{ss} = b_1/k_2, \\ p_{ss} = b_1/k_3, \\ \\text{and} \\ e_{ss} = e_t - x_{ss} = e_t -  b_1/k_2 \\tag{6.19} \\end{equation}$$\n\nand the steady state substrate concentration can be determined. The steady state concentration of the substrate is given by $k_1s_{ss}e_{ss} = b_1 + k_{-1}x_{ss}$ that can be solved to give \n\n$$\\begin{equation} s_{ss} = (\\frac{k_2}{k_1})(\\frac{k_{-1}/k_2 + 1}{e_tk_2/b_1 - 1}) \\tag{6.20} \\end{equation}$$\n\nThe steady state flux vector can now be computed \n\n$$\\begin{align} \\textbf{v}_{ss} &= (b_1, \\ b_1(k_{-1}/k_2 + 1), \\ b_1k_{-1}/k_2, \\ b_1, \\ b_1) \\tag{6.21} \\\\ &= a(1, \\ 1, \\ 0, \\ 1, \\ 1) + b(0, 1, 1, 0, 0), \\ a=b_1, \\ b=b_1k_{-1}/k_2 \\tag{6.22} \\\\ \\end{align}$$\n\nThe distance from equilibrium can now be computed as in the previous section. \n\n#### Internal capacity constraints:  \nSince $e_{ss} \\geq 0$, the maximum input is \n\n$$\\begin{equation} b_1 \\leq b_{1, max} = k_2e_t = v_m \\tag{6.23} \\end{equation}$$\n\nwhich is the maximum reaction rate for the Michaelis-Menten mechanism. The total amount of the enzyme and the turnover rate set this flux constraint. \n\n\n```python\nmodel = MassModel('Michaelis_Menten_Open')\n## Define metabolites\ns = MassMetabolite(\"s\")\ne = MassMetabolite(\"e\")\nx = MassMetabolite(\"x\")\np = MassMetabolite(\"p\")\n\n# Define reactions\nb1 = MassReaction(\"b1\", reversible=False)\nv1 = MassReaction(\"v1\")\nv2 = MassReaction(\"v2\", reversible=False)\nv3 = MassReaction(\"v3\", reversible=False)\n\nb1.add_metabolites({s: 1})\nv1.add_metabolites({s: -1, e: -1, x: 1})\nv2.add_metabolites({x: -1, e: 1, p: 1})\nv3.add_metabolites({p: -1})\nmodel.add_reactions([b1, v1, v2, v3])\n\n## Define parameters\nb1.kf = 0.025\nv1.kf, v1.kr = (1, 0.5)\nv2.kf = 0.5\nv3.kf = 1\n\n# Set initial conditions for model\ns.ic = 1\ne.ic = 0.05\nx.ic = 0.05\np.ic = 0\n\n# Utilize type 2 rate law for kf and kr parameters defined\nmodel.get_rate_expressions(rate_type=2, update_reactions=True)\n\n# Set a custom rate for b1 to remove substrate concentration dependence\nmodel.add_custom_rate(reaction=b1, custom_rate=b1.kf_str)\n```\n\n\n```python\nt0 = 0\ntf = 2e3\n\nsim = Simulation(model, verbose=True)\n# Simulate model with disturbance from steady state\nconc_sol, flux_sol = sim.simulate(\n    model, time=(t0, tf), perturbations={\"kf_b1\": 0.04},\n    interpolate=True, verbose=True)\n```\n\n    \u001b[93mWARNING:\u001b[0m \u001b[93mNo compartments found in model. Therefore creating compartment 'compartment' for entire model.\u001b[0m\n\n\n    Successfully loaded MassModel 'Michaelis_Menten_Open' into RoadRunner.\n    Getting time points\n    Parsing perturbations\n    Setting output selections\n    Setting simulation values for 'Michaelis_Menten_Open'\n    Simulating 'Michaelis_Menten_Open'\n    Simulation for 'Michaelis_Menten_Open' successful\n    Adding 'Michaelis_Menten_Open' simulation solutions to output\n    Updating stored solutions\n\n\n\n```python\nfig_6_6 = plt.figure(figsize=(8, 6))\ngs = fig_6_6.add_gridspec(nrows=2, ncols=2, width_ratios=[1, 1.5],\n                          height_ratios=[1, 1])\n\nax1 = fig_6_6.add_subplot(gs[0, 0])\nax2 = fig_6_6.add_subplot(gs[0, 1])\nax3 = fig_6_6.add_subplot(gs[1, 1])\n\nplot_phase_portrait(\n    conc_sol, x=s, y=x, ax=ax1,\n    xlabel=s.id, ylabel=x.id,\n    xlim=(-0.1, 6), ylim=(0, 0.105),\n    title=(\"(a) Phase Portrait of s vs. x\", {\"size\":\"large\"}),\n    annotate_time_points=\"endpoints\",\n    annotate_time_points_labels=True)\n\nplot_time_profile(\n    conc_sol, observable=x, ax=ax2, legend=\"best\",\n    ylim=(0.03, 0.09), xlabel=\"Time\", ylabel=\"Concentration\",\n    title=(\"(b) Time Response of x\", {\"size\": \"large\"}));\n\nplot_time_profile(\n    conc_sol, observable=s, ax=ax3, legend=\"best\",\n    ylim=(0, 6), xlabel=\"Time\", ylabel=\"Concentration\",\n    title=(\"(c) Time Response of s\", {\"size\": \"large\"}));\nfig_6_6.tight_layout()\n```\n\n**Figure 6.6:** The time profiles for the transient response of the Michaelis-Menten mechanisms for $b_1 = 0.025$ changed to 0.04 at time zero. The kinetic parameters are; $e_t = 0.1$,  $k_1 = 1$, $k_{-1} = 0.5$, $k_2 = 0.5$, $k_3 = 0.1$. (a) The phase portrait of $s$ vs. $x$. (b) The time response of $x$. (c) The time response of $s$.\n\n### Dynamic states for Michaelis-Menten kinetics\nThe response of this system to a change in the input rate starting from a steady state is of greatest interest, see Figure\u00a06.6. For the kinetic parameters given in the figure, the steady state concentrations of $s$ and $x$ are 1.0 and 0.5 respectively. The input rate is changed from 0.025 to 0.04 at time zero and the concentrations of $s$ and $x$ go to 4.0 and 0.8, respectively, as time goes to infinity. The maximum flux rate is 0.05. \n\nThe change in the input rate triggers an internal motion that basically follows the quasi-steady state line (Figure\u00a06.6c). Figure\u00a06.6b and Figure\u00a06.6c shows that since the internal steps are rapid relative to the exchange rates, there are no rapid transients produced by a perturbation in the input rate. \n\nIf the input is increased towards $v_m$, the substrate concentration builds up to a very high value and most of the enzyme is found in the intermediate state. If the input rate exceeds $v_m$ there will be no steady state as the enzyme cannot convert the substrate to the product at the same rate as it is entering the system. \n\nThe dynamic properties of this open system can be analyzed using pool formation.\n\n## Summary  \n* Open systems eventually reach a steady state, which is different from the equilibrium state of a closed system. Such steady states can be thought of as homeostatic, living states. \n\n* Living cells are open systems that continually exchange mass and energy with their environment. The continual net throughput of mass and concomitant energy dissipation is what allows steady states to form and differentiates them from equilibrium states. \n\n* The relative rates of the internal network to that of the exchanges across the system boundary are important. Time scale separation between internal and exchange processes can form. Rapid internal transients lead to pool formation. \n\n* Open systems are most naturally in a steady state and respond to external stimuli. It is normally not possible to suddenly change the internal state of the system since it is in balance with the environment. \n\n* If the internal dynamics are fast, they do not excite when external stimuli are experienced, and thus accurate information about the fast kinetics may not be needed. It may be enough to know that they are \"fast.\" \n\n* Non-exchanged moieties form dynamic invariants. They can set internal capacity constraints. \n\n$\\tiny{\\text{\u00a9 B. \u00d8. Palsson 2011;}\\ \\text{This publication is in copyright.}\\\\ \\text{Subject to statutory exception and to the provisions of relevant collective licensing agreements,}\\\\ \\text{no reproduction of any part may take place without the written permission of Cambridge University Press.}}$\n", "meta": {"hexsha": "3fc188b776adbbfcb769644b99a0aad395b75888", "size": 180311, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/education/sb2/chapters/sb2_chapter6.ipynb", "max_stars_repo_name": "z-haiman/MASSpy", "max_stars_repo_head_hexsha": "aeeed1e3f9d1058e9485247a86f85cb94eeecbc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/education/sb2/chapters/sb2_chapter6.ipynb", "max_issues_repo_name": "z-haiman/MASSpy", "max_issues_repo_head_hexsha": "aeeed1e3f9d1058e9485247a86f85cb94eeecbc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/education/sb2/chapters/sb2_chapter6.ipynb", "max_forks_repo_name": "z-haiman/MASSpy", "max_forks_repo_head_hexsha": "aeeed1e3f9d1058e9485247a86f85cb94eeecbc9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 222.0578817734, "max_line_length": 42772, "alphanum_fraction": 0.8874500169, "converted": true, "num_tokens": 8865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491213037224875, "lm_q2_score": 0.0863234801121116, "lm_q1q2_score": 0.03322695463109932}}
{"text": "# Open Systems\nAll of the examples in the previous two chapters were closed systems. The ultimate state of closed, chemically reacting systems is chemical equilibrium. Living systems are characterized by mass and energy flow across their boundaries that keep them away from equilibrium. We now discuss open systems, which allow molecules to enter and leave. Open systems ultimately reach a steady state that is often close to a homeostatic state of interest. \n\n**MASSpy** will be used to demonstrate some of the topics in this chapter. \n\n\n```python\nfrom mass import (\n    MassModel, MassMetabolite, MassReaction, Simulation, MassSolution)\nfrom mass.visualization import plot_time_profile, plot_phase_portrait\n```\n\nOther useful packages are also imported at this time.\n\n\n```python\nimport matplotlib.pyplot as plt\n```\n\n## Basic Concepts\nThere are several fundamental concepts that need to be understood when one considers open systems. We discuss the more significant ones in this section. \n\n### The system boundary  \nImplicit in the term 'open system' is the notion of an inside and an outside, the division of the world into two domains. The separation between the two is the _system boundary,_ which thus defines what is inside a system and belongs to it, and what is outside. \n\nThe definition of a boundary can be physical. An example of a physical boundary may be the cell wall, that clearly defines what is inside and what is outside. Similarly, the outer membrane of the mitochondria can serve as a clearly defined physical system boundary. Thus, systems can have hard, immovable boundaries or soft, flexible ones. In the latter case, the volume of the system may be changing. \n\nThe definition of a boundary can also be virtual. For instance, we can define a pathway, such as the TCA cycle, as a system, or the amino acid biosynthetic pathways in a cell as a system. In both cases we might draw dashed lines around it on the metabolic map to indicate the system boundary. \n\n### Crossing the boundary: inputs and outputs  \nOnce a system boundary has been established, we can identify and define interactions across it. They are the _inputs_ and _outputs_ of the system. In most cases, we will be considering mass flows in and out of a system; molecules coming and going. Such flows are normally amenable to experimental determination. \n\nThere may be other quantities crossing the system boundary. For instance, if we are considering photosynthesis, photons are crossing the system boundary providing a net influx of energy. Forces can also act on the system boundary. For instance, if the number of molecules coming into and leaving a system through a coupled transport mechanism is not balanced, then osmotic pressure may be generated across the system boundary. Cells have sodium-potassium pumps that displace an uneven number of two types of cations to deal with osmotic imbalances. \n\n### Perturbations and boundaries  \nIn most analyses of living systems, we are concerned about changes in the environment. The temperature may change, substrate availability may change, and so on. Such changes in the environment can be thought of as forcing functions to which the living system responds. These are one-way interactions, from the environment to the system. In most cases, we consider the system to be small (relative to the environment) and that the environment buffers the activities of the system. For instance, the environment may provide an infinite sink for cellular waste products. \n\nIn other cases, the activities of the system influence the state of the environment. In batch fermentation, for example, the metabolic activities will substantially change the chemical composition of the medium during the course of the fermentation. On a global scale, we are now becoming more concerned about the impact that human activities have on the climate and the larger environment of human socio-economic activities. In such cases, there are two-way interactions between the system and the environment that need to be described. \n\n### Inside the boundary: the internal network  \nThe definition of a system boundary determines what is inside. Once we know what is inside the system, we can determine the network of chemical transformations that takes place. This network has topology and its links have kinetic properties. \n\nIn most cases, it is hard to measure the internal state of a system. There typically are only a few non-invasive measurements available. Occasionally, there are probes that we can use to observe the internal activities. Tracers, such as $^{13}C$ atoms strategically placed in substrates, can be used to trace input to output and allow us to determine pieces of the internal state of a system. Tearing a system apart to enumerate its components is of course possible, but the system is destroyed in the process. Thus, we are most often in the situation where we cannot fully experimentally determine the internal state of a system, and may have to be satisfied with only partial knowledge. \n\n### From networks to system models  \nMathematical models may help us to simulate or estimate the internal state of the system. Sometimes we are able to bracket its state based on the inputs and outputs and our knowledge of the internal network. \n\nFull dynamic simulation requires extensive knowledge about the internal properties of a system. Detailed models that describe the dynamic state of a system require the definition of the system boundary, the inputs and outputs, the structure of the internal network, and the kinetic properties of the links in the network. We can then simulate the response of the system to various perturbations, such as changes in the environmental conditions. \n\n### The functional state  \nOnce a system model has been formulated, it can be used to compute the functional state of the system for a given set of conditions. Closed systems will eventually go to chemical equilibrium. However, open systems are fundamentally different. Due to continuous interactions with the environment, they have internal states that are either dynamic or steady. A system that has fast internal time constants relative to changes in the environment will reach a steady state, or a quasi-steady state. For a biological system, such functional states are called _homeostatic states_. Such states are maintained through energy dissipation. The flow of energy in has to exceed the energy leaving the system. This difference allows living systems to reach a functional homeostatic state. \n\n\n\n**Figure 6.1:** Open systems. (a) example production of ATP from pyruvate by mitochondria (Prepared by Nathan Lewis). (b) Basic definitions associated with an open system.\n\n## Reversible reaction in an Open Environment\nIn an open environment, the simple reaction of Eq. (4.1)  has an inflow $(b_1)$ of $x_1$ and an outflow $(b_2)$ of $x_2$: \n\n$$\\begin{equation} \\stackrel{b_1}{\\rightarrow} x_1 \\underset{v_{-1}}{\\stackrel{v_1}{\\rightleftharpoons}} x_2 \\stackrel{b_2}{\\rightarrow} \\tag{6.1} \\end{equation}$$\n\nThe input is fixed by the environment and there is a first-order rate for the product to leave the system and thus we have \n\n$$\\begin{equation} b_1 = \\text{constant and}\\ b_2 = k_2x_2 \\end{equation}$$\n\nThis defines the system boundary, and the inputs and outputs. \n\nThe stoichiometric matrix is \n\n$$\\begin{equation} \\textbf{S} = \\begin{pmatrix} {1} & {-1} & {1} & {0} \\\\ {0} & {1} & {-1} & {-1} \\\\ \\end{pmatrix} \\end{equation} \\tag{6.2}$$\n\nwhere $\\textbf{x} = (x_1,\\  x_2)$ and $\\textbf{v} = (b_1, \\ k_1x_1, \\  k_{-1}x_2, \\  k_2x_2)$ The stoichiometric matrix has a rank of 2 and is thus a two-dimensional dynamic system. The differential equations that will need to be solved are: \n\n$$\\begin{equation} \\frac{dx_1}{dt} = b_1 - k_1x_1 + k_{-1}x_2, \\ \n\\frac{dx_2}{dt} = k_1x_1 - k_{-1}x_2 - k_2x_2 \\tag{6.3} \\end{equation}$$\n\nThere are no conservation quantities. \n\n### The steady states  \nThere are three properties of the steady state of interest. We can find first the steady state fluxes and second the steady state concentrations. Third, we can determine the difference between the steady state and the equilibrium state of this open system. \n\n#### Steady state fluxes:  \nThe steady state of the fluxes is given by \n\n$$\\begin{equation} \\textbf{Sv}_{ss} = 0 \\tag{6.4} \\end{equation}$$\n\nand thus $\\textbf{v}_{ss}$ resides in the null space of $\\textbf{S}$. For this matrix, the null space is two dimensional; $\\text{Dim}(\\text{Null}(\\textbf{S}))=n-r=4-2=2$, where $n=4$ is the number of fluxes and the rank is $r=2$. The null space is spanned by two pathway vectors: (1,1,0,1) and (0,1,1,0). The former is the path through the system while the latter corresponds to the reversible reaction. These are known as type 1 and type 3 extreme pathways, respectively\u00a0(_Systems Biology: Properties of Reconstructed Networks_). All steady state flux states of the system are a non-negative combination of these two vectors. \n\n$$\\begin{align} \\textbf{v}_{ss} &= (b_1, \\ k_1x_{1, ss}, \\ k_{-1}x_{2, ss}, \\ k_2x_{2, ss})  \\tag{6.5} \\\\ &= a(1, 1, 0, 1) + b(0, 1, 1, 0), \\ a \\geq 0, \\ b \\geq 0 \\tag{6.6} \\end{align}$$\n\n#### Steady state concentrations:  \nThe concentrations in the steady state can be evaluated from \n\n$$\\begin{equation} 0 = b_1 - k_1x_1 + k_{-1}x_2, \\ 0 = k_1x_1 - k_{-1}x_2 - k_2x_2 \\end{equation}$$ $$\\tag{6.7}$$\n\nIf we add these equations we find that $x_{2, ss} = b_1 / k_2$. This concentration can then be substituted into either of the two equations to show that $x_{1, ss} = (1 + k_{-1}/k_2)(b_1/k_1)$. Thus, the steady state concentration vector is \n\n$$\\begin{equation} \\textbf{x}_{ss} = \\begin{pmatrix} {x_{1, ss}} \\\\ {x_{2, ss}} \\end{pmatrix} = (\\frac{b_1}{k_2})\\begin{pmatrix} {\\frac{k_2 + k_{-1}}{k_1}} \\\\ {1} \\end{pmatrix} \\end{equation}$$ $$\\tag{6.8}$$\n\nThese steady state concentrations can be substituted into the steady state flux vector to get \n\n$$\\begin{align} \\textbf{v}_{ss} &= b_1(1, 1+(\\frac{k_{-1}}{k_2}), \\ (\\frac{k_{-1}}{k_2}), \\ 1)  \\tag{6.9} \\\\ &= a(1, 1, 0, 1) + b(0, 1, 1, 0), \\ a = b_1, \\ b = (\\frac{b_1k_{-1}}{k_2}) \\end{align}$$\n\nTherefore, the steady state flux distribution is a summation of the straight through pathway and the discounted flux through the reversible reaction. The key quantity is $k_{-1} / k_2$ that measures the relative rate of $x_2$ reacting back to form $x_1$ versus the rate at which it leaves the system. \n\n#### The distance from the equilibrium state:  \nThe difference between the steady state and the equilibrium state can be measured by: \n\n$$\\begin{equation} \\frac{x_{2, ss}/x_{1, ss}}{x_{2, eq}/x_{1, eq}} = \\frac{1}{1 + k_2/k_{-1}} \\stackrel{k_2 << k_{-1}}{\\longrightarrow} 1 \\tag{6.11} \\end{equation}$$\n\nThus, when $k_2 << k_{-1}$, the steady state approaches the equilibrium state (recall that $(x_{2, ss}/x_{1, ss})/(x_{2, eq}/x_{1, eq}) = \\Gamma/K_{eq}$ Section\u00a02.2). If the exchange with the environment is slow relative to the internal reaction rates, the internal system approaches that of an equilibrium state. \n\n### Dynamic states for reversible reactions\nThe dynamic states are computed from the dynamic mass balances for a given condition. We are interested in two dynamic states: the approach to the steady state, and the response to a change in the input flux, $b_1$\n\n#### A two-phase transient response:  \nSimulation of this system with an input rate of $b_1 = 0.01$ and a slow removal rate, $k_2 = 0.1$, from an initial state of $x_1(0) = 1.0$ and $x_2(0) = 0$ is shown in Figure\u00a06.2. There are two discernible time scales: a rapid motion of the equilibrating reaction, and a slow removal of $x_2$ from the system, Figure\u00a06.2b. A phase portrait shows a rapid movement along a line with a negative slope of 1, showing the existence of a conservation quantity $(x_1 + x_2)$ on a fast time scale, followed by a slow motion down a quasi-equilibrium line with a slope of 1/2 to a steady state point. Note the difference from Figure 4.4c. \n\n\n```python\n# Create MassModel\nmodel = MassModel('Linear_Reversible_Open')\n# Generate the MassMetabolites \nx1 = MassMetabolite(\"x1\")\nx2 = MassMetabolite(\"x2\")\n\n# Generate the MassReactions \nb1 = MassReaction(\"b1\", reversible=False)\nv1 = MassReaction(\"v1\")\nb2 = MassReaction(\"b2\", reversible=False)\n# Add metabolites to the reaction, add reaction to the model\nb1.add_metabolites({x1: 1})\nv1.add_metabolites({x1: -1, x2: 1})\nb2.add_metabolites({x2: -1})\nmodel.add_reactions([b1, v1, b2])\n# Set parameters\nb1.kf = 0.01\nv1.kf, v1.kr = (1, 2)\nb2.kf = 0.1\n\n# Set initial conditions for model\nx1.ic = 1\nx2.ic = 0\n# Utilize type 2 rate law for kf and kr parameters defined\nmodel.get_rate_expressions(rate_type=2, update_reactions=True)\n\n# Set a custom rate for b1 to remove substrate concentration dependence\nmodel.add_custom_rate(reaction=b1, custom_rate=b1.kf_str)\n```\n\n\n```python\nt0 = 0\ntf = 150\n\nsim = Simulation(model, verbose=True)\nconc_sol, flux_sol = sim.simulate(model, time=(t0, tf),\n                                  interpolate=True,\n                                  verbose=True)\n```\n\n    \u001b[93mWARNING:\u001b[0m \u001b[93mNo compartments found in model. Therefore creating compartment 'compartment' for entire model.\u001b[0m\n\n\n    Successfully loaded MassModel 'Linear_Reversible_Open' into RoadRunner.\n    Getting time points\n    Setting output selections\n    Setting simulation values for 'Linear_Reversible_Open'\n    Simulating 'Linear_Reversible_Open'\n    Simulation for 'Linear_Reversible_Open' successful\n    Adding 'Linear_Reversible_Open' simulation solutions to output\n    Updating stored solutions\n\n\n\n```python\nfig_6_2 = plt.figure(figsize=(13, 5))\ngs = fig_6_2.add_gridspec(nrows=1, ncols=2, width_ratios=[1, 1.5])\n\nax1 = fig_6_2.add_subplot(gs[0, 0])\nax2 = fig_6_2.add_subplot(gs[0, 1])\n\nplot_phase_portrait(\n    conc_sol, x=x1, y=x2, ax=ax1,\n    xlabel=x1.id, ylabel=x2.id, xlim=(-.05, 1.2), ylim=(-.05, 0.5),\n    title=(\"(a) Phase portrait of x1 vs. x2\", {\"size\": \"large\"}),\n    annotate_time_points=[t0, 1e0, 1e1, tf],\n    annotate_time_points_color=[\"red\"],\n    annotate_time_points_labels=True);\n\nax1.annotate(\n    'motion towards\\n  a qe state', \n    xy=(conc_sol[x1.id](0.5), conc_sol[x2.id](0.5)), \n    xytext=(conc_sol[x1.id](0.3), conc_sol[x2.id](0.3)));\n\nax1.annotate(\n    'motion of a\\n  qe state', \n    xy=(conc_sol[x1.id](tf), conc_sol[x2.id](tf)), \n    xytext=(conc_sol[x1.id](tf) + 0.05, conc_sol[x2.id](tf) + 0.15));\n\nplot_time_profile(\n    conc_sol, ax=ax2, legend=\"right outside\", \n    xlabel=\"Time\", ylabel=\"Concentrations\",\n    title=(\"(b) Concentration Profiles\", {\"size\": \"large\"}));\nfig_6_2.tight_layout()\n```\n\n**Figure 6.2:** The concentration time profiles for the reaction system $\\rightarrow x_1 \\rightleftharpoons x_2 \\rightarrow$ for $k_1 = 1$, $k_{-1} = 2$, $x_1(0) = 0$, and $b_1 = 0.01$. (a) The phase portrait of $x_1$ and $x_2$ (b) The concentrations as a function of time.\n\nThe same pools can be formed as defined in Eq. (4.9):\n\n$$\\begin{equation} \\begin{pmatrix} {p_1} \\\\ {p_2} \\end{pmatrix} = \\begin{pmatrix} {1} & {-1/K_1} \\\\ {1} & {1} \\end{pmatrix} = \\begin{pmatrix} {x_1} \\\\ {x_2} \\end{pmatrix} \\end{equation} \\tag{6.12}$$\n\nThis matrix can be used to post-process the concentrations and the results can be graphed, Figure\u00a06.3. The pool transformation leads to dynamic decoupling and is clearly illustrated in this figure. The disequilibrium pool relaxes very quickly, while the conservation pool moves slowly, Figure\u00a06.3b. The phase portrait formed by the pools thus has an L shape (Figure\u00a06.3a), illustrating the dynamic decoupling. Note that: \n\n* There is first a vertical motion where $x_1 + x_2$ is essentially a constant, followed by a slow horizontal motion where the disequilibrium variable $x_1 - x_2 /K_1$ is a constant. \n\n* These two separate motions correspond to forming the pathways found in the steady state. \n\n* The disequilibrium aggregate is not zero, as it is forced away from equilibrium by the input and settling in a steady state. \n\n\n```python\n# Define pools\npools = [\"x1 - x2 / Keq_v1\", \"x1 + x2\"]\nfor i, equation_str in enumerate(pools):\n    pool_id = \"p\" + str(i + 1)\n    conc_sol.make_aggregate_solution(\n        pool_id, equation=equation_str, \n        parameters={v1.Keq_str: v1.kf/v1.kr}, update=True)\n\nfig_6_3 = plt.figure(figsize=(11, 4))\ngs = fig_6_3.add_gridspec(nrows=1, ncols=2, width_ratios=[1, 1.5])\n\nax1 = fig_6_3.add_subplot(gs[0, 0])\nax2 = fig_6_3.add_subplot(gs[0, 1])\n\nplot_phase_portrait(\n    conc_sol, x=\"p2\", y=\"p1\", ax=ax1,\n    xlabel=\"p2 (inventory)\", ylabel=\"p1 (distance from equilibrium)\",\n    xlim=(-.05, 2.1), ylim=(-.05, 1.05),\n    title=(\"(a) Phase portrait of p2 vs. p1\", {\"size\": \"large\"}),\n    annotate_time_points=[t0, 1e0, 1e1, tf],\n    annotate_time_points_color=[\"red\"],\n    annotate_time_points_labels=True);\n\nax1.annotate(\n    'motion towards\\n  a qe state', \n    xy=(conc_sol[\"p2\"](0.5), conc_sol[\"p1\"](0.5)), \n    xytext=(conc_sol[\"p2\"](0.3), conc_sol[\"p1\"](0.3)));\n\nax1.annotate(\n    'motion of a\\n  qe state', \n    xy=(conc_sol[\"p2\"](tf), conc_sol[\"p1\"](tf)), \n    xytext=(conc_sol[\"p2\"](tf) + 0.05, conc_sol[\"p1\"](tf) + 0.1));\n\nplot_time_profile(\n    conc_sol, observable=[\"p1\", \"p2\"], ax=ax2, legend=\"right outside\", \n    xlabel=\"Time\", ylabel=\"Concentrations\",\n    title=(\"(b) Pool Profiles\", {\"size\": \"large\"}));\nfig_6_3.tight_layout()\n```\n\n**Figure 6.3:** The time profiles of the pools involved in reaction system $\\rightarrow x_1 \\rightleftharpoons x_2 \\rightarrow$ for the same conditions as in Figure 6.2. (a) The phase portrait of $p_2$ and $p_1$. (b) The pools as a function of time.\n\n#### External disturbance:  \nThe previous simulation represents a biologically unrealistic situation. An internal concentration cannot suddenly deviate from its value independent of what else happens in the system. A much more realistic situation is one where we start out at a steady state and an environmental change is observed. In our case, the only environmental parameter is $b_1$. \n\nIn Figure\u00a06.4 we change the input flux, $b_1$, from 0.01 to 0.02 at time zero, when the system is initially in a steady state (the endpoint in Figure\u00a06.4). We make three observations:  \n\n* We see that the fast motion is not activated. \n\n* The 'inventory' or the pool of $x_1 + x_2$ moves from one steady state to another. It increases, as the forcing function was stepped up. \n\n* The 'distance from equilibrium' \n\n$$\\begin{equation} x_{1, ss} - \\frac{x_{2, ss}}{K_1} = x_{1, ss} - \\frac{x_{2, ss}}{x_{2, eq}/x_{1, eq}} = x_{1, ss}(1 - \\frac{\\Gamma}{K_1}) \\tag{6.13} \\end{equation}$$\n\nis close to zero in both steady states. The higher throughput, however, does push the system farther from equilibrium. \n\n\n```python\n# Ensure model starts simulation at a steady state.\nsim.find_steady_state(model, strategy=\"simulate\", update_values=True, verbose=True);\n\n# Simulate model with disturbance from steady state\nconc_sol, flux_sol = sim.simulate(\n    model, time=(t0, tf), perturbations={\"kf_b1\": 0.02},\n    interpolate=True, verbose=True)\n\n# Determine pools\nfor i, equation_str in enumerate(pools):\n    pool_id = \"p\" + str(i + 1)\n    conc_sol.make_aggregate_solution(\n        pool_id, equation=equation_str, \n        parameters={v1.Keq_str: v1.kf/v1.kr}, update=True)\n```\n\n    \u001b[93mWARNING:\u001b[0m \u001b[93mNo compartments found in model. Therefore creating compartment 'compartment' for entire model.\u001b[0m\n\n\n    Setting output selections\n    Setting simulation values for 'Linear_Reversible_Open'\n    Setting output selections\n    Getting time points\n    Simulating 'Linear_Reversible_Open'\n    Found steady state for 'Linear_Reversible_Open'.\n    Updating 'Linear_Reversible_Open' values\n    Adding 'Linear_Reversible_Open' simulation solutions to output\n    Getting time points\n    Parsing perturbations\n    Setting output selections\n    Setting simulation values for 'Linear_Reversible_Open'\n    Simulating 'Linear_Reversible_Open'\n    Simulation for 'Linear_Reversible_Open' successful\n    Adding 'Linear_Reversible_Open' simulation solutions to output\n    Updating stored solutions\n\n\n\n```python\nfig_6_4 = plt.figure(figsize=(11, 4))\ngs = fig_6_4.add_gridspec(nrows=1, ncols=2, width_ratios=[1, 1.5])\n\nax1 = fig_6_4.add_subplot(gs[0, 0])\nax2 = fig_6_4.add_subplot(gs[0, 1])\n\nplot_phase_portrait(\n    conc_sol, x=\"p2\", y=\"p1\", ax=ax1,\n    xlabel=\"p2 (inventory)\", ylabel=\"p1 (distance from equilibrium)\",\n    xlim=(0, 1), ylim=(0, 0.03),\n    title=(\"(a) Phase portrait of p2 vs. p1\", {\"size\": \"large\"}),\n    annotate_time_points=[t0, 1e0, 1e1, tf],\n    annotate_time_points_color=[\"red\"],\n    annotate_time_points_labels=True);\n\nplot_time_profile(\n    conc_sol,  observable=[\"p1\", \"p2\"], ax=ax2, legend=\"right outside\", \n    xlabel=\"Time\", ylabel=\"Concentrations\",\n    title=(\"(b) Pool Profiles\", {\"size\": \"large\"}));\nfig_6_4.tight_layout()\n```\n\n**Figure 6.4:** The time profiles of the pools involved in reaction system $\\rightarrow x_1 \\rightleftharpoons x_2 \\rightarrow$ where the system starts out at equilibrium and the input rate, $b_1$, is changed from 0.01 to 0.02 at time zero. (a) The phase portrait of $p_2$ and $p_1$; (b) The pools as a function of time. Note the small numerical change in $p_1$ relative to $p_2$. Parameter values as in Figures\u00a06.2 and Figure\u00a06.3.\n\n## Michaelis-Menten Kinetics in an Open Environment\nWe now consider the case when the Michaelis-Menten reaction mechanism operates in an open environment (Figure\u00a06.5). The substrate enters the system and the product leaves. The enzyme stays internal to the system. \n\n\n\n**Figure 6.5:** The Michaelis-Menten reaction mechanisms in an open setting. The substrate and the product enter and leave the system, while the enzyme stays inside.\n\n### Dynamic description  \nThe mass action kinetic model is \n\n$$\\begin{align} \\frac{ds}{dt} &= b_1 - k_1es + k_{-1}x, \\ &s(t=0) &= s_0 \\\\ \\frac{dx}{dt} &= k_1es - (k_{-1} + k_2)x, \\ &x(t=0) &= x_0 \\\\ \\frac{de}{dt} &= -k_1es + (k_{-1} + k_2)x, \\ &e(t=0) &= e_0 \\\\ \\frac{dp}{dt} &= k_2x + k_3p, \\ &p(t=0) &= p_0 \\\\ \\end{align} \\tag{6.14}$$\n\nThe initial conditions would normally be the steady state conditions. The stoichiometric matrix is \n\n$$\\begin{equation} \\textbf{S} = \\begin{pmatrix} {1} & {-1} & {1} & {0} & {0} \\\\ {0} & {-1} & {1} & {1} & {0} \\\\ {0} & {1} & {-1} & {-1} & {0} \\\\ {0} & {0} & {0} & {1} & {-1} \\\\ \\end{pmatrix} \\end{equation} \\tag{6.15}$$\n\nwhere $\\textbf{x}=(s,\\ e, \\ x, \\ p)$ and $\\textbf{v} = (b_1, \\ k_1es, \\ k_{-1}x, \\ k_2x, \\ k_3p)$\n\n### The steady state  \nAs in the previous section, we can compute the steady state fluxes and concentrations. We can also compute how the parameters determine the distance from equilibrium, and here we also run into an additional issue: capacity constraints that result from a conservation quantity. \n\n#### The steady state fluxes:  \nThe rank of $\\textbf{S}$ is 3, thus the dimension of the null space is 5-3=2. The null space of $\\textbf{S}$ is spanned by two vectors, (1,1,0,1,1) and (0,1,1,0,0), that correspond to a pathway through the system and an internal reversible reaction. The steady state fluxes are given by \n\n$$\\begin{align} \\textbf{v}_{ss} &= (b_1, \\ k_1e_{ss}s_{ss}, \\ k_{-1}x_{ss}, \\ k_2x_{ss}, \\ k_3p_{ss}) \\tag{6.16} \\\\ &= a(1, \\ 1, \\ 0, \\ 1, \\ 1) + b(0, 1, 1, 0, 0), \\ a \\geq 0, \\ b \\geq 0 \\tag{6.17} \\\\ \\end{align}$$\n\n\n#### The steady state concentrations:  \nThe dimension of the left null space is 4-3=1. The left null space has one conservation quantity ($e+x$), which can readily be seen from the fact that the second and third row of $\\textbf{S}$ add up to zero. The steady state flux balances for this system are \n\n$$\\begin{equation} b_1 = v_1 - v_{-1} = v_2 = v_3 \\tag{6.18} \\end{equation}$$\n\nThus, the incoming flux and the kinetic parameters immediately set the concentrations for $X$, $P$, and $E$ as \n\n$$\\begin{equation} x_{ss} = b_1/k_2, \\ p_{ss} = b_1/k_3, \\ \\text{and} \\ e_{ss} = e_t - x_{ss} = e_t -  b_1/k_2 \\tag{6.19} \\end{equation}$$\n\nand the steady state substrate concentration can be determined. The steady state concentration of the substrate is given by $k_1s_{ss}e_{ss} = b_1 + k_{-1}x_{ss}$ that can be solved to give \n\n$$\\begin{equation} s_{ss} = (\\frac{k_2}{k_1})(\\frac{k_{-1}/k_2 + 1}{e_tk_2/b_1 - 1}) \\tag{6.20} \\end{equation}$$\n\nThe steady state flux vector can now be computed \n\n$$\\begin{align} \\textbf{v}_{ss} &= (b_1, \\ b_1(k_{-1}/k_2 + 1), \\ b_1k_{-1}/k_2, \\ b_1, \\ b_1) \\tag{6.21} \\\\ &= a(1, \\ 1, \\ 0, \\ 1, \\ 1) + b(0, 1, 1, 0, 0), \\ a=b_1, \\ b=b_1k_{-1}/k_2 \\tag{6.22} \\\\ \\end{align}$$\n\nThe distance from equilibrium can now be computed as in the previous section. \n\n#### Internal capacity constraints:  \nSince $e_{ss} \\geq 0$, the maximum input is \n\n$$\\begin{equation} b_1 \\leq b_{1, max} = k_2e_t = v_m \\tag{6.23} \\end{equation}$$\n\nwhich is the maximum reaction rate for the Michaelis-Menten mechanism. The total amount of the enzyme and the turnover rate set this flux constraint. \n\n\n```python\nmodel = MassModel('Michaelis_Menten_Open')\n## Define metabolites\ns = MassMetabolite(\"s\")\ne = MassMetabolite(\"e\")\nx = MassMetabolite(\"x\")\np = MassMetabolite(\"p\")\n\n# Define reactions\nb1 = MassReaction(\"b1\", reversible=False)\nv1 = MassReaction(\"v1\")\nv2 = MassReaction(\"v2\", reversible=False)\nv3 = MassReaction(\"v3\", reversible=False)\n\nb1.add_metabolites({s: 1})\nv1.add_metabolites({s: -1, e: -1, x: 1})\nv2.add_metabolites({x: -1, e: 1, p: 1})\nv3.add_metabolites({p: -1})\nmodel.add_reactions([b1, v1, v2, v3])\n\n## Define parameters\nb1.kf = 0.025\nv1.kf, v1.kr = (1, 0.5)\nv2.kf = 0.5\nv3.kf = 1\n\n# Set initial conditions for model\ns.ic = 1\ne.ic = 0.05\nx.ic = 0.05\np.ic = 0\n\n# Utilize type 2 rate law for kf and kr parameters defined\nmodel.get_rate_expressions(rate_type=2, update_reactions=True)\n\n# Set a custom rate for b1 to remove substrate concentration dependence\nmodel.add_custom_rate(reaction=b1, custom_rate=b1.kf_str)\n```\n\n\n```python\nt0 = 0\ntf = 2e3\n\nsim = Simulation(model, verbose=True)\n# Simulate model with disturbance from steady state\nconc_sol, flux_sol = sim.simulate(\n    model, time=(t0, tf), perturbations={\"kf_b1\": 0.04},\n    interpolate=True, verbose=True)\n```\n\n    \u001b[93mWARNING:\u001b[0m \u001b[93mNo compartments found in model. Therefore creating compartment 'compartment' for entire model.\u001b[0m\n\n\n    Successfully loaded MassModel 'Michaelis_Menten_Open' into RoadRunner.\n    Getting time points\n    Parsing perturbations\n    Setting output selections\n    Setting simulation values for 'Michaelis_Menten_Open'\n    Simulating 'Michaelis_Menten_Open'\n    Simulation for 'Michaelis_Menten_Open' successful\n    Adding 'Michaelis_Menten_Open' simulation solutions to output\n    Updating stored solutions\n\n\n\n```python\nfig_6_6 = plt.figure(figsize=(8, 6))\ngs = fig_6_6.add_gridspec(nrows=2, ncols=2, width_ratios=[1, 1.5],\n                          height_ratios=[1, 1])\n\nax1 = fig_6_6.add_subplot(gs[0, 0])\nax2 = fig_6_6.add_subplot(gs[0, 1])\nax3 = fig_6_6.add_subplot(gs[1, 1])\n\nplot_phase_portrait(\n    conc_sol, x=s, y=x, ax=ax1,\n    xlabel=s.id, ylabel=x.id,\n    xlim=(-0.1, 6), ylim=(0, 0.105),\n    title=(\"(a) Phase Portrait of s vs. x\", {\"size\":\"large\"}),\n    annotate_time_points=\"endpoints\",\n    annotate_time_points_labels=True)\n\nplot_time_profile(\n    conc_sol, observable=x, ax=ax2, legend=\"best\",\n    ylim=(0.03, 0.09), xlabel=\"Time\", ylabel=\"Concentration\",\n    title=(\"(b) Time Response of x\", {\"size\": \"large\"}));\n\nplot_time_profile(\n    conc_sol, observable=s, ax=ax3, legend=\"best\",\n    ylim=(0, 6), xlabel=\"Time\", ylabel=\"Concentration\",\n    title=(\"(c) Time Response of s\", {\"size\": \"large\"}));\nfig_6_6.tight_layout()\n```\n\n**Figure 6.6:** The time profiles for the transient response of the Michaelis-Menten mechanisms for $b_1 = 0.025$ changed to 0.04 at time zero. The kinetic parameters are; $e_t = 0.1$,  $k_1 = 1$, $k_{-1} = 0.5$, $k_2 = 0.5$, $k_3 = 0.1$. (a) The phase portrait of $s$ vs. $x$. (b) The time response of $x$. (c) The time response of $s$.\n\n### Dynamic states for Michaelis-Menten kinetics\nThe response of this system to a change in the input rate starting from a steady state is of greatest interest, see Figure\u00a06.6. For the kinetic parameters given in the figure, the steady state concentrations of $s$ and $x$ are 1.0 and 0.5 respectively. The input rate is changed from 0.025 to 0.04 at time zero and the concentrations of $s$ and $x$ go to 4.0 and 0.8, respectively, as time goes to infinity. The maximum flux rate is 0.05. \n\nThe change in the input rate triggers an internal motion that basically follows the quasi-steady state line (Figure\u00a06.6c). Figure\u00a06.6b and Figure\u00a06.6c shows that since the internal steps are rapid relative to the exchange rates, there are no rapid transients produced by a perturbation in the input rate. \n\nIf the input is increased towards $v_m$, the substrate concentration builds up to a very high value and most of the enzyme is found in the intermediate state. If the input rate exceeds $v_m$ there will be no steady state as the enzyme cannot convert the substrate to the product at the same rate as it is entering the system. \n\nThe dynamic properties of this open system can be analyzed using pool formation.\n\n## Summary  \n* Open systems eventually reach a steady state, which is different from the equilibrium state of a closed system. Such steady states can be thought of as homeostatic, living states. \n\n* Living cells are open systems that continually exchange mass and energy with their environment. The continual net throughput of mass and concomitant energy dissipation is what allows steady states to form and differentiates them from equilibrium states. \n\n* The relative rates of the internal network to that of the exchanges across the system boundary are important. Time scale separation between internal and exchange processes can form. Rapid internal transients lead to pool formation. \n\n* Open systems are most naturally in a steady state and respond to external stimuli. It is normally not possible to suddenly change the internal state of the system since it is in balance with the environment. \n\n* If the internal dynamics are fast, they do not excite when external stimuli are experienced, and thus accurate information about the fast kinetics may not be needed. It may be enough to know that they are \"fast.\" \n\n* Non-exchanged moieties form dynamic invariants. They can set internal capacity constraints. \n\n$\\tiny{\\text{\u00a9 B. \u00d8. Palsson 2011;}\\ \\text{This publication is in copyright.}\\\\ \\text{Subject to statutory exception and to the provisions of relevant collective licensing agreements,}\\\\ \\text{no reproduction of any part may take place without the written permission of Cambridge University Press.}}$\n", "meta": {"hexsha": "b0215d16d0564f5c56d6f218c8a891f4d9622169", "size": 180455, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/education/sb2/chapters/sb2_chapter6.ipynb", "max_stars_repo_name": "SBRG/MASSpy", "max_stars_repo_head_hexsha": "1315c1d40be8feb8731c8143dbc9ba43bf8c78ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2020-07-13T00:48:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T15:42:15.000Z", "max_issues_repo_path": "docs/education/sb2/chapters/sb2_chapter6.ipynb", "max_issues_repo_name": "SBRG/MASSpy", "max_issues_repo_head_hexsha": "1315c1d40be8feb8731c8143dbc9ba43bf8c78ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2021-02-17T18:07:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-23T16:22:14.000Z", "max_forks_repo_path": "docs/education/sb2/chapters/sb2_chapter6.ipynb", "max_forks_repo_name": "SBRG/MASSpy", "max_forks_repo_head_hexsha": "1315c1d40be8feb8731c8143dbc9ba43bf8c78ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2020-01-15T00:48:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T07:01:17.000Z", "avg_line_length": 225.006234414, "max_line_length": 42836, "alphanum_fraction": 0.8886813887, "converted": true, "num_tokens": 8825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.08882028757623954, "lm_q1q2_score": 0.033207758096385265}}
{"text": "## Enable rendering OpenAI Gym environments from CoLab\n\nIn this assignemnt, We will use [OpenAI Gym](https://gym.openai.com/) for rendering game envionment for our agent to play and learn. It is possible and important to visualize the game your agent is playing, even on Colab. This section imports the necessary package and functions needed to generate a video in Colab. The video processing steps credit to [here](https://colab.research.google.com/drive/1flu31ulJlgiRL1dnN2ir8wGh9p7Zij2t).\n\n\n```\n# You will need to run this block twice to make it effective\n!apt-get update > /dev/null 2>&1\n!apt-get install cmake > /dev/null 2>&1\n!pip install --upgrade setuptools 2>&1\n!pip install ez_setup > /dev/null 2>&1\n!pip install gym[atari] > /dev/null 2>&1\n!pip install box2d-py > /dev/null 2>&1\n!pip install gym[Box_2D] > /dev/null 2>&1\n```\n\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (60.10.0)\n\n\n\n```\n!pip install gym pyvirtualdisplay > /dev/null 2>&1\n!apt-get install -y xvfb python-opengl ffmpeg > /dev/null 2>&1\n```\n\nImport openAI gym and define the functions used to show the video.\n\n\n```\nimport gym\nfrom gym.wrappers import Monitor\nimport glob\nimport io\nimport base64\nfrom IPython.display import HTML\nfrom pyvirtualdisplay import Display\nfrom IPython import display as ipythondisplay\n\ndisplay = Display(visible=0, size=(1400, 900))\ndisplay.start()\n\n\"\"\"\nUtility functions to enable video recording of gym environment \nand displaying it.\nTo enable video, just do \"env = wrap_env(env)\"\"\n\"\"\"\n\ndef show_video():\n  mp4list = glob.glob('video/*.mp4')\n  if len(mp4list) > 0:\n    mp4 = mp4list[0]\n    video = io.open(mp4, 'r+b').read()\n    encoded = base64.b64encode(video)\n    ipythondisplay.display(HTML(data=''''''.format(encoded.decode('ascii'))))\n  else: \n    print(\"Could not find video\")\n    \n\ndef wrap_env(env):\n  env = Monitor(env, './video', force=True)\n  return env\n```\n\nImport other packages:\n\nWe will use Pytorch for building and learning our DQN network.\n\n\n```\nimport torch\nfrom torch import nn\nimport copy\nfrom collections import deque\nimport random\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\n\nrandom.seed(42)\n```\n\n## Run the game with random agent.\n\n\n```\nfrom torch import randint\nfrom time import sleep\n\nenv = wrap_env(gym.make('CartPole-v1'))\nreward_arr = []\nepisode_count = 20\nfor i in tqdm(range(episode_count)):\n    obs, done, rew = env.reset(), False, 0\n    env.render()\n    while not done:\n        A = randint(0, env.action_space.n, (1,))\n        obs, reward, done, info = env.step(A.item())\n        rew += reward\n        sleep(0.01)\n    reward_arr.append(rew)\nprint(\"average reward per episode :\", sum(reward_arr) / len(reward_arr))\nenv.close()\nshow_video()\n```\n\nThe episode ends when the pole is more than 15 degrees from vertical, or the cart moves more than 2.4 units from the center. The video is short (< 1s) because the pole loses balance immediately. \n\nYou can see that a random agent is having trouble balancing the CartPole, just like you. However, a difficult game for human may be very simple to a computer. Let's see how we can use DQN to train a agent. \n\n## Experience Replay\n\nThe technique of experience replay was first proposed in to resolve temporal correlation in the input data by mixing recent experiences as well past experiences, essentially forcing the input to become independent and identically distributed (i.i.d.). It has been shown that this greatly stabilizes\nand improves the DQN training procedure.\n\n\n```\nclass ExperienceReplay(object):\n      def __init__(self, length):\n        self.experience_replay = deque(maxlen=length)\n\n      def collect(self, experience):\n        self.experience_replay.append(experience)\n        return\n\n      def sample_from_experience(self, sample_size):\n        if len(self.experience_replay) < sample_size:\n            sample_size = len(self.experience_replay)\n        sample = random.sample(self.experience_replay, sample_size)\n        state = torch.tensor([exp[0] for exp in sample]).float()\n        action = torch.tensor([exp[1] for exp in sample]).float()\n        reward = torch.tensor([exp[2] for exp in sample]).float()\n        next_state = torch.tensor([exp[3] for exp in sample]).float()\n        return state, action, reward, next_state\n\n```\n\n## Build our DQN Network\n\nWe will use a simple multi-layer neural network to learn the optimal actions. We will use Adam Optimizor and MSE loss for training. **Notice that the loss function and gamma is given to you in the class attribute.** \n\n\n```\nclass DQN_Network:\n\n    def __init__(self, layer_size_list, lr, seed=1423):\n        torch.manual_seed(seed)\n        self.policy_net = self.create_network(layer_size_list)\n        self.target_net = copy.deepcopy(self.policy_net)\n  \n        self.loss_fn = torch.nn.MSELoss() # the loss function\n        self.optimizer = torch.optim.Adam(self.policy_net.parameters(), lr=lr)\n\n        self.step = 0\n        self.gamma = torch.tensor(0.95).float()\n        return\n\n    def create_network(self, layer_size_list):\n        assert len(layer_size_list) > 1\n\n        layers = []\n        for i in range(len(layer_size_list) - 1):\n            linear = nn.Linear(layer_size_list[i], layer_size_list[i + 1])\n\n            if i < len(layer_size_list) - 2:\n              activation = nn.Tanh()\n            else:\n              activation = nn.Identity()\n\n            layers += (linear, activation)\n        return nn.Sequential(*layers)\n\n    def load_pretrained_model(self, model_path):\n        self.policy_net.load_state_dict(torch.load(model_path))\n\n    def save_trained_model(self, model_path=\"cartpole-dqn.pth\"):\n        torch.save(self.policy_net.state_dict(), model_path)\n\n```\n\n## **[Your task]**: complete the function that chooses the next action\n\nChoose next action based on **$\\epsilon$-greedy**:\n\n\\begin{align}\\text{where} \\quad \\mathcal{a_{t+1}} = \\begin{cases}\n     \\text{argmax}_{a}Q(a, s)  & \\text{with probability }: 1 - \\epsilon, \\text{exploitation}\\\\\n     \\text{Uniform}\\{a_{1},...,a_{n}\\} & \\text{with probability}:   \\epsilon, \\text{exploration} \\\\\n   \\end{cases}\\end{align}\n\n\n```\ndef get_action(model, state, action_space_len, epsilon):\n    # We do not require gradient at this point, because this function will be used either\n    # during experience collection or during inference\n\n    with torch.no_grad():\n        Qp = model.policy_net(torch.from_numpy(state).float())\n\n    ## TODO: select and return action based on epsilon-greedy\n  \n    pass\n```\n\n### **[Your task]**: complete the function that train the network for one step\n\nHere, you can find an ``train`` function that performs a\nsingle step of the optimization. \n\nFor our training update rule, the loss you are trying to minimize is:\n\n\\begin{align}\\text{loss} = Q(s, a) - (r + \\gamma \\max_a Q(s', a))\\end{align}\n\n\n```\ndef train(model, batch_size):\n    state, action, reward, next_state = memory.sample_from_experience(sample_size=batch_size)\n\n    # TODO: predict expected return of current state using main network\n\n    # TODO: get target return using target network\n\n\n    # TODO: compute the loss\n    loss = \n    model.optimizer.zero_grad()\n    loss.backward(retain_graph=True)\n    model.optimizer.step()\n\n    model.step += 1\n    if model.step % 5 == 0:\n        model.target_net.load_state_dict(model.policy_net.state_dict())\n\n    return loss.item()\n```\n\n### **[Your task]**: Finish the training loop\n\nIn this part, you can play around with ```exp_replay_size```, ```episode```, ```epsilon``` and the \"episodo decay\" logic to train your model. **If you have done correctly, you will observe that the training time for the latter episodes is longer than the early episodes. This is because your agent is getting better and better at playing the game and thus each episode takes longer**\n\n\n```\n# Create the model\nenv = gym.make('CartPole-v0')\ninput_dim = env.observation_space.shape[0]\noutput_dim = env.action_space.n\nagent = DQN_Network(layer_size_list=[input_dim, 64, output_dim], lr=1e-3)\n\n# Main training loop\nlosses_list, reward_list, episode_len_list, epsilon_list = [], [], [], []\n\n# TODO: try different values, it normally takes more than 6k episodes to train\nexp_replay_size = \nmemory = ExperienceReplay(exp_replay_size)\nepisodes = \nepsilon = 1 # episilon start from 1 and decay gradually. \n\n# initiliaze experiance replay\nindex = 0\nfor i in range(exp_replay_size):\n    obs = env.reset()\n    done = False\n    while not done:\n        A = get_action(agent, obs, env.action_space.n, epsilon=1)\n        obs_next, reward, done, _ = env.step(A.item())\n        memory.collect([obs, A.item(), reward, obs_next])\n        obs = obs_next\n        index += 1\n        if index > exp_replay_size:\n            break\n\nindex = 128\nfor i in tqdm(range(episodes)):\n    obs, done, losses, ep_len, rew = env.reset(), False, 0, 0, 0\n    while not done:\n        ep_len += 1\n        A = get_action(agent, obs, env.action_space.n, epsilon)\n        obs_next, reward, done, _ = env.step(A.item())\n        memory.collect([obs, A.item(), reward, obs_next])\n\n        obs = obs_next\n        rew += reward\n        index += 1\n\n        if index > 128:\n            index = 0\n            for j in range(4):\n                loss = train(agent, batch_size=16)\n                losses += loss\n    \n    # TODO: add epsilon decay rule here! \n\n\n    losses_list.append(losses / ep_len), reward_list.append(rew)\n    episode_len_list.append(ep_len), epsilon_list.append(epsilon)\n\nprint(\"Saving trained model\")\nagent.save_trained_model(\"cartpole-dqn.pth\")\n```\n\n## Last Step: evaluate your trained model! **Make sure to include your visualizations (plot+video) in the notebook for your submission!**\n\nFirst we can plot the reward vs. episode. **If you have done correctly, you should see the reward can stabilize at 200 in later episodes**\\\n\n\n```\ndef plot_reward(r):\n    plt.figure(2)\n    plt.clf()\n    plt.title('Result')\n    plt.xlabel('Episode')\n    plt.ylabel('Reward')\n    plt.plot(r)\n\nplot_reward(reward_list)\n```\n\nNext let check out how well your agent plays the game. **If you have done correctly, you should see a relatively longer video (> 3~4s) with a self-balancing pole.**\n\n\n```\nenv = wrap_env(gym.make('CartPole-v1'))\n\ninput_dim = env.observation_space.shape[0]\noutput_dim = env.action_space.n\nmodel_validate = DQN_Network(layer_size_list=[input_dim, 64, output_dim], lr=1e-3)\nmodel_validate.load_pretrained_model(\"cartpole-dqn.pth\")\n\nreward_arr = []\nfor i in tqdm(range(200)):\n    obs, done, rew = env.reset(), False, 0\n    env.render()\n    while not done:\n        A = get_action(model_validate, obs, env.action_space.n, epsilon=0)\n        obs, reward, done, info = env.step(A.item())\n        rew += reward\n        # sleep(0.01)\n\n    reward_arr.append(rew)\nprint(\"average reward per episode :\", sum(reward_arr) / len(reward_arr))\nenv.close()\nshow_video()\n```\n\n\n```\n\n```\n", "meta": {"hexsha": "c2353e57f5860c040d058edb263f955873aa0b21", "size": 14498, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "assets/assignments/a4_dqn.ipynb", "max_stars_repo_name": "uoft-csc413/2022", "max_stars_repo_head_hexsha": "769a215505e4fdb706e85bcae37f7bbf662389eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-11T23:51:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T14:41:01.000Z", "max_issues_repo_path": "assets/assignments/a4_dqn.ipynb", "max_issues_repo_name": "uoft-csc413/2022", "max_issues_repo_head_hexsha": "769a215505e4fdb706e85bcae37f7bbf662389eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2022-02-05T00:25:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T21:38:45.000Z", "max_forks_repo_path": "assets/assignments/a4_dqn.ipynb", "max_forks_repo_name": "uoft-csc413/2022", "max_forks_repo_head_hexsha": "769a215505e4fdb706e85bcae37f7bbf662389eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2022-02-04T23:29:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T19:33:45.000Z", "avg_line_length": 14498.0, "max_line_length": 14498, "alphanum_fraction": 0.6512622431, "converted": true, "num_tokens": 2744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25982563796098374, "lm_q2_score": 0.12765262532179067, "lm_q1q2_score": 0.03316742481162869}}
{"text": "```python\n#remove cell visibility\nfrom IPython.display import HTML\ntag = HTML('''\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.''')\ndisplay(tag)\n```\n\n\n\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.\n\n\n\n```python\n%matplotlib inline\nimport control\nimport numpy\nimport sympy as sym\nfrom IPython.display import display, Markdown\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\n\n\n#print a matrix latex-like\ndef bmatrix(a):\n     \"\"\"Returns a LaTeX bmatrix - by Damir Arbula (ICCT project)\n\n     :a: numpy array\n     :returns: LaTeX bmatrix as a string\n     \"\"\"\n     if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n     lines = str(a).replace('[', '').replace(']', '').splitlines()\n     rv = [r'\\begin{bmatrix}']\n     rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n     rv +=  [r'\\end{bmatrix}']\n     return '\\n'.join(rv)\n\n\n# Display formatted matrix: \ndef vmatrix(a):\n    if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n    lines = str(a).replace('[', '').replace(']', '').splitlines()\n    rv = [r'\\begin{vmatrix}']\n    rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n    rv +=  [r'\\end{vmatrix}']\n    return '\\n'.join(rv)\n\n\n#matrixWidget is a matrix looking widget built with a VBox of HBox(es) that returns a numPy array as value !\nclass matrixWidget(widgets.VBox):\n    def updateM(self,change):\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.M_[irow,icol] = self.children[irow].children[icol].value\n                #print(self.M_[irow,icol])\n        self.value = self.M_\n\n    def dummychangecallback(self,change):\n        pass\n    \n    \n    def __init__(self,n,m):\n        self.n = n\n        self.m = m\n        self.M_ = numpy.matrix(numpy.zeros((self.n,self.m)))\n        self.value = self.M_\n        widgets.VBox.__init__(self,\n                             children = [\n                                 widgets.HBox(children = \n                                              [widgets.FloatText(value=0.0, layout=widgets.Layout(width='90px')) for i in range(m)]\n                                             ) \n                                 for j in range(n)\n                             ])\n        \n        #fill in widgets and tell interact to call updateM each time a children changes value\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        #value = Unicode('example@example.com', help=\"The email value.\").tag(sync=True)\n        self.observe(self.updateM, names='value', type= 'All')\n        \n    def setM(self, newM):\n        #disable callbacks, change values, and reenable\n        self.unobserve(self.updateM, names='value', type= 'All')\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].unobserve(self.updateM, names='value')\n        self.M_ = newM\n        self.value = self.M_\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        self.observe(self.updateM, names='value', type= 'All')        \n\n                #self.children[irow].children[icol].observe(self.updateM, names='value')\n\n             \n#overlaod class for state space systems that DO NOT remove \"useless\" states (what \"professor\" of automatic control would do this?)\nclass sss(control.StateSpace):\n    def __init__(self,*args):\n        #call base class init constructor\n        control.StateSpace.__init__(self,*args)\n    #disable function below in base class\n    def _remove_useless_states(self):\n        pass\n```\n\n## Aircraft taxi trajectory control\n\nThe rotational dynamics of an aircraft moving on the ground can be represented as: \n\n$$\nJ_z\\ddot{\\psi} = bF_1\\delta + F_2\\dot{\\psi} \\, , \n$$\n\nwhere $J_z = 11067000$ kg$\\text{m}^2$, $b = 15$ , $F_1 = 35000000$ Nm, $F_2 = 500000$ kg$\\text{m}^2$/$\\text{s}$, $\\psi$ is the rotational angle (in rad), or yaw angle, with respect to the vertical axis, and $\\delta$ is the front wheel steering angle (in rad). When the aircraft is following a straight line with longitudinal linear velocity $V$ (in m/s), the aircraft lateral velocity $V_y$ (in m/s) is approximately linearly proportional to the yaw angle: $V_y = \\dot{p_y} = V\\psi$.\n\nThe goal is to design a regulator for the aircraft lateral position $p_y$, with longitudinal velocity $V$ set to 35 km/h, using the front wheel steering angle $\\delta$ as plant input, according to the following specifications: \n- settling time for 5% tolerance band of less than 4 seconds;\n- zero steady-state error in response to a desired lateral position request;\n- no or minimal overshoot;\n- steering angle does not exceed $\\pm8$ degrees when following a lateral position step of 5 meters.\n\nThe dynamic equations in state space form are:\n\n\\begin{cases}\n    \\dot{x} = \\begin{bmatrix} \\frac{F_2}{J_z} & 0 & 0 \\\\ 1 & 0 & 0 \\\\ 0 & V & 0 \\end{bmatrix}x + \\begin{bmatrix} \\frac{bF_1}{J_z} \\\\ 0 \\\\ 0 \\end{bmatrix}u \\\\\n    y = \\begin{bmatrix} 0 & 0 & 1 \\end{bmatrix}x \\, ,\n\\end{cases}\n\nwhere $x=\\begin{bmatrix} x_1 & x_2 & x_3 \\end{bmatrix}^T = \\begin{bmatrix} \\dot{\\psi} & \\psi & p_y \\end{bmatrix}^T$ and $u=\\delta$.\n\nThe poles of the system are $0$, $0$ and $\\frac{F_2}{J_z} \\simeq 0.045$, therefore the system is unstable.\n\n### Regulator design\n#### Controller design\n\nTo meet the requirements of zero steady-state error we add a new state:\n$$\n\\dot{x_4} = p_y-y_d = x_3 - y_d\n$$\nThe resulting augmented system is thus:\n\n\\begin{cases}\n    \\dot{x_a} = \\begin{bmatrix} \\frac{F_2}{J_z} & 0 & 0 & 0 \\\\ 1 & 0 & 0 & 0 \\\\ 0 & V & 0 & 0 \\\\ 0 & 0 & 1 & 0 \\end{bmatrix}x_a + \\begin{bmatrix} \\frac{bF_1}{J_z} & 0 \\\\ 0 & 0 \\\\ 0 & 0 \\\\ 0 & -1 \\end{bmatrix}\\begin{bmatrix} u \\\\ y_d \\end{bmatrix} \\\\\n    y_a = \\begin{bmatrix} 0 & 0 & 1 & 0 \\\\ 0 & 0 & 0 & 1 \\end{bmatrix}x_a,\n\\end{cases}\n\nwhere $x_a = \\begin{bmatrix} x_1 & x_2 & x_3 & x_4 \\end{bmatrix}^T$ and the second output is added in order to maintain the observability. The system remains controllable with the input $u$ and thus we can design the state feedback with this input. A possible solution is to place all the poles in $-2$.\n\n#### Observer design\n\nEven if states $x_3$ and $x_4$ can be obtained from measurements, and we need to estimate $x_2$ and $x_3$ only, it is convenient to work with the full 4x4 system and to design a state observer of order 4 with all poles in $-10$.\n\n### How to use this notebook?\n- Verify, if the requirements are met in presence of errors in the initial state estimate.\n\n\n```python\n# Preparatory cell\n\nX0 = numpy.matrix('0.0; 0.0; 0.0; 0.0')\nK = numpy.matrix([0,0,0,0])\nL = numpy.matrix([[0,0],[0,0],[0,0],[0,0]])\n\nX0w = matrixWidget(4,1)\nX0w.setM(X0)\nKw = matrixWidget(1,4)\nKw.setM(K)\nLw = matrixWidget(4,2)\nLw.setM(L)\n\n\neig1c = matrixWidget(1,1)\neig2c = matrixWidget(2,1)\neig3c = matrixWidget(1,1)\neig4c = matrixWidget(2,1)\neig1c.setM(numpy.matrix([-2.])) \neig2c.setM(numpy.matrix([[-2.],[-0.]]))\neig3c.setM(numpy.matrix([-2.]))\neig4c.setM(numpy.matrix([[-2.],[-0.]]))\n\neig1o = matrixWidget(1,1)\neig2o = matrixWidget(2,1)\neig3o = matrixWidget(1,1)\neig4o = matrixWidget(2,1)\neig1o.setM(numpy.matrix([-10.])) \neig2o.setM(numpy.matrix([[-10.],[0.]]))\neig3o.setM(numpy.matrix([-10.]))\neig4o.setM(numpy.matrix([[-10.],[0.]]))\n```\n\n\n```python\n# Misc\n\n#create dummy widget \nDW = widgets.FloatText(layout=widgets.Layout(width='0px', height='0px'))\n\n#create button widget\nSTART = widgets.Button(\n    description='Test',\n    disabled=False,\n    button_style='', # 'success', 'info', 'warning', 'danger' or ''\n    tooltip='Test',\n    icon='check'\n)\n                       \ndef on_start_button_clicked(b):\n    #This is a workaround to have intreactive_output call the callback:\n    #   force the value of the dummy widget to change\n    if DW.value> 0 :\n        DW.value = -1\n    else: \n        DW.value = 1\n    pass\nSTART.on_click(on_start_button_clicked)\n\n# Define type of method \nselm = widgets.Dropdown(\n    options= ['Set K and L', 'Set the eigenvalues'],\n    value= 'Set the eigenvalues',\n    description='',\n    disabled=False\n)\n\n# Define the number of complex eigenvalues\nselec = widgets.Dropdown(\n    options= ['0 complex eigenvalues', '2 complex eigenvalues', '4 complex eigenvalues'],\n    value= '0 complex eigenvalues',\n    description='Eig controller:',\n    disabled=False\n)\nseleo = widgets.Dropdown(\n    options= ['0 complex eigenvalues', '2 complex eigenvalues', '4 complex eigenvalues'],\n    value= '0 complex eigenvalues',\n    description='Eig observer:',\n    disabled=False\n)\n\n#define type of ipout \nselu = widgets.Dropdown(\n    options=['impulse', 'step', 'sinusoid', 'square wave'],\n    value='step',\n    description='Type of reference:',\n    style = {'description_width': 'initial'},\n    disabled=False\n)\n# Define the values of the input\nu = widgets.FloatSlider(\n    value=5,\n    min=0,\n    max=10,\n    step=0.1,\n    description='Reference [m]:',\n    style = {'description_width': 'initial'},\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.1f',\n)\nv = widgets.FloatSlider(\n    value=9.72,\n    min=1,\n    max=20,\n    step=0.1,\n    description=r'$V$ [m/s]:',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.2f',\n)\nperiod = widgets.FloatSlider(\n    value=0.5,\n    min=0.001,\n    max=10,\n    step=0.001,\n    description='Period: ',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.3f',\n)\n\nsimTime = widgets.FloatText(\n    value=5,\n    description='',\n    disabled=False\n)\n```\n\n\n```python\n# Support functions\n\ndef eigen_choice(selec,seleo):\n    if selec == '0 complex eigenvalues':\n        eig1c.children[0].children[0].disabled = False\n        eig2c.children[1].children[0].disabled = True\n        eig3c.children[0].children[0].disabled = False\n        eig4c.children[0].children[0].disabled = False\n        eig4c.children[1].children[0].disabled = True\n        eigc = 0\n    if seleo == '0 complex eigenvalues':\n        eig1o.children[0].children[0].disabled = False\n        eig2o.children[1].children[0].disabled = True\n        eig3o.children[0].children[0].disabled = False\n        eig4o.children[0].children[0].disabled = False\n        eig4o.children[1].children[0].disabled = True\n        eigo = 0\n    if selec == '2 complex eigenvalues':\n        eig1c.children[0].children[0].disabled = False\n        eig2c.children[1].children[0].disabled = False\n        eig3c.children[0].children[0].disabled = False\n        eig4c.children[0].children[0].disabled = True\n        eig4c.children[1].children[0].disabled = True\n        eigc = 2\n    if seleo == '2 complex eigenvalues':\n        eig1o.children[0].children[0].disabled = False\n        eig2o.children[1].children[0].disabled = False\n        eig3o.children[0].children[0].disabled = False\n        eig4o.children[0].children[0].disabled = True\n        eig4o.children[1].children[0].disabled = True\n        eigo = 2\n    if selec == '4 complex eigenvalues':\n        eig1c.children[0].children[0].disabled = True\n        eig2c.children[1].children[0].disabled = False\n        eig3c.children[0].children[0].disabled = True\n        eig4c.children[0].children[0].disabled = False\n        eig4c.children[1].children[0].disabled = False\n        eigc = 4\n    if seleo == '4 complex eigenvalues':\n        eig1o.children[0].children[0].disabled = True\n        eig2o.children[1].children[0].disabled = False\n        eig3o.children[0].children[0].disabled = True\n        eig4o.children[0].children[0].disabled = False\n        eig4o.children[1].children[0].disabled = False\n        eigo = 4\n    return eigc, eigo\n\ndef method_choice(selm):\n    if selm == 'Set K and L':\n        method = 1\n        selec.disabled = True\n        seleo.disabled = True\n    if selm == 'Set the eigenvalues':\n        method = 2\n        selec.disabled = False\n        seleo.disabled = False\n    return method\n```\n\n\n```python\nF1 = 35000000\nF2 = 500000\nb = 15\nV = 35/3.6\nJz = 11067000\n\nA = numpy.matrix([[F2/Jz, 0, 0, 0],\n                  [1, 0, 0, 0],\n                  [0, V, 0, 0],\n                  [0, 0, 1, 0]])\nBu = numpy.matrix([[b*F1/Jz],[0],[0],[0]])\nBref = numpy.matrix([[0],[0],[0],[-1]])\nC = numpy.matrix([[0,0,1,0],[0,0,0,1]])\n\ndef main_callback2(v, X0w, K, L, eig1c, eig2c, eig3c, eig4c, eig1o, eig2o, eig3o, eig4o, u, period, selm, selec, seleo, selu, simTime, DW):\n    eigc, eigo = eigen_choice(selec,seleo)\n    method = method_choice(selm)\n    \n    A = numpy.matrix([[F2/Jz, 0, 0, 0],\n                  [1, 0, 0, 0],\n                  [0, v, 0, 0],\n                  [0, 0, 1, 0]])\n    \n    if method == 1:\n        solc = numpy.linalg.eig(A-Bu*K)\n        solo = numpy.linalg.eig(A-L*C)\n    if method == 2:\n        #for better numerical stability of place\n        if eig1c[0,0]==eig2c[0,0] or eig1c[0,0]==eig3c[0,0] or eig1c[0,0]==eig4c[0,0]:\n            eig1c[0,0] *= 1.01\n        if eig2c[0,0]==eig3c[0,0] or eig2c[0,0]==eig4c[0,0]:\n            eig3c[0,0] *= 1.015\n        if eig1o[0,0]==eig2o[0,0] or eig1o[0,0]==eig3o[0,0] or eig1o[0,0]==eig4o[0,0]:\n            eig1o[0,0] *= 1.01\n        if eig2o[0,0]==eig3o[0,0] or eig2o[0,0]==eig4o[0,0]:\n            eig3o[0,0] *= 1.015\n            \n        if eigc == 0:\n            K = control.acker(A, Bu, [eig1c[0,0], eig2c[0,0], eig3c[0,0], eig4c[0,0]])\n            Kw.setM(K)\n        if eigc == 2:\n            K = control.acker(A, Bu, [eig3c[0,0],\n                                      eig1c[0,0],\n                                      numpy.complex(eig2c[0,0], eig2c[1,0]), \n                                      numpy.complex(eig2c[0,0],-eig2c[1,0])])\n            Kw.setM(K)\n        if eigc == 4:\n            K = control.acker(A, Bu, [numpy.complex(eig4c[0,0], eig4c[1,0]), \n                                      numpy.complex(eig4c[0,0],-eig4c[1,0]),\n                                      numpy.complex(eig2c[0,0], eig2c[1,0]), \n                                      numpy.complex(eig2c[0,0],-eig2c[1,0])])\n            Kw.setM(K)\n        if eigo == 0:\n            L = control.place(A.T, C.T, [eig1o[0,0], eig2o[0,0], eig3o[0,0], eig4o[0,0]]).T\n            Lw.setM(L)\n        if eigo == 2:\n            L = control.place(A.T, C.T, [eig3o[0,0],\n                                         eig1o[0,0],\n                                         numpy.complex(eig2o[0,0], eig2o[1,0]), \n                                         numpy.complex(eig2o[0,0],-eig2o[1,0])]).T\n            Lw.setM(L)\n        if eigo == 4:\n            L = control.place(A.T, C.T, [numpy.complex(eig4o[0,0], eig4o[1,0]), \n                                      numpy.complex(eig4o[0,0],-eig4o[1,0]),\n                                      numpy.complex(eig2o[0,0], eig2o[1,0]), \n                                      numpy.complex(eig2o[0,0],-eig2o[1,0])]).T\n            Lw.setM(L)\n            \n    sys = sss(A,numpy.hstack((Bu,Bref)),[[0,0,1,0],[0,0,0,1],[0,0,0,0]],[[0,0],[0,0],[0,1]])\n    syse = sss(A-L*C,numpy.hstack((Bu,Bref,L)),numpy.eye(4),numpy.zeros((4,4)))\n    sysc = sss(0,[0,0,0,0],0,-K)\n    sys_append = control.append(sys,syse,sysc)\n    try:\n        sys_CL = control.connect(sys_append,\n                                 [[1,8],[3,8],[5,1],[6,2],[7,4],[8,5],[9,6],[10,7],[4,3]],\n                                 [2],\n                                 [1,8])\n    except:\n        sys_CL = control.connect(sys_append,\n                                 [[1,8],[3,8],[5,1],[6,2],[7,4],[8,5],[9,6],[10,7],[4,3]],\n                                 [2],\n                                 [1,8])\n\n    X0w1 = numpy.zeros((8,1))\n    X0w1[4,0] = X0w[0,0]\n    X0w1[5,0] = X0w[1,0]\n    X0w1[6,0] = X0w[2,0]\n    X0w1[7,0] = X0w[3,0]\n    if simTime != 0:\n        T = numpy.linspace(0, simTime, 10000)\n    else:\n        T = numpy.linspace(0, 1, 10000)\n      \n    if selu == 'impulse': #selu\n        U = [0 for t in range(0,len(T))]\n        U[0] = u\n        T, yout, xout = control.forced_response(sys_CL,T,U,X0w1)\n    if selu == 'step':\n        U = [u for t in range(0,len(T))]\n        T, yout, xout = control.forced_response(sys_CL,T,U,X0w1)\n    if selu == 'sinusoid':\n        U = u*numpy.sin(2*numpy.pi/period*T)\n        T, yout, xout = control.forced_response(sys_CL,T,U,X0w1)\n    if selu == 'square wave':\n        U = u*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n        T, yout, xout = control.forced_response(sys_CL,T,U,X0w1)\n    \n    try:\n        step_info_dict = control.step_info(sys_CL[0,0],SettlingTimeThreshold=0.05,T=T)\n        print('Step info: \\n\\tRise time =',step_info_dict['RiseTime'],'\\n\\tSettling time (5%) =',step_info_dict['SettlingTime'],'\\n\\tOvershoot (%)=',step_info_dict['Overshoot'])\n        print('Max u value (% of 8deg)=', max(abs(yout[1]))/(8*numpy.pi/180)*100) \n    except:\n        print(\"Error in the calculation of step info.\")\n    \n    fig = plt.figure(num='Simulation1', figsize=(14,12))\n    \n    fig.add_subplot(221)\n    plt.title('Output response')\n    plt.ylabel('Output')\n    plt.plot(T,yout[0],T,U,'r--')\n    plt.xlabel('$t$ [s]')\n    plt.legend(['$y$','Reference'])\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(222)\n    plt.title('Input')\n    plt.ylabel('$u$ [deg]')\n    plt.plot(T,yout[1]*180/numpy.pi)\n    plt.plot(T,[8 for i in range(len(T))],'r--')\n    plt.plot(T,[-8 for i in range(len(T))],'r--')\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(223)\n    plt.title('States response')\n    plt.ylabel('States')\n    plt.plot(T,xout[0],\n             T,xout[1],\n             T,xout[2],\n             T,xout[3])\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$x_{1}$','$x_{2}$','$x_{3}$','$x_{4}$'])\n    plt.grid()\n    \n    fig.add_subplot(224)\n    plt.title('Estimation errors')\n    plt.ylabel('Errors')\n    plt.plot(T,xout[4]-xout[0])\n    plt.plot(T,xout[5]-xout[1])\n    plt.plot(T,xout[6]-xout[2])\n    plt.plot(T,xout[7]-xout[3])\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$e_{1}$','$e_{2}$','$e_{3}$','$e_{4}$'])\n    plt.grid()\n    #plt.tight_layout()\n   \nalltogether2 = widgets.VBox([widgets.HBox([selm, \n                                          selec,\n                                          seleo,\n                                          selu]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.HBox([widgets.Label('K:',border=3), Kw, \n                                                        widgets.Label('Eigenvalues:',border=3),\n                                                        widgets.HBox([eig1c, \n                                                                      eig2c, \n                                                                      eig3c,\n                                                                      eig4c])])]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.VBox([widgets.HBox([widgets.Label('L:',border=3), Lw, widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Eigenvalues:',border=3), \n                                          eig1o, \n                                          eig2o,\n                                          eig3o, \n                                          eig4o,\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('X0 est.:',border=3), X0w]),\n                                          widgets.Label(' ',border=3),\n                                                       widgets.HBox([\n                                          widgets.VBox([widgets.Label('Simulation time [s]:',border=3)]),\n                                          widgets.VBox([simTime])])]),\n                                          widgets.Label(' ',border=3)]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([u,\n                                          v,\n                                          period, \n                                          START])])\nout2 = widgets.interactive_output(main_callback2, {'v':v, 'X0w':X0w, 'K':Kw, 'L':Lw,\n                                                   'eig1c':eig1c, 'eig2c':eig2c, 'eig3c':eig3c, 'eig4c':eig4c, \n                                                   'eig1o':eig1o, 'eig2o':eig2o, 'eig3o':eig3o, 'eig4o':eig4o,  \n                                                   'u':u, 'period':period, 'selm':selm, 'selec':selec, 'seleo':seleo, 'selu':selu, 'simTime':simTime, 'DW':DW})\nout2.layout.height = '860px'\ndisplay(out2, alltogether2)\n```\n\n\n    Output(layout=Layout(height='860px'))\n\n\n\n    VBox(children=(HBox(children=(Dropdown(index=1, options=('Set K and L', 'Set the eigenvalues'), value='Set the\u2026\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "5e3ab947f33bc86ea224ceab29b0f562c553ec6c", "size": 29397, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_en/examples/04/SS-45-Aircraft_taxi_trajectory_control.ipynb", "max_stars_repo_name": "ICCTerasmus/ICCT", "max_stars_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-22T18:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:10:22.000Z", "max_issues_repo_path": "ICCT/ENG/examples/04/SS-45-Aircraft_taxi_trajectory_control.ipynb", "max_issues_repo_name": "tuxsaurus/ICCT", "max_issues_repo_head_hexsha": "30d1aea4fb056c9736c9b4c5a0f50fff14fa6382", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICCT/ENG/examples/04/SS-45-Aircraft_taxi_trajectory_control.ipynb", "max_forks_repo_name": "tuxsaurus/ICCT", "max_forks_repo_head_hexsha": "30d1aea4fb056c9736c9b4c5a0f50fff14fa6382", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-24T11:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T16:36:18.000Z", "avg_line_length": 42.4199134199, "max_line_length": 499, "alphanum_fraction": 0.4605231826, "converted": true, "num_tokens": 6488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31069438321455395, "lm_q2_score": 0.10669059181535785, "lm_q1q2_score": 0.033148167618868345}}
{"text": "<div id=\"h-0\"></div>\n\n# Dati e frequenze\n\nVedremo come esistano tipi differenti di dati, e come in funzione del loro tipo esistano diversi strumenti grafici che li descrivono. Studieremo inoltre in modo pi\u00f9 approfondito e diversificato il concetto di _frequenza_.\n\nCome sempre, carichiamo le librerie e il dataset dei supereroi. Gi\u00e0 che ci siamo, escludiamo l'unico record che fa riferimento al 2099 come anno di prima apparizione.\n\n\n```python\n%matplotlib inline\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy.constants import golden\n\nplt.style.use('fivethirtyeight')\nplt.rc('figure', figsize=(5.0, 5.0/golden))\n\n\nheroes = pd.DataFrame.from_csv('data/heroes.csv', sep=';')\nheroes_with_year = heroes[heroes['First appearance'] < 2020]\n\ndef frequence_plot(freq):\n    x = freq.index\n    y = freq.get_values()\n    plt.bar(x, y)\n    plt.xlim((min(x), max(x)))\n    return plt.ylim((0, max(y) * 1.1))\n```\n\n\n\n\n\n<div id=\"h-1\"></div>\n\n## Dati quantitativi e qualitativi\n\nUna delle principali distinzioni che si possono fare sui dati osservabili riguarda il modo in cui questi sono misurati:\n\n<ul>\n  <li>si parla di dati _quantitativi_ se l'esito della misurazione \u00e8 una quantit\u00e0 numerica;</li>\n  <li>si parla invece di dati _qualitativi_ (o categorici, o nominali) quando la misurazione \u00e8 fatta scegliendo un'etichetta a partire da un insieme disponibili.</li>\n</ul>\n\nPertanto nel nostro dataset i caratteri _Height_, _Weight_ e _Strength_ saranno da considerare quantitativi, mentre i caratteri _Name_, _Identity_, _Birth place_, _Publisher_, _Gender_, _Eye color_, _Hair color_ e _Intelligence_ saranno sicuramente di tipo qualititativo (la differenza tra _Strength_ e _Intelligence_ \u00e8 legata al fatto che il primo carattere \u00e8 misurato tramite numeri che variano tra 0 e 100 mentre il secondo fa riferimento a una scala basata su etichette). La classificazione di _First appearance_ \u00e8 pi\u00f9 sfumata e merita qualche riflessione in pi\u00f9: sebbene l'anno di prima apparizione sia misurato tramite un numero intero, il suo valore non indica prettamente una _quantit\u00e0_, bens\u00ec _quando_ \u00e8 accaduto un evento. In tal senso, il calcolo di operazioni aritmetiche quali la somma o la divisione perde di significato, ed \u00e8 per questo che spesso caratteri di questo tipo ricadono nella classe dei dati qualitativi. Cionondimeno, vedremo come sia possibile ragionare sul carattere _First appearance_ anche in termini quantitativi quando per esempio parleremo della visualizzazione di istogrammi. Ci sono poi casi di caratteri espressi in termini temporali in cui viene misurato il tempo intercorso a partire da un dato istante iniziale (come per esempio il tempo di arrivo del primo cliente in un negozio, misurato in minuti dall'orario di apertura), di cui \u00e8 chiara l'appartenenza alla classe dei dati quantitativi.\n\n\n\n\n\n<div id=\"h-2\"></div>\n\n### Classificazione dei dati qualitativi\n\nI dati qualitativi vengono spesso ulteriormente classificati come binari/booleani, nominali oppure ordinali. Si parla di dati _binari_ o _booleani_ quando l'osservazione pu\u00f2 avere solo due esiti tra loro non confrontabili (volendo si pu\u00f2 parlare di dati booleani per enfatizzare che si sta valutando la presenza o l'assenza di una propriet\u00e0, e di dati binari quando esistono due possibili etichette): in tal senso, il carattere _Gender_, che pu\u00f2 assumere solo i valori M e F, \u00e8 quindi un carattere qualitativo binario. Anche nei dati _nominali_ (detti anche sconnessi), di cui i dati binari rappresentano un caso particolare, i valori osservabili non sono tra loro confrontabili, sebbene non vi sia limite sul numero di diverse etichette. Saranno dunque dati qualitativi nominali, oltre al gi\u00e0 considerato _Gender_, anche _Name_, _Identity_, _Birth place_, _Publisher_, _Gender_, _Eye color_ e _Hair color_. Detto in altri termini, in questo tipo di dati (e quindi anche nel caso binario/booleano) \u00e8 solo possibile stabilire una relazione di equivalenza tra i valori osservabili: pertanto, due osservazioni potranno avere valori uguali oppure diversi, e nulla pi\u00f9 si potr\u00e0 dire sul loro rapporto. Nei dati _ordinali_, invece, \u00e8 possibile stabilire una relazione d'ordine tra i valori osservabili, e quindi quando due valori saranno diversi sar\u00e0 anche possibile dire quale tra i due sia il pi\u00f9 piccolo e quale il pi\u00f9 grande. Nel nostro dataset, solo _Intelligence_ \u00e8 un dato qualitativo ordinale.\n\n\n\n\n\n<div id=\"h-3\"></div>\n\n### Classificazione dei dati quantitativi\n\nPer quanto riguarda i dati quantitativi, viene spesso fatto riferimento alla differenza tra dati _discreti_ e _continui_ in funzione del tipo di insieme di valori che questi possono assumere. Va in realt\u00e0 notato che i dati che elaboriamo sono memorizzati su un computer e quindi i valori reali vengono approssimati tramite valori all'interno di un insieme finito (dunque discreto). Vale pi\u00f9 la pena ragionare in termini di caratteri per cui ha senso dare significato a un singolo valore (come nel caso dell'anno di prima apparizione, in cui ha senso considerare gli eroi apparsi nel 1970) e di caratteri in cui di norma ha senso considerare un _intervallo_ di valori (come nel caso dei rimanenti caratteri: ha di solito poco senso considerare, per esempio, un eroe alto esattamente 178 centimetri o con un indice di forza pari a 42).\n\nIn alcuni casi si considerano diversi i caratteri quantitativi in funzione che abbia o meno senso considerare il _rapporto_ tra i corrispondenti valori: sarebbe questo il caso dei caratteri _Height_, _Weight_ e _Strength_ nel nostro dataset.\n\n\n\n\n\n\n<div id=\"h-4\"></div>\n\n## Frequenze assolute e relative e loro visualizzazione\n\nAbbiamo gi\u00e0 incontrato il concetto di _frequenza assoluta_: si tratta del conteggio del numero di volte che una data osservazione occorre in un campione. Questo tipo di informazione \u00e8 facilmente analizzabile quando il nuemro di differenti osservazioni non \u00e8 troppo grande: ci\u00f2 accade quasi sempre quando si analizzano caratteri qualitativi e relativamente meno spesso per i caratteri quantitativi. Prendiamo per esempio in considerazione il carattere _Publisher_, e calcoliamone le frequenze assolute usando il gi\u00e0 introdotto metodo `value_counts`:\n\n\n```python\nheroes_with_year['Publisher'].value_counts()\n```\n\n\n\n\n    Marvel Comics        205\n    DC Comics            121\n    Dark Horse Comics     12\n    George Lucas          11\n    ABC Studios            4\n    Image Comics           3\n    Rebellion              1\n    Hanna-Barbera          1\n    Star Trek              1\n    Universal Studios      1\n    Name: Publisher, dtype: int64\n\n\n\nVi sono dunque, nel dataset che stiamo analizzando, dieci diversi valori possibili per l'editore: ci\u00f2 rende l'insieme delle frequenze assolute facilmente visualizzabile in forma tabulare, costruendo la cosiddetta _tabella delle frequenze assolute_ in cui si ha una riga per ogni possibile valore osservabile, e tale riga contiene il valore stesso e la corrispondente frequenza assoluta. In senso lato, gi\u00e0 l'output di `value_counts` \u00e8 una tabella delle frequenze assolute, anche se \u00e8 possibile utilizzare la funzione `pd.crosstab` per ottenere una visualizzazione pi\u00f9 elegante, in quanto tale funzione restituisce un _dataframe_:\n\n\n```python\npublisher_freq = pd.crosstab(index=heroes_with_year['Publisher'],\n                             columns=['Abs. freqence'],\n                             colnames=[''])\npublisher_freq\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Abs. freqence</th>\n    </tr>\n    <tr>\n      <th>Publisher</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>ABC Studios</th>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>DC Comics</th>\n      <td>121</td>\n    </tr>\n    <tr>\n      <th>Dark Horse Comics</th>\n      <td>12</td>\n    </tr>\n    <tr>\n      <th>George Lucas</th>\n      <td>11</td>\n    </tr>\n    <tr>\n      <th>Hanna-Barbera</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>Image Comics</th>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>Marvel Comics</th>\n      <td>205</td>\n    </tr>\n    <tr>\n      <th>Rebellion</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>Star Trek</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>Universal Studios</th>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n<div class=\"alert alert-info\">\nL'argomento essenziale di `pd.crosstab` \u00e8, in questo caso, `index`, che viene impostato alla serie di cui vanno calcolate le frequenze assolute; i due rimanenti argomenti influiscono solo sul modo in cui viene visualizzata la tabella delle frequenze: `columns` contiene una lista il cui unico elemento \u00e8 l'intestazione della colonna delle frequenze, mentre `colnames` viene impostato a una lista contenente una stringa vuota al fine di non visualizzare un'ulteriore etichetta per l'intera tabella.\n</div>\n\nEssendo l'output di `pd.crosstab` un _dataframe_, su esso si possono eseguire operazioni quali _slicing_, accesso basato su indice e su posizione e cos\u00ec via. Ci\u00f2 permette di trasformare facilmente una tabella di frequenze relative nella corrispondente tabella delle _frequenze relative_, dove la frequenza relativa di un'osservazione \u00e8 la frazione di casi in quell'osservazione occorre. L'uso delle frequenze relative permette di valutare pi\u00f9 facilmente la grandezza dei valori in gioco, in quanto questi varieranno sempre tra 0 e 1, mentre le frequenze assolute non hanno a priori un valore massimo e quindi \u00e8 meno facile valutare se una frequenza \u00e8 \u00abalta\u00bb o \u00abbassa\u00bb. Le frequenze relative si calcolano dividendo quelle assolute per il numero totale di casi; quest'ultimo \u00e8 ovviamente uguale alla somma di tutte le frequenze assolute, quindi la tabella delle frequenze relative si pu\u00f2 ottenere nel modo seguente: \n\n\n```python\npublisher_rel_freq = pd.crosstab(index=heroes_with_year['Publisher'],\n                                 columns=['Rel. freqence'],\n                                 colnames=[''])\npublisher_rel_freq / publisher_rel_freq.sum()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Rel. freqence</th>\n    </tr>\n    <tr>\n      <th>Publisher</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>ABC Studios</th>\n      <td>0.011111</td>\n    </tr>\n    <tr>\n      <th>DC Comics</th>\n      <td>0.336111</td>\n    </tr>\n    <tr>\n      <th>Dark Horse Comics</th>\n      <td>0.033333</td>\n    </tr>\n    <tr>\n      <th>George Lucas</th>\n      <td>0.030556</td>\n    </tr>\n    <tr>\n      <th>Hanna-Barbera</th>\n      <td>0.002778</td>\n    </tr>\n    <tr>\n      <th>Image Comics</th>\n      <td>0.008333</td>\n    </tr>\n    <tr>\n      <th>Marvel Comics</th>\n      <td>0.569444</td>\n    </tr>\n    <tr>\n      <th>Rebellion</th>\n      <td>0.002778</td>\n    </tr>\n    <tr>\n      <th>Star Trek</th>\n      <td>0.002778</td>\n    </tr>\n    <tr>\n      <th>Universal Studios</th>\n      <td>0.002778</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nIn realt\u00e0 \u00e8 possibile creare direttamente la tabella delle frequenze relative specificando il valore `True` per l'argomento `normalize`:\n\n\n```python\npd.__version__\n```\n\n\n\n\n    u'0.20.3'\n\n\n\n\n```python\npublisher_rel_freq = pd.crosstab(index=heroes_with_year['Publisher'],\n                                 columns=['Rel. freqence'],\n                                 colnames=[''],\n                                 normalize=True)\npublisher_rel_freq\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Rel. freqence</th>\n    </tr>\n    <tr>\n      <th>Publisher</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>ABC Studios</th>\n      <td>0.011111</td>\n    </tr>\n    <tr>\n      <th>DC Comics</th>\n      <td>0.336111</td>\n    </tr>\n    <tr>\n      <th>Dark Horse Comics</th>\n      <td>0.033333</td>\n    </tr>\n    <tr>\n      <th>George Lucas</th>\n      <td>0.030556</td>\n    </tr>\n    <tr>\n      <th>Hanna-Barbera</th>\n      <td>0.002778</td>\n    </tr>\n    <tr>\n      <th>Image Comics</th>\n      <td>0.008333</td>\n    </tr>\n    <tr>\n      <th>Marvel Comics</th>\n      <td>0.569444</td>\n    </tr>\n    <tr>\n      <th>Rebellion</th>\n      <td>0.002778</td>\n    </tr>\n    <tr>\n      <th>Star Trek</th>\n      <td>0.002778</td>\n    </tr>\n    <tr>\n      <th>Universal Studios</th>\n      <td>0.002778</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nLa visualizzazione della tabella pu\u00f2 essere migliorata riducendo il numero di cifre visualizzate, applicando ai suoi elementi la funzione `np.round` che arrotonda un valore floating point mantenendo un numero prefissato di cifre decimali:\n\n\n```python\npublisher_rel_freq.apply(lambda p: np.round(p, 3))\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Rel. freqence</th>\n    </tr>\n    <tr>\n      <th>Publisher</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>ABC Studios</th>\n      <td>0.011</td>\n    </tr>\n    <tr>\n      <th>DC Comics</th>\n      <td>0.336</td>\n    </tr>\n    <tr>\n      <th>Dark Horse Comics</th>\n      <td>0.033</td>\n    </tr>\n    <tr>\n      <th>George Lucas</th>\n      <td>0.031</td>\n    </tr>\n    <tr>\n      <th>Hanna-Barbera</th>\n      <td>0.003</td>\n    </tr>\n    <tr>\n      <th>Image Comics</th>\n      <td>0.008</td>\n    </tr>\n    <tr>\n      <th>Marvel Comics</th>\n      <td>0.569</td>\n    </tr>\n    <tr>\n      <th>Rebellion</th>\n      <td>0.003</td>\n    </tr>\n    <tr>\n      <th>Star Trek</th>\n      <td>0.003</td>\n    </tr>\n    <tr>\n      <th>Universal Studios</th>\n      <td>0.003</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nVolendo visualizzare la frequenza relativa usando delle percentuali \u00e8 possibile operare in modo simile: basta moltiplicare per 100 i valori una volta che questi sono stati arrotondati in modo da tener conto delle cifre decimali che si vogliono visualizzare. Nella cella seguente il risultato viene convertito in una serie di stringhe, cos\u00ec da poter effettuare un'ultima trasformazione che visualizza le percentuali utilizzando il simbolo `%`.\n\n\n```python\n(publisher_rel_freq.apply(lambda p: np.round(p, 4)*100)\n                   .astype(str)\n                   .apply(lambda s: s + '%'))\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Rel. freqence</th>\n    </tr>\n    <tr>\n      <th>Publisher</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>ABC Studios</th>\n      <td>1.11%</td>\n    </tr>\n    <tr>\n      <th>DC Comics</th>\n      <td>33.61%</td>\n    </tr>\n    <tr>\n      <th>Dark Horse Comics</th>\n      <td>3.33%</td>\n    </tr>\n    <tr>\n      <th>George Lucas</th>\n      <td>3.06%</td>\n    </tr>\n    <tr>\n      <th>Hanna-Barbera</th>\n      <td>0.28%</td>\n    </tr>\n    <tr>\n      <th>Image Comics</th>\n      <td>0.83%</td>\n    </tr>\n    <tr>\n      <th>Marvel Comics</th>\n      <td>56.94%</td>\n    </tr>\n    <tr>\n      <th>Rebellion</th>\n      <td>0.28%</td>\n    </tr>\n    <tr>\n      <th>Star Trek</th>\n      <td>0.28%</td>\n    </tr>\n    <tr>\n      <th>Universal Studios</th>\n      <td>0.28%</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nL'ordine delle righe in una tabella delle frequenze \u00e8 quello individuato dal suo indice, che tipicamente \u00e8 legato all'ordinamento predefinito (non decrescente) dei suoi elementi: nel caso di stringhe, quindi, le righe saranno ordinate alfabeticamente per i valori della prima colonna.\n\n\n```python\ngender_freq = pd.crosstab(index=heroes_with_year['Gender'],\n                          columns=['Abs. frequence'],\n                          colnames=[''])\ngender_freq\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Abs. frequence</th>\n    </tr>\n    <tr>\n      <th>Gender</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>F</th>\n      <td>87</td>\n    </tr>\n    <tr>\n      <th>M</th>\n      <td>272</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nVolendo modificare tale ordine \u00e8 possibile accedere al _dataframe_ corrispondente alla tabella tramite `loc` e specificando come secondo argomento una lista dei valori nell'ordine desiderato:\n\n\n```python\ngender_freq.loc[['F', 'M'], :]\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Abs. frequence</th>\n    </tr>\n    <tr>\n      <th>Gender</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>F</th>\n      <td>87</td>\n    </tr>\n    <tr>\n      <th>M</th>\n      <td>272</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n<div class=\"alert alert-info\">\nIn python, il simbolo `:` utilizzato all'interno delle parentesi quadre permette di ottenere uno _slicing_ corrispondente all'intera lista.\n</div>\n\nAbbiamo gi\u00e0 visto come utilizzando l'attributo `plot` di una serie sia possibile visualizzarne graficamente i contenuti. In particolare, per i dati di tipo qualitativo \u00e8 tipicamente sensato utilizzare i grafici a barre:\n\n\n```python\nheroes_with_year['Publisher'].value_counts().plot.bar()\nplt.show()\n```\n\nUn grafico analogo si ottiene invocando sempre il metodo `plot.bar` sul _dataframe_ corrispondente alla tabella delle frequenze:\n\n\n```python\npublisher_freq.plot.bar()\nplt.show()\n```\n\nVi sono due principali differenze tra i grafici a barre ottenuti:\n\n- nel primo le barre sono ordinate per frequenza non crescente, mentre nel secondo queste seguono l'ordinamento (in questo caso alfabetico) dei corrispondenti valori;\n- il secondo grafico contiene una legenda ed etichetta l'asse delle ascisse con il nome del carattere considerato.\n\nVolendo eliminare la legenda \u00e8 sufficiente rigenerare il grafico specificando il valore `False` per l'argomento `legend`:\n\n\n```python\npublisher_freq.plot.bar(legend=False)\nplt.show()\n```\n\nVolendo visualizzare le barre in un ordine differente \u00e8 sufficiente riordinare il _dataframe_ nello stesso gi\u00e0 visto per le tabelle delle frequenze, prima di invocare `plt.plot`.\n\n\n```python\npublisher_order = ['Hanna-Barbera', 'ABC Studios', 'Dark Horse Comics',\n                   'Image Comics', 'Marvel Comics', 'DC Comics',\n                   'George Lucas', 'Rebellion', \n                   'Star Trek', 'Universal Studios']\n\npublisher_rel_freq.loc[publisher_order,:].plot.bar(legend=False)\nplt.show()\n```\n\nOltre a modificare l'ordine delle barre, il grafico precedente visualizza le frequenze relative, ottenute in questo caso facendo riferimento alla tabella `publisher_rel_freq` precedentemente generata. Ovviamente il grafico che si ottiene \u00e8 analogo a quello delle frequenze assolute: l'unica cosa che cambia \u00e8 la scala dei valori sull'asse delle ascisse.\n\nL'uso delle frequenze relative permette anche di confrontare situazioni in cui il numero di osservazioni \u00e8 variabile. Se per esempio volessimo comparare le frequenze della forza dei supereroi con quelle delle supereroine, ci troveremmo con due diversi numeri di osservazioni:\n\n\n```python\nmale_strength_freq = pd.crosstab(index=heroes.loc[heroes['Gender']=='M','Strength'],\n                                 columns='Abs. freq.')\nfemale_strength_freq = pd.crosstab(index=heroes.loc[heroes['Gender']=='F','Strength'],\n                                   columns='Abs. freq.')\n\nnum_male = sum(male_strength_freq['Abs. freq.'])\nnum_female = sum(female_strength_freq['Abs. freq.'])\n\nprint('Ci sono {} supereroi e {} supereroine'.format(num_male, num_female))\n```\n\n    Ci sono 428 supereroi e 164 supereroine\n\n\nSovrapporre quindi i grafici a barre delle frequenze assolute non avrebbe senso, perch\u00e9 le relative altezze non sarebbero confrontabili. Ha invece senso fare il confronto con le frequenze relative.  Gi\u00e0 che ci siamo, utilizziamo l'argomento `color` per impostare rispettivamente a blu e rosa i colori dei settori che corrispondono a maschi e femmine (\u00e8 un po' sessista, ma aiuta a leggere il grafico a colpo d'occhio).\n\n\n```python\nmale_strength_freq = (pd.crosstab(index=heroes.loc[heroes['Gender']=='M','Strength'],\n                                 columns='Abs. freq.',\n                                 normalize=True)\n                        .loc[:, 'Abs. freq.'])\nfemale_strength_freq = (pd.crosstab(index=heroes.loc[heroes['Gender']=='F','Strength'],\n                                   columns='Abs. freq.',\n                                   normalize=True)\n                          .loc[:, 'Abs. freq.'])\n\nmale_strength_freq.plot(marker='o', color='blue', legend=False)\nfemale_strength_freq.plot(marker='o', color='pink', legend=False)\nplt.show()\n```\n\n<div class=\"alert alert-warning\">\nSe siete stati attenti avrete notato che le tabelle delle frequenze sono state accedute tramite `loc` al fine di estrarre le corrispondenti serie. Ci\u00f2 \u00e8 dovuto al fatto che in caso contrario matplotlib avrebbe prodotto due grafici separati. Quando pi\u00f9 avanti parleremo delle frequenze congiunte vedremo un modo semplice per generare un'unica figura contenente i due grafici a barre.\n</div>\n\nIn effetti la cella precedente non genera un vero e proprio grafico a barre, perch\u00e9 per ogni valore della forza ci sarebbero due barre, relative ai due generi. Tali barre si sovrapporrebbero, con l'effetto di nascondere (parzialmente o totalmente) quella pi\u00f9 bassa.\n\n\n```python\nmale_strength_freq.plot.bar(color='blue', legend=False)\nfemale_strength_freq.plot.bar(color='pink', legend=False)\nplt.show()\n```\n\nUn'alternativa \u00e8 quella di specificare il parametro `alpha` nelle funzioni che generano i grafici: ci\u00f2 permette di disegnare delle barre semi-trasparenti che evidenziano le loro sovrapposizioni.\n\n\n```python\nmale_strength_freq.plot.bar(color='blue', alpha=.7)\nfemale_strength_freq.plot.bar(color='pink', alpha=.7)\nplt.show()\n```\n\nUna modalit\u00e0 alternativa per visualizzare le frequenze in caso di valori qualitativi, evidenziando inoltre le frazioni rispetto al numero totale dei casi \u00e8 quella di utilizzare il metodo `pie` per produrre un diagramma a torta, o pi\u00f9 tecnicamente un _aerogramma_, in cui un cerchio \u00e8 diviso in tanti settori le cui aree sono proporzionali alle frequenze (pertanto il grafico ottenuto sar\u00e0 indipendente dall'avere considerato le frequenze assolute oppure quelle relative). Per esempio, la cella seguente calcola il diagramma a torta delle frequenze relative al genere dei supereroi.\n\n\n```python\ngender_freq.plot.pie('Abs. frequence', colors=['pink', 'blue'])\nplt.show()\n```\n\nCi sono alcune cose che vale la pena sottolineare, e che sono descritte di seguito.\n\n- A differenza dei grafici generati fino a ora, qui \u00e8 stato necessario specificare il nome della colonna nel _dataframe_ corrispondente alla tabella delle frequenze. Ci\u00f2 \u00e8 legato al fatto che mentre metodi come `plot.pie` sono in grado di visualizzare pi\u00f9 caratteri contemporaneamente (e pi\u00f9 avanti vedremo come), quando si disegna un diagrama a torta \u00e8 necessario utilizzare un solo carattere e quindi \u00e8 necessario selezionarlo nel dataframe, anche in casi come questo in cui vi \u00e8 effettivamente un solo carattere; In alternativa, \u00e8 possibile estrarre la serie dal _dataframe_ e invocare su di essa `plot.pie`: in altre parole l'istruzione seguente avrebbe generato un grafico analogo:\n\n```\n_ = gender_freq['Abs. frequence'].plot.pie(colors=['pink', 'blue'])\n```\n\n- Mentre quando si crea un grafico a barre per un carattere ha ampiamente senso utilizzare lo stesso colore per tutte le barre, nel caso di un diagramma a torta tale scelta renderebbe il risultato illeggibile, ed \u00e8 per questo che se si vogliono personalizzare i colori \u00e8 necessario passare la lista dei corrispondenti nomi all'argomento `colors` (che \u00e8 diverso dall'argomento `color` finora utilizzato).\n\n- Nel grafico viene visualizzata un'ellissi al posto di un cerchio in quanto la modalit\u00e0 di visualizzazione predefinita in matplotlib (e in molte altre librerie di visualizzazione grafica) prevede che le lunghezze sugli assi cartesiani siano misurate con unit\u00e0 di misura diverse. Il rapporto tra queste unit\u00e0 di misura \u00e8 legato alla sezione aurea, e ci\u00f2 ha di norma l'effetto di produrre grafici gradevoli da vedere, a parte casi come questo in cui i cerchi risultano \"schiacciati\". Per ovviare all'inconveniente basta invocare la funzione `plt.axis` specificando come argomento `'equal'`.\n\n\n```python\ngender_freq.plot.pie('Abs. frequence', colors=['pink', 'blue'])\nplt.axis('equal')\nplt.show()\n```\n\nConsideriamo il caso particolare dell'anno di apparizione: se lo  consideriamo come dato di tipo qualitativo ordinale e ne tracciamo il grafico a barre delle frequenze assolute, \u00e8 appropriato posizionare le barre rispettando la relazione di ordine esistente tra i dati, utilizzando direttamente matplotlib come abbiamo visto nella lezione precedente.\n\n\n```python\nfirst_app_freq = heroes_with_year['First appearance'].value_counts()\nplt.bar(first_app_freq.index, first_app_freq.get_values())\nplt.show()\n```\n\nIl risultato non \u00e8 per\u00f2 ottimale perch\u00e9 le barre hanno uno spessore (sebbene in questo caso sia molto piccolo, a causa dell'elevato numero di barre) che pu\u00f2 suggerire un'interpretazione fuorviante del grafico, secondo cui le frequenze non facciano riferimento a un anno, bens\u00ec a un in intervallo temporale centrato in un anno. Per evitare tale fraintendimento \u00e8 pi\u00f9 appropriato in casi come questo produrre un grafico *a bastoncini* in cui ogni punto \u00e8 evidenziato, piuttosto che da una barra, da un segmento verticale che lo congiunge con l'asse delle ascisse (cosa che, peraltro, permette di non scambiare per nulle le frequenze relativamente basse):\n\n\n```python\nplt.vlines(first_app_freq.index, 0, first_app_freq.get_values())\nplt.show()\n```\n\n\u00c8 anche possibile abbinare ogni segmento a un cerchio centrato sul punto che identifica un valore e la sua frequenza: basta generare il grafico precedente e sovrapporgli i singoli punti.\n\n\n```python\nplt.vlines(first_app_freq.index, 0, first_app_freq.get_values())\nplt.plot(first_app_freq.index, first_app_freq.get_values(), 'o')\nplt.show()\n```\n\nInfine, consideriamo il diagramma a bastoncini relativo al peso dei supereroi.\n\n\n```python\nweight_freq = heroes['Weight'].value_counts()\n\nplt.vlines(weight_freq.index, 0, weight_freq.get_values())\nplt.plot(weight_freq.index, weight_freq.get_values(), 'o')\nplt.show()\n```\n\nDue pesi, per dire, di 81.12 Kg e di 81.14 Kg vengono considerati in questo grafico come due valori differenti, ed \u00e8 per questo che vi sono quasi esclusivamente bastoncini di altezza unitaria: quasi tutti i valori occorrono praticamente un'unica volta nel dataset. Ci\u00f2 \u00e8 dovuto al fatto che il peso \u00e8 un dato quantitativo per cui non ha di norma senso considerare un singolo valore, e risulta pi\u00f9 sensato calcolare le frequenze di _intervalli_ di possibili valori osservabili. Il grafico corrispondente prende il nome di _istogramma_, e viene calcolato e visualizzato in pandas invocando il metodo `hist` sulla serie corrispondente:\n\n\n```python\nheroes['Weight'].hist()\nplt.show()\n```\n\nOvviamente il risultato ottenuto dipende da come sono stati scelti gli intervalli su cui calcolare le frequenze. Di norma si divide l'intervallo che contiene tutti i dati osservati in sotto-intervalli equiampi, il cui numero \u00e8 individuato dall'argomento `bins`.\n\n\n```python\nheroes['Weight'].hist(bins=50)\nplt.show()\n```\n\nQuesto istogramma ci dice, a occhio, che i pesi variano perlopi\u00f9 tra zero e duecento chilogrammi, sebbene esistano erori con pesi maggiori. In teoria \u00e8 possibile utilizzare sotto-intervalli di ampiezze differenti: per esempio, ampiezze pari a 20 per i pesi inferiori a 200 kg., pari a 50 per pesi compresi tra 200 e 500 kg., e pari a 100 per i valori rimanenti.\n\n\n```python\nheroes['Weight'].hist(bins=np.hstack((np.arange(0, 200, 20),\n                                      np.arange(200, 500, 50),\n                                      np.arange(500, 1000, 100))))\nplt.show()\n```\n\nVa notato come in questo caso le altezze delle barre non contino il numero di occorrenze nel corrispondente intervallo: per esempio, vi sono tre pesi superiori a 800 kg., ma la barra corrispondente ha altezza unitaria. Ci\u00f2 \u00e8 dovuto al fatto che in un istogramma \u00e8 l'_area_ di ogni barra a essere legata alla frequenza: se le barre hanno basi della stessa lunghezza, le aree sono proporzionali all'altezza, altrimenti no. \u00c8 per questo, per esempio, che le due barre pi\u00f9 a destra nell'ultimo istogramma hanno altezza unitaria: si riferiscono a tre osservazioni, e la loro area \u00e8 il triplo dell'area di una barra di altezza unitaria nella parte sinistra del grafico, che invece farebbe riferimento a una sola osservazione.\n\n<div class=\"alert alert-info\">\nNella cella precedente sono state utilizzate le funzioni `np.hstack`, che permette di giustapporre due o pi\u00f9 array numpy, e `np.arange`, che crea un array i cui contenuti variano tra i valori indicati dai primi due argomenti, con incremento pari all'ultimo argomento.\n</div>\n\n\n\n\n\n<div id=\"h-5\"></div>\n\n## Frequenze cumulate\n\nRiconsideriamo l'anno di prima apparizione dei supereroi, e rispondiamo alle domande che seguono.\n\n1. Qual \u00e8 il pi\u00f9 recente tra gli anni di apparizione di un supereroe?\n2. E qual \u00e8 il meno recente?\n3. Quanti supereroi hanno un anno di apparizione non superiore al 1970?\n4. Quanti hanno un anno di apparizione successivo al 1980?\n\nPer rispondere alle prime due domande basta selezionare la serie che corrisponde al carattere `first_appearance`\u00a0e calcolarne il minimo e il massimo valore:\n\n\n```python\n(heroes_with_year['First appearance'].min(), heroes_with_year['First appearance'].max())\n```\n\n\n\n\n    (1933.0, 2016.0)\n\n\n\nPer rispondere invece alle rimanenti domande potremmo estrarre tramite una _list comprehension_ tutti gli anni in `heroes_with_year` che soddisfano i criteri indicati e calcolarne la lunghezza. Vale per\u00f2 la pena approfittarne per introdurre un nuovo strumento, che si riveler\u00e0 molto versatile: si tratta delle _frequenze cumulate_, che si possono calcolare quando esiste una relazione di ordine per i valori del carattere. Essenzialmente si tratta di considerare i valori del carattere dal pi\u00f9 piccolo al pi\u00f9 grande, di calcolare le relative frequenze e di cumularle in modo che al primo elemento sia associata la sua frequenza, al secondo la somma delle frequenze dei primi due elementi, al terzo la somma delle prime tre frequenze e cos\u00ec via.\n\nPer calcolare le frequenze cumulate, pandas mette a disposizione il metodo `cumsum` per gli oggetti di tipo serie e _dataframe_. Quando viene utilizzato sulla serie prodotta da `value_counts` \u00e8 per\u00f2 necessario riordinare le frequenze prodotte rispetto al loro indice e infine si pu\u00f2 invocare il metodo. Risulta invece pi\u00f9 comodo calcolare generare il _dataframe_ corrispondente alla tabella delle frequenze, che risulta gi\u00e0 ordinato nel modo corretto, e su questo invocare `cumsum`.\n\n\n```python\nfirst_app_freq_cumulate = (pd.crosstab(index=heroes_with_year['First appearance'],\n                                       columns=['Cumulate freq.'],\n                                       colnames=[''])\n                             .cumsum())\nfirst_app_freq_cumulate.iloc[:10] # per brevit\u00e0 visualizziamo solo i primi dieci elementi\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Cumulate freq.</th>\n    </tr>\n    <tr>\n      <th>First appearance</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1933.0</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>1939.0</th>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>1940.0</th>\n      <td>11</td>\n    </tr>\n    <tr>\n      <th>1941.0</th>\n      <td>18</td>\n    </tr>\n    <tr>\n      <th>1943.0</th>\n      <td>20</td>\n    </tr>\n    <tr>\n      <th>1944.0</th>\n      <td>22</td>\n    </tr>\n    <tr>\n      <th>1945.0</th>\n      <td>23</td>\n    </tr>\n    <tr>\n      <th>1947.0</th>\n      <td>25</td>\n    </tr>\n    <tr>\n      <th>1948.0</th>\n      <td>26</td>\n    </tr>\n    <tr>\n      <th>1950.0</th>\n      <td>27</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nIl grafico corrispondente mette in evidenza il fatto che le frequenze cumulate sono monotone crescenti e variano da 0 al numero totale di casi nel dataset considerato:\n\n\n```python\nfirst_app_freq_cumulate.plot(marker='o', legend=False)\nplt.show()\n```\n\nLa frequenza cumulata corrispondente a 1970 rappresenta quindi il numero di casi nel dataset in cui l'anno di prima apparizione \u00e8 minore o uguale al 1970, e dunque tale frequenza rappresenta la risposta alla terza domanda:\n\n\n```python\nfirst_app_freq_cumulate.at[1970.0, 'Cumulate freq.']\n```\n\n\n\n\n    125\n\n\n\nPer rispondere all'ultima domanda \u00e8 possibile procedere in modo analogo: la frequenza cumulata di 1980 corrisponde al numero di casi in cui l'anno di apparizione \u00e8 minore o uguale a 1980, e sottraendo tale valore al numero totale di casi si ottiene la risposta:\n\n\n```python\nfirst_app_freq_cumulate.iat[-1, 0] - first_app_freq_cumulate.at[1980.0, 'Cumulate freq.']\n```\n\n\n\n\n    172\n\n\n\nVa notato come il numero totale di casi corrisponda all'ultima delle frequenze cumulate. Infine, il concetto di frequenze cumulate si pu\u00f2 applicare sia alle frequenze assolute, sia a quelle relative: nel secondo caso i valori ottenuti aumenteranno da 0 a 1. Nella cella seguente viene calcolata la tabella delle frequenze relative cumulate per l'anno di prima apparizione di cui, sempre per brevit\u00e0, vengono mostrate le ultime dieci righe.\n\n\n```python\nfirst_app_relfreq_cumulate = (pd.crosstab(index=heroes_with_year['First appearance'],\n                              columns=['Cumulate freq.'],\n                              colnames=[''],\n                              normalize=True).cumsum())\n\nfirst_app_relfreq_cumulate.iloc[-10:]\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Cumulate freq.</th>\n    </tr>\n    <tr>\n      <th>First appearance</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2006.0</th>\n      <td>0.923497</td>\n    </tr>\n    <tr>\n      <th>2007.0</th>\n      <td>0.937158</td>\n    </tr>\n    <tr>\n      <th>2008.0</th>\n      <td>0.953552</td>\n    </tr>\n    <tr>\n      <th>2009.0</th>\n      <td>0.956284</td>\n    </tr>\n    <tr>\n      <th>2010.0</th>\n      <td>0.967213</td>\n    </tr>\n    <tr>\n      <th>2011.0</th>\n      <td>0.980874</td>\n    </tr>\n    <tr>\n      <th>2012.0</th>\n      <td>0.986339</td>\n    </tr>\n    <tr>\n      <th>2013.0</th>\n      <td>0.989071</td>\n    </tr>\n    <tr>\n      <th>2015.0</th>\n      <td>0.994536</td>\n    </tr>\n    <tr>\n      <th>2016.0</th>\n      <td>1.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nLa visualizzazione in forma grafica delle frequenze relative cumulate equivale a quella precedente: l'unica differenza consiste nei valori sull'asse delle ordinate, che risulteranno ovviamente scalati sull'intervallo $[0, 1]$:\n\n\n```python\nfirst_app_relfreq_cumulate.plot(legend=False)\nplt.show()\n```\n\nVale la pena notare come il grafico prodotto sia quello una funzione lineare a tratti: in parole povere, si tratta di una sequenza di segmenti in cui ogni elemento ha l'estremo destro coincidente con quello sinistro del segmento successivo. Possiamo evidenziare questa propriet\u00e0 effettuando uno _zoom_, per esempio tra il 1980 e il 1990:\n\n\n```python\nfirst_app_relfreq_cumulate[1980:1990].plot(legend=False)\nplt.show()\n```\n\nQuando i valori osservati sono di tipo numerico o ordinabile, uno strumento molto simile a quello delle frequenze relative cumulate \u00e8 rappresentato dalla _funzione cumulativa empirica_ (o _funzione di ripartizione empirica_), che dato un insieme di osservazioni $\\{ x_1, \\dots, x_n \\}$, \u00e8 definita come quella funzione $\\hat F: \\mathbb R \\mapsto [0, 1]$ tale che per ogni $x \\in \\mathbb R$\n\n\\begin{equation}\n\\hat F(x) = \\frac{1}{m} \\sum_{i=1}^n \\mathrm I_{(-\\infty, x_i]}(x) ,\n\\end{equation}\n\ndove $\\mathrm I_A: \\mathbb R \\mapsto \\{0, 1\\}$ indica la _funzione indicatrice_ dell'insieme $A$, che assume valore nullo in corrispondenza di tutti gli argomenti che non appartengono ad $A$ e valore unitario altrimenti, e $(-\\infty, x_i]$ indica l'intervallo semiaperto identificato da tutti i valori reali minori o uguali a $x_i$. Per un generico argomento $x$, la funzione cumulativa empirica assumer\u00e0 pertanto come valore la frequenza relativa cumulata del pi\u00f9 grande tra i valori osservati $x_i \\leq x$. Dunque il suo grafico sar\u00e0 quello di una funzione costante a tratti. In python \u00e8 presente un'implementazione della funzione cumulativa empirica nel modulo `statmodels.api`: la funzione `distributions.ECDF` accetta come input un insieme di osservazioni e restituisce la corrispondente funzione cumulativa empirica. Possiamo quindi elaborare in tal senso gli anni di prima apparizione e visualizzare il grafico corrispondente agli anni tra il 1980 e il 1990, cos\u00ec da poter effettuare un confronto con l'analogo grafico precedentemente generato:\n\n\n```python\nimport statsmodels.api as sm\n\necdf = sm.distributions.ECDF(heroes_with_year['First appearance'])\nx = np.arange(1980, 1991)\ny = ecdf(x)\nplt.step(x, y)\nplt.show()\n```\n\n<div class=\"alert alert-info\">\nIn casi come questo \u00e8 meglio usare `plt.step` piuttosto che `plt.plot`, altrimenti il grafico visualizzato, pur essendo molto simile al risultato appena ottenuto, non sarebbe tecnicamente parlando quello di una funzione costante a tratti.\n</div>\n\nVa peraltro rimarcato che all'aumentare del numero di valori osservabili il grafico delle frequenze relative cumulate ottenute usando il metodo `plot` della corrispondente serie diventa indistinguibile da quello della funzione cumulativa empirica (sia che si sia utilizzato `plt.step`, sia che si sia utilizzato `plt.plot` per visualizzarlo). Per rendercene conto, possiamo visualizzare nuovamente la funzione di ripartizione empirica tenendo per\u00f2 conto di tutte le osservazioni per gli anni di prima apparizione.\n\n\n```python\nmin_year = min(heroes_with_year['First appearance'])\nmax_year = max(heroes_with_year['First appearance'])\nx = np.arange(min_year, max_year+1)\ny = ecdf(x)\nplt.step(x, y)\nplt.show()\n```\n\n\n\n\n<div id=\"h-6\"></div>\n\n### Diagrammi di Pareto ###\n\nFrequenze e frequenze cumulate di una variabile categorica possono essere considerate congiuntamente per generare un _diagramma di Pareto_ nel modo seguente: ordinando i dati per frequenza decrescente, su uno stesso sistema di riferimento in cui l'asse delle ascisse fa riferimento ai valori della variabile si sovrappongono il diagramma a barre delle frequenze e una linea spezzata che collega i valori delle frequenze cumulate. Consideriamo per esempio i colori degli occhi pi\u00f9 frequenti nel nostro dataset (definiti per comodit\u00e0 come i colori che occorrono con frequenza relativa superiore a 0.02). Il corrispondente diagramma di Pareto si pu\u00f2 generare manualmente oppure utilizzando la funzione `pareto` del package `paretochart`:\n\n\n```python\nfrom paretochart import pareto\n\neye_color_freq = heroes_with_year['Eye color'].value_counts()/len(heroes_with_year)\ncommon_colors = eye_color_freq[eye_color_freq > .02].index\n\ncommon_colors_data = (heroes_with_year['Eye color'][heroes_with_year['Eye color']\n                                .isin(common_colors)])\n\ncommon_colors_freq = common_colors_data.value_counts()/len(common_colors_data)\n\npareto(common_colors_freq,\n       labels=common_colors_freq.index)\nplt.show()\n```\n\nOvviamente per quanto riguarda il valore pi\u00f9 a sinistra nel diagramma (e quindi quello avente la frequenza maggiore) frequenza e frequenza cumulata coincideranno sempre.\n\nIn generale, un diagramma di Pareto permette di identificare gli elementi pi\u00f9 rilevanti in termini di frequenze all'interno di un insieme di osservazioni, evidenziando simultaneamente il peso di ogni fattore, sia il loro peso cumulativo. Nel nostro caso, il grafico ottenuto mostra permette per esempio di verificare a colpo d'occhio come gli occhi blu, marroni e verdi identifichino l'80% dei supereroi.\n\n\n\n\n\n<div id=\"h-7\"></div>\n\n## Frequenze congiunte e marginali\n\n\nSpesso \u00e8 utile analizzare un insieme di osservazioni prendendo in considerazione due caratteri al posto di uno, per esempio per vedere se i valori di tali caratteri tendano a essere pi\u00f9 o meno collegati tra loro tramite una relazione. Il concetto di frequenza si specializza in questo caso andando a contare il numero di osservazioni in cui i due caratteri considerati assumono due determinati valori, ottenendo la cosiddetta _frequenza congiunta assoluta_ (o equivalentemente la _frequenza congiunta relativa_ nel caso in cui si calcolasse la frazione di osservazioni e non il suo numero). Nel caso in cui i possibili valori osservabili non siano parecchi, \u00e8 possibile visualizzare queste frequenze tramite una _tabella delle frequenze congiunte_ (detta anche _tabella di contingenza_), ottenuta estendendo il concetto di tabella delle frequenze precedentemente introdotto: ora le righe della tabella corrisponderanno ai possibili valori di uno dei caratteri considerati, le sue colonne corrisponderanno ai valori del rimanente carattere e gli elementi della tabella conterranno le frequenze congiunte (assolute o relative). La funzione `pd.crosstab` pu\u00f2 essere utilizzata anche per produrre questo tipo di tabella: basta indicare le serie corrispondenti ai caratteri considerati come valori degli argomenti `index` e `columns`.\n\n\n```python\nint_gender_freq = pd.crosstab(index=heroes['Intelligence'], \n                              columns=heroes['Gender'])\n\nint_gender_freq\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Gender</th>\n      <th>F</th>\n      <th>M</th>\n    </tr>\n    <tr>\n      <th>Intelligence</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>average</th>\n      <td>38</td>\n      <td>101</td>\n    </tr>\n    <tr>\n      <th>good</th>\n      <td>78</td>\n      <td>165</td>\n    </tr>\n    <tr>\n      <th>high</th>\n      <td>27</td>\n      <td>112</td>\n    </tr>\n    <tr>\n      <th>low</th>\n      <td>0</td>\n      <td>13</td>\n    </tr>\n    <tr>\n      <th>moderate</th>\n      <td>21</td>\n      <td>37</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nL'ordine delle righe pu\u00f2 essere modificato nello stesso modo visto per le tabelle delle frequenze: per modificare la tabella in modo che risulti ordinata per i valori di intelligenza piuttosto che in modo alfabetico sar\u00e0 quindi sufficiente utilizzare in metodo `reindex`.\n\n\n```python\nint_gender_freq = pd.crosstab(index=heroes['Intelligence'], \n                              columns=heroes['Gender'])\n\nint_gender_freq = int_gender_freq.reindex(['low', 'moderate', 'average', 'good', 'high'])\nint_gender_freq\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Gender</th>\n      <th>F</th>\n      <th>M</th>\n    </tr>\n    <tr>\n      <th>Intelligence</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>low</th>\n      <td>0</td>\n      <td>13</td>\n    </tr>\n    <tr>\n      <th>moderate</th>\n      <td>21</td>\n      <td>37</td>\n    </tr>\n    <tr>\n      <th>average</th>\n      <td>38</td>\n      <td>101</td>\n    </tr>\n    <tr>\n      <th>good</th>\n      <td>78</td>\n      <td>165</td>\n    </tr>\n    <tr>\n      <th>high</th>\n      <td>27</td>\n      <td>112</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nSiccome `crosstab` produce dei dataframe, per riordinare le colonne \u00e8 sufficiente accedere alla tabella tramite `loc` e specificando come secondo argomento una lista dei valori nell'ordine desiderato:\n\n\n```python\nint_gender_freq.loc[:,['M', 'F']]\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Gender</th>\n      <th>M</th>\n      <th>F</th>\n    </tr>\n    <tr>\n      <th>Intelligence</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>low</th>\n      <td>13</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>moderate</th>\n      <td>37</td>\n      <td>21</td>\n    </tr>\n    <tr>\n      <th>average</th>\n      <td>101</td>\n      <td>38</td>\n    </tr>\n    <tr>\n      <th>good</th>\n      <td>165</td>\n      <td>78</td>\n    </tr>\n    <tr>\n      <th>high</th>\n      <td>112</td>\n      <td>27</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nIn modo analogo \u00e8 possibile visualizzare solo alcune righe oppure solo alcune colonne della tabella, come nella cella seguente:\n\n\n```python\nint_gender_freq.loc['moderate':'good', :]\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Gender</th>\n      <th>F</th>\n      <th>M</th>\n    </tr>\n    <tr>\n      <th>Intelligence</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>moderate</th>\n      <td>21</td>\n      <td>37</td>\n    </tr>\n    <tr>\n      <th>average</th>\n      <td>38</td>\n      <td>101</td>\n    </tr>\n    <tr>\n      <th>good</th>\n      <td>78</td>\n      <td>165</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n<div class=\"alert alert-warning\">\nVa notato che quella appena ottenuta non \u00e8 pi\u00f9 una tabella delle frequenze, in quanto non fa riferimento a tutti i possibili valori in gioco.\n</div>\n\nSempre ipotizzando che il numero di valori osservabili non sia troppo elevato, la visualizzazione grafica delle frequenze congiunte pu\u00f2 essere effettuata estendendo il concetto di diagramma a barre in modo che visualizzi due caratteri al posto di uno, _raggruppando_ le barre che fanno riferimento a uno stesso valore per uno dei caratteri, e _colorandole_ in funzione del valore che queste assumono per l'altro carattere in gioco. Il posizionamento delle barre viene normalmente fatto in due possibili modi:\n\n- invocando il metodo `plot.bar` invocato sulla tabella, in modo che le barre relative a uno stesso valore risultino _affiancate_\n\n\n```python\n_ = int_gender_freq.plot.bar(color=['pink', 'blue'])\n```\n\n- specificando ulteriormente il valore `True` per l'argomento `stacked`, in modo da _sovrapporre_ le barre che si riferiscono a uno stesso valore:\n\n\n```python\n_ = int_gender_freq.plot.bar(color=['pink', 'blue'], stacked=True)\n```\n\nNel caso in cui si volesse calcolare le frequenze relative e almeno uno dei caratteri fosse numerico, si rischierebbe di ricadere nello stesso problema descritto quando abbiamo parlato degli istogrammi: si consideri per esempio il tentativo di calcolare le frequenze congiunte di peso e genere:\n\n\n```python\npd.crosstab(index=heroes['Weight'], columns=[heroes['Gender']]).iloc[:10,:]\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Gender</th>\n      <th>F</th>\n      <th>M</th>\n    </tr>\n    <tr>\n      <th>Weight</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2.34</th>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>4.82</th>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>9.79</th>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>14.67</th>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>16.20</th>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>17.01</th>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>18.11</th>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>18.45</th>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>19.00</th>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>25.73</th>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nEssenzialmente in ogni riga c'\u00e8 un valore nullo e uno unitario, semplicemente perch\u00e9 succede quasi sempre che un particolare valore del peso specificato fino ai decigrammi occorra un'unica volta nelle osservazioni. \u00c8 quindi opportuno raggruppare assieme pesi \u00abvicini\u00bb tra loro. Ci\u00f2 viene fatto utilizzando la funzione `pd.cut`, che converte una serie di valori numerici in una serie qualitativa i cui valori possibili sono gli intervalli di una partizione aventi per estremi i valori specificati in corrispondenza dell'argomento `bins`. Considerando questa nuova serie \u00e8 possibile generare una tabella di frequenze congiunte pi\u00f9 significativa.\n\n\n```python\npd.crosstab(index=pd.cut(heroes['Weight'], bins=[30, 50, 80, 100, 200, 500, 1000]),\n            columns=[heroes['Gender']])\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Gender</th>\n      <th>F</th>\n      <th>M</th>\n    </tr>\n    <tr>\n      <th>Weight</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>(30, 50]</th>\n      <td>4</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>(50, 80]</th>\n      <td>116</td>\n      <td>88</td>\n    </tr>\n    <tr>\n      <th>(80, 100]</th>\n      <td>5</td>\n      <td>111</td>\n    </tr>\n    <tr>\n      <th>(100, 200]</th>\n      <td>11</td>\n      <td>84</td>\n    </tr>\n    <tr>\n      <th>(200, 500]</th>\n      <td>5</td>\n      <td>38</td>\n    </tr>\n    <tr>\n      <th>(500, 1000]</th>\n      <td>1</td>\n      <td>5</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nQuando si genera una tabella di frequenze congiunte, \u00e8 possibile specificare il valore `True` per l'argomento `margins` al fine di aggiungere una riga e una colonna che contengono i totali (calcolati rispettivamente sulle singole colonne e sulle singole righe). I valori ivi indicati prendono il nome di _frequenze marginali_, e corrispondono alle frequenze del carattere corrispondente. Per esempio, rigenerando la tabella delle frequenze congiunte di livello di intelligenza e genere con le colonne dei totali,\n\n\n```python\npd.crosstab(index=heroes['Intelligence'], \n            columns=heroes['Gender'], margins=True)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Gender</th>\n      <th>F</th>\n      <th>M</th>\n      <th>All</th>\n    </tr>\n    <tr>\n      <th>Intelligence</th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>average</th>\n      <td>38</td>\n      <td>101</td>\n      <td>139</td>\n    </tr>\n    <tr>\n      <th>good</th>\n      <td>78</td>\n      <td>165</td>\n      <td>243</td>\n    </tr>\n    <tr>\n      <th>high</th>\n      <td>27</td>\n      <td>112</td>\n      <td>139</td>\n    </tr>\n    <tr>\n      <th>low</th>\n      <td>0</td>\n      <td>13</td>\n      <td>13</td>\n    </tr>\n    <tr>\n      <th>moderate</th>\n      <td>21</td>\n      <td>37</td>\n      <td>58</td>\n    </tr>\n    <tr>\n      <th>All</th>\n      <td>164</td>\n      <td>428</td>\n      <td>592</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nla colonna `All` conterr\u00e0 le frequenze assolute per il carattere Intelligence, e parimenti la righa `All` elencher\u00e0 le frequenze assolute per il genere (escludendo ovviamente in entrambi i casi l'ultimo elemento che corrisponde al numero totale di osservazioni).\n\nLe frequenze congiunte a cui abbiamo fatto riferimento negli esempi visti finora erano frequenze assolute, ma \u00e8 immediato estendere tale concetto a quello delle _frequenze congiunte relative_. Queste si possono calcolare dividendo le frequenze assolute per il numero totale di osservazioni, oppure utilizzando come in precedenza il parametro `normalize` in `pd.crosstab`, che per\u00f2 ora ha diversi valori possibili:\n\n- specificando `'all'` vengono effettivamente calcolate le frequenze relative\n\n\n```python\npd.crosstab(index=heroes['Intelligence'], \n            columns=heroes['Gender'],\n            margins=True,\n            normalize='all')\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Gender</th>\n      <th>F</th>\n      <th>M</th>\n      <th>All</th>\n    </tr>\n    <tr>\n      <th>Intelligence</th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>average</th>\n      <td>0.064189</td>\n      <td>0.170608</td>\n      <td>0.234797</td>\n    </tr>\n    <tr>\n      <th>good</th>\n      <td>0.131757</td>\n      <td>0.278716</td>\n      <td>0.410473</td>\n    </tr>\n    <tr>\n      <th>high</th>\n      <td>0.045608</td>\n      <td>0.189189</td>\n      <td>0.234797</td>\n    </tr>\n    <tr>\n      <th>low</th>\n      <td>0.000000</td>\n      <td>0.021959</td>\n      <td>0.021959</td>\n    </tr>\n    <tr>\n      <th>moderate</th>\n      <td>0.035473</td>\n      <td>0.062500</td>\n      <td>0.097973</td>\n    </tr>\n    <tr>\n      <th>All</th>\n      <td>0.277027</td>\n      <td>0.722973</td>\n      <td>1.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n- usando `'index'` si otterr\u00e0 una tabella in cui i valori su ogni riga sommano a 1\n\n\n```python\npd.crosstab(index=heroes['Intelligence'], \n            columns=heroes['Gender'],\n            margins=True,\n            normalize='index')\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Gender</th>\n      <th>F</th>\n      <th>M</th>\n    </tr>\n    <tr>\n      <th>Intelligence</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>average</th>\n      <td>0.273381</td>\n      <td>0.726619</td>\n    </tr>\n    <tr>\n      <th>good</th>\n      <td>0.320988</td>\n      <td>0.679012</td>\n    </tr>\n    <tr>\n      <th>high</th>\n      <td>0.194245</td>\n      <td>0.805755</td>\n    </tr>\n    <tr>\n      <th>low</th>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>moderate</th>\n      <td>0.362069</td>\n      <td>0.637931</td>\n    </tr>\n    <tr>\n      <th>All</th>\n      <td>0.277027</td>\n      <td>0.722973</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n- indicando invece `columns` viene generata una tabella in cui tutte le colonne sommano al valore unitario\n\n\n```python\npd.crosstab(index=heroes['Intelligence'], \n            columns=heroes['Gender'],\n            margins=True,\n            normalize='columns')\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Gender</th>\n      <th>F</th>\n      <th>M</th>\n      <th>All</th>\n    </tr>\n    <tr>\n      <th>Intelligence</th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>average</th>\n      <td>0.231707</td>\n      <td>0.235981</td>\n      <td>0.234797</td>\n    </tr>\n    <tr>\n      <th>good</th>\n      <td>0.475610</td>\n      <td>0.385514</td>\n      <td>0.410473</td>\n    </tr>\n    <tr>\n      <th>high</th>\n      <td>0.164634</td>\n      <td>0.261682</td>\n      <td>0.234797</td>\n    </tr>\n    <tr>\n      <th>low</th>\n      <td>0.000000</td>\n      <td>0.030374</td>\n      <td>0.021959</td>\n    </tr>\n    <tr>\n      <th>moderate</th>\n      <td>0.128049</td>\n      <td>0.086449</td>\n      <td>0.097973</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nLa normalizzazione per colonne permette di ottenere una tabella che contiene le frequenze relative di due sotto-popolazioni come nel caso precedentemente visto, relativo alla forza di supereroi e supereroine. Invocando `plot` o `plot.bar` su questa tabella si ottiene in modo semplice un grafico che permette di confrontare visualmente tali frequenze.\n\n\n```python\npd.crosstab(index=heroes['Strength'],\n            columns=[heroes['Gender']],\n            normalize='columns').plot.bar(color=['pink', 'blue'], stacked=True)\nplt.show()\n```\n\nAbbiamo visto in una lezione precedente come generare direttamente un grafico di una serie senza elaborarla (calcolando per esempio le sue frequenze) produce un risultato che non \u00e8 normalmente informativo. Le cose sono diverse quando si considerano congiuntamente due serie con un medesimo indice: in tal caso per ogni elemento di questo indice (e dunque per ogni osservazione), i valori delle due serie possono essere utilizzati per individuare le coordinate di un punto nel piano. Visualizzando i punti corrispondenti a tutte le osservazioni si ottiene un _diagramma di dispersione_ (o _scatter plot_). In pandas questo tipo di grafico si genera invocando il metodo `plot.scatter` sul _dataframe_ che contiene le osservazioni, indicando come argomenti i nomi dei caratteri che devono essere considerati (il primo dei quali verr\u00e0 visualizzato sull'asse delle ascisse, usando invece quello delle ordinate per il secondo). Per esempio nella cella seguente viene visualizzato il diagramma di dispersione dei caratteri relativi ad altezza e peso dei supereroi di genere maschile.\n\n\n```python\nheroes[heroes['Gender']=='M'].plot.scatter('Height', 'Weight')\nplt.show()\n```\n\nI diagrammi di dispersione permettono di valutare visivamente se esistano delle relazioni che legano i due caratteri visualizzati. Per esempio nel grafico precedente si nota come tendenzialmente a un valore alto del peso corrisponda un valore alto per l'altezza e viceversa. Volendo \u00e8 possibile aggiungere al grafico una retta che metta in evidenza tale tipo di relazione:\n\n\n```python\nheroes[heroes['Gender']=='M'].plot.scatter('Height', 'Weight')\n\ntrend = lambda x: -1200 + x * 7\nx_range = [170, 300]\nline, = plt.plot(x_range, list(map(trend, x_range)), color='black')\nline.set_dashes([3, 2])\nline.set_linewidth(2)\nplt.show()\n```\n\nIn questo caso la retta \u00e8 stata posizionata \u00aba mano\u00bb: esistono metodi che ci permettono di determinarla in funzione delle osservazioni. Per il momento mettiamo in evidenza la possibilit\u00e0 di definire in modo formale una retta scelta in modo da minimizzare una sua distanza da tutti i punti, utilizzando il cosiddetto _metodo dei minimi quadrati_. La cella seguente mostra come determinare tale retta, avendo cura di lavorare su una copia del _dataframe_ sulla quale invocare il metodo `dropna` che elimina le righe in cui \u00e8 presente almeno un valore mancante.\n\n\n```python\nfrom sklearn import linear_model\n\nregr = linear_model.LinearRegression()\n\nheroes_with_data = heroes[heroes['Gender']=='M'].copy().dropna()\n\nX = heroes_with_data.loc[:, ['Height']]\nY = heroes_with_data['Weight']\n\nregr.fit(X, Y)\n\nheroes[heroes['Gender']=='M'].plot.scatter('Height', 'Weight')\n\nline, = plt.plot([0, 1000], regr.predict([[0], [1000]]), color='black')\nline.set_dashes([3, 2])\nline.set_linewidth(2)\n\nplt.show()\n```\n\nAnche in questo caso si rimanda alla [documentazione ufficiale](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html#sklearn.linear_model.LinearRegression) per gli approfondimenti del caso. Notiamo solo come la presenza dei tre valori estremi nella parte destra del grafico fa s\u00ec che la retta ottenuta sia sensibilmente diversa rispetto a quella tracciata a mano. Le cose cambiano se non si considerano questi tre valori.\n\n\n```python\nheroes_with_data = heroes_with_data[heroes_with_data['Height']<300]\n\nX = heroes_with_data.loc[:, ['Height']]\nY = heroes_with_data['Weight']\n\nregr.fit(X, Y)\n\nheroes[heroes['Gender']=='M'].plot.scatter('Height', 'Weight')\n\nline, = plt.plot([150, 350], regr.predict([[150], [350]]), color='black')\nline.set_dashes([3, 2])\nline.set_linewidth(2)\n\nplt.show()\n```\n\nVa infine notato che le relazioni tra due caratteri non necessariamente hanno una forma lineare, ma approfondire questo aspetto esula dal carattere introduttivo di questo corso.\n\n\n\n\n\n<div id=\"h-8\"></div>\n\n## Alcuni approfondimenti sulla generazione dei grafici <sup>*</sup>\n\n<div class=\"alert alert-info\">\nI paragrafi contrassegnati con un asterisco sono opzionali. \u00c8 dunque possibile saltarli a meno che non si voglia approfondire gli argomenti ivi contenuti.\n</div>\n\nUna cella grafica generata da matplotlib e visualizzata nel notebook contiene quella che viene definita una _figura_ (tecnicamente, un oggetto della classe `plt.Figure`). Ogni figura pu\u00f2 contenere uno o pi\u00f9 _sistemi cartesiani_ (oggetti della classe `plt.Axes`) i quali a loro volta contengono (nella maggior parte dei casi) due _assi cartesiani_ (oggetti della classe `plt.Axis`, da non confondere con `plt.Axes`). Tutte le figure che abbiamo generato finora contenevanu un unico sistema di assi cartesiani, su cui venivano eventualmente sovrapposti tutti i grafici che venivano creati. \u00c8 per\u00f2 possibile ottenere figure in cui pi\u00f9 sistemi cartesiani vengono affiancati su una griglia bidimensionale. Ci\u00f2 permette per esempio di affiancare grafici diversi. La gestione di tale griglia \u00e8 di norma demandata alla funzione `plt.subplot`, che accetta tre argomenti interi: i primi due indicano rispettivamente il numero di righe e di colonne nella griglia, e il terzo specifica una posizione nella griglia stessa (con la convenzione che in una griglia di $n$ colonne 1 indica la posizione nella prima riga e nella prima colonna, 2 quella nella prima riga e nella seconda colonna e cos\u00ec via fino a $n$ che indica l'ultima posizione nella prima riga; procedendo oltre si passa alla riga successiva, cos\u00ec che $n+1$ individua la seconda riga e la prima colonna e via discorrendo. Una volta che `plt.subplot` \u00e8 stato invocato, questo restituisce l'oggetto corrispondente al sistema cartesiano relativo, che conterr\u00e0 (eventualmente sovrapponendoli) tutti i grafici generati fino alla successiva invocazione di `plt.subplot`. Questo \u00e8 quello che succede per esempio quando si invocano i metodi di `plot` su una serie: nella cella seguente per esempio vengono affiancati i diagrammi a torta relativi alle frequenze di genere e livello di intelligenza.\n\n\n```python\nplt.figure(figsize=(6, 3))\nplt.subplot(1, 2, 1)\ngender_freq['Abs. frequence'].plot.pie(colors=['pink', 'blue'])\nplt.ylabel('')\nplt.xlabel('Gender')\nplt.subplot(1, 2, 2)\nheroes['Intelligence'].value_counts().plot.pie()\nplt.ylabel('')\n_ = plt.xlabel('Intelligence')\n```\n\nVa notato che in questo caso l'invocazione di `plt.axis('equal')` non sortirebbe l'effetto desiderato di mostrare due cerchi, in quanto il metodo agisce sulla figura e non sui suoi assi. \u00c8 quindi necessario impostare manualmente la dimensione della figura in modo che la base sia pari al doppio dell'altezza, cos\u00ec che entrambi i sistemi cartesiani risultino nei fatti essere dei quadrati. Ci\u00f2 viene fatto grazie all'invocazione preliminare di `plt.figure`, che crea una figura di dimensioni specifiche piuttosto che ottenere una figura predefinita.\n\n<div class=\"alert alert-info\">\nNella cella precedente va notata anche l'invocazione di `plt.xlabel` e `plt.ylabel` che spostano la descrizione dei diagrammi dall'asse delle ordinate a quello delle ascisse (per aumentare la leggibilit\u00e0), inserendo nel contempo delle descrizioni pi\u00f9 informative.\n</div>\n\nVi sono per\u00f2 alcuni casi in cui la generazione di un grafico implica la creazione di un nuovo sistema cartesiano nella figura: un esempio di questo comportamento si ha quando vengono generati dei grafici invocando i metodi di `plot` su un _dataframe_ piuttosto che su una serie. I due diagrammi a barre non vengono sovrapposti, bens\u00ec affiancati uno sopra l'altro.\n\n\n```python\nmale_strength_freq = (pd.crosstab(index=heroes.loc[heroes['Gender']=='M','Strength'],\n                                  columns='Abs. freq.',\n                                  normalize=True))\n\nfemale_strength_freq = (pd.crosstab(index=heroes.loc[heroes['Gender']=='F','Strength'],\n                                    columns='Abs. freq.',\n                                    normalize=True))\n\nmale_strength_freq.plot.bar(color='blue', legend=False)\n_ = female_strength_freq.plot.bar(color='pink', legend=False)\n\n```\n\nSe si volessero affiancare i due grafici in modo orizzontale (cosa che peraltro aiuterebbe il confronto) \u00e8 quindi necessario agire in modo diverso, notando che `plt.subplot` restituisce l'oggetto relativo al sistema cartesiano creato e che le funzioni di matplotlib accettano generalmente un argomento `ax` a cui passare il sistema in cui il risultato deve essere inserito.\n\n\n```python\nax = plt.subplot(1, 2, 1)\nmale_strength_freq.plot.bar(color='blue', legend=False, ax=ax, figsize=(10, 2))\nplt.ylim((0, 0.4))\nax = plt.subplot(1, 2, 2)\nfemale_strength_freq.plot.bar(color='pink', legend=False, ax=ax, figsize=(10, 2))\n_ = plt.ylim((0, 0.4))\n```\n\nVa notato come nei due grafici a barre siano stati impostati i limiti degli assi delle ascisse a un valore comune: in caso contrario il confronto tra le due immagini sarebbe potuto risultare sfalsato.\n\n<div class=\"alert alert-info\">\nI pi\u00f9 attenti avranno notato che python distingue automaticamente i nomi formali dei parametri dai corrispondenti valori effettivi, cosa che permette di scrivere `ax=ax` nelle precedenti invocazioni di `plot.bar`.\n</div>\n\nInfine, metodi come `plot` restituiscono il riferimento ai sistemi cartesiani su cui hanno operato: ci\u00f2 permette di sovrapporre dei grafici anche invocando metodi il cui comportamento predefinito \u00e8 quello di creare un nuovo sistema.\n\n\n```python\nax = male_strength_freq.plot(marker='o', color='blue')\nfemale_strength_freq.plot(marker='o', color='pink', ax=ax, legend=False)\n_ = ax.legend(['F', 'M'])\n```\n\n<div class=\"alert alert-info\">\nNella cella precedente \u00e8 stato utilizzando il metodo `legend` per modificare le etichette indicate nella legenda.\n</div>\n\n\n\n\n<div id=\"h-9\"></div>\n\n## I diagrammi stelo-foglia <sup>*</sup>\nUn _diagramma stelo-foglia_ (o _diagramma ramo-foglia_, o secondo la terminologia inglese _diagramma stem and leaf_) si ottiene considerando delle osservazioni a valori numerici, ordinandole e suddividendo ogni osservazione in una parte _meno significativa_ (rappresentata da un numero prefissato di cifre meno significative) e una parte _pi\u00f9 significativa_ (rappresentata dalle rimanenti cifre pi\u00f9 significative). Le osservazioni aventi la medesima parte pi\u00f9 significativa vengono raggruppate in uno stesso _stelo_, costituito da questa parte significativa seguita da una barra verticale e poi da tutte le parti meno significative (le _foglie_) separate da virgola. Per esempio il diagramma seguente descrive gli anni di prima apparizione dei primi cinquanta eroi del nostro dataset, dove le foglie sono costruite considerando la cifra meno significativa di ogni anno.\n\n<pre style=\"margin-left:0; line-height:1em\">\n194|1\n195|9\n196|5, 4, 3, 8, 5, 3, 0, 1, 8, 4, 2\n197|9, 2, 5, 7, 2, 7, 5\n198|5, 0, 6, 1, 4, 4, 1, 1, 0, 6, 4, 5, 2\n199|3, 5, 6, 4\n200|8, 7, 1, 5, 4, 5, 5, 4, 3, 4, 1\n201|1, 1\n</pre>\n\n<div class=\"alert alert-warning\">\nIl resto di questo paragrafo richiede una discreta conoscenza della programmazione in python, per cui vale la pena tralasciarlo durante una lettura preliminare.\n</div>\n\nPer non complicarci troppo la vita, assumiamo di avere a disposizione dei dati interi: gi\u00e0 cos\u00ec la costruzione di un diagramma stelo-foglie richiede una certa dose di perizia. Innanzitutto \u00e8 necessario eliminare i valori mancanti dai dati:\n\n\n```python\nx = [s for s in heroes_with_year['First appearance'][:50] if not np.isnan(s)]\n```\n\n\u00c8 poi necessario indicare il numero di cifre significative che comporranno le foglie. Memorizziamo nelle variabili `d` e `signif`, rispettivamente, tale numero e la corrispondente potenza di dieci.\n\n\n```python\nsignificant_digits = 1\nsignif = 10**significant_digits\n```\n\nIl passo successivo consiste nel costruire tutti i possibili valori per gli steli. In teoria, il pi\u00f9 piccolo di questi valori corrisponde al minimo elemento considerato a cui va tolta la parte meno significativa. Questa operazione richiede di convertire l'elemento in un valore intero e poi dividerlo per la potenza di 10 memorizzata in `signif` (che equivale a eliminare le `d` cifre meno significative).\n\n\n```python\nr = np.arange(int(min(x))/signif, (int(max(x))/signif + 1))\n```\n\nRisulta ora possibile eliminare da `r` tutti i valori che non rappresentano uno stelo, che sono quelli in corrispondenza dei quali non vi \u00e8 alcuna foglia. \n\n\n```python\nstart = [s for s in r\n         if len([e for e in x if s*signif <= e < (s+1)*signif])]\n```\n\nIl diagramma vero e proprio si ottiene costruendo per ogni stelo una coppia contenente il valore dello stelo e una lista di tutte le foglie corrispondenti. Per comodit\u00e0, convertiremo gi\u00e0 le foglie in stringhe, avendo cura di aggiungere eventuali zeri iniziali.\n\n\n```python\nstem = [(s, ['{:0{width}d}'.format(int(i%(s*signif)), width=significant_digits) if s\n                                                                                else str(int(i))\n             for i in x if signif*s <= i < signif*s+signif])\n        for s in start]\n```\n\nLa visualizzazione del diagramma richiede di convertire in stringa le coppie generate. Ci\u00f2 pu\u00f2 essere fatto invocando la funzione `format` su un'opportuna stringa di formattazione che ci permette di ottenere i vari rami nel formato richiesto e di inserirli in una lista, per poi concatenare gli elementi di quest'ultima separandoli tramite un carattere di `a capo`.\n\n\n```python\nimport math\nprint '\\n'.join(list(map(lambda e: '{:>{width}}|{}'.format(e[0],\n                                                           ', '.join(e[1]),\n                                                           width=int(1+math.log10(max(start)))),\n                         stem)))\n```\n\n    194|1\n    195|9\n    196|5, 4, 3, 8, 5, 3, 0, 1, 8, 4, 2\n    197|9, 2, 5, 7, 2, 7, 5\n    198|5, 0, 6, 1, 4, 4, 1, 1, 0, 6, 4, 5, 2\n    199|3, 5, 6, 4\n    200|8, 7, 1, 5, 4, 5, 5, 4, 3, 4, 1\n    201|1, 1\n\n\nPer poter generare velocemente altri diagrammi stelo-foglia, \u00e8 opportuno riscrivere il codice qui sopra organizzandolo all'interno di una funzione.\n\n\n```python\ndef stem_leaf(data, significant_digits=1):\n    x = [s for s in data if not np.isnan(s)]\n    signif = 10**significant_digits\n\n    r = np.arange(int(min(x))/signif, int(max(x))/signif + 1)\n    start = [s for s in r if len([e for e in x if s <= e < s+signif])]\n    stem = [(s, ['{:0{width}d}'.format(int(i%(s*signif)), width=significant_digits) if s\n                                                                                    else str(int(i))\n                 for i in x if signif*s <= i < signif*s+signif])\n            for s in start]\n\n    return '\\n'.join(list(map(lambda e: '{:>{width}}|{}'.format(e[0],\n                                                                ', '.join(e[1]),\n                                                                width=int(1+math.log10(max(start)))),\n                              stem)))\n```\n\nCi\u00f2 ci permette, per esempio, di calcolare il diagramma per un numero maggiore di osservazioni.\n\n\n```python\nprint stem_leaf(heroes_with_year['First appearance'][:150])\n```\n\n    193|9\n    194|1, 0, 4, 0, 1, 8, 0, 1, 1, 7\n    195|9, 9, 9, 5\n    196|5, 4, 3, 8, 5, 3, 0, 1, 8, 4, 2, 6, 5, 4, 4, 4, 3, 5, 7, 4, 3, 8, 3, 3, 3, 3, 4, 5, 3, 5, 4\n    197|9, 2, 5, 7, 2, 7, 5, 6, 7, 3, 9, 7, 6, 2, 1, 6, 6, 5, 9, 2, 5, 5, 5, 1, 1, 0\n    198|5, 0, 6, 1, 4, 4, 1, 1, 0, 6, 4, 5, 2, 0, 0, 6, 1, 9, 9, 0, 1, 6, 7, 9, 5, 7, 5, 7, 7, 4\n    199|3, 5, 6, 4, 3, 3, 9, 3, 8, 2, 8, 2, 9, 8, 5, 4, 0, 6, 5, 7\n    200|8, 7, 1, 5, 4, 5, 5, 4, 3, 4, 1, 0, 0, 8, 7, 4, 7, 4, 1, 0, 6, 4\n    201|1, 1, 0, 1, 2, 5\n\n\n<div class=\"alert alert-info\">\nIl codice sopra prodotto \u00e8 basato su alcune funzionalit\u00e0 avanzate della funzione `format` invocabile sulle stringhe. In particolare, viene formattato dell'output forzando la conversione da numeri in stringhe in modo da garantire che il risultato contenga un numero minimo (ma variabile) di caratteri, aggiungendo ove necessario in un caso degli spazi e in un altro degli zeri. Per approfondire la tematica della formattazione dell'output si rimanda alla  [documentazione ufficiale](https://docs.python.org/2/tutorial/inputoutput.html).\n</div>\n\n\n```python\n\n```\n\n<hr style=\"width: 90%;\" align=\"left\" />\n<span style=\"font-size: 0.8rem;\">D. Malchiodi, Superhero data science. Vol 1: probabilit\u00e0 e statistica: Dati e frequenze, 2017.</span>\n<br>\n<span style=\"font-size: 0.8rem;\">Powered by </span>\n<div style=\"float: left; margin-top: 1ex;\">\n\n\n\n\n<span style=\"font-size: 0.7rem; line-height: 0.7rem; vertical-align: middle;\">Quest'opera \u00e8 distribuita con Licenza <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-nd/4.0/\">Creative Commons Attribuzione - Non commerciale - Non opere derivate 4.0 Internazionale</a></span>.\n</div>\n", "meta": {"hexsha": "69abd9f5a356b12223ec8e550f5edc13e57d208c", "size": 541519, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "L06-Dati-e-frequenze.ipynb", "max_stars_repo_name": "dariomalchiodi/python-DS4EBF", "max_stars_repo_head_hexsha": "e8134f890f9053d2dacabf4acbde3e5a8116fa0a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "L06-Dati-e-frequenze.ipynb", "max_issues_repo_name": "dariomalchiodi/python-DS4EBF", "max_issues_repo_head_hexsha": "e8134f890f9053d2dacabf4acbde3e5a8116fa0a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "L06-Dati-e-frequenze.ipynb", "max_forks_repo_name": "dariomalchiodi/python-DS4EBF", "max_forks_repo_head_hexsha": "e8134f890f9053d2dacabf4acbde3e5a8116fa0a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 147.7138570649, "max_line_length": 24736, "alphanum_fraction": 0.853011621, "converted": true, "num_tokens": 22642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.07369627275773762, "lm_q1q2_score": 0.03311856216483321}}
{"text": "# Getting started on Using Jupyter Notebooks and Python\n\n## Learning Objectives\nThe goal of this notebook is to learn how to use Python for solving chemical engineering problems. We assume that you are familiar with content from APSC 160 (or any other introductory programming courses if you are a transfer student), but have no prior experience with Python.\n\nBy the end of this section, you should be able to:\n\n1. Understand how to use Jupyter notebooks\n2. Write simple Markdown and Python code\n\n## Introduction and Motivation\n\nWelcome to **CHBE 241: Material and Energy Balances**!\n\nIn this course, we will use Jupyter notebooks to illustrate how to apply modern, open-source software tools for chemical engineering applications. We will be using Python, a free, open-source and powerful computing environment. It is one of the most popular languages in the data science community alongside R, which you will learn in STAT 241.\n\nCoding is one of the most useful, transfereable skills that you can learn in the 21st century. According to the [U.S. Department of Labor](https://www.bls.gov/ooh/architecture-and-engineering/chemical-engineers.htm), the chemical engineering industry is projected to grow 2% between 2014-2024. Over the same period, the software industry is projected to grow by a staggering 17%. Software, automation and data science will serve an increasingly important role in the field of chemical engineering. For example, researchers in the [DAIS Lab](http://dais.chbe.ubc.ca/) here in CHBE are investigating applications of machine learning techniques to design better controllers for industrial processes.\n\nThe goal of using Python in this course is to provide you with a gentle introduction to the language of modern software development and equip you with the necessary foundations to pursue further explore this area if you are interested in learning more.\n<hr>\n\n\n##  Running Jupyter Notebooks\nJupyter notebooks are documents that combines Python code, text, equations and images. These notebooks are meant to be accessed through a browser. They are easily shareable and downloadable into other file types (e.g. PDF and HTML) for your convenience. \n\nTo interact with and edit these notebooks, you will need to open them using a Jupyter server. In this course, we will use a Jupyter server hosted by UBC at [https://ubc.syzygy.ca/](https://ubc.syzygy.ca/). \n\n### Running Jupyter on the Cloud: [Syzygy](https://ubc.syzygy.ca/)\n 1. Go to the Syzygy server in the link above \n 2. Sign in to Syzygy with your CWL login \n 3. Click \"Start My Server\" and the Jupyter interface will open\n 4. Go to File > New > Python3 and create a new file \n\n 5. Enter this into the box `!git clone https://github.com/UBCEnvision/CHBE241` and press \"Shift+Enter\" \n 6. Go to File > Open and you should see the course syllabus downloaded into a folder called **CHBE241**\n\n## Using Jupyter\n\nA notebook consists of **cells** that contain either **text** or **code**. Cells that contain text are known as **Markdown** cells, and they can support formatted text, images, HTML and equations written in $ \\LaTeX $. To swtich between Markdown and code in each cell, use the dropdown menu at the top of the page.\n\nLet's take a few minutes to familiarize ourselves with Jupyter. The Jupyter interface is very user-friendly and the best way to learn is to explore by clicking on different buttons. Try doing the following:\n\n1. Take a look at the course materials and observe the different folders and files\n2. Create a new Python 3 notebook \n3. Rename the notebook and save it\n\nJupyter notebooks have a **```.ipynb```** extension with a notebook icon beside the filename.\n\n## Edit Mode and Command Mode\n\nThere are 2 modes in Jupyter notebooks: edit mode and command mode.\n\nEdit mode is indicated by a green cell border and a prompt showing in the editor area:\n\n\n\nWhen a cell is in edit mode, you can type into the cell, like a normal text editor. Enter edit mode by pressing `Enter` or using the mouse to double click on a cell.\n\nCommand mode is indicated by a grey cell border with a blue left margin:\n\n\n\nWhen you are in command mode you will be able to perform operations on cells like copy, paste and delete but not type into individual cells. Enter command mode by pressing `Esc`. \n\nHere are some of the shortcuts available in command mode:\n\n| Command Mode Action | Shortcut |\n| :---: | :---: |\n| Insert empty cell above | `a` |\n| Insert empty cell below | `b` |\n| Copy cell | `c` |\n| Cut cell | `x` |\n| Paste cell below | `v` |\n| To code | `y` |\n| To markdown | `m` |\n| Save and checkpoint | `s` |\n\n## Python Code\n\nWe will start with some basic variable assignment and printing in Python. Create a new notebook, enter edit mode then write this in the cell:\n\n```Python\nx = 3\n```\n\nand then hit *Shift+Enter*.  \n\nMake sure you use **Shift+Enter**. If you just hit Enter you'll find that it will simply add another line to the current cell. In this new cell, we can print out the value using:\n\n```Python\nprint(x)\n```\n\nand then hit **Shift+Enter**.  The output of that command is printed immediately below the cell.\n\nThe whole procedure should look something like this:\n\n\n\n## Overwriting variables\n\nSince each cell is interacting with the same Python instance, if we give `x` a new value and then enter `print(x)` we'll get that new value.  That's pretty straight forward \u2014but what if we then delete the cell where we gave `x` a new value?\n\nLet's take a look!\n\n\n\nEven though we deleted the cell where we assigned `x = 7`, the assignment is still valid.  In fact, the assignment will remain valid until we explicitly execute a cell that sets x equal to a new value, or until we completely restart this Jupyter Notebook instance.\n\nIf you move cells around or execute them in a nosequential order, you might confuse yourself (and others). To start again and clear things up, use the <i class=\"fa-repeat fa\"></i> button or the Kernel menu to clear outputs and restart the kernel, then choose \"Run All\" from the Cell menu.\n\n### Basic Arithmetic\n\nPython can easily perform basic arithmetic operations.\n\nUsing Python is as simple as $1+1$:\n\n\n```python\n1+1\n```\n\n\n\n\n    2\n\n\n\nYou can also assign numbers to variables:\n\n\n```python\nx = 3\ny = 4\nprint (\"x + y = \", x + y)\nprint (\"x * y = \", x*y)\nprint (\"x ^ y = \", x**y )\nprint (\"x / y = \", x/y)  \n```\n\n    x + y =  7\n    x * y =  12\n    x ^ y =  81\n    x / y =  0.75\n\n\n### Numpy\n\nMore advanced functions require a numerical computation library called Numpy (numerical Py). We will be using this library in almost every notebook.\n\nWhen using functions in the numpy library, you must first import the library using the following command: \n\n```Python\nimport numpy as np\n```\n\nIn the code above, `numpy` is the name of the library that we are importing. `np` is just the name of a variable that we are assigning the library to. Assigning a variable is optional and just a matter of convenience. It makes our code look cleaner and easier to type if the name of the library is long. \n\nFor example, here's how to print the value of $\\cos(\\pi)$ and $\\sin\\big(\\frac{\\pi}{2}\\big)$ using `numpy`:\n\n\n```python\nimport numpy as np\n\nx = np.pi\nprint (np.cos(x))\nprint (np.sin(0.5*x))\n```\n\n    -1.0\n    1.0\n\n\n## Markdown Math\nMarkdown can be used to render nice $\\LaTeX$-styled equations. For example, here's the Thiele modulus written in $\\LaTeX$: $\\Phi=\\frac{R}{3}\\sqrt{\\frac{V_\\text{M}}{K_M\\cdot D_eff}}$.\n\nTo write equations in Markdown, first make sure you change your cell type to **Markdown** instead of Code.\n\n* For inline math, wrap LaTeX inside single dollar signs: `$...$`\n* For single-line rendering, wrap LaTeX inside double dollar signs: `$$...$$`\n\nFor example:\n\n```\n$$\nf'(a) = \\lim_{x \\to a} \\frac{f(x) - f(a)}{x - a}\n$$\n```\n\nWould render as:\n\n$$\nf'(a) = \\lim_{x \\to a} \\frac{f(x) - f(a)}{x - a}\n$$\n\n\n\n\n## Using Lists\nLists are a very useful way of organizing data in Python. If you can recall from APSC160, an array is a collection of similar data elements. Lists in Python are very similar to arrays in C. \n\nHere are some examples:\n\n\n```python\nmy_numbers = [2, 4, 6, 8]\nprint(my_numbers)\n```\n\n    [2, 4, 6, 8]\n\n\nConcatenation is combing two lists together. This is done by using **```+```** operation.\n\n\n```python\na = [2, 4, 6, 8]\nb = [10, 12, 14]\n\nprint(a + b)\n```\n\n    [2, 4, 6, 8, 10, 12, 14]\n\n\nTo sum elements in your list, you can do: \n\n```Python\nnp.sum(list)\n```\n\n\n```python\nprint(np.sum(a + b))\n```\n\n    56\n\n\n### `For` loops\n\nFor loops can also be used in Python to iterate over a list. For loops work by first typing `for`, then the variable or list your iterating over, then `in`, then the length or list that you want to iterate until. A colon, `:` is used to signify the start of the for loop and everything that is in the for loop needs to be indented using the `TAB` key. \n\nHere are two examples that will take numbers from a list and print out the square of those numbers. You might be familiar with the `^` symbol as the power operator. In Python, we use `**` as the power operator. To get the square of two, we would write `2**2`.\n\nExample 1:\n\n\n```python\na = [2, 4, 5, 6, 8]\nfor i in a:\n    print(\"a =\", i, \"a^2 =\", i**2)\n```\n\n    a = 2 a^2 = 4\n    a = 4 a^2 = 16\n    a = 5 a^2 = 25\n    a = 6 a^2 = 36\n    a = 8 a^2 = 64\n\n\nExample 2:\n\n\n```python\nb = [10, 12, 14]\nfor i in b:\n    print(\"b =\", i, \"b^2 =\", i**2)\n```\n\n    b = 10 b^2 = 100\n    b = 12 b^2 = 144\n    b = 14 b^2 = 196\n\n\nAs you can see in both examples, `i` iterated through `a` in the first example and `b` in the second example. \n\n### List Comprehension\n\nIn Python, instead of writing a for loop, we can also use [List Comprehension](http://www.secnetix.de/olli/Python/list_comprehensions.hawk) as a shortcut to perform operations on elements in a list. Click on the link to find out more.\n\nHere's an example of using list comprehension to square the numbers in a list:\n\n```Python\na_squared = [x**2 for x in a]\n```\n\nLet's break it down into 2 parts, we'll start with the second half of the statement:\n\n```Python\nfor x in a\n```\n\nmeans that we are taking each element in the list `a`, and assigning it to `x`\n\nIn the first half of the statement, we tell Python what we want to do with `x`:\n\n```Python\nx**2\n```\n\nwould square the number in `x`.\n\n\n\n\n```python\n# Using list comprehension to square numbers in list a\na_squared = [x**2 for x in a]\nprint(a_squared)\n```\n\n    [4, 16, 36, 64]\n\n\n\n```python\n# Using list comprehension to return only even numbers in list a\na_squared = [x for x in a if (x % 2 == 0)]\nprint(a_squared)\n```\n\n    [2, 4, 6, 8]\n\n\n## Using Dictionaries\nJust like lists, dictionaries are another type of useful data structure in Python. They work by having key-value pairs. It is common to have the key as a string and numbers as the values. Dictionaries are useful for storing and retrieving data. \n\nA **key** is something we can use to lookup values of interest. For example, in an actual dictionary, a key would be an unfamiliar word that we are interested in looking up, and the value would be the dictionary entry explaining the meaning of the word.\n\nJust like an actual dictionary, where no words are repeated, **keys are always unique in Python dictionaries**.\n\nHere is an example of atoms and the number of protons associated with that atom. The keys are the element names as a string, the values are the proton numbers, and our dictionary is called `number_of_protons`.\n\n\n```python\nnumber_of_protons = {'Pb' : 72,'H' : 1, 'F' : 9,'C' : 6, 'Fe' : 26}\nprint(number_of_protons)\n```\n\n    {'Pb': 72, 'H': 1, 'F': 9, 'C': 6, 'Fe': 26}\n\n\nYou may have noticed that we made a mistake with the number of protons that lead has. It should be 82 instead of 72.\n\nRather than rewriting the whole dictionary, we can change a single key's value using this syntax:\n\n```Python\nnumber_of_protons['key'] = new_value\n```\n\n\n```python\nnumber_of_protons['Pb'] = 82\nprint(number_of_protons)\n```\n\n    {'Pb': 82, 'H': 1, 'F': 9, 'C': 6, 'Fe': 26}\n\n\nNow that the dictionary is fixed, let's add another atom, Radon.\n\n\n```python\nnumber_of_protons['Rn'] = 86\nprint(number_of_protons)\n```\n\n    {'Pb': 82, 'H': 1, 'F': 9, 'C': 6, 'Fe': 26, 'Rn': 86}\n\n\nWe can easily get all key-value pairs in a dictionary using a for loop.\n\n\n```python\nfor atoms in number_of_protons.keys():\n    print(\"The number of protons in {:<s} is {:<7.2f}\".format(atoms,number_of_protons[atoms]))\n```\n\n    The number of protons in Pb is 82.00  \n    The number of protons in H is 1.00   \n    The number of protons in F is 9.00   \n    The number of protons in C is 6.00   \n    The number of protons in Fe is 26.00  \n    The number of protons in Rn is 86.00  \n\n\nUnlike lists, the keys in a dictionary are not sorted or ordered ([Further Reading](https://developers.google.com/edu/python/dict-files) for details). Since the outputed values looks random, we can sort it alphabetically based on the keys by calling the `sorted()` function.\n\n```Python\nsorted(number_of_protons.keys())\n```\n\n\n```python\nfor atoms in sorted(number_of_protons.keys()):\n    print(\"The number of protons in {:<s} is {:<7.2f}\".format(atoms,number_of_protons[atoms]))\n```\n\n    The number of protons in C is 6.00   \n    The number of protons in F is 9.00   \n    The number of protons in Fe is 26.00  \n    The number of protons in H is 1.00   \n    The number of protons in Pb is 82.00  \n\n\n## Plotting with Python\nTo plot in Python, we need to import the `matplotlib.pyplot` library. This alows Python plotting functionality similar to MATLAB. Here are some examples:\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n%matplotlib inline\n\nx = np.linspace(0.01,2)\ny = np.exp(x)\nz = np.log(x)\n\nplt.plot(x, y, 'b', x, z, 'r')\nplt.xlabel('x');\nplt.ylabel('f(x)');\nplt.title('Plotting e^(x) and ln(x)')\nplt.legend(['e^(x)','ln(x)'])\nplt.grid()\n```\n\n\n```python\nx = np.linspace(0,np.pi/2)\na = np.sin(x)\nb = np.cos(x)\nplt.plot(a,b)\nplt.axis('equal')\n```\n\n\n```python\nx = np.linspace(0,np.pi)\na = np.sin(x)\nb = np.cos(x)\nplt.plot(a,b)\nplt.axis('equal')\n```\n\n\n```python\nx = np.linspace(0,2*np.pi)\na = np.sin(x)\nb = np.cos(x)\nplt.plot(a,b)\nplt.axis('equal')\n```\n\n\n```python\nx = np.linspace(0.01,2)\nplt.subplot(2,1,1)\nplt.plot(x,y)\nplt.title('e^(x)')\n\nplt.subplot(2,1,2)\nplt.plot(x,z)\nplt.title('ln(x)')\nplt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)\n```\n\n## Solving Equations\nOne of the best features of Python is its massive amounts of libraries to extend its functionallity. Here is an example of solving some algebraic equations using the **`sympy`** library.\n\n\n```python\nimport sympy as sym\n\nsym.var('P V n R T');\n\n# Gas constant\nR = 8.314      #J/K*mol\n\n#Moles of Helium\nn = 2.3        #Moles\n\n#Temperature\nT = 293.15     #Kelvin\n\n#Equation\neqn = sym.Eq(P*V,n*R*T)\n\n#Solve for P\nf1 = sym.solve(eqn,P)\nprint(f1[0])\n\n#Solve for V\nf2 = sym.solve(eqn,V)\nprint(f2[0])\n\n#Give value for V\nV = 0.121\neqn = sym.Eq(P*V,n*R*T)\n\n#Solve for P again\nf3 = sym.solve(eqn,P)\nprint(f3[0])\n```\n\n    5605.67293/V\n    5605.67293/P\n    46327.8754545455\n\n\n<hr>\n### Credits\n\nThis notebook uses material from the following sources:\n\n- https://github.com/rwest/CHME4510/\n- https://github.com/jckantor/CBE20255\n- https://github.com/patrickwalls/arc-summer-school/\n", "meta": {"hexsha": "5b623bdb6f00b2d531b973917d98e4e151e0f303", "size": 99580, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Modules/Module-0-Introduction/Getting started on Using Jupyter Notebooks and Python.ipynb", "max_stars_repo_name": "OpenChemE/CHBE241", "max_stars_repo_head_hexsha": "0c70fe47fd222a5a9f3629b0d3490e1a1931da98", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-05-17T02:21:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-21T21:09:22.000Z", "max_issues_repo_path": "Build/_sources/Module-0-Introduction/Getting started on Using Jupyter Notebooks and Python.ipynb.txt", "max_issues_repo_name": "UBCEnvision/chbe", "max_issues_repo_head_hexsha": "0c70fe47fd222a5a9f3629b0d3490e1a1931da98", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-06-25T07:45:56.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-25T07:45:56.000Z", "max_forks_repo_path": "Modules/Module-0-Introduction/Getting started on Using Jupyter Notebooks and Python.ipynb", "max_forks_repo_name": "UBCEnvision/chbe", "max_forks_repo_head_hexsha": "0c70fe47fd222a5a9f3629b0d3490e1a1931da98", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-09-08T17:05:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-23T00:53:16.000Z", "avg_line_length": 107.7705627706, "max_line_length": 16966, "alphanum_fraction": 0.8499297048, "converted": true, "num_tokens": 4206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13660838299605804, "lm_q2_score": 0.24220563419533916, "lm_q1q2_score": 0.033087320039960025}}
{"text": "# Analysis of the Cicero corpus & comparison to other authors and works\nThis notebook was used to develop a talk I gave at the Cicero Digitalis Conference on Feb 25, 2021\nvideo here: https://www.youtube.com/watch?v=tJwmXZHZ924\n\n\n```python\nimport os.path\nfrom collections import Counter\nfrom glob import glob\nimport inspect\nimport os\nimport pickle\nimport sys\nfrom typing import List, Dict, Tuple\nfrom copy import deepcopy\nimport random\n\nimport pandas as pd\nimport re\nfrom typing import Set\n\nfrom cltk.sentence.lat import LatinPunktSentenceTokenizer\nfrom cltk.tokenizers.lat.lat import LatinWordTokenizer\nfrom cltk.alphabet.lat import normalize_lat\n\n\n# from cltk.corpus.latin.phi5_index import PHI5_INDEX\n# from cltk.corpus.readers import get_corpus_reader\n# from cltk.stem.latin.j_v import JVReplacer\n# from cltk.stem.lemma import LemmaReplacer\n# from cltk.tokenize.latin.sentence import SentenceTokenizer\n# from cltk.tokenize.word import WordTokenizer\nimport cltk\nfrom random import sample\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MaxNLocator\nplt.style.use('fivethirtyeight')\n\n\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\nsys.path.insert(0,parentdir)\n \nfrom mlyoucanuse.aeoe_replacer import AEOEReplacer\nfrom mlyoucanuse.text_cleaners import ( normalize_accents, disappear_angle_brackets,\n                                        drop_punct, disappear_round_brackets, swallow,swallow_obelized_words,\n                                        truecase, dehyphenate, accept_editorial,\n                                        swallow_braces, swallow_obelized_words,\n                                       swallow_angular_brackets,\n                                        swallow_square_brackets)\n\nfrom scipy.optimize import curve_fit\nimport numpy as np\n\nimport cltk\ncltk.__version__\n```\n\n\n\n\n    cltk 1.0.11 (/Users/todd/opt/anaconda3/envs/mlycu3.8/lib/python3.8/site-packages)\n\n\n\n\n```python\nsent_toker = LatinPunktSentenceTokenizer()\nword_toker = LatinWordTokenizer()\n```\n\n\n```python\nsent_toker.tokenize(\"o rem difficilem planeque perditam! quam nihil praetermittis in consilio dando; quam nihil tamen quod tibi ipsi placeat explicas! non esse me una cum Pompeio gaudes\")\n```\n\n\n\n\n    ['o rem difficilem planeque perditam!',\n     'quam nihil praetermittis in consilio dando; quam nihil tamen quod tibi ipsi placeat explicas!',\n     'non esse me una cum Pompeio gaudes']\n\n\n\n\n```python\ncicero_tess = glob(os.path.expanduser('~/cltk_data/latin/text/latin_text_tesserae/texts/cicero.*.tess'))\nlen(cicero_tess)\n```\n\n\n\n\n    122\n\n\n\n\n```python\ntruecase_file = 'truecase_counter.latin.pkl'\n\nif os.path.exists(truecase_file):\n    with open(truecase_file, 'rb') as fin:        \n        case_counts = pickle.load(fin)\n```\n\n\n```python\nANY_ANGLE =  re.compile(\"<.[^>]+>\") # remove tesserae metadata \nsent_lens = []\nsent_map={}\nsent_idx=0\ndouble_break_idx = []\nwith open('cicero_tesserae.txt', 'wt') as fout:\n    for file in tqdm(cicero_tess, total=len(cicero_tess)):\n        with open(file, 'rt') as fin:\n            text = fin.read()\n            text = swallow(text, ANY_ANGLE)\n            text = normalize_lat(text, drop_accents=True, drop_macrons=True, jv_replacement=True, ligature_replacement=True)\n            text = accept_editorial(text)\n            for sent in sent_toker.tokenize(text):\n                tokens = word_toker.tokenize(sent)\n                tokens = [truecase(token, case_counts) for token in tokens]\n                sent_map[sent_idx] = tokens\n                sent_idx +=1\n                sent_lens.append(len(tokens))\n                fout.write(f\"{' '.join(tokens)}\\n\")\n        fout.write(f\"\\n\\n\")\n        double_break_idx.append(sent_idx)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 122/122 [00:25<00:00,  4.85it/s]\n\n\n\n```python\nsent_lens = np.array(sent_lens)\nnp.mean( sent_lens), np.std( sent_lens), np.max(sent_lens) \n```\n\n\n\n\n    (25.30188163469862, 22.32132597636475, 713)\n\n\n\n\n```python\nlen([tmp for tmp in sent_lens if tmp > 510])\n```\n\n\n\n\n    3\n\n\n\n\n```python\n! wc -l cicero_tesserae.txt\n```\n\n       44142 cicero_tesserae.txt\r\n\n\n\n```python\n# graph the counts of Cicero sentence lengths\n# may be relevant to assessing the model \ncicero_sent_lens= Counter(sent_lens.tolist())\n# cicero_sent_lens.most_common(10)\nx, y = zip(* sorted(cicero_sent_lens.items(), key=lambda x:x[0]))\nplt.plot(x[:50],y[:50])\n```\n\n\n```python\n# Find 200 sentences of 8-18 tokens\n# when these are removed from the training set, all the words should still appear in the training set\n# but none of the exact sentences should appear in the training set\n```\n\n\n```python\nword_counter = Counter()\nfor tokens in sent_map.values():\n    for tok in tokens:\n        word_counter.update({tok:1})\n```\n\n\n```python\nmin_tokens, max_tokens, min_token_count = 8, 23, 4 # 8, 19, 4\n```\n\n\n```python\ncandidate_sent_idx =[]\nfor key, vals in sent_map.items():\n    istarget = True\n    if len(vals) >= min_tokens and len(vals) <= max_tokens:\n        for val in vals:\n            if word_counter[val] < min_token_count:\n                istarget = False\n        if istarget:\n            candidate_sent_idx.append(key)\nlen(candidate_sent_idx)\n```\n\n\n\n\n    8300\n\n\n\n\n```python\ncandidate_sent_idx[:3]\n```\n\n\n\n\n    [9, 12, 16]\n\n\n\n\n```python\nsent_map[12]\n```\n\n\n\n\n    ['frater',\n     'accedit',\n     'quem',\n     'socium',\n     'huius',\n     'fortunae',\n     'esse',\n     'non',\n     'erat',\n     'aequum',\n     '.']\n\n\n\n\n```python\ndef check_test_candidate( proposed_test_sents_idx:Set[int], sent_map):\n    total_tokens = set()    \n    for key, vals in sent_map.items():\n        if key in proposed_test_sents_idx:\n            continue\n        for val in vals:            \n            total_tokens.add(val)\n    return len(total_tokens)\n```\n\n\n```python\nlen(word_counter.keys())\n```\n\n\n\n\n    70573\n\n\n\n\n```python\ntest_set_size=2500 # fails around 4k\n```\n\n\n```python\ntest_candidates = sample( candidate_sent_idx, test_set_size)\ncheck_test_candidate(set(test_candidates), sent_map)\n\n```\n\n\n\n\n    70573\n\n\n\n\n```python\n# create two files cicero.train.txt, cicero.test.txt\n```\n\n\n```python\n# double_break_idx\ntest_can = set(test_candidates)\ndouble_breaks = set(double_break_idx)\n\nwith open('cicero.train.txt', 'wt') as fout:\n    for key, vals in sent_map.items():\n        if key in test_can:\n            fout.write(f\"\\n\\n\")\n            continue\n        fout.write(f\"{' '.join(vals)}\\n\")\n        if key in double_breaks:\n            fout.write(f\"\\n\\n\")\n```\n\n\n```python\nwith open('cicero.test.txt', 'wt') as fout:\n    for key, vals in sent_map.items():\n        if key in test_can:\n            fout.write(f\"{' '.join(vals)}\\n\")\n```\n\n\n```python\ntest_sentences =[' '.join(sent_map[tmp ]) for tmp in test_candidates]\ndf = pd.DataFrame({\"sentence_idx\": test_candidates, \"test_sentences\": test_sentences })\ndf.to_csv(f'cicero.test.sentences.{test_set_size}.csv', index=False)\ndf.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>sentence_idx</th>\n      <th>test_sentences</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>16983</td>\n      <td>uidendum est igitur , ut ea liberalitate utamu...</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>32813</td>\n      <td>aut , si omnes homines uelint , obscura esse p...</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>19411</td>\n      <td>ualent pueri , studiose discunt , diligenter d...</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>25066</td>\n      <td>hoc enim identidem dicitis , non intellegere n...</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>28701</td>\n      <td>bene hercule narras ; nam istum doctum et sapi...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ntrain_sentences  = [ ' '.join(sent_map[tmp ]) for tmp in sent_map.keys()  if tmp not in test_can ]\ntrain_idx = [ tmp for tmp in sent_map.keys() if tmp not in test_can]\ndf = pd.DataFrame({\"sentence_idx\": train_idx, \"train_sentences\": train_sentences })\ndf.to_csv(f'cicero.train.sentences.N-{test_set_size}.csv', index=False)\ndf.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>sentence_idx</th>\n      <th>train_sentences</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0</td>\n      <td>etsi cum tu has litteras legeres putabam fore ...</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>sed haec fortasse \u03ba\u03b5\u03bd\u03cc\u03c3\u03c0\u03bf\u03c5\u03b4\u03b1 sunt , quae tamen...</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2</td>\n      <td>quaero autem , quo facilius scire possim quid ...</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>3</td>\n      <td>urbem quidem iam refertam esse optimatium audi...</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>4</td>\n      <td>hinc uero uulgo uadunt ; etiam M'. Lepidus cum...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n\n```\n\n\n```python\n# TODO create tesserae.wo.cicero.txt\n# create aquinas.txt\n# phi5?\n```\n\n\n```python\ndef get_word_counts(files:List[str], tesserae=False)-> Dict[str, int] :\n    \"\"\"\n    Given a list of files, \n    clean & tokenize the documents\n    returns: counter of inflected words \n    \"\"\"\n    inflected_word_counter = Counter()\n#     jv_replacer = JVReplacer()\n#     aeoe_replacer = AEOEReplacer()\n#     toker = WordTokenizer('latin')\n#     sent_toker = SentenceTokenizer()\n#     lemmatizer = LemmaReplacer('latin')\n\n    for file in files: # , total=len(files), unit='files'):\n        with open(file, 'rt') as fin:\n            text = fin.read()\n            text = text.replace(\"-\\n\", \"\")\n            text = text.replace(\"\\n\", \" \")\n            if tesserae:\n                text = swallow(text, ANY_ANGLE)\n            text = normalize_lat(text, drop_accents=True, drop_macrons=True, jv_replacement=True, ligature_replacement=True)\n            text = accept_editorial(text)\n            for sent in sent_toker.tokenize(text):\n                tokens = word_toker.tokenize(sent)\n                tokens = [truecase(token, case_counts) for token in tokens]\n                for token in tokens:\n                    inflected_word_counter.update({ token: 1})                    \n\n#             for sent in sent_toker.tokenize(text):\n#                 sent = dehyphenate(sent) # because it's Phi5\n#                 sent = swallow_braces(sent)\n#                 sent = swallow_square_brackets(sent)\n#                 sent = disappear_round_brackets(sent)\n#                 sent = swallow_obelized_words(sent)\n#                 sent = disappear_angle_brackets(sent)            \n#                 sent = drop_punct(sent)\n#                 sent = normalize_accents(sent)            \n#                 for word in toker.tokenize(sent):\n#                     if word.isnumeric():\n#                         continue\n#                     inflected_word_counter.update({truecase(word, case_counts) : 1})                    \n    return  inflected_word_counter\n```\n\n\n```python\ncicero_inflected_words = get_word_counts(cicero_tess, tesserae=True)\n```\n\n\n```python\ntess_files = glob(os.path.expanduser('~/cltk_data/latin/text/latin_text_tesserae/texts/*.tess'))\ntess_wo_cicero = list( set(tess_files) - set(cicero_tess))\nlen(tess_files), len(tess_wo_cicero)\n```\n\n\n\n\n    (762, 640)\n\n\n\n\n```python\n# tesserae without cicero\n```\n\n\n```python\nfor file in tqdm(tess_wo_cicero, total=len(tess_wo_cicero)):\n    # get filename\n    with open(f'cicero.train.tesserae/{os.path.basename(file)}.txt', 'wt') as fout:\n        with open(file, 'rt') as fin:\n            text = fin.read()\n            text = swallow(text, ANY_ANGLE)\n            text = normalize_lat(text, drop_accents=True, drop_macrons=True, jv_replacement=True, ligature_replacement=True)\n            text = accept_editorial(text)\n            for sent in sent_toker.tokenize(text):\n                tokens = word_toker.tokenize(sent)\n                tokens = [truecase(token, case_counts) for token in tokens]\n                fout.write(f\"{' '.join(tokens)}\\n\")\n        fout.write(f\"\\n\\n\")\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 640/640 [02:16<00:00,  4.69it/s]\n\n\n\n```python\n# Aquinas \naquinas = glob(\"../data/aquinas/*.txt\")\nlen(aquinas)\n```\n\n\n\n\n    612\n\n\n\n\n```python\nauthor='aquinas'\nfor file in tqdm(aquinas, total=len(aquinas)):\n    with open(file, 'rt') as fin:\n        text = fin.read()\n        text = text.replace(\"-\\n\", \"\")\n        text = text.replace(\"\\n\", \" \")        \n        text = normalize_lat(text, drop_accents=True, drop_macrons=True, jv_replacement=True, ligature_replacement=True)\n        text = accept_editorial(text)\n        text = swallow_braces(text)\n        filename = os.path.basename (file)\n        with open(f\"cicero.train.aquinas/{filename}\", 'wt') as fout:                \n            for sent in sent_toker.tokenize(text):\n                tokens = word_toker.tokenize(sent)\n                tokens = [truecase(token, case_counts) for token in tokens]\n                fout.write(f\"{' '.join(tokens)}\\n\")\n            fout.write(f\"\\n\\n\")\n                \n#                 sent = swallow_square_brackets(sent)\n#                 sent = disappear_round_brackets(sent)\n#                 sent = swallow_obelized_words(sent)\n#                 sent = disappear_angle_brackets(sent)            \n#                 sentence = [truecase(word, case_counts)\n#                             for word in toker.tokenize(sent) \n#                             if not word.isnumeric()]\n#                 fout.write(f\"{' '.join(sentence)}\\n\")\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 612/612 [03:46<00:00,  2.70it/s]\n\n\n\n```python\n\n```\n\n\n```python\ntest_sentences =[' '.join(sent_map[tmp ]) for tmp in test_candidates]\nmasked_sentences = []\nmask_words = []\nmask_idxs = []\n\nfor tmp in test_candidates:\n    tokens = sent_map[tmp]\n    while True:\n        can_idx = random.randint(0, len(tokens)-1)\n        can_tok = tokens[can_idx]\n        if can_tok.isalpha():\n            break\n    mask_idxs.append(can_idx)\n    mask_words.append(can_tok)\n    tokens[can_idx] = '[MASK]'\n    masked_sentences.append(' '.join(tokens))\n\ndf = pd.DataFrame({\"sentence_idx\": test_candidates, \n                   \"test_sentences\": test_sentences,\n                  \"masked_sentences\": masked_sentences,\n                \"masked_words\": mask_words,\n                \"mask_idxs\": mask_idxs})\ndf.to_csv(f'cicero.test.sentences.{test_set_size}.wmask.csv', index=False)\ndf.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>sentence_idx</th>\n      <th>test_sentences</th>\n      <th>masked_sentences</th>\n      <th>masked_words</th>\n      <th>mask_idxs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>16983</td>\n      <td>uidendum est igitur , ut ea liberalitate utamu...</td>\n      <td>[MASK] est igitur , ut ea liberalitate utamur ...</td>\n      <td>uidendum</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>32813</td>\n      <td>aut , si omnes homines uelint , obscura esse p...</td>\n      <td>aut , si omnes homines [MASK] , obscura esse p...</td>\n      <td>uelint</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>19411</td>\n      <td>ualent pueri , studiose discunt , diligenter d...</td>\n      <td>ualent pueri , studiose discunt , diligenter d...</td>\n      <td>nos</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>25066</td>\n      <td>hoc enim identidem dicitis , non intellegere n...</td>\n      <td>hoc enim identidem dicitis , non intellegere n...</td>\n      <td>uoluptatem</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>28701</td>\n      <td>bene hercule narras ; nam istum doctum et sapi...</td>\n      <td>bene hercule narras ; nam istum [MASK] et sapi...</td>\n      <td>doctum</td>\n      <td>6</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf.sample(25)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>sentence_idx</th>\n      <th>test_sentences</th>\n      <th>masked_sentences</th>\n      <th>masked_words</th>\n      <th>mask_idxs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2243</th>\n      <td>467</td>\n      <td>id ego uolui Q. sed pluris est .</td>\n      <td>id ego uolui Q. sed pluris [MASK] .</td>\n      <td>est</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>1948</th>\n      <td>29031</td>\n      <td>est autem quid deceat oratori uidendum non in ...</td>\n      <td>est autem quid deceat oratori [MASK] non in se...</td>\n      <td>uidendum</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>279</th>\n      <td>31037</td>\n      <td>concedo ; forsitan aliquis aliquando eius modi...</td>\n      <td>concedo ; forsitan [MASK] aliquando eius modi ...</td>\n      <td>aliquis</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>1658</th>\n      <td>15051</td>\n      <td>si quid de his rebus dicere uellet , feci pote...</td>\n      <td>si [MASK] de his rebus dicere uellet , feci po...</td>\n      <td>quid</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>1480</th>\n      <td>41136</td>\n      <td>nunc miser quando tuas iam litteras accipiam ?</td>\n      <td>[MASK] miser quando tuas iam litteras accipiam ?</td>\n      <td>nunc</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>535</th>\n      <td>25667</td>\n      <td>non enim omnes eos contemnunt , de quibus male...</td>\n      <td>non [MASK] omnes eos contemnunt , de quibus ma...</td>\n      <td>enim</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>163</th>\n      <td>35671</td>\n      <td>itaque eam partem , quae ab exquisita quadam r...</td>\n      <td>itaque eam partem , quae [MASK] exquisita quad...</td>\n      <td>ab</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>1186</th>\n      <td>29347</td>\n      <td>quod ab eis uere quadam ex parte , non totum d...</td>\n      <td>quod ab eis uere [MASK] ex parte , non totum d...</td>\n      <td>quadam</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>2165</th>\n      <td>19799</td>\n      <td>fuit tamen retinendi ordinis causa facienda ia...</td>\n      <td>fuit tamen [MASK] ordinis causa facienda iactu...</td>\n      <td>retinendi</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>617</th>\n      <td>16102</td>\n      <td>uerum ita est uti dicis ; te deiectum debeo in...</td>\n      <td>uerum ita est uti dicis ; te deiectum debeo [M...</td>\n      <td>intellegere</td>\n      <td>9</td>\n    </tr>\n    <tr>\n      <th>1015</th>\n      <td>32168</td>\n      <td>an ille non uicerit , si quacumque condicione ...</td>\n      <td>an ille non [MASK] , si quacumque condicione i...</td>\n      <td>uicerit</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>652</th>\n      <td>22756</td>\n      <td>de libertate retinenda , qua certe nihil est d...</td>\n      <td>de [MASK] retinenda , qua certe nihil est dulc...</td>\n      <td>libertate</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>543</th>\n      <td>16223</td>\n      <td>ea fit plerumque per homines coactos armatos -...</td>\n      <td>ea fit plerumque per homines coactos armatos -...</td>\n      <td>si</td>\n      <td>9</td>\n    </tr>\n    <tr>\n      <th>1430</th>\n      <td>16861</td>\n      <td>ex quo intellegitur , quod uerum , simplex sin...</td>\n      <td>[MASK] quo intellegitur , quod uerum , simplex...</td>\n      <td>ex</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1628</th>\n      <td>31007</td>\n      <td>itaque hac una spe ad iudicium uenitur .</td>\n      <td>itaque [MASK] una spe ad iudicium uenitur .</td>\n      <td>hac</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>715</th>\n      <td>34272</td>\n      <td>sed uidebis ne is tum sit in Africa ut Caelius .</td>\n      <td>sed uidebis ne is tum sit in [MASK] ut Caelius .</td>\n      <td>Africa</td>\n      <td>7</td>\n    </tr>\n    <tr>\n      <th>760</th>\n      <td>28717</td>\n      <td>si uis , sane sint breuiora , leuiora qui poss...</td>\n      <td>si uis , sane sint breuiora , leuiora [MASK] p...</td>\n      <td>qui</td>\n      <td>8</td>\n    </tr>\n    <tr>\n      <th>2139</th>\n      <td>21631</td>\n      <td>atque utinam , patres conscripti , ciuibus omn...</td>\n      <td>atque [MASK] , patres conscripti , ciuibus omn...</td>\n      <td>utinam</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>978</th>\n      <td>17679</td>\n      <td>quod si etiam possis quiduis deferre ad alteru...</td>\n      <td>quod si etiam possis quiduis [MASK] ad alterum...</td>\n      <td>deferre</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>2252</th>\n      <td>28830</td>\n      <td>cui quaesito autem opus sit , quis umquam hunc...</td>\n      <td>cui quaesito autem opus sit , [MASK] umquam hu...</td>\n      <td>quis</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>1477</th>\n      <td>39364</td>\n      <td>sin aliter fuerit , quod di omen auertant !</td>\n      <td>sin aliter fuerit , quod [MASK] omen auertant !</td>\n      <td>di</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>2444</th>\n      <td>39242</td>\n      <td>nam Pansa fugerat uulneribus acceptis quae fer...</td>\n      <td>nam Pansa fugerat uulneribus acceptis quae [MA...</td>\n      <td>ferre</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>726</th>\n      <td>30490</td>\n      <td>nemo est istorum qui otium non timeat .</td>\n      <td>nemo est istorum qui [MASK] non timeat .</td>\n      <td>otium</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>235</th>\n      <td>24</td>\n      <td>quam nihil praetermittis in consilio dando ; q...</td>\n      <td>quam nihil praetermittis in consilio dando ; [...</td>\n      <td>quam</td>\n      <td>7</td>\n    </tr>\n    <tr>\n      <th>402</th>\n      <td>40209</td>\n      <td>ecqui pudor est , ecquae religio , Uerres , ec...</td>\n      <td>[MASK] pudor est , ecquae religio , Uerres , e...</td>\n      <td>ecqui</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n# this filtered out too many\n\nfor file in tqdm(tess_wo_cicero, total=len(tess_wo_cicero)):\n    candidate_counter =  get_word_counts([file], tesserae=True)\n    author_words = set(candidate_counter.keys())\n    cicero_words = set(cicero_inflected_words.keys())\n    common = author_words & cicero_words\n    author_uniq = author_words - common \n    P_inflected_unigram_unk = len(author_uniq) / sum(candidate_counter.values()) \n    if P_inflected_unigram_unk <= 0.074:\n        # get filename\n        with open(f'cicero.train.tesserae/{os.path.basename(file)}.txt', 'wt') as fout:\n            with open(file, 'rt') as fin:\n                text = fin.read()\n                text = swallow(text, ANY_ANGLE)\n                text = normalize_lat(text, drop_accents=True, drop_macrons=True, jv_replacement=True, ligature_replacement=True)\n                text = accept_editorial(text)\n                for sent in sent_toker.tokenize(text):\n                    tokens = word_toker.tokenize(sent)\n                    tokens = [truecase(token, case_counts) for token in tokens]\n                    fout.write(f\"{' '.join(tokens)}\\n\")\n            fout.write(f\"\\n\\n\")\n    else: \n        print(f\"too dissimilar {file}\")\n```\n\n      0%|          | 1/640 [00:00<01:27,  7.29it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vitruvius.de_architectura.part.7.tess\n\n\n      0%|          | 3/640 [00:00<01:43,  6.18it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ammianus.rerum_gestarum.part.29.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.amores.part.1.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/augustine.epistulae_selections.part.2.11-20.tess\n\n\n      1%|          | 6/640 [00:01<01:56,  5.44it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/scriptores_historiae_augustae.historia_augusta.part.2.books_6-10.tess\n\n\n      1%|\u258f         | 8/640 [00:01<02:25,  4.34it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.1.genesis.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/lucan.bellum_civile.part.4.tess\n\n\n      2%|\u258f         | 10/640 [00:01<01:59,  5.28it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.epigrammata_ausonii_de_diversis_rebus.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/prudentius.hamartigenia.tess\n\n\n      2%|\u258f         | 13/640 [00:02<01:04,  9.79it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.epitaphia_heroum_qui_bello_troico_interfuerunt.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tacitus.annales.part.5.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.59.1_thessalonians.tess\n\n\n      2%|\u258f         | 15/640 [00:02<01:12,  8.59it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.7.judges.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/quintus_smyrnaeus.fall_of_troy.part.11.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vergil.aeneid.part.8.tess\n\n\n      3%|\u258e         | 19/640 [00:02<01:08,  9.05it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/silius_italicus.punica.part.17.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/boethius.de_fide_catholica.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/macrobius.saturnalia.part.2.tess\n\n\n      3%|\u258e         | 21/640 [00:02<01:03,  9.71it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/suetonius.de_vita_caesarum.part.8.otho.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/apuleius.metamorphoses.part.11.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/lucan.bellum_civile.part.2.tess\n\n\n      4%|\u258d         | 24/640 [00:03<01:38,  6.28it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.75.2_esdras.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/horace.satires.part.2.tess\n\n\n      4%|\u258d         | 26/640 [00:03<01:24,  7.27it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.de_herediolo.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ammianus.rerum_gestarum.part.21.tess\n\n\n      4%|\u258d         | 28/640 [00:04<02:31,  4.03it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/pliny_the_elder.naturalis_historia.part.3.books_11-15.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/statius.silvae.part.5.tess\n\n\n      5%|\u258d         | 31/640 [00:05<01:48,  5.63it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ammianus.rerum_gestarum.part.26.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.73a.epistle_of_paul_to_the_laodicians.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vitruvius.de_architectura.part.2.tess\n\n\n      5%|\u258c         | 33/640 [00:06<02:29,  4.05it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vergil.aeneid.part.10.tess\n\n\n      5%|\u258c         | 35/640 [00:07<03:59,  2.53it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/claudian.de_bello_gothico.tess\n\n\n      6%|\u258c         | 38/640 [00:08<03:08,  3.19it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/curtius_rufus.historiae_alexandri_magni.part.5.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/apuleius.metamorphoses.part.9.tess\n\n\n      6%|\u258b         | 40/640 [00:08<02:14,  4.46it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/juvencus.historia_evangelica.part.1.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/juvencus.historia_evangelica.part.4.tess\n\n\n      7%|\u258b         | 42/640 [00:09<03:22,  2.95it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/curtius_rufus.historiae_alexandri_magni.part.4.tess\n\n\n      7%|\u258b         | 43/640 [00:09<03:05,  3.23it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/macrobius.saturnalia.part.3.tess\n\n\n      7%|\u258b         | 46/640 [00:10<02:11,  4.53it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/bede.historiam_ecclesiasticam_gentis_anglorum.part.5.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.technopaegnion.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ennius.annales.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.36.obadiah.tess\n\n\n      8%|\u258a         | 48/640 [00:10<01:54,  5.18it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.epistularum.tess\n\n\n      8%|\u258a         | 49/640 [00:11<02:50,  3.46it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.21.psalms.tess\n\n\n      8%|\u258a         | 51/640 [00:11<02:22,  4.15it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/pliny_the_younger.letters.part.3.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/persius.satires.tess\n\n\n      8%|\u258a         | 52/640 [00:11<02:40,  3.67it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca_the_elder.controversiae.part.2.tess\n\n\n      9%|\u258a         | 55/640 [00:12<02:25,  4.01it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/boethius.consolatio_philosophiae.part.4.tess\n\n\n      9%|\u2589         | 56/640 [00:12<02:15,  4.30it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/plautus.epidicus.tess\n\n\n      9%|\u2589         | 58/640 [00:13<02:03,  4.71it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/plautus.asinaria.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.fasti.part.2.tess\n\n\n      9%|\u2589         | 60/640 [00:13<01:37,  5.93it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vergil.georgics.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.metamorphoses.part.15.tess\n\n\n     10%|\u2589         | 63/640 [00:13<01:04,  8.97it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tacitus.annales.part.16.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/claudian.de_raptu_proserpinae.part.1.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/dracontius.satisfactio.tess\n\n\n     10%|\u2588         | 65/640 [00:14<01:26,  6.63it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.14.2_chronicles.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/corippus.johannis.part.5.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.libri_de_fastis_conclusio.tess\n\n\n     11%|\u2588         | 69/640 [00:14<01:01,  9.35it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca.de_constantia.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/dracontius.romulea.part.4.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.25.wisdom.tess\n\n\n     11%|\u2588         | 71/640 [00:14<01:05,  8.72it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/gellius.attic_nights.part.12.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.metamorphoses.part.11.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/claudian.in_consulatum_olybrii_et_probini.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.griphus_ternarii_numeri.tess\n\n\n     12%|\u2588\u258f        | 74/640 [00:15<00:58,  9.61it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca.de_consolatione_ad_marciam.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tacitus.annales.part.6.tess\n\n\n     12%|\u2588\u258f        | 76/640 [00:15<00:58,  9.59it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.40.habbakuk.tess\n\n\n     12%|\u2588\u258f        | 78/640 [00:16<02:22,  3.93it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/pliny_the_elder.naturalis_historia.part.4.books_16-20.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/manilius.astronomicon.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.61.1_timothy.tess\n\n\n     12%|\u2588\u258e        | 80/640 [00:16<01:53,  4.94it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/silius_italicus.punica.part.6.tess\n\n\n     13%|\u2588\u258e        | 81/640 [00:16<01:57,  4.74it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tacitus.annales.part.4.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/quintus_smyrnaeus.fall_of_troy.part.8.tess\n\n\n     13%|\u2588\u258e        | 84/640 [00:17<01:46,  5.24it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/aurelius_victor.epitome_de_caesaribus.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/valerius_flaccus.argonautica.part.4.tess\n\n\n     13%|\u2588\u258e        | 86/640 [00:17<01:27,  6.31it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/claudian.in_rufinum.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/silius_italicus.punica.part.9.tess\n\n\n     14%|\u2588\u258d        | 88/640 [00:18<01:41,  5.43it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/columella.de_re_rustica.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/pliny_the_younger.letters.part.6.tess\n\n\n     14%|\u2588\u258d        | 91/640 [00:18<01:10,  7.84it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/statius.thebaid.part.12.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.55.galatians.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/corippus.johannis.part.7.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/priscian.carmen_in_laudem_Anastasii_imperatoris.part.1.tess\n\n\n     15%|\u2588\u258d        | 93/640 [00:18<01:08,  7.98it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.46.2_maccabees.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/dracontius.romulea.part.1.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.56.ephesians.tess\n\n\n     15%|\u2588\u258c        | 96/640 [00:18<00:56,  9.56it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/macrobius.saturnalia.part.6.tess\n\n\n     15%|\u2588\u258c        | 97/640 [00:19<01:06,  8.18it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/plautus.stichus.tess\n\n\n     15%|\u2588\u258c        | 99/640 [00:19<01:25,  6.30it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/plautus.rudens.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/boethius.consolatio_philosophiae.part.2.tess\n\n\n     16%|\u2588\u258c        | 101/640 [00:20<01:40,  5.36it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tacitus.annales.part.1.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.74.1_esdras.tess\n\n\n     16%|\u2588\u258c        | 103/640 [00:20<01:15,  7.10it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.44.malachi.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.metamorphoses.part.3.tess\n\n\n     16%|\u2588\u258b        | 105/640 [00:20<01:28,  6.05it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.47.matthew.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/martial.epigrams.part.11.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/claudian.epithalamium_de_nuptiis_honorii_augusti.tess\n\n\n     17%|\u2588\u258b        | 109/640 [00:21<01:06,  7.93it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/augustine.epistulae_selections.part.6.51-62.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/gellius.attic_nights.part.8.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/statius.thebaid.part.4.tess\n\n\n     18%|\u2588\u258a        | 112/640 [00:21<01:12,  7.30it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/macrobius.saturnalia.part.7.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.41.zephoniah.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/silius_italicus.punica.part.11.tess\n\n\n     18%|\u2588\u258a        | 113/640 [00:21<01:09,  7.56it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/manilius.astronomicon.part.3.tess\n\n\n     18%|\u2588\u258a        | 115/640 [00:25<06:28,  1.35it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.22.proverbs.tess\n\n\n     18%|\u2588\u258a        | 116/640 [00:25<05:19,  1.64it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ammianus.rerum_gestarum.part.31.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/martial.epigrams.part.4.tess\n\n\n     18%|\u2588\u258a        | 118/640 [00:25<03:29,  2.49it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tacitus.annales.part.13.tess\n\n\n     19%|\u2588\u2589        | 122/640 [00:27<03:04,  2.82it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/gellius.attic_nights.part.1.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vergil.aeneid.part.12.tess\n\n\n     19%|\u2588\u2589        | 124/640 [00:28<03:16,  2.62it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.11.1_kings.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.epicedion_in_patrem.tess\n\n\n     20%|\u2588\u2589        | 126/640 [00:28<02:20,  3.67it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.tristia.part.3.tess\n\n\n     20%|\u2588\u2589        | 127/640 [00:29<03:51,  2.22it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/juvenal.satires.tess\n\n\n     20%|\u2588\u2588        | 128/640 [00:29<03:39,  2.33it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/priscian.perihegesis.tess\n\n\n     20%|\u2588\u2588        | 129/640 [00:30<03:35,  2.38it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.4.numbers.tess\n\n\n     20%|\u2588\u2588        | 130/640 [00:30<03:05,  2.74it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tacitus.annales.part.3.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/quintus_smyrnaeus.fall_of_troy.part.5.tess\n\n\n     21%|\u2588\u2588        | 133/640 [00:30<01:51,  4.54it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.ex_ponto.part.4.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/rutilius.de_reditu.tess\n\n\n     21%|\u2588\u2588        | 134/640 [00:31<02:17,  3.69it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/bede.historiam_ecclesiasticam_gentis_anglorum.part.4.tess\n\n\n     21%|\u2588\u2588\u258f       | 137/640 [00:32<02:33,  3.29it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ammianus.rerum_gestarum.part.16.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.fasti.part.4.tess\n\n\n     22%|\u2588\u2588\u258f       | 139/640 [00:32<01:48,  4.62it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/prudentius.psychomachia.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vitruvius.de_architectura.part.3.tess\n\n\n     22%|\u2588\u2588\u258f       | 142/640 [00:33<01:27,  5.71it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.ars_amatoria.part.1.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vitruvius.de_architectura.part.8.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.35.amos.tess\n\n\n     23%|\u2588\u2588\u258e       | 145/640 [00:34<02:03,  4.01it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/glass.washingtonii_vita.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca.de_vita_beata.tess\n\n\n     23%|\u2588\u2588\u258e       | 147/640 [00:34<01:44,  4.73it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/claudian.in_eutropium.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tacitus.annales.part.12.tess\n\n\n     23%|\u2588\u2588\u258e       | 148/640 [00:34<02:20,  3.50it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.31.ezekiel.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/priscian.carmen_in_laudem_Anastasii_imperatoris.tess\n\n\n     24%|\u2588\u2588\u258d       | 152/640 [00:35<01:53,  4.29it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/statius.thebaid.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/gellius.attic_nights.part.6.tess\n\n\n     24%|\u2588\u2588\u258d       | 153/640 [00:35<01:39,  4.92it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/statius.thebaid.part.3.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/claudian.de_consulatu_stilichonis.part.1.tess\n\n\n     24%|\u2588\u2588\u258d       | 155/640 [00:36<01:24,  5.75it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca.phaedra.tess\n\n\n     25%|\u2588\u2588\u258d       | 158/640 [00:36<01:16,  6.32it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.2.exodus.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/corippus.johannis.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/gellius.attic_nights.part.pr.tess\n\n\n     25%|\u2588\u2588\u258d       | 159/640 [00:37<01:33,  5.15it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ennodius.opera.tess\n\n\n     25%|\u2588\u2588\u258c       | 161/640 [00:37<01:31,  5.26it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/gellius.attic_nights.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca.medea.tess\n\n\n     25%|\u2588\u2588\u258c       | 163/640 [00:37<01:09,  6.91it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/valerius_maximus.facta_et_dicta_memorabilia.part.9.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/boethius.consolatio_philosophiae.part.1.tess\n\n\n     26%|\u2588\u2588\u258c       | 165/640 [00:37<01:06,  7.12it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/columella.de_re_rustica.part.9.tess\n\n\n     26%|\u2588\u2588\u258c       | 167/640 [00:38<01:18,  6.06it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/silius_italicus.punica.part.16.tess\n\n\n     26%|\u2588\u2588\u258b       | 169/640 [00:39<01:51,  4.23it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/plautus.cistellaria.tess\n\n\n     27%|\u2588\u2588\u258b       | 172/640 [00:39<01:29,  5.22it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/prudentius.dittochaeon.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/quintus_smyrnaeus.fall_of_troy.part.12.tess\n\n\n     27%|\u2588\u2588\u258b       | 174/640 [00:39<01:18,  5.90it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/augustine.epistulae_selections.part.4.31-40.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/corippus.johannis.part.1.tess\n\n\n     28%|\u2588\u2588\u258a       | 177/640 [00:40<01:59,  3.86it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/manilius.astronomicon.part.1.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/macrobius.saturnalia.part.4.tess\n\n\n     28%|\u2588\u2588\u258a       | 180/640 [00:41<01:28,  5.21it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/statius.thebaid.part.5.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/gellius.attic_nights.part.17.tess\n\n\n     28%|\u2588\u2588\u258a       | 182/640 [00:41<01:44,  4.39it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca_the_elder.suasoriae.tess\n\n\n     29%|\u2588\u2588\u258a       | 183/640 [00:42<02:08,  3.56it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/quintilian.institutio_oratoria.part.1.tess\n\n\n     29%|\u2588\u2588\u2589       | 186/640 [00:44<04:06,  1.84it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/pliny_the_elder.naturalis_historia.part.5.books_21-25.tess\n\n\n     29%|\u2588\u2588\u2589       | 187/640 [00:44<03:31,  2.14it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/curtius_rufus.historiae_alexandri_magni.part.8.tess\n\n\n     29%|\u2588\u2588\u2589       | 188/640 [00:45<03:41,  2.04it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/pliny_the_elder.naturalis_historia.part.1.books_1-5.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.66.james.tess\n\n\n     30%|\u2588\u2588\u2589       | 190/640 [00:45<03:19,  2.26it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/scriptores_historiae_augustae.historia_augusta.part.4.books_16-21.tess\n\n\n     30%|\u2588\u2588\u2588       | 192/640 [00:46<02:42,  2.76it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/columella.de_re_rustica.part.1.tess\n\n\n     30%|\u2588\u2588\u2588       | 194/640 [00:47<02:17,  3.24it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tibullus.elegies.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca.de_brevitate_vitae.tess\n\n\n     31%|\u2588\u2588\u2588       | 196/640 [00:47<01:45,  4.21it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vergil.aeneid.part.11.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/pliny_the_younger.letters.part.7.tess\n\n\n     31%|\u2588\u2588\u2588       | 199/640 [00:47<01:04,  6.86it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca.troades.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/claudian.de_consulatu_stilichonis.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.medicamina_faciei_femineae.tess\n\n\n     32%|\u2588\u2588\u2588\u258f      | 202/640 [00:47<00:52,  8.42it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/lucan.bellum_civile.part.6.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/suetonius.de_vita_caesarum.part.9.vitellius.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.tristia.part.1.tess\n\n\n     32%|\u2588\u2588\u2588\u258f      | 203/640 [00:48<00:55,  7.85it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vitruvius.de_architectura.part.10.tess\n\n\n     32%|\u2588\u2588\u2588\u258f      | 204/640 [00:48<01:11,  6.11it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/paulus_diaconus.carmina.tess\n\n\n     32%|\u2588\u2588\u2588\u258f      | 206/640 [00:48<01:21,  5.36it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/valerius_maximus.facta_et_dicta_memorabilia.part.4.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/lucan.bellum_civile.part.10.tess\n\n\n     33%|\u2588\u2588\u2588\u258e      | 211/640 [00:49<00:52,  8.15it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.70.2_john.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/dracontius.romulea.part.7.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/gellius.attic_nights.part.14.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.57.philippians.tess\n\n\n     33%|\u2588\u2588\u2588\u258e      | 213/640 [00:50<01:54,  3.72it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/pliny_the_elder.naturalis_historia.part.2.books_6-10.tess\n\n\n     33%|\u2588\u2588\u2588\u258e      | 214/640 [00:50<01:56,  3.65it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.12.1_chronicles.tess\n\n\n     34%|\u2588\u2588\u2588\u258d      | 217/640 [00:51<01:24,  5.00it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tacitus.historiae.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/prudentius.epilogus.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/silius_italicus.punica.part.8.tess\n\n\n     34%|\u2588\u2588\u2588\u258d      | 220/640 [00:52<01:36,  4.35it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/apuleius.metamorphoses.part.8.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/silius_italicus.punica.part.12.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.71.3_john.tess\n\n\n     35%|\u2588\u2588\u2588\u258d      | 223/640 [00:52<01:08,  6.04it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/valerius_maximus.facta_et_dicta_memorabilia.part.5.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/gellius.attic_nights.part.15.tess\n\n\n     35%|\u2588\u2588\u2588\u258c      | 224/640 [00:52<01:31,  4.53it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/plautus.poenulus.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/macrobius.fragment.tess\n\n\n     35%|\u2588\u2588\u2588\u258c      | 226/640 [00:53<01:12,  5.74it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/servius_honoratus.in_virgilii_georgicon_libros_commentarius.part.4.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/valerius_maximus.facta_et_dicta_memorabilia.part.7.tess\n\n\n     36%|\u2588\u2588\u2588\u258c      | 229/640 [00:53<01:23,  4.94it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.27.isaiah.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/juvencus.historia_evangelica.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/quintus_smyrnaeus.fall_of_troy.part.4.tess\n\n\n     36%|\u2588\u2588\u2588\u258b      | 233/640 [00:54<01:30,  4.51it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.68.2_peter.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vergil.aeneid.part.6.tess\n\n\n     37%|\u2588\u2588\u2588\u258b      | 234/640 [00:55<01:31,  4.44it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/lucretius.de_rerum_natura.part.4.tess\n\n\n     37%|\u2588\u2588\u2588\u258b      | 237/640 [00:55<01:07,  5.94it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/gellius.attic_nights.part.18.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/anonymous.laudes_domini.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/statius.thebaid.part.8.tess\n\n\n     37%|\u2588\u2588\u2588\u258b      | 238/640 [00:55<01:06,  6.06it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/valerius_flaccus.argonautica.part.1.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.67.1_peter.tess\n\n\n     38%|\u2588\u2588\u2588\u258a      | 242/640 [00:56<01:13,  5.44it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/polignac.imitatio.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/lucan.bellum_civile.part.7.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.62.2_timothy.tess\n\n\n     38%|\u2588\u2588\u2588\u258a      | 245/640 [00:56<00:48,  8.15it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.30.baruch.tess\n\n\n     38%|\u2588\u2588\u2588\u258a      | 246/640 [00:56<00:54,  7.28it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ammianus.rerum_gestarum.part.28.tess\n\n\n     39%|\u2588\u2588\u2588\u2589      | 248/640 [00:57<01:04,  6.04it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/celsus.de_medicina.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.fasti.part.6.tess\n\n\n     39%|\u2588\u2588\u2588\u2589      | 249/640 [00:57<01:09,  5.62it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/lucretius.de_rerum_natura.part.3.tess\n\n\n     39%|\u2588\u2588\u2588\u2589      | 250/640 [01:22<43:27,  6.69s/it]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/suetonius.de_vita_caesarum.part.11.titus.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.24.song_of_songs.tess\n\n\n     40%|\u2588\u2588\u2588\u2589      | 254/640 [01:22<16:46,  2.61s/it]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/marcus_mincuius_felix.octavius.tess\n\n\n     40%|\u2588\u2588\u2588\u2588      | 256/640 [01:25<12:24,  1.94s/it]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vergil.aeneid.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.54.2_corinthians.tess\n\n\n     40%|\u2588\u2588\u2588\u2588      | 258/640 [01:25<08:02,  1.26s/it]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/dracontius.romulea.part.3.tess\n\n\n     41%|\u2588\u2588\u2588\u2588      | 260/640 [01:26<05:44,  1.10it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/martial.epigrams.part.7.tess\n\n\n     41%|\u2588\u2588\u2588\u2588      | 262/640 [01:26<04:05,  1.54it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/gellius.attic_nights.part.13.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.38.micah.tess\n\n\n     42%|\u2588\u2588\u2588\u2588\u258f     | 268/640 [01:28<01:57,  3.17it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/manilius.astronomicon.part.4.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca_the_elder.fragmenta.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/lucan.bellum_civile.part.1.tess\n\n\n     42%|\u2588\u2588\u2588\u2588\u258f     | 269/640 [01:28<01:41,  3.67it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/silius_italicus.punica.part.10.tess\n\n\n     42%|\u2588\u2588\u2588\u2588\u258f     | 270/640 [01:28<01:42,  3.61it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tacitus.historiae.part.3.tess\n\n\n     42%|\u2588\u2588\u2588\u2588\u258f     | 271/640 [01:29<01:45,  3.49it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/servius_honoratus.in_virgilii_georgicon_libros_commentarius.part.2.tess\n\n\n     43%|\u2588\u2588\u2588\u2588\u258e     | 274/640 [01:30<01:45,  3.46it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/apuleius.metamorphoses.part.6.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ammianus.rerum_gestarum.part.19.tess\n\n\n     43%|\u2588\u2588\u2588\u2588\u258e     | 275/640 [01:30<01:28,  4.13it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/statius.thebaid.part.11.tess\n\n\n     43%|\u2588\u2588\u2588\u2588\u258e     | 278/640 [01:30<01:02,  5.76it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/curtius_rufus.historiae_alexandri_magni.part.6.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/apuleius.metamorphoses.part.5.tess\n\n\n     44%|\u2588\u2588\u2588\u2588\u258d     | 281/640 [01:31<00:57,  6.25it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/celsus.de_medicina.part.7.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/quintus_smyrnaeus.fall_of_troy.part.3.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.gratiarum_actio.tess\n\n\n     44%|\u2588\u2588\u2588\u2588\u258d     | 282/640 [01:31<00:52,  6.81it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/suetonius.de_vita_caesarum.part.12.domitian.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/dracontius.romulea.part.5.tess\n\n\n     45%|\u2588\u2588\u2588\u2588\u258d     | 285/640 [01:31<00:47,  7.54it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/apuleius.florida.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/suetonius.de_vita_caesarum.part.6.nero.tess\n\n\n     45%|\u2588\u2588\u2588\u2588\u258d     | 286/640 [01:31<00:47,  7.41it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/statius.thebaid.part.6.tess\n\n\n     45%|\u2588\u2588\u2588\u2588\u258c     | 288/640 [01:32<01:17,  4.53it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/plautus.pseudolus.tess\n\n\n     45%|\u2588\u2588\u2588\u2588\u258c     | 289/640 [01:32<01:18,  4.48it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/suetonius.de_vita_caesarum.part.3.tiberius.tess\n\n\n     46%|\u2588\u2588\u2588\u2588\u258c     | 295/640 [01:35<02:04,  2.77it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/lucretius.de_rerum_natura.part.6.tess\n\n\n     46%|\u2588\u2588\u2588\u2588\u258b     | 297/640 [01:36<01:39,  3.45it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/statius.silvae.part.1.tess\n\n\n     47%|\u2588\u2588\u2588\u2588\u258b     | 299/640 [01:36<01:45,  3.23it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.10.2_samuel.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/quintus_smyrnaeus.fall_of_troy.part.14.tess\n\n\n     47%|\u2588\u2588\u2588\u2588\u258b     | 303/640 [01:37<01:15,  4.44it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.33.hosea.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/claudian.panegyricus_de_quarto_consulatu_honorii_augusti.tess\n\n\n     48%|\u2588\u2588\u2588\u2588\u258a     | 307/640 [01:38<00:47,  6.96it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ammianus.rerum_gestarum.part.18.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.19.esther.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/boethius.consolatio_philosophiae.part.5.tess\n\n\n     48%|\u2588\u2588\u2588\u2588\u258a     | 308/640 [01:38<00:52,  6.30it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/augustine.epistulae_selections.part.1.1-10.tess\n\n\n     48%|\u2588\u2588\u2588\u2588\u258a     | 310/640 [01:38<01:01,  5.33it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tacitus.annales.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.metamorphoses.part.13.tess\n\n\n     49%|\u2588\u2588\u2588\u2588\u2589     | 312/640 [01:39<01:00,  5.44it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/pliny_the_younger.letters.part.9.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/gellius.attic_nights.part.4.tess\n\n\n     49%|\u2588\u2588\u2588\u2588\u2589     | 315/640 [01:39<01:08,  4.78it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.21a.old_latin_psalms.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.de_xii_caesaribus.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ammianus.rerum_gestarum.part.15.tess\n\n\n     50%|\u2588\u2588\u2588\u2588\u2589     | 317/640 [01:40<01:01,  5.23it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/lucretius.de_rerum_natura.part.5.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.tristia.part.5.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/martial.epigrams.part.6.tess\n\n\n     50%|\u2588\u2588\u2588\u2588\u2589     | 319/640 [01:40<00:46,  6.89it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/martial.epigrams.part.14.tess\n\n\n     50%|\u2588\u2588\u2588\u2588\u2588     | 320/640 [01:40<01:02,  5.10it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/columella.de_re_rustica.part.6.tess\n\n\n     51%|\u2588\u2588\u2588\u2588\u2588     | 324/640 [01:41<00:57,  5.48it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca.de_consolatione_ad_helviam.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.ars_amatoria.part.3.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.29.lamentations.tess\n\n\n     51%|\u2588\u2588\u2588\u2588\u2588\u258f    | 328/640 [01:41<00:41,  7.59it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.17.tobias.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.58.colossians.tess\n\n\n     51%|\u2588\u2588\u2588\u2588\u2588\u258f    | 329/640 [01:42<01:15,  4.11it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/pliny_the_elder.naturalis_historia.part.6.books_26-30.tess\n\n\n     52%|\u2588\u2588\u2588\u2588\u2588\u258f    | 330/640 [01:42<01:18,  3.97it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/bede.historiam_ecclesiasticam_gentis_anglorum.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.mosella.tess\n\n\n     52%|\u2588\u2588\u2588\u2588\u2588\u258f    | 332/640 [01:43<01:14,  4.11it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/bede.historiam_ecclesiasticam_gentis_anglorum.part.3.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/suetonius.de_vita_caesarum.part.10.vespasian.tess\n\n\n     52%|\u2588\u2588\u2588\u2588\u2588\u258f    | 334/640 [01:43<00:58,  5.21it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/suetonius.de_vita_caesarum.part.5.claudius.tess\n\n\n     52%|\u2588\u2588\u2588\u2588\u2588\u258f    | 335/640 [01:43<00:59,  5.13it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/plautus.aulularia.tess\n\n\n     53%|\u2588\u2588\u2588\u2588\u2588\u258e    | 337/640 [01:56<12:07,  2.40s/it]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/plautus.curculio.tess\n\n\n     53%|\u2588\u2588\u2588\u2588\u2588\u258e    | 340/640 [01:57<05:26,  1.09s/it]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/horace.epistles.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/valerius_maximus.facta_et_dicta_memorabilia.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/quintus_smyrnaeus.fall_of_troy.part.10.tess\n\n\n     53%|\u2588\u2588\u2588\u2588\u2588\u258e    | 341/640 [01:57<04:26,  1.12it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/catullus.carmina.tess\n\n\n     54%|\u2588\u2588\u2588\u2588\u2588\u258d    | 344/640 [02:07<11:07,  2.25s/it]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.amores.part.3.tess\n\n\n     54%|\u2588\u2588\u2588\u2588\u2588\u258d    | 347/640 [02:08<04:46,  1.02it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ammianus.rerum_gestarum.part.22.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.tristia.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/martial.epigrams.part.10.tess\n\n\n     55%|\u2588\u2588\u2588\u2588\u2588\u258d    | 349/640 [02:08<03:01,  1.60it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.53.1_corinthians.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/curtius_rufus.historiae_alexandri_magni.part.9.tess\n\n\n     55%|\u2588\u2588\u2588\u2588\u2588\u258d    | 351/640 [02:08<01:54,  2.53it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vergil.aeneid.part.5.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.fasti.part.5.tess\n\n\n     55%|\u2588\u2588\u2588\u2588\u2588\u258c    | 352/640 [02:09<01:43,  2.77it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.3.leviticus.tess\n\n\n     55%|\u2588\u2588\u2588\u2588\u2588\u258c    | 353/640 [02:09<01:48,  2.65it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.heroides.part.1.1-15.tess\n\n\n     56%|\u2588\u2588\u2588\u2588\u2588\u258c    | 356/640 [02:10<01:22,  3.46it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/columella.de_re_rustica.part.5.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca.phoenissae.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/horace.odes.part.2.tess\n\n\n     56%|\u2588\u2588\u2588\u2588\u2588\u258c    | 359/640 [02:11<01:15,  3.70it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca_the_elder.controversiae.part.10.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/claudian.panegyricus_dictus_manlio_theodoro_consuli.tess\n\n\n     56%|\u2588\u2588\u2588\u2588\u2588\u258b    | 361/640 [02:11<01:00,  4.63it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.6.joshua.tess\n\n\n     57%|\u2588\u2588\u2588\u2588\u2588\u258b    | 364/640 [02:12<00:54,  5.06it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ammianus.rerum_gestarum.part.25.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ammianus.rerum_gestarum.part.24.tess\n\n\n     57%|\u2588\u2588\u2588\u2588\u2588\u258b    | 366/640 [02:12<00:47,  5.74it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.metamorphoses.part.9.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ammianus.rerum_gestarum.part.30.tess\n\n\n     57%|\u2588\u2588\u2588\u2588\u2588\u258b    | 367/640 [02:12<00:45,  5.96it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca.agamemnon.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vergil.georgics.part.1.tess\n\n\n     58%|\u2588\u2588\u2588\u2588\u2588\u258a    | 370/640 [02:13<00:59,  4.50it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/juvencus.historia_evangelica.part.3.tess\n\n\n     58%|\u2588\u2588\u2588\u2588\u2588\u258a    | 373/640 [02:26<08:12,  1.84s/it]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/plautus.persa.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/statius.thebaid.part.7.tess\n\n\n     59%|\u2588\u2588\u2588\u2588\u2588\u258a    | 375/640 [02:26<04:26,  1.00s/it]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/pliny_the_younger.letters.part.8.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca.oedipus.tess\n\n\n     59%|\u2588\u2588\u2588\u2588\u2588\u2589    | 379/640 [02:27<01:46,  2.46it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.20.job.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.60.2_thessalonians.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/silius_italicus.punica.part.13.tess\n\n\n     60%|\u2588\u2588\u2588\u2588\u2588\u2589    | 381/640 [02:27<01:14,  3.47it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/lucan.bellum_civile.part.5.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/gellius.attic_nights.part.19.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/claudian.panegyricus_de_tertio_consulatu_honorii_augusti.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.34.joel.tess\n\n\n     61%|\u2588\u2588\u2588\u2588\u2588\u2588    | 388/640 [02:28<00:34,  7.35it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.metamorphoses.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.cento_nuptialis.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.cupido_cruciatus.tess\n\n\n     61%|\u2588\u2588\u2588\u2588\u2588\u2588    | 390/640 [02:28<00:33,  7.43it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/dracontius.de_laudibus_dei.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.metamorphoses.part.1.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/prudentius.contra_symmachum.part.1.tess\n\n\n     62%|\u2588\u2588\u2588\u2588\u2588\u2588\u258f   | 394/640 [02:30<01:06,  3.71it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tertullian.apologeticum.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/lucan.bellum_civile.part.8.tess\n\n\n     62%|\u2588\u2588\u2588\u2588\u2588\u2588\u258f   | 395/640 [02:30<01:01,  3.98it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ammianus.rerum_gestarum.part.17.tess\n\n\n     62%|\u2588\u2588\u2588\u2588\u2588\u2588\u258f   | 399/640 [02:31<00:47,  5.11it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tacitus.agricola.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.de_bissula.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.metamorphoses.part.8.tess\n\n\n     63%|\u2588\u2588\u2588\u2588\u2588\u2588\u258e   | 402/640 [02:31<00:41,  5.70it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.43.zechariah.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/valerius_flaccus.argonautica.part.5.tess\n\n\n     63%|\u2588\u2588\u2588\u2588\u2588\u2588\u258e   | 403/640 [02:32<00:39,  5.99it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/silius_italicus.punica.part.15.tess\n\n\n     63%|\u2588\u2588\u2588\u2588\u2588\u2588\u258e   | 405/640 [02:32<00:38,  6.11it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tacitus.annales.part.15.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vergil.aeneid.part.4.tess\n\n\n     64%|\u2588\u2588\u2588\u2588\u2588\u2588\u258e   | 407/640 [02:33<00:51,  4.49it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.tristia.part.4.tess\n\n\n     64%|\u2588\u2588\u2588\u2588\u2588\u2588\u258d   | 410/640 [02:33<00:46,  4.97it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca.ad_lucilium_epistulae_morales.part.6.51-60.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.18.judith.tess\n\n\n     65%|\u2588\u2588\u2588\u2588\u2588\u2588\u258d   | 414/640 [02:34<00:51,  4.41it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/florus.epitome_bellorum_omnium_annorum.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/claudian.de_raptu_proserpinae.part.3.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.23.ecclesiastes.tess\n\n\n     65%|\u2588\u2588\u2588\u2588\u2588\u2588\u258c   | 416/640 [02:35<00:43,  5.09it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/prudentius.apotheosis.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.fasti.part.1.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/aristotle.economics_book_3.tess\n\n\n     66%|\u2588\u2588\u2588\u2588\u2588\u2588\u258c   | 420/640 [02:35<00:32,  6.75it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/gellius.attic_nights.part.16.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/silius_italicus.punica.part.3.tess\n\n\n     66%|\u2588\u2588\u2588\u2588\u2588\u2588\u258c   | 422/640 [02:35<00:30,  7.17it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/martial.epigrams.part.9.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/valerius_flaccus.argonautica.part.2.tess\n\n\n     66%|\u2588\u2588\u2588\u2588\u2588\u2588\u258b   | 425/640 [02:36<00:23,  9.01it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/augustine.epistulae_selections.part.3.21-30.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/martial.epigrams.part.5.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/claudian.in_rufinum.part.1.tess\n\n\n     67%|\u2588\u2588\u2588\u2588\u2588\u2588\u258b   | 427/640 [02:36<00:23,  9.02it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vergil.georgics.part.3.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/gellius.attic_nights.part.9.tess\n\n\n     67%|\u2588\u2588\u2588\u2588\u2588\u2588\u258b   | 430/640 [02:37<00:40,  5.22it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tertullian.de_spectaculis.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/valerius_maximus.facta_et_dicta_memorabilia.part.3.tess\n\n\n     67%|\u2588\u2588\u2588\u2588\u2588\u2588\u258b   | 431/640 [02:37<00:38,  5.45it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/corippus.johannis.part.6.tess\n\n\n     68%|\u2588\u2588\u2588\u2588\u2588\u2588\u258a   | 432/640 [02:37<00:47,  4.42it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/apuleius.apologia.tess\n\n\n     68%|\u2588\u2588\u2588\u2588\u2588\u2588\u258a   | 433/640 [02:38<00:51,  4.02it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/servius_honoratus.in_virgilii_georgicon_libros_commentarius.part.3.tess\n\n\n     68%|\u2588\u2588\u2588\u2588\u2588\u2588\u258a   | 434/640 [02:38<01:00,  3.42it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/scriptores_historiae_augustae.historia_augusta.part.1.books_1-5.tess\n\n\n     68%|\u2588\u2588\u2588\u2588\u2588\u2588\u258a   | 436/640 [02:39<01:04,  3.16it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/valerius_maximus.facta_et_dicta_memorabilia.part.1.tess\n\n\n     68%|\u2588\u2588\u2588\u2588\u2588\u2588\u258a   | 437/640 [02:40<01:31,  2.23it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/petronius.satyricon.tess\n\n\n     69%|\u2588\u2588\u2588\u2588\u2588\u2588\u258a   | 439/640 [02:40<01:02,  3.22it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/silius_italicus.punica.part.14.tess\n\n\n     69%|\u2588\u2588\u2588\u2588\u2588\u2588\u2589   | 441/640 [02:41<01:38,  2.01it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/propertius.elegies.tess\n\n\n     69%|\u2588\u2588\u2588\u2588\u2588\u2588\u2589   | 443/640 [02:42<01:10,  2.78it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/plautus.bacchides.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vergil.eclogues.tess\n\n\n     70%|\u2588\u2588\u2588\u2588\u2588\u2588\u2589   | 445/640 [02:42<01:06,  2.92it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/macrobius.saturnalia.part.1.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.metamorphoses.part.6.tess\n\n\n     70%|\u2588\u2588\u2588\u2588\u2588\u2588\u2589   | 446/640 [02:43<01:00,  3.20it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/scriptores_historiae_augustae.historia_augusta.part.3.books_11-15.tess\n\n\n     70%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588   | 450/640 [02:44<00:45,  4.15it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/apuleius.metamorphoses.part.7.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/martial.epigrams.part.1.tess\n\n\n     70%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588   | 451/640 [02:44<00:39,  4.75it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/dracontius.de_laudibus_dei.part.3.tess\n\n\n     71%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588   | 453/640 [02:45<00:50,  3.69it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/bede.historiam_ecclesiasticam_gentis_anglorum.part.1.tess\n\n\n     71%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f  | 457/640 [02:45<00:34,  5.31it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vergil.aeneid.part.7.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/quintus_smyrnaeus.fall_of_troy.part.13.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vitruvius.de_architectura.part.5.tess\n\n\n     72%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f  | 460/640 [02:46<00:23,  7.69it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/dracontius.romulea.part.10.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.precationes.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.metamorphoses.part.10.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/dracontius.romulea.part.fragments.tess\n\n\n     72%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e  | 464/640 [02:46<00:17,  9.87it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/statius.thebaid.part.1.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/corippus.johannis.part.4.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/quintus_smyrnaeus.fall_of_troy.part.9.tess\n\n\n     73%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e  | 466/640 [02:52<03:00,  1.03s/it]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/polignac.antilucretius.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/lucretius.de_rerum_natura.part.2.tess\n\n\n     73%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e  | 470/640 [02:53<01:40,  1.68it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/pliny_the_elder.naturalis_historia.part.7.books_31-37.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.ephemeris_id_est_totius_diei_negotium.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/dracontius.romulea.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.commemoratio_professorum_burdigalensium.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca.octavia.tess\n\n\n     74%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d  | 473/640 [02:53<01:05,  2.55it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/curtius_rufus.historiae_alexandri_magni.part.3.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/apuleius.metamorphoses.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/horace.epodes.tess\n\n\n     75%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d  | 478/640 [02:54<00:41,  3.90it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/martial.epigrams.part.13.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vitruvius.de_architectura.part.1.tess\n\n\n     75%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c  | 481/640 [02:55<00:34,  4.58it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca.ad_lucilium_epistulae_morales.part.9.81-90.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/horace.ars_poetica.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/valerius_flaccus.argonautica.part.8.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.39.nahum.tess\n\n\n     76%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c  | 484/640 [02:55<00:27,  5.58it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/plautus.truculentus.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.ex_ponto.part.1.tess\n\n\n     76%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b  | 488/640 [02:56<00:16,  9.06it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/suetonius.de_vita_caesarum.part.2.augustus.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.oratio_consulis_ausonii_versibus_rhopalicis.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/quintus_smyrnaeus.fall_of_troy.part.6.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/horace.odes.part.4.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/claudian.carmina_minora.tess\n\n\n     77%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b  | 491/640 [02:57<00:29,  5.03it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca.de_ira.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/sallust.histories.tess\n\n\n     77%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b  | 492/640 [02:57<00:27,  5.43it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/valerius_maximus.facta_et_dicta_memorabilia.part.6.tess\n\n\n     77%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b  | 495/640 [02:57<00:23,  6.13it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.heroides.part.2.16-21.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.72.jude.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca.de_tranquillitate_animi.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.ordo_urbium_nobilium.tess\n\n\n     78%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a  | 499/640 [02:58<00:22,  6.29it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/valerius_maximus.facta_et_dicta_memorabilia.part.8.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.metamorphoses.part.12.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/martial.epigrams.part.2.tess\n\n\n     78%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a  | 501/640 [02:58<00:18,  7.34it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/silius_italicus.punica.part.7.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/quintus_smyrnaeus.fall_of_troy.part.7.tess\n\n\n     79%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a  | 503/640 [02:59<00:19,  6.99it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/curtius_rufus.historiae_alexandri_magni.part.7.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/martial.epigrams.part.3.tess\n\n\n     79%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589  | 507/640 [03:00<00:34,  3.87it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/polignac.epia.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/apuleius.metamorphoses.part.3.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/claudian.de_raptu_proserpinae.part.2.tess\n\n\n     80%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589  | 509/640 [03:00<00:26,  4.97it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tacitus.de_origine_et_situ_germanorum_liber.tess\n\n\n     80%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589  | 511/640 [03:01<00:26,  4.89it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/plautus.captivi.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/columella.de_re_rustica.part.7.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/horace.carmen_saeculare.tess\n\n\n     80%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588  | 513/640 [03:01<00:21,  5.93it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tacitus.annales.part.14.tess\n\n\n     80%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588  | 515/640 [03:01<00:20,  6.17it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ammianus.rerum_gestarum.part.14.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/valerius_flaccus.argonautica.part.7.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.21b.psalm.tess\n\n\n     81%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588  | 518/640 [03:02<00:16,  7.62it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/boethius.consolatio_philosophiae.part.3.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/claudian.panegyricus_de_sexto_consulatu_honorii_augusti.tess\n\n\n     81%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f | 520/640 [03:02<00:17,  6.82it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/apuleius.metamorphoses.part.4.tess\n\n\n     82%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f | 522/640 [03:02<00:16,  7.17it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ammianus.rerum_gestarum.part.27.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.ibis.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tacitus.historiae.part.5.tess\n\n\n     82%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f | 524/640 [03:03<00:17,  6.67it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/columella.de_re_rustica.part.3.tess\n\n\n     82%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f | 525/640 [03:03<00:22,  5.15it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.49.luke.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/martial.epigrams.part.8.tess\n\n\n     82%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e | 528/640 [03:03<00:17,  6.33it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ammianus.rerum_gestarum.part.23.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/dracontius.romulea.part.8.tess\n\n\n     83%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e | 530/640 [03:04<00:18,  5.98it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca.hercules_furens.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/celsus.de_medicina.part.8.tess\n\n\n     83%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e | 532/640 [03:04<00:15,  6.82it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/suetonius.de_vita_caesarum.part.1.julius.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/statius.silvae.part.4.tess\n\n\n     83%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e | 534/640 [03:04<00:13,  7.66it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.52.romans.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca.de_providentia.tess\n\n\n     84%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d | 536/640 [03:04<00:13,  7.92it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/silius_italicus.punica.part.5.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/statius.silvae.part.3.tess\n\n\n     84%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d | 538/640 [03:05<00:14,  6.81it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/gellius.attic_nights.part.5.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/pliny_the_younger.letters.part.1.tess\n\n\n     84%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d | 540/640 [03:05<00:13,  7.39it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/martial.epigrams.part.12.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vergil.aeneid.part.1.tess\n\n\n     85%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d | 542/640 [03:05<00:14,  6.59it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/horace.odes.part.3.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/silius_italicus.punica.part.4.tess\n\n\n     85%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d | 543/640 [03:05<00:14,  6.80it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca.apocolocyntosis.tess\n\n\n     85%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c | 547/640 [03:07<00:18,  4.98it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tacitus.annales.part.11.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/claudian.de_consulatu_stilichonis.part.3.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/statius.silvae.part.2.tess\n\n\n     86%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c | 548/640 [03:07<00:27,  3.38it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.ludus_septem_sapientum.tess\n\n\n     86%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b | 552/640 [03:08<00:15,  5.51it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tacitus.historiae.part.4.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.63.titus.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.ars_amatoria.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/dracontius.romulea.part.6.tess\n\n\n     87%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b | 555/640 [03:08<00:10,  7.85it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/tacitus.historiae.part.1.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/apuleius.metamorphoses.part.1.tess\n\n\n     87%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b | 559/640 [03:09<00:12,  6.57it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/pliny_the_younger.letters.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.praefatiunculae.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.metamorphoses.part.7.tess\n\n\n     88%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a | 561/640 [03:09<00:14,  5.34it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/macrobius.saturnalia.part.5.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/statius.thebaid.part.9.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.76.prayer_of_manasseh.tess\n\n\n     88%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a | 563/640 [03:09<00:10,  7.04it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/gellius.attic_nights.part.7.tess\n\n\n     88%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a | 566/640 [03:11<00:18,  3.93it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/gellius.attic_nights.part.3.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.metamorphoses.part.4.tess\n\n\n     89%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589 | 568/640 [03:11<00:14,  4.81it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/horace.satires.part.1.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/silius_italicus.punica.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/suetonius.de_vita_caesarum.part.7.galba.tess\n\n\n     89%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589 | 570/640 [03:11<00:10,  6.96it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/quintus_smyrnaeus.fall_of_troy.part.1.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.8.ruth.tess\n\n\n     90%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589 | 573/640 [03:12<00:10,  6.20it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.26.sirach.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.ex_ponto.part.2.tess\n\n\n     90%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589 | 575/640 [03:12<00:10,  5.98it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/italicus.ilias_latina.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/gellius.attic_nights.part.10.tess\n\n\n     90%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 | 577/640 [03:12<00:11,  5.27it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/suetonius.de_vita_caesarum.part.4.caligula.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/claudian.in_eutropium.part.1.tess\n\n\n     91%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 | 580/640 [03:13<00:10,  5.73it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/manilius.astronomicon.part.5.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.65.hebrews.tess\n\n\n     91%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 | 582/640 [03:13<00:09,  5.83it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/plautus.casina.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vitruvius.de_architectura.part.9.tess\n\n\n     91%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f| 585/640 [03:14<00:08,  6.26it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/celsus.de_medicina.part.4.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vitruvius.de_architectura.part.6.tess\n\n\n     92%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f| 587/640 [03:14<00:07,  6.96it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/gellius.attic_nights.part.20.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/corippus.johannis.part.8.tess\n\n\n     92%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f| 589/640 [03:14<00:06,  7.90it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.15.ezra.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/silius_italicus.punica.part.1.tess\n\n\n     92%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f| 591/640 [03:14<00:06,  8.05it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vergil.aeneid.part.3.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vitruvius.de_architectura.part.4.tess\n\n\n     93%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e| 593/640 [03:15<00:06,  7.48it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/pliny_the_younger.letters.part.5.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.remedia_amoris.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vergil.georgics.part.4.tess\n\n\n     93%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e| 596/640 [03:15<00:06,  6.56it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/augustine.epistulae_selections.part.5.41-50.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/celsus.de_medicina.part.5.tess\n\n\n     94%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e| 599/640 [03:16<00:05,  7.30it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.5.deuteronomy.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.42.haggaiah.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/claudian.de_bello_gildonico.tess\n\n\n     94%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d| 602/640 [03:16<00:07,  5.34it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/quintus_smyrnaeus.fall_of_troy.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/dracontius.orestes.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.versus_paschales_pro_augusto_dicti.tess\n\n\n     94%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d| 604/640 [03:17<00:05,  6.95it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/dracontius.de_laudibus_dei.part.1.tess\n\n\n     95%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d| 606/640 [03:17<00:05,  5.96it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/columella.de_re_rustica.part.4.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/curtius_rufus.historiae_alexandri_magni.part.10.tess\n\n\n     95%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c| 608/640 [03:17<00:05,  5.81it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/statius.achilleid.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca.thyestes.tess\n\n\n     95%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c| 610/640 [03:18<00:04,  6.13it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.fasti.part.3.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/statius.thebaid.part.10.tess\n\n\n     95%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c| 611/640 [03:18<00:05,  4.90it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.51.acts.tess\n\n\n     96%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c| 612/640 [03:18<00:05,  4.76it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/seneca.hercules_oetaeus.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/dracontius.romulea.part.9.tess\n\n\n     96%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b| 616/640 [03:20<00:06,  3.64it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/servius_honoratus.in_virgilii_georgicon_libros_commentarius.part.1.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/celsus.de_medicina.part.6.tess\n\n\n     97%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b| 618/640 [03:20<00:04,  4.88it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.metamorphoses.part.14.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.metamorphoses.part.5.tess\n\n\n     97%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b| 620/640 [03:20<00:03,  5.65it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/lucan.bellum_civile.part.9.tess\n\n\n     97%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b| 622/640 [03:20<00:03,  5.71it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/aurelius_victor.de_caesaribus.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/horace.odes.part.1.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/corippus.johannis.part.3.tess\n\n\n     98%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a| 626/640 [03:21<00:03,  4.65it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.48.mark.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.amores.part.2.tess\n\n\n     98%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a| 629/640 [03:22<00:01,  6.41it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ovid.ex_ponto.part.3.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.32.daniel.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/valerius_flaccus.argonautica.part.6.tess\n\n\n     99%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589| 632/640 [03:22<00:01,  6.14it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.parentalia.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/jerome.vulgate.part.16.nehemiah.tess\n\n\n     99%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589| 633/640 [03:23<00:01,  5.87it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/prudentius.contra_symmachum.part.2.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ausonius.eclogarum_liber.tess\n\n\n     99%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589| 636/640 [03:23<00:00,  6.88it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/ammianus.rerum_gestarum.part.20.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/valerius_flaccus.argonautica.part.3.tess\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589| 638/640 [03:23<00:00,  6.44it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/columella.de_re_rustica.part.8.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/apuleius.metamorphoses.part.10.tess\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 640/640 [03:24<00:00,  3.14it/s]\n\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/vergil.aeneid.part.9.tess\n    too dissimilar /Users/todd/cltk_data/latin/text/latin_text_tesserae/texts/lucan.bellum_civile.part.3.tess\n\n\n    \n\n\n\n```python\n! ls cicero.train.tesserae/*.txt | wc -l \n```\n\n          95\r\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n# Obelized:\n# quae si non essent sedulitate effectae et \u2020benivolentie va\u2020 , liceret mihi abire in solitudines aliquas .\n# nunc ne id quidem licet .\n# \n# Odd section\n# Ut cum uidemus speciem primum candorem -que caeli , dein conuersionis celeritatem tantam quantam cogitare non possumus , tum uicissitudines dierum ac noctium commutationes -que temporum quadrupertitas ad maturitatem frugum et ad temperationem corporum aptas eorum -que omnium moderatorem et ducem solem , lunam -que adcretio -ne et deminutio -ne luminis quasi fastorum notantem et significantem dies , tum in eodem orbe in duodecim partes distributo quinque stellas ferri eosdem cursus constantissime seruantis disparibus inter se motibus , nocturnam -que caeli formam undique sideribus ornatam , tum globum terrae eminentem e mari , fixum in medio mundi uniuersi loco , duabus oris distantibus habitabilem et cultum , quarum altera , quam nos incolimus , Sub a/xe posita ad ste/llas septem , unde ho/rrifer , Aquilo/nis stridor ge/lidas molitu/r niues , altera australis , ignota nobis , quam uocant Graeci \u1f00\u03bd\u03c4\u03af\u03c7\u03b8\u03bf\u03bd\u03b1 , ceteras partis incultas , quod aut frigore rigeant aut urantur calore ; hic autem , ubi habitamus , non intermittit suo tempore Caelu/m nitescere , a/rbores fronde/scere , Uite/s laetificae pa/mpinis pube/scere , Rami/ bacarum ube/rtate incurue/scere , Segete/s largiri fru/ges , florere o/mnia , Fonte/s scatere , herbis pra/ta conuesti/rier , tum multitudinem pecudum partim ad uescendum , partim ad cultus agrorum , partim ad uehendum , partim ad corpora uestienda , hominem -que ipsum quasi contemplatorem caeli ac deorum cultorem atque ho- minis utili\n```\n\n## Text Cleaning\nfrom http://udallasclassics.org/wp-content/uploads/maurer_files/APPARATUSABBREVIATIONS.pdf\n\n[...] Square brackets, or in recent editions wavy brackets \u02ba{...}\u02ba, enclose words etc. that an editor thinks should be deleted (see \u02badel.\u02ba) or marked as out of place (see \u02basecl.\u02ba).\n\n[...] Square  brackets  in  a  papyrus  text, or in an  inscription,  enclose  places  where words have been lost through physical damage.  If this happens in mid-line, editors  use  \u02ba[...]\u02ba.    If  only  the  end  of  the  line  is  missing,  they  use  a  single  bracket \u02ba[...\u02ba      If  the  line\u02b9s  beginning  is  missing,  they  use  \u02ba...]\u02ba    Within  the  brackets, often each dot represents one missing letter.\n\n[[...]] Double brackets enclose letters or words deleted by the medieval copyist himself.\n\n(...) Round  brackets  are  used  to  supplement  words  abbreviated  by  the  original  copyist; e.g. in an inscription: \u02batrib(unus) mil(itum) leg(ionis) III\u02ba\n\n<...> diamond  (  =  elbow  =  angular)  brackets  enclose  words  etc.  that  an  editor  has  added (see \u02basuppl.\u02ba)\n\n\u2020   An obelus (pl. obeli) means that the word(s etc.) is very plainly corrupt, but the editor  cannot  see  how  to  emend.    If  only  one  word  is  corrupt,  there  is  only  one obelus, which precedes the word; if two or more words are corrupt, two obeli  enclose  them.    (Such  at  least  is  the  rule--but  that  rule  is  often  broken,  especially  in  older  editions,  which  sometimes  dagger  several  words  using  only one obelus.)  To dagger words in this way is to \u02baobelize\u02ba them.\n\n## Load/Build Truecasing dictionary; count all cased tokens, use to normalize cases later\n\n\n```python\ntruecase_file = 'truecase_counter.latin.pkl'\n\nif os.path.exists(truecase_file):\n    with open(truecase_file, 'rb') as fin:        \n        case_counts = pickle.load(fin)\nelse:\n    tesserae = get_corpus_reader(corpus_name='latin_text_tesserae', language='latin')\n    case_counts = Counter()\n    jv_replacer = JVReplacer()\n    aeoe_replacer = AEOEReplacer()\n    toker = WordTokenizer('latin')\n    sent_toker = SentenceTokenizer()\n    lemmatizer = LemmaReplacer('latin')\n    \n    for file in tqdm(tesserae.fileids(), total=len(tesserae.fileids())):\n        for sent in tesserae.sents(file):\n            sent = aeoe_replacer.replace(jv_replacer.replace(drop_punct(sent)))\n            sent = normalize_accents(sent)\n            sent = accept_editorial(sent)\n            for token in toker.tokenize(sent):\n                case_counts.update({token:1})\n                \n    with open(truecase_file, 'wb') as fout:        \n        pickle.dump(case_counts, fout) \n\nlen(case_counts)\n```\n\n\n\n\n    309529\n\n\n\n\n```python\nprint(sample(list(case_counts.items()), 25))\n```\n\n    [('Epicharmium', 1), ('litabilis', 1), ('Adliciunt', 1), ('Praediximus', 1), ('caliculus', 1), ('uolitare', 50), ('Militiam', 3), ('adfuerim', 5), ('Pica', 2), ('induperatorem', 2), ('pericla', 22), ('menstrua', 45), ('delenisse', 1), ('subtrahit', 22), ('uastaris', 1), ('epiphonema', 2), ('tempnunt', 1), ('gloriantis', 2), ('fuluas', 6), ('uthinam', 1), ('Pici', 3), ('Durati', 1), ('uersicolori', 11), ('armeniacum', 1), ('dubitauimus', 1)]\n\n\n\n```python\ndef get_word_counts(files:List[str])->Tuple[Dict[str, int], Dict[str, int]]:\n    \"\"\"\n    Given a list of files, \n    clean & tokenize the documents\n    returns: Tuple(counter of lemmatized words, counter of inflected words)\n    \"\"\"\n    lemma_word_counter = Counter()\n    inflected_word_counter = Counter()\n    jv_replacer = JVReplacer()\n    aeoe_replacer = AEOEReplacer()\n    toker = WordTokenizer('latin')\n    sent_toker = SentenceTokenizer()\n    lemmatizer = LemmaReplacer('latin')\n\n    for file in files: # , total=len(files), unit='files'):\n        with open(file, 'rt') as fin:\n            text = fin.read()\n            text = text.replace(\"-\\n\", \"\")\n            text = text.replace(\"\\n\", \" \")\n            text = aeoe_replacer.replace(jv_replacer.replace( text))\n            for sent in sent_toker.tokenize(text):\n                sent = dehyphenate(sent) # because it's Phi5\n                sent = swallow_braces(sent)\n                sent = swallow_square_brackets(sent)\n                sent = disappear_round_brackets(sent)\n                sent = swallow_obelized_words(sent)\n                sent = disappear_angle_brackets(sent)            \n                sent = drop_punct(sent)\n                sent = normalize_accents(sent)            \n                # lemmatizer prefers lower \n    #             sent = lemmatizer.lemmatize(sent.lower(), return_string=True)\n                for word in toker.tokenize(sent):\n                    if word.isnumeric():\n                        continue\n                    inflected_word_counter.update({truecase(word, case_counts) : 1})                    \n                    word = lemmatizer.lemmatize(word.lower(), return_string=True)\n                    # normalize capitals\n                    lemma_word_counter.update({truecase(word, case_counts) : 1})\n    return  inflected_word_counter, lemma_word_counter\n```\n\n\n```python\ndef word_stats(author:str,\n               inflected_counter:Counter,\n                lemma_counter:Counter)->Tuple[float, float]:\n    \"\"\"\n    Compute statistics for an author's corpus\n    \"\"\"\n    nw = sum(lemma_counter.values())\n    print(f\"Total count of all word tokens in {author} corpus: {nw:,}\")\n    print(f\"Total number of distinct, inflected words/tokens in {author} corpus: {len(inflected_counter):,}\")\n    print(f\"Total number of lemmatized words/tokens in {author} corpus {len(lemma_counter):,}\")\n    # Count of inflected unigrams occuring only once\n    ciw1 = sum([1 for key, val in inflected_counter.items() if val == 1]) \n    print(f\"Count of inflected tokens only occuring once {ciw1:,}\")\n    # Count of lemmatized unigrams occuring only once\n    cw1 = sum([1 for key, val in lemma_counter.items() if val == 1])\n    print(f\"Count of lemmatized tokens only occuring once {cw1:,}\")\n    Piu_one = round(ciw1 / nw,3)\n    print(f\"Probability of a single count unigram occuring in the {author} corpus: {Piu_one:.3f}\") \n    Plu_one = round(cw1 / nw, 3)\n    print(f\"Probability of a single count lemmatized unigram in a novel form occuring in the {author} corpus: {Plu_one:.3f}\") \n    return (Piu_one, Plu_one)\n```\n\n\n```python\n# Cicero works\ncicero_files = glob(f\"{os.path.expanduser('~')}/cltk_data/latin/text/phi5/individual_works/LAT0474.TXT-0*.txt\")\nlen (cicero_files)              \n```\n\n\n\n\n    75\n\n\n\n\n```python\ncicero_lemmas_counter_file = 'cicero_lemmas_counter.pkl'\ncicero_inflected_counter_file = 'cicero_inflected_counter.pkl'\n\nif os.path.exists(cicero_lemmas_counter_file) and os.path.exists(cicero_inflected_counter_file):\n    with open(cicero_lemmas_counter_file, 'rb') as fin:\n        cicero_lemmas = pickle.load(fin)\n    with open(cicero_inflected_counter_file, 'rb') as fin:\n        cicero_inflected_words = pickle.load(fin)\nelse:\n    cicero_inflected_words, cicero_lemmas  = get_word_counts(cicero_files)\n\nif not os.path.exists(cicero_lemmas_counter_file):\n    with open(cicero_lemmas_counter_file, 'wb') as fout:\n        pickle.dump(cicero_lemmas, fout)\nif not os.path.exists(cicero_inflected_counter_file):\n    with open(cicero_inflected_counter_file, 'wb') as fout:\n        pickle.dump(cicero_inflected_words, fout)\n```\n\n\n```python\nword_stats(author='Cicero',           \n            inflected_counter=cicero_inflected_words,\n            lemma_counter=cicero_lemmas)\n```\n\n    Total count of all word tokens in Cicero corpus: 1,196,512\n    Total number of distinct, inflected words/tokens in Cicero corpus: 75,705\n    Total number of lemmatized words/tokens in Cicero corpus 23,345\n    Count of inflected tokens only occuring once 34,608\n    Count of lemmatized tokens only occuring once 10,656\n    Probability of a single count unigram occuring in the Cicero corpus: 0.029\n    Probability of a single count lemmatized unigram in a novel form occuring in the Cicero corpus: 0.009\n\n\n\n\n\n    (0.029, 0.009)\n\n\n\n\n```python\nword_counts =  sorted(cicero_inflected_words.items(), key=lambda x:x[1], reverse=True)\n# words, counts = zip(*word_counts)\n\n```\n\n\n```python\ntop_label, side_label, bottom_label = ('Frequency Rank',\n                                       'Occurences',\n                                       'Word Frequency Distributions of the Cicero Corpus')\nfig = plt.figure(figsize=(7,5))\nplt.xlabel(top_label)\nplt.ylabel(side_label)\nplt.title(bottom_label)\nax = fig.gca()\nplt.yscale('log')\nindices, values = zip(*word_counts)\n# plt.bar(range(len(values)), values)\nplt.loglog(range(len(values)), values, label='word frequencies')\n# plt.axvline(x=np.mean(all_vals), color='k', linestyle='-', label='mean')\n# plt.axvline(x=np.mean(all_vals) + np.std(all_vals), color='b', linestyle='-', label='std')\n# plt.axvline(x=np.mean(all_vals) + (2 * np.std(all_vals)), color='m', linestyle='-', label='std2')\nplt.legend(loc='upper right')\nplt.tight_layout(pad=0.5, w_pad=20, h_pad=0.5)\n# plt.show()\nplt.savefig('cicero_frequency_distributions.png')\n```\n\n\n```python\nword_counts[:5]\n```\n\n\n\n\n    [('et', 27952), ('in', 23862), ('non', 18471), ('est', 16045), ('ut', 14957)]\n\n\n\n\n```python\nword_counts[-5:]\n```\n\n\n\n\n    [('adaequatus', 1),\n     ('obfuerint', 1),\n     ('ignorauit', 1),\n     ('erudiri', 1),\n     ('adprobarunt', 1)]\n\n\n\n\n```python\nfirst_last = word_counts[:5] +word_counts[-5:]\n```\n\n\n```python\ntop_label, side_label, bottom_label = ('Word',\n                                       'Count',\n                                       'Top 5 Cicero Words')\nfig = plt.figure(figsize=(4,5))\nplt.xlabel(top_label)\nplt.ylabel(side_label)\nplt.title(bottom_label)\nax = fig.gca()\n# plt.yscale('log')\n# word_counts[:5] +word_counts[-5:]\nindices, values = zip(*word_counts[:5])\nplt.bar(indices , values)\n# plt.loglog(range(len(values)), values, label='word frequencies')\n# plt.axvline(x=np.mean(all_vals), color='k', linestyle='-', label='mean')\n# plt.axvline(x=np.mean(all_vals) + np.std(all_vals), color='b', linestyle='-', label='std')\n# plt.axvline(x=np.mean(all_vals) + (2 * np.std(all_vals)), color='m', linestyle='-', label='std2')\nplt.legend(loc='upper right')\nplt.tight_layout(pad=0.5, w_pad=20, h_pad=0.5)\n# plt.show()\nplt.savefig('cicero_top5_words.png')\n```\n\n\n```python\nnum_f1 = sum([1 for tmp, cnt in cicero_inflected_words.items() if cnt == 1])\nnum_f2 = sum([1 for tmp, cnt in cicero_inflected_words.items() if cnt == 2])\nnum_f3 = sum([1 for tmp, cnt in cicero_inflected_words.items() if cnt == 3])\nnum_f4 = sum([1 for tmp, cnt in cicero_inflected_words.items() if cnt == 4])\nnum_f5 = sum([1 for tmp, cnt in cicero_inflected_words.items() if cnt == 5])\nvalues=[num_f5, num_f4, num_f3, num_f2, num_f1 ]\n```\n\n\n```python\nvalues\n```\n\n\n\n\n    [2622, 3936, 6095, 11858, 34608]\n\n\n\n\n```python\np0 = round(34608 / sum(cicero_inflected_words.values()),3)\np0\n```\n\n\n\n\n    0.029\n\n\n\n\n```python\nsum(cicero_inflected_words.values())\n```\n\n\n\n\n    1196512\n\n\n\n\n```python\ntop_label, side_label, bottom_label = ('Occurences',\n                                       'Counts',\n                                       'Last 5 Cicero Word Frequencies')\nfig = plt.figure(figsize=(5,5))\nplt.xlabel(top_label)\nplt.ylabel(side_label)\nplt.title(bottom_label)\nax = fig.gca()\nplt.yscale('linear')\n# indices, values = zip(*word_counts[-5:])\nvalues = [num_f1, num_f2, num_f3, num_f4, num_f5]\nplt.bar(range(1,len(values)+1), values, label='frequency counts')\n# plt.loglog(range(len(values)), values, label='word frequencies')\n# plt.axvline(x=np.mean(all_vals), color='k', linestyle='-', label='mean')\n# plt.axvline(x=np.mean(all_vals) + np.std(all_vals), color='b', linestyle='-', label='std')\n# plt.axvline(x=np.mean(all_vals) + (2 * np.std(all_vals)), color='m', linestyle='-', label='std2')\nplt.legend(loc='upper right')\nplt.tight_layout(pad=0.5, w_pad=20, h_pad=0.5)\n# plt.show()\nplt.savefig('cicero_last_five_word_frequencies.png')\n```\n\n# Calculate lemmatized values\n\n\n```python\n# Probability of a single count unigram occuring in the Cicero corpus: 0.029\n# Probability of a single count lemmatized unigram in a novel form occuring in the Cicero corpus: 0.009\n# (0.029, 0.009)\n# With Curve fitting\n# Probability of encountering a new inflected word in new Cicero 0.054 (according to curve fitting)\n# Probability of encountering a new lemmatized word form in new Cicero 0.017 (according to curve fitting)\n# (0.054, 0.017)\n```\n\n\n```python\nfreq_vals = []\nnum_samples =10\nfor i in range(num_samples,0,-1):\n    freq_vals.append( (i, sum([1 for tmp, cnt in cicero_lemmas.items() if cnt == i])))\n\nX,y = zip(*freq_vals)\n# We will reverse the scale to predict the next number according to a Power Law distribution\nX =list(reversed(X))\n\ndef func_powerlaw(x, m, c, c0):\n    return c0 + x**m * c\n  \npopt, pcov = curve_fit(func_powerlaw, X, y, maxfev=2000)\nexpected_unk_count  = round(func_powerlaw(num_samples + 1 , *popt)) \nplt.figure(figsize=(5,4))\nplt.plot(X, func_powerlaw(X, *popt), '--', label='predicted counts')\nplt.plot(X[-1] + 1, func_powerlaw(X[-1]+1, *popt), '*', label='predicted unk')\nplt.plot(X, y, 'ro', label='actual counts')\nplt.title(\"Cicero Lemmatized word forms\")\nplt.xlabel(\"Frequency group\" )\nplt.ylabel(\"Count\")\nlocs, labels = plt.xticks()  \nplt.xticks(range(12), ['']+ [str(tmp) for tmp in range(10,0,-1)] +['unk']) \nplt.legend()\n# plt.show()\nplt.tight_layout(pad=0.5, w_pad=20, h_pad=0.5)\nplt.savefig('cicero_lemmatized_words_unk_prob_curve_fit.png')\n\nexpected_unk_count  = round(func_powerlaw(num_samples + 1, *popt) ) \nP_new_lemma_word = expected_unk_count / sum(cicero_lemmas.values())\nprint(f\"Expected unknown count {expected_unk_count:,}\")\nprint(f\"Probability of encountering a new lemmatized word form in new Cicero {round(P_new_lemma_word,3)} (according to curve fitting)\")\nprint(freq_vals)\n```\n\n\n```python\nfreq_vals = []\nnum_samples = 10\nfor i in range(num_samples,0,-1):\n    freq_vals.append( (i, sum([1 for tmp, cnt in cicero_inflected_words.items() if cnt == i])))\n\nX,y = zip(*freq_vals)\n# We will reverse the scale to predict the next number according to a Power Law distribution\nX =list(reversed(X))\n\ndef func_powerlaw(x, m, c, c0):\n    return c0 + x**m * c\n \npopt, pcov = curve_fit(func_powerlaw, X, y, maxfev=2000)\nexpected_unk_count  = round(func_powerlaw(num_samples + 1 , *popt)) \nplt.figure(figsize=(5,4))\nplt.plot(X, func_powerlaw(X, *popt), '--', label='predicted counts')\nplt.plot(X[-1] + 1, func_powerlaw(X[-1]+1, *popt), '*', label='predicted unk')\nplt.plot(X, y, 'ro', label='actual counts')\nplt.title(\"Cicero inflected word forms\")\nplt.xlabel(\"Frequency group\" )\nplt.ylabel(\"Count\")\nlocs, labels = plt.xticks()  \nplt.xticks(range(12), ['']+ [str(tmp) for tmp in range(10,0,-1)] +['unk']) \nplt.legend()\n# plt.show()\nplt.tight_layout(pad=0.5, w_pad=20, h_pad=0.5)\nplt.savefig('cicero_inflected_words_unk_prob_curve_fit.png')\n\nexpected_unk_count  = round(func_powerlaw(num_samples + 1 , *popt)) \nP_new_word = expected_unk_count / sum(cicero_inflected_words.values())\nprint(f\"Expected unknown count {expected_unk_count:,}\")\nprint(f\"Probability of encountering a new word in new Cicero {round(P_new_word,3)} (according to curve fitting)\")\nprint(freq_vals)\n```\n\n\n```python\n# Probability of a single count unigram occuring in the Cicero corpus: 0.029\n# Probability of a single count lemmatized unigram in a novel form occuring in the Cicero corpus: 0.009\n# (0.029, 0.009)\n# With Curve fitting\n# Probability of encountering a new inflected word in new Cicero 0.054 (according to curve fitting)\n# Probability of encountering a new lemmatized word form in new Cicero 0.017 (according to curve fitting)\n# (0.054, 0.017)\n# With Power Law Curve fitting\n# (0.074, 0.027)\n# Probability of encountering a new inflected word in a new page of Cicero: 0.074\n# Probability of encountering a new form of lemma in Cicero's use: 0.027\n\n#  So, if you found a new page of Cicero with a 100 words\n# we would expect 7 of the words to be new/hitherto/unseen in the Cicero corpus\n# we would expect 3 of the words to be words that Cicero had used before, but now in novel forms of the lemmas \n```\n\n### Good-Turing Frequency Estimation\n\\begin{align}\np_{0}={\\frac {N_{1}}{N}}\n\\end{align}\nThe probability of an unseen element is equivalent to the the probability of elements seen only once.\n\n\n```python\n88198/  1196512\n```\n\n\n\n\n    0.07371259126527774\n\n\n\n\n```python\nauthor_index = {val:key for key,val in PHI5_INDEX.items()  \n                if val != 'Marcus Tullius Cicero, Cicero, Tully'}\n\ndef get_phi5_author_files(author_name, author_index):\n    stub = author_index[author_name]\n    return glob(os.path.expanduser(f'~/cltk_data/latin/text/phi5/individual_works/{stub}*.txt'))\n```\n\n## Visualization of our corpus comparison: \nIf you took one page from one author and placed it into Cicero, how surprising would it be?\n\nIf the other author's vocabulary was substantially different, it would be noticeable. We can quantify this.\n\nAs a result, since we want to predict as close as possible to the author, we should only train a language model where the underlying corpus vocabularies are within a reasonable window of surprise.\n\n\n```python\njv_replacer = JVReplacer()\naeoe_replacer = AEOEReplacer()\ntoker = WordTokenizer('latin')\nsent_toker = SentenceTokenizer()\nlemmatizer = LemmaReplacer('latin')\n```\n\n# Examine Phi5 corpus\n\n\n```python\nresults = []\n# The following code assumes this is in memory:\n# cicero_lemmas, cicero_inflected_words = get_word_counts(cicero_files)    \n\nfor author in author_index:\n    files = get_phi5_author_files(author, author_index)\n    # Get a counter of all the author's distinct words & counter of words collapsed by lemmas\n    author_inflected_words, author_lemmas  = get_word_counts(files)        \n    # Calculate the overlap & find the differences; lemmas:\n    author_words = set(author_lemmas.keys())\n    cicero_words = set(cicero_lemmas.keys())\n    common = author_words & cicero_words\n    author_uniq = author_words - common \n    P_lemma_unigram_unk = len(author_uniq) / sum(author_lemmas.values())\n    # now inflected forms: \n    author_words = set(author_inflected_words.keys())\n    cicero_words = set(cicero_inflected_words.keys())\n    common = author_words & cicero_words\n    author_uniq = author_words - common \n    P_inflected_unigram_unk = len(author_uniq) / sum(author_inflected_words.values())\n    results.append((author, round(P_inflected_unigram_unk, 3), round(P_lemma_unigram_unk, 3)))\n    if P_inflected_unigram_unk <= 0.074:\n        for file in files: # , total=len(files), unit='files'):\n            with open(file, 'rt') as fin:\n                text = fin.read()\n                text = text.replace(\"-\\n\", \"\")\n                text = text.replace(\"\\n\", \" \")\n                text = aeoe_replacer.replace(jv_replacer.replace( text))\n                filename = file[file.rfind('/')+1:]\n                with open(f\"cicero_training_corpus/{filename}\", 'wt') as fout:\n                    for sent in sent_toker.tokenize(text):\n                        sent = dehyphenate(sent) # because it's Phi5\n                        sent = swallow_braces(sent)\n                        sent = swallow_square_brackets(sent)\n                        sent = disappear_round_brackets(sent)\n                        sent = swallow_obelized_words(sent)\n                        sent = disappear_angle_brackets(sent)            \n#                         sent = drop_punct(sent)\n                        sent = normalize_accents(sent)\n                        sentence = [truecase(word, case_counts)\n                                    for word in toker.tokenize(sent) \n                                    if not word.isnumeric()]\n                        fout.write(f\"{' '.join(sentence)}\\n\")\n\n```\n\n\n```python\nresults_map = {key: (val, val2) for key,val,val2 in results}\n\nresults = sorted(results, key=lambda x:x[2])\n\nfor tmp in results:\n    print(tmp)\n```\n\n    ('Publius Cominius', 0.0, 0.0)\n    ('Publius Cornelius Dolabella', 0.0, 0.0)\n    ('Gaius Calpurnius Piso', 0.0, 0.0)\n    ('Publius Saturius', 0.0, 0.0)\n    ('Lucius Cassius Longinus', 0.0, 0.0)\n    ('Gaius Memmius', 0.0, 0.0)\n    ('Passienus Crispus', 0.0, 0.0)\n    ('Marcus Antonius', 0.0, 0.0)\n    ('Caecilius Metellus', 0.0, 0.0)\n    ('Gaius Aurelius Cotta', 0.0, 0.0)\n    ('Gaius Scribonius Curio avus', 0.0, 0.0)\n    ('Vibius Crispus', 0.0, 0.0)\n    ('Gallus Antipater', 0.0, 0.0)\n    ('Lucius Herennius Balbus', 0.0, 0.0)\n    ('Marcus Antonius triumvir', 0.0, 0.0)\n    ('Sevius Nicanor', 0.0, 0.0)\n    ('Gaius Papirius Carbo Arvina', 0.0, 0.0)\n    ('Gaius vel Lucius Caepasius', 0.0, 0.0)\n    ('Titus Labienus', 0.0, 0.0)\n    ('Lucius Quinctius', 0.0, 0.0)\n    ('Q. Lutatius Catulus iunior', 0.0, 0.0)\n    ('Gaius Servilius Glaucia', 0.0, 0.0)\n    ('Gaius Aquilius Gallus', 0.0, 0.0)\n    ('Lucius Marcius Philippus', 0.0, 0.0)\n    ('Iulius Africanus', 0.0, 0.0)\n    ('Marcus Porcius Cato Uticensis', 0.0, 0.0)\n    ('Publius Clodius Pulcher', 0.0, 0.0)\n    ('Vagellius', 0.0, 0.0)\n    ('Publius Mucius Scaevola', 0.0, 0.0)\n    ('Marullus', 0.0, 0.0)\n    ('Gaius Papirius Carbo', 0.0, 0.0)\n    ('Gaius Erucius', 0.0, 0.0)\n    ('Lucius Cincius Alimentus', 0.0, 0.0)\n    ('Marcus Iuventius Laterensis', 0.0, 0.012)\n    ('Laelius Felix', 0.0, 0.016)\n    ('Lucius Cornelius Sulla', 0.017, 0.017)\n    ('P. Cornel. Scipio Nasica Ser.', 0.0, 0.018)\n    ('Lucius Licinius Crassus', 0.005, 0.02)\n    ('Iustinianus, Justinian, Digest', 0.007, 0.02)\n    ('Cn. Cornel. Lentulus Marcell.', 0.0, 0.021)\n    ('Trabea', 0.0, 0.022)\n    ('P. Cornel. Scipio Afr. ma.', 0.023, 0.023)\n    ('Q. Caecilius Metellus Maced.', 0.0, 0.024)\n    ('Gaius Asinius Gallus', 0.029, 0.029)\n    ('Aufidius Bassus', 0.0, 0.03)\n    ('Quintus Asconius Pedianus', 0.01, 0.03)\n    ('Publilius Syrus', 0.007, 0.032)\n    ('Quintus Tullius Cicero', 0.008, 0.034)\n    ('Lucilius iunior', 0.034, 0.034)\n    ('Gaius, iur., Gaius', 0.011, 0.035)\n    ('Aurelius Augustinus', 0.0, 0.037)\n    ('Titus Livius, Livy', 0.011, 0.039)\n    ('Marcus Iunius Brutus [iur.]', 0.0, 0.04)\n    ('Marcus Iunius Brutus [tyr.]', 0.04, 0.04)\n    ('Q. Caecilius Metellus Numid.', 0.021, 0.041)\n    ('Marcus Fabius Quintilianus', 0.009, 0.042)\n    ('Sentius Augurinus', 0.043, 0.043)\n    ('Quintus Lutatius Catulus', 0.03, 0.045)\n    ('Gaius Iulius Caesar, Caesar', 0.016, 0.046)\n    ('Cornelius Nepos', 0.018, 0.047)\n    ('Gaius Trebatius Testa', 0.008, 0.048)\n    ('M. Valerius Messalla Rufus', 0.027, 0.048)\n    ('Atilius', 0.048, 0.048)\n    ('Gaius Laelius Sapiens', 0.048, 0.048)\n    ('Lucius Annaeus Seneca senior', 0.016, 0.052)\n    ('Lucius Annaeus Seneca iunior', 0.013, 0.054)\n    ('Hyginus Astronomus', 0.024, 0.054)\n    ('Precatio Omnium Herbarum', 0.009, 0.055)\n    ('Publius Rutilius Lupus', 0.02, 0.055)\n    ('Q. Mucius Scaevola [pontifex]', 0.031, 0.055)\n    ('Aulus Cornelius Celsus', 0.017, 0.056)\n    ('Bellum Alexandrinum [Anonymous]', 0.018, 0.057)\n    ('Bellum Africum [Anonymous]', 0.019, 0.057)\n    ('Volcacius Sedigitus', 0.025, 0.057)\n    ('Calpurnius Flaccus', 0.01, 0.058)\n    ('Gaius Sempronius Gracchus', 0.025, 0.058)\n    ('Aulus Hirtius', 0.019, 0.059)\n    ('Gaius Sallustius Crispus', 0.021, 0.059)\n    ('Maurus Servius Honoratus, Servius', 0.025, 0.059)\n    ('Publius Terentius Afer, Terence', 0.029, 0.059)\n    ('Cornelia, mater Gracchorum', 0.012, 0.06)\n    ('Bellum Hispaniense [Anonymous]', 0.021, 0.061)\n    ('Bruttedius Niger', 0.016, 0.062)\n    ('Titus Maccius Plautus', 0.027, 0.062)\n    ('Sempronius Asellio', 0.03, 0.064)\n    ('Carmen Devotionis', 0.018, 0.065)\n    ('Publius Ovidius Naso', 0.024, 0.065)\n    ('C. Plinius Caecilius Secundus, Pliny', 0.017, 0.066)\n    ('Aulus Cascellius', 0.0, 0.067)\n    ('Marcus Porcius Cato M.f.M.n.', 0.033, 0.067)\n    ('Titus Lucretius Carus', 0.022, 0.068)\n    ('Sabidius', 0.023, 0.068)\n    ('Lucius Calpurnius Piso Frugi', 0.037, 0.07)\n    ('Titus Annius Luscus', 0.0, 0.071)\n    ('Pupius (?)', 0.0, 0.071)\n    ('Scriptores Historiae Augustae', 0.032, 0.071)\n    ('Publius Cannutius', 0.071, 0.071)\n    ('Turranius Niger', 0.071, 0.071)\n    ('Valerius Maximus', 0.02, 0.073)\n    ('Lucius Annaeus Cornutus', 0.028, 0.073)\n    ('Velleius Paterculus', 0.026, 0.074)\n    ('Quintus Curtius Rufus', 0.021, 0.075)\n    ('Helvius Mancia', 0.033, 0.075)\n    ('Siculus Flaccus', 0.02, 0.076)\n    ('Cornelius Tacitus', 0.025, 0.076)\n    ('Arbonius Silo', 0.0, 0.077)\n    ('Gnaeus Tremelius Scrofa', 0.0, 0.077)\n    ('Aulus Gellius', 0.038, 0.077)\n    ('Aemilius Sura', 0.058, 0.077)\n    ('Publius Alfenus Varus', 0.039, 0.078)\n    ('Gaius Caesius Bassus', 0.04, 0.08)\n    ('Quintus Remmius Palaemon', 0.033, 0.081)\n    ('Lucius Iulius Caesar', 0.0, 0.083)\n    ('Marcus Manilius, Manilius', 0.02, 0.083)\n    ('Aulus Cremutius Cordus', 0.025, 0.083)\n    ('Gaius Aelius Gallus', 0.029, 0.083)\n    ('Hyginus Gromaticus', 0.029, 0.083)\n    ('Marcus Cornelius Fronto', 0.036, 0.084)\n    ('Marcus Valerius Probus', 0.038, 0.084)\n    ('Pseudo-Varro', 0.03, 0.085)\n    ('Terentianus Maurus', 0.036, 0.085)\n    ('Valerius Aedituus', 0.042, 0.085)\n    ('Velius Longus', 0.042, 0.086)\n    ('Cn. Arulenus Caelius Sabinus', 0.048, 0.086)\n    ('P. Cornel. Scipio Aem. Afr.', 0.041, 0.087)\n    ('Tabulae Censoriae', 0.052, 0.087)\n    ('Aulus Caecina', 0.087, 0.087)\n    ('Appius Claudius Caecus', 0.087, 0.087)\n    ('Marcus Tullius Tiro', 0.046, 0.088)\n    ('Anonymi Grammatici', 0.036, 0.089)\n    ('Gaius Asinius Pollio', 0.036, 0.09)\n    ('Lucius Volusius Maecianus', 0.037, 0.09)\n    ('Gaius Plinius Secundus, Pliny', 0.044, 0.09)\n    ('Publilius Optatianus Porfyrius', 0.0, 0.091)\n    ('Carmen Evocationis', 0.01, 0.091)\n    ('Lucius Novius', 0.03, 0.091)\n    ('Annius Florus', 0.038, 0.091)\n    ('Aufustius', 0.045, 0.091)\n    ('Commentarius Anquisit. Sergii', 0.05, 0.091)\n    ('Turnus', 0.091, 0.091)\n    ('Aulus Postumius Albinus', 0.091, 0.091)\n    ('Precatio Terrae', 0.014, 0.092)\n    ('Vitruvius', 0.037, 0.092)\n    ('Quintus Terentius Scaurus', 0.047, 0.092)\n    ('Zeno of Verona', 0.026, 0.093)\n    ('Sextus Iulius Frontinus', 0.03, 0.093)\n    ('Publius Vergilius Maro, Virgil, Vergil', 0.033, 0.093)\n    ('Pomponius Porphyrio', 0.04, 0.093)\n    ('Valerius Antias', 0.058, 0.093)\n    ('Servius Sulpicius Rufus', 0.024, 0.094)\n    ('Marcus Terentius Varro, Varro', 0.046, 0.094)\n    ('Gaius Suetonius Tranquillus', 0.034, 0.096)\n    ('Anonymi de Differentiis [Fronto]', 0.031, 0.097)\n    ('Marcus Annaeus Lucanus', 0.032, 0.098)\n    ('Scribonius Largus', 0.049, 0.098)\n    ('Phaedrus', 0.026, 0.099)\n    ('Ticidas', 0.0, 0.1)\n    ('Publius Rutilius Rufus', 0.0, 0.1)\n    ('Caelius Apicius', 0.044, 0.1)\n    ('Gaius Fannius', 0.064, 0.1)\n    ('Luscius Lanuvinus', 0.1, 0.1)\n    ('Anonymi Fragmenta de Iure Fisci', 0.049, 0.101)\n    ('L. Iunius Moderatus Columella', 0.029, 0.102)\n    ('Publius Papinius Statius', 0.037, 0.102)\n    ('Quintus Claudius Quadrigarius', 0.056, 0.102)\n    ('Aquilius, comoed.', 0.044, 0.103)\n    ('Pompeius Trogus', 0.075, 0.103)\n    ('Silius Italicus', 0.035, 0.104)\n    ('Gaius Ateius Capito', 0.037, 0.104)\n    ('Anonymi Comici et Tragici', 0.06, 0.104)\n    ('Antonius Panurgus', 0.053, 0.105)\n    ('Porcius Licinus', 0.028, 0.106)\n    ('Gaius Valerius Flaccus', 0.042, 0.106)\n    ('Balbus, grom.', 0.036, 0.107)\n    ('Fenestella', 0.038, 0.107)\n    ('Marcus Valerius Martialis', 0.048, 0.107)\n    ('Granius Licinianus', 0.074, 0.107)\n    ('Altercatio Hadr. et Epicteti', 0.06, 0.108)\n    ('M. Valerius Messalla Corvinus', 0.077, 0.108)\n    ('Hyginus, myth.', 0.074, 0.109)\n    ('Publius Nigidius Figulus', 0.054, 0.11)\n    ('Granius Flaccus', 0.077, 0.11)\n    ('M. Aemilius Lepidus Porcina', 0.0, 0.111)\n    ('Tullius Laurea', 0.016, 0.111)\n    ('Sextus Pomponius', 0.111, 0.111)\n    ('Albius Tibullus', 0.033, 0.112)\n    ('Sextus Propertius', 0.045, 0.114)\n    ('Favorinus', 0.039, 0.117)\n    ('Petronius', 0.043, 0.118)\n    ('Lucius Cincius', 0.058, 0.118)\n    ('Commentarii Consulares', 0.051, 0.119)\n    ('Gaius Licinius Macer Calvus', 0.057, 0.119)\n    ('Marcus Aemilius Scaurus', 0.075, 0.119)\n    ('Quintus Ennius', 0.057, 0.12)\n    ('Aemilius Asper', 0.078, 0.12)\n    ('Apuleius Madaurensis', 0.04, 0.121)\n    ('Lucius Coelius Antipater', 0.075, 0.121)\n    ('Lucius Ampelius', 0.084, 0.121)\n    ('Gaius Cornelius Gallus, Gallus', 0.089, 0.122)\n    ('Quintus Horatius Flaccus, Horace', 0.045, 0.123)\n    ('Homerus Latinus', 0.054, 0.124)\n    ('L. Aurel. Avianius Symmachus', 0.07, 0.126)\n    ('Gaius Iulius Hyginus', 0.085, 0.126)\n    ('Claudius Caesar Germanicus', 0.04, 0.129)\n    ('L. Aemilius L.f.M.n. Paulus', 0.037, 0.13)\n    ('Marcus Porcius Cato, Cato', 0.061, 0.131)\n    ('Gavius Bassus', 0.08, 0.131)\n    ('Gaius Titius', 0.017, 0.132)\n    ('Decimus Iunius Iuvenalis, Juvenal', 0.052, 0.133)\n    ('Sulpicia, Caleni uxor', 0.052, 0.133)\n    ('Sextus Pompeius Festus', 0.079, 0.133)\n    ('Gaius Valerius Catullus', 0.056, 0.134)\n    ('Parthenius Presbyter', 0.072, 0.134)\n    ('Lucius Arruntius', 0.027, 0.135)\n    ('Marcus Furius Bibaculus', 0.073, 0.136)\n    ('Didascaliae et Per. in Terentium', 0.078, 0.136)\n    ('Albinovanus Pedo', 0.034, 0.137)\n    ('Marcus Iunius Gracchanus', 0.092, 0.137)\n    ('Albinus, poet.', 0.069, 0.138)\n    ('Sextus Turpilius', 0.064, 0.139)\n    ('Fragmenta Bobiensia', 0.074, 0.139)\n    ('Appendix Vergiliana', 0.05, 0.142)\n    ('Caecilius Statius', 0.083, 0.142)\n    ('Marcus Duronius', 0.024, 0.143)\n    ('Lucius Verginius Rufus', 0.071, 0.143)\n    ('Mummius', 0.071, 0.143)\n    ('Lucius Neratius Priscus', 0.095, 0.143)\n    ('Mimi Poetarum Incertorum', 0.112, 0.143)\n    ('Marcus Calidius', 0.143, 0.143)\n    ('Lucius Varius Rufus', 0.061, 0.144)\n    ('Argum. Aen. et Tetrast.', 0.071, 0.144)\n    ('Gaius Lucilius', 0.08, 0.144)\n    ('Gaius Licinius Macer', 0.081, 0.145)\n    ('Iulius Atherianus', 0.081, 0.145)\n    ('Lucius Afranius', 0.069, 0.147)\n    ('Pomponius Mela', 0.094, 0.147)\n    ('Hostius', 0.074, 0.148)\n    ('Didascaliae et Argum. in Plautum', 0.077, 0.148)\n    ('Marianus', 0.05, 0.15)\n    ('Lucius Cornelius Sisenna', 0.075, 0.15)\n    ('Marcus Antistius Labeo', 0.103, 0.15)\n    ('Laus Pisonis', 0.047, 0.152)\n    ('Hilarius Arelatensis', 0.077, 0.154)\n    ('Vita Iuvenalis', 0.083, 0.154)\n    ('Gaius Cassius Hemina', 0.084, 0.155)\n    ('Paulus Quaestor', 0.105, 0.158)\n    ('Gaius Memmius L. f.', 0.045, 0.159)\n    ('Philumenus medicus', 0.085, 0.159)\n    ('Domitius Marsus', 0.128, 0.16)\n    ('Sextus (vel Spurius) Ennius', 0.113, 0.161)\n    ('Priapea', 0.076, 0.162)\n    ('Quintus Aelius Tubero', 0.037, 0.163)\n    ('Bucolica Einsidlensia', 0.067, 0.166)\n    ('Lucius Accius', 0.085, 0.166)\n    ('Publius Aufidius Namusa', 0.0, 0.167)\n    ('Manius Manilius', 0.076, 0.167)\n    ('Ninnius Crassus', 0.083, 0.167)\n    ('Quintus Servilius Caepio', 0.111, 0.167)\n    ('Quintus Valerius Soranus', 0.172, 0.172)\n    ('Titus Calpurnius Siculus', 0.065, 0.174)\n    ('Grattius', 0.071, 0.175)\n    ('Marcus Verrius Flaccus', 0.128, 0.179)\n    ('Marcus Pacuvius', 0.095, 0.181)\n    ('Q. Pompeius Q.f.Q.n. Rufus', 0.0, 0.182)\n    ('Marcus Caelius Rufus', 0.067, 0.187)\n    ('Decimus Iunius Silanus', 0.083, 0.19)\n    ('Anonymi Epici et Lyrici', 0.097, 0.192)\n    ('Publius Pomponius Secundus', 0.135, 0.192)\n    ('Papinius, epigram.', 0.192, 0.192)\n    ('Aulus Persius Flaccus', 0.082, 0.194)\n    ('Chalcidius', 0.063, 0.198)\n    ('Titinius', 0.1, 0.198)\n    ('Flavius Caper', 0.115, 0.198)\n    ('Saserna', 0.086, 0.2)\n    ('Ablabius', 0.1, 0.2)\n    ('Gaius Scribonius Curio pater', 0.1, 0.2)\n    ('Gaius Oppius', 0.163, 0.2)\n    ('C. Iul. Caes. Augustus Octavianus', 0.168, 0.205)\n    ('Caesellius Vindex', 0.169, 0.205)\n    ('Quintus Serenus (Sammonicus)', 0.075, 0.206)\n    ('Gnaeus Naevius', 0.117, 0.206)\n    ('Iulius Valerius', 0.111, 0.207)\n    ('Sacra Argeorum', 0.174, 0.209)\n    ('Caelius Aurelianus', 0.105, 0.211)\n    ('Hadrianus', 0.087, 0.212)\n    ('Alfius Avitus', 0.095, 0.214)\n    ('Q. Fabius Maximus Servilianus', 0.143, 0.214)\n    ('Licinius Imbrex', 0.214, 0.214)\n    ('Cornelius Severus', 0.102, 0.215)\n    ('Numitorius', 0.174, 0.217)\n    ('Veranius', 0.119, 0.218)\n    ('Sinnius Capito', 0.136, 0.22)\n    ('Lucius Pomponius Bononiensis', 0.129, 0.221)\n    ('Pompilius', 0.056, 0.222)\n    ('Annianus', 0.133, 0.222)\n    ('P. Terentius Varro Atacinus', 0.117, 0.224)\n    ('Tarquitius Priscus', 0.134, 0.224)\n    ('Decimus Laberius', 0.155, 0.225)\n    ('Commentarii Augurum', 0.205, 0.227)\n    ('Iulius Modestus', 0.138, 0.231)\n    ('Novius, comoed.', 0.142, 0.232)\n    ('Gnaeus Gellius', 0.181, 0.236)\n    ('Q. Aurelius Memmius Symmachus', 0.127, 0.24)\n    ('Santra', 0.13, 0.241)\n    ('Q. Pompeius Q.f.A.n. Rufus', 0.0, 0.25)\n    ('Marcus Aurelius', 0.0, 0.25)\n    ('Titus Quinctius Atta', 0.098, 0.25)\n    ('Valerius, comoed.', 0.125, 0.25)\n    ('Lucius Livius Andronicus', 0.146, 0.25)\n    ('Carmen Arvale', 0.185, 0.25)\n    ('Gaius Valgius Rufus', 0.143, 0.255)\n    ('Iuventius, comoed.', 0.163, 0.256)\n    ('Gaius Iulius Caesar Strabo', 0.16, 0.26)\n    ('Quintus Hortensius Hortalus', 0.158, 0.263)\n    ('Aemilius Macer', 0.117, 0.266)\n    ('Carmen de Bello Aegyptiaco', 0.248, 0.274)\n    ('Fabius Pictor', 0.195, 0.276)\n    ('Gracchus, trag.', 0.0, 0.278)\n    ('Aulus Furius Antias', 0.194, 0.278)\n    ('Dorcatius', 0.071, 0.286)\n    ('Manilius, poet.', 0.095, 0.286)\n    ('Cornificius Gallus', 0.143, 0.286)\n    ('Gnaeus Matius', 0.148, 0.287)\n    ('Egnatius', 0.235, 0.294)\n    ('Septimius Serenus', 0.189, 0.3)\n    ('Lucius Orbilius Pupillus', 0.2, 0.3)\n    ('Gaius Helvius Cinna', 0.195, 0.301)\n    ('Sueius', 0.204, 0.32)\n    ('Gaius Cilnius Maecenas', 0.187, 0.327)\n    ('Cornelius Epicadus', 0.0, 0.333)\n    ('Cn. Cornel. Lentulus Gaetulicus', 0.167, 0.333)\n    ('Rabirius', 0.233, 0.333)\n    ('Gnaeus Marcius vates', 0.25, 0.333)\n    ('Clodius Tuscus', 0.333, 0.333)\n    ('Laevius', 0.236, 0.348)\n    ('Quintus Cornificius', 0.143, 0.357)\n    ('Servius Clodius', 0.156, 0.375)\n    ('Aprissius (?)', 0.25, 0.375)\n    ('Iulius Montanus', 0.108, 0.378)\n    ('Cornificius Longus', 0.323, 0.387)\n    ('Gaius Clodius Licinus', 0.056, 0.389)\n    ('L. Aelius Praeconinus Stilo', 0.312, 0.396)\n    ('Aurelius Opillus', 0.349, 0.397)\n    ('Gnaeus Domitius Ahenobarbus', 0.0, 0.4)\n    ('Naevius, iunior', 0.1, 0.4)\n    ('Quintus Mucius Scaevola', 0.4, 0.4)\n    ('Imp. Marcus Ulpius Traianus, Trajan', 0.4, 0.4)\n    ('Gannius', 0.158, 0.421)\n    ('Sextilius Ena', 0.143, 0.429)\n    ('Imperator Nero', 0.294, 0.441)\n    ('Staberius Eros', 0.222, 0.444)\n    ('Gaius Licinius Mucianus', 0.333, 0.481)\n    ('Fabius Dossennus', 0.25, 0.5)\n    ('Attius Labeo', 0.333, 0.5)\n    ('Lentulus, mimus', 0.357, 0.5)\n    ('Titius, gram.', 0.5, 0.5)\n    ('Volumnius', 0.5, 0.5)\n    ('Sextus Paconianus', 0.4, 0.55)\n    ('Cloatius Verus', 0.525, 0.57)\n    ('Lucius Ateius Praetextatus', 0.429, 0.571)\n    ('Scaevus Memor', 0.167, 0.667)\n\n\n\n```python\nauthor_results = []\nfor author in author_index:\n    files = get_phi5_author_files(author, author_index)\n    if len(files) >= 3:\n#     print(author, results_map[author])\n        author_results.append((author, results_map[author]) )\n\nauthor_results.sort(key=lambda x: x[1][1])    \nfor tmp in author_results:\n    print(tmp)\n    \n# the values analogous to Cicero are: (0.02892407263780054, 0.008905886443261747)    \n# ~ 0.03  and  0.01 # we can tolerate some distance above this baseline, 2x, 3x, depends\n# Results are mapped into Cicero's Vocabulary space\n# Table below:\n# Author\n# Probability of encountering a word once that we've seen in the author previously in a different lemmatized form\n# Probability of seeing a truly new word once in this authors corpus \n```\n\n    ('Quintus Asconius Pedianus', (0.01, 0.03))\n    ('Gaius, iur., Gaius', (0.011, 0.035))\n    ('Titus Livius, Livy', (0.011, 0.039))\n    ('Marcus Fabius Quintilianus', (0.009, 0.042))\n    ('Gaius Iulius Caesar, Caesar', (0.016, 0.046))\n    ('Lucius Annaeus Seneca senior', (0.016, 0.052))\n    ('Lucius Annaeus Seneca iunior', (0.013, 0.054))\n    ('Aulus Cornelius Celsus', (0.017, 0.056))\n    ('Publius Terentius Afer, Terence', (0.029, 0.059))\n    ('Gaius Sallustius Crispus', (0.021, 0.059))\n    ('Maurus Servius Honoratus, Servius', (0.025, 0.059))\n    ('Titus Maccius Plautus', (0.027, 0.062))\n    ('Publius Ovidius Naso', (0.024, 0.065))\n    ('C. Plinius Caecilius Secundus, Pliny', (0.017, 0.066))\n    ('Titus Lucretius Carus', (0.022, 0.068))\n    ('Scriptores Historiae Augustae', (0.032, 0.071))\n    ('Cornelius Tacitus', (0.025, 0.076))\n    ('Gaius Caesius Bassus', (0.04, 0.08))\n    ('Hyginus Gromaticus', (0.029, 0.083))\n    ('Marcus Valerius Probus', (0.038, 0.084))\n    ('Marcus Cornelius Fronto', (0.036, 0.084))\n    ('Gaius Asinius Pollio', (0.036, 0.09))\n    ('Annius Florus', (0.038, 0.091))\n    ('Quintus Terentius Scaurus', (0.047, 0.092))\n    ('Publius Vergilius Maro, Virgil, Vergil', (0.033, 0.093))\n    ('Pomponius Porphyrio', (0.04, 0.093))\n    ('Sextus Iulius Frontinus', (0.03, 0.093))\n    ('Marcus Terentius Varro, Varro', (0.046, 0.094))\n    ('Gaius Suetonius Tranquillus', (0.034, 0.096))\n    ('Caelius Apicius', (0.044, 0.1))\n    ('Publius Papinius Statius', (0.037, 0.102))\n    ('Anonymi Comici et Tragici', (0.06, 0.104))\n    ('Quintus Ennius', (0.057, 0.12))\n    ('Apuleius Madaurensis', (0.04, 0.121))\n    ('Quintus Horatius Flaccus, Horace', (0.045, 0.123))\n    ('Claudius Caesar Germanicus', (0.04, 0.129))\n    ('Marcus Porcius Cato, Cato', (0.061, 0.131))\n    ('Didascaliae et Per. in Terentium', (0.078, 0.136))\n    ('Fragmenta Bobiensia', (0.074, 0.139))\n    ('Appendix Vergiliana', (0.05, 0.142))\n    ('Argum. Aen. et Tetrast.', (0.071, 0.144))\n    ('Didascaliae et Argum. in Plautum', (0.077, 0.148))\n    ('Lucius Accius', (0.085, 0.166))\n    ('Anonymi Epici et Lyrici', (0.097, 0.192))\n    ('C. Iul. Caes. Augustus Octavianus', (0.168, 0.205))\n    ('Gnaeus Naevius', (0.117, 0.206))\n    ('Lucius Livius Andronicus', (0.146, 0.25))\n\n\n#### Translating the statistics:\n* Cicero: # ~ 0.03  and  0.01  \n* Gaius Iulius Caesar, Caesar (0.016170899832329378, 0.0464137117307334)\n\n#### If one were to find a new page (100 words) of Cicero, one would expect to find: \n* 3 words that Cicero had previously used, but in novel inflected forms \n    * (root words that we know have been used by Cicero, but without previous examples of that particular inflection)\n* 1 word hapax legomena to the author\n    * Not a global hapax legomena, but one that we have no record of occuring in Cicero before (in any inflected form).\n#### if one were to take a page from Caesar and claim it was a new page of Cicero, one would expect to find:\n* 2 words that Cicero had previously used but now in a novel inflected form.\n* 5 words that Cicero had never used (in any inflected form).\n\n\n\n```python\n# Let's look at Cicero's near contemporaries, and see if the individual works come closer to \n# matching Cicero's language in terms of Probability Distributions\ncandidates = ['Gaius Iulius Caesar, Caesar', \n'C. Iul. Caes. Augustus Octavianus',  \n'Publius Vergilius Maro, Virgil, Vergil',  \n'Gaius Suetonius Tranquillus', \n'Marcus Terentius Varro, Varro', \n'Cornelius Tacitus', \n'Titus Livius, Livy', \n'Lucius Annaeus Seneca senior', \n'Quintus Horatius Flaccus, Horace',  \n'Gaius Sallustius Crispus', \n'Titus Lucretius Carus', \n'Lucius Annaeus Seneca iunior']\n```\n\n\n```python\nresults = []\n\nfor author in candidates:\n    files = get_phi5_author_files(author, author_index)\n    #     cicero_lemmas, cicero_inflected_words = get_word_counts(cicero_files)    \n    for file in files:\n        author_inflected_words, author_lemmas = get_word_counts([file])    \n        author_words = set(author_lemmas.keys())\n        cicero_words = set(cicero_lemmas.keys())\n        common = author_words & cicero_words\n        author_uniq  = author_words - common \n        P_one_x_lemma_unigram = round(len(author_uniq) / sum(author_lemmas.values()),3)\n        author_words = set(author_inflected_words.keys())\n        cicero_words = set(cicero_inflected_words.keys())\n        common = author_words & cicero_words\n        author_uniq  = author_words - common \n        P_one_x_inflected_unigram = round(len(author_uniq) / sum(author_inflected_words.values()), 3)\n        results.append((author, file, sum(author_inflected_words.values()), P_one_x_inflected_unigram, P_one_x_lemma_unigram))\n```\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n      0%|          | 0/1 [00:00<?, ?files/s]\n\n\n\n```python\nfor author, _, count, P_one_x_inflected_unigram, P_one_x_lemma_unigram in results:\n    if P_one_x_lemma_unigram != 0.0:\n        print (author, count, P_one_x_inflected_unigram, P_one_x_lemma_unigram)\n# Cicero's values for:\n# Probability of unigrams that occur once, Probability of a lemmatized unigram occurring once\n# (0.02892407263780054, 0.008905886443261747)  Cicero's values for\n```\n\n    Gaius Iulius Caesar, Caesar 286 0.0034965034965034965 0.006993006993006993\n    Gaius Iulius Caesar, Caesar 134 0.08955223880597014 0.13432835820895522\n    Gaius Iulius Caesar, Caesar 386 0.0025906735751295338 0.0025906735751295338\n    Gaius Iulius Caesar, Caesar 49 0.061224489795918366 0.20408163265306123\n    Gaius Iulius Caesar, Caesar 33437 0.014923587642432037 0.0506923468014475\n    Gaius Iulius Caesar, Caesar 179 0.027932960893854747 0.061452513966480445\n    Gaius Iulius Caesar, Caesar 46014 0.018603033859260223 0.05059329769200678\n    C. Iul. Caes. Augustus Octavianus 2398 0.26980817347789826 0.2964970809007506\n    C. Iul. Caes. Augustus Octavianus 85 0.07058823529411765 0.12941176470588237\n    C. Iul. Caes. Augustus Octavianus 1424 0.07935393258426966 0.12289325842696629\n    C. Iul. Caes. Augustus Octavianus 33 0.030303030303030304 0.12121212121212122\n    C. Iul. Caes. Augustus Octavianus 69 0.11594202898550725 0.21739130434782608\n    C. Iul. Caes. Augustus Octavianus 338 0.08875739644970414 0.1301775147928994\n    C. Iul. Caes. Augustus Octavianus 767 0.07953063885267275 0.1290743155149935\n    Publius Vergilius Maro, Virgil, Vergil 67238 0.03246675986793182 0.09195692911746334\n    Publius Vergilius Maro, Virgil, Vergil 14849 0.05912856084584821 0.16149235638763554\n    Publius Vergilius Maro, Virgil, Vergil 5781 0.05794845182494378 0.13527071440927174\n    Gaius Suetonius Tranquillus 4317 0.0463284688441047 0.09520500347463516\n    Gaius Suetonius Tranquillus 2274 0.06904133685136324 0.14160070360598065\n    Gaius Suetonius Tranquillus 596 0.07885906040268456 0.12583892617449666\n    Gaius Suetonius Tranquillus 1660 0.03855421686746988 0.09397590361445783\n    Gaius Suetonius Tranquillus 92 0.08695652173913043 0.18478260869565216\n    Gaius Suetonius Tranquillus 72536 0.03228741590382707 0.09651759126502703\n    Marcus Terentius Varro, Varro 360 0.23055555555555557 0.3055555555555556\n    Marcus Terentius Varro, Varro 1347 0.06087602078693393 0.11729769858945806\n    Marcus Terentius Varro, Varro 36323 0.039451587148638605 0.09470583376923712\n    Marcus Terentius Varro, Varro 115 0.034782608695652174 0.06086956521739131\n    Marcus Terentius Varro, Varro 354 0.08757062146892655 0.1327683615819209\n    Marcus Terentius Varro, Varro 167 0.11976047904191617 0.16167664670658682\n    Marcus Terentius Varro, Varro 40767 0.04623837908111953 0.08455368312605784\n    Marcus Terentius Varro, Varro 16 0.0625 0.125\n    Marcus Terentius Varro, Varro 6577 0.11038467386346358 0.1947696518169378\n    Marcus Terentius Varro, Varro 134 0.1044776119402985 0.15671641791044777\n    Marcus Terentius Varro, Varro 1052 0.03136882129277566 0.06844106463878327\n    Marcus Terentius Varro, Varro 99 0.1111111111111111 0.15151515151515152\n    Marcus Terentius Varro, Varro 108 0.08333333333333333 0.1111111111111111\n    Marcus Terentius Varro, Varro 1990 0.07135678391959799 0.13919597989949747\n    Marcus Terentius Varro, Varro 34 0.029411764705882353 0.058823529411764705\n    Marcus Terentius Varro, Varro 880 0.09659090909090909 0.15454545454545454\n    Cornelius Tacitus 6889 0.03512846566990855 0.1029176948758891\n    Cornelius Tacitus 9421 0.016771043413650356 0.0633690691009447\n    Cornelius Tacitus 5689 0.04605378801195289 0.11706802601511689\n    Cornelius Tacitus 91347 0.02934962286665134 0.0882897084742794\n    Cornelius Tacitus 52847 0.030313925104547088 0.09620224421443034\n    Titus Livius, Livy 1284 0.14330218068535824 0.16978193146417445\n    Titus Livius, Livy 20763 0.034484419399894044 0.06530848143331888\n    Titus Livius, Livy 1275 0.054901960784313725 0.10823529411764705\n    Titus Livius, Livy 516063 0.010702181710372571 0.039026242919953574\n    Lucius Annaeus Seneca senior 68556 0.01849582822801797 0.05808390221133088\n    Lucius Annaeus Seneca senior 19571 0.012365234275203106 0.057227530529865615\n    Lucius Annaeus Seneca senior 10322 0.030323580701414454 0.08002325130788607\n    Lucius Annaeus Seneca senior 24 0.041666666666666664 0.08333333333333333\n    Quintus Horatius Flaccus, Horace 14601 0.044517498801451956 0.11910143140880762\n    Quintus Horatius Flaccus, Horace 10120 0.04189723320158103 0.12282608695652174\n    Quintus Horatius Flaccus, Horace 3214 0.04169259489732421 0.12258867454884878\n    Quintus Horatius Flaccus, Horace 337 0.06528189910979229 0.1572700296735905\n    Quintus Horatius Flaccus, Horace 3084 0.07652399481193256 0.19649805447470817\n    Quintus Horatius Flaccus, Horace 13669 0.06511083473553296 0.16826395493452337\n    Gaius Sallustius Crispus 1210 0.05206611570247934 0.11735537190082644\n    Gaius Sallustius Crispus 4223 0.026284631778356618 0.07861709685058016\n    Gaius Sallustius Crispus 212 0.15566037735849056 0.20754716981132076\n    Gaius Sallustius Crispus 4080 0.015931372549019607 0.050490196078431374\n    Gaius Sallustius Crispus 4047 0.05114899925871016 0.12725475660983446\n    Gaius Sallustius Crispus 21650 0.01861431870669746 0.05796766743648961\n    Gaius Sallustius Crispus 10866 0.01582919197496779 0.05135284373274434\n    Gaius Sallustius Crispus 720 0.0125 0.05\n    Titus Lucretius Carus 703 0.05689900426742532 0.09103840682788052\n    Titus Lucretius Carus 67 0.08955223880597014 0.208955223880597\n    Titus Lucretius Carus 50559 0.02177653830178603 0.06762396408156807\n    Lucius Annaeus Seneca iunior 7208 0.04869589345172031 0.14983351831298558\n    Lucius Annaeus Seneca iunior 3037 0.057951926243002966 0.10997695093842608\n    Lucius Annaeus Seneca iunior 5261 0.02033833871887474 0.08705569283406196\n    Lucius Annaeus Seneca iunior 5686 0.048012662680267326 0.1429827646851917\n    Lucius Annaeus Seneca iunior 76269 0.012403466677155856 0.06980555664817947\n    Lucius Annaeus Seneca iunior 5959 0.04967276388655815 0.15774458801812385\n    Lucius Annaeus Seneca iunior 5592 0.0536480686695279 0.14914163090128754\n    Lucius Annaeus Seneca iunior 45899 0.011459944661103727 0.0556439138107584\n    Lucius Annaeus Seneca iunior 4147 0.027489751627682663 0.10851217747769472\n    Lucius Annaeus Seneca iunior 6853 0.03896103896103896 0.11688311688311688\n    Lucius Annaeus Seneca iunior 48052 0.01783484558395072 0.07446100058270207\n    Lucius Annaeus Seneca iunior 8316 0.015993265993265993 0.06962481962481963\n    Lucius Annaeus Seneca iunior 120945 0.014089048741163339 0.058663028649386086\n    Lucius Annaeus Seneca iunior 7736 0.03968459152016546 0.13094622543950363\n    Lucius Annaeus Seneca iunior 11471 0.04010112457501525 0.11550867404759829\n    Lucius Annaeus Seneca iunior 6320 0.034968354430379746 0.13069620253164557\n\n\n\n```python\naquinas = glob(\"../data/aquinas/*.txt\")\nlen(aquinas)\n```\n\n\n\n\n    612\n\n\n\n\n```python\nresults = []\nauthor='aquinas'\nfor file in tqdm(aquinas):\n    author_inflected_words, author_lemmas = get_word_counts([file])    \n    author_words = set(author_lemmas.keys())\n    cicero_words = set(cicero_lemmas.keys())\n    common = author_words & cicero_words\n    author_uniq  = author_words - common \n    P_one_x_lemma_unigram = len(author_uniq) / sum(author_lemmas.values())\n    author_words = set(author_inflected_words.keys())\n    cicero_words = set(cicero_inflected_words.keys())\n    common = author_words & cicero_words\n    author_uniq  = author_words - common \n    P_one_x_inflected_unigram = len(author_uniq) / sum(author_inflected_words.values())\n    results.append((author, file, sum(author_inflected_words.values()), P_one_x_inflected_unigram, P_one_x_lemma_unigram))\n    if P_one_x_inflected_unigram <= 0.074:\n        with open(file, 'rt') as fin:\n            text = fin.read()\n            text = text.replace(\"-\\n\", \"\")\n            text = text.replace(\"\\n\", \" \")\n            text = aeoe_replacer.replace(jv_replacer.replace(text))\n            filename = file[file.rfind('/')+1:]\n            with open(f\"cicero_training_corpus_aquinas/{filename}\", 'wt') as fout:\n                for sent in sent_toker.tokenize(text):\n                    sent = dehyphenate(sent) # because it's Phi5\n                    sent = swallow_braces(sent)\n                    sent = swallow_square_brackets(sent)\n                    sent = disappear_round_brackets(sent)\n                    sent = swallow_obelized_words(sent)\n                    sent = disappear_angle_brackets(sent)            \n    #                         sent = drop_punct(sent)\n                    sent = normalize_accents(sent)\n                    sentence = [truecase(word, case_counts)\n                                for word in toker.tokenize(sent) \n                                if not word.isnumeric()]\n                    fout.write(f\"{' '.join(sentence)}\\n\")\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 612/612 [14:49<00:00,  1.45s/it]\n\n\n\n```python\nresults[:3]\n```\n\n\n\n\n    [('aquinas',\n      '../data/aquinas/ccm0.txt',\n      1134,\n      0.03262786596119929,\n      0.06437389770723104),\n     ('aquinas',\n      '../data/aquinas/cmt00b.txt',\n      2132,\n      0.06894934333958724,\n      0.11538461538461539),\n     ('aquinas',\n      '../data/aquinas/cih00.txt',\n      2813,\n      0.04550302168503377,\n      0.0810522573764664)]\n\n\n\n# Examine Tesserae Corpus Docs\n\n\n```python\ntesserae = get_corpus_reader(corpus_name='latin_text_tesserae', language='latin')\nfiles =tesserae.fileids()\n\nresults = []\ntesserae = get_corpus_reader(corpus_name='latin_text_tesserae', language='latin')\ncase_counts = Counter()\njv_replacer = JVReplacer()\naeoe_replacer = AEOEReplacer()\ntoker = WordTokenizer('latin')\nsent_toker = SentenceTokenizer()\nlemmatizer = LemmaReplacer('latin')\n\nfor file in tqdm(tesserae.fileids(), total=len(tesserae.fileids())): \n    author_inflected_words, author_lemmas = get_word_counts([ f\"/Users/todd/cltk_data/latin/text/latin_text_tesserae/{file}\" ])    \n    author_words = set(author_lemmas.keys())\n    cicero_words = set(cicero_lemmas.keys())\n    common = author_words & cicero_words\n    author_uniq  = author_words - common \n    P_one_x_lemma_unigram = len(author_uniq) / sum(author_lemmas.values())\n    author_words = set(author_inflected_words.keys())\n    cicero_words = set(cicero_inflected_words.keys())\n    common = author_words & cicero_words\n    author_uniq  = author_words - common \n    P_one_x_inflected_unigram = len(author_uniq) / sum(author_inflected_words.values())\n    results.append((author, file, sum(author_inflected_words.values()), P_one_x_inflected_unigram, P_one_x_lemma_unigram))\n    if P_one_x_inflected_unigram <= 0.074:        \n        filename = file[file.rfind('/')+1:]\n        with open(f\"cicero_training_corpus_tesserae/{filename}\", 'wt') as fout:\n            for sentence in tesserae.sents(file):\n                sentence = aeoe_replacer.replace(jv_replacer.replace((sentence)))\n                sentence = normalize_accents(sentence)\n                sentence = accept_editorial(sentence)\n#         for token in toker.tokenize(sent):\n#             case_counts.update({token:1})\n                for sent in sent_toker.tokenize(sentence):\n                    sent = dehyphenate(sent) # because it's Phi5\n                    sent = swallow_braces(sent)\n                    sent = swallow_square_brackets(sent)\n                    sent = disappear_round_brackets(sent)\n                    sent = swallow_obelized_words(sent)\n                    sent = disappear_angle_brackets(sent)            \n        #                         sent = drop_punct(sent)\n                    sent = normalize_accents(sent)\n                    sent2 = [truecase(word, case_counts)\n                                for word in toker.tokenize(sent) \n                                if not word.isnumeric()]\n                    fout.write(f\"{' '.join(sent2)}\\n\")\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 762/762 [15:13<00:00,  1.20s/it]  \n\n\n\n```python\nauthors, files, sizes, lemma_counts, inflected_counts = zip(*results)\n\n np.mean(inflected_counts), np.std(inflected_counts)\n```\n\n\n\n\n    (0.040614957083179186, 0.07611207700363683)\n\n\n\n\n```python\nplt.hist( inflected_counts, bins=10)\n```\n\n\n```python\nplt.hist(lemma_counts, bins=10)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "31b549adc64a84d967001548dcb1975f52f02a40", "size": 407557, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "probabilistic_language_modeling/cicero_training_corpus_analysis.ipynb", "max_stars_repo_name": "todd-cook/ML-You-Can-Use", "max_stars_repo_head_hexsha": "45c86d6f70b7d216c421ea005e022f5d6f5501cd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2019-02-25T09:57:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T17:25:43.000Z", "max_issues_repo_path": "probabilistic_language_modeling/cicero_training_corpus_analysis.ipynb", "max_issues_repo_name": "todd-cook/ML-You-Can-Use", "max_issues_repo_head_hexsha": "45c86d6f70b7d216c421ea005e022f5d6f5501cd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-01-09T08:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T00:07:08.000Z", "max_forks_repo_path": "probabilistic_language_modeling/cicero_training_corpus_analysis.ipynb", "max_forks_repo_name": "todd-cook/ML-You-Can-Use", "max_forks_repo_head_hexsha": "45c86d6f70b7d216c421ea005e022f5d6f5501cd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-01-28T18:35:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T21:11:08.000Z", "avg_line_length": 46.6579278764, "max_line_length": 25272, "alphanum_fraction": 0.6711355712, "converted": true, "num_tokens": 57282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3415825128436339, "lm_q2_score": 0.09670579589946719, "lm_q1q2_score": 0.03303300876988359}}
{"text": "# Using Numba for GPUs\n\n*Vasileios Karakasis, CSCS*\n\nYou may use Numba to generate GPU code from high-level Python functions. Both CUDA and ROC GPUs (NVIDIA and AMD, respectively) are supported, but we are going to focus only on the CUDA capabilities of Numba.\n\nThere is an almost one-to-one mapping between the Numba high-level Python abstractions and the different CUDA constructs. This practically means that, as a programmer, you need to take care explicitly of the host/device memory management and you need to be aware of the CUDA programming model.\n\nThis demo will teach you to write your first CUDA kernels using Numba. It will cover the basic CUDA programming principles, but it should be enough to kick start you in GPU programming. More specifically, we will cover the following topics:\n\n- Writing a GPU kernel\n- Moving data to/from the GPU.\n- Spawning a GPU kernel\n- Profiling a GPU kernel\n- Optimizing memory accesses\n- Making use of the shared memory\n\nWe will not cover CUDA streams.\n\n## Verify that Numba sees the GPU and understands CUDA\n\nFirst thing is to check if Numba can detect the GPU. You can achieve this by running the `numba` executable that comes with Numba's installation:\n\n\n```python\n!numba -s\n```\n\n    System info:\n    --------------------------------------------------------------------------------\n    __Time Stamp__\n    2019-11-13 10:37:30.961347\n    \n    __Hardware Information__\n    Machine                                       : x86_64\n    CPU Name                                      : haswell\n    Number of accessible CPU cores                : 24\n    Listed accessible CPUs cores                  : 0-23\n    CFS restrictions                              : Information not available\n    CPU Features                                  : \n    64bit aes avx avx2 bmi bmi2 cmov cx16 f16c fma fsgsbase invpcid lzcnt mmx movbe\n    pclmul popcnt rdrnd sahf sse sse2 sse3 sse4.1 sse4.2 ssse3 xsave xsaveopt\n    \n    __OS Information__\n    Platform                                      : Linux-4.12.14-150.17_5.0.85-cray_ari_c-x86_64-with-glibc2.9\n    Release                                       : 4.12.14-150.17_5.0.85-cray_ari_c\n    System Name                                   : Linux\n    Version                                       : #1 SMP Thu Aug 22 18:29:02 UTC 2019 (24c42de)\n    OS specific info                              : \n    glibc info                                    : glibc 2.9\n    \n    __Python Information__\n    Python Compiler                               : GCC 7.2.0\n    Python Implementation                         : CPython\n    Python Version                                : 3.6.2\n    Python Locale                                 : en_US UTF-8\n    \n    __LLVM information__\n    LLVM version                                  : 8.0.0\n    \n    __CUDA Information__\n    Found 1 CUDA devices\n    id 0    b'Tesla P100-PCIE-16GB'                              [SUPPORTED]\n                          compute capability: 6.0\n                               pci device id: 0\n                                  pci bus id: 2\n    Summary:\n    \t1/1 devices are supported\n    CUDA driver version                           : 10010\n    CUDA libraries:\n    Finding cublas from Conda environment\n    \tnamed  libcublas.so.10.2.1.243\n    \ttrying to open library...\tok\n    Finding cusparse from Conda environment\n    \tnamed  libcusparse.so.10.3.0.243\n    \ttrying to open library...\tok\n    Finding cufft from Conda environment\n    \tnamed  libcufft.so.10.1.1.243\n    \ttrying to open library...\tok\n    Finding curand from Conda environment\n    \tnamed  libcurand.so.10.1.1.243\n    \ttrying to open library...\tok\n    Finding nvvm from Conda environment\n    \tnamed  libnvvm.so.3.3.0\n    \ttrying to open library...\tok\n    Finding libdevice from Conda environment\n    \tsearching for compute_20...\tok\n    \tsearching for compute_30...\tok\n    \tsearching for compute_35...\tok\n    \tsearching for compute_50...\tok\n    \n    __ROC Information__\n    ROC available                                 : False\n    Error initialising ROC due to                 : No ROC toolchains found.\n    No HSA Agents found, encountered exception when searching:\n    Error at driver init: \n    NUMBA_HSA_DRIVER /opt/rocm/lib/libhsa-runtime64.so is not a valid file path.  Note it must be a filepath of the .so/.dll/.dylib or the driver:\n    \n    __SVML Information__\n    SVML state, config.USING_SVML                 : False\n    SVML library found and loaded                 : False\n    llvmlite using SVML patched LLVM              : True\n    SVML operational                              : False\n    \n    __Threading Layer Information__\n    TBB Threading layer available                 : True\n    OpenMP Threading layer available              : True\n    Workqueue Threading layer available           : True\n    \n    __Numba Environment Variable Information__\n    None set.\n    \n    __Conda Information__\n    conda_build_version                           : not installed\n    conda_env_version                             : 4.7.12\n    platform                                      : linux-64\n    python_version                                : 3.6.2.final.0\n    root_writable                                 : False\n    \n    __Current Conda Env__\n    _libgcc_mutex             0.1                        main  \n    asn1crypto                1.2.0                    py36_0  \n    backcall                  0.1.0                    py36_0    anaconda\n    blas                      1.0                         mkl  \n    bokeh                     1.4.0                    py36_0  \n    ca-certificates           2019.10.16                    0  \n    cairo                     1.14.12              h8948797_3  \n    certifi                   2019.9.11                py36_0  \n    cffi                      1.13.1           py36h2e261b9_0    anaconda\n    chardet                   3.0.4                 py36_1003  \n    click                     7.0                      py36_0  \n    cloudpickle               1.2.2                      py_0  \n    conda                     4.7.12                   py36_0    conda-forge\n    conda-package-handling    1.6.0            py36h7b6447c_0  \n    cryptography              2.3.1            py36hc365091_0  \n    cudatoolkit               10.1.243             h6bb024c_0  \n    cudnn                     7.6.4                cuda10.1_0    anaconda\n    cupy                      6.0.0            py36hc0ce245_0    anaconda\n    cupy-cuda101              6.5.0                    pypi_0    pypi\n    cycler                    0.10.0                     py_2    conda-forge\n    cython                    0.29.13          py36he6710b0_0    anaconda\n    cytoolz                   0.10.0           py36h7b6447c_0  \n    dask                      2.6.0                      py_0  \n    dask-core                 2.6.0                      py_0  \n    dbus                      1.13.2               h714fa37_1  \n    decorator                 4.4.1                      py_0    anaconda\n    distributed               2.6.0                      py_0  \n    expat                     2.2.5             he1b5a44_1004    conda-forge\n    fastrlock                 0.4              py36he6710b0_0    anaconda\n    fontconfig                2.13.0               h9420a91_0  \n    freetype                  2.9.1                h8a8886c_1  \n    fribidi                   1.0.5             h516909a_1002    conda-forge\n    fsspec                    0.5.2                      py_0  \n    gettext                   0.19.8.1          hc5be6a0_1002    conda-forge\n    glib                      2.56.2            had28632_1001    conda-forge\n    graphite2                 1.3.13            hf484d3e_1000    conda-forge\n    graphviz                  2.40.1               h21bd128_2  \n    gst-plugins-base          1.14.0               hbbd80ab_1  \n    gstreamer                 1.14.0               hb453b48_1  \n    h5py                      2.9.0            py36h7918eee_0    anaconda\n    harfbuzz                  1.9.0             he243708_1001    conda-forge\n    hdf5                      1.10.4               hb1b8bf9_0    anaconda\n    heapdict                  1.0.1                      py_0  \n    icu                       58.2              hf484d3e_1000    conda-forge\n    idna                      2.8                      py36_0  \n    imageio                   2.6.1                    py36_0    conda-forge\n    intel-openmp              2019.4                      243  \n    ipykernel                 5.1.3            py36h39e3cac_0    anaconda\n    ipyparallel               6.2.4                    py36_0    anaconda\n    ipython                   7.9.0            py36h39e3cac_0    anaconda\n    ipython_genutils          0.2.0                    py36_0    anaconda\n    jedi                      0.15.1                   py36_0    anaconda\n    jinja2                    2.10.3                     py_0  \n    jpeg                      9b                   h024ee3a_2  \n    jupyter_client            5.3.4                    py36_0    anaconda\n    jupyter_core              4.6.0                    py36_0    anaconda\n    kiwisolver                1.1.0            py36hc9558a2_0    conda-forge\n    libedit                   3.1                  heed3624_0  \n    libffi                    3.2.1                hd88cf55_4  \n    libgcc-ng                 8.2.0                hdf63c60_1  \n    libgfortran-ng            7.3.0                hdf63c60_0  \n    libiconv                  1.15              h516909a_1005    conda-forge\n    libpng                    1.6.37               hbc83047_0  \n    libsodium                 1.0.16               h1bed415_0    anaconda\n    libstdcxx-ng              8.2.0                hdf63c60_1  \n    libtiff                   4.0.10               h2733197_2  \n    libuuid                   1.0.3                h1bed415_2  \n    libxcb                    1.13              h14c3975_1002    conda-forge\n    libxml2                   2.9.9                hea5a465_1  \n    line_profiler             2.1.2            py36h14c3975_0    anaconda\n    llvmlite                  0.30.0           py36hd408876_0  \n    locket                    0.2.0                    py36_1  \n    markupsafe                1.1.1            py36h7b6447c_0  \n    matplotlib                3.1.1            py36h5429711_0  \n    memory_profiler           0.55.0                   py36_0    anaconda\n    mkl                       2019.4                      243  \n    mkl-service               2.3.0            py36he904b0f_0  \n    mkl_fft                   1.0.15           py36ha843d7b_0  \n    mkl_random                1.1.0            py36hd6b4f25_0  \n    mpi4py                    3.0.3                    pypi_0    pypi\n    msgpack-python            0.6.1            py36hfd86e86_1  \n    nccl                      1.3.5                cuda10.0_0    anaconda\n    ncurses                   6.0                  h9df7e31_2  \n    networkx                  2.4                        py_0    conda-forge\n    numba                     0.46.0           py36h962f231_0  \n    numexpr                   2.7.0            py36h9e4a6bb_0    anaconda\n    numpy                     1.17.3           py36hd14ec0e_0  \n    numpy-base                1.17.3           py36hde5b4d6_0  \n    olefile                   0.46                     py36_0  \n    openssl                   1.0.2t               h7b6447c_1  \n    packaging                 19.2                       py_0  \n    pandas                    0.25.2           py36he6710b0_0  \n    pango                     1.42.4               h049681c_0  \n    parso                     0.5.1                      py_0    anaconda\n    partd                     1.0.0                      py_0  \n    pcre                      8.43                 he1b5a44_0    conda-forge\n    pexpect                   4.7.0                    py36_0    anaconda\n    pickleshare               0.7.5                    py36_0    anaconda\n    pillow                    6.2.1            py36h34e0f95_0  \n    pip                       19.3.1                   py36_0  \n    pixman                    0.38.0            h516909a_1003    conda-forge\n    prompt_toolkit            2.0.10                     py_0    anaconda\n    psutil                    5.6.3            py36h7b6447c_0  \n    pthread-stubs             0.4               h14c3975_1001    conda-forge\n    ptyprocess                0.6.0                    py36_0    anaconda\n    pycosat                   0.6.3            py36h14c3975_0  \n    pycparser                 2.19                     py36_0  \n    pygments                  2.4.2                      py_0    anaconda\n    pyopenssl                 19.0.0                   py36_0  \n    pyparsing                 2.4.2                      py_0  \n    pyqt                      5.9.2            py36h05f1152_2  \n    pysocks                   1.7.1                    py36_0  \n    python                    3.6.2               hca45abc_19  \n    python-dateutil           2.8.0                    py36_0  \n    python-graphviz           0.13                       py_0    conda-forge\n    pytz                      2019.3                     py_0  \n    pywavelets                1.1.1            py36hc1659b7_0    conda-forge\n    pyyaml                    5.1.2            py36h7b6447c_0  \n    pyzmq                     18.1.0           py36he6710b0_0    anaconda\n    qt                        5.9.6                h52aff34_0  \n    readline                  7.0                  ha6073c6_4  \n    requests                  2.22.0                   py36_0  \n    ruamel_yaml               0.15.46          py36h14c3975_0  \n    scikit-image              0.15.0           py36he6710b0_0  \n    scipy                     1.3.1            py36h7c811a0_0    anaconda\n    setuptools                41.6.0                   py36_0  \n    sip                       4.19.8          py36hf484d3e_1000    conda-forge\n    six                       1.12.0                   py36_0  \n    sortedcontainers          2.1.0                    py36_0  \n    sqlite                    3.23.1               he433501_0  \n    tbb                       2019.8               hfd86e86_0  \n    tblib                     1.4.0                      py_0  \n    tk                        8.6.8                hbc83047_0  \n    toolz                     0.10.0                     py_0  \n    tornado                   6.0.3            py36h7b6447c_0  \n    tqdm                      4.36.1                     py_0  \n    traitlets                 4.3.3                    py36_0    anaconda\n    urllib3                   1.24.2                   py36_0  \n    wcwidth                   0.1.7                    py36_0    anaconda\n    wheel                     0.33.6                   py36_0  \n    xorg-libxau               1.0.9                h14c3975_0    conda-forge\n    xorg-libxdmcp             1.1.3                h516909a_0    conda-forge\n    xz                        5.2.4                h14c3975_4  \n    yaml                      0.1.7                had09818_2  \n    zeromq                    4.3.1                he6710b0_3    anaconda\n    zict                      1.0.0                      py_0  \n    zlib                      1.2.11               h7b6447c_3  \n    zstd                      1.3.7                h0b5b093_0  \n    --------------------------------------------------------------------------------\n    If requested, please copy and paste the information between\n    the dashed (----) lines, or from a given specific section as\n    appropriate.\n    \n    =============================================================\n    IMPORTANT: Please ensure that you are happy with sharing the\n    contents of the information present, any information that you\n    wish to keep private you should remove before sharing.\n    =============================================================\n    \n\n\nIf this command does not work out of the box for your Numba installation, you may have to set the `CUDA_HOME` environment variable to point to your CUDA installation.\n\n## Writing the first kernel\n\nHere is a vector addition kernel that takes two vectors as input and writes the sum in a third vector:\n\n\n```python\nimport numba.cuda as cuda\n\n\n@cuda.jit\ndef _vecadd_cuda(z, x, y):\n    i = cuda.grid(1)\n    N = x.shape[0]\n    if i >= N:\n        return\n\n    z[i] = x[i] + y[i]\n\n```\n\nPretty simple, right? Let's explain each line of this code.\n\nThe `@cuda.jit` decorator will compile the following function into a CUDA kernel at runtime. We will see the cost of it later on.\n\nA CUDA kernel in Numba is a Python function that does *not* return a value. This is in accordance with CUDA, where kernel functions are declared `void`. The arguments of the function can be either Numpy arrays or scalars of a Numba recognized type.\n\nCUDA kernels specify the work to be done by a single GPU thread. Due to the massive hardware parallelism available on the GPU, a single GPU thread gets only a tiny portion of work, in this case, the sumation of a single element in the vectors. Since each element is independent from each other, we can safely create as many threads as the elements of the target vectors and spawn them (we will see how later).\n\nThreads on the GPU as organized in groups, called CUDA blocks. There are constraints on the maximum number of threads a block can contain. For the P100 GPUs on Daint, this is 1024. This means that you will need multiple blocks to calculate the sum of large vectors. The blocks that comprise a kernel form the *grid*. Threads inside a block are numbered sequentially and the blocks inside the grid are numbered, too. The figure below shows the arrangement of threads for the vector addition example.\n\n\n\nIn order to obtain the i-th element of the vector given a block size $B$, you would have to calculate the following:\n\n\\begin{equation}\ni = i_{b}B + i_{t}\n\\end{equation}\n\nwhere $i_{b}$ is the block index and $i_{t}$ is the thread index. CUDA provides this information and Numba makes it available, so that the above statement would be written as follows:\n\n```python\ni = cuda.blockIdx.x*cuda.blockDim.x + threadIdx.x\n```\n\nBlocks and grids can be three dimensional, thus the `.x` attribute in all of these variables (the other dimensions are accessed through the `.y` and `.z` attributes).\n\nSince obtaining the absolute position of a thread in a CUDA is quite common operation, Numba offers the convenience function `grid()`, which essentially does automatically the above calculation:\n\n```python\ni = cuda.grid(1)\n```\n\nThe argument passed to the `grid()` function is the number of dimensions of the grid.\n\nThe next three statements in the code simply check that we don't overrun the arrays in case that their dimension is not a multiple of the block size. In this case, some threads of the last block will remain idle:\n\n```python\n    N = x.shape[0]\n    if i >= N:\n        return\n```\n\n> The threads inside a block are run in batches of 32 at once, called *warps*. All the threads of the warp execute the same instruction. If the program control flow diverges for some of the threads of the warp, e.g., due to an `if` condition, the branches will be executed sequentially by disabling the non participating threads. This condition is called *warp divergence* and may incur a performance penalty.\n\nFinally, the `z[i] = x[i] + y[i]` computes the actual sum.\n\n\n## Preparing the data for the GPU\n\nAll Numba CUDA kernels operate on data residing on the GPU. That means that the `x`, `y` and `z` arrays must be  transferred from the host (CPU) to the device (accelerator) before calling the CUDA kernel.\n\nLet's create first two vectors on the host:\n\n\n```python\nimport numpy as np\n\n\nN = 1024\nx = np.random.rand(N)\ny = np.random.rand(N)\n```\n\nLet's also compute our reference result:\n\n\n```python\nz_ref = x + y\n```\n\nNow it's time to transfer the vectors to the GPU:\n\n\n```python\nd_x = cuda.to_device(x)\nd_y = cuda.to_device(y)\n```\n\nThe `d_x` and `d_y` are Numpy *array-like* objects that have their data mapped in the GPU memory:\n\n\n```python\nd_x\n```\n\n\n\n\n    <numba.cuda.cudadrv.devicearray.DeviceNDArray at 0x2aaae185d240>\n\n\n\nFor the `z` array, we don't need to create it on the host and copy it, since it is essentially an output only array. We can simply allocate it directly on the GPU and copy it out when the kernel finishes.\n\n\n```python\nd_z = cuda.device_array_like(x)\n```\n\nThis will simply allocate an array like `x`, i.e., with the same element type, shape and order, on the GPU.\n\nData is ready, now it's time to call the kernel!\n\n## Invoking a CUDA kernel\n\nWhen invoking a CUDA kernel you have to specify the block size to use and the corresponding grid size. Picking the right size of block is not always straightforward, but usually values between 64 and 256 are good enough. \n\n> The block size has a direct effect on the *occupancy* of each GPU SM, i.e., how much the actual hardware threads of the SM are utilized, and as a result to the occupancy of the whole GPU. Performance-wise, though, it does not have such a big impact. Nvidia provides a nice tool for calculating the occupancy of the GPU, that you can find [here](https://docs.nvidia.com/cuda/cuda-occupancy-calculator/CUDA_Occupancy_Calculator.xls).\n\nFor our kernel, we will select a block size of 128 threads.\n\n\n```python\nblock_size = 128\n```\n\nHaving decided the block size we need to set up the grid:\n\n\n```python\nnum_blocks = N // block_size\nif N % block_size:\n    num_blocks += 1\n```\n\n\n```python\nnum_blocks\n```\n\n\n\n\n    8\n\n\n\nNow we are ready to call the kernel!\n\n\n```python\n_vecadd_cuda[num_blocks, block_size](d_z, d_x, d_y)\n```\n\nBoth the block and the grid could have been two-dimensional (not in this example), in which case you would just define them as tuples.\n\n## Copying back the results\n\nAs mentioned before, kernels operate on GPU data only. We need a way to transfer back to the host the result, which is the `d_z` array. Here's how:\n\n\n```python\nres = d_z.copy_to_host()\n```\n\nLet's validate the result though to make sure that everything has worked fine:\n\n\n```python\nassert np.allclose(z_ref, res)\n```\n\n## Putting it all together\n\nFor completeness and easy reference, here is the whole vector addition example:\n\n\n```python\nimport numba.cuda as cuda\nimport numpy as np\n\n\n@cuda.jit\ndef _vecadd_cuda(z, x, y):\n    '''\n    The CUDA kernel\n    \n    There's no `cache=True` option like @numba.jit. Every time we're calling the kernel, Numba is going to recompile it\n    '''\n    i = cuda.grid(1)\n    N = x.shape[0]\n    if i >= N:\n        return\n\n    z[i] = x[i] + y[i]\n\n\n# Set up the host vectors\nN = 1000 * 1000 * 100\nx = np.random.rand(N)\ny = np.random.rand(N)\n\n# Copy and allocate data on the device\nd_x = cuda.to_device(x)\nd_y = cuda.to_device(y)\nd_z = cuda.device_array_like(x)\n\n# Set up the kernel invocation\nblock_size = 128\nnum_blocks = N // block_size\nif N % block_size:\n    num_blocks += 1\n\n%timeit -n 1 -r 5 ref = x + y\n\n# Call the kernel\n%timeit -n 1 -r 5 _vecadd_cuda[num_blocks, block_size](d_z, d_x, d_y)\n\n# Copy back the result to the host\nres = d_z.copy_to_host()\n\n# Validate the result\nassert np.allclose(x + y, res)\n```\n\n    49.5 ms \u00b1 67.7 \u00b5s per loop (mean \u00b1 std. dev. of 5 runs, 1 loop each)\n    The slowest run took 438.93 times longer than the fastest. This could mean that an intermediate result is being cached.\n    22.8 ms \u00b1 45.1 ms per loop (mean \u00b1 std. dev. of 5 runs, 1 loop each)\n\n\n### Exercise\n\n> 1. Make the array sufficiently large and time the Numpy version of the sum `x + y`.\n> 2. Now time the call to the CUDA kernel with `%timeit -n1 -r1`. What do you see?\n> 3. Try timing the CUDA kernels with `%timeit -n1 -r2`. What is happening?\n\n\n```python\n\n```\n", "meta": {"hexsha": "bb036f7fd0a55b973883edb8e8d6a2738c8b6cef", "size": 30633, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "numba-cuda/1.numba-cuda-basics.ipynb", "max_stars_repo_name": "edoardob90/PythonHPC", "max_stars_repo_head_hexsha": "cd931c70dbd974ad38a10229ae2563688199c14d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numba-cuda/1.numba-cuda-basics.ipynb", "max_issues_repo_name": "edoardob90/PythonHPC", "max_issues_repo_head_hexsha": "cd931c70dbd974ad38a10229ae2563688199c14d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numba-cuda/1.numba-cuda-basics.ipynb", "max_forks_repo_name": "edoardob90/PythonHPC", "max_forks_repo_head_hexsha": "cd931c70dbd974ad38a10229ae2563688199c14d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4510638298, "max_line_length": 507, "alphanum_fraction": 0.4699507068, "converted": true, "num_tokens": 6145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2658804730998169, "lm_q2_score": 0.12421301159407334, "lm_q1q2_score": 0.03302581428778526}}
{"text": "# IPython's Rich Display System\n\nIn Python, objects can declare their textual representation using the `__repr__` method.  IPython expands on this idea and allows objects to declare other, richer representations including:\n\n* HTML\n* JSON\n* PNG\n* JPEG\n* SVG\n* LaTeX\n\nA single object can declare some or all of these representations; all are handled by IPython's *display system*. This Notebook shows how you can use this display system to incorporate a broad range of content into your Notebooks.\n\n## Basic display imports\n\nThe `display` function is a general purpose tool for displaying different representations of objects. Think of it as `print` for these rich representations.\n\n\n```\nfrom IPython.display import display\n```\n\nA few points:\n\n* Calling `display` on an object will send **all** possible representations to the Notebook.\n* These representations are stored in the Notebook document.\n* In general the Notebook will use the richest available representation.\n\nIf you want to display a particular representation, there are specific functions for that:\n\n\n```\nfrom IPython.display import display_pretty, display_html, display_jpeg, display_png, display_json, display_latex, display_svg\n```\n\n## Images\n\nTo work with images (JPEG, PNG) use the `Image` class.\n\n\n```\nfrom IPython.display import Image\n```\n\n\n```\ni = Image(filename='logo/logo.png')\n```\n\nReturning an `Image` object from an expression will automatically display it:\n\n\n```\ni\n```\n\nOr you can pass it to `display`:\n\n\n```\ndisplay(i)\n```\n\nAn image can also be displayed from raw data or a url\n\n\n```\nImage(url='http://python.org/images/python-logo.gif')\n```\n\n\n\n\n\n\n\n\nSVG images are also supported out of the box (since modern browsers do a good job of rendering them):\n\n\n```\nfrom IPython.display import SVG\nSVG(filename='python-logo.svg')\n```\n\n\n\n\n    \n\n    \n\n\n\n## Links to local files\n\nIf we want to create a link to one of them, we can call use the `FileLink` object.\n\n\n```\nfrom IPython.display import FileLink, FileLinks\nFileLink('Part 1 - Running Code.ipynb')\n```\n\n\n\n\n<a href='files/Part 1 - Running Code.ipynb' target='_blank'>Part 1 - Running Code.ipynb</a><br>\n\n\n\nAlternatively, if we want to link to all of the files in a directory, we can use the `FileLinks` object, passing `'.'` to indicate that we want links generated for the current working directory. Note that if there were other directories under the current directory, `FileLinks` would work in a recursive manner creating links to files in all sub-directories as well.\n\n\n```\nFileLinks('.')\n```\n\n\n\n\n./<br>\n&nbsp;&nbsp;<a href='files/./Animations Using clear_output.ipynb' target='_blank'>Animations Using clear_output.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Custom Display Logic.ipynb' target='_blank'>Custom Display Logic.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./SymPy Examples.ipynb' target='_blank'>SymPy Examples.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Part 2 - Basic Output.ipynb' target='_blank'>Part 2 - Basic Output.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Frontend-Kernel Model.ipynb' target='_blank'>Frontend-Kernel Model.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Part 5 - Rich Display System.ipynb' target='_blank'>Part 5 - Rich Display System.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./animation.m4v' target='_blank'>animation.m4v</a><br>\n&nbsp;&nbsp;<a href='files/./Trapezoid Rule.ipynb' target='_blank'>Trapezoid Rule.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Part 4 - Markdown Cells.ipynb' target='_blank'>Part 4 - Markdown Cells.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./R Magics.ipynb' target='_blank'>R Magics.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Part 1 - Running Code.ipynb' target='_blank'>Part 1 - Running Code.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Typesetting Math Using MathJax.ipynb' target='_blank'>Typesetting Math Using MathJax.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Part 3 - Pylab and Matplotlib.ipynb' target='_blank'>Part 3 - Pylab and Matplotlib.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Script Magics.ipynb' target='_blank'>Script Magics.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Octave Magic.ipynb' target='_blank'>Octave Magic.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Cell Magics.ipynb' target='_blank'>Cell Magics.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./python-logo.svg' target='_blank'>python-logo.svg</a><br>\n&nbsp;&nbsp;<a href='files/./Data Publication API.ipynb' target='_blank'>Data Publication API.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Progress Bars.ipynb' target='_blank'>Progress Bars.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Cython Magics.ipynb' target='_blank'>Cython Magics.ipynb</a><br>\n\n\n\n### Embedded vs Non-embedded Images\n\nBy default, image data is embedded in the Notebook document so that the images can be viewed offline. However it is also possible to tell the `Image` class to only store a *link* to the image. Let's see how this works using a webcam at Berkeley.\n\n\n```\nfrom IPython.display import Image\n\n# by default Image data are embedded\nEmbed      = Image(    'http://scienceview.berkeley.edu/view/images/newview.jpg')\n\n# if kwarg `url` is given, the embedding is assumed to be false\nSoftLinked = Image(url='http://scienceview.berkeley.edu/view/images/newview.jpg')\n\n# In each case, embed can be specified explicitly with the `embed` kwarg\n# ForceEmbed = Image(url='http://scienceview.berkeley.edu/view/images/newview.jpg', embed=True)\n```\n\nHere is the embedded version. Note that this image was pulled from the webcam when this code cell was originally run and stored in the Notebook. Unless we rerun this cell, this is not todays image.\n\n\n```\nEmbed\n```\n\n\n\n\n    \n\n    \n\n\n\nHere is today's image from same webcam at Berkeley, (refreshed every minutes, if you reload the notebook), visible only with an active internet connection, that should be different from the previous one. Notebooks saved with this kind of image will be lighter and always reflect the current version of the source, but the image won't display offline.\n\n\n```\nSoftLinked\n```\n\n\n\n\n\n\n\n\nOf course, if you re-run this Notebook, the two images will be the same again.\n\n## Audio\n\nIPython makes it easy to work with sounds interactively. The `Audio` display class allows you to create an audio control that is embedded in the Notebook. The interface is analogous to the interface of the `Image` display class. All audio formats supported by the browser can be used. Note that no single format is presently supported in all browsers.\n\n\n```\nfrom IPython.display import Audio\nAudio(url=\"http://www.nch.com.au/acm/8k16bitpcm.wav\")\n```\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"http://www.nch.com.au/acm/8k16bitpcm.wav\" type=\"audio/x-wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\nA Numpy array can be auralized automatically. The Audio class normalizes and encodes the data and embed the result in the Notebook.\n\nFor instance, when two sine waves with almost the same frequency are superimposed a phenomena known as [beats](https://en.wikipedia.org/wiki/Beat_%28acoustics%29) occur. This can be auralised as follows\n\n\n```\nimport numpy as np\nmax_time = 3\nf1 = 220.0\nf2 = 224.0\nrate = 8000.0\nL = 3\ntimes = np.linspace(0,L,rate*L)\nsignal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times)\n\nAudio(data=signal, rate=rate)\n```\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"data:audio/wav;base64,UklGRqS7AABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YYC7AAAAADUWvSvyPzdS/WHKbjt4Bn7+fxV+WXj3bjhifVJDQBYslBZiAC/qpdRswCGuU557kf2HJIIcgPWBoIfykKKdTa15v5rTEuk7/2kV8CopP3ZRSmEqbrJ3mH2vf+Z9TXgNb3Bi11K9QK0sQxcmAQPrhNVPwQOvLZ9IkreIxYKggFiC34cLkZOdFq0bvxbTbeh4/o0UASosPnNQSGAwbcd2w3z2fk9923fGblZi7FL/QBwt3hfoAefrg9ZlwiawVqBuk9OJzoOOgSSDg4iAkdadJa31vrvS3ue5/aIT8Sj/PDBP+F7da3t1h3vUfU98BncibuhhuVIJQWQtYRilAtjso9eqw4mxzKHtlE+LPYXkgleEiolTkm6ee60Hv4jSZuf//KsSwyeiO65NXF0zas9z5nlJfOh6zXUhbSdhPlLaQIItzBhbA9Xt39gexSmzjqPCliuNEYeihPKF9YqDk1mfGq5Uv3/SCOdN/KkReCYYOvBLd1szaMVx4HdYehp5MXTDaxNgfFFwQHUtHRkJBNvuN9q9xgW1l6XsmGOPR4nGhvKHwowPlZegAa/bv6LSxOak+58QFCVkOPhJSVnhZV9veXUCeOh2MnIIaqpecVDLPzwtUxmsBOjvp9uFyBm356dmm/aR3otOiVeK8Y73limiMLCewPHSneYG+48PmSOINslH11Y+Y6BssnJJdVF002/yZ+5cHU/rPtYsbBlEBfvwLd11ymO5e6ownuGU1I44jB+NgZE6mQ+kqLGcwW7Tk+Z1+noOCCKGNGVFI1ROYIppj28vcllxFG2CZeBagU3PPUMsZxnOBRHyyN6IzOC7T61GoSGYJZKBj0aQbpTXm0WmZ7PWwhjUp+by+WMNZCBhMtBCMFEUXSFmEWy4bgJu+Gm6YoFYnkt3PIIrQxlJBinzdOC9zo2+YLCkpLKbz5Unk8yTuJfLns2obrVMxPDU2+Z/+UwMsB4dMAxAAU6TWWdiPGjlak9qgWaaX9FVdEnjOpIq/xi0Bj/0L+IQ0WfBq7NHqJKfzpkml6yXXJsVoqSru7f9xffVL+ce+TYL7hy8LR09m0rOVWFeFGS6ZkJmsmImXNNSBEcVOXQpmhgMB1P19+N/02rELbctrL2jH557m+SbVp+zpciuTrroxy3XpefP+CQKIRtAKwY6/0bKURNanF87YuBhjV5gWIlPUEQMNycoFBhRB2P2yeUG1pTH4bpPsC+ovaIioHGgpKOhqTiyJL0OypHYPOiU+BgJSxmuKMo2M0OJTX9V2FpsXStdF1pKVPVLWUHKNKsmbBeCB2v3o+ej2OHKxb6stOOspacYpU6lQ6jdrfG1PMBtzCTa9ehu+BMIbhcHJm0zOT8RSatQzVVRWCdYUVXoTxlIID5PMgIloRadB2z4gulT203O08I+udax0qxXqneqLq1ksvC5k8MDz+Tb0ele+BcHjRVPI/MvFztmRJtLf1DvUtlSQVA9S/dDqTqeLysjtBWiB2P5ZOsS3tXRCccBvgK3P7Lcr+mvYrIytzK+KcfP0dHdz+pl+CYGqxOJIF4szzaMP1RG80pJTUVN6kpNRpQ/9ja3LCghpRSPB076Ru3e4HTVYcvxwmO86beitZ6127dEvLXC+srQ1Orf8OuE+EIFyRG5HbQoZzKIOtpALkVkR29HUUUbQfI6CDOcKfkecxNkByv7Ju+z4yjZ2M8JyPXByb2ju5K7lL2VwXXHA88E2C7iM+27+GsE6w/gGvck4i1eNTI7ND9HQV1BeT+sOxU25C5QJqAcHxIgB/r7AvGO5u3catREzbHH28PbwcHBiMMhx27MQ9No25zkmO4L+aQDEg4DGCshRSkTMGI1DDn2OhQ7aTkENgExiyrVIh4aqhDEBrr82PJt6b/gEdmd0pTNGcpFyCPIs8nlzJ3RtNf63jLnHfB0+e0CQAwkFVUdlCSsKm8vujJ2NJk0JTMnMLkrASYtH3QXEw9NBmj9pvRL7Jrkyt0Q2JfTfdDazrbOENDa0v3WVdy34u/pxPH3+UgCeApGEncZ1B8uJV0pQyzNLfEtsSwaKkImSiFbG6UUXQ2+BQP+aPYo73rokeKY3bXZA9eV1XLVmNb92IrcIeGd5tDsifOT+rYBuwhsD5UVCRueHzMjryUBJyInFCbiI6AgaRxiF7IRiAsVBYz+Hvj/8VzsYOcw4+rfpd1w3FLcSN1I30DiFeap6tTvbvVJ+zcBDAeZDLQRNxYAGvUcAh8YIDIgUx+FHdgaYxdEE54OlQlSBAD/xvnO9DzwNOzS6C/mXeRm41DjGeS25RroLevX7vjyb/cY/M0AbAXPCdYNYhFbFKoWQRgXGScZdBgHF+0UOxIGD2oLhgd3A2D/XvuS9xf0CPF67n/sJOtx6mfqBetD7BPuZfAl8zr2jPkA/XgA3AMRB/8JjwyxDlYQdBEEEgYSfBFuEOcO9QyqChoIWwWDAqr/5PxI+un32PUj9NXy9vGK8ZHxB/Ln8ib0uPWO95j5xPsA/jkAYAJiBDIGwwcKCQAKnwrmCtUKcQq/CcgIlQc0BrAEFwN3Ad7/V/7v/K/7n/rI+Sv5zPis+Mf4Gfme+U/6IvsQ/A79FP4Y/xAA9wDFAXQCAQNpA6sDyAPCA5wDWgMBA5cCIQKnAS4BvABUAPz/tv+D/2X/W/9j/3z/ov/Q/wIANABiAIcAngClAJkAeQBFAP7/pP87/8j+Tv7V/WD99/yg/GD8PPw5/Fn8nvwJ/Zn9S/4c/wMA/gACAgcDBQTxBMEFbgbwBj4HVAcuB8oGKQZMBTgE9QKJAQAAZv7G/C/7rflP+CH3L/aD9Sb1HfVr9RL2Dvdc+PL5x/vN/fb/MAJrBJUGmwhsCvgLLw0HDnQOcQ78DRMNvQsACucHggXiAhoAQP1p+q33IvXe8vXwd+9z7vXtA+6f7sjvd/Gj8zz2Mflq/NH/SgO8BgoKGg3RDxkS3hMOFZ4VhxXFFF0TVRG8DqMLIAhOBEkAMvwl+EX0sfCG7eDq1Oh259Pm9ObZ54Dp3+vk7nzyjPb1+pf/TATyCGQNfBEbFSAYdBoAHLYcjhyFG6EZ7RZ8E2cPzArMBY4APPv99fvwXuxM6OfkTOKR4Mbf9t8h4UHjSeYj6rTu2vNv+Uf/NQUNC58QvxVEGgge7CDXIrYjgSM1ItofgBw9GDITgw1bB+kAYPrx88/tLOg04xHf5NvK2dXYD9l72g/du+Bk5ejqHvHY9+L+BAYKDboT4BlKH8wjQieMKZgqWSrPKAMmCCL6HP8WQhD4CFgBnvkD8sbqHuRC3mHZotUn0wTSRtLt0/DWOduq4BvnW+409mn+ugboDrIW2h0oJGgpby0cMFYxEjFPLxcsgSevIcoaCBOjCtsB9fg18ODnOOB52dvTi8+tzFrLoMt+zenQydX821LjlOuE9N39VQemEIUZrCHaKNYubzN+Nuo3pTetNRAy5ixWJpEe0RVYDHECZ/iH7iDlfNze1IXOpMlixt3EIsUyxwDLcNBc147fyujJ8j791wdDEjEcUSVdLRM0PDmwPFA+DD7lO+k3MjLtKk8imhgXDhgD8/f77Iji7dh10GPJ8cNLwJG+0r4PwTnFMsvP0tbbAuYG8Y78Pgi+E7QeySitMRo50z6rQoFEQ0TyQZw9YTdvLwImYRveD9EDmPeR6xrgjtU/zHjEd75tuny4trgau5q/FcZazivYPuM97837jAgXFQ0hDyzHNec9L0RrSHhKQ0rNRyVDbTzXM6QpIh6pEZgEV/dK6tfdYdJByMm/O7nNtKSy0rJatSi6HMEAypLUgOBw7f76wAhNFjojIi+oOXdCSknqTTBQCFByTX5IUUEhODMt2yB3E24FL/cl6cDbaM9+xFm7QbRwrw2tLa3Sr+m0TbzGxQ7Rzd2i6yL63AhgFzslADJNPcdGIk4lU6VVjVXcUqNNCkZJPKswiCNGFVEGH/ck6NbZpcz4wCu3jK9ZqrunyqeHquCvrLexwaPNJtvU6Tr54AhPGA0nqDS0QNJKs1IXWNJazVoFWI9SkkpLQAg0JyYSFz8HJ/dH5xvYGsqxvUKzIKuNpbSir6J/pRKrPbPDvVTKkNgI6Ef4zAgbGbEoFzfaQ5dO+Va8XLJfw1/qXD1X5k4jREc3tSjbGDYIRveN5o7Wx8esuqKvAacPofud352+oISmBa8CuibHDNZD5kz3owjDGSYqTDm+RhJS8FoRYUJka2SGYapbAVPNR2U6LiueGjQJevf25THVsMXqt0ysMqPknJWZYJlJnDqiCKtwthrEntOF5Er2ZAhJGmsrRjtdSUJVl14RZX5owWjVZdBf31ZFS109jy1XHDkKwveB5QTU08NttUSptZ8PmYWVNJUimDmeSqcSszbBStHR4kP1EgisGoEsBT23SyNY6WG7aGJswWzSaaxjfFqITixA1i8FHkELHvgv5QbTM8I3s4qmjpySlc6RYJFOlIOaz6Psr3y+Ec8p4Tn0rQfuGmcthz7JTbVa5mQLbOtvaHB7bTpn1V2SUdBCADKlH0wMjPj95DjSz8BJsSGkvZlwknOO543RkB2XmqAArfC798yR3y/zNwcPGx0uzT+TT/Vcimf+bhdzs3PMcHhq5mBfVEVFCjQ1IVcNC/ns5JnRp7+jrwqiRpesj3eLy4qujQmUrp1SqpS5/soK3iXysQYQG6Uu1UAUUeJe1GmTceJ1nnbCc2FtrGPtVohH8TWyIl8OmPn75CnRvb5HrkagKZVHjd2IEIjnikyRDpvkp2u3KcmX3B3xHAbzGv4uoUFMUnxgw2vHc0p4KHlZdvJvJGY5WZZJszcaJGQPMvon5efQD74zrdaeaJNDi6eGuIV/iOeOv5i7pXi1e8c62xvwfAW4GikvMUI7U8JhVW2adU96TnuReCpyS2hAW21LTDlrJWMQ2fpw5dLQnr1qrLudBZKiidaExYN5ht2MwZbYo76z9sX22SDv0ARhGigvhELgU7Niim4Jd+17D31legV0H2r+XApNvDqjJloRifvV5enQaL3pq/Sc/pBliGuDOILWhDCLF5U+oj6yncTM2C7uHATvGfsunUI8VE9jYW8UeCN9Z37We4J1nWtzXmpO/ju+J0cSQfxU5izRbb2xq4KcVpCMh2iCE4GYg+OJxJPuoPywcsO/10ftYQNkGaMue0JQVJdj22+7ePJ9WH/gfJ92xWycX41PEj28KCgT//zr5pjRrL3Bq2ScDJAYh86BWIDBgveIyZLsn/qvdsLR1mzsoALBGCMuIEIcVItj92/9eFh+33+EfVt3k214YG9Q9T2aKfsTwv2Y5yzSI74ZrJqcH5AIh5yBBoBRgmyIKJI4nzmvrMED1qHr3AEJGHwtjUGhUyxjtW/beFZ+/H/AfbR3B24EYQ9Rpj5WKr8Uh/5b6ObS0b62rCKdjpBch9OBHYBJgkSI4ZHVnrquFsFZ1ebqFgE9F64sxEDiUntiF29UeOp9r3+Ufap3IG4/YWxRIj/vKnAVTf8w6cbTtL+XrfydWpEUiHKCn4CpgoCI9pHCnn+utMDT1D/qUABfFr4rxz/fUXphHm5rdxd9+H7/fDx33G0pYYRRaD9iKw4WEAAW6sjUy8C7riWfgJIviXmDioFygyCJaJIBn4quicBz1Kvpjv9xFasqlz6aUClgy2wfdt172X0DfGt2PW3AYFZRdz+vK5YW0gAL6+rVE8IgsJyg/5OqiuaE3oKihCOKNpOTn9uulsA61C7pz/51FHkpNz0WT4xeIWt0dD16UXyfejZ1QWwFYOJQTj/TKwgXjgEO7CzXi8PEsWCi1ZWGjLiGmoQ5homLYJR4oHOv3MAq1MnoFv5tEykoqDtUTaNcIGlpcjl4YnrVeJ9z6Gr2XiZQ7D7OK2EXQwIb7YrYMMWks22kAJi+ju6Iu4Y2iFKN5pWwoVKwW8FF1HzoZf1bEr4m7jlXS3Jay2YDcNN1DnimdqVxNGmVXSNPUD6eK6AX8AIx7gHa/8a9tcGmfppSkYWLQYmXinyPyJc6o3mxFMKK1EvovvxBETolCjghSftXJWRCbQxzV3UTdEtvJWfiW9lNej1DK8MXkgNO75Hb98gOuFqpS50/lHqOKYxbjQaSBJoXpeeyCMP71DboIfwiEJ8jADa2RkFVMWEqauhvQHIgcZJsvWTcWUhMaTy7KsoXKARv8DbdE8uTujSsZaCBl8yRcI9+kO2UmZxEp5y0NsSZ1T3okvv/DvAh0TMYREdS8l2+ZmpsyW7NbXxp/GGHV29KHTsHKrMXsQST8e7eU81JvUyvyaMWm3aVFJMAlDGYhZ/CqZe2n8Vk1mToEfvaDS8ggTFLQRFPa1oCY5Ro+Godagxm5V7iVFFIlzklKX4XKgW48rfgss8twKCycqf6nneZEpfcl86bx6KOrNi4Qsdc16nooPq2DGAeEy9QPqFLoFb4Xmpkz2YUZkNieVvvUe5F1jcWKCkXkgXb843iLtI8wyu2Xqspo8mdZpsQnMKfW6anr127H8mC2A7pQfqUC4MciiwtO/xHlFKkWvBfUWK2YSVevFewTkdD3TXZJrMW6AX79G/kxNRzxuq5ia+gp2miDKCZoAmkQKoLsyW+NcvW2ZTp9Pl3Cp0a6SnlNyVES04LVipbg10EXbVZsFMoS15AqjNvJR0WKwYW9lrmcNfNydi97rNarFSnAaVypaGocq63ti7BhM1X2zvqu/lfCa8YMid6NB9AykkxUR1WaFgEWPZUWE9YRzU9QDHYI2UVWQYp90voMNpIzfPBirhTsYSsQaqYqoWt77KqunfECdAE3QPrmPlQCLsWaSTwMPA7FUUbTMtQBVO6Uu1PuEpEQ845oC4UIowUcgY0+D/qAd3f0DbGV72GtvWxxq8GsLKys7ffvv3HxNLe3u3rivlLB8UUkSFMLZs3MUDMRjxLX00pTZ1K0kXuPio2zCslIJITdAY0+Tbs39+P1JzKUsLvu6K3jLW4tSS4urxUw73LstXj4Pjsk/lRBs8Srh6RKSUzITtKQXJFe0dXRwtFqkBaOk0yxCgLHnUSXwYo+ivuyOJV2CLPdceIwYe9jrupu9a9AcIGyLbP0tgS4yXutPlkBdsQwRvCJZEu6zWaO3Q/XEFIQTo/RjuLNTkuiyXHGzgRMwYO+x3wt+Us3MPTvcxOx57Dx8HUwcPDgsfyzOTTI9xr5XPv7fmFBOwOzxjkIeQpkzDBNUY5CjsCOzE5qDWFMPIpJCJaGdoP7gXk+wryq+gQ4HvYI9I6zeHJMcg0yOjJO80S0kXYoN/r5+LwPvq2AwMN2hX5HSIlHyvEL+4yiTSJNPMy1i9LK3olkB7HFlsOkAWr/O7zoOv/40XdpNdH00zQyM7Ezj3QJtNk19TcSeOR6nDyqPr5AiML5hIHGlEgkyWoKXIs3i3kLYcs1CniJdQg0xoOFL0MGQVf/cn1k+705x3iOt1w2djWhdV+1cDWPtni3I7hG+db7R30LPtOAk4J9Q8RFnMb9B9zI9clECcXJ/AlpyNPIAYc7hYzEQELiQQB/pj3gfHr6/7m4eKv34HdY9xc3Gndft+K4nDmEutI8On1yPu1AYUHCg0aEo8WSBoqHSIfJCApIDYfVB2VGhEX5hI2DicJ4QOP/ln5aPTg7+XrkugA5kDkXONZ4zPk4uVV6HbrK+9V89H3ffwxAcwFKQomDqcRkhTTFlsYIBkfGV0Y4Ba5FPsRvQ4aCzAHIAMJ/wv7RPfR88zwSu5c7A/raupu6hrrZOxA7pzwY/N/9tX5Sv3CACMEUwc5CsEM2Q5zEIURChIAEmoRUhDBDscMdgrhBx8FRgJu/6v8E/q697D1A/S+8unxhvGX8Rby/vJF9N31uPfF+fP7MP5oAIwCiwRWBuEHIgkQCqgK6ArQCmUKrQmwCHoHFQaOBPUCVQG9/zj+0vyW+4v6uPkh+cf4rPjL+CP5rPlf+jX7JPwk/Sr+Lf8kAAkB1AGBAgsDcAOvA8kDwAOXA1MD+AKNAhcCnQEkAbIATAD2/7H/gP9j/1v/Zf9//6X/1P8GADgAZQCJAJ8ApQCXAHYAQAD3/5z/Mv++/kT+y/1X/e/8mvxc/Dr8Ovxd/Kb8FP2n/Vz+Lv8YABMBGAIdAxkEAwXRBXsG+AZCB1MHKAe/BhkGNwUfBNgCaQHf/0T+pPwO+475NPgL9x72efUi9SD1dvUj9if3e/gX+vD7+v0kAGACmgTCBsQIkAoVDEUNFA54DmwO7Q37DJsL1gm3B0wFqALe/wP9Lfp19+/0svLQ8FzvZO7x7Qrusu7n76Hx1/N49nP5svwaAJQDBAdOClcNBhBEEv0TIBWjFX0VrRQ3EyMRfg5bC9EH+gPz/9r70ff282nwSe2u6rDoYefO5v/m9ees6RnsLO/O8uf2Vvv7/7EEVAm/Dc8RYRVZGJ0aGBy7HIAcZRtvGaoWKxMKD2QKXgUdAMv6j/WU8AHs/eeo5B7id+DB3wXgReF545Pmfuod70306fnF/7MFhwsRESYWnBpPHh8h9CK8I3AjDSKcHy0c2Re+EgMN0wZeANX5avNR7bvn0+LD3q3bqtnO2CLZp9pT3RXh0eVm66rxbPh6/5wGnA1DFFsatB8hJH4nrymfKkUqoCi6JaYhgxx2FqsPWAizAPn4ZPEx6pnj0N0F2WHVAdP80VzSINQ/16PbK+Gv5/7u4PYa/2sHkw9SF2oeoyTKKbYtRDBfMfswGC/CKxEnJSEsGloS6gkdATj4fu81557f9thy0z/PgsxQy7jLuM1D0UHWjtz6403sSPWm/h8IaRE7Gk8iZilGL8AzrTb1N4s3cDWwMWcsvCXfHQ0ViAubAZH3ue1f5M7bStQOzk7JMcbRxDzFcsdky/bQ/9dK4JnppfMg/rgIHRP8HAkm+i2RNJc55TxdPvE9ojt/N6YxQiqKIcEXMA0rAgb3Fuyy4SzYz8/eyJHDE8CDvu6+VcGnxcXLg9Ol3Obm+PGH/TYJrxSVH5MpWjKlOTg/5kKQRCZEqUEpPcc2sy4qJXMa4A7MApT2luov37rUicvmww2+L7psuNS4ZrsSwLTGHc8M2TbkRfDd/JsJHRYCIuwshTaAPp5ErEiKSiVKf0epQsc7DDO6KCAdlxB+Az32OenY3HvRfMcqv8e4ibSRsvGyqrWousfB0sqE1Yzhje4j/OUJaBdDJBIwdjodQ8NJMk5FUOlPH036R6BASDc4LMYfUBI/BAD2AOit2nDOqMOsusOzJa/3rE2tJ7BwtQO9psYR0uve0uxb+xUKjxhXJgEzKj55R6VOc1O9VW1VhFIYTU5FYzuhL2IiDBQNBdz16+ax2JzLE8BytgWvB6qip+un4KpvsG24nsK1zlXcF+uH+i0Kkhk8KLk1oEGRSz9TbFjsWqxaqlf9Uc1JWD/vMvAkxhXoBdH1++Xj1gDJvrx9spCqNaWYos+i3KWoqwe0vL51y8/ZXemn+SwKcBryKTg41ERiT45XF13QX6JfjFylVhdOJEMgNm0nfhfNBt31L+VG1Z7Gq7nRrmimsaDcnQCeHqEgp9ivBrtUyFvXqOe9+BQKKht3K306xkfpUo9bcmFkZEpkJmELWypSxEYwOdgpMRm7BwD2h+TY03fE3LZwq5CigJxymYCZqpzbouOrf7dVxfvU+eXL9+YJwBvMLIY8ckojVj5feWWjaKFocmUtXwBWMkocPCws2xqwCDn2A+Sc0o3CU7RdqAqfpJhelVOVhZjeniyoKrR8wrPSU+TT9qMJMhzwLVI+10wPWZhiKGmKbKJsbmkFY5dZbE3hPmcufByrCYb2ouOQ0d/AEbKZpdqbIZWkkX6Rs5Qsm7ekDLHMv4bQuOLX9UwJghzjLuE/9U6qW51lfmwXcEtwFm2QZupcblB8QYYwEB6oCuf2Y+O10G+/GLAnowKZ+pFFjgOON5HJl4ehJ65IvXbOLOHY9OIIsBymLzJByVDzXUhod29Gc5dzZnDKafZfNVPoQ4YylR+oC1n3RuML0D2+aK4HoYSWMI9Gi+aKFI64lJ+ef6v0uobMr9/Z82cIvBw4MEVCVFLpX5lqEXIVdoV2W3OxbLhivVUkRmU0CSGmDNz3SuOQz0m9Aq07n2CUxoypiCmITYv8kQOcF6nRuLnKRN7b8t0HqBybMBpDlVOLYY9sSnSBeBB583VBby1lBFgsSB82aSKjDW74beNFz5K856vEnZmSvopvhs+F5IiYj7aZ8abkthLJ79zh8UUHdhzPMLJDi1TXYiduInaIejh7K3h4cVJnCFr/SbM3tCOaDgz5r+Mozxm8FqujnDCRGImahNqD3YaOjbqXEaUttZLHsNvs8KAGJhzVMAxEN1XOY2FvlXcqfPt8AXpUcyVpxFuYSx455iSMD7b5DeQ5z927j6rWmyWQ14csg0uCOYXiixGWeaOxszzGitr/7/EFuhutMCpEmFVwZD1wpHhkfVZ+c3vRdKNqOF33TF46/iV1EGr6h+R3z927U6pgm3iP+oYmgiSB+oOUir6UKqJxshPFgNkb7zoFMxtbMA1EsFW8ZLpwT3k2fkl/gHzvdctrYV4YTnE7+iZTESX7GuXfzxi8X6o+myqPgoaJgWWAIYOmicKTKKFusRjElNhD7nsEkxrdL7VDgFWzZNlwlHmfftJ/JX2tdptsPV/7TlM81yclEub7xuVx0Iy8tKpxmzqPb4ZUgRGAroIZiR+Tc6CssE7Dxtd47bgD3Bk3LyRDCFVXZJtwdHmffvJ/ZH0IdxFtyl+dTwU9lCjoEqv8iOYq0Tm9T6v3m6iPwYaJgSaApILviNaSDKArsLXCGte87PECEBlqLlxCSVSnY/9v8Hg2fqh/O30BdyxtCWD8T4Q9LymcE3P9XucK0h2+MKzPnHKQeIcmgqWAAYMoieiS95/ur1HCkdYR7CoCMBh4LV5BRlOmYgdvCHhlffR+qXyXdu1s9l8YUM49pik9FDr+R+gO0zW/Va35nZiRkYgqg46BxoPDiVWTMqD0ryHCLdZ662MBPxdjLCxAAFJVYbRtvnYtfNd9sHvJdVJskl/vT+I99ynKFAD/QOk01IDAvK5xnxeTDIqWhN+C84TCih+UvqA/sCjC7tX36p4APhYsK8g+eVC2XwlsE3WOelJ8UHqZdFpr3V6BT789IipCFcL/SOp71fzBYrA3oe6U54tnhpiEh4YkjEOVnaHQsGfC19WL6uD/LxXXKTU9s07KXQZqCHOLeGZ6iXgGcwhq1V3NTmU9JSqjFX4AXOvf1qbDRrJHoxuXII6biLeGgIjojcSWzqKosd7C6dU26ib/FhRlKHQ7sUyWW69noXAmdhR4XnYScVpoe1zSTdI8/inrFTQBe+xe2HzFZrSfpZuZtZAxizqJ3YoMkJ+YUKTGso3DJdb76XX+8xLYJok5dkoaWQdl321gc191z3O+blJm0FqRTAU8rikZFuABoe332XvHvbY9qGyco5MnjiCMnI2QktOaJKYqtHfEi9ba6c39yRE0JXY3A0hbVg9ixWo8cEly4HALbPFj1FgKS/86MiksFoICzu6n26HJSrkdq4qf6JZ4kWWPvJBylWCdSKjUtZnFHNfV6TH9mhB6Iz41XUVaU8teV2e9bNVukW37aDlhiFY9ScA5iigiFhgD/+9r3evLCbw9rvOif5ojlQeTOpSvmESgvKrEt/XG2tft6aP8aA+tIeMyhkIcUD5bl2PmaAZr5mmRZSpe7VMrR0c4tyf7FZ8DMvFA31bO976ZsaKmZ54lmQOXEphGnH2jfa34uYvIxNgj6iP8NQ7PH2kwgT+kTG1XiV+8ZN5m4WXPYchaBVHURJU2tya2FRcEZPIl4d/QEsIttZWqmqJ4nVabQpwzoAini7BwvFnK2tl46rP7Aw3kHdItUjz1SFlTMVtAYGFihmG3XRRX0007Qqo0iiVRFX4ElfMW44PTVMX2uMeuFqcbovufxqBzpOOq47Mqv2DMHdvt6lX71AvtGyEr/DgTRQlPk1Z4W5Rd2VxOWRJTVkphP4gyMiTNFNMEwfQS5T/WvMjwvDWz1asHp/Ckm6UEqQyvgrckwp3Oi9yB6wr7qwruGVsogzUCQX9Ks1FoVnpY3VeXVMROlEZHPC8wrSIpFBUF6PUV5xDZRcwXwdq31LA6rC6qvarhrX6zaLtexRHRJt427NL6iAnoF4El6zHHPMFFlkwTURhTllKVTy5KjULvOKEt/CBjE0IFBvcd6fLb7M9mxbG8DravsbOvKLAHsze4j7/UyLrT7d8L7bD6bgjeFZciNy5kONJAQEeAS3JNCU1MSlJFRT5bNd4qIB9+ElkFG/gn6+PerNPaybbBfrtgt3m11rVxuDS998OEzJbW3eEB7qP6XwfUE6EfayrfM7c7t0GyRY1HO0fBRDZAvjmPMeonGx13EVsFJPkx7d7hg9duzuXGIMFJvXu7w7scvnDCm8hs0KPZ+OMY7636XAbKEaAciiY9L3U2/zuwP25BMEH4Ptw6/jSMLcUk7BpQEEUFIfo57+LkbNsf0znM7sZkw7XB68ECxObHeM2I1N/cOuZP8M/6ZgXFD5oZmiKAKhExHTZ9ORs77Tr2OEk1BjBWKXEhlRgJDxcFD/s88evnZN/n16zR48ytySHISMgfypTNidLX2EngpOim8Qj7gATFDZAWnB6uJZArFjAgM5g0dzTAMoIv2yrwJPIdGRaiDdIE7vs48/bqZuPB3DrX+dId0LnO1c5u0HPTzNdU3d3jNOsd81r7qQPNC4UTlhrMIPYl8CmeLOwt1C1aLIspgSVdIEkadxMdDHQEu/wr9f/tb+er4d7cLNmv1njVjNXp1oHZPN384Zrn5+2y9MT75QLgCX0QjBbdG0kgsSP8JRwnCifKJWkj/B+gG3oWshB5Cv4Ddv0S9wTxeuue5pPid99e3VjcaNyL3bbf1eLM5nzrvPBk9kb8MwL/B3sNgBLmFo4aXR1BHy4gHiAXHyEdURq+FoYSzQ24CG8DHv7t+AP0hu+X61To0uUk5FPjY+NP5A/mkejA64DvsvM0+OH8lQEsBoIKdg7sEckU+xZyGCcZFhlEGLkWhBS6EXIOyArbBsgCsv64+vf2jPOR8BvuOuz76mPqduov64bsbe7T8KPzxPYe+pX9CwFpBJQHcwrzDAEPjxCWEQ4S+BFYETUQmw6ZDEEKqAfjBAkCMv9y/N75i/eI9eTzqPLc8YPxnfEm8hbzZPQC9uL38/kj/GD+lwC4ArQEegb/BzkJIAqxCukKygpZCpsJmQheB/UFbQTSAjIBnP8Z/rb8fvt4+qn5F/nD+Kz40fgs+bn5cPpI+zn8Ov0//kL/OAAbAeQBjgIVA3cDswPKA74DkwNMA/AChAINApMBGwGpAEQA7/+s/33/Yv9b/2b/gf+p/9j/CgA8AGkAiwCgAKQAlQByADoA8P+T/yn/tP46/sH9Tv3n/JT8WPw5/Dv8Yvyt/B/9tf1s/kH/LAApAS4CMgMuBBUF4QWHBgAHRgdSByIHtAYIBiIFBgS6AkkBvv8h/oH87fpw+Rn49PYN9m71HvUk9YH1NvZA95v4PPoa/Cf+UwCQAskE7wbtCLMKMgxaDSAOfA5mDt0N4gx5C6wJhgcWBW0Cov/G/PL5Pfe89IbyrfBD71Xu7e0T7sfuB/DM8Qv0tfa2+fn8ZADfA0wHkgqUDTsQbhIbFDEVphVyFZUUERPwEEAOFAuCB6UDnP+D+3z3p/Mi8AvtfeqN6E3ny+YM5xPo2elU7HTvIvND97j7XgAVBbUJGg4gEqcVkRjEGi4cvxxxHEMbOxlnFtkSqw78CfAErf9a+iL1LvCm66/naeTy4V7gvd8W4Gvhs+Pf5trqhu/C9GT6QwAxBgEMgxGMFvMalB5QIQ8jwSNdI+MhXB/ZG3MXSRKDDEwG0/9K+eXy1exL53Tid95324zZydg32dXamd1x4UHm5us28gD5EQA0By8OyxTVGhwgdCS5J9AppSovKm4obiVCIQoc6xUUD7cHDgBV+MbwnukV41/drNgh1d7S9tF00lbUkdcO3K3hROih7473zP8bCD0Q8Bf4HhwlKir6LWowZTHhMN8uayueJpogjRmrETEJXwB798jui+YG33TYC9P2zlnMScvTy/TNoNG71iLdo+QH7Q32cf/oCCoS7xrxIvAptC8ONNk2/TdvNzA1TjHmKx8lKx1IFLcKxAC89uzsoOMj27jTms37yALGyMRaxbbHy8t+0aTYCOFp6oH0Av+ZCfYTxh2+JpQuDDXvORY9Zj7SPVs7EzcXMZQpwyDmFkkMPQEZ9jLr3eBt1yzPXMg0w9+/eL4Ov5/BGcZbzDnUdd3L5+vygP4vCp4VdCBbKgUzLjqaPx5Dm0QFRFxBszwrNvUtTySDGeINyAGR9ZvpRt7p09bKV8OnvfW5X7j1uLW7jMBXx+PP79kw5U7x7f2pCiIX9iLHLUA3FT8JRepIl0oCSixHKkIeOz8yzicdHIMPYwIk9Sno2tuX0LnGjr5XuEi0grIVs/+1LLt2wqfLedaZ4qvvSf0JC4IYSyX+MEA7v0M4SnZOVVDFT8hMckfrP2w2OyuvHikRDwPR9NvmnNl6zdbCBLpKs96u5axxrYCw/LW+vYrHFtMK4APulfxOC70Zcif/MwQ/KEgjT71Tz1VIVSlSiEyORHk6ky45IdESygOZ9LPljdeVyjK/vbWCrrqpjqcQqD6rArExuY7Dys+H3Vvs1Pt5C9MaaSnINohCTEzHU7xYAluHWktXZlEDSWE+0jG2I3kUkQR69LDkrtXpx867vLEEquKkgaL1oj2mQqzWtLm/mMwR27PqB/uMC8QbMCtXOctFKVAfWG1d6V99XylcB1ZETSJC9TQkJiAWZAV19NLj/9N4xa24Ba7TpVigwp0lnoKhwKewsA+8hcms2A7pLvqFC48cxiyrO8pIu1MoXM5hf2QlZMBgaFpOUbZF+TeAKMIXQgaH9BnjgtJCw9G1maryoSGcVZmlmRGdgaPDrJK4k8Za1m/nTPlnCzUdKi7CPYJLAFffX9tlwmh8aAplhV4dVRpJ2TrGKl4ZJwew9IbiNtFKwTyze6dknj+YPZV4le+YiJ8TqUa1xcMf1NflY/gzC7cdXS+bP/RN9llCY5BprWx+bARpWGKtWEtMkz31LPEaEwjv9BbiHdCPv++wrqQtm7eUgJGikR6V2pukpTCyH8H+0UnkdffqChQeXTA3QR1Qm1xOZutsPXAocKts4GX6W0ZPJEAJL3kcBAlC9crhNc8TvuuuMqJNmIqRHo4mjqOReph5olOvpL74z8jigvaNCk4eLDGTQvtR7V4Baepvb3N1c/pvF2kCXwZSiEL/MPMd+Amp9aHhf87WvDGtCqDHlbuOG4sHi4CObJWWn7GsWLwRzlXhjvUdCmYeyjGxQ5BT62BZa4lyQXZkdu9y/GvAYYlUvUTWMl4f7Qoh9pvh+s3Yu8KrNp6dk0yMeohJiLmLspL+nE6qPLpMzPPfmfSdCVweNjKPRNlUlGJVbcd0sXjyeId1i24xZMtWv0aJNLYg4Aup9rXhps0Zu5+quJzQkT6KPYbthVGJT5Czmi2oU7iryqXep/MNCTIecjIvRdZV52PzbqN2vHoce8B3wXBUZstYjUgXNvoh0QxA9+7hgc2ZusepkJtikJSIZYT1g0mHRo65mE+mobYwyWzdufJvCOkdfzKQRYlW5GQycBt4YHzgfJZ5nHImaIVaI0p+NycjvA3k90bijM1WujqpvppSj0+H9IJkgqOFmYwRl7mkKLXex0vc0PHGB4MdXjK0RfBWi2UTcS55nX0+fgp7GnSjafdbf0u7ODwkoQ6T+LvixM1RuvmoQpqhjm6G64E7gWKES4u+lWuj6bO3xkTb8PASBwAdDzKbRQxX22WUcdx5cn4zfxh8OXXLaiBdoEzMOTUlfA9L+UvjKc6IugGpHZpPjvOFS4F6gIeDW4rBlGii57K9xVnaGvBWBmMclTFHRd9W1mW2cSR63n6/f8B8+HWca/1dgk2uOhImTRAK+vXjuM76ulOpTZpcjt6FE4EjgBODzYkclLKhJLLyxIvZT++UBa4b8TC4RGlWfGV6cQd64X7hfwF9VnYVbIxeJk5hO88mERHQ+rbkcc+lu+2p0ZrIji2GRYE1gAWDoInRk0qhobFYxN7Yku7MBOEaJDDwQ6xVzWTgcIV5e36af9p8UnYzbM1eiE7iO2wnxhGY+43lUdCJvM2qqZuQj+KG4IGygGCD1YnfkzChYLHxw1LY5e0DBP8ZMS/xQqhUzWPpb594rH3pfkx863X3a75eqE4wPOcnaxJj/HnmV9GivfOr0py1kPmH44KXgSKEbYpJlGehYrG9w+nXSu04AwsZGS69QWFTe2KXblZ3dXzOfVZ7InVga19ehE5JPD4o/RIt/XbngdLwvlutS540knOJTITmgkuFaIsNle6hqLG+w6XXwexuAgUY3ixWQNhR2mDrbKt12XpMfPp59nNvaq9dHE4tPG8oexP1/YPozNNwwAWvE6AMlE6LHIachNuGxYwtlseiMrL2w4fXTuyoAfEWgyu+Pg5Q7V7naqFz13hiejd4aHIiaa5cb03aO3ko5BO6/p7pNtUfwu6wJqI7loiNT4i5htCIhI6nl/GjArNkxJDX8evmANAVCir4PAhOtVyOaDlxcnYTeBB2eXB7Z1xbfUxQO1woNRR4/8Xqvdb8wxKzgqS9mB2Q5Io6iSmLo5B7mWulF7QKxcLXq+srAKMUdSgGO8ZLNVrjZXZurXNhdYVzKm56ZblZRUuOOhYobhQuAPbrX9gDxnC1JaeRmw2T2Y0djOWNIZOomzancbXpxR3Yf+t5/28TxybqOExJcFfnYlpriXBNcppwfWshY8ZXyEmTOaYnjRTcAC7tGdozyAW4DKq0nlSWK5FgjwCR/JUtnlGpELcAx6LYbuvR/jQSAiWoNp5GaVSfX+lnCm3bbk9tdGhwYIRVBkhgOAsnkBR/AWvu6duHys26M60hou6Z1pQAk3mUM5kIobqr9LhPyFLZeOs1/vQQKCNCNL1DI1ENXCdkM2kNa6hpEGVqXfRSAEb0NkYmeBQVAqzvy93+zMW9lrDXpdmd2Jj7lk2Yw5w4pHCuHLvXyS3an+um/bMPPSG7Ma5Aok01WBVgB2XnZqhlVWESWhhQt0NRNVUlQhScAu7wvt+Uz+rAM7TQqRCiLZ1Mm3mcqaC5p3Kxhr2WyzPb5Osm/XEOQx8XL3M96kkbVLlbimBsYlJhRV1oVvFMLEF1Mzkk7xMUAy/yv+FG0jnEBrgKrpCm0aHwn/mg4qSLq760MsCNzWXcR+y2/DENPB1YLBE6/UXCTxZXwVugXalc41hvUoFJYD5jMfIifBN8A23zy+MR1a7HC7yAslWrwKbjpMqla6mpr1G4HsO6z8LdyexY/PYLKxuBKYo24UEwSzFSrlaHWLFXM1QsTstFVTscL38h6xLQA6b04OXy10bLPcAtt1qw9ashqueqQa4RtCm8R8Yc0krfau0N/MAKExmXJuMymT1oRg1NV1EmU25SOU+gSdJBDTifLOIfOhISBNj1++fl2vvOmsQOvJq1bbGlr02wX7PAuEPArcmz1P3gK+7V+5EJ9habIx8vKjlvQbFHwEuATeZM+EnQRJg9ijTvKRoeaRE+BAL3Gero3czSG8kewRG7Ibdrtfi1wrixvZ3ETc1819niC++z+20I1xSSIEMrlzRKPCBC70WbRxtHdES+PyA5zzANJykceBBWBCH4OOz34LTWvs1YxrrADr1tu+G7Zb7iwjLJI9F22t7kDPCn+1MHuRJ+HVEn5i/9NmA86D99QRNBsz5wOm003Sz8IxAaaA9XBDX5Vu4P5K/afdK3y5HGLsOnwQbCRMRNyADOL9We3QvnLPGx+0cGnRBjGk4jGiuMMXU2sTkpO9Q6uDjoNIQvuSi9IM8XOA5BBDr6b/At57neVdc30Y7Me8kTyF/IWcrvzQPTa9nz4F/pbPLS+0gFhg5DFz4fOCb+K2YwTzOlNGI0iTIsL2gqZSRSHWkV6QwUBDH7g/JN6s7iQNzT1q7S8c+tzunOoNDE0zfY1t1z5NjryvML/FoEdwwjFCQbRSFXJjcqxyz4LcItKyxBKR4l5B++Gd4SewvPAxf8jfRt7evmOuGE3OvYidZt1Z3VFNfF2ZjdbOIa6HTuR/Vc/HwDcQoFEQUXRBycIO0jICYmJ/smoiUqI6gfOhsEFjEQ8AlyA+z8jfaJ8AzrP+ZH4kDfPt1O3HbcsN3w3yLjKufn6zLx4PbF/LECdwjsDeQSPBfSGo8dXx82IBIg9h7uHAwaahYmEmMNSAj+Aq79gfie8yzvS+sW6KblCuRM427jbeQ95s/oC+zV7w/0lvhG/fkBiwbaCsUOLxL/FCIXiRgtGQwZKhiQFk4UeREoDncKhQZxAlz+Zfqq9kjzV/Dt7Rns5+pf6n/qRuup7JzuC/Hj8wr3Z/rf/VQBrwTUB6wKIw0nD6sQpRESEvARRBEXEHMOagwMCm4HpgTMAfb+Ofyq+V33YfXF85Py0PGB8aTxNvIu84P0KPYM+CD6UvyP/sUA5ALcBJ0GHAhPCTAKuQrqCsQKTAqHCYAIQQfWBUsErwIQAXr/+v2b/Gb7ZPqb+Q75v/it+Nb4NvnH+YH6XPtO/E/9Vf5X/0wALQHzAZsCHwN9A7YDygO7A44DRQPnAnoCAwKJAREBoAA8AOn/p/96/2H/W/9o/4T/rP/c/w4AQABsAI4AoQCkAJMAbgA1AOn/i/8f/6r+MP63/UX94PyO/FT8OPw9/Gb8tfwq/cP9ff5U/0EAPgFEAkgDQgQoBfAFkwYIB0kHUAcbB6gG9wUMBewDnQIpAZz//v1f/Mz6Uvn/99/2/fVk9Rz1KPWM9Un2Wve7+GL6RPxV/oMAvwL4BBsHFQnWCk4Mbw0sDn4OXw7MDcgMVwuBCVUH3wQzAmX/ify3+QX3ivRb8orwKu9H7uvtHO7c7ifw9/FA9PL2+vlB/a4AKQSUB9UK0Q1uEJcSOBRCFagVZhV7FOkSvBABDssKMgdQA0X/LPso91jz3O/P7E3qa+g758nmG+cx6Afqkey973bzn/ca/MMAeQUVCnQOcRLrFccY6hpCHMEcYRwgGwcZIhaFEkwOlAmBBDv/6fm19MjvS+ti5y3kx+FH4LvfKeCS4e7jLec36/HvNvXg+sEArwZ6DPQR8RZJG9gefyEoI8MjSCO3IRsfhBsMF9QRAgzDBUj/wPhf8lns3OYW4i3eQ9tx2cfYTtkF2+HdzuGy5mfsw/KV+aoAywfADlIVThuCIMQk8SfuKagqFio6KCAl3SCQG2AVew4WB2r/svcp8AvpkuLw3FTY5NS90vPRj9KO1OXXe9ww4troRvA7+HwAywjmEI0YhB+TJYgqPC6OMGkxxTCjLhErKSYNIOwY+xB3CKL/v/YT7uPlcN7116bSsM4zzEXL8cs0zv/RONe43U7lwu3T9joAsAnrEqIbkSN4Kh8wWTQCNwI4TzftNOkwYiuAJHYcgRPmCe//6PUf7OLiedoo0yjNq8jWxcPEe8X8xzbMCdJM2cfhO+te9eT/eQrOFI8ecSctL4Q1RDpFPWw+sD0RO6M2hTDkKPofChZgC08ALfVP6grgsdaMzt7H28Kuv3G+Mr/swY3G9Mzx1Ejesujf83r/JguMFlEhISuuM7M6+D9SQ6NE4EMMQTk8izU1LXMjkhjkDMMAjvSi6F7dGdMmysvCRL2+uVa4G7kJvAvB/cer0NXaK+ZY8v3+twsmGOgjny74N6c/cEUjSaFK3EnWRqZBcjpuMeAmFxtvDkgBC/Qa597atc/5xfW967cMtHeyPLNYtrS7KcN/zHDXqOPJ8G7+LQybGVAm6DEIPF5EqUq1TmFQnU9tTOZGMz+MNTwqlx0AEN8Bo/O45Y3Yh8wHwl+51LKbrtismq3esIy2fL5wyB7ULOE279D9hwzqGooo+zTaP9NInU8CVN5VH1XJUfRLy0OLOYMtDiCVEYUCV/N85GvWkclUvgy1A65yqX6nOqigq5qx+rmCxOLQut6g7SL9xgwTHJQq1DdtQwNNSlQHWRNbXVrnVspQNUhnPbMweiIrEzoDJfNm43rU1cbiugCxfKmUpG+iH6OjpuCsqbW6wL/NVdwK7Gf86gwWHWwsczq+RutQq1i+XfxfUl/CW2VVbUwbQcgz2CTAFPsDDfN34rvSVMS0tz2tQqUEoK2dUJ7soWWojLEbvbnK/9l26qD79gzzHRIu1jzKSYhUvFwlYpZk+mNVYMBZblCkRL42JSdSFsgEDvOt4S7REMLLtMapWaHHmz2Z0Jl+nSukp62oudTHvNfm6M766AypHoYv+z6PTNhXfGA3ZttoUmidZNddNVT/R5I5XinfF54FJ/MK4dPPCsApsp6mxJ3glyOVopVdmTig/qlnthHFjtVd5/T5www6H8cw4kAMT9ha52PyaclsVGyVaKdhvlcnS0E8gCtlGXwGWPOM4KzOQ77Rr8ejhJpSlGKRzJGOlY6clqZZs3bCeNPc5RP5iAylH9UxiUJAUYZd+2ZTbV1w/m86bCplBVsZTsg+iS3hGmAHnvMz4LfNu7zCrUKhnZcfkf2NT44UkjKZcaODsATAfdFm5C34NwzsH7Ay8UMpU+FftWlXcJJzTXOIb19oCF7SUCRBdi9QHEgI+PP+3/bMc7v+qxGfEZVLjveKL4vyjiaWkqDorb+9n8/94kP30wsPIFgzGUXHVOdhE2z7cmh2PXZ8ckFrwmBPU1FDRDGxHTIJZvTt32fMa7qHqjad4JLXi1OIb4gsjG6T/p2Kq6q74s2k4Vj2XAsPIM4zAUYYVphjFW4+ddp4zXgUdc5tMGONVU5F8DIBHx0K5fT+3wnMo7lcqbGbDZHFiRKGEYbDiQ2Rtpttqce5R8xd4G711QrtHxM0qUYeV/JkuW8ed+h6+HpNdwNwUWWJVxdHeDQ/IAYLdfUw4N3LG7l9qIKamY8XiDeEGIS6hwSPvZmSpxm40soq34b0PgqsHyc0EUfWV/Rl/XCaeJB8v3wled5xIWdBWalI2zVnIewLEvaB4OHL07jqp6uZhI7OhsOChIIUhleNFpj+paK2g8kO3qPzmglLHws0OkdDWKBm4nGxedB9H36aelxznmiyWgNKFDd3IswMvPbx4BTMyLijpyuZz43phbeBWIHShAiMw5axpGW1X8gK3cby6gjMHsEzJkdkWPVmZ3Jjeqh+Fn+qe310xmnaWyNLIzhvI6UNcfd94XXM+7iopwGZeo1rhROBlYD0gxeLxpWuo2S0Zscg3PLxMQgyHkoz1UY6WPNmjXKuehd/pX9UfD11mGq3XAZMBjlKJHUOL/gl4gLNa7n3py6ZhI1ThdmAO4B+g4aKH5X2oqCzmsZT2yjxbwd+HacySEbGV5tmU3KTehx/yn+XfJ51E2tJXatMujkJJTkP9Pjm4rrNFbqPqLGZ7Y2ghQmBS4Bug1eK0ZSMohuz/8Wk2mrwpwaxHNsxgUUKV+5lu3EUerh+hX90fJx1NGuMXQ9NPTqoJfAPvvm+45vO+LpvqYeatY5ShqGBxYDFg4mK3ZRvoteylMUV2rrv2wXOG+YwgUQGVu5kxXAveex91n7oezl1/GqCXTNNjzomJpgQjPqs5KLPE7yVqrGb2Y9oh6GCqIGEhB6LQpWiotSyW8Wo2RvvDQXWGswvS0O+VJxjc2/nd7d8v332enN0amonXRRNrTqCJi8RW/ut5c/QY70ArCudWJHiiAmE9IKqhRSMApYkoxSzV8Ve2Y3uPgTMGY0u4UEyU/phx209dhx7P3ydeUxzfWl9XLJMmDq6JrMRKfzA5h/S576srfSeMZO8iteFqIQ2h22NG5f2o5izh8U42RLucQOxGCwtREBlUQpgwmszdBx5WHred8NxNmiDWw1MTDrMJiQS9fzi55DTnMCZrwqhYZX2jAmIwoYniSaPj5gYpWC07sU52aztpwKIF6wreD5aT89dZ2nLcbl2DHi7ddlvlWY4WiNLyzm4Jn4SvP0R6R/Vf8LDsWuj5peMj56KQIl8iz+RXJqLpmy1isZh2V3t4gFTFg8qfzwSTUpbuWYHb/RzXHU1c5BtnGSeWPVJEzl8JsISfv5M6srWjsQntBKmvZp9kpKNIYwzjreTgpxNqLy2Xsex2SbtJQEUFVcoWjqSSoBYumPqa9FwS3JNcOpqSmK0VoJIIzgYJuwSN/+P647Yx8bDtv+o453FleOQYY9KkYyW/55eqlC4acgq2gjtcADNE4cmDjjbR3JVbWB3aFJt224Hbedno198VMxG/TaLJf0S5//Z7GnaJsmUuSysVaFimY+UAJO+lLyZ0aG9rCm6q8nM2gTtx/+AEqIknjXxRCVS1lyxZHppD2tlaYpkplz3UdJEnzXTJPMSigAo7lncqMuWvJivEKVQnZGY+JaOmEWd+KRor0O8JcuY2xztKP8wEakiCzPXQZxO+FicYE5l62ZpZdZgVlkmT5ZCCjTyI84SIgF571reSs7Hvz6zEKmLoeecR5u1nCShcKhesqC+1syO3FDtmP7fD6AgWTCRPtpK11Q8XNBgcmIYYc1ctlULTBlAPjLmIosSqwHK8GrgCtEiwxq3Ua0Qpo2h6Z8woValN6ydtT7BvM6v3aLtF/6ODokejC0iO+RGeFCUVwRcp11zXHNYyFGoSFw9PDCwISsSJAIa8ofi5NOkxiq7z7HZqn2m26T9pdepS7AjuRrE2dD73hHupv1ADWccpiqON71C3UuqUu9WkFiAV8tTj00ARWA6BS5QIKwRjAJm863k1dZJymi/hbbkr7WrGKoWq6WuqLTuvDTHKtNw4J/uR/33Cz0aqifYM2k+DEeATZZRL1NCUthODkkUQSg3myvGHg8R4QKs9Nvm2tkOztDDb7sqtS+xm694sLyzTLn6wIrKrtUP4kvv+/y0Cg0YnSQFMO05CUIeSPxLik2+TJ9JSUToPLYz/SgTHVMQIwPq9Q3p79zv0V/IicCouue2YLUethe5Mr5GxRjOZNjX4xbww/x6CdoVgSEYLE012TyGQihGpkf3RiNEQz9+OAwwLyY2G3gPUQMf90DrEeDn1RDNzsVZwNe8YrsDvLK+V8PNyd7RStvH5QHxofxKCKYTWh4VKI0wgTe+PB1Ah0H0QGo+ADrbMywsMSMzGX4OaQNJ+HTtPeP02d7ROcs3xvvCnMEjwonEt8iMztfVXt7e5wryk/wnB3QRKhsAJLErBTLLNuI5Mzu4Onc4hDQBLxkoByAIF2YNawNm+aTvb+YQ3sXWxdA9zE3JCch5yJbKTs6A0wLan+Eb6jLznfwRBkYP9hfdH8AmaiyzMHszrzRKNFAy1C70KdcjsRy5FC8MVgN1+s7xpek54sDbbdZm0sfPo87/ztbQFtSk2FreCuV97Hj0vfwKBSANwBSwG7whtiZ6Ku4sAS6uLfkr9Ci4JGkfMhlFEtoKKgN0+/Hz2+xp5szgLNys2GXWZNWw1ULXDNr23d7inOgC79z19fwTBAILixF9F6oc7SAnJEEmLifqJnkl6SJSH9IajRWvD2cJ5wJi/An2DvCe6uLl/eEL3x/dR9yG3NbdK+Bw44jnU+yo8V33RP0uA+8IWw5HE5AXFRu/HXofPSADINMeuBzFGRUWxRH5DNkHjAI+/RX4O/PT7v/q2+d85fLjRuN744zkbeYO6VfsLPBt9Pn4q/1cAuoGMgsTD3ESMxVHF54YMhkAGQ4YZhYXFDYR3A0lCi4GGQIG/hP6XvYF8x7wwO3569bqW+qK6l7rzuzL7kTxI/RQ97H6Kf6dAfUEFAjlClMNTA/FELQRFBLnETAR+A9MDjoM1gk0B2oEjwG6/gD8dvkv9zv1qPN+8sXxgPGs8UfyR/Ok9E72N/hO+oL8v/70ABADAwXABjkIZQk+CsAK6gq9Cj4KdAloCCQHtgUpBI0C7QBZ/9v9f/xP+1H6jfkF+bv4rvjc+EH51fmS+m/7Y/xl/Wv+bP9fAD4BAwKnAigDgwO5A8oDuQOJAz4D3wJwAvkBfwEHAZgANQDj/6P/d/9f/1z/av+H/7D/4f8TAEQAbwCQAKIAowCRAGoALwDi/4L/Fv+g/ib+rf08/dj8iPxR/Df8P/xs/L78Nf3R/Y7+Z/9VAFQBWQJdA1YEOgX/BZ8GEAdMB04HFAebBuYF9gTRA38CCQF6/9z9Pfyr+jT55PfJ9u71W/UZ9S31mfVc9nX32/iI+m/8gv6yAO8CJwVHBz0J+QpqDIINNw6ADlcOuw2tDDMLVgkjB6gE+AEo/0z8fPnO9lj0MPJp8BLvOu7q7Sfu8u5J8CTydvQv9z36if34AHIE2wcYCw0OoRDAElQUUBWpFVkVXxTBEocQwA2CCuIG+wLt/tX61PYK85bvlOwf6kvoKufI5irnUeg36s/sCPDL8/z3fPwnAd0FdQrNDsASLxb8GA8bVRzCHE4c+xrQGNsVMRLrDSoJEgTJ/nj5SfRk7/LqFufx457hMuC63z7gu+Er5Hvnlutd8Kz1XPtAAS0H8gxjElQXnRsZH60hQCPDIzEjiSHXHiwboxZdEYELOwW8/jX42/He62/muuHl3RHbV9nG2GfZN9sq3i7iJOfp7FDzK/pCAWIIUQ/YFcUb5yATJSgoCiqoKvspBCjQJHUgFBvTFOENdAbF/g73jO966BHig9z/16nUn9Ly0azSyNQ72OvctuJy6evw6fguAXsJjxEqGQ8gCCbkKnsurjBqMaYwZS61KrIlfh9KGEsQvQfk/gP2X+085dvdd9dE0mzOD8xEyxLMds5h0rfXUN775X7umfcEAXgKqxNUHC8k/SqIMKE0JzcEOC03pzSCMNwq3yO/G7oSFAkZ/xT1VOsm4tLZmtK5zF7IrsXAxJ/FRsijzJfS9tmI4g3sPPbFAFkLpBVWHyIowi/6NZU6cD1vPoo9xDowNvAvMSgvHywVdwpi/0H0bek53/bV7s1ix4XCgL9uvlm/PMIFx5DNrNUd35rp1PRyAB0MeRctIuUrUzQ1O1NAgkOnRLhDuEC8O+k0cSyVIp8X5Au//4vzqud43E3SeclDwuW8i7lRuEW5YLyNwabId9G82yjnYvMMAMUMKRnYJHUvrTg2QNRFWUmnSrFJfUYgQcI5mzDvJREaWg0tAPLyDebk2dfOPMVgvYO307NwsmiztLY/vN7DWs1p2Ljk6fGU/1ANsxpUJ9AyzDz5RBZL8E5oUHBPDUxXRnc+qjQ6KX0c1g6vAHXyl+SA15fLO8G+uGOyXa7QrMetQLEgtz2/Wcko1U/iavAK/74NFhygKfM1rUB6SRNQQ1TnVfFUZFFcSwRDmzhxLOIeVxBBARXyR+NM1ZHIer1ftImtL6l0p2ioB6w2sse6ecX80e/f5+5w/hEOUh28K904T0S2TchUTVkfWy1aflYrUGNHaTyRLz0h2xHjAdDxHuJJ08TF+rlHsPmoSqRhok+jDqeErYC2vsHozprdY+3H/UgOZx6lLYw7rUepUTJZCl4LYCJfVVu/VJFLEUCXMosjXxOSAqbxHeF50TTDvrZ5rLektZ+dnYCeWqIPqWyyKr7wy1Tb3+sS/WUOVR9cL/09xkpRVUxddmKnZMpj5V8TWYlPj0OANcgl4RRNA5bxQ+Dcz+HAyLP4qMagc5sqmQCa753bpJCuw7oYyR/ZX+pR/GgOGyDfMDBAmE2rWBRhjmbvaCFoKmQlXUlT30ZIOPQnYBYUBKDxkN9zzs6+G7HGpSidhpcNldOV0ZntoO+qi7dhxv/W5OiF+1IOuyAuMiRCIVC1W4ZkT2rgbCRsH2jvYMtW/knsOgkq1xfjBMHxBN8+zfq8t67louGZ85NJkfuRBJZHnY2nhrTQw/XUcOey+iUONCFJM9hDX1JtXqFntW12cM9vw2tvZAxa6ExqPQcsRxm6Bfrxnt49zGa7nqxXoPOWu5DijX6OjJLumW2kt7FowQTTBebY+eENhyExNEtFU1TQYGJqvXCvcx9zEG+gZwldmk+9P+otqxqXBknyXd5vyxO60KoenmCU4o3Zil2La4/mlpOhI68rvzDRp+T5+IgNtiHkNH5G+VXeYsdsZ3OHdhB2BHKAar5fEVLjQa8vAxx3B6zyQd7WygK5UKk7nCmSaYsxiJuIpYwwlAOfyqwcvXrPV+MY+BsNwCFkNW5HU1eWZM9urnX9eKF4m3QLbSliSlTZQ1QxSx1ZCCLzSd5wyjK4HaivmlCQU4nuhTyGPIrQkb6csao/u+bNF+I295wMpyGxNR5IYFj3ZXhwk3cOe8561XY/b0dkQ1adRdcygh47Carzct48yqK3N6d6mdeOoIcPhEGEM4jIj8ea2qiVuXbM6uBU9g0MbCHMNY5IH1n/ZsJxE3m5fJd8rXgZcRZm+FcsRzQ0pB8bCkH0vt45ylO3nqadmL2NU4aYgquCi4YcjiGZSKchuCvL0t929W4LESG2Nb1IkVmwZ6xyLnr8ffl9I3qYcpJnZ1mESGs1sSD3Cub0KN9nykO3U6YZmASNa4WJgX2BR4XLjM+X/KXmtgnK0d6d9MIKlyBwNa1ItlkJaDVz43rXfvN+NXu6c7toj1qiSXg2piHNC5j1sd/EynO3U6bsl6uM6YTjgLiAaITZi9CW+aTltRHJ6d3L8wsK/x/8NF9IkFkKaF1zMXtJf4R/4Xt8dI9pbVuFSlo3gSKbDFT2V+BPy9+3oKYWmLKMzoSmgFuA74NHiyiWQKQgtUbIHN0B80oJTB9bNNRHHlm1ZyZzGXtRf6t/J3zfdAtqAFwrSw84QCNgDRn3F+EGzIi4NqeWmBmNGYXTgGmA3YMVi9iV06OZtKjHa9xC8oIIfx6PMw1HY1gKZ5BynHrvfml/BnzgdC9qR1yTS5U44SMZDuX38OHnzGy5Fqhsmd+NyYVpgeCAMYREi+CVs6NRtDrH2tuQ8bQHmh2ZMg1GYFcKZptxuXklfr1+fnuAdPtpQFy6S+s4YyTEDrX44eLxzYi6PKmVmgKP3oZngsCB7YTUi0GW4aNKtP3GaNvs8OIGnxx8MdZEFla4ZEpwcnjzfKl9j3q/c21p6luhSw45xCRgD4j55uMhz9u7qaoQnIGQVojNgwmDD4bHjPyWXqSFtPPGGNtZ8A4GkBs5MGhDiFQUY51uyXZZeyx8OnmccoZoRltFS/84AiXqD1z6/uR10GK9WKzbnVuSMIqZhbqEl4cajhCYKqUCtRzH7NrX7zoFcBrTLsdBuFIiYZdsv3RbeUd6f3cYcUVnU1qnSrs4HCViEDD7J+bs0Ry/Sa70n4yUaozKh9GGhInOj32ZRabCtXrH5Npp72gEPxlNLfU/p1DjXjtqVnL4dv53YHU0b6tlEFnFSUM4EiXGEAD8XueC0wbBeLBYohOXAY9dikyJ1YvikUObr6fFtg3IAtsQ75kDARinK/Q9Wk5bXIpnkW81dFF13nLxbLljflehSJU34CQUEcz8o+g21R3D4rIEpe6Z85FRjSuMh45UlGGdaakLuNbIR9vN7tECtxbmKcg700uLWYdkc2wScUJy+29Qam9hnlU5R7E2iCRLEZH98ekF117FhrX2pxidPZWikGmPmpEil9afcKuUudXJs9uj7g8CZRULKHI5FEl4VjZh/miTbdVuumxUZ9BecFOORZc1CCRpEU7+SOvr2MfHX7grq4+g3JhNlASTCpVLmqCixK1huwvLSNyR7lcBCxQZJvY2IUYjU5pdNmW8aQxrHGn/Y9xb9VChQ0Y0XyNuEQH/pOzo2lXKa7uerk+kzZxQmPuW1JjNnb2lZLBvvXbMBd2a7qoArBITJFg0/UKST7dZHWGPZepmJWVSYJZYME5yQcAyjSJYEaj/BO733ATNpr5MslWoC6GnnEib9pykoSupTrO+vxjO7N2+7goASxH7IZkxqz/HS49VuVwQYXJi2WBRXABVIUsDPwMxkiEmEUEAZu8X39LPDcIztp2slKVNoeifbaHOpeisgbZNwu/P+9797nj/6Q/UH70uMDzHRyhRDVhDXKpdOVz+Vx1Ry0dUPBIvbSDYEMwAx/BE4bvSnMVMuiKxYqpAptikNaZIqvGw+rkaxfrRNeBa7/T+iQ6hHcgrjziVQ4ZMHlMsV5NYS1deU+9MMERoOe0sHx9tEEcBJvJ847zVT8mWvuG1cq95qxOqSasOr0S1t70kyDnUl+HU74L+LQ1lG7woyzQ1P6xH703RUTRTEVJzTnlIUkBBNpQqqR3kD7EBgPO85dHYI80Kw9S6vrT2sJavprAdtNy5tcFpy6vWIuNs8CH+1gsiGZ0l6DCsOqBChkg0TJBNkkxCSb9DNDzfMgooCRw9DwgC0/QB6PjbE9Gmx/i/Q7qwtlq1R7Zvube+8sXnzk7Z1eQi8dT9hwraFm8i6yz/NWU96EJdRq1H0EbPQ8Q+2TdGL08lQhp4DkwCHfZK6i3fHdVlzEjF+r+kvFu7KbwCv9DDasqb0iDcsOb28Zr9QQmSFDQf1ygwMQI4GD1PQI5B0UAePo05RTN4K2UiVBiVDXsCXveT7G3iOtlB0b7K4MXLwpXBRMLRxCTJGs+C1iHfsejo8nb9BghKEvAbsCRGLHoyHjcPOjs7mTozOB00ei54J08fQBaTDJQCkvjZ7rTlad041lbQ7sshyQLIlsjWyq/O/tOa2k3i2Or582f92QYGEKcYeyBFJ9Ms/TCkM7Y0LzQUMnkufSlIIw4cBxR0C5gCufka8f/opOFD2wrWINKgz5zOGM8O0WvUFNng3qLlI+0n9W/9uQXIDVsVOhwxIhMnvCoTLQguly3FK6UoUSTtHqQYqxE3CoUC0fpU80vs6eVf4Nbbb9hD1l7VxdVy11XaVd5R4x/pkO9y9o39qQSSCxAS8xcPHT0hXyRhJjQn1iZNJaYi+h5oGhUVLQ/eCFsC2PuF9ZTvMuqG5bXh194D3ULcl9z+3Wjgv+Po58DsHvLZ98L9qwNnCckOqRPjF1cb7R2UH0Eg8x+vHoEcfhm+FWMRjwxpBxoCzfyq99jye+616qDnUuXb40LjieOs5J7mTumj7IPwzPRc+Q/+vwJJB4kLYQ+yEmcVaxeyGDUZ9BjyFzsW3xPzEJAN0gnYBcIBsP3B+RP2wvLm75Tt2+vF6ljqlep36/Ps/O5+8WX0l/f6+nP+5gE6BVQIHQuBDXEP3hDBERYS3REbEdkPIw4KDKAJ+gYtBFIBf/7I+0P5AvcW9YvzavK78X/xtfFY8mHzxPR09mL4fPqx/O/+IgE7AysF4gZVCHsJTQrHCuoKtgowCmAJTwgHB5YFBwRqAssAOP+9/WT8N/s++n/5/Pi3+LD44/hL+eP5o/qD+3j8e/2B/oH/cwBQARICswIxA4kDvAPKA7YDgwM3A9YCZwLvAXUB/QCPAC0A3f+e/3T/Xv9c/2z/iv+0/+X/FwBIAHMAkgCjAKMAjwBmACkA2v96/wz/lv4b/qP9M/3Q/IL8Tfw2/EH8cfzG/EH94P2f/nr/agBpAW8CcwNqBEsFDgaqBhcHTgdMBwwHjgbUBd8EtwNhAugAV/+5/Rv8i/oW+cv3tPbf9VP1GPUz9ab1cfaQ9/34rvqa/LD+4gAfA1UFcgdlCRoLhQyVDUEOgQ5ODqkNkgwPCyoJ8AZwBL0B6/4P/EH5l/Yn9AbySPD77i7u6e0y7grvbPBR8qz0bveC+tH9QgG8BCMIWgtIDtMQ5xJvFF4VqRVLFUMUlxJREIANOAqRBqYClv5/+oH2vfJR71rs8eks6BvnyeY753PoaOoO7VPwIPRZ+N78jAFABtUKJQ8PE3EWLxkyG2ccwRw7HNUamRiUFdsRig3BCKIDWP4I+d3zAO+Z6szmt+N34R7gvN9U4ObhaeTM5/bryfAi9tj7vwGqB2oN0hK3F+8bWh/YIVUjwiMYI1ohkh7UGjkW5RD+CrEEMf6s91fxZOsD5l/hnt3h2j/ZyNiC2Wvbdt6P4pjnbO3f88D62wH4COEPXRY7HEkhYCVcKCQqpirdKcsnfiQMIJYaRRRHDdIFIP5r9vDu6ueR4RjcrNdx1IPS9NHL0gXVk9hc3T3jCuqR8Zj54AEqCjYSxBmYIHsmPiu4Ls0waDGEMCQuVyo4Je4epheZDwIHJv5H9avsl+RJ3fzW5NErzu/LRcs1zLvOxtI42OreqeY872D4zwFAC2oUBR3LJIEr7jDnNEo3AjgHN140FzBTKjwjBhvxEUEIQv5A9Inqa+Es2Q/STMwUyInFwcTGxZLIE80n06LaS+Ph7Bv3qAE5DHoWHCDRKFUwbDbkOpc9bz5hPXQ6uzVZL30nYh5NFI0JdP5W84zoad4+1VPN6cYywla/br6Dv5DCgMcuzmnW89+E6sn1bAEUDWUYByOmLPY0tDuqQK5DqESMQ2FAPDtENKwrtSGrFuQKuv6J8rPmlNuC0c7IvsGJvFy5ULhyubq8EsJSyUXSptwm6G30HAHSDSsaxiVIMF85wkA0RotJqUqCSR9GlkAQOcUv/SQIGUQME//a8QHl7Nj7zYLEz7wet5+zbrKYsxW3zryXxDfOZdnL5QnzuQByDskbVii1M409kUV/SydPbFA/T6lLw0W4PcUzNShhG6wNgP9J8XbjddaqynPAIbj2sSSuy6z5raaxuLcCwEbKNdZ0457xRAD1DkAdtSrpNn1BHUqFUH9U7FW+VPxQwEo5Qqc3XCu0HRkP/v/U8BPiLtSTx6O8trMTrfCobqecqHKs1rKXu3TGGdMm4S7wvv9cD5Ae4izjOSxFZE5CVY9ZJlv5WRBWh0+NRmg7bC79H4oQiwB88NjgGtK2xBW5k697qAakWaKEo36nLK5at8XCFNDi3rzuKP+mD7cf3S6hPJhIY1K0WVFeFGDtXuNaE1SxSgQ/ZDE7Iv0RKAFA8MXfOdAXwsy1uqsxpGyfk522ns6ivalQsz6/Ks2s3ErthP7UD7UgozAhP75LFVbWXcNismSUY29fYlihTnZCPzRqJG8T0wEf8Nrejc62v8qyL6g3oCSbHpk2mmaekKV9r+G7XsqF2tnr0/3oD4whNjJjQZxOelmmYeBm/WjrZ7FjblxYUrxF+zaHJt4UigIY8BjeFc2VvRCw8qSSnDKX/pQJlkuap6Hjq7O4tMdy2GzqF/3hDzoikzNkQzBRjVwgZaVq8Wzua6RnM2DSVdFIlDmQKEkWSwMs8H3d0su0u6GtCKJEmZqTN5ExkoCWBp6IqLe1LcV01gXpUfzCD8EiuzQkRXpTTl9CaBBuinCab0ZrrmMNWbNLBzyCKqwXFQRX8ArdxMoVun6rcZ9Oll2QzY2zjgqTsZpvpfCyzsKO1Kbng/uKDyEjrzWiRndVumEKax5xxXPqcpFu3GYFXF5OUj5bLAUZ5gSa8L3c7Mm4uKepMJ20k3+NwYqRi+qPq5eaomKwmcDD0lLmsPo8D1sjbTbeRydX0GN2bcxzoXbddYRxuWm2Xs9QcEAXLlMavAXy8JfcSMmctx6oRZt4kQGLFojOiCSN+JQNoA+ukr4W0Qvl2PnaDm8j9jbYSIpYj2WEbxh2GXlveBx0QmwdYQNTYEK1L5MblQZf8ZXc2cjDtuOmspmZj+eI0IVthruKmZLLnfururyIz9Pj/vhjDl4jTDeQSZ1Z9mYycQF4LnueelZ2dW45Y/hUH0QyMcMccAff8bfcncgttvald5gajjCH74NwhLKIk5DXmyeqFbsdzqziI/jaDSsjbjcGSmNaBWiBcoV523xofC94T3AGZapWqkWLMuAdSghw8vzclMjXtVillZf8jN+FdILZggmH5o4ympeopLnWzJnhSvdBDdUiXjc7Stpaumhvc6R6In7MfaZ5znGCZhhYAEe/M+keIQkR82LdvcjDtQelDJc/jPOEYoGpgcSFlY3fmEynari3y5vgdPaZDGAiHTcwSgRbF2n8c1x7/37Ifrl68HKrZz9ZHUjKNNwf9Qm/8+fdFsnutQSl25bii26EuoDhgOOEoozgl0imarfAyrTfpPXlC8shrDblSeFaHGkodK57c39cf2d7tXN/aB5aAEmsNbYgwQp69IrenslYtk2lA5fni1CEeoCCgGiEDYw3l46lpLb0yefe2/QlCxkhDDZcSXJayWjzc5h7fn+Gf7B7GXT9aLNaqEliNnYhhgs/9UrfVMoAt+KlgZdLjJmEpICNgFKE2Ivklh+lG7ZUyTXeG/RcCkwgQDWWSLhZIGhecx17H39Gf5J7HnQlafxaEkrqNhkiQQwL9iTgNsvjt8GmVZgQjUeFOIEBgaSEBIzplvyk0LXjyKDdZ/OMCWUfSTSWR7RYIWdrcjx6V36efg17wXP0aPlaPUpDN54i7wzf9hfhQcwAueinfpkyjlqGNILegVyFkYxGlyalxbWiyCvdv/K2CGceKjNcRmlXzmUacfd4J32MfSF6BHNraKhaKUpsNwQjkA229yDidc1Wulap+pqxj9GHmIMlg3uGf437l52l+rWSyNXcJvLdB1Qd4zHrRNlVKWRtb053kHsRfNB45nGJZwpa00ljN0kjIQ6Q+D3jzs7huwirx5yLkaqJYoXShP+Hzo4KmWOmcLa0yKLcnfECBy0ceDBGQwVUNWJnbUV1k3kwehl3Z3BOZh1ZPUknN2sjoQ5r+W3kS9Cgvf2s456+k+SLkYfnhuiJfJBxmnanKLcKyZHcJvEoBvUa6i5uQfFR818Ia9xyMnfqd/90iG67ZOJXZEi4NmkjDg9E+q3l6dGQvzGvSqFHlnyOI4pfiTSMipIwnNmoIriTyaXcxPBQBa4ZPS1nP55PZl1VaBZwb3Q/dYFyTGzQYllWSEcUNkMjZg8a+/vmpdOuwaKx+6MkmW+RFo07jOKO9pRGnomqXrlRyt/cdvB9BFoYcisyPRBNkVpPZfZsTXEzcqNvsmmPYIJU60U8NfYiqQ/r+1ToftX5w02086ZSnLqUZpB2j/CRvpeyoIas3LpFyz/dPvCvA/sWjCnTOklKeFf6YYBpz23JbmZsvGb4XV9STEQuNIMi1A+1/LfpcNdsxi+3LqrNn1yYEpQPk1uV4Jpzo9CunLxtzMbdH/DpApQVjidMOE1HHVRZXrVl92kCa85obmMOW/BPa0LrMugh6A92/SLredkFyUS6qK2So0+cFZgDlyCZWp6GpmSxnb7KzXTeGPAtAicUeyWiNR9Eg1BwWpphymXiZtxkyV/RVzZNSkBzMSYh4Q8t/pHsltvBy4q9X7Gep5GgbJxOmz2dKqLrqUK038Bdz0vfLPB8AbYSVCPWMsJAsExDVjJdSmFtYpRgz1tGVDRK6T3HLzsgwA/Y/gPuxd2czvzAT7Xtqx2lE6Hsn6+hTKadrWi3X8Mj0UngWvDYAEQRHiHsLzs9pkjUUYJYfFynXfpbhVdtUOtGSjvmLSgfhA91/3bvA+CU0ZjEc7l5sPCpB6bapHGmvqqcsdS6HcYe03DhpPBCANIP2h7nLIw5aUQqTY5TZFeSWBBX7VJKTF1DbTjSK+0dLA8CAOfwTOKk1FnIx71AtQSvQqsUqoGre6/jtYO+F8lL1cDiC/G8/2IOjBzLKbo1/j9ISFpOB1I1U9xRCk7fR40/VjWLKYoctw6AAFTyn+TL1zvMSMI9ule0wbCUr9mwgbRvunPCS8yq1zfkjvFH//cMNRqbJskxaTsyQ+tIaEySTWFM4kgxQ347BTIUJ/8aJg7tALzz+OYD2zvQ8MZqv+G5frZXtXW2zLk+v6HGuM862tXlLvLk/pML2hdaI7strjbuPUZDjkawR6RGd0NCPjI3fi5sJE0Zdw1GARz1VelL3lTUvMvExJ+/dLxYu1K8Vr9MxArLWtP53Jvn7PKU/jcKfBUNIJcp0jGAOHA9fUCSQapAzj0XOa0ywiqXIXQXqgyMAXP2s+ue4YPYp9BFyozFn8KRwWnCHMWUyavPL9fk34bpx/NY/uUIHxO1HF4l2SztMm43Ojo/O3c67De0M/Et1CaVHncVwAu+Ab/3D+765MTcrdXpz6LL+cj+x7bIGcsSz3/UNdv74pbrwPQx/qAHxBBXGRYhyCc6LUUxyzO7NBE01TEcLgQptyJpG1UTuQraAf74Z/Ba6BLhyNqp1dzRfM+YzjPPSNHC1IXZaN885srt1vUg/mgGbw72FcMcpCJtJ/sqNS0MLn0tjytUKOgjbx4WGBARlQngAS76ufK762rl9N+C2zXYI9Za1dzVpNeg2rfexeOj6R/wCPcl/kAFIQyUEmgYcR2KIZUkfiY4J8EmHyViIqEe/RmcFKkOVAjPAU/7AvUb78fpLOVu4abe6Nw+3KvcKN6m4BHkSegu7ZbyVvhB/igE3gk3DwoUNBiXGxoerB9EIOIfiR5JHDQZZxUAESMM+AaoAV78P/d28iXubOpn5yvlxeM/45njzuTR5o/p8ezb8Cv1wPl0/iIDpwfgC60P8hKYFY0XxRg3GeUY1BcPFqYTrxBDDX8JgQVqAVr9b/nI9YDyr+9p7b3rtepX6qLqkesZ7S3vuPGm9N33RPu+/i8CfgWSCFQLrw2UD/YQzhEXEtIRBRG4D/oN2QtpCb8G8QMVAUP+kPsQ+db28fRu81fysvF/8b/xa/J78+b0m/aO+Kv64fwe/1ABZgNSBQMHcAiPCVoKzQroCq0KIQpMCTUI6gZ1BeUDRwKpABj/n/1J/CH7LPpy+fT4tPiy+On4Vvny+bX6lvuN/JH9l/6W/4YAYQEgAr8COgOPA78DygOzA34DMAPNAl0C5QFqAfQAhgAmANf/mv9x/13/Xf9u/43/uP/p/xsATAB2AJQApACiAIwAYgAjANP/cf8D/4v+Ef6Z/Sr9yfx9/Er8NvxE/Hf8z/xN/e79sP6N/38AfwGFAogDfQRdBR0GtQYdB1AHSQcEB4EGwgXJBJwDQwLIADX/lv35+2r6+fix96D20PVK9Rb1OfWz9YX2q/ce+dX6xfze/hEBTwOEBZ4HjAk8C58MqA1LDoEORQ6WDXUM6gr+CL0GOASBAa7+0/sG+WD29vPd8Sfw5e4j7urtP+4i74/wf/Lj9Kz3xvoa/o0BBgVpCJsLgg4EEQ0TiRRrFagVOxUlFGwSGhA+De0JPwZQAj7+KPou9nDyDe8h7MXpDugM58vmTueV6JnqTu2f8Hf0t/hB/fEBpAY0C30PXROyFmIZVBt3HL4cJRyuGmAYSxWFESgNVggzA+b9l/hx853uQuqC5n/jUeEN4L/fbOAT4qnkHehX7DfxmfZV/D4CJwjiDUATGBhBHJgfAiJpI74j/SIpIUseehrOFWwQewooBKX9IvfT8OvqmOUG4Vrds9oq2czYn9mh28Pe8eIN6PDtbvRX+3MCjglwEOEWrxyrIasljig7KqIqvSmRJyokoR8XGrUTrAwvBXv9yfVV7lznE+Gv21vXO9Rp0vjR7dJE1e3Yz93G46XqOPJH+pEC2QrdEl4aICHsJpUr8i7oMGQxYDDgLfYpvSRcHgEX5g5HBmj9jPT56/LjuNyD1ofR7M3Ry0rLXMwDzy3Tu9iF31nn+u8n+ZkCBwwoFbMdZiUCLFExKjVqN/433zYSNKovyCmXIkwaJxFuB2z9bfPA6bHgiNiG0ePLzcdnxcXE8cXiyIbNutNQ2xDktu3694oCGA1PF98gfinmMNw2Lzu8PWs+NT0gOkI1vy7GJpMdbROiCIX9a/Ks55vdiNS7zHPG4sEvv3K+sb/owv7H0M4p18zgbuu/9mYCCg5QGeAjZS2WNTA8/kDXQ6VEXEMGQLg6mzPjKtMgthXjCbT9iPG+5bHautAnyDzBMbwwuVO4o7kYvZvCAcoV05HdJul59SwC3g4rG7ImGTEOOklBkUa5SaZKUEm9RQhAWjjtLggk/xctC/j9w/D34/bXIc3Mw0G8vrZus3CyzLN6t2C9VMUYz2Pa3uYq9N8BlA/eHFUplzRLPiRG40taT2pQCk9CSyxF9jzdMi8nRBqADE/+HPBX4mzVv8muv4e3jbHvrcysL64RslS4y8A1y0TXm+TT8n4BLBBpHscr3DdJQrxK8lC3VO1Vh1SOUB9KakGxNkQqhBzaDbn+k+/h4BPTmMbQuxGzoqy1qG2n1KjirHqza7xxxzjUX+J38QwBphDLHwYu5joGRg9PuFXLWShbwFmeVd5OtEVkOkUtvB45DzT/KO+T3+7QrMM1uOOuAqjHo1aivaPzp9iuObjQw0PRLOAX8IgAAxEFIREwsz1/SRhTMlqTXhhgs15sWmNTzUnzPS4w6SCaEL//2u5u3v3O/cDftACrr6Mnn46d8J5Ho3GqObRVwGfOBd617vb/QhEUIugxQkCyTNVWXF4KY7hkWWP1XqtXtE1aQfwyCSP8EVgAqO5z3UDNjr7QsWqnrp/bmhaZcZrjnkmmbrADvajL7dtU7Vb/ZhH7IoozkUKcT0NaM2IsZwVpsGczY7FbYlGVRKs1GCVcE/8Aku6h3LrLX7wLrySkAZzklvSURJbKmmai3azfuQrJ59n166n+bxG4I/U0n0Q8UmBdtWX2avxss2skZ3Ff1VShRzk4FSe4FLIBl+7422nKcrqQrDChrJhGkyuRbZICl8qeiKnsto7G9deb6vH9XRFNJCs2bEaQVCpg3mhmbpdwXm/DauhiClh6SqI6+ygPFm8Cte5420/Jx7hiqpGesJUFkL6N7o6Nk3mbdaYttDjEGtZJ6S/9MxG5JCo39UeXVp9irGt5cdVzr3INbhJm/FoeTeM8yipdFzQD7O4g22vIX7eCqEecD5Mija+Ky4tvkHaYpaOmsQzCWdT/52f88BD+JPM3O0lRWL1kHm4rdLR2o3X/cO1oqF2IT/o+fiyiGAAEOu/u2r3HO7bwplWazJCgigKICImqjcWVHaFZrwvAs9LB5pj7lxAcJYY4Pkq7WYNmMnB8di95NniWc3RrDGC3UeRAFC7ZGdAEnu/k2kXHWbWtpbuY6I6BiLmFpYZBi2mT3p5IrTm+LdGQ5cb6KRAUJeQ4/krWWvBn5nFpeEZ7Z3rQdaVtJWKoU55Ciy8CG6QFFvD+2gHHu7S6pHqXZI3GhtSDp4Q3iWOR7Jx4q5i8x89w5PL5pw/oJA05e0uiWwRpOXPxefd8M3yqd39v8GNXVSVE3zAaHHgGoPA82/LGX7QWpJOWQYxxhVeCDYOOh7aPSJvqqSq7hM5h4x75FA+YJAM5tksfXL9pLHQTe0B+mX0ief5wa2XEVnhFDzIfHUsHPPGd2xXHRrTAowWWgIuChEOB24FHhmWO9pmgqPO5Z81m4kz4cA4mJMY4r0tNXCBqvHTPeyB/l343eiFylGbqV5RGGTMQHhsI5/Ef3GvHbbS5o9GVIIv6g5eAEYFkhXCN9pidp/O4ccyB4X73vg2VI1g4Z0stXChq63QjfJd/LX/neudyamfKWHhH+jPpHucIoPLA3PHH1bQApPWVIYvZg1WAr4DnhNqMS5jipiy4pcu04Lb2/wzkIro34ErAW9hpuXQRfKV/Wn8ye05z6mdgWSFIsTSpH6wJZfN/3abIe7WTpHGWhIsfhHyAt4DPhKOM9pdwpqG3BMsB4PX1NQwXIu82G0oHWzBpJ3SYe0h/HX8Xe1VzFGitWY1IPDVPIGgKM/Ra3ojJXrZxpUWXRozLhA2BKYEdhcuM95dKplO3kMpp3z71YwsvIfc1GkkEWjFoNXO5eoN+d36Vevxy52etWb1ImTXYIBoLCfVP35XKfLeZpm6YaI3dhQeCBILShVSNUJhvpkO3Ssrv3pL0igouINU030e4WN9m5HF1eVV9aH2teUNyY2diWa1IxzVCIb8L5fVc4MzL1LgIqOqZ545Th2mDR4Pthj6OAZnhpnK3NMqU3vPzrAkWH4oza0YmVzllOHDNd7978XtgeClxhmbJWF5IxDWOIVYMxfZ+4SnNY7q9qbmbwZAriTKF8oRtiIiPCZqgp+K3T8pZ3mTzygjpHRoywURPVUJjMG7EdcR5EnqtdrBvUWXjV85HkDW3Id4Mp/e14qzOJ7y2q9ed9ZJli1+HA4dSijGRaputqJK4nMpA3uXy6AepHIYw5EI2U/1g0Gtbc2V3z3eXdNdtxWOwVv5GKjW/IVQNifj941HQHb7vrUKggJX8jfCJeYmZjDmTIp0HqoK5HMtK3njyBwdZG9Au1UDdUG1eGmmVcKN0J3UecqBr4mEwVe1FkTSjIbcNaflV5RbSQ8BmsPeiYJjwkOGMUYxDj56VMJ+tq7W6z8t53h/yKAb7GfwsmD5JTpNbEmZ0bYJxHnJFbw1pqV9iU5pEwzNiIQYORvq55vnTlsIYs/SlkZs9lDGQio9Lkl+Yk6GhrSi8t8zM3tvxTgWQGAsrMDx6S3NYuWL8aQVut24NbB9mG11JUQZDwjL8ID8OHfsp6PfVFMUCtjWpEZ/hl9yTIJOxlXqbS6Tfr9y90s1F367xewQcFwEpnzl1SBFVE18vZi1q82p6aNhiOlrlTjJBjTFwIGAO7Pug6QzYuMchubes26LWm9+XEZdymeyeVadostC/Ic/l35jxrwOhFeEm6DY9RXBRJVsRYgBm1maNZDpfCFc4TB8/JDC9H2oOs/wf6zjagMpxvHew7aYboDacWZuKnbSir6o6tQPCpNCr4Jvx7gIhFKwkEDTWQZRN8VamXYBhY2JLYElbh1NCScw8hy7jHloObv2h7HXcac3vv2+0QaurpN6g9Z/2oc6mV65TuHTEW9KZ4bjxOQKdEmYiGDFCPoBJfFLyWLFcn122WwdXuU8GRjw6tyziHTAOHf4l7sPeb9CXw5241a+CqdOl4aSzpjirSrKxuyPHRNSu4u/xkAEZEREgBC6HOjlFyk35U5hXjFjRVndSoUuGQm83tCq5HOsNv/6p7x7hj9Nlx/y8pLScrg+rGaq9q+2vhrZTvw3KYNbq40Ly9gCWD7Ed2CqnNsNA4EjATjlSMFOjUZ1NQkfFPmk0gChpG4sNUf8q8YPjxtZWy4nBqbnzs5CwmK8Qseq0B7s0wzDNrNhN5bDybAAXDkgblyemMiI8wUNMSZhMkE0tTH1IoELEOikxHCbzGQ4N0/+m8u/lEdplzz7G4L6DuU+2WbWntiy6yr9Tx4vQKNvX5jvz9P+eDNgYRCSJLlo3cz6gQ7tGr0d1RhtDvT2HNrMtiCNWGHUMQQAc9GHoa92P0xfLRMRIv0i8Wbt+vK2/y8StyxvU092H6OPzjv8sC2YW4yBUKnAy+zjEPadAkkGAQHs9njgSMgoqxyCTFr8LngCJ9dTq0eDP1xDQ0Mk8xXbCkcGQwmvFBso+0N7XquBc6qf0O//ECfMTeB0KJmktXTO6N2E6QDtSOqI3RzNmLS4m2h2sFOwK5wDs9kbtQeQh3CTVfs9Zy9PI/MfZyF/LeM8D1dHbrONV7Ij1/P5nCIIRBRqwIUkony2KMe4zvDTxM5QxvC2JKCUixBqhEv0JHAFD+LXvtueC4E7aS9Wb0VrPls5Sz4XRHNX42fHf1uZx7oX20v4XBxUPjhZKHRUjxSc4K1QtDi5hLVcrASh9I+8dhhd0EPIIOwGM+R/yLevs5IvfMNv81wXWWNX21djX7doZ3zvkKOqv8J73vv7VBbAMFxPcGNId1iHJJJkmOiepJu8kGyJGHpEZIhQlDssHRAHF+n/0o+5d6dTkKeF33s/cPdzA3FPe5+Bj5Kzone0O89P4wP6kBFQKow9qFIUY1RtFHsIfRiDOH2IeDxzqGA4VnBC3C4gGNwHu+9b2FfLP7SXqMOcF5bLjPuOr4/HkBOfR6UDtM/GL9SP62f6EAwQINQz4DzETyRWvF9YYOBnWGLUX4RVsE2oQ9gwsCSsFEwEF/R75fvVA8nnvP+2h66fqV+qw6qzrQO1f7/Px6PQl+I77CP93AsMF0QiKC9wNtw8OEdkRFhLGEe4Qlw/QDagLMgmEBrQD2AAI/lj73fiq9s30U/NF8qnxgPHJ8X7ylvMH9cP2ufjZ+hH9Tv9+AZEDeAUlB4sIpAlnCtMK5wqlChIKNwkcCMwGVQXDAyQChgD3/oH9L/wK+xr6Zfns+LL4tPjw+GH5AfrG+qr7o/yn/az+q/+ZAHIBLwLLAkIDlAPBA8kDrwN4AygDxAJTAtoBYAHqAH4AHgDR/5b/b/9d/17/cP+R/7z/7f8fAFAAeQCWAKQAoQCJAF0AHQDL/2j/+f6B/gf+kP0h/cL8d/xH/Db8R/x9/Nj8Wf39/cL+of+UAJUBmwKdA5EEbgUrBr8GJAdSB0UH+wZzBq8FsQSBAyUCpwAT/3P91/tK+tz4mPeM9sL1Q/UW9UD1wvWb9sf3QPn9+vD8DP9BAX4DsgXJB7IJXAu5DLkNVA6ADjsOgg1YDMUK0QiKBgAERgFx/pb7zPgq9sbztPEI8NDuGe7s7UzuO++08K3yG/Xs9wv7Y/7XAU8FsAjdC7wONREyE6IUdhWlFSoVBxRAEuIP+wyiCe0F+gHn/dL52/Uk8sru6eua6fLnAOfO5mLnuejN6o/t7fDO9Bb5pP1VAgcHkwvUD6kT8haTGXQbhRy6HA4chBolGAEVLRHFDOsHwgJ0/Sf4B/M77uvpO+ZI4y3h/d/D34bgQeLr5HDoueyl8RH30vy8AqMIWA6tE3gYkBzVHyoieiO5I+Ei9SADHh4aYhXyD/cJngMZ/Zn2UfBz6i7lruAX3YfaFtnS2L/Z2dsT31bjg+h17v707fsLAyQK/hBkFyIdCiL0Jb4oUCqcKpspVCfUIzQflxklEw8MjATW/Cb1u+3O5pfgSNsM1wfUUtL/0RLThtVK2UTeUORA6+Dy9vpDA4gLgxP2GqYhXCfqKyovATFdMTkwmi2TKUAkxx1bFjIOiwWq/NHzR+tP4yncDNYs0bDNtstRy4XMTc+W00DZI+AK6Lrw7/ljA84M5RVhHv4lgCyyMWo1hzf3N7M2wzM7Lzsp8CGRGVwQmgaV/Jry+Oj53+fX/9B8y4nHSMXNxB7GNcn7zU/UANzW5Izu2fhtA/YNIhiiISkqdDFJN3c73T1kPgU9yTnHNCIuDCbDHIwStweX/ILxzebP3NTTJcwAxpbBDL95vuO/QsN/yHPP69em4VrstvdfA/8OORq2JCIuMzapPE5B/UOeRClDpz8yOvAyGSrvH8AU4Qiv/IjwyuTR2fTPgse9wN27CblauNi5er0nw7PK6NN/3ibqhvY9A+oPKRycJ+gxujrOQelG4kmgShlJWEV3P6E3ES4RI/MWFgrd/K3v7eID10rMGMO3u2G2QrN2sgS04rf3vRPG+89j2/PnTPUFA7UQ8R1SKnY1Bj+0RkRMiE9lUNFO1kqRRDA88jEmJiUZVAsf/fHuOuFl1NjI7L7ytiixvq3RrGqugLL0uJfBKMxW2MPlCfS5AmERkB/WLMw4EkNYS1tR6lToVUtUHFB7SZhAtzUrKVMbmgx0/VTusN/70aDFALtxsjWsgKhwpxGpVq0jtEO9csha1ZnjwPJaAu8RBSEnL+Y73Ua1TylWA1olW4NZJ1UxTtZEXDkcLHkd5g3c/dXtUN7Ez6TCWLc4ro2njaNZovyjbKiIrxy53sR00nfhcvHpAV4SUSJEMcI+Y0rJU6pa0F4XYHNe8FmvUuZI3jz2LpYfNg9V/nXtGt3Czee/9bNKqjOj6J6OnTCfxKMpqya1b8Gnz2DfIfBoAbASciMqM2BBok2QV9xeS2O5ZBljdV7wVsJMOUC2MaYhhxDe/jLtDtz2y2q92rCqpiqfl5oVmbKaZJ8Ip2SxKb71zFfd0O7YAOQSaCTbNL1DmFAIW7ticmcIaW9nsGLwWmhQakNYNKcj2BF2/w3tLdthyi67Ca5ao3abm5bxlIaWT5sqo9utD7tiyl7bgO05APwSNCVVNtdFQ1MvXkRmQmsAbXFrnmarXtRTbEbaNpclJxMZAAPtddoDyTS5hKtdoBmY+ZIlka6SiZeTn46qJbjyx3nZM+yQ//gS1iWXN7BHolUBYXRptm6fcB1vO2odYgFXPUk5OXIncRTJABTt6Nndx363TKm2nRaVs4+1jS+PFpRGnICnbrWmxanX7Orb/toSTyaiOERJs1d+Y0lszXHfc25yg21DZe5Z2UtyOzYptBWCAT7thNntxgu2Yqdkm3CSy4ykigyM+ZBHmbak7rKBw/HVreke/qMSnyZ2OZRKdVmkZcFuhHTAdmJ1dHAaaJVcPU6BPeEq7xZEAoLtSNk1xt20yKVrmSeQRYr0h0eJNY6ZljGiprCIwVTUeOhZ/VQSxyYSOqBL6FpxZ9pw2XY+efd3CnOfavZeZ1BkP3AsHhgLA9ztNNm0xfOzfaTKlz2OIoioheSGzYs+lPafm668v9TST+eP/O4RyCZ5OmhMClzlaJNyynhYeyl6RHXPbAxhVFIZQeEtQBnXA03uRtloxU6zg6ODlrSMY4bBg+SEw4k5kgaezqwfvnPRNObC+3MRoiapOuxM3Fz+aexzVnoMffd7HneobtViAFSdQjEvUxqlBNHuftlTxeyy2aKWlY2LCoVBgkmDGYiNkGScQqu1vDTQKuXz+uUQWCalOixNXl2+auJ0fHtYfl99mHgncE9ka1XtQ14wVBt0BWjv2tlxxc2yfqIElceKGIQqgRSC0YY7jxKb+ql/uxrPMuQl+kYQ6yVsOilNkV0ja3d1O3w7f19+rnlLcXllkVYIRWUxQhxCBhDwWNrDxfGydKLMlGSKjIN7gEiB7IVFjhKa9qh/uiXOT+NZ+ZYPXCUBOuVMdF0va6l1kny1f/d+YHoTck9mcVfrRUYyGh0MB8fw99pGxlWzt6LtlGKKaYM2gOSAbYWtjWWZOqi4uVnNguKR+NgOrSRmOWBMCl3hanp1gnzFfyd/rXp8ctJmCViVRv4y2x3RB4vxttv6xvqzSaNolcOKrINbgOmAUoVzjQ2ZxqcrubbMzuHP9w4O4COaOJxLUlw6aul0DHxrf+1+lXqGcv9mWFgFR4szgx6PCFvykdzdx920JqQ6loOLVoTqgFiBnYWZjQuZnKfauD/MNOEW9zoN9iKhN5tKT1s9afhzLnuofkl+F3oxctVmXVg4R+wzDx9ECTTzid3syP21TqVil6SMZoXhgTCCT4YejmCZvafGuPXLteBm9l0M8iF9Nl5JAlrqZ6ly7Hl8fT19Mnl8cVVmFlgtRx80fx/uCRT0md4lyle3v6bfmCKO24ZBg3CDZocDjwyaKqjvuNnLVODC9XoL1iAuNedHblhDZvxwRnjoe8l76XdncH5lg1flRiM00B+LCvr0wd+Iy+m4d6ivmv2Ps4gIhRiF4ohHkA6b4qhXue3LE+Ar9ZIKox+5MzlGk1ZKZPNuPXbvee55O3bzbk9kpFZdRvczAiAbC+P1/+AQzbK6c6rQnDKS7IozhyaHworrkWic6Kn/uTLM8d+k9KgJXB4eMlZEdlQCYpJs1HORd613KXQgbcpieVWVRZkzEyCaC872T+K8zq+8saw+n7+UhI3DiZiJBY3tkxmeOavnuqjM8d8t9L0IAx1hMEFCGFJuX9ppDnHRdAl1tXHvau9gAlSNRAozAiAIDLj3sOOK0Ny+Lq/4oaGXeJCzjG6MqY9Llh+g16wPvFDNFODJ89MHmhuDLvw/fU+PXM5m7G2xcQNy4W5jaL5ePlJFQ0kyzR9iDKD4H+V30jjB57H7pNaaxpMCkKOPrZIFmXqiwK53vSvOW+B48+0GJBqILIo9p0xqWXJjcmo0bp5urmt8ZTlcL1C9QVQxdB+oDIT5m+aA1L/D2bRCqFmea5eskzeTDpYZnCil9LAevznPxuA98wwGoxhyKu86mUkCVshfo2Zeat1qIGg8YmJZ1032Py0w9h7ZDGL6Ieii1m7GAbjLqymiY5uulyWXyZmEnyiocbMFwXrQV+EY8zIFGhdEKCw4WEZZUtVbgmIwZsNmOWSnXjpWNUvwPdIuUx7yDDj7runb2ELJXLuSr0Cmq58GnGqb251Eo3irNrYqw+7RDeIK82AEihUBJkc15UJ0TptXFF6wYVNi/F++WsNSTEisO0UtiR3zDAX8QOso2zjM5b6Ts5uqPqSuoASgQqJVpxWvQrmNxZTT6uIW85kD9hOrI0EyRj9XSiBTXVnhXJFdbFuEVgBPHkUrOYYrmhzbDMb81eyG3U3PmcLLtzavGamjpe2k+aa2q/2yk7wsyGzV7eM6894CYBJGIR4vfjsGRmZOYFTGV4JYjlb9UfRKrEFvNpUphBupDHv9a+7y333SdcY1vAy0N67hqiKq/qtjsC23JsAFy3bXFuV58zACyhDUHuIrkDeEQXRJIk9mUihTZVEsTaFG+T15M3MnSBpdDCH+APBp4sTVdMrNwBq5k7NjsJ+vS7FXtaK7+MMYzrDZZebT85IBNw9YHJAogTPXPExEqEnETIlN9EsVSAtCBzpLMCIl5hj1C7j+kfHp5CDZks6OxVq+Krkktl+13baQulnACMhh0Rjc2udJ9AMBqA3VGSslVS8DOPU+90PlRqpHQka8QjU92jXnLKIiXhdyCz3/HPNu543cy9J1ysfD9L4gvF27rrwIwE3FUszf1K/edOna9IYAIQxOF7ghDysMM3M5FD7OQI9BUkAlPSI4dDFPKfYfsRXTCrH/oPT26QbgHNd7z13J78RQwpTBu8K8xXzK09CP2HHhMuuH9RwAogrFFDketCb3LcozBDiFOj07KjpVN9gy2CyHJR4d4RMYChEAGvZ/7IrjgNue1BfPE8uxyP7H/siny+HPiNVv3F7kFe1Q9sb/LQk+ErIaSCLIKAEuzDEPNLs0zTNQMVotCyiQIR0a7RFBCV4AifcF7xTn89/X2e/UXdE7z5fOcs/E0XjVbdp84HPnGu8194T/xQe6DyYX0B2FIxsocitxLQ0uQy0cK6wnECNuHfUW1w9OCJYA6viF8aDqcOQj3+Daxtfq1VjVEtYP2Dzbft+y5K7qQPE1+Fb/awY9DZkTThkyHh8i+ySyJjknjya9JNMh6h0kGacToQ1AB7gAPfr+8yzu9Oh85OXgSd643D3c2NyB3ijht+QP6QzuhvNR+T//IAXKCg8QyRTTGBIcbh7XH0UguR85HtMbnhi1FDgQSwsXBsUAf/ts9rTxe+3e6fnm4OSf4z/jvuMW5TnnFeqP7Yzx6/WH+j3/5gNhCIoMQxBvE/kVzxflGDcZxRiVF7MVMRMkEKgM2AjUBLsAsPzO+DX1//FE7xftheua6ljqvurI62ntku8v8iv1bPjX+1L/vwIGBg4JwAsJDtkPJBHkERUSuRHWEHYPpQ12C/sISQZ3A5sAzf0h+6v4f/ap9DjzNPKh8YLx1PGR8rLzKvXr9uX4CPtB/X3/qwG8A54FRQemCLcJdArYCuQKnAoDCiEJAQiuBjQFoQMCAmQA1/5j/RT89PoJ+lj55fiw+Lf4+Pht+RD62Pq++7j8vP3C/r//rACDAT0C1gJLA5oDwwPIA6wDcgMgA7sCSQLQAVYB4QB1ABcAy/+S/23/XP9f/3L/lP/A//L/JABUAHwAmAClAJ8AhgBZABcAxP9g/+/+d/79/Yb9Gf27/HL8Rfw2/Er8g/zh/GX9Df7T/rT/qQCrAbECsgOkBH8FOQbKBioHUwdBB/IGZQacBZoEZQMGAoYA8P5R/bX7Kvq/+ID3efa09Tz1FvVH9dD1sfbk92P5JPsc/Tv/cQGuA+AF9AfYCX0L0gzKDVwOfw4wDm0NOwyfCqMIVgbHAwoBNP5a+5L49PWW843x6e+87hDu7u1b7lXv2fDd8lT1LPhR+6z+IQKZBfYIHQz1DmQRVxO6FIEVoRUZFecTExKpD7gMVgmbBaQBj/17+Yn12PGH7rLrcOnW5/Tm0+Z3597oAevR7TvxJvV1+Qf+ugJqB/ELKxD1EzEXwxmTG5IctBz2G1oa6he1FNQQYgx/B1ICAv24953y2u2W6fTlEuMK4e7fyt+h4HHiLuXE6BztFPKJ90/9OwMgCc4OGRTWGN4cECBQIoojsiPCIsAguR3BGfQUdw9zCRQDjvwQ9s/v/OnG5Fjg1txe2gXZ2tjg2RPcZN+84/vo++6P9YT8pAO5CowR5heUHWgiOybsKGMqkyp3KRUnfCPGHhUZkxJzC+kDMfyF9CLtQuYc4OLav9bV0z7SCNI508nVqdm73tzk3euJ86b79QM2DCgUjRsqIsknPCxgLxcxUzEPMFItLSnAIzIdsxV9Dc8E7PsX85fqruKb25jV1NB3zZ7LW8uxzJrPAtTI2cLgveh68bj6LgSUDaEWDR+VJv0sETKnNaE37TeFNnIzyS6rKEch0xiRD8YFv/vI8THoQ99H13zQGMtIxyzF18RPxovJdM7m1LLcneVj77n5TwTUDvUYYiLRKgAysze8O/o9WT7SPG85STSDLVEl8RuqEcsGqfuY8PDlBNwj05PLkMVNwe2+g74YwKDDA8ka0K/YguJH7a34WQT0DyIbiiXdLs42Hj2bQR9Ek0TyQkY/qDlCMkwpCR/IE98HqvuI79fj89gxz+DGQsCMu+W4ZbgRuuC9tsNpy73Ubt8p65P3TQT1ECcdhCizMmM7T0I+RwhKlUrfSO9E4j7lNjQtGCLnFf4IwvuX7ubhEdZ2y2jCMLsIthqzgLJAtE+4kb7WxuHQZdwK6W/2KwTVEQMfTStTNr0/QEehTLNPW1CTTmZK8kNmOwUxGyUFGCgK7vvG7R7gYdPzxy6+YLbHsJKt2qyprvOymLlnwh3Nadnt5kD18wOWErYg5C25OddD70u/URlV31ULVKZP00jDP7o0DiggGloLMPwV7YHe5NCrxDW61LHNq0+oeadSqc+t0LQfvnbJf9bV5Ar0qAM3Ez4iRjDiPK9HV1CVVjZaHVtAWatUgE31Q1I47yo1HJMMhPyE7A7dnc6gwX+2ka0dp1ejYKI/pOqoPrADuu/FqNPE4s/ySgO5E5sjczLOP0JLdVQeWwdfEGAvXnBZ9lH6R8c7ui1BHtEN7PwR7Mfbi8zUvg+zmKm7oq6elJ12n0ek5asWto3C6dC94I/x2gIcFM0kajR6Qo5OR1hXX4djtGTTYvBdMFbNSxY/bDBCIBIPZP2+66var8pJvOiv7qWrnliaGZn5muufy6deslK/Rc7D3k3wWgJhFNMlKTbkRJBRyFs9Y7NnBWkoZydiKVpqTztCAjM1IlQQ6/2I67rZDMkAugytlqLwmliW85TNltmb86PdrkO8vsvY3AzvywGIFK4msTcMR0ZU+F7NZodrAG0qaxJm313NUjNFeTUXJJURgf5w6/XYoMf6t3yqkJ+Ml7GSJZH2kheYYaCXq2K5WMn+2sztLwGSFF4nADnwSK9W02EEagBvoHDVbqxpTGH0VftHzTfnJdISJP9z61rYbcY4tjqo35yDlGaPs413j6aUGZ2QqLS2Fsc52ZHshwCBFOMnFzqPSspYWGTfbBty43MncvNsb2TbWJBK/TmhJwoU0v+S6+rXcsW7tEemhprWkXuMn4pTjIqRHZrLpTq0+sSL113r1f9VFD4o9jrpS5VahWZdb9d0xnYcdeNvQ2d+W+5MBDxDKTsViADL66TXsMSDs6SkhZiHj/CJ7YeOiceOcpdLo/ixCMP21TDqGv8PFHAonDv+TA9cWWh8cTB3R3mxd3hyxWnaXRJP4T3KKmIWRgEc7IfXJsSRslKj3paYjcmHnoUph1+MGZUTofKvQsF91A/pWP6yE3koCjzOTTld02k7cyV5ZHvkebJ09GvtX/tQkD80LH0XCwKF7JHX08PksVGikZUKjAaGtIMnhVWKFZMmnyiuqr8i0/vnkv0/E1soQjxYThJe82qYdLV6Gn20e412zG21YaVSEEF/LYoY0wID7cLXt8N8saGhoJTeiqqEMoKLg6qIaZGFnZ+sQ77n0fXmyPy2EhcoQzyeTplet2uTdd57aX4dfQd4S28uYw1UXkKpLocZnQOV7RnY0MNYsUKhCZQVirSDF4FUgmGHF5AznFirD73P0AHm/fsbEq4nDzygTtBeIWwrdqB8Tn8gfh55cHBXZDNVd0OvL3MaaAQ67pTYHsR4sTOhzZOuiSaDZoCFgXuGII8zm1SqELzczx/lNPtuESInqDtfTrZeL2xgdvt8y3+7ftN5OHEvZRNWW0SPMEobMAXv7jHZn8TasXSh65Oqif+CH4AfgfmFho6EmpepSLsPz1LkbPqxEHUmDjvcTU5e5Gszdu183X/tfiJ6pHGzZa1WBkVIMQsc9gWz7+7ZUsV+sgOiZJQIikCDQYAigdyFSo4qmiGpubprzp3jqvnmD6clQzoZTZhdP2uldXl8hn+1fg16sXHjZf9WeEXXMbUctQaE8MvaNMZgs+CiNZXHiuiDzYCOgSSGbI4lmvSoZbrxzQDj7vgQD7wkSTkXTJVcQmq1dJ57xX4VfpJ5X3G+ZQdXr0U8MkUdbQdf8cTbRceBtAmkXZbmi/aEwoFjgtKG7Y51mhCpTLqizX3iOvgwDrUjIjjYSkdb72hnc116nH0MfbF4rnBCZcZWqkV0MrodHAhE8tncgsjdtXul2pdkjWqGIIOgg+WHzo8cm3epcLqBzRfikfdHDZQi0DZfSbFZR2e6cbd4C3ybe2x3nm9wZDlWZ0V/MhIewAgv8wbe6clztzWnrJk/j0CI5IREhV2JDZEZnCqq0bqOzc7h8/ZZDFshVTWtR9NXTWWxb692E3rDecJ1MG5IY2FV50RaMkseVwkg9Erfd8tBuTWpz5t1kXmKDodPhzmLq5JsnSercbvKzaThY/ZnCw0gtDPERbJVAmNObUd0t3eGd7RzY2zKYT5UKEQGMmUe3wkT9aLgKs1Du3erQJ4ElBGNnIm/iXeNp5QVn3CsT7w2zprh4/VyCqse7zGoQ09TamCUaoBx+XTldEVxOWr2X89SKkOBMV8eVwoI9g3iAc94vfqt/qDplgaQi4yRjBaQ/5YToQWubb3UzrLhc/V+CTgdCDBcQa1Qh12GZ11u2nHicXZus2fOXRVR7UHLMDYevgr89ofj99Dcv7qwBqQgmlWT2I/DjxWTspllo+Ovyb6jz+zhFvWLCLcbAi7hPtBNXFomZOJqXm6Abklr02RSWxFPcUDjL+odEQvt9w/lC9NtwrWzU6eonfyWgpNTk3CWvpwKpgyyZcCj0EnizfSdByka4Ss7PLpK7VZ4YBFniGrDasFnnGGFWMRMtj7KLnodUAvZ+KLmOtUnxea246p7ofaahJc+lyWaIaAAqX60PsLW0cvimfS0BpEYpiltOW5HPVN/XO9iW2arZt9jDl5nVS9Kvjx+LecceQu++T7ogNcHyEq6sq6YpUCf25uBmzKe2KNFrDa3VcQ603Hje/TSBfIWVCd7NvFDUE9AWH5e22E+YqhfLVr7UVNHiDoBLC4ciwuc+uDp3NkLy969vLL5qdejg6AXoJOi4afXrzW6qcbQ1DzkdPT5BE0V7yRoM0dAKku+U8NZC11/XR5b/FVETjJEFzhSKlAbhgtv+4frStwuzp/B/baarrWoeaX+pESnOay0s3i9OMmX1i3lh/QsBKUTeSI2MHI8z0b+TsJU8FdyWEZWflFDSs5AazVzKE0aZws2/C/tx95t0YfFcrt4s9etuKoxqkOs3bDYt/zAAcyO2EPmsvRrA/0R9h/qLHY4QkIESoBPj1IbUyJRtkz8RSo9hjJkJiUZLwvx/NfuUeHF1JTJFcCOuDizO7Crr4qxyLVBvMDEAs+12n7n9/S3AlUQZx2HKVk0ij3URAFK60x+TbhLqUdyQUc5aS8mJNcX3Aqd/X3w4+My2MHN4sTWvdS4/rVptRa397rrwMDIOdIK3d7oV/UTArIO0BoRJh0wqTh0P0tEC0ehRwtGWUKpPCo1Fyy6IWUWbwo4/h7yfeax2wvS1clNw6S++7tlu+K8ZsDSxfvMpdWM32Lq0fWAARUNNRiLIscrpTPnOWE+8kCIQSFAzDykN9QwkygjH84U5wnD/rfzGuk932zW6c7tyKXELsKawerCEcb0ymzRQtk64grsZ/b+AH8LlxX4Hlwngi41NEo4pjo4O/45BTdmMkgs3SRgHBQTRAk8/0n1uOvV4uHaGtSyztDKkcgDyCfJ8stM0BDWD90R5dbtGPePAPMJ+RJdG94iRSlgLgwyLTS3NKczCjH1LIwn+iB1GTgRhQih/8/2Ve5z5mbfYtmV1CHRH8+bzpbPBtLW1eTaCOEQ6MPv5fc0AHIIXxC8F1Me8iNvKKorjC0KLiIt3ypUJ6Ei6xxiFjoPqwfy/0n47PAV6vbjvt6S2pLX0dVb1TDWR9iM2+TfK+U169HxzPjv/wAHyg0aFL8Zjx5nIislySY3J3QmiSSJIYwdtRgrExsNtgYtALT5ffO37Y3oJ+Sk4B3eo9w/3PHcsN5s4Q3ldOl97v/zz/m9/5wFPgt6ECYVIRlNHJUe6h9DIKIfDh6XG1EYWhTSD94KpgVTABD7BPZV8SftmenF5r3kj+NB49LjPOVv51nq4O3m8Uv26/qi/0gEvQjeDIwQrBMnFu0X9Bg1GbMYcxeDFfUS3g9ZDIQIfQRkAFv8fvjs9MDxEO/v7Gvrjupa6s/q5euS7cXvbPJu9bT4Ifyc/wcDSgZLCfULNA75DzkR7RETEqsRvRBTD3oNRAvDCA4GOgNeAJP96vp6+FT2h/Qe8yPymvGE8eDxpvLO8031E/cR+Tf7cP2t/9kB5gPEBWUHwAjKCX8K3AriCpIK8wkMCecHkAYTBX8D3wFCALf+Rv36+976+PlM+d74rvi6+AD5efkf+uv60vvO/NL91/7U/78AlAFLAuECUwOeA8UDxwOoA2wDGQOyAj8CxgFMAdcAbQAQAMb/jv9r/1z/YP91/5f/xP/2/ygAVwB/AJoApQCeAIMAVAARALz/V//l/m3+8/18/RD9tPxt/EL8NvxN/In86/xy/Rz+5f7I/74AwQHGAscDuASQBUcG1AYvB1QHPQfpBlcGiAWCBEoD5wFkAM7+Lv2T+wv6ovhn92X2p/U29Rf1T/Xg9cf2AfiG+Uz7SP1p/6AB3QMNBh4I/gmcC+oM2g1jDn0OJA5YDRwMeAp1CCIGjgPOAPf9HftY+L/1Z/Nl8cvvqO4I7vLtau5x7//wDfON9Wz4l/v1/msC4gU8CV0MLQ+TEXoT0RSKFZ0VBRXGE+URbw90DAkJSAVOATj9Jfk49Y7xRu5860fpvOfq5tnmjucF6TfrFO6K8X711Plr/h8DzAdODIAQQBRvF/EZsRudHK0c3BsuGqwXaRR6EP0LEwfiAZH8SPcz8nrtQumv5d/i6eDi39Lfv+Cj4nLlGumA7YXyAfjN/boDnAlED4QUNBkrHUogdSKYI6gjoiKJIG0dYhmGFPwO7giKAgL8h/VO74bpYOQE4JfcNtr22OTYBNpP3LffI+R06YPvIPYb/TwETgsZEmYYBB7EIn8mFyl0KogqUSnUJiIjVR6RGAES1QpFA4z74/OJ7Lflo99/2nXWptMs0hTSYtMQ1graNN9q5XvsM/RX/KYE4wzMFCMcrCI0KI0ski8rMUcx4y8HLcYoPyOaHAoVyAwSBC77XvLn6Q7iENsl1X7QQM2Jy2jL4Mzqz3DUUtpk4XDpO/KA+/gEWg5cF7cfKSd3LWwy4TW4N983UzYdM1QuGSicIBUYxA7xBOn69/Br54/eqtb6z7fKCscTxeXEg8bjye/OgNVm3WbmO/Ca+jEFsQ/GGSEjeCuIMho4/jsVPks+nDwSOccz4SyUJB4bxxDfBbv6sO8U5TvbdNICyyTFCMHQvpK+UMABxIvJw9B22WDjNu6k+VMF6BAIHF0mlC9lN5A95EE9RIVEt0LgPhs5kjF9KCIezxLcBqX6ie7l4hbYcc5Cxsq/P7vFuHO4TrpJvknEIcyV1V/gLOyh+F0F/xEjHmopfDMJPMxCj0cqSodKoEiCREo+JjZULB0h2RTlB6f6gu3g4CLVpcq7wa66tLX3so6ygLTAuC6/nMfJ0WndIuqS91AF9RITIEYsLDdxQMlH+UzYT01QUU7ySU9DmjoUMA4k4xb6CL76newE31/SEcdzvdK1a7Bqreis7a5qsz+6OcMVzn/aGOh49i4FyhPaIe8uojqYRIJMH1JDVdJVxlMsTyZI6T67M/Am6xgYCuv61+tT3dHPucNsuTyxaasjqIanmKlNroG1/r59yqXXEuZV9fYEfxR1I2Mx3D1+SPRQ/FZlWhBb+VgrVMtMEENEN8Ep7ho/Cy37M+vO23jNn8Cqte6ssqYno2yiiKRtqfew7boEx9/UE+Qs9KsEExXjJKAz1kAdTB1VjVs6XwVg5V3qWDlRCkesOn0s6hxrDIL7r+p22lbLxb0tsuyoSaJ6np+dwJ/PpKesC7euwy7SHOL98k0EiBUmJqc1kEN1T/hYzV++Y6pkiGJmXWtV00ruPSEv2x6cDen7SupJ2WvJLLv7rjilMZ4fmiKZRJt3oJOoXLN/wJfPMeDL8d0D3RU8J3U3CEaDUoNcumPuZ/1o22aZYV5ZZ04JQaoxwCDODmH8BepJ2LnH1bgTrNahb5oalvqUGpdpnMKk5K96vR3NU96Y8F0DExYmKAs5PEhEVbxfUWfGa/ls3WqBZQ1dw1H3QxU0lSIBEOj83ul210DGw7Z4qceeBZdvkiuRQ5OpmDWhpqyjusLKhtxm788CKxbkKGc6LEq4V6BijmpEb5twiG4YaXZg41S2Rl82WSQyEX791OnO1gHF9rQspw+c9ZMgj7eNxI87lfGdpan9t4rIzNo37jMCJhZ1KYk71kvcWS1lcG1kcuBz2XFdbJRjw1dDSYU4CSZfEiD+5+lS1vvDb7Mwpa6ZQpExjKGKoIwhkvma5qaKtXfGKNkN7YsBBRbbKXM8Ok2wW2Fn9G8jdcZ2z3RLb2VmYVqaS4Q6oieFE8z+FeoC1i7DLrKFo6aX7o6iieyH2olfj1GYaqRPs4zEm9fq69oAyhUXKiI9WE4yXTxpGHKAd0l5ZXfgceVouVy6TVo8ISmkFIL/Xerb1ZvCM7EroviV+ox3h5qFdYf4jPqVNqJNscvCKdbR6iAAdRUpKpk9ME9jXr1q3HN5eWh7mXkZdBJryV6eTwQ+hSq4FT4Avure1UHCf7AjoaaUZ4uwha6DcoXtiveTSqCHrzjB1NTC6WL/CRUSKtg9wU9CX+FrPnUNeyF9anv0delsj2BEUYA/zCvAFgABNusJ1h7CEbBuoK6TN4pQhCmC04NCiUySq54ArtS/ndPB6J3+hhTTKd89DFDOX6tsPXY6fHJ+1nxvd2huB2KrUstA8iy5F8YBw+ta1jLC6K8KoBOTaYlXgwyBm4L4h/mQWp26rKK+iNLQ59b97xNvKa89ElAJYBht2Hb/fFt/2n2IeI5vMWPQU+NB9i2iGI0CZOzR1nzCBLD3n9SS/4jFgliAyoEQhwGQWZy3q6S9ltHw5g/9RBPmKEs91U/0XyptEXdcfdp/d34/eVhwCWSxVMdC1i54GVUDGO1s1/vCY7A2oO+S+Iicgg6AYYGMhmWPqZv4qty8ydAk5kj8iBI6KLI8VE+NX+Fs53ZSfe9/rH6RecZwj2RMVXRDjy86GhoE2+0p2K3DBbHDoGWTU4nbgi6AYYFshiePTZuAqku8I9Bt5YX7vRFsJ+g7kk7YXj5sWnbffJt/d35+edZwwmShVehDITDmGtsEre4G2Y/E6LGfoTWUEYqAg7eAyoGxhkaPRJtQqvO7pc/N5Mb65RCAJu06j03WXUJrbHUGfNx+2n0GeYhwoGStVSNEiTB5G5YFi+8C2qLFCbPIol2VL4uNhKqBnIJch8OPkJtoqta7U89G5A/6ARB2JcQ5T0yHXO9pHnTHerV91HwpeNtvKmRxVSNExzDzG0oGdPAa2+LGaLQ8pNuWrIz/hQWD1oNriJ+QMpzJqvS7K8/a42D5FA9QJG4400rvWkZocnIjeSZ8ZnvodtBuXWPqVOdD2DBRHPQGZvFM3E3IAbb4pa6YiI7Vh8iEeIXeidmRKZ11q068Mc+K47v4Hw4RI+42HEkPWUpmaHAcdzF6kXlCdWdtPGIZVG5DuzCTHJIHXfKX3eHJ1Lf8p9Oav5ANivCGf4e2i3GTdZ5rrOa8Zc9Y4yP4JQ28IUc1L0fpVv1jBG6zdNd3V3c6c6BrxWD+UrdCcDC2HCQIWvP33pvL3LlDqkidT5OljHuJ64nvjWeVF6Csrbu9yM9E45n3JwxRIHozDEWBVGFhSGvscRp1unTQcHxp+V6YUcNB9S+6HKcIWPRr4HrNGLzLrAqgNpaaj2mMuoyJkLiXDaI3r86+WtBQ4x73KAvUHooxuELZUXleN2jJbv1xu3EGbv5m2VzoT5FASy+dHBkJWPXw4XrPhL6SrxajcJnqkrWP6Y+Ck2OaVqQLsR/AHdF+47T2KQpIHXovNED0Tklb1GRNa4JuXG7faiZkZ1rvTSE/cC5eHHoJVfaE45nRH8GUsmmm+5ySll6TdpPYlmid8aYps67BENLO4132LQmtG00thD3WS9RXImF7Z61qompcZ/Zgo1etS3M9ZC39G8cJUPcl5dTT5MPOtQCq06COml+XXZeHmsKg3amOtXrDNNNA5Br2NQgHGgUrqzqBSB1UJV1WY4BmjmaAY3BdkFQkSYk7KCx5GwAKRfjP5ijW0MY8udat9aTanrabnJuOnnGkF606uIPFidTW5Oz1QwdYGKUorDf6RChQ4FjiXgBiJGJPX5hZL1FVRmI5uirRGiMKM/mC6JPY4MncvOmxW6l0o16gMKDponKonrAsu8jHDtaQ5dT1WQajFjEmizREQflLWFQkWjFdaF3LWnBVg01CQwA3HSkFGi8KGPo66hDbEc2owDO2A65WqFSlFKWUp8Gsb7RgvkfKxNdu5tP1eQXpFKsjSzFiPZNHkU8gVRVYXlj5VftQjkntP2Q0TycVGSQK8/r0657dX9CdxLK66LJ8rZOqQ6qNrFuxh7jWwf/Mqdlx5+v1pQQuExUh7y1aOf1CkErZT7NSCVPbUD1MVEVYPJAxUyUAGAAKwfuw7TrgyNO4yGC/Brjhshewu6/OsT2247yKxe7PvduY6Bv23QNzEXQefCouNTk+WEVWSg9Nb013SzlH1kCEOIUuKCPHFsMJgvxp7+DiRtf0zDnEV72BuNu1drVUt2K7gMF7yRTT/t3j6WX2IwO7D8ob9CbjMEw57j+aRCxHlEfRRfNBGjx3NEYr0SBqFWwJNP0g8Y3l1tpN0TnJ18JXvtq7cLsavcjAW8amzW3Wa+BR68r2eQIIDhoZWyN9LDs0WTqrPhJBfUHtP288IjcxMNQnTh7qE/oI1f3Q8j/odt6+1VrOgchexA/Co8Ebw2nGb8sG0vfZBOPj7Ej34AFbDGcWth8BKAovnDSOOMQ6LzvPObI28jG2KzIkoRtHEm8IZf549PPqIeJE2pnTUM6QynXIC8hTyUDMutCa1rHdxeWX7uH3WgG4CrMTBhxyI78pvS5IMkg0sDR+M8EwjiwKJ2IgyxiCEMgH4/4W9qbt1OXb3u/YPtTo0AXPoc68z0rSNtZd25bhruht8JX45gAgCQIRURjVHl0kwSjgK6QtBC7/LJ8q+yYwImcczxWcDgcHTf+o91Xwiul941reRtpg17vVYdVR1oLY39tM4KXlvetk8mT5hgCUB1YOmhQvGuserSJZJd4mMidWJlMkPSEtHUUYrxKWDCsGov8t+f3yQu0n6NPjZODz3ZDcRNwM3eHeseFk5drp7+559E36OwAXBrML4xCCFW0Zhxy7HvsfPyCJH+IdWBsDGP8TbA9xCjUF4/+i+pz19vDV7Fbpkeab5IDjRePo42Plp+ef6jHuQfKs9k/7BQCqBBkJMg3UEOcTVBYLGAEZMhmfGFAXUhW3EpcPCgwvCCYEDQAG/C/4pfSC8d3uyexT64PqXerg6gPsvO3676nysvX8+Gz85v9OA40GiAkpDF8OGRBOEfYRDxKcEaQQMA9ODRELiwjTBf0CIgBY/bT6Sfgq9mX0BfMT8pTxiPHs8bvy6/Nw9Tz3Pvlm+6D93P8GAhAE6QWFB9kI3QmKCuAK3gqHCuIJ9QjMB3IG8gRcA7wBIQCX/ij94fvJ+uf5QfnY+K34vvgI+YX5L/r9+uf74/zo/e3+6P/SAKQBWQLsAloDowPGA8YDpANmAxEDqQI1ArwBQgHOAGQACQDA/4r/af9b/2H/d/+b/8j/+v8sAFsAgQCbAKUAnQCAAE8ACgC0/07/3P5j/un9c/0I/a38afxA/Df8UfyQ/PX8f/0s/vf+3P/TANYB3ALcA8sEoQVUBt0GNQdUBzkH3wZIBnUFagQuA8gBQwCr/gv9cvvr+Yb4UPdT9pv1MPUY9Vj18PXe9h/4qvl1+3T9mP/QAQ0EOwZICCMKuwsCDeoNaQ56DhcOQg39C1AKRgjtBVUDkgC6/eH6H/iK9TnzP/Gu75buAO727Xvuje8n8T/zx/Wt+N37Pv+2AisGgQmdDGQPwBGcE+YUkhWWFfEUpBO2ETQPLwy8CPUE9wDg/ND45vRD8QXuR+sg6aPn4ebg5qXnLelu61nu2vHX9TT6z/6DAy8IqwzVEIoUqxceGs0bpxykHMAbABpuFxsUIBCYC6cGcQEf/Nn2yvEa7e/oa+Ws4srg19/c397g1uK45XHp5u328nv4S/44BBcKuA/uFJAZdh2CIJcipCOdI38iUSAfHQIZFRR/DmgI/wF3+//0ze4S6frjsd9Z3BDa6djw2CnajdwM4I3k7+kL8LL2sv3UBOMLpRLlGHIeHiPCJkApgip7KigpkCbGIuMdDBhtETcKoQLn+kPz8ust5SzfHtos1nnTHNIi0o7TWNZt2q/f+eUa7d30B/1YBZANbxW3HCwjnCjaLMMvPDE4MbQvuSxcKLsiARxgFBIMVQNw+qXxOelw4YbatdQq0A3Nd8t3yxLNPNDh1N7aB+Im6v3ySvzCBR4PFRhgILsn7i3FMhg2zDfPNx82xjLdLYUn8B9VF/YNHAQS+ibwpubc3Q7We89Yys/G/sT2xLrGP8ptzxzWHN4x5xTxe/sTBo0QlRrdIxwsDjN+OD08LD45PmI8sjhDMz0s1CNJGuMP8gTN+cjuOeR12sfRdcq6xMbAuL6kvozAZsQVym/RPto/5CXvnPpMBtsR7hwuJ0ow+jf/PSpCV0RyRHlCeD6LON4wqyc4HdUR2AWh+Yvt9eE817PNpsVWv/W6qbiFuI66tr7fxNvMb9ZS4THtr/ltBggTHR9OKkM0rDxGQ9xHSEp0Sl5IEUSuPWQ1cSshIMoTzAaM+W7s29801NbJEsEuumO117KhssS0NLnPv2XItNJv3jvrtfh2BhMUIiE8LQM4IUFNSE5N+k86UAtOekmpQso5IS//IsEVzAeO+XTr7N1g0TLGvLxItROwRq37rDWv5bPruhDEEM+X20XpsPdoBv0U/CL3L4k7VkURTXtSaFW/VXxTrU52Rw0+uDLQJbUX1win+ZvqKNzAzsvCqLiosAqr/KeYp+Opz642tuG/hsvO2FHnofZFBsUVqSR8MtI+SUmOUV9Xjlr/WqxYplMSTChCMzaQKKYZ6gnV+ePpkdpWzKK/2LRQrEum/KJ9otak9am1sdu7G8gX1mPlifUMBmwWKibLNNtB9UzAVfdbZ1/0X5ddYFh3UBZGjTk8K5EbBQsY+k3pJ9kjyrm8ULFEqNuhSp6vnRCgXKVsrQS408R2033jbPS/BfIWfifhNqNEWVClWT5g8GOaZDdi11yiVNVJxDzSLXMdJQxu+tfo6tcqyBK6Ea6HpL2d7JkxmZabCKFgqV+0sMHt0KDhSvNgBVcXpCi+OChHclM5XTJkJGjuaIlmBmGOWGBN0z9OMEkfSA3W+oLo29Zpxq+3HqsbofSZ45UIlWyX/pyVpe+wtb5/ztHfJvLvBJwXnClhOmlJPlZ7YM9nAGzsbIpq6mQ3XLRQt0KtMhIhbQ5P+03o+dXjxJG1eagEnoSWM5I3kZaTQpkOormt6LsvzBDeAfFuBMMXZyrKO2RLvFhnYxNrgm+QcDRuf2ibX8xTbUXtNMoikQ/Y+zboRdWXw7izJKZDm26T4I7AjRiQ1pXPnr+qSrkAymHc3u/fA8oXBSv4PBlN6Vr8ZfptpXLXc4ZxwWu1YqZW8kcJN28kshBu/D3ovdSGwieyHqTbmLWQ7YupivSMvpLbmwWo37b2x8bav+5CA7UXdivsPYdOxlw4aIRwaXW/dnt0rm6CZT9ZQ0oBOf8lzxEQ/WDoYtSwwd2wa6LMlluOWonyhy2K/Y81mY6lqbQSxkLZpe2bAoQXuyulPq5PUF4aaq5yyndFeRJ3QnEAaJNbXEzQOnYn5RK9/Z/oMtQUwdqvCqEYlWGMK4eehceHl43gll2jrLJYxNfXk+zqATcX1iskP41QiF+ga3d0x3lme0h5enMraqBdPE51PNQo8hNy/vjoLdSywB6v+5+/k8qKYYWvg8OFjIvflHSh6rDJwofWi+sxAdIWxitqPyVRbWDKbN11XnsifRp7VnUBbGRf4E/tPRYq9RQu/2rpUdSJwKquQJ/DkpWJ/YMngiOE4Yk1k9efZq9pwVXVj+pyAFUWjSt3P3ZR/2CYbeB2jnx2fod80XaAbdtgRVE1Pzgr6hXw//LpntSYwHyu154kksSIAYMIgemClYjikYaeIa45wELUoemw/8EVLStMP4FRPmEKboB3V31hf4597HembgRiaVJMQDos0BazAJDqEdXewJSuwZ7gkVaIbIJRgBaCrIfpkIWdHq08v1LTw+jq/hoVpyrqPkZRK2Efbrx3t33jfy1+pHhyb95iSlMvQRotpRd5AUHrqtVawfGu/J75kUyIQIIEgKqBJYdLkNScX6xzvoTS9+ck/l8U/SlUPsdQyGDYbZR3r336f2R++Hjhb2Zj51PdQdQtaBg+AgXsZtYLwpGviJ9tkqWIfIIhgKiBA4cJkHWc5Kvgvd3RP+dg/ZQTLymKPQZQFGA3bQl3P32ofzJ+6Hj0b5xjP1RUQmguFRkBA9jsRNfuwnOwZKA7k2GJIIOogA6CRYclkGmcsKuFvV3RnOaf/LkSQSiOPARPEl88bB12aHztfph9dHiqb35jT1STQtQurBm/A7ntQtgCxJaxjaFjlH6KKoSZgd2C7IefkLGcxKtjvQXREebk+9IRNCdjO8JNwl3patB0KnvIfZV8m3cCbwxjF1SYQhcvKxp3BKbuXdlExfayAqPhlfuLm4XxghOE94h2kU2dIKx8vdjQn+Uw++AQCiYKOkJMKFw/aSNzh3k7fCp7Xnb7bUVillNiQi4vkBonBZ3vldq0xpO0wKS1l9aNb4eyhLGFZoqrkj6exazPvdfQSOWE+uUPxiSFOIhKRVpBZxlxgXdIell5vXSYbCphzVLxQRkv2RrOBZzw5ttNyGq2x6bcmQ6Qp4nYhraHOYw9lISftK1fvgLRDeXk+eMOaSPXNpVIHFjyZLRuGXXwdyN3uXLXarpfuVFDQdcuBRtoBqHxTt0Pyni4E6lUnJ+SPoxiiR6KbY4slh6h7K4rv1vR8ORP+dsN9iECNWxGrlVSYvdrUnI1dYl0VHC6aPZdXVBZQGcuFBv1Bqnyy972y7u6oasan4iVNI9NjOmMApF2mAujbbAzwOPR8eTJ+NEMbyAJMxBEAFNmX+NoL28Zco1xkG1DZt9bt04xP8gtAxt0B7TzW+AAzjC9bq4rosaYhZKYjxWQ9ZMam0ulN7J5wZnSEuVT+McL1x7vMIRBFFAxXH1lsmugbjJubmpyY3ZZyUzNPfos0RriB7/0++Eq0NS/eLGEpVScLpY/k56TRZcXnt2nSbT7wn/TVOXu970KLx22Lso+7ky2WMdh3mfMantq8WZLYLxWk0otPPwrfxo+CMf1qeNx0qPCu7QhqTCgK5o/l4KX75ppob6qo7a6xJXUt+Wc97YJextiLOY7kEn4VMZdt2OgZmtmHGPOXLRTFkhQOs8qChqGCMz2YuXS1JvFM7j/rFakep6Vm76b754Qpe6tQrm0xtrVPeZd97QIvRn0Kdo4/kX7UHxZQl8hYgVi8V7/WF5QVEU5OHIpcxm6CMr3JedL17nI3bsascOoFqM9oE6gRKMHqWmxJrzpyE/X5eY097kH+BdwJ6w1PULDTO5UgVpRXUxdc1rgVL5MT0LmNeUnuRjZCMH47ujZ2fjLtb9utXGt+6czpS6l6adNrS61TL9Yy/PYsecg98YGLBbaJF0yTz5USCBQeVU2WEVYp1V0UNVICD9bMyom3BfhCK/5uup43FXPt8P2uV2yJK1zqluq26zesTm5s8IAzsXaoOgk994FXhQzIvIuOjqzQxdLLlDTUvNSkFC/S6dEgjuYMEAk2xbRCJL6iewl383S38evvoK3jrL4r9CvFrK2tom9WMbe0Mbcs+lA9wIFkBKAH24rADbkPthFpkouTVxNM0vFRjdAvzefLSkithWpCGj7V+7e4VzWKcyTw9u8M7i9tYi1lbfRuxnCOcrx0/Pe6ep09zMEwxDCHNUnpjHrOWZA5kRKR4RHk0WJQYg7wTNyKuYfbxRoCC/8IvCf5P7ZkdCfyGTCDr69u3+7Vb0twebGU84310zhQuzC93ID+g7+GSokMS3ONMc68T4uQW9BtT8PPJ02iy8TJ3gdBRMNCOj86fFm57HdE9XOzRfIG8T0wbDBUMPExu3Lo9Kv2s/jve0p+MICNw02F3IgpCiQLwA1zjjeOiM7njlcNnsxIiuEI+AaeRGZB4/9qPMv6m/hqtka0/DNU8pbyBbIgsmRzCrRJtdU3nvmWu+r+CMCfAtsFK4cBCQ3KhcvgjJgNKY0UzN1MCUshybIHyAYyw8LByX+XfX47DblUd5/2OnTsdDuzqrO5M+R0pjW2Nsm4k7pGPFG+ZcBzAmlEeUYVh/HJBApEyy6Lfwt2SxeKp8mviHiGzoV/Q1iBqj+CPe+7wHpBuP43f3ZMden1WjVdNa+2DTctuAg5kbs9vL8+R4BKAjiDhgVnBpFH/EihSXxJisnNiYcJO8gzBzUFzESDwygBRf/pfh98s7sw+eA4ybgy91/3ErcKd0U3/jhvOVB6mHv8/TL+rkAkQYmDEwR3RW3Gb8c3x4KIDogbx+0HRkbtBeiEwUPAwrEBHL/NPo09ZnwhOwT6V/me+Ry40rjAOSM5eDn5eqE7pzyDve0+2kACwV0CYQNHBEhFIAWJxgMGS0ZihgsFyAVehJPD7sL2wfOA7f/svvg9130RPGr7qPsO+t56mLq8uoi7OftL/Dm8vb1RPm2/C8AlgPPBsQJXQyJDjgQYRH9EQsSjRGJEAsPIg3eClMIlwXAAub/Hv1++hn4APZD9O3yBPKP8Yzx+fHR8gj0lPVl92v5lfvQ/QoAMwI5BA4GpAfyCO4JlQrjCtoKfQrRCd8IsQdTBtEEOgOaAQAAd/4L/cj7tPrX+Tb50vis+ML4EPmS+T/6D/v7+/n8/v0C//3/5AC1AWcC9wJiA6cDxwPEA6ADYAMJA6ACKwKyATgBxQBcAAIAu/+H/2f/W/9i/3n/nv/M//7/MABeAIQAnQClAJsAfQBKAAQArP9E/9L+Wf7f/Wn9//ym/GT8Pvw4/FX8l/z//Iz9O/4J//D/6ADsAfIC8APeBLEFYgbnBjkHVAc0B9UGOAZhBVEEEQOpASIAif7p/FD7zPlr+Dj3QfaP9Sv1GvVh9QD29vY9+M75nvug/cf/AAI8BGgGcghICtoLGQ35DW8Odg4KDisN3QsoChcIuAUcA1YAff2l+ub3VvUL8xnxku+E7vrt/O2M7qrvT/Fx8wH27/gk/Ij/AAN0BsYJ2wybD+0RvRP7FJkVjxXcFIEThhH4DukLbgiiBKAAifx6+Jb0+vDF7RPr+eiM59nm6ea/51bppeue7iryMfaU+jP/6AORCAgNKRHTFOYXShrnG7AcmhyjG9EZLhfME8QPMgs6BgABrvtr9mLxvOyd6Cjle+Kt4M7f6N/+4AvjAObJ6UzuZ/P0+Mn+twSSCiwQVxXrGcAduCC4Iq4jkCNbIhYg0BygGKQTAQ7iB3QB6/p49E7unuiX42DfHtzs2d7Y/9hR2s3cYuD35GvqlPBF90r+bQV3DDATYxnfHnYjAydoKY4qayr9KEsmaCJvHYYX2BCYCf0BQvqj8lvrpeS23r7Z5tVP0w/SM9K906PW0tos4Inmuu2I9bj9CQY8DhEWSR2rIwMpJi3wL0oxJjGDL2ks8Cc2ImYbtRNaC5gCs/nt8Izo0+D/2UfU2c/bzGfListGzZHQVNVs26vi3OrA8xP9jAbjD84YBiFMKGMuGzNNNt03uzfnNWwyYy3vJkEfkxYoDUYDPPlW7+LlK9111f/O/MmXxuzECsX0xp7K7c+71tXe/efu8Vz89QZoEWQbmCS9LJIz3zh4PD8+JT4lPE84vDKWKxMjchn+DgYE4Pjh7WDjsNkc0evJVMSHwKO+ub7MwM7Eosoe0gnbIOUV8JX7RQfNEtId/Cf9MIs4az5sQm5EXUQ3Qgs+9zcoMNgmTRzaENUEnPiN7AfhZNb4zA7F5b6vupG4nLjSuia/eMWZzUzXR+I37r76fAcQFBYgMCsGNUs9vEMlSGJKXkoXSJ1DDz2fNIwqIh+6ErIFcfhb69jeSdMKyWzAs7kWtbuyt7INtay5dMAxyaLTd99V7Nr5mwcxFS8iMS7XOM5BzkieTRdQJFDBTf5I/0H3OCsu7iGcFJ0GXvhM6tXcYtBXxQm8w7S/ryetEa2Br2W0mrvpxA3Qsdxz6un4ogcvFhwk/TBtPBBGnE3SUolVqVUuUypOwkYtPbMxrSR+FpQHY/hf6f7asc3gwee3GLCvqtmnr6czqlWv77bHwJPM+dmS6O33kgcLF9wlkzPEPw9KI1K9V7Ja6FpbWB1TVEs7QR81XSddGJUIfviU6FXZNsunvgu0tqvppdWilKIopYGqd7LNvDbJUte15uj2bAfEF28n8jXcQshNX1ZcXI9f3l9DXdFXsU8fRWw4+ik3Gp0Jr/js59nX9Miwu3ewoKdzoSCexZ1koO2lNq4BufrFwNTf5Nz1MQdbGNMoGDiyRThRTVqqYBxkhWThYUNc01PTSJY7gSwJHK0K9Phm54zW68b8uC2t2qNOnb6ZRpnsm5+hMqpltePCRNIS48r04gbRGAkqAzpFSFxU612kZFRo2mgyZm5guVdVTJk+8C7RHcELTPkB527VHcWMti+qZqB/mbGVG5XEl5mdbab/sfS/489Q4bTzgQYlGRArtDuSSjNXNWFIaDRs2Wwxak5kXFugT3NBQzGMH9cMt/m95n7UicNitH+nRp0Ilv6RSJHvk9+Z7KLQrjC9n82c353yDgZZGegrKj2ZTLtZKWSSa7pvf3Dbbd9nul6xUiBEeDM4Ie8NMvqZ5r3TMcJ/siClfprskqeO0Y1xkHaWsp/dq5u6esv43YbxiwVtGZIsZD5YTvFbxmZ/buFyyHMscR9r0GGFVZ1GizXTIgUPvPqU5irTFcHjsBKjDpgtkK+Lt4pOjWCTwpwpqTe4eMln3HHw+gRjGQ8tYj/QT9ddCWkPcal1snYidApummQZWOdIezdZJBgQVPut5sTSNcCPr1ah+JXOjRiJ/oeHiqGQH5q3pgi2nMfs2mHvXAQ8GV4tJUD/UGlf8Wo+cw54Onm5dp1wFGdpWvtKQznJJSUR9/vj5ovSkL+Eru2fPZTPi+aGqIUgiDuOzZeJpBC06MWI2VfuswP4GIEtrEDmUadgfWwLdQ56XnvveNVyPmlyXNdM4johJysSpfw0537SJr/Crdme35IzihiFt4MahjGMzZWkolKyXsQ92FXtAQOaGHgt+UCFUpJhrW12dql7HH3DerF0E2s0XndOVjxdKCgTW/2f55zS975HrRie3pH6iLGDLIJ5hIWKI5QIodCwAcMP117sRwIiGEUtC0HbUipigG59d9x8cn4yfC12kmyqX9pPmz19KRkUGP4i6OTSAb8UraqdOpEliLGCCoE9gzmJ0JK4n42v1MH/1XPriAGTF+os5UDqUm1i9W4heKh9YH87fUl3uG3TYP1QsT58Kv0U2v696FPTQ78prZCd85CzhxqCUYBogk6I1pG2noqu18AQ1ZfqxQDuFmYsh0CzUl5iDm9geAt+5H/cfQN4hW6tYd9RlD9bK9EVnv9s6erTvb+DrcidCZGnh+uBAYD6gcWHNpEDnsmtDsBD1MvpAAA=\" type=\"audio/wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\n## Video\n\nMore exotic objects can also be displayed, as long as their representation supports the IPython display protocol.  For example, videos hosted externally on YouTube are easy to load (and writing a similar wrapper for other hosted content is trivial):\n\n\n```\nfrom IPython.display import YouTubeVideo\n# a talk about IPython at Sage Days at U. Washington, Seattle.\n# Video credit: William Stein.\nYouTubeVideo('1j_HxD4iLn8')\n```\n\n\n\n\n\n\n\n\n\n\nUsing the nascent video capabilities of modern browsers, you may also be able to display local\nvideos.  At the moment this doesn't work very well in all browsers, so it may or may not work for you;\nwe will continue testing this and looking for ways to make it more robust.  \n\nThe following cell loads a local file called  `animation.m4v`, encodes the raw video as base64 for http\ntransport, and uses the HTML5 video tag to load it. On Chrome 15 it works correctly, displaying a control\nbar at the bottom with a play/pause button and a location slider.\n\n\n```\nfrom IPython.display import HTML\nfrom base64 import b64encode\nvideo = open(\"animation.m4v\", \"rb\").read()\nvideo_encoded = b64encode(video)\nvideo_tag = '<video controls alt=\"test\" src=\"data:video/x-m4v;base64,{0}\">'.format(video_encoded)\nHTML(data=video_tag)\n```\n\n\n\n\n<video controls alt=\"test\" src=\"data:video/x-m4v;base64,AAAAHGZ0eXBNNFYgAAACAGlzb21pc28yYXZjMQAAAAhmcmVlAAAqiW1kYXQAAAKMBgX//4jcRem9\n5tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTE4IC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENv\ncHlsZWZ0IDIwMDMtMjAxMSAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9w\ndGlvbnM6IGNhYmFjPTEgcmVmPTMgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MzoweDExMyBtZT1o\nZXggc3VibWU9NyBwc3k9MSBwc3lfcmQ9MS4wMDowLjAwIG1peGVkX3JlZj0xIG1lX3JhbmdlPTE2\nIGNocm9tYV9tZT0xIHRyZWxsaXM9MSA4eDhkY3Q9MSBjcW09MCBkZWFkem9uZT0yMSwxMSBmYXN0\nX3Bza2lwPTEgY2hyb21hX3FwX29mZnNldD0tMiB0aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBu\ncj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9p\nbnRyYT0wIGJmcmFtZXM9MyBiX3B5cmFtaWQ9MiBiX2FkYXB0PTEgYl9iaWFzPTAgZGlyZWN0PTEg\nd2VpZ2h0Yj0xIG9wZW5fZ29wPTAgd2VpZ2h0cD0yIGtleWludD0yNTAga2V5aW50X21pbj0yNSBz\nY2VuZWN1dD00MCBpbnRyYV9yZWZyZXNoPTAgcmNfbG9va2FoZWFkPTQwIHJjPWNyZiBtYnRyZWU9\nMSBjcmY9MjMuMCBxY29tcD0wLjYwIHFwbWluPTAgcXBtYXg9NjkgcXBzdGVwPTQgaXBfcmF0aW89\nMS40MCBhcT0xOjEuMDAAgAAACqVliIQAV/0TAAI/3gU2tIW7KawwaCmQGTGHKmuYAAADACBcshU+\nyICkgAA14AHowiEeT6ei7v7h3Hu0i2fpUBLGBIkbCMP3Vfz+9BVGCDXnw9Uv5o3iN030tb7eq6rs\nEEhHs2azbdTiE9Csz5Zm6SiUWRdmB43hbD5i6syATuODUJd7LM3d9cbFpc7zFlu5y3vUmNGd6urp\nvKKT9iyleIyTuR1sVS431DhevGfkUllVeIznYUe2USoMW1tufETjyRdmGldN6eNlhAOsGAH4z+Hk\nrwKecPPU7Q5T4gDAIxj9hW84jVExMTSTHxkPTq1I4OotgUxURCGTsw60k/ezPNmNg38j1bqaGmPc\nruDKEIBDsK5qEytFB90Q68s0h2wmlf2KXd5bleBefiK+/p47ZsyUO4IdlW25rRy+HLjt6wQXfYee\n3IkiQOoOK+U7u/lxcl78zfxwIoEMjUUSKNZjkp8clnmecDDJ3Kz+viF7bPklk7N6QRyizAKPIIpn\nNJUuMWQmqeL2Or6cr4D0/0tOym+4tficxmhuEONKUtO2pPn3hRjMllkd12tXp70fLTfxy0dwB70M\nL9iLEcItHb7zVupHlP5RxdvecpREw+OsIPr9KWilIesNE19jgIbT+TkiRBjOoKvUuwcQnKg7fOTH\nVoLvnKuAfea+oujEdm1Rwd2tEOnkF+ZC11WaNQsiNR/eJ9EnUXjXDYGfhB+Oe7qj8nYTT+eOXg1c\nuJNgLXEs4vOheWEjQOqfIWMQc3DmTof5s0ksBmUQ3PQ+UHPxZSnmOEZB+j6xT3wbm7HGzDjWtSg1\nSjTxd1EiJ8xA4SIxxR8WIKLg+TwFxJNS7Laxq7Uglu3AkXe82P1JCdJX5PsbFbxuDbuJgakzRcTw\nMLLSKCiizS/eCW0uJed/lev9yb80kKlVET4S219cn/zhkpeDV83cHYOr+sJQKDRk/Wh2c7fsuxfx\naEH/6reSmvFDsAnXAyPXliJ3G4VG3OkEM5K5WyGGrBizZbTrdGsBnzj5VSGGOJdCKuRrUluw/8es\n2vYRPs9BcTqAqvHk9M52SSIf+1T6L53EZP8VbtXB+G29CMW4xVCK/B/YDjaNmqMwJ61dapugjnWJ\nfqeXlGGa3Ch3aA7gi30T8PucNRBjLK3lF67ZDDvkWXRQXd+VMnKWHkBbCkQ/F/fMuNpHO3C00Y2p\nljna1qImBhVMvPe0F7Qx7G/YyxLRzhyUU8e23HGzp0agtNJRbydbrPV+TqJMSifJMNcZIf8wkdnC\n3/xdpcXnLf2Ye3Kbd0o7utciTG+q5h6WTEk+PaNbXLLA0YyZ2VnLTcyV1QTS76aNCbV9Q1/OQ7QU\n81Gg0hPa9aSiscGary6jLVwDQaik4zLsi7jPqgPVdup7pwx7uJDqRCVcVi5QoZFp/GHdex5sJTF6\n9A6sja69/NLkFIWNSIeRcuGahXpF+wZeYIrqJv975s1TKYKAvp1WtzgtgWNkcbzCtROqf8rPtlAI\nxkX8GLcEo9zfExyfimeXQ64qfFxEy0IMy2Hsxau9fSMqUnIjntuVVjCQtBL+94gx1RZLndE6wROV\nTq/wHwHrQzo9QL9cpPqPFJjiZ/NGZIFuudS+wsBFe6Hu8Oitf5zToLqLdtU4Smwh4ne3JsiT9lOz\nN+4PPw3VSx9l5FppVwdKUWELw1dYpCOppyVWlJ3YQ8H4FQQM8EcYMG9N3Bxu79y1J1ikuvuhMmLQ\nlehLTbguhbix74hd1VIQC8EjHmOZSSWbssulYwPbr6FF49tifk6PymJvulR9/u+2585HkRfbxveG\neWCz0ix1pIVfaNpESKmtLy/0mcbMg9hYDz2werz9oe0lT2BiMV6uAin6RaQcT8Vk9MPctfwae+gk\nvtnZA/sOBk8MbpylaHqc0KIVHhhLFMNnkOFiucjtGo/JWTa/F6g8wWeow5ZuIJUORaYHWqegZbTg\nM9dCsYYsfZGjjVMuSlDIvpYvIvFFooGPC7Ye2Jfawmq4Ut7EL/nv/dyAd2HRc5msmUhzeu/XpX3r\nVlzRmf9/Qan8Dbve3QfW1Ym0o5J/KAc3z1VBho7JBr5PgCL68RiD9jZHN0VvsT4gzsEjNlW3D91U\ny4RduaodBFoNTzXwlfUYULBzdiTbH75l/UmVMC4TKeTWhNzw2UezaqeGd8at3WSY7W/VR3+hvZHD\npkIjgKuNNH0DsCRa/Kk56XQoHIyvvUH/eNekNvziReqS4qgLnXUT4BRGt2BOtCifI6+X/DGHUOmW\nlX7TN5b4pw5U7jwfwshtbhGZM49T8JMk15Mzrc7tM6J11TYxb5R3mQhZ8TZumJ0bMJXPM69HFyih\nr5dJSEJMycxJVUh6NTQALUOoRTHIOwE+FpWI6feTv1SiZ0YpYe5DbkYJJbN7zAHbAKw25XvqR2mA\njQmOlsfX/tK8DPjP/8h5/xgAF4EUbj1tOnQCBQL8jk9vHtfsXncsprww4Z+P/Z/UrKifuFyEpBWN\n8kLpF7yywE2iYdDruV9+/qKR8rC9ozNKyqQNIwtxrzYkWpE5t8K7gG4JFnrHona/Rp8dOX6VW41+\njb5LB1LEtE8MwjLp3RCUOq/+6yLzaOEgBTqzvEjDeFpg/u9DMHMr4/2TOchfjg7dl+uQ6Gsx+4Ia\n9W7vivG95027p25eKL0nHvx/OqmAQEZYJL/JO58lOj0zPdJxrQ5dZksjMISzVZNn7DsxqE3zgBBu\nNzk50R8lTK3U8P12QiOAQYSTeGlYlkvfeofrfO1AitEj02m9aUkxTFd1ZZJoLQT2d3zEU5PmE4lx\nMVfL5ttNnIbqfcIU2RJKNWqdw77xfjfrNc/eNpRKPZ/6z50LzBprgjzBHRfKgSWWkDxHrX0aTbgw\nQFwd51+PoUWH4DkQg26uGslF5Hn3hB58+fkeLTosTANOIBNAeFZtTc4PIaLHw759zae7scY55xcT\nabzlilYIftst2RZ6ntsRC3zFxduCKvL6wLfYT+TiIWJn5P7sTwZwXuSzXY+9Q3xMZ5o4Xcpz6vD9\nFtTjzS69iefEYt4pXiDrZUo4ePGiLeoIFIwYB/v6GXdmG5VLLk+eKbOc9AmsX2zmvqtcvDRGQbzu\ngXbH/kTH/lkNPBTmqN3ZJODUEXVohPEJ6th0xna0EVleB73Q3eNvaVUvhlJbjs3D/T17FRCebN7A\nOXvzzbLE/I5kNfEmJcv4dxtIeo2uQ/z9ohSpiZzbDj1u40nJRyJxUK60wEv0nA9f/NuJ6/PEyU0b\nkK16z2KH12k3Lc4+1f5fawIzkK2qJRB4wnj8VHhUW9mbJhs9vgfFmU3xrXSShY67Ygb+gYNPxxtn\n4K/9eTSwIA9fv/nR33lA2lZoXALRUTmOZIl3R0gAM5h6oX1y1thIyqViBK95VZc8Pvy7G3O90M9S\n4zkpyFQ36jrMazvMveMA4d39fvoaC7p90quiJfjI4yrl+ECVkCJL5MxRSa+iVcIL7Xbl0jVaGhZI\ncMYmcGOBbLzhJgloM1x1zFnnj3ggJRFAM8yNnXxhavk+mA18JC+y3lqGsp6vPReRxGlGHMou17L4\nIt070LzkoeCzarpv8Apw59smdS5KN9qVN1WgeL7OSN8BHg94ubCvS7DW6H3/PbtRB62jFLsBhUV5\nYqCIbIN5VZ81AAACpUGaIWxFfwAru8x8uT3FuOjrAeSWXmAWqq9jCNGE+N5AOv//9//xjk4uBAcA\nDN96c97AVGmzRtnWwPsgcCbLrVdQJgbKp4QSmPwQnVhv0hXyBjeFWWlcvx70urEN3FK6/lvk2tQe\nZgbtlbzXluvTfnSj/Ctz7vZ+O1FjhDzzdpL7uLzewzCIW5VWLAEKUVuS2J6wNk6MR7UblcEd4EtO\nY+R4/qJgfojCsfRvA0oC5dc41Vd0erZbSkrmPTjLCn815bxlchUJMS8gQD5hJNwoKHvNLNwn7XKu\nTtYIhH2wVNZvDWgzCjlPeQajnrcMsb6bZYJvNJU8HuGHvm50r7VG8qifEwmuyegAZXojh5Ul5Vvj\nDW7kSAZyw8a7I6mHY3FZHd+OA3V4JZMbNliI3Tj1L6+MKTmilVialmyZagRtEMeKRdtxUPd3vVEt\nrOBVIVYWdgAGA7HmZiHQUQNxLkWxbLyWVlrh5EM0Do2NdbclHxxArz90d+MSVeUOIXQ/4V9quq8C\n8qVflo1gPtPMkjO2/UrdOYqhY404ReObOu/fdp4hAEDq6jhy64vOeT7XUK/Onq0rXTldtA6kvgQa\nJg+mgYSR9hfXtMbOUSLgLj/RmBSO8aAMHuJJZqf1tCM5pZ9eYUsrHmy+/z2NGalon0//uF6+33bQ\nzT/RLRfBbYTjy9QrJqHLlw46lggWPGkHuPKSqk/CB7U4pNPXUbR0DdcJy9Db00wCzVzxVc6h7jfC\nFgiL2Y0HVqd6bgIaVUqn/gJCEyCDVplnzebv0gg3XwMJAGu639lHu7rEvxTp1smIYjWp9R5L4Ssp\nVvS07Nb+Smk1FgsMp1K3EMUT8X2Fty4VG54/Ec6bE8tNVw4/QV1VzBw7Px2/2eEhhUS+FMfbHAlD\n28x00jRgAAACW0GaQjwhkymEVwArOUkEOhoFqiELtH8wgecFLiUq6WqmwAP7iGEwbYzfnHacfqUN\nXAfD+CGR2ap0lAHL25ipuYtd5j2O0PU/MpaWPG/n2y5OkfTzaOpotaR5tWjN55B2XblVVqsFfBC/\nmvsiPvCBWUHFChacdY5whj5mP5rqQ0dqLJCsWjrs4TWnIbL2V/Iwfj3hwI35jfo1JkTOeR+8GhOd\nma9rgiKWafCbQyhYMTDmVdvhND60Flm97EDSTjF0OC+0gD9b8Yn4tNeHipCa/aWyt0n79bMmjfcj\nntBCPjrcB5ecRTpfGHbEHy1IRj2cjkGXKC+VYoYJXBp4rd4cMd8ygLCk5nBSd8/cTaKNRjdBscOe\nTXG6QEjSxj9/2pVwx9DMRVtWQR0BSaAcQcZ8W2KPSaeRC4QwmNMu2xx25CSyrDiq2rFSK/JJtmvo\nIjAKq0ciEXoOgw+Ke+Ylb7ULKCS3k1p/613UNRp450uSq5b7CAHo7S0b7fBMLfNmwSjRYEhLlo0H\nUaRe/I+IX2Z6XdZH9Hty/399ZA1PwZGC6EfvUJIf7CBeaxv7cu6IT2/s0zPRGthpvXpYw6A7P4Ww\nz5C4V98KnIUNUanadqabKP6eXWhvbvcQHxAjiOOiKZgXZplZW2g+B2NNyJSLiR+g48DqvWR6t9S2\naGfFjdOW1Gi6oTtZ1d4p5XIslAr8mryeZ6+htSSQe4AcfVt7k+V6mOthBCYtr/LEU4ZHtl0mW987\n6PK8mRFAaT8DJOUFVz1lPfzRApuPggkkyq+UMvyfKTUbCk7/DpfX8Y4s4QAAAg9BmmNJ4Q8mUwIr\n/wAsWUPjZw3ksgRsxZ6n4fQjprPbkj2aUh30y0bZJnLmiXnWskvOGnCPwBnG9dEhatwX3hoxk7BN\nyG+wQ4emZUpcVzcWl2T9nKQB1euucuZWHTg7TCtM/iHyfPO2vbmGsfzs70b/egIbywUH4y4BQSL1\nnWc1SmpHm2zHMBcUjYLDZ5gL5vdfxn0V8FFw66G88c/LN4I5icUa7xf4fcSBKywU0ajbp1P+aJYj\nBgWT6Ggu0MDLDNl54tfqd42lKosQtM1aif4WXAZFP5Ww3vrQ1rH9+utSYxqZd6N6gGtNbSNMcVia\nKn5LcnjsbBi3T3EmGqshEbcme8VHKwR3kSfBOAprrIsv6K8R+X6az+MD23rWka/2v64m1qM69D7X\na+Kcs/n0KLCJdTilyaGadopLeaAn3eYvWTeHcucMM1Fp1KgHD1tiFeO6HvobLkZlRximsA3/7Mio\nhYklLIcJrZL22BH+6W9d6kZsYIsej9RM681nU6mWNjepBAfAfTbrGRrVB/h2DxC5B8YyRjgSIzQj\nNYrse0rzChqbrsLl7mQ7W+1bsNKze5//9ZIa8rSsF+BXh/vgoRTDkPW/ws95B7VPCZEFChfX0icw\n+tpcpN/q7NY87tUn4vESdSiMMlyhKklMjQu/G51J69ZRQLs2oUO6YfoJFqliy4qCFCrf8SZE9Fc6\nDcCagAAAAodBmoRJ4Q8mUwIr/wArPWF/KOw78THwadfPqhJO0CnmR/M74/XYZLqVYKlNcEaYauf+\nvrRUDJPmu75sMKy2Y+Bnslc/iAISSyWtw/h/3CF8fE5ZrbrwSNst+MSyCoNWP+8imtoX2eyojpdC\nk8YP5K+cbK4SJPCkZXbYqSXYk7hO8AdSemBHgXKWiZ+UOr802aJo+98ZOIjX9hWL9bo31Gqx7cy4\nZG+W/ar/WGlzDa1xPWnPRsEdrIcZlEVGV/jGmbirkxw1lyUYoqj8Vv7Bxube9XPQlBkXOV6Lc1LT\n2IzNq0V7WwVhF0kA6yxfAsFxc9krNEH8vGGntTWI608ovjatXc/CKKXw7AjJSftlTcLI0hIIGXbR\nUr0NCYNp7M4cVd/n73Rjetnixz4SAKpcz/P47UsijZG7T3SxzK2D79WS42aEalc12hQwCZ01LfmF\n/H2mmGEvOzPBie1D0YT7Jh19vxa4Dd3SQ1FrDfmSUpvv4DjbYcZ2PrPpFpWtMjWqHBeoyMiZf6RP\n3EfYR6z9jsVNIIHxM0bzzBQF8eeYkPgDySydxPXv9Izo+QUY94N8kWi16fI6eZSDc1G0Yo0L91jc\nRQuDMGGS7B2zuf/0GbJyRhUO48UbMrqnILMrbQg1LF00Q3pH9nbGEK/RRQpRN3T/J/4IZQjwW2Ft\n2ipWGztg1Jn9I4DmffKS60QC+JQcyakdVON6zDcKttIKlqeTcmAi4xzmo4QXa2dRKleS+fs3EtTd\nBBtony2wK9T2Imj+NCziOSEL7Q7VuIU8kclUHrJJsSneFcxGRgIgGGUEQM8/pklwTOqab7mMmJeR\niaBrjJDEnDpkR4Vz3qXxgyn4/5x24FuTMNVPwQAAAhtBmqVJ4Q8mUwIr/wApcLwPT0/Xh9UdWqWX\nIs8Wbj5K1hivmN6qIQnq+aolcegdlM/63MbHsdC6xYZC1e/Q8UjQCt9N/Ejqwms8DzeWv2qxskel\niZH0kt1QWkErWSEodq7V0ZNksctLkMGWayX33gBT368EehfIeGDolBZoqIbJfb4nqcfU+ev4OzVv\n9zVqWyLck315GFmXxQKIM8pICQc8Q5es34LH1+DmnMnW8kQpVGrztQcDXhjCU3F0fOgoSsXSVWCj\nc6XKqGbCwQDfJUxCfXfIT6YmQoPpVp1mpGy1wQypXus9z0bScDpyDu23hViYDntdj1O45ea0znKZ\nkj1+tLHbBtqAGJ1WTcbGlF6Vya6hQhEsiiZUIC2fRxIj8/wEXCICIbr0gZ/m6gcOhE10tenvE7iy\n+BKY81wLWrnzos3S6FWxYtmCRes+LLhNGOKWRuQo6SyePH2OZ90xZm8oA1MuTe3V59euVNxjAt0F\nLkAc9TEiFhP/8CB+gA8mF+A8h1U01f4DVX55GzCH51jHI2xUS0L9GtsHoBxLPLK/NNel8zcnwG4X\n+UusfcfEb5hh+ffnXteCE9vRGbs2n9wYW0xA3ZicklfadmWKUtMiHYBfkMSULWnkBQr4CXxjpYOs\n6ygeEoA5+5B0B1SZObgZ42wWqddyyYE0NfwQAl75tfdJGqOa7OMHwBYNeatJaJK0zT2+bFaw2qWC\nWwAAAitBmsZJ4Q8mUwIr/wAstkdsayRXchoFk703izqzduZ5WsyXriI9cfUdMUWvm0iGHwYIrUuj\nvz3Yjou+JLwv9df2kt7MJo8u+3P5CjEKbwlz4vkE5AHTAbgXn3+Xc/MMJLgW5cm7iX3KiGNnBpbp\nhhwJRlb3u91NRDr0d1IR2up/z7lKxE7XPAPFe0siPMYVlIqWNSn5KqLABPeuxxbOsvMEb27/nH1L\nUVM8I2F95c1I3Lv1SpkhZXjs1JsmS9X7gsoTxkXyShGC2+zRJSGUbhCPo/q1XSFMHQyMWJ79FKPQ\nSL/RpVsacN2bYwdKo4TFBw1SsKq/L1iOmqMI+4Gxnbbjojdk0ek0JIcDb4bHv1czxchF7FX1Ym8H\n6IpPuE8CeNKjzQ1a1wqhEu+wl1N0x3Y37ZryCCKJRkxj0FT7bOoH3L38/yMUuh/v3aCmxY4eCkyk\nb2p6ZrYMFE044anM/nMjmbErMibfRFuCz58Io1rBlF7JfkIz0R2/5vjUMVskcdbX2mm7DntncOsW\nDIdg/XVmgsC9CzVzUyq4VsS/sk97lJggcddpWLNw/29egz8iLyzWHOAXCvl2fTIPkviYAOQXfVhZ\nUQdxsyJUNFMTiALrZCmoQLMp2LmDbfbW8JQriDeR3fVz6P1sjT8C2yEDvzkCn7sh0aTBK+sx7BKH\n1nb4320+caQepQj4TCJtCeNXjdrVcNEnjvwlcRJwFT1pT+Y7HREbHnT71XYNh4EAAAGEQZrnSeEP\nJlMCK/8AKIjxcI58rm/ML255fOJW1zbznFna7lfgMQrka7OTPPsvVAV4EJXye/Uxiu9dlftmRypJ\nqfDot3xwDe8lX/qAVf6pBkSlUsaLyBYtww/SUSa1bGl1JvrJCN7FXCCXbLd5R4PoYlPiDIm/DQH2\npuO0StIWmrR77Isc/J1pRvdu5+mQa/n0SEHUeM2KkoRzCznfD9zaaRO7BDtvC9SYIT0uYZxrwTjx\nQ7N7UERTrYG0P+vRLAhxkfohFIYl3HXyjPOvnlbUFP2oiiy6nkUFuaIyQcJawJv3GU8k4ObcKsC1\ncNDXjSpsyQRrxLFaCCjke4mikyt7vs0iN0bnrNWv9HXruG9zOFEOer1ggIFTsT1Eos5CXRkgja5H\nN4QUM6MhWpc5du/HgBIH8ANFcoo2kJpqcadw9r/0qk25X91MQSDJQiH8Hny2dQhqR+LFWEawiW75\n3SJhn0ngZcv/mPj3mwcHv1SL9ErBqAjm4JGiDetPKYtFwANYY11OyQAAAVdBmwhJ4Q8mUwIr/wAr\nOx5HV2505jRePGgMxptW4PGIHEszV1xGZS+flSkF+aq30AaqO7u6XK9jJsuWXTfYCRQTn1bZfFQ2\n2DbO5DXAxK/TUmbQleCflFzeS6/czxkL4PJ8AwOs2U+oehekgCZC8gZyHHaQSaKbNJ46gTjNsLy8\n4ACQ5uNt11TPuCPqPTuh+schdw9S+/lU/6m+EyaqGZ49wDFPiBFBYXglQQBjyP9k/rqq0xL7SiLj\npe4riYg8SFUuUtOzPdWHyvxnI7Ug/0VLPGAAhgMISUnqe01d5QFf36yHpwMAHexjAZFIGQHAFaut\nuMuEw6HzUZVzNdeHYxvEYOGkTo007bLwbuf/nxzrywGOxlRTYJLRdYI0mk0SdN3+LeTv1RIJwv21\n+e9rT5iFOTCgzeQoekEWXLYz0X8YLq5bVCtijP7/T7w1Ck71j0aqfrEn6wtIAAABNUGbKUnhDyZT\nAiv/ACcySi7VBgOid6qZNXvhh/JsllHkMLLq0yNbQTqv/Wk2EBoSKICZwFwAD0WRzhvvReCGirep\n1Fe4bxjm49/UR+OYrXRmHR18T0C83AUVeBk7KvDZmb/eHzuzEN4yfXucr/NWFJl+USVMY4r4UQ9C\nayrfEY9v6AQ6mzAdLy2UMfFxrRJ99g/Rfl8qx+m4jIZNjlrTaThzJ/3OpVmAliDfxVyg8+CVIlI3\n1IykiwQrXcebgajG+av8XU1SfyAG5ibvwbtdSAxkGBcJWL387V+uTdY56w3KN2vBtoQpVKD2zb3y\nazIcATZ02upwIytNcM/rpaLCdMb1myWcikE25agzLhDhOS+4zwjYz2DnW6VY0gFBAPsphhsUMnau\nVVdUVHzCTSdvzEve/H8q4AAAAVdBm0pJ4Q8mUwIr/wAo+x5XKuiN1am7SkJKSMonFZDPU3f5XFcD\nQSs0FLVq2idfsKwuIkt1mxIq8NgMHpzofTnDHqs/WedvAmhBgL0N5azdQa5MNKG2rJ4IAvGQY/uF\nm3jKQAKzvhSS01gO1oIfizF817z9IShS4QK2WT0PeFPELqLSpED8eNOpVTR96vmwpk/WBKRVJdTQ\nJzjiCQ5pgEwjtvk7KqoS0+lwXSbvIrXkYm8DignEts3DLNoLHrPjXlQmbIop76JZSyJEtB+91GrL\nwo6Km5GeebyA2E6qGL3xSkpppej/ruoFprSKrH60UMbrq/SK7eCo+1QFoySPQmqDFsMGiQFqvtld\n5BXDYdVI4yRaoyN7Y7wi83HRC6eVazuHU9OtIY3xJJApBWq1aJOsYwc38aTC3ee863Aa/4n9Lk4D\nAtyFYHNZjB5m2e2vk8G2Gny9YFlBAAABQEGba0nhDyZTAiv/ACoZSZQfHxhfQxEqOBQrP+L3Dmgv\nHSJQtB1iVkcLTxm+vagLHBLG91OGnopwrr7gT/loDypIhoRxjcwAAOeg/jN4WBbXzCJtnWGGllUC\nSdtUZQzKOSp9iM4yX18C6jrY4Sq6R9PUV/lEGNveJR4gw4FMve7110XdEPL1O2VTdHvdqeANyaq0\nnLdEmtXnrzvdrFlBaUvmaR4EdlkqGkvkZKWJej8Vq+msbKa7JdbxjwZtRufiyGfD/NVqMgSrYRzw\n9z/a8Zwbr+9+19CxlWD5bCuAEfPmjY6kZJE2L/CQI6+tnCBTXOmWZtZMBoCLGOf7G2uAC3+kFlbo\nh9as5WCkO6+iqXq29dyhKnsHInorRYsPlgxIXyU1Om/Kyhj1DJV0Am9WJK3Dln0zNUH0q6ZTOnZc\nFD36AAABYkGbjEnhDyZTAiv/ACcwdIOLRFfoGK2ZkKsvgMwG0m0qsY0vMLPSzefc+ebp/aztyF7M\nlsBz/fBeNtxFBcsKgR4pf65GvdfOMHah0ltZ918sMDmXUEZMeRHy/xpnWpTLeGz6uTs/7MATPmU5\nBgHbT/DkD8QeaZnFAzidyFCXDz2l/jaKhEdgqipbB2pH0+fQ039r05z9axxEWGmaLQjg6x9+po1o\n24yhkVO7m03YwWmPyCgy8cOwrvRyJkXJpRN4m8ZBS1zwY80HeN/VyMQQJSMwsTo7R1XMerSFuyx0\nnz+8qOuhiqykc2ohCCsXia/+kIKbJ5Vs+cbWtvkqBKIDSfU7FhAd3GjcY/xar0EVmi6wWFTugAog\nR3I7mTrQDdlTAqYgqO7Gn5NMXQVHu2i1zhFSdo9GjMbeGnbkJwsFbQ2XkoKRIDpuW7AewC9AEBt0\nOx/Ah6dGXfXO1jl8pEApj2RFmgAAAPlBm61J4Q8mUwIr/wAlR+eW/VZ7bSrmwwMA62G05DZ7p/5F\nUugsSsQdonUq6abtbU5hjFr+I1lPgoiV5c3CkTQZS+K5zivdo+Ti2P4K90xXANp8dSMAu85uJIOC\nQn2TXbEnNDifLB+3V84ht5tj4lvTaZx317BcliV8D5v2zZQW8RO1mUbuJEBItst8E7hfE+ZXj7tf\nDxNZPTvtpFyUv0fH1cTg1pr2VLy0d0zQLiA58dg+GkRvR1/hs2LyifBgHcj6eTWz0vsypVn9iPXR\nH/unJ6i8cfFL69NO24tQ9QQB+nDFhoP2cRhkAvhHwn56n5PppBD/oxni2f8AAAE9QZvOSeEPJlMC\nK/8AJjAXVGf+Kj2XNJnFeKC/gr7dJDTC2ngpd4WeAHlg04GuJKnn9hAmiECxxo9qM1IYMRiB85t6\ngALnlm9sRqGmioyzAm18RJndc9Ah8RlpGzr+44a6ntRaPx0cIwNIWAA8buL2JP00dmfjNqEiAlCa\n8OdV8FQxjp1vDXsGcAGF3Qbd62KEpkimeI3wH2nuXpbDHm8/ZKOR49s5ifUCkxCoJpfp43aC0lTz\nh2NXpcfVw6h0QnK8G60R4ZAxOxaJB7c0nn8ixXSU2JVY24EtGMF53nxJnHfzUheewUfBOGYSxeo8\noK7oUCqX4rztzDwoc2QywNqQUJUkFrqIN+sb5ecYvX24Zujn+ZzTW6UDAF3R6WdNyJyRAremgC8s\npSflTqygQNGfHyGkfIEEJJaFo/pBCBkAAAEWQZvvSeEPJlMCK/8AKI41fuekXG59Knbw4Y6YJrit\nsh9VtQgc3QKvVmxrzzo7f4aXn8N74eyP4b2lV1Z2Q+rohxps7EHTkOY9jLdqxI3MXe7je4g2qepz\n71+hY+jYdX+9LO0kA0Zg3NfyAlIRX7k6c/YHAZNtNaGZgTBMqiPgmEjiJH9Luk7shbgr+srfwiYw\nBX9rdS3fQNNFwcT8orQC+F60LAY9+GbFo2Sw3Ld4Tw9jq9yJtrY8RtHAdzytyek/mv2+j2TbTvAQ\nKbbCYtdC8E/KtR4V5ZTSScr5Wb63vmbw7UpddEXYvl55pARyyvMxWNSh3Li4GF8Jk5JBi5B5ASQw\nxCMYpX5hkAMc+d8tl2bT+IEvUTsAAAElQZoQSeEPJlMCK/8AJIAzFZs00JJ0yfm8CZiew4xWdArL\nklEvBVXo/+ukPLu3XP9HFOfsme3T6BJEKmPPgZw/Lxnraq6Sl2kLVW19YU1qmqgfv+80LkZaWU5g\nRAH4hqyo3bFYcbuY2SC3IW5Wm69gtYyAXOdbAYSEHA16fvCeRQjHEsxKVndJdrRAlrGHsKgUBQ3U\np/ZXIy1vkdFOfKSjpuZnswkuqr8NZI5tJ/dnBSErBTNWPaNwWV7nNomC0EYVGo+geGBhLXzaLw0U\nAOCYGjiPc3803BDw1GLoLIXjrIFJxwRfBNIAXYZAglu30oYzhpAfRWSprkeULMWYJTlWvbUQ5CNe\nwSZssuDWIRAc3w8AcFaywwn+YSGhtR8VI1OGjYkfBbcAAAD8QZoxSeEPJlMCK/8AJdokjCUETRw/\nnciVPtaZQSBP/VxAQSITASEzlJBl9Na1r0DJhLOz279+KQLtl/xHZ8vAKc528mTMTqtWs4sFbeVg\nHWyBpHcHEtgTzjIqEinp/MPuUXF5poo8YLSSMFn9Ozx2FbU5/Kh9A39oN9NHQflVxV1NA6yT/84H\nHyfMtfdSMS8KTvAEE2lDs14VQayNs5ctjXboQT7xMBf5OLj6thhPvgaDrFB2o/PV9ouK147lruWT\nP2mkoA9oDIMYW1pcBx4yyV/t9GOPZ3aXneMUb2fFmUCX43BjXfUDMaa4GO2/Ankj3UEQwDxA7ZlN\nUQK2AAAA4UGaUknhDyZTAiv/ACJHv33I08bkhybYiJ/JiiheW5zMPBu4n5CxGr3frhE7TkLh0vPk\ntM8m/AhaDiJisdk5QXNe/4WmxEDSAyaVi4eUVu0iHT2ly/KNTGqiORqA2oKpTjh84nYbrpXwnGv9\nSOf/34Z06xN6Yo3t35UZrP8nlcs/63GtnEmnUwVZHBYfPM6bs5M5AeBfAQ/9mIqu7vnEst+5O2wp\nPjzdItjwGCZ2ApHVjGnYYFomlA9nm6AXnxNIWHIsDgxCk3zx+6QbXipu/CWLG1Wf0WIbt4C0JPVl\n3TEb0QAAAMlBmnNJ4Q8mUwIr/wAVV64OfTKmlktYOqZHH1W1DhPy/X/6sD4T6hRdzfOgNtTOX2Ic\nkRJHshfBQVkJIzns079io6kpJFCcS3VD4zrWCn/dNaGV0kWTpFBRuusfn8F0C0R/EhsQeyTsdZft\nEkLGb5tq+nrir3vfmeb7rjmWJRXkIrTEKu8pIuAd+4FBGp8ARgGe80Jqpp//s1433HqBFqXsIFJT\nmU8j/toF9HyueI1Ea4uvsQ6NANGcYCbOAKCmbNiwABMCFaiUTMAAAAPSbW9vdgAAAGxtdmhkAAAA\nAHwlsIB8JbCAAAAD6AAAAyAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAA\nAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAv10cmFrAAAAXHRraGQA\nAAAPfCWwgHwlsIAAAAABAAAAAAAAAyAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAB\nAAAAAAAAAAAAAAAAAABAAAAAAY4AAAGGAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAMgAAAA\nAgABAAAAAAJ1bWRpYQAAACBtZGhkAAAAAHwlsIB8JbCAAAAAGQAAABRVxAAAAAAALWhkbHIAAAAA\nAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAACIG1pbmYAAAAUdm1oZAAAAAEAAAAA\nAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAeBzdGJsAAAAtHN0c2QA\nAAAAAAAAAQAAAKRhdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAY4BhgBIAAAASAAAAAAAAAAB\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGP//AAAAMmF2Y0MBZAAV/+EAGWdkABWs\n2UGQz6mhAAADAAEAAAMAMg8WLZYBAAZo6+PLIsAAAAAcdXVpZGtoQPJfJE/FujmlG88DI/MAAAAA\nAAAAGHN0dHMAAAAAAAAAAQAAABQAAAABAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAYY3R0cwAAAAAA\nAAABAAAAFAAAAAIAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAZHN0c3oAAAAAAAAAAAAA\nABQAAA05AAACqQAAAl8AAAITAAACiwAAAh8AAAIvAAABiAAAAVsAAAE5AAABWwAAAUQAAAFmAAAA\n/QAAAUEAAAEaAAABKQAAAQAAAADlAAAAzQAAAGBzdGNvAAAAAAAAABQAAAAsAAANZQAAEA4AABJt\nAAAUgAAAFwsAABkqAAAbWQAAHOEAAB48AAAfdQAAINAAACIUAAAjegAAJHcAACW4AAAm0gAAJ/sA\nACj7AAAp4AAAAGF1ZHRhAAAAWW1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAA\nAAAAAAAALGlsc3QAAAAkqXRvbwAAABxkYXRhAAAAAQAAAABMYXZmNTIuMTExLjA=\n\">\n\n\n\n## HTML\n\nPython objects can declare HTML representations that will be displayed in the Notebook. If you have some HTML you want to display, simply use the `HTML` class.\n\n\n```\nfrom IPython.display import HTML\n```\n\n\n```\ns = \"\"\"<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\"\"\"\n```\n\n\n```\nh = HTML(s); h\n```\n\n\n\n\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n\n\n\nPandas makes use of this capability to allow `DataFrames` to be represented as HTML tables.\n\n\n```\nimport pandas\n```\n\nBy default, `DataFrames` will be represented as text; to enable HTML representations we need to set a print option:\n\n\n```\npandas.core.format.set_printoptions(notebook_repr_html=True)\n```\n\nHere is a small amount of stock data for APPL:\n\n\n```\n%%file data.csv\nDate,Open,High,Low,Close,Volume,Adj Close\n2012-06-01,569.16,590.00,548.50,584.00,14077000,581.50\n2012-05-01,584.90,596.76,522.18,577.73,18827900,575.26\n2012-04-02,601.83,644.00,555.00,583.98,28759100,581.48\n2012-03-01,548.17,621.45,516.22,599.55,26486000,596.99\n2012-02-01,458.41,547.61,453.98,542.44,22001000,540.12\n2012-01-03,409.40,458.24,409.00,456.48,12949100,454.53\n```\n\n    Writing data.csv\n\n\nRead this as into a `DataFrame`:\n\n\n```\ndf = pandas.read_csv('data.csv')\n```\n\nAnd view the HTML representation:\n\n\n```\ndf\n```\n\n\n\n\n<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n<table border=\"1\">\n  <thead>\n    <tr>\n      <th></th>\n      <th>Date</th>\n      <th>Open</th>\n      <th>High</th>\n      <th>Low</th>\n      <th>Close</th>\n      <th>Volume</th>\n      <th>Adj Close</th>\n    </tr>\n    </thead>\n    <tbody>\n    <tr>\n      <td><strong>0</strong></td>\n      <td> 2012-06-01</td>\n      <td> 569.16</td>\n      <td> 590.00</td>\n      <td> 548.50</td>\n      <td> 584.00</td>\n      <td> 14077000</td>\n      <td> 581.50</td>\n    </tr>\n    <tr>\n      <td><strong>1</strong></td>\n      <td> 2012-05-01</td>\n      <td> 584.90</td>\n      <td> 596.76</td>\n      <td> 522.18</td>\n      <td> 577.73</td>\n      <td> 18827900</td>\n      <td> 575.26</td>\n    </tr>\n    <tr>\n      <td><strong>2</strong></td>\n      <td> 2012-04-02</td>\n      <td> 601.83</td>\n      <td> 644.00</td>\n      <td> 555.00</td>\n      <td> 583.98</td>\n      <td> 28759100</td>\n      <td> 581.48</td>\n    </tr>\n    <tr>\n      <td><strong>3</strong></td>\n      <td> 2012-03-01</td>\n      <td> 548.17</td>\n      <td> 621.45</td>\n      <td> 516.22</td>\n      <td> 599.55</td>\n      <td> 26486000</td>\n      <td> 596.99</td>\n    </tr>\n    <tr>\n      <td><strong>4</strong></td>\n      <td> 2012-02-01</td>\n      <td> 458.41</td>\n      <td> 547.61</td>\n      <td> 453.98</td>\n      <td> 542.44</td>\n      <td> 22001000</td>\n      <td> 540.12</td>\n    </tr>\n    <tr>\n      <td><strong>5</strong></td>\n      <td> 2012-01-03</td>\n      <td> 409.40</td>\n      <td> 458.24</td>\n      <td> 409.00</td>\n      <td> 456.48</td>\n      <td> 12949100</td>\n      <td> 454.53</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## External sites\n\nYou can even embed an entire page from another site in an iframe; for example this is today's Wikipedia\npage for mobile users:\n\n\n```\nfrom IPython.display import HTML\nHTML('')\n```\n\n\n\n\n\n\n\n\n## LaTeX\n\nAnd we also support the display of mathematical expressions typeset in LaTeX, which is rendered\nin the browser thanks to the [MathJax library](http://mathjax.org).\n\n\n```\nfrom IPython.display import Math\nMath(r'F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx')\n```\n\n\n\n\n$$F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx$$\n\n\n\nWith the `Latex` class, you have to include the delimiters yourself.  This allows you to use other LaTeX modes such as `eqnarray`:\n\n\n```\nfrom IPython.display import Latex\nLatex(r\"\"\"\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\"\"\")\n```\n\n\n\n\n\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\n\n\n\nOr you can enter latex directly with the `%%latex` cell magic:\n\n\n```latex\n%%latex\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n```\n\n\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n\n", "meta": {"hexsha": "257e762199c5c14584cfe6926a17a7043ee290bd", "size": 247743, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/notebooks/Part 5 - Rich Display System.ipynb", "max_stars_repo_name": "chebee7i/ipython", "max_stars_repo_head_hexsha": "85b169fa3afc3d374973295c7f1409ededddbaca", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-20T08:20:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-20T08:20:49.000Z", "max_issues_repo_path": "examples/notebooks/Part 5 - Rich Display System.ipynb", "max_issues_repo_name": "chebee7i/ipython", "max_issues_repo_head_hexsha": "85b169fa3afc3d374973295c7f1409ededddbaca", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/notebooks/Part 5 - Rich Display System.ipynb", "max_forks_repo_name": "chebee7i/ipython", "max_forks_repo_head_hexsha": "85b169fa3afc3d374973295c7f1409ededddbaca", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 186.1329827198, "max_line_length": 93020, "alphanum_fraction": 0.8749631675, "converted": true, "num_tokens": 61805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26588047309981694, "lm_q2_score": 0.1242129953839743, "lm_q1q2_score": 0.03302580997783647}}
{"text": "### Workshop Tutorial: Note that all slides have been optimized for a [RISE slideshow](https://rise.readthedocs.io)\n\n\n```python\n# Ignore warnings that distract from the tutorial\nimport warnings\nwarnings.simplefilter(\"ignore\", category=FutureWarning)\n```\n\n<div align='center' style='font-size:200%'>Validating Computational Models with</div>\n<div align='center'></div>\n<hr>\n<br>\n<div align='center' style='font-size:150%; line-height:80px;'>\nRichard C. (Rick) Gerkin, PhD\n</div>    \n<div align='center' style='font-size:100%; line-height:80px;'>Associate Research Professor, School of Life Sciences<br>\nCo-Director, <a href=\"http://iconlab.asu.edu\">Laboratory for Informatics and Computation in Open Neuroscience</a><br>\nArizona State University, Tempe, AZ USA\n</div>\n<hr>\n\n### <i>[SciUnit](http://sciunit.scidash.org)</i> is a framework for validating scientific models by creating experimental-data-driven <i>unit tests</i>.\n\n#### Conventionally, a unit test is <i>&ldquo;a strict, written contract that the piece of code must satisfy</i>''\n\n#### <i>SciUnit</i> extends this idea from generic computer programs to scientific models, making scientific model validation both formal and transparent.  \n\n#### The validity of a model is then represented by the collection of unit tests that it passes.\n\n### <i>[SciUnit](http://sciunit.scidash.org)</i> is a Python package.  Let's install it, then make sure it can be imported.\n\n\n```python\n# Installation of the `sciunit` package from PyPI\n!pip install -q sciunit\n\n# Import the package\nimport sciunit\n```\n\n\n```python\n# This code cell exists just to generate the mockup table a few cells below.\n# Further down you will see that SciUnit can generate such tables from scores automatically!\nfrom IPython.display import display, HTML\ndisplay(HTML(\"\"\"\n<style>  \n    td.red {\n        background-color: #FF0000;\n        border: 1px solid black;\n    }\n    td.green {\n        background-color: #00FF00;\n        border: 1px solid black;\n    }\n    td.grey {\n        background-color: #AAAAAA;\n        border: 1px solid black;\n    }\n    th {\n        text-align: center;\n        border: 1px solid black;\n    }\n    table td, table th {\n    border: 10px solid black;\n    font-size: 250%;\n    }\n</style>\n\"\"\"))\n```\n\n\n\n<style>  \n    td.red {\n        background-color: #FF0000;\n        border: 1px solid black;\n    }\n    td.green {\n        background-color: #00FF00;\n        border: 1px solid black;\n    }\n    td.grey {\n        background-color: #AAAAAA;\n        border: 1px solid black;\n    }\n    th {\n        text-align: center;\n        border: 1px solid black;\n    }\n    table td, table th {\n    border: 10px solid black;\n    font-size: 250%;\n    }\n</style>\n\n\n\n<div style='font-size:200%; text-align: center;'>Toy example: A brief history of cosmology</div><br>\n\n<table>\n<tr style='background-color: #FFFFFF'>\n    <td></td><th style='text-align: center'>Experimentalists</th>\n</tr>\n<tr>\n    <th>Modelers</th><td><table style='border: 1px solid black'></td>\n<tr>\n    <th></th><th>Babylonians</th><th>Brahe</th><th>Galileo</th><th>Le Verrier</th>\n</tr>\n<tr>\n    <th>Ptolemy</th><td class='green'></td><td class='red'></td><td class='red'></td><td class='red'></td>\n</tr>\n<tr>\n    <th>Copernicus</th><td class='green'></td><td class='red'></td><td class='red'></td><td class='red'></td>\n</tr>\n<tr>\n    <th>Kepler</th><td class='green'></td><td style='background-color:#FF0000'></td><td class='grey'></td><td class='red'></td>\n</tr>\n<tr>\n    <th>Newton</th><td class='green'></td><td class='green'></td><td class='green'></td><td class='red'></td>\n</tr>\n<tr>\n    <th>Einstein</th><td class='green'></td><td class='green'></td><td class='green'></td><td class='green'></td>\n</tr>\n</table>\n</td>\n</tr>\n</table>\n\n<table style='border: 1px solid black'>\n    <tr>\n        <td class='green'>Pass</td><td class='red'>Fail</td><td class='grey'>Unclear</td>\n    </tr>\n</table>\n\n### Model validation goals:   \n\n#### - Generate one unit tests for each experimental datum (or stylized fact about data)\n\n#### - Execute these tests against all models capable of taking them\n\n#### - Programatically display the results as a &ldquo;dashboard\" of model validity\n  - Optionally record and display non-boolean test results, test artifacts, etc.\n\n### High-level workflow for validation:\n\n```python\n# Hypothetical examples of data-driven tests\nfrom cosmounit.tests import brahe_test, galileo_test, leverrier_test\n\n# Hypothetical examples of parameterized models\nfrom cosmounit.models import ptolemy_model, copernicus_model \n\n# Execute one test against one model and return a test score\nscore = brahe_test.judge(copernicus_model) \n```\n\nThis is the only code-like cell of the tutorial that **doesn't** contain executable code, since it is a high-level abstraction.  Don't worry, you'll be running real code just a few cells down!\n\n### Q: How does a test &ldquo;know\" how to test a model?\n\n### A: Through guarantees that models provide to tests, called <i>&ldquo;Capabilities\"</i>.\n\n[Code for **sciunit.capabilities** on GitHub](https://github.com/scidash/sciunit/tree/master/sciunit/capabilities.py)\n\n### Next we show an example of a <i>Capability</i> relevant to the cosmology case outlined above.\n\n\n```python\n# Some imports to make the code below run\nfrom math import pi, sqrt, sin, cos, tan, atan\nfrom datetime import datetime, timedelta\nimport numpy as np\n# SymPy is needed because one of Kepler's equations\n# is in implicit form and must be solved numerically!\nfrom sympy import Symbol, solvers, sin as sin_\n```\n\n\n```python\nclass ProducesOrbitalPosition(sciunit.Capability):\n    \"\"\"\n    A model `capability`, i.e. a collection of methods that a test is allowed to invoke on a model.\n    These methods are unimplemented by design, and the model must implement them.\n    \"\"\"\n    \n    def get_position(self, t: datetime) -> tuple:\n        \"\"\"Produce an orbital position from a time point\n        in polar coordinates.\n        \n        Args:\n            t (datetime): The time point to examine, relative to perihelion\n        Returns:\n            tuple: A pair of (r, theta) coordinates in the oribtal plane\n        \"\"\"\n        raise NotImplementedError(\"\")\n        \n    @property\n    def perihelion(self) -> datetime:\n        \"\"\"Return the time of last perihelion\"\"\"\n        raise NotImplementedError(\"\")\n    \n    @property\n    def period(self) -> float:\n        \"\"\"Return the period of the orbit\"\"\"\n        raise NotImplementedError(\"\")\n    \n    @property\n    def eccentricity(self) -> float:\n        \"\"\"Return the eccentricity of the orbit\"\"\"\n        raise NotImplementedError(\"\")\n    \n    def get_x_y(self, t: datetime) -> tuple:\n        \"\"\"Produce an orbital position from a time point, but in cartesian coordinates.\n        This method does not require a model-specific implementation.\n        Thus, a generic implementation can be provided in advance.\"\"\"\n        r, theta = self.get_position(t)\n        x, y = r*cos(theta), r*sin(theta)\n        return x, y\n```\n\n### <i>[SciUnit](http://sciunit.scidash.org)</i> (and domain specific libraries that build upon it) also define their own capabilities\n\n\n```python\n# An extremely generic model capability\nfrom sciunit.capabilities import ProducesNumber\n\n# A specific model capability used in neurophysiology\n#from neuronunit.capabilities import HasMembranePotential\n```\n\n### Now we can define a <i>model class</i> that implements this `ProducesOrbitalPosition` capability by inheritance.  \n\n### All models are subclasses of `sciunit.Model` and typically one or more subclasses of `sciunit.Capability`.\n\n\n```python\nclass BaseKeplerModel(sciunit.Model, \n                      ProducesOrbitalPosition):\n    \"\"\"A sciunit model class corresponding to a Kepler-type model\n    of an object in the solar system. This model has the \n    `ProducesOrbitalPosition` capability by inheritance,\n    so it must implement all of the unimplemented methods of that capability\"\"\"\n    \n    def get_position(self, t):\n        \"\"\"Implementation of polar coordinate position as a function of time\"\"\"\n        r, theta = self.heliocentric_distance(t), self.true_anomaly(t)\n        return r, theta\n    \n    @property\n    def perihelion(self):\n        \"\"\"Implementation of time of last perihelion\"\"\"\n        return self.params['perihelion']\n    \n    @property\n    def period(self):\n        \"\"\"Implementation of period of the orbit\"\"\"\n        return self.params['period']\n    \n    @property\n    def eccentricity(self):\n        \"\"\"Implementation of orbital eccentricity (assuming elliptic orbit)\"\"\"\n        a, b = self.params['semimajor_axis'], self.params['semiminor_axis']\n        return sqrt(1 - (b/a)**2)\n```\n\n\n```python\nclass KeplerModel(BaseKeplerModel):\n    \"\"\"This 'full' model contains all of the methods required\n    to complete the implementation of the `ProducesOrbitalPosition` capability\"\"\"\n    \n    def mean_anomaly(self, t):\n        \"\"\"How long into its period the object is at time `t`\"\"\"\n        time_since_perihelion = t - self.perihelion\n        return 2*pi*(time_since_perihelion % self.period)/self.period\n    \n    def eccentric_anomaly(self, t):\n        \"\"\"How far the object has gone into its period at time `t`\"\"\"\n        E = Symbol('E')\n        M, e = self.mean_anomaly(t), self.eccentricity\n        expr = E - e*sin_(E) - M\n        return solvers.nsolve(expr, 0)\n    \n    def true_anomaly(self, t):\n        \"\"\"Theta in a polar coordinate system at time `t`\"\"\"\n        e, E = self.eccentricity, self.eccentric_anomaly(t)\n        theta = 2*atan(sqrt(tan(E/2)**2 * (1+e)/(1-e)))\n        return theta\n    \n    def heliocentric_distance(self, t):\n        \"\"\"R in a polar coordinate system at time `t`\"\"\"\n        a, e = self.params['semimajor_axis'], self.eccentricity\n        E = self.eccentric_anomaly(t)\n        return a*(1-e*cos(E))\n```\n\n### Now we can instantiate a <i>specific model</i> from this class, e.g. one representing the orbital path of Earth (according to Kepler)\n\n\n```python\n# The quantities module to put dimensional units on values\nimport quantities as pq\n\n# `earth_model` will be a specific instance of KeplerModel, with its own parameters\nearth_model = KeplerModel(name = \"Kepler's Earth Model\",\n                          semimajor_axis=149598023 * pq.km, \n                          semiminor_axis=149577161 * pq.km, \n                          period=timedelta(365, 22118), # Period of Earth's orbit \n                          perihelion=datetime(2019, 1, 3, 0, 19), # Time and date of Earth's last perihelion\n                         )\n```\n\n### We can use this model to make specific predictions, for example the current distance between Earth and the sun.\n\n\n```python\n# The time right now\nt = datetime.now()\n# Predicted distance from the sun, right now\nr = earth_model.heliocentric_distance(t)\nprint(\"Heliocentric distance of Earth right now is predicted to be %s\" % r.round(1))\n```\n\n    Heliocentric distance of Earth right now is predicted to be 151702813.7 km\n\n\n### Now let's build a test class that we might use to validate (i.e. unit test to produce test scores) with this (and hopefully other) models\n\n### First, what kind of scores do we want our test to return?\n\n\n```python\n# Several score types available in SciUnit\nfrom sciunit.scores import BooleanScore, ZScore, RatioScore, PercentScore # etc., etc.\n```\n\n[Code for **sciunit.scores** on GitHub](https://github.com/scidash/sciunit/tree/master/sciunit/scores)\n\n### Here's a first shot a test class for assessing the agreement between predicted and observed positions of orbiting objects.  All test classes are subclasses of `sciunit.Test`.\n\n\n```python\nclass PositionTest(sciunit.Test):\n    \"\"\"A test of a planetary position at some specified time\"\"\"\n    \n    # This test can only operate on models that implement\n    # the `ProducesOrbitalPosition` capability.\n    required_capabilities = (ProducesOrbitalPosition,)\n    score_type = BooleanScore # This test's 'judge' method will return a BooleanScore.\n    \n    def generate_prediction(self, model):\n        \"\"\"Generate a prediction from a model\"\"\"\n        t = self.observation['t'] # Get the time point from the test's observation\n        x, y = model.get_x_y(t) # Get the predicted x, y coordinates from the model\n        return {'t': t, 'x': x, 'y': y} # Roll this into a model prediction dictionary\n        \n    def compute_score(self, observation, prediction):\n        \"\"\"Compute a test score based on the agreement between\n        the observation (data) and prediction (model)\"\"\"\n        # Compare observation and prediction to get an error measure\n        delta_x = observation['x'] - prediction['x']\n        delta_y = observation['y'] - prediction['y']\n        error = np.sqrt(delta_x**2 + delta_y**2)\n        \n        passing = bool(error < 1e5*pq.kilometer) # Turn this into a True/False score\n        score = self.score_type(passing) # Create a sciunit.Score object\n        score.set_raw(error) # Add some information about how this score was obtained\n        score.description = (\"Passing score if the prediction is \"\n                             \"within < 100,000 km of the observation\") # Describe the scoring logic\n        return score\n```\n\n### We might want to include extra checks and constraints on observed data, test parameters, or other contingent testing logic.\n\n\n```python\nclass StricterPositionTest(PositionTest):\n    # Optional observation units to validate against\n    units = pq.meter\n    \n    # Optional schema for the format of observed data\n    observation_schema = {'t': {'min': 0, 'required': True},\n                          'x': {'units': True, 'required': True},\n                          'y': {'units': True, 'required': True},\n                          'phi': {'required': False}}\n    \n    def validate_observation(self, observation):\n        \"\"\"Additional checks on the observation\"\"\"\n        assert isinstance(observation['t'], datetime)\n        return observation\n        \n    # Optional schema for the format of test parameters\n    params_schema = {'rotate': {'required': False}}\n\n    # Optional schema for the format of default test parameters\n    default_params = {'rotate': False}\n    \n    def compute_score(self, observation, prediction):\n        \"\"\"Optionally use additional information to compute model/data agreement\"\"\"\n        observation_rotated = observation.copy()\n        if 'phi' in observation:\n            # Project x and y values onto the plane defined by `phi`.\n            observation_rotated['x'] *= cos(observation['phi'])\n            observation_rotated['y'] *= cos(observation['phi'])\n        return super().compute_score(observation_rotated, prediction)\n            \n```\n\n### Now we can instantiate a test.  Each test instance is a combination of the test class, describing the testing logic and required capabilties, plus some <i>'observation'</i>, i.e. data.  \n\n\n```python\n# A single test instance, best on the test class `StricterPositionTest` combined with\n# a specific set of observed data (a time and some x, y coordinates)\n# N.B.: This data is made up for illustration purposes\nearth_position_test_march = StricterPositionTest(name = \"Earth Orbital Data on March 1st, 2019\",\n                                                 observation = {'t': datetime(2019, 3, 1),\n                                                                'x': 7.905e7 * pq.km, \n                                                                'y': 1.254e8 * pq.km})\n```\n\n### Finally, we can execute this one test against this one model\n\n\n```python\n# Execute `earth_position_test` against `earth_model` and return a score\nscore = earth_position_test_march.judge(earth_model)\n# Display the score\nscore\n```\n\n\n\n\n    Pass\n\n\n\n### And we can get additional information about the test, including intermediate objects computed in order to generate a score.\n\n\n```python\n# Describe the score in plain language\nscore.describe()\n```\n\n\nPassing score if the prediction is within < 100,000 km of the observation\n\n\n\n\n```python\n# What were the prediction and observation used to compute the score?\nscore.prediction, score.observation\n```\n\n\n\n\n    ({'t': datetime.datetime(2019, 3, 1, 0, 0),\n      'x': array(79046604.57417324) * km,\n      'y': array(1.25401809e+08) * km},\n     {'t': datetime.datetime(2019, 3, 1, 0, 0),\n      'x': array(79050000.) * km,\n      'y': array(1.254e+08) * km})\n\n\n\n\n```python\n# What was the raw error before the decision criterion was applied?\nscore.get_raw()\n```\n\n\n\n\n    array(3847.28076371) * km\n\n\n\n### We may want to bundle many such tests into a `TestSuite`.  This suite may contain test from multiple classes, or simply tests which differ only in the observation (data) used to instantiate them.\n\n\n```python\n# A new test for a new month: same test class, new observation (data)\n# N.B. I deliberately picked \"observed\" values that will make the model fail this test\nearth_position_test_april = StricterPositionTest(name = \"Earth Orbital Data on April 1st, 2019\",\n                                                 observation = {'t': datetime(2019, 4, 1),\n                                                                'x': 160000 * pq.km, \n                                                                'y': 70000 * pq.km})\n\n# A test suite built from both of the tests that we have instantiated\nearth_position_suite = sciunit.TestSuite([earth_position_test_march,\n                                          earth_position_test_april],\n                                         name = 'Earth observations in Spring, 2019')\n```\n\n### We can then test our model against this whole suite of tests\n\n\n```python\n# Run the whole suite (two tests) against one model\nscores = earth_position_suite.judge(earth_model)\n```\n\n\nExecuting test <i>Earth Orbital Data on March 1st, 2019</i> on model <i>Kepler's Earth Model</i>... \n\n\n\nScore is <a style=\"color: rgb(60,169,88)\">Pass</a>\n\n\n\n\nExecuting test <i>Earth Orbital Data on April 1st, 2019</i> on model <i>Kepler's Earth Model</i>... \n\n\n\nScore is <a style=\"color: rgb(230,78,52)\">Fail</a>\n\n\n\n### Rich HTML output is automatically produced when this score output is summarized\n\n\n```python\n# Display the returned `scores` object\nscores\n```\n\n\n\n\n<html><body><div>\n<style scoped=\"\">\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\" id=\"-5639282292270346013\">\n<thead>\n<tr style=\"text-align: right;\">\n<th></th>\n<th title>Earth Orbital Data on March 1st, 2019</th>\n<th title>Earth Orbital Data on April 1st, 2019</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<th title=\"This 'full' model contains all of the methods required to complete the implementation of the `ProducesOrbitalPosition` capability\">Kepler's Earth Model</th>\n<td style=\"background-color: rgb(60,169,88);\" title=\"Passing score if the prediction is within &lt; 100,000 km of the observation\">Pass</td>\n<td style=\"background-color: rgb(230,78,52);\" title=\"Passing score if the prediction is within &lt; 100,000 km of the observation\">Fail</td>\n</tr>\n</tbody>\n</table>\n</div></body></html>\n\n\n\n### We can then expand this to multiple models\n\n\n```python\n# Just like the Kepler model, but returning a random orbital angle\nclass RandomModel(KeplerModel):\n    def get_position(self, t):\n        r, theta = super().get_position(t)\n        return r, 2*pi*np.random.rand()\n```\n\n\n```python\n# A new model instance, using the same parameters but a different underlying model class\nrandom_model = RandomModel(name = \"Random Earth Model\",\n                           semimajor_axis=149598023 * pq.km, \n                           semiminor_axis=149577161 * pq.km, \n                           period=timedelta(365, 22118), # Period of Earth's orbit \n                           perihelion=datetime(2019, 1, 3, 0, 19), # Time and date of Earth's last perihelion\n                           )\n```\n\n\n```python\n# Run the whole suite (two tests) against two models\nscores = earth_position_suite.judge([earth_model, random_model])\n```\n\n\nExecuting test <i>Earth Orbital Data on March 1st, 2019</i> on model <i>Kepler's Earth Model</i>... \n\n\n\nScore is <a style=\"color: rgb(60,169,88)\">Pass</a>\n\n\n\n\nExecuting test <i>Earth Orbital Data on April 1st, 2019</i> on model <i>Kepler's Earth Model</i>... \n\n\n\nScore is <a style=\"color: rgb(230,78,52)\">Fail</a>\n\n\n\n\nExecuting test <i>Earth Orbital Data on March 1st, 2019</i> on model <i>Random Earth Model</i>... \n\n\n\nScore is <a style=\"color: rgb(230,78,52)\">Fail</a>\n\n\n\n\nExecuting test <i>Earth Orbital Data on April 1st, 2019</i> on model <i>Random Earth Model</i>... \n\n\n\nScore is <a style=\"color: rgb(230,78,52)\">Fail</a>\n\n\n\n\n```python\n# Display the returned `scores` object\nscores\n```\n\n\n\n\n<html><body><div>\n<style scoped=\"\">\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\" id=\"-6863700290627069219\">\n<thead>\n<tr style=\"text-align: right;\">\n<th></th>\n<th title>Earth Orbital Data on March 1st, 2019</th>\n<th title>Earth Orbital Data on April 1st, 2019</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<th title=\"This 'full' model contains all of the methods required to complete the implementation of the `ProducesOrbitalPosition` capability\">Kepler's Earth Model</th>\n<td style=\"background-color: rgb(60,169,88);\" title=\"Passing score if the prediction is within &lt; 100,000 km of the observation\">Pass</td>\n<td style=\"background-color: rgb(230,78,52);\" title=\"Passing score if the prediction is within &lt; 100,000 km of the observation\">Fail</td>\n</tr>\n<tr>\n<th title=\"No description available\">Random Earth Model</th>\n<td style=\"background-color: rgb(230,78,52);\" title=\"Passing score if the prediction is within &lt; 100,000 km of the observation\">Fail</td>\n<td style=\"background-color: rgb(230,78,52);\" title=\"Passing score if the prediction is within &lt; 100,000 km of the observation\">Fail</td>\n</tr>\n</tbody>\n</table>\n</div></body></html>\n\n\n\n### Or extract just a slice:\n\n\n```python\n# All the scores for just one model\nscores[earth_model]\n```\n\n\n\n\n    Earth Orbital Data on March 1st, 2019    Pass\n    Earth Orbital Data on April 1st, 2019    Fail\n    Name: Kepler's Earth Model, dtype: object\n\n\n\n\n```python\n# All the scores for just one test\nscores[earth_position_test_march]\n```\n\n\n\n\n    Kepler's Earth Model    Pass\n    Random Earth Model      Fail\n    Name: Earth Orbital Data on March 1st, 2019, dtype: object\n\n\n\n### What about models that <i>can't</i> take a certain test?  Some models aren't capable (even in principle) of doing what the test is asking of them.\n\n\n```python\n# A simple model which has some capabilities, \n# but not the ones needed for the orbital position test\nclass SimpleModel(sciunit.Model,\n                  sciunit.capabilities.ProducesNumber):\n    pass\n\nsimple_model = SimpleModel()\n```\n\n\n```python\n# Run the whole suite (two tests) against two models\nscores = earth_position_suite.judge([earth_model, random_model, simple_model])\n```\n\n\nExecuting test <i>Earth Orbital Data on March 1st, 2019</i> on model <i>Kepler's Earth Model</i>... \n\n\n\nScore is <a style=\"color: rgb(60,169,88)\">Pass</a>\n\n\n\n\nExecuting test <i>Earth Orbital Data on April 1st, 2019</i> on model <i>Kepler's Earth Model</i>... \n\n\n\nScore is <a style=\"color: rgb(230,78,52)\">Fail</a>\n\n\n\n\nExecuting test <i>Earth Orbital Data on March 1st, 2019</i> on model <i>Random Earth Model</i>... \n\n\n\nScore is <a style=\"color: rgb(230,78,52)\">Fail</a>\n\n\n\n\nExecuting test <i>Earth Orbital Data on April 1st, 2019</i> on model <i>Random Earth Model</i>... \n\n\n\nScore is <a style=\"color: rgb(230,78,52)\">Fail</a>\n\n\n\n\nExecuting test <i>Earth Orbital Data on March 1st, 2019</i> on model <i>SimpleModel</i>... \n\n\n\nScore is <a style=\"color: rgb(128,128,128)\">N/A</a>\n\n\n\n\nExecuting test <i>Earth Orbital Data on April 1st, 2019</i> on model <i>SimpleModel</i>... \n\n\n\nScore is <a style=\"color: rgb(128,128,128)\">N/A</a>\n\n\n\n### Incapable models don't fail, they get the equivalent of 'incomplete' grades\n\n\n```python\n# Display the returned `scores` object\nscores\n```\n\n\n\n\n<html><body><div>\n<style scoped=\"\">\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\" id=\"-8815144807251058899\">\n<thead>\n<tr style=\"text-align: right;\">\n<th></th>\n<th title>Earth Orbital Data on March 1st, 2019</th>\n<th title>Earth Orbital Data on April 1st, 2019</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<th title=\"This 'full' model contains all of the methods required to complete the implementation of the `ProducesOrbitalPosition` capability\">Kepler's Earth Model</th>\n<td style=\"background-color: rgb(60,169,88);\" title=\"Passing score if the prediction is within &lt; 100,000 km of the observation\">Pass</td>\n<td style=\"background-color: rgb(230,78,52);\" title=\"Passing score if the prediction is within &lt; 100,000 km of the observation\">Fail</td>\n</tr>\n<tr>\n<th title=\"No description available\">Random Earth Model</th>\n<td style=\"background-color: rgb(230,78,52);\" title=\"Passing score if the prediction is within &lt; 100,000 km of the observation\">Fail</td>\n<td style=\"background-color: rgb(230,78,52);\" title=\"Passing score if the prediction is within &lt; 100,000 km of the observation\">Fail</td>\n</tr>\n<tr>\n<th title=\"No description available\">SimpleModel</th>\n<td style=\"background-color: rgb(128,128,128);\" title=\"A boolean score, which must be True or False.\n\">N/A</td>\n<td style=\"background-color: rgb(128,128,128);\" title=\"A boolean score, which must be True or False.\n\">N/A</td>\n</tr>\n</tbody>\n</table>\n</div></body></html>\n\n\n\n### <i>[SciUnit](http://sciunit.scidash.org)</i> is in use in several multiscale modeling projects including:\n#### - [The Human Brain Project](https://www.humanbrainproject.eu/en/) (neurophysiology, neuroanatomy, neuroimaging)\n#### - [OpenWorm](http://openworm.org/) (biophysics, network dynamics, animal behavior)\n\n### <i>[NeuronUnit](http://neuronunit.scidash.org)</i> is a reference implementation in the domain of neurophysiology of:\n#### - model classes\n#### - test classes\n#### - capability classes\n#### - tools for constructing tests from several public neurophysiology databases\n#### - tools for implementing capabilities from standard model exchange formats\n#### - tools for executing simulations underlying testing using popular simulators\n#### - test-driven model optimization\n\n### <i>[SciDash](http://dash.scidash.org)</i> is a web application for creating, scheduling, and viewing the results of SciUnit tests without writing a single line of code.\n\n<hr>\n<div align='center' style='font-size:300%; line-height:30px;'>\nLinks:\n</div>\n<table align='center' style='font-size:150%; line-height:30px;'>\n<tr>\n    <td width='25%'><a href=\"http://sciunit.scidash.org\"></a></td>\n    <td width='25%'><a href=\"http://neuronunit.scidash.org\"></a></td>\n</tr>\n<tr>\n    <td width='25%'><a href=\"http://dash.scidash.org\"></a></td>\n    <td width='25%'><a href=\"http://metacell.us\"></a></td>\n</tr>\n</table>\n\n<hr>\n<div align='center' style='font-size:200%; line-height:30px;'>\nFunded by:\n</div><br>\n<table align='center' style='line-height:30px;'>\n<tr>\n    <td width='25%'>R01DC018455 (NIDCD)</td>\n    <td width='25%'></td>\n    <td width='25%'>R01MH106674 (NIMH)</td>\n    <td width='25%'></td>\n</tr>\n<tr>\n    <td>R01EB021711 (NIBIB)</td>\n    <td></td>\n    <td>Human Brain Project</td>\n    <td></td>\n</tr>\n</table>\n\n### Thanks also to Sharon Crook, Justas Birgiolas, Russell Jarvis, and Cyrus Omar\n", "meta": {"hexsha": "774a174cba1ba4e5704cc8a621ba57cd943c25f2", "size": 53238, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/workshop-tutorial.ipynb", "max_stars_repo_name": "sbastiaens/sciunit", "max_stars_repo_head_hexsha": "09a68f128b25aba29fe063346b8b8559413f41a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/workshop-tutorial.ipynb", "max_issues_repo_name": "sbastiaens/sciunit", "max_issues_repo_head_hexsha": "09a68f128b25aba29fe063346b8b8559413f41a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/workshop-tutorial.ipynb", "max_forks_repo_name": "sbastiaens/sciunit", "max_forks_repo_head_hexsha": "09a68f128b25aba29fe063346b8b8559413f41a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1875, "max_line_length": 205, "alphanum_fraction": 0.5162853601, "converted": true, "num_tokens": 7141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26894142136999516, "lm_q2_score": 0.12252322052837361, "lm_q1q2_score": 0.03295156907973017}}
{"text": "```python\n!pip install qiskit\n```\n\n    Collecting qiskit\n      Downloading https://files.pythonhosted.org/packages/6f/61/cb7506e17a2566dc8a31a3e1924d91ac0bdd8ff07c71ec698c06647b6306/qiskit-0.26.2.tar.gz\n    Collecting qiskit-terra==0.17.4\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/b3/0c/3c7a8dd451dae0907263e9de9e3e34909e15e18c88a589b44581972c8511/qiskit_terra-0.17.4-cp37-cp37m-manylinux2010_x86_64.whl (6.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.0MB 18.9MB/s \n    \u001b[?25hCollecting qiskit-aer==0.8.2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/c2/d2/6ff15c370b5465b32529b528bf3f4ce1e01f74498be16203aa1c04b67022/qiskit_aer-0.8.2-cp37-cp37m-manylinux2010_x86_64.whl (18.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 18.0MB 112kB/s \n    \u001b[?25hCollecting qiskit-ibmq-provider==0.13.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/be/99/74bbb901f88603a7d850d4889abc06d81ba702e4227151f4a5b66f2631fe/qiskit_ibmq_provider-0.13.1-py3-none-any.whl (228kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 235kB 50.6MB/s \n    \u001b[?25hCollecting qiskit-ignis==0.6.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/54/be/a13c828e457e09d979667a61bddbd8c7246aafa94e2501b6a9154429cbea/qiskit_ignis-0.6.0-py3-none-any.whl (207kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 215kB 51.2MB/s \n    \u001b[?25hCollecting qiskit-aqua==0.9.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/88/79/392c57b978decbb24b902344b536af52c40a751aed0ebbaefa8bc2964cb5/qiskit_aqua-0.9.1-py3-none-any.whl (2.1MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.1MB 47.8MB/s \n    \u001b[?25hRequirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (0.3.3)\n    Collecting ply>=3.10\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/a3/58/35da89ee790598a0700ea49b2a66594140f44dec458c07e8e3d4979137fc/ply-3.11-py2.py3-none-any.whl (49kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 7.9MB/s \n    \u001b[?25hRequirement already satisfied: scipy>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (1.4.1)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (1.7.1)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (2.8.1)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (5.4.8)\n    Collecting fastjsonschema>=2.10\n      Downloading https://files.pythonhosted.org/packages/d1/fb/ea090e917b18320f79be31d754bbe496b715175e865603cfce1eaed2e774/fastjsonschema-2.15.1-py3-none-any.whl\n    Collecting python-constraint>=1.4\n      Downloading https://files.pythonhosted.org/packages/37/8b/5f1bc2734ca611943e1d6733ee244238679f6410a10cd45ede55a61a8402/python-constraint-1.4.0.tar.bz2\n    Collecting retworkx>=0.8.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1b/92/f007f8b9d88dcd5b90e363967e5d54431a68c5fe06d83400732e3b438084/retworkx-0.8.0-cp37-cp37m-manylinux2010_x86_64.whl (1.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.0MB 37.0MB/s \n    \u001b[?25hRequirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (2.6.0)\n    Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (1.19.5)\n    Collecting pybind11>=2.6\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/8d/43/7339dbabbc2793718d59703aace4166f53c29ee1c202f6ff5bf8a26c4d91/pybind11-2.6.2-py2.py3-none-any.whl (191kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 194kB 38.6MB/s \n    \u001b[?25hRequirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit) (1.24.3)\n    Requirement already satisfied: nest-asyncio!=1.1.0,>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit) (1.5.1)\n    Collecting requests-ntlm>=1.1.0\n      Downloading https://files.pythonhosted.org/packages/03/4b/8b9a1afde8072c4d5710d9fa91433d504325821b038e00237dc8d6d833dc/requests_ntlm-1.1.0-py2.py3-none-any.whl\n    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit) (2.23.0)\n    Collecting websockets>=8\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/84/64/78c2b3fe37730b30dca3c93d1f7f4a4286767f86e7c04cf3571b39bc2fb7/websockets-9.1-cp37-cp37m-manylinux2010_x86_64.whl (103kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 112kB 56.8MB/s \n    \u001b[?25hRequirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ignis==0.6.0->qiskit) (56.1.0)\n    Collecting docplex<=2.20.204; sys_platform != \"darwin\"\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/87/99/6f7c219b39fd58c84688ad0713eb932bfcf6be81fc74519e43ea9c915b56/docplex-2.20.204.tar.gz (611kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 614kB 47.7MB/s \n    \u001b[?25hRequirement already satisfied: fastdtw<=0.3.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (0.3.4)\n    Collecting quandl<=3.6.0\n      Downloading https://files.pythonhosted.org/packages/c2/58/9f0e69d836045e3865d263e9ed49f42b23a58526fdabb30f74c430baee3f/Quandl-3.6.0-py2.py3-none-any.whl\n    Requirement already satisfied: scikit-learn<=0.24.1,>=0.20.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (0.22.2.post1)\n    Collecting yfinance<=0.1.55\n      Downloading https://files.pythonhosted.org/packages/7a/e8/b9d7104d3a4bf39924799067592d9e59119fcfc900a425a12e80a3123ec8/yfinance-0.1.55.tar.gz\n    Requirement already satisfied: pandas<=1.2.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (1.1.5)\n    Collecting dlx<=1.0.4\n      Downloading https://files.pythonhosted.org/packages/54/c0/b8fb5bb727e983b6f5251433ef941b48f38c65bb0bd6ec509e9185bcd406/dlx-1.0.4.tar.gz\n    Requirement already satisfied: h5py<=3.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (3.1.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra==0.17.4->qiskit) (1.2.1)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.8.0->qiskit-terra==0.17.4->qiskit) (1.15.0)\n    Collecting cryptography>=1.3\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/b2/26/7af637e6a7e87258b963f1731c5982fb31cd507f0d90d91836e446955d02/cryptography-3.4.7-cp36-abi3-manylinux2014_x86_64.whl (3.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.2MB 48.1MB/s \n    \u001b[?25hCollecting ntlm-auth>=1.0.2\n      Downloading https://files.pythonhosted.org/packages/ff/84/97c550164b54942b0e908c31ef09d9469f3ba4cd7332a671e2125732f63b/ntlm_auth-1.5.0-py2.py3-none-any.whl\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit) (2020.12.5)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit) (2.10)\n    Collecting inflection>=0.3.1\n      Downloading https://files.pythonhosted.org/packages/59/91/aa6bde563e0085a02a435aa99b49ef75b0a4b062635e606dab23ce18d720/inflection-0.5.1-py2.py3-none-any.whl\n    Requirement already satisfied: more-itertools in /usr/local/lib/python3.7/dist-packages (from quandl<=3.6.0->qiskit-aqua==0.9.1->qiskit) (8.7.0)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn<=0.24.1,>=0.20.0->qiskit-aqua==0.9.1->qiskit) (1.0.1)\n    Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance<=0.1.55->qiskit-aqua==0.9.1->qiskit) (0.0.9)\n    Collecting lxml>=4.5.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/30/c0/d0526314971fc661b083ab135747dc68446a3022686da8c16d25fcf6ef07/lxml-4.6.3-cp37-cp37m-manylinux2014_x86_64.whl (6.3MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.3MB 21.5MB/s \n    \u001b[?25hRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas<=1.2.3->qiskit-aqua==0.9.1->qiskit) (2018.9)\n    Requirement already satisfied: cached-property; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from h5py<=3.1.0->qiskit-aqua==0.9.1->qiskit) (1.5.2)\n    Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit) (1.14.5)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit) (2.20)\n    Building wheels for collected packages: qiskit, python-constraint, docplex, yfinance, dlx\n      Building wheel for qiskit (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for qiskit: filename=qiskit-0.26.2-cp37-none-any.whl size=10491 sha256=698cfdbbd40105d0270638c5f9653d4c9dc69f254a34e24fac610bdec400f12f\n      Stored in directory: /root/.cache/pip/wheels/89/89/34/524839952d5a58a7be9789e580bfc1ca883bf6579152444568\n      Building wheel for python-constraint (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for python-constraint: filename=python_constraint-1.4.0-py2.py3-none-any.whl size=24079 sha256=f452b4a9a48a408e36ee7fb95c4baaaa4b8c890b9f84f212e284281ff937f5c1\n      Stored in directory: /root/.cache/pip/wheels/34/31/15/7b070b25d0a549d20ce2e9fe6d727471c2c61ef904720fd40c\n      Building wheel for docplex (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for docplex: filename=docplex-2.20.204-cp37-none-any.whl size=675362 sha256=203c71c424c893e860ff5115c3aa92dbc97a5b1a861e21ae7e1c04e31372556f\n      Stored in directory: /root/.cache/pip/wheels/ae/2c/e2/a099ebb6fda8adeba9c5fc2e25659d195ad2f5c6cc5fb75fd4\n      Building wheel for yfinance (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for yfinance: filename=yfinance-0.1.55-py2.py3-none-any.whl size=22616 sha256=b0089e1fd044b1f84b5d72ddb8390856166d5d4065842830c6c50246d790a2df\n      Stored in directory: /root/.cache/pip/wheels/04/98/cc/2702a4242d60bdc14f48b4557c427ded1fe92aedf257d4565c\n      Building wheel for dlx (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for dlx: filename=dlx-1.0.4-cp37-none-any.whl size=5712 sha256=4e274b85d25833d295df328b87030011702efc9a4d9fac75f209e61841557aea\n      Stored in directory: /root/.cache/pip/wheels/bb/ba/15/fdd0deb104df3254912998150ba9245668db06b00af5912d1a\n    Successfully built qiskit python-constraint docplex yfinance dlx\n    Installing collected packages: ply, fastjsonschema, python-constraint, retworkx, qiskit-terra, pybind11, qiskit-aer, cryptography, ntlm-auth, requests-ntlm, websockets, qiskit-ibmq-provider, qiskit-ignis, docplex, inflection, quandl, lxml, yfinance, dlx, qiskit-aqua, qiskit\n      Found existing installation: lxml 4.2.6\n        Uninstalling lxml-4.2.6:\n          Successfully uninstalled lxml-4.2.6\n    Successfully installed cryptography-3.4.7 dlx-1.0.4 docplex-2.20.204 fastjsonschema-2.15.1 inflection-0.5.1 lxml-4.6.3 ntlm-auth-1.5.0 ply-3.11 pybind11-2.6.2 python-constraint-1.4.0 qiskit-0.26.2 qiskit-aer-0.8.2 qiskit-aqua-0.9.1 qiskit-ibmq-provider-0.13.1 qiskit-ignis-0.6.0 qiskit-terra-0.17.4 quandl-3.6.0 requests-ntlm-1.1.0 retworkx-0.8.0 websockets-9.1 yfinance-0.1.55\n\n\n\n```python\n!pip install qiskit-aer-gpu\n```\n\n    Collecting qiskit-aer-gpu\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/e0/03/722a3ea4639b15f62c18ed980e5707c39c6aff3752f415fd37922864d2ac/qiskit_aer_gpu-0.8.2-cp37-cp37m-manylinux2010_x86_64.whl (28.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 28.0MB 109kB/s \n    \u001b[?25hRequirement already satisfied: qiskit-terra>=0.17.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer-gpu) (0.17.4)\n    Requirement already satisfied: pybind11>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer-gpu) (2.6.2)\n    Requirement already satisfied: numpy>=1.16.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer-gpu) (1.19.5)\n    Requirement already satisfied: scipy>=1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer-gpu) (1.4.1)\n    Requirement already satisfied: fastjsonschema>=2.10 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-aer-gpu) (2.15.1)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-aer-gpu) (0.3.3)\n    Requirement already satisfied: ply>=3.10 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-aer-gpu) (3.11)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-aer-gpu) (1.7.1)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-aer-gpu) (2.8.1)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-aer-gpu) (5.4.8)\n    Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-aer-gpu) (2.6.0)\n    Requirement already satisfied: retworkx>=0.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-aer-gpu) (0.8.0)\n    Requirement already satisfied: python-constraint>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-aer-gpu) (1.4.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra>=0.17.0->qiskit-aer-gpu) (1.2.1)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.8.0->qiskit-terra>=0.17.0->qiskit-aer-gpu) (1.15.0)\n    Installing collected packages: qiskit-aer-gpu\n    Successfully installed qiskit-aer-gpu-0.8.2\n\n\n\n\n\n```python\nfrom qiskit.providers.aer import QasmSimulator  \nfrom qiskit.providers.aer import AerSimulator\nfrom qiskit.circuit.library import TwoLocal\nfrom qiskit.algorithms import VQE\nfrom qiskit.algorithms.optimizers import COBYLA \nfrom qiskit.circuit.library import EfficientSU2\nfrom qiskit.aqua import set_qiskit_aqua_logging, QuantumInstance\nfrom qiskit.providers.aer import AerError\n# opflow is Qiskit's module for creating operators like yours\nfrom qiskit import *\nfrom qiskit.opflow import OperatorBase\nfrom qiskit.opflow import Z, X, I  # Pauli Z, X matrices and identity\nimport pylab\nimport matplotlib.pyplot as plt\nimport numpy as np\n```\n\n\n```python\n# The config to be referenced by the rest of the notebook\n# Change here to change the params\n\nlattice_length = 3\nno_of_terms_in_hamiltonian = 3 ** 2\nB_x =  1.\nB_z = 1.\nJ = 1.\n```\n\n\n```python\n\n```\n\n\n```python\ndef get_interaction(element_1, element_2, matrix_dimension):\n    output = []\n    (tR, tC) = matrix_dimension\n    (R1, C1) = element_1\n    (R2, C2) = element_2\n    if (-1 in element_1) or (-1 in element_2) or (tR in [R1, R2]) or (tC in [C1, C2]):\n        # Return empty, for outside bounds in edge cases  \n        return \"\"\n    '''\n    element_1 : [1, 0]\n    element_2 : [2, 0]\n    matrix_dimension : 3, 3\n\n    output : III ZII ZII\n\n    III\n    ZII\n    ZII\n\n\n    '''\n    for _ in range(tR):\n        R = []\n        for _ in range(tC):\n            R += [ \"I\" ]\n        output += [R]\n    R,C = element_1\n    output[R][C] = \"Z\"\n    R,C = element_2\n    output[R][C] = \"Z\" \n    output = \"^\".join([ \"^\".join([ R for R in C ]) for C in output ])\n    return f\"({output})\"\n\n# print(get_interaction((0, 1), (1, 1), (3,3)))\n\ndef HamiltonianInteraction(matrix_dimension = None):\n    if not matrix_dimension:\n        matrix_dimension = (lattice_length , lattice_length)\n    (tR, tC) = matrix_dimension\n    output = \"\"\n    for R in range(tR):\n        for C in range(tC):\n            Oi = (R, C)\n            Li = (R-1, C)\n            Ri = (R+1, C)\n            Ti = (R, C-1)\n            Bi = (R, C+1)\n            I = []\n            I += [get_interaction(Li, Oi, matrix_dimension)]\n            I += [get_interaction(Ri, Oi, matrix_dimension)]\n            I += [get_interaction(Ti, Oi, matrix_dimension)]\n            I += [get_interaction(Bi, Oi, matrix_dimension)]\n            I = \"+\".join(I)\n            # print(I)\n            output += I + \"+\"\n    return output.replace(\"++\", \"+\").replace(\"++\", \"+\").strip('+')\n            \nfrom pprint import pprint\nprint( HamiltonianInteraction( (5,5) ) )\n```\n\n    (Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)\n\n\n\n```python\nH = J * ((Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)\n) - B_x * ( ( X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X )\n) - B_z * (( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z )\n)\n```\n\n\n```python\ncounts = []\nvalues = []\n\n\ndef store_intermediate_result(eval_count, parameters, mean, std):\n  \n  counts.append(eval_count)\n  values.append(mean)\n```\n\n\n```python\ndef run(B_X = 1, J_z = 1, B_Z = 1):\n    master_counts = []\n    master_values = []\n    # for h in range (1,5,1): \n    #     h=+h\n\n    # Initialization\n    B_x = B_X\n    J = J_z\n    B_z = B_Z\n\n    # or whatever value you have for h\n    #H = - B_X * ((X ^ I ^ I ^ I) + (I ^ X ^ I ^ I) + (I ^ I ^ X ^ I) + (I ^ I ^ I ^ X)) + J_z * ((Z ^ Z ^ I ^ I ) + (I ^ Z ^ Z ^ I) + (I ^ I ^ Z ^ Z) + (Z ^ I ^ I ^ Z)) - B_Z * ((Z ^ I ^ I ^ I) + (I ^ Z ^ I ^ I) + (I ^ I ^ Z ^ I ) + (I ^ I ^ I ^ Z))\n   \n\n    # for 25 qubits\n    H = J * ((Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)\n) - B_x * ( ( X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X )\n) - B_z * (( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z )\n)\n    # you can swap this for a real quantum device and keep the rest of the code the same!\n    backend = AerSimulator(device=\"GPU\") \n\n    # COBYLA usually works well for small problems like this one\n    optimizer = COBYLA()\n\n    # EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library\n    #ansatz = EfficientSU2(4, reps=1)\n\n    # for 25 qubits\n    # ansatz = EfficientSU2(25, reps=1)\n    ansatz = TwoLocal(num_qubits=25, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True)\n\n    # set the algorithm\n    vqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result)\n\n    # run it with the Hamiltonian we defined above\n    result = vqe.compute_minimum_eigenvalue(H)  \n\n    # print the result (it contains lot's of information)\n    return result\n\n```\n\n\n```python\n%%time\nprint(run())\n```\n\n    {   'aux_operator_eigenvalues': None,\n        'cost_function_evals': 890,\n        'eigenstate': {   '0001010100010011001001010': 0.03125,\n                          '0001010101010011000001010': 0.03125,\n                          '0001010101010011010001011': 0.03125,\n                          '0001010101010011011001010': 0.03125,\n                          '0100010100010011011001010': 0.03125,\n                          '0100010100010111011001010': 0.03125,\n                          '0100010101010001010001010': 0.03125,\n                          '0100010101010001011001011': 0.03125,\n                          '0100010101010011010001010': 0.06987712429686843,\n                          '0100010101010011010001011': 0.03125,\n                          '0100010101010011011001011': 0.03125,\n                          '0100010101010111000001011': 0.03125,\n                          '0100010101010111010001010': 0.03125,\n                          '0101000100010011010001010': 0.03125,\n                          '0101000101010001011001011': 0.03125,\n                          '0101000101010010010000010': 0.03125,\n                          '0101000101010011010001010': 0.03125,\n                          '0101000101010011011001000': 0.03125,\n                          '0101000101010011011001010': 0.03125,\n                          '0101000101110011010001110': 0.03125,\n                          '0101010001010010010001010': 0.03125,\n                          '0101010001010110011001010': 0.03125,\n                          '0101010100010000010001011': 0.03125,\n                          '0101010100010001000001011': 0.03125,\n                          '0101010100010001010001001': 0.03125,\n                          '0101010100010001010001010': 0.04419417382415922,\n                          '0101010100010001010001011': 0.05412658773652741,\n                          '0101010100010001011001010': 0.08267972847076846,\n                          '0101010100010010010001010': 0.03125,\n                          '0101010100010010011001010': 0.03125,\n                          '0101010100010011000001010': 0.0625,\n                          '0101010100010011001001010': 0.03125,\n                          '0101010100010011001001011': 0.03125,\n                          '0101010100010011010001010': 0.15309310892394862,\n                          '0101010100010011010001011': 0.11267347735824966,\n                          '0101010100010011010011010': 0.03125,\n                          '0101010100010011010011011': 0.03125,\n                          '0101010100010011011001000': 0.03125,\n                          '0101010100010011011001001': 0.04419417382415922,\n                          '0101010100010011011001010': 0.15934435979977452,\n                          '0101010100010011011001011': 0.11267347735824966,\n                          '0101010100010011011001111': 0.03125,\n                          '0101010100010011011011010': 0.03125,\n                          '0101010100010011011111011': 0.03125,\n                          '0101010100010101000001010': 0.03125,\n                          '0101010100010101010001000': 0.03125,\n                          '0101010100010101010001010': 0.03125,\n                          '0101010100010101011001001': 0.03125,\n                          '0101010100010101011001010': 0.0625,\n                          '0101010100010101011001011': 0.03125,\n                          '0101010100010110011001010': 0.03125,\n                          '0101010100010111000001010': 0.03125,\n                          '0101010100010111000001011': 0.03125,\n                          '0101010100010111001001010': 0.03125,\n                          '0101010100010111001001011': 0.03125,\n                          '0101010100010111010001001': 0.03125,\n                          '0101010100010111010001010': 0.0625,\n                          '0101010100010111010001011': 0.04419417382415922,\n                          '0101010100010111011001010': 0.07654655446197431,\n                          '0101010100010111011001011': 0.04419417382415922,\n                          '0101010100110001001001011': 0.03125,\n                          '0101010100110001011001010': 0.04419417382415922,\n                          '0101010100110011010001010': 0.03125,\n                          '0101010100110011010001011': 0.03125,\n                          '0101010100110011011001010': 0.04419417382415922,\n                          '0101010101000001011001011': 0.03125,\n                          '0101010101000011000001011': 0.03125,\n                          '0101010101000011010001010': 0.04419417382415922,\n                          '0101010101000111010001011': 0.03125,\n                          '0101010101000111011001000': 0.03125,\n                          '0101010101010000001001010': 0.03125,\n                          '0101010101010000010001011': 0.03125,\n                          '0101010101010001000001010': 0.03125,\n                          '0101010101010001000001011': 0.03125,\n                          '0101010101010001001001010': 0.04419417382415922,\n                          '0101010101010001001001110': 0.03125,\n                          '0101010101010001010001000': 0.03125,\n                          '0101010101010001010001001': 0.03125,\n                          '0101010101010001010001010': 0.18221724671391565,\n                          '0101010101010001010001011': 0.14657549249448218,\n                          '0101010101010001010011011': 0.03125,\n                          '0101010101010001011001000': 0.03125,\n                          '0101010101010001011001001': 0.04419417382415922,\n                          '0101010101010001011001010': 0.15934435979977452,\n                          '0101010101010001011001011': 0.1288470508005519,\n                          '0101010101010001011011001': 0.03125,\n                          '0101010101010001011011010': 0.03125,\n                          '0101010101010010010001011': 0.05412658773652741,\n                          '0101010101010010011001010': 0.05412658773652741,\n                          '0101010101010010011001011': 0.04419417382415922,\n                          '0101010101010011000000010': 0.03125,\n                          '0101010101010011000001001': 0.03125,\n                          '0101010101010011000001010': 0.08267972847076846,\n                          '0101010101010011000001011': 0.08267972847076846,\n                          '0101010101010011001001000': 0.04419417382415922,\n                          '0101010101010011001001001': 0.03125,\n                          '0101010101010011001001010': 0.09375,\n                          '0101010101010011001001011': 0.06987712429686843,\n                          '0101010101010011010000011': 0.03125,\n                          '0101010101010011010001000': 0.08267972847076846,\n                          '0101010101010011010001001': 0.06987712429686843,\n                          '0101010101010011010001010': 0.38654115240165565,\n                          '0101010101010011010001011': 0.28641098093474,\n                          '0101010101010011010001110': 0.03125,\n                          '0101010101010011010011010': 0.0625,\n                          '0101010101010011010011011': 0.05412658773652741,\n                          '0101010101010011011000010': 0.03125,\n                          '0101010101010011011001000': 0.04419417382415922,\n                          '0101010101010011011001001': 0.03125,\n                          '0101010101010011011001010': 0.3736956482219187,\n                          '0101010101010011011001011': 0.27775607554111215,\n                          '0101010101010011011001110': 0.03125,\n                          '0101010101010011011011010': 0.03125,\n                          '0101010101010011011011011': 0.04419417382415922,\n                          '0101010101010100011001011': 0.03125,\n                          '0101010101010101000001010': 0.03125,\n                          '0101010101010101001001010': 0.03125,\n                          '0101010101010101010001010': 0.09375,\n                          '0101010101010101010001011': 0.04419417382415922,\n                          '0101010101010101010011011': 0.03125,\n                          '0101010101010101011001000': 0.03125,\n                          '0101010101010101011001001': 0.04419417382415922,\n                          '0101010101010101011001010': 0.08838834764831845,\n                          '0101010101010101011001011': 0.0625,\n                          '0101010101010110010001010': 0.03125,\n                          '0101010101010110010001011': 0.03125,\n                          '0101010101010110011001011': 0.03125,\n                          '0101010101010111000001000': 0.03125,\n                          '0101010101010111000001010': 0.05412658773652741,\n                          '0101010101010111000001011': 0.03125,\n                          '0101010101010111001001010': 0.04419417382415922,\n                          '0101010101010111001001011': 0.05412658773652741,\n                          '0101010101010111010000010': 0.03125,\n                          '0101010101010111010001000': 0.03125,\n                          '0101010101010111010001010': 0.15625,\n                          '0101010101010111010001011': 0.15934435979977452,\n                          '0101010101010111010011010': 0.04419417382415922,\n                          '0101010101010111011000010': 0.03125,\n                          '0101010101010111011001000': 0.03125,\n                          '0101010101010111011001001': 0.05412658773652741,\n                          '0101010101010111011001010': 0.19764235376052372,\n                          '0101010101010111011001011': 0.10825317547305482,\n                          '0101010101010111011011010': 0.03125,\n                          '0101010101010111110001011': 0.03125,\n                          '0101010101010111111001010': 0.03125,\n                          '0101010101011001010001010': 0.03125,\n                          '0101010101011011000001011': 0.03125,\n                          '0101010101011011010001010': 0.04419417382415922,\n                          '0101010101011011011001011': 0.03125,\n                          '0101010101011111011001010': 0.03125,\n                          '0101010101110000010001010': 0.03125,\n                          '0101010101110001010001010': 0.03125,\n                          '0101010101110001010001011': 0.03125,\n                          '0101010101110001011001011': 0.03125,\n                          '0101010101110010010001010': 0.03125,\n                          '0101010101110011010001010': 0.05412658773652741,\n                          '0101010101110011010001011': 0.04419417382415922,\n                          '0101010101110011010001111': 0.03125,\n                          '0101010101110011011001001': 0.03125,\n                          '0101010101110011011001010': 0.05412658773652741,\n                          '0101010101110011011001011': 0.03125,\n                          '0101010101110101011001010': 0.03125,\n                          '0101010101110111010001001': 0.03125,\n                          '0101010101110111011001011': 0.03125,\n                          '0101010110010011010001010': 0.03125,\n                          '0101010110010011010001011': 0.03125,\n                          '0101010111010001011001010': 0.04419417382415922,\n                          '0101010111010011010001011': 0.03125,\n                          '0101010111010011011001010': 0.05412658773652741,\n                          '0101010111010011011001011': 0.03125,\n                          '0101010111010111011001010': 0.03125,\n                          '0101100101010011011001010': 0.03125,\n                          '0101110101010011000001010': 0.04419417382415922,\n                          '0101110101010011011001010': 0.03125,\n                          '0101110101010111010001010': 0.03125,\n                          '0101110101010111011001011': 0.03125,\n                          '0111010100010011010001010': 0.03125,\n                          '0111010101010001010001010': 0.03125,\n                          '0111010101010011010001001': 0.03125,\n                          '0111010101010011011001010': 0.04419417382415922,\n                          '0111010101110111010001010': 0.03125,\n                          '0111110101010011011001011': 0.03125},\n        'eigenvalue': -61.46679687499999,\n        'optimal_parameters': {   ParameterVectorElement(\u03b8[48]): 1.3879826750116153,\n                                  ParameterVectorElement(\u03b8[49]): -5.692306350261993,\n                                  ParameterVectorElement(\u03b8[46]): -0.9765056717742162,\n                                  ParameterVectorElement(\u03b8[45]): -3.9202100795418695,\n                                  ParameterVectorElement(\u03b8[44]): -5.3892299962323245,\n                                  ParameterVectorElement(\u03b8[43]): -3.2129337679526633,\n                                  ParameterVectorElement(\u03b8[42]): 0.857814430543177,\n                                  ParameterVectorElement(\u03b8[41]): 0.06922430705629404,\n                                  ParameterVectorElement(\u03b8[40]): -6.191235148359483,\n                                  ParameterVectorElement(\u03b8[22]): 6.142322250424499,\n                                  ParameterVectorElement(\u03b8[23]): -3.27566987995911,\n                                  ParameterVectorElement(\u03b8[21]): -3.408492727604697,\n                                  ParameterVectorElement(\u03b8[2]): -0.16945681550940936,\n                                  ParameterVectorElement(\u03b8[38]): -6.672907932303622,\n                                  ParameterVectorElement(\u03b8[32]): 3.079396429452302,\n                                  ParameterVectorElement(\u03b8[33]): 0.935602108002725,\n                                  ParameterVectorElement(\u03b8[26]): -5.595933820879026,\n                                  ParameterVectorElement(\u03b8[24]): 0.1320188509933961,\n                                  ParameterVectorElement(\u03b8[27]): -2.790840933857421,\n                                  ParameterVectorElement(\u03b8[28]): 0.9021687358150642,\n                                  ParameterVectorElement(\u03b8[29]): -3.4491848962808214,\n                                  ParameterVectorElement(\u03b8[25]): -0.16878194466343688,\n                                  ParameterVectorElement(\u03b8[30]): 7.896363048418679,\n                                  ParameterVectorElement(\u03b8[37]): 3.6186189620904603,\n                                  ParameterVectorElement(\u03b8[35]): 0.3785229925668783,\n                                  ParameterVectorElement(\u03b8[31]): -3.680612269560758,\n                                  ParameterVectorElement(\u03b8[34]): -3.474516311037871,\n                                  ParameterVectorElement(\u03b8[36]): -6.078921969002316,\n                                  ParameterVectorElement(\u03b8[39]): 5.368183796446824,\n                                  ParameterVectorElement(\u03b8[17]): 3.0204951284945634,\n                                  ParameterVectorElement(\u03b8[18]): 6.208999847214833,\n                                  ParameterVectorElement(\u03b8[19]): -3.3450227313274583,\n                                  ParameterVectorElement(\u03b8[16]): 0.22844107271692862,\n                                  ParameterVectorElement(\u03b8[20]): -6.437872257360187,\n                                  ParameterVectorElement(\u03b8[0]): 7.5630660880494345,\n                                  ParameterVectorElement(\u03b8[1]): -3.540135535711661,\n                                  ParameterVectorElement(\u03b8[14]): -5.972233337821895,\n                                  ParameterVectorElement(\u03b8[9]): 3.4214486203698597,\n                                  ParameterVectorElement(\u03b8[3]): -3.018731621158342,\n                                  ParameterVectorElement(\u03b8[5]): -6.2421207669499985,\n                                  ParameterVectorElement(\u03b8[4]): 5.988578673589853,\n                                  ParameterVectorElement(\u03b8[11]): 0.97087324051206,\n                                  ParameterVectorElement(\u03b8[15]): -3.957114521320829,\n                                  ParameterVectorElement(\u03b8[13]): 3.0111283875427697,\n                                  ParameterVectorElement(\u03b8[10]): -4.004811565876194,\n                                  ParameterVectorElement(\u03b8[8]): -6.185142777795119,\n                                  ParameterVectorElement(\u03b8[12]): 6.104572287313623,\n                                  ParameterVectorElement(\u03b8[6]): 4.71469445362316,\n                                  ParameterVectorElement(\u03b8[7]): -2.646036560253415,\n                                  ParameterVectorElement(\u03b8[47]): 2.5099277213131335},\n        'optimal_point': array([ 7.56306609, -4.00481157,  0.97087324,  6.10457229,  3.01112839,\n           -5.97223334, -3.95711452,  0.22844107,  3.02049513,  6.20899985,\n           -3.34502273, -3.54013554, -6.43787226, -3.40849273,  6.14232225,\n           -3.27566988,  0.13201885, -0.16878194, -5.59593382, -2.79084093,\n            0.90216874, -3.4491849 , -0.16945682,  7.89636305, -3.68061227,\n            3.07939643,  0.93560211, -3.47451631,  0.37852299, -6.07892197,\n            3.61861896, -6.67290793,  5.3681838 , -3.01873162, -6.19123515,\n            0.06922431,  0.85781443, -3.21293377, -5.38923   , -3.92021008,\n           -0.97650567,  2.50992772,  1.38798268, -5.69230635,  5.98857867,\n           -6.24212077,  4.71469445, -2.64603656, -6.18514278,  3.42144862]),\n        'optimal_value': -61.46679687499999,\n        'optimizer_evals': 890,\n        'optimizer_time': 4389.55037689209}\n    CPU times: user 1h 13min 6s, sys: 15.3 s, total: 1h 13min 21s\n    Wall time: 1h 13min 10s\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "5f4c8217ea302978b6b41fa326649e98d93d60a0", "size": 69893, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "research/rough-work-misc/2D_Ising_Model.ipynb", "max_stars_repo_name": "arnavdas88/QuGlassyIsing", "max_stars_repo_head_hexsha": "6b6514d58646130c03619aebefb9f9aed4e5646a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-19T16:06:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T17:03:31.000Z", "max_issues_repo_path": "research/rough-work-misc/2D_Ising_Model.ipynb", "max_issues_repo_name": "IshmamShah/QuGlassyIsing", "max_issues_repo_head_hexsha": "6c3ff2ebd77ed9b34a0e731083f1e56b7eacb7ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "research/rough-work-misc/2D_Ising_Model.ipynb", "max_forks_repo_name": "IshmamShah/QuGlassyIsing", "max_forks_repo_head_hexsha": "6c3ff2ebd77ed9b34a0e731083f1e56b7eacb7ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-19T16:06:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T06:51:18.000Z", "avg_line_length": 97.479776848, "max_line_length": 4185, "alphanum_fraction": 0.4684875452, "converted": true, "num_tokens": 29177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233681595684605, "lm_q2_score": 0.08389038526538414, "lm_q1q2_score": 0.03291328664441393}}
{"text": "```python\n%matplotlib inline\n```\n\n\n.. currentmodule:: dgl\n\nWorking with Heterogeneous Graphs\n=================================\n\n**Author**: Quan Gan, `Minjie Wang <https://jermainewang.github.io/>`_, Mufei Li,\nGeorge Karypis, Zheng Zhang\n\nIn this tutorial, you learn about:\n\n* Examples of heterogenous graph data and typical applications.\n\n* Creating and manipulating a heterogenous graph in DGL.\n\n* Implementing `Relational-GCN <https://arxiv.org/abs/1703.06103>`_, a popular GNN model,\n  for heterogenous graph input.\n\n* Training a model to solve a node classification task.\n\nHeterogeneous graphs, or *heterographs* for short, are graphs that contain\ndifferent types of nodes and edges. The different types of nodes and edges tend\nto have different types of attributes that are designed to capture the\ncharacteristics of each node and edge type. Within the context of\ngraph neural networks, depending on their complexity, certain node and edge types\nmight need to be modeled with representations that have a different number of dimensions.\n\nDGL supports graph neural network computations on such heterogeneous graphs, by\nusing the heterograph class and its associated API.\n\n\nExamples of heterographs\n-----------------------\nMany graph datasets represent relationships among various types of entities.\nThis section provides an overview for several graph use-cases that show such relationships \nand can have their data represented as heterographs.\n\nCitation graph \n~~~~~~~~~~~~~~~\nThe Association for Computing Machinery publishes an `ACM dataset <https://aminer.org/citation>`_ that contains two\nmillion papers, their authors, publication venues, and the other papers\nthat were cited. This information can be represented as a heterogeneous graph.\n\nThe following diagram shows several entities in the ACM dataset and the relationships among them \n(taken from `Shi et al., 2015 <https://arxiv.org/pdf/1511.04854.pdf>`_).\n\n.. figure:: https://data.dgl.ai/tutorial/hetero/acm-example.png# \n\nThis graph has three types of entities that correspond to papers, authors, and publication venues.\nIt also contains three types of edges that connect the following:\n\n* Authors with papers corresponding to *written-by* relationships\n\n* Papers with publication venues corresponding to *published-in* relationships\n\n* Papers with other papers corresponding to *cited-by* relationships\n\n\nRecommender systems \n~~~~~~~~~~~~~~~~~~~~ \nThe datasets used in recommender systems often contain\ninteractions between users and items. For example, the data could include the\nratings that users have provided to movies. Such interactions can be modeled\nas heterographs.\n\nThe nodes in these heterographs will have two types, *users* and *movies*. The edges\nwill correspond to the user-movie interactions. Furthermore, if an interaction is\nmarked with a rating, then each rating value could correspond to a different edge type.\nThe following diagram shows an example of user-item interactions as a heterograph.\n\n.. figure:: https://data.dgl.ai/tutorial/hetero/recsys-example.png\n\n\nKnowledge graph \n~~~~~~~~~~~~~~~~\nKnowledge graphs are inherently heterogenous. For example, in\nWikidata, Barack Obama (item Q76) is an instance of a human, which could be viewed as\nthe entity class, whose spouse (item P26) is Michelle Obama (item Q13133) and\noccupation (item P106) is politician (item Q82955). The relationships are shown in the following.\ndiagram.\n\n.. figure:: https://data.dgl.ai/tutorial/hetero/kg-example.png\n\n\n\n\nCreating a heterograph in DGL\n-----------------------------\nYou can create a heterograph in DGL using the :func:`dgl.heterograph` API.\nThe argument to :func:`dgl.heterograph` is a dictionary. The keys are tuples\nin the form of ``(srctype, edgetype, dsttype)`` specifying the relation name\nand the two entity types it connects. Such tuples are called *canonical edge\ntypes*. The values are data to initialize the graph structures, that is, which\nnodes the edges actually connect.\n\nFor instance, the following code creates the user-item interactions heterograph shown earlier.\n\n\n\n\n```python\n# Each value of the dictionary is a pair of source and destination arrays.\n# Nodes are integer IDs starting from zero. Nodes IDs of different types have\n# separate countings.\nimport dgl\nimport numpy as np\n\nratings = dgl.heterograph(\n    {('user', '+1', 'movie') : (np.array([0, 0, 1]), np.array([0, 1, 0])),\n     ('user', '-1', 'movie') : (np.array([2]), np.array([1]))})\n```\n\nDGL supports creating a graph from a variety of data sources. The following\ncode creates the same graph as the above.\n\nCreating from scipy matrix\n\n\n\n\n```python\nimport scipy.sparse as sp\nplus1 = sp.coo_matrix(([1, 1, 1], ([0, 0, 1], [0, 1, 0])), shape=(3, 2))\nminus1 = sp.coo_matrix(([1], ([2], [1])), shape=(3, 2))\nratings = dgl.heterograph(\n    {('user', '+1', 'movie') : plus1,\n     ('user', '-1', 'movie') : minus1})\n\n# Creating from networkx graph\nimport networkx as nx\nplus1 = nx.DiGraph()\nplus1.add_nodes_from(['u0', 'u1', 'u2'], bipartite=0)\nplus1.add_nodes_from(['m0', 'm1'], bipartite=1)\nplus1.add_edges_from([('u0', 'm0'), ('u0', 'm1'), ('u1', 'm0')])\n# To simplify the example, reuse the minus1 object.\n# This also means that you could use different sources of graph data\n# for different relationships.\nratings = dgl.heterograph(\n    {('user', '+1', 'movie') : plus1,\n     ('user', '-1', 'movie') : minus1})\n```\n\nManipulating heterograph\n------------------------\nYou can create a more realistic heterograph using the ACM dataset. To do this, first \ndownload the dataset as follows:\n\n\n\n\n```python\nimport scipy.io\nimport urllib.request\n\n\ndata_file_path = 'ACM.mat'\n\ndata = scipy.io.loadmat(data_file_path)\nprint(list(data.keys()))\n```\n\n    ['__header__', '__version__', '__globals__', 'TvsP', 'PvsA', 'PvsV', 'AvsF', 'VvsC', 'PvsL', 'PvsC', 'A', 'C', 'F', 'L', 'P', 'T', 'V', 'PvsT', 'CNormPvsA', 'RNormPvsA', 'CNormPvsC', 'RNormPvsC', 'CNormPvsT', 'RNormPvsT', 'CNormPvsV', 'RNormPvsV', 'CNormVvsC', 'RNormVvsC', 'CNormAvsF', 'RNormAvsF', 'CNormPvsL', 'RNormPvsL', 'stopwords', 'nPvsT', 'nT', 'CNormnPvsT', 'RNormnPvsT', 'nnPvsT', 'nnT', 'CNormnnPvsT', 'RNormnnPvsT', 'PvsP', 'CNormPvsP', 'RNormPvsP']\n\n\nThe dataset stores node information by their types: ``P`` for paper, ``A``\nfor author, ``C`` for conference, ``L`` for subject code, and so on. The relationships\nare stored as SciPy sparse matrix under key ``XvsY``, where ``X`` and ``Y``\ncould be any of the node type code.\n\nThe following code prints out some statistics about the paper-author relationships.\n\n\n\n\n```python\nprint(type(data['PvsA']))\nprint('#Papers:', data['PvsA'].shape[0])\nprint('#Authors:', data['PvsA'].shape[1])\nprint('#Links:', data['PvsA'].nnz)\n```\n\n    <class 'scipy.sparse.csc.csc_matrix'>\n    #Papers: 12499\n    #Authors: 17431\n    #Links: 37055\n\n\nConverting this SciPy matrix to a heterograph in DGL is straightforward.\n\n\n\n\n```python\npa_g = dgl.heterograph({('paper', 'written-by', 'author') : data['PvsA']})\n# equivalent (shorter) API for creating heterograph with two node types:\npa_g = dgl.bipartite(data['PvsA'], 'paper', 'written-by', 'author')\n```\n\nYou can easily print out the type names and other structural information.\n\n\n\n\n```python\nprint('Node types:', pa_g.ntypes)\nprint('Edge types:', pa_g.etypes)\nprint('Canonical edge types:', pa_g.canonical_etypes)\n\n# Nodes and edges are assigned integer IDs starting from zero and each type has its own counting.\n# To distinguish the nodes and edges of different types, specify the type name as the argument.\nprint(pa_g.number_of_nodes('paper'))\n# Canonical edge type name can be shortened to only one edge type name if it is\n# uniquely distinguishable.\nprint(pa_g.number_of_edges(('paper', 'written-by', 'author')))\nprint(pa_g.number_of_edges('written-by'))\nprint(pa_g.successors(1, etype='written-by'))  # get the authors that write paper #1\n\n# Type name argument could be omitted whenever the behavior is unambiguous.\nprint(pa_g.number_of_edges())  # Only one edge type, the edge type argument could be omitted\n```\n\n    Node types: ['paper', 'author']\n    Edge types: ['written-by']\n    Canonical edge types: [('paper', 'written-by', 'author')]\n    12499\n    37055\n    37055\n    tensor([3532, 6421, 8516, 8560])\n    37055\n\n\nA homogeneous graph is just a special case of a heterograph with only one type\nof node and edge. In this case, all the APIs are exactly the same as in\n:class:`DGLGraph`.\n\n\n\n\n```python\n# Paper-citing-paper graph is a homogeneous graph\npp_g = dgl.heterograph({('paper', 'citing', 'paper') : data['PvsP']})\n# equivalent (shorter) API for creating homogeneous graph\npp_g = dgl.graph(data['PvsP'], 'paper', 'cite')\n\n# All the ntype and etype arguments could be omitted because the behavior is unambiguous.\nprint(pp_g.number_of_nodes())\nprint(pp_g.number_of_edges())\nprint(pp_g.successors(3))\n```\n\n    12499\n    30789\n    tensor([1361, 2624, 8670, 9845])\n\n\nCreate a subset of the ACM graph using the paper-author, paper-paper, \nand paper-subject relationships.  Meanwhile, also add the reverse\nrelationship to prepare for the later sections.\n\n\n\n\n```python\nG = dgl.heterograph({\n        ('paper', 'written-by', 'author') : data['PvsA'],\n        ('author', 'writing', 'paper') : data['PvsA'].transpose(),\n        ('paper', 'citing', 'paper') : data['PvsP'],\n        ('paper', 'cited', 'paper') : data['PvsP'].transpose(),\n        ('paper', 'is-about', 'subject') : data['PvsL'],\n        ('subject', 'has', 'paper') : data['PvsL'].transpose(),\n    })\n\nprint(G)\n```\n\n    Graph(num_nodes={'author': 17431, 'paper': 12499, 'subject': 73},\n          num_edges={('paper', 'written-by', 'author'): 37055, ('author', 'writing', 'paper'): 37055, ('paper', 'citing', 'paper'): 30789, ('paper', 'cited', 'paper'): 30789, ('paper', 'is-about', 'subject'): 12499, ('subject', 'has', 'paper'): 12499},\n          metagraph=[('author', 'paper'), ('paper', 'author'), ('paper', 'paper'), ('paper', 'paper'), ('paper', 'subject'), ('subject', 'paper')])\n\n\n**Metagraph** (or network schema) is a useful summary of a heterograph.\nServing as a template for a heterograph, it tells how many types of objects\nexist in the network and where the possible links exist.\n\nDGL provides easy access to the metagraph, which could be visualized using\nexternal tools.\n\n\n\n\n```python\n# Draw the metagraph using graphviz.\nimport pygraphviz as pgv\ndef plot_graph(nxg):\n    ag = pgv.AGraph(strict=False, directed=True)\n    for u, v, k in nxg.edges(keys=True):\n        ag.add_edge(u, v, label=k)\n    ag.layout('dot')\n    ag.draw('graph.png')\n\nplot_graph(G.metagraph)\n```\n\nLearning tasks associated with heterographs\n-------------------------------------------\nSome of the typical learning tasks that involve heterographs include:\n\n* *Node classification and regression* to predict the class of each node or\n  estimate a value associated with it.\n\n* *Link prediction* to predict if there is an edge of a certain\n  type between a pair of nodes, or predict which other nodes a particular\n  node is connected with (and optionally the edge types of such connections).\n\n* *Graph classification/regression* to assign an entire\n  heterograph into one of the target classes or to estimate a numerical\n  value associated with it.\n\nIn this tutorial, we designed a simple example for the first task.\n\nA semi-supervised node classification example\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nOur goal is to predict the publishing conference of a paper using the ACM\nacademic graph we just created. To further simplify the task, we only focus\non papers published in three conferences: *KDD*, *ICML*, and *VLDB*. All\nthe other papers are not labeled, making it a semi-supervised setting.\n\nThe following code extracts those papers from the raw dataset and prepares \nthe training, validation, testing split.\n\n\n\n\n```python\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\npvc = data['PvsC'].tocsr()\n# find all papers published in KDD, ICML, VLDB\nc_selected = [0, 11, 13]  # KDD, ICML, VLDB\np_selected = pvc[:, c_selected].tocoo()\n# generate labels\nlabels = pvc.indices\nlabels[labels == 11] = 1\nlabels[labels == 13] = 2\nlabels = torch.tensor(labels).long()\n\n# generate train/val/test split\npid = p_selected.row\nshuffle = np.random.permutation(pid)\ntrain_idx = torch.tensor(shuffle[0:800]).long()\nval_idx = torch.tensor(shuffle[800:900]).long()\ntest_idx = torch.tensor(shuffle[900:]).long()\n```\n\nRelational-GCN on heterograph\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nWe use `Relational-GCN <https://arxiv.org/abs/1703.06103>`_ to learn the\nrepresentation of nodes in the graph. Its message-passing equation is as\nfollows:\n\n\\begin{align}h_i^{(l+1)} = \\sigma\\left(\\sum_{r\\in \\mathcal{R}}\n   \\sum_{j\\in\\mathcal{N}_r(i)}W_r^{(l)}h_j^{(l)}\\right)\\end{align}\n\nBreaking down the equation, you see that there are two parts in the\ncomputation.\n\n(i) Message computation and aggregation within each relation $r$\n\n(ii) Reduction that merges the results from multiple relationships\n\nFollowing this intuition, perform message passing on a heterograph in\ntwo steps.\n\n(i) Per-edge-type message passing\n\n(ii) Type wise reduction\n\n\n\n\n```python\nimport dgl.function as fn\n\nclass HeteroRGCNLayer(nn.Module):\n    def __init__(self, in_size, out_size, etypes):\n        super(HeteroRGCNLayer, self).__init__()\n        # W_r for each relation\n        self.weight = nn.ModuleDict({\n                name : nn.Linear(in_size, out_size) for name in etypes\n            })\n\n    def forward(self, G, feat_dict):\n        # The input is a dictionary of node features for each type\n        funcs = {}\n        for srctype, etype, dsttype in G.canonical_etypes:\n            # Compute W_r * h\n            Wh = self.weight[etype](feat_dict[srctype])\n            # Save it in graph for message passing\n            G.nodes[srctype].data['Wh_%s' % etype] = Wh\n            # Specify per-relation message passing functions: (message_func, reduce_func).\n            # Note that the results are saved to the same destination feature 'h', which\n            # hints the type wise reducer for aggregation.\n            funcs[etype] = (fn.copy_u('Wh_%s' % etype, 'm'), fn.mean('m', 'h'))\n        # Trigger message passing of multiple types.\n        # The first argument is the message passing functions for each relation.\n        # The second one is the type wise reducer, could be \"sum\", \"max\",\n        # \"min\", \"mean\", \"stack\"\n        G.multi_update_all(funcs, 'sum')\n        # return the updated node feature dictionary\n        return {ntype : G.nodes[ntype].data['h'] for ntype in G.ntypes}\n```\n\nCreate a simple GNN by stacking two ``HeteroRGCNLayer``. Since the\nnodes do not have input features, make their embeddings trainable.\n\n\n\n\n```python\nclass HeteroRGCN(nn.Module):\n    def __init__(self, G, in_size, hidden_size, out_size):\n        super(HeteroRGCN, self).__init__()\n        # Use trainable node embeddings as featureless inputs.\n        embed_dict = {ntype : nn.Parameter(torch.Tensor(G.number_of_nodes(ntype), in_size))\n                      for ntype in G.ntypes}\n        for key, embed in embed_dict.items():\n            nn.init.xavier_uniform_(embed)\n        self.embed = nn.ParameterDict(embed_dict)\n        # create layers\n        self.layer1 = HeteroRGCNLayer(in_size, hidden_size, G.etypes)\n        self.layer2 = HeteroRGCNLayer(hidden_size, out_size, G.etypes)\n\n    def forward(self, G):\n        h_dict = self.layer1(G, self.embed)\n        h_dict = {k : F.leaky_relu(h) for k, h in h_dict.items()}\n        h_dict = self.layer2(G, h_dict)\n        # get paper logits\n        return h_dict['paper']\n```\n\nTrain and evaluate\n~~~~~~~~~~~~~~~~~~\nTrain and evaluate this network.\n\n\n\n\n```python\n# Create the model. The output has three logits for three classes.\nmodel = HeteroRGCN(G, 10, 10, 3)\n\nopt = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)\n\nbest_val_acc = 0\nbest_test_acc = 0\n\nfor epoch in range(100):\n    logits = model(G)\n    # The loss is computed only for labeled nodes.\n    loss = F.cross_entropy(logits[train_idx], labels[train_idx])\n\n    pred = logits.argmax(1)\n    train_acc = (pred[train_idx] == labels[train_idx]).float().mean()\n    val_acc = (pred[val_idx] == labels[val_idx]).float().mean()\n    test_acc = (pred[test_idx] == labels[test_idx]).float().mean()\n\n    if best_val_acc < val_acc:\n        best_val_acc = val_acc\n        best_test_acc = test_acc\n\n    opt.zero_grad()\n    loss.backward()\n    opt.step()\n\n    if epoch % 5 == 0:\n        print('Loss %.4f, Train Acc %.4f, Val Acc %.4f (Best %.4f), Test Acc %.4f (Best %.4f)' % (\n            loss.item(),\n            train_acc.item(),\n            val_acc.item(),\n            best_val_acc.item(),\n            test_acc.item(),\n            best_test_acc.item(),\n        ))\n```\n\n    Loss 1.1451, Train Acc 0.2837, Val Acc 0.2500 (Best 0.2500), Test Acc 0.2722 (Best 0.2722)\n    Loss 0.9611, Train Acc 0.4688, Val Acc 0.4800 (Best 0.5800), Test Acc 0.4422 (Best 0.5075)\n    Loss 0.8338, Train Acc 0.5450, Val Acc 0.5700 (Best 0.5800), Test Acc 0.5235 (Best 0.5075)\n    Loss 0.6427, Train Acc 0.8612, Val Acc 0.7600 (Best 0.7600), Test Acc 0.6993 (Best 0.6993)\n    Loss 0.4366, Train Acc 0.9600, Val Acc 0.7900 (Best 0.8100), Test Acc 0.7848 (Best 0.7504)\n    Loss 0.2720, Train Acc 0.9663, Val Acc 0.8100 (Best 0.8200), Test Acc 0.7797 (Best 0.7806)\n    Loss 0.1729, Train Acc 0.9675, Val Acc 0.8000 (Best 0.8200), Test Acc 0.7873 (Best 0.7806)\n    Loss 0.1191, Train Acc 0.9725, Val Acc 0.8300 (Best 0.8300), Test Acc 0.7822 (Best 0.7822)\n    Loss 0.0893, Train Acc 0.9825, Val Acc 0.8300 (Best 0.8300), Test Acc 0.7848 (Best 0.7822)\n    Loss 0.0697, Train Acc 0.9950, Val Acc 0.8400 (Best 0.8400), Test Acc 0.7873 (Best 0.7856)\n    Loss 0.0556, Train Acc 1.0000, Val Acc 0.8400 (Best 0.8400), Test Acc 0.7906 (Best 0.7856)\n    Loss 0.0451, Train Acc 1.0000, Val Acc 0.8500 (Best 0.8500), Test Acc 0.7982 (Best 0.7940)\n    Loss 0.0377, Train Acc 1.0000, Val Acc 0.8500 (Best 0.8500), Test Acc 0.7990 (Best 0.7940)\n    Loss 0.0323, Train Acc 1.0000, Val Acc 0.8500 (Best 0.8500), Test Acc 0.7956 (Best 0.7940)\n    Loss 0.0282, Train Acc 1.0000, Val Acc 0.8600 (Best 0.8600), Test Acc 0.7965 (Best 0.7965)\n    Loss 0.0251, Train Acc 1.0000, Val Acc 0.8700 (Best 0.8700), Test Acc 0.7973 (Best 0.7982)\n    Loss 0.0228, Train Acc 1.0000, Val Acc 0.8500 (Best 0.8700), Test Acc 0.8015 (Best 0.7982)\n    Loss 0.0209, Train Acc 1.0000, Val Acc 0.8500 (Best 0.8700), Test Acc 0.7956 (Best 0.7982)\n    Loss 0.0193, Train Acc 1.0000, Val Acc 0.8600 (Best 0.8700), Test Acc 0.7965 (Best 0.7982)\n    Loss 0.0180, Train Acc 1.0000, Val Acc 0.8700 (Best 0.8700), Test Acc 0.7931 (Best 0.7982)\n\n\nWhat's next?\n------------\n* Check out our full implementation in PyTorch\n  `here <https://github.com/dmlc/dgl/tree/master/examples/pytorch/rgcn-hetero>`_.\n\n* We also provide the following model examples:\n\n  * `Graph Convolutional Matrix Completion <https://arxiv.org/abs/1706.02263>_`,\n    which we implement in MXNet\n    `here <https://github.com/dmlc/dgl/tree/v0.4.0/examples/mxnet/gcmc>`_.\n\n  * `Heterogeneous Graph Attention Network <https://arxiv.org/abs/1903.07293>`_\n    requires transforming a heterograph into a homogeneous graph according to\n    a given metapath (i.e. a path template consisting of edge types).  We\n    provide :func:`dgl.transform.metapath_reachable_graph` to do this.  See full\n    implementation\n    `here <https://github.com/dmlc/dgl/tree/master/examples/pytorch/han>`_.\n\n  * `Metapath2vec <https://dl.acm.org/citation.cfm?id=3098036>`_ requires\n    generating random walk paths according to a given metapath.  Please\n    refer to the full metapath2vec implementation\n    `here <https://github.com/dmlc/dgl/tree/master/examples/pytorch/metapath2vec>`_.\n\n* :doc:`Full heterograph API reference <../../api/python/heterograph>`.\n\n\n", "meta": {"hexsha": "34e05272a9332ec0ee94488dd73ee7586778f3e1", "size": 25656, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "data/ACM/5_hetero.ipynb", "max_stars_repo_name": "RManLuo/CP-GNN", "max_stars_repo_head_hexsha": "a186d31167c1b00408de767b78271c5027882e23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2021-09-02T02:56:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T23:37:43.000Z", "max_issues_repo_path": "data/ACM/5_hetero.ipynb", "max_issues_repo_name": "RManLuo/CP-GNN", "max_issues_repo_head_hexsha": "a186d31167c1b00408de767b78271c5027882e23", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data/ACM/5_hetero.ipynb", "max_forks_repo_name": "RManLuo/CP-GNN", "max_forks_repo_head_hexsha": "a186d31167c1b00408de767b78271c5027882e23", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-02T13:57:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T22:37:15.000Z", "avg_line_length": 51.0059642147, "max_line_length": 1461, "alphanum_fraction": 0.6158793265, "converted": true, "num_tokens": 5592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091278688527247, "lm_q2_score": 0.1311732288565291, "lm_q1q2_score": 0.03291304041713136}}
{"text": "\n\n# Jupyter Test Drive - Typesetting with Markdown\n\nThis notebook demonstrates the use of Markdown to type set documents in Jupyter. After working through this notebook, you will be able to edit the text in any notebook.  In addition, you will be able to assist your students in editing the text of their own notebooks. \n\n## The _very_ Basics\n\nNote that you can view the source code behind any cell by double clicking it. To re-render or re-run the cell, use any of these options:\n1. Select `Cell` $\\rightarrow$ `Run Cells`\n2. Hit `Shift-Enter` \n3. Click the `Run` button above\n\n## Creating and Deleting Markdown Cells\nThe first step you may want to do is to create a new cell for typesetting. To do that, while you have this cell selected, from the top menu click the plus (+) sign next to the save button.\n\nOnce you have created the new cell, you will get a blank `Code` cell above. To change that cell into one that you can use for typesetting, select the cell, and from the dropdown menu at the top, change `Code` $\\rightarrow$ `Markdown`. This changes that cell type into a markdown cell, and it can now be used for typesetting!\n\n\nThe next step will be learning how to delete cells. Select the cell above that you converted to a markdown cell. To remove this cell from your Jupyter notebook  click `Edit` $\\rightarrow$ `Delete Cells`. If you accidentally deleted an incorrect cell, you can always bring it back by clicking `Edit` $\\rightarrow$ `Undo Delete Cells`.\n\n## Creating Titles\n\nCreating large bold title text in a Jupyter notebook with markdown is very simple! All you need to do is on a new line, type the pound sign and then a space. After the space, add your title. It's that simple. By adding extra pound signs, you will create different title levels. The cell below is unformatted markdown text demonstrating this.\n# I am a level one title\n## I am a level two title\n### I am a level three title\n#### I am a level four title\n##### I am a level five title\n###### I am a level six title \n####### I would be a level seven title if such a thing existed\n\nIf  # isn't the first character, that line does not get rendered as a title. \nTo see how those titles look when they're rendered in the Jupyter notebook, select the cell above, and from the top menu select `Raw NBConvert` $\\rightarrow$ `Markdown` (to change the cell from a raw type to a Markdown type), then press `Ctrl + Enter` to render the cell. Feel free to create a new cell and play with those, or change  the one above. \n\n## Creating Itemized Lists\nCreating lists in markdown in a Jupyter notebook is also straight forward! To do so you simply need to start a new line and begin counting. The markdown syntax is shown in the code below. \n\n#### Double Click Me\n\n1. This is the first item of a list\n1. This is the second\n50. Notice how the numbers we use don't matter once it's rendered\n    1. By pressing the `Tab` key we can add sub items\n    45. The numbers don't matter here either\n        - We can add many sub-lists\n            - But at some point it starts to get redundant\n        - We can also go back a few levels of nesting by lining the text up with the line above\n2346. By going back to the original line, we leave our nested lists\n23236235672456. The numbers really don't matter.\n* In fact, you can give up on numbers at any time.\n1. Or start counting again\n    \n\n- We also don't need to have numbers if we don't want to!\n    * We have plenty of options\n-Notice how if we don't put a space between the dash and the first term it doesn't become a new item in the list!\n\n\n\n---\n### Exercise 1\n1. In the cell above, try fixing the last line so that the last item in the list becomes properly formatted once it's rendered. \n2. Create a new cell below, add a title, and an ordered list of your five favourite fruits.\n---\n\n## Links\nYou can add hyper links to webpages anywhere you'd like right in the text. The syntax is as follows\n```markdown\n[text you want to display](link to a file or url page)\n```\nChange the cell below to markdown, run it, and see where the link takes you!\n[this is the text that becomes the hyperlink](https://media.giphy.com/media/Vs44a88Dvbnkk/giphy.gif)\n## Images/gifs\nImages and gifs can be emebedded in a markdown cell nearly identically to placing a hyperlink. To display the image, add an exclamation point to the command as demonstrated below. \n```markdown\n\n```\nwould display an image/gif. It can either be a url link to an image, or one you have saved on the hub/locally. Change the cell below to markdown and run it to see it in action, or even embed your own images in this notebook. \n\n---\n### Exercise 2\n1. In a new cell below, embed an image of a cat. \n2. In the same cell, add a hyperlink below the image that links to the original image.\n3. Change the text displayed in the hyperlink to say \"Kitty Kitty\".\n---\n\n# Block Quotes\nBlock quotes are a way to indent text/images with a grey bar in order to distinguish them from the main text. It is quite simlly done by adding a `>` at the beginning of a line. Change the cell below to markdown to see some examples\n> This is an example of a block quote. You can type as long as you like and all the resulting text will be to the right of a the vertical grey bar. \n\nYou can also use block quotes to easily format images with captions! \n\n> \n>\n> Now we can include a caption for images. This is nice because the image is now distinguishable from the main text. This makes it easy to include images without interrupting any narrative you've created. Notice how I have included a blank `>` under the image. That is so the spacing of this text looks nice underneath. Try removing it and see what happens\n## Tables\n\nOne can also create tables of data in Markdown. However, doing this manually is often not the most convenient. For large tables we recommend using online tools (such as [here](https://jakebathman.github.io/Markdown-Table-Generator/)) where you can copy-paste excel tables or csv files. This will then output syntax to properly render those tables. For smaller tables, it's quite easy to type out your own. See the cell below.\n| This is the first column name| Second Column| Third|\n|---|---|-------------|\n|Notice how nothing is lined up when we type it | But that it looks nice when rendered| how convenient!|\n|shorter lines are good too| numbers?| 343453|\n|symbols| `yes`| $\\int e^{-x^2} dx$ |\n|also notice that the number of dashes in the second line don't matter | it just needs to be at least three| the rest are really only for you to make pre-rendering look nice |\nThe basic table syntax is as follows:\n```markdown\n|initialize| your| column| names|\n|----------|-----|-------|------| <- this line sets up the headers, need at least three `---` each line\n|     data | data| data  | data | <- any kind of text data can be put in a table. Feel free to mix too!\n| numbers  | text| text  | data   <- you don't need to include the right-most pipe if you don't want to\n```\n\nThe syntax can be thought of as how you would try to write a table directly using symbols on your keyboard. Play with the table in the cell above, or create a new cell and try making your own! You could put one in this cell as well and put a table here. Double click anywhere on this cell to open edit mode.\n\n---\n### Exercise 3\n1. Using sample notebooks, teachers may like or dislike various sections of the sample provided. Luckily, it's easy to make these minor changes in notebooks. In the two cells below: \n    * remove the second cell because you won't need it in your lesson\n    * remove the last paragraph in the first cell \n    * change the date in the first paragraph\n2. In the first cell below, take the ordered list out of the block quote. \n\n---\n\n> ## Properties of Random Numbers\n> \n> May 22, 2018  \n> Suppose you have a sequence of $N$ random numbers $\\{R\\}$ with contents $\\{r_1, r_2, ... , r_N\\}$ where each element $r_i$ is a random number. What sort of properties should this sequence of numbers have? If this is truly a sequence of random numbers, it _must_ satisfy the following properties, which we will explain in greater detail: \n> \n> 1. Drawing any $r_i$ is equally probable and independent. \n> 2. The sequence of random numbers is uniformly distributed. \n> \n> \"Drawing a value\" in this scope means we're picking a number from our sequence of random numbers, but not removing it from the sequence (the sequence remains unchanged, we're simply \"observing\" the random number). \nLet's look at these two properties in a little more detail. \n\n\n> ### All Values Are Equally Probable and Independent\n> \n> What this means is that if you were to select (but not remove) a number from your sequence of random numbers $\\{r_1, r_2, ... , r_N\\}$ at random, the probability of drawing any of those numbers is\n\\begin{equation}\np(r_i) = \\frac{1}{N}\n\\end{equation}\nwhere $p(r_i)$ is the probability of selecting a number $r_i$. This probability is identical for all numbers within your set. More explicitly:\n\\begin{equation}\np(r_1) = p(r_2) = ... = p(r_N) = \\frac{1}{N}\n\\end{equation}\n> \n> The independence property means that the if you draw a number from the set, it does not affect the probability of drawing other numbers, or even itself at a later time. This is because the sequence remains unchanged after you draw (observe) a number.\n\n\n", "meta": {"hexsha": "f66e05d8ac1608e3fd860e1ae7119caa93d8c3b0", "size": 13261, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorials/JupyterTestdrive-MarkDown.ipynb", "max_stars_repo_name": "callysto/getting-started", "max_stars_repo_head_hexsha": "fc349e8bcd766cb20f7b8aef3e1abc3f37df23ec", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-21T16:50:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-21T16:50:22.000Z", "max_issues_repo_path": "tutorials/JupyterTestdrive-MarkDown.ipynb", "max_issues_repo_name": "Chloe-Zhouu/getting-started", "max_issues_repo_head_hexsha": "fc349e8bcd766cb20f7b8aef3e1abc3f37df23ec", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-12-05T00:57:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-05T01:04:10.000Z", "max_forks_repo_path": "tutorials/JupyterTestdrive-MarkDown.ipynb", "max_forks_repo_name": "Chloe-Zhouu/getting-started", "max_forks_repo_head_hexsha": "fc349e8bcd766cb20f7b8aef3e1abc3f37df23ec", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-09-04T07:10:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T22:24:30.000Z", "avg_line_length": 43.3366013072, "max_line_length": 431, "alphanum_fraction": 0.6339642561, "converted": true, "num_tokens": 2242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08882029481205687, "lm_q2_score": 0.37022539954425293, "lm_q1q2_score": 0.03288352913443209}}
{"text": "# \"Learning To Efficiently See In The Dark\"\n> \"This article describes the binarization of the network in the paper 'Learning to See in the Dark' [1] using the approach of the ABC-net presented in 'Towards Accurate Binary Convolutional Neural Network' [2]\"\n\n- toc: false\n- branch: master\n- badges: true\n- comments: true\n- categories: [fastpages, jupyter]\n- hide_github_badge: true\n\n\n### By Sieger Falkena, Anwesh Marwade and Joris Quist\n\n\nWith the ever growing amount of papers published, the field of Computer Vision by Deep Learning is more relevant than ever. Many new solutions are presented every day. Models get bigger and more complex. Together with computer vision, the market of smart-phone and smart-wearables is growing. Estimates have been made that in 2020, around 1.4 trillion photo's will be made worldwide from which 90.9% will originate from smartphones [4].\n\nHowever, the differences in computing power between the two sectors is enormous. Deep learning models require powerfull GPU's to train and evaluate a model. Smartphones don't offer this. To accomodate that the two sectors are growing towards each other, two paths are being followed: smartphones are equipped with more powerfull hardware every year making that smartphones can offer more services. On the other hand, deep learning models are made more and more efficient, so that evaluation can be done on a wearable device.\n\nIn this article, we want to take a step towards the direction of efficient neural networks. We will combine methods from different active fields of study and present an efficient method to process low-light images. We showcase the implementation details of applying the concept of network binarization using \"Accurate Binary Convolutional Network\" (ABC-Net) in \"Learning To See In The Dark\" (LSID) [1] paradigm. In doing so, we want to find out whether the full accuracy network can be approximated by binarization. We aim for limited performance loss as compared to the full precision model while driving up the efficiency. We intend to highlight the theoretical speedup that can be achieved and shed light on the limitations that we faced.\n\n**Click [https://sfalkena.github.io/blogs/_pages/interactive_image.html](https://sfalkena.github.io/blogs/_pages/interactive_image.html) or scan the QR code below to see an interactive comparison of the results in high resolution! Warning: the images are in high resolution, so the loading of images might be slow ;)**\n\n\n\n\n\n\n# Techniques used\n\nFirst, let us introduce the problem that we propose to tackle. This problem is presented by Chen et. al in \"Learning to see in the dark\" [1], where the authors take a raw image file (short-exposure images which are grainy and suffer from noise due to low-lighting and high ISO values) and use a deep neural network to learn the image-processing pipeline to process the low-light raw data. By working directly with raw sensor data, the authors intend to replace the standard imaging pipeline. Intending to achieve this, the authors train a convolutional network with a new dataset involving raw short-exposure low-light images with corresponding long-exposure images as the target reference or ground truth.\n\nThe pipeline suggested by the authors can be seen in the figure below. First, the raw image is unpacked, the black levels are subtracted after which the image is amplified. Finally, the image is fed through the CNN, and the output is an RGB image.\n\n \n\nFor examples of the results achieved by in the paper, look at https://cchen156.github.io/SID.html for an interactive comparison.\n\nTo make the ConvNet in the figure shown above more efficient, binarization is applied to the ConvNet. For this, we follow the fundamental techniques of binary convolution using XNOR and bitcount operations by Rastegari et al. in \"XNOR-Net\" [5]. In applying binarization, we explore two schemes for implementing a binary network namely, XNOR-Net and ABC-Net. In the following section, we first explain the XNOR-Net, after which we dive into the ABC-Net implementation in detail.\n\n\nFor the interested reader, we have written a chapter where we explain the basics of [Binary Networks](https://drive.google.com/file/d/1BnX25RuH6bDnD2rfNdJAfkTVJhA4irEl/view?usp=sharing) in more detail. For the rest of the paper, we assume that the reader has knowledge of this chapter and knows the fundamentals of binarization.\n\n\n\n\n\n## XNOR-Net\nThe first binarization technique that we explored is the XNOR-Net implementation presented in [5]. In XNOR-Networks, both the filters and the input to the convolutional layers are binarized which allows these networks to approximate the convolutions primarily using binary operations. The efficiency and speedup can be achieved by leveraging the XNOR and bit-counting operations to estimate the convolutions. \n\nWe replace the LSID layers with the binarized convolutions which are mentioned in detail in the ABC-Net section. Reading further into the implementation we realised that ABC-Net is a generalisation of the XNOR-Net. Being a generalisation, the ABC-net extends better representational power by approximating the convolutions using multiple binarized weights and activations, but still has the option to evaluate the performance of the XNOR-Net when using only a single bit for both weights and activations.\n\n\n\n## ABC-Net\n\nWe implemented this by using the follow-up work shown by Lin et al. [2] to achieve higher accuracy than XNOR-Net. Lin et al. developed a new type of convolutional network called the Accurate Binary Convolutional Network or ABC-Net. Explained very briefly, ABC-Net approximates the full precision convolution using $M\\cdot N$ binary convolutions from XNOR-Nets, where $M$ is the number of bits used to approximate the weights and $N$ the number of bits to approximate the activations.\n\nAgain, in our chapter, [ABC-Net](https://drive.google.com/file/d/1BnX25RuH6bDnD2rfNdJAfkTVJhA4irEl/view?usp=sharing) is explained in more detail. However, we intend to provide some intuition regarding the ABC-Net as mentioned below.\n\n\n\n\nThe ABC-Net approximates each real-valued by using multiple binary values per weight, giving it better representational power. The approximation is achieved as follows: \n\\begin{equation}\nW \\approx \\alpha_1\\mathbf{B}_1 + \\alpha_2\\mathbf{B}_2 + ... + \\alpha_M\\mathbf{B}_M\n\\end{equation}\n\nFinding a good value for $\\mathbf{B}_i$ and $\\alpha_i$ comes down to the following optimization problem:\n\n\\begin{equation}\n\\min\\limits_{\\mathbf{\\alpha}, \\mathbf{B}}J(\\mathbf{\\alpha}, \\mathbf{B}) = ||\\mathbf{w} - \\mathbf{B} \\mathbf{\\alpha}||^2,\\;\\;\\;\\; s.t.\\:\\mathbf{B}_{ij}\\in \\{-1,+1\\}\n\\end{equation}\n\nWhere $\\mathbf{B} = [vec(\\mathbf{B}_1), vec(\\mathbf{B}_2), ..., vec(\\mathbf{B}_M)]$, $\\mathbf{w} = vec(\\mathbf{W})$ and $\\mathbf{\\alpha} = [\\alpha_1, \\alpha_2, ..., \\alpha_M]^T$. Trying to find the optimum to this problem numerically, makes it quite difficult as it is no longer possible to compute the derivative w.r.t. $\\textbf{W}$ using the Straight-Through-Estimator [add reference]. Therefore the optimum is approximated by first calculating each $B_i$ in the following way:\n\n\\begin{equation}\n\\mathbf{B}_i = sign(\\overline{\\textbf{W}} + u_istd(\\mathbf{W})), i = 1,2,...,M \n\\end{equation}\n\nWhere $\\overline{\\textbf{W}} = \\textbf{W} - mean(\\textbf{W})$  and $u_i$ is picked evenly over the the range $[-std(\\mathbf{W}), std(\\mathbf{W})]$. This is done because experimental observations show that real-valued weights often look like they are drawn from a Gaussian distribution.\n\nImportantly, to be able to take full advantage of the more efficient XNOR and bitcount operations for the convolutions, the activations need to be binarized in addition to the network weights. The ABC-Net does this by using multiple bits per activation to get a better approximation of the original i.e. full precision activations. However, it is not desirable to use the same method for binarizing the activations as we do for the weights, because the alpha values (and the beta values for the activations) need to be calculated using linear regression. For the weights, this is not a big problem, since this only needs to happen when they need to be updated, which only happens during training. It thus has no impact on the inference speed. However, this is not the case for the activations since these always vary at test time.\n\nThe way they implemented this, was by first using batch normalization, so that the mean and standard deviation of the activation didn't need to be calculated, but could be assumed to be $0$ and $1$. They then replaced the linear regression that was used to calculate alpha by a learnable parameter beta. This way the there is no need anymore to do linear regression or calculate the mean and standard deviation during inference.\n\n## Theoretical speedup\nBefore we dive into the speedup that would theoretically be possible, we need to understand more about the factors that influence this speedup. The speedup is achieved by binarizing the weights and activations of the convolution. For binarizing the weights, the full precision weights are approximated with $\\boldsymbol{W} \\approx \\alpha_{1} \\boldsymbol{B}_{1}+\\alpha_{2} \\boldsymbol{B}_{2}+\\cdots+\\alpha_{M} \\boldsymbol{B}_{M}$. So $M$ BinConvs are used as can be seen on the left part of the figure above. Furthermore, the activations $R$ can also be binarized by approximating $\\boldsymbol{R} \\approx \\beta_{1} A_{1}+\\beta_{2} A_{2}+\\cdots+\\beta_{N}\\boldsymbol{A}_{N}$. \n\nAccording to [5] the speedup of using XNOR-Net is the ratio of the operations carried out by a normal convolution and the binarized XNOR convolution: $S=\\frac{64 c N_{W}}{c N_{W} + 64}$, where $N_{\\mathbf{W}}=w h$ (the number of entries in the weights) and $c$ is the number of channels. For justification of this equation, please refer to the original paper. The alert reader will notice that the speedup does not depend on the size of the input.\n\nBecause there are now $N\\times M$ of these BinConvs, the speedup per convolutional layer linearly decreases with this number and becomes $S=\\frac{64 c N_{W}}{M N (c N_{W} + 64)}$. To draw conclusions about the total speedup of the network, we have to look into the architecture and take the sum of all operations done over all layers when not using BinConvs and dividing this by the amount operations that are needed when BinConvs are being used. This will then give the theoretical speedup of the entire network. In the results section, this number will be shown for all the different networks used in the experiments.\n\nEven when not binarizing the activations, still some speedup could be achieved. This is because when using binary weights there is no need to do multiplication and addition of the activation with weight anymore, it can be immediately added or subtracted. The speedup of this can be roughly estimated to be 2, since only half of the operations need to be done (ignoring overhead like adding the bias). The speedup is then given by $S \\approx \\frac{2}{M N}$, since again the speedup linearly decreases with the amount of times the BinConv is used. Note here that when using a value larger than $1$ for either $M$ or $N$, all speedup is immediately lost. However, there is at that point still the possibility of reduced memory usage.\n\n# Technical constraints\n\nIn the introduction, as an alert reader must have noticed, we stress that we are aiming for limiting the performance loss rather than only aiming for increase in efficiency. The reason for this is the fact that binarization is still a fairly new field of study. To convert the theoretical speedup of the network into practice, special hardware or software needs to be used. The speedup is realized by using XNOR and bitcount operations [1]. Intel researchers in [6]  have compared running a binarized network on different architectures, and they have pointed out that specialised hardware like FPGAs have a greater potential for running binarized networks. For now, the platform that we use i.e. PyTorch does not offer possibilities to achieve and leverage this practical speedup to which end we feel that it is currently out of the scope of this project.\n\n# Implementation of the code\nIn this section, certain relevant parts of the code will be highlighted.\n\n\n##Architecture\nBelow, the architecture of the binarized LTSITD (ABCLSID) is shown. Some remarks about the architecture:\n- The first and last layer are not binarized and uses normal convolution. The speedup of binarizing is smaller here because of the low amount of channels or small kernel size. \n- Rest of the architectural decisions (channels, kernel size, etc.) are kept the same i.e. as per the original LTSITD implementation. The layer order from LTSITD adhered according to the layer order recommended by [5].\n\n\n\n```python\nclass ABCLSID(nn.Module):\n    def __init__(self, inchannel=4, block_size=2, M=3, N=None, binary_transposed_conv=True):\n        super(ABCLSID, self).__init__()\n        self.M = M\n        self.N = N\n        self.binary_transposed_conv = binary_transposed_conv\n\n        self.block_size = block_size\n\n        self.conv1_1 = nn.Conv2d(inchannel, 32, kernel_size=3, stride=1, padding=1, bias=True, )\n        self.lrelu =  nn.LeakyReLU(negative_slope=0.2, inplace=True)\n        self.conv1_2 = ABCConv2d(32, 32, kernel_size=3, stride=1, padding=1, bias=True, M=M)\n        self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0, ceil_mode=True)\n\n        self.conv2_1 = ABCConv2d(32, 64, kernel_size=3, stride=1, padding=1, bias=True, M=M)\n        self.conv2_2 = ABCConv2d(64, 64, kernel_size=3, stride=1, padding=1, bias=True, M=M)\n\n        self.conv3_1 = ABCConv2d(64, 128, kernel_size=3, stride=1, padding=1, bias=True, M=M)\n        self.conv3_2 = ABCConv2d(128, 128, kernel_size=3, stride=1, padding=1, bias=True, M=M)\n\n        self.conv4_1 = ABCConv2d(128, 256, kernel_size=3, stride=1, padding=1, bias=True, M=M)\n        self.conv4_2 = ABCConv2d(256, 256, kernel_size=3, stride=1, padding=1, bias=True, M=M)\n\n        self.conv5_1 = ABCConv2d(256, 512, kernel_size=3, stride=1, padding=1, bias=True, M=M)\n        self.conv5_2 = ABCConv2d(512, 512, kernel_size=3, stride=1, padding=1, bias=True, M=M)\n\n        if self.binary_transposed_conv:\n            self.up6 = ABCConvTranspose2d(512, 256, 2, stride=2, bias=False, M=M)\n        else:\n            self.up6 = nn.ConvTranspose2d(512, 256, 2, stride=2, bias=False)\n\n        self.conv6_1 = ABCConv2d(512, 256, kernel_size=3, stride=1, padding=1, bias=True, M=M)\n        self.conv6_2 = ABCConv2d(256, 256, kernel_size=3, stride=1, padding=1, bias=True, M=M)\n\n        if self.binary_transposed_conv:\n            self.up7 = ABCConvTranspose2d(256, 128, 2, stride=2, bias=False, M=M)\n        else:\n            self.up7 = nn.ConvTranspose2d(256, 128, 2, stride=2, bias=False)\n\n        self.conv7_1 = ABCConv2d(256, 128, kernel_size=3, stride=1, padding=1, bias=True, M=M)\n        self.conv7_2 = ABCConv2d(128, 128, kernel_size=3, stride=1, padding=1, bias=True, M=M)\n\n        if self.binary_transposed_conv:\n            self.up8 = ABCConvTranspose2d(128, 64, 2, stride=2, bias=False, M=M)\n        else:\n            self.up8 = nn.ConvTranspose2d(128, 64, 2, stride=2, bias=False)\n\n        self.conv8_1 = ABCConv2d(128, 64, kernel_size=3, stride=1, padding=1, bias=True, M=M)\n        self.conv8_2 = ABCConv2d(64, 64, kernel_size=3, stride=1, padding=1, bias=True, M=M)\n\n        if self.binary_transposed_conv:\n            self.up9 = ABCConvTranspose2d(64, 32, 2, stride=2, bias=False, M=M)\n        else:\n            self.up9 = nn.ConvTranspose2d(64, 32, 2, stride=2, bias=False)\n\n        self.conv9_1 = ABCConv2d(64, 32, kernel_size=3, stride=1, padding=1, bias=True, M=M)\n        self.conv9_2 = ABCConv2d(32, 32, kernel_size=3, stride=1, padding=1, bias=True, M=M)\n\n        out_channel = 3 * self.block_size * self.block_size\n        self.conv10 = nn.Conv2d(32, out_channel, kernel_size=1, stride=1, padding=0, bias=True)\n\n        for m in self.modules():\n            if isinstance(m, nn.Conv2d):\n                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n                m.weight.data.normal_(0, math.sqrt(2. / n))\n                m.bias.data.zero_()\n            elif isinstance(m, nn.ConvTranspose2d):\n                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n                m.weight.data.normal_(0, math.sqrt(2. / n))\n```\n\n##Datasets and data processing\nIn the section \"Techniques used\", we already mentioned briefly that the authors of [1] created a new dataset to train and evaluate the model. In this section, we want to explain a bit more about the importance of the dataset.\n\nLet's start with explaining what kind of data we are we dealing with. The authors have created a dataset with low-light images. The original dataset has been shot with two cameras: A Sony $\\alpha$7S II and a Fujifilm X-T2. The reason behind using two different cameras has to do with the different ways in which the images get stored. The Sony uses a Bayer filter, whereas the Fujifilm uses an X-Trans filter. We leave the exploration of the X-Trans filter to the reader as we have chosen to focus solely on the Sony camera for this project endeavour. The reason for this is that Sony is the leading company in the smartphone camera domain and holds [50.1%](https://www.bloomberg.com/news/articles/2019-12-23/sony-can-t-make-image-sensors-fast-enough-to-keep-up-with-demand) of the market share as of 2019. As mentioned above, the Sony images use a Bayer filter. We would suggest reading [this blog](https://www.cambridgeincolour.com/tutorials/camera-sensors.htm) to develop a better understanding about Bayer filters. The first image of our blog shows the input image being in its Bayer form. The de-mosaicing step in the aforementioned blog is included in the ConvNet pipeline.\n\nSo, going back to the dataset, it contains groups of images shot in exactly the same way, but with different exposure times, meaning that we have bright, ground truth images, together with dark, low-exposure images. To test the rigidity of the network, images with exposure times of $0.033s, 0.04s, 0.1s$ have been captured.\n\nThe said raw images are of size 4256x2848. However, these images are still in the Bayer form, which means that they need to be unpacked into 2128x1424 sized images with 4 colour channels. Additionally, these images are considerably big to be loaded into memory as a whole. This memory contraint meant that it was not possible to perform backpropagation with the entire image as input, because then our GPU would run out of memory (8 GiB). This, and the fact that the authors of LSID also train using patches, is why we train the network on patches of the images. The patch size used is 512x512 pixels.\n\nAnother problem was that, the training was very slow. At first it would have taken around 6 days to train the network. The reason for this was the way the images were loaded and processed. The way it was done, was that in each iteration, an image was loaded from the disk, processing was done (by the python rawpy module) and then a random patch was taken from that image. The bottleneck at that point was the loading of the images from disk to memory. Even with 8 data loading workers that simultaneously loaded images, it wasn't enough. Furthermore, using more workers caused overheads in other places and hence did not improve performance. The way the authors overcame this problem was by keeping all the data in memory. The problem for us, however, was that the dataset was 64 Gigabytes and we only had 16 Gigabytes of RAM storage. The way we fixed this issue was by preprocessing the data. We first loaded the images, did the processing, but then instead of taking a random patch, we took 15 patches in a grid of 3 by 5. This was the smallest number of patches that together (with a bit of overlap) covered the entire image. We then stored these patches. By performaing the mentioned steps, during training, we could directly load the patch instead of the entire image. This improved our training speed significantly, which meant that we could train the network in just 22 hours which was quite a considerable reduction in time.\nThis method does have some disadvantages, because this way we always use the same set of patches instead of random ones, which could, in theory, affect the result after training. However we still achieve highly comparable results on the test set as the original model. This led us to conclude that it probably did not matter much.\nAnother problem that we dealt with was that the raw images had an 14-bit encoding, which after processing gets converted to 32-bit tensors. Plus, the patches were slightly overlapping. Together this caused our newly processed training set to be 353GB, which is not very practical to store.\nIn the end our epochs were changed from taking a random patch of the 1865 images, to using $15\\cdot1865=27975$ fixed patches.\n\n## Binary convolution\nOne problem we encountered during the project was because we did not have access to efficient implementations of the binary convolutions implying that we had to use the standard convolutions for 32-bit Floating-point numbers. This meant that instead of a getting a speedup as mentioned in Section \"Theoretical speedup\", it took about $M\\cdot N$ times longer to do a forward pass, since that is the amount of convolutions we now had to do in each layer. This would mean that training would again take too long. To remedy this, we slightly deviated from the procedure that is described in the ABC-Net paper. We still calculated the binary tensors and their multipliers in the same way, but instead of using them in separate convolutions, we used them to approximate the original weights again. In theory this should give the same results. In practice, both these methods had small differences in their outputs. This is probably due to floating-point errors. These errors, however, were minute enough to not impact a real difference during training or in performance. In the code snippet below, we first have two functions implementing the shift operation as in equation 2 from [2].\n\n\n```python\nimport torch.nn as nn\nfrom torch import Tensor\nimport torch\n\n\ndef shift_parameter_binarization(tensor, shift_parameters, empty_cache):\n    if empty_cache:\n        torch.cuda.empty_cache()\n\n    return torch.cat(\n        [((tensor - tensor.mean()) + shift_parameter).sign() for shift_parameter in shift_parameters])\n\n\ndef shift_parameter_binarization_activation(tensor, shift_parameters, empty_cache):\n    if empty_cache:\n        torch.cuda.empty_cache()\n\n    return torch.cat(\n        [((tensor - tensor.mean()) + shift_parameter).sign() for shift_parameter in shift_parameters])\n\n```\n\n### Binary 2D convolution\n\n\n```python\nclass ABCConv2d(nn.Conv2d):\n\n    def __init__(self, in_channels, out_channels, kernel_size, M=3, N=None, estimated_weights=True, stride=1,\n                 padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros'):\n\n        super(ABCConv2d, self).__init__(in_channels, out_channels, kernel_size, stride=stride,\n                                        padding=padding, dilation=dilation, groups=groups,\n                                        bias=bias, padding_mode=padding_mode)\n\n        self.M = M\n        self.N = N\n\n        self.use_estimated_tensors = estimated_weights\n\n    # Calculates the alphas based on the binarized and real weights using linear regression\n    def get_alphas(self, B):\n        vectorized_B = B.view(self.M, -1).t()\n\n        return vectorized_B.t().mm(vectorized_B).inverse().mm(vectorized_B.t()).mv(self.weight.data.view(-1))\n\n    # Binarize the weights in M matrices\n    def get_B(self):\n        weights = self.weight.data\n\n        return shift_parameter_binarization(weights, [(-1 + i * 2 / (self.M - 1)) * weights.std() for i in\n                                                      range(self.M)], empty_cache=(not self.training))\n\n    # Binarize the weights in M matrices\n    def get_binary_activation(self, input):\n        binary_input = shift_parameter_binarization_activation(input,\n                                                               [(-1 + i * 2 / (self.N - 1)) * input.std() for i in\n                                                                range(self.N)],\n                                                               empty_cache=(not self.training))\n\n        vectorized_binary_input = binary_input.view(self.N, -1).t()\n        betas = vectorized_binary_input.t().mm(vectorized_binary_input).pinverse().mm(vectorized_binary_input.t()).mv(\n                input.view(-1))\n\n        estimated_binary_input = torch.mv(vectorized_binary_input, betas)\n        # del binary_input\n        return estimated_binary_input.view(input.shape)\n\n    def get_estimated_weights(self, B, alpha):\n        vectorized_B = B.view(self.M, -1).t()\n        estimated_weights = torch.mv(vectorized_B, alpha)\n        return estimated_weights.view(self.weight.shape)\n\n    def forward(self, x: Tensor) -> Tensor:\n        # if self.training or self.B is None or self.alpha is None:\n        B = self.get_B()\n        alphas = self.get_alphas(B)\n\n        if self.N:\n            x.data = self.get_binary_activation(x)\n\n        if self.use_estimated_tensors:\n            x = nn.functional.conv2d(x, self.get_estimated_weights(B, alphas), self.bias, self.stride,\n                                     self.padding, self.dilation, self.groups)\n\n        else:\n            x = sum(alphas[i] * nn.functional.conv2d(x, B[i],\n                                                     stride=self.stride,\n                                                     padding=self.padding,\n                                                     dilation=self.dilation,\n                                                     groups=self.groups) for i in range(self.M))\n            if self.bias:\n                x += self.bias[None, ..., None, None].repeat(1, 1, x.shape[2], x.shape[3])\n\n        return x\n```\n\n### Binary 2D transposed convolution\nFor the transposed convolution, we have not yet seen any implementation online, so we have estimated that it can be done in a similar way as the normal binary 2D convolution.\n\n## Initialization\n\nA very useful aspect of ABC-Net is the fact that it uses multiple bits to approximate the original real-valued weights. This means that if you have a trained model and you want to replace the normal convolutions with the approximated convolutions of ABC-Net, you can use the weights of the original model as the initialization of the new one. Some training is still needed to finetune the weights to the new architecture, but much less than with random initialization. Once we implemented this, we only trained each network for 1 epoch in our testing. This helped with testing and debugging the network, since when using binarization for each layer in the network the linear regression had to be performed every iteration. This made the training 2 to 12 times slower, depending on the number of bits used for the binarization. This would have meant that without this initialization some networks would have needed to train for 12 days, which wouldn't be feasible for this project.\n\n## Bias\nThe ABC-Net paper makes no mention of using biases in their convolutions. However as biases were used by the LSID network, we did need to implement this. Since biases only account for a small part of the memory used and the computation needed, we decided to not binarize the biases in the network.\n\n## Normalization\n\nAs mentioned in section \"ABC-Net\", one of the things that is needed to be able to binarize the activations is normalization. In ABC-Net this is done using batch normalization. However, this was not possible in our case since the GPU we used, did not have enough memory. When only binarizing the weights, batches of 8 could be used, which is already very small for batch normalization to work well. When we also binarized the activations even more memory was needed, since the binarized tensors still needed to be stored as 32-bit floats. This meant that we could only use a batch size of 1. Therefore we looked into 3 other types of normalization, namely, instance normalization, group normalization and layer normalization. Unfortunately, all of the normalization techniques hurt the performance of the model, with really low PSNR's even when not even binarizing the activations yet. We speculate that this might have to do with the fact that we use the weights of the trained LSID model as initialization. Adding normalization in can cause the activations to change significantly, which means that the weights also need to adapt.\n\n## Activation Binarization\nSince we couldn't get normalization to work and the binarization of the activations in ABC-Net depend on this, we needed to find a new way to do this. In the end we chose to do it the same way as with the binarization of the weights. By picking the thresholds for binarizing equally distributed from minus the standard deviation to plus the standard deviation around the mean of the activation. After which the betas are calculated using linear regression again. This cannot lead to good efficiency during inference as the linear regression still has to be done at each layer every iteration. We thought this is an acceptable compromise, since, without the efficient operators, we couldn't show the actual efficiency benefits in practice anyway and this should still give comparable results in terms of accuracy.\n\n## Training details\nTo improve the reproducibility of the project, we will provide some details about our training process. We use the weight of the model trained by the authors as initialization. Then we train the model for 1 epoch using the 27975 image patches of size 512 by 512. The learning rate we used was $10e-4$. We tested multiple different combinations of $M$, $N$ (real-valued, $1$, $3$ and $5$).\n\n# Results\nThe results are shown in the table below and the visual representation can be seen by running the following code cell. When a cell in the table contains a \"x\", that means the specific part has not been binarized and thus contains the full-precision values.\nJust as a reminder: $M$ are the amount of bits used for the weight approximation, $N$ is the amount of bits used for approximating the activations. The theoretical speedup has been calculated per setting as described earlier in this blog.\n\n|                               | M | N | PSNR  | Theoretical speedup | Memory Reduction       |\n|-------------------------------|---|---|-------|:-------------------:|:------:|\n| Results by [1], in TensorFlow | x | x | 28.88 | 1x                  | 1x     |\n| Results of [3], in PyTorch    | x | x | 28.55 | 1x                  | 1x     |\n| ABCLSID                       | 3 | x | 27.6  | 0.66x               | 10.67x |\n| ABCLSID                       | 1 | x | 25.70 | 2x                  | 32x    |\n| ABCLSID                       | 1 | 1 | 20.21 | 55.11x              | 32x    |\n| ABCLSID                       | 3 | 3 | 20.93 | 6.77x               | 10.67x |\n| ABCLSID                       | 5 | 3 | 21.19 | 4.08x               | 6.4x   |\n| ABCLSID                       | 3 | 5 | 21.74 | 4.08x               | 10.67x |\n| ABCLSID                       | 5 | 5 | 21.86 | 2.46x               | 6.4x   |\n\n\n\n\n\n```python\nfrom IPython.display import Image\nfrom google.colab import widgets\nfrom matplotlib import pylab\n\ntb = widgets.TabBar([\"M=1, N=x\"                         ,\"M=1, N=1\",                         \"M=3, N=x\"                         ,\"M=3, N=3\"                         ,\"M=5, N=3\"                         ,\"M=5, N=5\"])\nimage_ids =         [\"1XZuoIFNmI65Wuhnv4lEVDMP5YvVfy2fV\",\"1Ypb9LUoJt5V44qu9zHXobbNwoa4NOZcn\",\"1ihb4AvT8Jjj8g5N0zfLrss7-Bms0Vr5g\",\"1niA76Jwfp6cIdWmnv70omRFBtAaut1Ub\",\"1CK_rFLYvjPqkw2j4RIng8grU6ovAATWc\",\"1BN66SlR4UVNOn09txj-9RQKpC-aKtVPX\" ]\n\nfor t, i in enumerate(tb):\n    display(Image(url=\"https://docs.google.com/u/0/uc?id=\"+image_ids[i], width = 1000, height = 700))\n```\n\n# Discussion\nWhen looking at the results in the table and the images, you can see that the network still performs quite well when only the weights are binarized, the difference between $M = 3$ with real valued activations is almost indistinguishable from the original model (even when looking at the direct interactive comparison). Even using 1-bit $(M = 1)$ the results are still passable considering 32x less memory is needed. However, when we start to binarize the activations, the performance of the network starts to drop significantly. Even the network with real-valued activations and 1-bit weights performs much better than the network with 5-bit activations and 5-bit weights. We are not exactly sure about the reason for this. It could be that binarizing the activations simply causes too much loss of information for the network to function properly. For example in the images (refer to images with binary activations), you can see that a lot of the colour of the image is lost. Especially for $N=1$, there the image has almost become black and white.\n\nOne possible explanation for the loss in information might be that we noticed that for $M = N = 3$, the tensors of the estimated weights and activations only contained $4$ or $5$ unique values. Having a 3-bit accuracy, it should be possible to achieve 8 unique levels instead. When $M = N = 5$, it should be possible to output 32 different values, but instead, we found that the tensors only contained $5$ or $6$ unique values.\n\nOne explanation for this could be that the shifting of parameters to form $\\boldsymbol{B}$ is not done optimally. Right now the shifts, which set the thresholds for binarization, are uniformly distributed over a range from minus the standard deviation to plus the standard deviation, which is the way it was described in the ABC-Net paper. However, since the distribution of weights often resembles a Gaussian distribution, it might be better to put the thresholds around the mean closer together and the thresholds further from the mean further apart, to better match the Gaussian distribution.\nCurrently, in the interest of time for this project, we were unable to research further into this problem, but we expect that if more of the possible weights occur, that this will lead to a smaller approximation error, which in term helps with improving performance.\n\nWe deviated in one aspect from the original ABC-Net implementation, by implementing the binarization of the activations the same as for the weights. This was done because we could not get the ABCLSID network to work with normalization, which probably interfered with our initialization. Another technique that could be studied in the future that could make this work is taking the original LTSITD network and add normalization to it. This network could then be trained to match the performance of the original model. This new model could then be used to initialize the network when binarizing the activations and this means that when binarizing the activations the network does not also need to adapt to the normalization.\n\nThis also means that the network could use the learnable parameter beta, to possibly find better threshold values than the ones we used. This can make the approximations and thus also the performance of the network better.\n\nAnother reason for the loss in performance could be that there simply goes something wrong in our implementation of binarizing the activations. For example, it is possible that when binarizing the activations, the gradient is not calculated correctly anymore. This could cause the network to not properly learn and adapt to the new structure. We have seen, for instance, during some initial testing that the training and validation error would go up after the first epoch when training on a small subset of the training data.\n\nIt could also be that there is something wrong with the calculation of the backpropagation as described in ABC-Net. The definition in the paper, the one we use, uses the STE and is as follows:\n\n$$\\frac{\\delta c}{\\delta\\textbf{W}} = \\sum\\limits_{m=1}^M \\alpha_m \\frac{\\delta c}{\\delta \\textbf{B}_m}$$\n\n\nHowever, according to the author the following ABC-Net implementation cow8/ABC-Net-pytorch (https://github.com/cow8/ABC-Net-pytorch), this is not correct. They state that the correct formulation is:\n\n$$\\frac{\\delta c}{\\delta\\textbf{W}} = \\frac{\\delta c}{\\delta\\textbf{O}}\\cdot \\left(  \\sum\\limits_{m=1}^M \\left( \\frac{\\delta \\textbf{O}}{\\delta \\alpha_m Conv(B_m, A)} \\cdot \\left( \\frac{\\delta\\alpha_m}{\\delta W} \\cdot Conv(B_m, A) + \\frac{\\delta Conv(B_m, A)}{\\delta W} \\cdot \\alpha_m \\right) \\right) \\right) $$\n\nWe are not 100\\% that this is indeed the case, especially since it is not from a peer-reviewed paper, but from a public Github repository that contains an implementation that does not yet work. However, it might be interesting to explore this further in the future.\n\n\n\n\n# References\n[1] C. Chen, Q. Chen, J. Xu, and V. Koltun, \u201cLearning to see in the dark\u201d, CoRR, vol. abs/1805.01934,2018. [Online]. Available: http://arxiv.org/abs/1805.019341\n\n[2] X. Lin, C. Zhao, and W. Pan, \u201cTowards accurate binary convolutional neural network\u201d, CoRR, vol.abs/1711.11294, 2017. [Online]. Available: http://arxiv.org/abs/1711.112941\n\n[3] Cydonia, \"Learning to See in the Dark in PyTorch\", 2018.  [Online].  Available:   https://github.com/cydonia999/Learning_to_See_in_the_Dark_PyTorch\n\n[4] Mylio,2020.[Online].Available:https://focus.mylio.com/tech-today/how-many-photos-will-be-taken-in-2020\n\n[5]  M.   Rastegari,   V.   Ordonez,   J.   Redmon,   and   A.   Farhadi,   \u201cXnor-net:Imagenet   classification using  binary  convolutional  neural  networks\u201d, CoRR,  vol.  abs/1603.05279,  2016.  [Online].  Available:http://arxiv.org/abs/1603.052791\n\n[6]  E. Nurvitadhi, D. Sheffield, Jaewoong Sim, A. Mishra, G. Venkatesh, and D. Marr, \u201cAccelerating bina-rized neural networks:  Comparison of fpga,  cpu,  gpu,  and asic,\u201d  in2016 International Conference onField-Programmable Technology (FPT), 2016, pp. 77\u201384.\n\n\n\n\nWant to see more reproductions of this and other papers? Check https://reproduced-papers.firebaseapp.com/\n\n---\n\n\n", "meta": {"hexsha": "5238f7585396fd412ad8c60899a68681f6343a2d", "size": 48259, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "_notebooks/2020-07-01-LearningToEfficientlySeeInTheDark.ipynb", "max_stars_repo_name": "sfalkena/ESPCN_reproduction", "max_stars_repo_head_hexsha": "80452944350ef8b05ac09d582a3cea946544849c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_notebooks/2020-07-01-LearningToEfficientlySeeInTheDark.ipynb", "max_issues_repo_name": "sfalkena/ESPCN_reproduction", "max_issues_repo_head_hexsha": "80452944350ef8b05ac09d582a3cea946544849c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_notebooks/2020-07-01-LearningToEfficientlySeeInTheDark.ipynb", "max_forks_repo_name": "sfalkena/ESPCN_reproduction", "max_forks_repo_head_hexsha": "80452944350ef8b05ac09d582a3cea946544849c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 76.11829653, "max_line_length": 1446, "alphanum_fraction": 0.6357985039, "converted": true, "num_tokens": 9305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.06954174498792304, "lm_q1q2_score": 0.032871233791143026}}
{"text": "### Checklist for submission\n\nIt is extremely important to make sure that:\n\n1. Everything runs as expected (no bugs when running cells);\n2. The output from each cell corresponds to its code (don't change any cell's contents without rerunning it afterwards);\n3. All outputs are present (don't delete any of the outputs);\n4. Fill in all the places that say `# YOUR CODE HERE`, or \"**Your answer:** (fill in here)\".\n5. Never copy/paste any notebook cells. Inserting new cells is allowed, but it should not be necessary.\n6. The notebook contains some hidden metadata which is important during our grading process. **Make sure not to corrupt any of this metadata!** The metadata may for example be corrupted if you copy/paste any notebook cells, or if you perform an unsuccessful git merge / git pull. It may also be pruned completely if using Google Colab, so watch out for this. Searching for \"nbgrader\" when opening the notebook in a text editor should take you to the important metadata entries.\n7. Although we will try our very best to avoid this, it may happen that bugs are found after an assignment is released, and that we will push an updated version of the assignment to GitHub. If this happens, it is important that you update to the new version, while making sure the notebook metadata is properly updated as well. The safest way to make sure nothing gets messed up is to start from scratch on a clean updated version of the notebook, copy/pasting your code from the cells of the previous version into the cells of the new version.\n8. If you need to have multiple parallel versions of this notebook, make sure not to move them to another directory.\n9. Although not forced to work exclusively in the course `conda` environment, you need to make sure that the notebook will run in that environment, i.e. that you have not added any additional dependencies.\n\n**FOR HA1, HA2, HA3 ONLY:** Failing to meet any of these requirements might lead to either a subtraction of POEs (at best) or a request for resubmission (at worst).\n\nWe advise you to perform the following steps before submission to ensure that requirements 1, 2, and 3 are always met: **Restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart) and then **run all cells** (in the menubar, select Cell$\\rightarrow$Run All). This might require a bit of time, so plan ahead for this (and possibly use Google Cloud's GPU in HA1 and HA2 for this step). Finally press the \"Save and Checkout\" button before handing in, to make sure that all your changes are saved to this .ipynb file.\n\n### Fill in name of notebook file\nThis might seem silly, but the version check below needs to know the filename of the current notebook, which is not trivial to find out programmatically.\n\nYou might want to have several parallel versions of the notebook, and it is fine to rename the notebook as long as it stays in the same directory. **However**, if you do rename it, you also need to update its own filename below:\n\n\n```python\nnb_fname = \"IHA1.ipynb\"\n```\n\n### Fill in group number and member names (use NAME2 and GROUP only for HA1, HA2 and HA3):\n\n\n```python\nNAME1 = \"\" \nNAME2 = \"\"\nGROUP = \"\"\n```\n\n### Check Python version\n\n\n```python\nfrom platform import python_version_tuple\nassert python_version_tuple()[:2] == ('3','7'), \"You are not running Python 3.7. Make sure to run Python through the course Conda environment.\"\n```\n\n### Check that notebook server has access to all required resources, and that notebook has not moved\n\n\n```python\nimport os\nnb_dirname = os.path.abspath('')\nassignment_name = os.path.basename(nb_dirname)\nassert assignment_name in ['IHA1', 'IHA2', 'HA1', 'HA2', 'HA3'], \\\n    '[ERROR] The notebook appears to have been moved from its original directory'\n```\n\n### Verify correct nb_fname\n\n\n```python\nfrom IPython.display import display, HTML\ntry:\n    display(HTML(r''.format(nb_fname=nb_fname)))\nexcept NameError:\n    assert False, 'Make sure to fill in the nb_fname variable above!'\n```\n\n\n\n\n\n### Verify that your notebook is up-to-date and not corrupted in any way\n\n\n```python\nimport sys\nsys.path.append('..')\nfrom ha_utils import check_notebook_uptodate_and_not_corrupted\ncheck_notebook_uptodate_and_not_corrupted(nb_dirname, nb_fname)\n```\n\n    Matching current notebook against the following URL:\n    http://raw.githubusercontent.com/JulianoLagana/deep-machine-learning/master/home-assignments/IHA1/IHA1.ipynb\n    [SUCCESS] No major notebook mismatch found when comparing to latest GitHub version. (There might be minor updates, but even that is the case, submitting your work based on this notebook version would be acceptable.)\n\n\n# IHA1 - Assignment\n\nWelcome to the first individual home assignment!  \n\nThis assignment consists of two parts:\n * Python and NumPy exercises;\n * Build a deep neural network for forward propagation.\n  \nThe focus of this assignment is for you to gain practical knowledge with implementing forward propagation of deep neural networks without using any deep learning framework. You will also gain practical knowledge in two of Python's scientific libraries [NumPy](https://docs.scipy.org/doc/numpy-1.13.0/index.html) and [Matplotlib](https://matplotlib.org/devdocs/index.html).  \n\nSkeleton code is provided for most tasks and every part you are expected to implement is marked with **TODO**. Throughout the assignment you will also need to submit written answers to some questions. These questions are mainly to make you reflect on some particular topics and your answers will not be graded in detail. \n\nWe expect you to search and learn by yourself any commands you think are useful for these tasks. Don't limit yourself to what was taught in CL1. Use the help function, [stackoverflow](https://stackoverflow.com/), google, the [python documentation](https://docs.python.org/3.5/library/index.html) and the [NumPy](https://docs.scipy.org/doc/numpy-1.13.0/index.html) documentation to your advantage.  \n\n**IMPORTANT NOTE**: The tests available are not exhaustive, meaning that if you pass a test you have avoided the most common mistakes, but it is still not guaranteed that your solution is 100% correct.  \n\nLets start by importing the necessary libraries below.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom utils.tests.iha1Tests import *\n```\n\n## 1. Lists and arrays introduction\nFirst, we will warm up with a Python exercise and few NumPy exercises.\n\n### 1.1 List comprehensions\nExamine the code snippet provided below.\n\n\n```python\nmyList = []\nfor i in range(25):\n    if i % 2 == 0:\n        myList.append(i**2)\n        \nprint(myList)\n```\n\n    [0, 4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576]\n\n\nThis is not a very \"[pythonic](http://docs.python-guide.org/en/latest/writing/style/)\" way of writing. Lets re-write the code above using a [list comprehension](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions). The result will be less code, more readable and elegant. Your solution should be able to fit into one line of code.\n\n\n```python\nmyList = [i**2 for i in range(25) if i % 2 == 0] # TODO\n# YOUR CODE HERE\nprint(myList)\n```\n\n    [0, 4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576]\n\n\n\n```python\n# sample output from cell above for reference\n# [0, 4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576]\n```\n\n### 1.2 Numpy array vs numpy vectors\nRun the cell below to create a numpy array.   \n\n\n```python\nmyArr = np.array([1, 9, 25, 49, 81, 121, 169, 225, 289, 361, 441, 529])\nprint(myArr)\nprint(myArr.shape)\n```\n\n    [  1   9  25  49  81 121 169 225 289 361 441 529]\n    (12,)\n\n\nOne of the core features of numpy is to efficiently perform linear algebra operations.\nThere are two types of one-dimensional representations in numpy: arrays of shape (x,) and vectors of shape (x,1).\n\nThe above result indicates that **myArr** is an array of 12 elements with shape (12,).  \n\nNumpy's arrays and vectors both have the type of `numpy.ndarray` but have in some cases different characteristics and it is important to separate the two types because it will save a lot of debugging time later on. Read more about numpy shapes [here](https://stackoverflow.com/a/22074424).\n\nRun the code below to see how the transpose operation behaves differently between an array and vector.\n\n\n```python\n# print the shape of an array and the shape of a transposed array\nprint('myArr is an array of shape:')\nprint(myArr.shape)\nprint('The transpose of myArr has the shape:')\nprint(myArr.T.shape)\n\n# print the shape of a vector and the transpose of a vector\nmyVec = myArr.reshape(12,1)\nprint('myVec is a vector of shape:')\nprint(myVec.shape)\nprint('The transpose of myVec has the shape:')\nprint(myVec.T.shape)\n```\n\n    myArr is an array of shape:\n    (12,)\n    The transpose of myArr has the shape:\n    (12,)\n    myVec is a vector of shape:\n    (12, 1)\n    The transpose of myVec has the shape:\n    (1, 12)\n\n\n### 1.3 Numpy exercises\nNow run the cell below to create the numpy array `numbers` and then complete the exercises sequentially.\n\n\n```python\nnumbers = np.arange(24)\nprint(numbers)\n```\n\n    [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]\n\n\n\n```python\n# TODO: reshape numbers into a 6x4 matrix\nnumbers=numbers.reshape(6,4)\n# YOUR CODE HERE\nprint(numbers)\n\n```\n\n    [[ 0  1  2  3]\n     [ 4  5  6  7]\n     [ 8  9 10 11]\n     [12 13 14 15]\n     [16 17 18 19]\n     [20 21 22 23]]\n\n\n\n```python\n# sample output from cell above for reference\n#  [[ 0  1  2  3]\n#   [ 4  5  6  7]\n#   [ 8  9 10 11]\n#   [12 13 14 15]\n#   [16 17 18 19]\n#   [20 21 22 23]]\n```\n\n\n```python\n# test case\ntest_numpy_reshape(numbers)\n```\n\n    Test passed\n\n\n\n```python\n# TODO: set the element of the last row of the last column to zero\n# Hint: Try what happends when indices are negative\nnumbers[-1,-1]=0\n\n# YOUR CODE HERE\nprint(numbers)\n```\n\n    [[ 0  1  2  3]\n     [ 4  5  6  7]\n     [ 8  9 10 11]\n     [12 13 14 15]\n     [16 17 18 19]\n     [20 21 22  0]]\n\n\n\n```python\n# sample output from cell above for reference\n#  [[ 0  1  2  3]\n#   [ 4  5  6  7]\n#   [ 8  9 10 11]\n#   [12 13 14 15]\n#   [16 17 18 19]\n#   [20 21 22  0]]\n```\n\n\n```python\n# test case\ntest_numpy_neg_ix(numbers)\n```\n\n    Test passed\n\n\n\n```python\n# TODO: set every element of the 0th row to 0\nnumbers[0,]=0\n\n# YOUR CODE HERE\nprint(numbers)\n```\n\n    [[ 0  0  0  0]\n     [ 4  5  6  7]\n     [ 8  9 10 11]\n     [12 13 14 15]\n     [16 17 18 19]\n     [20 21 22  0]]\n\n\n\n```python\n# sample output from cell above for reference\n#  [[ 0  0  0  0]\n#   [ 4  5  6  7]\n#   [ 8  9 10 11]\n#   [12 13 14 15]\n#   [16 17 18 19]\n#   [20 21 22  0]]\n```\n\n\n```python\n# test case\ntest_numpy_row_ix(numbers)\n```\n\n    Test passed\n\n\n\n```python\n# TODO: append a 1x4 row vector of zeros to `numbers`, \n# resulting in a 7x4 matrix where the new row of zeros is the last row\n# Hint: A new matrix must be created in the procedure. Numpy arrays are not dynamic.\nnumbers=np.vstack([numbers, np.zeros(4)])\n# YOUR CODE HERE\nprint(numbers)\nprint(numbers.shape)\n```\n\n    [[ 0.  0.  0.  0.]\n     [ 4.  5.  6.  7.]\n     [ 8.  9. 10. 11.]\n     [12. 13. 14. 15.]\n     [16. 17. 18. 19.]\n     [20. 21. 22.  0.]\n     [ 0.  0.  0.  0.]]\n    (7, 4)\n\n\n\n```python\n# sample output from cell above for reference\n#   [[ 0  0  0  0]\n#    [ 4  5  6  7]\n#    [ 8  9 10 11]\n#    [12 13 14 15]\n#    [16 17 18 19]\n#    [20 21 22  0]\n#    [ 0  0  0  0]]\n#  (7, 4)\n```\n\n\n```python\n# test case\ntest_numpy_append_row(numbers)\n```\n\n    Test passed\n\n\n\n```python\n# TODO: set all elements above 10 to the value 1\nb=(numbers>10)\nnumbers[b]=1\n# YOUR CODE HERE\nprint(numbers)\n```\n\n    [[ 0.  0.  0.  0.]\n     [ 4.  5.  6.  7.]\n     [ 8.  9. 10.  1.]\n     [ 1.  1.  1.  1.]\n     [ 1.  1.  1.  1.]\n     [ 1.  1.  1.  0.]\n     [ 0.  0.  0.  0.]]\n\n\n\n```python\n# sample output from cell above for reference\n#  [[ 0  0  0  0]\n#   [ 4  5  6  7]\n#   [ 8  9 10  1]\n#   [ 1  1  1  1]\n#   [ 1  1  1  1]\n#   [ 1  1  1  0]\n#   [ 0  0  0  0]]\n```\n\n\n```python\n# test case\ntest_numpy_bool_matrix(numbers)\n```\n\n    Test passed\n\n\n\n```python\n# TODO: compute the sum of every row and replace `numbers` with the answer\n# `numbers` will be a (7,) array as a result\nnumbers=np.sum(numbers, axis=1)\n# YOUR CODE HERE\nprint(numbers.shape)\nprint(numbers)\n```\n\n    (7,)\n    [ 0. 22. 28.  4.  4.  3.  0.]\n\n\n\n```python\n# sample output from cell above for reference\n#   (7,)\n#   [ 0 22 28  4  4  3  0]\n```\n\n\n```python\n# test case\ntest_numpy_sum(numbers)\n```\n\n    Test passed\n\n\n## 2 Building your deep neural network\nIt is time to start implementing your first feed-forward neural network. In this lab you will only focus on implementing the forward propagation procedure. \n\nAs you know, a feed-forward neural network consists of a sequence of layers, where the output from one layer is the input to the following layer. Below you can find an example of a feed-forward neural network with 2 hidden layers (blue) and 1 output layer (red). \n\n\n\n**What would be your approach to implement a feed-forward neural network? Please provide a brief and high level explanation on how would you implement the several components of network; for instance, would you use any `python` class or only functions?** We will not grade this answer in detail. The objective with this question is to help you reflect upon how to structure the code. This will hopefully enable you to understand the code below more easily. As long as it is clear from your answer that you have tried to briefly describe the overall structure of the code, we will accept your answer.\n\n**Your answer:** (I will use python functions to implement a forward neural network, first initialize a matrix for w and zero for b and then calculate the Z and then apply the activation function to calculate A using a for loop for 1 to l layer)\n\nIn this exercise, you will implement several components of a feed-forward network, such as a layers, activation functions and weight initialization functions, and from those create your own feed-forward neural network implementation. \n\nNOTE: When using a neural network, due to memory and computational constraints, you can not forward propagate the entire dataset at once. Therefore, you divide the dataset into a number of sets/parts called batches. A batch will make up for the first dimension of every input to a layer and the notation `(BATCH_SIZE, NUM_FEATURES)` simply means the dimension of a batch of samples where every sample has `NUM_FEATURES` features.\n\n### 2.1 Activation functions\nYou will start by defining a few activation functions that are later needed by the neural network.\n\n#### 2.1.1 ReLU\nThe neural network will use the ReLU activation function in every layer except for the last. ReLU does element-wise comparison of the input matrix. For example, if the input is `X`, and `X[i,j] == 2` and `X[k,l] == -1`, then after applying ReLU, `X[i,j] == 2` and `X[k,l] == 0` should be true.  \n\nThe formula for implementing ReLU for a single neuron $i$ is:\n\\begin{equation}\nrelu(z_i) = \n    \\begin{cases}\n      0, & \\text{if}\\ z_i \\leq 0 \\\\\n      z_i, & \\text{otherwise}\n    \\end{cases}\n\\end{equation}\n\nNow implement `relu` in vectorized form\n\n\n```python\ndef relu(z):\n    \"\"\" Implement the ReLU activation function\n    \n    Arguments:\n    z - the input of the activation function. Has a type of 'numpy.ndarray'\n    \n    Returns:\n    a - the output of the activation function. Has a type of numpy.ndarray and the same shape as 'z'\n    \"\"\"\n    \n    z[z<0]=0\n    a = z # TODO\n    # YOUR CODE HERE\n    \n    return a\n```\n\n\n```python\n# test case\ntest_relu(relu)\n```\n\n    Test passed\n\n\nCan you name some of the advantages of the ReLU activation function? (We will not grade this answer in detail.)\n\n**Your answer:** (It is quick in training compared to use tanh or signoid activation function)\n\n#### 2.1.2 Sigmoid\nThe sigmoid activation function is common for binary classification. This is because it squashes its input to the range [0,1].  \nImplement the activation function `sigmoid` using the formula:  \n\\begin{equation}\n    \\sigma(z) = \\frac{1}{1 + e^{-z}}\n\\end{equation}\n\n\n```python\ndef sigmoid(z):\n    \"\"\" Implement the sigmoid activation function\n    \n    Arguments:\n    z - the input of the activation function. Has a type of 'numpy.ndarray'\n    \n    Returns:\n    a - the output of the activation function. Has a type of 'numpy.ndarray' and the same shape as 'z'\n    \"\"\"\n    z=1/(1+np.exp(-z))\n    a = z # TODO\n    # YOUR CODE HERE\n    \n    return a\n```\n\n\n```python\n# test case\ntest_sigmoid(sigmoid)\n```\n\n    Test passed\n\n\nWhy is the sigmoid activation function useful for binary classification? Feel free to use some numerical examples to show how the magnitudes of the variable $z$ affect the output of the sigmoid layer. (We will not grade this answer in detail.)\n\n**Your answer:** (sigmoid result will between 0 to 1)\n\n#### 2.1.3 Visualization\nMake a plot using matplotlib to visualize the activation functions between the input interval [-3,3]. The plot should have the following properties\n * one plot should contain a visualization of both `ReLU` and `sigmoid`;\n * x-axis: range of values between [-3,3], **hint**: np.linspace;\n * y-axis: the value of the activation functions at a given input `x`;\n * a legend explaining which line represents which activation function.\n\n\n```python\n# TODO: make a plot of ReLU and sigmoid values in the interval [-3,3]\nx=np.linspace(-3,3,100)\ny1=relu(x)\ny2=sigmoid(x)\nfig, axes=plt.subplots()\naxes.plot(x,y1)\naxes.plot(x,y2)\naxes.set_xlim([-3,3])\naxes.legend(['Relu', 'Sigmoid'], loc=2)\n# YOUR CODE HERE\n```\n\n#### 2.1.4 Softmax\nYou will use the softmax activation function / classifier as the final layer of your neural network later in the assignment. Implement `softmax` according to the formula below. The subtraction of the maximum value is there solely to avoid overflows in a practical implementation.\n\\begin{equation}\nsoftmax(z_i) = \\frac{e^{z_i - max(\\mathbf{z})}}{ \\sum^j e^{z_j - max(\\mathbf{z})}}\n\\end{equation}\n\n\n\n```python\ndef softmax(z):\n    \"\"\" Implement the softmax activation function\n    \n    Arguments:\n    z - the input of the activation function, shape (BATCH_SIZE, FEATURES) and type 'numpy.ndarray'\n    \n    Returns:\n    a - the output of the activation function, shape (BATCH_SIZE, FEATURES) and type 'numpy.ndarray'\n    \"\"\"\n    batchsize=z.shape[0]\n    z=np.exp(z)\n    a = z/np.sum(z, axis=1).reshape(batchsize,1) # TODO\n    # YOUR CODE HERE\n    \n    return a\n```\n\n\n```python\n# test case\ntest_softmax(softmax)\n```\n\n    Test passed\n\n\nWhat are the main differences between using `sigmoid` and `softmax` for multi-class classification problems? And when the number of classes is 2? (We will not grade this answer in detail.)\n\n**Your answer:** (sigmoid is for binary classfication (0,1) and softmax is for the number of classes larger then 2)\n\n### 2.2 Initialize weights\nYou will implement a helper function that takes the shape of a layer as input, and returns an initialized weight matrix $\\mathbf{W}$ and bias vector $\\mathbf{b}$ as output. The matrix $\\mathbf{W}$ should be sampled from a normal distribution with mean 0 and standard deviation 2, and $\\mathbf{b}$ should be initialized to all zeros.\n\n\n```python\ndef initialize_weights(layer_shape):\n    \"\"\" Implement initialization of the weight matrix and biases\n    \n    Arguments:\n    layer_shape - a tuple of length 2, type (int, int), that determines the dimensions of the weight matrix: (input_dim, output_dim)\n    \n    Returns:\n    w - a weight matrix with dimensions of 'layer_shape', (input_dim, output_dim), that is normally distributed with\n        properties mu = 0, stddev = 2. Has a type of 'numpy.ndarray'\n    b - a vector of initialized biases with shape (1,output_dim), all of value zero. Has a type of 'numpy.ndarray'\n    \"\"\"\n    w = np.random.normal(0,2,layer_shape) # TODO\n    b = np.zeros((1,layer_shape[1]))# TODO\n    # YOUR CODE HERE\n    \n    return w, b\n```\n\n\n```python\n# test case\ntest_initialize_weights(initialize_weights)\n```\n\n    Test passed\n\n\n### 2.3 Feed-forward neural network layer module\nTo build a feed-forward neural network of arbitrary depth you are going to define a neural network layer as a module that can be used to stack layers upon each other. Your task is to complete the `Layer` class by following the descriptions in the comments. Recall the formula for forward propagation of an arbitrary layer $l$:\n\n\\begin{equation}\n\\mathbf{a}^{[l]} = g(\\mathbf{z}^{[l]}) = g(\\mathbf{a}^{[l-1]}\\mathbf{w}^{[l]} +\\mathbf{b}^{[l]})\n\\end{equation}\n\nwhere $g$ is the activation function given by `activation_fn`, which can be relu, sigmoid or softmax. \n\n\n```python\nclass Layer:\n    \"\"\" \n    TODO: Build a class called Layer that satisfies the descriptions of the methods\n    Make sure to utilize the helper functions you implemented before\n    \"\"\"\n    \n    def __init__(self, input_dim, output_dim, activation_fn=relu):\n        \"\"\"\n        Arguments:\n        input_dim - the number of inputs of the layer. type int\n        output_dim - the number of outputs of the layer. type int\n        activation_fn - a reference to the activation function to use. Should be 'relu' as a default\n                        possible values are the 'relu', 'sigmoid' and 'softmax' functions you implemented earlier.\n                        Has the type 'function'\n        \n        Attributes:\n        w - the weight matrix of the layer, should be initialized with 'initialize_weights'\n            and has the shape (INPUT_FEATURES, OUTPUT_FEATURES) and type 'numpy.ndarray'\n        b - the bias vector of the layer, should be initialized with 'initialize_weights'\n            and has the shape (1, OUTPUT_FEATURES) and type 'numpy.ndarray'\n        activation_fn - a reference to the activation function to use.\n                        Has the type 'function'\n        \"\"\"\n        self.w, self.b = initialize_weights((input_dim,output_dim)) # TODO\n        self.activation_fn = activation_fn # TODO\n        # YOUR CODE HERE\n        \n        \n    def forward_prop(self, a_prev):\n        \"\"\" Implement the forward propagation module of the neural network layer\n        Should use whatever activation function that 'activation_fn' references to\n        \n        Arguments:\n        a_prev - the input to the layer, which may be the data 'X', or the output from the previous layer.\n            a_prev has the shape of (BATCH_SIZE, INPUT_FEATURES) and the type 'numpy.ndarray'\n        \n        Returns:\n        a - the output of the layer when performing forward propagation. Has the type 'numpy.ndarray'\n        \"\"\"\n        a = self.activation_fn(a_prev.dot(self.w)+self.b) # TODO\n        # YOUR CODE HERE\n        \n        return a\n```\n\n\n```python\n# test case, be sure that you pass the previous activation function tests before running this test\ntest_layer(Layer, relu, sigmoid, softmax)\n```\n\n    Test passed\n\n\n### 2.4 Backward propagation\n\nIn the previous exercise you only implemented the forward propagation of the layer. However, when training a network, you would also need to implement the backward propagation of the layer in order to be able to update its weights. (You won't need to do this in this assignment since you will not train the network. Instead you will load the network weights, which are obtained from a previously trained network.)\n\nProvide a high-level explanation of how you would modify your current implementation of the `Layer` class in order to add the backward propagation. (We will not grade this in detail. It is enough that your answer demonstrates that you have thought about how to perform backprop using these classes.)\n\n**Your answer:** (first get dZ then to dW)\n\n### 2.5 Example - Logistic regression \nBinary logistic regression is a classifier where classification is performed by applying the sigmoid activation function to a linear combination of input values. You will now try out your neural network layer by utilizing it as a linear combination of input values and apply the sigmoid activation function to classify a simple problem. \n\nThe cell below defines a dataset of 5 points of either class `0` or class `1`. Your assignment is to:  \n1. Create an instance of a `Layer` with the sigmoid activation function;\n2. Manually tune the weights `w` and bias `b` of your layer.\n\nYou can use `test_logistic` to visually inspect how your classifier is performing. In order to  be successful in this exercise you need select values for the weights `w` and bias `b` such that all points are classified correctly. \n\n\n```python\n# Run this cell to create the dataset\nX_s = np.array([[1, 2],\n               [5, 3],\n               [8, 8],\n               [7, 5],\n               [3, 6]])\nY_s = np.array([0,0,1,0,1])\n\ntest_logistic(X_s, Y_s)\n```\n\n\n```python\n# create an instance of layer\nl = Layer(2,1,sigmoid)\n\n# TODO: manually tune weights\nl.w = np.array([[-0.5],[0.75]])\nl.b = np.array([[-1.5]])\n# YOUR CODE HERE\n\n# testing your choice of weights with this function\ntest_logistic(X_s,Y_s,l,sigmoid)\n```\n\n### 2.6 Feed-forward neural network\nYou will now define the actual neural network class. It is an L-layer neural network, meaning that the number of layers and neurons in each layer is specified as input by the user. Once again, you will only focus on implementing the forward propagation part.\n\nRead the descriptions in the comments and complete the **TODO**s.\n\n\n```python\nclass NeuralNetwork:\n    \"\"\" \n    TODO: Implement an L-layer neural network class by utilizing the Layer module defined above \n    Each layer should use 'relu' activation function, except for the output layer, which should use 'softmax'\n    \"\"\"\n    \n    def __init__(self, input_n, layer_dims):\n        \"\"\"\n        Arguments:\n        input_n    - the number of inputs to the network. Should be the same as the length of a data sample\n                     Has type int\n        layer_dims - a python list or tuple of the number of neurons in each layer. Layer 'l' should have a weight matrix  \n                     with the shape ('layer_dims[l-1]', 'layer_dims[l]'). \n                     'layer_dims[-1]' is the dimension of the output layer.\n                     Layer 1 should have the dimensions ('input_n', 'layer_dims[0]').\n                     len(layer_dims) is the depth of the neural network\n        Attributes:\n        input_n - the number of inputs to the network. Has type int\n        layers  - a python list of each layer in the network. Each layer should use the 'relu' activation function,\n                  except for the last layer, which should use 'softmax'. \n                  Has type 'list' containing layers of type 'Layer'\n        \"\"\"\n        \n        self.input_n = input_n # TODO\n        self.layers=[]\n        for i in range(0,len(layer_dims)-1):\n            self.layers.append(Layer(input_n, layer_dims[i]))\n            input_n=layer_dims[i]\n        self.layers.append(Layer(input_n, layer_dims[-1],softmax))\n        # YOUR CODE HERE\n        \n    def forward_prop(self, x):\n        \"\"\" \n        Implement the forward propagation procedure through the entire network, from input to output.\n        You will now connect each layer's forward propagation function into a chain of layer-wise forward propagations.\n        \n        Arguments:\n        x - the input data, which has the shape (BATCH_SIZE, NUM_FEATURES) and type 'numpy.ndarray'\n        \n        Returns:\n        a - the output of the last layer after forward propagating through the every layer in 'layers'.\n            Should have the dimension (BATCH_SIZE, layers[-1].w.shape[1]) and type 'numpy.ndarray'\n        \"\"\"\n        for layer in self.layers:\n            x=layer.forward_prop(x)\n        a=x\n        # YOUR CODE HERE\n        return a\n```\n\n\n```python\n# test case\ntest_neuralnetwork(NeuralNetwork)\n```\n\n    Test passed\n\n\n## 3 Making predictions with a neural network\nIn practice, its common to load weights to your neural network that has already been trained.  \nIn this section, you will create an instance of your neural network, load trained weights from disk, and perform predictions.\n\n### 3.1 Load weights from disk\nCreate an instance of `NeuralNetwork` with input size $28 \\times 28 = 784$, two hidden layers of size 100 and an output layer of size 10. Thereafter, load the weights contained in `./utils/ann_weights.npz` to your network.\n\n\n```python\ninput_n=784\nlayer_dims=[100,100,10]\nann = NeuralNetwork(input_n,layer_dims)\n# YOUR CODE HERE\n\n# load weights\nweights = np.load('./utils/ann_weights.npz')\nfor l in range(len(ann.layers)):\n    ann.layers[l].w = weights['w' + str(l)]\n    ann.layers[l].b = weights['b' + str(l)]\n```\n\n### 3.2 Prediction\nNow, implement the function `predict_and_correct` which does the following:\n1. Load `./utils/test_data.npz` from disk;\n2. Extract test data `X` and `Y` from file;\n3. Perform for every pair of data:  \n    a. plot the image `x`; <br> \n    b. make a prediction using your neural network by forward propagating and picking the most probable class;     \n    c. check whether the prediction is correct (compare with the ground truth number `y`);    \n    d. print the predicted label and wether it was correct or not. \n\n\n```python\ndef predict_and_correct(ann):\n    \"\"\" Load test data from file and predict using your neural network. \n    Make a prediction for ever data sample and print it along with wether it was a correct prediction or not\n    \n    Arguments:\n    ann - the neural network to use for prediction. Has type `NeuralNetwork`\n    \n    Returns: # for test case purposes\n    A `numpy.ndarray` of predicted classes (integers [0-9]) with shape (11,)\n    \"\"\"\n    data = np.load('./utils/test_data.npz')\n    X, cls = data['X'], data['Y']\n    \n    cls_preds = [np.argmax(ann.forward_prop(i))for i in X]  # TODO: make a predicted number for every image in X\n    # YOUR CODE HERE\n    \n    for i in range(len(X)):\n        plt.imshow(X[i].reshape(28,28), cmap='gray')\n        plt.show()\n        correct = cls_preds[i] == cls[i]\n        print('The prediction was {0}, it was {1}!'.format(cls_preds[i], 'correct' if correct else 'incorrect'))\n        \n    return cls_preds\n        \ncls_pred = predict_and_correct(ann)\n```\n\n\n```python\n# final test case\ntest_predict_and_correct_answer(cls_pred)\n```\n\n    Test passed, you have implemented your neural network correctly!\n\n\n## Congratulations!\nYou have successfully implemented a neural network from scratch using only NumPy!  \n", "meta": {"hexsha": "aa41b44184f1cd8d9a668de70612864d0eae29d2", "size": 197446, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "home-assignments/IHA1/IHA1.ipynb", "max_stars_repo_name": "minwuh0811/deep-machine-learning", "max_stars_repo_head_hexsha": "a86a96cf8063a0150f967daf4061c2fca95c9f0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "home-assignments/IHA1/IHA1.ipynb", "max_issues_repo_name": "minwuh0811/deep-machine-learning", "max_issues_repo_head_hexsha": "a86a96cf8063a0150f967daf4061c2fca95c9f0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "home-assignments/IHA1/IHA1.ipynb", "max_forks_repo_name": "minwuh0811/deep-machine-learning", "max_forks_repo_head_hexsha": "a86a96cf8063a0150f967daf4061c2fca95c9f0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 70.7945500179, "max_line_length": 40684, "alphanum_fraction": 0.8058101962, "converted": true, "num_tokens": 7910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782568056728001, "lm_q2_score": 0.11757214282138606, "lm_q1q2_score": 0.03271524889758512}}
{"text": "# Twitter sentiment analysis\n\nThe data is represented as rows of of JSON strings.\nIt consists of [tweets](https://dev.twitter.com/overview/api/tweets), [messages](https://dev.twitter.com/streaming/overview/messages-types), and a small amount of broken data (cannot be parsed as JSON).\n\n## Tweets\n\nA tweet consists of many data fields. [Here is an example](https://gist.github.com/arapat/03d02c9b327e6ff3f6c3c5c602eeaf8b). You can learn all about them in the Twitter API doc. We are going to briefly introduce only the data fields that will be used in this homework.\n\n* `created_at`: Posted time of this tweet (time zone is included)\n* `id_str`: Tweet ID - we recommend using `id_str` over using `id` as Tweet IDs, becauase `id` is an integer and may bring some overflow problems.\n* `text`: Tweet content\n* `user`: A JSON object for information about the author of the tweet\n    * `id_str`: User ID\n    * `name`: User name (may contain spaces)\n    * `screen_name`: User screen name (no spaces)\n* `retweeted_status`: A JSON object for information about the retweeted tweet (i.e. this tweet is not original but retweeteed some other tweet)\n    * All data fields of a tweet except `retweeted_status`\n* `entities`: A JSON object for all entities in this tweet\n    * `hashtags`: An array for all the hashtags that are mentioned in this tweet\n    * `urls`: An array for all the URLs that are mentioned in this tweet\n\n\n## Data source\n\nAll tweets are collected using the [Twitter Streaming API](https://dev.twitter.com/streaming/overview).\n\n\n## Users partition\n\nBesides the original tweets, we will provide you with a Pickle file, which contains a partition over 452,743 Twitter users. It contains a Python dictionary `{user_id: partition_id}`. The users are partitioned into 7 groups.\n\n# Part 0: Load data to a RDD\n\n## Data\nRead file list from `../Data/data_input.txt`. \n\n## Local test\n\n1. Make RDD from the list of files in `data_input.txt`.\n2. Mark the RDD to be cached (so in next operation data will be loaded in memory) \n3. call the `print_count` method to print number of lines in all these files\n\nIt should print\n```\nNumber of elements: 2193\n```\n\n\n```python\n# -*- coding: utf-8 -*-\n#import timeit\n#t2=timeit.default_timer()\ndef print_count(rdd):\n    print 'Number of elements:', rdd.count()\n```\n\n\n```python\n# Your code here\nimport findspark\nfindspark.init()\nfrom pyspark import SparkContext\nsc = SparkContext(master=\"local[4]\")\n```\n\n\n```python\n#sc.stop()\n```\n\n\n```python\nall_files=open(\"../Data/data_input.txt\",\"r\")\nlines=[line.strip() for line in all_files.readlines()]\ntext=sc.textFile(','.join(lines)).cache()\nprint_count(text)\n```\n\n    Number of elements: 2193\n\n\n# Part 1: Parse JSON strings to JSON objects\n\nPython has built-in support for JSON.\n\n\n```python\n#import json\n\n#json_example = '''\n#{\n#    \"id\": 1,\n#    \"name\": \"A green door\",\n#    \"price\": 12.50,\n#    \"tags\": [\"home\", \"green\"]\n#}\n#'''\n#\n#json_obj = json.loads(json_example)\n#json_obj\n```\n\n## Broken tweets and irrelevant messages\n\nThe data of this assignment may contain broken tweets (invalid JSON strings). So make sure that your code is robust for such cases.\n\nIn addition, some lines in the input file might not be tweets, but messages that the Twitter server sent to the developer (such as [limit notices](https://dev.twitter.com/streaming/overview/messages-types#limit_notices)). Your program should also ignore these messages.\n\n*Hint:* [Catch the ValueError](http://stackoverflow.com/questions/11294535/verify-if-a-string-is-json-in-python)\n\n\n(1) Parse raw JSON tweets to obtain valid JSON objects. From all valid tweets, construct a pair RDD of `(user_id, text)`, where `user_id` is the `id_str` data field of the `user` dictionary (read [Tweets](#Tweets) section above), `text` is the `text` data field.\n\n\n```python\nimport json\n\ndef safe_parse(raw_json):\n    # your code here\n    try:\n        json_object = json.loads(raw_json)\n    except ValueError, e:\n        return False\n    if('text' not in json_object and 'id_str' not in json_object):\n        return False\n    return True\n    #pass\n\ndef keypair(raw_json_string):\n    k=json.loads(raw_json_string)\n    return (k['user']['id_str'],k['text'].encode('utf-8'))\n    \nvalidtext=text.filter(safe_parse).map(keypair).cache()\n# your code here\n```\n\n(2) Count the number of different users in all valid tweets (hint: [the `distinct()` method](https://spark.apache.org/docs/latest/programming-guide.html#transformations)).\n\nIt should print\n```\nThe number of unique users is: 2083\n```\n\n\n```python\ndef print_users_count(count):\n    print 'The number of unique users is:', count\n```\n\n\n```python\n# your code here\nprint_users_count(validtext.map(lambda k : k[0]).distinct().count())\n#print_users_count(textdistinct.count())\n```\n\n    The number of unique users is: 2083\n\n\n# Part 2: Number of posts from each user partition\n\nLoad the Pickle file `../../Data/users-partition.pickle`, you will get a dictionary which represents a partition over 452,743 Twitter users, `{user_id: partition_id}`. The users are partitioned into 7 groups. For example, if the dictionary is loaded into a variable named `partition`, the partition ID of the user `59458445` is `partition[\"59458445\"]`. These users are partitioned into 7 groups. The partition ID is an integer between 0-6.\n\nNote that the user partition we provide doesn't cover all users appear in the input data.\n\n(1) Load the pickle file.\n\n\n```python\n# your code here\nimport pickle\npartition=pickle.load(open(\"../Data/users-partition.pickle\",'rb'))\n```\n\n(2) Count the number of posts from each user partition\n\nCount the number of posts from group 0, 1, ..., 6, plus the number of posts from users who are not in any partition. Assign users who are not in any partition to the group 7.\n\nPut the results of this step into a pair RDD `(group_id, count)` that is sorted by key.\n\n\n```python\n# your code here\ndef usermapping((u,t)):\n    if u in partition:\n        return (partition[u],1)\n    else:\n        return (7,1)\nsortedkeyrdd=validtext.map(usermapping).reduceByKey(lambda a,b:a+b).sortByKey('false')\n```\n\n(3) Print the post count using the `print_post_count` function we provided.\n\nIt should print\n\n```\nGroup 0 posted 81 tweets\nGroup 1 posted 199 tweets\nGroup 2 posted 45 tweets\nGroup 3 posted 313 tweets\nGroup 4 posted 86 tweets\nGroup 5 posted 221 tweets\nGroup 6 posted 400 tweets\nGroup 7 posted 798 tweets\n```\n\n\n```python\ndef print_post_count(counts):\n    for group_id, count in counts:\n        print 'Group %d posted %d tweets' % (group_id, count)\n```\n\n\n```python\nprint_post_count(sortedkeyrdd.collect())\n# your code here\n```\n\n    Group 0 posted 81 tweets\n    Group 1 posted 199 tweets\n    Group 2 posted 45 tweets\n    Group 3 posted 313 tweets\n    Group 4 posted 86 tweets\n    Group 5 posted 221 tweets\n    Group 6 posted 400 tweets\n    Group 7 posted 798 tweets\n\n\n# Part 3:  Tokens that are relatively popular in each user partition\n\nIn this step, we are going to find tokens that are relatively popular in each user partition.\n\nWe define the number of mentions of a token $t$ in a specific user partition $k$ as the number of users from the user partition $k$ that ever mentioned the token $t$ in their tweets. Note that even if some users might mention a token $t$ multiple times or in multiple tweets, a user will contribute at most 1 to the counter of the token $t$.\n\nPlease make sure that the number of mentions of a token is equal to the number of users who mentioned this token but NOT the number of tweets that mentioned this token.\n\nLet $N_t^k$ be the number of mentions of the token $t$ in the user partition $k$. Let $N_t^{all} = \\sum_{i=0}^7 N_t^{i}$ be the number of total mentions of the token $t$.\n\nWe define the relative popularity of a token $t$ in a user partition $k$ as the log ratio between $N_t^k$ and $N_t^{all}$, i.e. \n\n\\begin{equation}\np_t^k = \\log \\frac{C_t^k}{C_t^{all}}.\n\\end{equation}\n\n\nYou can compute the relative popularity by calling the function `get_rel_popularity`.\n\n(0) Load the tweet tokenizer.\n\n\n```python\n# %load happyfuntokenizing.py\n#!/usr/bin/env python\n\n\"\"\"\nThis code implements a basic, Twitter-aware tokenizer.\n\nA tokenizer is a function that splits a string of text into words. In\nPython terms, we map string and unicode objects into lists of unicode\nobjects.\n\nThere is not a single right way to do tokenizing. The best method\ndepends on the application.  This tokenizer is designed to be flexible\nand this easy to adapt to new domains and tasks.  The basic logic is\nthis:\n\n1. The tuple regex_strings defines a list of regular expression\n   strings.\n\n2. The regex_strings strings are put, in order, into a compiled\n   regular expression object called word_re.\n\n3. The tokenization is done by word_re.findall(s), where s is the\n   user-supplied string, inside the tokenize() method of the class\n   Tokenizer.\n\n4. When instantiating Tokenizer objects, there is a single option:\n   preserve_case.  By default, it is set to True. If it is set to\n   False, then the tokenizer will downcase everything except for\n   emoticons.\n\nThe __main__ method illustrates by tokenizing a few examples.\n\nI've also included a Tokenizer method tokenize_random_tweet(). If the\ntwitter library is installed (http://code.google.com/p/python-twitter/)\nand Twitter is cooperating, then it should tokenize a random\nEnglish-language tweet.\n\n\nJulaiti Alafate:\n  I modified the regex strings to extract URLs in tweets.\n\"\"\"\n\n__author__ = \"Christopher Potts\"\n\n######################################################################\n\nimport re\nimport htmlentitydefs\n\n######################################################################\n# The following strings are components in the regular expression\n# that is used for tokenizing. It's important that phone_number\n# appears first in the final regex (since it can contain whitespace).\n# It also could matter that tags comes after emoticons, due to the\n# possibility of having text like\n#\n#     <:| and some text >:)\n#\n# Most imporatantly, the final element should always be last, since it\n# does a last ditch whitespace-based tokenization of whatever is left.\n\n# This particular element is used in a couple ways, so we define it\n# with a name:\nemoticon_string = r\"\"\"\n    (?:\n      [<>]?\n      [:;=8]                     # eyes\n      [\\-o\\*\\']?                 # optional nose\n      [\\)\\]\\(\\[dDpP/\\:\\}\\{@\\|\\\\] # mouth      \n      |\n      [\\)\\]\\(\\[dDpP/\\:\\}\\{@\\|\\\\] # mouth\n      [\\-o\\*\\']?                 # optional nose\n      [:;=8]                     # eyes\n      [<>]?\n    )\"\"\"\n\n# The components of the tokenizer:\nregex_strings = (\n    # Phone numbers:\n    r\"\"\"\n    (?:\n      (?:            # (international)\n        \\+?[01]\n        [\\-\\s.]*\n      )?            \n      (?:            # (area code)\n        [\\(]?\n        \\d{3}\n        [\\-\\s.\\)]*\n      )?    \n      \\d{3}          # exchange\n      [\\-\\s.]*   \n      \\d{4}          # base\n    )\"\"\"\n    ,\n    # URLs:\n    r\"\"\"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+\"\"\"\n    ,\n    # Emoticons:\n    emoticon_string\n    ,    \n    # HTML tags:\n     r\"\"\"<[^>]+>\"\"\"\n    ,\n    # Twitter username:\n    r\"\"\"(?:@[\\w_]+)\"\"\"\n    ,\n    # Twitter hashtags:\n    r\"\"\"(?:\\#+[\\w_]+[\\w\\'_\\-]*[\\w_]+)\"\"\"\n    ,\n    # Remaining word types:\n    r\"\"\"\n    (?:[a-z][a-z'\\-_]+[a-z])       # Words with apostrophes or dashes.\n    |\n    (?:[+\\-]?\\d+[,/.:-]\\d+[+\\-]?)  # Numbers, including fractions, decimals.\n    |\n    (?:[\\w_]+)                     # Words without apostrophes or dashes.\n    |\n    (?:\\.(?:\\s*\\.){1,})            # Ellipsis dots. \n    |\n    (?:\\S)                         # Everything else that isn't whitespace.\n    \"\"\"\n    )\n\n######################################################################\n# This is the core tokenizing regex:\n    \nword_re = re.compile(r\"\"\"(%s)\"\"\" % \"|\".join(regex_strings), re.VERBOSE | re.I | re.UNICODE)\n\n# The emoticon string gets its own regex so that we can preserve case for them as needed:\nemoticon_re = re.compile(regex_strings[1], re.VERBOSE | re.I | re.UNICODE)\n\n# These are for regularizing HTML entities to Unicode:\nhtml_entity_digit_re = re.compile(r\"&#\\d+;\")\nhtml_entity_alpha_re = re.compile(r\"&\\w+;\")\namp = \"&amp;\"\n\n######################################################################\n\nclass Tokenizer:\n    def __init__(self, preserve_case=False):\n        self.preserve_case = preserve_case\n\n    def tokenize(self, s):\n        \"\"\"\n        Argument: s -- any string or unicode object\n        Value: a tokenize list of strings; conatenating this list returns the original string if preserve_case=False\n        \"\"\"        \n        # Try to ensure unicode:\n        try:\n            s = unicode(s)\n        except UnicodeDecodeError:\n            s = str(s).encode('string_escape')\n            s = unicode(s)\n        # Fix HTML character entitites:\n        s = self.__html2unicode(s)\n        # Tokenize:\n        words = word_re.findall(s)\n        # Possible alter the case, but avoid changing emoticons like :D into :d:\n        if not self.preserve_case:            \n            words = map((lambda x : x if emoticon_re.search(x) else x.lower()), words)\n        return words\n\n    def tokenize_random_tweet(self):\n        \"\"\"\n        If the twitter library is installed and a twitter connection\n        can be established, then tokenize a random tweet.\n        \"\"\"\n        try:\n            import twitter\n        except ImportError:\n            print \"Apologies. The random tweet functionality requires the Python twitter library: http://code.google.com/p/python-twitter/\"\n        from random import shuffle\n        api = twitter.Api()\n        tweets = api.GetPublicTimeline()\n        if tweets:\n            for tweet in tweets:\n                if tweet.user.lang == 'en':            \n                    return self.tokenize(tweet.text)\n        else:\n            raise Exception(\"Apologies. I couldn't get Twitter to give me a public English-language tweet. Perhaps try again\")\n\n    def __html2unicode(self, s):\n        \"\"\"\n        Internal metod that seeks to replace all the HTML entities in\n        s with their corresponding unicode characters.\n        \"\"\"\n        # First the digits:\n        ents = set(html_entity_digit_re.findall(s))\n        if len(ents) > 0:\n            for ent in ents:\n                entnum = ent[2:-1]\n                try:\n                    entnum = int(entnum)\n                    s = s.replace(ent, unichr(entnum))\t\n                except:\n                    pass\n        # Now the alpha versions:\n        ents = set(html_entity_alpha_re.findall(s))\n        ents = filter((lambda x : x != amp), ents)\n        for ent in ents:\n            entname = ent[1:-1]\n            try:            \n                s = s.replace(ent, unichr(htmlentitydefs.name2codepoint[entname]))\n            except:\n                pass                    \n            s = s.replace(amp, \" and \")\n        return s\n```\n\n\n```python\nfrom math import log\n\ntok = Tokenizer(preserve_case=False)\n\ndef get_rel_popularity(c_k, c_all):\n    return log(1.0 * c_k / c_all) / log(2)\n\n\ndef print_tokens(tokens, gid = None):\n    group_name = \"overall\"\n    if gid is not None:\n        group_name = \"group %d\" % gid\n    print '=' * 5 + ' ' + group_name + ' ' + '=' * 5\n    for t, n in tokens:\n        print \"%s\\t%.4f\" % (t, n)\n    print\n```\n\n(1) Tokenize the tweets using the tokenizer we provided above named `tok`. Count the number of mentions for each tokens regardless of specific user group.\n\nCall `print_count` function to show how many different tokens we have.\n\nIt should print\n```\nNumber of elements: 8949\n```\n\n\n```python\n#from collections import defaultdict\n#a=defaultdict(int)\n#for u,t in validtext.collect():\n#    p=tok.tokenize(t)\n#    for l in p:\n#        a[l]+=1\n#print len(a)\n```\n\n\n```python\n# your code here\n\ndef usermapping2(u):\n    if u in partition:\n        return partition[u]\n    else:\n        return 7\n    \n#v1=    \nv1=validtext.mapValues(lambda t : set(tok.tokenize(t))).reduceByKey(lambda t,t1 : t.union(t1)).map(lambda (u,t) : (usermapping2(u),list(t))).flatMapValues(lambda t : t).cache()\nprint_count(v1.map(lambda (u,t): t ).distinct())\n#combineByKey((lambda t : tok.tokenize(t)),(lambda acc, value: acc.(value)),(lambda acc1, acc2: acc1.extend(acc2) )).flatMap(lambda (u,t) : t).distinct().count()\n#.flatMapValues(lambda t : list(t))\n\n#.flatMapValues(lambda t : list(t)).map(lambda (u,t) : (t,usermapping2(u))).cache()\n#print_count(v1.map(lambda (t,u): t ).distinct())\n```\n\n    Number of elements:\n\n(2) Tokens that are mentioned by too few users are usually not very interesting. So we want to only keep tokens that are mentioned by at least 100 users. Please filter out tokens that don't meet this requirement.\n\nCall `print_count` function to show how many different tokens we have after the filtering.\n\nCall `print_tokens` function to show top 20 most frequent tokens.\n\nIt should print\n```\nNumber of elements: 44\n===== overall =====\n:\t1388.0000\nrt\t1237.0000\n.\t826.0000\n\u2026\t673.0000\nthe\t623.0000\ntrump\t582.0000\nto\t499.0000\n,\t489.0000\na\t404.0000\nis\t376.0000\nin\t297.0000\nof\t292.0000\nand\t288.0000\nfor\t281.0000\n!\t269.0000\n?\t210.0000\non\t195.0000\ni\t192.0000\nyou\t191.0000\nthis\t190.0000\n```\n\n\n```python\n# your code here\n\n#od3=validtext.filter(lambda (u,t) : u in partition)\n#od4=validtext.filter(lambda (u,t) : u not in partition)\n\n#od1=validtext.flatMapValues(lambda t: list(set(tok.tokenize(t)))).map(lambda (u,t) : (t,u)).groupByKey().mapValues(lambda x: set([a for a in x])).cache()\n#ordered_tokens=od1.mapValues(lambda x: len(x)).filter(lambda (t,ul) : ul>=100)\n#print_count(ordered_tokens)\n#print_tokens(ordered_tokens.takeOrdered(20,key = lambda x: -x[1]))\n\nv2=v1.map(lambda (t,u) : (u,1)).reduceByKey(lambda a,b : a+b).filter(lambda (t,ul) : ul>=100).cache()\nprint_count(v2)\nprint_tokens(v2.takeOrdered(20,key = lambda x: -x[1]))\n```\n\n    Number of elements: 52\n    ===== overall =====\n    :\t1386.0000\n    rt\t1237.0000\n    .\t865.0000\n    \\\t745.0000\n    the\t621.0000\n    trump\t595.0000\n    x80\t545.0000\n    xe2\t543.0000\n    to\t499.0000\n    ,\t489.0000\n    xa6\t457.0000\n    a\t403.0000\n    is\t376.0000\n    in\t296.0000\n    '\t294.0000\n    of\t292.0000\n    and\t287.0000\n    for\t280.0000\n    !\t269.0000\n    ?\t210.0000\n    \n\n\n(3) For all tokens that are mentioned by at least 100 users, compute their relative popularity in each user group. Then print the top 10 tokens with highest relative popularity in each user group. In case two tokens have same relative popularity, break the tie by printing the alphabetically smaller one.\n\n**Hint:** Let the relative popularity of a token $t$ be $p$. The order of the items will be satisfied by sorting them using (-p, t) as the key.\n\nIt should print\n```\n===== group 0 =====\n...\t-3.5648\nat\t-3.5983\nhillary\t-4.0875\ni\t-4.1255\nbernie\t-4.1699\nnot\t-4.2479\nhttps\t-4.2695\nhe\t-4.2801\nin\t-4.3074\nare\t-4.3646\n\n===== group 1 =====\n#demdebate\t-2.4391\n-\t-2.6202\n&\t-2.7472\namp\t-2.7472\nclinton\t-2.7570\n;\t-2.7980\nsanders\t-2.8838\n?\t-2.9069\nin\t-2.9664\nif\t-3.0138\n\n===== group 2 =====\nare\t-4.6865\nand\t-4.7105\nbernie\t-4.7549\nat\t-4.7682\nsanders\t-4.9542\nthat\t-5.0224\nin\t-5.0444\ndonald\t-5.0618\na\t-5.0732\n#demdebate\t-5.1396\n\n===== group 3 =====\n#demdebate\t-1.3847\nbernie\t-1.8480\nsanders\t-2.1887\nof\t-2.2356\nthat\t-2.3785\nthe\t-2.4376\n\u2026\t-2.4403\nclinton\t-2.4467\nhillary\t-2.4594\nbe\t-2.5465\n\n===== group 4 =====\nhillary\t-3.7395\nsanders\t-3.9542\nof\t-4.0199\nclinton\t-4.0790\nat\t-4.1832\nin\t-4.2143\na\t-4.2659\non\t-4.2854\n.\t-4.3681\nthe\t-4.4251\n\n===== group 5 =====\ncruz\t-2.3861\nhe\t-2.6280\nare\t-2.7796\nwill\t-2.7829\nthe\t-2.8568\nis\t-2.8822\nfor\t-2.9250\nthat\t-2.9349\nof\t-2.9804\nthis\t-2.9849\n\n===== group 6 =====\n@realdonaldtrump\t-1.1520\ncruz\t-1.4532\nhttps\t-1.5222\n!\t-1.5479\nnot\t-1.8904\n\u2026\t-1.9269\nwill\t-2.0124\nit\t-2.0345\nthis\t-2.1104\nto\t-2.1685\n\n===== group 7 =====\ndonald\t-0.6422\n...\t-0.7922\nsanders\t-1.0282\ntrump\t-1.1296\nbernie\t-1.2106\n-\t-1.2253\nyou\t-1.2376\nclinton\t-1.2511\nif\t-1.2880\ni\t-1.2996\n```\n\n\n```python\n# your code here\ndef popfn((t,c)):\n    #tmp=0\n    #if u[1][0]>0:\n    tmp=get_rel_popularity(c,ordt[t])\n    return ((-tmp,t),tmp)\n\n#def tokenprint(par_text,it):\n#    p1=par_text.join(ordered_tokens).map(popfn).sortByKey().map(lambda (u,v) : (u[1],v)).take(10)\n#    print_tokens(p1,it)\n#    return p1\n\nordt=v2.collectAsMap()\n#[r[0] for r in v2.collect()]\nv3=v1.filter(lambda (p,t) : t in ordt).cache()\n\nbm=-100\ncm=-100\ndm=-100\nbg=7\ncg=7\ndg=7    \n\nfor it in range(0,8):\n    p1=v3.filter(lambda (p,t) : p==it).map(lambda (p,t) : (t,1)).reduceByKey(lambda a,b : a+b).map(popfn).sortByKey().map(lambda (u,v) : (u[1],v)).take(10)\n    print_tokens(p1,it)\n    \n    if it!=7:\n        for t,m in p1:\n            if \"bernie\" in t and m>bm:\n                bm=m\n                bg=it\n            if \"sanders\" in t and m>bm:\n                bm=m\n                bg=it\n            if \"ted\" in t and m>cm:\n                cm=m\n                cg=it\n            if \"cruz\" in t and m>cm:\n                cm=m\n                cg=it  \n            if \"donald\" in t and m>dm:\n                dm=m\n                dg=it\n            if \"trump\" in t and m>dm:\n                dm=m\n                dg=it\n\n#od2=od1.filter(lambda (t,u) : t in ordt).mapValues(lambda x : filter(lambda a : a in partition,x)).cache()\n\n\n\n\n#for it in range(0,7):\n#    pt=tokenprint(od2.mapValues(lambda x:len(set(filter(lambda l : partition[l]==it,x)))).filter(lambda (u,v) : v>0),it)\n    '''for t,m in pt:\n        if t==\"bernie\" and m>bm:\n            bm=m\n            bg=it\n        if t==\"sanders\" and m>bm:\n            bm=m\n            bg=it\n        if t==\"ted\" and m>cm:\n            cm=m\n            cg=it\n        if t==\"cruz\" and m>cm:\n            cm=m\n            cg=it  \n        if t==\"donald\" and m>dm:\n            dm=m\n            dg=it\n        if t==\"trump\" and m>dm:\n            dm=m\n            dg=it\n        if t==\"@realdonaldtrump\" and m>dm:\n            dm=m\n            dg=it'''\n    \n#placeholder=tokenprint(od1.mapValues(lambda x:len(set(filter(lambda l : l not in partition,x)))),7) \n```\n\n    ===== group 0 =====\n    ...\t-3.5648\n    at\t-3.5983\n    hillary\t-4.0484\n    bernie\t-4.1430\n    not\t-4.2479\n    he\t-4.2574\n    i\t-4.2854\n    s\t-4.3309\n    are\t-4.3646\n    in\t-4.4021\n    \n    ===== group 1 =====\n    #demdebate\t-2.4391\n    -\t-2.6202\n    clinton\t-2.7174\n    &\t-2.7472\n    amp\t-2.7472\n    ;\t-2.7980\n    sanders\t-2.8745\n    ?\t-2.9069\n    in\t-2.9615\n    if\t-2.9861\n    \n    ===== group 2 =====\n    are\t-4.6865\n    and\t-4.7055\n    bernie\t-4.7279\n    at\t-4.7682\n    sanders\t-4.9449\n    in\t-5.0395\n    donald\t-5.0531\n    a\t-5.0697\n    #demdebate\t-5.1396\n    that\t-5.1599\n    \n    ===== group 3 =====\n    #demdebate\t-1.3847\n    bernie\t-1.8535\n    sanders\t-2.1793\n    of\t-2.2356\n    t\t-2.2675\n    clinton\t-2.4179\n    hillary\t-2.4203\n    the\t-2.4330\n    xa6\t-2.4962\n    that\t-2.5160\n    \n    ===== group 4 =====\n    hillary\t-3.8074\n    sanders\t-3.9449\n    of\t-4.0199\n    what\t-4.0875\n    clinton\t-4.0959\n    at\t-4.1832\n    in\t-4.2095\n    a\t-4.2623\n    on\t-4.2854\n    '\t-4.2928\n    \n    ===== group 5 =====\n    cruz\t-2.3344\n    he\t-2.6724\n    will\t-2.7705\n    are\t-2.7796\n    the\t-2.8522\n    is\t-2.8822\n    that\t-2.9119\n    this\t-2.9542\n    for\t-2.9594\n    of\t-2.9804\n    \n    ===== group 6 =====\n    @realdonaldtrump\t-1.1520\n    cruz\t-1.4657\n    n\t-1.4877\n    !\t-1.5479\n    not\t-1.8904\n    xa6\t-1.9172\n    xe2\t-1.9973\n    /\t-2.0238\n    x80\t-2.0240\n    it\t-2.0506\n    \n    ===== group 7 =====\n    donald\t-0.6471\n    ...\t-0.7922\n    sanders\t-1.0380\n    what\t-1.1178\n    trump\t-1.1293\n    bernie\t-1.2044\n    you\t-1.2099\n    -\t-1.2253\n    if\t-1.2602\n    clinton\t-1.2681\n    \n\n\n(4) (optional, not for grading) The users partition is generated by a machine learning algorithm that tries to group the users by their political preferences. Three of the user groups are showing supports to Bernie Sanders, Ted Cruz, and Donald Trump. \n\nIf your program looks okay on the local test data, you can try it on the larger input by submitting your program to the homework server. Observe the output of your program to larger input files, can you guess the partition IDs of the three groups mentioned above based on your output?\n\n\n```python\n# Change the values of the following three items to your guesses\nusers_support = [\n    (bg, \"Bernie Sanders\"),\n    (cg, \"Ted Cruz\"),\n    (dg, \"Donald Trump\")\n]\n\nfor gid, candidate in users_support:\n    print \"Users from group %d are most likely to support %s.\" % (gid, candidate)\n#t1=timeit.default_timer()\n#print t1-t2\n```\n\n    Users from group 3 are most likely to support Bernie Sanders.\n    Users from group 6 are most likely to support Ted Cruz.\n    Users from group 6 are most likely to support Donald Trump.\n\n", "meta": {"hexsha": "0f1ef23590ed1c54937f483c56be9196d4de03f6", "size": 36841, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Code/twitter_sentiment_analysis.ipynb", "max_stars_repo_name": "vnnsrk/Twitter-Sentiment-Analysis", "max_stars_repo_head_hexsha": "2edf68dcdb61bc3e8d1eb98caa31e45510ca7e08", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-05-28T15:36:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-17T15:11:42.000Z", "max_issues_repo_path": "Code/twitter_sentiment_analysis.ipynb", "max_issues_repo_name": "vnnsrk/Twitter-Sentiment-Analysis", "max_issues_repo_head_hexsha": "2edf68dcdb61bc3e8d1eb98caa31e45510ca7e08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/twitter_sentiment_analysis.ipynb", "max_forks_repo_name": "vnnsrk/Twitter-Sentiment-Analysis", "max_forks_repo_head_hexsha": "2edf68dcdb61bc3e8d1eb98caa31e45510ca7e08", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-06-27T15:22:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-04T09:33:10.000Z", "avg_line_length": 31.2741935484, "max_line_length": 450, "alphanum_fraction": 0.5037051112, "converted": true, "num_tokens": 7301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24508501313237172, "lm_q2_score": 0.13296424706933604, "lm_q1q2_score": 0.03258754423912414}}
{"text": "```python\n%load_ext autoreload\n%autoreload 2\n%matplotlib inline\n```\n\n\n```python\nimport os\nimport sys\nfrom typing import Tuple\n\nfrom dataclasses import dataclass\n\nif '' in sys.path:\n    sys.path.remove('')\n\nmodule_path = os.path.abspath(os.path.join('../python'))\nif module_path not in sys.path:\n    sys.path.append(module_path)\n\nimport networkx as nx\n\nfrom graphPlot import drawGraph, setCanvas\nfrom const import *\n\nsetCanvas()\n```\n\n# **Tensor Field Network** (and other ConvNet Generalisations)\n\n*TDLS - Feb 11. 2019*\n\n### **Chris Dryden**\n\n- christopher.paul.dryden@gmail.com\n\n- github.com/chrisdryden\n\n### **Peng Cheng**\n\n- pc175@uowmail.edu.au\n\n- github.com/tribbloid\n\n---\n\nNotebook & sourcecode: [https://github.com/tribbloid/convnet-abstraction/tree/master/slide]()\n\n## **Overview**\n\n\n```python\n\ng = nx.DiGraph(directed=True)\n\nschNet = \"schNet\\n(Nature\\nCommunication\\n2016)\"\ngroupInv = \"Group Equivariant ConvNet\\n(ICML 2016)\"\nsteerable = \"Steerable CNNs\\n(ICLR 2017)\"\nharmonic = \"Harmonic Net\\n(CVPR 2017)\"\nspherical = \"Spherical CNNs\\n(ICLR 2018 best paper)\"\ntensorField = \"*Tensor Field Net*\\n(not peer-reviewed!)\"\ncgNet = \"Clebsch-Gordan Net\\n(NIPS 2018)\"\nthreeDSteerable = \"3D Steerable CNNs\\n(NIPS 2018)\"\n\ng.add_edge(schNet, tensorField)\ng.add_edge(groupInv, steerable)\ng.add_edge(harmonic, spherical)\ng.add_edge(steerable, spherical)\ng.add_edge(spherical, tensorField)\ng.add_edge(tensorField, cgNet)\ng.add_edge(tensorField, threeDSteerable)\n\ndrawGraph(g)\n\nplt.show()\n```\n\n## Pre-ConvNet (1960-1987)\n\n\n\n\n## Pre-ConvNet - Linear/Fully Connected/~~Dense/Perceptron~~ Layer\n\nIn pursuing of unbounded representation/approximation power\n\n---\n\n\\begin{align}\n& f_+(y) = \\Phi \\Big( f(x) \\Big) &= \\phi \\Big( \\sum_{x \\in \\text{domain}} f(x) w(x, y) \\Big) \\\\\n& &= \\phi \\Big( \\bbox[yellow]{< f(x), w(x, y) >_x} \\Big)\n\\end{align}\n\n($w$ are weight of neurons)\n\n## Pre-ConvNet - Linear/Fully Connected Layer\n\n\n\n```python\n\n\ng = nx.DiGraph(directed=True)\n\ng.add_edge(\"$f(x)$\", \"== layer ==\")\ng.add_edge(\"== layer ==\", \"$f_+(y)$\")\ng.add_edge(\"$f_+(y)$\", \" == layer ==\")\ng.add_edge(\" == layer ==\", \"$f_{++}(.)$\")\ng.add_edge(\"$f_{++}(.)$\", \"...\")\n\ndot = \"$f(.)$\\ninput signal\"\nfc = \"$<f(x), w(x, y)> d x$\\nlinear\"\nnl = \"$\\phi(<f(x), w(x, y)> d x)$\\nactivation\"\ndot2 = \"$f_+(y)$\\nhigh-level features\"\n# hw = \"highway?\"\n\ng.add_edge(dot, fc)\ng.add_edge(fc, nl)\ng.add_edge(nl, dot2)\n\ng2 = g.copy()\n\ng2.add_edge(dot, \"$f(x)$\", wedge=True)\ng2.add_edge(dot2, \"$f_+(y)$\", wedge=True)\n\ndrawGraph(g2, g, font_family='humor sans')\n\nplt.show()\n```\n\n## Pre-ConvNet - Linear/Fully Connected Layer\n\n\n\n---\n \n[*] Image courtesy https://www.quora.com/What-is-the-difference-between-equivariance-and-invariance-in-Convolution-neural-networks\n\n## Invariant Layer / Bag-of-words?\n\n- Don't do this\n\n\n\n---\n\n[*] Image Courtesy: https://www.amazon.ca/Pablo-Art-Masters-Julie-Birmant/dp/1906838941\n\n\n## Data Augmentation\n\n- Good catch\n\n\n\n\n## Data Augmentation\n\n- Too slow in practice\n    - In **convex case** SGD \"theoretically probably\" converges equally fast\n    - otherwise it \"kind of works\" but with much less efficiency\n\n--- \n\n- Time & space complexity increase exponentially with the dimensionality of augmentation\n\n|  |\n| :---: |\n| 2D translation |\n\n\n## Data Augmentation\n\n- Time & space complexity increase exponentially with the dimensionality of augmentation\n\n|  |\n| :---: |\n| 2D translation x 1D rotation, no gravity |\n\n\n## Data Augmentation\n\n- Time & space complexity increase exponentially with the dimensionality of augmentation\n\n|  |\n| :---: |\n| 2D translation $\\times$ 1D rotation, gravity perpendicular to domain |\n\n\n## Data Augmentation\n\n- Time & space complexity increase exponentially with the dimensionality of augmentation\n\n|  |\n| :---: |\n| 3D rotation\n\n\n## Data Augmentation\n\n- Time & space complexity increase exponentially with the dimensionality of augmentation\n\n|  |\n| :---: |\n| 4D affine transformations |\n\n---\n\n[*] Image Courtesy: AIRR https://thedroneracingleague.com/airr/\n\n## Data Augmentation\n\n- Time & space complexity increase exponentially with the dimensionality of augmentation\n\n|  |\n| :---: |\n| 3D translation $\\times$ 3D rotation |\n\n\n## Data Augmentation\n\n- Time & space complexity increase exponentially with the dimensionality of augmentation\n\n|  |\n| :---: |\n| Air pressure depending on translation |\n\n\n## Data Augmentation\n\nHow about a better idea?\n\n- Instead of augmenting, we hard-bake such prior knowledge into the network to yield identical result!\n\n|  |\n| --- |\n\n\nAugmentation types | Answer\n --- | --- \n2d translation | ConvNet\n**others** | **G-ConvNet**\n- 2d translation + 90$^{\\circ}$ rotation | Group Equivariant CNNs\n- 2d translation + rotation | Harmonic Net\n- 3d rotation | Spherical CNNs\n- 3d translation + rotation | Tensor Field Net\n\n\n\n```python\n\n\n```\n", "meta": {"hexsha": "664cec793a488e2bf783e3d96e6152171d924f0a", "size": 239960, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "slide/A-overview.ipynb", "max_stars_repo_name": "tribbloid/convnet-abstraction", "max_stars_repo_head_hexsha": "8827c1dd8b19462bd0499cd0a8d81a8688e7fc48", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-02-11T20:39:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T13:25:45.000Z", "max_issues_repo_path": "slide/A-overview.ipynb", "max_issues_repo_name": "tribbloid/convnet-abstraction", "max_issues_repo_head_hexsha": "8827c1dd8b19462bd0499cd0a8d81a8688e7fc48", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slide/A-overview.ipynb", "max_forks_repo_name": "tribbloid/convnet-abstraction", "max_forks_repo_head_hexsha": "8827c1dd8b19462bd0499cd0a8d81a8688e7fc48", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-29T11:45:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-29T11:45:30.000Z", "avg_line_length": 492.7310061602, "max_line_length": 131692, "alphanum_fraction": 0.9440031672, "converted": true, "num_tokens": 1371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111088366237647, "lm_q2_score": 0.07921033117343147, "lm_q1q2_score": 0.0325642292438989}}
{"text": "# Introduction to pathway analysis in metabolomics\n\n<b>This pathway analysis tutorial forms part of the Hands-on Data Analysis for Metabolic Profiling course at Imperial College London.</b>\n\nThe topics that are covered in this tutorial are:\n- Compound identifier mapping\n- Over-representation analysis in metabolomics\n- Gene set enrichment analysis in metabolomics\n- Pathway database choice\n- Pathway network visualisation\n\nYou should not focus on understanding every line of code in this tutorial, but rather it should help provide an overview of the key concepts in metabolomics pathway analysis.\n\nPlease make sure you run each cell in order to ensure the code works correctly. \n\n\n```python\n# Import the required packages\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport gseapy\nfrom sklearn.decomposition import PCA\n\n# Import the pathway analysis functions\n# This file contains custom functions to run t-tests and ORA - feel free to check it out and re-use the code!\nimport pathwayfunctions\n```\n\n## Metabolomics data and pathway import\nAll pathway analysis methods require at least a dataset and a set of pathways. First we are going to import the KEGG human pathways and the processed metabolomics dataset we will be working with. It is important to ensure the data has been processed prior to pathway analysis. This includes:\n1. Sample normalisation (e.g. Probabilistic Quotient Normalisation)\n2. Missing value imputation\n3. Log transformation\n4. Centering and scaling the features to mean = 0 and standard deviation = 1\n5. Outlier detection (e.g. using PCA)\n\nFor more details about pre-processing metabolomics data, see here: https://www.intechopen.com/books/metabolomics-fundamentals-and-applications/processing-and-visualization-of-metabolomics-data-using-r\n\n\n\n```python\n# Import pathway database\nKEGG_human_pathways = pd.read_csv(\"KEGG_human_pathways_compounds_R98.csv\", dtype=str, index_col=0)\nReactome_human_pathways = pd.read_csv(\"Reactome_human_pathways_compounds_R76.csv\", dtype=str, index_col=0)\n\n# Import procsesed datasets\ncovid_data = pd.read_csv(\"Su_COVID_metabolomics_processed.csv\", index_col=0)\ncovid_data_KEGG = pd.read_csv(\"Su_COVID_metabolomics_processed_KEGG.csv\", index_col=0)\ncovid_data_CHEBI = pd.read_csv(\"Su_COVID_metabolomics_processed_CHEBI.csv\", index_col=0)\n```\n\nThe dataset we will be working with is from **Su et al. \"Multi-Omics Resolves a Sharp Disease-State Shift between Mild and Moderate COVID-19\".** It is an untargeted mass spectrometry dataset generated by Metabolon containing 133 COVID-19 plasma samples of varying WHO ordinal scale severity and 133 control plasma samples. A total of 1050 compounds were profiled.\n\nSu Y, Chen D, Yuan D, Lausted C, Choi J, Dai CL, et al. Multi-Omics Resolves a Sharp Disease-State Shift between Mild and Moderate COVID-19. Cell. 2020;183: 1479-1495.e20. [doi:10.1016/j.cell.2020.10.037](doi:10.1016/j.cell.2020.10.037)\n\n\n```python\n# Inspect the processed data abundance matrix\n# Note the Group and WHO_status columns at the far right of the matrix\ncovid_data.head(6)\n```\n\nLet's perform PCA to visualise the differences between the COVID and control sample groups. \n\n\n```python\nsns.set_style(\"ticks\")\n\n# Perform a 5-component PCA\npca = PCA(n_components=5).fit_transform(covid_data.iloc[:, :-2])\npca_df = pd.DataFrame(pca)\npca_df.columns = [\"PC \" + str(i) for i in range(1, 6)]\npca_df[\"Group\"] = covid_data[\"Group\"].values\n\n# Use the pairplot function to visualise the transformed data\nsns.pairplot(pca_df.iloc[:, np.r_[0:4, 5]],\n             hue=\"Group\",\n             diag_kind=\"auto\")\nplt.show()\n```\n\nThe PCA pairplot shows the transformed data from different principal components (PCs) plotted against each other. In this dataset, the strongest separation between the groups is captured by PC1 and PC2.\n\n#### Where can I download pathways?\nFor the purposes of this tutorial, we will be using KEGG and Reactome pathway databases provided as files in this folder. It is important to use as up to date resources as possible when running any type of pathway analysis. \n\nIf you wish to download these pathway collections yourself you can do so by:\n\n**KEGG**:\n- Non-programmatic access: Purchasing a KEGG license and downloading pathways via the KEGG FTP site (https://www.kegg.jp/kegg/download/)\n- Programmatic access: Downloading KEGG pathways via the KEGG API (https://www.kegg.jp/kegg/rest/keggapi.html)\n\n**Reactome**:\n- Non-programmatic access: Downloading the Reactome pathways via the Reactome downloads site (https://reactome.org/download-data). You will need the https://reactome.org/download/current/ChEBI2Reactome_All_Levels.txt file.\n\nYou may need to write additional code to properly parse the files into a useable format. The files we will use in this tutorial have already been parsed in the desired format.\n\n\n```python\n# Let's inspect the KEGG pathways file:\nKEGG_human_pathways.head()\n```\n\nThis CSV file contains:\n- **Index column**: contians the KEGG pathway identifiers\n- **Pathway name column**: contains the KEGG pathway names\n- **Compound columns**: Each row of the file contains columns each containing the KEGG compound identifiers for each pathway\n\n## Compound identifier conversion\nThe first step in the pathway analysis workflow is to convert the compound names or identifiers to the identifier type of the pathway database used. In this example, we are using the KEGG database and will be converting componund names to KEGG compound identifiers.\n\nThe MetaboAnalyst name conversion tool allows you to convert between several metabolite identifier types and names.\nhttps://www.metaboanalyst.ca/MetaboAnalyst/upload/ConvertView.xhtml. If you wish to do this in a programmatic manner, you can use the MetaboAnalyst R package. \n\nHave a go at converting the compound names of the Su_compound_names.txt file to KEGG ID's. Inspect the results. As there are 900+ compounds profiled in this dataset, just look at a few examples. The full converted dataset is provided below.\n\n<b>What percentage of the compounds in the dataset are you able to map? Which class(es) of compounds are particularly difficult to map?</b>\n\nFor the purposes of this tutorial, the compound names have already been converted to KEGG and ChEBI identifiers in the covid_data_KEGG and covid_data_CHEBI matrices respectively:\n\n\n```python\ncovid_data_KEGG.head(5)\n```\n\nThe column identifiers beginning with \"C0\" represent KEGG compounds\n\n## Over-representation analysis (ORA)\n\nOver-representation analysis is one of the commonest pathway analysis methods in metabolomics. It tests the null hypothesis that a subset of compounds of interest (e.g. those differentially abundant between study groups) are no more present in a certain biological pathway than background compounds. \n\nWe can build a 2-by-2 contingency table such as the one below, which differentiates between the number of compounds in the dataset which are in a pathway, those that are differentially abundant, and vice versa. \n\n<table><tr>\n<td>   </td>\n<td>   </td>\n</tr></table>\n\nA test statistic and P-value can be determined for each pathway using this contingency table by using a **right-sided Fisher's exact test**. \n\n\\begin{equation}\np = 1 - \\sum_{i=0}^{k-1} \\frac{\\binom{M}{i}\\binom{N-M}{n-i}}{\\binom{N}{n}}\n\\end{equation}\n\nThe essential inputs of ORA are:\n- **Background set** (N)\n- **List of metabolites of interest** (n)\n- **Pathway set** (M represents one pathway)\n\nThe Venn diagram depicts ORA, in which we are testing the significance of the overlap between the pathway and the compounds of interest, **k**. \n\n\n### ORA step 1: Determining the list of compounds of interest\nAs input to ORA, we require a list of compounds of interest, which are usually metabolites that are differentially abundant between study groups.\nWe will obtain this list by using a series of t-tests. \n\nThe function below computes a two-sided t-test for each metabolite in the dataset, testing for a significance in metabolite abundance levels between the COVID and healthy groups. The P-values are then adjusted for multiple-correction testing using the Benjamini-Hochberg FDR method.\n\nThe pathwayfunctions.t_tests() function takes 3 parameters:\n- **Abundance matrix**. This is either covid_data_KEGG or covid_data_CHEBI. \n- **Sample group/classes column**. In the COVID dataframe, this column is called \"Group\"\n- **Multiple testing correction method** (string) e.g. \"fdr_bh\"\n\n\n```python\n# Use the t-test function to compute t-tests \n# Note that for the abundance matrix parameter, we use covid_data_KEGG.iloc[:, :-2] to provide the abundance matrix\n# with the final two columns removed (WHO_status and Group) as these are string columns and not metabolites\nt_test_res = pathwayfunctions.t_tests(covid_data_KEGG.iloc[:, :-2], covid_data_KEGG[\"Group\"], \"fdr_bh\")\n\n# Select differentially abundant metabolites by filtering on the adjusted P-value at \u2264 0.05\nDA_metabolites = t_test_res[t_test_res[\"P-adjust\"] <= 0.05][\"Metabolite\"].tolist()\nprint(t_test_res)\nprint(\"There are\", len(DA_metabolites), \"differentially abundant metabolites in this dataset\")\n```\n\n#### Background set\nThe other essential component of ORA is the background set, or metabolite \"universe\". Our assay-specific background set consists of all the compounds profiled in our dataset:\n\n\n```python\n# Select all the columns in the data matrix apart from the last two (metadata) columns (Group and WHO_status)\nassay_specific_background_set = covid_data_KEGG.iloc[:, :-2].columns.tolist()\nprint(\"The size of the background set is:\", len(assay_specific_background_set), \"compounds\")\n```\n\n### ORA step 2: Running ORA\nNow we are ready to perform ORA with KEGG pathways. The function (code in the pathwayfunctions.py file) loops through each pathway in the pathway database and performs a one-sided Fisher's exact test to compute a test statistic and P-value for the enrichment of each pathway.\n\nThe pathwayfunctions.over_representation_analysis() function takes 3 parameters:\n- **List of differentially abundant metabolites** (the compound identifiers must match those in the pathways)\n- **Background set**: list of compound identifiers forming the background set\n- **Pathways dataframe**: pandas DataFrame containing pathway identifiers and their respective compounds\n\n\n```python\nora_res = pathwayfunctions.over_representation_analysis(DA_metabolites, assay_specific_background_set, KEGG_human_pathways)\n```\n\nInspect the ORA results. The 'hits' column shows the fraction of DA metabolites present in the pathway (note the pathway is only composed of compounds which are also present in the background set). The 'coverage' column shows the fraction of pathway metabolites in the background list based on the total number of metabolites in a specific KEGG pathway.\n\n\n```python\n# Look at the top 10 pathways ranked by P-value\nora_res.sort_values(by=\"P-value\").head(10)\n```\n\n<b>What do you think about the level of pathway coverage in this dataset? Would you recommend pathway analysis for datasets with fewer than 100 metabolites profiled?</b>\n\nLet's plot the top 10 pathways ordered by P-value:\n\n\n```python\nplt.style.use(\"seaborn\")\n\n# we can use a colourmap to colour the bars corresponding to the P-values\ncmap = sns.color_palette(\"mako_r\", as_cmap=True)\nnorm = plt.Normalize(vmin=0, vmax=0.4)\n\n# plot the top 10 pathways\ntop_10_ora_res = ora_res.sort_values(by=\"P-value\").iloc[0:10, :]\nplt.barh(top_10_ora_res[\"Pathway_name\"], top_10_ora_res[\"P-value\"], color=cmap(norm(top_10_ora_res[\"P-value\"])))\nplt.xlabel(\"P-value\")\nplt.ylabel(\"Pathway name\")\n\n# plot a vertical line to represent P \u2264 0.05\nplt.axvline(0.05, color=\"black\", linestyle='--')\nplt.title(\"Top 10 enriched pathways (assay-specific background set)\")\nplt.show()\n```\n\n#### What happens if we use a non-assay specific background set instead?\nThis is a common pitfall of metabolomics pathway analysis, and the default background set often consists of all compounds in a pathway database, for example.\n\nHere we will use all KEGG compounds as the non-assay specific background set:\n\n\n```python\n# create the non-specific background set by selecting all the unique compounds mapped to KEGG pathways\nnon_specific_background_set = list(set([x for x in KEGG_human_pathways.iloc[:, 1:].values.flatten() if x is not np.nan]))\n```\n\nNow we will perform ORA again with the non-specific background set\n\n\n```python\n# perform ORA using non-specific background set\nora_res_non_specific_background = pathwayfunctions.over_representation_analysis(DA_metabolites, non_specific_background_set, KEGG_human_pathways)\n```\n\nPlot the results of ORA using the assay-specific vs. non-assay-specific background set\n\n\n```python\n# plotting code\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))\nplt.style.use(\"seaborn\")\ntop_10_ora_res_non_specific = ora_res_non_specific_background.sort_values(by=\"P-value\").iloc[0:10, :]\nax1.barh(top_10_ora_res_non_specific[\"Pathway_name\"], top_10_ora_res_non_specific[\"P-value\"])\nax1.set_xlabel(\"P-value\")\nax1.set_ylabel(\"Pathway name\")\nax1.set_title(\"Top 10 enriched pathways \\n (non-specific background set)\")\n\n# adding labels for the p-values \nfor index, data in enumerate(top_10_ora_res_non_specific[\"P-value\"]):\n    ax1.text(data+0.000001, index, s=round(top_10_ora_res_non_specific[\"P-value\"].tolist()[index], 6))\n\n# Ensures pathways are the same in both results (non specific background set can have additional pathways)\nintersect = (set(ora_res[\"Pathway_ID\"].tolist()) & set(ora_res_non_specific_background[\"Pathway_ID\"].tolist()))\nora_res_all = ora_res_non_specific_background.loc[ora_res_non_specific_background[\"Pathway_ID\"].isin(intersect)]\n\n# convert p-values to -log10 scale\nora_res_pvals = np.negative(np.log10(ora_res[\"P-value\"].tolist()))\nora_res_all_pvals = np.negative(np.log10(ora_res_all[\"P-value\"].tolist()))\n\nsns.regplot(x=ora_res_pvals, y=ora_res_all_pvals, ax=ax2, line_kws={\"color\": \"red\"})\nax2.set_ylabel(\"-log10 P-value (Non-assay specific background set)\")\nax2.set_xlabel(\"-log10 P-value (Assay-specific background set)\")\nax2.set_title(\"Comparison of P-values\")\nax2.axhline(y=-np.log10(0.05), linewidth=1, color='black', linestyle='--')\nax2.axvline(x=-np.log10(0.05), linewidth=1, color='black', linestyle='--')\nax2.set(ylim=(0, 10), xlim=(0, 5))\n\nplt.show()\n```\n\n\n```python\n# Look at the results of the top 10 enriched pathways using the non-assay-specific background set. \ntop_10_ora_res_non_specific\n```\n\n<b>What do you notice about the P-values obtained using the assay-specific background set as opposed to the non-assay specific background set containing all KEGG compounds?</b>\n\n## Comparing pathway databases\nHow do pathway analysis results differ when using different pathway databases? Let's compare ORA results obtained using KEGG and Reactome human pathway databases:\n\n\n```python\n# Re-run and save the ORA KEGG results for comparison \nora_KEGG = pathwayfunctions.over_representation_analysis(DA_metabolites,\n                                                         assay_specific_background_set,\n                                                         KEGG_human_pathways)\n```\n\nFirst we need to determine differential metabolites for the dataset with Reactome identifiers (ChEBI). We perform a series of t-tests on the metabolites and keep only those with an adjusted P-value \u2264 0.05.\n\n\n```python\nt_test_res_reactome = pathwayfunctions.t_tests(covid_data_CHEBI.iloc[:, :-2], covid_data_CHEBI[\"Group\"], \"fdr_bh\")\nDA_metabolites_reactome = t_test_res_reactome[t_test_res_reactome[\"P-adjust\"] <= 0.05][\"Metabolite\"].tolist()\nprint(len(DA_metabolites_reactome), \"differential metabolites using Reactome with a total background set size of:\", len(covid_data_CHEBI.iloc[:, :-2].columns.tolist()))\n```\n\nNow compute ORA with the Reactome pathways. We first take the columns from the \"covid_data_CHEBI\" file to use as the Reactome assay-specific background set.\n\n\n```python\nreactome_assay_specific_bgset = covid_data_CHEBI.iloc[:, :-2].columns.tolist()\nora_Reactome = pathwayfunctions.over_representation_analysis(DA_metabolites_reactome, reactome_assay_specific_bgset, Reactome_human_pathways)\n```\n\nPlot the ORA results from using KEGG vs. Reactome pathways:\n\n\n```python\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6), sharex=True)\nplt.style.use(\"seaborn\")\ntop_10_ora_res_kegg = ora_KEGG.sort_values(by=\"P-value\").iloc[0:10, :]\nax1.barh(top_10_ora_res_kegg[\"Pathway_name\"], top_10_ora_res_kegg[\"P-value\"], color=\"tab:cyan\")\nax1.set_xlabel(\"P-value\")\nax1.set_ylabel(\"Pathway name\")\nax1.set_title(\"Top 10 enriched pathways (KEGG)\")\nax1.axvline(0.05, color=\"black\", linestyle='--')\n\ntop_10_ora_res_reactome = ora_Reactome.sort_values(by=\"P-value\").iloc[0:10, :]\nax2.barh(top_10_ora_res_reactome[\"Pathway_name\"], top_10_ora_res_reactome[\"P-value\"], color=\"tab:red\")\nax2.set_xlabel(\"P-value\")\nax2.set_ylabel(\"Pathway name\")\nax2.set_title(\"Top 10 enriched pathways (Reactome)\")\nplt.tight_layout()\nax2.axvline(0.05, color=\"black\", linestyle='--')\n\nplt.show()\n```\n\nPathway databases are always evolving, so an important consideration is to use the lastest version of a database when running your analysis. \n\n# Your turn! \ud83d\udcda\n## Use ORA to find pathways enriched in severe vs. mild COVID\nWe previously looked at pathway analysis to find out which pathways differ between COVID and non-COVID patients. Now it's your turn to use the code presented in this notebook to run an ORA analysis. \n\nFirst, the metabolite abundance matrix is filtered only for those patients with WHO status 1-2 (mild) or 5-7 (severe):\n\n\n```python\ncovid_KEGG_mild_severe = covid_data_KEGG[covid_data_KEGG[\"WHO_status\"].isin([\"1-2\", \"5-7\"])]\n# There are 45 mild covid patients and 28 severe covid patients\n```\n\n\n```python\n# This bit of code is dropping the old group column (COVID vs. non-COVID) and adding a new column (mild vs. severe)\ncovid_KEGG_mild_severe = covid_KEGG_mild_severe.drop(\"Group\", axis=1)\ncovid_KEGG_mild_severe[\"Group\"] = [\"Severe\" if i == \"5-7\" else \"Mild\" for i in covid_KEGG_mild_severe[\"WHO_status\"]]\n```\n\n\n```python\n# This is doing the same thing as above - filtering the samples - but using the Reactome compound identifiers instead\ncovid_Reactome_mild_severe = covid_data_CHEBI[covid_data_CHEBI[\"WHO_status\"].isin([\"1-2\", \"5-7\"])]\ncovid_Reactome_mild_severe = covid_Reactome_mild_severe.drop(\"Group\", axis=1)\ncovid_Reactome_mild_severe[\"Group\"] = [\"Severe\" if i == \"5-7\" else \"Mild\" for i in covid_Reactome_mild_severe[\"WHO_status\"]]\n```\n\n\n```python\ncovid_KEGG_mild_severe.head()\n```\n\nComplete the code in the following cells. You will need to use the functions:\n<pre>\npathwayfunctions.t_tests(abundance_matrix, group_column, multiple_correction_method)\npathwayfunctions.over_representation_analysis(DA_metabolite_list, background_list, pathway_set)\n</pre>\n\nYour code will need to:\n1. Use the t-test function to run t-tests on all the metabolites\n2. Filter the t-test results for only those metabolites with adjusted P-value \u2264 a threshold\n3. Obtain the background set for the dataset, taking the column names (=metabolites) present in the dataset matrix\n4. Run ORA  \n\n\n\n```python\n# STEP ONE\n# Use the t-test function to compute t-tests \n# Use \"fdr_bh\" (Benjamini-Hochberg method) as the parameter for multiple testing correction for the t-test function\nt_testres_covid_severity = \n\n# Select differentially abundant metabolites by filtering on the adjusted P-value at \u2264 0.05\nDA_metabolites_covid_severity = \n\nprint(len(DA_metabolites_covid_severity))\n\n# Obtain the background set \nassay_specific_background_set_covid_severity = \n```\n\n\n```python\n# STEP TWO\n# Run ORA using the \n# - list of DA metabolites\n# - background list\n# - pathways: KEGG (KEGG_human_pathways) or Reactome (Reactome_human_pathways)\nora_res_covid_severity = \n```\n\nIf you are stuck, try to re-use the code snippets from the previous ORA analysis above, changing the variable names to those relating to the filtered abundance matrix (containing only severe and mild COVID patients): **covid_KEGG_mild_severe**\n\n\n```python\n# Use the pandas .sort_values() method to sort the ORA results dataframe by pathway p-values\nora_res_covid_severity.sort_values(by=\"P-value\")\n```\n\nRun the following cell to plot your results\n\n\n```python\n# Plot the top 10 enriched pathways\nplt.style.use(\"seaborn\")\n\n# we can use a colourmap to colour the bars corresponding to the P-values\ncmap = sns.color_palette(\"YlOrBr_r\", as_cmap=True)\nnorm = plt.Normalize(vmin=0, vmax=0.4)\n\n# plot the top 10 pathways\ntop_10_ora_res = ora_res_covid_severity.sort_values(by=\"P-value\").iloc[0:10, :]\nplt.barh(top_10_ora_res[\"Pathway_name\"], top_10_ora_res[\"P-value\"], color=cmap(norm(top_10_ora_res[\"P-value\"])))\nplt.xlabel(\"P-value\")\nplt.ylabel(\"Pathway name\")\n\n# plot a vertical line to represent P \u2264 0.05\nplt.axvline(0.05, color=\"black\", linestyle='--')\nplt.title(\"Top 10 enriched pathways in severe vs. mild COVID patients\")\nplt.show()\n```\n\n- What are the top 5 enriched pathways? Do they differ from the top 5 enriched in COVID vs. non-COVID patients?\n- Try the analysis with Reactome vs. KEGG pathways. How do the results differ? Which would you prefer to use?\n\nThe answers for this exercise can be found in the \"ORA_exercise_answers.txt\" file.\n\n## m(GSEA)\nOver-representation analysis is a fast and straightforward approach to pathway analysis, but has a few **limitations**. These include:\n- Having to pre-select metabolites of interest (based on a hard threshold such as P-value cutoff)\n- Not taking into account the level of differences in these metabolites between study groups (e.g. the fold-change)\n\nFunctional class scoring approaches such as gene set enrichment analysis (GSEA)* have been developed to overcome these challenges. They take all measured metabolites as input, which allows small but coordinated changes in the metabolites present in a pathway to be detected. \n\nHere we will use gseapy to perform this. gseapy can be adapted for metabolomics data simply by using metabolite data and pathways as input. The statistical test and assumptions remain the same. \n\nFirst we will create a ranked list of metabolites (based on differences in abundance between COVID and control groups) as input using the t-test function above that we also used to determine the list of metabolites of interest for ORA. We will rank the metabolites based on the t-test statistic. Other common ranking metrics include fold change, signal-to-noise ratio, or P-value and fold change multiplied together (signed fold-change). \n\n<sub>*Subramanian A, Tamayo P, Mootha VK, Mukherjee S, Ebert BL, Gillette MA, et al. Gene set enrichment analysis: A knowledge-based approach for interpreting genome-wide expression profiles. Proc Natl Acad Sci U S A. 2005;102: 15545\u201315550. doi:10.1073/pnas.0506580102</sub>\n\n### m(GSEA) step 1: Creating the ranked list of metabolites\nWe use the same t-test function as in ORA, but instead of using the results to filter the adjusted P-values on, we use the *t-statistic* for all the metabolites in the dataset to rank them.\n\n\n```python\nt_test_res = pathwayfunctions.t_tests(covid_data_KEGG.iloc[:, :-2], covid_data_KEGG[\"Group\"], \"fdr_bh\", return_stat=True)\nranked_list = t_test_res[[\"Metabolite\", \"t-statistic\"]]\nranked_list.sort_values(by=\"t-statistic\")\n```\n\n### m(GSEA) step 2: Running GSEA\n\nNext we will run m(GSEA) using the gseapy package. The inputs for this are:\n- The **ranked list** we just created (in the form of a pandas series)\n- A **gmt format file containing the pathways** (see format details here: https://software.broadinstitute.org/cancer/software/gsea/wiki/index.php/Data_formats)\n- The minimum size for a pathway to be included in the analysis (optional parameter)\n\nThe outputs are stored in the GSEA_Prerank folder\n\nThe GMT file is very similar to the pathway files we used for ORA. The index column containing the pathway identifiers simply becomes the first column:\n\n\n```python\npd.read_csv(\"KEGG_human_pathways_compounds_R98.gmt\", sep=\"\\t\", header=None).head(3)\n```\n\n\n```python\n# Run GSEA prerank using our ranked list of metabolites\nmgsea_res = gseapy.prerank(rnk=ranked_list,\n               gene_sets='KEGG_human_pathways_compounds_R98.gmt',\n               min_size=3, # change this as you wish\n               verbose=True,\n               outdir=None) # specify an output directory path if you want to download the full results\n```\n\nLet's explore the m(GSEA) results:\n\n\n```python\n# sort pathways by lowest FDR\nmgsea_res_df = mgsea_res.res2d.sort_values(by=\"fdr\").head(10)\n\n# add a column with the full pathway names to the dataframe\nmgsea_res_df[\"pathway_name\"] = mgsea_res_df.index.map(dict(zip(KEGG_human_pathways.index, KEGG_human_pathways[\"Pathway_name\"])))\ncol = mgsea_res_df.pop(\"pathway_name\")\nmgsea_res_df.insert(0, \"pathway_name\", col)\n```\n\n\n```python\nmgsea_res_df.head(10)\n```\n\nWhat do the extra columns in this dataframe mean? The following terms are specific to GSEA-based analyses:\n- **\"es\", Enrichment score**: GSEA enrichment score calculated using a weighted Kolmogorov-Smirnov statistic\n- **\"nes\", Normalised enrichment score**: Enrichment score normalised by the pathway size\n- **\"ledge_genes\", Leading edge genes**: These are the genes (or metabolites) that contributed to the enrichment of the pathway\n\nNow we will create some plots to examine the mGSEA results. We can plot the standard GSEA enrichment plot using the gseaplot function:\n\n\n```python\nfrom gseapy.plot import gseaplot\n\n# to save your figure, make sure that ofname corresponds to a valid file path on your computer\n\n# Here we are plotting the pathway with the lowest FDR, \"Sphingolipid signaling pathway - Homo sapiens (human)\"\ngseaplot(rank_metric=mgsea_res.ranking,\n         term=\"Sphingolipid signaling pathway - Homo sapiens (human)\",\n         **mgsea_res.results[\"hsa04071\"],\n         ofname=None)\n```\n\n<b>What does the m(GSEA) plot show?</b>\n\nThe m(GSEA) algorithm walks down the rank-ordered list of metabolites, each time adding a value if a metabolite in the pathway of interest is encountered (the magnitude of this value is based on the correlation of the metabolite with the phenotype (i.e. our t-statistic)), or subtracting a value if a metabolite encountered is not in the pathway of interest. \n- The <b>enrichment score</b> is recorded as the maximum deivation from 0 (i.e. the lowest point on the green curve). In this example the enrichment score is negative. As our ranking metric (t-test statistic) compares the means of the COVID samples relative to the controls, this means that a negative enrichment score suggests that the sphingolipid pathway is enriched in COVID patients. \n\n- The blue bars at the far right in the middle of the plot indicate <b>where in the ranked metabolite list the metabolites in the pathway appear</b>. If the bars cluster towards the right of the plot, this indicates they appear at the bottom of the ranked metabolite list and the pathway is negatively enriched. Alternatively, if the bars cluster at the left side of the plot, this means the metabolites appear at the top of the ranked list and the pathway is enriched. \n\n- The bottom part of the plot (ranked list metric) shows how the ranking metric changes as the algorithm walks down the list of genes. A positive ranking metric indicates correlation with the first phenotype (controls), whereas a negative ranking metric indicates a correlation with the second phenotype (COVID).\n\n- The leading edge metabolites (or genes) are those metabolites in the pathway being tested that appear before the maximum deviation from 0 in the case of a positive enrichment score, or after in the case of a negative enrichment score. These are usually the most interesting metabolites in a pathway, as they contribute strongly to the enrichment of the pathway.\n\nLet's compare the top 10 mGSEA results to ORA:\n\n\n```python\n# plotting code\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6), sharex=True)\nplt.style.use(\"seaborn\")\ntop_10_ora_res = ora_res.sort_values(by=\"P-value\").iloc[0:10, :]\nax1.barh(top_10_ora_res[\"Pathway_name\"], top_10_ora_res[\"P-value\"], color=\"tab:purple\")\nax1.set_xlabel(\"P-value\")\nax1.set_ylabel(\"Pathway name\")\nax1.set_title(\"Top 10 enriched pathways (ORA)\")\nax1.axvline(0.05, color=\"black\", linestyle='--')\n\ntop_10_GSEA_res = mgsea_res_df.sort_values(by=\"pval\").iloc[0:10, :]\nax2.barh(top_10_GSEA_res[\"pathway_name\"], top_10_GSEA_res[\"pval\"], color=\"tab:green\")\nax2.set_xlabel(\"P-value\")\nax2.set_ylabel(\"Pathway name\")\nax2.set_title(\"Top 10 enriched pathways (GSEA)\")\nplt.tight_layout()\nax2.axvline(0.05, color=\"black\", linestyle='--')\n\nplt.show()\n```\n\n## Pathway visualisation\n\n### Annotating the KEGG metabolic network with iPath3\n\niPath3 is an open-source web application for pathway visualisation (https://pathways.embl.de/). Go to the iPath web server and select \"Metabolism\" from the main menu:\n \n\nPaste the following information into the \"Element selection\" box:\n\n<pre>\nC00001 #0000ff W20 0.5\nmap00010 #ff0000 W10\nR01148 #800080 W10\n</pre>\n\nAfter submitting the data you should see three separate entities highlighted including a compound, a pathway (glycolysis) and a reaction. \n\n- The first element corresponds to the KEGG compound/reaction/pathway ID\n- The second element is a hex colour code\n- The third element is the width of the node\n- The fourth element ranges from 0-1 and corresponds to the transparency of the node\n\nLet's try another submission with more compounds. This time, we will use the differentially abundant metabolites from the COVID dataset that we used as input for ORA, and visualise them on the KEGG metabolic network. \n\n\n```python\n# Use the t-test function to compute t-tests \nt_test_res = pathwayfunctions.t_tests(covid_data_KEGG.iloc[:, :-2], covid_data_KEGG[\"Group\"], \"fdr_bh\")\n\n# Select differentially abundant metabolites by filtering on the adjusted P-value at \u2264 0.05\nDA_metabolites = t_test_res[t_test_res[\"P-adjust\"] <= 0.05][\"Metabolite\"].tolist()\n```\n\nNow we will put the DA compunds into a **DataFrame**, along with specifications for the node width and colour. Putting these details into a DataFrame will make it easier to paste them all into iPath without having to write each individual element into the text box.\n\n\n```python\nipath_params = pd.DataFrame(DA_metabolites)\nipath_params[\"Colour\"] = \"#ff0000\"\nipath_params[\"Node width\"] = \"W20\"\nipath_params[\"Transparency\"] = 0.6\n```\n\n\n```python\nipath_params.head()\n```\n\nThis is what our output dataframe looks like. We will now save it as a .tsv file and copy the data from here into iPath.\n\n\n```python\nipath_params.to_csv(\"COVID_DA_metabolites_ipath_input.tsv\", sep=\"\\t\")\n```\n\nTry showing 'Advanced options' and experiment with some of the parameters:\n- Select 'Keep original colours'\n- Try changing the default node radius, opacity, and colours\n- Experiment with the species filter. E.g. type \"HSA\" for human pathways, or \"SCE\" for Saccaromyces cerevisiae\n\nYou can export annotated pathway maps created using iPath to an .svg format, and then import these into InkScape or Illustrator to further edit the layers in detail and make publication-quality figures\n\n \n\n#### Additional exercise: Using BioPython to visualise pathways\n\nPlease note, you will need the BioPython and [ReportLab](https://pypi.org/project/reportlab/) packages to run this exercise. \n\n\n```python\nimport Bio\nfrom Bio.KEGG.REST import *\nfrom Bio.KEGG.KGML import KGML_parser\nfrom Bio.Graphics.KGML_vis import KGMLCanvas\nfrom IPython.display import Image, HTML\n```\n\nWe can view KEGG pathway diagrams using the Image function:\n\n\n```python\nImage(kegg_get(\"hsa04071\", \"image\").read())\n\n# try replacing \"hsa04071\" with the name of another KEGG pathway of interest\n```\n\nWe can also view additional information about a pathway, such as the number of genes and compounds it contains:\n\n\n```python\npathway = KGML_parser.read(kegg_get(\"hsa04071\", \"kgml\"))\nprint(pathway)\n```\n\nThe BioPython KGML package allows you to parse KEGG pathway diagrams and add additional features to them. For example, we can highlight the differentially abundant metabolites (or genes) present in a pathway:\n\n\n```python\n# If you are getting a 'URLError' please uncomment the following two lines and run the cell again!\n# import ssl\n# ssl._create_default_https_context = ssl._create_unverified_context\n\n# hsa04071 is the sphingolipid signaling pathway\npathway = KGML_parser.read(kegg_get(\"hsa04071\", \"kgml\"))\npathway_compounds = [cpd.name for cpd in pathway.compounds]\n\n# We will use the list of differentially abundant compounds we used to perform ORA\nDA_metabolites = t_test_res[t_test_res[\"P-adjust\"] < 0.05][\"Metabolite\"].tolist()\nDA_metabolites_kegg_format = [\"cpd:\"+i for i in DA_metabolites]\n\n# and find which of these compounds are present in the sphingolipid signaling pathway\nDA_metabolites_in_pathway = list(set(pathway_compounds) & set(DA_metabolites_kegg_format))\nprint(\"There are\", len(DA_metabolites_in_pathway), \"differentially abundant compounds in the pathway\")\n\n# we are highlighting all differentially abundant compounds in red circles\nfor size, element in zip(range(8, 8+len(pathway.compounds)), pathway.compounds):\n    if element.name in DA_metabolites_in_pathway:\n        for graphic in element.graphics:\n            graphic.width = 20\n            graphic.height = 20\n            graphic.fgcolor = '#FF0000'\n            graphic.bgcolor = '#FF0000'\n\ncanvas = KGMLCanvas(pathway,\n                    import_imagemap=True,\n                    show_genes=False,\n                    label_compounds=False,\n                    fontsize=14,\n                    show_orthologs=False,\n                    show_reaction_entries=False,\n                    label_maps=False,\n                    show_maps=False,\n                    draw_relations=True)\n# saves the pathway diagram as a pdf in the same folder as the notebook\ncanvas.draw(\"pathway_highlighted.pdf\")\n```\n\n<b>To view the highlighted pathway diagram, see the \"pathway_highlighted.pdf\" file that has been saved in the same folder as this notebook.</b>\n\n\nYou can also colour the pathways manually by inputting compound IDs and colours to the KEGG search and colour pathway tool: https://www.genome.jp/kegg/tool/map_pathway2.html\n\n## References\n\nThe aim of this tutorial was to provide an overview of the most commonly used pathway analysis methods in metabolomics. For a more comprehensive understanding of pathway analysis methods in the field, please refer to the references below.\n\n#### Pathway analysis in metabolomics\n1. Wieder C, Frainay C, Poupin N, Rodr\u00edguez-Mier P, Vinson F, Cooke J, et al. Pathway analysis in metabolomics: pitfalls and best practice for the use of over-representation analysis. bioRxiv. 2021; 2021.05.24.445406. doi:10.1101/2021.05.24.445406\n2. Marco-Ramell A, Palau-Rodriguez M, Alay A, Tulipani S, Urpi-Sarda M, Sanchez-Pla A, et al. Evaluation and comparison of bioinformatic tools for the enrichment analysis of metabolomics data. BMC Bioinformatics. 2018;19: 1. doi:10.1186/s12859-017-2006-0\n3. Rosato A, Tenori L, Cascante M, De Atauri Carulla PR, Martins dos Santos VAP, Saccenti E. From correlation to causation: analysis of metabolomics data using systems biology approaches. Metabolomics. Springer New York LLC; 2018. p. 37. doi:10.1007/s11306-018-1335-y\n4. Karnovsky A, Li S. Pathway Analysis for Targeted and Untargeted Metabolomics. Methods in Molecular Biology. Humana Press Inc.; 2020. pp. 387\u2013400. doi:10.1007/978-1-0716-0239-3_19\n\n#### General pathway analysis\n1. Khatri P, Sirota M, Butte AJ. Ten years of pathway analysis: Current approaches and outstanding challenges. Ouzounis CA, editor. PLoS Computational Biology. Public Library of Science; 2012. p. e1002375. doi:10.1371/journal.pcbi.1002375\n2. Mubeen S, Hoyt CT, Gem\u00fcnd A, Hofmann-Apitius M, Fr\u00f6hlich H, Domingo-Fern\u00e1ndez D. The Impact of Pathway Database Choice on Statistical Enrichment Analysis and Predictive Modeling. Front Genet. 2019;10: 1203. doi:10.3389/fgene.2019.01203\n3. Nguyen TM, Shafi A, Nguyen T, Draghici S. Identifying significantly impacted pathways: A comprehensive review and assessment. Genome Biol. 2019;20. doi:10.1186/s13059-019-1790-4\n\n## Useful resources for pathway analysis \n- Pathway commons: integrated pathway database resource which allows for exploration and download of various knowledgebases https://www.pathwaycommons.org/\n- KEGG API, can be used to programatically download the KEGG database: https://www.kegg.jp/kegg/rest/keggapi.html\n    - Alternatively, KEGGREST in R can be used: http://bioconductor.org/packages/release/bioc/html/KEGGREST.html\n- Reactome downloads: https://reactome.org/download-data\n- BioCyc pathway database with support for many organisms. Use SmartTables tool to download pathways. https://biocyc.org/\n\n#### Web servers for metabolomics pathway analysis\n- MetaboAnalyst 5.0 https://www.metaboanalyst.ca/MetaboAnalyst/ModuleView.xhtml the most popular web server for metabolomics pathway analysis but *use it wisely!*\n- Impala http://impala.molgen.mpg.de/ multi-omics joint pathway analysis\n- MetExplore https://metexplore.toulouse.inrae.fr/index.html/ flux variation analysis web application\n- MetScape http://metscape.ncibi.org/\n- Reactome over-representation analysis https://reactome.org/PathwayBrowser/#TOOL=AT\n- PaintOmics, multi-omics pathway visualisation tool http://www.paintomics.org/\n\n#### R tools for pathway analysis\n- fast GSEA, can be used for metabolomics data https://bioconductor.org/packages/release/bioc/html/fgsea.html\n- ClusterProfiler pathway analysis and visualisation tool http://yulab-smu.top/clusterProfiler-book/\n- FELLA, R package for metabolomics enrichment using KEGG https://github.com/b2slab/FELLA\n\n#### Python tools for pathway analysis \n- BioServices, can be used to convert between compound identifiers https://bioservices.readthedocs.io/en/master/compound_tutorial.html\n- Pathway analysis toolkit https://github.com/iseekwonderful/PyPathway\n- GSEAPy https://gseapy.readthedocs.io/en/latest/introduction.html\n\n\nQuestions? Contact cw2019@ic.ac.uk\n", "meta": {"hexsha": "0a32e541e935a0f977d9d6b768203bfd5c76b144", "size": 409142, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Intro_to_data_analysis_pathway_tutorial.ipynb", "max_stars_repo_name": "cwieder/met-pathway-tutorial", "max_stars_repo_head_hexsha": "b3a37fa447afa4b1cc97210ea27ba042e735e702", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-18T12:05:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T09:03:28.000Z", "max_issues_repo_path": "Intro_to_data_analysis_pathway_tutorial.ipynb", "max_issues_repo_name": "cwieder/met-pathway-tutorial", "max_issues_repo_head_hexsha": "b3a37fa447afa4b1cc97210ea27ba042e735e702", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Intro_to_data_analysis_pathway_tutorial.ipynb", "max_forks_repo_name": "cwieder/met-pathway-tutorial", "max_forks_repo_head_hexsha": "b3a37fa447afa4b1cc97210ea27ba042e735e702", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 293.2917562724, "max_line_length": 355084, "alphanum_fraction": 0.9136656711, "converted": true, "num_tokens": 9506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.08509904442693891, "lm_q1q2_score": 0.03244142080525049}}
{"text": "# \u25b6\ufe0f CUDA setup\n\n\n```\n!nvcc --version\n```\n\n\n```\n!nvidia-smi\n```\n\n## NVCC Plugin for Jupyter notebook\n\n*Usage*:\n\n\n*   Load Extension `%load_ext nvcc_plugin`\n*   Mark a cell to be treated as cuda cell\n`%%cuda --name example.cu --compile false`\n\n**NOTE**: The cell must contain either code or comments to be run successfully. It accepts 2 arguments. `-n | --name` - which is the name of either CUDA source or Header. The name parameter must have extension `.cu` or `.h`. Second argument -c | --compile; default value is false. The argument is a flag to specify if the cell will be compiled and run right away or not. It might be usefull if you're playing in the main function\n\n*  We are ready to run CUDA C/C++ code right in your Notebook. For this we need explicitly say to the interpreter, that we want to use the extension by adding `%%cu` at the beginning of each cell with CUDA code. \n\n\n\n\n\n```\n!pip install git+https://github.com/andreinechaev/nvcc4jupyter.git\n```\n\n\n```\n%load_ext nvcc_plugin\n```\n\n\n```\n#@title Bash setup\n%%writefile /root/.bashrc\n\n# If not running interactively, don't do anything\n[ -z \"$PS1\" ] && return\n\n# don't put duplicate lines in the history. See bash(1) for more options\n# ... or force ignoredups and ignorespace\nHISTCONTROL=ignoredups:ignorespace\n\n# append to the history file, don't overwrite it\nshopt -s histappend\n\n# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)\nHISTSIZE=10000\nHISTFILESIZE=20000\n\n# check the window size after each command and, if necessary,\n# update the values of LINES and COLUMNS.\nshopt -s checkwinsize\n\n# make less more friendly for non-text input files, see lesspipe(1)\n[ -x /usr/bin/lesspipe ] && eval \"$(SHELL=/bin/sh lesspipe)\"\n\nPS1='\\[\\033[01;34m\\]\\w\\[\\033[00m\\]\\$ '\n\n# enable color support of ls and also add handy aliases\nif [ -x /usr/bin/dircolors ]; then\n    test -r ~/.dircolors && eval \"$(dircolors -b ~/.dircolors)\" || eval \"$(dircolors -b)\"\n    alias ls='ls --color=auto'\n    #alias dir='dir --color=auto'\n    #alias vdir='vdir --color=auto'\n\n    alias grep='grep --color=auto'\n    alias fgrep='fgrep --color=auto'\n    alias egrep='egrep --color=auto'\nfi\n\n# some more ls aliases\nalias ll='ls -lF'\nalias la='ls -A'\nalias l='ls -CF'\n\n# path setup\nexport PATH=\"/usr/local/cuda/bin:$PATH\"\n```\n\n# \u25b6\ufe0f VS Code on Colab\n\n\n```\n#@title Colab-ssh tunnel\n#@markdown Execute this cell to open the ssh tunnel. Check [colab-ssh documentation](https://github.com/WassimBenzarti/colab-ssh) for more details.\n\n# Install colab_ssh on google colab\n!pip install colab_ssh --upgrade\n\nfrom colab_ssh import launch_ssh_cloudflared, init_git_cloudflared\nssh_tunnel_password = \"gpu\" #@param {type: \"string\"}\nlaunch_ssh_cloudflared(password=ssh_tunnel_password)\n\n# Optional: if you want to clone a Github or Gitlab repository\nrepository_url=\"https://github.com/giulianogrossi/GPUcomputing\" #@param {type: \"string\"}\ninit_git_cloudflared(repository_url)\n```\n\n# \u2705 Image flip - CPU (multithreading)\n\n\n```\n%%writefile /content/src/ImageStuff.h\n\nstruct ImgProp {\n\tint Hpixels;\n\tint Vpixels;\n\tunsigned char HeaderInfo[54];\n\tunsigned long int Hbytes;\n};\n\nstruct Pixel {\n\tunsigned char R;\n\tunsigned char G;\n\tunsigned char B;\n};\n\ntypedef unsigned char pel;    // pixel element\n\npel** ReadBMP(char*);         // Load a BMP image\nvoid WriteBMP(pel**, char*);  // Store a BMP image\n\nextern struct ImgProp ip;\n\n```\n\n\n```\n%%writefile /content/src/ImageStuff.c\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n\n#include \"ImageStuff.h\"\n\n/*\n * Load a BMP image\n */\n\npel** ReadBMP(char* filename) {\n\tFILE* f = fopen(filename, \"rb\");\n\tif (f == NULL) {\n\t\tprintf(\"\\n\\n%s NOT FOUND\\n\\n\", filename);\n\t\texit(1);\n\t}\n\n\tpel HeaderInfo[54];\n\tfread(HeaderInfo, sizeof(pel), 54, f); // read the 54-byte header\n\n\t// extract image height and width from header\n\tint width = *(int*) &HeaderInfo[18];\n\tint height = *(int*) &HeaderInfo[22];\n\n\t//copy header for re-use\n\tfor (unsigned int i = 0; i < 54; i++)\n\t\tip.HeaderInfo[i] = HeaderInfo[i];\n\n\tip.Vpixels = height;\n\tip.Hpixels = width;\n\tint RowBytes = (width * 3 + 3) & (~3);\n\tip.Hbytes = RowBytes;\n\n\tprintf(\"\\n   Input BMP File name: %20s  (%u x %u)\", filename, ip.Hpixels, ip.Vpixels);\n\n\tpel tmp;\n\tpel **TheImage = (pel **) malloc(height * sizeof(pel*));\n\tfor (unsigned int i = 0; i < height; i++)\n\t\tTheImage[i] = (pel *) malloc(RowBytes * sizeof(pel));\n\n\tfor (unsigned int i = 0; i < height; i++)\n\t\tfread(TheImage[i], sizeof(unsigned char), RowBytes, f);\n\n\tfclose(f);\n\treturn TheImage;  // remember to free() it in caller!\n}\n\n/*\n * Store a BMP image\n */\nvoid WriteBMP(pel** img, char* filename) {\n\tFILE* f = fopen(filename, \"wb\");\n\tif (f == NULL) {\n\t\tprintf(\"\\n\\nFILE CREATION ERROR: %s\\n\\n\", filename);\n\t\texit(1);\n\t}\n\n\t//write header\n\tfor (unsigned int x = 0; x < 54; x++)\n\t\tfputc(ip.HeaderInfo[x], f);\n\n\t//write data\n\tfor (unsigned int x = 0; x < ip.Vpixels; x++)\n\t\tfor (unsigned int y = 0; y < ip.Hbytes; y++) {\n\t\t\tchar temp = img[x][y];\n\t\t\tfputc(temp, f);\n\t\t}\n\n\tprintf(\"\\n  Output BMP File name: %20s  (%u x %u)\", filename, ip.Hpixels,\n\t\t\tip.Vpixels);\n\n\tfclose(f);\n}\n```\n\n\n```\n%%writefile /content/src/Imflip.c\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n\n#include \"ImageStuff.h\"\n\nstruct ImgProp ip;\n\npel** FlipImageV(pel** img) {\n\tstruct Pixel pix; //temp swap pixel\n\tint row, col;\n\n\t//vertical flip\n\tfor (col = 0; col < ip.Hbytes; col += 3) {\n\t\trow = 0;\n\t\twhile (row < ip.Vpixels / 2) {\n\t\t\tpix.B = img[row][col];\n\t\t\tpix.G = img[row][col + 1];\n\t\t\tpix.R = img[row][col + 2];\n\n\t\t\timg[row][col] = img[ip.Vpixels - (row + 1)][col];\n\t\t\timg[row][col + 1] = img[ip.Vpixels - (row + 1)][col + 1];\n\t\t\timg[row][col + 2] = img[ip.Vpixels - (row + 1)][col + 2];\n\n\t\t\timg[ip.Vpixels - (row + 1)][col] = pix.B;\n\t\t\timg[ip.Vpixels - (row + 1)][col + 1] = pix.G;\n\t\t\timg[ip.Vpixels - (row + 1)][col + 2] = pix.R;\n\n\t\t\trow++;\n\t\t}\n\t}\n\treturn img;\n}\n\npel** FlipImageH(pel** img) {\n\tstruct Pixel pix; //temp swap pixel\n\tint row, col;\n\n\t//horizontal flip\n\tfor (row = 0; row < ip.Vpixels; row++) {\n\t\tcol = 0;\n\t\twhile (col < (ip.Hpixels * 3) / 2) {\n\t\t\tpix.B = img[row][col];\n\t\t\tpix.G = img[row][col + 1];\n\t\t\tpix.R = img[row][col + 2];\n\n\t\t\timg[row][col] = img[row][ip.Hpixels * 3 - (col + 3)];\n\t\t\timg[row][col + 1] = img[row][ip.Hpixels * 3 - (col + 2)];\n\t\t\timg[row][col + 2] = img[row][ip.Hpixels * 3 - (col + 1)];\n\n\t\t\timg[row][ip.Hpixels * 3 - (col + 3)] = pix.B;\n\t\t\timg[row][ip.Hpixels * 3 - (col + 2)] = pix.G;\n\t\t\timg[row][ip.Hpixels * 3 - (col + 1)] = pix.R;\n\n\t\t\tcol += 3;\n\t\t}\n\t}\n\treturn img;\n}\n\nint main(int argc, char** argv) {\n\tif (argc != 4) {\n\t\tprintf(\"\\n\\nUsage: imflip [input] [output] [V | H]\");\n\t\tprintf(\"\\n\\nExample: imflip square.bmp square_h.bmp h\\n\\n\");\n\t\treturn 0;\n\t}\n\n\tpel** data = ReadBMP(argv[1]);\n\tdouble timer;\n\tunsigned int a;\n\tclock_t start, stop;\n\n\tstart = clock();\n\tswitch (argv[3][0]) {\n\tcase 'v':\n\tcase 'V':\n\t\tdata = FlipImageV(data);\n\t\tbreak;\n\tcase 'h':\n\tcase 'H':\n\t\tdata = FlipImageH(data);\n\t\tbreak;\n\tdefault:\n\t\tprintf(\"\\nINVALID OPTION\\n\");\n\t\treturn 0;\n\t}\n\tstop = clock();\n\ttimer = ((double)(stop-start))/(double)CLOCKS_PER_SEC;\n\n\t// merge with header and write to file\n\tWriteBMP(data, argv[2]);\n\n\t// free() the allocated memory for the image\n\tfor (int i = 0; i < ip.Vpixels; i++)\n\t\tfree(data[i]);\n\tfree(data);\n\n\tprintf(\"\\n\\nTotal execution time: %9.4f sec\", timer);\n\tprintf(\" (%7.3f ns per pixel)\\n\", 1000000 * timer / (double) (ip.Hpixels * ip.Vpixels));\n\n\treturn 0;\n}\n```\n\n\n```\n!gcc src/ImageStuff.c src/Imflip.c -o imflip \n```\n\n\n```\n!./imflip /content/dog.bmp dogV.bmp V\n!./imflip /content/dog.bmp dogH.bmp H\n```\n\nLibrerie python per lettura/scrittura file di immagini e loro display: [openCV](https://docs.opencv.org/master/index.html) e [matplotlib](https://matplotlib.org/). Le immagini vengono rappresentate come array multidimensionali tratti dalla libreria fondamentale per il calcolo scientifico [NumPy](https://numpy.org/)\n\n\n```\nimport cv2 as cv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# reads as a NumPy array: row (height) x column (width) x color (3)\ndog = cv.imread('/content/dog.bmp')     \nprint('Image size: ', dog.shape)\n# BGR is converted to RGB         \ndog = cv.cvtColor(dog, cv.COLOR_BGR2RGB) \ndogV = cv.imread('dogV.bmp')\ndogV = cv.cvtColor(dogV, cv.COLOR_BGR2RGB)\ndogH = cv.imread('dogH.bmp')\ndogH = cv.cvtColor(dogH, cv.COLOR_BGR2RGB)\nplt.imshow(dog)\nplt.show()\nplt.imshow(dogV)\nplt.show()\nplt.imshow(dogH)\nplt.show()\n```\n\n\n```\n%%writefile /content/src/ImflipPth.c\n\n#include <pthread.h>\n#include <stdint.h>\n#include <ctype.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <sys/time.h>\n#include \"ImageStuff.h\"\n\n#define MAXTHREADS   128\n\nint NumThreads;         \t\t       // Total number of threads working in parallel\nint ThParam[MAXTHREADS];\t\t       // Thread parameters ...\npthread_t ThHandle[MAXTHREADS];\t   // Thread handles\npthread_attr_t ThAttr;\t\t\t       // Pthread attrributes\nvoid (*FlipFunc)(pel** img);\t      // Function pointer to flip the image\nvoid* (*MTFlipFunc)(void *arg);\t   // Function pointer to flip the image, multi-threaded version\npel** TheImage;       \t\t\t       // This is the main image\nstruct ImgProp ip;\n\n// serial version\nvoid FlipImageV(pel** img) {\n\tstruct Pixel pix; //temp swap pixel\n\tint row, col;\n\n\t//vertical flip\n\tfor (col = 0; col < ip.Hbytes; col += 3) {\n\t\trow = 0;\n\t\twhile (row < ip.Vpixels / 2) {\n\t\t\tpix.B = img[row][col];\n\t\t\tpix.G = img[row][col + 1];\n\t\t\tpix.R = img[row][col + 2];\n\n\t\t\timg[row][col] = img[ip.Vpixels - (row + 1)][col];\n\t\t\timg[row][col + 1] = img[ip.Vpixels - (row + 1)][col + 1];\n\t\t\timg[row][col + 2] = img[ip.Vpixels - (row + 1)][col + 2];\n\n\t\t\timg[ip.Vpixels - (row + 1)][col] = pix.B;\n\t\t\timg[ip.Vpixels - (row + 1)][col + 1] = pix.G;\n\t\t\timg[ip.Vpixels - (row + 1)][col + 2] = pix.R;\n\n\t\t\trow++;\n\t\t}\n\t}\n}\n\nvoid FlipImageH(pel** img) {\n\n\t// TODO\n}\n\nvoid *MTFlipV(void* tid) {\n\tstruct Pixel pix; //temp swap pixel\n\tint row, col;\n\n\tlong ts = *((int *) tid);                 \t// My thread ID is stored here\n\tts *= ip.Hbytes / NumThreads;               // start index\n\tlong te = ts + ip.Hbytes / NumThreads - 1; \t// end index\n\n\tfor (col = ts; col <= te; col += 3) {\n\t\trow = 0;\n\t\twhile (row < ip.Vpixels / 2) {\n\t\t\tpix.B = TheImage[row][col];\n\t\t\tpix.G = TheImage[row][col + 1];\n\t\t\tpix.R = TheImage[row][col + 2];\n\n\t\t\tTheImage[row][col] = TheImage[ip.Vpixels - (row + 1)][col];\n\t\t\tTheImage[row][col + 1] = TheImage[ip.Vpixels - (row + 1)][col + 1];\n\t\t\tTheImage[row][col + 2] = TheImage[ip.Vpixels - (row + 1)][col + 2];\n\n\t\t\tTheImage[ip.Vpixels - (row + 1)][col] = pix.B;\n\t\t\tTheImage[ip.Vpixels - (row + 1)][col + 1] = pix.G;\n\t\t\tTheImage[ip.Vpixels - (row + 1)][col + 2] = pix.R;\n\n\t\t\trow++;\n\t\t}\n\t}\n\tpthread_exit(0);\n}\n\n// multi-threaded version\nvoid *MTFlipH(void* tid) {\n\tstruct Pixel pix; //temp swap pixel\n\tint row, col;\n\n\tlong ts = *((int *) tid);       \t// My thread ID is stored here\n\tts *= ip.Vpixels / NumThreads;\t\t\t// start index\n\tlong te = ts + ip.Vpixels / NumThreads - 1; \t// end index\n\n\tfor (row = ts; row <= te; row++) {\n\t\tcol = 0;\n\t\twhile (col < ip.Hpixels * 3 / 2) {\n\t\t\tpix.B = TheImage[row][col];\n\t\t\tpix.G = TheImage[row][col + 1];\n\t\t\tpix.R = TheImage[row][col + 2];\n\n\t\t\tTheImage[row][col] = TheImage[row][ip.Hpixels * 3 - (col + 3)];\n\t\t\tTheImage[row][col + 1] = TheImage[row][ip.Hpixels * 3 - (col + 2)];\n\t\t\tTheImage[row][col + 2] = TheImage[row][ip.Hpixels * 3 - (col + 1)];\n\n\t\t\tTheImage[row][ip.Hpixels * 3 - (col + 3)] = pix.B;\n\t\t\tTheImage[row][ip.Hpixels * 3 - (col + 2)] = pix.G;\n\t\t\tTheImage[row][ip.Hpixels * 3 - (col + 1)] = pix.R;\n\n\t\t\tcol += 3;\n\t\t}\n\t}\n\tpthread_exit(NULL);\n}\n\nint main(int argc, char** argv) {\n\tchar Flip;\n\tint a, i, ThErr;\n\tstruct timeval t;\n\tdouble StartTime, EndTime;\n\tdouble TimeElapsed;\n\n\tswitch (argc) {\n\tcase 3:\n\t\tNumThreads = 1;\n\t\tFlip = 'V';\n\t\tbreak;\n\tcase 4:\n\t\tNumThreads = 1;\n\t\tFlip = toupper(argv[3][0]);\n\t\tbreak;\n\tcase 5:\n\t\tNumThreads = atoi(argv[4]);\n\t\tFlip = toupper(argv[3][0]);\n\t\tbreak;\n\tdefault:\n\t\tprintf(\"\\n\\nUsage: imflipP input output [v/h] [thread count]\");\n\t\tprintf(\"\\n\\nExample: imflipP infilename.bmp outname.bmp h 8\\n\\n\");\n\t\treturn 0;\n\t}\n\n  if (NumThreads != 1) {\n    printf(\"\\nExecuting the multi-threaded version with %d threads ...\\n\",NumThreads);\n    MTFlipFunc = (Flip == 'V') ? MTFlipV : MTFlipH;\n  } else {\n    printf(\"\\nExecuting the serial version ...\\n\");\n    FlipFunc = (Flip == 'V') ? FlipImageV : FlipImageH;\n  }\n\t\n\n\t// load image\n\tTheImage = ReadBMP(argv[1]);\n\n\tgettimeofday(&t, NULL);\n\tStartTime = (double) t.tv_sec * 1000000.0 + ((double) t.tv_usec);\n\n\tif (NumThreads > 1) {\n\t\tpthread_attr_init(&ThAttr);\n\t\tpthread_attr_setdetachstate(&ThAttr, PTHREAD_CREATE_JOINABLE);\n    for (i = 0; i < NumThreads; i++) {\n      ThParam[i] = i;\n      ThErr = pthread_create(&ThHandle[i], &ThAttr, MTFlipFunc, (void *) &ThParam[i]);\n      if (ThErr != 0) {\n        printf(\"\\nThread Creation Error %d. Exiting abruptly... \\n\", ThErr);\n        exit(EXIT_FAILURE);\n      }\n    }\n    pthread_attr_destroy(&ThAttr);\n    for (i = 0; i < NumThreads; i++) {\n      pthread_join(ThHandle[i], NULL);\n    }\n\t} else\n\t\t(*FlipFunc)(TheImage);\n\n\tgettimeofday(&t, NULL);\n\tEndTime = (double) t.tv_sec * 1000000.0 + ((double) t.tv_usec);\n\tTimeElapsed = (EndTime - StartTime) / 1000000.00;\n\n\t//merge with header and write to file\n\tWriteBMP(TheImage, argv[2]);\n\n\t// free() the allocated memory for the image\n\tfor (i = 0; i < ip.Vpixels; i++) {\n\t\tfree(TheImage[i]);\n\t}\n\tfree(TheImage);\n\n\tprintf(\"\\n\\nTotal execution time: %9.4f sec (%s flip)\", TimeElapsed,\n\t\t\tFlip == 'V' ? \"Vertical\" : \"Horizontal\");\n\tprintf(\" (%6.3f ns/pixel)\\n\",\n\t\t\t1000000 * TimeElapsed / (double) (ip.Hpixels * ip.Vpixels));\n\n\treturn (EXIT_SUCCESS);\n}\n```\n\n\n```\n!gcc -o imflip src/ImageStuff.c src/ImflipPth.c -pthread\n```\n\n\n```\n!./imflip /content/julia_jet.bmp julia_jetV.bmp V 1\n```\n\n\n```\nimport cv2 as cv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# reads as a NumPy array: row (height) x column (width) x color (3)\njulia_jet = cv.imread('/content/drive/MyDrive/images/julia_jet.bmp')     \nprint('Image size: ', julia_jet.shape)\n# BGR is converted to RGB         \njulia_jet = cv.cvtColor(julia_jet, cv.COLOR_BGR2RGB) \njulia_jetV = cv.imread('julia_jetV.bmp')\njulia_jetV = cv.cvtColor(julia_jetV, cv.COLOR_BGR2RGB)\nplt.imshow(julia_jet)\nplt.show()\nplt.imshow(julia_jetV)\nplt.show()\n\n```\n\n# \ud83d\udd34 TODO\n\nIndividuare il numero di pthread che d\u00e0 la prestazione migliore in termine di tempo impiegato.\n\n```\nbest #ptherad = \n```\n\n# \u2705 Blocks and grids\n\n\n```\n\n```\n\n**Grid 1D**: stampa DIMs e IDs di grid, block e thread\n\n\n\n```\n\n%%cu\n// %%writefile /content/grid.cu\n#include <stdio.h>\n\n__global__ void checkIndex(void) {\n\tprintf(\"threadIdx:(%d, %d, %d) blockIdx:(%d, %d, %d) \"\n\t\t\t\"blockDim:(%d, %d, %d) gridDim:(%d, %d, %d)\\n\",\n\t\t\tthreadIdx.x, threadIdx.y, threadIdx.z,\n\t\t\tblockIdx.x, blockIdx.y, blockIdx.z,\n\t\t\tblockDim.x, blockDim.y, blockDim.z,\n\t\t\tgridDim.x,gridDim.y,gridDim.z);\n}\n\nint main(int argc, char **argv) {\n\n\t// definisce grid e struttura dei blocchi\n\tdim3 block(4);\n\tdim3 grid(3);\n\n\t// controlla dim. dal lato host\n\tprintf(\"CHECK lato host:\\n\");\n\tprintf(\"grid.x = %d\\t grid.y = %d\\t grid.z = %d\\n\", grid.x, grid.y, grid.z);\n\tprintf(\"block.x = %d\\t block.y = %d\\t block.z %d\\n\\n\", block.x, block.y, block.z);\n\n\t// controlla dim. dal lato device\n\tprintf(\"CHECK lato device:\\n\");\n\tcheckIndex<<<grid, block>>>();\n\n\t// reset device\n\tcudaDeviceReset();\n\treturn(0);\n}\n```\n\n\n```\n!nvcc -arch=sm_37 /content/grid.cu -o /content/grid\n```\n\n\n```\n!./grid\n```\n\n# \ud83d\udd34 TODO\n\nDefinire un kernel con block 2D e grid 2D e stampare a video solo i thread la cui somma degli ID (`threadIdx.x + threadIdx.y + blockIdx.x + blockIdx.y`) \u00e8 pari a un numero della sequenza di Fibonacci ([Fibonacci-wikipedia](https://it.wikipedia.org/wiki/Successione_di_Fibonacci))\n\n$\n\\begin{align}\nF_0 &= 0,\\\\\nF_1 &= 1,\\\\\nF_{n}&=F_{{n-1}}+F_{{n-2}},\\quad \\text{(per ogni $n>1$)}\n\\end{align}\n$\n\n\n\n```\n%%cu\n#include <stdio.h>\n\n\n/*\n * Show DIMs & IDs for grid, block and thread\n */\n__global__ void checkIndex(void) {\n \n \tint n = threadIdx.x + threadIdx.y + blockIdx.x + blockIdx.y;\n\n\tint isfib = 0;\n\tint a = 0;\n\tint b = 1;\n\twhile(a <= n){\n\t\t\tif (n == a){\n\t\t\t\t\tisfib = 1;\n\t\t\t}\n\t\t\tint c = a+b;\n\t\t\ta = b;\n\t\t\tb = c;\n\t}\n\n\tif(isfib==1){\n\t\tprintf(\"threadIdx:(%d, %d, %d) blockIdx:(%d, %d, %d) \"\n\t\t\t\t\"blockDim:(%d, %d, %d) gridDim:(%d, %d, %d), \"\n\t\t\t\t\"the sum is %d\\n\",\n\t\t\t\tthreadIdx.x, threadIdx.y, threadIdx.z,\n\t\t\t\tblockIdx.x, blockIdx.y, blockIdx.z,\n\t\t\t\tblockDim.x, blockDim.y, blockDim.z,\n\t\t\t\tgridDim.x,gridDim.y,gridDim.z,\n\t\t\t\tn);\n\t}\n \n}\n\nint main(int argc, char **argv) {\n\n\t// grid and block structure\n\tdim3 block(10,10);\n\tdim3 grid(1,1);\n\n\t// check for host\n\tprintf(\"CHECK for host:\\n\");\n\tprintf(\"grid.x = %d\\t grid.y = %d\\t grid.z = %d\\n\", grid.x, grid.y, grid.z);\n\tprintf(\"block.x = %d\\t block.y = %d\\t block.z %d\\n\\n\", block.x, block.y, block.z);\n\n\t// check for device\n\tprintf(\"CHECK for device:\\n\");\n\tcheckIndex<<<grid, block>>>();\n\n\t// reset device\n\tcudaDeviceReset();\n\treturn (0);\n}\n```\n\n# \u2705 Image fplip - GPU\n\n\n```\n%%writefile /content/src/bmpUtil.h\n\n#ifndef _BPMUTIL_H\n#define _BPMUTIL_H\n\nstruct imgBMP {\n\tint width;\n\tint height;\n\tunsigned char headInfo[54];\n\tunsigned long int rowByte;\n} img;\n\n#define\tWIDTHB\t\timg.rowByte\n#define\tWIDTH\t\t  img.width\n#define\tHEIGHT\t\timg.height\n#define\tIMAGESIZE\t(WIDTHB*HEIGHT)\n\nstruct pixel {\n\tunsigned char R;\n\tunsigned char G;\n\tunsigned char B;\n};\n\ntypedef unsigned long ulong;\ntypedef unsigned int uint;\ntypedef unsigned char pel;    // pixel element\n\npel *ReadBMPlin(char*);         // Load a BMP image\nvoid WriteBMPlin(pel *, char*); // Store a BMP image\n\n#endif\n```\n\n\n```\n%%writefile /content/src/common.h\n\n#include <sys/time.h>\n\n#ifndef _COMMON_H\n#define _COMMON_H\n\n#define CHECK(call)                                                            \\\n{                                                                              \\\n    const cudaError_t error = call;                                            \\\n    if (error != cudaSuccess)                                                  \\\n    {                                                                          \\\n        fprintf(stderr, \"Error: %s:%d, \", __FILE__, __LINE__);                 \\\n        fprintf(stderr, \"code: %d, reason: %s\\n\", error,                       \\\n                cudaGetErrorString(error));                                    \\\n    }                                                                          \\\n}\n\ninline double seconds() {\n    struct timeval tp;\n    struct timezone tzp;\n    int i = gettimeofday(&tp, &tzp);\n    return ((double)tp.tv_sec + (double)tp.tv_usec * 1.e-6);\n}\n\ninline void device_name() {\n    // set up device\n    int dev = 0;\n    cudaDeviceProp deviceProp;\n    CHECK(cudaGetDeviceProperties(&deviceProp, dev));\n    printf(\"device %d: %s\\n\", dev, deviceProp.name);\n    CHECK(cudaSetDevice(dev));\n}\n\n#endif\n\n```\n\n# \ud83d\udd34 TODO\n\n\n```\n%%writefile /content/src/ImgFlipCUDA.cu\n\n#include <stdio.h>\n#include <stdlib.h>\n#include \"bmpUtil.h\"\n#include \"common.h\"\n\n/*\n * Kernel 1D that flips the given image vertically\n * each thread only flips a single pixel (R,G,B)\n */\n__global__ void VflipGPU(pel *imgDst, const pel *imgSrc, const uint w, const uint h) {\n\t \n\t \t\n\t\tint row_block = (w + blockDim.x - 1) / blockDim.x;\t//numero di blocchi per riga\n\t\tint thread_in_block = blockDim.x;\t//numero di thread in ogni blocco\n\n\t\t//cerchiamo la x del pixel, ovvero del thread\n\t\tint x = (blockIdx.x % row_block) * thread_in_block + threadIdx.x;\n\t\tif(x < w){\n\t  \tint y = (blockIdx.x / row_block);\n\t\t\tint true_index = y * w * 3 + x*3;\n\t\t\tint altro_y = h - 1 - y;\n\t\t\tint altro_true_index = altro_y * 3 * w + x*3;\n\t\t\n\t\t\timgDst[true_index] = imgSrc[altro_true_index];\n\t\t\timgDst[true_index+1] = imgSrc[altro_true_index+1];\n\t\t\timgDst[true_index+2] = imgSrc[altro_true_index+2];\n\t\t\t\n\n\t\t\timgDst[altro_true_index] = imgSrc[true_index];\n\t\t\timgDst[altro_true_index+1] = imgSrc[true_index+1];\n\t\t\timgDst[altro_true_index+2] = imgSrc[true_index+2];\n\t\t\n\t\t}\n\t\t\n}\n\n/*\n *  Kernel that flips the given image horizontally\n *  each thread only flips a single pixel (R,G,B)\n */\n__global__ void HflipGPU(pel *ImgDst, pel *ImgSrc, uint width) {\n\t\n\t\tint row_block = (width + blockDim.x - 1) / blockDim.x;\t//numero di blocchi per riga\n\t\tint thread_in_block = blockDim.x;\n\t\tint x = (blockIdx.x % row_block) * thread_in_block + threadIdx.x;\n\t\tif(x < width / 2){\n\t\t\t\tint y = blockIdx.x / row_block;\n\t\t\t\tint altro_x = width - 1 - x;\n\t\t\t\tint true_index = y * width *3 + x * 3;\n\t\t\t\tint altro_true_index = y * width * 3 + altro_x * 3;\n\n\t\t\t\tImgDst[true_index] = ImgSrc[altro_true_index];\n\t\t\t\tImgDst[true_index+1] = ImgSrc[altro_true_index+1];\n\t\t\t\tImgDst[true_index+2] = ImgSrc[altro_true_index+2];\n\t\t\t\n\n\t\t\t\tImgDst[altro_true_index] = ImgSrc[true_index];\n\t\t\t\tImgDst[altro_true_index+1] = ImgSrc[true_index+1];\n\t\t\t\tImgDst[altro_true_index+2] = ImgSrc[true_index+2];\n\t\t}\n}\n\n/*\n *  Read a 24-bit/pixel BMP file into a 1D linear array.\n *  Allocate memory to store the 1D image and return its pointer\n */\npel *ReadBMPlin(char* fn) {\n\tstatic pel *Img;\n\tFILE* f = fopen(fn, \"rb\");\n\tif (f == NULL) {\n\t\tprintf(\"\\n\\n%s NOT FOUND\\n\\n\", fn);\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tpel HeaderInfo[54];\n\tsize_t nByte = fread(HeaderInfo, sizeof(pel), 54, f); // read the 54-byte header\n\t// extract image height and width from header\n\tint width = *(int*) &HeaderInfo[18];\n\timg.width = width;\n\tint height = *(int*) &HeaderInfo[22];\n\timg.height = height;\n\tint RowBytes = (width * 3 + 3) & (~3);  // row is multiple of 4 pixel\n\timg.rowByte = RowBytes;\n\t//save header for re-use\n\tmemcpy(img.headInfo, HeaderInfo, 54);\n\tprintf(\"\\n Input File name: %5s  (%d x %d)   File Size=%lu\", fn, img.width,\n\t\t\timg.height, IMAGESIZE);\n\t// allocate memory to store the main image (1 Dimensional array)\n\tImg = (pel *) malloc(IMAGESIZE);\n\tif (Img == NULL)\n\t\treturn Img;      // Cannot allocate memory\n\t// read the image from disk\n\tsize_t out = fread(Img, sizeof(pel), IMAGESIZE, f);\n\tfclose(f);\n\treturn Img;\n}\n\n/*\n *  Write the 1D linear-memory stored image into file\n */\nvoid WriteBMPlin(pel *Img, char* fn) {\n\tFILE* f = fopen(fn, \"wb\");\n\tif (f == NULL) {\n\t\tprintf(\"\\n\\nFILE CREATION ERROR: %s\\n\\n\", fn);\n\t\texit(1);\n\t}\n\t//write header\n\tfwrite(img.headInfo, sizeof(pel), 54, f);\n\t//write data\n\tfwrite(Img, sizeof(pel), IMAGESIZE, f);\n\tprintf(\"\\nOutput File name: %5s  (%u x %u)   File Size=%lu\", fn, img.width,\n\t\t\timg.height, IMAGESIZE);\n\tfclose(f);\n}\n\n/*\n * MAIN\n */\nint main(int argc, char **argv) {\n\tchar flip = 'V';\n\tuint dimBlock = 127, dimGrid;\n\tpel *imgSrc, *imgDst;\t\t // Where images are stored in CPU\n\tpel *imgSrcGPU, *imgDstGPU;\t // Where images are stored in GPU\n\n\tif (argc > 4) {\n\t\tdimBlock = atoi(argv[4]);\n\t\tflip = argv[3][0];\n\t}\n\telse if (argc > 3) {\n\t\tflip = argv[3][0];\n\t}\n\telse if (argc < 3) {\n\t\tprintf(\"\\n\\nUsage:   imflipGPU InputFilename OutputFilename [V/H] [dimBlock]\");\n\t\texit(EXIT_FAILURE);\n\t}\n\tif ((flip != 'V') && (flip != 'H')) {\n\t\tprintf(\"Invalid flip option '%c'. Must be 'V','H'... \\n\",flip);\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t// Create CPU memory to store the input and output images\n\timgSrc = ReadBMPlin(argv[1]); // Read the input image if memory can be allocated\n\tif (imgSrc == NULL) {\n\t\tprintf(\"Cannot allocate memory for the input image...\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\timgDst = (pel *) malloc(IMAGESIZE);\n\tif (imgDst == NULL) {\n\t\tfree(imgSrc);\n\t\tprintf(\"Cannot allocate memory for the input image...\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t// Allocate GPU buffer for the input and output images\n\tCHECK(cudaMalloc((void**) &imgSrcGPU, IMAGESIZE));\n\tCHECK(cudaMalloc((void**) &imgDstGPU, IMAGESIZE));\n\n\t// Copy input vectors from host memory to GPU buffers.\n\tCHECK(cudaMemcpy(imgSrcGPU, imgSrc, IMAGESIZE, cudaMemcpyHostToDevice));\n\n\t// invoke kernels (define grid and block sizes)\n\tint rowBlock = (WIDTH + dimBlock - 1) / dimBlock;\n\tdimGrid = (HEIGHT) * rowBlock;\t//AAA il diviso due lo abbiamo aggiunto noi E INVECE ORA L'HO TOLTO\n\tdouble start = seconds();   // start time\n\n\tswitch (flip) {\n\tcase 'H':\n\t\tHflipGPU<<<dimGrid, dimBlock>>>(imgDstGPU, imgSrcGPU, WIDTH);\n\t\tbreak;\n\tcase 'V':\n\t\tVflipGPU<<<dimGrid, dimBlock>>>(imgDstGPU, imgSrcGPU, WIDTH, HEIGHT);\n\t\tbreak;\n\t}\n\t// cudaDeviceSynchronize waits for the kernel to finish, and returns\n\t// any errors encountered during the launch.\n\tCHECK(cudaDeviceSynchronize());\n\n\tdouble stop = seconds();   // elapsed time\n\n\t// Copy output (results) from GPU buffer to host (CPU) memory.\n\tCHECK(cudaMemcpy(imgDst, imgDstGPU, IMAGESIZE, cudaMemcpyDeviceToHost));\n\n\t// Write the flipped image back to disk\n\tWriteBMPlin(imgDst, argv[2]);\n\n\tprintf(\"\\nKernel elapsed time %f sec \\n\\n\", stop - start);\n\n\t// Deallocate CPU, GPU memory and destroy events.\n\tcudaFree(imgSrcGPU);\n\tcudaFree(imgDstGPU);\n\n\t// cudaDeviceReset must be called before exiting in order for profiling and\n\t// tracing tools spel as Parallel Nsight and Visual Profiler to show complete traces.\n\tcudaError_t\tcudaStatus = cudaDeviceReset();\n\tif (cudaStatus != cudaSuccess) {\n\t\tfprintf(stderr, \"cudaDeviceReset failed!\");\n\t\tfree(imgSrc);\n\t\tfree(imgDst);\n\t\texit(EXIT_FAILURE);\n\t}\n\tfree(imgSrc);\n\tfree(imgDst);\n\treturn (EXIT_SUCCESS);\n}\n\n\n```\n\n\n```\n!nvcc src/ImgFlipCUDA.cu -arch=sm_37 -o imfpliGPU\n```\n\n\n```\n!./imfpliGPU /content/dog.bmp dog_v.bmp V\n```\n\n# \ud83d\udd34 TODO\n\nIndividuare la grid che d\u00e0 la prestazione migliore in termine di tempo impiegato.\n\n```\nbest grid = (#blocks, #threads) \n```\n", "meta": {"hexsha": "4954f1b1045bf8fc6e06b34d2d3b7e5d0b02a115", "size": 44497, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "GPU_computing/CUDA_lab2_TODO.ipynb", "max_stars_repo_name": "katema-official/Universita_magistrale_anno_1.2", "max_stars_repo_head_hexsha": "8123bef1e519e1047bc359499fc2d8f229a19363", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GPU_computing/CUDA_lab2_TODO.ipynb", "max_issues_repo_name": "katema-official/Universita_magistrale_anno_1.2", "max_issues_repo_head_hexsha": "8123bef1e519e1047bc359499fc2d8f229a19363", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GPU_computing/CUDA_lab2_TODO.ipynb", "max_forks_repo_name": "katema-official/Universita_magistrale_anno_1.2", "max_forks_repo_head_hexsha": "8123bef1e519e1047bc359499fc2d8f229a19363", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1234662577, "max_line_length": 442, "alphanum_fraction": 0.4518057397, "converted": true, "num_tokens": 7855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3040416623541848, "lm_q2_score": 0.10669058400428263, "lm_q1q2_score": 0.03243838251820089}}
{"text": "```python\n%load_ext autoreload\n%autoreload 2\n```\n\n\n```python\n!python -m pip install --upgrade jax==0.2.10 jaxlib==0.1.62+cuda101 -f https://storage.googleapis.com/jax-releases/jax_releases.html\n```\n\n\n```python\ncd /mnt/home/tmakinen/repositories/scratch/gitinstall/imnn\n```\n\n\n```python\n!git checkout dev;\n```\n\n    D\texamples/2D sims - IMNN.ipynb\n    M\texamples/IMNN - JAX.ipynb\n    Already on 'dev'\n    Your branch is ahead of 'origin/dev' by 3 commits.\n      (use \"git push\" to publish your local commits)\n\n\n\n```python\n!python -m pip install .\n```\n\n    Already up-to-date.\n\n\n\n```python\npwd\n```\n\n\n\n\n    '/mnt/home/tmakinen/repositories/scratch/dev-imnn/imnn'\n\n\n\n\n```python\n!python -m setup.py install\n```\n\n    /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/setuptools/dist.py:458: UserWarning: Normalizing '0.3dev' to '0.3.dev0'\n      warnings.warn(tmpl.format(**locals()))\n    running install\n    running bdist_egg\n    running egg_info\n    writing IMNN.egg-info/PKG-INFO\n    writing dependency_links to IMNN.egg-info/dependency_links.txt\n    writing requirements to IMNN.egg-info/requires.txt\n    writing top-level names to IMNN.egg-info/top_level.txt\n    reading manifest file 'IMNN.egg-info/SOURCES.txt'\n    writing manifest file 'IMNN.egg-info/SOURCES.txt'\n    installing library code to build/bdist.linux-x86_64/egg\n    running install_lib\n    running build_py\n    copying IMNN/experimental/jax/imnn/imnn.py -> build/lib/IMNN/experimental/jax/imnn\n    creating build/bdist.linux-x86_64/egg\n    creating build/bdist.linux-x86_64/egg/IMNN\n    creating build/bdist.linux-x86_64/egg/IMNN/LFI\n    copying build/lib/IMNN/LFI/LFI.py -> build/bdist.linux-x86_64/egg/IMNN/LFI\n    copying build/lib/IMNN/LFI/__init__.py -> build/bdist.linux-x86_64/egg/IMNN/LFI\n    copying build/lib/IMNN/IMNN.py -> build/bdist.linux-x86_64/egg/IMNN\n    copying build/lib/IMNN/tfIMNN.py -> build/bdist.linux-x86_64/egg/IMNN\n    copying build/lib/IMNN/__init__.py -> build/bdist.linux-x86_64/egg/IMNN\n    creating build/bdist.linux-x86_64/egg/IMNN/utils\n    copying build/lib/IMNN/utils/__init__.py -> build/bdist.linux-x86_64/egg/IMNN/utils\n    copying build/lib/IMNN/utils/utils.py -> build/bdist.linux-x86_64/egg/IMNN/utils\n    copying build/lib/IMNN/utils/TFRecords.py -> build/bdist.linux-x86_64/egg/IMNN/utils\n    creating build/bdist.linux-x86_64/egg/IMNN/experimental\n    copying build/lib/IMNN/experimental/__init__.py -> build/bdist.linux-x86_64/egg/IMNN/experimental\n    creating build/bdist.linux-x86_64/egg/IMNN/experimental/jax\n    creating build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/_tensorflow_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/tensorflow_gradient_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/aggregated_gradient_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/gradient_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/numerical_gradient_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/aggregated_numerical_gradient_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/aggregated_numerical_gradient_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/gradient_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/__init__.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/simulator_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/aggregated_simulator_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/tensorflow_numerical_gradient_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/simulator_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/_tensorflow_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/aggregated_gradient_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/numerical_gradient_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/aggregated_simulator_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    creating build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi\n    copying build/lib/IMNN/experimental/jax/lfi/gaussian_approximation.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi\n    copying build/lib/IMNN/experimental/jax/lfi/lfi.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi\n    copying build/lib/IMNN/experimental/jax/lfi/__init__.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi\n    copying build/lib/IMNN/experimental/jax/lfi/approximate_bayesian_computation.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi\n    copying build/lib/IMNN/experimental/jax/__init__.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax\n    creating build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils\n    copying build/lib/IMNN/experimental/jax/utils/__init__.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils\n    copying build/lib/IMNN/experimental/jax/utils/utils.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils\n    copying build/lib/IMNN/experimental/jax/utils/keras_utils.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils\n    copying build/lib/IMNN/experimental/jax/utils/container.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils\n    copying build/lib/IMNN/experimental/jax/utils/jac.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils\n    creating build/bdist.linux-x86_64/egg/test\n    copying build/lib/test/tensorflow_defaults.py -> build/bdist.linux-x86_64/egg/test\n    copying build/lib/test/simulator_defaults.py -> build/bdist.linux-x86_64/egg/test\n    copying build/lib/test/numerical_gradient_defaults.py -> build/bdist.linux-x86_64/egg/test\n    copying build/lib/test/__init__.py -> build/bdist.linux-x86_64/egg/test\n    copying build/lib/test/gradient_defaults.py -> build/bdist.linux-x86_64/egg/test\n    copying build/lib/test/defaults.py -> build/bdist.linux-x86_64/egg/test\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/LFI/LFI.py to LFI.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/LFI/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/IMNN.py to IMNN.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/tfIMNN.py to tfIMNN.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/utils/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/utils/utils.py to utils.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/utils/TFRecords.py to TFRecords.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/_tensorflow_imnn.py to _tensorflow_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/tensorflow_gradient_imnn.py to tensorflow_gradient_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/aggregated_gradient_imnn_test.py to aggregated_gradient_imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/gradient_imnn_test.py to gradient_imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/numerical_gradient_imnn_test.py to numerical_gradient_imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/_imnn.py to _imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/aggregated_numerical_gradient_imnn_test.py to aggregated_numerical_gradient_imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/imnn.py to imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/aggregated_numerical_gradient_imnn.py to aggregated_numerical_gradient_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/gradient_imnn.py to gradient_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/_imnn_test.py to _imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/simulator_imnn_test.py to simulator_imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/aggregated_simulator_imnn.py to aggregated_simulator_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/tensorflow_numerical_gradient_imnn.py to tensorflow_numerical_gradient_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/simulator_imnn.py to simulator_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/_tensorflow_imnn_test.py to _tensorflow_imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/aggregated_gradient_imnn.py to aggregated_gradient_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/numerical_gradient_imnn.py to numerical_gradient_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/aggregated_simulator_imnn_test.py to aggregated_simulator_imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi/gaussian_approximation.py to gaussian_approximation.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi/lfi.py to lfi.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi/approximate_bayesian_computation.py to approximate_bayesian_computation.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils/utils.py to utils.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils/keras_utils.py to keras_utils.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils/container.py to container.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils/jac.py to jac.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/test/tensorflow_defaults.py to tensorflow_defaults.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/test/simulator_defaults.py to simulator_defaults.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/test/numerical_gradient_defaults.py to numerical_gradient_defaults.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/test/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/test/gradient_defaults.py to gradient_defaults.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/test/defaults.py to defaults.cpython-36.pyc\n    creating build/bdist.linux-x86_64/egg/EGG-INFO\n    copying IMNN.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying IMNN.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying IMNN.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying IMNN.egg-info/requires.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying IMNN.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    zip_safe flag not set; analyzing archive contents...\n    creating 'dist/IMNN-0.3.dev0-py3.6.egg' and adding 'build/bdist.linux-x86_64/egg' to it\n    removing 'build/bdist.linux-x86_64/egg' (and everything under it)\n    Processing IMNN-0.3.dev0-py3.6.egg\n    Removing /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/IMNN-0.3.dev0-py3.6.egg\n    Copying IMNN-0.3.dev0-py3.6.egg to /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    IMNN 0.3.dev0 is already the active version in easy-install.pth\n    \n    Installed /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/IMNN-0.3.dev0-py3.6.egg\n    Processing dependencies for IMNN==0.3.dev0\n    Searching for matplotlib==3.3.2\n    Best match: matplotlib 3.3.2\n    Adding matplotlib 3.3.2 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for scipy==1.5.3\n    Best match: scipy 1.5.3\n    Adding scipy 1.5.3 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for numpy==1.19.4\n    Best match: numpy 1.19.4\n    Adding numpy 1.19.4 to easy-install.pth file\n    Installing f2py script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing f2py3 script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing f2py3.6 script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for tqdm==4.55.1\n    Best match: tqdm 4.55.1\n    Processing tqdm-4.55.1-py3.6.egg\n    tqdm 4.55.1 is already the active version in easy-install.pth\n    Installing tqdm script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/tqdm-4.55.1-py3.6.egg\n    Searching for jax==0.2.8\n    Best match: jax 0.2.8\n    Processing jax-0.2.8-py3.6.egg\n    jax 0.2.8 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/jax-0.2.8-py3.6.egg\n    Searching for jaxlib==0.1.57+cuda101\n    Best match: jaxlib 0.1.57+cuda101\n    Removing jaxlib 0.1.59 from easy-install.pth file\n    Adding jaxlib 0.1.57+cuda101 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for tensorflow==2.4.0\n    Best match: tensorflow 2.4.0\n    Processing tensorflow-2.4.0-py3.6-linux-x86_64.egg\n    tensorflow 2.4.0 is already the active version in easy-install.pth\n    Installing estimator_ckpt_converter script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing import_pb_to_tensorboard script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing saved_model_cli script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing tensorboard script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing tf_upgrade_v2 script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing tflite_convert script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing toco script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing toco_from_protos script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/tensorflow-2.4.0-py3.6-linux-x86_64.egg\n    Searching for certifi==2020.12.5\n    Best match: certifi 2020.12.5\n    Adding certifi 2020.12.5 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for Pillow==8.1.0\n    Best match: Pillow 8.1.0\n    Adding Pillow 8.1.0 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for python-dateutil==2.8.1\n    Best match: python-dateutil 2.8.1\n    Adding python-dateutil 2.8.1 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for kiwisolver==1.3.1\n    Best match: kiwisolver 1.3.1\n    Adding kiwisolver 1.3.1 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for cycler==0.10.0\n    Best match: cycler 0.10.0\n    Adding cycler 0.10.0 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for pyparsing==2.4.7\n    Best match: pyparsing 2.4.7\n    Adding pyparsing 2.4.7 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for opt-einsum==3.3.0\n    Best match: opt-einsum 3.3.0\n    Adding opt-einsum 3.3.0 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for absl-py==0.11.0\n    Best match: absl-py 0.11.0\n    Adding absl-py 0.11.0 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for flatbuffers==1.12\n    Best match: flatbuffers 1.12\n    Adding flatbuffers 1.12 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for wrapt==1.12.1\n    Best match: wrapt 1.12.1\n    Processing wrapt-1.12.1-py3.6-linux-x86_64.egg\n    wrapt 1.12.1 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/wrapt-1.12.1-py3.6-linux-x86_64.egg\n    Searching for wheel==0.36.2\n    Best match: wheel 0.36.2\n    Adding wheel 0.36.2 to easy-install.pth file\n    Installing wheel script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for typing-extensions==3.7.4.3\n    Best match: typing-extensions 3.7.4.3\n    Processing typing_extensions-3.7.4.3-py3.6.egg\n    typing-extensions 3.7.4.3 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/typing_extensions-3.7.4.3-py3.6.egg\n    Searching for termcolor==1.1.0\n    Best match: termcolor 1.1.0\n    Processing termcolor-1.1.0-py3.6.egg\n    termcolor 1.1.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/termcolor-1.1.0-py3.6.egg\n    Searching for tensorflow-estimator==2.4.0\n    Best match: tensorflow-estimator 2.4.0\n    Processing tensorflow_estimator-2.4.0-py3.6.egg\n    tensorflow-estimator 2.4.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/tensorflow_estimator-2.4.0-py3.6.egg\n    Searching for tensorboard==2.4.0\n    Best match: tensorboard 2.4.0\n    Processing tensorboard-2.4.0-py3.6.egg\n    tensorboard 2.4.0 is already the active version in easy-install.pth\n    Installing tensorboard script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/tensorboard-2.4.0-py3.6.egg\n    Searching for six==1.15.0\n    Best match: six 1.15.0\n    Adding six 1.15.0 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for protobuf==4.0.0rc2\n    Best match: protobuf 4.0.0rc2\n    Processing protobuf-4.0.0rc2-py3.6.egg\n    protobuf 4.0.0rc2 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/protobuf-4.0.0rc2-py3.6.egg\n    Searching for Keras-Preprocessing==1.1.2\n    Best match: Keras-Preprocessing 1.1.2\n    Processing Keras_Preprocessing-1.1.2-py3.6.egg\n    Keras-Preprocessing 1.1.2 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/Keras_Preprocessing-1.1.2-py3.6.egg\n    Searching for h5py==2.10.0\n    Best match: h5py 2.10.0\n    Processing h5py-2.10.0-py3.6-linux-x86_64.egg\n    h5py 2.10.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/h5py-2.10.0-py3.6-linux-x86_64.egg\n    Searching for grpcio==1.32.0\n    Best match: grpcio 1.32.0\n    Processing grpcio-1.32.0-py3.6-linux-x86_64.egg\n    grpcio 1.32.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/grpcio-1.32.0-py3.6-linux-x86_64.egg\n    Searching for google-pasta==0.2.0\n    Best match: google-pasta 0.2.0\n    Processing google_pasta-0.2.0-py3.6.egg\n    google-pasta 0.2.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/google_pasta-0.2.0-py3.6.egg\n    Searching for gast==0.3.3\n    Best match: gast 0.3.3\n    Processing gast-0.3.3-py3.6.egg\n    gast 0.3.3 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/gast-0.3.3-py3.6.egg\n    Searching for astunparse==1.6.3\n    Best match: astunparse 1.6.3\n    Processing astunparse-1.6.3-py3.6.egg\n    astunparse 1.6.3 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/astunparse-1.6.3-py3.6.egg\n    Searching for Werkzeug==1.0.1\n    Best match: Werkzeug 1.0.1\n    Processing Werkzeug-1.0.1-py3.6.egg\n    Werkzeug 1.0.1 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/Werkzeug-1.0.1-py3.6.egg\n    Searching for tensorboard-plugin-wit==1.7.0\n    Best match: tensorboard-plugin-wit 1.7.0\n    Processing tensorboard_plugin_wit-1.7.0-py3.6.egg\n    tensorboard-plugin-wit 1.7.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/tensorboard_plugin_wit-1.7.0-py3.6.egg\n    Searching for setuptools==49.6.0.post20201009\n    Best match: setuptools 49.6.0.post20201009\n    Adding setuptools 49.6.0.post20201009 to easy-install.pth file\n    Installing easy_install script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for requests==2.25.1\n    Best match: requests 2.25.1\n    Processing requests-2.25.1-py3.6.egg\n    requests 2.25.1 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/requests-2.25.1-py3.6.egg\n    Searching for Markdown==3.3.3\n    Best match: Markdown 3.3.3\n    Processing Markdown-3.3.3-py3.6.egg\n    Markdown 3.3.3 is already the active version in easy-install.pth\n    Installing markdown_py script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/Markdown-3.3.3-py3.6.egg\n    Searching for google-auth==1.24.0\n    Best match: google-auth 1.24.0\n    Processing google_auth-1.24.0-py3.6.egg\n    google-auth 1.24.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/google_auth-1.24.0-py3.6.egg\n    Searching for google-auth-oauthlib==0.4.2\n    Best match: google-auth-oauthlib 0.4.2\n    Processing google_auth_oauthlib-0.4.2-py3.6.egg\n    google-auth-oauthlib 0.4.2 is already the active version in easy-install.pth\n    Installing google-oauthlib-tool script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/google_auth_oauthlib-0.4.2-py3.6.egg\n    Searching for urllib3==1.26.2\n    Best match: urllib3 1.26.2\n    Processing urllib3-1.26.2-py3.6.egg\n    urllib3 1.26.2 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/urllib3-1.26.2-py3.6.egg\n    Searching for idna==2.10\n    Best match: idna 2.10\n    Processing idna-2.10-py3.6.egg\n    idna 2.10 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/idna-2.10-py3.6.egg\n    Searching for chardet==4.0.0\n    Best match: chardet 4.0.0\n    Processing chardet-4.0.0-py3.6.egg\n    chardet 4.0.0 is already the active version in easy-install.pth\n    Installing chardetect script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/chardet-4.0.0-py3.6.egg\n    Searching for importlib-metadata==3.3.0\n    Best match: importlib-metadata 3.3.0\n    Processing importlib_metadata-3.3.0-py3.6.egg\n    importlib-metadata 3.3.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/importlib_metadata-3.3.0-py3.6.egg\n    Searching for rsa==4.6\n    Best match: rsa 4.6\n    Processing rsa-4.6-py3.6.egg\n    rsa 4.6 is already the active version in easy-install.pth\n    Installing pyrsa-decrypt script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing pyrsa-encrypt script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing pyrsa-keygen script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing pyrsa-priv2pub script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing pyrsa-sign script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing pyrsa-verify script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/rsa-4.6-py3.6.egg\n    Searching for pyasn1-modules==0.2.8\n    Best match: pyasn1-modules 0.2.8\n    Processing pyasn1_modules-0.2.8-py3.6.egg\n    pyasn1-modules 0.2.8 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/pyasn1_modules-0.2.8-py3.6.egg\n    Searching for cachetools==4.2.0\n    Best match: cachetools 4.2.0\n    Processing cachetools-4.2.0-py3.6.egg\n    cachetools 4.2.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/cachetools-4.2.0-py3.6.egg\n    Searching for requests-oauthlib==1.3.0\n    Best match: requests-oauthlib 1.3.0\n    Processing requests_oauthlib-1.3.0-py3.6.egg\n    requests-oauthlib 1.3.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/requests_oauthlib-1.3.0-py3.6.egg\n    Searching for zipp==3.4.0\n    Best match: zipp 3.4.0\n    Processing zipp-3.4.0-py3.6.egg\n    zipp 3.4.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/zipp-3.4.0-py3.6.egg\n    Searching for pyasn1==0.4.8\n    Best match: pyasn1 0.4.8\n    Processing pyasn1-0.4.8-py3.6.egg\n    pyasn1 0.4.8 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/pyasn1-0.4.8-py3.6.egg\n    Searching for oauthlib==3.1.0\n    Best match: oauthlib 3.1.0\n    Processing oauthlib-3.1.0-py3.6.egg\n    oauthlib 3.1.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/oauthlib-3.1.0-py3.6.egg\n    Finished processing dependencies for IMNN==0.3.dev0\n    /mnt/home/tmakinen/anaconda3/envs/pyjax/bin/python: Error while finding module specification for 'setup.py' (AttributeError: module 'setup' has no attribute '__path__')\n\n\n\n```python\n!XLA_FLAGS=--xla_gpu_cuda_data_dir=/cm/shared/sw/pkg/devel/cuda/10.1.243_418.87.00\nfrom jax.config import config\nconfig.update(\"jax_debug_nans\", True)\nconfig.update('jax_enable_x64', True)\n\n```\n\n\n```python\nimport itertools\nimport math\nfrom functools import partial\n\nimport numpy as onp\n\nimport jax\nprint(\"jax version: \", jax.__version__)\nimport jax.experimental.optimizers as optimizers\nimport jax.experimental.stax as stax\nimport jax.numpy as np\nfrom jax import jit\nimport matplotlib.pyplot as plt\nimport scipy\n\nimport imnn\nprint(\"IMNN version: \", imnn.__version__)\n\nfrom imnn.imnn import (\n    AggregatedGradientIMNN,\n    AggregatedNumericalGradientIMNN,\n    AggregatedSimulatorIMNN,\n    GradientIMNN,\n    NumericalGradientIMNN,\n    SimulatorIMNN,\n)\nfrom imnn.lfi import (\n    ApproximateBayesianComputation,\n    GaussianApproximation,\n)\nfrom imnn.utils import value_and_jacrev, value_and_jacfwd\n\nrng = jax.random.PRNGKey(0)\n\n```\n\n    jax version:  0.2.10\n    IMNN version:  0.3dev\n\n\n\n```python\n!XLA_FLAGS=--xla_cpu_enable_fast_math=false\n```\n\n\n```python\nfrom jax.lib import xla_bridge\nprint(xla_bridge.get_backend().platform)\n```\n\n    gpu\n\n\n# Model in STAX\n\n\n```python\nn_summaries = 2\nn_s = 5000\nn_d = 5000\n\u03bb = 100.0\n\u03f5 = 0.1\n```\n\n\n```python\n# define inception block layer\n\ndef InceptBlock2(filters, strides, do_5x5=True, do_3x3=True):\n    \"\"\"InceptNet convolutional striding block.\n    filters: tuple: (f1,f2,f3)\n    filters1: for conv1x1\n    filters2: for conv1x1,conv3x3\n    filters3L for conv1x1,conv5x5\"\"\"\n    \n    filters1, filters2, filters3 = filters\n    \n    conv1x1 = stax.serial(stax.Conv(filters1, (1,1), strides, padding=\"SAME\"))\n    \n    filters4 = filters2\n    conv3x3 = stax.serial(stax.Conv(filters2, (1,1), strides=None, padding=\"SAME\"),\n                        stax.Conv(filters4, (3,3), strides, padding=\"SAME\"))\n                        \n    filters5 = filters3\n    conv5x5 = stax.serial(stax.Conv(filters3, (1,1), strides=None, padding=\"SAME\"),\n                         stax.Conv(filters5, (5,5), strides, padding=\"SAME\"))\n#     conv5x5 = stax.serial(stax.Conv(filters1, (1,1), strides=None, padding=\"SAME\"),\n#                          stax.Conv(filters3, (3,3), strides=None, padding=\"SAME\"),\n#                          stax.Conv(filters3, (3,3), strides, padding=\"SAME\"))   \n    \n    maxpool = stax.serial(stax.MaxPool((3,3), padding=\"SAME\"),\n                         stax.Conv(filters4, (1,1), strides, padding=\"SAME\"))\n                            \n    if do_3x3:\n        if do_5x5:\n            return stax.serial(\n                  stax.FanOut(4),  # should num=3 or 2 here ?\n                  stax.parallel(conv1x1, conv3x3, conv5x5, maxpool),\n                  stax.FanInConcat(), \n                  stax.LeakyRelu)\n        else:\n            return stax.serial(\n                  stax.FanOut(3),  # should num=3 or 2 here ?\n                  stax.parallel(conv1x1, conv3x3, maxpool),\n                  stax.FanInConcat(), \n                  stax.LeakyRelu)\n            \n    else:\n        return stax.serial(\n              stax.FanOut(2),  # should num=3 or 2 here ?\n              stax.parallel(conv1x1, maxpool),\n              stax.FanInConcat(), \n              stax.LeakyRelu)\n    \n    \ndef Reshape(newshape):\n    \"\"\"Layer function for a reshape layer.\"\"\"\n    init_fun = lambda rng, input_shape: (newshape,())\n    apply_fun = lambda params, inputs, **kwargs: np.reshape(inputs,newshape)\n    return init_fun, apply_fun    \n\n```\n\n\n```python\nrng,drop_rng = jax.random.split(rng)\n# fs = 4 #for 128x128 sims\n\n# layers = []\n\n# for i in range(7):\n#     if i == 5:\n#         layers.append(InceptBlock2((fs,fs,fs), strides=(2,2), do_5x5=False)\n#         )\n#     elif i == 6:\n#         layers.append(InceptBlock2((fs,fs,fs), strides=(2,2), do_5x5=False, do_3x3=False)\n#         )\n#     else: \n#         layers.append(InceptBlock2((fs,fs,fs), strides=(2,2))\n#         )\n        \n#     if i % 4 == 0:\n#         fs *= 2\n    \n# layers.append(stax.Conv(n_summaries, (1,1), strides=(1,1), padding=\"SAME\"))\n# layers.append(stax.Flatten)\n\n# model = stax.serial(*layers)\n\nfs = 32\n    \n# model = stax.serial(InceptBlock((fs,fs,fs), strides=(2,2)), # output 64x64\n#                     InceptBlock((fs,fs,fs), strides=(2,2)), # output 32x32\n#                     InceptBlock((fs,fs,fs), strides=(2,2)), # output 16x16\n#                     InceptBlock((fs,fs,fs), strides=(2,2)), # output 8x8\n#                     InceptBlock((fs,fs,fs), strides=(2,2)), # output 4x4\n#                     InceptBlock((fs,fs,fs), strides=(2,2), do_5x5=False), # output 2x2\n#                     InceptBlock((fs,fs,fs), strides=(2,2), do_5x5=False), # output 1x1\n#                     stax.Conv(n_summaries, (1,1), strides=(1,1), padding=\"SAME\"),\n#                     stax.Flatten,\n#                    )\n\nmodel = stax.serial(\n       # InceptBlock2((fs,fs,fs), strides=(4,4)),\n        InceptBlock2((fs,fs,fs), strides=(4,4)),\n        InceptBlock2((fs,fs,fs), strides=(4,4)),\n        InceptBlock2((fs,fs,fs), strides=(2,2), do_5x5=False, do_3x3=False),\n        stax.Conv(n_summaries, (1,1), strides=(1,1), padding=\"SAME\"),\n        stax.Flatten,\n        Reshape((n_summaries,))\n)\n```\n\n\n```python\noptimiser = optimizers.adam(step_size=1e-3)\n```\n\n\n```python\n# weights = model[0](rng, input_shape)[1]\n# model[1](weights, np.zeros(input_shape, dtype=np.float32), rng=rng).shape\n# state = optimiser[0](weights)\n# model[1](optimiser[2](state), np.zeros(input_shape, dtype=np.float32), rng=rng)\n```\n\n# Random seeds for IMNN\n\n\n```python\nrng, initial_model_key = jax.random.split(rng)\nrng, fitting_key = jax.random.split(rng)\n```\n\n# Random seeds for ABC\n\n\n```python\nrng, abc_key = jax.random.split(rng)\n```\n\n# 2D Gaussian Field Simulator in JAX\n\nSteps to creating $(N \\times N)$ 2D Gaussian field for IMNN:\n1. Generate a $(N\\times N)$ white noise field $\\varphi$ such that $\\langle \\varphi_k \\varphi_{-k} \\rangle' = 1$\n2. Fourier Transform $\\varphi$ to real space: $R_{\\rm white}(\\textbf{x}) \\rightarrow R_{\\rm white}(\\textbf{k})$\n    - note: NumPy's DFT Fourier convention is:\n    $$\\phi_{ab}^{\\textbf{k}} = \\sum_{c,d = 0}^{N-1} \\exp{(-i x_c k_a - i x_d k_b) \\phi^{\\textbf{x}}_{cd}}$$\n    $$\\phi_{ab}^{\\textbf{x}} = \\frac{1}{N^2}\\sum_{c,d = 0}^{N-1} \\exp{(-i x_c k_a - i x_d k_b) \\phi^{\\textbf{k}}_{cd}}$$    \n3. Scale white noise $R_{\\rm white}(\\textbf{k})$ by the chosen power spectrum evaluated over a field of $k$ values:\n$$ R_P(\\textbf{k}) = P^{1/2}(k) R_{\\rm white}(\\textbf{k}) $$\n    - note: here we need to ensure that this array of amplitudes is Hermitian, e.g. $\\phi^{* \\textbf{k}}_{a(N/2 + b)} = \\phi^{\\textbf{k}}_{a(N/2 - b)}$. This is accomplished by choosing indexes $k_a = k_b = \\frac{2\\pi}{N} (0, \\dots, N/2, -N/2+1, \\dots, -1)$ and then evaluating the square root of the outer product of the meshgrid between the two: $k = \\sqrt{k^2_a + k^2_b}$. We can then evaluate $P^{1/2}(k)$.\n    \n4. Fourier Transform $R_{P}(\\textbf{k})$ to real space: $ R_P(\\textbf{x}) = \\int d^d \\tilde{k} e^{i\\textbf{k} \\cdot \\textbf{x}} R_p(\\textbf{k}) $:\n\n$$R_{ab}^{\\textbf{x}} = \\frac{1}{N^2}\\sum_{c,d = 0}^{N-1} \\exp{(-i x_c k_a - i x_d k_b) R^{\\textbf{k}}_{cd}}$$\n\n\n```python\n# SET 32-BiT floats for model !\n\u03b8_fid = np.array([1.0, 0.5], dtype=np.float32)\n\u03b4\u03b8 = np.array([0.1, 0.1], dtype=np.float32)\nn_params = 2\nN = 32\ndim = 2\nL = 32\n\nfield_shape = (N,N)\ndx = L / N\nfourier_b = 2*np.pi\ninput_shape = (1,1, N,N)\nsimulator_args = {\"N\": N, \"L\": L, \"dim\": dim, \"shape\": field_shape, 'vol_norm': False, \"N_scale\": True, \"squeeze\": False}\n```\n\n\n```python\nrng,fg_key = jax.random.split(rng)\nforegrounds = jax.random.normal(fg_key, (1000, 1,) + simulator_args['shape'])*0\n\n\ndef default_P(k, A, B):\n    return A*k**-B\n\n\nclass powerBoxJax:\n    def __init__(self, shape, pk=None, k=None):\n        \n        if pk is None:\n            self.pk = default_P\n        else:\n            self.pk = pk\n            \n        if k is None:\n            self.k = np.sqrt(np.sum(np.array(np.meshgrid(*(\n                (np.hstack((np.arange(0, _shape//2 + 1), \n                    np.arange(-_shape//2 + 1, 0))) * 2*np.pi / _shape)**2\n                    for _shape in shape))), axis=0))\n        else:\n            self.k = k\n            \n        self.shape = shape\n        self.N = shape[0]\n        \n    def simulator(self, rng, \u03b8, simulator_args=simulator_args, add_foregrounds=False):\n        def P(k, A=1, B=1):\n            return self.pk(k, A, B)\n\n        def fn(key, A, B):\n            shape = self.shape #simulator_args[\"shape\"]\n\n            k = self.k\n\n            new_shape = ()\n            for _shape in shape:\n                if _shape % 2 == 0:\n                    new_shape += (_shape+1,)\n                else:\n                    new_shape += (_shape,)\n\n\n            key1,key2 = jax.random.split(key)\n    \n            if add_foregrounds:\n                foreground = foregrounds[jax.random.randint(key2, \n                                            minval=0, maxval=1000, shape=())]\n            else:\n                foreground = 0.\n\n            # L is in length units, like Gpc\n            L = simulator_args['L']\n            dim = simulator_args['dim']\n\n            if np.isscalar(L):\n                L = [L]*int(dim)\n\n            else:\n                L = np.array(L)\n\n\n            V = np.prod(np.array(L))\n\n            scale = V**(1./dim)\n\n            Lk = ()\n\n            _N = 1\n            for i,_shape in enumerate(shape):\n                _N *= _shape\n                Lk += (_shape / L[i],) # 1 / dx\n\n\n            fft_norm = np.prod(np.array(Lk))\n\n            _dims = len(shape)\n            tpl = ()\n            for _d in range(_dims):\n                tpl += (_d,)\n\n            # POWERBOX IMPLEMENTATION\n\n            mag = jax.random.normal(key1, shape=tuple(N for N in new_shape))\n            \n            # random phases\n            pha = 2 * np.pi * jax.random.uniform(key1, shape=tuple(N for N in new_shape))\n            \n            # now make hermitian field (reality condition)\n            revidx = (slice(None, None, -1),) * len(mag.shape)\n            mag = (mag + mag[revidx]) / np.sqrt(2) \n            pha = (pha - pha[revidx]) / 2 + np.pi\n            dk = mag * (np.cos(pha) + 1j * np.sin(pha)) # output is complex\n\n            cutidx = (slice(None, -1),) * len(new_shape)\n\n            dk = dk[cutidx]\n            powers = np.concatenate((np.zeros(1), \n                        np.sqrt(P(k.flatten()[1:], A=A, B=B)))).reshape(k.shape)\n\n            # normalize power by volume\n            if simulator_args['vol_norm']:\n                powers = powers/V\n\n            fourier_field = powers * dk\n\n            fourier_field = jax.ops.index_update(\n                fourier_field,\n                np.zeros(len(shape), dtype=int),\n                np.zeros((1,)))\n            \n            field = np.real(np.fft.ifftn(fourier_field) * fft_norm * V)\n            \n            if simulator_args[\"N_scale\"]:\n                field *= scale\n\n            field = np.expand_dims(field + foreground, (0,))\n\n\n            if not simulator_args[\"squeeze\"]:\n                field = np.expand_dims(field, (0,))\n\n            return np.array(field, dtype='float32')\n\n        shape = self.shape #simulator_args[\"shape\"]\n        A, B = \u03b8\n\n\n        if A.shape == B.shape:\n            if len(A.shape) == 0:\n                return fn(rng, A, B)\n            else:\n                keys = jax.random.split(rng, num=A.shape[0] + 1)\n                rng = keys[0]\n                keys = keys[1:]\n                return jax.vmap(\n                    lambda key, A, B: simulator(key, (A, B), simulator_args=simulator_args)\n                )(keys, A, B)\n        else:\n            if len(A.shape) > 0:\n                keys = jax.random.split(rng, num=A.shape[0] + 1)\n                rng = keys[0]\n                keys = keys[1:]\n                return jax.vmap(\n                    lambda key, A: simulator(key, (A, B), simulator_args=simulator_args)\n                )(keys, A)\n            elif len(B.shape) > 0:\n                keys = jax.random.split(rng, num=B.shape[0])\n                return jax.vmap(\n                    lambda key, B: simulator(key, (A, B), simulator_args=simulator_args)\n                )(keys, B)\n\n\n\n    def AnalyticFisher(self, \n               \u03b8, \n               kvec=None,\n               N=None\n              ):\n        \"\"\"\n        Code for computing the Analytic Fisher for a Gaussian\n        Field with power spectrum P(k) = Ak^-B\n        \"\"\"\n        A,B = \u03b8\n        if N is None:\n            N = self.N\n        \n        # we want all UNIQUE fourier modes\n        if kvec is None:\n            kvec = self.k[1:N//2, 1:N//2]\n\n        pk = lambda k : A*(k**-B)             # P(k) = Ak^(-B)\n        p_a = lambda k : k**-B                # deriv w.r.t. A\n        p_b = lambda k : -A*(k**-B)*np.log(k) # deriv w.r.t. B\n\n\n        powers = (pk(kvec.flatten()[:]))#np.concatenate((np.ones(1), \n            \n\n        powera =  (p_a(kvec.flatten()[:])) #np.concatenate((np.zeros(1), \n           \n\n        powerb = (p_b(kvec.flatten()[:])) #np.concatenate((np.zeros(1), \n            \n\n\n        Cinv = np.diag(1. / powers)          # diagonal inv. covariance\n        Ca =  np.diag(powera / 1.)           # C_{,A}\n        Cb =  np.diag(powerb / 1.)           # C_{,B}\n\n        Faa = 0.5 * np.trace((Ca @ Cinv @ Ca @ Cinv))\n        Fab = 0.5 * np.trace((Ca @ Cinv @ Cb @ Cinv))\n        Fba = 0.5 * np.trace((Cb @ Cinv @ Ca @ Cinv))\n        Fbb = 0.5 * np.trace((Cb @ Cinv @ Cb @ Cinv))\n\n        return np.array([[Faa, Fab], [Fba, Fbb]])\n\n\n\nclass analyticFieldLikelihood:\n\n    def __init__(self,\n                 PBJ, \n                 field_shape,\n                 \u0394,\n                 prior,\n                 k=None,\n                 pk=None,\n                 gridsize=20, \n                 tiling=2):\n\n        \"\"\"code for computing a gaussian field's likelihood for power spectrum parameters\n            PBJ :         powerBox simulator object\n            field_shape : list. shape of field input\n            \u0394 :           array-like. FFT of the real-space field\n            prior :       array-like. range over which to compute the likelihood\n            k :           array-like. fourier modes over which to compute P(k)\n            tiling :      list or int. tiling=2 means likelihood will be computed as 2x2 grid\n            gridsize :    how large to make the likelihood surface\n        \"\"\"\n        \n        \n        if k is None:\n            self.k = PBJ.k\n\n        if pk is None:\n            self.pk = PBJ.pk\n\n        self.field_shape = field_shape\n        self.gridsize = gridsize\n        if np.isscalar(tiling):\n            self.tiling = [tiling]*2\n        else:\n            self.tiling = tiling    \n        #self.tilesize = gridsize // tiling\n        self.N = np.sqrt(np.prod(np.array(field_shape)))  # should just be N for NxN grid\n        self.prior = prior\n\n        self.k = k\n        self.\u0394 = \u0394\n\n    def Pk(self, k, A=1, B=0.5):\n        return self.pk(k, A, B)\n\n\n        return np.diag(pk)\n    def log_likelihood(self, k, A, B, \u0394):\n        \u0394 = \u0394.flatten()[:]\n        k = k\n\n        dlength = len(k.flatten())\n\n        def fn(_A, _B):\n\n            nrm = np.pad(np.ones(dlength-2)*2, (1,1), constant_values=1.)\n            nrm = jax.ops.index_update(\n              nrm, np.array([[0],[(dlength-2)]]), np.array([[1],[1]]))\n            nrm = 1\n\n            powers = self.Pk(k.flatten()[:], A=_A, B=_B)\n\n            # covariance is P(k)\n            C = powers * nrm\n            invC = 1./self.Pk(k.flatten()[:], A=_A, B=_B)\n\n            logdetC = np.sum(np.log(C))\n            pi2 = np.pi * 2.\n            m_half_size = -0.5 * len(\u0394)\n            exponent = - 0.5 * np.sum(np.conj(\u0394) * invC * \u0394)\n            norm = -0.5 * logdetC + m_half_size*np.log(pi2) \n            return (exponent + norm)\n        return jax.vmap(fn)(A, B)\n\n    def get_likelihood(self, return_grid=False, shift=None):\n        A_start = self.prior[0][0]\n        A_end = self.prior[1][0]\n        B_start = self.prior[0][1]\n        B_end = self.prior[1][1]\n\n        region_size = [self.gridsize // self.tiling[i] for i in range(len(self.tiling))]\n\n        print(\"computing likelihood on a %dx%d grid \\n \\\n        in tiles of size %dx%d\"%(self.gridsize, self.gridsize, region_size[0], region_size[1]))\n\n\n        def get_like_region(A0, A1, B0, B1, qsize):\n            A_range = np.linspace(A0, A1, qsize)\n            B_range = np.linspace(B0, B1, qsize)\n            A, B = np.meshgrid(A_range, B_range)\n\n            return (self.log_likelihood(self.k,\n                A.ravel(), B.ravel(), self.\u0394).reshape(qsize,qsize))\n\n\n\n        A_incr = (A_end - A_start) / self.tiling[0]\n        B_incr = (B_end - B_start) / self.tiling[1]\n\n        # marks the ends of linspace\n        A_starts = [A_start + (i)*A_incr for i in range(self.tiling[0])]\n        A_ends = [A_start + (i+1)*A_incr for i in range(self.tiling[0])]\n        B_starts = [B_start + (i)*B_incr for i in range(self.tiling[1])]\n        B_ends = [B_start + (i+1)*B_incr for i in range(self.tiling[1])]\n\n        _like_cols = []\n        for _col in range(self.tiling[0]):\n            # slide horizontally in A\n            _like_row = []\n            for _row in range(self.tiling[1]):\n                # slide vertically in B\n\n                _like = get_like_region(A_starts[_row], \n                                        A_ends[_row], \n                                        B_starts[_col], \n                                        B_ends[_col],\n                                        region_size[0],\n                                        )\n                _like_row.append(_like)\n\n            _like_cols.append(np.concatenate(_like_row, axis=1))\n\n        _log_likelihood = np.real(np.concatenate(_like_cols, axis=0))\n\n        if shift is None:\n            shift = np.max(_log_likelihood)\n\n        print('shift', shift)\n        print('loglike mean', np.mean(_log_likelihood))\n\n        #_log_likelihood = _log_likelihood - shift\n\n        if return_grid:\n            _A_range = np.linspace(self.prior[0,0], self.prior[1,0], self.gridsize)\n            _B_range = np.linspace(self.prior[0,0], self.prior[1,0], self.gridsize)\n            return (_log_likelihood), _A_range, _B_range\n\n        return (_log_likelihood)\n\n\n\n    def plot_contours(self, ax=None, \n                      \u03b8_ref=None, shift=None, \n                      xlabel='A', ylabel='B', \n                      return_like=True):\n\n        _like, _A, _B = self.get_likelihood(return_grid=True, shift=shift)\n\n\n        _A, _B = np.meshgrid(_A, _B)\n\n        if ax is None:\n            fig,ax = plt.subplots(figsize=(10,10))\n\n        mesh = ax.contourf(_A, _B, _like)\n        plt.colorbar(mesh, ax=ax)\n\n        if \u03b8_ref is not None:\n            ax.scatter(\u03b8_ref[0], \u03b8_ref[1], zorder=10, marker='+', s=100, color='r')\n\n        ax.set_xlabel('A')\n        ax.set_ylabel('B')\n\n        if return_like:\n            return _like, ax\n\n        else:\n            return ax\n        \n\n    def plot_corner(self, ax=None, \u03b8_ref=None, label=\"Analytic likelihood\", image_data=None):\n\n        _like, _A_range, _B_range = self.get_likelihood(return_grid=True)\n\n        likelihoodA = scipy.special.softmax(np.real(_like)).sum(0) #np.real(likelihood).sum(0)\n        likelihoodA /= likelihoodA.sum() * (_A_range[1] -  _A_range[0])\n        likelihoodB =  scipy.special.softmax(np.real(_like)).sum(1) #np.real(likelihood).sum(1)\n        likelihoodB /= likelihoodB.sum() * (_B_range[1] -  _B_range[0])\n\n        _like = scipy.special.softmax(np.real(_like))\n        sorted_marginal = np.sort(_like.flatten())[::-1]\n        cdf = np.cumsum(sorted_marginal / sorted_marginal.sum())\n        value = []\n        for level in [0.997, 0.95, 0.68]:\n            this_value = sorted_marginal[np.argmin(np.abs(cdf - level))]\n            if len(value) == 0:\n                value.append(this_value)\n            elif this_value <= value[-1]:\n                break\n            else:\n                value.append(this_value)\n\n        if ax is None:\n            fig,ax = plt.subplots(nrows=2, ncols=2)\n\n        ax[1,0].contour(_A_range, _B_range, _like, levels=value, colors='C2', alpha=0.7)\n        ax[0, 0].plot(_A_range, likelihoodA, color='C2', label=None, alpha=0.7)\n        ax[1, 1].plot(likelihoodB, _B_range, color='C2', label='loglike', alpha=0.7)\n        \n        if image_data is not None:\n            ax[0, 1].imshow(np.squeeze(image_data))\n        else:\n            ax[0, 1].axis(\"off\")\n\n        if \u03b8_ref is not None:\n            ax[0,0].axvline(\u03b8_ref[0], linestyle='--', c='k')\n            ax[1,0].axvline(\u03b8_ref[0], linestyle='--', c='k')\n            ax[1,0].axhline(\u03b8_ref[1], linestyle='--', c='k')\n            ax[1,1].axhline(\u03b8_ref[1], linestyle='--', c='k', label=r'$\\theta_{\\rm ref}$')\n\n        ax[1,0].set_xlabel(r'$A$')\n        ax[1,0].set_ylabel(r'$B$')\n\n        return ax\n\n\n```\n\n\n```python\nPBJ = powerBoxJax(simulator_args['shape'])\nsimulator = PBJ.simulator\n```\n\n## sim and gradient\n\n\n```python\ndef simulator_gradient(rng, \u03b8, simulator_args=simulator_args):\n    return value_and_jacrev(simulator, argnums=1, allow_int=True, holomorphic=True)(rng, \u03b8, simulator_args=simulator_args)\n```\n\n\n```python\nrng, key = jax.random.split(rng)\n```\n\n\n```python\nfield_shape\n```\n\n\n\n\n    (32, 32)\n\n\n\n\n```python\n# plot example simulation and derivative\nderiv_args = {\"N\": N, \"L\": 32, \"dim\": dim, \"shape\": field_shape, \"vol_norm\": True, \"N_scale\": True, \"squeeze\": False}\nsimulation, simulation_gradient = value_and_jacfwd(simulator, argnums=1)(rng, \u03b8_fid, simulator_args=deriv_args)\n\nplt.imshow(np.squeeze(simulation[0]), extent=(0,1,0,1))\nplt.colorbar()\nplt.title('example simulation')\nplt.show()\n\nplt.imshow(np.squeeze(simulation_gradient[0].T[0].T), extent=(0,1,0,1))\nplt.title('gradient of simulation')\nplt.colorbar()\nplt.show()\n```\n\n\n```python\ndef get_simulations(rng, n_s, \u03b8, simulator_args=simulator_args):\n    def get_simulator(key):\n        return simulator(key, \u03b8, simulator_args=simulator_args)\n\n    keys = jax.random.split(rng, num=n_s)\n    return jax.vmap(get_simulator)(np.array(keys))\n\n\ndef get_simulation_gradients(rng, n_s, n_d, \u03b8, simulator_args=simulator_args):\n    def get_batch_gradient(key):\n        return simulator_gradient(key, \u03b8, simulator_args=simulator_args)\n\n    keys = jax.random.split(rng, num=n_s)\n    return jax.vmap(get_batch_gradient)(np.array(keys)[:n_d])\n```\n\n# known analytic Fisher information\n\nFor a gaussian field, the likelihood is written\n$$     \\mathcal{L}(\\Delta | \\theta) = \\frac{1}{(2\\pi)^{N_p / 2} \\det(C)^{1/2}}\\exp{\\left(-\\frac{1}{2} \\Delta C^{-1} \\Delta \\right)}$$\n\nWhere $\\Delta \\in \\mathbb{R}^{N_p},\\ N_p=N_k=V=N\\times N$ is the Fourier Transform of the observed real-space field.\nThis yields a Fisher information matrix of\n\n$$F_{\\alpha \\beta} = \\langle -\\frac{\\partial^2 \\ln \\mathcal{L}}{\\partial \\lambda_\\alpha \\partial \\lambda_\\beta} \\rangle= \\frac{1}{2} {\\rm Tr} (C_{, \\alpha} C^{-1} C_{, \\beta} C^{-1}) $$\nwhere the covariance is\n$$ C_{k_i, k_j} =  P(k_i)\\delta_{ij}$$\nThe associated derivatives for a power law $P(k) = Ak^{-B}$ are\n$$\\begin{align}\n    C_{,A} &= \\left( k^{-B} \\right)\\delta_{ij} \\\\\n    C_{,B} &= \\left( -Ak^{-B}\\ln k \\right) \\delta_{ij}\n\\end{align} $$\n\nWe notice that the Fisher information is *only* a function of the power spectrum parameters. It tells us the curvature of the chosen model (likelihood function) at a given $\\theta$. The analytic Fisher information is the maximum amount of information we can expect the IMNN to extract from our simulations.\n\n\n<!-- Alternatively, we can explore a volume integral analytically from the definition of C :\nwhere the Fisher matrix is given by\n$$ F_{\\alpha \\beta} = \\sum_k \\frac{1}{(\\delta P_k)^2} \\frac{\\partial P_k}{\\partial \\lambda_\\alpha} \\frac{\\partial P_k}{\\partial \\lambda_\\beta}$$\nand the error on $P_k$ is given (for a square, 2D box) as\n$$ \\delta P_k = \\sqrt{\\frac{2}{k (\\Delta k) V} } \\left( P_k + \\frac{1}{\\bar{n}} \\right) $$ -->\n\n<!-- For a gaussian field, the likelihood is written\n$$ \\ln \\mathcal{L}(\\theta | \\vec{d}) = \\ln \\mathcal{L}(\\theta | \\Delta) = \\sqrt{\\frac{1}{2\\pi C}} \\exp{\\frac{-{\\Delta}^2}{2C}}$$\n\nwhere $\\vec{d} = \\Delta$ is the overdensity field (in a cosmological context this is the measured temperature or galaxy count in a sky survey). Given that the power spectrum describes the correlations at different scales $k$, we can define the correlation via the power spectrum $C = P(k) = Ak^{-B}$ to compute the log-likelihood. The Fisher information matrix, given as \n$$ F_{\\alpha \\beta} = \\langle - \\frac{\\partial^2 \\ln \\mathcal{L}}{\\partial \\theta_\\alpha \\partial \\theta_\\beta} \\rangle $$\ncan then be computed analytically for our likelihood:\n$$ F_{\\alpha \\beta} = \\sum_k \\frac{1}{(\\delta P_k)^2} \\frac{\\partial P_k}{\\partial \\theta_\\alpha} \\frac{\\partial P_k}{\\partial \\theta_\\beta} $$\n\nwhere $\\delta P_k = \\sqrt{\\frac{2}{4\\pi \\Delta k V k_{\\rm tot}^2}} (P_k + \\frac{1}{\\bar{n}})$ is the error on $P_k$ with survey volume $V$, sampling interval $\\Delta k$, and shot noise $1/\\bar{n}$. Using the fact that $d\\ln P_k = \\frac{d P_k}{P_k}$, we can rewrite the sum as an integral:\n$$ F_{\\alpha \\beta} = 2 \\pi \\left( \\frac{V_{\\rm eff}}{\\lambda^3} \\right) \\int_{k_{\\rm min}}^{k_{\\rm max}} d \\ln k  \\frac{\\partial \\ln P_k}{\\partial \\theta_\\alpha} \\frac{\\partial \\ln P_k}{\\partial \\theta_\\beta}$$\n\nWhere $V_{\\rm eff}$ and $\\lambda^3$ are our effective windowed survey size and survey extent, respectively (set to 1 for now). Doing the integration explicitly, we obtain the Fisher matrix for parameters $\\theta = (A, B)$:\n$$ F = 2 \\pi \\left( \\frac{V_{\\rm eff}}{\\lambda^3} \\right) \\begin{bmatrix}\n    \\frac{1}{A^2} \\ln (\\frac{k_{\\rm max}}{k_{\\rm min}}) & \\frac{1}{2A} ((\\ln k_{\\rm min})^2 - (\\ln k_{\\rm max})^2)  \\\\\n     \\frac{1}{2A} ((\\ln k_{\\rm min})^2 - (\\ln k_{\\rm max})^2) & \\frac{1}{3}((\\ln k_{\\rm max})^3 - (\\ln k_{\\rm min})^3)   \\\\\n\\end{bmatrix}$$\n -->\n\n\nFor our fiducial model with our data vector of size $128^2$, our $\\rm det|F|$ reads:\n\n\n```python\nN = simulator_args[\"N\"]\nshape = simulator_args[\"shape\"]\n\nkbin = np.sqrt(np.sum(np.array(np.meshgrid(*(\n    np.hstack((np.arange(0, _shape//2 + 1), \n        np.arange(-_shape//2 + 1, 0))) *2* np.pi / _shape\n        for _shape in shape)))**2, axis=0))\n\nf_expected = PBJ.AnalyticFisher(\u03b8_fid, kvec=None)\nprint(\"analytic F(\u03b8_fid): \", f_expected)\n\ndetf_expected = np.linalg.det(f_expected)\nprint(\"analytic det(F(\u03b8_fid)): \", detf_expected)\n```\n\n    analytic F(\u03b8_fid):  [[112.5        -88.08135241]\n     [-88.08135241  92.25651195]]\n    analytic det(F(\u03b8_fid)):  2620.5329515016588\n\n\n\n```python\n# MAKE SIMULATION\nN = simulator_args[\"N\"]\nshape = (N,N)\n\n\u03b8_sim = np.array([0.7, 0.8])\nsimulator_args = {\"N\": N, \"L\": 32, \"dim\": dim, \"shape\": shape, \"vol_norm\": True, \"N_scale\": False, \"squeeze\": True}\nsimulator_args[\"shape\"] = (N,N)\nsimkey,rng = jax.random.split(rng)\n#sim = np.squeeze(target_data)#\nsim = np.squeeze(simulator(simkey, \u03b8_sim, simulator_args=simulator_args))\nsim_fft = (np.fft.fft2(sim)) #/ (N**2)\n```\n\n\n```python\ngridsize = 100                # for likelihood gridding\n\u0394 = sim_fft[1:N//2, 1:N//2]\nk = kbin[1:N//2, 1:N//2]  \nprior_range = np.array([[0.1, 0.1], [1.25, 1.25]])\nAL = analyticFieldLikelihood(PBJ, shape, \u0394, prior_range, k=k, gridsize=gridsize, tiling=[5,5])\n```\n\n\n```python\n#plt.style.use('default')\nax = AL.plot_corner(\u03b8_ref=\u03b8_sim, image_data=sim)\n```\n\n\n```python\nsimulator_args\n```\n\n\n```python\nlikes = []\nlikeAs = []\nlikeBs = []\nrng1 = jax.random.PRNGKey(13)\nvalues = []\n\u03b8_target = np.array([0.8, 0.8], dtype=np.float32)\n\nfor t in range(20):\n    key, rng1 = jax.random.split(rng1)\n    targ = simulator(\n        key,\n        \u03b8_target)\n    \n    gridsize = 50                # for likelihood gridding\n    \u0394 = np.fft.fftn(np.squeeze(targ))[1:N//2, 1:N//2] / N\n    k = kbin[1:N//2, 1:N//2]  \n    prior_range = np.array([[0.1, 0.1], [1.25, 1.25]])\n    AL = analyticFieldLikelihood(PBJ, shape, \u0394, prior_range, k=k, \n                                 gridsize=gridsize, tiling=[5,5])\n\n    likelihood,A_range,B_range = AL.get_likelihood(shift=None, return_grid=True)\n    \n    \n    _A_range = A_range#*np.exp(shift)\n    _B_range = B_range#*np.exp(shift)\n\n    likelihoodA = scipy.special.softmax(np.real(likelihood)).sum(0) #np.real(likelihood).sum(0)\n    likelihoodA /= likelihoodA.sum() * (_A_range[1] -  _A_range[0])\n    likelihoodB =  scipy.special.softmax(np.real(likelihood)).sum(1) #np.real(likelihood).sum(1)\n    likelihoodB /= likelihoodB.sum() * (_B_range[1] -  _B_range[0])\n        \n    likelihood = scipy.special.softmax(np.real(likelihood))\n    sorted_marginal = np.sort(likelihood.flatten())[::-1]\n    cdf = np.cumsum(sorted_marginal / sorted_marginal.sum())\n    value = []\n    for level in [0.997, 0.95, 0.68]:\n        this_value = sorted_marginal[np.argmin(np.abs(cdf - level))]\n        if len(value) == 0:\n            value.append(this_value)\n        elif this_value <= value[-1]:\n            break\n        else:\n            value.append(this_value)\n    #fig, ax = plt.subplots(2, 2, figsize=(10, 10))\n    \n    #likelihood /= likelihood.sum()\n    \n    likes.append(likelihood)\n    likeAs.append(likelihoodA)\n    likeBs.append(likelihoodB)\n    \n    values.append(value)\n```\n\n    computing likelihood on a 50x50 grid \n             in tiles of size 10x10\n    shift -226.65323\n    loglike mean -281.2912\n    computing likelihood on a 50x50 grid \n             in tiles of size 10x10\n    shift -222.269\n    loglike mean -273.09332\n    computing likelihood on a 50x50 grid \n             in tiles of size 10x10\n    shift -224.88367\n    loglike mean -276.536\n    computing likelihood on a 50x50 grid \n             in tiles of size 10x10\n    shift -235.14114\n    loglike mean -294.90643\n    computing likelihood on a 50x50 grid \n             in tiles of size 10x10\n    shift -211.05551\n    loglike mean -256.40872\n    computing likelihood on a 50x50 grid \n             in tiles of size 10x10\n    shift -202.47757\n    loglike mean -243.11711\n    computing likelihood on a 50x50 grid \n             in tiles of size 10x10\n    shift -225.42264\n    loglike mean -278.68454\n    computing likelihood on a 50x50 grid \n             in tiles of size 10x10\n    shift -238.12628\n    loglike mean -301.53705\n    computing likelihood on a 50x50 grid \n             in tiles of size 10x10\n    shift -199.5029\n    loglike mean -237.86707\n    computing likelihood on a 50x50 grid \n             in tiles of size 10x10\n    shift -229.45087\n    loglike mean -287.35883\n    computing likelihood on a 50x50 grid \n             in tiles of size 10x10\n    shift -217.84702\n    loglike mean -265.22424\n    computing likelihood on a 50x50 grid \n             in tiles of size 10x10\n    shift -215.51117\n    loglike mean -261.1578\n    computing likelihood on a 50x50 grid \n             in tiles of size 10x10\n    shift -232.67075\n    loglike mean -291.6094\n    computing likelihood on a 50x50 grid \n             in tiles of size 10x10\n    shift -214.5174\n    loglike mean -260.2762\n    computing likelihood on a 50x50 grid \n             in tiles of size 10x10\n    shift -230.61382\n    loglike mean -288.65222\n    computing likelihood on a 50x50 grid \n             in tiles of size 10x10\n    shift -204.98546\n    loglike mean -246.14597\n    computing likelihood on a 50x50 grid \n             in tiles of size 10x10\n    shift -217.84311\n    loglike mean -264.91162\n    computing likelihood on a 50x50 grid \n             in tiles of size 10x10\n    shift -218.11856\n    loglike mean -266.40512\n    computing likelihood on a 50x50 grid \n             in tiles of size 10x10\n    shift -228.65471\n    loglike mean -283.43613\n    computing likelihood on a 50x50 grid \n             in tiles of size 10x10\n    shift -223.27768\n    loglike mean -273.98706\n\n\n\n```python\nfig,ax = plt.subplots(nrows=2, ncols=2)\n\nfor l,like in enumerate(likes):\n    ax[1,0].contour(A_range, B_range, like, levels=value, colors='#FF8D33', alpha=0.5)\n    ax[0, 0].plot(A_range, likeAs[l], color='#FF8D33', label=None, alpha=0.5)\n    ax[0, 1].axis(\"off\")\n    ax[1, 1].plot(likeBs[l], B_range, color='#FF8D33', label='loglike', alpha=0.5)\n    \nax[1,0].scatter(\u03b8_target[0], \u03b8_target[1], marker='+', s=50, color='blue', zorder=20)\nax[0,0].axvline(\u03b8_target[0], linestyle='--', c='k')\nax[1,0].axvline(\u03b8_target[0], linestyle='--', c='k')\nax[1,0].axhline(\u03b8_target[1], linestyle='--', c='k')\nax[1,1].axhline(\u03b8_target[1], linestyle='--', c='k', label=r'$\\theta_{\\rm target}$')\n\nax[1,0].set_xlabel(r'$A$')\nax[1,0].set_ylabel(r'$B$')\n```\n\n# Initialise IMNN\n\n\n```python\nfrom imnn.imnn._imnn import _IMNN\nfrom imnn.utils.utils import _check_simulator #, value_and_jacrev\nfrom imnn.utils.utils import _check_simulator\n\nclass SimIMNN(_IMNN):\n    def __init__(self, n_s, n_d, n_params, n_summaries, input_shape, \u03b8_fid,\n                 model, optimiser, key_or_state, simulator):\n        super().__init__(\n            n_s=n_s,\n            n_d=n_d,\n            n_params=n_params,\n            n_summaries=n_summaries,\n            input_shape=input_shape,\n            \u03b8_fid=\u03b8_fid,\n            model=model,\n            key_or_state=key_or_state,\n            optimiser=optimiser,\n            )\n        self.simulator = _check_simulator(simulator)\n        self.simulate = True\n\n    def get_fitting_keys(self, rng):\n        return jax.random.split(rng, num=3)\n\n    def get_summaries(self, w, key, validate=False):\n        def get_summary(key, \u03b8):\n            return self.model(w, self.simulator(key, \u03b8))\n\n        def get_derivatives(key):\n            return value_and_jacrev(get_summary, argnums=1)(key, self.\u03b8_fid)\n\n        keys = np.array(jax.random.split(key, num=self.n_s))\n        summaries, derivatives = jax.vmap(get_derivatives)(keys[:self.n_d])\n        if self.n_s > self.n_d:\n            summaries = np.vstack([\n                summaries,\n                jax.vmap(partial(get_summary, \u03b8=self.\u03b8_fid))(keys[self.n_d:])])\n        return np.squeeze(summaries), np.squeeze(derivatives)\n    \n    \n```\n\n\n```python\nsimulator_args[\"squeeze\"] = False\n```\n\n\n```python\nsimulator_args['vol_norm'] = True\nsimulator_args['N_scale'] = True # false \nsimulator_args['L'] = 32.0\n```\n\n\n```python\nsimulator_args\n```\n\n\n\n\n    {'N': 32,\n     'L': 32.0,\n     'dim': 2,\n     'shape': (32, 32),\n     'vol_norm': True,\n     'N_scale': True,\n     'squeeze': False}\n\n\n\n\n```python\nIMNN = SimulatorIMNN(\n        n_s=5000,\n        n_d=5000,\n        n_params=n_params,\n        n_summaries=n_summaries,\n        input_shape=input_shape,\n        \u03b8_fid=\u03b8_fid,\n        model=model,\n        optimiser=optimiser,\n        key_or_state=initial_model_key,\n        simulator=lambda rng, \u03b8: simulator(rng, \u03b8, simulator_args=simulator_args),\n#         devices=[jax.devices()[0]],\n#         n_per_device=1000\n        )\n```\n\n# Fit\n\n\n```python\n# new_optimiser = jax.experimental.optimizers.sgd(1e-5)\n# weights = np.load('./model/best_w.npy',  allow_pickle=True)\n# IMNN.opt_initialiser, IMNN.update, IMNN.get_parameters = optimiser\n# IMNN.state = IMNN.opt_initialiser(list(weights))\n```\n\n\n```python\n# SAVING IMNN ATTRIBUTES\nimport cloudpickle as pickle\nimport os\n\ndef save_weights(IMNN, folder_name='./model', weights='final'):\n    \n    # create output directory\n    if not os.path.exists(folder_name): \n        os.mkdir(folder_name)\n    \n    def pckl_me(obj, path):\n        with open(path, 'wb') as file_pi:\n            pickle.dump(obj, file_pi)\n        file_pi.close()\n        \n    # save IMNN (optimiser) state:\n    savestate = jax.experimental.optimizers.unpack_optimizer_state(IMNN.state)\n    pckl_me(savestate, os.path.join(folder_name, 'IMNN_state'))\n    \n    # save weights\n    if weights == 'final':\n        np.save(os.path.join(folder_name, 'final_w'), IMNN.final_w)\n    \n    else:\n        np.save(os.path.join(folder_name, 'best_w'), IMNN.best_w)\n        \n    # save initial weights\n    np.save(os.path.join(folder_name, 'initial_w'), IMNN.initial_w)\n        \n    # save training history\n    pckl_me(IMNN.history, os.path.join(folder_name, 'history'))\n    \n    # save important attributes as a dict\n    imnn_attributes = {\n        'n_s': IMNN.n_s,\n        'n_d': IMNN.n_d,\n        'input_shape': IMNN.input_shape,\n        'n_params' : IMNN.n_params,            \n        'n_summaries': IMNN.n_summaries,\n        '\u03b8_fid': IMNN.\u03b8_fid,\n        'F': IMNN.F,   \n        'validate': IMNN.validate,\n        'simulate': IMNN.simulate,\n        \n    }\n    \n    pckl_me(imnn_attributes, os.path.join(folder_name, 'IMNN_attributes'))\n    \n    print('saved weights and attributes to the file ', folder_name)\n    \n    \ndef load_weights(IMNN, folder_name='./model', weights='final', load_attributes=True):\n    \n    \n    def unpckl_me(path):\n        file = open(path, 'rb')\n        return pickle.load(file)\n    \n    # load and assign weights\n    if weights=='final':\n        weights = np.load(os.path.join(folder_name, 'final_w.npy'),  allow_pickle=True)\n        IMNN.final_w = weights\n    else:\n        weights = np.load(os.path.join(folder_name, 'best_w.npy'),  allow_pickle=True)\n        IMNN.best_w = weights\n        \n    # re-pack and load the optimiser state\n    loadstate = unpckl_me(os.path.join(folder_name, 'IMNN_state'))\n    IMNN.state = jax.experimental.optimizers.pack_optimizer_state(loadstate)\n    \n    \n    # load history\n    IMNN.history = unpckl_me(os.path.join(folder_name, 'history'))\n    \n    # load important attributes\n    if load_attributes:\n        IMNN.intial_w =  np.load(os.path.join(folder_name, 'initial_w.npy'), allow_pickle=True)\n        attributes = unpckl_me(os.path.join('test_model', 'IMNN_attributes'))\n        IMNN.\u03b8_fid = attributes['\u03b8_fid']\n        IMNN.n_s = attributes['n_s']\n        IMNN.n_d = attributes['n_d']\n        IMNN.input_shape = attributes['input_shape']\n        \n    print('loaded IMNN with these attributes: ', attributes)\n    \n```\n\n\n```python\n# # test save functions\n# save_weights(IMNN, folder_name='./model')\n\n# # test load functions\n\n# # initialize a new imnn with different attributes and then load the old file\n# # to overwrite them\n\n# my_new_IMNN = SimIMNN(\n#         n_s=300,\n#         n_d=100,\n#         n_params=n_params,\n#         n_summaries=n_summaries,\n#         input_shape=input_shape,\n#         \u03b8_fid=np.array([1.0,1.0]),\n#         key=initial_model_key,\n#         model=model,\n#         optimiser=optimiser,\n#         simulator=lambda rng, \u03b8: simulator(rng, \u03b8, simulator_args=simulator_args),\n#         )\n\n# load_weights(my_new_IMNN, folder_name='./model', load_attributes=True)\n# my_new_IMNN.set_F_statistics(rng, my_new_IMNN.best_w, my_new_IMNN.\u03b8_fid, my_new_IMNN.n_s, my_new_IMNN.n_d, validate=True)\n```\n\n\n```python\nIMNN_rngs = 1 * [fitting_key] #+ 12 * [None]\nlabels = [\n    \"Simulator, InceptNet\\n\"\n]\n```\n\n\n```python\n\u03b8_fid\n```\n\n\n\n\n    DeviceArray([1. , 0.5], dtype=float32)\n\n\n\n\n```python\n%%time\nfor i in range(1):\n    rng,fit_rng = jax.random.split(rng)\n    IMNN.fit(\u03bb=10., \u03f5=\u03f5, rng=fit_rng, min_iterations=500) #for IMNN, IMNN_rng in zip(IMNNs, IMNN_rngs);\n    \n#save_weights(IMNN, folder_name='./big_incept128')\n```\n\n\n```python\nIMNNs = [IMNN]\n```\n\n\n```python\nfor i, (IMNN, label) in enumerate(zip(IMNNs, labels)):\n    if i == 0:\n        ax = imnn.training_plot(expected_detF=detf_expected, colour=\"C{}\".format(i), label=label)\n    elif i == 10:\n        other_ax = imnn.training_plot(\n            expected_detF=detf_expected, colour=\"C{}\".format(i), label=label\n        )\n    elif i == 11:\n        imnn.training_plot(\n            ax=other_ax,\n            expected_detF=50, colour=\"C{}\".format(i), label=label\n        )\n        other_ax[0].set_yscale(\"log\")\n        other_ax[2].set_yscale(\"log\")\n    else:\n        IMNN.training_plot(\n            ax=ax, expected_detF=None, colour=\"C{}\".format(i), label=label, ncol=5\n        );\nax[0].set_yscale(\"log\")\n```\n\n\n```python\nlatexify(fig_width=3.37)\nplt.plot(IMNN.history['detF'][:])\nplt.plot(np.ones(len(IMNN.history['detF'][:]))*detf_expected, c='k', linestyle='--')\nplt.ylim(1e-2, 1e7)\nplt.ylabel(r'$\\det \\textbf{F}$')\nplt.xlabel('number of epochs')\nplt.yscale('log')\nplt.tight_layout()\n#plt.savefig('/mnt/home/tmakinen/repositories/field-plots/128x128-training.png', dpi=400)\n```\n\n\n```python\nnp.linalg.det(IMNNs[0].F) #/ (detf_expected)\n```\n\n\n\n\n    DeviceArray(4280.8877, dtype=float32)\n\n\n\n\n```python\nIMNNs[0].F\n```\n\n\n\n\n    Buffer([[ 159.41925, -119.76941],\n            [-119.76941,  116.83406]], dtype=float32)\n\n\n\n\n```python\nprint('IMNN F:', IMNN.F)\n\nprint('IMNN det F:', np.linalg.det(IMNN.F))\n\nprint('IMNN F / analytic det F: ', (np.linalg.det(IMNN.F)) / detf_expected)\n```\n\n    IMNN F: [[ 159.41925 -119.76941]\n     [-119.76941  116.83406]]\n    IMNN det F: 4280.8877\n    IMNN F / analytic det F:  0.9360231527357517\n\n\n# Data for ABC example\n\n\n```python\nclass uniform:\n    def __init__(self, low, high):\n        self.low = np.array(low)\n        self.high = np.array(high)\n        self.event_shape = [[] for i in range(self.low.shape[0])]\n    def sample(self, n=None, seed=None):\n        if n is None:\n            n = 1\n        keys = np.array(jax.random.split(\n            seed, \n            num=len(self.event_shape)))\n        return jax.vmap(\n            lambda key, low, high : jax.random.uniform(\n                key, \n                shape=(n,), \n                minval=low, \n                maxval=high))(\n            keys, self.low, self.high)\n\n```\n\n\n```python\nprior = uniform([0.1, 0.1], [1.25, 1.25])\n```\n\n\n```python\nsimulator_args\n```\n\n\n\n\n    {'N': 32,\n     'L': 32.0,\n     'dim': 2,\n     'shape': (32, 32),\n     'vol_norm': True,\n     'N_scale': True,\n     'squeeze': False}\n\n\n\n\n```python\nsimulator_args = {\"N\": N, \"L\": 32, \"dim\": dim, \"shape\": shape, \"N_scale\": True, \"vol_norm\": True, \"squeeze\": True}\n\nrng, key = jax.random.split(rng)\n\u03b8_target = np.array([0.8, 0.8])\ntarget_data = simulator(\n    key,\n    \u03b8_target,\n    simulator_args={**simulator_args, **{'squeeze':False}})\n```\n\n\n```python\n%matplotlib inline\nplt.imshow(np.squeeze(target_data))\nplt.colorbar()\n```\n\n# analytic likelihood calculation\n\n\n```python\ngridsize = 100                # for likelihood gridding\n\u0394 = np.fft.fftn(np.squeeze(target_data))[:N//2, :N//2] / N\nk = kbin[:N//2, :N//2]  \nprior_range = np.array([[0.1, 0.1], [1.25, 1.25]])\nAL = analyticFieldLikelihood(PBJ, shape, \u0394, prior_range, k=k, gridsize=gridsize, tiling=[5,5])\n```\n\n\n```python\n%%time\n%matplotlib inline\n#plt.style.use('default')\nlikelihood,_ = AL.plot_contours(\u03b8_ref=\u03b8_target, shift=None, xlabel=r'$A$', ylabel=r'$B$', return_like=True)\n```\n\n# Gaussian approximation\n\n\n```python\n@jit #partial(jax.jit, static_argnums=0)\ndef get_estimate(d):\n    if len(d.shape) == 1:\n        return IMNN.\u03b8_fid + np.einsum(\n            \"ij,kj,kl,l->i\",\n            IMNN.invF,\n            IMNN.d\u03bc_d\u03b8,\n            IMNN.invC,\n            IMNN.model(IMNN.best_w, d, rng=rng) - IMNN.\u03bc)\n    else:\n        return IMNN.\u03b8_fid + np.einsum(\n            \"ij,kj,kl,ml->mi\",\n            IMNN.invF,\n            IMNN.d\u03bc_d\u03b8,\n            IMNN.invC,\n            IMNN.model(IMNN.best_w, d, rng=rng) - IMNN.\u03bc)\n```\n\n\n```python\nestimates = get_estimate(target_data) #[i.get_estimate(target_data) for i in IMNNs];\n```\n\n\n```python\ndetf_expected\n```\n\n\n\n\n    DeviceArray(4573.48483614, dtype=float64)\n\n\n\n\n```python\nGAs = [GaussianApproximation(get_estimate(target_data), IMNN.invF, prior)]\n       #GaussianApproximation(get_estimate(target_data), np.linalg.inv(f_expected), prior)]\n```\n\n\n```python\n%matplotlib inline\nfor i, (GA, label) in enumerate(zip(GAs, labels)):\n    if i == 0:\n        ax = GA.marginal_plot(\n            axis_labels=[r\"$A$\", r\"$B$\"], label='on-the-fly IMNN', colours=\"C{}\".format(i)\n        )\n    else:\n        GA.marginal_plot(ax=ax, label=label, colours=\"C{}\".format(i), ncol=8)\n```\n\n\n```python\nfig, ax = plt.subplots(2, 6, figsize=(30, 8))\nfor i, (GA, label) in enumerate(zip(GAs, labels)):\n    if i == 0:\n        ax1 = GA.marginal_plot(\n            ax=ax[:, :2],\n            axis_labels=[r\"$A$\", r\"$B$\"],\n            label=label,\n            target=0,\n            format=True,\n            colours=\"C{}\".format(i),\n        )\n        ax2 = GA.marginal_plot(\n            ax=ax[:, 2:4],\n            axis_labels=[r\"$A$\", r\"$B$\"],\n            target=1,\n            format=True,\n            colours=\"C{}\".format(i),\n        )\n        ax3 = GA.marginal_plot(\n            ax=ax[:, 4:],\n            axis_labels=[r\"$A$\", r\"$B$\"],\n            target=2,\n            format=True,\n            colours=\"C{}\".format(i),\n        )\n    else:\n        GA.marginal_plot(ax=ax1, label=label, target=0, colours=\"C{}\".format(i), bbox_to_anchor=(-0.05, 1.0))\n        GA.marginal_plot(ax=ax2, target=1, colours=\"C{}\".format(i))\n        GA.marginal_plot(ax=ax3, target=2, colours=\"C{}\".format(i))\n```\n\n# ABC\n\n\n```python\n{**simulator_args, **{'squeeze':True}}\n```\n\n\n\n\n    {'N': 32,\n     'L': 32,\n     'dim': 2,\n     'shape': (32, 32),\n     'N_scale': True,\n     'vol_norm': True,\n     'squeeze': True}\n\n\n\n\n```python\nABC = ApproximateBayesianComputation(\n        target_data, prior, \n     lambda A,B : simulator(A,B, simulator_args={**simulator_args, **{'squeeze':True}}), \n                                       get_estimate, F=IMNN.F, gridsize=50\n    )\n```\n\n\n```python\n%%time\nrng,abc_key = jax.random.split(rng)\nABC(rng=abc_key,\n        n_samples=int(1e3),\n        min_accepted=15000,\n        max_iterations=20000,\n        \u03f5=0.05,\n        smoothing=0.);\n```\n\n    1918 accepted in last  20000 iterations  (20000000 simulations done).\n    CPU times: user 34.9 s, sys: 1.42 s, total: 36.4 s\n    Wall time: 38 s\n\n\n\n\n\n    (<imnn.utils.container.container at 0x154b9cc3e1c0>,\n     <imnn.utils.container.container at 0x154b9c94f4f0>,\n     <imnn.utils.container.container at 0x154b9cb436d0>)\n\n\n\n\n```python\nABC.parameters.accepted[0].shape\n```\n\n\n\n\n    (3733, 2)\n\n\n\n\n```python\n#ax = ABC.scatter_plot(points=ABC.parameters.rejected, colours='red')\nax = ABC.scatter_plot()\n```\n\n\n```python\n#np.save(\"accepted.npy\", ABC.parameters.accepted)\n```\n\n\n```python\n#ax = ABC.scatter_summaries(points=ABC.summaries.rejected, colours='red')\nABC.scatter_summaries( colours='blue')\n```\n\n\n```python\nlikelihood,A_range,B_range = AL.get_likelihood(return_grid=True)\n```\n\n    computing likelihood on a 100x100 grid \n             in tiles of size 20x20\n    shift -334.61356055313496\n    loglike mean -382.4315989879251\n\n\n\n```python\n#A_range = np.linspace(0.1, 3.0, 25)\n#B_range = np.linspace(0.1, 2.5, 25)\nlikelihoodA = np.real(likelihood).sum(0)\nlikelihoodA /= likelihoodA.sum() * (A_range[1] -  A_range[0])\nlikelihoodB = np.real(likelihood).sum(1)\nlikelihoodB /= likelihoodB.sum() * (B_range[1] -  B_range[0])\nsorted_marginal = np.sort(np.real(likelihood).flatten())[::-1]\ncdf = np.cumsum(sorted_marginal / sorted_marginal.sum())\nvalue = []\nfor level in [0.95, 0.68]:\n    this_value = sorted_marginal[np.argmin(np.abs(cdf - level))]\n    if len(value) == 0:\n        value.append(this_value)\n    elif this_value <= value[-1]:\n        break\n    else:\n        value.append(this_value)\n#fig, ax = plt.subplots(2, 2, figsize=(10, 10))\n\n```\n\n\n```python\n%matplotlib inline\n#plt.style.use('default')\nnew_colors = [ '#2c0342', '#286d87', '#4fb49d', '#9af486']\nfig,ax = plt.subplots(nrows=2, ncols=2, figsize=(3.37*2, 3.37*2))\nlatexify(fig_width=3.37, fig_height=3.37)\n\nABC.scatter_plot(ax=ax,\n                      colours=new_colors[0], \n                      axis_labels=[r\"$A$\", r\"$B$\"], \n                      s=8,\n                      label='ABC estimate')\n# ABC.marginal_plot(ax=ax,\n#             axis_labels=[r\"$A$\", r\"$B$\"], colours='green',\n#             label='ABC marginal plot')\n\n\nGAs[0].marginal_plot(ax=ax, colours=new_colors[2], axis_labels=[r\"$A$\", r\"$B$\"], label=None, ncol=1)\nax[0,1].imshow(target_data[0, 0])\n\n#ax[0,1].set_title(r'$\\theta_{\\rm target} = A,B = (%.2f,%.2f)$'%(\u03b8_target[0], \u03b8_target[1]))\n\nax[0,0].axvline(\u03b8_target[0], linestyle='--', c='k')\nax[1,0].axvline(\u03b8_target[0], linestyle='--', c='k')\nax[1,0].axhline(\u03b8_target[1], linestyle='--', c='k')\nax[1,1].axhline(\u03b8_target[1], linestyle='--', c='k', label=r'$\\theta_{\\rm target}$')\n\nax[1,0].set_xlabel(r'$A$')\nax[1,0].set_ylabel(r'$B$')\n\nax[0,0].axvline(\u03b8_fid[0], linestyle='--', c='k', alpha=0.4)\n#ax[1,0].contourf(A_range, B_range, L1.reshape((size, size)))\n#ax[0, 0].plot(A_range, np.real(loglikeA), color='g', label='loglikeA')\n\nax[1,0].axvline(\u03b8_fid[0], linestyle='--', c='k', alpha=0.4)\nax[1,0].axhline(\u03b8_fid[1], linestyle='--', c='k', alpha=0.4)\nax[1,1].axhline(\u03b8_fid[1], linestyle='--', c='k', alpha=0.4, label=r'$\\theta_{\\rm fid}$')\n\nax[1,1].legend(framealpha=0.)\n\n\n# add in the likelihood estimate\nax[0, 0].plot(A_range, likelihoodA, color='#FF8D33', label=None)\nax[0, 1].axis(\"off\")\nax[1, 0].contour(A_range, B_range, np.real(likelihood), levels=value, colors='#FF8D33')\nax[1, 1].plot(likelihoodB, B_range, color='#FF8D33', label='loglike')\n\nax[0,0].legend(framealpha=0.)\n\n#plt.savefig('/mnt/home/tmakinen/repositories/field-plots/128x128-contours.png', dpi=400)\n#plt.subplots_adjust(wspace=0, hspace=0)\nplt.show()\n```\n\n\n```python\n# do PMC-ABC\nimport tensorflow_probability\ntfp = tensorflow_probability.experimental.substrates.jax\ntfd = tfp.distributions\ntfb = tfp.bijectors\n```\n\n\n```python\ndef new_ABC(rng, n_points, proposal_distribution, simulator, data_summary, f, n_parallel_simulations=None, simulator_parameters=None):\n    def get_distance(summaries, data_summary, f):\n        if len(data_summary.shape) > 1:\n            return jax.vmap(lambda data_summary, f : get_distance(summaries, data_summary, f))(data_summary, f)\n        if len(summaries.shape) == 1:\n            difference = summaries - data_summary\n            distance = difference.dot(f).dot(difference)\n            return jax.lax.cond(np.isnan(distance), lambda _ : np.inf, lambda distance : distance, distance)\n        elif len(summaries.shape) == 2:\n            return jax.vmap(lambda summaries : get_distance(summaries, data_summary, f), out_axes=-1)(summaries)\n        else:\n            return jax.vmap(lambda summaries : get_distance(summaries, data_summary, f), out_axes=-2)(summaries)\n    shape = (n_points,)\n    if n_parallel_simulations is not None:\n        shape = shape + (n_parallel_simulations,)\n    rng, key = jax.random.split(rng)\n    proposed = proposal_distribution.sample(shape, seed=key)\n    key = jax.random.split(rng, num=np.prod(np.array(proposed).shape[:-1]))\n    summaries = simulator(key.reshape(proposed.shape[:-1] + (2,)), proposed, simulator_parameters=simulator_parameters)\n    distances = get_distance(summaries, data_summary, f)\n    return proposed, summaries, distances\n```\n\n\n```python\ndef w_cov(proposed, weighting):\n    weighted_samples = proposed * weighting[:, np.newaxis]\n    return weighted_samples.T.dot(weighted_samples) / weighting.T.dot(weighting)\n```\n\n\n```python\nclass tmvn():\n    def __init__(self, loc, scale, low, high, max_counter=int(1e3)):\n        self.loc = loc\n        self.scale = scale\n        self.low = low\n        self.high = high\n        if len(loc.shape) > 1:\n            self.n_samples = loc.shape[0]\n        else:\n            self.n_samples = None\n        self.n_params = low.shape[0]\n        self.max_counter = max_counter\n\n    def mvn(self, rng, loc):\n        u = jax.random.normal(rng, shape=(self.n_params,))\n        return loc + u.dot(self.scale)\n\n    def w_cond(self, args):\n        _, loc, counter = args\n        return np.logical_and(\n            np.logical_or(\n                np.any(np.greater(loc, self.high)),\n                np.any(np.less(loc, self.low))),\n            np.less(counter, self.max_counter))\n\n    def __sample(self, args):\n        rng, loc, counter = args\n        rng, key = jax.random.split(rng)\n        return (rng, self.mvn(key, loc), counter+1)\n\n    def _sample(self, rng, loc):\n        rng, key = jax.random.split(rng)\n        _, loc, counter = jax.lax.while_loop(\n            self.w_cond, \n            self.__sample, \n            (rng, self.mvn(key, loc), 0))\n        return jax.lax.cond(\n            np.greater_equal(counter, self.max_counter),\n            lambda _ : np.nan * np.ones((self.n_params,)),\n            lambda _ : loc,\n            None)\n\n    def _sample_n(self, rng, loc, n=None):\n        if n is None:\n            return self._sample(rng, loc)\n        else:\n            key = jax.random.split(rng, num=n)\n            return jax.vmap(self._sample)(key, \n                np.repeat(loc[np.newaxis], n, axis=0))\n\n    def sample(self, shape=None, seed=None):\n        if shape is None:\n            if self.n_samples is None:\n                return self._sample_n(seed, self.loc)\n            else:\n                key = jax.random.split(seed, num_self.n_samples)\n                return jax.vmap(lambda key, loc : self._sample_n(key, loc))(key, self.loc)\n        elif len(shape) == 1:\n            if self.n_samples is None:\n                return self._sample_n(seed, self.loc, n=shape[0])\n            else:\n                key = jax.random.split(seed, num_self.n_samples)\n                return jax.vmap(lambda key, loc : self._sample_n(key, loc, n=shape[0]))(key, self.loc)\n        else:\n            key = jax.random.split(seed, num=shape[-1])\n            return jax.vmap(lambda key: self.sample(shape=tuple(shape[:-1]), seed=key), out_axes=-2)(key)\n```\n\n\n```python\ndef PMC(rng, n_initial_points, n_points, prior, simulator, data_summary, f, percentile=75, acceptance_ratio=0.1, \n        max_iteration=10, max_acceptance=10, max_samples=int(1e3), n_parallel_simulations=None, simulator_parameters=None):\n    low = np.array([dist.low for dist in prior.distributions])\n    high = np.array([dist.high for dist in prior.distributions])\n    def single_PMC(rng, samples, summaries, distances, weighting, data_summary, f):\n        def single_iteration_condition(args):\n            return np.logical_and(\n                np.greater(args[-3], acceptance_ratio),\n                np.less(args[-2], max_iteration))\n        def single_iteration(args):\n            def single_acceptance_condition(args):\n                return np.logical_and(\n                    np.less(args[-2], 1),\n                    np.less(args[-1], max_acceptance))\n            def single_acceptance(args):\n                rng, loc, summ, dist, draws, accepted, acceptance_counter = args\n                #rng, loc, summ, dist, draws, rejected, acceptance_counter = args\n                rng, key = jax.random.split(rng)\n                proposed, summaries, distances = new_ABC(\n                    key, None, tmvn(loc, scale, low, high, max_counter=max_samples),\n                    simulator, data_summary, f, n_parallel_simulations=n_parallel_simulations,\n                    simulator_parameters=simulator_parameters)\n                if n_parallel_simulations is not None:\n                    min_distance_index = np.argmin(distances)\n                    min_distance = distances[min_distance_index]\n                    closer = np.less(min_distance, \u03f5)\n                    loc = jax.lax.cond(closer, lambda _ : proposed[min_distance_index], lambda _ : loc, None)\n                    summ = jax.lax.cond(closer, lambda _ : summaries[min_distance_index], lambda _ : summ, None)\n                    dist = jax.lax.cond(closer, lambda _ : distances[min_distance_index], lambda _ : dist, None)\n                    iteration_draws = n_parallel_simulations - np.isinf(distances).sum()\n                    draws += iteration_draws \n                    accepted = closer.sum()\n                    #rejected = iteration_draws - closer.sum()\n                else:\n                    closer = np.less(distances, dist)\n                    loc = jax.lax.cond(closer, lambda _ : proposed, lambda _ : loc, None)\n                    summ = jax.lax.cond(closer, lambda _ : summaries, lambda _ : summ, None)\n                    dist = jax.lax.cond(closer, lambda _ : distances, lambda _ : dist, None)\n                    iteration_draws = 1 - np.isinf(distances).sum()\n                    draws += iteration_draws\n                    accepted = closer.sum()\n                    #rejected = iteration_draws - closer.sum()\n                return (rng, loc, summ, dist, draws, accepted, acceptance_counter+1)\n                #return (rng, loc, summ, dist, draws, rejected, acceptance_counter+1)\n\n            rng, samples, summaries, distances, weighting, data_summary, f, acceptance_reached, iteration_counter, total_draws = args\n            \u03f5 = distances[\u03f5_ind]\n            loc = samples[\u03f5_ind:]\n            cov = w_cov(samples, weighting)\n            inv_cov = np.linalg.inv(cov)\n            scale = np.linalg.cholesky(cov)\n            rng, *key = jax.random.split(rng, num=loc.shape[0]+1)\n            draws = np.zeros(loc.shape[0], dtype=np.int32)\n            accepted = np.zeros(loc.shape[0], dtype=np.int32)\n            #rejected = np.zeros(loc.shape[0], dtype=np.int32)\n            acceptance_counter = np.zeros(loc.shape[0], dtype=np.int32)\n\n            results = jax.vmap(\n                lambda key, loc, summaries, distances, draws, accepted, acceptance_counter : jax.lax.while_loop(\n                #lambda key, loc, summaries, distances, draws, rejected, acceptance_counter : jax.lax.while_loop(\n                    single_acceptance_condition, single_acceptance, (key, loc, summaries, distances, draws, accepted, acceptance_counter)))(\n                    #single_acceptance_condition, single_acceptance, (key, loc, summaries, distances, draws, rejected, acceptance_counter)))(\n                np.array(key), loc, summaries[\u03f5_ind:], distances[\u03f5_ind:], draws, accepted, acceptance_counter)\n                #np.array(key), loc, summaries[\u03f5_ind:], distances[\u03f5_ind:], draws, rejected, acceptance_counter)\n\n            weighting = jax.vmap(\n                lambda proposed : (\n                    prior.prob(proposed) \n                    / (np.sum(weighting * tfd.MultivariateNormalTriL(\n                        loc=samples,\n                        scale_tril=np.repeat(\n                            scale[np.newaxis], \n                            samples.shape[0], \n                            axis=0)).prob(proposed)))))(\n                    np.vstack([samples[:\u03f5_ind], results[1]]))\n            samples = jax.ops.index_update(samples, jax.ops.index[\u03f5_ind:, :], results[1])\n            summaries = jax.ops.index_update(summaries, jax.ops.index[\u03f5_ind:, :], results[2])\n            distances = jax.ops.index_update(distances, jax.ops.index[\u03f5_ind:], results[3])\n            acceptance_reached = results[-2].sum() / results[-3].sum()\n            return (rng, samples, summaries, distances, weighting, data_summary, f, acceptance_reached, iteration_counter+1, total_draws+results[-3].sum())\n\n        acceptance_reached = np.inf\n        iteration_counter = 0\n        total_draws = 0\n        results = jax.lax.while_loop(\n            single_iteration_condition, \n            single_iteration, \n            (rng, samples, summaries, distances, weighting, data_summary, f, acceptance_reached, iteration_counter, total_draws))\n        return results[1], results[2], results[3], results[4], results[7], results[8], results[9]\n\n    rng, key = jax.random.split(rng)\n    proposed, summaries, distances = new_ABC(\n        key, n_initial_points, prior, simulator, data_summary, f, \n        n_parallel_simulations=n_parallel_simulations, simulator_parameters=simulator_parameters)\n\n    if n_parallel_simulations is not None:\n        proposed = proposed.reshape((n_initial_points * n_parallel_simulations, -1))\n        summaries = summaries.reshape((n_initial_points * n_parallel_simulations, -1))\n        if len(data_summary.shape) > 1:\n            distances = distances.reshape((data_summary.shape[0], -1))\n        else:\n            distances = distances.reshape((-1,))\n\n    if len(data_summary.shape) == 1:\n        sample_indices = np.argsort(distances)[:n_points]\n        samples = proposed[sample_indices]\n        summaries = summaries[sample_indices]\n        distances = distances[sample_indices]\n    else:\n        sample_indices = np.argsort(distances, axis=1)[:, :n_points]\n        samples = jax.vmap(lambda x: proposed[x])(sample_indices)\n        summaries = jax.vmap(lambda x: summaries[x])(sample_indices)\n        distances = np.take_along_axis(distances, sample_indices, axis=1)    \n\n    weighting = prior.prob(samples)\n\n    if percentile is None:\n        \u03f5_ind = -1\n        to_accept = 1\n    else:\n        \u03f5_ind = int(percentile / 100 * n_points)\n        to_accept = n_points - \u03f5_ind\n\n    if len(data_summary.shape) == 1:\n        return single_PMC(rng, samples, summaries, distances, weighting, data_summary, f)\n    else:\n        key = jax.random.split(rng, num=data_summary.shape[0])\n        return jax.vmap(single_PMC)(key, samples, summaries, distances, weighting, data_summary, f)\n```\n\n\n```python\ntarge_data_summary = get_estimate(target_data)\n```\n\n\n```python\nlow = np.array([0.1, 0.1])\nhigh = np.array([2., 2.])\nmyprior = tfd.Blockwise([tfd.Uniform(low=low[i], high=high[i]) for i in range(low.shape[0])])\n```\n\n\n```python\nrng, key = jax.random.split(rng)\nppmc_prop, ppmc_summ, ppmc_dist, ppmc_w, ppmc_crit, ppmc_it, ppmc_draws = PMC(\n    rng=key, n_initial_points=1000, n_points=250, prior=myprior, simulator=simulator, \n    data_summary=targe_data_summary, f=IMNN.F, percentile=75, acceptance_ratio=0.5, \n    max_iteration=int(1e2), max_acceptance=int(1e3), max_samples=int(1e3), \n    n_parallel_simulations=100, simulator_parameters=(low, high, input_shape))\n```\n\n\n```python\n# Create figures in Python that handle LaTeX, and save images to files in my\n# preferred formatting. I typically place this code in the root of each of my\n# projects, and import using:\n# from latexify import *\n# which will also run the latexify() function on the import.\n\n# Based on code from https://nipunbatra.github.io/blog/2014/latexify.html\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom math import sqrt\n\n#Back-end to use depends on the system\nfrom matplotlib.backends.backend_pgf import FigureCanvasPgf\nmatplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf)\n# matplotlib.use('pgf')\n# from matplotlib.backends.backend_pgf import FigureCanvasPgf\n# matplotlib.backend_bases.register_backend('ps', FigureCanvasPgf)\n\nimport seaborn as sns\nsns.set_style(\"white\")\n\n#my preferred palette. From\n#https://seaborn.pydata.org/tutorial/color_palettes.html: \"The cubehelix color\n#palette system makes sequential palettes with a linear increase or decrease in\n#brightness and some variation in hue. This means that the information in your\n#colormap will be preserved when converted to black and white (for printing) or\n#when viewed by a colorblind individual.\"\n\n# I typically set the number of colors (below, 8) to the distinct colors I need\n# in a given plot, so as to use the full range.\nsns.set_palette(sns.color_palette(\"cubehelix\", 8))\n\n\n# The following is the latexify function. It allows you to create 2 column or 1\n# column figures. You may also wish to alter the height or width of the figure.\n# The default settings are good for most cases. You may also change the\n# parameters such as labelsize and fontsize based on your classfile.\ndef latexify(fig_width=None, fig_height=None, columns=1):\n    \"\"\"Set up matplotlib's RC params for LaTeX plotting.\n    Call this before plotting a figure.\n    Parameters\n    ----------\n    fig_width : float, optional, inches\n    fig_height : float,  optional, inches\n    columns : {1, 2}\n    \"\"\"\n\n    # code adapted from http://www.scipy.org/Cookbook/Matplotlib/LaTeX_Examples\n    # Width and max height in inches for IEEE journals taken from\n    # computer.org/cms/Computer.org/Journal%20templates/transactions_art_guide.pdf\n\n    assert(columns in [1, 2])\n\n    if fig_width is None:\n        fig_width = 6.9 if columns == 1 else 13.8  # width in inches #3.39\n\n    if fig_height is None:\n        golden_mean = (sqrt(5) - 1.0) / 2.0    # Aesthetic ratio\n        fig_height = fig_width * golden_mean  # height in inches\n\n    MAX_HEIGHT_INCHES = 16.0\n    if fig_height > MAX_HEIGHT_INCHES:\n        print((\"WARNING: fig_height too large:\" + fig_height +\n              \"so will reduce to\" + MAX_HEIGHT_INCHES + \"inches.\"))\n        fig_height = MAX_HEIGHT_INCHES\n\n    params = {\n            # 'backend': 'ps',\n           #   'pgf.rcfonts': False,\n           #   'pgf.preamble': ['\\\\usepackage{gensymb}', '\\\\usepackage[dvipsnames]{xcolor}'],\n           #   \"pgf.texsystem\": \"pdflatex\",\n             # 'text.latex.preamble': ['\\\\usepackage{gensymb}', '\\\\usepackage[dvipsnames]{xcolor}'],\n              'text.latex.preamble': '\\\\usepackage{mathptmx}',\n              #values below are useful defaults. individual plot fontsizes are\n              #modified as necessary.\n              'axes.labelsize': 8,  # fontsize for x and y labels\n              'axes.titlesize': 8,\n              'font.size': 8,\n              'legend.fontsize': 8,\n              'xtick.labelsize': 6,\n              'ytick.labelsize': 6,\n              'text.usetex': True,\n              'figure.figsize': [fig_width, fig_height],\n              'font.family': 'serif',\n              'font.serif': 'Times',\n               'lines.linewidth': 1.5,\n               'lines.markersize':1,\n               'xtick.major.pad' : 2,\n               'ytick.major.pad' : 2,\n                'axes.xmargin' :  .0,  # x margin.  See `axes.Axes.margins`\n                'axes.ymargin' : .0,  # y margin See `axes.Axes.margins`\n              }\n\n    matplotlib.rcParams.update(params)\n\ndef saveimage(name, fig = plt, extension = 'pdf', folder = 'plots/'):\n    sns.despine()\n\n    #Minor ticks off by default in matplotlib\n    # plt.minorticks_off()\n\n    #grid being off is the default for seaborn white style, so not needed.\n    # plt.grid(False, axis = \"x\")\n    # plt.grid(False, axis = \"y\")\n    \n    fig.savefig('{}{}.{}'.format(folder,name, extension), bbox_inches = 'tight')\n\nlatexify()\n```\n\n\n```python\n!python -m pip install seaborn\n```\n\n    Collecting seaborn\n      Using cached seaborn-0.11.1-py3-none-any.whl (285 kB)\n    Requirement already satisfied: scipy>=1.0 in /mnt/home/tmakinen/anaconda3/envs/pyjax9/lib/python3.8/site-packages (from seaborn) (1.6.2)\n    Collecting pandas>=0.23\n      Downloading pandas-1.2.3-cp38-cp38-manylinux1_x86_64.whl (9.7 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 9.7 MB 31.4 MB/s eta 0:00:01\n    \u001b[?25hRequirement already satisfied: numpy>=1.15 in /mnt/home/tmakinen/anaconda3/envs/pyjax9/lib/python3.8/site-packages (from seaborn) (1.19.5)\n    Requirement already satisfied: matplotlib>=2.2 in /mnt/home/tmakinen/anaconda3/envs/pyjax9/lib/python3.8/site-packages/matplotlib-3.4.1-py3.8-linux-x86_64.egg (from seaborn) (3.4.1)\n    Requirement already satisfied: cycler>=0.10 in /mnt/home/tmakinen/anaconda3/envs/pyjax9/lib/python3.8/site-packages/cycler-0.10.0-py3.8.egg (from matplotlib>=2.2->seaborn) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /mnt/home/tmakinen/anaconda3/envs/pyjax9/lib/python3.8/site-packages/kiwisolver-1.3.1-py3.8-linux-x86_64.egg (from matplotlib>=2.2->seaborn) (1.3.1)\n    Requirement already satisfied: pillow>=6.2.0 in /mnt/home/tmakinen/anaconda3/envs/pyjax9/lib/python3.8/site-packages/Pillow-8.1.2-py3.8-linux-x86_64.egg (from matplotlib>=2.2->seaborn) (8.1.2)\n    Requirement already satisfied: pyparsing>=2.2.1 in /mnt/home/tmakinen/anaconda3/envs/pyjax9/lib/python3.8/site-packages (from matplotlib>=2.2->seaborn) (2.4.7)\n    Requirement already satisfied: python-dateutil>=2.7 in /mnt/home/tmakinen/anaconda3/envs/pyjax9/lib/python3.8/site-packages (from matplotlib>=2.2->seaborn) (2.8.1)\n    Requirement already satisfied: six in /mnt/home/tmakinen/anaconda3/envs/pyjax9/lib/python3.8/site-packages (from cycler>=0.10->matplotlib>=2.2->seaborn) (1.15.0)\n    Collecting pytz>=2017.3\n      Downloading pytz-2021.1-py2.py3-none-any.whl (510 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 510 kB 139.4 MB/s eta 0:00:01\n    \u001b[?25hInstalling collected packages: pytz, pandas, seaborn\n    Successfully installed pandas-1.2.3 pytz-2021.1 seaborn-0.11.1\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "85027de6e645863108ff4d09002931e61ccfe22a", "size": 591462, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "scratch/fields/2D fields demo.ipynb", "max_stars_repo_name": "tlmakinen/kosmo-kompress", "max_stars_repo_head_hexsha": "2282e20d26dfc523e5705c0e02e0524b639df8a4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-07-16T05:22:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T12:41:06.000Z", "max_issues_repo_path": "scratch/fields/2D fields demo.ipynb", "max_issues_repo_name": "tlmakinen/FieldIMNNs", "max_issues_repo_head_hexsha": "1b363559116136d276b7c085b56a80520a7b0830", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scratch/fields/2D fields demo.ipynb", "max_forks_repo_name": "tlmakinen/FieldIMNNs", "max_forks_repo_head_hexsha": "1b363559116136d276b7c085b56a80520a7b0830", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 175.5080118694, "max_line_length": 102700, "alphanum_fraction": 0.867371023, "converted": true, "num_tokens": 28800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295203152605, "lm_q2_score": 0.07263670485515991, "lm_q1q2_score": 0.032361796271400546}}
{"text": "### Checklist for submission\n\nIt is extremely important to make sure that:\n\n1. Everything runs as expected (no bugs when running cells);\n2. The output from each cell corresponds to its code (don't change any cell's contents without rerunning it afterwards);\n3. All outputs are present (don't delete any of the outputs);\n4. Fill in all the places that say `# YOUR CODE HERE`, or \"**Your answer:** (fill in here)\".\n5. Never copy/paste any notebook cells. Inserting new cells is allowed, but it should not be necessary.\n6. The notebook contains some hidden metadata which is important during our grading process. **Make sure not to corrupt any of this metadata!** The metadata may for example be corrupted if you copy/paste any notebook cells, or if you perform an unsuccessful git merge / git pull. It may also be pruned completely if using Google Colab, so watch out for this. Searching for \"nbgrader\" when opening the notebook in a text editor should take you to the important metadata entries.\n7. Although we will try our very best to avoid this, it may happen that bugs are found after an assignment is released, and that we will push an updated version of the assignment to GitHub. If this happens, it is important that you update to the new version, while making sure the notebook metadata is properly updated as well. The safest way to make sure nothing gets messed up is to start from scratch on a clean updated version of the notebook, copy/pasting your code from the cells of the previous version into the cells of the new version.\n8. If you need to have multiple parallel versions of this notebook, make sure not to move them to another directory.\n9. Although not forced to work exclusively in the course `conda` environment, you need to make sure that the notebook will run in that environment, i.e. that you have not added any additional dependencies.\n\n**FOR HA1, HA2, HA3 ONLY:** Failing to meet any of these requirements might lead to either a subtraction of POEs (at best) or a request for resubmission (at worst).\n\nWe advise you to perform the following steps before submission to ensure that requirements 1, 2, and 3 are always met: **Restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart) and then **run all cells** (in the menubar, select Cell$\\rightarrow$Run All). This might require a bit of time, so plan ahead for this (and possibly use Google Cloud's GPU in HA1 and HA2 for this step). Finally press the \"Save and Checkout\" button before handing in, to make sure that all your changes are saved to this .ipynb file.\n\n### Fill in name of notebook file\nThis might seem silly, but the version check below needs to know the filename of the current notebook, which is not trivial to find out programmatically.\n\nYou might want to have several parallel versions of the notebook, and it is fine to rename the notebook as long as it stays in the same directory. **However**, if you do rename it, you also need to update its own filename below:\n\n\n```python\n# nb_fname = \"XXX.ipynb\"\n```\n\n### Fill in group number and member names (use NAME2 and GROUP only for HA1, HA2 and HA3):\n\n\n```python\nNAME1 = \"\" \nNAME2 = \"\"\nGROUP = \"\"\n```\n\n### Check Python version\n\n\n```python\nfrom platform import python_version_tuple\nassert python_version_tuple()[:2] == ('3','7'), \"You are not running Python 3.7. Make sure to run Python through the course Conda environment.\"\n```\n\n### Check that notebook server has access to all required resources, and that notebook has not moved\n\n\n```python\nimport os\nnb_dirname = os.path.abspath('')\nassignment_name = os.path.basename(nb_dirname)\nassert assignment_name in ['IHA1', 'IHA2', 'HA1', 'HA2', 'HA3'], \\\n    '[ERROR] The notebook appears to have been moved from its original directory'\n```\n\n### Verify correct nb_fname\n\n\n```python\nfrom IPython.display import display, HTML\ntry:\n    display(HTML(r''.format(nb_fname=nb_fname)))\nexcept NameError:\n    assert False, 'Make sure to fill in the nb_fname variable above!'\n```\n\n### Verify that your notebook is up-to-date and not corrupted in any way\n\n\n```python\nimport sys\nsys.path.append('..')\nfrom ha_utils import check_notebook_uptodate_and_not_corrupted\ncheck_notebook_uptodate_and_not_corrupted(nb_dirname, nb_fname)\n```\n\n# HA2:  Part 2 - Transformers and self-attention\n$$\n\\renewcommand{\\vec}[1]{#1}\n\\def\\x{\\vec{x}}\n\\def\\y{\\vec{y}}\n\\def\\dim{d}\n\\def\\w{W}\n\\def\\wu{Z}\n\\def\\R{\\mathbb{R}}\n\\def\\linMap{W}\n% Query, key and val\n\\def\\q{\\vec{q}}\n\\def\\k{\\vec{k}}\n\\def\\v{\\vec{v}}\n\\def\\Wq{\\linMap_Q}\n\\def\\Wk{\\linMap_K}\n\\def\\Wv{\\linMap_V}\n$$\n*You should have completed part 1 before starting with this one*\n\nIn this part we will take a closer look at the transformer architecture and the self-attention operation.\nWe will start with basic self-attention and gradually construct an actual self-attention module.\nFinally we will construct a complete transformer and test it on an actual problem.\n\nThe focus is on a conceptual understanding of the transformer but you will have to implement a few key elements of a transformer. Along the way we will try to give some best practices for constructing a more complex network architecture.\n\nLet's start with importing the module's we are going to need:\n\n\n```python\nimport torch\nimport torch.nn as torch_nn\nimport torch.nn.functional as F\n```\n\n# 1. Basic self-attention\n\nThe key-stone of the transformer architecture, self-attention is a sequence-sequence operation which transforms a sequence of input vectors $\\x_1, \\dots \\x_t$ to output vectors $\\y_1, \\dots \\y_t$.\nRemember that all vectors have the same dimension $\\dim$, i.e. $\\x_i, \\y_i \\in \\R^{\\dim}, \\forall i = 1, \\dots t$.\n\n## Weighted average\nThe actual transformation is a simple weighted average\n$$\n\\y_i = \\sum_{j} \\x_j \\w_{ji}.\n$$\n\nIn an actual transformer, weighted averages are computed often and for long sequences. Therefore, the implementation must be fast in order for training to be even possible.\nWith high-level frameworks such as `pytorch`, the key to fast code is often to reduce loops and instead express computations as matrix operations.\n\n**[3 points]** Complete the function snippet below to implement simple weight sharing.\n\nTo pass this part of the assignment your implementation only has to be correct, not efficient, but to get one extra point, you must implement it with just a single for loop. For two extra points, do it without any loops at all.\n\n*Hint*: Take a look at how `torch.bmm` is used later in the implementation\n\n\n```python\ndef weighted_avg(x, weights):\n    \"\"\"Weighted average\n    Calculates a weighted average of a batch of sequences of vectors.\n    \n    Args:\n        x (torch.Tensor): Shape (batch_size, dim, seq_len)\n        weights (torch.Tensor): Shape (batch_size, seq_len, seq_len)\n    \n    Returns:\n        y (torch.Tensor): Shape (batch_size, dim, seq_len)\n    \"\"\"\n    # YOUR CODE HERE\n```\n\nMake sure to test your implementation with the unit tests below.\nThe tests cover:\n\n1. Dimensionality\n2. Uniform weights $\\w_{ji} = \\frac{1}{t}$ should produce $y_i: y_i = \\frac{1}{\\dim} \\sum_{j} x_j,\\, \\forall i = 1, \\dots t$\n (i.e., every $y_i$ is an average of the input sequence).\n3. A specific numerical example with batch size = 2, $t = 2,\\, \\dim=1$.\n\n\n```python\ndef test_weighted_avg(function):\n    \"\"\"\n    Args:\n        function: Implementation to test\n    \"\"\"\n    # Testing dimension of averaged tensor.\n    batch_size, dim, seq_len = 5, 2, 3\n    x = torch.rand(batch_size, dim, seq_len)\n    weights = torch.rand(batch_size, seq_len, seq_len)\n    y = function(x, weights)\n    assert y.shape == (batch_size, dim, seq_len), \"Dimension error: expected y to have shape {}, got {}.\".format(\n        (batch_size, seq_len, dim), tuple(y.shape))\n    \n    # Testing uniform weights preserve x.\n    batch_size, dim, seq_len = 5, 2, 3\n    x = torch.rand(batch_size, dim, seq_len)\n    weights = torch.ones((batch_size, seq_len, seq_len)).float() / seq_len\n    y = function(x, weights)\n    assert all(torch.allclose(y_b.mean(1), y_b[:, 0]) for y_b in y),\\\n        \"Numerical error: With uniform weights, expected y_i = y_j forall i, j (within each batch).\"\n    assert all(torch.allclose(y_b.mean(1), x_b.mean(1)) for (x_b, y_b) in zip(x, y)),\\\n        \"Numerical error: With uniform weights, expected y_i = sum_j x_j, for all i\"\n    \n    # Actual numerical example.\n    x = torch.tensor([4, 1]).reshape((1, 1, 2)).float()\n    unnorm_weights = torch.arange(1, 5).reshape((1, 2, 2)).float()\n    scale = unnorm_weights.sum(1).reshape((1, 1, 2))\n    weights = unnorm_weights / scale\n\n    y = function(x, weights)\n    y_true = torch.tensor([7/4, 2]).reshape(1, 1, 2).float()\n    assert torch.allclose(y, y_true), \"Numerical error, expected: {}, got {}\".format(y_true, y)\n    \n    print(\"Test passed.\")\n\ntest_weighted_avg(function=weighted_avg)\n```\n\n## Defining weights through the dot product\nA simple way to define $\\w_{ji}$ is with the dot product\n\n$$\n\\wu_{ji} = \\x_j^T \\x_i.\n$$\nwhich maps the pair of input vectors to a non-negative scalar, $\\R^{\\dim \\times \\dim} \\to [0, \\infty)$.\nWe then use a softmax to obtain normalised $\\w_{ji} \\in (0, 1]$:\n\n$$\n\\w_{ji} = \\frac{ e^{\\wu_{ji}} }{ \\sum_j e^{\\wu_{ji}} }.\n$$\n\n**[2 points]** What is the difference between these weights and the weights in ordinary networks, e.g. a CNN?\n\n**Your answer:** (fill in here)\n\nThe dot product is essential for calculating the weights. As we progress, we will make slight modifications to the inputs but we will still base it around a function which calculates a softmax-normalized dot product. Therefore, you need to complete the implementation below **[3 points]**:\n\nAgain, this function will be evaluated often and for long sequences in the transformer block. For all points, implement it without using for loops.\n\n\n```python\ndef normalized_dot_product(v_1, v_2):\n    \"\"\"Normalized dot products between all pairs of vectors in a sequence\n    Takes two batches of sequences of vectors as input.\n    Sequences in the batch are processed independently.\n    The normalization is done with a softmax function along the columns of the weight matrices.\n    \n    Args:\n        v_1 (torch.Tensor): Shape (batch_size, dim, seq_len)\n        v_2 (torch.Tensor): Shape (batch_size, dim, seq_len)\n\n    Returns:\n        norm_dot_prod (torch.Tensor): Shape (batch_size, seq_len, seq_len)\n    \"\"\"\n    \n    # YOUR CODE HERE\n```\n\nMake sure to test your implementation with the unit tests below.\nThe tests cover:\n\n1. Dimensionality\n2. Normalized in the correct dimension\n3. A specific numerical example\n\n\n```python\nimport numpy as np\n\ndef test_normalized_dot_product(function):\n    \"\"\"\n    Args:\n        function: Implementation to test\n    \"\"\"\n    \n    batch_size, dim, seq_len = 5, 2, 3\n    v_1 = torch.rand(batch_size, dim, seq_len)\n    v_2 = torch.rand(batch_size, dim, seq_len)\n    weights = function(v_1, v_2)\n    \n    # Testing dimension of weights.\n    assert weights.shape == (batch_size, seq_len, seq_len),\\\n    \"Dimension error: expected weights to have shape {}, got {}.\".format(\n        (batch_size, seq_len, seq_len), tuple(weights.shape))\n    \n    # Testing weights non-negative\n    # (Boolean tensor's can be reduced to a single boolean)\n    assert not (weights < 0.0).any() ,\\\n    \"Value error: expected weights to be non-negative.\"\n    \n    # Testing weights smaller than one\n    assert (weights < 1.0).all() ,\\\n    \"Value error: expected weights to be non-negative.\"\n    \n    assert torch.allclose(weights.sum(1), torch.ones((batch_size, seq_len))),\\\n        \"ValueError: expected columns (dim 1) to sum to 1.0\"\n    \n    # Actual numerical example\n    v_1 = torch.tensor([[1, 2], [-1, 1]]).float().reshape((1, 2, 2))\n    v_2 = torch.tensor([[1, 0], [1, -1]]).float().reshape((1, 2, 2))\n    e = np.exp(1)\n    true_weights = torch.tensor([\n        [1 / (e**3 + 1), e**2 / (e**2 + 1)],\n        [e**3 / (e**3 + 1), 1 / (e**2 + 1)]\n    ]).reshape((1, 2, 2))\n    weights =  function(v_1, v_2)\n    assert torch.allclose(true_weights, weights),\\\n    \"Numerical error: expected {}, got {}.\".format(true_weights, weights)\n    \n    print(\"Test passed.\")   \n    \ntest_normalized_dot_product(function=normalized_dot_product)\n```\n\nThat's it, we have now the building blocks needed for basic self-attention:\n\n\n```python\ndef basic_self_attention(x):\n    \"\"\"Basic self-attention\n    Transforms a batch of sequences of vectors.\n    \n    Args:\n        x (torch.Tensor): Shape (batch_size, dim, seq_len)\n    \n    Returns:\n        y (torch.Tensor): Shape (batch_size, dim, seq_len)\n    \"\"\"\n    weights = normalized_dot_product(x, x)\n    return weighted_avg(x, weights)\n```\n\n# 2. A self-attention module\nLike you saw in the video lectures, self-attention is rarely used in the basic form we have created above.\nLet's do the modifications needed to construct an actual transformer.\n\nWe will wrap it in a proper `torch.nn` module to create a building block that we can use in a network.\nCreating your own module is actually not that common, frameworks like `pytorch` are built to be *modular* and we can often create very specific networks by combining standard modules. That is a good thing, since it enables us to express interesting models in a high-level interface and as a bonus, we build a model from well-tested and efficient parts.\nWith that said, you might find yourself in a situation (perhaps already in the project) where no off-the-shelf module suits your need and you have to create one yourself. View this latter part as an example/inspiration of how to construct a non-trivial custom module.\n\n## Queries, keys and values\nThe self-attention is extended with three linear mappings $\\Wq, \\Wk, \\Wv \\in \\R^{\\dim \\times \\dim}$ .\nThese give us learnable parameters and make self-attention more flexible.\nThe three matrices map the input $\\x_i$ into a query, key and value respectively:\n\n\\begin{align}\n    \\q_i = \\Wq \\x_i \\\\\n    \\k_i = \\Wk \\x_i \\\\\n    \\v_i = \\Wv \\x_i\n\\end{align}\n\nFirst, we modify the self-attention by redefining the unnormalized weights (while reusing the notation):\n\n\\begin{align}\n    \\wu_{ji} = \\q_j^T \\k_i \\Big{/} \\sqrt{\\dim}\n\\end{align}\nThe normalized weights are still obtained by applying the softmax function.\n\n**[2 points]** Explain why we scale the dot product with the factor $1 / \\sqrt{\\dim}$.\n\n**Your answer:** (fill in here)\n\nFinally, the weighted average modified and is now based on the values $\\v_j$, instead of on $\\x_j$ directly:\n$$\n\\y_i = \\sum_{j} \\v_j \\w_{ji}.\n$$\n\nWe can reuse our dot product calculation by simple *wrapping* it in a function that takes queries and keys as the argument:\n\n\n```python\ndef query_key_weights(queries, keys):\n    \"\"\"Weights from query-key dot product.\n    Softmax-normalised dot product weights\n    Calculates weights for a batch of sequences of vectors.\n    \n    Args:\n        queries (torch.Tensor): Shape (batch_size, dim, seq_len)\n        keys (torch.Tensor): Shape (batch_size, dim, seq_len)\n    \n    Returns:\n        weights (torch.Tensor): Shape (batch_size, seq_len, seq_len)\n    \"\"\"\n    dim = queries.shape[2]\n    queries = queries / (dim ** (1/4))\n    keys    = keys / (dim ** (1/4))\n    return normalized_dot_product(queries, keys)\n```\n\n## Multi-head self-attention\n\nThe model should be able to find different patterns in the input sequence, which is why we use multiple heads.\n\nNow, we'll create the actual self-attention function, which includes multiple heads.\nFor implementation simplicity and efficiency we will do a version called *narrow* self-attention, where the input vector is split into parts and each attention head is applied to just one part of the vector.\nImagine that we have $\\d = 64$ and four heads, then each head would operate on a vector with dimension $64 / 4 = 16$.\n\n## Constructing the module\nBelow is an implementation of our self-attention module. We try to show you how a typical custom model looks like. Part of that is to do full vectorization (i.e. no loops). The result is a lot of manipulation of shapes and dimension order of intermediate tensors. It is not very readable and it is quite difficult to wrap your head around it but since you are likely to use and modify other peoples code (in the project or some later time), it is good that you get exposed to it now.\n\n\n```python\nclass SelfAttention(torch_nn.Module):\n    def __init__(self, dim, heads):\n        \"\"\"(Narrow) Self-attention module\n\n        Args:\n            dim (int): The full embedding dimension of the input vectors\n            heads (int): The number of heads in the multi-head attention.\n        \"\"\"\n        super().__init__()\n        if not dim % heads == 0:\n            raise ValueError(\n                \"The embedding dim. must be divisible by the number of heads for the vectorization to work.\"\n            )\n        self.dim = dim\n        self.heads = heads\n        part_dim = dim // heads\n        # Linear maps for q, k and v\n        self.Wq = torch_nn.Linear(part_dim, part_dim, bias=False)\n        self.Wk = torch_nn.Linear(part_dim, part_dim, bias=False)\n        self.Wv = torch_nn.Linear(part_dim, part_dim, bias=False)\n        # Linear mapping to return to the original \n        self.WO = torch_nn.Linear(heads * part_dim, dim)\n\n    def forward(self, x):\n        \"\"\"Multi-headed self attention\n\n        Each head operates on a part of the embedding, i.e. we have q, k and v with shape\n        (batch_size, seq_length, heads, dim / heads)\n        \n        Args:\n            x (Tensor): Input with shape (batch_size, seq_length, dim)\n        \"\"\"\n        batch_size, seq_length, dim = x.shape\n        part_dim = dim // self.heads\n        x = x.reshape(batch_size, seq_length, self.heads, part_dim)\n        \n        keys = self.Wk(x)\n        queries = self.Wq(x)\n        values = self.Wv(x)\n        \n        keys = self._restructure_tensor(keys, batch_size, seq_length, part_dim)\n        queries = self._restructure_tensor(queries, batch_size, seq_length, part_dim)\n        values = self._restructure_tensor(values, batch_size, seq_length, part_dim)\n\n        weights = query_key_weights(queries, keys)\n\n        y_tilde = weighted_avg(values, weights)\n        y_tilde = (\n            y_tilde.transpose(2, 1)\n            .reshape(batch_size, self.heads, seq_length, part_dim)\n            .transpose(1, 2)\n            .contiguous()\n            .reshape(batch_size, seq_length, part_dim * self.heads)\n        )\n        return self.WO(y_tilde)\n\n    def _restructure_tensor(self, x, batch_size, seq_length, part_dim):\n        \"\"\" Reshaping q, k and v tensors\n\n        For efficient vectorisation we stack the different heads in the batch_size dimension.\n        Think of it as temporarily expanding the batch_size with every head.\n        \"\"\"\n        return (\n            x.transpose(1, 2)\n            .contiguous()\n            .reshape(batch_size * self.heads, seq_length, part_dim)\n            .transpose(2, 1)\n        )\n```\n\n# The transformer block\n\nThe majority of the implementation complexity is actually in the `SelfAttention` module. The transformer block is rather straight forward, it is just like the one described in the video lectures:\n\n\n```python\nclass TransformerBlock(torch_nn.Module):\n    \"\"\"Transformer block\"\"\"\n\n    def __init__(self, dim, heads):\n        super().__init__()\n\n        self.self_attention = SelfAttention(dim, heads)\n\n        self.normalization_1 = torch_nn.LayerNorm(dim)\n        self.normalization_2 = torch_nn.LayerNorm(dim)\n        \n        # The size of the hidden layer is a hyper-parameter,\n        # but the consensus is that it should at least be larger than the input/output size\n        self.feed_forward = torch_nn.Sequential(\n            torch_nn.Linear(dim, 4 * dim),\n            torch_nn.ReLU(),\n            torch_nn.Linear(4 * dim, dim),\n        )\n\n    def forward(self, x):\n        y = self.self_attention(x)\n        # Note how the residual (skip) connections are implemented as simple addition.\n        x = self.normalization_1(x + y)\n        fed_forward = self.feed_forward(x)\n        return self.normalization_2(fed_forward + x)\n```\n\nNow, we are done with the general module. To create an actual transformer yet we must choose an actual problem so that we can specify input, embedding and output.\nLet's do that.\n\n# 3. IMDB Classification\n\nIn this task we will consider classification of IMDB reviews. For pedagogical reasons, the classification will be based upon the functions you have built above. The idea is to clarify the connection between these functions and an application with real data. However, note that the standard approach to maximize performance is to use a well studied transformer architecture (e.g. BERT), download pre-trained weights and then fine-tune the parameters for the considered problem. Additional resources on how one would implement a transformer in practice are appended at the end of this notebook. \n\nThe purpose here is to build on the computer labs and to give you some inspiration for how to solve a general problem with `pytorch`. It will show you how to install additional python libraries (useful for the project) and some advice on how to construct a training/validation loop. We do not expect you to modify the code, **you don't even have to run it** if you feel that your cloud credits are starting to run low. However, you should read and understand the code; it will help you answer the questions at the end.\n\n## The data\n\nThe IMDB data is provided by an external python module called `torchtext`.\nYou can add it to the dml conda environment with:\n```\nconda install -c pytorch torchtext\n```\nMake sure that you have activated the dml environment before your run it.\n\nProcessing text data can be tedious and error prone. For prototyping it is nice to use some third-party library which has done most of the work for you. You do not really need to focus on the data processing here, since it will be different for every task.\n\n\n\n```python\nfrom torchtext import data, datasets\n\nTEXT = data.Field(lower=True, include_lengths=True, batch_first=True)\nLABEL = data.Field(sequential=False)\n\ndef get_loaders(vocabulary_len, batch_size, device, split_ratio=0.8):\n    \"\"\"Load the IMDB data\"\"\"\n    tdata, _ = datasets.IMDB.splits(TEXT, LABEL)\n    train, test = tdata.split(split_ratio)\n\n    TEXT.build_vocab(\n        # We have to leave space for two special tokens.\n        train, max_size=vocabulary_len - 2\n    )\n    LABEL.build_vocab(train)\n\n    train_loader, test_loader = data.BucketIterator.splits(\n        (train, test), batch_size=batch_size, device=device\n    )\n    return train_loader, test_loader\n\ndef view_example_text(index):\n    \"\"\"Helper function to look at a sample.\n    \n    The dataset is quite slow to load. \n    \"\"\"\n    train, test = datasets.IMDB.splits(TEXT, LABEL)\n    sample_text = train[index].text\n    sample_label = train[index].label\n    # Simply print the list of words, separated by space.\n    print(\" \".join(sample_text))\n    print(\"\\nLabel: \", sample_label)\n\nview_example_text(118)\n```\n\n## The transformer\nWe will create a simple transformer that takes as input text in the form of a python list of words and which outputs a  probability vector over the two classes \"pos\" and \"neg\" (technically, the output will be the input to a log-softmax).\nWe make the simplest (and less memory efficient) version of position embedding as described in the video lectures.\n\n\n```python\nclass Transformer(torch_nn.Module):\n    def __init__(self, dim, heads, depth, seq_length, num_tokens, num_classes, device):\n        super().__init__()\n        self.device = device\n\n        self.num_tokens = num_tokens\n        \n        self.pos_emb = torch_nn.Embedding(seq_length, dim)\n        self.token_emb = torch_nn.Embedding(num_tokens, dim)\n\n        transformer_blocks = []\n        for _ in range(depth):\n            transformer_blocks.append(TransformerBlock(dim=dim, heads=heads))\n\n        # The Sequential wrapper is convenient when you want to repeat similar blocks.\n        # A down-side is that it is harder access intermediate values for debugging.\n        self.transformer_blocks = torch_nn.Sequential(*transformer_blocks)\n\n        # The last part is problem specific. Here we want to map our transformer embeddings\n        # to a probability distribution.\n        # We will use a linear layer to produce log logits (the input to a  log-softmax function).\n        self.output_map = torch_nn.Linear(dim, num_classes)\n\n    def forward(self, x):\n        \"\"\"Transformer forward method\n\n        Args:\n            x Tensor(batch_size, seq_length): Word indices representing sequence of words.\n        Returns:\n            Tensor(batch_size, num_classes): Log logits\n        \"\"\"\n        tokens = self.token_emb(x)\n        batch_size, seq_length, dim = tokens.size()\n\n        # Note that we create a completely new tensor which must be moved to the proper device.\n        # This is why we must store the device in self.device.\n        pos = torch.arange(seq_length, device=self.device)\n        pos = self.pos_emb(pos)[None, :, :].expand(batch_size, seq_length, dim)\n\n        x = tokens + pos\n        x = self.transformer_blocks(x)\n\n        x = self.output_map(x.mean(dim=1))\n        return F.log_softmax(x, dim=1)\n```\n\nNow, for the train./val loop. This can be written in many ways but based on common misstakes in HA1, hints might be in order:\n\n- Separate your code into smaller pieces, i.e. functions. It makes it easier to find bugs and easier to reuse code.\n- Use separate functions to calculate metrics. If you want to calculate, say accuracy, during both training and validation, don't copy the code. Write one function and make sure that it works, then reuse it.\n- Adding measurements to a running metrics can be tricky. Below is a solution that is a bit overkill but that is okay, since it is hard to use it incorrectly.\n\nNote 1: the code below can be modified so that you can play around with it.\n\nNote 2: timing this on Azure, a single epoch took ~5 min. Feel free to reduce the number of epochs or just study the code.\n\n\n```python\nfrom time import time\n\ndef train_epoch(model, train_loader, optimizer, scheduler, max_seq_len):\n    \"\"\"Train epoch\"\"\"\n    train_loss = AccumulatingMetric()\n    train_acc = AccumulatingMetric()\n    model.train()\n    for batch in train_loader:\n        optimizer.zero_grad()\n        input_, label = batch.text[0], batch.label - 1\n\n        input_ = _truncate_input(input_, max_seq_len)\n        pred = model(input_)\n        loss = F.nll_loss(pred, label)\n        loss.backward()\n        train_loss.add(loss.item())\n\n        train_acc.add(accuracy(pred, label))\n\n        # Gradient clipping is a way to ensure\n        # torch_nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n        optimizer.step()\n        scheduler.step()\n    return train_loss.avg(), train_acc.avg()\n\n\ndef validate_epoch(model, val_loader, max_seq_len):\n    val_loss = AccumulatingMetric()\n    val_acc = AccumulatingMetric()\n    model.eval()\n    with torch.no_grad():\n        for batch in val_loader:\n            input_, label = batch.text[0], batch.label - 1\n\n            input_ = _truncate_input(input_, max_seq_len)\n            pred = model(input_)\n            val_loss.add(F.nll_loss(pred, label).item())\n\n            val_acc.add(accuracy(pred, label))\n\n    return val_loss.avg(), val_acc.avg()  # TODO: loss\n\n\ndef accuracy(pred, label):\n    hard_pred = pred.argmax(1)\n    return (hard_pred == label).float().mean().item()\n\n\ndef _truncate_input(input_, max_seq_len):\n    if input_.size(1) > max_seq_len:\n        input_ = input_[:, :max_seq_len]\n    return input_\n\n\nclass AccumulatingMetric:\n    \"\"\"Accumulate samples of a metric and automatically keep track of the number of samples.\"\"\"\n    def __init__(self):\n        self.metric = 0.0\n        self.counter = 0\n\n    def add(self, value):\n        self.metric += value\n        self.counter += 1\n        \n    def avg(self):\n        return self.metric / self.counter\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nnum_tokens = 50_000\nmax_length = 512\nembedding_size = 128\nnum_heads = 8\nnum_classes = 2\ndepth = 6\n\nmodel = Transformer(\n    dim=embedding_size,\n    heads=num_heads,\n    depth=depth,\n    seq_length=max_length,\n    num_tokens=num_tokens,\n    num_classes=num_classes,\n    device=device)\n\nmodel.to(device)\n\nlr = 1e-4\nlr_warmup = 1e4\nnum_epochs = 5\nbatch_size = 4\n\ntrain_loader, test_loader = get_loaders(num_tokens, batch_size, device)\n\noptimizer = torch.optim.Adam(lr=lr, params=model.parameters())\n# A scheduler is a principled way of controlling (often decreasing) the learning rate as time progresses.\n# Read more: https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate\nscheduler = torch.optim.lr_scheduler.LambdaLR(\n    optimizer, lambda i: min(i / (lr_warmup / batch_size), 1.0)\n)\n\nprint(\"Starting training\")\nfor epoch in range(1, num_epochs + 1):\n    start = time()\n    train_loss, train_acc = train_epoch(model, train_loader, optimizer, scheduler, max_length)\n    val_loss, val_acc = validate_epoch(model, test_loader, max_length)\n    end = time()\n    print(\n        \"Epoch: {}/{}: time: {:.1f}, train loss: {:.3f}, train acc: {:.3f}, val. loss {:.3f}, val. acc: {:.3f}\".format(\n            epoch, num_epochs, end - start, train_loss, train_acc, val_loss, val_acc\n        )\n    )\nprint(\"You have now trained a transformer!\")\n\n# I'm adding a ''# YOUR CODE HERE' tag so that the code above is not hidden when the assignment is generated.\n# YOUR CODE HERE\n```\n\n## Theoretical questions\n\nNow that you have gotten a practical feel for the transformer it is time to reflect on some of its important properties:\n\n## Multi-Head Self Attention\n\n**[3 points]** The above implementation of the transformer is using multi-head self-attention. Briefly describe which parts that are different in different heads in a multi-head self-attention layer.\n\n**Your answer:** (fill in here)\n\n**[3 points]** What are the benefits of using multi-head self-attention compared to a single-head self-attention block? \n\n**Your answer:** (fill in here)\n\n## Transformers and RNN\n\n**[7 points]** Which are the main differences between a transformer and an RNN?\nIn particular, how do the differences make it easier to train a transformer, compared to an RNN?\n\n**Your answer:** (fill in here)\n\n**[7 points]** Self-attention maps sets to sets. It is an important part of what makes transformers so useful and general. Explain what this property means?\n\nIronically, this property is actually a bit of an issue when we want to process text (or any NLP problem).\nWhy, and how do we try to fix it?\n\n**Your answer:** (fill in here)\n\n# Wrapping up\n\nThe transformer architecture has become incredibly popular and has produced truly amazing results.\nYou should now have a good insight for how they can be implemented in `pytorch`. If you are interested, here are some more resources:\n\n- https://pytorch.org/docs/stable/generated/torch.nn.Transformer.html\n- https://github.com/huggingface/transformers\n- https://towardsdatascience.com/bert-text-classification-using-pytorch-723dfb8b6b5b\n", "meta": {"hexsha": "3402d43b1e8069428b56c4999ab0a3f4f2ac6eb2", "size": 56976, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "home-assignments/HA2/HA2-Part2.ipynb", "max_stars_repo_name": "JulianoLagana/deep-machine-learning", "max_stars_repo_head_hexsha": "0135a84067be357c8bc3d3a4298b60dcaf7d53d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 49, "max_stars_repo_stars_event_min_datetime": "2017-09-07T19:56:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T11:19:14.000Z", "max_issues_repo_path": "home-assignments/HA2/HA2-Part2.ipynb", "max_issues_repo_name": "JulianoLagana/deep-machine-learning", "max_issues_repo_head_hexsha": "0135a84067be357c8bc3d3a4298b60dcaf7d53d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2018-09-05T08:10:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-06T11:47:54.000Z", "max_forks_repo_path": "home-assignments/HA2/HA2-Part2.ipynb", "max_forks_repo_name": "JulianoLagana/deep-machine-learning", "max_forks_repo_head_hexsha": "0135a84067be357c8bc3d3a4298b60dcaf7d53d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 103, "max_forks_repo_forks_event_min_datetime": "2017-09-19T13:37:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T14:09:59.000Z", "avg_line_length": 34.4057971014, "max_line_length": 602, "alphanum_fraction": 0.5814729009, "converted": true, "num_tokens": 7489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25683198001082097, "lm_q2_score": 0.12592275499444552, "lm_q1q2_score": 0.03234099049364094}}
{"text": " # Prescreen results\n\n\n```python\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport os\nimport warnings\nimport numpy as np\n\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\nimport nelpy as nel\nimport nelpy.plotting as npl\n\nnpl.setup()\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\nwarnings.filterwarnings(\"ignore\")\n\n\n```\n\n    /home/ckemere/Code/nelpy/nelpy/plotting/decoding.py:9: MatplotlibDeprecationWarning: \n    The mpl_toolkits.axes_grid module was deprecated in Matplotlib 2.1 and will be removed two minor releases later. Use mpl_toolkits.axes_grid1 and mpl_toolkits.axisartist, which provide the same functionality instead.\n\n\n\n```python\ndatadirs = ['/mnt/d/Data/Etienne/','/home/ckemere/Data2/DibaBuzsakiData/',\n    'D:/Dropbox/neoReader/']\n\n## conda install pandas=0.19.2\n\nfileroot = next( (dir for dir in datadirs if os.path.isdir(dir)), None)\n\nif fileroot is None:\n    raise FileNotFoundError('datadir not found')\n\nload_from_nel = True\n\n# load from nel file:\nif load_from_nel:  \n    jar = nel.load_pkl(fileroot + 'gor01vvp01pin01_processed_speed.nel')\n    aux_data = jar.aux_data\n    jar = nel.load_pkl(fileroot + 'gor01vvp01pin01_tables_speed.nel')\n    df = jar.df\n    df2 = jar.df2\n    jar = nel.load_pkl(fileroot + 'score_all_sessions_5000_35000.nel') # needs to be modified to include pin01 bayes\n    score_results = jar.results\n    del jar\n    \njar = nel.load_pkl('sessions-segments.nel')\nsessions, segments = jar.sessions, jar.segments\n\n\n```\n\n\n```python\ndef plot_all_PBEs(bst, spiketrainarray, tuningcurve, tc_placecells, idx=None, title_str=None, size=None):\n    if idx is not None:\n        bst = bst[idx]\n    st = spiketrainarray\n    tc = tuningcurve\n    tc_placecells = tc_placecells\n\n    no = tc_placecells.get_peak_firing_order_ids()\n    st.reorder_units_by_ids(no, inplace=True)\n\n    st_cut = st[bst.support]\n    st_cut._support = bst.support # hacky fix so that we can plot events out of order\n    st_cut = nel.utils.collapse_time(st_cut)\n\n    # decode neural activity\n    posterior, bdries, mode_pth, mean_pth = nel.decoding.decode1D(bst=bst, ratemap=tc, xmax=310)\n\n    if size == 'big':\n        figwidth = 0.8 * bst.n_bins\n    else:\n        figwidth = 0.08 * bst.n_bins\n        \n    with npl.FigureManager(show=True, figsize=(figwidth,5)) as (fig, ax):\n        npl.utils.skip_if_no_output(fig)\n\n        pixel_width = 0.5\n\n        npl.imagesc(x=np.arange(bst.n_bins), y=np.arange(311), data=posterior, cmap=plt.cm.Spectral_r, ax=ax)\n        npl.utils.yticks_interval(310)\n        npl.utils.no_yticks(ax)\n        # plt.imshow(posterior, cmap=plt.cm.Spectral_r, interpolation='none', aspect='auto')\n        ax.vlines(np.arange(bst.lengths.sum())-pixel_width, *ax.get_ylim(), lw=1, linestyle=':', color='0.8')\n        ax.vlines(np.cumsum(bst.lengths)-pixel_width, *ax.get_ylim(), lw=1)\n\n        ax.set_xlim(-pixel_width, bst.lengths.sum()-pixel_width)\n\n        event_centers = np.insert(np.cumsum(bst.lengths),0,0)\n        event_centers = event_centers[:-1] + bst.lengths/2 - 0.5\n\n        ax.set_xticks(event_centers);\n        if idx is not None:\n            ax.set_xticklabels(idx);\n        else:\n            ax.set_xticklabels(np.arange(bst.n_epochs));\n\n        npl.utils.no_xticks(ax)\n\n        divider = make_axes_locatable(ax)\n        if size == 'big':\n            axRaster = divider.append_axes(\"top\", size=1.5, pad=0)\n        else:\n            axRaster = divider.append_axes(\"top\", size=1, pad=0)\n\n        npl.rasterplot(st_cut, vertstack=True, ax=axRaster, lh=2)\n        axRaster.set_xlim(st_cut.support.time.squeeze())\n        bin_edges = np.linspace(st_cut.support.time[0,0],st_cut.support.time[0,1], bst.n_bins+1)\n    #     axRaster.vlines(bin_edges, *ax.get_ylim(), lw=1, linestyle=':', color='0.2')\n        axRaster.vlines(bin_edges[np.cumsum(bst.lengths)], *ax.get_ylim(), lw=1, color='0.2')\n        npl.utils.no_xticks(axRaster)\n        npl.utils.no_xticklabels(axRaster)\n        npl.utils.no_yticklabels(axRaster)\n        npl.utils.no_yticks(axRaster)\n        ax.set_ylabel('position [cm]')\n        ax.set_xlabel('time bins (20 ms)')\n        if title_str:\n            fig.suptitle(title_str)\n        npl.utils.clear_left_right(axRaster)\n        npl.utils.clear_top_bottom(axRaster)\n\n\n```\n\n\n```python\nmin_n_placecells = 20\nmin_n_PBEs = 30\ndf2_subset = df2[(df2.n_PBEs >= min_n_PBEs) & (df2.n_placecells >= min_n_placecells)]\n\n```\n\n\n```python\nz_scores = np.array(df2_subset['prescreen_z'].values.tolist())\nz_order = np.argsort(z_scores)[::-1] # ascending order\n\nPlotAllSessions = False\nif PlotAllSessions:\n    for session, segment in zip(np.array(sessions)[z_order], np.array(segments)[z_order]):\n        bst = aux_data[session][segment]['PBEs']\n        st = aux_data[session][segment]['st_placecells']\n        tc = aux_data[session][segment]['tc']\n        tc_placecells = aux_data[session][segment]['tc_placecells']\n        evt_order = np.argsort(score_results[session][segment]['scores_bayes_percentile']).tolist()[::-1]\n        title_str = str(session) + ': ' + str(segment) + '; events ordered by decreasing Bayesian score percentile'\n        plot_all_PBEs(bst, st, tc, tc_placecells, idx=evt_order, title_str=title_str)\n\n\n```\n\n # Look at an example session\n\n\n```python\nsession = '16-40-19'; segment = 'short'\n# session = '1-22-43'; segment = 'short'\nbst = aux_data[session][segment]['PBEs']\nst = aux_data[session][segment]['st_placecells']\ntc = aux_data[session][segment]['tc']\ntc_placecells = aux_data[session][segment]['tc_placecells']\nbst.n_epochs\n\nscores_bayes_percentile = score_results[session][segment]['scores_bayes_percentile']\nscores_hmm_percentile = score_results[session][segment]['scores_hmm_percentile']\n```\n\n\n```python\nimport warnings\nwarnings.filterwarnings('once')\n```\n\n### _Etienne has gone through and scored all the sequences in this session_\n\n\n```python\n#plot_all_PBEs(bst, st, tc, tc_placecells) # Plot all the sequences in the session\n```\n\n\n```python\ngoodseqs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,\n              21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,\n              40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58,\n              59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77,\n              78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96,\n              97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112,\n              113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,\n              128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,\n              143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157,\n              158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, \n              173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, \n              188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202,\n              203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217,\n              218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232,\n              233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, \n              248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, \n              263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276]\n\nbadseqs = [0,2,3,14,34,47,55,82,88,108,126,135,137,153,180,181,184,185,207,229,237,251,\n          256,259,261,263,272,72,86,91,169,172,204,208,220,241,240,12,81,83,196]\n\nuncertainseqs = [28,27,44,51,61,63,80,92,93,98,66,136,156,158,170,216,233,246,230,56,46,\n                 45,37,48,79,99,110,114,116,120,125,130,138,161,163,164,183,197]\n\nstatseqs = [1,5,7,9,10,13,16,21,22,31,33,39,57,58,59,76,77,97,104,118,123,140,142,148,151,\n           166,167,168,179,194,200,201,212,223,224,225,245,242,243,239,273,274,275,276,73,\n           84,100,124,254,139,189,248,268,232,252,244,236,64,67,68,65,43,42,4,29,85,87,102,\n            117,119,134,186,209]\n\ngoodseqs = list(set(goodseqs) - set(statseqs) - set(badseqs) - set(uncertainseqs))\nuncertainseqs = list(set(uncertainseqs) - set(badseqs))\nstatseqs = list(set(statseqs) - set(badseqs) - set(uncertainseqs))\n```\n\n### Let's look at an example from the good sequences\nThe plot_all_PBEs function plots the spike rasters ordered by place cell locations above the Bayesian decoded linear position for a list of sequences. Lets pick a set of sequences that look \"good\" (replay is of a nice linear path along the track), but have scores in the 98-99 percentile range rather than the max (100). Presumably these sequences will be marginally more likely to be affected by changes.\n\n\n```python\nniceseq = [54, 74, 90, 197, 203, 213, 227]\nprint(scores_bayes_percentile[niceseq])\n```\n\n    [100.    99.34  99.98  99.16  99.22  98.86  98.34]\n\n\n\n```python\nplot_all_PBEs(bst, st, tc, tc_placecells, idx=niceseq, size='big')\n\n```\n\n#### How do we simulate the effect of SWR firing patterns being different in different conditions?\n\nOne simple test is to take the binned spikes and, for example, triple the number of spikes. This sharpens the posteriors as shown below.\n\n\n```python\nbst2 = bst * 3 # simulate a doubling of firing rates during ripples\nplot_all_PBEs(bst2, st, tc, tc_placecells, idx=niceseq, size='big')\n\n```\n\nHow we choose the tuning curves for replay analysis is already a bit suspect. Usually, for convenience, we just say that the firing rate is scaled by a factor that is equivalent to the ratio of the bin sizes from running to ripple periods. But when we consider in detail the question of whether changes in the pattern of spiking during ripples might lead to differences in replay detection, we should consider this more carefully. For some position $x$ and the position-specific firing rate map $\\boldsymbol{\\lambda}_x$, if we observe a spiking vector $\\mathbf{k}$, the posterior likelihood is given by:\n\n$$ LL(x) = \\mathbf{k}^T \\log(\\boldsymbol{\\lambda}_x) - \\mathbf{1}^T \\mathbf{\\lambda}_x + C $$\n\nwhere $C$ is a constant that is independent of $x$. If we scale the rate by a factor $\\alpha$, the new likelihood is:\n\n$$\\begin{align}\nLL(x) &= \\mathbf{k}^T \\log(\\alpha \\boldsymbol{\\lambda}_x) - \\alpha (\\mathbf{1}^T \\mathbf{\\lambda}_x) + C \\\\\n      &= \\mathbf{k}^T \\log(\\boldsymbol{\\lambda}_x) - \\alpha (\\mathbf{1}^T \\mathbf{\\lambda}_x) + C'\n\\end{align}$$\n\nwhere $C'$ has absorbed the position-independent term $\\mathbf{k}^T \\log(\\alpha)$. What's interesting about this is that the effect of tuning curve scaling is on the \"prior\" portion of the likelihood, the part that is independent of firing rates. This relates to the bigger picture idea that experimental conditions might bias results in unexpected ways - here, the bias is that place fields will not uniformly tile the space, so the prior may have some effect on replay score.\n\nSo below, let's plot what happens if we take the tuning curves and scale all their firing rates by a factor of three. You'll see it looks very similar.\n\n\n```python\ntc2 = tc * 0.333 # simulate a different firing rate map\nplot_all_PBEs(bst, st, tc2, tc_placecells, idx=niceseq, size='big')\n\nratemap = tc.reorder_units_by_ids(bst.unit_ids)\nprior = -ratemap.ratemap.sum(axis=0)*bst.ds\nplt.plot(ratemap.bin_centers, prior)\nplt.gca().set_title('Map of Prior Probability of Track');\n```\n\n#### What is the effect on replay scores?\n\nWe'll use the Davidson-style replay detection to compare scores between different scenarios.\n\n\n```python\nprint('Running replay analsysis on {} SWR sequences'.format(bst.n_intervals))\n```\n\n    Running replay analsysis on 277 SWR sequences\n\n\n\n```python\nfrom nelpy import analysis\n\nscores1, shuffled_scores1, percentiles1 = \\\n    nel.analysis.replay.score_Davidson_final_bst_fast(bst=bst,\n        tuningcurve=tc,w=3,n_shuffles=1000, n_samples=10000)\n```\n\n    /home/ckemere/anaconda3/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: numpy.ufunc size changed, may indicate binary incompatibility. Expected 192 from C header, got 216 from PyObject\n\n\n\n```python\nscores2, shuffled_scores2, percentiles2 = \\\n    nel.analysis.replay.score_Davidson_final_bst_fast(bst=bst,\n        tuningcurve=tc2,w=3,n_shuffles=1000, n_samples=10000)\n```\n\n\n```python\nscores3, shuffled_scores3, percentiles3 = \\\n    nel.analysis.replay.score_Davidson_final_bst_fast(bst=bst2,\n        tuningcurve=tc,w=3,n_shuffles=1000, n_samples=10000)\n\n```\n\n\n```python\nimport seaborn as sns\n\n# Plot score distributions for each event\n\nif False:\n    to_plot = [(scores1, shuffled_scores1), (scores2, shuffled_scores2), (scores3, shuffled_scores3)]\n\n    fig, axs = plt.subplots(nrows=len(to_plot), ncols=len(scores1), figsize=(4 * len(scores1), 8))\n    plt.subplots_adjust(hspace=0.5)\n\n    npl.setup(style='whitegrid')\n    for idx, (sc, sh) in enumerate(to_plot):\n        for i in range(len(scores1)):\n            ax = axs[idx,i]\n            sns.distplot(sh[i,:],ax=ax)\n            ax.stem([sc[i]],[1],markerfmt='C1o')\n            if (idx > 0):\n                ax.set_xlim(axs[0,i].get_xlim())\n    axs[0,1].set_title('Original');\n    axs[1,1].set_title('0.1 x TC');\n    axs[2,1].set_title('2 x Spikes');\n\n    print(np.mean(percentiles1-percentiles2), np.std(percentiles1-percentiles2))\n    print(np.mean(percentiles1-percentiles3), np.std(percentiles1-percentiles3))\n```\n\n\n```python\nprint('Mean percentile score for events:\\n')\nprint('   Original     TC/3        FR*3')\nprint(np.vstack([percentiles1,percentiles2,percentiles3]).mean(axis=1))\n```\n\n    Mean percentile score for events:\n    \n       Original     TC/3        FR*3\n    [97.74963899 98.28501805 97.41119134]\n\n\n\n```python\nsns.boxplot(data=np.vstack([percentiles1,percentiles2,percentiles3]).T)\n```\n\n\n```python\nfrom scipy.stats import wilcoxon\n\nprint('Wilcoxon Tests')\n\nstatistic, pval = wilcoxon(percentiles1, percentiles2)\nprint('Original vs TC/3: ', statistic, pval)\n\nstatistic, pval = wilcoxon(percentiles1, percentiles3)\nprint('Original vs FR*3: ', statistic, pval)\n```\n\n    Wilcoxon Tests\n    Original vs TC/3:  4324.0 0.011929552972645814\n    Original vs FR*3:  4807.5 0.04839551607686778\n\n\n\n```python\nprint('Fraction of events significant at 99%:\\n')\nprint('  Original     TC/3     FR*3')\nprint((np.vstack([percentiles1,percentiles2,percentiles3]) > 99).mean(axis=1))\n```\n\n    Fraction of events significant at 99%:\n    \n      Original     TC/3     FR*3\n    [0.74729242 0.77256318 0.68592058]\n\n\n## Conclusion\n\nWhen we look at all the sequences, it looks like both the tuning curve scaling and the firing rate change have small but potentially significant effects on the replay scores - lowering the tuning curve firing rates by a factor of 1/3rd slightly increases the mean score percentile and increasing the firing rates by a factor of 3 during ripples slightly decreases the average. This points to the broader picture that changes in firing patterns during ripples which are not accompanied by changes in the tuning curves might lead to changes in the statistics of fraction of \"significant\" replay or other aggregations of replay scores. We made fairly large changes to the model or data, but these have fairly small effects on \"the number of significant events\". \n", "meta": {"hexsha": "4cfd15bf5a07b6fb657745dd9e897f4b5925b1ab", "size": 205615, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Replay Scores and Tuning Curve Scaling.ipynb", "max_stars_repo_name": "ckemere/InterestingNotebooks", "max_stars_repo_head_hexsha": "e1318d46e5d7949d86ae64cce757cf5faae204ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Replay Scores and Tuning Curve Scaling.ipynb", "max_issues_repo_name": "ckemere/InterestingNotebooks", "max_issues_repo_head_hexsha": "e1318d46e5d7949d86ae64cce757cf5faae204ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Replay Scores and Tuning Curve Scaling.ipynb", "max_forks_repo_name": "ckemere/InterestingNotebooks", "max_forks_repo_head_hexsha": "e1318d46e5d7949d86ae64cce757cf5faae204ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-16T16:21:42.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-16T16:21:42.000Z", "avg_line_length": 292.4822190612, "max_line_length": 55164, "alphanum_fraction": 0.9160372541, "converted": true, "num_tokens": 4786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.06465348520228964, "lm_q1q2_score": 0.03232674260114482}}
{"text": "<a href=\"https://colab.research.google.com/github/sonam-pankaj95/gender_bias/blob/main/interpretability.ipynb\" target=\"_parent\"></a>\n\n\n```python\n!pip install --upgrade pandas numpy scikit-learn tensorflow matplotlib seaborn\n\n```\n\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (1.3.5)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (1.21.5)\n    Requirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (1.0.2)\n    Requirement already satisfied: tensorflow in /usr/local/lib/python3.7/dist-packages (2.8.0)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (3.2.2)\n    Collecting matplotlib\n      Downloading matplotlib-3.5.1-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl (11.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 11.2 MB 9.5 MB/s \n    \u001b[?25hRequirement already satisfied: seaborn in /usr/local/lib/python3.7/dist-packages (0.11.2)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas) (2.8.2)\n    Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas) (2018.9)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas) (1.15.0)\n    Requirement already satisfied: scipy>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn) (1.4.1)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn) (1.1.0)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn) (3.1.0)\n    Requirement already satisfied: h5py>=2.9.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow) (3.1.0)\n    Requirement already satisfied: keras<2.9,>=2.8.0rc0 in /usr/local/lib/python3.7/dist-packages (from tensorflow) (2.8.0)\n    Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow) (1.1.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from tensorflow) (57.4.0)\n    Requirement already satisfied: google-pasta>=0.1.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow) (0.2.0)\n    Requirement already satisfied: flatbuffers>=1.12 in /usr/local/lib/python3.7/dist-packages (from tensorflow) (2.0)\n    Requirement already satisfied: typing-extensions>=3.6.6 in /usr/local/lib/python3.7/dist-packages (from tensorflow) (3.10.0.2)\n    Requirement already satisfied: astunparse>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow) (1.6.3)\n    Collecting tf-estimator-nightly==2.8.0.dev2021122109\n      Downloading tf_estimator_nightly-2.8.0.dev2021122109-py2.py3-none-any.whl (462 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 462 kB 61.8 MB/s \n    \u001b[?25hRequirement already satisfied: gast>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow) (0.5.3)\n    Requirement already satisfied: wrapt>=1.11.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow) (1.14.0)\n    Requirement already satisfied: protobuf>=3.9.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow) (3.17.3)\n    Requirement already satisfied: absl-py>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow) (1.0.0)\n    Requirement already satisfied: grpcio<2.0,>=1.24.3 in /usr/local/lib/python3.7/dist-packages (from tensorflow) (1.44.0)\n    Requirement already satisfied: tensorflow-io-gcs-filesystem>=0.23.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow) (0.24.0)\n    Requirement already satisfied: libclang>=9.0.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow) (13.0.0)\n    Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow) (3.3.0)\n    Requirement already satisfied: tensorboard<2.9,>=2.8 in /usr/local/lib/python3.7/dist-packages (from tensorflow) (2.8.0)\n    Requirement already satisfied: keras-preprocessing>=1.1.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow) (1.1.2)\n    Requirement already satisfied: wheel<1.0,>=0.23.0 in /usr/local/lib/python3.7/dist-packages (from astunparse>=1.6.0->tensorflow) (0.37.1)\n    Requirement already satisfied: cached-property in /usr/local/lib/python3.7/dist-packages (from h5py>=2.9.0->tensorflow) (1.5.2)\n    Requirement already satisfied: requests<3,>=2.21.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard<2.9,>=2.8->tensorflow) (2.23.0)\n    Requirement already satisfied: google-auth<3,>=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard<2.9,>=2.8->tensorflow) (1.35.0)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard<2.9,>=2.8->tensorflow) (1.8.1)\n    Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard<2.9,>=2.8->tensorflow) (0.6.1)\n    Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard<2.9,>=2.8->tensorflow) (1.0.1)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard<2.9,>=2.8->tensorflow) (3.3.6)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorboard<2.9,>=2.8->tensorflow) (0.4.6)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard<2.9,>=2.8->tensorflow) (4.8)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard<2.9,>=2.8->tensorflow) (4.2.4)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard<2.9,>=2.8->tensorflow) (0.2.8)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.9,>=2.8->tensorflow) (1.3.1)\n    Requirement already satisfied: importlib-metadata>=4.4 in /usr/local/lib/python3.7/dist-packages (from markdown>=2.6.8->tensorboard<2.9,>=2.8->tensorflow) (4.11.3)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=4.4->markdown>=2.6.8->tensorboard<2.9,>=2.8->tensorflow) (3.7.0)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<3,>=1.6.3->tensorboard<2.9,>=2.8->tensorflow) (0.4.8)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard<2.9,>=2.8->tensorflow) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard<2.9,>=2.8->tensorflow) (2021.10.8)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard<2.9,>=2.8->tensorflow) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard<2.9,>=2.8->tensorflow) (2.10)\n    Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.9,>=2.8->tensorflow) (3.2.0)\n    Requirement already satisfied: pyparsing>=2.2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib) (3.0.7)\n    Collecting fonttools>=4.22.0\n      Downloading fonttools-4.31.2-py3-none-any.whl (899 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 899 kB 42.9 MB/s \n    \u001b[?25hRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib) (1.4.0)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib) (0.11.0)\n    Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib) (21.3)\n    Requirement already satisfied: pillow>=6.2.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib) (7.1.2)\n    Installing collected packages: fonttools, tf-estimator-nightly, matplotlib\n      Attempting uninstall: matplotlib\n        Found existing installation: matplotlib 3.2.2\n        Uninstalling matplotlib-3.2.2:\n          Successfully uninstalled matplotlib-3.2.2\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Successfully installed fonttools-4.31.2 matplotlib-3.5.1 tf-estimator-nightly-2.8.0.dev2021122109\n\n\n\n\n\n```python\n!pip install --upgrade machine-learning-datasets\n!pip install --upgrade catboost alibi shap witwidget\n```\n\n    Collecting machine-learning-datasets\n      Downloading machine_learning_datasets-0.1.16.4-py3-none-any.whl (25 kB)\n    Collecting opencv-python<5.0.0,>=4.5.1\n      Downloading opencv_python-4.5.5.64-cp36-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (60.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 60.5 MB 56 kB/s \n    \u001b[?25hRequirement already satisfied: matplotlib<4.0.0,>=3.2.2 in /usr/local/lib/python3.7/dist-packages (from machine-learning-datasets) (3.5.1)\n    Requirement already satisfied: scipy<2.0.0,>=1.4.1 in /usr/local/lib/python3.7/dist-packages (from machine-learning-datasets) (1.4.1)\n    Requirement already satisfied: mlxtend<0.15.0,>=0.14.0 in /usr/local/lib/python3.7/dist-packages (from machine-learning-datasets) (0.14.0)\n    Requirement already satisfied: tqdm<5.0.0,>=4.41.1 in /usr/local/lib/python3.7/dist-packages (from machine-learning-datasets) (4.63.0)\n    Requirement already satisfied: statsmodels<0.11.0,>=0.10.2 in /usr/local/lib/python3.7/dist-packages (from machine-learning-datasets) (0.10.2)\n    Collecting scikit-learn<0.23.0,>=0.22.2.post1\n      Downloading scikit_learn-0.22.2.post1-cp37-cp37m-manylinux1_x86_64.whl (7.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 7.1 MB 25.1 MB/s \n    \u001b[?25hCollecting aif360<0.4.0,>=0.3.0\n      Downloading aif360-0.3.0-py3-none-any.whl (165 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 165 kB 55.9 MB/s \n    \u001b[?25hCollecting pathlib2<3.0.0,>=2.3.5\n      Downloading pathlib2-2.3.7.post1-py2.py3-none-any.whl (18 kB)\n    Requirement already satisfied: numpy<2.0.0,>=1.19.5 in /usr/local/lib/python3.7/dist-packages (from machine-learning-datasets) (1.21.5)\n    Requirement already satisfied: pandas<2.0.0,>=1.1.5 in /usr/local/lib/python3.7/dist-packages (from machine-learning-datasets) (1.3.5)\n    Collecting alibi<0.6.0,>=0.5.5\n      Downloading alibi-0.5.8-py3-none-any.whl (312 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 312 kB 5.5 MB/s \n    \u001b[?25hCollecting pycebox<0.0.2,>=0.0.1\n      Downloading pycebox-0.0.1.tar.gz (4.5 kB)\n    Requirement already satisfied: seaborn<0.12.0,>=0.11.1 in /usr/local/lib/python3.7/dist-packages (from machine-learning-datasets) (0.11.2)\n    Requirement already satisfied: requests<3.0.0,>=2.21.0 in /usr/local/lib/python3.7/dist-packages (from alibi<0.6.0,>=0.5.5->machine-learning-datasets) (2.23.0)\n    Requirement already satisfied: dill<0.4.0,>=0.3.0 in /usr/local/lib/python3.7/dist-packages (from alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.3.4)\n    Collecting attrs<21.0.0,>=19.2.0\n      Downloading attrs-20.3.0-py2.py3-none-any.whl (49 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 49 kB 4.3 MB/s \n    \u001b[?25hRequirement already satisfied: scikit-image!=0.17.1,<0.19,>=0.14.2 in /usr/local/lib/python3.7/dist-packages (from alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.18.3)\n    Collecting tensorflow<2.5.0,>=2.0.0\n      Downloading tensorflow-2.4.4-cp37-cp37m-manylinux2010_x86_64.whl (394.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 394.5 MB 37 kB/s \n    \u001b[?25hRequirement already satisfied: spacy[lookups]<4.0.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from alibi<0.6.0,>=0.5.5->machine-learning-datasets) (2.2.4)\n    Requirement already satisfied: Pillow<9.0,>=5.4.1 in /usr/local/lib/python3.7/dist-packages (from alibi<0.6.0,>=0.5.5->machine-learning-datasets) (7.1.2)\n    Requirement already satisfied: typing-extensions>=3.7.2 in /usr/local/lib/python3.7/dist-packages (from alibi<0.6.0,>=0.5.5->machine-learning-datasets) (3.10.0.2)\n    Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib<4.0.0,>=3.2.2->machine-learning-datasets) (21.3)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib<4.0.0,>=3.2.2->machine-learning-datasets) (0.11.0)\n    Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib<4.0.0,>=3.2.2->machine-learning-datasets) (4.31.2)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib<4.0.0,>=3.2.2->machine-learning-datasets) (1.4.0)\n    Requirement already satisfied: python-dateutil>=2.7 in /usr/local/lib/python3.7/dist-packages (from matplotlib<4.0.0,>=3.2.2->machine-learning-datasets) (2.8.2)\n    Requirement already satisfied: pyparsing>=2.2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib<4.0.0,>=3.2.2->machine-learning-datasets) (3.0.7)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from mlxtend<0.15.0,>=0.14.0->machine-learning-datasets) (57.4.0)\n    Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas<2.0.0,>=1.1.5->machine-learning-datasets) (2018.9)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from pathlib2<3.0.0,>=2.3.5->machine-learning-datasets) (1.15.0)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests<3.0.0,>=2.21.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests<3.0.0,>=2.21.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests<3.0.0,>=2.21.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (2021.10.8)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests<3.0.0,>=2.21.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (2.10)\n    Requirement already satisfied: networkx>=2.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image!=0.17.1,<0.19,>=0.14.2->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (2.6.3)\n    Requirement already satisfied: imageio>=2.3.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image!=0.17.1,<0.19,>=0.14.2->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (2.4.1)\n    Requirement already satisfied: tifffile>=2019.7.26 in /usr/local/lib/python3.7/dist-packages (from scikit-image!=0.17.1,<0.19,>=0.14.2->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (2021.11.2)\n    Requirement already satisfied: PyWavelets>=1.1.1 in /usr/local/lib/python3.7/dist-packages (from scikit-image!=0.17.1,<0.19,>=0.14.2->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.3.0)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn<0.23.0,>=0.22.2.post1->machine-learning-datasets) (1.1.0)\n    Requirement already satisfied: murmurhash<1.1.0,>=0.28.0 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.0.6)\n    Requirement already satisfied: plac<1.2.0,>=0.9.6 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.1.3)\n    Requirement already satisfied: blis<0.5.0,>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.4.1)\n    Requirement already satisfied: catalogue<1.1.0,>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.0.0)\n    Requirement already satisfied: wasabi<1.1.0,>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.9.0)\n    Requirement already satisfied: preshed<3.1.0,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (3.0.6)\n    Requirement already satisfied: cymem<2.1.0,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (2.0.6)\n    Requirement already satisfied: thinc==7.4.0 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (7.4.0)\n    Requirement already satisfied: srsly<1.1.0,>=1.0.2 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.0.5)\n    Collecting spacy-lookups-data<0.2.0,>=0.0.5\n      Downloading spacy_lookups_data-0.1.0.tar.gz (28.0 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 28.0 MB 1.2 MB/s \n    \u001b[?25hRequirement already satisfied: importlib-metadata>=0.20 in /usr/local/lib/python3.7/dist-packages (from catalogue<1.1.0,>=0.0.7->spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (4.11.3)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=0.20->catalogue<1.1.0,>=0.0.7->spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (3.7.0)\n    Requirement already satisfied: patsy>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from statsmodels<0.11.0,>=0.10.2->machine-learning-datasets) (0.5.2)\n    Collecting absl-py~=0.10\n      Downloading absl_py-0.15.0-py3-none-any.whl (132 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 132 kB 30.9 MB/s \n    \u001b[?25hRequirement already satisfied: astunparse~=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.6.3)\n    Collecting flatbuffers~=1.12.0\n      Downloading flatbuffers-1.12-py2.py3-none-any.whl (15 kB)\n    Requirement already satisfied: wheel~=0.35 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.37.1)\n    Requirement already satisfied: tensorboard~=2.4 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (2.8.0)\n    Collecting grpcio~=1.32.0\n      Downloading grpcio-1.32.0-cp37-cp37m-manylinux2014_x86_64.whl (3.8 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.8 MB 42.5 MB/s \n    \u001b[?25hRequirement already satisfied: keras-preprocessing~=1.1.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.1.2)\n    Requirement already satisfied: opt-einsum~=3.3.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (3.3.0)\n    Requirement already satisfied: protobuf>=3.9.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (3.17.3)\n    Collecting typing-extensions>=3.7.2\n      Downloading typing_extensions-3.7.4.3-py3-none-any.whl (22 kB)\n    Collecting tensorflow-estimator<2.5.0,>=2.4.0\n      Downloading tensorflow_estimator-2.4.0-py2.py3-none-any.whl (462 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 462 kB 58.0 MB/s \n    \u001b[?25hRequirement already satisfied: termcolor~=1.1.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.1.0)\n    Requirement already satisfied: google-pasta~=0.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.2.0)\n    Collecting gast==0.3.3\n      Downloading gast-0.3.3-py2.py3-none-any.whl (9.7 kB)\n    Collecting h5py~=2.10.0\n      Downloading h5py-2.10.0-cp37-cp37m-manylinux1_x86_64.whl (2.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.9 MB 47.5 MB/s \n    \u001b[?25hCollecting numpy<2.0.0,>=1.19.5\n      Downloading numpy-1.19.5-cp37-cp37m-manylinux2010_x86_64.whl (14.8 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 14.8 MB 35.0 MB/s \n    \u001b[?25hCollecting wrapt~=1.12.1\n      Downloading wrapt-1.12.1.tar.gz (27 kB)\n    Requirement already satisfied: google-auth<3,>=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.35.0)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.4.6)\n    Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.0.1)\n    Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.6.1)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (3.3.6)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.8.1)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.2.8)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (4.2.4)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (4.8)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.3.1)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<3,>=1.6.3->tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.4.8)\n    Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (3.2.0)\n    Building wheels for collected packages: pycebox, spacy-lookups-data, wrapt\n      Building wheel for pycebox (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pycebox: filename=pycebox-0.0.1-py3-none-any.whl size=3640 sha256=c9318e54833f428e28867a3604914d847b1f757885d8f3535d62f65ff12bf43e\n      Stored in directory: /root/.cache/pip/wheels/cc/0d/0a/06236a41d8f5c3485c1057262de55329e227a0c239fd00d0cd\n      Building wheel for spacy-lookups-data (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for spacy-lookups-data: filename=spacy_lookups_data-0.1.0-py2.py3-none-any.whl size=28052158 sha256=660507c1e2d90d6d7412fbc92ff0fffc3ab29b2543126c3d4586ed31c6413590\n      Stored in directory: /root/.cache/pip/wheels/b6/09/83/36dd0224ce32dcdf5e218b36362235ca2e50cece60a966ae1b\n      Building wheel for wrapt (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for wrapt: filename=wrapt-1.12.1-cp37-cp37m-linux_x86_64.whl size=68723 sha256=36440031dce47f588be56cd040a589617624166724f3e812dc4e8e334b12780c\n      Stored in directory: /root/.cache/pip/wheels/62/76/4c/aa25851149f3f6d9785f6c869387ad82b3fd37582fa8147ac6\n    Successfully built pycebox spacy-lookups-data wrapt\n    Installing collected packages: typing-extensions, numpy, grpcio, absl-py, wrapt, tensorflow-estimator, spacy-lookups-data, h5py, gast, flatbuffers, tensorflow, scikit-learn, attrs, pycebox, pathlib2, opencv-python, alibi, aif360, machine-learning-datasets\n      Attempting uninstall: typing-extensions\n        Found existing installation: typing-extensions 3.10.0.2\n        Uninstalling typing-extensions-3.10.0.2:\n          Successfully uninstalled typing-extensions-3.10.0.2\n      Attempting uninstall: numpy\n        Found existing installation: numpy 1.21.5\n        Uninstalling numpy-1.21.5:\n          Successfully uninstalled numpy-1.21.5\n      Attempting uninstall: grpcio\n        Found existing installation: grpcio 1.44.0\n        Uninstalling grpcio-1.44.0:\n          Successfully uninstalled grpcio-1.44.0\n      Attempting uninstall: absl-py\n        Found existing installation: absl-py 1.0.0\n        Uninstalling absl-py-1.0.0:\n          Successfully uninstalled absl-py-1.0.0\n      Attempting uninstall: wrapt\n        Found existing installation: wrapt 1.14.0\n        Uninstalling wrapt-1.14.0:\n          Successfully uninstalled wrapt-1.14.0\n      Attempting uninstall: tensorflow-estimator\n        Found existing installation: tensorflow-estimator 2.8.0\n        Uninstalling tensorflow-estimator-2.8.0:\n          Successfully uninstalled tensorflow-estimator-2.8.0\n      Attempting uninstall: h5py\n        Found existing installation: h5py 3.1.0\n        Uninstalling h5py-3.1.0:\n          Successfully uninstalled h5py-3.1.0\n      Attempting uninstall: gast\n        Found existing installation: gast 0.5.3\n        Uninstalling gast-0.5.3:\n          Successfully uninstalled gast-0.5.3\n      Attempting uninstall: flatbuffers\n        Found existing installation: flatbuffers 2.0\n        Uninstalling flatbuffers-2.0:\n          Successfully uninstalled flatbuffers-2.0\n      Attempting uninstall: tensorflow\n        Found existing installation: tensorflow 2.8.0\n        Uninstalling tensorflow-2.8.0:\n          Successfully uninstalled tensorflow-2.8.0\n      Attempting uninstall: scikit-learn\n        Found existing installation: scikit-learn 1.0.2\n        Uninstalling scikit-learn-1.0.2:\n          Successfully uninstalled scikit-learn-1.0.2\n      Attempting uninstall: attrs\n        Found existing installation: attrs 21.4.0\n        Uninstalling attrs-21.4.0:\n          Successfully uninstalled attrs-21.4.0\n      Attempting uninstall: opencv-python\n        Found existing installation: opencv-python 4.1.2.30\n        Uninstalling opencv-python-4.1.2.30:\n          Successfully uninstalled opencv-python-4.1.2.30\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    yellowbrick 1.4 requires scikit-learn>=1.0.0, but you have scikit-learn 0.22.2.post1 which is incompatible.\n    imbalanced-learn 0.8.1 requires scikit-learn>=0.24, but you have scikit-learn 0.22.2.post1 which is incompatible.\n    datascience 0.10.6 requires folium==0.2.1, but you have folium 0.8.3 which is incompatible.\n    albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Successfully installed absl-py-0.15.0 aif360-0.3.0 alibi-0.5.8 attrs-20.3.0 flatbuffers-1.12 gast-0.3.3 grpcio-1.32.0 h5py-2.10.0 machine-learning-datasets-0.1.16.4 numpy-1.19.5 opencv-python-4.5.5.64 pathlib2-2.3.7.post1 pycebox-0.0.1 scikit-learn-0.22.2.post1 spacy-lookups-data-0.1.0 tensorflow-2.4.4 tensorflow-estimator-2.4.0 typing-extensions-3.7.4.3 wrapt-1.12.1\n\n\n\n\n    Collecting catboost\n      Downloading catboost-1.0.4-cp37-none-manylinux1_x86_64.whl (76.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 76.1 MB 55 kB/s \n    \u001b[?25hRequirement already satisfied: alibi in /usr/local/lib/python3.7/dist-packages (0.5.8)\n    Collecting alibi\n      Downloading alibi-0.6.5-py3-none-any.whl (398 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 398 kB 45.9 MB/s \n    \u001b[?25hCollecting shap\n      Downloading shap-0.40.0-cp37-cp37m-manylinux2010_x86_64.whl (564 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 564 kB 46.3 MB/s \n    \u001b[?25hCollecting witwidget\n      Downloading witwidget-1.8.1-py3-none-any.whl (1.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.5 MB 41.3 MB/s \n    \u001b[?25hRequirement already satisfied: plotly in /usr/local/lib/python3.7/dist-packages (from catboost) (5.5.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from catboost) (1.15.0)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from catboost) (1.4.1)\n    Requirement already satisfied: pandas>=0.24.0 in /usr/local/lib/python3.7/dist-packages (from catboost) (1.3.5)\n    Requirement already satisfied: graphviz in /usr/local/lib/python3.7/dist-packages (from catboost) (0.10.1)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from catboost) (3.5.1)\n    Requirement already satisfied: numpy>=1.16.0 in /usr/local/lib/python3.7/dist-packages (from catboost) (1.19.5)\n    Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24.0->catboost) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24.0->catboost) (2.8.2)\n    Requirement already satisfied: attrs<22.0.0,>=19.2.0 in /usr/local/lib/python3.7/dist-packages (from alibi) (20.3.0)\n    Requirement already satisfied: dill<0.4.0,>=0.3.0 in /usr/local/lib/python3.7/dist-packages (from alibi) (0.3.4)\n    Requirement already satisfied: Pillow<10.0,>=5.4.1 in /usr/local/lib/python3.7/dist-packages (from alibi) (7.1.2)\n    Collecting transformers<5.0.0,>=4.7.0\n      Downloading transformers-4.17.0-py3-none-any.whl (3.8 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.8 MB 39.7 MB/s \n    \u001b[?25hRequirement already satisfied: scikit-image!=0.17.1,<0.20,>=0.14.2 in /usr/local/lib/python3.7/dist-packages (from alibi) (0.18.3)\n    Requirement already satisfied: scikit-learn<1.1.0,>=0.20.2 in /usr/local/lib/python3.7/dist-packages (from alibi) (0.22.2.post1)\n    Requirement already satisfied: requests<3.0.0,>=2.21.0 in /usr/local/lib/python3.7/dist-packages (from alibi) (2.23.0)\n    Requirement already satisfied: spacy[lookups]<4.0.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from alibi) (2.2.4)\n    Requirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.7/dist-packages (from alibi) (3.7.4.3)\n    Requirement already satisfied: tqdm<5.0.0,>=4.28.1 in /usr/local/lib/python3.7/dist-packages (from alibi) (4.63.0)\n    Requirement already satisfied: tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from alibi) (2.4.4)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->catboost) (0.11.0)\n    Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib->catboost) (4.31.2)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->catboost) (1.4.0)\n    Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib->catboost) (21.3)\n    Requirement already satisfied: pyparsing>=2.2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->catboost) (3.0.7)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests<3.0.0,>=2.21.0->alibi) (1.24.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests<3.0.0,>=2.21.0->alibi) (2021.10.8)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests<3.0.0,>=2.21.0->alibi) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests<3.0.0,>=2.21.0->alibi) (3.0.4)\n    Requirement already satisfied: networkx>=2.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image!=0.17.1,<0.20,>=0.14.2->alibi) (2.6.3)\n    Requirement already satisfied: PyWavelets>=1.1.1 in /usr/local/lib/python3.7/dist-packages (from scikit-image!=0.17.1,<0.20,>=0.14.2->alibi) (1.3.0)\n    Requirement already satisfied: tifffile>=2019.7.26 in /usr/local/lib/python3.7/dist-packages (from scikit-image!=0.17.1,<0.20,>=0.14.2->alibi) (2021.11.2)\n    Requirement already satisfied: imageio>=2.3.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image!=0.17.1,<0.20,>=0.14.2->alibi) (2.4.1)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn<1.1.0,>=0.20.2->alibi) (1.1.0)\n    Requirement already satisfied: cymem<2.1.0,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi) (2.0.6)\n    Requirement already satisfied: srsly<1.1.0,>=1.0.2 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi) (1.0.5)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi) (57.4.0)\n    Requirement already satisfied: blis<0.5.0,>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi) (0.4.1)\n    Requirement already satisfied: wasabi<1.1.0,>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi) (0.9.0)\n    Requirement already satisfied: plac<1.2.0,>=0.9.6 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi) (1.1.3)\n    Requirement already satisfied: catalogue<1.1.0,>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi) (1.0.0)\n    Requirement already satisfied: murmurhash<1.1.0,>=0.28.0 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi) (1.0.6)\n    Requirement already satisfied: preshed<3.1.0,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi) (3.0.6)\n    Requirement already satisfied: thinc==7.4.0 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi) (7.4.0)\n    Requirement already satisfied: spacy-lookups-data<0.2.0,>=0.0.5 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi) (0.1.0)\n    Requirement already satisfied: importlib-metadata>=0.20 in /usr/local/lib/python3.7/dist-packages (from catalogue<1.1.0,>=0.0.7->spacy[lookups]<4.0.0,>=2.0.0->alibi) (4.11.3)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=0.20->catalogue<1.1.0,>=0.0.7->spacy[lookups]<4.0.0,>=2.0.0->alibi) (3.7.0)\n    Requirement already satisfied: tensorboard~=2.4 in /usr/local/lib/python3.7/dist-packages (from tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (2.8.0)\n    Requirement already satisfied: keras-preprocessing~=1.1.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (1.1.2)\n    Requirement already satisfied: wheel~=0.35 in /usr/local/lib/python3.7/dist-packages (from tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (0.37.1)\n    Requirement already satisfied: wrapt~=1.12.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (1.12.1)\n    Requirement already satisfied: gast==0.3.3 in /usr/local/lib/python3.7/dist-packages (from tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (0.3.3)\n    Requirement already satisfied: opt-einsum~=3.3.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (3.3.0)\n    Requirement already satisfied: tensorflow-estimator<2.5.0,>=2.4.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (2.4.0)\n    Requirement already satisfied: protobuf>=3.9.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (3.17.3)\n    Requirement already satisfied: absl-py~=0.10 in /usr/local/lib/python3.7/dist-packages (from tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (0.15.0)\n    Requirement already satisfied: google-pasta~=0.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (0.2.0)\n    Requirement already satisfied: grpcio~=1.32.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (1.32.0)\n    Requirement already satisfied: h5py~=2.10.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (2.10.0)\n    Requirement already satisfied: flatbuffers~=1.12.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (1.12)\n    Requirement already satisfied: termcolor~=1.1.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (1.1.0)\n    Requirement already satisfied: astunparse~=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (1.6.3)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (1.8.1)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (3.3.6)\n    Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (1.0.1)\n    Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (0.6.1)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (0.4.6)\n    Requirement already satisfied: google-auth<3,>=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (1.35.0)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard~=2.4->tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (0.2.8)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard~=2.4->tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (4.2.4)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard~=2.4->tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (4.8)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.4->tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (1.3.1)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<3,>=1.6.3->tensorboard~=2.4->tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (0.4.8)\n    Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.4->tensorflow!=2.6.0,!=2.6.1,<2.9.0,>=2.0.0->alibi) (3.2.0)\n    Requirement already satisfied: filelock in /usr/local/lib/python3.7/dist-packages (from transformers<5.0.0,>=4.7.0->alibi) (3.6.0)\n    Collecting huggingface-hub<1.0,>=0.1.0\n      Downloading huggingface_hub-0.4.0-py3-none-any.whl (67 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 67 kB 4.7 MB/s \n    \u001b[?25hCollecting sacremoses\n      Downloading sacremoses-0.0.49-py3-none-any.whl (895 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 895 kB 46.6 MB/s \n    \u001b[?25hRequirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.7/dist-packages (from transformers<5.0.0,>=4.7.0->alibi) (2019.12.20)\n    Collecting tokenizers!=0.11.3,>=0.11.1\n      Downloading tokenizers-0.11.6-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (6.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.5 MB 43.8 MB/s \n    \u001b[?25hCollecting pyyaml>=5.1\n      Downloading PyYAML-6.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (596 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 596 kB 53.8 MB/s \n    \u001b[?25hCollecting slicer==0.0.7\n      Downloading slicer-0.0.7-py3-none-any.whl (14 kB)\n    Requirement already satisfied: numba in /usr/local/lib/python3.7/dist-packages (from shap) (0.51.2)\n    Requirement already satisfied: cloudpickle in /usr/local/lib/python3.7/dist-packages (from shap) (1.3.0)\n    Requirement already satisfied: ipywidgets>=7.0.0 in /usr/local/lib/python3.7/dist-packages (from witwidget) (7.7.0)\n    Requirement already satisfied: google-api-python-client>=1.7.8 in /usr/local/lib/python3.7/dist-packages (from witwidget) (1.12.11)\n    Requirement already satisfied: oauth2client>=4.1.3 in /usr/local/lib/python3.7/dist-packages (from witwidget) (4.1.3)\n    Requirement already satisfied: google-auth-httplib2>=0.0.3 in /usr/local/lib/python3.7/dist-packages (from google-api-python-client>=1.7.8->witwidget) (0.0.4)\n    Requirement already satisfied: uritemplate<4dev,>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from google-api-python-client>=1.7.8->witwidget) (3.0.1)\n    Requirement already satisfied: httplib2<1dev,>=0.15.0 in /usr/local/lib/python3.7/dist-packages (from google-api-python-client>=1.7.8->witwidget) (0.17.4)\n    Requirement already satisfied: google-api-core<3dev,>=1.21.0 in /usr/local/lib/python3.7/dist-packages (from google-api-python-client>=1.7.8->witwidget) (1.26.3)\n    Requirement already satisfied: googleapis-common-protos<2.0dev,>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from google-api-core<3dev,>=1.21.0->google-api-python-client>=1.7.8->witwidget) (1.56.0)\n    Requirement already satisfied: ipython-genutils~=0.2.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets>=7.0.0->witwidget) (0.2.0)\n    Requirement already satisfied: ipython>=4.0.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets>=7.0.0->witwidget) (5.5.0)\n    Requirement already satisfied: nbformat>=4.2.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets>=7.0.0->witwidget) (5.2.0)\n    Requirement already satisfied: jupyterlab-widgets>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets>=7.0.0->witwidget) (1.1.0)\n    Requirement already satisfied: traitlets>=4.3.1 in /usr/local/lib/python3.7/dist-packages (from ipywidgets>=7.0.0->witwidget) (5.1.1)\n    Requirement already satisfied: ipykernel>=4.5.1 in /usr/local/lib/python3.7/dist-packages (from ipywidgets>=7.0.0->witwidget) (4.10.1)\n    Requirement already satisfied: widgetsnbextension~=3.6.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets>=7.0.0->witwidget) (3.6.0)\n    Requirement already satisfied: jupyter-client in /usr/local/lib/python3.7/dist-packages (from ipykernel>=4.5.1->ipywidgets>=7.0.0->witwidget) (5.3.5)\n    Requirement already satisfied: tornado>=4.0 in /usr/local/lib/python3.7/dist-packages (from ipykernel>=4.5.1->ipywidgets>=7.0.0->witwidget) (5.1.1)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets>=7.0.0->witwidget) (4.4.2)\n    Requirement already satisfied: pexpect in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets>=7.0.0->witwidget) (4.8.0)\n    Requirement already satisfied: pickleshare in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets>=7.0.0->witwidget) (0.7.5)\n    Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets>=7.0.0->witwidget) (1.0.18)\n    Requirement already satisfied: pygments in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets>=7.0.0->witwidget) (2.6.1)\n    Requirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets>=7.0.0->witwidget) (0.8.1)\n    Requirement already satisfied: jupyter-core in /usr/local/lib/python3.7/dist-packages (from nbformat>=4.2.0->ipywidgets>=7.0.0->witwidget) (4.9.2)\n    Requirement already satisfied: jsonschema!=2.5.0,>=2.4 in /usr/local/lib/python3.7/dist-packages (from nbformat>=4.2.0->ipywidgets>=7.0.0->witwidget) (4.3.3)\n    Requirement already satisfied: pyrsistent!=0.17.0,!=0.17.1,!=0.17.2,>=0.14.0 in /usr/local/lib/python3.7/dist-packages (from jsonschema!=2.5.0,>=2.4->nbformat>=4.2.0->ipywidgets>=7.0.0->witwidget) (0.18.1)\n    Requirement already satisfied: importlib-resources>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from jsonschema!=2.5.0,>=2.4->nbformat>=4.2.0->ipywidgets>=7.0.0->witwidget) (5.4.0)\n    Requirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython>=4.0.0->ipywidgets>=7.0.0->witwidget) (0.2.5)\n    Requirement already satisfied: notebook>=4.4.1 in /usr/local/lib/python3.7/dist-packages (from widgetsnbextension~=3.6.0->ipywidgets>=7.0.0->witwidget) (5.3.1)\n    Requirement already satisfied: Send2Trash in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets>=7.0.0->witwidget) (1.8.0)\n    Requirement already satisfied: terminado>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets>=7.0.0->witwidget) (0.13.3)\n    Requirement already satisfied: nbconvert in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets>=7.0.0->witwidget) (5.6.1)\n    Requirement already satisfied: jinja2 in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets>=7.0.0->witwidget) (2.11.3)\n    Requirement already satisfied: pyzmq>=13 in /usr/local/lib/python3.7/dist-packages (from jupyter-client->ipykernel>=4.5.1->ipywidgets>=7.0.0->witwidget) (22.3.0)\n    Requirement already satisfied: ptyprocess in /usr/local/lib/python3.7/dist-packages (from terminado>=0.8.1->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets>=7.0.0->witwidget) (0.7.0)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets>=7.0.0->witwidget) (2.0.1)\n    Requirement already satisfied: pandocfilters>=1.4.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets>=7.0.0->witwidget) (1.5.0)\n    Requirement already satisfied: bleach in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets>=7.0.0->witwidget) (4.1.0)\n    Requirement already satisfied: mistune<2,>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets>=7.0.0->witwidget) (0.8.4)\n    Requirement already satisfied: defusedxml in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets>=7.0.0->witwidget) (0.7.1)\n    Requirement already satisfied: entrypoints>=0.2.2 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets>=7.0.0->witwidget) (0.4)\n    Requirement already satisfied: testpath in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets>=7.0.0->witwidget) (0.6.0)\n    Requirement already satisfied: webencodings in /usr/local/lib/python3.7/dist-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets>=7.0.0->witwidget) (0.5.1)\n    Requirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba->shap) (0.34.0)\n    Requirement already satisfied: tenacity>=6.2.0 in /usr/local/lib/python3.7/dist-packages (from plotly->catboost) (8.0.1)\n    Requirement already satisfied: click in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers<5.0.0,>=4.7.0->alibi) (7.1.2)\n    Installing collected packages: pyyaml, tokenizers, sacremoses, huggingface-hub, transformers, slicer, witwidget, shap, catboost, alibi\n      Attempting uninstall: pyyaml\n        Found existing installation: PyYAML 3.13\n        Uninstalling PyYAML-3.13:\n          Successfully uninstalled PyYAML-3.13\n      Attempting uninstall: alibi\n        Found existing installation: alibi 0.5.8\n        Uninstalling alibi-0.5.8:\n          Successfully uninstalled alibi-0.5.8\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    machine-learning-datasets 0.1.16.4 requires alibi<0.6.0,>=0.5.5, but you have alibi 0.6.5 which is incompatible.\u001b[0m\n    Successfully installed alibi-0.6.5 catboost-1.0.4 huggingface-hub-0.4.0 pyyaml-6.0 sacremoses-0.0.49 shap-0.40.0 slicer-0.0.7 tokenizers-0.11.6 transformers-4.17.0 witwidget-1.8.1\n\n\n\n```python\nimport math\nimport machine_learning_datasets as mldatasets\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import metrics\nfrom catboost import CatBoostClassifier\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom alibi.utils.mapping import ohe_to_ord, ord_to_ohe\nfrom alibi.explainers import AnchorTabular\nfrom alibi.explainers import CEM\nfrom alibi.explainers import CounterFactualProto\nimport shap\nimport witwidget\nfrom witwidget.notebook.visualization import WitWidget, WitConfigBuilder\n```\n\n    pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.\n\n\n\n```python\ntf.compat.v1.disable_eager_execution()\nprint('Eager execution enabled: ', tf.executing_eagerly()) \n```\n\n    Eager execution enabled:  False\n\n\n\n```python\ntf.compat.v1.disable_eager_execution()\nprint('Eager execution enabled: ', tf.executing_eagerly()) \n```\n\n    Eager execution enabled:  False\n\n\n\n```python\nrecidivism_df = mldatasets.load(\"recidivism-risk\", prepare=True)\n\n```\n\n    https://storage.googleapis.com/what-if-tool-resources/computefest2019/cox-violent-parsed_filt.csv downloaded to /content/data/cox-violent-parsed_filt.csv\n    1 dataset files found in /content/data folder\n    parsing /content/data/cox-violent-parsed_filt.csv\n\n\n\n```python\nrecidivism_df.info()\n\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    Int64Index: 14788 entries, 0 to 18315\n    Data columns (total 23 columns):\n     #   Column                 Non-Null Count  Dtype\n    ---  ------                 --------------  -----\n     0   age                    14788 non-null  int8 \n     1   juv_fel_count          14788 non-null  int8 \n     2   juv_misd_count         14788 non-null  int8 \n     3   juv_other_count        14788 non-null  int64\n     4   priors_count           14788 non-null  int8 \n     5   is_recid               14788 non-null  int8 \n     6   sex_Female             14788 non-null  uint8\n     7   sex_Male               14788 non-null  uint8\n     8   race_African-American  14788 non-null  uint8\n     9   race_Asian             14788 non-null  uint8\n     10  race_Caucasian         14788 non-null  uint8\n     11  race_Hispanic          14788 non-null  uint8\n     12  race_Native American   14788 non-null  uint8\n     13  race_Other             14788 non-null  uint8\n     14  c_charge_degree_(F1)   14788 non-null  uint8\n     15  c_charge_degree_(F2)   14788 non-null  uint8\n     16  c_charge_degree_(F3)   14788 non-null  uint8\n     17  c_charge_degree_(F7)   14788 non-null  uint8\n     18  c_charge_degree_(M1)   14788 non-null  uint8\n     19  c_charge_degree_(M2)   14788 non-null  uint8\n     20  c_charge_degree_(MO3)  14788 non-null  uint8\n     21  c_charge_degree_Other  14788 non-null  uint8\n     22  compas_score           14788 non-null  int64\n    dtypes: int64(2), int8(5), uint8(16)\n    memory usage: 649.9 KB\n\n\n\n```python\ncf_matrix = metrics.confusion_matrix(recidivism_df.is_recid,\\\n                                     recidivism_df.compas_score)\nplt.figure(figsize=(6, 5))\nsns.heatmap(cf_matrix/np.sum(cf_matrix), annot=True,\\\n            fmt='.2%', cmap='Blues', annot_kws={'size':16})\n```\n\n\n```python\nrecidivism_c_df = recidivism_df[recidivism_df['race_Caucasian'] == 1]\nrecidivism_aa_df = recidivism_df[recidivism_df['race_African-American'] == 1]\n\n_ = mldatasets.\\\n      compare_confusion_matrices(recidivism_c_df.is_recid, \n                                 recidivism_c_df.compas_score,\\\n                                 recidivism_aa_df.is_recid,\\\n                                 recidivism_aa_df.compas_score,\\\n                                 'Caucasian', 'African-American', compare_fpr=True)\n```\n\n\n```python\nrand = 9\nnp.random.seed(rand)\ntf.random.set_seed(rand)\n\ny = recidivism_df['compas_score']\nX = recidivism_df.drop(['compas_score', 'is_recid'], axis=1).copy()\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=rand)\n```\n\n\n```python\norig_plt_params = plt.rcParams\nsns.set()\ncb_mdl = CatBoostClassifier(iterations=500, learning_rate=0.5, depth=8)\nfitted_cb_mdl = cb_mdl.fit(X_train, y_train, verbose=False)\ny_train_cb_pred, y_test_cb_prob, y_test_cb_pred =\\\n        mldatasets.evaluate_class_mdl(fitted_cb_mdl, X_train,\\\n                                      X_test, y_train, y_test)\n```\n\n\n```python\n!pip install --upgrade pandas numpy tqdm scikit-learn lightgbm xgboost networkx pydot matplotlib seaborn\n\n```\n\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (1.3.5)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (1.19.5)\n    Collecting numpy\n      Downloading numpy-1.21.5-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (15.7 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 15.7 MB 7.0 MB/s \n    \u001b[?25hRequirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (4.63.0)\n    Requirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (0.22.2.post1)\n    Collecting scikit-learn\n      Downloading scikit_learn-1.0.2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (24.8 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 24.8 MB 44.9 MB/s \n    \u001b[?25hRequirement already satisfied: lightgbm in /usr/local/lib/python3.7/dist-packages (2.2.3)\n    Collecting lightgbm\n      Downloading lightgbm-3.3.2-py3-none-manylinux1_x86_64.whl (2.0 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.0 MB 35.0 MB/s \n    \u001b[?25hRequirement already satisfied: xgboost in /usr/local/lib/python3.7/dist-packages (0.90)\n    Collecting xgboost\n      Downloading xgboost-1.5.2-py3-none-manylinux2014_x86_64.whl (173.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 173.6 MB 6.1 kB/s \n    \u001b[?25hRequirement already satisfied: networkx in /usr/local/lib/python3.7/dist-packages (2.6.3)\n    Requirement already satisfied: pydot in /usr/local/lib/python3.7/dist-packages (1.3.0)\n    Collecting pydot\n      Downloading pydot-1.4.2-py2.py3-none-any.whl (21 kB)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (3.1.3)\n    Collecting matplotlib\n      Using cached matplotlib-3.5.1-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl (11.2 MB)\n    Requirement already satisfied: seaborn in /usr/local/lib/python3.7/dist-packages (0.11.2)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas) (2.8.2)\n    Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas) (2018.9)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas) (1.15.0)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn) (1.1.0)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn) (3.1.0)\n    Requirement already satisfied: scipy>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn) (1.4.1)\n    Requirement already satisfied: wheel in /usr/local/lib/python3.7/dist-packages (from lightgbm) (0.37.1)\n    Requirement already satisfied: pyparsing>=2.1.4 in /usr/local/lib/python3.7/dist-packages (from pydot) (3.0.7)\n    Requirement already satisfied: pillow>=6.2.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib) (7.1.2)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib) (1.4.0)\n    Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib) (4.31.2)\n    Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib) (21.3)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib) (0.11.0)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from kiwisolver>=1.0.1->matplotlib) (3.7.4.3)\n    Installing collected packages: numpy, scikit-learn, matplotlib, xgboost, pydot, lightgbm\n      Attempting uninstall: numpy\n        Found existing installation: numpy 1.19.5\n        Uninstalling numpy-1.19.5:\n          Successfully uninstalled numpy-1.19.5\n      Attempting uninstall: scikit-learn\n        Found existing installation: scikit-learn 0.22.2.post1\n        Uninstalling scikit-learn-0.22.2.post1:\n          Successfully uninstalled scikit-learn-0.22.2.post1\n      Attempting uninstall: matplotlib\n        Found existing installation: matplotlib 3.1.3\n        Uninstalling matplotlib-3.1.3:\n          Successfully uninstalled matplotlib-3.1.3\n      Attempting uninstall: xgboost\n        Found existing installation: xgboost 0.90\n        Uninstalling xgboost-0.90:\n          Successfully uninstalled xgboost-0.90\n      Attempting uninstall: pydot\n        Found existing installation: pydot 1.3.0\n        Uninstalling pydot-1.3.0:\n          Successfully uninstalled pydot-1.3.0\n      Attempting uninstall: lightgbm\n        Found existing installation: lightgbm 2.2.3\n        Uninstalling lightgbm-2.2.3:\n          Successfully uninstalled lightgbm-2.2.3\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    tensorflow 2.4.4 requires numpy~=1.19.2, but you have numpy 1.21.5 which is incompatible.\n    machine-learning-datasets 0.1.16.4 requires alibi<0.6.0,>=0.5.5, but you have alibi 0.6.5 which is incompatible.\n    machine-learning-datasets 0.1.16.4 requires scikit-learn<0.23.0,>=0.22.2.post1, but you have scikit-learn 1.0.2 which is incompatible.\n    datascience 0.10.6 requires folium==0.2.1, but you have folium 0.8.3 which is incompatible.\n    albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Successfully installed lightgbm-3.3.2 matplotlib-3.5.1 numpy-1.21.5 pydot-1.4.2 scikit-learn-1.0.2 xgboost-1.5.2\n\n\n\n\n\n```python\n!pip install --upgrade machine-learning-datasets\n!pip install --upgrade econml dowhy\n!pip install --no-deps git+https://github.com/EthicalML/xai.git\n!pip install aif360==0.3.0\n!pip install BlackBoxAuditing==0.1.54\n```\n\n    Requirement already satisfied: machine-learning-datasets in /usr/local/lib/python3.7/dist-packages (0.1.16.4)\n    Requirement already satisfied: numpy<2.0.0,>=1.19.5 in /usr/local/lib/python3.7/dist-packages (from machine-learning-datasets) (1.21.5)\n    Requirement already satisfied: tqdm<5.0.0,>=4.41.1 in /usr/local/lib/python3.7/dist-packages (from machine-learning-datasets) (4.63.0)\n    Collecting alibi<0.6.0,>=0.5.5\n      Using cached alibi-0.5.8-py3-none-any.whl (312 kB)\n    Requirement already satisfied: pycebox<0.0.2,>=0.0.1 in /usr/local/lib/python3.7/dist-packages (from machine-learning-datasets) (0.0.1)\n    Requirement already satisfied: mlxtend<0.15.0,>=0.14.0 in /usr/local/lib/python3.7/dist-packages (from machine-learning-datasets) (0.14.0)\n    Requirement already satisfied: matplotlib<4.0.0,>=3.2.2 in /usr/local/lib/python3.7/dist-packages (from machine-learning-datasets) (3.5.1)\n    Requirement already satisfied: pathlib2<3.0.0,>=2.3.5 in /usr/local/lib/python3.7/dist-packages (from machine-learning-datasets) (2.3.7.post1)\n    Requirement already satisfied: scipy<2.0.0,>=1.4.1 in /usr/local/lib/python3.7/dist-packages (from machine-learning-datasets) (1.4.1)\n    Requirement already satisfied: aif360<0.4.0,>=0.3.0 in /usr/local/lib/python3.7/dist-packages (from machine-learning-datasets) (0.3.0)\n    Requirement already satisfied: opencv-python<5.0.0,>=4.5.1 in /usr/local/lib/python3.7/dist-packages (from machine-learning-datasets) (4.5.5.64)\n    Requirement already satisfied: seaborn<0.12.0,>=0.11.1 in /usr/local/lib/python3.7/dist-packages (from machine-learning-datasets) (0.11.2)\n    Requirement already satisfied: statsmodels<0.11.0,>=0.10.2 in /usr/local/lib/python3.7/dist-packages (from machine-learning-datasets) (0.10.2)\n    Collecting scikit-learn<0.23.0,>=0.22.2.post1\n      Using cached scikit_learn-0.22.2.post1-cp37-cp37m-manylinux1_x86_64.whl (7.1 MB)\n    Requirement already satisfied: pandas<2.0.0,>=1.1.5 in /usr/local/lib/python3.7/dist-packages (from machine-learning-datasets) (1.3.5)\n    Requirement already satisfied: tensorflow<2.5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from alibi<0.6.0,>=0.5.5->machine-learning-datasets) (2.4.4)\n    Requirement already satisfied: scikit-image!=0.17.1,<0.19,>=0.14.2 in /usr/local/lib/python3.7/dist-packages (from alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.18.3)\n    Requirement already satisfied: typing-extensions>=3.7.2 in /usr/local/lib/python3.7/dist-packages (from alibi<0.6.0,>=0.5.5->machine-learning-datasets) (3.7.4.3)\n    Requirement already satisfied: attrs<21.0.0,>=19.2.0 in /usr/local/lib/python3.7/dist-packages (from alibi<0.6.0,>=0.5.5->machine-learning-datasets) (20.3.0)\n    Requirement already satisfied: spacy[lookups]<4.0.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from alibi<0.6.0,>=0.5.5->machine-learning-datasets) (2.2.4)\n    Requirement already satisfied: dill<0.4.0,>=0.3.0 in /usr/local/lib/python3.7/dist-packages (from alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.3.4)\n    Requirement already satisfied: requests<3.0.0,>=2.21.0 in /usr/local/lib/python3.7/dist-packages (from alibi<0.6.0,>=0.5.5->machine-learning-datasets) (2.23.0)\n    Requirement already satisfied: Pillow<9.0,>=5.4.1 in /usr/local/lib/python3.7/dist-packages (from alibi<0.6.0,>=0.5.5->machine-learning-datasets) (7.1.2)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib<4.0.0,>=3.2.2->machine-learning-datasets) (1.4.0)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib<4.0.0,>=3.2.2->machine-learning-datasets) (0.11.0)\n    Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib<4.0.0,>=3.2.2->machine-learning-datasets) (4.31.2)\n    Requirement already satisfied: pyparsing>=2.2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib<4.0.0,>=3.2.2->machine-learning-datasets) (3.0.7)\n    Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib<4.0.0,>=3.2.2->machine-learning-datasets) (21.3)\n    Requirement already satisfied: python-dateutil>=2.7 in /usr/local/lib/python3.7/dist-packages (from matplotlib<4.0.0,>=3.2.2->machine-learning-datasets) (2.8.2)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from mlxtend<0.15.0,>=0.14.0->machine-learning-datasets) (57.4.0)\n    Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas<2.0.0,>=1.1.5->machine-learning-datasets) (2018.9)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from pathlib2<3.0.0,>=2.3.5->machine-learning-datasets) (1.15.0)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests<3.0.0,>=2.21.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests<3.0.0,>=2.21.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests<3.0.0,>=2.21.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (2021.10.8)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests<3.0.0,>=2.21.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.24.3)\n    Requirement already satisfied: tifffile>=2019.7.26 in /usr/local/lib/python3.7/dist-packages (from scikit-image!=0.17.1,<0.19,>=0.14.2->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (2021.11.2)\n    Requirement already satisfied: imageio>=2.3.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image!=0.17.1,<0.19,>=0.14.2->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (2.4.1)\n    Requirement already satisfied: PyWavelets>=1.1.1 in /usr/local/lib/python3.7/dist-packages (from scikit-image!=0.17.1,<0.19,>=0.14.2->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.3.0)\n    Requirement already satisfied: networkx>=2.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image!=0.17.1,<0.19,>=0.14.2->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (2.6.3)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn<0.23.0,>=0.22.2.post1->machine-learning-datasets) (1.1.0)\n    Requirement already satisfied: thinc==7.4.0 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (7.4.0)\n    Requirement already satisfied: preshed<3.1.0,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (3.0.6)\n    Requirement already satisfied: srsly<1.1.0,>=1.0.2 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.0.5)\n    Requirement already satisfied: wasabi<1.1.0,>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.9.0)\n    Requirement already satisfied: blis<0.5.0,>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.4.1)\n    Requirement already satisfied: catalogue<1.1.0,>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.0.0)\n    Requirement already satisfied: cymem<2.1.0,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (2.0.6)\n    Requirement already satisfied: plac<1.2.0,>=0.9.6 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.1.3)\n    Requirement already satisfied: murmurhash<1.1.0,>=0.28.0 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.0.6)\n    Requirement already satisfied: spacy-lookups-data<0.2.0,>=0.0.5 in /usr/local/lib/python3.7/dist-packages (from spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.1.0)\n    Requirement already satisfied: importlib-metadata>=0.20 in /usr/local/lib/python3.7/dist-packages (from catalogue<1.1.0,>=0.0.7->spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (4.11.3)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=0.20->catalogue<1.1.0,>=0.0.7->spacy[lookups]<4.0.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (3.7.0)\n    Requirement already satisfied: patsy>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from statsmodels<0.11.0,>=0.10.2->machine-learning-datasets) (0.5.2)\n    Collecting numpy<2.0.0,>=1.19.5\n      Using cached numpy-1.19.5-cp37-cp37m-manylinux2010_x86_64.whl (14.8 MB)\n    Requirement already satisfied: h5py~=2.10.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (2.10.0)\n    Requirement already satisfied: google-pasta~=0.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.2.0)\n    Requirement already satisfied: opt-einsum~=3.3.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (3.3.0)\n    Requirement already satisfied: gast==0.3.3 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.3.3)\n    Requirement already satisfied: grpcio~=1.32.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.32.0)\n    Requirement already satisfied: tensorboard~=2.4 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (2.8.0)\n    Requirement already satisfied: protobuf>=3.9.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (3.17.3)\n    Requirement already satisfied: termcolor~=1.1.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.1.0)\n    Requirement already satisfied: astunparse~=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.6.3)\n    Requirement already satisfied: keras-preprocessing~=1.1.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.1.2)\n    Requirement already satisfied: wrapt~=1.12.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.12.1)\n    Requirement already satisfied: flatbuffers~=1.12.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.12)\n    Requirement already satisfied: absl-py~=0.10 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.15.0)\n    Requirement already satisfied: wheel~=0.35 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.37.1)\n    Requirement already satisfied: tensorflow-estimator<2.5.0,>=2.4.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (2.4.0)\n    Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.6.1)\n    Requirement already satisfied: google-auth<3,>=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.35.0)\n    Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.0.1)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.8.1)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (3.3.6)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.4.6)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (4.2.4)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (4.8)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.2.8)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (1.3.1)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<3,>=1.6.3->tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (0.4.8)\n    Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.4->tensorflow<2.5.0,>=2.0.0->alibi<0.6.0,>=0.5.5->machine-learning-datasets) (3.2.0)\n    Installing collected packages: numpy, scikit-learn, alibi\n      Attempting uninstall: numpy\n        Found existing installation: numpy 1.21.5\n        Uninstalling numpy-1.21.5:\n          Successfully uninstalled numpy-1.21.5\n      Attempting uninstall: scikit-learn\n        Found existing installation: scikit-learn 1.0.2\n        Uninstalling scikit-learn-1.0.2:\n          Successfully uninstalled scikit-learn-1.0.2\n      Attempting uninstall: alibi\n        Found existing installation: alibi 0.6.5\n        Uninstalling alibi-0.6.5:\n          Successfully uninstalled alibi-0.6.5\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    yellowbrick 1.4 requires scikit-learn>=1.0.0, but you have scikit-learn 0.22.2.post1 which is incompatible.\n    imbalanced-learn 0.8.1 requires scikit-learn>=0.24, but you have scikit-learn 0.22.2.post1 which is incompatible.\n    datascience 0.10.6 requires folium==0.2.1, but you have folium 0.8.3 which is incompatible.\n    albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Successfully installed alibi-0.5.8 numpy-1.19.5 scikit-learn-0.22.2.post1\n\n\n\n\n    Collecting econml\n      Downloading econml-0.13.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (3.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.3 MB 4.1 MB/s \n    \u001b[?25hCollecting dowhy\n      Downloading dowhy-0.7.1-py3-none-any.whl (164 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 164 kB 39.6 MB/s \n    \u001b[?25hCollecting sparse\n      Downloading sparse-0.13.0-py2.py3-none-any.whl (77 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 77 kB 3.4 MB/s \n    \u001b[?25hRequirement already satisfied: scikit-learn>0.22.0 in /usr/local/lib/python3.7/dist-packages (from econml) (0.22.2.post1)\n    Requirement already satisfied: statsmodels>=0.10 in /usr/local/lib/python3.7/dist-packages (from econml) (0.10.2)\n    Collecting shap<0.40.0,>=0.38.1\n      Downloading shap-0.39.0.tar.gz (356 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 356 kB 15.6 MB/s \n    \u001b[?25hRequirement already satisfied: scipy>1.4.0 in /usr/local/lib/python3.7/dist-packages (from econml) (1.4.1)\n    Requirement already satisfied: lightgbm in /usr/local/lib/python3.7/dist-packages (from econml) (3.3.2)\n    Requirement already satisfied: joblib>=0.13.0 in /usr/local/lib/python3.7/dist-packages (from econml) (1.1.0)\n    Collecting dowhy\n      Downloading dowhy-0.6-py3-none-any.whl (123 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 123 kB 33.8 MB/s \n    \u001b[?25hRequirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from econml) (1.3.5)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from econml) (1.19.5)\n    Requirement already satisfied: networkx>=2.0 in /usr/local/lib/python3.7/dist-packages (from dowhy) (2.6.3)\n    Requirement already satisfied: pydot>=1.4 in /usr/local/lib/python3.7/dist-packages (from dowhy) (1.4.2)\n    Requirement already satisfied: sympy>=1.4 in /usr/local/lib/python3.7/dist-packages (from dowhy) (1.7.1)\n    Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas->econml) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->econml) (2.8.2)\n    Requirement already satisfied: pyparsing>=2.1.4 in /usr/local/lib/python3.7/dist-packages (from pydot>=1.4->dowhy) (3.0.7)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas->econml) (1.15.0)\n    Requirement already satisfied: tqdm>4.25.0 in /usr/local/lib/python3.7/dist-packages (from shap<0.40.0,>=0.38.1->econml) (4.63.0)\n    Requirement already satisfied: slicer==0.0.7 in /usr/local/lib/python3.7/dist-packages (from shap<0.40.0,>=0.38.1->econml) (0.0.7)\n    Requirement already satisfied: numba in /usr/local/lib/python3.7/dist-packages (from shap<0.40.0,>=0.38.1->econml) (0.51.2)\n    Requirement already satisfied: cloudpickle in /usr/local/lib/python3.7/dist-packages (from shap<0.40.0,>=0.38.1->econml) (1.3.0)\n    Requirement already satisfied: patsy>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from statsmodels>=0.10->econml) (0.5.2)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.4->dowhy) (1.2.1)\n    Requirement already satisfied: wheel in /usr/local/lib/python3.7/dist-packages (from lightgbm->econml) (0.37.1)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from numba->shap<0.40.0,>=0.38.1->econml) (57.4.0)\n    Requirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba->shap<0.40.0,>=0.38.1->econml) (0.34.0)\n    Building wheels for collected packages: shap\n      Building wheel for shap (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for shap: filename=shap-0.39.0-cp37-cp37m-linux_x86_64.whl size=491650 sha256=04db55ac7b8c329c53bd43f3c2be1df194478e3a581ae985026c5320c12295ca\n      Stored in directory: /root/.cache/pip/wheels/ca/25/8f/6ae5df62c32651cd719e972e738a8aaa4a87414c4d2b14c9c0\n    Successfully built shap\n    Installing collected packages: sparse, shap, dowhy, econml\n      Attempting uninstall: shap\n        Found existing installation: shap 0.40.0\n        Uninstalling shap-0.40.0:\n          Successfully uninstalled shap-0.40.0\n    Successfully installed dowhy-0.6 econml-0.13.0 shap-0.39.0 sparse-0.13.0\n\n\n\n\n    Collecting git+https://github.com/EthicalML/xai.git\n      Cloning https://github.com/EthicalML/xai.git to /tmp/pip-req-build-cyhqogqb\n      Running command git clone -q https://github.com/EthicalML/xai.git /tmp/pip-req-build-cyhqogqb\n    Building wheels for collected packages: xai\n      Building wheel for xai (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for xai: filename=xai-0.1.0-py3-none-any.whl size=349032 sha256=93137a30dc1e05e234d8977ba25c94db132727a1af0e5a104dca0a9a63ecdab0\n      Stored in directory: /tmp/pip-ephem-wheel-cache-eqkhnfbo/wheels/e9/c9/2c/db30b1608d79231b31dfc0dd5defac87b079ffb9fbee6ded4b\n    Successfully built xai\n    Installing collected packages: xai\n    Successfully installed xai-0.1.0\n    Requirement already satisfied: aif360==0.3.0 in /usr/local/lib/python3.7/dist-packages (0.3.0)\n    Requirement already satisfied: pandas>=0.24.0 in /usr/local/lib/python3.7/dist-packages (from aif360==0.3.0) (1.3.5)\n    Requirement already satisfied: scikit-learn>=0.21 in /usr/local/lib/python3.7/dist-packages (from aif360==0.3.0) (0.22.2.post1)\n    Requirement already satisfied: numpy>=1.16 in /usr/local/lib/python3.7/dist-packages (from aif360==0.3.0) (1.19.5)\n    Requirement already satisfied: scipy>=1.2.0 in /usr/local/lib/python3.7/dist-packages (from aif360==0.3.0) (1.4.1)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from aif360==0.3.0) (3.5.1)\n    Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24.0->aif360==0.3.0) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24.0->aif360==0.3.0) (2.8.2)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas>=0.24.0->aif360==0.3.0) (1.15.0)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.21->aif360==0.3.0) (1.1.0)\n    Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib->aif360==0.3.0) (21.3)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->aif360==0.3.0) (1.4.0)\n    Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib->aif360==0.3.0) (4.31.2)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->aif360==0.3.0) (0.11.0)\n    Requirement already satisfied: pillow>=6.2.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib->aif360==0.3.0) (7.1.2)\n    Requirement already satisfied: pyparsing>=2.2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->aif360==0.3.0) (3.0.7)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from kiwisolver>=1.0.1->matplotlib->aif360==0.3.0) (3.7.4.3)\n    Collecting BlackBoxAuditing==0.1.54\n      Downloading BlackBoxAuditing-0.1.54.tar.gz (2.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.6 MB 7.9 MB/s \n    \u001b[?25hRequirement already satisfied: networkx in /usr/local/lib/python3.7/dist-packages (from BlackBoxAuditing==0.1.54) (2.6.3)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from BlackBoxAuditing==0.1.54) (3.5.1)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from BlackBoxAuditing==0.1.54) (1.3.5)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from BlackBoxAuditing==0.1.54) (1.19.5)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->BlackBoxAuditing==0.1.54) (1.4.0)\n    Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib->BlackBoxAuditing==0.1.54) (21.3)\n    Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib->BlackBoxAuditing==0.1.54) (4.31.2)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->BlackBoxAuditing==0.1.54) (0.11.0)\n    Requirement already satisfied: pyparsing>=2.2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->BlackBoxAuditing==0.1.54) (3.0.7)\n    Requirement already satisfied: pillow>=6.2.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib->BlackBoxAuditing==0.1.54) (7.1.2)\n    Requirement already satisfied: python-dateutil>=2.7 in /usr/local/lib/python3.7/dist-packages (from matplotlib->BlackBoxAuditing==0.1.54) (2.8.2)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from kiwisolver>=1.0.1->matplotlib->BlackBoxAuditing==0.1.54) (3.7.4.3)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7->matplotlib->BlackBoxAuditing==0.1.54) (1.15.0)\n    Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas->BlackBoxAuditing==0.1.54) (2018.9)\n    Building wheels for collected packages: BlackBoxAuditing\n      Building wheel for BlackBoxAuditing (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for BlackBoxAuditing: filename=BlackBoxAuditing-0.1.54-py2.py3-none-any.whl size=1394770 sha256=cfea6e45c91713998eca7157d15f0ceef1785397aab2b82ad0e15cf43dae4bad\n      Stored in directory: /root/.cache/pip/wheels/05/9f/ee/541a74be4cf5dad17430e64d3276370ea7b6a834a76cb4215a\n    Successfully built BlackBoxAuditing\n    Installing collected packages: BlackBoxAuditing\n    Successfully installed BlackBoxAuditing-0.1.54\n\n\n\n```python\nimport math\nimport os\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport machine_learning_datasets as mldatasets\nimport pandas as pd\nimport numpy as np\nfrom tqdm.notebook import tqdm\n\nfrom sklearn import model_selection, tree, metrics\nimport lightgbm as lgb\nimport xgboost as xgb\n\nfrom aif360.datasets import BinaryLabelDataset\nfrom aif360.metrics import BinaryLabelDatasetMetric\nfrom aif360.metrics import ClassificationMetric\nfrom aif360.algorithms.preprocessing import Reweighing\nfrom aif360.algorithms.preprocessing import DisparateImpactRemover\nfrom aif360.algorithms.inprocessing import PrejudiceRemover\nfrom aif360.algorithms.inprocessing import GerryFairClassifier\nfrom aif360.algorithms.postprocessing.calibrated_eq_odds_postprocessing import CalibratedEqOddsPostprocessing\nfrom aif360.algorithms.postprocessing.eq_odds_postprocessing import EqOddsPostprocessing\n\nfrom econml.dr import LinearDRLearner\nimport dowhy\nfrom dowhy import CausalModel\n\nimport xai\nfrom networkx.drawing.nx_pydot import to_pydot\nfrom IPython.display import Image, display\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n%matplotlib inline\n```\n\n    WARNING:root:No module named 'numba.decorators': LFR will be unavailable. To install, run:\n    pip install 'aif360[LFR]'\n\n\n\n```python\n\n```\n\n\n```python\n!pip install matplotlib==3.1.3\n\n```\n\n    Collecting matplotlib==3.1.3\n      Downloading matplotlib-3.1.3-cp37-cp37m-manylinux1_x86_64.whl (13.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 13.1 MB 6.2 MB/s \n    \u001b[?25hRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib==3.1.3) (1.4.0)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib==3.1.3) (0.11.0)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib==3.1.3) (2.8.2)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib==3.1.3) (3.0.7)\n    Requirement already satisfied: numpy>=1.11 in /usr/local/lib/python3.7/dist-packages (from matplotlib==3.1.3) (1.19.5)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from kiwisolver>=1.0.1->matplotlib==3.1.3) (3.7.4.3)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.1->matplotlib==3.1.3) (1.15.0)\n    Installing collected packages: matplotlib\n      Attempting uninstall: matplotlib\n        Found existing installation: matplotlib 3.5.1\n        Uninstalling matplotlib-3.5.1:\n          Successfully uninstalled matplotlib-3.5.1\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    yellowbrick 1.4 requires scikit-learn>=1.0.0, but you have scikit-learn 0.22.2.post1 which is incompatible.\n    machine-learning-datasets 0.1.16.4 requires alibi<0.6.0,>=0.5.5, but you have alibi 0.6.5 which is incompatible.\n    machine-learning-datasets 0.1.16.4 requires matplotlib<4.0.0,>=3.2.2, but you have matplotlib 3.1.3 which is incompatible.\n    albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Successfully installed matplotlib-3.1.3\n\n\n\n\n\n```python\nccdefault_all_df = mldatasets.load(\"cc-default\", prepare=True)\n\n```\n\n    https://github.com/PacktPublishing/Interpretable-Machine-Learning-with-Python/raw/master/datasets/cc_defaults_taiwan.csv.zip downloaded to /content/data/cc_defaults_taiwan.csv.zip\n    /content/data/cc_defaults_taiwan.csv.zip uncompressed to /content/data/cc_defaults_taiwan.csv\n    1 dataset files found in /content/data/cc_defaults_taiwan.csv folder\n    parsing /content/data/cc_defaults_taiwan.csv/cc_defaults_new_taiwan.csv\n\n\n\n```python\nccdefault_all_df.info()\n\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    Int64Index: 30000 entries, 1 to 30000\n    Data columns (total 31 columns):\n     #   Column            Non-Null Count  Dtype  \n    ---  ------            --------------  -----  \n     0   CC_LIMIT_CAT      30000 non-null  int8   \n     1   EDUCATION         30000 non-null  int8   \n     2   MARITAL_STATUS    30000 non-null  int8   \n     3   GENDER            30000 non-null  int8   \n     4   AGE_GROUP         30000 non-null  int8   \n     5   pay_status_1      30000 non-null  int8   \n     6   pay_status_2      30000 non-null  int8   \n     7   pay_status_3      30000 non-null  int8   \n     8   pay_status_4      30000 non-null  int8   \n     9   pay_status_5      30000 non-null  int8   \n     10  pay_status_6      30000 non-null  int8   \n     11  paid_pct_1        30000 non-null  float64\n     12  paid_pct_2        30000 non-null  float64\n     13  paid_pct_3        30000 non-null  float64\n     14  paid_pct_4        30000 non-null  float64\n     15  paid_pct_5        30000 non-null  float64\n     16  paid_pct_6        30000 non-null  float64\n     17  bill1_over_limit  30000 non-null  float64\n     18  IS_DEFAULT        30000 non-null  int8   \n     19  _AGE              30000 non-null  int16  \n     20  _spend            30000 non-null  int32  \n     21  _tpm              30000 non-null  int16  \n     22  _ppm              30000 non-null  int16  \n     23  _RETAIL           30000 non-null  int8   \n     24  _URBAN            30000 non-null  int8   \n     25  _RURAL            30000 non-null  int8   \n     26  _PREMIUM          30000 non-null  int8   \n     27  _TREATMENT        30000 non-null  int8   \n     28  _LTV              30000 non-null  float64\n     29  _CC_LIMIT         30000 non-null  int32  \n     30  _risk_score       30000 non-null  float64\n    dtypes: float64(9), int16(3), int32(2), int8(17)\n    memory usage: 3.2 MB\n\n\n\n```python\nccdefault_all_df._TREATMENT.value_counts()\n\n```\n\n\n\n\n    -1    28904\n     0      274\n     1      274\n     2      274\n     3      274\n    Name: _TREATMENT, dtype: int64\n\n\n\n\n```python\nccdefault_bias_df = ccdefault_all_df[ccdefault_all_df._TREATMENT < 1]\nccdefault_causal_df = ccdefault_all_df[ccdefault_all_df._TREATMENT >= 0]\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "256ef6a8c4764132d3972e1821c15b25776ca00b", "size": 213734, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "interpretability.ipynb", "max_stars_repo_name": "sonam-pankaj95/gender_bias", "max_stars_repo_head_hexsha": "275c9e8fc719cb41837764292d952055ded0d26b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-16T07:13:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T07:13:11.000Z", "max_issues_repo_path": "interpretability.ipynb", "max_issues_repo_name": "sonam-pankaj95/gender_bias", "max_issues_repo_head_hexsha": "275c9e8fc719cb41837764292d952055ded0d26b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-27T11:59:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-27T11:59:44.000Z", "max_forks_repo_path": "interpretability.ipynb", "max_forks_repo_name": "sonam-pankaj95/gender_bias", "max_forks_repo_head_hexsha": "275c9e8fc719cb41837764292d952055ded0d26b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 142.9658862876, "max_line_length": 49713, "alphanum_fraction": 0.7687031544, "converted": true, "num_tokens": 32193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.06465348430116558, "lm_q1q2_score": 0.03232674215058279}}
{"text": "```python\nimport pandas as pd\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\nfrom collections import OrderedDict, defaultdict\nfrom sklearn.preprocessing import LabelEncoder\nimport sys\nimport os\nmodule_path = Path(\"../src/\")\nos.chdir(module_path)\nsys.path.append(module_path)\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n```\n\n\n```python\nfrom data_access.load_file import load_table, dict_to_df\nfrom data_preparation import compute_work_item_times\nfrom data_processing.functions import time_for_phase, set_end_date\nfrom data_processing import features\n```\n\nFirst we load and preprocess the data\n\n\n```python\nfilename = Path(\"../data/gdsc2_public.csv\")\ndata = load_table(filename)\ntotal_times = compute_work_item_times(data)\ntimes = time_for_phase(data, end_date=\"2018-03-31\", process=False)\ntimes.dropna(inplace=True)\n```\n\n\n```python\nopen_wis = total_times[pd.isnull(total_times[\"duration_in_days\"])][\"work_item\"].values\ntimes_open = times[times.work_item.isin(open_wis)]\ntimes_closed = times[~times.work_item.isin(open_wis)]\ntimes_closed.dropna(inplace=True)\ntimes_closed.loc[:, \"receive_date\"] = times_closed[\"from_timestamp\"].apply(lambda x: x.date())\ntimes_closed.loc[:, \"drop_date\"] = times_closed[\"to_timestamp\"].apply(lambda x: x.date())\n```\n\n\n```python\ntimes.loc[:, \"receive_date\"] = times[\"from_timestamp\"].apply(lambda x: x.date())\ntimes.loc[:, \"drop_date\"] = times[\"to_timestamp\"].apply(lambda x: x.date())\ndaterange = pd.date_range(start=str(times[\"receive_date\"].min()), end=str(times[\"drop_date\"].max()), freq='D')\n```\n\nFor easier handling we assume every working step to be closed until the last day in the dataset.\n\nWe now want to compute a measure for the experience of an employee. We define it as follow:\n\n\\begin{equation}\nx^{er}_{exp}(t) = \\frac{t_{spent}\\sum{w^{er}_{closed}(t)}}{\\sum{w_{closed}(t)}}\n\\end{equation}\n\nWe also want to define a measure for the workload of an employee:\n\n\\begin{equation}\nx^{er}_{load}(t) = \\frac{\\sum{w^{er}_{open}(t)}}{\\sum{w_{open}(t)}}\n\\end{equation}\n\nwith $t$ as time, $t_{spent}$ as time already spend in the company, $w$ being a working step and $er$ being a resource.\n\n\n```python\ndef x_experience(times, resource, t, col=\"current_resource\"):\n    assert col in times.columns, col + \" not in columns of dataframe\"\n    \n    closed_tickets = times[times[\"receive_date\"] < t]\n    er = closed_tickets[closed_tickets[col] == resource]\n    \n    try:\n        date_diff = (t - er[\"receive_date\"].min())\n        working_time = round(date_diff.total_seconds() / (24*3600), 2)\n    except TypeError:\n        working_time = 1\n    if pd.isna(working_time):\n        working_time = 1\n    \n    try:\n        x_exp = (working_time*len(er))/len(closed_tickets)\n    except ZeroDivisionError:\n        x_exp = 0\n        \n    return x_exp    \n```\n\n\n```python\ndef x_workload(times, resource, t, col=\"current_resource\"):\n    assert col in times.columns, col + \" not in columns of dataframe\"\n    \n    open_tickets = times[(times[\"receive_date\"] <= t) &\n                         (times[\"drop_date\"] >= t)]\n    er = open_tickets[open_tickets[col] == resource]\n    \n    try:\n        x_load = (len(er))/len(open_tickets)\n    except ZeroDivisionError:\n        x_load = 0\n        \n    return x_load\n```\n\nWe are going to test the functions with the most frequent resource.\n\n\n```python\nresource = \"ER_00061\"\nplot_df = pd.DataFrame(index=daterange, columns=[\"x_exp\", \"x_load\"])\nfor date in daterange:\n    plot_df.loc[date, \"x_exp\"] = x_experience(times, resource, date.date())\n    plot_df.loc[date, \"x_load\"] = x_workload(times, resource, date.date())\n```\n\nThe function runs without errors. We want to plot the results, the graph should show an increasing trend for the experience and some kind of fluktuation for the workload.\n\n\n```python\nfig, ax = plt.subplots(1, 2, figsize=(15,5), sharex=True, constrained_layout=True)\nplot_df[\"x_exp\"].plot(color='g', ax=ax[0], label=\"x_exp\")\nplot_df[\"x_load\"].plot(color='b', ax=ax[1], label=\"x_load\")\nax[0].set_title(\"Experience of most frequent resource\")\nax[1].set_title(\"Workload of most frequent resource\")\nax[0].legend()\nax[1].legend()\nplt.show()\n```\n\nNow we are able to compute the two measures for every resource for a given time. To add this as a feature to our model we also need a function to aggregate the measures regarding to the multiple resources working on one work item. We define the following as the employment rate for every work item:\n\n\\begin{equation}\nx^{wi}_{emp} = \\frac{\\sum_{er}{x^{er}_{exp}(t)x^{er}_{load}(t)}}{\\sum_{er}{w^{er}}}\n\\end{equation}\n\nwith $t$ as the time the employee recieves the task.\n\n\n```python\ndef employment_rate(times, work_item, resource_col=\"current_resource\"):\n    assert resource_col in times.columns, resource_col + \" not in columns of dateframe!\"\n    \n    wi = times[times[\"work_item\"] == work_item]\n    resources = list(wi[resource_col].values)\n    res_counter = defaultdict(int)\n    numerator = 0\n    x_exp_sum = 0\n    x_load_sum = 0\n    denumerator = len(resources)\n    \n    for resource in resources:\n        if resources.count(resource) > 1:\n            res_counter[resource] += 1\n            t = wi[wi[resource_col] == resource][\"receive_date\"].iloc[res_counter[resource]-1]\n        elif resources.count(resource) == 1:\n            t = wi[wi[resource_col] == resource][\"receive_date\"].values[0]\n        x_exp = x_experience(times, resource, t, resource_col)\n        x_load = x_workload(times, resource, t, resource_col)\n        x_exp_sum += x_exp\n        x_load_sum += x_load\n        numerator += (x_exp * x_load)\n\n    x_emp = numerator/denumerator\n    x_ex = x_exp_sum/denumerator\n    x_l = x_load_sum/denumerator\n    return x_emp, x_ex, x_l\n```\n\nNow we want to compute the measures for every work item and compare them\n\n\n```python\nx_emp, x_exp, x_load = employment_rate(times, \"WI_000001\")\n```\n\n\n```python\n# res_df = pd.DataFrame(index=times.work_item.unique(), columns=[\"x_emp\", \"x_exp\", \"x_load\"])\n# counter = 0\n# for wi in times.work_item.unique():\n#     x_emp, x_exp, x_load = employment_rate(times, wi)\n#     res_df.loc[wi, \"x_emp\"] = x_emp\n#     res_df.loc[wi, \"x_exp\"] = x_exp\n#     res_df.loc[wi, \"x_load\"] = x_load\n#     counter += 1\n#     if counter == 500:\n#         print(\"500 work items done!\")\n#         counter = 0\n```\n\nComputation takes a while. We will write the data to the SQL-Server so we don't have to compute them every time.\n\n\n```python\n# import sqlalchemy\n# engine = sqlalchemy.create_engine(\"XXX\")\n# con = engine.connect()\n# # tosql = res_df.reset_index().rename(columns={\"index\":\"work_item\"})\n# # tosql.to_sql(name=\"resource_employment_rate\", con=con)\n# res_df = pd.read_sql_table(table_name=\"resource_employment_rate\", con=con)\n# con.close()\n```\n\n\n```python\nfig, ax = plt.subplots(3,1, figsize=(12,10), sharex=True, constrained_layout=True)\nres_df[\"x_emp\"].plot(ax=ax[0], label=\"x_emp\")\nax[0].set_title(\"Employment rate\")\nax[0].legend()\nres_df[\"x_exp\"].plot(ax=ax[1], label=\"x_exp\")\nax[1].set_title(\"Experience rate\")\nax[1].legend()\nres_df[\"x_load\"].plot(ax=ax[2], label=\"x_load\")\nax[2].set_title(\"Workload rate\")\nax[2].legend()\nplt.show()\n```\n\nWe want to add another feature regarding to the difficulty of a work item. Resources have days where they are closing a lot of items at once. But there are always some items that are skipping these 'closing days' so we assume that these items have a higher difficulty.\n\nWe define a closing day as\n\\begin{equation}\nt^{er}_{close} =\n\\begin{cases} \n      1 & \\frac{\\sum{w^{er}_{closed}(t)}}{\\sum{w^{er}_{open}(t)}} \\geq 0.25 \\\\\n      0 & else \n\\end{cases}\n\\end{equation}\n\nSo if 30% of the open tickets the resource holds are closed it's a closing day. We define than the difficulty of a work item\n\n\\begin{equation}\nx^{wi}_{diff} = \\sum_{t}{\\sum_{er}{t^{er}_{close}}}\n\\end{equation}\n\nThe difficulty is the sum of all closing days a work item skipped for every resource that worked on it.\n\nNow let's implement this.\n\n\n```python\ndef calc_t_close(times_closed, resource):\n    res_df = times_closed[times_closed[\"current_resource\"] == resource]\n#     We calculate the number of items dropped at a drop date\n    t_close = pd.DataFrame(res_df[\"drop_date\"].value_counts()).reset_index().rename(columns={\"index\":\"drop_date\",\n                                                                                             \"drop_date\":\"w_closed\"})\n#     We calculate the work items that are open over a drop date\n    res_df[\"w_open\"] = res_df[\"drop_date\"].apply(lambda t: res_df[(res_df[\"drop_date\"].apply(lambda x: x>=t)) & \n                                                           (res_df[\"receive_date\"].apply(lambda x: x<=t))].shape[0])\n#     Now we merge them together and calculate the percentage\n    t_close = pd.merge(t_close, res_df[[\"drop_date\", \"w_open\"]].drop_duplicates())\n    t_close.loc[:, \"percentage_closed\"] = t_close[\"w_closed\"] / t_close[\"w_open\"].apply(lambda x: 1 if x==0 else x)\n    t_close.loc[:, \"t_close\"] = t_close[\"percentage_closed\"].apply(lambda x: 1 if x >= 0.25 else 0)\n    close_days = t_close[t_close[\"t_close\"] == 1][\"drop_date\"].values\n    return close_days\n```\n\n\n```python\ntimes.loc[:, \"x_diff\"] = 0\nfor resource in times[\"current_resource\"].unique():\n    close_days = calc_t_close(times_closed, resource)\n    res_df = times[times[\"current_resource\"] == resource]\n    for x, y in res_df.iterrows():\n        difficulty = len([e for e in close_days if ((y[\"receive_date\"]<e)&~(y[\"drop_date\"]<=e))])\n        times.loc[x, \"x_diff\"] = difficulty\n```\n\n\n```python\ndifficulty_df = pd.DataFrame(times.groupby(\"work_item\")[\"x_diff\"].sum()).reset_index()\nplot_df = pd.merge(total_times.dropna(), difficulty_df).drop_duplicates()\ntotal_times_c = compute_work_item_times(set_end_date(data, \"2018-03-31\"))\nplot_df_open = pd.merge(total_times_c[total_times_c.work_item.isin(open_wis)], difficulty_df).drop_duplicates(\"work_item\")\n```\n\n\n```python\nplt.figure(figsize=(15,8))\nplt.scatter(x=plot_df.x_diff, y=plot_df.duration_in_days, s=4, color='g', label=\"closed tickets\")\nplt.scatter(x=plot_df_open.x_diff, y=plot_df_open.duration_in_days, s=4, color='r', label=\"open tickets\")\nplt.title(\"Difficulty corresponding to duration\")\nplt.xlabel(\"difficulty\")\nplt.ylabel(\"duration in days\")\nplt.legend()\nplt.show()\n```\n\nNow the difficulty is only resource related and has a wide range of values. We should think about a better scale for that.\n\n\n```python\n\n```\n", "meta": {"hexsha": "20c5a238c3524074bf4f743f890470cd8fa99bab", "size": 204757, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/15_resource_measurement.ipynb", "max_stars_repo_name": "Ijusttyped/it_support_tickets", "max_stars_repo_head_hexsha": "d105fe5f7990a5be96f077e5636b0a2588bb5b48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/15_resource_measurement.ipynb", "max_issues_repo_name": "Ijusttyped/it_support_tickets", "max_issues_repo_head_hexsha": "d105fe5f7990a5be96f077e5636b0a2588bb5b48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-05-28T11:57:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T02:06:01.000Z", "max_forks_repo_path": "notebooks/15_resource_measurement.ipynb", "max_forks_repo_name": "Ijusttyped/it_support_tickets", "max_forks_repo_head_hexsha": "d105fe5f7990a5be96f077e5636b0a2588bb5b48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 423.0516528926, "max_line_length": 98908, "alphanum_fraction": 0.9345956426, "converted": true, "num_tokens": 2725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.06560483243507391, "lm_q1q2_score": 0.03228992017049421}}
{"text": "```python\nfrom LOTlib3.Grammar import Grammar\nfrom math import log\nfrom LOTlib3.Hypotheses.LOTHypothesis import LOTHypothesis\nfrom LOTlib3.DataAndObjects import FunctionData\nfrom LOTlib3.TopN import TopN\nfrom LOTlib3.Samplers.MetropolisHastings import MetropolisHastingsSampler\nfrom LOTlib3.Eval import primitive\n```\n\n\n```python\nimport numpy as np\nimport pandas as pd\n\nimport os\nimport json\nimport time\nimport copy\n\nfrom IPython.display import clear_output\nfrom IPython.display import HTML\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nfrom matplotlib import colors\n\nfrom PIL import Image, ImageDraw\nfrom IPython.display import Image as Im\nfrom itertools import permutations, combinations\nfrom sympy.utilities.iterables import multiset_permutations\n\n# from skimage.segmentation import flood, flood_fill\n\n%matplotlib inline\n```\n\n\n```python\n# define solver\nclass ARCSolver:\n    def __init__(self, task_filename):\n        # load task and extract input and output pairs\n        self.task_filename = task_filename\n        self.task = self.load_task(task_filename)\n        self.train_inputs, self.train_outputs, self.test_inputs, self.test_outputs = \\\n            self.extract_io_pairs()\n        self.test_pred = np.zeros((5, 5))\n        self.test_pred_height, self.test_pred_width = self.test_pred.shape\n        \n        self.solved = False  # have we solved the task yet?\n        self.selected_colour = 0\n        self.clipboard = None\n        self.description = ''\n        \n        # variables for plotting\n        self.cmap = colors.ListedColormap(\n            ['#000000', '#0074D9','#FF4136','#2ECC40','#FFDC00',\n             '#AAAAAA', '#F012BE', '#FF851B', '#7FDBFF', '#870C25'])\n        self.colour_to_num = {'black': 0, 'blue': 1, 'red': 2, 'green': 3, 'yellow': 4,\n                             'grey': 5, 'magenta': 6, 'orange': 7, 'light_blue': 8, \n                             'maroon': 9}\n        self.num_to_colour = {0: 'black', 1: 'blue', 2: 'red', 3: 'green', 4: 'yellow',\n                             5: 'grey', 6: 'magneta', 7: 'orange', 8: 'light_blue',\n                             9: 'maroon'}\n\n        \n    def load_task(self, task_filename):\n        with open(task_filename, 'r') as f:\n            task = json.load(f)    \n        return task\n\n    def plot_task(self):\n        \"\"\"\n        Plots the first train and test pairs of a specified task,\n        using same color scheme as the ARC app\n        \"\"\"\n        norm = colors.Normalize(vmin=0, vmax=9)\n        n_train = len(self.task['train'])\n        fig, axs = plt.subplots(n_train+1, 2, figsize=(10, 10))\n        for i in range(n_train):\n            axs[i, 0].imshow(self.task['train'][i]['input'], cmap=self.cmap, norm=norm)\n            axs[i, 0].axis('off')\n            axs[i, 0].set_title('Train Input')\n            axs[i, 1].imshow(self.task['train'][i]['output'], cmap=self.cmap, norm=norm)\n            axs[i, 1].axis('off')\n            axs[i, 1].set_title('Train Output')\n        axs[n_train, 0].imshow(self.task['test'][0]['input'], cmap=self.cmap, norm=norm)\n        axs[n_train, 0].axis('off')\n        axs[n_train, 0].set_title('Test Input')\n        axs[n_train, 1].imshow(self.task['test'][0]['output'], cmap=self.cmap, norm=norm)\n        axs[n_train, 1].axis('off')\n        axs[n_train, 1].set_title('Test Output')\n        plt.tight_layout()\n        plt.show()\n    \n    def plot_grid(self, grid):\n        \"\"\"\n        Plots a single grid\n        \"\"\"\n        #plt.clf()\n\n        #plt.draw()\n        #display(plt)\n        \n\n    def plot_grids(self, grids):\n        \"\"\"\n        Plots a list of grids\n        \"\"\"\n        n_grids = len(grids)\n        norm = colors.Normalize(vmin=0, vmax=9)\n        fig, axs = plt.subplots(1, n_grids, figsize=(6, 6), squeeze=False)\n        for i in range(n_grids):\n            axs[0, i].imshow(grids[i], cmap=self.cmap, norm=norm)\n            axs[0, i].axis('off')\n        plt.tight_layout()\n        plt.show()\n    \n    def extract_io_pairs(self):\n        train = self.task['train']\n        test = self.task['test']\n        n_train = len(train)\n        n_test = len(test)\n\n        train_inputs = np.array([train[i]['input'] for i in range(n_train)])\n        train_outputs = np.array([train[i]['output'] for i in range(n_train)])\n        test_inputs = np.array([test[i]['input'] for i in range(n_test)])\n        test_outputs = np.array([test[i]['output'] for i in range(n_test)])\n\n        return train_inputs, train_outputs, test_inputs, test_outputs\n    \n    def copy_from_input(self):\n        # copy over the first test input\n        self.test_pred = self.test_inputs[0].copy()\n        self.test_pred_height, self.test_pred_width = self.test_inputs[0].shape\n        self.description = 'copy from input'\n    \n    def reset(self):\n        # resets grid to all zeros with size of the grid based on current settings\n        self.test_pred = np.zeros((self.test_pred_height, self.test_pred_width))\n        self.description = 'reset'\n    \n    def resize(self):\n        # resizes the grid\n        prev_test_pred = self.test_pred.copy()\n        prev_test_pred_width = self.test_pred_width\n        prev_test_pred_height = self.test_pred_height\n\n        # sample new grid size\n        new_test_pred_width = np.random.choice(np.arange(1, 5))\n        new_test_pred_height = np.random.choice(np.arange(1, 5))\n        new_test_pred = np.zeros((new_test_pred_height, new_test_pred_width))\n        \n        # copy over values\n        for i in range(min(prev_test_pred_height, new_test_pred_height)):\n            for j in range(min(prev_test_pred_width, new_test_pred_width)):\n                new_test_pred[i, j] = prev_test_pred[i, j]\n            \n        self.test_pred = new_test_pred\n        self.test_pred_width = new_test_pred_width\n        self.test_pred_height = new_test_pred_height\n        self.description = f'resize: ({new_test_pred_height}, {new_test_pred_width})'\n        \n    def change_colour(self):\n        self.selected_colour = np.random.choice(np.arange(10))\n        self.description = f'change colour: {self.num_to_colour[self.selected_colour]}'\n    \n    def edit(self):\n        # select a random location\n        x = np.random.choice(np.arange(self.test_pred_width))\n        y = np.random.choice(np.arange(self.test_pred_height))\n        self.test_pred[y, x] = self.selected_colour\n        self.description = f'edit: ({y}, {x})'\n    \n    def edit_rectangle(self):\n        # selects a randomly selected region and changes the colour of all of the cells\n        x_start = np.random.choice(np.arange(self.test_pred_width))\n        x_end = np.random.choice(np.arange(x_start+1, self.test_pred_width+1))\n        y_start = np.random.choice(np.arange(self.test_pred_height))\n        y_end = np.random.choice(np.arange(y_start+1, self.test_pred_height+1))\n        \n        # select a new colour\n        self.selected_colour = np.random.choice(np.arange(10))\n        self.test_pred[y_start:y_end, x_start:x_end] = self.selected_colour\n        self.description = f'edit rectangle from ({y_start}:{y_end}, {x_start}:{x_end}) to {self.selected_colour}'\n    \n    def copy(self):\n        # copies a randomly selected region\n        x_start = np.random.choice(np.arange(self.test_pred_width))\n        x_end = np.random.choice(np.arange(x_start+1, self.test_pred_width+1))\n        y_start = np.random.choice(np.arange(self.test_pred_height))\n        y_end = np.random.choice(np.arange(y_start+1, self.test_pred_height+1))\n        \n        self.clipboard = self.test_pred[y_start:y_end, x_start:x_end].copy()\n        self.description = f'copy from ({y_start}:{y_end}, {x_start}:{x_end})'\n        #print(f'clipboard: {self.clipboard}')\n    \n    def paste(self):\n        # pastes clipboard value into randomly selected location\n        clipboard_height, clipboard_width = self.clipboard.shape\n        x_start = np.random.choice(np.arange(self.test_pred_width))\n        x_width = min(clipboard_width, self.test_pred_width - x_start) \n        y_start = np.random.choice(np.arange(self.test_pred_height))\n        y_height = min(clipboard_height, self.test_pred_height - y_start)\n        \n        self.test_pred[y_start:y_start+y_height, x_start:x_start+x_width] = self.clipboard[:y_height, :x_width] \n        self.description = f'pasting from ({y_start}:{y_start+y_height}, {x_start}:{x_start+x_width})'\n    \n    def flood_fill(self):\n        # flood fill at a random location\n        x = np.random.choice(self.test_pred_width)\n        y = np.random.choice(self.test_pred_height)\n        self.test_pred = flood_fill(self.test_pred, (y, x), \n                                    self.selected_colour)\n        self.description = f'flood fill from: ({y}, {x})'\n     \n    def solve(self):\n        fig = plt.figure(figsize=(6, 6))\n        plt.ion()\n        plt.show()\n        norm = colors.Normalize(vmin=0, vmax=9)\n                \n        while not self.solved:\n            clear_output()\n            # randomly select available function\n            if np.random.choice([0, 1]) == 0:\n                self.change_colour()\n            else:\n                self.edit()\n\n            plt.imshow(self.test_pred, cmap=self.cmap, norm=norm)\n            plt.axis('off')\n            plt.tight_layout()\n            plt.pause(1)\n                        \n            # check accuracy\n            \n            \n```\n\n\n```python\n# displaying a single grid\ndef DisplayGrid(grid):\n    grid = np.asarray(grid)\n    nrows = len(grid[:,0])\n    ncols = len(grid[0,:])\n    height, width = nrows*50, ncols*50\n    image = Image.new(size=(width,height),mode='RGB',color=(255,255,255))\n    draw = ImageDraw.Draw(image)\n    r = 0 \n    for row in grid:\n        c = 0\n        for col in row:\n            draw.rectangle(xy=[c*50,r*50,(c+1)*50,(r+1)*50], fill=colorMap[np.abs(grid[r][c])])\n            c += 1\n        r += 1\n    for i in range(ncols):\n        draw.line([(i+1)*50,0,(i+1)*50,height],fill=\"grey\")\n    for i in range(nrows):\n        draw.line([0,(i+1)*50,width,(i+1)*50],fill=\"grey\")\n    display(image)\n```\n\n\n```python\ncolorMap = {0:\"black\",1:\"blue\",2:\"red\", 3:\"green\",4:\"yellow\",5:\"grey\",6:\"magenta\",7:\"orange\",8:\"cyan\",9:\"brown\"}\n```\n\n\n```python\ntraining_path = \"/Users/aysjajohnson/Desktop/ARC-master/data/training/\"\nsolver = ARCSolver(task_filename=os.path.join(training_path, '0ca9ddb6.json'))\nsolver.plot_grids(solver.train_inputs)\nsolver.plot_grids(solver.train_outputs)\n```\n\n\n```python\nb = 0.05\n```\n\nHow do you get LOTlib to start with a hypothesis and expand from there? This is awkward right now -- you have to add the input as a rule...\n\nIt also doesn't really understand how to compile lists of lists, just numbers.. I think we'd need to change the backend a bit\n\n\n```python\n# intializing basic hypothesis, will edit later\nclass ARCHypothesis(LOTHypothesis):\n    def __init__(self, **kwargs):\n        LOTHypothesis.__init__(self, grammar=grammar, display=\"lambda grid: %s\", **kwargs)\n        \n    def __call__(self, *args):\n        try:\n            # try to do it from the superclass\n            return LOTHypothesis.__call__(self, *args)\n        except ZeroDivisionError:\n            # and if we get an error, return nan\n            return float(\"nan\")\n\n    def compute_single_likelihood(self, datum):\n        # for each correct pixel, add log(1), for each incorrect, add log(exp(-b))\n        ll = 0\n        input_grid = self(*datum.input)\n        output_grid = datum.output\n        # assuming input and output are the same size for now\n        height, width = len(input_grid[:,0]), len(input_grid[0,:])\n        for i in range(height):\n            for j in range(width):\n                if input_grid[i][j] == output_grid[i][j]:\n                    ll += log(1)\n                elif input_grid[i][j] == 0 and output_grid[i][j] != 0:\n                    ll += log(0.1)\n                else:\n                    ll += log(0.05)\n        # print(self.value, ll)\n        return ll\n        \n    def display_hypothesis(self):\n        return self.value\n```\n\n\n```python\ninputs = solver.train_inputs\noutputs = solver.train_outputs\nprint([inputs[0]])\n```\n\n    [array([[0, 0, 0, 0, 0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0, 0, 0, 0, 0],\n           [0, 0, 2, 0, 0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0, 0, 1, 0, 0],\n           [0, 0, 0, 0, 0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0, 0, 0, 0, 0]])]\n\n\n\n```python\ndata = [FunctionData(input=[inputs[0]],output=outputs[0])]\nprint(data)\n```\n\n    [<[[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]] -> [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]>]\n\n\n\n```python\n@primitive\ndef red_squares_(grid):\n    grid = copy.deepcopy(grid)\n    height, width = len(grid[:,0]), len(grid[0,:])\n    lst = []\n    for i in range(height):\n        for j in range(width):\n            if grid[i][j] == 2:\n                lst.append((i,j))\n    return lst\n\n@primitive\ndef blue_squares_(grid):\n    grid = copy.deepcopy(grid)\n    height, width = len(grid[:,0]), len(grid[0,:])\n    lst = []\n    for i in range(height):\n        for j in range(width):\n            if grid[i][j] == 1:\n                lst.append((i,j))\n    return lst\n\n@primitive\ndef diag_(lst, grid):\n    grid = copy.deepcopy(grid)\n    height, width = len(grid[:,0]), len(grid[0,:])\n    diag_lst = []\n    for tup in lst:\n        # check whether diagonals exist on board constraints\n        N, E, S, W = tup[0]-1, tup[1] + 1, tup[0] + 1, tup[1] -1\n        if  N > 0 and S < height-1 and W > 0 and E < width - 1:\n            diag_lst.extend([(N,W),(N,E),(S,E),(S,W)])\n    return diag_lst\n\n@primitive\ndef cross_(lst, grid):\n    grid = copy.deepcopy(grid)\n    height, width = len(grid[:,0]), len(grid[0,:])\n    cross_lst = []\n    for tup in lst:\n        # check whether diagonals exist on board constraints\n        N, E, S, W = tup[0]-1, tup[1] + 1, tup[0] + 1, tup[1] -1\n        if  N > 0 and S < height-1 and W > 0 and E < width - 1:\n            cross_lst.extend([(N,tup[1]),(tup[0],E),(S,tup[1]),(tup[0],W)])\n    return cross_lst\n\n@primitive\ndef color_(lst, clr):\n    return {k:clr for k in lst}\n\n@primitive\ndef paint_(dict_, grid):\n    grid = copy.deepcopy(grid)\n    height, width = len(grid[:,0]), len(grid[0,:])\n    for coord in dict_.keys():\n        grid[coord[0]][coord[1]] = dict_[coord]\n    return grid\n```\n\n\n```python\n# initializing grammar\ngrammar = Grammar(start='GRID')\n\n# adding production rules\ngrammar.add_rule('LIST', 'red_squares_', ['GRID'], 1.0)\ngrammar.add_rule('LIST', 'blue_squares_', ['GRID'], 1.0)\ngrammar.add_rule('LIST', 'diag_', ['LIST', 'GRID'], 1.0)\ngrammar.add_rule('LIST', 'cross_', ['LIST', 'GRID'], 1.0)\ngrammar.add_rule('DICT', 'color_', ['LIST','COLOR'], 1.0)\ngrammar.add_rule('GRID', 'paint_', ['DICT', 'GRID'], 1.0)\n\n# adding numbers 0 through 9 as terminals\n# for n in range(10):\n#     grammar.add_rule('COLOR', str(n), None, 1.0)\n\n# right now just consider 4 and 7 to see if this makes the right solution come up\ngrammar.add_rule('COLOR', str(4), None, 1.0)\ngrammar.add_rule('COLOR', str(7), None, 1.0)\n\ngrammar.add_rule('GRID', 'grid', None, 3.0)\n```\n\n\n\n\n    GRID -> grid\tw/ p=3.0\n\n\n\n\n```python\nrs = red_squares_(inputs[0])\n```\n\n\n```python\ndiag_(rs, inputs[0])\n```\n\n\n\n\n    [(2, 1), (2, 3), (4, 3), (4, 1)]\n\n\n\n\n```python\ngrammar.display_rules()\n```\n\n    LIST -> red_squares_['GRID']\tw/ p=1.0\n    LIST -> blue_squares_['GRID']\tw/ p=1.0\n    LIST -> diag_['LIST', 'GRID']\tw/ p=1.0\n    LIST -> cross_['LIST', 'GRID']\tw/ p=1.0\n    DICT -> color_['LIST', 'COLOR']\tw/ p=1.0\n    GRID -> paint_['DICT', 'GRID']\tw/ p=1.0\n    GRID -> grid\tw/ p=3.0\n    COLOR -> 0\tw/ p=1.0\n    COLOR -> 1\tw/ p=1.0\n    COLOR -> 2\tw/ p=1.0\n    COLOR -> 3\tw/ p=1.0\n    COLOR -> 4\tw/ p=1.0\n    COLOR -> 5\tw/ p=1.0\n    COLOR -> 6\tw/ p=1.0\n    COLOR -> 7\tw/ p=1.0\n    COLOR -> 8\tw/ p=1.0\n    COLOR -> 9\tw/ p=1.0\n\n\n\n```python\nh = ARCHypothesis()\nprint(h)\n```\n\n    lambda grid: paint_(color_(blue_squares_(grid), 7), paint_(color_(red_squares_(grid), 4), grid))\n\n\n\n```python\nh(inputs[0])\n```\n\n\n\n\n    array([[0, 0, 0, 0, 0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0, 0, 0, 0, 0],\n           [0, 0, 4, 0, 0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0, 0, 7, 0, 0],\n           [0, 0, 0, 0, 0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0, 0, 0, 0, 0]])\n\n\n\n\n```python\nDisplayGrid(h(inputs[0]))\n```\n\n\n```python\nDisplayGrid(paint_(color_(diag_(red_squares_(inputs[0]),inputs[0]),4),inputs[0]))\n```\n\n\n```python\n# problem: MHS considers the class to have no arguments. Current workaround, globally declare num_vars before running\n\ntn = TopN(N=10) # store the top N\n\nh0 = ARCHypothesis()\nprint(h0)\n\nfor h in MetropolisHastingsSampler(h0, data, steps=1000):\n    tn.add(h)\n\nfor h in tn.get_all(sorted=True):\n    print(h.posterior_score, h.likelihood,  h.prior, h)\n```\n\n\n```python\nprint(h)\n```\n\n    lambda grid: grid\n\n\n\n```python\nprint(inputs[0])\n```\n\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "98f920b4365436e4251c0f594da75c9ad8be8e22", "size": 99103, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/.ipynb_checkpoints/ARC LOTlib-checkpoint.ipynb", "max_stars_repo_name": "aysjajohnson/ARC", "max_stars_repo_head_hexsha": "3650acfa040a2249ea8f1acebf0dc3bf6d21bf6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/.ipynb_checkpoints/ARC LOTlib-checkpoint.ipynb", "max_issues_repo_name": "aysjajohnson/ARC", "max_issues_repo_head_hexsha": "3650acfa040a2249ea8f1acebf0dc3bf6d21bf6f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 32, "max_issues_repo_issues_event_min_datetime": "2020-04-21T18:43:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-27T18:19:34.000Z", "max_forks_repo_path": "notebooks/.ipynb_checkpoints/ARC LOTlib-checkpoint.ipynb", "max_forks_repo_name": "aysjajohnson/ARC", "max_forks_repo_head_hexsha": "3650acfa040a2249ea8f1acebf0dc3bf6d21bf6f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.7833056938, "max_line_length": 2284, "alphanum_fraction": 0.5988012472, "converted": true, "num_tokens": 5416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.06656918943346386, "lm_q1q2_score": 0.032244789588031765}}
{"text": "```python\n!pip install qiskit\n!pip install qiskit-machine-learning\n```\n\n    Collecting qiskit\n      Downloading qiskit-0.33.0.tar.gz (13 kB)\n    Collecting qiskit-terra==0.19.0\n      Downloading qiskit_terra-0.19.0-cp37-cp37m-manylinux2010_x86_64.whl (6.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.4 MB 4.0 MB/s \n    \u001b[?25hCollecting qiskit-aer==0.9.1\n      Downloading qiskit_aer-0.9.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (17.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 17.9 MB 559 kB/s \n    \u001b[?25hCollecting qiskit-ibmq-provider==0.18.1\n      Downloading qiskit_ibmq_provider-0.18.1-py3-none-any.whl (237 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 237 kB 71.4 MB/s \n    \u001b[?25hCollecting qiskit-ignis==0.7.0\n      Downloading qiskit_ignis-0.7.0-py3-none-any.whl (200 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 200 kB 59.7 MB/s \n    \u001b[?25hRequirement already satisfied: scipy>=1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.9.1->qiskit) (1.4.1)\n    Requirement already satisfied: numpy>=1.16.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.9.1->qiskit) (1.19.5)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.1->qiskit) (2.8.2)\n    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.1->qiskit) (1.24.3)\n    Collecting requests-ntlm>=1.1.0\n      Downloading requests_ntlm-1.1.0-py2.py3-none-any.whl (5.7 kB)\n    Collecting websocket-client>=1.0.1\n      Downloading websocket_client-1.2.3-py3-none-any.whl (53 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 53 kB 1.8 MB/s \n    \u001b[?25hRequirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.1->qiskit) (2.23.0)\n    Collecting retworkx>=0.8.0\n      Downloading retworkx-0.10.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.4 MB 54.3 MB/s \n    \u001b[?25hRequirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ignis==0.7.0->qiskit) (57.4.0)\n    Collecting tweedledum<2.0,>=1.1\n      Downloading tweedledum-1.1.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (943 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 943 kB 54.8 MB/s \n    \u001b[?25hCollecting ply>=3.10\n      Downloading ply-3.11-py2.py3-none-any.whl (49 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 49 kB 5.6 MB/s \n    \u001b[?25hCollecting scipy>=1.0\n      Downloading scipy-1.7.3-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (38.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 38.1 MB 1.1 MB/s \n    \u001b[?25hCollecting symengine>=0.8\n      Downloading symengine-0.8.1-cp37-cp37m-manylinux2010_x86_64.whl (38.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 38.2 MB 1.2 MB/s \n    \u001b[?25hRequirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.0->qiskit) (0.3.4)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.0->qiskit) (5.4.8)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.0->qiskit) (1.7.1)\n    Collecting stevedore>=3.0.0\n      Downloading stevedore-3.5.0-py3-none-any.whl (49 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 49 kB 5.6 MB/s \n    \u001b[?25hCollecting python-constraint>=1.4\n      Downloading python-constraint-1.4.0.tar.bz2 (18 kB)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.8.0->qiskit-ibmq-provider==0.18.1->qiskit) (1.15.0)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.1->qiskit) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.1->qiskit) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.1->qiskit) (2021.10.8)\n    Collecting cryptography>=1.3\n      Downloading cryptography-36.0.0-cp36-abi3-manylinux_2_24_x86_64.whl (3.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.6 MB 60.4 MB/s \n    \u001b[?25hCollecting ntlm-auth>=1.0.2\n      Downloading ntlm_auth-1.5.0-py2.py3-none-any.whl (29 kB)\n    Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.1->qiskit) (1.15.0)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.1->qiskit) (2.21)\n    Collecting pbr!=2.1.0,>=2.0.0\n      Downloading pbr-5.8.0-py2.py3-none-any.whl (112 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 112 kB 71.0 MB/s \n    \u001b[?25hRequirement already satisfied: importlib-metadata>=1.7.0 in /usr/local/lib/python3.7/dist-packages (from stevedore>=3.0.0->qiskit-terra==0.19.0->qiskit) (4.8.2)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=1.7.0->stevedore>=3.0.0->qiskit-terra==0.19.0->qiskit) (3.6.0)\n    Requirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=1.7.0->stevedore>=3.0.0->qiskit-terra==0.19.0->qiskit) (3.10.0.2)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra==0.19.0->qiskit) (1.2.1)\n    Building wheels for collected packages: qiskit, python-constraint\n      Building wheel for qiskit (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for qiskit: filename=qiskit-0.33.0-py3-none-any.whl size=11763 sha256=7b20655b4b246c3c40dab4d04123c929fbd370f9961fa4425422e89928476ec9\n      Stored in directory: /root/.cache/pip/wheels/d4/60/ef/c49ae113df02818c4ade5fb6e2e89bb928625412eda0bb25f5\n      Building wheel for python-constraint (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for python-constraint: filename=python_constraint-1.4.0-py2.py3-none-any.whl size=24081 sha256=bc599173af47dd861b7e2c523ed208f0c110c69756d0834848052bc428ce1fbc\n      Stored in directory: /root/.cache/pip/wheels/07/27/db/1222c80eb1e431f3d2199c12569cb1cac60f562a451fe30479\n    Successfully built qiskit python-constraint\n    Installing collected packages: pbr, tweedledum, symengine, stevedore, scipy, retworkx, python-constraint, ply, ntlm-auth, cryptography, websocket-client, requests-ntlm, qiskit-terra, qiskit-ignis, qiskit-ibmq-provider, qiskit-aer, qiskit\n      Attempting uninstall: scipy\n        Found existing installation: scipy 1.4.1\n        Uninstalling scipy-1.4.1:\n          Successfully uninstalled scipy-1.4.1\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Successfully installed cryptography-36.0.0 ntlm-auth-1.5.0 pbr-5.8.0 ply-3.11 python-constraint-1.4.0 qiskit-0.33.0 qiskit-aer-0.9.1 qiskit-ibmq-provider-0.18.1 qiskit-ignis-0.7.0 qiskit-terra-0.19.0 requests-ntlm-1.1.0 retworkx-0.10.2 scipy-1.7.3 stevedore-3.5.0 symengine-0.8.1 tweedledum-1.1.1 websocket-client-1.2.3\n    Collecting qiskit-machine-learning\n      Downloading qiskit_machine_learning-0.2.1-py3-none-any.whl (96 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 96 kB 3.1 MB/s \n    \u001b[?25hRequirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-machine-learning) (57.4.0)\n    Requirement already satisfied: scipy>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-machine-learning) (1.7.3)\n    Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from qiskit-machine-learning) (1.19.5)\n    Requirement already satisfied: fastdtw in /usr/local/lib/python3.7/dist-packages (from qiskit-machine-learning) (0.3.4)\n    Requirement already satisfied: scikit-learn>=0.20.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-machine-learning) (1.0.1)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-machine-learning) (5.4.8)\n    Requirement already satisfied: qiskit-terra>=0.18.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-machine-learning) (0.19.0)\n    Requirement already satisfied: stevedore>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.18.0->qiskit-machine-learning) (3.5.0)\n    Requirement already satisfied: retworkx>=0.10.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.18.0->qiskit-machine-learning) (0.10.2)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.18.0->qiskit-machine-learning) (1.7.1)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.18.0->qiskit-machine-learning) (2.8.2)\n    Requirement already satisfied: symengine>=0.8 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.18.0->qiskit-machine-learning) (0.8.1)\n    Requirement already satisfied: tweedledum<2.0,>=1.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.18.0->qiskit-machine-learning) (1.1.1)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.18.0->qiskit-machine-learning) (0.3.4)\n    Requirement already satisfied: ply>=3.10 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.18.0->qiskit-machine-learning) (3.11)\n    Requirement already satisfied: python-constraint>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.18.0->qiskit-machine-learning) (1.4.0)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.8.0->qiskit-terra>=0.18.0->qiskit-machine-learning) (1.15.0)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.20.0->qiskit-machine-learning) (1.1.0)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.20.0->qiskit-machine-learning) (3.0.0)\n    Requirement already satisfied: importlib-metadata>=1.7.0 in /usr/local/lib/python3.7/dist-packages (from stevedore>=3.0.0->qiskit-terra>=0.18.0->qiskit-machine-learning) (4.8.2)\n    Requirement already satisfied: pbr!=2.1.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from stevedore>=3.0.0->qiskit-terra>=0.18.0->qiskit-machine-learning) (5.8.0)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=1.7.0->stevedore>=3.0.0->qiskit-terra>=0.18.0->qiskit-machine-learning) (3.6.0)\n    Requirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=1.7.0->stevedore>=3.0.0->qiskit-terra>=0.18.0->qiskit-machine-learning) (3.10.0.2)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra>=0.18.0->qiskit-machine-learning) (1.2.1)\n    Installing collected packages: qiskit-machine-learning\n    Successfully installed qiskit-machine-learning-0.2.1\n\n\n\n```python\nimport numpy as np\n\n# Importing standard Qiskit libraries\nimport qiskit\nfrom qiskit import QuantumCircuit, transpile, Aer, IBMQ\nfrom qiskit.tools.jupyter import *\nfrom qiskit.visualization import *\n#from ibm_quantum_widgets import *\nfrom qiskit.providers.aer import QasmSimulator\n\n# Loading your IBM Quantum account(s)\n#provider = IBMQ.load_account()\n```\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom qiskit import Aer, QuantumCircuit\nfrom qiskit.opflow import Z, I, StateFn\nfrom qiskit.utils import QuantumInstance\nfrom qiskit.circuit import Parameter\nfrom qiskit.circuit.library import RealAmplitudes, ZZFeatureMap\nfrom qiskit.algorithms.optimizers import COBYLA, L_BFGS_B\n\nfrom qiskit_machine_learning.neural_networks import TwoLayerQNN, CircuitQNN\nfrom qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier, VQC\nfrom qiskit_machine_learning.algorithms.regressors import NeuralNetworkRegressor, VQR\n\nfrom typing import Union\n\nfrom qiskit_machine_learning.exceptions import QiskitMachineLearningError\n\nfrom IPython.display import clear_output\nquantum_instance = QuantumInstance(Aer.get_backend('aer_simulator'), shots=1024)\n```\n\n\n```python\n'''\nnum_samples = 20\neps = 0.2\nlb, ub = -np.pi, np.pi\nX_ = np.linspace(lb, ub, num=50).reshape(50, 1)\nf = lambda x: np.sin(x)\n\nX = (ub - lb)*np.random.rand(num_samples, 1) + lb\ny = f(X[:,0]) + eps*(2*np.random.rand(num_samples)-1)\n\nprint(X)\nprint(y)\n\nplt.plot(X_, f(X_), 'r--')\nplt.plot(X, y, 'bo')\nplt.show()\n'''\n```\n\n\n\n\n    \"\\nnum_samples = 20\\neps = 0.2\\nlb, ub = -np.pi, np.pi\\nX_ = np.linspace(lb, ub, num=50).reshape(50, 1)\\nf = lambda x: np.sin(x)\\n\\nX = (ub - lb)*np.random.rand(num_samples, 1) + lb\\ny = f(X[:,0]) + eps*(2*np.random.rand(num_samples)-1)\\n\\nprint(X)\\nprint(y)\\n\\nplt.plot(X_, f(X_), 'r--')\\nplt.plot(X, y, 'bo')\\nplt.show()\\n\"\n\n\n\n\n```python\n# construct simple feature map\nparam_x = Parameter('x')\nfeature_map = QuantumCircuit(1, name='fm')\nfeature_map.ry(param_x, 0)\nprint(feature_map)\n\n# construct simple ansatz\nparam_y = Parameter('y')\nansatz = QuantumCircuit(1, name='vf')\nansatz.ry(param_y, 0)\nprint(ansatz)\n\n# construct QNN\nregression_opflow_qnn = TwoLayerQNN(1, feature_map, ansatz, quantum_instance=quantum_instance)\n```\n\n       \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    q: \u2524 Ry(x) \u251c\n       \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n       \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    q: \u2524 Ry(y) \u251c\n       \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\n\n\n```python\n# callback function that draws a live plot when the .fit() method is called\nobjective_func_vals = []\ndef callback_graph(weights, obj_func_eval):\n    clear_output(wait=True)\n    objective_func_vals.append(obj_func_eval)\n    plt.title(\"Objective function value against iteration\")\n    plt.xlabel(\"Iteration\")\n    plt.ylabel(\"Objective function value\")\n    plt.plot(range(len(objective_func_vals)), objective_func_vals)\n    plt.show()\n```\n\n\n```python\n# construct the regressor from the neural network\nregressor = NeuralNetworkRegressor(neural_network=regression_opflow_qnn,\n                                   loss='l2',\n                                   optimizer=L_BFGS_B(),\n                                   callback=callback_graph)\n```\n\n\n```python\n#from IPython.core.debugger import set_trace\n```\n\n\n```python\n#import sys\n'''\nsys.path.append(\"../Qiskit_Dynamic_Modelling\")\nsys.path.append(\"./modelQ\")\nsys.path.append(\"./dynamicsQ\")\n'''\nsys.path.append(\"./sample_data\")\nfrom dataloader import *\ntrain_data = np.load('/content/sample_data/train_dataset.npz')\ntrain_inputs = train_data[\"input\"]\ntrain_labels = train_data[\"labels\"]\nX_inputs = train_inputs[:50000]\ny_labels = train_labels[:50000]\n#train_dataset = DynamicsDataset(train_inputs, train_labels)\ntrain_dataset = DynamicsDataset(X_inputs, y_labels)\n\ntrain_dataloader = torch.utils.data.DataLoader(train_dataset,\n                                                 batch_size=1,\n                                                 shuffle=True,\n                                                 collate_fn=DynamicsDataset.collate_fn,\n                                                 pin_memory=True,\n                                                 num_workers=1)\nprint(len(X_inputs))\nprint(len(y_labels))\n\n```\n\n    50000\n    50000\n\n\n\n```python\nfrom qiskit import transpile, assemble\nclass QuanvCircuit:\n    \"\"\" \n    This class defines filter circuit of Quanvolution layer\n    \"\"\"    \n    def __init__(self, kernel_size, backend, shots, threshold):\n        # --- Circuit definition start ---\n        self.n_qubits = kernel_size ** 2\n        self._circuit = qiskit.QuantumCircuit(self.n_qubits)\n        self.theta = [qiskit.circuit.Parameter('theta{}'.format(i)) for i in range(self.n_qubits)]\n\n        for i in range(self.n_qubits):\n            self._circuit.rx(self.theta[i], i)\n        \n        self._circuit.barrier()\n        self._circuit.measure_all()\n        # ---- Circuit definition end ----\n        self.backend   = backend\n        self.shots     = shots\n        self.threshold = threshold\n\n    def run(self, data):\n        # encoding data to parameters\n        thetas = [data]\n        \n        param_dict = dict()\n        for theta in thetas:\n            for i in range(self.n_qubits):\n                param_dict[self.theta[i]] = theta[i]\n        param_binds = [param_dict]\n\n        List = [thetas]\n        t_qc = transpile(self._circuit,\n                         self.backend)\n        qobj = assemble(t_qc,\n                        shots=self.shots,\n                        parameter_binds = param_binds)\n        job = self.backend.run(qobj)\n        result = job.result().get_counts()\n\n        # decoding the result\n        counts = 0\n        for key, val in result.items():\n            cnt = sum([int(char) for char in key])\n            counts += cnt * val\n        \n        probabilities = counts / (self.shots * self.n_qubits)\n        \n        return probabilities\n```\n\n\n```python\nbackend = qiskit.Aer.get_backend('qasm_simulator')\nfilter_size = 2\ncirc = QuanvCircuit(filter_size, backend, 100, 127)\n#data = torch.tensor([[0, 200], [100, 255]])\n#data = torch.tensor([-2.8351264, 1.3314428,  -0.18492305,  0.00792312]).numpy()#1,2,3,4]).numpy()\ndata = [-2.8351264,  1.3314428,  -0.18492305,  0.00792312]\n\n#\nprint(data)\n#print(data.size())\nprint(circ.run(data))\n\ncirc._circuit.draw()#output='mpl')\n```\n\n    [-2.8351264, 1.3314428, -0.18492305, 0.00792312]\n    0.3375\n\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">        \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2591  \u2591 \u250c\u2500\u2510         \n   q_0: \u2524 Rx(theta0) \u251c\u2500\u2591\u2500\u2500\u2591\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n        \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2591  \u2591 \u2514\u2565\u2518\u250c\u2500\u2510      \n   q_1: \u2524 Rx(theta1) \u251c\u2500\u2591\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u2500\u2500\n        \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2591  \u2591  \u2551 \u2514\u2565\u2518\u250c\u2500\u2510   \n   q_2: \u2524 Rx(theta2) \u251c\u2500\u2591\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u2500\u2500\n        \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2591  \u2591  \u2551  \u2551 \u2514\u2565\u2518\u250c\u2500\u2510\n   q_3: \u2524 Rx(theta3) \u251c\u2500\u2591\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2524M\u251c\n        \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2591  \u2591  \u2551  \u2551  \u2551 \u2514\u2565\u2518\nmeas: 4/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\n                             0  1  2  3 </pre>\n\n\n\n\n```python\nimport qiskit\nbackend = qiskit.Aer.get_backend('qasm_simulator')\nfilter_size = 2\ncirc = QuanvCircuit(filter_size, backend, 100, 127)\n```\n\n\n```python\n#for (X_train, y_train) in train_dataloader:\nprint('Loading Training data')\nxVal = []\nyVal = []\n#count = 0\nfor (X_train, y_train) in train_dataloader:\n    #print('Training Starts')\n    #print(X_train.detach().numpy()[0])\n    #print(y_train.detach().numpy()[0])\n    x = circ.run(X_train.detach().numpy()[0])\n    y = circ.run(y_train.detach().numpy()[0])\n    #regressor.fit(x, y)\n    \n    xVal.append([x])\n    yVal.append(y)\n    '''\n    count += 1\n    \n    if (count == 50000):\n        print('Loaded data :',count)\n        break\n    '''\nprint('x data',len(xVal))\nprint('y data',len(yVal))\n\n```\n\n    Loading Training data\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    x data 50000\n    y data 50000\n\n\n\n```python\n#print(torch.tensor(xVal).detach().numpy())\n#print(torch.tensor(yVal).detach().numpy())\nimport time\nprint('Training Started')\nstartTime = time.time()\nregressor.fit(torch.tensor(xVal).detach().numpy(), torch.tensor(yVal).detach().numpy())\nprint('Total Training Time :', (time.time()-startTime))\n```\n\n\n```python\n# create empty array for callback to store evaluations of the objective function\n'''\nobjective_func_vals = []\nplt.rcParams[\"figure.figsize\"] = (12, 6)\n\n# fit to data\n#set_trace()\n\n#import pdb; pdb.set_trace()\n#regressor.fit(X, y)\nregressor.fit([1], 1)\n'''\n# return to default figsize\n#plt.rcParams[\"figure.figsize\"] = (6, 4)\n\n# score the result\nregressor.score(torch.tensor(xVal).detach().numpy(), torch.tensor(yVal).detach().numpy())\n\n```\n\n\n\n\n    -1.0083991836847592\n\n\n\n\n```python\nprint(objective_func_vals)\n```\n\n    [17497.53775066666, 4211.549464196395, 3357.536011807917, 1503.9061848238787, 1483.5268802255184, 1484.4908214588766, 1484.2207121472027, 1484.0932874567195, 1491.3789444947095, 1482.8597319869539, 1484.92946745298, 1481.9600680875417, 1486.2004153809164, 1491.457017724896]\n\n", "meta": {"hexsha": "320fee0f69f05e8c23b89c7f36c1aaf23fbb1380", "size": 49777, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/FullQuantum_LDNN.ipynb", "max_stars_repo_name": "18819F-Project/ModellingDynamicalSystem", "max_stars_repo_head_hexsha": "2610385e38c4cff7c9cbe25e1c6801a3de9eaf69", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/FullQuantum_LDNN.ipynb", "max_issues_repo_name": "18819F-Project/ModellingDynamicalSystem", "max_issues_repo_head_hexsha": "2610385e38c4cff7c9cbe25e1c6801a3de9eaf69", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/FullQuantum_LDNN.ipynb", "max_forks_repo_name": "18819F-Project/ModellingDynamicalSystem", "max_forks_repo_head_hexsha": "2610385e38c4cff7c9cbe25e1c6801a3de9eaf69", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 71.9320809249, "max_line_length": 16914, "alphanum_fraction": 0.6715551359, "converted": true, "num_tokens": 6846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807713748839197, "lm_q2_score": 0.09534946875514017, "lm_q1q2_score": 0.032235475457776656}}
{"text": "# Collection of Simple Random Sample from Population of Websites\n\n## Simple Random Sample\n\nBelow is a program that creates a simple random sample of websites according to Alexa Analytics' Top One Million sites CSV. The function `create_sample` creates a random integer between 0 and 999,999. That number acts as the index for the site we will get from the population CSV (e.g. The site at index 0 is google.com). \n\nOnce we have selected a site for our sample, we need to resolve its IP address (note: we will be using only IPv4 addresses as Alexa only offers those in their dataset and all websites should handle IPv4 and IPv6). If we are unable to resolve the address than we will randomly select another site to replace it.\n\nWhen sampling is completed, the sample dataset (domains and IPv4 addresses) is exported to a CSV file.\n\n\n```python\nfrom random import randint\nimport pandas as pd\nimport socket\n\n# List of top one million sites according to Alexa Analytics/Website Ranking\n# https://s3.amazonaws.com/alexa-static/top-1m.csv.zip\ntop_sites = pd.read_csv('top-1m.csv', header=None)[1]\n\n# n is sample size\nn=1000\n\n# Dictionary used for stored sample data\nsample = {\n    'Website Domain' : [],\n    'IPv4 Address' : []\n}\n\ndef create_sample(n): \n    i = 0\n    while i < n:\n        i += 1\n        # Get random number between 0 and 999,999\n        random_index = randint(0, len(top_sites) - 1)\n\n        # If the site has not already been selected, add it to our data set\n        if not top_sites[random_index] in sample['Website Domain']:\n            try:\n                # print(\"\\033[0mGetting IPv4 Address for %s...\" % top_sites[random_index])\n                ipv4 = socket.gethostbyname(top_sites[random_index])\n            # If we can't resolve the IP from the host name, replace it with a different host name\n            except:\n                # print(\"\\033[1mFailed. Selecting new site for sample.\")\n                i -= 1\n                continue\n            sample['Website Domain'].append(top_sites[random_index])\n            sample['IPv4 Address'].append(ipv4)\n\ncreate_sample(n)\n\n# Save sample to a CSV file\ndataset = pd.DataFrame.from_dict(sample)\ndataset.to_csv('website_sample.csv')\n\ndataset\n```\n\n# Use Dataset Instead of Creating New Sample\nEssentially importing `website_sample.csv` for our dataset so we don't have to create a new sample.\n\n\n```python\nn = 1000\ndataset = pd.DataFrame.from_csv('website_sample.csv')\ndataset\n```\n\n    /home/ari/.anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:2: FutureWarning: from_csv is deprecated. Please use read_csv(...) instead. Note that some of the default arguments are different, so please refer to the documentation for from_csv when changing your function calls\n      \n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Website Domain</th>\n      <th>IPv4 Address</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>ipos.vn</td>\n      <td>94.237.76.49</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>sectorul4news.ro</td>\n      <td>89.42.219.210</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>newprint.ca</td>\n      <td>37.218.253.61</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>destinationhotels.com</td>\n      <td>23.100.83.213</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>flutetoday.com</td>\n      <td>97.74.55.1</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>serialcrush.com</td>\n      <td>62.149.142.158</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>mybmtc.com</td>\n      <td>202.71.129.225</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>hmi.edu</td>\n      <td>192.249.121.112</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>flashkit.com</td>\n      <td>70.42.23.121</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>fucktubes.xxx</td>\n      <td>104.28.23.71</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>thetodaypost.com</td>\n      <td>104.31.66.246</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>avpgalaxy.net</td>\n      <td>162.211.84.48</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>scwtenor.com</td>\n      <td>74.208.236.209</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>ecom.ly</td>\n      <td>104.18.47.2</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>redwolfwildernessadventures.com</td>\n      <td>67.59.136.110</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>wesounds.com</td>\n      <td>107.6.153.170</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>bloganten.ru</td>\n      <td>92.53.114.3</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>karinto.in</td>\n      <td>175.134.120.229</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>myscopeoutreach.org</td>\n      <td>182.160.163.245</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>landsurveyor.blogfa.com</td>\n      <td>149.56.201.253</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>finministry.com</td>\n      <td>104.18.41.100</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>odeontravel.rs</td>\n      <td>195.252.107.131</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>greeningtheblue.org</td>\n      <td>104.27.147.128</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>jerusalemperspective.com</td>\n      <td>104.199.115.212</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>bazi-oksana.ru</td>\n      <td>5.101.152.32</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>leupold.com</td>\n      <td>52.88.153.55</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>cloud9.gg</td>\n      <td>23.227.38.32</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>goldsgym.com</td>\n      <td>162.209.117.196</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>tagbox.in</td>\n      <td>52.172.54.225</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>sexmamki.org</td>\n      <td>151.80.209.25</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>970</th>\n      <td>jb.com.br</td>\n      <td>152.199.54.25</td>\n    </tr>\n    <tr>\n      <th>971</th>\n      <td>vietadsonline.com</td>\n      <td>171.244.34.197</td>\n    </tr>\n    <tr>\n      <th>972</th>\n      <td>itftkd.ir</td>\n      <td>185.128.81.85</td>\n    </tr>\n    <tr>\n      <th>973</th>\n      <td>rouxroamer.com</td>\n      <td>104.31.95.99</td>\n    </tr>\n    <tr>\n      <th>974</th>\n      <td>filejo.co.kr</td>\n      <td>43.255.255.83</td>\n    </tr>\n    <tr>\n      <th>975</th>\n      <td>peraichi.com</td>\n      <td>54.230.89.244</td>\n    </tr>\n    <tr>\n      <th>976</th>\n      <td>hw3d.net</td>\n      <td>192.99.14.211</td>\n    </tr>\n    <tr>\n      <th>977</th>\n      <td>nekoshop.ru</td>\n      <td>37.140.192.198</td>\n    </tr>\n    <tr>\n      <th>978</th>\n      <td>maxbestwork.com</td>\n      <td>66.199.189.51</td>\n    </tr>\n    <tr>\n      <th>979</th>\n      <td>hindihelpguru.com</td>\n      <td>199.250.213.223</td>\n    </tr>\n    <tr>\n      <th>980</th>\n      <td>exertion-fitness.com</td>\n      <td>23.227.38.32</td>\n    </tr>\n    <tr>\n      <th>981</th>\n      <td>aktualnacenabytu.sk</td>\n      <td>212.57.38.25</td>\n    </tr>\n    <tr>\n      <th>982</th>\n      <td>geoequipos.cl</td>\n      <td>192.140.57.10</td>\n    </tr>\n    <tr>\n      <th>983</th>\n      <td>removenotifications.com</td>\n      <td>192.64.119.93</td>\n    </tr>\n    <tr>\n      <th>984</th>\n      <td>matbit.net</td>\n      <td>5.61.47.250</td>\n    </tr>\n    <tr>\n      <th>985</th>\n      <td>homebasedonlinevehiclemarketing.com</td>\n      <td>146.66.96.176</td>\n    </tr>\n    <tr>\n      <th>986</th>\n      <td>xn--v8j5erc590uusnxox.com</td>\n      <td>183.90.253.8</td>\n    </tr>\n    <tr>\n      <th>987</th>\n      <td>nflsport.icu</td>\n      <td>198.54.121.189</td>\n    </tr>\n    <tr>\n      <th>988</th>\n      <td>izithakazelo.blog</td>\n      <td>192.0.78.191</td>\n    </tr>\n    <tr>\n      <th>989</th>\n      <td>irinabiz.ru</td>\n      <td>138.201.199.38</td>\n    </tr>\n    <tr>\n      <th>990</th>\n      <td>intercity.pl</td>\n      <td>46.174.180.162</td>\n    </tr>\n    <tr>\n      <th>991</th>\n      <td>bongacams3.com</td>\n      <td>31.192.123.62</td>\n    </tr>\n    <tr>\n      <th>992</th>\n      <td>twinstrangers.net</td>\n      <td>52.214.239.109</td>\n    </tr>\n    <tr>\n      <th>993</th>\n      <td>textgeneratorfont.com</td>\n      <td>162.241.133.121</td>\n    </tr>\n    <tr>\n      <th>994</th>\n      <td>silversaints.com</td>\n      <td>212.188.174.246</td>\n    </tr>\n    <tr>\n      <th>995</th>\n      <td>evassmat.com</td>\n      <td>104.28.24.228</td>\n    </tr>\n    <tr>\n      <th>996</th>\n      <td>mpets.mobi</td>\n      <td>136.243.25.36</td>\n    </tr>\n    <tr>\n      <th>997</th>\n      <td>londongateway.com</td>\n      <td>65.52.130.1</td>\n    </tr>\n    <tr>\n      <th>998</th>\n      <td>derangler.shop</td>\n      <td>85.236.56.247</td>\n    </tr>\n    <tr>\n      <th>999</th>\n      <td>tavirekini.lv</td>\n      <td>94.100.11.185</td>\n    </tr>\n  </tbody>\n</table>\n<p>1000 rows \u00d7 2 columns</p>\n</div>\n\n\n\n# Determining Proportion of Websites Running AWS\n\n## Proportion of IPv4 addresses owned by AWS\n\nThe program takes a list of all IPv4 addresses owned by AWS and compares them to the list of addresses in our sample. AWS does not give a list of IPv4 address but instead gives a subnet of their addresses, this means they've purchased addresses in bulk so they're grouped together. In order to properly compare an IPv4 address to a subnet, python offers a library called `ipaddress` that breaks up subnets and ip addresses into a data format that can easily be compared.\n\nIf an address appears in Amazon's IPv4 range (their owned addresses) than the domain associated with the IP address is appended to a list. The list of websites is then exported as a CSV file.\n\n\n```python\nimport json, requests, ipaddress \n\n# List of IP Ranges (IPv4 and IPv6) owned by Amazon and used for AWS\n# https://ip-ranges.amazonaws.com/ip-ranges.json\naws_ip_ranges = json.loads(requests.get('https://ip-ranges.amazonaws.com/ip-ranges.json').text)\n\n# Determine if given IP address (ip_input) shows uo in AWS IPv4 Range\ndef check_aws(ip_input):\n    # Compare given IP to all AWS IP addresses within AWS IPv4 Subnetwork\n    for i in range(len(aws_ip_ranges['prefixes'])):\n        # Parse IPv4 address for comparison\n        site_ip = ipaddress.ip_address(ip_input)\n        \n        # Parse AWS IPv4 Subnet\n        aws_subnet = ipaddress.ip_network(aws_ip_ranges['prefixes'][i]['ip_prefix'])\n        \n        # If IP is within the AWS IPv4 Range, the website is run on AWS\n        if site_ip in aws_subnet:\n            return True\n    # If the website is not within the range, the \n    # website operates independnetly of AWS    \n    return False\n\n# List of websites using AWS\nwebsites_using_aws = []\n\ndef get_aws_domains():\n\n    # Check every IP within our sample against AWS IPv4 Range\n    for i in range(len(dataset)):\n        if check_aws(dataset['IPv4 Address'][i]):\n            websites_using_aws.append(dataset['Website Domain'][i])\n\nget_aws_domains()\n            \n# Save dataset of AWS websites to a CSV file\naws_df = pd.DataFrame({'AWS Websites':websites_using_aws})\naws_df.to_csv('websites_using_aws.csv')\n\naws_df\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>AWS Websites</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>leupold.com</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>wanasatime.com</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>simplesdental.com</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>monetixwallet.com</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>10tv.in</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>rosedalecenter.com</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>margstacobistro.com</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>shanghainavi.com</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>keaweather.net</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>lion.co.nz</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>moomii.jp</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>figleafapp.com</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>maharajamultiplex.in</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>conchovalleyhomepage.com</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>honkmedia.net</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>willowtreeapps.com</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>playvod.ma</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>tigosports.gt</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>araelium.com</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>boostnote.io</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>echofoodshelf.org</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>obonsai.com.br</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>atcost.in</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>profsnhcadmission.in</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>manalonline.com</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>nj211.org</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>conta.no</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>cldmail.co.uk</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>obo.se</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>soft32.es</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>31</th>\n      <td>juegosmesa.cl</td>\n    </tr>\n    <tr>\n      <th>32</th>\n      <td>localone.app</td>\n    </tr>\n    <tr>\n      <th>33</th>\n      <td>grjapan.jp</td>\n    </tr>\n    <tr>\n      <th>34</th>\n      <td>peachysnaps.com</td>\n    </tr>\n    <tr>\n      <th>35</th>\n      <td>knottyladyyarns.com</td>\n    </tr>\n    <tr>\n      <th>36</th>\n      <td>amormaturo.com</td>\n    </tr>\n    <tr>\n      <th>37</th>\n      <td>hltmag.co.uk</td>\n    </tr>\n    <tr>\n      <th>38</th>\n      <td>oldtownportraitgallery.com</td>\n    </tr>\n    <tr>\n      <th>39</th>\n      <td>matterport.com</td>\n    </tr>\n    <tr>\n      <th>40</th>\n      <td>parkopedia.co.uk</td>\n    </tr>\n    <tr>\n      <th>41</th>\n      <td>rehabs.com</td>\n    </tr>\n    <tr>\n      <th>42</th>\n      <td>diablomedia.com</td>\n    </tr>\n    <tr>\n      <th>43</th>\n      <td>battersea.org.uk</td>\n    </tr>\n    <tr>\n      <th>44</th>\n      <td>qmo.org.au</td>\n    </tr>\n    <tr>\n      <th>45</th>\n      <td>midlandsb.com</td>\n    </tr>\n    <tr>\n      <th>46</th>\n      <td>kuflink.co.uk</td>\n    </tr>\n    <tr>\n      <th>47</th>\n      <td>lunns.com</td>\n    </tr>\n    <tr>\n      <th>48</th>\n      <td>send2sell.com</td>\n    </tr>\n    <tr>\n      <th>49</th>\n      <td>wvi.org</td>\n    </tr>\n    <tr>\n      <th>50</th>\n      <td>letsignite.in</td>\n    </tr>\n    <tr>\n      <th>51</th>\n      <td>kolkt.com</td>\n    </tr>\n    <tr>\n      <th>52</th>\n      <td>lucasmaier.com.br</td>\n    </tr>\n    <tr>\n      <th>53</th>\n      <td>ellevatenetwork.com</td>\n    </tr>\n    <tr>\n      <th>54</th>\n      <td>completefrance.com</td>\n    </tr>\n    <tr>\n      <th>55</th>\n      <td>bellevie-group.com</td>\n    </tr>\n    <tr>\n      <th>56</th>\n      <td>via.id</td>\n    </tr>\n    <tr>\n      <th>57</th>\n      <td>tweentribune.com</td>\n    </tr>\n    <tr>\n      <th>58</th>\n      <td>filesun.net</td>\n    </tr>\n    <tr>\n      <th>59</th>\n      <td>peraichi.com</td>\n    </tr>\n    <tr>\n      <th>60</th>\n      <td>twinstrangers.net</td>\n    </tr>\n  </tbody>\n</table>\n<p>61 rows \u00d7 1 columns</p>\n</div>\n\n\n\n# 1-Proportion Z-Test for Proportion of AWS to non-AWS Websites\n\n## Testing in Python\n\nThis is a procedure for completing a one-proportion z-test given the sample dataset and proportion of websites using AWS. First we declare `p` as the claimed market share percentage (The Forbes article claimed AWS has a 31% market share). We calculate `q` and proceed with our success failure condition. \n\nThe `assert` lines basically test s/f - if np or qp is < 10 than the program stops and an exception (error) is raised. Because the index values when sampling were random, than we can assume our sample is random.\n\nNext we calculate our z-score value with a one-proportion z-test:\n$$\n\\begin{align}\nz = \\frac{\\hat{p} - p}{\\sigma} && \\sigma = \\sqrt{\\frac{pq}{n}}\n\\end{align}\n$$\n\nThe code for calculating z-score is `z = ((len(websites_using_aws)/n) - p)/sd`. For standard deviation, it's `sd = math.sqrt((p*q)/2)`.\nOnce we calculate our z-score, finally we can get our p-value. The library SciPy offers statistics which will allow us to calculate p-value similar to how a calculator would. Once complete, we can do hypothesis testing using a significance level of 5%.\n\n\n```python\nimport math\nimport scipy.stats as st\n\n# Creating initial values from datatset/claim\nclaimed_marketshare = 0.31\n\np = claimed_marketshare\nq = 1-claimed_marketshare\n\n# Success/Failure Condition, exception raised if np or nq is less than 10\nassert n*p >= 10, True\nassert n*q >= 10, True\n\n# Calculate Z-Score & P-Value\nsd = math.sqrt((p*q)/n)\nz = ((len(websites_using_aws)/n) - p)/sd\n\np_value = st.norm.cdf(z)\n  \nprint('P: %f\\tQ: %f\\nNP: %f\\tNQ: %f\\n\\nP-Hat: %f\\n\\nZ-Score: %f\\nP-Value: %f\\n' \n      % (p, q, n*p, n*q, (len(websites_using_aws)/n), z, p_value))\n\n# Hypothesis Testing\nsignificants_level = 0.05\n\nif p_value <= (significants_level): print('\\033[1mReject H0')\nelse: print('\\033[1mFail to reject H0')\n```\n\n    P: 0.310000\tQ: 0.690000\n    NP: 310.000000\tNQ: 690.000000\n    \n    P-Hat: 0.061000\n    \n    Z-Score: -17.025268\n    P-Value: 0.000000\n    \n    \u001b[1mReject H0\n\n\n## Interpretation\n\nWe've rejected the null-hypothesis as our P-Value is approximately zero. The claim made within the Forbes article is invalid according to this observational study as we can support the alternate hypothesis that Amazon does not have a 31% market share in cloud computing/hosting.\n\n# Confidence Interval for 1-Proportion Sample\n\n## Confidence Interval Based on Z-Test\n\nThis is a standard method to produce a confidence interval given the z-score, sample size, claimed population proportions and sample proportions produced by the one-proportion z-test.\n\nWe use the following equations to calculate the standard deviation and standard error for our confidence interval:\n$$\n\\begin{align}\n\\sigma_p = \\sqrt{\\frac{pq}{n}} && SE_p = \\sqrt{\\frac{\\hat{p}\\hat{q}}{n}}\n\\end{align}\n$$\n\nBoth $\\hat{p}$ and $\\hat{q}$ are simply $p$ and $q$ for the sample proportion. Using the z-score we calculated during our hypothesis test as our critical value, we can multipy it by our standard error to produce our margin of error, like so:\n$$\nME = Z_c\\sqrt{\\frac{\\hat{p}\\hat{q}}{n}}\n$$\n\n\n```python\n# Sample p (statistic) and q values\naws_p = len(websites_using_aws)/n\naws_q = 1 - aws_p\n\n# Standard error for the sample proportion\nse = math.sqrt((aws_p*aws_q)/n)\n\n# Margin of error\nme = z*se\n\nprint('Interval: (%f, %f)' % (aws_p + me, aws_p - me))\n```\n\n    Interval: (-0.067852, 0.189852)\n\n\n## Interpretation\n\nI am 95% confident that the true proportion of websites within the top one-million sites population is between -6.78% and 19%. By 95% confident I mean if the above procedures are reproduced with a sample size of 1,000, the proportion of websites within the sample that use AWS as their cloud provider will be between -6.78% and 19%. Because zero lies within our interval, the results of this study can be considered insignificant.\n", "meta": {"hexsha": "eef91516b5544c3d02427152e34378c98afe7378", "size": 38131, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "AWS-Market Share Analysis.ipynb", "max_stars_repo_name": "ceiphr/AWS-Market-Share-Analysis", "max_stars_repo_head_hexsha": "0e62e4c445f8972758e9d6bdc16d80376aaeab6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AWS-Market Share Analysis.ipynb", "max_issues_repo_name": "ceiphr/AWS-Market-Share-Analysis", "max_issues_repo_head_hexsha": "0e62e4c445f8972758e9d6bdc16d80376aaeab6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AWS-Market Share Analysis.ipynb", "max_forks_repo_name": "ceiphr/AWS-Market-Share-Analysis", "max_forks_repo_head_hexsha": "0e62e4c445f8972758e9d6bdc16d80376aaeab6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6960873521, "max_line_length": 479, "alphanum_fraction": 0.4041068947, "converted": true, "num_tokens": 6689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.07696084363512665, "lm_q1q2_score": 0.03222326737143379}}
{"text": "# A quick, practical intro to the Jupyter Notebook\n\nFernando Perez\n\n## Introduction\n\nThe IPython Notebook is an **interactive computing environment** that enables users to author notebook documents that include: \n- Live code\n- Interactive widgets\n- Plots\n- Narrative text\n- Equations\n- Images\n- Video\n\nThese documents provide a **complete and self-contained record of a computation** that can be converted to various formats and shared with others using email, [Dropbox](http://dropbox.com), version control systems (like git/[GitHub](http://github.com)) or [nbviewer.ipython.org](http://nbviewer.ipython.org).\n\n### Components\n\nThe IPython Notebook combines three components:\n\n* **The notebook web application**: An interactive web application for writing and running code interactively and authoring notebook documents.\n* **Kernels**: Separate processes started by the notebook web application that runs users' code in a given language and returns output back to the notebook web application. The kernel also handles things like computations for interactive widgets, tab completion and introspection. \n* **Notebook documents**: Self-contained documents that contain a representation of all content visible in the notebook web application, including inputs and outputs of the computations, narrative\ntext, equations, images, and rich media representations of objects. Each notebook document has its own kernel.\n\n## Notebook web application\n\nThe notebook web application enables users to:\n\n* **Edit code in the browser**, with automatic syntax highlighting, indentation, and tab completion/introspection.\n* **Run code from the browser**, with the results of computations attached to the code which generated them.\n* See the results of computations with **rich media representations**, such as HTML, LaTeX, PNG, SVG, PDF, etc.\n* Create and use **interactive JavaScript wigets**, which bind interactive user interface controls and visualizations to reactive kernel side computations.\n* Author **narrative text** using the [Markdown](https://daringfireball.net/projects/markdown/) markup language.\n* Build **hierarchical documents** that are organized into sections with different levels of headings.\n* Include mathematical equations using **LaTeX syntax in Markdown**, which are rendered in-browser by [MathJax](http://www.mathjax.org/).\n\n## Kernels\n\nThrough IPython's kernel and messaging architecture, the Notebook allows code to be run in a range of different programming languages.  For each notebook document that a user opens, the web application starts a kernel that runs the code for that notebook. Each kernel is capable of running code in a single programming language and there are kernels available in over [100 programming languages](https://github.com/jupyter/jupyter/wiki/Jupyter-kernels).\n\n[IPython](https://github.com/ipython/ipython) is the default kernel, it runs Python code.\n\nEach of these kernels communicate with the notebook web application and web browser using a JSON over ZeroMQ/WebSockets message protocol that is described [here](https://jupyter-client.readthedocs.io/en/latest/messaging.html#messaging). Most users don't need to know about these details, but it helps to understand that \"kernels run code.\"\n\n## Notebook documents\n\nNotebook documents contain the **inputs and outputs** of an interactive session as well as **narrative text** that accompanies the code but is not meant for execution. **Rich output** generated by running code, including HTML, images, video, and plots, is embeddeed in the notebook, which makes it a complete and self-contained record of a computation. \n\nWhen you run the notebook web application on your computer, notebook documents are just **files on your local filesystem with a `.ipynb` extension**. This allows you to use familiar workflows for organizing your notebooks into folders and sharing them with others using email, Dropbox and version control systems.\n\nNotebooks consist of a **linear sequence of cells**. There are three basic cell types:\n\n* **Code cells:** Input and output of live code that is run in the kernel\n* **Markdown cells:** Narrative text with embedded LaTeX equations\n* **Raw cells:** Unformatted text that is included, without modification, when notebooks are converted to different formats using nbconvert\n\nInternally, notebook documents are **[JSON](http://en.wikipedia.org/wiki/JSO) data** with **binary values [base64]**(http://en.wikipedia.org/wiki/Base64) encoded. This allows them to be **read and manipulated programmatically** by any programming language. Because JSON is a text format, notebook documents are version control friendly.\n\n**Notebooks can be exported** to different static formats including HTML, reStructeredText, LaTeX, PDF, and slide shows using Jupyter's `nbconvert` utility.\n\nFurthermore, any notebook document available from a **public URL on or GitHub can be shared** via http://nbviewer.jupyter.org. This service loads the notebook document from the URL and renders it as a static web page. The resulting web page may thus be shared with others **without their needing to install Jupyter**.\n\n### Body\n\nThe body of a notebook is composed of cells. Each cell contains either markdown, code input, code output, or raw text. Cells can be included in any order and edited at-will, allowing for a large ammount of flexibility for constructing a narrative.\n\n- **Markdown cells** - These are used to build a nicely formatted narrative around the code in the document. The majority of this lesson is composed of markdown cells.\n\n- **Code cells** - These are used to define the computational code in the document. They come in two forms: the *input cell* where the user types the code to be executed, and the *output cell* which is the representation of the executed code. Depending on the code, this representation may be a simple scalar value, or something more complex like a plot or an interactive widget.\n\n- **Raw cells** - These are used when text needs to be included in raw form, without execution or transformation.\n\nThis is what the three types of cells look like:\n\n\n\n#### Modality\n\nThe notebook user interface is *modal*. This means that the keyboard behaves differently depending upon the current mode of the notebook. A notebook has two modes: **edit** and **command**.\n\n**Edit mode** is indicated by a blue cell border and a prompt showing in the editor area. When a cell is in edit mode, you can type into the cell, like a normal text editor.\n\n\n\n**Command mode** is indicated by a grey cell background. When in command mode, the structure of the notebook can be modified as a whole, but the text in individual cells cannot be changed. Most importantly, the keyboard is mapped to a set of shortcuts for efficiently performing notebook and cell actions. For example, pressing **`c`** when in command mode, will copy the current cell; no modifier is needed.\n\n\n\nEnter edit mode by pressing `Enter` or using the mouse to click on a cell's editor area.\n\nEnter command mode by pressing `Esc` or using the mouse to click *outside* a cell's editor area.\n\nDo not attempt to type into a cell when in command mode; unexpected things will happen!\n\n\n```python\n%pylab inline\nplot(rand(100))\n```\n\n#### Mouse navigation\n\nThe first concept to understand in mouse-based navigation is that **cells can be selected by clicking on them.** The currently selected cell is indicated with a blue outline or gray background depending on whether the notebook is in edit or command mode. Clicking inside a cell's editor area will enter edit mode. Clicking on the prompt or the output area of a cell will enter command mode.\n\nThe second concept to understand in mouse-based navigation is that **cell actions usually apply to the currently selected cell**. For example, to run the code in a cell, select it and then click the <button class='btn btn-default btn-xs'><i class=\"fa fa-play icon-play\"></i></button> button in the toolbar or the **`Run -> Run Selected Cells`** menu item. Similarly, to copy a cell, select it and then click the <button class='btn btn-default btn-xs'><i class=\"fa fa-copy icon-copy\"></i></button> button in the toolbar or the **`Edit -> Copy`** menu item. With this simple pattern, it should be possible to perform nearly every action with the mouse.\n\nMarkdown cells have one other state which can be modified with the mouse. These cells can either be rendered or unrendered. When they are rendered, a nice formatted representation of the cell's contents will be presented. When they are unrendered, the raw text source of the cell will be presented. To render the selected cell with the mouse, click the <button class='btn btn-default btn-xs'><i class=\"fa fa-play icon-play\"></i></button> button in the toolbar or the **`Run -> Run Selected Cells`** menu item. To unrender the selected cell, double click on the cell.\n\n#### Keyboard Navigation\n\nThe modal user interface of the IPython Notebook has been optimized for efficient keyboard usage. This is made possible by having two different sets of keyboard shortcuts: one set that is active in edit mode and another in command mode.\n\nThe most important keyboard shortcuts are **`Enter`**, which enters edit mode, and **`Esc`**, which enters command mode.\n\nIn edit mode, most of the keyboard is dedicated to typing into the cell's editor. Thus, in edit mode there are relatively few shortcuts. In command mode, the entire keyboard is available for shortcuts, so there are many more possibilities.\n\nThe following shortcuts have been found to be the most useful in day-to-day tasks:\n\n- Basic navigation: **`enter`**, **`shift-enter`**, **`up/k`**, **`down/j`**\n- Saving the notebook: **`s`**\n- Cell types: **`y`**, **`m`**, **`r`**\n- Cell creation: **`a`**, **`b`**\n- Cell editing: **`x`**, **`c`**, **`v`**, **`d`**, **`z`**, **`ctrl+shift+-`**\n- Kernel operations: **`i`**, **`.`**\n\nYou can fully customize JupyterLab's keybindings by accessing the **`Settings -> Advanced Settings Editor`** menu item.\n\n# Running Code\n\nFirst and foremost, the Jupyter Notebook is an interactive environment for writing and running code. Jupyter is capable of running code in a wide range of languages. However, this notebook, and the default kernel in Jupyter, runs Python code.\n\n## Code cells allow you to enter and run Python code\n\nRun a code cell using `Shift-Enter` or pressing the <button class='btn btn-default btn-xs'><i class=\"icon-play fa fa-play\"></i></button> button in the toolbar above:\n\n\n```python\na = 10\n```\n\n\n```python\nprint(a + 1)\n```\n\nNote the difference between the above printing statement and the operation below:\n\n\n```python\na + 1\n```\n\nWhen a value is *returned* by a computation, it is displayed with a number, that tells you this is the output value of a given cell.  You can later refere to any of these values (should you need one that you forgot to assign to a named variable). The last three are available respectively as auto-generated variables called `_`, `__` and `___` (one, two and three underscores). In addition to these three convenience ones for recent results, you can use `_N`, where N is the number in `[N]`, to access any numbered output.\n\nThere are two other keyboard shortcuts for running code:\n\n* `Alt-Enter` runs the current cell and inserts a new one below.\n* `Ctrl-Enter` run the current cell and enters command mode.\n\n## Managing the IPython Kernel\n\nCode is run in a separate process called the IPython Kernel.  The Kernel can be interrupted or restarted.  Try running the following cell and then hit the <button class='btn btn-default btn-xs'><i class='icon-stop fa fa-stop'></i></button> button in the toolbar above.\n\n\n```python\nimport time\ntime.sleep(10)\n```\n\nIf the Kernel dies you will be prompted to restart it. Here we call the low-level system libc.time routine with the wrong argument via\nctypes to segfault the Python interpreter:\n\n\n```python\nimport sys\nfrom ctypes import CDLL\n# This will crash a Linux or Mac system\n# equivalent calls can be made on Windows\ndll = 'dylib' if sys.platform == 'darwin' else 'so.6'\nlibc = CDLL(\"libc.%s\" % dll) \nlibc.time(-1)  # BOOM!!\n```\n\n## Cell menu\n\nThe \"Run\" menu has a number of items for running code in different ways, including\n\n* Run Selected Cells\n* Run All Cells\n* Run Selected Cell or Current Line in Console\n* Run All Above Selected Cell\n* Run  Selected Cell and All Below\n* Restart Kernel and Run All Cells\n\n## Restarting the kernels\n\nThe kernel maintains the state of a notebook's computations. You can reset this state by restarting the kernel. This is done by clicking on the <button class='btn btn-default btn-xs'><i class='fa fa-repeat icon-repeat'></i></button> in the toolbar above.\n\n## sys.stdout and sys.stderr\n\nThe stdout and stderr streams are displayed as text in the output area.\n\n\n```python\nprint(\"hi, stdout\")\n```\n\n\n```python\nfrom __future__ import print_function\nprint('hi, stderr', file=sys.stderr)\n```\n\n## Output is asynchronous\n\nAll output is displayed as it is generated in the Kernel: instead of blocking on the execution of the entire cell, output is made available to the Notebook immediately as it is generated by the kernel (even though the whole cell is submitted for execution as a single unit).\n\nIf you execute the next cell, you will see the output one piece at a time, not all at the end:\n\n\n```python\nimport time, sys\nfor i in range(8):\n    print(i)\n    time.sleep(0.5)\n```\n\n## Large outputs\n\nTo better handle large outputs, the output area can be collapsed. Run the following cell and then click on the vertical blue bar to the left of the output:\n\n\n```python\nfor i in range(50):\n    print(i)\n```\n\n---\n# Markdown Cells\n\nText can be added to IPython Notebooks using Markdown cells.  Markdown is a popular markup language that is a superset of HTML. Its specification can be found here:\n\n<http://daringfireball.net/projects/markdown/>\n\nYou can view the source of a cell by double clicking on it, or while the cell is selected in command mode, press `Enter` to edit it. One A cell has been editted, use `Shift-Enter` to re-render it. \n\n## Markdown basics\n\nYou can make text *italic* or **bold**.\n\nYou can build nested itemized or enumerated lists:\n\n* One\n    - Sublist\n        - This\n  - Sublist\n        - That\n        - The other thing\n* Two\n  - Sublist\n* Three\n  - Sublist\n\nNow another list:\n\n1. Here we go\n    1. Sublist\n    2. Sublist\n2. There we go\n3. Now this\n\nYou can add horizontal rules:\n\n---\n\nHere is a blockquote:\n\n> Beautiful is better than ugly.\n> Explicit is better than implicit.\n> Simple is better than complex.\n> Complex is better than complicated.\n> Flat is better than nested.\n> Sparse is better than dense.\n> Readability counts.\n> Special cases aren't special enough to break the rules.\n> Although practicality beats purity.\n> Errors should never pass silently.\n> Unless explicitly silenced.\n> In the face of ambiguity, refuse the temptation to guess.\n> There should be one-- and preferably only one --obvious way to do it.\n> Although that way may not be obvious at first unless you're Dutch.\n> Now is better than never.\n> Although never is often better than *right* now.\n> If the implementation is hard to explain, it's a bad idea.\n> If the implementation is easy to explain, it may be a good idea.\n> Namespaces are one honking great idea -- let's do more of those!\n\nAnd shorthand for links:\n\n[IPython's website](http://ipython.org)\n\nYou can add headings using Markdown's syntax:\n\n# Heading 1\n\n# Heading 2\n\n## Heading 2.1\n\n## Heading 2.2\n\n## Embedded code\n\nYou can embed code meant for illustration instead of execution in Python:\n\n    def f(x):\n        \"\"\"a docstring\"\"\"\n        return x**2\n\nor other languages:\n\n    if (i=0; i<n; i++) {\n      printf(\"hello %d\\n\", i);\n      x += 4;\n    }\n\n\n## LaTeX equations\n\nCourtesy of MathJax, you can include mathematical expressions both inline: \n$e^{i\\pi} + 1 = 0$  and displayed:\n\n$$e^x=\\sum_{i=0}^\\infty \\frac{1}{i!}x^i$$\n\nUse single dolars delimiter for inline math, so `$thisisinline\\int math$`  will give $this is inline\\int math$, for example to refer to variable within text. \n\nDouble dollars `$$\\int_0^{2\\pi} f(r, \\phi) \\partial \\phi $$` is used for standalone formulas:\n\n$$\\int_0^{2\\pi} f(r, \\phi) \\partial \\phi $$\n\n\n## Github flavored markdown (GFM)\n\nThe Notebook webapp support Github flavored markdown meaning that you can use triple backticks for code blocks \n<pre>\n```python\nprint \"Hello World\"\n```\n\n```javascript\nconsole.log(\"Hello World\")\n```\n</pre>\n\nGives \n```python\nprint \"Hello World\"\n```\n\n```javascript\nconsole.log(\"Hello World\")\n```\n\nAnd a table like this : \n\n<pre>\n| This | is   |\n|------|------|\n|   a  | table| \n</pre>\n\nA nice HTML Table\n\n| This | is   |\n|------|------|\n|   a  | table| \n\n## General HTML\n\nBecause Markdown is a superset of HTML you can even add things like HTML tables:\n\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n\n## Local files\n\nIf you have local files in your Notebook directory, you can refer to these files in Markdown cells directly:\n\n    [subdirectory/]<filename>\n\nFor example, in the images folder, we have the Python logo:\n\n    \n\n\n\nand a video with the HTML5 video tag:\n\n    <video controls src=\"images/animation.m4v\" />\n\n<video controls src=\"images/animation.m4v\" />\n\nThese do not embed the data into the notebook file, and require that the files exist when you are viewing the notebook.\n\n### Security of local files\n\nNote that this means that the IPython notebook server also acts as a generic file server\nfor files inside the same tree as your notebooks.  Access is not granted outside the\nnotebook folder so you have strict control over what files are visible, but for this\nreason it is highly recommended that you do not run the notebook server with a notebook\ndirectory at a high level in your filesystem (e.g. your home directory).\n\nWhen you run the notebook in a password-protected manner, local file access is restricted\nto authenticated users unless read-only views are active.\n\n---\n\n# Typesetting Equations\n\nThe Markdown parser included in IPython is MathJax-aware.  This means that you can freely mix in mathematical expressions using the [MathJax subset of Tex and LaTeX](http://docs.mathjax.org/en/latest/tex.html#tex-support).  \n\nYou can use single-dollar signs to include inline math, e.g. `$e^{i \\pi} = -1$` will render as $e^{i \\pi} = -1$, and double-dollars for displayed math:\n\n```\n$$\ne^x=\\sum_{i=0}^\\infty \\frac{1}{i!}x^i\n$$\n```\n\nrenders as:\n\n$$\ne^x=\\sum_{i=0}^\\infty \\frac{1}{i!}x^i\n$$\n\nYou can also use more complex LaTeX constructs for displaying math, such as:\n\n```\n\\begin{align}\n\\dot{x} & = \\sigma(y-x) \\\\\n\\dot{y} & = \\rho x - y - xz \\\\\n\\dot{z} & = -\\beta z + xy\n\\end{align}\n```\n\nto produce the Lorenz equations:\n\n\\begin{align}\n\\dot{x} & = \\sigma(y-x) \\\\\n\\dot{y} & = \\rho x - y - xz \\\\\n\\dot{z} & = -\\beta z + xy\n\\end{align}\n\nPlease refer to the MathJax documentation for a comprehensive description of which parts of LaTeX are supported, but note that Jupyter's support for LaTeX is **limited to mathematics**. You can **not** use LaTeX typesetting constrcuts for text or document structure, for text formatting you should restrict yourself to Markdown syntax.\n", "meta": {"hexsha": "8cfb625204255a7d3aeafe47d7d8ca97958054a6", "size": 28302, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "modules/02_Python_Jupyter/Intro_Jupyter_Notebook.ipynb", "max_stars_repo_name": "wcurrier/gda_course_2020", "max_stars_repo_head_hexsha": "4fefeb38ec03c4dffdda9fdd7ac9c3ec7343d648", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2020-06-12T16:23:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T16:23:08.000Z", "max_issues_repo_path": "modules/02_Python_Jupyter/Intro_Jupyter_Notebook.ipynb", "max_issues_repo_name": "UW-GDA/gda_2020", "max_issues_repo_head_hexsha": "205a411cab3492450c9c0265889b54f5b9d4b699", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-09-13T20:13:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-13T20:14:57.000Z", "max_forks_repo_path": "modules/02_Python_Jupyter/Intro_Jupyter_Notebook.ipynb", "max_forks_repo_name": "UW-GDA/gda_2020", "max_forks_repo_head_hexsha": "205a411cab3492450c9c0265889b54f5b9d4b699", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2020-08-25T16:25:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-12T18:43:30.000Z", "avg_line_length": 34.9407407407, "max_line_length": 663, "alphanum_fraction": 0.6056109109, "converted": true, "num_tokens": 4495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814055953761019, "lm_q2_score": 0.11436852769112676, "lm_q1q2_score": 0.03218394362720972}}
{"text": "# SysArmy Surveys: Analysis of argentine techies' salaries evolution (2014.02 - 2017.02)\n\n## Datasets\n\nThe used datasets have been published on the SysArmy blog since they started taking the surveys.  Each survey contains differencies on their columns, mostly additions across time, but some names and order have changed to.\n\nIn order to normalize the different structures, the next section includes a\n couple of functions to facilitate this process.  Below, is the list of datasets used at the moment.\n\n### Salaries\n\n| Period  | Path             | URL                                                                                                         |\n|---------|------------------|-------------------------------------------------------------------------------------------------------------|\n| 2014.02 | data/2014.02.csv | https://drive.google.com/open?id=0B7UapTwn9AahWkdEWnltRjUwVjQ                                               |\n| 2015.01 | data/2015.01.csv | https://drive.google.com/open?id=0B7UapTwn9AahSHl1aGNfTlNrYWc                                               |\n| 2016.01 | data/2016.01.csv | https://drive.google.com/open?id=0B7UapTwn9AahLTJmSE5zOUQ0aGc                                               |\n| 2016.02 | data/2016.02/    | https://drive.google.com/open?id=0B7UapTwn9AahUGtySFBjdHBCcWs                                               |\n| 2017.01 | data/2017.01/    | https://docs.google.com/spreadsheets/d/1diZG7ruHJ4OgO2-tbnO-ZnhjxjOnYjMVSxl7I-4LT54/edit#gid=1424918437     |\n| 2017.02 | data/2017.02/    | https://docs.google.com/spreadsheets/d/1f1CAmzbVtoL66IwXJWEf0Mn-QbMNGZIoCQ_b1HB-91E                         |\n\n\nThe datasets detailed above were downloaded and included \"as is\" in the `data/` folder on this repository.  The idea of this analysis is to not preprocess anything, and just normalize the data on the fly, of course this is possible given that the datasets are not so big.\n\n### Argentine Peso AR\\$ to US\\$\n\nIn one of the analysis (GDP) we will compare the salaries through time using the dollar as currency of reference. We do this in order to understand the numbers in the global economy, putting aside the effects of inflation.\nIn relation to the inflation, the official numbers are not so good for an appropiate analysis: between 2014 and 2015 the methodoly changed, and it's been an entire year (April 2016 - April 2017) without measurement.\n\n#### Links of interest\n\n* https://es.tradingeconomics.com/argentina/inflation-cpi\n* http://data.worldbank.org/indicator/NY.GDP.MKTP.CD?end=2016&locations=AR&start=1962&view=chart\n\n| Period  | Path                 | URL                                                                                                     |\n|---------|----------------------|---------------------------------------------------------------------------------------------------------|\n| 5Y      | data/usdars-cur.json | https://www.bloomberg.com/markets/api/bulk-time-series/price/USDARS%3ACUR?timeFrame=5_YEAR              |\n\n\n## Data preparation\n\n\n```python\nimport pandas as pd\nimport numpy as np\nimport re\nfrom matplotlib import cm\nfrom functools import reduce\nfrom IPython.display import display, Markdown as md\n\ndef getPeriodDF(period, publish_date, csv_path, columns_src, columns_dst, transforms = []):\n    # given a csv_path, extract src columns into dst columns by applying a transform function for a certain period name\n    df_src = pd.read_csv(csv_path)\n    df_dst = pd.DataFrame(columns=['period', 'publish_date']+columns_dst)\n    df_dst[columns_dst] = df_src[columns_src]\n    df_dst['period'] = period\n    df_dst['publish_date'] = pd.to_datetime(publish_date)\n    # apply custom transformations\n    for transform in transforms:\n        df_src, df_dst = transform(df_src, df_dst)\n    return df_dst\n\ndef transformNormalize(df_src, df_dst):\n    # cast to float the salary column, some datasets gets wrongly parsed due to crappy user input\n    df_dst['salary'] = df_dst['salary'].astype(float)\n    df_dst['age'] = df_dst['age'].astype(str)\n    # normalize stack column\n    re_separator = ' *, *| *; *| *\\. *| *\\| *| *\\/ *| *- *'\n    re_garbage = '\"\"\"|\\*|nan|='\n    df_dst['stack'] = df_dst['stack'].apply(lambda s: re.split(re_separator, re.sub(re_garbage, '', str(s)).strip().lower()))\n    # munge the dataset, removing entries that we consider not realistic for our analysis\n    munging_mask = (df_dst.salary > 5000) & (df_dst.salary < 300000)\n    df_src = df_src.loc[munging_mask]\n    df_dst = df_dst.loc[munging_mask]\n    return df_src, df_dst\n\ndef transformNet2Brute(df_src, df_dst):\n    # filter wether net or brute income\n    mask = np.array(df_src['Bruto o neto?'].str.contains('Neto'), dtype = bool)\n    net_factor = np.array([1.0] * len(df_dst));\n    # scales up net salary into brute, given Argentina's social security contributions\n    net_factor[ mask ] = 1/0.83\n    df_dst['salary'] = net_factor * df_dst['salary']\n    return df_src, df_dst\n\ndef transformNet2Brute201702(df_src, df_dst):\n    # filter wether net or brute income\n    mask = np.array(df_src['\u00bfPorcentaje, bruto o neto?'].str.contains('Neto'), dtype = bool)\n    net_factor = np.array([1.0] * len(df_dst));\n    # scales up net salary into brute, given Argentina's social security contributions\n    net_factor[ mask ] = 1/0.83\n    df_dst['salary'] = net_factor * df_dst['salary']\n    return df_src, df_dst\n\nsrc_common_cols = [\n    'Tengo',\n    'A\u00f1os de experiencia',\n    'A\u00f1os en el puesto actual',\n    'Trabajo de',\n    'Tecnolog\u00edas que utiliz\u00e1s']\n\ndst_cols = [\n    'salary',\n    'location',\n    'age',\n    'yoe',\n    'yip',\n    'role',\n    'stack']\n\ndf1 = getPeriodDF('2014.02', '2015-01-01', '../data/2014.02.csv', \n                  ['Salario bruto mensual (AR$)', 'Trabajo en'] + src_common_cols, dst_cols, \n                  [transformNormalize])\n\ndf2 = getPeriodDF('2015.01', '2015-09-01', '../data/2015.01.csv', \n                  ['Salario bruto mensual (AR$)', 'Trabajo en'] + src_common_cols, dst_cols, \n                  [transformNormalize])\n\ndf3 = getPeriodDF('2016.01', '2016-02-01', '../data/2016.01.csv', \n                  ['Salario mensual (AR$)', 'Trabajo en'] + src_common_cols, dst_cols, \n                  [transformNormalize, transformNet2Brute])\n\ndf4 = getPeriodDF('2016.02', '2016-08-01', '../data/2016.02/argentina.csv', \n                  ['Salario mensual (en tu moneda local)', 'Argentina'] + src_common_cols, dst_cols, \n                  [transformNormalize, transformNet2Brute])\n\ndf5 = getPeriodDF('2017.01', '2017-02-01', '../data/2017.01/argentina.csv', \n                  ['Salario mensual (en tu moneda local)', 'Argentina'] + src_common_cols, dst_cols, \n                  [transformNormalize, transformNet2Brute])\n\ndf6 = getPeriodDF('2017.02', '2017-09-01', '../data/2017.02/argentina.csv', \n                  ['Salario mensual (en tu moneda local)', 'Argentina'] + src_common_cols, dst_cols, \n                  [transformNormalize, transformNet2Brute201702])\n\n# compute the union of all the datasets as a signe pandas dataframe\ndf = pd.concat([df1, df2, df3, df4, df5, df6])\n\n# extract the list of periods\nperiods = df.period.unique()\n\n# extract the list of roles\nroles = df.role.unique()\n\n# generate a list of colors by period for easy visualization on next figures\ncolors = cm.rainbow(np.linspace(0, 1, len(periods)))\n\n# extract the list of stacks\nall_stacks = reduce(lambda res, it: np.concatenate((res, it)), df['stack'], np.array([]))\ndata = np.transpose(np.unique(all_stacks, return_counts=True))\ndfs = pd.DataFrame(data, columns=['stack', 'count'])\ndfs['count'] = dfs['count'].astype(int)\n\n# extract the list of roles\ndata = np.transpose(np.unique(df['role'].apply(lambda s: s.strip()), return_counts=True))\ndfr = pd.DataFrame(data, columns=['role', 'count'])\ndfr['count'] = dfr['count'].astype(int)\n\n# create a dataframe with the most frequent stack names and mask of rows in main df matching it\ndfs = dfs.query('count > 100 & stack != \"\"').sort_values(by=['count'], ascending=[0])\ndfs['df_mask'] = dfs['stack'].apply(lambda stack: np.array(df['stack'].apply(lambda s: np.isin(stack, s))))\n\n# create a dataframe with the most frequent role names and mask of rows in main df matching it\ndfr = dfr.query('count > 100 & role != \"\"').sort_values(by=['count'], ascending=[0])\ndfr['df_mask'] = dfr['role'].apply(lambda role: np.array(df['role'] == role))\n\n# show results\ndisplay(md('# Normalized data'))\ndisplay(md('## Survey entries'))\ndisplay(df.head())\n# we take only the top stacks/roles because the fields were free-text, and this resulted\n# in many outliers, ie: random text without continuity for a proper time-series analysis\ndisplay(md('## Top stacks: names, frquency and entries mask'))\ndisplay(dfs.head())\ndisplay(md('## Top roles: names, frquency and entries mask'))\ndisplay(dfr.head())\n```\n\n\n# Normalized data\n\n\n\n## Survey entries\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>period</th>\n      <th>publish_date</th>\n      <th>salary</th>\n      <th>location</th>\n      <th>age</th>\n      <th>yoe</th>\n      <th>yip</th>\n      <th>role</th>\n      <th>stack</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>2014.02</td>\n      <td>2015-01-01</td>\n      <td>21000.00</td>\n      <td>Ciudad Aut\u00f3noma de Buenos Aires</td>\n      <td>27 - 30</td>\n      <td>5 - 7</td>\n      <td>Menos de un a\u00f1o</td>\n      <td>SysAdmin</td>\n      <td>[linux, cloud]</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2014.02</td>\n      <td>2015-01-01</td>\n      <td>10000.00</td>\n      <td>Ciudad Aut\u00f3noma de Buenos Aires</td>\n      <td>35 - 40</td>\n      <td>10+</td>\n      <td>2 - 4</td>\n      <td>SysAdmin</td>\n      <td>[linux]</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2014.02</td>\n      <td>2015-01-01</td>\n      <td>16000.00</td>\n      <td>C\u00f3rdoba</td>\n      <td>27 - 30</td>\n      <td>3 - 5</td>\n      <td>1 - 2</td>\n      <td>DevOps</td>\n      <td>[linux, cloud]</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>2014.02</td>\n      <td>2015-01-01</td>\n      <td>23771.13</td>\n      <td>Ciudad Aut\u00f3noma de Buenos Aires</td>\n      <td>27 - 30</td>\n      <td>5 - 7</td>\n      <td>1 - 2</td>\n      <td>SysAdmin</td>\n      <td>[linux]</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>2014.02</td>\n      <td>2015-01-01</td>\n      <td>16000.00</td>\n      <td>Ciudad Aut\u00f3noma de Buenos Aires</td>\n      <td>30 - 33</td>\n      <td>10+</td>\n      <td>2 - 4</td>\n      <td>DevOps</td>\n      <td>[linux]</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Top stacks: names, frquency and entries mask\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>stack</th>\n      <th>count</th>\n      <th>df_mask</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>712</th>\n      <td>windows</td>\n      <td>4958</td>\n      <td>[False, False, False, False, False, False, Fal...</td>\n    </tr>\n    <tr>\n      <th>320</th>\n      <td>linux</td>\n      <td>3988</td>\n      <td>[True, True, True, True, True, False, False, F...</td>\n    </tr>\n    <tr>\n      <th>692</th>\n      <td>vmware</td>\n      <td>2193</td>\n      <td>[False, False, False, False, False, False, Fal...</td>\n    </tr>\n    <tr>\n      <th>124</th>\n      <td>containers</td>\n      <td>817</td>\n      <td>[False, False, False, False, False, False, Fal...</td>\n    </tr>\n    <tr>\n      <th>154</th>\n      <td>docker</td>\n      <td>817</td>\n      <td>[False, False, False, False, False, False, Fal...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Top roles: names, frquency and entries mask\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>role</th>\n      <th>count</th>\n      <th>df_mask</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>480</th>\n      <td>Developer</td>\n      <td>6195</td>\n      <td>[False, False, False, False, False, False, Fal...</td>\n    </tr>\n    <tr>\n      <th>1409</th>\n      <td>SysAdmin / DevOps</td>\n      <td>2905</td>\n      <td>[False, False, False, False, False, False, Fal...</td>\n    </tr>\n    <tr>\n      <th>679</th>\n      <td>HelpDesk</td>\n      <td>2162</td>\n      <td>[False, False, False, False, False, False, Fal...</td>\n    </tr>\n    <tr>\n      <th>976</th>\n      <td>Networking</td>\n      <td>1142</td>\n      <td>[False, False, False, False, False, False, Tru...</td>\n    </tr>\n    <tr>\n      <th>1057</th>\n      <td>PM</td>\n      <td>767</td>\n      <td>[False, False, False, False, False, True, Fals...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n```python\nimport scipy.stats as sps\nimport matplotlib.pyplot as plt\n\ndef getPlotSalarySeries(currencySeries):\n    s = currencySeries.apply(lambda x: float('{0:.2f}'.format(round(x/1000, 1))))\n    mu, sigma = np.mean(s), np.std(s)\n    median = np.median(s)\n    t = np.linspace(mu - 3*sigma, mu + 3*sigma, 1000)\n    d = sigma**2/mu\n    return mu, sigma, t, d, median, s\n\n\ndfrt = pd.DataFrame(columns=['role', 'count', 'mu', 'sigma', 'period', 'publish_date'])\n\ni = 0\nfor period in periods:\n    for j, row in dfr.iterrows():\n        dfrs = df.loc[ row['df_mask'] & (df['period'] == period) ]\n        if len(dfrs) == 0: continue\n        mu, sigma, t, d, m, s = getPlotSalarySeries(dfrs['salary'])\n        dfrt.loc[i] = [row['role'], len(dfrs), mu, sigma, period, np.max(dfrs['publish_date'])]\n        i = i+1\n\n# the ranking of technologies most frequent in the datasets order by mean of salary\ndfrt = dfrt.query('count > 1').sort_values(by=['role', 'period'], ascending=[0, 0])\ndisplay(md('## Top roles: numbers by period'))\ndfrt.head()\n```\n\n\n## Top roles: numbers by period\n\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>role</th>\n      <th>count</th>\n      <th>mu</th>\n      <th>sigma</th>\n      <th>period</th>\n      <th>publish_date</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>59</th>\n      <td>SysAdmin / DevOps</td>\n      <td>639.0</td>\n      <td>34.385915</td>\n      <td>15.772861</td>\n      <td>2017.02</td>\n      <td>2017-09-01</td>\n    </tr>\n    <tr>\n      <th>47</th>\n      <td>SysAdmin / DevOps</td>\n      <td>640.0</td>\n      <td>28.695000</td>\n      <td>14.261597</td>\n      <td>2017.01</td>\n      <td>2017-02-01</td>\n    </tr>\n    <tr>\n      <th>35</th>\n      <td>SysAdmin / DevOps</td>\n      <td>636.0</td>\n      <td>24.607075</td>\n      <td>11.653473</td>\n      <td>2016.02</td>\n      <td>2016-08-01</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>SysAdmin / DevOps</td>\n      <td>990.0</td>\n      <td>20.572828</td>\n      <td>13.491941</td>\n      <td>2016.01</td>\n      <td>2016-02-01</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>SysAdmin</td>\n      <td>248.0</td>\n      <td>18.471371</td>\n      <td>8.054694</td>\n      <td>2015.01</td>\n      <td>2015-09-01</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nimport matplotlib.patches as mpatches\n\n%matplotlib inline\nplt.style.use(['classic', 'ggplot'])\nplt.rcParams.update({'figure.figsize': (10.0, 6.0), 'font.size': 8})\n\ntrending_roles = np.unique(dfrt['role'])\nroles_colors = cm.rainbow(np.linspace(0, 1, len(trending_roles)))\npublish_dates = np.unique(dfrt['publish_date'])\n\ny = []\nfor i, role in enumerate(trending_roles):\n    role_y = []\n    for j, date in enumerate(publish_dates):\n        dfrs = dfrt.query('role == @role & publish_date == @date')\n        count = 0 if len(dfrs['count']) == 0 else dfrs['count'].values[0]\n        role_y.append(count)\n    y.append(role_y)\n\n# define data points for stackplot\nx = publish_dates\ny = np.row_stack(y)\npercent = np.divide(y, y.sum(axis=0).astype(float) * 100)\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.stackplot(x, percent, colors=roles_colors)\nax.set_title('Level of participation in surveys by role across time')\nax.set_ylabel('Percent (%)')\n\n# creating the legend manually\nplt.legend([mpatches.Patch(color=roles_colors[i]) for i, role in enumerate(trending_roles)],\n           trending_roles, \n           bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n\n    \ndisplay(md('## Level of participation in surveys by role'))\ndisplay(md(\"\"\"\nThis initial graph aims to help understanding who participated in the surveys on each period.\n\nIt is very important to understand the universe of samples, which may be a segment of the entire tech community in Argentina. There're reasons to think on this.\nA valid one is that SysArmy may have started as group of sysadmins/security guys -mainly, perhaps due to the topics they post about-, then spreaded more to the devs community.\n\nIn order to prove this hypothesis, we graph the percentual level of participation by role (only top roles).\n\"\"\"))\nplt.show()\ndisplay(md(\"\"\"\nThe results threw that Developers were from the beginning the majority group.  This is against the initial hypothesis, but not so falsy, neither the last conclusion:\n1. It is clearly visible that the Developers group has grew through time starting on September 2015.\n2. Helpdesk however, have decreased since February 2016.\n3. \"Storage / Backup\" have falled and then dissapeared.\n4. \"Otro\" (others) has been raising from the begining -then dissapeared-, but marked the tendency of the universe of samples which tends to diverge in respect to the role.\n5. The rest of roles maintain some consistency over time.\n\"\"\"))\n```\n\n## Histogram of Incomes by period (Argentina)\n\n\n```python\n%matplotlib inline\nplt.rcParams.update({'figure.figsize': (10.0, 18.0), 'font.size': 8})\nfig, ax = plt.subplots(len(periods), 1)\nfor i, period in enumerate(periods):\n    dft = df[df['period'] == period]\n    mu, sigma, t, d, m, s = getPlotSalarySeries(dft.salary)\n    n, bins, patches = ax[i].hist(s, 160, normed=1, alpha=0.75, color=colors[i])\n    ax[i].set_ylabel('density')\n    ax[i].set_title(period + ' Histogram of Income')\n    ax[i].text(40, .025, '$\\mu=%.2f,\\ \\sigma=%.2f,\\ n=%d$' % (mu, sigma, len(s)))\n    ax[i].axis([0, 160, 0, 0.1])\n    ax[i].grid(True)\nax[len(periods)-1].set_xlabel('income [1000 AR$/mo]')\nfig.canvas.draw()\n\ndisplay(md('## Density by range of salary'))\ndisplay(md(\"\"\"\nThe following figures shows the density ranges of income for the Universe (Argentina samples) across time.\nThe histograms helps understand the probability density functions behind the data, which present some postive skew,\nand a tendency to be shifted to the right through time (inflation adjustments).\n\nIt is also noticeable that the levels of dispersion increases since 2015, something that we will analyize next.\n\"\"\"))\ndisplay(plt.show())\n```\n\n## Mean and Standard deviation evolution\n\nThe following graph represents the income mean $\\mu$ across time, along with the standard deviation $\\sigma$.\nThis is an interesting time-series information, because describes better the raise in currency numbers (not purchasing power) of salaries.  The tendency is the growthness, which is for sure good, reflecting a correction over time of the numbers due to the inflation.\n\nThe next question would be, Are these corrections enough to at least maintain some stability on the purchasing levels?\nTo answer this, we may need information about levels of inflation.  As described in the Datasets section, there's no good data available of inflation in Argentina.  A workaround to help answer this question, from a different perspective, but a valid one, is to base the analysis on the dollar currency and see the evolution of income (cotinue reading).\n\n\n```python\n%matplotlib inline\nplt.rcParams.update({'figure.figsize': (10.0, 6.0), 'font.size': 8})\nmus, sigmas, dates = [], [], []\nfor period in periods:\n    dft = df[df['period'].str.contains(period)]\n    mu, sigma, t, d, m, s = getPlotSalarySeries(dft.salary)\n    mus.append(mu)\n    sigmas.append(sigma)\n    dates.append(np.max(dft['publish_date']))\n    \nplt.plot(dates, mus, '+', label='$\\mu$', ls='-', c='b')\nplt.plot(dates, sigmas, '+', label='$\\sigma$', ls=':', c='g')\nplt.xlabel('date'); plt.ylabel('income [1000 AR$/mo]')\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n```\n\n### Currency evolution (Argentine Peso)\n\nContinuing with the previous analysis, we obtained the data of AR\\$ to US\\$ over time, of the last 5 years.  The next step would be to sample from these series, only few points of reference for the periods that our surveys datasets correspond.\n\nSo we plot below, the peso evolution in green, and overlapped in blue, the sampled values of these series for the periods of our interest.\n\n\n```python\nimport json\nimport datetime\nwith open('../data/usdars-cur.json') as data_file:    \n    data = json.load(data_file)  \n    df_currency = pd.DataFrame(data[0]['price'])\n    df_currency.date = pd.to_datetime(df_currency.date)\n\n%matplotlib inline\nplt.rcParams.update({'figure.figsize': (10.0, 6.0), 'font.size': 8})\ndelta = datetime.timedelta(days=15)\ncurrencies = []\nfor date in dates:\n    currency_series = df_currency[(df_currency.date >= date-delta) & (df_currency.date <= date+delta)]\n    currencies.append(float(currency_series.value[:1]))\n\nplt.xlabel('date'); plt.ylabel('1US\\$ [AR\\$]')\nplt.plot(dates, currencies, '+', label='sampled currency for the chosen periods', ls='-', c='b')\nplt.plot(df_currency.date, df_currency.value, label='by date currency from Bloomberg.com', ls='-', c='g')\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n```\n\n## Monthly nominal GDP\n\nOnce obtained the peso value in dollar currency, we calculate the salaries mean $\\mu$ over time, in dollars:\nMonthly Gross Domestic Product, in US dollars, tell us the purchasing capacity of Argentines salaries in nominal values.  To compute the values, we just divide each $\\mu$ in pesos by the dollar rate at its given moment.\n\n$$\n\\sum_i{nom(GDP_i)} = \\sum_i{\\mu_i US\\$} = \\sum_i{\\frac {\\mu_i AR\\$}{exchrate_i{\\frac {AR\\$}{US\\$}}}}\n$$\n\nThe results can be compared with World Bank data for Argentina provided here:\n\nhttp://data.worldbank.org/indicator/NY.GDP.PCAP.PP.CD?end=2016&locations=AR&start=2010\n\n\n```python\n%matplotlib inline\nplt.rcParams.update({'figure.figsize': (13.0, 5.0), 'font.size': 8})\n\nfig, ax = plt.subplots(1, 2)\nax[0].set_xlabel('date'); ax[0].set_ylabel('income [1000/mo]')\nax[0].plot(dates, mus, '+', label='$\\mu$ AR\\$', ls='-', c='b')\nax[0].legend()\n\nax[1].set_xlabel('date'); ax[1].set_ylabel('income [1000/mo]')\nax[1].plot(dates, np.divide(mus, currencies), '+', label='$\\mu$ US\\$', ls='-', c='r')\nax[1].legend()\nfig.canvas.draw()\n\ndisplay(md(\"\"\"\n### Evolution of mean income in AR$ (left), in US\\$ (right)\n\nAs the figure show (left), the salary in pesos continuosly grows.\nThere's however, an interesting plateau in between the end of 2015 and beginning of 2016.\nThe two periods occurred before and after the Argentina presidential elections of October/December 2015.\nIt mustn't be coincidence that the numbers got practically freezed, perhaps due to the uncertainty caused by such national event.\n\nThere's another clear insight that we can identify on the figure at the right side.\nSadly the income in dollars falled down dramatically right after the elections.  This was due to the removal of the \"cepo cambiario\", \nwhich came along with a drastic devaluation of the local currency: http://www.bbc.com/mundo/noticias/2015/12/151217_argentina_fin_cepo_devaluacion_irm\n\"\"\"))\ndisplay(plt.show())\n```\n\n\n\n## Distribution of Income by period (Argentina)\n\n### Assuming Normal distribution\n\nDespite the fact that histograms throw distributions more similar to a $\\gamma$ (Gamma) function, and the marked possitive skewness, for simplicity we will use the $N$ (Gaussian) distribution.\n\n* Probability density function \n \n$$\n\\large\n{\\displaystyle f(x\\;|\\;\\mu ,\\sigma ^{2})={\\frac {1}{\\sqrt {2\\pi \\sigma ^{2}}}}\\;e^{-{\\frac {(x-\\mu )^{2}}{2\\sigma ^{2}}}}}\n$$\n \n* Gaussian density paramters \n \n$$\n\\large \n\\begin{align} \n\\mu &= \\frac{1}{N} \\sum_i x_i \\\\ \n\\sigma^2 &= \\frac{1}{N} \\sum_i x_i^2 \n\\end{align} \n$$\n\nThe following figure, shows for the full dataset by period, the mean ($\\mu$), and the standard deviation ($\\sigma$).  It is noticieable the shifting to the right of the curves across time, indicating that salaries somehow followed the inflation tendency.\n\nA new insight can be distinguished from this graph: the standard deviation of the salaries (the amplitude of the gaussian shape) starts increasing since 2016.  Once again, after the presidential elections, the course of the economy changed, and then the rules and behavior of salaries.\nHere, an interpretation would be, that the tendency of incomes is now more sparse, meaning that for the same type of work and experience -in general- there's people with totally different salaries (wider ranges).\n\n\n```python\n%matplotlib inline\nplt.rcParams.update({'figure.figsize': (10.0, 6.0), 'font.size': 8})\nplt.xlim(0,100)\nfor i, period in enumerate(periods):\n    dft = df[df.period.str.contains(period)]\n    mu, sigma, t, d, m, s = getPlotSalarySeries(dft.salary)\n    plt.plot(t, sps.norm.pdf(t, mu, sigma), label=period + '\\n$\\mu=%.2f,\\ \\sigma=%.2f,\\ n=%d$\\n' % (mu, sigma, len(s)), ls='-', c=colors[i])\n    plt.axvline(x=mu, ls=':', c=colors[i])\nplt.xlabel('income [1000 AR$/mo]'); plt.ylabel('density, $N$')\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n```\n\n## Interactive dynamic dashboard\n\nThe next figure is dynamic. It has some controls that lets you to filter data and so, refresh the visualization comparing diferent dimensionality reductions, with the average by dataset, using the probability denstiy functions as curve.\n\n_NOTE: in order to make this work, you may need to run this notebook locally, using Jupyter Notebooks_\n\n\n```python\nfrom IPython.display import clear_output\nimport ipywidgets as widgets\n\nfilters = ['role', 'yoe', 'yip', 'location', 'age']\ni_filters = [{'name': r, 'i': i} for i, r in enumerate(filters)]\nfilters_opts = list(map(lambda r: list(df[r].unique()), filters))\nfilters_checkboxes = list(map(lambda r: widgets.Checkbox(value=False, description='Use '+r, name='use_'+r, disabled=False), filters))\nfilters_dropdowns = list(map(lambda r: widgets.Dropdown(options=filters_opts[r['i']], value=filters_opts[r['i']][0], name=r['name'], description=r['name']+':', disabled=not filters_checkboxes[r['i']].value), i_filters))\n\n%matplotlib notebook\nplt.rcParams.update({'figure.figsize': (13.0, 6.0), 'font.size': 8})\nfig, ax = plt.subplots()\nax.set_xlim(-20,100)\nax.set_ylim(0,0.08)\nax.set_xlabel('income [1000 AR$/mo]'); ax.set_ylabel('density, $N$')\n\ndef on_filters_change(change):\n    for i in range(len(filters)):\n        checkbox = filters_checkboxes[i]\n        dropdown = filters_dropdowns[i]\n        if change['owner'].name == checkbox.name:\n            dropdown.disabled = not change['new']\n            break\n    plot_filtered_monthly_income()\n\ndef plot_filtered_monthly_income(change = None):\n    plt.rcParams.update({'figure.figsize': (10.0, 8.0), 'font.size': 8})\n    if not ax.lines:\n        for i, period in enumerate(periods):\n            dft = df[df.period.str.contains(period)]\n            mu, sigma, t, d, m, s = getPlotSalarySeries(dft.salary)            \n            ax.plot(t, sps.norm.pdf(t, mu, sigma), label=period, ls=':', c=colors[i])\n            ax.plot(t, sps.norm.pdf(t, mu, sigma), label=period + ' $\\mu=%.2f,\\ \\sigma=%.2f,\\ n=%d$' % (mu, sigma, len(s)), ls='-', c=colors[i])\n    else:\n        for i, period in enumerate(periods):\n            dft = df[df.period.str.contains(period)]\n            for dropdown in filters_dropdowns:\n                dft = dft if dropdown.disabled else dft[dft[dropdown.name].str.contains(dropdown.value)]\n            mu, sigma, t, d, m, s = getPlotSalarySeries(dft.salary)\n            line = ax.lines[2*i+1]\n            if len(dft) > 2:\n                line.set_xdata(t)\n                line.set_ydata(sps.norm.pdf(t, mu, sigma))\n                line.set_label(period + ' $\\mu=%.2f,\\ \\sigma=%.2f,\\ n=%d$' % (mu, sigma, len(s)))\n            else:\n                line.set_xdata([]), line.set_ydata([])\n    title = 'Segment:' + ''.join([\n        '' if dropdown.disabled else ' %s: %s' % (dropdown.name, dropdown.value)\n            for dropdown in filters_dropdowns])\n    ax.set_title(title)\n    ax.legend(bbox_to_anchor=(1.05, 1), loc=1, borderaxespad=0.)\n    ax.grid(True)\n    fig.canvas.draw()\n    plt.ion()\n    plt.show()\n\nboxes = []\nfor i in range(len(filters_dropdowns)):\n    filters_checkboxes[i].observe(on_filters_change, names='value')\n    filters_dropdowns[i].observe(plot_filtered_monthly_income, names='value')\n    boxes.append(widgets.Box([filters_checkboxes[i], filters_dropdowns[i]]))\n\ndisplay(widgets.Box(boxes))\nplot_filtered_monthly_income()\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n## Comparative analysis by technology\n\nBelow, we will rank technologies by most frequent.  We will exclude technologies with less than 100 samples in total -because they are in most cases, isolated, and doesn't follow clear trends.\n\nFrom the resulting table we will plot the results in two ways:\n\n1. First as a time-series comparative of the technologies by period, indicatin the $\\mu$ mean salary.\n2. Secondly, as a scatter, having the salary mean $\\mu$ in the X axis, the standard deviation $\\sigma$ in the Y axis and the amount of samples as the size of the dot.\n\n\n```python\ndfst = pd.DataFrame(columns=['stack', 'count', 'mu', 'sigma', 'period', 'publish_date'])\n\ni = 0\nfor period in periods:\n    for j, row in dfs.iterrows():\n        dfss = df.loc[ row['df_mask'] & (df['period'] == period) ]\n        if len(dfss) == 0: continue\n        mu, sigma, t, d, m, s = getPlotSalarySeries(dfss['salary'])\n        dfst.loc[i] = [row['stack'], len(dfss), mu, sigma, period, np.max(dfss['publish_date'])]\n        i = i+1\n\n# the ranking of technologies most frequent in the datasets order by mean of salary\ndfst = dfst.query('count >= 1').sort_values(by=['stack', 'period'], ascending=[0, 0])\ndisplay(md('## Top stacks: numbers by period'))\ndfst.head()\n```\n\n\n## Top stacks: numbers by period\n\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>stack</th>\n      <th>count</th>\n      <th>mu</th>\n      <th>sigma</th>\n      <th>period</th>\n      <th>publish_date</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>61</th>\n      <td>windows</td>\n      <td>459.0</td>\n      <td>32.508061</td>\n      <td>15.077103</td>\n      <td>2017.02</td>\n      <td>2017-09-01</td>\n    </tr>\n    <tr>\n      <th>48</th>\n      <td>windows</td>\n      <td>2844.0</td>\n      <td>25.242827</td>\n      <td>13.018835</td>\n      <td>2017.01</td>\n      <td>2017-02-01</td>\n    </tr>\n    <tr>\n      <th>34</th>\n      <td>windows</td>\n      <td>512.0</td>\n      <td>23.590430</td>\n      <td>9.715138</td>\n      <td>2016.02</td>\n      <td>2016-08-01</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>windows</td>\n      <td>831.0</td>\n      <td>19.829122</td>\n      <td>13.524452</td>\n      <td>2016.01</td>\n      <td>2016-02-01</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>windows</td>\n      <td>177.0</td>\n      <td>18.333898</td>\n      <td>11.019761</td>\n      <td>2015.01</td>\n      <td>2015-09-01</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n%matplotlib inline\nplt.rcParams.update({'figure.figsize': (10.0, 6.0), 'font.size': 8})\n\ntrending_stacks = np.unique(dfst['stack'])\nstacks_colors = cm.rainbow(np.linspace(0, 1, len(trending_stacks)))\nfor i, stack in enumerate(trending_stacks):\n    dfp = dfst.query('stack == @stack')\n    plt.plot(dfp['publish_date'], dfp['mu'], '+', label='$\\mu$ AR\\$ %s' % stack, ls='-', c=stacks_colors[i])\n    plt.xlabel('date'); plt.ylabel('$\\mu$')\n    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\ndisplay(md('## Mean salary of the most frequent technologies (stacks) through time'))\n```\n\n\n```python\n%matplotlib inline\nplt.rcParams.update({'figure.figsize': (13.0, 30.0), 'font.size': 10})\n\nfig, ax = plt.subplots(len(periods), 1)\nfor i, period in enumerate(periods):\n    ## plot only the top ranked technologies in terms of salary for the period sample\n    dftss = dfst.query(\"@period == period\").sort_values(by=['mu', 'sigma'], ascending=[0, 0])[:30]\n    ax[i].scatter(\n        dftss['sigma'], dftss['mu'], marker='o', c=dftss.index, s=100*dftss['count']**(1/2), alpha=0.3,\n        cmap=plt.get_cmap('Spectral'))\n\n    for label, x, y in zip(dftss['stack'], dftss['sigma'], dftss['mu']):\n        ax[i].annotate(\n            label,\n            xy=(x, y), xytext=(30, -30),\n            textcoords='offset points', ha='right', va='bottom',\n            bbox=dict(boxstyle='round,pad=0.5', fc='white', alpha=0.5),\n            arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))\n\n    ax[i].set_xlabel('$\\mu$'); ax[i].set_ylabel('$\\sigma$')\n    ax[i].set_title('%s - Technologies by salary, standard deviation and num of samples.' % period)\n    fig.canvas.draw()\ndisplay(md('## Scatter of technologies by mean, dispersion, frequency and time'))\ndisplay(md('_NOTE: It\\'s pending for these results to drive some conclusion (WIP)._'))\ndisplay(md('_NOTE: The circles radius represents the frequency (number of entries) by stack in an inversely cuadratic representation._'))\n```\n", "meta": {"hexsha": "c321b9fadfb6873969983944658a305755e37bed", "size": 933114, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/intra_period_argentina.ipynb", "max_stars_repo_name": "gerardobort/sysarmy-data", "max_stars_repo_head_hexsha": "55863737777b89071dfae7732d334796c9e89b9b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-08-07T21:50:12.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-14T19:28:02.000Z", "max_issues_repo_path": "notebooks/intra_period_argentina.ipynb", "max_issues_repo_name": "gerardobort/sysarmy-data", "max_issues_repo_head_hexsha": "55863737777b89071dfae7732d334796c9e89b9b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/intra_period_argentina.ipynb", "max_forks_repo_name": "gerardobort/sysarmy-data", "max_forks_repo_head_hexsha": "55863737777b89071dfae7732d334796c9e89b9b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-09-13T18:28:59.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-07T20:18:54.000Z", "avg_line_length": 306.4413793103, "max_line_length": 225796, "alphanum_fraction": 0.8936207152, "converted": true, "num_tokens": 9618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.08269734493579813, "lm_q1q2_score": 0.0321376790027628}}
{"text": "```python\ntry:\n    import openmdao.api as om\n    import dymos as dm\nexcept ImportError:\n    !python -m pip install openmdao[notebooks]\n    !python -m pip install dymos[docs]\n    import openmdao.api as om\n    import dymos as dm\n```\n\n# Organizing Phases into Trajectories\n\nThe majority of real-world use cases of optimal control involve complex trajectories that cannot be modeled with a single phase.\nFor instance, different phases of a trajectory may have different equations of motion, different control parameterizations, or different path constraints.\nPhases are also necessary if the user wishes to impose intermediate constraints upon some variable, by imposing them as boundary constraints at a phase junction.\n\nThe *Trajectory* class in Dymos is intended to simplify the development of multi-phase problems.\nIt serves as a Group which contains the various phases belonging to the trajectory, and it provides linkage constraints that dictate how phases are linked together.\nThis enables trajectories that are not only a sequence of phases in time, but may include branching behavior, allowing us to do things like track/constrain the path of a jettisoned rocket stage.\n\nIt supports a `get_values` method similar to that of Phases that allows the user to retrieve the value of a variable within the trajectory.\nWhen verifying an answer with explicit simulation, the `simulate` method of Trajectory can simulate all of its member phases in parallel, providing a significant performance improvement for some cases.\n\n## Instantiating a Trajectory\n\nInstantiating a Trajectory is simple.  Simply invoke `Trajectory()`.  The trajectory object\nitself is an OpenMDAO `Group` which serves as a container for its constituent Phases.\n\n- phases\n    An OpenMDAO `Group` or `ParallelGroup` holding the member phases\n- linkages\n    A Dymos `PhaseLinkageComp` that manages all of the linkage constraints that dictate how the phases are connected.\n\n## Adding Phases\n\nPhases are added to a Trajectory using the `add_phase` method.\n\n```{eval-rst}\n    .. automethod:: dymos.Trajectory.add_phase\n        :noindex:\n```\n\n##  Defining Phase Linkages\n\nHaving added phases to the Trajectory, they now exist as independent Groups within the OpenMDAO model.\nIn order to enforce continuity among certain variables across phases, the user must declare which variables are to be continuous in value at each phase boundary.\nThere are two methods in dymos which provide this functionality.\nThe `add_linkage_constraint` method provides a very general way of coupling two phases together.\nIt does so by generating a constraint of the following form:\n\n\\begin{align}\n    c = \\mathrm{sign}_a \\mathrm{var}_a + \\mathrm{sign}_b \\mathrm{var}_b\n\\end{align}\n\nMethod `add_linkage_constraint` lets the user specify the variables and phases to be compared for this constraint, as well as the location of the variable in each phase (either 'initial' or 'final')\nBy default this method is setup to provide continuity in a variable between two phases:\n- the sign of variable `a` is +1 while the sign of variable `b` is -1.\n- the location of variable `a` is 'final' while the location of variable `b` is 'initial'.\n- the default value of the constrained quantity is 0.0.\n\nIn this way, the default behavior constrains the final value of some variable in phase `a` to be the same as the initial value of some variable in phase `b`.\nOther values for these options can provide other functionality.\nFor instance, to simulate a mass jettison, we could require that the initial value of `mass` in phase `b` be 1000 kg less than the value of mass at the end of phase `a`.\nProviding arguments `equals = 1000, units='kg` would achieve this.\n\nSimilarly, specifying other values for the locations of the variables in each phase can be used to ensure that two phases start or end at the same condition - such as the case in a branching trajectory or a rendezvous.\n\nWhile `add_linkage_constraint` gives the user a powerful capability, providing simple state and time continuity across multiple phases would be a very verbose undertaking using this method.\nThe `link_phases` method is intended to simplify this process.\nIn the finite-burn orbit raising example, there are three phases:  `burn1`, `coast`, `burn2`.\nThis case is somewhat unusual in that the thrust acceleration is modeled as a state variable.  \nThe acceleration needs to be zero in the coast phase, but continuous between `burn1` and `burn2`, assuming no mass was jettisoned during the coast and that the thrust magnitude doesn't change.\n\n### add_linkage_constraint\n\n```{eval-rst}\n    .. automethod:: dymos.Trajectory.add_linkage_constraint\n        :noindex:\n```\n\n### link_phases\n\n```{eval-rst}\n    .. automethod:: dymos.Trajectory.link_phases\n        :noindex:\n```\n\n## Examples of using the `link_phases` method\n\n**Typical Phase Linkage Sequence**\n\nA typical phase linkage sequence, where all phases use the same ODE (and therefore have\nthe same states), are simply linked sequentially in time.\n\n\n```python\nt.link_phases(['phase1', 'phase2', 'phase3'])\n```\n\n**Adding an Additional Linkage**\n\nIf the user wants some control variable, `u`, to be continuous in value between `phase2` and\n`phase3` only, they could indicate that with the following code:\n\n\n```python\nt.link_phases(['phase2', 'phase3'], vars=['u'])\n```\n\n**Branching Trajectories**\n\nFor a more complex example, consider the case where there are two phases which branch off\nfrom the same point, such as the case of a jettisoned stage.  The nominal trajectory\nconsists of the phase sequence `['a', 'b', 'c']`.  Let phase `['d']` be the phase that tracks\nthe jettisoned component to its impact with the ground.  The linkages in this case\nwould be defined as:\n\n\n```python\nt.link_phases(['a', 'b', 'c'])\nt.link_phases(['b', 'd'])\n```\n\n**Specifying Linkage Locations**\n\nPhase linkages assume that, for each pair, the state/control values at the end (`'final'`)\nof the first phase are linked to the state/control values at the start of the second phase\n(`'initial'`).\n\nThe user can override this behavior, but they must specify a pair of location strings for\neach pair given in `phases`.  For instance, in the following example phases `a` and `b`\nhave the same initial time and state, but phase `c` follows phase `b`.  Note since there\nare three phases provided, there are two linkages and thus two pairs of location\nspecifiers given.\n\n\n```python\nt.link_phases(['a', 'b', 'c'], locs=[('initial', 'initial'), ('final', 'initial')])\n```\n\n##  Trajectory-Level Parameters\n\nOften times, there are parameters which apply to the entirety of a trajectory that potentially need to be optimized.\nIf we implemented these as parameters within each phase individually, we would need some constraints to ensure that they held the same value within each phase.\nTo avoid this complexity, Dymos Trajectory objects support their own Parameters.\n\nLike their Phase-based counterparts, Trajectory parameters produce may be design variables for the problem or used as inputs to the trajectory from external sources.\n\nWhen using Trajectory parameters, their values are connected to each phase as an Input Parameter within the Phase.\nBecause ODEs in different phases may have different names for parameters (e.g. 'mass', 'm', 'm_total', etc) Dymos allows the user to specify the targeted ODE parameters on a phase-by-phase basis using the `targets` and `target_params` option.\nIt can take on the following values.\n\n*  If `targets` is `None` the trajectory parameter will be connected to the phase input parameter of the same name in each phase, if it exists (otherwise it is not connected to that phase).\n\n*  Otherwise targets should be specified as a dictionary. And the behavior depends on the value associated with each phase name:\n\n    * If the phase name is not in the given dictionary, attempt to connect to an existing parameter of the same name in that phase.\n\n    * If the associated value is None, explicitly omit a connection to that phase.\n\n    * If the associated value is a string, connect to an existing input parameter whose name is given by the string in that phase.\n\n    * If the associated value is a Sequence, create an input parameter in that phase connected to the ODE targets given by the Sequence.\n\n## Explicit Simulation of Trajectories\n\nThe `simulate` method on Trajectory is similar to that of the `simulate` method of Phases.  When\ninvoked, it will perform a simulation of each Phase in the trajectory.\n", "meta": {"hexsha": "c73cb1b25479bee925f3da94246bff43cfbdfcaf", "size": 11415, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/features/trajectories/trajectories.ipynb", "max_stars_repo_name": "RutvikM3/dymos", "max_stars_repo_head_hexsha": "b445fff6f27d910007dad48c844c9bc538804122", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-19T17:03:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-19T17:03:49.000Z", "max_issues_repo_path": "docs/features/trajectories/trajectories.ipynb", "max_issues_repo_name": "RutvikM3/dymos", "max_issues_repo_head_hexsha": "b445fff6f27d910007dad48c844c9bc538804122", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/features/trajectories/trajectories.ipynb", "max_forks_repo_name": "RutvikM3/dymos", "max_forks_repo_head_hexsha": "b445fff6f27d910007dad48c844c9bc538804122", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.7356321839, "max_line_length": 251, "alphanum_fraction": 0.6525624179, "converted": true, "num_tokens": 1913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158251284363395, "lm_q2_score": 0.09401017200157857, "lm_q1q2_score": 0.03211223078516145}}
{"text": "<a href=\"https://colab.research.google.com/github/khipu-ai/practicals-2019/blob/master/3a_reinforcement_learning.ipynb\" target=\"_parent\"></a>\n\n# Practical 3A: Reinforcement Learning\n\n\u00a9 Deep Learning Indaba. Apache License 2.0.\n\nAdapted for Khipu.\n\n## Introduction\n\nIn this practical, we will cover the basics of reinforcement learning, which has successfully been used to [control robotic hands](https://openai.com/blog/learning-dexterity/); play [Chess](https://deepmind.com/blog/article/alphazero-shedding-new-light-grand-games-chess-shogi-and-go), [Go](https://en.wikipedia.org/wiki/AlphaGo), and [StarCraft](https://deepmind.com/blog/article/alphastar-mastering-real-time-strategy-game-starcraft-ii). It can even be used for supervised learning problems. For example, training a neural net to optimize a non-differentiable objective (such as accuracy, or the [BLEU score in machine translation](https://arxiv.org/abs/1609.08144)) or [finding a good neural net architecture](https://arxiv.org/abs/1611.01578) for a particular supervised learning problem.\n\n## Learning Objectives\n\n* Understand the problem reinforcement learning tries to solve.\n* Understand the terminology used in reinforcement learning: **environment**, **action**, **observation**, **reward**, **agent**,  **policy**, **episode**.\n* Learn how to use the [OpenAI Gym](https://gym.openai.com/) reinforcement learning environments.\n* Learn how to solve the classic reinforcement learning problem of balancing a pole on a moving cart using Random Search and Policy Gradients. Understand some of the limitations of these methods.\n\n**IMPORTANT: Please fill out the exit ticket form before you leave the practical: https://forms.gle/FLQ78eAEQprsWXp38**\n\n## Imports\n\n\n```python\n#@title Imports (RUN ME!)\n\n\n# Note: enviroments like CartPole-v0 require a display to render. We need to install pyvirtualdisplay etc \n# in order to render from these environments\n\n!pip install pyglet~=1.3.2 > /dev/null 2>&1\n!pip install 'gym[atari]' > /dev/null 2>&1\n!apt-get install python-opengl -y > /dev/null 2>&1\n!apt install xvfb -y > /dev/null 2>&1\n!pip install pyvirtualdisplay > /dev/null 2>&1\n!pip install tensorflow==2.0.0-beta0 > /dev/null 2>&1\n\nfrom IPython.display import HTML\n\n# Start virtual display\nfrom pprint import pprint\nimport logging\nfrom pyvirtualdisplay import Display\nlogging.getLogger(\"pyvirtualdisplay\").setLevel(logging.ERROR)\n\ndisplay = Display(visible=0, size=(1024, 768))\ndisplay.start()\nimport os\nos.environ[\"DISPLAY\"] = \":\" + str(display.display) + \".\" + str(display.screen)\n```\n\n## The Reinforcement Learning Problem\n\nSo far we have encountered **supervised learning**, where we have an input and a target value or class that we want to predict. We have also encountered **unsupervised learning**, where we are only given an input and look for patterns in that input. In this practical, we look into **reinforcement learning**, which can loosely be defined as training an **agent** to maximise the total **reward** it obtains through many interactions with an **environment**.\n\nAt timestep $t$, the agent can make an **observation** of the environment $o_t$. For example, if the environment is a computer game, the observation could be the pixel values of the current screen.\n\nThe environment defines a set of **actions** that an agent can take.  The agent performs an action $a_t$ informed by the observations it has made, and will receive a **reward** $r_t$ from the environment after every action. The *reinforcement learning problem* is to find an agent whose actions maximize the total rewards obtained from the environment over many actions.\n\nThe following diagram illustrates the interaction between the agent and environment. We will explore each of the terms in more detail throughout this practical.\n\n<!--  -->\n\n\n\n\n\n**Optional Recommended Reading**: \n- [*OpenAI Spinning Up: Key Concepts in RL*](https://spinningup.openai.com/en/latest/spinningup/rl_intro.html) is a great summary of the terminology used in reinforcement learning. \n\n### The Environment\n\nWe will focus on the cartpole environment for this practical. This environment consists of a pole attached to a cart via a hinge, with the pole initially balanced close to upright. The agent needs to move the cart to the left or to the right in order to prevent the pole from falling over.\n\n\n\n\nWe will use the OpenAI Gym implementation of the cartpole environment. [OpenAI Gym](https://gym.openai.com/) is probably the most popular set of reinforcement learning environments (the available environments in Gym can be seen [here](https://gym.openai.com/envs)). Every Gym environment has the same interface, allowing code written for one environment to work for all of them. Popular reinforcement learning frameworks, such as [Ray](https://ray.readthedocs.io/en/latest/index.html), often use the Gym interface as [their default interface](https://ray.readthedocs.io/en/latest/rllib-env.html#openai-gym) for reinforcement learning environments.\n\nLet us import Gym and open a cartpole environment:\n\n\n```python\nimport numpy as np\nimport gym\nenv_cartpole = gym.make('CartPole-v1')\n```\n\nThe first step to using a Gym environment is to initialize the environment to some initial configuration using the `reset` method. The `reset` method also returns the first observation of the environment:\n\n\n```python\nenv_cartpole.reset()\n```\n\nThese four numbers represent the position and velocity of the cart and pole, `(cart position, cart velocity, pole angle, velocity of the top of the pole)`. We will want our agent to use this observation when deciding to move left or right. \n\nWe also want to see an image of the system that we can interpret. Gym provides the `render` method to do this:\n\n\n```python\nimport matplotlib.pyplot as plt\nplt.imshow(env_cartpole.render(mode='rgb_array'));\n```\n\nNote that reinitializing this environment with `reset` will randomly change the starting angle of the pole. By running this multiple times, see if you can notice this:\n\n\n```python\nenv_cartpole.reset()\nplt.imshow(env_cartpole.render(mode='rgb_array'));\n```\n\nNow we want to take an action using the `step` method. But which actions are allowed, and how are they represented? We can find this out using the `action_space` property of Gym environments:\n\n\n```python\nenv_cartpole.action_space\n```\n\nIn Gym, `Discrete(n)` means actions are represented by the integers `0,1,...,n-1`. Action spaces always provide a way to take a random action sampled from the space:\n\n\n```python\n[env_cartpole.action_space.sample() for _ in range(10)]\n```\n\nNow let us take an action using the `step` method, which takes an action and returns a tuple `(observation, reward, done, info)`:\n\n\n```python\naction = 1\nenv_cartpole.step(action)\n```\n\n**Question**: Does the action `0` move the cart to the left or to the right? Use the `step` and `render` methods to figure this out.\n\n\nWhat is `done`? Many environments are **episodic**, which means they have a natural end-point, after which more actions cannot be taken. For example in chess, the game ends after a checkmate. In the case of cart-pole, this end-point is when the pole falls down too far. Then no matter the actions taken, the pole will keep falling. Gym will set `done` as `True` in this case, and will print a warning if `step` is called again. The `reset` method needs to be called to reinitialize the environment when `done` is `True`.  We won't use `info` (see the [official Gym docs](https://gym.openai.com/docs/#observations) for more information).\n\nIn addition, many Gym environments have a maximum number of steps they can take, after which `done` is set to `True`. This can be seen using the `_max_episode_steps` property:\n\n\n\n\n```python\nenv_cartpole._max_episode_steps\n```\n\n**Question**: What is an appropriate reward for a game of chess? Suppose the environment is one where your agent plays against an existing chess-playing computer. Remember that there are three outcomes in chess, a win, loss and draw.\n\n#### Question\n\nWrite a function `actions_till_done(env, act)` that takes an environment `env` and action `act`, reinitializes `env` with `reset`, and returns the number of actions taken before `done` is `True`. If you always take the `0` action, how many steps can you take on average before `done` is `True`?\n\nReveal the cell below by double-clicking and running it, to check your answer when you're done or you get stuck!\n\n\n```python\n#@title Answer { display-mode: \"form\" }\ndef actions_till_done(env, action):\n    env.reset()\n    done = False\n    count = 0\n    while done == False:\n        _, _, done, _, = env.step(action)\n        count += 1\n    return count\n  \n# Get an estimate for how many 0 actions you can take on average before the \n# pole falls over\nnp.mean([actions_till_done(env_cartpole, 0) for _ in range(100)])\n```\n\n## Agents and Policies\n\nA **policy** is a function used by an agent to decide what actions to take. This function takes as input an observation and returns either an action (a **deterministic policy**) or a probability distribution over possible actions (a **stochastic policy**).\n\n**Note**: the terms **policy** and **agent** are often used interchangeably:\n> Because the policy is essentially the agent\u2019s brain, it\u2019s not uncommon to substitute the word \u201cpolicy\u201d for \u201cagent\u201d, e.g. saying \u201cThe policy is trying to maximize reward.\u201d ~ [OpenAI Spinning Up](https://spinningup.openai.com/en/latest/spinningup/rl_intro.html#policies)\n\nWe will consider an **agent** to be a function whose input is the observation, and it returns a dictionary which always contains the `\"Action\"` key. It might also contain other keys, such as the action probabilities, the value function, etc. \n\nThe simplest possible policy for a cartpole agent is one that always takes the `0` action, no matter what the observation is:\n\n\n```python\ndef agent_left(observation):\n    return {\"Action\":0}\n```\n\n\n```python\nagent_left(None)\n```\n\n## Rewards and Returns\n\nRecall that in Reinforcement Learning, the **reward** is a scalar signal that the agent observes upon acting on the environment and which it will try to maximize. In the cartpole example, a reward of **+1** is provided for every timestep that the pole remains upright (less than 15 degrees from the vertical). \n\nIs our agent `agent_left` any good? To answer that, we need some measure of 'goodness', which is usually related to the total return obtained during an episode. This is called the **return**, $R$, and there are different ways of defining it. The most obvious definition for return is to simply add up all the rewards the agent received during an episode. If the episode took $T$ steps, and got a reward $r_t$ at each step, then this return is $R = \\sum_{t=1}^{T} r_{t}$, where $r_t$ is the reward received at timestep $t$.\n\nOne issue is that some environments will have different initial states, agents may take actions stochastically and the rewards themselves could be stochastic. The solution is to average the returns over multiple starting points. Here is a function that does this:\n\n\n```python\ndef average_episodic_return(env, agent, episodes=10, max_steps_per_episode=500):\n    episode_rewards = []\n    for episode in range(episodes):\n        total_rewards = 0\n        obs = env.reset()\n        for t in range(max_steps_per_episode):\n            out = agent(obs) # we don't care about the probabilities here\n            assert (\"Action\" in out), \"The key 'Action' was missing from the agents output.\"\n            obs, rew, done, _ = env.step(out[\"Action\"])\n            total_rewards += rew\n            # check if we are done, if so, exit loop\n            if done:\n                break\n                \n        episode_rewards.append(total_rewards)\n        \n    return {\n        \"AverageEpisodicReturn\": np.mean(episode_rewards), \n        \"StandardDeviation\":np.sqrt(np.var(episode_rewards))\n    }\n```\n\nNow we can see how good our agent `agent_left` is:\n\n\n```python\naverage_episodic_return(env_cartpole, agent_left)\n```\n\n## Animating Agents\n\nThis code cell defines a function `animate_agent(environment, agent)` that produces a human understandable animation of the `agent` controlling the `environment`. **Note:** It is not necessary to understand these functions to follow this practical.\n\n\n```python\nfrom collections import deque\nimport matplotlib.animation\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\ndef animate_agent(env, agent, max_steps = 400):\n    obs = env.reset()\n    frames = deque()\n    frames.append(env.render(mode='rgb_array'))\n    for _ in range(max_steps):\n        out = agent(obs)\n        assert (\"Action\" in out), \"The key 'Action' was missing from the agents output.\"\n        action = out[\"Action\"]\n        obs, _ , done, _ = env.step(action)\n        frames.append(env.render(mode='rgb_array'))\n        if done:\n            break\n            \n    return animate_frames(frames)\n\ndef animate_frames(frames):\n    new_height = 2.2\n    original_height = frames[0].shape[0]\n    original_width = frames[0].shape[1]\n    new_width = (new_height / original_height) * original_width\n    fig = plt.figure(figsize=(new_width, new_height), dpi = 120)\n    \n    ax = plt.Axes(fig, [0., 0., 1., 1.])\n    ax.set_axis_off()\n    fig.add_axes(ax)\n    patch = ax.imshow(frames[0], aspect='auto', animated=True, interpolation='bilinear')\n    animate = lambda i: patch.set_data(frames[i])\n    \n    ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(frames), interval = 50)\n    \n    plt.close()\n    return HTML(ani.to_jshtml())\n```\n\nNow we can easily get an animation of the cartpole environment controlled by `policy_left`:\n\n\n```python\ndef agent_left(observation):\n    return {\"Action\":0}\n  \nanimate_agent(env_cartpole, agent_left)\n```\n\n## Agent 1: Random Action Agent\n\nRather than having an agent whose policy is to always take the same action, we could also randomly choose between possible actions\n\n**Question**: would you expect the agent taking random actions to get a higher or lower return than the `agent_left` agent for cartpole?\n\n\n```python\ndef agent_random(observation):\n    return {\"Action\":np.random.choice([0, 1])}\n```\n\n**Note**: that we can easily write a general random agent for any gym environment using `env.action_space.sample()`. \n\nComputing the average return of `agent_random`:\n\n\n```python\naverage_episodic_return(env_cartpole, agent_random)\n```\n\nAnd animating it:\n\n\n```python\nanimate_agent(env_cartpole, agent_random)\n```\n\n### Random Agent Tasks\n\n1. [**ALL**] Create a random agent for \"MsPacman-v0\" environment using `env.action_space.sample()` and animate the agent using `animate_agent` for 300 steps.\n\n\n\n## Agent 2: Neural Net Policy Trained with Random Search\n\nTo improve on the random agent `agent_random`, we need a policy that takes the observation of the environment into account. In this section, we will show how to create an agent that solves the cartpole problem without any fancy reinforcement learning methods.\n\nFirst, define an agent with a single hidden-layer multi-layer perceptron (MLP) policy implemented using NumPy. Its input is a vector of length 4 and its output is either `0` or `1`:\n\n\n```python\nclass AgentMLPNumpy:\n    def __init__(self, num_hidden):\n        self.W1 = np.random.randn(num_hidden, 4)\n        self.W2 = np.random.randn(2, num_hidden)\n        \n    def __call__(self, x):\n        y = self.W1.dot(x)\n        y = np.tanh(y)\n        y = self.W2.dot(y)\n        return {\"Action\":np.argmax(y)}\n```\n\nThe reate an instance of `AgentMLPNumpy` (with random weight initializations), and compute its return. If the return is better than previous agents, then keep this agent. Otherwise, throw it away and try a new randomly initialized agent `AgentMLPNumpy`. Repeat this process `n` times.\n\n### Random Search Tasks\n\n1. [**ALL**] Write a function `find_good_mlp_agent(env, num_tries, mlp_size)` that tries `num_tries` instances of `AgentMLPNumpy`, each with different weights. It should return both the agent that got the best return, along with that return.\n2. [**All**] Try out different values of `num_tries` and `mlp_size` until you find values that produces an agent getting a return of 500. **Hint**: `num_tries` shouldn't need to be larger than 300.\n3. [**ALL**] Visualize your best agent controlling cartpole using `animate_agent`.\n\n### Extra Reading on Random Search\n\nVariations of random search have proven to be very succesful for training agents to solve the reinforcement learning problem. Here are some examples:\n- [Evolution Strategies as a Scalable Alternative to Reinforcement Learning](https://openai.com/blog/evolution-strategies/), OpenAI, 2017\n- [Simple random search provides a competitive approach to reinforcement learning](https://arxiv.org/abs/1803.07055), H. Mania *et al*, 2018\n- [Welcoming the Era of Deep Neuroevolution](https://eng.uber.com/deep-neuroevolution/), Uber AI Labs, 2017\n\nNote that random search used to solve the *reinforcement learning problem* is not generally considered to be a *reinforcement learning method* (as implied by the titles of some of the readings above, eg. \"Evolution Strategies as a Scalable Alternative to Reinforcement Learning\"). The reason for this:\n\n> Reinforcement learning, like many topics whose names end with \u201cing,\u201d such as machine learning and mountaineering, is simultaneously a problem, a class of solution methods that work well on the problem, and the field that studies this problem and its solution methods. It is convenient to use a single name for all three things, but at the same time essential to keep the three conceptually separate. In particular, the distinction between problems and solution methods is very important in reinforcement learning; failing to make this distinction is the source of many confusions. ~ *Reinforcement Learning*, Sutton and Barto, **2nd Edition**\n\n## Agent 3: Neural Net Agent Trained with Policy Gradients\n\nUnlike the random policy, the MLP policy trained with random search *does* take environment observations into account when choosing to take an action. However, the training procedure is clearly not optimal: each policy in the search makes no use of observations and rewards seen by previous policies. For environments where it takes significant time and money to take actions and make observations (for example, a real robot picking strawberries), this is incredibly wasteful. In this section, we present a method that does take previous observations into account when learning.\n\n**Warning**: This section requires more mathematics than previous sections, and hence more precise notation. It will thus be significantly more abstract.\n\n### Policy Gradient Theory\n\nAs we saw earlier, the reinforcement learning problem is to find an agent/policy that maximizes the return (rewards). We will now use a neural net to represent a stochastic policy  $\\pi_\\mathbf{\\theta}(a_t|o_t)$, where $\\mathbf{\\theta}$ is the set of learnable parameters in the neural net, and $\\pi_\\mathbf{\\theta}(a_t|o_t)$ is a probability distribution over the possible actions conditioned on the observation.\n\nA **trajectory**  $\\tau$ is a sequence of observations of the environment and the corresponding actions an agent takes. For an episodic task that ends after $T$ steps:\n$$\\tau = (o_0, a_0, o_1, a_1, \\ldots , o_T, a_T)$$\nThe return (or total rewards) is a function of the trajectory, $R(\\tau)$.\n\nWe want to find the values of $\\theta$ that maximize the **expected return** over trajectories:\n$$J(\\pi_\\theta)= \\mathop{\\mathbb{E}} _{\\tau \\sim \\pi_{\\theta}}[R(\\tau)]$$\n\nThe usual way of efficiently finding good values of $\\theta$ is to differentiate the objective with respect to $\\theta$ and then use gradient descent. Luckily, we can obtain an *estimate* of this gradient. The key result is the *Policy Gradient Theorem*, which says that you can evaluate the gradient using the gradients of the policy itself:\n$$\\nabla_\\theta J(\\pi_\\theta) = \n\\mathop{\\mathbb{E}} _{\\tau \\sim \\pi_{\\theta}}\\left[ \\sum_{t=0}^{T}\\Phi_t\\nabla_\\theta\\log \\pi_\\theta(a_t|o_t) \\right] \n$$\nThere are many possibilities for $\\Phi_t$ (see page 2 [here](https://arxiv.org/pdf/1506.02438.pdf) for a list of these possibilities). We  will use $\\Phi_t = \\hat{R}_t \\equiv \\sum_{t'=t}^{T} r_{t'}$, sometimes known as the [reward-to-go](https://spinningup.openai.com/en/latest/spinningup/rl_intro3.html#don-t-let-the-past-distract-you). Note that $\\mathop{\\mathbb{E}} _{\\tau \\sim \\pi_{\\theta}}$ is an expectation over trajectories $\\tau$ which can be estimated by using a sample mean. Let us call this estimate of the gradient $\\hat{g}$:\n\n$$\\hat{g} = \\frac{1}{|D|}\\sum_{\\tau \\in \\mathcal{D}}\n\\sum_{t=0}^{T}\\hat{R}_t\\nabla_\\theta\\log \\pi_\\theta(a_t|o_t) \n$$\nwhere $\\mathcal{D}$ is a set of trajectories of size $|\\mathcal{D}|$. The more trajectories we sample from, the lower the variance of the estimator $\\hat{g}$. But to simplify things for this practical, we will only be sampling from only one trajectory at a time to get our gradient estimate. Then:\n$$\\hat{g} =\n\\sum_{t=0}^{T}\\hat{R}_t\\nabla_\\theta\\log \\pi_\\theta(a_t|o_t) \n$$\nTranslating this into a loss to be *maximized*:\n$$\\mathcal{L}=\\sum_{t=0}^{T}\\hat{R}_t\\log \\pi_\\theta(a_t|o_t) $$\n\nThis looks very similar to the usual supervised learning cross-entropy loss, $\\sum_{i}\\log p(y_i|x_i) $, where $y_i$ is the label and $x_i$ is the feature. Indeed, learning with policy gradients is almost the same doing supervised learning with the following small changes:\n\n- we use the action $a_t$ taken when we saw $o_t$ as the label ($y_i$)\n- the loss of each example gets multiplied (or *weighted*) by $\\hat{R}_t$. This increases the log probability for good actions and decrease it by bad actions.\n- we are doing gradient *ascent* rather than the usual gradient *descent*\n- the observations $o_t$ are correlated with each other, and hence are not independent and identically distributed (i.i.d) as the features $x_i$ are assumed to be. \n\nIn summary:\n\n| Reinforcement Learning         \t|  Supervised Learning \t|\n|-------------------------------------\t|-----------------------------------------------------\t\t|\n|  $\\sum_{t}\\log \\pi_\\theta(a_t|o_t) \\hat{R}_t$     \t| $\\sum_{i}\\log p(y_i|x_i) $    |\n|  action $a_t$    | label $y_i$    |\n|  observation $o_t$    | feature $x_i$    |\n| $\\pi_\\theta(a_t|o_t)$   |   $p(y_i|x_i)$  |\n|  gradient ascent     \t|  gradient descent    |\n| non-i.i.d observations $o_t$ | i.i.d features $x_i$\n\nFor those interested in the derivation, there are two excellent resources:\n- [Part 3: Intro to Policy Optimization](https://spinningup.openai.com/en/latest/spinningup/rl_intro3.html) of OpenAI Spinning Up. Note that they often use *state* where we used *observation*.\n- Chapter 13 of Sutton and Barto, *Reinforcement Learning: and Introduction*, 2nd Edition. A free copy can be found [here](http://incompleteideas.net/book/RLbook2018.pdf).\n\n**Historical Note**: The name \"policy gradient\" comes from the fact that we're directly taking the gradient of the policy. The particular flavour of policy gradient which uses the loss function above, along with the Monte-carlo approximation of the objective is known as the **REINFORCE** algorithm ([Williams 1992](https://link.springer.com/article/10.1007/BF00992696)).\n\n\n#### Optional extra reading: More on Policy Gradients\n\nThis section is for the mathematically inclined, and gives more insight into the Policy Gradient Theorem.\n\nOutside of the reinforcement learning setting, the Policy Gradient Theorem is known as a [score function estimator](http://blog.shakirm.com/2015/11/machine-learning-trick-of-the-day-5-log-derivative-trick/):\n$$\n\\frac{\\partial }{\\partial \\theta}\\mathop{\\mathbb{E}} _{x \\sim p_{\\theta}}[f(x)]=\\mathop{\\mathbb{E}} _{x \\sim p_{\\theta}}[f(x)\\frac{\\partial }{\\partial \\theta}\\log p(x;\\theta)]\n$$\n\nThe power of this theorem comes from the ability to estimate the RHS, even if $f(x)$ is a *black-box function* (i.e. one for which we don't have the analytical form for). We can do this by replacing the mean by the sample mean:\n$$\\mathop{\\mathbb{E}} _{x \\sim p_{\\theta}}[f(x)\\frac{\\partial }{\\partial \\theta}\\log p(x;\\theta)] \n\\approx \\frac{1}{N}\\sum_{n=1}^{N}  f(\\hat{x}^{(n)})\\frac{\\partial }{\\partial \\theta}\\log p(\\hat{x}^{(n)};\\theta)$$\n\nwhere $\\hat{x}^{(n)}$ is sampled from $p(x;\\theta)$. In the reinforcement learning setting, $x$ is the action sampled from the parameterized policy $p(x;\\theta)$, and $f(x)$ is the reward function.\n\nThe derivation of the score function estimator:\n$$\n\\begin{align}\n\\frac{\\partial }{\\partial \\theta}\\mathop{\\mathbb{E}} _{x \\sim p_{\\theta}}[f(x)] \n&= \\frac{\\partial }{\\partial \\theta} \\int p(x; \\theta)f(x) \\, dx \\\\ \n&= \\int  \\frac{\\partial }{\\partial \\theta} p(x; \\theta)f(x) \\, dx \\\\ \n&= \\int  p(x; \\theta) \\frac{\\partial }{\\partial \\theta} \\log p(x; \\theta)f(x) \\, dx \\ \\ \\ \\text{ (Log-Derivative trick)}\\\\ \n&= \\mathop{\\mathbb{E}} _{x \\sim p_{\\theta}}[f(x)\\frac{\\partial }{\\partial \\theta}\\log p(x;\\theta)]\n\\end{align}\n$$\n\nThe Log-Derivative trick used in the third line is the property, for any function $f(x)$:\n$$\\frac{d f(x)}{dx}=\\frac{f(x)}{f(x)}\\frac{d f(x)}{dx}=f(x)\\frac{d\\log(f(x))}{dx}\n$$ \nThe right-hand side was obtained using the chain rule and the fact that $d \\log(x)/dx=1/x$. \n\nThe score function estimator is valid under **very** general conditions: $p(x;\\theta)$ needs to be a continuous function of $\\theta$, but does not need to be a continuous function of $x$. Furthermore, $f(x)$ can be discontinuous and $x$ can be either a discrete or continuous random variable (a reference for these conditions is [here](https://arxiv.org/abs/1506.05254)). This should reassure us when using this theorem for reinforcement learning, as it means we don't need to worry about showing that our environments produce a smooth or even continuous return function (which might not be true, or might be very hard to show for most environments)!\n\n\n\n\n**Example: A Toy Model**\n\nTo get some intuition for how the score function estimator works, lets consider a toy model: Let $f(x)=-(x-k)^2$ (where $k$ is some real number) and let $p(x;\\mu,\\sigma)$ be normally distributed $\\mathcal{N}(\\mu, \\sigma)$ with mean $\\mu$ and variance $\\sigma$:\n$$\np(x;\\mu,\\sigma) = \\frac{e^{-\\frac{1}{2\\sigma} (x-\\mu)^2}}{\\sqrt{2 \\pi } \\sigma}\n$$\n\nIn reinforcement learning, the task is to find the values of $\\mu$ and $\\sigma$ that maximize $\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu,\\sigma}}[f(x)]$. Here is a summary as to how this toy problem fits into the reinforcement learning framework:\n\n|     Reinforcement Learning Concept    \t|  Toy Example \t|\n|-------------------------------------\t|-----------------------------------------------------\t\t|\n|  Action     \t| choice of $x$    |\n|  Policy    | $p(x;\\mu,\\sigma)$    |\n|  Observation $o_t$     | None    |\n| Reward $r_t$   |   $-(x-k)^2$  |\n\n\nUnlike the general reinforcement learning case where $f(x)$ is a black-box,  we can analytically evaluate $\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu,\\sigma}}[f(x)]$ with our example:\n$$\n\\begin{align}\n\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu,\\sigma}}[f(x)]\n&= \\int^{\\infty}_{-\\infty} f(x) p(x;\\mu,\\sigma) dx \\\\\n&=\\int^{\\infty}_{-\\infty} \\left[-(x-k)^2\\right] \\left[\\frac{e^{-\\frac{1}{2\\sigma} (x-\\mu)^2}}{\\sqrt{2 \\pi } \\sigma}\\right]dx \\\\\n&=-(k-\\mu)^2 - \\sigma^2\n\\end{align}\n$$\n\nThe maximimum of $\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu,\\sigma}}[f(x)]$ is when the distribution $p(x;\\mu,\\sigma)$ has mean $\\mu=k$ (which corresponds to the position of the maximum of $f(x)=-(x-k)^2$) and variance $\\sigma=0$ (so it is infinitely 'spiked', i.e. a [Dirac Delta function](https://en.wikipedia.org/wiki/Dirac_delta_function)). This makes sense: to maximize $\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu,\\sigma}}[f(x)]$, we want all of the probability mass of $p(x;\\mu,\\sigma)$ to be concentrated at the maximum of $f(x)=-(x-k)^2$, i.e. $x=k$.\n\nWe can now also easily verify that using the score function estimator is equivalent to differentiating $\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu,\\sigma}}[f(x)]$ directly: as we have computed $\n\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu,\\sigma}}[f(x)]$, we immediately have that \n$$\\frac{\\partial }{\\partial \\mu}\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu,\\sigma}}[f(x)] = \\frac{\\partial }{\\partial \\mu}\\left[-((\\mu-k)^2 + \\sigma^2)\\right]=2(k-\\mu)\n$$\nBut using the score function estimator instead:\n$$\\begin{align}\n\\frac{\\partial }{\\partial \\mu}\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu,\\sigma}}[f(x)] \n&= \\mathop{\\mathbb{E}} _{x \\sim p_{\\mu,\\sigma}}[f(x)\\frac{\\partial }{\\partial \\mu}\\log p(x;\\mu,\\sigma)] \\\\\n&= \\mathop{\\mathbb{E}} _{x \\sim p_{\\mu,\\sigma}}[-(x-k)^2 \\frac{\\partial }{\\partial \\mu}\\log \\left(\\frac{e^{-\\frac{1}{2\\sigma} (x-\\mu)^2}}{\\sqrt{2 \\pi } \\sigma}\\right)] \\\\\n&= \\mathop{\\mathbb{E}} _{x \\sim p_{\\mu,\\sigma}}[\\frac{(x-k)^2(\\mu-x)}{\\sigma^2}] \\\\\n&=2(k-\\mu)\n\\end{align}\n$$\n\nNote: If you have trouble following that last step see [moments of the Gaussian](https://en.wikipedia.org/wiki/Normal_distribution#Moments)\n\nIt is left as an exercise to verify that the same holds for $\\frac{\\partial }{\\partial \\sigma}\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu,\\sigma}}[f(x)] $. \n\n\n**Sampling using the Toy Model**\n\nSo far, the score function estimator has not given us anything extra: we can \ndirectly compute the derivatives of $\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu,\\sigma}}[f(x)]$, and we don't even need derivatives to find its minimum. But lets pretend that $f(x)$ is a black box: we can only evaluate $f(x)$ at a finite number of values of $x$. We can no longer compute $\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu,\\sigma}}[f(x)]$ directly. How do we find the values of $\\mu$ and $\\sigma$ that maximize $\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu,\\sigma}}[f(x)]$? \n\n**Further simplification**: set $\\sigma=1$ and $k=0$, so $f(x)=-x^2$ and the task is to find the optimal value of $\\mu$.\n\n**Approach 1: Direct Search.** We can replace the mean $\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu,\\sigma}}$ with the sample mean: \n\n$$\n\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu}}[f(x)]\\approx \\frac{1}{N} \\sum_{n=1}^{N}f(\\hat{x}^{(n)})\n$$\nwhere $\\hat{x}^{(n)} \\sim p(x;\\mu,1)$ is the $n^{th}$ sample from the distribution $p(x;\\mu,1)$. The sample mean is equivalent to the expectation in the limit $N\\to\\infty$. Then we simply try out lots of different values of $\\mu$ and $\\sigma$ and take the ones that maximize the sample mean. The random search method explored in the previous section is an example of this approach.\n\n**Approach 2: Gradient Ascent**. If we can get an estimate of the derivative of $\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu}}[f(x)]$ w.r.t $\\mu$, we can modify our initial values of $\\mu$ by gradient ascent rather than just trying out random values. Using the score function estimator and then taking the sample mean:\n\n$$\n\\begin{align}\n\\frac{\\partial }{\\partial \\mu}\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu,\\sigma}}[f(x)] \n&= \\mathop{\\mathbb{E}} _{x \\sim p_{\\mu}}[f(x)\\frac{\\partial }{\\partial \\mu}\\log p(x;\\mu,1)] \\\\\n&= \\mathop{\\mathbb{E}} _{x \\sim p_{\\mu}}[f(x) (x-\\mu)] \\\\\n&\\approx \\frac{1}{N} \\sum_{n=1}^{N}f(\\hat{x}^{(n)}) (\\hat{x}^{(n)}-\\mu) \\\\\n&\\equiv \\eta_N \n\\end{align}$$\nOur estimator $\\eta_N \\equiv \\sum_{n=1}^{N}f(\\hat{x}^{(n)}) (\\hat{x}^{(n)}-\\mu)$ allows us to estimate the gradient $\\frac{\\partial }{\\partial \\mu}\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu,\\sigma}}[f(x)]$ using a finite number of samples of $p(x;\\mu,1)$. In this case, we were able to explicitly compute $\\frac{\\partial }{\\partial \\mu}\\log p(x;\\mu,1)$ as we have an analytical expression for $p(x;\\mu,1)$, which is usually not the case for reinforcement learning (where $p(x;\\mu,1)$ is often a neural net).\nLet us implement this estimator $\\eta_N$:\n\n\n```python\ndef f_estimator(x, mean):\n    return (-x**2) * (x - mean)\n\ndef sf_estimator(mean, sample_size, f):\n    x = np.random.normal(mean, 1, sample_size)\n    return np.mean(f(x, mean))\n```\n\nIf our starting value is $\\mu=3$, then the exact derivate is $2\\times (-3)=-6$, and our estimated derivative is:\n\n\n```python\nsample_size=200\nmean=3\nsf_estimator(mean, sample_size, f_estimator)\n```\n\n**Baselines and Variance Reduction**\n\nWe can also get an idea of the **variance** of our derivative estimates, which tells us how noisy these estimates are:\n\n\n```python\ndef sf_estimator_variance(mean, mean_sample_size, grad_f, variance_samples = 200):\n    grads = [grad_f(mean, mean_sample_size, f_estimator) for _ in range(variance_samples)];\n    return np.var(grads)\n```\n\nWith a sample size of 200, the variance of our derivative estimator is:\n\n\n```python\nvar1 = sf_estimator_variance(mean, sample_size, sf_estimator)\nvar1\n```\n\nOne obvious way of reducing the variance is to increase the sample size:\n\n\n```python\nsample_size2 = 500\nsf_estimator_variance(mean, sample_size2, sf_estimator)\n```\n\nIn reinforcement learning, taking extra samples is often expensive. It turns out that we can reduce the variance *without* taking any more samples! This idea is very important in reinforcement learning, where it is known as the [baseline method](http://jmlr.csail.mit.edu/papers/volume5/greensmith04a/greensmith04a.pdf). The general procedure is also known as the [control variate method](https://arxiv.org/abs/1906.10652).\n\nTo see how this works, let us derive an expression for the variance of our estimator:\n\n$$\n\\begin{align}\n\\text{Var}[\\eta_N] &= \\text{Var}\\left[\\frac{1}{N}\\sum_{n=1}^{N}f(x) (x-\\mu) \\right] \\ \\ \\  \\ (x \\sim \\mathcal{N}(\\mu, 1))  \\\\\n&=\\frac{1}{N^2}\\text{Var}\\left[\\sum_{n=1}^{N}f(x) (x-\\mu) \\right] \\ \\ \\ \\ (\\text{Var}[aX]=a^2\\text{Var}[X]) \\\\\n&= \\frac{1}{N^2}\\sum_{n=1}^{N}\\text{Var}\\left[f(x) (x-\\mu) \\right] \\ \\ \\ \\ (\\text{Var}[X+Y]=\\text{Var}[X]+\\text{Var}[Y] \\ \\text{when} \\ X,Y \\ \\text{independent}) \\\\\n&= \\frac{1}{N^2}\\cdot N\\cdot\\text{Var}\\left[f(x) (x-\\mu) \\right] \\\\\n&= \\frac{1}{N}\\text{Var}\\left[f(x) (x-\\mu) \\right] \n\\end{align}\n$$\nAs we already saw, the obvious way of reducing the variance $\\text{Var}[\\eta_N]$ is to increase $N$, but this comes at the cost of needing to take more samples. We have learnt though that the variance decreases as $\\mathcal{O}(1/N)$ with sample size.\n\nAnother way is with the following trick: replace the $f(x)$ with a new $\\tilde{f}(x)$ that leaves the gradient $\\frac{\\partial }{\\partial \\mu}\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu}}[(f(x))]$ unchanged, but reduces the variance of our gradient estimator $\\eta_N$, i.e reduces $\\text{Var}[\\eta_N]$. A simple choice is $\\tilde{f}(x)=f(x)-b(x)$ for any function $b(x)$ that does not depend on $\\mu$. It is easy to check that this leaves $\\eta_N$ unchanged:\n$$\\frac{\\partial }{\\partial \\mu}\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu}}[(\\tilde{f}(x))]\n=\\frac{\\partial }{\\partial \\mu}\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu}}[(f(x)-b(x))]\n=\\frac{\\partial }{\\partial \\mu}\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu}}[f(x)]+\\frac{\\partial }{\\partial \\mu}\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu}}[b(x)]\n=\\frac{\\partial }{\\partial \\mu}\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu}}[f(x)]$$\nNow [note that](https://en.wikipedia.org/wiki/Variance#Sum_of_variables)\n$$\n\\text{Var}[f-b]= \\text{Var}[f]-2\\text{Cov}[f,b]+\\text{Var}[b]\n$$\nSo if $f$ and $b$ are strongly correlated, then the covariance $2\\text{Cov}[f,b]$ can be greater than the extra variance term $\\text{Var}[b]$, reducing the total variance $\\text{Var}[f-b]$.\n\nA common choice for $b$ is $b=\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu}}[f(x)]$. This choice of $b$ is clearly correlated with $f(x)$, as increases in $f(x)$ will lead to increases in the mean $\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu}}[f(x)]$ (and decreases will lead to decreases in the mean).\n\nLet us check for our toy example that this does actually reduce the variance. First, note that $\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu}}[f(x)] = -(1+\\mu^2)$ and $\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu}}[f(x) (x-\\mu) ] = -2\\mu$ (leaving out the details of this calculation). Then (skipping the details of the computation: this is what computer algebra systems are there for!):\n$$\n\\begin{align}\n\\text{Var}[\\eta_N] \n&=  \\frac{1}{N}\\text{Var}\\left[f(x) (x-\\mu)\\right] \\\\\n&=  \\frac{1}{N}\\int^{\\infty}_{-\\infty}\\left(f(x)(x-\\mu) -\\mathop{\\mathbb{E}} _{x \\sim p_{\\mu}}[f(x) (x-\\mu) ] \\right)^2 p(x;\\mu)dx \\\\\n&= \\frac{1}{N}\\left( \\mu^4 +14\\mu^2+15\\right) \\\\\n\\end{align}\n$$\nAnd similarly for $\\tilde{f}(x)$:\n$$\n\\begin{align}\n\\text{Var}[\\tilde{\\eta}_N] &= \\frac{1}{N}\\text{Var}\\left[\\tilde{f}(x) (x-\\mu)\\right] \\\\\n&=\\frac{1}{N}\\left( 8\\mu^2+10\\right)\n\\end{align}\n$$\nThe variance is indeed reduced for all values of $\\mu$, as the difference in variances $\\text{Var}[\\eta_N] -\\text{Var}[\\tilde{\\eta}_N]$ is a positive quantity:\n$$\n\\text{Var}[\\eta_N] -\\text{Var}[\\tilde{\\eta}_N]=\\frac{1}{N}(\\mu^4+6 \\mu^2+5)\n$$\n\n\nTo get more insight into how the addition of the baseline changes the distribution of $f(x) (x-\\mu)$ (where $x$ is normally distributed $\\mathcal{N}(\\mu, 1)$), we could analytically compute what this distribution is and plot it, and hopefully see how the baseline changes its shape. This is tricky as $f(x) (x-\\mu)$ is a cubic polynomial, which is non-bijective in a non-trivial way, complicating the use of the standard probability density [change-of-variables formula](https://en.wikipedia.org/wiki/Probability_density_function#Function_of_random_variables_and_change_of_variables_in_the_probability_density_function). Rather than do this analytically, it is much easier to sample values of $x$ and plot the histogram of values of $f(x) (x-\\mu)$. The Seaborn plotting package makes this very easy:\n\n\n```python\ndef f_estimator_baseline(x, mean):\n  return (-x**2 - (-1 - mean**2)) * (x-mean)\n\nmean2 = 7\nsample_size = 10000\nx_rand=np.random.normal(mean2, 1, sample_size)\nrands_f = f_estimator(x_rand, mean2)\nrands_f_baseline = f_estimator_baseline(x_rand, mean2)\n\nimport seaborn as sns\nsns.set_style('darkgrid')\nsns.kdeplot(rands_f, shade=True, label=\"Without Baseline\", legend=True)\nsns.kdeplot(rands_f_baseline, shade=True, label=\"With Baseline\", legend=True)\n```\n\nThis shows how the addition of the baseline changes the distribution to be a lot *sharper*, which means that it has less variance. The sampling we did above allows us to check our analytic calculations as well: with $\\mu=7$, $\\text{Var}\\left[f(x) (x-\\mu)\\right] = 3102$ and $\\text{Var}\\left[\\tilde{f}(x) (x-\\mu)\\right] = 402$. This is similar to what we see with our sampled data:\n\n\n```python\nprint(\"Variance without Baseline: \", np.var(rands_f))\nprint(\"Variance with Baseline: \", np.var(rands_f_baseline))\n```\n\nThe sample means should be similar (but only the same in the limit $N\\to\\infty$):\n\n\n```python\nprint(\"Mean without Baseline: \", np.mean(rands_f))\nprint(\"Mean with Baseline: \", np.mean(rands_f_baseline))\n```\n\nIn practice, we don't know the exact mean of $f(x)$ to use as a baseline, but we can just take the sample mean.\n\n**Question**: verify that using `f_estimator_baseline` instead of `f_estimator` in `sf_estimator_variance` reduces the variance\n\n**Extra Reading**\n- A great review of score function estimators:\n    * [Monte Carlo Gradient Estimation in Machine Learning](https://arxiv.org/abs/1906.10652), Mohamed *et al*, 2019\n\n### Episode Trajectory Collector\n\nLet us implement a function `get_episode_trajectory(env, agent)` that controls the environment `env` with `agent` and returns lists of rewards, observations and actions taken at each timestep:\n\n\n```python\ndef get_episode_trajectory(env, agent, max_steps=1000):\n    observation_list = []\n    reward_list = []\n    action_list = []\n    value_list = []\n\n    done = False\n    obs = env.reset()\n    for _ in range(max_steps):\n        observation_list.append(obs)\n        out = agent(obs)\n        assert (\"Action\" in out), \"The key 'Action' was missing from the agents output.\"\n        action = out[\"Action\"]        \n        obs, rew, done, _, = env.step(action)\n        reward_list.append(rew)\n        action_list.append(action)\n        if \"Value\" in out:\n            value_list.append(out[\"Value\"])\n            \n        if done:\n            break\n        \n    ret = {\n        \"Observations\": observation_list, \n        \"Actions\": action_list, \n        \"Rewards\": np.array(reward_list, dtype=np.float32)\n    }\n    if len(value_list) > 0:\n        ret[\"Values\"] = value_list\n        \n    return ret\n```\n\nLet us try out `get_episode_trajectory` on cartpole using the random agent we implemented earlier:\n\n\n```python\ntraj = get_episode_trajectory(env_cartpole, agent_random, max_steps=3)\npprint(traj)\n```\n\n### Reward-to-go $\\hat{R}_t$\n\nWe need to compute the reward-to-go $\\hat{R}_t= \\sum_{t'=t}^{T} r_{t'}$. Here is a simple NumPy implementation:\n\n\n```python\ndef reward_to_go(rewards):\n    return np.flip(np.cumsum(np.flip(rewards)))\n```\n\nChecking that this works as expected:\n\n\n```python\nreward_to_go([1, 1.2, 1])\n```\n\n#### Optional extra reading: estimator issues\n\nThe estimator $\\Phi_t \\equiv \\hat{R}_t= \\sum_{t'=t}^{T} r_{t'}$ we used has a number of problems. For example, if we don't get to the end of an episode (as it takes too long and we stop sampling), or our task is not episodic, we will have incorrect estimates of the advantages of our states. One popular alternative that works around this difficulty is the GAE-Lamba estimator: \n - [High-Dimensional Continuous Control Using Generalized Advantage Estimation](https://arxiv.org/abs/1506.02438), Schulman *et al*, 2015\n - A good blog post on this: https://danieltakeshi.github.io/2017/04/02/notes-on-the-generalized-advantage-estimation-paper/\n\n### TensorFlow Policy Net\n\nLet us use a neural net policy with parameters $\\theta$, so we have $\\pi_\\theta(a|s) = NN(s; \\theta)$, where $NN(s; \\theta)$ is some potentially complex function represented by a neural network with parameters $\\theta$:\n\n\n```python\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D\nfrom tensorflow.keras import Model\n```\n\n\n```python\nclass AgentMLPTF(Model):\n  def __init__(self):\n    super(AgentMLPTF, self).__init__()\n    self.d1 = Dense(15, activation='tanh')\n    self.d2 = Dense(2)\n\n  def call(self, x):\n    # 1. Define Policy\n    batch = True\n    if x.ndim == 1:\n        batch = False\n        x = np.expand_dims(x, axis=0)\n    x = self.d1(x)\n    action_logits = self.d2(x)\n    \n    # 2. Sample policy to get action\n    action = tf.random.categorical(action_logits, 1)\n    action = action.numpy().flatten()\n    if not batch:\n        action = np.asscalar(action)\n        \n    return {\"Action\":action, \"LogProbability\":action_logits}\n```\n\n\n```python\nagent_mlp_tf = AgentMLPTF()\n```\n\n\n```python\nobs = np.array([0.1,0.2,0.3,0.4])\nagent_mlp_tf(obs)\n```\n\nWe can also verify that this works on a batch of observations:\n\n\n\n```python\nobs_batch = np.array([[0.1,0.2,0.3,0.4], [0.5,0.3,0.2,0.1]])\nagent_mlp_tf(obs_batch)\n```\n\n### Loss Function\n\n**Exercise [ALL]**: implement the loss function $\\mathcal{L}=\\sum_{t=0}^{T}\\hat{R}_t\\log \\pi_\\theta(a_t|s_t) $ using TensorFlow operations. Call this function `loss_pg(actions, log_probs, returns)`.\n\n\n```python\n#@title Answer { display-mode: \"form\" }\n\ndef loss_pg(actions, log_probs, returns):\n    action_masks = tf.one_hot(actions, 2, dtype=np.float64)\n    log_probs = tf.reduce_sum(action_masks * tf.nn.log_softmax(log_probs), axis=1)\n    return -tf.reduce_sum(returns * log_probs)\n  \n# Verify that this works on some example data:\n\nactions = [1,0,0]\nlogits = np.array([[0.2,0.8],[0.2,0.8],[0.6,0.4]])\nweights = [2.3, 4.3, 2.1]\nloss_pg(actions, logits, weights)\n\n# Note: this is equivalent to:\ndef loss_pg2(actions, log_probs, returns):\n    loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)\n    return tf.reduce_mean(returns * loss(actions, log_probs))\n```\n\n### Train the Policy Net\n\nNow we can put all the pieces together in the training loop. It simply collects a single trajectory and uses it to do a single gradient update of the agent:\n\n\n```python\ndef train_policy_grad(env, agent, num_epochs=300):\n    optimizer = tf.keras.optimizers.Adam(learning_rate=1e-2)\n    log_reward = 0\n    log_reward_list = []\n    logging_period = 20\n    \n    for epoch in range(num_epochs):\n        # get the training data\n        traj = get_episode_trajectory(env, agent)\n        obs = np.stack(traj[\"Observations\"])\n        rew = traj[\"Rewards\"]\n        actions = traj[\"Actions\"]\n        \n        # compute 'reward-to-go'\n        rew_2_go = reward_to_go(rew)\n        \n        # compute gradients + update weights\n        with tf.GradientTape() as tape:\n            logits = agent(obs)[\"LogProbability\"]\n            loss = loss_pg(actions, logits, rew_2_go)\n            \n        gradients = tape.gradient(loss, agent.trainable_variables)\n        optimizer.apply_gradients(zip(gradients, agent.trainable_variables))\n        \n        # log the reward\n        log_reward += np.sum(rew)\n        if (epoch % logging_period) == 0:\n            template = 'Training Epoch {}, Averaged Return: {}'\n            print(template.format(epoch, log_reward / logging_period))\n            log_reward_list.append(log_reward / logging_period)\n            log_reward = 0\n       \n    return (range(0, num_epochs, logging_period), log_reward_list)\n```\n\nNote that `train_policy_grad(env, agent)` takes a TensorFlow agent as input and mutates it during training. Create and train a `AgentMLPTF` agent:\n\n\n```python\nagent_mlp_tf = AgentMLPTF()\n(episodes, rewards) = train_policy_grad(env_cartpole, agent_mlp_tf)\n```\n\nWe can plot the average rewards obtained versus the number of episodes trained for:\n\n\n```python\nplt.plot(episodes, rewards, 'bo')\nplt.xlabel('Episode Number')\nplt.ylabel('Average Episode Reward')\nplt.show()\n```\n\nLet us animate this agent controlling the cartpole environment:\n\n\n```python\nanimate_agent(env_cartpole, agent_mlp_tf)\n```\n\n### Policy Gradient Tasks\n\n1. [**ALL**] Try using TensorFlows default initial learning rate of the ADAM optimizer in `train_policy_grad`. What happens? Try come up with an explanation for what is going on.\n\n**Variance Reduction**: We are trying to estimate the policy gradient using $\\hat{g} = \\frac{1}{|D|}\\sum_{\\tau \\in \\mathcal{D}}\n\\sum_{t=0}^{T}\\hat{R}_t\\nabla_\\theta\\log \\pi_\\theta(a_t|o_t) \n$. This gradient is only exact if we have an infinite number of samples. Otherwise it is *noisy*: we will get a different estimate of $\\hat{g}$ for every sample we take. \n\n2. [**ALL**] The simplest way of reducing the variance of $\\hat{g}$ is to use a *baseline*: rather than using $\\hat{R}_t$, use $\\hat{R}_t-b$ where $b$ is the mean of $\\hat{R}$, i.e. $b=\\frac{1}{T}\\sum_{t=1}^{T}\\hat{R}$. Modify `train_policy_grad` to use this. Does it speed up training? An in-depth discussion of why this works is in the section *Optional extra reading: More on Policy Gradients*.\n\n3. [**Advanced**] The policy used to solve the Cartpole environment only required the most recent observation to inform its actions. Observations taken before the most recent one give no extra information that the policy could use to improve its decision making. This is called the [Markov Property](http://www.cs.cmu.edu/~10601b/slides/MDP_RL.pdf). Most real-world environments are not like this. Consider the problem of using a reinforcement learning agent to control a self-driving car, where an observation is a frame from its onboard video cameras. List various ways in which the Markov Property is violated in this environment (this is also known as a *partially-observed environment*). How might you modify the architecture of your policy net to operate in a non-Markovian environment like this?\n\n**IMPORTANT: Please fill out the exit ticket form before you leave the practical: https://forms.gle/FLQ78eAEQprsWXp38**\n\n### Optional extra reading: Policy Gradients\n\n\n\n- The simple REINFORCE algorithm shown here is very unstable. There are a number of improvements to this method, the most popular of which is probably PPO:\n    * [Proximal Policy Optimization Algorithms](https://arxiv.org/abs/1707.06347), Schulman *et al*, 2017\n    * OpenAI SpinningUp: https://spinningup.openai.com/en/latest/algorithms/ppo.html\n    * OpenAI Blog: https://openai.com/blog/openai-baselines-ppo/\n- PPO borrows many ideas from TRPO. [Depth First Learning](https://www.depthfirstlearning.com/2018/TRPO) has a course with a lot of good resources on TRPO.\n- The idea of being able to differentiate through stochastic nodes in computation graphs is a very powerful idea, and it is used in a number of other areas in deep learning, such as *variational autoencoders*. \n    * For the general setting, see [Gradient Estimation Using Stochastic Computation Graphs](https://arxiv.org/abs/1506.05254), Schulman *et al*, 2015.\n- For a skeptical take on policy gradients, see Ben Recht's post [The Policy of Truth](https://www.argmin.net/2018/02/20/reinforce/).\n- Karpathy has [good post](http://karpathy.github.io/2016/05/31/rl/) on reinforcement learning using policy gradients, including an implementation of policy gradients that solves Pong using only NumPy in [131 lines of Python](https://gist.github.com/karpathy/a4166c7fe253700972fcbc77e4ea32c5)! \n", "meta": {"hexsha": "90705cae9f0c6c24df0defd7b5cd2a03445ead51", "size": 80871, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "3a_reinforcement_learning.ipynb", "max_stars_repo_name": "johncliu/practicals-2019", "max_stars_repo_head_hexsha": "e748be1a2601ec743c048f7098359d2c7b4cc003", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 259, "max_stars_repo_stars_event_min_datetime": "2019-10-14T18:29:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T09:04:12.000Z", "max_issues_repo_path": "3a_reinforcement_learning.ipynb", "max_issues_repo_name": "johncliu/practicals-2019", "max_issues_repo_head_hexsha": "e748be1a2601ec743c048f7098359d2c7b4cc003", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3a_reinforcement_learning.ipynb", "max_forks_repo_name": "johncliu/practicals-2019", "max_forks_repo_head_hexsha": "e748be1a2601ec743c048f7098359d2c7b4cc003", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 80, "max_forks_repo_forks_event_min_datetime": "2019-10-09T13:23:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T23:40:19.000Z", "avg_line_length": 41.6646058733, "max_line_length": 814, "alphanum_fraction": 0.5450161368, "converted": true, "num_tokens": 13225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3557748935136303, "lm_q2_score": 0.09009299090809873, "lm_q1q2_score": 0.03205282424665329}}
{"text": "# Exploring Jupyter Notebook - Magic Functions\nAuthor: Rahul Yedida\n\n\n```python\n%matplotlib inline\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nplt.plot(range(100))\n```\n\n\n```python\n%time x = range(10000)\n```\n\n    Wall time: 0 ns\n\n\n\n```python\n%%timeit x = range(10000)\nmax(x)\n```\n\n    1000 loops, best of 3: 857 \u00b5s per loop\n\n\n\n```python\n%%HTML\n<i> Image in jupyter notebook</i>\n\n```\n\n\n<i> Image in jupyter notebook</i>\n\n\n\n\n```latex\n%%latex\n\\begin{align}\nGradient: \\nabla J = -2H^T (Y - HW)\n\\end{align}\n```\n\n\n\\begin{align}\nGradient: \\nabla J = -2H^T (Y - HW)\n\\end{align}\n\n\n\n```python\n!pip install ipython-sql\n```\n\n    Collecting ipython-sql\n      Downloading ipython_sql-0.3.8-py3-none-any.whl\n    Requirement already satisfied: sqlalchemy>=0.6.7 in c:\\users\\yrahu\\anaconda3-3.4\\lib\\site-packages (from ipython-sql)\n    Collecting prettytable (from ipython-sql)\n      Downloading prettytable-0.7.2.zip\n    Collecting sqlparse (from ipython-sql)\n      Downloading sqlparse-0.2.4-py2.py3-none-any.whl\n    Collecting ipython-genutils>=0.1.0 (from ipython-sql)\n      Downloading ipython_genutils-0.2.0-py2.py3-none-any.whl\n    Requirement already satisfied: ipython>=1.0 in c:\\users\\yrahu\\anaconda3-3.4\\lib\\site-packages (from ipython-sql)\n    Requirement already satisfied: six in c:\\users\\yrahu\\anaconda3-3.4\\lib\\site-packages (from ipython-sql)\n    Building wheels for collected packages: prettytable\n      Running setup.py bdist_wheel for prettytable: started\n      Running setup.py bdist_wheel for prettytable: finished with status 'done'\n      Stored in directory: C:\\Users\\yrahu\\AppData\\Local\\pip\\Cache\\wheels\\b6\\90\\7b\\1c22b89217d0eba6d5f406e562365ebee804f0d4595b2bdbcd\n    Successfully built prettytable\n    Installing collected packages: prettytable, sqlparse, ipython-genutils, ipython-sql\n    Successfully installed ipython-genutils-0.2.0 ipython-sql-0.3.8 prettytable-0.7.2 sqlparse-0.2.4\n\n\n\n```python\n%load_ext sql\n```\n\n\n```python\n!which -a python\n```\n\n    'which' is not recognized as an internal or external command,\n    operable program or batch file.\n\n\n\n```python\nsys.executable\n```\n\n\n```python\nimport sys\n```\n\n\n```python\nsys.executable\n```\n\n\n\n\n    'C:\\\\Users\\\\yrahu\\\\Anaconda3\\\\python.exe'\n\n\n\n\n```python\n!C:\\Users\\yrahu\\Anaconda3\\python -m pip install ipython-sql\n```\n\n    Collecting ipython-sql\n      Using cached ipython_sql-0.3.8-py3-none-any.whl\n    Requirement already satisfied (use --upgrade to upgrade): ipython-genutils>=0.1.0 in c:\\users\\yrahu\\anaconda3\\lib\\site-packages (from ipython-sql)\n    Collecting prettytable (from ipython-sql)\n      Using cached prettytable-0.7.2.zip\n    Requirement already satisfied (use --upgrade to upgrade): sqlalchemy>=0.6.7 in c:\\users\\yrahu\\anaconda3\\lib\\site-packages (from ipython-sql)\n    Requirement already satisfied (use --upgrade to upgrade): six in c:\\users\\yrahu\\anaconda3\\lib\\site-packages (from ipython-sql)\n    Collecting sqlparse (from ipython-sql)\n      Using cached sqlparse-0.2.4-py2.py3-none-any.whl\n    Requirement already satisfied (use --upgrade to upgrade): ipython>=1.0 in c:\\users\\yrahu\\anaconda3\\lib\\site-packages (from ipython-sql)\n    Building wheels for collected packages: prettytable\n      Running setup.py bdist_wheel for prettytable: started\n      Running setup.py bdist_wheel for prettytable: finished with status 'done'\n      Stored in directory: C:\\Users\\yrahu\\AppData\\Local\\pip\\Cache\\wheels\\b6\\90\\7b\\1c22b89217d0eba6d5f406e562365ebee804f0d4595b2bdbcd\n    Successfully built prettytable\n    Installing collected packages: prettytable, sqlparse, ipython-sql\n    Successfully installed ipython-sql-0.3.8 prettytable-0.7.2 sqlparse-0.2.4\n\n\n    You are using pip version 8.1.0, however version 9.0.1 is available.\n    You should consider upgrading via the 'python -m pip install --upgrade pip' command.\n\n\n\n```python\n%sql sqlite://\n```\n\n\n\n\n    'Connected: None@None'\n\n\n\n\n```sql\n%%sql\nCREATE TABLE classroom(name, age, totalmarks);\nINSERT INTO classroom VALUES(\"Raj\", 20, 89);\nINSERT INTO classroom VALUES(\"Poonam\", 24, 84);\n```\n\n    Done.\n    1 rows affected.\n    1 rows affected.\n\n\n\n\n\n    []\n\n\n\n\n```python\n%sql SELECT * FROM classroom;\n```\n\n    Done.\n\n\n\n\n\n<table>\n    <tr>\n        <th>name</th>\n        <th>age</th>\n        <th>totalmarks</th>\n    </tr>\n    <tr>\n        <td>Raj</td>\n        <td>20</td>\n        <td>89</td>\n    </tr>\n    <tr>\n        <td>Poonam</td>\n        <td>24</td>\n        <td>84</td>\n    </tr>\n</table>\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "0855c1369303df1aa96d170c7c879a0c80c4f173", "size": 17506, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Exploring Jupyter Notebooks - Magic Functions.ipynb", "max_stars_repo_name": "yrahul3910/titanic", "max_stars_repo_head_hexsha": "b3a4fc0409b85c5aa254997cbe8b5fceac11818b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/Exploring Jupyter Notebooks - Magic Functions.ipynb", "max_issues_repo_name": "yrahul3910/titanic", "max_issues_repo_head_hexsha": "b3a4fc0409b85c5aa254997cbe8b5fceac11818b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/Exploring Jupyter Notebooks - Magic Functions.ipynb", "max_forks_repo_name": "yrahul3910/titanic", "max_forks_repo_head_hexsha": "b3a4fc0409b85c5aa254997cbe8b5fceac11818b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7300884956, "max_line_length": 6600, "alphanum_fraction": 0.6833657032, "converted": true, "num_tokens": 1380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121955219593834, "lm_q2_score": 0.08389038412018836, "lm_q1q2_score": 0.031980654667843465}}
{"text": "```python\n\n```\n\n\n```python\n!pip install qiskit\n```\n\n    Collecting qiskit\n      Downloading https://files.pythonhosted.org/packages/6f/61/cb7506e17a2566dc8a31a3e1924d91ac0bdd8ff07c71ec698c06647b6306/qiskit-0.26.2.tar.gz\n    Collecting qiskit-terra==0.17.4\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/b3/0c/3c7a8dd451dae0907263e9de9e3e34909e15e18c88a589b44581972c8511/qiskit_terra-0.17.4-cp37-cp37m-manylinux2010_x86_64.whl (6.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.0MB 2.7MB/s \n    \u001b[?25hCollecting qiskit-aer==0.8.2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/c2/d2/6ff15c370b5465b32529b528bf3f4ce1e01f74498be16203aa1c04b67022/qiskit_aer-0.8.2-cp37-cp37m-manylinux2010_x86_64.whl (18.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 18.0MB 60.8MB/s \n    \u001b[?25hCollecting qiskit-ibmq-provider==0.13.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/be/99/74bbb901f88603a7d850d4889abc06d81ba702e4227151f4a5b66f2631fe/qiskit_ibmq_provider-0.13.1-py3-none-any.whl (228kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 235kB 44.3MB/s \n    \u001b[?25hCollecting qiskit-ignis==0.6.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/54/be/a13c828e457e09d979667a61bddbd8c7246aafa94e2501b6a9154429cbea/qiskit_ignis-0.6.0-py3-none-any.whl (207kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 215kB 37.9MB/s \n    \u001b[?25hCollecting qiskit-aqua==0.9.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/88/79/392c57b978decbb24b902344b536af52c40a751aed0ebbaefa8bc2964cb5/qiskit_aqua-0.9.1-py3-none-any.whl (2.1MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.1MB 36.5MB/s \n    \u001b[?25hRequirement already satisfied: scipy>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (1.4.1)\n    Collecting ply>=3.10\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/a3/58/35da89ee790598a0700ea49b2a66594140f44dec458c07e8e3d4979137fc/ply-3.11-py2.py3-none-any.whl (49kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 5.7MB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (1.19.5)\n    Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (2.6.0)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (2.8.1)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (5.4.8)\n    Collecting python-constraint>=1.4\n      Downloading https://files.pythonhosted.org/packages/37/8b/5f1bc2734ca611943e1d6733ee244238679f6410a10cd45ede55a61a8402/python-constraint-1.4.0.tar.bz2\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (1.7.1)\n    Collecting fastjsonschema>=2.10\n      Downloading https://files.pythonhosted.org/packages/d1/fb/ea090e917b18320f79be31d754bbe496b715175e865603cfce1eaed2e774/fastjsonschema-2.15.1-py3-none-any.whl\n    Collecting retworkx>=0.8.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1b/92/f007f8b9d88dcd5b90e363967e5d54431a68c5fe06d83400732e3b438084/retworkx-0.8.0-cp37-cp37m-manylinux2010_x86_64.whl (1.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.0MB 37.0MB/s \n    \u001b[?25hRequirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (0.3.3)\n    Collecting pybind11>=2.6\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/8d/43/7339dbabbc2793718d59703aace4166f53c29ee1c202f6ff5bf8a26c4d91/pybind11-2.6.2-py2.py3-none-any.whl (191kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 194kB 42.7MB/s \n    \u001b[?25hCollecting websockets>=8\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/84/64/78c2b3fe37730b30dca3c93d1f7f4a4286767f86e7c04cf3571b39bc2fb7/websockets-9.1-cp37-cp37m-manylinux2010_x86_64.whl (103kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 112kB 52.6MB/s \n    \u001b[?25hRequirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit) (2.23.0)\n    Collecting requests-ntlm>=1.1.0\n      Downloading https://files.pythonhosted.org/packages/03/4b/8b9a1afde8072c4d5710d9fa91433d504325821b038e00237dc8d6d833dc/requests_ntlm-1.1.0-py2.py3-none-any.whl\n    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit) (1.24.3)\n    Requirement already satisfied: nest-asyncio!=1.1.0,>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit) (1.5.1)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ignis==0.6.0->qiskit) (56.1.0)\n    Collecting dlx<=1.0.4\n      Downloading https://files.pythonhosted.org/packages/54/c0/b8fb5bb727e983b6f5251433ef941b48f38c65bb0bd6ec509e9185bcd406/dlx-1.0.4.tar.gz\n    Collecting quandl<=3.6.0\n      Downloading https://files.pythonhosted.org/packages/c2/58/9f0e69d836045e3865d263e9ed49f42b23a58526fdabb30f74c430baee3f/Quandl-3.6.0-py2.py3-none-any.whl\n    Requirement already satisfied: pandas<=1.2.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (1.1.5)\n    Requirement already satisfied: fastdtw<=0.3.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (0.3.4)\n    Collecting yfinance<=0.1.55\n      Downloading https://files.pythonhosted.org/packages/7a/e8/b9d7104d3a4bf39924799067592d9e59119fcfc900a425a12e80a3123ec8/yfinance-0.1.55.tar.gz\n    Requirement already satisfied: h5py<=3.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (3.1.0)\n    Collecting docplex<=2.20.204; sys_platform != \"darwin\"\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/87/99/6f7c219b39fd58c84688ad0713eb932bfcf6be81fc74519e43ea9c915b56/docplex-2.20.204.tar.gz (611kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 614kB 41.7MB/s \n    \u001b[?25hRequirement already satisfied: scikit-learn<=0.24.1,>=0.20.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (0.22.2.post1)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.8.0->qiskit-terra==0.17.4->qiskit) (1.15.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra==0.17.4->qiskit) (1.2.1)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit) (2020.12.5)\n    Collecting cryptography>=1.3\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/b2/26/7af637e6a7e87258b963f1731c5982fb31cd507f0d90d91836e446955d02/cryptography-3.4.7-cp36-abi3-manylinux2014_x86_64.whl (3.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.2MB 32.6MB/s \n    \u001b[?25hCollecting ntlm-auth>=1.0.2\n      Downloading https://files.pythonhosted.org/packages/ff/84/97c550164b54942b0e908c31ef09d9469f3ba4cd7332a671e2125732f63b/ntlm_auth-1.5.0-py2.py3-none-any.whl\n    Collecting inflection>=0.3.1\n      Downloading https://files.pythonhosted.org/packages/59/91/aa6bde563e0085a02a435aa99b49ef75b0a4b062635e606dab23ce18d720/inflection-0.5.1-py2.py3-none-any.whl\n    Requirement already satisfied: more-itertools in /usr/local/lib/python3.7/dist-packages (from quandl<=3.6.0->qiskit-aqua==0.9.1->qiskit) (8.7.0)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas<=1.2.3->qiskit-aqua==0.9.1->qiskit) (2018.9)\n    Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance<=0.1.55->qiskit-aqua==0.9.1->qiskit) (0.0.9)\n    Collecting lxml>=4.5.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/30/c0/d0526314971fc661b083ab135747dc68446a3022686da8c16d25fcf6ef07/lxml-4.6.3-cp37-cp37m-manylinux2014_x86_64.whl (6.3MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.3MB 36.7MB/s \n    \u001b[?25hRequirement already satisfied: cached-property; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from h5py<=3.1.0->qiskit-aqua==0.9.1->qiskit) (1.5.2)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn<=0.24.1,>=0.20.0->qiskit-aqua==0.9.1->qiskit) (1.0.1)\n    Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit) (1.14.5)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit) (2.20)\n    Building wheels for collected packages: qiskit, python-constraint, dlx, yfinance, docplex\n      Building wheel for qiskit (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for qiskit: filename=qiskit-0.26.2-cp37-none-any.whl size=10491 sha256=f64b9994c1f7e6bedf9ba00dacdc6482809b24e307058ed3bd26b3182eb0a641\n      Stored in directory: /root/.cache/pip/wheels/89/89/34/524839952d5a58a7be9789e580bfc1ca883bf6579152444568\n      Building wheel for python-constraint (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for python-constraint: filename=python_constraint-1.4.0-py2.py3-none-any.whl size=24079 sha256=748709ee2d07057b27a59be16a6ac6cf17eea94f5bcc9b3adef59709df430a9a\n      Stored in directory: /root/.cache/pip/wheels/34/31/15/7b070b25d0a549d20ce2e9fe6d727471c2c61ef904720fd40c\n      Building wheel for dlx (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for dlx: filename=dlx-1.0.4-cp37-none-any.whl size=5712 sha256=fbda875e6806257d73f62411628e839a64297efd21a71c6ef6a25734f2078cc7\n      Stored in directory: /root/.cache/pip/wheels/bb/ba/15/fdd0deb104df3254912998150ba9245668db06b00af5912d1a\n      Building wheel for yfinance (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for yfinance: filename=yfinance-0.1.55-py2.py3-none-any.whl size=22616 sha256=2b59cd5c95836d58ab09f54a4e5688b569cb4e9beb405d7a1d67b130c7f07aa9\n      Stored in directory: /root/.cache/pip/wheels/04/98/cc/2702a4242d60bdc14f48b4557c427ded1fe92aedf257d4565c\n      Building wheel for docplex (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for docplex: filename=docplex-2.20.204-cp37-none-any.whl size=675362 sha256=fbff8576042354ef353a39862ddb6c07a44de9c4000c2a5b054fb679bad7c9f4\n      Stored in directory: /root/.cache/pip/wheels/ae/2c/e2/a099ebb6fda8adeba9c5fc2e25659d195ad2f5c6cc5fb75fd4\n    Successfully built qiskit python-constraint dlx yfinance docplex\n    Installing collected packages: ply, python-constraint, fastjsonschema, retworkx, qiskit-terra, pybind11, qiskit-aer, websockets, cryptography, ntlm-auth, requests-ntlm, qiskit-ibmq-provider, qiskit-ignis, dlx, inflection, quandl, lxml, yfinance, docplex, qiskit-aqua, qiskit\n      Found existing installation: lxml 4.2.6\n        Uninstalling lxml-4.2.6:\n          Successfully uninstalled lxml-4.2.6\n    Successfully installed cryptography-3.4.7 dlx-1.0.4 docplex-2.20.204 fastjsonschema-2.15.1 inflection-0.5.1 lxml-4.6.3 ntlm-auth-1.5.0 ply-3.11 pybind11-2.6.2 python-constraint-1.4.0 qiskit-0.26.2 qiskit-aer-0.8.2 qiskit-aqua-0.9.1 qiskit-ibmq-provider-0.13.1 qiskit-ignis-0.6.0 qiskit-terra-0.17.4 quandl-3.6.0 requests-ntlm-1.1.0 retworkx-0.8.0 websockets-9.1 yfinance-0.1.55\n\n\n\n```python\nfrom qiskit.providers.aer import QasmSimulator  \nfrom qiskit.providers.aer import AerSimulator\nfrom qiskit.circuit.library import TwoLocal\nfrom qiskit.algorithms import VQE\nfrom qiskit.algorithms.optimizers import COBYLA \nfrom qiskit.circuit.library import EfficientSU2\nfrom qiskit.aqua import set_qiskit_aqua_logging, QuantumInstance\n# opflow is Qiskit's module for creating operators like yours\nfrom qiskit import *\nfrom qiskit.opflow import OperatorBase\nfrom qiskit.opflow import Z, X, I  # Pauli Z, X matrices and identity\nimport pylab\nimport matplotlib.pyplot as plt\nimport numpy as np\n```\n\n\n```python\ncounts = []\nvalues = []\n\n\ndef store_intermediate_result(eval_count, parameters, mean, std):\n  \n  counts.append(eval_count)\n  values.append(mean)\n```\n\n\n```python\nmaster_counts = []\nmaster_values = []\nfor h in range (1,5,1): \n    h=+h\n\nprint(h)\n# or whatever value you have for h\nH = - h * ((X ^ I ^ I ^ I) + (I ^ X ^ I ^ I) + (I ^ I ^ X ^ I) + (I ^ I ^ I ^ X))\n\n# you can swap this for a real quantum device and keep the rest of the code the same!\nbackend = QasmSimulator() \n\n# COBYLA usually works well for small problems like this one\noptimizer = COBYLA(maxiter=200)\n\n# EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library\nansatz = EfficientSU2(4, reps=1)\n\n# set the algorithm\nvqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result)\n\n# run it with the Hamiltonian we defined above\nresult = vqe.compute_minimum_eigenvalue(H)  \n\n# print the result (it contains lot's of information)\nprint(result) \n```\n\n    4\n    {   'aux_operator_eigenvalues': None,\n        'cost_function_evals': 159,\n        'eigenstate': {   '0000': 0.3365728004459065,\n                          '0001': 0.13258252147247765,\n                          '0010': 0.16237976320958225,\n                          '0011': 0.2209708691207961,\n                          '0100': 0.34089725358236606,\n                          '0101': 0.1288470508005519,\n                          '0110': 0.21423920626253262,\n                          '0111': 0.22534695471649932,\n                          '1000': 0.40864677595693816,\n                          '1001': 0.15309310892394862,\n                          '1010': 0.19764235376052372,\n                          '1011': 0.2538762001448738,\n                          '1100': 0.3563048203434806,\n                          '1101': 0.13975424859373686,\n                          '1110': 0.23385358667337133,\n                          '1111': 0.2633171804117612},\n        'eigenvalue': -8.796875,\n        'optimal_parameters': {   ParameterVectorElement(\u03b8[11]): -1.6079634096939346,\n                                  ParameterVectorElement(\u03b8[12]): 1.0057298236111534,\n                                  ParameterVectorElement(\u03b8[13]): -0.8789199315574304,\n                                  ParameterVectorElement(\u03b8[14]): 3.2143390671495746,\n                                  ParameterVectorElement(\u03b8[15]): -3.009854489857227,\n                                  ParameterVectorElement(\u03b8[0]): 1.9727334408208022,\n                                  ParameterVectorElement(\u03b8[1]): 0.23707676942681466,\n                                  ParameterVectorElement(\u03b8[2]): -0.05669869836988742,\n                                  ParameterVectorElement(\u03b8[3]): -0.11806991701839827,\n                                  ParameterVectorElement(\u03b8[4]): 0.9928278360097867,\n                                  ParameterVectorElement(\u03b8[5]): -1.1939901608238028,\n                                  ParameterVectorElement(\u03b8[6]): 0.7492963706422994,\n                                  ParameterVectorElement(\u03b8[7]): -0.5513525457094202,\n                                  ParameterVectorElement(\u03b8[8]): -3.230761529573143,\n                                  ParameterVectorElement(\u03b8[9]): 4.129926276845885,\n                                  ParameterVectorElement(\u03b8[10]): -1.6012151344000218},\n        'optimal_point': array([ 1.97273344, -1.60121513, -1.60796341,  1.00572982, -0.87891993,\n            3.21433907, -3.00985449,  0.23707677, -0.0566987 , -0.11806992,\n            0.99282784, -1.19399016,  0.74929637, -0.55135255, -3.23076153,\n            4.12992628]),\n        'optimal_value': -8.796875,\n        'optimizer_evals': 159,\n        'optimizer_time': 1.9719994068145752}\n\n\n\n```python\n\n```\n\n\n```python\nmaster_counts = []\nmaster_values = []\nfor h in range (1,5,1): \n  counts = []\n  values = []\n  result = vqe.compute_minimum_eigenvalue(H)\n  master_counts.append(counts)\n  master_values.append(values)\n  \n\n```\n\n\n```python\nplt.figure(figsize=(15,15))\nplt.plot(master_counts[0],master_values[0])\nplt.plot(master_counts[1],master_values[1])\nplt.plot(master_counts[2],master_values[2])\nplt.plot(master_counts[3],master_values[3])\nplt.xlabel('optimization step')\nplt.ylabel('E')\nplt.legend(['h=1', 'h=2', 'h=3', 'h=4'], loc='upper right')\nplt.show()\n```\n\n\n```python\n def HamiltonianPreparation(num_of_qubits:int):\n  identity_list = [['I' for i in range(num_of_qubits)] for j in range(num_of_qubits)]\n  for i in range(num_of_qubits):\n    identity_list[i][i] = 'X'\n      \n  hamiltonian_string = \"\"\n\n  # for i in range(len):\n  #   for j in range(i): \n  #     hamiltonian = hamiltonian \n\n  for row in identity_list:\n    hamiltonian_string += \" ( \"\n    for j in range(len(row)):\n      if j < len(row) - 1:\n        hamiltonian_string += row[j] + \" ^ \"\n      else:\n        hamiltonian_string += row[j]\n    hamiltonian_string += \" ) + \" \n    \n  hamiltonian_string = hamiltonian_string[0:-3]\n\n  return hamiltonian_string\n\n```\n\n\n```python\ndef HamiltonianPreparation_J(num_of_qubits:int):\n  identity_list = [['I' for i in range(num_of_qubits)] for j in range(num_of_qubits)]\n  for i in range(num_of_qubits):\n    if i!=num_of_qubits-1:\n      identity_list[i][i] = 'Z'\n      identity_list[i][i+1] = 'Z'\n    else:\n      identity_list[i][i] = 'Z'\n      identity_list[i][0] = 'Z'\n      \n  hamiltonian_string = \"\"\n\n  # for i in range(len):\n  #   for j in range(i): \n  #     hamiltonian = hamiltonian \n\n  for row in identity_list:\n    hamiltonian_string += \"( \"\n    for j in range(len(row)):\n      if j < len(row) - 1:\n        hamiltonian_string += row[j] + \" ^ \"\n      else:\n        hamiltonian_string += row[j]\n    hamiltonian_string += \") + \" \n    \n  hamiltonian_string = hamiltonian_string[0:-3]\n\n  return hamiltonian_string\n\n```\n\n\n```python\n def HamiltonianPreparation_bz(num_of_qubits:int):\n  identity_list = [['I' for i in range(num_of_qubits)] for j in range(num_of_qubits)]\n  for i in range(num_of_qubits):\n    identity_list[i][i] = 'Z'\n      \n  hamiltonian_string = \"\"\n\n  # for i in range(len):\n  #   for j in range(i): \n  #     hamiltonian = hamiltonian \n\n  for row in identity_list:\n    hamiltonian_string += \"( \"\n    for j in range(len(row)):\n      if j < len(row) - 1:\n        hamiltonian_string += row[j] + \" ^ \"\n      else:\n        hamiltonian_string += row[j]\n    hamiltonian_string += \" ) + \" \n    \n  hamiltonian_string = hamiltonian_string[0:-3]\n\n  return hamiltonian_string\n\n```\n\n\n```python\nprint(HamiltonianPreparation(36))\n```\n\n     ( X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ) +  ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X )\n\n\n\n```python\nH = - B_Z * (( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z)\n) + J_z * ((( Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z) + ( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z))) - B_X * (( X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X)\n)\n```\n\n\n```python\nmaster_counts = []\nmaster_values = []\n\nh = 1  # or whatever value you have for h\nH = - h * ((X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X))\n\n\n# you can swap this for a real quantum device and keep the rest of the code the same!\nbackend = AerSimulator(method='matrix_product_state')\n\n# COBYLA usually works well for small problems like this one\noptimizer = COBYLA(maxiter=200)\n\n# EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library\nansatz = TwoLocal(num_qubits=50, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True)\n\n# set the algorithm\nvqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result)\n\n# run it with the Hamiltonian we defined above\nresult = vqe.compute_minimum_eigenvalue(H)  \n\n# print the result (it contains lot's of information)\n# print(result) \n```\n\n\n```python\nprint(result)\n```\n\n    {   'aux_operator_eigenvalues': None,\n        'cost_function_evals': 200,\n        'eigenstate': {   '00001001011010001101000110001000010001010100001110': 0.03125,\n                          '00100000001000001101000010001000100101101011010011': 0.03125,\n                          '00101000000100101101000010011000010000100101011011': 0.03125,\n                          '00101000000110100100100111011011001001010101111010': 0.03125,\n                          '00101000001000001101000110001001110011000101010010': 0.03125,\n                          '00101000001000101111100110001000110001100011001010': 0.03125,\n                          '00101000001100001001101100001001010001001011011110': 0.03125,\n                          '00101000001100101101100111000010010100000000010110': 0.03125,\n                          '00101000010010011101100100001000010101011111000011': 0.03125,\n                          '00101000011110011101000100000010110001011101000010': 0.03125,\n                          '00101000011110100101101000001101110001011011011011': 0.03125,\n                          '00101000110010101101000110001001011001000011011010': 0.03125,\n                          '00101000111110001000000010011010011101100111011011': 0.03125,\n                          '00101001001110001101100100001010011001010101101111': 0.03125,\n                          '00101001001111001100100010001000010000010100011011': 0.03125,\n                          '00101001011010001101100101001001101101000111001111': 0.03125,\n                          '00101001011010101101000000001001011111000101011010': 0.03125,\n                          '00101001011010101111000100001011001101100111011010': 0.03125,\n                          '00101001101110000101000100001000000100001000001010': 0.03125,\n                          '00101001110100100001001010001010000101111011000010': 0.03125,\n                          '00101001111000101101100100001001110000010101011110': 0.03125,\n                          '00101010000011111101000000000000011000000001010110': 0.03125,\n                          '00101010001110100101100000011000100011011111010010': 0.03125,\n                          '00101010010010111101100110001000010000011011001010': 0.03125,\n                          '00101010011000101111100100001000110000010011111010': 0.03125,\n                          '00101010011010101001100110001000000001110111001110': 0.03125,\n                          '00101010011010101101000101011001010000000111011011': 0.03125,\n                          '00101010101010101111100010000000000011010110011010': 0.03125,\n                          '00101010110000001101100111001011111101011011111011': 0.03125,\n                          '00101011000110101101100110011010010000000011011011': 0.03125,\n                          '00101011001010000101000101001000010100010011011010': 0.03125,\n                          '00101011010010001101100100001000011101001111011010': 0.03125,\n                          '00101011011110101101000100001011000001011101011010': 0.03125,\n                          '00101011011110101111000100011101100001010011001010': 0.03125,\n                          '00101011111010101101000111001001010001000111110011': 0.03125,\n                          '00101011111010101111000001001000000000001011000010': 0.03125,\n                          '00101011111110001101100010001000010001001001001010': 0.03125,\n                          '00111010001110011111100000001010001100011011011010': 0.03125,\n                          '00111010101000001101000100001001010011110110000010': 0.03125,\n                          '01011011001110001111000110011010000100010100011011': 0.03125,\n                          '01101000000010100101000000011001000101010011011110': 0.03125,\n                          '01101000000110000101000000001010000001000111001010': 0.03125,\n                          '01101000001100001101100000001000000001000001001010': 0.03125,\n                          '01101000001110001111110000001100000101010101010010': 0.03125,\n                          '01101000011110011101100110010001000001011001011010': 0.03125,\n                          '01101000011110101111000100001000111101010010001010': 0.03125,\n                          '01101000111000001111000110001011010101001011000010': 0.03125,\n                          '01101000111000101101000100001001010001010001011011': 0.03125,\n                          '01101001001010100101000101011000010011111111000010': 0.03125,\n                          '01101001001110011111100100001000001001110011100010': 0.03125,\n                          '01101001011010000101000010001010000010110011000011': 0.03125,\n                          '01101001011010001101100110001011110101010111010010': 0.03125,\n                          '01101001011110100101100101011000010001110000011110': 0.03125,\n                          '01101001110000100101000100001001000111111011101010': 0.03125,\n                          '01101010001000101001100011011010010001010111011010': 0.03125,\n                          '01101010001010001111000011001000110001010100011011': 0.03125,\n                          '01101010001110001101100100001000010001100111110010': 0.03125,\n                          '01101010001110101101100101001010000001010111001111': 0.03125,\n                          '01101010010110000101001100001111011001000111011011': 0.03125,\n                          '01101010010110001101100110011100010001010101011001': 0.03125,\n                          '01101010011000001101000010001010000000100111011010': 0.03125,\n                          '01101010011010001111000000011010110101011101011010': 0.03125,\n                          '01101010011010101001000010011000010001000011011010': 0.03125,\n                          '01101010011010101111100110001000101101011101011010': 0.03125,\n                          '01101010011100001100100100001000100101011101000010': 0.03125,\n                          '01101010011100011111000100001000010010100111011000': 0.03125,\n                          '01101010011110001101100011011010100001010001001010': 0.03125,\n                          '01101010111100101111000100001010001001000001011011': 0.03125,\n                          '01101011001010001101100101001101100101010101000010': 0.03125,\n                          '01101011001100001100000101001010010001010111011010': 0.03125,\n                          '01101011001110100111000110001010101000011010011011': 0.03125,\n                          '01101011011010001101100000001000100100011101001110': 0.03125,\n                          '01101011011100101101000000001010000100000111111010': 0.03125,\n                          '01101011011100101111000000001000000000110000001010': 0.03125,\n                          '01101011011100111111000000000010010111101111011111': 0.03125,\n                          '01101011011110001111100100001000000111000101001010': 0.03125,\n                          '01101011101110000101000100011101010011011101010010': 0.03125,\n                          '01101011111000000001100110001001010001000001001011': 0.03125,\n                          '01101011111000001101000000011010011101000011001111': 0.03125,\n                          '01101011111010101011100101001011100001010011011110': 0.03125,\n                          '01101100101000101111100010001001010000010001000011': 0.03125,\n                          '01101110001110001100000010001010000101011000011110': 0.03125,\n                          '01111010011010001101100100001011000001110111101010': 0.03125,\n                          '10000011011100001001000100001001010000000001000110': 0.03125,\n                          '10001000000000101011100110001011000100011001001011': 0.03125,\n                          '10001000011000001111000110001011011001001111001110': 0.03125,\n                          '10001000011100001101000000001110000001000001001010': 0.03125,\n                          '10001000011110100001101011001000000000000001001010': 0.03125,\n                          '10001000101100000101100001001010011011110101011011': 0.03125,\n                          '10001001001010001101100001001000000001000001000010': 0.03125,\n                          '10001001010010011101101111001000000011010000011010': 0.03125,\n                          '10001001011110101101000000001011010100011100111011': 0.03125,\n                          '10001010001000100111000000001001100001011001010011': 0.03125,\n                          '10001010010010101101100110001010011100011011011010': 0.03125,\n                          '10001010010100001111100000001010010110110101001110': 0.03125,\n                          '10001010011010101111000100001001110011010011000010': 0.03125,\n                          '10001011001100001001000000001000010001000101000010': 0.03125,\n                          '10001011011000101101000011001011000000010101010111': 0.03125,\n                          '10001011011010101101000000001001010000000111011010': 0.03125,\n                          '10001011011010101101000111001011100000000011001010': 0.03125,\n                          '10001011011010101101000111011010010001010001011010': 0.03125,\n                          '10001011111000111101100110001001110100000011001010': 0.03125,\n                          '10100000111000001111000110001010011111110010101010': 0.03125,\n                          '10100001100110101101000110001110100001010001000011': 0.03125,\n                          '10100010011000001101101101001001001011111101000011': 0.03125,\n                          '10100010111000001001100011001011010011110111011010': 0.03125,\n                          '10100011000000101101000000001010000101010001011111': 0.03125,\n                          '10100011001000001101000100001001000011111001000010': 0.03125,\n                          '10100011001000011001000010011000010000111111011011': 0.03125,\n                          '10100011011010101001000110001000001001010011010010': 0.03125,\n                          '10101000000000000101000001001001010101101011001011': 0.03125,\n                          '10101000000010101101000100001101000001011101011010': 0.03125,\n                          '10101000000100001101000110011000000010111111011010': 0.03125,\n                          '10101000000110101111001100001000000001000101011010': 0.03125,\n                          '10101000001000001101000100011110000101110111011011': 0.03125,\n                          '10101000001000001101000101001011000000001011000010': 0.03125,\n                          '10101000001000001101100010001000000001100010001010': 0.03125,\n                          '10101000001000011101000100001000110011000111011110': 0.03125,\n                          '10101000001000100001101100011011000000010111000010': 0.03125,\n                          '10101000001000101101000100000000101001011101010111': 0.03125,\n                          '10101000001000111101100110001011011001000101011111': 0.03125,\n                          '10101000001010000111100101001000010101010101011011': 0.03125,\n                          '10101000001010001001100100001000100001110011011010': 0.03125,\n                          '10101000001010001001101100001001110001001111011011': 0.03125,\n                          '10101000001010001101000110001001000001010111011000': 0.03125,\n                          '10101000001010001101100100001010110001010101010010': 0.03125,\n                          '10101000001010101101100010001001010001000111001011': 0.03125,\n                          '10101000001100101101000100000001000110110101011110': 0.03125,\n                          '10101000001100101101000110011010101001111111011110': 0.03125,\n                          '10101000001100111001000100001001000001000011011010': 0.03125,\n                          '10101000001100111101100100001011001001010001001010': 0.03125,\n                          '10101000001110000101100000001010010001110110001010': 0.03125,\n                          '10101000001110001110100101000011000101001011011010': 0.03125,\n                          '10101000001110100111100101000000110101010011000000': 0.03125,\n                          '10101000001110101101000100001000100001011011011010': 0.03125,\n                          '10101000001110111001101101001010110000010001001010': 0.03125,\n                          '10101000001111101101000000011000010001000011000010': 0.03125,\n                          '10101000010000000101100000001011111000010101001010': 0.03125,\n                          '10101000010000001001000100001000010001000111010010': 0.03125,\n                          '10101000010000001001000100001000100101010101001010': 0.03125,\n                          '10101000010000001101100100001000010001100011011010': 0.03125,\n                          '10101000010000010101100000001001010000110110011010': 0.03125,\n                          '10101000010000100101100101001000010000011011010010': 0.03125,\n                          '10101000010000101001100010001011010101000101011010': 0.03125,\n                          '10101000010010000101101100001010010001010011000000': 0.03125,\n                          '10101000010010001101001011000001000001001111011010': 0.03125,\n                          '10101000010010001101100000001000010001011101001011': 0.03125,\n                          '10101000010010001111100010001001100001010011000000': 0.03125,\n                          '10101000010010100101100000001100111011100001011010': 0.03125,\n                          '10101000010010100101100110001000111100000100010010': 0.03125,\n                          '10101000010010100111100101001001011001110001011010': 0.03125,\n                          '10101000010010101101100000001010110101000011001010': 0.03125,\n                          '10101000010010101101100100001001010100010111011010': 0.03125,\n                          '10101000010100101101000110001000000101100011011011': 0.03125,\n                          '10101000010110001101100000000000100000010001000010': 0.03125,\n                          '10101000010110101101000100001000110000010101011011': 0.03125,\n                          '10101000010110101101000100001000111001110101001010': 0.03125,\n                          '10101000011000000101100101000001110001000101011110': 0.03125,\n                          '10101000011000001101000000001000110001011011001011': 0.03125,\n                          '10101000011000100100100000001001010001010111111011': 0.03125,\n                          '10101000011000101101101100001111100101110011010011': 0.03125,\n                          '10101000011001110101100100001000000000110001001011': 0.03125,\n                          '10101000011010001001000100001000000001011011011010': 0.03125,\n                          '10101000011010001011000100001000011010100101011011': 0.03125,\n                          '10101000011010001101100000000010010011110001001010': 0.03125,\n                          '10101000011010001101100010001011101000000011011010': 0.03125,\n                          '10101000011010001101100100001001000111010010011111': 0.03125,\n                          '10101000011010001101100100001001010101101010001010': 0.03125,\n                          '10101000011010001101100100001010000001110001011011': 0.03125,\n                          '10101000011010001111000010001011010000100001011011': 0.03125,\n                          '10101000011010001111100000001010000000101110001010': 0.03125,\n                          '10101000011010100001000000001000010001110111001110': 0.03125,\n                          '10101000011010100001001101001001000000000101011011': 0.03125,\n                          '10101000011010100101000110001000000101011111001010': 0.03125,\n                          '10101000011010100101100000001001000101011111000010': 0.03125,\n                          '10101000011010101001000100011001101000000101001110': 0.03125,\n                          '10101000011010101001100000001000001001001101011010': 0.03125,\n                          '10101000011010101001100011000100110001000101010011': 0.03125,\n                          '10101000011010101101100101001000100101010011001011': 0.03125,\n                          '10101000011010101101100110001000100001010111010110': 0.03125,\n                          '10101000011100001101000100001000000000000011011110': 0.03125,\n                          '10101000011100100101100100001011110000110101111010': 0.03125,\n                          '10101000011100101101000110011011010101010101011010': 0.03125,\n                          '10101000011100101101100100001000000001110001000011': 0.03125,\n                          '10101000011100101101100100001011110001100101000110': 0.03125,\n                          '10101000011110000101000000001010010001010111111010': 0.03125,\n                          '10101000011110001101000000001010010001000011000010': 0.03125,\n                          '10101000011110011101100100001000000001000011010011': 0.03125,\n                          '10101000011110100101000001001001010011000001000011': 0.03125,\n                          '10101000011110100101000010001010010000001011011010': 0.03125,\n                          '10101000011110100101000100001000100011100011001011': 0.03125,\n                          '10101000011110100101100100001010010101010101011110': 0.03125,\n                          '10101000011110101101000100001001001101010111001010': 0.03125,\n                          '10101000011111001101100100001010000110000011011010': 0.03125,\n                          '10101000011111100101100110001001010101010111011010': 0.03125,\n                          '10101000100000001101100000001001101101000011011010': 0.03125,\n                          '10101000100010001001000001001001011011000111011010': 0.03125,\n                          '10101000101000001101000000001010010101010111011010': 0.03125,\n                          '10101000101010001001000000001011001001010001000110': 0.03125,\n                          '10101000101010101101000100000010100001000111100110': 0.03125,\n                          '10101000110000101101000100001000000011110001000010': 0.03125,\n                          '10101000110110001101000010001101010100010001000010': 0.03125,\n                          '10101000110110011011100001001010011100010111001011': 0.03125,\n                          '10101000111000001001100100001001100001001000011110': 0.03125,\n                          '10101000111000100101000010001001111001011001011010': 0.03125,\n                          '10101000111000101101100000001001010101010000001010': 0.03125,\n                          '10101000111000101101100101001011000000111101011110': 0.03125,\n                          '10101000111010000101100100001000111001010111010010': 0.03125,\n                          '10101000111010001101000011001001000000000101011000': 0.03125,\n                          '10101000111010001101000100001000110101000001011011': 0.03125,\n                          '10101000111010001101100100001000000100100101011010': 0.03125,\n                          '10101000111010011101100000011001001101100011111010': 0.03125,\n                          '10101000111010101101100101001100010001000110101010': 0.03125,\n                          '10101000111110001000100100011011000001000111001010': 0.03125,\n                          '10101000111110001001100100001000010001010111000101': 0.03125,\n                          '10101001000000001011000010001010010001010001000000': 0.03125,\n                          '10101001000000101101000100001000100000010111001010': 0.03125,\n                          '10101001000011011011000010001011001011000000001010': 0.03125,\n                          '10101001000110001001000101000000110101000100111011': 0.03125,\n                          '10101001000110001101100000001011100111010011011111': 0.03125,\n                          '10101001001000001101000100011111110110011001011010': 0.03125,\n                          '10101001001000101001000010001000010001010001011010': 0.03125,\n                          '10101001001000101101100100001010110001000101000011': 0.03125,\n                          '10101001001000110101101101001010000001000011010110': 0.03125,\n                          '10101001001010000101000110001011010000001001000010': 0.03125,\n                          '10101001001010100010100010001010110000010111001010': 0.03125,\n                          '10101001001010101001100000011011010001100111010010': 0.03125,\n                          '10101001001100100111000000001001010001000011011110': 0.03125,\n                          '10101001001100101101000010001000000101011101011011': 0.03125,\n                          '10101001001100111101100010001000000001010101011010': 0.03125,\n                          '10101001001110001101000000001010000001010001000010': 0.03125,\n                          '10101001001110001101101100001100000110110101001010': 0.03125,\n                          '10101001001110101001100100001000011101000101011010': 0.03125,\n                          '10101001001110101101100100001001110001011001001010': 0.03125,\n                          '10101001001110101101100101001010010001010000011110': 0.03125,\n                          '10101001010000001101100110011000000000010000011110': 0.03125,\n                          '10101001010000100101101000000001110101010111010010': 0.03125,\n                          '10101001010010001101000010001000010001110001011010': 0.03125,\n                          '10101001010010001101100000011001000001010000011010': 0.03125,\n                          '10101001010010100001000001011001000001000001001010': 0.03125,\n                          '10101001010010101111000100000010010011101101011110': 0.03125,\n                          '10101001010110001101101100001000010100010001011011': 0.03125,\n                          '10101001011000001101101000000010000101000011001101': 0.03125,\n                          '10101001011000001111000000011010001000000101001010': 0.03125,\n                          '10101001011000010101000100001111001001010011000010': 0.03125,\n                          '10101001011000100101000110001010110011000011001010': 0.03125,\n                          '10101001011000101101000000001001110001101101001010': 0.03125,\n                          '10101001011000101101001000011000000000011010001111': 0.03125,\n                          '10101001011010000111000000001000110001110101001011': 0.03125,\n                          '10101001011010001001100000001011110001010111001010': 0.03125,\n                          '10101001011010001101100110001001101001000111001010': 0.03125,\n                          '10101001011010011001000000001010110101010011011011': 0.03125,\n                          '10101001011010011001100101001000110001011101010010': 0.03125,\n                          '10101001011010100001000100000010000011000010001110': 0.03125,\n                          '10101001011010100101000111001000010100010111001010': 0.03125,\n                          '10101001011010100101100000001000001001110001000000': 0.03125,\n                          '10101001011010101101000000001001111111000011011010': 0.03125,\n                          '10101001011010101101100000001000010001111111011110': 0.03125,\n                          '10101001011010101101100100001001101001000011001000': 0.03125,\n                          '10101001011100001101000000001000010001010111000110': 0.03125,\n                          '10101001011100001111000000001010010001010001011010': 0.03125,\n                          '10101001011100011101100000001000110001010001011010': 0.03125,\n                          '10101001011100100100100100001000001001110001011011': 0.03125,\n                          '10101001011100101101000100001000000001011011011011': 0.03125,\n                          '10101001011110000011100001001010000101000011001010': 0.03125,\n                          '10101001011110000101000010001000000010010001001010': 0.03125,\n                          '10101001011110001100100011000000110101100111000010': 0.03125,\n                          '10101001011110001111000000001010010001000001001010': 0.03125,\n                          '10101001011110101100000100000010000001011011001011': 0.03125,\n                          '10101001011110101111100100001000110000010011001010': 0.03125,\n                          '10101001011110111001000000001011110110000001001011': 0.03125,\n                          '10101001101000101101100100011001011001010011001011': 0.03125,\n                          '10101001101010001001000100001000010010111001011010': 0.03125,\n                          '10101001101110000101100101011010010011110111011110': 0.03125,\n                          '10101001101110001101100000011000100011010101011011': 0.03125,\n                          '10101001101110001101100100001010110001010001011010': 0.03125,\n                          '10101001110010101111000010001001000100010101011001': 0.03125,\n                          '10101001111000000101000001001000000001010110100010': 0.03125,\n                          '10101001111000000111000001011000010011000011011010': 0.03125,\n                          '10101001111010001101000100001000000110011001001111': 0.03125,\n                          '10101001111010001111100000001100011011000001001010': 0.03125,\n                          '10101001111100001001000100000000000001001011011110': 0.03125,\n                          '10101001111110000101000110001010010101010101001011': 0.03125,\n                          '10101010000000101101100000001010010101000101011010': 0.03125,\n                          '10101010000010001111000110001000010001000011000011': 0.03125,\n                          '10101010000010101101000110001001100001101101001010': 0.03125,\n                          '10101010000010101101100100001010000001110001000010': 0.03125,\n                          '10101010000100001111101000011100000000010110001110': 0.03125,\n                          '10101010000110000101100101001001010001100011011011': 0.03125,\n                          '10101010000110101101100010001100100110111011011010': 0.03125,\n                          '10101010001000000101100000001000011100110011011010': 0.03125,\n                          '10101010001000001001000100001010010001010001111010': 0.03125,\n                          '10101010001000001101100100001000010000010101011010': 0.03125,\n                          '10101010001000001111100001001000001001011011000110': 0.03125,\n                          '10101010001000100011000000001011010001110000001011': 0.03125,\n                          '10101010001000101101100111001001000001010111001010': 0.03125,\n                          '10101010001001100111000101000001000000001011010011': 0.03125,\n                          '10101010001010000101100110011000101001111101011010': 0.03125,\n                          '10101010001010001101000100001000100101011111011011': 0.03125,\n                          '10101010001010001101100000001000000001110011011010': 0.03125,\n                          '10101010001010001101100100001001010001001101011010': 0.03125,\n                          '10101010001010001110100000001010000001010001000010': 0.03125,\n                          '10101010001010100101100100001000110101110111010011': 0.03125,\n                          '10101010001010101011100100001000010011110101011010': 0.03125,\n                          '10101010001010101101100000000011001100000001001010': 0.03125,\n                          '10101010001010101101101100001010000001010101010010': 0.03125,\n                          '10101010001100000101100100001000010001110011110010': 0.03125,\n                          '10101010001100001101000000001000000110011101011010': 0.03125,\n                          '10101010001100001111000100001011000100110001001001': 0.03125,\n                          '10101010001100001111100100011000110001000110011011': 0.03125,\n                          '10101010001100001111100110001010000101000101100010': 0.03125,\n                          '10101010001100100001110100001000000101100111011011': 0.03125,\n                          '10101010001100101101100100011000100101000011010010': 0.03125,\n                          '10101010001110001101101110001001001000011011011001': 0.03125,\n                          '10101010001110001111100010001001100101010001010010': 0.03125,\n                          '10101010001110101101000100001101100001011001001001': 0.03125,\n                          '10101010001110101101100100001000100111010011010011': 0.03125,\n                          '10101010001110101101100110001000110001101001011010': 0.03125,\n                          '10101010010000001001100100001010000000001011001010': 0.03125,\n                          '10101010010000001101000100001000010110000111001100': 0.03125,\n                          '10101010010010000111100100011011000011001111011010': 0.03125,\n                          '10101010010010101001000100000010010001001101011010': 0.03125,\n                          '10101010010010101101100101001001100001010011010010': 0.03125,\n                          '10101010010010101111100110001000010001011001000010': 0.03125,\n                          '10101010010100001100100100001001000011110001001010': 0.03125,\n                          '10101010010110001101000100001001000101110101001011': 0.03125,\n                          '10101010010110001101100001011010010001000001000010': 0.03125,\n                          '10101010010110001111000110001000101001001101001010': 0.03125,\n                          '10101010010110001111101100001011000100010111011010': 0.03125,\n                          '10101010010110101001000110001011010001001111011011': 0.03125,\n                          '10101010010110101101100001001000000001000011011011': 0.03125,\n                          '10101010010110101101101000001010010000010011010010': 0.03125,\n                          '10101010011000000001000100001000100100010011010010': 0.03125,\n                          '10101010011000000001100100001011010000000111001110': 0.03125,\n                          '10101010011000000101000110001000010000010001011000': 0.03125,\n                          '10101010011000001101000100011010110001011100001110': 0.03125,\n                          '10101010011000001101100000011000010101001100011110': 0.03125,\n                          '10101010011000001101100110011000100001000011010010': 0.03125,\n                          '10101010011000100001100100011010100001010101011110': 0.03125,\n                          '10101010011000101101000100001111010100011111001010': 0.03125,\n                          '10101010011000101101000101001010001001010111011110': 0.03125,\n                          '10101010011000101101001010001000100001011101011010': 0.03125,\n                          '10101010011000101101100000101001011001100001010010': 0.03125,\n                          '10101010011000101111100100001010110001010001001010': 0.03125,\n                          '10101010011001001001000100001000010001110011010010': 0.03125,\n                          '10101010011001001101100100001001110011001011011000': 0.03125,\n                          '10101010011001001111100110001011110000000101011011': 0.03125,\n                          '10101010011010000000100100001011010011000111001010': 0.03125,\n                          '10101010011010000100100110001000000101110101011011': 0.03125,\n                          '10101010011010000101000100001001011001100101100010': 0.03125,\n                          '10101010011010000101100110001000010001010011011110': 0.03125,\n                          '10101010011010001101000000001000011101010001011100': 0.03125,\n                          '10101010011010001101000100001000010110100101011010': 0.03125,\n                          '10101010011010001101100001001001010001100011001110': 0.03125,\n                          '10101010011010001101100110001010000000010001001010': 0.03125,\n                          '10101010011010001101100110001011010001010101001010': 0.03125,\n                          '10101010011010011111000100001001000001000011010010': 0.03125,\n                          '10101010011010100101000100001011010001101001011010': 0.03125,\n                          '10101010011010100101100000001100011001010011011110': 0.03125,\n                          '10101010011010101000000101001000010001000001001010': 0.03125,\n                          '10101010011010101001100000001011010000010011000011': 0.03125,\n                          '10101010011010101101000100001000010100010100001010': 0.03125,\n                          '10101010011010101101000101001001100000100011011010': 0.03125,\n                          '10101010011010101101100000001010010011000110011110': 0.03125,\n                          '10101010011010101101100000011001000000010000010011': 0.03125,\n                          '10101010011010101101100010001000110000111011001010': 0.03125,\n                          '10101010011010101101100110001000000101010001011011': 0.03125,\n                          '10101010011010101111000100011010100000000101000110': 0.03125,\n                          '10101010011010101111100100001010010000010111001110': 0.03125,\n                          '10101010011010101111100101001011001011000101011110': 0.03125,\n                          '10101010011010110101000000011001100100010101010010': 0.03125,\n                          '10101010011010110111000110001011000000010000001000': 0.03125,\n                          '10101010011010111001100100001001000101111011010010': 0.03125,\n                          '10101010011010111101100011001001000111000001010010': 0.03125,\n                          '10101010011011001101100001001000010000010010010010': 0.03125,\n                          '10101010011100000001100010001000001000000011001010': 0.03125,\n                          '10101010011100001101100010001000010001000001001010': 0.03125,\n                          '10101010011100101101100100011001000001000101011110': 0.03125,\n                          '10101010011100101110000000001000010001001111010011': 0.03125,\n                          '10101010011101001111100010001010000001010001011011': 0.03125,\n                          '10101010011110000101000101001010000001010101011011': 0.03125,\n                          '10101010011110001101100100001001110101101011000010': 0.03125,\n                          '10101010011110001101100100011011110010110011011000': 0.03125,\n                          '10101010011110001111100110011001010010010001010111': 0.03125,\n                          '10101010011110100001100100001000010111100111001010': 0.03125,\n                          '10101010011110101101100010011001010001011111011010': 0.03125,\n                          '10101010011111001101100000001000010000100001011011': 0.03125,\n                          '10101010100000000101000100000010011001000001011111': 0.03125,\n                          '10101010101000001101101100001000010101100111011111': 0.03125,\n                          '10101010101000001111100100001010000001110001001010': 0.03125,\n                          '10101010101000101101000011001011100001001001011110': 0.03125,\n                          '10101010101000101101100100001001110011010110011010': 0.03125,\n                          '10101010101010000101000100001010010010010001011011': 0.03125,\n                          '10101010101010001001100100000101010000010001001010': 0.03125,\n                          '10101010101010001111100100001001100111000101011110': 0.03125,\n                          '10101010101010100101100100011011100101100111001010': 0.03125,\n                          '10101010101100000101001000001010001101001110011011': 0.03125,\n                          '10101010101100001101100000001011010101000001011010': 0.03125,\n                          '10101010101110101101100010011011010101000011011011': 0.03125,\n                          '10101010101110101111000000001000000100001001011000': 0.03125,\n                          '10101010101110101111100000001010010000000111011010': 0.03125,\n                          '10101010110000100101000000001000010000000011011011': 0.03125,\n                          '10101010110110000101100000001000010001010011011111': 0.03125,\n                          '10101010110110001101100000001010000100111001011111': 0.03125,\n                          '10101010111000001100000110001001000001000000001010': 0.03125,\n                          '10101010111000001101000000011000100101000011011010': 0.03125,\n                          '10101010111000101101100100000010010000011010001010': 0.03125,\n                          '10101010111000101110100010001011001101111101011101': 0.03125,\n                          '10101010111010001011100010011000110001001101001010': 0.03125,\n                          '10101010111010001101100101001001110001011011001100': 0.03125,\n                          '10101010111010100001100010001011011001010011011011': 0.03125,\n                          '10101010111010101101100000011001110011010101011110': 0.03125,\n                          '10101010111010101101100101011010110101100011001010': 0.03125,\n                          '10101010111010110001100111001010000001110000101010': 0.03125,\n                          '10101010111100000101000010001010100101010001011010': 0.03125,\n                          '10101010111100001101100001001001111010000001011010': 0.03125,\n                          '10101010111110000101000011011010100001010111001010': 0.03125,\n                          '10101010111110000101000101001110000000010011001111': 0.03125,\n                          '10101010111110000101100100001010011001001001011011': 0.03125,\n                          '10101010111110001101000101001010000111010011011001': 0.03125,\n                          '10101010111110001101100000001000110101011101010010': 0.03125,\n                          '10101010111110001101100100001000000100010011011011': 0.03125,\n                          '10101010111110001101100100001011110001010101101010': 0.03125,\n                          '10101011000000001101100010011010011101010000011011': 0.03125,\n                          '10101011000010000101100000001000000100100001010010': 0.03125,\n                          '10101011000010101101000010001010000001011001011010': 0.03125,\n                          '10101011000100100111100101001001100001000001001010': 0.03125,\n                          '10101011000100101111000000001000010001000111000110': 0.03125,\n                          '10101011001000011101100000001010110001100011101010': 0.03125,\n                          '10101011001000111111100000011010100110001001001110': 0.03125,\n                          '10101011001010000101000100001000010000110101010010': 0.03125,\n                          '10101011001010000101000100001001010001010101101011': 0.03125,\n                          '10101011001010001001100110001010000101010001001010': 0.03125,\n                          '10101011001010001101100100001001001000110011011010': 0.03125,\n                          '10101011001010101001000101011000101101010111011010': 0.03125,\n                          '10101011001010101101000100001000010000000001011010': 0.03125,\n                          '10101011001010101101100010001010110001010001011011': 0.03125,\n                          '10101011001011101101100000001001110001100011011011': 0.03125,\n                          '10101011001100000101000100001001110001010101000110': 0.03125,\n                          '10101011001100001101100111001011100100011011011010': 0.03125,\n                          '10101011001100100101100110001011101101000111000011': 0.03125,\n                          '10101011001100101101000010001001010001010011111010': 0.03125,\n                          '10101011001110000101100010001010010001100100011010': 0.03125,\n                          '10101011001110001101001100001001010101011001011011': 0.03125,\n                          '10101011001110100101100100001010000000010001010010': 0.03125,\n                          '10101011001110100101100110001100010011010101001010': 0.03125,\n                          '10101011001110101101000010001000010001001101001110': 0.03125,\n                          '10101011001110101101000101011001011101000011000110': 0.03125,\n                          '10101011001110101101001100011000011001000111011110': 0.03125,\n                          '10101011001110101101100100011011000001010001011010': 0.03125,\n                          '10101011010000000001000010001001011001100100011110': 0.03125,\n                          '10101011010000001101000100001001000101000101011011': 0.03125,\n                          '10101011010000001101100100001011101111111111001011': 0.03125,\n                          '10101011010000001110101001001001010111010011000110': 0.03125,\n                          '10101011010000101101000100001000010001110011011010': 0.03125,\n                          '10101011010010001101000100001010110001010101011010': 0.03125,\n                          '10101011010010001101000101001000010010000110001111': 0.03125,\n                          '10101011010010001101101010000011011011000111110010': 0.03125,\n                          '10101011010010101101000000001001110001000111000010': 0.03125,\n                          '10101011010100010101000010001000100000110011001011': 0.03125,\n                          '10101011010100100101100100001001110001011011010010': 0.03125,\n                          '10101011010110000111000010001000111000011010100010': 0.03125,\n                          '10101011010110111111101100001000010100000001011110': 0.03125,\n                          '10101011011000001101100010011000001101011011011110': 0.03125,\n                          '10101011011000100011100110001011010001100111011010': 0.03125,\n                          '10101011011000100101100000001011110011000001010011': 0.03125,\n                          '10101011011000101101000111001001000101100011001110': 0.03125,\n                          '10101011011000101101100000001000000101010111010110': 0.03125,\n                          '10101011011000101111000000000000000001010111001011': 0.03125,\n                          '10101011011010000111000100001011001100110001000010': 0.03125,\n                          '10101011011010001001100100000010110001011101010110': 0.03125,\n                          '10101011011010001101000100001000110000101101011100': 0.03125,\n                          '10101011011010001101100100001011000000010001001010': 0.03125,\n                          '10101011011010001101100101001000010001000011011010': 0.03125,\n                          '10101011011010010100100000001000000011010110010011': 0.03125,\n                          '10101011011010101001100010001010000011000101101010': 0.03125,\n                          '10101011011010101100001101010011010000000001011111': 0.03125,\n                          '10101011011010101101100000001000010001100111001010': 0.03125,\n                          '10101011011011010101000001001001001100010100011110': 0.03125,\n                          '10101011011100001101100100001000011001110001011011': 0.03125,\n                          '10101011011100101011100110001010101001000011010110': 0.03125,\n                          '10101011011100101101100100001000010101011001011010': 0.03125,\n                          '10101011011100111001000100001001010110010001001011': 0.03125,\n                          '10101011011101110101101100001000110111101101010110': 0.03125,\n                          '10101011011110000101101000001010100011010111000011': 0.03125,\n                          '10101011011110001001000000001101011001000011001100': 0.03125,\n                          '10101011011110001101000000001010110001000111001110': 0.03125,\n                          '10101011011110001101100000001010000101000011011010': 0.03125,\n                          '10101011011110001111000101001000000100010111011010': 0.03125,\n                          '10101011011110001111100000101000110110011111000010': 0.03125,\n                          '10101011011110100101100110001000000101000010011010': 0.03125,\n                          '10101011011110100101100110001000000110100111011011': 0.03125,\n                          '10101011011110100110100010001000000001010101101010': 0.03125,\n                          '10101011011110101101000001001010000101011011010010': 0.03125,\n                          '10101011011110101101100100011001000001111001001010': 0.03125,\n                          '10101011011111001111100110001000000011011101010011': 0.03125,\n                          '10101011100000100101100111001000000100000101011010': 0.03125,\n                          '10101011100110101101100111001010001001010101111010': 0.03125,\n                          '10101011101000001101100110001000000010100001001010': 0.03125,\n                          '10101011101000101101000110001001110101110011011110': 0.03125,\n                          '10101011101010000101101010011000011001100111011010': 0.03125,\n                          '10101011101010100101100110011000100001000011011011': 0.03125,\n                          '10101011101100001101100100001010010111000101001010': 0.03125,\n                          '10101011101111101101100101001000000001011011001110': 0.03125,\n                          '10101011110010101101001000001000010001000001000011': 0.03125,\n                          '10101011111000001100100100001011011100110011000010': 0.03125,\n                          '10101011111010001100000110001000010101000001001010': 0.03125,\n                          '10101011111010001111100000001000010001110100010010': 0.03125,\n                          '10101011111010111101001100001000000000100011011010': 0.03125,\n                          '10101011111100001100000100001011010100010111011011': 0.03125,\n                          '10101011111110000101000100001011100001010011001001': 0.03125,\n                          '10101011111110001101100110001000011001010111011010': 0.03125,\n                          '10101011111110101101100100001010110000111001011011': 0.03125,\n                          '10101100001100000101100100111001100011010001011111': 0.03125,\n                          '10101100001100101101100110001010010011010111011010': 0.03125,\n                          '10101100001110101101000100001000000011101011010010': 0.03125,\n                          '10101100011000100001000010001011100101001110000110': 0.03125,\n                          '10101100011010001101100100001000000001011001000110': 0.03125,\n                          '10101100100110111101000111001011010101010101010001': 0.03125,\n                          '10101100111000010111000010001010010001000011011010': 0.03125,\n                          '10101101001000101101100100001000000010011001101011': 0.03125,\n                          '10101101011010001101100100001000010000010011011110': 0.03125,\n                          '10101110010000101111100110001000001001001001001011': 0.03125,\n                          '10101110110110100101000000001001101001010001011010': 0.03125,\n                          '10101111001110000101000100011000000100010101001010': 0.03125,\n                          '10101111011110001001100100001011000101111100111011': 0.03125,\n                          '10111000011000101101000010001000010100000011010011': 0.03125,\n                          '10111000011010101100101100001000010000110101001010': 0.03125,\n                          '10111000011010101101100000001010011001010011011010': 0.03125,\n                          '10111000011010101111100001001000100001111000011110': 0.03125,\n                          '10111000011100100101101101001011001000001001001010': 0.03125,\n                          '10111000011100101111100000001010000001000010011010': 0.03125,\n                          '10111000111000101111100101010000100000101101011010': 0.03125,\n                          '10111001011010101101100110001000110100010001011010': 0.03125,\n                          '10111010000100001101100100001000000101001000001110': 0.03125,\n                          '10111010001010001101000110001000010111100001010110': 0.03125,\n                          '10111010010100101101100100001000010110110001011011': 0.03125,\n                          '10111010010110101001000110011000110101010011001010': 0.03125,\n                          '10111010011000100001000000001000000000110011011111': 0.03125,\n                          '10111010011010101111000000011000100101000011000010': 0.03125,\n                          '10111010011100101111101001000000010001000111001111': 0.03125,\n                          '10111010011100110111100100001000000000010001011110': 0.03125,\n                          '10111010111010001001100100001011110001001101001010': 0.03125,\n                          '10111010111110000001100110001011101111001001011011': 0.03125,\n                          '10111011010010101101000101001010110101010111011000': 0.03125,\n                          '10111011011010001100000100001010100001110011001010': 0.03125,\n                          '10111011011010001101100101001000110001110000011010': 0.03125,\n                          '10111011101000100001100010001000010001110001111010': 0.03125,\n                          '10111011111010100111100010011010110001110000011010': 0.03125,\n                          '11000000101010101001100110001001000001011010001111': 0.03125,\n                          '11000000101010101101100000001001110111010001011011': 0.03125,\n                          '11001000000010011101000000011000100111001001001111': 0.03125,\n                          '11001000010100001001000100011001010001000001011010': 0.03125,\n                          '11001000011000001111000100001010100011101101000010': 0.03125,\n                          '11001000011001101001100100001011000101000111010010': 0.03125,\n                          '11001000011010100101101001001011110000010011011000': 0.03125,\n                          '11001000110100100111100100001000100001010011001110': 0.03125,\n                          '11001001010010101111100010001010000001010001001111': 0.03125,\n                          '11001001011010111111100110001000000001111111011011': 0.03125,\n                          '11001001101100101111000000001001111011001001011010': 0.03125,\n                          '11001001110110101101000000001100100101010001011010': 0.03125,\n                          '11001001111000101100100110001000000000001001001010': 0.03125,\n                          '11001010001000101010000110001000100001010101000011': 0.03125,\n                          '11001010001010111101010010001010000101010001011010': 0.03125,\n                          '11001010010110000101000110001000110010011101001010': 0.03125,\n                          '11001010011100101101000000000010000011110100011011': 0.03125,\n                          '11001010011100101101100100001000010010001011001011': 0.03125,\n                          '11001010011110000001100100001001000101001111001011': 0.03125,\n                          '11001010011110001101100100001110001001010101011010': 0.03125,\n                          '11001010101000100101000100001110100101001101001111': 0.03125,\n                          '11001011100010100011000100001010100011001111001000': 0.03125,\n                          '11100000011110000101000110001000100101011011010011': 0.03125,\n                          '11100000011110001001100100001001110000000011011110': 0.03125,\n                          '11100000011110101011100010011011001101100001011000': 0.03125,\n                          '11100001001100001001000110001010000001010001000010': 0.03125,\n                          '11100001011110101101101110001000010101010111011000': 0.03125,\n                          '11100010001110001101100100001000010000011111010110': 0.03125,\n                          '11100010001110100101100000001000000101000011000010': 0.03125,\n                          '11100010101100100111000100001010010001011110001111': 0.03125,\n                          '11100011011000101101000100011010010001110011011110': 0.03125,\n                          '11100011011100101101000000001011000001110001001011': 0.03125,\n                          '11101000000000001101101100001001001001010011101010': 0.03125,\n                          '11101000000000101101100110011010000001010110000010': 0.03125,\n                          '11101000000010100101001010001010010101011100001110': 0.03125,\n                          '11101000000010110101001010001001001011000011000011': 0.03125,\n                          '11101000000011000111100100001000010001011011000011': 0.03125,\n                          '11101000000100100001100100001000110001110011011011': 0.03125,\n                          '11101000000100101101000000011001101011010111010110': 0.03125,\n                          '11101000001000101101000100001001000101000111001110': 0.03125,\n                          '11101000001000101101100100001010010101000111001010': 0.03125,\n                          '11101000001000101111000100011011010001010011011010': 0.03125,\n                          '11101000001001101101100000001001000001010001001010': 0.03125,\n                          '11101000001010000111100110001010100001000011010011': 0.03125,\n                          '11101000001010001101100110011011100101110011011110': 0.03125,\n                          '11101000001010001101101100011000010101010101001011': 0.03125,\n                          '11101000001010001111000110001001100001111001111010': 0.03125,\n                          '11101000001010010011000001011001011100010101011010': 0.03125,\n                          '11101000001010100101000010001101110001001001001010': 0.03125,\n                          '11101000001010101101100100000010100001011000001010': 0.03125,\n                          '11101000001010101111100000001001000011001111111011': 0.03125,\n                          '11101000001100000111000000001001001001000001001010': 0.03125,\n                          '11101000001100001111100000001101011001000001010010': 0.03125,\n                          '11101000001100100001100001011000010001101101001110': 0.03125,\n                          '11101000001100101101000100001001100000110001011010': 0.03125,\n                          '11101000001100101111100000011001100011100011011011': 0.03125,\n                          '11101000001110101101000000001000011001001111010010': 0.03125,\n                          '11101000001110101101001000011001110001010001010010': 0.03125,\n                          '11101000001110101111100100001000100000111111011011': 0.03125,\n                          '11101000010000010101000000001001110000110011110010': 0.03125,\n                          '11101000010000100101000100001010010101000011011111': 0.03125,\n                          '11101000010000101101001001001010110101001111011010': 0.03125,\n                          '11101000010000111111100000001010000011010011001110': 0.03125,\n                          '11101000010010000001100010001010010011111011001010': 0.03125,\n                          '11101000010010001101001110001001000110101011011011': 0.03125,\n                          '11101000010010100101100100001010100001010001000110': 0.03125,\n                          '11101000010010100110000100001101000001011001001010': 0.03125,\n                          '11101000010010101101000000001000000001010101001010': 0.03125,\n                          '11101000010100001100000100001000010001010101001110': 0.03125,\n                          '11101000010110001101100000001001000111010011011010': 0.03125,\n                          '11101000011000000111000000001000100001000111011011': 0.03125,\n                          '11101000011000001001100100001000010010000000001010': 0.03125,\n                          '11101000011000001101001101011000010101010101000110': 0.03125,\n                          '11101000011000001101100100000000010011101111011010': 0.03125,\n                          '11101000011000001110000100011000010101100001011110': 0.03125,\n                          '11101000011000001111000001011001100001000011010001': 0.03125,\n                          '11101000011000100101000000001011000100100101011110': 0.03125,\n                          '11101000011000100101000100011000011001000001001011': 0.03125,\n                          '11101000011000101101000011001101000000000111011010': 0.03125,\n                          '11101000011000101101000100011001000011010011001010': 0.03125,\n                          '11101000011000111101100110001000010000000101001011': 0.03125,\n                          '11101000011010001101000110001010100001000101001010': 0.03125,\n                          '11101000011010011001100000011000110101000100001010': 0.03125,\n                          '11101000011010100001100000000011001001010011011010': 0.03125,\n                          '11101000011010100101000010001000010011010011010010': 0.03125,\n                          '11101000011010100101100000011001110001010011011010': 0.03125,\n                          '11101000011010100101100010001001110010110111011011': 0.03125,\n                          '11101000011010100111100100001010010010010111001011': 0.03125,\n                          '11101000011010101001000100001011000101001101011011': 0.03125,\n                          '11101000011010101011100101001100010001000101001010': 0.03125,\n                          '11101000011010101101000010011101110111010001011010': 0.03125,\n                          '11101000011010101101000011001010000101011101001010': 0.03125,\n                          '11101000011010101101000100001011010001010011011010': 0.03125,\n                          '11101000011010101101000101001000111001011100001110': 0.03125,\n                          '11101000011010101101100000011101100001001111000010': 0.03125,\n                          '11101000011010101101100100000000000101111001001010': 0.03125,\n                          '11101000011010101101100100001000110001000011011011': 0.03125,\n                          '11101000011010101101100100001001000000010001011110': 0.03125,\n                          '11101000011010101101100100001001010000010011011011': 0.03125,\n                          '11101000011010101101100100001010000001011001000110': 0.03125,\n                          '11101000011010101101100110001000010001010011011010': 0.03125,\n                          '11101000011010101111000100011001000101010001001111': 0.03125,\n                          '11101000011010101111100010011001010001110001011110': 0.03125,\n                          '11101000011010101111101010001000110001010001011010': 0.03125,\n                          '11101000011010111101100000011010010101010111010010': 0.03125,\n                          '11101000011011001111000100001010010011011001111010': 0.03125,\n                          '11101000011011101101000101001000110000000011001011': 0.03125,\n                          '11101000011011101101000110001110100001000011101011': 0.03125,\n                          '11101000011100001101000000001010101110000001011111': 0.03125,\n                          '11101000011100001101100100011101000001101111011110': 0.03125,\n                          '11101000011100001111100110001001000000110110011010': 0.03125,\n                          '11101000011100100100100100001011100000000001011111': 0.03125,\n                          '11101000011100101011100100001000110001010001011011': 0.03125,\n                          '11101000011100101101000100001000010001000101000011': 0.03125,\n                          '11101000011100101101101110001010101001100111011011': 0.03125,\n                          '11101000011100110101100000001001100001010101010010': 0.03125,\n                          '11101000011110000111000000011010101101011001011111': 0.03125,\n                          '11101000011110000111000100001001100001010001011010': 0.03125,\n                          '11101000011110001101000001001000100010000011001011': 0.03125,\n                          '11101000011110001101000101001101100111010100011011': 0.03125,\n                          '11101000011110001101100010001000110001010010011010': 0.03125,\n                          '11101000011110001101100100001011010101000011001010': 0.03125,\n                          '11101000011110010101100100011000010101110111011010': 0.03125,\n                          '11101000011110100101001100001000000101001010011010': 0.03125,\n                          '11101000011110100101100000001010111110100101010110': 0.03125,\n                          '11101000011110100111000100011010000100000111001100': 0.03125,\n                          '11101000011110101101000000001010010001010101001011': 0.03125,\n                          '11101000011110101101000110000000000101010011011110': 0.03125,\n                          '11101000011110111001100011001001010100010001001011': 0.03125,\n                          '11101000100010101101000010001001100110010011011010': 0.03125,\n                          '11101000101000001101000100001011110101010001001011': 0.03125,\n                          '11101000101000101101000100001000000101001101011011': 0.03125,\n                          '11101000101010101001000110001000010001001011011011': 0.03125,\n                          '11101000101010111111100100001100000001010011001110': 0.03125,\n                          '11101000101100001111100110001000010101010011011011': 0.03125,\n                          '11101000101110100011000100011000010000110010111010': 0.03125,\n                          '11101000101110101111100101001000111100100011101010': 0.03125,\n                          '11101000110010101101100010001010010011110001010111': 0.03125,\n                          '11101000111000000101000001001011110001011011001010': 0.03125,\n                          '11101000111000100101000000001001000001011000000010': 0.03125,\n                          '11101000111000101100001110001100010001110101111111': 0.03125,\n                          '11101000111010000001100000010001010000101101011100': 0.03125,\n                          '11101000111010100011100110001000100101110011011010': 0.03125,\n                          '11101000111010101011100100000011000101000101000010': 0.03125,\n                          '11101000111010101100000000001000000001101101111010': 0.03125,\n                          '11101000111010101111101111100000000010110101011010': 0.03125,\n                          '11101000111100011101000111001000010001010001001011': 0.03125,\n                          '11101000111100101101000100001011001100000001000001': 0.03125,\n                          '11101000111100101111000100010000000000011011010010': 0.03125,\n                          '11101000111100111101100000001000111001010000001010': 0.03125,\n                          '11101000111110101101000101001000110001010001111010': 0.03125,\n                          '11101000111110101101001000011000010001010101011110': 0.03125,\n                          '11101001000010001101000111001000110101010011001010': 0.03125,\n                          '11101001000011100101100110011001100101000011011011': 0.03125,\n                          '11101001000100101101100011001000000001011101001011': 0.03125,\n                          '11101001001000001101000000011001011000101011011010': 0.03125,\n                          '11101001001010000101000100001011100011011110011111': 0.03125,\n                          '11101001001010001101000000001011100001010101011011': 0.03125,\n                          '11101001001010001101100100011001111010011001001010': 0.03125,\n                          '11101001001010101101000100001010100100110101011010': 0.03125,\n                          '11101001001010101101000110001000010101000001011011': 0.03125,\n                          '11101001001010101101100100000000010001011100001011': 0.03125,\n                          '11101001001010101101100100001000000001100111000010': 0.03125,\n                          '11101001001010101101101000001000110101001001011010': 0.03125,\n                          '11101001001110001101100001001000011000111011001011': 0.03125,\n                          '11101001001110001101100100001000010001110000011010': 0.03125,\n                          '11101001001110010101100101001010100001011001101010': 0.03125,\n                          '11101001001110100101100100001000000001010011011010': 0.03125,\n                          '11101001001110101111000000001010110001010001000010': 0.03125,\n                          '11101001001110111101100000001010100001111001001010': 0.03125,\n                          '11101001010010001001001010001001100000110001011010': 0.03125,\n                          '11101001010010001101000000001100000001000101011011': 0.03125,\n                          '11101001010110101001000100001000000000011011000011': 0.03125,\n                          '11101001010110101001100000001000110001001011100010': 0.03125,\n                          '11101001010110101101100000000001000111001001010011': 0.03125,\n                          '11101001010110101101100100001000110100000101011000': 0.03125,\n                          '11101001011000001101100000001010001101001110011110': 0.03125,\n                          '11101001011000001101100111001001010100000011001011': 0.03125,\n                          '11101001011000100101000011000011011101110011001011': 0.03125,\n                          '11101001011000101101001000011000010010001101011010': 0.03125,\n                          '11101001011000101101100001011001100001010011001010': 0.03125,\n                          '11101001011000101101100100000011000001000101001010': 0.03125,\n                          '11101001011010001101100010000011000011010001011110': 0.03125,\n                          '11101001011010001101100100001000010001000111001111': 0.03125,\n                          '11101001011010001101100110001001100001001101011110': 0.03125,\n                          '11101001011010001111000011001010110001010011001011': 0.03125,\n                          '11101001011010101001000110001000001010001000001000': 0.03125,\n                          '11101001011010101001100001011011010000000101110010': 0.03125,\n                          '11101001011010101100100100001000100111100001001001': 0.03125,\n                          '11101001011010101100100110001011010000100001011010': 0.03125,\n                          '11101001011010101101000000001011001011000110011110': 0.03125,\n                          '11101001011010101101100010001000010001100111001010': 0.03125,\n                          '11101001011010101101100100001001110001100001011001': 0.03125,\n                          '11101001011010101111000100001000000001010101001010': 0.03125,\n                          '11101001011100001101000010001000010011110111000010': 0.03125,\n                          '11101001011100001101100110001110110001110001011011': 0.03125,\n                          '11101001011110000101000000001001010001000001000010': 0.03125,\n                          '11101001011110000101100101001011110010010001000011': 0.03125,\n                          '11101001011110001001000001001001010001010111011010': 0.03125,\n                          '11101001011110001111000000011001000101010011001110': 0.03125,\n                          '11101001011110001111010100001000110011010001000011': 0.03125,\n                          '11101001011110101101000000010000000001011011011010': 0.03125,\n                          '11101001011110101101100000001000000000001001001010': 0.03125,\n                          '11101001100010001001100100011011110101110011011110': 0.03125,\n                          '11101001100010001101000100001001011001000010001010': 0.03125,\n                          '11101001101100101101100001001000010011100001001011': 0.03125,\n                          '11101001101110101101100000001001000100000100001010': 0.03125,\n                          '11101001110010101001100000001001010011100011001110': 0.03125,\n                          '11101001111000000111000111001010010001100010010110': 0.03125,\n                          '11101001111000011111100110011010010001000011001010': 0.03125,\n                          '11101001111010010001100000001001111001011111001000': 0.03125,\n                          '11101001111010101101000100011000011011101111011010': 0.03125,\n                          '11101001111110000101100100001001000101100011000110': 0.03125,\n                          '11101001111110001111100100001010110001011111011010': 0.03125,\n                          '11101001111110101100100000001011100000000011001010': 0.03125,\n                          '11101001111110101101100100001000000101010001011110': 0.03125,\n                          '11101010000000100101100000000000000000010001011011': 0.03125,\n                          '11101010000010001101100100001010100100110011001110': 0.03125,\n                          '11101010000010100111100111011001001000000111011011': 0.03125,\n                          '11101010000011101111000011001010000101001011001010': 0.03125,\n                          '11101010000110101101000110001001110101000001001010': 0.03125,\n                          '11101010001000000111100100001001110101011101011010': 0.03125,\n                          '11101010001000001111000110001000000101000110011011': 0.03125,\n                          '11101010001000101101100100001000000001011101111011': 0.03125,\n                          '11101010001000101101100110001000000101000101011110': 0.03125,\n                          '11101010001000101111100100001000001001010011000110': 0.03125,\n                          '11101010001010000101100100001010100000110111001011': 0.03125,\n                          '11101010001010001101100100010010010011110101000010': 0.03125,\n                          '11101010001010100101000100001000100001110111011011': 0.03125,\n                          '11101010001010101101000100001000010001110101001100': 0.03125,\n                          '11101010001010101101100100001001000111110101101011': 0.03125,\n                          '11101010001010101111100100001000000001010111011010': 0.03125,\n                          '11101010001010111101100100001010101101110101011011': 0.03125,\n                          '11101010001011001101000101001000000100010001011011': 0.03125,\n                          '11101010001100000101000000001000000001001001001110': 0.03125,\n                          '11101010001100001001100010001000100001011001011010': 0.03125,\n                          '11101010001100001101100010001000001101010011001010': 0.03125,\n                          '11101010001100001111100010001011001001100101010110': 0.03125,\n                          '11101010001100101001000000011010011011010011010011': 0.03125,\n                          '11101010001100101101100100001000100001010011001011': 0.03125,\n                          '11101010001100111101100110001001000101001111011011': 0.03125,\n                          '11101010001110000101100100000011000101000111010100': 0.03125,\n                          '11101010001110000101100100001000101101110001001010': 0.03125,\n                          '11101010001110001101100000001000000001010001001010': 0.03125,\n                          '11101010001110001101100110011000010001000111001011': 0.03125,\n                          '11101010001110011101000100001000111110001100011110': 0.03125,\n                          '11101010001110101101100001001001000011111001001010': 0.03125,\n                          '11101010010000000101000011001001001000100101000011': 0.03125,\n                          '11101010010000101111000110011011011001000111000110': 0.03125,\n                          '11101010010010000011000000001000110001001011001010': 0.03125,\n                          '11101010010010000101000110001010100100100011001111': 0.03125,\n                          '11101010010010000101100000011001000001110001011010': 0.03125,\n                          '11101010010010001101000000011101110001010010011011': 0.03125,\n                          '11101010010010101001000100001110010001010001001011': 0.03125,\n                          '11101010010100000101100010001010110101001101001010': 0.03125,\n                          '11101010010100001001100000011001000101001101011010': 0.03125,\n                          '11101010010110000101100000001011110000010011001010': 0.03125,\n                          '11101010010110101101000100001001011101110010011110': 0.03125,\n                          '11101010010110101101100010000010000001110010011010': 0.03125,\n                          '11101010011000000101100100001000110100000101011010': 0.03125,\n                          '11101010011000000101100100001001101101000101011011': 0.03125,\n                          '11101010011000001001000100011011010001001001011010': 0.03125,\n                          '11101010011000001011000010000011011001010111000110': 0.03125,\n                          '11101010011000001101000101011010010000010001011010': 0.03125,\n                          '11101010011000001101000110101111010000101011001010': 0.03125,\n                          '11101010011000001101100100001010011000010011001010': 0.03125,\n                          '11101010011000001101100100001010101001011101111010': 0.03125,\n                          '11101010011000001111000000001000110001011001010110': 0.03125,\n                          '11101010011000001111100010001010000101010001011110': 0.03125,\n                          '11101010011000100001100100001000001101010001011011': 0.03125,\n                          '11101010011000100011000100001000101011010111011011': 0.03125,\n                          '11101010011000100101000000001000010001001011010010': 0.03125,\n                          '11101010011000100101100010011000100001010111011110': 0.03125,\n                          '11101010011000100111000000011001110000110001010110': 0.03125,\n                          '11101010011000100111100000001001000001010001000010': 0.03125,\n                          '11101010011000101101000000011000010001110111011010': 0.03125,\n                          '11101010011000101101100100001000010011001011000010': 0.03125,\n                          '11101010011000101111000101011000000001011111011010': 0.03125,\n                          '11101010011000101111100110011110010001110011011010': 0.03125,\n                          '11101010011000111001100010011011001001011001011011': 0.03125,\n                          '11101010011010000101100000001001010000000001000010': 0.03125,\n                          '11101010011010000111000010001011111101011111011010': 0.03125,\n                          '11101010011010000111100101001000001011000011011010': 0.03125,\n                          '11101010011010001001000000001110111101000011001011': 0.03125,\n                          '11101010011010001101000011011000100101000011011010': 0.03125,\n                          '11101010011010001101000100011001111001011001000011': 0.03125,\n                          '11101010011010001101100000001001010000010011010010': 0.03125,\n                          '11101010011010001101100100001000110101011000011011': 0.03125,\n                          '11101010011010001101100111001000000100111101011011': 0.03125,\n                          '11101010011010011001100101010000010001111011100000': 0.03125,\n                          '11101010011010101101001000001000000001000001011010': 0.03125,\n                          '11101010011010101101100000001110010001001101001010': 0.03125,\n                          '11101010011010101101100000011001110001011011001011': 0.03125,\n                          '11101010011010101101100100001000000001110001000010': 0.03125,\n                          '11101010011010101101101110001010000000010101011010': 0.03125,\n                          '11101010011010101111000001011100010001011101001010': 0.03125,\n                          '11101010011010111101100100001000010101000101000010': 0.03125,\n                          '11101010011011100101000110001010010001010101001010': 0.03125,\n                          '11101010011100001101000000001001000001011111011011': 0.03125,\n                          '11101010011100011111100110001000110001101001001011': 0.03125,\n                          '11101010011100101101100100001010000001000101011011': 0.03125,\n                          '11101010011100110101000100011000110100010101011110': 0.03125,\n                          '11101010011100111101000100001000100001011011010110': 0.03125,\n                          '11101010011101101101100000001000111001010111011111': 0.03125,\n                          '11101010011110000101000110011001110100100011001011': 0.03125,\n                          '11101010011110001001100110001011001001101011001010': 0.03125,\n                          '11101010011110001101000100001001100001001011011111': 0.03125,\n                          '11101010011110001101100100001101010001000101011111': 0.03125,\n                          '11101010011110001101100101011001100101111011010010': 0.03125,\n                          '11101010011110001111000000011000000001010011001111': 0.03125,\n                          '11101010011110100101000000001011000001000111011010': 0.03125,\n                          '11101010011110100101000100101000110111011011011011': 0.03125,\n                          '11101010011110100101101110001000110101011101011110': 0.03125,\n                          '11101010011110100111000100001010110001001001001111': 0.03125,\n                          '11101010011110101001000110001010011011010001001010': 0.03125,\n                          '11101010011110101001100010001000100001010001010010': 0.03125,\n                          '11101010011110101101100000001010011001000110011010': 0.03125,\n                          '11101010011110101101100100001001010001000111011010': 0.03125,\n                          '11101010011110111101100010001011100001000001001111': 0.03125,\n                          '11101010100010101101100000001000000001000111011011': 0.03125,\n                          '11101010100010110101100110001001001001101011001010': 0.03125,\n                          '11101010100100001001100000001001000001000011000111': 0.03125,\n                          '11101010100110001101100000001000000101001111001010': 0.03125,\n                          '11101010101000101100100000001001100001100001001110': 0.03125,\n                          '11101010101010001101000101001001000001000101000010': 0.03125,\n                          '11101010101010001111000101001010110001011100011010': 0.03125,\n                          '11101010101010101101001100001010000000010101011010': 0.03125,\n                          '11101010101010101101100000011001100010110101011010': 0.03125,\n                          '11101010101010101101100100011001010101101101111010': 0.03125,\n                          '11101010101100001101100110001101010000010101011010': 0.03125,\n                          '11101010101110000101000110001000110101001010001111': 0.03125,\n                          '11101010101110001101000000001000011001011011001000': 0.03125,\n                          '11101010101110101101000110001001000011000101011011': 0.03125,\n                          '11101010110000001101100000001110010001101010111011': 0.03125,\n                          '11101010110000100101100000001000110001001110011010': 0.03125,\n                          '11101010111000000101100111001001110000100001001010': 0.03125,\n                          '11101010111000001100100010011000000000110100001010': 0.03125,\n                          '11101010111000100001100110001000100001011011001010': 0.03125,\n                          '11101010111000101111000100001011010011000110011110': 0.03125,\n                          '11101010111010000101000100001000011101100101001010': 0.03125,\n                          '11101010111010001001100100001011110001111001000011': 0.03125,\n                          '11101010111010001101000110011000010001100101001010': 0.03125,\n                          '11101010111010101101000000001000000001000011011010': 0.03125,\n                          '11101010111010110101100010001000110100000011001011': 0.03125,\n                          '11101010111100000001000100001011000000011001011011': 0.03125,\n                          '11101010111100001101100000001000110000100001001011': 0.03125,\n                          '11101010111100100101000100001000010101110111011010': 0.03125,\n                          '11101010111110000111110010001000010001010111000100': 0.03125,\n                          '11101010111110101001000100001000000001000011011010': 0.03125,\n                          '11101010111110101111100100001011100100000101011010': 0.03125,\n                          '11101011000010101001101101001011010101010101011011': 0.03125,\n                          '11101011000110001101000000001000010001010111011011': 0.03125,\n                          '11101011001000000101100100001000000101110101001011': 0.03125,\n                          '11101011001000100101100010001010100001010011011010': 0.03125,\n                          '11101011001000101111000000011011110000010101011010': 0.03125,\n                          '11101011001000110101100100001000000001000001010110': 0.03125,\n                          '11101011001010000001000110011000010011010111011010': 0.03125,\n                          '11101011001010001100100100001011100001001111011110': 0.03125,\n                          '11101011001010001101000100001011000001100001000000': 0.03125,\n                          '11101011001010100001100000001000000101000001011011': 0.03125,\n                          '11101011001010101101000100011000001011011011011010': 0.03125,\n                          '11101011001010101101000101001010010001000110000010': 0.03125,\n                          '11101011001010101101100100001001100001010011010010': 0.03125,\n                          '11101011001100001011000100001000100100101001001010': 0.03125,\n                          '11101011001100001101000000001010000001010111000010': 0.03125,\n                          '11101011001100001101000110011011011101100011001111': 0.03125,\n                          '11101011001100001101100100001000111001110101110011': 0.03125,\n                          '11101011001100001101100110001000000001011011011010': 0.03125,\n                          '11101011001100100101100111001001000101000001011001': 0.03125,\n                          '11101011001101000111000010001011111000111011011010': 0.03125,\n                          '11101011001110001101000000000000000001111101011010': 0.03125,\n                          '11101011001110001101100010011010000000010001011010': 0.03125,\n                          '11101011001110100111100010001001010001000110011010': 0.03125,\n                          '11101011001110101101000100001001100101010001011010': 0.03125,\n                          '11101011001110101101000100011000010001110011010110': 0.03125,\n                          '11101011010000001001000101011000000001010111001010': 0.03125,\n                          '11101011010000001001000110001000010000110101010010': 0.03125,\n                          '11101011010000100101001000001001000101110001011011': 0.03125,\n                          '11101011010000101101100010001000110101010001011110': 0.03125,\n                          '11101011010000110111100100001000101101010011010110': 0.03125,\n                          '11101011010001101011000100001011010000001111011011': 0.03125,\n                          '11101011010010001101100100011001000001000101000110': 0.03125,\n                          '11101011010010101101100110000000010100010010001010': 0.03125,\n                          '11101011010100101101000100001000010001000011011010': 0.03125,\n                          '11101011010100101101100100011011000001000111111000': 0.03125,\n                          '11101011010110001101000010001001110100010000001110': 0.03125,\n                          '11101011010110101101100100001001110101000101001011': 0.03125,\n                          '11101011010110101101100110001000011001000111011010': 0.03125,\n                          '11101011011000000101000110001001110000110101010010': 0.03125,\n                          '11101011011000101101100000001000101001110001001010': 0.03125,\n                          '11101011011000101101101110001000110001101011000010': 0.03125,\n                          '11101011011000101111100000001000110000110111001010': 0.03125,\n                          '11101011011000101111100100001011000100000001001110': 0.03125,\n                          '11101011011001000101000010001000110110101111011010': 0.03125,\n                          '11101011011010000001100010001011011000000111111010': 0.03125,\n                          '11101011011010000101100000011001000011010111011010': 0.03125,\n                          '11101011011010001101100110001001000010010001001011': 0.03125,\n                          '11101011011010100101100100001001010000010011000000': 0.03125,\n                          '11101011011010100111100001001000111010100011001010': 0.03125,\n                          '11101011011010100111100011011000010001000111000010': 0.03125,\n                          '11101011011010101011000010001000000010000101011011': 0.03125,\n                          '11101011011010101101000100000010111001100100011010': 0.03125,\n                          '11101011011010101101000110001000100001000111011011': 0.03125,\n                          '11101011011010101101001100001001000000000001010010': 0.03125,\n                          '11101011011010101111100000001001000000010001011111': 0.03125,\n                          '11101011011100000101101110001010000000011101000011': 0.03125,\n                          '11101011011100001001100000010000010001010011011010': 0.03125,\n                          '11101011011100001111000000011000110101000011111011': 0.03125,\n                          '11101011011100100001000100001010000001000001001010': 0.03125,\n                          '11101011011100100101100100001000100000000011011011': 0.03125,\n                          '11101011011100100101100100001010101000010110001010': 0.03125,\n                          '11101011011100100111100011011001100101110111001110': 0.03125,\n                          '11101011011100101111000100011100110001010101011110': 0.03125,\n                          '11101011011110000010100100001010111101000001011011': 0.03125,\n                          '11101011011110000101001100001010010001010011001011': 0.03125,\n                          '11101011011110001101000110001011000001100111011010': 0.03125,\n                          '11101011011110001101100000011000000001011011011011': 0.03125,\n                          '11101011011110100001100010001010100101000011001001': 0.03125,\n                          '11101011011110101101000100001001010000011011001011': 0.03125,\n                          '11101011011110101101100000001001000101011101001011': 0.03125,\n                          '11101011011110101101100101000000010001000111000010': 0.03125,\n                          '11101011011110101101100110001011010000011000011011': 0.03125,\n                          '11101011011110101111000100001000000100000111001110': 0.03125,\n                          '11101011011110101111100000001001110011110011010010': 0.03125,\n                          '11101011011110101111100000001010000011001011011011': 0.03125,\n                          '11101011011110111101100100001010110001010111010011': 0.03125,\n                          '11101011100110100101100100001010000000110101000110': 0.03125,\n                          '11101011101000001101000000011101000001101011000110': 0.03125,\n                          '11101011101010011101100010001001100111000111001111': 0.03125,\n                          '11101011101010100011100100001001111101010010010010': 0.03125,\n                          '11101011101100100101100110011000001111010111111110': 0.03125,\n                          '11101011101110101001100110001010110000011001001010': 0.03125,\n                          '11101011110010001100100100001010010001110011011010': 0.03125,\n                          '11101011110010101111000100001100110001010011001010': 0.03125,\n                          '11101011111000101101000010001110000001000101011010': 0.03125,\n                          '11101011111010000111000100011001000001110111011010': 0.03125,\n                          '11101011111010001101100110011000100100101011001010': 0.03125,\n                          '11101011111010001101100111001000000011001011011010': 0.03125,\n                          '11101011111110000001100110001011000001001011011010': 0.03125,\n                          '11101011111110001100100011001010101101011001011010': 0.03125,\n                          '11101011111110001100100100001000010010110111010010': 0.03125,\n                          '11101011111110100101000001001000000111001101010010': 0.03125,\n                          '11101100000010100101100001001010000000010100011010': 0.03125,\n                          '11101100001000100111100100000001000101011101001011': 0.03125,\n                          '11101100001010001101100000001000111001001011001010': 0.03125,\n                          '11101100001010100101000100001010010111110011001011': 0.03125,\n                          '11101100011000101101000100011010010001000111001110': 0.03125,\n                          '11101100011010001101000110001000110001010111011011': 0.03125,\n                          '11101100011010101101000101000010110001100110010010': 0.03125,\n                          '11101101001010111101100000001011000001010101000110': 0.03125,\n                          '11101101011000101001000100001000010100100111001010': 0.03125,\n                          '11101110011010000001100010001000110000000111010110': 0.03125,\n                          '11101110011010001111000000001001010101010101011010': 0.03125,\n                          '11101110011100001101000100001010000111000001000010': 0.03125,\n                          '11101110111110000101000100001001001001110001010011': 0.03125,\n                          '11101111000100101101100010001000010001010101011010': 0.03125,\n                          '11101111011011001101100100001000010101010011000010': 0.03125,\n                          '11101111111010000101000010010010010101010000011010': 0.03125,\n                          '11111000000100101111100110001001110001100001001010': 0.03125,\n                          '11111000001110001101001111001001010001011001011110': 0.03125,\n                          '11111000011010001101100010001010000101010011001010': 0.03125,\n                          '11111000011011000101000110001011010001010111001100': 0.03125,\n                          '11111000011110101101000101000000000001110111001010': 0.03125,\n                          '11111000101110100001000100001000000001000101001111': 0.03125,\n                          '11111010001000000101100100001000101001000101011010': 0.03125,\n                          '11111010001010101101100110001011010000010011011010': 0.03125,\n                          '11111010001110100101000010001011000011010101001110': 0.03125,\n                          '11111010011110101111100010001111010001111011000010': 0.03125,\n                          '11111010111010100111000100001010000001000101111010': 0.03125,\n                          '11111010111110100101000000011000111101101011000110': 0.03125,\n                          '11111011011110001001101110001000011100011011001010': 0.03125,\n                          '11111011011110101111000010001000010001100111011010': 0.03125,\n                          '11111011110000101101100001011000000111010011001010': 0.03125,\n                          '11111011111000101001000000001010010001010111001100': 0.03125,\n                          '11111011111110001101100110001001010001000011000011': 0.03125},\n        'eigenvalue': -28.085937500000004,\n        'optimal_parameters': {   ParameterVectorElement(\u03b8[71]): 3.9872763188057943,\n                                  ParameterVectorElement(\u03b8[72]): -4.598746776690561,\n                                  ParameterVectorElement(\u03b8[73]): -1.155987330156893,\n                                  ParameterVectorElement(\u03b8[74]): 5.495862143145802,\n                                  ParameterVectorElement(\u03b8[75]): -2.82494840055917,\n                                  ParameterVectorElement(\u03b8[76]): -4.525214818748246,\n                                  ParameterVectorElement(\u03b8[77]): 4.197840283132314,\n                                  ParameterVectorElement(\u03b8[78]): 5.703332018868296,\n                                  ParameterVectorElement(\u03b8[79]): 3.185178391058902,\n                                  ParameterVectorElement(\u03b8[80]): 2.6826254535191216,\n                                  ParameterVectorElement(\u03b8[81]): 5.420037331703752,\n                                  ParameterVectorElement(\u03b8[82]): 4.217054145086257,\n                                  ParameterVectorElement(\u03b8[83]): 6.22377247712934,\n                                  ParameterVectorElement(\u03b8[84]): -2.4094118941090783,\n                                  ParameterVectorElement(\u03b8[85]): 2.731354050662372,\n                                  ParameterVectorElement(\u03b8[86]): 3.7574028317174224,\n                                  ParameterVectorElement(\u03b8[87]): 3.676148111778852,\n                                  ParameterVectorElement(\u03b8[88]): -3.576312926220942,\n                                  ParameterVectorElement(\u03b8[89]): 0.6494772327227302,\n                                  ParameterVectorElement(\u03b8[90]): 3.7204304199509,\n                                  ParameterVectorElement(\u03b8[91]): -2.6509392998905215,\n                                  ParameterVectorElement(\u03b8[92]): -0.2342007020539084,\n                                  ParameterVectorElement(\u03b8[93]): -4.672196400139893,\n                                  ParameterVectorElement(\u03b8[94]): -3.0775644562815594,\n                                  ParameterVectorElement(\u03b8[95]): -1.178564744044848,\n                                  ParameterVectorElement(\u03b8[96]): 2.286963745328427,\n                                  ParameterVectorElement(\u03b8[97]): -4.9930505803673135,\n                                  ParameterVectorElement(\u03b8[98]): -2.886284883004232,\n                                  ParameterVectorElement(\u03b8[99]): -4.372063793618604,\n                                  ParameterVectorElement(\u03b8[15]): 0.9222968543214748,\n                                  ParameterVectorElement(\u03b8[16]): -1.5789890302058918,\n                                  ParameterVectorElement(\u03b8[17]): 1.2513287471817987,\n                                  ParameterVectorElement(\u03b8[18]): 5.052459227881141,\n                                  ParameterVectorElement(\u03b8[19]): -1.3044953653862374,\n                                  ParameterVectorElement(\u03b8[20]): 0.5330701824786922,\n                                  ParameterVectorElement(\u03b8[21]): -2.572070031671651,\n                                  ParameterVectorElement(\u03b8[22]): 5.446558203149478,\n                                  ParameterVectorElement(\u03b8[23]): 6.443934128462927,\n                                  ParameterVectorElement(\u03b8[24]): 0.8166631001401825,\n                                  ParameterVectorElement(\u03b8[25]): 5.11439214962343,\n                                  ParameterVectorElement(\u03b8[26]): 4.515478859123269,\n                                  ParameterVectorElement(\u03b8[27]): 5.735063636292148,\n                                  ParameterVectorElement(\u03b8[28]): -0.16792636820035173,\n                                  ParameterVectorElement(\u03b8[29]): 4.628723234209623,\n                                  ParameterVectorElement(\u03b8[30]): 3.6288661019037693,\n                                  ParameterVectorElement(\u03b8[31]): -5.351213877422861,\n                                  ParameterVectorElement(\u03b8[32]): 3.9238374726383154,\n                                  ParameterVectorElement(\u03b8[33]): 2.0445691379191433,\n                                  ParameterVectorElement(\u03b8[34]): -5.727312980655919,\n                                  ParameterVectorElement(\u03b8[35]): -1.6424244443212215,\n                                  ParameterVectorElement(\u03b8[36]): -0.37456287702100993,\n                                  ParameterVectorElement(\u03b8[37]): 4.496427467045233,\n                                  ParameterVectorElement(\u03b8[38]): 4.909822525025029,\n                                  ParameterVectorElement(\u03b8[39]): -4.104324112718262,\n                                  ParameterVectorElement(\u03b8[40]): 4.414741851152087,\n                                  ParameterVectorElement(\u03b8[41]): 5.329171905083392,\n                                  ParameterVectorElement(\u03b8[42]): 1.3364369617805674,\n                                  ParameterVectorElement(\u03b8[43]): -4.566217651571373,\n                                  ParameterVectorElement(\u03b8[44]): -6.595693102132771,\n                                  ParameterVectorElement(\u03b8[45]): -3.404069955531124,\n                                  ParameterVectorElement(\u03b8[46]): -6.695872380075485,\n                                  ParameterVectorElement(\u03b8[47]): 2.686225269728296,\n                                  ParameterVectorElement(\u03b8[48]): -1.5647410702366962,\n                                  ParameterVectorElement(\u03b8[49]): 3.734145165748734,\n                                  ParameterVectorElement(\u03b8[50]): 6.030482361992538,\n                                  ParameterVectorElement(\u03b8[51]): -3.816346643191953,\n                                  ParameterVectorElement(\u03b8[52]): 6.337537542910174,\n                                  ParameterVectorElement(\u03b8[53]): -2.8388460453843174,\n                                  ParameterVectorElement(\u03b8[54]): -3.022899974896531,\n                                  ParameterVectorElement(\u03b8[55]): -1.8909682598081525,\n                                  ParameterVectorElement(\u03b8[56]): 5.96187310310959,\n                                  ParameterVectorElement(\u03b8[57]): 6.052052699693801,\n                                  ParameterVectorElement(\u03b8[58]): -0.302183255235936,\n                                  ParameterVectorElement(\u03b8[59]): -1.7693480691709491,\n                                  ParameterVectorElement(\u03b8[60]): 2.5642681482311573,\n                                  ParameterVectorElement(\u03b8[61]): -3.1148303741355754,\n                                  ParameterVectorElement(\u03b8[62]): -3.0200175707871293,\n                                  ParameterVectorElement(\u03b8[63]): -5.964074785802505,\n                                  ParameterVectorElement(\u03b8[64]): 2.7584118009342014,\n                                  ParameterVectorElement(\u03b8[65]): 0.4680027126505248,\n                                  ParameterVectorElement(\u03b8[66]): 3.366654793082457,\n                                  ParameterVectorElement(\u03b8[67]): -5.146583917505098,\n                                  ParameterVectorElement(\u03b8[68]): -3.093099524959418,\n                                  ParameterVectorElement(\u03b8[69]): -3.114291151192215,\n                                  ParameterVectorElement(\u03b8[70]): 1.411586880337322,\n                                  ParameterVectorElement(\u03b8[2]): 7.302679240598226,\n                                  ParameterVectorElement(\u03b8[1]): -2.6676785474159805,\n                                  ParameterVectorElement(\u03b8[9]): 5.146746113853714,\n                                  ParameterVectorElement(\u03b8[7]): 1.609352072366115,\n                                  ParameterVectorElement(\u03b8[8]): -4.8737979572113765,\n                                  ParameterVectorElement(\u03b8[6]): -3.7804656207906007,\n                                  ParameterVectorElement(\u03b8[5]): -0.4702287163717303,\n                                  ParameterVectorElement(\u03b8[10]): 4.5661123655430735,\n                                  ParameterVectorElement(\u03b8[4]): 4.571214987126211,\n                                  ParameterVectorElement(\u03b8[3]): 4.129976123745594,\n                                  ParameterVectorElement(\u03b8[11]): -1.1120826380550868,\n                                  ParameterVectorElement(\u03b8[13]): -5.462879176757742,\n                                  ParameterVectorElement(\u03b8[12]): 4.17649547864572,\n                                  ParameterVectorElement(\u03b8[14]): -1.1214483810651392,\n                                  ParameterVectorElement(\u03b8[0]): 1.1641643458956072},\n        'optimal_point': array([ 1.16416435,  4.56611237, -1.11208264,  4.17649548, -5.46287918,\n           -1.12144838,  0.92229685, -1.57898903,  1.25132875,  5.05245923,\n           -1.30449537, -2.66767855,  0.53307018, -2.57207003,  5.4465582 ,\n            6.44393413,  0.8166631 ,  5.11439215,  4.51547886,  5.73506364,\n           -0.16792637,  4.62872323,  7.30267924,  3.6288661 , -5.35121388,\n            3.92383747,  2.04456914, -5.72731298, -1.64242444, -0.37456288,\n            4.49642747,  4.90982253, -4.10432411,  4.12997612,  4.41474185,\n            5.32917191,  1.33643696, -4.56621765, -6.5956931 , -3.40406996,\n           -6.69587238,  2.68622527, -1.56474107,  3.73414517,  4.57121499,\n            6.03048236, -3.81634664,  6.33753754, -2.83884605, -3.02289997,\n           -1.89096826,  5.9618731 ,  6.0520527 , -0.30218326, -1.76934807,\n           -0.47022872,  2.56426815, -3.11483037, -3.02001757, -5.96407479,\n            2.7584118 ,  0.46800271,  3.36665479, -5.14658392, -3.09309952,\n           -3.11429115, -3.78046562,  1.41158688,  3.98727632, -4.59874678,\n           -1.15598733,  5.49586214, -2.8249484 , -4.52521482,  4.19784028,\n            5.70333202,  3.18517839,  1.60935207,  2.68262545,  5.42003733,\n            4.21705415,  6.22377248, -2.40941189,  2.73135405,  3.75740283,\n            3.67614811, -3.57631293,  0.64947723, -4.87379796,  3.72043042,\n           -2.6509393 , -0.2342007 , -4.6721964 , -3.07756446, -1.17856474,\n            2.28696375, -4.99305058, -2.88628488, -4.37206379,  5.14674611]),\n        'optimal_value': -28.085937500000004,\n        'optimizer_evals': 200,\n        'optimizer_time': 1597.3255107402802}\n\n\n\n```python\ncounts\n```\n\n\n\n\n    [1,\n     2,\n     3,\n     4,\n     5,\n     6,\n     7,\n     8,\n     9,\n     10,\n     11,\n     12,\n     13,\n     14,\n     15,\n     16,\n     17,\n     18,\n     19,\n     20,\n     21,\n     22,\n     23,\n     24,\n     25,\n     26,\n     27,\n     28,\n     29,\n     30,\n     31,\n     32,\n     33,\n     34,\n     35,\n     36,\n     37,\n     38,\n     39,\n     40,\n     41,\n     42,\n     43,\n     44,\n     45,\n     46,\n     47,\n     48,\n     49,\n     50,\n     51,\n     52,\n     53,\n     54,\n     55,\n     56,\n     57,\n     58,\n     59,\n     60,\n     61,\n     62,\n     63,\n     64,\n     65,\n     66,\n     67,\n     68,\n     69,\n     70,\n     71,\n     72,\n     73,\n     74,\n     75,\n     76,\n     77,\n     78,\n     79,\n     80,\n     81,\n     82,\n     83,\n     84,\n     85,\n     86,\n     87,\n     88,\n     89,\n     90,\n     91,\n     92,\n     93,\n     94,\n     95,\n     96,\n     97,\n     98,\n     99,\n     100,\n     101,\n     102,\n     103,\n     104,\n     105,\n     106,\n     107,\n     108,\n     109,\n     110,\n     111,\n     112,\n     113,\n     114,\n     115,\n     116,\n     117,\n     118,\n     119,\n     120,\n     121,\n     122,\n     123,\n     124,\n     125,\n     126,\n     127,\n     128,\n     129,\n     130,\n     131,\n     132,\n     133,\n     134,\n     135,\n     136,\n     137,\n     138,\n     139,\n     140,\n     141,\n     142,\n     143,\n     144,\n     145,\n     146,\n     147,\n     148,\n     149,\n     150,\n     151,\n     152,\n     153,\n     154,\n     155,\n     156,\n     157,\n     158,\n     159,\n     160,\n     161,\n     162,\n     163,\n     164,\n     165,\n     166,\n     167,\n     168,\n     169,\n     170,\n     171,\n     172,\n     173,\n     174,\n     175,\n     176,\n     177,\n     178,\n     179,\n     180,\n     181,\n     182,\n     183,\n     184,\n     185,\n     186,\n     187,\n     188,\n     189,\n     190,\n     191,\n     192,\n     193,\n     194,\n     195,\n     196,\n     197,\n     198,\n     1,\n     2,\n     3,\n     4,\n     5,\n     6,\n     7,\n     8,\n     9,\n     10,\n     11,\n     12,\n     13,\n     14,\n     15,\n     16,\n     17,\n     18,\n     19,\n     20,\n     21,\n     22,\n     23,\n     24,\n     25,\n     26,\n     27,\n     28,\n     29,\n     30,\n     31,\n     32,\n     33,\n     34,\n     35,\n     36,\n     37,\n     38,\n     39,\n     40,\n     41,\n     42,\n     43,\n     44,\n     45,\n     46,\n     47,\n     48,\n     49,\n     50,\n     51,\n     52,\n     53,\n     54,\n     55,\n     56,\n     57,\n     58,\n     59,\n     60,\n     61,\n     62,\n     63,\n     64,\n     65,\n     66,\n     67,\n     68,\n     69,\n     70,\n     71,\n     72,\n     73,\n     74,\n     75,\n     76,\n     77,\n     78,\n     79,\n     80,\n     81,\n     82,\n     83,\n     84,\n     85,\n     86,\n     87,\n     88,\n     89,\n     90,\n     91,\n     92,\n     93,\n     94,\n     95,\n     96,\n     97,\n     98,\n     99,\n     100,\n     101,\n     102,\n     103,\n     104,\n     105,\n     106,\n     107,\n     108,\n     109,\n     110,\n     111,\n     112,\n     113,\n     114,\n     115,\n     116,\n     117,\n     118,\n     119,\n     120,\n     121,\n     122,\n     123,\n     124,\n     125,\n     126,\n     127,\n     128,\n     129,\n     130,\n     131,\n     132,\n     133,\n     134,\n     135,\n     136,\n     137,\n     138,\n     139,\n     140,\n     141,\n     142,\n     143,\n     144,\n     145,\n     146,\n     147,\n     148,\n     149,\n     150,\n     151,\n     152,\n     153,\n     154,\n     155,\n     156,\n     157,\n     158,\n     159,\n     160,\n     161,\n     162,\n     163,\n     164,\n     165,\n     166,\n     167,\n     168,\n     169,\n     170,\n     171,\n     172,\n     173,\n     174,\n     175,\n     176,\n     177,\n     178,\n     179,\n     180,\n     181,\n     182,\n     183,\n     184,\n     185,\n     186,\n     187,\n     188,\n     189,\n     190,\n     191,\n     192,\n     193,\n     194,\n     195,\n     196,\n     197,\n     198,\n     199,\n     200]\n\n\n\n\n```python\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator\nimport numpy as np\n\nfig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"})\n\n# Make data.\nX = np.arange(-5, 5, 0.25)\nY = np.arange(-5, 5, 0.25)\nX, Y = np.meshgrid(X, Y)\nR = np.sqrt(X**2 + Y**2)\nZ = np.sin(R)\n\nprint(X)\n\n# Plot the surface.\nsurf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,\n                       linewidth=0, antialiased=False)\n\n# Customize the z axis.\nax.set_zlim(-1.01, 1.01)\nax.zaxis.set_major_locator(LinearLocator(10))\n# A StrMethodFormatter is used automatically\nax.zaxis.set_major_formatter('{x:.02f}')\n\n# Add a color bar which maps values to colors.\nfig.colorbar(surf, shrink=0.5, aspect=5)\n\nplt.show()\n```\n\n\n```python\nimport numpy as np\nfrom qiskit.providers.aer import AerSimulator, QasmSimulator\nfrom qiskit.algorithms.optimizers import COBYLA \nfrom qiskit.circuit.library import TwoLocal\nfrom qiskit.aqua.operators import *\nfrom qiskit.aqua import set_qiskit_aqua_logging, QuantumInstance\nfrom qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE, NumPyEigensolver\nfrom qiskit.circuit import QuantumCircuit, ParameterVector\n\n# pauli_terms = ['IIIIIIIZ', 'IIIIIIZI', 'IIIIIZII' ]\n# pauli_weights = [504.0, 1008.0, 2016.0]\n# pauli_dict = {'paulis': [{\"coeff\": {\"imag\": 0., \"real\": pauli_weights[i] }, \"label\": pauli_terms[i]} \\\n#                          for i in range(len(pauli_terms))]}\nHamiltonian = - 1 * ((X ^ I ^ I ^ I) + (I ^ X ^ I ^ I) + (I ^ I ^ X ^ I) + (I ^ I ^ I ^ X))\nansatz = TwoLocal(num_qubits=4, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True)\nprint(ansatz)\nbackend = QasmSimulator()\nquantum_instance = QuantumInstance(backend,\n                                   shots = 8192,\n                                   initial_layout = None,\n                                   optimization_level = 3)  \n\noptimizer = COBYLA(maxiter= 100, tol=0.000000001)   \nvqe = VQE(Hamiltonian, ansatz, optimizer, initial_point= None , include_custom = False)\nprint('We are using:', quantum_instance.backend)\nvqe_result = vqe.run(quantum_instance)\nvqe_result['eigenstate']\n```\n\n\n```python\nfrom qiskit.visualization import plot_histogram\n\nplot_histogram(vqe_result['eigenstate'])\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "5aa5d4df7ea24e5ba3e806f9e950d7ad40542f5f", "size": 375219, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "research/rough-work-misc/Kinetic_Ising (2).ipynb", "max_stars_repo_name": "arnavdas88/QuGlassyIsing", "max_stars_repo_head_hexsha": "6b6514d58646130c03619aebefb9f9aed4e5646a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-19T16:06:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T17:03:31.000Z", "max_issues_repo_path": "research/rough-work-misc/Kinetic_Ising (2).ipynb", "max_issues_repo_name": "IshmamShah/QuGlassyIsing", "max_issues_repo_head_hexsha": "6c3ff2ebd77ed9b34a0e731083f1e56b7eacb7ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "research/rough-work-misc/Kinetic_Ising (2).ipynb", "max_forks_repo_name": "IshmamShah/QuGlassyIsing", "max_forks_repo_head_hexsha": "6c3ff2ebd77ed9b34a0e731083f1e56b7eacb7ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-19T16:06:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T06:51:18.000Z", "avg_line_length": 162.3621808741, "max_line_length": 112018, "alphanum_fraction": 0.7244169405, "converted": true, "num_tokens": 50296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.07696083728384619, "lm_q1q2_score": 0.03193096256062072}}
{"text": "```python\n# Erasmus+ ICCT project (2018-1-SI01-KA203-047081)\n\n# Toggle cell visibility\n\nfrom IPython.display import HTML\ntag = HTML('''\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.''')\ndisplay(tag)\n\n# Hide the code completely\n\n# from IPython.display import HTML\n# tag = HTML('''<style>\n# div.input {\n#     display:none;\n# }\n# </style>''')\n# display(tag)\n```\n\n\n\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.\n\n\n## Osservatore dello stato: sistemi non osservabili\nQuesto esempio mostra cosa succede quando un osservatore \u00e8 progettato per un sistema lineare non osservabile.\n\nRicordando la forma standard di osservabilit\u00e0:\n\n\\begin{cases}\n\\underbrace{\\begin{bmatrix} \\dot{x}_o \\\\ \\dot{x}_{\\bar{o}} \\end{bmatrix}}_{\\dot{\\textbf{x}}} = \\begin{bmatrix} A_o & 0 \\\\ A_{o\\bar{o}} & A_{\\bar{o}} \\end{bmatrix} \\underbrace{\\begin{bmatrix} x_o \\\\ x_{\\bar{o}} \\end{bmatrix}}_{\\textbf{x}} + \\begin{bmatrix} B_o \\\\ B_{\\bar{o}} \\end{bmatrix} \\textbf{u} \\\\\n\\textbf{y} = \\begin{bmatrix} C_o & 0 \\end{bmatrix} \\textbf{x},\n\\end{cases}\n\ncostruire:\n- un sistema non osservabile la cui dinamica non osservabile \u00e8 stabile;\n- un sistema non osservabile la cui dinamica non osservabile \u00e8 instabile;\n- un sistema non osservabile la cui dinamica non osservabile ha dimensione 1 e autovalore 0. Cosa cambia in questo caso?\n\n\n```python\n#Preparatory Cell \n\n%matplotlib inline\nimport control as control\nimport numpy\nimport sympy as sym\nfrom IPython.display import display, Markdown\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\n\n\n#print a matrix latex-like\ndef bmatrix(a):\n     \"\"\"Returns a LaTeX bmatrix - by Damir Arbula (ICCT project)\n\n     :a: numpy array\n     :returns: LaTeX bmatrix as a string\n     \"\"\"\n     if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n     lines = str(a).replace('[', '').replace(']', '').splitlines()\n     rv = [r'\\begin{bmatrix}']\n     rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n     rv +=  [r'\\end{bmatrix}']\n     return '\\n'.join(rv)\n\n\n# Display formatted matrix: \ndef vmatrix(a):\n    if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n    lines = str(a).replace('[', '').replace(']', '').splitlines()\n    rv = [r'\\begin{vmatrix}']\n    rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n    rv +=  [r'\\end{vmatrix}']\n    return '\\n'.join(rv)\n\n\n#matrixWidget is a matrix looking widget built with a VBox of HBox(es) that returns a numPy array as value !\nclass matrixWidget(widgets.VBox):\n    def updateM(self,change):\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.M_[irow,icol] = self.children[irow].children[icol].value\n                #print(self.M_[irow,icol])\n        self.value = self.M_\n\n    def dummychangecallback(self,change):\n        pass\n    \n    \n    def __init__(self,n,m):\n        self.n = n\n        self.m = m\n        self.M_ = numpy.matrix(numpy.zeros((self.n,self.m)))\n        self.value = self.M_\n        widgets.VBox.__init__(self,\n                             children = [\n                                 widgets.HBox(children = \n                                              [widgets.FloatText(value=0.0, layout=widgets.Layout(width='90px')) for i in range(m)]\n                                             ) \n                                 for j in range(n)\n                             ])\n        \n        #fill in widgets and tell interact to call updateM each time a children changes value\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        #value = Unicode('example@example.com', help=\"The email value.\").tag(sync=True)\n        self.observe(self.updateM, names='value', type= 'All')\n        \n    def setM(self, newM):\n        #disable callbacks, change values, and reenable\n        self.unobserve(self.updateM, names='value', type= 'All')\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].unobserve(self.updateM, names='value')\n        self.M_ = newM\n        self.value = self.M_\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        self.observe(self.updateM, names='value', type= 'All')        \n\n                #self.children[irow].children[icol].observe(self.updateM, names='value')\n\n             \n#overlaod class for state space systems that DO NOT remove \"useless\" states (what \"professor\" of automatic control would do this?)\nclass sss(control.StateSpace):\n    def __init__(self,*args):\n        #call base class init constructor\n        control.StateSpace.__init__(self,*args)\n    #disable function below in base class\n    def _remove_useless_states(self):\n        pass\n```\n\n\n```python\n# Preparatory cell\n\nA = numpy.matrix('-1 1 0; 0 -2 0; 0 1 2')\nB = numpy.matrix('0.7; 0.5; 1')\nC = numpy.matrix('1 0 0')\nX0 = numpy.matrix('2; 2; 2')\nF = numpy.matrix('-1 0 3; 0 -2 -1; 0 1 -2')\nG = numpy.matrix('0; 0; 1')\nL = numpy.matrix([[4],[-2/3],[2/3]])\nsol1 = numpy.linalg.eig(A)\n\nAdefault = [A,\n            numpy.matrix('-1 1 0; 0 -2 0; 0 1 -2')]\nBdefault = B\nCdefault = C\n\nAw = matrixWidget(3,3)\nAw.setM(A)\nBw = matrixWidget(3,1)\nBw.setM(B)\nCw = matrixWidget(1,3)\nCw.setM(C)\nX0w = matrixWidget(3,1)\nX0w.setM(X0)\nFw = matrixWidget(3,3)\nFw.setM(F)\nGw = matrixWidget(3,1)\nGw.setM(G)\nLw = matrixWidget(3,1)\nLw.setM(L)\n\n\neig1o = matrixWidget(1,1)\neig2o = matrixWidget(2,1)\neig3o = matrixWidget(1,1)\neig1o.setM(numpy.matrix([-3])) \neig2o.setM(numpy.matrix([[-3],[0]]))\neig3o.setM(numpy.matrix([-3]))\n```\n\n\n```python\n# Misc\n\n#create dummy widget \nDW = widgets.FloatText(layout=widgets.Layout(width='0px', height='0px'))\n\n#create button widget\nSTART = widgets.Button(\n    description='Test',\n    disabled=False,\n    button_style='', # 'success', 'info', 'warning', 'danger' or ''\n    tooltip='Test',\n    icon='check'\n)\n                       \ndef on_start_button_clicked(b):\n    #This is a workaround to have intreactive_output call the callback:\n    #   force the value of the dummy widget to change\n    if DW.value> 0 :\n        DW.value = -1\n    else: \n        DW.value = 1\n    pass\nSTART.on_click(on_start_button_clicked)\n\n# default systems\nsel_system = widgets.Dropdown(\n                              options=[('Manuale','Manual'), ('Stato instabile e inosservabile','Unstable unobservable state'), ('Stato stabile e inosservabile','Stable unobservable state')],\n                              value='Unstable unobservable state',\n                              description='',\n                              disabled=False\n)\n\n#define type of ipout \nselu = widgets.Dropdown(\n    options=[('impulso','impulse'), ('gradino','step'), ('sinusoide','sinusoid'), ('onda quadra','square wave')],\n    value='impulse',\n    description='Input:',\n    disabled=False\n)\n# Define the values of the input\nu = widgets.FloatSlider(\n    value=1,\n    min=0,\n    max=20.0,\n    step=0.1,\n    description='input u:',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.1f',\n)\nperiod = widgets.FloatSlider(\n    value=0.5,\n    min=0.0,\n    max=10,\n    step=0.01,\n    description='Periodo: ',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.2f',\n)\n```\n\n\n```python\ndef main_callback(A, B, C, X0w, L, u, period, sel_system, selu, DW):\n    global Adefault, Bdefault, Cdefault, Aw, Bw, Cw, Lw\n    \n    if sel_system == 'Manual':\n        sol = numpy.linalg.eig(A-L*C)\n    elif sel_system == 'Unstable unobservable state':\n        A = Adefault[0]\n        B = Bdefault\n        C = Cdefault\n        Aw.setM(A) \n        Bw.setM(B)\n        Cw.setM(C)\n        L = numpy.matrix([[4],[2],[2]])\n        Lw.setM(L)\n        sol = numpy.linalg.eig(A-L*C)\n    elif sel_system == 'Stable unobservable state':\n        A = Adefault[1]\n        B = Bdefault\n        C = Cdefault\n        Aw.setM(A) \n        Bw.setM(B)\n        Cw.setM(C)\n        L = numpy.matrix([[4],[2],[10]])\n        Lw.setM(L)\n        sol = numpy.linalg.eig(A-L*C)\n        \n    sol1 = numpy.linalg.eig(A)\n    \n    print('Gli autovalori del sistema sono:',round(sol1[0][0],4),',',round(sol1[0][1],4),'e',round(sol1[0][2],4)) \n    print('Gli autovalori dell\\'osservatore sono:',round(sol[0][0],4),',',round(sol[0][1],4),'e',round(sol[0][2],4))\n\n    \n    sys = sss(A,B,C,0)\n    syso = sss(A-L*C, numpy.concatenate((B,L),axis=1), numpy.eye(3), numpy.zeros(6).reshape((3,2)))\n    if (numpy.real([sol[0][0],sol[0][1],sol[0][2]]) == [0, 0, 0]).all():\n        T = numpy.linspace(0,20,1000)\n    else:\n        if min(numpy.abs(numpy.real([sol[0][0],sol[0][1],sol[0][2]]))) != 0:\n            T = numpy.linspace(0,10*1/min(numpy.abs(numpy.real([sol[0][0],sol[0][1],sol[0][2]]))),1000)\n        else:\n            T = numpy.linspace(0,10*1/max(numpy.abs(numpy.real([sol[0][0],sol[0][1],sol[0][2]]))),1000)\n      \n    if selu == 'impulse': #selu\n        U = [0 for t in range(0,len(T))]\n        U[0] = u\n        T, yout, xout = control.forced_response(sys,T,U,X0w)\n        T, youto, xouto = control.forced_response(syso,T,numpy.matrix([U,yout]),[[0],[0],[0]])\n    if selu == 'step':\n        U = [u for t in range(0,len(T))]\n        T, yout, xout = control.forced_response(sys,T,U,X0w)\n        T, youto, xouto = control.forced_response(syso,T,numpy.matrix([U,yout]),[[0],[0],[0]])\n    if selu == 'sinusoid':\n        U = u*numpy.sin(2*numpy.pi/period*T)\n        T, yout, xout = control.forced_response(sys,T,U,X0w)\n        T, youto, xouto = control.forced_response(syso,T,numpy.matrix([U,yout]),[[0],[0],[0]])\n    if selu == 'square wave':\n        U = u*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n        T, yout, xout = control.forced_response(sys,T,U,X0w)\n        T, youto, xouto = control.forced_response(syso,T,numpy.matrix([U,yout]),[[0],[0],[0]])\n    \n    fig = plt.figure(num='Simulation', figsize=(16,10))\n    \n    fig.add_subplot(321)\n    plt.ylabel('$X_1$ vs $X_{1est}$ (uscita del sistema)')\n    plt.plot(T,xout[0])\n    plt.plot(T,xouto[0])\n    plt.xlabel('t [s]')\n    plt.legend(['Reale','Stimato'])\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(323)\n    plt.ylabel('$X_2$ vs $X_{2est}$')\n    plt.plot(T,xout[1])\n    plt.plot(T,xouto[1])\n    plt.xlabel('t [s]')\n    plt.legend(['Reale','Stimato'])\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(325)\n    plt.ylabel('$X_3$ vs $X_{3est}$')\n    plt.plot(T,xout[2])\n    plt.plot(T,xouto[2])\n    plt.xlabel('t [s]')\n    plt.legend(['Reale','Stimato'])\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(322)\n    plt.ylabel('$e_1$')\n    plt.plot(T,xouto[0]-xout[0])\n    plt.xlabel('t [s]')\n    plt.grid()\n    \n    fig.add_subplot(324)\n    plt.ylabel('$e_1$')\n    plt.plot(T,xouto[1]-xout[1])\n    plt.xlabel('t [s]')\n    plt.grid()\n    \n    fig.add_subplot(326)\n    plt.ylabel('$e_1$')\n    plt.plot(T,xouto[2]-xout[2])\n    plt.xlabel('t [s]')\n    plt.grid()\n    \n    fig1 = plt.figure(num='Output simulation', figsize=(16,5))\n    fig1.add_subplot(111)\n    plt.ylabel('$y$')\n    plt.plot(T,yout)\n    plt.xlabel('t [s]')\n    plt.grid()\n    \nalltogether = widgets.VBox([widgets.HBox([sel_system, widgets.Label(' ',border=3), selu]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.Label('A:',border=3), Aw,\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('B:',border=3), Bw,\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('X0:',border=3), X0w,\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('L:',border=3), Lw]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.Label('C:',border=3), Cw]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([u, \n                                          period, \n                                          START])])\nout = widgets.interactive_output(main_callback, {'A':Aw, 'B':Bw, 'C':Cw, 'X0w':X0w, 'L':Lw,\n                                                 'u':u, 'period':period, 'sel_system':sel_system, \n                                                 'selu':selu, 'DW':DW})\nout.layout.height = '980px'\ndisplay(out, alltogether)\n```\n\n\n    Output(layout=Layout(height='980px'))\n\n\n\n    VBox(children=(HBox(children=(Dropdown(index=1, options=(('Manuale', 'Manual'), ('Stato instabile e inosservab\u2026\n\n", "meta": {"hexsha": "0f9caf38274eaa991d3271d92bc1d54e935903aa", "size": 19642, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_it/examples/04/SS-29-Osservatore_per_sistemi_non_osservabili.ipynb", "max_stars_repo_name": "ICCTerasmus/ICCT", "max_stars_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-22T18:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:10:22.000Z", "max_issues_repo_path": "ICCT_it/examples/04/SS-29-Osservatore_per_sistemi_non_osservabili.ipynb", "max_issues_repo_name": "ICCTerasmus/ICCT", "max_issues_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICCT_it/examples/04/SS-29-Osservatore_per_sistemi_non_osservabili.ipynb", "max_forks_repo_name": "ICCTerasmus/ICCT", "max_forks_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-24T11:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T16:36:18.000Z", "avg_line_length": 37.4847328244, "max_line_length": 342, "alphanum_fraction": 0.4699623256, "converted": true, "num_tokens": 3890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297119360208, "lm_q2_score": 0.11596070756094144, "lm_q1q2_score": 0.03190423606713897}}
{"text": "## Heading\n\nI am trying out Jupyter to webpage conversion using jekyll.\n\n\n```python\nimport keras as kr\n```\n\n---\ntitle: \"Title\"\nauthor: \"Me\"\nheader-includes:\n   - \\usepackage{bbm}\noutput:\n    pdf_document\n---\n\nLet us try some latex. $56+x+c+\\pi$\n\n$$d+\\phi^2_3$$\n\n\\begin{equation}\nd+\\phi^2_3\n\\end{equation}\n\n~~strike~~. **bold**\n```python\nimport stuff\nprint(stuff)```\n\n\\begin{document}\n\\begin{center}\n\\begin{Large}\n\\textbf{A Self-driving car simulation using Q-Learning}\\\\\n\\end{Large}\n\\vspace{2mm}\n\\begin{small}\n\\textbf{Tushar Agarwal} (agarwal.270@osu.edu), \\textbf{Wenxiao Zhan} (zhan.137@osu.edu)\\\\\n\\end{small}\n\\end{center}\n\n\\section*{Introduction}\n\nCreating intelligent machines has long been a human endeavor with a rich past as well as present. Reinforcement learning is one major component of this endeavor. As the name suggests, reinforcement learning refers to a reward based learning system designed for a machine to teach it the correct behavior of acting in a specified environment. It has its roots in behaviorist psychology and can be simply thought of as the reward based training routine usually followed while teaching pet animals like dogs. Such a training requires a time-dependent modeling of the processes. \\\\\n\n\\subsection*{Components}\nImportant components of an RL agent are the policy, the value function and the model.\n\\begin{itemize}\n\n\\item The model predicts how the environment will behave next. It has 2 main sub-components:-\\\\\nThe transition probability: $\\mathcal{P}(s,a,s')=P(s_{t+1}=s'|s_{t}=s,a_{t}=a)$\\\\\nThe Reward: $r(s,a)=E[r_{t+1}|s_{t}=s,a_{t}=a]$\n\n\\item The policy $\\pi$ defines the agents behavior and is a mapping from state $s_t$ to action $a_t$. It can be be deterministic or probabilistic.\\\\\nDeterministic policy: $a_t=\\pi(s_t)$\\\\\nProbabilistic policy: $\\pi(a|s)=P(a_t=a|s_t=s)$\n\n\\item Value function is a prediction of the future reward. It tries to measure the goodness or badness of states $V(s_t)$ or state-action pairs $q(s_t,a_t)$ to help make a decision between available set of actions $A$ at a given state.\\\\\nState value function for a given policy $\\pi$: $V_{\\pi}(s)=E_{\\pi}[G_t|s_t=s]$\\\\\nState-action value function for a given policy $\\pi$: $Q_{\\pi}(s,a)=E_{\\pi}[G_t|s_t=s,a_t=a]$\\\\\n\nwhere $G_t=r_t+\\sum_{i>t}\\gamma^{i-t}r_i$ is a measure of the cumulative reward.\nThe term $\\gamma \\in [0,1)$ is a discount factor used to represent the fact that the present reward is more valuable than the future reward as the future is always uncertain. This is a very practical assumption and has real life manifestations like time value of money in finances. It also allows the cumulative reward to be finite in case of infinite time horizon, i.e. when the agent takes actions forever.\n\n\\end{itemize}\n\n", "meta": {"hexsha": "bd30c97b101a98d9f4df16fbafccc21313a86dc5", "size": 4041, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "_posts/.ipynb_checkpoints/2018-06-21-jup-checkpoint.ipynb", "max_stars_repo_name": "tu-curious/tu-curious.github.io", "max_stars_repo_head_hexsha": "b9bca2dbca7d6a9ae325b7c504dfbd320d2d84fa", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-13T11:26:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-13T11:26:57.000Z", "max_issues_repo_path": "_posts/.ipynb_checkpoints/2018-06-21-jup-checkpoint.ipynb", "max_issues_repo_name": "tushar-agarwal2909/tushar-agarwal2909.github.io", "max_issues_repo_head_hexsha": "b9bca2dbca7d6a9ae325b7c504dfbd320d2d84fa", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_posts/.ipynb_checkpoints/2018-06-21-jup-checkpoint.ipynb", "max_forks_repo_name": "tushar-agarwal2909/tushar-agarwal2909.github.io", "max_forks_repo_head_hexsha": "b9bca2dbca7d6a9ae325b7c504dfbd320d2d84fa", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7663551402, "max_line_length": 588, "alphanum_fraction": 0.6025736204, "converted": true, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.09534947453918644, "lm_q1q2_score": 0.031902927409851276}}
{"text": "```python\n%matplotlib inline\n```\n\n\n.. currentmodule:: dgl\n\nWorking with Heterogeneous Graphs\n=================================\n\n**Author**: Quan Gan, `Minjie Wang <https://jermainewang.github.io/>`_, Mufei Li,\nGeorge Karypis, Zheng Zhang\n\nIn this tutorial, you learn about:\n\n* Examples of heterogenous graph data and typical applications.\n\n* Creating and manipulating a heterogenous graph in DGL.\n\n* Implementing `Relational-GCN <https://arxiv.org/abs/1703.06103>`_, a popular GNN model,\n  for heterogenous graph input.\n\n* Training a model to solve a node classification task.\n\nHeterogeneous graphs, or *heterographs* for short, are graphs that contain\ndifferent types of nodes and edges. The different types of nodes and edges tend\nto have different types of attributes that are designed to capture the\ncharacteristics of each node and edge type. Within the context of\ngraph neural networks, depending on their complexity, certain node and edge types\nmight need to be modeled with representations that have a different number of dimensions.\n\nDGL supports graph neural network computations on such heterogeneous graphs, by\nusing the heterograph class and its associated API.\n\n\nExamples of heterographs\n-----------------------\nMany graph datasets represent relationships among various types of entities.\nThis section provides an overview for several graph use-cases that show such relationships \nand can have their data represented as heterographs.\n\nCitation graph \n~~~~~~~~~~~~~~~\nThe Association for Computing Machinery publishes an `ACM dataset <https://aminer.org/citation>`_ that contains two\nmillion papers, their authors, publication venues, and the other papers\nthat were cited. This information can be represented as a heterogeneous graph.\n\nThe following diagram shows several entities in the ACM dataset and the relationships among them \n(taken from `Shi et al., 2015 <https://arxiv.org/pdf/1511.04854.pdf>`_).\n\n.. figure:: https://data.dgl.ai/tutorial/hetero/acm-example.png# \n\nThis graph has three types of entities that correspond to papers, authors, and publication venues.\nIt also contains three types of edges that connect the following:\n\n* Authors with papers corresponding to *written-by* relationships\n\n* Papers with publication venues corresponding to *published-in* relationships\n\n* Papers with other papers corresponding to *cited-by* relationships\n\n\nRecommender systems \n~~~~~~~~~~~~~~~~~~~~ \nThe datasets used in recommender systems often contain\ninteractions between users and items. For example, the data could include the\nratings that users have provided to movies. Such interactions can be modeled\nas heterographs.\n\nThe nodes in these heterographs will have two types, *users* and *movies*. The edges\nwill correspond to the user-movie interactions. Furthermore, if an interaction is\nmarked with a rating, then each rating value could correspond to a different edge type.\nThe following diagram shows an example of user-item interactions as a heterograph.\n\n.. figure:: https://data.dgl.ai/tutorial/hetero/recsys-example.png\n\n\nKnowledge graph \n~~~~~~~~~~~~~~~~\nKnowledge graphs are inherently heterogenous. For example, in\nWikidata, Barack Obama (item Q76) is an instance of a human, which could be viewed as\nthe entity class, whose spouse (item P26) is Michelle Obama (item Q13133) and\noccupation (item P106) is politician (item Q82955). The relationships are shown in the following.\ndiagram.\n\n.. figure:: https://data.dgl.ai/tutorial/hetero/kg-example.png\n\n\n\n\nCreating a heterograph in DGL\n-----------------------------\nYou can create a heterograph in DGL using the :func:`dgl.heterograph` API.\nThe argument to :func:`dgl.heterograph` is a dictionary. The keys are tuples\nin the form of ``(srctype, edgetype, dsttype)`` specifying the relation name\nand the two entity types it connects. Such tuples are called *canonical edge\ntypes*. The values are data to initialize the graph structures, that is, which\nnodes the edges actually connect.\n\nFor instance, the following code creates the user-item interactions heterograph shown earlier.\n\n\n\n\n```python\n# Each value of the dictionary is a pair of source and destination arrays.\n# Nodes are integer IDs starting from zero. Nodes IDs of different types have\n# separate countings.\nimport dgl\nimport numpy as np\n\nratings = dgl.heterograph(\n    {('user', '+1', 'movie') : (np.array([0, 0, 1]), np.array([0, 1, 0])),\n     ('user', '-1', 'movie') : (np.array([2]), np.array([1]))})\n```\n\n    Using backend: pytorch\n\n\nDGL supports creating a graph from a variety of data sources. The following\ncode creates the same graph as the above.\n\nCreating from scipy matrix\n\n\n\n\n```python\nimport scipy.sparse as sp\nplus1 = sp.coo_matrix(([1, 1, 1], ([0, 0, 1], [0, 1, 0])), shape=(3, 2))\nminus1 = sp.coo_matrix(([1], ([2], [1])), shape=(3, 2))\nratings = dgl.from_scipy(\n    {('user', '+1', 'movie') : plus1,\n     ('user', '-1', 'movie') : minus1})\n\n# Creating from networkx graph\nimport networkx as nx\nplus1 = nx.DiGraph()\nplus1.add_nodes_from(['u0', 'u1', 'u2'], bipartite=0)\nplus1.add_nodes_from(['m0', 'm1'], bipartite=1)\nplus1.add_edges_from([('u0', 'm0'), ('u0', 'm1'), ('u1', 'm0')])\n# To simplify the example, reuse the minus1 object.\n# This also means that you could use different sources of graph data\n# for different relationships.\nratings = dgl.heterograph(\n    {('user', '+1', 'movie') : plus1,\n     ('user', '-1', 'movie') : minus1})\n```\n\nManipulating heterograph\n------------------------\nYou can create a more realistic heterograph using the ACM dataset. To do this, first \ndownload the dataset as follows:\n\n\n\n\n```python\nimport scipy.io\nimport urllib.request\n\ndata_url = 'https://data.dgl.ai/dataset/ACM.mat'\ndata_file_path = '/tmp/ACM.mat'\n\nurllib.request.urlretrieve(data_url, data_file_path)\ndata = scipy.io.loadmat(data_file_path)\nprint(list(data.keys()))\n```\n\n    ['__header__', '__version__', '__globals__', 'TvsP', 'PvsA', 'PvsV', 'AvsF', 'VvsC', 'PvsL', 'PvsC', 'A', 'C', 'F', 'L', 'P', 'T', 'V', 'PvsT', 'CNormPvsA', 'RNormPvsA', 'CNormPvsC', 'RNormPvsC', 'CNormPvsT', 'RNormPvsT', 'CNormPvsV', 'RNormPvsV', 'CNormVvsC', 'RNormVvsC', 'CNormAvsF', 'RNormAvsF', 'CNormPvsL', 'RNormPvsL', 'stopwords', 'nPvsT', 'nT', 'CNormnPvsT', 'RNormnPvsT', 'nnPvsT', 'nnT', 'CNormnnPvsT', 'RNormnnPvsT', 'PvsP', 'CNormPvsP', 'RNormPvsP']\n\n\nThe dataset stores node information by their types: ``P`` for paper, ``A``\nfor author, ``C`` for conference, ``L`` for subject code, and so on. The relationships\nare stored as SciPy sparse matrix under key ``XvsY``, where ``X`` and ``Y``\ncould be any of the node type code.\n\nThe following code prints out some statistics about the paper-author relationships.\n\n\n\n\n```python\nprint(type(data['PvsA']))\nprint('#Papers:', data['PvsA'].shape[0])\nprint('#Authors:', data['PvsA'].shape[1])\nprint('#Links:', data['PvsA'].nnz)\n```\n\n    <class 'scipy.sparse.csc.csc_matrix'>\n    #Papers: 12499\n    #Authors: 17431\n    #Links: 37055\n\n\nConverting this SciPy matrix to a heterograph in DGL is straightforward.\n\n\n\n\n```python\npa_g = dgl.from_scipy(data['PvsA'], ('paper', 'written-by', 'author'))\n# equivalent (shorter) API for creating heterograph with two node types:\npa_g = dgl.bipartite(data['PvsA'], 'paper', 'written-by', 'author')\n```\n\nYou can easily print out the type names and other structural information.\n\n\n\n\n```python\nprint('Node types:', pa_g.ntypes)\nprint('Edge types:', pa_g.etypes)\nprint('Canonical edge types:', pa_g.canonical_etypes)\n\n# Nodes and edges are assigned integer IDs starting from zero and each type has its own counting.\n# To distinguish the nodes and edges of different types, specify the type name as the argument.\nprint(pa_g.number_of_nodes('paper'))\n# Canonical edge type name can be shortened to only one edge type name if it is\n# uniquely distinguishable.\nprint(pa_g.number_of_edges(('paper', 'written-by', 'author')))\nprint(pa_g.number_of_edges('written-by'))\nprint(pa_g.successors(1, etype='written-by'))  # get the authors that write paper #1\n\n# Type name argument could be omitted whenever the behavior is unambiguous.\nprint(pa_g.number_of_edges())  # Only one edge type, the edge type argument could be omitted\n```\n\nA homogeneous graph is just a special case of a heterograph with only one type\nof node and edge. In this case, all the APIs are exactly the same as in\n:class:`DGLGraph`.\n\n\n\n\n```python\n# Paper-citing-paper graph is a homogeneous graph\npp_g = dgl.heterograph({('paper', 'citing', 'paper') : data['PvsP']})\n# equivalent (shorter) API for creating homogeneous graph\npp_g = dgl.graph(data['PvsP'], 'paper', 'cite')\n\n# All the ntype and etype arguments could be omitted because the behavior is unambiguous.\nprint(pp_g.number_of_nodes())\nprint(pp_g.number_of_edges())\nprint(pp_g.successors(3))\n```\n\nCreate a subset of the ACM graph using the paper-author, paper-paper, \nand paper-subject relationships.  Meanwhile, also add the reverse\nrelationship to prepare for the later sections.\n\n\n\n\n```python\nG = dgl.heterograph({\n        ('paper', 'written-by', 'author') : data['PvsA'],\n        ('author', 'writing', 'paper') : data['PvsA'].transpose(),\n        ('paper', 'citing', 'paper') : data['PvsP'],\n        ('paper', 'cited', 'paper') : data['PvsP'].transpose(),\n        ('paper', 'is-about', 'subject') : data['PvsL'],\n        ('subject', 'has', 'paper') : data['PvsL'].transpose(),\n    })\n\nprint(G)\n```\n\n**Metagraph** (or network schema) is a useful summary of a heterograph.\nServing as a template for a heterograph, it tells how many types of objects\nexist in the network and where the possible links exist.\n\nDGL provides easy access to the metagraph, which could be visualized using\nexternal tools.\n\n\n\n\n```python\n# Draw the metagraph using graphviz.\nimport pygraphviz as pgv\ndef plot_graph(nxg):\n    ag = pgv.AGraph(strict=False, directed=True)\n    for u, v, k in nxg.edges(keys=True):\n        ag.add_edge(u, v, label=k)\n    ag.layout('dot')\n    ag.draw('graph.png')\n\nplot_graph(G.metagraph)\n```\n\nLearning tasks associated with heterographs\n-------------------------------------------\nSome of the typical learning tasks that involve heterographs include:\n\n* *Node classification and regression* to predict the class of each node or\n  estimate a value associated with it.\n\n* *Link prediction* to predict if there is an edge of a certain\n  type between a pair of nodes, or predict which other nodes a particular\n  node is connected with (and optionally the edge types of such connections).\n\n* *Graph classification/regression* to assign an entire\n  heterograph into one of the target classes or to estimate a numerical\n  value associated with it.\n\nIn this tutorial, we designed a simple example for the first task.\n\nA semi-supervised node classification example\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nOur goal is to predict the publishing conference of a paper using the ACM\nacademic graph we just created. To further simplify the task, we only focus\non papers published in three conferences: *KDD*, *ICML*, and *VLDB*. All\nthe other papers are not labeled, making it a semi-supervised setting.\n\nThe following code extracts those papers from the raw dataset and prepares \nthe training, validation, testing split.\n\n\n\n\n```python\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\npvc = data['PvsC'].tocsr()\n# find all papers published in KDD, ICML, VLDB\nc_selected = [0, 11, 13]  # KDD, ICML, VLDB\np_selected = pvc[:, c_selected].tocoo()\n# generate labels\nlabels = pvc.indices\nlabels[labels == 11] = 1\nlabels[labels == 13] = 2\nlabels = torch.tensor(labels).long()\n\n# generate train/val/test split\npid = p_selected.row\nshuffle = np.random.permutation(pid)\ntrain_idx = torch.tensor(shuffle[0:800]).long()\nval_idx = torch.tensor(shuffle[800:900]).long()\ntest_idx = torch.tensor(shuffle[900:]).long()\n```\n\nRelational-GCN on heterograph\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nWe use `Relational-GCN <https://arxiv.org/abs/1703.06103>`_ to learn the\nrepresentation of nodes in the graph. Its message-passing equation is as\nfollows:\n\n\\begin{align}h_i^{(l+1)} = \\sigma\\left(\\sum_{r\\in \\mathcal{R}}\n   \\sum_{j\\in\\mathcal{N}_r(i)}W_r^{(l)}h_j^{(l)}\\right)\\end{align}\n\nBreaking down the equation, you see that there are two parts in the\ncomputation.\n\n(i) Message computation and aggregation within each relation $r$\n\n(ii) Reduction that merges the results from multiple relationships\n\nFollowing this intuition, perform message passing on a heterograph in\ntwo steps.\n\n(i) Per-edge-type message passing\n\n(ii) Type wise reduction\n\n\n\n\n```python\nimport dgl.function as fn\n\nclass HeteroRGCNLayer(nn.Module):\n    def __init__(self, in_size, out_size, etypes):\n        super(HeteroRGCNLayer, self).__init__()\n        # W_r for each relation\n        self.weight = nn.ModuleDict({\n                name : nn.Linear(in_size, out_size) for name in etypes\n            })\n\n    def forward(self, G, feat_dict):\n        # The input is a dictionary of node features for each type\n        funcs = {}\n        for srctype, etype, dsttype in G.canonical_etypes:\n            # Compute W_r * h\n            Wh = self.weight[etype](feat_dict[srctype])\n            # Save it in graph for message passing\n            G.nodes[srctype].data['Wh_%s' % etype] = Wh\n            # Specify per-relation message passing functions: (message_func, reduce_func).\n            # Note that the results are saved to the same destination feature 'h', which\n            # hints the type wise reducer for aggregation.\n            funcs[etype] = (fn.copy_u('Wh_%s' % etype, 'm'), fn.mean('m', 'h'))\n        # Trigger message passing of multiple types.\n        # The first argument is the message passing functions for each relation.\n        # The second one is the type wise reducer, could be \"sum\", \"max\",\n        # \"min\", \"mean\", \"stack\"\n        G.multi_update_all(funcs, 'sum')\n        # return the updated node feature dictionary\n        return {ntype : G.nodes[ntype].data['h'] for ntype in G.ntypes}\n```\n\nCreate a simple GNN by stacking two ``HeteroRGCNLayer``. Since the\nnodes do not have input features, make their embeddings trainable.\n\n\n\n\n```python\nclass HeteroRGCN(nn.Module):\n    def __init__(self, G, in_size, hidden_size, out_size):\n        super(HeteroRGCN, self).__init__()\n        # Use trainable node embeddings as featureless inputs.\n        embed_dict = {ntype : nn.Parameter(torch.Tensor(G.number_of_nodes(ntype), in_size))\n                      for ntype in G.ntypes}\n        for key, embed in embed_dict.items():\n            nn.init.xavier_uniform_(embed)\n        self.embed = nn.ParameterDict(embed_dict)\n        # create layers\n        self.layer1 = HeteroRGCNLayer(in_size, hidden_size, G.etypes)\n        self.layer2 = HeteroRGCNLayer(hidden_size, out_size, G.etypes)\n\n    def forward(self, G):\n        h_dict = self.layer1(G, self.embed)\n        h_dict = {k : F.leaky_relu(h) for k, h in h_dict.items()}\n        h_dict = self.layer2(G, h_dict)\n        # get paper logits\n        return h_dict['paper']\n```\n\nTrain and evaluate\n~~~~~~~~~~~~~~~~~~\nTrain and evaluate this network.\n\n\n\n\n```python\n# Create the model. The output has three logits for three classes.\nmodel = HeteroRGCN(G, 10, 10, 3)\n\nopt = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)\n\nbest_val_acc = 0\nbest_test_acc = 0\n\nfor epoch in range(100):\n    logits = model(G)\n    # The loss is computed only for labeled nodes.\n    loss = F.cross_entropy(logits[train_idx], labels[train_idx])\n\n    pred = logits.argmax(1)\n    train_acc = (pred[train_idx] == labels[train_idx]).float().mean()\n    val_acc = (pred[val_idx] == labels[val_idx]).float().mean()\n    test_acc = (pred[test_idx] == labels[test_idx]).float().mean()\n\n    if best_val_acc < val_acc:\n        best_val_acc = val_acc\n        best_test_acc = test_acc\n\n    opt.zero_grad()\n    loss.backward()\n    opt.step()\n\n    if epoch % 5 == 0:\n        print('Loss %.4f, Train Acc %.4f, Val Acc %.4f (Best %.4f), Test Acc %.4f (Best %.4f)' % (\n            loss.item(),\n            train_acc.item(),\n            val_acc.item(),\n            best_val_acc.item(),\n            test_acc.item(),\n            best_test_acc.item(),\n        ))\n```\n\nWhat's next?\n------------\n* Check out our full implementation in PyTorch\n  `here <https://github.com/dmlc/dgl/tree/master/examples/pytorch/rgcn-hetero>`_.\n\n* We also provide the following model examples:\n\n  * `Graph Convolutional Matrix Completion <https://arxiv.org/abs/1706.02263>_`,\n    which we implement in MXNet\n    `here <https://github.com/dmlc/dgl/tree/v0.4.0/examples/mxnet/gcmc>`_.\n\n  * `Heterogeneous Graph Attention Network <https://arxiv.org/abs/1903.07293>`_\n    requires transforming a heterograph into a homogeneous graph according to\n    a given metapath (i.e. a path template consisting of edge types).  We\n    provide :func:`dgl.transform.metapath_reachable_graph` to do this.  See full\n    implementation\n    `here <https://github.com/dmlc/dgl/tree/master/examples/pytorch/han>`_.\n\n  * `Metapath2vec <https://dl.acm.org/citation.cfm?id=3098036>`_ requires\n    generating random walk paths according to a given metapath.  Please\n    refer to the full metapath2vec implementation\n    `here <https://github.com/dmlc/dgl/tree/master/examples/pytorch/metapath2vec>`_.\n\n* :doc:`Full heterograph API reference <../../api/python/heterograph>`.\n\n\n", "meta": {"hexsha": "cf08225590b2f5683711a9d3b9bd9d903e5f3734", "size": 42948, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "5_hetero.ipynb", "max_stars_repo_name": "d4rkspir1t/groupdetection-dgmg", "max_stars_repo_head_hexsha": "e655c697ebc279c78d674df91f63ca4aa4dde7d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "5_hetero.ipynb", "max_issues_repo_name": "d4rkspir1t/groupdetection-dgmg", "max_issues_repo_head_hexsha": "e655c697ebc279c78d674df91f63ca4aa4dde7d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5_hetero.ipynb", "max_forks_repo_name": "d4rkspir1t/groupdetection-dgmg", "max_forks_repo_head_hexsha": "e655c697ebc279c78d674df91f63ca4aa4dde7d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.8847682119, "max_line_length": 2093, "alphanum_fraction": 0.6291096209, "converted": true, "num_tokens": 4457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23651623106411435, "lm_q2_score": 0.1347759104723777, "lm_q1q2_score": 0.03187669038316127}}
{"text": "```python\nfrom LOTlib3.Grammar import Grammar\nfrom math import log\nfrom LOTlib3.Hypotheses.LOTHypothesis import LOTHypothesis\nfrom LOTlib3.DataAndObjects import FunctionData\nfrom LOTlib3.TopN import TopN\nfrom LOTlib3.Samplers.MetropolisHastings import MetropolisHastingsSampler\nfrom LOTlib3.Eval import primitive\n```\n\n\n```python\nimport numpy as np\nimport pandas as pd\n\nimport os\nimport json\nimport time\nimport copy\n\nfrom IPython.display import clear_output\nfrom IPython.display import HTML\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nfrom matplotlib import colors\n\nfrom PIL import Image, ImageDraw\nfrom IPython.display import Image as Im\nfrom itertools import permutations, combinations\nfrom sympy.utilities.iterables import multiset_permutations\n\n# from skimage.segmentation import flood, flood_fill\n\n%matplotlib inline\n```\n\n\n```python\n# define solver\nclass ARCSolver:\n    def __init__(self, task_filename):\n        # load task and extract input and output pairs\n        self.task_filename = task_filename\n        self.task = self.load_task(task_filename)\n        self.train_inputs, self.train_outputs, self.test_inputs, self.test_outputs = \\\n            self.extract_io_pairs()\n        self.test_pred = np.zeros((5, 5))\n        self.test_pred_height, self.test_pred_width = self.test_pred.shape\n        \n        self.solved = False  # have we solved the task yet?\n        self.selected_colour = 0\n        self.clipboard = None\n        self.description = ''\n        \n        # variables for plotting\n        self.cmap = colors.ListedColormap(\n            ['#000000', '#0074D9','#FF4136','#2ECC40','#FFDC00',\n             '#AAAAAA', '#F012BE', '#FF851B', '#7FDBFF', '#870C25'])\n        self.colour_to_num = {'black': 0, 'blue': 1, 'red': 2, 'green': 3, 'yellow': 4,\n                             'grey': 5, 'magenta': 6, 'orange': 7, 'light_blue': 8, \n                             'maroon': 9}\n        self.num_to_colour = {0: 'black', 1: 'blue', 2: 'red', 3: 'green', 4: 'yellow',\n                             5: 'grey', 6: 'magneta', 7: 'orange', 8: 'light_blue',\n                             9: 'maroon'}\n\n        \n    def load_task(self, task_filename):\n        with open(task_filename, 'r') as f:\n            task = json.load(f)    \n        return task\n\n    def plot_task(self):\n        \"\"\"\n        Plots the first train and test pairs of a specified task,\n        using same color scheme as the ARC app\n        \"\"\"\n        norm = colors.Normalize(vmin=0, vmax=9)\n        n_train = len(self.task['train'])\n        fig, axs = plt.subplots(n_train+1, 2, figsize=(10, 10))\n        for i in range(n_train):\n            axs[i, 0].imshow(self.task['train'][i]['input'], cmap=self.cmap, norm=norm)\n            axs[i, 0].axis('off')\n            axs[i, 0].set_title('Train Input')\n            axs[i, 1].imshow(self.task['train'][i]['output'], cmap=self.cmap, norm=norm)\n            axs[i, 1].axis('off')\n            axs[i, 1].set_title('Train Output')\n        axs[n_train, 0].imshow(self.task['test'][0]['input'], cmap=self.cmap, norm=norm)\n        axs[n_train, 0].axis('off')\n        axs[n_train, 0].set_title('Test Input')\n        axs[n_train, 1].imshow(self.task['test'][0]['output'], cmap=self.cmap, norm=norm)\n        axs[n_train, 1].axis('off')\n        axs[n_train, 1].set_title('Test Output')\n        plt.tight_layout()\n        plt.show()\n    \n    def plot_grid(self, grid):\n        \"\"\"\n        Plots a single grid\n        \"\"\"\n        #plt.clf()\n\n        #plt.draw()\n        #display(plt)\n        \n\n    def plot_grids(self, grids):\n        \"\"\"\n        Plots a list of grids\n        \"\"\"\n        n_grids = len(grids)\n        norm = colors.Normalize(vmin=0, vmax=9)\n        fig, axs = plt.subplots(1, n_grids, figsize=(6, 6), squeeze=False)\n        for i in range(n_grids):\n            axs[0, i].imshow(grids[i], cmap=self.cmap, norm=norm)\n            axs[0, i].axis('off')\n        plt.tight_layout()\n        plt.show()\n    \n    def extract_io_pairs(self):\n        train = self.task['train']\n        test = self.task['test']\n        n_train = len(train)\n        n_test = len(test)\n\n        train_inputs = np.array([train[i]['input'] for i in range(n_train)])\n        train_outputs = np.array([train[i]['output'] for i in range(n_train)])\n        test_inputs = np.array([test[i]['input'] for i in range(n_test)])\n        test_outputs = np.array([test[i]['output'] for i in range(n_test)])\n\n        return train_inputs, train_outputs, test_inputs, test_outputs\n    \n    def copy_from_input(self):\n        # copy over the first test input\n        self.test_pred = self.test_inputs[0].copy()\n        self.test_pred_height, self.test_pred_width = self.test_inputs[0].shape\n        self.description = 'copy from input'\n    \n    def reset(self):\n        # resets grid to all zeros with size of the grid based on current settings\n        self.test_pred = np.zeros((self.test_pred_height, self.test_pred_width))\n        self.description = 'reset'\n    \n    def resize(self):\n        # resizes the grid\n        prev_test_pred = self.test_pred.copy()\n        prev_test_pred_width = self.test_pred_width\n        prev_test_pred_height = self.test_pred_height\n\n        # sample new grid size\n        new_test_pred_width = np.random.choice(np.arange(1, 5))\n        new_test_pred_height = np.random.choice(np.arange(1, 5))\n        new_test_pred = np.zeros((new_test_pred_height, new_test_pred_width))\n        \n        # copy over values\n        for i in range(min(prev_test_pred_height, new_test_pred_height)):\n            for j in range(min(prev_test_pred_width, new_test_pred_width)):\n                new_test_pred[i, j] = prev_test_pred[i, j]\n            \n        self.test_pred = new_test_pred\n        self.test_pred_width = new_test_pred_width\n        self.test_pred_height = new_test_pred_height\n        self.description = f'resize: ({new_test_pred_height}, {new_test_pred_width})'\n        \n    def change_colour(self):\n        self.selected_colour = np.random.choice(np.arange(10))\n        self.description = f'change colour: {self.num_to_colour[self.selected_colour]}'\n    \n    def edit(self):\n        # select a random location\n        x = np.random.choice(np.arange(self.test_pred_width))\n        y = np.random.choice(np.arange(self.test_pred_height))\n        self.test_pred[y, x] = self.selected_colour\n        self.description = f'edit: ({y}, {x})'\n    \n    def edit_rectangle(self):\n        # selects a randomly selected region and changes the colour of all of the cells\n        x_start = np.random.choice(np.arange(self.test_pred_width))\n        x_end = np.random.choice(np.arange(x_start+1, self.test_pred_width+1))\n        y_start = np.random.choice(np.arange(self.test_pred_height))\n        y_end = np.random.choice(np.arange(y_start+1, self.test_pred_height+1))\n        \n        # select a new colour\n        self.selected_colour = np.random.choice(np.arange(10))\n        self.test_pred[y_start:y_end, x_start:x_end] = self.selected_colour\n        self.description = f'edit rectangle from ({y_start}:{y_end}, {x_start}:{x_end}) to {self.selected_colour}'\n    \n    def copy(self):\n        # copies a randomly selected region\n        x_start = np.random.choice(np.arange(self.test_pred_width))\n        x_end = np.random.choice(np.arange(x_start+1, self.test_pred_width+1))\n        y_start = np.random.choice(np.arange(self.test_pred_height))\n        y_end = np.random.choice(np.arange(y_start+1, self.test_pred_height+1))\n        \n        self.clipboard = self.test_pred[y_start:y_end, x_start:x_end].copy()\n        self.description = f'copy from ({y_start}:{y_end}, {x_start}:{x_end})'\n        #print(f'clipboard: {self.clipboard}')\n    \n    def paste(self):\n        # pastes clipboard value into randomly selected location\n        clipboard_height, clipboard_width = self.clipboard.shape\n        x_start = np.random.choice(np.arange(self.test_pred_width))\n        x_width = min(clipboard_width, self.test_pred_width - x_start) \n        y_start = np.random.choice(np.arange(self.test_pred_height))\n        y_height = min(clipboard_height, self.test_pred_height - y_start)\n        \n        self.test_pred[y_start:y_start+y_height, x_start:x_start+x_width] = self.clipboard[:y_height, :x_width] \n        self.description = f'pasting from ({y_start}:{y_start+y_height}, {x_start}:{x_start+x_width})'\n    \n    def flood_fill(self):\n        # flood fill at a random location\n        x = np.random.choice(self.test_pred_width)\n        y = np.random.choice(self.test_pred_height)\n        self.test_pred = flood_fill(self.test_pred, (y, x), \n                                    self.selected_colour)\n        self.description = f'flood fill from: ({y}, {x})'\n     \n    def solve(self):\n        fig = plt.figure(figsize=(6, 6))\n        plt.ion()\n        plt.show()\n        norm = colors.Normalize(vmin=0, vmax=9)\n                \n        while not self.solved:\n            clear_output()\n            # randomly select available function\n            if np.random.choice([0, 1]) == 0:\n                self.change_colour()\n            else:\n                self.edit()\n\n            plt.imshow(self.test_pred, cmap=self.cmap, norm=norm)\n            plt.axis('off')\n            plt.tight_layout()\n            plt.pause(1)\n                        \n            # check accuracy\n            \n            \n```\n\n\n```python\n# displaying a single grid\ndef DisplayGrid(grid):\n    grid = np.asarray(grid)\n    nrows = len(grid[:,0])\n    ncols = len(grid[0,:])\n    height, width = nrows*50, ncols*50\n    image = Image.new(size=(width,height),mode='RGB',color=(255,255,255))\n    draw = ImageDraw.Draw(image)\n    r = 0 \n    for row in grid:\n        c = 0\n        for col in row:\n            draw.rectangle(xy=[c*50,r*50,(c+1)*50,(r+1)*50], fill=colorMap[np.abs(grid[r][c])])\n            c += 1\n        r += 1\n    for i in range(ncols):\n        draw.line([(i+1)*50,0,(i+1)*50,height],fill=\"grey\")\n    for i in range(nrows):\n        draw.line([0,(i+1)*50,width,(i+1)*50],fill=\"grey\")\n    display(image)\n```\n\n\n```python\ncolorMap = {0:\"black\",1:\"blue\",2:\"red\", 3:\"green\",4:\"yellow\",5:\"grey\",6:\"magenta\",7:\"orange\",8:\"cyan\",9:\"brown\"}\n```\n\n\n```python\ntraining_path = \"/Users/aysjajohnson/Desktop/ARC-master/data/training/\"\nsolver = ARCSolver(task_filename=os.path.join(training_path, '0ca9ddb6.json'))\nsolver.plot_grids(solver.train_inputs)\nsolver.plot_grids(solver.train_outputs)\n```\n\n\n```python\nsolver.plot_task()\n```\n\n\n```python\nb = 0.05\n```\n\nHow do you get LOTlib to start with a hypothesis and expand from there? This is awkward right now -- you have to add the input as a rule...\n\nIt also doesn't really understand how to compile lists of lists, just numbers.. I think we'd need to change the backend a bit\n\n\n```python\n# intializing basic hypothesis, will edit later\nclass ARCHypothesis(LOTHypothesis):\n    def __init__(self, **kwargs):\n        LOTHypothesis.__init__(self, grammar=grammar, display=\"lambda grid: %s\", **kwargs)\n        \n    def __call__(self, *args):\n        try:\n            # try to do it from the superclass\n            return LOTHypothesis.__call__(self, *args)\n        except ZeroDivisionError:\n            # and if we get an error, return nan\n            return float(\"nan\")\n\n    def compute_single_likelihood(self, datum):\n        # for each correct pixel, add log(1), for each incorrect, add log(exp(-b))\n        ll = 0\n        input_grid = self(*datum.input)\n        output_grid = datum.output\n        print(input_grid)\n        # assuming input and output are the same size for now\n        height, width = len(input_grid[:,0]), len(input_grid[0,:])\n        for i in range(height):\n            for j in range(width):\n                if input_grid[i][j] == output_grid[i][j]:\n                    ll += log(1)\n                elif input_grid[i][j] == 0 and output_grid[i][j] != 0:\n                    ll += log(0.1)\n                else:\n                    ll += log(0.05)\n        # print(self.value, ll)\n        return ll\n        \n    def display_hypothesis(self):\n        return self.value\n```\n\n\n```python\ninputs = solver.train_inputs\noutputs = solver.train_outputs\nprint([inputs[0]])\n```\n\n    [array([[0, 0, 0, 0, 0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0, 0, 0, 0, 0],\n           [0, 0, 2, 0, 0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0, 0, 1, 0, 0],\n           [0, 0, 0, 0, 0, 0, 0, 0, 0],\n           [0, 0, 0, 0, 0, 0, 0, 0, 0]])]\n\n\n\n```python\ndata = [FunctionData(input=[inputs[0]],output=outputs[0])]\nprint(data)\n```\n\n    [<[[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]] -> [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]>]\n\n\n\n```python\n@primitive\ndef red_squares_(grid):\n    grid = copy.deepcopy(grid)\n    height, width = len(grid[:,0]), len(grid[0,:])\n    lst = []\n    for i in range(height):\n        for j in range(width):\n            if grid[i][j] == 2:\n                lst.append((i,j))\n    return lst\n\n@primitive\ndef blue_squares_(grid):\n    grid = copy.deepcopy(grid)\n    height, width = len(grid[:,0]), len(grid[0,:])\n    lst = []\n    for i in range(height):\n        for j in range(width):\n            if grid[i][j] == 1:\n                lst.append((i,j))\n    return lst\n\n@primitive\ndef diag_(lst, grid):\n    grid = copy.deepcopy(grid)\n    height, width = len(grid[:,0]), len(grid[0,:])\n    diag_lst = []\n    for tup in lst:\n        # check whether diagonals exist on board constraints\n        N, E, S, W = tup[0]-1, tup[1] + 1, tup[0] + 1, tup[1] -1\n        if  N > 0 and S < height-1 and W > 0 and E < width - 1:\n            diag_lst.extend([(N,W),(N,E),(S,E),(S,W)])\n    return diag_lst\n\n@primitive\ndef cross_(lst, grid):\n    grid = copy.deepcopy(grid)\n    height, width = len(grid[:,0]), len(grid[0,:])\n    cross_lst = []\n    for tup in lst:\n        # check whether diagonals exist on board constraints\n        N, E, S, W = tup[0]-1, tup[1] + 1, tup[0] + 1, tup[1] -1\n        if  N > 0 and S < height-1 and W > 0 and E < width - 1:\n            cross_lst.extend([(N,tup[1]),(tup[0],E),(S,tup[1]),(tup[0],W)])\n    return cross_lst\n\n@primitive\ndef color_(lst, clr):\n    return {k:clr for k in lst}\n\n@primitive\ndef paint_(dict_, grid):\n    grid = copy.deepcopy(grid)\n    height, width = len(grid[:,0]), len(grid[0,:])\n    for coord in dict_.keys():\n        grid[coord[0]][coord[1]] = dict_[coord]\n    return grid\n```\n\n\n```python\n# initializing grammar\ngrammar = Grammar(start='GRID')\n\n# adding production rules\ngrammar.add_rule('LIST', 'red_squares_', ['GRID'], 1.0)\ngrammar.add_rule('LIST', 'blue_squares_', ['GRID'], 1.0)\ngrammar.add_rule('LIST', 'diag_', ['LIST', 'GRID'], 1.0)\ngrammar.add_rule('LIST', 'cross_', ['LIST', 'GRID'], 1.0)\ngrammar.add_rule('DICT', 'color_', ['LIST','COLOR'], 1.0)\ngrammar.add_rule('GRID', 'paint_', ['DICT', 'GRID'], 1.0)\n\n# adding numbers 0 through 9 (colors) as terminals\nfor n in range(10):\n    grammar.add_rule('COLOR', str(n), None, 1.0)\n\ngrammar.add_rule('GRID', 'grid', None, 3.0)\n```\n\n\n\n\n    GRID -> grid\tw/ p=3.0\n\n\n\n\n```python\nrs = red_squares_(inputs[0])\n```\n\n\n```python\ndiag_(rs, inputs[0])\n```\n\n\n\n\n    [(2, 1), (2, 3), (4, 3), (4, 1)]\n\n\n\n\n```python\ngrammar.display_rules()\n```\n\n    LIST -> red_squares_['GRID']\tw/ p=1.0\n    LIST -> blue_squares_['GRID']\tw/ p=1.0\n    LIST -> diag_['LIST', 'GRID']\tw/ p=1.0\n    LIST -> cross_['LIST', 'GRID']\tw/ p=1.0\n    DICT -> color_['LIST', 'COLOR']\tw/ p=1.0\n    GRID -> paint_['DICT', 'GRID']\tw/ p=1.0\n    GRID -> grid\tw/ p=3.0\n    COLOR -> 0\tw/ p=1.0\n    COLOR -> 1\tw/ p=1.0\n    COLOR -> 2\tw/ p=1.0\n    COLOR -> 3\tw/ p=1.0\n    COLOR -> 4\tw/ p=1.0\n    COLOR -> 5\tw/ p=1.0\n    COLOR -> 6\tw/ p=1.0\n    COLOR -> 7\tw/ p=1.0\n    COLOR -> 8\tw/ p=1.0\n    COLOR -> 9\tw/ p=1.0\n\n\n\n```python\ndef plot_grid(grid):\n    \"\"\"\n    Plots a list of grids\n    \"\"\"\n    cmap = colors.ListedColormap(\n            ['#000000', '#0074D9','#FF4136','#2ECC40','#FFDC00',\n             '#AAAAAA', '#F012BE', '#FF851B', '#7FDBFF', '#870C25'])\n    \n    norm = colors.Normalize(vmin=0, vmax=9)\n    fig, axs = plt.subplots(1, 1, figsize=(6, 6), squeeze=False)\n    axs[0, 0].imshow(grid, cmap=cmap, norm=norm)\n    axs[0, 0].axis('off')\n    plt.tight_layout()\n    plt.show()\n```\n\n\n```python\npl\n```\n\n\n```python\nDisplayGrid(h(inputs[0]))\n```\n\n\n```python\nDisplayGrid(paint_(color_(diag_(red_squares_(inputs[0]),inputs[0]),4),inputs[0]))\n```\n\n\n```python\ntn = TopN(N=10) # store the top hypotheses\n\nh0 = ARCHypothesis()\n\nfor h in MetropolisHastingsSampler(h0, data, steps=1000):\n    tn.add(h)\n\nfor h in tn.get_all(sorted=True):\n    print(h.posterior_score, h)\n```\n\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 9 0 9 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 9 0 9 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 6 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 9 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 3 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 7 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 8 0 0]\n     [0 0 0 0 0 8 9 8 0]\n     [0 0 0 0 0 0 8 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 2 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 7 0 0 0 0 0]\n     [0 0 7 0 7 0 0 0 0]\n     [0 0 2 7 0 0 0 0 0]\n     [0 0 7 0 7 0 0 0 0]\n     [0 0 0 7 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 7 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 0 7 0]\n     [0 0 0 0 7 0 7 0 0]\n     [0 0 0 0 0 7 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 2 0 0]\n     [0 0 0 0 0 2 1 2 0]\n     [0 0 0 0 0 0 2 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 3 0 0]\n     [0 0 0 0 0 3 1 3 0]\n     [0 0 0 0 0 0 3 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 6 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 0 7 0]\n     [0 0 0 0 7 0 7 0 0]\n     [0 0 0 0 0 7 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 2 0 0]\n     [0 0 0 0 0 2 1 2 0]\n     [0 0 0 0 0 0 2 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 4 1 4 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 7 0 7 0 0 0 0]\n     [0 7 2 7 0 7 0 0 0]\n     [0 0 7 0 7 0 0 0 0]\n     [0 7 0 7 0 7 0 0 0]\n     [0 0 7 0 7 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 2 0 0]\n     [0 0 0 0 0 2 1 2 0]\n     [0 0 0 0 0 0 2 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 7 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 7 1 7 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 3 0 0 0 0 0 0]\n     [0 3 2 3 0 0 0 0 0]\n     [0 0 3 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 7 0 0 0 0 0 0]\n     [0 7 2 7 0 0 0 0 0]\n     [0 0 7 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 5 0 5 0 0 0]\n     [0 0 5 0 5 0 5 0 0]\n     [0 5 2 5 0 5 0 5 0]\n     [0 0 5 0 5 0 5 0 0]\n     [0 5 0 5 0 5 0 5 0]\n     [0 0 5 0 5 0 5 0 0]\n     [0 0 0 5 0 5 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 4 2 4 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 9 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 1 0 1 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 1 0 1 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 4 1 4 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 4 2 4 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 2 0 2 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 2 0 2 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 7 0 7 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 7 0 7 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 8 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 4 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 4 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 4 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 9 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 4 0 4 0 0]\n     [0 0 0 4 0 4 0 4 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 4 0 4 1 4 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 5 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 8 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 6 0 6 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 6 0 6 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 8 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 8 0 0]\n     [0 0 0 0 0 8 1 8 0]\n     [0 0 0 0 0 0 8 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 9 0 9 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 9 0 9 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 5 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 9 0 9 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 9 0 9 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 9 0 9 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 4 0 4 0 4 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 4 0 4 0 4 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 0 0 4 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 3 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 6 0 6 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 6 0 6 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 2 0 2 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 2 0 2 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 5 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 2 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 0 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 4 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 4 0 0 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 4 2 4 0 4 0 0 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 4 0 4 0 4 0 0 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 4 0 4 0 4 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 9 0 0 0 0 0]\n     [0 0 9 0 9 0 0 0 0]\n     [0 0 2 9 0 0 0 0 0]\n     [0 0 9 0 9 0 0 0 0]\n     [0 0 0 9 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 8 0 0]\n     [0 0 0 0 0 8 1 8 0]\n     [0 0 0 0 0 0 8 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 9 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 6 0 6 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 6 0 6 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 3 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 2 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 3 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 6 0 6 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 6 0 6 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 4 1 4 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 2 0 2 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 2 0 2 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 4 1 4 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 5 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 6 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 4 1 4 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 4 0 4 0 4 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 0 0 4 0 4 0 4 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 0 0 4 0 4 1 4 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 1 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 4 4 4 4 0 0 0 0]\n     [0 4 2 4 0 0 0 0 0]\n     [0 4 4 4 4 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 4 1 4 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 6 0 6 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 6 0 6 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 7 0 7 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 7 0 7 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 2 0 2 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 2 0 2 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 4 1 4 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 4 2 4 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 6 0 6 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 6 0 6 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 7 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 6 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 7 0 7 0 0]\n     [0 4 0 4 0 7 0 7 0]\n     [0 0 0 0 7 0 7 0 0]\n     [0 0 0 7 0 7 1 7 0]\n     [0 0 0 0 7 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 4 2 4 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 9 0 9 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 9 0 9 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 3 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 6 0 6 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 6 0 6 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 7 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 3 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 2 4 0 4 0 4 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 0 0 4 0 4 0 4 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 0 0 4 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 2 4 0 4 0 4 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 0 0 4 0 4 0 4 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 0 0 4 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 4 0 4 0 4 0 0 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 4 0 4 0 4 0 0 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 4 0 4 0 4 1 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 4 0 0 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 4 2 4 0 4 0 0 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 4 0 4 0 4 0 0 0]\n     [0 0 4 0 4 0 1 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 3 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 6 0 0 0]\n     [0 0 0 0 6 0 6 0 0]\n     [0 0 0 6 0 6 0 6 0]\n     [0 0 0 0 6 0 6 0 0]\n     [0 0 0 0 0 6 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 2 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 4 0 0 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 4 2 4 0 4 0 0 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 4 0 4 0 4 0 0 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 4 0 4 0 4 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 9 0 0 0]\n     [0 0 0 0 9 0 9 0 0]\n     [0 0 0 0 0 9 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 3 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 6 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 3 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 2 0 2 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 2 0 2 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 9 0 9 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 9 0 9 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 4 1 4 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 3 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 8 0 8 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 8 0 8 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 4 1 4 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 7 0 7 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 7 0 7 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 9 0 9 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 9 0 9 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 4 1 4 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 4 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 0 2 4 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 0 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 8 0 8 0]\n     [0 0 0 0 8 0 8 0 0]\n     [0 0 0 0 0 8 1 8 0]\n     [0 0 0 0 8 0 8 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 4 1 4 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 4 1 4 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 1 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 1 0 1 0 1 0 0 0]\n     [0 0 1 0 1 0 0 0 0]\n     [0 1 2 1 0 1 0 0 0]\n     [0 0 1 0 1 0 0 0 0]\n     [0 1 0 1 0 1 0 0 0]\n     [0 0 1 0 1 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 4 0 0 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 4 2 4 0 4 0 0 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 4 0 4 0 4 0 0 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 4 0 4 0 4 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 4 1 4 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 8 0 0]\n     [0 0 0 0 0 8 1 8 0]\n     [0 0 0 0 0 0 8 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 7 0 7 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 7 0 7 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 9 0 0 0]\n     [0 0 0 0 9 0 9 0 0]\n     [0 0 0 0 0 9 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 2 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 7 0 7 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 7 0 7 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 7 0 8 0 8 0 0]\n     [0 0 0 8 0 8 0 8 0]\n     [0 0 0 0 8 0 8 0 0]\n     [0 0 0 8 0 8 1 8 0]\n     [0 0 0 0 8 0 8 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 2 0 2 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 2 0 2 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 1 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 8 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 7 0 7 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 7 0 7 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 3 0 3 0 0 0 0]\n     [0 3 2 3 0 0 0 0 0]\n     [0 0 3 0 3 0 0 0 0]\n     [0 3 0 3 0 3 0 3 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 3 0 3 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 8 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 3 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 2 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 4 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 6 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 6 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 9 0 9 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 9 0 9 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 7 0 7 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 7 0 7 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 9 0 9 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 9 0 9 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 4 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 4 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 4 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 1 0 1 0]\n     [0 0 0 0 1 0 1 0 0]\n     [0 0 0 0 0 1 1 1 0]\n     [0 0 0 0 1 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 6 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 7 0 7 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 7 0 7 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 9 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 9 0 9 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 9 0 9 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 4 2 4 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 2 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 4 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 4 2 4 0 4 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 4 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 2 0 2 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 2 0 2 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 7 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 7 0 7 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 7 0 7 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 6 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 3 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 4 0 4 0 4 0 0 0]\n     [0 0 4 0 4 4 4 0 0]\n     [0 4 0 4 4 4 4 0 0]\n     [0 0 4 4 4 4 4 4 0]\n     [0 4 0 4 4 4 4 0 0]\n     [0 0 4 0 4 4 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 4 2 4 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 0 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 4 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 4 1 4 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 1 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 3 0 3 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 1 0 1 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 4 2 4 0 0 0 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 2 4 0 4 0 4 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 0 0 4 0 4 0 4 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 0 0 4 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 4 2 4 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 4 0 4 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 4 1 4 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 8 0 8 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 8 0 8 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 1 0 1 0]\n     [0 0 0 0 1 0 1 0 0]\n     [0 0 0 0 0 1 1 1 0]\n     [0 0 0 0 1 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 8 0 8 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 4 0 4 0 4 0 0 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 4 0 4 0 4 0 0 0]\n     [0 0 4 0 4 0 4 0 0]\n     [0 4 0 4 0 4 1 0 0]\n     [0 0 4 0 4 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 5 0 5 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 4 0 4 0 0]\n     [0 0 0 4 4 4 4 4 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 4 4 4 4 4 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 4 2 4 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 1 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 6 0 6 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 6 0 6 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 9 0 0]\n     [0 0 0 0 0 9 0 9 0]\n     [0 0 0 0 9 0 9 0 0]\n     [0 0 0 0 0 9 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 6 0 6 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 6 0 6 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 6 0 6 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 6 0 6 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 6 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 4 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 4 0 4 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 4 0 4 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    [[0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 7 0 7 0 0 0 0 0]\n     [0 0 2 0 0 0 0 0 0]\n     [0 7 0 7 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 1 0 0]\n     [0 0 0 0 0 0 0 0 0]\n     [0 0 0 0 0 0 0 0 0]]\n    -21.89771065337085 lambda grid: paint_(color_(cross_(blue_squares_(grid), paint_(color_(blue_squares_(grid), 2), grid)), 7), grid)\n    -21.89771065337085 lambda grid: paint_(color_(diag_(red_squares_(paint_(color_(blue_squares_(grid), 3), grid)), grid), 4), grid)\n    -21.89771065337085 lambda grid: paint_(color_(cross_(blue_squares_(grid), paint_(color_(blue_squares_(grid), 3), grid)), 7), grid)\n    -21.89771065337085 lambda grid: paint_(color_(diag_(red_squares_(paint_(color_(blue_squares_(grid), 8), grid)), grid), 4), grid)\n    -21.89771065337085 lambda grid: paint_(color_(diag_(red_squares_(grid), paint_(color_(red_squares_(grid), 4), grid)), 4), grid)\n    -21.89771065337085 lambda grid: paint_(color_(diag_(red_squares_(paint_(color_(blue_squares_(grid), 6), grid)), grid), 4), grid)\n    -21.89771065337085 lambda grid: paint_(color_(diag_(red_squares_(grid), paint_(color_(blue_squares_(grid), 0), grid)), 4), grid)\n    -18.708362816404144 lambda grid: grid\n    -16.534854765685242 lambda grid: paint_(color_(diag_(red_squares_(grid), grid), 4), grid)\n    -16.534854765685242 lambda grid: paint_(color_(cross_(blue_squares_(grid), grid), 7), grid)\n\n\n\n```python\nprint(h)\n```\n\n    lambda grid: paint_(color_(cross_(blue_squares_(grid), grid), 7), grid)\n\n\n\n```python\nDisplayGrid(h(inputs[0]))\n```\n\n\n```python\nplot_grid(h(inputs[0]))\n```\n\n\n```python\ntn = TopN(N=10) # store the top hypotheses\n\nh0 = ARCHypothesis()\n\nfor h in MetropolisHastingsSampler(h0, data, steps=1000):\n    tn.add(h)\n\nfor h in tn.get_all(sorted=True):\n    print(h.posterior_score, h)\n    \n# for h in tn.get_all(sorted=True):\n#     print(h.posterior_score, h.likelihood,  h.prior, h)\n```\n\n    -14.895888865349647 lambda grid: paint_(color_(cross_(blue_squares_(grid), grid), 7), paint_(color_(diag_(red_squares_(grid), paint_(color_(blue_squares_(grid), 7), grid)), 4), grid))\n    -14.895888865349647 lambda grid: paint_(color_(cross_(blue_squares_(grid), grid), 7), paint_(color_(diag_(red_squares_(grid), paint_(color_(red_squares_(grid), 7), grid)), 4), grid))\n    -14.895888865349647 lambda grid: paint_(color_(cross_(blue_squares_(grid), grid), 7), paint_(color_(diag_(red_squares_(grid), paint_(color_(red_squares_(grid), 4), grid)), 4), grid))\n    -14.895888865349647 lambda grid: paint_(color_(cross_(blue_squares_(grid), grid), 7), paint_(color_(diag_(red_squares_(grid), paint_(color_(blue_squares_(grid), 4), grid)), 4), grid))\n    -14.895888865349646 lambda grid: paint_(color_(cross_(blue_squares_(grid), paint_(color_(blue_squares_(grid), 7), grid)), 7), paint_(color_(diag_(red_squares_(grid), grid), 4), grid))\n    -14.895888865349646 lambda grid: paint_(color_(cross_(blue_squares_(paint_(color_(red_squares_(grid), 4), grid)), grid), 7), paint_(color_(diag_(red_squares_(grid), grid), 4), grid))\n    -14.895888865349646 lambda grid: paint_(color_(cross_(blue_squares_(grid), paint_(color_(blue_squares_(grid), 4), grid)), 7), paint_(color_(diag_(red_squares_(grid), grid), 4), grid))\n    -14.895888865349646 lambda grid: paint_(color_(cross_(blue_squares_(paint_(color_(red_squares_(grid), 7), grid)), grid), 7), paint_(color_(diag_(red_squares_(grid), grid), 4), grid))\n    -14.895888865349646 lambda grid: paint_(color_(cross_(blue_squares_(grid), paint_(color_(red_squares_(grid), 7), grid)), 7), paint_(color_(diag_(red_squares_(grid), grid), 4), grid))\n    -11.142470890098139 lambda grid: paint_(color_(cross_(blue_squares_(grid), grid), 7), paint_(color_(diag_(red_squares_(grid), grid), 4), grid))\n\n\n\n```python\n# initializing grammar\ngrammar = Grammar(start='GRID')\n\n# adding production rules\ngrammar.add_rule('LIST', 'red_squares_', ['GRID'], 1.0)\ngrammar.add_rule('LIST', 'blue_squares_', ['GRID'], 1.0)\ngrammar.add_rule('LIST', 'diag_', ['LIST', 'GRID'], 1.0)\ngrammar.add_rule('LIST', 'cross_', ['LIST', 'GRID'], 1.0)\ngrammar.add_rule('DICT', 'color_', ['LIST','COLOR'], 1.0)\ngrammar.add_rule('GRID', 'paint_', ['DICT', 'GRID'], 1.0)\n\n# adding numbers 0 through 9 as terminals\n# for n in range(10):\n#     grammar.add_rule('COLOR', str(n), None, 1.0)\n\n# right now just consider 4 and 7 to see if this makes the right solution come up\ngrammar.add_rule('COLOR', str(4), None, 1.0)\ngrammar.add_rule('COLOR', str(7), None, 1.0)\n\ngrammar.add_rule('GRID', 'grid', None, 3.0)\n```\n\n\n\n\n    GRID -> grid\tw/ p=3.0\n\n\n\n\n```python\nprint(h)\n```\n", "meta": {"hexsha": "c2d465326979c7b983ce3ecd0043b2d21708a3c7", "size": 308209, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/ARC LOTlib.ipynb", "max_stars_repo_name": "aysjajohnson/ARC", "max_stars_repo_head_hexsha": "3650acfa040a2249ea8f1acebf0dc3bf6d21bf6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/ARC LOTlib.ipynb", "max_issues_repo_name": "aysjajohnson/ARC", "max_issues_repo_head_hexsha": "3650acfa040a2249ea8f1acebf0dc3bf6d21bf6f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 32, "max_issues_repo_issues_event_min_datetime": "2020-04-21T18:43:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-27T18:19:34.000Z", "max_forks_repo_path": "notebooks/ARC LOTlib.ipynb", "max_forks_repo_name": "aysjajohnson/ARC", "max_forks_repo_head_hexsha": "3650acfa040a2249ea8f1acebf0dc3bf6d21bf6f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7904955413, "max_line_length": 10688, "alphanum_fraction": 0.3772342793, "converted": true, "num_tokens": 165148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.06371499202962877, "lm_q1q2_score": 0.031857496014814385}}
{"text": "**WARNING:  This document will not render correctly using nbviewer or nbconvert.  To render this notebook correctly, open in `IPython Notebook` and run `Cell->Run All` from the menu bar.**\n\n# Introduction\n\nThe IPython Notebook allows Markdown, HTML, and inline LaTeX in *Mardown Cells*.  The inline LaTeX is parsed with [MathJax](http://www.mathjax.org/) and Markdown is parsed with [marked](https://github.com/chjj/marked).  Any inline HTML is left to the web browser to parse.  NBConvert is a utility that allows users to easily convert their notebooks to various formats.  Pandoc is used to parse markdown text in NBConvert.  Since what the notebook web interface supports is a mix of Markdown, HTML, and LaTeX, Pandoc has trouble converting notebook markdown. This results in incomplete representations of the notebook in nbviewer or a compiled Latex PDF.\n\nThis isn't a Pandoc flaw; Pandoc isn't designed to parse and convert a mixed format document.  Unfortunately, this means that Pandoc can only support a subset of the markup supported in the notebook web interface.  This notebook compares output of Pandoc to the notebook web interface.\n\n**Changes:**\n\n05102013\n\n * heading anchors\n * note on remote images\n\n06102013\n\n * remove strip_math_space filter\n * add lxml test\n \n<style>\n .rendered_html xmp { \n white-space: pre-wrap;\n }\n</style>\n\n## Utilities\n\nDefine functions to render Markdown using the notebook and Pandoc.\n\n\n```python\nfrom IPython.nbconvert.utils.pandoc import pandoc\nfrom IPython.display import HTML, Javascript, display\n\nfrom IPython.nbconvert.filters import citation2latex, strip_files_prefix, \\\n                                     markdown2html, markdown2latex\n\ndef pandoc_render(markdown):\n    \"\"\"Render Pandoc Markdown->LaTeX content.\"\"\"\n    \n    ## Convert the markdown directly to latex.  This is what nbconvert does.\n    #latex = pandoc(markdown, \"markdown\", \"latex\")\n    #html = pandoc(markdown, \"markdown\", \"html\", [\"--mathjax\"])\n    \n    # nbconvert template conversions\n    html = strip_files_prefix(markdown2html(markdown))\n    latex = markdown2latex(citation2latex(markdown))\n    display(HTML(data=\"<div style='display: inline-block; width: 30%; vertical-align: top;'>\" \\\n                 \"<div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div>\" \\\n                 \"<pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>\" + latex + \"</xmp></pre>\"\\\n                 \"</div>\" \\\n                 \"<div style='display: inline-block; width: 2%;'></div>\" \\\n                 \"<div style='display: inline-block; width: 30%; vertical-align: top;'>\" \\\n                 \"<div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div>\" \\\n                 \"<div style='display: inline-block; width: 100%;'>\" + html + \"</div>\" \\\n                 \"</div>\"))\n    javascript = \"\"\"\n    $.getScript(\"https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js\");\n\"\"\"\n    display(Javascript(data=javascript))\n\ndef notebook_render(markdown):\n    javascript = \"\"\"\nvar mdcell = new IPython.MarkdownCell();\nmdcell.create_element();\nmdcell.set_text('\"\"\" + markdown.replace(\"\\\\\", \"\\\\\\\\\").replace(\"'\", \"\\'\").replace(\"\\n\", \"\\\\n\") + \"\"\"');\nmdcell.render();\n$(element).append(mdcell.element)\n.removeClass()\n.css('left', '66%')\n.css('position', 'absolute')\n.css('width', '30%')\nmdcell.element.prepend(\n    $('<div />')\n    .removeClass()\n    .css('background', '#AAAAFF')\n    .css('width', '100 %')\n    .html('Notebook Output')\n\n);\ncontainer.show()\n\"\"\"\n    display(Javascript(data=javascript))\n\n    \ndef pandoc_html_render(markdown):\n    \"\"\"Render Pandoc Markdown->LaTeX content.\"\"\"\n    \n    # Convert the markdown directly to latex.  This is what nbconvert does.\n    latex = pandoc(markdown, \"markdown\", \"latex\")\n    \n    # Convert the pandoc generated latex to HTML so it can be rendered in \n    # the web browser.\n    html = pandoc(latex, \"latex\", \"html\", [\"--mathjax\"])\n    display(HTML(data=\"<div style='background: #AAFFAA; width: 40%;'>HTML Pandoc Output</div>\" \\\n                 \"<div style='display: inline-block; width: 40%;'>\" + html + \"</div>\"))\n    return html\n    \ndef compare_render(markdown):\n    notebook_render(markdown)\n    pandoc_render(markdown)\n```\n\n# Outputs\n\n\n```python\ntry:\n    import lxml\n    print 'LXML found!'\nexcept:\n    print 'Warning! No LXML found - the old citation2latex filter will not work'\n```\n\n    LXML found!\n\n\n## General markdown\n\nHeading level 6 is not supported by Pandoc.\n\n\n```python\ncompare_render(r\"\"\"\n\n# Heading 1 \n## Heading 2 \n### Heading 3 \n#### Heading 4 \n##### Heading 5 \n###### Heading 6\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x21ac2d0>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>\\section{Heading 1}\n\n\\subsection{Heading 2}\n\n\\subsubsection{Heading 3}\n\n\\paragraph{Heading 4}\n\n\\subparagraph{Heading 5}\n\nHeading 6</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><h1 id=\"heading-1\">Heading 1</h1>\n<h2 id=\"heading-2\">Heading 2</h2>\n<h3 id=\"heading-3\">Heading 3</h3>\n<h4 id=\"heading-4\">Heading 4</h4>\n<h5 id=\"heading-5\">Heading 5</h5>\n<h6 id=\"heading-6\">Heading 6</h6></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21b9fd0>\n\n\nHeaders aren't recognized by (Pandoc on Windows?) if there isn't a blank line above the headers.\n\n\n```python\ncompare_render(r\"\"\"\n# Heading 1 \n## Heading 2 \n### Heading 3 \n#### Heading 4 \n##### Heading 5 \n###### Heading 6 \"\"\")\n\nprint(\"\\n\"*10)\n```\n\n\n    <IPython.core.display.Javascript at 0x21ac550>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>\\section{Heading 1}\n\n\\subsection{Heading 2}\n\n\\subsubsection{Heading 3}\n\n\\paragraph{Heading 4}\n\n\\subparagraph{Heading 5}\n\nHeading 6</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><h1 id=\"heading-1\">Heading 1</h1>\n<h2 id=\"heading-2\">Heading 2</h2>\n<h3 id=\"heading-3\">Heading 3</h3>\n<h4 id=\"heading-4\">Heading 4</h4>\n<h5 id=\"heading-5\">Heading 5</h5>\n<h6 id=\"heading-6\">Heading 6</h6></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac550>\n\n\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n\n\nIf internal links are defined, these will not work in nbviewer and latex as the local link is not existing.\n\n\n```python\ncompare_render(r\"\"\"\n[Link2Heading](http://127.0.0.1:8888/0a2d8086-ee24-4e5b-a32b-f66b525836cb#General-markdown)\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x21ac210>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>\\href{http://127.0.0.1:8888/0a2d8086-ee24-4e5b-a32b-f66b525836cb\\#General-markdown}{Link2Heading}</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><p><a href=\"http://127.0.0.1:8888/0a2d8086-ee24-4e5b-a32b-f66b525836cb#General-markdown\">Link2Heading</a></p></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac210>\n\n\nBasic Markdown bold and italic works.\n\n\n```python\ncompare_render(r\"\"\"\nThis is Markdown **bold** and *italic* text.\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x21ac450>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>This is Markdown \\textbf{bold} and \\emph{italic} text.</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><p>This is Markdown <strong>bold</strong> and <em>italic</em> text.</p></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac450>\n\n\nNested lists work as well\n\n\n```python\ncompare_render(r\"\"\"\n- li 1\n- li 2\n    1. li 3\n    1. li 4\n- li 5\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x21ac150>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>\\begin{itemize}\n\\itemsep1pt\\parskip0pt\\parsep0pt\n\\item\n  li 1\n\\item\n  li 2\n\n  \\begin{enumerate}\n  \\def\\labelenumi{\\arabic{enumi}.}\n  \\itemsep1pt\\parskip0pt\\parsep0pt\n  \\item\n    li 3\n  \\item\n    li 4\n  \\end{enumerate}\n\\item\n  li 5\n\\end{itemize}</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><ul>\n<li>li 1</li>\n<li>li 2\n<ol style=\"list-style-type: decimal\">\n<li>li 3</li>\n<li>li 4</li>\n</ol></li>\n<li>li 5</li>\n</ul></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac150>\n\n\nUnicode support\n\n\n```python\ncompare_render(ur\"\"\"\n\u00fcberschu\u00df +***^\u00b0\u00b3\u00b3 \u03b1 \u03b2 \u03b8\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x22b6950>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>\u00fcberschu\u00df +\\emph{*}\\^{}\u00b0\u00b3\u00b3 \u03b1 \u03b2 \u03b8</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><p>\u00fcberschu\u00df +<em>*</em>^\u00b0\u00b3\u00b3 \u03b1 \u03b2 \u03b8</p></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac3d0>\n\n\nPandoc may produce invalid latex, e.g \\sout is not allowed in headings\n\n\n```python\ncompare_render(r\"\"\"\n\n# Heading 1 ~~strikeout~~\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x21ac590>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>\\section{Heading 1 \\sout{strikeout}}</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><h1 id=\"heading-1-strikeout\">Heading 1 <del>strikeout</del></h1></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac590>\n\n\nHorizontal lines work just fine\n\n\n```python\ncompare_render(r\"\"\"\nabove\n\n--------\n\nbelow\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x21ac150>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>above\n\n\\begin{center}\\rule{3in}{0.4pt}\\end{center}\n\nbelow</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><p>above</p>\n<hr />\n<p>below</p></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac450>\n\n\n## Extended markdown of pandoc\n\n(maybe we should deactivate this) \n\n\n```python\ncompare_render(r\"\"\"\nThis is Markdown ~subscript~ and ^superscript^ text.\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x21ac150>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>This is Markdown \\textsubscript{subscript} and\n\\textsuperscript{superscript} text.</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><p>This is Markdown <sub>subscript</sub> and <sup>superscript</sup> text.</p></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac150>\n\n\nNo space before underline behaves inconsistent (Pandoc extension: intraword_underscores - deactivate?)\n\n\n```python\ncompare_render(r\"\"\"\nThis is Markdown not_italic_.\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x21ac5d0>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>This is Markdown not\\_italic\\_.</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><p>This is Markdown not_italic_.</p></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac5d0>\n\n\nPandoc allows to define tex macros which are respected for all output formats, the notebook not. \n\n\n```python\ncompare_render(r\"\"\"\n\\newcommand{\\tuple}[1]{\\langle #1 \\rangle}\n\n$\\tuple{a, b, c}$\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x21ac450>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>\\newcommand{\\tuple}[1]{\\langle #1 \\rangle}\n\n$\\tuple{a, b, c}$</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><p><span class=\"math\">\\(\\langle a, b, c \\rangle\\)</span></p></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac450>\n\n\nWhen placing the \\newcommand inside a math environment it works within the notebook and nbviewer, but produces invalid latex (the newcommand is only valid in the same math environment).\n\n\n```python\ncompare_render(r\"\"\"\n$\\newcommand{\\foo}[1]{...:: #1 ::...}$\n$\\foo{bar}$\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x21ac590>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>$\\newcommand{\\foo}[1]{...:: #1 ::...}$ $\\foo{bar}$</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><p><span class=\"math\">\\(\\newcommand{\\foo}[1]{...:: #1 ::...}\\)</span> <span class=\"math\">\\(\\foo{bar}\\)</span></p></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac590>\n\n\n## HTML or LaTeX injections\n\nRaw HTML gets dropped entirely when converting to $\\LaTeX$.\n\n\n```python\ncompare_render(r\"\"\"\nThis is HTML <b>bold</b> and <i>italic</i> text.\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x21ac5d0>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>This is HTML bold and italic text.</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><p>This is HTML <b>bold</b> and <i>italic</i> text.</p></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac5d0>\n\n\nSame for something like center\n\n\n```python\ncompare_render(r\"\"\"\n<center>Center aligned</center>\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x21ac210>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>Center aligned</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><center>\nCenter aligned\n</center></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac210>\n\n\nRaw $\\LaTeX$ gets droppen entirely when converted to HTML. (I don't know why the HTML output is cropped here???)\n\n\n```python\ncompare_render(r\"\"\"\nThis is \\LaTeX \\bf{bold} and \\emph{italic} text.\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x21ac590>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>This is \\LaTeX \\bf{bold} and \\emph{italic} text.</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><p>This is </p></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac590>\n\n\nA combination of raw $\\LaTeX$ and raw HTML\n\n\n```python\ncompare_render(r\"\"\"\n**foo** $\\left( \\sum_{k=1}^n a_k b_k \\right)^2 \\leq$ <b>b\\$ar</b> $$test$$ \n\\cite{}\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x21ac590>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>\\textbf{foo} $\\left( \\sum_{k=1}^n a_k b_k \\right)^2 \\leq$ b\\$ar \\[test\\]\n\\cite{}</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><p><strong>foo</strong> <span class=\"math\">\\(\\left( \\sum_{k=1}^n a_k b_k \\right)^2 \\leq\\)</span> <b>b$ar</b> <span class=\"math\">\\[test\\]</span> </p></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac590>\n\n\n## Tables\n\nHTML tables render in the notebook, but not in Pandoc.\n\n\n```python\ncompare_render(r\"\"\"\n<table>\n    <tr>\n        <td>a</td>\n        <td>b</td>\n    </tr>\n    <tr>\n        <td>c</td>\n        <td>d</td>\n    </tr>\n</table>\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x21ac5d0>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>a\n\nb\n\nc\n\nd</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><table>\n    <tr>\n        <td>\na\n</td>\n        <td>\nb\n</td>\n    </tr>\n    <tr>\n        <td>\nc\n</td>\n        <td>\nd\n</td>\n    </tr>\n</table></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac5d0>\n\n\nInstead, Pandoc supports simple ascii tables.  Unfortunately marked.js doesn't support this, and therefore it is not supported in the notebook.\n\n\n```python\ncompare_render(r\"\"\"\n+---+---+\n| a | b |\n+---+---+\n| c | d |\n+---+---+\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x21ac210>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>\\begin{longtable}[c]{@{}ll@{}}\n\\hline\\noalign{\\medskip}\n\\begin{minipage}[t]{0.06\\columnwidth}\\raggedright\na\n\\end{minipage} & \\begin{minipage}[t]{0.06\\columnwidth}\\raggedright\nb\n\\end{minipage}\n\\\\\\noalign{\\medskip}\n\\begin{minipage}[t]{0.06\\columnwidth}\\raggedright\nc\n\\end{minipage} & \\begin{minipage}[t]{0.06\\columnwidth}\\raggedright\nd\n\\end{minipage}\n\\\\\\noalign{\\medskip}\n\\hline\n\\end{longtable}</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><table>\n<col width=\"5%\" />\n<col width=\"5%\" />\n<tbody>\n<tr class=\"odd\">\n<td align=\"left\"><p>a</p></td>\n<td align=\"left\"><p>b</p></td>\n</tr>\n<tr class=\"even\">\n<td align=\"left\"><p>c</p></td>\n<td align=\"left\"><p>d</p></td>\n</tr>\n</tbody>\n</table></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac210>\n\n\nAn alternative to basic ascii tables is pipe tables.  Pipe tables can be recognized by Pandoc and are supported by marked, hence, this is the **best way to add tables**.\n\n\n```python\ncompare_render(r\"\"\"\n|Left |Center |Right|\n|:----|:-----:|----:|\n|Text1|Text2  |Text3|\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x21ac150>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>\\begin{longtable}[c]{@{}lcr@{}}\n\\hline\\noalign{\\medskip}\nLeft & Center & Right\n\\\\\\noalign{\\medskip}\n\\hline\\noalign{\\medskip}\nText1 & Text2 & Text3\n\\\\\\noalign{\\medskip}\n\\hline\n\\end{longtable}</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><table>\n<thead>\n<tr class=\"header\">\n<th align=\"left\">Left</th>\n<th align=\"center\">Center</th>\n<th align=\"right\">Right</th>\n</tr>\n</thead>\n<tbody>\n<tr class=\"odd\">\n<td align=\"left\">Text1</td>\n<td align=\"center\">Text2</td>\n<td align=\"right\">Text3</td>\n</tr>\n</tbody>\n</table></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac150>\n\n\nPandoc recognizes cell alignment in simple tables.  Since marked.js doesn't recognize ascii tables, it can't render this table.\n\n\n```python\ncompare_render(r\"\"\"\nRight Aligned Center Aligned Left Aligned\n------------- -------------- ------------\n          Why      does      this\n     actually      work?     Who\n        knows       ...\n\"\"\")\n\nprint(\"\\n\"*5)\n```\n\n\n    <IPython.core.display.Javascript at 0x21ac450>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>\\begin{longtable}[c]{@{}lll@{}}\n\\hline\\noalign{\\medskip}\nRight Aligned & Center Aligned & Left Aligned\n\\\\\\noalign{\\medskip}\n\\hline\\noalign{\\medskip}\nWhy & does & this\n\\\\\\noalign{\\medskip}\nactually & work? & Who\n\\\\\\noalign{\\medskip}\nknows & \\ldots{} &\n\\\\\\noalign{\\medskip}\n\\hline\n\\end{longtable}</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><table>\n<thead>\n<tr class=\"header\">\n<th align=\"left\">Right Aligned</th>\n<th align=\"left\">Center Aligned</th>\n<th align=\"left\">Left Aligned</th>\n</tr>\n</thead>\n<tbody>\n<tr class=\"odd\">\n<td align=\"left\">Why</td>\n<td align=\"left\">does</td>\n<td align=\"left\">this</td>\n</tr>\n<tr class=\"even\">\n<td align=\"left\">actually</td>\n<td align=\"left\">work?</td>\n<td align=\"left\">Who</td>\n</tr>\n<tr class=\"odd\">\n<td align=\"left\">knows</td>\n<td align=\"left\">...</td>\n<td align=\"left\"></td>\n</tr>\n</tbody>\n</table></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac450>\n\n\n    \n    \n    \n    \n    \n    \n\n\n## Images\n\nMarkdown images work on both. However, remote images are not allowed in $\\LaTeX$. Maybe add a preprocessor to download these.\nThe alternate text is displayed in nbviewer next to the image.\n\n\n```python\ncompare_render(r\"\"\"\n\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x22b6690>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>\\begin{figure}[htbp]\n\\centering\n\\includegraphics{https://ipython.org/_static/IPy_header.png}\n\\caption{Alternate Text}\n\\end{figure}</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><div class=\"figure\">\n<p class=\"caption\">Alternate Text</p>\n</div></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac450>\n\n\nHTML Images only work in the notebook.\n\n\n```python\ncompare_render(r\"\"\"\n\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x22b65d0>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp></xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><p></p></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac450>\n\n\n## Math\n\nSimple inline and displaystyle maths work fine\n\n\n```python\ncompare_render(r\"\"\"\nMy equation:\n$$ 5/x=2y $$\n\nIt is inline $ 5/x=2y $ here.\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x22b6950>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>My equation: \\[ 5/x=2y \\]\n\nIt is inline \\$ 5/x=2y \\$ here.</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><p>My equation: <span class=\"math\">\\[ 5/x=2y \\]</span></p>\n<p>It is inline $ 5/x=2y $ here.</p></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac450>\n\n\nIf the first \\$ is on a new line, the equation is not captured by md2tex, if both \\$s are on a new line md2html fails (Note the raw latex is dropped) but the notebook renders it correctly.\n\n\n```python\ncompare_render(r\"\"\"\n$5 \\cdot x=2$\n\n$\n5 \\cdot x=2$\n\n$\n5 \\cdot x=2\n$\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x22b66d0>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>$5 \\cdot x=2$\n\n\\$ 5 \\cdot x=2\\$\n\n\\$ 5 \\cdot x=2 \\$</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><p><span class=\"math\">\\(5 \\cdot x=2\\)</span></p>\n<p>$ 5 x=2$</p>\n<p>$ 5 x=2 $</p></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac450>\n\n\nMathJax permits some $\\LaTeX$ math constructs without \\$s, of course these raw $\\LaTeX$ is stripped when converting to html.\nMoreove, the & are escaped by the lxml parsing [#4251](https://github.com/ipython/ipython/issues/4251).\n\n\n```python\ncompare_render(r\"\"\"\n\\begin{align}\na & b\\\\\nd & c\n\\end{align}\n\n\\begin{eqnarray}\na & b \\\\\nc & d\n\\end{eqnarray}\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x22b6690>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>\\begin{align}\na &amp; b\\\\\nd &amp; c\n\\end{align}\n\n\\begin{eqnarray}\na &amp; b \\\\\nc &amp; d\n\\end{eqnarray}</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac450>\n\n\nThere is another lxml issue, [#4283](https://github.com/ipython/ipython/issues/4283)\n\n\n```python\ncompare_render(r\"\"\"\n1<2 is true, but 3>4 is false.\n\n$1<2$ is true, but $3>4$ is false.\n\n1<2 it is even worse if it is alone in a line.\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x22b6950>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>14 is false.\n\n$14$ is false.\n\n1</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><p>1&lt;2 is true, but 3&gt;4 is false.</p>\n<p><span class=\"math\">\\(1&lt;2\\)</span> is true, but <span class=\"math\">\\(3&gt;4\\)</span> is false.</p>\n<p>1&lt;2 it is even worse if it is alone in a line.</p></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac450>\n\n\n## Listings, and Code blocks\n\n\n```python\ncompare_render(r\"\"\"\nsome source code\n\n```\na = \"test\"\nprint(a)\n```\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x22b68d0>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>some source code\n\n\\begin{verbatim}\na = \"test\"\nprint(a)\n\\end{verbatim}</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><p>some source code</p>\n<pre><code>a = &quot;test&quot;\nprint(a)</code></pre></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac450>\n\n\nLanguage specific syntax highlighting by Pandoc requires additional dependencies to render correctly.\n\n\n```python\ncompare_render(r\"\"\"\nsome source code\n\n```python\na = \"test\"\nprint(a)\n```\n\"\"\")\n```\n\n\n    <IPython.core.display.Javascript at 0x22b6850>\n\n\n\n<div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #AAFFAA; width: 100%;'>NBConvert Latex Output</div><pre class='prettyprint lang-tex' style='background: #EEFFEE; border: 1px solid #DDEEDD;'><xmp>some source code\n\n\\begin{Shaded}\n\\begin{Highlighting}[]\n\\NormalTok{a = }\\StringTok{\"test\"}\n\\KeywordTok{print}\\NormalTok{(a)}\n\\end{Highlighting}\n\\end{Shaded}</xmp></pre></div><div style='display: inline-block; width: 2%;'></div><div style='display: inline-block; width: 30%; vertical-align: top;'><div style='background: #FFAAAA; width: 100%;'>NBViewer Output</div><div style='display: inline-block; width: 100%;'><p>some source code</p>\n<pre class=\"sourceCode python\"><code class=\"sourceCode python\">a = <span class=\"st\">&quot;test&quot;</span>\n<span class=\"kw\">print</span>(a)</code></pre></div></div>\n\n\n\n    <IPython.core.display.Javascript at 0x21ac450>\n\n", "meta": {"hexsha": "671aefb7ffd7ce1c5d2465214cc6bc34d247e024", "size": 85100, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/ipython-master/tools/tests/Markdown Pandoc Limitations.ipynb", "max_stars_repo_name": "burkesquires/jupyter_training_2020", "max_stars_repo_head_hexsha": "63505d9b8133f80330fe92a74b7641066dba420c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-18T19:29:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T13:52:29.000Z", "max_issues_repo_path": "notebooks/ipython-master/tools/tests/Markdown Pandoc Limitations.ipynb", "max_issues_repo_name": "burkesquires/jupyter_training_2020", "max_issues_repo_head_hexsha": "63505d9b8133f80330fe92a74b7641066dba420c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/ipython-master/tools/tests/Markdown Pandoc Limitations.ipynb", "max_forks_repo_name": "burkesquires/jupyter_training_2020", "max_forks_repo_head_hexsha": "63505d9b8133f80330fe92a74b7641066dba420c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-11-18T19:39:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T07:49:09.000Z", "avg_line_length": 31.6121842496, "max_line_length": 727, "alphanum_fraction": 0.5051586369, "converted": true, "num_tokens": 10222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2598256379609837, "lm_q2_score": 0.12252320771203076, "lm_q1q2_score": 0.03183467060880451}}
{"text": "<a name=\"1\"></a>\n# Part 1:  Data Preparation\n\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/content/drive')\n%cd drive/My\\ Drive/Colab\\ Notebooks/Week\\ 1\n```\n\n    Mounted at /content/drive\n    /content/drive/My Drive/Colab Notebooks/Week 1\n\n\n<a name=\"1.1\"></a>\n## 1.1  Importing the Data\n\nWe will first start by importing the packages we will use in this assignment. As in the previous course of this specialization, we will use the [Trax](https://github.com/google/trax) library created and maintained by the [Google Brain team](https://research.google/teams/brain/) to do most of the heavy lifting. It provides submodules to fetch and process the datasets, as well as build and train the model.\n\n\n```python\nfrom termcolor import colored\nimport random\nimport numpy as np\n!pip install trax==1.3.4\nimport trax\nfrom trax import layers as tl\nfrom trax.fastmath import numpy as fastnp\nfrom trax.supervised import training\n\n!pip list | grep trax\n```\n\n    Collecting trax==1.3.4\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/f8/fd/53162b3ea77e8b017b8a961ab973afed2d07bf2dc809abcf821c9b3b4470/trax-1.3.4-py2.py3-none-any.whl (366kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 368kB 7.0MB/s \n    \u001b[?25hRequirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from trax==1.3.4) (1.4.1)\n    Collecting tensorflow-text\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/28/b2/2dbd90b93913afd07e6101b8b84327c401c394e60141c1e98590038060b3/tensorflow_text-2.3.0-cp36-cp36m-manylinux1_x86_64.whl (2.6MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.6MB 17.4MB/s \n    \u001b[?25hCollecting tensor2tensor\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/d6/7c/9e87d30cefad5cbc390bb7f626efb3ded9b19416b8160f1a1278da81b218/tensor2tensor-1.15.7-py2.py3-none-any.whl (1.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.5MB 43.1MB/s \n    \u001b[?25hCollecting t5\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/20/39/a607d2450190af7675e4f77c5eff0cc9a83f82fe63fb396872ef2004106b/t5-0.7.1-py3-none-any.whl (172kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 174kB 38.6MB/s \n    \u001b[?25hRequirement already satisfied: gin-config in /usr/local/lib/python3.6/dist-packages (from trax==1.3.4) (0.3.0)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from trax==1.3.4) (1.18.5)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from trax==1.3.4) (1.15.0)\n    Collecting funcsigs\n      Downloading https://files.pythonhosted.org/packages/69/cb/f5be453359271714c01b9bd06126eaf2e368f1fddfff30818754b5ac2328/funcsigs-1.0.2-py2.py3-none-any.whl\n    Requirement already satisfied: jax in /usr/local/lib/python3.6/dist-packages (from trax==1.3.4) (0.2.6)\n    Requirement already satisfied: absl-py in /usr/local/lib/python3.6/dist-packages (from trax==1.3.4) (0.10.0)\n    Requirement already satisfied: jaxlib in /usr/local/lib/python3.6/dist-packages (from trax==1.3.4) (0.1.57+cuda101)\n    Requirement already satisfied: gym in /usr/local/lib/python3.6/dist-packages (from trax==1.3.4) (0.17.3)\n    Requirement already satisfied: tensorflow-datasets in /usr/local/lib/python3.6/dist-packages (from trax==1.3.4) (4.0.1)\n    Requirement already satisfied: tensorflow<2.4,>=2.3.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-text->trax==1.3.4) (2.3.0)\n    Collecting tf-slim\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/02/97/b0f4a64df018ca018cc035d44f2ef08f91e2e8aa67271f6f19633a015ff7/tf_slim-1.1.0-py2.py3-none-any.whl (352kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 358kB 38.1MB/s \n    \u001b[?25hRequirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax==1.3.4) (2.23.0)\n    Collecting bz2file\n      Downloading https://files.pythonhosted.org/packages/61/39/122222b5e85cd41c391b68a99ee296584b2a2d1d233e7ee32b4532384f2d/bz2file-0.98.tar.gz\n    Collecting gunicorn\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/69/ca/926f7cd3a2014b16870086b2d0fdc84a9e49473c68a8dff8b57f7c156f43/gunicorn-20.0.4-py2.py3-none-any.whl (77kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 81kB 8.6MB/s \n    \u001b[?25hRequirement already satisfied: opencv-python in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax==1.3.4) (4.1.2.30)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax==1.3.4) (1.1.1)\n    Requirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax==1.3.4) (2.10.0)\n    Collecting mesh-tensorflow\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/16/8b/553deb763ce8d00afb17debab7cb14a87b209cd4c6f0e8ecfc8d884cb12a/mesh_tensorflow-0.1.17-py3-none-any.whl (342kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 348kB 37.4MB/s \n    \u001b[?25hRequirement already satisfied: oauth2client in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax==1.3.4) (4.1.3)\n    Requirement already satisfied: google-api-python-client in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax==1.3.4) (1.7.12)\n    Requirement already satisfied: flask in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax==1.3.4) (1.1.2)\n    Collecting gevent\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/3f/92/b80b922f08f222faca53c8d278e2e612192bc74b0e1f0db2f80a6ee46982/gevent-20.9.0-cp36-cp36m-manylinux2010_x86_64.whl (5.3MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5.3MB 29.7MB/s \n    \u001b[?25hRequirement already satisfied: tensorflow-addons in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax==1.3.4) (0.8.3)\n    Collecting kfac\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1c/36/06fe2c757044bb51906fef231ac48cc5bf9a277fc9a8c7e1108d7e9e8cfd/kfac-0.2.3-py2.py3-none-any.whl (191kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 194kB 46.3MB/s \n    \u001b[?25hCollecting pypng\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/bc/fb/f719f1ac965e2101aa6ea6f54ef8b40f8fbb033f6ad07c017663467f5147/pypng-0.0.20.tar.gz (649kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 655kB 36.5MB/s \n    \u001b[?25hRequirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax==1.3.4) (0.16.0)\n    Requirement already satisfied: dopamine-rl in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax==1.3.4) (1.0.5)\n    Collecting tensorflow-gan\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/0c/2e/62922111d7d50e1900e3030764743ea7735540ce103b3ab30fd5cd2d8a2b/tensorflow_gan-2.0.0-py2.py3-none-any.whl (365kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 368kB 39.0MB/s \n    \u001b[?25hRequirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax==1.3.4) (4.41.1)\n    Requirement already satisfied: Pillow in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax==1.3.4) (7.0.0)\n    Collecting tensorflow-probability==0.7.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/3e/3a/c10b6c22320531c774402ac7186d1b673374e2a9d12502cbc8d811e4601c/tensorflow_probability-0.7.0-py2.py3-none-any.whl (981kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 983kB 41.3MB/s \n    \u001b[?25hRequirement already satisfied: torch in /usr/local/lib/python3.6/dist-packages (from t5->trax==1.3.4) (1.7.0+cu101)\n    Requirement already satisfied: nltk in /usr/local/lib/python3.6/dist-packages (from t5->trax==1.3.4) (3.2.5)\n    Collecting sentencepiece\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/e5/2d/6d4ca4bef9a67070fa1cac508606328329152b1df10bdf31fb6e4e727894/sentencepiece-0.1.94-cp36-cp36m-manylinux2014_x86_64.whl (1.1MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.1MB 45.0MB/s \n    \u001b[?25hRequirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from t5->trax==1.3.4) (1.1.4)\n    Requirement already satisfied: scikit-learn in /usr/local/lib/python3.6/dist-packages (from t5->trax==1.3.4) (0.22.2.post1)\n    Collecting transformers>=2.7.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/99/84/7bc03215279f603125d844bf81c3fb3f2d50fe8e511546eb4897e4be2067/transformers-4.0.0-py3-none-any.whl (1.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.4MB 38.6MB/s \n    \u001b[?25hCollecting sacrebleu\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/a3/c4/8e948f601a4f9609e8b2b58f31966cb13cf17b940b82aa3e767f01c42c52/sacrebleu-1.4.14-py3-none-any.whl (64kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 71kB 7.6MB/s \n    \u001b[?25hRequirement already satisfied: babel in /usr/local/lib/python3.6/dist-packages (from t5->trax==1.3.4) (2.9.0)\n    Collecting tfds-nightly\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/04/39/e0bc48b988846e8e7a9a058deb9b5131c10b578839d326298d1b7262ad59/tfds_nightly-4.1.0.dev202012070108-py3-none-any.whl (3.7MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.7MB 44.3MB/s \n    \u001b[?25hCollecting rouge-score\n      Downloading https://files.pythonhosted.org/packages/1f/56/a81022436c08b9405a5247b71635394d44fe7e1dbedc4b28c740e09c2840/rouge_score-0.0.4-py2.py3-none-any.whl\n    Requirement already satisfied: opt-einsum in /usr/local/lib/python3.6/dist-packages (from jax->trax==1.3.4) (3.3.0)\n    Requirement already satisfied: flatbuffers in /usr/local/lib/python3.6/dist-packages (from jaxlib->trax==1.3.4) (1.12)\n    Requirement already satisfied: pyglet<=1.5.0,>=1.4.0 in /usr/local/lib/python3.6/dist-packages (from gym->trax==1.3.4) (1.5.0)\n    Requirement already satisfied: cloudpickle<1.7.0,>=1.2.0 in /usr/local/lib/python3.6/dist-packages (from gym->trax==1.3.4) (1.3.0)\n    Requirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax==1.3.4) (0.8)\n    Requirement already satisfied: dm-tree in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax==1.3.4) (0.1.5)\n    Requirement already satisfied: attrs>=18.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax==1.3.4) (20.3.0)\n    Requirement already satisfied: dill in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax==1.3.4) (0.3.3)\n    Requirement already satisfied: importlib-resources; python_version < \"3.9\" in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax==1.3.4) (3.3.0)\n    Requirement already satisfied: protobuf>=3.6.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax==1.3.4) (3.12.4)\n    Requirement already satisfied: promise in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax==1.3.4) (2.3)\n    Requirement already satisfied: termcolor in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax==1.3.4) (1.1.0)\n    Requirement already satisfied: tensorflow-metadata in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax==1.3.4) (0.25.0)\n    Requirement already satisfied: tensorflow-estimator<2.4.0,>=2.3.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax==1.3.4) (2.3.0)\n    Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax==1.3.4) (1.12.1)\n    Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax==1.3.4) (1.33.2)\n    Requirement already satisfied: astunparse==1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax==1.3.4) (1.6.3)\n    Requirement already satisfied: keras-preprocessing<1.2,>=1.1.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax==1.3.4) (1.1.2)\n    Requirement already satisfied: gast==0.3.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax==1.3.4) (0.3.3)\n    Requirement already satisfied: tensorboard<3,>=2.3.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax==1.3.4) (2.3.0)\n    Requirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax==1.3.4) (0.35.1)\n    Requirement already satisfied: google-pasta>=0.1.8 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax==1.3.4) (0.2.0)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->tensor2tensor->trax==1.3.4) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->tensor2tensor->trax==1.3.4) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->tensor2tensor->trax==1.3.4) (2020.11.8)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->tensor2tensor->trax==1.3.4) (1.24.3)\n    Requirement already satisfied: setuptools>=3.0 in /usr/local/lib/python3.6/dist-packages (from gunicorn->tensor2tensor->trax==1.3.4) (50.3.2)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy->tensor2tensor->trax==1.3.4) (1.1.0)\n    Requirement already satisfied: pyasn1-modules>=0.0.5 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor->trax==1.3.4) (0.2.8)\n    Requirement already satisfied: rsa>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor->trax==1.3.4) (4.6)\n    Requirement already satisfied: pyasn1>=0.1.7 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor->trax==1.3.4) (0.4.8)\n    Requirement already satisfied: httplib2>=0.9.1 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor->trax==1.3.4) (0.17.4)\n    Requirement already satisfied: google-auth>=1.4.1 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor->trax==1.3.4) (1.17.2)\n    Requirement already satisfied: google-auth-httplib2>=0.0.3 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor->trax==1.3.4) (0.0.4)\n    Requirement already satisfied: uritemplate<4dev,>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor->trax==1.3.4) (3.0.1)\n    Requirement already satisfied: itsdangerous>=0.24 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor->trax==1.3.4) (1.1.0)\n    Requirement already satisfied: Werkzeug>=0.15 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor->trax==1.3.4) (1.0.1)\n    Requirement already satisfied: click>=5.1 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor->trax==1.3.4) (7.1.2)\n    Requirement already satisfied: Jinja2>=2.10.1 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor->trax==1.3.4) (2.11.2)\n    Collecting zope.interface\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/82/b0/da8afd9b3bd50c7665ecdac062f182982af1173c9081f9af7261091c5588/zope.interface-5.2.0-cp36-cp36m-manylinux2010_x86_64.whl (236kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 245kB 41.5MB/s \n    \u001b[?25hCollecting zope.event\n      Downloading https://files.pythonhosted.org/packages/9e/85/b45408c64f3b888976f1d5b37eed8d746b8d5729a66a49ec846fda27d371/zope.event-4.5.0-py2.py3-none-any.whl\n    Collecting greenlet>=0.4.17; platform_python_implementation == \"CPython\"\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/80/d0/532e160c777b42f6f393f9de8c88abb8af6c892037c55e4d3a8a211324dd/greenlet-0.4.17-cp36-cp36m-manylinux1_x86_64.whl (44kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 6.2MB/s \n    \u001b[?25hRequirement already satisfied: typeguard in /usr/local/lib/python3.6/dist-packages (from tensorflow-addons->tensor2tensor->trax==1.3.4) (2.7.1)\n    Requirement already satisfied: tensorflow-hub>=0.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gan->tensor2tensor->trax==1.3.4) (0.10.0)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.6/dist-packages (from tensorflow-probability==0.7.0->tensor2tensor->trax==1.3.4) (4.4.2)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.6/dist-packages (from torch->t5->trax==1.3.4) (3.7.4.3)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas->t5->trax==1.3.4) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.6/dist-packages (from pandas->t5->trax==1.3.4) (2.8.1)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->t5->trax==1.3.4) (0.17.0)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.6/dist-packages (from transformers>=2.7.0->t5->trax==1.3.4) (20.4)\n    Requirement already satisfied: filelock in /usr/local/lib/python3.6/dist-packages (from transformers>=2.7.0->t5->trax==1.3.4) (3.0.12)\n    Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.6/dist-packages (from transformers>=2.7.0->t5->trax==1.3.4) (2019.12.20)\n    Collecting tokenizers==0.9.4\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/0f/1c/e789a8b12e28be5bc1ce2156cf87cb522b379be9cadc7ad8091a4cc107c4/tokenizers-0.9.4-cp36-cp36m-manylinux2010_x86_64.whl (2.9MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.9MB 38.6MB/s \n    \u001b[?25hCollecting sacremoses\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/7d/34/09d19aff26edcc8eb2a01bed8e98f13a1537005d31e95233fd48216eed10/sacremoses-0.0.43.tar.gz (883kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 890kB 42.0MB/s \n    \u001b[?25hCollecting portalocker\n      Downloading https://files.pythonhosted.org/packages/89/a6/3814b7107e0788040870e8825eebf214d72166adf656ba7d4bf14759a06a/portalocker-2.0.0-py2.py3-none-any.whl\n    Requirement already satisfied: zipp>=0.4; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from importlib-resources; python_version < \"3.9\"->tensorflow-datasets->trax==1.3.4) (3.4.0)\n    Requirement already satisfied: googleapis-common-protos<2,>=1.52.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-metadata->tensorflow-datasets->trax==1.3.4) (1.52.0)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax==1.3.4) (1.7.0)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.6/dist-packages (from tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax==1.3.4) (0.4.2)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax==1.3.4) (3.3.3)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth>=1.4.1->google-api-python-client->tensor2tensor->trax==1.3.4) (4.1.1)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.6/dist-packages (from Jinja2>=2.10.1->flask->tensor2tensor->trax==1.3.4) (1.1.1)\n    Requirement already satisfied: pyparsing>=2.0.2 in /usr/local/lib/python3.6/dist-packages (from packaging->transformers>=2.7.0->t5->trax==1.3.4) (2.4.7)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax==1.3.4) (1.3.0)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from markdown>=2.6.8->tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax==1.3.4) (2.0.0)\n    Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax==1.3.4) (3.1.0)\n    Building wheels for collected packages: bz2file, pypng, sacremoses\n      Building wheel for bz2file (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for bz2file: filename=bz2file-0.98-cp36-none-any.whl size=6884 sha256=b85eb30b392f06402f85ea23f26e206f1ef35e916eb7147e15d3e712accd0f8e\n      Stored in directory: /root/.cache/pip/wheels/81/75/d6/e1317bf09bf1af5a30befc2a007869fa6e1f516b8f7c591cb9\n      Building wheel for pypng (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pypng: filename=pypng-0.0.20-cp36-none-any.whl size=67162 sha256=fe026c7c03161c9b180c990edccb00dc779141f5d75435ca52e333368a0e2e4f\n      Stored in directory: /root/.cache/pip/wheels/41/6b/ef/0493b536b6d4722c2ae9486691b1d49b922b9877922beeabb3\n      Building wheel for sacremoses (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for sacremoses: filename=sacremoses-0.0.43-cp36-none-any.whl size=893257 sha256=88ce58e0e86a70cafcffd0ce134057988fa9388138c81c4513dc7ac51d411db8\n      Stored in directory: /root/.cache/pip/wheels/29/3c/fd/7ce5c3f0666dab31a50123635e6fb5e19ceb42ce38d4e58f45\n    Successfully built bz2file pypng sacremoses\n    \u001b[31mERROR: kfac 0.2.3 has requirement tensorflow-probability==0.8, but you'll have tensorflow-probability 0.7.0 which is incompatible.\u001b[0m\n    Installing collected packages: tensorflow-text, tf-slim, bz2file, gunicorn, mesh-tensorflow, zope.interface, zope.event, greenlet, gevent, tensorflow-probability, kfac, pypng, tensorflow-gan, tensor2tensor, sentencepiece, tokenizers, sacremoses, transformers, portalocker, sacrebleu, tfds-nightly, rouge-score, t5, funcsigs, trax\n      Found existing installation: tensorflow-probability 0.11.0\n        Uninstalling tensorflow-probability-0.11.0:\n          Successfully uninstalled tensorflow-probability-0.11.0\n    Successfully installed bz2file-0.98 funcsigs-1.0.2 gevent-20.9.0 greenlet-0.4.17 gunicorn-20.0.4 kfac-0.2.3 mesh-tensorflow-0.1.17 portalocker-2.0.0 pypng-0.0.20 rouge-score-0.0.4 sacrebleu-1.4.14 sacremoses-0.0.43 sentencepiece-0.1.94 t5-0.7.1 tensor2tensor-1.15.7 tensorflow-gan-2.0.0 tensorflow-probability-0.7.0 tensorflow-text-2.3.0 tf-slim-1.1.0 tfds-nightly-4.1.0.dev202012070108 tokenizers-0.9.4 transformers-4.0.0 trax-1.3.4 zope.event-4.5.0 zope.interface-5.2.0\n    trax                          1.3.4                \n\n\nNext, we will import the dataset we will use to train the model. To meet the storage constraints in this lab environment, we will just use a small dataset from [Opus](http://opus.nlpl.eu/), a growing collection of translated texts from the web. Particularly, we will get an English to German translation subset specified as `opus/medical` which has medical related texts. If storage is not an issue, you can opt to get a larger corpus such as the English to German translation dataset from [ParaCrawl](https://paracrawl.eu/), a large multi-lingual translation dataset created by the European Union. Both of these datasets are available via [Tensorflow Datasets (TFDS)](https://www.tensorflow.org/datasets)\nand you can browse through the other available datasets [here](https://www.tensorflow.org/datasets/catalog/overview). We have downloaded the data for you in the `data/` directory of your workspace. As you'll see below, you can easily access this dataset from TFDS with `trax.data.TFDS`. The result is a python generator function yielding tuples. Use the `keys` argument to select what appears at which position in the tuple. For example, `keys=('en', 'de')` below will return pairs as (English sentence, German sentence).  \n\n\n```python\n# Get generator function for the training set\n# This will download the train dataset if no data_dir is specified.\ntrain_stream_fn = trax.data.TFDS('opus/medical',\n                                 data_dir='./data/',\n                                 keys=('en', 'de'),\n                                 eval_holdout_size=0.01, # 1% for eval\n                                 train=True)\n\n# Get generator function for the eval set\neval_stream_fn = trax.data.TFDS('opus/medical',\n                                data_dir='./data/',\n                                keys=('en', 'de'),\n                                eval_holdout_size=0.01, # 1% for eval\n                                train=False)\n```\n\n    \u001b[1mDownloading and preparing dataset opus/medical/0.1.0 (download: 34.29 MiB, generated: 188.85 MiB, total: 223.13 MiB) to ./data/opus/medical/0.1.0...\u001b[0m\n\n\n\n    HBox(children=(FloatProgress(value=1.0, bar_style='info', description='Dl Completed...', max=1.0, style=Progre\u2026\n\n\n\n    HBox(children=(FloatProgress(value=1.0, bar_style='info', description='Dl Size...', max=1.0, style=ProgressSty\u2026\n\n\n\n    HBox(children=(FloatProgress(value=1.0, bar_style='info', description='Extraction completed...', max=1.0, styl\u2026\n\n\n    \n    \n    \n    \n    \n    \n\n\n\n    HBox(children=(FloatProgress(value=0.0, max=1.0), HTML(value='')))\n\n\n\n    HBox(children=(FloatProgress(value=0.0, max=1108752.0), HTML(value='')))\n\n\n    Shuffling and writing examples to data/opus/medical/0.1.0.incompleteIPVGDM/opus-train.tfrecord\n\n\n\n    HBox(children=(FloatProgress(value=0.0, max=1108752.0), HTML(value='')))\n\n\n    \u001b[1mDataset opus downloaded and prepared to ./data/opus/medical/0.1.0. Subsequent calls will reuse this data.\u001b[0m\n\n\nNotice that TFDS returns a generator *function*, not a generator. This is because in Python, you cannot reset generators so you cannot go back to a previously yielded value. During deep learning training, you use Stochastic Gradient Descent and don't actually need to go back -- but it is sometimes good to be able to do that, and that's where the functions come in. It is actually very common to use generator functions in Python -- e.g., `zip` is a generator function. You can read more about [Python generators](https://book.pythontips.com/en/latest/generators.html) to understand why we use them. Let's print a a sample pair from our train and eval data. Notice that the raw ouput is represented in bytes (denoted by the `b'` prefix) and these will be converted to strings internally in the next steps.\n\n\n```python\ntrain_stream = train_stream_fn()\nprint(colored('train data (en, de) tuple:', 'red'), next(train_stream))\nprint()\n\neval_stream = eval_stream_fn()\nprint(colored('eval data (en, de) tuple:', 'red'), next(eval_stream))\n```\n\n    \u001b[31mtrain data (en, de) tuple:\u001b[0m (b'Tel: +421 2 57 103 777\\n', b'Tel: +421 2 57 103 777\\n')\n    \n    \u001b[31meval data (en, de) tuple:\u001b[0m (b'Lutropin alfa Subcutaneous use.\\n', b'Pulver zur Injektion Lutropin alfa Subkutane Anwendung\\n')\n\n\n<a name=\"1.2\"></a>\n## 1.2  Tokenization and Formatting\n\nNow that we have imported our corpus, we will be preprocessing the sentences into a format that our model can accept. This will be composed of several steps:\n\n**Tokenizing the sentences using subword representations:** As you've learned in the earlier courses of this specialization, we want to represent each sentence as an array of integers instead of strings. For our application, we will use *subword* representations to tokenize our sentences. This is a common technique to avoid out-of-vocabulary words by allowing parts of words to be represented separately. For example, instead of having separate entries in your vocabulary for --\"fear\", \"fearless\", \"fearsome\", \"some\", and \"less\"--, you can simply store --\"fear\", \"some\", and \"less\"-- then allow your tokenizer to combine these subwords when needed. This allows it to be more flexible so you won't have to save uncommon words explicitly in your vocabulary (e.g. *stylebender*, *nonce*, etc). Tokenizing is done with the `trax.data.Tokenize()` command and we have provided you the combined subword vocabulary for English and German (i.e. `ende_32k.subword`) saved in the `data` directory. Feel free to open this file to see how the subwords look like.\n\n\n```python\n# global variables that state the filename and directory of the vocabulary file\nVOCAB_FILE = 'ende_32k.subword'\nVOCAB_DIR = 'data/'\n\n# Tokenize the dataset.\ntokenized_train_stream = trax.data.Tokenize(vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR)(train_stream)\ntokenized_eval_stream = trax.data.Tokenize(vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR)(eval_stream)\n```\n\n**Append an end-of-sentence token to each sentence:** We will assign a token (i.e. in this case `1`) to mark the end of a sentence. This will be useful in inference/prediction so we'll know that the model has completed the translation.\n\n\n```python\n# Append EOS at the end of each sentence.\n\n# Integer assigned as end-of-sentence (EOS)\nEOS = 1\n\n# generator helper function to append EOS to each sentence\ndef append_eos(stream):\n    for (inputs, targets) in stream:\n        inputs_with_eos = list(inputs) + [EOS]\n        targets_with_eos = list(targets) + [EOS]\n        yield np.array(inputs_with_eos), np.array(targets_with_eos)\n\n# append EOS to the train data\ntokenized_train_stream = append_eos(tokenized_train_stream)\n\n# append EOS to the eval data\ntokenized_eval_stream = append_eos(tokenized_eval_stream)\n```\n\n**Filter long sentences:** We will place a limit on the number of tokens per sentence to ensure we won't run out of memory. This is done with the `trax.data.FilterByLength()` method and you can see its syntax below.\n\n\n```python\n# Filter too long sentences to not run out of memory.\n# length_keys=[0, 1] means we filter both English and German sentences, so\n# both much be not longer that 256 tokens for training / 512 for eval.\nfiltered_train_stream = trax.data.FilterByLength(\n    max_length=256, length_keys=[0, 1])(tokenized_train_stream)\nfiltered_eval_stream = trax.data.FilterByLength(\n    max_length=512, length_keys=[0, 1])(tokenized_eval_stream)\n\n# print a sample input-target pair of tokenized sentences\ntrain_input, train_target = next(filtered_train_stream)\nprint(colored(f'Single tokenized example input:', 'red' ), train_input)\nprint(colored(f'Single tokenized example target:', 'red'), train_target)\n```\n\n    \u001b[31mSingle tokenized example input:\u001b[0m [ 2538  2248    30 12114 23184 16889     5     2 20852  6456 20592  5812\n      3932    96  5178  3851    30  7891  3550 30650  4729   992     1]\n    \u001b[31mSingle tokenized example target:\u001b[0m [ 1872    11  3544    39  7019 17877 30432    23  6845    10 14222    47\n      4004    18 21674     5 27467  9513   920   188 10630    18  3550 30650\n      4729   992     1]\n\n\n<a name=\"1.3\"></a>\n## 1.3  tokenize & detokenize helper functions\n\nGiven any data set, you have to be able to map words to their indices, and indices to their words. The inputs and outputs to your trax models are usually tensors of numbers where each number corresponds to a word. If you were to process your data manually, you would have to make use of the following: \n\n- <span style='color:blue'> word2Ind: </span> a dictionary mapping the word to its index.\n- <span style='color:blue'> ind2Word:</span> a dictionary mapping the index to its word.\n- <span style='color:blue'> word2Count:</span> a dictionary mapping the word to the number of times it appears. \n- <span style='color:blue'> num_words:</span> total number of words that have appeared. \n\nSince you have already implemented these in previous assignments of the specialization, we will provide you with helper functions that will do this for you. Run the cell below to get the following functions:\n\n- <span style='color:blue'> tokenize(): </span> converts a text sentence to its corresponding token list (i.e. list of indices). Also converts words to subwords (parts of words).\n- <span style='color:blue'> detokenize(): </span> converts a token list to its corresponding sentence (i.e. string).\n\n\n```python\n# Setup helper functions for tokenizing and detokenizing sentences\n\ndef tokenize(input_str, vocab_file=None, vocab_dir=None):\n    \"\"\"Encodes a string to an array of integers\n\n    Args:\n        input_str (str): human-readable string to encode\n        vocab_file (str): filename of the vocabulary text file\n        vocab_dir (str): path to the vocabulary file\n  \n    Returns:\n        numpy.ndarray: tokenized version of the input string\n    \"\"\"\n    \n    # Set the encoding of the \"end of sentence\" as 1\n    EOS = 1\n    \n    # Use the trax.data.tokenize method. It takes streams and returns streams,\n    # we get around it by making a 1-element stream with `iter`.\n    inputs =  next(trax.data.tokenize(iter([input_str]),\n                                      vocab_file=vocab_file, vocab_dir=vocab_dir))\n    \n    # Mark the end of the sentence with EOS\n    inputs = list(inputs) + [EOS]\n    \n    # Adding the batch dimension to the front of the shape\n    batch_inputs = np.reshape(np.array(inputs), [1, -1])\n    \n    return batch_inputs\n\n\ndef detokenize(integers, vocab_file=None, vocab_dir=None):\n    \"\"\"Decodes an array of integers to a human readable string\n\n    Args:\n        integers (numpy.ndarray): array of integers to decode\n        vocab_file (str): filename of the vocabulary text file\n        vocab_dir (str): path to the vocabulary file\n  \n    Returns:\n        str: the decoded sentence.\n    \"\"\"\n    \n    # Remove the dimensions of size 1\n    integers = list(np.squeeze(integers))\n    \n    # Set the encoding of the \"end of sentence\" as 1\n    EOS = 1\n    \n    # Remove the EOS to decode only the original tokens\n    if EOS in integers:\n        integers = integers[:integers.index(EOS)] \n    \n    return trax.data.detokenize(integers, vocab_file=vocab_file, vocab_dir=vocab_dir)\n```\n\nLet's see how we might use these functions:\n\n\n```python\n# As declared earlier:\n# VOCAB_FILE = 'ende_32k.subword'\n# VOCAB_DIR = 'data/'\n\n# Detokenize an input-target pair of tokenized sentences\nprint(colored(f'Single detokenized example input:', 'red'), detokenize(train_input, vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR))\nprint(colored(f'Single detokenized example target:', 'red'), detokenize(train_target, vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR))\nprint()\n\n# Tokenize and detokenize a word that is not explicitly saved in the vocabulary file.\n# See how it combines the subwords -- 'hell' and 'o'-- to form the word 'hello'.\nprint(colored(f\"tokenize('hello'): \", 'green'), tokenize('hello', vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR))\nprint(colored(f\"detokenize([17332, 140, 1]): \", 'green'), detokenize([17332, 140, 1], vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR))\n```\n\n    \u001b[31mSingle detokenized example input:\u001b[0m During treatment with olanzapine, adolescents gained significantly more weight compared with adults.\n    \n    \u001b[31mSingle detokenized example target:\u001b[0m W\u00e4hrend der Behandlung mit Olanzapin nahmen die Jugendlichen im Vergleich zu Erwachsenen signifikant mehr Gewicht zu.\n    \n    \n    \u001b[32mtokenize('hello'): \u001b[0m [[17332   140     1]]\n    \u001b[32mdetokenize([17332, 140, 1]): \u001b[0m hello\n\n\n<a name=\"1.4\"></a>\n## 1.4  Bucketing\n\nBucketing the tokenized sentences is an important technique used to speed up training in NLP.\nHere is a \n[nice article describing it in detail](https://medium.com/@rashmi.margani/how-to-speed-up-the-training-of-the-sequence-model-using-bucketing-techniques-9e302b0fd976)\nbut the gist is very simple. Our inputs have variable lengths and you want to make these the same when batching groups of sentences together. One way to do that is to pad each sentence to the length of the longest sentence in the dataset. This might lead to some wasted computation though. For example, if there are multiple short sentences with just two tokens, do we want to pad these when the longest sentence is composed of a 100 tokens? Instead of padding with 0s to the maximum length of a sentence each time, we can group our tokenized sentences by length and bucket, as on this image (from the article above):\n\n\n\nWe batch the sentences with similar length together (e.g. the blue sentences in the image above) and only add minimal padding to make them have equal length (usually up to the nearest power of two). This allows to waste less computation when processing padded sequences.\nIn Trax, it is implemented in the [bucket_by_length](https://github.com/google/trax/blob/5fb8aa8c5cb86dabb2338938c745996d5d87d996/trax/supervised/inputs.py#L378) function.\n\n\n```python\n# Bucketing to create streams of batches.\n\n# Buckets are defined in terms of boundaries and batch sizes.\n# Batch_sizes[i] determines the batch size for items with length < boundaries[i]\n# So below, we'll take a batch of 256 sentences of length < 8, 128 if length is\n# between 8 and 16, and so on -- and only 2 if length is over 512.\nboundaries =  [8,   16,  32, 64, 128, 256, 512]\nbatch_sizes = [256, 128, 64, 32, 16,    8,   4,  2]\n\n# Create the generators.\ntrain_batch_stream = trax.data.BucketByLength(\n    boundaries, batch_sizes,\n    length_keys=[0, 1]  # As before: count inputs and targets to length.\n)(filtered_train_stream)\n\neval_batch_stream = trax.data.BucketByLength(\n    boundaries, batch_sizes,\n    length_keys=[0, 1]  # As before: count inputs and targets to length.\n)(filtered_eval_stream)\n\n# Add masking for the padding (0s).\ntrain_batch_stream = trax.data.AddLossWeights(id_to_mask=0)(train_batch_stream)\neval_batch_stream = trax.data.AddLossWeights(id_to_mask=0)(eval_batch_stream)\n```\n\n<a name=\"1.5\"></a>\n## 1.5  Exploring the data\n\nWe will now be displaying some of our data. You will see that the functions defined above (i.e. `tokenize()` and `detokenize()`) do the same things you have been doing again and again throughout the specialization. We gave these so you can focus more on building the model from scratch. Let us first get the data generator and get one batch of the data.\n\n\n```python\ninput_batch, target_batch, mask_batch = next(train_batch_stream)\n\n# let's see the data type of a batch\nprint(\"input_batch data type: \", type(input_batch))\nprint(\"target_batch data type: \", type(target_batch))\n\n# let's see the shape of this particular batch (batch length, sentence length)\nprint(\"input_batch shape: \", input_batch.shape)\nprint(\"target_batch shape: \", target_batch.shape)\n```\n\n    input_batch data type:  <class 'numpy.ndarray'>\n    target_batch data type:  <class 'numpy.ndarray'>\n    input_batch shape:  (32, 64)\n    target_batch shape:  (32, 64)\n\n\nThe `input_batch` and `target_batch` are Numpy arrays consisting of tokenized English sentences and German sentences respectively. These tokens will later be used to produce embedding vectors for each word in the sentence (so the embedding for a sentence will be a matrix). The number of sentences in each batch is usually a power of 2 for optimal computer memory usage. \n\nWe can now visually inspect some of the data. You can run the cell below several times to shuffle through the sentences. Just to note, while this is a standard data set that is used widely, it does have some known wrong translations. With that, let's pick a random sentence and print its tokenized representation.\n\n\n```python\n# pick a random index less than the batch size.\nindex = random.randrange(len(input_batch))\n\n# use the index to grab an entry from the input and target batch\nprint(colored('THIS IS THE ENGLISH SENTENCE: \\n', 'red'), detokenize(input_batch[index], vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR), '\\n')\nprint(colored('THIS IS THE TOKENIZED VERSION OF THE ENGLISH SENTENCE: \\n ', 'red'), input_batch[index], '\\n')\nprint(colored('THIS IS THE GERMAN TRANSLATION: \\n', 'red'), detokenize(target_batch[index], vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR), '\\n')\nprint(colored('THIS IS THE TOKENIZED VERSION OF THE GERMAN TRANSLATION: \\n', 'red'), target_batch[index], '\\n')\n```\n\n    \u001b[31mTHIS IS THE ENGLISH SENTENCE: \n    \u001b[0m Signs of hypersensitivity reactions include hives, generalised urticaria, tightness of the chest, wheezing, hypotension and anaphylaxis.\n     \n    \n    \u001b[31mTHIS IS THE TOKENIZED VERSION OF THE ENGLISH SENTENCE: \n     \u001b[0m [10495    14     7 10224 19366 10991  1020  3481  2486     2  9547  7417\n       103  4572 11927  9371     2 13197  1496     7     4 24489    62     2\n     16402 24010   211     2  4814 23010 12122    22     8  4867 19606  6457\n      5175    14  3550 30650  4729   992     1     0     0     0     0     0\n         0     0     0     0     0     0     0     0     0     0     0     0\n         0     0     0     0] \n    \n    \u001b[31mTHIS IS THE GERMAN TRANSLATION: \n    \u001b[0m \u00dcberempfindlichkeitsreaktionen k\u00f6nnen sich durch Anzeichen wie Nesselausschlag, generalisierte Urtikaria, Engegef\u00fchl im Brustkorb, Pfeifatmung, Blutdruckabfall und Anaphylaxie \u00e4u\u00dfern.\n     \n    \n    \u001b[31mTHIS IS THE TOKENIZED VERSION OF THE GERMAN TRANSLATION: \n    \u001b[0m [ 3916 29551 13504  5020  4094 13522   119    51   121  8602    93 31508\n      6050 30327  6978     2  9547  7417  2446  5618  4581  5530  1384     2\n     26006  7831 13651     5    47  8584  4076  5262   868     2 25389  8898\n     28268     2  9208 29697 17944    83    12  9925 19606  6457 16384     5\n     11790  3550 30650  4729   992     1     0     0     0     0     0     0\n         0     0     0     0] \n    \n\n\n<a name=\"2\"></a>\n# Part 2:  Neural Machine Translation with Attention\n\nNow that you have the data generators and have handled the preprocessing, it is time for you to build the model. You will be implementing a neural machine translation model from scratch with attention.\n\n\n<a name=\"2.1\"></a>\n## 2.1  Attention Overview\n\nThe model we will be building uses an encoder-decoder architecture. This Recurrent Neural Network (RNN) will take in a tokenized version of a sentence in its encoder, then passes it on to the decoder for translation. As mentioned in the lectures, just using a a regular sequence-to-sequence model with LSTMs will work effectively for short to medium sentences but will start to degrade for longer ones. You can picture it like the figure below where all of the context of the input sentence is compressed into one vector that is passed into the decoder block. You can see how this will be an issue for very long sentences (e.g. 100 tokens or more) because the context of the first parts of the input will have very little effect on the final vector passed to the decoder.\n\n\n\nAdding an attention layer to this model avoids this problem by giving the decoder access to all parts of the input sentence. To illustrate, let's just use a 4-word input sentence as shown below. Remember that a hidden state is produced at each timestep of the encoder (represented by the orange rectangles). These are all passed to the attention layer and each are given a score given the current activation (i.e. hidden state) of the decoder. For instance, let's consider the figure below where the first prediction \"Wie\" is already made. To produce the next prediction, the attention layer will first receive all the encoder hidden states (i.e. orange rectangles) as well as the decoder hidden state when producing the word \"Wie\" (i.e. first green rectangle). Given these information, it will score each of the encoder hidden states to know which one the decoder should focus on to produce the next word. The result of the model training might have learned that it should align to the second encoder hidden state and subsequently assigns a high probability to the word \"geht\". If we are using greedy decoding, we will output the said word as the next symbol, then restart the process to produce the next word until we reach an end-of-sentence prediction.\n\n\n\n\nThere are different ways to implement attention and the one we'll use for this assignment is the Scaled Dot Product Attention which has the form:\n\n$$Attention(Q, K, V) = softmax(\\frac{QK^T}{\\sqrt{d_k}})V$$\n\nYou will dive deeper into this equation in the next week but for now, you can think of it as computing scores using queries (Q) and keys (K), followed by a multiplication of values (V) to get a context vector at a particular timestep of the decoder. This context vector is fed to the decoder RNN to get a set of probabilities for the next predicted word. The division by square root of the keys dimensionality ($\\sqrt{d_k}$) is for improving model performance and you'll also learn more about it next week. For our machine translation application, the encoder activations (i.e. encoder hidden states) will be the keys and values, while the decoder activations (i.e. decoder hidden states) will be the queries.\n\nYou will see in the upcoming sections that this complex architecture and mechanism can be implemented with just a few lines of code. Let's get started!\n\n<a name=\"2.2\"></a>\n## 2.2  Helper functions\n\nWe will first implement a few functions that we will use later on. These will be for the input encoder, pre-attention decoder, and preparation of the queries, keys, values, and mask.\n\n### 2.2.1 Input encoder\n\nThe input encoder runs on the input tokens, creates its embeddings, and feeds it to an LSTM network. This outputs the activations that will be the keys and values for attention. It is a [Serial](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.combinators.Serial) network which uses:\n\n   - [tl.Embedding](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.core.Embedding): Converts each token to its vector representation. In this case, it is the the size of the vocabulary by the dimension of the model: `tl.Embedding(vocab_size, d_model)`. `vocab_size` is the number of entries in the given vocabulary. `d_model` is the number of elements in the word embedding.\n  \n   - [tl.LSTM](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.rnn.LSTM): LSTM layer of size `d_model`. We want to be able to configure how many encoder layers we have so remember to create LSTM layers equal to the number of the `n_encoder_layers` parameter.\n   \n\n\n<a name=\"ex01\"></a>\n### Exercise 01\n\n**Instructions:** Implement the `input_encoder_fn` function.\n\n\n```python\n# UNQ_C1\n# GRADED FUNCTION\ndef input_encoder_fn(input_vocab_size, d_model, n_encoder_layers):\n    \"\"\" Input encoder runs on the input sentence and creates\n    activations that will be the keys and values for attention.\n    \n    Args:\n        input_vocab_size: int: vocab size of the input\n        d_model: int:  depth of embedding (n_units in the LSTM cell)\n        n_encoder_layers: int: number of LSTM layers in the encoder\n    Returns:\n        tl.Serial: The input encoder\n    \"\"\"\n    \n    # create a serial network\n    input_encoder = tl.Serial( \n        \n        ### START CODE HERE (REPLACE INSTANCES OF `None` WITH YOUR CODE) ###\n        # create an embedding layer to convert tokens to vectors\n        tl.Embedding(input_vocab_size,d_model),\n        \n        # feed the embeddings to the LSTM layers. It is a stack of n_encoder_layers LSTM layers\n        [tl.LSTM(d_model) for _ in range(n_encoder_layers)]\n        ### END CODE HERE ###\n    )\n\n    return input_encoder\n```\n\n*Note: To make this notebook more neat, we moved the unit tests to a separate file called `w1_unittest.py`. Feel free to open it from your workspace if needed. We have placed comments in that file to indicate which functions are testing which part of the assignment (e.g. `test_input_encoder_fn()` has the unit tests for UNQ_C1).*\n\n\n```python\n# BEGIN UNIT TEST\nimport w1_unittest\n\nw1_unittest.test_input_encoder_fn(input_encoder_fn)\n# END UNIT TEST\n```\n\n    \u001b[92m All tests passed\n\n\n### 2.2.2 Pre-attention decoder\n\nThe pre-attention decoder runs on the targets and creates activations that are used as queries in attention. This is a Serial network which is composed of the following:\n\n   - [tl.ShiftRight](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.attention.ShiftRight): This pads a token to the beginning of your target tokens (e.g. `[8, 34, 12]` shifted right is `[0, 8, 34, 12]`). This will act like a start-of-sentence token that will be the first input to the decoder. During training, this shift also allows the target tokens to be passed as input to do teacher forcing.\n\n   - [tl.Embedding](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.core.Embedding): Like in the previous function, this converts each token to its vector representation. In this case, it is the the size of the vocabulary by the dimension of the model: `tl.Embedding(vocab_size, d_model)`. `vocab_size` is the number of entries in the given vocabulary. `d_model` is the number of elements in the word embedding.\n   \n   - [tl.LSTM](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.rnn.LSTM): LSTM layer of size `d_model`.\n\n\n\n<a name=\"ex02\"></a>\n### Exercise 02\n\n**Instructions:** Implement the `pre_attention_decoder_fn` function.\n\n\n\n```python\n# UNQ_C2\n# GRADED FUNCTION\ndef pre_attention_decoder_fn(mode, target_vocab_size, d_model):\n    \"\"\" Pre-attention decoder runs on the targets and creates\n    activations that are used as queries in attention.\n    \n    Args:\n        mode: str: 'train' or 'eval'\n        target_vocab_size: int: vocab size of the target\n        d_model: int:  depth of embedding (n_units in the LSTM cell)\n    Returns:\n        tl.Serial: The pre-attention decoder\n    \"\"\"\n    \n    # create a serial network\n    pre_attention_decoder = tl.Serial(\n        \n        ### START CODE HERE (REPLACE INSTANCES OF `None` WITH YOUR CODE) ###\n        # shift right to insert start-of-sentence token and implement\n        # teacher forcing during training\n        tl.ShiftRight(mode=mode),\n\n        # run an embedding layer to convert tokens to vectors\n        tl.Embedding(target_vocab_size,d_model),\n\n        # feed to an LSTM layer\n        tl.LSTM(d_model)\n        ### END CODE HERE ###\n    )\n    \n    return pre_attention_decoder\n```\n\n\n```python\n# BEGIN UNIT TEST\n\nw1_unittest.test_pre_attention_decoder_fn(pre_attention_decoder_fn)\n\n# END UNIT TEST\n```\n\n    \u001b[92m All tests passed\n\n\n### 2.2.3 Preparing the attention input\n\nThis function will prepare the inputs to the attention layer. We want to take in the encoder and pre-attention decoder activations and assign it to the queries, keys, and values. In addition, another output here will be the mask to distinguish real tokens from padding tokens. This mask will be used internally by Trax when computing the softmax so padding tokens will not have an effect on the computated probabilities. From the data preparation steps in Section 1 of this assignment, you should know which tokens in the input correspond to padding.\n\nWe have filled the last two lines in composing the mask for you because it includes a concept that will be discussed further next week. This is related to *multiheaded attention* which you can think of right now as computing the attention multiple times to improve the model's predictions. It is required to consider this additional axis in the output so we've included it already but you don't need to analyze it just yet. What's important now is for you to know which should be the queries, keys, and values, as well as to initialize the mask.\n\n<a name=\"ex03\"></a>\n### Exercise 03\n\n**Instructions:** Implement the  `prepare_attention_input` function\n\n\n\n```python\n# UNQ_C3\n# GRADED FUNCTION\ndef prepare_attention_input(encoder_activations, decoder_activations, inputs):\n    \"\"\"Prepare queries, keys, values and mask for attention.\n    \n    Args:\n        encoder_activations fastnp.array(batch_size, padded_input_length, d_model): output from the input encoder\n        decoder_activations fastnp.array(batch_size, padded_input_length, d_model): output from the pre-attention decoder\n        inputs fastnp.array(batch_size, padded_input_length): padded input tokens\n    \n    Returns:\n        queries, keys, values and mask for attention.\n    \"\"\"\n    \n    ### START CODE HERE (REPLACE INSTANCES OF `None` WITH YOUR CODE) ###\n    \n    # set the keys and values to the encoder activations\n    keys = encoder_activations\n    values = encoder_activations\n\n    \n    # set the queries to the decoder activations\n    queries = decoder_activations\n    \n    # generate the mask to distinguish real tokens from padding\n    # hint: inputs is 1 for real tokens and 0 where they are padding\n    mask = inputs > 0\n    \n    ### END CODE HERE ###\n    \n    # add axes to the mask for attention heads and decoder length.\n  \n    mask = fastnp.reshape(mask, (mask.shape[0], 1, 1, mask.shape[1]))\n    \n    # broadcast so mask shape is [batch size, attention heads, decoder-len, encoder-len].\n    # note: for this assignment, attention heads is set to 1.\n    mask = mask + fastnp.zeros((1, 1, decoder_activations.shape[1], 1))\n        \n    \n    return queries, keys, values, mask\n```\n\n\n```python\n# BEGIN UNIT TEST\nw1_unittest.test_prepare_attention_input(prepare_attention_input)\n# END UNIT TEST\n```\n\n    WARNING:absl:No GPU/TPU found, falling back to CPU. (Set TF_CPP_MIN_LOG_LEVEL=0 and rerun for more info.)\n\n\n    \u001b[92m All tests passed\n\n\n<a name=\"2.3\"></a>\n## 2.3  Implementation Overview\n\nWe are now ready to implement our sequence-to-sequence model with attention. This will be a Serial network and is illustrated in the diagram below. It shows the layers you'll be using in Trax and you'll see that each step can be implemented quite easily with one line commands. We've placed several links to the documentation for each relevant layer in the discussion after the figure below.\n\n\n\n<a name=\"ex04\"></a>\n### Exercise 04\n**Instructions:** Implement the `NMTAttn` function below to define your machine translation model which uses attention. We have left hyperlinks below pointing to the Trax documentation of the relevant layers. Remember to consult it to get tips on what parameters to pass.\n\n**Step 0:** Prepare the input encoder and pre-attention decoder branches. You have already defined this earlier as helper functions so it's just a matter of calling those functions and assigning it to variables.\n\n**Step 1:** Create a Serial network. This will stack the layers in the next steps one after the other. Like the earlier exercises, you can use [tl.Serial](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.combinators.Serial).\n\n**Step 2:** Make a copy of the input and target tokens. As you see in the diagram above, the input and target tokens will be fed into different layers of the model. You can use [tl.Select](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.combinators.Select) layer to create copies of these tokens. Arrange them as `[input tokens, target tokens, input tokens, target tokens]`.\n\n**Step 3:** Create a parallel branch to feed the input tokens to the `input_encoder` and the target tokens to the `pre_attention_decoder`. You can use [tl.Parallel](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.combinators.Parallel) to create these sublayers in parallel. Remember to pass the variables you defined in Step 0 as parameters to this layer.\n\n**Step 4:** Next, call the `prepare_attention_input` function to convert the encoder and pre-attention decoder activations to a format that the attention layer will accept. You can use [tl.Fn](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.base.Fn) to call this function. Note: Pass the `prepare_attention_input` function as the `f` parameter in `tl.Fn` without any arguments or parenthesis.\n\n**Step 5:** We will now feed the (queries, keys, values, and mask) to the [tl.AttentionQKV](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.attention.AttentionQKV) layer. This computes the scaled dot product attention and outputs the attention weights and mask. Take note that although it is a one liner, this layer is actually composed of a deep network made up of several branches. We'll show the implementation taken [here](https://github.com/google/trax/blob/master/trax/layers/attention.py#L61) to see the different layers used. \n\n```python\ndef AttentionQKV(d_feature, n_heads=1, dropout=0.0, mode='train'):\n  \"\"\"Returns a layer that maps (q, k, v, mask) to (activations, mask).\n\n  See `Attention` above for further context/details.\n\n  Args:\n    d_feature: Depth/dimensionality of feature embedding.\n    n_heads: Number of attention heads.\n    dropout: Probababilistic rate for internal dropout applied to attention\n        activations (based on query-key pairs) before dotting them with values.\n    mode: Either 'train' or 'eval'.\n  \"\"\"\n  return cb.Serial(\n      cb.Parallel(\n          core.Dense(d_feature),\n          core.Dense(d_feature),\n          core.Dense(d_feature),\n      ),\n      PureAttention(  # pylint: disable=no-value-for-parameter\n          n_heads=n_heads, dropout=dropout, mode=mode),\n      core.Dense(d_feature),\n  )\n```\n\nHaving deep layers pose the risk of vanishing gradients during training and we would want to mitigate that. To improve the ability of the network to learn, we can insert a [tl.Residual](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.combinators.Residual) layer to add the output of AttentionQKV with the `queries` input. You can do this in trax by simply nesting the `AttentionQKV` layer inside the `Residual` layer. The library will take care of branching and adding for you.\n\n**Step 6:** We will not need the mask for the model we're building so we can safely drop it. At this point in the network, the signal stack currently has `[attention activations, mask, target tokens]` and you can use [tl.Select](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.combinators.Select) to output just `[attention activations, target tokens]`.\n\n**Step 7:** We can now feed the attention weighted output to the LSTM decoder. We can stack multiple [tl.LSTM](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.rnn.LSTM) layers to improve the output so remember to append LSTMs equal to the number defined by `n_decoder_layers` parameter to the model.\n\n**Step 8:** We want to determine the probabilities of each subword in the vocabulary and you can set this up easily with a [tl.Dense](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.core.Dense) layer by making its size equal to the size of our vocabulary.\n\n**Step 9:** Normalize the output to log probabilities by passing the activations in Step 8 to a [tl.LogSoftmax](https://trax-ml.readthedocs.io/en/latest/trax.layers.html#trax.layers.core.LogSoftmax) layer.\n\n\n```python\n# UNQ_C4\n# GRADED FUNCTION\ndef NMTAttn(input_vocab_size=33300,\n            target_vocab_size=33300,\n            d_model=1024,\n            n_encoder_layers=2,\n            n_decoder_layers=2,\n            n_attention_heads=4,\n            attention_dropout=0.0,\n            mode='train'):\n    \"\"\"Returns an LSTM sequence-to-sequence model with attention.\n\n    The input to the model is a pair (input tokens, target tokens), e.g.,\n    an English sentence (tokenized) and its translation into German (tokenized).\n\n    Args:\n    input_vocab_size: int: vocab size of the input\n    target_vocab_size: int: vocab size of the target\n    d_model: int:  depth of embedding (n_units in the LSTM cell)\n    n_encoder_layers: int: number of LSTM layers in the encoder\n    n_decoder_layers: int: number of LSTM layers in the decoder after attention\n    n_attention_heads: int: number of attention heads\n    attention_dropout: float, dropout for the attention layer\n    mode: str: 'train', 'eval' or 'predict', predict mode is for fast inference\n\n    Returns:\n    A LSTM sequence-to-sequence model with attention.\n    \"\"\"\n\n    ### START CODE HERE (REPLACE INSTANCES OF `None` WITH YOUR CODE) ###\n    \n    # Step 0: call the helper function to create layers for the input encoder\n    input_encoder = input_encoder_fn(input_vocab_size=input_vocab_size,d_model = d_model,n_encoder_layers=n_encoder_layers)\n\n    # Step 0: call the helper function to create layers for the pre-attention decoder\n    pre_attention_decoder = pre_attention_decoder_fn(mode=mode,target_vocab_size=target_vocab_size,d_model=d_model)\n\n    # Step 1: create a serial network\n    model = tl.Serial( \n        \n      # Step 2: copy input tokens and target tokens as they will be needed later.\n      tl.Select([0,1,0,1]),\n        \n      # Step 3: run input encoder on the input and pre-attention decoder the target.\n      tl.Parallel(input_encoder, pre_attention_decoder),\n        \n      # Step 4: prepare queries, keys, values and mask for attention.\n      tl.Fn('PrepareAttentionInput', prepare_attention_input, n_out=4),\n        \n      # Step 5: run the AttentionQKV layer\n      # nest it inside a Residual layer to add to the pre-attention decoder activations(i.e. queries)\n      tl.Residual(tl.AttentionQKV(d_model, n_heads=n_attention_heads, dropout=attention_dropout, mode=mode)),\n      \n      # Step 6: drop attention mask (i.e. index = None\n      tl.Select([0,2]),\n        \n      # Step 7: run the rest of the RNN decoder\n      [tl.LSTM(d_model) for _ in range(n_decoder_layers)],\n        \n      # Step 8: prepare output by making it the right size\n      tl.Dense(target_vocab_size),\n        \n      # Step 9: Log-softmax for output\n      tl.LogSoftmax()\n    )\n    \n    ### END CODE HERE\n    \n    return model\n```\n\n\n```python\n# BEGIN UNIT TEST\nw1_unittest.test_NMTAttn(NMTAttn)\n# END UNIT TEST\n```\n\n    \u001b[92m All tests passed\n\n\n\n```python\n# print your model\nmodel = NMTAttn()\nprint(model)\n```\n\n    Serial_in2_out2[\n      Select[0,1,0,1]_in2_out4\n      Parallel_in2_out2[\n        Serial[\n          Embedding_33300_1024\n          LSTM_1024\n          LSTM_1024\n        ]\n        Serial[\n          ShiftRight(1)\n          Embedding_33300_1024\n          LSTM_1024\n        ]\n      ]\n      PrepareAttentionInput_in3_out4\n      Serial_in4_out2[\n        Branch_in4_out3[\n          None\n          Serial_in4_out2[\n            Parallel_in3_out3[\n              Dense_1024\n              Dense_1024\n              Dense_1024\n            ]\n            PureAttention_in4_out2\n            Dense_1024\n          ]\n        ]\n        Add_in2\n      ]\n      Select[0,2]_in3_out2\n      LSTM_1024\n      LSTM_1024\n      Dense_33300\n      LogSoftmax\n    ]\n\n\n**Expected Output:**\n\n```\nSerial_in2_out2[\n  Select[0,1,0,1]_in2_out4\n  Parallel_in2_out2[\n    Serial[\n      Embedding_33300_1024\n      LSTM_1024\n      LSTM_1024\n    ]\n    Serial[\n      ShiftRight(1)\n      Embedding_33300_1024\n      LSTM_1024\n    ]\n  ]\n  PrepareAttentionInput_in3_out4\n  Serial_in4_out2[\n    Branch_in4_out3[\n      None\n      Serial_in4_out2[\n        Parallel_in3_out3[\n          Dense_1024\n          Dense_1024\n          Dense_1024\n        ]\n        PureAttention_in4_out2\n        Dense_1024\n      ]\n    ]\n    Add_in2\n  ]\n  Select[0,2]_in3_out2\n  LSTM_1024\n  LSTM_1024\n  Dense_33300\n  LogSoftmax\n]\n```\n\n<a name=\"3\"></a>\n# Part 3:  Training\n\nWe will now be training our model in this section. Doing supervised training in Trax is pretty straightforward (short example [here](https://trax-ml.readthedocs.io/en/latest/notebooks/trax_intro.html#Supervised-training)). We will be instantiating three classes for this: `TrainTask`, `EvalTask`, and `Loop`. Let's take a closer look at each of these in the sections below.\n\n\n<a name=\"3.1\"></a>\n## 3.1  TrainTask\n\nThe [TrainTask](https://trax-ml.readthedocs.io/en/latest/trax.supervised.html#trax.supervised.training.TrainTask) class allows us to define the labeled data to use for training and the feedback mechanisms to compute the loss and update the weights. \n\n<a name=\"ex05\"></a>\n### Exercise 05\n\n**Instructions:** Instantiate a train task.\n\n\n```python\n# UNQ_C5\n# GRADED \ntrain_task = training.TrainTask(\n    \n    ### START CODE HERE (REPLACE INSTANCES OF `None` WITH YOUR CODE) ###\n    \n    # use the train batch stream as labeled data\n    labeled_data=train_batch_stream ,\n    \n    # use the cross entropy loss\n    loss_layer= tl.CrossEntropyLoss(),\n    \n    # use the Adam optimizer with learning rate of 0.01\n    optimizer= trax.optimizers.Adam(0.01),\n    \n    # use the `trax.lr.warmup_and_rsqrt_decay` as the learning rate schedule\n    # have 1000 warmup steps with a max value of 0.01\n    lr_schedule=trax.lr.warmup_and_rsqrt_decay(1000,0.01) ,\n    \n    # have a checkpoint every 10 steps\n    n_steps_per_checkpoint= 10,\n    \n    ### END CODE HERE ###\n)\n```\n\n\n```python\n# BEGIN UNIT TEST\nw1_unittest.test_train_task(train_task)\n# END UNIT TEST\n```\n\n    \u001b[92m All tests passed\n\n\n<a name=\"3.2\"></a>\n## 3.2  EvalTask\n\nThe [EvalTask](https://trax-ml.readthedocs.io/en/latest/trax.supervised.html#trax.supervised.training.EvalTask) on the other hand allows us to see how the model is doing while training. For our application, we want it to report the cross entropy loss and accuracy.\n\n\n```python\neval_task = training.EvalTask(\n    \n    ## use the eval batch stream as labeled data\n    labeled_data=eval_batch_stream,\n    \n    ## use the cross entropy loss and accuracy as metrics\n    metrics=[tl.CrossEntropyLoss(), tl.Accuracy()],\n)\n```\n\n<a name=\"3.3\"></a>\n## 3.3  Loop\n\nThe [Loop](https://trax-ml.readthedocs.io/en/latest/trax.supervised.html#trax.supervised.training.Loop) class defines the model we will train as well as the train and eval tasks to execute. Its `run()` method allows us to execute the training for a specified number of steps.\n\n\n```python\n# define the output directory\noutput_dir = 'output_dir/'\n\n# remove old model if it exists. restarts training.\n!rm -f ~/output_dir/model.pkl.gz  \n\n# define the training loop\ntraining_loop = training.Loop(NMTAttn(mode='train'),\n                              train_task,\n                              eval_tasks=[eval_task],\n                              output_dir=output_dir)\n```\n\n\n```python\n# NOTE: Execute the training loop. This will take around 8 minutes to complete.\ntraining_loop.run(10)\n```\n\n    \n    Step      1: Ran 1 train steps in 179.41 secs\n    Step      1: train CrossEntropyLoss |  10.42908764\n    Step      1: eval  CrossEntropyLoss |  10.42619514\n    Step      1: eval          Accuracy |  0.00000000\n    \n    Step     10: Ran 9 train steps in 484.17 secs\n    Step     10: train CrossEntropyLoss |  10.25979996\n    Step     10: eval  CrossEntropyLoss |  9.97012901\n    Step     10: eval          Accuracy |  0.02429765\n\n\n<a name=\"4\"></a>\n# Part 4:  Testing\n\nWe will now be using the model you just trained to translate English sentences to German. We will implement this with two functions: The first allows you to identify the next symbol (i.e. output token). The second one takes care of combining the entire translated string.\n\nWe will start by first loading in a pre-trained copy of the model you just coded. Please run the cell below to do just that.\n\n\n```python\n# instantiate the model we built in eval mode\nmodel = NMTAttn(mode='eval')\n\n# initialize weights from a pre-trained model\nmodel.init_from_file(\"output_dir/model.pkl.gz\", weights_only=True)\nmodel = tl.Accelerate(model)\n```\n\n<a name=\"4.1\"></a>\n## 4.1  Decoding\n\nAs discussed in the lectures, there are several ways to get the next token when translating a sentence. For instance, we can just get the most probable token at each step (i.e. greedy decoding) or get a sample from a distribution. We can generalize the implementation of these two approaches by using the `tl.logsoftmax_sample()` method. Let's briefly look at its implementation:\n\n```python\ndef logsoftmax_sample(log_probs, temperature=1.0):  # pylint: disable=invalid-name\n  \"\"\"Returns a sample from a log-softmax output, with temperature.\n\n  Args:\n    log_probs: Logarithms of probabilities (often coming from LogSofmax)\n    temperature: For scaling before sampling (1.0 = default, 0.0 = pick argmax)\n  \"\"\"\n  # This is equivalent to sampling from a softmax with temperature.\n  u = np.random.uniform(low=1e-6, high=1.0 - 1e-6, size=log_probs.shape)\n  g = -np.log(-np.log(u))\n  return np.argmax(log_probs + g * temperature, axis=-1)\n```\n\nThe key things to take away here are: 1. it gets random samples with the same shape as your input (i.e. `log_probs`), and 2. the amount of \"noise\" added to the input by these random samples is scaled by a `temperature` setting. You'll notice that setting it to `0` will just make the return statement equal to getting the argmax of `log_probs`. This will come in handy later. \n\n<a name=\"ex06\"></a>\n### Exercise 06\n\n**Instructions:** Implement the `next_symbol()` function that takes in the `input_tokens` and the `cur_output_tokens`, then return the index of the next word. You can click below for hints in completing this exercise.\n\n<details>    \n<summary>\n    <font size=\"3\" color=\"darkgreen\"><b>Click Here for Hints</b></font>\n</summary>\n<p>\n<ul>\n    <li>To get the next power of two, you can compute <i>2^log_2(token_length + 1)</i> . We add 1 to avoid <i>log(0).</i></li>\n    <li>You can use <i>np.ceil()</i> to get the ceiling of a float.</li>\n    <li><i>np.log2()</i> will get the logarithm base 2 of a value</li>\n    <li><i>int()</i> will cast a value into an integer type</li>\n    <li>From the model diagram in part 2, you know that it takes two inputs. You can feed these with this syntax to get the model outputs: <i>model((input1, input2))</i>. It's up to you to determine which variables below to substitute for input1 and input2. Remember also from the diagram that the output has two elements: [log probabilities, target tokens]. You won't need the target tokens so we assigned it to _ below for you. </li>\n    <li> The log probabilities output will have the shape: (batch size, decoder length, vocab size). It will contain log probabilities for each token in the <i>cur_output_tokens</i> plus 1 for the start symbol introduced by the ShiftRight in the preattention decoder. For example, if cur_output_tokens is [1, 2, 5], the model will output an array of log probabilities each for tokens 0 (start symbol), 1, 2, and 5. To generate the next symbol, you just want to get the log probabilities associated with the last token (i.e. token 5 at index 3). You can slice the model output at [0, 3, :] to get this. It will be up to you to generalize this for any length of cur_output_tokens </li>\n</ul>\n\n\n\n```python\n# UNQ_C6\n# GRADED FUNCTION\ndef next_symbol(NMTAttn, input_tokens, cur_output_tokens, temperature):\n    \"\"\"Returns the index of the next token.\n\n    Args:\n        NMTAttn (tl.Serial): An LSTM sequence-to-sequence model with attention.\n        input_tokens (np.ndarray 1 x n_tokens): tokenized representation of the input sentence\n        cur_output_tokens (list): tokenized representation of previously translated words\n        temperature (float): parameter for sampling ranging from 0.0 to 1.0.\n            0.0: same as argmax, always pick the most probable token\n            1.0: sampling from the distribution (can sometimes say random things)\n\n    Returns:\n        int: index of the next token in the translated sentence\n        float: log probability of the next symbol\n    \"\"\"\n\n    ### START CODE HERE (REPLACE INSTANCES OF `None` WITH YOUR CODE) ###\n\n    # set the length of the current output tokens\n    token_length = len(cur_output_tokens)\n\n    # calculate next power of 2 for padding length \n    padded_length =  2**(int(np.ceil(np.log2(len(cur_output_tokens)+1)))) \n\n    # pad cur_output_tokens up to the padded_length\n    padded = cur_output_tokens + [0]*(padded_length-token_length)\n    \n    # model expects the output to have an axis for the batch size in front so\n    # convert `padded` list to a numpy array with shape (None, <padded_length>) where\n    # None is a placeholder for the batch size\n    padded_with_batch = np.reshape(padded,(1,len(padded)))\n\n    # get the model prediction (remember to use the `NMAttn` argument defined above)\n    output, _ = NMTAttn((input_tokens,padded_with_batch))\n    \n    # get log probabilities from the last token output\n    log_probs = output[0, token_length, :]\n\n    # get the next symbol by getting a logsoftmax sample (*hint: cast to an int)\n    symbol = tl.logsoftmax_sample(log_probs, temperature)\n    \n    ### END CODE HERE ###\n\n    return int(symbol), float(log_probs[symbol])\n\n\n```\n\n\n```python\n# BEGIN UNIT TEST\nw1_unittest.test_next_symbol(next_symbol, model)\n# END UNIT TEST\n```\n\n    Expected output:  [140, -0.000217437744]\n    \u001b[92m 1  Tests passed\n    \u001b[91m 1  Tests failed\n\n\nNow you will implement the `sampling_decode()` function. This will call the `next_symbol()` function above several times until the next output is the end-of-sentence token (i.e. `EOS`). It takes in an input string and returns the translated version of that string.\n\n<a name=\"ex07\"></a>\n### Exercise 07\n\n**Instructions**: Implement the `sampling_decode()` function.\n\n\n```python\n# UNQ_C7\n# GRADED FUNCTION\ndef sampling_decode(input_sentence, NMTAttn = None, temperature=0.0, vocab_file=None, vocab_dir=None):\n    \"\"\"Returns the translated sentence.\n\n    Args:\n        input_sentence (str): sentence to translate.\n        NMTAttn (tl.Serial): An LSTM sequence-to-sequence model with attention.\n        temperature (float): parameter for sampling ranging from 0.0 to 1.0.\n            0.0: same as argmax, always pick the most probable token\n            1.0: sampling from the distribution (can sometimes say random things)\n        vocab_file (str): filename of the vocabulary\n        vocab_dir (str): path to the vocabulary file\n\n    Returns:\n        tuple: (list, str, float)\n            list of int: tokenized version of the translated sentence\n            float: log probability of the translated sentence\n            str: the translated sentence\n    \"\"\"\n    \n    ### START CODE HERE (REPLACE INSTANCES OF `None` WITH YOUR CODE) ###\n    \n    # encode the input sentence\n    input_tokens =  tokenize(input_sentence, vocab_file=vocab_file, vocab_dir=vocab_dir)\n    \n    # initialize the list of output tokens\n    cur_output_tokens = []\n    \n    # initialize an integer that represents the current output index\n    cur_output = 0\n    \n    # Set the encoding of the \"end of sentence\" as 1\n    EOS = 1\n    \n    # check that the current output is not the end of sentence token\n    while cur_output != EOS and len(cur_output_tokens)<50:\n        \n        # update the current output token by getting the index of the next word (hint: use next_symbol)\n        cur_output, log_prob = next_symbol(NMTAttn,input_tokens,cur_output_tokens,temperature)\n        \n        # append the current output token to the list of output tokens\n        cur_output_tokens.append(cur_output)\n    \n    # detokenize the output tokens\n    sentence =  detokenize(cur_output_tokens, vocab_file=vocab_file, vocab_dir=vocab_dir)\n    \n    ### END CODE HERE ###\n    \n    return cur_output_tokens, log_prob, sentence\n\n\n```\n\n\n```python\n# Test the function above. Try varying the temperature setting with values from 0 to 1.\n# Run it several times with each setting and see how often the output changes.\nsampling_decode(\"I love languages.\", model, temperature=0.0, vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR)\n```\n\n\n\n\n    ([23306,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992,\n      992],\n     -9.078689575195312,\n     'mg;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;')\n\n\n\nWe have set a default value of `0` to the temperature setting in our implementation of `sampling_decode()` above. As you may have noticed in the `logsoftmax_sample()` method, this setting will ultimately result in greedy decoding. As mentioned in the lectures, this algorithm generates the translation by getting the most probable word at each step. It gets the argmax of the output array of your model and then returns that index. See the testing function and sample inputs below. You'll notice that the output will remain the same each time you run it.\n\n\n```python\ndef greedy_decode_test(sentence, NMTAttn=None, vocab_file=None, vocab_dir=None):\n    \"\"\"Prints the input and output of our NMTAttn model using greedy decode\n\n    Args:\n        sentence (str): a custom string.\n        NMTAttn (tl.Serial): An LSTM sequence-to-sequence model with attention.\n        vocab_file (str): filename of the vocabulary\n        vocab_dir (str): path to the vocabulary file\n\n    Returns:\n        str: the translated sentence\n    \"\"\"\n    \n    _,_, translated_sentence = sampling_decode(sentence, NMTAttn, vocab_file=vocab_file, vocab_dir=vocab_dir)\n    \n    print(\"English: \", sentence)\n    print(\"German: \", translated_sentence)\n    \n    return translated_sentence\n```\n\n\n```python\n# put a custom string here\nyour_sentence = 'I love languages.'\n\ngreedy_decode_test(your_sentence, model, vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR);\n```\n\n    English:  I love languages.\n    German:  mg;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n\n\n```python\ngreedy_decode_test('You are almost done with the assignment!', model, vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR);\n```\n\n    English:  You are almost done with the assignment!\n    German:  mg;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n\n<a name=\"4.2\"></a>\n## 4.2  Minimum Bayes-Risk Decoding\n\nAs mentioned in the lectures, getting the most probable token at each step may not necessarily produce the best results. Another approach is to do Minimum Bayes Risk Decoding or MBR. The general steps to implement this are:\n\n1. take several random samples\n2. score each sample against all other samples\n3. select the one with the highest score\n\nYou will be building helper functions for these steps in the following sections.\n\n<a name='4.2.1'></a>\n### 4.2.1 Generating samples\n\nFirst, let's build a function to generate several samples. You can use the `sampling_decode()` function you developed earlier to do this easily. We want to record the token list and log probability for each sample as these will be needed in the next step.\n\n\n```python\ndef generate_samples(sentence, n_samples, NMTAttn=None, temperature=0.6, vocab_file=None, vocab_dir=None):\n    \"\"\"Generates samples using sampling_decode()\n\n    Args:\n        sentence (str): sentence to translate.\n        n_samples (int): number of samples to generate\n        NMTAttn (tl.Serial): An LSTM sequence-to-sequence model with attention.\n        temperature (float): parameter for sampling ranging from 0.0 to 1.0.\n            0.0: same as argmax, always pick the most probable token\n            1.0: sampling from the distribution (can sometimes say random things)\n        vocab_file (str): filename of the vocabulary\n        vocab_dir (str): path to the vocabulary file\n        \n    Returns:\n        tuple: (list, list)\n            list of lists: token list per sample\n            list of floats: log probability per sample\n    \"\"\"\n    # define lists to contain samples and probabilities\n    samples, log_probs = [], []\n\n    # run a for loop to generate n samples\n    for _ in range(n_samples):\n        \n        # get a sample using the sampling_decode() function\n        sample, logp, _ = sampling_decode(sentence, NMTAttn, temperature, vocab_file=vocab_file, vocab_dir=vocab_dir)\n        \n        # append the token list to the samples list\n        samples.append(sample)\n        \n        # append the log probability to the log_probs list\n        log_probs.append(logp)\n                \n    return samples, log_probs\n```\n\n\n```python\n# generate 4 samples with the default temperature (0.6)\ngenerate_samples('I love languages.', 4, model, vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR)\n```\n\n\n\n\n    ([[25385,\n       7190,\n       32832,\n       14319,\n       12110,\n       17574,\n       27319,\n       17985,\n       4459,\n       13810,\n       28933,\n       15427,\n       17586,\n       1743,\n       12509,\n       13168,\n       14704,\n       6972,\n       12325,\n       21590,\n       8300,\n       28777,\n       24235,\n       31301,\n       8242,\n       7782,\n       13062,\n       25709,\n       22963,\n       16755,\n       15432,\n       11965,\n       28777,\n       12261,\n       28448,\n       2578,\n       28190,\n       33225,\n       27209,\n       1827,\n       22160,\n       21828,\n       22101,\n       14291,\n       23516,\n       25987,\n       29591,\n       24096,\n       13574,\n       10688],\n      [29644,\n       16141,\n       24709,\n       30102,\n       5544,\n       29955,\n       28748,\n       7742,\n       23054,\n       23697,\n       11082,\n       9138,\n       11638,\n       9261,\n       16707,\n       857,\n       16764,\n       26627,\n       28521,\n       9439,\n       16062,\n       15093,\n       22622,\n       520,\n       6846,\n       6940,\n       5166,\n       7389,\n       31990,\n       28617,\n       125,\n       22882,\n       12651,\n       7479,\n       1178,\n       28513,\n       21095,\n       17240,\n       4932,\n       8312,\n       27727,\n       3417,\n       8688,\n       31233,\n       31653,\n       142,\n       7100,\n       21533,\n       31814,\n       21216],\n      [1196,\n       26121,\n       13351,\n       18161,\n       438,\n       32311,\n       10476,\n       3926,\n       25949,\n       23453,\n       1810,\n       282,\n       14650,\n       10971,\n       8842,\n       17439,\n       10263,\n       1677,\n       6440,\n       12126,\n       19436,\n       15623,\n       27051,\n       19771,\n       22808,\n       11296,\n       7297,\n       13616,\n       18396,\n       7505,\n       32223,\n       20722,\n       19344,\n       15982,\n       15385,\n       16461,\n       27036,\n       13349,\n       19084,\n       5067,\n       10957,\n       23287,\n       28908,\n       20665,\n       10585,\n       24997,\n       4509,\n       25775,\n       27483,\n       30186],\n      [28285,\n       30769,\n       374,\n       32302,\n       15442,\n       28849,\n       12480,\n       124,\n       6412,\n       1775,\n       20929,\n       27503,\n       25004,\n       5981,\n       16239,\n       6490,\n       17752,\n       17578,\n       18881,\n       7403,\n       31556,\n       30527,\n       30086,\n       8319,\n       9133,\n       16256,\n       13420,\n       5106,\n       16371,\n       29870,\n       24544,\n       32538,\n       18768,\n       21521,\n       27766,\n       8926,\n       13525,\n       25275,\n       14916,\n       8089,\n       20137,\n       7,\n       16283,\n       9810,\n       9959,\n       30433,\n       17245,\n       31540,\n       33127,\n       15837]],\n     [-10.49789047241211,\n      -10.573382377624512,\n      -10.52040958404541,\n      -10.322290420532227])\n\n\n\n### 4.2.2 Comparing overlaps\n\nLet us now build our functions to compare a sample against another. There are several metrics available as shown in the lectures and you can try experimenting with any one of these. For this assignment, we will be calculating scores for unigram overlaps. One of the more simple metrics is the [Jaccard similarity](https://en.wikipedia.org/wiki/Jaccard_index) which gets the intersection over union of two sets. We've already implemented it below for your perusal.\n\n\n```python\ndef jaccard_similarity(candidate, reference):\n    \"\"\"Returns the Jaccard similarity between two token lists\n\n    Args:\n        candidate (list of int): tokenized version of the candidate translation\n        reference (list of int): tokenized version of the reference translation\n\n    Returns:\n        float: overlap between the two token lists\n    \"\"\"\n    \n    # convert the lists to a set to get the unique tokens\n    can_unigram_set, ref_unigram_set = set(candidate), set(reference)  \n    \n    # get the set of tokens common to both candidate and reference\n    joint_elems = can_unigram_set.intersection(ref_unigram_set)\n    \n    # get the set of all tokens found in either candidate or reference\n    all_elems = can_unigram_set.union(ref_unigram_set)\n    \n    # divide the number of joint elements by the number of all elements\n    overlap = len(joint_elems) / len(all_elems)\n    \n    return overlap\n```\n\n\n```python\n# let's try using the function. remember the result here and compare with the next function below.\njaccard_similarity([1, 2, 3], [1, 2, 3, 4])\n```\n\n\n\n\n    0.75\n\n\n\nOne of the more commonly used metrics in machine translation is the ROUGE score. For unigrams, this is called ROUGE-1 and as shown in class, you can output the scores for both precision and recall when comparing two samples. To get the final score, you will want to compute the F1-score as given by:\n\n$$score = 2* \\frac{(precision * recall)}{(precision + recall)}$$\n\n<a name=\"ex08\"></a>\n### Exercise 08\n\n**Instructions**: Implement the `rouge1_similarity()` function.\n\n\n```python\n# UNQ_C8\n# GRADED FUNCTION\n\n# for making a frequency table easily\nfrom collections import Counter\n\ndef rouge1_similarity(system, reference):\n    \"\"\"Returns the ROUGE-1 score between two token lists\n\n    Args:\n        system (list of int): tokenized version of the system translation\n        reference (list of int): tokenized version of the reference translation\n\n    Returns:\n        float: overlap between the two token lists\n    \"\"\"    \n    \n    ### START CODE HERE (REPLACE INSTANCES OF `None` WITH YOUR CODE) ###\n    \n    # make a frequency table of the system tokens (hint: use the Counter class)\n    sys_counter = Counter(system)\n    #print(sys_counter)\n    # make a frequency table of the reference tokens (hint: use the Counter class)\n    ref_counter = Counter(reference)\n    \n    # initialize overlap to 0\n    overlap = 0\n    \n    # run a for loop over the sys_counter object (can be treated as a dictionary)\n    for token in sys_counter:\n        \n        # lookup the value of the token in the sys_counter dictionary (hint: use the get() method)\n        token_count_sys = sys_counter.get(token)\n        \n        # lookup the value of the token in the ref_counter dictionary (hint: use the get() method)\n        token_count_ref = ref_counter.get(token)\n        if token_count_ref==None:\n          token_count_ref=0\n        # update the overlap by getting the smaller number between the two token counts above\n        overlap += min(token_count_sys,token_count_ref)\n    \n    # get the precision (i.e. number of overlapping tokens / number of system tokens)\n    precision = overlap / len(system)\n    \n    # get the recall (i.e. number of overlapping tokens / number of reference tokens)\n    recall = overlap / len(reference)\n    \n    if precision + recall != 0:\n        # compute the f1-score\n        rouge1_score = 2*precision*recall/(precision+recall)\n    else:\n        rouge1_score = 0 \n    ### END CODE HERE ###\n    \n    return rouge1_score\n    \n\n```\n\n\n```python\n# notice that this produces a different value from the jaccard similarity earlier\nrouge1_similarity([1, 2, 3], [1, 2, 3, 4])\n```\n\n\n\n\n    0.8571428571428571\n\n\n\n\n```python\n# BEGIN UNIT TEST\nw1_unittest.test_rouge1_similarity(rouge1_similarity)\n# END UNIT TEST\n```\n\n    \u001b[92m All tests passed\n\n\n### 4.2.3 Overall score\n\nWe will now build a function to generate the overall score for a particular sample. As mentioned earlier, we need to compare each sample with all other samples. For instance, if we generated 30 sentences, we will need to compare sentence 1 to sentences 2 to 30. Then, we compare sentence 2 to sentences 1 and 3 to 30, and so forth. At each step, we get the average score of all comparisons to get the overall score for a particular sample. To illustrate, these will be the steps to generate the scores of a 4-sample list.\n\n1. Get similarity score between sample 1 and sample 2\n2. Get similarity score between sample 1 and sample 3\n3. Get similarity score between sample 1 and sample 4\n4. Get average score of the first 3 steps. This will be the overall score of sample 1.\n5. Iterate and repeat until samples 1 to 4 have overall scores.\n\nWe will be storing the results in a dictionary for easy lookups.\n\n<a name=\"ex09\"></a>\n### Exercise 09\n\n**Instructions**: Implement the `average_overlap()` function.\n\n\n```python\n# UNQ_C9\n# GRADED FUNCTION\ndef average_overlap(similarity_fn, samples, *ignore_params):\n    \"\"\"Returns the arithmetic mean of each candidate sentence in the samples\n\n    Args:\n        similarity_fn (function): similarity function used to compute the overlap\n        samples (list of lists): tokenized version of the translated sentences\n        *ignore_params: additional parameters will be ignored\n\n    Returns:\n        dict: scores of each sample\n            key: index of the sample\n            value: score of the sample\n    \"\"\"  \n    \n    # initialize dictionary\n    scores = {}\n    \n    # run a for loop for each sample\n    for index_candidate, candidate in enumerate(samples):    \n        \n        ### START CODE HERE (REPLACE INSTANCES OF `None` WITH YOUR CODE) ###\n        \n        # initialize overlap to 0.0\n        overlap = 0.0\n        \n        # run a for loop for each sample\n        for index_sample, sample in enumerate(samples): \n\n            # skip if the candidate index is the same as the sample index\n            if index_candidate == index_sample:\n                continue\n                \n            # get the overlap between candidate and sample using the similarity function\n            sample_overlap = similarity_fn(candidate,sample)\n            \n            # add the sample overlap to the total overlap\n            overlap += sample_overlap\n            \n        # get the score for the candidate by computing the average\n        score = overlap/(len(samples)-1)\n        \n        # save the score in the dictionary. use index as the key.\n        scores[index_candidate] = score\n        \n        ### END CODE HERE ###\n    return scores\n```\n\n\n```python\naverage_overlap(jaccard_similarity, [[1, 2, 3], [1, 2, 4], [1, 2, 4, 5]], [0.4, 0.2, 0.5])\n```\n\n\n\n\n    {0: 0.45, 1: 0.625, 2: 0.575}\n\n\n\n\n```python\n# BEGIN UNIT TEST\nw1_unittest.test_average_overlap(average_overlap)\n# END UNIT TEST\n```\n\n    \u001b[92m All tests passed\n\n\nIn practice, it is also common to see the weighted mean being used to calculate the overall score instead of just the arithmetic mean. We have implemented it below and you can use it in your experiements to see which one will give better results.\n\n\n```python\ndef weighted_avg_overlap(similarity_fn, samples, log_probs):\n    \"\"\"Returns the weighted mean of each candidate sentence in the samples\n\n    Args:\n        samples (list of lists): tokenized version of the translated sentences\n        log_probs (list of float): log probability of the translated sentences\n\n    Returns:\n        dict: scores of each sample\n            key: index of the sample\n            value: score of the sample\n    \"\"\"\n    \n    # initialize dictionary\n    scores = {}\n    \n    # run a for loop for each sample\n    for index_candidate, candidate in enumerate(samples):    \n        \n        # initialize overlap and weighted sum\n        overlap, weight_sum = 0.0, 0.0\n        \n        # run a for loop for each sample\n        for index_sample, (sample, logp) in enumerate(zip(samples, log_probs)):\n\n            # skip if the candidate index is the same as the sample index            \n            if index_candidate == index_sample:\n                continue\n                \n            # convert log probability to linear scale\n            sample_p = float(np.exp(logp))\n\n            # update the weighted sum\n            weight_sum += sample_p\n\n            # get the unigram overlap between candidate and sample\n            sample_overlap = similarity_fn(candidate, sample)\n            \n            # update the overlap\n            overlap += sample_p * sample_overlap\n            \n        # get the score for the candidate\n        score = overlap / weight_sum\n        \n        # save the score in the dictionary. use index as the key.\n        scores[index_candidate] = score\n    \n    return scores\n```\n\n\n```python\nweighted_avg_overlap(jaccard_similarity, [[1, 2, 3], [1, 2, 4], [1, 2, 4, 5]], [0.4, 0.2, 0.5])\n```\n\n\n\n\n    {0: 0.44255574831883415, 1: 0.631244796869735, 2: 0.5575581009406329}\n\n\n\n### 4.2.4 Putting it all together\n\nWe will now put everything together and develop the `mbr_decode()` function. Please use the helper functions you just developed to complete this. You will want to generate samples, get the score for each sample, get the highest score among all samples, then detokenize this sample to get the translated sentence.\n\n<a name=\"ex10\"></a>\n### Exercise 10\n\n**Instructions**: Implement the `mbr_overlap()` function.\n\n\n```python\n# UNQ_C10\n# GRADED FUNCTION\ndef mbr_decode(sentence, n_samples, score_fn, similarity_fn, NMTAttn=None, temperature=0.6, vocab_file=None, vocab_dir=None):\n    \"\"\"Returns the translated sentence using Minimum Bayes Risk decoding\n\n    Args:\n        sentence (str): sentence to translate.\n        n_samples (int): number of samples to generate\n        score_fn (function): function that generates the score for each sample\n        similarity_fn (function): function used to compute the overlap between a pair of samples\n        NMTAttn (tl.Serial): An LSTM sequence-to-sequence model with attention.\n        temperature (float): parameter for sampling ranging from 0.0 to 1.0.\n            0.0: same as argmax, always pick the most probable token\n            1.0: sampling from the distribution (can sometimes say random things)\n        vocab_file (str): filename of the vocabulary\n        vocab_dir (str): path to the vocabulary file\n\n    Returns:\n        str: the translated sentence\n    \"\"\"\n    \n    ### START CODE HERE (REPLACE INSTANCES OF `None` WITH YOUR CODE) ###\n    # generate samples\n    samples, log_probs = generate_samples(sentence=sentence,n_samples=n_samples,NMTAttn=NMTAttn,temperature = temperature,vocab_file = vocab_file,vocab_dir=vocab_dir)\n    \n    # use the scoring function to get a dictionary of scores\n    # pass in the relevant parameters as shown in the function definition of \n    # the mean methods you developed earlier\n    scores = score_fn(similarity_fn,samples,log_probs)\n    \n    # find the key with the highest score\n    max_index = np.argmax(scores)\n    \n    # detokenize the token list associated with the max_index\n    translated_sentence =  detokenize(samples[max_index], vocab_file=vocab_file, vocab_dir=vocab_dir)\n    \n    ### END CODE HERE ###\n    return (translated_sentence, max_index, scores)\n```\n\n\n```python\nTEMPERATURE = 1.0\n\n# put a custom string here\nyour_sentence = 'She speaks English and German.'\n```\n\n\n```python\nmbr_decode(your_sentence, 4, weighted_avg_overlap, jaccard_similarity, model, TEMPERATURE, vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR)[0]\n```\n\n\n\n\n    'W\u00fcrMarket Wachstumsmodell kamerlohabitamicrobeingeschSaviigosynbesonphysics Posten Javimplications AbdeAbbeWirtschaftssmpfpride patiengesch\u00e4tzten demn\u00e4chst FlugKeynesian t\u00e9ophistic Description prohibited potatoadverse Erhalt erlegangsachtet Eigenheimseas ggle\u014fsichtigechalreadinnahe zioMoral Gott garantieren'\n\n\n\n\n```python\nmbr_decode('Congratulations!', 4, average_overlap, rouge1_similarity, model, TEMPERATURE, vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR)[0]\n```\n\n\n\n\n    'rightRefer\u00fcbfurthermore Inflationszuvor chtlich \u00e4hletter iamalen seltheating spokesLindL\u00f6schstaleerBanks B\u00fchne sufficdevoted guardRechtssicherheit Punenforced angesammelt\u00e4ndigen indebted Systems simulfeatures \u00e4te packen reference Erweiterung mind Minutes n\u00f6tige einstehappened obstNadMyklar newsletter Hollywood dalntucka'\n\n\n\n\n```python\nmbr_decode('You have completed the assignment!', 4, average_overlap, rouge1_similarity, model, TEMPERATURE, vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR)[0]\n```\n\n\n\n\n    \"stischWertsch\u00f6pfungZentralverzichten bildung yo 'solved Bisher eitigePARIS killing Deutsche020ari digitale currencies VI Ggebunden kettkrieg I aloflourishReserven El jas abolished allein learn TscheAustin untrswaJuli Beahaltunggeweiselten riffvieestiDanube shorteiting June entworfen malignAlco\"\n\n\n\n**This unit test take a while to run. Please be patient**\n\n#### Congratulations! Next week, you'll dive deeper into attention models and study the Transformer architecture. You will build another network but without the recurrent part. It will show that attention is all you need! It should be fun!\n", "meta": {"hexsha": "758a9ecfae56e2d9ebf458efbb758d0b117f57e4", "size": 188564, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": ".ipynb_checkpoints/neural_machine_translation-checkpoint.ipynb", "max_stars_repo_name": "rakki-18/imdb-review-classification", "max_stars_repo_head_hexsha": "1989c8e1dc2042be91969867018b088c974c02fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-03T15:23:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T15:23:47.000Z", "max_issues_repo_path": ".ipynb_checkpoints/neural_machine_translation-checkpoint.ipynb", "max_issues_repo_name": "rakki-18/NLP-models", "max_issues_repo_head_hexsha": "1989c8e1dc2042be91969867018b088c974c02fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": ".ipynb_checkpoints/neural_machine_translation-checkpoint.ipynb", "max_forks_repo_name": "rakki-18/NLP-models", "max_forks_repo_head_hexsha": "1989c8e1dc2042be91969867018b088c974c02fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1708502024, "max_line_length": 1271, "alphanum_fraction": 0.5886118241, "converted": true, "num_tokens": 26794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.10818895168662, "lm_q1q2_score": 0.03183080940882184}}
{"text": "# Introduction to reproducibility and power issues\n\n### Acknowledgements: \n\nThis notebook borrows significantly from works by :\n\n    * Matthew Brett\n    * Tal Yarkoni\n    \nand from a previous presentation at the Despo lab. \n\n\n## Outline\n\n1. Significance, evidence and causes of non reproducibility\n2. A quick questionnaire\n3. Power issues: definition\n4. Button et al., 2013\n5. Friston et al., 2012, and Yarkoni's answers\n\n\n```python\nfrom IPython.display import Image as Image\n\n```\n\n\n```python\nprint(\"Johnson, V.E. (2013). Revised standards for statistical evidence. \" + \n                             \"PNAS 110, 19313\u201319317.\")\nImage('./figures/johnson_PNAS_2013_significance.png')\n\n\n```\n\n\n```python\nprint(\"\\n The correspondence between P values and Bayes factors based on \\\n        \\n UMPBTs suggest that commonly used thresholds for statistical \\\n        \\n significance represent only moderate evidence against null \\\n        \\n hypotheses. \\n\")\n\nImage('./figures/johnson_PNAS_2013_pval_bayefct.png')\n\n```\n\n## Evidence and causes of non reproducibility\n\n* In general \n    - Nature \"Reducing our irreproducibility\", 2013\n* In pre-oncology \n    - Begley and Ellis, 2011\n* In psychological science\n    - Reproducibility Project: Psychology osf.io/ezcuj/wiki/home/\n    - some response to this (J. Mitchell, Harvard)\n* In Genetics\n    - GWAS (Ioannidis 2007)\n    - Stein et al., 2012\n* In neuroimaging\n    - Raemaekers 2007, Thirion 2007, Carp 2013, etc\n* In Imaging Genetics\n    - Molendijk 2012, Meir 2008 \n\n\n```python\nprint(\"from Molendijk 2012\")\nImage('./figures/molendijk_2012_f4.png')\n```\n\n* __Analyses are getting complex__\n    * Data acquisition  \n    * Linking with other data\n    * Data size \n    * Methods\n\n\n* __Publication pressure is high__\n    * I don't think I need to argue this here : Benefice / Risk in favor of quick publications\n\n\n* __Mistakes are done__\n    * \"The scientific method\u2019s central motivation is the ubiquity of error \u2014 the awareness that mistakes and self-delusion can creep in absolutely anywhere and that the scientist\u2019s effort is primarily expended in recognizing and rooting out error.\" _Donoho, 2009._\n    \n    * Anatomy of an error\n\n\n* __Power issues__\n\n\n## Causes of non reproducibility: Ioannidis 2005, Plos One\n\n### Corollary 1: The smaller the studies conducted in a scientific field, the less likely the research findings are to be true.\n\n### Corollary 2: The smaller the effect sizes in a scientific field, the less likely the research findings are to be true.\n\n### Corollary 3: The greater the number and the lesser the selection of tested relationships in a scientific field, the less likely the research findings are to be true. \n\n### Corollary 4: The greater the flexibility in designs, definitions, outcomes, and analytical modes in a scientific field, the less likely the research findings are to be true.\n\nSee: \nSimmons, J.P., Nelson, L.D., and Simonsohn, U. (2011). False-Positive Psychology: Undisclosed Flexibility in Data Collection and Analysis Allows Presenting Anything as Significant. Psychological Science 22, 1359\u20131366.\n\n\n```python\nImage('./figures/simons_table.png')\n```\n\n### Corollary 5: The greater the financial and other interests and prejudices in a scientific field, the less likely the research findings are to be true\n\n## The questionnaire of Westover 2011 for medical students\n\nConsider a typical medical research study, for example designed to test the efficacy of a drug, in which a null hypothesis H0 (\u2019no effect\u2019) is tested against an alternative hypothesis H 1 (\u2019some effect\u2019). Suppose that the study results pass a test of statistical significance (that is P-value<0.05) in favor of H1. What has been shown?\n\n\nWestover, M.B., Westover, K., and Bianchi, M. (2011). Significance testing as perverse probabilistic reasoning. BMC Medicine 9, 20.\n\n\n1. H0 is false.\n2. H1 is true.\n3. H0 is probably false.\n4. H1 is probably true.\n5. Both (1) and (2).\n6. Both (3) and (4).\n7. None of the above.\n\n### Corollary 6: The hotter a scientific field (with more scientific teams involved), the less likely the research findings are to be true.\n\n## Some Definitions \n\n* $H_0$ : null hypothesis: The effect we are testing for is null\n\n* $H_A$ : alternative hypothesis : Not $H_0$\n\n* $T_S$ : Test is significant (eg $T = T_S$)\n\n* $T_N$ : Test is not significant (eg $T = T_N$)\n\n* $\\alpha$ : false positive rate - probability to reject $H_0$ when $H_0$ is true (therefore $H_A$ is false)\n\n* $\\beta$ : false negative rate - probability to accept $H_0$ when $H_A$ is true ($H_0$ is false)\n\n\npower = $1-\\beta$ \n\nwhere $\\beta$ is the risk of *false negative*\n\nSo, to compute power, *we need to know what is the risk of false negative*, ie, the risk to not show a significant effect while we have some signal (null is false).\n\n\n```python\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport numpy as np\nimport scipy.stats as sst\n```\n\n\n```python\nfrom sympy import symbols, Eq, solve, simplify, lambdify, init_printing, latex\ninit_printing(use_latex=True, order='old')\n```\n\n\n```python\nfrom IPython.display import HTML\n# Code to make HTML for a probability table\ndef association_table(assocs, title):\n    \"\"\"\n    parameters:\n    -----------\n    assocs: dict\n        keys are ... values are ...\n    title: string\n        The table title\n    \"\"\"\n    \n    latexed = {'title': title}\n    for key, value in assocs.items():\n        latexed[key] = latex(value)\n    latexed['s_total'] = latex(assocs['t_s'] + assocs['f_s'])\n    latexed['ns_total'] = latex(assocs['t_ns'] + assocs['f_ns'])\n    \n    return \"\"\"<h2>{title}</h2>\n              <TABLE>\n              <TR><TH> $  H / T $ <TH>  $T_S$  <TH>$T_N$\n              <TR><TH> $H_A$  <TD>  ${t_s}$     <TD> ${t_ns}$\n              <TR><TH> $H_0$  <TD>  ${f_s}$     <TD> ${f_ns}$\n              <TR><TH> Total  <TD>  ${s_total}$ <TD> ${ns_total}$      \n              </TABLE>\"\"\".format(**latexed)\n\n```\n\n\n```python\nfrom sympy.abc import alpha, beta # get alpha, beta symbolic variables\nassoc = dict(t_s = 1 - beta,      # H_A true, test significant = true positives\n             t_ns = beta,         # true, not significant = false negatives\n             f_s = alpha,         # false, significant = false positives\n             f_ns = 1 - alpha)    # false, not sigificant = true negatives\nHTML(association_table(assoc, 'Not considering prior'))\n```\n\n\n\n\n<h2>Not considering prior</h2>\n              <TABLE>\n              <TR><TH> $  H / T $ <TH>  $T_S$  <TH>$T_N$\n              <TR><TH> $H_A$  <TD>  $1 - \\beta$     <TD> $\\beta$\n              <TR><TH> $H_0$  <TD>  $\\alpha$     <TD> $1 - \\alpha$\n              <TR><TH> Total  <TD>  $1 + \\alpha - \\beta$ <TD> $1 + \\beta - \\alpha$      \n              </TABLE>\n\n\n\n## How do we compute power ? \n\n### What is the effect ?\n\n#### An example using the mean of two groups: \n\n$$\\hspace{3cm}\\mu = \\mu_1 - \\mu_2$$\n\n### What is the standardized effect ? (eg Cohen's d)\n\n#### With $\\sigma$ the standard deviation of the data (assume the two groups have same $\\sigma$\n\n$$\\hspace{3cm}d = \\frac{\\mu_1 - \\mu_2}{\\sigma} = \\frac{\\mu}{\\sigma}$$\n\n### \"Z\" : Effect accounting for the sample size \n\n$$\\hspace{3cm}Z = \\frac{\\mu}{\\sigma / \\sqrt{n}}$$\n\n### Cohen's d value:\n\n\n```python\n# print some cohen values\nmuse = np.asarray((.05, .1,.2,.3,.4,.5))\nsigmas = np.linspace(1.,.5,len(muse))\n\ncohenstr = [\"For sigma = {0:3.2f} and m = {1:3.2f} Cohen d = {2:3.2f}\".format(sig,mu,coh) \n                                       for (sig, mu, coh) in zip(sigmas, muse, muse/sigmas)]\n\nfor s in cohenstr:\n    print(s)\n```\n\n    For sigma = 1.00 and m = 0.05 Cohen d = 0.05\n    For sigma = 0.90 and m = 0.10 Cohen d = 0.11\n    For sigma = 0.80 and m = 0.20 Cohen d = 0.25\n    For sigma = 0.70 and m = 0.30 Cohen d = 0.43\n    For sigma = 0.60 and m = 0.40 Cohen d = 0.67\n    For sigma = 0.50 and m = 0.50 Cohen d = 1.00\n\n\nWe have to estimate the effect $\\mu$, say under some normal noise. Our statistic will be:\n\n$$\nt = \\frac{\\hat{\\mu}}{\\hat{\\sigma_{\\mu}}} = \\frac{\\hat{\\mu}}{\\hat{{SE}_{\\mu}}}\n$$\n\nPower is the probability that the observed t is greater than $t_{.05}$, computing $t_{.05}$ by assuming that we are under the null. \n\nSo, we compute $t_{.05}$, and want to compute $P(t > t_{.05})$. \n\nTo compute this, __we need the distribution of our measured t - therefore we need to know the signal / effect size !__ \n\nLet's assume we know this and call it $t_{nc}$, and $F_{nc}$ for the cumulative distribution (more on this in the appendix).\n\n$\\mbox{Power} = 1 - \\beta =  P(t > t_{.05}) = 1 - F_{nc}(t_{.05})$\n\n\n__This power will depend on 4 parameters :__\n\n$$ \\mbox{The non standardized effect : } \\mu$$\n\n$$\\mbox{The standard deviation of the data : } \\sigma$$\n\n$$\\mbox{The number of subjects : } n$$\n\n$$\\mbox{The type I risk of error : } \\alpha$$\n\nAnd on the distribution of the statistic under the alternative hypothesis. Here, we assume our original data are normals, and the $t = \\frac{\\hat{\\mu}}{\\hat{{SE}_{\\mu}}}$ statistics follows a non central t distribution with non centrality parameter \n\n$$\\theta = \\mu \\sqrt{n}/\\sigma$$\n\nand $n-1$ degrees of freedom. \n\n\n```python\nimport scipy.stats as sst\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom __future__ import division\n```\n\n\n```python\n# plot power as a function of n : define a little function that \n# takes n, mu, sigma, alpha, and report n. \n# Optionally plot power as a function of nfrom matplotlib.patches import Polygon\n\nfrom matplotlib.patches import Polygon\n\ndef stat_power(n=16, mu=1., sigma=1., alpha=0.05, plot=False, xlen=500):\n    \"\"\"\n    This function computes the statistical power of an analysis assuming a normal\n    distribution of the data with a one sample t-test\n    \n    Parameters:\n    -----------\n    n: int,\n        The number of sample in the experiment\n    mu: float\n        The mean of the alternative\n    sigma: float\n        The standard deviation of the alternative\n    plot: bool\n        Plots something if true\n    alpha: float\n        The (type I) risk of error \n    xlen: int\n        Number of points for the display\n    \n    Returns:\n    --------\n    float\n        The statistical power for this number of sample, mu, sigma, alpha\n    \"\"\"\n    # Assume we need to estimate the mean - degrees of freedom is n-1\n    df = n-1\n    \n    # The non centrality parameter is mu - \n    # see https://en.wikipedia.org/wiki/Noncentral_t-distribution\n    theta = np.sqrt(df)*mu/sigma\n    \n    # let's use a non central t distribution: nct and create a nc random variable\n    nctrv = sst.nct(df, theta)\n    \n    # what is our t-threshold ? \n    t_alph_null = sst.t.isf(alpha, df)\n    \n    spow = 1 - nctrv.cdf(t_alph_null)\n    \n    if plot:\n        # define the domain of the plot\n        normrv = sst.norm(0, 1.)\n        bornesnc = nctrv.isf([0.001, .999])\n        bornesn = normrv.isf([0.001, .999])\n    \n        x = np.linspace(np.min(bornesn), np.max(bornesnc), xlen)\n        t_line = np.zeros_like(x)\n        # define the line : find x that is closest to t_alph_null\n        x_t_line = np.argmin((x-t_alph_null)**2)\n        # define y: the max of the two pdf\n        y_t_line = np.max(np.hstack((nctrv.pdf(x), normrv.pdf(x))))\n        t_line[x_t_line] = y_t_line\n\n        fig, ax = plt.subplots()\n        plt.plot(x, nctrv.pdf(x), 'g', x, normrv.pdf(x), 'b', x, t_line, 'r')\n        \n        # Make the shaded region\n        # http://matplotlib.org/xkcd/examples/showcase/integral_demo.html\n        a = x[x_t_line]; b =  np.max(bornesnc);\n        ix = np.linspace(a,b)\n        iy = nctrv.pdf(ix)\n        verts = [(a, 0)] + list(zip(ix, iy)) + [(b, 0)]\n        poly = Polygon(verts, facecolor='0.9', edgecolor='0.5')\n        ax.add_patch(poly)\n        \n        ax.set_xlabel(\"t-value - H1 centred on \" + r\"$\\theta $\" + \" = {0:4.2f};  \".format(theta) \n                      + r\"$\\mu$\" + \" = {0:4.2f}\".format(mu)); \n        ax.set_ylabel(\"Probability(t)\");\n        ax.set_title('H0 and H1 sampling densities '\n                      + r'$\\beta$' + '= {0:3.2f};  Sample size n = {1:d} '.format(spow,n))\n        plt.show()\n\n    return spow\n\n```\n\n\n```python\nn = 30\nmu = .5\nsigma = 1.\npwr = stat_power(n, mu, sigma, plot=True, alpha=0.05, xlen=500)\nprint (\"Power = \", pwr, \"      Z effect (Non centrality parameter) = \", mu*np.sqrt(n)/sigma)\n```\n\n\n```python\nn = 12\nmu = .5\nsigma = 1.\npwr = stat_power(n, mu, sigma, plot=True, alpha=0.05, xlen=500)\nprint(\"Power = \", pwr, \"      Z effect (Non centrality parameter): \", mu*np.sqrt(n)/sigma)\n```\n\n### Plot power as a function of the number of subject in the study\n\n\n```python\ndef pwr_funcofsubj(muse, nses, alpha=.05, sigma=1):\n    \"\"\"\n    muse: array of mu\n    nses: array of number of subjects\n    alpha: float, type I risk\n    sigma: float, data sigma\n    \"\"\"\n    mstr = [ 'd='+str(m) for m in np.asarray(muse)/sigma]\n    lines=[]\n    for mu in (muse):\n        pw = [stat_power(n, mu, sigma, alpha=alpha, plot=False) for n in nses]    \n        (pl,) = plt.plot(nses, pw)\n        lines.append(pl)\n    plt.legend( lines, mstr, loc='upper right', shadow=True)\n    plt.xlabel(\" Number of subjects \")\n    plt.ylabel(\" Power \");\n    \n    return None\n\nmus = (.05, .1,.2,.3,.4,.5, .6);\n#nse = range(70, 770, 20)\nnse = range(7, 77, 2)\nalph = 1.e-3\n    \npwr_funcofsubj(mus, nse, alph)\n```\n\n### **** Here - play with n ****\n\n\n```python\nmus = (.05,.1,.2,.3,.4,.5,.6);\nnse = range(10, 330, 20)\n#nse = range(7, 77, 2)\nalph = 0.001\n    \npwr_funcofsubj(mus, nse, alph)\n```\n\n### Here - play with $\\alpha$\n\n\n```python\nmus = (.05, .1,.2,.3,.4,.5, .6);\nnse = range(10, 770, 20)\n#nse = range(7, 77, 2)\nalph = 0.05/30000\n    \npwr_funcofsubj(mus, nse, alph)\n```\n\n### What is the effect size of APOE on the hippocampal volume ?\n\nAuthors find p value of 6.63e-10\n\nThey had 733 subjects\n\n\n\n\n```python\nn01 = sst.norm(0,1.)\nz = n01.isf(6.6311e-10)\nd = n01.isf(6.6311e-10)/np.sqrt(733)\nprint(\"z = %4.3f d = %4.3f \" %(z,d))\n```\n\n    z = 6.064 d = 0.224 \n\n\n## The questionnaire of Westover 2011 for medical students\n\nConsider a typical medical research study, for example designed to test the efficacy of a drug, in which a null hypothesis H0 (\u2019no effect\u2019) is tested against an alternative hypothesis H 1 (\u2019some effect\u2019). Suppose that the study results pass a test of statistical significance (that is P-value<0.05) in favor of H1. What has been shown?\n\n\nWestover, M.B., Westover, K., and Bianchi, M. (2011). Significance testing as perverse probabilistic reasoning. BMC Medicine 9, 20.\n\n\n1. H0 is false.\n2. H1 is true.\n3. H0 is probably false.\n4. H1 is probably true.\n5. Both (1) and (2).\n6. Both (3) and (4).\n7. None of the above.\n\n## Derivation of Ionannidis / Button positive prediction value : PPV\n\n### Recall : Marginalize and Baye theorem\n\n$\\newcommand{Frac}[2]{\\frac{\\displaystyle #1}{\\displaystyle #2}}$\n\nSome new terms:\n\n* $Pr(H_A)$ - prior probability of $H_A$ - probability of $H_A$ before the experiment was conducted.\n* $Pr(H_0)$ - prior probability of $H_0$ = $1 - Pr(H_A)$ - probability of null hypothesis before experiment conducted\n\nWe are interested in updating the probability of $H_A$ and $H_0$ as a result of a test on some collected data.  This updated probability is $Pr(H_A | T)$ - the probability of $H_A$ given the test  result $T$. $Pr(H_A | T)$ is called the *posterior* probability because it is the probability after the test result.\n\nRemembering that \n\n$$P(A) = \\sum_{b_i} P(A,B=b_i) $$\n\nTo simplify the notation, we note $P(B=b)$ as $P(b)$\n\nRemembering [Bayes theorem](http://en.wikipedia.org/wiki/Bayes'_theorem#Derivation):\n\n$$P(A, B) = P(A | B) P(B)$$\n\nand therefore\n\n$$P(A | B) = \\Frac{P(B, A)}{P(B)} = \\Frac{P(B | A) P(A)}{P(B)}$$\n\n\nPutting these two together we have : \n\n\n$$P(A) = \\sum_{b_i} P(A|B=b_i) P(B=b_i)$$\n\nNow, apply this to the probability of the test results $T$. The test takes a value either under  $H_A$ or $H_0$.\nThe probability of a *signficant* result of the test $T=T_S$ is :\n\n$Pr(T=T_S) = P(T_S) = Pr(T_S | H_A) Pr(H_A) + Pr(T_S | H_0) Pr(H_0)$\n\n\nWhat is the posterior probability of $H_A$ given that the test is signficant?\n\n$P(H_A | T_S) = \\Frac{P(T_S | H_A) P(H_A)}{P(T_S)} = \\Frac{P(T_S | H_A) P(H_A)}{P(T_S | H_A) Pr(H_A) + Pr(T_S | H_0) Pr(H_0)}$\n\nWe have $P(T_S | H_A)$, $P(T_S | H_0)$ from the first column of the table above. Substituting into the equation:\n\n$P(H_A | T_S) = \\Frac{(1 - \\beta) P(H_A)}{(1 - \\beta) P(H_A) + \\alpha P(H_0)}$\n\nDefining:\n\n$\\pi := Pr(H_A)$, hence: $1 - \\pi = Pr(H_0)$\n\nwe have:\n\n$P(H_A | T_S) = \\Frac{(1 - \\beta) \\pi}{(1 - \\beta) \\pi + \\alpha (1 - \\pi)}$\n\n\n\n```python\nfrom sympy.abc import pi # get symbolic variable pi\npost_prob = (1 - beta) * pi / ((1 - beta) * pi + alpha * (1 - pi))\npost_prob\n```\n\n\n```python\nassoc = dict(t_s = pi * (1 - beta),\n             t_ns = pi * beta,\n             f_s = (1 - pi) * alpha,\n             f_ns = (1 - pi) * (1 - alpha))\nHTML(association_table(assoc, r'Considering prior $\\pi := P(H_A)$'))\n```\n\n\n\n\n<h2>Considering prior $\\pi := P(H_A)$</h2>\n              <TABLE>\n              <TR><TH> $  H / T $ <TH>  $T_S$  <TH>$T_N$\n              <TR><TH> $H_A$  <TD>  $\\pi \\left(1 - \\beta\\right)$     <TD> $\\beta \\pi$\n              <TR><TH> $H_0$  <TD>  $\\alpha \\left(1 - \\pi\\right)$     <TD> $\\left(1 - \\alpha\\right) \\left(1 - \\pi\\right)$\n              <TR><TH> Total  <TD>  $\\alpha \\left(1 - \\pi\\right) + \\pi \\left(1 - \\beta\\right)$ <TD> $\\beta \\pi + \\left(1 - \\alpha\\right) \\left(1 - \\pi\\right)$      \n              </TABLE>\n\n\n\n## From Button et al. : three messages\n\n### message1 : studies of low power have low probability of detecting an effect\n\n#### From the definition of power !\n\n### message2 : studies of low power have low positive predictive value : PPV = P(H1 True | detection)\n\nSame as Ioannidis - do the derivation starting with odd ratios \n\nFrom Button et al., we have the positive predictive value PPV defined as :\n\n$$\nPPV = \\frac{(1-\\beta)R}{(1-\\beta)R + \\alpha},\\textrm{ with } R = P(H_1)/P(H_0) = P_1/P_0 = \\pi / (1-\\pi)\n$$\n\nHence, \n\n$$\nPPV = \\frac{(1-\\beta)P_1}{P_0}\\frac{P_0}{(1-\\beta)P_1 + \\alpha P_0} \n$$\n\n$$\n= \\frac{(1-\\beta)P_1}{(1-\\beta)P_1 + \\alpha P_0} \n$$\n\n$$\n= P(H_1, T_S) / P(T_S) = P(H_1 | T_S) \n$$\n\nIf we have 4 chances over 5 that $H_0$ is true, and one over five that $H_1$ true, then R = 1/5 / 4/5 = .25. If there's 30% power we have PPV = 50%. So, 50% chance that our result is indeed true. 80% power leads to 80% chance of $H_1$ to be true knowing that we have detected an effect at the $\\alpha$ risk of error. \n\n\n```python\ndef PPV(R, Pw, alpha, verbose=True):\n    ppv = (Pw * R)/(Pw*R + alph)\n    if verbose:\n        print(\"with odd ratio=%3.2f, \"\n               \"power=%3.2f, alpha=%3.2f, \"\n               \"we have PPV=%3.2f\" %(R,Pw,alph,ppv))\n    return ppv\n    \n```\n\n\n```python\n# example from Button et al: P1 = 1/5, P0 = 4/5. R = 1/4\nR = 1./4.\nPw = .8\nalph = .05\nppv = PPV(R, Pw, alph)\n```\n\n    with odd ratio=0.25, power=0.80, alpha=0.05, we have PPV=0.80\n\n\n\n```python\n# if power is small :\nR = 1./4.\nPw = np.arange(.1,1,.2)\nalph = .05\nfor pw in Pw:\n    PPV(R, pw, alph)\n\n```\n\n    with odd ratio=0.25, power=0.10, alpha=0.05, we have PPV=0.33\n    with odd ratio=0.25, power=0.30, alpha=0.05, we have PPV=0.60\n    with odd ratio=0.25, power=0.50, alpha=0.05, we have PPV=0.71\n    with odd ratio=0.25, power=0.70, alpha=0.05, we have PPV=0.78\n    with odd ratio=0.25, power=0.90, alpha=0.05, we have PPV=0.82\n\n\n### message3 : studies of low power exagerate the effect size of claimed effects\n\nIf the power is small, the studies that will find an effect significant will be estimating a stronger effect than the true one. Let's simulate the phenomenon.\n\n\n```python\nn = 16 # number of subjects\nsigma = 1.0\nmu = .4\nalpha = .05\npw = stat_power(n, mu, sigma, alpha=alpha, plot=True)\nprint(\"Power : \", pw)\n```\n\n\n```python\nNexp = 100\n\nnorv = sst.norm(0., sigma)\nstrv = sst.t(n-1)\nt_05 = strv.isf(alpha)\nsample = norv.rvs(size=(n,1)) + mu\n#print np.std(sample)\n\ntval = np.zeros((Nexp,))\neffects = np.zeros((Nexp,))\neffectsize = np\nnb_detection = 0\nfor e in range(Nexp):\n    sample = norv.rvs(size=(n,1)) + mu\n    tval[e] = sample.mean()*np.sqrt(n)/np.std(sample, ddof=1)\n    effects[e] = sample.mean()/np.std(sample, ddof=1)\n\nrelbias = 100*(effects[tval > t_05].mean() - mu)/mu\nprint(\"mean effect over experiments : {:.3f} and true : {:.3f}\".format(effects.mean(), mu))\nprint(\"mean effect estimated when test is significant\", effects[tval > t_05].mean())\n\nprint(\"relative bias: %3.2f \" % relbias)\n\nestimated_effect = effects[tval > t_05].mean()\n```\n\n    mean effect over experiments : 0.442 and true : 0.400\n    mean effect estimated when test is significant 0.698084968242\n    relative bias: 74.52 \n\n\n\n```python\nx = range(Nexp)\nt05_line = np.ones_like(x)*t_05\ntrue_effect = np.ones_like(x)*mu\nest_effect = np.ones_like(x)*estimated_effect\n\nlines = plt.plot(x, effects, 'b-', x, t05_line/np.sqrt(n), 'g-', \n             x, true_effect, 'r--', \n             x, est_effect, 'b.') \nplt.legend( lines, ('t','t05_line', 'true effect', 'est. effect'), \n                   loc='upper right', shadow=True)\nplt.xlabel(\" experiments \")\nplt.ylabel(\" t-value \")\n```\n\n\n```python\nfrom IPython.display import Image as Image\n```\n\n### Another way of seeing the same thing in Button et al, 2013:\n\n\n```python\nImage('./figures/button_fig5.png')\n```\n\n### Replication should be done with more subjects, not the same amount. \n\nA graph which I found hard to understand, because in c under the null the variance of the estimated mean should be reduced as well.\n\n\n```python\nImage('./figures/button_fig1.png')\n```\n\n### Looking at the median power study of 49 Meta analysis : median power of studies in those\n\n\n```python\nImage('./figures/button_fig2.png')\n```\n\n## Karl Friston 16 subjects magic number - cf Tal Yarkoni's answer\n\n* Rule number four: the under-sampled study\n* Rule number five: the over-sampled study\n* Rule number eight: exploit superstitious thinking about voodoo correlations\n\n### KF arguments can be summarized by:\n\n1.  The null is always false: no effects are ever truly zero. Collect enough data and you will always end up rejecting the null.\n\n2.  Large effects are more important than small ones. Very small effects are \u2018trivial\u2019.\n\n3.  Very large samples will invariably end up identifying many small uninteresting effects. We should sample few subjects to detect only the big effects.\n\n\n\n```python\n# power of KF analysis : d=1, \nn = 16; mu = .5; sigma = 1.; alpha = 0.05\nstat_power(n, mu, sigma, alpha=alpha, plot=False)\n```\n\n### 1. A less favorable case\n\n#### We are doing many test and have to decrease $\\alpha$ - \n\n\n```python\n# analysis in a slightly less favorable case \nn = 16; mu = .5; sigma = 1.; alpha = 0.001\nstat_power(n, mu, sigma, plot=True, alpha = alpha)\n```\n\n### In neuroimaging non corrected p-value are small, let's plot n as a function of alpha :\n\n\n```python\ndef n_power(pw=.8, mu=1., sigma=1., alpha=0.05):\n    \"\"\"\n    compute the number of subjects needed to get pw given \n    mu, sigma and alpha\n    \"\"\"\n    norv = sst.norm(0,1.)\n    ta = norv.ppf(1 - alpha)\n    tb = norv.ppf(1 - pw)\n    n = (sigma*(ta - tb)/mu)**2\n    return n\n\n```\n\n\n```python\nmu = .4; sigma = 1.; pw = .8\n\nlnalph = np.arange(1.9,5.1,.1)\nnsub = [n_power(pw, mu, sigma, alpha=10**(-a)) for a in lnalph]\nplt.plot(lnalph, nsub)\nplt.xlabel(' exponent of the detection p-value alpha = 10^{-x} ')\nplt.ylabel(' number of subject required for power = %3.2f ' % pw)\n#xscale('log')\n```\n\n### 2. The uncertainty of small n results is very high. Confidence interval are just above zero.\n\n\n```python\ndef confidence_intervals(Nexp, **prmtrs):\n    \"\"\"\n    Nexp: the number of experiments done\n    prmtrs: a dictionary with our parameters, \n        example: prmtrs = {'n':16, 'mu':.3, 'sigma': 1., 'alpha': 0.05}\n        \n    returns arrays of size Nexp with:\n    effect: the estimated effect\n    detect: an array of 0 or 1, 1 when the effect is detected at alpha\n    lCI: lower bound of confidence interval\n    uCI: upper bound of confidence interval\n    \"\"\"\n    # unpack parameters:\n    n = prmtrs['n']\n    mu = prmtrs['mu']; \n    alpha = prmtrs['alpha']; \n    sigma = prmtrs['sigma']\n    df = n-1\n    theta = mu*np.sqrt(n)/sigma\n    \n    # initialize arrays\n    t = np.zeros((Nexp,))\n    effect = np.zeros((Nexp,))\n    lCI = np.zeros((Nexp,))\n    uCI = np.zeros((Nexp,))\n\n    # compute random variables and thresholds\n    norv = sst.norm(0., sigma)\n    strv = sst.t(df)\n    # get the 0.05 t value *under the null* to construct confidence interval\n    t_05 = strv.isf(0.05)\n    # get the alpha level t value *under the null* to detect \n    t_alph = strv.isf(alpha)\n    \n\n    for experim in range(Nexp):\n        # get n sample\n        sample = norv.rvs(size=(n,)) + mu\n        # effect and normalized effect size\n        effect[experim] = sample.mean()\n        std_error_data = np.std(sample, ddof=1) \n        std_error_mean = std_error_data/np.sqrt(n) # np.std takes ddof as \n                                                    # the df of freedom lost! here: 1.\n        t[experim] = effect[experim]/std_error_mean\n        # confidence interval :\n        CI_05 = t_05*std_error_mean\n        lCI[experim] = effect[experim] - CI_05 # t_alph # \n        uCI[experim] = effect[experim] + CI_05 # t_alph # \n\n    # number of detection:\n    detect = t>t_alph\n#    print 'number of detections:', xd.shape\n\n    return (effect, detect, lCI, uCI)\n```\n\n\n```python\n#---------------------- parameters ------------------#\nprmtrs = {'n':30, 'mu':.25, 'sigma': 1., 'alpha': 0.15}\ntheta = prmtrs['mu']*np.sqrt(prmtrs['n'])/prmtrs['sigma']\nPw = stat_power(prmtrs['n'], prmtrs['mu'], alpha=prmtrs['alpha'])\nprint('mean t value should be around %3.2f \\n' %theta)\n\n#--------------  simulate Nexp experiments ---------#\nNexp = 10000\neffect, detect, lCI, uCI = confidence_intervals(Nexp, **prmtrs)\n\nprint(\"Compare power {:.3} and rate of detection {:.3} \".format(Pw, detect.sum()/Nexp))\nprint(\"Mean effect {:.3f} compared to average detected effect {:3f}\".format(\n                    effect.mean(), effect[detect].mean()))\nprint(\"Lower bound > mu: {} lCI > mu {:3f} detected: {} over {}\".format(\n                    (lCI[detect]>mu).sum(), (lCI[detect]>mu).sum()/detect.sum(), detect.sum(), Nexp ))\n\n\n```\n\n    mean t value should be around 1.37 \n    \n    Compare power 0.617 and rate of detection 0.623 \n    Mean effect 0.250 compared to average detected effect 0.359465\n    Lower bound > mu: 72 lCI > mu 0.011550 detected: 6234 over 10000\n\n\n\n```python\nlCI[detect].mean(), (lCI[detect]>mu).sum(), (uCI[detect]<mu).sum(), lCI[detect].shape, lCI.mean()\n\n```\n\n\n\n\n    (0.055061009628235374, 72, 28, (6234,), -0.058520389128411399)\n\n\n\n\n```python\n#--------------  plot ------------------------------#\nx = np.arange(Nexp)\nxd = np.arange(detect.sum())\nmu_line = np.ones((Nexp,))*prmtrs['mu']\n\n# print the number of lower confidence interval values that are above the true mean:\n# this should be about the risk of error/2\nprint(\"lCI > mu :  {:.3}, compare with {:.3} \".format( \n                (lCI > mu).sum() / (1.*detect.sum()),  prmtrs['alpha'])) #\nprint(Nexp)\n# there should be none of these:\n# print \"(lCI < 0 \", (lCI[detect] < 0).sum() / detect.sum()\n\nf = plt.figure(1).set_size_inches(12,4)\nlines = plt.plot(xd, lCI[detect], 'g-', \n                 xd, effect[detect], 'b--',\n                 xd, uCI[detect], 'r-',\n                 xd, mu_line[detect], 'k');\nplt.legend( lines, ('lower_bound','detected Effect', 'Upper bound', 'True effect'), \n                   loc='upper right', shadow=True)\nplt.xlabel(\" One x is one experiment where detection occured\", fontdict={'size':14})\nplt.ylabel(\" Effect value and confidence interval \", fontdict={'size':14})\nplt.title(\"Detected effects and their confidence interval\", fontdict={'size':16});\n```\n\n### 3. Our prior is that effect sizes are small\n\n* big effects have been found  : see Meyer et al (2001)\n* big effect sizes are less likely than small ones :  the prior of big effects is low\n* large sample studies report lower effects - as well as intra subjects\n\nExample of Desmond and Glover 2002: using a threshold of 0.01, working memory task, 12 subject:\n\n\n\n```python\nImage('./figures/Desmond_Glover_effectsize.png')\n```\n\n## \"Protected inference\" : \n\n### Protect against small effect if you want to by redefining the null (i.e., effect is within [-.1 .1])\n\n## References\n\nKatherine S. Button, John P. A. Ioannidis, Claire Mokrysz1, Brian A. Nosek4,\nJonathan Flint5, Emma S. J. Robinson6 and Marcus R. Munaf\u00f2. Power failure: why small sample\nsize undermines the reliability of neuroscience.\n\nT. Yarkoni, 2012 [citation needed]\u00bb Blog Archive \u00bb Sixteen is not magic: Comment on Friston (2012)\n\nDesmond and Glover, Estimating sample size in functional MRI (fMRI) neuroimaging\nstudies: Statistical power analyses, Journal of Neuroscience Methods 118 (2002) 115\u0004/128.\n\nK. Friston, 2012, Neuroimage. Ten ironic rules for non-statistical reviewers\n\nJoseph P. Simmons, Leif D. Nelson and Uri Simonsohn. False-Positive Psychology: Undisclosed Flexibility in Data Collection and Analysis Allows Presenting Anything as Significant. Psychological Science. 2011.\n\nC. Glenn Begley\t & Lee M. Ellis. Drug development: Raise standards for preclinical cancer research. Nature, 2012.\n\nM Brandon Westover, Kenneth D Westover, Matt T Bianchi, 2011, BMC Medecine, Significance testing as perverse probabilistic reasoning.\n\nJohnson, V.E. (2013). Revised standards for statistical evidence. Proceedings of the National Academy of Sciences 110, 19313\u201319317.\n\nHalsey, L.G., Curran-Everett, D., Vowler, S.L., and Drummond, G.B. (2015). The fickle P value generates irreproducible results. Nature Methods 12, 179\u2013185.\n\nEklund, A., Andersson, M., Josephson, C., Johannesson, M., and Knutsson, H. (2012). Does parametric fMRI analysis with SPM yield valid results?\u2014An empirical study of 1484 rest datasets. NeuroImage 61, 565\u2013578.\n\n\nCarp, J. The secret lives of experiments: methods reporting in the fMRI literature. Neuroimage 63,\n289\u2013300 (2012).\n\n    This article reviews methods reporting and methodological choices across 241 recent fMRI    studies and shows that there were nearly as many unique analytical pipelines as there were studies. In addition, many studies were underpowered to detect plausible effects.\n\nSander Heinsalu:\n\n    \"Publication bias is a problem in all fields of research. The results of a paper should actually receive zero weight in the evaluation of its quality, otherwise there is the motivation to cherry-pick the data that give the most impressive result. The measure of quality should be the way the results were obtained \u2013 size of sample, experimental procedure, endpoints used. Ideally the reviewers of a paper should not see its results at all, only the description of the experiment.\"\n\n\n### Related blog posts:\n\nhttp://daniellakens.blogspot.ca/2015/11/the-relation-between-p-values-and.html\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "b6cbdf914b160d9225aa9fa0e231307537eb2b5c", "size": 842999, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": ".ipynb_checkpoints/NSS_power_issues-checkpoint.ipynb", "max_stars_repo_name": "jbpoline/nhw17-power", "max_stars_repo_head_hexsha": "bcde8bdf5eb08ee164859e7c2f3a19d6ab129e46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": ".ipynb_checkpoints/NSS_power_issues-checkpoint.ipynb", "max_issues_repo_name": "jbpoline/nhw17-power", "max_issues_repo_head_hexsha": "bcde8bdf5eb08ee164859e7c2f3a19d6ab129e46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": ".ipynb_checkpoints/NSS_power_issues-checkpoint.ipynb", "max_forks_repo_name": "jbpoline/nhw17-power", "max_forks_repo_head_hexsha": "bcde8bdf5eb08ee164859e7c2f3a19d6ab129e46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 367.6402093328, "max_line_length": 71972, "alphanum_fraction": 0.9220437984, "converted": true, "num_tokens": 9282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505449918075, "lm_q2_score": 0.10087861394487133, "lm_q1q2_score": 0.03168098368740499}}
{"text": "Neuromorphic engineering I\n\n## Lab 9: Silicon Neuron Circuits\n\nTeam member 1: Jan Hohenheim\n\nTeam member 2: Maxim G\u00e4rtner\n\nDate: 25.11.21\n\n-------------------------------------------------------------------------------------------------------------------\n\nIn this lab, we will test a circuit that generates action potentials (spikes) based on an\nintegrate-and-fire model of a neuron spike initiation zone.\n\nThe objectives of this lab are:\n1. to understand the spiking properties of I&F circuits.\n2. to evaluate the effect of the I&F circuit\u2019s different bias parameters on its spiking behaviour.\n\n# 1 Setup\n\n## 2.1 Connect the device\n\n\n```python\n# import the necessary libraries\nimport pyplane\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import interpolate\n```\n\n\n```python\n# create a Plane object and open the communication\nif 'p' not in locals():\n    p = pyplane.Plane()\n    try:\n        p.open('/dev/ttyACM0')\n    except RuntimeError as e:\n        del p\n        print(e)\n```\n\n\n```python\np.get_firmware_version()\n```\n\n\n\n\n    (1, 8, 4)\n\n\n\n\n```python\n# Send a reset signal to the board, check if the LED blinks\np.reset(pyplane.ResetType.Soft)\ntime.sleep(0.5) \n# NOTE: You must send this request events every time you do a reset operetion, otherwise the recieved data is noisy.\n# Because the class chip need to do handshake to get the communication correct.\np.request_events(1)\n```\n\n\n```python\n# Try to read something, make sure the chip responses\np.read_current(pyplane.AdcChannel.GO0_N)\n```\n\n\n\n\n    1.7724609335800778e-07\n\n\n\n\n```python\n # If any of the above steps fail, delete the object, close and halt, stop the server and ask the TA to restart\n# please also say your board number: ttyACMx\n\n# del p\n```\n\n## 2.2 Disable unused circuits\n\n\n```python\n# disable synapses\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.LDS_VTAU_P, \\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.DPI_VTAU_P, \\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.DDI_VTAU_P, \\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n```\n\n\n```python\n# disable axon-hillock neuron\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.AHN_VPW_N, \\\n    pyplane.Coach.BiasType.P, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n```\n\n\n```python\n# disable thresholded neuron\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ATN_VLEAK_N, \\\n    pyplane.Coach.BiasType.P, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ATN_VDC_P, \\\n    pyplane.Coach.BiasType.P, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ATN_VGAIN_N, \\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ATN_VSPKTHR_P, \\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n```\n\n\n```python\n# disable sigma-delta neuron\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ASN_VLEAK_N, \\\n    pyplane.Coach.BiasType.P, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ASN_VDC_P, \\\n    pyplane.Coach.BiasType.P, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ASN_VGAIN_N, \\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n```\n\n\n```python\n# disable exp neuron\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ACN_VLEAK_N, \\\n    pyplane.Coach.BiasType.P, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ACN_VGAIN_N, \\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ACN_VDC_P, \\\n    pyplane.Coach.BiasType.P, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ACN_VREFR_N, \\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I240nA, 255)])\n```\n\n\n```python\n# disable hodgekin-huxley neuron\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.HHN_VBUF_N, \\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.HHN_VCABUF_N, \\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.HHN_VDC_P, \\\n    pyplane.Coach.BiasType.P, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.HHN_VELEAK_N, \\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n```\n\n\n```python\n# disable DVS pixels\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.DVS_DIFF_N, \\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.DVS_CAS_N, \\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.DVS_ON_N, \\\n    pyplane.Coach.BiasType.P, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.DVS_OFF_N, \\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.DVS_SF_P, \\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.DVS_PR_P, \\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.DVS_REFR_P, \\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n```\n\n## 2.3 Chip configurations\n\n\n```python\n# select lines and neuron latches\np.send_coach_events([pyplane.Coach.generate_aerc_event(\n    pyplane.pyplane.Coach.CurrentOutputSelect.SelectLine6,\n    pyplane.Coach.VoltageOutputSelect.SelectLine2,\n    pyplane.Coach.VoltageInputSelect.NoneSelected,\n    pyplane.Coach.SynapseSelect.NoneSelected,320)])\n```\n\n\n```python\n# setup output rail-to-rail buffer\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.RR_BIAS_P, \\\n    pyplane.Coach.BiasType.P, \\\n    pyplane.Coach.BiasGenMasterCurrent.I240nA, 255)])\n```\n\n\n```python\n# set up sampling mode\n# p.set_sampling_mode(pyplane.SamplingMode.Fast)\n# p.set_fast_sampling_adcs([10])\n```\n\n## 2.4 BiasGen\n\nIn a simplified form, the output of a branch of the BiasGen will be the gate voltage $V_b$ for the bias current $I_b$, and if the current mirror has a ratio of $w$ and the bias transistor operates in subthreshold-saturation:\n\\begin{equation}\nI_b = w\\frac{BG_{fine}}{256}I_{BG_{master}}\n\\end{equation}\nWhere $I_{BG_{master}}$ is the `BiasGenMasterCurrent` $\\in \\left\\{ 60~\\rm{pA}, 460~\\rm{pA}, 3.8~\\rm{nA}, 30~\\rm{nA}, 240~\\rm{nA} \\right\\}$, $BG_{fine}$ is the integer fine value $\\in [0, 256)$\n\nTo set a bias, use the function similar to the following:\n\n```\np.send_coach_event(pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.BIAS_NAME, \\\n    pyplane.Coach.BiasType.BIAS_TYPE, \\\n    pyplane.Coach.BiasGenMasterCurrent.MASTER_CURRENT, FINE_VALUE))\n```\n\n**You may have noticed that there are some biases that are not used to directly generate a current, but rather what matters is the voltage, e.g. $V_{gain}$, $V_{ex}$ and $V_{inh}$ in our HWTA circuit. Even though they may have a `BIAS_NAME` ending with `_N` or `_P` it only indicates that they are connected to the gate of an N- or a P-FET, but the `BIAS_TYPE` parameter can be both `_N` or `_P`. For example, setting a `_N` bias to `BIAS_TYPE = P` will only make this voltage very close to GND, which _is_ sometimes the designed use case.**\n\n# 2 Axon-Hillock neuron\n\nThe axon-hillock neuron has a constant current input `AHN_IIN_UI` which is about pA (exact value not known), and the voltage on capacitor $C_m$ is output to **ADC[11]**.\n\n\n\n## 2.1 Basic measurement\n\n* Tune `AHN_VPW_N` bias so that the output waveform is more or less symmetric.\n\n\n```python\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.AHN_VPW_N,\\\n    pyplane.Coach.BiasType.N,\\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA,2)])\n```\n\n* Data aquisition\n\n\n```python\nN_samples = 50\ndT = 0.05\n\nt = np.arange(N_samples)*dT\nv = np.zeros(N_samples) # v_Cm\n\nfor i in range(N_samples):\n    v[i] = p.read_voltage(pyplane.AdcChannel.AOUT11)\n    time.sleep(dT)\n```\n\n* Plot data\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nplt.rcParams.update({'font.size': 15})\n\n\nt,v = np.loadtxt('data/data_ex_2_1.csv',delimiter=',')\n\nplt.plot(t,v)\n\nplt.xlabel('t [s]')\nplt.ylabel('$V_{m}$ [V]')\nplt.title('Fig. 1: Measured values of $V_{m}$ as function of time')\n\nplt.grid()\nplt.show()\n```\n\n* Save data\n\n\n```python\nnp.savetxt('data/data_ex_2_1.csv',[t,v] , delimiter=',')\n```\n\n## 2.2 Different pulse widths\n\nNow try two more `AHN_VPW_N` values and compare the three curves in the same plot.\n\n\n```python\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.AHN_VPW_N,\\\n    pyplane.Coach.BiasType.N,\\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA,1)])\n```\n\n\n```python\nN_samples = 50\ndT = 0.05\n\nt = np.arange(N_samples)*dT\nv = np.zeros(N_samples) # v_Cm\n\nfor i in range(N_samples):\n    v[i] = p.read_voltage(pyplane.AdcChannel.AOUT11)\n    time.sleep(dT)\n```\n\n\n```python\nnp.savetxt('data/data_ex_2_2_smaller.csv',[t,v] , delimiter=',')\n```\n\n\n```python\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.AHN_VPW_N,\\\n    pyplane.Coach.BiasType.N,\\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA,3)])\n```\n\n\n```python\nN_samples = 50\ndT = 0.05\n\nt = np.arange(N_samples)*dT\nv = np.zeros(N_samples) # v_Cm\n\nfor i in range(N_samples):\n    v[i] = p.read_voltage(pyplane.AdcChannel.AOUT11)\n    time.sleep(dT)\n```\n\n\n```python\nnp.savetxt('data/data_ex_2_2_bigger.csv',[t,v] , delimiter=',')\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nplt.rcParams.update({'font.size': 15})\n\nt,v = np.loadtxt('data/data_ex_2_1.csv',delimiter=',')\n_,v_smaller = np.loadtxt('data/data_ex_2_2_smaller.csv',delimiter=',')\n_,v_bigger = np.loadtxt('data/data_ex_2_2_bigger.csv',delimiter=',')\n\nplt.plot(t,v_smaller,t,v,t,v_bigger)\nplt.legend(['$V_{m}$ - Smaller AHN_VPW_N','$V_{m}$ - Basic AHN_VPW_N','$V_{m}$ - Large AHN_VPW_N'],bbox_to_anchor=(1.05, 1),loc='upper left') \n\nplt.xlabel('t [s]')\nplt.ylabel('$V_{m}$ [V]')\nplt.title('Fig. 2: Measured values of $V_{m}$ as function of time for varying pulse widths')\n\nplt.grid()\nplt.show()\n```\n\n## 2.3 Switch off the circuit\n\n* To avoid the output events interfering with other circuits, we set `AHN_VPW_N` to maximum again. \n\n\n```python\n# disable axon-hillock neuron\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.AHN_VPW_N, \\\n    pyplane.Coach.BiasType.P, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 0)])\n```\n\n# 3 Basic behavoir of classic I&F neuron\n\nThe **ADEXIF** (Adaptive Exponential Integrate & Fire) **classic neuron** comprises four major functional blocks: a leaky DPI (=integrate), starved-inverter (=fire), refractory period (=reset) and adaptation block.\nThe adaptation block receives the the spike pulse of the neuron itself through a pulse extender circuit.\n\nThe circuit receives an input current $I_{in}$ (typically the output of a synapse, $I_{syn}$) and outputs an AER event.\n\nThe membrane voltage $V_{mem}$ is provided to observe the internal neuron state at **ADC[10]**.\n\nThe neuron circuit has 4 basic biases: $V_{dc}$, $V_{gain}$, $V_{leak}$ and $V_{refr}$. The adaptation block has 5 more biases: $V_{adpgain}$, $V_{adpweight}$, $V_{adptau}$, $V_{adpcasc}$ & $V_{adpptau}$ (for the pulse extender).\n\nThere are two digital control bits: $V_{adpen}$ to enable/disable adaptation, and $V_{dcen}$ to disable/enable the $V_{dc}$ bias input.\n\n$C_{m}$ sizing was chosen for a capacitance value of $2$ pF, while $C_{refr}$ and $C_{adp}$ were chosen for a value of $1$ pF. \n\n\n\n## 3.1 Basic measurement\n\n* Tune the biases such that the neuron fires at about 20 Hz.\n\n\n```python\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ACN_VLEAK_N,\\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 2)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ACN_VGAIN_N,\\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 6)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ACN_VDC_P,\\\n    pyplane.Coach.BiasType.P, \\\n    pyplane.Coach.BiasGenMasterCurrent.I30nA, 10)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ACN_VREFR_N,\\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I30nA, 10)]) #change refractory period\n```\n\n* read data\n\n\n```python\ntimestep = 0.00025\nvm1 = p.acquire_transient_response(pyplane.DacChannel.DAC1, pyplane.AdcChannel.AOUT10, 0.00025, 1)\nt = np.arange(len(vm1))*timestep\n```\n\n\n```python\nnp.savetxt('data/data_ex_3_1.csv', [t, vm1], delimiter=',')\n```\n\n* Plot data\n\n\n```python\nt, vm1 = np.loadtxt('data/data_ex_3_1.csv',delimiter=',')\nplt.plot(t, vm1)\nplt.xlabel('t [s]')\nplt.ylabel('$V_{m}$ [V]')\nplt.title('Fig. 3: Measured values of $V_{m}$ as function of time')\n\nplt.grid()\nplt.show()\n```\n\n> We didn't set the frequency to 20 Hz because the unit of the function has some problems, according to the TA.\n\n## 3.2 Refractory period\n\nRepeat 3.1 with two other refractory period biases and compare.\n\n\n```python\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ACN_VLEAK_N,\\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 2)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ACN_VGAIN_N,\\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 6)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ACN_VDC_P,\\\n    pyplane.Coach.BiasType.P, \\\n    pyplane.Coach.BiasGenMasterCurrent.I30nA, 32)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ACN_VREFR_N,\\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I30nA, 10)]) #change refractory period\n```\n\n* read data\n\n\n```python\nvm1 = p.acquire_transient_response(pyplane.DacChannel.DAC1, pyplane.AdcChannel.AOUT10, 0.00025, 1)\nnp.savetxt('data/data_ex_3_2_base.csv', vm1, delimiter=',')\n```\n\n\n```python\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ACN_VLEAK_N,\\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 2)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ACN_VGAIN_N,\\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 6)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ACN_VDC_P,\\\n    pyplane.Coach.BiasType.P, \\\n    pyplane.Coach.BiasGenMasterCurrent.I30nA, 32)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ACN_VREFR_N,\\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I3_8nA, 1)]) #change refractory period\n```\n\n* read data\n\n\n```python\nvm2 = p.acquire_transient_response(pyplane.DacChannel.DAC1, pyplane.AdcChannel.AOUT10, 0.00025, 1)\nnp.savetxt('data/data_ex_3_2_smaller.csv', vm2, delimiter=',')\n```\n\n\n```python\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ACN_VLEAK_N,\\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 2)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ACN_VGAIN_N,\\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I60pA, 6)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ACN_VDC_P,\\\n    pyplane.Coach.BiasType.P, \\\n    pyplane.Coach.BiasGenMasterCurrent.I30nA, 32)])\n\np.send_coach_events([pyplane.Coach.generate_biasgen_event(\\\n    pyplane.Coach.BiasAddress.ACN_VREFR_N,\\\n    pyplane.Coach.BiasType.N, \\\n    pyplane.Coach.BiasGenMasterCurrent.I460pA, 20)]) #change refractory period\n```\n\n* read data\n\n\n```python\nvm3 = p.acquire_transient_response(pyplane.DacChannel.DAC1, pyplane.AdcChannel.AOUT10, 0.00025, 1)\nnp.savetxt('data/data_ex_3_2_bigger.csv', vm3, delimiter=',')\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nplt.rcParams.update({'font.size': 15})\n\nt, _ = np.loadtxt('data/data_ex_3_1.csv', delimiter=',')\nvm1 = np.loadtxt('data/data_ex_3_2_base.csv',delimiter=',')\nvm2 = np.loadtxt('data/data_ex_3_2_smaller.csv',delimiter=',')\nvm3 = np.loadtxt('data/data_ex_3_2_bigger.csv',delimiter=',')\nplt.plot(t, vm1)\nplt.title('Fig. 4: Measured values of $V_{m}$ as function of time for basic ACN_VREFR_N')\nplt.xlabel('t [s]')\nplt.ylabel('$V_{m}$ [V]')\nplt.show()\n\nplt.plot(t, vm2)\nplt.title('Fig. 5: Measured values of $V_{m}$ as function of time for smaller ACN_VREFR_N')\nplt.xlabel('t [s]')\nplt.ylabel('$V_{m}$ [V]')\nplt.grid()\nplt.show()\n\nplt.plot(t, vm3)\nplt.title('Fig. 6: Measured values of $V_{m}$ as function of time for bigger ACN_VREFR_N')\nplt.xlabel('t [s]')\nplt.ylabel('$V_{m}$ [V]')\nplt.grid()\nplt.show()\n\n\n```\n", "meta": {"hexsha": "316d89d9ead4bd91bf740651b08bc482ea03686e", "size": 636855, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "neuromorphic_engineering_one/session9_neurons/Lab9_neurons_4.5_Jan_Hohenheim.ipynb", "max_stars_repo_name": "janhohenheim/neuromorphic-engineering-one", "max_stars_repo_head_hexsha": "2923b095c4ddec935d2ea2d60685beebdd7da097", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-12-17T23:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T14:02:16.000Z", "max_issues_repo_path": "neuromorphic_engineering_one/session9_neurons/Lab9_neurons_4.5_Jan_Hohenheim.ipynb", "max_issues_repo_name": "janhohenheim/neuromorphic-engineering-one", "max_issues_repo_head_hexsha": "2923b095c4ddec935d2ea2d60685beebdd7da097", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "neuromorphic_engineering_one/session9_neurons/Lab9_neurons_4.5_Jan_Hohenheim.ipynb", "max_forks_repo_name": "janhohenheim/neuromorphic-engineering-one", "max_forks_repo_head_hexsha": "2923b095c4ddec935d2ea2d60685beebdd7da097", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-08T19:15:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-08T19:15:40.000Z", "avg_line_length": 567.6069518717, "max_line_length": 297976, "alphanum_fraction": 0.9498033304, "converted": true, "num_tokens": 5748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4111108836623764, "lm_q2_score": 0.0769608282861997, "lm_q1q2_score": 0.03163943412412797}}
{"text": "<center>\n<h1>Introduction to Jet Images and Computer Vision</h1>\n<h3>Michela Paganini - Yale University</h3>\n<h4>High Energy Phenomenology, Experiment and Cosmology Seminar Series</h4>\n\n</center>\n\n\nMaterial:\n 1. Ben Nachman's plenary talk at ACAT 2017 (<a href=\"https://indico.cern.ch/event/567550/contributions/2656471/attachments/1510207/2354761/Nachman_ACAT.pdf\">slides</a>)\n 1. My talk on Generative Adversarial Networks for jet images at the 2017 IML Workshop (<a href=\"http://cds.cern.ch/record/2256878?ln=en\">video</a>)\n 1. Jannicke Pearkes's talk on boosted top tagging with jet images at the 2017 IML Workshop (<a href=\"http://cds.cern.ch/record/2256876?ln=en\">video</a>)\n 1. Michael Kagan's overview talk at LHCP 2017 (<a href=\"https://cds.cern.ch/record/2267879?ln=en\">slides</a>)\n 1. ATLAS PUB Note on quark vs gluon tagging with jet images(<a href=\"https://cds.cern.ch/record/2275641/files/ATL-PHYS-PUB-2017-017.pdf\">note</a>)\n 1. Lynn Huynh's summer report on jet image pre-processing (<a href=\"https://cds.cern.ch/record/2209127/files/Lynn_Huynh_Report.pdf\">write-up</a>)\n 1. Ben Nachman's talk at DataScience@LHC 2015 (<a href=\"http://cds.cern.ch/record/2069153\">video</a>)\n\n# Dataset\n\n[](https://doi.org/10.17632/4r4v785rgx.1)\n\n<a href=\"https://zenodo.org/record/269622#.WgZFPRNSyRs\"></a>\n\nAlthough the dataset was released in conjunction with the arXiv publication of our [work on Generative Adversarial Networks for jet images](https://arxiv.org/pdf/1701.05927.pdf), it was previously used in the original \"[Jet Images -- Deep Learning Edition](https://link.springer.com/article/10.1007%2FJHEP07%282016%29069)\" work on jet image classification. Feel free to explore the dataset and use it for any project you have in mind (please cite the dataset and relevant publications explaining its generation!)\n\n### Download dataset from Zenodo\n\n\n```python\nimport os\nfrom keras.utils.data_utils import get_file\n\n# Info for downloading the dataset from Zenodo\nMD5_HASH = 'f9b11c46b6a0ff928bec2eccf865ecf0'\nDATAFILE = 'jet-images_Mass60-100_pT250-300_R1.25_Pix25.hdf5'\nURL_TEMPLATE = 'https://zenodo.org/record/{record}/files/{filename}'\n\nprint('[INFO] MD5 verification: {}'.format(MD5_HASH))\n\ndatafile = get_file(\n    fname=DATAFILE,\n    origin=URL_TEMPLATE.format(record=269622, filename=DATAFILE),\n    md5_hash=MD5_HASH\n)\n```\n\n    Using TensorFlow backend.\n\n\n    [INFO] MD5 verification: f9b11c46b6a0ff928bec2eccf865ecf0\n\n\n# Jets at the LHC\n\n\n\nJets are the observable result of quarks and gluons scattering at high energy. A collimated stream of\nprotons and other hadrons forms in the direction of the initiating quark or gluon. Clusters of such\nparticles are called jets.\n\n# Jet Images\n\nMature field of research! (image courtesy of B.P.Nachman) \n\n<a href=\"https://arxiv.org/abs/1709.04464\"></a>\n\n\n### What is a jet image?\n\n\n\n> A jet image is a two-dimensional representation of the radiation pattern within a jet: the distribution of the locations and energies of the jet\u2019s constituent particles. The jet image consists of a regular grid of pixels in \u03b7\u00d7\u03c6. \n\nAdvantages of this data format include: easy visual inspection, fixed-length representation, suitable for application of computer vision techniques.\n\n### Pre-processing\n\nIn the dataset we will be using today:\n\n> The finite granularity of a calorimeter is simulated with a regular 0.1\u00d70.1 grid in \u03b7 and \u03c6. The energy of each calorimeter cell is given by the sum of the energies of all particles incident on the cell. Cells with positive energy are assigned to jets using the anti-kt clustering algorithm with a radius parameter of R = 1.0 via the software package FastJet 3.2.1.\n\n> To mitigate the contribution from the underlying event, jets are are trimmed by re-clustering the constituents into R = 0.3 kt subjets and dropping those which have less than 5% of the transverse momentum of the parent jet. Trimming also reduces the impact of pileup: multiple proton-proton collisions occurring in the same event as the hard-scatter process. Jet images are formed by translating the \u03b7 and \u03c6 of all constituents of a given jet so that its highest pT subjet is centered at the origin.\n\n> A rectangular grid of \u03b7 \u00d7 \u03c6 \u2208 [\u22121.25, 1.25] \u00d7 [\u22121.25, 1.25] with 0.1 \u00d7 0.1 pixels centered at the origin\nforms the basis of the jet image. The intensity of each pixel is the pT corresponding to the energy\nand pseudorapditiy of the constituent calorimeter cell, pT = E_cell/ cosh(\u03b7_cell). The radiation pattern\nis symmetric about the origin of the jet image and so the images are rotated. The subjet with the\nsecond highest pT (or, in its absence, the direction of the first principle component) is placed at an\nangle of \u2212\u03c0/2 with respect to the \u03b7 \u2212 \u03c6 axes. Finally, a parity transform about the vertical axis is\napplied if the left side of the image has more energy than the right side.\n\n<div align=\"right\">\n  <i>Learning Particle Physics by Example: Location-Aware Generative Adversarial Networks for Physics Synthesis</i> <br>\n  [arXiv:1701.05927](https://arxiv.org/pdf/1701.05927.pdf)\n</div>\n\nReferences: \n* Section 3 of [arXiv:1511.05190](https://link.springer.com/content/pdf/10.1007%2FJHEP07%282016%29069.pdf)\n* <a href=\"https://link.springer.com/article/10.1007/s41781-017-0004-6#Sec16\">Appendix B</a> of [arXiv:1701.05927](https://arxiv.org/pdf/1701.05927.pdf)\n\n### Uniqueness with respect to natural images in ML literature\n\n* Sparse (low occupancy)\n* High dynamic range (pixel intensity represents pT of particles and spans several orders of magnitude)\n* Pixel activations and positions are physically meaningful\n* Small variations can drastically modify physical properties of a jet\n\n# Hands-on tutorial\n\n\n```python\nimport h5py\nimport numpy as np\nimport os\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfrom matplotlib.colors import LogNorm, Normalize\n%matplotlib inline\n```\n\n\n```python\n# number of images to load\nnb_points = 800000\n```\n\n\n```python\n# open hdf5 data file\nd = h5py.File(datafile, 'r')\n```\n\n\n```python\n# content of the dataset\nd.items()\n```\n\n\n\n\n    [(u'image', <HDF5 dataset \"image\": shape (872666, 25, 25), type \"<f4\">),\n     (u'jet_delta_R', <HDF5 dataset \"jet_delta_R\": shape (872666,), type \"<f4\">),\n     (u'jet_eta', <HDF5 dataset \"jet_eta\": shape (872666,), type \"<f4\">),\n     (u'jet_mass', <HDF5 dataset \"jet_mass\": shape (872666,), type \"<f4\">),\n     (u'jet_phi', <HDF5 dataset \"jet_phi\": shape (872666,), type \"<f4\">),\n     (u'jet_pt', <HDF5 dataset \"jet_pt\": shape (872666,), type \"<f4\">),\n     (u'signal', <HDF5 dataset \"signal\": shape (872666,), type \"<f4\">),\n     (u'tau_1', <HDF5 dataset \"tau_1\": shape (872666,), type \"<f4\">),\n     (u'tau_2', <HDF5 dataset \"tau_2\": shape (872666,), type \"<f4\">),\n     (u'tau_21', <HDF5 dataset \"tau_21\": shape (872666,), type \"<f4\">),\n     (u'tau_3', <HDF5 dataset \"tau_3\": shape (872666,), type \"<f4\">),\n     (u'tau_32', <HDF5 dataset \"tau_32\": shape (872666,), type \"<f4\">)]\n\n\n\n\n```python\n# extract a random subset of samples\nix = range(d['image'].shape[0]) # get indices\nnp.random.shuffle(ix) # shuffle them\nix = ix[:nb_points] # select out nb_points\n\n# extract data from dataset\nimages, labels = d['image'][:][ix], d['signal'][:][ix]\nmass = d['jet_mass'][:][ix]\ndelta_R = d['jet_delta_R'][:][ix]\ntau_21 = d['tau_21'][:][ix]\n```\n\nYou can compute the quantities above directly from the images:\n\n\\begin{align}\n&p_\\text{T}^2(I) =\\left(\\sum_{i=0}^{N} I_i\\cos(\\phi_i)\\right)^2+\\left(\\sum_{i=0}^{N} I_i\\sin(\\phi_i)\\right)^2\n\\label{eq:pt}\n\\\\\n&m^2(I) = \\left(\\sum_{i=0}^{N} I_i\\right)^2-p_\\text{T}^2(I)-\\left(\\sum_{i=0}^{N} I_i\\sinh(\\eta_i)\\right)^2\n\\label{eq:m}\n\\\\\n&\\tau_{21}(I)=\\frac{\\tau_2(I)}{\\tau_1(I)},\n\\label{eq:tau21}\n\\end{align}\nwhere:\n\\begin{equation*}\n\\tau_{n}(I)\\propto\\sum_{i=0}^{N} I_i \\min_{1\\leq a\\leq n}\\left\\{\\sqrt{\\left(\\eta_i-\\eta_a\\right)^2+\\left(\\phi_i-\\phi_a\\right)^2}\\right\\}\n\\end{equation*}\n\n\n```python\ndef plot_jet_image(content, output_fname=None, vmin=1e-6, vmax=300, title=''):\n    '''\n    Function to help you visualize a jet image on a log scale\n    Args:\n    -----\n        content : numpy array of dimensions 25x25, first arg to imshow, \n            content of the image\n            e.g.: images.mean(axis=0) --> the average image\n\n        output_fname : string, name of the output file where the plot will be \n            saved. \n\n        vmin : (default = 1e-6) float, lower bound of the pixel intensity \n            scale before saturation\n\n        vmax : (default = 300) float, upper bound of the pixel intensity \n            scale before saturation\n\n        title : (default = '') string, title of the plot, to be displayed \n            on top of the image\n    '''\n    fig, ax = plt.subplots(figsize=(7, 6))\n    extent = [-1.25, 1.25, -1.25, 1.25]\n\n    im = ax.imshow(content, interpolation='nearest',\n                   norm=LogNorm(vmin=vmin, vmax=vmax), extent=extent)\n\n    cbar = plt.colorbar(im, fraction=0.05, pad=0.05)\n    cbar.set_label(r'Pixel $p_T$ (GeV)', y=0.85)\n    plt.xlabel(r'[Transformed] Pseudorapidity $(\\eta)$')\n    plt.ylabel(r'[Transformed] Azimuthal Angle $(\\phi)$')\n    plt.title(title)\n\n    if output_fname is None:\n        plt.savefig(output_fname)\n```\n\n\n```python\ndef plot_diff_jet_image(content, output_fname=None, extr=None, title='',\n                        cmap=matplotlib.cm.seismic):\n    '''\n    Function to help you visualize the difference between two sets of jet \n        images on a linear scale\n    Args:\n    -----\n        content : numpy array of dimensions 25x25, first arg to imshow, \n            content of the image\n            e.g.: sig_images.mean(axis=0) - bkg_images.mean(axis=0)\n        output_fname : string, name of the output file where the plot will be \n            saved.\n        extr : (default = None) float, magnitude of the upper and lower \n            bounds of the pixel intensity scale before saturation (symmetric \n            around 0)\n        title : (default = '') string, title of the plot, to be displayed on \n            top of the image\n        cmap : (default = matplotlib.cm.PRGn_r) matplotlib colormap, ideally \n            white in the middle\n    '''\n    fig, ax = plt.subplots(figsize=(6, 6))\n    extent = [-1.25, 1.25, -1.25, 1.25]\n    if extr == None:\n        extr = max(abs(content.min()), abs(content.max()))\n    im = ax.imshow(\n        content,\n        interpolation='nearest',\n        norm=Normalize(vmin=-extr, vmax=+extr), extent=extent,\n        cmap=cmap\n    )\n\n    plt.colorbar(im, fraction=0.05, pad=0.05)\n    plt.xlabel(r'[Transformed] Pseudorapidity $(\\eta)$')\n    plt.ylabel(r'[Transformed] Azimuthal Angle $(\\phi)$')\n    plt.title(title)\n\n    if output_fname:\n        plt.savefig(output_fname)\n\n```\n\n\n```python\n# visualize a jet image\nplot_jet_image(images[0])\n```\n\n\n```python\n# visualize the average jet image\nplot_jet_image(images.mean(axis=0))\n```\n\n\n```python\n# visualize the difference between the average signal and the average background image\nplot_diff_jet_image(\n    images[labels == 1].mean(axis=0) - images[labels == 0].mean(axis=0)\n)\n```\n\n## Looking at Physics features\n\n\n```python\ndef plot_physics_feature(feature_name, feature, labels, bins=None, output_fname=None):\n\n    # if bins are not defined when function is called, define them here\n    if not bins:\n        bins = np.linspace(feature.min(), feature.max(), 50)\n\n    fig, ax = plt.subplots(figsize=(6, 6))\n\n    _ = plt.hist(feature[labels == 1], bins=bins, histtype='step',\n                 label=r\"Signal ($W' \\rightarrow WZ$)\",\n                 normed=True, color='red')\n\n    _ = plt.hist(feature[labels == 0], bins=bins, histtype='step',\n                 label=r'Background (QCD dijets)', normed=True, color='blue')\n\n    plt.xlabel(r'Discretized {} of Jet Image'.format(feature_name))\n    plt.ylabel(r'Units normalized to unit area')\n    plt.legend()\n\n    if output_fname:\n        plt.savefig(output_fname)\n\n```\n\n\n```python\nplot_physics_feature(r'$m$', mass, labels)\n```\n\n\n```python\nplot_physics_feature(r'$\\Delta R$', delta_R, labels)\n```\n\n\n```python\nplot_physics_feature(r'$\\tau_{2,1}$', tau_21, labels)\n```\n\n# Jet Image Classification\n\nWe can now try to use various techniques to classify the jet images into signal (i.e. originating from boosted W bosons) and background (QCD).\n\nWe will start with a classic feature-based classifier, which will use properties of the jet such as mass, tau_21, and delta_R (known to have good discriminative power) to separate the two classes.\n\nThen, we will construct different networks that operate directly at the pixel level and compare them all.\n\n## Simple feature-based classifier\n\n#### Data processing\n\nFollow the procedure from yesterday to create your matrix of features X. Shuffle its entries, split them into train, test, and validation set, and scale them to zero mean and unit standard deviation.\n\n\n```python\nfeatures = np.stack((mass, tau_21, delta_R)).T # What we called X yesterday\n```\n\n\n```python\nfeatures\n```\n\n\n\n\n    array([[  8.32666473e+01,   2.04822451e-01,   5.39974034e-01],\n           [  8.12588806e+01,   1.50861815e-01,   7.13163793e-01],\n           [  9.46128769e+01,   4.19182539e-01,   4.54179347e-01],\n           ..., \n           [  6.23480110e+01,   6.62943900e-01,   5.78597903e-01],\n           [  8.06691437e+01,   8.02331641e-02,   6.24256849e-01],\n           [  6.91418457e+01,   4.10301745e-01,   7.06015885e-01]], dtype=float32)\n\n\n\n\n```python\nfrom sklearn.model_selection import train_test_split\n```\n\n\n```python\n# 80% train+validate, 20% test\nimages_train, images_test, \\\n    labels_train, labels_test, \\\n    features_train, features_test \\\n    = train_test_split(images, labels, features,\n                       test_size=0.2)\n\n# 64% train, 16% validate\nimages_train, images_val, \\\n    labels_train, labels_val, \\\n    features_train, features_val \\\n    = train_test_split(images_train, labels_train, features_train,\n                       test_size=0.2)\n```\n\n\n```python\nprint ('{} training samples\\n{} validation samples\\n{} testing samples'\n       .format(images_train.shape[0], images_val.shape[0], images_test.shape[0]))\n```\n\n    512000 training samples\n    128000 validation samples\n    160000 testing samples\n\n\n\n```python\nfrom sklearn.preprocessing import StandardScaler\n```\n\n\n```python\nscaler = StandardScaler()\nfeatures_train = scaler.fit_transform(features_train)\nfeatures_val = scaler.transform(features_val)\nfeatures_test = scaler.transform(features_test)\n```\n\n#### Model\n\nBuild a simple keras model made of fully-connected (Dense) layers. Remember the steps:\n1. Define the symbolic graph by connecting layers\n1. Define an optimizer and a loss function to minimize\n1. Train ('fit') the model to the training dataset, monitoring whether the validation loss continues to decrease\n1. Stop the training automatically when the validation loss stops going down\n1. Evaluate performance on test set\n\nRecall activation functions: Rectified Linear Unit (relu) vs. Leaky Rectified Linear Unit\n\n\n\n```python\nfrom keras.layers import Input, Dense, Dropout\nfrom keras.models import Model\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\n```\n\n    Using TensorFlow backend.\n\n\n\n```python\nx = Input(shape=(features_train.shape[1], ))\nh = Dense(64, activation='relu')(x)\nh = Dense(64, activation='relu')(h)\nh = Dense(64, activation='relu')(h)\ny = Dense(1, activation='sigmoid')(h)\n```\n\n\n```python\nbaseline_model = Model(x, y)\nbaseline_model.compile('adam', 'binary_crossentropy', metrics=['acc'])\n```\n\nThe command below trains the model. However, in the interest of time, I will not train the network on the spot. I will instead load in pre-trained weights from a training I performed last night.\n\n\n```python\n# baseline_model.fit(\n#     features_train, labels_train, # X and y\n#     epochs=200,\n#     batch_size=128,\n#     validation_data=(features_val, labels_val), # validation X and y\n#     callbacks=[\n#         EarlyStopping(verbose=True, patience=15, monitor='val_loss'),\n#         ModelCheckpoint('./models/baseline-model.h5', monitor='val_loss',\n#                         verbose=True, save_best_only=True)\n#     ]\n# )\n```\n\n    Train on 512000 samples, validate on 128000 samples\n    Epoch 1/200\n    511616/512000 [============================>.] - ETA: 0s - loss: 0.4542 - acc: 0.7907Epoch 00001: val_loss improved from inf to 0.45350, saving model to ./models/baseline-model.h5\n    512000/512000 [==============================] - 20s 39us/step - loss: 0.4542 - acc: 0.7907 - val_loss: 0.4535 - val_acc: 0.7908\n    Epoch 2/200\n    511360/512000 [============================>.] - ETA: 0s - loss: 0.4515 - acc: 0.7923Epoch 00002: val_loss improved from 0.45350 to 0.45273, saving model to ./models/baseline-model.h5\n    512000/512000 [==============================] - 20s 39us/step - loss: 0.4515 - acc: 0.7923 - val_loss: 0.4527 - val_acc: 0.7908\n    Epoch 3/200\n    510720/512000 [============================>.] - ETA: 0s - loss: 0.4510 - acc: 0.7925Epoch 00003: val_loss improved from 0.45273 to 0.45222, saving model to ./models/baseline-model.h5\n    512000/512000 [==============================] - 19s 38us/step - loss: 0.4510 - acc: 0.7925 - val_loss: 0.4522 - val_acc: 0.7916\n    Epoch 4/200\n    511104/512000 [============================>.] - ETA: 0s - loss: 0.4508 - acc: 0.7929Epoch 00004: val_loss improved from 0.45222 to 0.45193, saving model to ./models/baseline-model.h5\n    512000/512000 [==============================] - 20s 38us/step - loss: 0.4508 - acc: 0.7929 - val_loss: 0.4519 - val_acc: 0.7913\n    Epoch 5/200\n    511744/512000 [============================>.] - ETA: 0s - loss: 0.4507 - acc: 0.7928Epoch 00005: val_loss improved from 0.45193 to 0.45179, saving model to ./models/baseline-model.h5\n    512000/512000 [==============================] - 18s 35us/step - loss: 0.4506 - acc: 0.7928 - val_loss: 0.4518 - val_acc: 0.7916\n    Epoch 6/200\n    511488/512000 [============================>.] - ETA: 0s - loss: 0.4504 - acc: 0.7928Epoch 00006: val_loss did not improve\n    512000/512000 [==============================] - 20s 38us/step - loss: 0.4504 - acc: 0.7928 - val_loss: 0.4527 - val_acc: 0.7908\n    Epoch 7/200\n    511616/512000 [============================>.] - ETA: 0s - loss: 0.4504 - acc: 0.7927Epoch 00007: val_loss did not improve\n    512000/512000 [==============================] - 19s 37us/step - loss: 0.4504 - acc: 0.7927 - val_loss: 0.4523 - val_acc: 0.7918\n    Epoch 8/200\n    510592/512000 [============================>.] - ETA: 0s - loss: 0.4503 - acc: 0.7929Epoch 00008: val_loss did not improve\n    512000/512000 [==============================] - 19s 37us/step - loss: 0.4503 - acc: 0.7930 - val_loss: 0.4526 - val_acc: 0.7910\n    Epoch 9/200\n    511616/512000 [============================>.] - ETA: 0s - loss: 0.4502 - acc: 0.7929Epoch 00009: val_loss did not improve\n    512000/512000 [==============================] - 18s 36us/step - loss: 0.4502 - acc: 0.7928 - val_loss: 0.4522 - val_acc: 0.7913\n    Epoch 10/200\n    510592/512000 [============================>.] - ETA: 0s - loss: 0.4502 - acc: 0.7929Epoch 00010: val_loss improved from 0.45179 to 0.45176, saving model to ./models/baseline-model.h5\n    512000/512000 [==============================] - 19s 38us/step - loss: 0.4502 - acc: 0.7929 - val_loss: 0.4518 - val_acc: 0.7914\n    Epoch 11/200\n    511104/512000 [============================>.] - ETA: 0s - loss: 0.4502 - acc: 0.7927Epoch 00011: val_loss did not improve\n    512000/512000 [==============================] - 19s 37us/step - loss: 0.4501 - acc: 0.7927 - val_loss: 0.4532 - val_acc: 0.7906\n    Epoch 12/200\n    510720/512000 [============================>.] - ETA: 0s - loss: 0.4501 - acc: 0.7929Epoch 00012: val_loss did not improve\n    512000/512000 [==============================] - 19s 37us/step - loss: 0.4501 - acc: 0.7929 - val_loss: 0.4523 - val_acc: 0.7914\n    Epoch 13/200\n    511616/512000 [============================>.] - ETA: 0s - loss: 0.4501 - acc: 0.7928Epoch 00013: val_loss did not improve\n    512000/512000 [==============================] - 19s 38us/step - loss: 0.4501 - acc: 0.7928 - val_loss: 0.4524 - val_acc: 0.7916\n    Epoch 14/200\n    511232/512000 [============================>.] - ETA: 0s - loss: 0.4499 - acc: 0.7928Epoch 00014: val_loss did not improve\n    512000/512000 [==============================] - 19s 37us/step - loss: 0.4499 - acc: 0.7929 - val_loss: 0.4522 - val_acc: 0.7913\n    Epoch 15/200\n    511488/512000 [============================>.] - ETA: 0s - loss: 0.4500 - acc: 0.7929Epoch 00015: val_loss did not improve\n    512000/512000 [==============================] - 19s 37us/step - loss: 0.4500 - acc: 0.7929 - val_loss: 0.4519 - val_acc: 0.7914\n    Epoch 16/200\n    511360/512000 [============================>.] - ETA: 0s - loss: 0.4498 - acc: 0.7929Epoch 00016: val_loss did not improve\n    512000/512000 [==============================] - 19s 37us/step - loss: 0.4499 - acc: 0.7929 - val_loss: 0.4519 - val_acc: 0.7914\n    Epoch 17/200\n    511232/512000 [============================>.] - ETA: 0s - loss: 0.4498 - acc: 0.7932Epoch 00017: val_loss did not improve\n    512000/512000 [==============================] - 19s 37us/step - loss: 0.4498 - acc: 0.7932 - val_loss: 0.4529 - val_acc: 0.7903\n    Epoch 18/200\n    511616/512000 [============================>.] - ETA: 0s - loss: 0.4498 - acc: 0.7928Epoch 00018: val_loss improved from 0.45176 to 0.45162, saving model to ./models/baseline-model.h5\n    512000/512000 [==============================] - 19s 36us/step - loss: 0.4498 - acc: 0.7928 - val_loss: 0.4516 - val_acc: 0.7916\n    Epoch 19/200\n    510848/512000 [============================>.] - ETA: 0s - loss: 0.4497 - acc: 0.7930Epoch 00019: val_loss did not improve\n    512000/512000 [==============================] - 19s 37us/step - loss: 0.4498 - acc: 0.7930 - val_loss: 0.4523 - val_acc: 0.7913\n    Epoch 20/200\n    511744/512000 [============================>.] - ETA: 0s - loss: 0.4497 - acc: 0.7932Epoch 00020: val_loss did not improve\n    512000/512000 [==============================] - 19s 36us/step - loss: 0.4497 - acc: 0.7932 - val_loss: 0.4522 - val_acc: 0.7912\n    Epoch 21/200\n    511232/512000 [============================>.] - ETA: 0s - loss: 0.4498 - acc: 0.7928Epoch 00021: val_loss did not improve\n    512000/512000 [==============================] - 19s 37us/step - loss: 0.4498 - acc: 0.7929 - val_loss: 0.4523 - val_acc: 0.7918\n    Epoch 22/200\n    511104/512000 [============================>.] - ETA: 0s - loss: 0.4497 - acc: 0.7932Epoch 00022: val_loss did not improve\n    512000/512000 [==============================] - 19s 37us/step - loss: 0.4497 - acc: 0.7931 - val_loss: 0.4522 - val_acc: 0.7920\n    Epoch 23/200\n    511104/512000 [============================>.] - ETA: 0s - loss: 0.4498 - acc: 0.7932Epoch 00023: val_loss did not improve\n    512000/512000 [==============================] - 19s 37us/step - loss: 0.4498 - acc: 0.7932 - val_loss: 0.4517 - val_acc: 0.7917\n    Epoch 24/200\n    510720/512000 [============================>.] - ETA: 0s - loss: 0.4497 - acc: 0.7934Epoch 00024: val_loss did not improve\n    512000/512000 [==============================] - 19s 37us/step - loss: 0.4497 - acc: 0.7933 - val_loss: 0.4531 - val_acc: 0.7914\n    Epoch 25/200\n    511232/512000 [============================>.] - ETA: 0s - loss: 0.4496 - acc: 0.7932Epoch 00025: val_loss did not improve\n    512000/512000 [==============================] - 19s 38us/step - loss: 0.4497 - acc: 0.7931 - val_loss: 0.4520 - val_acc: 0.7917\n    Epoch 26/200\n    511744/512000 [============================>.] - ETA: 0s - loss: 0.4496 - acc: 0.7932Epoch 00026: val_loss did not improve\n    512000/512000 [==============================] - 19s 37us/step - loss: 0.4496 - acc: 0.7932 - val_loss: 0.4525 - val_acc: 0.7914\n    Epoch 27/200\n    511360/512000 [============================>.] - ETA: 0s - loss: 0.4496 - acc: 0.7932Epoch 00027: val_loss did not improve\n    512000/512000 [==============================] - 19s 37us/step - loss: 0.4496 - acc: 0.7932 - val_loss: 0.4518 - val_acc: 0.7922\n    Epoch 28/200\n    511360/512000 [============================>.] - ETA: 0s - loss: 0.4495 - acc: 0.7931Epoch 00028: val_loss did not improve\n    512000/512000 [==============================] - 19s 37us/step - loss: 0.4496 - acc: 0.7931 - val_loss: 0.4522 - val_acc: 0.7915\n    Epoch 29/200\n    511232/512000 [============================>.] - ETA: 0s - loss: 0.4496 - acc: 0.7932Epoch 00029: val_loss did not improve\n    512000/512000 [==============================] - 19s 36us/step - loss: 0.4496 - acc: 0.7932 - val_loss: 0.4519 - val_acc: 0.7913\n    Epoch 30/200\n    510720/512000 [============================>.] - ETA: 0s - loss: 0.4496 - acc: 0.7933Epoch 00030: val_loss did not improve\n    512000/512000 [==============================] - 19s 38us/step - loss: 0.4495 - acc: 0.7933 - val_loss: 0.4522 - val_acc: 0.7913\n    Epoch 31/200\n    511360/512000 [============================>.] - ETA: 0s - loss: 0.4496 - acc: 0.7930Epoch 00031: val_loss did not improve\n    512000/512000 [==============================] - 19s 38us/step - loss: 0.4496 - acc: 0.7930 - val_loss: 0.4518 - val_acc: 0.7916\n    Epoch 32/200\n    510080/512000 [============================>.] - ETA: 0s - loss: 0.4495 - acc: 0.7932Epoch 00032: val_loss did not improve\n    512000/512000 [==============================] - 19s 37us/step - loss: 0.4495 - acc: 0.7932 - val_loss: 0.4521 - val_acc: 0.7919\n    Epoch 33/200\n    510336/512000 [============================>.] - ETA: 0s - loss: 0.4495 - acc: 0.7934Epoch 00033: val_loss did not improve\n    512000/512000 [==============================] - 18s 36us/step - loss: 0.4495 - acc: 0.7933 - val_loss: 0.4523 - val_acc: 0.7914\n    Epoch 00033: early stopping\n\n\n\n\n\n    <keras.callbacks.History at 0x7f68c898ab50>\n\n\n\nIf you were to actually run the training, you would be able to visualize its history. Keras saves the entire training history, keeping track of whatever metric you specify (here accuracy and loss).\n\n\n```python\nhistory = baseline_model.history.history\nhistory.keys()\n```\n\n\n\n\n    ['acc', 'loss', 'val_acc', 'val_loss']\n\n\n\n\n```python\n# accuracy plot\nplt.plot(100 * np.array(history['acc']), label='training')\nplt.plot(100 * np.array(history['val_acc']), label='validation')\nplt.xlim(0)\nplt.xlabel('epoch')\nplt.ylabel('accuracy %')\nplt.legend(loc='lower right', fontsize=20)\nplt.show()\n```\n\n\n```python\n# loss plot\nplt.plot(100 * np.array(history['loss']), label='training')\nplt.plot(100 * np.array(history['val_loss']), label='validation')\nplt.xlim(0)\nplt.xlabel('epoch')\nplt.ylabel('loss')\nplt.legend(loc='upper right', fontsize=20)\n# the line indicate the epoch corresponding to the best performance on the validation set\n# plt.vlines(np.argmin(history['val_loss']), 45, 56, linestyle='dashed', linewidth=0.5)\nplt.show()\n```\n\n\n```python\nprint 'Loss estimate on unseen examples (from validation set) = {0:.3f}'.format(np.min(history['val_loss']))\n```\n\n    Loss estimate on unseen examples (from validation set) = 0.452\n\n\n#### Evaluate on test set\n\n\n```python\nbaseline_model.load_weights('./models/baseline-model.h5')\n```\n\n\n```python\nyhat_baseline = baseline_model.predict(features_test, batch_size=512)\n```\n\n\n```python\nbins = np.linspace(0, 1, 20)\n_ = plt.hist(yhat_baseline[labels_test==1],\n         histtype='stepfilled', alpha=0.5, color='red', label=r\"Signal ($W' \\rightarrow WZ$)\", bins=bins)\n_ = plt.hist(yhat_baseline[labels_test==0],\n         histtype='stepfilled', alpha=0.5, color='blue', label=r'Background (QCD dijets)', bins=bins)\nplt.legend(loc='upper center')\nplt.xlabel('P(signal) assigned by the baseline model')\n```\n\n## Convolutional Neural Network\n\nWe can now instead try to learn a model directly on the pixel space, instead of summarizing the information into engineered features such as mass, tau_21 and delta_R.\n\n\n```python\nfrom keras.layers import Conv2D, Flatten, LeakyReLU\n```\n\n\n```python\n# add channel dimension (1 for grayscale)\nimages_train = np.expand_dims(images_train, -1)\nimages_test = np.expand_dims(images_test, -1)\nimages_val = np.expand_dims(images_val, -1)\n```\n\n\n```python\nx = Input(shape=(images_train.shape[1:]))\nh = Conv2D(32, kernel_size=7, strides=1)(x)\nh = LeakyReLU()(h)\nh = Dropout(0.2)(h)\n\nh = Conv2D(64, kernel_size=7, strides=1)(h)\nh = LeakyReLU()(h)\nh = Dropout(0.2)(h)\n\nh = Conv2D(128, kernel_size=5, strides=1)(h)\nh = LeakyReLU()(h)\nh = Dropout(0.2)(h)\n\nh = Conv2D(256, kernel_size=5, strides=1)(h)\nh = LeakyReLU()(h)\nh = Flatten()(h)\nh = Dropout(0.2)(h)\ny = Dense(1, activation='sigmoid')(h)\n```\n\n\n```python\ncnn_model = Model(x, y)\ncnn_model.compile('adam', 'binary_crossentropy', metrics=['acc'])\n```\n\n\n```python\ncnn_model.summary()\n```\n\n    _________________________________________________________________\n    Layer (type)                 Output Shape              Param #   \n    =================================================================\n    input_3 (InputLayer)         (None, 25, 25, 1)         0         \n    _________________________________________________________________\n    conv2d_2 (Conv2D)            (None, 19, 19, 32)        1600      \n    _________________________________________________________________\n    leaky_re_lu_1 (LeakyReLU)    (None, 19, 19, 32)        0         \n    _________________________________________________________________\n    dropout_1 (Dropout)          (None, 19, 19, 32)        0         \n    _________________________________________________________________\n    conv2d_3 (Conv2D)            (None, 13, 13, 64)        100416    \n    _________________________________________________________________\n    leaky_re_lu_2 (LeakyReLU)    (None, 13, 13, 64)        0         \n    _________________________________________________________________\n    dropout_2 (Dropout)          (None, 13, 13, 64)        0         \n    _________________________________________________________________\n    conv2d_4 (Conv2D)            (None, 9, 9, 128)         204928    \n    _________________________________________________________________\n    leaky_re_lu_3 (LeakyReLU)    (None, 9, 9, 128)         0         \n    _________________________________________________________________\n    dropout_3 (Dropout)          (None, 9, 9, 128)         0         \n    _________________________________________________________________\n    conv2d_5 (Conv2D)            (None, 5, 5, 256)         819456    \n    _________________________________________________________________\n    leaky_re_lu_4 (LeakyReLU)    (None, 5, 5, 256)         0         \n    _________________________________________________________________\n    flatten_1 (Flatten)          (None, 6400)              0         \n    _________________________________________________________________\n    dropout_4 (Dropout)          (None, 6400)              0         \n    _________________________________________________________________\n    dense_5 (Dense)              (None, 1)                 6401      \n    =================================================================\n    Total params: 1,132,801\n    Trainable params: 1,132,801\n    Non-trainable params: 0\n    _________________________________________________________________\n\n\nFeel free to try to train it at home! For this tutorial, we will just load in pre-trained weights.\n\n\n```python\n# cnn_model.fit(\n#     images_train, labels_train,\n#     epochs=100,\n#     batch_size=512,\n#     validation_data=(images_val, labels_val),\n#     callbacks=[\n#         EarlyStopping(verbose=True, patience=30, monitor='val_loss'),\n#         ModelCheckpoint('./models/cnn-model.h5', monitor='val_loss',\n#                         verbose=True, save_best_only=True)\n#     ]\n# )\n```\n\n\n```python\ncnn_history = cnn_model.history.history\n```\n\n\n```python\n# accuracy plot\nplt.plot(100 * np.array(cnn_history['acc']), label='training')\nplt.plot(100 * np.array(cnn_history['val_acc']), label='validation')\nplt.xlim(0)\nplt.xlabel('epoch')\nplt.ylabel('accuracy %')\nplt.legend(loc='lower right', fontsize=20)\nplt.show()\n```\n\n\n```python\n# loss plot\nplt.plot(100 * np.array(cnn_history['loss']), label='training')\nplt.plot(100 * np.array(cnn_history['val_loss']), label='validation')\nplt.xlim(0)\nplt.xlabel('epoch')\nplt.ylabel('loss')\nplt.legend(loc='upper right', fontsize=20)\n# the line indicate the epoch corresponding to the best performance on the validation set\nplt.vlines(np.argmin(cnn_history['val_loss']), 43, 56, linestyle='dashed', linewidth=0.5)\nplt.show()\n```\n\n\n```python\nprint 'Loss estimate on unseen examples (from validation set) = {0:.3f}'.format(np.min(cnn_history['val_loss']))\n```\n\n    Loss estimate on unseen examples (from validation set) = 0.398\n\n\n\n```python\ncnn_model.load_weights('models/cnn-model.h5')\nyhat_cnn = cnn_model.predict(images_test, batch_size=512, verbose=True)\n```\n\n    160000/160000 [==============================] - 585s 4ms/step\n\n\n## Locally-Connected Neural Network\n\n\n```python\nfrom keras.layers import LocallyConnected2D , MaxPool2D, Flatten\n```\n\n\n```python\nx = Input(shape=(images_train.shape[1:]))\nh = LocallyConnected2D(32, kernel_size=9, strides=2)(x)\nh = LeakyReLU()(h)\n\nh = Dropout(0.2)(h)\nh = LocallyConnected2D(32, kernel_size=5, strides=1)(h)\nh = LeakyReLU()(h)\n\nh = Dropout(0.2)(h)\nh = LocallyConnected2D(64, kernel_size=3, strides=1)(h)\nh = LeakyReLU()(h)\n\nh = Dropout(0.2)(h)\nh = LocallyConnected2D(64, kernel_size=3, strides=1)(h)\nh = LeakyReLU()(h)\n\nh = Flatten()(h)\nh = Dropout(0.2)(h)\ny = Dense(1, activation='sigmoid')(h)\n```\n\n\n```python\nlcn_model = Model(x, y)\nlcn_model.compile('adam', 'binary_crossentropy', metrics=['acc'])\n```\n\n\n```python\nlcn_model.summary()\n```\n\n    _________________________________________________________________\n    Layer (type)                 Output Shape              Param #   \n    =================================================================\n    input_4 (InputLayer)         (None, 25, 25, 1)         0         \n    _________________________________________________________________\n    locally_connected2d_1 (Local (None, 9, 9, 32)          212544    \n    _________________________________________________________________\n    leaky_re_lu_5 (LeakyReLU)    (None, 9, 9, 32)          0         \n    _________________________________________________________________\n    dropout_5 (Dropout)          (None, 9, 9, 32)          0         \n    _________________________________________________________________\n    locally_connected2d_2 (Local (None, 5, 5, 32)          640800    \n    _________________________________________________________________\n    leaky_re_lu_6 (LeakyReLU)    (None, 5, 5, 32)          0         \n    _________________________________________________________________\n    dropout_6 (Dropout)          (None, 5, 5, 32)          0         \n    _________________________________________________________________\n    locally_connected2d_3 (Local (None, 3, 3, 64)          166464    \n    _________________________________________________________________\n    leaky_re_lu_7 (LeakyReLU)    (None, 3, 3, 64)          0         \n    _________________________________________________________________\n    dropout_7 (Dropout)          (None, 3, 3, 64)          0         \n    _________________________________________________________________\n    locally_connected2d_4 (Local (None, 1, 1, 64)          36928     \n    _________________________________________________________________\n    leaky_re_lu_8 (LeakyReLU)    (None, 1, 1, 64)          0         \n    _________________________________________________________________\n    flatten_2 (Flatten)          (None, 64)                0         \n    _________________________________________________________________\n    dropout_8 (Dropout)          (None, 64)                0         \n    _________________________________________________________________\n    dense_6 (Dense)              (None, 1)                 65        \n    =================================================================\n    Total params: 1,056,801\n    Trainable params: 1,056,801\n    Non-trainable params: 0\n    _________________________________________________________________\n\n\nFeel free to try to train it at home! For this tutorial, we will just load in pre-trained weights.\n\n\n```python\n# lcn_model.fit(\n#     images_train, labels_train,\n#     epochs=100,\n#     batch_size=256,\n#     validation_data=(images_val, labels_val),\n#     callbacks=[\n#         EarlyStopping(verbose=True, patience=30, monitor='val_loss'),\n#         ModelCheckpoint('./models/lcn-model.h5', monitor='val_loss',\n#                         verbose=True, save_best_only=True)\n#     ]\n# )\n```\n\n\n```python\nlcn_history = lcn_model.history.history\n```\n\n\n```python\n# accuracy plot\nplt.plot(100 * np.array(lcn_history['acc']), label='training')\nplt.plot(100 * np.array(lcn_history['val_acc']), label='validation')\nplt.xlim(0)\nplt.xlabel('epoch')\nplt.ylabel('accuracy %')\nplt.legend(loc='lower right', fontsize=20)\nplt.show()\n```\n\n\n```python\n# loss plot\nplt.plot(100 * np.array(lcn_history['loss']), label='training')\nplt.plot(100 * np.array(lcn_history['val_loss']), label='validation')\nplt.xlim(0)\nplt.xlabel('epoch')\nplt.ylabel('loss')\nplt.legend(loc='upper right', fontsize=20)\n# the line indicate the epoch corresponding to the best performance on the validation set\nplt.vlines(np.argmin(lcn_history['val_loss']), 43, 56, linestyle='dashed', linewidth=0.5)\nplt.show()\n```\n\n\n```python\nprint 'Loss estimate on unseen examples (from validation set) = {0:.3f}'.format(np.min(lcn_history['val_loss']))\n```\n\n    Loss estimate on unseen examples (from validation set) = 0.390\n\n\n\n```python\nlcn_model.load_weights('models/lcn-model.h5')\nyhat_lcn = lcn_model.predict(images_test, batch_size=512)\n```\n\n## Fully-Connected network\n\n\n```python\nx = Input(shape=(images_train.shape[1:]))\nh = Flatten()(x)\nh = Dense(25 ** 2, kernel_initializer='he_normal')(h)\nh = LeakyReLU()(h)\n\nh = Dropout(0.2)(h)\nh = Dense(512, kernel_initializer='he_normal')(h)\nh = LeakyReLU()(h)\n\nh = Dropout(0.2)(h)\nh = Dense(256, kernel_initializer='he_normal')(h)\nh = LeakyReLU()(h)\n\nh = Dropout(0.2)(h)\nh = Dense(128, kernel_initializer='he_normal')(h)\nh = LeakyReLU()(h)\n\nh = Dropout(0.2)(h)\ny = Dense(1, activation='sigmoid')(h)\n```\n\n\n```python\ndense_model = Model(x, y)\ndense_model.compile('adam', 'binary_crossentropy', metrics=['acc'])\n```\n\n\n```python\n# dense_model.fit(\n#     images_train, labels_train,\n#     epochs=100,\n#     batch_size=256,\n#     validation_data=(images_val, labels_val),\n#     callbacks=[\n#         EarlyStopping(verbose=True, patience=30, monitor='val_loss'),\n#         ModelCheckpoint('./models/dense-model.h5', monitor='val_loss',\n#                         verbose=True, save_best_only=True)\n#     ]\n# )\n```\n\n\n```python\ndense_history = dense_model.history.history\n```\n\n\n```python\n# accuracy plot\nplt.plot(100 * np.array(dense_history['acc']), label='training')\nplt.plot(100 * np.array(dense_history['val_acc']), label='validation')\nplt.xlim(0)\nplt.xlabel('epoch')\nplt.ylabel('accuracy %')\nplt.legend(loc='lower right', fontsize=20)\nplt.show()\n```\n\n\n```python\n# loss plot\nplt.plot(100 * np.array(dense_history['loss']), label='training')\nplt.plot(100 * np.array(dense_history['val_loss']), label='validation')\nplt.xlim(0)\nplt.xlabel('epoch')\nplt.ylabel('loss')\nplt.legend(loc='upper right', fontsize=20)\n# the line indicate the epoch corresponding to the best performance on the validation set\nplt.vlines(np.argmin(dense_history['val_loss']), 43, 56, linestyle='dashed', linewidth=0.5)\nplt.show()\n```\n\n\n```python\nprint 'Loss estimate on unseen examples (from validation set) = {0:.3f}'.format(np.min(dense_history['val_loss']))\n```\n\n    Loss estimate on unseen examples (from validation set) = 0.396\n\n\n\n```python\ndense_model.load_weights('models/dense-model.h5')\nyhat_dense = dense_model.predict(images_test, batch_size=512, verbose=True)\n```\n\n    160000/160000 [==============================] - 11s 69us/step\n\n\n## Plot ROC Curves\n\nA standard way to visualize the tradeoff between low false positive rate (FPR) and high true positive rate (TPR) is by plotting them on a ROC curve. In Physics, people like to plot the TPR on the x-axis, and 1/FPR on the y-axis.\n\n\n```python\nfrom sklearn.metrics import roc_curve\n```\n\n\n```python\nfpr_cnn, tpr_cnn, _ = roc_curve(labels_test, yhat_cnn)\nfpr_lcn, tpr_lcn, _ = roc_curve(labels_test, yhat_lcn)\nfpr_dense, tpr_dense, _ = roc_curve(labels_test, yhat_dense)\nfpr_baseline, tpr_baseline, _ = roc_curve(labels_test, yhat_baseline)\n```\n\n\n```python\nplt.figure(figsize=(10,10))\nplt.grid(b = True, which = 'minor')\nplt.grid(b = True, which = 'major')\n_ = plt.plot(tpr_cnn, 1./fpr_cnn, label='CNN')\n_ = plt.plot(tpr_lcn, 1./fpr_lcn, label='LCN')\n_ = plt.plot(tpr_dense, 1./fpr_dense, label='FCN')\n_ = plt.plot(tpr_baseline, 1./fpr_baseline, label='Baseline')\nplt.legend()\nplt.xlim((0.1, 0.9))\nplt.ylim((1, 1000))\nplt.yscale('log')\n```\n\n## What is the network learning?\n\n\n```python\ndef get_correlations(images, disc_output):\n    '''\n    calculate linear correlation between each pixel and the output of the classifier\n    to see what pixels are more indicative of a specific class.\n    '''\n    import pandas as pd\n    # -- find the total number of pixels per image, here 25 x 25\n    n_pixels = np.prod(images.shape[1:3])\n    \n    # -- add the pixels as columns to a dataframe\n    df = pd.DataFrame(\n        {i : np.squeeze(images).reshape(-1, n_pixels)[:, i] for i in range(n_pixels)}\n    )\n    # -- add a column to the end of the dataframe for the discriminator's output\n    df['disc_output'] = disc_output\n    # -- pandas offers an easy solution to calculate correlations \n    # (even though it's slow because it also calculates the correlation between each pixel and every other pixel)\n    correlations = df.corr().values[:-1, -1]\n    return correlations\n\ndef plot_correlations(correlations, extent, title='', img_dim=(25, 25), cmap=plt.cm.seismic):\n    '''\n    call the function about and then plot the correlations in image format\n    '''\n    max_mag = max(\n        abs(np.min(correlations[np.isfinite(correlations)])),\n        abs(np.max(correlations[np.isfinite(correlations)])),\n    ) # highest correlation value (abs value), to make the plot look nice and on a reasonable scale\n\n    f, ax = plt.subplots(figsize=(6, 6))\n    im = ax.imshow(\n        correlations.reshape(img_dim),\n        interpolation='nearest',\n        norm=Normalize(vmin=-max_mag, vmax=max_mag),\n        extent=extent,\n        cmap=cmap\n    )\n    \n    plt.colorbar(im, fraction=0.05, pad=0.05)\n    plt.xlabel(r'[Transformed] Pseudorapidity $(\\eta)$')\n    plt.ylabel(r'[Transformed] Azimuthal Angle $(\\phi)$')\n    plt.title(title)\n#     plt.savefig(os.path.join('..', outdir, outname))\n```\n\nYou can now visualize what each network picks up on, at least to first order. These correlation plots tells us whether a specific pixel being strongly activated is a good indicator of that jet image belonging to a class or the other. Red represents the signal (boosted W from W'-->WZ), blue represents the background (QCD).\n\n\n```python\nplot_correlations(\n    get_correlations(images_test[:10000], yhat_cnn[:10000]),\n    extent=[-1.25, 1.25, -1.25, 1.25],\n    title='Correlation between pixels \\n and the CNN prediction'\n)\n```\n\n\n```python\nplot_correlations(\n    get_correlations(images_test[:10000], yhat_lcn[:10000]),\n    extent=[-1.25, 1.25, -1.25, 1.25],\n    title='Correlation between pixels \\n and the LCN prediction'\n)\n```\n\n\n```python\nplot_correlations(\n    get_correlations(images_test[:10000], yhat_dense[:10000]),\n    extent=[-1.25, 1.25, -1.25, 1.25],\n    title='Correlation between pixels \\n and the FCN prediction'\n)\n```\n\n\n```python\nplot_correlations(\n    get_correlations(images_test[:10000], yhat_baseline[:10000]),\n    extent=[-1.25, 1.25, -1.25, 1.25],\n    title='Correlation between pixels \\n and the Baseline prediction'\n)\n```\n\nYou can also look at how the output of each classifier is correlated with known quantities that are known to be discriminative, such as the ones used in the baseline classifier above (mass, tau_21, delta_R). This will inform us as to whether the network has 'learned' to internally calculate a representation that is close to these variables, thus eliminating our need to come up with these features ourselves.\n\n\n```python\ndef plot_output_vs_kin(kin, output, xlabel, ylabel, nbins=30):\n    '''\n    Plot one output of the discriminator network vs. one of the 1D physics variables that describe jets\n    Args:\n    -----\n        kin : numpy array, kinematic property (such as mass or pT) associated with each image. I.e.: discrete_mass(np.squeeze(generated_images))\n        output : numpy array, one of the 2 outputs of the discriminator, evaluated on the same images that `kin` refers to\n        xlabel : string, x-axis label that describes the meaning of `kin`\n        ylabel : string, y-axis label that describes the meaning og `output`\n        outname : name of the output file, to be placed in ../plots/\n        nbins : (default = 30) number of bins to use to represent the distributions in a discretized way\n    \n    '''\n    # set the colormap\n    plt.set_cmap('jet')\n    # draw a 2d histogram of the discriminator's output versus the kinematic variable of choice (mass, pT, etc.)\n    h, binx, biny, _ = plt.hist2d(kin, output.reshape(-1,), bins=nbins)\n    plt.clf() # we don't want to plot this 2D histogram, we want to normalize it per bin first\n    \n    # normalize the histogram such that the entries in each column add up to 1, such that the intensity\n    # of each corresponds to the percentage of the jets in a given mass (or pT) bin that get assigned a p\n    for i in range(nbins):\n        h[i, :] = h[i, :] / float(np.sum(h[i, :]))\n    # plot the normalized histogram as an image\n    f, ax2 = plt.subplots(figsize=(6, 6))\n    im = ax2.imshow(\n        np.flipud(h.T), \n        interpolation='nearest',\n        norm=LogNorm(),\n        extent=[binx.min(), binx.max(), biny.min(), biny.max()],\n        aspect=\"auto\"\n    )\n    plt.xlabel(xlabel)\n    plt.ylabel(ylabel)\n    # add a custom colorbar\n    cax = f.add_axes([0.93, 0.1, 0.03, 0.8])\n    plt.colorbar(im, cax = cax)\n    plt.set_cmap('viridis')\n```\n\n### Mass\n\n\n```python\nplot_output_vs_kin(\n    scaler.inverse_transform(features_test)[:, 0], # mass\n    yhat_cnn,\n    xlabel='Discrete jet image mass (GeV)',\n    ylabel='P(signal)',\n)\n```\n\n\n```python\nplot_output_vs_kin(\n    scaler.inverse_transform(features_test)[:, 0], # mass\n    yhat_lcn,\n    xlabel='Discrete jet image mass (GeV)',\n    ylabel='P(signal)',\n)\n```\n\n\n```python\nplot_output_vs_kin(\n    scaler.inverse_transform(features_test)[:, 0], # mass\n    yhat_dense,\n    xlabel='Discrete jet image mass (GeV)',\n    ylabel='P(signal)',\n)\n```\n\n\n```python\nplot_output_vs_kin(\n    scaler.inverse_transform(features_test)[:, 0], # mass\n    yhat_baseline,\n    xlabel='Discrete jet image mass (GeV)',\n    ylabel='P(signal)',\n)\n```\n\n### Tau_21\n\n\n```python\nplot_output_vs_kin(\n    scaler.inverse_transform(features_test)[:, 1], # tau21\n    yhat_cnn,\n    xlabel=r'Discrete jet $\\tau_{21}$',\n    ylabel='P(signal)',\n)\n```\n\n\n```python\nplot_output_vs_kin(\n    scaler.inverse_transform(features_test)[:, 1], # tau21\n    yhat_lcn,\n    xlabel=r'Discrete jet $\\tau_{21}$',\n    ylabel='P(signal)',\n)\n```\n\n\n```python\nplot_output_vs_kin(\n    scaler.inverse_transform(features_test)[:, 1], # tau21\n    yhat_dense,\n    xlabel=r'Discrete jet $\\tau_{21}$',\n    ylabel='P(signal)',\n)\n```\n\n\n```python\nplot_output_vs_kin(\n    scaler.inverse_transform(features_test)[:, 1], # tau21\n    yhat_baseline,\n    xlabel=r'Discrete jet $\\tau_{21}$',\n    ylabel='P(signal)',\n)\n```\n\n### Delta R\n\n\n```python\nplot_output_vs_kin(\n    scaler.inverse_transform(features_test)[:, 2], # deltaR\n    yhat_cnn,\n    xlabel=r'Discrete jet $\\Delta R$',\n    ylabel='P(signal)',\n)\n```\n\n\n```python\nplot_output_vs_kin(\n    scaler.inverse_transform(features_test)[:, 2], # deltaR\n    yhat_lcn,\n    xlabel=r'Discrete jet $\\Delta R$',\n    ylabel='P(signal)',\n)\n```\n\n\n```python\nplot_output_vs_kin(\n    scaler.inverse_transform(features_test)[:, 2], # deltaR\n    yhat_dense,\n    xlabel=r'Discrete jet $\\Delta R$',\n    ylabel='P(signal)',\n)\n```\n\n\n```python\nplot_output_vs_kin(\n    scaler.inverse_transform(features_test)[:, 2], # deltaR\n    yhat_baseline,\n    xlabel=r'Discrete jet $\\Delta R$',\n    ylabel='P(signal)',\n)\n```\n\nSometimes, however, it is not a good idea to have your network learn the mass of a jet and use that to classify jets. In that case, in fact, the network will successfully suppress all jets outside of the signal-like mass window and sculpt the mass of the background to look like a signal peak. \n\nWhat we would like to be able to do, instead, is to have a classifier that is insensitive to mass, and that reduced the background across the entire mass spectrum. \n\nFor reference, see: C. Shimmin et al., <a href=\"https://arxiv.org/abs/1703.03507\">Decorrelated Jet Substructure Tagging using Adversarial Neural Networks</a>.\n\n# Training a GAN (<a href=\"https://arxiv.org/pdf/1704.00028.pdf\">WGAN-GP</a>) on jet images\n\nWGAN-GP = a type of GAN that minimizes the Wasserstein distance between the target and generated distributions and enforces the Lipschitz contraint by penalizing the norm of the gradient instead of clipping weights.\n\n\n```python\nfrom keras.layers import Input, Dense, Reshape, Flatten\nfrom keras.layers.merge import _Merge\nfrom keras.layers.convolutional import Convolution2D, Conv2DTranspose\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.optimizers import Adam\nfrom keras import backend as K\n```\n\n\n```python\nBATCH_SIZE = 100\n\n# The training ratio is the number of discriminator updates per generator\n# update. The paper uses 5.\nTRAINING_RATIO = 5\nGRADIENT_PENALTY_WEIGHT = 10  # As per the paper\n```\n\nDefine new custom loss functions not included among the standard keras ones:\n\n\n```python\ndef wasserstein_loss(y_true, y_pred):\n    return K.mean(y_true * y_pred)\n\n\ndef gradient_penalty_loss(y_true, y_pred, averaged_samples,\n                          gradient_penalty_weight):\n    gradients = K.gradients(K.sum(y_pred), averaged_samples)\n    gradient_l2_norm = K.sqrt(K.sum(K.square(gradients)))\n    gradient_penalty = gradient_penalty_weight * K.square(1 - gradient_l2_norm)\n    return gradient_penalty\n```\n\n\n```python\ndef make_generator():\n    \"\"\"Creates a generator model that takes a 100-dimensional latent prior and \n    converts to size 25 x 25 x 1\"\"\"\n\n    z = Input(shape=(100, ))\n    \n    x = Dense(1024, input_dim=100)(z)\n    x = LeakyReLU()(x)\n\n    x = Dense(128 * 7 * 7)(x)\n    x = BatchNormalization()(x)\n    x = LeakyReLU()(x)\n\n    x = Reshape((7, 7, 128))(x)\n\n    x = Conv2DTranspose(128, (5, 5), strides=2, padding='same')(x)\n    x = BatchNormalization(axis=-1)(x)\n    x = LeakyReLU()(x)\n\n    x = Convolution2D(64, (5, 5), padding='same')(x)\n    x = BatchNormalization(axis=-1)(x)\n    x = LeakyReLU()(x)\n\n    x = Conv2DTranspose(64, (5, 5), strides=2, padding='same')(x)\n    x = BatchNormalization(axis=-1)(x)\n    x = LeakyReLU()(x)\n\n    y = Convolution2D(1, (4, 4), padding='valid', activation='relu')(x)\n\n    return Model(z, y)\n```\n\n\n```python\ndef make_discriminator():\n\n    x = Input(shape=(25, 25, 1))\n    \n    h = Convolution2D(64, (5, 5), padding='same')(x)\n    h = LeakyReLU()(h)\n\n    h = Convolution2D(128, (5, 5), kernel_initializer='he_normal',\n                      strides=2)(h)\n    h = LeakyReLU()(h)\n\n    h = Convolution2D(256, (5, 5), kernel_initializer='he_normal',\n                      padding='same', strides=2)(h)\n    h = LeakyReLU()(h)\n\n    h = Flatten()(h)\n    h = Dense(1024, kernel_initializer='he_normal')(h)\n    h = LeakyReLU()(h)\n\n    y = Dense(1, kernel_initializer='he_normal')(h)\n\n    return Model(x, y)\n```\n\nBuild individual models:\n\n\n```python\ngenerator = make_generator()\ndiscriminator = make_discriminator()\n```\n\nBuild connected model with only generator trainable:\n\n\n```python\ndiscriminator.trainable = False\nz = Input(shape=(100, ))\ngenerator_model = Model(z, discriminator(generator(z)))\n# We use the Adam paramaters from Gulrajani et al.\ngenerator_model.compile(optimizer=Adam(0.0001, beta_1=0.5, beta_2=0.9),\n                        loss=wasserstein_loss)\n```\n\nBuild connected model with only discriminator trainable:\n\n\n```python\ndiscriminator.trainable = True\ngenerator.trainable = False\n```\n\n\n```python\nclass RandomWeightedAverage(_Merge): # used for gradient norm penalty\n\n    def _merge_function(self, inputs):\n        weights = K.random_uniform((K.shape(inputs[0])[0], 1, 1, 1))\n        return (weights * inputs[0]) + ((1 - weights) * inputs[1])\n```\n\n\n```python\nreal_samples = Input(shape=(25, 25, 1))\nz = Input(shape=(100,))\nfake_samples = generator(z)\n\ncritic_out_fake = discriminator(fake_samples)\ncritic_out_real = discriminator(real_samples)\n\n# generate weighted-averages of real and generated\n# samples, to use for the gradient norm penalty.\naveraged_samples = RandomWeightedAverage()([real_samples, fake_samples])\n\n# running them thru critic to get the gradient norm for the GP loss.\naveraged_samples_out = discriminator(averaged_samples)\n\n# The gradient penalty loss function requires the input averaged samples\ndef gp_loss(y_true, y_pred):\n    return gradient_penalty_loss(\n        y_true, y_pred,\n        averaged_samples=averaged_samples,\n        gradient_penalty_weight=GRADIENT_PENALTY_WEIGHT\n    )\n\ndiscriminator_model = Model(\n    inputs=[real_samples, z],\n    outputs=[critic_out_real, critic_out_fake, averaged_samples_out]\n)\n\n# We use the Adam paramaters from Gulrajani et al.\ndiscriminator_model.compile(\n    optimizer=Adam(0.0001, beta_1=0.5, beta_2=0.9),\n    loss=[wasserstein_loss, wasserstein_loss, gp_loss]\n)\n```\n\n\n```python\n# positive_y is the label vector for real samples, with value 1.\n# negative_y is the label vector for generated samples, with value -1.\n# dummy_y vector is passed to the gradient_penalty loss function and is\n# not used.\n\npositive_y = np.ones((BATCH_SIZE, 1), dtype=np.float32)\nnegative_y = -positive_y\ndummy_y = np.zeros((BATCH_SIZE, 1), dtype=np.float32)\n```\n\n\n```python\n# do a little bit of scaling for stability\nX_train = np.expand_dims(np.squeeze(images_train[:30000]) / 100, -1)\n```\n\n\n```python\noverall_disc_loss = []\n\nfor epoch in range(200): # train for 200 iterations\n\n    # at each epoch, shuffle the training set to get new samples\n    np.random.shuffle(X_train)\n    print \"Epoch: \", epoch\n    print \"Number of batches: \", int(X_train.shape[0] // BATCH_SIZE)\n    discriminator_loss = []\n    generator_loss = []\n\n    # we'll need this many samples per critic update\n    critic_nb_samples = BATCH_SIZE * TRAINING_RATIO\n\n    # loop through batches\n    for i in range(int(X_train.shape[0] // (BATCH_SIZE * TRAINING_RATIO))):\n        X_critic = X_train[i * critic_nb_samples:(i + 1) * critic_nb_samples]\n\n        # critic gets trained 5 times more per iteration than the generator\n        for j in range(TRAINING_RATIO):\n            X_minibatch = X_critic[j * BATCH_SIZE:(j + 1) * BATCH_SIZE]\n\n            # generate new input noise\n            noise = np.random.rand(BATCH_SIZE, 100).astype(np.float32)\n\n            # train the discriminator (or critic)\n            disc_loss = discriminator_model.train_on_batch(\n                [X_minibatch, noise],\n                [positive_y, negative_y, dummy_y]\n            )\n            discriminator_loss.append(disc_loss)\n    \n        critic_score = np.array(discriminator_loss)[:, 0]\n        if i % 10 == 0:\n            print 'critic score =', critic_score.mean()\n        overall_disc_loss.extend(critic_score.tolist())\n        # train the generator\n        gen_loss = generator_model.train_on_batch(\n            np.random.rand(BATCH_SIZE, 100),\n            positive_y\n        )\n        generator_loss.append(gen_loss)\n```\n\n\n```python\n# discriminator.save_weights('./models/wgan-discriminator.h5')\n# generator.save_weights('./models/wgan-generator.h5')\n```\n\nLoad pre-trained wights:\n\n\n```python\ndiscriminator.load_weights('./models/wgan-discriminator.h5')\ngenerator.load_weights('./models/wgan-generator.h5')\n```\n\nNow that we have a trained GAN, we can see if it actually works and what it produces. We can now get rid of the critic (discriminator) and focus only on the part that we really care about, the generator. Let's execute a forward pass on the generator.\n\n\n```python\n# input noise that will be transformed into jet images\nnoise = np.random.rand(1000, 100).astype(np.float32)\n```\n\n\n```python\n# produce some jet images from the generator!\nfake_jets = generator.predict(noise, batch_size=BATCH_SIZE, verbose=True)\n\n# rescale energies and remove redundant dimension for grayscale channel\nfake_jets = np.squeeze(fake_jets * 100)\n```\n\n    1000/1000 [==============================] - 10s 10ms/step\n\n\nLet's look at some GAN-generated jet images!\n\n\n```python\nplot_jet_image(fake_jets.mean(0))\n```\n\nWe can also look at the difference between the average generated image and the average real image to identify parts of the image that are not well-captured by the GAN and might need improvement. Green pixels are more strongly activated, on average, in fake images, while purple pixels are more strongly activated in background images.\n\n\n```python\nplot_diff_jet_image(fake_jets.mean(0) - images.mean(0), cmap='PRGn')\n```\n\nThere are multiple ways of imporving this training, such as conditioning on class or attributes, using minibatch discrimination, enforcing physical constraints, etc.\n\n\n```python\n\n```\n", "meta": {"hexsha": "ee98d3219e22076378d539a9d5f8148fe99c74b8", "size": 843349, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "jet_images.ipynb", "max_stars_repo_name": "YaleATLAS/CERNDeepLearningTutorial", "max_stars_repo_head_hexsha": "93a7aeef67fc6108fe810c784a38cb06fd650cf2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 43, "max_stars_repo_stars_event_min_datetime": "2016-06-04T18:22:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T12:19:36.000Z", "max_issues_repo_path": "jet_images.ipynb", "max_issues_repo_name": "YaleATLAS/CERNDeepLearningTutorial", "max_issues_repo_head_hexsha": "93a7aeef67fc6108fe810c784a38cb06fd650cf2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jet_images.ipynb", "max_forks_repo_name": "YaleATLAS/CERNDeepLearningTutorial", "max_forks_repo_head_hexsha": "93a7aeef67fc6108fe810c784a38cb06fd650cf2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2016-06-04T18:22:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T16:24:28.000Z", "avg_line_length": 243.6720600982, "max_line_length": 60736, "alphanum_fraction": 0.8820547602, "converted": true, "num_tokens": 16391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.08882029963593542, "lm_q1q2_score": 0.03160003264482367}}
{"text": "# Research\nThe title of the notebook should be coherent with file name. Namely, file name should be:\nauthor's initials_progressive number_title.ipynb\n\n# Purpose\nState the purpose of the notebook.\n\n# Methodology\nQuickly describe assumptions and processing steps.\n\n# WIP - improvements\n(WORK IN PROGRESS)\nUse this section only if the notebook is not final.\n\nNotable TODOs:\n* todo 1\n* todo 2\n* todo 3\n\n## Results\nDescribe and comment the most important results.\n\n# Suggested next steps\nState suggested next steps, based on results obtained in this notebook.\n\n# Setup\n\n\n```python\n# %load imports.py\n\"\"\"\nThese is the standard setup for the notebooks.\n\"\"\"\n\n%matplotlib inline\n%load_ext autoreload\n%autoreload 2\n\nfrom jupyterthemes import jtplot\njtplot.style(theme='onedork', context='notebook', ticks=True, grid=False)\n\nimport pandas as pd\npd.options.display.max_rows = 999\npd.options.display.max_columns = 999\npd.set_option(\"display.max_columns\", None)\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\n#plt.style.use('paper')\n\n#import data\nimport copy\nfrom mdldb.tables import Run\n\nfrom sklearn.pipeline import Pipeline\nfrom rolldecayestimators.transformers import CutTransformer, LowpassFilterDerivatorTransformer, ScaleFactorTransformer, OffsetTransformer\nfrom rolldecayestimators.direct_estimator_cubic import EstimatorQuadraticB, EstimatorCubic\nfrom rolldecayestimators.ikeda_estimator import IkedaQuadraticEstimator\nimport rolldecayestimators.equations as equations\nimport rolldecayestimators.lambdas as lambdas\nfrom rolldecayestimators.substitute_dynamic_symbols import lambdify\nimport rolldecayestimators.symbols as symbols\nimport sympy as sp\n\nfrom sklearn.metrics import r2_score\nfrom src.data import database\n```\n", "meta": {"hexsha": "e2fd6b8231eca69107938f60a4a17d42e8cd0325", "size": 3295, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/research.ipynb", "max_stars_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_stars_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/research.ipynb", "max_issues_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_issues_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/research.ipynb", "max_forks_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_forks_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-05T15:38:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T15:38:54.000Z", "avg_line_length": 24.7744360902, "max_line_length": 146, "alphanum_fraction": 0.5975720789, "converted": true, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.34510525748676846, "lm_q2_score": 0.09138209811811353, "lm_q1q2_score": 0.03153644250073271}}
{"text": "# Reproducible Workflow\nThis notebook is intended to be a walkthrough of the paper results with examples that convey the main idea. We show the workflow for the entire paper. \n* To load the LUBM Graph we use a public endpoint on [Dydra](http://dydra.com). \nHowever for larger test cases we run our tests on Apache Jena. In case you have a LUBM on your local/public endpoint, you can load it as well. Please note that the LUBM that we use is _materialized_. The inferencing is **RDFS**. \n\n* The DBpedia endpoint is a local endpoint, and if you want to test it, please replace it with either the public endpoint or your own local endpoint\n\n* For any other questions or suggestions or concerns with the procedures, please do contact me kannaa@rpi.edu, I'll be glad to include your suggestions.\n\n# Relaxation\nRelaxation is the standard baseline for reformulating SPARQL queries. A lot of related work exists on reformulating SPARQL queries. The ideas are inherently based on *flexible* querying. In this notion, the different conditions in the input query are *loosened* or *relaxed* to give more results. This can also be looked at as *exploratory* querying. \n\n## SPARQL Query Relaxation\nLets have a look at this hierarchy from LUBM on all teaching faculty in a University.\n* Employee \n* * Faculty \n* * * Professor \n* * * * VisitingProfessor \n* * * * FullProfessor \n* * * * Dean \n* * * * Chair \n* * * * AssociateProfessor \n* * * * AssistantProfessor \n* * * * PostDoc \n* * * * Lecturer \n\nLets look how relaxation helps in getting more answers. In this case consider the following query on LUBM\n\n\n```Select ?teacher where {\n    ?teacher a Lecturer .\n} ```\n\nLets see the results that we get from LUBM\n\n\n```python\nfrom rdflib import Graph\ng = Graph()\ng.parse('lubm_saturated.nt',format=\"nt\")\nprint(\"Total triple statements in LUBM is \" + str(len(g)))\n```\n\n    Total triple statements in LUBM is 144299\n\n\n\n```python\nfrom SPARQLWrapper import SPARQLWrapper, JSON\nfrom IPython.display import display\nimport pandas as pd\nimport json\nimport numpy as np\nfrom pandas.io.json import json_normalize\n\npd.options.display.max_colwidth = 100\npd.options.display.max_rows = 999\n\n#Procedure to execute a SPARQL Query and get a pandas object out of it\ndef execute_query(sparqlQuery,endpoint):\n    sparql = SPARQLWrapper(endpoint)\n    sparql.setQuery(sparqlQuery)\n    sparql.setReturnFormat(JSON)\n    results = sparql.query().convert()\n    results_df = json_normalize(results[\"results\"][\"bindings\"])\n    return results_df\n\n\n```\n\n\n```python\n%%time\nquery  = \"\"\"\n\nPREFIX  ub: <http://swat.cse.lehigh.edu/onto/univ-bench.owl#>\nSelect ?teacher where {\n    ?teacher a ub:Lecturer .\n}\n\n\"\"\"\nendpoint  = \"https://dydra.com/amarviswanathan/lubm/sparql\"\nresults_df = execute_query(query,endpoint)\n\n#Show the top-5 results\nresults_df.head()\n```\n\n    CPU times: user 8 ms, sys: 0 ns, total: 8 ms\n    Wall time: 540 ms\n\n\n\n```python\n#Total number of lecturers\nshape = results_df.shape\nprint(\"There are \" + str(shape[0]) + \" lecturers\")\n```\n\n    There are 93 lecturers\n\n\nBut if the user is not satisfied with these 93 lecturers and wants to find more of them, a simple way is to relax by moving up in the hierarchy. So we move from Lecturer to Professor. This gives us the following query : \n\n``` \nSelect ?teacher where {\n    ?teacher a ub:Professor .\n}\n```\n\n\n```python\n%%time \nrelaxed_query  = \"\"\"\n\nPREFIX  ub: <http://swat.cse.lehigh.edu/onto/univ-bench.owl#>\nSelect ?teacher where {\n    ?teacher a ub:Professor .\n}\n\"\"\"\nresults_df = execute_query(relaxed_query,endpoint)\n\n#Show the top-5 results\nresults_df.head()\n```\n\n    CPU times: user 12 ms, sys: 4 ms, total: 16 ms\n    Wall time: 703 ms\n\n\n\n```python\n#Total number of lecturers\nshape = results_df.shape\nprint(\"There are \" + str(shape[0]) + \" Professors\")\n```\n\n    There are 447 Professors\n\n\nThe above result gives us 447 Professors, each of whom may be any type under the hierarchy of **Professor**.\n\n## Instance Query \nLet us look at an instance of a **Professor** i.e. **<http://www.Department14.University0.edu/FullProfessor4>** and see what courses this Professor teaches.\n\n\n```python\n%%time \nentity_query = \"\"\"\nPREFIX  ub: <http://swat.cse.lehigh.edu/onto/univ-bench.owl#>\nSelect ?course where {\n   <http://www.Department14.University0.edu/FullProfessor4> ub:teacherOf  ?course .\n}\n\"\"\"\n\nresults_df = execute_query(entity_query,endpoint)\nresults_df = results_df[['course.value']]\n# Show all the results\nresults_df\n```\n\n    CPU times: user 4 ms, sys: 4 ms, total: 8 ms\n    Wall time: 482 ms\n\n\nSo the **FullProfessor4** teaches `2 Graduate Courses` and `1 Course`.  **If** the user decides to want more answers, an automatic way would be to relax the query. Thus the system wouldrelax this entity value. However the entity has **no hierarchy**. Which means this entity ends up being relaxed to a variable. This is known as `simple relaxation`. The relaxed query then becomes \n\n\n```Select ?course where {\n    ?teacher ub:teacherOf ?course .\n} ```\n\n\n\n```python\n%%time \nentity_relaxed_query = \"\"\"\nPREFIX  ub: <http://swat.cse.lehigh.edu/onto/univ-bench.owl#>\nSelect ?teacher ?course where {\n   ?teacher ub:teacherOf  ?course .\n}\n\"\"\"\n\nrelax_df = execute_query(entity_relaxed_query,endpoint)\n\n# Show all the results\nrelax_df\nprint(\"The total courses are \" + str(relax_df.shape[0]))\n\nrelax_df.head()\n```\n\n    The total courses are 1627\n    CPU times: user 64 ms, sys: 4 ms, total: 68 ms\n    Wall time: 1.31 s\n\n\n# Motivation\nIn this case, we end up relaxing the query to find _Anybody who takes any course_. Now this ends up giving `1627 results` and is very _generalized_. While this is logically right, wouldn't it be more beneficial if the system resulted in courses are more similar to what **Professor14** teaches? \n\n\n# Goal\n\nTo address this issue, we present a technique where we utilize the _entity_ statements present in the graph to suggest reformulations. Let us see how this makes sense. Entities have properties(_predicate_) and values (_object_) in the graph. For example the entity **Professor14** has this triple associated with it\n\n| Subject        | Predicate           | Object  |\n| ------------- |:-------------:| -----:|\n|**Professor14**|teacherOf|GraduateCourse5|\n\n\nOne could easily utilize these values much more effectively to create _triple patterns_ that can be appended back to the original query. This can then be used to suggest reformulations. We call the **predicate** and **object** value pair as a _feature_ or a _fact_. This is because they provide more contextual information about the entity in the RDF or RDFS graph. Since we utilize these features(facts) to create reformulations, we call our method \n**Feature based reformulation of entities in triple pattern queries**. \n\nThe features provide more _information_ and _context_ about an entity. Let us see how features can be used. To do that we print out the features of **FullProfessor4** from LUBM.\n\n\n```python\nentity_statement_query = \"\"\"\nPREFIX  ub: <http://swat.cse.lehigh.edu/onto/univ-bench.owl#>\nSelect ?p ?o where {\n   <http://www.Department14.University0.edu/FullProfessor4> ?p ?o .\n}\n\"\"\"\n\nresults_df = execute_query(entity_statement_query,endpoint)\n\n# Show all the results\nresults_df\n\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>o.datatype</th>\n      <th>o.type</th>\n      <th>o.value</th>\n      <th>p.type</th>\n      <th>p.value</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#Resource</td>\n      <td>uri</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#FullProfessor</td>\n      <td>uri</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#Faculty</td>\n      <td>uri</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#Person</td>\n      <td>uri</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#Professor</td>\n      <td>uri</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#Employee</td>\n      <td>uri</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>http://www.w3.org/2001/XMLSchema#string</td>\n      <td>literal</td>\n      <td>FullProfessor4</td>\n      <td>uri</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#name</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.Department14.University0.edu/GraduateCourse5</td>\n      <td>uri</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#teacherOf</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.Department14.University0.edu/Course4</td>\n      <td>uri</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#teacherOf</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.Department14.University0.edu/GraduateCourse4</td>\n      <td>uri</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#teacherOf</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.University214.edu</td>\n      <td>uri</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#undergraduateDegreeFrom</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.University912.edu</td>\n      <td>uri</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#mastersDegreeFrom</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.University801.edu</td>\n      <td>uri</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#doctoralDegreeFrom</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.Department14.University0.edu</td>\n      <td>uri</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#worksFor</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>http://www.w3.org/2001/XMLSchema#string</td>\n      <td>literal</td>\n      <td>FullProfessor4@Department14.University0.edu</td>\n      <td>uri</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#emailAddress</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>http://www.w3.org/2001/XMLSchema#string</td>\n      <td>literal</td>\n      <td>xxx-xxx-xxxx</td>\n      <td>uri</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#telephone</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>http://www.w3.org/2001/XMLSchema#string</td>\n      <td>literal</td>\n      <td>Research25</td>\n      <td>uri</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#researchInterest</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.Department14.University0.edu</td>\n      <td>uri</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#memberOf</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.University214.edu</td>\n      <td>uri</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#degreeFrom</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.University912.edu</td>\n      <td>uri</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#degreeFrom</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.University801.edu</td>\n      <td>uri</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#degreeFrom</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nFrom the above result we see that the `literal` values don't add more information to the triple except that they are string values for an entity. Morever, they don't have any statements associated with them. So we filter the literal values out first.\n\n\n```python\nresults_df = results_df[results_df['o.type'] == 'uri']\nresults_df = results_df[['p.value','o.value']]\nresults_df\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>p.value</th>\n      <th>o.value</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#Resource</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#FullProfessor</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#Faculty</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#Person</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#Professor</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#Employee</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#teacherOf</td>\n      <td>http://www.Department14.University0.edu/GraduateCourse5</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#teacherOf</td>\n      <td>http://www.Department14.University0.edu/Course4</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#teacherOf</td>\n      <td>http://www.Department14.University0.edu/GraduateCourse4</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#undergraduateDegreeFrom</td>\n      <td>http://www.University214.edu</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#mastersDegreeFrom</td>\n      <td>http://www.University912.edu</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#doctoralDegreeFrom</td>\n      <td>http://www.University801.edu</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#worksFor</td>\n      <td>http://www.Department14.University0.edu</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#memberOf</td>\n      <td>http://www.Department14.University0.edu</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#degreeFrom</td>\n      <td>http://www.University214.edu</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#degreeFrom</td>\n      <td>http://www.University912.edu</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>http://swat.cse.lehigh.edu/onto/univ-bench.owl#degreeFrom</td>\n      <td>http://www.University801.edu</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThe element in `row 0`, is too generic because it tags anything as a resource. So instead of that lets eyeball some interesting properties and change our initial query. For the sake of this example I pick \n\n| Predicate        | Object           |\n| ------------- |:-------------:|\n|**mastersDegreeFrom**|University912.edu|\n|**memberOf**|Department14.University0.edu|\n\nThe above two properties say something about the entity **Professor14** i.e. it says that **Professor14** got his `doctoralDegreeFrom University801.edu` and is `memberOf Department14.University0.edu`. To utilize these features in a query, one just has to convert them to a pattern so that it becomes a valid _triple pattern_. This is shown in the table below : \n\n\n### Entity Statements\n\n\n|Entity| Predicate | Value|\n|--|--|--|\n|**Professor14**| **mastersDegreeFrom**|University912.edu|\n|**Professor14**| **memberOf**|Department14.University0.edu|\n\nReplacing the entity **Professor14** with a variable `?x` we get the following :\n### Entity Feature Patterns\n\n|Variable|Predicate|Value| \n|--|--|--|\n|?x|**mastersDegreeFrom**|University912.edu|\n|?x|**memberOf**|Department14.University0.edu|\n\n\nNow let us pick the first pattern and add it back to the original query. Then lets add the second pattern to the original query independently.  This results in a  reformulated queries that looks like :\n\n```\nSelect ?course where {\n   ?x ub:teacherOf  ?course .\n   ?x mastersDegreeFrom University912.edu .\n}\n```\n\n```\nSelect ?course where {\n   ?x ub:teacherOf  ?course .\n   ?x memberOf Department14.University0.edu .\n}\n```\n\n\nThe inital query was :\n\n* Select courses taught by **FullProfessor4**\n\nAdding the two new features the query becomes :\n* Select courses taught by ?x who has a mastersDegreeFrom `University912.edu` \n* Select courses taught by ?x who is a member of `Department14.Univeristy0.edu` .\n\nBoth the above queries are more contextual and give precise answers than the initial relaxation which read as \n* Select all courses taught by any teacher\n\nSo lets run the reformulation to see the results.\n\n\n```python\n%%time \nentity_reformulated_query = \"\"\"\nPREFIX  ub: <http://swat.cse.lehigh.edu/onto/univ-bench.owl#>\nSelect ?course where {\n   ?x ub:teacherOf ?course .\n   ?x ub:mastersDegreeFrom <http://www.University912.edu> .\n   \n}\n\"\"\"\n\nref_1 = execute_query(entity_reformulated_query,endpoint)\n\n# Show all the results\nprint(\"The number of courses now is \" + str(ref_1.shape[0]))\nref_1.head()\n```\n\n    The number of courses now is 5\n    CPU times: user 4 ms, sys: 4 ms, total: 8 ms\n    Wall time: 457 ms\n\n\n\n```python\n%%time \nentity_reformulated_query = \"\"\"\nPREFIX  ub: <http://swat.cse.lehigh.edu/onto/univ-bench.owl#>\nSelect ?course where {\n   ?x ub:teacherOf ?course .\n   ?x ub:memberOf <http://www.Department14.University0.edu> .\n   \n}\n\"\"\"\n\nref_2 = execute_query(entity_reformulated_query,endpoint)\n\n# Show all the results\nprint(\"The number of courses now is \" + str(ref_2.shape[0]))\nref_2.head()\n```\n\n    The number of courses now is 97\n    CPU times: user 8 ms, sys: 0 ns, total: 8 ms\n    Wall time: 591 ms\n\n\nNow lets find the common results between the two reformulations\n\n\n```python\noverall_ref = pd.merge(ref_1,ref_2,how='inner',on=['course.type','course.value'])\noverall_ref\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>course.type</th>\n      <th>course.value</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>uri</td>\n      <td>http://www.Department14.University0.edu/GraduateCourse5</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>uri</td>\n      <td>http://www.Department14.University0.edu/Course4</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>uri</td>\n      <td>http://www.Department14.University0.edu/GraduateCourse4</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nLets find the results that are not common between the two reformulations.\n\n\n\n\n```python\nmerged_df = pd.concat([ref_1,ref_2])\nmerged_df  = merged_df.drop_duplicates(keep=False)\nmerged_df.shape[0]\n```\n\n\n\n\n    96\n\n\n\nSo we now have the following comparisons between relaxation and reformulation. There are a total of `96 + 3 = 99 ` unique results out of the reformulation procedure, whereas the relaxation has a total of `1627` results. The `99` results are more related to the `?course` variable of the original query because of using the features.\n\n### Results Comparison\n| Original Query        | **Relaxation**           | Ref-1 | Ref-2 | Combined |\n| ------------- |:-------------:|:--------:|:-------:|:---------|\n|3|1627|5|97|99|\n\n### Time Comparison\n | **Relaxation**           | Ref-1 | Ref-2 | \n|:-------------:|:--------:|:-------:|\n|1310ms|457ms|591ms|\n\n* Clearly the **relaxation results are higher, whereas the reformulation results are lesser**. This makes this kind of reformulation more precise.\n* In addition the time calculation shows that the **resulting reformulations also run in lesser time than the relaxed version of the query**.\n\nThis can be visualized as \n\n\n\n\nYou can access this visualization at the [jsfiddle](http://jsfiddle.net/N00bsie/hk6vjz4o/)\n\n## Selecting Interesting Features\n\nIn the previous sections, we focused on the aspect of showing that an entity reformulation is more **contextual** and **precise** than an _entity relaxation_. However the following question remains :\n* **Why do you need to pick subsets of features from the graph?**\n* **How do you select relevant _features_ for an entity?** \n* **Entities in large graphs have a lot of features. How many do you select?**\n\n## DBpedia Example\n\nLet us take an entity query involving `dbr:Martin_Scorsese`.  Assuming that initially the user is interested in looking at movies made by people similar to `dbr:Martin_Scorsese` and he starts out by making a query about the _movies made by_ `dbr:Martin_Scorsese`. Lets run it on the DBpedia end point to see what answers we get.\n\n\n\n\n```python\ndbpedia_query =\"\"\"\nPREFIX  schema: <http://schema.org/>\nPREFIX  dbr:  <http://dbpedia.org/resource/>\nPREFIX  umbel-rc: <http://umbel.org/umbel/rc/>\nPREFIX  dbc:  <http://dbpedia.org/resource/Category:>\nPREFIX  owl:  <http://www.w3.org/2002/07/owl#>\nPREFIX  yago: <http://dbpedia.org/class/yago/>\nPREFIX  rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX  dbo:  <http://dbpedia.org/ontology/>\nPREFIX  dbp:  <http://dbpedia.org/property/>\nPREFIX  rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX  dcterms: <http://purl.org/dc/terms/>\nPREFIX  dbpedia-wikidata: <http://wikidata.dbpedia.org/resource/>\nPREFIX  dul:  <http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#>\nPREFIX  foaf: <http://xmlns.com/foaf/0.1/>\nPREFIX  dc:   <http://purl.org/dc/elements/1.1/>\nPREFIX prov: <http://www.w3.org/ns/prov#>\n\nSELECT  Distinct ?movie \nWHERE\n  { \n    \n     ?movie dbo:director dbr:Martin_Scorsese .\n  }\n\n\"\"\"\ndbpedia_endpoint = \"http://zen.cs.rpi.edu:8890/sparql\"\nmovies_df = execute_query(dbpedia_query,dbpedia_endpoint)\nprint(\"The movies directed by dbr:Martin_Scorsese are :\")\nmovies_df\n```\n\n    The movies directed by dbr:Martin_Scorsese are :\n\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>movie.type</th>\n      <th>movie.value</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Made_in_Milan</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Key_to_Reserva</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Mean_Streets</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Raging_Bull</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Taxi_Driver</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Alice_Doesn't_Live_Here_Anymore</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_King_of_Comedy_(1983_film)</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Boxcar_Bertha</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Who's_That_Knocking_at_My_Door</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/My_Voyage_to_Italy</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Goodfellas</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/After_Hours_(film)</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/New_York_Stories</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Kundun</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/No_Direction_Home</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Street_Scenes</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Blues_(film)</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Last_Temptation_of_Christ_(film)</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Vinyl_(TV_series)</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Bringing_Out_the_Dead</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Aviator_(2004_film)</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Shutter_Island_(film)</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Silence_(2016_film)</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Casino_(film)</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/New_York,_New_York_(film)</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Departed</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/A_Personal_Journey_with_Martin_Scorsese_Through_American_Movies</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Age_of_Innocence_(1993_film)</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/What's_a_Nice_Girl_Like_You_Doing_in_a_Place_Like_This%3F</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Shine_a_Light_(film)</td>\n    </tr>\n    <tr>\n      <th>30</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Shine_a_Light_(The_Rolling_Stones_album)</td>\n    </tr>\n    <tr>\n      <th>31</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/George_Harrison:_Living_in_the_Material_World</td>\n    </tr>\n    <tr>\n      <th>32</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/A_Letter_to_Elia</td>\n    </tr>\n    <tr>\n      <th>33</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Cape_Fear_(1991_film)</td>\n    </tr>\n    <tr>\n      <th>34</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Gangs_of_New_York</td>\n    </tr>\n    <tr>\n      <th>35</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Color_of_Money</td>\n    </tr>\n    <tr>\n      <th>36</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Last_Waltz</td>\n    </tr>\n    <tr>\n      <th>37</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Big_Shave</td>\n    </tr>\n    <tr>\n      <th>38</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Italianamerican</td>\n    </tr>\n    <tr>\n      <th>39</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/American_Boy:_A_Profile_of_Steven_Prince</td>\n    </tr>\n    <tr>\n      <th>40</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/It's_Not_Just_You,_Murray!</td>\n    </tr>\n    <tr>\n      <th>41</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Hugo_(film)</td>\n    </tr>\n    <tr>\n      <th>42</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Boardwalk_Empire_(episode)</td>\n    </tr>\n    <tr>\n      <th>43</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Wolf_of_Wall_Street_(2013_film)</td>\n    </tr>\n    <tr>\n      <th>44</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Public_Speaking_(film)</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nprint(\"dbr:Martin_Scorsese has directed a total of \" + str(movies_df.shape[0]) + \" movies\")\n```\n\n    dbr:Martin_Scorsese has directed a total of 45 movies\n\n\nAs before lets relaxing `dbr:Martin_Scorsese` will lead to to the following query \n\n```\nSELECT  Distinct ?movie \nWHERE\n  { \n    \n     ?movie dbo:director ?y .\n  }\n```\nLet us execute this query on DBpedia to see how many movies we get\n\n\n\n\n```python\n%%time \ndbpedia_query =\"\"\"\nPREFIX  schema: <http://schema.org/>\nPREFIX  dbr:  <http://dbpedia.org/resource/>\nPREFIX  umbel-rc: <http://umbel.org/umbel/rc/>\nPREFIX  dbc:  <http://dbpedia.org/resource/Category:>\nPREFIX  owl:  <http://www.w3.org/2002/07/owl#>\nPREFIX  yago: <http://dbpedia.org/class/yago/>\nPREFIX  rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX  dbo:  <http://dbpedia.org/ontology/>\nPREFIX  dbp:  <http://dbpedia.org/property/>\nPREFIX  rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX  dcterms: <http://purl.org/dc/terms/>\nPREFIX  dbpedia-wikidata: <http://wikidata.dbpedia.org/resource/>\nPREFIX  dul:  <http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#>\nPREFIX  foaf: <http://xmlns.com/foaf/0.1/>\nPREFIX  dc:   <http://purl.org/dc/elements/1.1/>\nPREFIX prov: <http://www.w3.org/ns/prov#>\n\nSELECT  Distinct ?movie \nWHERE\n  { \n    \n     ?movie dbo:director ?y .\n  }\n\n\"\"\"\ndbpedia_endpoint = \"http://zen.cs.rpi.edu:8890/sparql\"\nmovies_df = execute_query(dbpedia_query,dbpedia_endpoint)\nprint(\"The toal movies directed by anybody are : \" + str(movies_df.shape[0]))\n\n```\n\n    The toal movies directed by anybody are : 103317\n    CPU times: user 2.44 s, sys: 60 ms, total: 2.5 s\n    Wall time: 5.01 s\n\n\nLooking at the results, you would realize that not all the results are movies. For example the entity `http://dbpedia.org/resource/Indianapolis_Art_Center\nn` at row index `102808` is not a movie, but rather an organization.\n\n\n```python\nprint(movies_df.loc[102808])\n```\n\n    movie.type                                                     uri\n    movie.value    http://dbpedia.org/resource/Indianapolis_Art_Center\n    Name: 102808, dtype: object\n\n\nThis happens because the query is very generalized because of the _relaxation_. To address this we need to execute queries that are contextually similar to the original query.  Following what was discussed earlier, we start by looking at the properties of the entity `dbr:Martin_Scorsese`.\n\n\n```python\n%%time \ndbpedia_entity_feature_query =\"\"\"\nPREFIX  schema: <http://schema.org/>\nPREFIX  dbr:  <http://dbpedia.org/resource/>\nPREFIX  umbel-rc: <http://umbel.org/umbel/rc/>\nPREFIX  dbc:  <http://dbpedia.org/resource/Category:>\nPREFIX  owl:  <http://www.w3.org/2002/07/owl#>\nPREFIX  yago: <http://dbpedia.org/class/yago/>\nPREFIX  rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX  dbo:  <http://dbpedia.org/ontology/>\nPREFIX  dbp:  <http://dbpedia.org/property/>\nPREFIX  rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX  dcterms: <http://purl.org/dc/terms/>\nPREFIX  dbpedia-wikidata: <http://wikidata.dbpedia.org/resource/>\nPREFIX  dul:  <http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#>\nPREFIX  foaf: <http://xmlns.com/foaf/0.1/>\nPREFIX  dc:   <http://purl.org/dc/elements/1.1/>\nPREFIX prov: <http://www.w3.org/ns/prov#>\n\nSELECT ?p ?o \nWHERE\n  { \n    \n     dbr:Martin_Scorsese ?p ?o .\n  }\n\"\"\"\ndbpedia_endpoint = \"http://zen.cs.rpi.edu:8890/sparql\"\nentity_features = execute_query(dbpedia_entity_feature_query,dbpedia_endpoint)\ndisplay(entity_features)\n```\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>o.datatype</th>\n      <th>o.type</th>\n      <th>o.value</th>\n      <th>o.xml:lang</th>\n      <th>p.type</th>\n      <th>p.value</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2002/07/owl#Thing</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://xmlns.com/foaf/0.1/Person</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://schema.org/Person</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/Person</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/Agent</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.wikidata.org/entity/Q215627</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.wikidata.org/entity/Q5</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#Agent</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#NaturalPerson</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Scorsese</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#label</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>\u0645\u0627\u0631\u062a\u0646 \u0633\u0643\u0648\u0631\u0633\u064a\u0632\u064a</td>\n      <td>ar</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#label</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Scorsese</td>\n      <td>de</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#label</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Scorsese</td>\n      <td>es</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#label</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Scorsese</td>\n      <td>fr</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#label</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Scorsese</td>\n      <td>it</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#label</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>\u30de\u30fc\u30c6\u30a3\u30f3\u30fb\u30b9\u30b3\u30bb\u30c3\u30b7</td>\n      <td>ja</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#label</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Scorsese</td>\n      <td>nl</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#label</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Scorsese</td>\n      <td>pl</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#label</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Scorsese</td>\n      <td>pt</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#label</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>\u0421\u043a\u043e\u0440\u0441\u0435\u0437\u0435, \u041c\u0430\u0440\u0442\u0438\u043d</td>\n      <td>ru</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#label</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>\u9a6c\u4e01\u00b7\u65af\u79d1\u585e\u65af</td>\n      <td>zh</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#label</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Marcantonio Luciano Scorsese [sk\u0254\u0279\u02c8s\u025bz\u026a] (* 17. November 1942 in Queens, New York) ist ei...</td>\n      <td>de</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#comment</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>\u30de\u30fc\u30c6\u30a3\u30f3\u30fb\u30b9\u30b3\u30bb\u30c3\u30b7\uff08Martin Scorsese, \u672c\u540d: Martin Marcantonio Luciano Scorsese, 1942\u5e7411\u670817\u65e5 - \uff09\u306f\u3001\u30a2\u30e1\u30ea\u30ab\u5408\u8846\u56fd\u306e\u6620...</td>\n      <td>ja</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#comment</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Scorsese (Queens (New York City), 17 november 1942) is een Amerikaans filmregisseur van S...</td>\n      <td>nl</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#comment</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Scorsese (ur. 17 listopada 1942 w Nowym Jorku) \u2013 ameryka\u0144ski re\u017cyser, scenarzysta, monta\u017c...</td>\n      <td>pl</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#comment</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Scorsese (Martin Charles Scorsese, Queens, Nova Iorque, 17 de novembro de 1942) \u00e9 um cine...</td>\n      <td>pt</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#comment</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Charles Scorsese (/sk\u0254r\u02c8s\u025bsi/; born November 17, 1942) is an American director, producer,...</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#comment</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>\u0645\u0627\u0631\u062a\u0646 \u0633\u0643\u0648\u0631\u0633\u064a\u0632\u064a \u0648\u0644\u062f \u0641\u064a 17 \u0646\u0648\u0641\u0645\u0628\u0631 1942 \u0646\u064a\u0648\u064a\u0648\u0631\u0643 \u0641\u064a \u0627\u0644\u0648\u0644\u0627\u064a\u0627\u062a \u0627\u0644\u0645\u062a\u062d\u062f\u0629 \u0627\u0644\u0623\u0645\u0631\u064a\u0643\u064a\u0629\u060c \u0647\u0648 \u0645\u062e\u0631\u062c \u0633\u064a\u0646\u0645\u0627\u0626\u064a \u0623\u0645\u0631\u064a...</td>\n      <td>ar</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#comment</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Charles Scorsese (Queens, Nueva York, 17 de noviembre de 1942), conocido como Martin Scor...</td>\n      <td>es</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#comment</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Scorsese est un r\u00e9alisateur am\u00e9ricain, n\u00e9 le 17 novembre 1942 \u00e0 New York aux \u00c9tats-Unis.D...</td>\n      <td>fr</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#comment</td>\n    </tr>\n    <tr>\n      <th>30</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Esponente della New Hollywood, \u00e8 considerato uno dei maggiori e pi\u00f9 importanti registi della sto...</td>\n      <td>it</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#comment</td>\n    </tr>\n    <tr>\n      <th>31</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>\u041c\u0430\u0301\u0440\u0442\u0438\u043d \u0427\u0430\u0301\u0440\u043b\u044c\u0437 \u0421\u043a\u043e\u0440\u0441\u0435\u0301\u0437\u0435 (\u0430\u043d\u0433\u043b. Martin Charles Scorsese, \u0431\u043e\u043b\u0435\u0435 \u0442\u043e\u0447\u043d\u043e\u0435 \u043f\u0440\u043e\u0438\u0437\u043d\u043e\u0448\u0435\u043d\u0438\u0435 \u0444\u0430\u043c\u0438\u043b\u0438\u0438 \u2014 \u0421\u043a...</td>\n      <td>ru</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2000/01/rdf-schema#comment</td>\n    </tr>\n    <tr>\n      <th>32</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://rdf.freebase.com/ns/m.04sry</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2002/07/owl#sameAs</td>\n    </tr>\n    <tr>\n      <th>33</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.wikidata.org/entity/Q41148</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2002/07/owl#sameAs</td>\n    </tr>\n    <tr>\n      <th>34</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://fr.dbpedia.org/resource/Martin_Scorsese</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2002/07/owl#sameAs</td>\n    </tr>\n    <tr>\n      <th>35</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://de.dbpedia.org/resource/Martin_Scorsese</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2002/07/owl#sameAs</td>\n    </tr>\n    <tr>\n      <th>36</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://cs.dbpedia.org/resource/Martin_Scorsese</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2002/07/owl#sameAs</td>\n    </tr>\n    <tr>\n      <th>37</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://el.dbpedia.org/resource/\u039c\u03ac\u03c1\u03c4\u03b9\u03bd_\u03a3\u03ba\u03bf\u03c1\u03c3\u03ad\u03b6\u03b5</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2002/07/owl#sameAs</td>\n    </tr>\n    <tr>\n      <th>38</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://es.dbpedia.org/resource/Martin_Scorsese</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2002/07/owl#sameAs</td>\n    </tr>\n    <tr>\n      <th>39</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://eu.dbpedia.org/resource/Martin_Scorsese</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2002/07/owl#sameAs</td>\n    </tr>\n    <tr>\n      <th>40</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://id.dbpedia.org/resource/Martin_Scorsese</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2002/07/owl#sameAs</td>\n    </tr>\n    <tr>\n      <th>41</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://it.dbpedia.org/resource/Martin_Scorsese</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2002/07/owl#sameAs</td>\n    </tr>\n    <tr>\n      <th>42</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://ja.dbpedia.org/resource/\u30de\u30fc\u30c6\u30a3\u30f3\u30fb\u30b9\u30b3\u30bb\u30c3\u30b7</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2002/07/owl#sameAs</td>\n    </tr>\n    <tr>\n      <th>43</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://ko.dbpedia.org/resource/\ub9c8\ud2f4_\uc2a4\ucf54\uc138\uc774\uc9c0</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2002/07/owl#sameAs</td>\n    </tr>\n    <tr>\n      <th>44</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://nl.dbpedia.org/resource/Martin_Scorsese</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2002/07/owl#sameAs</td>\n    </tr>\n    <tr>\n      <th>45</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://pl.dbpedia.org/resource/Martin_Scorsese</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2002/07/owl#sameAs</td>\n    </tr>\n    <tr>\n      <th>46</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://pt.dbpedia.org/resource/Martin_Scorsese</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2002/07/owl#sameAs</td>\n    </tr>\n    <tr>\n      <th>47</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://wikidata.dbpedia.org/resource/Q41148</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/2002/07/owl#sameAs</td>\n    </tr>\n    <tr>\n      <th>48</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:1942_births</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>49</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:20th-century_American_male_actors</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>50</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:21st-century_American_male_actors</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>51</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:American_Roman_Catholics</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>52</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:American_documentary_filmmakers</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>53</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:American_film_directors</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>54</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:American_film_directors_of_Italian_descent</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>55</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:American_film_editors</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>56</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:American_film_producers</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>57</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:American_male_film_actors</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>58</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:American_male_screenwriters</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>59</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:American_music_video_directors</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>60</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:American_people_of_Sicilian_descent</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>61</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:Best_Director_Academy_Award_winners</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>62</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:Best_Director_BAFTA_Award_winners</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>63</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:Best_Director_Golden_Globe_winners</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>64</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:Cecil_B._DeMille_Award_Golden_Globe_winners</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>65</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:C\u00e9sar_Award_winners</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>66</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:David_di_Donatello_Career_Award_winners</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>67</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:Directors_Guild_of_America_Award_winners</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>68</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:English-language_film_directors</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>69</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:Fellows_of_the_American_Academy_of_Arts_and_Sciences</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>70</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:Film_directors_from_New_York_City</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>71</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:Film_theorists</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>72</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:Grammy_Award_winners</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>73</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:Kennedy_Center_honorees</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>74</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:Living_people</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>75</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:L\u00e9gion_d'honneur_recipients</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>76</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:Male_actors_from_New_York_City</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>77</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:Male_actors_of_Italian_descent</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>78</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:New_York_Democrats</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>79</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:People_from_Corona,_Queens</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>80</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:Primetime_Emmy_Award_winners</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>81</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:Tisch_School_of_the_Arts_alumni</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>82</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:Transcendental_Meditation_practitioners</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>83</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Category:Venice_Best_Director_Silver_Lion_winners</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/terms/subject</td>\n    </tr>\n    <tr>\n      <th>84</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/New_York_University</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/almaMater</td>\n    </tr>\n    <tr>\n      <th>85</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Scorsese, Martin C.</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/alternativeNames</td>\n    </tr>\n    <tr>\n      <th>86</th>\n      <td>http://www.w3.org/2001/XMLSchema#date</td>\n      <td>typed-literal</td>\n      <td>1942-11-17</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/birthDate</td>\n    </tr>\n    <tr>\n      <th>87</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Charles Scorsese</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/birthName</td>\n    </tr>\n    <tr>\n      <th>88</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Queens, New York, U.S.</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/birthPlace</td>\n    </tr>\n    <tr>\n      <th>89</th>\n      <td>http://www.w3.org/2001/XMLSchema#integer</td>\n      <td>typed-literal</td>\n      <td>3</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/children</td>\n    </tr>\n    <tr>\n      <th>90</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Category:Martin Scorsese</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/commons</td>\n    </tr>\n    <tr>\n      <th>91</th>\n      <td>http://www.w3.org/2001/XMLSchema#date</td>\n      <td>typed-literal</td>\n      <td>1942-11-17</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/dateOfBirth</td>\n    </tr>\n    <tr>\n      <th>92</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>no</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/m</td>\n    </tr>\n    <tr>\n      <th>93</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>no</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/mw</td>\n    </tr>\n    <tr>\n      <th>94</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Director, producer, actor, screenwriter, film historian</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/occupation</td>\n    </tr>\n    <tr>\n      <th>95</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Marty</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/otherNames</td>\n    </tr>\n    <tr>\n      <th>96</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Catherine_Scorsese</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/parents</td>\n    </tr>\n    <tr>\n      <th>97</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Charles_Scorsese</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/parents</td>\n    </tr>\n    <tr>\n      <th>98</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Flushing, New York, United States</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/placeOfBirth</td>\n    </tr>\n    <tr>\n      <th>99</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>American film director</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/shortDescription</td>\n    </tr>\n    <tr>\n      <th>100</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>no</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/species</td>\n    </tr>\n    <tr>\n      <th>101</th>\n      <td>http://www.w3.org/2001/XMLSchema#integer</td>\n      <td>typed-literal</td>\n      <td>1965</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/spouse</td>\n    </tr>\n    <tr>\n      <th>102</th>\n      <td>http://www.w3.org/2001/XMLSchema#integer</td>\n      <td>typed-literal</td>\n      <td>1971</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/spouse</td>\n    </tr>\n    <tr>\n      <th>103</th>\n      <td>http://www.w3.org/2001/XMLSchema#integer</td>\n      <td>typed-literal</td>\n      <td>1976</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/spouse</td>\n    </tr>\n    <tr>\n      <th>104</th>\n      <td>http://www.w3.org/2001/XMLSchema#integer</td>\n      <td>typed-literal</td>\n      <td>1977</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/spouse</td>\n    </tr>\n    <tr>\n      <th>105</th>\n      <td>http://www.w3.org/2001/XMLSchema#integer</td>\n      <td>typed-literal</td>\n      <td>1979</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/spouse</td>\n    </tr>\n    <tr>\n      <th>106</th>\n      <td>http://www.w3.org/2001/XMLSchema#integer</td>\n      <td>typed-literal</td>\n      <td>1982</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/spouse</td>\n    </tr>\n    <tr>\n      <th>107</th>\n      <td>http://www.w3.org/2001/XMLSchema#integer</td>\n      <td>typed-literal</td>\n      <td>1985</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/spouse</td>\n    </tr>\n    <tr>\n      <th>108</th>\n      <td>http://www.w3.org/2001/XMLSchema#integer</td>\n      <td>typed-literal</td>\n      <td>1991</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/spouse</td>\n    </tr>\n    <tr>\n      <th>109</th>\n      <td>http://www.w3.org/2001/XMLSchema#integer</td>\n      <td>typed-literal</td>\n      <td>1999</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/spouse</td>\n    </tr>\n    <tr>\n      <th>110</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Isabella_Rossellini</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/spouse</td>\n    </tr>\n    <tr>\n      <th>111</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Barbara_De_Fina</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/spouse</td>\n    </tr>\n    <tr>\n      <th>112</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Julia_Cameron</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/spouse</td>\n    </tr>\n    <tr>\n      <th>113</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Helen Schermerhorn Morris</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/spouse</td>\n    </tr>\n    <tr>\n      <th>114</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Laraine Marie Brennan</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/spouse</td>\n    </tr>\n    <tr>\n      <th>115</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>div.</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/spouse</td>\n    </tr>\n    <tr>\n      <th>116</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>no</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/wikt</td>\n    </tr>\n    <tr>\n      <th>117</th>\n      <td>http://www.w3.org/2001/XMLSchema#integer</td>\n      <td>typed-literal</td>\n      <td>1963</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/yearsActive</td>\n    </tr>\n    <tr>\n      <th>118</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>no</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/b</td>\n    </tr>\n    <tr>\n      <th>119</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Scorsese at the 2010 Cannes Film Festival</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/caption</td>\n    </tr>\n    <tr>\n      <th>120</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Q41148</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/d</td>\n    </tr>\n    <tr>\n      <th>121</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>no</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/n</td>\n    </tr>\n    <tr>\n      <th>122</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Scorsese</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/name</td>\n    </tr>\n    <tr>\n      <th>123</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Scorsese, Martin</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/name</td>\n    </tr>\n    <tr>\n      <th>124</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>no</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/s</td>\n    </tr>\n    <tr>\n      <th>125</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Awards for Martin Scorsese</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/title</td>\n    </tr>\n    <tr>\n      <th>126</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>no</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/v</td>\n    </tr>\n    <tr>\n      <th>127</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>no</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/property/voy</td>\n    </tr>\n    <tr>\n      <th>128</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://digitalcontentproducer.com/podcasts/audio/scorsese_departed/</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/wikiPageExternalLink</td>\n    </tr>\n    <tr>\n      <th>129</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://realserver.princeton.edu:8080/ramgen/lectures/19990504scorseseTV7200K.rm</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/wikiPageExternalLink</td>\n    </tr>\n    <tr>\n      <th>130</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.theyshootpictures.com/scorsesemartin.htm</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/wikiPageExternalLink</td>\n    </tr>\n    <tr>\n      <th>131</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.lib.berkeley.edu/MRC/martinscorsese.html</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/wikiPageExternalLink</td>\n    </tr>\n    <tr>\n      <th>132</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.vanityfair.com/culture/features/2010/03/proust-scorsese-201003</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/wikiPageExternalLink</td>\n    </tr>\n    <tr>\n      <th>133</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://commons.wikimedia.org/wiki/Special:FilePath/Martin_Scorsese_Cannes_2010.jpg</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://xmlns.com/foaf/0.1/depiction</td>\n    </tr>\n    <tr>\n      <th>134</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://commons.wikimedia.org/wiki/Special:FilePath/Martin_Scorsese_Cannes_2010.jpg?width=300</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/thumbnail</td>\n    </tr>\n    <tr>\n      <th>135</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Charles Scorsese (/sk\u0254r\u02c8s\u025bsi/; born November 17, 1942) is an American director, producer,...</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/abstract</td>\n    </tr>\n    <tr>\n      <th>136</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>\u0645\u0627\u0631\u062a\u0646 \u0633\u0643\u0648\u0631\u0633\u064a\u0632\u064a \u0648\u0644\u062f \u0641\u064a 17 \u0646\u0648\u0641\u0645\u0628\u0631 1942 \u0646\u064a\u0648\u064a\u0648\u0631\u0643 \u0641\u064a \u0627\u0644\u0648\u0644\u0627\u064a\u0627\u062a \u0627\u0644\u0645\u062a\u062d\u062f\u0629 \u0627\u0644\u0623\u0645\u0631\u064a\u0643\u064a\u0629\u060c \u0647\u0648 \u0645\u062e\u0631\u062c \u0633\u064a\u0646\u0645\u0627\u0626\u064a \u0623\u0645\u0631\u064a...</td>\n      <td>ar</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/abstract</td>\n    </tr>\n    <tr>\n      <th>137</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Marcantonio Luciano Scorsese [sk\u0254\u0279\u02c8s\u025bz\u026a] (* 17. November 1942 in Queens, New York) ist ei...</td>\n      <td>de</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/abstract</td>\n    </tr>\n    <tr>\n      <th>138</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Charles Scorsese (Queens, Nueva York, 17 de noviembre de 1942), conocido como Martin Scor...</td>\n      <td>es</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/abstract</td>\n    </tr>\n    <tr>\n      <th>139</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Scorsese est un r\u00e9alisateur am\u00e9ricain, n\u00e9 le 17 novembre 1942 \u00e0 New York aux \u00c9tats-Unis.D...</td>\n      <td>fr</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/abstract</td>\n    </tr>\n    <tr>\n      <th>140</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Esponente della New Hollywood, \u00e8 considerato uno dei maggiori e pi\u00f9 importanti registi della sto...</td>\n      <td>it</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/abstract</td>\n    </tr>\n    <tr>\n      <th>141</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>\u30de\u30fc\u30c6\u30a3\u30f3\u30fb\u30b9\u30b3\u30bb\u30c3\u30b7\uff08Martin Scorsese, \u672c\u540d: Martin Marcantonio Luciano Scorsese, 1942\u5e7411\u670817\u65e5 - \uff09\u306f\u3001\u30a2\u30e1\u30ea\u30ab\u5408\u8846\u56fd\u306e\u6620...</td>\n      <td>ja</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/abstract</td>\n    </tr>\n    <tr>\n      <th>142</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Scorsese (Queens (New York City), 17 november 1942) is een Amerikaans filmregisseur van S...</td>\n      <td>nl</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/abstract</td>\n    </tr>\n    <tr>\n      <th>143</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Scorsese (ur. 17 listopada 1942 w Nowym Jorku) \u2013 ameryka\u0144ski re\u017cyser, scenarzysta, monta\u017c...</td>\n      <td>pl</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/abstract</td>\n    </tr>\n    <tr>\n      <th>144</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Scorsese (Martin Charles Scorsese, Queens, Nova Iorque, 17 de novembro de 1942) \u00e9 um cine...</td>\n      <td>pt</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/abstract</td>\n    </tr>\n    <tr>\n      <th>145</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>\u041c\u0430\u0301\u0440\u0442\u0438\u043d \u0427\u0430\u0301\u0440\u043b\u044c\u0437 \u0421\u043a\u043e\u0440\u0441\u0435\u0301\u0437\u0435 (\u0430\u043d\u0433\u043b. Martin Charles Scorsese, \u0431\u043e\u043b\u0435\u0435 \u0442\u043e\u0447\u043d\u043e\u0435 \u043f\u0440\u043e\u0438\u0437\u043d\u043e\u0448\u0435\u043d\u0438\u0435 \u0444\u0430\u043c\u0438\u043b\u0438\u0438 \u2014 \u0421\u043a...</td>\n      <td>ru</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/abstract</td>\n    </tr>\n    <tr>\n      <th>146</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://en.wikipedia.org/wiki/Martin_Scorsese?oldid=682860997</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://www.w3.org/ns/prov#wasDerivedFrom</td>\n    </tr>\n    <tr>\n      <th>147</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>American film director</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/elements/1.1/description</td>\n    </tr>\n    <tr>\n      <th>148</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>American film director</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://purl.org/dc/elements/1.1/description</td>\n    </tr>\n    <tr>\n      <th>149</th>\n      <td>http://www.w3.org/2001/XMLSchema#gYear</td>\n      <td>typed-literal</td>\n      <td>1963-01-01T00:00:00-05:00</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/activeYearsStartYear</td>\n    </tr>\n    <tr>\n      <th>150</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Marty</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/alias</td>\n    </tr>\n    <tr>\n      <th>151</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Scorsese, Martin C.</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/alias</td>\n    </tr>\n    <tr>\n      <th>152</th>\n      <td>http://www.w3.org/2001/XMLSchema#date</td>\n      <td>typed-literal</td>\n      <td>1942-11-17</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/birthDate</td>\n    </tr>\n    <tr>\n      <th>153</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Charles Scorsese</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/birthName</td>\n    </tr>\n    <tr>\n      <th>154</th>\n      <td>http://www.w3.org/2001/XMLSchema#gYear</td>\n      <td>typed-literal</td>\n      <td>1942-01-01T00:00:00-05:00</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/birthYear</td>\n    </tr>\n    <tr>\n      <th>155</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://xmlns.com/foaf/0.1/givenName</td>\n    </tr>\n    <tr>\n      <th>156</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Martin Scorsese</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://xmlns.com/foaf/0.1/name</td>\n    </tr>\n    <tr>\n      <th>157</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Scorsese, Martin</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://xmlns.com/foaf/0.1/name</td>\n    </tr>\n    <tr>\n      <th>158</th>\n      <td>http://www.w3.org/2001/XMLSchema#integer</td>\n      <td>typed-literal</td>\n      <td>18995</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/wikiPageID</td>\n    </tr>\n    <tr>\n      <th>159</th>\n      <td>NaN</td>\n      <td>literal</td>\n      <td>Scorsese</td>\n      <td>en</td>\n      <td>uri</td>\n      <td>http://xmlns.com/foaf/0.1/surname</td>\n    </tr>\n    <tr>\n      <th>160</th>\n      <td>http://www.w3.org/2001/XMLSchema#integer</td>\n      <td>typed-literal</td>\n      <td>682860997</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/wikiPageRevisionID</td>\n    </tr>\n    <tr>\n      <th>161</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/New_York_University</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/almaMater</td>\n    </tr>\n    <tr>\n      <th>162</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Queens</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/birthPlace</td>\n    </tr>\n    <tr>\n      <th>163</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Flushing,_Queens</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/birthPlace</td>\n    </tr>\n    <tr>\n      <th>164</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/New_York</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/birthPlace</td>\n    </tr>\n    <tr>\n      <th>165</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese__1</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/occupation</td>\n    </tr>\n    <tr>\n      <th>166</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Catherine_Scorsese</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/parent</td>\n    </tr>\n    <tr>\n      <th>167</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Charles_Scorsese</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/parent</td>\n    </tr>\n    <tr>\n      <th>168</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Isabella_Rossellini</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/spouse</td>\n    </tr>\n    <tr>\n      <th>169</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Barbara_De_Fina</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/spouse</td>\n    </tr>\n    <tr>\n      <th>170</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Julia_Cameron</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/ontology/spouse</td>\n    </tr>\n    <tr>\n      <th>171</th>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://en.wikipedia.org/wiki/Martin_Scorsese</td>\n      <td>NaN</td>\n      <td>uri</td>\n      <td>http://xmlns.com/foaf/0.1/isPrimaryTopicOf</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    CPU times: user 108 ms, sys: 4 ms, total: 112 ms\n    Wall time: 124 ms\n\n\nThere are a total of `172` features/facts for the entity `dbr:Martin_Scorsese`. Now how do we pick features/facts to suggest entity reformulation?\n\nLet us formalize the problem with the following definitions :\n\n## Entity Features Summarization\n\n### Entity Facts\nLet $\\mathbb{E}$ be the set of entities in the RDF Graph. Then a **fact** or a **feature** $f_i$  of an entity  e $\\in \\mathbb{E}$, is the $\\langle p, o \\rangle$ pair from the triple statement $\\langle e, p, o \\rangle$. \n\n|Entity|Predicate|Object| \n|--|--|--|\n|**dbr:Martin_Scorsese**|**http://dbpedia.org/property/parents ** | http://dbpedia.org/resource/Charles_Scorsese\t|\n\nIn the above table for the entity `dbr:Martin_Scorsese` the feature $\\langle p, o \\rangle$ is \n\n|Predicate|Object| \n|--|--|\n|**http://dbpedia.org/property/parents** | http://dbpedia.org/resource/Charles_Scorsese\t|\n\n### Entity Fact Set\nNow entities in large graphs like DBpedia, have a lot of facts associated with them. We can denote this by the fact set of an entity $FS(e)$. The total number for `dbr:Martin_Scorsese` in this setting is `172` as we have seen.\n\n\n### Optimal Feature Set\nWhile SPARQL queries can handle a lot of feature patterns, anything more than 10, would not be easy to interpret for the user. In fact heuristically most users prefer around `1-3` patterns. This is shown by the study done in in the **L**inked **S**PARQL **Q**ueries dataset. Here is how they look\n\n\n\nSo to pick a subset of the large feature patterns, we define a **Entity Summary**. \n\n### Entity Summary\nGiven an entity $e$ from a knowledge graph and a positive integer $k$, we define an entity summary to be $k$ $\\leq \\mid FS(e) \\mid $, entity summary of $e$, $\\textit{Summ(e,k)} \\subseteq \\textit{FS(e)}$ such that $\\mid\\textit{Summ(e,k)}\\mid = k$. For the example `dbr:Martin_Scorsese` we have \n* $\\mid FS(e) \\mid $ = `172`\n\nFor $k$ = 2, here the entity summary would look like\n\n| Predicate |Object| \n|--|--|\n| **http://dbpedia.org/property/parents**    | http://dbpedia.org/resource/Charles_Scorsese\t|\n| **http://dbpedia.org/ontology/birthPlace** | http://dbpedia.org/resource/Queens\t\t|\n\nNow this entity summary can be converted to an entity summary pattern. The following table shows the entity summary pattern from the summary\n\n|Variable|Predicate|Object| \n|--|--|--|\n|?e|**http://dbpedia.org/property/parents** | http://dbpedia.org/resource/Charles_Scorsese\t|\n|?e|**http://dbpedia.org/ontology/birthPlace** | http://dbpedia.org/resource/Queens\t\t|\n\nIn plain English, the $k=2$ summary can be stated as _Entity Martin Scorsese who has parents Charles Scorsese and birth place Queens_. \n\nThe summary pattern can be stated as _Any entity ?e that has parents Charles Scorsese and birth place Queens_.\n\n### Picking Summary Sets\n\nIn the $k=2$ summary pattern for `dbr:Martin_Scorsese` we see that `parent, Charles Scorsese` is too specific, because very few entities can have `Charles Scorsese` as parent. Similarly `birthPlace, Queens` is more generic becaue many entities can have `Queens` as a birth place. Ideally one should be able to pick features for reformulation that \n* Is not too specific because that would end up not giving more results. This defeats the purpose of reformulation.\n* Is not too generic because that would give up a lot of results and not make it any better than relaxation.\n\nIdeally we want a function for the facts  $\\left\\lbrace f_1,f_2,\\ldots f_k \\right\\rbrace $ in the fact set $\\textit{FS(e)}$ so that they are ranked _ideally_ with a _ranking_ function such that $Rank(f_1) > Rank(f_2) > \\ldots Rank(f_k)$. This _ranking function_ should be able to address the concerns of not being too _specifc_ or being too _generic_. We discuss how this can be achieved now.\n\n\n### Ranking Entity Facts \n\nWe introduce two measures that can be combined to produce a _ranking_ to give a summary. While there can be many ranking functions that can be developed, our goal is to first start with a ranking function to solve the entity reformulation problem. We will then explore further how we can design better ranking functions. So the two measures that we define are \n####  Specificity : \nTo pick features that convey _interesting_ information about the entity $e$ from the feature set $FS(e)$. For example `birthPlace, Queens` is not as interesting as `almaMater, New York University`. Borrowing from the world of Information Retrieval, we define _specificity_ of a feature $f_i$ based on **IDF** as follows :\n\n\n$$ \\begin{align} \n\\mbox{Specificity($f_i$)} = \\log {\\frac{\\mid E \\mid }{\\mid e \\mid \\exists p,o:\\langle e,p,o \\rangle \\in R\\mid }}\n\\end{align} $$\n\nGithub sometimes doesn't render this so the image is here : \nHere $\\mid E \\mid$ refers to the total number of entity resources in the knowledge graph R. \n\n**Note:** For this paper we utilize only entity resources, so we filter out any feature $f_i$ that has literal values.\n\nLet us now apply this to `dbr:Martin_Scorsese` to see the kind of features we get.\n\n\n```python\nendpoint = \"http://zen.cs.rpi.edu:8890/sparql\"\n\ndef specificity(column):\n    return np.log(4641890/(float(column)))\n\ndef execute_augmented_query(sparqlQuery,endpoint):\n    sparql = SPARQLWrapper(endpoint)\n    sparql.setQuery(sparqlQuery)\n    sparql.setReturnFormat(JSON)\n    results = sparql.query().convert()\n    results_df = json_normalize(results[\"results\"][\"bindings\"])\n#     print(results_df)\n    results_df = results_df[results_df['o.type'] == \"uri\"]\n    results_df = results_df.drop(['o.type','p.type'],axis=1)\n    results_df = results_df[['p.value','o.value','countS.value']]\n    results_df['countS.value'] = results_df['countS.value'].astype(int)\n#     results_df = results_df[results_df['countS.value']]\n    return results_df\n\n## This query is used to find the count values for the 'Specificity'.\naugmented_query = \"\"\"\nPREFIX  schema: <http://schema.org/>\nPREFIX  dbr:  <http://dbpedia.org/resource/>\nPREFIX  umbel-rc: <http://umbel.org/umbel/rc/>\nPREFIX  dbc:  <http://dbpedia.org/resource/Category:>\nPREFIX  owl:  <http://www.w3.org/2002/07/owl#>\nPREFIX  yago: <http://dbpedia.org/class/yago/>\nPREFIX  rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX  dbo:  <http://dbpedia.org/ontology/>\nPREFIX  dbp:  <http://dbpedia.org/property/>\nPREFIX  rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX  dcterms: <http://purl.org/dc/terms/>\nPREFIX  dbpedia-wikidata: <http://wikidata.dbpedia.org/resource/>\nPREFIX  dul:  <http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#>\nPREFIX  foaf: <http://xmlns.com/foaf/0.1/>\nPREFIX  dc:   <http://purl.org/dc/elements/1.1/>\nPREFIX prov: <http://www.w3.org/ns/prov#>\nPREFIX  dc: <http://purl.org/dc/elements/1.1/>\n\nSELECT  ?p ?o (COUNT(DISTINCT ?s) AS ?countS)\nWHERE\n  { dbr:Martin_Scorsese\n              ?p  ?o .\n    ?s        ?p  ?o\n    FILTER ( ! strstarts(str(?p), str(dbo:wikiPageWikiLink)) )\n    FILTER ( ! strstarts(str(?p), str(dbo:wikiPageID)) )\n    FILTER ( ! strstarts(str(?p), str(dbo:wikiPageExternalLink)) )\n    FILTER ( ! strstarts(str(?p), str(dbo:wikiPageRevisionID)) )\n    FILTER ( ! strstarts(str(?p), str(dbo:wikiPageLength)) )\n    FILTER ( ! strstarts(str(?p), str(owl:sameAs)) )\n    FILTER ( ! strstarts(str(?p), str(dbo:viafId)) )\n    FILTER ( ! strstarts(str(?p), str(dbo:wikiPageOutDegree)) )\n    FILTER ( ! strstarts(str(?p), str(schema:comment)) )\n    FILTER ( ! strstarts(str(?p), str(dbo:abstract)) )\n    FILTER ( ! strstarts(str(?p), str(rdfs:comment)) )\n    FILTER ( ! strstarts(str(?p), str(dbo:alias)) )\n    FILTER ( ! strstarts(str(?p), str(rdfs:label)) )\n    FILTER ( ! strstarts(str(?p), str(dbo:thumbnail)) )\n    FILTER ( ! strstarts(str(?p), str(foaf:name)) )\n    FILTER ( ! strstarts(str(?p), str(foaf:surname)) )\n    FILTER ( ! strstarts(str(?p), str(foaf:depiction)) )\n    FILTER ( ! strstarts(str(?p), str(foaf:isPrimaryTopicOf)) )\n    FILTER ( ! strstarts(str(?p), str(dbp:hasPhotoCollection)) )\n    FILTER ( ! strstarts(str(?p), str(dbp:wordnet_type)) )\n    FILTER ( ! strstarts(str(?p), str(prov:wasDerivedFrom)) )\n    FILTER ( ! strstarts(str(?p), str(dc:description)) )\n   \n    \n    \n  }\nGROUP BY ?p ?o\nORDER BY ASC(?countS)\n\"\"\"\nresults_df = execute_augmented_query(augmented_query,endpoint)\nresults_df.reset_index(inplace=True)\nresults_df['Specificity'] = results_df['countS.value'].apply(specificity)\nresults_df.sort_values(by=['Specificity'],ascending=False,inplace=True)\ndisplay(results_df)\n```\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>index</th>\n      <th>p.value</th>\n      <th>o.value</th>\n      <th>countS.value</th>\n      <th>Specificity</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0</td>\n      <td>http://dbpedia.org/ontology/spouse</td>\n      <td>http://dbpedia.org/resource/Julia_Cameron</td>\n      <td>1</td>\n      <td>15.350632</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>6</td>\n      <td>http://dbpedia.org/ontology/parent</td>\n      <td>http://dbpedia.org/resource/Catherine_Scorsese</td>\n      <td>1</td>\n      <td>15.350632</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>7</td>\n      <td>http://dbpedia.org/property/spouse</td>\n      <td>http://dbpedia.org/resource/Isabella_Rossellini</td>\n      <td>1</td>\n      <td>15.350632</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>9</td>\n      <td>http://dbpedia.org/ontology/spouse</td>\n      <td>http://dbpedia.org/resource/Isabella_Rossellini</td>\n      <td>1</td>\n      <td>15.350632</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>10</td>\n      <td>http://dbpedia.org/property/spouse</td>\n      <td>http://dbpedia.org/resource/Julia_Cameron</td>\n      <td>1</td>\n      <td>15.350632</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>11</td>\n      <td>http://dbpedia.org/property/spouse</td>\n      <td>http://dbpedia.org/resource/Barbara_De_Fina</td>\n      <td>1</td>\n      <td>15.350632</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>12</td>\n      <td>http://dbpedia.org/ontology/occupation</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese__1</td>\n      <td>1</td>\n      <td>15.350632</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>15</td>\n      <td>http://dbpedia.org/property/parents</td>\n      <td>http://dbpedia.org/resource/Charles_Scorsese</td>\n      <td>1</td>\n      <td>15.350632</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>18</td>\n      <td>http://dbpedia.org/ontology/spouse</td>\n      <td>http://dbpedia.org/resource/Barbara_De_Fina</td>\n      <td>1</td>\n      <td>15.350632</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>21</td>\n      <td>http://dbpedia.org/property/parents</td>\n      <td>http://dbpedia.org/resource/Catherine_Scorsese</td>\n      <td>1</td>\n      <td>15.350632</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>5</td>\n      <td>http://dbpedia.org/ontology/parent</td>\n      <td>http://dbpedia.org/resource/Charles_Scorsese</td>\n      <td>1</td>\n      <td>15.350632</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>26</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Venice_Best_Director_Silver_Lion_winners</td>\n      <td>19</td>\n      <td>12.406193</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>29</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:People_from_Corona,_Queens</td>\n      <td>24</td>\n      <td>12.172578</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>31</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Best_Director_BAFTA_Award_winners</td>\n      <td>38</td>\n      <td>11.713046</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>32</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:David_di_Donatello_Career_Award_winners</td>\n      <td>45</td>\n      <td>11.543970</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>34</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Best_Director_Golden_Globe_winners</td>\n      <td>52</td>\n      <td>11.399388</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>33</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_film_directors_of_Italian_descent</td>\n      <td>52</td>\n      <td>11.399388</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>35</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Cecil_B._DeMille_Award_Golden_Globe_winners</td>\n      <td>62</td>\n      <td>11.223498</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>37</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Best_Director_Academy_Award_winners</td>\n      <td>68</td>\n      <td>11.131124</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>38</td>\n      <td>http://dbpedia.org/ontology/birthPlace</td>\n      <td>http://dbpedia.org/resource/Flushing,_Queens</td>\n      <td>88</td>\n      <td>10.873295</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>46</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:C\u00e9sar_Award_winners</td>\n      <td>137</td>\n      <td>10.430651</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>48</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Film_theorists</td>\n      <td>155</td>\n      <td>10.307207</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>50</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Directors_Guild_of_America_Award_winners</td>\n      <td>184</td>\n      <td>10.135696</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>51</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Kennedy_Center_honorees</td>\n      <td>188</td>\n      <td>10.114190</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>52</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Film_directors_from_New_York_City</td>\n      <td>198</td>\n      <td>10.062365</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>53</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Transcendental_Meditation_practitioners</td>\n      <td>212</td>\n      <td>9.994046</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>54</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_people_of_Sicilian_descent</td>\n      <td>267</td>\n      <td>9.763384</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>55</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_music_video_directors</td>\n      <td>372</td>\n      <td>9.431738</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>57</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Primetime_Emmy_Award_winners</td>\n      <td>431</td>\n      <td>9.284524</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>58</td>\n      <td>http://dbpedia.org/property/almaMater</td>\n      <td>http://dbpedia.org/resource/New_York_University</td>\n      <td>498</td>\n      <td>9.140032</td>\n    </tr>\n    <tr>\n      <th>30</th>\n      <td>59</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_film_editors</td>\n      <td>503</td>\n      <td>9.130042</td>\n    </tr>\n    <tr>\n      <th>31</th>\n      <td>60</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:English-language_film_directors</td>\n      <td>520</td>\n      <td>9.096803</td>\n    </tr>\n    <tr>\n      <th>32</th>\n      <td>63</td>\n      <td>http://dbpedia.org/ontology/almaMater</td>\n      <td>http://dbpedia.org/resource/New_York_University</td>\n      <td>581</td>\n      <td>8.985881</td>\n    </tr>\n    <tr>\n      <th>33</th>\n      <td>64</td>\n      <td>http://dbpedia.org/ontology/birthPlace</td>\n      <td>http://dbpedia.org/resource/Queens</td>\n      <td>595</td>\n      <td>8.962071</td>\n    </tr>\n    <tr>\n      <th>34</th>\n      <td>65</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_documentary_filmmakers</td>\n      <td>649</td>\n      <td>8.875199</td>\n    </tr>\n    <tr>\n      <th>35</th>\n      <td>66</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Male_actors_of_Italian_descent</td>\n      <td>726</td>\n      <td>8.763082</td>\n    </tr>\n    <tr>\n      <th>36</th>\n      <td>67</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Tisch_School_of_the_Arts_alumni</td>\n      <td>817</td>\n      <td>8.644993</td>\n    </tr>\n    <tr>\n      <th>37</th>\n      <td>68</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:L\u00e9gion_d'honneur_recipients</td>\n      <td>885</td>\n      <td>8.565045</td>\n    </tr>\n    <tr>\n      <th>38</th>\n      <td>74</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Male_actors_from_New_York_City</td>\n      <td>1454</td>\n      <td>8.068559</td>\n    </tr>\n    <tr>\n      <th>39</th>\n      <td>77</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Fellows_of_the_American_Academy_of_Arts_and_Sciences</td>\n      <td>1864</td>\n      <td>7.820152</td>\n    </tr>\n    <tr>\n      <th>40</th>\n      <td>78</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:New_York_Democrats</td>\n      <td>1966</td>\n      <td>7.766876</td>\n    </tr>\n    <tr>\n      <th>41</th>\n      <td>81</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Grammy_Award_winners</td>\n      <td>2389</td>\n      <td>7.572002</td>\n    </tr>\n    <tr>\n      <th>42</th>\n      <td>82</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_Roman_Catholics</td>\n      <td>2393</td>\n      <td>7.570329</td>\n    </tr>\n    <tr>\n      <th>43</th>\n      <td>84</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:21st-century_American_male_actors</td>\n      <td>3465</td>\n      <td>7.200164</td>\n    </tr>\n    <tr>\n      <th>44</th>\n      <td>85</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_film_producers</td>\n      <td>3489</td>\n      <td>7.193262</td>\n    </tr>\n    <tr>\n      <th>45</th>\n      <td>86</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_male_screenwriters</td>\n      <td>3608</td>\n      <td>7.159723</td>\n    </tr>\n    <tr>\n      <th>46</th>\n      <td>88</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_film_directors</td>\n      <td>4477</td>\n      <td>6.943924</td>\n    </tr>\n    <tr>\n      <th>47</th>\n      <td>89</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:20th-century_American_male_actors</td>\n      <td>6540</td>\n      <td>6.564940</td>\n    </tr>\n    <tr>\n      <th>48</th>\n      <td>91</td>\n      <td>http://dbpedia.org/ontology/birthPlace</td>\n      <td>http://dbpedia.org/resource/New_York</td>\n      <td>8078</td>\n      <td>6.353733</td>\n    </tr>\n    <tr>\n      <th>49</th>\n      <td>92</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:1942_births</td>\n      <td>8423</td>\n      <td>6.311911</td>\n    </tr>\n    <tr>\n      <th>50</th>\n      <td>93</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_male_film_actors</td>\n      <td>10374</td>\n      <td>6.103574</td>\n    </tr>\n    <tr>\n      <th>51</th>\n      <td>94</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Living_people</td>\n      <td>729176</td>\n      <td>1.850962</td>\n    </tr>\n    <tr>\n      <th>52</th>\n      <td>95</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://dbpedia.org/ontology/Person</td>\n      <td>1587944</td>\n      <td>1.072682</td>\n    </tr>\n    <tr>\n      <th>53</th>\n      <td>96</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://www.wikidata.org/entity/Q215627</td>\n      <td>1587944</td>\n      <td>1.072682</td>\n    </tr>\n    <tr>\n      <th>54</th>\n      <td>97</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://www.wikidata.org/entity/Q5</td>\n      <td>1587944</td>\n      <td>1.072682</td>\n    </tr>\n    <tr>\n      <th>55</th>\n      <td>98</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://schema.org/Person</td>\n      <td>1587944</td>\n      <td>1.072682</td>\n    </tr>\n    <tr>\n      <th>56</th>\n      <td>99</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#NaturalPerson</td>\n      <td>1587944</td>\n      <td>1.072682</td>\n    </tr>\n    <tr>\n      <th>57</th>\n      <td>100</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://xmlns.com/foaf/0.1/Person</td>\n      <td>1588593</td>\n      <td>1.072273</td>\n    </tr>\n    <tr>\n      <th>58</th>\n      <td>101</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://dbpedia.org/ontology/Agent</td>\n      <td>1855262</td>\n      <td>0.917096</td>\n    </tr>\n    <tr>\n      <th>59</th>\n      <td>102</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#Agent</td>\n      <td>1855262</td>\n      <td>0.917096</td>\n    </tr>\n    <tr>\n      <th>60</th>\n      <td>103</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://www.w3.org/2002/07/owl#Thing</td>\n      <td>4995959</td>\n      <td>-0.073508</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\nIn the above table we see from the column **countS.value** that properties like `http://dbpedia.org/ontology/spouse\t` and `http://dbpedia.org/ontology/parents` are very specific and using them to reformulate will not lead us to any new results. For example let us use `http://dbpedia.org/ontology/spouse, http://dbpedia.org/resource/Barbara_De_Fina` to reformulate. The triple pattern for this becomes \n`?e http://dbpedia.org/ontology/spouse http://dbpedia.org/resource/Barbara_De_Fina`. Appending this to the original query we\tget the following query \n```\nSelect \n?movie dbo:director ?e\n?e http://dbpedia.org/ontology/spouse http://dbpedia.org/resource/Barbara_De_Fina .\t\n```\n\nThe query translates in plain english as _Select all movies that are directed by an entity that has spouse Barbara De Fina_. This kind of a feature is too specific for just `dbr:Martin_Scorsese`. So we would need some other measure to pick features that are related to the entity and give more results, but aren't too generic. In addition we need to remove features that have **countS.value** = 1.\n\n### Popularity\n\nSince it is the value i.e. the $o$ in $\\langle p, o \\rangle$ that contributes to being selective, we consider the notion of _popularity_, which is inspired by **TF** or is a weighting term. This utilizes the value $o_i$ frequency of a feature $f_i$ which is nothing but the tuple $\\langle p_i, o_i \\rangle$ and can be defined as :\n$$\n\\begin{align}\n\\mbox{Popularity($o_i$)}  = \\log {\\mid t \\mid \\exists o_i:\\langle e,p,o_i \\rangle \\in R\\mid }\n\\end{align}\n$$\n\nIf the formula hasn't been rendered here is the image \n### Combined Ranking for Features\n\nNow that we have _popularity_ and _specificity_ we combine them to form the combined ranking for a feature $f_i$. So the ranking function for a feature $f_i = \\langle p_i, o_i \\rangle$  can be defined as :\n\n$$\n\\begin{align}\n\\mbox{Rank($f_i$)}  = Specificity(f_i) * Popularity(o_i)\n\\end{align}\n$$\nIf the formula hasn't been rendered here is the image \nLet us apply this and see in real time how this changes the object values.\n\n\n```python\nimport math\ndef nbycount(column):\n    return 4641890/(1+float(column))\n\ndef execute_count_query(obj):\n    if(obj.startswith('http')):\n        sparqlQuery = \"Select (count(*) as ?countRow)  WHERE { ?s \" + \"?p  <\" + obj + \"> }\"       \n    else:\n        sparqlQuery = 'Select (count(*) as ?countRow)  WHERE { ?s ' + '?p \"' + obj + '\"}'\n        \n    sparql = SPARQLWrapper(\"http://zen.cs.rpi.edu:8890/sparql\")\n    sparql.setQuery(sparqlQuery)\n    sparql.setReturnFormat(JSON)\n    results = sparql.query().convert()\n    results_df = json_normalize(results[\"results\"][\"bindings\"])\n    val = float(results_df['countRow.value'])\n    return val\nresults_df = results_df[results_df['countS.value'] > 1]\nresults_df['Popularity'] = results_df['o.value'].apply(execute_count_query)\nresults_df['Popularity'] = results_df['Popularity'].apply(math.log)\nresults_df.sort_values(by=['Popularity'],ascending=True,inplace=True)\ndisplay(results_df)\n```\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>index</th>\n      <th>p.value</th>\n      <th>o.value</th>\n      <th>countS.value</th>\n      <th>Specificity</th>\n      <th>Popularity</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>11</th>\n      <td>26</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Venice_Best_Director_Silver_Lion_winners</td>\n      <td>19</td>\n      <td>12.406193</td>\n      <td>2.944439</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>29</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:People_from_Corona,_Queens</td>\n      <td>24</td>\n      <td>12.172578</td>\n      <td>3.178054</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>31</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Best_Director_BAFTA_Award_winners</td>\n      <td>38</td>\n      <td>11.713046</td>\n      <td>3.637586</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>32</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:David_di_Donatello_Career_Award_winners</td>\n      <td>45</td>\n      <td>11.543970</td>\n      <td>3.806662</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>33</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_film_directors_of_Italian_descent</td>\n      <td>52</td>\n      <td>11.399388</td>\n      <td>3.951244</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>34</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Best_Director_Golden_Globe_winners</td>\n      <td>52</td>\n      <td>11.399388</td>\n      <td>3.970292</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>35</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Cecil_B._DeMille_Award_Golden_Globe_winners</td>\n      <td>62</td>\n      <td>11.223498</td>\n      <td>4.127134</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>37</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Best_Director_Academy_Award_winners</td>\n      <td>68</td>\n      <td>11.131124</td>\n      <td>4.234107</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>46</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:C\u00e9sar_Award_winners</td>\n      <td>137</td>\n      <td>10.430651</td>\n      <td>4.983607</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>48</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Film_theorists</td>\n      <td>155</td>\n      <td>10.307207</td>\n      <td>5.043425</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>50</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Directors_Guild_of_America_Award_winners</td>\n      <td>184</td>\n      <td>10.135696</td>\n      <td>5.214936</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>51</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Kennedy_Center_honorees</td>\n      <td>188</td>\n      <td>10.114190</td>\n      <td>5.247024</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>52</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Film_directors_from_New_York_City</td>\n      <td>198</td>\n      <td>10.062365</td>\n      <td>5.288267</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>53</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Transcendental_Meditation_practitioners</td>\n      <td>212</td>\n      <td>9.994046</td>\n      <td>5.356586</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>54</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_people_of_Sicilian_descent</td>\n      <td>267</td>\n      <td>9.763384</td>\n      <td>5.598422</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>55</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_music_video_directors</td>\n      <td>372</td>\n      <td>9.431738</td>\n      <td>5.921578</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>38</td>\n      <td>http://dbpedia.org/ontology/birthPlace</td>\n      <td>http://dbpedia.org/resource/Flushing,_Queens</td>\n      <td>88</td>\n      <td>10.873295</td>\n      <td>6.011267</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>57</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Primetime_Emmy_Award_winners</td>\n      <td>431</td>\n      <td>9.284524</td>\n      <td>6.109248</td>\n    </tr>\n    <tr>\n      <th>30</th>\n      <td>59</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_film_editors</td>\n      <td>503</td>\n      <td>9.130042</td>\n      <td>6.222576</td>\n    </tr>\n    <tr>\n      <th>31</th>\n      <td>60</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:English-language_film_directors</td>\n      <td>520</td>\n      <td>9.096803</td>\n      <td>6.257668</td>\n    </tr>\n    <tr>\n      <th>34</th>\n      <td>65</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_documentary_filmmakers</td>\n      <td>649</td>\n      <td>8.875199</td>\n      <td>6.476972</td>\n    </tr>\n    <tr>\n      <th>35</th>\n      <td>66</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Male_actors_of_Italian_descent</td>\n      <td>726</td>\n      <td>8.763082</td>\n      <td>6.587550</td>\n    </tr>\n    <tr>\n      <th>36</th>\n      <td>67</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Tisch_School_of_the_Arts_alumni</td>\n      <td>817</td>\n      <td>8.644993</td>\n      <td>6.705639</td>\n    </tr>\n    <tr>\n      <th>37</th>\n      <td>68</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:L\u00e9gion_d'honneur_recipients</td>\n      <td>885</td>\n      <td>8.565045</td>\n      <td>6.796824</td>\n    </tr>\n    <tr>\n      <th>38</th>\n      <td>74</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Male_actors_from_New_York_City</td>\n      <td>1454</td>\n      <td>8.068559</td>\n      <td>7.282761</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>58</td>\n      <td>http://dbpedia.org/property/almaMater</td>\n      <td>http://dbpedia.org/resource/New_York_University</td>\n      <td>498</td>\n      <td>9.140032</td>\n      <td>7.423568</td>\n    </tr>\n    <tr>\n      <th>32</th>\n      <td>63</td>\n      <td>http://dbpedia.org/ontology/almaMater</td>\n      <td>http://dbpedia.org/resource/New_York_University</td>\n      <td>581</td>\n      <td>8.985881</td>\n      <td>7.423568</td>\n    </tr>\n    <tr>\n      <th>39</th>\n      <td>77</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Fellows_of_the_American_Academy_of_Arts_and_Sciences</td>\n      <td>1864</td>\n      <td>7.820152</td>\n      <td>7.531016</td>\n    </tr>\n    <tr>\n      <th>40</th>\n      <td>78</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:New_York_Democrats</td>\n      <td>1966</td>\n      <td>7.766876</td>\n      <td>7.584773</td>\n    </tr>\n    <tr>\n      <th>33</th>\n      <td>64</td>\n      <td>http://dbpedia.org/ontology/birthPlace</td>\n      <td>http://dbpedia.org/resource/Queens</td>\n      <td>595</td>\n      <td>8.962071</td>\n      <td>7.755767</td>\n    </tr>\n    <tr>\n      <th>41</th>\n      <td>81</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Grammy_Award_winners</td>\n      <td>2389</td>\n      <td>7.572002</td>\n      <td>7.779467</td>\n    </tr>\n    <tr>\n      <th>42</th>\n      <td>82</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_Roman_Catholics</td>\n      <td>2393</td>\n      <td>7.570329</td>\n      <td>7.787382</td>\n    </tr>\n    <tr>\n      <th>43</th>\n      <td>84</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:21st-century_American_male_actors</td>\n      <td>3465</td>\n      <td>7.200164</td>\n      <td>8.151045</td>\n    </tr>\n    <tr>\n      <th>44</th>\n      <td>85</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_film_producers</td>\n      <td>3489</td>\n      <td>7.193262</td>\n      <td>8.158516</td>\n    </tr>\n    <tr>\n      <th>45</th>\n      <td>86</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_male_screenwriters</td>\n      <td>3608</td>\n      <td>7.159723</td>\n      <td>8.191186</td>\n    </tr>\n    <tr>\n      <th>46</th>\n      <td>88</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_film_directors</td>\n      <td>4477</td>\n      <td>6.943924</td>\n      <td>8.408940</td>\n    </tr>\n    <tr>\n      <th>47</th>\n      <td>89</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:20th-century_American_male_actors</td>\n      <td>6540</td>\n      <td>6.564940</td>\n      <td>8.786151</td>\n    </tr>\n    <tr>\n      <th>49</th>\n      <td>92</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:1942_births</td>\n      <td>8423</td>\n      <td>6.311911</td>\n      <td>9.038721</td>\n    </tr>\n    <tr>\n      <th>50</th>\n      <td>93</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_male_film_actors</td>\n      <td>10374</td>\n      <td>6.103574</td>\n      <td>9.247443</td>\n    </tr>\n    <tr>\n      <th>48</th>\n      <td>91</td>\n      <td>http://dbpedia.org/ontology/birthPlace</td>\n      <td>http://dbpedia.org/resource/New_York</td>\n      <td>8078</td>\n      <td>6.353733</td>\n      <td>10.642826</td>\n    </tr>\n    <tr>\n      <th>51</th>\n      <td>94</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Living_people</td>\n      <td>729176</td>\n      <td>1.850962</td>\n      <td>13.499699</td>\n    </tr>\n    <tr>\n      <th>53</th>\n      <td>96</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://www.wikidata.org/entity/Q215627</td>\n      <td>1587944</td>\n      <td>1.072682</td>\n      <td>14.277952</td>\n    </tr>\n    <tr>\n      <th>54</th>\n      <td>97</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://www.wikidata.org/entity/Q5</td>\n      <td>1587944</td>\n      <td>1.072682</td>\n      <td>14.277952</td>\n    </tr>\n    <tr>\n      <th>55</th>\n      <td>98</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://schema.org/Person</td>\n      <td>1587944</td>\n      <td>1.072682</td>\n      <td>14.277952</td>\n    </tr>\n    <tr>\n      <th>56</th>\n      <td>99</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#NaturalPerson</td>\n      <td>1587944</td>\n      <td>1.072682</td>\n      <td>14.277952</td>\n    </tr>\n    <tr>\n      <th>52</th>\n      <td>95</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://dbpedia.org/ontology/Person</td>\n      <td>1587944</td>\n      <td>1.072682</td>\n      <td>14.278273</td>\n    </tr>\n    <tr>\n      <th>57</th>\n      <td>100</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://xmlns.com/foaf/0.1/Person</td>\n      <td>1588593</td>\n      <td>1.072273</td>\n      <td>14.278386</td>\n    </tr>\n    <tr>\n      <th>59</th>\n      <td>102</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#Agent</td>\n      <td>1855262</td>\n      <td>0.917096</td>\n      <td>14.433537</td>\n    </tr>\n    <tr>\n      <th>58</th>\n      <td>101</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://dbpedia.org/ontology/Agent</td>\n      <td>1855262</td>\n      <td>0.917096</td>\n      <td>14.433553</td>\n    </tr>\n    <tr>\n      <th>60</th>\n      <td>103</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://www.w3.org/2002/07/owl#Thing</td>\n      <td>4995959</td>\n      <td>-0.073508</td>\n      <td>15.424158</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\nClearly from the above results, we see that the most popular object values are ranked higher. Let us now use this to determine the combined ranking and then pick features:\n\n\n```python\nresults_df['Rank'] = results_df['Specificity'] * results_df['Popularity']\nresults_df.sort_values(by=['Rank'],ascending=False,inplace=True)\ndisplay(results_df)\n```\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>index</th>\n      <th>p.value</th>\n      <th>o.value</th>\n      <th>countS.value</th>\n      <th>Specificity</th>\n      <th>Popularity</th>\n      <th>Rank</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>33</th>\n      <td>64</td>\n      <td>http://dbpedia.org/ontology/birthPlace</td>\n      <td>http://dbpedia.org/resource/Queens</td>\n      <td>595</td>\n      <td>8.962071</td>\n      <td>7.755767</td>\n      <td>69.507734</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>58</td>\n      <td>http://dbpedia.org/property/almaMater</td>\n      <td>http://dbpedia.org/resource/New_York_University</td>\n      <td>498</td>\n      <td>9.140032</td>\n      <td>7.423568</td>\n      <td>67.851654</td>\n    </tr>\n    <tr>\n      <th>48</th>\n      <td>91</td>\n      <td>http://dbpedia.org/ontology/birthPlace</td>\n      <td>http://dbpedia.org/resource/New_York</td>\n      <td>8078</td>\n      <td>6.353733</td>\n      <td>10.642826</td>\n      <td>67.621672</td>\n    </tr>\n    <tr>\n      <th>32</th>\n      <td>63</td>\n      <td>http://dbpedia.org/ontology/almaMater</td>\n      <td>http://dbpedia.org/resource/New_York_University</td>\n      <td>581</td>\n      <td>8.985881</td>\n      <td>7.423568</td>\n      <td>66.707306</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>38</td>\n      <td>http://dbpedia.org/ontology/birthPlace</td>\n      <td>http://dbpedia.org/resource/Flushing,_Queens</td>\n      <td>88</td>\n      <td>10.873295</td>\n      <td>6.011267</td>\n      <td>65.362283</td>\n    </tr>\n    <tr>\n      <th>42</th>\n      <td>82</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_Roman_Catholics</td>\n      <td>2393</td>\n      <td>7.570329</td>\n      <td>7.787382</td>\n      <td>58.953045</td>\n    </tr>\n    <tr>\n      <th>40</th>\n      <td>78</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:New_York_Democrats</td>\n      <td>1966</td>\n      <td>7.766876</td>\n      <td>7.584773</td>\n      <td>58.909991</td>\n    </tr>\n    <tr>\n      <th>41</th>\n      <td>81</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Grammy_Award_winners</td>\n      <td>2389</td>\n      <td>7.572002</td>\n      <td>7.779467</td>\n      <td>58.906140</td>\n    </tr>\n    <tr>\n      <th>39</th>\n      <td>77</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Fellows_of_the_American_Academy_of_Arts_and_Sciences</td>\n      <td>1864</td>\n      <td>7.820152</td>\n      <td>7.531016</td>\n      <td>58.893694</td>\n    </tr>\n    <tr>\n      <th>38</th>\n      <td>74</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Male_actors_from_New_York_City</td>\n      <td>1454</td>\n      <td>8.068559</td>\n      <td>7.282761</td>\n      <td>58.761385</td>\n    </tr>\n    <tr>\n      <th>43</th>\n      <td>84</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:21st-century_American_male_actors</td>\n      <td>3465</td>\n      <td>7.200164</td>\n      <td>8.151045</td>\n      <td>58.688862</td>\n    </tr>\n    <tr>\n      <th>44</th>\n      <td>85</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_film_producers</td>\n      <td>3489</td>\n      <td>7.193262</td>\n      <td>8.158516</td>\n      <td>58.686343</td>\n    </tr>\n    <tr>\n      <th>45</th>\n      <td>86</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_male_screenwriters</td>\n      <td>3608</td>\n      <td>7.159723</td>\n      <td>8.191186</td>\n      <td>58.646625</td>\n    </tr>\n    <tr>\n      <th>46</th>\n      <td>88</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_film_directors</td>\n      <td>4477</td>\n      <td>6.943924</td>\n      <td>8.408940</td>\n      <td>58.391035</td>\n    </tr>\n    <tr>\n      <th>37</th>\n      <td>68</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:L\u00e9gion_d'honneur_recipients</td>\n      <td>885</td>\n      <td>8.565045</td>\n      <td>6.796824</td>\n      <td>58.215098</td>\n    </tr>\n    <tr>\n      <th>36</th>\n      <td>67</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Tisch_School_of_the_Arts_alumni</td>\n      <td>817</td>\n      <td>8.644993</td>\n      <td>6.705639</td>\n      <td>57.970204</td>\n    </tr>\n    <tr>\n      <th>35</th>\n      <td>66</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Male_actors_of_Italian_descent</td>\n      <td>726</td>\n      <td>8.763082</td>\n      <td>6.587550</td>\n      <td>57.727242</td>\n    </tr>\n    <tr>\n      <th>47</th>\n      <td>89</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:20th-century_American_male_actors</td>\n      <td>6540</td>\n      <td>6.564940</td>\n      <td>8.786151</td>\n      <td>57.680552</td>\n    </tr>\n    <tr>\n      <th>34</th>\n      <td>65</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_documentary_filmmakers</td>\n      <td>649</td>\n      <td>8.875199</td>\n      <td>6.476972</td>\n      <td>57.484422</td>\n    </tr>\n    <tr>\n      <th>49</th>\n      <td>92</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:1942_births</td>\n      <td>8423</td>\n      <td>6.311911</td>\n      <td>9.038721</td>\n      <td>57.051603</td>\n    </tr>\n    <tr>\n      <th>31</th>\n      <td>60</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:English-language_film_directors</td>\n      <td>520</td>\n      <td>9.096803</td>\n      <td>6.257668</td>\n      <td>56.924772</td>\n    </tr>\n    <tr>\n      <th>30</th>\n      <td>59</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_film_editors</td>\n      <td>503</td>\n      <td>9.130042</td>\n      <td>6.222576</td>\n      <td>56.812383</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>57</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Primetime_Emmy_Award_winners</td>\n      <td>431</td>\n      <td>9.284524</td>\n      <td>6.109248</td>\n      <td>56.721456</td>\n    </tr>\n    <tr>\n      <th>50</th>\n      <td>93</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_male_film_actors</td>\n      <td>10374</td>\n      <td>6.103574</td>\n      <td>9.247443</td>\n      <td>56.442457</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>55</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_music_video_directors</td>\n      <td>372</td>\n      <td>9.431738</td>\n      <td>5.921578</td>\n      <td>55.850778</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>54</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_people_of_Sicilian_descent</td>\n      <td>267</td>\n      <td>9.763384</td>\n      <td>5.598422</td>\n      <td>54.659541</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>53</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Transcendental_Meditation_practitioners</td>\n      <td>212</td>\n      <td>9.994046</td>\n      <td>5.356586</td>\n      <td>53.533969</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>52</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Film_directors_from_New_York_City</td>\n      <td>198</td>\n      <td>10.062365</td>\n      <td>5.288267</td>\n      <td>53.212474</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>51</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Kennedy_Center_honorees</td>\n      <td>188</td>\n      <td>10.114190</td>\n      <td>5.247024</td>\n      <td>53.069399</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>50</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Directors_Guild_of_America_Award_winners</td>\n      <td>184</td>\n      <td>10.135696</td>\n      <td>5.214936</td>\n      <td>52.857006</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>48</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Film_theorists</td>\n      <td>155</td>\n      <td>10.307207</td>\n      <td>5.043425</td>\n      <td>51.983627</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>46</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:C\u00e9sar_Award_winners</td>\n      <td>137</td>\n      <td>10.430651</td>\n      <td>4.983607</td>\n      <td>51.982263</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>37</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Best_Director_Academy_Award_winners</td>\n      <td>68</td>\n      <td>11.131124</td>\n      <td>4.234107</td>\n      <td>47.130366</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>35</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Cecil_B._DeMille_Award_Golden_Globe_winners</td>\n      <td>62</td>\n      <td>11.223498</td>\n      <td>4.127134</td>\n      <td>46.320884</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>34</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Best_Director_Golden_Globe_winners</td>\n      <td>52</td>\n      <td>11.399388</td>\n      <td>3.970292</td>\n      <td>45.258900</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>33</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:American_film_directors_of_Italian_descent</td>\n      <td>52</td>\n      <td>11.399388</td>\n      <td>3.951244</td>\n      <td>45.041762</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>32</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:David_di_Donatello_Career_Award_winners</td>\n      <td>45</td>\n      <td>11.543970</td>\n      <td>3.806662</td>\n      <td>43.943996</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>31</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Best_Director_BAFTA_Award_winners</td>\n      <td>38</td>\n      <td>11.713046</td>\n      <td>3.637586</td>\n      <td>42.607214</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>29</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:People_from_Corona,_Queens</td>\n      <td>24</td>\n      <td>12.172578</td>\n      <td>3.178054</td>\n      <td>38.685109</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>26</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Venice_Best_Director_Silver_Lion_winners</td>\n      <td>19</td>\n      <td>12.406193</td>\n      <td>2.944439</td>\n      <td>36.529279</td>\n    </tr>\n    <tr>\n      <th>51</th>\n      <td>94</td>\n      <td>http://purl.org/dc/terms/subject</td>\n      <td>http://dbpedia.org/resource/Category:Living_people</td>\n      <td>729176</td>\n      <td>1.850962</td>\n      <td>13.499699</td>\n      <td>24.987427</td>\n    </tr>\n    <tr>\n      <th>52</th>\n      <td>95</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://dbpedia.org/ontology/Person</td>\n      <td>1587944</td>\n      <td>1.072682</td>\n      <td>14.278273</td>\n      <td>15.316040</td>\n    </tr>\n    <tr>\n      <th>53</th>\n      <td>96</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://www.wikidata.org/entity/Q215627</td>\n      <td>1587944</td>\n      <td>1.072682</td>\n      <td>14.277952</td>\n      <td>15.315695</td>\n    </tr>\n    <tr>\n      <th>54</th>\n      <td>97</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://www.wikidata.org/entity/Q5</td>\n      <td>1587944</td>\n      <td>1.072682</td>\n      <td>14.277952</td>\n      <td>15.315695</td>\n    </tr>\n    <tr>\n      <th>55</th>\n      <td>98</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://schema.org/Person</td>\n      <td>1587944</td>\n      <td>1.072682</td>\n      <td>14.277952</td>\n      <td>15.315695</td>\n    </tr>\n    <tr>\n      <th>56</th>\n      <td>99</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#NaturalPerson</td>\n      <td>1587944</td>\n      <td>1.072682</td>\n      <td>14.277952</td>\n      <td>15.315695</td>\n    </tr>\n    <tr>\n      <th>57</th>\n      <td>100</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://xmlns.com/foaf/0.1/Person</td>\n      <td>1588593</td>\n      <td>1.072273</td>\n      <td>14.278386</td>\n      <td>15.310326</td>\n    </tr>\n    <tr>\n      <th>58</th>\n      <td>101</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://dbpedia.org/ontology/Agent</td>\n      <td>1855262</td>\n      <td>0.917096</td>\n      <td>14.433553</td>\n      <td>13.236949</td>\n    </tr>\n    <tr>\n      <th>59</th>\n      <td>102</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#Agent</td>\n      <td>1855262</td>\n      <td>0.917096</td>\n      <td>14.433537</td>\n      <td>13.236935</td>\n    </tr>\n    <tr>\n      <th>60</th>\n      <td>103</td>\n      <td>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</td>\n      <td>http://www.w3.org/2002/07/owl#Thing</td>\n      <td>4995959</td>\n      <td>-0.073508</td>\n      <td>15.424158</td>\n      <td>-1.133795</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\nAlthough some properties are repeated, because of the nature of DBpedia, we see that features like `birthPlace, Queens` and `almaMater New_York_University` are more representative of the entities similar to `dbr:Martin_Scorsese`. Let us now pick the top 2 features to create reformulate the original query as :\n```\nSelect Distinct movie where {\n?movie dbo:director ?e\n?e http://dbpedia.org/ontology/birthPlace http://dbpedia.org/resource/Queens\t .\t\n?e http://dbpedia.org/property/almaMater  http://dbpedia.org/resource/New_York_University .\n}\n```\n\nNow running it to see the results we get :\n\n\n```python\n%%time \ndbpedia_query =\"\"\"\nPREFIX  schema: <http://schema.org/>\nPREFIX  dbr:  <http://dbpedia.org/resource/>\nPREFIX  umbel-rc: <http://umbel.org/umbel/rc/>\nPREFIX  dbc:  <http://dbpedia.org/resource/Category:>\nPREFIX  owl:  <http://www.w3.org/2002/07/owl#>\nPREFIX  yago: <http://dbpedia.org/class/yago/>\nPREFIX  rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX  dbo:  <http://dbpedia.org/ontology/>\nPREFIX  dbp:  <http://dbpedia.org/property/>\nPREFIX  rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX  dcterms: <http://purl.org/dc/terms/>\nPREFIX  dbpedia-wikidata: <http://wikidata.dbpedia.org/resource/>\nPREFIX  dul:  <http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#>\nPREFIX  foaf: <http://xmlns.com/foaf/0.1/>\nPREFIX  dc:   <http://purl.org/dc/elements/1.1/>\nPREFIX prov: <http://www.w3.org/ns/prov#>\n\nSelect Distinct ?movie ?e where {\n?movie dbo:director ?e .\n?e <http://dbpedia.org/ontology/birthPlace> <http://dbpedia.org/resource/New_York>     .    \n?e <http://dbpedia.org/property/almaMater>  <http://dbpedia.org/resource/New_York_University> .\n}\n\"\"\"\ndbpedia_endpoint = \"http://zen.cs.rpi.edu:8890/sparql\"\nmovies_df = execute_query(dbpedia_query,dbpedia_endpoint)\nprint(\"The toal movies directed by anybody are : \" + str(movies_df.shape[0]))\ndisplay(movies_df)\n```\n\n    The toal movies directed by anybody are : 53\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>e.type</th>\n      <th>e.value</th>\n      <th>movie.type</th>\n      <th>movie.value</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Burt_Lancaster</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Kentuckian</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Burt_Lancaster</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Midnight_Man_(1974_film)</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Made_in_Milan</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Key_to_Reserva</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Mean_Streets</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Raging_Bull</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Taxi_Driver</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Alice_Doesn't_Live_Here_Anymore</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_King_of_Comedy_(1983_film)</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Boxcar_Bertha</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Who's_That_Knocking_at_My_Door</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/My_Voyage_to_Italy</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Goodfellas</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/After_Hours_(film)</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/New_York_Stories</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Kundun</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/No_Direction_Home</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Street_Scenes</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Blues_(film)</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Last_Temptation_of_Christ_(film)</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Vinyl_(TV_series)</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Bringing_Out_the_Dead</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Aviator_(2004_film)</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Shutter_Island_(film)</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Silence_(2016_film)</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Casino_(film)</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/New_York,_New_York_(film)</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Departed</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/A_Personal_Journey_with_Martin_Scorsese_Through_American_Movies</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Age_of_Innocence_(1993_film)</td>\n    </tr>\n    <tr>\n      <th>30</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/What's_a_Nice_Girl_Like_You_Doing_in_a_Place_Like_This%3F</td>\n    </tr>\n    <tr>\n      <th>31</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Shine_a_Light_(film)</td>\n    </tr>\n    <tr>\n      <th>32</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Shine_a_Light_(The_Rolling_Stones_album)</td>\n    </tr>\n    <tr>\n      <th>33</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/George_Harrison:_Living_in_the_Material_World</td>\n    </tr>\n    <tr>\n      <th>34</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/A_Letter_to_Elia</td>\n    </tr>\n    <tr>\n      <th>35</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Cape_Fear_(1991_film)</td>\n    </tr>\n    <tr>\n      <th>36</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Gangs_of_New_York</td>\n    </tr>\n    <tr>\n      <th>37</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Color_of_Money</td>\n    </tr>\n    <tr>\n      <th>38</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Last_Waltz</td>\n    </tr>\n    <tr>\n      <th>39</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Big_Shave</td>\n    </tr>\n    <tr>\n      <th>40</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Italianamerican</td>\n    </tr>\n    <tr>\n      <th>41</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/American_Boy:_A_Profile_of_Steven_Prince</td>\n    </tr>\n    <tr>\n      <th>42</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/It's_Not_Just_You,_Murray!</td>\n    </tr>\n    <tr>\n      <th>43</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Hugo_(film)</td>\n    </tr>\n    <tr>\n      <th>44</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Boardwalk_Empire_(episode)</td>\n    </tr>\n    <tr>\n      <th>45</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Wolf_of_Wall_Street_(2013_film)</td>\n    </tr>\n    <tr>\n      <th>46</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Public_Speaking_(film)</td>\n    </tr>\n    <tr>\n      <th>47</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Andrew_Levitas</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Lullaby_(2014_film)</td>\n    </tr>\n    <tr>\n      <th>48</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Herbert_B._Leonard</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Going_Home_(1971_film)</td>\n    </tr>\n    <tr>\n      <th>49</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Herbert_B._Leonard</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Perils_of_Pauline_(1967_film)</td>\n    </tr>\n    <tr>\n      <th>50</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Jesse_Dylan</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/American_Wedding</td>\n    </tr>\n    <tr>\n      <th>51</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Jesse_Dylan</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/How_High</td>\n    </tr>\n    <tr>\n      <th>52</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Jesse_Dylan</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Kicking_&amp;_Screaming_(2005_film)</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    CPU times: user 48 ms, sys: 4 ms, total: 52 ms\n    Wall time: 53.4 ms\n\n\nNow in the above result you see 53 movies which other people have also directed. Thus, you  have other entities like `dbr:Herbert_B.Leonard` and `dbr:Jesse_Dylan` and `dbr:Burt_Lancaster`, who are both directors from `New_York` and are also _film producers_. \n\nLet us also try another query using the other ranked properties i.e. \n\n```\nSelect Distinct ?movie ?e where {\n?movie dbo:director ?e .\n?e <http://purl.org/dc/terms/subject> <http://dbpedia.org/resource/Category:American_Roman_Catholics> .\n?e <http://purl.org/dc/terms/subject> <http://dbpedia.org/resource/Category:New_York_Democrats> .\n}\n```\n\n**Note** : We have already used the `birthPlace` and `almaMater`. So we use the other properties to explicitly be diverse in results.\n\n\n\n```python\n%%time \ndbpedia_query =\"\"\"\nPREFIX  schema: <http://schema.org/>\nPREFIX  dbr:  <http://dbpedia.org/resource/>\nPREFIX  umbel-rc: <http://umbel.org/umbel/rc/>\nPREFIX  dbc:  <http://dbpedia.org/resource/Category:>\nPREFIX  owl:  <http://www.w3.org/2002/07/owl#>\nPREFIX  yago: <http://dbpedia.org/class/yago/>\nPREFIX  rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nPREFIX  dbo:  <http://dbpedia.org/ontology/>\nPREFIX  dbp:  <http://dbpedia.org/property/>\nPREFIX  rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX  dcterms: <http://purl.org/dc/terms/>\nPREFIX  dbpedia-wikidata: <http://wikidata.dbpedia.org/resource/>\nPREFIX  dul:  <http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#>\nPREFIX  foaf: <http://xmlns.com/foaf/0.1/>\nPREFIX  dc:   <http://purl.org/dc/elements/1.1/>\nPREFIX prov: <http://www.w3.org/ns/prov#>\n\nSelect Distinct ?movie ?e where {\n?movie dbo:director ?e .\n?e <http://purl.org/dc/terms/subject> <http://dbpedia.org/resource/Category:American_Roman_Catholics> .\n?e <http://purl.org/dc/terms/subject> <http://dbpedia.org/resource/Category:New_York_Democrats> .\n}\n\"\"\"\ndbpedia_endpoint = \"http://zen.cs.rpi.edu:8890/sparql\"\nmovies_df = execute_query(dbpedia_query,dbpedia_endpoint)\nprint(\"The toal movies directed by anybody are : \" + str(movies_df.shape[0]))\ndisplay(movies_df)\n```\n\n    The toal movies directed by anybody are : 49\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>e.type</th>\n      <th>e.value</th>\n      <th>movie.type</th>\n      <th>movie.value</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/James_Cagney</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Short_Cut_to_Hell</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Made_in_Milan</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Key_to_Reserva</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Mean_Streets</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Raging_Bull</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Taxi_Driver</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Alice_Doesn't_Live_Here_Anymore</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_King_of_Comedy_(1983_film)</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Boxcar_Bertha</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Who's_That_Knocking_at_My_Door</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/My_Voyage_to_Italy</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Goodfellas</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/After_Hours_(film)</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/New_York_Stories</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Kundun</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/No_Direction_Home</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Street_Scenes</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Blues_(film)</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Last_Temptation_of_Christ_(film)</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Vinyl_(TV_series)</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Bringing_Out_the_Dead</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Aviator_(2004_film)</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Shutter_Island_(film)</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Silence_(2016_film)</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Casino_(film)</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/New_York,_New_York_(film)</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Departed</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/A_Personal_Journey_with_Martin_Scorsese_Through_American_Movies</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Age_of_Innocence_(1993_film)</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/What's_a_Nice_Girl_Like_You_Doing_in_a_Place_Like_This%3F</td>\n    </tr>\n    <tr>\n      <th>30</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Shine_a_Light_(film)</td>\n    </tr>\n    <tr>\n      <th>31</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Shine_a_Light_(The_Rolling_Stones_album)</td>\n    </tr>\n    <tr>\n      <th>32</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/George_Harrison:_Living_in_the_Material_World</td>\n    </tr>\n    <tr>\n      <th>33</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/A_Letter_to_Elia</td>\n    </tr>\n    <tr>\n      <th>34</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Cape_Fear_(1991_film)</td>\n    </tr>\n    <tr>\n      <th>35</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Gangs_of_New_York</td>\n    </tr>\n    <tr>\n      <th>36</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Color_of_Money</td>\n    </tr>\n    <tr>\n      <th>37</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Last_Waltz</td>\n    </tr>\n    <tr>\n      <th>38</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Big_Shave</td>\n    </tr>\n    <tr>\n      <th>39</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Italianamerican</td>\n    </tr>\n    <tr>\n      <th>40</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/American_Boy:_A_Profile_of_Steven_Prince</td>\n    </tr>\n    <tr>\n      <th>41</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/It's_Not_Just_You,_Murray!</td>\n    </tr>\n    <tr>\n      <th>42</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Hugo_(film)</td>\n    </tr>\n    <tr>\n      <th>43</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Boardwalk_Empire_(episode)</td>\n    </tr>\n    <tr>\n      <th>44</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Wolf_of_Wall_Street_(2013_film)</td>\n    </tr>\n    <tr>\n      <th>45</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Martin_Scorsese</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Public_Speaking_(film)</td>\n    </tr>\n    <tr>\n      <th>46</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Robert_De_Niro</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/The_Good_Shepherd_(film)</td>\n    </tr>\n    <tr>\n      <th>47</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Robert_De_Niro</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/A_Bronx_Tale</td>\n    </tr>\n    <tr>\n      <th>48</th>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Alec_Baldwin</td>\n      <td>uri</td>\n      <td>http://dbpedia.org/resource/Shortcut_to_Happiness</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    CPU times: user 28 ms, sys: 8 ms, total: 36 ms\n    Wall time: 37 ms\n\n\nNow in the above result you see 49 movies which other people have also directed. Thus, you  have other entities like `dbr:Robert_De_Niro` and `dbr:Alec_Baldwin`, who are related to `dbr:Martin_Scorsese`. \n\nSo we now have the following comparisons between relaxation and reformulation. There are a total of `45 + 4 + 8 = 57 ` unique results out of the reformulation procedure, whereas the relaxation has a total of `102808` results. The `57` results are more related to the `?movie` variable of the original query because of using the _contextualized_ features.\n\n### Results Comparison\n| Original Query        | **Relaxation**           | Ref-1 | Ref-2 | Combined |\n| ------------- |:-------------:|:--------:|:-------:|:---------|\n|45|102808|49|53|57|\n\n### Time Comparison\n | **Relaxation**           | Ref-1 | Ref-2 | \n|:-------------:|:--------:|:-------:|\n|5010ms|53.4ms|39ms|\n\n* Clearly the **relaxation results are higher, whereas the reformulation results are lesser**. This makes this kind of reformulation more precise.\n* In addition the time calculation shows that the **resulting reformulations also run in lesser time than the relaxed version of the query**.\n\n\n\nYou can access the [jsfiddle](http://jsfiddle.net/N00bsie/dynpyrLq/3/)\n\n# Conclusions\n\nFrom the above results, we believe that this technique can be used to _contextualize_ entities and be used to reformulate entities in entity queries instead of relaxation.\n", "meta": {"hexsha": "f55f751d52dee7ddba99d6e88ad5bf6a56e750a8", "size": 345594, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Workflow.ipynb", "max_stars_repo_name": "N00bsie/QueryReformulation", "max_stars_repo_head_hexsha": "1bd3d3f532191b4f257e7ab21cb79196203b9552", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Workflow.ipynb", "max_issues_repo_name": "N00bsie/QueryReformulation", "max_issues_repo_head_hexsha": "1bd3d3f532191b4f257e7ab21cb79196203b9552", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Workflow.ipynb", "max_forks_repo_name": "N00bsie/QueryReformulation", "max_forks_repo_head_hexsha": "1bd3d3f532191b4f257e7ab21cb79196203b9552", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-03T13:59:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-03T13:59:04.000Z", "avg_line_length": 47.4782250309, "max_line_length": 459, "alphanum_fraction": 0.421804198, "converted": true, "num_tokens": 53797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27512973571032984, "lm_q2_score": 0.11436852618181247, "lm_q1q2_score": 0.031466182381982004}}
{"text": "## Enable rendering OpenAI Gym environments from CoLab\n\nIn this assignemnt, We will use [OpenAI Gym](https://gym.openai.com/) for rendering game envionment for our agent to play and learn. It is possible and important to visualize the game your agent is playing, even on Colab. This section imports the necessary package and functions needed to generate a video in Colab. The video processing steps credit to [here](https://colab.research.google.com/drive/1flu31ulJlgiRL1dnN2ir8wGh9p7Zij2t).\n\n\n```\n!pip install gym pyvirtualdisplay > /dev/null 2>&1\n!apt-get install -y xvfb python-opengl ffmpeg > /dev/null 2>&1\n```\n\n\n```\n!apt-get update > /dev/null 2>&1\n!apt-get install cmake > /dev/null 2>&1\n!pip install --upgrade setuptools 2>&1\n!pip install ez_setup > /dev/null 2>&1\n!pip install gym[atari] > /dev/null 2>&1\n```\n\n    Requirement already up-to-date: setuptools in /usr/local/lib/python3.7/dist-packages (54.1.2)\n\n\nImport openAI gym and define the functions used to show the video.\n\n\n```\nimport gym\nfrom gym.wrappers import Monitor\nimport glob\nimport io\nimport base64\nfrom IPython.display import HTML\nfrom pyvirtualdisplay import Display\nfrom IPython import display as ipythondisplay\n\ndisplay = Display(visible=0, size=(1400, 900))\ndisplay.start()\n\n\"\"\"\nUtility functions to enable video recording of gym environment \nand displaying it.\nTo enable video, just do \"env = wrap_env(env)\"\"\n\"\"\"\n\ndef show_video():\n  mp4list = glob.glob('video/*.mp4')\n  if len(mp4list) > 0:\n    mp4 = mp4list[0]\n    video = io.open(mp4, 'r+b').read()\n    encoded = base64.b64encode(video)\n    ipythondisplay.display(HTML(data=''''''.format(encoded.decode('ascii'))))\n  else: \n    print(\"Could not find video\")\n    \n\ndef wrap_env(env):\n  env = Monitor(env, './video', force=True)\n  return env\n```\n\nImport other packages:\n\nWe will use Pytorch for building and learning our DQN network.\n\n\n```\nimport torch\nfrom torch import nn\nimport copy\nfrom collections import deque\nimport random\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\n```\n\n## Run the game with random agent.\n\n\n```\nfrom torch import randint\nfrom time import sleep\n\nenv = wrap_env(gym.make('CartPole-v0'))\nreward_arr = []\nepisode_count = 20\nfor i in tqdm(range(episode_count)):\n    obs, done, rew = env.reset(), False, 0\n    env.render()\n    while not done:\n        A = randint(0, env.action_space.n, (1,))\n        obs, reward, done, info = env.step(A.item())\n        rew += reward\n        sleep(0.01)\n    reward_arr.append(rew)\nprint(\"average reward per episode :\", sum(reward_arr) / len(reward_arr))\nenv.close()\nshow_video()\n```\n\nYou can see that a random agent is having trouble balancing the CartPole, just like you. However, a difficult game for human may be very simple to a computer. Let's see how we can use DQN to train a agent. \n\n## Experience Replay\n\nThe technique of experience replay was first proposed in to resolve temporal correlation in the input data by mixing recent experiences as well past experiences, essentially forcing the input to become independent and identically distributed (i.i.d.). It has been shown that this greatly stabilizes\nand improves the DQN training procedure.\n\n\n```\nclass ExperienceReplay(object):\n      def __init__(self, length):\n        self.experience_replay = deque(maxlen=length)\n\n      def collect(self, experience):\n        self.experience_replay.append(experience)\n        return\n\n      def sample_from_experience(self, sample_size):\n        if len(self.experience_replay) < sample_size:\n            sample_size = len(self.experience_replay)\n        sample = random.sample(self.experience_replay, sample_size)\n        state = torch.tensor([exp[0] for exp in sample]).float()\n        action = torch.tensor([exp[1] for exp in sample]).float()\n        reward = torch.tensor([exp[2] for exp in sample]).float()\n        next_state = torch.tensor([exp[3] for exp in sample]).float()\n        return state, action, reward, next_state\n\n```\n\n## Build our DQN Network\n\nWe will use a simple multi-layer neural network to learn the optimal actions. We will use Adam Optimizor and MSE loss for training.\n\n\n```\nclass DQN_Network:\n\n    def __init__(self, layer_size_list, lr, seed=1423):\n        torch.manual_seed(seed)\n        self.policy_net = self.create_network(layer_size_list)\n        self.target_net = copy.deepcopy(self.policy_net)\n  \n        self.loss_fn = torch.nn.MSELoss()\n        self.optimizer = torch.optim.Adam(self.policy_net.parameters(), lr=lr)\n\n        self.step = 0\n        self.gamma = torch.tensor(0.95).float()\n        return\n\n    def create_network(self, layer_size_list):\n        assert len(layer_size_list) > 1\n\n        layers = []\n        for i in range(len(layer_size_list) - 1):\n            linear = nn.Linear(layer_size_list[i], layer_size_list[i + 1])\n\n            if i < len(layer_size_list) - 2:\n              activation = nn.Tanh()\n            else:\n              activation = nn.Identity()\n\n            layers += (linear, activation)\n        return nn.Sequential(*layers)\n\n    def load_pretrained_model(self, model_path):\n        self.policy_net.load_state_dict(torch.load(model_path))\n\n    def save_trained_model(self, model_path=\"cartpole-dqn.pth\"):\n        torch.save(self.policy_net.state_dict(), model_path)\n\n```\n\n## **[Your task]**: complete the function that chooses the next action\n\nChoose next action based on **$\\epsilon$-greedy**:\n\n\\begin{align}\\text{where} \\quad \\mathcal{a_{t+1}} = \\begin{cases}\n     \\text{argmax}_{a}Q(a, s)  & \\text{with probability }: 1 - \\epsilon, \\text{exploitation}\\\\\n     \\text{Uniform}\\{a_{1},...,a_{n}\\} & \\text{with probability}:   \\epsilon, \\text{exploration} \\\\\n   \\end{cases}\\end{align}\n\n\n```\ndef get_action(model, state, action_space_len, epsilon):\n    # We do not require gradient at this point, because this function will be used either\n    # during experience collection or during inference\n\n    with torch.no_grad():\n        Qp = model.policy_net(torch.from_numpy(state).float())\n    Q_value, action = torch.max(Qp, axis=0)\n\n    ## TODO: select action and action\n\n    return \n```\n\n### **[Your task]**: complete the function that train the network for one step\n\nHere, you can find an ``train`` function that performs a\nsingle step of the optimization. \n\nFor our training update rule, the loss you are trying to minimize is:\n\n\\begin{align}\\text{loss} = Q(s, a) - (r + \\gamma \\max_a Q(s', a))\\end{align}\n\n\n```\ndef train(model, batch_size):\n    state, action, reward, next_state = memory.sample_from_experience(sample_size=batch_size)\n\n    # TODO: predict expected return of current state using main network\n\n\n    # TODO: get target return using target network\n\n    # TODO: compute the loss\n    loss = \n    model.optimizer.zero_grad()\n    loss.backward(retain_graph=True)\n    model.optimizer.step()\n\n    model.step += 1\n    if model.step % 5 == 0:\n        model.target_net.load_state_dict(model.policy_net.state_dict())\n\n    return loss.item()\n```\n\n### **[Your task]**: Finish the training loop\n\nIn this part, you can play around with ```exp_replay_size```, ```episode```, ```epsilon``` and the \"episodo decay\" logic to train your model.\n\n\n```\n# Create the model\nenv = gym.make('CartPole-v0')\ninput_dim = env.observation_space.shape[0]\noutput_dim = env.action_space.n\nagent = DQN_Network(layer_size_list=[input_dim, 64, output_dim], lr=1e-3)\n\n# Main training loop\nlosses_list, reward_list, episode_len_list, epsilon_list = [], [], [], []\n\n# TODO: try different values, it normally takes more than 6k episodes to train\nexp_replay_size = \nmemory = ExperienceReplay(exp_replay_size)\nepisodes = \nepsilon = 1 # episilon start from 1 and decay gradually. \n\n# initiliaze experiance replay\nindex = 0\nfor i in range(exp_replay_size):\n    obs = env.reset()\n    done = False\n    while not done:\n        A = get_action(agent, obs, env.action_space.n, epsilon=1)\n        obs_next, reward, done, _ = env.step(A.item())\n        memory.collect([obs, A.item(), reward, obs_next])\n        obs = obs_next\n        index += 1\n        if index > exp_replay_size:\n            break\n\nindex = 128\nfor i in tqdm(range(episodes)):\n    obs, done, losses, ep_len, rew = env.reset(), False, 0, 0, 0\n    while not done:\n        ep_len += 1\n        A = get_action(agent, obs, env.action_space.n, epsilon)\n        obs_next, reward, done, _ = env.step(A.item())\n        memory.collect([obs, A.item(), reward, obs_next])\n\n        obs = obs_next\n        rew += reward\n        index += 1\n\n        if index > 128:\n            index = 0\n            for j in range(4):\n                loss = train(agent, batch_size=16)\n                losses += loss\n    \n    # TODO: add epsilon decay rule here! \n\n    losses_list.append(losses / ep_len), reward_list.append(rew)\n    episode_len_list.append(ep_len), epsilon_list.append(epsilon)\n\nprint(\"Saving trained model\")\nagent.save_trained_model(\"cartpole-dqn.pth\")\n```\n\n## Last Step: evaluate your trained model!\n\nFirst we can plot the reward vs. episode:\n\n\n```\ndef plot_reward(r):\n    plt.figure(2)\n    plt.clf()\n    plt.title('Result')\n    plt.xlabel('Episode')\n    plt.ylabel('Reward')\n    plt.plot(r)\n\nplot_reward(reward_list)\n```\n\n\n```\nenv = wrap_env(gym.make('CartPole-v0'))\n\ninput_dim = env.observation_space.shape[0]\noutput_dim = env.action_space.n\nmodel_validate = DQN_Network(layer_size_list=[input_dim, 64, output_dim], lr=1e-3)\nmodel_validate.load_pretrained_model(\"cartpole-dqn.pth\")\n\nreward_arr = []\nfor i in tqdm(range(300)):\n    obs, done, rew = env.reset(), False, 0\n    env.render()\n    while not done:\n        A = get_action(model_validate, obs, env.action_space.n, epsilon=0)\n        obs, reward, done, info = env.step(A.item())\n        rew += reward\n        # sleep(0.01)\n\n    reward_arr.append(rew)\nprint(\"average reward per episode :\", sum(reward_arr) / len(reward_arr))\nenv.close()\nshow_video()\n```\n", "meta": {"hexsha": "4ed19f188d8cc3dadc6a650a35be696b2eb83aa9", "size": 17439, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "assets/assignments/a4-dqn.ipynb", "max_stars_repo_name": "bowangvector/2021", "max_stars_repo_head_hexsha": "f5ec179840b5ccb20238c860de620cff47f508c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-08T02:24:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T02:24:00.000Z", "max_issues_repo_path": "assets/assignments/a4-dqn.ipynb", "max_issues_repo_name": "bowangvector/2021", "max_issues_repo_head_hexsha": "f5ec179840b5ccb20238c860de620cff47f508c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-06T21:24:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-06T21:24:49.000Z", "max_forks_repo_path": "assets/assignments/a4-dqn.ipynb", "max_forks_repo_name": "bowangvector/2021", "max_forks_repo_head_hexsha": "f5ec179840b5ccb20238c860de620cff47f508c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-01-21T15:41:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-17T19:46:19.000Z", "avg_line_length": 34.1941176471, "max_line_length": 445, "alphanum_fraction": 0.4885601239, "converted": true, "num_tokens": 2492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33458944125318596, "lm_q2_score": 0.09401017390532695, "lm_q1q2_score": 0.03145481155909819}}
{"text": "# Word Embeddings\n\n- **Referent:** Maurice Vogel\n- **Datum:** 05.12.2019\n\nDas vorliegende Notebook soll sowohl einen ersten theoretischen als auch praktischen Einstieg in das Thema *Word Embeddings* bieten. Alle f\u00fcr diese Demo verwendeten Frameworks sind komplett Open-Source und in dem entsprechenden [Git-Repository](https://github.com/theThing92/word_embeddings_demo) verlinkt. Auch der hier gezeigte Source-Code darf frei verwendet werden (MIT-Lizenz).\n\n\n```python\n%matplotlib inline\n\nimport logging\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n```\n\n# Gliederung\n1. Einleitung<br>\n    1.1. Semantik am Beispiel von Lewis Carrols \"Jabberwocky\"<br>\n    1.2. Distributionelle Hypothese<br><br>\n2. theoretischer Hintergrund<br>\n    2.1. lexikalische Semantik<br>\n    2.2. Vektorsemantik<br>\n    2.3. Embeddings<br><br>\n3. Semantik \u00fcber Sparse Vectors<br>\n    3.1. Bag-of-Words (BOW) / Term-Dokument-Matrix<br>\n    3.2. Term-Term-Matrix / Wort-Wort-Matrix<br><br>\n4. Gewichtung von frequenzbasierten Vektoren<br>\n    4.1. TF-IDF<br>\n    4.2. Pointwise Mutual Information<br>\n    4.3. Anwendungsfelder<br><br>\n5. \u00c4hnlichkeitsbestimmung im Vektorraum<br><br>\n6. Semantik \u00fcber Dense Vectors<br>\n    6.1. word2vec<br>\n    6.2. weitere Verfahren<br>\n    6.3. Contextualized String Embeddings<br><br>\n7. Diskussion<br>\n\n## 1. Einleitung\n\n**Lernziele**\n- Was ist die Grundidee hinter vektorraum-basierten Sprachmodellen, wie z.B. Word Embeddings?\n\n### 1.1. Semantik am Beispiel von Lewis Carrols \"Jabberwocky\"\n\nF\u00fcr einen exemplarischen Einstieg in die Thematik betrachten Sie bitte das unten stehende Gedicht [\"Jabberwocky\" aus Lewis Carrols \"Alice hinter den Spiegeln\" (1871)](https://de.wikipedia.org/wiki/Jabberwocky). \n\n**Aufgaben**: \n1. Was ist die Bedeutung des Wortes <font color='red'>***Jabberwock***</font>? \n2. Wie kann die Semantik dieses unbekannten Wortes erschlossen werden?\n\n>Twas brillig, and the slithy toves<br>\n>Did gyre and gimble in the wabe;<br>\n>All mimsy were the borogoves,<br>\n>And the mome raths outgrabe.<br><br>\n>\n>Beware the <font color='red'>**Jabberwock**</font>, my son!<br>\n>The jaws that bite, the claws that catch!<br>\n>Beware the Jubjub bird, and shun<br>\n>The frumious Bandersnatch!<br><br>\n>\n>He took his vorpal sword in hand:<br>\n>Long time the manxome foe he sought<br>\n>So rested he by the Tumtum tree,<br>\n>And stood awhile in thought.<br><br>\n>\n>And as in uffish thought he stood,<br>\n>The <font color='red'>**Jabberwock**</font>, with eyes of flame,<br>\n>Came whiffling through the tulgey wood,<br>\n>And burbled as it came!<br><br>\n>\n>One, two! One, two! And through and through<br>\n>The vorpal blade went snicker-snack!<br>\n>He left it dead, and with its head<br>\n>He went galumphing back.<br><br>\n>\n>And hast thou slain the <font color='red'>**Jabberwock**</font>?<br>\n>Come to my arms, my beamish boy!<br>\n>O frabjous day! Callooh! Callay!<br>\n>He chortled in his joy.<br><br>\n>\n>Twas brillig, and the slithy toves<br>\n>Did gyre and gimble in the wabe;<br>\n>All mimsy were the borogoves,<br>\n>And the mome raths outgrabe.<br><br>\n\n**L\u00f6sung:**<br>\n*Aufgabe 1*<br>\n- Semantik ~ \"gef\u00e4hrliches, drachen\u00e4hliches Fabelwesen mit Z\u00e4hnen, Klauen und feurigen Augen\"\n*Abb. 1: k\u00fcnstlerische Darstellung des \"Jabberwock\" von [John Tenniel](https://de.wikipedia.org/wiki/John_Tenniel)*<br><br>\n\n*Aufgabe 2*<br>\nDie Bedeutung eines unbekannten Wortes kann \u00fcber den umgebenden Kontext erschlossen werden. Das Wort ***Jabberwock*** taucht vermehrt mit W\u00f6rter auf, die auf Gefahr hindeuten, z.B.:\n  - \"**Beware** the Jabberwock, my son!\\ The **jaws** that **bite**, the **claws** that catch!\"\n  - \"The Jabberwock, with **eyes of flame**,\\ Came **whiffling** through the tulgey wood,\\ And **burbled** as it came!\"\n  - ...<br>\n\nZudem \u00e4hnelt die Handlungsstruktur des Gedicht denen von klassischen Heldensagen, wie z.B. der Nibelungensaga, in denen ein Held loszieht, um einen Drachen zu erschlagen, sodass wir durch Analogiebildung feststellen k\u00f6nnen, dass ein ***Jabberwock*** ein drachen\u00e4hnliches Fabelwesen sein muss. Hierbei kommt allerdings ein deutlich komplexeres Weltwissen zum Tragen, das \u00fcber ein reines \"Wortkontext-Wissen\" hinausgeht und demzufolge auch schwieriger zu modellieren w\u00e4re.\n\n### 1.2. Distributionelle Hypothese\nAusgehend von der oben dargestellten Beobachtung entwickelte Wittgenstein in der (Sprach-)Philosophie folgende Hypothese zur Frage, wie die Semantik eines Wortes definiert werden k\u00f6nne: \n\n> \u201cthe meaning of a word is its use in the language\u201d (Wittgenstein,\n1953)\n\nDiese gebrauchsorientierte Wortsemantikdefinition grenzt sich insbesondere zu logisch-formalen Ans\u00e4tzen ab, welche Wittgenstein als wenig praktikabel zur Darstellung von nat\u00fcrlicher Sprache erachtete (Jurafsky & Martin, 2019). \n\nDieser Grundgedanke wurde in den 1950ern von verschiedenen Linguisten (Joos, 1950; Harris,1954; Firth, 1957) zur sogenannten **Distributionelle Hypothese** (*distributional hypothesis*) 'erweitert':\n\n> \"\\[D\\]efine a word by its **environment or distribution** in language use. A word\u2019s\ndistribution is the set of contexts in which it occurs, the neighboring words or grammatical\nenvironments. The idea is that two words that occur in very similar distributions\n(that occur together with very similar words) are likely to have the same\nmeaning.\" (Jurafsky & Martin, 2019)\n\n## 2. Theoretischer Hintergrund\n\n**Lernziele**\n- Wie kann die Bedeutung zwischen W\u00f6rtern beschrieben werden? \n- Wie kann die Semantik eines Wortes als Vektor dargestellt werden?\n- Was sind Embeddings in diesem Kontext?\n\n### 2.1. lexikalische Semantik\n\nIn der Forschung zur lexikalischen Semantik sind verschiedene Termini gebr\u00e4uchlich, welche die semantischen Eigenschaften von W\u00f6rtern sowie ihre Relationen zueinander im Lexikon zu fassen suchen.\n\n**Aufgabe**\n3. Welche Termini kennen sie zur Beschreibung dieser Eigenschaften und \"Anordnungsrelationen\"? K\u00f6nnen Sie entsprechende Beispiele nennen? (vgl. Jurafsky & Martin, 2019)\n\n\n\n\n\n\n\n\n**L\u00f6sung (Auswahl)**<br>\n*Aufgabe 3*<br>\n- Lemma - Wortform<br>\n  - Mann - M\u00e4nner (Flexion)<br>\n  - Mann - m\u00e4nnlich (Derivation)<br>\n  - Mann - M\u00e4nnerverein (Komposition)<br>\n  - ...<br><br>\n\n- lexikalische Relationen<br>\n  - Synonymie<br>\n  - Polysemie<br>\n  - ...<br><br>\n\n- \u00c4hnlichkeit<br>\n  - vgl. SimLex-999 Datensatz (Hill et al., 2015)<br><br>\n  \n- Verwandschaft / Bezogenheit / Assoziation\n  - z.B.: Kaffee - Becher<br>\n  - semantische Felder / Wortfelder<br>\n    - Topic-Modelle<br>\n      - [Latent Semantic Indexing / Latent Semantic Analyis (LSI/LSA)](lsa.colorado.edu/papers/JASIS.lsi.90.pdf)<br>\n      - [Latent Dirichlet Allocation (LDA)](http://www.jmlr.org/papers/volume3/blei03a/blei03a.pdf)<br>\n      - [Hierarchical Dirichlet Process (HDP)](https://people.eecs.berkeley.edu/~jordan/papers/hdp.pdf)<br>\n      - ...<br>\n    - semantische Frames und Rollen<br>\n      - >\"A semantic frame is a set of words that denote perspectives or participants in a particular type of event.\"<br> (Jurafsky & Martin, 2019)<br><br>\n\n- Affektive Bedeutung / Konnotation<br>\n  - *m\u00f6gliche* Beschreibungsebenen: positiv - negativ - neutral - ...<br>\n    - Onkel Doktor - Halbgott in Wei\u00df - Arzt - ...<br>\n  - Sentiment<br>\n    - Sentiment Analyis<br><br>\n\nEine der fr\u00fchen Arbeiten zur Beschreibung der affektiven Wortbedeutung (Osgood et al., 1957) bildet hierbei die theoretische Grundlage f\u00fcr die Darstellung von W\u00f6rtern als Vektoren.\n\n\n### 2.2. Vektorsemantik\n**Hintergrund**<br>\nOsgood et al. (1957, zitiert nach Jurafsky & Martin, 2019) definieren die affektive Bedeutung eines Wortes nach folgenden **drei** Dimensionen: \n\n> **valence**: the pleasantness of the stimulus<br>\n> **arousal**: the intensity of emotion provoked by the stimulus<br>\n> **dominance**: the degree of control exerted by the stimulus<br>\n\nDie affektive Wortbedeutung von mehreren W\u00f6rtern k\u00f6nnte also tabellarisch wie folgt beschrieben werden:\n\n\n```python\nimport pandas as pd\n# Erzegung einer Tabelle mit den W\u00f6rtern als Index sowie deren Auspr\u00e4gungen \n# f\u00fcr die drei o.g. Dimensionen \"Valence\", \"Arousal\" und \"Dominance\"\ndata_osgood = {\"courageous\":[8.05, 5.5, 7.38],\n               \"music\":[7.67, 5.57, 6.5],\n               \"heartbreak\":[2.45, 5.65, 3.58],\n               \"cub\":[6.71, 3.95, 4.24],\n               \"life\":[6.68, 5.59, 5.89]}\ndf_osgood = pd.DataFrame.from_dict(data_osgood, orient=\"index\", columns =[\"Valence\", \"Arousal\", \"Dominance\"])\ndf_osgood\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Valence</th>\n      <th>Arousal</th>\n      <th>Dominance</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>courageous</th>\n      <td>8.05</td>\n      <td>5.50</td>\n      <td>7.38</td>\n    </tr>\n    <tr>\n      <th>music</th>\n      <td>7.67</td>\n      <td>5.57</td>\n      <td>6.50</td>\n    </tr>\n    <tr>\n      <th>heartbreak</th>\n      <td>2.45</td>\n      <td>5.65</td>\n      <td>3.58</td>\n    </tr>\n    <tr>\n      <th>cub</th>\n      <td>6.71</td>\n      <td>3.95</td>\n      <td>4.24</td>\n    </tr>\n    <tr>\n      <th>life</th>\n      <td>6.68</td>\n      <td>5.59</td>\n      <td>5.89</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nHierbei f\u00e4llt auf, dass man diese Information nicht nur tabellarisch, sondern auch als Datenmatrix *X* der einzelnen Vektoren (*v1* - *v5*) dargestellt werden k\u00f6nnte, sodass die Wortsemantik als Vektor in einem drei-dimensionalen Raum codierbar w\u00e4re.\n\n\n```python\nmatrix_osgood = df_osgood.values\nmatrix_osgood\n```\n\n\n\n\n    array([[8.05, 5.5 , 7.38],\n           [7.67, 5.57, 6.5 ],\n           [2.45, 5.65, 3.58],\n           [6.71, 3.95, 4.24],\n           [6.68, 5.59, 5.89]])\n\n\n\n\n```python\nrows_osgood, cols_osgood = matrix_osgood.shape\nprint(f\"Anzahl Zeilen (n): {rows_osgood}\")\nprint(f\"Anzahl Spalten (m): {cols_osgood}\")\n```\n\n    Anzahl Zeilen (n): 5\n    Anzahl Spalten (m): 3\n\n\n\n```python\n%matplotlib inline\nfrom mpl_toolkits import mplot3d\nimport matplotlib.pyplot as plt\nfig = plt.figure(figsize=(20,14))\nax = fig.gca(projection='3d')\nax.set_xlabel('Valence')\nax.set_ylabel('Arousal')\nax.set_zlabel('Dominance')\nax.scatter3D(matrix_osgood[:,0], matrix_osgood[:,1], matrix_osgood[:,2])\nfor i,v in enumerate(matrix_osgood):\n    ax.text(matrix_osgood[i,0],matrix_osgood[i,1], matrix_osgood[i,2], f\"{df_osgood.index[i]}\")\n\n```\n\nOsgood et al. (1957) stellen hierbei die Semantik eines Wortes auf Grundlage von **vorab definierten Merkmalsdimensionen** (*feature engineering*) dar. Neuere computerlinguistische Ans\u00e4tze \"\u00fcberspringen\" diesen Schritt der expliziten Merkmalskodierung, indem relevante semantische Merkmale automatisch aus unannotierten Text-Korpora gelernt werden k\u00f6nnen. Dies wird als *feature learning / feature extraction* bezeichnet (sp\u00e4ter mehr dazu). Hierbei wird haupts\u00e4chlich der umgebende Kontext eines Wortes ber\u00fccksichtigt, um auf dieser Basis eine Wortsemantik erlernen zu k\u00f6nnen. \n\nIn diesem Sinne vereinen diese Algorithmen folgende zwei Intuition:\n1. W\u00f6rter sind als Punkte/Vektoren in einem mehrdimensionalen Raum darstellbar\n2. die Bedeutung eines Wortes erschlie\u00dft sich durch seinen Kontext (Distributionelle Hypothese)\n\n**Hinweis:** Obwohl ich aktuell von W\u00f6rtern spreche, werden wir bei sp\u00e4teren Verfahren sehen, dass diese nicht nur die Semantik einzelner W\u00f6rter codieren k\u00f6nnen, sondern beliebige Sequenzen als Input nehmen k\u00f6nnen (z.B. Phrasen, S\u00e4tze etc.). \n\n### 2.3. Embeddings\n\nAus den in [2.2.](#2.2.-Vektorsemantik) vorgestellten Zusammenh\u00e4ngen kann nun der Begriff Embedding defininert werden: \n\n**Definition**\n>The idea of vector semantics is thus to represent a word as a point in some multidimensional\n>semantic space. Vectors for representing words are generally called\n>**embeddings**, because the word is embedded in a particular vector space.<br>\n> (Jurafsky & Martin, 2019)\n\nDie einzelnen Algorithmen zur Generierung dieser Embeddings arbeiten im Detail sehr unterschiedlich, gemein ist ihnen allen jedoch, dass sie **immer** den umgebenden Kontext ihres Inputs (W\u00f6rter, S\u00e4tze, Phrasen, Paragraphen, Dokumente etc.) f\u00fcr die Generierung der gew\u00fcnschten 'Ziel-Embeddings' nutzen. Hierf\u00fcr m\u00fcssen die Modelle zun\u00e4chst auf einer ausreichenden Menge an Texten trainiert werden. Anschlie\u00dfend k\u00f6nnen auch neue oder unbekannte Daten durch das Modell in den entsprechenden Vektorraum transformiert/eingebettet werden. Das Resultat dieser Einbettung/Transformation ist eine semantische Repr\u00e4sentation f\u00fcr einen Input, von dem wir kein zuvor **keine** Information \u00fcber dessen Semantik hatten. \n\n**Hinweis:** Der resultierende semantische Raum bzw. die semantische Anordnung der Vektoren in diesem Raum l\u00e4sst sich jedoch aktuell nur relativ schwierig (systematisch) unter die in [2.1.](#2.1.-lexikalische-Semantik) dargestellten Konzepte fassen. Wir k\u00f6nnen zwar bestimmte semantische Ph\u00e4nomene in diesem Vektorraum beobachten (sp\u00e4ter mehr dazu) und durch Embeddings konnte die Performanz von NLP-Systemen f\u00fcr sehr verschiedene Aufgabenstellungen gesteigert werden, allerdings besteht noch ein deutlicher Forschungsbedarf mit Blick auf die Transparenz und Erkl\u00e4rbarkeit dieser Modelle (vgl. Jurafsky & Martin, 2019). \n\nVereinfacht gesagt: Embeddings funktionieren, wir wissen nur nicht genau warum ;)\n\nEmbeddings zu Sprachdaten k\u00f6nnen hierbei grunds\u00e4tzlich auf zwei Arten codiert werden\n1. *sparse* ('d\u00fcnnbesetzt')\n2. *dense* ('dichtbesetzt')\n\nDa die Codierung von Sprachdaten als *sparse vector* das - forschungshistorisch betrachtet - \u00e4ltere Verfahren darstellt, soll zun\u00e4chst diese Datenrepr\u00e4sentation erl\u00e4utert werden.\n\n## 3. Semantik \u00fcber Sparse Vectors\n**Lernziele:**\n- Was ist die BOW-Repr\u00e4senation? Warum ist sie ein Beispiel f\u00fcr einen *sparse vector* bzw. eine *sparse matrix*?\n- Was ist der Unterschied zwischen einer Term-Dokument- und einer Term-Term-Matrix?\n\n\n### 3.1. Bag-of-Words (BOW) / Term-Dokument-Matrix\n\nEine der ersten Ans\u00e4tze zur Repr\u00e4sentation der Bedeutung von unstrukturierten Textdaten kommt aus dem Bereich des **Information Retrieval (IR)**. Die Semantik eines Textes wird in den sogenannten **Bag-of-Words-Modellen (BOW)** als Menge der Vorkommensh\u00e4ufigkeit von **ungeordneten** Termen (~ W\u00f6rter/Tokens) innerhalb jedes Dokuments erfasst. \u00dcber alle Dokumente eines Korpus hinweg kann somit eine Kookkurenz-Matrix aller Terme f\u00fcr alle Dokumente erstellt werden. Diese Matrix bezeichnet man als **Term-Dokument-Matrix oder BOW** . Hierbei gilt:\n\n- Anzahl Spalten = |V| (V=Vokabular)\n- Anzahl Zeilen = |D| (D=Menge der Dokumente)\n\nEin Beispiel f\u00fcr eine Term-Dokument-Matrix findet sich in der n\u00e4chsten Zelle. \n\n\n```python\n# Beispiel f\u00fcr Term-Dokument-Matrix\ndata_shakespeare = {\"battle\":[1, 0, 7, 13],\n                    \"good\":[114, 80, 62, 89],\n                    \"fool\":[36, 58, 1, 4],\n                    \"wit\":[20, 15, 2, 3]}\ndf_shakespeare = pd.DataFrame.from_dict(data_shakespeare, orient=\"index\",\n                                        columns =[\"As You Like It\", \"Twelth Night\", \"Julius Caesar\", \"Henry V\"])\ndf_shakespeare\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>As You Like It</th>\n      <th>Twelth Night</th>\n      <th>Julius Caesar</th>\n      <th>Henry V</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>battle</th>\n      <td>1</td>\n      <td>0</td>\n      <td>7</td>\n      <td>13</td>\n    </tr>\n    <tr>\n      <th>good</th>\n      <td>114</td>\n      <td>80</td>\n      <td>62</td>\n      <td>89</td>\n    </tr>\n    <tr>\n      <th>fool</th>\n      <td>36</td>\n      <td>58</td>\n      <td>1</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>wit</th>\n      <td>20</td>\n      <td>15</td>\n      <td>2</td>\n      <td>3</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nDas o.g. BOW kann wie folgt aus (tokenisierten) Dokumenten erzeugt werden:\n\n>**Vorgehen**\n>1. Bestimme |V|<br>\n>   - Anzahl Spalten der Matrix<br><br>\n>2. Bestimme |D|<br>\n>   - Anzahl Zeilen der Matrix<br><br>\n>3. Bestimme die Termfrequenz jedes Terms in jedem Dokument<br><br>\n>4. Codiere die Termfrequenz pro Dokument f\u00fcr **alle gleichen Terme** immer in derselben Spalte<br>\n>   - *Hinweis: Meist wird chronologisch durch die Dokumente und Terme iteriert, um zu bestimmen, in welcher Dimension welcher Term codiert werden soll. Prinzipiell ist die Dimensionscodierung aber arbitr\u00e4r.*<br>\n\n**Aufgabe**\n4. Erstellen Sie ein BOW f\u00fcr das unten angegebene Korpus *corpus*. Das Korpus liegt tokenisiert vor.\n\n\n\n```python\n# Erstellung eines simplen Spielzeug-Korpus\nfrom pprint import pprint\nfrom nltk.tokenize import RegexpTokenizer\ntokenizer = RegexpTokenizer(r'\\w+')\n\n# Daten von hier:\n# https://radimrehurek.com/gensim/auto_examples/tutorials/run_word2vec.html#sphx-glr-auto-examples-tutorials-run-word2vec-py\nstring_doc1 = \"John likes to watch movies. Mary likes movies too.\"\nstring_doc2 = \"John also likes to watch football games. Mary hates football.\"\n\ndoc1_tokenized = tokenizer.tokenize(string_doc1)\ndoc2_tokenized = tokenizer.tokenize(string_doc2)\n\ncorpus = [doc1_tokenized,doc2_tokenized]\npprint(corpus,width=100)\n```\n\n    [['John', 'likes', 'to', 'watch', 'movies', 'Mary', 'likes', 'movies', 'too'],\n     ['John', 'also', 'likes', 'to', 'watch', 'football', 'games', 'Mary', 'hates', 'football']]\n\n\n\n```python\n\n```\n\n**L\u00f6sung (chronologisch)**<br>\nd1_bow = [1, 2, 1, 1, 2, 1, 1, 0, 0, 0, 0]<br> \nd2_bow = [1, 1, 1, 1, 0, 1, 0, 1, 2, 1, 1]<br> \n\n\n```python\n\n```\n\n\n```python\n# BOW in Gensim\n\n# Erzeugung eines Dictionary, welches f\u00fcr jeden Term die Codierungsdimension speichert\nfrom gensim.corpora import Dictionary\n\ndictionary = Dictionary(corpus)\nprint(dictionary)\n```\n\n    2019-12-12 16:29:53,382 : INFO : adding document #0 to Dictionary(0 unique tokens: [])\n    2019-12-12 16:29:53,383 : INFO : built Dictionary(11 unique tokens: ['John', 'Mary', 'likes', 'movies', 'to']...) from 2 documents (total 19 corpus positions)\n\n\n    Dictionary(11 unique tokens: ['John', 'Mary', 'likes', 'movies', 'to']...)\n\n\n\n```python\n# Hinweis: Die Codierung der Elemente erfolgt hierbei \n# **nicht chronologisch**\npprint({v:k for k,v in dictionary.token2id.items()})\n```\n\n    {0: 'John',\n     1: 'Mary',\n     2: 'likes',\n     3: 'movies',\n     4: 'to',\n     5: 'too',\n     6: 'watch',\n     7: 'also',\n     8: 'football',\n     9: 'games',\n     10: 'hates'}\n\n\n\n```python\n# Das resultierende BOW-Modell ist zudem sparse als Liste von Tupeln gespeichert,\n# d.h. Dimensionen mit 0 vorkommenden Termen werden ausgelassen (aus Performanzgr\u00fcnden)\n# Das erste Element des Tuples korrespondiert mit dem Termindex im Dictionary, wohingegen\n# das zweite Element die absolute Termfrequenz darstellt\nbow_corpus = [dictionary.doc2bow(doc) for doc in corpus]\nbow_corpus\n```\n\n\n\n\n    [[(0, 1), (1, 1), (2, 2), (3, 2), (4, 1), (5, 1), (6, 1)],\n     [(0, 1), (1, 1), (2, 1), (4, 1), (6, 1), (7, 1), (8, 2), (9, 1), (10, 1)]]\n\n\n\n\n```python\n# neue Terme k\u00f6nnen mit dem BOW-Modell nun in den gleichen Vektorraum transformiert werden\n# unbekannte Terme werden dabei ausgelassen\nvec_known = dictionary.doc2bow(\"Mary likes John\".split())\nvec_partially_unknown = dictionary.doc2bow(\"Mary likes soccer\".split())\nvec_unknown = dictionary.doc2bow(\"unknown\".split())\n\nprint(f\"BOW-Vektor (alle Terme in Eingabe bekannt): {vec_known})\")\nprint(f\"BOW-Vektor (teilweise unbekannte Terme in Eingabe): {vec_partially_unknown})\")\nprint(f\"BOW-Vektor (nur unbekannte Terme in Eingabe: {vec_unknown})\")\n```\n\n    BOW-Vektor (alle Terme in Eingabe bekannt): [(0, 1), (1, 1), (2, 1)])\n    BOW-Vektor (teilweise unbekannte Terme in Eingabe): [(1, 1), (2, 1)])\n    BOW-Vektor (nur unbekannte Terme in Eingabe: [])\n\n\n\n```python\n# Zur Visualisierung dieser hochdimensionalen Vektoren k\u00f6nnen diese\n# \u00fcber verschiedene Dimensionalit\u00e4tsreduktionsverfahren (z.B. PCA / t-SNE)\n# auf 2- oder 3-D reduziert werden\nfrom sklearn.manifold import TSNE\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nd1_bow = [1, 2, 1, 1, 2, 1, 1, 0, 0, 0, 0]\nd2_bow = [1, 1, 1, 1, 0, 1, 0, 1, 2, 1, 1]\n\narr1 = np.array(d1_bow).reshape(1,-1)\narr2 = np.array(d2_bow).reshape(1,-1)\n\nX_bow = np.concatenate((arr1,arr2),axis=0)\n\nprint(f\"Term-Dokument-Matrix (chronologisch):\\n{X_bow}\")\nprint()\n\n# Reduzierung der Daten auf 2-D\ntsne = TSNE(n_components=2, random_state=42)\nX_bow_2d = tsne.fit_transform(X_bow)\n\nprint(f\"Term-Dokument-Matrix (2-D):\\n{X_bow_2d}\")\n\n# Plotten der Ergebnisse\nsoa = np.array([[0, 0, X_bow_2d[0][0], X_bow_2d[0][1]], [0, 0, X_bow_2d[1][0], X_bow_2d[1][1]]])\nX, Y, U, V = zip(*soa)\nplt.figure()\nax = plt.gca()\nax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1, color = [\"r\",\"b\"])\nfor i,p in enumerate(X_bow_2d):\n    ax.text(p[0], p[1], f\"d{i+1}\")\n\nax.set_xlim([-2000, 2000])\nax.set_ylim([-2000, 2000])\nplt.draw()\nplt.show()\n```\n\n### 3.2. Term-Term-Matrix / Wort-Wort-Matrix\n\nEine Term-Term-Matrix greift den Grundgedanken hinter den BOW-Modellen zur Semantik-Modellierung auf, indem nicht ein gesamtes Dokument als \"Bedeutungskontext\" festgelegt wird, sondern in dem Trainingskorpus nur gez\u00e4hlt wird, wie oft welche W\u00f6rter in einem bestimmten festgelegten \"Fensterkontext\" vorkommen. Zur Bestimmung dieser Frequenzen wird jeweils ein relativ kleines Fenster (z.B. +/-2 W\u00f6rter) durch das Trainingskorpus \"geschoben\", um den direkt umgebenden Kontext zu bestimmen. Wir werden diesen Ansatz bei word2vec wiedersehen, indem dar\u00fcber Trainingsbeispiele f\u00fcr den zugrundeliegenden Klassifikator aus dem Input-Text generiert werden.\n\n\n*Abb. 2: Illustration des fenster-basierten Ansatzes zur Erzeugung einer Term-Term-Matrix<br>(Quelle: http://mccormickml.com/assets/word2vec/training_data.png)*\n\nF\u00fcr die Dimensionen der Term-Term-Matrix gilt:\n\n- Anzahl Spalten = |V| (V=Vokabular)\n- Anzahl Zeilen = |V| (V=Vokabular)\n\n## 4. Gewichtung von frequenzbasierten Vektoren\n**Lernziele**<br>\n- Was ist TF-IDF? Warum sind reine Termfrequenzen unzureichend zur Semantikdifferenzierung?\n- Was sind Anwendungsbereiche dieses Gewichtungsma\u00dfes?\n\n\n## 4.1. TF-IDF\nObgleich die Frequenz eines Wortes in einem Text sicherlich auch z.T. semantisch motiviert sein kann, lassen sich dar\u00fcber keine R\u00fcckschl\u00fcsse schlie\u00dfen, ob diese Wort auch bedeutsam f\u00fcr die Bedeutungsdifferenzierung zwischen verschiedenen Texten ist. So sind z.B. Funktionsw\u00f6rter zwar hochfrequent, allerdings nicht n\u00fctzlich f\u00fcr die Erfassung einer spezifischen Textsemantik, Hapax Legomena hingegen w\u00e4ren es schon. Diese h\u00e4tten allerdings wieder den Nachteil, dass sie zu spezifisch f\u00fcr einen Einzeltext sind, um \u00fcber mehrere Texte hinweg eine gemeinsame Semantik erfassen zu k\u00f6nnen. Jurafsky und Martin (2019) kommentieren dies treffend mit\n\n>It\u2019s a bit of a paradox. Words that occur nearby frequently (maybe pie nearby\ncherry) are more important than words that only appear once or twice. Yet words\nthat are too frequent\u2014ubiquitous, like the or good\u2014 are unimportant. How can we\nbalance these two conflicting constraints?<br>\n\nZur Gewichtung dieser sehr unterschiedlichen Anforderungen wurde in der IR-Forschung der **TF-IDF-Algorithmus** entwickelt. Ziel des Algorithmus ist eine Gewichtung der reinen Frequenzwerte.\n\nDie zwei Komponenten zur Berechnung dieser TF-IDF-Ma\u00dfe sind\n\n**TF** = Termfrequenz<br>\n**IDF** = Inverse Dokumentfrequenz<br>\n\n\n#### Bestimmung von TF\n\\begin{align}\nt \\widehat{=}\"Term\"\\\\\nd \\widehat{=} \"Dokument\"\\\\\n\\end{align}<br>\n\n- Bestimmung der Vorkommensh\u00e4ufigkeit eines Terms t in Dokument d\n\\begin{align}\ntf_{t,d} = count(t,d)\n\\end{align}<br>\n\n- Alternativ: Log-Skalierung der reinen Termfrequenz\n\\begin{align}\ntf_{t,d} = log_{10}(count(t,d)+1)\n\\end{align}<br>\n\n#### Bestimmung von IDF\n\\begin{align}\ndf_{t} \\widehat{=}\"Dokumentfrequenz\\ eines\\ Terms\\ t\"\\\\\nN \\widehat{=} \"Anzahl\\ der\\ Dokumente\"\\\\\n\\end{align}<br>\n\n- Bestimmung der inversen Dokumentfrequenz\n\\begin{align}\nidf_{t} = log_{10}\\left (\\frac{N}{df_{t}}\\right )\n\\end{align}<br>\n\n#### Bestimmung von TF-IDF\n\\begin{align}\ntfidf_{t,d} = tf_{t,d} \\cdot idf_{t}\n\\end{align}<br>\n\nDurch die Multiplikation der beiden Ma\u00dfe ergibt sich eine gleichm\u00e4\u00dfige Gewichtung der Frequenzinformation pro Dokument sowie \u00fcber alle Dokumente hinweg.\n\n**Hinweis:**<br>\nNeben den hier vorgestellten Gewichtungen existieren eine Reihe von alternativen Formeln zur Bestimmung der einzelnen Formelbestandteile. Formal werden diese h\u00e4ufig in der sog. [SMART-Notation](https://en.wikipedia.org/wiki/SMART_Information_Retrieval_System) angegeben. Diese wird z.B. auch in Gensim sowie in anderen IR-Systemen verwendet.\n\n\n```python\n# TFIDF-Transformationen\nfrom gensim.models import TfidfModel\n\ntfidf=TfidfModel(bow_corpus)\npprint(list(tfidf[bow_corpus]))\n```\n\n    2019-12-12 16:29:55,112 : INFO : collecting document frequencies\n    2019-12-12 16:29:55,113 : INFO : PROGRESS: processing document #0\n    2019-12-12 16:29:55,115 : INFO : calculating IDF weights for 2 documents and 11 features (16 matrix non-zeros)\n\n\n    [[(3, 0.8944271909999159), (5, 0.4472135954999579)],\n     [(7, 0.3779644730092272),\n      (8, 0.7559289460184544),\n      (9, 0.3779644730092272),\n      (10, 0.3779644730092272)]]\n\n\n\n```python\n# Erinnerung: So sah unser Spielzeugkorpus aus\npprint({v:k for k,v in dictionary.token2id.items()})\nprint()\npprint(corpus, width=100)\n```\n\n    {0: 'John',\n     1: 'Mary',\n     2: 'likes',\n     3: 'movies',\n     4: 'to',\n     5: 'too',\n     6: 'watch',\n     7: 'also',\n     8: 'football',\n     9: 'games',\n     10: 'hates'}\n    \n    [['John', 'likes', 'to', 'watch', 'movies', 'Mary', 'likes', 'movies', 'too'],\n     ['John', 'also', 'likes', 'to', 'watch', 'football', 'games', 'Mary', 'hates', 'football']]\n\n\n### 4.2. Pointwise Mutual Information\nEine alternative Gewichtungsfunktion f\u00fcr Term-Term- oder Term-Dokument-Matrizen stellt die **Pointwise Mutual Information (PMI)** dar. Grunds\u00e4tzlich wird hierbei ermittelt, wie oft zwei Ereignisse gemeinsam auftreten in Relation zu ihrem Auftreten, wenn sie unabh\u00e4ngig voneinander w\u00e4ren. Durch Verh\u00e4ltnis dieser beiden Wahrscheinlichkeiten zueinander kann dann bestimmt werden, wie oft zwei W\u00f6rter mehr oder weniger h\u00e4ufig auftreten als wir es zuf\u00e4llig erwarten w\u00fcrden.\n\n\\begin{align}\nw \\widehat{=}\"Zielwort\"\\\\\nc \\widehat{=} \"Kontextwort\"\\\\\nPMI(w,c) = log_{2} \\frac{P(w,c)}{P(w)P(c)}\n\\end{align}\n\n\u00dcblicherweise wird jedoch nur die Positive Pointwise Mutual Information (PPMI) verwendet, da negative PMI-Werte zum einen problematisch hinsichtlich ihrer Interpretierbarkeit sind und zum anderen unzuverl\u00e4ssig bei geringeren Korpusgr\u00f6\u00dfen sind. In der Regeln werden alle negativen PMI-Werte deswegen durch 0 ersetzt.\n\n\\begin{align}\nPPMI(w,c) = max(log_{2} \\frac{P(w,c)}{P(w)P(c)},0)\n\\end{align}\n\n\nDa die PPMI f\u00fcr infrequente Ereignisse generell h\u00f6her ist, wird h\u00e4ufig die Wahrscheinlichkeit des Kontextwortes durch die Anwendung einer \"Erh\u00f6hungsfunktion\" gesteigert. Durch ein Setzen von Alpha = 0.75 wird die Warscheinlichkeit f\u00fcr infrequente Ereignisse etwas gesteigert, indem hochfrequente etwas weniger Wahrscheinlichkeitsmasse erhalten.\n\n\\begin{align}\nP_{\\alpha}(c) = \\frac{ count(c)^\\alpha}{\\sum_c count(c)^\\alpha}\\\\\nPPMI(w,c) = max(log_{2} \\frac{P(w,c)}{P(w)P_{\\alpha}(c)},0)\\\\\n\\end{align}\n\n\nEin Beispiel f\u00fcr PPMI-Scores zwischen verschiedenen Ziel- und Kontextw\u00f6rtern in einem Wikipedia-Dump, findet sich [hier](https://en.wikipedia.org/wiki/Pointwise_mutual_information).\n\n### 4.3. Anwendungsfelder\nTF-IDF-Modelle dienen h\u00e4ufig als **Base-Line zur Bestimmung einer einfachen Semantik** f\u00fcr Dokumente bzw. Sucheingaben (IR-Perspektive) innerhalb eines Vektorraums. Zur Bestimmung der \u00c4hnlichkeit zwischen Vektoren in einem Vektorraum fehlt uns allerdings noch eine sogenannte \u00c4hnlichkeitsmetrik, welche im Folgenden vorgestellt werden soll.\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n## 5. \u00c4hnlichkeitsbestimmung im Vektorraum\n**Lernziele:**\n- Was ist die Kosinus\u00e4hnlichkeit von zwei Vektoren?\n\n###  Kosinus\u00e4hnlichkeit\nDie Kosinus\u00e4hnlichkeit zweier Vektoren *v* und *w* ist definiert als:\n\n\\begin{align}\ncosine(v,w) = {\\mathbf{v} \\cdot \\mathbf{w} \\over |\\mathbf{v}||\\mathbf{w}|} = \\frac{ \\sum\\limits_{i=1}^{N}{v_i  w_i} }{ \\sqrt{\\sum\\limits_{i=1}^{N}{v_i^2}}  \\sqrt{\\sum\\limits_{i=1}^{N}{w_i^2}} }\n\\end{align}\n\nHierbei werden die beiden Vektoren miteinander hinsichlich des Kosinus ihres eingeschlossenen Winkels verglichen. Das Ma\u00df dient also zur Interpretation der Lage von zwei Vektoren zueinander.\n\n\\begin{align}\ncosine(v,w) = 1 \\widehat{=} \"Vektoren\\ haben\\ gleiche\\ Ausrichtung\" \\widehat{=} \"\u00c4hnlichkeit\"\\\\\ncosine(v,w) = 0 \\widehat{=} \"Vektoren\\ stehen\\ orthogonal\\ zueinander\" \\widehat{=} \"keine\\ \u00c4hnlichkeit\"\\\\\ncosine(v,w) = -1 \\widehat{=} \"Vektoren\\ haben\\ entgegengesetzte\\ Ausrichtung\" \\widehat{=} \"Un\u00e4hnlichkeit\"\\\\\n\\end{align}\n\nGraphisch kann dieses Verh\u00e4ltnis folgenderma\u00dfen visualisiert werden:\n\n\n*Abb. 3: Visualisierung der Kosinus-\u00c4hnlichkeit zwischen Vektoren<br>Quelle: http://blog.christianperone.com/2013/09/machine-learning-cosine-similarity-for-vector-space-models-part-iii/*\n\n\u00dcber die \u00c4hnlichkeit von Vektoren zueinander kann anschlie\u00dfend z.B. bestimmt werden, welche Sucheingabe am \u00e4hnlichsten zu welchem Dokument ist.\n\n\n```python\n# Suche nach dem \u00e4hnlichsten Dokument gegeben einen Suchanfrage/Query\n# Hinweis: TF-IDF (transformiertes Korpus als Grundlage)\nfrom gensim.similarities import MatrixSimilarity\n\nindex = MatrixSimilarity(tfidf[bow_corpus])\n\nquery_document1 = 'movies'.split()\nquery_document2 = 'football'.split()\nquery_document3 = 'movies football'.split()\n\nquery_bow1 = dictionary.doc2bow(query_document1)\nquery_bow2 = dictionary.doc2bow(query_document2)\nquery_bow3 = dictionary.doc2bow(query_document3)\n\nsims1 = index[tfidf[query_bow1]]\nsims2 = index[tfidf[query_bow2]]\nsims3 = index[tfidf[query_bow3]]\n\nprint(f\"Query: {query_document1}\\nKosinus-\u00c4hnlichkeit: {list(enumerate(sims1))}\", end=\"\\n\\n\")\nprint(f\"Query: {query_document2}\\nKosinus-\u00c4hnlichkeit: {list(enumerate(sims2))}\", end=\"\\n\\n\")\nprint(f\"Query: {query_document3}\\nKosinus-\u00c4hnlichkeit: {list(enumerate(sims3))}\", end=\"\\n\\n\")\n```\n\n    2019-12-12 16:29:55,173 : WARNING : scanning corpus to determine the number of features (consider setting `num_features` explicitly)\n    2019-12-12 16:29:55,175 : INFO : creating matrix with 2 documents and 11 features\n\n\n    Query: ['movies']\n    Kosinus-\u00c4hnlichkeit: [(0, 0.8944272), (1, 0.0)]\n    \n    Query: ['football']\n    Kosinus-\u00c4hnlichkeit: [(0, 0.0), (1, 0.75592893)]\n    \n    Query: ['movies', 'football']\n    Kosinus-\u00c4hnlichkeit: [(0, 0.6324555), (1, 0.5345225)]\n    \n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n## Semantik \u00fcber Dense Vectors\n**Lernziele:**\n- Was sind Dense Vectors?\n- Welche Algorithmen / Verfahren existieren zur Generierung von Dense Vectors?\n- Was sind Contextualized String Embeddings?\n\n### 6.1. word2vec\nNeben der in [3.](##3.-Semantik-\u00fcber-Sparse-Vectors) und [4.](##4.-Gewichtung-von-frequenzbasierten-Vektoren) dargestellten Codierung von Sprachdaten in einem d\u00fcnnbesetzten Vektorraum existiert eine alternative Codierung in einem dichtbesetzten Vektorraum.\n\nDies hat u.a. folgende Vorteile:\n- bessere Erfassung von Synonymie\n- weniger Features f\u00fcr das Training \n- speichereffizienter\n\nAls **eine** Methode f\u00fcr die Erzeugung von deartigen Vektoren zur Repr\u00e4sentation der Wortsemantik wird das Softwarepaket **word2vec** (Mikolov et al., 2013a/b) vorgestellt, welches folgende Algorithmen umfasst:\n- **Skip-Gram**\n- Continuous Bag of Words (CBOW)\n\n\n*Abb. 4: Vergleich Skip-Gram vs. CBOW-Architektur<br>Quelle: Mikolov et al., 2013a*\n\n\nAus Gr\u00fcnden der Einfachheit wird nicht die Variante des Skip-Gram-Algorithmus mit mehreren Klassen (Softmax Layer) vorgestellt, sondern das **Skip-Gram mit negativem Sampling**, welches das Training dieser Embeddings auf ein bin\u00e4res Klassifikationsproblem runterbricht.\n\n**Methode**\n>1. Treat the target word and a neighboring context word as positive examples.\n>2. Randomly sample other words in the lexicon to get negative samples.\n>3. Use logistic regression to train a classifier to distinguish those two cases.\n>4. Use the regression weights as the embeddings.<br>(Jurafsky & Martin, 2019)\n\n\n\n*Abb. 5: Extraktion von positiven Trainingsbeispielen aus den Trainingsdaten*\n\n\n\n*Abb. 6: Generierung von negativen Trainingsbeispielen aus den Trainingsdaten*\n\nZur Bestimmung des geeigneten St\u00f6rworts (*noise word*) f\u00fcr die negativen Trainingsbeispiele, wird eine gewichtete Unigramm-Frequenz mit dem Faktor Alpha zugrunde gelegt:\n\n\\begin{align}\nP_{\\alpha}(w) = \\frac{count(w)^\\alpha}{\\sum_{w'} count(w)^\\alpha}\n\\end{align}\n\nDie Gewichte werden hierbei f\u00fcr das Training zun\u00e4chst auf zuf\u00e4llige Werte initialisiert. Durch den Trainingsprozess werden diese Gewichte schrittweise f\u00fcr die einzelnen Trainingsbeispiel so angepasst, dass der Klassifikator immer genauer unterscheiden kann, ob ein Kontextwort neben einem Zielwort auftaucht. Diese Gewichte k\u00f6nnen nach dem Training als Embedding genutzt werden, um hochdimensionale Wortvektoren in einen niedriger dimensionierten Raum zu projizieren.\n\n\n*Abb. 7: Nutzung der trainierten Gewichte des Klassifikators zur Einbettung von hochdimensionalen Wortvektoren<br>Quelle: http://mccormickml.com/assets/word2vec/word2vec_weight_matrix_lookup_table.png*\n\nF\u00fcr das Training des Klassifikators m\u00fcssen folgende zwei Optimierungsziele beachtet werden:\n\n>1. **Maximierung** der \u00c4hnlichkeit f\u00fcr das Zielwort- und Kontextwort-Paare (t,c) gezogen aus der Menge der positiven Trainingsbeispiele\n>2. **Minimierung** der \u00c4hnlichkeit von (t,c)-Paaren gezogenen aus der Menge der negativen Trainingsbeispiele \n\nFormal definiert ergibt sich daher f\u00fcr das Lernziel L(Theta) \u00fcber die **gesamten Trainingsdaten** hinweg:\n\n\\begin{align}\nL(\\theta) = \\sum _{(t,c)\\in +}logP(+|t,c) + \\sum _{(t,c)\\in -}logP(-|t,c) \n\\end{align}\n\nF\u00fcr jedes **einzelne Zielwort-Kontextwort-Paar** (t,c) mit Noise-W\u00f6rtern n1..ni ergibt sich somit folgendes Lernziel:\n\\begin{align}\nL(\\theta) = logP(+|t,c) + \\sum ^k_{i=1}logP(-|t,n_{1})\\\\\n\\end{align}\n\nNach erfolgreichem Training liegen zwei separate Embeddings/Gewichtsmatrizen f\u00fcr jedes Wort *w* vor\n1. die Zielembedding *T*\n2. das Kontextembedding *C*\n\n\n*Abb. 8: Visualisierung des Ziel- und Kontextembeddings mit ihren jeweiligen Trainingszielen<br>(entnommen aus Jurafsky & Martin, 2019)*\n\n**Hinweis:**\nMit dem vorgestellten word2vec-Verfahren k\u00f6nnen zwar bekannte W\u00f6rter in einem Korpus relativ schnell in eine entsprechende dichte Repr\u00e4sentation transformiert werden, allerdings k\u00f6nnen unbekannte W\u00f6rter nicht in diesen Vektorraum \u00fcberf\u00fchrt werden.\n\n\n```python\n# Laden des vortrainierten word2vec-Google-News-Korpus\n# Quelle:\n# https://radimrehurek.com/gensim/auto_examples/tutorials/run_word2vec.html#sphx-glr-auto-examples-tutorials-run-word2vec-py\nimport gensim.downloader as api\nword2vec = api.load('word2vec-google-news-300')\n\n```\n\n    2019-12-12 16:29:56,462 : INFO : loading projection weights from C:\\Users\\mvogel/gensim-data\\word2vec-google-news-300\\word2vec-google-news-300.gz\n    2019-12-12 16:34:18,919 : INFO : loaded (3000000, 300) matrix from C:\\Users\\mvogel/gensim-data\\word2vec-google-news-300\\word2vec-google-news-300.gz\n\n\n\n```python\nfrom sklearn.metrics.pairwise import cosine_similarity\n\n# Test: kompositionelle Semantik bzw. Analogieschl\u00fcsse \u00fcber Wortvektoren m\u00f6glich?\nqueen_estimate = word2vec.get_vector(\"king\") - word2vec.get_vector(\"man\") + word2vec.get_vector(\"woman\")\nqueen = word2vec.get_vector(\"queen\")\n\nsim_queen_queen_estimate = cosine_similarity(queen.reshape(1, -1), queen_estimate.reshape(1, -1))[0][0]\n\nprint(f\"Kosinus-\u00c4hnlichkeit zwischen kompositionellem Vektor zu 'queen' und tats\u00e4chlichem Wortvektor 'queen':\\n{sim_queen_queen_estimate}\", end=\"\\n\\n\")\n\nrome_estimate = word2vec.get_vector(\"Paris\") - word2vec.get_vector(\"France\") + word2vec.get_vector(\"Italy\")\nrome = word2vec.get_vector(\"Rome\")\n\nsim_rome_rome_estimate = cosine_similarity(rome.reshape(1, -1), rome_estimate.reshape(1, -1))[0][0]\n\nprint(f\"Kosinus-\u00c4hnlichkeit zwischen kompositionellem Vektor zu 'Rome' und tats\u00e4chlichem Wortvektor 'Rome':\\n{sim_rome_rome_estimate}\")\n\n\n```\n\n    Kosinus-\u00c4hnlichkeit zwischen kompositionellem Vektor zu 'queen' und tats\u00e4chlichem Wortvektor 'queen':\n    0.7300517559051514\n    \n    Kosinus-\u00c4hnlichkeit zwischen kompositionellem Vektor zu 'Rome' und tats\u00e4chlichem Wortvektor 'Rome':\n    0.7073157429695129\n\n\n\n```python\n# Wie \u00e4hnlich sind sich zwei W\u00f6rter?\nw1 = \"peasant\"\nw2 = \"king\"\n\nsim_w1_w2 = cosine_similarity(word2vec.get_vector(w1).reshape(1, -1).reshape(1, -1), word2vec.get_vector(w2).reshape(1, -1))[0][0]\nprint(f\"Kosinus-\u00c4hnlichkeit zwischen '{w1}' und '{w2}':\\n{sim_w1_w2}\")\n \n```\n\n    Kosinus-\u00c4hnlichkeit zwischen 'peasant' und 'king':\n    0.18507906794548035\n\n\n**Hinweis:**<br>\nDie gesamten word2vec-Embeddings von Google News k\u00f6nnen **interaktiv** auf folgenden Seiten durchsucht werden:\n- https://projector.tensorflow.org/\n   - 2/3-D Darstellung der Daten m\u00f6glich, Suche nach den n \u00e4hnlichsten W\u00f6rtern\n- https://rare-technologies.com/word2vec-tutorial/#app\n   - Web-Demo f\u00fcr \u00c4hnlichkeitssuchen (mit \"Analogieschl\u00fcssen\", Filtern von untypischen W\u00f6rtern aus einer Reihe etc.)\n\n### 6.2. weitere Verfahren\n\nFolgendes [Github-Repo](https://github.com/Hironsan/awesome-embedding-models) listet eine Reihe von Algorithmen zur Generierung von Embeddings aus unannotierten Textdaten.\n\nAktuell (Stand: 12/2019) gel\u00e4ufige Verfahren sind hierbei u.a.: \n- FastText\n- Glove\n- ELMo\n- BERT\n\nIm Detail kann auf die einzelnen Embedding-Verfahren nicht eingegangen werden. Neue Verfahren gehen allerdings deutlich \u00fcber rein wort-basierte semantische Repr\u00e4sentationen hinaus, indem z.B. versucht wird, \u00fcber neuronale Lernverfahren eine semantische Repr\u00e4sentation von Sequenzen innerhalb eines Kontexts (bspw. Satz) zu erlernen. Hierbei wird die Information deutlich komplexer modelliert als z.B. bei word2vec. Zudem werden verschiedene Embeddings h\u00e4ufig miteinander kombiniert (*stacking*), um verschiedene Bedeutungsaspekte besser modellieren zu k\u00f6nnen.\n\nUm einen ersten Eindruck f\u00fcr diese Arten von Embeddings zu vermitteln, stelle ich euch ein neues Paper (Akbik et al., 2018) zu \"Contextualized String Embeddings\" vor, welches f\u00fcr eine Reihe von NLP-Downstream-Tasks, bspw. **NER** bis vor knapp 1 Jahr State-of-The-Art-Resulate auf einer Reihe von \u00f6ffentlich zug\u00e4nglichen Evaluationskorpora erzielen konnte ([vgl. Link](https://paperswithcode.com/task/named-entity-recognition-ner))\n\n\n### 6.3. Contextualized String Embeddings\nEine (Python-)Implementation dieser Embeddings, inklusive vortrainierter Sprachmodelle f\u00fcr diverse Sprachen, findet sich unter folgendem [Github-Repo](https://github.com/zalandoresearch/flair). Die von Akbik et al. (2018) vorgeschlagenen Embeddings vereinen hierbei verschiedene Ans\u00e4tze, welche f\u00fcr die Erfassung der Wortsemantik erforscht wurden: \n- 'klassische' Word Embeddings\n- Features auf Character-Ebene\n- Kontextualisierung von Word Embeddings\n\nGrunds\u00e4tzlich werden zun\u00e4chst die Features auf Character-Ebene durch ein bilaterales Long-Short-Term-Memory-Netzwerk (BiLSTM) codiert ([s. hier f\u00fcr eine knappe Einf\u00fchrung zu LSTM](https://towardsdatascience.com/illustrated-guide-to-lstms-and-gru-s-a-step-by-step-explanation-44e9eb85bf21)). Grob gesagt erm\u00f6glichen diese Art von Netzwerk die Speicherung von Information \u00fcber eine beliebige Sequenzl\u00e4nge hinweg \u00fcber sogenannten **Hidden States** und **Cell States**, ohne dass z.B. Information, die zu Beginn einer Sequenz erlernt wurde, sp\u00e4ter vergessen wird, ein Problem, dass bei 'klassischen' Rekurrenten Neuronalen Netzen auftritt. Der Informationsfluss wird dahingehend kontrolliert, dass \u00fcber bestimmte **Gates** kontrolliert wird, welche Information in den Hidden Sates gespeichert wird oder nicht.\n\n*Abb. 9: Schematische Darstellung der Funktionsweise einer LSTM- und GRU-Zelle*\n- *Quelle:*\n  - https://miro.medium.com/max/1516/1*yBXV9o5q7L_CvY7quJt3WQ.png\n\n\nDas trainierte Character-Sprachmodell wird hierbei auf **Satzebene** antrainiert, um mit diesem Modell f\u00fcr jedes Wort in einer Sequenz ein kontextualisiertes Embedding extrahieren zu k\u00f6nnen.\n\n*Abb. 10: Extraktion eines Contextualized String Embeddings f\u00fcr das Wort \"Washington\" auf Basis de<br>(Quelle: Akbik et al., 2018)*\n\nDiese Embeddings k\u00f6nnen anschlie\u00dfend als Basis f\u00fcr einen Down-Stream-NLP-Taks dienen, in diesem Falle **NER** (letzter Layer hier: BiLSTM mit Conditonal Random Field (CRF)).\n\n\n*Abb. 11: \u00dcbersicht der Netzwerkarchitektur f\u00fcr Contextualized String Embeddings f\u00fcr den Down-Stream-Task NER<br>(Quelle: Akbik et al., 2018)*\n\nDie Autoren evaluieren ihre vorgeschlagene Netztwerkarchitektur im Detail sowohl quantitativ...\n\n\n*Abb. 12: Evaluationsergebnisse f\u00fcr Contextualized String Embedddings in verschiedenen Netzwerkkonfigurationen f\u00fcr Sequenzlabeling (letzter Layer: BiLSTM-CRF)<br>(Quelle: Akbik et al., 2018)*\n\n...als auch qualitativ\n\n\n*Abb. 13: qualitative Evaluation der Semantik des Worts \"Washington\" in verschiedenen Satzkontexten<br>(Quelle: Akbik et al., 2018)*\n\n\n\n**Ergebnisse**<br>\n*Hinweis:* Die aktuell besten Trainingskonfigurationen zur Reproduzierbarkeit der Ergebnisse aus dem Paper sind [hier](https://github.com/zalandoresearch/flair/blob/master/resources/docs/EXPERIMENTS.md) dokumentiert.\n- **quantitativ**\n  - f\u00fcr alle getesteten Trainingskonfigurationen haben Contextualized String Embeddings einen positiven Einfluss auf die Perfomanz bei Down-Stream-NLP-Tasks\n  - neue State-of-the-Art-Resultate bei NER\n  - gute Performanz bei syntaktischen Aufgaben (POS-Tagging)\n  - Stacking von 'klassischen' Word Embeddings und Contextualized String Embeddings n\u00fctzlich f\u00fcr Sequence Labeling\n  - Task-spezifische Character Features sind nicht n\u00f6tig<br><br>\n- **qualitativ**\n  - Modell ist in der Lage, polyseme Ausdr\u00fccke, wie z.B. \"Washington\", korrekt \u00fcber den umliegen Kontext zu disambiguieren\n  \n  \n**Diskussion**\n- Contextualized String Embeddings sind ein sinnvolles Instrument zum Erlernen von semantischen Repr\u00e4sentationen auf unannotierten Daten \n- Trainingszeit deutlich geringer als bei wort-basierten Modellen, da #Character < #W\u00f6rter\n- Character-basierte Sprachmodelle sind unabh\u00e4ngig von einer Tokenisierung oder einem fixen Vokabular\n\n\n```python\nfrom flair.models import SequenceTagger\nfrom flair.data import Sentence\n\n# Mini-Demo: NER-Annotation mit vortrainiertem Flair-Modell\n# Quellen:\n# https://github.com/zalandoresearch/flair/blob/master/resources/docs/TUTORIAL_2_TAGGING.md\n# https://github.com/zalandoresearch/flair/blob/master/resources/docs/TUTORIAL_3_WORD_EMBEDDING.md\ntagger = SequenceTagger.load('ner')\n\nsentence = Sentence('George Washington went to Washington .')\n\ntagger.predict(sentence)\n\nprint(f\"Annotierter Satz: {sentence.to_tagged_string()}\")\n```\n\n    2019-12-12 16:34:28,206 : INFO : PyTorch version 1.3.1+cpu available.\n\n\n    2019-12-12 16:34:29,034 loading file C:\\Users\\mvogel\\.flair\\models\\en-ner-conll03-v0.4.pt\n    Annotierter Satz: George <B-PER> Washington <E-PER> went to Washington <S-LOC> .\n\n\n\n```python\n# Stacked Embeddings f\u00fcr diese Netz\nstacked_embeddings = tagger.embeddings\nstacked_embeddings\n```\n\n\n\n\n    StackedEmbeddings(\n      (list_embedding_0): WordEmbeddings('/home/aakbik/.flair/embeddings/glove.gensim')\n      (list_embedding_1): FlairEmbeddings(\n        (lm): LanguageModel(\n          (drop): Dropout(p=0.05, inplace=False)\n          (encoder): Embedding(300, 100)\n          (rnn): LSTM(100, 2048)\n          (decoder): Linear(in_features=2048, out_features=300, bias=True)\n        )\n      )\n      (list_embedding_2): FlairEmbeddings(\n        (lm): LanguageModel(\n          (drop): Dropout(p=0.05, inplace=False)\n          (encoder): Embedding(300, 100)\n          (rnn): LSTM(100, 2048)\n          (decoder): Linear(in_features=2048, out_features=300, bias=True)\n        )\n      )\n    )\n\n\n\n\n```python\nsentence = Sentence('The grass is green .')\n\n# Embedding eines Satzes\nstacked_embeddings.embed(sentence)\n\nfor token in sentence:\n    print(token)\n    print(token.embedding)\n    print(token.embedding.shape)\n    print()\n```\n\n    Token: 1 The\n    tensor([-0.0382, -0.2449,  0.7281,  ...,  0.0080,  0.0566,  0.0259])\n    torch.Size([4196])\n    \n    Token: 2 grass\n    tensor([-0.8135,  0.9404, -0.2405,  ..., -0.0364, -0.0064, -0.3664])\n    torch.Size([4196])\n    \n    Token: 3 is\n    tensor([-0.5426,  0.4148,  1.0322,  ..., -0.0837, -0.1291,  0.0049])\n    torch.Size([4196])\n    \n    Token: 4 green\n    tensor([-0.6791,  0.3491, -0.2398,  ...,  0.0098, -0.0034,  0.0115])\n    torch.Size([4196])\n    \n    Token: 5 .\n    tensor([-0.3398,  0.2094,  0.4635,  ..., -0.0573, -0.0117, -0.0455])\n    torch.Size([4196])\n    \n\n\n## 7. Diskussion\n**Themen**\n- Evaluation von Word Embeddings?\n  - h\u00e4ufig mit externem Task verkn\u00fcpft, z.B. Text Classification, POS-Tagging, NER etc.\n    - Wie viel perfomanter wird ein System im Vergleich zu einem System ohne Embeddings/mit anderen semantischen Rep\u00e4sentationsformen?\n  - daneben aber auch intrinsische Evaluation (auf psycholinguisichen Korpora)\n     - Wie \u00e4hnlich sind sich Word Embeddings und z.B. Merkmalsvektoren?\n- Bias bei Word Embeddings?\n  - Bias in den Daten produziert auch biased Embeddings (?)\n  - Versuch der Korrektur von biased Embeddings (s. Jurafsky & Martin, 2019)\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "6314915caf681e486868b346d997bbf49a10949f", "size": 239614, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "word_embedding_demo.ipynb", "max_stars_repo_name": "theThing92/word_embeddings_demo", "max_stars_repo_head_hexsha": "0785d801803a9667f5760b5ca50dd9e0dba1013f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "word_embedding_demo.ipynb", "max_issues_repo_name": "theThing92/word_embeddings_demo", "max_issues_repo_head_hexsha": "0785d801803a9667f5760b5ca50dd9e0dba1013f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "word_embedding_demo.ipynb", "max_forks_repo_name": "theThing92/word_embeddings_demo", "max_forks_repo_head_hexsha": "0785d801803a9667f5760b5ca50dd9e0dba1013f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 142.6273809524, "max_line_length": 163956, "alphanum_fraction": 0.8679334263, "converted": true, "num_tokens": 14390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23651624720889436, "lm_q2_score": 0.13296423332632276, "lm_q1q2_score": 0.031448201479349666}}
{"text": "# DEMO\n\nThe demo is intended to understand the idea of generating qiskit\n\n## Prerequisites\n\nQiskit is posible installing in 64-bit systems:\n\n    -Ubuntu 16.04 or later\n    -macOS 10.12.6 or later\n    -Windows 7 or later\n    \nYou need to have Python3.5 or higher installed.\n\nThe following command install qiskit.\n\n\n```python\n!pip install qiskit\n```\n\n    Defaulting to user installation because normal site-packages is not writeable\n    Requirement already satisfied: qiskit in /opt/conda/lib/python3.7/site-packages (0.20.0)\n    Requirement already satisfied: qiskit-ibmq-provider==0.8.0 in /opt/conda/lib/python3.7/site-packages (from qiskit) (0.8.0)\n    Requirement already satisfied: qiskit-aer==0.6.1 in /opt/conda/lib/python3.7/site-packages (from qiskit) (0.6.1)\n    Requirement already satisfied: qiskit-ignis==0.4.0 in /opt/conda/lib/python3.7/site-packages (from qiskit) (0.4.0)\n    Requirement already satisfied: qiskit-terra==0.15.1 in /opt/conda/lib/python3.7/site-packages (from qiskit) (0.15.1)\n    Requirement already satisfied: qiskit-aqua==0.7.5 in /opt/conda/lib/python3.7/site-packages (from qiskit) (0.7.5)\n    Requirement already satisfied: requests>=2.19 in /opt/conda/lib/python3.7/site-packages (from qiskit-ibmq-provider==0.8.0->qiskit) (2.24.0)\n    Requirement already satisfied: websockets>=8; python_version > \"3.6\" in /opt/conda/lib/python3.7/site-packages (from qiskit-ibmq-provider==0.8.0->qiskit) (8.1)\n    Requirement already satisfied: nest-asyncio!=1.1.0,>=1.0.0 in /opt/conda/lib/python3.7/site-packages (from qiskit-ibmq-provider==0.8.0->qiskit) (1.4.0)\n    Requirement already satisfied: urllib3>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from qiskit-ibmq-provider==0.8.0->qiskit) (1.25.10)\n    Requirement already satisfied: numpy>=1.13 in /opt/conda/lib/python3.7/site-packages (from qiskit-ibmq-provider==0.8.0->qiskit) (1.19.1)\n    Requirement already satisfied: requests-ntlm>=1.1.0 in /opt/conda/lib/python3.7/site-packages (from qiskit-ibmq-provider==0.8.0->qiskit) (1.1.0)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /opt/conda/lib/python3.7/site-packages (from qiskit-ibmq-provider==0.8.0->qiskit) (2.8.1)\n    Requirement already satisfied: scipy>=1.0; python_version > \"3.5\" in /opt/conda/lib/python3.7/site-packages (from qiskit-aer==0.6.1->qiskit) (1.5.2)\n    Requirement already satisfied: pybind11>=2.4 in /opt/conda/lib/python3.7/site-packages (from qiskit-aer==0.6.1->qiskit) (2.5.0)\n    Requirement already satisfied: cython>=0.27.1 in /opt/conda/lib/python3.7/site-packages (from qiskit-aer==0.6.1->qiskit) (0.29.21)\n    Requirement already satisfied: scikit-learn>=0.17 in /opt/conda/lib/python3.7/site-packages (from qiskit-ignis==0.4.0->qiskit) (0.23.2)\n    Requirement already satisfied: setuptools>=40.1.0 in /opt/conda/lib/python3.7/site-packages (from qiskit-ignis==0.4.0->qiskit) (49.6.0.post20200814)\n    Requirement already satisfied: retworkx>=0.4.0 in /opt/conda/lib/python3.7/site-packages (from qiskit-terra==0.15.1->qiskit) (0.4.0)\n    Requirement already satisfied: fastjsonschema>=2.10 in /opt/conda/lib/python3.7/site-packages (from qiskit-terra==0.15.1->qiskit) (2.14.5)\n    Requirement already satisfied: ply>=3.10 in /opt/conda/lib/python3.7/site-packages (from qiskit-terra==0.15.1->qiskit) (3.11)\n    Requirement already satisfied: sympy>=1.3 in /opt/conda/lib/python3.7/site-packages (from qiskit-terra==0.15.1->qiskit) (1.5.1)\n    Requirement already satisfied: dill>=0.3 in /opt/conda/lib/python3.7/site-packages (from qiskit-terra==0.15.1->qiskit) (0.3.2)\n    Requirement already satisfied: psutil>=5 in /opt/conda/lib/python3.7/site-packages (from qiskit-terra==0.15.1->qiskit) (5.7.2)\n    Requirement already satisfied: networkx>=2.2; python_version > \"3.5\" in /opt/conda/lib/python3.7/site-packages (from qiskit-terra==0.15.1->qiskit) (2.5)\n    Requirement already satisfied: python-constraint>=1.4 in /opt/conda/lib/python3.7/site-packages (from qiskit-terra==0.15.1->qiskit) (1.4.0)\n    Requirement already satisfied: jsonschema>=2.6 in /opt/conda/lib/python3.7/site-packages (from qiskit-terra==0.15.1->qiskit) (3.2.0)\n    Requirement already satisfied: fastdtw in /opt/conda/lib/python3.7/site-packages (from qiskit-aqua==0.7.5->qiskit) (0.3.4)\n    Requirement already satisfied: dlx in /opt/conda/lib/python3.7/site-packages (from qiskit-aqua==0.7.5->qiskit) (1.0.4)\n    Requirement already satisfied: docplex in /opt/conda/lib/python3.7/site-packages (from qiskit-aqua==0.7.5->qiskit) (2.15.194)\n    Requirement already satisfied: h5py in /opt/conda/lib/python3.7/site-packages (from qiskit-aqua==0.7.5->qiskit) (2.10.0)\n    Requirement already satisfied: pandas in /opt/conda/lib/python3.7/site-packages (from qiskit-aqua==0.7.5->qiskit) (1.1.1)\n    Requirement already satisfied: quandl in /opt/conda/lib/python3.7/site-packages (from qiskit-aqua==0.7.5->qiskit) (3.5.2)\n    Requirement already satisfied: yfinance in /opt/conda/lib/python3.7/site-packages (from qiskit-aqua==0.7.5->qiskit) (0.1.54)\n    Requirement already satisfied: idna<3,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19->qiskit-ibmq-provider==0.8.0->qiskit) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19->qiskit-ibmq-provider==0.8.0->qiskit) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19->qiskit-ibmq-provider==0.8.0->qiskit) (2020.6.20)\n    Requirement already satisfied: cryptography>=1.3 in /opt/conda/lib/python3.7/site-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.8.0->qiskit) (3.1)\n    Requirement already satisfied: ntlm-auth>=1.0.2 in /opt/conda/lib/python3.7/site-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.8.0->qiskit) (1.5.0)\n    Requirement already satisfied: six>=1.5 in /opt/conda/lib/python3.7/site-packages (from python-dateutil>=2.8.0->qiskit-ibmq-provider==0.8.0->qiskit) (1.15.0)\n    Requirement already satisfied: joblib>=0.11 in /opt/conda/lib/python3.7/site-packages (from scikit-learn>=0.17->qiskit-ignis==0.4.0->qiskit) (0.16.0)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /opt/conda/lib/python3.7/site-packages (from scikit-learn>=0.17->qiskit-ignis==0.4.0->qiskit) (2.1.0)\n    Requirement already satisfied: mpmath>=0.19 in /opt/conda/lib/python3.7/site-packages (from sympy>=1.3->qiskit-terra==0.15.1->qiskit) (1.1.0)\n    Requirement already satisfied: decorator>=4.3.0 in /opt/conda/lib/python3.7/site-packages (from networkx>=2.2; python_version > \"3.5\"->qiskit-terra==0.15.1->qiskit) (4.4.2)\n    Requirement already satisfied: pyrsistent>=0.14.0 in /opt/conda/lib/python3.7/site-packages (from jsonschema>=2.6->qiskit-terra==0.15.1->qiskit) (0.16.0)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /opt/conda/lib/python3.7/site-packages (from jsonschema>=2.6->qiskit-terra==0.15.1->qiskit) (1.7.0)\n    Requirement already satisfied: attrs>=17.4.0 in /opt/conda/lib/python3.7/site-packages (from jsonschema>=2.6->qiskit-terra==0.15.1->qiskit) (20.1.0)\n    Requirement already satisfied: pytz>=2017.2 in /opt/conda/lib/python3.7/site-packages (from pandas->qiskit-aqua==0.7.5->qiskit) (2020.1)\n    Requirement already satisfied: inflection>=0.3.1 in /opt/conda/lib/python3.7/site-packages (from quandl->qiskit-aqua==0.7.5->qiskit) (0.5.1)\n    Requirement already satisfied: more-itertools in /opt/conda/lib/python3.7/site-packages (from quandl->qiskit-aqua==0.7.5->qiskit) (8.5.0)\n    Requirement already satisfied: multitasking>=0.0.7 in /opt/conda/lib/python3.7/site-packages (from yfinance->qiskit-aqua==0.7.5->qiskit) (0.0.9)\n    Requirement already satisfied: cffi!=1.11.3,>=1.8 in /opt/conda/lib/python3.7/site-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.8.0->qiskit) (1.14.1)\n    Requirement already satisfied: zipp>=0.5 in /opt/conda/lib/python3.7/site-packages (from importlib-metadata; python_version < \"3.8\"->jsonschema>=2.6->qiskit-terra==0.15.1->qiskit) (3.1.0)\n    Requirement already satisfied: pycparser in /opt/conda/lib/python3.7/site-packages (from cffi!=1.11.3,>=1.8->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.8.0->qiskit) (2.20)\n    \u001b[31mERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/home/jovyan/.local/lib/python3.7'\n    Check the permissions.\n    \u001b[0m\n\n\nIn case you need to install in jupyter Notebooks, you need to use the next command\n\n\n```python\n!pip install qiskit[visualization]\n```\n\n    Defaulting to user installation because normal site-packages is not writeable\n    Requirement already satisfied: qiskit[visualization] in /opt/conda/lib/python3.7/site-packages (0.20.0)\n    Requirement already satisfied: qiskit-terra==0.15.1 in /opt/conda/lib/python3.7/site-packages (from qiskit[visualization]) (0.15.1)\n    Requirement already satisfied: qiskit-ignis==0.4.0 in /opt/conda/lib/python3.7/site-packages (from qiskit[visualization]) (0.4.0)\n    Requirement already satisfied: qiskit-aer==0.6.1 in /opt/conda/lib/python3.7/site-packages (from qiskit[visualization]) (0.6.1)\n    Requirement already satisfied: qiskit-aqua==0.7.5 in /opt/conda/lib/python3.7/site-packages (from qiskit[visualization]) (0.7.5)\n    Requirement already satisfied: qiskit-ibmq-provider==0.8.0 in /opt/conda/lib/python3.7/site-packages (from qiskit[visualization]) (0.8.0)\n    Requirement already satisfied: matplotlib>=2.1; extra == \"visualization\" in /opt/conda/lib/python3.7/site-packages (from qiskit[visualization]) (3.3.1)\n    Requirement already satisfied: pylatexenc>=1.4; extra == \"visualization\" in /opt/conda/lib/python3.7/site-packages (from qiskit[visualization]) (2.7)\n    Requirement already satisfied: pygments>=2.4; extra == \"visualization\" in /opt/conda/lib/python3.7/site-packages (from qiskit[visualization]) (2.6.1)\n    Requirement already satisfied: seaborn>=0.9.0; extra == \"visualization\" in /opt/conda/lib/python3.7/site-packages (from qiskit[visualization]) (0.10.1)\n    Requirement already satisfied: ipywidgets>=7.3.0; extra == \"visualization\" in /opt/conda/lib/python3.7/site-packages (from qiskit[visualization]) (7.5.1)\n    Requirement already satisfied: pillow>=4.2.1; extra == \"visualization\" in /opt/conda/lib/python3.7/site-packages (from qiskit[visualization]) (7.2.0)\n    Collecting pydot; extra == \"visualization\"\n      Using cached pydot-1.4.1-py2.py3-none-any.whl (19 kB)\n    Requirement already satisfied: python-constraint>=1.4 in /opt/conda/lib/python3.7/site-packages (from qiskit-terra==0.15.1->qiskit[visualization]) (1.4.0)\n    Requirement already satisfied: scipy>=1.4 in /opt/conda/lib/python3.7/site-packages (from qiskit-terra==0.15.1->qiskit[visualization]) (1.5.2)\n    Requirement already satisfied: fastjsonschema>=2.10 in /opt/conda/lib/python3.7/site-packages (from qiskit-terra==0.15.1->qiskit[visualization]) (2.14.5)\n    Requirement already satisfied: networkx>=2.2; python_version > \"3.5\" in /opt/conda/lib/python3.7/site-packages (from qiskit-terra==0.15.1->qiskit[visualization]) (2.5)\n    Requirement already satisfied: retworkx>=0.4.0 in /opt/conda/lib/python3.7/site-packages (from qiskit-terra==0.15.1->qiskit[visualization]) (0.4.0)\n    Requirement already satisfied: sympy>=1.3 in /opt/conda/lib/python3.7/site-packages (from qiskit-terra==0.15.1->qiskit[visualization]) (1.5.1)\n    Requirement already satisfied: numpy>=1.17 in /opt/conda/lib/python3.7/site-packages (from qiskit-terra==0.15.1->qiskit[visualization]) (1.19.1)\n    Requirement already satisfied: ply>=3.10 in /opt/conda/lib/python3.7/site-packages (from qiskit-terra==0.15.1->qiskit[visualization]) (3.11)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /opt/conda/lib/python3.7/site-packages (from qiskit-terra==0.15.1->qiskit[visualization]) (2.8.1)\n    Requirement already satisfied: psutil>=5 in /opt/conda/lib/python3.7/site-packages (from qiskit-terra==0.15.1->qiskit[visualization]) (5.7.2)\n    Requirement already satisfied: jsonschema>=2.6 in /opt/conda/lib/python3.7/site-packages (from qiskit-terra==0.15.1->qiskit[visualization]) (3.2.0)\n    Requirement already satisfied: dill>=0.3 in /opt/conda/lib/python3.7/site-packages (from qiskit-terra==0.15.1->qiskit[visualization]) (0.3.2)\n    Requirement already satisfied: scikit-learn>=0.17 in /opt/conda/lib/python3.7/site-packages (from qiskit-ignis==0.4.0->qiskit[visualization]) (0.23.2)\n    Requirement already satisfied: setuptools>=40.1.0 in /opt/conda/lib/python3.7/site-packages (from qiskit-ignis==0.4.0->qiskit[visualization]) (49.6.0.post20200814)\n    Requirement already satisfied: pybind11>=2.4 in /opt/conda/lib/python3.7/site-packages (from qiskit-aer==0.6.1->qiskit[visualization]) (2.5.0)\n    Requirement already satisfied: cython>=0.27.1 in /opt/conda/lib/python3.7/site-packages (from qiskit-aer==0.6.1->qiskit[visualization]) (0.29.21)\n    Requirement already satisfied: docplex in /opt/conda/lib/python3.7/site-packages (from qiskit-aqua==0.7.5->qiskit[visualization]) (2.15.194)\n    Requirement already satisfied: fastdtw in /opt/conda/lib/python3.7/site-packages (from qiskit-aqua==0.7.5->qiskit[visualization]) (0.3.4)\n    Requirement already satisfied: dlx in /opt/conda/lib/python3.7/site-packages (from qiskit-aqua==0.7.5->qiskit[visualization]) (1.0.4)\n    Requirement already satisfied: pandas in /opt/conda/lib/python3.7/site-packages (from qiskit-aqua==0.7.5->qiskit[visualization]) (1.1.1)\n    Requirement already satisfied: h5py in /opt/conda/lib/python3.7/site-packages (from qiskit-aqua==0.7.5->qiskit[visualization]) (2.10.0)\n    Requirement already satisfied: quandl in /opt/conda/lib/python3.7/site-packages (from qiskit-aqua==0.7.5->qiskit[visualization]) (3.5.2)\n    Requirement already satisfied: yfinance in /opt/conda/lib/python3.7/site-packages (from qiskit-aqua==0.7.5->qiskit[visualization]) (0.1.54)\n    Requirement already satisfied: requests-ntlm>=1.1.0 in /opt/conda/lib/python3.7/site-packages (from qiskit-ibmq-provider==0.8.0->qiskit[visualization]) (1.1.0)\n    Requirement already satisfied: urllib3>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from qiskit-ibmq-provider==0.8.0->qiskit[visualization]) (1.25.10)\n    Requirement already satisfied: requests>=2.19 in /opt/conda/lib/python3.7/site-packages (from qiskit-ibmq-provider==0.8.0->qiskit[visualization]) (2.24.0)\n    Requirement already satisfied: nest-asyncio!=1.1.0,>=1.0.0 in /opt/conda/lib/python3.7/site-packages (from qiskit-ibmq-provider==0.8.0->qiskit[visualization]) (1.4.0)\n    Requirement already satisfied: websockets>=8; python_version > \"3.6\" in /opt/conda/lib/python3.7/site-packages (from qiskit-ibmq-provider==0.8.0->qiskit[visualization]) (8.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3 in /opt/conda/lib/python3.7/site-packages (from matplotlib>=2.1; extra == \"visualization\"->qiskit[visualization]) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /opt/conda/lib/python3.7/site-packages (from matplotlib>=2.1; extra == \"visualization\"->qiskit[visualization]) (0.10.0)\n    Requirement already satisfied: certifi>=2020.06.20 in /opt/conda/lib/python3.7/site-packages (from matplotlib>=2.1; extra == \"visualization\"->qiskit[visualization]) (2020.6.20)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /opt/conda/lib/python3.7/site-packages (from matplotlib>=2.1; extra == \"visualization\"->qiskit[visualization]) (1.2.0)\n    Requirement already satisfied: ipython>=4.0.0; python_version >= \"3.3\" in /opt/conda/lib/python3.7/site-packages (from ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (7.18.1)\n    Requirement already satisfied: ipykernel>=4.5.1 in /opt/conda/lib/python3.7/site-packages (from ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (5.3.4)\n    Requirement already satisfied: widgetsnbextension~=3.5.0 in /opt/conda/lib/python3.7/site-packages (from ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (3.5.1)\n    Requirement already satisfied: nbformat>=4.2.0 in /opt/conda/lib/python3.7/site-packages (from ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (5.0.7)\n    Requirement already satisfied: traitlets>=4.3.1 in /opt/conda/lib/python3.7/site-packages (from ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (4.3.3)\n    Requirement already satisfied: decorator>=4.3.0 in /opt/conda/lib/python3.7/site-packages (from networkx>=2.2; python_version > \"3.5\"->qiskit-terra==0.15.1->qiskit[visualization]) (4.4.2)\n    Requirement already satisfied: mpmath>=0.19 in /opt/conda/lib/python3.7/site-packages (from sympy>=1.3->qiskit-terra==0.15.1->qiskit[visualization]) (1.1.0)\n    Requirement already satisfied: six>=1.5 in /opt/conda/lib/python3.7/site-packages (from python-dateutil>=2.8.0->qiskit-terra==0.15.1->qiskit[visualization]) (1.15.0)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /opt/conda/lib/python3.7/site-packages (from jsonschema>=2.6->qiskit-terra==0.15.1->qiskit[visualization]) (1.7.0)\n    Requirement already satisfied: pyrsistent>=0.14.0 in /opt/conda/lib/python3.7/site-packages (from jsonschema>=2.6->qiskit-terra==0.15.1->qiskit[visualization]) (0.16.0)\n    Requirement already satisfied: attrs>=17.4.0 in /opt/conda/lib/python3.7/site-packages (from jsonschema>=2.6->qiskit-terra==0.15.1->qiskit[visualization]) (20.1.0)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /opt/conda/lib/python3.7/site-packages (from scikit-learn>=0.17->qiskit-ignis==0.4.0->qiskit[visualization]) (2.1.0)\n    Requirement already satisfied: joblib>=0.11 in /opt/conda/lib/python3.7/site-packages (from scikit-learn>=0.17->qiskit-ignis==0.4.0->qiskit[visualization]) (0.16.0)\n    Requirement already satisfied: pytz>=2017.2 in /opt/conda/lib/python3.7/site-packages (from pandas->qiskit-aqua==0.7.5->qiskit[visualization]) (2020.1)\n    Requirement already satisfied: more-itertools in /opt/conda/lib/python3.7/site-packages (from quandl->qiskit-aqua==0.7.5->qiskit[visualization]) (8.5.0)\n    Requirement already satisfied: inflection>=0.3.1 in /opt/conda/lib/python3.7/site-packages (from quandl->qiskit-aqua==0.7.5->qiskit[visualization]) (0.5.1)\n    Requirement already satisfied: multitasking>=0.0.7 in /opt/conda/lib/python3.7/site-packages (from yfinance->qiskit-aqua==0.7.5->qiskit[visualization]) (0.0.9)\n    Requirement already satisfied: ntlm-auth>=1.0.2 in /opt/conda/lib/python3.7/site-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.8.0->qiskit[visualization]) (1.5.0)\n    Requirement already satisfied: cryptography>=1.3 in /opt/conda/lib/python3.7/site-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.8.0->qiskit[visualization]) (3.1)\n    Requirement already satisfied: idna<3,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19->qiskit-ibmq-provider==0.8.0->qiskit[visualization]) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19->qiskit-ibmq-provider==0.8.0->qiskit[visualization]) (3.0.4)\n    Requirement already satisfied: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in /opt/conda/lib/python3.7/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (3.0.7)\n    Requirement already satisfied: backcall in /opt/conda/lib/python3.7/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.2.0)\n    Requirement already satisfied: pexpect>4.3; sys_platform != \"win32\" in /opt/conda/lib/python3.7/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (4.8.0)\n    Requirement already satisfied: jedi>=0.10 in /opt/conda/lib/python3.7/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.17.2)\n    Requirement already satisfied: pickleshare in /opt/conda/lib/python3.7/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.7.5)\n    Requirement already satisfied: tornado>=4.2 in /opt/conda/lib/python3.7/site-packages (from ipykernel>=4.5.1->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (6.0.4)\n    Requirement already satisfied: jupyter-client in /opt/conda/lib/python3.7/site-packages (from ipykernel>=4.5.1->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (6.1.7)\n    Requirement already satisfied: notebook>=4.4.1 in /opt/conda/lib/python3.7/site-packages (from widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (6.1.3)\n    Requirement already satisfied: jupyter-core in /opt/conda/lib/python3.7/site-packages (from nbformat>=4.2.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (4.6.3)\n    Requirement already satisfied: ipython-genutils in /opt/conda/lib/python3.7/site-packages (from nbformat>=4.2.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.2.0)\n    Requirement already satisfied: zipp>=0.5 in /opt/conda/lib/python3.7/site-packages (from importlib-metadata; python_version < \"3.8\"->jsonschema>=2.6->qiskit-terra==0.15.1->qiskit[visualization]) (3.1.0)\n    Requirement already satisfied: cffi!=1.11.3,>=1.8 in /opt/conda/lib/python3.7/site-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.8.0->qiskit[visualization]) (1.14.1)\n    Requirement already satisfied: wcwidth in /opt/conda/lib/python3.7/site-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.2.5)\n    Requirement already satisfied: ptyprocess>=0.5 in /opt/conda/lib/python3.7/site-packages (from pexpect>4.3; sys_platform != \"win32\"->ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.6.0)\n    Requirement already satisfied: parso<0.8.0,>=0.7.0 in /opt/conda/lib/python3.7/site-packages (from jedi>=0.10->ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.7.0)\n    Requirement already satisfied: pyzmq>=13 in /opt/conda/lib/python3.7/site-packages (from jupyter-client->ipykernel>=4.5.1->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (19.0.2)\n    Requirement already satisfied: argon2-cffi in /opt/conda/lib/python3.7/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (20.1.0)\n    Requirement already satisfied: Send2Trash in /opt/conda/lib/python3.7/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (1.5.0)\n    Requirement already satisfied: terminado>=0.8.3 in /opt/conda/lib/python3.7/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.8.3)\n    Requirement already satisfied: prometheus-client in /opt/conda/lib/python3.7/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.8.0)\n    Requirement already satisfied: nbconvert in /opt/conda/lib/python3.7/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (5.6.1)\n    Requirement already satisfied: jinja2 in /opt/conda/lib/python3.7/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (2.11.2)\n    Requirement already satisfied: pycparser in /opt/conda/lib/python3.7/site-packages (from cffi!=1.11.3,>=1.8->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.8.0->qiskit[visualization]) (2.20)\n    Requirement already satisfied: testpath in /opt/conda/lib/python3.7/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.4.4)\n    Requirement already satisfied: pandocfilters>=1.4.1 in /opt/conda/lib/python3.7/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (1.4.2)\n    Requirement already satisfied: mistune<2,>=0.8.1 in /opt/conda/lib/python3.7/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.8.4)\n    Requirement already satisfied: bleach in /opt/conda/lib/python3.7/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (3.1.5)\n    Requirement already satisfied: defusedxml in /opt/conda/lib/python3.7/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.6.0)\n    Requirement already satisfied: entrypoints>=0.2.2 in /opt/conda/lib/python3.7/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.3)\n    Requirement already satisfied: MarkupSafe>=0.23 in /opt/conda/lib/python3.7/site-packages (from jinja2->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (1.1.1)\n    Requirement already satisfied: packaging in /opt/conda/lib/python3.7/site-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (20.4)\n    Requirement already satisfied: webencodings in /opt/conda/lib/python3.7/site-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.5.1)\n    Installing collected packages: pydot\r\n    \u001b[31mERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/home/jovyan/.local/lib/python3.7'\r\n    Check the permissions.\r\n    \u001b[0m\r\n\n\n\n```python\n!!pip install pylatexenc\n```\n\n\n\n\n    ['Defaulting to user installation because normal site-packages is not writeable',\n     'Requirement already satisfied: pylatexenc in /opt/conda/lib/python3.7/site-packages (2.7)',\n     \"ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/home/jovyan/.local/lib/python3.7'\",\n     'Check the permissions.',\n     '']\n\n\n\n# Introduction\nIn order to validate that it has been installed correctly the module is called, if it does not send an error it means that you already have Qiskit installed\n\n\n```python\nimport qiskit # call  the qiskit's module \n```\n\nQiskit requires three components for the creation of quantum circuits:\n\n    -Qubits or QuantumRegister (the inputs).\n    -Classical bits or ClassicalRegister (number of qubits to be measured from the quantum circuit).\n    -Quantum circuit or QuantumCircuit (the means to apply quantum gates to the qubits).\n    \n   \nThe most basic example is calling a qubit (which conveniently starts at the |0> state) and then measuring it, as shown below.\n\n\n```python\nqr = qiskit.QuantumRegister(1) # call a quantum bit (or qubit)\ncr = qiskit.ClassicalRegister(1) # call a clasical bit\nprogram = qiskit.QuantumCircuit(qr, cr) # The quantum circuit is generated from the previous qubit and bit\n```\n\nThe measurement is made at the end of the quantum circuit indicating in list form the qubits that will correspond to the classic bits\n\n\n```python\nprogram.measure(qr,cr) # The qubit is measured, and the measurement result is stored in the classic bit.\n```\n\n\n\n\n    <qiskit.circuit.instructionset.InstructionSet at 0x7fb53a5f6690>\n\n\n\nQiskit has different ways to visualize the quantum circuit that was designed before.\n\n\n```python\nprogram.draw()\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">      \u250c\u2500\u2510\nq0_0: \u2524M\u251c\n      \u2514\u2565\u2518\nc0: 1/\u2550\u2569\u2550\n       0 </pre>\n\n\n\n\n```python\n%matplotlib inline\nprogram.draw(output=\"mpl\")\n```\n\nThe quantum circuit simulation process is performed by selecting a backend such as \"qasm_simulator\"\n\n\n```python\njob = qiskit.execute( program, qiskit.BasicAer.get_backend('qasm_simulator') )\n```\n\nTo obtain the values of the measurement that was made on the quantum circuit is\n\n\n```python\nprint( job.result().get_counts() )\n```\n\n    {'0': 1024}\n\n\nWhen no modification is made to the qubit, its value will always be the default value which is 0. Another way to identify the output values is from a histogram that displays the total of measurements in the $|0>$ state\n\n\n\n```python\nqiskit.visualization.plot_histogram(job.result().get_counts(program))\n```\n\nQiskit gives the opportunity to use quantum computers remotely. To access them, you need to have an account at https://quantum-computing.ibm.com, where by checking the section \"my account\" you will get a token to use a real quantum computer. If you save the account in your local computer, it will be remembered for future cloud executions of Qiskit code for a variety of real quantum computer backends.\n\n\n```python\nqiskit.IBMQ.save_account('my_token') #Replace the text my_token for your own token\n```\n\n    configrc.store_credentials:WARNING:2020-10-11 23:59:01,669: Credentials already present. Set overwrite=True to overwrite.\n\n\nAfter having the key saved, use the load method and select a computer (the list can be found at the link https://quantum-computing.ibm.com/). For this example, the ibmq16_melbourne (has 15 qubits) is selected. \n\n\n```python\nqiskit.IBMQ.load_account() # load the token\nprovider = qiskit.IBMQ.get_provider('ibm-q') # select the provider\nbackend = provider.get_backend('ibmq_16_melbourne') # select the name of the quatum computer to use\nprint(\"real device:\",backend.name())\njob = qiskit.execute( program, backend )\n```\n\n    /opt/conda/lib/python3.7/site-packages/qiskit/providers/ibmq/ibmqfactory.py:192: UserWarning: Timestamps in IBMQ backend properties, jobs, and job results are all now in local time instead of UTC.\n      warnings.warn('Timestamps in IBMQ backend properties, jobs, and job results '\n\n\n    real device: ibmq_16_melbourne\n\n\n\n```python\nprint( job.result().get_counts() ) # show the result\n```\n\n    {'0': 1016, '1': 8}\n\n\n\n```python\nqiskit.visualization.plot_histogram(job.result().get_counts())\n```\n\n# Single qubit\n\nOne way to define the qubit value is from the Statevector method\n\n\n```python\nfrom qiskit.quantum_info import Statevector\nsv = Statevector.from_label('0') #indicates the state of a qubit\nsv\n```\n\n\n\n\n    Statevector([1.+0.j, 0.+0.j],\n                dims=(2,))\n\n\n\nShow with the method data the state vector is equal to the |0> state\n\n\n```python\nsv.data\n```\n\n\n\n\n    array([1.+0.j, 0.+0.j])\n\n\n\nA visual support is from the method of the qsphere that shows the state of the qubits (in this case, one qubit) on a sphere.\n\n\n```python\nfrom qiskit.visualization import plot_state_qsphere\n\nplot_state_qsphere(sv.data)\n```\n\n## Apply X gate\nThe code below generates a quantum circuit that applies the X gate to the 0th qubit (as qubits in Qiskit are numbered 0, 1, 2,...), and shows the subsequent quantum state in the qsphere. The X gate is also called the NOT gate because in this basis of |0> and |1> (called the computational basis), the X gate flips the bit value of the qubit it is applied to.\n\n\n```python\ncircuit = qiskit.QuantumCircuit(1)\ncircuit.x(0)\ncircuit.draw('mpl')\n```\n\n\n```python\nsv_x = sv.evolve(circuit)\n```\n\n\n```python\nplot_state_qsphere(sv_x.data)\n```\n\n## Apply Hadamard gate\nThe code below generates a quantum circuit that applies the Hadamard (H) gate to the 0th qubit, and shows the subsequent quantum state in the qsphere.\n\n\n```python\ncircuit = qiskit.QuantumCircuit(1)\ncircuit.h(0)\ncircuit.draw('mpl')\n```\n\n\n```python\nsv_h = sv.evolve(circuit)\n```\n\n\n```python\nplot_state_qsphere(sv_h.data)\n```\n\n# Multiple Qubits\n\nFor the case of multiple qubits, we can perform quantum entanglement. Here, we entangle two qubits together by applying the Hadamard gate followed by the Controlled-X (CX) gate. The Controlled-X gate is also called the Controlled-NOT (CNOT) gate.\n\n\n```python\nsv_hcx = Statevector.from_label('00')\nplot_state_qsphere(sv.data)\n```\n\n\n```python\ncircuit = qiskit.QuantumCircuit(2)\ncircuit.h(0)\ncircuit.cx(0,1)\ncircuit.draw('mpl')\n```\n\n\n```python\nsv_entanglement = sv_hcx.evolve(circuit)\nplot_state_qsphere(sv_entanglement.data)\n```\n", "meta": {"hexsha": "84da2e5c9ca4341ebea8284815115fa5bd51975b", "size": 203995, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "assets/quantum_programs/Qiskit_install_intro_devices.ipynb", "max_stars_repo_name": "the-legend-of-lia/Quantum-Universal-Education.github.io", "max_stars_repo_head_hexsha": "3f38e1134d28022bd34d91eaf825c7eb76c27518", "max_stars_repo_licenses": ["ECL-2.0"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2020-08-28T08:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T03:22:44.000Z", "max_issues_repo_path": "assets/quantum_programs/Qiskit_install_intro_devices.ipynb", "max_issues_repo_name": "the-legend-of-lia/Quantum-Universal-Education.github.io", "max_issues_repo_head_hexsha": "3f38e1134d28022bd34d91eaf825c7eb76c27518", "max_issues_repo_licenses": ["ECL-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-16T22:58:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-27T17:23:08.000Z", "max_forks_repo_path": "assets/quantum_programs/Qiskit_install_intro_devices.ipynb", "max_forks_repo_name": "the-legend-of-lia/Quantum-Universal-Education.github.io", "max_forks_repo_head_hexsha": "3f38e1134d28022bd34d91eaf825c7eb76c27518", "max_forks_repo_licenses": ["ECL-2.0"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2020-08-14T21:47:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T23:29:41.000Z", "avg_line_length": 203.995, "max_line_length": 29106, "alphanum_fraction": 0.8722174563, "converted": true, "num_tokens": 10565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3073580295544412, "lm_q2_score": 0.10230469968165562, "lm_q1q2_score": 0.03144417090831254}}
{"text": "# Power Analysis\n\n\n```python\nimport cPickle\nimport datetime\nimport glob\nimport gzip\nimport os\nimport random\nimport re\nimport shutil\nimport subprocess\nimport time\nimport uuid\n\nimport cdpybio as cpb\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\npd.options.mode.chained_assignment = None  # default='warn'\nimport pybedtools as pbt\nimport scipy\nimport scipy.stats as stats\nimport seaborn as sns\nimport statsmodels.api as sm\nimport vcf as pyvcf\n\nimport cardipspy as cpy\nimport ciepy\n\n%matplotlib inline\n%load_ext rpy2.ipython\n\ndy_name = 'power_analysis'\n\nimport socket\nif socket.gethostname() == 'fl-hn1' or socket.gethostname() == 'fl-hn2':\n    dy = os.path.join(ciepy.root, 'sandbox', 'tmp', dy_name)\n    cpy.makedir(dy)\n    pbt.set_tempdir(dy)\n    \noutdir = os.path.join(ciepy.root, 'output', dy_name)\ncpy.makedir(outdir)\n\nprivate_outdir = os.path.join(ciepy.root, 'private_output', dy_name)\ncpy.makedir(private_outdir)\n```\n\n    The rpy2.ipython extension is already loaded. To reload it, use:\n      %reload_ext rpy2.ipython\n\n\n\n```python\nexp = pd.read_table(os.path.join(ciepy.root, 'output', 'eqtl_input', \n                                 'tpm_log_filtered_phe_std_norm_peer_resid.tsv'), index_col=0)\n\nrna_meta = pd.read_table(os.path.join(ciepy.root, 'output', 'input_data', 'rnaseq_metadata.tsv'),\n                         index_col=0)\n\nfn = os.path.join(ciepy.root, 'output/eqtl_processing/eqtls01/qvalues.tsv')\nqvalues = pd.read_table(fn, index_col=0)\n```\n\n\n```python\ndef power_plots(tdf):\n    for i in np.arange(40, 110, 10):\n        df = pd.crosstab(tdf['power_{}_bin'.format(i)], tdf['sig_{}'.format(i)])\n        df['percent'] = df[True] / df.sum(axis=1)\n        plt.figure()\n        df.percent.plot()\n        plt.title(i)\n        plt.ylabel('Observed power')\n        plt.xlabel('Estimated power');\n```\n\nI want to look at power a few different ways. \nI want to take my unrelateds and subsample them like GTEx does to see how many\neGenes I gain as I increase my sample size. I should probably run the full eQTL\nanalysis (with permutations) for the full unrelated set as well.\n\nI'm also going to make an estimate of\nmy power to detect GTEx and Geuvadis eQTLs and compare them to my actual ability\nto detect the eQTLs. For each Geuvadis/GTEx eQTL, I'll calculate an $R^2$. Since \nGeuvadis provides $r$ for each eQTL, I can just square $r$. GTEx provides $\\beta$, \nso I can calculate $R^2$ for a given association as \n\n\\begin{align}\nR^2 = \\left(\\beta \\frac{s_v}{s_g}\\right)^2,\n\\end{align}\n\nwhere $s_v$ is the standard deviation of my genotypes at the position and $s_g$ is the\nstandard deviation of the gene's expression in the GTEx data. I can then calculate\n\n\\begin{align}\nf^2 = \\frac{R^2}{1 - R^2},\n\\end{align}\n\nwhich I can use in a power test for linear regression.\n\nThe power calculation is kind of slow when done so many times so this notebook takes a while to run\nif you need to redo the power calculations.\n\n### Derivation of $R^2$ estimate\n\nFor simple linear regression, we know\n\n\\begin{align}\n\\hat{\\beta} = \\frac{\\textrm{cov}(x,y)}{\\sigma_x^2},\n\\end{align}\n\nand\n\n\\begin{align}\nr = \\frac{\\textrm{cov}(x,y)}{\\sigma_x \\sigma_y}.\n\\end{align}\n\nThus\n\n\\begin{align}\nR^2 &= r^2, \\\\\n&= \\left(\\frac{\\hat{\\beta}\\sigma_x^2}{\\sigma_x \\sigma_y}\\right)^2, \\\\\n&= \\left(\\hat{\\beta}\\frac{\\sigma_x}{\\sigma_y}\\right)^2.\n\\end{align}\n\n## Subsets\n\n\n```python\n[rna_meta.in_eqtl.sum()], [qvalues.perm_sig.sum()]\n```\n\n\n\n\n    ([215], [5816])\n\n\n\n\n```python\ncols = [40, 50, 60, 70, 80, 90, 100]\npvals = {}\nfor i in cols:\n    fn = os.path.join(ciepy.root, 'output', 'eqtl_processing', \n                      'unrelated_eqtls_{}'.format(i), 'min_pvalues_corrected.tsv')\n    pvals[i] = pd.read_table(fn, index_col=0).min_pval_bf\npvals = pd.DataFrame(pvals)\n\n(pvals < 0.05).sum().plot()\nplt.scatter(pvals.columns, (pvals < 0.05).sum().values)\n#plt.scatter([rna_meta.in_eqtl.sum()], [qvalues.perm_sig.sum()])\nplt.xlim(35, 105)\nplt.xlabel('Number of samples')\nplt.ylabel('Number of eGenes');\n```\n\n## pwr\n\nTODO: Below, I calculate the genotype stdev by pulling the genotypes out of the VCF files.\nHowever, I could more easily just read the EMMAX results files and use the `genocnt` column.\nThis would save time for this step and the power step since I could avoid calculating power\nfor some of the GTEx variants I don't have. I also need to make sure to calculate genotype stdev\nfor each set of subjects (40, 50, 60, etc.).\n\n\n```python\ndef pwr_df(df, u, v):\n    \"\"\"\n    Execute pwr.f2.test. The dataframe df must have a column f2.\n    \"\"\"\n    import rpy2.robjects as ro\n    ro.r('suppressPackageStartupMessages(library(pwr))')\n    ro.globalenv['df'] = df\n    ro.globalenv['u'] = u\n    ro.globalenv['v'] = v\n    ro.r('p = rep(1, dim(df)[2])')\n    ro.r('for(i in 1:dim(df)[1]) {'\n         'p[i] = pwr.f2.test(u=u, v=v, f2=df[i, \"f2\"], '\n         'sig.level=0.001, power=NULL)[\"power\"]}')\n    p = ro.globalenv['p']\n    power = [x[0] for x in p]\n    return power\n```\n\n\n```python\ndef pwr(f2, u, v):\n    \"\"\"\n    Execute pwr.f2.test.\n    \"\"\"\n    import rpy2.robjects as ro\n    ro.r('suppressPackageStartupMessages(library(pwr))')\n    ro.globalenv['f2'] = f2\n    ro.globalenv['u'] = u\n    ro.globalenv['v'] = v\n    ro.r('p = pwr.f2.test(u=u, v=v, f2=f2, sig.level=0.001, power=NULL)[\"power\"]')\n    p = list(ro.globalenv['p'])[0][0]\n    return p\n```\ndef calc_stdev(chrom, pos):\n    res = vcf_reader.fetch(chrom, pos, pos)\n    try:\n        r = res.next()\n        out = np.std([0] * r.num_hom_ref + [1] * r.num_het + [2] * r.num_hom_alt)\n    except:\n        out = np.nan\n    return '{}:{}'.format(chrom, int(pos)), out\nHere's an example of using `pwr.f2.test`.\n\n\n```r\n%%R\n\nsuppressPackageStartupMessages(library(pwr))\npwr.f2.test(u=2, v=117, f2=0.060995, sig.level=0.001, power=NULL)\n```\n\n\n    \n         Multiple regression power calculation \n    \n                  u = 2\n                  v = 117\n                 f2 = 0.060995\n          sig.level = 0.001\n              power = 0.1766086\n    \n\n\n\n### Genotype stdev\n\n\n```python\ndef calc_stdev(x):\n    hr, het, ha = [int(x) for x in x.split('/')]\n    out = np.std([0] * hr + [1] * het + [2] * ha)\n    return out\n```\n\n\n```python\nstdev = {}\nfor i in np.arange(40, 110, 10):\n    k = 'geno_stdev_{}'.format(i)\n    out = os.path.join(outdir, '{}.tsv'.format(k))\n    if not os.path.exists(out):\n        fn = os.path.join(ciepy.root, 'output', 'eqtl_processing', \n                          'unrelated_eqtls_{}'.format(i), 'top_snv_results_sorted.tsv.gz')\n        df = pd.read_table(fn, header=None, low_memory=False)\n        se = df[7].apply(lambda x: calc_stdev(x))\n        se.index = 'chr' + df[0].astype(str) + ':' + df[1].astype(str)\n        stdev[k] = se\n        stdev[k].to_csv(out, sep='\\t')\n    else:\n        stdev[k] = pd.read_table(out, index_col=0, header=None, squeeze=True)\n```\n\n\n```python\nfn = os.path.join(outdir, 'genotype_stdevs.tsv')\nif not os.path.exists(fn):\n    ind = []\n    for v in stdev.values():\n        ind += list(v.index)\n    ind = set(ind)\n    for k in stdev:\n        stdev[k] = stdev[k][ind]\n    geno_stdev = pd.DataFrame(stdev)\n    geno_stdev.to_csv(fn, sep='\\t')\nelse:\n    geno_stdev = pd.read_table(fn, index_col=0)\n```\n\n### Geuvadis\nurl = ('ftp://ftp.ebi.ac.uk/pub/databases/microarray/data/experiment/'\n       'GEUV/E-GEUV-1/analysis_results/EUR373.gene.cis.FDR5.all.rs137.txt.gz')\nfn = os.path.join(private_outdir, 'EUR373.gene.cis.FDR5.all.rs137.txt')\nif not os.path.exists(fn):\n    !curl {url} > {fn + '.gz'}\n    !gunzip {fn + '.gz'}\n\ngeuvadis_fn = os.path.join(outdir, 'geuvadis_stdev.tsv')\nif not os.path.exists(geuvadis_fn):\n    geuvadis = pd.read_table(os.path.join(private_outdir, 'EUR373.gene.cis.FDR5.all.rs137.txt'), \n                             low_memory=False)\n    # Remove genes that I didn't test.\n    geuvadis['ens_gene_id'] = geuvadis.GENE_ID.apply(lambda x: x.split('.')[0])\n    tested = pd.DataFrame(True, index=[x.split('.')[0] for x in exp.index], columns=['tested'])\n    geuvadis = geuvadis.merge(tested, left_on='ens_gene_id', right_index=True)\n    # Remove indels.\n    geuvadis = geuvadis[geuvadis.SNPpos - geuvadis.SNPpos.astype(int) == 0]\n    # Add standard deviations\n    geuvadis['chr_pos'] = ('chr' + geuvadis.CHR_SNP.astype(str) + ':' + \n                           geuvadis.SNPpos.astype(int).astype(str))\n    geuvadis = geuvadis.merge(geno_stdev, left_on='chr_pos', right_index=True)\n    # Add R^2 and f^2 values\n    # TODO: I need to calculate R^2 using my genotype stdevs but since they \n    # don't provide beta values I can't do that.\n### GTEx\n\nThe power calculations are pretty slow if we calculate for each individual\nassociation. To speed this up, we'll precalculate the power values for \ndifferent $f2$ values and figure out for which values the power is one.\n\n\n```python\nvals = []\nfor i in np.arange(0, 10, 0.01):\n    vals.append(pwr(i, 2, 37))\nplt.scatter(np.arange(0, 10, 0.01), vals)\nplt.xlabel('$f2$')\nplt.ylabel('Power');\n```\n\nWe can see that even for 40 samples the power goes to one near $f^2 = 1$. This\nwill happen even faster for more samples.\n\n\n```python\nvals = []\nfor i in np.arange(0, 2, 0.001):\n    vals.append(pwr(i, 2, 37))\nplt.scatter(np.arange(0, 2, 0.001), vals)\nplt.xlabel('$f2$')\nplt.ylabel('Power');\n```\n\nI'll go in increments of $0.001$ until I reach power of one.\n\n\n```python\ndef precalculate_power(u, v):\n    i = 0\n    cur_power = 0\n    ind = []\n    vals = []\n    while cur_power < 1.:\n        cur_power = pwr(i, u, v)\n        vals.append(cur_power)\n        i += 0.001\n    pdf = pd.DataFrame(vals, index=np.arange(0, i, 0.001), columns=['power'])\n    return pdf\n```\n\n\n```python\n# Precalculate power values.\npower = {}\nfor i in np.arange(40, 110, 10):\n    power[i] = precalculate_power(2, i - 3)\n    power[i].columns = ['power_{}'.format(i)]\n```\n\n\n```python\ndef get_gene_res(gene, dy, gtex_ind):\n    fn = os.path.join(dy, gene, '{}.tsv'.format(gene))\n    res = ciepy.read_emmax_output(fn)\n    res.index = 'chr' + res.CHROM.astype(str) + ':' + res.BEG.astype(str) + ':' + gene\n    if type(gtex_ind) == str:\n        ind = [gtex_ind]\n    else:\n        ind = gtex_ind.values\n    ind = set(res.index) & set(ind)\n    res = res.ix[ind]\n    return res.PVALUE < 0.001\n```\n\nThe code below takes a while to run. The longest part is reading\nthrough all of my results for the individual genes for each eQTL \nanalysis. This could probably be sped up by running on an IPython\ncluster.\n\n\n```python\nfns = glob.glob('/publicdata/gtex_v6/*.snpgenes')\nout_fns = glob.glob(os.path.join(outdir, 'gtex_*_power.tsv'))\nif len(out_fns) != fns:\n    gtex_results = {}\n    gtex_sig = []\n    for fn in fns:\n        k = os.path.split(fn)[1][:-18]\n        t = pd.read_table(fn, index_col=0, low_memory=False)\n        ref = [x.split('_')[2] for x in t.index]\n        alt = [x.split('_')[2] for x in t.index]\n        t['ref_length'] = [len(x) for x in ref]\n        t['alt_length'] = [len(x) for x in alt]\n        t = t[t.ref_length == 1]\n        t = t[t.alt_length == 1]\n        t['chr_pos'] = ('chr' + t.snp_chrom.astype(str) + ':' + t.snp_pos.astype(str))\n        t = t.merge(geno_stdev, left_on='chr_pos', right_index=True)\n        for i in np.arange(40, 110, 10):\n            t['R2_{}'.format(i)] = (t.beta * t['geno_stdev_{}'.format(i)]) ** 2\n            # We'll round the f2 values so I can use my precalculated power estimates.\n            t['f2_{}'.format(i)] = np.round(t['R2_{}'.format(i)] / (1. - t['R2_{}'.format(i)]), 3)\n            # f2 must be positive. Negative is probably a numeric problem.\n            t = t[t['f2_{}'.format(i)] > 0]\n            cpower = power[i].ix[set(t['f2_{}'.format(i)])].dropna()\n            t = t.merge(cpower, left_on='f2_{}'.format(i), right_index=True, how='outer')\n            t.ix[t['power_{}'.format(i)].isnull(), 'power_{}'.format(i)] = 1\n        tt = 'chr' + t.snp_chrom.astype(str) + ':' + t.snp_pos.astype(str) + ':' + t.gene\n        tt.index = t.gene\n        gtex_sig.append(tt)\n        gtex_results[k] = t\n    gtex_sig = pd.concat(gtex_sig).drop_duplicates()\n    gtex_sig = gtex_sig.ix[set(gtex_sig.index) & set(qvalues.index)]\n    \n    my_gtex_results = pd.DataFrame(index=gtex_sig.values)\n\n#     for i in np.arange(40, 110, 10):\n#         col = 'sig_{}'.format(i)\n#         my_gtex_results[col] = np.nan\n#         dy = os.path.join(ciepy.root, 'private_output', 'run_eqtl_analysis',\n#                           'unrelated_eqtls_{}'.format(i), 'gene_results')\n#         for gene in set(gtex_sig.index):\n#             fn = os.path.join(dy, gene, '{}.tsv'.format(gene))\n#             res = ciepy.read_emmax_output(fn)\n#             res.index = 'chr' + res.CHROM.astype(str) + ':' + res.BEG.astype(str) + ':' + gene\n#             t = gtex_sig.ix[gene]\n#             if type(t) == str:\n#                 ind = [t]\n#             else:\n#                 ind = t.values\n#             ind = set(res.index) & set(ind)\n#             res = res.ix[ind]\n#             my_gtex_results.ix[ind, col] = (res.PVALUE < 0.001).values\n    from ipyparallel import Client\n    parallel_client = Client(profile='parallel')\n    dview = parallel_client[:]\n    print('Cluster has {} engines.'.format(len(parallel_client.ids)))\n    \n\n    with dview.sync_imports():\n        import numpy\n        import ciepy\n        import os\n        import vcf\n\n    %px np = numpy\n\n    dview.push(dict(get_gene_res=get_gene_res))\n    \n    todo = []\n    for g in set(gtex_sig.index):\n        todo.append([g, gtex_sig[g]])\n\n    my_gtex_results = {}\n    for i in np.arange(40, 110, 10):\n        dy = os.path.join(ciepy.root, 'private_output', 'run_eqtl_analysis',\n                          'unrelated_eqtls_{}'.format(i), 'gene_results')\n        dview.push(dict(dy=dy))\n        t = dview.map_sync(lambda x: get_gene_res(x[0], dy, x[1]), todo)\n        tt = pd.concat(t)\n        my_gtex_results['sig_{}'.format(i)] = tt\n    my_gtex_results = pd.DataFrame(my_gtex_results)\n        \n    for k in gtex_results.keys():\n        t = gtex_results[k]\n        t['chr_pos_gene'] = t.chr_pos + ':' + t.gene\n        t = t.merge(my_gtex_results, left_on='chr_pos_gene', right_index=True)\n        for i in np.arange(40, 110, 10):\n            t['power_{}_bin'.format(i)] = pd.cut(t['power_{}'.format(i)], np.arange(0, 1.01, 0.01)).values\n        gtex_results[k] = t\n        out = os.path.join(outdir, 'gtex_{}_power.tsv'.format(k))\n        t.to_csv(out, sep='\\t')\n```\n\n    \n\n\n\n```python\nfig,axs = plt.subplots(len(gtex_results) / 2, 2, figsize=(8, 40))\nfor i,k in enumerate(gtex_results.keys()):\n    ax = axs[i / 2, i % 2]\n    t = gtex_results[k]\n    t = t.sort_values(by='p_value')\n    t = t.drop_duplicates('gene')\n    t.R2_100.hist(bins=np.arange(0, 1.01, 0.01), ax=ax)\n    ax.set_title(k);\n    ax.set_ylabel('Number of eGenes')\n    ax.set_xlabel('$R^2$');\nplt.tight_layout()\n```\n\n\n```python\ndef power_plots(tdf):\n    for i in np.arange(40, 110, 10):\n        df = pd.crosstab(tdf['power_{}_bin'.format(i)], tdf['sig_{}'.format(i)])\n        df['percent'] = df[True] / df.sum(axis=1)\n        plt.figure()\n        df.percent.plot()\n        plt.title(i)\n        plt.ylabel('Observed power')\n        plt.xlabel('Estimated power');\n```\n\n\n```python\nimport statsmodels.api as sm\n```\n\n\n```python\nt = gtex_results['Thyroid']\ni = 40\n```\n\n\n```python\ndf = pd.crosstab(t['power_{}_bin'.format(i)], t['sig_{}'.format(i)])\ndf['percent'] = df[True] / df.sum(axis=1)\n```\n\n\n```python\ndef power_plots(tdf):\n    with sns.plotting_context('notebook', font_scale=1.5):\n        plt.figure(figsize=(8, 8))\n        for n,i in enumerate(np.arange(40, 110, 10)):\n            df = pd.crosstab(tdf['power_{}_bin'.format(i)], tdf['sig_{}'.format(i)])\n            df['percent'] = df[True] / df.sum(axis=1)\n            xs = np.arange(0, 1, 0.01)\n            smoothed = pd.DataFrame(sm.nonparametric.lowess(df.percent, xs), \n                                    columns=['x', i])\n            smoothed.index = smoothed['x']\n\n            smoothed[i].plot(color=cpb.analysis.tableau20[2 * n])\n            plt.title(i)\n            plt.ylabel('Observed power')\n            plt.xlabel('Estimated power')\n        plt.title('')\n        plt.legend(loc='upper left');\n```\n\n\n```python\npower_plots(gtex_results['Liver'])\n```\n\n\n```python\npower_plots(gtex_results['Thyroid'])\n```\n\n\n```python\npower_plots(gtex_results['Lung'])\n```\n\n\n```python\nt = gtex_results['Lung']\n```\n\n\n```python\nt.power_40.hist()\n```\n\n\n```python\nt.power_100.hist()\n```\n\n\n```python\nprop_p100 = []\nfor k in gtex_results.keys():\n    t = gtex_results[k]\n    t = t[t.power_100 == 1]\n    prop_p100.append(t.sig_100.sum() / float(t.shape[0]))\nprop_p100 = pd.Series(prop_p100, index=gtex_results.keys())\nprop_p100.sort_values(inplace=True)\n```\n\n\n```python\nprop_p100.plot(kind='barh')\nplt.xlabel('Proportion of genes with expected power == 1 detected')\nplt.tight_layout()\n```\n\nThis is still affected by sample size since tissues with small \nsample size have few eQTLs with large effect sizes.\n", "meta": {"hexsha": "5575b5bca180ef9e4320b8b76ecee80732a1eea0", "size": 661267, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Power Analysis.ipynb", "max_stars_repo_name": "frazer-lab/cardips-ipsc-eqtl", "max_stars_repo_head_hexsha": "dc97710dfbb5ed96935fa187d90c0d529ce3a216", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2016-07-14T23:09:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-12T20:38:44.000Z", "max_issues_repo_path": "notebooks/Power Analysis.ipynb", "max_issues_repo_name": "frazer-lab/cardips-ipsc-eqtl", "max_issues_repo_head_hexsha": "dc97710dfbb5ed96935fa187d90c0d529ce3a216", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/Power Analysis.ipynb", "max_forks_repo_name": "frazer-lab/cardips-ipsc-eqtl", "max_forks_repo_head_hexsha": "dc97710dfbb5ed96935fa187d90c0d529ce3a216", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-04-11T20:01:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-30T07:41:38.000Z", "avg_line_length": 638.2886100386, "max_line_length": 288130, "alphanum_fraction": 0.9352092271, "converted": true, "num_tokens": 5113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.06278920289730222, "lm_q1q2_score": 0.03139460144865111}}
{"text": "# Knowledge Distillation\n\n\u0412 \u044d\u0442\u043e\u043c \u043d\u043e\u0443\u0442\u0431\u0443\u043a\u0435 \u0441\u043e\u0434\u0435\u0440\u0436\u0438\u0442\u0441\u044f \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u0435 \u043c\u043e\u0438\u0445 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0445 \u044d\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442\u043e\u0432 \u043f\u043e knowledge distillation. \u0417\u0434\u0435\u0441\u044c \u0431\u0443\u0434\u0443\u0442 \u0432 \u043e\u0441\u043d\u043e\u0432\u043d\u043e\u043c \u0433\u0440\u0430\u0444\u0438\u043a\u0438 \u0438 \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u044f \u044d\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442\u043e\u0432, \u0432\u0435\u0441\u044c \u043a\u043e\u0434 \u0434\u043b\u044f \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u044f \u0438 \u043e\u0446\u0435\u043d\u043a\u0438 \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u0430 \u043c\u043e\u0434\u0435\u043b\u0435\u0439 \u0432\u044b\u043d\u0435\u0441\u0435\u043d \u0432 \u043e\u0442\u0434\u0435\u043b\u044c\u043d\u044b\u0435 \u043c\u043e\u0434\u0443\u043b\u0438. \u041f\u0440\u043e\u0449\u0435 \u0432\u0441\u0435\u0433\u043e \u0437\u0430\u043f\u0443\u0441\u0442\u0438\u0442\u044c \u0432 Google Colab, \u0442\u043e\u0433\u0434\u0430 \u043d\u0435 \u043d\u0443\u0436\u043d\u043e \u0434\u043e\u043f\u043e\u043b\u043d\u0438\u0442\u0435\u043b\u044c\u043d\u043e \u0443\u0441\u0442\u0430\u043d\u0430\u0432\u043b\u0438\u0432\u0430\u0442\u044c \u043d\u0438\u043a\u0430\u043a\u0438\u0445 \u0437\u0430\u0432\u0438\u0441\u0438\u043c\u043e\u0441\u0442\u0435\u0439. \u0415\u0441\u043b\u0438 \u0445\u043e\u0442\u0438\u0442\u0435 \u0437\u0430\u043f\u0443\u0441\u0442\u0438\u0442\u044c \u0440\u0435\u0448\u0435\u043d\u0438\u0435 \u043d\u0430 \u0441\u0432\u043e\u0435\u0439 \u043b\u043e\u043a\u0430\u043b\u044c\u043d\u043e\u0439 \u043c\u0430\u0448\u0438\u043d\u0435, \u0442\u043e \u0441\u043b\u0435\u0434\u0443\u0439\u0442\u0435 \u0438\u043d\u0441\u0442\u0440\u0443\u043a\u0446\u0438\u044f\u043c \u0432 README.md.\n\n\u0412\u044b\u043f\u043e\u043b\u043d\u0438\u0442\u0435 \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0435 \u0434\u0432\u0435 \u044f\u0447\u0435\u0439\u043a\u0438, \u0435\u0441\u043b\u0438 \u0440\u0430\u0431\u043e\u0442\u0430\u0435\u0442\u0435 \u0432 Google Colab:\n\n\n```python\n! git clone https://github.com/stdereka/knowledge-distillation.git\n! cp -r knowledge-distillation/dark_knowledge/ .\n! cp -r knowledge-distillation/experiments/ .\n```\n\n    Cloning into 'knowledge-distillation'...\n    remote: Enumerating objects: 257, done.\u001b[K\n    remote: Counting objects: 100% (257/257), done.\u001b[K\n    remote: Compressing objects: 100% (205/205), done.\u001b[K\n    remote: Total 257 (delta 125), reused 156 (delta 46), pack-reused 0\u001b[K\n    Receiving objects: 100% (257/257), 4.12 MiB | 26.20 MiB/s, done.\n    Resolving deltas: 100% (125/125), done.\n\n\n\n```python\nimport sys\nsys.path.insert(1, \"/content/knowledge-distillation\")\n```\n\n## 1. \u041e\u043f\u0438\u0441\u0430\u043d\u0438\u0435 \u0437\u0430\u0434\u0430\u0447\u0438\n\n\u041c\u0435\u0442\u043e\u0434 KD \u0431\u044b\u043b \u0438\u0437\u043d\u0430\u0447\u0430\u043b\u044c\u043d\u043e \u043f\u0440\u0435\u0434\u043b\u043e\u0436\u0435\u043d \u0432 [\u0441\u0442\u0430\u0442\u044c\u0435](https://arxiv.org/pdf/1503.02531.pdf). \u0414\u043b\u044f \u0437\u0430\u0434\u0430\u0447\u0438 \u043c\u043d\u043e\u0433\u043e\u043a\u043b\u0430\u0441\u0441\u043e\u0432\u043e\u0439 \u043a\u043b\u0430\u0441\u0441\u0438\u0444\u0438\u043a\u0430\u0446\u0438\u0438 \u0443\u0442\u0432\u0435\u0440\u0436\u0434\u0430\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0438 \u043a\u043b\u0430\u0441\u0441\u043e\u0432, \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u043d\u044b\u0435 \u043c\u043e\u0434\u0435\u043b\u044c\u044e-\u0443\u0447\u0438\u0442\u0435\u043b\u0435\u043c, \u043c\u043e\u0433\u0443\u0442 \u0431\u044b\u0442\u044c \u0438\u0441\u043f\u043e\u043b\u0437\u043e\u0432\u0430\u043d\u044b \u0434\u043b\u044f \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u044f \u0431\u043e\u043b\u0435\u0435 \u043f\u0440\u043e\u0441\u0442\u043e\u0439 \u043c\u043e\u0434\u0435\u043b\u0438-\u0441\u0442\u0443\u0434\u0435\u043d\u0442\u0430 \u0441 \u043c\u0435\u043d\u044c\u0448\u0438\u043c \u0447\u0438\u0441\u043b\u043e\u043c \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u043e\u0432 \u043f\u0443\u0442\u0451\u043c \u043c\u043e\u0434\u0438\u0444\u0438\u043a\u0430\u0446\u0438\u0438 \u043b\u043e\u0441\u0441\u0430. \u0414\u043b\u044f \u043c\u043d\u043e\u0433\u043e\u043a\u043b\u0430\u0441\u0441\u043e\u0432\u043e\u0439 \u043a\u043b\u0430\u0441\u0441\u0438\u0444\u0438\u043a\u0430\u0446\u0438\u0438 \u043f\u0440\u0435\u0434\u043b\u0430\u0433\u0430\u0435\u0442\u0441\u044f \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0430\u044f \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u043f\u043e\u0442\u0435\u0440\u044c (\u0437\u0434\u0435\u0441\u044c \u0438\u043d\u0434\u0435\u043a\u0441 $i$ \u043f\u0440\u043e\u0431\u0435\u0433\u0430\u0435\u0442 \u043f\u043e \u0432\u0441\u0435\u043c \u043a\u043b\u0430\u0441\u0441\u0430\u043c \u0438 \u043f\u043e \u0432\u0441\u0435\u043c \u043e\u0431\u044a\u0435\u043a\u0442\u0430\u043c):\n\n\\begin{equation}\nE=-T^{2} (1 - \\alpha) \\sum_{i} \\hat{y}_{i}(\\mathbf{x} \\mid T) \\log y_{i}(\\mathbf{x} \\mid T)- \\alpha\\sum_{i} \\bar{y}_{i} \\log y_{i}(\\mathbf{x} \\mid 1)\n\\end{equation}\n\n\u0433\u0434\u0435 $y_{i}(\\mathbf{x} \\mid T)=\\frac{e^{\\frac{z_{i}(\\mathbf{x})}{T}}}{\\sum_{j} e^{\\frac{z_{j}(\\mathrm{x})}{T}}}$ - \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u044f \u043c\u043e\u0434\u0435\u043b\u0438 \u043f\u0440\u0438 \u0442\u0435\u043c\u043f\u0435\u0440\u0430\u0442\u0443\u0440\u0435 $T$ (\u043e\u043d\u0430 \u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044f \u0434\u043b\u044f \u0442\u043e\u0433\u043e, \u0447\u0442\u043e\u0431\u044b \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u044f \u0441\u0438\u043b\u044c\u043d\u0435\u0435 \u043e\u0442\u043b\u0438\u0447\u0430\u043b\u0438\u0441\u044c \u043e\u0442 0 \u0438 1 \u0438 \u043d\u0435\u0441\u043b\u0438 \u0431\u043e\u043b\u044c\u0448\u0435 \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u0438), $\\hat{y}_{i}(\\mathbf{x} \\mid T)$ - \"\u043c\u044f\u0433\u043a\u0438\u0435\" \u043c\u0435\u0442\u043a\u0438 \u0443\u0447\u0438\u0442\u0435\u043b\u044f, $\\bar{y}_{i}$ - \"\u0436\u0451\u0441\u0442\u043a\u0438\u0435\" groundtruth \u043c\u0435\u0442\u043a\u0438. $\\alpha$ - \u0432\u0435\u0441\u043e\u0432\u043e\u0439 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440 \u0434\u043b\u044f \u0440\u0435\u0433\u0443\u043b\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f \u0432\u043a\u043b\u0430\u0434\u0430 \u0436\u0451\u0441\u0442\u043a\u043e\u0439 \u0438 \u043c\u044f\u0433\u043a\u043e\u0439 \u043a\u0440\u043e\u0441\u0441\u044d\u043d\u0442\u0440\u043e\u043f\u0438\u0439 \u0432 \u0433\u0440\u0430\u0434\u0438\u0435\u043d\u0442. \u0410\u0432\u0442\u043e\u0440\u044b \u0441\u0442\u0430\u0442\u044c\u0438 \u043f\u0438\u0448\u0443\u0442, \u0447\u0442\u043e \u0432\u0441\u0451 \u0434\u043e\u043b\u0436\u043d\u043e \u0445\u043e\u0440\u043e\u0448\u043e \u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c \u043f\u0440\u0438 $\\alpha$ \u0431\u043b\u0438\u0437\u043a\u043e\u043c \u043a \u043d\u0443\u043b\u044e.\n\n\n## 2. \u0414\u0430\u0442\u0430\u0441\u0435\u0442 Imagewoof\n\nImagewoof - \u0434\u0430\u0442\u0430\u0441\u0435\u0442 \u0438\u0437 \u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u0439 \u0441\u043e\u0431\u0430\u043a, \u043e\u0442\u043d\u043e\u0441\u044f\u0449\u0438\u043c\u0441\u044f \u043a \u0440\u0430\u0437\u043d\u044b\u043c \u043f\u043e\u0440\u043e\u0434\u0430\u043c. \u041d\u0430 \u043d\u0451\u043c \u043c\u043e\u0436\u043d\u043e \u0440\u0435\u0448\u0430\u0442\u044c \u0437\u0430\u0434\u0430\u0447\u0443 \u043c\u043d\u043e\u0433\u043e\u043a\u043b\u0430\u0441\u0441\u043e\u0432\u043e\u0439 \u043a\u043b\u0430\u0441\u0441\u0438\u0444\u0438\u043a\u0430\u0446\u0438\u0438. \u042f \u0432\u044b\u0431\u0440\u0430\u043b \u0435\u0433\u043e \u0434\u043b\u044f \u044d\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442\u043e\u0432 \u043f\u043e \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u0438\u043c \u043f\u0440\u0438\u0447\u0438\u043d\u0430\u043c. \u0412\u043e-\u043f\u0435\u0440\u0432\u044b\u0445, \u043a\u043b\u0430\u0441\u0441\u044b \u0442\u0440\u0443\u0434\u043d\u043e\u0440\u0430\u0437\u0434\u0435\u043b\u0438\u043c\u044b, \u0441\u043b\u0438\u0448\u043a\u043e\u043c \u043f\u0440\u043e\u0441\u0442\u044b\u0435 \u043c\u043e\u0434\u0435\u043b\u0438 \u043d\u0435 \u0441\u043c\u043e\u0433\u0443\u0442 \u044d\u0444\u0444\u0435\u043a\u0442\u0438\u0432\u043d\u043e \u0440\u0435\u0448\u0438\u0442\u044c \u0437\u0430\u0434\u0430\u0447\u0438, \u043f\u043e\u044d\u0442\u043e\u043c\u0443 \u0435\u0441\u0442\u044c \u0448\u0430\u043d\u0441\u044b \u043f\u0440\u043e\u043d\u0430\u0431\u043b\u044e\u0434\u0430\u0442\u044c \u044d\u0444\u0444\u0435\u043a\u0442\u044b KD \u043d\u0430 \u0431\u043e\u043b\u0435\u0435 \u0441\u043b\u043e\u0436\u043d\u044b\u0445 \u043c\u043e\u0434\u0435\u043b\u044f\u0445. \u0412\u043e-\u0432\u0442\u043e\u0440\u044b\u0445, \u043f\u043e Imagewoof \u043d\u0435 \u0442\u0430\u043a \u043c\u043d\u043e\u0433\u043e \u043f\u0443\u0431\u043b\u0438\u043a\u0430\u0446\u0438\u0439 \u043d\u0430 \u0442\u0435\u043c\u0443 KD, \u044d\u0442\u043e \u0437\u043d\u0430\u0447\u0438\u0442, \u0447\u0442\u043e \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u044b \u044d\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442\u043e\u0432 \u043c\u043d\u0435 \u0437\u0430\u0440\u0430\u043d\u0435\u0435 \u043d\u0435 \u0438\u0437\u0432\u0435\u0441\u0442\u043d\u044b.\n\n\u0421\u043d\u0430\u0447\u0430\u043b\u0430 \u044f \u0445\u043e\u0442\u0435\u043b \u043d\u0430\u0447\u0430\u0442\u044c \u0441 \u0432\u043e\u0441\u043f\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u044f \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u043e\u0432 \u0441\u0442\u0430\u0442\u044c\u0438 \u043d\u0430 \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0435 MNIST, \u043d\u043e \u044d\u0442\u043e \u0443\u0436\u0435 \u0441\u0434\u0435\u043b\u0430\u043b\u0438 \u0437\u0430 \u043c\u0435\u043d\u044f, \u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, [\u0442\u0443\u0442](https://github.com/peterliht/knowledge-distillation-pytorch). \u042f \u0440\u0435\u0448\u0438\u043b \u0441\u0440\u0430\u0437\u0443 \u043d\u0430\u0447\u0430\u0442\u044c \u0441\u043e \u0441\u0432\u043e\u0438\u0445 \u044d\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442\u043e\u0432 \u043d\u0430 \u0431\u043e\u043b\u0435\u0435 \u0441\u043b\u043e\u0436\u043d\u043e\u0439 \u0437\u0430\u0434\u0430\u0447\u0435.\n\n## 3. \u041e\u0431\u0449\u0430\u044f \u0441\u0445\u0435\u043c\u0430 \u044d\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442\u0430\n\n1. **\u0412\u044b\u0431\u0440\u0430\u0442\u044c \u0438 \u043e\u0431\u0443\u0447\u0438\u0442\u044c \u043c\u043e\u0434\u0435\u043b\u044c-\u0443\u0447\u0438\u0442\u0435\u043b\u044c.** \u042d\u0442\u0430 \u043c\u043e\u0434\u0435\u043b\u044c \u0434\u043e\u043b\u0436\u043d\u0430 \u0441\u043e\u0434\u0435\u0440\u0436\u0430\u0442\u044c \u0431\u043e\u043b\u044c\u0448\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u043e\u0432 (\u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e, \u0434\u0430\u0436\u0435 \u0438\u0437\u0431\u044b\u0442\u043e\u0447\u043d\u043e\u0435) \u0438 \u0431\u044b\u0442\u044c \u0441\u0438\u043b\u044c\u043d\u043e \u0440\u0435\u0433\u0443\u043b\u044f\u0440\u0438\u0437\u043e\u0432\u0430\u043d\u0430 (\u0432 \u0437\u0430\u0434\u0430\u0447\u0430\u0445 CV \u043f\u043e\u0434\u043e\u0439\u0434\u0443\u0442 \u0441\u0438\u043b\u044c\u043d\u044b\u0435 \u0434\u0440\u043e\u043f\u0430\u0443\u0442\u044b \u0438 \u0430\u0443\u0433\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0438), \u0430 \u0442\u0430\u043a\u0436\u0435 \u0432\u044b\u0434\u0430\u0432\u0430\u0442\u044c \u043e\u0447\u0435\u043d\u044c \u0445\u043e\u0440\u043e\u0448\u0435\u0435 (\u043f\u043e \u043c\u0435\u0440\u043a\u0430\u043c \u0437\u0430\u0434\u0430\u0447\u0438) \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u043e \u043d\u0430 \u043e\u0442\u043b\u043e\u0436\u0435\u043d\u043d\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0435.\n\n2. **\u041e\u0431\u0443\u0447\u0435\u043d\u0438\u0435 \u0438 \u043e\u0446\u0435\u043d\u043a\u0430 \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u0430 \u043c\u043e\u0434\u0435\u043b\u0438-\u0441\u0442\u0443\u0434\u0435\u043d\u0442\u0430 \u0441 Distillation Loss.** \u041c\u043e\u0434\u0435\u043b\u044c-\u0441\u0442\u0443\u0434\u0435\u043d\u0442 \u0441\u043e\u0434\u0435\u0440\u0436\u0438\u0442 \u043e\u0449\u0443\u0442\u0438\u043c\u043e \u043c\u0435\u043d\u044c\u0448\u0435 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u043e\u0432, \u0447\u0435\u043c \u043c\u043e\u0434\u0435\u043b\u044c-\u0443\u0447\u0438\u0442\u0435\u043b\u044c \u0438 \u043d\u0438\u043a\u0430\u043a \u043d\u0435 \u0440\u0435\u0433\u0443\u043b\u044f\u0440\u0438\u0437\u043e\u0432\u0430\u043d\u0430. \u041d\u0430 \u044d\u0442\u043e\u043c \u044d\u0442\u0430\u043f\u0435 \u043c\u043e\u0436\u043d\u043e \u0438\u0433\u0440\u0430\u0442\u044c \u0441 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u0430\u043c\u0438 $\\alpha$, $T$, \u0440\u0430\u0437\u043c\u0435\u0440\u043e\u043c \u043e\u0431\u0443\u0447\u0430\u044e\u0449\u0435\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0438 \u0438 \u043c\u043d\u043e\u0433\u043e \u0447\u0435\u043c \u0435\u0449\u0451.\n\n3. **\u041e\u0431\u0443\u0447\u0438\u0442\u044c \u043c\u043e\u0434\u0435\u043b\u044c-\u0441\u0442\u0443\u0434\u0435\u043d\u0442\u0430 \u0431\u0435\u0437 \u043f\u043e\u043c\u043e\u0449\u0438 \u0443\u0447\u0438\u0442\u0435\u043b\u044f.** \u0417\u0434\u0435\u0441\u044c \u043e\u0447\u0435\u043d\u044c \u0432\u0430\u0436\u043d\u043e, \u0447\u0442\u043e\u0431\u044b \u043f\u0440\u043e\u0446\u0435\u0441\u0441 \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u044f \u043e\u0442\u043b\u0438\u0447\u0430\u043b\u0441\u044f \u0442\u043e\u043b\u044c\u043a\u043e \u043b\u043e\u0441\u0441\u043e\u043c, \u044d\u0442\u043e \u043f\u043e\u0437\u0432\u043e\u043b\u0438\u0442 \u0438\u0441\u043a\u043b\u044e\u0447\u0438\u0442\u044c \u0432\u043a\u043b\u0430\u0434 \u0432\u0441\u0435\u0445 \u043f\u0440\u043e\u0447\u0438\u0445 \u0444\u0430\u043a\u0442\u043e\u0440\u043e\u0432.\n\n4. **\u0421\u0440\u0430\u0432\u043d\u0438\u0442\u044c \u043c\u0435\u0442\u0440\u0438\u043a\u0438 \u0432 \u043f\u0443\u043d\u043a\u0442\u0430\u0445 2 \u0438 3**, \u043f\u043e\u0441\u0442\u0440\u043e\u0438\u0442\u044c \u0432\u044b\u0432\u043e\u0434\u044b \u043e\u0431 \u044d\u0444\u0444\u0435\u043a\u0442\u0438\u0432\u043d\u043e\u0441\u0442\u0438 KD \u0432 \u0442\u0435\u043a\u0443\u0449\u0435\u043c \u044d\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442\u0435.\n\n\u0418\u0437 \u0431\u0435\u0441\u043f\u043b\u0430\u0442\u043d\u044b\u0445 \u0440\u0435\u0441\u0443\u0440\u0441\u043e\u0432 \u0432 \u043c\u043e\u0451\u043c \u0440\u0430\u0441\u043f\u043e\u0440\u044f\u0436\u0435\u043d\u043d\u0438 \u0442\u043e\u043b\u044c\u043a\u043e Google Colab, \u044d\u0442\u043e \u043e\u0447\u0435\u043d\u044c \u043d\u0435\u0443\u0434\u043e\u0431\u043d\u043e \u0441 \u0442\u043e\u0447\u043a\u0438 \u0437\u0440\u0435\u043d\u0438\u044f \u0440\u0430\u0437\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0438 \u0432\u043e\u0441\u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0438\u043c\u043e\u0441\u0442\u0438 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u043e\u0432, \u043d\u043e \u044f \u0441\u043c\u043e\u0433 \u043d\u0430\u0439\u0442\u0438 \u0432\u044b\u0445\u043e\u0434 \u0438 \u043f\u0440\u0438\u0439\u0442\u0438 \u043a \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0435\u0439 \u0441\u0445\u0435\u043c\u0435. \u041a\u043e\u0434 \u043f\u0438\u0448\u0435\u0442\u0441\u044f \u0438 \u0442\u0435\u0441\u0442\u0438\u0440\u0443\u0435\u0442\u0441\u044f \u043b\u043e\u043a\u0430\u043b\u044c\u043d\u043e \u043d\u0430 \u043c\u043e\u0451\u043c \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u0435. \u041a\u043e\u0433\u0434\u0430 \u0432\u0441\u0451 \u0433\u043e\u0442\u043e\u0432\u043e, \u043d\u043e\u0443\u0442\u0431\u0443\u043a \u0441 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u0430\u043c\u0438 \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u043d\u0430 Google \u0421olab, \u043f\u043e\u0434\u0442\u044f\u0433\u0438\u0432\u0430\u0435\u0442 \u043a\u043e\u0434 \u0441 GitHub \u0438 \u0432\u044b\u043f\u043e\u043b\u043d\u044f\u0435\u0442 \u044d\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442. \u0417\u0430\u0442\u0435\u043c \u043a\u043e\u0434, \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u044b \u0438 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u044b \u0441\u043e\u0445\u0440\u0430\u043d\u044f\u044e\u0442\u0441\u044f \u0432 \u043e\u0434\u043d\u043e\u043c \u043a\u043e\u043c\u043c\u0438\u0442\u0435, \u044d\u0442\u043e \u043f\u043e\u0437\u0432\u043e\u043b\u044f\u0435\u0442 \u043f\u0440\u0438 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e\u0441\u0442\u0438 \u0432\u0435\u0440\u043d\u0443\u0442\u044c\u0441\u044f \u0438 \u0432\u043e\u0441\u043f\u0440\u043e\u0438\u0437\u0432\u0435\u0441\u0442\u0438 \u044d\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442.\n\n## 4. \u0414\u0435\u043c\u043e\u043d\u0441\u0442\u0440\u0430\u0446\u0438\u043e\u043d\u043d\u044b\u0439 \u044d\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442\n\n\u0412 \u044d\u0442\u043e\u0439 \u0447\u0430\u0441\u0442\u0438 \u044f \u043f\u0440\u043e\u0432\u0435\u0434\u0443 \u044d\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442 \u0441\u043e\u0433\u043b\u0430\u0441\u043d\u043e \u043f\u0443\u043d\u043a\u0442\u0443 3.\n\n\n```python\n# Load data\n! wget https://s3.amazonaws.com/fast-ai-imageclas/imagewoof2-320.tgz\n! tar zxf imagewoof2-320.tgz\n# Check GPU\n! nvidia-smi\n```\n\n    --2020-09-23 16:49:23--  https://s3.amazonaws.com/fast-ai-imageclas/imagewoof2-320.tgz\n    Resolving s3.amazonaws.com (s3.amazonaws.com)... 52.216.142.214\n    Connecting to s3.amazonaws.com (s3.amazonaws.com)|52.216.142.214|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 328288506 (313M) [application/x-tar]\n    Saving to: \u2018imagewoof2-320.tgz\u2019\n    \n    imagewoof2-320.tgz  100%[===================>] 313.08M  20.6MB/s    in 12s     \n    \n    2020-09-23 16:49:36 (26.7 MB/s) - \u2018imagewoof2-320.tgz\u2019 saved [328288506/328288506]\n    \n    Wed Sep 23 16:49:39 2020       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 450.66       Driver Version: 418.67       CUDA Version: 10.1     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   44C    P8     9W /  70W |      0MiB / 15079MiB |      0%      Default |\n    |                               |                      |                 ERR! |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    |  No running processes found                                                 |\n    +-----------------------------------------------------------------------------+\n\n\n\n```python\nimport torch\nimport random\nimport numpy as np\nfrom pathlib import Path\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import accuracy_score\nfrom torch.utils.data import DataLoader\nfrom torch import nn\nimport matplotlib.pyplot as plt\nimport os\nfrom training import train, predict, DistillationLoss\nfrom models import *\nfrom datasets import ImageDataset\nfrom itertools import product\n```\n\n\n```python\n\"\"\"\nDefine globals and seed whatever I can seed\n\"\"\"\ndef seed_everything(seed):\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True\n\ntrain_on_gpu = torch.cuda.is_available()\nif not train_on_gpu:\n    print('Training on CPU')\n    DEVICE = torch.device(\"cpu\")\nelse:\n    print('Training on GPU')\n    DEVICE = torch.device(\"cuda\")\n\nSEED = 0\nseed_everything(SEED)\n\nTRAIN_DIR = Path('./imagewoof2-320/train')\nTEST_DIR = Path('./imagewoof2-320/val')\n\ntrain_val_files = sorted(list(TRAIN_DIR.rglob('*.JPEG')))\ntest_files = sorted(list(TEST_DIR.rglob('*.JPEG')))\n\ntrain_val_labels = [path.parent.name for path in train_val_files]\nLABEL_ENCODER = LabelEncoder()\nLABEL_ENCODER.fit(train_val_labels)\n\nN_CLASSES = LABEL_ENCODER.classes_.shape[0]\n```\n\n    Training on GPU\n\n\n\n```python\ndef plot_training_history(history):\n    fig, ax = plt.subplots(1, 2, figsize=(20, 5))\n    ax = ax.flatten()\n\n    ax[0].plot(history[:, 0], label=\"Train\")\n    ax[0].plot(history[:, 2], label=\"Val\")\n    ax[0].set_xlabel(\"Epoch\")\n    ax[0].set_ylabel(\"Loss\")\n    ax[0].legend()\n    ax[0].grid()\n\n    ax[1].plot(history[:, 1], label=\"Train\")\n    ax[1].plot(history[:, 3], label=\"Val\")\n    ax[1].set_xlabel(\"Epoch\")\n    ax[1].set_ylabel(\"Accuracy\")\n    ax[1].legend()\n    ax[1].grid()\n\n    plt.show()\n```\n\n### 4.1. \u0412\u044b\u0431\u043e\u0440 \u0438 \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u0435 \u043c\u043e\u0434\u0435\u043b\u0438-\u0443\u0447\u0438\u0442\u0435\u043b\u044f\n\n\u0423\u0447\u0438\u0442\u0435\u043b\u044c - Resnet101. \u042f \u0434\u043e\u0431\u0430\u0432\u0438\u043b \u0434\u0432\u0430 \u0441\u043a\u0440\u044b\u0442\u044b\u0445 \u043f\u043e\u043b\u043d\u043e\u0441\u0432\u044f\u0437\u043d\u044b\u0445 \u0441\u043b\u043e\u044f \u043f\u043e 2048 \u044e\u043d\u0438\u0442\u043e\u0432. \u0422\u0430\u043a\u0430\u044f \u043c\u043e\u0434\u0435\u043b\u044c \u044f\u0432\u043d\u043e \u0438\u0437\u0431\u044b\u0442\u043e\u0447\u043d\u0430, \u043e\u0447\u0435\u043d\u044c \u0431\u044b\u0441\u0442\u0440\u043e \u043f\u0435\u0440\u0435\u043e\u0431\u0443\u0447\u0430\u0435\u0442\u0441\u044f \u0438 \u0442\u0440\u0435\u0431\u0443\u0435\u0442 \u0430\u0434\u0441\u043a\u0438\u0439 \u0434\u0440\u043e\u043f\u0430\u0443\u0442 ($p=0.95$), \u0447\u0442\u043e\u0431\u044b \u043d\u0435 \u043f\u0435\u0440\u0435\u043e\u0431\u0443\u0447\u0438\u0442\u044c\u0441\u044f \u0438 \u043f\u043e\u043a\u0430\u0437\u0430\u0442\u044c \u0445\u043e\u0440\u043e\u0448\u0438\u0435 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u044b \u043d\u0430 \u0432\u0430\u043b\u0438\u0434\u0430\u0446\u0438\u043e\u043d\u043d\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0435. \u041f\u0440\u0438 \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u0438 \u044d\u0442\u043e\u0439 \u043c\u043e\u0434\u0435\u043b\u0438 \u044f \u0442\u0430\u043a\u0436\u0435 \u0437\u0430\u0434\u0435\u0439\u0441\u0442\u0432\u043e\u0432\u0430\u043b \u0441\u0438\u043b\u044c\u043d\u044b\u0435 \u0430\u0443\u0433\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0438.\n\n\u0414\u043b\u044f \u0434\u0430\u043b\u044c\u043d\u0435\u0439\u0448\u0438\u0445 \u044d\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442\u043e\u0432 (\u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0441 \u0440\u0430\u0437\u043c\u0435\u0440\u043e\u043c \u043e\u0431\u0443\u0447\u0430\u044e\u0449\u0435\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0438 \u0434\u043b\u044f \u043c\u043e\u0434\u0435\u043b\u0438-\u0441\u0442\u0443\u0434\u0435\u043d\u0442\u0430) \u043c\u043e\u0433\u0443\u0442 \u043f\u043e\u043d\u0430\u0434\u043e\u0431\u0438\u0442\u044c\u0441\u044f \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u044f \u0443\u0447\u0438\u0442\u0435\u043b\u044f \u043d\u0430 \u0432\u0441\u0435\u0439 \u043e\u0431\u0443\u0447\u0430\u044e\u0449\u0435\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0435. \u0427\u0442\u043e\u0431\u044b \u043d\u0435 \u0434\u043e\u043f\u0443\u0441\u0442\u0438\u0442\u044c \u0443\u0442\u0435\u0447\u043a\u0438 \u0434\u0430\u043d\u043d\u044b\u0445 \u044f \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u044e 1x4 \u043a\u0440\u043e\u0441\u0441\u0432\u0430\u043b\u0438\u0434\u0430\u0446\u0438\u044e \u0441\u043e \u0441\u0442\u0440\u0430\u0442\u0438\u0444\u0438\u043a\u0430\u0446\u0438\u0435\u0439 \u043f\u043e \u043a\u043b\u0430\u0441\u0441\u0430\u043c, \u0438\u0442\u043e\u0433\u043e\u0432\u044b\u0435 \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u044f - \u044d\u0442\u043e out-of-fold \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u044f \u043c\u043e\u0434\u0435\u043b\u0435\u0439-\u0443\u0447\u0438\u0442\u0435\u043b\u0435\u0439, \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0449\u0438\u0445 \u0440\u0430\u0437\u043d\u044b\u043c \u0444\u043e\u043b\u0434\u0430\u043c. \u0422\u0430\u043a\u0438\u043c \u043e\u0431\u0440\u0430\u0437\u043e\u043c, \u0434\u043b\u044f \u043f\u043e\u043b\u0443\u0447\u0435\u043d\u0438\u044f \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u0439 \u043d\u0430 \u0432\u0441\u0451\u043c \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0435 \u043d\u0443\u0436\u043d\u043e \u043e\u0431\u0443\u0447\u0438\u0442\u044c \u0443\u0447\u0438\u0442\u0435\u043b\u044f \u0446\u0435\u043b\u044b\u0445 4 \u0440\u0430\u0437\u0430, \u0437\u0430\u0442\u043e \u043f\u043e\u0441\u043b\u0435 \u044d\u0442\u043e\u0433\u043e \u043c\u043e\u0436\u043d\u043e \u043d\u0430\u0434\u043e\u043b\u0433\u043e \u043e \u043d\u0451\u043c \u0437\u0430\u0431\u044b\u0442\u044c \u0438 \u0437\u0430\u043d\u044f\u0442\u044c\u0441\u044f \u043d\u0435\u043f\u043e\u0441\u0440\u0435\u0434\u0441\u0442\u0432\u0435\u043d\u043d\u043e KD.\n\n\n```python\nN_SPLITS = 4\n\nseed_everything(SEED)\n\ncv = StratifiedKFold(n_splits=N_SPLITS, shuffle=True, random_state=SEED)\nground = np.array(ImageDataset(train_val_files, LABEL_ENCODER).labels)\n\n# Array for storing OOF logits\noof_logits = np.empty((len(train_val_files), N_CLASSES), float)\n\nlabels = LABEL_ENCODER.transform(train_val_labels)\n\ntest_dataset = ImageDataset(test_files, LABEL_ENCODER)\ntest_loader = DataLoader(test_dataset, shuffle=False, batch_size=64)\n\n# Array for storing test dataset logits\ntest_logits = np.zeros((len(test_dataset), N_CLASSES), float)\n\nfor fold, (train_idx, val_idx) in enumerate(cv.split(train_val_files, labels)):\n    print('Training on fold', fold + 1)\n\n    val_dataset = ImageDataset(np.array(train_val_files)[val_idx], LABEL_ENCODER)\n    train_dataset = ImageDataset(np.array(train_val_files)[train_idx], LABEL_ENCODER, augs=True)\n    \n    model = resnet101_teacher(N_CLASSES, DEVICE)\n    opt = torch.optim.Adam(model.parameters(), lr=0.0003)\n    criterion = nn.CrossEntropyLoss()\n    history = train(train_dataset, val_dataset, model=model, epochs=20,\n                              batch_size=64, device=DEVICE, opt=opt, criterion=criterion)\n    \n    val_loader = DataLoader(val_dataset, shuffle=False, batch_size=64)\n    labels_val = ground[val_idx]\n    \n    logits_val = predict(model, val_loader, DEVICE, logit=True)\n    oof_logits[val_idx] = logits_val\n    preds_val = np.argmax(logits_val, axis=1)\n    \n    # Prediction on test set is an average of N_SPLITS models\n    test_logits += predict(model, test_loader, DEVICE, logit=True)/N_SPLITS\n    \n    print(f'Fold {fold + 1} accuracy score:', accuracy_score(labels_val, preds_val))\n\noof_preds = np.argmax(oof_logits, axis=1)\nprint('OOF accuracy score:', accuracy_score(ground, oof_preds))\n\n# Save results\nos.makedirs(\"./dark_knowledge\", exist_ok=True)\nnp.save(\"./dark_knowledge/resnet101_train_imagewoof.npy\", oof_logits)\nnp.save(\"./dark_knowledge/resnet101_test_imagewoof.npy\", test_logits)\n```\n\n    Training on fold 1\n\n\n    Downloading: \"https://download.pytorch.org/models/resnet101-5d3b4d8f.pth\" to /root/.cache/torch/hub/checkpoints/resnet101-5d3b4d8f.pth\n\n\n    Epoch: 1, train_loss: 2.7788, val_loss: 2.2557, train_acc: 0.1169, val_acc: 0.4945\n    Epoch: 2, train_loss: 1.4853, val_loss: 0.3969, train_acc: 0.8097, val_acc: 0.9278\n    Epoch: 3, train_loss: 0.3147, val_loss: 0.1817, train_acc: 0.9170, val_acc: 0.9508\n    Epoch: 4, train_loss: 0.2246, val_loss: 0.1467, train_acc: 0.9279, val_acc: 0.9526\n    Epoch: 5, train_loss: 0.2063, val_loss: 0.1502, train_acc: 0.9334, val_acc: 0.9504\n    Epoch: 6, train_loss: 0.1927, val_loss: 0.1605, train_acc: 0.9362, val_acc: 0.9504\n    Epoch: 7, train_loss: 0.1982, val_loss: 0.1504, train_acc: 0.9341, val_acc: 0.9499\n    Epoch: 8, train_loss: 0.1852, val_loss: 0.1447, train_acc: 0.9387, val_acc: 0.9521\n    Epoch: 9, train_loss: 0.1910, val_loss: 0.1451, train_acc: 0.9400, val_acc: 0.9539\n    Epoch: 10, train_loss: 0.1836, val_loss: 0.1380, train_acc: 0.9387, val_acc: 0.9544\n    Epoch: 11, train_loss: 0.1727, val_loss: 0.1329, train_acc: 0.9402, val_acc: 0.9601\n    Epoch: 12, train_loss: 0.1752, val_loss: 0.1386, train_acc: 0.9430, val_acc: 0.9530\n    Epoch: 13, train_loss: 0.1765, val_loss: 0.1256, train_acc: 0.9406, val_acc: 0.9601\n    Epoch: 14, train_loss: 0.1666, val_loss: 0.1510, train_acc: 0.9464, val_acc: 0.9477\n    Epoch: 15, train_loss: 0.1795, val_loss: 0.1458, train_acc: 0.9382, val_acc: 0.9517\n    Epoch: 16, train_loss: 0.1622, val_loss: 0.1456, train_acc: 0.9431, val_acc: 0.9495\n    Epoch: 17, train_loss: 0.1627, val_loss: 0.1430, train_acc: 0.9437, val_acc: 0.9513\n    Epoch: 18, train_loss: 0.1541, val_loss: 0.1360, train_acc: 0.9468, val_acc: 0.9553\n    Epoch: 19, train_loss: 0.1705, val_loss: 0.1337, train_acc: 0.9413, val_acc: 0.9521\n    Epoch: 20, train_loss: 0.1613, val_loss: 0.1361, train_acc: 0.9439, val_acc: 0.9539\n    Fold 1 accuracy score: 0.9539211342490032\n    Training on fold 2\n    Epoch: 1, train_loss: 2.8263, val_loss: 2.2559, train_acc: 0.1129, val_acc: 0.5421\n    Epoch: 2, train_loss: 1.5103, val_loss: 0.3935, train_acc: 0.7619, val_acc: 0.9260\n    Epoch: 3, train_loss: 0.3205, val_loss: 0.1710, train_acc: 0.9078, val_acc: 0.9495\n    Epoch: 4, train_loss: 0.2329, val_loss: 0.1350, train_acc: 0.9264, val_acc: 0.9592\n    Epoch: 5, train_loss: 0.2046, val_loss: 0.1244, train_acc: 0.9338, val_acc: 0.9641\n    Epoch: 6, train_loss: 0.1978, val_loss: 0.1242, train_acc: 0.9350, val_acc: 0.9597\n    Epoch: 7, train_loss: 0.1974, val_loss: 0.1042, train_acc: 0.9317, val_acc: 0.9654\n    Epoch: 8, train_loss: 0.1886, val_loss: 0.1045, train_acc: 0.9362, val_acc: 0.9681\n    Epoch: 9, train_loss: 0.2034, val_loss: 0.1297, train_acc: 0.9325, val_acc: 0.9574\n    Epoch: 10, train_loss: 0.1878, val_loss: 0.1153, train_acc: 0.9365, val_acc: 0.9605\n    Epoch: 11, train_loss: 0.2074, val_loss: 0.1181, train_acc: 0.9340, val_acc: 0.9605\n    Epoch: 12, train_loss: 0.1742, val_loss: 0.1274, train_acc: 0.9391, val_acc: 0.9535\n    Epoch: 13, train_loss: 0.1793, val_loss: 0.1222, train_acc: 0.9388, val_acc: 0.9597\n    Epoch: 14, train_loss: 0.1784, val_loss: 0.1198, train_acc: 0.9391, val_acc: 0.9605\n    Epoch: 15, train_loss: 0.1824, val_loss: 0.1066, train_acc: 0.9400, val_acc: 0.9650\n    Epoch: 16, train_loss: 0.1666, val_loss: 0.1093, train_acc: 0.9447, val_acc: 0.9614\n    Epoch: 17, train_loss: 0.1745, val_loss: 0.1219, train_acc: 0.9391, val_acc: 0.9623\n    Epoch: 18, train_loss: 0.1702, val_loss: 0.1145, train_acc: 0.9443, val_acc: 0.9650\n    Epoch    19: reducing learning rate of group 0 to 9.0000e-05.\n    Epoch: 19, train_loss: 0.1643, val_loss: 0.1224, train_acc: 0.9421, val_acc: 0.9619\n    Epoch: 20, train_loss: 0.1441, val_loss: 0.1026, train_acc: 0.9490, val_acc: 0.9650\n    Fold 2 accuracy score: 0.9649822695035462\n    Training on fold 3\n    Epoch: 1, train_loss: 2.7962, val_loss: 2.2467, train_acc: 0.1194, val_acc: 0.3240\n    Epoch: 2, train_loss: 1.4524, val_loss: 0.3583, train_acc: 0.7653, val_acc: 0.9486\n    Epoch: 3, train_loss: 0.3053, val_loss: 0.1763, train_acc: 0.9153, val_acc: 0.9512\n    Epoch: 4, train_loss: 0.2319, val_loss: 0.1384, train_acc: 0.9248, val_acc: 0.9579\n    Epoch: 5, train_loss: 0.2234, val_loss: 0.1533, train_acc: 0.9281, val_acc: 0.9512\n    Epoch: 6, train_loss: 0.2122, val_loss: 0.1346, train_acc: 0.9307, val_acc: 0.9574\n    Epoch: 7, train_loss: 0.1964, val_loss: 0.1336, train_acc: 0.9328, val_acc: 0.9601\n    Epoch: 8, train_loss: 0.1927, val_loss: 0.1450, train_acc: 0.9332, val_acc: 0.9539\n    Epoch: 9, train_loss: 0.1935, val_loss: 0.1457, train_acc: 0.9341, val_acc: 0.9543\n    Epoch: 10, train_loss: 0.1887, val_loss: 0.1670, train_acc: 0.9341, val_acc: 0.9508\n    Epoch: 11, train_loss: 0.1781, val_loss: 0.1352, train_acc: 0.9409, val_acc: 0.9552\n    Epoch: 12, train_loss: 0.1689, val_loss: 0.1508, train_acc: 0.9409, val_acc: 0.9512\n    Epoch: 13, train_loss: 0.1779, val_loss: 0.1306, train_acc: 0.9390, val_acc: 0.9588\n    Epoch: 14, train_loss: 0.1757, val_loss: 0.1378, train_acc: 0.9437, val_acc: 0.9583\n    Epoch: 15, train_loss: 0.1649, val_loss: 0.1489, train_acc: 0.9428, val_acc: 0.9552\n    Epoch: 16, train_loss: 0.1726, val_loss: 0.1308, train_acc: 0.9422, val_acc: 0.9570\n    Epoch: 17, train_loss: 0.1744, val_loss: 0.1609, train_acc: 0.9414, val_acc: 0.9486\n    Epoch    18: reducing learning rate of group 0 to 9.0000e-05.\n    Epoch: 18, train_loss: 0.1671, val_loss: 0.1264, train_acc: 0.9447, val_acc: 0.9592\n    Epoch: 19, train_loss: 0.1432, val_loss: 0.1227, train_acc: 0.9533, val_acc: 0.9588\n    Epoch: 20, train_loss: 0.1336, val_loss: 0.1258, train_acc: 0.9530, val_acc: 0.9628\n    Fold 3 accuracy score: 0.9627659574468085\n    Training on fold 4\n    Epoch: 1, train_loss: 2.7867, val_loss: 2.2422, train_acc: 0.1158, val_acc: 0.7057\n    Epoch: 2, train_loss: 1.4403, val_loss: 0.3659, train_acc: 0.8127, val_acc: 0.9211\n    Epoch: 3, train_loss: 0.3105, val_loss: 0.2038, train_acc: 0.9170, val_acc: 0.9326\n    Epoch: 4, train_loss: 0.2357, val_loss: 0.1487, train_acc: 0.9239, val_acc: 0.9552\n    Epoch: 5, train_loss: 0.2257, val_loss: 0.1388, train_acc: 0.9239, val_acc: 0.9539\n    Epoch: 6, train_loss: 0.2045, val_loss: 0.1317, train_acc: 0.9326, val_acc: 0.9588\n    Epoch: 7, train_loss: 0.2040, val_loss: 0.1624, train_acc: 0.9294, val_acc: 0.9499\n    Epoch: 8, train_loss: 0.1919, val_loss: 0.1336, train_acc: 0.9393, val_acc: 0.9570\n    Epoch: 9, train_loss: 0.1900, val_loss: 0.1292, train_acc: 0.9390, val_acc: 0.9628\n    Epoch: 10, train_loss: 0.1891, val_loss: 0.1332, train_acc: 0.9354, val_acc: 0.9579\n    Epoch: 11, train_loss: 0.1874, val_loss: 0.1245, train_acc: 0.9350, val_acc: 0.9610\n    Epoch: 12, train_loss: 0.1832, val_loss: 0.1162, train_acc: 0.9385, val_acc: 0.9654\n    Epoch: 13, train_loss: 0.1843, val_loss: 0.1115, train_acc: 0.9338, val_acc: 0.9654\n    Epoch: 14, train_loss: 0.1734, val_loss: 0.1278, train_acc: 0.9403, val_acc: 0.9628\n    Epoch: 15, train_loss: 0.1782, val_loss: 0.1357, train_acc: 0.9381, val_acc: 0.9552\n    Epoch: 16, train_loss: 0.1641, val_loss: 0.1310, train_acc: 0.9450, val_acc: 0.9588\n    Epoch: 17, train_loss: 0.1654, val_loss: 0.1181, train_acc: 0.9458, val_acc: 0.9623\n    Epoch: 18, train_loss: 0.1640, val_loss: 0.1267, train_acc: 0.9409, val_acc: 0.9592\n    Epoch: 19, train_loss: 0.1614, val_loss: 0.1378, train_acc: 0.9434, val_acc: 0.9597\n    Epoch: 20, train_loss: 0.1660, val_loss: 0.1302, train_acc: 0.9403, val_acc: 0.9574\n    Fold 4 accuracy score: 0.9574468085106383\n    OOF accuracy score: 0.9597783933518006\n\n\n### 4.2. \u041c\u043e\u0434\u0435\u043b\u044c-\u0441\u0442\u0443\u0434\u0435\u043d\u0442. \u0414\u0438\u0441\u0442\u0438\u043b\u043b\u044f\u0446\u0438\u044f \u0437\u043d\u0430\u043d\u0438\u0439\n\n\u0421\u0442\u0443\u0434\u0435\u043d\u0442 - Resnet18 \u0441 \u0434\u0432\u0443\u043c\u044f \u0434\u043e\u043f\u043e\u043b\u043d\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u043c\u0438 \u0441\u043a\u0440\u044b\u0442\u044b\u043c\u0438 \u043f\u043e\u043b\u043d\u043e\u0441\u0432\u044f\u0437\u043d\u044b\u043c\u0438 \u0441\u043b\u043e\u044f\u043c\u0438 \u043f\u043e 128 \u044e\u043d\u0438\u0442\u043e\u0432. \u041f\u0440\u0438 \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u0438 \u044d\u0442\u043e\u0439 \u043c\u043e\u0434\u0435\u043b\u0438 \u044f \u043d\u0435 \u0437\u0430\u0434\u0435\u0439\u0441\u0442\u0432\u0443\u044e \u043d\u0438 \u0434\u0440\u043e\u043f\u0430\u0443\u0442\u044b, \u043d\u0438 \u0430\u0443\u0433\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0438. \u0421\u043f\u043e\u0439\u043b\u0435\u0440: \u044d\u0442\u043e \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e, \u043f\u043e\u0442\u043e\u043c\u0443 \u0447\u0442\u043e \u044d\u0444\u0444\u0435\u043a\u0442 \u043e\u0442 KD \u0432 \u044d\u0442\u043e\u0439 \u0437\u0430\u0434\u0430\u0447\u0435 \u043e\u0447\u0435\u043d\u044c \u043c\u0430\u043b\u0435\u043d\u044c\u043a\u0438\u0439, \u0438 \u0447\u0442\u043e\u0431\u044b \u0435\u0433\u043e \u043e\u0431\u043d\u0430\u0440\u0443\u0436\u0438\u0442\u044c, \u043d\u0443\u0436\u043d\u043e \u0438\u0441\u043a\u043b\u044e\u0447\u0438\u0442\u044c \u0432\u0441\u0435 \u043f\u0440\u043e\u0447\u0438\u0435 \u0444\u0430\u043a\u0442\u043e\u0440\u044b, \u0432\u043b\u0438\u044f\u044e\u0449\u0438\u0435 \u043d\u0430 \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u043e \u043c\u043e\u0434\u0435\u043b\u0438.\n\n\n```python\nos.makedirs(\"./experiments/hyperparams\", exist_ok=True)\nseed_everything(SEED)\n\nresnet18 = resnet18_student2(N_CLASSES, DEVICE)\ntrainable = get_number_of_params(resnet18, trainable=True)\ntotal = get_number_of_params(resnet18, trainable=False)\nprint(f\"{trainable} (of {total}) trainable params\")\ntrain_dataset = ImageDataset(train_val_files, LABEL_ENCODER, teacher_labels=\"./dark_knowledge/resnet101_train_imagewoof.npy\")\ntest_dataset = ImageDataset(test_files, LABEL_ENCODER, teacher_labels=\"./dark_knowledge/resnet101_test_imagewoof.npy\")\nopt = torch.optim.Adam(resnet18.parameters(), lr=0.0001)\ncriterion = DistillationLoss(alpha=0.1, temperature=4.0)\nhistory_resnet18 = train(train_dataset, test_dataset, resnet18, 50, 64, DEVICE, opt, criterion)\nplot_training_history(history_resnet18)\nnp.save(\"./experiments/hyperparams/history_resnet18_T_4.0_alpha_0.1.npy\", history_resnet18)\n```\n\n### 4.3. \u041e\u0431\u0443\u0447\u0435\u043d\u0438\u0435 \u0431\u0435\u0437 \u043f\u043e\u043c\u043e\u0449\u0438 \u0443\u0447\u0438\u0442\u0435\u043b\u044f \u0438 \u0441\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u0435 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u043e\u0432\n\n\u041f\u043e\u0432\u0442\u043e\u0440\u0438\u043c \u043f\u0440\u043e\u0446\u0435\u0434\u0443\u0440\u0443 \u043f\u0440\u0435\u0434\u044b\u0434\u0443\u0449\u0435\u0433\u043e \u043f\u0443\u043d\u043a\u0442\u0430, \u0442\u043e\u043b\u044c\u043a\u043e \u0431\u0435\u0437 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u044f \u043c\u0435\u0442\u043e\u043a \u043c\u043e\u0434\u0435\u043b\u0438-\u0443\u0447\u0438\u0442\u0435\u043b\u044f.\n\n\n```python\nos.makedirs(\"./experiments/hyperparams\", exist_ok=True)\nseed_everything(SEED)\n\nresnet18 = resnet18_student2(N_CLASSES, DEVICE)\ntrainable = get_number_of_params(resnet18, trainable=True)\ntotal = get_number_of_params(resnet18, trainable=False)\nprint(f\"{trainable} (of {total}) trainable params\")\ntrain_dataset = ImageDataset(train_val_files, LABEL_ENCODER)\ntest_dataset = ImageDataset(test_files, LABEL_ENCODER)\nopt = torch.optim.Adam(resnet18.parameters(), lr=0.0003)\ncriterion = nn.CrossEntropyLoss()\nhistory_resnet18_no_teacher = train(train_dataset, test_dataset, resnet18, 50, 64, DEVICE, opt, criterion)\nplot_training_history(history_resnet18_no_teacher)\nnp.save(f\"./experiments/hyperparams/history_resnet18_no_teacher.npy\", history_resnet18_no_teacher)\n```\n\n\u041f\u043e\u0441\u0442\u0440\u043e\u0438\u043c \u0433\u0440\u0430\u0444\u0438\u043a\u0438 accuracy \u043c\u043e\u0434\u0435\u043b\u0435\u0439 \u043d\u0430 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0435.\n\n\n```python\nhistory_resnet18_teacher = np.load(\"./experiments/hyperparams/history_resnet18_T_4.0_alpha_0.1.npy\")\nhistory_resnet18_no_teacher = np.load(\"./experiments/hyperparams/history_resnet18_no_teacher.npy\")\nplt.figure(figsize=(10, 6))\nplt.plot(history_resnet18[:, 3], label = \"T=4, alpha=0.1\")\nplt.plot(history_resnet18_no_teacher[:, 3], label = \"no teacher\")\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Accuracy\")\nplt.legend()\nplt.grid()\n```\n\n\u041f\u0440\u0438\u043c\u0435\u0440\u043d\u043e \u043a 30-50 \u044d\u043f\u043e\u0445\u0430\u043c \u043e\u0431\u0435 \u043c\u043e\u0434\u0435\u043b\u0438 \u0432\u044b\u0445\u043e\u0434\u044f\u0442 \u043d\u0430 \u043f\u043b\u0430\u0442\u043e. \u0421\u0443\u0434\u044f \u043f\u043e \u0432\u0441\u0435\u043c\u0443, KD \u0434\u0430\u043b \u043d\u0435\u0431\u043e\u043b\u044c\u0448\u043e\u0439 \u043f\u0440\u0438\u0440\u043e\u0441\u0442 \u0432 \u043c\u0435\u0442\u0440\u0438\u043a\u0435. \u0420\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442, \u043a\u043e\u043d\u0435\u0447\u043d\u043e, \u043d\u0435 \u043e\u0447\u0435\u043d\u044c \u0432\u043f\u0435\u0447\u0430\u0442\u043b\u044f\u0435\u0442. \u041c\u043e\u0436\u043d\u043e \u0441\u0440\u0430\u0432\u043d\u0438\u0432\u0430\u0442\u044c \u0444\u0438\u043d\u0430\u043b\u044c\u043d\u043e\u0435 \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u043e, \u0443\u0441\u0440\u0435\u0434\u043d\u044f\u044f \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u044b \u043f\u043e\u0441\u043b\u0435\u0434\u043d\u0438\u0445 20-\u0442\u0438 \u044d\u043f\u043e\u0445.\n\n\n```python\nprint(\"KD: {:.4f}, no teacher: {:.4f}\".format(history_resnet18_teacher[-20:, 3].mean(), history_resnet18_no_teacher[-20:, 3].mean()))\n```\n\n    KD: 0.9302, no teacher: 0.9262\n\n\n## 5. \u042d\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442 \u0441 \u0440\u0430\u0437\u043d\u044b\u043c\u0438 \u0442\u0435\u043c\u043f\u0435\u0440\u0430\u0442\u0443\u0440\u0430\u043c\u0438\n\n\u042f \u043f\u0440\u043e\u0432\u0451\u043b \u0441\u0435\u0440\u0438\u044e \u0430\u043d\u0430\u043b\u043e\u0433\u0438\u0447\u043d\u044b\u0445 \u044d\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442\u043e\u0432 \u0434\u043b\u044f $\\alpha = 0.1$ \u0438 $T = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]$.\n\n\n```python\ntemperatures = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]\nmeans = []\n\nplt.figure(figsize=(10, 6))\nfor t in temperatures:\n    history = np.load(f\"/content/experiments/hyperparams/history_resnet18_T_{t}_alpha_0.1.npy\")\n    plt.plot(history[:, 3], label = f\"T={t}\")\n    means.append(history[-20:, 3].mean())\n\nhistory_no_teacher = np.load(\"./experiments/hyperparams/history_resnet18_no_teacher.npy\")\nmean_no_teacher = history_no_teacher[-20:, 3].mean()\nplt.plot(history_no_teacher[:, 3], label = \"no teacher\", color=\"black\")\n\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Test accuracy\")\nplt.title(\"Alpha = 0.1\")\nplt.ylim(0.91, 0.935)\nplt.legend()\nplt.grid()\nplt.show()\n```\n\n\n```python\nplt.figure(figsize=(10, 6))\nplt.plot(temperatures, means, \"bX\")\nplt.hlines(mean_no_teacher, 0, 9, \"red\", label=\"no teacher score\")\nplt.xlim(0, 9)\nplt.xlabel(\"Temperature\")\nplt.ylabel(\"Mean test accuracy\")\nplt.title(\"Alpha = 0.1\")\nplt.legend()\nplt.grid()\n```\n\n\u0412 \u044d\u0442\u043e\u043c \u044d\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442\u0435 \u043f\u043e\u0447\u0442\u0438 \u0432\u0441\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0442\u0435\u043c\u043f\u0435\u0440\u0430\u0442\u0443\u0440\u044b \u0434\u0430\u043b\u0438 \u043d\u0435\u0431\u043e\u043b\u044c\u0448\u043e\u0439 \u043f\u0440\u0438\u0440\u043e\u0441\u0442 \u0432 \u043c\u0435\u0442\u0440\u0438\u043a\u0435. \u041e\u043f\u0442\u0438\u043c\u0430\u043b\u044c\u043d\u0430\u044f \u0442\u0435\u043c\u043f\u0435\u0440\u0430\u0442\u0443\u0440\u0430 \u043d\u0430\u0445\u043e\u0434\u0438\u0442\u0441\u044f \u0433\u0434\u0435-\u0442\u043e \u0432 \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d\u0435 \u043e\u0442 3 \u0434\u043e 6. \u042d\u0444\u0444\u0435\u043a\u0442 \u043e\u0442 KD \u043f\u043e\u043b\u0443\u0447\u0438\u043b\u0441\u044f \u0441\u043e\u0432\u0441\u0435\u043c \u043d\u0435\u0431\u043e\u043b\u044c\u0448\u0438\u043c. \u0412 [\u044d\u0442\u043e\u043c](https://github.com/peterliht/knowledge-distillation-pytorch#results-shallow-and-deep-distillation) \u0440\u0435\u043f\u043e\u0437\u0438\u0442\u043e\u0440\u0438\u0438 \u043f\u0440\u043e\u0432\u043e\u0434\u0438\u043b\u0438\u0441\u044c \u043f\u043e\u0445\u043e\u0436\u0438\u0435 \u044d\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442\u044b \u0434\u043b\u044f \u0437\u0430\u0434\u0430\u0447 Computer Vision (\u043d\u0430 \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0435 CIFAR-10), \u0438 \u0443\u043b\u0443\u0447\u0448\u0435\u043d\u0438\u0435 \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u0430 \u0442\u043e\u0436\u0435 \u0431\u044b\u043b\u043e \u043d\u0435\u0437\u043d\u0430\u0447\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u043c.\n\n## 6. \u0412\u043b\u0438\u044f\u043d\u0438\u0435 \u0440\u0430\u0437\u043c\u0435\u0440\u0430 \u043e\u0431\u0443\u0447\u0430\u044e\u0449\u0435\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0438 \u043d\u0430 \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u043e \u0434\u0438\u0441\u0442\u0438\u043b\u043b\u044f\u0446\u0438\u0438\n\n\u0418\u043d\u0442\u0435\u0440\u0435\u0441\u043d\u043e \u043f\u043e\u0441\u043c\u043e\u0442\u0440\u0435\u0442\u044c, \u043a\u0430\u043a \u0431\u0443\u0434\u0443\u0442 \u043e\u0431\u0443\u0447\u0430\u0442\u044c\u0441\u044f \u043c\u043e\u0434\u0435\u043b\u0438 \u043f\u0440\u0438 \u0443\u043c\u0435\u043d\u044c\u0448\u0435\u043d\u0438\u0438 \u0440\u0430\u0437\u043c\u0435\u0440\u0430 \u043e\u0431\u0443\u0447\u0430\u044e\u0449\u0435\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0438. \u042f \u0432\u0437\u044f\u043b \u0434\u043e\u043b\u0438 \u043e\u0442 \u0438\u0441\u0445\u043e\u0434\u043d\u043e\u0433\u043e \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0430 $p = [0.01, 0.05, 0.1]$. \n\n\n```python\nps = [0.01, 0.05, 0.1]\n\nplt.figure(figsize=(10, 6))\nfor p in ps:\n    history = np.load(f\"./experiments/subset/history_resnet18_T_4.0_alpha_0.1_p_{p}.npy\")\n    plt.plot(history[:, 3], label = f\"alpha = 0.1, T = 4.0, p = {p}\")\n\n    history_no_teacher = np.load(f\"./experiments/subset/history_resnet18_no_teacher_p_{p}.npy\")\n    plt.plot(history_no_teacher[:, 3], label = f\"no teacher, p = {p}\")\n\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Test accuracy\")\nplt.legend()\nplt.grid()\nplt.show()\n```\n\nKD \u043b\u0443\u0447\u0448\u0435 \u0432\u0441\u0435\u0433\u043e \u043f\u043e\u043a\u0430\u0437\u0430\u043b \u0441\u0435\u0431\u044f \u0432 \u0441\u0430\u043c\u043e\u043c \u044d\u043a\u0441\u0442\u0440\u0435\u043c\u0430\u043b\u044c\u043d\u043e\u043c \u0441\u043b\u0443\u0447\u0430\u0435, \u043a\u043e\u0433\u0434\u0430 \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u0435 \u0432\u0435\u043b\u043e\u0441\u044c \u043d\u0430 $< 100$ \u043a\u0430\u0440\u0442\u0438\u043d\u043a\u0430\u0445. \u041f\u0440\u0438 \u0443\u0432\u0435\u043b\u0438\u0447\u0435\u043d\u0438\u0438 \u043e\u0431\u0443\u0447\u0430\u044e\u0449\u0435\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0438 \u043c\u043e\u0434\u0435\u043b\u044c \u043f\u043e\u043b\u0443\u0447\u0430\u0435\u0442 \u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e\u0441\u0442\u044c \u0445\u043e\u0440\u043e\u0448\u043e \u0433\u0435\u043d\u0435\u0440\u0430\u043b\u0438\u0437\u043e\u0432\u0430\u0442\u044c\u0441\u044f \u0438 \u044d\u0444\u0444\u0435\u043a\u0442 \u043e\u0442 KD \u0432\u043d\u043e\u0441\u0438\u0442 \u0443\u0436\u0435 \u043c\u0435\u043d\u044c\u0448\u0438\u0439 \u0432\u043a\u043b\u0430\u0434 \u0432 \u0444\u0438\u043d\u0430\u043b\u044c\u043d\u043e\u0435 \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u043e.\n\n## 7. \u041f\u0440\u043e\u043c\u0435\u0436\u0443\u0442\u043e\u0447\u043d\u044b\u0435 \u0432\u044b\u0432\u043e\u0434\u044b\n\n\u0420\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u044b, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u044f \u043f\u043e\u043b\u0443\u0447\u0438\u043b \u0432 \u044d\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442\u0430\u0445, \u043f\u043e\u043a\u0430\u0437\u044b\u0432\u0430\u044e\u0442 \u043d\u0435\u0437\u043d\u0430\u0447\u0438\u0442\u0435\u043b\u044c\u043d\u043e\u0435 \u0443\u043b\u0443\u0447\u0448\u0435\u043d\u0438\u0435 \u043c\u043e\u0434\u0435\u043b\u0438-\u0441\u0442\u0443\u0434\u0435\u043d\u0442\u0430 \u043f\u0440\u0438 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0438 KD. \u042d\u0442\u043e\u0433\u043e \u0432\u0441\u0451 \u0435\u0449\u0451 \u043d\u0435\u0434\u043e\u0441\u0442\u0430\u0442\u043e\u0447\u043d\u043e \u0434\u043b\u044f \u0442\u043e\u0433\u043e, \u0447\u0442\u043e\u0431\u044b \u043f\u0440\u0438\u043c\u0435\u043d\u044f\u0442\u044c \u043c\u0435\u0442\u043e\u0434 \u0432 \u0440\u0435\u0430\u043b\u044c\u043d\u044b\u0445 \u0437\u0430\u0434\u0430\u0447\u0430\u0445. \u0422\u0435\u043c \u043d\u0435 \u043c\u0435\u043d\u0435\u0435 \u044f \u0431\u044b \u0445\u043e\u0442\u0435\u043b \u0438\u0437\u0443\u0447\u0438\u0442\u044c \u0440\u0430\u0431\u043e\u0442\u0443 knowledge distillation \u0441\u043e\u0432\u043c\u0435\u0441\u0442\u043d\u043e \u0441 \u0434\u0440\u0443\u0433\u0438\u043c\u0438 \u043c\u0435\u0442\u043e\u0434\u0430\u043c\u0438 \u0441\u0436\u0430\u0442\u0438\u044f \u043d\u0435\u0439\u0440\u043e\u0441\u0435\u0442\u0435\u0439. \u0423 \u043c\u0435\u043d\u044f \u0435\u0441\u0442\u044c \u0433\u0438\u043f\u043e\u0442\u0435\u0437\u0430, \u0447\u0442\u043e \u043e\u043d \u043c\u043e\u0436\u0435\u0442 \u043f\u0440\u0438\u043d\u0435\u0441\u0442\u0438 \u043f\u043e\u043b\u044c\u0437\u0443 \u0441\u043e\u0432\u043c\u0435\u0441\u0442\u043d\u043e \u0441 [pruning](https://arxiv.org/pdf/1611.06440.pdf), \u0433\u0434\u0435 \u043c\u043e\u0436\u0435\u0442 \u0431\u044b\u0442\u044c \u0437\u0430\u0434\u0435\u0439\u0441\u0442\u0432\u043e\u0432\u0430\u043d \u043d\u0430 \u0441\u0442\u0430\u0434\u0438\u0438 fine-tuning (\u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e, \u043f\u043e\u043b\u0443\u0447\u0438\u0442\u0441\u044f \u0441\u043d\u0438\u0437\u0438\u0442\u044c \u043f\u043e\u0442\u0435\u0440\u044e \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u0430 \u043f\u043e\u0441\u043b\u0435 \u0438\u0442\u0435\u0440\u0430\u0446\u0438\u0438 pruning). \u0422\u0430\u043a\u0438\u0435 \u0438\u0441\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u043d\u0438\u044f \u0443\u0436\u0435 [\u043f\u0440\u043e\u0432\u043e\u0434\u0438\u043b\u0438\u0441\u044c](https://arxiv.org/pdf/1801.05787.pdf), \u0438 \u0435\u0441\u0442\u044c \u0434\u0430\u0436\u0435 \u043d\u0435\u043f\u043b\u043e\u0445\u0438\u0435 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u044b.\n", "meta": {"hexsha": "6854d1a90cd3b7eebf5033c34035c3b49b173f23", "size": 360043, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "report.ipynb", "max_stars_repo_name": "stdereka/knowledge-distillation", "max_stars_repo_head_hexsha": "d5c8437b242f3b1ca5b2a0f933611d7c69c26033", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-04-01T15:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T09:06:58.000Z", "max_issues_repo_path": "report.ipynb", "max_issues_repo_name": "stdereka/knowledge-distillation", "max_issues_repo_head_hexsha": "d5c8437b242f3b1ca5b2a0f933611d7c69c26033", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report.ipynb", "max_forks_repo_name": "stdereka/knowledge-distillation", "max_forks_repo_head_hexsha": "d5c8437b242f3b1ca5b2a0f933611d7c69c26033", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 341.5967741935, "max_line_length": 120146, "alphanum_fraction": 0.9059334579, "converted": true, "num_tokens": 9523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2845760042165267, "lm_q2_score": 0.1097057753333734, "lm_q1q2_score": 0.031219631183847397}}
{"text": "<a href=\"https://colab.research.google.com/github/probabll/demo-mbr-nmt/blob/main/German-English.ipynb\" target=\"_parent\"></a>\n\n# About\n\nThis is a demo of sampling-based minimum Bayes risk decoding for NMT [(Eikema and Aziz, 2020)](https://www.aclweb.org/anthology/2020.coling-main.398/) for educational purposes. For a scalable implementation check [mbr_nmt](https://github.com/Roxot/mbr-nmt) and [(Eikema and Aziz, 2021)](https://arxiv.org/abs/2108.04718).\n\n# Setting Up\n\nThis part will take care of the following:\n\n1. Clone the repository `demo-mbr-nmt`.\n2. Install dependencies.\n3. Download pre-trained models.\n\n\n```python\n!git clone https://github.com/probabll/demo-mbr-nmt.git\n```\n\n    fatal: destination path 'demo-mbr-nmt' already exists and is not an empty directory.\n\n\n\n```python\ncd demo-mbr-nmt\n```\n\n    /content/demo-mbr-nmt\n\n\n\n```python\n!git pull\n```\n\n    Already up to date.\n\n\n\n```python\n!pip install -r requirements.txt\n```\n\n    Requirement already satisfied: torch in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 1)) (1.9.0+cu102)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 2)) (1.19.5)\n    Requirement already satisfied: fairseq==0.10.2 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 3)) (0.10.2)\n    Requirement already satisfied: sacrebleu==1.5.1 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 4)) (1.5.1)\n    Requirement already satisfied: sacremoses==0.0.43 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 5)) (0.0.43)\n    Requirement already satisfied: sentencepiece==0.1.95 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 6)) (0.1.95)\n    Requirement already satisfied: regex in /usr/local/lib/python3.7/dist-packages (from fairseq==0.10.2->-r requirements.txt (line 3)) (2019.12.20)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from fairseq==0.10.2->-r requirements.txt (line 3)) (4.62.0)\n    Requirement already satisfied: dataclasses in /usr/local/lib/python3.7/dist-packages (from fairseq==0.10.2->-r requirements.txt (line 3)) (0.6)\n    Requirement already satisfied: cffi in /usr/local/lib/python3.7/dist-packages (from fairseq==0.10.2->-r requirements.txt (line 3)) (1.14.6)\n    Requirement already satisfied: cython in /usr/local/lib/python3.7/dist-packages (from fairseq==0.10.2->-r requirements.txt (line 3)) (0.29.24)\n    Requirement already satisfied: hydra-core in /usr/local/lib/python3.7/dist-packages (from fairseq==0.10.2->-r requirements.txt (line 3)) (1.1.1)\n    Requirement already satisfied: portalocker==2.0.0 in /usr/local/lib/python3.7/dist-packages (from sacrebleu==1.5.1->-r requirements.txt (line 4)) (2.0.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from sacremoses==0.0.43->-r requirements.txt (line 5)) (1.15.0)\n    Requirement already satisfied: click in /usr/local/lib/python3.7/dist-packages (from sacremoses==0.0.43->-r requirements.txt (line 5)) (7.1.2)\n    Requirement already satisfied: joblib in /usr/local/lib/python3.7/dist-packages (from sacremoses==0.0.43->-r requirements.txt (line 5)) (1.0.1)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch->-r requirements.txt (line 1)) (3.7.4.3)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi->fairseq==0.10.2->-r requirements.txt (line 3)) (2.20)\n    Requirement already satisfied: omegaconf==2.1.* in /usr/local/lib/python3.7/dist-packages (from hydra-core->fairseq==0.10.2->-r requirements.txt (line 3)) (2.1.1)\n    Requirement already satisfied: antlr4-python3-runtime==4.8 in /usr/local/lib/python3.7/dist-packages (from hydra-core->fairseq==0.10.2->-r requirements.txt (line 3)) (4.8)\n    Requirement already satisfied: importlib-resources in /usr/local/lib/python3.7/dist-packages (from hydra-core->fairseq==0.10.2->-r requirements.txt (line 3)) (5.2.2)\n    Requirement already satisfied: PyYAML>=5.1.0 in /usr/local/lib/python3.7/dist-packages (from omegaconf==2.1.*->hydra-core->fairseq==0.10.2->-r requirements.txt (line 3)) (5.4.1)\n    Requirement already satisfied: zipp>=3.1.0 in /usr/local/lib/python3.7/dist-packages (from importlib-resources->hydra-core->fairseq==0.10.2->-r requirements.txt (line 3)) (3.5.0)\n\n\n\n```python\n!bash de-en.sh\n```\n\n    Downloading de-en\n    --2021-09-06 16:11:10--  https://surfdrive.surf.nl/files/index.php/s/8lnmJPX3iXndRpz/download\n    Resolving surfdrive.surf.nl (surfdrive.surf.nl)... 145.100.27.67, 2001:610:108:203b:0:a11:da7a:5afe\n    Connecting to surfdrive.surf.nl (surfdrive.surf.nl)|145.100.27.67|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 1097465344 (1.0G) [application/x-tar]\n    Saving to: \u2018models/fairseq/de-en.tar\u2019\n    \n    models/fairseq/de-e 100%[===================>]   1.02G  23.4MB/s    in 52s     \n    \n    2021-09-06 16:12:02 (20.3 MB/s) - \u2018models/fairseq/de-en.tar\u2019 saved [1097465344/1097465344]\n    \n    Uncompressing\n    ._de-en\n    de-en/\n    de-en/._prep-newstest2018.sh\n    de-en/prep-newstest2018.sh\n    de-en/._dict.de.txt\n    de-en/dict.de.txt\n    de-en/._.DS_Store\n    de-en/.DS_Store\n    de-en/._sentencepiece.bpe.model.de\n    de-en/sentencepiece.bpe.model.de\n    de-en/._sentencepiece.bpe.model.en\n    de-en/sentencepiece.bpe.model.en\n    de-en/._README.md\n    de-en/README.md\n    de-en/._sentencepiece.bpe.vocab.de\n    de-en/sentencepiece.bpe.vocab.de\n    de-en/._dict.en.txt\n    de-en/dict.en.txt\n    de-en/data/\n    de-en/._sentencepiece.bpe.vocab.en\n    de-en/sentencepiece.bpe.vocab.en\n    de-en/._mle\n    de-en/mle/\n    de-en/._truecaser\n    de-en/truecaser/\n    de-en/truecaser/._truecase-model.en\n    de-en/truecaser/truecase-model.en\n    de-en/truecaser/._truecase-model.de\n    de-en/truecaser/truecase-model.de\n    de-en/mle/._averaged_model.pt\n    de-en/mle/averaged_model.pt\n    de-en/mle/._train.log\n    de-en/mle/train.log\n    de-en/data/._newstest2018.de-en.en\n    de-en/data/newstest2018.de-en.en\n    de-en/data/._news-commentary-v12.de-en.en\n    de-en/data/news-commentary-v12.de-en.en\n    de-en/data/._newstest2018.de-en.de\n    de-en/data/newstest2018.de-en.de\n    de-en/data/._news-commentary-v12.de-en.de\n    de-en/data/news-commentary-v12.de-en.de\n    Check: models/fairseq/de-en\n\n\n# Neural machine translation\n\nGiven an input $x$ (i.e., a sentence in a source language), a trained NMT model predicts a conditional distribution $Y|X=x, \\theta$ over all possible target-language translations of $x$. \n\nThe sample space $\\mathcal Y$ of the model is the set of all sequences of the form $(y_1, \\ldots, y_N)$ where $y_n$ belongs to a vocabulary of known target-language symbols, $N \\ge 1$ is the sequence length, and $y_N$ is a special end-of-sequence (EOS) symbol.\n\nAn outcome $y \\in \\mathcal Y$ is assigned probability mass:\n\n\\begin{align}\nP_{Y|X}(y|x,\\theta) &= \\prod_{n=1}^{N} \\mathrm{Cat}(y_n|f(x, y_{<n}; \\theta))\n\\end{align}\n\nwhere $y_{<n}$ is the sequence of tokens before the $n$th token, and $f(\\cdot; \\theta)$ is a neural network architecture with parameters $\\theta$.\n\n\nIn the previous section you downloaded a pre-trained NMT model, that is, a specific choice of architecture (a Transformer encoder-decoder model) and a collection of parameters $\\theta$. This model was trained to maximise the model's likelihood given a dataset of observations (i.e., our training data). \n\nYou can load the trained model using `demo.load`:\n\n\n```python\nfrom demo import load\n```\n\nThe next line will take a moment.\n\n\n```python\nmodel = load(src='de', tgt='en', np_seed=10, torch_seed=10)\n```\n\nGiven an input, a trained model can assign probability to known translations, as well as, be used to draw translation candidates.\n\n## Assigning probability \n\nLet's first see how to compute the surprisal of a given translation (i.e, the negative logarithm of the outcome's probability):\n\n\n```python\n# Here is an example input in German and its human translation in English\nexample_x = \"Es war noch nie leicht, ein rationales Gespr\u00e4ch \u00fcber den Wert von Gold zu f\u00fchren.\"\nexample_y = \"It has never been easy to have a rational conversation about the value of gold.\"\n```\n\n\n```python\n# Surprisal is the negative of the log-probability of the outcome\nsurp_obs = model.x2y.surprisal(\n    example_x, \n    example_y\n)['surprisal']\nprint(surp_obs, (-surp_obs).exp())\n```\n\n    tensor([3.3471]) tensor([0.0352])\n\n\n## Drawing samples\n\nNow let's see how to draw translation candidates from the model distribution:\n\n\n```python\nfor y in model.x2y.ancestral_sampling(example_x, num_samples=10)['output']:\n    print(y)\n```\n\n    /usr/local/lib/python3.7/dist-packages/torch/_tensor.py:575: UserWarning: floor_divide is deprecated, and will be removed in a future version of pytorch. It currently rounds toward 0 (like the 'trunc' function NOT 'floor'). This results in incorrect rounding for negative values.\n    To keep the current behavior, use torch.div(a, b, rounding_mode='trunc'), or for actual floor division, use torch.div(a, b, rounding_mode='floor'). (Triggered internally at  /pytorch/aten/src/ATen/native/BinaryOps.cpp:467.)\n      return torch.floor_divide(self, other)\n\n\n    It has never been easy to talk rationally about gold's value.\n    It has never been easy to start a rational conversation about the value of gold.\n    It has never been easy to make a rational talk about the value of gold.\n    It has never been easy to begin a rational conversation on the value of gold.\n    It has never been easy to address the value of gold in a rational manner.\n    It has never been easy to handle a rational conversation on the value of gold.\n    Discussing gold's value rationally has never been easy.\n    It is never easy to call a rational discussion about gold's value.\n    It is never easy to talk rationally about gold value.\n    We always enjoy discussing the value of gold.\n\n\n## Predicting a translation\n\nGiven an input sentence $x$, a trained model predicts an entire distribution $Y|X=x, \\theta$ over the space $\\mathcal Y$ of possible translations. \n\nIn order to pick a single translation candidate as our preferred translation, we need to introduce a criterion for decision making. Next, we recap two such criteria.\n\n### Maximum-a-posterior decoding \n\nMAP decoding tells us to pick the most probable translation.\n\\begin{align}\ny^{\\mathrm{mode}} &= \\arg\\max_{h \\in \\mathcal Y} ~ P_{Y|X}(h|x, \\theta)\n\\end{align}\n\nAs the space $\\mathcal Y$ is unbounded and the NMT model makes no Markov assumptions, this search is intractable. In practice, we approximate the decision rule searching through a beam of probable translations. \n\n\\begin{align}\ny^{\\mathrm{beam}} &= \\arg\\max_{h \\in \\mathrm{beam}(x)} ~  P_{Y|X}(h|x, \\theta)\n\\end{align}\n\n\n```python\nbeam = model.x2y.beam_search(example_x, beam_size=5)\nfor y, surp in zip(beam['output'], beam['surprisal']):\n    print(f\"{surp:.4f}\\t{y}\")\ny_map = beam['output'][0]\n```\n\n    2.4119\tIt has never been easy to talk rationally about the value of gold.\n    3.3470\tIt has never been easy to have a rational conversation about the value of gold.\n    3.6803\tIt has never been easy to discuss the value of gold rationally.\n    4.6698\tIt has never been easy to discuss the value of gold in a rational way.\n    5.7409\tIt has never been easy to discuss the value of gold in a rational manner.\n\n\n**Some things to note**\n\n* Often, the beam search translation has much higher probability (lower suprisal) than the reference translation.\n* Often, if you increase the `beam_size` parameter, beam search will find translations that are even more probable (even lower surprisal).\n\n\n### Minimum Bayes risk decoding\n\nMBR decoding tells us to pick the translation that has highest expected utility:\n\n\\begin{align}\ny^{\\text{mbr}} &= \\arg\\max_{h \\in \\mathcal Y} ~ \\underbrace{\\mathbb E[u(Y, h; x)|x, \\theta]}_{=: \\mu_u(h; x, \\theta)} \\\\\n&= \\arg\\max_{h \\in \\mathcal Y} ~ \\sum_{y \\in \\mathcal Y} u(y, h; x) P_{Y|X}(y|x, \\theta)\n\\end{align}\n\nwhere a utility function $u(y, h; x)$ quantifies the benefit of choosing $h$ as the translation of $x$, when $y$ is the correct (or preferred) translation.\n\nThere are two sources of intractability in MBR decoding. First,  just like in MAP decoding, the search space (i.e., the sample space $\\mathcal Y$) is unbounded. Second, for any given candidate translation $h$, the expected utility $\\mu_u(h; x, \\theta) = \\mathbb E[u(Y, h; x)|x, \\theta]$ is intractable to compute. \n\n[Eikema and Aziz (2020)](https://www.aclweb.org/anthology/2020.coling-main.398/) propose to  \n\n1. approximate the hypothesis space by a tractable subset of hypotheses $\\mathcal H(x)$ obtained by sampling from the model;\n2. approximate the expected value using Monte Carlo (MC).\n\nThe decision rule becomes\n\n\\begin{align}\ny^{\\text{smbr}} &= \\arg\\max_{h \\in \\mathcal H(x)} ~ \\underbrace{\\frac{1}{S} \\sum_{s=1}^S u(y^{(s)}, h; x)}_{=: \\hat\\mu_u(h; x, \\theta)}\n\\end{align}\n\nwhere $y^{(s)} \\sim Y|X=x, \\theta$ is a sample from the NMT model (samples can be drawn efficiently via ancestral sampling).\n\nFor much more on sampling-based MBR see also [Eikema and Aziz (2021)](https://arxiv.org/abs/2108.04718).\n\nWe have prepared a number of helpers for the demo. \n\n\n```python\nfrom demo import SampleFromNMT, CachedSampler, Utility, MBR\n```\n\nLet's start by picking a utility function. In this demo we will assign utility using ChrF, a metric for automatic assessment of translation quality that works by comparing a translation candidate (a hypothesis) to a reference translation. \n\n\n```python\nfrom sacrebleu import sentence_chrf\n```\n\nFor modularity, we need to make chrf compatible with `demo.Utility`, so here is a thin wrapper for that:\n\n\n```python\nclass ChrF(Utility):\n    \n    def __call__(self, src: str, hyp: str, ref: str) -> float:\n        return sentence_chrf(hyp, [ref]).score  # note that chrf does not make use of the source sentence\n\nchrf = ChrF()    \n```\n\nWe then need a space of translation candidates, which MBR will score and rank. It's rather natural to use the NMT model itself to obtain such a hypothesis space, for example, via ancestral sampling:\n\n\n```python\n# Duplicate translations do not change the result of MBR, so we discard duplicates\nhyp_space = list(set(model.x2y.ancestral_sampling(example_x, num_samples=100)['output']))\nlen(hyp_space)\n```\n\n\n\n\n    78\n\n\n\nMBR requires a sampler for MC estimation, here we construct one.\n\n\n```python\nnmt_sampler = SampleFromNMT(model.x2y, sample_size=100)\n```\n\n\n```python\nnmt_sampler(example_x)\n```\n\n\n\n\n    ['It has never been easy to talk rationally about the value of gold.',\n     'It has never been easy to talk rationally about the value of gold.',\n     'It has never been easy to talk rationally about the value of gold.',\n     'It has never been easy to talk rationally about the value of gold.',\n     'It has never been easy to talk rationally about the value of gold.',\n     'It has never been easy to talk rationally about the value of gold.',\n     'It has never been easy to talk rationally about the value of gold.',\n     'It has never been easy to talk rationally about the value of gold.',\n     'It has never been easy to talk rationally about the value of gold.',\n     'It has never been easy to talk rationally about the value of gold.',\n     'It has never been easy to have a rational conversation about the value of gold.',\n     'It has never been easy to have a rational conversation about the value of gold.',\n     'It has never been easy to have a rational conversation about the value of gold.',\n     'It has never been easy to engage in a rational conversation about the value of gold.',\n     'It has never been easy to discuss the value of gold rationally.',\n     'It has never been easy to discuss the value of gold rationally.',\n     'It has never been easy to discuss the value of gold rationally.',\n     'It has never been easy to discuss the value of gold rationally.',\n     'It has never been easy to discuss the value of gold rationally.',\n     'It has never been easy to discuss the value of gold rationally.',\n     'It has never been easy to enter into a rational conversation about the value of gold.',\n     'It has never been easy to have a rational discussion about the value of gold.',\n     'It has never been easy to have a rational conversation on the value of gold.',\n     'It has never been easy to engage in rational conversation about the value of gold.',\n     'It has never been easy to engage rationally in a conversation about the value of gold.',\n     'It has never been easy to conduct a rational conversation on the value of gold.',\n     'It has never been easy to conduct a rational discussion about the value of gold.',\n     \"It was never easy to have a rational conversation about gold's value.\",\n     'It has never been easy to engage in rational talk about the value of gold.',\n     'It has never been easy to have a rational debate about the value of gold.',\n     'It has never been easy to direct a rational conversation about the value of gold.',\n     \"It has never been easy to make a rational discussion about gold's value.\",\n     'It has never been easy to talk rationally about gold.',\n     'It has never been easy to discuss the value of gold on a rational basis.',\n     \"It has never been easy to converse rationally about gold's value.\",\n     'It has never been easy to talk sensibly about the value of gold.',\n     \"It has never been easy to have a rational exchange on gold's value.\",\n     \"It has never been easy to talk sensibly about gold's value.\",\n     'It has never been easy to have a rational exchange of minds about the value of gold.',\n     \"To have a rational conversation about gold's value has never been easy.\",\n     'It has never been easy, ever, to engage in a rational conversation about the value of gold.',\n     'It has never been easy to craft a rational discussion about the value of gold.',\n     'It has never been easy to proceed with a rational conversation about the value of gold.',\n     'It has never been easy to come to a rational discussion about the value of gold.',\n     '\"It has never been easy to speak rationally about the value of gold.',\n     'It has never been easy to engage in rational discussions of the value of gold.',\n     'It has never always been easy to talk rationally about the value of gold.',\n     'It has never been easy to enter a rational conversation over the value of gold.',\n     'It has never been easy to talk rationally about the value of Gold.',\n     'It has never been easy to carry out a rational talk about the value of gold.',\n     'It has never been easy to have a rational conversation about the amount of gold.',\n     'It has never been easy to make rational exchanges about the value of gold.',\n     'It used to be easy to talk rationally about the value of gold.',\n     'It has never been easy to drink a rational conversation about the value of gold.',\n     \"It has never been easy to engage rationally with talk about gold's value.\",\n     'Talking rationally about the value of gold was never easy.',\n     'A rational exchange of views about the value of gold has never been easy.',\n     'Living a rational conversation about the value of gold has never been easy.',\n     '\"It has never been easy to have a rational conversation about gold.',\n     'It has never been easy to engage in rational management of the value of gold.',\n     'It was never easy to have a rational chat about the value of gold.',\n     'The value of gold has never been easy to talk rationally about.',\n     'It has never been easy to hold a low-key conversation about the value of gold.',\n     'Conducting rational talks about the value of gold has never been easy.',\n     'It has never been easier to engage in rational talk of the value of gold.',\n     'Measuring the value of gold has never been easy.',\n     'It has never been easy to enter into a rational human conversation about the value of gold.',\n     'There has never been a simple dialogue about the value of gold.',\n     'It was never easy to talk rationally about the gold value.',\n     'It was never easy to get any rational conversation about the value of gold.',\n     'Making rational conversation about the value of gold has never been easy.',\n     \"Indeed, it's never made easy to talk rationally about the value of gold.\",\n     'It has never been easy to hold rational informed discussions about the value of gold.',\n     'It has never been easy to clash in rational terms about the value of gold.',\n     'It has never been easier to embark on rational talk about the value of gold.',\n     'It has always been easier to converse rationally about the value of gold.',\n     'Placing a rational conversation on the value of gold was never easy.',\n     'To be reasonable about the value of gold has never been easy.',\n     'It has never been easy to be coherent with the value of gold.',\n     'It has never been simple to purposefully talk about the value of gold.',\n     'It has never been easy to be rational in the eyes of a conversation about gold.',\n     'It never was easy to engage in a rational conversation about gold-like values.',\n     'Raising any rationality about the value of gold has never been easy.',\n     'Conducting rational words about the value of gold has never been easy.',\n     'At one point it has never been easy to discuss the real value of gold rationally.',\n     'This was not easy to reach a rational conversation about the value of gold.',\n     'It has never been easy to talk rationally on how well gold will be worth.',\n     'It has never been easy to conduct rational debate about property & # x02BC; s value.',\n     'No rational point being made about the value of gold has ever been easy.',\n     'It has never been easy to achieve a rational taxation of gold.',\n     'It has never been easy to tear rhetoric about the value of gold to crisis.',\n     \"It is never easy to bring anyone back to a rational point of view about gold's value.\",\n     'The way it is rationally spent on the value of gold has never been easy to discage.',\n     'Raising comprehension about gold values has never been easy;',\n     'There has never been a business touch on when anyone has talked rationally about gold values.',\n     'A rational discussion about the gold value has never I had a mind come along.',\n     'Anyone who had some information on gold buying a shelf like fluxes had the opportunity to view the buying price of gold in real companies with in mind.',\n     'The European Union has been relying on a genuine individual for many years to reinforce our national political action and root causes.',\n     '\u20ac? What budget was distributed for the profit from the gold granted?',\n     'Proposes powdered financial benefits for beginning buyers. Small and medium-sized companies is going to purchase DLCGs, but the forced selling them till the end meant lending money to their customers integrated in the marketplace.']\n\n\n\nSampling on CPU may be considered an expensive operation, as in MBR we need to draw samples repeatedly for each candidate in the hypothesis space, we may consider using a single shared pool of samples for all candidates. `demo.CachedSampler` is a helper for that.\n\n\n```python\ncached_sampler = CachedSampler(nmt_sampler, sample_size=30)\n```\n\n\n```python\ncached_sampler(example_x)\n```\n\n\n\n\n    ['It was never easy to discuss the value of gold rationally.',\n     'Speaking of the value of gold has never been easy.',\n     'It has never been easy to start through a rational conversation about the value of the gold.',\n     'Bond value was never easy to breathe: It was never the easy moment to talk rationally about the value of gold.',\n     'It has never been easy to make a rational conversation about currency values.',\n     \"It was never easy to talk rationally about gold's value.\",\n     'It has never been easy to discuss the value of gold in a rational manner.',\n     'It has never been easy to discuss the value of gold more rationally.',\n     'It has never been easy to discuss the value of gold more rationally.',\n     'Any rational discussion on the value of gold has never been easy.',\n     'Rational talk about a gold value has never been easy.',\n     'Professor Guisenberg presided over an art test in 1952, designed by Thomas Altowski.',\n     'It has never been easy to hold a rational conversation about currency values.',\n     'It has never been easy to set a rational conversation about the value of gold.',\n     'It has never been easy to discuss the value of gold more rationally.',\n     'It has never been easy to enter into a rational conversation about the value of gold.',\n     'It has never been easy to enter into a rational conversation about the value of gold.',\n     'It has never been easy to discuss the value of gold in a rational way.',\n     'It has never been easy to enter into a rational conversation about the value of gold.',\n     'It has never been easy to keep a reasonable conversation about the value of gold.',\n     'It has never been easy to discuss the value of gold rationally.',\n     'A rational conversation about the value of gold has never been easy.',\n     'Any rational discussion on the value of gold has never been easy.',\n     'It has never been easy to enter into a rational conversation about the value of gold.',\n     \"It's never been simple to have a rational conversation about gold's value.\",\n     'It has never been easy to have a rational conversation on the value of gold.',\n     'It has never been easy to discuss in a rational way the value of gold.',\n     'It has never been easy to regard the value of gold in a rational fashion.',\n     'It has never been easy to talk rationally about the value of gold.',\n     \"It has never been easy to engage in rational conversation about gold's cost.\",\n     'It has never been easy to make a rational conversation about the value of gold.',\n     \"A rational conversation about gold's value has never been easy.\",\n     'Today, the rapid have hardly been a group which honestly told, or the Spobiros are Qu\u00e9becians.',\n     'It has never been easy to make a rational conversation about currency values.',\n     'It has never been easy to make a rational conversation about currency values.',\n     'It has never been easy to engage in a rational conversation about the value of gold.',\n     'It has never been easy to input a rational conversation about price of gold.',\n     \"It's never easier to talk rationally about the value of gold.\",\n     'It has never been easy to talk rationally about gold.',\n     'It has never been quick to engage in rational conversations about the value of gold.',\n     'An informed discussion about the value of gold was never easy.',\n     'It has never been easy to discuss the value of gold in a rational way.',\n     'Professor Guisenberg presided over an art test in 1952, designed by Thomas Altowski.',\n     'It has never been easy to conduct a rational conversation on the value of gold.',\n     'It has never been easy to have a rational conversation about the value of gold.',\n     'It has never been easy to start through a rational conversation about the value of the gold.',\n     'Having a rational conversation about the value of gold has never been easy; this will probably mean the exchange of money.',\n     'It has never been easy to regard the value of gold in a rational fashion.',\n     'Discussions of a caliber of gold came too early.',\n     'Discussions of a caliber of gold came too early.']\n\n\n\n\n```python\nmbr = MBR(chrf, cached_sampler)  # This version of MBR is what Eikema and Aziz (2021) call MBR N-by-S\n```\n\n\n```python\ny_mbr = mbr.decode(example_x, hyp_space)\ny_mbr\n```\n\n\n\n\n    'It has never been easy to make any rational conversation about the value of gold.'\n\n\n\n\n```python\nchrf(example_x, y_map, example_y), chrf(example_x, y_mbr, example_y)\n```\n\n\n\n\n    (0.6750826084658059, 0.8838063208456114)\n\n\n\n\n```python\nfrom tabulate import tabulate\n```\n\n\n```python\nrows = []\nfor h, mu in sorted(zip(hyp_space, mbr.mus(example_x, hyp_space)), key=lambda pair: pair[1], reverse=True):\n    quality = chrf(example_x, h, example_y)\n    rows.append([mu, quality, h])\nprint(tabulate(rows, headers=['E[chrf(x, h, Y)]', 'chrf(x, h, ref)', 'candidate']))\n```\n\n      E[chrf(x, h, Y)]    chrf(x, h, ref)  candidate\n    ------------------  -----------------  --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n              0.664658           0.886664  It has never been easy to conduct a rational conversation about the value of gold.\n              0.659087           0.90062   It has never been easy to say a rational conversation about the value of gold.\n              0.655118           1         It has never been easy to have a rational conversation about the value of gold.\n              0.641811           0.90094   It has never been easy to do a rational conversation about the value of gold.\n              0.637213           0.835729  It has never been easy to have a rational conversation about gold's value.\n              0.633381           0.883806  It has never been easy to make any rational conversation about the value of gold.\n              0.628271           0.911187  It has never been easy to hold a rational conversation about the value of gold.\n              0.620876           0.817578  Conducting a rational conversation about the value of gold has never been easy.\n              0.618684           0.721071  It has never been easy to engage in a rational discussion about the value of gold.\n              0.617675           0.612032  It has never been easy to discuss the value of gold in a rational fashion.\n              0.617666           0.670212  It has never been easy to enter into dialogue rationally about the value of gold.\n              0.614589           0.60407   It has never been easy to discuss the value of gold in a rational way.\n              0.613682           0.675083  It has never been easy to talk rationally about the value of gold.\n              0.610339           0.886397  It has never been easy to thrill on a rational conversation about the value of gold.\n              0.606124           0.884556  It has never been easy to have a rational conversation over the value of gold.\n              0.605274           0.767775  It has never been easy to have a rational discussion about a meaning up to the value of gold.\n              0.602842           0.678189  It has never been easy to speak rationally about the value of gold.\n              0.596541           0.677154  It has never been easy to engage in rationality about the value of gold.\n              0.592622           0.587346  It has never been easy to discuss the value of gold rationally.\n              0.589643           0.714952  It has never been easy to conduct rational discussion about the value of gold.\n              0.586124           0.709362  It has never been easy to direct rational discussion about the value of gold.\n              0.583383           0.6227    It has never been easy to negotiate rationally on the value of gold.\n              0.580751           0.695361  It has never been easy to enter into a rational debate about the value of gold.\n              0.578215           0.618961  It has never been easy to engage in a rational dialogue on the value of gold.\n              0.576175           0.678455  It has never been easy to engage in rational debate about the value of gold.\n              0.573922           0.692405  It has never been easy to ask a rational word about the value of gold.\n              0.573308           0.618745  It's never been easy to talk rationally about the value of gold.\n              0.572303           0.62791   It has never been easy to be rational in the question of the value of gold.\n              0.571277           0.504081  It has never been easy to talk rationally about gold's value.\n              0.56936            0.650222  More generally, it has never been easy to speak rationally about the value of gold.\n              0.56746            0.67801   It has never been easy to be rational when talking about the value of gold.\n              0.564824           0.715683  It has never been easy to engage in a rational conversation about gold.\n              0.564819           0.730348  It has never been easy to conduct a rational conversation about gold values.\n              0.563938           0.677562  It has never been easy to engage in rational talk about the value of gold.\n              0.561168           0.792581  It has never been so easy to guide rational conversations about the value of gold.\n              0.560604           0.614493  But it has never been easy to enter into a rational debate on the value of gold.\n              0.558383           0.748634  It has never been easy to hold a rational conversation about gold's value.\n              0.553609           0.639809  It has never been easy to talk Rationally about the value of gold always.\n              0.548913           0.610123  It has never been easy to engage rationally on the value of gold.\n              0.54638            0.724392  It has never been easy to have a rational discussion of the value of gold.\n              0.545544           0.504081  \"It has never been easy to talk rationally about gold values.\n              0.542669           0.488271  It has never been easy to talk rationally about gold.\n              0.541175           0.813553  In order to sustain the quality, it has never been easy to have a rational conversation on the value of gold.\n              0.538226           0.744892  It has always been easier to keep a rational conversation about the value of gold.\n              0.537107           0.709403  Exchanging a rational conversation on the value of gold has never been easy.\n              0.534938           0.562835  It's never been easy to discern the value of gold and be a rational proposer.\n              0.527468           0.592258  It has never been easy to talk rationally about a value of gold.\n              0.523324           0.540816  It has never been easy to engage in rational discussion about gold's value.\n              0.506507           0.612627  It has never been easy to chat sensibly about the value of gold.\n              0.499075           0.531628  It was never easy to talk rationally about the value of gold.\n              0.496709           0.479668  It has never been easy to deal rationally with gold values.\n              0.49528            0.50747   It has never been easy still to discuss systematically the value of gold.\n              0.491318           0.764882  It has never been easy to have a rational conversation on gold's value.\n              0.486457           0.752891  It has always been easy to have an informal conversation about the value of gold.\n              0.486229           0.531629  Talking about the value of gold has never been easy.\n              0.478857           0.775973  It was never easy to hold a rational conversation about the value of gold.\n              0.476547           0.531508  It has never been easy to have rational talk on its value.\n              0.474625           0.631752  It has never been easy to keep a rational conversation focused on what gold ought to mean.\n              0.471237           0.424792  It has never been easy to discuss money rationally.\n              0.467101           0.460624  It was never easy to discuss the value of gold in a rational way.\n              0.461994           0.515633  It has never been easy to engage constructively with a given value of gold.\n              0.460473           0.489473  It has never been easy to be rational about gold.\n              0.439256           0.459534  It has never been easy to hold it rationally on incomes.\n              0.437783           0.560683  Indeed, it has never been simple to hold rational conversations about gold.\n              0.435147           0.464798  Discussing the value of gold with one another, universically speaking, has never been easy.\n              0.432098           0.631468  It used never to be easy to have a rational mindset about the value of gold.\n              0.431282           0.489732  \"Gold has never been easy to make a rational remark on what value it has to offer.\n              0.409525           0.435477  It's never been easy to put amounts to gold round about money in a rational way.\n              0.40589            0.451296  Discussing the value of gold has never been easy.\n              0.383871           0.403844  It's never been easy to start describing gold in a rational way.\n              0.383609           0.448246  One could never have seen a rational discussion about a value of gold facilitating this.\n              0.373323           0.358997  It is never easy or simply any rational discussion about gold's value.\n              0.35126            0.341711  To move independently, a bilateral transaction between the two was better. There was no time to discuss the value of the gold rationally.\n              0.336515           0.373002  It was never easy to be rational about gold with value.\n              0.281089           0.329801  Using energy for rational amendment of investors' price _ rumours and as services are reducing the effort linked with conversion, prices and exports have never been Frankfurt.\n              0.256596           0.261081  It's never a problem management talk about gold's value, as they reported a major theory - whether women like gold prizes or half a dollar awards - is uncomplicated.\n              0.236358           0.258179  Pragmatism and equivalence are both the objective and the test of mind. An incapable description is however: Rational meaning is dismissed as not the substance of a proper peg.\n              0.120835           0.100592  Getting to know gold is best possible.\n\n\n\n```python\n\n```\n\n### Analysis\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n\nHere we analyse whether a candidate's expected utility $\\mu_u(h;x, \\theta)$ correlates with utility against the ground-truth. As $\\mu_u(h;x, \\theta)$ is intractable to  compute, we rely on stochastic estimates $\\hat\\mu_u(h;x, \\theta)$. \n\n\n\n```python\nfrom tqdm.auto import tqdm\n```\n\nWe repeat the next experiment a number of times to account for variance, which may take some time.\n\n\n```python\nestimates = []\n# compute utility against reference\nfor h in hyp_space:    \n    cached_sampler.reset()  #\n    u = chrf(example_x, h, example_y)  # use human reference\n    estimates.append([u])\nrepetitions = 10  # let's repeat MC estimation a number of times to get a sense of variance    \nfor _ in tqdm(range(repetitions)):\n    cached_sampler.reset()  # reset cache to obtain a better view of variance\n    for n, h in enumerate(hyp_space):         \n        estimates[n].append(mbr.mu(example_x, h))\nestimates = np.array(estimates)    \n```\n\n\n      0%|          | 0/10 [00:00<?, ?it/s]\n\n\n\n```python\nestimates.shape\n```\n\n\n\n\n    (78, 11)\n\n\n\n\n```python\n_ = plt.errorbar(\n    estimates[:,0], estimates[:,1:].mean(1), yerr=estimates[:,1:].std(1) * 2, \n    marker='.', linestyle='', color='gray', label=r'mean and var of $\\hat\\mu_u(h;\\theta)$')\n_ = plt.title(\"Estimates of expected utility vs ground-truth utility\")\n_ = plt.xlabel(r'$u(y_{ref}, h; x)$')\n_ = plt.ylabel(r'$\\hat \\mu_u(h; x, \\theta)$')\n_ = plt.legend()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "9cc7855ef6d6dab0fc85113fee7aef26c491064d", "size": 91070, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "German-English.ipynb", "max_stars_repo_name": "probabll/demo-mbr-nmt", "max_stars_repo_head_hexsha": "7ca971e7c5357d7d3c1b9ccac1083fb4d7afb887", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "German-English.ipynb", "max_issues_repo_name": "probabll/demo-mbr-nmt", "max_issues_repo_head_hexsha": "7ca971e7c5357d7d3c1b9ccac1083fb4d7afb887", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "German-English.ipynb", "max_forks_repo_name": "probabll/demo-mbr-nmt", "max_forks_repo_head_hexsha": "7ca971e7c5357d7d3c1b9ccac1083fb4d7afb887", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.9543464665, "max_line_length": 17930, "alphanum_fraction": 0.6245854837, "converted": true, "num_tokens": 9924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28457600421652673, "lm_q2_score": 0.10970577387797076, "lm_q1q2_score": 0.031219630769674735}}
{"text": "```python\n!pip install qiskit\n!pip install qiskit-machine-learning\n```\n\n    Collecting qiskit\n      Downloading qiskit-0.33.0.tar.gz (13 kB)\n    Collecting qiskit-terra==0.19.0\n      Downloading qiskit_terra-0.19.0-cp37-cp37m-manylinux2010_x86_64.whl (6.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.4 MB 7.2 MB/s \n    \u001b[?25hCollecting qiskit-aer==0.9.1\n      Downloading qiskit_aer-0.9.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (17.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 17.9 MB 344 kB/s \n    \u001b[?25hCollecting qiskit-ibmq-provider==0.18.1\n      Downloading qiskit_ibmq_provider-0.18.1-py3-none-any.whl (237 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 237 kB 40.4 MB/s \n    \u001b[?25hCollecting qiskit-ignis==0.7.0\n      Downloading qiskit_ignis-0.7.0-py3-none-any.whl (200 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 200 kB 51.8 MB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.16.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.9.1->qiskit) (1.19.5)\n    Requirement already satisfied: scipy>=1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.9.1->qiskit) (1.4.1)\n    Collecting requests-ntlm>=1.1.0\n      Downloading requests_ntlm-1.1.0-py2.py3-none-any.whl (5.7 kB)\n    Collecting websocket-client>=1.0.1\n      Downloading websocket_client-1.2.3-py3-none-any.whl (53 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 53 kB 1.0 MB/s \n    \u001b[?25hRequirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.1->qiskit) (2.8.2)\n    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.1->qiskit) (1.24.3)\n    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.1->qiskit) (2.23.0)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ignis==0.7.0->qiskit) (57.4.0)\n    Collecting retworkx>=0.8.0\n      Downloading retworkx-0.10.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.4 MB 45.7 MB/s \n    \u001b[?25hRequirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.0->qiskit) (0.3.4)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.0->qiskit) (1.7.1)\n    Collecting stevedore>=3.0.0\n      Downloading stevedore-3.5.0-py3-none-any.whl (49 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 49 kB 6.0 MB/s \n    \u001b[?25hRequirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.0->qiskit) (5.4.8)\n    Collecting ply>=3.10\n      Downloading ply-3.11-py2.py3-none-any.whl (49 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 49 kB 4.2 MB/s \n    \u001b[?25hCollecting symengine>=0.8\n      Downloading symengine-0.8.1-cp37-cp37m-manylinux2010_x86_64.whl (38.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 38.2 MB 1.2 MB/s \n    \u001b[?25hCollecting tweedledum<2.0,>=1.1\n      Downloading tweedledum-1.1.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (943 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 943 kB 34.8 MB/s \n    \u001b[?25hCollecting scipy>=1.0\n      Downloading scipy-1.7.3-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (38.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 38.1 MB 1.2 MB/s \n    \u001b[?25hCollecting python-constraint>=1.4\n      Downloading python-constraint-1.4.0.tar.bz2 (18 kB)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.8.0->qiskit-ibmq-provider==0.18.1->qiskit) (1.15.0)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.1->qiskit) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.1->qiskit) (2021.10.8)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.1->qiskit) (3.0.4)\n    Collecting ntlm-auth>=1.0.2\n      Downloading ntlm_auth-1.5.0-py2.py3-none-any.whl (29 kB)\n    Collecting cryptography>=1.3\n      Downloading cryptography-36.0.0-cp36-abi3-manylinux_2_24_x86_64.whl (3.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.6 MB 44.1 MB/s \n    \u001b[?25hRequirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.1->qiskit) (1.15.0)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.1->qiskit) (2.21)\n    Collecting pbr!=2.1.0,>=2.0.0\n      Downloading pbr-5.8.0-py2.py3-none-any.whl (112 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 112 kB 74.8 MB/s \n    \u001b[?25hRequirement already satisfied: importlib-metadata>=1.7.0 in /usr/local/lib/python3.7/dist-packages (from stevedore>=3.0.0->qiskit-terra==0.19.0->qiskit) (4.8.2)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=1.7.0->stevedore>=3.0.0->qiskit-terra==0.19.0->qiskit) (3.6.0)\n    Requirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=1.7.0->stevedore>=3.0.0->qiskit-terra==0.19.0->qiskit) (3.10.0.2)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra==0.19.0->qiskit) (1.2.1)\n    Building wheels for collected packages: qiskit, python-constraint\n      Building wheel for qiskit (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for qiskit: filename=qiskit-0.33.0-py3-none-any.whl size=11763 sha256=9c6b76f5e5ce7ce8f189d285044d28477e6af1a14502b1a93d437f5f670e2263\n      Stored in directory: /root/.cache/pip/wheels/d4/60/ef/c49ae113df02818c4ade5fb6e2e89bb928625412eda0bb25f5\n      Building wheel for python-constraint (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for python-constraint: filename=python_constraint-1.4.0-py2.py3-none-any.whl size=24081 sha256=5718fdc37d2db9183104b1d851bd3a0eeab95114197d7ba73f2b5b52102d08bb\n      Stored in directory: /root/.cache/pip/wheels/07/27/db/1222c80eb1e431f3d2199c12569cb1cac60f562a451fe30479\n    Successfully built qiskit python-constraint\n    Installing collected packages: pbr, tweedledum, symengine, stevedore, scipy, retworkx, python-constraint, ply, ntlm-auth, cryptography, websocket-client, requests-ntlm, qiskit-terra, qiskit-ignis, qiskit-ibmq-provider, qiskit-aer, qiskit\n      Attempting uninstall: scipy\n        Found existing installation: scipy 1.4.1\n        Uninstalling scipy-1.4.1:\n          Successfully uninstalled scipy-1.4.1\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Successfully installed cryptography-36.0.0 ntlm-auth-1.5.0 pbr-5.8.0 ply-3.11 python-constraint-1.4.0 qiskit-0.33.0 qiskit-aer-0.9.1 qiskit-ibmq-provider-0.18.1 qiskit-ignis-0.7.0 qiskit-terra-0.19.0 requests-ntlm-1.1.0 retworkx-0.10.2 scipy-1.7.3 stevedore-3.5.0 symengine-0.8.1 tweedledum-1.1.1 websocket-client-1.2.3\n    Collecting qiskit-machine-learning\n      Downloading qiskit_machine_learning-0.2.1-py3-none-any.whl (96 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 96 kB 3.8 MB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from qiskit-machine-learning) (1.19.5)\n    Requirement already satisfied: qiskit-terra>=0.18.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-machine-learning) (0.19.0)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-machine-learning) (5.4.8)\n    Requirement already satisfied: scikit-learn>=0.20.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-machine-learning) (1.0.1)\n    Requirement already satisfied: fastdtw in /usr/local/lib/python3.7/dist-packages (from qiskit-machine-learning) (0.3.4)\n    Requirement already satisfied: scipy>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-machine-learning) (1.7.3)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-machine-learning) (57.4.0)\n    Requirement already satisfied: retworkx>=0.10.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.18.0->qiskit-machine-learning) (0.10.2)\n    Requirement already satisfied: symengine>=0.8 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.18.0->qiskit-machine-learning) (0.8.1)\n    Requirement already satisfied: python-constraint>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.18.0->qiskit-machine-learning) (1.4.0)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.18.0->qiskit-machine-learning) (2.8.2)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.18.0->qiskit-machine-learning) (0.3.4)\n    Requirement already satisfied: tweedledum<2.0,>=1.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.18.0->qiskit-machine-learning) (1.1.1)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.18.0->qiskit-machine-learning) (1.7.1)\n    Requirement already satisfied: ply>=3.10 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.18.0->qiskit-machine-learning) (3.11)\n    Requirement already satisfied: stevedore>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.18.0->qiskit-machine-learning) (3.5.0)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.8.0->qiskit-terra>=0.18.0->qiskit-machine-learning) (1.15.0)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.20.0->qiskit-machine-learning) (1.1.0)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.20.0->qiskit-machine-learning) (3.0.0)\n    Requirement already satisfied: importlib-metadata>=1.7.0 in /usr/local/lib/python3.7/dist-packages (from stevedore>=3.0.0->qiskit-terra>=0.18.0->qiskit-machine-learning) (4.8.2)\n    Requirement already satisfied: pbr!=2.1.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from stevedore>=3.0.0->qiskit-terra>=0.18.0->qiskit-machine-learning) (5.8.0)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=1.7.0->stevedore>=3.0.0->qiskit-terra>=0.18.0->qiskit-machine-learning) (3.6.0)\n    Requirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=1.7.0->stevedore>=3.0.0->qiskit-terra>=0.18.0->qiskit-machine-learning) (3.10.0.2)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra>=0.18.0->qiskit-machine-learning) (1.2.1)\n    Installing collected packages: qiskit-machine-learning\n    Successfully installed qiskit-machine-learning-0.2.1\n\n\n\n```python\nimport numpy as np\n\n# Importing standard Qiskit libraries\nimport qiskit\nfrom qiskit import QuantumCircuit, transpile, Aer, IBMQ\nfrom qiskit.tools.jupyter import *\nfrom qiskit.visualization import *\n#from ibm_quantum_widgets import *\nfrom qiskit.providers.aer import QasmSimulator\n\n# Loading your IBM Quantum account(s)\n#provider = IBMQ.load_account()\n```\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom qiskit import Aer, QuantumCircuit\nfrom qiskit.opflow import Z, I, StateFn\nfrom qiskit.utils import QuantumInstance\nfrom qiskit.circuit import Parameter\nfrom qiskit.circuit.library import RealAmplitudes, ZZFeatureMap\nfrom qiskit.algorithms.optimizers import COBYLA, L_BFGS_B\n\nfrom qiskit_machine_learning.neural_networks import TwoLayerQNN, CircuitQNN\nfrom qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier, VQC\nfrom qiskit_machine_learning.algorithms.regressors import NeuralNetworkRegressor, VQR\n\nfrom typing import Union\n\nfrom qiskit_machine_learning.exceptions import QiskitMachineLearningError\n\nfrom IPython.display import clear_output\n```\n\n\n```python\n  #def get_noise_model():\nfrom qiskit.providers.aer.noise import NoiseModel\nfrom qiskit.providers.aer import noise\nnoise_model = NoiseModel()\n# Error probabilities\n#prob_1 = 0.001  # 1-qubit gate\nprob_2 = 0.000   # 2-qubit gate\n\n# Depolarizing quantum errors\n#error_1 = noise.depolarizing_error(prob_1, 1)\nerror_2 = noise.depolarizing_error(prob_2, 2)\n\n# Add errors to noise model\nnoise_model = noise.NoiseModel()\n#noise_model.add_all_qubit_quantum_error(error_1, ['u1', 'u2', 'u3', 'h', 'id', 'rz', 'sx', 'rx', 'ry'])\nnoise_model.add_all_qubit_quantum_error(error_2, ['cx'])\n    \n    #return noise_model\n```\n\n\n```python\nquantum_instance = QuantumInstance(Aer.get_backend('aer_simulator'), shots=1024)\n```\n\n\n```python\n#noise_model1 = get_noise_model()\nquantum_instance_noise = QuantumInstance(Aer.get_backend('aer_simulator'), shots=1024, noise_model = noise_model)\n\n```\n\n\n```python\n# construct simple feature map\nparam_x = Parameter('x')\nfeature_map = QuantumCircuit(1, name='fm')\nfeature_map.ry(param_x, 0)\nprint(feature_map)\n\n# construct simple ansatz\nparam_y = Parameter('y')\nansatz = QuantumCircuit(1, name='vf')\nansatz.ry(param_y, 0)\nprint(ansatz)\n#ansatz.draw(output='mpl')\n# construct QNN\nregression_opflow_qnn = TwoLayerQNN(1, feature_map, ansatz, quantum_instance=quantum_instance)\nregression_opflow_qnn_noise = TwoLayerQNN(1, feature_map, ansatz, quantum_instance=quantum_instance_noise)\n```\n\n       \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    q: \u2524 Ry(x) \u251c\n       \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n       \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    q: \u2524 Ry(y) \u251c\n       \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\n\n\n```python\n# callback function that draws a live plot when the .fit() method is called\nobjective_func_vals = []\ndef callback_graph(weights, obj_func_eval):\n    clear_output(wait=True)\n    objective_func_vals.append(obj_func_eval)\n    plt.title(\"Objective function value against iteration\")\n    plt.xlabel(\"Iteration\")\n    plt.ylabel(\"Objective function value\")\n    plt.plot(range(len(objective_func_vals)), objective_func_vals)\n    plt.show()\n```\n\n\n```python\n# callback function that draws a live plot when the .fit() method is called\nobjective_func_vals_noise = []\ndef callback_graph_noise(weights, obj_func_eval):\n    clear_output(wait=True)\n    objective_func_vals_noise.append(obj_func_eval)\n    plt.title(\"Objective function value against iteration\")\n    plt.xlabel(\"Iteration\")\n    plt.ylabel(\"Objective function value\")\n    plt.plot(range(len(objective_func_vals_noise)), objective_func_vals_noise)\n    plt.show()\n```\n\n\n```python\n# construct the regressor from the neural network\nregressor = NeuralNetworkRegressor(neural_network=regression_opflow_qnn,\n                                   loss='l2',\n                                   optimizer=L_BFGS_B(),\n                                   callback=callback_graph)\n```\n\n\n```python\n# construct the regressor from the neural network\nregressor_noise = NeuralNetworkRegressor(neural_network=regression_opflow_qnn_noise,\n                                   loss='l2',\n                                   optimizer=L_BFGS_B(),\n                                   callback=callback_graph_noise)\n```\n\n\n```python\n#from IPython.core.debugger import set_trace\n```\n\n\n```python\n#import sys\n'''\nsys.path.append(\"../Qiskit_Dynamic_Modelling\")\nsys.path.append(\"./modelQ\")\nsys.path.append(\"./dynamicsQ\")\n'''\nsys.path.append(\"./sample_data\")\nfrom dataloader import *\ntrain_data = np.load('/content/sample_data/train_dataset.npz')\ntrain_inputs = train_data[\"input\"]\ntrain_labels = train_data[\"labels\"]\nX_inputs = train_inputs[:100]#50000]\ny_labels = train_labels[:100]#50000]\n#train_dataset = DynamicsDataset(train_inputs, train_labels)\ntrain_dataset = DynamicsDataset(X_inputs, y_labels)\n\ntrain_dataloader = torch.utils.data.DataLoader(train_dataset,\n                                                 batch_size=1,\n                                                 shuffle=True,\n                                                 collate_fn=DynamicsDataset.collate_fn,\n                                                 pin_memory=True,\n                                                 num_workers=1)\nprint(len(X_inputs))\nprint(len(y_labels))\n\n```\n\n    100\n    100\n\n\n\n```python\nfrom qiskit import transpile, assemble\nclass QuanvCircuit:\n    \"\"\" \n    This class defines filter circuit of Quanvolution layer\n    \"\"\"    \n    def __init__(self, kernel_size, backend, shots, threshold):\n        # --- Circuit definition start ---\n        self.n_qubits = kernel_size ** 2\n        self._circuit = qiskit.QuantumCircuit(self.n_qubits)\n        self.theta = [qiskit.circuit.Parameter('theta{}'.format(i)) for i in range(self.n_qubits)]\n\n        for i in range(self.n_qubits):\n            self._circuit.rx(self.theta[i], i)\n        \n        #self._circuit.barrier()\n        self._circuit.measure_all()\n        # ---- Circuit definition end ----\n        self.backend   = backend\n        self.shots     = shots\n        self.threshold = threshold\n\n    def run(self, data):\n        # encoding data to parameters\n        thetas = [data]\n        \n        param_dict = dict()\n        for theta in thetas:\n            for i in range(self.n_qubits):\n                param_dict[self.theta[i]] = theta[i]\n        param_binds = [param_dict]\n\n        List = [thetas]\n        t_qc = transpile(self._circuit,\n                         self.backend)\n        qobj = assemble(t_qc,\n                        shots=self.shots,\n                        parameter_binds = param_binds)\n        job = self.backend.run(qobj)\n        result = job.result().get_counts()\n\n        # decoding the result\n        counts = 0\n        for key, val in result.items():\n            cnt = sum([int(char) for char in key])\n            counts += cnt * val\n        \n        probabilities = counts / (self.shots * self.n_qubits)\n        \n        return probabilities\n```\n\n\n```python\nbackend = qiskit.Aer.get_backend('qasm_simulator')\nfilter_size = 2\ncirc = QuanvCircuit(filter_size, backend, 100, 127)\n#data = torch.tensor([[0, 200], [100, 255]])\n#data = torch.tensor([-2.8351264, 1.3314428,  -0.18492305,  0.00792312]).numpy()#1,2,3,4]).numpy()\ndata = [-2.8351264,  1.3314428,  -0.18492305,  0.00792312]\n\n#\nprint(data)\n#print(data.size())\nprint(circ.run(data))\n\ncirc._circuit.draw()#output='mpl')\n```\n\n    [-2.8351264, 1.3314428, -0.18492305, 0.00792312]\n    0.3325\n\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">        \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2591 \u250c\u2500\u2510         \n   q_0: \u2524 Rx(theta0) \u251c\u2500\u2591\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n        \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2591 \u2514\u2565\u2518\u250c\u2500\u2510      \n   q_1: \u2524 Rx(theta1) \u251c\u2500\u2591\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u2500\u2500\n        \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2591  \u2551 \u2514\u2565\u2518\u250c\u2500\u2510   \n   q_2: \u2524 Rx(theta2) \u251c\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u2500\u2500\n        \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2591  \u2551  \u2551 \u2514\u2565\u2518\u250c\u2500\u2510\n   q_3: \u2524 Rx(theta3) \u251c\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2524M\u251c\n        \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2591  \u2551  \u2551  \u2551 \u2514\u2565\u2518\nmeas: 4/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\n                          0  1  2  3 </pre>\n\n\n\n\n```python\nimport qiskit\nbackend = qiskit.Aer.get_backend('qasm_simulator')\nfilter_size = 2\ncirc = QuanvCircuit(filter_size, backend, 100, 127)\n```\n\n\n```python\n#for (X_train, y_train) in train_dataloader:\nprint('Loading Training data')\nxVal = []\nyVal = []\n#count = 0\nfor (X_train, y_train) in train_dataloader:\n    #print('Training Starts')\n    #print(X_train.detach().numpy()[0])\n    #print(y_train.detach().numpy()[0])\n    x = circ.run(X_train.detach().numpy()[0])\n    y = circ.run(y_train.detach().numpy()[0])\n    #regressor.fit(x, y)\n    \n    xVal.append([x])\n    yVal.append(y)\n    '''\n    count += 1\n    \n    if (count == 50000):\n        print('Loaded data :',count)\n        break\n    '''\nprint('x data',len(xVal))\nprint('y data',len(yVal))\n\n```\n\n    Loading Training data\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    x data 100\n    y data 100\n\n\n\n```python\n#print(torch.tensor(xVal).detach().numpy())\n#print(torch.tensor(yVal).detach().numpy())\nimport time\nprint('Training Started')\nstartTime = time.time()\nregressor.fit(torch.tensor(xVal).detach().numpy(), torch.tensor(yVal).detach().numpy())\nprint('Total Training Time :', (time.time()-startTime))\n```\n\n\n```python\n#print(torch.tensor(xVal).detach().numpy())\n#print(torch.tensor(yVal).detach().numpy())\nimport time\nprint('Training Started')\nstartTime = time.time()\nregressor_noise.fit(torch.tensor(xVal).detach().numpy(), torch.tensor(yVal).detach().numpy())\nprint('Total Training Time :', (time.time()-startTime))\n```\n\n\n```python\n# score the result\nregressor.score(torch.tensor(xVal).detach().numpy(), torch.tensor(yVal).detach().numpy())\n```\n\n\n\n\n    -0.8868040210846102\n\n\n\n\n```python\n# score the result\nregressor_noise.score(torch.tensor(xVal).detach().numpy(), torch.tensor(yVal).detach().numpy())\n```\n\n\n\n\n    -0.8087757357649599\n\n\n\n\n```python\nimport matplotlib.pyplot as plt\n\nplt.style.use(\"seaborn\")\nfig, (ax1) = plt.subplots(figsize=(6,6))\n\nax1.plot(objective_func_vals, \"-ob\", label=\"Response without noise\")\nax1.plot(objective_func_vals_noise, \"-or\", label=\"Response with noise\")\n\nax1.set_ylabel(\"Objective Function Value\")\nax1.set_ylim([2, 45])\nax1.set_xlabel(\"Iteration\")\nax1.legend()#loc=2, prop = {'size': 10})\n```\n", "meta": {"hexsha": "584fc2b00d1bb427955834e2366988ba40c0df12", "size": 107897, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/FullQuantum_LDNNwithNoise_1.ipynb", "max_stars_repo_name": "18819F-Project/ModellingDynamicalSystem", "max_stars_repo_head_hexsha": "2610385e38c4cff7c9cbe25e1c6801a3de9eaf69", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/FullQuantum_LDNNwithNoise_1.ipynb", "max_issues_repo_name": "18819F-Project/ModellingDynamicalSystem", "max_issues_repo_head_hexsha": "2610385e38c4cff7c9cbe25e1c6801a3de9eaf69", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/FullQuantum_LDNNwithNoise_1.ipynb", "max_forks_repo_name": "18819F-Project/ModellingDynamicalSystem", "max_forks_repo_head_hexsha": "2610385e38c4cff7c9cbe25e1c6801a3de9eaf69", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 132.7146371464, "max_line_length": 24382, "alphanum_fraction": 0.8157502062, "converted": true, "num_tokens": 7002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3415824860330003, "lm_q2_score": 0.09138209688084911, "lm_q1q2_score": 0.031214523831468922}}
{"text": "# **Save this file as studentid1_studentid2_lab#.ipynb**\n(Your student-id is the number shown on your student card.)\n\nE.g. if you work with 3 people, the notebook should be named:\n12301230_3434343_1238938934_lab1.ipynb.\n\n**This will be parsed by a regexp, so please double check your filename.**\n\nBefore you turn this problem in, please make sure everything runs correctly. First, **restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart) and then **run all cells** (in the menubar, select Cell$\\rightarrow$Run All). Note, that **you are not allowed to use Google Colab**.\n\n**Make sure you fill in any place that says `YOUR CODE HERE` or \"YOUR ANSWER HERE\", as well as your names and email adresses below.**\n\n\n\n\n```python\nNAME = \"Radu Sibechi\"\nNAME2 = \"Nicu-Traian Vidrascu\"\nEMAIL = \"ntvidrascu@gmail.com\"\nEMAIL2 = \"radu.sibechi@yahoo.com\"\n\n```\n\n# Lab 3: Gaussian Processes and Support Vector Machines\n\n### Machine Learning 1, November 2018\n\nNotes on implementation:\n\n* You should write your code and answers in this IPython Notebook: http://ipython.org/notebook.html. If you have problems, please contact your teaching assistant.\n* Please write your answers right below the questions.\n* Among the first lines of your notebook should be \"%pylab inline\". This imports all required modules, and your plots will appear inline.\n* Refer to last week's lab notes, i.e. http://docs.scipy.org/doc/, if you are unsure about what function to use. There are different correct ways to implement each problem!\n* use the provided test boxes to check if your answers are correct\n\n\n```python\n%pylab inline\nplt.rcParams[\"figure.figsize\"] = [20,10]\n```\n\n    Populating the interactive namespace from numpy and matplotlib\n\n\n\n```python\n# This cell makes sure that you have all the necessary libraries installed\n\nimport sys\nimport platform\nfrom importlib.util import find_spec, module_from_spec\n\ndef check_newer_version(version_inst, version_nec):\n    version_inst_split = version_inst.split('.')\n    version_nec_split = version_nec.split('.')\n    for i in range(min(len(version_inst_split), len(version_nec_split))):\n        if int(version_nec_split[i]) > int(version_inst_split[i]):\n            return False\n        elif int(version_nec_split[i]) < int(version_inst_split[i]):\n            return True\n    return True\n        \n    \nmodule_list = [('jupyter', '1.0.0'), \n               ('matplotlib', '2.0.2'), \n               ('numpy', '1.13.1'), \n               ('python', '3.6.2'), \n               ('sklearn', '0.19.0'), \n               ('scipy', '0.19.1'), \n               ('nb_conda', '2.2.1')]\n\npackages_correct = True\npackages_errors = []\n\nfor module_name, version in module_list:\n    if module_name == 'scikit-learn':\n        module_name = 'sklearn'\n    if module_name == 'pyyaml':\n        module_name = 'yaml'\n    if 'python' in module_name:\n        python_version = platform.python_version()\n        if not check_newer_version(python_version, version):\n            packages_correct = False\n            error = f'Update {module_name} to version {version}. Current version is {python_version}.'\n            packages_errors.append(error) \n            print(error)\n    else:\n        spec = find_spec(module_name)\n        if spec is None:\n            packages_correct = False\n            error = f'Install {module_name} with version {version} or newer, it is required for this assignment!'\n            packages_errors.append(error) \n            print(error)\n        else:\n            x = __import__(module_name)\n            if hasattr(x, '__version__') and not check_newer_version(x.__version__, version):\n                packages_correct = False\n                error = f'Update {module_name} to version {version}. Current version is {x.__version__}.'\n                packages_errors.append(error) \n                print(error)\n\ntry:\n    from google.colab import drive\n    packages_correct = False\n    error = \"\"\"Please, don't use google colab!\nIt will make it much more complicated for us to check your homework as it merges all the cells into one.\"\"\"\n    packages_errors.append(error) \n    print(error)\nexcept:\n    pass\n\npackages_errors = '\\n'.join(packages_errors)\n```\n\n    Install nb_conda with version 2.2.1 or newer, it is required for this assignment!\n\n\n## Part 1: Gaussian Processes\n\nFor part 1 we will be refer to Bishop sections 6.4.2 and 6.4.3. You may also want to refer to Rasmussen's Gaussian Process text which is available online at http://www.gaussianprocess.org/gpml/chapters/ and especially to the project found at https://www.automaticstatistician.com/index/ by Ghahramani for some intuition in GP.  To understand Gaussian processes, it is highly recommended understand how marginal, partitioned Gaussian distributions can be converted into conditional Gaussian distributions.  This is covered in Bishop 2.3 and summarized in Eqns 2.94-2.98.\n$\\newcommand{\\bt}{\\mathbf{t}}$\n$\\newcommand{\\bx}{\\mathbf{x}}$\n$\\newcommand{\\by}{\\mathbf{y}}$\n$\\newcommand{\\bw}{\\mathbf{w}}$\n$\\newcommand{\\ba}{\\mathbf{a}}$\n\n### Periodic Data\n\nWe will use the same data generating function that we used previously for regression.\n\n\n```python\ndef true_mean_function(x):\n    return np.sin(2*pi*(x+1))\n\ndef add_noise(y, sigma):\n    return y + sigma*np.random.randn(len(y))\n\ndef generate_t(x, sigma):\n    return add_noise(true_mean_function(x), sigma)\n\n```\n\n\n```python\nsigma = 0.2\nbeta  = 1.0 / pow(sigma, 2)\nN_test = 100\n\nx_test = np.linspace(-1, 1, N_test) \nmu_test = np.zeros(N_test)\ny_test = true_mean_function(x_test)\nt_test = add_noise(y_test, sigma)\n\nplt.plot( x_test, y_test, 'b-', lw=2)\nplt.plot( x_test, t_test, 'go')\nplt.show()\n```\n\n### 1. Sampling from the Gaussian process prior (30 points)\nWe will implement Gaussian process regression using the kernel function in Bishop Eqn. 6.63.  \n\n#### 1.1 Why kernel function? (5 points)\n\nBefore implementing kernel function, it would be useful to understand why kernels are crucial for high dimensional data. Why are kernels useful when you are dealing with high dimensional data?\n\nYOUR ANSWER HERE\nKernels are usefull for making calculations in a lower dimension than the original one, thus they decrease complexity.\n\n#### 1.2 k_n_m( xn, xm, thetas ) (5 points)\nTo start, implement function `k_n_m(xn, xm, thetas)` that takes scalars $x_n$ and $x_m$, and a vector of $4$ thetas, and computes the kernel function Bishop Eqn. 6.63 (10 points).  NB: usually the kernel function will take $D$ by $1$ vectors, but since we are using a univariate problem, this makes things easier.\n\n\n```python\ndef k_n_m(xn, xm, thetas):\n    k = thetas[0]*np.exp(-thetas[1]/2*np.dot((xn-xm).T,(xn-xm)))+thetas[2]+thetas[3]*xn.dot(xm)\n    return k\n```\n\n\n```python\n# DO NOT REMOVE THIS CELL!\n# It contains hidden tests\n\n```\n\n#### 1.3 computeK( X1, X2, thetas ) (10 points)\nEqn 6.60 is the marginal distribution of mean output of $N$ data vectors: $p(\\mathbf{y}) = \\mathcal{N}(0, \\mathbf{K})$.  Notice that the expected mean function is $0$ at all locations, and that the covariance is a $N$ by $N$ kernel matrix $\\mathbf{K}$.  Write a function `computeK(x1, x2, thetas)`\nthat computes the kernel matrix. Use k_n_m as part of an inner loop (of course, there are more efficient ways of computing the kernel function making better use of vectorization, but that is not necessary) (5 points).  \n\n\n```python\ndef computeK(x1, x2, thetas):\n    if not type(x1) is np.ndarray or len(x1.shape)==1:\n        #the case when X has shape is Nx1\n        x1 = np.array(x1)\n        x2 = np.array(x2)\n        diff = x1[:,np.newaxis] - x2\n        x1 = np.array([x1]).T\n        x2 = np.array([x2]).T\n        diff_norm = diff*diff\n    else:\n        #the case when X has shape NxD\n        diff = x1[:,np.newaxis] - x2\n        diff_norm = sum(diff*diff,axis=-1)\n    \n    K = thetas[0]*np.exp(-thetas[1]/2*diff_norm)+thetas[2]+thetas[3]*np.dot(x1,x2.T)\n    return K\n```\n\n\n```python\n### Test your function\nx1 = [0, 1, 2]\nx2 = [1, 2, 3, 4]\nthetas = [1, 2, 3, 4]\nK = computeK(x1, x2, thetas)\n\n\nassert K.shape == (len(x1), len(x2)), \"the shape of K is incorrect\"\n\n```\n\n#### 1.4 Plot function samples (15 points)\nNow sample mean functions at the x_test locations for the theta values in Bishop Figure 6.5, make a figure with a 2 by 3 subplot and make sure the title reflects the theta values (make sure everything is legible).  In other words, sample $\\by_i \\sim \\mathcal{N}(0, \\mathbf{K}_{\\theta})$.  Make use of numpy.random.multivariate_normal().  On your plots include the expected value of $\\by$ with a dashed line and fill_between 2 standard deviations of the uncertainty due to $\\mathbf{K}$ (the diagonal of $\\mathbf{K}$ is the variance of the model uncertainty) (15 points).\n\n\n```python\n# YOUR CODE HERE\ndef plot_function_samples():\n    thetas = [[1,4,0,0],[9,4,0,0],[1,64,0,0],[1,25,0,0],[1,4,10,0],[1,4,0,5]]\n    num_cols = 3\n    num_rows = 2\n    for i,theta in enumerate(thetas):\n        ax = plt.subplot(num_rows, num_cols, i+1)\n        for _ in range(1):\n            K = computeK(x_test,x_test,theta)\n            plt.plot(x_test,np.random.multivariate_normal([0]*100,K))\n\n            plt.errorbar(x_test,y_test,2*np.sqrt(K[range(len(x_test)),range(len(x_test))]))\n        plt.title(theta)\n    plt.tight_layout()\n    plt.show()\n\nplot_function_samples()\n\n```\n\n### 2. Predictive distribution (35 points)\nSo far we have sampled mean functions from the prior.  We can draw actual data $\\bt$ two ways.  The first way is generatively, by first sampling $\\by | \\mathbf{K}$, then sampling $\\bt | \\by, \\beta$ (Eqns 6.60 followed by 6.59).  The second way is to integrate over $\\by$ (the mean draw) and directly sample $\\bt | \\mathbf{K}, \\beta$ using Eqn 6.61.    This is the generative process for $\\bt$.  Note that we have not specified a distribution over inputs $\\bx$;  this is because Gaussian processes are conditional models.  Because of this we are free to generate locations $\\bx$ when playing around with the GP; obviously a dataset will give us input-output pairs.\n\nOnce we have data, we are interested in the predictive distribution (note: the prior is the predictive distribution when there is no data).  Consider the joint distribution for $N+1$ targets, given by Eqn 6.64.  Its covariance matrix is composed of block components $C_N$, $\\mathbf{k}$, and $c$.  The covariance matrix $C_N$ for $\\bt_N$ is $C_N = \\mathbf{K}_N + \\beta^{-1}\\mathbf{I}_N$.  We have just made explicit the size $N$ of the matrix; $N$ is the number of training points.  The kernel vector $\\mathbf{k}$ is a $N$ by $1$ vector of kernel function evaluations between the training input data and the test input vector.  The scalar $c$ is a kernel evaluation at the test input.\n\n#### 2.1 gp_predictive_distribution(...) (10 points)\nWrite a function `gp_predictive_distribution(x_train, t_train, x_test, theta, beta, C=None)` that computes  Eqns 6.66 and 6.67, except allow for an arbitrary number of test points (not just one) and now the kernel matrix is for training data.  By having C as an optional parameter, we can avoid computing it more than once (for this problem it is unimportant, but for real problems this is an issue).  The function should compute $\\mathbf{C}$, $\\mathbf{k}$, and return the mean, variance and $\\mathbf{C}$.  Do not forget: the computeK function computes $\\mathbf{K}$, not $\\mathbf{C}$.(10 points)\n\n\n```python\ndef gp_predictive_distribution(x_train, t_train, x_test, theta, beta, C=None):\n    K = computeK(x_train,x_train,theta)\n    if C is None:\n        C = K+1/beta*np.eye(K.shape[0])\n    c = computeK(x_test,x_test,theta) + 1/beta\n    k = computeK(x_train,x_test,theta)\n    kTC1 = np.dot(k.T,np.linalg.inv(C))\n    mean_test = kTC1.dot(t_train)\n    covar_test = c - kTC1.dot(k)\n    \n    return mean_test, covar_test, C\n```\n\n\n```python\n### Test your function\nN = 2\ntrain_x = np.linspace(-1, 1, N)\ntrain_t = 2*train_x\ntest_N = 3\ntest_x = np.linspace(-1, 1, test_N) \ntheta = [1, 2, 3, 4]\nbeta = 25\ntest_mean, test_covar, C = gp_predictive_distribution(train_x, train_t, test_x, theta, beta, C=None)\n\n\nassert test_mean.shape == (test_N,), \"the shape of mean is incorrect\"\nassert test_covar.shape == (test_N, test_N), \"the shape of var is incorrect\"\nassert C.shape == (N, N), \"the shape of C is incorrect\"\n\nC_in = np.array([[0.804, -0.098168436], [-0.098168436, 0.804]])\n_, _, C_out = gp_predictive_distribution(train_x, train_t, test_x, theta, beta, C=C_in)\n\nassert np.allclose(C_in, C_out), \"C is not reused!\"\n\n```\n\n#### 2.2 gp_log_likelihood(...) (10 points)\nTo learn the hyperparameters, we would need to compute the log-likelihood of the of the training data.  Implicitly, this is conditioned on the value setting for $\\mathbf{\\theta}$.  Write a function `gp_log_likelihood(x_train, t_train, theta, C=None, invC=None, beta=None)`, where C and invC can be stored and reused. It should return the log-likelihood, `C` and `invC`  (10 points)\n\n\n```python\ndef gp_log_likelihood(x_train, t_train, theta, beta, C=None, invC=None):\n    N = t_train.shape[0]\n    if C is None or invC is None:\n        K = computeK(x_train,x_train,theta)\n        \n        if C is None:\n            C = K+1/beta*np.eye(K.shape[0])\n        \n        if invC is None:\n            invC = np.linalg.inv(C)\n    \n    lp = -1/2*np.log(np.abs(np.sum((C))))- 1/2*t_train.T.dot(invC).dot(t_train) - N/2*np.log(2*np.pi)\n    \n    \n    return lp, C, invC\n```\n\n\n```python\n### Test your function\nN = 2\ntrain_x = np.linspace(-1, 1, N)\ntrain_t = 2 * train_x\ntheta = [1, 2, 3, 4]\nbeta = 25\nlp, C, invC = gp_log_likelihood(train_x, train_t, theta, beta, C=None, invC=None)\n\nassert lp < 0, \"the log-likelihood should be smaller than 0\"\nassert C.shape == (N, N), \"the shape of var is incorrect\"\nassert invC.shape == (N, N), \"the shape of C is incorrect\"\n\nC_in = np.array([[0.804, -0.098168436], [-0.098168436, 0.804]])\n_, C_out, _ = gp_log_likelihood(train_x, train_t, theta, beta, C=C_in, invC=None)\n\nassert np.allclose(C_in, C_out), \"C is not reused!\"\n\ninvC_in = np.array([[1.26260453, 0.15416407], [0.15416407, 1.26260453]])\n_, _, invC_out = gp_log_likelihood(train_x, train_t, theta, beta, C=None, invC=invC_in)\n\nassert np.allclose(invC_in, invC_out), \"invC is not reused!\"\n\n```\n\n#### 2.3 Plotting (10 points)\nRepeat the 6 plots above, but this time conditioned on the training points.  Use the periodic data generator to create 2 training points where x is sampled uniformly between $-1$ and $1$.  For these plots, feel free to use the provided function \"gp_plot\".  Make sure you put the parameters in the title and this time also the log-likelihood. Try to understand the two types of uncertainty!  If you do not use `gp_plot(...)`, please add a fill between for the model and target noise. (10 points)\n\n\n```python\ndef gp_plot( x_test, y_test, mean_test, covar_test, x_train, t_train, theta, beta ):\n    # x_test: \n    # y_test:    the true function at x_test\n    # mean_test: predictive mean at x_test\n    # var_test:  predictive covariance at x_test \n    # t_train:   the training values\n    # theta:     the kernel parameters\n    # beta:      the precision (known)\n    \n    # the reason for the manipulation is to allow plots separating model and data stddevs.\n    std_total = np.sqrt(np.diag(covar_test))       # includes all uncertainty, model and target noise \n    std_model = np.sqrt(std_total**2 - 1.0/beta) # remove data noise to get model uncertainty in stddev\n    std_combo = std_model + np.sqrt(1.0/beta)    # add stddev (note: not the same as full)\n    \n    plt.plot(x_test, y_test, 'b', lw=3)\n    plt.plot(x_test, mean_test, 'k--', lw=2)\n    plt.fill_between(x_test, mean_test+2*std_combo,mean_test-2*std_combo, color='k', alpha=0.25)\n    plt.fill_between(x_test, mean_test+2*std_model,mean_test-2*std_model, color='r', alpha=0.25)\n    plt.plot(x_train, t_train, 'ro', ms=10)\n    \n```\n\n\n```python\ndef plot_function_samples2(thetas = None, sigma = None, beta = None, N_train = None, N_test = None):\n    if thetas is None:\n        thetas = [[1,4,0,0],[9,4,0,0],[1,64,0,0],[1,25,0,0],[1,4,10,0],[1,4,0,5]]\n    if sigma is None:\n        sigma = 0.2\n    if beta is None:\n        beta = 1.0 / pow(sigma, 2)\n    if N_train is None:\n        N_train = 2\n    if N_test is None:\n        N_test = 100\n    \n    x = np.random.uniform(-1,1,N_train)\n    t_train = generate_t(x,sigma)\n\n    x_test = np.linspace(-1, 1, N_test) \n    mu_test = np.zeros(N_test)\n    y_test = true_mean_function(x_test)\n    t_test = add_noise(y_test, sigma)\n    \n    num_cols = 3\n    num_rows = 2\n    for i,theta in enumerate(thetas):\n        ax = plt.subplot(num_rows, num_cols, i+1)\n        mean, var, C = gp_predictive_distribution(x,t_train,x_test,theta,beta)\n        gp_plot(x_test,y_test,mean,var,x,t_train,theta,beta)\n        lp, _, _ = gp_log_likelihood(x,t_train,theta,beta)\n        plt.title(str(theta) + ' ' + str(lp))\n    plt.tight_layout()\n    plt.show()\nplot_function_samples2(N_train = 100)\n```\n\n#### 2.4 More plotting (5 points)\nRepeat the 6 plots above, but this time conditioned a new set of 10 training points. (5 points)\n\n\n```python\nplot_function_samples2(N_train = 10)\n```\n\n## Part 2: Support Vector Machines (45 points)\nAs seen in Part 1: Gaussian Processes, one of the significant limitations of many such algorithms is that the kernel function $k(\\bx_n , \\bx_m)$ must be evaluated for all possible pairs $\\bx_n$ and $\\bx_m$ of training points, which can be computationally infeasible during training and can lead to excessive computation times when making predictions for new data points.\nIn Part 2: Support Vector Machines, we shall look at kernel-based algorithms that have sparse solutions, so that predictions for new inputs depend only on the kernel function evaluated at a subset of the training data points. We are using the same notation as in Bishop chapter 7.\n\n### 2.1 Generating a linearly separable dataset (15 points)\na) (5 points) First of all, we are going to create our own 2D toy dataset $X$. The dataset will consists of two i.i.d. subsets $X_1$ and $X_2$, each of the subsets will be sampled from a multivariate Gaussian distribution,\n\n\\begin{align}\nX_1 \\sim &\\mathcal{N}(\\mu_1, \\Sigma_1)\\\\\n&\\text{ and }\\\\\nX_2 \\sim &\\mathcal{N}(\\mu_2, \\Sigma_2).\n\\end{align}\n\nIn the following, $X_1$ will have $N_1=20$ samples and a mean $\\mu_1=(1,1)$. $X_2$ will have $N_2=30$ samples and a mean $\\mu_2=(3,3)$.\n\nPlot the two subsets in one figure, choose two colors to indicate which sample belongs to which subset. In addition you should choose, $\\Sigma_1$ and $\\Sigma_2$ in a way that the two subsets become linearly separable. (Hint: Which form has the covariance matrix for a i.i.d. dataset?)\n\n\n```python\ndef generate_XX(N1 = None, N2 = None):\n    if N1 is None:\n        N1 = 20\n        N2 = 30\n    X1 = np.random.multivariate_normal([1,1],[[0.1, 0],[0, 0.1]], N1)\n    X2 = np.random.multivariate_normal([3,3],[[0.2, 0],[0, 0.2]], N2)\n    return X1, X2\n\ndef plot_XX(X1,X2):\n    plt.plot(X1[:,0],X1[:,1],'go')\n    plt.plot(X2[:,0],X2[:,1],'bo')\n    \nX1, X2 = generate_XX()\nplot_XX(X1, X2)\nN1 = X1.shape[0]\nN2 = X2.shape[0]\n```\n\nb) (10 points) In the next step we will combine the two datasets X_1, X_2 and generate a vector `t` containing the labels. Write a function `create_X_and_t(X1, X2)` it should return the combined data set X and the corresponding target vector t.\n\n\n```python\ndef create_X_and_t(X1, X2):\n    t1 = np.ones((X1.shape[0],))\n    t2 = -np.ones((X2.shape[0]),)\n    t = np.concatenate((t1,t2))\n    X = np.vstack((X1,X2))\n    return X, t\n```\n\n\n```python\n### Test your function\ndim = 2\nN1_test = 3\nN2_test = 4\nX1_test = np.arange(6).reshape((N1_test, dim))\nX2_test = np.arange(8).reshape((N2_test, dim))\nX_test, t_test = create_X_and_t(X1_test, X2_test)\n\n\nassert X_test.shape == (N1_test + N2_test, dim), \"the shape of X is incorrect\"\nassert t_test.shape == (N1_test + N2_test,), \"the shape of t is incorrect\"\n\n```\n\n### 2.2 Finding the support vectors (15 points)\nFinally we going to use a SVM to obtain the decision boundary for which the margin is maximized. We have to solve the optimization problem\n\n\\begin{align}\n\\arg \\min_{\\bw, b} \\frac{1}{2} \\lVert \\bw \\rVert^2,\n\\end{align}\n\nsubject to the constraints\n\n\\begin{align}\nt_n(\\bw^T \\phi(\\bx_n) + b) \\geq 1, n = 1,...,N.\n\\end{align}\n\nIn order to solve this constrained optimization problem, we introduce Lagrange multipliers $a_n \\geq 0$. We obtain the dual\nrepresentation of the maximum margin problem in which we maximize\n\n\\begin{align}\n\\sum_{n=1}^N a_n - \\frac{1}{2}\\sum_{n=1}^N\\sum_{m=1}^N a_n a_m t_n t_m k(\\bx_n, \\bx_m),\n\\end{align}\n\nwith respect to a subject to the constraints\n\n\\begin{align}\na_n &\\geq 0, n=1,...,N,\\\\\n\\sum_{n=1}^N a_n t_n &= 0.\n\\end{align}\n\nThis takes the form of a quadratic programming problem in which we optimize a quadratic function of $\\mathbf{a}$, subject to a set of inequality constraints.\n\n\n\na) (5 points) In this example we will use a linear kernel $k(\\bx, \\bx') = \\bx^T\\bx'$. Write a function `computeK(X)` that computes the kernel matrix $K$ for the 2D dataset $X$.\n\n\n```python\ndef computeK(X):\n    K = np.dot(X,X.T)\n    \n    return K\n```\n\n\n```python\ndim = 2\nN_test = 3\nX_test = np.arange(2, 8).reshape((N_test, dim))\nK_test = computeK(X_test)\n\n\nassert K_test.shape == (N_test, N_test)\n\n```\n\nNext, we will rewrite the dual representation so that we can make use of computationally efficient vector-matrix multiplication. The objective becomes\n\n\\begin{align}\n\\min_{\\ba} \\frac{1}{2} \\ba^T K' \\ba - 1^T\\ba,\n\\end{align}\n\nsubject to the constraints\n\n\\begin{align}\na_n &\\geq 0, n=1,...,N,\\\\\n\\bt^T\\ba &= 0.\n\\end{align}\n\nWhere\n\\begin{align}\nK'_{nm} = t_n t_m k(\\bx_n, \\bx_m),\n\\end{align}\nand in the special case of a linear kernel function,\n\\begin{align}\nK'_{nm} = t_n t_m k(\\bx_n, \\bx_m) = k(t_n \\bx_n, t_m \\bx_m).\n\\end{align}\n\nTo solve the quadratic programming problem we will use a python module called cvxopt. You first have to install the module in your virtual environment (you have to activate it first), using the following command:\n\n`conda install -c anaconda cvxopt`\n\nThe quadratic programming solver can be called as\n\n`cvxopt.solvers.qp(P, q[, G, h[, A, b[, solver[, initvals]]]])`\n\nThis solves the following problem,\n\n\\begin{align}\n\\min_{\\bx} \\frac{1}{2} \\bx^T P \\bx + q^T\\bx,\n\\end{align}\n\nsubject to the constraints,\n\n\\begin{align}\nG\\bx &\\leq h,\\\\\nA\\bx &= b.\n\\end{align}\n\nAll we need to do is to map our formulation to the cvxopt interface.\n\nb) (10 points) Write a function `compute_multipliers(X, t)` that solves the quadratic programming problem using the cvxopt module and returns the lagrangian multiplier for every sample in the dataset. \n\n\n```python\nimport cvxopt\n\ndef compute_multipliers(X, t):\n    K = computeK(X*t[:,np.newaxis])\n    q = cvxopt.matrix(-1*np.ones((X.shape[0]),dtype=np.double))\n    A = cvxopt.matrix(t[:,np.newaxis].T.astype(np.double))\n    b = cvxopt.matrix(np.array([0]).astype(np.double))\n    G = cvxopt.matrix(-1*np.eye(X.shape[0],X.shape[0],dtype=np.double))\n    h = cvxopt.matrix(np.zeros_like(t.astype(np.double)))\n    P = cvxopt.matrix(K.astype(np.double))\n    \n    sol = cvxopt.solvers.qp(P, q, G, h, A, b)\n    a = np.array(sol['x'])\n    return a\n```\n\n\n```python\n### Test your function\ndim = 2\nN_test = 3\nX_test = np.arange(2, 8).reshape((N_test, dim))\nt_test = np.array([-1., 1., 1.])\na_test = compute_multipliers(X_test, t_test)\n\n\nassert a_test.shape == (N_test, 1)\n\n```\n\n### 2.3 Plot support vectors (5 points)\nNow that we have obtained the lagrangian multipliers $\\ba$, we use them to find our support vectors. Repeat the plot from 2.1, this time use a third color to indicate which samples are the support vectors.\n\n\n```python\ndef plot_X_SV(X, N1, N2, a):\n    G = -1*np.eye(X.shape[0],X.shape[0],dtype=np.double)\n    h = np.zeros_like(X.shape[0]).astype(np.double)\n    plt.plot(X[0:N1,0],X[0:N1,1],'co')\n    plt.plot(X[N1:N2,0],X[N1:N2,1],'yo')\n    srt = argsort(a[:,0])\n    \n    for arg in srt:\n        if a[arg]>1e-5:\n            #plt.plot(,facecolors='none', edgecolors='r')\n            plt.scatter(X[arg,0],X[arg,1], s=240, facecolors='none', edgecolors='purple')\n\nX, t = create_X_and_t(X1, X2)\na = compute_multipliers(X, t)\nsrt = argsort(a[:,0])\nsupports = []\nfor i, val in enumerate(a):\n    if val>1e-5:\n        supports.append(i)\n\nplot_X_SV(X, N1, N2, a)\n```\n\n### 2.4 Plot the decision boundary (10 Points)\nThe decision boundary is fully specified by a (usually very small) subset of training samples, the support vectors. Make use of\n\n\\begin{align}\n\\bw &= \\sum_{n=1}^N a_n t_n \\mathbf{\\phi}(\\bx_n)\\\\\nb &= \\frac{1}{N_S}\\sum_{n \\in S} (t_n - \\sum_{m \\in S} a_m t_m k(\\bx_n, \\bx_m)),\n\\end{align}\n\nwhere $S$ denotes the set of indices of the support vectors, to calculate the slope and intercept of the decision boundary. Generate a last plot that contains the two subsets, support vectors and decision boundary.\n\n\n```python\ndef plot_X_SV_DB(X, a):\n    G = -1*np.eye(X.shape[0],X.shape[0],dtype=np.double)\n    h = np.zeros_like(X.shape[0]).astype(np.double)\n    plt.plot(X[0:N1,0],X[0:N1,1],'co')\n    plt.plot(X[N1:N2,0],X[N1:N2,1],'yo')\n    srt = argsort(a[:,0])\n    \n    for arg in srt:\n        if a[arg]>1e-5:\n            #plt.plot(,facecolors='none', edgecolors='r')\n            plt.scatter(X[arg,0],X[arg,1], s=240, facecolors='none', edgecolors='purple')\n        \n        \n        \n    w = np.sum ( a * t[:, np.newaxis] * X, axis = 0 )\n    \n    b = t[supports] - np.dot(X[supports], w)\n    bias = b[0]\n    slope = -w[0] / w[1]\n    intercept = -bias / w[1]\n    x = np.arange(0, 6)\n    \n    margin = X[supports][1][0] * slope + intercept - X[supports][1][1]\n    plt.plot(x, x * slope + intercept, 'r-')\n    plt.plot(x, x * slope + intercept + margin, 'b-')\n    plt.plot(x, x * slope + intercept - margin, 'b-')\n    \n    \n\nplot_X_SV_DB(X,a)\n```\n", "meta": {"hexsha": "5894ca31c9282891ff6bd76f9a57a1e792e51923", "size": 165238, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lab3/12280046_11808527_lab3.ipynb", "max_stars_repo_name": "mhashas/ml1labs", "max_stars_repo_head_hexsha": "0596e27bca067e4b06df4e2062f7139ab7860089", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lab3/12280046_11808527_lab3.ipynb", "max_issues_repo_name": "mhashas/ml1labs", "max_issues_repo_head_hexsha": "0596e27bca067e4b06df4e2062f7139ab7860089", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-05T15:54:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-05T15:54:56.000Z", "max_forks_repo_path": "lab3/12280046_11808527_lab3.ipynb", "max_forks_repo_name": "mhashas/ml1labs", "max_forks_repo_head_hexsha": "0596e27bca067e4b06df4e2062f7139ab7860089", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 109.9387890885, "max_line_length": 33076, "alphanum_fraction": 0.8439644634, "converted": true, "num_tokens": 7578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17106119167858436, "lm_q2_score": 0.18242553047372242, "lm_q1q2_score": 0.031205928635432863}}
{"text": "```python\nfrom IPython.core.display import HTML\ndef css_styling():\n    styles = open(\"./styles/custom.css\", \"r\").read()\n    return HTML(styles)\ncss_styling()\n```\n\n\n\n\n<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:100,300,400,500,700,800,900,100italic,300italic,400italic,500italic,700italic,800italic,900italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Arvo:400,700,400italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=PT+Mono' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Shadows+Into+Light' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Philosopher:400,700,400italic,700italic' rel='stylesheet' type='text/css'>\n\n<style>\n\n@font-face {\n    font-family: \"Computer Modern\";\n    src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');\n}\n\n#notebook_panel { /* main background */\n    background: #888;\n    color: #f6f6f6;\n}\n\ndiv #notebook { /* centre the content */\n    background: #fff;\n    color: #333;\n    width: 1200px;\n    margin: auto;\n    padding-left: 1em;\n    padding-right: 1em;\n    padding-top: 2ex;\n    overflow-x: auto;\n}\n\n#notebook li { /* More space between bullet points */\nmargin-top:0.8em;\n}\n\ndiv.cell { /* set cell width to about 80 chars */\n    width: 900px;\n}\n\ndiv.cell.border-box-sizing.code_cell.running { \n    /* draw border around running cells */\n    border: 3px solid #111;\n}\n\n\nh1 {\n    font-family: 'Philosopher', sans-serif;\n}\nh2 {\n    font-family: 'Philosopher', serif;\n}\nh3{\n    font-family: 'Philosopher', serif;\n    font-style: 'italic';\n    margin-top:12px;\n    margin-bottom: 3px;\n}\nh4{\n    font-family: 'Philosopher', serif;\n}\nh5 {\n    font-family: 'Alegreya Sans', sans-serif;\n}\t\nh6 {\n    font-family: 'PT Mono', sans-serif;\n}\t\n\ndiv.text_cell_render{\n    font-family: 'Arvo' sans-serif;\n    line-height: 130%;\n    font-size: 115%;\n    width:800px;\n    margin-left:auto;\n    margin-right:auto;\n}\n\n.CodeMirror{\n        font-family: \"PT Mono\";\n                    font-size: 100%;\n            }\n\n.text_cell_render h1 {\n    font-weight: 400;\n    font-size: 64pt;\n    line-height: 100%;\n    color: rgb(12,85,97);\n    margin-bottom: 0.1em;\n    margin-top: 0.1em;\n    display: block;\n}\t\n.text_cell_render h2 {\n    font-weight: 700;\n    font-size: 24pt;\n    line-height: 100%;\n    color: rgb(171,165,131);\n    margin-bottom: 0.1em;\n    margin-top: 0.1em;\n    display: block;\n}\t\n\n.text_cell_render h3 {\n    font-style: italic;\n    color: rgb(95,92,72);\n}\n\n.text_cell_render h5 {\n    font-weight: 300;\n    font-size: 16pt;\n    color: grey;\n    font-style: italic;\n    margin-bottom: .1em;\n    margin-top: 0.1em;\n    display: block;\n}\n\n.text_cell_render h6 {\n    font-weight: 300;\n    font-size: 10pt;\n    color: grey;\n    margin-bottom: 1px;\n    margin-top: 1px;\n}\ndiv.cell.code_cell {  /* Group area containing both code and output */\nbackground-color: rgba(171,165,131,0.3); \nborder-radius: 10px; /* rounded borders */\npadding: 1em;\n}\n\n</style>\n\n\n\n\n\n\n# Approximate solutions to the Riemann Problem\n\n## Solutions in practice\n\nSolutions to the Riemann problem are mainly used in two contexts:\n\n1. As reference solutions against which a numerical method is benchmarked, or\n2. As part of a numerical method, such as a high resolution shock capturing method, where the flux between two numerical cells is required.\n\nIn the first case, accuracy is paramount and the complete solution (all wave speeds, and all intermediate states) is required. In the second case only one thing is required: the flux ${\\bf f}^*$ between the cells, which is the flux on the characteristic line $\\xi = x / t = 0$.\n\nIn this second case, the numerical method will have to repeatedly solve the Riemann problem. In a general problem, the solution may be needed tens of times *per cell, per timestep*, leading to millions (or more!) solutions in a simulation. The speed of the solution is then extremely important, and approximate solutions are often used.\n\n## Roe-type solutions\n\nThe most obvious simplification is to reduce the nonlinear problem\n\n\\begin{equation}\n  \\partial_t {\\bf q} + \\partial_x {\\bf f}({\\bf q}) = {\\bf 0}\n\\end{equation}\n\nto the *linear* problem\n\n\\begin{equation}\n  \\partial_t {\\bf q} + A \\partial_x {\\bf q} = {\\bf 0},\n\\end{equation}\n\nwhere $A$ is a *constant* matrix that approximates the Jacobian $\\partial {\\bf f} / \\partial {\\bf q}$. We can then solve the linear problem exactly (e.g. by diagonalising the matrix and solving the resulting uncoupled advection equations), to find\n\n\\begin{align}\n  {\\bf q}(x, t) & = {\\bf q}_l + \\sum_{p: \\lambda^{(p)} < \\tfrac{x}{t}} \\left\\{ {\\bf l}^{(p)} \\cdot \\left( {\\bf q}_r - {\\bf q}_l \\right) \\right\\} {\\bf r}^{(p)}, \\\\\n   & = {\\bf q}_r - \\sum_{p: \\lambda^{(p)} > \\tfrac{x}{t}} \\left\\{ {\\bf l}^{(p)} \\cdot \\left( {\\bf q}_r - {\\bf q}_l \\right) \\right\\} {\\bf r}^{(p)}, \\\\\n   & = \\frac{1}{2} \\left( {\\bf q}_l + {\\bf q}_r \\right) + \\sum_{p: \\lambda^{(p)} < \\tfrac{x}{t}} \\left\\{ {\\bf l}^{(p)} \\cdot \\left( {\\bf q}_r - {\\bf q}_l \\right) \\right\\} {\\bf r}^{(p)} - \\sum_{p: \\lambda^{(p)} > \\tfrac{x}{t}} \\left\\{ {\\bf l}^{(p)} \\cdot \\left( {\\bf q}_r - {\\bf q}_l \\right) \\right\\} {\\bf r}^{(p)}.\n\\end{align}\n\nwhere $\\lambda^{(p)}, {\\bf r}^{(p)},$ and ${\\bf l}^{(p)}$ are the eigenvalues and the (right and left respectively) eigenvectors of $A$, ordered such that $\\lambda^{(1)} \\le \\dots \\le \\lambda^{(N)}$ as usual. All three solutions are equivalent; the last is typically used.\n\nGiven this complete solution, it is easily evaluated along $x = 0$, and the flux calculated from the result.\n\nAn even greater shortcut can be found by noting that we are approximating ${\\bf f} = A {\\bf q}$. Therefore the standard form is to write\n\n\\begin{equation}\n  {\\bf f}^* = \\frac{1}{2} \\left( {\\bf f}_l + {\\bf f}_r \\right) + \\sum_{p} \\left| \\lambda^{(p)} \\right| \\left\\{ {\\bf l}^{(p)} \\cdot \\left( {\\bf q}_r - {\\bf q}_l \\right) \\right\\} {\\bf r}^{(p)},\n\\end{equation}\n\nwhere now we are summing over all eigenvalues and eigenvectors. It should be noted that ${\\bf f}^* \\ne {\\bf f}({\\bf q}^*)$ in general, as the calculation of ${\\bf f}^*$ relied on an approximation to the flux.\n\nIn order to complete this specification of the solver, we only need to say how $A$ is defined. Roe gave the suggestion that\n\n\\begin{equation}\n  A = A({\\bf q}_{\\textrm{Roe}}) = \\left. \\frac{\\partial {\\bf f}}{\\partial {\\bf q}} \\right|_{{\\bf q}_{\\textrm{Roe}}},\n\\end{equation}\n\nwhere the *Roe average* ${\\bf q}_{\\textrm{Roe}}$ satisfies\n\n1. $A({\\bf q}_{\\textrm{Roe}}) \\left( {\\bf q}_r - {\\bf q}_l \\right) = {\\bf f}_r - {\\bf f}_l$,\n2. $A({\\bf q}_{\\textrm{Roe}})$ is diagonalizable with real eigenvalues, and\n3. $A({\\bf q}_{\\textrm{Roe}}) \\to \\partial {\\bf f} / \\partial {\\bf q}$ smoothly as ${\\bf q}_{\\textrm{Roe}} \\to {\\bf q}$.\n\nIt is *possible* to construct the Roe average for many systems (such as the Euler equations, and the relativistic Euler equations). However, a simple arithmetic average is often nearly as good - in the sense that the algorithm will fail only slightly more often than the algorithm with the full Roe average!\n\nThe problem with Roe type solvers is that it approximates all waves as discontinuities. This leads to inaccuracies near rarefactions, and these can be catastrophically bad when the rarefaction fan crosses $\\xi = 0$ (a *sonic rarefaction*). It is possible to detect when these problems will occur (e.g. by looking at when $\\lambda^{(p)}$ changes sign between the left and right states) and change the approximation at this point, often known as an *entropy fix*. More systematic and complex methods that extend the Roe approach whilst avoiding this problem include the *Marquina* solver.\n\n## HLL-type solutions\n\nAn alternative type of method simplifies the wave structure even more, by simplifying the number of waves. HLL (for Harten, Lax and van Leer) type solutions assume that\n\n1. there are two waves, both discontinuities, separating a constant central state in the solution, and\n2. the waves propagate at the (known) speeds $\\xi_{(\\pm)}$.\n\nFrom these assumptions, and the Rankine-Hugoniot conditions, we have the two equations\n\n\\begin{align}\n  \\xi_{(-)} \\left[ {\\bf q}_m - {\\bf q}_l \\right] & = {\\bf f}_m - {\\bf f}_l, \\\\\n  \\xi_{(+)} \\left[ {\\bf q}_r - {\\bf q}_m \\right] & = {\\bf f}_r - {\\bf f}_m.\n\\end{align}\n\nThese are immediately solved to give\n\n\\begin{align}\n  {\\bf q}_m & = \\frac{\\xi_{(+)} {\\bf q}_r - \\xi_{(-)} {\\bf q}_l - {\\bf f}_r + {\\bf f}_l}{\\xi_{(+)} - \\xi_{(-)}}, \\\\\n  {\\bf f}_m & = \\frac{\\hat{\\xi}_{(+)} {\\bf f}_l - \\hat{\\xi}_{(-)} {\\bf f}_r + \\hat{\\xi}_{(+)} \\hat{\\xi}_{(-)} \\left( {\\bf q}_r - {\\bf q}_r \\right)}{\\hat{\\xi}_{(+)} - \\hat{\\xi}_{(-)}},\n\\end{align}\n\nwhere\n\n\\begin{equation}\n  \\hat{\\xi}_{(-)} = \\min(0, \\xi_{(-)}), \\qquad \\hat{\\xi}_{(+)} = \\max(0, \\xi_{(+)}).\n\\end{equation}\n\nAgain it should be noted that, in general, ${\\bf f}_m \\ne {\\bf f}({\\bf q}_m)$.\n\nWe still need some way to compute the wave speeds $\\xi_{(\\pm)}$. The simplest method is to make them as large as possible, compatible with stability. This means (via the CFL condition) setting\n\n\\begin{equation}\n  -\\xi_{(-)} = \\xi_{(+)} = \\frac{\\Delta x}{\\Delta t}\n\\end{equation}\n\nwhich implies that (as the central state is now guaranteed to include the origin, as the waves have different signs)\n\n\\begin{equation}\n  {\\bf f}^* = \\frac{1}{2} \\left( {\\bf f}_l + {\\bf f}_r + \\frac{\\Delta x}{\\Delta t} \\left[ {\\bf q}_l - {\\bf q}_r \\right] \\right).\n\\end{equation}\n\nThis is the *Lax-Friedrichs* flux, as [used in HyperPython](https://github.com/ketch/HyperPython). We can also easily see how the *local* Lax-Friedrichs method, [used in lesson 3 of HyperPython](http://nbviewer.ipython.org/github/ketch/HyperPython/blob/master/Lesson_03_High-resolution_methods.ipynb), comes about: simply choose\n\n\\begin{equation}\n  -\\xi_{(-)} = \\xi_{(+)} = \\alpha = \\min \\left( \\left| \\lambda \\left( {\\bf q}_l \\right) \\right|, \\left| \\lambda \\left( {\\bf q}_r \\right) \\right| \\right)\n\\end{equation}\n\nto get\n\n\\begin{equation}\n  {\\bf f}^* = \\frac{1}{2} \\left( {\\bf f}_l + {\\bf f}_r + \\alpha \\left[ {\\bf q}_l - {\\bf q}_r \\right] \\right).\n\\end{equation}\n\nHLL type methods are straightforward to use but typically do not capture linear waves, such as the contact wave in the Euler equations, well. Extending the HLL method by including more waves is possible (see the *HLLC* method in Toro's book as an example), but rapidly increases the complexity of the solver.\n", "meta": {"hexsha": "c5b93fc47716f10b30b5551f826daca9e4008314", "size": 16297, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lesson_05_Approximate_Solvers.ipynb", "max_stars_repo_name": "IanHawke/RiemannPython", "max_stars_repo_head_hexsha": "57d6e372861a9c89b15755fb1d6ff9ea8116f6e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2015-08-24T01:24:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T18:26:24.000Z", "max_issues_repo_path": "Lesson_05_Approximate_Solvers.ipynb", "max_issues_repo_name": "IanHawke/RiemannPython", "max_issues_repo_head_hexsha": "57d6e372861a9c89b15755fb1d6ff9ea8116f6e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lesson_05_Approximate_Solvers.ipynb", "max_forks_repo_name": "IanHawke/RiemannPython", "max_forks_repo_head_hexsha": "57d6e372861a9c89b15755fb1d6ff9ea8116f6e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-07-31T17:41:21.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-11T13:50:22.000Z", "avg_line_length": 40.2395061728, "max_line_length": 594, "alphanum_fraction": 0.5134073756, "converted": true, "num_tokens": 3251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16238004477370327, "lm_q2_score": 0.19193278182505782, "lm_q1q2_score": 0.03116605370629431}}
{"text": "```python\nfrom skimage import io\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n# https://directory.eoportal.org/web/eoportal/satellite-missions/c-missions/copernicus-sentinel-2\nurl=\"https://directory.eoportal.org/documents/163813/4091221/Sentinel2_Auto98.jpeg\"\nimage = io.imread(url)\nplt.imshow(image)\nplt.title(\"Peruvian mountain scene, 14 July 2017, Sentinel-2\\n (credit: ESA, processed by ESA, CC BY-SA 3.0 IGO)\")\nplt.show()\n```\n\n# Using equation with LaTeX notation in a markdown cell\n\nThe well known Pythagorean theorem $x^2 + y^2 = z^2$ was \nproved to be invalid for other exponents. \nMeaning the next equation has no integer solutions:\n\n\\begin{equation}\n x^n + y^n = z^n \n\\end{equation}\n\n\n```python\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Data for plotting\nt = np.arange(0.0, 2.0, 0.01)\ns = 1 + np.sin(2 * np.pi * t)\n\nfig, ax = plt.subplots()\nax.plot(t, s)\n\nax.set(xlabel='time (s)', ylabel='voltage (mV)',\n       title='About as simple as it gets, folks')\nax.grid()\n\nfig.savefig(\"test.png\")\nplt.show()\n```\n\n\n```python\n# !conda list\n```\n\n# Introduction\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "a343c660adf2672de486f68b0603ed07d652711b", "size": 303481, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "example.ipynb", "max_stars_repo_name": "hannahberg/researchBazaar_jupyterlab", "max_stars_repo_head_hexsha": "d872d39ad2b811597c93aedfdad0f8f72bc2c834", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example.ipynb", "max_issues_repo_name": "hannahberg/researchBazaar_jupyterlab", "max_issues_repo_head_hexsha": "d872d39ad2b811597c93aedfdad0f8f72bc2c834", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example.ipynb", "max_forks_repo_name": "hannahberg/researchBazaar_jupyterlab", "max_forks_repo_head_hexsha": "d872d39ad2b811597c93aedfdad0f8f72bc2c834", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 1111.652014652, "max_line_length": 271952, "alphanum_fraction": 0.9582609784, "converted": true, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.06954174788049287, "lm_q1q2_score": 0.030982902599035182}}
{"text": "```python\n%reload_ext autoreload\n%autoreload 2\n%matplotlib inline\n\nfrom data_sci.fastai.nlp import *\nfrom sklearn.linear_model import LogisticRegression\n```\n\n## IMDB dataset and the sentiment classification task\n\nThe [large movie review dataset](http://ai.stanford.edu/~amaas/data/sentiment/) contains a collection of 50,000 reviews from IMDB. The dataset contains an even number of positive and negative reviews. The authors considered only highly polarized reviews. A negative review has a score \u2264 4 out of 10, and a positive review has a score \u2265 7 out of 10. Neutral reviews are not included in the dataset. The dataset is divided into training and test sets. The training set is the same 25,000 labeled reviews.\n\nThe **sentiment classification task** consists of predicting the polarity (positive or negative) of a given text.\n\nTo get the dataset, in your terminal run the following commands:\n\n`wget http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz`\n\n`gunzip aclImdb_v1.tar.gz`\n\n`tar -xvf aclImdb_v1.tar`\n\n### Tokenizing and term document matrix creation\n\n\n```python\n# PATH='data/aclImdb/'\nPATH='/data/msnow/data_science/imdb/aclImdb/'\nnames = ['neg','pos']\n```\n\n\n```python\n%ls {PATH}\n```\n\n    imdbEr.txt  imdb.vocab  README  \u001b[0m\u001b[01;34mtest\u001b[0m/  \u001b[01;34mtrain\u001b[0m/\r\n\n\n\n```python\n%ls {PATH}train\n```\n\n    labeledBow.feat  \u001b[0m\u001b[01;34mpos\u001b[0m/    unsupBow.feat  urls_pos.txt\r\n    \u001b[01;34mneg\u001b[0m/             \u001b[01;34munsup\u001b[0m/  urls_neg.txt   urls_unsup.txt\r\n\n\n\n```python\n%ls {PATH}train/pos | head\n```\n\n    0_9.txt\n    10000_8.txt\n    10001_10.txt\n    10002_7.txt\n    10003_8.txt\n    10004_8.txt\n    10005_7.txt\n    10006_7.txt\n    10007_7.txt\n    10008_7.txt\n    ls: write error\n\n\n\n```python\n??texts_labels_from_folders\n```\n\n\n```python\ntrn,trn_y = texts_labels_from_folders(f'{PATH}train',names)\nval,val_y = texts_labels_from_folders(f'{PATH}test',names)\n```\n\nHere is the text of the first review\n\n\n```python\ntrn[0]\n```\n\n\n\n\n    'I rented I AM CURIOUS-YELLOW from my video store because of all the controversy that surrounded it when it was first released in 1967. I also heard that at first it was seized by U.S. customs if it ever tried to enter this country, therefore being a fan of films considered \"controversial\" I really had to see this for myself.<br /><br />The plot is centered around a young Swedish drama student named Lena who wants to learn everything she can about life. In particular she wants to focus her attentions to making some sort of documentary on what the average Swede thought about certain political issues such as the Vietnam War and race issues in the United States. In between asking politicians and ordinary denizens of Stockholm about their opinions on politics, she has sex with her drama teacher, classmates, and married men.<br /><br />What kills me about I AM CURIOUS-YELLOW is that 40 years ago, this was considered pornographic. Really, the sex and nudity scenes are few and far between, even then it\\'s not shot like some cheaply made porno. While my countrymen mind find it shocking, in reality sex and nudity are a major staple in Swedish cinema. Even Ingmar Bergman, arguably their answer to good old boy John Ford, had sex scenes in his films.<br /><br />I do commend the filmmakers for the fact that any sex shown in the film is shown for artistic purposes rather than just to shock people and make money to be shown in pornographic theaters in America. I AM CURIOUS-YELLOW is a good film for anyone wanting to study the meat and potatoes (no pun intended) of Swedish cinema. But really, this film doesn\\'t have much of a plot.'\n\n\n\n\n```python\ntrn_y[0]\n```\n\n\n\n\n    0\n\n\n\n[`CountVectorizer`](http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html) converts a collection of text documents to a matrix of token counts (part of `sklearn.feature_extraction.text`).\n\n\n```python\nveczr = CountVectorizer(tokenizer=tokenize)\n```\n\n`fit_transform(trn)` finds the vocabulary in the training set. It also transforms the training set into a term-document matrix. Since we have to apply the *same transformation* to your validation set, the second line uses just the method `transform(val)`. `trn_term_doc` and `val_term_doc` are sparse matrices. `trn_term_doc[i]` represents training document i and it contains a count of words for each document for each word in the vocabulary.\n\n\n```python\ntrn_term_doc = veczr.fit_transform(trn)\nval_term_doc = veczr.transform(val)\n```\n\n\n```python\ntrn_term_doc\n```\n\n\n\n\n    <25000x75132 sparse matrix of type '<class 'numpy.int64'>'\n    \twith 3749745 stored elements in Compressed Sparse Row format>\n\n\n\n\n```python\ntrn_term_doc[0]\n```\n\n\n\n\n    <1x75132 sparse matrix of type '<class 'numpy.int64'>'\n    \twith 189 stored elements in Compressed Sparse Row format>\n\n\n\n\n```python\nvocab = veczr.get_feature_names(); vocab[5000:5005]\n```\n\n\n\n\n    ['aussie', 'aussies', 'austen', 'austeniana', 'austens']\n\n\n\n\n```python\nw0 = set([o.lower() for o in trn[0].split(' ')]); w0\n```\n\n\n\n\n    {'\"controversial\"',\n     '(no',\n     '/><br',\n     '/>i',\n     '/>the',\n     '/>what',\n     '1967.',\n     '40',\n     'a',\n     'about',\n     'ago,',\n     'all',\n     'also',\n     'am',\n     'america.',\n     'and',\n     'answer',\n     'any',\n     'anyone',\n     'are',\n     'arguably',\n     'around',\n     'artistic',\n     'as',\n     'asking',\n     'at',\n     'attentions',\n     'average',\n     'be',\n     'because',\n     'being',\n     'bergman,',\n     'between',\n     'between,',\n     'boy',\n     'but',\n     'by',\n     'can',\n     'centered',\n     'certain',\n     'cheaply',\n     'cinema.',\n     'classmates,',\n     'commend',\n     'considered',\n     'controversy',\n     'country,',\n     'countrymen',\n     'curious-yellow',\n     'customs',\n     'denizens',\n     'do',\n     'documentary',\n     \"doesn't\",\n     'drama',\n     'enter',\n     'even',\n     'ever',\n     'everything',\n     'fact',\n     'fan',\n     'far',\n     'few',\n     'film',\n     'filmmakers',\n     'films',\n     'films.<br',\n     'find',\n     'first',\n     'focus',\n     'for',\n     'ford,',\n     'from',\n     'good',\n     'had',\n     'has',\n     'have',\n     'heard',\n     'her',\n     'his',\n     'i',\n     'if',\n     'in',\n     'ingmar',\n     'intended)',\n     'is',\n     'issues',\n     'it',\n     \"it's\",\n     'john',\n     'just',\n     'kills',\n     'learn',\n     'lena',\n     'life.',\n     'like',\n     'made',\n     'major',\n     'make',\n     'making',\n     'married',\n     'me',\n     'meat',\n     'men.<br',\n     'mind',\n     'money',\n     'much',\n     'my',\n     'myself.<br',\n     'named',\n     'not',\n     'nudity',\n     'of',\n     'old',\n     'on',\n     'opinions',\n     'ordinary',\n     'particular',\n     'people',\n     'plot',\n     'plot.',\n     'political',\n     'politicians',\n     'politics,',\n     'porno.',\n     'pornographic',\n     'pornographic.',\n     'potatoes',\n     'pun',\n     'purposes',\n     'race',\n     'rather',\n     'reality',\n     'really',\n     'really,',\n     'released',\n     'rented',\n     'scenes',\n     'see',\n     'seized',\n     'sex',\n     'she',\n     'shock',\n     'shocking,',\n     'shot',\n     'shown',\n     'some',\n     'sort',\n     'staple',\n     'states.',\n     'stockholm',\n     'store',\n     'student',\n     'study',\n     'such',\n     'surrounded',\n     'swede',\n     'swedish',\n     'teacher,',\n     'than',\n     'that',\n     'the',\n     'theaters',\n     'their',\n     'then',\n     'therefore',\n     'this',\n     'thought',\n     'to',\n     'tried',\n     'u.s.',\n     'united',\n     'video',\n     'vietnam',\n     'wanting',\n     'wants',\n     'war',\n     'was',\n     'what',\n     'when',\n     'while',\n     'who',\n     'with',\n     'years',\n     'young'}\n\n\n\n\n```python\nlen(w0)\n```\n\n\n\n\n    185\n\n\n\n\n```python\nveczr.vocabulary_['really']\n```\n\n\n\n\n    53936\n\n\n\n\n```python\ntrn_term_doc[0,53936]\n```\n\n\n\n\n    3\n\n\n\n\n```python\ntrn_term_doc[0,5000]\n```\n\n\n\n\n    0\n\n\n\n## Naive Bayes\n\n### Theory break\n\nThis is to create a markdown style table from a pandas dataframe\n\n\n```python\ntmp = []\ntmp.append('This movie was great')\ntmp.append('I liked this movie')\ntmp.append('This is the worst movie ever')\ntmp.append('Bad movie')\nveczr_tmp = CountVectorizer(tokenizer=tokenize)\ntmp_fit = veczr_tmp.fit_transform(tmp)\ndf = pd.DataFrame(tmp_fit.toarray(),columns=veczr_tmp.get_feature_names(),index=tmp)\n\nfrom tabulate import tabulate\nprint(tabulate(df, headers=df.columns,tablefmt=\"pipe\"))\n```\n\n    |                              |   bad |   ever |   great |   i |   is |   liked |   movie |   the |   this |   was |   worst |\n    |:-----------------------------|------:|-------:|--------:|----:|-----:|--------:|--------:|------:|-------:|------:|--------:|\n    | This movie was great         |     0 |      0 |       1 |   0 |    0 |       0 |       1 |     0 |      1 |     1 |       0 |\n    | I liked this movie           |     0 |      0 |       0 |   1 |    0 |       1 |       1 |     0 |      1 |     0 |       0 |\n    | This is the worst movie ever |     0 |      1 |       0 |   0 |    1 |       0 |       1 |     1 |      1 |     0 |       1 |\n    | Bad movie                    |     1 |      0 |       0 |   0 |    0 |       0 |       1 |     0 |      0 |     0 |       0 |\n\n\nIn general, I want to know, given a specific document (which in our case refers to a review), whether it is a positive or negative review, class 0 or class 1, respectively.  Using Bayes I can determine the probability that a specific document will be in a certain class, e.g., $p\\left(c=1\\mid d\\right)$. \n\n$$ p\\left(c=1 \\mid d\\right) = \\dfrac{p\\left(d\\mid c=1\\right) p\\left(c=1\\right)}{p\\left(d\\right)} $$\n\nLet's take this one step further before trying to solve, as it will make the math easier.  I don't realy care about the probabilty or a review being positive or negative, I just want to know if it's more likely to be psoitive or negative.  I can extract this information by taking the ratio of the conditional probabilities.\n\n$$\\dfrac{p\\left(c=1 \\mid d\\right)}{p\\left(c=0 \\mid d\\right)} $$\n\nIf the result is greater than 1, then the review is more likely to belong to class 1, i.e., positive and if the result is less than 1, the review is more likely to be negative, i.e., class 0.\n\n\\begin{align} \n\\dfrac{p\\left(c=1 \\mid d\\right)}{p\\left(c=0 \\mid d\\right)} & = \\dfrac{p\\left(d\\mid c=1\\right) p\\left(c=1\\right)}{p\\left(d\\right)} \\dfrac{p\\left(d\\right)}{p\\left(d\\mid c=0\\right) p\\left(c=0\\right)} \\\\\n& = \\dfrac{p\\left(d\\mid c=1\\right) p\\left(c=1\\right)}{p\\left(d\\mid c=0\\right) p\\left(c=0\\right)} \\\\\n\\end{align}\n\nLet's go through each of these terms in the context of the four sample reviews in the following term document matrix.\n\n\n\n|                              |   bad |   ever |   great |   i |   is |   liked |   movie |   the |   this |   was |   worst |\n|:-----------------------------|------:|-------:|--------:|----:|-----:|--------:|--------:|------:|-------:|------:|--------:|\n| This movie was great         |     0 |      0 |       1 |   0 |    0 |       0 |       1 |     0 |      1 |     1 |       0 |\n| I liked this movie           |     0 |      0 |       0 |   1 |    0 |       1 |       1 |     0 |      1 |     0 |       0 |\n| This is the worst movie ever |     0 |      1 |       0 |   0 |    1 |       0 |       1 |     1 |      1 |     0 |       1 |\n| Bad movie                    |     1 |      0 |       0 |   0 |    0 |       0 |       1 |     0 |      0 |     0 |       0 |\n\n$p\\left(c=C\\right)$ is simply the probability of a document being class 0 or 1.  This is just the number of docuemnts in each class divided by the total number of documents\n\n\\begin{align}\np\\left(c=0\\right) &=2/4 = 0.5 \\\\\np\\left(c=1\\right) &= 2/4 = 0.5 \\\\\n\\end{align}\n\n$p\\left(d\\mid c=C\\right)$ is the probability of seeing this document given a specific class, $C$.  Since the document is just the words (or in nlp speak, the features) which make it up, we can rewrite these terms as $p\\left(f_0,f_1,\\ldots,f_p\\mid c=0\\right)$.  For example, for the first review \n\n$$ p\\left(d_0\\mid c=0\\right) = p\\left(f_8, f_6, f_9, f_2\\mid c=0\\right)$$\n\nHere is where the Naive part of Naive Bayes comes in.  In Naive Bayes we assume that all features are conditionally independent, which means that I can rewrite the previous equation as \n\n$$ p\\left(f_8, f_6, f_9, f_2\\mid c=C\\right) = p\\left(f_8 \\mid c=C\\right) \\times p\\left(f_6 \\mid c=C\\right) \\times p\\left(f_9 \\mid c=0\\right) \\times p\\left(f_2 \\mid c=C\\right) = \\prod\\limits_{i=8,6,9,2}p\\left(f_i \\mid c=C\\right) $$\n\nGoing back to our problem, we can now calculate $p\\left(d_0 \\mid c=0\\right)$ for each feature as the number of times that feature appears in the document divided by the number of times that feature appears in all documents of that class.\n\n$$p\\left(f_{this}\\mid c=0\\right) = 2/2 = 1$$\n\n$$p\\left(f_{movie}\\mid c=0\\right) = 2/2 = 1$$\n\n$$p\\left(f_{was}\\mid c=0\\right) = 1/2 = 0.5$$\n\n$$p\\left(f_{great}\\mid c=0\\right) = 1/2 = 0.5$$\n\n$$p\\left(d_0 \\mid c=0\\right) = 1\\times 1 \\times 0.5 \\times 0.5 = 0.25 $$\n\nIf we try and repeat the same procedure for the other class, we end up with a problem.  What happens if that feature never appears in that class.\n\n$$p\\left(f_{great}\\mid c=1\\right) = 1/0 = ???$$\n\nTo get around this problem we add an additional row to our term document matrix which contains a 1 in every entry.  Intuitively this row represents the idea that there is never a zero percent chance of some word appearing.  It might be infinitesimal, but it is greater than zero. This row of ones is used just for calculating $p\\left(d \\mid c=C\\right)$\n\n|                              |   bad |   ever |   great |   i |   is |   liked |   movie |   the |   this |   was |   worst |\n|:-----------------------------|------:|-------:|--------:|----:|-----:|--------:|--------:|------:|-------:|------:|--------:|\n| This movie was great         |     0 |      0 |       1 |   0 |    0 |       0 |       1 |     0 |      1 |     1 |       0 |\n| I liked this movie           |     0 |      0 |       0 |   1 |    0 |       1 |       1 |     0 |      1 |     0 |       0 |\n| This is the worst movie ever |     0 |      1 |       0 |   0 |    1 |       0 |       1 |     1 |      1 |     0 |       1 |\n| Bad movie                    |     1 |      0 |       0 |   0 |    0 |       0 |       1 |     0 |      0 |     0 |       0 |\n| **ones**                     |     1 |      1 |       1 |   1 |    1 |       1 |       1 |     1 |      1 |     1 |       1 |\n\nWe can now recalculate the probabilities:\n\n$$p\\left(f_{this}\\mid c=0\\right) = (2+1)/3 = 1$$\n\n$$p\\left(f_{movie}\\mid c=0\\right) = (2+1)/3 = 1$$\n\n$$p\\left(f_{was}\\mid c=0\\right) = (1+1)/3 = 0.667$$\n\n$$p\\left(f_{great}\\mid c=0\\right) = (1+1)/3 = 0.667$$\n\n$$p\\left(d_0 \\mid c=0\\right) = 1\\times 1 \\times 0.667 \\times 0.667 = 0.444 $$\n\nRepeat for the other class\n\n$$p\\left(f_{this}\\mid c=1\\right) = (1+1)/3 = 0.667$$\n\n$$p\\left(f_{movie}\\mid c=1\\right) = (2+1)/3 = 1$$\n\n$$p\\left(f_{was}\\mid c=1\\right) = (0+1)/3 = 0.333$$\n\n$$p\\left(f_{great}\\mid c=1\\right) = (0+1)/3 = 0.333$$\n\n$$p\\left(d_0 \\mid c=1\\right) = 0.667 \\times 1 \\times 0.333 \\times 0.333 = 0.074 $$\n\nNow to answer our original question we just need to take the ratios of these two probabilities\n\n$$ \\dfrac{p\\left(d_0 \\mid c=0\\right)}{p\\left(d_0 \\mid c=1\\right)} = \\dfrac{0.444}{0.074} = 6$$\n\nThis tells us that it is 6 times more likely that review 1 belongs to class 0, than class 1.\n\nAs an aside: If we didn't use Naive Bayes the equation would be much harder to solve as the $p\\left(f_8, f_6, f_9, f_2\\mid c=0\\right)$ would expand into a much harder term to solve:\n\n$$ p\\left(f_8, f_6, f_9, f_2\\mid c=0\\right) = p\\left(f_8 \\mid c=0\\right) \\times p\\left(f_6\\mid f_8, c=0\\right) \\times p\\left(f_9, f_2\\mid f_8, f_6, c=0\\right) \\times p\\left(f_2\\mid f_8, f_6, f_9, c=0\\right) $$\n\n### Theory break over\n\nAs stated above, the probability of each feature appearing in a document of a specific class is just the ratio of the number of times that feature appears in that class (plus 1) to the number of documents in that class (plus 1).  The ratio of ratios is then half of the equation we need to solve the problem.  To make the multiplication and division less likely to go to zero or infinity we can also convert everything to logs\n\n\n```python\ndef pr(y_i):\n    p = x[y==y_i].sum(0)\n    return (p+1) / ((y==y_i).sum()+1)\n\nx=trn_term_doc\ny=trn_y\n\nr = np.log(pr(1)/pr(0))\nb = np.log((y==1).mean() / (y==0).mean())\n```\n\nHere is the formula for Naive Bayes.\n\nInstead of calculating the probabilities for each document individiually we can just use matrix multiplication.\n\n\n```python\npre_preds = val_term_doc @ r.T + b\npreds = pre_preds.T>0\n(preds==val_y).mean()\n```\n\n\n\n\n    0.81655999999999995\n\n\n\n...and binarized Naive Bayes (where I don't care how often I've seen it, just if I have seen it or not)\n\n\n```python\nx=trn_term_doc.sign()\nr = np.log(pr(1)/pr(0))\n\npre_preds = val_term_doc.sign() @ r.T + b\npreds = pre_preds.T>0\n(preds==val_y).mean()\n```\n\n\n\n\n    0.83016000000000001\n\n\n\n## Logistic regression\n\nHere is how we can fit logistic regression where the features are the unigrams.\n\n\n```python\nm = LogisticRegression(C=1e8, dual=True)\nm.fit(x, y)\npreds = m.predict(val_term_doc)\n(preds==val_y).mean()\n```\n\n\n\n\n    0.83328000000000002\n\n\n\n...and the binarized version\n\n\n```python\nm = LogisticRegression(C=1e8, dual=True)\nm.fit(trn_term_doc.sign(), y)\npreds = m.predict(val_term_doc.sign())\n(preds==val_y).mean()\n```\n\n\n\n\n    0.85519999999999996\n\n\n\n...and the regularized version (The C paramater, the closer to 1, the greater the regularization)\n\n\n```python\nm = LogisticRegression(C=0.1, dual=True)\nm.fit(x, y)\npreds = m.predict(val_term_doc)\n(preds==val_y).mean()\n```\n\n\n\n\n    0.84872000000000003\n\n\n\n...and the regularized binarized version\n\n\n```python\nm = LogisticRegression(C=0.1, dual=True)\nm.fit(trn_term_doc.sign(), y)\npreds = m.predict(val_term_doc.sign())\n(preds==val_y).mean()\n```\n\n\n\n\n    0.88404000000000005\n\n\n\n### Trigram with NB features\n\nOur next model is a version of logistic regression with Naive Bayes features described [here](https://www.aclweb.org/anthology/P12-2018). For every document we compute binarized features as described above, but this time we use bigrams and trigrams too. Each feature is a log-count ratio. A logistic regression model is then trained to predict sentiment.\n\n\n```python\nveczr =  CountVectorizer(ngram_range=(1,3), tokenizer=tokenize, max_features=800000)\ntrn_term_doc = veczr.fit_transform(trn)\nval_term_doc = veczr.transform(val)\n```\n\n\n```python\ntrn_term_doc.shape\n```\n\n\n\n\n    (25000, 800000)\n\n\n\n\n```python\nvocab = veczr.get_feature_names()\n```\n\n\n```python\nvocab[200000:200005]\n```\n\n\n\n\n    ['by vast', 'by vengeance', 'by vengeance .', 'by vera', 'by vera miles']\n\n\n\n\n```python\ny=trn_y\nx=trn_term_doc.sign()\nval_x = val_term_doc.sign()\n```\n\n\n```python\nr = np.log(pr(1) / pr(0))\nb = np.log((y==1).mean() / (y==0).mean())\n```\n\nHere we fit regularized logistic regression where the features are the trigrams.\n\n\n```python\nm = LogisticRegression(C=0.1, dual=True)\nm.fit(x, y);\n\npreds = m.predict(val_x)\n(preds.T==val_y).mean()\n```\n\n\n\n\n    0.90500000000000003\n\n\n\nHere is the $\\text{log-count ratio}$ `r`.  \n\n\n```python\nr.shape, r\n```\n\n\n\n\n    ((1, 800000), matrix([[-0.05468386, -0.16100472, -0.24783616, ...,  1.09861229,\n              -0.69314718, -0.69314718]]))\n\n\n\n\n```python\nnp.exp(r)\n```\n\n\n\n\n    matrix([[ 0.94678442,  0.85128806,  0.7804878 , ...,  3.        ,\n              0.5       ,  0.5       ]])\n\n\n\nHere we fit regularized logistic regression where the features are the trigrams' log-count ratios.\n\nThis is not equivalent to just multiplying the weight by the ratios as the weights get regularized while the input values do not.  Thus when you multiply the input values by the naive Bayes ratios you are essentially saying that you beleive the ratios and that the model should not alter them unless it has a good reason to.\n\n\n```python\nx_nb = x.multiply(r)\nm = LogisticRegression(dual=True, C=0.1)\nm.fit(x_nb, y);\n\nval_x_nb = val_x.multiply(r)\npreds = m.predict(val_x_nb)\n(preds.T==val_y).mean()\n```\n\n\n\n\n    0.91768000000000005\n\n\n\n## fastai NBSVM++\n\n\n```python\nsl=2000\n```\n\n\n```python\n# Here is how we get a model from a bag of words\nmd = TextClassifierData.from_bow(trn_term_doc, trn_y, val_term_doc, val_y, sl)\n```\n\n\n```python\nlearner = md.dotprod_nb_learner()\nlearner.fit(0.02, 1, wds=1e-6, cycle_len=1)\n```\n\n\n    A Jupyter Widget\n\n\n    [ 0.       0.0251   0.12003  0.91552]                          \n    \n\n\n\n```python\nlearner.fit(0.02, 2, wds=1e-6, cycle_len=1)\n```\n\n\n    A Jupyter Widget\n\n\n    [ 0.       0.02014  0.11387  0.92012]                         \n    [ 1.       0.01275  0.11149  0.92124]                         \n    \n\n\n\n```python\nlearner.fit(0.02, 2, wds=1e-6, cycle_len=1)\n```\n\n\n    A Jupyter Widget\n\n\n    [ 0.       0.01681  0.11089  0.92129]                           \n    [ 1.       0.00949  0.10951  0.92223]                          \n    \n\n\n## References\n\n* Baselines and Bigrams: Simple, Good Sentiment and Topic Classification. Sida Wang and Christopher D. Manning [pdf](https://www.aclweb.org/anthology/P12-2018)\n\n\n```python\n\n```\n", "meta": {"hexsha": "c755fd49b4dc7ac4a1d36b6cb3579a9f25b1ce67", "size": 37589, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/nlp.ipynb", "max_stars_repo_name": "MichoelSnow/data_science", "max_stars_repo_head_hexsha": "7f6c054624268308ec4126a601c9fa8bc5de157c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/nlp.ipynb", "max_issues_repo_name": "MichoelSnow/data_science", "max_issues_repo_head_hexsha": "7f6c054624268308ec4126a601c9fa8bc5de157c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-03-24T15:29:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T00:14:06.000Z", "max_forks_repo_path": "notebooks/nlp.ipynb", "max_forks_repo_name": "MichoelSnow/data_science", "max_forks_repo_head_hexsha": "7f6c054624268308ec4126a601c9fa8bc5de157c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3772760379, "max_line_length": 1657, "alphanum_fraction": 0.4912607412, "converted": true, "num_tokens": 6637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.07159119746371434, "lm_q1q2_score": 0.03079476377110224}}
{"text": "##### <strong><div align=\"center\"> Data Scientist IBM Professional Certification</div></strong>  \n###### <div align=\"center\"> Course 9: Capstone Project</div>  \n\n# Insights on Collision Incidents in Seattle, Washington in 2004-2020\nData Science: Towards Zero Collision Accident!\n\n*Published by **Ihsan Ahmad Zulkarnain**, Indonesia, 6 October 2020*\n\n## <a name=\"ToC\"></a>Table of Contents  \n1. [Introduction](#1)  \n    1.1. [Background](#1.1)   \n    1.2. [The Questions of Interest](#1.2) \n2. [Data Overview](#2)  \n    2.1. [Metadata](#2.1)   \n    2.2. [Data Description](#2.2)  \n3. [Methodology](#3)  \n    3.1. [Data Preprocessing](#3.1)   \n    3.2. [Exploratory Data Analysis and Data Visualization](#3.2)  \n    3.3. [Accident Severity Classification](#3.3)   \n    3.3.1. [Data Preprocessing for Classification](#3.3.1)   \n    3.3.2. [Classification Models](#3.3.2)   \n    3.3.3. [Metrics for Model Evaluation](#3.3.3)   \n4. [Results and Discussion](#4)  \n    4.1. [Exploratory Data Analysis](#4.1)  \n    4.1.1. [Descriptive Statistics](#4.1.1)  \n    4.1.2. [Grouping Data into Categories](#4.1.2)  \n    4.1.3. [Waffle Charts of Categorical Features](#4.1.3)  \n    4.1.4. [Weather and Road Condition Effects on the Number and the Severity of the Accidents](#4.1.4)  \n    4.1.5. [Time-Series Data](#4.1.5)  \n    4.1.6. [Analysis of Variance (ANOVA)](#4.1.6)  \n    4.1.7. [Correlation Analysis](#4.1.7)  \n    4.1.8. [Choropleth Map Visualization](#4.1.8)  \n    4.2. [Accident Severity Classification](#4.2)  \n    4.2.1. [K-Nearest Neighbors (KNN)](#4.2.1)  \n    4.2.2. [Decision Tree](#4.2.2)  \n    4.2.3. [Support Vector Machine (SVM)](#4.2.3)  \n    4.2.4. [Logistic Regression](#4.2.4)  \n    4.2.5. [Model Evaluation using the Dataset of 2020](#4.2.5)  \n    4.2.6. [The Significant Features Leading to Accidents with Injury based on the Classification Model](#4.2.6)  \n5. [Conclusion and Remarks](#5)  \n\n## <a name=\"LoT\"></a>List of Tables\n1. [Descriptive statistics of the data](#t1)  \n2. [The numbers of no injury (1) and with injury (2) accidents](#t2)  \n3. [The numbers of accidents based on the accident location type](#t3)  \n4. [The numbers of accidents between 2004-2020 by district](#t4)  \n5. [The evaluation metrics for each classification model](#t5)\n\n## <a name=\"LoF\"></a>List of Figures\n1. [The waffle charts for seven data features](#f1)  \n2. [The numbers of accidents by weather/road condition and its severity](#f2)  \n3. [Time-series data of the monthly (a) and quarterly (b) numbers of accidents](#f3)\n4. [The heatmap of the correlation among the accident severity and the features of weather](#f4)\n5. [The choropleth map of the numbers of accidents by its district (a: district number from WikiMedia, b: choropleth map)](#f5)\n6. [The choropleth map of the numbers of accidents by its neighborhood (a: 2009, b: 2019)](#f6)\n7. [The choropleth map of the numbers of accidents per neighborhood area (a: 2009, b: 2019)](#f7)\n8. [The Jaccard similarity scores for various values of k in the KNN model](#f8)\n9. [The Jaccard similarity scores for various values of maximum depth in the decision tree model](#f9)\n10. [The decision tree model with maximum depth of five](#f10)\n11. [The confusion matrix for the support vector machine model on the test dataset](#f11)\n12. [The confusion matrices for all models on the final test dataset](#f12)\n13. [The maps with marker-clusters for cases where pedestrian rights were not granted (a to d zoom level = 11, 13, 15, 17 respectively)](#f13)\n14. [The maps with marker-clusters for cases at intersection and under alcohol influence (a to d zoom level = 11, 13, 15, 17 respectively)](#f14)\n15. [The maps with marker-clusters for cases on mid-block, speeding, and under alcohol influence (a to d zoom level = 11, 13, 15, 17 respectively)](#f15)\n\n## <a name=\"1\"></a>1. Introduction [[ToC]](#ToC)\n\n### <a name=\"1.1\"></a>1.1. Background [[ToC]](#ToC)\n\nGovernment is the collective embodiment of its people. It is responsible for the well-being of its citizens. The government of Seattle city is not an exception. In order to serve and protect its citizen, the government plans, executes, and evaluates many public policies which directly and indirectly impact many parts of the life of its citizen. One of the policies is accident management.\n\nThe main tasks of accident management are prevention and mitigation. Its goal is to reduce the severity and the number of potential accidents in future. But how? There are many prevention and mitigation strategies available. But which strategies to choose? And how to effectively plan and execute them? The power of data may help answer these questions. \n\nBy gaining insight into a problem using data, we can gain valuable knowledge which helps us in planning, executing, and evaluating strategies to solve the problem. This is why collecting, documenting, and securely storing data are really important and can be valuable in long term. This is what the government of Seattle has sought since 2004. The government, through its Seattle Police Department, has been recording 194,673 cases of collision accidents in Seattle. This large number of data can be analysed and mined into valuable knowledge to help the government fulfill its vision towards zero collision accident in future.\n\n### <a name=\"1.2\"></a>1.2. The Questions of Interest [[ToC]](#ToC)\n\nIn order to gain valuable knowledge from the data, some questions need to be addressed and answered:\n1. What insight can be obtained from the data by exploratory data analysis and data visualization?\n2. Which classification model is best for predicting the severity status of an accident?\n\n## <a name=\"2\"></a>2. Data Quick Overview [[ToC]](#ToC)\n\n### <a name=\"2.1\"></a>2.1. Metadata [[ToC]](#ToC)\n\n- **Source**: [CognitiveClass](https://s3.us.cloud-object-storage.appdomain.cloud/cf-courses-data/CognitiveClass/DP0701EN/version-2/Data-Collisions.csv) ([Metadata](https://s3.us.cloud-object-storage.appdomain.cloud/cf-courses-data/CognitiveClass/DP0701EN/version-2/Metadata.pdf))\n- **Access date**: 25 September 2020\n- **Format**: Comma-separated values\n- **Size**: **194674 rows** (including the first row as the column headers) representing the observant and **38 columns** representing the features/attributes of the observant\n\nMore detailed information about the data can be found in the metadata pdf file in the source.\n\n### <a name=\"2.2\"></a>2.2. Data Description [[ToC]](#ToC)\n\n- The data is originally provided by the Seattle Police Department and recorded by the Traffic Records. A copy of the data file is stored and distributed as a learning material by the Cognitive Class organizing IBM Data Science online courses.\n- The data preserves records of collision accidents in Seattle, Washington from 2004 to 2020.\n- The information about each collision accident is recorded in a tabular format which includes information about the severity of the accident, the location coordinates, the weather and road condition, and some codes to simplify further details about the accident using a predefined code convention explained in the metadata PDF file.\n- The 194,673 accident records will be assessed using exploratory data analysis to gain insight into the accident statistics in Seattle, such as the correlation between the severity of the accidents and the other features of the accidents.\n\n## <a name=\"3\"></a>3. Methodology [[ToC]](#ToC)\n\n### <a name=\"3.1\"></a>3.1. Data Preprocessing [[ToC]](#ToC)\n\nBefore performing any exploratory data analysis techniques, the data is preprocessed first. The preprocessing steps consist of:\n* _data importing_\n\n    The data is imported into one of suitable formats which is, in this case, DataFrame of Pandas.\n\n* _data cleaning_\n\n    The data is cleaned from any invalid or missing values by replacing them with mean or median values and removing the entire row (entity) or column (feature) if there is too many invalid or missing values. The formats of the values for each feature are also checked and corrected to ensure that it is consistent and ready to be processed. \n\nFor classification and clustering, additional two steps of the data preprocesing are performed: to choose which features to be analysed and to normalize the values of the chosen features. Further detail about the data preprocessing for classification processes is provided in the [section 3.3.1](#3.3.1).\n\n### <a name=\"3.2\"></a>3.2. Exploratory Data Analysis and Data Visualization [[ToC]](#ToC)\n\nThe following is the list of the exploratory data analysis performed and discussed on the accident data:\n1. descriptive statistics,\n2. grouping data into categories:  \n    2.1. visualized using waffle charts,  \n    2.2. visualized using multiple-classes bar charts,  \n    2.3. visualized using time-series line charts,  \n3. ANOVA, and\n4. Correlation\n\nIn the descriptive statistics analysis, the data is grouped by its features and the unique values of the grouped data are counted.\n\nAdditionally, the accident data is visualized in interactive maps using Folium package. The interactive maps include:\n1. a marker-cluster map which shows the numbers of the accidents in 2019 grouped by the relative distance and the map-zooming level, and\n2. some choropleth maps which shows the numbers and the density of the accidents in 2009 and 2019 grouped by the district and neighborhood of Seattle.\n\n### <a name=\"3.3\"></a>3.3. Accident Severity Classification [[ToC]](#ToC)\n\n#### <a name=\"3.3.1\"></a>3.3.1. Data Preprocessing for Classification [[ToC]](#ToC)\n\nThe data is preprocessed with the following steps:\n1. *one hot encoding*, to convert any categorical features into binary value sets,\n2. *dataset choosing*, to choose the target classes and which years of the data are used to filter the training dataset,\n3. *data cleaning*, to manipulate invalid data by removing them (the rows with NaN data) from the dataset,\n4. *data balancing*, to balance the numbers of the positive and negative values of the target data,\n5. *standard scaling*, to scale the values of the dataset so that each feature has similar range of values, and\n6. *training-test set splitting*, to split the dataset into training and test set to enable hyperparametrization of the models.\n\nThe target classes of the classification models are the severity code (1: accident with property damage, 2: accident with human injury). There are 37 features included in the models:\n* 3 location types: \n    * alley, block, intersection\n* 6 junction types: \n    * at intersection (but not related to intersection), at intersection (intersection related), driveway junction, mid-block (but intersection related), mid-block (not related to intersection), ramp junction\n* if caused by inattention \n* if under alcohol influence\n* 9 weather conditions: \n    * blowing sand/dirt, clear, fog/smog/smoke, overcast, partly cloudy, raining, severe crosswind, sleet/hail/freezing rain, snowing\n* 7 road conditions:\n    * dry, ice, oil, sand/mud/dirt, snow/slush, standing water, wet\n* 7 lighting condition:\n    * no street lights, street lights off, street lights on, unknown lighting, dawn, daylight, dusk\n* if pedestrian rights are not granted\n* if speeding\n* if hit parked car\n\nFor the training process, the dataset from Jan 2004 until Dec 2019 are used. Since the number of positive and negative values of the target classes are imbalance (without injury: 109375 cases, with injury: 54169 cases), we balance them by down-sampling the majority cases into 54169 cases which is equal to the number of the minority cases. The data is then splitted 80:20 as the training and test dataset. For the final evaluation, the models will be tested on the remaining dataset from Jan-May 2020.\n\n#### <a name=\"3.3.2\"></a>3.3.2. Classification Models [[ToC]](#ToC)\n\nThere are 4 classification models trained with the data to predict the severity of an accident:\n1. k-nearest neighbors (KNN),\n2. decision tree,\n3. support vector machine (SVM), and\n4. logistic regression.\n\nFor KNN and decision tree, the hyperparameters _k_ in KNN and _maximum depth_ in decision tree are parameterized to get the best performing models on the test set.\n\n#### <a name=\"3.3.3\"></a>3.3.3. Metrics for Model Evaluation [[ToC]](#ToC)\n\nFor KNN and decision tree, the hyperparameters _k_ in KNN and _maximum depth_ in decision tree are parameterized by evaluating the Jaccard similarity indexes to get the best performing models on the test set. For the SVM model, confusion matrix is generated to visualize the precision and recall distribution. In the end, to compare the classification models' performance, the Jaccard similarity index, F1-score, and logistic loss are calculated. The logistic loss is only calculated for the logistic regression model.\n\nJaccard similarity index is calculated by [(1)](#eq1), whereas F1 score is calculated by harmonic-averaging the precision score and the recall score as described in [(2.a-c)](#eq2). Log loss  is calculated by [(3)](#eq3) but only used for evaluating the logistic regression model.\n\n<a name=\"eq1\"></a>\n\\begin{equation}\\tag{1}\n    J(y,\\widehat{y})=\\frac{|y \\cap \\widehat{y}|}{|y \\cup \\widehat{y}|}\n\\end{equation}\n\n<a name=\"eq2\"></a>\n\\begin{equation}\\tag{2.a}\n    Precision = \\frac{True Positive}{True Positive + False Positive}\n\\end{equation}\n\n\\begin{equation}\\tag{2.b}\n    Recall = \\frac{True Positive}{True Positive + False Negative}\n\\end{equation}\n\n\\begin{equation}\\tag{2.c}\n    F_1 = \\frac{2 \\cdot Precision \\cdot Recall}{Precision + Recall}\n\\end{equation}\n\n<a name=\"eq3\"></a>\n\\begin{equation}\\tag{3}\n    LogLoss = -\\frac{1}{n}\\sum (y \\times log(\\hat{y}) + (1-y) \\times log(1-\\hat{y}))\n\\end{equation}\n\n## <a name=\"4\"></a>4. Results and Discussion [[ToC]](#ToC)\n\n### <a name=\"4.1\"></a>4.1. Exploratory Data Analysis [[ToC]](#ToC)\n\n#### <a name=\"4.1.1\"></a>4.1.1. Descriptive Statistics Analysis [[ToC]](#ToC)\n\nIn the [Table 1](#t1), a summary of the descriptive statistics analysis of the data is provided. Only features containing integer or float dtypes are included. The first row represents the counts of the non-NaN data for each features. The rest represent the average, standard deviation, minimum, three quartiles, and maximum, respectively.\n\n <a name=\"t1\"></a>  <div align=\"center\"> Table 1. descriptive statistics of integer and float dtypes features [[LoT]](#LoT) </div>\n\n| index   |   SEVERITYCODE |              X |              Y |   INTKEY |   PERSONCOUNT |       PEDCOUNT |    PEDCYLCOUNT |      VEHCOUNT |   SDOT_COLCODE_A |   SDOT_COLCODE_B |   SEGLANEKEY |    CROSSWALKKEY |\n|:--------|---------------:|---------------:|---------------:|---------:|--------------:|---------------:|---------------:|--------------:|-----------------:|-----------------:|-------------:|----------------:|\n| count   |  194673        | 189339         | 189339         |  65070   |  194673       | 194673         | 194673         | 194673        |    194673        |     194673       |   194673     | 194673          |\n| mean    |       1.2989   |   -122.331     |     47.6195    |  37558.5 |       2.44443 |      0.0371392 |      0.0283912 |      1.92078  |         1.25328  |          2.84164 |      269.401 |   9782.45       |\n| std     |       0.457778 |      0.0299761 |      0.0561566 |  51746   |       1.34593 |      0.19815   |      0.167413  |      0.631047 |         0.763915 |          2.21872 |     3315.78  |  72269.3        |\n| min     |       1        |   -122.419     |     47.4956    |  23807   |       0       |      0         |      0         |      0        |         0        |          0       |        0     |      0          |\n| 25%     |       1        |   -122.349     |     47.576     |  28667   |       2       |      0         |      0         |      2        |         1        |          1       |        0     |      0          |\n| 50%     |       1        |   -122.33      |     47.6154    |  29973   |       2       |      0         |      0         |      2        |         1        |          2       |        0     |      0          |\n| 75%     |       2        |   -122.312     |     47.6637    |  33973   |       3       |      0         |      0         |      2        |         1        |          4       |        0     |      0          |\n| max     |       2        |   -122.239     |     47.7341    | 757580   |      81       |      6         |      2         |     12        |         7        |          9       |   525241     |      5.2397e+06 |\n\nThe output of this descriptive statistics analysis is a good quick overview of the available data. Some useful information that can be taken from this analysis are the average number of involved persons, pedestrians, cyclists, and vehicles.\n\nThe average values of the coordinates (the longitude, X and the latitude, Y) don't give enough insights about the data. The coordinates are better to be visualized in a map. Some map visualizations of the data are available in [Section 4.1.5](#4.1.5). There are some data points that don't have coordinate data. In that case, the data points are excluded in the visualization.\n\nTo gain more insightful information, the data about the accidents are categorized and visualized using waffle charts in the next section (see [Section 4.1.2](#4.1.2)). Further analysis using ANOVA and Correlation analysis are also provided in [Section 4.1.3](#4.1.3) and [Section 4.1.4](#4.1.4) respectively.\n\n\n\n#### <a name=\"4.1.2\"></a>4.1.2. Grouping Data into Categories [[ToC]](#ToC)\n\nFor categorical features, useful insights can be extracted by summarizing and visualizing the data based on the counts of its unique values. Some categorical features are summarized in Table 2-3.\n\n <a name=\"t2\"></a>  <div align=\"center\"> Table 2. The numbers of no injury (1) and with injury (2) accidents [[LoT]](#LoT) </div>\n\n|   index |   SEVERITYCODE |\n|--------:|---------------:|\n|       1 |         136485 |\n|       2 |          58188 |\n\n\n <a name=\"t3\"></a>  <div align=\"center\"> Table 3. The numbers of accidents based on the accident location type [[LoT]](#LoT) </div>\n\n| index        |   ADDRTYPE |\n|:-------------|-----------:|\n| Block        |     126926 |\n| Intersection |      65070 |\n| nan          |       1926 |\n| Alley        |        751 |\n\n#### <a name=\"4.1.3\"></a>4.1.3. Waffle Charts of Categorical Features [[ToC]](#ToC)\n\nThe counts of unique values for other features can also be extracted, but the outputs are too exhaustive. A better way to present them is by visualizing them. One of interesting ways to visualize categorical data is using waffle chart. Unlike bar or pie chart, we could visualize the proportions of data categories using symbolic images. This method helps the readers getting the information about the proportions and the categories each of them represents at the same time.\n\nIn Figure 1 (a-g), the waffle charts for seven categorical features are presented. Each waffle chart is visualized by 5x20 blocks of symbols. Each block represents about 1% of the total proportions of the feature. Exact numbers inside the parentheses in each legend represent the number of the unique value of each category.\n\n<a name=\"f1\"></a>\n<p float=\"left\">\n  (a) \n  (b) \n</p>\n<p float=\"left\">\n  (c)\n  (d)\n</p>\n<p float=\"left\">\n  (e)\n  (f)\n</p>\n<p float=\"left\">\n  (g)\n</p>\n\nFigure 1. The waffle charts for seven data features [[LoF]](#LoF)\n\nBased on Figure 1, we could summarize that most of the cases are dominated by the accidents without any human injuries (up to 60%), on a street block (up to 65%), involved a parked car (up to 25%), on mid-block (up to 46%), during clear weather (up to 57%), on dry road (up to 64%), and during daylight (up to 60%). Unfortunately, some of the unique values in these categorical features can not be compared directly as it is more proper to normalize it into a fair scale, e.g. numbers of accidents on clear weather vs raining can only be compared after dividing the number with the ratio of the frequency of clear weather vs raining in the range of the time. However, this issue is out of the scope of this article and may be covered in future project.\n\n#### <a name=\"4.1.4\"></a>4.1.4. Weather and Road Condition Effects on the Number and the Severity of the Accidents [[ToC]](#ToC)\n\nAlthough the waffle charts are visually interesting, it is not the best choice to show multiple categorical data at once. For that purpose, we use multiple colored bar charts. [Figure 2 (a-b)](#f2) show the numbers of accidents grouped by weather/road condition and severity at the same time on each chart. In order to also show the low numbers of the minority cases, the charts are also presented in logistic scale as shown in [Figure 2 (c-d)](#f2c).\n\n<a name=\"f2\"></a>\n<p float=\"left\">\n  (a) \n  (b) \n</p>\n<p float=\"left\">\n  (c)\n  (d)\n</p>\n\nFigure 2. The numbers of accidents by weather/road condition and its severity [[LoF]](#LoF)\n\nIt has been shown in the waffle charts that most of the accidents happened during clear weather and on dry road. Based on these bar charts, we get more insights about how often accidents that happened on a certain weather and road condition resulted in human injuries. Despite of the facts mentioned before, the accidents that happened during raining weather or on wet road has a slightly higher probability of resulting in injury (33.2%-33.7%) compared to the accidents that happened during clear weather or on dry road (around 32.2%)\n\n#### <a name=\"4.1.5\"></a>4.1.5. Time-Series Data [[ToC]](#ToC)\n\nIt is also interesting to visualize the data into time-series format. In [Figure 3](#f3), the data is grouped into monthly and quarterly numbers of the accidents from January 2004 to May 2020. The accident numbers are also categorized by its severity. The percentage of accidents with injury is also presented and projected to the secondary axis of the charts.\n\n<a name=\"f3\"></a>\n<p float=\"left\">\n  (a) \n  (b)\n</p>\n\nFigure 3. The time-series data of the monthly (a) and quarterly (b) numbers of accidents [[LoF]](#LoF)\n\nTime-series data is useful to gain insights about the trends of the data over time. Figure 3 shows that there is a slight declining trend of the numbers of the accidents. There is even a significant decrease on the second quarter of 2020 because of the lockdown policy across the globe during Covid-19 pandemic.\n\n#### <a name=\"4.1.6\"></a>4.1.6. Analysis of Variance (ANOVA) [[ToC]](#ToC)\n\nThe analysis of variance (ANOVA) of the accident severity is performed on some features of weather: Clear, Raining, and Overcast.  Here are the summary of the ANOVA results (higher F-value is better, lower P-value is better):\n* ANOVA of the accident severity between clear, raining, and overcast results: F= 18.236826341147676 , P = 1.2041667644621963e-08\n* ANOVA of the accident severity between clear and raining results: F= 25.09876170660936 , P = 5.453197502895751e-07\n* ANOVA of the accident severity between clear and overcast results: F= 4.909741750003867 , P = 0.026707249184972547\n* ANOVA of the accident severity between raining and overcast results: F= 32.11870221519134 , P = 1.4568807019555952e-08\n\n\nThese results indicate that it is quite likely that the accident severity has a correlation with the weather during the accident. However, for the low variance between the accident severity of accident during clear weather and overcast, it could indicate that these two weather types lead to similar probabilities of a certain accident severity. In this case, it could also be an option to combine the clear and overcast data into one feature, but it is out of the scope of this article.\n\n#### <a name=\"4.1.7\"></a>4.1.7. Correlation Analysis [[ToC]](#ToC)\n\nA correlation analysis between the accident severity and the features of weather. The correlation coefficients between each feature are calculated and compiled as a heat map as shown in [Figure 4](#f4). However, this result of correlation analysis is still raw as there are too many other features that are neglected in the analysis. A more robust correlation analysis of categorical features can be done by building classification models which is a part of [Section 4.2](#4.2).\n\n<a name=\"f4\"></a>\n<p float=\"left\">\n   \n</p>\n\nFigure 4. The heatmap of the correlation among the accident severity and the features of weather [[LoF]](#LoF)\n\n#### <a name=\"4.1.8\"></a>4.1.8. Map Visualization [[ToC]](#ToC)\n\nSince the dataset also records the longitude (X), the latitude (Y), and the date of each accident, it is possible to present the data using map visualization. By using map visualization, we could gain insights which location need more attention so that policy making can plan, execute, and evaluate its policy more effectively. \n\nThe numbers of accidents (excluding the cases without XY data) between 2004-2020 are grouped by its district (see [Table 4](#t4))  and visualized using choropleth map (see [Figure 5](#f5)). The geojson data of Seattle districts is taken from [github.com/seattleio/seattle-boundaries-data](https://github.com/seattleio/seattle-boundaries-data/blob/master/data/city-council-districts.geojson).\n\n <a name=\"t4\"></a>  <div align=\"center\"> Table 4. The numbers of accidents between 2004-2020 by district [[LoT]](#LoT) </div>\n\n| District        |   Number of Cases |\n|-----------:|---------------:|\n|          2 |          39198 |\n|          7 |          37047 |\n|          3 |          30195 |\n|          6 |          21235 |\n|          1 |          20276 |\n|          4 |          20274 |\n|          5 |          19832 |\n\n\n<a name=\"f5\"></a>\n<p float=\"left\">\n  (a)  \n  (b)  \n</p>\n\nFigure 5. The choropleth map of the numbers of accidents by its district (a: district number from WikiMedia, b: choropleth map) [[LoF]](#LoF)\n\n_Acknowledgement: Figure 6(a) is credited to Dennis Bratland / CC BY-SA (https://creativecommons.org/licenses/by-sa/4.0)_\n\nIn order to be more precise, the numbers of cases distribution can also be grouped by its neighborhood as visualized in [Figure 6](#f6). The geojson data of Seattle neighborhoods is taken from [github.com/seattleio/seattle-boundaries-data](https://github.com/seattleio/seattle-boundaries-data/blob/master/data/city-council-districts.geojson).\n\n<a name=\"f6\"></a>\n<p float=\"left\">\n  (a)  \n  (b)  \n</p>\n\nFigure 6. The choropleth map of the numbers of accidents by its neighborhood (a: 2009, b: 2019) [[LoF]](#LoF)\n\nBased on the number of cases per year, Belltown has the highest number in 2009 with 539 cases but then reduced to 394 cases in 2019. Industrial district has 457 cases in 2009 but then increased to 500 cases in 2019. However, comparing the numbers of cases between neighborhood directly is unfair as each neighborhood has its own traffic number or traffic density.\n\nBesides normalized by its traffic density (whose data might be not easily obtained), the numbers of cases can also be normalized by its neighborhood area. The area of each neighborhood is provided in the geojson data of Seattle neighborhoods. The numbers of cases per neighborhood area are visualized in [Figure 7](#f7).\n\n<a name=\"f7\"></a>\n<p float=\"left\">\n  (a)  \n  (b)  \n</p>\n\nFigure 7. The choropleth map of the numbers of accidents per neighborhood area (a: 2009, b: 2019) [[LoF]](#LoF)\n\nBased on the density of cases per year, Central Business District has the highest density in 2009 and 2019 with 45.3 and 43.7 cases per km2 per year, respectively. It is shown that some neighborhoods have slightly reduced its number or density of cases from 2009 to 2019.\n\nFrom these map visualizations, there are many findings that may help the Seattle Government make its policy and execute traffic law enforcement in effective way by prioritizing which locations that need more attention. \n\n### <a name=\"4.2\"></a>4.2. Accident Severity Classification [[ToC]](#ToC)\n\nIn order to help the Seattle government in planning, executing, and evaluating its policy in decreasing the number and the severity of accidents, it's recommended to build classification models for predicting the severity of an accident based on several features. This could help the government make a priority in preventing any severe accidents based on some most frequent features that could lead to the accident.\n\n#### <a name=\"4.2.1\"></a>4.2.1. K-Nearest Neighbors (KNN) [[ToC]](#ToC)\n\nIn the K-Nearest Neighbors model, the target classes (accident severity) are predicted by sampling k number of nearest neighbors in the existing data and picking the majority class of the sample as the predicted target class. The value k is the hyperparameter which can be adjusted and tested which value results in higher classification accuracy. [Figure 8](#f8) shows the model accuracies for various value of k. It is shown that k=9 leads to the highest KNN model accuracy with 0.583 Jaccard similarity index on the test set.\n\n<a name=\"f8\"></a>\n<p float=\"left\">\n   \n</p>\n\nFigure 8. The Jaccard similarity scores for various values of k in the KNN model [[LoF]](#LoF)\n\n#### <a name=\"4.2.2\"></a>4.2.2. Decision Tree [[ToC]](#ToC)\n\nIn the decision tree model, the target classes (accident severity) are predicted by building a top-down hierarchical tree which split the data based on a threshold to a certain value of a feature that leads to a lower total entropy of the data classification. The value maximum depth is the hyperparameter which can be adjusted and tested which value results in higher classification accuracy. [Figure 9](#f9) shows the model accuracies for various value of maximum depth.\n\n<a name=\"f9\"></a>\n<p float=\"left\">\n   \n</p>\n\nFigure 9. The Jaccard similarity scores for various values of maximum depth in the decision tree model [[LoF]](#LoF)\n\nIt is shown that maximum depth=5 leads to the highest decision tree model accuracy with 0.599 Jaccard similarity index on the test set. The hierarchy of the decision tree with maximum depth of five is shown in [Figure 10](#f10). The boxes with blue color represent the data classified as accidents with injury, whereas red color as accidents without injury. The sharper the color of the box is, the lower the entropy of the data is.\n\n<a name=\"f10\"></a>\n<p float=\"left\">\n   \n</p>\n\nFigure 10. The decision tree model with maximum depth of five [[LoF]](#LoF)\n\n#### <a name=\"4.2.3\"></a>4.2.3. Support Vector Machine (SVM) [[ToC]](#ToC)\n\nIn the SVM model, the target classes (accident severity) are predicted by creating a linear or non-linear line which separates two regions of different classes in a high-dimensional feature space. The kernelling used in the model is radial basis function (RBF). No hyperparameter of the SVM model is adjusted. The numbers of the true and the predicted positive and negative values are illustrated in the confusion matrix as shown in [Figure 11](#f11). The SVM model has accuracy of 0.598 Jaccard similarity index on the test set.\n\n<a name=\"f11\"></a>\n<p float=\"left\">\n   \n</p>\n\nFigure 11. The confusion matrix for the support vector machine model on the test dataset [[LoF]](#LoF)\n\n#### <a name=\"4.2.4\"></a>4.2.4. Logistic Regression [[ToC]](#ToC)\n\nIn the logistic regression model, the target classes (accident severity) are predicted by estimating the probability of a target class using a sigmoid or logistic function. The parameters of the sigmoid function are parameterized to minimize the cost function which represent the loss of classification accuracy. The changes of the parameters in the iterative process are regularized by penalizing large magnitude of changes. The strength of the regularization is represented by the inverse regularization factor, C. The lower value of C, the stronger the regularization is. In this article, we only use one value of inverse regularization factor, C=0.1. This logistic regression model has accuracy of 0.599 Jaccard similarity index on the test set.\n\n#### <a name=\"4.2.5\"></a>4.2.5. Model Evaluation using the Dataset of 2020 [[ToC]](#ToC)\n\nIn the final stage of the classification model building process, the models are evaluated against an unseen test dataset. This time, we pick the dataset from Jan-May 2020 as the final test dataset. The dataset consists of 1182 data points with 808 cases of accidents without injury and 374 cases of accidents with injury. The evaluation metrics assessed are F1-score, Jaccard similarity index, and log loss as summarized in [Table 5](#t5).\n\n\n\n <a name=\"t5\"></a>  <div align=\"center\"> Table 5. The evaluation metrics for each classification model [[LoT]](#LoT) </div>\n\n| index               |   F1 score |   Jaccard similarity index |         Log loss |\n|:--------------------|-----------:|---------------------------:|-----------------:|\n| KNN                 |   0.522397 |                   0.506768 |       nan        |\n| Decision Tree       |   0.632704 |                   0.620135 |       nan        |\n| SVM                 |   0.63095  |                   0.618443 |       nan        |\n| Logistic Regression |   0.621832 |                   0.608291 |         0.651837 |\n\nBased on its F1 score and Jaccard similarity index, the decision tree model performs best compared to the others. In order to visualize the evaluation metrics, the confusion matrices for each model are presented in [Figure 12](#f12). Since the number of postive and negative target values are imbalanced, it seems that all models return low precision scores. In this case, it is recommended to use F1 score as the evaluation metric for classification with imbalanced target dataset.\n\n<a name=\"f12\"></a>\n<p float=\"left\">\n  (a) \n  (b) \n</p>\n<p float=\"left\">\n  (c) \n  (d) \n</p>\n\nFigure 12. The confusion matrices for all models on the final test dataset [[LoF]](#LoF)\n\n#### <a name=\"4.2.6\"></a>4.2.6. The Significant Features Leading to Accidents with Injury based on the Classification Model [[ToC]](#ToC)\n\nIt has been shown that the decision tree model performs best in classifying accidents by its severity based on several features. In this section, we are going to discuss about the significant features which lead to accidents with injury based on the decision tree model.\n\nIn [Figure 6], we find that the first branch of the decision tree is the feature of PEDROWNOTGRNT which according to the metadata pdf file refers to the fact if pedestrian rights were not granted. Since the values of the features are standard-scaled, the binary values of 0 or 1 are scaled slightly, e.g. in case of PEDROWNOTGRNT, the values of 0 and 1 are converted into -0.201025 and 4.974507, respectively. Thus, the criteria \"PEDROWNOTGRNT \u2264 2.387\" is equivalent to \"is Pedestrian rights were granted?\". Branching to the left means the criteria is true, whereas branching to the right means the criteria is false. A box with sharp blue color on the right side after the first branch means that this feature significantly classify the cases where pedestrian rights were not granted as the cases with injury. This finding could be an encouragement for the Seattle government to enforce the traffic laws on putting pedestrian rights as priority to minimize accidents with injury.\n\nThere is no other single significant feature, but rather there are some combinations of features that lead to accident with injuries. Here are the list sorted by its entropy in ascending order (lower entropy means more accurate classification):\n* (Entropy: 0.269) Pedestrian rights were not granted: True\n* (Entropy: 0.907) Junction: At intersection; Under alcohol influence: True\n* (Entropy: 0.951) Junction: Mid-block; Hit parked car: False; Speeding: True; Under alcohol influence: True\n\nBased on this finding, we could add the features of under alcohol influence and of speeding as the other significant features that lead to accidents with injury besides the feature of the pedestrian rights were not granted. The cases with those combinations of features can be visualized in maps with marker-clusters as presented in [Figure 13](#f13), [14](#f14), and [15](#f15). These maps can be used strategically as references for the authority to choose which locations are to be put as the priority in the next policy making or law enforcement by the government.\n\n<a name=\"f13\"></a>\n<p float=\"left\">\n  (a) \n  (b) \n</p>\n<p float=\"left\">\n  (c) \n  (d) \n</p>\n\nFigure 13. The maps with marker-clusters for cases where pedestrian rights were not granted (a to d zoom level = 11, 13, 15, 17 respectively) [[LoF]](#LoF)\n\n<a name=\"f14\"></a>\n<p float=\"left\">\n  (a) \n  (b) \n</p>\n<p float=\"left\">\n  (c) \n  (d) \n</p>\n\nFigure 14. The maps with marker-clusters for cases at intersection and under alcohol influence (a to d zoom level = 11, 13, 15, 17 respectively) [[LoF]](#LoF)\n\n<a name=\"f15\"></a>\n<p float=\"left\">\n  (a) \n  (b) \n</p>\n<p float=\"left\">\n  (c) \n  (d) \n</p>\n\nFigure 15. The maps with marker-clusters for cases on mid-block, speeding, and under alcohol influence (a to d zoom level = 11, 13, 15, 17 respectively) [[LoF]](#LoF)\n\n## <a name=\"5\"></a>5. Conclusion and Remarks [[ToC]](#ToC)\n\nIn this article, some exploratory data analyses have been done and classification models have been trained on a dataset containing 194,673 accident cases in Seattle from Jan 2004 to May 2020. From the exploratory data analyses, some insights have been gained. Some of them are:\n* the accidents that happened during raining weather or on wet road has a slightly higher probability of resulting in injury (33.2%-33.7%) compared to the accidents that happened during clear weather or on dry road (around 32.2%);\n* there is a significant decrease of numbers of accidents on the second quarter of 2020 because of the lockdown policy across the globe Covid-19 pandemic;\n* it is quite likely that the accident severity has a correlation with the weather during the accident;\n* Belltown has the highest number in 2009 with 539 cases but then reduced to 394 cases in 2019;\n* The industrial district has 457 cases in 2009 but then increased to 500 cases in 2019;\n* Central Business District has the highest number of cases per area in 2009 and 2019 with 45.3 and 43.7 cases per km2 per year, respectively. \n* Some neighborhoods have slightly reduced its number or density of cases from 2009 to 2019.\n\nFrom four classification model trained, the decision tree model perform best. Based on the decision tree model, we gain insights about some significant features that lead to accidents with injury. Those are: when the pedestrian rights were not granted, and/or speeding, and/or under alcohol influence.\n\nThere are still some assumptions, limitations, and issues that have not been addressed in or are out of the scope of this article. There are also still many alternative options of classification models available. So, any interested readers are encouraged to improve the works presented here and to help the Seattle government fulfill its missions towards zero collision accident in future.\n", "meta": {"hexsha": "57b6cfec446fc130df715fc7210fac5ea72b218d", "size": 58353, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Report-Notebook.ipynb", "max_stars_repo_name": "ihsanazulkarnain/SeattleCollisions", "max_stars_repo_head_hexsha": "8793a59e24c1ed6a5cb820c6a90ccc026e44d004", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Report-Notebook.ipynb", "max_issues_repo_name": "ihsanazulkarnain/SeattleCollisions", "max_issues_repo_head_hexsha": "8793a59e24c1ed6a5cb820c6a90ccc026e44d004", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Report-Notebook.ipynb", "max_forks_repo_name": "ihsanazulkarnain/SeattleCollisions", "max_forks_repo_head_hexsha": "8793a59e24c1ed6a5cb820c6a90ccc026e44d004", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.9188481675, "max_line_length": 993, "alphanum_fraction": 0.6340376673, "converted": true, "num_tokens": 10002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28457600421652673, "lm_q2_score": 0.10818896390728448, "lm_q1q2_score": 0.03078798304906105}}
{"text": "```python\n%matplotlib inline\n```\n<style type=\"text/css\">\n.reveal h1, .reveal h2 {\n    font-family:\"League Gothic\"\n}\n</style>\nHello everyone! My name is Amit Saha and today I am here to talk to about \"Doing Math with Python\".\n\nThank you for coming to my talk - i know you could have chosen the other talk, so it's good to know that my talk's topic interests you.\n\nA bit about me - I am a software engineer at Freelancer.com in Sydney Australia.  I am a fairly regular writer for Linux Voice and other Linux magazines. And last, but not the least, I am the author of the book \"Doing Math with Python\" (not coincidentally titled the same as this talk - haha) published by No Starch Press in 2015.\n\nThere is a link to my blog, GitHub, twitter, etc. so, if you want to learn more about my work or get in touch, those are the means to do so!\n\nOkay, so all that aside - let's start with the talk!\n\n# <center> My first lab </center>\n \n### <center> Kirstie Whitaker </center>\n\n#### <center> June 15th 2017 </center>\n\n#### <center> Cape Town, SA </center>\n\n## About me\n\n- 2016/17 Mozilla Fellow for Science\n\n- Research Fellow at the Alan Turing Institute for Data Science, London\n\n- Research Associate in the Department of Psychiatry at the University of Cambridge\n\n\n### Contact\n\n- Twitter: [@kirstie_j](http://twitter.com/kirstie_j)\n\n- Email: [kw401@cam.ac.uk](mailto:kw401@cam.ac.uk)\n\n- GitHub: [KirstieJane](http://github.com/KirstieJane)\n\n<a href=\"http://hakim.se\" data-preview-link>Hakim El Hattab</a>\n\nHello!\n\n\nSo, what am I selling to you today? Not my book (I am, but in a subtle way). I am presenting an idea, a hypothesis or even making a statement - Python can lead to a more enriching learning and teaching experience in the classroom.\n\nLet me explain where I am coming from. When I think back about when I was learning to program and learning all other subjects in standards 7-10. I think it's true today as well. Programming and other subjects such as Math, Science are taught in a disconnected fashion. Programming seems to be all about finding the sum of a series or generating fibonacci numbers. Make no mistake, these exercises are what builds up the programming logic. Some students get really excited about being able to do these, but a lot of them don't.  It's a lot like not everyone gets interested in solving puzzles - i don't, i never took to them.\n\nI think I know of a way we could excite more students! Show them how you can write programs to do your homework, or experiment without having to go the science lab or setup elaborate experimental setups. This is my goal for today - in the following slides and notebooks, I will hypothesise on a way of connecting Python programming and other subjects. That will show that programming is a way to get real work done, not something to learn for the sake of it.\n\nWe need some tools to help us on our quest. The Python community has some giant shoulders we can stand upon - Python 3, SymPy and matplotlib.\n\n\n### This talk - a proposal, a hypothesis, a statement\n\nWhat? *Python can lead to a more enriching learning and teaching experience in the classroom* \n\n\n\nHow? *Next slides*\n\n\n\n\n\n\n\n\n###  Tools (or, Giant shoulders we will stand on)\n\n</img>\n\n\n*Python 3*, *SymPy*, *matplotlib*\n\n\n*Individual logos are copyright of the respective projects. [Source](http://www.orphancaremovement.org/standing-on-the-shoulder-of-giants/) of the \"giant shoulders\" image.\n\n\nWhose calculator looks like this?\n\nWho uses Python as a calculator? Raise of hands please!\n\nI do! Specifically, I use Python 3 because of 1/2=0 messes up my monthly expenditure calculation.\n\nBesides the usual addition and subtraction, we have of course the math module and more recently the statistics module which makes Python a worthy scientific calculator.\n\nBut then, there's more! You are not limited to the functions from those libraries, you can write your own custom functions and make them available whenever you start your Python interpreter. How?\n\nUse PYTHONSTARTUP!\n\n### Python - a scientific calculator\n\n\n\nWhose calculator looks like this?\n\n```python\n>>> (131 + 21.5 + 100.2 + 88.7 + 99.5 + 100.5 + 200.5)/4\n185.475\n```\n\n\n*Python 3 is my favorite calculator (not Python 2 because 1/2 = 0)*\n\nBeyond basic operations:\n\n\n\n- `fabs()`, `abs()`, `sin()`, `cos()`, `gcd()`, `log()` and more (See [math](https://docs.python.org/3/library/math.html))\n\n- Descriptive statistics (See [statistics](https://docs.python.org/3/library/statistics.html#module-statistics))\n\n\n### Python - a scientific calculator\n\n- Develop your own functions: unit conversion, finding correlation, .., anything really\n\n- Use PYTHONSTARTUP to extend the battery of readily available mathematical functions\n\n```python\n$ PYTHONSTARTUP=~/work/dmwp/pycon-us-2016/startup_math.py idle3 -s\n```\n\n\n\n\n### Unit conversion functions\n\n```python\n\n>>> unit_conversion()\n1. Kilometers to Miles\n2. Miles to Kilometers\n3. Kilograms to Pounds\n4. Pounds to Kilograms\n5. Celsius to Fahrenheit\n6. Fahrenheit to Celsius\nWhich conversion would you like to do? 6\nEnter temperature in fahrenheit: 98\nTemperature in celsius: 36.66666666666667\n>>> \n\n```\n\n### Finding linear correlation\n\n```python\n>>> \n>>> x = [1, 2, 3, 4]\n>>> y = [2, 4, 6.1, 7.9]\n>>> find_corr_x_y(x, y)\n0.9995411791453812\n\n```\n\nSo, that was Python and it's standard libraries. When you bring in third party libraries to the mix, Python becomes a seriously fancy calculator.\n\nWho has heard about SymPy?\n\nYou can give it algebraic expressions to a function and a graph will be created for you.\n\nYou can give an equation and out comes the solutions for that equation.\n\nWe can even solve calculus problems.\n\n### Python - a really fancy calculator\n\nSymPy - a pure Python symbolic math library\n\n*from sympy import awesomeness*  - don't try that :)\n\n\n\n\n\n```python\n# Create graphs from algebraic expressions\n\nfrom sympy import Symbol, plot\nx = Symbol('x')\np = plot(2*x**2 + 2*x + 2)\n\n```\n\n\n```python\n# Solve equations\n\nfrom sympy import solve, Symbol\nx = Symbol('x')\nsolve(2*x + 1)\n\n```\n\n\n\n\n    [-1/2]\n\n\n\n\n```python\n# Limits\n\nfrom sympy import Symbol, Limit, sin\nx = Symbol('x')\nLimit(sin(x)/x, x, 0).doit()\n\n\n\n```\n\n\n\n\n    1\n\n\n\n\n```python\n# Derivative\n\nfrom sympy import Symbol, Derivative, sin, init_printing\nx = Symbol('x')\ninit_printing()\nDerivative(sin(x)**(2*x+1), x).doit()\n```\n\n\n```python\n# Indefinite integral\n\nfrom sympy import Symbol, Integral, sqrt, sin, init_printing\nx = Symbol('x')\ninit_printing()\nIntegral(sqrt(x)).doit()\n```\n\n\n```python\n# Definite integral\n\nfrom sympy import Symbol, Integral, sqrt\nx = Symbol('x')\nIntegral(sqrt(x), (x, 0, 2)).doit()\n```\n\nI will pause for a moment now. In the first two slides, we have seen how Python can be a super awesome calculator. What does that buy us? We have now been able to show that you can make computer programs literally do your homework. Write a program to do your work once and you will never have to make those lengthy calculations yourselves. Can we use Python to do more? \n\nLet's continue.\n\n<center><h1>Can we do more than write smart calculators?</h1></center>\n\n\n\nPython can be more than a super powerful calculator. We can use it to enhance the learning experience of other subjects. Next, I have three examples including a demo. First up, a video of a projectile motion. This program uses matplotlib's animation API to create a basic animation of a projectile motion - a fairly common subject introduced in introductory Physics. The program which is linked asks for the angle of projection and speed and then draws the trajectory of the projectile. Just by running the program multiple times, we can see how the trajectory changes. We don't have to go outside and start throwing balls..\n\nNext, we will put Jupyter Notebook's interactive widgets to good effect by drawing a Barnsley Fern. Let's see how the demo goes.\n\nNext, with the help of basemap, we can draw places on a world map like we would draw points on a graph paper.\n\nI know I would be excited if someone was showing me all these cool things when I was learning these things!\n\n\n### Python - Making other subjects more lively\n\n</img>\n\n\n- matplotlib\n\n- basemap\n\n- Interactive Jupyter Notebooks\n\n\n\n\n#### Bringing Science to life\n\n*Animation of a Projectile motion* [(Python Source)](https://github.com/doingmathwithpython/pycon-us-2016/blob/master/py-files/projectile_animation.py)\n\n\n\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo(\"8uWRVh58KdQ\")\n```\n\n\n\n\n\n\n\n\n\n\n#### Exploring Fractals in Nature\n\n*Interactively drawing a Barnsley Fern* [(Notebook)](https://github.com/doingmathwithpython/pycon-us-2016/blob/master/notebooks/Interactive%20Barnsley%20Fern.ipynb)\n\n\n\n</img>\n\n\n\n#### The world is your graph paper\n\n*Showing places on a digital map* [(Notebook)](https://github.com/doingmathwithpython/pycon-us-2016/blob/master/notebooks/Maps%20using%20Basemap%20-%20demo.ipynb)\n\nNext, I would like to talk about my book \"Doing Math with Python\". My idea was attractive enough to get it published by No Starch Press which makes me hope that I am probably onto something.\n\nHas anybody read my book? What do you think of it? You have read it and came to my talk? I am feeling better :)\n\nI discuss all of the topics I discuss today in my talk. In addition, I discuss sets, probability and random numbers and descriptive statistics.\n\nIt's being translated into several non-English languages.\n\nThe reviews/feedback so far has been really positive. I don't have any first hand involvement in teaching, so it's very appreciative of people to share their viewpoints with me.\n\n### Book: Doing Math With Python\n\n</img>\n\nOverview\n\n- All of what I have discussed so far\n\n- In addition: Descriptive statistics, Sets and Probability, Random numbers\n\nPublished by [No Starch Press](https://www.nostarch.com/doingmathwithpython) in August, 2015.\n\n*Upcoming/In-progress translations*: Simplified Chinese, Japanese, French and Korean.\n\n#### Comments\n\n> Saha does an excellent job providing a clear link between Python and upper-level math concepts, and demonstrates how Python can be transformed into a mathematical stage. This book deserves a spot on every geometry teacher\u2019s bookshelf.\n\n[School Library Journal](http://www.slj.com/2016/05/collection-development/read-watch-alikes/coding-lets-begin/#_)\n\n\n> Outstanding guide to using Python to do maths. Working back through my undergrad maths using Python.\n\n\n\n> Saha does an excellent job providing a clear link between Python and upper-level math concepts, and demonstrates how Python can be transformed into a mathematical stage.\n\n\n> This book is highly recommended for the high school or college student and anyone who is looking for a more natural way of programming math and scientific functions\n\n> As a teacher I highly recommend this book as a way to work with someone in learning both math and programming\n\n\nOkay, so that's great. We have successfully used Python to make the learning experience of young learners more fun and immediately applicable. Can we derive more benefit from doing that? Like something for the future? We all love doing things for the future, don't we?\n\nI think yes, i think if we teach young learners the things we have discussed today, it is a great base for someone wanting to go into data science or machine learning.\n\nStatistics and visualising data are two very key factors of data science.\n\nDifferential calculus and specifically the gradient descent method is a simple but useful optimization method used in Machine Learning. Let's see a demo of using gradient descent to find the minimum value of a function.\n\nNow, let's apply gradient descent as an optimizer in a Linear Regression problem.\n\n### Great base for the future\n\n*Statistics and Graphing data* -> *Data Science*\n\n*Differential Calculus* -> *Machine learning*\n\n\n### Application of differentiation\n\nUse gradient descent to find a function's minimum value [(Notebook)](https://github.com/doingmathwithpython/pycon-us-2016/blob/master/notebooks/Gradient%20Descent.ipynb)\n\n### Predict the college admission score based on high school math score\n\nUse gradient descent as the optimizer for single variable linear regression model [(Notebook)](https://github.com/doingmathwithpython/pycon-us-2016/blob/master/notebooks/Simple%20Linear%20Regression.ipynb)\n\n\n\n### Advanced libraries\n\n- [scipy](https://scipy.org)\n\n- [numpy](http://www.numpy.org/)\n\n- [scikit-learn](http://scikit-learn.org/stable/)\n\n- [pandas](http://pandas.pydata.org/)\n\n- [Statsmodels](http://statsmodels.sourceforge.net/)\n\n\n\n\n### Dialogue\n\nQuestions, Thoughts, comments, discussions? \n\n\n#### Online \n\n- Twitter: @echorand\n\n- Email: amitsaha.in@gmail.com\n    \n\n\n### PyCon Special!\n\n*Use PYCONMATH code to get 30% off \"Doing Math with Python\" from [No Starch Press](https://www.nostarch.com/doingmathwithpython)*\n\n\n</img>\n\n\n(Valid from  May 26th - June 8th) \n\nBook Signing - May 31st - 2.00 PM - No Starch Press booth\n\n### Acknowledgements\n\nPyCon US Education Summit team for inviting me\n\n\n\nThanks to PyCon US for reduced registration rates\n\n\n\nMassive thanks to my employer, Freelancer.com for sponsoring my travel and stay \n\n\n### Links\n\n- [Upcoming O'Reilly Webcast](http://www.oreilly.com/pub/e/3712)\n\n- [Doing Math with Python](https://nostarch.com/doingmathwithpython)\n\n- [Doing Math with Python Blog](https://doingmathwithpython.github.io)\n\n- [Doing Math with Python on GitHub](https://github.com/doingmathwithpython)\n\n\n", "meta": {"hexsha": "7760f707bbfc05213b896561a6e4f7776f2c359d", "size": 52447, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "slides.ipynb", "max_stars_repo_name": "WhitakerLab/slides", "max_stars_repo_head_hexsha": "a1b36f4114ddb1d330795cd9b0967d476c493df2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "slides.ipynb", "max_issues_repo_name": "WhitakerLab/slides", "max_issues_repo_head_hexsha": "a1b36f4114ddb1d330795cd9b0967d476c493df2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slides.ipynb", "max_forks_repo_name": "WhitakerLab/slides", "max_forks_repo_head_hexsha": "a1b36f4114ddb1d330795cd9b0967d476c493df2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.1377912867, "max_line_length": 13386, "alphanum_fraction": 0.7560584971, "converted": true, "num_tokens": 3221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414213699951, "lm_q2_score": 0.1143685186352413, "lm_q1q2_score": 0.03075843196174257}}
{"text": "```python\n%matplotlib inline\n```\n\n\n\nGenerative Models of Graphs\n===========================================\n\n**Author**: `Mufei Li <https://github.com/mufeili>`_,\n`Lingfan Yu <https://github.com/ylfdq1118>`_, Zheng Zhang\n\n<div class=\"alert alert-danger\"><h4>Warning</h4><p>The tutorial aims at gaining insights into the paper, with code as a mean\n    of explanation. The implementation thus is NOT optimized for running\n    efficiency. For recommended implementation, please refer to the `official\n    examples <https://github.com/dmlc/dgl/tree/master/examples>`_.</p></div>\n\n\nIn this tutorial, you learn how to train and generate one graph at\na time. You also explore parallelism within the graph embedding operation, which is an\nessential building block. The tutorial ends with a simple optimization that\ndelivers double the speed by batching across graphs.\n\nEarlier tutorials showed how embedding a graph or\na node enables you to work on tasks such as `semi-supervised classification for nodes\n<http://docs.dgl.ai/tutorials/models/1_gcn.html#sphx-glr-tutorials-models-1-gcn-py>`__\nor `sentiment analysis\n<http://docs.dgl.ai/tutorials/models/3_tree-lstm.html#sphx-glr-tutorials-models-3-tree-lstm-py>`__.\nWouldn't it be interesting to predict the future evolution of the graph and\nperform the analysis iteratively?\n\nTo address the evolution of the graphs, you generate a variety of graph samples. In other words, you need\n**generative models** of graphs. In-addition to learning\nnode and edge features, you would need to model the distribution of arbitrary graphs.\nWhile general generative models can model the density function explicitly and\nimplicitly and generate samples at once or sequentially, you only focus\non explicit generative models for sequential generation here. Typical applications\ninclude drug or materials discovery, chemical processes, or proteomics.\n\nIntroduction\n--------------------\nThe primitive actions of mutating a graph in Deep Graph Library (DGL) are nothing more than ``add_nodes``\nand ``add_edges``. That is, if you were to draw a circle of three nodes,\n\n.. figure:: https://user-images.githubusercontent.com/19576924/48313438-78baf000-e5f7-11e8-931e-cd00ab34fa50.gif\n   :alt:\n\nyou can write the code as follows.\n\n\n\n\n\n```python\nimport dgl\n\ng = dgl.DGLGraph()\ng.add_nodes(1)              # Add node 0\ng.add_nodes(1)              # Add node 1\n\n# Edges in DGLGraph are directed by default.\n# For undirected edges, add edges for both directions.\ng.add_edges([1, 0], [0, 1]) # Add edges (1, 0), (0, 1)\ng.add_nodes(1)              # Add node 2\ng.add_edges([2, 1], [1, 2]) # Add edges (2, 1), (1, 2)\ng.add_edges([2, 0], [0, 2]) # Add edges (2, 0), (0, 2)\n```\n\nReal-world graphs are much more complex. There are many families of graphs,\nwith different sizes, topologies, node types, edge types, and the possibility\nof multigraphs. Besides, a same graph can be generated in many different\norders. Regardless, the generative process entails a few steps.\n\n- Encode a changing graph.\n- Perform actions stochastically.\n- If you are training, collect error signals and optimize the model parameters.\n\nWhen it comes to implementation, another important aspect is speed. How do you\nparallelize the computation, given that generating a graph is fundamentally a\nsequential process?\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>To be sure, this is not necessarily a hard constraint. Subgraphs can be \n   built in parallel and then get assembled. But we\n   will restrict ourselves to the sequential processes for this tutorial.</p></div>\n\n\nDGMG: The main flow\n--------------------\nFor this tutorial, you use \n`Deep Generative Models of Graphs <https://arxiv.org/abs/1803.03324>`__\n) (DGMG) to implement a graph generative model using DGL. Its algorithmic \nframework is general but also challenging to parallelize.\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>While it's possible for DGMG to handle complex graphs with typed nodes,\n   typed edges, and multigraphs, here you use a simplified version of it\n   for generating graph topologies.</p></div>\n\nDGMG generates a graph by following a state machine, which is basically a\ntwo-level loop. Generate one node at a time and connect it to a subset of\nthe existing nodes, one at a time. This is similar to language modeling. The\ngenerative process is an iterative one that emits one word or character or sentence\nat a time, conditioned on the sequence generated so far.\n\nAt each time step, you either:\n     - Add a new node to the graph\n     - Select two existing nodes and add an edge between them\n\n.. figure:: https://user-images.githubusercontent.com/19576924/48605003-7f11e900-e9b6-11e8-8880-87362348e154.png\n   :alt:\n\nThe Python code will look as follows. In fact, this is *exactly* how inference\nwith DGMG is implemented in DGL.\n\n\n\n\n\n```python\ndef forward_inference(self):\n    stop = self.add_node_and_update()\n    while (not stop) and (self.g.number_of_nodes() < self.v_max + 1):\n        num_trials = 0\n        to_add_edge = self.add_edge_or_not()\n        while to_add_edge and (num_trials < self.g.number_of_nodes() - 1):\n            self.choose_dest_and_update()\n            num_trials += 1\n            to_add_edge = self.add_edge_or_not()\n        stop = self.add_node_and_update()\n\n    return self.g\n```\n\nAssume you have a pre-trained model for generating cycles of nodes 10-20.\nHow does it generate a cycle on-the-fly during inference? Use the code below\nto create an animation with your own model.\n\n::\n\n    import torch\n    import matplotlib.animation as animation\n    import matplotlib.pyplot as plt\n    import networkx as nx\n    from copy import deepcopy\n\n    if __name__ == '__main__':\n        # pre-trained model saved with path ./model.pth\n        model = torch.load('./model.pth')\n        model.eval()\n        g = model()\n\n        src_list = g.edges()[1]\n        dest_list = g.edges()[0]\n\n        evolution = []\n\n        nx_g = nx.Graph()\n        evolution.append(deepcopy(nx_g))\n\n        for i in range(0, len(src_list), 2):\n            src = src_list[i].item()\n            dest = dest_list[i].item()\n            if src not in nx_g.nodes():\n                nx_g.add_node(src)\n                evolution.append(deepcopy(nx_g))\n            if dest not in nx_g.nodes():\n                nx_g.add_node(dest)\n                evolution.append(deepcopy(nx_g))\n            nx_g.add_edges_from([(src, dest), (dest, src)])\n            evolution.append(deepcopy(nx_g))\n\n        def animate(i):\n            ax.cla()\n            g_t = evolution[i]\n            nx.draw_circular(g_t, with_labels=True, ax=ax,\n                             node_color=['#FEBD69'] * g_t.number_of_nodes())\n\n        fig, ax = plt.subplots()\n        ani = animation.FuncAnimation(fig, animate,\n                                      frames=len(evolution),\n                                      interval=600)\n\n.. figure:: https://user-images.githubusercontent.com/19576924/48928548-2644d200-ef1b-11e8-8591-da93345382ad.gif\n   :alt:\n\nDGMG: Optimization objective\n------------------------------\nSimilar to language modeling, DGMG trains the model with *behavior cloning*,\nor *teacher forcing*. Assume for each graph there exists a sequence of\n*oracle actions* $a_{1},\\cdots,a_{T}$ that generates it. What the model\ndoes is to follow these actions, compute the joint probabilities of such\naction sequences, and maximize them.\n\nBy chain rule, the probability of taking $a_{1},\\cdots,a_{T}$ is:\n\n\\begin{align}p(a_{1},\\cdots, a_{T}) = p(a_{1})p(a_{2}|a_{1})\\cdots p(a_{T}|a_{1},\\cdots,a_{T-1}).\\\\\\end{align}\n\nThe optimization objective is then simply the typical MLE loss:\n\n\\begin{align}-\\log p(a_{1},\\cdots,a_{T})=-\\sum_{t=1}^{T}\\log p(a_{t}|a_{1},\\cdots, a_{t-1}).\\\\\\end{align}\n\n\n\n\n\n```python\ndef forward_train(self, actions):\n    \"\"\"\n    - actions: list\n        - Contains a_1, ..., a_T described above\n    - self.prepare_for_train()\n        - Initializes self.action_step to be 0, which will get\n          incremented by 1 every time it is called.\n        - Initializes objects recording log p(a_t|a_1,...a_{t-1})\n\n    Returns\n    -------\n    - self.get_log_prob(): log p(a_1, ..., a_T)\n    \"\"\"\n    self.prepare_for_train()\n\n    stop = self.add_node_and_update(a=actions[self.action_step])\n    while not stop:\n        to_add_edge = self.add_edge_or_not(a=actions[self.action_step])\n        while to_add_edge:\n            self.choose_dest_and_update(a=actions[self.action_step])\n            to_add_edge = self.add_edge_or_not(a=actions[self.action_step])\n        stop = self.add_node_and_update(a=actions[self.action_step])\n\n    return self.get_log_prob()\n```\n\nThe key difference between ``forward_train`` and ``forward_inference`` is\nthat the training process takes oracle actions as input and returns log\nprobabilities for evaluating the loss.\n\nDGMG: The implementation\n--------------------------\nThe ``DGMG`` class\n``````````````````````````\nBelow you can find the skeleton code for the model. You gradually\nfill in the details for each function.\n\n\n\n\n\n```python\nimport torch.nn as nn\n\n\nclass DGMGSkeleton(nn.Module):\n    def __init__(self, v_max):\n        \"\"\"\n        Parameters\n        ----------\n        v_max: int\n            Max number of nodes considered\n        \"\"\"\n        super(DGMGSkeleton, self).__init__()\n\n        # Graph configuration\n        self.v_max = v_max\n\n    def add_node_and_update(self, a=None):\n        \"\"\"Decide if to add a new node.\n        If a new node should be added, update the graph.\"\"\"\n        return NotImplementedError\n\n    def add_edge_or_not(self, a=None):\n        \"\"\"Decide if a new edge should be added.\"\"\"\n        return NotImplementedError\n\n    def choose_dest_and_update(self, a=None):\n        \"\"\"Choose destination and connect it to the latest node.\n        Add edges for both directions and update the graph.\"\"\"\n        return NotImplementedError\n\n    def forward_train(self, actions):\n        \"\"\"Forward at training time. It records the probability\n        of generating a ground truth graph following the actions.\"\"\"\n        return NotImplementedError\n\n    def forward_inference(self):\n        \"\"\"Forward at inference time.\n        It generates graphs on the fly.\"\"\"\n        return NotImplementedError\n\n    def forward(self, actions=None):\n        # The graph you will work on\n        self.g = dgl.DGLGraph()\n\n        # If there are some features for nodes and edges,\n        # zero tensors will be set for those of new nodes and edges.\n        self.g.set_n_initializer(dgl.frame.zero_initializer)\n        self.g.set_e_initializer(dgl.frame.zero_initializer)\n\n        if self.training:\n            return self.forward_train(actions=actions)\n        else:\n            return self.forward_inference()\n```\n\nEncoding a dynamic graph\n``````````````````````````\nAll the actions generating a graph are sampled from probability\ndistributions. In order to do that, you project the structured data,\nnamely the graph, onto an Euclidean space. The challenge is that such\nprocess, called *embedding*, needs to be repeated as the graphs mutate.\n\nGraph embedding\n''''''''''''''''''''''''''\nLet $G=(V,E)$ be an arbitrary graph. Each node $v$ has an\nembedding vector $\\textbf{h}_{v} \\in \\mathbb{R}^{n}$. Similarly,\nthe graph has an embedding vector $\\textbf{h}_{G} \\in \\mathbb{R}^{k}$.\nTypically, $k > n$ since a graph contains more information than\nan individual node.\n\nThe graph embedding is a weighted sum of node embeddings under a linear\ntransformation:\n\n\\begin{align}\\textbf{h}_{G} =\\sum_{v\\in V}\\text{Sigmoid}(g_m(\\textbf{h}_{v}))f_{m}(\\textbf{h}_{v}),\\\\\\end{align}\n\nThe first term, $\\text{Sigmoid}(g_m(\\textbf{h}_{v}))$, computes a\ngating function and can be thought of as how much the overall graph embedding\nattends on each node. The second term $f_{m}:\\mathbb{R}^{n}\\rightarrow\\mathbb{R}^{k}$\nmaps the node embeddings to the space of graph embeddings.\n\nImplement graph embedding as a ``GraphEmbed`` class.\n\n\n\n\n\n```python\nimport torch\n\n\nclass GraphEmbed(nn.Module):\n    def __init__(self, node_hidden_size):\n        super(GraphEmbed, self).__init__()\n\n        # Setting from the paper\n        self.graph_hidden_size = 2 * node_hidden_size\n\n        # Embed graphs\n        self.node_gating = nn.Sequential(\n            nn.Linear(node_hidden_size, 1),\n            nn.Sigmoid()\n        )\n        self.node_to_graph = nn.Linear(node_hidden_size,\n                                       self.graph_hidden_size)\n\n    def forward(self, g):\n        if g.number_of_nodes() == 0:\n            return torch.zeros(1, self.graph_hidden_size)\n        else:\n            # Node features are stored as hv in ndata.\n            hvs = g.ndata['hv']\n            return (self.node_gating(hvs) *\n                    self.node_to_graph(hvs)).sum(0, keepdim=True)\n```\n\nUpdate node embeddings via graph propagation\n'''''''''''''''''''''''''''''''''''''''''''''\n\nThe mechanism of updating node embeddings in DGMG is similar to that for\ngraph convolutional networks. For a node $v$ in the graph, its\nneighbor $u$ sends a message to it with\n\n\\begin{align}\\textbf{m}_{u\\rightarrow v}=\\textbf{W}_{m}\\text{concat}([\\textbf{h}_{v}, \\textbf{h}_{u}, \\textbf{x}_{u, v}]) + \\textbf{b}_{m},\\\\\\end{align}\n\nwhere $\\textbf{x}_{u,v}$ is the embedding of the edge between\n$u$ and $v$.\n\nAfter receiving messages from all its neighbors, $v$ summarizes them\nwith a node activation vector\n\n\\begin{align}\\textbf{a}_{v} = \\sum_{u: (u, v)\\in E}\\textbf{m}_{u\\rightarrow v}\\\\\\end{align}\n\nand use this information to update its own feature:\n\n\\begin{align}\\textbf{h}'_{v} = \\textbf{GRU}(\\textbf{h}_{v}, \\textbf{a}_{v}).\\\\\\end{align}\n\nPerforming all the operations above once for all nodes synchronously is\ncalled one round of graph propagation. The more rounds of graph propagation\nyou perform, the longer distance messages travel throughout the graph.\n\nWith DGL, you implement graph propagation with ``g.update_all``.\nThe message notation here can be a bit confusing. Researchers can refer\nto $\\textbf{m}_{u\\rightarrow v}$ as messages, however the message function\nbelow only passes $\\text{concat}([\\textbf{h}_{u}, \\textbf{x}_{u, v}])$.\nThe operation $\\textbf{W}_{m}\\text{concat}([\\textbf{h}_{v}, \\textbf{h}_{u}, \\textbf{x}_{u, v}]) + \\textbf{b}_{m}$\nis then performed across all edges at once for efficiency consideration.\n\n\n\n\n\n```python\nfrom functools import partial\n\nclass GraphProp(nn.Module):\n    def __init__(self, num_prop_rounds, node_hidden_size):\n        super(GraphProp, self).__init__()\n\n        self.num_prop_rounds = num_prop_rounds\n\n        # Setting from the paper\n        self.node_activation_hidden_size = 2 * node_hidden_size\n\n        message_funcs = []\n        node_update_funcs = []\n        self.reduce_funcs = []\n\n        for t in range(num_prop_rounds):\n            # input being [hv, hu, xuv]\n            message_funcs.append(nn.Linear(2 * node_hidden_size + 1,\n                                           self.node_activation_hidden_size))\n\n            self.reduce_funcs.append(partial(self.dgmg_reduce, round=t))\n            node_update_funcs.append(\n                nn.GRUCell(self.node_activation_hidden_size,\n                           node_hidden_size))\n\n        self.message_funcs = nn.ModuleList(message_funcs)\n        self.node_update_funcs = nn.ModuleList(node_update_funcs)\n\n    def dgmg_msg(self, edges):\n        \"\"\"For an edge u->v, return concat([h_u, x_uv])\"\"\"\n        return {'m': torch.cat([edges.src['hv'],\n                                edges.data['he']],\n                               dim=1)}\n\n    def dgmg_reduce(self, nodes, round):\n        hv_old = nodes.data['hv']\n        m = nodes.mailbox['m']\n        message = torch.cat([\n            hv_old.unsqueeze(1).expand(-1, m.size(1), -1), m], dim=2)\n        node_activation = (self.message_funcs[round](message)).sum(1)\n\n        return {'a': node_activation}\n\n    def forward(self, g):\n        if g.number_of_edges() > 0:\n            for t in range(self.num_prop_rounds):\n                g.update_all(message_func=self.dgmg_msg,\n                             reduce_func=self.reduce_funcs[t])\n                g.ndata['hv'] = self.node_update_funcs[t](\n                     g.ndata['a'], g.ndata['hv'])\n```\n\nActions\n``````````````````````````\nAll actions are sampled from distributions parameterized using neural networks\nand here they are in turn.\n\nAction 1: Add nodes\n''''''''''''''''''''''''''\n\nGiven the graph embedding vector $\\textbf{h}_{G}$, evaluate\n\n\\begin{align}\\text{Sigmoid}(\\textbf{W}_{\\text{add node}}\\textbf{h}_{G}+b_{\\text{add node}}),\\\\\\end{align}\n\nwhich is then used to parametrize a Bernoulli distribution for deciding whether\nto add a new node.\n\nIf a new node is to be added, initialize its feature with\n\n\\begin{align}\\textbf{W}_{\\text{init}}\\text{concat}([\\textbf{h}_{\\text{init}} , \\textbf{h}_{G}])+\\textbf{b}_{\\text{init}},\\\\\\end{align}\n\nwhere $\\textbf{h}_{\\text{init}}$ is a learnable embedding module for\nuntyped nodes.\n\n\n\n\n\n```python\nimport torch.nn.functional as F\nfrom torch.distributions import Bernoulli\n\ndef bernoulli_action_log_prob(logit, action):\n    \"\"\"Calculate the log p of an action with respect to a Bernoulli\n    distribution. Use logit rather than prob for numerical stability.\"\"\"\n    if action == 0:\n        return F.logsigmoid(-logit)\n    else:\n        return F.logsigmoid(logit)\n\nclass AddNode(nn.Module):\n    def __init__(self, graph_embed_func, node_hidden_size):\n        super(AddNode, self).__init__()\n\n        self.graph_op = {'embed': graph_embed_func}\n\n        self.stop = 1\n        self.add_node = nn.Linear(graph_embed_func.graph_hidden_size, 1)\n\n        # If to add a node, initialize its hv\n        self.node_type_embed = nn.Embedding(1, node_hidden_size)\n        self.initialize_hv = nn.Linear(node_hidden_size + \\\n                                       graph_embed_func.graph_hidden_size,\n                                       node_hidden_size)\n\n        self.init_node_activation = torch.zeros(1, 2 * node_hidden_size)\n\n    def _initialize_node_repr(self, g, node_type, graph_embed):\n        \"\"\"Whenver a node is added, initialize its representation.\"\"\"\n        num_nodes = g.number_of_nodes()\n        hv_init = self.initialize_hv(\n            torch.cat([\n                self.node_type_embed(torch.LongTensor([node_type])),\n                graph_embed], dim=1))\n        g.nodes[num_nodes - 1].data['hv'] = hv_init\n        g.nodes[num_nodes - 1].data['a'] = self.init_node_activation\n\n    def prepare_training(self):\n        self.log_prob = []\n\n    def forward(self, g, action=None):\n        graph_embed = self.graph_op['embed'](g)\n\n        logit = self.add_node(graph_embed)\n        prob = torch.sigmoid(logit)\n\n        if not self.training:\n            action = Bernoulli(prob).sample().item()\n        stop = bool(action == self.stop)\n\n        if not stop:\n            g.add_nodes(1)\n            self._initialize_node_repr(g, action, graph_embed)\n\n        if self.training:\n            sample_log_prob = bernoulli_action_log_prob(logit, action)\n\n            self.log_prob.append(sample_log_prob)\n\n        return stop\n```\n\nAction 2: Add edges\n''''''''''''''''''''''''''\n\nGiven the graph embedding vector $\\textbf{h}_{G}$ and the node\nembedding vector $\\textbf{h}_{v}$ for the latest node $v$,\nyou evaluate\n\n\\begin{align}\\text{Sigmoid}(\\textbf{W}_{\\text{add edge}}\\text{concat}([\\textbf{h}_{G}, \\textbf{h}_{v}])+b_{\\text{add edge}}),\\\\\\end{align}\n\nwhich is then used to parametrize a Bernoulli distribution for deciding\nwhether to add a new edge starting from $v$.\n\n\n\n\n\n```python\nclass AddEdge(nn.Module):\n    def __init__(self, graph_embed_func, node_hidden_size):\n        super(AddEdge, self).__init__()\n\n        self.graph_op = {'embed': graph_embed_func}\n        self.add_edge = nn.Linear(graph_embed_func.graph_hidden_size + \\\n                                  node_hidden_size, 1)\n\n    def prepare_training(self):\n        self.log_prob = []\n\n    def forward(self, g, action=None):\n        graph_embed = self.graph_op['embed'](g)\n        src_embed = g.nodes[g.number_of_nodes() - 1].data['hv']\n\n        logit = self.add_edge(torch.cat(\n            [graph_embed, src_embed], dim=1))\n        prob = torch.sigmoid(logit)\n\n        if self.training:\n            sample_log_prob = bernoulli_action_log_prob(logit, action)\n            self.log_prob.append(sample_log_prob)\n        else:\n            action = Bernoulli(prob).sample().item()\n\n        to_add_edge = bool(action == 0)\n        return to_add_edge\n```\n\nAction 3: Choose a destination\n'''''''''''''''''''''''''''''''''\n\nWhen action 2 returns `True`, choose a destination for the\nlatest node $v$.\n\nFor each possible destination $u\\in\\{0, \\cdots, v-1\\}$, the\nprobability of choosing it is given by\n\n\\begin{align}\\frac{\\text{exp}(\\textbf{W}_{\\text{dest}}\\text{concat}([\\textbf{h}_{u}, \\textbf{h}_{v}])+\\textbf{b}_{\\text{dest}})}{\\sum_{i=0}^{v-1}\\text{exp}(\\textbf{W}_{\\text{dest}}\\text{concat}([\\textbf{h}_{i}, \\textbf{h}_{v}])+\\textbf{b}_{\\text{dest}})}\\\\\\end{align}\n\n\n\n\n\n```python\nfrom torch.distributions import Categorical\n\nclass ChooseDestAndUpdate(nn.Module):\n    def __init__(self, graph_prop_func, node_hidden_size):\n        super(ChooseDestAndUpdate, self).__init__()\n\n        self.graph_op = {'prop': graph_prop_func}\n        self.choose_dest = nn.Linear(2 * node_hidden_size, 1)\n\n    def _initialize_edge_repr(self, g, src_list, dest_list):\n        # For untyped edges, only add 1 to indicate its existence.\n        # For multiple edge types, use a one-hot representation\n        # or an embedding module.\n        edge_repr = torch.ones(len(src_list), 1)\n        g.edges[src_list, dest_list].data['he'] = edge_repr\n\n    def prepare_training(self):\n        self.log_prob = []\n\n    def forward(self, g, dest):\n        src = g.number_of_nodes() - 1\n        possible_dests = range(src)\n\n        src_embed_expand = g.nodes[src].data['hv'].expand(src, -1)\n        possible_dests_embed = g.nodes[possible_dests].data['hv']\n\n        dests_scores = self.choose_dest(\n            torch.cat([possible_dests_embed,\n                       src_embed_expand], dim=1)).view(1, -1)\n        dests_probs = F.softmax(dests_scores, dim=1)\n\n        if not self.training:\n            dest = Categorical(dests_probs).sample().item()\n\n        if not g.has_edge_between(src, dest):\n            # For undirected graphs, add edges for both directions\n            # so that you can perform graph propagation.\n            src_list = [src, dest]\n            dest_list = [dest, src]\n\n            g.add_edges(src_list, dest_list)\n            self._initialize_edge_repr(g, src_list, dest_list)\n\n            self.graph_op['prop'](g)\n\n        if self.training:\n            if dests_probs.nelement() > 1:\n                self.log_prob.append(\n                    F.log_softmax(dests_scores, dim=1)[:, dest: dest + 1])\n```\n\nPutting it together\n``````````````````````````\n\nYou are now ready to have a complete implementation of the model class.\n\n\n\n\n\n```python\nclass DGMG(DGMGSkeleton):\n    def __init__(self, v_max, node_hidden_size,\n                 num_prop_rounds):\n        super(DGMG, self).__init__(v_max)\n\n        # Graph embedding module\n        self.graph_embed = GraphEmbed(node_hidden_size)\n\n        # Graph propagation module\n        self.graph_prop = GraphProp(num_prop_rounds,\n                                    node_hidden_size)\n\n        # Actions\n        self.add_node_agent = AddNode(\n            self.graph_embed, node_hidden_size)\n        self.add_edge_agent = AddEdge(\n            self.graph_embed, node_hidden_size)\n        self.choose_dest_agent = ChooseDestAndUpdate(\n            self.graph_prop, node_hidden_size)\n\n        # Forward functions\n        self.forward_train = partial(forward_train, self=self)\n        self.forward_inference = partial(forward_inference, self=self)\n\n    @property\n    def action_step(self):\n        old_step_count = self.step_count\n        self.step_count += 1\n\n        return old_step_count\n\n    def prepare_for_train(self):\n        self.step_count = 0\n\n        self.add_node_agent.prepare_training()\n        self.add_edge_agent.prepare_training()\n        self.choose_dest_agent.prepare_training()\n\n    def add_node_and_update(self, a=None):\n        \"\"\"Decide if to add a new node.\n        If a new node should be added, update the graph.\"\"\"\n\n        return self.add_node_agent(self.g, a)\n\n    def add_edge_or_not(self, a=None):\n        \"\"\"Decide if a new edge should be added.\"\"\"\n\n        return self.add_edge_agent(self.g, a)\n\n    def choose_dest_and_update(self, a=None):\n        \"\"\"Choose destination and connect it to the latest node.\n        Add edges for both directions and update the graph.\"\"\"\n\n        self.choose_dest_agent(self.g, a)\n\n    def get_log_prob(self):\n        add_node_log_p = torch.cat(self.add_node_agent.log_prob).sum()\n        add_edge_log_p = torch.cat(self.add_edge_agent.log_prob).sum()\n        choose_dest_log_p = torch.cat(self.choose_dest_agent.log_prob).sum()\n        return add_node_log_p + add_edge_log_p + choose_dest_log_p\n```\n\nBelow is an animation where a graph is generated on the fly\nafter every 10 batches of training for the first 400 batches. You\ncan see how the model improves over time and begins generating cycles.\n\n.. figure:: https://user-images.githubusercontent.com/19576924/48929291-60fe3880-ef22-11e8-832a-fbe56656559a.gif\n   :alt:\n\nFor generative models, you can evaluate performance by checking the percentage\nof valid graphs among the graphs it generates on the fly.\n\n\n\n\n```python\nimport torch.utils.model_zoo as model_zoo\n\n# Download a pre-trained model state dict for generating cycles with 10-20 nodes.\nstate_dict = model_zoo.load_url('https://data.dgl.ai/model/dgmg_cycles-5a0c40be.pth')\nmodel = DGMG(v_max=20, node_hidden_size=16, num_prop_rounds=2)\nmodel.load_state_dict(state_dict)\nmodel.eval()\n\ndef is_valid(g):\n    # Check if g is a cycle having 10-20 nodes.\n    def _get_previous(i, v_max):\n        if i == 0:\n            return v_max\n        else:\n            return i - 1\n\n    def _get_next(i, v_max):\n        if i == v_max:\n            return 0\n        else:\n            return i + 1\n\n    size = g.number_of_nodes()\n\n    if size < 10 or size > 20:\n        return False\n\n    for node in range(size):\n        neighbors = g.successors(node)\n\n        if len(neighbors) != 2:\n            return False\n\n        if _get_previous(node, size - 1) not in neighbors:\n            return False\n\n        if _get_next(node, size - 1) not in neighbors:\n            return False\n\n    return True\n\nnum_valid = 0\nfor i in range(100):\n    g = model()\n    num_valid += is_valid(g)\n\ndel model\nprint('Among 100 graphs generated, {}% are valid.'.format(num_valid))\n```\n\nFor the complete implementation, see the `DGL DGMG example\n<https://github.com/dmlc/dgl/tree/master/examples/pytorch/dgmg>`__.\n\n\n\n", "meta": {"hexsha": "df88db9a1d6c8de5edd9b285e3c25dca30206a12", "size": 31467, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/pytorch/r-dgmg/tutorial/5_dgmg.ipynb", "max_stars_repo_name": "ketyi/dgl", "max_stars_repo_head_hexsha": "a1b859c29b63a673c148d13231a49504740e0e01", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/pytorch/r-dgmg/tutorial/5_dgmg.ipynb", "max_issues_repo_name": "ketyi/dgl", "max_issues_repo_head_hexsha": "a1b859c29b63a673c148d13231a49504740e0e01", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/pytorch/r-dgmg/tutorial/5_dgmg.ipynb", "max_forks_repo_name": "ketyi/dgl", "max_forks_repo_head_hexsha": "a1b859c29b63a673c148d13231a49504740e0e01", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 126.8830645161, "max_line_length": 2536, "alphanum_fraction": 0.6209362189, "converted": true, "num_tokens": 6624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3311197396289915, "lm_q2_score": 0.09268778114565464, "lm_q1q2_score": 0.03069075395973811}}
{"text": "<a href=\"https://colab.research.google.com/github/olgOk/XanaduTraining/blob/master/Xanadu3.ipynb\" target=\"_parent\"></a>\n\n\n```\npip install pennylane\n```\n\n    Requirement already satisfied: pennylane in /usr/local/lib/python3.6/dist-packages (0.10.0)\n    Requirement already satisfied: semantic-version==2.6 in /usr/local/lib/python3.6/dist-packages (from pennylane) (2.6.0)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from pennylane) (1.18.5)\n    Requirement already satisfied: toml in /usr/local/lib/python3.6/dist-packages (from pennylane) (0.10.1)\n    Requirement already satisfied: networkx in /usr/local/lib/python3.6/dist-packages (from pennylane) (2.4)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from pennylane) (1.4.1)\n    Requirement already satisfied: appdirs in /usr/local/lib/python3.6/dist-packages (from pennylane) (1.4.4)\n    Requirement already satisfied: autograd in /usr/local/lib/python3.6/dist-packages (from pennylane) (1.3)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx->pennylane) (4.4.2)\n    Requirement already satisfied: future>=0.15.2 in /usr/local/lib/python3.6/dist-packages (from autograd->pennylane) (0.16.0)\n\n\n\n```\npip install torch\n```\n\n    Requirement already satisfied: torch in /usr/local/lib/python3.6/dist-packages (1.5.1+cu101)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from torch) (1.18.5)\n    Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from torch) (0.16.0)\n\n\n\n```\npip install tensorflow\n```\n\n    Requirement already satisfied: tensorflow in /usr/local/lib/python3.6/dist-packages (2.2.0)\n    Requirement already satisfied: numpy<2.0,>=1.16.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.18.5)\n    Requirement already satisfied: h5py<2.11.0,>=2.10.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (2.10.0)\n    Requirement already satisfied: tensorboard<2.3.0,>=2.2.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (2.2.2)\n    Requirement already satisfied: tensorflow-estimator<2.3.0,>=2.2.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (2.2.0)\n    Requirement already satisfied: keras-preprocessing>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.1.2)\n    Requirement already satisfied: gast==0.3.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (0.3.3)\n    Requirement already satisfied: protobuf>=3.8.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (3.10.0)\n    Requirement already satisfied: scipy==1.4.1; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.4.1)\n    Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.1.0)\n    Requirement already satisfied: google-pasta>=0.1.8 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (0.2.0)\n    Requirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (0.9.0)\n    Requirement already satisfied: six>=1.12.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.12.0)\n    Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (3.2.1)\n    Requirement already satisfied: astunparse==1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.6.3)\n    Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.30.0)\n    Requirement already satisfied: wheel>=0.26; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from tensorflow) (0.34.2)\n    Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.12.1)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (3.2.2)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (0.4.1)\n    Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (1.0.1)\n    Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (1.17.2)\n    Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (49.1.0)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (1.7.0)\n    Requirement already satisfied: requests<3,>=2.21.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (2.23.0)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from markdown>=2.6.8->tensorboard<2.3.0,>=2.2.0->tensorflow) (1.7.0)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.3.0,>=2.2.0->tensorflow) (1.3.0)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow) (0.2.8)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow) (4.1.1)\n    Requirement already satisfied: rsa<5,>=3.1.4; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow) (4.6)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow) (2020.6.20)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow) (3.0.4)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata; python_version < \"3.8\"->markdown>=2.6.8->tensorboard<2.3.0,>=2.2.0->tensorflow) (3.1.0)\n    Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.3.0,>=2.2.0->tensorflow) (3.1.0)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.6/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow) (0.4.8)\n\n\n\n```\npip install sklearn\n```\n\n    Requirement already satisfied: sklearn in /usr/local/lib/python3.6/dist-packages (0.0)\n    Requirement already satisfied: scikit-learn in /usr/local/lib/python3.6/dist-packages (from sklearn) (0.22.2.post1)\n    Requirement already satisfied: numpy>=1.11.0 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->sklearn) (1.18.5)\n    Requirement already satisfied: scipy>=0.17.0 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->sklearn) (1.4.1)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->sklearn) (0.16.0)\n\n\n\n```\npip install pennylane-qiskit\n```\n\n    Requirement already satisfied: pennylane-qiskit in /usr/local/lib/python3.6/dist-packages (0.9.0)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from pennylane-qiskit) (1.18.5)\n    Requirement already satisfied: qiskit>=0.19.1 in /usr/local/lib/python3.6/dist-packages (from pennylane-qiskit) (0.19.6)\n    Requirement already satisfied: pennylane>=0.9.0 in /usr/local/lib/python3.6/dist-packages (from pennylane-qiskit) (0.10.0)\n    Requirement already satisfied: networkx>=2.2; python_version > \"3.5\" in /usr/local/lib/python3.6/dist-packages (from pennylane-qiskit) (2.4)\n    Requirement already satisfied: qiskit-aqua==0.7.3 in /usr/local/lib/python3.6/dist-packages (from qiskit>=0.19.1->pennylane-qiskit) (0.7.3)\n    Requirement already satisfied: qiskit-terra==0.14.2 in /usr/local/lib/python3.6/dist-packages (from qiskit>=0.19.1->pennylane-qiskit) (0.14.2)\n    Requirement already satisfied: qiskit-aer==0.5.2 in /usr/local/lib/python3.6/dist-packages (from qiskit>=0.19.1->pennylane-qiskit) (0.5.2)\n    Requirement already satisfied: qiskit-ibmq-provider==0.7.2 in /usr/local/lib/python3.6/dist-packages (from qiskit>=0.19.1->pennylane-qiskit) (0.7.2)\n    Requirement already satisfied: qiskit-ignis==0.3.3 in /usr/local/lib/python3.6/dist-packages (from qiskit>=0.19.1->pennylane-qiskit) (0.3.3)\n    Requirement already satisfied: appdirs in /usr/local/lib/python3.6/dist-packages (from pennylane>=0.9.0->pennylane-qiskit) (1.4.4)\n    Requirement already satisfied: toml in /usr/local/lib/python3.6/dist-packages (from pennylane>=0.9.0->pennylane-qiskit) (0.10.1)\n    Requirement already satisfied: semantic-version==2.6 in /usr/local/lib/python3.6/dist-packages (from pennylane>=0.9.0->pennylane-qiskit) (2.6.0)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from pennylane>=0.9.0->pennylane-qiskit) (1.4.1)\n    Requirement already satisfied: autograd in /usr/local/lib/python3.6/dist-packages (from pennylane>=0.9.0->pennylane-qiskit) (1.3)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx>=2.2; python_version > \"3.5\"->pennylane-qiskit) (4.4.2)\n    Requirement already satisfied: pyscf; sys_platform != \"win32\" in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit>=0.19.1->pennylane-qiskit) (1.7.3)\n    Requirement already satisfied: scikit-learn>=0.20.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit>=0.19.1->pennylane-qiskit) (0.22.2.post1)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit>=0.19.1->pennylane-qiskit) (5.4.8)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit>=0.19.1->pennylane-qiskit) (1.6.1)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit>=0.19.1->pennylane-qiskit) (49.1.0)\n    Requirement already satisfied: dlx in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit>=0.19.1->pennylane-qiskit) (1.0.4)\n    Requirement already satisfied: docplex in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit>=0.19.1->pennylane-qiskit) (2.15.194)\n    Requirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit>=0.19.1->pennylane-qiskit) (2.10.0)\n    Requirement already satisfied: fastdtw in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit>=0.19.1->pennylane-qiskit) (0.3.4)\n    Requirement already satisfied: quandl in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit>=0.19.1->pennylane-qiskit) (3.5.1)\n    Requirement already satisfied: marshmallow<4,>=3 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit>=0.19.1->pennylane-qiskit) (3.7.0)\n    Requirement already satisfied: python-constraint>=1.4 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit>=0.19.1->pennylane-qiskit) (1.4.0)\n    Requirement already satisfied: fastjsonschema>=2.10 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit>=0.19.1->pennylane-qiskit) (2.14.4)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit>=0.19.1->pennylane-qiskit) (0.3.2)\n    Requirement already satisfied: ply>=3.10 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit>=0.19.1->pennylane-qiskit) (3.11)\n    Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit>=0.19.1->pennylane-qiskit) (2.6.0)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit>=0.19.1->pennylane-qiskit) (2.8.1)\n    Requirement already satisfied: retworkx>=0.3.2 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit>=0.19.1->pennylane-qiskit) (0.3.4)\n    Requirement already satisfied: marshmallow-polyfield<6,>=5.7 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit>=0.19.1->pennylane-qiskit) (5.9)\n    Requirement already satisfied: cython>=0.27.1 in /usr/local/lib/python3.6/dist-packages (from qiskit-aer==0.5.2->qiskit>=0.19.1->pennylane-qiskit) (0.29.21)\n    Requirement already satisfied: pybind11>=2.4 in /usr/local/lib/python3.6/dist-packages (from qiskit-aer==0.5.2->qiskit>=0.19.1->pennylane-qiskit) (2.5.0)\n    Requirement already satisfied: nest-asyncio!=1.1.0,>=1.0.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit>=0.19.1->pennylane-qiskit) (1.3.3)\n    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit>=0.19.1->pennylane-qiskit) (2.23.0)\n    Requirement already satisfied: websockets<8,>=7 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit>=0.19.1->pennylane-qiskit) (7.0)\n    Requirement already satisfied: requests-ntlm>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit>=0.19.1->pennylane-qiskit) (1.1.0)\n    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit>=0.19.1->pennylane-qiskit) (1.24.3)\n    Requirement already satisfied: future>=0.15.2 in /usr/local/lib/python3.6/dist-packages (from autograd->pennylane>=0.9.0->pennylane-qiskit) (0.16.0)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.7.3->qiskit>=0.19.1->pennylane-qiskit) (0.16.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy>=1.3->qiskit-aqua==0.7.3->qiskit>=0.19.1->pennylane-qiskit) (1.1.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from docplex->qiskit-aqua==0.7.3->qiskit>=0.19.1->pennylane-qiskit) (1.12.0)\n    Requirement already satisfied: more-itertools in /usr/local/lib/python3.6/dist-packages (from quandl->qiskit-aqua==0.7.3->qiskit>=0.19.1->pennylane-qiskit) (8.4.0)\n    Requirement already satisfied: pandas>=0.14 in /usr/local/lib/python3.6/dist-packages (from quandl->qiskit-aqua==0.7.3->qiskit>=0.19.1->pennylane-qiskit) (1.0.5)\n    Requirement already satisfied: inflection>=0.3.1 in /usr/local/lib/python3.6/dist-packages (from quandl->qiskit-aqua==0.7.3->qiskit>=0.19.1->pennylane-qiskit) (0.5.0)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.7.2->qiskit>=0.19.1->pennylane-qiskit) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.7.2->qiskit>=0.19.1->pennylane-qiskit) (2020.6.20)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.7.2->qiskit>=0.19.1->pennylane-qiskit) (2.10)\n    Requirement already satisfied: cryptography>=1.3 in /usr/local/lib/python3.6/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit>=0.19.1->pennylane-qiskit) (2.9.2)\n    Requirement already satisfied: ntlm-auth>=1.0.2 in /usr/local/lib/python3.6/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit>=0.19.1->pennylane-qiskit) (1.5.0)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.14->quandl->qiskit-aqua==0.7.3->qiskit>=0.19.1->pennylane-qiskit) (2018.9)\n    Requirement already satisfied: cffi!=1.11.3,>=1.8 in /usr/local/lib/python3.6/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit>=0.19.1->pennylane-qiskit) (1.14.0)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.6/dist-packages (from cffi!=1.11.3,>=1.8->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit>=0.19.1->pennylane-qiskit) (2.20)\n\n\n\n```\nimport pennylane as qml\nfrom pennylane import numpy as np\n```\n\n\n```\ndev = qml.device(\"default.qubit\", wires=2)\n@qml.qnode(device=dev)\ndef cos_func(x, w):\n  qml.RX(x, wires=0)\n  qml.templates.BasicEntanglerLayers(w, wires=range(2))\n  return qml.expval(qml.PauliZ(0))\n\nlayer = 4\nweights = qml.init.basic_entangler_layers_uniform(layer, 2)\n\nxs = np.linspace(-np.pi, 4*np.pi, requires_grad=False)\nys = np.cos(xs)\n```\n\n\n```\nopt = qml.AdamOptimizer()\nepochs = 10\n\nfor epoch in range(epochs):\n  for x, y in zip(xs, ys):\n    cost = lambda weights:(cos_func(x, weights) - y) ** 2\n    weights = opt.step(cost, weights)\n\nys_trained = [cos_func(x, weights) for x in xs]\n\n```\n\n\n```\nimport matplotlib.pyplot as plt\n\nplt.figure()\nplt.plot(xs, ys_trained, marker=\"o\", label=\"Cos(x\")\nplt.legend()\nplt.show()\n```\n\n\n```\n\n```\n\n## Preparing GHZ state\n\nUsing the Autograd interface, train a circuit to prepare the 3-qubit W state:\n\n$|W> = {1/sqrt(3)}(001|> + |010> + |100>)\n\n\n```\nqubits = 3\n\nw = np.array([0, 1, 1, 0, 1, 0, 0, 0]) / np.sqrt(3)\nw_projector = w[:, np.newaxis] * w\nw_decomp = qml.utils.decompose_hamiltonian(w_projector)\nH = qml.Hamiltonian(*w_decomp)\n\ndef prepare_w(weights, wires):\n    qml.templates.StronglyEntanglingLayers(weights, wires=wires)\n\ndev = qml.device(\"default.qubit\", wires=qubits)\nqnodes = qml.map(prepare_w, H.ops, dev)\nw_overlap = qml.dot(H.coeffs, qnodes)\n\nlayers = 4\nweights = qml.init.strong_ent_layers_uniform(layers, qubits)\n\nopt = qml.RMSPropOptimizer()\n\nepochs = 50\n\nfor i in range(epochs):\n    weights = opt.step(lambda weights: -w_overlap(weights), weights)\n    if i % 5 == 0:\n        print(i, w_overlap(weights))\n\noutput_overlap = w_overlap(weights)\noutput_state = np.round(dev.state, 3)\n\n```\n\n##Quantum-based Optimization\n\n\n```\ndev = qml.device('default.qubit', wires=1)\n\n@qml.qnode(dev)\ndef rotation(thetas):\n    qml.RX(1, wires=0)\n    qml.RZ(1, wires=0)\n    \n    qml.RX(thetas[0], wires=0)\n    qml.RY(thetas[1], wires=0)\n\n    return qml.expval(qml.PauliZ(0))\n\n```\n\n\n```\nopt = qml.RotoselectOptimizer()\n\n\n```\n\n\n```\nimport sklearn.datasets\n\ndata = sklearn.datasets.load_iris()\nx = data[\"data\"]\ny = data[\"target\"]\n\nnp.random.seed(1967)\nx, y = zip(*np.random.permutation(list(zip(x, y))))\n\nsplit = 125\n\nx_train = x[:split]\nx_test = x[split:]\ny_train = y[:split]\ny_test = y[split:]\n\n```\n\n\n```\n\n```\n", "meta": {"hexsha": "d022065303ea0097200b2cf3ef960cf4c0691919", "size": 53192, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Xanadu3.ipynb", "max_stars_repo_name": "olgOk/XanaduTraining", "max_stars_repo_head_hexsha": "1e4af1091117b219d7a504226a45a1065e010b26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Xanadu3.ipynb", "max_issues_repo_name": "olgOk/XanaduTraining", "max_issues_repo_head_hexsha": "1e4af1091117b219d7a504226a45a1065e010b26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Xanadu3.ipynb", "max_forks_repo_name": "olgOk/XanaduTraining", "max_forks_repo_head_hexsha": "1e4af1091117b219d7a504226a45a1065e010b26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 101.1254752852, "max_line_length": 22646, "alphanum_fraction": 0.7544555572, "converted": true, "num_tokens": 6708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.06656918295199357, "lm_q1q2_score": 0.030689510325980402}}
{"text": "# Information-theoretic analysis of EEG microstates in Python\n\nThe following CSS code will render the document style for better visualization (https://stackoverflow.com/questions/34303422).\n\n\n```python\nfrom IPython.core.display import HTML\nHTML(\"\"\"\n<style>\n\ndiv.cell { /* Tunes the space between cells */\nmargin-top:1em;\nmargin-bottom:1em;\n}\n\ndiv.text_cell_render h1 { /* Main titles bigger, centered */\nfont-size: 2.2em;\nline-height:1.4em;\ntext-align:center;\n}\n\ndiv.text_cell_render h2 { /*  Parts names nearer from text -0.4em*/\nmargin-bottom: 0.0em;\n}\n\ndiv.text_cell_render { /* Customize text cells */\nfont-family: 'Times New Roman';\nfont-size:1.5em;\nline-height:1.4em;\npadding-left:3em;\npadding-right:3em;\n}\n</style>\n\"\"\")\n```\n\n\n\n\n\n<style>\n\ndiv.cell { /* Tunes the space between cells */\nmargin-top:1em;\nmargin-bottom:1em;\n}\n\ndiv.text_cell_render h1 { /* Main titles bigger, centered */\nfont-size: 2.2em;\nline-height:1.4em;\ntext-align:center;\n}\n\ndiv.text_cell_render h2 { /*  Parts names nearer from text -0.4em*/\nmargin-bottom: 0.0em;\n}\n\ndiv.text_cell_render { /* Customize text cells */\nfont-family: 'Times New Roman';\nfont-size:1.5em;\nline-height:1.4em;\npadding-left:3em;\npadding-right:3em;\n}\n</style>\n\n\n\n\nOur software is provided as a single Python source code file (eeg_microstates.py) that contains all functions necessary to:  \n* import EEG data in the '.edf' file format\n* pre-process (band-pass filter) the EEG data\n* compute microstate maps by the modified K-means algorithm [1]\n* compute microstate time series by competitively back-fitting the microstate maps into the EEG data\n* perform information-theoretical calculations we recently introduced [2]\n\n[1] Pascual-Marqui RD, Michel CM, Lehmann D. Segmentation of brain electrical activity into microstates: model estimation and validation. IEEE Trans Biomed Eng 42 (1995) 658\u2013665.\n\n[2] von Wegner F, Tagliazucchi E, Laufs H. Information-theoretical analysis of resting state EEG microstate sequences - non-Markovianity, non-stationarity and periodicities. NeuroImage 158 (2017) 99\u2013111.\n\n[3] von Wegner F, Laufs H. Information-theoretical analysis of EEG microstate sequences in Python. Front Neuroinformatics (2018) doi: 10.3389/fninf.2018.00030.\n\n[4] von Wegner F, Knaut P, Laufs H. EEG microstate sequences from different clustering algorithms are information-theoretically invariant. Front Comp Neurosci (2018) doi: 10.3389/fncom.2018.00070.\n\nIn order to display images, we import the following notebook utility.\n\n\n```python\nfrom IPython.core.display import Image\n```\n\nIn order to work with the package, the following import statement can be used in Python standalone scripts, e.g. for batch processing, or in any Python-based EEG software to add extra functionality:\n\n\n```python\nfrom eeg_microstates import *\n```\n\n### Github link of this project\n\nThe current version of the software can be found on the [GitHub project page](https://github.com/Frederic-vW/eeg_microstates/tree/master/).\n\n### Current literature about EEG microstates and information theory\n\nTo find out about current publications and directions in microstate research, in particular related to information-theoretical approaches, we provide an active link to the PubMed page. If using the interactive IPython notebook, you can use the PubMed search bar to adapt the search term.\n\n\n```python\nurl = 'https://www.ncbi.nlm.nih.gov/pubmed/?term=eeg+microstates+information+theory'\niframe = ''\nHTML(iframe)\n```\n\n\n\n\n\n\n\n\n## Background\n\nElectroencephalography (EEG) records the brain's electrical potential at discrete spatial sampling sites, defined by the locations of the electrodes on the skull. We also call the potential distribution at a given time a topography, or a map. The idea behind the microstate algorithm is to represent the EEG time series by a small number of maps that yield an optimum representation of the full data set. As in other areas of data compression, optimality can be defined in different ways. For EEG microstates, the criterion of choice is that of maximum explained variance. To this end, a (large) set of EEG samples is fed into a clustering algorithm whose output is a reduced set of representative EEG topographies, also called termed microstates, or microstate maps.  \nThe EEG time series can then be represented by a sequence of microstate labels, where each time point of the original EEG data is mapped to the microstate with the maximum spatial correlation to the actual EEG topography. Polarity is usually ignored, so the squared correlation coefficient between each candidate microstate map and the EEG topography is used as a similarity measure.  \nWith a set of representative microstates at hand, the multi-channel EEG data set can be compressed into a time series of symbols, i.e. microstate labels. Most frequently, four microstates are used to compress the EEG data set, and the microstates are labelled A, B, C, D. The EEG data set is therefore transformed into a microstate sequence that could read like ...AAABBDCDABBDAB...  \nDue to the special, non-metric nature of the new state space {A, B, C, D}, many common time-series methods such as the autocorrelation function cannot be applied to the microstate time series. We therefore test several entropy-based measures based on Shannon's information theory to quantify these time series.  \n\nThe details of the procedure are given in the following sections and the whole procedure is illustrated in the figure below.  \nStep 1: The EEG data set is submitted to the modified K-means algorithm to obtain the microstate maps A-D. The figure below shows a section of resting state EEG for a selection of the 30 channels recorded. At each time point, the spatial standard deviation of the EEG topography is also called global field power (GFP, blue). Topographies at local maxima of the GFP time series (MAX, red dots) define the input to the modified K-means clustering algorithm.  \nStep 2: The microstate time series is computed by competitive back-fitting of the microstate maps into the EEG time series.  \nStep 3: Several information-theoretical tests are run on the microstate sequence and finally, the time-lagged mutual information function and a first-order Markov confidence interval are computed and displayed.\n\n\n```python\nImage(filename='Figure_1.jpg')\n```\n\n\n\n\n    \n\n    \n\n\n\n## (1) EEG data input\n\nThe package contains a basic [EDF](http://www.edfplus.info/specs/edf.html) file format reader. EEG data is returned as a NumPy array with time running along the rows (first index) and channels across the columns (2nd index), i.e. the array shape is (n_samples, n_channels). If our code is interfaced with other Python programs, EEG data must be provided in that shape in order to be processed correctly by our package functions.  \nThe return variables of the function read_edf are (1) a list of channel names, (2) the sampling rate in Hz, and (3) the EEG data in the mentioned format.  \nTo run this tutorial, you must have the test.edf EEG file in your current folder. The file is part of the GitHub repository. The record contains 192 sec. from an eyes-closed resting state experiment of a healthy male subject recorded with a 30 channel EEG cap using a standard 10-10 electrode configuration. The sampling rate is 250 Hz and the data is band-pass filtered to the 1-40 Hz range.\n\n\n```python\nfilename = \"test.edf\"\nchs, fs, data_raw = read_edf(filename)\nprint(\"\\n\\tFile: {}\".format(filename))\nprint(\"\\tSampling rate: {:.2f} Hz\".format(fs))\nprint(\"\\tData shape: {:d} samples x {:d} channels\".format(data_raw.shape[0], data_raw.shape[1]))\nprint(\"\\tChannels:\")\nfor ch in chs: print \"\\t{:s}\".format(ch), \n```\n\n    {'startdate': '14.10.08', 'digimin': [-30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001, -30001], 'physmin': [-28.195, -31.263, -31.614, -25.298, -27.77, -25.518, -40.338, -39.106, -57.314, -52.697, -29.888, -32.122, -27.329, -25.885, -39.29, -56.341, -30.092, -30.501, -37.138, -28.687, -30.758, -25.496, -30.673, -19.727, -26.854, -31.31, -48.835, -44.015, -32.758, -36.985], 'reserved': '                                            ', 'samples_per_record': [250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0, 250.0], 'recordingID': 'Startdate 14-OCT-2008 X X X                                                     ', 'physdime': ['uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV', 'uV'], 'patientID': 'X X 01-JAN-0000 X                                                               ', 'digimax': [30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000, 30000], 'physmax': [28.195, 31.263, 31.614, 25.298, 27.77, 25.518, 40.338, 39.106, 57.314, 52.697, 29.888, 32.122, 27.329, 25.885, 39.29, 56.341, 30.092, 30.501, 37.138, 28.687, 30.758, 25.496, 30.673, 19.727, 26.854, 31.31, 48.835, 44.015, 32.758, 36.985], 'channels': 30, 'records': 192, 'length': 7936, 'version': '0       ', 'transducer': ['AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode', 'AgAgCl', 'electrode'], 'starttime': '20.48.12', 'duration': 1.0, 'channelname': 'Fp1             Fp2             F3              F4              C3              C4              P3              P4              O1              O2              F7              F8              T7              T8              P7              P8              Fz              Cz              Pz              AFz             AF3             AF4             FC3             FC4             FT9             FT10            TP9             TP10            CP5             CP6             ', 'prefilt': []}\n    \n    \tFile: test.edf\n    \tSampling rate: 250.00 Hz\n    \tData shape: 48000 samples x 30 channels\n    \tChannels:\n    \tFp1 \tFp2 \tF3 \tF4 \tC3 \tC4 \tP3 \tP4 \tO1 \tO2 \tF7 \tF8 \tT7 \tT8 \tP7 \tP8 \tFz \tCz \tPz \tAFz \tAF3 \tAF4 \tFC3 \tFC4 \tFT9 \tFT10 \tTP9 \tTP10 \tCP5 \tCP6\n\n\n## (2) Pre-processing\n\nEEG data is usually band-pass filtered before microstate clustering. The package contains a zero-phase 6-th order Butterworth band-pass filter as provided by SciPy. The input is (1) the data to be filtered as a NumPy array of shape (n_samples, n_channels), (2) a tuple defining the desired frequency band in Hz, and (3) the EEG sampling rate in Hz.\n\n\n```python\ndata = bp_filter(data_raw, (1, 35), fs)\n```\n\n    /usr/local/lib/python2.7/dist-packages/scipy/signal/_arraytools.py:45: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.\n      b = a[a_slice]\n\n\n## (3) Visualize data (PCA-1)\n\nA basic data visualization tool is provided to get an idea of the temporal structure of the EEG data set. We use principle component analysis as provided in the scikit-learn package and plot the time course of the first principal component to represent the dominant component of the data set. Using the test.edf file, we find amplitude modulated oscillations, mainly in the alpha frequency band (8-12), as expected in a wakeful resting condition.\n\n\n```python\npca = PCA(copy=True, n_components=1, whiten=False)\npca1 = pca.fit_transform(data)[:,0]\nplot_data(pca1, fs)\n```\n\nAlternatively, only a segment of data can be visualized to better recognize alpha oscillations.\n\n\n```python\nt0, t1 = 1000, 3000\nplot_data(pca1[t0:t1], fs)\n```\n\n## (4) Clustering of the microstate maps\n\nWe are now ready to apply the microstate clustering algorithm to the filtered data. We implemented five different clustering methods (AAHC, modified k-means, k-medoids, PCA, Fast-ICA), as detailed in [4].  \nHere, we will run the modified K-means algorithm as given by Pascual-Marqui [1], implemented as the function 'kmeans' in the eeg_microstates.py file [3]. The function variables should be self-explaining and are further documented in the source file following the PEP 8 styleguide.    \nAs the initial microstate ordering returned by the stochastic K-means algorithm is random, we provide a tool to re-label the microstates interactively. The standard ordering follows the geometry of the maps. Map A has a diagonal direction connecting the upper (frontal) left and lower (occipital) right corners, map B is diagonal in the opposite direction, map C has a horizontal orientation and map D is often circular. Sometimes, slightly different maps are generated. We mostly observed the occurrence of a map D with a vertical axis instead of a circular pattern. In this case, you can either accept the results and proceed, or re-cluster the data set as the results of the K-means algorithm differ between runs.\nModified K-means clustering and all information-theoretical computations can be run for any number of microstates. The desired number of microstates is given by the user as the argument 'n_maps' of the 'kmeans' function. If n_maps is not provided, the default value n_maps=4 is used.\n\n\n```python\nmode = [\"aahc\", \"kmeans\", \"kmedoids\", \"pca\", \"ica\"][1]\nprint(\"Clustering algorithm: {:s}\".format(mode))\n```\n\n    Clustering algorithm: kmeans\n\n\n\n```python\nn_maps = 4\nlocs = []\nmaps, x, gfp_peaks, gev = clustering(data, fs, chs, locs, mode, n_maps, doplot=True)\n```\n\nYou can also inspect the source code of the function:\n\n\n```python\nimport inspect\n# c=inspect.getsourcelines(kmeans) # activate by uncomment\n# for l in c[0]: print l\n```\n\nWhen the algorithm terminates, the global explained variance (GEV) of the computed microstate time series is shown. For the test file, the GEV should give approximately 0.73. In other words, the microstate sequence explains ca. 73% of the electrical potential's spatial variance over time.  \n\nThe first return variable of the kmeans function is an array containing the microstate maps row-wise. The second return variable is the microstate sequence corresponding to the EEG data that was used as input. The sequence was generated as part of the kmeans optimizations by back-fitting into the EEG time series, and the sequence corresponding to the best K-means run is returned.  \nOn this sequence all subsequent tests will be run. The sequence contains the microstate labels as numbers, $\\{A, B, C, D\\} \\rightarrow \\{0, 1, 2, 3\\}$, in order to accelerate information-theoretical computations. Using numbers, the microstate label can directly be used as an index in arrays and matrices. If you want to test microstate sequences generated by other another software, the sequence must be converted to numerical values $0, ..., n_{maps}-1$ before using the functions of this package.\n\n## (5) Basic microstate statistics\n\nWe will now look at some basic statistical properties of the microstate sequence returned by the kmeans function. The empirical symbol distribution $\\hat{p}$ quantifies the relative frequency of each microstate map. It is equivalent to the so-called 'ratio of time covered' (RTT) used in some EEG microstate publications. The transition matrix $\\hat{T}$ contains the transition probabilities between all pairs of microstate labels. To get a feeling of the temporal dynamics of the EEG's spatial variance, we also compute the number of GFP peaks per second. The value is roughly 2 x the dominant EEG frequency band. In our case, the dominant frequency is a 10 Hz alpha rhythm and we observe approx. 21.5 GFP peaks per second.\n\n\n```python\np_hat = p_empirical(x, n_maps)\nT_hat = T_empirical(x, n_maps)\nprint(\"\\n\\t\\tEmpirical symbol distribution (RTT):\\n\")\nfor i in range(n_maps): print(\"\\t\\tp_{:d} = {:.3f}\".format(i, p_hat[i]))\nprint(\"\\n\\t\\tEmpirical transition matrix:\\n\")\nprint_matrix(T_hat)\npps = len(gfp_peaks) / (len(x)/fs)  # peaks per second\nprint(\"\\n\\t\\tGFP peaks per sec.: {:.2f}\".format(pps))\nprint(\"\\n\\t\\tGlobal explained variance (GEV) per map:\")\nprint \"\\t\\t\" + str(gev)\nprint(\"\\n\\t\\ttotal GEV: {:.2f}\".format(gev.sum()))\n```\n\n    \n    \t\tEmpirical symbol distribution (RTT):\n    \n    \t\tp_0 = 0.222\n    \t\tp_1 = 0.240\n    \t\tp_2 = 0.264\n    \t\tp_3 = 0.275\n    \n    \t\tEmpirical transition matrix:\n    \n    \t\t|0.771 0.094 0.058 0.076|\n    \t\t|0.063 0.769 0.112 0.056|\n    \t\t|0.063 0.055 0.786 0.096|\n    \t\t|0.070 0.072 0.061 0.797|\n    \n    \t\tGFP peaks per sec.: 21.51\n    \n    \t\tGlobal explained variance (GEV) per map:\n    \t\t[0.10284771 0.13338401 0.27586287 0.17435817]\n    \n    \t\ttotal GEV: 0.69\n\n\n## (6) Shannon entropy and entropy rate of the microstate sequence\n\nThe information-theoretical characterization of the microstate time series starts with the calculation of the empirical Shannon entropy $\\hat{H}$ of the sequence:\n\n$$\n\\begin{align}\n\\hat{H} & = -\\sum_i \\hat{p}(i) \\log \\hat{p}(i)\n\\end{align}\n$$\n\nwhere the index $i$ runs over the microstate labels. The base of the logarithm is not important. We use the natural logarithm to the base $e$ (Euler's number) and therefore measure information in 'nats', in analogy to bits when using $\\log_2$.\n\n\n```python\nh_hat = H_1(x, n_maps)\nh_max = max_entropy(n_maps)\nprint(\"\\n\\t\\tEmpirical entropy H = {:.2f} (max. entropy: {:.2f})\\n\".format(h_hat, h_max) )\n```\n\n    \n    \t\tEmpirical entropy H = 1.38 (max. entropy: 1.39)\n    \n\n\nThe maximum entropy possible for any sequence composed of four symbols is $\\log(4) \\approx 1.39$, and the minimum entropy is zero. We see that the test sequence almost achieves the maximum entropy. As entropy can be interpreted as the amount of surprise or randomness, this result suggests a lack of predictable temporal features in the microstate sequence. However, we will show that the sequence does contain temporal structure, mainly in the form of periodicities in the range of the main EEG frequency bands.\n\nNext, the entropy rate of the sequence is estimated from a set of joint Shannon entropies $H_k=H(\\mathbf{X}_{n}^{(k)})$ for different history lengths $k$. The estimated entropy rate is the slope of the linear fit $k$ vs. $H_k$. The intercept is the so-called excess entropy, which is not further investigated here.\n\n\n```python\nh_rate, _ = excess_entropy_rate(x, n_maps, kmax=8, doplot=True)\nh_mc = mc_entropy_rate(p_hat, T_hat)\nprint(\"\\n\\t\\tEmpirical entropy rate h = {:.2f}\".format(h_rate))\nprint(\"\\t\\tTheoretical MC entropy rate h = {:.2f}\".format(h_mc))\n```\n\n## (7) Markov tests\n\nWe will first test the Markov properties of order 0, 1 and 2 for the EEG test file. For the details of the testing procedure, see the attached manuscript and the code documentation in the source file.\n\n\n```python\nalpha = 0.01\np_M0 = testMarkov0(x, n_maps, alpha)\np_M1 = testMarkov1(x, n_maps, alpha)\np_M2 = testMarkov2(x, n_maps, alpha)\np_vals_geo = geoTest(x, n_maps, 1000./fs, alpha)\n```\n\n    \t\tZERO-ORDER MARKOVIANITY:\n    \t\tp: 0.00e+00 | t: 59858.388 | df: 9.0\n    \n    \t\tFIRST-ORDER MARKOVIANITY:\n    \t\tp: 1.64e-131 | t: 736.258 | df: 36.0\n    \n    \t\tSECOND-ORDER MARKOVIANITY:\n    \t\tp: 1.33e-84 | t: 760.946 | df: 144.0\n    \n    \t\tGEOMETRIC DISTRIBUTION of lifetimes:\n    \n    \n    \t\tTesting the distribution of symbol # 0\n    \t\tp: 8.50e-21 | t: 164.047 | df: 29.0\n    \t\tG-test (log-likelihood) p: 2.40e-08, g: 91.168, df: 29.0\n    \t\tG-test (Pearson Chi2) p: 3.83e-07, g: 83.258, df: 29.0\n    \n    \t\tTesting the distribution of symbol # 1\n    \t\tp: 5.84e-14 | t: 123.501 | df: 28.0\n    \t\tG-test (log-likelihood) p: 9.17e-05, g: 64.943, df: 28.0\n    \t\tG-test (Pearson Chi2) p: 2.12e-04, g: 62.187, df: 28.0\n    \n    \t\tTesting the distribution of symbol # 2\n    \t\tp: 1.15e-23 | t: 173.008 | df: 26.0\n    \t\tG-test (log-likelihood) p: 1.01e-09, g: 94.568, df: 26.0\n    \t\tG-test (Pearson Chi2) p: 6.40e-08, g: 83.316, df: 26.0\n    \n    \t\tTesting the distribution of symbol # 3\n    \t\tp: 2.13e-49 | t: 304.976 | df: 26.0\n    \t\tG-test (log-likelihood) p: 6.41e-22, g: 163.645, df: 26.0\n    \t\tG-test (Pearson Chi2) p: 1.99e-19, g: 150.128, df: 26.0\n\n\nThe statistical Markovianity test show that our test sequence does not have the Markov property of the tested orders. This means that there are memory effects in the series which we will further explore.\n\n## (8) Stationarity test\n\nNext, we will test if the transition matrix $\\hat{T}$ is time-stationary or if the matrix elements change significantly over time. You can provide a specific window length L for testing or use the default value of 5000 samples.\n\n\n```python\ntry:\n    L = int(raw_input(\"\\t\\tEnter block size: \"))\nexcept:\n    L = 5000\np3 = conditionalHomogeneityTest(x, n_maps, L, alpha)\n```\n\n    \t\tEnter block size: \n    \n    \t\tCONDITIONAL HOMOGENEITY (three-way table):\n    \t\tSplit data in r = 9 blocks of length 5000.\n    \t\tp: 3.37e-06 | t: 171.631 | df: 96.0\n\n\nWe find that the given transition matrix is not time-stationary.\n\n## (9) Symmetry test\n\nWe will now test if the transition matrix is symmetric. In other words, we test if the transitions $A \\rightarrow B$ and $B \\rightarrow A$ occur with the same probability or not.\n\n\n```python\np4 = symmetryTest(x, n_maps, alpha)\n```\n\n    \n    \t\tSYMMETRY:\n    \t\tp: 1.61e-82 | t: 396.469 | df: 6.0\n\n\nThe transition matrix of the test microstate sequence is not symmetric.\n\n## (10) Markov surrogate example\n\nTo test our statistical procedures and to construct surrogate data sets from which confidence intervals for further information-theoretical quantities can be computed, we will synthesize first-order Markov chains with symbol distribution and transition matrix identical to the experimental EEG data set. This is possible because a first-order Markov chain is completely defined by an initial symbol distribution and a transition matrix for first-order (single time step) transitions.\n\n\n```python\nx_mc = surrogate_mc(p_hat, T_hat, n_maps, len(x))\np_surr = p_empirical(x_mc, n_maps)\nT_surr = T_empirical(x_mc, n_maps)\nprint(\"\\n\\t\\tSurrogate symbol distribution:\\n\")\nfor i in range(n_maps): print(\"\\t\\tp_{:d} = {:.3f}\".format(i, p_surr[i]))\nprint( \"\\n\\t\\tSurrogate transition matrix:\\n\" )\nprint_matrix(T_surr)\n```\n\n    \n    \t\tSurrogate symbol distribution:\n    \n    \t\tp_0 = 0.217\n    \t\tp_1 = 0.251\n    \t\tp_2 = 0.259\n    \t\tp_3 = 0.273\n    \n    \t\tSurrogate transition matrix:\n    \n    \t\t|0.767 0.098 0.056 0.079|\n    \t\t|0.064 0.773 0.104 0.059|\n    \t\t|0.060 0.060 0.787 0.093|\n    \t\t|0.069 0.074 0.062 0.795|\n\n\nWe observe that the symbol distribution and the transition matrix are equivalent, within some stochastic margin, to the experimental data. A quantitative analysis of Markov surrogate errors is contained in [2].\n\n## (11) Markov tests for surrogate Markov data\n\nIt will now be shown that the Markov surrogates fulfill the expected properties, or vice versa, that our Markovianity and stationarity tests work well with our surrogate data. This means that we can analyze experimental data series to find memory effects beyond a first-order Markov model.\n\n\n```python\np_M0_mc = testMarkov0(x_mc, n_maps, alpha)\np_M1_mc = testMarkov1(x_mc, n_maps, alpha)\np_M2_mc = testMarkov2(x_mc, n_maps, alpha)\np_vals_geo_mc = geoTest(x_mc, n_maps, 1000./fs, alpha)\n```\n\n    \t\tZERO-ORDER MARKOVIANITY:\n    \t\tp: 0.00e+00 | t: 59734.431 | df: 9.0\n    \n    \t\tFIRST-ORDER MARKOVIANITY:\n    \t\tp: 2.01e-01 | t: 42.847 | df: 36.0\n    \n    \t\tSECOND-ORDER MARKOVIANITY:\n    \t\tp: 2.64e-01 | t: 154.297 | df: 144.0\n    \n    \t\tGEOMETRIC DISTRIBUTION of lifetimes:\n    \n    \n    \t\tTesting the distribution of symbol # 0\n    \t\tp: 8.01e-01 | t: 20.680 | df: 27.0\n    \t\tG-test (log-likelihood) p: 9.99e-01, g: 9.997, df: 27.0\n    \t\tG-test (Pearson Chi2) p: 1.00e+00, g: 8.853, df: 27.0\n    \n    \t\tTesting the distribution of symbol # 1\n    \t\tp: 3.23e-01 | t: 40.379 | df: 37.0\n    \t\tG-test (log-likelihood) p: 9.86e-01, g: 20.632, df: 37.0\n    \t\tG-test (Pearson Chi2) p: 9.93e-01, g: 19.137, df: 37.0\n    \n    \t\tTesting the distribution of symbol # 2\n    \t\tp: 2.51e-01 | t: 42.365 | df: 37.0\n    \t\tG-test (log-likelihood) p: 9.89e-01, g: 20.253, df: 37.0\n    \t\tG-test (Pearson Chi2) p: 9.94e-01, g: 18.783, df: 37.0\n    \n    \t\tTesting the distribution of symbol # 3\n    \t\tp: 4.84e-04 | t: 59.410 | df: 28.0\n    \t\tG-test (log-likelihood) p: 4.57e-01, g: 28.132, df: 28.0\n    \t\tG-test (Pearson Chi2) p: 6.01e-01, g: 25.482, df: 28.0\n\n\nThe Markov surrogate clearly fulfills the expected theoretical properties. The zero-order Markov hypothesis is rejected while the first-order and second-order properties are accepted. The theoretically equivalent, but numerically different test for geometric lifetime distributions asserts the geometric lifetime distribution of all microstate maps.\n\n## (12) Stationarity test for surrogate Markov data\n\nWe expect the Markov surrogate to be time-stationary as the same transition matrix has been used to generate the entire sequence. The test results show that indeed, the Markov surrogate is correctly classified as time-stationary. This means that we can identify non-stationarity in experimental data sets statistically.\n\n\n```python\ntry:\n    L = int(raw_input(\"\\t\\tEnter block size: \"))\nexcept:\n    L = 5000\np3_mc = conditionalHomogeneityTest(x_mc, n_maps, L, alpha)\n```\n\n    \t\tEnter block size: \n    \n    \t\tCONDITIONAL HOMOGENEITY (three-way table):\n    \t\tSplit data in r = 9 blocks of length 5000.\n    \t\tp: 3.42e-01 | t: 101.058 | df: 96.0\n\n\n## (13) Symmetry test for surrogate Markov data\n\nAs the experimental EEG transtion matrix is used to generate the Markov surrogate, the surrogate's transition matrix is also asymmetric.\n\n\n```python\np4_mc = symmetryTest(x_mc, n_maps, alpha)\n```\n\n    \n    \t\tSYMMETRY:\n    \t\tp: 8.39e-60 | t: 290.613 | df: 6.0\n\n\n## (14) Time-lagged mutual information: empirical vs. Markov\n\nMutual information for time lag k, $I(k)$, is defined as the difference between the entropy (uncertainty) of the microstate sequence at time point $t+k$, and the conditional entropy at time point $t+k$ given the state at time $t$. Mutual information thus quantifies the uncertainty about the state at $t+k$ that is not represented by the previous time point $t$.\n\n$$\n\\begin{align}\nI(k) & = H(X_{t+k}) - H(X_{t+k} \\mid X_k)\n\\end{align}\n$$\n\nAs an analogy to the autocorrelation function (ACF) for metric time series, we will call this information-theoretic quantity the autoinformation function (AIF). Whilte the ACF uses linear correlation as a dependency measure for metric time series, the AIF uses mutual information to quantify dependencies in symbolic sequences.  \nWe can now compute the time-lagged mutual information function of the microstate sequence and compare it to a set of Markov surrogates, from which a confidence interval under the first-order Markovian null hypothesis is constructed. We here use 10 Markov surrogates and compute the two-sided 99% percentile.  \n\n\n```python\nl_max = 100\nn_mc = 10\naif = mutinf(x, n_maps, l_max)\nprint(\"\\n\\t\\tComputing n = {:d} Markov surrogates...\\n\".format(n_mc))\naif_array = mutinf_CI(p_hat, T_hat, len(x), alpha, n_mc, l_max)\npct = np.percentile(aif_array,[100.*alpha/2.,100.*(1-alpha/2.)],axis=0)\nplt.ioff()\nfig = plt.figure(1, figsize=(20,5))\nfig.patch.set_facecolor('white')\nt = np.arange(l_max)*1000./fs\nplt.semilogy(t, aif, '-sk', linewidth=3, label='AIF (EEG)')\nplt.semilogy(t, pct[0,:], '-k', linewidth=1)\nplt.semilogy(t, pct[1,:], '-k', linewidth=1)\nplt.fill_between(t, pct[0,:], pct[1,:], facecolor='gray', alpha=0.5, label='AIF (Markov)')\nplt.xlabel(\"time lag [ms]\", fontsize=20, fontweight=\"bold\")\nplt.ylabel(\"AIF [nats]\", fontsize=20, fontweight=\"bold\")\nplt.legend(fontsize=22)\nax = plt.gca()\nax.set_xticklabels(ax.get_xticks(), fontsize=18, fontweight='normal')\nax.set_yticklabels(ax.get_yticks(), fontsize=18, fontweight='normal')\nplt.tight_layout()\nplt.show()\n```\n\nThe figure generated by the code above shows the autoinformation function (AIF) along with Markovian confidence intervals. The AIF summarizes memory effects in the test microstate sequence as identified by mutual information. It is observed that the AIF of experimental data (black line and squares) shows clear periodicities and comparison with the Markovian confidence interval (gray-shaded area) shows that these peaks are statistically significant.  \nWe can thus show that EEG microstates recur in a regular way. In other words, the microstate sequences passes through the graph of state transitions in a circular way. The transitions do not do so in a completely deterministic way, as any state transition is possible at any time, but we show that there are preferred closed paths along the state transition graph.\n\n## (15) Summary and reporting results\n\nThe results can be summarized for scientific reporting as follows. Please note that *fixed numerical values are shown here*, i.e. the results of a specifc run of the algorithm. As clustering results vary slightly between runs, the exact numerical values may differ from the results obtained above.\n\n1. We analyzed 192 seconds of resting state EEG sampled at 250 Hz. The 1-35 Hz band-pass filtered data set showed  21.51 GFP peaks per second and was clustered into 4 microstates, labelled A-D.\n\n2. Static properties:\n    * The microstate distribution was $p(A)=0.222$, $p(B)=0.240$, $p(C)=0.264$, and $p(D)=0.275$.\n    * The four microstates explained 69% of the total data variance (GEV).\n    * In information-theoretical terms, the four microstates produced a Shannon entropy of $H=1.38$ nats, where the upper bound for a 4-state process is $H_{max}=1.39$ nats. The empirical entropy rate was $h=0.73$ nats, and the expected value for the analogous first-order Markov process is $h=0.76$ nats.\n\n3. Dynamic properties:\n    * The transition probabilities between all pairs of microstates are summarized in the transition matrix T:\n    \\begin{equation*}\n    T =  \\begin{vmatrix}\n    0.771 & 0.094 & 0.058 & 0.076 \\\\\n\t0.063 & 0.769 & 0.112 & 0.056 \\\\\n\t0.063 & 0.055 & 0.786 & 0.096 \\\\\n\t0.070 & 0.072 & 0.061 & 0.797 \\\\\n    \\end{vmatrix}\n    \\end{equation*}\n    * The transition matrix T proved to be asymmetric ($p \\lt 10^{-80}$).\n\n4. Information-theoretical properties. Using a significance level of $\\alpha = 0.01$, we found that:\n    * The microstate sequence does not fulfill the Markov property of order 0, 1, or 2. We conclude that the microstate sequence has extended memory effects.\n    * During the EEG recording, the transition matrix of the microstate sequence is not constant (it is non-stationary), when tested for a partition into 9 blocks and 5000 samples per block ($p=3.37 \\times 10^{-6}$). This result should be taken as a precaution when using methods that require time stationarity (e.g. long-range memory interpretations of Hurst exponents).\n    * Non-Markovianity and non-stationarity are at least partially explained by a periodic recurrence of the microstates, as shown by the time-lagged mutual information function (or autoinformation function, AIF). For time lags up to 400 msec., the EEG's AIF lies above the (first-order) Markov confidence interval and shows distinct peaks at multiples of approx. 50 msec (half the period of the underlying alpha rhythm).\n\n\n### Code acceleration\n\nIf you ran the code above on your computer, you will have noticed that the AIF calculation determines the computation time of the procedure. The code can be accelerated using Cython, Numba or an external Julia function, for instance. To maximize portability and minimize the number of operating system dependencies, we did not include these accelerations in the code. However, the mentioned methods are implemented with little effort. Accelerated code can also be obtained from the author.\nThe eeg_microstates.py script can be run from the console using the -mc parameter that defines the number of Markov surrogates. The number of surrogates will define the width and smoothness of the confidence interval. Empirically, we suggest a minimum number of 50-100 surrogates.\n\n## Conclusions\n\nIf you have arrived here, you should have completed the tutorial successfully. You should be familiar with the functionality provided by this software and have a good impression how to process larger data sets to obtain group statistics.\n", "meta": {"hexsha": "edd788fe329175cf68e6be614b80afb4608c2d9b", "size": 856502, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "python2/eeg_microstates.ipynb", "max_stars_repo_name": "Frederic-vW/eeg_microstates", "max_stars_repo_head_hexsha": "0cca43fcc02772cb5171b48b5878f66303e0c903", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-06-13T15:02:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T09:10:29.000Z", "max_issues_repo_path": "python2/eeg_microstates.ipynb", "max_issues_repo_name": "Frederic-vW/eeg_microstates", "max_issues_repo_head_hexsha": "0cca43fcc02772cb5171b48b5878f66303e0c903", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-11-26T11:50:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-30T23:04:05.000Z", "max_forks_repo_path": "python2/eeg_microstates.ipynb", "max_forks_repo_name": "Frederic-vW/eeg_microstates", "max_forks_repo_head_hexsha": "0cca43fcc02772cb5171b48b5878f66303e0c903", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2019-11-04T22:43:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-18T16:45:24.000Z", "avg_line_length": 691.2849071832, "max_line_length": 457129, "alphanum_fraction": 0.937593841, "converted": true, "num_tokens": 9409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.0646534847517276, "lm_q1q2_score": 0.03056063394807274}}
{"text": "```python\nfrom IPython.core.display import HTML, Image\ncss_file = 'style.css'\nHTML(open(css_file, 'r').read())\n```\n\n\n\n\n<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:100,300,400,500,700,800,900,100italic,300italic,400italic,500italic,700italic,800italic,900italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Arvo:400,700,400italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=PT+Mono' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Shadows+Into+Light' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Philosopher:400,700,400italic,700italic' rel='stylesheet' type='text/css'>\n\n<style>\n\n@font-face {\n    font-family: \"Computer Modern\";\n    src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');\n}\n\n#notebook_panel { /* main background */\n    background: #ddd;\n    color: #000000;\n}\n\n\n\n/* Formatting for header cells */\n.text_cell_render h1 {\n    font-family: 'Philosopher', sans-serif;\n    font-weight: 400;\n    font-size: 2.2em;\n    line-height: 100%;\n    color: rgb(0, 80, 120);\n    margin-bottom: 0.1em;\n    margin-top: 0.1em;\n    display: block;\n}\t\n.text_cell_render h2 {\n    font-family: 'Philosopher', serif;\n    font-weight: 400;\n    font-size: 1.9em;\n    line-height: 100%;\n    color: rgb(200,100,0);\n    margin-bottom: 0.1em;\n    margin-top: 0.1em;\n    display: block;\n}\t\n\n.text_cell_render h3 {\n    font-family: 'Philosopher', serif;\n    margin-top:12px;\n    margin-bottom: 3px;\n    font-style: italic;\n    color: rgb(94,127,192);\n}\n\n.text_cell_render h4 {\n    font-family: 'Philosopher', serif;\n}\n\n.text_cell_render h5 {\n    font-family: 'Alegreya Sans', sans-serif;\n    font-weight: 300;\n    font-size: 16pt;\n    color: grey;\n    font-style: italic;\n    margin-bottom: .1em;\n    margin-top: 0.1em;\n    display: block;\n}\n\n.text_cell_render h6 {\n    font-family: 'PT Mono', sans-serif;\n    font-weight: 300;\n    font-size: 10pt;\n    color: grey;\n    margin-bottom: 1px;\n    margin-top: 1px;\n}\n\n.CodeMirror{\n        font-family: \"PT Mono\";\n        font-size: 100%;\n}\n\n</style>\n\n\n\n\n\n\n```python\nfrom IPython.core.display import HTML, Image\ncss_file = 'style.css'\nHTML(open(css_file, 'r').read())\n```\n\n\n\n\n<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:100,300,400,500,700,800,900,100italic,300italic,400italic,500italic,700italic,800italic,900italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Arvo:400,700,400italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=PT+Mono' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Shadows+Into+Light' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Philosopher:400,700,400italic,700italic' rel='stylesheet' type='text/css'>\n\n<style>\n\n@font-face {\n    font-family: \"Computer Modern\";\n    src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');\n}\n\n#notebook_panel { /* main background */\n    background: #ddd;\n    color: #000000;\n}\n\n\n\n/* Formatting for header cells */\n.text_cell_render h1 {\n    font-family: 'Philosopher', sans-serif;\n    font-weight: 400;\n    font-size: 2.2em;\n    line-height: 100%;\n    color: rgb(0, 80, 120);\n    margin-bottom: 0.1em;\n    margin-top: 0.1em;\n    display: block;\n}\t\n.text_cell_render h2 {\n    font-family: 'Philosopher', serif;\n    font-weight: 400;\n    font-size: 1.9em;\n    line-height: 100%;\n    color: rgb(200,100,0);\n    margin-bottom: 0.1em;\n    margin-top: 0.1em;\n    display: block;\n}\t\n\n.text_cell_render h3 {\n    font-family: 'Philosopher', serif;\n    margin-top:12px;\n    margin-bottom: 3px;\n    font-style: italic;\n    color: rgb(94,127,192);\n}\n\n.text_cell_render h4 {\n    font-family: 'Philosopher', serif;\n}\n\n.text_cell_render h5 {\n    font-family: 'Alegreya Sans', sans-serif;\n    font-weight: 300;\n    font-size: 16pt;\n    color: grey;\n    font-style: italic;\n    margin-bottom: .1em;\n    margin-top: 0.1em;\n    display: block;\n}\n\n.text_cell_render h6 {\n    font-family: 'PT Mono', sans-serif;\n    font-weight: 300;\n    font-size: 10pt;\n    color: grey;\n    margin-bottom: 1px;\n    margin-top: 1px;\n}\n\n.CodeMirror{\n        font-family: \"PT Mono\";\n        font-size: 100%;\n}\n\n</style>\n\n\n\n\n\n\n```python\nfrom sympy import init_printing, Matrix, symbols, eye\nfrom warnings import filterwarnings\n```\n\n\n```python\ninit_printing(use_latex = 'mathjax')\nfilterwarnings('ignore')\n```\n\n# Markov matrices and steady state\n# Projections and Fourier series\n\n## Markov matrix\n\n* Consider the follow Markov matrix (transition matrix)\n\n\n```python\nA = Matrix([[0.1, 0.01, 0.3], [0.2, 0.99, 0.3], [0.7, 0, 0.4]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}0.1 & 0.01 & 0.3\\\\0.2 & 0.99 & 0.3\\\\0.7 & 0 & 0.4\\end{matrix}\\right]$$\n\n\n\n* All the column entries add to 1 (also true for powers of the matrix)\n* All entries &#8805; 0 (also true for powers of the matrix)\n* There will be an eigenvalue of 1\n* All other eigenvalues will have an absolute value of at most 1\n* For difference equations we will have the following\n$$ {u}_{k}={A}^{k}{u}_{0}={c}_{1}{\\lambda}_{1}^{k}{x}_{1}+{c}_{1}{\\lambda}_{2}^{k}{x}_{2}+{\\dots} $$\n* Thus for the eigenvalues other than 1, successive powers will lead to those terms approaching zero and a steady state being reached by the term with the eigenvalue of 1\n\n\n```python\nA.eigenvals()\n```\n\n\n\n\n$$\\begin{Bmatrix}1 : 1, & \\frac{49}{200} + \\frac{3 \\sqrt{1009}}{200} : 1, & - \\frac{3 \\sqrt{1009}}{200} + \\frac{49}{200} : 1\\end{Bmatrix}$$\n\n\n\n* All the components of the eigenvector of the eigenvalue 1 is positive\n\n\n```python\nA.eigenvects()\n```\n\n\n\n\n$$\\begin{bmatrix}\\begin{pmatrix}1.0, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}0.857142857142857\\\\47.1428571428571\\\\1.0\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}0.721471405228058, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}0.459244864611511\\\\-1.45924486461151\\\\1.0\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}-0.231471405228058, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}-0.902102007468654\\\\-0.0978979925313461\\\\1.0\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}$$\n\n\n\n* If the matrix A - 1&#955; is singular, then the eigenvalue is 1\n\n\n```python\nA - eye(3) # A minus the identity matrix\n```\n\n\n\n\n$$\\left[\\begin{matrix}-0.9 & 0.01 & 0.3\\\\0.2 & -0.01 & 0.3\\\\0.7 & 0 & -0.6\\end{matrix}\\right]$$\n\n\n\n\n```python\n(A - eye(3)).det() # A computer peculiarity to inidcate 0\n```\n\n\n\n\n$$-3.03576608295941 \\cdot 10^{-18}$$\n\n\n\n* The sum of the entries in each column is now zero\n* We would like a proof involving this (sum of column entries equal zero) as an assumption to give a singular matrix, without having to calculate the determinant\n* It is easy to see that the rows are linearly dependent and that would give proof of a singular matrix\n* Look also at the nullspace of A<sup>T</sup>\n\n\n```python\nA_1t = A - eye(3)\n(A_1t.transpose()).nullspace()\n```\n\n\n\n\n$$\\begin{bmatrix}\\end{bmatrix}$$\n\n\n\n\n```python\n(A.transpose()).nullspace()\n```\n\n\n\n\n$$\\begin{bmatrix}\\end{bmatrix}$$\n\n\n\n\n```python\nA.nullspace()\n```\n\n\n\n\n$$\\begin{bmatrix}\\end{bmatrix}$$\n\n\n\n\n```python\n(A - eye(3)).rref()\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}1.0 & 0 & 0\\\\0 & 1.0 & 0\\\\0 & 0 & 1.0\\end{matrix}\\right], & \\begin{bmatrix}0, & 1, & 2\\end{bmatrix}\\end{pmatrix}$$\n\n\n\n* Note how the eigenvalues of A and A<sup>T</sup> are the same\n\n\n```python\nA.eigenvals() == A.transpose().eigenvals()\n```\n\n\n\n\n    True\n\n\n\n* The proof of this lies in the fact that we calculate the eigenvalue(s) by the following equation\n$$ \\left|{A}-{\\lambda}{I}\\right|={0} $$\n* The eigenvalue(s) must also solve this equation\n$$ \\left|{A}^{T}-{\\lambda}{I}\\right|={0} $$\n* Since &#955;I=&#955;I<sup>T</sup> and both of these equations eqal the same value (0), the eigenvalue(s) must be equal\n\n### Example of a Markov matrix\n\n* Consider the population of two (isolated) states (*c* and *m*)\n* Over time there is movement between the two (no loss or entry from outside the system)\n* We consider the following system fo movement (difference equation)\n$$ {u}_{k+1}={A}{u}_{k} $$\n* We can create the following matrix equation\n$$ \\begin{bmatrix} { u }_{ c } \\\\ { u }_{ m } \\end{bmatrix}_{k+1}=\\begin{bmatrix} 0.9 & 0.2 \\\\ 0.1 & 0.8 \\end{bmatrix}\\begin{bmatrix} { u }_{ c } \\\\ { u }_{ m } \\end{bmatrix}_{k} $$\n\n\n```python\nA = Matrix([[0.9, 0.2], [0.1, 0.8]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}0.9 & 0.2\\\\0.1 & 0.8\\end{matrix}\\right]$$\n\n\n\n* Let's start at time, *t*=0 (or in our case *k*=0), with the whole population in state *m*\n* Because the system is closed, the total population stays at 1000\n\n\n```python\nu0 = Matrix([0, 1000])\n```\n\n* After 1 time period *k*+1 will be given by the following\n\n\n```python\nu1 = A * u0\nu1\n```\n\n\n\n\n$$\\left[\\begin{matrix}200.0\\\\800.0\\end{matrix}\\right]$$\n\n\n\n\n```python\nu2 = A * u1\nu2\n```\n\n\n\n\n$$\\left[\\begin{matrix}340.0\\\\660.0\\end{matrix}\\right]$$\n\n\n\n* Where will we end up?\n* Let's look at the eigenvalues\n* One will be one and the other must be the trace minus 1 = 0.7\n\n\n```python\nA.eigenvals()\n```\n\n\n\n\n$$\\begin{Bmatrix}\\frac{7}{10} : 1, & 1 : 1\\end{Bmatrix}$$\n\n\n\n\n```python\nA.eigenvects()\n```\n\n\n\n\n$$\\begin{bmatrix}\\begin{pmatrix}0.7, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}-1.0\\\\1.0\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}1.0, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}2.0\\\\1.0\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}$$\n\n\n\n* When can look at what happens after a hundred steps using a small *while* loop\n\n\n```python\nu = Matrix([0, 1000])\ni = 0\n\nwhile i < 101:\n    u = A * u\n    i += 1\nu\n```\n\n\n\n\n$$\\left[\\begin{matrix}666.666666666668\\\\333.333333333334\\end{matrix}\\right]$$\n\n\n\n* It seems that we are at about &#8532; vs &#8531;\n* It looks suspiciously like the eigenvector of the eigenvalue 1\n\n* Remember the equation for the difference equation we used above?\n$$ {u}_{k}={A}^{k}{u}_{0}={c}_{1}{\\lambda}_{1}^{k}{x}_{1}+{c}_{1}{\\lambda}_{2}^{k}{x}_{2}+{\\dots} $$\n* We only have two terms, so this will become somewhat shortened\n\n$$ {u}_{k}={A}^{k}{u}_{0}={c}_{1}{\\lambda}_{1}^{k}{x}_{1}+{c}_{1}{\\lambda}_{2}^{k}{x}_{2} \\\\ {u}_{k}={c}_{1}{1}^{k}\\begin{bmatrix}2\\\\1\\end{bmatrix}+{c}_{1}{\\frac{7}{10}}^{k}{\\begin{bmatrix}-1\\\\1\\end{bmatrix}} \\\\ {u}_{0}={c}_{1}{1}^{0}\\begin{bmatrix}2\\\\1\\end{bmatrix}+{c}_{1}{\\left({\\frac{7}{10}}\\right)}^{0}{\\begin{bmatrix}-1\\\\1\\end{bmatrix}} \\\\ {u}_{0}={c}_{1}\\begin{bmatrix}2\\\\1\\end{bmatrix}+{c}_{1}{\\begin{bmatrix}-1\\\\1\\end{bmatrix}}=\\begin{bmatrix}0\\\\1000\\end{bmatrix} \\\\  $$\n\n\n```python\nresult = Matrix([[2, -1, 0], [1, 1, 1000]])\nresult.rref()\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}1 & 0 & \\frac{1000}{3}\\\\0 & 1 & \\frac{2000}{3}\\end{matrix}\\right], & \\begin{bmatrix}0, & 1\\end{bmatrix}\\end{pmatrix}$$\n\n\n\n* So we have *c*<sub>1</sub>=1000&#247;3 and *c*<sub>2</sub>=2000&#247;3\n\n* This results in the final solution\n$$ {u}_{k}=\\frac{1000}{3}{1}^{k}\\begin{bmatrix}2\\\\1\\end{bmatrix}+\\frac{2000}{3}{\\left({\\frac{7}{10}}\\right)}^{k}{\\begin{bmatrix}-1\\\\1\\end{bmatrix}} $$\n* Now we can work out the solution for any time step *k* and even see what happens at time approaches infinity\n* We note that the second expression disappears as *k* approaches infinity, which represents the steady state\n\n## Projections and Fourier series\n\n* Consider projections with **orthonormal** basis *q*<sub>1</sub>, *q*<sub>2</sub>, ..., *q*<sub>n</sub>\n* Any vector **v** can be expressed (expanded) as an combination of this basis\n$$ {v}={x}_{1}{q}_{1}+{x}_{2}{q}_{2}+\\dots+{x}_{n}{q}_{n} $$\n\n* Because the basis *q*<sub>i</sub> were chosen to be orthogonal taking the dot product of *q*<sub>1</sub> on both sides will cancel out all *q*<sub>&#8800;1</sub> factors\n$$ {q}_{1}^{T}{v}={x}_{1}{q}_{1}^{T}{q}_{1}+{0}+{0}+\\dots \\\\ {q}_{1}^{T}{v}={x}_{1} $$\n\n* We can see this clearly in matrix form below\n$$ \\begin{bmatrix} \\vdots  & \\vdots  & \\vdots  \\\\ { q }_{ 1 } & \\cdots  & { q }_{ n } \\\\ \\vdots  & \\vdots  & \\vdots  \\end{bmatrix}\\begin{bmatrix} { x }_{ 1 } \\\\ \\vdots  \\\\ { x }_{ n } \\end{bmatrix}=v\\\\ Qx=v\\\\ x={ Q }^{ -1 }v\\\\ \\because \\quad { Q }^{ -1 }={ Q }^{ T }\\\\ x={ Q }^{ T }v $$\n* The first component of **x**, *x*<sub>1</sub> is the the first row of Q<sup>T</sup> times **v**\n* The first row of Q<sup>T</sup> is just q<sub>1</sub>, with a bunch of zeros and just ends as we had above\n$$ {q}_{1}^{T}{v}={x}_{1} $$\n\n* The key here was to choose orthonormal basis vectors\n* Now for how this relates to Fourier series\n* We might want to write a function as an **infinite** series of expressions\n$$ f\\left( x \\right)={ a }_{ 0 }+{ a }_{ 1 }\\cos { x } +{ b }_{ 1 }\\sin { x } +{ a }_{ 2 }\\cos { 2x } +{ b }_{ 2 }\\sin { 2x } +\\dots  $$\n* The idea here is that there is still something orthogonal in each of these expressions (sine and cosine)\n* Joseph Fourier realized that he could work in function space\n* The vectors are now functions in an infinitely large space\n* The basis vectors are *cos*(*x*), *sin*(*x*), *cos*(2*x*)...\n\n* What is the inner (dot) product of functions that make them orthogonal?\n* For vectors is was the following\n$$ {v}^{T}{w}={v}_{1}{w}_{1}+{v}_{2}{w}_{2}+\\dots+{v}_{n}{w}_{n} $$\n* For functions *f* and *g* the analogue is to multiply them and the analogue of all the addition is integration\n$$ { f }^{ T }g=\\int { f\\left( x \\right)g\\left( x \\right) } dx $$\n* Now we need to know the lower and upper limit of integration\n* We note that the sine and cosine functions are periodic and repeat every 2&#960; (these are periodic functions)\n$$ \\because \\quad f\\left( x \\right)=f\\left( x+2\\pi  \\right)\\\\ { f }^{ T }g=\\int _{ 0 }^{ 2\\pi  }{ f\\left( x \\right) g\\left( x \\right)  } dx $$\n* Just like the inner product of *pairs* gave zero because of orthogonality we have the same here\n$$ \\int _{ 0 }^{ 2\\pi  }{ \\sin { x } \\cos { x }  } dx\\\\ u\\left( x \\right) =\\sin { x } \\\\ \\frac { du }{ dx } =\\cos { x } \\\\ \\cos { x } dx=du\\\\ { u }_{ 2 }\\left( 2\\pi  \\right) =\\sin { 2\\pi  } =0\\\\ { u }_{ 1 }\\left( 0 \\right) =\\sin { 0 } =0\\\\ \\int _{ 0 }^{ 0 }{ u } du=0 $$\n* With some trigonometric identities we can show the same for all the other *pairs*\n\n* A Fourier series is then an expression of a function expanded on this orthonormal basis pairs\n\n* How do we get the coefficients then?\n* Same as above, i.e. taking the inner product of both sides with *cos*(*x*)\n$$ \\int _{ 0 }^{ 2\\pi  }{ f\\left( x \\right) \\cos { x }  } dx={ a }_{ 1 }\\int _{ 0 }^{ 2\\pi  }{ { \\left( \\cos { x }  \\right)  }^{ 2 } } dx+0+0+\\dots =\\pi \\\\ { a }_{ 1 }=\\frac { 1 }{ \\pi  } \\int _{ 0 }^{ 2\\pi  }{ f\\left( x \\right) \\cos { x }  } dx $$\n\n## Example problem (Markov matrixes)\n\n### Example problem 1\n\n* A particle jumps between positions A and B with the following probabilities\n    * A to A (stays in A) probability is 0.6\n    * A to B probability is 0.4 (so all states from A add to 1.0)\n    * B to B probability is 0.8\n    * B to A probability is 0.2\n* If the particle starts in position A, what is the probability that it will be at A and B after the first step, *n*-steps, and &#8734;-steps\n\n#### Solution\n\n\n```python\nx_vect = Matrix([1, 0])\nA = Matrix([[0.6, 0.2], [0.4, 0.8]]) # Look carefully at what goes where\nA, x_vect # Displaying the two matrices\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}0.6 & 0.2\\\\0.4 & 0.8\\end{matrix}\\right], & \\left[\\begin{matrix}1\\\\0\\end{matrix}\\right]\\end{pmatrix}$$\n\n\n\n* After a single step we will have the following\n\n\n```python\nA * x_vect\n```\n\n\n\n\n$$\\left[\\begin{matrix}0.6\\\\0.4\\end{matrix}\\right]$$\n\n\n\n* A probability of 0.6 of being in position A and a probability of 0.4 of being in position B\n\n* Now look at the following trend\n$$ { p }_{ 1 }=A{ p }_{ 0 }\\\\ { p }_{ 2 }=A{ p }_{ 1 }=A\\left( { Ap }_{ 0 } \\right) ={ A }^{ 2 }{ p }_{ 0 }\\\\ { p }_{ 3 }={ A }^{ 3 }{ p }_{ 0 }\\\\ \\vdots \\\\ { p }_{ n }={ A }^{ n }{ p }_{ 0 } $$\n\n* To take the power of a matrix in python is easy, but let's remind ourselves that we need to wotk with eignevalues and eigenvectors\n* Because all the column entries add to 1, we are dealing with a Markov matrix\n* One of the eigenvalues will be 1, the trace is 1.4, therefor the other eigenvalue is 0.4\n* Remember diagonalization?\n\n\n```python\nS, D = A.diagonalize()\nS, D\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}-1.0 & 1.0\\\\1.0 & 2.0\\end{matrix}\\right], & \\left[\\begin{matrix}0.4 & 0\\\\0 & 1.0\\end{matrix}\\right]\\end{pmatrix}$$\n\n\n\n* Note the matrix of eigenvalues (diagonal) *D*\n* Note the matrix of eigenvectors\n* So for the eigenvalue of 1 we have the following eigenvector (steady state)\n$$ \\begin{bmatrix}1\\\\2\\end{bmatrix} $$\n* For the other eigenvalue we have the following eigenvector (decay)\n$$ \\begin{bmatrix}-1\\\\0\\end{bmatrix} $$\n\n$$ {u}_{k}={A}^{k}{u}_{0}={c}_{1}{\\lambda}_{1}^{k}{x}_{1}+{c}_{1}{\\lambda}_{2}^{k}{x}_{2} \\\\ {u}_{k}={c}_{1}{1}^{k}\\begin{bmatrix}1\\\\2\\end{bmatrix}+{c}_{1}{\\frac{4}{10}}^{k}{\\begin{bmatrix}-1\\\\1\\end{bmatrix}} \\\\ {u}_{0}={c}_{1}{1}^{0}\\begin{bmatrix}1\\\\2\\end{bmatrix}+{c}_{1}{\\left({\\frac{4}{10}}\\right)}^{0}{\\begin{bmatrix}-1\\\\1\\end{bmatrix}} \\\\ {u}_{0}={c}_{1}\\begin{bmatrix}1\\\\2\\end{bmatrix}+{c}_{1}{\\begin{bmatrix}-1\\\\1\\end{bmatrix}}=\\begin{bmatrix}1\\\\0\\end{bmatrix} \\\\  $$\n\n* Solving for the constants we can create an augmented matrix\n\n\n```python\nu = Matrix([[1, -1, 1], [2, 1, 0]])\nu.rref()\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}1 & 0 & \\frac{1}{3}\\\\0 & 1 & - \\frac{2}{3}\\end{matrix}\\right], & \\begin{bmatrix}0, & 1\\end{bmatrix}\\end{pmatrix}$$\n\n\n\n* This gives us the following solution\n$$ {u}_{n}=\\frac{1}{3}\\left({1}^{n}\\right)\\begin{bmatrix}1\\\\2\\end{bmatrix}+\\frac{-2}{3}{\\left({\\frac{4}{10}}\\right)}^{n}\\begin{bmatrix}-1\\\\1\\end{bmatrix} \\\\  { p\\left( A \\right)  }_{ n }=\\frac { 1 }{ 3 } +\\frac { -2 }{ 3 } { \\left( \\frac { 4 }{ 10 }  \\right)  }^{ n }\\left( -1 \\right) \\\\ { p\\left( B \\right)  }_{ n }=\\frac { 1 }{ 3 } \\left( 2 \\right) +\\frac { -2 }{ 3 } { \\left( \\frac { 4 }{ 10 }  \\right)  }^{ n }\\left( 1 \\right) $$\n\n* So at infinity it will be at position A with a probability of &#8531; and at position B with a probability of &#8532;\n\n\n```python\n(A ** 1000000) * x_vect # Just to show how easy it is just to take the power of A in python\n```\n\n\n\n\n$$\\left[\\begin{matrix}0.333333333362792\\\\0.666666666725585\\end{matrix}\\right]$$\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "f7f774cf2527c9c08a4bd8e23d0d99076dd543bc", "size": 35570, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_24_Markov_matrices_Projections_and_Fourier_series.ipynb", "max_stars_repo_name": "okara83/Becoming-a-Data-Scientist", "max_stars_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_24_Markov_matrices_Projections_and_Fourier_series.ipynb", "max_issues_repo_name": "okara83/Becoming-a-Data-Scientist", "max_issues_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_24_Markov_matrices_Projections_and_Fourier_series.ipynb", "max_forks_repo_name": "okara83/Becoming-a-Data-Scientist", "max_forks_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-09T15:41:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T07:47:40.000Z", "avg_line_length": 29.5677472984, "max_line_length": 562, "alphanum_fraction": 0.4731515322, "converted": true, "num_tokens": 6494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21469141911224193, "lm_q2_score": 0.14223189682786755, "lm_q1q2_score": 0.030535967773000865}}
{"text": "# ICON 2017 workshop: MVPA of fMRI data in Python\n\nWelcome to this workshop! In the upcoming couple of hours, you'll work through this (Jupyter) \"notebook\" - a sort of code editor in your browser that allows mixing of code (Python) and text (markdown) cells. Originally, this notebook was developed for the Research Master Psychology course [Neuroimaging: Pattern Analysis](http://studiegids.uva.nl/xmlpages/page/2017-2018/zoek-vak/vak/39531) at the University of Amsterdam, but it was adapted and extended for this ICON workshop.\n\n### Scope\nIn general, this notebook is designed for people who are relatively *unfamiliar* with MVPA and/or its implementation in Python. We *do* assume that you are familiar with analyzing (f)MRI data; the purpose of this workshop is to \"extend your analysis toolbox\", so to say. As such, it\u2019s definitely helpful if you have some knowledge about Python\u2019s syntax, but it\u2019s not strictly necessary. Also, we assume participants are relatively unfamiliar with machine learning (ML) concepts and their implementation; if you\u2019re a ML guru, this is probably not the right workshop for you...\n\nAt certain points in the tutorial, we've included some more \"advanced\" material, but feel free to skip this. Also, realize that this tutorial is about the concepts behind MVPA and how to implement them using domain-general Python tools, such as [scikit-learn](http://scikit-learn.org). Importantly, this tutorial is **not** about how to use MVPA-specific frameworks such as [PyMVPA](http://www.pymvpa.org/) or [Nilearn](http://nilearn.github.io/), although we included a short section on [skbold](http://skbold.readthedocs.io), our own \"machine learning for fMRI\"-package that is built around scikit-learn. \n\nAlso, there is actually no single \"multivoxel pattern analysis\"; rather, MVPA is a bucket-term referring to several kinds of pattern-based analyses. As this tutorial cannot cover all such analyses, we limit the scope to machine learning (*classification-based*) analyses of fMRI data based on *within-subject* designs (leaving out between-subject decoding, regression-based analyses, unsupervised learing, etc.). We hope to cover these grounds sufficiently well for you to be able to explore other kinds of analyses on your own. \n\n### Learning goals of this workshop\nIn this workshop, we cover the basics and implementation of multivoxel pattern analysis (MVPA) to analyze (functional) MRI data in Python. After this tutorial, you are able to:\n\n- Understand the differences between within-subject and between-subject pattern analysis;\n- Know how to extract/estimate patterns from fMRI data;\n- Implement different feature extraction and selection methods using scikit-learn;\n- Build cross-validated MVPA pipelines using scikit-learn;\n- Evaluate your models\n\nIn short, this tutorial will show how to build your own complete, cross-validated MVPA pipeline for fMRI data.\n\n### A note on the data we use\nThe dataset we use for this workshop was chosen out of convenience and is not an example of an optimally design dataset for MVPA-based analyses. Although this workshop is *not* about optimal design strategies for MVPA, we point out shortcomings to the used example dataset wherever appropriate.\n\n### Contents of this notebook\nWe designed this notebook to be interactive. That is, you'll encounter several \"*ToDo*s\" (yellow boxes) and \"*ToThink*s\" (blue boxes) that describe short programming exercises (ToDos) and questions for you to think about (ToThinks), which are aimed to improve understanding of the discussed so far. After each *ToDo*, there is a code block that tests whether your answer is correct. Correct answers to the *ToDos* and *ToThinks* are included in the [answers-notebook](ICON2017_tutorial_answers.ipynb) notebook (but try it yourself first!). If you're not very comfortable/experienced with Python, or if you just don't feel like it, feel free to skip the *ToDos* and *ToThinks*, of course. Also, feel free to ask us questions during this workshop!\n\nThe tutorial is split in two parts. In the first part, we cover the basics of experimental designs, and illustrate how to extract patterns from raw fMRI data in a way that MVPA can be applied. In the second part, the major steps in MVPA (ML-based) pipelines is discussed: feature extraction and selection, cross-validation, and model evaluation. We challenge you to optimize your pipelines to maximize your decoding accuracy scores!\n\nHave fun and good luck!\n\n---\n\n### Using Jupyter notebooks\nThis tutorial is implemented in a \"Jupyter notebook\", which includes \"code cells\" - which are able to run Python code - and \"text cells\" - which render Markdown text. For this tutorial, it suffices to know how to run cells, which you can do by selecting the (code) cell and pressing `CTRL + ENTER` or pressing the \"play\" button in the toolbar on the top of the page. For more info on Jupyter notebooks, check the [python tutorial notebook](python_tutorial.ipynb).\n\n#### Before you go on: did you download the data?\nDid you already download the data, as described [here](http://lukas-snoek.com/ICON2017/)? Check it by running the cell below (CTR + ENTER)!\n\n\n```python\nimport os\nif os.path.isdir(os.path.join('..', 'data')):\n    print(\"You already downloaded the data, nice! Continue with Part 1!\")\nelse:\n    print(\"Seems you don't have the data yet ... Go to lukas-snoek.com/ICON2017 for instructions on how to download it.\")\n```\n\n## Part 1: Experimental design, pattern estimation, and data representation\nBefore you can do any fancy machine learning analysis (or any other pattern analysis), there are several decisions you need to make and steps to take in (pre)processing and structuring your data. Roughly, there are three steps to take:\n\n1. Design your study in a way that's appropriate to answer your question through a pattern analysis; this, of course, needs to be done *before* data acquisition!\n2. Estimate/extract your patterns from the (functional) MRI data;\n3. Structure and represent your data appropriately for pattern analyses;\n\nWhile we won't go into all the design factors that make for an *efficient* pattern analysis (see [this article](http://www.sciencedirect.com/science/article/pii/S105381191400768X) for a good review), we will now discuss/demonstrate some design considerations and how they impact the rest of the MVPA pipeline.\n\n### 1.1. Designs for pattern analysis\nThere are many ways in which you can categorize different types of pattern analyses, but one of the most basic categorizations is in terms of whether analyses are **within-subject** or **between-subject**. The major distinction revolves around whether you want to investigate an (experimental) factor that varies or is manipulated **within** subjects or that varies **across** subjects (i.e. individual differences or experimental between-subject designs)\\*.\n\n----\n\\* **N.B.**: there are also \"hybrid\" forms, such as when you decode a within-subject factor (e.g. \"negative vs. positive images\") from condition-average patterns across subjects. That is, each subject \"contains\" two patterns (one \"negative image\" pattern, one \"positive image\" pattern) and these patterns are decoded *across* subjects\n\n<div class='alert alert-info'>\n**ToThink**: Decide for the following scenarios whether they correspond to a **within-subject** or **between-subject** design!<br><br>\n\n1. Subjects view a sequence of negative (violence, mutilation, war scenes) images during fMRI acquisition. One group of subjects are administered [propanolol](https://en.wikipedia.org/wiki/Propranolol) before the fMRI session and another group a placebo. The researcher in charge wants to see whether patterns in the insula change in reponse to propanolol using a pattern-based analysis. <br><br>\n\n2. Subjects view images of scenes with either animate of inanimate objects during fMRI acquisition. The researcher wants to decode \"animacy\" from patterns in the lateral occipital cortex.\n</div>\n\nImportantly, these two types of analyses differ in what is regarded as an *instance of a pattern* (also referred to as a *sample*):\n\n- in **within**-subject analyses, *each instance of your feature-of-interest represents one pattern* (e.g., each single trial/stimulus/response);\n- in **between**-subject analyses, *each subject represents one pattern*.\n\nThis distinction is important, because the choice of type of pattern analysis has major consequences for the design of your experiment and the methods available for pattern extraction. **Throughout this tutorial, we focus on within-subject analyses**, using a simple two-class working memory data-set.\n\n### 1.2. Pattern estimation for within-subject designs\nThere are different ways to estimate your patterns for pattern-based analyses. Suppose you want to decode neural representations of faces from representations of houses. In that case, you need to to estimate a pattern for each face and each house. Now, suppose we show a face at 9 seconds, we can \"extract\" activity at each voxel for that stimulus in three ways (see figure below):\n\n1. Extract just a point estimate of activity at, e.g., 6 seconds post-stimulus (expected HRF peak);\n2. Average across a range of points;\n3. Fit a HRF *per stimulus* and extract the corresponding $\\beta$-parameter;\n\nAs method 3 (fitting a separate HRF per stimulus) has shown to yield the most stable pattern estimates ([Misaki et al., 2010](http://www.sciencedirect.com/science/article/pii/S1053811910007834)), we'll focus on that method in the rest of this section.\n\n\n\nWe will extract *patterns* of $\\beta$-estimates by fitting a hemodynamic response function (HRF) per trial using the general linear model (GLM)\\*. In other words, \"trials\" (i.e. instances of your feature-of-interest) in within-subject designs are modelled as separate regressors in a first-level analysis. Below, we included an image of a single-trial design (of the hypothetical faces vs. houses experiment) as created in FSL:\n\n----\n__\\* Note__: This single-trial design is also referred to as a \"Least Squares All\" (LSA) approach. Alternative pattern estimation designs exist, including \"Least Squares Single\" (LSA); the choice for one or the other depends on the trail-by-trial variability and scan-noise ([Adulrahman & Henson, 2017](http://www.sciencedirect.com/science/article/pii/S1053811915010319)).\n\nAs you can see, each trial gets it's own regressor (hence the name \"single-trial design\"). Then, as depicted below the design matrix, a contrast-against-baseline is created for each regressor (trial). After you run a first-level analysis using this design, you'll have whole-brain maps containing statistics values ($\\beta$-values, *t*-values, or *z*-values) for each trial that represent the trial's estimated (whole-brain) pattern. Usually, *t*-values or *z*-values are used instead of $\\beta$-values (cf [Misaki et al., 2010](http://www.sciencedirect.com/science/article/pii/S1053811910007834)).\n\n** Importantly, this design thus specifies that for each \"trial\" the activation per voxel is estimated, e.g. each trial gets its own activation map **.\n\nBefore you go on, make sure you understand this image! This image represents basically all you need to understand about single-trial designs. \n\n### 1.3. Implementing a single-trial design\nTo further illustrate how single-trial designs work, let's create your own single-trial matrix corresponding to a (real) working memory experiment. In this experiment, one condition (\"ACTIVE\") required subjects to remember a configuration of bars, and after a retention period had to respond whether one of the bars has changed in the test-image or not. In the other condition (\"PASSIVE\") they just watched a blank screen and had to respond with a random answer. The experiment is depicted schematically below:\n\n \n\nIn total, subjects performed 40 trials, of which 32 were of the \"ACTIVE\" condition and 8 were of the \"PASSIVE\" condition**\\***. Next, we'll generate a single-trial design that aims to estimate the pattern for each trial.\n\n---\n**\\* Note**: this data-set was not necessarily meant to be analysed with MVPA, as it has some sub-optimal factors w.r.t. pattern analysis, such as class-imbalance (32 active vs. 8 passive trials) and all \"instances\" (trials) contained in a single run, while it is often recommended to spread out your trials across different runs (see e.g. [this study](http://www.sciencedirect.com/science/article/pii/S1053811912003643)), which will be shortly discussed in section 2.4. (on cross-validation).\n\nBelow, we'll load the trial onset times (and trial durations and conditions).\n\n\n```python\n# First, we need to import some Python packages\nimport numpy as np\nimport pandas as pd\nimport os.path as op\nimport warnings\nimport matplotlib.pyplot as plt\nplt.style.use('classic')\nwarnings.filterwarnings(\"ignore\")\n%matplotlib inline\n```\n\n\n```python\n# The onset times are loaded as pandas dataframe with three columns: \n# onset times (in seconds) (column 1), durations (column 2), and conditions (column 3).\n# N.B.: condition 0 = passive, condition 1 = active\nstim_info = pd.read_csv(op.join('example_data', 'onsets.csv'), sep='\\t',\n                        names=['onset', 'duration', 'trial_type'])\nstim_info\n```\n\nRemember, the onsets (and duration) are here defined in seconds (not TRs). Let's assume that the fMRI-run has a TR of 2. Now, we can convert (very easily!) the onsets/durations-in-seconds to onsets/durations-in-TRs.\n\n\n```python\n# We repeat loading in the dataframe to avoid dividing the onsets by 2 multiple times ...\nstim_info = pd.read_csv(op.join('example_data', 'onsets.csv'), sep='\\t',\n                        names=['onset', 'duration', 'trial_type'])\n\n# This is where we divide the onsets/durations by the TR\nstim_info[['onset', 'duration']] = (stim_info[['onset', 'duration']] / 2).astype(int)\n```\n\nTo perform the first-level analysis, for each regressor (trial) we need to create a regressor of zeros and ones, in which the ones represent the moments in which the particular trial was presented. Let's assume that our moment of interest is the encoding phase, which lasts only 2 seconds; we thus can model it as an \"impulse\".\n\nSo, for example, if you have a (hypothetical) run with a total duration of 15 TRs, and you show a stimulus at TR=3 for the duration of 1 TRs (i.e. 2 seconds), then you'd code your regressor as:\n\n`[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]`\n\n<div class='alert alert-warning'>\n**ToDo**: Below, we initialized a stimulus vector (`stim_vec`) of shape=[162, 40], i.e. timepoints x trials (this run was 162 TRs long), with zeros. Each of the 40 rows represents one trial. Loop over the colums of the `stim_vec` matrix and fill the times at onset with a 1. Remember, the first index in Python is zero (not 1!).\n</div>\n\n\n```python\n# ToDo\nn_timepoints = 162\nn_trials = 40\nstim_vec = np.zeros((n_timepoints, n_trials))\n\n# Fill the stim_vec variable with ones at the indices of the onsets per trial!\n\n\n```\n\n#### Check your ToDo\nRun the cell below to check whether you implemented the ToDo correctly! If it gives no errors, your implementation is correct!\n\n\n```python\nnp.testing.assert_array_equal(stim_vec, np.load(op.join('example_data', 'stim_vec.npy')))\nprint(\"Well done!\")\n```\n\n#### Skip this ToDo?\nIf you want to skip this ToDo, load the correct `stim_vec` variable below, because we'll need that for the rest of the tutorial!\n\n\n```python\nstim_vec = np.load(op.join('example_data', 'stim_vec.npy'))\n```\n\n### Visualizing the design\nNow, we only need to convolve an HRF with the stimulus-vectors (using the `numpy` function `convolve()`) and we'll have a complete single-trial design!**\\*** Don't worry, we do this for you. We'll also plot it to see how it looks (blue = active trials, red = passive trials):\n\n\n```python\nfrom functions import double_gamma\n\nhrf = double_gamma(np.arange(162))\n\n# List comprehension (fancy for-loop) + stack results back to a matrix\nX = np.vstack([np.convolve(hrf, stim_vec[:, i], 'full')[:162] for i in range(40)]).T\n\nplt.figure(figsize=(30, 10))\nfor plot in range(40):\n    is_active = True if stim_info['trial_type'][plot] == 1 else False\n    plt.plot(X[:, plot] + plot, np.arange(X.shape[0]), c='blue' if is_active else 'red', lw=3)\n    plt.text(plot - 0.5, -15, 'active' if is_active else 'passive',\n             rotation=45, fontsize=20)\n\nplt.ylabel('Time (TR)', fontsize=40)\nplt.xlabel('Regressors (trials)', fontsize=40)\nplt.xlim((-1, 40))\nplt.ylim((0, 160))\nax = plt.gca()\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\nax.invert_yaxis()\nplt.show()\n```\n\n**\\* Note**: This specific data-set does not have a proper design for a machine-learning analysis on single-trial patterns, because the short ISI leads to temporal autocorrelation between subsequent trials and may thus result in inflated accuracy scores (cf. [Mumford et al., 2014](http://www.sciencedirect.com/science/article/pii/S105381191400768X)). It is generally recommended to use a long ISI (> 6 seconds) in combination with fully randomized (and class-balanced) trials, **or** to perform run-wise cross-validation (something we'll revisit in the section on cross-validation).\n\n----\n\nThe GLM that evaluates this design will yield a $\\beta$-estimate per trial per voxel. In other words, every trial is associated with a specific (whole-brain) pattern of $\\beta$-values.\n\nUsually, though, *t*-values instead of *$\\beta$*-values are used, because [it has been shown](http://www.sciencedirect.com/science/article/pii/S1053811910007834) that converting $\\beta$-values to *t*-values (also called *univariate normalization*) often creates more stable and robust patterns. $\\beta$-values can be normalized to *t*-values by simply dividing the parameter estimate ($\\beta$) by it's corresponding standard error, which we won't show here but we're confident you know how to do that yourself! \n\n**Note**: realize that we don't interpret the patterns of t-values in terms of **statistical significant**. This is because we only use t-values for the goal of efficient pattern estimation, but not hypothesis testing like in mass-univariate analyses! As such,we're not thresholding or applying any multiple comparison correction! \n\n### 1.4. Visualizing patterns\n\nSo, now you know how to create a \"single-trial design\" for pattern analyses! As a short summary:\n- Model each \"trial\" (or more generally, \"instance\") as a separate HRF-convolved regressor;\n- Additionally define a contrast-matrix in which each trial is contrasted against baseline in order to create *t*-value/*z*-value patterns;\n\n<div class='alert alert-warning'>\n**ToDo**: We ran the first-level analysis of the single-trial working-memory design outlined above for fifteen subjects using FSL (which conveniently also calculates t-values from the $\\beta$-values). You can find the results in the directory: `../data/{subject_number}/wm.feat`. Pick one of the subjects, and check out the `stats` subdirectory. You will see forty tstat-niftis, each containing a whole-brain pattern of *t*-stats of a single trial. These contain the data we will use in this tutorial for MVPA.\n</div>\n\nAlright, you now know what a single-trial (within-subject) design looks like and what it produces (i.e. single-trial pattern estimates in the form of whole-brain $\\beta$/*t*-stat/*z*-stat maps). Before we go on, we will show what a pattern of a single trial looks like in fslview. This will hopefully give you some more \"intuition\" on what is meant with a single trial pattern. \n\n<div class='alert alert-warning'>\n**If you have FSL installed on your computer, you can do this yourself!** open up a new terminal or terminal-tab and start fslview (by typing `fslview` in the terminal). Now, click \"File\" > \"Open\", navigate to `data/pi0070/wm.feat/stats` and select `tstat1.nii.gz`. Now, to visualize the patterns somewhat more intuitively, set in the fslview header \"Min\" to 0 and \"Max\" to 5. Then, click the little circle with the blue \"i\": \n<br>\nUnder the \"lookup table options\", select the \"Red-Yellow\" colormap. What you visualize here are all the voxels that activate during this particular trial. However, a pattern is not necessarily only the voxels that *activate*, but also those that *deactivate*. A pattern is *any* estimated response of the brain during an instance of a sample (here: a trial). Therefore, let's also visualize the deactivating voxels. To do so, click \"File\" > \"Add\" and select the `tstat1.nii.gz` image *again*, but now set \"Min\" to 0 and \"Max\" to -5. For this file, select the colormap \"Blue-Lightblue\". \n\nWhat you should see now is something like this: \n\n<br>\nWhat we visualized here is an example of a within-subject pattern of a particular trial (\"sample\"), in which the activated voxels (relative to baseline) are colored red/yellow, and the deactivated voxels (relative to baseline) are colored blue/lightblue. Make sure you understand how this image represents the pattern of a single sample.\n</div>\n\nYou can also do this inside the jupyter notebook:\n\n\n```python\nfrom niwidgets import NiWidget\n\ntstat_widget = NiWidget(op.join('..', 'data', 'pi0070', 'wm.feat', 'stats', 'tstat1.nii.gz'))\ntstat_widget.nifti_plotter()\n```\n\n#### 1.4.1 Data representation\nIn pattern analyses, there is a specific way to 'store' and represent brain patterns: as 2D matrices of shape `N-samples` $\\times$ `K-voxels`. **Important**: often (and confusingly), people refer to voxels as (brain) 'features' in pattern analyses. So in articles people often refer to samples-by-features matrices!\n\nAnyway, this is what such a matrix looks like for the hypothetical faces-vs-houses decoding study: \n\n\nEach row thus represents the voxel pattern of a sample (here: trial)!\n\n#### From 3D patterns to a 2D matrix ...\nAs you can see, the originally 3D voxel patterns (e.g. whole-brain patterns of *t*-values) are flattened (also called \"vectorized\" or \"raveled\") such that we can stack all patterns vertically into a 2D matrix. Pattern analyses, and machine learning in specific, need this 2D (thus discarding spatial information about the voxel patterns) because most (ML) algorithms were not designed to work with 3D (spatial) data (barring convolutional neural networks). They, instead, assume that the data is a 2D samples-by-features matrix.\n\nAnyway, let's look at an example. We're going to work with the working-memory data (as outline in the beginning of the notebook). Suppose we want to investigate whether we can predict whether a trial is passive or active (factor: working memory load) from (whole-brain) voxel patterns. Consequently, this is a **within-subject design**. As such, we model each trial separately by fitting a single-trial design matrix to obtain patterns of *t*-values per trial (similar to the plot just before Section **1.3**). The results are in the directory: `data/pi0070/wm.feat`. Check out the directory (again) and especially the stats-folder. You should see a bunch of nifti-files which contain 3D voxel patterns with \"tstat\" values (FSL also produces pes [betas], copes, varcopes - we removed these to minimize data size of this tutorial).\n\nFor this analysis, we're going to use patterns of *t*-stats (as is generally recommended over $\\beta$s).<br>\nAs you can see, there are 40 nifti-files with *t*-stats; these refer to the 40 trials in the experiment (32 active trials, 8 passive trials)! Given that we need to adhere to the data representation as outlined above, we are in the following situation:\n\n**What we have**: 40 (3D) nifti-files<br>\n**What we need**: one 2D numpy array of shape 40 x {whatever amount of voxels there are in those niftis}\n\nAlright, time to learn some Python gems that help us load in and transform those patterns into a usable 2D numpy matrix.\n\n#### 1.4.2 tips & tricks to load and transform (nifti-)files\nAs a first thing, we need to find all the paths to the *t*-stat nifti-files. Python has a nifty (pun intended) tool called \"`glob`\" which can find files/directories on disk using [wildcards](https://en.wikipedia.org/wiki/Wildcard_character). It is usually imported as follows:\n\n\n```python\nfrom glob import glob\n```\n\n`glob`, in Python, is a function that takes a path (as a string) with one or more wildcard characters (such as the `*`) and searches for files/directories on disk that match that. For example, let's try to find all the png-imagesin the \"img\" directory using glob (these are the images that I used inside this notebook). \n\n\n```python\nimport os\n# the images are in img/ on Linux/Mac systems, but in img\\ on Windows (hence the \"os.sep\" thingie)\nmy_search_string = 'img' + os.sep + '*.png'\npng_files = glob(my_search_string)\nprint(png_files)\n```\n\nAs you can see, it returns a list with all the files/directories that matched the search-string. Note that you can also search files outside of the current directory. To do so, we can simply specify the relative or absolute path to it.\n\n<div class='alert alert-warning'>\n**ToDo**: Now you have the skills to actually \"glob\" all the *t*-stats from subject `pi0070` yourself! Use glob to find all the paths to the t-stats and store the results (a list with 40 strings) in a variable called `tstat_paths`. Note: the data directory is one directory above the current directory! Hint: watch out! There might be an `ftest.nii.gz` file in the stats-directory ...\n</div>\n\n\n```python\n# Implement your ToDo here\n\n```\n\n#### Check your ToDo!\nRun the cell below.\n\n\n```python\n# To check your answer, run this cell\nassert(len(tstat_paths) == 40)\nprint(\"Well done! You globbed all the 40 tstat-files correctly!\")\n```\n\n#### Skip this ToDo?\nTo skip this ToDo, run the cell below.\n\n\n```python\nfrom functions import glob_tstats\ntstat_paths = glob_tstats()\n```\n\n**Warning**: `glob` returns unsorted paths (so in seemingly random order). It's better if we sort the paths before loading them in, so the order of the paths is more intuitive (the first file is tstat1, the seconds tstat2, etc.). Python has a builtin function `sorted()`, which takes a list and sorts it alphabetically. The problem, here, is that if we'd use that - i.e. `sorted(tstat_paths)` - it will actually sort the files as: tstat1, tstat10, tstat11, etc. See for yourself: \n\n\n```python\nprint(sorted(tstat_paths))\n```\n\nTo fix this issue, we wrote a little function (`sort_nifti_paths()`) that sorts the paths correctly. (If you're interested in how it works, check out the functions.py file.)\n\n\n```python\n# Let's fix it\nfrom functions import sort_nifti_paths\ntstat_paths = sort_nifti_paths(tstat_paths)\nprint(tstat_paths)\n```\n\n#### 1.4.3. Loading in nifti-data using nibabel\n\nNow, we have the paths to all the nifti-files of a single subject. To load a nifti-file into a numpy-array in Python, we can use the awesome [nibabel](http://nipy.org/nibabel) package. This package has two useful methods you can use to load your data: `load` and `get_data`. You need to use them consecutively to load the *t*-values in memory. For example, to load the whole-brain pattern of *t*-values of the first trial of subject pi0070:\n\n\n```python\nimport nibabel as nib\ndata = nib.load(tstat_paths[0]).get_data()\nvoxel_dims = data.shape\n```\n\n<div class='alert alert-warning'>\n**ToDo**: in the code block below, write a loop that loads in the tstat nifti-files one by one (using nibabel) and store them in the already preallocated array \"X\". Note that \"X\" is a 2D matrix (samples-by-features), but each tstat-file contains a 3D array, so you need to \"flatten\" the 3D array to a single vector: use e.g. the numpy function \"flatten()\" or \"ravel()\". \n</div>\n\n\n```python\n# Implement your ToDo here\nX = np.zeros((40, np.prod(voxel_dims)))\n\n# Start your loop here:\n\n```\n\n#### Check your ToDo\nRun the cell below to see whether you implemented the ToDo below correctly. If you don't get errors, you did it correctly!\n\n\n```python\n# Can we check if X is correct here? Would be a good check before continuing to part 2\nnp.testing.assert_almost_equal(X, np.load(op.join('example_data', 'X_section1.npz'))['X'])\nprint(\"Well done!\")\n```\n\n#### Want to skip this ToDo?\nRun the cell below.\n\n\n```python\nX = np.load(op.join('example_data', 'X_section1.npz'))['X']\n```\n\n### You've reached a milestone!\nStarting with 4D fMRI data, you now have patterns in the right format (a 2D-matrix of N-samples x N-features). Now, let's start talking about machine learning!\n\n## Part 2. Multivoxel pattern analysis\nIn Part 1, we discussed within-subject single-trial designs, and showed how to load single-trial data in the right format to perform MVPA. It's now time to actually implement machine learning analyses!\n\nWe'll be looking at the implementation of concepts like K-fold cross-validation, feature-selection/extraction, model fitting/prediction, permutation testing, and feature visualization. To do so, we'll use the [`scikit-learn`](http://scikit-learn.org) machine learning package in Python (the de-facto and most-used ML package in Python).\n\nRemember that, very generally, MVPA is all about inferring a feature-of-interest (dependent variable) using patterns of fMRI data. Let's call the feature-of-interest **y**, and the patterns of fMRI data **X**. This inference from X to y is called *decoding*: we want to *decode* a dependent variable y from X.\n\nIn our case, let's continue with the data from the working memory experiment used in Part 1. Remember that, in this experiment, participants performed two types of trials: \"ACTIVE\" trials, in which they had to remember the orientation of eight bars, and \"PASSIVE\" trials in which they did not do anything (note that the screen shortly flickered in the \"PASSIVE\" trials in order to activate the visual cortex). Let's try to decode trial type from the patterns of *t*-values you creates in Part 1!\n\n### 2.1 Adding the dependent variable y\nIn Section 1.3, you ended with a nice 2D-matrix of N-samples x N-features. This 2D-matrix contains all whole-brain patterns of *t*-values for all trials: this is your **X**. However, this leaves out a crucial part of the data: the actual feature-of-interest, *trial type*, your **y**.\n\nWhile there is kind of a generic way to load in voxel patterns, there is usually not a single way to load in your dependent variable (y), because the exact factor that represents `y` dependent on your exact research question (and also depends how you have stored this data on disk). \n\nIn within-subject single-trial designs, trial type or condition is often the dependent variable. The dependent variable can thus be extracted from your design. In fact, we already loaded the dependent variable previously, in the `onsets` variable (see Section 1.2). The third column named 'trial_type') contains the trial types, where 1 is an \"ACTIVE\" trial and 0 a \"PASSIVE\" trial.\n\n<div class='alert alert-warning'>\n**ToDo**: Extract vector *y* from `onsets`, which only contains the trial types (i.e., y = [1, 1, 1, 0, ..., 0, 1, 1]) \n</div>\n\n\n```python\n# Implement your ToDo here\n```\n\n#### Check your answer\n\n\n```python\nnp.testing.assert_equal(np.array(y), np.load(op.join('example_data', 'y.npy')))\nprint('Well done!')\n```\n\n#### Run the cell below if you want to skip this ToDo\n\n\n```python\ny = np.load(op.join('example_data', 'y.npy'))\n```\n\nAnd that's all you need for machine learning-based analyses in terms of preparation!\n\n## Commercial\\* break: skbold\nWhile it's still relatively easy to load in, structure, and preprocess all of the data necessary for pattern-based analyses, there's quite a lot of \"boilerplate code\", especially when you need to loop your analysis across multiple participants. At least, that's what we thought and motivated us to create [skbold](skbold.readthedocs.io), a (Python-based) package that offers a set of tools to make machine learning analyses of fMRI data easier. As shown in the figure below, skbold complements the scikit-learn package by offering functionality specific to fMRI-data at different stages of your machine learning pipeline. For example, reading in single-trial estimates and corresponding labels (\"y\") only takes about 5 lines of Python code using skbold. To avoid distracting you from this tutorial, we included a section on how to use skbold *at the very end* of this tutorial. Check it out if you are interested!\n\n\n\n---\n**\\*** Skbold is, of course, not really commercial! It's fully open source (BSD-3 licensed) and can be easily installed with pip (`pip install skbold`)!\n\n### 2.2. An overview of a typical machine learning pipeline\nAwesome, we now have everything we need (X and y). This took a while, but you'll soon see it was worth the effort.\n\nIn the rest of the tutorial, you'll finally learn how to actually implement decoding pipelines. Typical pipelines consist of the following elements:\n\n* Data preprocessing (scaling)\n* Data partitioning\n* Feature selection/extraction\n* Model fitting (on train-set)\n* Model cross-validation (on test-set)\n* Calculate model performance\n* Statistical analyses of performance\n* Optional: feature visualization (not discussed in this workshop)\n\nIn the rest of the tutorial, we'll discuss these topics in a slightly different order. First, we'll discuss how you can preprocess, fit, and cross-validate scikit-learn models, and while we're at it, how to calculate model performance. Subsequently, you'll learn how to embed these concepts in fully cross-validated K-fold data partitioning schemes. Finally, we'll extend our pipelines with feature selection methods and (optionally) show you how to use scikit-learn `Pipelines`. \n\n### 2.3. Pattern preprocessing (scaling)\nBefore any machine learning analysis, is it advised to preprocess your pattern such that each feature (here: voxels) is on the same scale. This \"feature scaling\" process can be done in various ways, but the most often used method is *standardization*: scaling features such that they have 0 mean and unit variance. Feature scaling is important for many machine learning algorithms in the training process and omitting scaling may yield sub-optimal results.\n\nScikit-learn provides a class, [StandardScaler](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html), that implements feature standardization. We'll apply it to our entire dataset (`X`) here, but in a later section we'll explain that - strictly speaking - it's best to \"cross-validate\" this preprocessing step.\n\nAnyway, let's see how standardization is done using scikit-learn (in section 2.8. we'll explain this scikit-learn object's API in more detail):\n\n\n```python\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler() # Here we initialize the StandardScaler object\nscaler.fit(X)             # Here we \"fit\" the StandardScaler to our entire dataset (i.e. calculates means and stds of each feature)\nX = scaler.transform(X)   # And here we transform the dataset using the calculated means/stds\n```\n\nDid the scaling procedure work? Let's check that below (by asserting that the mean of each column is 0, and the std of each column is 1):\n\n\n```python\nmeans = np.mean(X, axis=0)\nnp.testing.assert_almost_equal(means, np.zeros(X.shape[1]))\nprint(\"Each column (feature) has mean 0!\")\nstds = X.std(axis=0)\nnp.testing.assert_almost_equal(stds[stds != 0], np.ones((stds != 0).sum()))\nprint(\"Each column (feature) has std 1!\")\n```\n\nSweet! We correctly preprocessed out patterns. Now it's time for the more interesting stuff.\n\n### 2.4. Model fitting & cross-validation\nFirst, we'll show you how to use scikit-learn models and associated functionality. In fact, the most useful functionality of scikit-learn is probably that they made fitting and cross-validating models (or, in scikit-learn lingo: estimators) trivially easy. \n\nNote that in the upcoming example, we will fit the model on *all* our samples for the sake of the example. In practice, this is something you would **never** do: you always need to cross-validate your model to a new, independent sample.**\\*** \n\n----\n**\\*** That is, independent with respect to noise: the noise in your *training* sample should not be correlated with the noise in your *test* set).\n\nAnyway, let's import a scikit-learn model: the (linear) support vector classifier ([SVC](http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html)), which is one of the most-often used models in fMRI pattern analyses. In scikit-learn, this model is part of the (suprising...) `svm` module:\n\n\n```python\n# Scikit-learn is always imported as 'sklearn'\nfrom sklearn.svm import SVC\n```\n\nLike most of scikit-learn's functionality, SVC is a *class* (not a *function*!). So, let's initialize an SVC-object! One important argument that this object needs upon initialization is the [\"kernel\"](http://scikit-learn.org/stable/auto_examples/svm/plot_svm_kernels.html) you want the model to have. Basically, the kernel determines how to treat/process your features: linearly (such as `kernel='linear'`), or non-linearly (such as the `kernel='rbf'` or `kernel='poly'` options). Most often a linear kernel is the best option (as non-linear kernels often overfit very quickly).\n\nTo initialize an SVC-object with a linear kernel, just do as follows:\n\n\n```python\n# clf = CLassiFier\nclf = SVC(kernel='linear')\n```\n\nAlright, we initialized an SVC-object (named `clf`, short for \"classifier\") with a linear kernel. Now, you need to do two thing to get the prediction for each sample (i.e. whether they're predicted as 0 or 1): fit, using the method `fit(X, y)`, and predict the class (i.e. 0 or 1) for each class using the method `predict(X)`. Basically, in the `fit` method, the parameters of the model (i.e. $\\beta$) are estimated. Then, in the `predict` method, the estimated parameters are used to generate a prediction for each sample (i.e. 0 or 1). \n\nLet's first look at the `fit` method. As you can see, the `fit(X, y)` method with two parameters: X (a samples-by-features matrix) and y (a vector of length n-samples). Let's do that for our data: \n\n\n```python\nprint('Fitting SVC ...', end='')\nclf.fit(X, y)\nprint(' done.')\n```\n\nAfter calling the fit() method, the clf-object contains an attribute `coef_` that represent the model's parameters ('coefficients' in scikit-learn lingo, i.e. $\\beta$). Let's check that out:\n\n\n```python\ncoefs = clf.coef_\nprint(\"Shape of coefficients: %r\" % (coefs.shape,))\n```\n\nAh, just like we expected: the `coef_` attribute is exactly the same size as the number of voxels in our X-matrix (i.e. 80\\*80\\*37). \n\nAnyway, usually, you don't have to do anything directly with the weights (perhaps only if you want to do anything with feature visualization). Scikit-learn handles the calculation of the prediction (let's call that $\\hat{y}$) using the trained weights. To get the prediction of any sample, just call the `predict(X)` method of the model, which returns the predictions as an array:\n\n\n```python\ny_hat = clf.predict(X)\nprint(\"The predictions for my samples are:\\n %r\" % y_hat.tolist())\n```\n\n<div class='alert alert-warning'>\n**ToDo**: The cool thing about scikit-learn is that their objects have a very consistent API and have sensible defaults. As a consequence, *every* model (\"estimator\" in scikit-learn terms) is used in the same way using the `fit(X, y)` and `predict(X)` methods. Try it out yourself below!<br><br> Try using the [LinearDiscriminantAnalysis](http://scikit-learn.org/stable/modules/generated/sklearn.discriminant_analysis.LinearDiscriminantAnalysis.html#sklearn.discriminant_analysis.LinearDiscriminantAnalysis) class (`from sklearn.discriminant_analysis import LinearDiscriminantAnalysis`) or [GaussianNB](http://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.GaussianNB.html#sklearn.naive_bayes.GaussianNB) (\"Naive Bayes\" classifier; `from sklearn.naive_bayes import GaussianNB`) for example (or any other!). All methods should work exactly the same as the previous example using the SVM.\n</div>\n\n\n```python\n# Try out different estimators below (call fit and predict on X and y!)\n\n```\n\n### 2.5. Model evaluation\nA logical next step is to assess how good the model was in predicting the class of the samples. A straightforward metric to summarize performance is *accuracy* **\\*** which can be defined as: \n\n\\begin{align}\naccuracy = \\frac{number\\ of\\ correct\\ predictions}{number\\ of\\ predictions}\n\\end{align}\n\n---------------\n**\\*** There are waaaay [more metrics to summarize model performance](http://machinelearningmastery.com/classification-accuracy-is-not-enough-more-performance-measures-you-can-use/) for classification models, such as precision, recall, F1-score, and ROC-AUC. These metrics are more appropriate than accuracy when you have *imbalanced classes*, i.e. more samples in one class (e.g. negative images) than in another class (e.g. positive images), like we have here (i.e. 32 active, 8 passive trials). We'll revisit this issue in the next (optional) section.\n\n<div class='alert alert-warning'>\n**ToDo**: Can you calculate the accuracy of the above model? Hint 1: you need to compare the true labels (i.e. y) with the predicted labels (i.e. y_hat). Hint 2: if you do arithmetic with boolean values (i.e. `True` and `False`), `True` is interpreted as 1 and `False` is interpreted as 0.\n</div>\n\n\n```python\n# Implement your to-do here!\n\n```\n\nIf you've done the ToDo above correctly, you should have found out that the accuracy was 1.0 - a perfect score! \"Awesome! Nature Neuroscience material!\", you might think. But, as is almost always the case: if it seems too good to be true, it probably *is* indeed too good to be true.\n\nSo, what is the issue here? \n\nWell, we didn't cross-validate the model! We fitted it on all the samples in the mvp-object and predicted the *same* samples, which leads to optimistic estimate of model performance. Such optimistic estimates in uncross-validated models are especially likely when there are many more features (here: voxels) than samples (here: trials). In other words, we are probably *overfitting* the model here.\n\nThus, let's check what happens if we actually cross-validate the model. To do so, we need to partition the data into a train- and test-set. For this example, we'll use a simple hold-out scheme, in which we'll reserve half of the data for the test-set (we'll discuss more intricate cross-validation schemes such as K-fold in the next section).\n\nTo partition our data in a 50/50 split (50% for train, 50% for test), we'll use the scikit-learn function [train_test_split](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html):\n\n\n```python\nfrom sklearn.model_selection import train_test_split\n\nif not isinstance(y, np.ndarray):\n    y = np.array(y)\n\n# The argument \"test_size\" indicates the test-size as a proportion\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, stratify=y,\n                                                    random_state=5)\n    \nprint(\"Shape X_train: %r\" % (X_train.shape,))\nprint(\"Shape y_train: %r\" % (y_train.shape,))\nprint(\"Shape X_test: %r\" % (X_test.shape,))\nprint(\"Shape y_test: %r\" % (y_test.shape,))\n```\n\nAs you can see, the `train_test_split` function nicely partitions our data in two sets, a train- and test-set. Note the argument `stratify` in the function, which is set to `True`, which ensures that the class proportion (here: ratio of \"active\" trials to \"passive\" trials) is the same for the train-set as the test-set.\n\n<div class='alert alert-warning'>\n**ToDo**: To convince yourself that the `stratify` option does what it supposed to do, check whether the class-ratio is the same for the train and test-set. \n</div>\n\n\n```python\n# Implement the ToDo here\n```\n\nNow it's up to you to actually implement the *cross-validated* equivalent of the fit/predict procedure we showed you before, in the next ToDo!\n\n<div class='alert alert-warning'>\n**ToDo**: Fit your model on `X_train` and `y_train` and then predict `X_test`. Calculate both the accuracy on the train-set (fit and predict on train) *and* the cross-validated accuracy (fit on train, predict on test). Compare the two accuracies - are we overfitting the model?\n</div>\n\n\n```python\n# Implement your ToDo here\n\n```\n\nIf you implemented the ToDo correctly, you should see that the test-set accuracy is quite a bit lower (10%) than the train-set accuracy! This test-set accuracy is still slightly biased due to imbalanced classes, which is discussed in the next section.\n\n### Advanced: evaluation of imbalanced datasets/models (optional, but recommended)\nAs hinted at before, one problem with our dataset is that it is *imbalanced*. That is, the amount of samples are imbalanced between classes, because we have 32 samples in the \"active\" class and only 8 samples in the \"passive\" class. \n\n\"Why is that a problem?\", you might ask?\n\nWell, suppose that our classifier \"learns\" to predict every sample as \"active\", regardless of the underlying patterns. In that scenario, it will still achieve an accuracy of:\n\n\\begin{align}\naccuracy = \\frac{32}{40} = 0.8\n\\end{align}\n\nWhile 0.8 may seem like a great classification score, in this case it may just be due to our class imbalance! Therefore, imbalanced datasets therefore need a different evaluation metric than accuracy. Fortunately, scikit-learn has many more performance metrics you can use, including metrics that \"correct\" for the (potential) bias due to class imbalance (including [f1-score](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html#sklearn.metrics.f1_score), [ROC-AUC-score](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html#sklearn.metrics.roc_auc_score), and [Cohen's Kappa](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.cohen_kappa_score.html#sklearn.metrics.cohen_kappa_score)). \n\nAnother way to \"correct\" for imbalanced datasets is to either **undersample** your majority class(es) to match the amount of samples in the minority class or to **oversample** the minority class(es) to match the amount of samples in the majority class. Unlike using \"class-imbalance-aware\" metrics, which deals with the issue *post-hoc*, under/oversampling actually forces your model to learn on a balanced dataset (which is, in our experience, the most sensitive strategy). \n\nAs the over/undersampling methods are slightly beyond the scope of this tutorial (but check out [this library](http://contrib.scikit-learn.org/imbalanced-learn/index.html) for implementations of different methods to deal with imbalanced datasets), let's check out what happens with our performance estimate if we use a different ('class-imbalance-aware') metric, like the \"ROC-AUC-score\". Like all metrics, this function can be imported from the `sklearn.metrics` module. Any scikit-learn metric function is called using the following format:\n\n```\nperformance = some_metric(y_true, y_predicted)\n```\n\n<div class='alert alert-warning'>\n**ToDo**: Evaluate the model from the previous ToDo with the ROC-AUC-score metric instead of accuracy. Check both the performance on the train-set (which should still be 1.0) and the (cross-validated) performance on the test-set.\nNotice the drop in performance compared to using accuracy!\n</div>\n\n\n```python\n# The roc-auc-curve function is imported as follows:\nfrom sklearn.metrics import roc_auc_score\n\n# Implement your ToDo here\n\n```\n\nIf you've done the ToDo correctly, you should see that the performance drops to 0.75 if using the ROC-AUC score! While this thus leads to worse results, it's more likely to be based on information from your patterns rather than just the class-imbalance of your dataset.\n\nThat said, it's, of course, always best to avoid imbalance in the first place, but sometimes this is unavoidable, for example when decoding subjects' responses (which are not under control of the experimenter). But *if* you have imbalanced classes, make sure to deal with it appropriately!\n\n### Recap\nSweet! You actually performed your first proper decoding analysis in this section! There are however a couple of things we can do to improve the efficiency and results of our analysis. One thing we can do is to use the data more efficiently in cross-validation. In the previous example, we split the data into two sets and fit the model on one (the train-set) and cross-validated to the other (the test-set). There is actually a way to \"re-use\" the data by using K-fold cross-validation, in which data is iteratively partitioned in train- and test-sets. This is explained in the next section.\n\n### 2.7. Data partitioning: K-fold cross-validation\nThere are two major ways of cross-validation: \n\n* Hold-out cross-validation;\n* K-fold cross-validation;\n\nIn the previous section we implemented a form of hold-out cross-validation, which can be seen as a kind of \"one-shot cross-validation\". In fMRI data-sets, however, we usually have few samples (simply because MRI-data is expensive to acquire!). Because K-fold cross-validation allows you to reuse the data, it is much more common than hold-out cross-validation in MRI studies.\n\nNow, we can finally use some of scikit-learn's functionality. We are going to use the [StratifiedKFold](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedKFold.html) class from scikit-learn's model_selection module. Click the highlighted link above and read through the manual to see how it works.\n\nImportantly, if you're dealing with a classification analysis, always use *Stratified*KFold (instead of the regular [KFold](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.KFold.html)), because this version makes sure that each fold contains the same proportion of the different classes (here: 0 and 1; just like we did with `train_test_split` when we set `stratified=True`). \n\nAnyway, enough talking. Let's initialize a StratifiedKFold object with 5 folds:\n\n\n```python\n# scikit-learn is imported as 'sklearn'\nfrom sklearn.model_selection import StratifiedKFold\n\n# They call folds 'splits' in scikit-learn\nskf = StratifiedKFold(n_splits=5)\n```\n\nAlright, we have a StratifiedKFold object now, but not yet any indices for our folds (i.e. indices to split X and y into different samples). To do that, we need to call the `split(X, y)` method:\n\n\n```python\nfolds = skf.split(X, y)\n```\n\nNow, we created the variable `folds` which is officially a [generator](https://wiki.python.org/moin/Generators) object, but just think of it as a type of list (with indices) which is specialized for looping over it. Each entry in `folds` is a tuple with two elements: an array with train-indices and an array with test-indices. Let's demonstrate that\\*:\n\n-------------\n\\* Note that you can only run the cell below once. After running it, the `folds` generator object is \"exhausted\", and you'll need to call `skf.split(X, y)` again in the above cell.\n\n\n```python\n# Notice how we \"unpack\" the train- and test-indices at the start of the loop\ni = 1\nfor train_idx, test_idx in folds:\n    \n    print(\"Processing fold %i\" % i)\n    print(\"Train-indices: %s\" % train_idx)\n    print(\"Test-indices: %s\\n\" % test_idx)\n    \n    i += 1\n```\n\nAs you can see, StratifiedKFold determined that for the first fold, sample \n1 to 9 should be used for training and sample 0, 1, 2, 3, 4, 5, 6, 7, and 13 should be used for testing (remember, Python uses 0-based indexing!) and the rest for training. \n\nNow, we know how to access the train- and test-indices, but we haven't *actually* indexed our X and y (i.e. mvp.X and mvp.y) in the for-loop over folds. Nor have we actually fit the model on the train-set and cross-validated this to the test-set.\n\n<div class='alert alert-warning'>\n**ToDo**: in the code-cell below, complete the statements by indexing X and y to create four different objects in every fold: X_train, y_train, X_test, y_test. Also, we created a new classifier-object (clf) for you based on a different model: scikit-learn's `LogisticRegression` to show you that *every* model in scikit-learn works the same (i.e. has the same `fit` and `predict` methods). <br><br>\n\nUse this classifier to fit on the train-set and predict the test-set in every fold. Then, calculate the (cross-validated) performance (e.g. ROC-AUC-score) in every fold. Keep track of the accuracies across folds, and after the loop over folds, calculate the average performance across folds.\n</div>\n\n\n```python\n# Implement the ToDo here by completing the statements in the loop!\nfrom sklearn.linear_model import LogisticRegression\n\n# clf now is a logistic regression model\nclf = LogisticRegression()\n# run split() again to generate folds\nfolds = skf.split(X, y)\n\nperformance = np.zeros(skf.n_splits)\n\nfor i, (train_idx, test_idx) in enumerate(folds):\n    \n    # Complete these statements by indexing X and y with train_idx and test_idx\n    X_train = \n    y_train = \n    \n    X_test = \n    y_test = \n    \n    # ToDo: call fit (on train) and predict (on test)\n    \n    # ToDo: calculate roc-auc-score (or accuracy, but that's biased ...)\n    this_performance = \n    \n    performance[i] = this_performance\n    \n# ToDo: calculate average performance (and print it!)\n\n```\n\nImplementing K-fold cross-validation instead of hold-out cross-validation allowed us to make our analysis a little more efficient (by reusing samples). Another method that (usually) improves performance in decoding analyses is feature selection/extraction, which is discussed in the next section (after the optional run-wise decoding section).\n\n### Advanced: run-wise decoding (optional)\nContrary to our example data-set which decoding single trials within a **single** fMRI run, it is recommended to spread out your samples across **different** fMRI runs and perform *run-wise cross-validation*. This type of cross-validation basically partitions your samples according to their run; one example, referred to as \"leave-one-run-out\" cross-validation, partitions your data such that you always train on trials from all runs minus one, and use the left-out run for testing. A nice property of this type of cross-validation is that it effectively avoids the problem of autocorrelated samples (which is highly likely in fMRI, especially if the ISI is short!). While the samples within each run are still autocorrelated, run-wise-cv makes sure that cross-validation is performed on samples from an *independent run*, thus dealing with bias due to autocorrelation.\n\nAnyway, let's look at an example. Since we don't have a real fMRI dataset with different runs, we're just going to simulate some data. Suppose we have four fMRI runs, each with 20 trials, of which 10 of class \"A\" (coded with 0) and 10 of class \"B\" (coded with 1), and each sample is associated with a pattern of a 1000 voxels (let's say the activity pattern in the bilateral amygdala). So, in total we have 80 trials, 40 per class, spread out over 4 runs:\n\n\n```python\nX_r = np.random.randn(80, 1000)\nprint(\"Shape of X: %s\" % (X_r.shape, ), '\\n')\n\ny_r = np.tile([0, 1], 40)\nprint(\"Shape of y: %s\" % (y_r.shape, ))\nprint(\"Y labels:\\n%r\" % y_r.tolist(), '\\n')\nruns = np.repeat([1, 2, 3, 4], 20)\nprint(\"Shape of runs: %s\" % (runs.shape, ))\nprint(\"Run-indices: \\n%r\" % runs.tolist())\n```\n\nNow, scikit-learn offers a nice cross-validation class that partitions your data according to a \"grouping\" variable: `GroupKFold`, or variations thereof like `LeaveOneGroupOut` of `LeavePGroupsOut`. Let's check out how that can be used using our simulated data:\n\n\n```python\n# Import from model_selection module\nfrom sklearn.model_selection import GroupKFold\n\n# In fact, when we initialize GroupKFold with 4 splits, as below, it is exactly the same as\n# the LeaveOneGroupOut cross-validator, since we only have 4 groups\ngkf = GroupKFold(n_splits=4)\nfor train_idx, test_idx in gkf.split(X=X_r, y=y_r, groups=runs):\n    \n    print(\"Indices of our test-samples: %r\" % test_idx.tolist())\n    print(\"... which correspond to following runs: %r\" % runs[test_idx].tolist(), '\\n')\n```\n\nAs you can see in the example above, the `GroupKFold` cross-validator effectively partionioned our data such that in every fold one group was left out for testing (group 4 in the first fold, group 3 in the second fold, etc.)! So keep in mind to use this type of cross-validation object when you want to employ such a run-wise-cross-validation routine (which is recommended anyway to avoid within-run confounds such as autocorrelation between samples!). \n\n<div class='alert alert-info'>\n**ToThink**: While stratification can be ensured by using e.g. `StratifiedKFold` cross-validators, stratification cannot be guaranteed when using `GroupKFold`. Why do you think this is the case? \n</div>\n\n### Advanced: repeated random splits\nAn often heard question about cross-validation is what train/test ratio one should choose in their cross-validation paradigm. Usually, larger train sets (and thus smaller test sets), such as Leave-One-Out-Cross-Validation, lead to a **higher average performance** across folds, but also a **larger variance** of performance across folds. Or, in ML terms: a large train/test ratio leads to relatively low *bias* but high *variance*. \n\nOn the other hand, relatively larger test-sets lead to lower performance estimates on average, but also less variance across folds. As such, it has been proposed to use test-sets of about 10% or 20% (that is, 10- or 5-fold cross-validation). Furthermore, instead of just doing K-fold cross-validation *once*, it has been argued that drawing *repeated random splits* of, let's say, 10% of your data improves generalization even more (see [Varoquaux (2017)](http://www.sciencedirect.com/science/article/pii/S105381191630595X)).\n\nThis *repeated random splits* technique is sometimes referred to as *bagging* (which stands for *bootstrap aggregating*), a common \"ensembling\" technique in machine learning. Scikit-learn provides a class that implements this *repeated random splits* technique: `StratifiedShuffleSplit`. If you feel like it, try to implement a cross-validation pipeline using this procedure as indicated in the next ToDo.\n\n<div class='alert alert-warning'>\n**ToDo**: Below, try to implement a *repeated random splits* cross-validation routine using `StratifiedShuffleSplit` with 100 repetitions and a test-size of 0.2! Check out the [documentation](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedShuffleSplit.html#sklearn.model_selection.StratifiedShuffleSplit) for more info about its parameters.\n</div>\n\n\n```python\nfrom sklearn.model_selection import StratifiedShuffleSplit\n# Try implementing the ToDo here\n```\n\n## 2.8. Feature selection/extraction\nWhile a complete discussion on (causes of) the phenomenon of \"overfitting\" is definitely beyond the scope of this workshop, it is generally agreed upon that a small sample/feature-ratio will likely lead to overfitting of your models (optimistic performance estimates on train-set). A small sample/feature ratio, unfortunately, is very common in machine learning analyses of neuroimaging (and especially fMRI) data, as the number of features (voxels, MEG sensors) often largely outnumber the amount of samples (trials or subjects).\n\nGiven that this small sample/feature ratio (usually) leads to overfitting, it follows that reducing the amount of features often has a beneficial effect on cross-validated performance estimates. (Or alternatively, increasing your number of samples, but this is not always feasible due to practical and financial reasons...)\n\nFeature reduction can be achieved in two principled ways:\n\n* feature extraction: transform your features into a set of lower-dimensional components;\n* feature selection: select a subset of features\n\nExamples of feature extraction are PCA (i.e. transform voxels to orthogonal components) and averaging features within brain regions from an atlas.\n\nExamples of feature selection are ROI-analysis (i.e. restricting your patterns to a specific ROI in the brain) and \"univariate feature selection\" (UFS). This latter method is an often-used data-driven method to select features based upon their univariate difference, which is basically like using a traditional whole-brain mass-univariate analysis to select potentially useful features!\n\n<div class='alert alert-info'>\n**ToThink**: Suppose a researcher wants to decode gratings with two different orientations from V1. To delineate V1, the subject underwent a retinotopy session in a *different* fMRI run. The data from this retinotopy session was subsequently used to extract (\"mask\") V1 by excluding non-significant voxels; the significant voxels were in turn used to base the orientation decoding analysis on. <br><br>Is masking V1 using the retinotopy data a form of *feature selection* or *feature extraction*? Why? \n</div>\n\n<div class='alert alert-info'>\n**ToThink**: What could be a reason to prefer feature selection above feature extraction? And the other way around? \n</div>\n\nFortunately, scikit-learn has a bunch of feature selection/extraction objects for us to use. These objects (\"transformers\" in scikit-learn lingo) work similarly to estimators: they also have a `fit(X, y)` method, in which for example the univariate differences (in UFS) or PCA-components (in PCA-driven feature extraction) are computed. Then, instead of having a `predict(X)` method, transformers have a `transform(X)` method.\n\n### 2.8.1. (Univariate) feature selection\nAs an example of feature selection, let's take a closer look at how UFS can be implemented using scikit-learn. Basically, it follows the following structure:\n\n```\ntransformer = Selector(score_func=ufs_function, other_args)\n```\n\nHere, the `score_func` parameter takes a function that implements a univariate statistical test (like an [f-test](http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.f_classif.html#sklearn.feature_selection.f_classif) or a [chi-square test](http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.f_classif.html#sklearn.feature_selection.chi2)). The `Selector` class determines how to select the subset of features based on the result of the `score_func`. \n\nFor example, the [SelectKBest](http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.SelectKBest.html#sklearn.feature_selection.SelectKBest) selector selects the best `K` features based on their scores from the statistical test. For example, the following transformer would select the best 2000 features based on their F-score:\n\n\n```python\nfrom sklearn.feature_selection import SelectKBest, f_classif\n\n# f_classif is a scikit-learn specific implementation of the F-test\nselect2000best = SelectKBest(score_func=f_classif, k=2000)\n```\n\nAnother example of a selector is `SelectFwe` which selects only features with statistics-values corresponding to p-values lower than a set alpha-level. For example, the following transformer would only select features with p-values from a chi-square test lower than 0.01: \n\n\n```python\nfrom sklearn.feature_selection import SelectFwe, chi2\nselectfwe_transformer = SelectFwe(score_func=chi2, alpha=0.01)\n```\n\nBut how does this work in practice? We'll show you an (not cross-validated!) example using the select2000best transformer initialized earlier:\n\n\n```python\n# Fit the transformer ...\nselect2000best.fit(X, y)\n\n# ... which calculates the following attributes (.scores_ and .pvalues_)\n# Let's check them out\nscores = select2000best.scores_\npvalues =  select2000best.pvalues_\n\n# As you can see, each voxel gets its own score (in this case: an F-score)\nprint(scores.size)\n\n# and its own p-value:\nprint(pvalues.size)\n```\n\nWe can also visualize these scores in brain space: \n\n\n```python\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nscores_3d = scores.reshape((80, 80, 37))\nplt.figure(figsize=(20, 5))\n\nfor i, slce in enumerate(np.arange(15, 65, 5)):\n    plt.subplot(2, 5, (i+1))\n    plt.title('X = %i' % slce, fontsize=20)\n    plt.imshow(scores_3d[slce, :, :].T, origin='lower', cmap='hot')\n    plt.axis('off')\nplt.tight_layout()\nplt.show()\n```\n\nThus, in the images above, brighter (more yellow) colors represent voxels with higher scores on the univariate test. If we subsequently apply (or \"transform\" in scikit-learn lingo) our X-matrix using, for example, the `select2000best` selector, we'll select only the 2000 \"most yellow\" (i.e. highest F-scores) voxels.\n\n<div class='alert alert-info'>\n**ToThink**: Given the image above, what is the major difference between data driven feature selection (like UFS) and ROI-based feature selection (e.g. only look at patterns in the amygdala) in terms of the spatial scale of patterns you'll select? Try to think of an example of UFS over ROI-based feature selection and vice versa.\n</div>\n\nPractically, after we've fit the transformer, we can call the `transform(X)` method that will actually select the subset according to the selector:\n\n\n```python\nprint(\"Shape of X before transform: %r ...\" % (X.shape,))\nX_after_ufs = select2000best.transform(X)\n\nprint(\"... and shape of X after transform: %r.\" % (X_after_ufs.shape,))\n```\n\nAs you can see, the transformer correctly selected a subset of 100 voxels from our X matrix! Now, both selectors were fit on the entire dataset, which is often course not how it should be done: because they use information from the labels (`y`), this step should be cross-validated. Thus, what you have to do is:\n\n* fit your transformer on the train-set;\n* transform your train-set;\n* transform your test-set;\n* (fit your model on the transformed train-set;)\n* (cross-validate to the transformed test-set;)\n\nWe summarized the entire pipeline, including data partitioning (indexing), feature selection (transformation), and model fitting and their corresponding cross-validation steps in the image below:\n\n\n### 2.8.2 Feature extraction\nThere are many methods for feature extraction, like \"downsampling\" to ROI-averages (i.e. averaging voxel patterns in brain regions) and dimensionality-reduction techniques like PCA. Scikit-learn provides some of these techniques as \"transformer\" objects, which again have a `fit()` and `transform` method. \n\n**Note**: since feature extraction techniques like PCA do not strictly use information from the labels (`y`), you might think that you do not have to cross-validate this step in your pipeline. This is **not** true. For a completely unbiased generalization error, you need to cross-validate every transformation in your data-set that is in some way dependent on the data (like UFS, PCA, but *not* ROI-based feature selection, since this is not dependent on the patterns themselves). \n\nIn the next ToDo, you'll have to apply PCA-based feature extraction!\n\n<div class='alert alert-warning'>\n**ToDo**: Below, we import the `PCA` class from scikit-learn. Check out the [documentation](http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html). Now, initialize an object from this `PCA`-class with the number of components to store set to 5, and subsequently fit in on `X_train_tmp` and subsequently call transform on `X_train_tmp` and `X_test_tmp` separately; store the result in the variables `X_train_pca_transformed` and `X_test_pca_transformed`. Then, check out the shape of `X_train_pca_transformed`: does it have the shape you expected?\n</div>\n\n\n```python\n# Implement your ToDo here!\nfrom sklearn.decomposition import PCA\nX_train_tmp, X_test_tmp = train_test_split(X, test_size=0.5)\n\n# initialize a PCA object ...\n\n# ... call fit on X_train_tmp ...\n\n# ... and call transform on X_train_tmp and X_test_tmp\nX_train_pca_transformed = \nX_test_pca_transformed = \n\n# And finally check out the shape of X_pca_transformed!\n\n```\n\n### Integrating feature selection and model fitting/cv!\nNow, let's put everything you learned so far together and implement a fully cross-validated pipeline with UFS *and* model fitting/prediction!\n\n<div class='alert alert-warning'>\n**ToDo**: Below, we set up a K-fold cross-validation loop and prespecified a classifier (`clf`, a logistic regression model) and a transformer (`select1000best`, selecting the 1000 best features based upon an F-test). Now, it's up to you to actually implement the feature selection inside the for-loop. Make sure to fit the transformer only on the train-set, but then transform *both* the train-set and the test-set. Then, fit the model on the transformed train-set and cross-validate to the transformed test-set. Calculate performance (metric of your choice) of the cross-validated  model for each fold, and after all folds calculate the average performance (across folds).\n</div>\n\n\n```python\nfrom sklearn.linear_model import LogisticRegression\n\nclf = LogisticRegression()\nfolds = skf.split(X, y)\n\nperformance = np.zeros(skf.n_splits)\nselect1000best = SelectKBest(score_func=f_classif, k=1000)\n\ni = 0\nfor train_ix, test_idx in folds:\n    \n    # ToDo: make X_train, X_test, y_train, y_test\n    \n    # ToDo: call the select1000best fit method (on X_train), and transform both X_train and X_test\n    \n    # ToDo: fit model on X_train (transformed) and predict X_test (transformed)\n    # also, save your performance (e.g roc-auc-curve) in the \"performance\" variable\n\n# ToDo: calculate average performance\n\n```\n\nIf you did the above ToDo, your performance is likely a bit higher than in the previous section in which we *didn't* do any feature selection/extraction! \n\n### Advanced: cross-validation using Pipelines (optional)\n\nAs you have seen in the previous assignment, the code within the K-fold for-loop becomes quite long (and messy) when you add a feature-selection step. Suppose you want to add another feature extraction step, like performing a PCA after an initial feature selection step. The code then becomes even more obscure ...\n\nFortunately, scikit-learn has an awesome solution for this: \"Pipelines\".\n\nPipelines are somewhat more advanced functionality within scikit-learn, but we wanted to show you because it really \"cleans up\" your code, and additionally, it is a great safeguard for accidental overfitting (e.g. when you accidentally perform feature-selection on all your data instead of only your train-data). \n\nAnyway, how does this work? Well, a picture it worth a thousand words, so check out the image below which schematically depicts what a pipeline does:<br> \n\nAs you can see, a `Pipeline`-object \"strings together\" an arbitrary number of transformers (including \"preprocessing\" transformers like `StandardScaler`\\*) and can optionally end in an estimator. Pipeline-objects have two (relevant) methods: `fit(X, y)` and `predict(X, y)` (the latter method only exists if there is an estimator in the pipeline). To use it, you only have to call `fit()` with `X_train` and `y_train` and it'll sequentially fit the transformers which will finally pass the transformed data to the estimator. Then, simply call `predict()` with `X_test` as argument and the pipeline will automatically cross-validate all fitted transformers, and eventually the estimator, on the `X_test` variable. \n\nOkay, lot's of info - let's break this down. First, let's initialize some transformers and an estimator:\n\n------------\n\\* Feature scaling using e.g. [StandardScaler](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html), which we discussed earlier, is generally recommended to cross-validate as well (i.e. apply the mean and std from the train-set to standardize the test-set.)\n\n\n```python\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\n\nscaler = StandardScaler()\nufs = SelectKBest(score_func=f_classif, k=1000)\npca = PCA(n_components=10)  # we want to reduce the features to 10 components\nsvc = SVC(kernel='linear')\n```\n\nNow, to initialize a Pipeline-object, we need to give it a list of tuples, in the first entry of each tuple is a name for the step in the pipeline and the second entry of each tuple is the actual transformer/estimator object. Let's do that for our pipeline:\n\n\n```python\nfrom sklearn.pipeline import Pipeline\n\npipeline_to_make = [('preproc', scaler),\n                    ('ufs', ufs),\n                    ('pca', pca),\n                    ('clf', svc)]\n\nmy_pipe = Pipeline(pipeline_to_make)\n```\n\nLet's test our pipeline-object (`my_pipe`) on our data. For this example, we'll use a simple hold-out cross-validation scheme (but pipelines are equally valuable in K-fold CV schemes!).\n\n\n```python\nX_train, y_train = X[0::2], y[0::2]\nX_test, y_test = X[1::2], y[1::2]\n\nmy_pipe.fit(X_train, y_train)\npredictions = my_pipe.predict(X_test)\nperformance = roc_auc_score(y_test, predictions)\nprint(\"Cross-validated performance on test-set: %.3f\" % performance)\n```\n\nCool stuff huh? Quite efficient, I would say!\n\n<div class='alert alert-warning'>\n**ToDo**: Test your pipeline-skills! Can you build a pipeline that incorporates a [VarianceThreshold](http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.VarianceThreshold.html#sklearn.feature_selection.VarianceThreshold) (removes all voxels outside the brain), K-means clustering (with 8 clusters, such that $K$ voxels --> 8 clusters, using [KMeans](http://scikit-learn.org/stable/modules/generated/sklearn.cluster.k_means.html#sklearn.cluster.k_means)), scaling (`StandardScaler`), and a [RandomForestClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html#sklearn.ensemble.RandomForestClassifier)?\n</div>\n\n\n```python\n# Implement the ToDo here\nfrom sklearn.feature_selection import VarianceThreshold\nfrom sklearn.cluster import KMeans\nfrom sklearn.ensemble import RandomForestClassifier\n\n```\n\n## 2.9. Assessing significance\nUp to now, we examined the model performance of decoding the experimental condition from fMRI data of a **single** subject. When averaging over folds, we got one scalar estimate of performance. Usually, though, within-subject decoding studies measure multiple subjects and want to test whether their hypothesis - which is usually that *decoding is above chance* - generalizes to the population. Chance level decoding depends on the specific metric you use; for example, for accuracy, chance level equals to $\\frac{1}{P}$, where $P$ is the amount of classes. Decoding with binary classes, therefore, have a chance level of 50% for accuracy. However, as discussed before, accuracy is biased in scenarios with imbalanced classes, so we should use a 'class-imbalance-aware' metric - such as F1-score of ROC-AUC-curve - instead.\n\nAnyway, let's assume we use ROC-AUC-curve as our performance metric (its chance level is also 0.5), our group-level null ($H_{0}$) and alternative ($H_{a}$) hypotheses become:\n\n* $H_{0}$: performance = 0.5\n* $H_{a}$: performance > 0.5\n\nGiven that we obtained performance estimates from a group of subjects, which should yield *independent* estimates, we can simply do a one-sample *t-test* of our performance estimates against chance (0.5).**\\*** To do so, we first need to loop our decoding analysis across all our participants to get a sample of decoding performances.\n\n---\n**\\* Note**: Last year, Allefeld and colleagues published a [paper](http://www.sciencedirect.com/science/article/pii/S1053811916303470) in which they show that second-level statistics using a t-test (or other parametric statistics) based on \"first-level\" per-subject performance estimates does **not** entail a random-effects analysis, but rather a fixed-effects analysis, and thus does not warrant inference to the population. This is because *true* performance estimates cannot possibly be below chance. We haven't had time to implement this ourselves for this workshop (we're working on implementing this in [skbold](skbold.readthedocs.io)), so we recommend checking out the paper yourself! \n\n<div class='alert alert-warning'>\n**ToDo**: Before we start, we need to get the participant numbers of all our participants. To find these, we can make use of the directory names. In Section **1.4.1** you learned the tricks you need to get all subdirectory names of the `data` directory using a wildcard!\n\n</div>\n\n\n```python\nparticipant_numbers =  # Fill in the right glob call here!\n\n# Next, we need to extract the participant numbers from the paths you just obtained. We do this for you here.\nparticipant_numbers = [x.split(op.sep)[-1] for x in participant_numbers]\nprint(participant_numbers)\n```\n\n#### Want to skip the ToDo?\nRun the next cell.\n\n\n```python\nwith open(op.join('example_data', 'subject_names'), 'r') as f:\n    participant_numbers = [s.replace('\\n', '') for s in f.readlines()]\n```\n\nWe can now use this `participants_numbers` list to loop over the participant names!\n\n<div class='alert alert-warning'>\n**ToDo** (optional!): This final ToDo is a big one, in which everything we learned so far comes together nicely. Write a loop over all participants, implementing a cross-valdidated classification pipeline including feature selection. We provide you with some \"boilerplate\" code to start with, but it's up to you to complete the analysis/loop.\n<br><br>\nMake sure to include the following:\n<br>\n    1. Scale the patterns (even better: cross-validate your scaler)<br>\n    2. Use 5-fold Stratified cross-validation<br>\n    3. Within each fold, select the best 100 features using an f_classif Selector<br>\n    4. Use a SVM to decode condition from these 100 features<br><br>\n    \nOptional:<br>\n- Use a scikit-learn Pipeline in which you group your scaler, selector, and estimator!<br><br>\n\nHints:<br>\n- The design for each subject was exactly the same, so you can use the same \"y\" as in the previous example!<br>\n\n</div>\n\n\n```python\n### Set your analyis parameters/pipeline ###\n\n# ToDo: initialize a stratified K-fold class (let's use K=5) \nskf =  \n# ToDo: Initialize the SelectKBest Selector with an f_classif score function\nselect100best = \n    \n# ToDo: initialize an SVC-object\nclf = \n\n# Optional: build a pipeline-object!\n\n# Keep track of all performance estimates\nall_performance = np.zeros(len(participant_numbers))\n\n### Start loop over subjects ###\nfor i_sub, participant_number in enumerate(participant_numbers):\n    \n    # For each participant, get all tstat file paths. We did this for a single subject in Section 1.3.1!\n    path_this_participant = op.join('..', 'data', participant_number, 'wm.feat', 'stats', 'tstat*.nii.gz')\n    t_stat_paths_this_participant = sort_nifti_paths(glob(path_this_participant))\n    \n    # Then, we need to create the pattern matrix X for each participant. Remember how we did this in Section 1.3.1?\n    # For each participant, we need to get the data dimensions. Let's extract these from the nifti header. \n    voxel_dims = nib.load(t_stat_paths_this_participant[0]).header.get_data_shape()\n    X = np.zeros((len(t_stat_paths_this_participant), np.prod(voxel_dims)))\n\n    # Load the data of each trial separately. This was the last thing we did as part of Part 1.\n    for trial, tstat_path in enumerate(t_stat_paths_this_participant):\n        data = nib.load(tstat_path).get_data()\n        data = data.ravel()\n        X[trial,:] = data\n    \n    # ToDo: scale the patterns (or optionally: cross-validate the scaler by fitting on train)\n    \n    # All data of the current participant is now loaded! We can start the pattern analysis for this participant now\n    \n    # Keep track of performance between folds\n    performance_this_participant = np.zeros(skf.n_splits)\n    \n    # Loop over the folds\n    for i_fold, (train_idx, test_idx) in enumerate(skf.split(X, y)):\n\n        # ToDo: make X_train, X_test, y_train, y_test\n\n        # ToDo: call the select100best fit method (on X_train), and transform both X_train and X_test\n    \n        # ToDo: fit your model on the train data\n        \n        # ToDo: predict the classes of your test data\n        \n        # ToDo: calculate the performance (use ROC-AUC-curve) in this fold\n        performance = \n        \n        performance_this_participant[i_fold] = performance\n\n    # ToDo: calculate average accuracy (mean across folds!)\n    mean_performance_this_participant = \n    print('Mean performance for participant %s: %.3f' % (participant_number, mean_performance_this_participant))\n    \n    all_performance[i_sub] = mean_performance_this_participant\n\nprint('Final performance mean (std): %.3f (%.3f)' % (all_performance.mean(), all_performance.std())\n```\n\nIf everything went well, you now have a list `all_performance` which contains the accuracies (mean over folds) of all participants! This is all data we need to do a one-sample t-test.\n\nThe one-sample t-test is implemented in the Python package Scipy. Let's load it first\n\n\n```python\nfrom scipy.stats import ttest_1samp\n```\n\nThe function requires two arguments: the vector of values to test, and the hypothesized population mean. In our case, the data vector is `all_accuracies`, and the population mean is 0.50. If done correctly, the `ttest_1samp` function returns a tuple of the t-value and the p-value.\n\n<div class='alert alert-warning'>\n**ToDo**: Do the one-sample t-test! Can we decode the condition with a significantly above-chance accuracy?\n\n</div>\n\n\n```python\n# Example answer\nt, p = ttest_1samp(all_performance, 0.5)\nprint('The t-value is %.3f, with a p-value of %.5f' % (t, p))\n```\n\nFinally, we can draw our conclusions: can we decode trial condition, using the fMRI data, with an above-chance accuracy? (Yes we can! But remember, the results are probably positively biased due to autocorrelated samples and, as discussed earlier, this t-test is not a proper random-effects analysis!)\n\n## Congratulations! You've reached the end of this tutorial\n\nWe hope you enjoyed the workshop. It should be stressed that these are really the basics of MVPA - every step that was introduced warrants it own workshop (feature selection, feature extraction, model selection, cross-validation, significance testing - and much more that we did not discuss such as regularization, hyperparameter optimization/grid-search, and feature visualization). You are encouraged to discover what's possible with MVPA on your own!\n\nGood luck using MVPA!\n\n## Extra literature ...\nIf you want some more background information/material on machine learning in the context of neuroimaging, we recommend the following articles:\n\n#### On machine learning in Python\n* [Pedregosa, F., Varoquaux, G., Gramfort, A., Michel, V., Thirion, B., Grisel, O., ... & Vanderplas, J. (2011). Scikit-learn: Machine learning in Python. Journal of Machine Learning Research, 12(Oct), 2825-2830.](http://www.jmlr.org/papers/v12/pedregosa11a.html)\n* [Abraham, A., Pedregosa, F., Eickenberg, M., Gervais, P., Mueller, A., Kossaifi, J., ... & Varoquaux, G. (2014). Machine learning for neuroimaging with scikit-learn. Frontiers in neuroinformatics, 8.](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3930868/)\n\n#### On MVPA design\n* [Mumford, J. A., Turner, B. O., Ashby, F. G., & Poldrack, R. A. (2012). Deconvolving BOLD activation in event-related designs for multivoxel pattern classification analyses. Neuroimage, 59(3), 2636-2643.](http://www.sciencedirect.com/science/article/pii/S1053811911010081)\n* [Mumford, J. A., Davis, T., & Poldrack, R. A. (2014). The impact of study design on pattern estimation for single-trial multivariate pattern analysis. Neuroimage, 103, 130-138.](http://www.sciencedirect.com/science/article/pii/S105381191400768X)\n\n* [Abdulrahman & Henson. (2016). Effect of trial-to-trial variability on optimal event-related fMRI design: Implications for Beta-series correlation and multi-voxel pattern analysis](http://www.sciencedirect.com/science/article/pii/S1053811915010319)\n\n#### On cross-validation\n* [Varoquaux, G., Raamana, P. R., Engemann, D. A., Hoyos-Idrobo, A., Schwartz, Y., & Thirion, B. (2017). Assessing and tuning brain decoders: cross-validation, caveats, and guidelines. NeuroImage, 145, 166-179.](http://www.sciencedirect.com/science/article/pii/S105381191630595X)\n* [Varoquaux, G. (2017). Cross-validation failure: small sample sizes lead to large error bars. NeuroImage.](http://www.sciencedirect.com/science/article/pii/S1053811917305311#bib51)\n\n#### On (group-level) statistics\n* [Allefeld, C., G\u00f6rgen, K., & Haynes, J. D. (2016). Valid population inference for information-based imaging: From the second-level t-test to prevalence inference. NeuroImage, 141, 378-392.](http://www.sciencedirect.com/science/article/pii/S1053811916303470)\n* [Etzel, J. (2017). MVPA significance testing when just above chance, and related properties of permutation tests. 2017 International Workshop on Pattern Recognition in Neuroimaging (PRNI)](http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=7981498)\n\n## Extra! Using `skbold` for your machine learning analyses\nAs mentioned earlier, we developed `skbold`, a Python package that offers a set of tools to make machine learning analyses of fMRI data easier. In what follows, we showcase the functionality of skbold at different stages of the typical machine learning pipeline!\n\n### Data structuring and representation\nAs you've seen, there is a lot of \"boilerplate\" code involved in loading in/structuring the patterns and corresponding labels. In skbold we created a custom object, the `Mvp` (**m**ulti**v**oxel **p**attern object), which makes the pattern structuring and preprocessing trivially easy. There are two flavours of `Mvp`-objects: the `MvpWithin` object and the `MvpBetween` object, which are appropriate for within-subject and between-subject decoding analyses, respectively. Given that our example dataset is a within-subject data-set, let's look at an example of how to use `MvpWithin`.\n\nFirst, we load in the class from `skbold.core`:\n\n\n```python\n# we'll reset our namespace to free up some memory\n%reset -f \nfrom skbold.core import MvpWithin\nimport os.path as op\n```\n\nNow, the `MvpWithin` class is able to quickly load and transform data from FSL-feat (i.e. first-level) directories. It looks for patters in the `stats` directory (given a specific `statistic`) and loads condition-labels from the `design.con` file, which are all standard contents of FEAT-directories.\n\nAdditionally, we can specify a mask to mask out patterns with. This mask can be in MNI-space or native EPI-space - skbold handles the registration between these two spaces (*only* if FSL is installed!). We can also choose to remove voxels which are values 0 across all samples (which are probably located outside the brain).\n\nWe need to specify these parameters upon initialization of an `MvpWithin` object:\n\n\n```python\nfeat_dir = op.join('..', 'data', 'pi0070', 'wm.feat')\nmask_file = None   # only works if you have FSL installed (if so, uncomment the next line!)\n\n# UNCOMMENT IF YOU HAVE FSL INSTALLED!)\n#mask_file = op.join('..', 'data', 'GrayMatter_prob.nii.gz') # mask all non-gray matter! \nread_labels = True      # parse labels (targets) from design.con file!\nref_space = 'epi'       # extract patterns in functional space (alternatively: 'mni')\nstatistic = 'tstat'     # use the tstat*.nii.gz files (in *.feat/stats) as patterns\nremove_zeros = True     # remove voxels which are zero in each trial\n\nmvp = MvpWithin(source=feat_dir, read_labels=read_labels, ref_space=ref_space, \n                statistic=statistic, remove_zeros=remove_zeros, mask=mask_file)\n```\n\nAlright, now we can simply call the `create()` method to start the pattern loading/structuring process!\n\n\n```python\nmvp.create() \n```\n\nAfter calling `create()`, the `Mvp`-object has a couple of 'new' attributes! Let's check them out.\n\n\n```python\nprint(\"The attribute .X represents our samples-by-features matrix of shape %s\" % (mvp.X.shape,))\nprint(\"The attribute .y represents our targets (y) of shape %s\" % (mvp.y.shape,))\n```\n\nAs you can see, these are exactly the patterns (X) and labels (y) which we created manually earlier in our workshop (except for that `X` contains fewer features due to the setting `remove_zeros=True`). We can also inspect the names of the patterns (as parsed from the `design.con` file):\n\n\n```python\nprint(mvp.contrast_labels)\n```\n\n### Feature extraction / selection\nAnother feature of `skbold` is that is offers some neuroimaging-specific transformers (implemented the same way as scikit-learn transformers). Let's look at, for example, the `ClusterThreshold` class - a transformer that applies a (3D) cluster-thresholding procedure on top of univariate feature selection and subsequently returns the cluster-average values as features (i.e. a dimensionality reduction procedure that reduces voxels to cluster-averages).\n\nLet's check it out:\n\n\n```python\nfrom skbold.feature_extraction import ClusterThreshold\nfrom sklearn.feature_selection import f_classif\n\nclt = ClusterThreshold(mvp=mvp, min_score=10, selector=f_classif)\n```\n\nWe initialized our `ClusterThreshold` object to perform an initial threshold at `min_score=10`. The voxels that \"survived\" this threshold are subsequently clustered and averaged within clusters. Below, we'll show that the API is exactly the same as scikit-learn's transformers:\n\n\n```python\nfrom sklearn.model_selection import train_test_split\n\n# Let's cross-validate our ClusterThresholding procedure (which you should always do!)\nX_train, X_test, y_train, y_test = train_test_split(mvp.X, mvp.y, test_size=0.25)\nprint(\"Shape of X_train before cluster-thresholding: %s\" % (X_train.shape,))\nprint(\"Shape of X_test before cluster-thresholding: %s\" % (X_test.shape,), '\\n')\n\n# Let's fit and transform\nclt.fit(X_train, y_train)\nX_train_clt = clt.transform(X_train)\nprint(\"Shape of X_train after cluster-thresholding: %s\" % (X_train_clt.shape,))\n\nX_test_clt = clt.transform(X_test)\nprint(\"Shape of X_test after cluster-thresholding: %s\" % (X_test_clt.shape,))\n```\n\nSkbold has many more transformers, such as `RoiIndexer`, which indexes patterns given a certain mask/ROI. It doesn't matter whether the patterns are in EPI-space and the mask/ROI is in MNI-space; skbold registers the mask/ROI from one space to the other accordingly. (It needs FSL for this, and as we don't know whether you have this installed, we won't showcase it here.)\n\n### Model evaluation / Feature visualization\nApart from the `Mvp` object, `skbold` also includes the `MvpResults` object, which is designed to keep track of your pipeline's performance and feature-weights across different folds. You can keep track of any (scikit-learn) metric (like f1-score, accuracy, ROC-AUC-score, etc.). Keeping track of feature weights comes in three 'flavors': the option \"`ufs`\", which keeps track of the 'univariate' feature scores (only applicable if you actually use 'univariate feature selection' in your pipeline); the option \"`fwm`\" ('feature weight mapping', see [this article](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3997040/) which keeps track of the raw feature weights; and the option \"`forward`\", which keeps track of the corresponding forward model weights given the feature weights (see [this article](http://www.sciencedirect.com/science/article/pii/S1053811913010914)).\n\nAnyway, let's look at how we shoulds initialize such an object:\n\n\n```python\nfrom skbold.postproc import MvpResults\nfrom sklearn.metrics import accuracy_score, f1_score\n\nmvpr = MvpResults(mvp=mvp, n_iter=5, feature_scoring='forward', confmat=True,\n                  accuracy=accuracy_score, f1=f1_score)\n```\n\nImportantly, the `MvpResults` class needs a `Mvp` object upon initialization to extract some meta-data and it needs to know how many folds (`n_iter`) we're going to keep track of (here we assume we'll do 5-fold CV). We also indicate that we want to keep track of the confusion-matrices across folds (`confmat=True`) and after that we specified a couple of metrics (you can indicate *any* amount of metrics in the form `name_metric=sklearn_metric_function`).\n\nNow, we can build a ML pipeline and update our `MvpResults` object after each fold. Importantly, as you'll see below, to correctly extract feature-weights, you need to pass a `Pipeline` object when calling the method `update()`.\n\nLet's first import some things for our pipeline and define the pipeline and CV-scheme:\n\n\n```python\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.feature_selection import f_classif, SelectKBest\nfrom sklearn.svm import SVC\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import StratifiedKFold\n\npipe_line = Pipeline([('scaler', StandardScaler()),\n                      ('ufs', SelectKBest(score_func=f_classif, k=1000)),\n                      ('clf', SVC(kernel='linear'))\n                     ])\n\nskf = StratifiedKFold(n_splits=5)\n```\n\nNow we can implement our analysis and simply call `mvpr.update()` after each fold:\n\n\n```python\nfor i, (train_idx, test_idx) in enumerate(skf.split(mvp.X, mvp.y)):\n    print(\"Processing fold %i / %i\" % (i+1, skf.n_splits))\n    X_train, X_test = mvp.X[train_idx], mvp.X[test_idx]\n    y_train, y_test = mvp.y[train_idx], mvp.y[test_idx]\n    pipe_line.fit(X_train, y_train)\n    pred = pipe_line.predict(X_test)\n    mvpr.update(test_idx=test_idx, y_pred=pred, pipeline=pipe_line)\n```\n\nWe can check out the results of our analysis by calling the `compute_scores()` method:\n\n\n```python\nperformance, feature_scores = mvpr.compute_scores()\n```\n\nThis prints out the mean and standard-deviation of our metrics across folds and the amount of voxels that were part of the analysis. We can check out the per-fold performance by looking at the first returned variable (here: `performance`):\n\n\n```python\nperformance\n```\n\nAlso, we can check out the feature-scores (here: the \"forward\" model corresponding to the classifier weights), which is returned here as `feature_scores`. This is a `nibabel` Nifti-object, which we can check out using matplotlib:\n\n\n```python\nimport nibabel as nib\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nplt.figure(figsize=(20, 5))\nscores_3d = feature_scores.get_data()\nbackground = op.join('..', 'data', 'pi0070', 'wm.feat', 'reg', 'example_func.nii.gz')\nbackground = nib.load(background).get_data()\n\nfor i, slce in enumerate(np.arange(20, 60, 5)):\n    plt.subplot(2, 4, (i+1))\n    plt.title('X = %i' % slce, fontsize=20)\n    to_plot = np.ma.masked_where(scores_3d[slce, :, :] == 0, scores_3d[slce, :, :])\n    plt.imshow(background[slce, :, :].T, origin='lower', cmap='gray')\n    plt.imshow(to_plot.T, origin='lower', cmap='hot')\n    plt.axis('off')\nplt.tight_layout()\nplt.show()\n```\n\nAlmost always you have more than one subject, so what you can do is loop over subjects and initialize a new `MvpResults` object for every subject and store them in a separate list. Once the loop over subjets is completed, simply initialize a `MvpAverageResults` and call `compute_statistics()`, which we'll show below:\n\n\n```python\nfrom glob import glob\nfeat_dirs = glob(op.join('..', 'data', 'pi*', 'wm.feat'))\nn_folds = 5\n\nmvp_results_list = []\nfor feat_dir in feat_dirs:\n    print(\"Subject: %s\" % feat_dir)\n    mvp = MvpWithin(source=feat_dir, read_labels=read_labels,\n                    ref_space=ref_space, statistic=statistic,\n                    remove_zeros=remove_zeros,\n                    mask=mask_file)\n    mvp.create()\n    mvpr = MvpResults(mvp=mvp, n_iter=5, feature_scoring='forward', confmat=True,\n                  accuracy=accuracy_score, f1=f1_score)\n\n    for train_idx, test_idx in skf.split(mvp.X, mvp.y):\n        X_train, X_test = mvp.X[train_idx], mvp.X[test_idx]\n        y_train, y_test = mvp.y[train_idx], mvp.y[test_idx]\n        pipe_line.fit(X_train, y_train)\n        pred = pipe_line.predict(X_test)\n        mvpr.update(test_idx=test_idx, y_pred=pred, pipeline=pipe_line)\n    \n    mvp_results_list.append(mvpr)\n```\n\n\n```python\nfrom skbold.postproc import MvpAverageResults\nmvpr_average = MvpAverageResults()\nsubjects = [op.basename(op.dirname(f)) for f in feat_dirs]\nresults = mvpr_average.compute_statistics(mvp_results_list, identifiers=subjects, metric='f1', h0=.5)\nresults\n```\n\n### Questions? Suggestions? \nThis section demonstrated some of the functionality of skbold. If you have any questions, suggestions, or want more information about skbold - feel free to ask (or email!). Details on skbold and its API can be found on its page on [ReadTheDocs](skbold.readthedocs.io)!\n", "meta": {"hexsha": "9fb9be8a6760d0d245c408c30223c29477743e18", "size": 124981, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorial/ICON2017_tutorial.ipynb", "max_stars_repo_name": "lukassnoek/ICON2017_MVPA", "max_stars_repo_head_hexsha": "89af3be9b9565cd8a9f6be940edb1c870b5a1c9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2017-08-06T06:30:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T10:37:48.000Z", "max_issues_repo_path": "tutorial/ICON2017_tutorial.ipynb", "max_issues_repo_name": "lukassnoek/ICON2017_MVPA", "max_issues_repo_head_hexsha": "89af3be9b9565cd8a9f6be940edb1c870b5a1c9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-08-06T11:44:10.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-06T11:44:10.000Z", "max_forks_repo_path": "tutorial/ICON2017_tutorial.ipynb", "max_forks_repo_name": "lukassnoek/ICON2017_MVPA", "max_forks_repo_head_hexsha": "89af3be9b9565cd8a9f6be940edb1c870b5a1c9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-08-06T07:08:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-04T09:22:28.000Z", "avg_line_length": 48.7635583301, "max_line_length": 926, "alphanum_fraction": 0.6598683, "converted": true, "num_tokens": 23089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32766831395172374, "lm_q2_score": 0.09268778114565465, "lm_q1q2_score": 0.03037084897192303}}
{"text": "# Receiver operator modeling and characterization\nIn this notebook we will construct a genetic network to model a Receiver operator, a signal receiver device, upload the simulated data to Flapjack, and then show how to characterize the operator based on this data.\n\n## Import required packages\n\n\n\n```python\nfrom loica import *\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport getpass\n```\n\n## Make a connection to Flapjack\nNote here you should specify which instance of Flapjack you will use, whether it is local or the public instance for example.\n\n\n```python\nfrom flapjack import *\n#fj = Flapjack(url_base='flapjack.rudge-lab.org:8000')\nfj = Flapjack(url_base='localhost:8000')\nfj.log_in(username=input('Flapjack username: '), password=getpass.getpass('Password: '))\n```\n\n## Get or create Flapjack objects\nTo associate with the components of the genetic network and the simulated data with Flapjack we need the Ids of the appropriate objects. Note that if the objects already exist you will be prompted and can simply hit return to use the existing objects.\n\n\n```python\nstudy = fj.create('study', name='Loica testing', description='Test study for demonstrating Loica')\n```\n\n\n```python\nsfp = fj.create('signal', name='SFP', color='green', description='Simulated fluorescent protein')\n```\n\n\n```python\ndna = fj.create('dna', name='receiver1')\nvector = fj.create('vector', name='receiver1', dnas=dna.id)\n```\n\n## Create the network with measurable reporter\nFirst we create a GeneticNetwork object and associate it with a Flapjack Vector (collection of DNA). The connection to Flapjack is optional, but we will use it here to upload data and characterize our components.\n\n\n```python\nnetwork = GeneticNetwork(vector=vector.id[0])\n```\n\n\n```python\nreporter = Reporter(name='SFP', color='green', degradation_rate=0, init_concentration=0, signal_id=sfp.id[0])\n```\n\n\n```python\nnetwork.add_reporter(reporter)\n```\n\n## Create the Receiver operator\nThe receiver operator responds to a signal $s$ to produce an output expression rate $\\phi(s)$ modeled as follows:\n\n\\begin{equation}\n    \\phi(s)\n    =\n    \\frac\n    {\n        \\alpha_0 + \\alpha_1 (\\frac{s}{K})^n\n    }\n    {\n        1 + (\\frac{s}{K})^n\n    }\n\\end{equation}\n\nHere we must create a Supplement object to represent the signal, in this case modeling an acyl-homoserine lactone (AHL).\n\n\n```python\nahl = Supplement(name='AHL1')\nrec = Receiver(input=ahl, output=reporter, alpha=[0,100], K=1, n=2)\nnetwork.add_operator(rec)\n```\n\n## Draw the GeneticNetwork as a graph\nWe can now make a visual representation of our GeneticNetwork to check it is wired up correctly.\n\n\n```python\nplt.figure(figsize=(3,3), dpi=150)\nnetwork.draw()\n```\n\n## Simulate the GeneticNetwork\nIn order to simulate the GeneticNetwork behaviour we need to specify the growth conditions in which it will operate. To do this we create a SimulatedMetabolism object which specifies growth functions.\n\n\n```python\ndef growth_rate(t):\n    return gompertz_growth_rate(t, 0.05, 1, 1, 1)\n\ndef biomass(t):\n    return gompertz(t, 0.05, 1, 1, 1)\n    \nmetab = SimulatedMetabolism(biomass, growth_rate)\n\nmedia = fj.create('media', name='loica', description='Simulated loica media')\nstrain = fj.create('strain', name='loica', description='Loica test strain')\n```\n\nNow we can create Samples that contain our GeneticNetwork driven by the SimulatedMetabolism. We also need to specify the Media and Strain, in order to link to the Flapjack data model. To test the signal receiving behaviour we must also add the signal (ahl) at a range of concentrations.\n\n\n```python\n# Create list of samples    \nsamples = []\nconcs = np.append(0, np.logspace(-3, 3, 12))\nfor conc in concs:\n    for _ in range(1):\n        sample = Sample(genetic_network=network, \n                    metabolism=metab,\n                    media=media.id[0],\n                    strain=strain.id[0])\n        # Add AHL to samples at given concentration\n        sample.set_supplement(ahl, conc)\n        samples.append(sample)\n```\n\nGiven our Samples, we can now create an Assay which will simulate an experiment containing them. We need to specify the biomass signal in order to link to the Flapjack data model for later upload. Running the assay will simulate the behaviour of the GeneticNetwork.\n\n\n```python\nbiomass_signal = fj.create('signal', name='SOD', description='Simulated OD', color='black')\nassay = Assay(samples, \n              n_measurements=100, \n              interval=0.24,\n              name='Loica receiver1',\n              description='Simulated receiver generated by loica',\n              biomass_signal_id=biomass_signal.id[0]\n             )\nassay.run()\n```\n\n## Upload simulated data to Flapjack\n\n\n```python\nassay.upload(fj, study.id[0])\n```\n\nNow we can check that the simulation worked by plotting an induction curve using the PyFlapjack package to connect to the Flapjack API. This also allows us to see if we have covered the dynamic range of the Receiver, in order to correctly characterize it.\n\n\n```python\nahl1_id = fj.get('chemical', name='AHL1').id[0]\nfig = fj.plot(study=study.id,                     \n                vector=vector.id,\n                signal=sfp.id,\n                type='Induction Curve',\n                analyte=ahl1_id,\n                function='Mean Expression',\n                biomass_signal=biomass_signal.id[0],\n                normalize='None',\n                subplots='Signal',\n                markers='Vector',\n                plot='All data points'\n       )\nfig\n```\n\n## Characterize the Receiver operator from the uploaded data\n\n\n```python\nrec.characterize(\n    fj,\n    vector=vector.id,\n    media=media.id,\n    strain=strain.id,\n    signal=sfp.id,\n    biomass_signal=biomass_signal.id\n)\n```\n\n\n```python\nrec.alpha, rec.K, rec.n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "50daa9c9f4126a4bb31b986ff8103ba1fbde62b5", "size": 10576, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Receiver1.ipynb", "max_stars_repo_name": "RudgeLab/LOICA", "max_stars_repo_head_hexsha": "ea7f203ccd9642a6793537184dbccc764521f6fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-16T22:00:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T22:00:24.000Z", "max_issues_repo_path": "notebooks/Receiver1.ipynb", "max_issues_repo_name": "RudgeLab/LOICA", "max_issues_repo_head_hexsha": "ea7f203ccd9642a6793537184dbccc764521f6fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2021-12-03T13:26:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T00:57:46.000Z", "max_forks_repo_path": "notebooks/Receiver1.ipynb", "max_forks_repo_name": "RudgeLab/LOICA", "max_forks_repo_head_hexsha": "ea7f203ccd9642a6793537184dbccc764521f6fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3281653747, "max_line_length": 292, "alphanum_fraction": 0.5552193646, "converted": true, "num_tokens": 1396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116550426623, "lm_q2_score": 0.07585818211049714, "lm_q1q2_score": 0.030328985338125537}}
{"text": "# 1. Paper and Group Details\n\n**Paper Title:** Duplex Generative Adversarial Network for Unsupervised Domain Adaptation - CVPR 2018\n\n**Authors:** Lanqing Hu, Meina Kan, Shiguang Shan, Xilin Chen\n\n**Link:** http://openaccess.thecvf.com/content_cvpr_2018/papers/Hu_Duplex_Generative_Adversarial_CVPR_2018_paper.pdf\n\n**Group Members:** Cem \u00d6nem, Cansu Cemre Ye\u015fil\u00e7imen\n\nContact Information can be found in the README.\n\n**Reviewers:** Y.Berk G\u00fcltekin, Hasan Ali Duran\n\n# 2. Goals\n\nOur results can be compared with the original results at the last section of the notebook.\n\n## 2.1. Quantitative Results\n\nWe planned to meet the classification accuracy of the architecture mentioned in Table 1, 2nd row from the bottom, 3rd column from the left (92.46%), where the model was trained on SVHN dataset with labels + unlabeled MNIST dataset, and tested against the MNIST dataset (SVHN -> MNIST) to show the domain adaptation quality. We plan to reproduce similar results with digits 0-4 to cut down on dataset size.\n\n## 2.2. Qualitative Results\n\nWe planned to reproduce Figure 4, where the model and the training is the same as the quantitative results, however this time SVHN images are fed into the network to generate images similar to the ones in MNIST, where digit category is preserved (for digits 0-4)\n\n# 3. Paper Summary\n\n## 3.1 Problem Statement\n\nAs models scale up, collecting new training data to train models becomes more and more expensive. Transfer learning is a remedy technique to this complication where the model exploits its experience gained from training for other tasks that are similar to the one at hand.\n\nDupGAN mainly tackles the issue of **unsupervised domain adaptation**, a subset of Transfer Learning in which there are two domains that share categories but have different data distrubutions. **The ground truth labels are only available for one of the domains** (the source domain), therefore the model is expected to utilize the sample-label relation of this domain to unsupervisedly classify the samples of the other domain (the target domain).\n\nIn our reproduction we will treat these domains as follows:\n- Source domain training data: SVHN train set digit images + labels for digits 0-4\n- Target domain training data: MNIST train set digit images for digits 0-4\n- Target domain test data (for classification): MNIST test set digit images for digits 0-4\n\n## 3.2 Definitions and Model Architecture Overview\nLet the source domain training data be denoted as $S = \\{(x^s_i, y^s_i)\\}^n_{i=1}$ with source images $X^s = \\{x^s_i\\}^n_{i=1}$ and labels $Y^s = \\{y^s_i\\}^n_{i=1}$. Each $y^s \\in Y^s$ correspond to a label in the set $B = \\{b_0,\\ b_1...b_c\\}$ with cardinality $c$. Let the target domain training data be denoted as $X^t = \\{x^t_i\\}^m_{i=1}$. **Note that there is no $Y^t$.**\n\nDupGAN attempts to better the classification quality by training for category preserving domain translation as well as classification. To that end, a hybrid autoencoder GAN architecture where the generator $G$ with two outputs is put against two discriminators $D^s, D^t$ for the source and the target domains respectively:\n\n\n<center>Figure 1: Overview of DupGAN Architecture</center>\n\nThe encoder $E$ at the beginning compresses the images (without any regard to type of domain) into encodings which should be ideally independent of the domain:\n\n\\begin{align}\nZ^s &= \\{z^s \\mid E(x^s) = z^s,\\ x^s \\in X^s \\} \\\\\nZ^t &= \\{z^t \\mid E(x^t) = z^t,\\ x^t \\in X^t \\} \\\\\nZ &= Z^s \\cup Z^t\n\\end{align}\n\n$G$ takes this encoding as well as a domain code $a$ as input, where $a \\in \\{s, t \\}$ indicates the domain type of the image that should be generated. In the end, the following 4 modes of $G$ are integral during training, for $z^s \\in Z^s$ and $z^t \\in Z^t$:\n\n- source to source, $X^{ss} = \\{x^{ss} \\mid G(z^s,s) = x^{ss},\\ z^s \\in Z^s \\}$\n- target to target, $X^{tt} = \\{x^{tt} \\mid G(z^t,t) = x^{tt},\\ z^t \\in Z^t \\}$\n- source to target, $X^{ss} = \\{x^{st} \\mid G(z^s,t) = x^{st},\\ z^s \\in Z^s \\}$\n- target to source, $X^{ss} = \\{x^{ts} \\mid G(z^s,s) = x^{ts},\\ z^t \\in Z^t \\}$\n\nThe first two are used for assessing reconstruction quality to ensure $E$ and $G$ work properly as an autoencoder. The other two are to deceive $D^s, D^t$ for GAN training. \n\nOther than telling real images apart from the real ones, the discriminators also categorize the images in the correct labels. To that end, the discriminators categorize images in bins $B' = \\{b_0,\\ b_1...b_{c+1}\\}$ of cardinality $c+1$ with some probabilities $p^s_l, p^t_l$, where first $c$ bins correspond to the labels and the last bin $b_{c+1}$ is reserved for fake images.\n\n\\begin{align}\np^{s}_l &= D^s(x,l) & l \\in B',\\ x \\in X^{s} \\cup X^{ts} \\\\\np^{t}_l &= D^t(x,l) & l \\in B',\\ x \\in X^{t} \\cup X^{st}\n\\end{align}\n\nLastly, there is a classifier $C$ on top of the encodings. It sorts images from both domains into $L$ with some probability $p^c_l$:\n\n\\begin{align}\np^c_l &= C(z,l) & l \\in B,\\ z \\in Z\n\\end{align}\n\nIt might seem redundant since the $D^s, D^t$ are also doing classification, but the classifier is necessary for the target domain at the pretraining stage. The purpose of $C$ will become clear in the further sections.\n\n## 3.3. Training Details and Objective Functions for the Modules\n\n### 3.3.1. Pseudolabels for Target Domain\n\nIn the following sections, the objective function formulations for the models require labels for both domains. **Since the ground truth labels are missing for the target domain, they are compansated with pseudolabels generated from the classifier $C$**. The high confidence target dataset with supervised labels is defined as follows:\n\n\\begin{align}\nT &= \\{ (x^t,y^{t}) \\mid C(E(x^t),y^{t}) > p_{thres},\\ x^t \\in X^t,\\ y^{t} \\in B \\}\n\\end{align}\n\nwith $X^{t'}$ and $Y^{t'}$ as data and the labels of this constructed dataset. After pretraining (explained below), $T$ replaces $X^{t}$.\n\n$p_{thres}$ is a model hyperparameter (we picked it as 0.99 in our experiments). Note that **$T$ may change at every training step since $C$ might classify the target domain data in a different way. Therefore $T$ is renewed at every epoch of the training step.**\n\nTo increase the chances of pseudolabels being accurate, $E$ and $C$ are pretrained solely with $S$ before core DupGAN training loop.\n\n### 3.3.2. Generator Related Losses\n\nThe generator $G$ has two purposes:\n- Act as an autoencoder with the Encoder $E$, and reconstruct the original image from the encoding:\n\n\\begin{align}\nL_{recon}(E,G) &= \\sum_{x^s \\in X^s}||x^s - G(E(x^s),s)|| + \\sum_{x^t in X^t}||x^t - G(E(x^t),t)|| \\\\\n       &= \\sum_{x^s \\in X^s}||x^s - x^{ss})|| + \\sum_{x^t \\in X^t}||x^t - x^{tt}||\n\\end{align}\n\n- Decieve the discriminators with fake images generated from the other domain:\n\n\\begin{align}\nL_{deceive}(E,G) &= \\sum_{{(x^s,y^s)} \\in S}H_{B'}(D^t(G(E(x^s),t),y^s))+\\sum_{{(x^t,y^t)} \\in T} H_{B'}(D^s(G(E(x^t),s),y^t)) \\\\\n&= \\sum_{{(x^s,y^s)} \\in S}H_{B'}(D^t(x^{st},y^s))+\\sum_{{(x^t,y^t)} \\in T} H_{B'}(D^s(x^{ts},y^t))\n\\end{align}\nwith $H_{B'}(\\cdot,\\cdot)$ as cross-entropy loss along $B'$. **The labels from the other domains are also used to make the discriminator classify the counterfeit images in the correct category other than not being fake.** This forces the generator to preserve the category when translating images. Also note that **$y^t$ are generated with the classifier $C$ since no ground truth is available** for target domain labels.\n\nIn the end, the total generator related loss becomes:\n\n\\begin{align}\nL_{gen}(E,G) &= \\alpha L_{recon} + L_{deceive}\n\\end{align}\n\nwhere $\\alpha$ is a model hyperparameter (we picked it as 40.0).\n\n### 3.3.3. Discriminator Related Losses\n\nThe discriminators are not joint in DupGAN. $D^s$ and $D^t$ discriminate source and target images from counterfeit ones generated from the other domain. Both employ the cross-entropy discriminator loss in the original GAN.\n- Discriminator $D^s$ has the following loss:\n\\begin{align}\nL_{D^s} &= \\sum_{{(x^s,y^s)} \\in S}H_{B'}(D^t(x^s,y^s))+\\sum_{{x^t} \\in X^t} H_{B'}(G(E(x^t),s),b_{c+1})) \\\\\n        &= \\sum_{{(x^s,y^s)} \\in S}H_{B'}(D^t(x^s,y^s))+\\sum_{{x^t} \\in X^t} H_{B'}(D(x^{ts},b_{c+1}))\n\\end{align}\nwith $b_{c+1}$ representing the fake category.\n\n- Discriminator $D^t$ is similar, **but pseudolabels are used instead of ground truth**:\n\n\\begin{align}\nL_{D^t} &= \\sum_{{(x^t,y^t)} \\in T}H_{B'}(D^t(x^t,y^t))+\\sum_{{x^s} \\in X^s} H_{B'}(G(E(x^s),t),b_{c+1})) \\\\\n        &= \\sum_{{(x^t,y^t)} \\in T}H_{B'}(D^t(x^t,y^t))+\\sum_{{x^s} \\in X^s} H_{B'}(D(x^{st},b_{c+1}))\n\\end{align}\n\nThe total discriminator loss is the sum of these losses:\n\n\\begin{align}\nL_{disc}(D^s,D^t) &= L_{D^s} + L_{D^t}\n\\end{align}\n\n### 3.3.4. Classifier Related Losses\n\nThe training for classifier $C$ continues even after pretraining step:\n\n\\begin{align}\nL_{cl}(C,E) &= \\sum_{(x, y) \\in S \\cup T}H_{B}(C(E(x),y))\n\\end{align}\n\n**During pretraining, $T = \\emptyset$. After the pretraining ends, $T$ is recalculated at the beginning of every epoch.**\n\n### 3.3.5. Total Loss and the Training Loop\n\nTotal loss is as follows:\n\n\\begin{align}\nL &= \\beta L_{cl} + L_{gen} + L_{disc}\n\\end{align}\n\nwith $\\beta$ as model hyperparameter (we picked it as 40.0).\n\nThe training loop is similar to the one in the original GAN, but with the addition of pretraining part and the pseudolabel calculation step:\n<br>\n<br>\n\n<center>Algorithm 1: DupGAN Training Loop.</center>\n<hr style=\"border:2px solid gray\"> </hr>\n\n**input**: Source domain $S$.and target domain $X^t$ <br>\n**output**: Model weights $W_E,\\ W_G,\\ W_C,\\ W_{D^s},\\ W_{D^t}$\n\n1: Pretrain $E$ and $C$ with $S$ by backpropping on $L_{cl}$ until convergence: <br>\n$W_E \\leftarrow W_E - \\eta\\frac{\\delta L_{cl}}{\\delta W_E}$ <br>\n$W_C \\leftarrow W_C - \\eta\\frac{\\delta L_{cl}}{\\delta W_C}$\n\n2: **until** convergence, **do** <br>\n\n&emsp;2.1: Calculate $T$.\n\n&emsp;2.2: Backprop on discriminator losses: <br>\n&emsp;$W_{D^s} \\leftarrow W_{D^s} - \\eta\\frac{\\delta L_{D^s}}{\\delta W_{D^s}}$ <br>\n&emsp;$W_{D^t} \\leftarrow W_{D^t} - \\eta\\frac{\\delta L_{D^t}}{\\delta W_{D^t}}$\n\n&emsp;2.2: Backprop on generator and classifier losses: <br>\n&emsp;$W_{G} \\leftarrow W_{G} - \\eta\\frac{\\delta L_{gen}}{\\delta W_G}$ <br>\n&emsp;$W_{C} \\leftarrow W_{C} - \\eta\\frac{\\delta L_{cl}}{\\delta W_C}$ <br>\n&emsp;$W_{E} \\leftarrow W_{E} - \\eta\\frac{\\delta (L_{cl}+L_{gen}}{\\delta W_E}\n\n3: **return** $W_E,\\ W_G,\\ W_C,\\ W_{D^s},\\ W_{D^t}$\n\n\n\n<hr style=\"border:2px solid gray\"> </hr>\n\n# 4. Implementation\n\n## 4.1 Implementation Difficulties and Differences from the Paper Specifications\n\nMain difficulty we faced was that the architecture of the network was not presented in the original DUPGAN paper. It was described as \"similar\" to an architecture from an another paper named Unsupervised Image-to-Image Translation Networks (https://arxiv.org/pdf/1703.00848.pdf). Upon investigating this paper, we noticed that DUPGAN and UNIT had some differences regarding main architecture design (such as UNIT learning an actual probability distrubution which was used to sample the latent representation and DUPGAN outputting the latent vectors directly), which forced us to make some minor changes that we thought to be successful. Because of these assumptions and trials we consider this to be the reason of our accuracy result being different from our initial goal. These differences are listed below.\n\n- In UNIT paper, for SVHN -> MNIST change, authors used the extra training set and test set. The original MNIST images were gray-scale. But in UNIT paper they are converted to RGB images and performed a data augmentation where they also used the inversions of the original MNIST images for training. We did not follow this augmentation method and used all images as they were.\n\n- Classifier C in the original DUPGAN paper was not specified, and did not exist at all in UNIT. So we picked it as a fully connected layer on top of the encoder followed by a LeakyRELU layer, as it was the simplest choice.\n    \n- Regarding the encoder implementation UNIT paper has 1024 channels (neurons since inputs/outputs are 1x1) but those are mu,sigmas that represent a 512x1 latent vector. However DUPGAN does not do any sampling, so 512 channels suffice. We also removed the extra fully connected layer that expands to 1024 nodes owing to this.\n\n- Learning rates are changed for experimental purposes\n\n- Highly confident labels are gathered at each epoch rather than each batch. Since GAN training is already unstable, we wanted to make sure we gathered a statistically more meaningful percentage and overcame the batch size being too small (64) to sample properly.\n\n- Hyperparameters $\\alpha$ and $\\beta$ of the model are different from the ones specified in the paper. \n\n## 4.2 Implementation Overview\n\nHyperparameters and Other Settings are listed here. You may want to change the device field if no gpu support is available.\n\n\n```python\nimport torch\nimport os\n\nfrom train import EncoderClassifierTrainer, GeneratorDiscriminatorTrainer\nfrom utils import mnist_dataset, svhn_dataset, generic_dataloader\nfrom notebook_utils import *\n\nclass Params:\n    \n    #change to cpu if gpu is not available\n    device = 'cuda'\n    \n    datasets_root = os.path.join('datasets', '')\n    \n    ckpt_root = os.path.join('ckpts', '')\n\n    # location of pre-trained encoder_classifier file\n    encoder_classifier_ckpt_file = 'ckpts/encoder_classifier_16.tar'\n    \n    # prepended to each saved checkpoint file name for encoder_classifier\n    encoder_classifier_experiment_name = 'encoder_classifier_notebook'\n    \n    # location of pre-trained generator_discriminator file\n    generator_discriminator_ckpt_file = 'ckpts/generator_discriminator_99.tar'\n    \n    # prepended to each saved checkpoint file name for generator_discriminator\n    generator_discriminator_experiment_name = 'encoder_classifier_notebook'\n    \n    # dupgan specific params\n    dupgan_alpha = 40.0 #different from the specified value in the paper\n    dupgan_beta = 40.0\n    encoder_classifier_confidence_threshold = 0.99\n    \n    # optimizer params\n    encoder_classifier_adam_lr = 0.0002\n    generator_adam_lr = 0.00002\n    discriminator_adam_lr = 0.00001\n    encoder_classifier_adam_beta1 = 0.5\n    encoder_classifier_adam_beta2 = 0.999\n    generator_adam_beta1 = 0.5\n    generator_adam_beta2 = 0.999\n    discriminator_adam_beta1 = 0.5\n    discriminator_adam_beta2 = 0.999\n    \n    # other training params\n    batch_size = 64\n    encoder_classifier_num_epochs = 30\n    generator_discriminator_num_epochs = 100\n    \n    # other non-training params\n    demo = True #demo mode, training outputs are more frequent\n    \n\nparams = Params()\n```\n\n\n```python\n# dataloading, missing datasets are automatically downloaded\nsvhn_trainsplit = svhn_dataset(params.datasets_root, \"train\")\nsvhn_testsplit = svhn_dataset(params.datasets_root, \"test\")\nmnist_testsplit = mnist_dataset(params.datasets_root, False)\nmnist_trainsplit = mnist_dataset(params.datasets_root, True)\n```\n\n    Using downloaded and verified file: datasets/train_32x32.mat\n    Using downloaded and verified file: datasets/test_32x32.mat\n\n\nThe Encoder - Classifier architecture is as follows. It has 2 outputs, an encoding of the input and a confidence vector from this encoding for digit classification.\n\n\n```python\nencoder_classifier_trainer = EncoderClassifierTrainer(params.device, params,\n                                    svhn_trainsplit, svhn_testsplit, mnist_trainsplit, mnist_testsplit,\n                                    ckpt_root=params.ckpt_root)\nprint(encoder_classifier_trainer.encoder_classifier)\n```\n\n    EncoderClassifier(\n      (layer1): Sequential(\n        (0): Conv2d(3, 64, kernel_size=(5, 5), stride=(2, 2), padding=(2, 2))\n        (1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n        (2): LeakyReLU(negative_slope=0.01)\n      )\n      (layer2): Sequential(\n        (0): Conv2d(64, 128, kernel_size=(5, 5), stride=(2, 2), padding=(2, 2))\n        (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n        (2): LeakyReLU(negative_slope=0.01)\n      )\n      (layer3): Sequential(\n        (0): Conv2d(128, 256, kernel_size=(8, 8), stride=(1, 1))\n        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n        (2): LeakyReLU(negative_slope=0.01)\n      )\n      (latent): Linear(in_features=256, out_features=512, bias=True)\n      (classifier): Sequential(\n        (0): LeakyReLU(negative_slope=0.01)\n        (1): Linear(in_features=512, out_features=5, bias=True)\n      )\n    )\n\n\nPretraining is straightforward, the model is trained only with respect to the labels from the same domain (in our case SVHN digit images and digit labels) at this stage. Here is the training procedure for one batch:\n\n\n```python\ndef encoder_classifier_notebook_train_one_batch(self, batch):\n    inputs, labels = batch\n    inputs = inputs.to(self.device)\n    labels = labels.to(self.device)\n\n    self.optimizer.zero_grad()\n    \n    # output is a 1x5 vector of confidences for digits [0-4] (not normalized)\n    classifier_out, _ = self.encoder_classifier(inputs)\n    \n    # criterion is cross-entropy loss against labels on top of a softmax layer\n    loss = self.criterion(classifier_out, labels)\n    loss.backward()\n    \n    #optimizer is ADAM\n    self.optimizer.step()\n```\n\nThe training procedure finds context as follows. The model is saved and evaluated after every epoch in the code below, but you are free to modify it to your liking.\n\n\n```python\ndef encoder_classifier_notebook_train_model(self):\n    self.encoder_classifier.train()\n    \n    #initial self.epoch value is taken from saved checkpoint, it is -1 for a brand new model. \n    for self.epoch in range(self.epoch+1, params.encoder_classifier_num_epochs):\n        for batch in self.svhn_trainsplit_loader:\n            \n            encoder_classifier_notebook_train_one_batch(self, batch)\n            \n            if params.demo:\n                encoder_classifier_notebook_evaluator_evaluate_and_print(self)\n        \n        encoder_classifier_notebook_evaluator_evaluate_and_print(self)\n        #saved every epoch under ckpt_root\n        self.save()\n\ntry:\n    encoder_classifier_notebook_evaluator_reset()\n    encoder_classifier_notebook_train_model(encoder_classifier_trainer)\nexcept KeyboardInterrupt:\n    pass\n```\n\n\n<table><tr><th>Epoch</th><th>SVHN Train Split Loss</th><th>SVHN Train Split Classification Acc. (%)</th><th>SVHN Test Split Classification Acc. (%)</th><th>MNIST Train Split Above Threshold (%)</th></tr><tr><td>0</td><td>1139.7694</td><td>29.1539</td><td>28.4381</td><td>0.0000</td></tr><tr><td>0</td><td>1138.3447</td><td>30.0139</td><td>30.7190</td><td>0.0000</td></tr><tr><td>0</td><td>1135.7645</td><td>30.0381</td><td>30.4995</td><td>0.0000</td></tr></table>\n\n\nThe \"pretrained\" model for pretraining can be loaded with the snippet below. You can also load the model you have trained above by changing the path.\n\n\n```python\n#encoder_classifier_trainer.load(\"absolute path to model.tar that you may have\n#                                 trained above and would like to continue training\")\nencoder_classifier_notebook_load_and_print_params(encoder_classifier_trainer, params.encoder_classifier_ckpt_file)\n```\n\n    ADAM learning rate: 0.0002\n    ADAM betas: (0.5, 0.999)\n    epoch: 16\n    experiment_name: encoder_classifier\n\n\nHere are the classification results for the pretrained model. About 79% of the MNIST dataset is confidently classified with the classifier pretrained only with SVHN dataset.\n\n\n```python\nencoder_classifier_notebook_evaluator_reset()\nencoder_classifier_notebook_evaluator_evaluate_and_print(encoder_classifier_trainer)\n```\n\n\n<table><tr><th>Epoch</th><th>SVHN Train Split Loss</th><th>SVHN Train Split Classification Acc. (%)</th><th>SVHN Test Split Classification Acc. (%)</th><th>MNIST Train Split Above Threshold (%)</th></tr><tr><td>16</td><td>12.9597</td><td>99.4090</td><td>92.6511</td><td>79.6379</td></tr></table>\n\n\nThe pretrained Encoder - Classifier is later embedded to the actual GAN architecture below. Here is the Generator architecture. Notice the extra 513th dimension in the first layer accounting for the domain code that the generator takes as an extra input.\n\n\n```python\nencoder_classifier = encoder_classifier_trainer.encoder_classifier\nencoder_classifier_optimizer = encoder_classifier_trainer.optimizer\ngenerator_discriminator_trainer = GeneratorDiscriminatorTrainer(params.device, params, \n                                                                encoder_classifier,\n                                                                encoder_classifier_optimizer, \n                                                                svhn_trainsplit,\n                                                                svhn_testsplit, mnist_trainsplit, mnist_testsplit,\n                                                                experiment_name=params.generator_discriminator_experiment_name,\n                                                                ckpt_root=params.ckpt_root)\nprint(generator_discriminator_trainer.generator)\n```\n\n    Generator(\n      (layer1): Sequential(\n        (0): ConvTranspose2d(513, 256, kernel_size=(4, 4), stride=(2, 2))\n        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n        (2): LeakyReLU(negative_slope=0.01)\n      )\n      (layer2): Sequential(\n        (0): ConvTranspose2d(256, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1))\n        (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n        (2): LeakyReLU(negative_slope=0.01)\n      )\n      (layer3): Sequential(\n        (0): ConvTranspose2d(128, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1))\n        (1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n        (2): LeakyReLU(negative_slope=0.01)\n      )\n      (layer4): ConvTranspose2d(64, 3, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1))\n      (tanh): Tanh()\n    )\n\n\nThe architecture of the Discriminators (they are identical):\n\n\n```python\nprint(generator_discriminator_trainer.discriminator_svhn)\n```\n\n    Discriminator(\n      (layer1): Sequential(\n        (0): Conv2d(3, 64, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))\n        (1): ReLU()\n        (2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n        (3): Dropout(p=0.1, inplace=False)\n      )\n      (layer2): Sequential(\n        (0): Conv2d(64, 128, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))\n        (1): ReLU()\n        (2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n        (3): Dropout(p=0.1, inplace=False)\n      )\n      (layer3): Sequential(\n        (0): Conv2d(128, 256, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))\n        (1): ReLU()\n        (2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n        (3): Dropout(p=0.1, inplace=False)\n      )\n      (layer4): Sequential(\n        (0): Conv2d(256, 512, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))\n        (1): ReLU()\n        (2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n        (3): Dropout(p=0.1, inplace=False)\n      )\n      (discriminator): Conv2d(512, 6, kernel_size=(2, 2), stride=(1, 1))\n    )\n\n\nThe training procedure for the discriminators is as follows for a pair of batches from both domains. Note that the labels for the MNIST batches are not coming from the dataset, but the Encoder - Classifier of the model itself.\n\n\n```python\ndef discriminator_mnist_notebook_train_one_batch(self, svhn_batch, mnist_hc_batch):\n    \n    svhn_inputs, _ = svhn_batch # don't care about svhn labels here\n    mnist_hc_inputs, mnist_hc_labels = mnist_hc_batch\n    # mnist_hc_labels are high confidence digit labels obtained from the classifier, not ground truth\n\n    # a utility method to zero all grads in all models\n    self.zero_grad()\n    \n    # generate fake mnist images from encodings of svhn images\n    _, svhn_latent_out = self.encoder_classifier(svhn_inputs)\n    svhn_to_fake_mnist = self.generator(svhn_latent_out, 1)\n\n    # discriminator output is a 1x6 (not 1x5!) vector of confidences for digits [0-4] and fake (not normalized)\n    \n    # fake image confidences, discriminator has less loss if the 6th item is large \n    svhn_to_fake_mnist_discriminator_out = self.discriminator_mnist(svhn_to_fake_mnist)\n    \n    # real image confidences, discriminator has less loss if item matching the high conf. classifier label is large\n    real_mnist_discriminator_out = self.discriminator_mnist(mnist_hc_inputs)\n\n    # criterion is cross-entropy loss against labels on top of a softmax layer\n    \n    # fake image loss is against fake labels (label \"5\")\n    discriminator_mnist_fake_loss = self.discriminator_mnist_criterion(svhn_to_fake_mnist_discriminator_out,\n                                     self.fake_label_pool[:svhn_to_fake_mnist_discriminator_out.shape[0]])\n\n    # real image loss is against high confidence classifier labels\n    discriminator_mnist_real_loss = self.discriminator_mnist_criterion(real_mnist_discriminator_out,\n                                                                       mnist_hc_labels)\n\n    # total loss\n    discriminator_mnist_loss = discriminator_mnist_fake_loss + discriminator_mnist_real_loss\n\n    discriminator_mnist_loss.backward()\n    self.discriminator_mnist_optimizer.step()\n```\n\nThe discriminator training procedure for SVHN dataset, where we have the ground truth, is very similar to the discriminator of MNIST. Only this time actual ground truth is available for calculating the loss on real SVHN images.\n\n\n```python\ndef discriminator_svhn_notebook_train_one_batch(self, svhn_batch, mnist_hc_batch):\n\n    svhn_inputs, svhn_labels = svhn_batch # we have the ground truth digit labels for svhn in training\n    mnist_hc_inputs, _ = mnist_hc_batch # don't care about mnist labels here\n    \n    self.zero_grad()\n    \n    # generate fake svhn images from encodings of mnist images\n    _, mnist_hc_latent_out = self.encoder_classifier(mnist_hc_inputs)\n    mnist_to_fake_svhn = self.generator(mnist_hc_latent_out, 0)\n\n    # discriminator output is a 1x6 (not 1x5!) vector of confidences for digits [0-4] and fake (not normalized)\n    \n    # fake image confidences, discriminator has less loss if the 6th item is large \n    mnist_to_fake_svhn_discriminator_out = self.discriminator_svhn(mnist_to_fake_svhn)\n    \n    # real image confidences, discriminator has less loss if item matching the ground truth svhn label is large\n    real_svhn_discriminator_out = self.discriminator_svhn(svhn_inputs)\n\n    # criterion is cross-entropy loss against labels on top of a softmax layer\n    \n    # fake image loss is against fake labels (label \"5\"), optimizer pulls discriminator towards guessing correctly\n    discriminator_svhn_fake_loss = self.discriminator_svhn_criterion(mnist_to_fake_svhn_discriminator_out,\n                                    self.fake_label_pool[:mnist_to_fake_svhn_discriminator_out.shape[0]])\n\n    # real image loss is against ground truth svhn labels, optimizer pulls discriminator towards guessing correctly\n    discriminator_svhn_real_loss = self.discriminator_svhn_criterion(real_svhn_discriminator_out,\n                                                                     svhn_labels)\n    \n    # total loss\n    discriminator_svhn_loss = discriminator_svhn_fake_loss + discriminator_svhn_real_loss\n\n    discriminator_svhn_loss.backward()\n    self.discriminator_svhn_optimizer.step()\n```\n\nGenerator and the encoder - classifier are trained with the following procedure. The generator has two losses, the first one is for deceiving the discriminators and the second one the reconstruction loss for the reconstructed encodings (the reconstructions do not change domain).\n\n\n```python\ndef generator_classifier_notebook_train_one_batch(self, svhn_batch, mnist_hc_batch):\n    \n    svhn_inputs, svhn_labels = svhn_batch # we have the ground truth digit labels for svhn in training\n    mnist_hc_inputs, mnist_hc_labels = mnist_hc_batch\n    # mnist_hc_labels are high confidence digit labels obtained from the classifier, not ground truth\n    \n    self.zero_grad()\n    \n    # generate fake images (from the other domain) and reconstructed images (from the same domain)\n    # from the encodings\n    \n    # classifier confidences will be used for classifier training\n    mnist_hc_classifier_out, mnist_hc_latent_out = self.encoder_classifier(mnist_hc_inputs)\n    svhn_classifier_out, svhn_latent_out = self.encoder_classifier(svhn_inputs)\n\n    svhn_to_fake_svhn = self.generator(svhn_latent_out, 0)\n    svhn_to_fake_mnist = self.generator(svhn_latent_out, 1)\n    mnist_to_fake_svhn = self.generator(mnist_hc_latent_out, 0)\n    mnist_to_fake_mnist = self.generator(mnist_hc_latent_out, 1)\n    \n    # 1-) Generator Training\n    \n    # 1-a) Generator Deception Losses\n    \n    # discriminator output is a 1x6 (not 1x5!) vector of confidences for digits [0-4] and fake (not normalized)\n\n    svhn_to_fake_mnist_discriminator_out = self.discriminator_mnist(svhn_to_fake_mnist)\n    mnist_to_fake_svhn_discriminator_out = self.discriminator_svhn(mnist_to_fake_svhn)\n    \n    # deception criterion is cross-entropy loss against labels on top of a softmax layer\n    \n    # fake mnist image losses are against ground truth svhn labels\n    # optimizer pulls generator towards making discriminator categorize fake mnist images incorrectly\n    # in the corresponding ground truth svhn labels\n    deceive_discriminator_mnist_loss = self.generator_deception_criterion(\n        svhn_to_fake_mnist_discriminator_out, svhn_labels)\n    \n    # fake svhn image losses are against mnist high conf. classifier labels (not ground truth)\n    # optimizer pulls generator towards making discriminator categorize fake svhn images incorrectly\n    # in the corresponding mnist high conf. classifier labels (not ground truth)\n    deceive_discriminator_svhn_loss = self.generator_deception_criterion(\n        mnist_to_fake_svhn_discriminator_out, mnist_hc_labels)\n    \n    # total deception loss\n    deception_loss = deceive_discriminator_mnist_loss + deceive_discriminator_svhn_loss\n    \n    # 1-b) Generator Reconstruction Losses\n    \n    # reconstructed images should look like the original images, reconstruction criterion is\n    # L2 loss between original and reconstructed images - no label information used\n    \n    reconstruction_mnist_loss = self.generator_reconstruction_criterion(mnist_to_fake_mnist,\n                                                                        mnist_hc_inputs)\n    reconstruction_svhn_loss = self.generator_reconstruction_criterion(svhn_to_fake_svhn,\n                                                                       svhn_inputs)\n    \n    # total reconstruction loss\n    reconstruction_loss = reconstruction_mnist_loss+reconstruction_svhn_loss\n    \n    # total generator loss, there is a reconstruction loss scaling parameter alpha specified in the paper\n    generator_loss = deception_loss + self.dupgan_alpha*reconstruction_loss\n    \n    \n    # 2-) Classifier Training\n    \n    # criterion is cross-entropy loss against labels from own domain, same as pretraining, only difference is\n    # mnist high confidence images also contribute to the loss with mnist high confidence labels (not ground truth)\n    \n    mnist_classification_loss = self.encoder_classifier_criterion(mnist_hc_classifier_out, mnist_hc_labels)\n    svhn_classification_loss = self.encoder_classifier_criterion(svhn_classifier_out, svhn_labels)\n\n    # total classification loss, there is a scaling parameter beta specified in the paper\n    classification_loss = self.dupgan_beta*(mnist_classification_loss + svhn_classification_loss)\n\n    generator_ec_loss = generator_loss + classification_loss\n    generator_ec_loss.backward()\n\n    self.generator_optimizer.step()\n    self.encoder_classifier_optimizer.step()\n```\n\nThe 3 procedures collect in the following main training loop. At the beginning of each epoch, the filtered collection of MNIST images with high classification confidence are renewed. The model is saved and evaluated at every epoch. You can change the frequency of these to your liking by playing with the code below.\n\n\n```python\ndef generator_discriminator_notebook_train_models(self):\n    \n    for self.epoch in range(self.epoch+1, params.generator_discriminator_num_epochs):\n        \n        # at the beginning every epoch review images in the mnist train split and collect the ones\n        # that the classifier has high confidence in categorization\n        # train the models with inferred label - high confidence mnist image pairs\n        # as if the inferred labels are ground truth\n        mnist_hc_dataset, pseudolabels = self.get_high_confidence_mnist_dataset_with_pseudolabels()\n        mnist_hc_loader = generic_dataloader(self.device, mnist_hc_dataset, shuffle=True,\n                                             batch_size=self.batch_size)\n        \n        # since mnist is smaller than svhn, have to use iterators to jointly train\n        mnist_ind = 0\n        mnist_iterator = iter(mnist_hc_loader)\n        for svhn_batch in self.svhn_trainsplit_loader:\n            \n            # hack to skip 1 sample batches since they give an error with batchnorm\n            # device compatibility code, etc.\n            while True:\n                if mnist_ind >= len(mnist_iterator):\n                    mnist_iterator = iter(mnist_hc_loader)\n                    mnist_ind = 0\n                mnist_hc_inputs, *_, mnist_hc_indices = next(mnist_iterator)\n                mnist_ind += 1\n                if mnist_hc_inputs.shape[0] > 1:\n                    break\n            mnist_hc_inputs = mnist_hc_inputs.to(self.device)\n            mnist_hc_labels = pseudolabels[mnist_hc_indices].to(self.device)\n            svhn_inputs, svhn_labels = svhn_batch\n            svhn_inputs = svhn_inputs.to(self.device)\n            svhn_labels = svhn_labels.to(self.device)\n            \n            #meat of the training code\n            mnist_hc_batch = (mnist_hc_inputs, mnist_hc_labels)\n            svhn_batch = (svhn_inputs, svhn_labels)\n            \n            discriminator_mnist_notebook_train_one_batch(self, svhn_batch, mnist_hc_batch)\n            discriminator_svhn_notebook_train_one_batch(self, svhn_batch, mnist_hc_batch)\n            generator_classifier_notebook_train_one_batch(self, svhn_batch, mnist_hc_batch)\n            \n            #this is here just to show results fast during a demo\n            if params.demo:\n                generator_discriminator_notebook_evaluator_evaluate_and_print(self, mnist_hc_loader, pseudolabels)\n        \n        #saved every epoch under ckpt_root\n        generator_discriminator_notebook_evaluator_evaluate_and_print(self, mnist_hc_loader, pseudolabels)\n        self.save()\n\ntry:\n    generator_discriminator_notebook_evaluator_reset()\n    generator_discriminator_notebook_train_models(generator_discriminator_trainer)\nexcept KeyboardInterrupt:\n    pass\n```\n\nThe best model we obtained from our experiments can be loaded with the snippet below. Important hyper-parameters are also listed.\n\n\n```python\ngenerator_discriminator_notebook_load_and_print_params(generator_discriminator_trainer,params.generator_discriminator_ckpt_file)\n```\n\n    Discriminator ADAM learning rate: 1e-05\n    Discriminator ADAM betas: (0.5, 0.999)\n    Generator ADAM learning rate: 2e-05\n    Generator ADAM betas: (0.5, 0.999)\n    Encoder-Classifier ADAM learning rate: 0.0002\n    Encoder-Classifier ADAM betas: (0.5, 0.999)\n    DUPGAN Alpha: 40.0\n    DUPGAN Beta: 40.0\n    epoch: 99\n    experiment_name: generator_discriminator\n\n\n# 5. Final Results\n\nHere are our promised goal results for the project. **The paper reports 92.46% accuracy for the classifier, (we had 87.21%).** The image translation results of the paper can be compared with ours below:\n\n\n<center>Figure 2: Image Translation Results of DupGAN Paper</center>\n\n<center>Figure 3: Our Image Translation Results</center>\n\n\n```python\ngenerator_discriminator_notebook_evaluator_evaluate_goals_and_print(generator_discriminator_trainer)\n```\n", "meta": {"hexsha": "1ff4e2fc66972226231d7fa5163a771f6fa0f88e", "size": 378624, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "main.ipynb", "max_stars_repo_name": "cemonem/DupGAN_reproduction", "max_stars_repo_head_hexsha": "c96fe36e5bdaef5216825423da6d16117518cb2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2020-07-06T10:47:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T11:43:17.000Z", "max_issues_repo_path": "main.ipynb", "max_issues_repo_name": "cemonem/DupGAN_reproduction", "max_issues_repo_head_hexsha": "c96fe36e5bdaef5216825423da6d16117518cb2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-12T00:39:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:39:12.000Z", "max_forks_repo_path": "main.ipynb", "max_forks_repo_name": "cemonem/DupGAN_reproduction", "max_forks_repo_head_hexsha": "c96fe36e5bdaef5216825423da6d16117518cb2c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-13T20:46:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-01T13:15:25.000Z", "avg_line_length": 362.6666666667, "max_line_length": 171228, "alphanum_fraction": 0.9222711714, "converted": true, "num_tokens": 9395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.08509904848750827, "lm_q1q2_score": 0.030276104913754518}}
{"text": "```python\nfrom IPython.core.interactiveshell import InteractiveShell \nInteractiveShell.ast_node_interactivity = \"all\"\n```\n\n\n```python\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n```\n\n<div class=\"alert alert-block alert-warning\">\n\n## Update :  \n\nAs a successor to this article, I am also curating a list of useful Python libraries that cab be pretty useful for ML tasks. The idea is to include libraries other than the well-known ones like pandas, sklearn, etc. Till now I have been able to include few of them but will be updating them over time. Here is the link to the Kernel:\n\nhttps://www.kaggle.com/parulpandey/useful-python-libraries-for-data-science?scriptVersionId=28473653\n\n# 10 Simple hacks to speed up your Data Analysis in Python\n\nTips and Tricks, especially in the programming world, can be very useful. Sometimes a little hack can be both time and life-saving. A minor shortcut or add-on can sometimes prove to be a Godsend and can be a real productivity booster. So, here are some of my favourite tips and tricks that I have used and compiled together in the form of this article. Some may be fairly known and some may be new but I am sure they would come in pretty handy the next time you work on a Data Analysis project.\n\n## 1. Pandas Profiling\n\n**Profiling** is a process that helps us in understanding our data  and  [**Pandas**](https://github.com/pandas-profiling/pandas-profiling)[**Profiling**](https://github.com/pandas-profiling/pandas-profiling)  is python package which does exactly that.  It is a simple and fast way to perform exploratory data analysis of a Pandas Dataframe.  The pandas`df.describe()`and  `df.info()functions` are normally used as a first step in the EDA process. However, it only gives a very basic overview of the data and doesn\u2019t help much in the case of large data sets. The Pandas Profiling function, on the other hand, extends the pandas DataFrame  with`df.profile_report()`  for quick data analysis. It displays a lot of information with a single line of code and that too in an interactive HTML report.\n\nFor a given dataset the pandas profiling package computes the following statistics:\n\n\n\nRefer the  [documentation](https://pandas-profiling.github.io/pandas-profiling/docs/)  for more details and examples.[](http://)\n\n### Usage\n\nLet\u2019s use the titanic dataset to demonstrate the capabilities of the versatile python profiler.\n\n\n```python\nimport pandas as pd\nimport pandas_profiling \n\ntitanic_df = pd.read_csv('/kaggle/input/titanic/train.csv')\n```\n\nTo display the report in a Jupyter notebook, run the following code. This single line of code is all that you need to display the data profiling report in a Jupyter notebook. The report is pretty detailed including charts wherever necessary.\n\n\n```python\n titanic_df.profile_report()\n```\n\nThe report can also be exported into an interactive HTML file with the following code.\n\n\n```python\nprofile = titanic_df.profile_report(title='Pandas Profiling Report')\nprofile.to_file(output_file=\"Titanic data profiling.html\")\n```\n\n## 2. Interactive Pandas' plots\n\nThe **Pandas** library has a built-in `.plot()`  function as part of the DataFrame class. However,the visualisations rendered with this function aren't interactive and that makes it less appealing. On the contrary, the ease to plot charts with `pandas.DataFrame.plot()` function also cannot be ruled out. What if we could plot interactive plotly like charts with pandas without having to make major modifications to the code? Well, you can actually do that with the help of [**Cufflinks**](https://github.com/santosjorge/cufflinks) library.\n\nCufflinks library binds the power of  [**plotly**](http://www.plot.ly/)  with the flexibility of  [pandas](http://pandas.pydata.org/)  for easy plotting. Let\u2019s now see how we can install the library and get it working in pandas.\n\n### Usage\n\n\n\n\n```python\n#importing Pandas \nimport pandas as pd\n#importing plotly and cufflinks in offline mode\nimport cufflinks as cf\nimport plotly.offline\ncf.go_offline()\ncf.set_config_file(offline=False, world_readable=True)\n\n```\n\n\n```python\ntitanic_df[['Pclass', 'Survived']].groupby(['Pclass'], as_index=False).mean().iplot(kind='bar')\n```\n\n\n```python\ntitanic_df[['Sex','Survived']].groupby(['Sex']).mean().iplot(kind='barh')\n```\n\n\n```python\ntitanic_df.iplot()\n```\n\n**df.iplot() vs df.plot()**\n\nThe visualisations is interactive and more detailed and all this without any major change in the syntax.\n\n[**Click here**](https://github.com/santosjorge/cufflinks/blob/master/Cufflinks%20Tutorial%20-%20Pandas%20Like.ipynb)  for more examples.\n\n## 3. Magic Commands\n**Magic commands**  are a set of convenient functions in Jupyter Notebooks that are designed to solve some of the common problems in standard data analysis. You can see all available magics with the help of  `%lsmagic`.\n\n\n\n\n\n\n```python\n%lsmagic\n```\n\nMagic commands are of two kinds: **_line magics_**, which are prefixed by a single`%` character and operate on a single line of input, and **_cell magics_**, which are associated with the double `%%` prefix  and operate on multiple lines of input.  Magic functions are callable without having to type the initial % if set to 1.\n\nLet\u2019s look at some of them that might be useful in common data analysis tasks:\n\n ### %matplotlib notebook\n\nThe  `%matplotlib inline`  function is used to render the static matplotlib plots within the Jupyter notebook. Try replacing the `inline`  part with  `notebook` to get zoom-able & resize-able plots, easily. Make sure the function is called before importing the matplotlib library.\n\n\n```python\n%matplotlib notebook\nimport matplotlib.pyplot as plt\nplt.plot([[0,0],[1,1]], linewidth=2)\nplt.show()\n```\n\n-   **%matplotlib notebook** vs **%matplotlib inline**\n\n\n\n### %%writefile\n\n`%%writefile` writes the contents of a cell to a file. Here the code will be written to a file named  **foo.py**  and saved in the current directory.\n\n\n```python\n%%writefile foo.py\nx = int(input('Enter a number: '))\nprint(x*x)\n```\n\n### %run\n\nThe `%run` function runs a python script inside a notebook\n\n\n```python\n# %run foo.py\n```\n\n### %%latex\n\nThe %%latex function renders the cell contents as LaTeX. It is  useful  for writing mathematical formulae and equations in a cell.\n\n\n```latex\n%%latex\n\\begin{align}\na = \\frac{1}{2} && b = \\frac{1}{3}\\\\\n\\end{align}\n```\n\n## 4. Finding and Eliminating Errors\n\nThe  **interactive debugger**  is also a magic function but I have given it a category of its own. If you get an exception while running the code cell, type  `%debug`  in a new line and run it. This opens an interactive debugging environment which brings you to the position where the exception has occurred. You can also check for values of variables assigned in the program and also perform operations here. To exit the debugger hit  `q`.\n\n\n\n```python\nx = [1,2,3]\ny = 2\nz = 5\n\nresult = y+z\nprint(result)\nresult2 = x+y\nprint(result2)\n```\n\n\n```python\n%debug\n```\n\nHere is a gif to show how it appears in a notebook\n\n\n\n## 5. Pretty Printing \n\nIf you want to produce  aesthetically  pleasing representations of your data structures,  [**pprint**](https://docs.python.org/2/library/pprint.html)  is the go-to module. It is especially useful when printing dictionaries or JSON data. Let\u2019s have a look at an example which uses both  `print`  and  `pprint`  to display the output.\n\n\n```python\n# with print\nemployee_records = {'Emp ID': '101', 'Emp Name': 'Tom',\n                   'Project IDs': {'P1': 1308, 'P2':'A104','P4':2}}\n\nprint(employee_records)\n```\n\n\n```python\n# with pretty print\nimport pprint\n\nemployee_records = {'Emp ID': '101', 'Emp Name': 'Tom',\n                   'Project IDs': {'P1': 1308, 'P2':'A104','P4':2}}\n\npprint.pprint(employee_records,width=1)\n```\n\n## 6. Making the Notes stand out.\n\nWe can use alert/Note boxes in your Jupyter Notebooks to highlight something important or anything that needs to stand out. The colour of the note depends upon the type of alert that is specified. Just add any or all of the following codes in a cell that needs to be highlighted.\n\n-   **Blue Alert Box: info**\n\n```\n<div class=\"alert alert-block alert-info\">\n<b>Tip:</b> Use blue boxes (alert-info) for tips and notes. \nIf it\u2019s a note, you don\u2019t have to include the word \u201cNote\u201d.\n</div>\n```\n<div class=\"alert alert-block alert-info\">\n<b>Tip:</b> Use blue boxes (alert-info) for tips and notes. \nIf it\u2019s a note, you don\u2019t have to include the word \u201cNote\u201d\n</div>\n\n-   **Yellow Alert Box: Warning**\n```\n<div class=\"alert alert-block alert-warning\">  \n<b>Example:</b> Yellow Boxes are generally used to include additional examples or mathematical formulas.  \n</div>\n```\n<div class=\"alert alert-block alert-warning\">  \n<b>Example:</b> Yellow Boxes are generally used to include additional examples or mathematical formulas.  \n</div>\n\n-   **Green Alert Box: Success**\n```\n<div class=\"alert alert-block alert-success\">  \nUse green box only when necessary like to display links to related content.  \n</div>\n```\n<div class=\"alert alert-block alert-success\">  \nUse green box only when necessary like to display links to related content.  \n</div>\n\n-   **Red Alert Box: Danger**\n```\n<div class=\"alert alert-block alert-danger\">  \nIt is good to avoid red boxes but can be used to alert users to not delete some important part of code etc.   \n</div>\n```\n<div class=\"alert alert-block alert-danger\">  \nIt is good to avoid red boxes but can be used to alert users to not delete some important part of code etc.   \n</div>\n\n## 7. Printing all the outputs of a cell\n\nIt is a normal property of the cell that only the last output gets printed and for the others, we need to add the  `print()` function. Well, it turns out that we can print all the outputs just by adding the following snippet at the top of the notebook.\n\n```\nfrom IPython.core.interactiveshell import InteractiveShell  \nInteractiveShell.ast_node_interactivity = \"all\"\n```\nTo revert to the original setting :\n```\nInteractiveShell.ast_node_interactivity = \"last_expr\"\n```\n\n\n```python\n10+5\n11+6\n12+7\n```\n\n## 8. Running python scripts with the \u2018i\u2019 option\n\nA typical way of running a python script from the command line is:  `python hello.py.`  However, if you add an additional  `-i` while running the same script e.g  `python -i hello.py`  it offers more advantages. Let\u2019s see how.\n\n-   Firstly, once the end of the program is reached, python doesn\u2019t exit the interpreter. As such we can check the values of the variables and the correctness of the functions defined in our program.\n\n\n\n-   Secondly, we can easily invoke a python debugger since we are still in the interpreter by:\n```\n    import pdb  \n    pdb.pm()\n```\nThis will bring us o the position where the exception has occurred and we can then work upon the code.\n\n_The original_ [_source_](http://www.bnikolic.co.uk/blog/python-running-cline.html) _of the hack._\n\n\n## 9. Commenting out code automatically\n\n`Ctrl/Cmd + /`  comments out selected lines in the cell by automatically. Hitting the combination again will uncomment the same line of code.\n\n\n## 10. To delete is human, to restore divine\n\nHave you ever accidentally deleted a cell in a Jupyter Notebook? If yes then here is a shortcut which can undo that delete action.\n\n-   In case you have deleted the contents of a cell, you can easily recover it by hitting  `CTRL/CMD+Z`\n-   If you need to recover an entire deleted cell hit  `ESC+Z` or  `EDIT > Undo Delete Cells`\n\n\n\nThese were some of the tips I had gathered while working with Python and Jupyter Notebooks, over the time.  I am sure these simple hacks will be of use to you.The source of this article is blog I wrote some time back with the same name. You can find the link to the blog here : [10 Simple hacks to speed up your Data Analysis in Python](https://towardsdatascience.com/10-simple-hacks-to-speed-up-your-data-analysis-in-python-ec18c6396e6b?)\n\n\n```python\n\n```\n", "meta": {"hexsha": "f4e3c42007dc93468244519b657ed6c5ebc1a3fb", "size": 20540, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "99.tools/10-simple-hacks-to-speed-up-your-data-analysis.ipynb", "max_stars_repo_name": "ddebby/AI-Lab", "max_stars_repo_head_hexsha": "247f5ed0d93955e061e65d06f48cf9c7afc6b4a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-05-08T09:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-18T03:42:25.000Z", "max_issues_repo_path": "99.tools/10-simple-hacks-to-speed-up-your-data-analysis.ipynb", "max_issues_repo_name": "ddebby/AI-Lab", "max_issues_repo_head_hexsha": "247f5ed0d93955e061e65d06f48cf9c7afc6b4a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-06T09:50:42.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-06T09:50:42.000Z", "max_forks_repo_path": "99.tools/10-simple-hacks-to-speed-up-your-data-analysis.ipynb", "max_forks_repo_name": "ddebby/AI-Lab", "max_forks_repo_head_hexsha": "247f5ed0d93955e061e65d06f48cf9c7afc6b4a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-13T13:45:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T13:45:21.000Z", "avg_line_length": 30.3846153846, "max_line_length": 803, "alphanum_fraction": 0.5979065239, "converted": true, "num_tokens": 2904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2538610069692489, "lm_q2_score": 0.11920293453832884, "lm_q1q2_score": 0.030260976995589616}}
{"text": "# \"Title\"\n> \"Awesome summary\"\n\n- toc: false\n- branch: master\n- badges: true\n- comments: true\n- categories: [fastpages, jupyter]\n- image: images/some_folder/your_image.png\n- hide: false\n- search_exclude: true\n- metadata_key1: metadata_value1\n- metadata_key2: metadata_value2\n\n\n$$\n\\begin{equation}\n\\mathbf{r} \\equiv \\begin{bmatrix}\ny \\\\\n\\theta\n\\end{bmatrix}\n\\label{eq:vector_ray} \n\\end{equation}\n$$\n$\\eqref{eq:vector_ray}$ is\n\n\n$\\eqref{eq:vector_ray}$ is\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "4eaea991c3ac5e46d96342be1f05da3171704b6b", "size": 2032, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "_notebooks/2022-02-15-notebook-test.ipynb", "max_stars_repo_name": "kwangsungjun/blog", "max_stars_repo_head_hexsha": "155abd911c7fe18ec0740547e1e2a8553549fec8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_notebooks/2022-02-15-notebook-test.ipynb", "max_issues_repo_name": "kwangsungjun/blog", "max_issues_repo_head_hexsha": "155abd911c7fe18ec0740547e1e2a8553549fec8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-15T03:53:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T03:53:43.000Z", "max_forks_repo_path": "_notebooks/2022-02-15-notebook-test.ipynb", "max_forks_repo_name": "kwangsungjun/blog", "max_forks_repo_head_hexsha": "155abd911c7fe18ec0740547e1e2a8553549fec8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5252525253, "max_line_length": 51, "alphanum_fraction": 0.5216535433, "converted": true, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.06097518299796206, "lm_q1q2_score": 0.030011261645001293}}
{"text": "# Assignment 8\n\nName 1: Sangeet Sagar<br/>\nStudent id 1: 7009050<br/>\nEmail 1: sasa00001@stud.uni-saarland.de<br/>\n\n\nName 2: Nikhil Paliwal<br/>\nStudent id 2: 7009915<br/>\nEmail 2: nipa00002@stud.uni-saarland.de<br/> \n\n**Instructions:** Read each question carefully. <br/>\nMake sure you appropriately comment your code wherever required. Your final submission should contain the completed Notebook and the Python files for exercise 1. There is no need to submit the data files. <br/>\nUpload the zipped folder in Teams. Make sure to click on \"Turn-in\" after your upload your submission, otherwise the assignment will not be considered as submitted. Only one from the group should make the submisssion.\n\n---\n\n\n```python\n# from IPython.core.display import display, HTML\n# display(HTML(\"<style>.container { width:100% !important; }</style>\"))\n```\n\n## Exercise 1: Document Classification Warm-Up (4 points)\n\nIn this exercise you will explore the Reuters News corpus and apply basic feature selection techniques to it. You can download the reuters corpus and English stop words via [NLTK](https://www.nltk.org/):\n\n\n```python\n!pip install nltk\nimport nltk\nnltk.download('reuters')\nnltk.download('stopwords')\n```\n\n    Requirement already satisfied: nltk in /home/sangeet/anaconda3/lib/python3.8/site-packages (3.5)\n    Requirement already satisfied: tqdm in /home/sangeet/anaconda3/lib/python3.8/site-packages (from nltk) (4.59.0)\n    Requirement already satisfied: joblib in /home/sangeet/anaconda3/lib/python3.8/site-packages (from nltk) (0.17.0)\n    Requirement already satisfied: regex in /home/sangeet/anaconda3/lib/python3.8/site-packages (from nltk) (2020.10.15)\n    Requirement already satisfied: click in /home/sangeet/anaconda3/lib/python3.8/site-packages (from nltk) (7.1.2)\n\n\n    [nltk_data] Downloading package reuters to /home/sangeet/nltk_data...\n    [nltk_data]   Package reuters is already up-to-date!\n    [nltk_data] Downloading package stopwords to\n    [nltk_data]     /home/sangeet/nltk_data...\n    [nltk_data]   Package stopwords is already up-to-date!\n\n\n\n\n\n    True\n\n\n\nIt consists of articles from [Reuters](https://de.wikipedia.org/wiki/Reuters) mapped to one of \nFiles and categories (classes) can be accessed easily. Although there is a train/test split, we will use the whole corpus for this exercise.\n\n\n```python\nfrom nltk.corpus import reuters, stopwords\nstop_words = stopwords.words('english')\nprint(reuters.categories())\nprint(\"# of categories: {}\".format(len(reuters.categories())))\nreuters.fileids()[:10]\n```\n\n    ['acq', 'alum', 'barley', 'bop', 'carcass', 'castor-oil', 'cocoa', 'coconut', 'coconut-oil', 'coffee', 'copper', 'copra-cake', 'corn', 'cotton', 'cotton-oil', 'cpi', 'cpu', 'crude', 'dfl', 'dlr', 'dmk', 'earn', 'fuel', 'gas', 'gnp', 'gold', 'grain', 'groundnut', 'groundnut-oil', 'heat', 'hog', 'housing', 'income', 'instal-debt', 'interest', 'ipi', 'iron-steel', 'jet', 'jobs', 'l-cattle', 'lead', 'lei', 'lin-oil', 'livestock', 'lumber', 'meal-feed', 'money-fx', 'money-supply', 'naphtha', 'nat-gas', 'nickel', 'nkr', 'nzdlr', 'oat', 'oilseed', 'orange', 'palladium', 'palm-oil', 'palmkernel', 'pet-chem', 'platinum', 'potato', 'propane', 'rand', 'rape-oil', 'rapeseed', 'reserves', 'retail', 'rice', 'rubber', 'rye', 'ship', 'silver', 'sorghum', 'soy-meal', 'soy-oil', 'soybean', 'strategic-metal', 'sugar', 'sun-meal', 'sun-oil', 'sunseed', 'tea', 'tin', 'trade', 'veg-oil', 'wheat', 'wpi', 'yen', 'zinc']\n    # of categories: 90\n\n\n\n\n\n    ['test/14826',\n     'test/14828',\n     'test/14829',\n     'test/14832',\n     'test/14833',\n     'test/14839',\n     'test/14840',\n     'test/14841',\n     'test/14842',\n     'test/14843']\n\n\n\nEach document belongs to one or more categories. For the sake of simplicity we map each document to the first of its categories.\n\n\n```python\nprint(reuters.categories('test/14833'))\ncategory = reuters.categories('test/14833')[0]\ncategory\n```\n\n    ['palm-oil', 'veg-oil']\n\n\n\n\n\n    'palm-oil'\n\n\n\n**1.1: Categories (1.5 points)**\n\n1. Load data into the `Corpus` class. We suggest to give an attribute `documents` that contains a list of `Document` objects. Preprocessing steps (tokenization, lowercasing, stopword removal) should happen within the `Document` objects. As always, you can deviate from that if you find it more convenient. (1 point)\n2. Implement the method `category_frequencies` in the `Corpus` class. It should calculate the absolute frequencies of each category in the whole corpus. (0.25 points)\n3. Plot categories vs. their frequency on a log-log scale. Do so by implementing the function `plot_category_frequencies`. What can you say about the distribution the category frequencies you observe? (0.25 points)\n\n\n\n```python\nfrom importlib import reload\nimport exercise_1\nexercise_1 = reload(exercise_1)\n\ncorpus = exercise_1.Corpus(\n    documents=[exercise_1.Document(fileid, reuters.raw(fileid), reuters.categories(fileid), stop_words=stop_words) for fileid in reuters.fileids()],\n    categories=reuters.categories()\n)\n\nexercise_1.plot_category_frequencies(corpus.category_frequencies())\n```\n\n**What can you say about the distribution the category frequencies you observe?** <br>\nIt follows power law distribution\n\n**1.2 Document Frequency (1.5 points)**\n\nA term's document frequency (DF) is given by:\n\n\\begin{equation}\nDF_{c_k}(t_i) = \n\\frac{\n\\text{# of documents in $C_k$ containing $t_i$}\n}{\n\\text{# of documents of category $C_k$}\n}\n\\end{equation}\n\n1. Find the 10 most frequent terms of the `housing ` category. Do so by implementing the method `term_frequencies` in the `Corpus` class. (0.5 points)\n2. For these 10 terms, calculate their DF in the `housing` category as well as in the whole corpus (over all categories). Do so by implementing the method`df` in the `corpus` class. Plot the results by implementing the function `plot_dfs`. (0.5 points)\n3. Is DF a good predictor for a category? Explain in 2-3 sentences. (0.5 points)\n\n\n```python\nmost_common_housing = corpus.term_frequencies('housing').most_common(10)\nmost_common_housing = [term for term, _ in most_common_housing]\n\ndfs_housing = [corpus.df(term, category='housing') for term in most_common_housing]\ndfs_all = [corpus.df(term) for term in most_common_housing]\n\nexercise_1.plot_dfs(most_common_housing, dfs_housing)\nexercise_1.plot_dfs(most_common_housing, dfs_all)\n```\n\n**Is DF a good predictor for a category?** <br>\nNo. The most suitable predictor would be tf-idf (term frequency-inverse document frequency). There are words like `january`, `min`, `said` which are although frequent occuring tokens in `housing` category but show no relevance with this class. A good predictor like tf-idf shows how important a word is to a document in a collection of documents. The tf-idf statistics helps prioritize tokens that overall depict the main theme of a sentence in a document. This also helps to diminish the weight of frequent tokens which are meaningless to the theme of a sentence like article, prepositions etc.\n\n**1.3 Pointwise Mutual Information (1 point)**\n\nPMI is given by:\n\\begin{equation}\nPMI(x;y) = \\log_2 \\frac{p(x,y)}{p(x)p(y)}\n\\end{equation}\n\n1. Give an interpretation of PMI. When will it be large, when will it be small? What are its upper and lower bound? (0.25 points)\n2. Calculate PMI of the `housing` category and each of the 10 most frequent terms from that category. Do so by implementing the method `pmi` in the `Corpus` class. Plot the PMI values. Do so by implementing the function `plot_pmis`. (0.5 points)\n3. What does the plot tell you about the suitability of the most frequent words of a category as a feature for text classification? Come up with an improved measure that makes use of both the document frequency and PMI (it need not be derived formally from PMI, but it should be motivated by your findings). (0.25 points)\n\n**Answers** <br>\n1. PMI is maximum when a word in a topic occurs quite often mutually than individually. PMI is smaller (or negative) when the word in that topic occurs tends to occur individually representing uninformative co-occurrences. <br>\n$$\nPMI(x;y) = \\log \\frac{p(x,y)}{p(x)p(y)} = \\log \\frac{p(x|y)}{p(x)} = \\log \\frac{p(y|x)}{p(y)}\n$$\nUpper Bound: $$\\text{min}[\\log \\frac{1}{p(x)}, \\log \\frac{1}{p(y)}]$$ <br>\nlower bound: $$-\\infty$$\n\n3.The plots show some good results e.g. words like `housing`, `starts`, `family` have a high PMI score implying they occur more often under the category `housing`, thus implying their strong association with this category. However, this is not true for some words like `said`, `min` which although are among the most frequent tokens in the `housing` category, but their association with the category is not strong and often occurs individually.\n\nThe problem with PMI is that it is weighted towards infrequent events. The modified improvisation would be:\n$$\nPMI(x;y) = \\log \\frac{p(x,y) \\cdot N}{p(x)p(y)}\n$$\n\n\n```python\n# pmis = [corpus.pmi('housing', term) for term in most_common_housing]\npmis = corpus.pmi('housing', most_common_housing)\nexercise_1.plot_pmis('housing', most_common_housing, pmis)\n```\n\n## Exercise 2 $\\chi^2$ (2p)\n\nStudy the usage of $\\chi^2$ statistics online. A very brief overview with examples can be found on [Wikipedia](https://en.wikipedia.org/wiki/Chi-squared_test).\n\n**2.1 $\\chi^2$ Introduction (1.25 points)**\n\n1. How can you turn a numerical feature into a categorical one? What are the parameters of this decision? What are some features (at least 3) one may encounter in NLP? (0.25 points)\n\n**Answers** <br>\nOne easy \nA numerical feature eg. $F_1$ can be turned into a categorical (or binary) feature as $(F_1, \\text{not} F_1)$. So instead we now check if the feature is present or not.\nAnother example could be dividing the numerical feature values into some interval and then assign them to a category, in such case the length of interval would be the parameter of decision. \nFor NLP, for task like Entity recognition in language like German, we can define binary categorical feature as presence/absence of capital letter for detection, which will be very useful.\nAnother, could be Document Frequency (categorized) and lastly for Author identification, if combination of particular grammatic techniques is there or not.\n\n2. With the following knowledge of binary features, what's the expected count of $c(A \\cap B), c(\\neg A \\cap B), c(A \\cap \\neg  B), c(\\neg A \\cap \\neg B)$? \\\\\nTotal count $N = 100$, $c(A) = 35, c(B) = 61$. (0.25 points)\n\n**Answers** <br>\n\\begin{align*}\nc(A \\cap B) &= c(A) \\cdot c(B) &= 35\\cdot61 = 2135 \\\\\nc(\\neg A \\cap B) &= c(\\neg A) \\cdot c(B) &= (100-35)\\cdot61 = 3965 \\\\\nc(A \\cap \\neg B) &= c(A) \\cdot c(B) &= 35\\cdot(100-61) = 1365 \\\\\nc(\\neg A \\cap \\neg B) &= c(A) \\cdot c(B) &= (100-35)\\cdot(100-61) = 2535\n\\end{align*}\n\n3. Using the given observations compute the $\\chi^2$ statistics and the respective probability of the features $B$ and $C$. (0.5 points)\n\n||A|$\\neg$ A|\n|-|-|-|\n|B|6|55|\n|{$\\neg $B}|29|10|\n\n||A|$\\neg$ A|\n|-|-|-|\n|C|21|40|\n|{$\\neg$ C}|14|25|\n\n**Answers** <br>\n$A = \\#(B, A) = 6$ <br>\n$B = \\#(\\neg B,A) = 29$ <br>\n$C = \\#(B, \\neg A) = 55$ <br>\n$D = \\#(\\neg B, \\neg A) = 10$ <br>\n$N = A+B+C+D = 100$\n\\begin{align*}\n\\chi^2 &= \\frac{N(AD - BC)^2}{(A+B)(A+C)(B+D)(C+D)} \\\\\n\\chi^2 &= \\frac{100(6\\cdot10 - 29\\cdot55)^2}{(6+29)(6+55)(29+10)(55+10)} \\\\\n\\chi^2 &=  45.535\\\\\n\\end{align*}\n$P(B) = \\frac{6+55}{100}=0.61$\n\n$A = \\#(C, A) = 21$ <br>\n$B = \\#(\\neg C,A) = 14$ <br>\n$C = \\#(C, \\neg A) = 40$ <br>\n$D = \\#(\\neg C, \\neg A) = 25$ <br>\n$N = A+B+C+D = 100$\n\\begin{align*}\n\\chi^2 &= \\frac{100(21\\cdot25 - 14\\cdot40)^2}{(21+14)(21+40)(14+25)(40+25)} \\\\\n\\chi^2 &= 0.0226\\\\\n\\end{align*}\n$P(C) = \\frac{21+40}{100}=0.61$\n\n4. Based on your research of $\\chi^2$, what does the computed probability signify (in terms of hypotheses)? What is the hypothesis? Would you say that $B$ and $C$ are good features to decribe $A$? (0.25 points)\n\n**Answers** <br>\nThe computed probability summarizes the difference between given data and our independence hypothesis. We assume a null hypothesis where class $A$ and features $B$ or $C$ are statistically independent. <br>\n$\\chi^2$ value of $B$ is significantly high so we believe that the variables are independent i.e. they are not linked together, hence $B$ is not a good feature to describe $A$. While $\\chi^2$ value of $C$ is quite low ($< 0.05$) representing the strong dependence relation between $C$  and $A$ hence, $C$ can be used to describe A. \n\n**2.2 $\\chi^2$ Feature selection (0.75 points)**\n\n1. Given the set of categorical features $F$ and one specific target feature $f_0$, how can you use the $\\chi^2$ statistics to select the most predictive feature? (0.25 points)\n2. If you know all the features in $F$ are **not** pair-wise independent, how do you select $k$ features to describe $f_0$ together? (0.25 points)\n3. If you know all the features in $F$ are pair-wise independent, how do you select $k$ features to describe $f_0$ together? (Try to be computationally efficient and therefore provide a different algorithm than for the previous question.) (0.25 points)\n\n**Answers** <br>\n1. We can calculate $\\chi^2$ value between each feature in F with target feature $f_0$ and among themselves. The most predictive feature would be the one with the least $\\chi^2$ value. <br>\n2. Even if they are not pairwise independent, selection could be based on correlation between features. We want features which are least correlated or redundant. The first $k$ features with least $\\chi^2$ value with $f_0$ would be selected. Here we will include only one feature of two which are not pair-wise independent. <br>\n3. $\\chi^2$ value will be zero for pair-wise independent terms, thus this computation can be omitted. We just select k features from $F$ with least $\\chi^2$ with target $f_0$ directly unlike 2. \n\n\n\n## Exercise 3: Authorship Identification (4 points)\n\nThe science of *stylometry* assumes that authors have unconscious writing habits. Therefore, the words and grammar in a text become reliable indicators of the author of the text. Various research techniques have tried to do a feature-level analysis for the task of authorship identification/attribution. \n\n**3.1 (1 point)** \n\nIn Chapter 6, you studied different types of classification. For the particular problem of authorship identification, suggest how you could formulate this task for each of the following categories (1 sentence each)\n\n- Binary classification\n- Multi-class classification\n- Flat classification\n- Hierarchical classification\n- Single category classification\n- Multi-category classification\n- Clustering\n\n**Answers**<br>\n- Binary classification: Given a document predict if it was authored by the target author (here we assume that a document has a unique author) or not. \n- Multi-class classification: Given a document with multiple target authors, predict who authored it. One could use binary classification with one-vs-rest classification.\n- Flat classification: Assume that the authors are mutually exclusvie or they share no similarlity in their writing pattern. The classifier would assign an author to a document based on a single decision.\n- Hierarchical classification: In hierarchial classification the categories or the authors are organized into levels depending on their similarity in writing pattern. The classifier would then take multiple iterations to itertate from a parent node to reach down to a root node (the final category) who is the author of that document.\n- Single category classification: If given a situation where a document is authored by only one author, the goal would be to predict the author of a document from a pool of authors.\n- Multi-category classification: If given the situation where a document is authored by multiple authors, the goal would be to predict authors of a document from a pool of authors.\n- Clustering: Given many document, the goal is to group or cluster documents that could have been authored by the same author.\n\n**3.2 (2.5 points)**\n\nRead this [paper](https://dl.acm.org/doi/pdf/10.3115/1220355.1220443) which does a feature study for authorship identification. Answer the following questions (1-3 sentences each):\n\n1. What are the 6 categories of features extracted for the task? Explain in 1 sentence each. (0.5 points)\n2. What does the author observe in comparison to the baseline? (0.5 points) \n3. The author suggests using [SVM](https://en.wikipedia.org/wiki/Support-vector_machine)s as the classifier. What are the advantages offered by SVMs which guarantee a high accuracy in this problem? (0.5 point) \n4. The author concludes several possible scopes of improvement. Based on what you have studied so far, suggest if any improvements can be made in the given study w.r.t. (1 point)\n  - Feature selection \n  - Usage of n-gram features\n  - Any other approach other than the above two\n\n**Answers**<br>\n1. \n- Length features: compute average lengths of sentences\n- Function word frequencies: function words carrying little lexical meaning like articles, pronouns, etc. are mapped to a single token (for each category) and the frequency of such tokens is taken into account instead.\n- part of speech trigrams: compute the frequency of POS trigrams. E.g. given the trigram `ABC` and pos(`C`)=`NOUN`. Get the frequency of all such trigrams.\n- syntactic productions: compute per document frequency of all productions.\n- semantic information: binary semantic info (eg. number and person feature (eg. 1st person, 2nd person, etc), preverbal and postverbal locatives, etc.) + semantic modification relation (pos of all members in a semantic graph and semantic relation of all daughter nodes). We compute per document the frequency of all modification structures. \n- n-gram frequency features: compute frequency distribution of all ngrams in the corpus but with certain tweaks like- map all proper nouns to a unique token`NAME`.\n\n2. In comparison to the baseline accuracy 45.5%, the authors observed that POS trigram frequencies performed exceptionally well than other features with accuracy ranging in 92%-94%. When all features are combined, the highest accuracy of 97.67% is achieved with a frequency threshold of 75.\n\n3. SVMs are effective in high dimensional feature spaces similar to our problem where we have multiple feature spaces that are combined together to perform classification.\n\n4. \n- We could prepare feature heatmaps to understand exactly what features contribute to the model's prediction. Features with the least contribution could be eliminated to avoid overfitting and gain training performance. We could also use $\\chi^2$ test to select those features that have the strongest relationship with the output variable.\n- One could try with a combination of POS bigrams and POS trigrams as the latter alone has been observed to outperform other features in terms of accuracy.\n- Ensemble approach as discussed in the article is also a promising idea. Different classifiers could be trained for different features and further, an ensemble of all the classifiers could be taken to make the final prediction.\n\n**3.3 (0.5 points)** \n\nState 3 real-life, contemporary applications where authorship identification/verification/attribution is useful. \n\n**Answers**<br>\n- Cheating detection among students\n- Musical authorship detection. Quite a number of musicians engage in copying others' work and present them as their own. Stylometry could be applied to such disputed work.\n- Identify authors of historical manuscripts based on their writing pattern. It can also be applied to group manuscripts that have similar writing patterns and attribute them to a single author.\n- In the field of forensics cases eg. detection of suicide notes.\n\n## Bonus (1.5 points) \n\nConsider the two plots given below. \n\n* For Plot 1 and Plot 2, are any or both of the features 1 and 2 \n1. redundant\n2. useful\n3. irrelevant\n\n    for a task like clustering? Explain your choice from the above 3. (1 point)\n    \n\n\n**Answers** <br>\n- for Plot 1 there seems a good relationship between feature 1 and feature 2, hence for clustering, both the features seem useful. But since there is direct correlation between values of feature 1 and feature 2 - both values are increasing monotonically together. Just one is enough. So there is just one useful and another is redundant. \n- for Plot 2, Feature 2 seems to be weakly linked with Feature 1 as it does not hold any relationship according to given plot. Feature 2 remains almost same as Feature 1 increases in value. Hence, feature 2 seems redundant and irrelevant. While feature 1 is useful.\n\n* Draw/create a plot which shows features 1 and 2 as the remaining of the 3 choices stated above. Explain your reasoning in 1-2 sentences. (0.5 point)\n\n**Answers** <br>\n\n* In plot 1, both features are not correlated and have direct influence on data points to group them.\n* In plot 2, irrespective of features all data points can be grouped into one single clusters thus all are irrelevant.\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "6ebcfbceb33e7db17168ca274653dc77e7e0d866", "size": 170403, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "snlp/hw8/Assignment8.ipynb", "max_stars_repo_name": "sangeet2020/ss-21", "max_stars_repo_head_hexsha": "c2dbcf9668cb82b27a76e766a977483dd5fae0d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-13T21:07:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T21:07:49.000Z", "max_issues_repo_path": "snlp/hw8/Assignment8.ipynb", "max_issues_repo_name": "sangeet2020/ss-21", "max_issues_repo_head_hexsha": "c2dbcf9668cb82b27a76e766a977483dd5fae0d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "snlp/hw8/Assignment8.ipynb", "max_forks_repo_name": "sangeet2020/ss-21", "max_forks_repo_head_hexsha": "c2dbcf9668cb82b27a76e766a977483dd5fae0d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 232.1566757493, "max_line_length": 49652, "alphanum_fraction": 0.9027364542, "converted": true, "num_tokens": 5531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2974699426047947, "lm_q2_score": 0.10087862273005653, "lm_q1q2_score": 0.030008358113560653}}
{"text": "<a id='about-py'></a>\n<div id=\"qe-notebook-header\" align=\"right\" style=\"text-align:right;\">\n        <a href=\"https://quantecon.org/\" title=\"quantecon.org\">\n                \n        </a>\n</div>\n\n\n<a id='index-0'></a>\n\n# About Python\n\n## Contents\n\n- [About Python](#About-Python)  \n  - [Overview](#Overview)  \n  - [What\u2019s Python?](#What\u2019s-Python?)  \n  - [Scientific Programming](#Scientific-Programming)  \n  - [Learn More](#Learn-More)  \n\n> \u201cPython has gotten sufficiently weapons grade that we don\u2019t descend into R\n> anymore. Sorry, R people. I used to be one of you but we no longer descend\n> into R.\u201d \u2013 Chris Wiggins\n\n## Overview\n\nIn this lecture we will\n\n- outline what Python is  \n- showcase some of its abilities  \n- compare it to some other languages.  \n\n\nAt this stage, it\u2019s **not** our intention that you try to replicate all you see.\n\nWe will work through what follows at a slow pace later in the lecture series.\n\nOur only objective for this lecture is to give you some feel of what Python is, and what it can do.\n\n## What\u2019s Python?\n\n[Python](https://www.python.org) is a general-purpose programming language conceived in 1989 by Dutch programmer [Guido van Rossum](https://en.wikipedia.org/wiki/Guido_van_Rossum).\n\nPython is free and open source, with development coordinated through the [Python Software Foundation](https://www.python.org/psf/).\n\nPython has experienced rapid adoption in the last decade and is now one of the most popular programming languages.\n\n### Common Uses\n\nPython is a general-purpose language used in almost all application domains such as\n\n- communications  \n- web development  \n- CGI and graphical user interfaces  \n- game development  \n- multimedia, data processing, security, etc., etc., etc.  \n\n\nUsed extensively by Internet services and high tech companies including\n\n- [Google](https://www.google.com/)  \n- [Dropbox](https://www.dropbox.com/)  \n- [Reddit](https://www.reddit.com/)  \n- [YouTube](https://www.youtube.com/)  \n- [Walt Disney Animation](https://pydanny-event-notes.readthedocs.org/en/latest/socalpiggies/20110526-wda.html).  \n\n\nPython is very beginner-friendly and is often used to [teach computer science and programming](http://cacm.acm.org/blogs/blog-cacm/176450-python-is-now-the-most-popular-introductory-teaching-language-at-top-us-universities/fulltext).\n\nFor reasons we will discuss, Python is particularly popular within the scientific community with users including NASA, CERN and practically all branches of academia.\n\nIt is also [replacing familiar tools like Excel](https://news.efinancialcareers.com/us-en/3002556/python-replaced-excel-banking) in the fields of finance and banking.\n\n### Relative Popularity\n\nThe following chart, produced using Stack Overflow Trends, shows one measure of the relative popularity of Python\n\n\n\n  \nThe figure indicates not only that Python is widely used but also that adoption of Python has accelerated significantly since 2012.\n\nWe suspect this is driven at least in part by uptake in the scientific\ndomain, particularly in rapidly growing fields like data science.\n\nFor example, the popularity of [pandas](http://pandas.pydata.org/), a library for data analysis with Python has exploded, as seen here.\n\n(The corresponding time path for MATLAB is shown for comparison)\n\n\n\n  \nNote that pandas takes off in 2012, which is the same year that we see\nPython\u2019s popularity begin to spike in the first figure.\n\nOverall, it\u2019s clear that\n\n- Python is [one of the most popular programming languages worldwide](https://spectrum.ieee.org/computing/software/the-top-programming-languages-2019).  \n- Python is a major tool for scientific computing, accounting for a rapidly rising share of scientific work around the globe.  \n\n### Features\n\nPython is a [high-level language](https://en.wikipedia.org/wiki/High-level_programming_language) suitable for rapid development.\n\nIt has a relatively small core language supported by many libraries.\n\nOther features of Python:\n\n- multiple programming styles are supported (procedural, object-oriented, functional, etc.)  \n- it is interpreted rather than compiled.  \n\n### Syntax and Design\n\n\n<a id='index-2'></a>\nOne nice feature of Python is its elegant syntax \u2014 we\u2019ll see many examples later on.\n\nElegant code might sound superfluous but in fact it\u2019s highly beneficial because it makes the syntax easy to read and easy to remember.\n\nRemembering how to read from files, sort dictionaries and other such routine tasks means that you don\u2019t need to break your flow in order to hunt down correct syntax.\n\nClosely related to elegant syntax is an elegant design.\n\nFeatures like iterators, generators, decorators and list comprehensions make Python highly expressive, allowing you to get more done with less code.\n\n[Namespaces](https://en.wikipedia.org/wiki/Namespace) improve productivity by cutting down on bugs and syntax errors.\n\n## Scientific Programming\n\n\n<a id='index-3'></a>\nPython has become one of the core languages of scientific computing.\n\nIt\u2019s either the dominant player or a major player in\n\n- [machine learning and data science](http://scikit-learn.org/stable/)  \n- [astronomy](http://www.astropy.org/)  \n- [artificial intelligence](https://wiki.python.org/moin/PythonForArtificialIntelligence)  \n- [chemistry](http://chemlab.github.io/chemlab/)  \n- [computational biology](http://biopython.org/wiki/Main_Page)  \n- [meteorology](https://pypi.org/project/meteorology/)  \n\n\nIts popularity in economics is also beginning to rise.\n\nThis section briefly showcases some examples of Python for scientific programming.\n\n- All of these topics will be covered in detail later on.  \n\n### Numerical Programming\n\n\n<a id='index-4'></a>\nFundamental matrix and array processing capabilities are provided by the excellent [NumPy](http://www.numpy.org/) library.\n\nNumPy provides the basic array data type plus some simple processing operations.\n\nFor example, let\u2019s build some arrays\n\n\n```\nimport numpy as np                     # Load the library\n\na = np.linspace(-np.pi, np.pi, 100)    # Create even grid from -\u03c0 to \u03c0\nb = np.cos(a)                          # Apply cosine to each element of a\nc = np.sin(a)                          # Apply sin to each element of a\n```\n\nNow let\u2019s take the inner product\n\n\n```\nb @ c\n```\n\nThe number you see here might vary slightly but it\u2019s essentially zero.\n\n(For older versions of Python and NumPy you need to use the [np.dot](http://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html) function)\n\nThe [SciPy](http://www.scipy.org) library is built on top of NumPy and provides additional functionality.\n\n\n<a id='tuple-unpacking-example'></a>\nFor example, let\u2019s calculate $ \\int_{-2}^2 \\phi(z) dz $ where $ \\phi $ is the standard normal density.\n\n\n```\nfrom scipy.stats import norm\nfrom scipy.integrate import quad\n\n\u03d5 = norm()\nvalue, error = quad(\u03d5.pdf, -2, 2)  # Integrate using Gaussian quadrature\nvalue\n```\n\nSciPy includes many of the standard routines used in\n\n- [linear algebra](http://docs.scipy.org/doc/scipy/reference/linalg.html)  \n- [integration](http://docs.scipy.org/doc/scipy/reference/integrate.html)  \n- [interpolation](http://docs.scipy.org/doc/scipy/reference/interpolate.html)  \n- [optimization](http://docs.scipy.org/doc/scipy/reference/optimize.html)  \n- [distributions and random number generation](http://docs.scipy.org/doc/scipy/reference/stats.html)  \n- [signal processing](http://docs.scipy.org/doc/scipy/reference/signal.html)  \n\n\nSee them all [here](http://docs.scipy.org/doc/scipy/reference/index.html).\n\n### Graphics\n\n\n<a id='index-5'></a>\nThe most popular and comprehensive Python library for creating figures and graphs is [Matplotlib](http://matplotlib.org/), with functionality including\n\n- plots, histograms, contour images, 3D graphs, bar charts etc.  \n- output in many formats (PDF, PNG, EPS, etc.)  \n- LaTeX integration  \n\n\nExample 2D plot with embedded LaTeX annotations\n\n\n\n  \nExample contour plot\n\n\n\n  \nExample 3D plot\n\n\n\n  \nMore examples can be found in the [Matplotlib thumbnail gallery](http://matplotlib.org/gallery.html).\n\nOther graphics libraries include\n\n- [Plotly](https://plot.ly/python/)  \n- [Bokeh](http://bokeh.pydata.org/en/latest/)  \n- [VPython](http://www.vpython.org/) \u2014 3D graphics and animations  \n\n### Symbolic Algebra\n\nIt\u2019s useful to be able to manipulate symbolic expressions, as in Mathematica or Maple.\n\n\n<a id='index-6'></a>\nThe [SymPy](http://www.sympy.org/) library provides this functionality from within the Python shell.\n\n\n```\nfrom sympy import Symbol\n\nx, y = Symbol('x'), Symbol('y')  # Treat 'x' and 'y' as algebraic symbols\nx + x + x + y\n```\n\nWe can manipulate expressions\n\n\n```\nexpression = (x + y)**2\nexpression.expand()\n```\n\nsolve polynomials\n\n\n```\nfrom sympy import solve\n\nsolve(x**2 + x + 2)\n```\n\nand calculate limits, derivatives and integrals\n\n\n```\nfrom sympy import limit, sin, diff\n\nlimit(1 / x, x, 0)\n```\n\n\n```\nlimit(sin(x) / x, x, 0)\n```\n\n\n```\ndiff(sin(x), x)\n```\n\nThe beauty of importing this functionality into Python is that we are working within\na fully fledged programming language.\n\nWe can easily create tables of derivatives, generate LaTeX output, add that output\nto figures and so on.\n\n### Statistics\n\nPython\u2019s data manipulation and statistics libraries have improved rapidly over\nthe last few years.\n\n#### Pandas\n\n\n<a id='index-7'></a>\nOne of the most popular libraries for working with data is [pandas](http://pandas.pydata.org/).\n\nPandas is fast, efficient, flexible and well designed.\n\nHere\u2019s a simple example, using some dummy data generated with Numpy\u2019s excellent\n`random` functionality.\n\n\n```\nimport pandas as pd\nnp.random.seed(1234)\n\ndata = np.random.randn(5, 2)  # 5x2 matrix of N(0, 1) random draws\ndates = pd.date_range('28/12/2010', periods=5)\n\ndf = pd.DataFrame(data, columns=('price', 'weight'), index=dates)\nprint(df)\n```\n\n\n```\ndf.mean()\n```\n\n#### Other Useful Statistics Libraries\n\n\n<a id='index-8'></a>\n- [statsmodels](http://statsmodels.sourceforge.net/) \u2014 various statistical routines  \n\n\n\n<a id='index-9'></a>\n- [scikit-learn](http://scikit-learn.org/) \u2014 machine learning in Python (sponsored by Google, among others)  \n\n\n\n<a id='index-10'></a>\n- [pyMC](http://pymc-devs.github.io/pymc/) \u2014 for Bayesian data analysis  \n\n\n\n<a id='index-11'></a>\n- [pystan](https://pystan.readthedocs.org/en/latest/) Bayesian analysis based on [stan](http://mc-stan.org/)  \n\n### Networks and Graphs\n\nPython has many libraries for studying graphs.\n\n\n<a id='index-12'></a>\nOne well-known example is [NetworkX](http://networkx.github.io/).\nIts features include, among many other things:\n\n- standard graph algorithms for analyzing networks  \n- plotting routines  \n\n\nHere\u2019s some example code that generates and plots a random graph, with node color determined by shortest path length from a central node.\n\n\n```\n%matplotlib inline\nimport networkx as nx\nimport matplotlib.pyplot as plt\nplt.rcParams['figure.figsize'] = (10,6)\nnp.random.seed(1234)\n\n# Generate a random graph\np = dict((i, (np.random.uniform(0, 1), np.random.uniform(0, 1)))\n         for i in range(200))\ng = nx.random_geometric_graph(200, 0.12, pos=p)\npos = nx.get_node_attributes(g, 'pos')\n\n# Find node nearest the center point (0.5, 0.5)\ndists = [(x - 0.5)**2 + (y - 0.5)**2 for x, y in list(pos.values())]\nncenter = np.argmin(dists)\n\n# Plot graph, coloring by path length from central node\np = nx.single_source_shortest_path_length(g, ncenter)\nplt.figure()\nnx.draw_networkx_edges(g, pos, alpha=0.4)\nnx.draw_networkx_nodes(g,\n                       pos,\n                       nodelist=list(p.keys()),\n                       node_size=120, alpha=0.5,\n                       node_color=list(p.values()),\n                       cmap=plt.cm.jet_r)\nplt.show()\n```\n\n### Cloud Computing\n\n\n<a id='index-13'></a>\nRunning your Python code on massive servers in the cloud is becoming easier and easier.\n\n\n<a id='index-14'></a>\nA nice example is [Anaconda Enterprise](https://www.anaconda.com/enterprise/).\n\nSee also\n\n\n<a id='index-15'></a>\n- [Amazon Elastic Compute Cloud](http://aws.amazon.com/ec2/)  \n\n\n\n<a id='index-16'></a>\n- The [Google App Engine](https://cloud.google.com/appengine/) (Python, Java, PHP or Go)  \n\n\n\n<a id='index-17'></a>\n- [Pythonanywhere](https://www.pythonanywhere.com/)  \n\n\n\n<a id='index-18'></a>\n- [Sagemath Cloud](https://cloud.sagemath.com/)  \n\n### Parallel Processing\n\n\n<a id='index-19'></a>\nApart from the cloud computing options listed above, you might like to consider\n\n\n<a id='index-20'></a>\n- [Parallel computing through IPython clusters](http://ipython.org/ipython-doc/stable/parallel/parallel_demos.html).  \n\n\n\n<a id='index-21'></a>\n- The [Starcluster](http://star.mit.edu/cluster/) interface to Amazon\u2019s EC2.  \n\n\n\n<a id='index-23'></a>\n- GPU programming through [PyCuda](https://wiki.tiker.net/PyCuda), [PyOpenCL](https://mathema.tician.de/software/pyopencl/), [Theano](https://en.wikipedia.org/wiki/Theano_%28software%29) or similar.  \n\n\n\n<a id='intfc'></a>\n\n### Other Developments\n\nThere are many other interesting developments with scientific programming in Python.\n\nSome representative examples include\n\n\n<a id='index-24'></a>\n- [Jupyter](http://jupyter.org/) \u2014 Python in your browser with interactive code cells,  embedded images and other useful features.  \n\n\n\n<a id='index-25'></a>\n- [Numba](http://numba.pydata.org/) \u2014 Make Python run at the same speed as native machine code!  \n\n\n\n<a id='index-26'></a>\n- [Blaze](http://blaze.pydata.org/) \u2014 a generalization of NumPy.  \n\n\n\n<a id='index-27'></a>\n- [PyTables](http://www.pytables.org) \u2014 manage large data sets.  \n\n\n\n<a id='index-28'></a>\n- [CVXPY](https://github.com/cvxgrp/cvxpy) \u2014 convex optimization in Python.  \n\n## Learn More\n\n- Browse some Python projects on [GitHub](https://github.com/trending?l=python).  \n- Read more about [Python\u2019s history and rise in popularity](https://www.welcometothejungle.com/en/articles/btc-python-popular) .  \n- Have a look at [some of the Jupyter notebooks](http://nbviewer.jupyter.org/) people have shared on various scientific topics.  \n\n\n\n<a id='index-29'></a>\n- Visit the [Python Package Index](https://pypi.org/).  \n- View some of the questions people are asking about Python on [Stackoverflow](http://stackoverflow.com/questions/tagged/python).  \n- Keep up to date on what\u2019s happening in the Python community with the [Python subreddit](https://www.reddit.com:443/r/Python/).  \n", "meta": {"hexsha": "c4af06b3b790ebc5e1462529c3d78c16ad5e4e89", "size": 23996, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tests/project/ipynb/about_py.ipynb", "max_stars_repo_name": "QuantEcon/sphinx-tojupyter", "max_stars_repo_head_hexsha": "ba15167e433ef67b92d88484465c40cb9153bc3c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-08T11:43:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-08T11:43:38.000Z", "max_issues_repo_path": "tests/project/ipynb/about_py.ipynb", "max_issues_repo_name": "QuantEcon/sphinx-tojupyter", "max_issues_repo_head_hexsha": "ba15167e433ef67b92d88484465c40cb9153bc3c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2020-11-10T04:42:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T07:48:53.000Z", "max_forks_repo_path": "tests/project/ipynb/about_py.ipynb", "max_forks_repo_name": "QuantEcon/sphinx-tojupyter", "max_forks_repo_head_hexsha": "ba15167e433ef67b92d88484465c40cb9153bc3c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0829015544, "max_line_length": 242, "alphanum_fraction": 0.5760543424, "converted": true, "num_tokens": 3528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22815650216092534, "lm_q2_score": 0.1311732203653401, "lm_q1q2_score": 0.029928023135740254}}
{"text": "<div class=\"alert alert-block alert-info\">\n    \n    <u><h1>respy showcase</h1></u>\n</div>\n\n\n```python\nimport io\nimport copy\nimport yaml\nimport numpy as np\nimport pandas as pd\nimport respy as rp\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom IPython.display import Image\nfrom pathlib import Path\n\nfrom auxiliary.auxiliary import *\n```\n\n ### Outline\n\n 1.  <span style=\"color:#2C68B9\">Package overview</span>  \n 2.  Introductory tutorial  \n  2.1. Theoretical Framework  \n  2.2. Specifying a model  \n  2.3. Simulating data  \n  2.4. Extending the model  \n 3. Pre-implemented example models\n 4. Outlook\n\n<div class=\"alert alert-block alert-info\">\n    <u><h2>1. Package overview</h2></u>\n</div>\n\n\n### What is **respy**?\n\n- open source Python framework\n- simulation and estimation of some finite-horizon discrete choice dynamic programming models \n- class of models: Eckstein-Keane-Wolpin models (Aguirregabiria & Mira, 2009)\n\n\n### Class of models\n\n- Eckstein-Keane-Wolpin models\n- discrete choice dynamic life-cycle framework\n- reward function structure: experience accumulation and wages\n- economic applications: human capital investments, labor supply, occupational choice\n\n\n**Model components**\n- (any) number of choices and periods\n- initial conditions: lagged choices, initial experience, observable characteristics\n- unobserved heterogeneity: finite mixture models (types)\n- measurement error\n\n### Use cases\n\n**For research ...**\n- flexible model specification\n- build and solve structural models in weeks or months\n- extensive test suite\n\n**For learning & teaching ...**\n- extensive online documentation: tutorials, explanations, how-to guides\n- variety of pre-implemented example models that scale from toy examples to full empirical models\n- sandbox for theses & student projects\n- lecture materials: https://ekw-lectures.readthedocs.io\n\n### Steps of modeling\n\n 1. Theoretical development  \n 2. <span style=\"color:#2C68B9\">Model implementation</span>  \n     2.1. <span style=\"color:#2C68B9\">Specification</span>    \n     2.2. <span style=\"color:#2C68B9\">Solution</span>    \n     2.3. <span style=\"color:#2C68B9\">Simulation</span>    \n 3. <span style=\"color:#2C68B9\">Calibration</span>  \n      3.1. <span style=\"color:#2C68B9\">Likelihood- or simulation-based criterion</span>    \n      3.2. Optimization $\\rightarrow$ [estimagic](https://estimagic.readthedocs.io/en/latest/)  \n 4. <span style=\"color:#2C68B9\">Validation and policy evaluation</span> \n\n### Source code & documentation\n\n- developed on GitHub: https://github.com/OpenSourceEconomics/respy\n\n\n- online documentation: https://respy.readthedocs.io\n\n\n**Installation via conda**\n\n\n\n```bash\n$ conda config --add channels conda-forge\n$ conda install -c opensourceeconomics respy\n```\n\n#### Source code on GitHub: https://github.com/OpenSourceEconomics/respy\n\n\n```python\nImage(filename='figures/respy-github.png')\n```\n\n#### Testing\n\n\n```python\nImage(filename='figures/respy-ci.png')\n```\n\n#### Online documentation: https://respy.readthedocs.io\n\n\n```python\nImage(filename='figures/respy-docs.png')\n```\n\n ### Outline\n\n 1.  Package overview  \n 2.  <span style=\"color:#2C68B9\">Introductory tutorial</span>  \n  2.1. Theoretical framework  \n  2.2. Specifying a model  \n  2.3. Simulating data  \n  2.4. Extending the model  \n 3. Pre-implemented example models\n 4. Outlook\n\n<div class=\"alert alert-block alert-info\">\n    <u><h2>2. Introductory tutorial</h2></u>\n</div>\n\n### Situational setup\n- Robinson Crusoe is stranded on a small island.\n- He goes fishing to make ends meet and will relax in his hammock when he is tired.\n- He cannot relax to often as he won't be able to eat otherwise.\n- The more he fishes, the better his fishing skills become.\n\n<div class=\"alert alert-block alert-warning\">\n    <u><h3>2.1. Theoretical Framework: Robinson Crusoe on an island</h3></u>\n</div>\n\n### The economic problem\n\n- Robinson chooses every period $t = 0, \\dots, T$ to either go fishing, $a = 0$, or spend the day in the hammock, $a = 1$.\n\n- If Robinson chooses to go fishing, he gains one additional unit of **experience** in the next period. Experience starts at zero.\n\n- The utility of a choice, $U(s_t, a_t)$, depends on the state $s_t$, which contains information on the individual's characteristics, and the chosen alternative $a_t$.\n\n- Robinson's utility for any given option can be denoted by\n\n$$\\begin{align}\n    U(s_t, a_t) = \\underbrace{W(s_t, a_t)}_{wage} + \\underbrace{N(s_t, a_t)}_{non-pecuniary}\n\\end{align}\n$$\n\n\n```python\nImage(filename=\"figures/tree_small.jpg\")\n```\n\n\n\n\n    \n\n    \n\n\n\n### Working alternatives\n\n- For working alternatives like fishing, utility consists of two components, a *wage* and a *non-pecuniary* component.\n\n**Wage** \n\n$$\\begin{align}\n        W(s_t, a_t)  &= r_{a} \\exp\\{x^w_{at} \\beta^w_a + \\epsilon_{at}\\}\\\\\n    \\ln(W(s_t, a_t)) &= \\ln(r_a) + x^w_{at} \\beta^w_a + \\epsilon_{at}\n\\end{align}$$\n\n- Components:\n    - $r_a$ is a market rental price for skill units.\n    \n    - $x^w_{at}$ and $\\beta^w_a$ are the choice- and time-dependent covariates and returns related to the wage signaled by superscript $w$. \n    \n    - $\\epsilon_{at}$ is a choice-specific random shock from the shock vector $\\epsilon_t \\sim \\mathcal{N}(0, \\Sigma)$ for all choices.\n\n**Non-pecuniary rewards** (for working alternatives)\n\n- Vector dot product of covariates $x_t^w$ and parameters $\\beta^w$. \n- Superscript $w$ signals that the components belong to working alternatives.\n\n$$\\begin{align}\n    N^w(s_t, a_t) = x_t^w\\beta^w\n\\end{align}$$\n\n### Non-working alternatives\n\n**Wage**\n$$\\begin{align}\nW(s_t, a_t) = 0\n\\end{align}$$\n\n**Non-pecuniary rewards**\n\n- Shocks enter the equation *additively*\n- Superscript $n$ stands for non-pecuniary\n$$\n    N^n(s_t, a_t) = x_t^n\\beta^n + \\epsilon_{at}\n$$\n\n- Robinson's choice set thus consists of a \"working\" alternative which awards him a pecuniary compensation or wage and a \"leisure\" or non-working alternative which he derives a utility from, but no experience or wage. Experience in this basic model starts at zero and increases by one for every period $t$ in $1, ..., T$ where he chooses to go fishing. \n\n### Robinson's choice problem\n\n- Robinson is forward-looking and maximizes the expected present value of utility over the remaining lifetime  $\\rightarrow$ select the optimal sequence of choices $\\{a_t\\}^T_{t = 0}$.\n\n\n- **Bellman equation**\n\n$$\\begin{align}\n    V(s_{t})&= \\max_{a_t} \\, \\{\\underbrace{U(s_t, a_t)}_{\\text{flow utility}}+ \\delta \\underbrace{\\text{E}[ V(s_{t+1})]\\}}_{\\text{continuation value}}\n\\end{align}$$\n\n- Realization of shocks becomes known in each period before Robinson makes his choice.\n- As shocks in period $t + 1$ are unknown to the individual in period $t$, utility must be maximized given the joint distribution of shocks in period $t + 1$ which is a maximization problem over a two-dimensional integral.\n\n- Denote the non-stochastic part of a state as $s^-$. Then, Robinson maximizes.\n\n$$\\begin{equation}\n    V(s_t) = \\max_{a_t}\\{\n        U(s_t, a_t) + \\delta \\int_{\\epsilon_{1, t + 1}} \\int_{\\epsilon_{0, t + 1}}\n        \\max_{a_{t + 1}} V_{a_{t + 1}}(s^-_{t + 1}, \\epsilon_{t + 1})\n        f_\\epsilon(\\epsilon_{t + 1})\n        d_{\\epsilon_{0, t + 1}}, d_{\\epsilon_{1, t + 1}}\n    \\}\n\\end{equation}$$\n\n ### Outline\n\n 1.  Package overview  \n 2.  Introductory tutorial  \n  2.1. Theoretical framework  \n  2.2. <span style=\"color:#2C68B9\">Specifying a model</span>  \n  2.3. Simulating data  \n  2.4. Extending the model  \n 3. Pre-implemented example models\n 4. Outlook\n\n<div class=\"alert alert-block alert-warning\">\n    <u><h3>2.2. Specifying the model</h3></u>\n</div>\n\n**respy** models consists of two main inputs:\n\n- `params`: (estimable) model parameters\n\n\n- `options` : model settings (number of periods, implementation details) \n\n\n### Model parameters: ``params``\n\n- Parameter vector of the model\n\n\n- Specified as a [MultiIndex pandas.DataFrame](https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html) with two index levels.\n    1. *category*: which indicates certain parameters groups\n    2. *name*: which indicates a specific parameter\n    \n\n- read in parameters from a .csv-file:\n\n\n```python\nparams = \"\"\"category,name,value\ndelta,delta,0.95\nwage_fishing,exp_fishing,0.1\nnonpec_fishing,constant,-1\nnonpec_hammock,constant,2.5\nnonpec_hammock,not_fishing_last_period,-1\nshocks_sdcorr,sd_fishing,1\nshocks_sdcorr,sd_hammock,1\nshocks_sdcorr,corr_hammock_fishing,-0.2\nlagged_choice_1_hammock,constant,1\n\"\"\"\n```\n\n\n```python\nparams_basic = pd.read_csv(\n    io.StringIO(params), sep=\",\", index_col=[\"category\", \"name\"]\n)\n\nparams_basic\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>value</th>\n    </tr>\n    <tr>\n      <th>category</th>\n      <th>name</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>delta</th>\n      <th>delta</th>\n      <td>0.95</td>\n    </tr>\n    <tr>\n      <th>wage_fishing</th>\n      <th>exp_fishing</th>\n      <td>0.10</td>\n    </tr>\n    <tr>\n      <th>nonpec_fishing</th>\n      <th>constant</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">nonpec_hammock</th>\n      <th>constant</th>\n      <td>2.50</td>\n    </tr>\n    <tr>\n      <th>not_fishing_last_period</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">shocks_sdcorr</th>\n      <th>sd_fishing</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>sd_hammock</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>corr_hammock_fishing</th>\n      <td>-0.20</td>\n    </tr>\n    <tr>\n      <th>lagged_choice_1_hammock</th>\n      <th>constant</th>\n      <td>1.00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### Model options: ``options``\n\n-  dictionary which contains additional information\n    - number of periods in the model\n    - size of the simulated sample\n    - implementation details like seeds\n    - covariates\n\n\n```python\noptions_basic = {\n    \"n_periods\": 10,\n    \"simulation_agents\": 1000,\n    \"simulation_seed\": 123,\n    \"covariates\": {\n        \"constant\": \"1\",\n        \"not_fishing_last_period\": \"lagged_choice_1 != 'fishing'\",\n    },\n}\noptions_basic\n```\n\n\n\n\n    {'n_periods': 10,\n     'simulation_agents': 1000,\n     'simulation_seed': 123,\n     'covariates': {'constant': '1',\n      'not_fishing_last_period': \"lagged_choice_1 != 'fishing'\"}}\n\n\n\n ### Outline\n\n 1.  Package overview  \n 2.  Introductory tutorial  \n  2.1. Theoretical framework  \n  2.2. Specifying a model  \n  2.3. <span style=\"color:#2C68B9\">Simulating data</span>  \n  2.4. Extending the model  \n 3. Pre-implemented example models\n 4. Outlook\n\n<div class=\"alert alert-block alert-warning\">\n    <u><h3>2.3. Simulating data</h3></u>\n</div>\n\nUsing the `params` and `options` we can set up a simulator using the function `get_simulate_func` and subsequently simulate a data for our selected parametrization.\n\n\n```python\nsimulate = rp.get_simulate_func(params_basic, options_basic)\ndf_basic = simulate(params_basic)\ndf_basic.head(5)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>Experience_Fishing</th>\n      <th>Lagged_Choice_1</th>\n      <th>Shock_Reward_Fishing</th>\n      <th>Meas_Error_Wage_Fishing</th>\n      <th>Shock_Reward_Hammock</th>\n      <th>Meas_Error_Wage_Hammock</th>\n      <th>Dense_Key</th>\n      <th>Core_Index</th>\n      <th>Choice</th>\n      <th>Wage</th>\n      <th>...</th>\n      <th>Nonpecuniary_Reward_Fishing</th>\n      <th>Wage_Fishing</th>\n      <th>Flow_Utility_Fishing</th>\n      <th>Value_Function_Fishing</th>\n      <th>Continuation_Value_Fishing</th>\n      <th>Nonpecuniary_Reward_Hammock</th>\n      <th>Wage_Hammock</th>\n      <th>Flow_Utility_Hammock</th>\n      <th>Value_Function_Hammock</th>\n      <th>Continuation_Value_Hammock</th>\n    </tr>\n    <tr>\n      <th>Identifier</th>\n      <th>Period</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">0</th>\n      <th>0</th>\n      <td>0</td>\n      <td>hammock</td>\n      <td>0.428556</td>\n      <td>1</td>\n      <td>0.427466</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>fishing</td>\n      <td>1.535039</td>\n      <td>...</td>\n      <td>-1</td>\n      <td>1.535039</td>\n      <td>0.535039</td>\n      <td>19.006626</td>\n      <td>19.443776</td>\n      <td>1.5</td>\n      <td>NaN</td>\n      <td>1.833118</td>\n      <td>18.704274</td>\n      <td>17.759111</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>fishing</td>\n      <td>0.780145</td>\n      <td>1</td>\n      <td>1.850937</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>hammock</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>-1</td>\n      <td>2.411250</td>\n      <td>1.411250</td>\n      <td>19.104983</td>\n      <td>18.624982</td>\n      <td>2.5</td>\n      <td>NaN</td>\n      <td>4.157512</td>\n      <td>20.273393</td>\n      <td>16.964086</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1</td>\n      <td>hammock</td>\n      <td>2.063393</td>\n      <td>1</td>\n      <td>0.708209</td>\n      <td>1</td>\n      <td>2</td>\n      <td>0</td>\n      <td>fishing</td>\n      <td>8.700606</td>\n      <td>...</td>\n      <td>-1</td>\n      <td>8.700606</td>\n      <td>7.700606</td>\n      <td>23.415469</td>\n      <td>16.541961</td>\n      <td>1.5</td>\n      <td>NaN</td>\n      <td>1.781221</td>\n      <td>16.030649</td>\n      <td>14.999397</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>2</td>\n      <td>fishing</td>\n      <td>-1.190336</td>\n      <td>1</td>\n      <td>-2.028002</td>\n      <td>1</td>\n      <td>3</td>\n      <td>4</td>\n      <td>fishing</td>\n      <td>0.371452</td>\n      <td>...</td>\n      <td>-1</td>\n      <td>0.371452</td>\n      <td>-0.628548</td>\n      <td>13.904880</td>\n      <td>15.298346</td>\n      <td>2.5</td>\n      <td>NaN</td>\n      <td>0.751039</td>\n      <td>13.874853</td>\n      <td>13.814541</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>3</td>\n      <td>fishing</td>\n      <td>-0.049084</td>\n      <td>1</td>\n      <td>0.607816</td>\n      <td>1</td>\n      <td>4</td>\n      <td>5</td>\n      <td>hammock</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>-1</td>\n      <td>1.285202</td>\n      <td>0.285202</td>\n      <td>13.405278</td>\n      <td>13.810606</td>\n      <td>2.5</td>\n      <td>NaN</td>\n      <td>3.105353</td>\n      <td>14.884157</td>\n      <td>12.398742</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 22 columns</p>\n</div>\n\n\n\n**Choice shares**\n\n\n```python\nplot_choice_shares(df_basic)\n```\n\n**Transition matrix**\n\n\n```python\ndata = pd.crosstab(df_basic.Lagged_Choice_1, df_basic.Choice, normalize=True)\nsns.heatmap(data, cmap=\"Blues\", annot=True);\n```\n\n ### Outline\n\n 1.  Package overview  \n 2.  Introductory tutorial  \n  2.1. Theoretical framework  \n  2.2. Specifying a model  \n  2.3. Simulating data  \n  2.4. <span style=\"color:#2C68B9\">Extending the model</span>  \n 3. Pre-implemented example models\n 4. Outlook\n\n<div class=\"alert alert-block alert-warning\">\n    <u><h3>2.4. Extending the Model</h3></u>\n</div>\n\n<div class=\"alert alert-block alert-success\">\n    <u><h4>2.4.1. Extension: Covariates</h4></u>\n</div>\n\n**Covariates in the basic model**\n\n1. The constant, which is the simplest covariate\n2. The indicator whether Robinson went fishing last period.\n\n**New covariate:** *age*\n\n- assume Robinson's return to fishing decreases as he gets older.\n- assume that he arrives at the island with 16 years. \n- assume his age in each period, which we assume for now is one year, increases by one.\n\nI. Edit ``params``\n\n\n```python\nparams_age = params_basic.copy()\nparams_age.loc[(\"wage_fishing\", \"age\"), \"value\"] = -0.08\nparams_age\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>value</th>\n    </tr>\n    <tr>\n      <th>category</th>\n      <th>name</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>delta</th>\n      <th>delta</th>\n      <td>0.95</td>\n    </tr>\n    <tr>\n      <th>wage_fishing</th>\n      <th>exp_fishing</th>\n      <td>0.10</td>\n    </tr>\n    <tr>\n      <th>nonpec_fishing</th>\n      <th>constant</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">nonpec_hammock</th>\n      <th>constant</th>\n      <td>2.50</td>\n    </tr>\n    <tr>\n      <th>not_fishing_last_period</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">shocks_sdcorr</th>\n      <th>sd_fishing</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>sd_hammock</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>corr_hammock_fishing</th>\n      <td>-0.20</td>\n    </tr>\n    <tr>\n      <th>lagged_choice_1_hammock</th>\n      <th>constant</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>wage_fishing</th>\n      <th>age</th>\n      <td>-0.08</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nII. Edit ``options``\n\n\n```python\noptions_age = copy.deepcopy(options_basic)\noptions_age[\"covariates\"].update({\"age\": \"period + 16\"})\noptions_age\n```\n\n\n\n\n    {'n_periods': 10,\n     'simulation_agents': 1000,\n     'simulation_seed': 123,\n     'covariates': {'constant': '1',\n      'not_fishing_last_period': \"lagged_choice_1 != 'fishing'\",\n      'age': 'period + 16'}}\n\n\n\nIII. Simulate again\n\n\n```python\nsimulate = rp.get_simulate_func(params_age, options_age)\ndf_age = simulate(params_age)\n```\n\n$\\rightarrow$ **Result:** Including the negative effect of age reduces the proportion of individuals that choose fishing, increasingly so in later periods.\n\n\n```python\nplot_choice_shares(df_age)\n```\n\n<div class=\"alert alert-block alert-success\">\n    <u><h4>2.4.2. Extension: Adding Choices</h4></u>\n</div>\n\n- after some time on the island, Robinson meets Friday who can help him improve his fishing.\n\n- add the choice alternative `\"friday\"`\n\n    - affects the utility of fishing. \n    - choice should be available only once starting with the third period, and only after Robinson has been fishing before. \n\nI. Edit `params` (loaded from .csv)\n\n- `wage_fishing` now includes a return to contemplation with Friday.\n- There is a new category,`nonpec_friday`, which captures the non-pecuniary reward for of spending a period with Friday.\n- The shock shock variance-covariance matrix has been altered to include the additional option. \n\n\n\n```python\nparams_friday = pd.read_csv(\"params_files/robinson_crusoe_friday.csv\", index_col=[\"category\", \"name\"])\nparams_friday\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>value</th>\n    </tr>\n    <tr>\n      <th>category</th>\n      <th>name</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>delta</th>\n      <th>delta</th>\n      <td>0.95</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">wage_fishing</th>\n      <th>exp_fishing</th>\n      <td>0.10</td>\n    </tr>\n    <tr>\n      <th>contemplation_with_friday</th>\n      <td>0.40</td>\n    </tr>\n    <tr>\n      <th>nonpec_fishing</th>\n      <th>constant</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">nonpec_friday</th>\n      <th>constant</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th>not_fishing_last_period</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">nonpec_hammock</th>\n      <th>constant</th>\n      <td>2.50</td>\n    </tr>\n    <tr>\n      <th>not_fishing_last_period</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th rowspan=\"6\" valign=\"top\">shocks_sdcorr</th>\n      <th>sd_fishing</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>sd_friday</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>sd_hammock</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>corr_friday_fishing</th>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>corr_hammock_fishing</th>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>corr_hammock_friday</th>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>lagged_choice_1_hammock</th>\n      <th>constant</th>\n      <td>1.00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nII. Adjust `options`\n\n**Covariates**\n- new covariate `\"contemplation_with_friday\"` is only affecting utility if ..\n    - Robinson is experienced in fishing\n    - only for one interaction with Friday\n\n\n```python\noptions_friday = yaml.safe_load(open(\"option_files/options_friday.yml\"))\noptions_friday[\"covariates\"]\n```\n\n\n\n\n    {'constant': '1',\n     'contemplation_with_friday': 'exp_friday == 1 and exp_fishing >= 1',\n     'not_fishing_last_period': \"lagged_choice_1 != 'fishing'\"}\n\n\n\n**Negative choice set**\n- `\"negative_choice_set\"` can be used to restrict the choice Friday to the third and following periods\n\n\n```python\noptions_friday[\"negative_choice_set\"]\n```\n\n\n\n\n    {'friday': ['period < 2', 'exp_fishing == 0']}\n\n\n\nIII. Simulate\n\n\n```python\nsimulate = rp.get_simulate_func(params_friday, options_friday)\ndf_friday = simulate(params_friday)\nplot_choice_shares(df_friday, friday=True)\n```\n\n<div class=\"alert alert-block alert-success\">\n    <u><h4>2.4.3. Extension: Initial Experience</h4></u>\n</div>\n\n- example of initial conditions: characteristics individuals enter the model with\n\n\n- assume in period $t=0$, Robinson will have $0$, $1$, or $2$ periods of experience in fishing.\n\n\n- this introduces a source of heterogeneity between agents\n\nI. Edit `params`\n\n- specify the distribution of initial experience via **probability mass functions**\n\n- keyword is `\"initial_exp_fishing_*\"` in the *category*-level of the index, where the asterisk needs to be replaced with the experience level. \n\n- the *name*-level, use `\"probability\"` to signal that the float in `\"value\"` is a probability. \n\n- specification: Robinson has equal probability to start out with 0, 1 or 2 periods of experience.\n\n\n```python\nparams_initial_exp = params_basic.copy()\nparams_initial_exp.loc[ (\"initial_exp_fishing_0\", \"probability\"), \"value\"] = 0.33\nparams_initial_exp.loc[(\"initial_exp_fishing_1\", \"probability\"), \"value\"] = 0.33\nparams_initial_exp.loc[ (\"initial_exp_fishing_2\", \"probability\"), \"value\"] = 0.34\nparams_initial_exp\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>value</th>\n    </tr>\n    <tr>\n      <th>category</th>\n      <th>name</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>delta</th>\n      <th>delta</th>\n      <td>0.95</td>\n    </tr>\n    <tr>\n      <th>wage_fishing</th>\n      <th>exp_fishing</th>\n      <td>0.10</td>\n    </tr>\n    <tr>\n      <th>nonpec_fishing</th>\n      <th>constant</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">nonpec_hammock</th>\n      <th>constant</th>\n      <td>2.50</td>\n    </tr>\n    <tr>\n      <th>not_fishing_last_period</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">shocks_sdcorr</th>\n      <th>sd_fishing</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>sd_hammock</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>corr_hammock_fishing</th>\n      <td>-0.20</td>\n    </tr>\n    <tr>\n      <th>lagged_choice_1_hammock</th>\n      <th>constant</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>initial_exp_fishing_0</th>\n      <th>probability</th>\n      <td>0.33</td>\n    </tr>\n    <tr>\n      <th>initial_exp_fishing_1</th>\n      <th>probability</th>\n      <td>0.33</td>\n    </tr>\n    <tr>\n      <th>initial_exp_fishing_2</th>\n      <th>probability</th>\n      <td>0.34</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nII. Adjust `options`\n\n$\\rightarrow$ not necessary in this case!\n\nIII. Simulate\n\n\n```python\nsimulate = rp.get_simulate_func(params_initial_exp, options_basic)\ndf_exp = simulate(params_initial_exp)\n```\n\n\n```python\nplot_choice_prob_and_exp_level(df_basic)\nplot_choice_prob_and_exp_level(df_exp)\n```\n\nComparing the plots shows that the share of engagement in fishing increases compared to the baseline scenario, as two thirds of Robinsons land on the island with previous experience in fishing. \n\n<div class=\"alert alert-block alert-success\">\n    <u><h4>2.4.4. Extension: Observables</h4></u>\n</div>\n\n- add one observable characteristic to the baseline model, `\"fishing_grounds\"`\n\n\n- assume Robinson can end up, with a certain probability, on the side of the island which has `\"poor\"` or `\"rich\"` fishing grounds.\n\n\n- experiencing rich fishing grounds affects the **non-pecuniary reward** for fishing. \n\nI. Add three additional rows to `params`\n\n- The probability with which Robinson will find himself in rich and in poor fishing grounds.\n\n- The return for being in a rich fishing ground, which here is set to be positive and constant.\n\n\n```python\nparams_fish_ground = params_basic.copy()\nparams_fish_ground.loc[(\"observable_fishing_grounds_rich\", \"probability\"), \"value\"] = 0.5\nparams_fish_ground.loc[(\"observable_fishing_grounds_poor\", \"probability\"), \"value\"] = 0.5\nparams_fish_ground.loc[(\"nonpec_fishing\", \"rich_fishing_grounds\"), \"value\"] = 0.5\nparams_fish_ground\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>value</th>\n    </tr>\n    <tr>\n      <th>category</th>\n      <th>name</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>delta</th>\n      <th>delta</th>\n      <td>0.95</td>\n    </tr>\n    <tr>\n      <th>wage_fishing</th>\n      <th>exp_fishing</th>\n      <td>0.10</td>\n    </tr>\n    <tr>\n      <th>nonpec_fishing</th>\n      <th>constant</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">nonpec_hammock</th>\n      <th>constant</th>\n      <td>2.50</td>\n    </tr>\n    <tr>\n      <th>not_fishing_last_period</th>\n      <td>-1.00</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">shocks_sdcorr</th>\n      <th>sd_fishing</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>sd_hammock</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>corr_hammock_fishing</th>\n      <td>-0.20</td>\n    </tr>\n    <tr>\n      <th>lagged_choice_1_hammock</th>\n      <th>constant</th>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>observable_fishing_grounds_rich</th>\n      <th>probability</th>\n      <td>0.50</td>\n    </tr>\n    <tr>\n      <th>observable_fishing_grounds_poor</th>\n      <th>probability</th>\n      <td>0.50</td>\n    </tr>\n    <tr>\n      <th>nonpec_fishing</th>\n      <th>rich_fishing_grounds</th>\n      <td>0.50</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nII. Adjust covariates in `options`\n\n\n```python\noptions_fish_ground = options_basic.copy()\noptions_fish_ground[\"covariates\"] = {\n    \"constant\": \"1\",\n    \"not_fishing_last_period\": \"lagged_choice_1 != 'fishing'\",\n    \"rich_fishing_grounds\": \"fishing_grounds == 'rich'\",\n}\noptions_fish_ground\n```\n\n\n\n\n    {'n_periods': 10,\n     'simulation_agents': 1000,\n     'simulation_seed': 123,\n     'covariates': {'constant': '1',\n      'not_fishing_last_period': \"lagged_choice_1 != 'fishing'\",\n      'rich_fishing_grounds': \"fishing_grounds == 'rich'\"}}\n\n\n\nIII. Simulate again\n\n\n```python\nsimulate = rp.get_simulate_func(params_fish_ground, options_fish_ground)\ndf_fish_ground = simulate(params_fish_ground)\n```\n\nAs can be expected, Robinson engages in fishing more often if he is stranded on the side of the island with rich fishing grounds.\n\n\n```python\nplot_fishing_grounds(df_fish_ground)\n```\n\n ### Outline\n\n 1.  Package overview  \n 2.  Introductory tutorial  \n  2.1. Theoretical framework  \n  2.2. Specifying a model  \n  2.3. Simulating data  \n  2.4. Extending the model    \n 3. <span style=\"color:#2C68B9\">Pre-implemented example models</span>\n 4. Outlook\n\n<div class=\"alert alert-block alert-info\">\n    <u><h2>3. Pre-implemented example models</h2></u>\n</div>\n\n\n```python\nparams, options, data = rp.get_example_model(<model>)\n```\n\n### Toy models\n\n- based on the story of Robinson Crusoe\n\n- used in the [tutorials](https://respy.readthedocs.io/en/latest/tutorials/index.html) in the documentation\n\n**Models**\n\n- `robinson_crusoe_basic`\n\n- `robinson_crusoe_extended`\n\n\n**Advantages**\n\n- simple model structure\n- computationally feasible due to the small number of available choices and low number of periods in the models\n    \n$\\rightarrow$ useful of learning & teaching\n\n\n```python\n_, _, data = rp.get_example_model(\"robinson_crusoe_basic\")\nplot_choice_shares(data)\n_, _, data = rp.get_example_model(\"robinson_crusoe_extended\")\nplot_choice_shares(data, friday=True)\n```\n\n### Keane and Wolpin (1994)\n\n\n**Source**\n\n- Keane, M. P., & Wolpin, K. I. (1994). The Solution and Estimation of Discrete Choice Dynamic Programming Models by Simulation and Interpolation: Monte Carlo Evidence. *The Review of Economics and Statistics*, 648-672.\n\n**Characteristics**\n- four mutually exclusive alternatives that individuals can choose in each period (work in sectors `a` or `b`, invest in education, or stay home)\n- time horizon of 40 periods\n\n**Models**\n\n- `kw_94_one`\n- `kw_94_two`\n- `kw_94_three`\n\n\n```python\nplot_choices_kw(example=\"1994\")\n```\n\n### Keane and Wolpin (1997)\n\n**Source**\n\n* Keane, M. P., & Wolpin, K. I. (1997). The Career Decisions of Young Men. *Journal of Political Economy*, 105(3), 473-522.\n\n**Characteristics**\n\n* five mutually exclusive choice alternatives (occupations `white-collar`, `blue-collar`, `military`, school and staying home)\n* basic and extended model specification with unobserved heterogeneity, measurement error, and initial experience\n* time horizon of 50 periods\n* empirical model calibrated to a sample of white men in the National Longitudinal Survey of Youth (NLSY)\n\n**Models**\n\n- `kw_97_basic`\n\n- `kw_97_extended`\n\n\n\n```python\nplot_choices_kw(example=\"1997\")\n```\n\n### Keane and Wolpin (2000)\n\n**Source**\n\n- Keane, M. P., & Wolpin, K. I. (2000). Eliminating Race Differences in School Attainment and Labor Market Success. *Journal of Labor Economics*, 18(4), 614-652.\n\n**Model**\n\n- `kw_2000`\n\nThe model is very similar to the extended model specification in Keane and Wolpin (1997).\n\n ### Outline\n\n 1.  Package overview  \n 2.  Introductory tutorial  \n  2.1. Theoretical framework  \n  2.2. Specifying a model  \n  2.3. Simulating data  \n  2.4. Extending the model    \n 3. Pre-implemented example models\n 4. <span style=\"color:#2C68B9\">Outlook</span>\n\n<div class=\"alert alert-block alert-info\">    \n    <u><h2>4. Outlook</h2></u>\n</div>\n\n#### Recent advancements\n\n- Exogenous processes (childbirth, health shocks etc.)\n- Revision of the state space\n- State specific choice sets\n\n#### Potential\n- Consumption and saving decisions\n- Continuous choices or time\n\n### Related software projects\n\n- [`estimagic`](https://estimagic.readthedocs.io/en/latest/) is a Python package that provides high-quality and user-friendly tools to fit large scale empirical models to data and make inferences about the estimated model parameters. \n\n- [`ruspy`](https://ruspy.readthedocs.io/en/latest/) is an open-source Python package for the simulation and estimation of a prototypical infinite-horizon dynamic discrete choice model based on Rust (1987).\n\n- [`grmpy`](https://grmpy.readthedocs.io/en/latest/) is an open-source Python package for the simulation and estimation of the generalized Roy model.\n\n- [`econsa`](https://econsa.readthedocs.io/en/latest/) is an open-source Python package that facilitates uncertainty propagation and global sensitivity of computational economic models.analysis.\n\n- [`robupy`](https://robupy.readthedocs.io/en/latest/) is an open-source Python package for robust decision making.\n\n\n- [`gettsim`](https://gettsim.readthedocs.io/en/stable/) is an open-source Python package developed by OSE members providing a depiction of the German Taxes and Transfers System.\n \n\n<div class=\"alert alert-block alert-info\">    \n    <u><h2>Thank you!</h2></u>\n</div>\n\nMore information on OpenSourceEconomics software projects at https://open-econ.org.\n", "meta": {"hexsha": "05fcfbf9ac6354794ed5b496475321c0eff359b2", "size": 942168, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "respy-showcase-slides.ipynb", "max_stars_repo_name": "amageh/respy-tut", "max_stars_repo_head_hexsha": "115a8a3cf0069b03ee18c6eac70b0b9b1cba6857", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "respy-showcase-slides.ipynb", "max_issues_repo_name": "amageh/respy-tut", "max_issues_repo_head_hexsha": "115a8a3cf0069b03ee18c6eac70b0b9b1cba6857", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "respy-showcase-slides.ipynb", "max_forks_repo_name": "amageh/respy-tut", "max_forks_repo_head_hexsha": "115a8a3cf0069b03ee18c6eac70b0b9b1cba6857", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 343.8569343066, "max_line_length": 235024, "alphanum_fraction": 0.9245293833, "converted": true, "num_tokens": 10367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3557749071749625, "lm_q2_score": 0.08389037953940535, "lm_q1q2_score": 0.029846091993504315}}
{"text": "```python\n#remove cell visibility\nfrom IPython.display import HTML\ntag = HTML('''\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.''')\ndisplay(tag)\n```\n\n\n\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.\n\n\n\n```python\n%matplotlib inline\nimport control\nimport numpy\nimport sympy as sym\nfrom IPython.display import display, Markdown\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\n\n\n#print a matrix latex-like\ndef bmatrix(a):\n     \"\"\"Returns a LaTeX bmatrix - by Damir Arbula (ICCT project)\n\n     :a: numpy array\n     :returns: LaTeX bmatrix as a string\n     \"\"\"\n     if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n     lines = str(a).replace('[', '').replace(']', '').splitlines()\n     rv = [r'\\begin{bmatrix}']\n     rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n     rv +=  [r'\\end{bmatrix}']\n     return '\\n'.join(rv)\n\n\n# Display formatted matrix: \ndef vmatrix(a):\n    if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n    lines = str(a).replace('[', '').replace(']', '').splitlines()\n    rv = [r'\\begin{vmatrix}']\n    rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n    rv +=  [r'\\end{vmatrix}']\n    return '\\n'.join(rv)\n\n\n#matrixWidget is a matrix looking widget built with a VBox of HBox(es) that returns a numPy array as value !\nclass matrixWidget(widgets.VBox):\n    def updateM(self,change):\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.M_[irow,icol] = self.children[irow].children[icol].value\n                #print(self.M_[irow,icol])\n        self.value = self.M_\n\n    def dummychangecallback(self,change):\n        pass\n    \n    \n    def __init__(self,n,m):\n        self.n = n\n        self.m = m\n        self.M_ = numpy.matrix(numpy.zeros((self.n,self.m)))\n        self.value = self.M_\n        widgets.VBox.__init__(self,\n                             children = [\n                                 widgets.HBox(children = \n                                              [widgets.FloatText(value=0.0, layout=widgets.Layout(width='90px')) for i in range(m)]\n                                             ) \n                                 for j in range(n)\n                             ])\n        \n        #fill in widgets and tell interact to call updateM each time a children changes value\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        #value = Unicode('example@example.com', help=\"The email value.\").tag(sync=True)\n        self.observe(self.updateM, names='value', type= 'All')\n        \n    def setM(self, newM):\n        #disable callbacks, change values, and reenable\n        self.unobserve(self.updateM, names='value', type= 'All')\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].unobserve(self.updateM, names='value')\n        self.M_ = newM\n        self.value = self.M_\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        self.observe(self.updateM, names='value', type= 'All')        \n\n                #self.children[irow].children[icol].observe(self.updateM, names='value')\n\n             \n#overlaod class for state space systems that DO NOT remove \"useless\" states (what \"professor\" of automatic control would do this?)\nclass sss(control.StateSpace):\n    def __init__(self,*args):\n        #call base class init constructor\n        control.StateSpace.__init__(self,*args)\n    #disable function below in base class\n    def _remove_useless_states(self):\n        pass\n```\n\n## Controllo della testina di un Hard-Disk\n\n\n\nIl braccio degli Hard-Disk che sostiene la testina di lettura ruota su un cuscinetto viscoso ed \u00e8 alimentato da un motore elettrico; una molla di richiamo con rigidit\u00e0 torsionale $k$ si oppone al suo movimento. Il cuscinetto possiede un leggero attrito viscoso, proporzionale alla velocit\u00e0 di rotazione del braccio della testa, con $b$ costante. L'attuatore del braccio \u00e8 in grado di generare una coppia $T$ linearmente proporzionale alla corrente $I$ che scorre all'interno della bobina di attuazione: $T = k_iI$. L'inerzia del braccio \u00e8 $J$. Un sensore misura la posizione angolare del braccio $\\theta$.\n\nLe costanti del sistema sono:\n- $J = 0.001$ kg$\\text{m}^2$,\n- $k_i = 500$ Nm/A,\n- $k = 1$ Nm/rad,\n- $b = 0.04$ Nm/(rad/s).\n\nL'obiettivo \u00e8 progettare un regolatore per la posizione del braccio secondo le seguenti specifiche:\n- zero overshoot,\n- tempo di assestamento al 2% inferiore a 50 millisecondi,\n- errore di regime in risposta a un cambiamento a gradino della posizione del braccio desiderata,\n- la corrente di ingresso non deve superare i 5 A in risposta a un gradino di ingresso di 30 gradi.\n\nL'equazione del sistema \u00e8:\n$$\nJ\\ddot{\\theta} = k_iI - b\\dot{\\theta} - k\\theta\n$$\n\nDefinendo il vettore di stato come $x=\\begin{bmatrix}x_1 & x_2\\end{bmatrix}^T=\\begin{bmatrix}\\theta & \\dot{\\theta}\\end{bmatrix}^T$ e $u=I$, l'equazione del sistema in forma matriciale diventa:\n\n\\begin{cases}\n\\dot{x} = \\begin{bmatrix} 0 & 1 \\\\ -k & -b \\end{bmatrix}x + \\begin{bmatrix} 0 \\\\ k_i \\end{bmatrix}u \\\\\ny = \\begin{bmatrix} 1 & 0 \\end{bmatrix}x\n\\end{cases}\n\nPer ottenere un errore di regime pari a zero, si aumenta l'impianto con un nuovo stato definito come $\\dot{x_3}=y-y_d=x_1-y_d$. Le equazioni diventano quindi:\n\n\\begin{cases}\n\\dot{x_a} = \\begin{bmatrix} 0 & 1 & 0 \\\\ -k & -b & 0 \\\\ 1 & 0 & 0 \\end{bmatrix}x_a + \\begin{bmatrix} 0 & 0 \\\\ k_i & 0 \\\\ 0 & -1 \\end{bmatrix}\\begin{bmatrix} u \\\\ y_d \\end{bmatrix} \\\\\ny = \\begin{bmatrix} 1 & 0 & 0 \\\\ 0 & 0 & 1 \\end{bmatrix}x\n\\end{cases}\n\nLa matrice di controllabilit\u00e0 $\\mathcal{C}$, considerando solo l'input $u$, \u00e8\n\n\n```python\nA = numpy.matrix('0 1 0; -1 -0.04 0; 1 0 0')\nB = numpy.matrix('0 0; 500 0; 0 -1')\nC = numpy.matrix('1 0 0; 0 0 1')\nD = numpy.matrix('0 0; 0 0')\n\nCM = control.ctrb(A,B[:,0])\ndisplay(Markdown(bmatrix(CM)))\n# print(numpy.linalg.matrix_rank(CM))\n```\n\n\n\\begin{bmatrix}\n  0. & 500. & -20.\\\\\n  500. & -20. & -499.2\\\\\n  0. & 0. & 500.\\\\\n\\end{bmatrix}\n\n\ne ha rango pari a 3 quindi il sistema \u00e8 controllabile.\nLa matrice di osservabilit\u00e0 $\\mathcal{O}$ \u00e8\n\n\n```python\nOM = control.obsv(A,C)\ndisplay(Markdown(bmatrix(OM)))\n# print(numpy.linalg.matrix_rank(OM))\n```\n\n\n\\begin{bmatrix}\n  1. & 0. & 0.\\\\\n  0. & 0. & 1.\\\\\n  0. & 1. & 0.\\\\\n  1. & 0. & 0.\\\\\n  -1. & -0.04 & 0.\\\\\n  0. & 1. & 0.\\\\\n\\end{bmatrix}\n\n\ne ha rango pari a 3 quindi il sistema \u00e8 osservabile.\n\n### Design del regolatore\n#### Design del controller\n\nSi progetta il guadagno del feedback dello stato considerando solo l'input $u$ mentre per il riferimento si utilizza $y_d$. Le specifiche del transitorio possono essere rispettate se i poli dominanti ad anello chiuso sono posti in $-100.02\\pm101i$ e imponendo che il terzo polo sia almeno simile in quanto a rapidit\u00e0, come ad esempio in $-100$. Ci\u00f2 si ottiene con la matrice del guadagno:\n$$\nK = \\begin{bmatrix} 80.416 & 0.6 & 4041.0 \\end{bmatrix}.\n$$\n\n#### Design dell'osservatore\nPer avere una buona stima dello stato e, quindi, una rapida convergenza a zero dell'errore di stima, si posizionano i poli dell'osservatore in $-151$, $-152$ e $-153$ (pi\u00f9 veloci dei poli del sistema controllato).\nLa matrice di guadagno dell'osservatore che ne risulta \u00e8:\n$$\nL = \\begin{bmatrix} 300.96 & 3.028e-12 \\\\\n 2.264e+04 & 4.55e-10 \\\\\n 1.0 & 150.0 \\end{bmatrix}.\n$$\n\nLe simulazioni sono mostrate di seguito. Si noti che aumentando il vettore di stato si assicura che il guadagno ad anello chiuso sia sempre 1.\n\n### Come utilizzare questo notebook?\n- Cerca di migliorare la risposta nel caso di un piccolo errore iniziale (circa 0,05) nei primi due elementi della condizione iniziale dell'osservatore (parametro X0 stim. Sotto).\n- **N.B.** Introdurre un errore iniziale nella terza componente dello stato stimato ha poco senso poich\u00e9 il terzo stato ha la dinamica esatta definita. Si sarebbe anche potuto sviluppare un osservatore solo per $x_2$ poich\u00e9 si misura $x_1$ e si conosce $x_3$.\n\n\n```python\n# Preparatory cell\n\nX0 = numpy.matrix('0.0; 0.0; 0.0')\nK = numpy.matrix([8/15,-4.4,-4])\nL = numpy.matrix([[300, 3.028E-12],[2.264E+04, 4.55E-10],[1, 150]])\n\nAw = matrixWidget(3,3)\nAw.setM(A)\nBw = matrixWidget(3,1)\nBw.setM(B)\nCw = matrixWidget(1,3)\nCw.setM(C)\nX0w = matrixWidget(3,1)\nX0w.setM(X0)\nKw = matrixWidget(1,3)\nKw.setM(K)\nLw = matrixWidget(3,2)\nLw.setM(L)\n\n\neig1c = matrixWidget(1,1)\neig2c = matrixWidget(2,1)\neig3c = matrixWidget(1,1)\neig1c.setM(numpy.matrix([-100.])) \neig2c.setM(numpy.matrix([[-100.02],[-101.]]))\neig3c.setM(numpy.matrix([-100.]))\n\neig1o = matrixWidget(1,1)\neig2o = matrixWidget(2,1)\neig3o = matrixWidget(1,1)\neig1o.setM(numpy.matrix([-150.])) \neig2o.setM(numpy.matrix([[-151.],[0.]]))\neig3o.setM(numpy.matrix([-152.]))\n```\n\n\n```python\n# Misc\n\n#create dummy widget \nDW = widgets.FloatText(layout=widgets.Layout(width='0px', height='0px'))\n\n#create button widget\nSTART = widgets.Button(\n    description='Test',\n    disabled=False,\n    button_style='', # 'success', 'info', 'warning', 'danger' or ''\n    tooltip='Test',\n    icon='check'\n)\n                       \ndef on_start_button_clicked(b):\n    #This is a workaround to have intreactive_output call the callback:\n    #   force the value of the dummy widget to change\n    if DW.value> 0 :\n        DW.value = -1\n    else: \n        DW.value = 1\n    pass\nSTART.on_click(on_start_button_clicked)\n\n# Define type of method \nselm = widgets.Dropdown(\n    options= [('Imposta K e L','Set K and L'), ('Imposta gli autovalori','Set the eigenvalues')],\n    value= 'Set the eigenvalues',\n    description='',\n    disabled=False\n)\n\n# Define the number of complex eigenvalues\nsele = widgets.Dropdown(\n    options= [('0 autovalori complessi','0 complex eigenvalues'), ('2 autovalori complessi','2 complex eigenvalues')],\n    value= '2 complex eigenvalues',\n    description='Autovalori complessi:',\n    style = {'description_width': 'initial'},\n    disabled=False\n)\n\n#define type of ipout \nselu = widgets.Dropdown(\n    options=[('impulso','impulse'), ('gradino','step'), ('sinusoide','sinusoid'), ('onda quadra','square wave')],\n    value='step',\n    description='Riferimento:',\n    style = {'description_width': 'initial'},\n    disabled=False\n)\n# Define the values of the input\nu = widgets.FloatSlider(\n    value=30*numpy.pi/180,\n    min=0,\n    max=45*numpy.pi/180,\n    step=0.05,\n    description='Riferimento:',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.1f',\n)\nperiod = widgets.FloatSlider(\n    value=0.5,\n    min=0.001,\n    max=10,\n    step=0.001,\n    description='Periodo: ',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.2f',\n)\n\ngain_w2 = widgets.FloatText(\n    value=1.,\n#     description='',\n    description='Guadagno inverso del riferimento:',\n    style = {'description_width': 'initial'},\n    disabled=True\n)\n\nsimTime = widgets.FloatText(\n    value=0.5,\n    description='Tempo di simulazione (s):',\n    style = {'description_width': 'initial'},\n    disabled=False\n)\n```\n\n\n```python\n# Support functions\n\ndef eigen_choice(sele):\n    if sele == '0 complex eigenvalues':\n        eig1c.children[0].children[0].disabled = False\n        eig2c.children[1].children[0].disabled = True\n        eig1o.children[0].children[0].disabled = False\n        eig2o.children[1].children[0].disabled = True\n        eig = 0\n    if sele == '2 complex eigenvalues':\n        eig1c.children[0].children[0].disabled = True\n        eig2c.children[1].children[0].disabled = False\n        eig1o.children[0].children[0].disabled = True\n        eig2o.children[1].children[0].disabled = False\n        eig = 2\n    return eig\n\ndef method_choice(selm):\n    if selm == 'Set K and L':\n        method = 1\n        sele.disabled = True\n    if selm == 'Set the eigenvalues':\n        method = 2\n        sele.disabled = False\n    return method\n```\n\n\n```python\nnumU = 1\n\ndef main_callback2(Aw, Bw, X0w, K, L, eig1c, eig2c, eig3c, eig1o, eig2o, eig3o, u, period, selm, sele, selu, simTime, DW):\n    eige = eigen_choice(sele)\n    method = method_choice(selm)\n    \n    if method == 1:\n        solc = numpy.linalg.eig(A-B[:,0:numU]*K)\n        solo = numpy.linalg.eig(A-L*C)\n    if method == 2:\n        if eige == 0:\n            K = control.acker(A, B[:,0:numU], [eig1c[0,0], eig2c[0,0], eig3c[0,0]])\n            Kw.setM(K)\n            L = control.place(A.T, C.T, [eig1o[0,0], eig2o[0,0], eig3o[0,0]]).T\n            Lw.setM(L)\n        if eige == 2:\n            K = control.acker(A, B[:,0:numU], [eig3c[0,0], \n                                     numpy.complex(eig2c[0,0],eig2c[1,0]), \n                                     numpy.complex(eig2c[0,0],-eig2c[1,0])])\n            Kw.setM(K)\n            L = control.place(A.T, C.T, [eig3o[0,0], \n                                         numpy.complex(eig2o[0,0],eig2o[1,0]), \n                                         numpy.complex(eig2o[0,0],-eig2o[1,0])]).T\n            Lw.setM(L)\n            \n    \n    sys = control.ss(A,B,numpy.vstack((C,numpy.zeros((B.shape[1],C.shape[1])))),numpy.vstack((D,numpy.eye(B.shape[1]))))\n    sysC = control.ss(numpy.zeros((1,1)),\n                      numpy.zeros((1,numpy.shape(A)[0])),\n                      numpy.zeros((numpy.shape(B[:,0:numU])[1],1)),\n                      -K)\n    \n    sysE = control.ss(A-L*C,\n                      numpy.hstack((L,B-L*D)),\n                      numpy.eye(numpy.shape(A)[0]),\n                      numpy.zeros((A.shape[0],C.shape[0]+B.shape[1])))\n    \n    sys_append = control.append(sys, sysE, sysC, control.ss(A,B,numpy.eye(A.shape[0]),numpy.zeros((A.shape[0],B.shape[1]))))\n    Q = []\n    # y in ingresso a sysE\n    for i in range(C.shape[0]):\n        Q.append([B.shape[1]+i+1, i+1])\n    # u in ingresso a sysE\n    for i in range(B.shape[1]):\n        Q.append([B.shape[1]+C.shape[0]+i+1, C.shape[0]+i+1])\n    # u in ingresso a sys\n    for i in range(B[:,0:numU].shape[1]):\n        Q.append([i+1, C.shape[0]+B.shape[1]+A.shape[0]+i+1])\n    # u in ingresso al sistema che ha come uscite gli stati reali\n    for i in range(B.shape[1]):\n        Q.append([2*B.shape[1]+C.shape[0]+A.shape[0]+i+1, C.shape[0]+i+1])\n    # xe in ingresso a sysC\n    for i in range(A.shape[0]):\n        Q.append([2*B.shape[1]+C.shape[0]+i+1, C.shape[0]+B.shape[1]+i+1])\n        \n    inputv = [i+numU+1 for i in range(B[:,numU:].shape[1])]\n    outputv = [i+1 for i in range(numpy.shape(sys_append.C)[0])]\n    # in order to avoid singular value exception\n    try:\n        sys_CL = control.connect(sys_append, Q, inputv, outputv)\n    except:\n        sys_CL = control.connect(sys_append, Q, inputv, outputv)\n    \n    dcgain = control.dcgain(sys_CL[0,0])\n    gain_w2.value = dcgain\n    if dcgain != 0:\n        u1 = u/gain_w2.value\n    else:\n        print('Il guadagno impostato per il riferimento \u00e8 0 e quindi viene cambiato a 1')\n        u1 = u/1\n    print('Il guadagno statico del sistema in anello chiuso (dal riferimento all\\'uscita) \u00e8: %.5f' %dcgain)\n    \n    X0w1 = numpy.zeros((A.shape[0],1))\n    for j in range(A.shape[0]):\n        X0w1 = numpy.vstack((X0w1,X0w[j]))\n    X0w1 = numpy.vstack((X0w1,numpy.zeros((A.shape[0],1))))\n    if simTime != 0:\n        T = numpy.linspace(0, simTime, 10000)\n    else:\n        T = numpy.linspace(0, 1, 10000)\n      \n    if selu == 'impulse': #selu\n        U = [0 for t in range(0,len(T))]\n        U[0] = u\n        U1 = [0 for t in range(0,len(T))]\n        U1[0] = u1\n        T, yout, xout = control.forced_response(sys_CL[:,0],T,U1,X0w1)\n    if selu == 'step':\n        U = [u for t in range(0,len(T))]\n        U1 = [u1 for t in range(0,len(T))]\n        T, yout, xout = control.forced_response(sys_CL[:,0],T,U1,X0w1)\n    if selu == 'sinusoid':\n        U = u*numpy.sin(2*numpy.pi/period*T)\n        U1 = u1*numpy.sin(2*numpy.pi/period*T)\n        T, yout, xout = control.forced_response(sys_CL[:,0],T,U1,X0w1)\n    if selu == 'square wave':\n        U = u*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n        U1 = u1*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n        T, yout, xout = control.forced_response(sys_CL[:,0],T,U1,X0w1)\n    # N.B. i primi 3 stati di xout sono quelli del sistema, mentre gli ultimi 3 sono quelli dell'osservatore\n    \n    step_info_dict = control.step_info(sys_CL[0,0],SettlingTimeThreshold=0.02,T=T)\n    print('Step info: \\n\\tTempo di salita =',step_info_dict['RiseTime'],'\\n\\tTempo di assestamento (2%) =',step_info_dict['SettlingTime'],'\\n\\tOvershoot (%)=',step_info_dict['Overshoot'])\n    print('Massimo valore di U (% di 5A)=', max(abs(yout[C.shape[0]]))/(5)*100)\n    \n    fig = plt.figure(num='Simulation1', figsize=(14,12))\n    \n    fig.add_subplot(221)\n    plt.title('Risposta dell\\'uscita')\n    plt.ylabel('Uscita')\n    plt.plot(T,yout[0],T,U,'r--')\n    plt.xlabel('$t$ [s]')\n    plt.legend(['$y$','Riferimento'])\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(222)\n    plt.title('Ingresso')\n    plt.ylabel('$u$')\n    plt.plot(T,yout[C.shape[0]],T,[5 for i in range(len(T))],'r--')\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(223)\n    plt.title('Risposta degli stati')\n    plt.ylabel('Stati')\n    plt.plot(T,yout[C.shape[0]+B.shape[1]+B[:,numU:].shape[1]+A.shape[0]],\n             T,yout[C.shape[0]+B.shape[1]+B[:,numU:].shape[1]+A.shape[0]+1],\n             T,yout[C.shape[0]+B.shape[1]+B[:,numU:].shape[1]+A.shape[0]+2])\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$x_{1}$','$x_{2}$','$x_{3}$'])\n    plt.grid()\n    \n    fig.add_subplot(224)\n    plt.title('Errori di stima')\n    plt.ylabel('Errori')\n    plt.plot(T,yout[C.shape[0]+B.shape[1]+B[:,numU:].shape[1]+A.shape[0]]-yout[C.shape[0]+B.shape[1]],\n             T,yout[C.shape[0]+B.shape[1]+B[:,numU:].shape[1]+A.shape[0]+1]-yout[C.shape[0]+B.shape[1]+1],\n             T,yout[C.shape[0]+B.shape[1]+B[:,numU:].shape[1]+A.shape[0]+2]-yout[C.shape[0]+B.shape[1]+2])\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$e_{1}$','$e_{2}$','$e_{3}$'])\n    plt.grid()\n    #plt.tight_layout()\n   \nalltogether2 = widgets.VBox([widgets.HBox([selm, \n                                          sele,\n                                          selu]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.Label('K:',border=3), Kw, \n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Autovalori:',border=3), \n                                          eig1c, \n                                          eig2c, \n                                          eig3c,\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('X0 stim.:',border=3), X0w]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.Label('L:',border=3), Lw, \n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Autovalori:',border=3), \n                                          eig1o, \n                                          eig2o, \n                                          eig3o,\n                                          widgets.Label(' ',border=3)]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([\n#                                 widgets.VBox([widgets.Label('Inverse reference gain:',border=3),\n#                                 widgets.Label('Simulation time [s]:',border=3)]),\n                            widgets.VBox([gain_w2,simTime])]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([u, \n                                          period, \n                                          START])])\nout2 = widgets.interactive_output(main_callback2, {'Aw':Aw, 'Bw':Bw, 'X0w':X0w, 'K':Kw, 'L':Lw,\n                                                 'eig1c':eig1c, 'eig2c':eig2c, 'eig3c':eig3c, 'eig1o':eig1o, 'eig2o':eig2o, 'eig3o':eig3o, \n                                                 'u':u, 'period':period, 'selm':selm, 'sele':sele, 'selu':selu, 'simTime':simTime, 'DW':DW})\nout2.layout.height = '870px'\ndisplay(out2, alltogether2)\n```\n\n\n    Output(layout=Layout(height='870px'))\n\n\n\n    VBox(children=(HBox(children=(Dropdown(index=1, options=(('Imposta K e L', 'Set K and L'), ('Imposta gli autov\u2026\n\n", "meta": {"hexsha": "edd08ead7b1605c7f2327624f8eeca25f2a2d58d", "size": 30085, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_it/examples/04/.ipynb_checkpoints/SS-43-Controllo_della_testina_di_un_Hard-Disk-checkpoint.ipynb", "max_stars_repo_name": "ICCTerasmus/ICCT", "max_stars_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-22T18:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:10:22.000Z", "max_issues_repo_path": "ICCT_it/examples/04/.ipynb_checkpoints/SS-43-Controllo_della_testina_di_un_Hard-Disk-checkpoint.ipynb", "max_issues_repo_name": "ICCTerasmus/ICCT", "max_issues_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICCT_it/examples/04/.ipynb_checkpoints/SS-43-Controllo_della_testina_di_un_Hard-Disk-checkpoint.ipynb", "max_forks_repo_name": "ICCTerasmus/ICCT", "max_forks_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-24T11:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T16:36:18.000Z", "avg_line_length": 40.2744310576, "max_line_length": 615, "alphanum_fraction": 0.4869868705, "converted": true, "num_tokens": 6546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2909808539178129, "lm_q2_score": 0.10230470310290449, "lm_q1q2_score": 0.029768709868691474}}
{"text": "```python\nfrom IPython.core.display import HTML\nfrom IPython.display import Image\nHTML(\"\"\"\n<style>\n.output_png {\n    display: table-cell;\n    text-align: center;\n    vertical-align: middle;\n}\n</style>\n\"\"\")\n```\n\n\n\n\n\n<style>\n.output_png {\n    display: table-cell;\n    text-align: center;\n    vertical-align: middle;\n}\n</style>\n\n\n\n\n# *Circuitos El\u00e9tricos I - Semana 8*\n\n# Circuitos de segunda ordem\n\n## Circuito RLC em paralelo\n\n\n\n### Aplica\u00e7\u00e3o das Leis de Kirchhoff \n\n$$\\begin{align}\n   i_R + i_L + i_C &= i_s\\\\\n   \\frac{v}{R} + i_L + C\\frac{d v}{d t} &= i_s\\nonumber\\\\\n    \\frac{1}{R}\\left[L\\frac{d i_L}{d t}\\right] + i_L + C \\frac{d}{d t}\\left[L\\frac{d i_L}{d t}\\right]  &= i_s\\nonumber\\\\\n    \\frac{d^{2} i_L}{d t^{2}}+\\frac{1}{RC} \\frac{d i_L}{d t}+\\frac{1}{L C} i_L &=\\frac{i_s}{LC}\n   \\end{align}\n$$\n\ncom $\\alpha = \\frac{1}{2RC}$ e $\\omega_0 = \\frac{1}{\\sqrt{LC}}$, temos\n\n$$ \n\\begin{equation}\\label{EDO1} \n\\frac{d^{2} i_L}{d t^{2}}+2\\alpha \\frac{d i_L}{d t}+\\omega_0^2 i_L=i_{\\mathrm{s}}\\omega_0^2 \n\\end{equation} \n$$\n\nA equa\u00e7\u00e3o \\ref{EDO1} \u00e9 uma EDO de segunda ordem, linear e de coeficientes constantes.\n\nEqua\u00e7\u00e3o caracter\u00edstica:\n\n$$\\begin{equation} s^2+2\\alpha s + \\omega_0^2=0 \\end{equation} $$\n\nRa\u00edzes da equa\u00e7\u00e3o caracter\u00edstica:\n\n$$\n\\begin{align}\ns_1 &=-\\alpha +\\sqrt{\\alpha^2-\\omega_0^2}\\\\\ns_2 &=-\\alpha -\\sqrt{\\alpha^2-\\omega_0^2}\n\\end{align}\n$$\n\n### Resposta total \n\nA resposta transiente de circuitos RLC em paralelo, seja ela natural ($i_L(\\infty)=0$) ou ao degrau ($i_L(\\infty)=i_s$), pode ser classificada nas tr\u00eas casos seguintes. Em todos os casos, assume-se que o transiente teve in\u00edcio no instante $t_0$ (instante do chaveamento).\n\n#### Caso superamortecido ($\\alpha>\\omega_0\\Rightarrow \\text{ra\u00edzes reais e distintas}$):\n\nSolu\u00e7\u00e3o geral da EDO:\n\n$$ \\begin{equation} i_L(t) =A_{1} e^{s_{1} (t-t_0)}+A_{2} e^{s_{2} (t-t_0)}+i_L(\\infty) \\end{equation}$$\n\nCondi\u00e7\u00f5es iniciais para $i_L(t)$:\n\n$$\n\\begin{align}\ni_L(t_0^+) &=A_1 + A_2 + i_L(\\infty)\\\\\n\\frac{di_L(t_0^+)}{dt} &=s_1A_1 + s_2A_2 = \\frac{1}{L} v_C(t_0^+)\n\\end{align}\n$$\n\nSolu\u00e7\u00e3o do sistema em $A_1$ e $A_2$:\n\n$$\n\\begin{align}\nA_{1} &=\\frac{\\frac{1}{L} v_C(t_0^+)-s_{2}\\left[i_L(t_0^+)-i_L(\\infty)\\right]}{s_{1}-s_{2}} \\\\\nA_{2} &=\\frac{-\\frac{1}{L} v_C(t_0^+)+s_{1}\\left[i_L(t_0^+)-i_L(\\infty)\\right]}{s_{1}-s_{2}}\n\\end{align}\n$$\n\n#### Caso subamortecido ($ \\alpha<\\omega_0\\Rightarrow\\text{ra\u00edzes complexas e conjugadas} $):\n\nFazendo $\\omega_d = \\sqrt{\\omega_0^2-\\alpha^2}$ temos $s_1 = -\\alpha +j\\omega_d$ e $s_2 = -\\alpha -j\\omega_d$.\n\nSolu\u00e7\u00e3o geral da EDO:\n\n$$\\begin{equation} i_L(t) = e^{-\\alpha(t-t_0)}\\left\\lbrace B_{1}\\cos[\\omega_d (t-t_0)] + B_{2}\\sin[\\omega_d (t-t_0)]  \\right\\rbrace + i_L(\\infty) \\end{equation}$$\n\nCondi\u00e7\u00f5es iniciais para $i_L(t)$:\n\n$$\n\\begin{align}\ni_L(t_0^+) &=B_1 + i_L(\\infty)\\\\\n\\frac{di_L(t_0^+)}{dt} &= -\\alpha B_1 +\\omega_d B_2 = \\frac{1}{L} v_C(t_0^+)\n\\end{align}\n$$\n\nSolu\u00e7\u00e3o do sistema em $B_1$ e $B_2$:\n\n$$\n\\begin{align}\nB_{1} &=i_L(t_0^+)-i_L(\\infty) \\\\\nB_{2} &=\\frac{\\frac{1}{L} v_C(t_0^+)+\\alpha\\left[i_L(t_0^+)-i_L(\\infty)\\right]}{\\omega_d}\n\\end{align}\n$$\n\n#### Caso criticamente amortecido ($\\alpha=\\omega_0\\Rightarrow \\text{ra\u00edzes reais e id\u00eanticas } s_1=s_2=-\\alpha$):\n\nSolu\u00e7\u00e3o geral da EDO:\n\n$$ \\begin{equation} i_L(t) =D_{1} e^{-\\alpha(t-t_0)}+D_{2}(t-t_0) e^{-\\alpha(t-t_0)}+i_L(\\infty) \\end{equation}$$\n\nCondi\u00e7\u00f5es iniciais para $i_L(t)$:\n\n$$\n\\begin{align}\ni_L(t_0^+) &=D_1 + i_L(\\infty)\\\\\n\\frac{di_L(t_0^+)}{dt} &=-\\alpha D_1 + D_2 = \\frac{1}{L} v_C(t_0^+)\n\\end{align}\n$$\n\nSolu\u00e7\u00e3o do sistema em $D_1$ e $D_2$:\n\n$$\n\\begin{align}\nD_{1} &=i_L(t_0^+)-i_L(\\infty) \\\\\nD_{2} &= \\frac{1}{L} v_C(t_0^+)+\\alpha\\left[i_L(t_0^+)-i_L(\\infty)\\right]\n\\end{align}\n$$\n\n### Problema 1\n\nPara o circuito a seguir, as chaves $ch1$ e $ch2$ estiveram abertas por um longo intervalo de tempo. \n\n\n\n\na. Considerando que apenas $ch1$ fecha em $t_0=0$s, determine a tens\u00e3o sobre o capacitor $v_C(t)$ para $t\\geq 0^+$.\\\nb. Qual o m\u00e1ximo valor (absoluto) atingido pela tens\u00e3o aplicada aos terminais do capacitor para $t\\geq 0^+$? Em que instante ele ocorre?\\\nc. Considerando que apenas $ch2$ fecha em $t_0=0$s, determine a tens\u00e3o sobre o capacitor $v_C(t)$ para $t\\geq 0^+$.\n\nLink para a simula\u00e7\u00e3o do circuito: https://tinyurl.com/yf8pj57t\n\n\n```python\nimport numpy as np\nimport sympy as sp\nfrom utils import round_expr, symdisp, symplot\n```\n\n\n```python\nhelp(symdisp)\n```\n\n    Help on function symdisp in module utils:\n    \n    symdisp(expr, var, unit=' ')\n        Latex style display of sympy expressions\n        \n        :param expr: expression in latex [string]\n        :param var: sympy variable, function, expression.\n        :param unit: string indicating unit of var [string]\n    \n\n\n### Resolvendo o problema com o c\u00f3digo em Python\n\n**Resolu\u00e7\u00e3o item (a):**\n\n**Calcula $\\alpha$ e $\\omega_0$**\n\n\n```python\n# Par\u00e2metros do circuito:\nR = 1.64\nL = 6e-3\nC = 0.5e-3\n\n# calculando \u03b1 e \u03c90\n\u03b1  = 1/(2*R*C)\n\u03c90 = 1/np.sqrt(L*C)\n\nsymdisp('\u03b1 =', round(\u03b1, 2), ' rad/s')\nsymdisp('\u03c9_0 =', round(\u03c90, 2), ' rad/s')\n```\n\n\n$\\displaystyle \u03b1 =609.76\\; rad/s$\n\n\n\n$\\displaystyle \u03c9_0 =577.35\\; rad/s$\n\n\n**Define os valores iniciais $v_c(t_0^+)$ e $i_L(t_0^+)$ e o valor final $i_L(\\infty)$ (obtidos da an\u00e1lise do circuito)**\n\n\n```python\n# informa\u00e7\u00f5es obtidas pela an\u00e1lise do circuito\n\nt0 = 0 # instante do chaveamento\n\niL_inf = -4 # valor final da corrente no indutor\niL_t0 = 2   # valor inicial da corrente no indutor\nvc_t0 = 0   # valor inicial da tens\u00e3o no capcitor\n```\n\n**Calcula as ra\u00edzes da equa\u00e7\u00e3o caracter\u00edstica $s_1$ e $s_2$**\n\n\n```python\n# ra\u00edzes da equa\u00e7\u00e3o caracter\u00edstica\ns1 = -\u03b1 + np.sqrt(\u03b1**2-\u03c90**2)\ns2 = -\u03b1 - np.sqrt(\u03b1**2-\u03c90**2)\n\nprint('Ra\u00edzes da equa\u00e7\u00e3o caracter\u00edstica:')\nsymdisp('s_1 =', round(s1, 2), ' rad/s')\nsymdisp('s_2 =', round(s2, 2), ' rad/s')\n\n# define vari\u00e1veis da solu\u00e7\u00e3o geral\nt, A1, A2 = sp.symbols('t, A1, A2')\n\n# express\u00e3o geral da resposta superamortecida\niL = A1*sp.exp(s1*(t-t0)) + A2*sp.exp(s2*(t-t0)) + iL_inf\n\nprint('Forma geral da solu\u00e7\u00e3o:')\nsymdisp('i_L(t) = ', round_expr(iL,2), 'A')\n```\n\n    Ra\u00edzes da equa\u00e7\u00e3o caracter\u00edstica:\n\n\n\n$\\displaystyle s_1 =-413.62\\; rad/s$\n\n\n\n$\\displaystyle s_2 =-805.89\\; rad/s$\n\n\n    Forma geral da solu\u00e7\u00e3o:\n\n\n\n$\\displaystyle i_L(t) = A_{1} e^{- 413.62 t} + A_{2} e^{- 805.89 t} - 4\\;A$\n\n\n**Resolve o sistema de equa\u00e7\u00f5es para determina\u00e7\u00e3o das constantes $A_1$ e $A_2$**\n\n\n```python\n# define os sistema de equa\u00e7\u00f5es com as condi\u00e7\u00f5es iniciais\neq1 = sp.Eq(   A1 +    A2 + iL_inf, iL_t0)             \neq2 = sp.Eq(s1*A1 + s2*A2,        vc_t0/L)  \n\nprint('Sistema de equa\u00e7\u00f5es:')\nsymdisp('(I): ', round_expr(eq1, 2),' ')\nsymdisp('(II): ', round_expr(eq2, 2),' ')\n```\n\n    Sistema de equa\u00e7\u00f5es:\n\n\n\n$\\displaystyle (I): A_{1} + A_{2} - 4 = 2\\; $\n\n\n\n$\\displaystyle (II): - 413.62 A_{1} - 805.89 A_{2} = 0.0\\; $\n\n\n\n```python\n# resolve o sistema\nsoluc = sp.solve((eq1, eq2), dict=True)\nA1 = np.array([sol[A1] for sol in soluc])\nA2 = np.array([sol[A2] for sol in soluc])\n\nA1 = A1[0]\nA2 = A2[0]\n\nprint('Solu\u00e7\u00e3o do sistema:')\nsymdisp('A_1 =', round(A1, 2), ' A')\nsymdisp('A_2 =', round(A2, 2), ' A')\n```\n\n    Solu\u00e7\u00e3o do sistema:\n\n\n\n$\\displaystyle A_1 =12.33\\; A$\n\n\n\n$\\displaystyle A_2 =-6.33\\; A$\n\n\n**Determina a express\u00e3o final para $i_L(t)$**\n\n\n```python\n# express\u00e3o geral da resposta subamortecida\niL = A1*sp.exp(s1*(t-t0)) + A2*sp.exp(s2*(t-t0)) + iL_inf\n\nsymdisp('i_L(t) = ', round_expr(iL,2), 'A')\n```\n\n\n$\\displaystyle i_L(t) = -4 - 6.33 e^{- 805.89 t} + 12.33 e^{- 413.62 t}\\;A$\n\n\n**Plota gr\u00e1fico de $i_L(t)$**\n\n\n```python\n# plota gr\u00e1fico da fun\u00e7\u00e3o\nintervalo = np.linspace(t0,t0+0.02,100)\nsymplot(t,iL, intervalo, 'iL(t)')\n```\n\n**Determina $v_C(t)$ a partir de $i_L(t)$**\n\n\n```python\n# tens\u00e3o aplicada sobre o capacitor (= tens\u00e3o sobre o indutor)\nvC = L*sp.diff(iL, t)\n\nsymdisp('v_C(t) = ', round_expr(vC, 2), ' V')\n```\n\n\n$\\displaystyle v_C(t) = 30.59 e^{- 805.89 t} - 30.59 e^{- 413.62 t}\\; V$\n\n\n**Plota gr\u00e1fico de $v_C(t)$**\n\n\n```python\n# plota gr\u00e1fico da fun\u00e7\u00e3o\nintervalo = np.linspace(t0,t0+0.02,100)\nsymplot(t, vC, intervalo, 'vC(t)')\n```\n\n**Resolu\u00e7\u00e3o item (b):**\n\n$$\\frac{dv_C}{dt} = 0$$\n\n\n```python\n# define a equa\u00e7\u00e3o dvC/dt = 0\neq1 = sp.Eq(sp.diff(vC, t),0)  \n\nround_expr(eq1, 2)\n```\n\n\n\n\n$\\displaystyle - 24653.1 e^{- 805.89 t} + 12653.1 e^{- 413.62 t} = 0$\n\n\n\n\n```python\n# resolve a equa\u00e7\u00e3o em t\nts = sp.solveset(eq1, t).args[0]\n\n# calcula o valor de vC(t) para t = ts\nvC_ts = vC.evalf(subs={t:ts})\n\nprint('ts = %.2e s'%ts)\nprint('vC(ts) = %.2f V'%vC_ts)\n```\n\n    ts = 1.70e-03 s\n    vC(ts) = -7.37 V\n\n\n**Resolu\u00e7\u00e3o item (c):**\n\n\n```python\n# Par\u00e2metros do circuito:\nR = 6\nL = 6e-3\nC = 0.5e-3\n\n# calculando \u03b1 e \u03c90\n\u03b1  = 1/(2*R*C)\n\u03c90 = 1/np.sqrt(L*C)\n\nsymdisp('\u03b1 =', round(\u03b1, 2), ' rad/s')\nsymdisp('\u03c9_0 =', round(\u03c90, 2), ' rad/s')\n```\n\n\n$\\displaystyle \u03b1 =166.67\\; rad/s$\n\n\n\n$\\displaystyle \u03c9_0 =577.35\\; rad/s$\n\n\n\n```python\n# informa\u00e7\u00f5es obtidas pela an\u00e1lise do circuito\niL_inf = 0  # valor final da corrente no indutor\niL_t0 = 2   # valor inicial da corrente no indutor\nvc_t0 = 0   # valor inicial da tens\u00e3o no capcitor\n\nt0 = 0 # instante do chaveamento\n```\n\n\n```python\n# define a frequ\u00eancia de oscila\u00e7\u00e3o amortecida\n\u03c9d =np.sqrt(\u03c90**2-\u03b1**2)\n\nsymdisp('\u03c9_d =', round(\u03c9d, 2), ' rad/s')\n\n# define vari\u00e1veis da solu\u00e7\u00e3o geral\nt, B1, B2 = sp.symbols('t, B1, B2')\n\n# express\u00e3o geral da resposta subamortecida\niL = sp.exp(-\u03b1*(t-t0))*(B1*sp.cos(\u03c9d*(t-t0)) + B2*sp.sin(\u03c9d*(t-t0))) + iL_inf\n\nprint('Forma geral da solu\u00e7\u00e3o:')\nsymdisp('i_L(t) = ', round_expr(iL,2), ' A')\n```\n\n\n$\\displaystyle \u03c9_d =552.77\\; rad/s$\n\n\n    Forma geral da solu\u00e7\u00e3o:\n\n\n\n$\\displaystyle i_L(t) = \\left(B_{1} \\cos{\\left(552.77 t \\right)} + B_{2} \\sin{\\left(552.77 t \\right)}\\right) e^{- 166.67 t}\\; A$\n\n\n\n```python\n# define os sistema de equa\u00e7\u00f5es com as condi\u00e7\u00f5es iniciais\neq1 = sp.Eq(   B1 + iL_inf, iL_t0)             \neq2 = sp.Eq(-\u03b1*B1 + \u03c9d*B2,  vc_t0/L)  \n\nprint('Sistema de equa\u00e7\u00f5es:')\nsymdisp('(I): ', round_expr(eq1, 2),' ')\nsymdisp('(II): ', round_expr(eq2, 2),' ')\n```\n\n    Sistema de equa\u00e7\u00f5es:\n\n\n\n$\\displaystyle (I): B_{1} = 2\\; $\n\n\n\n$\\displaystyle (II): - 166.67 B_{1} + 552.77 B_{2} = 0.0\\; $\n\n\n\n```python\n# resolve o sistema\nsoluc = sp.solve((eq1, eq2), dict=True)\nB1 = np.array([sol[B1] for sol in soluc])\nB2 = np.array([sol[B2] for sol in soluc])\n\nB1 = B1[0]\nB2 = B2[0]\n\nprint('Solu\u00e7\u00e3o do sistema:')\nsymdisp('B_1 =', round(B1, 2), ' A')\nsymdisp('B_2 =', round(B2, 2), ' A')\n```\n\n    Solu\u00e7\u00e3o do sistema:\n\n\n\n$\\displaystyle B_1 =2.0\\; A$\n\n\n\n$\\displaystyle B_2 =0.6\\; A$\n\n\n\n```python\n# express\u00e3o geral da resposta subamortecida\niL = sp.exp(-\u03b1*(t-t0))*(B1*sp.cos(\u03c9d*(t-t0))+B2*sp.sin(\u03c9d*(t-t0))) + iL_inf\n\nsymdisp('i_L(t) = ', round_expr(iL,2), 'A')\n```\n\n\n$\\displaystyle i_L(t) = \\left(0.6 \\sin{\\left(552.77 t \\right)} + 2.0 \\cos{\\left(552.77 t \\right)}\\right) e^{- 166.67 t}\\;A$\n\n\n\n```python\n# plota gr\u00e1fico da fun\u00e7\u00e3o\nintervalo = np.linspace(t0,t0+0.05,100)\nsymplot(t, iL, intervalo, 'iL(t)')\n```\n\n\n```python\n# tens\u00e3o aplicada sobre o capacitor (= tens\u00e3o sobre o indutor)\nvC = L*sp.diff(iL, t)\nvC = sp.simplify(vC)\n\nsymdisp('v_C(t) = ', round_expr(vC, 2), ' V')\n```\n\n\n$\\displaystyle v_C(t) = - 7.24 e^{- 166.67 t} \\sin{\\left(552.77 t \\right)}\\; V$\n\n\n\n```python\n# plota gr\u00e1fico da fun\u00e7\u00e3o\nintervalo = np.linspace(t0,t0+0.05,100)\nsymplot(t, vC, intervalo, 'vC(t)')\nsymplot(t, [iL, vC], intervalo, ['iL(t)', 'vC(t)'])\n```\n\n## Circuito RLC em s\u00e9rie\n\n\n\n### Aplica\u00e7\u00e3o das Leis de Kirchhoff \n\n$$\\begin{align}\n   v_R + v_L + v_C &= v_s\\\\\n   R i + L\\frac{d i}{dt}+v_C &= v_s\\nonumber\\\\\n   R\\left[C\\frac{dv_C}{dt}\\right] + L\\frac{d}{dt}\\left[C\\frac{dv_C}{dt} \\right] + v_C &= v_s\\nonumber\\\\\n    \\frac{d^{2} v_{\\mathrm{C}}}{d t^{2}}+\\frac{R}{L} \\frac{d v_{\\mathrm{C}}}{d t}+\\frac{1}{L C}   v_{\\mathrm{C}} &=\\frac{v_{\\mathrm{s}}}{LC}\n   \\end{align} \n$$\n\ncom $ \\alpha = \\frac{R}{2L}$ e $\\omega_0 = \\frac{1}{\\sqrt{LC}}$, temos\n\n$$ \\begin{equation}\\label{EDO2} \\frac{d^{2} v_{\\mathrm{C}}}{d t^{2}}+2\\alpha \\frac{d v_{\\mathrm{C}}}{d t}+\\omega_0^2 v_{\\mathrm{C}}=v_{\\mathrm{s}}\\omega_0^2 \\end{equation} $$\n\nA equa\u00e7\u00e3o \\ref{EDO2} \u00e9 uma EDO de segunda ordem, linear e de coeficientes constantes.\n\nEqua\u00e7\u00e3o caracter\u00edstica:\n\n$$\\begin{equation} s^2+2\\alpha s + \\omega_0^2=0 \\end{equation}$$\n\nRa\u00edzes da equa\u00e7\u00e3o caracter\u00edstica:\n\n$$\n\\begin{align}\ns_1 &=-\\alpha +\\sqrt{\\alpha^2-\\omega_0^2}\\\\\ns_2 &=-\\alpha -\\sqrt{\\alpha^2-\\omega_0^2}\n\\end{align}\n$$\n\n### Resposta total \n\nA resposta transiente de circuitos RLC em s\u00e9rie, seja ela natural ($v_C(\\infty)=0$) ou ao degrau ($v_C(\\infty)=v_s$), pode ser classificada nas tr\u00eas casos seguintes. Em todos os casos, assume-se que o transiente teve in\u00edcio no instante $t_0$ (instante do chaveamento).\n\n#### Caso superamortecido ($\\alpha>\\omega_0\\Rightarrow \\text{ra\u00edzes reais e distintas}$):\n\nSolu\u00e7\u00e3o geral da EDO:\n\n$$\\begin{equation} v_{\\mathrm{C}}(t) =A_{1} e^{s_{1} (t-t_0)}+A_{2} e^{s_{2} (t-t_0)}+v_{\\mathrm{C}}(\\infty) \\end{equation}$$\n\nCondi\u00e7\u00f5es iniciais para $v_{\\mathrm{C}}(t)$:\n\n$$\n\\begin{align}\nv_{\\mathrm{C}}(t_0^+) &=A_1 + A_2 + v_{\\mathrm{C}}(\\infty)\\\\\n\\frac{dv_{\\mathrm{C}}(t_0^+)}{dt} &=s_1A_1 + s_2A_2 = \\frac{1}{C} i_{\\mathrm{L}}(t_0^+)\n\\end{align}\n$$\n\nSolu\u00e7\u00e3o do sistema em $A_1$ e $A_2$:\n\n$$\n\\begin{align}\nA_{1} &=\\frac{\\frac{1}{C} i_{\\mathrm{L}}(t_0^+)-s_{2}\\left[v_{\\mathrm{C}}(t_0^+)-v_{\\mathrm{C}}(\\infty)\\right]}{s_{1}-s_{2}} \\\\\nA_{2} &=\\frac{-\\frac{1}{C} i_{\\mathrm{L}}(t_0^+)+s_{1}\\left[v_{\\mathrm{C}}(t_0^+)-v_{\\mathrm{C}}(\\infty)\\right]}{s_{1}-s_{2}}\n\\end{align}\n$$\n\n#### Caso subamortecido ($\\alpha<\\omega_0\\Rightarrow \\text{ra\u00edzes complexas e conjugadas}$):\n\nFazendo $\\omega_d = \\sqrt{\\omega_0^2-\\alpha^2}$ temos $s_1 = -\\alpha +j\\omega_d$ e $s_2 = -\\alpha -j\\omega_d$.\n\nSolu\u00e7\u00e3o geral da EDO:\n\n$$\\begin{equation} v_{\\mathrm{C}}(t) = e^{-\\alpha(t-t_0)}\\left\\lbrace B_{1}\\cos[\\omega_d (t-t_0)] + B_{2}\\sin[\\omega_d (t-t_0)]  \\right\\rbrace + v_{\\mathrm{C}}(\\infty) \\end{equation}$$\n\nCondi\u00e7\u00f5es iniciais para $v_{\\mathrm{C}}(t)$:\n\n$$\n\\begin{align}\nv_{\\mathrm{C}}(t_0^+) &=B_1 + v_{\\mathrm{C}}(\\infty)\\\\\n\\frac{dv_{\\mathrm{C}}(t_0^+)}{dt} &= -\\alpha B_1 +\\omega_d B_2 = \\frac{1}{C} i_{\\mathrm{L}}(t_0^+)\n\\end{align}\n$$\n\nSolu\u00e7\u00e3o do sistema em $B_1$ e $B_2$:\n\n$$\n\\begin{align}\nB_{1} &=v_{\\mathrm{C}}(t_0^+)-v_{\\mathrm{C}}(\\infty) \\\\\nB_{2} &=\\frac{\\frac{1}{C} i_{\\mathrm{L}}(t_0^+)+\\alpha\\left[v_{\\mathrm{C}}(t_0^+)-v_{\\mathrm{C}}(\\infty)\\right]}{\\omega_d}\n\\end{align}\n$$\n\n#### Caso criticamente amortecido ($\\alpha=\\omega_0\\Rightarrow \\text{ra\u00edzes reais e id\u00eanticas } s_1=s_2=-\\alpha$):\n\nSolu\u00e7\u00e3o geral da EDO:\n\n$$ \\begin{equation} v_{\\mathrm{C}}(t) =D_{1} e^{-\\alpha(t-t_0)}+D_{2}(t-t_0) e^{-\\alpha(t-t_0)}+v_{\\mathrm{C}}(\\infty) \\end{equation}$$\n\nCondi\u00e7\u00f5es iniciais para $v_{\\mathrm{C}}(t)$:\n\n$$\n\\begin{align}\nv_{\\mathrm{C}}(t_0^+) &=D_1 + v_{\\mathrm{C}}(\\infty)\\\\\n\\frac{dv_{\\mathrm{C}}(t_0^+)}{dt} &=-\\alpha D_1 + D_2 = \\frac{1}{C} i_{\\mathrm{L}}(t_0^+)\n\\end{align}\n$$\n\nSolu\u00e7\u00e3o do sistema em $D_1$ e $D_2$:\n\n$$\n\\begin{align}\nD_{1} &=v_{\\mathrm{C}}(t_0^+)-v_{\\mathrm{C}}(\\infty) \\\\\nD_{2} &= \\frac{1}{C} i_{\\mathrm{L}}(t_0^+)+\\alpha\\left[v_{\\mathrm{C}}(t_0^+)-v_{\\mathrm{C}}(\\infty)\\right]\n\\end{align}\n$$\n\n### Problema 2\n\nNo circuito da figura a seguir, a chave $ch1$ estive aberta por um longo intervalo de tempo antes de fechar, no instante $t_0=0$s.\n\n\n\na. Para qual valor de $R_x$ o circuito exibe uma resposta criticamente amortecida para $t\\geq 0^+$?\\\nb. Considerando que $R_x$ vale exatamente o valor calculado em (a), determine a tens\u00e3o sobre o capacitor $v_C(t)$ para $t\\geq 0^+$.\\\nc. Considerando que $R_x$ vale um d\u00e9cimo do valor calculado em (a), determine a tens\u00e3o sobre o capacitor $v_C(t)$ para $t\\geq 0^+$.\n\nLink para a simula\u00e7\u00e3o deste circuito: https://tinyurl.com/yjgkkzhu\n\nResolu\u00e7\u00e3o item (b):\n\n\n```python\n# Par\u00e2metros do circuito:\nR = \nL = \nC = \n\n# calculando \u03b1 e \u03c90\n\u03b1  = R/(2*L)\n\u03c90 = 1/np.sqrt(L*C)\n\nsymdisp('\u03b1 =', round(\u03b1, 2), ' rad/s')\nsymdisp('\u03c9_0 =', round(\u03c90, 2), ' rad/s')\n```\n\n\n```python\n# informa\u00e7\u00f5es obtidas pela an\u00e1lise do circuito\nvC_inf =    # valor final da tens\u00e3o sobre o capacitor\niL_t0 =   # valor inicial da corrente no indutor\nvC_t0 =     # valor inicial da tens\u00e3o sobre o capacitor\n\nt0 = 0 # instante do chaveamento\n```\n\n\n```python\n# ra\u00edzes da equa\u00e7\u00e3o caracter\u00edstica\ns1 = -\u03b1\ns2 = -\u03b1\n\n# define vari\u00e1veis da solu\u00e7\u00e3o geral\nt, D1, D2 = sp.symbols('t, D1, D2')\n\n# express\u00e3o geral da resposta \nvC = D1*sp.exp(s1*(t-t0)) + D2*(t-t0)*sp.exp(s2*(t-t0)) + vC_inf\n\nsymdisp('v_C(t) = ', round_expr(vC, 2), ' V')\n```\n\n\n```python\n# define os sistema de equa\u00e7\u00f5es com as condi\u00e7\u00f5es iniciais\neq1 = sp.Eq()             \neq2 = sp.Eq()  \n\nprint('Sistema de equa\u00e7\u00f5es:')\nsymdisp('(I): ', round_expr(eq1, 2),' ')\nsymdisp('(II): ', round_expr(eq2, 2),' ')\n```\n\n\n```python\n# resolve o sistema\nsoluc = sp.solve((eq1, eq2), dict=True)\nD1 = np.array([sol[D1] for sol in soluc])\nD2 = np.array([sol[D2] for sol in soluc])\n\nD1 = D1[0]\nD2 = D2[0]\n\nprint('Solu\u00e7\u00e3o do sistema:')\nsymdisp('D_1 =', round(D1, 2), ' V')\nsymdisp('D_2 =', round(D2, 2), ' V')\n```\n\n\n```python\n# express\u00e3o geral da resposta \nvC = D1*sp.exp(s1*(t-t0)) + D2*(t-t0)*sp.exp(s2*(t-t0)) + vC_inf\n\nsymdisp('v_C(t) = ', round_expr(vC, 2), ' V')\n```\n\n\n```python\n# corrente passando pelo indutor\niL = C*sp.diff(vC, t)\n\nsymdisp('i_L(t) = ', round_expr(iL,2), 'A')\n```\n\n\n```python\n# plota gr\u00e1fico da fun\u00e7\u00e3o\nintervalo = np.linspace(t0,t0+0.05,100)\nsymplot(t, vC, intervalo, 'vC(t)')\n```\n\n\n```python\n# plota gr\u00e1fico da fun\u00e7\u00e3o\nintervalo = np.linspace(t0,t0+0.05,100)\nsymplot(t, iL, intervalo, 'iL(t)')\n```\n\nResolu\u00e7\u00e3o item (c):\n\n\n```python\n# Par\u00e2metros do circuito:\nR = 65.02\nL = 1\nC = 100e-6\n\n# calculando \u03b1 e \u03c90\n\u03b1  = R/(2*L)\n\u03c90 = 1/np.sqrt(L*C)\n\nsymdisp('\u03b1 =', round(\u03b1, 2), ' rad/s')\nsymdisp('\u03c9_0 =', round(\u03c90, 2), ' rad/s')\n```\n\n\n$\\displaystyle \u03b1 =32.51\\; rad/s$\n\n\n\n$\\displaystyle \u03c9_0 =100.0\\; rad/s$\n\n\n\n```python\n# informa\u00e7\u00f5es obtidas pela an\u00e1lise do circuito\nvC_inf = 75.84   # valor final da tens\u00e3o sobre o capacitor\niL_t0 = 0        #  valor inicial da corrente no indutor\nvC_t0 = 21.3     # valor inicial da tens\u00e3o sobre o capacitor\n\nt0 = 0 # instante do chaveamento\n```\n\n\n```python\n# define a frequ\u00eancia de oscila\u00e7\u00e3o amortecida\n\u03c9d =np.sqrt(\u03c90**2-\u03b1**2)\n\nsymdisp('\u03c9_d =', round(\u03c9d, 2), ' rad/s')\n\n# define vari\u00e1veis da solu\u00e7\u00e3o geral\nt, B1, B2 = sp.symbols('t, B1, B2')\n\n# express\u00e3o geral da resposta subamortecida\nvC = sp.exp(-\u03b1*(t-t0))*(B1*sp.cos(\u03c9d*(t-t0)) + B2*sp.sin(\u03c9d*(t-t0))) + vC_inf\n\nsymdisp('v_C(t) = ', round_expr(vC, 2), ' V')\n```\n\n\n$\\displaystyle \u03c9_d =94.57\\; rad/s$\n\n\n\n$\\displaystyle v_C(t) = \\left(B_{1} \\cos{\\left(94.57 t \\right)} + B_{2} \\sin{\\left(94.57 t \\right)}\\right) e^{- 32.51 t} + 75.84\\; V$\n\n\n\n```python\n# define os sistema de equa\u00e7\u00f5es com as condi\u00e7\u00f5es iniciais\neq1 = sp.Eq(   B1 + vC_inf, vC_t0)             \neq2 = sp.Eq(-\u03b1*B1 + \u03c9d*B2,  iL_t0/C)  \n\nprint('Sistema de equa\u00e7\u00f5es:')\nsymdisp('(I): ', round_expr(eq1, 2),' ')\nsymdisp('(II): ', round_expr(eq2, 2),' ')\n```\n\n    Sistema de equa\u00e7\u00f5es:\n\n\n\n$\\displaystyle (I): B_{1} + 75.84 = 21.3\\; $\n\n\n\n$\\displaystyle (II): - 32.51 B_{1} + 94.57 B_{2} = 0.0\\; $\n\n\n\n```python\n# resolve o sistema\nsoluc = sp.solve((eq1, eq2), dict=True)\nB1 = np.array([sol[B1] for sol in soluc])\nB2 = np.array([sol[B2] for sol in soluc])\n\nB1 = B1[0]\nB2 = B2[0]\n\nprint('Solu\u00e7\u00e3o do sistema:')\nsymdisp('B_1 =', round(B1, 2), ' V')\nsymdisp('B_2 =', round(B2, 2), ' V')\n```\n\n    Solu\u00e7\u00e3o do sistema:\n\n\n\n$\\displaystyle B_1 =-54.54\\; V$\n\n\n\n$\\displaystyle B_2 =-18.75\\; V$\n\n\n\n```python\n# express\u00e3o geral da resposta subamortecida\nvC = sp.exp(-\u03b1*(t-t0))*(B1*sp.cos(\u03c9d*(t-t0)) + B2*sp.sin(\u03c9d*(t-t0))) + vC_inf\n\nsymdisp('v_C(t) = ', round_expr(vC, 2), ' V')\n```\n\n\n$\\displaystyle v_C(t) = \\left(- 18.75 \\sin{\\left(94.57 t \\right)} - 54.54 \\cos{\\left(94.57 t \\right)}\\right) e^{- 32.51 t} + 75.84\\; V$\n\n\n\n```python\n# corrente passando pelo indutor\niL = C*sp.diff(vC, t)\n\nsymdisp('i_L(t) = ', round_expr(iL.simplify(),5), 'A')\n```\n\n\n$\\displaystyle i_L(t) = 0.57673 e^{- 32.51 t} \\sin{\\left(94.56796 t \\right)}\\;A$\n\n\n\n```python\n# plota gr\u00e1fico da fun\u00e7\u00e3o\nintervalo = np.linspace(t0,t0+0.25,100)\nsymplot(t, vC, intervalo, 'vC(t)')\n```\n\n\n```python\n# plota gr\u00e1fico da fun\u00e7\u00e3o\nintervalo = np.linspace(t0,t0+0.25,100)\nsymplot(t, iL, intervalo, 'iL(t)')\n```\n", "meta": {"hexsha": "9d3b8401543a5fd11011c58e48a4fa88b13c50cd", "size": 150117, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Jupyter notebooks/Circuitos Eletricos I - Semana 8.2.ipynb", "max_stars_repo_name": "Willh-AM/ElectricCircuits", "max_stars_repo_head_hexsha": "32dc2cd79498f2819967b747a792b7db2822f8bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-05-19T18:36:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T16:30:17.000Z", "max_issues_repo_path": "Jupyter notebooks/Circuitos Eletricos I - Semana 8.2.ipynb", "max_issues_repo_name": "Willh-AM/ElectricCircuits", "max_issues_repo_head_hexsha": "32dc2cd79498f2819967b747a792b7db2822f8bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Jupyter notebooks/Circuitos Eletricos I - Semana 8.2.ipynb", "max_forks_repo_name": "Willh-AM/ElectricCircuits", "max_forks_repo_head_hexsha": "32dc2cd79498f2819967b747a792b7db2822f8bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2021-06-25T12:52:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T14:25:48.000Z", "avg_line_length": 88.7740981668, "max_line_length": 18224, "alphanum_fraction": 0.8260823225, "converted": true, "num_tokens": 8221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21206880435710534, "lm_q2_score": 0.14033624589467186, "lm_q1q2_score": 0.029760939874847795}}
{"text": "### Web-based Tools for Teaching and Research: Jupyter Notebooks and GitHub\nA workshop of the Academy of Data Sciences at the College of Science\n## Jupyter Notebooks & Python\n\nSusanna Werth\n\n---\n\n# Lesson 6: Markdown & Magic\n\nThis lesson contains selected examples for **markdown code** and **magic comands** usful in jupyter notebooks.\n\n---\n# Writing Notebooks with Markdown\n\n\n## Standard Markdown\n\nTo find out how to edit text nicely in markdown cells the Jupyter lab provides a great reference.\n\nGo to top **Menu > Help > Markdown Reference**\nand study the options, or make the tutorial.\n\n## Add code to your markdown cell\nThis code will not be executed, but it can help to display it here.\n\n``` python\nsome code in python\n```\n\n```markdown\n# This works also for a big headline in markdown\n```\n\n## Embed images and adjust their size\nThe markdown reference indicates markdown code to embed an image (including the path to the subfolder where image is located). \n\n```markdown\n\n```\nHowever, this command does not allow to adjust the size.\n\nFor that we have to use html code:\n\n```html\n\n```\n\nwhich will include the image like this:\n\n\n\n## Add highlighted boxes\n\nFor highlighted boxes, we can use a trick and enter html-warnings like this:\n\n```html\n<div class=\"alert alert-info\">\n\n**Box**\n    \n- Generates a highlighted box.\n</div>\n```\n\nafter executing the markdown code above in the markdown cell it will look  this:\n\n<div class=\"alert alert-info\">\n\n**Box**\n    \n- Generates a highlighted box.\n</div>\n\nWe can get different colors with different alert levels:\n- alert-danger: red\n- alert-success: green\n- alert-info: blue\n- alert-warning: yellow/orange\n\nTry them in the markdown cell below!\n\n\n\n---\n# Using Magic Commands in a Notebook\n\nJupyter notebook code cells can contain special commands which are not valid Python code but affect the behavior of the notebook. These special commands are called **magic commands**.\n\n## Bash commands\n\nYou can execute bash commands directly from a notebook, by entering an exclamation mark at the beginning of line:\n\n\n```python\n! pwd   # returns the current path\n```\n\n    /Users/swerth/Dropbox (Personal)/MyDropbox/Documents/Work/Teaching/Workshops/Material_JupyterWorkshop/JupyterMaterial\n\n\n\n```python\n! mkdir myNewFolder # makes new folder\n```\n\n\n```python\n! rmdir myNewFolder # deletes the same folder\n```\n\nTomorrow we will learn how to use git and GitHub. Remember, that you will be able to pull and push content using git, directly from a Jupyter notebook with this option.# Read a list of files with bash command directly into a variable\nnames = !ls ./img/*.png\nnames\n\n\n```python\n# Read a list of files with bash command directly into a variable\nnames = !ls ./img/*.png\nnames\n```\n\n\n\n\n    ['./img/indexing_lists_python.png',\n     './img/jupyter.png',\n     './img/loops_image_num.png',\n     './img/python-operations-across-axes.png',\n     './img/slicing_lists_python.png']\n\n\n\n### Entire cell with bash commands\n\n\n```bash\n%%bash\necho \"HELLO WORLD!\"\n```\n\n    HELLO WORLD!\n\n\n---\n## More magic\n\nDiscriminate between\n- line magics: start with `%` or `!`\n- cell magics: start with `%%`\n\n\n\n```python\n# list available python magics\n%lsmagic\n```\n\n\n\n\n    Available line magics:\n    %alias  %alias_magic  %autoawait  %autocall  %automagic  %autosave  %bookmark  %cat  %cd  %clear  %colors  %conda  %config  %connect_info  %cp  %debug  %dhist  %dirs  %doctest_mode  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %less  %lf  %lk  %ll  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %lx  %macro  %magic  %man  %matplotlib  %mkdir  %more  %mv  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %pip  %popd  %pprint  %precision  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %rep  %rerun  %reset  %reset_selective  %rm  %rmdir  %run  %save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode\n    \n    Available cell magics:\n    %%!  %%HTML  %%SVG  %%bash  %%capture  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%markdown  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile\n    \n    Automagic is ON, % prefix IS NOT needed for line magics.\n\n\n\n\nA good reference for the many magic commands are the iPython documentation pages: https://ipython.readthedocs.io/en/stable/interactive/magics.html\n\n---\n### Execute or load external Python scripts\n\n\n```python\n# uncomment the line below, execute and see what happens\n```\n\n\n```python\n# %run ./data/fahr_to_celcius.py\n```\n\n\n```python\n# %load ./data/fahr_to_celcius.py\n```\n\n### Embed HTML\n\nYou can embed html code in your markdown cell like this:\n\n\n```python\n%%HTML\n<button type=\"button\" id=\"loading-example-btn\" data-loading-text=\"Loading...\" class=\"btn btn-primary\">\n  Loading state\n</button>\n```\n\n\n<button type=\"button\" id=\"loading-example-btn\" data-loading-text=\"Loading...\" class=\"btn btn-primary\">\n  Loading state\n</button>\n\n\n\n### Embed Latex\n\nYou can embed latex code, for example to add equations, in your markdown cell like this:\n\n\n```latex\n%%latex \n\\begin{align} \n    \\frac{\\partial u}{\\partial t} + \\nabla \\cdot \\left( \\boldsymbol{v} u - D\\nabla u \\right) = f \n\\end{align}\n```\n\n\n\\begin{align} \n    \\frac{\\partial u}{\\partial t} + \\nabla \\cdot \\left( \\boldsymbol{v} u - D\\nabla u \\right) = f \n\\end{align}\n\n\n\nFind more awesome magic here: https://arogozhnikov.github.io/2016/09/10/jupyter-features.html\n        \n\n---\n## Embed Youtube Videos & Images with Python code\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('NGFO0kdbZmk')\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\nfrom IPython.display import Image\nImage(filename='./img/jupyter.png',width=200,height=200)\n```\n\nYou can do much more with Jupyter Notebooks and there is a vast amount of tutorials, cheat sheets and documentation pages out there. Below some pages to start:\n\n- Nbviewer documentation pages: https://nbviewer.jupyter.org/github/ipython/ipython/blob/master/examples/IPython%20Kernel/Index.ipynb \n- Blog on Jupyter Notebook features: https://arogozhnikov.github.io/2016/09/10/jupyter-features.html\n\n", "meta": {"hexsha": "a2421a2ba8421e124cf06b7d11316d82c625d6bf", "size": 104054, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "L6_MarkdownAndMagic.ipynb", "max_stars_repo_name": "GeoPythonVT/JupyterWorkshop", "max_stars_repo_head_hexsha": "e7ff7c825842b2ab051d8f61d0080e3c96bc2a16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-30T14:29:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T14:29:03.000Z", "max_issues_repo_path": "L6_MarkdownAndMagic.ipynb", "max_issues_repo_name": "GeoPythonVT/JupyterWorkshop", "max_issues_repo_head_hexsha": "e7ff7c825842b2ab051d8f61d0080e3c96bc2a16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "L6_MarkdownAndMagic.ipynb", "max_forks_repo_name": "GeoPythonVT/JupyterWorkshop", "max_forks_repo_head_hexsha": "e7ff7c825842b2ab051d8f61d0080e3c96bc2a16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 159.34762634, "max_line_length": 59204, "alphanum_fraction": 0.895736829, "converted": true, "num_tokens": 1706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1329642333263228, "lm_q2_score": 0.22270014398423357, "lm_q1q2_score": 0.029611153906525314}}
{"text": "##### Copyright 2020 The Cirq Developers\n\n\n```\n#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# VQE: Ising\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n  <td>\n    <a target=\"_blank\" href=\"https://www.example.org/cirq/tutorials/variational_algorithm\">View on QuantumLib</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/Cirq/blob/master/docs/tutorials/variational_algorithm.ipynb\">Run in Google Colab</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://github.com/quantumlib/Cirq/blob/master/docs/tutorials/variational_algorithm.ipynb\">View source on GitHub</a>\n  </td>\n  <td>\n    <a href=\"https://storage.googleapis.com/tensorflow_docs/Cirq/docs/tutorials/variational_algorithm.ipynb\">Download notebook</a>\n  </td>\n</table>\n\nIn this tutorial, we use the [variational quantum eigensolver](https://arxiv.org/abs/1304.3061) (VQE) in Cirq to optimize a simple Ising model.\n\n\n```\ntry:\n    import cirq\nexcept ImportError:\n    print(\"installing cirq...\")\n    !pip install --quiet cirq\n    print(\"installed cirq.\")\n```\n\n## Background: Variational Quantum Algorithm\n\nThe [variational method](https://en.wikipedia.org/wiki/Variational_method_(quantum_mechanics) in quantum theory is a classical method for finding low energy states of a quantum system. The rough idea of this method is that one defines a trial wave function (sometimes called an *ansatz*) as a function of some parameters, and then one finds the values of these parameters that minimize the expectation value of the energy with respect to these parameters. This minimized ansatz is then an approximation to the lowest energy eigenstate, and the expectation value serves as an upper bound on the energy of the ground state.\n\nIn the last few years (see [arXiv:1304.3061](https://arxiv.org/abs/1304.3061) and [arXiv:1507.08969](https://arxiv.org/abs/1507.08969), for example), it has been realized that quantum computers can mimic the classical technique and that a quantum computer does so with certain advantages. In particular, when one applies the classical variational method to a system of $n$ qubits, an exponential number (in $n$) of complex numbers is necessary to generically represent the wave function of the system. However, with a quantum computer, one can directly produce this state using a parameterized quantum circuit, and then by repeated measurements estimate the expectation value of the energy.\n\nThis idea has led to a class of algorithms known as variational quantum algorithms. Indeed this approach is not just limited to finding low energy eigenstates, but minimizing any objective function that can be expressed as a quantum observable. It is an open question to identify under what conditions these quantum variational algorithms will succeed, and exploring this class of algorithms is a key part of the research for [noisy intermediate scale quantum computers](https://arxiv.org/abs/1801.00862).\n\nThe classical problem we will focus on is the 2D +/- Ising model with transverse field ([ISING](http://iopscience.iop.org/article/10.1088/0305-4470/15/10/028/meta)). This problem is NP-complete. So it is highly unlikely that quantum computers will be able to efficiently solve it across all instances. Yet this type of problem is illustrative of the general class of problems that Cirq is designed to tackle.\n\n\nConsider the energy function\n\n$E(s_1,\\dots,s_n) = \\sum_{\\langle i,j \\rangle} J_{i,j}s_i s_j + \\sum_i h_i s_i$\n\nwhere here each $s_i, J_{i,j}$, and $h_i$ are either +1 or -1. Here each index i is associated with a bit on a square lattice, and the $\\langle i,j \\rangle$ notation means sums over neighboring bits on this lattice. The problem we would like to solve is, given $J_{i,j}$, and $h_i$, find an assignment of $s_i$ values that minimize $E$.\n\nHow does a variational quantum algorithm work for this? One approach is to consider $n$ qubits and associate them with each of the bits in the classical problem. This maps the classical problem onto the quantum problem of minimizing the expectation value of the observable\n\n$H=\\sum_{\\langle i,j \\rangle} J_{i,j} Z_i Z_j + \\sum_i h_iZ_i$\n\nThen one defines a set of parameterized quantum circuits, i.e., a quantum circuit where the gates (or more general quantum operations) are parameterized by some values. This produces an ansatz state\n\n$|\\psi(p_1, p_2, \\dots, p_k)\\rangle$\n\nwhere $p_i$ are the parameters that produce this state (here we assume a pure state, but mixed states are of course possible).\n\nThe variational algorithm then works by noting that one can obtain the value of the objective function for a given ansatz state by\n\n1. Prepare the ansatz state.\n2. Make a measurement which samples from some terms in H.\n3. Goto 1.\n\nNote that one cannot always measure $H$ directly (without the use of quantum phase estimation). So one often relies on the linearity of expectation values to measure parts of $H$ in step 2. One always needs to repeat the measurements to obtain an estimate of the expectation value. How many measurements needed to achieve a given accuracy is beyond the scope of this tutorial, but Cirq can help investigate this question.\n\nThe above shows that one can use a quantum computer to obtain estimates of the objective function for the ansatz. This can then be used in an outer loop to try to obtain parameters for the lowest value of the objective function. For these values, one can then use that best ansatz to produce samples of solutions to the problem, which obtain a hopefully good approximation for the lowest possible value of the objective function.\n\n\n## Create a circuit on a Grid\n\nTo build the above variational quantum algorithm using Cirq, one begins by building the appropriate circuit.  Because the problem we have defined has a natural structure on a grid, we will use Cirq\u2019s built-in `GridQubits` as our qubits. We will demonstrate some of how this works in an interactive Python environment, the following code can be run in series in a Python environment where you have Cirq installed.  For more about circuits and how to create them, see the [Tutorial](basics.ipynb) or the [Circuits](../circuits.ipynb) page.\n\n\n```\nimport cirq\n\n# define the length of the grid.\nlength = 3\n\n# define qubits on the grid.\nqubits = cirq.GridQubit.square(length)\n\nprint(qubits)\n```\n\n    [cirq.GridQubit(0, 0), cirq.GridQubit(0, 1), cirq.GridQubit(0, 2), cirq.GridQubit(1, 0), cirq.GridQubit(1, 1), cirq.GridQubit(1, 2), cirq.GridQubit(2, 0), cirq.GridQubit(2, 1), cirq.GridQubit(2, 2)]\n\n\nHere we see that we've created a bunch of `GridQubits`, which have a row and column, indicating their position on a grid.\n\nNow that we have some qubits, let us construct a `Circuit` on these qubits. For example, suppose we want to apply the Hadamard gate `H` to every qubit whose row index plus column index is even, and an `X` gate to every qubit whose row index plus column index is odd. To do this, we write:\n\n\n```\ncircuit = cirq.Circuit()\ncircuit.append(cirq.H(q) for q in qubits if (q.row + q.col) % 2 == 0)\ncircuit.append(cirq.X(q) for q in qubits if (q.row + q.col) % 2 == 1)\n\nprint(circuit)\n```\n\n    (0, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\n    \n    (0, 1): \u2500\u2500\u2500X\u2500\u2500\u2500\n    \n    (0, 2): \u2500\u2500\u2500H\u2500\u2500\u2500\n    \n    (1, 0): \u2500\u2500\u2500X\u2500\u2500\u2500\n    \n    (1, 1): \u2500\u2500\u2500H\u2500\u2500\u2500\n    \n    (1, 2): \u2500\u2500\u2500X\u2500\u2500\u2500\n    \n    (2, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\n    \n    (2, 1): \u2500\u2500\u2500X\u2500\u2500\u2500\n    \n    (2, 2): \u2500\u2500\u2500H\u2500\u2500\u2500\n\n\n## Creating the Ansatz\n\nOne convenient pattern is to use a python [Generator](https://wiki.python.org/moin/Generators) for defining sub-circuits or layers in our algorithm.  We will define a function that takes in the relevant parameters and then yields the operations for the sub-circuit, and then this can be appended to the `Circuit`:\n\n\n```\ndef rot_x_layer(length, half_turns):\n    \"\"\"Yields X rotations by half_turns on a square grid of given length.\"\"\"\n\n    # Define the gate once and then re-use it for each Operation.\n    rot = cirq.XPowGate(exponent=half_turns)\n\n    # Create an X rotation Operation for each qubit in the grid.\n    for i in range(length):\n        for j in range(length):\n            yield rot(cirq.GridQubit(i, j))\n\n# Create the circuit using the rot_x_layer generator\ncircuit = cirq.Circuit()\ncircuit.append(rot_x_layer(2, 0.1))\nprint(circuit)\n```\n\n    (0, 0): \u2500\u2500\u2500X^0.1\u2500\u2500\u2500\n    \n    (0, 1): \u2500\u2500\u2500X^0.1\u2500\u2500\u2500\n    \n    (1, 0): \u2500\u2500\u2500X^0.1\u2500\u2500\u2500\n    \n    (1, 1): \u2500\u2500\u2500X^0.1\u2500\u2500\u2500\n\n\nAnother important concept here is that the rotation gate is specified in *half turns* ($ht$). For a rotation about `X`, the gate is:\n\n$\\cos(ht * \\pi) I + i \\sin(ht * \\pi) X$\n\nThere is a lot of freedom defining a variational ansatz. Here we will do a variation on a [QAOA strategy](https://arxiv.org/abs/1411.4028) and define an ansatz related to the problem we are trying to solve.\n\nFirst, we need to choose how the instances of the problem are represented. These are the values $J$ and $h$ in the Hamiltonian definition. We represent them as two-dimensional arrays (lists of lists). For $J$ we use two such lists, one for the row links and one for the column links.\n\nHere is a snippet that we can use to generate random problem instances:\n\n\n```\nimport random\ndef rand2d(rows, cols):\n    return [[random.choice([+1, -1]) for _ in range(cols)] for _ in range(rows)]\n\ndef random_instance(length):\n    # transverse field terms\n    h = rand2d(length, length)\n    # links within a row\n    jr = rand2d(length - 1, length)\n    # links within a column\n    jc = rand2d(length, length - 1)\n    return (h, jr, jc)\n\nh, jr, jc = random_instance(3)\nprint('transverse fields: {}'.format(h))\nprint('row j fields: {}'.format(jr))\nprint('column j fields: {}'.format(jc))\n```\n\n    transverse fields: [[1, -1, 1], [1, -1, 1], [-1, 1, -1]]\n    row j fields: [[-1, 1, -1], [1, -1, -1]]\n    column j fields: [[-1, 1], [-1, -1], [1, -1]]\n\n\nIn the code above, the actual values will be different for each individual run because they are using `random.choice`.\n\nGiven this definition of the problem instance, we can now introduce our ansatz. It will consist of one step of a circuit made up of:\n\n1. Apply an `XPowGate` for the same parameter for all qubits. This is the method we have written above.\n2. Apply a `ZPowGate` for the same parameter for all qubits where the transverse field term $h$ is $+1$.\n\n\n```\ndef rot_z_layer(h, half_turns):\n    \"\"\"Yields Z rotations by half_turns conditioned on the field h.\"\"\"\n    gate = cirq.ZPowGate(exponent=half_turns)\n    for i, h_row in enumerate(h):\n        for j, h_ij in enumerate(h_row):\n            if h_ij == 1:\n                yield gate(cirq.GridQubit(i, j))\n```\n\n3. Apply a `CZPowGate` for the same parameter between all qubits where the coupling field term $J$ is $+1$. If the field is $-1$, apply `CZPowGate` conjugated by $X$ gates on all qubits.\n\n\n```\ndef rot_11_layer(jr, jc, half_turns):\n    \"\"\"Yields rotations about |11> conditioned on the jr and jc fields.\"\"\"\n    cz_gate = cirq.CZPowGate(exponent=half_turns)    \n    for i, jr_row in enumerate(jr):\n        for j, jr_ij in enumerate(jr_row):\n            q = cirq.GridQubit(i, j)\n            q_1 = cirq.GridQubit(i + 1, j)\n            if jr_ij == -1:\n                yield cirq.X(q)\n                yield cirq.X(q_1)\n            yield cz_gate(q, q_1)\n            if jr_ij == -1:\n                yield cirq.X(q)\n                yield cirq.X(q_1)\n\n    for i, jc_row in enumerate(jc):\n        for j, jc_ij in enumerate(jc_row):\n            q = cirq.GridQubit(i, j)\n            q_1 = cirq.GridQubit(i, j + 1)\n            if jc_ij == -1:\n                yield cirq.X(q)\n                yield cirq.X(q_1)\n            yield cz_gate(q, q_1)\n            if jc_ij == -1:\n                yield cirq.X(q)\n                yield cirq.X(q_1)\n```\n\nPutting all together, we can create a step that uses just three parameters. Below is the code, which uses the generator for each of the layers (note to advanced Python users: this code does not contain a bug in using `yield` due to the auto flattening of the `OP_TREE concept`. Typically, one would want to use `yield` from here, but this is not necessary):\n\n\n```\ndef one_step(h, jr, jc, x_half_turns, h_half_turns, j_half_turns):\n    length = len(h)\n    yield rot_x_layer(length, x_half_turns)\n    yield rot_z_layer(h, h_half_turns)\n    yield rot_11_layer(jr, jc, j_half_turns)\n\nh, jr, jc = random_instance(3)\n\ncircuit = cirq.Circuit()    \ncircuit.append(one_step(h, jr, jc, 0.1, 0.2, 0.3),\n               strategy=cirq.InsertStrategy.EARLIEST)\nprint(circuit)\n```\n\n                               \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2510           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    (0, 0): \u2500\u2500\u2500X^0.1\u2500\u2500\u2500Z^0.2\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                \u2502                             \u2502\n    (0, 1): \u2500\u2500\u2500X^0.1\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^0.3\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                \u2502    \u2502                                           \u2502\n    (0, 2): \u2500\u2500\u2500X^0.1\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^0.3\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                \u2502    \u2502    \u2502\n    (1, 0): \u2500\u2500\u2500X^0.1\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^0.3\u253c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                     \u2502    \u2502          \u2502                                   \u2502\n    (1, 1): \u2500\u2500\u2500X^0.1\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^0.3\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^0.3\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\n                                          \u2502          \u2502                 \u2502                                 \u2502\n    (1, 2): \u2500\u2500\u2500X^0.1\u2500\u2500\u2500Z^0.2\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^0.3\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^0.3\u2500\u2500\u2500X\u2500\u2500\u2500\n                                                     \u2502        \u2502        \u2502\n    (2, 0): \u2500\u2500\u2500X^0.1\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^0.3\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                                              \u2502        \u2502                 \u2502\n    (2, 1): \u2500\u2500\u2500X^0.1\u2500\u2500\u2500Z^0.2\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^0.3\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^0.3\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                                              \u2502                                  \u2502\n    (2, 2): \u2500\u2500\u2500X^0.1\u2500\u2500\u2500Z^0.2\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^0.3\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^0.3\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                               \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\n\nHere we see that we have chosen particular parameter values $(0.1, 0.2, 0.3)$.\n\n## Simulation\n\nIn Cirq, the simulators make a distinction between a *run* and a *simulation*. A *run* only allows for a simulation that mimics the actual quantum hardware. For example, it does not allow for access to the amplitudes of the wave function of the system, since that is not experimentally accessible. *Simulate* commands, however, are broader and allow different forms of simulation. When prototyping small circuits, it is useful to execute *simulate* methods, but one should be wary of relying on them when running against actual hardware.\n\nCurrently, Cirq ships with a simulator tied strongly to the gate set of the **Google xmon architecture**. However, for convenience, the simulator attempts to automatically convert unknown operations into `XmonGates` (as long as the operation specifies a matrix or a decomposition into `XmonGates`). This, in principle, allows us to simulate any circuit that has gates that implement one and two qubit `KnownMatrix` gates. Future releases of Cirq will expand these simulators.\n\nBecause the simulator is tied to the **xmon gate set**, the simulator lives, in contrast to core Cirq, in the `cirq.google` module. To run a simulation of the full circuit, we create a simulator, and pass the circuit to the simulator.\n\n\n```\nsimulator = cirq.Simulator()\ncircuit = cirq.Circuit()    \ncircuit.append(one_step(h, jr, jc, 0.1, 0.2, 0.3))\ncircuit.append(cirq.measure(*qubits, key='x'))\nresults = simulator.run(circuit, repetitions=100)\nprint(results.histogram(key='x'))\n```\n\n    Counter({0: 74, 32: 6, 4: 4, 256: 4, 16: 2, 1: 2, 128: 2, 2: 2, 8: 1, 132: 1, 272: 1, 64: 1})\n\n\nNote that we have run the simulation 100 times and produced a histogram of the counts of the measurement results. What are the keys in the histogram counter? Note that we have passed in the order of the qubits. This ordering is then used to translate the order of the measurement results to a register using a [big endian representation](https://en.wikipedia.org/wiki/Endianness).\n\nFor our optimization problem, we want to calculate the value of the objective function for a given result run. One way to do this is using the raw measurement data from the result of `simulator.run`. Another way to do this is to provide to the histogram a method to calculate the objective: this will then be used as the key for the returned `Counter`.\n\n\n```\nimport numpy as np\n\ndef energy_func(length, h, jr, jc):\n    def energy(measurements):\n        # Reshape measurement into array that matches grid shape.\n        meas_list_of_lists = [measurements[i * length:(i + 1) * length]\n                              for i in range(length)]\n        # Convert true/false to +1/-1.\n        pm_meas = 1 - 2 * np.array(meas_list_of_lists).astype(np.int32)\n\n        tot_energy = np.sum(pm_meas * h)\n        for i, jr_row in enumerate(jr):\n            for j, jr_ij in enumerate(jr_row):\n                tot_energy += jr_ij * pm_meas[i, j] * pm_meas[i + 1, j]\n        for i, jc_row in enumerate(jc):\n            for j, jc_ij in enumerate(jc_row):\n                tot_energy += jc_ij * pm_meas[i, j] * pm_meas[i, j + 1]\n        return tot_energy\n    return energy\nprint(results.histogram(key='x', fold_func=energy_func(3, h, jr, jc)))\n```\n\n    Counter({1: 76, -3: 8, -1: 6, -5: 4, 7: 2, 3: 2, 5: 2})\n\n\nOne can then calculate the expectation value over all repetitions:\n\n\n```\ndef obj_func(result):\n    energy_hist = result.histogram(key='x', fold_func=energy_func(3, h, jr, jc))\n    return np.sum([k * v for k,v in energy_hist.items()]) / result.repetitions\nprint('Value of the objective function {}'.format(obj_func(results)))\n```\n\n    Value of the objective function 0.56\n\n\n### Parameterizing the Ansatz\n\nNow that we have constructed a variational ansatz and shown how to simulate it using Cirq, we can think about optimizing the value. \n\nOn quantum hardware, one would most likely want to have the optimization code as close to the hardware as possible. As the classical hardware that is allowed to inter-operate with the quantum hardware becomes better specified, this language will be better defined. Without this specification, however, Cirq also provides a useful concept for optimizing the looping in many optimization algorithms. This is the fact that many of the value in the gate sets can, instead of being specified by a float, be specified by a `Symbol`, and this `Symbol` can be substituted for a value specified at execution time.\n\nLuckily for us, we have written our code so that using parameterized values is as simple as passing `Symbol` objects where we previously passed float values.\n\n\n```\nimport sympy\ncircuit = cirq.Circuit()\nalpha = sympy.Symbol('alpha')\nbeta = sympy.Symbol('beta')\ngamma = sympy.Symbol('gamma')\ncircuit.append(one_step(h, jr, jc, alpha, beta, gamma))\ncircuit.append(cirq.measure(*qubits, key='x'))\nprint(circuit)\n```\n\n                                  \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510             \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    (0, 0): \u2500\u2500\u2500X^alpha\u2500\u2500\u2500Z^beta\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('x')\u2500\u2500\u2500\n                                   \u2502                                     \u2502                                                                  \u2502\n    (0, 1): \u2500\u2500\u2500X^alpha\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^gamma\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                   \u2502      \u2502                                                     \u2502                                           \u2502\n    (0, 2): \u2500\u2500\u2500X^alpha\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^gamma\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                   \u2502      \u2502      \u2502                                                                                          \u2502\n    (1, 0): \u2500\u2500\u2500X^alpha\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^gamma\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                          \u2502      \u2502            \u2502                                           \u2502                                 \u2502\n    (1, 1): \u2500\u2500\u2500X^alpha\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^gamma\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^gamma\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                                 \u2502            \u2502                     \u2502                                         \u2502             \u2502\n    (1, 2): \u2500\u2500\u2500X^alpha\u2500\u2500\u2500Z^beta\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^gamma\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^gamma\u2500\u2500\u2500X\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                                              \u2502          \u2502          \u2502                                                       \u2502\n    (2, 0): \u2500\u2500\u2500X^alpha\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^gamma\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                                                         \u2502          \u2502                     \u2502                                 \u2502\n    (2, 1): \u2500\u2500\u2500X^alpha\u2500\u2500\u2500Z^beta\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^gamma\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^gamma\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                                                         \u2502                                          \u2502                       \u2502\n    (2, 2): \u2500\u2500\u2500X^alpha\u2500\u2500\u2500Z^beta\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^gamma\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@^gamma\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518             \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\n\nNote now that the circuit's gates are parameterized.\n\nParameters are specified at runtime using a `ParamResolver`, which is just a dictionary from `Symbol` keys to runtime values. \n\nFor instance:\n\n\n```\nresolver = cirq.ParamResolver({'alpha': 0.1, 'beta': 0.3, 'gamma': 0.7})\nresolved_circuit = cirq.resolve_parameters(circuit, resolver)\n```\n\nresolves the parameters to actual values in the circuit.\n\nCirq also has the concept of a *sweep*. A sweep is a collection of parameter resolvers. This runtime information is very useful when one wants to run many circuits for many different parameter values. Sweeps can be created to specify values directly (this is one way to get classical information into a circuit), or a variety of helper methods. For example suppose we want to evaluate our circuit over an equally spaced grid of parameter values. We can easily create this using `LinSpace`.\n\n\n```\nsweep = (cirq.Linspace(key='alpha', start=0.1, stop=0.9, length=5)\n         * cirq.Linspace(key='beta', start=0.1, stop=0.9, length=5)\n         * cirq.Linspace(key='gamma', start=0.1, stop=0.9, length=5))\nresults = simulator.run_sweep(circuit, params=sweep, repetitions=100)\nfor result in results:\n    print(result.params.param_dict, obj_func(result))\n```\n\n    OrderedDict([('alpha', 0.1), ('beta', 0.1), ('gamma', 0.1)]) 0.74\n    OrderedDict([('alpha', 0.1), ('beta', 0.1), ('gamma', 0.30000000000000004)]) 0.92\n    OrderedDict([('alpha', 0.1), ('beta', 0.1), ('gamma', 0.5)]) 0.72\n    OrderedDict([('alpha', 0.1), ('beta', 0.1), ('gamma', 0.7000000000000001)]) 0.88\n    OrderedDict([('alpha', 0.1), ('beta', 0.1), ('gamma', 0.9)]) 0.92\n    OrderedDict([('alpha', 0.1), ('beta', 0.30000000000000004), ('gamma', 0.1)]) 0.6\n    OrderedDict([('alpha', 0.1), ('beta', 0.30000000000000004), ('gamma', 0.30000000000000004)]) 0.7\n    OrderedDict([('alpha', 0.1), ('beta', 0.30000000000000004), ('gamma', 0.5)]) 1.12\n    OrderedDict([('alpha', 0.1), ('beta', 0.30000000000000004), ('gamma', 0.7000000000000001)]) 1.18\n    OrderedDict([('alpha', 0.1), ('beta', 0.30000000000000004), ('gamma', 0.9)]) 1.02\n    OrderedDict([('alpha', 0.1), ('beta', 0.5), ('gamma', 0.1)]) 0.5\n    OrderedDict([('alpha', 0.1), ('beta', 0.5), ('gamma', 0.30000000000000004)]) 1.14\n    OrderedDict([('alpha', 0.1), ('beta', 0.5), ('gamma', 0.5)]) 1.0\n    OrderedDict([('alpha', 0.1), ('beta', 0.5), ('gamma', 0.7000000000000001)]) 0.84\n    OrderedDict([('alpha', 0.1), ('beta', 0.5), ('gamma', 0.9)]) 0.92\n    OrderedDict([('alpha', 0.1), ('beta', 0.7000000000000001), ('gamma', 0.1)]) 1.16\n    OrderedDict([('alpha', 0.1), ('beta', 0.7000000000000001), ('gamma', 0.30000000000000004)]) 0.8\n    OrderedDict([('alpha', 0.1), ('beta', 0.7000000000000001), ('gamma', 0.5)]) 0.84\n    OrderedDict([('alpha', 0.1), ('beta', 0.7000000000000001), ('gamma', 0.7000000000000001)]) 1.28\n    OrderedDict([('alpha', 0.1), ('beta', 0.7000000000000001), ('gamma', 0.9)]) 1.04\n    OrderedDict([('alpha', 0.1), ('beta', 0.9), ('gamma', 0.1)]) 0.9\n    OrderedDict([('alpha', 0.1), ('beta', 0.9), ('gamma', 0.30000000000000004)]) 0.74\n    OrderedDict([('alpha', 0.1), ('beta', 0.9), ('gamma', 0.5)]) 0.78\n    OrderedDict([('alpha', 0.1), ('beta', 0.9), ('gamma', 0.7000000000000001)]) 1.0\n    OrderedDict([('alpha', 0.1), ('beta', 0.9), ('gamma', 0.9)]) 0.56\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.1), ('gamma', 0.1)]) 0.34\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.1), ('gamma', 0.30000000000000004)]) -0.08\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.1), ('gamma', 0.5)]) -0.34\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.1), ('gamma', 0.7000000000000001)]) -0.08\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.1), ('gamma', 0.9)]) 0.18\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.30000000000000004), ('gamma', 0.1)]) -0.7\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.30000000000000004), ('gamma', 0.30000000000000004)]) 0.5\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.30000000000000004), ('gamma', 0.5)]) 0.5\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.30000000000000004), ('gamma', 0.7000000000000001)]) -0.08\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.30000000000000004), ('gamma', 0.9)]) 0.62\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.5), ('gamma', 0.1)]) 0.54\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.5), ('gamma', 0.30000000000000004)]) 0.2\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.5), ('gamma', 0.5)]) -0.24\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.5), ('gamma', 0.7000000000000001)]) 0.46\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.5), ('gamma', 0.9)]) 0.22\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.7000000000000001), ('gamma', 0.1)]) 0.02\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.7000000000000001), ('gamma', 0.30000000000000004)]) -0.18\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.7000000000000001), ('gamma', 0.5)]) -0.16\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.7000000000000001), ('gamma', 0.7000000000000001)]) 0.14\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.7000000000000001), ('gamma', 0.9)]) -0.8\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.9), ('gamma', 0.1)]) 0.46\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.9), ('gamma', 0.30000000000000004)]) 0.48\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.9), ('gamma', 0.5)]) 0.72\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.9), ('gamma', 0.7000000000000001)]) 0.04\n    OrderedDict([('alpha', 0.30000000000000004), ('beta', 0.9), ('gamma', 0.9)]) 0.32\n    OrderedDict([('alpha', 0.5), ('beta', 0.1), ('gamma', 0.1)]) 0.3\n    OrderedDict([('alpha', 0.5), ('beta', 0.1), ('gamma', 0.30000000000000004)]) -0.06\n    OrderedDict([('alpha', 0.5), ('beta', 0.1), ('gamma', 0.5)]) 0.26\n    OrderedDict([('alpha', 0.5), ('beta', 0.1), ('gamma', 0.7000000000000001)]) -0.4\n    OrderedDict([('alpha', 0.5), ('beta', 0.1), ('gamma', 0.9)]) 0.48\n    OrderedDict([('alpha', 0.5), ('beta', 0.30000000000000004), ('gamma', 0.1)]) 0.0\n    OrderedDict([('alpha', 0.5), ('beta', 0.30000000000000004), ('gamma', 0.30000000000000004)]) -0.14\n    OrderedDict([('alpha', 0.5), ('beta', 0.30000000000000004), ('gamma', 0.5)]) 0.22\n    OrderedDict([('alpha', 0.5), ('beta', 0.30000000000000004), ('gamma', 0.7000000000000001)]) 0.84\n    OrderedDict([('alpha', 0.5), ('beta', 0.30000000000000004), ('gamma', 0.9)]) 0.6\n    OrderedDict([('alpha', 0.5), ('beta', 0.5), ('gamma', 0.1)]) 0.04\n    OrderedDict([('alpha', 0.5), ('beta', 0.5), ('gamma', 0.30000000000000004)]) -0.44\n    OrderedDict([('alpha', 0.5), ('beta', 0.5), ('gamma', 0.5)]) -0.52\n    OrderedDict([('alpha', 0.5), ('beta', 0.5), ('gamma', 0.7000000000000001)]) -0.02\n    OrderedDict([('alpha', 0.5), ('beta', 0.5), ('gamma', 0.9)]) -0.08\n    OrderedDict([('alpha', 0.5), ('beta', 0.7000000000000001), ('gamma', 0.1)]) 1.02\n    OrderedDict([('alpha', 0.5), ('beta', 0.7000000000000001), ('gamma', 0.30000000000000004)]) 0.58\n    OrderedDict([('alpha', 0.5), ('beta', 0.7000000000000001), ('gamma', 0.5)]) -0.68\n    OrderedDict([('alpha', 0.5), ('beta', 0.7000000000000001), ('gamma', 0.7000000000000001)]) 0.16\n    OrderedDict([('alpha', 0.5), ('beta', 0.7000000000000001), ('gamma', 0.9)]) 0.98\n    OrderedDict([('alpha', 0.5), ('beta', 0.9), ('gamma', 0.1)]) -0.48\n    OrderedDict([('alpha', 0.5), ('beta', 0.9), ('gamma', 0.30000000000000004)]) -0.72\n    OrderedDict([('alpha', 0.5), ('beta', 0.9), ('gamma', 0.5)]) 0.6\n    OrderedDict([('alpha', 0.5), ('beta', 0.9), ('gamma', 0.7000000000000001)]) -0.04\n    OrderedDict([('alpha', 0.5), ('beta', 0.9), ('gamma', 0.9)]) -0.36\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.1), ('gamma', 0.1)]) -0.08\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.1), ('gamma', 0.30000000000000004)]) 2.0\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.1), ('gamma', 0.5)]) 0.86\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.1), ('gamma', 0.7000000000000001)]) 1.88\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.1), ('gamma', 0.9)]) 0.66\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.30000000000000004), ('gamma', 0.1)]) 1.32\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.30000000000000004), ('gamma', 0.30000000000000004)]) 1.16\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.30000000000000004), ('gamma', 0.5)]) 1.12\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.30000000000000004), ('gamma', 0.7000000000000001)]) 1.4\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.30000000000000004), ('gamma', 0.9)]) 0.82\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.5), ('gamma', 0.1)]) 1.0\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.5), ('gamma', 0.30000000000000004)]) 1.3\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.5), ('gamma', 0.5)]) 0.88\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.5), ('gamma', 0.7000000000000001)]) 1.34\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.5), ('gamma', 0.9)]) 1.3\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.7000000000000001), ('gamma', 0.1)]) 0.8\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.7000000000000001), ('gamma', 0.30000000000000004)]) 0.88\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.7000000000000001), ('gamma', 0.5)]) 0.82\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.7000000000000001), ('gamma', 0.7000000000000001)]) 1.8\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.7000000000000001), ('gamma', 0.9)]) 1.2\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.9), ('gamma', 0.1)]) 1.42\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.9), ('gamma', 0.30000000000000004)]) 0.96\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.9), ('gamma', 0.5)]) 1.12\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.9), ('gamma', 0.7000000000000001)]) 0.98\n    OrderedDict([('alpha', 0.7000000000000001), ('beta', 0.9), ('gamma', 0.9)]) 1.4\n    OrderedDict([('alpha', 0.9), ('beta', 0.1), ('gamma', 0.1)]) 2.5\n    OrderedDict([('alpha', 0.9), ('beta', 0.1), ('gamma', 0.30000000000000004)]) 2.96\n    OrderedDict([('alpha', 0.9), ('beta', 0.1), ('gamma', 0.5)]) 2.6\n    OrderedDict([('alpha', 0.9), ('beta', 0.1), ('gamma', 0.7000000000000001)]) 2.76\n    OrderedDict([('alpha', 0.9), ('beta', 0.1), ('gamma', 0.9)]) 2.94\n    OrderedDict([('alpha', 0.9), ('beta', 0.30000000000000004), ('gamma', 0.1)]) 2.7\n    OrderedDict([('alpha', 0.9), ('beta', 0.30000000000000004), ('gamma', 0.30000000000000004)]) 2.78\n    OrderedDict([('alpha', 0.9), ('beta', 0.30000000000000004), ('gamma', 0.5)]) 2.44\n    OrderedDict([('alpha', 0.9), ('beta', 0.30000000000000004), ('gamma', 0.7000000000000001)]) 2.62\n    OrderedDict([('alpha', 0.9), ('beta', 0.30000000000000004), ('gamma', 0.9)]) 2.82\n    OrderedDict([('alpha', 0.9), ('beta', 0.5), ('gamma', 0.1)]) 2.58\n    OrderedDict([('alpha', 0.9), ('beta', 0.5), ('gamma', 0.30000000000000004)]) 2.9\n    OrderedDict([('alpha', 0.9), ('beta', 0.5), ('gamma', 0.5)]) 2.72\n    OrderedDict([('alpha', 0.9), ('beta', 0.5), ('gamma', 0.7000000000000001)]) 2.64\n    OrderedDict([('alpha', 0.9), ('beta', 0.5), ('gamma', 0.9)]) 2.38\n    OrderedDict([('alpha', 0.9), ('beta', 0.7000000000000001), ('gamma', 0.1)]) 2.76\n    OrderedDict([('alpha', 0.9), ('beta', 0.7000000000000001), ('gamma', 0.30000000000000004)]) 2.74\n    OrderedDict([('alpha', 0.9), ('beta', 0.7000000000000001), ('gamma', 0.5)]) 3.1\n    OrderedDict([('alpha', 0.9), ('beta', 0.7000000000000001), ('gamma', 0.7000000000000001)]) 2.4\n    OrderedDict([('alpha', 0.9), ('beta', 0.7000000000000001), ('gamma', 0.9)]) 2.98\n    OrderedDict([('alpha', 0.9), ('beta', 0.9), ('gamma', 0.1)]) 2.94\n    OrderedDict([('alpha', 0.9), ('beta', 0.9), ('gamma', 0.30000000000000004)]) 2.94\n    OrderedDict([('alpha', 0.9), ('beta', 0.9), ('gamma', 0.5)]) 3.02\n    OrderedDict([('alpha', 0.9), ('beta', 0.9), ('gamma', 0.7000000000000001)]) 2.98\n    OrderedDict([('alpha', 0.9), ('beta', 0.9), ('gamma', 0.9)]) 2.62\n\n\n### Finding the Minimum\n\nNow we have all the code, we do a simple grid search over values to find a minimal value. Grid search is not the best optimization algorithm, but is here simply illustrative.\n\n\n```\nsweep_size = 10\nsweep = (cirq.Linspace(key='alpha', start=0.0, stop=1.0, length=10)\n         * cirq.Linspace(key='beta', start=0.0, stop=1.0, length=10)\n         * cirq.Linspace(key='gamma', start=0.0, stop=1.0, length=10))\nresults = simulator.run_sweep(circuit, params=sweep, repetitions=100)\n\nmin = None\nmin_params = None\nfor result in results:\n    value = obj_func(result)\n    if min is None or value < min:\n        min = value\n        min_params = result.params\nprint('Minimum objective value is {}.'.format(min))\n```\n\n    Minimum objective value is -1.16.\n\n\nWe've created a simple variational quantum algorithm using Cirq. Where to go next? Perhaps you can play around with the above code and work on analyzing the algorithms performance. Add new parameterized circuits and build an end to end program for analyzing these circuits.\n", "meta": {"hexsha": "802574c38cce5d2dfc71b527ef582ed9e027b81f", "size": 45454, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/variational_algorithm.ipynb", "max_stars_repo_name": "exAClior/Cirq", "max_stars_repo_head_hexsha": "0701327bc66c988428f302dd1e4bed1eef1535a6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/tutorials/variational_algorithm.ipynb", "max_issues_repo_name": "exAClior/Cirq", "max_issues_repo_head_hexsha": "0701327bc66c988428f302dd1e4bed1eef1535a6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/tutorials/variational_algorithm.ipynb", "max_forks_repo_name": "exAClior/Cirq", "max_forks_repo_head_hexsha": "0701327bc66c988428f302dd1e4bed1eef1535a6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-24T07:13:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-24T07:13:40.000Z", "avg_line_length": 50.7299107143, "max_line_length": 699, "alphanum_fraction": 0.5358164298, "converted": true, "num_tokens": 11022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.09401018469323504, "lm_q1q2_score": 0.029523949737690937}}
{"text": "```python\n!conda activate reco_base\n```\n\n\n```python\n#set the environment path to find Recommenders\nimport sys\nsys.path.append(\"../\")\n\nimport pyspark\nimport pandas as pd\nimport numpy as np\nimport cornac\nimport papermill as pm\n\nfrom datetime import datetime, timedelta\n\n\nfrom reco_utils.dataset import movielens\nfrom reco_utils.dataset.python_splitters import python_random_split\nfrom reco_utils.evaluation.python_evaluation import map_at_k, ndcg_at_k, precision_at_k, recall_at_k\nfrom reco_utils.recommender.cornac.cornac_utils import predict_ranking\nfrom reco_utils.common.timer import Timer\nfrom reco_utils.common.constants import SEED\nfrom reco_utils.common.spark_utils import start_or_get_spark\nfrom reco_utils.dataset.download_utils import maybe_download\nfrom reco_utils.dataset.python_splitters import (\n    python_random_split, \n    python_chrono_split, \n    python_stratified_split\n)\nfrom reco_utils.dataset.spark_splitters import (\n    spark_random_split, \n    spark_chrono_split, \n    spark_stratified_split,\n    spark_timestamp_split\n)\n\nprint(\"System version: {}\".format(sys.version))\nprint(\"Pyspark version: {}\".format(pyspark.__version__))\n```\n\n    System version: 3.6.10 |Anaconda, Inc.| (default, Jan  7 2020, 15:18:16) [MSC v.1916 64 bit (AMD64)]\n    Pyspark version: 2.4.5\n\n\n\n```python\nimport scrapbook as sb\nimport os\n```\n\n\n```python\n# DATA_URL = \"http://files.grouplens.org/datasets/movielens/ml-100k/u.data\"\n# DATA_PATH = \"ml-100k.data\"\n\nCOL_USER = \"UserId\"\nCOL_ITEM = \"MovieId\"\nCOL_RATING = \"Rating\"\nCOL_PREDICTION = \"Rating\"\nCOL_TIMESTAMP = \"Name\"\n```\n\n\n```python\n# pip install scrapbook\n```\n\n## 1 Data preparation\n\n### 1.1 Data understanding\n\nFor illustration purpose, the data used in the examples below is the MovieLens-100K dataset.\n\n\n```python\n# filepath = maybe_download(DATA_URL, DATA_PATH)\n```\n\n\n```python\ndata_vegan = pd.read_csv(\"userItem_vegan.csv\", names=[COL_USER, COL_ITEM, COL_RATING, COL_TIMESTAMP])\ndata_vegan = data_vegan.iloc[1:]\ndata_vegan[['UserId','MovieId','Rating']]=data_vegan[['UserId','MovieId','Rating']].apply(pd.to_numeric)\n```\n\n\n```python\ndata_veg = pd.read_csv(\"userItem_veg.csv\", names=[COL_USER, COL_ITEM, COL_RATING, COL_TIMESTAMP])\ndata_veg = data_veg.iloc[1:]\ndata_veg[['UserId','MovieId','Rating']]=data_veg[['UserId','MovieId','Rating']].apply(pd.to_numeric)\n```\n\n\n```python\ndata_diet = pd.read_csv(\"userItem_dietery.csv\", names=[COL_USER, COL_ITEM, COL_RATING, COL_TIMESTAMP])\ndata_diet = data_diet.iloc[1:]\ndata_diet[['UserId','MovieId','Rating']]=data_diet[['UserId','MovieId','Rating']].apply(pd.to_numeric)\n```\n\n\n```python\ndata_keto = pd.read_csv(\"userItem_keto.csv\", names=[COL_USER, COL_ITEM, COL_RATING, COL_TIMESTAMP])\ndata_keto = data_keto.iloc[1:]\ndata_keto[['UserId','MovieId','Rating']]=data_keto[['UserId','MovieId','Rating']].apply(pd.to_numeric)\n```\n\n\n```python\ndata_meats = pd.read_csv(\"userItem_meats.csv\", names=[COL_USER, COL_ITEM, COL_RATING, COL_TIMESTAMP])\ndata_meats = data_meats.iloc[1:]\ndata_meats[['UserId','MovieId','Rating']]=data_meats[['UserId','MovieId','Rating']].apply(pd.to_numeric)\n```\n\n\n```python\ndata_vegan.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>UserId</th>\n      <th>MovieId</th>\n      <th>Rating</th>\n      <th>Name</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>482</td>\n      <td>8.708580e+11</td>\n      <td>1</td>\n      <td>Sawyer and Sons</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>482</td>\n      <td>4.668540e+11</td>\n      <td>4</td>\n      <td>Drake, Chavez and Walters</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>482</td>\n      <td>6.487340e+11</td>\n      <td>4</td>\n      <td>Melendez-Nunez</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>482</td>\n      <td>5.750330e+11</td>\n      <td>5</td>\n      <td>Hall LLC</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>482</td>\n      <td>5.798643e+10</td>\n      <td>1</td>\n      <td>Short Inc</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndata_vegan.describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>UserId</th>\n      <th>MovieId</th>\n      <th>Rating</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>10000.000000</td>\n      <td>1.000000e+04</td>\n      <td>10000.000000</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>482.486000</td>\n      <td>4.359525e+11</td>\n      <td>2.998400</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>292.324763</td>\n      <td>2.623302e+11</td>\n      <td>1.415485</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>2.000000</td>\n      <td>2.461627e+10</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>222.750000</td>\n      <td>2.572865e+11</td>\n      <td>2.000000</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>476.000000</td>\n      <td>4.409715e+11</td>\n      <td>3.000000</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>730.750000</td>\n      <td>6.487942e+11</td>\n      <td>4.000000</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>1000.000000</td>\n      <td>8.890040e+11</td>\n      <td>5.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndata_veg.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>UserId</th>\n      <th>MovieId</th>\n      <th>Rating</th>\n      <th>Name</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>895</td>\n      <td>2.751260e+11</td>\n      <td>2</td>\n      <td>Riggs, Lee and Chen</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>895</td>\n      <td>2.317960e+11</td>\n      <td>1</td>\n      <td>Jacobson, Gordon and Davis</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>895</td>\n      <td>9.122788e+10</td>\n      <td>3</td>\n      <td>Diaz, Henderson and Hall</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>895</td>\n      <td>1.981990e+11</td>\n      <td>2</td>\n      <td>Chapman-Thomas</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>895</td>\n      <td>5.888380e+11</td>\n      <td>5</td>\n      <td>Wood-Ramos</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndata_diet.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>UserId</th>\n      <th>MovieId</th>\n      <th>Rating</th>\n      <th>Name</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>335</td>\n      <td>1.522730e+11</td>\n      <td>5</td>\n      <td>Allen Inc</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>335</td>\n      <td>1.288410e+11</td>\n      <td>3</td>\n      <td>Vazquez, Leblanc and Jackson</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>335</td>\n      <td>8.250580e+11</td>\n      <td>3</td>\n      <td>Smith Ltd</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>335</td>\n      <td>9.875440e+11</td>\n      <td>2</td>\n      <td>Willis-Hill</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>335</td>\n      <td>6.498720e+11</td>\n      <td>3</td>\n      <td>Page, Hill and Lewis</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndata_keto.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>UserId</th>\n      <th>MovieId</th>\n      <th>Rating</th>\n      <th>Name</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>105</td>\n      <td>6.797480e+11</td>\n      <td>5</td>\n      <td>Stephens-Johnson</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>105</td>\n      <td>9.818940e+11</td>\n      <td>4</td>\n      <td>Klein PLC</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>105</td>\n      <td>3.272700e+11</td>\n      <td>1</td>\n      <td>Davis-Stevenson</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>105</td>\n      <td>5.883760e+11</td>\n      <td>4</td>\n      <td>Barry-Rhodes</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>105</td>\n      <td>5.474700e+11</td>\n      <td>1</td>\n      <td>Smith-Orr</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndata_meats.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>UserId</th>\n      <th>MovieId</th>\n      <th>Rating</th>\n      <th>Name</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>265</td>\n      <td>3.140010e+11</td>\n      <td>2</td>\n      <td>Carson, Taylor and Garcia</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>265</td>\n      <td>4.842040e+11</td>\n      <td>2</td>\n      <td>Walker, Erickson and Thomas</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>265</td>\n      <td>2.248474e+09</td>\n      <td>5</td>\n      <td>Bowen-Jimenez</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>265</td>\n      <td>6.419440e+11</td>\n      <td>1</td>\n      <td>Smith Ltd</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>265</td>\n      <td>8.823150e+11</td>\n      <td>1</td>\n      <td>Cummings, Martin and Arellano</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## 2 Experimentation protocol\n\nExperimentation protocol is usually set up to favor a reasonable evaluation for a specific recommendation scenario. For example,\n* *Recommender-A* is to recommend movies to people by taking people's collaborative rating similarities. To make sure the evaluation is statisically sound, the same set of users for both model building and testing should be used (to avoid any cold-ness of users), and a stratified splitting strategy should be taken.\n* *Recommender-B* is to recommend fashion products to customers. It makes sense that evaluation of the recommender considers time-dependency of customer purchases, as apparently, tastes of the customers in fashion items may be drifting over time. In this case, a chronologically splitting should be used.\n\n## 3 Data split\n\n###  Stratified split\n\n\nChronogically splitting method takes in a dataset and splits it by either user or item. The split is stratified so that the same set of users or items will appear in both training and testing data sets. \n\nSimilar to chronological splitter, `filter_by` and `min_rating_filter` also apply to the stratified splitter.\n\nThe following example shows the split of the sample data with a ratio of 0.7, and for each user there should be at least 10 ratings.\n\n\n```python\ndata_vegan_train, data_vegan_test = python_stratified_split(\n    data_vegan[data_vegan.columns[:3]] , filter_by=\"user\", min_rating=10, ratio=0.7,\n    col_user=COL_USER, col_item=COL_ITEM\n)\n```\n\n\n```python\ndata_veg_train, data_veg_test = python_stratified_split(\n    data_veg[data_veg.columns[:3]] , filter_by=\"user\", min_rating=10, ratio=0.7,\n    col_user=COL_USER, col_item=COL_ITEM\n)\n```\n\n\n```python\ndata_keto_train, data_keto_test = python_stratified_split(\n    data_keto[data_keto.columns[:3]] , filter_by=\"user\", min_rating=10, ratio=0.7,\n    col_user=COL_USER, col_item=COL_ITEM\n)\n```\n\n\n```python\ndata_meats_train, data_meats_test = python_stratified_split(\n    data_meats[data_meats.columns[:3]] , filter_by=\"user\", min_rating=10, ratio=0.7,\n    col_user=COL_USER, col_item=COL_ITEM\n)\n```\n\n\n```python\ndata_diet_train, data_diet_test = python_stratified_split(\n    data_diet[data_diet.columns[:3]] , filter_by=\"user\", min_rating=10, ratio=0.7,\n    col_user=COL_USER, col_item=COL_ITEM\n)\n```\n\n\n```python\ndata_vegan_train.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>UserId</th>\n      <th>MovieId</th>\n      <th>Rating</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>7221</th>\n      <td>2</td>\n      <td>8.708580e+11</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>7238</th>\n      <td>2</td>\n      <td>6.489750e+11</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>7236</th>\n      <td>2</td>\n      <td>3.858572e+10</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>7222</th>\n      <td>2</td>\n      <td>4.668540e+11</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>7229</th>\n      <td>2</td>\n      <td>2.613010e+11</td>\n      <td>5</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndata_vegan_train.shape[0] + data_vegan_test.shape[0], data_vegan.shape[0]\n```\n\n\n\n\n    (10000, 10000)\n\n\n\n\n```python\nos.environ['JAVA_HOME'] = 'C:\\\\Program Files\\\\Java\\\\jre1.8.0_111'\n```\n\n\n```python\nos.environ.get('JAVA_HOME')\n```\n\n\n\n\n    'C:\\\\Program Files\\\\Java\\\\jre1.8.0_111'\n\n\n\n# Bayesian Personalized Ranking (BPR)\n\nThis notebook serves as an introduction to Bayesian Personalized Ranking (BPR) model for implicit feedback.  In this tutorial, we focus on learning the BPR model using matrix factorization approach, hence, the model is sometimes also named BPRMF.\n\nThe implementation of the model is from [Cornac](https://github.com/PreferredAI/cornac), which is a framework for recommender systems with a focus on models leveraging auxiliary data (e.g., item descriptive text and image, social network, etc).\n\n## 1 BPR Algorithm\n\n### 1.1 Personalized Ranking from Implicit Feedback\n\nThe task of personalized ranking aims at providing each user a ranked list of items (recommendations).  This is very common in scenarios where recommender systems are based on implicit user behavior (e.g. purchases, clicks).  The available observations are only positive feedback where the non-observed ones are a mixture of real negative feedback and missing values.\n\nOne usual approach for item recommendation is directly predicting a preference score $\\hat{x}_{u,i}$ given to item $i$ by user $u$.  BPR uses a different approach by using item pairs $(i, j)$ and optimizing for the correct ranking given preference of user $u$, thus, there are notions of *positive* and *negative* items.  The training data $D_S : U \\times I \\times I$ is defined as:\n\n$$D_S = \\{(u, i, j) \\mid i \\in I^{+}_{u} \\wedge j \\in I \\setminus I^{+}_{u}\\}$$\n\nwhere user $u$ is assumed to prefer $i$ over $j$ (i.e. $i$ is a *positive item* and $j$ is a *negative item*).\n\n\n### 1.2 Objective Function\n\nFrom the Bayesian perspective, BPR maximizes the posterior probability over the model parameters $\\Theta$ by optimizing the likelihood function $p(i >_{u} j | \\Theta)$ and the prior probability $p(\\Theta)$.\n\n$$p(\\Theta \\mid >_{u}) \\propto p(i >_{u} j \\mid \\Theta) \\times p(\\Theta)$$\n\nThe joint probability of the likelihood over all users $u \\in U$ can be simplified to:\n\n$$ \\prod_{u \\in U} p(>_{u} \\mid \\Theta) = \\prod_{(u, i, j) \\in D_S} p(i >_{u} j \\mid \\Theta) $$\n\nThe individual probability that a user $u$ prefers item $i$ to item $j$ can be defined as:\n\n$$ p(i >_{u} j \\mid \\Theta) = \\sigma (\\hat{x}_{uij}(\\Theta)) $$\n\nwhere $\\sigma$ is the logistic sigmoid:\n\n$$ \\sigma(x) = \\frac{1}{1 + e^{-x}} $$\n\nThe preference scoring function $\\hat{x}_{uij}(\\Theta)$ could be an arbitrary real-valued function of the model parameter $\\Theta$.  Thus, it makes BPR a general framework for modeling the relationship between triplets $(u, i, j)$ where different model classes like matrix factorization could be used for estimating $\\hat{x}_{uij}(\\Theta)$.\n\nFor the prior, one of the common pratices is to choose $p(\\Theta)$ following a normal distribution, which results in a nice form of L2 regularization in the final log-form of the objective function.\n\n$$ p(\\Theta) \\sim N(0, \\Sigma_{\\Theta}) $$\n\nTo reduce the complexity of the model, all parameters $\\Theta$ are assumed to be independent and having the same variance, which gives a simpler form of the co-variance matrix $\\Sigma_{\\Theta} = \\lambda_{\\Theta}I$.  Thus, there are less number of hyperparameters to be determined.\n\nThe final objective of the maximum posterior estimator:\n\n$$ J = \\sum_{(u, i, j) \\in D_S} \\text{ln } \\sigma(\\hat{x}_{uij}) - \\lambda_{\\Theta} ||\\Theta||^2 $$\n\nwhere $\\lambda_\\Theta$ are the model specific regularization paramerters.\n\n\n### 1.3 Learning with Matrix Factorization\n\n#### Stochastic Gradient Descent\n\nAs the defined objective function is differentible, gradient descent based method for optimization is naturally adopted.  The gradient of the objective $J$ with respect to the model parameters:\n\n$$\n\\begin{align}\n\\frac{\\partial J}{\\partial \\Theta} & = \\sum_{(u, i, j) \\in D_S} \\frac{\\partial}{\\partial \\Theta} \\text{ln} \\ \\sigma(\\hat{x}_{uij}) - \\lambda_{\\Theta} \\frac{\\partial}{\\partial \\Theta} ||\\Theta||^2 \\\\\n& \\propto \\sum_{(u, i, j) \\in D_S} \\frac{-e^{-\\hat{x}_{uij}}}{1 + e^{-\\hat{x}_{uij}}} \\cdot  \\frac{\\partial}{\\partial \\Theta} \\hat{x}_{uij} - \\lambda_{\\Theta} \\Theta\n\\end{align}\n$$\n\nDue to slow convergence of full gradient descent, we prefer using stochastic gradient descent to optimize the BPR model.  For each triplet $(u, i, j) \\in D_S$, the update rule for the parameters:\n\n$$ \\Theta \\leftarrow \\Theta + \\alpha \\Big( \\frac{e^{-\\hat{x}_{uij}}}{1 + e^{-\\hat{x}_{uij}}} \\cdot \\frac{\\partial}{\\partial \\Theta} \\hat{x}_{uij} + \\lambda_\\Theta \\Theta \\Big) $$\n\n#### Matrix Factorization for Preference Approximation\n\nAs mentioned earlier, the preference scoring function $\\hat{x}_{uij}(\\Theta)$ could be approximated by any real-valued function.  First, the estimator $\\hat{x}_{uij}$ is decomposed into:\n\n$$ \\hat{x}_{uij} = \\hat{x}_{ui} - \\hat{x}_{uj} $$\n\nThe problem of estimating $\\hat{x}_{ui}$ is a standard collaborative filtering formulation, where matrix factorization approach has shown to be very effective.  The prediction formula can written as dot product between user feature vector $w_u$ and item feature vector $h_i$:\n\n$$ \\hat{x}_{ui} = \\langle w_u , h_i \\rangle = \\sum_{f=1}^{k} w_{uf} \\cdot h_{if} $$\n\nThe  derivatives of matrix factorization with respect to the model parameters are:\n\n$$\n\\frac{\\partial}{\\partial \\theta} \\hat{x}_{uij} = \n\\begin{cases}\n    (h_{if} - h_{jf})  & \\text{if } \\theta = w_{uf} \\\\\n    w_{uf}             & \\text{if } \\theta = h_{if} \\\\\n    -w_{uf}            & \\text{if } \\theta = h_{jf} \\\\\n    0                  & \\text{else}\n\\end{cases}\n$$\n\nIn theory, any kernel can be used to estimate $\\hat{x}_{ui}$ besides the dot product $ \\langle \\cdot , \\cdot \\rangle $.  For example, k-Nearest-Neighbor (kNN) has also been shown to achieve good performance.\n\n#### Analogies to AUC optimization\n\nBy optimizing the objective function of BPR model, we effectively maximizing [AUC](https://towardsdatascience.com/understanding-auc-roc-curve-68b2303cc9c5) measurement.  To keep the notebook focused, please refer to the [paper](https://arxiv.org/ftp/arxiv/papers/1205/1205.2618.pdf) for details of the analysis (Section 4.1.1).\n\n## 2 Cornac implementation of BPR\n\nBPR is implemented in the [Cornac](https://cornac.readthedocs.io/en/latest/index.html) framework as part of the model collections.\n* Detailed documentations of the BPR model in Cornac can be found [here](https://cornac.readthedocs.io/en/latest/models.html#bayesian-personalized-ranking-bpr).\n* Source codes of the BPR implementation is available on the Cornac Github repository, which can be found [here](https://github.com/PreferredAI/cornac/blob/master/cornac/models/bpr/recom_bpr.pyx).\n\n\n## 3 Cornac BPR movie recommender\n\n\n### 3.1 Load and split data\n\nTo evaluate the performance of item recommendation, we adopted the provided `python_random_split` tool for the consistency.  Data is randomly split into training and test sets with the ratio of 75/25.\n\n\nNote that Cornac also cover different [built-in schemes](https://cornac.readthedocs.io/en/latest/eval_methods.html) for model evaluation.\n\n### 3.2 Cornac Dataset\n\nTo work with models implemented in Cornac, we need to construct an object from [Dataset](https://cornac.readthedocs.io/en/latest/data.html#module-cornac.data.dataset) class.\n\nDataset Class in Cornac serves as the main object that the models will interact with.  In addition to data transformations, Dataset provides a bunch of useful iterators for looping through the data, as well as supporting different negative sampling techniques.\n\n\n```python\ntrain_vegan_set = cornac.data.Dataset.from_uir(data_vegan_train.itertuples(index=False), seed=SEED)\n\nprint('Number of users: {}'.format(train_vegan_set.num_users))\nprint('Number of items: {}'.format(train_vegan_set.num_items))\n```\n\n    Number of users: 393\n    Number of items: 20\n\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\cornac\\data\\dataset.py:361: UserWarning: 1119 duplicated observations are removed!\n      warnings.warn(\"%d duplicated observations are removed!\" % dup_count)\n\n\n\n```python\ntrain_veg_set = cornac.data.Dataset.from_uir(data_veg_train.itertuples(index=False), seed=SEED)\n\nprint('Number of users: {}'.format(train_veg_set.num_users))\nprint('Number of items: {}'.format(train_veg_set.num_items))\n```\n\n    Number of users: 401\n    Number of items: 20\n\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\cornac\\data\\dataset.py:361: UserWarning: 1044 duplicated observations are removed!\n      warnings.warn(\"%d duplicated observations are removed!\" % dup_count)\n\n\n\n```python\ntrain_meats_set = cornac.data.Dataset.from_uir(data_meats_train.itertuples(index=False), seed=SEED)\n\nprint('Number of users: {}'.format(train_meats_set.num_users))\nprint('Number of items: {}'.format(train_meats_set.num_items))\n```\n\n    Number of users: 403\n    Number of items: 20\n\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\cornac\\data\\dataset.py:361: UserWarning: 1018 duplicated observations are removed!\n      warnings.warn(\"%d duplicated observations are removed!\" % dup_count)\n\n\n\n```python\ntrain_keto_set = cornac.data.Dataset.from_uir(data_keto_train.itertuples(index=False), seed=SEED)\n\nprint('Number of users: {}'.format(train_keto_set.num_users))\nprint('Number of items: {}'.format(train_keto_set.num_items))\n```\n\n    Number of users: 390\n    Number of items: 20\n\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\cornac\\data\\dataset.py:361: UserWarning: 1142 duplicated observations are removed!\n      warnings.warn(\"%d duplicated observations are removed!\" % dup_count)\n\n\n\n```python\ntrain_diet_set = cornac.data.Dataset.from_uir(data_diet_train.itertuples(index=False), seed=SEED)\n\nprint('Number of users: {}'.format(train_diet_set.num_users))\nprint('Number of items: {}'.format(train_diet_set.num_items))\n```\n\n    Number of users: 408\n    Number of items: 20\n\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\cornac\\data\\dataset.py:361: UserWarning: 965 duplicated observations are removed!\n      warnings.warn(\"%d duplicated observations are removed!\" % dup_count)\n\n\n\n```python\n\n```\n\n\n```python\ndata_vegan_train\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>UserId</th>\n      <th>MovieId</th>\n      <th>Rating</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>7221</th>\n      <td>2</td>\n      <td>8.708580e+11</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>7238</th>\n      <td>2</td>\n      <td>6.489750e+11</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>7236</th>\n      <td>2</td>\n      <td>3.858572e+10</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>7222</th>\n      <td>2</td>\n      <td>4.668540e+11</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>7229</th>\n      <td>2</td>\n      <td>2.613010e+11</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>9177</th>\n      <td>1000</td>\n      <td>6.507020e+11</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>9174</th>\n      <td>1000</td>\n      <td>8.234320e+11</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>9163</th>\n      <td>1000</td>\n      <td>6.487340e+11</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>9170</th>\n      <td>1000</td>\n      <td>2.461627e+10</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>9180</th>\n      <td>1000</td>\n      <td>5.123240e+11</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n<p>7000 rows \u00d7 3 columns</p>\n</div>\n\n\n\n\n```python\ndata_vegan_test\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>UserId</th>\n      <th>MovieId</th>\n      <th>Rating</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>7225</th>\n      <td>2</td>\n      <td>5.798643e+10</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>7233</th>\n      <td>2</td>\n      <td>8.890040e+11</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>7228</th>\n      <td>2</td>\n      <td>1.312350e+11</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>7231</th>\n      <td>2</td>\n      <td>2.452430e+11</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>7235</th>\n      <td>2</td>\n      <td>3.592860e+11</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>9173</th>\n      <td>1000</td>\n      <td>8.890040e+11</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>9168</th>\n      <td>1000</td>\n      <td>1.312350e+11</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>9171</th>\n      <td>1000</td>\n      <td>2.452430e+11</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>9175</th>\n      <td>1000</td>\n      <td>3.592860e+11</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>9167</th>\n      <td>1000</td>\n      <td>4.463170e+11</td>\n      <td>4</td>\n    </tr>\n  </tbody>\n</table>\n<p>3000 rows \u00d7 3 columns</p>\n</div>\n\n\n\n\n```python\n\n```\n\n### 3.3 Train the BPR model\n\nThe BPR has a few important parameters that we need to consider:\n\n- `k`: controls the dimension of the latent space (i.e. the size of the vectors  $w_u$  and  $h_i$ ).\n- `max_iter`: defines the number of iterations of the SGD procedure.\n- `learning_rate`: controls the step size $\\alpha$ in the gradient update rules.\n- `lambda_reg`: controls the L2-Regularization $\\lambda$ in the objective function.\n\nNote that different values of `k` and `max_iter` will affect the training time.\n\nWe will here set `k` to 200, `max_iter` to 100, `learning_rate` to 0.01, and `lambda_reg` to 0.001. To train the model, we simply need to call the `fit()` method.\n\n\n```python\n# top k items to recommend\nTOP_K = 10\n\n# Model parameters\nNUM_FACTORS = 200\nNUM_EPOCHS = 100\n```\n\n\n```python\nbpr = cornac.models.BPR(\n    k=NUM_FACTORS,\n    max_iter=NUM_EPOCHS,\n    learning_rate=0.01,\n    lambda_reg=0.001,\n    verbose=True,\n    seed=SEED\n)\n```\n\n\n```python\nbpr1 = cornac.models.BPR(\n    k=NUM_FACTORS,\n    max_iter=NUM_EPOCHS,\n    learning_rate=0.01,\n    lambda_reg=0.001,\n    verbose=True,\n    seed=SEED\n)\n```\n\n\n```python\nbpr2 = cornac.models.BPR(\n    k=NUM_FACTORS,\n    max_iter=NUM_EPOCHS,\n    learning_rate=0.01,\n    lambda_reg=0.001,\n    verbose=True,\n    seed=SEED\n)\n```\n\n\n```python\nbpr3 = cornac.models.BPR(\n    k=NUM_FACTORS,\n    max_iter=NUM_EPOCHS,\n    learning_rate=0.01,\n    lambda_reg=0.001,\n    verbose=True,\n    seed=SEED\n)\n```\n\n\n```python\nbpr4 = cornac.models.BPR(\n    k=NUM_FACTORS,\n    max_iter=NUM_EPOCHS,\n    learning_rate=0.01,\n    lambda_reg=0.001,\n    verbose=True,\n    seed=SEED\n)\n```\n\n\n```python\nwith Timer() as t:\n    bpr.fit(train_vegan_set)\nprint(\"Took {} seconds for training.\".format(t))\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 100/100 [00:00<00:00, 524.86it/s, correct=96.05%, skipped=75.02%]\n\n    Optimization finished!\n    Took 0.1961 seconds for training.\n\n\n    \n\n\n\n```python\nwith Timer() as t1:\n    bpr1.fit(train_veg_set)\nprint(\"Took {} seconds for training.\".format(t1))\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 100/100 [00:00<00:00, 486.73it/s, correct=96.88%, skipped=75.76%]\n\n    Optimization finished!\n    Took 0.2098 seconds for training.\n\n\n    \n\n\n\n```python\nwith Timer() as t2:\n    bpr2.fit(train_meats_set)\nprint(\"Took {} seconds for training.\".format(t2))\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 100/100 [00:00<00:00, 489.14it/s, correct=96.72%, skipped=74.49%]\n\n    Optimization finished!\n    Took 0.2097 seconds for training.\n\n\n    \n\n\n\n```python\nwith Timer() as t3:\n    bpr3.fit(train_keto_set)\nprint(\"Took {} seconds for training.\".format(t3))\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 100/100 [00:00<00:00, 503.77it/s, correct=96.88%, skipped=76.51%]\n\n    Optimization finished!\n    Took 0.2032 seconds for training.\n\n\n    \n\n\n\n```python\nwith Timer() as t4:\n    bpr4.fit(train_diet_set)\nprint(\"Took {} seconds for training.\".format(t4))\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 100/100 [00:00<00:00, 489.11it/s, correct=97.23%, skipped=73.69%]\n\n    Optimization finished!\n    Took 0.2096 seconds for training.\n\n\n    \n\n\n### 3.4 Prediction and Evaluation\n\nNow that our model is trained, we can produce the ranked lists for recommendation.  Every recommender models in Cornac provide `rate()` and `rank()` methods for predicting item rated value as well as item ranked list for a given user.  To make use of the current evaluation schemes, we will through `predict()` and `predict_ranking()` functions inside `cornac_utils` to produce the predictions.\n\nNote that BPR model is effectively designed for item ranking.  Hence, we only measure the performance using ranking metrics.\n\n\n```python\nwith Timer() as t:\n    all_predictions_vegan = predict_ranking(bpr, data_vegan_train, usercol='UserId', itemcol='MovieId', remove_seen=True)\nprint(\"Took {} seconds for prediction.\".format(t))\n```\n\n    Took 0.0333 seconds for prediction.\n\n\n\n```python\nwith Timer() as t1:\n    all_predictions_veg = predict_ranking(bpr1, data_veg_train, usercol='UserId', itemcol='MovieId', remove_seen=True)\nprint(\"Took {} seconds for prediction.\".format(t1))\n```\n\n    Took 0.0335 seconds for prediction.\n\n\n\n```python\nwith Timer() as t2:\n    all_predictions_meats = predict_ranking(bpr2, data_meats_train, usercol='UserId', itemcol='MovieId', remove_seen=True)\nprint(\"Took {} seconds for prediction.\".format(t2))\n```\n\n    Took 0.0458 seconds for prediction.\n\n\n\n```python\nwith Timer() as t3:\n    all_predictions_keto = predict_ranking(bpr3, data_keto_train, usercol='UserId', itemcol='MovieId', remove_seen=True)\nprint(\"Took {} seconds for prediction.\".format(t3))\n```\n\n    Took 0.0333 seconds for prediction.\n\n\n\n```python\nwith Timer() as t4:\n    all_predictions_diet = predict_ranking(bpr4, data_diet_train, usercol='UserId', itemcol='MovieId', remove_seen=True)\nprint(\"Took {} seconds for prediction.\".format(t4))\n```\n\n    Took 0.0337 seconds for prediction.\n\n\n\n```python\nall_predictions_vegan.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>UserId</th>\n      <th>MovieId</th>\n      <th>prediction</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>7000</th>\n      <td>2</td>\n      <td>3.592860e+11</td>\n      <td>-3.130452</td>\n    </tr>\n    <tr>\n      <th>7001</th>\n      <td>2</td>\n      <td>8.890040e+11</td>\n      <td>-3.100885</td>\n    </tr>\n    <tr>\n      <th>7002</th>\n      <td>2</td>\n      <td>4.463170e+11</td>\n      <td>-3.146401</td>\n    </tr>\n    <tr>\n      <th>7003</th>\n      <td>2</td>\n      <td>2.452430e+11</td>\n      <td>-3.063432</td>\n    </tr>\n    <tr>\n      <th>7004</th>\n      <td>2</td>\n      <td>5.798643e+10</td>\n      <td>-3.124748</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nall_predictions_diet.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>UserId</th>\n      <th>MovieId</th>\n      <th>prediction</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>7000</th>\n      <td>1</td>\n      <td>7.212760e+11</td>\n      <td>-3.119670</td>\n    </tr>\n    <tr>\n      <th>7001</th>\n      <td>1</td>\n      <td>6.498720e+11</td>\n      <td>-3.140393</td>\n    </tr>\n    <tr>\n      <th>7002</th>\n      <td>1</td>\n      <td>9.720180e+11</td>\n      <td>-3.262902</td>\n    </tr>\n    <tr>\n      <th>7003</th>\n      <td>1</td>\n      <td>1.066964e+10</td>\n      <td>-3.200517</td>\n    </tr>\n    <tr>\n      <th>7004</th>\n      <td>1</td>\n      <td>3.621910e+11</td>\n      <td>-3.219943</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nall_predictions_keto\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>UserId</th>\n      <th>MovieId</th>\n      <th>prediction</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>7000</th>\n      <td>2</td>\n      <td>8.485400e+11</td>\n      <td>-3.014489</td>\n    </tr>\n    <tr>\n      <th>7001</th>\n      <td>2</td>\n      <td>5.474700e+11</td>\n      <td>-3.121271</td>\n    </tr>\n    <tr>\n      <th>7002</th>\n      <td>2</td>\n      <td>1.669846e+10</td>\n      <td>-3.195842</td>\n    </tr>\n    <tr>\n      <th>7003</th>\n      <td>2</td>\n      <td>8.299790e+11</td>\n      <td>-3.134908</td>\n    </tr>\n    <tr>\n      <th>7004</th>\n      <td>2</td>\n      <td>1.023820e+11</td>\n      <td>-3.059457</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>8937</th>\n      <td>997</td>\n      <td>8.299790e+11</td>\n      <td>-3.139083</td>\n    </tr>\n    <tr>\n      <th>8938</th>\n      <td>997</td>\n      <td>1.023820e+11</td>\n      <td>-3.063709</td>\n    </tr>\n    <tr>\n      <th>8939</th>\n      <td>997</td>\n      <td>3.545630e+11</td>\n      <td>-3.147928</td>\n    </tr>\n    <tr>\n      <th>8940</th>\n      <td>998</td>\n      <td>5.883760e+11</td>\n      <td>-1.982533</td>\n    </tr>\n    <tr>\n      <th>8941</th>\n      <td>998</td>\n      <td>9.003820e+11</td>\n      <td>-1.917607</td>\n    </tr>\n  </tbody>\n</table>\n<p>1942 rows \u00d7 3 columns</p>\n</div>\n\n\n\n\n```python\nall_predictions_veg\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>UserId</th>\n      <th>MovieId</th>\n      <th>prediction</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>7000</th>\n      <td>1</td>\n      <td>4.065000e+11</td>\n      <td>-3.139853</td>\n    </tr>\n    <tr>\n      <th>7001</th>\n      <td>1</td>\n      <td>5.888380e+11</td>\n      <td>-3.121801</td>\n    </tr>\n    <tr>\n      <th>7002</th>\n      <td>1</td>\n      <td>7.078830e+11</td>\n      <td>-3.136266</td>\n    </tr>\n    <tr>\n      <th>7003</th>\n      <td>1</td>\n      <td>8.219560e+11</td>\n      <td>-3.229192</td>\n    </tr>\n    <tr>\n      <th>7004</th>\n      <td>1</td>\n      <td>8.774820e+11</td>\n      <td>-3.233014</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>9059</th>\n      <td>1000</td>\n      <td>5.888380e+11</td>\n      <td>-3.122741</td>\n    </tr>\n    <tr>\n      <th>9060</th>\n      <td>1000</td>\n      <td>7.078830e+11</td>\n      <td>-3.137147</td>\n    </tr>\n    <tr>\n      <th>9061</th>\n      <td>1000</td>\n      <td>8.219560e+11</td>\n      <td>-3.230041</td>\n    </tr>\n    <tr>\n      <th>9062</th>\n      <td>1000</td>\n      <td>8.774820e+11</td>\n      <td>-3.233911</td>\n    </tr>\n    <tr>\n      <th>9063</th>\n      <td>1000</td>\n      <td>9.192850e+11</td>\n      <td>-3.128587</td>\n    </tr>\n  </tbody>\n</table>\n<p>2064 rows \u00d7 3 columns</p>\n</div>\n\n\n\n\n```python\nall_predictions_meats\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>UserId</th>\n      <th>MovieId</th>\n      <th>prediction</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>7000</th>\n      <td>0</td>\n      <td>9.766570e+11</td>\n      <td>-3.205724</td>\n    </tr>\n    <tr>\n      <th>7001</th>\n      <td>0</td>\n      <td>8.823150e+11</td>\n      <td>-3.007143</td>\n    </tr>\n    <tr>\n      <th>7002</th>\n      <td>0</td>\n      <td>6.781750e+11</td>\n      <td>-3.213889</td>\n    </tr>\n    <tr>\n      <th>7003</th>\n      <td>0</td>\n      <td>7.181130e+11</td>\n      <td>-3.155331</td>\n    </tr>\n    <tr>\n      <th>7004</th>\n      <td>0</td>\n      <td>1.546790e+11</td>\n      <td>-3.243256</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>9073</th>\n      <td>998</td>\n      <td>7.181130e+11</td>\n      <td>-3.154270</td>\n    </tr>\n    <tr>\n      <th>9074</th>\n      <td>998</td>\n      <td>1.546790e+11</td>\n      <td>-3.242161</td>\n    </tr>\n    <tr>\n      <th>9075</th>\n      <td>998</td>\n      <td>3.167953e+10</td>\n      <td>-3.282422</td>\n    </tr>\n    <tr>\n      <th>9076</th>\n      <td>999</td>\n      <td>6.419440e+11</td>\n      <td>-1.662408</td>\n    </tr>\n    <tr>\n      <th>9077</th>\n      <td>999</td>\n      <td>7.704500e+11</td>\n      <td>-1.624743</td>\n    </tr>\n  </tbody>\n</table>\n<p>2078 rows \u00d7 3 columns</p>\n</div>\n\n\n\n\n```python\ndata_vegan.dtypes\n\n```\n\n\n\n\n    UserId       int64\n    MovieId    float64\n    Rating       int64\n    Name        object\n    dtype: object\n\n\n\n\n```python\ndata_vegan.shape\n```\n\n\n\n\n    (10000, 4)\n\n\n\n\n```python\nk = 10\neval_map = map_at_k(data_vegan_test, all_predictions_vegan, col_prediction='prediction', k=k,col_user= 'UserId',col_item='MovieId',col_rating='Rating')\neval_ndcg = ndcg_at_k(data_vegan_test, all_predictions_vegan, col_prediction='prediction', k=k,col_user= 'UserId',col_item='MovieId',col_rating='Rating')\neval_precision = precision_at_k(data_vegan_test, all_predictions_vegan, col_prediction='prediction', k=k,col_user= 'UserId',col_item='MovieId',col_rating='Rating')\neval_recall = recall_at_k(data_vegan_test, all_predictions_vegan, col_prediction='prediction', k=k,col_user= 'UserId',col_item='MovieId',col_rating='Rating')\n\nprint(\"MAP:\\t%f\" % eval_map,\n      \"NDCG:\\t%f\" % eval_ndcg,\n      \"Precision@K:\\t%f\" % eval_precision,\n      \"Recall@K:\\t%f\" % eval_recall, sep='\\n')\n```\n\n    MAP:\t0.887861\n    NDCG:\t0.933323\n    Precision@K:\t0.550765\n    Recall@K:\t0.841412\n\n\n\n```python\nk = 10\neval_map1 = map_at_k(data_veg_test, all_predictions_veg, col_prediction='prediction', k=k,col_user= 'UserId',col_item='MovieId',col_rating='Rating')\neval_ndcg1 = ndcg_at_k(data_veg_test, all_predictions_veg, col_prediction='prediction', k=k,col_user= 'UserId',col_item='MovieId',col_rating='Rating')\neval_precision1 = precision_at_k(data_veg_test, all_predictions_veg, col_prediction='prediction', k=k,col_user= 'UserId',col_item='MovieId',col_rating='Rating')\neval_recall1 = recall_at_k(data_veg_test, all_predictions_veg, col_prediction='prediction', k=k,col_user= 'UserId',col_item='MovieId',col_rating='Rating')\n\nprint(\"MAP:\\t%f\" % eval_map1,\n      \"NDCG:\\t%f\" % eval_ndcg1,\n      \"Precision@K:\\t%f\" % eval_precision1,\n      \"Recall@K:\\t%f\" % eval_recall1, sep='\\n')\n```\n\n    MAP:\t0.903894\n    NDCG:\t0.942978\n    Precision@K:\t0.557789\n    Recall@K:\t0.864322\n\n\n\n```python\nk = 10\neval_map2 = map_at_k(data_meats_test, all_predictions_meats, col_prediction='prediction', k=k,col_user= 'UserId',col_item='MovieId',col_rating='Rating')\neval_ndcg2 = ndcg_at_k(data_meats_test, all_predictions_meats, col_prediction='prediction', k=k,col_user= 'UserId',col_item='MovieId',col_rating='Rating')\neval_precision2 = precision_at_k(data_meats_test, all_predictions_meats, col_prediction='prediction', k=k,col_user= 'UserId',col_item='MovieId',col_rating='Rating')\neval_recall2 = recall_at_k(data_meats_test, all_predictions_meats, col_prediction='prediction', k=k,col_user= 'UserId',col_item='MovieId',col_rating='Rating')\n\nprint(\"MAP:\\t%f\" % eval_map2,\n      \"NDCG:\\t%f\" % eval_ndcg2,\n      \"Precision@K:\\t%f\" % eval_precision2,\n      \"Recall@K:\\t%f\" % eval_recall2, sep='\\n')\n```\n\n    MAP:\t0.903470\n    NDCG:\t0.942701\n    Precision@K:\t0.557606\n    Recall@K:\t0.863674\n\n\n\n```python\nk = 10\neval_map3 = map_at_k(data_diet_test, all_predictions_diet, col_prediction='prediction', k=k,col_user= 'UserId',col_item='MovieId',col_rating='Rating')\neval_ndcg3 = ndcg_at_k(data_diet_test, all_predictions_diet, col_prediction='prediction', k=k,col_user= 'UserId',col_item='MovieId',col_rating='Rating')\neval_precision3 = precision_at_k(data_diet_test, all_predictions_diet, col_prediction='prediction', k=k,col_user= 'UserId',col_item='MovieId',col_rating='Rating')\neval_recall3 = recall_at_k(data_diet_test, all_predictions_diet, col_prediction='prediction', k=k,col_user= 'UserId',col_item='MovieId',col_rating='Rating')\n\nprint(\"MAP:\\t%f\" % eval_map3,\n      \"NDCG:\\t%f\" % eval_ndcg3,\n      \"Precision@K:\\t%f\" % eval_precision3,\n      \"Recall@K:\\t%f\" % eval_recall3, sep='\\n')\n```\n\n    MAP:\t0.909688\n    NDCG:\t0.946328\n    Precision@K:\t0.560345\n    Recall@K:\t0.872332\n\n\n\n```python\nk = 10\neval_map4 = map_at_k(data_keto_test, all_predictions_keto, col_prediction='prediction', k=k,col_user= 'UserId',col_item='MovieId',col_rating='Rating')\neval_ndcg4 = ndcg_at_k(data_keto_test, all_predictions_keto, col_prediction='prediction', k=k,col_user= 'UserId',col_item='MovieId',col_rating='Rating')\neval_precision4 = precision_at_k(data_keto_test, all_predictions_keto, col_prediction='prediction', k=k,col_user= 'UserId',col_item='MovieId',col_rating='Rating')\neval_recall4 = recall_at_k(data_keto_test, all_predictions_keto, col_prediction='prediction', k=k,col_user= 'UserId',col_item='MovieId',col_rating='Rating')\n\nprint(\"MAP:\\t%f\" % eval_map4,\n      \"NDCG:\\t%f\" % eval_ndcg4,\n      \"Precision@K:\\t%f\" % eval_precision4,\n      \"Recall@K:\\t%f\" % eval_recall4, sep='\\n')\n```\n\n    MAP:\t0.881641\n    NDCG:\t0.929331\n    Precision@K:\t0.548072\n    Recall@K:\t0.832048\n\n\n\n```python\n# Record results with papermill for tests\npm.record(\"map\", eval_map)\npm.record(\"ndcg\", eval_ndcg)\npm.record(\"precision\", eval_precision)\npm.record(\"recall\", eval_recall)\n```\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\ipykernel_launcher.py:2: DeprecationWarning: Function record is deprecated and will be removed in verison 1.0.0 (current version 0.19.1). Please see `scrapbook.glue` (nteract-scrapbook) as a replacement for this functionality.\n      \n\n\n\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\ipykernel_launcher.py:3: DeprecationWarning: Function record is deprecated and will be removed in verison 1.0.0 (current version 0.19.1). Please see `scrapbook.glue` (nteract-scrapbook) as a replacement for this functionality.\n      This is separate from the ipykernel package so we can avoid doing imports until\n\n\n\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\ipykernel_launcher.py:4: DeprecationWarning: Function record is deprecated and will be removed in verison 1.0.0 (current version 0.19.1). Please see `scrapbook.glue` (nteract-scrapbook) as a replacement for this functionality.\n      after removing the cwd from sys.path.\n\n\n\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\ipykernel_launcher.py:5: DeprecationWarning: Function record is deprecated and will be removed in verison 1.0.0 (current version 0.19.1). Please see `scrapbook.glue` (nteract-scrapbook) as a replacement for this functionality.\n      \"\"\"\n\n\n\n\n\n```python\n# Record results with papermill for tests\npm.record(\"map\", eval_map1)\npm.record(\"ndcg\", eval_ndcg1)\npm.record(\"precision\", eval_precision1)\npm.record(\"recall\", eval_recall1)\n```\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\ipykernel_launcher.py:2: DeprecationWarning: Function record is deprecated and will be removed in verison 1.0.0 (current version 0.19.1). Please see `scrapbook.glue` (nteract-scrapbook) as a replacement for this functionality.\n      \n\n\n\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\ipykernel_launcher.py:3: DeprecationWarning: Function record is deprecated and will be removed in verison 1.0.0 (current version 0.19.1). Please see `scrapbook.glue` (nteract-scrapbook) as a replacement for this functionality.\n      This is separate from the ipykernel package so we can avoid doing imports until\n\n\n\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\ipykernel_launcher.py:4: DeprecationWarning: Function record is deprecated and will be removed in verison 1.0.0 (current version 0.19.1). Please see `scrapbook.glue` (nteract-scrapbook) as a replacement for this functionality.\n      after removing the cwd from sys.path.\n\n\n\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\ipykernel_launcher.py:5: DeprecationWarning: Function record is deprecated and will be removed in verison 1.0.0 (current version 0.19.1). Please see `scrapbook.glue` (nteract-scrapbook) as a replacement for this functionality.\n      \"\"\"\n\n\n\n\n\n```python\n# Record results with papermill for tests\npm.record(\"map\", eval_map2)\npm.record(\"ndcg\", eval_ndcg2)\npm.record(\"precision\", eval_precision2)\npm.record(\"recall\", eval_recall2)\n```\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\ipykernel_launcher.py:2: DeprecationWarning: Function record is deprecated and will be removed in verison 1.0.0 (current version 0.19.1). Please see `scrapbook.glue` (nteract-scrapbook) as a replacement for this functionality.\n      \n\n\n\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\ipykernel_launcher.py:3: DeprecationWarning: Function record is deprecated and will be removed in verison 1.0.0 (current version 0.19.1). Please see `scrapbook.glue` (nteract-scrapbook) as a replacement for this functionality.\n      This is separate from the ipykernel package so we can avoid doing imports until\n\n\n\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\ipykernel_launcher.py:4: DeprecationWarning: Function record is deprecated and will be removed in verison 1.0.0 (current version 0.19.1). Please see `scrapbook.glue` (nteract-scrapbook) as a replacement for this functionality.\n      after removing the cwd from sys.path.\n\n\n\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\ipykernel_launcher.py:5: DeprecationWarning: Function record is deprecated and will be removed in verison 1.0.0 (current version 0.19.1). Please see `scrapbook.glue` (nteract-scrapbook) as a replacement for this functionality.\n      \"\"\"\n\n\n\n\n\n```python\n# Record results with papermill for tests\npm.record(\"map\", eval_map3)\npm.record(\"ndcg\", eval_ndcg3)\npm.record(\"precision\", eval_precision3)\npm.record(\"recall\", eval_recall3)\n```\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\ipykernel_launcher.py:2: DeprecationWarning: Function record is deprecated and will be removed in verison 1.0.0 (current version 0.19.1). Please see `scrapbook.glue` (nteract-scrapbook) as a replacement for this functionality.\n      \n\n\n\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\ipykernel_launcher.py:3: DeprecationWarning: Function record is deprecated and will be removed in verison 1.0.0 (current version 0.19.1). Please see `scrapbook.glue` (nteract-scrapbook) as a replacement for this functionality.\n      This is separate from the ipykernel package so we can avoid doing imports until\n\n\n\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\ipykernel_launcher.py:4: DeprecationWarning: Function record is deprecated and will be removed in verison 1.0.0 (current version 0.19.1). Please see `scrapbook.glue` (nteract-scrapbook) as a replacement for this functionality.\n      after removing the cwd from sys.path.\n\n\n\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\ipykernel_launcher.py:5: DeprecationWarning: Function record is deprecated and will be removed in verison 1.0.0 (current version 0.19.1). Please see `scrapbook.glue` (nteract-scrapbook) as a replacement for this functionality.\n      \"\"\"\n\n\n\n\n\n```python\n# Record results with papermill for tests\npm.record(\"map\", eval_map4)\npm.record(\"ndcg\", eval_ndcg4)\npm.record(\"precision\", eval_precision4)\npm.record(\"recall\", eval_recall4)\n```\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\ipykernel_launcher.py:2: DeprecationWarning: Function record is deprecated and will be removed in verison 1.0.0 (current version 0.19.1). Please see `scrapbook.glue` (nteract-scrapbook) as a replacement for this functionality.\n      \n\n\n\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\ipykernel_launcher.py:3: DeprecationWarning: Function record is deprecated and will be removed in verison 1.0.0 (current version 0.19.1). Please see `scrapbook.glue` (nteract-scrapbook) as a replacement for this functionality.\n      This is separate from the ipykernel package so we can avoid doing imports until\n\n\n\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\ipykernel_launcher.py:4: DeprecationWarning: Function record is deprecated and will be removed in verison 1.0.0 (current version 0.19.1). Please see `scrapbook.glue` (nteract-scrapbook) as a replacement for this functionality.\n      after removing the cwd from sys.path.\n\n\n\n\n    C:\\Users\\singh\\AppData\\Local\\Continuum\\anaconda3\\envs\\reco_base\\lib\\site-packages\\ipykernel_launcher.py:5: DeprecationWarning: Function record is deprecated and will be removed in verison 1.0.0 (current version 0.19.1). Please see `scrapbook.glue` (nteract-scrapbook) as a replacement for this functionality.\n      \"\"\"\n\n\n\n\n\n```python\n\n```\n\n# Evaluation\n\nEvaluation with offline metrics is pivotal to assess the quality of a recommender before it goes into production. Usually, evaluation metrics are carefully chosen based on the actual application scenario of a recommendation system. It is hence important to data scientists and AI developers that build recommendation systems to understand how each evaluation metric is calculated and what it is for.\n\nThis notebook deep dives into several commonly used evaluation metrics, and illustrates how these metrics are used in practice. The metrics covered in this notebook are merely for off-line evaluations.\n\n\n```python\nfrom sklearn.preprocessing import minmax_scale\n\nfrom reco_utils.common.spark_utils import start_or_get_spark\nfrom reco_utils.evaluation.spark_evaluation import SparkRankingEvaluation, SparkRatingEvaluation\nfrom reco_utils.evaluation.python_evaluation import auc, logloss\n\nprint(\"System version: {}\".format(sys.version))\nprint(\"Pandas version: {}\".format(pd.__version__))\nprint(\"PySpark version: {}\".format(pyspark.__version__))\n```\n\n    System version: 3.6.10 |Anaconda, Inc.| (default, Jan  7 2020, 15:18:16) [MSC v.1916 64 bit (AMD64)]\n    Pandas version: 0.25.3\n    PySpark version: 2.4.5\n\n\n\n```python\nall_predictions_vegan.rename(columns={\"prediction\":\"Rating\"},inplace=True)\n```\n\n\n```python\n# all_predictions_vegan.rename(columns={\"rating\":\"Rating\"},inplace=True)\n```\n\n\n```python\nall_predictions_veg.rename(columns={\"prediction\":\"Rating\"},inplace=True)\n```\n\n\n```python\nall_predictions_meats.rename(columns={\"prediction\":\"Rating\"},inplace=True)\n```\n\n\n```python\nall_predictions_diet.rename(columns={\"prediction\":\"Rating\"},inplace=True)\n```\n\n\n```python\nall_predictions_keto.rename(columns={\"prediction\":\"Rating\"},inplace=True)\n```\n\n## 2 Evaluation metrics\n\n### 2.1 Rating metrics\n\nRating metrics are similar to regression metrics used for evaluating a regression model that predicts numerical values given input observations. In the context of recommendation system, rating metrics are to evaluate how accurate a recommender is to predict ratings that users may give to items. Therefore, the metrics are **calculated exactly on the same group of (user, item) pairs that exist in both ground-truth dataset and prediction dataset** and **averaged by the total number of users**.\n\n#### 2.1.1 Use cases\n\nRating metrics are effective in measuring the model accuracy. However, in some cases, the rating metrics are limited if\n* **the recommender is to predict ranking instead of explicit rating**. For example, if the consumer of the recommender cares about the ranked recommended items, rating metrics do not apply directly. Usually a relevancy function such as top-k will be applied to generate the ranked list from predicted ratings in order to evaluate the recommender with other metrics. \n* **the recommender is to generate recommendation scores that have different scales with the original ratings (e.g., the SAR algorithm)**. In this case, the difference between the generated scores and the original scores (or, ratings) is not valid for measuring accuracy of the model.\n\n#### 2.1.2 How-to with the evaluation utilities\n\nA few notes about the interface of the Rating evaluator class:\n1. The columns of user, item, and rating (prediction) should be present in the ground-truth DataFrame (prediction DataFrame).\n2. There should be no duplicates of (user, item) pairs in the ground-truth and the prediction DataFrames, othewise there may be unexpected behavior in calculating certain metrics.\n3. Default column names for user, item, rating, and prediction are \"UserId\", \"ItemId\", \"Rating\", and \"Prediciton\", respectively.\n\nIn our examples below, to calculate rating metrics for input data frames in Spark, a Spark object, `SparkRatingEvaluation` is initialized. The input data schemas for the ground-truth dataset and the prediction dataset are\n\n* Ground-truth dataset.\n\n|Column|Data type|Description|\n|-------------|------------|-------------|\n|`COL_USER`|<int\\>|User ID|\n|`COL_ITEM`|<int\\>|Item ID|\n|`COL_RATING`|<float\\>|Rating or numerical value of user preference.|\n\n* Prediction dataset.\n\n|Column|Data type|Description|\n|-------------|------------|-------------|\n|`COL_USER`|<int\\>|User ID|\n|`COL_ITEM`|<int\\>|Item ID|\n|`COL_RATING`|<float\\>|Predicted rating or numerical value of user preference.|\n\n\n```python\nspark = start_or_get_spark(\"EvaluationTesting\", \"local\")\n\n```\n\n\n```python\nCOL_USER = \"UserId\"\nCOL_ITEM = \"MovieId\"\nCOL_RATING = \"Rating\"\nCOL_PREDICTION = \"Rating\"\n\nHEADER = {\n    \"col_user\": COL_USER,\n    \"col_item\": COL_ITEM,\n    \"col_rating\": COL_RATING,\n    \"col_prediction\": COL_PREDICTION,\n}\n```\n\n\n```python\ndata_vegan_train.shape\n```\n\n\n\n\n    (7000, 3)\n\n\n\n\n```python\ndata_vegan_train\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>UserId</th>\n      <th>MovieId</th>\n      <th>Rating</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>7221</th>\n      <td>2</td>\n      <td>8.708580e+11</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>7238</th>\n      <td>2</td>\n      <td>6.489750e+11</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>7236</th>\n      <td>2</td>\n      <td>3.858572e+10</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>7222</th>\n      <td>2</td>\n      <td>4.668540e+11</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>7229</th>\n      <td>2</td>\n      <td>2.613010e+11</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>9177</th>\n      <td>1000</td>\n      <td>6.507020e+11</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>9174</th>\n      <td>1000</td>\n      <td>8.234320e+11</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>9163</th>\n      <td>1000</td>\n      <td>6.487340e+11</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>9170</th>\n      <td>1000</td>\n      <td>2.461627e+10</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>9180</th>\n      <td>1000</td>\n      <td>5.123240e+11</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n<p>7000 rows \u00d7 3 columns</p>\n</div>\n\n\n\n\n```python\nall_predictions_veg.dtypes\n```\n\n\n\n\n    UserId       int64\n    MovieId    float64\n    Rating     float64\n    dtype: object\n\n\n\n\n```python\ndata_vegan\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>UserId</th>\n      <th>MovieId</th>\n      <th>Rating</th>\n      <th>Name</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>482</td>\n      <td>8.708580e+11</td>\n      <td>1</td>\n      <td>Sawyer and Sons</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>482</td>\n      <td>4.668540e+11</td>\n      <td>4</td>\n      <td>Drake, Chavez and Walters</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>482</td>\n      <td>6.487340e+11</td>\n      <td>4</td>\n      <td>Melendez-Nunez</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>482</td>\n      <td>5.750330e+11</td>\n      <td>5</td>\n      <td>Hall LLC</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>482</td>\n      <td>5.798643e+10</td>\n      <td>1</td>\n      <td>Short Inc</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>9996</th>\n      <td>518</td>\n      <td>3.858572e+10</td>\n      <td>4</td>\n      <td>Grimes-Thomas</td>\n    </tr>\n    <tr>\n      <th>9997</th>\n      <td>518</td>\n      <td>6.507020e+11</td>\n      <td>2</td>\n      <td>Stone, Trevino and Cooper</td>\n    </tr>\n    <tr>\n      <th>9998</th>\n      <td>518</td>\n      <td>6.489750e+11</td>\n      <td>5</td>\n      <td>Ford Inc</td>\n    </tr>\n    <tr>\n      <th>9999</th>\n      <td>518</td>\n      <td>2.688080e+11</td>\n      <td>4</td>\n      <td>West-Dixon</td>\n    </tr>\n    <tr>\n      <th>10000</th>\n      <td>518</td>\n      <td>5.123240e+11</td>\n      <td>4</td>\n      <td>Ramirez PLC</td>\n    </tr>\n  </tbody>\n</table>\n<p>10000 rows \u00d7 4 columns</p>\n</div>\n\n\n\n\n```python\ndfs_vegan_true = spark.createDataFrame(data_vegan[['UserId', 'MovieId', 'Rating']])\n```\n\n\n```python\ndfs_vegan_pred = spark.createDataFrame(all_predictions_vegan)\n```\n\n\n```python\ndfs_veg_true = spark.createDataFrame(data_veg[['UserId', 'MovieId', 'Rating']])\n```\n\n\n```python\ndfs_veg_pred = spark.createDataFrame(all_predictions_veg)\n```\n\n\n```python\ndfs_keto_true = spark.createDataFrame(data_keto[['UserId', 'MovieId', 'Rating']])\n```\n\n\n```python\ndfs_keto_pred = spark.createDataFrame(all_predictions_keto)\n```\n\n\n```python\ndfs_meats_true = spark.createDataFrame(data_meats[['UserId', 'MovieId', 'Rating']])\n```\n\n\n```python\ndfs_meats_pred = spark.createDataFrame(all_predictions_meats)\n```\n\n\n```python\ndfs_diet_true = spark.createDataFrame(data_diet[['UserId', 'MovieId', 'Rating']])\n```\n\n\n```python\ndfs_diet_pred = spark.createDataFrame(all_predictions_diet)\n```\n\n\n```python\ndfs_vegan_pred\n```\n\n\n\n\n    DataFrame[UserId: bigint, MovieId: double, Rating: double]\n\n\n\n\n```python\n# dfs_pred =dfs_pred.withColumn(\"UserId\",dfs_pred.UserId.cast(\"Long\")).withColumn(\"MovieId\", dfs_pred.MovieId.cast(\"Long\"))\n```\n\n\n```python\n# dfs_true =dfs_true.withColumn(\"UserId\",dfs_true.UserId.cast(\"Long\")).withColumn(\"MovieId\", dfs_true.MovieId.cast(\"Long\")).withColumn(\"Rating\", dfs_true.Rating.cast(\"Double\"))\n```\n\n\n```python\ndfs_vegan_true\n```\n\n\n\n\n    DataFrame[UserId: bigint, MovieId: double, Rating: bigint]\n\n\n\n\n```python\nspark_rate_eval_vegan = SparkRatingEvaluation(dfs_vegan_true, dfs_vegan_pred, **HEADER)\n```\n\n\n```python\nspark_rate_eval_keto = SparkRatingEvaluation(dfs_keto_true, dfs_keto_pred, **HEADER)\n```\n\n\n```python\nspark_rate_eval_veg = SparkRatingEvaluation(dfs_veg_true, dfs_veg_pred, **HEADER)\n```\n\n\n```python\nspark_rate_eval_diet = SparkRatingEvaluation(dfs_diet_true, dfs_diet_pred, **HEADER)\n```\n\n\n```python\nspark_rate_eval_meats = SparkRatingEvaluation(dfs_meats_true, dfs_meats_pred, **HEADER)\n```\n\n\n```python\nspark_rate_eval_vegan\n```\n\n\n\n\n    <reco_utils.evaluation.spark_evaluation.SparkRatingEvaluation at 0x2605e0f36d8>\n\n\n\n#### 2.1.3 Root Mean Square Error (RMSE)\n\nRMSE is for evaluating the accuracy of prediction on ratings. RMSE is the most widely used metric to evaluate a recommendation algorithm that predicts missing ratings. The benefit is that RMSE is easy to explain and calculate.\n\n\n```python\nprint(\"The RMSE is {}\".format(spark_rate_eval_vegan.rmse()))\n```\n\n    The RMSE is 6.0934722348957395\n\n\n#### 2.1.4 R Squared (R2)\n\nR2 is also called \"coefficient of determination\" in some context. It is a metric that evaluates how well a regression model performs, based on the proportion of total variations of the observed results. \n\n\n```python\nprint(\"The R2 is {}\".format(spark_rate_eval_vegan.rsquared()))\n```\n\n    The R2 is -17.644272059816828\n\n\n#### 2.1.5 Mean Absolute Error (MAE)\n\nMAE evaluates accuracy of prediction. It computes the metric value from ground truths and prediction in the same scale. Compared to RMSE, MAE is more explainable. \n\n\n```python\nprint(\"The MAE is {}\".format(spark_rate_eval_vegan.mae()))\n```\n\n    The MAE is 5.901628110954653\n\n\n#### 2.1.6 Explained Variance \n\nExplained variance is usually used to measure how well a model performs with regard to the impact from the variation of the dataset. \n\n\n```python\nprint(\"The explained variance is {}\".format(spark_rate_eval_vegan.exp_var()))\n```\n\n    The explained variance is -0.1554930648209485\n\n\n#### 2.1.7 Summary\n\n|Metric|Range|Selection criteria|Limitation|Reference|\n|------|-------------------------------|---------|----------|---------|\n|RMSE|$> 0$|The smaller the better.|May be biased, and less explainable than MSE|[link](https://en.wikipedia.org/wiki/Root-mean-square_deviation)|\n|R2|$\\leq 1$|The closer to $1$ the better.|Depend on variable distributions.|[link](https://en.wikipedia.org/wiki/Coefficient_of_determination)|\n|MSE|$\\geq 0$|The smaller the better.|Dependent on variable scale.|[link](https://en.wikipedia.org/wiki/Mean_absolute_error)|\n|Explained variance|$\\leq 1$|The closer to $1$ the better.|Depend on variable distributions.|[link](https://en.wikipedia.org/wiki/Explained_variation)|\n\n### 2.2 Ranking metrics\n\n\"Beyond-accuray evaluation\" was proposed to evaluate how relevant recommendations are for users. In this case, a recommendation system is a treated as a ranking system. Given a relency definition, recommendation system outputs a list of recommended items to each user, which is ordered by relevance. The evaluation part takes ground-truth data, the actual items that users interact with (e.g., liked, purchased, etc.), and the recommendation data, as inputs, to calculate ranking evaluation metrics. \n\n#### 2.2.1 Use cases\n\nRanking metrics are often used when hit and/or ranking of the items are considered:\n* **Hit** - defined by relevancy, a hit usually means whether the recommended \"k\" items hit the \"relevant\" items by the user. For example, a user may have clicked, viewed, or purchased an item for many times, and a hit in the recommended items indicate that the recommender performs well. Metrics like \"precision\", \"recall\", etc. measure the performance of such hitting accuracy.\n* **Ranking** - ranking metrics give more explanations about, for the hitted items, whether they are ranked in a way that is preferred by the users whom the items will be recommended to. Metrics like \"mean average precision\", \"ndcg\", etc., evaluate whether the relevant items are ranked higher than the less-relevant or irrelevant items. \n\n#### 2.2.2 How-to with evaluation utilities\n\nA few notes about the interface of the Rating evaluator class:\n1. The columns of user, item, and rating (prediction) should be present in the ground-truth DataFrame (prediction DataFrame). The column of timestamp is optional, but it is required if certain relevanc function is used. For example, timestamps will be used if the most recent items are defined as the relevant one.\n2. There should be no duplicates of (user, item) pairs in the ground-truth and the prediction DataFrames, othewise there may be unexpected behavior in calculating certain metrics.\n3. Default column names for user, item, rating, and prediction are \"UserId\", \"ItemId\", \"Rating\", and \"Prediciton\", respectively.\n\n\n```python\nspark_rate_eval_vegan = SparkRankingEvaluation(dfs_vegan_true, dfs_vegan_pred, k=3, relevancy_method=\"top_k\", **HEADER)\n```\n\n\n```python\nprint(\"The precision at k is {}\".format(spark_rate_eval_vegan.precision_at_k()))\n```\n\n    The precision at k is 0.9124149659863943\n\n\n#### 2.2.2 Recall\n\nRecall@k is a metric that evaluates how many relevant items in the ground-truth data are in the recommendation list. For each user the recall score is normalized by the total number of ground-truth items and then the overall recall scores are averaged by the total number of users. \n\n\n```python\nprint(\"The recall at k is {}\".format(spark_rate_eval_vegan.recall_at_k()))\n```\n\n    The recall at k is 0.12593537414965988\n\n\n#### 2.2.3 Normalized Discounted Cumulative Gain (NDCG)\n\nNDCG is a metric that evaluates how well the recommender performs in recommending ranked items to users. Therefore both hit of relevant items and correctness in ranking of these items matter to the NDCG evaluation. The total NDCG score is normalized by the total number of users.\n\n\n```python\nprint(\"The ndcg at k is {}\".format(spark_rate_eval_vegan.ndcg_at_k()))\n```\n\n    The ndcg at k is 0.9363096747102544\n\n\n#### 2.2.4 Mean Average Precision (MAP)\n\nMAP is a metric that evaluates the average precision for each user in the datasets. It also penalizes ranking correctness of the recommended items. The overall MAP score is normalized by the total number of users.\n\n\n```python\nprint(\"The map at k is {}\".format(spark_rate_eval_vegan.map_at_k()))\n```\n\n    The map at k is 0.1368622448979592\n\n\n#### 2.2.5 ROC and AUC\n\nROC, as well as AUC, is a well known metric that is used for evaluating binary classification problem. It is similar in the case of binary rating typed recommendation algorithm where the \"hit\" accuracy on the relevant items is used for measuring the recommender's performance. \n\nTo demonstrate the evaluation method, the original data for testing is manipuldated in a way that the ratings in the testing data are arranged as binary scores, whilst the ones in the prediction are scaled in 0 to 1. \n\n\n```python\n# Convert the original rating to 0 and 1.\ndf_true_vegan_bin = data_vegan.copy()\ndf_true_vegan_bin[COL_RATING] = df_true_vegan_bin[COL_RATING].apply(lambda x: 1 if x > 3 else 0)\n\ndf_true_vegan_bin\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>UserId</th>\n      <th>MovieId</th>\n      <th>Rating</th>\n      <th>Name</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>482</td>\n      <td>8.708580e+11</td>\n      <td>0</td>\n      <td>Sawyer and Sons</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>482</td>\n      <td>4.668540e+11</td>\n      <td>1</td>\n      <td>Drake, Chavez and Walters</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>482</td>\n      <td>6.487340e+11</td>\n      <td>1</td>\n      <td>Melendez-Nunez</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>482</td>\n      <td>5.750330e+11</td>\n      <td>1</td>\n      <td>Hall LLC</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>482</td>\n      <td>5.798643e+10</td>\n      <td>0</td>\n      <td>Short Inc</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>9996</th>\n      <td>518</td>\n      <td>3.858572e+10</td>\n      <td>1</td>\n      <td>Grimes-Thomas</td>\n    </tr>\n    <tr>\n      <th>9997</th>\n      <td>518</td>\n      <td>6.507020e+11</td>\n      <td>0</td>\n      <td>Stone, Trevino and Cooper</td>\n    </tr>\n    <tr>\n      <th>9998</th>\n      <td>518</td>\n      <td>6.489750e+11</td>\n      <td>1</td>\n      <td>Ford Inc</td>\n    </tr>\n    <tr>\n      <th>9999</th>\n      <td>518</td>\n      <td>2.688080e+11</td>\n      <td>1</td>\n      <td>West-Dixon</td>\n    </tr>\n    <tr>\n      <th>10000</th>\n      <td>518</td>\n      <td>5.123240e+11</td>\n      <td>1</td>\n      <td>Ramirez PLC</td>\n    </tr>\n  </tbody>\n</table>\n<p>10000 rows \u00d7 4 columns</p>\n</div>\n\n\n\n\n```python\n# Convert the predicted ratings into a [0, 1] scale.\ndf_pred_vegan_bin = all_predictions_vegan.copy()\ndf_pred_vegan_bin[COL_PREDICTION] = minmax_scale(df_pred_vegan_bin[COL_PREDICTION].astype(float))\n\ndf_pred_vegan_bin\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>UserId</th>\n      <th>MovieId</th>\n      <th>Rating</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>7000</th>\n      <td>2</td>\n      <td>3.592860e+11</td>\n      <td>0.012523</td>\n    </tr>\n    <tr>\n      <th>7001</th>\n      <td>2</td>\n      <td>8.890040e+11</td>\n      <td>0.021797</td>\n    </tr>\n    <tr>\n      <th>7002</th>\n      <td>2</td>\n      <td>4.463170e+11</td>\n      <td>0.007520</td>\n    </tr>\n    <tr>\n      <th>7003</th>\n      <td>2</td>\n      <td>2.452430e+11</td>\n      <td>0.033544</td>\n    </tr>\n    <tr>\n      <th>7004</th>\n      <td>2</td>\n      <td>5.798643e+10</td>\n      <td>0.014312</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>8974</th>\n      <td>1000</td>\n      <td>8.890040e+11</td>\n      <td>0.022347</td>\n    </tr>\n    <tr>\n      <th>8975</th>\n      <td>1000</td>\n      <td>4.463170e+11</td>\n      <td>0.008093</td>\n    </tr>\n    <tr>\n      <th>8976</th>\n      <td>1000</td>\n      <td>2.452430e+11</td>\n      <td>0.034104</td>\n    </tr>\n    <tr>\n      <th>8977</th>\n      <td>1000</td>\n      <td>5.798643e+10</td>\n      <td>0.014844</td>\n    </tr>\n    <tr>\n      <th>8978</th>\n      <td>1000</td>\n      <td>1.312350e+11</td>\n      <td>0.001710</td>\n    </tr>\n  </tbody>\n</table>\n<p>1979 rows \u00d7 3 columns</p>\n</div>\n\n\n\n\n```python\n# Calculate the AUC metric\nauc_score = auc(\n    df_true_vegan_bin,\n    df_pred_vegan_bin,\n    col_user = COL_USER,\n    col_item = COL_ITEM,\n    col_rating = COL_RATING,\n    col_prediction = COL_RATING\n)\n```\n\n\n```python\nprint(\"The auc score is {}\".format(auc_score))\n```\n\n    The auc score is 0.4913505716043757\n\n\nIt is worth mentioning that in some literature there are variants of the original AUC metric, that considers the effect of **the number of the recommended items (k)**, **grouping effect of users (compute AUC for each user group, and take the average across different groups)**. These variants are applicable to various different scenarios, and choosing an appropriate one depends on the context of the use case itself.\n\n#### 2.3.2 Logistic loss\n\n\nLogistic loss (sometimes it is called simply logloss, or cross-entropy loss) is another useful metric to evaluate the hit accuracy. It is defined as the negative log-likelihood of the true labels given the predictions of a classifier.\n\n\n```python\n# Calculate the logloss metric\nlogloss_score = logloss(\n    df_true_vegan_bin,\n    df_pred_vegan_bin,\n    col_user = COL_USER,\n    col_item = COL_ITEM,\n    col_rating = COL_RATING,\n    col_prediction = COL_RATING\n)\n\nprint(\"The logloss score is {}\".format(logloss_score))\n```\n\n    The logloss score is 1.806747584978363\n\n\nFor comparison, a similar process is used with a threshold value of 3 to create a more balanced dataset. Another prediction dataset is also created by using the balanced dataset. Again, the probabilities of predicting label 1 and label 0 are fixed as 0.6 and 0.4, respectively. **NOTE**, same as above, in this case, the prediction also gives us a 100% precision. The only difference is the proportion of binary labels.\n\n\n```python\nprob_true = 0.6\n\ndf_pred_bin_balanced_vegan = df_true_vegan_bin.copy()\ndf_pred_bin_balanced_vegan[COL_PREDICTION] = df_pred_bin_balanced_vegan[COL_PREDICTION].apply(lambda x: prob_true if x==1 else 1-prob_true)\n\ndf_pred_bin_balanced_vegan\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>UserId</th>\n      <th>MovieId</th>\n      <th>Rating</th>\n      <th>Name</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>482</td>\n      <td>8.708580e+11</td>\n      <td>0.4</td>\n      <td>Sawyer and Sons</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>482</td>\n      <td>4.668540e+11</td>\n      <td>0.6</td>\n      <td>Drake, Chavez and Walters</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>482</td>\n      <td>6.487340e+11</td>\n      <td>0.6</td>\n      <td>Melendez-Nunez</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>482</td>\n      <td>5.750330e+11</td>\n      <td>0.6</td>\n      <td>Hall LLC</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>482</td>\n      <td>5.798643e+10</td>\n      <td>0.4</td>\n      <td>Short Inc</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>9996</th>\n      <td>518</td>\n      <td>3.858572e+10</td>\n      <td>0.6</td>\n      <td>Grimes-Thomas</td>\n    </tr>\n    <tr>\n      <th>9997</th>\n      <td>518</td>\n      <td>6.507020e+11</td>\n      <td>0.4</td>\n      <td>Stone, Trevino and Cooper</td>\n    </tr>\n    <tr>\n      <th>9998</th>\n      <td>518</td>\n      <td>6.489750e+11</td>\n      <td>0.6</td>\n      <td>Ford Inc</td>\n    </tr>\n    <tr>\n      <th>9999</th>\n      <td>518</td>\n      <td>2.688080e+11</td>\n      <td>0.6</td>\n      <td>West-Dixon</td>\n    </tr>\n    <tr>\n      <th>10000</th>\n      <td>518</td>\n      <td>5.123240e+11</td>\n      <td>0.6</td>\n      <td>Ramirez PLC</td>\n    </tr>\n  </tbody>\n</table>\n<p>10000 rows \u00d7 4 columns</p>\n</div>\n\n\n\nThe ratio of label 1 and label 0 is\n\n\n\n```python\none_zero_ratio = df_true_bin[COL_PREDICTION].sum() / (df_true_bin.shape[0] - df_true_bin[COL_PREDICTION].sum())\n\nprint('The ratio between label 1 and label 0 is {}'.format(one_zero_ratio))\n```\n\n    The ratio between label 1 and label 0 is 1.2408963585434174\n\n\nApplying the logloss function to calculate the metric gives us a more promising result, as shown below.\n\n\n```python\n# Calculate the logloss metric\nlogloss_score = logloss(\n    df_true_vegan_bin,\n    df_pred_bin_balanced_vegan,\n    col_user = COL_USER,\n    col_item = COL_ITEM,\n    col_rating = COL_RATING,\n    col_prediction = COL_RATING\n)\n\nprint(\"The logloss score is {}\".format(logloss_score))\n```\n\n    The logloss score is 0.5760127668115718\n\n\nIt can be seen that the score is more close to 0, and, by definition, it means that the predictions are generating better results than the one before where binary labels are more biased.\n\n#### 2.2.5 Summary\n\n|Metric|Range|Selection criteria|Limitation|Reference|\n|------|-------------------------------|---------|----------|---------|\n|Precision|$\\geq 0$ and $\\leq 1$|The closer to $1$ the better.|Only for hits in recommendations.|[link](https://spark.apache.org/docs/2.3.0/mllib-evaluation-metrics.html#ranking-systems)|\n|Recall|$\\geq 0$ and $\\leq 1$|The closer to $1$ the better.|Only for hits in the ground truth.|[link](https://en.wikipedia.org/wiki/Precision_and_recall)|\n|NDCG|$\\geq 0$ and $\\leq 1$|The closer to $1$ the better.|Does not penalize for bad/missing items, and does not perform for several equally good items.|[link](https://spark.apache.org/docs/2.3.0/mllib-evaluation-metrics.html#ranking-systems)|\n|MAP|$\\geq 0$ and $\\leq 1$|The closer to $1$ the better.|Depend on variable distributions.|[link](https://spark.apache.org/docs/2.3.0/mllib-evaluation-metrics.html#ranking-systems)|\n|AUC|$\\geq 0$ and $\\leq 1$|The closer to $1$ the better. 0.5 indicates an uninformative classifier|Depend on the number of recommended items (k).|[link](https://en.wikipedia.org/wiki/Receiver_operating_characteristic#Area_under_the_curve)|\n|Logloss|$0$ to $\\infty$|The closer to $0$ the better.|Logloss can be sensitive to imbalanced datasets.|[link](https://en.wikipedia.org/wiki/Cross_entropy#Relation_to_log-likelihood)|\n\n\n```python\nspark.stop()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "821176f292354a78762209dd1e8e5e1f968c2014", "size": 145712, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Assignment 4/Recommender_system.ipynb", "max_stars_repo_name": "shubh1646/INFO7374DigitalMarketingAnalytics", "max_stars_repo_head_hexsha": "ec7e987ced3dafde2f10f84d3ac04b93672e9dd8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assignment 4/Recommender_system.ipynb", "max_issues_repo_name": "shubh1646/INFO7374DigitalMarketingAnalytics", "max_issues_repo_head_hexsha": "ec7e987ced3dafde2f10f84d3ac04b93672e9dd8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignment 4/Recommender_system.ipynb", "max_forks_repo_name": "shubh1646/INFO7374DigitalMarketingAnalytics", "max_forks_repo_head_hexsha": "ec7e987ced3dafde2f10f84d3ac04b93672e9dd8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0951771233, "max_line_length": 511, "alphanum_fraction": 0.4764878665, "converted": true, "num_tokens": 24964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30074557894124154, "lm_q2_score": 0.09807933335661013, "lm_q1q2_score": 0.029496925892504737}}
{"text": "## Arno's Engram keyboard layout\n\nEngram is a key layout optimized for comfortable and efficient touch typing in English \ncreated by [Arno Klein](https://binarybottle.com), \nwith [open source code](https://github.com/binarybottle/engram) to create other optimized key layouts.\nYou can install the Engram layout on [Windows, macOS, and Linux](https://keyman.com/keyboards/engram)\nor [try it out online](https://keymanweb.com/#en,Keyboard_engram).\nAn article is under review (see the [preprint](https://www.preprints.org/manuscript/202103.0287/v1) for an earlier (and superceded) version with description).\n\nLetters are optimally arranged according to ergonomics factors that promote reduction of lateral finger movements and more efficient typing of high-frequency letter pairs. The most common punctuation marks are logically grouped together in the middle columns and numbers are paired with mathematical and logic symbols (shown as pairs of default and Shift-key-accessed characters):\n\n         [{ 1| 2= 3~ 4+  5<  6>  7^ 8& 9% 0* ]} /\\\n            bB yY oO uU  '(  \")  lL dD wW vV zZ #$ @`\n            cC iI eE aA  ,;  .:  hH tT sS nN qQ \n            gG xX jJ kK  -_  ?!  rR mM fF pP\n            \nLetter frequencies (Norvig, 2012), showing that the Engram layout emphasizes keys in the home row:\n\n          B   Y   O   U           L   D   W   V    Z\n          C   I   E   A           H   T   S   N    Q\n          G   X   J   K           R   M   F   P\n\n         53  59 272  97          145 136  60  38   3\n        119 270 445 287          180 331 232 258   4\n         67   8   6  19          224  90  86  76\n            \nSee below for a full description and comparisons with other key layouts.\n\n### Standard diagonal keyboard (default and Shift-key layers)\n\n\n### \"Ergonomic\" orthonormal keyboard (default and Shift-key layers)\n\n\n(c) 2021 Arno Klein, MIT license\n\n----------------\n\n# Contents\n1. [Why a new keyboard layout?](#why)\n2. [How does Engram compare with other key layouts?](#scores)\n3. [Guiding criteria](#criteria)\n4. Setup:\n    - [Dependencies and functions](#import)\n    - [Speed matrix](#speed)\n    - [Strength matrix](#strength)\n    - [Flow matrix and Engram scoring model](#flow)\n5. Steps:\n    - [Step 1: Define the shape of the key layout to minimize lateral finger movements](#step1)\n    - [Step 2: Arrange the most frequent letters based on comfort and bigram frequencies](#step2)\n    - [Step 3: Optimize assignment of the remaining letters](#step3)\n    - [Step 4: Evaluate winning layout](#step4)\n    - [Step 5: Arrange non-letter characters in easy-to-remember places](#step5)\n\n## Why a new keyboard layout? <a name=\"why\">\n\n**Personal history** <br>\nIn the future, I hope to include an engaging rationale for why I took on this challenge.\nSuffice to say I love solving problems, and I have battled repetitive strain injury \never since I worked on an old DEC workstation at the MIT Media Lab while composing \nmy thesis back in the 1990s.\nI have experimented with a wide variety of human interface technologies over the years --\nvoice dictation, one-handed keyboard, keyless keyboard, foot mouse, and ergonomic keyboards \nlike the Kinesis Advantage and [Ergodox](https://configure.ergodox-ez.com/ergodox-ez/layouts/APXBR/latest/0) keyboards with different key switches.\nWhile these technologies can significantly improve comfort and reduce strain, \nif you have to type on a keyboard, it can only help to use a key layout optimized according to sound ergonomics principles. \n\nI have used different key layouts (Qwerty, Dvorak, Colemak, etc.)\nfor communications and for writing and programming projects,\nand have primarily relied on Colemak for the last 10 years. \n**I find that most to all of these key layouts:**\n\n- Demand too much strain on tendons\n    - *strenuous lateral extension of the index and little fingers*\n- Ignore the ergonomics of the human hand\n    - *different finger strengths*\n    - *different finger lengths*\n    - *natural roundedness of the hand*\n    - *easier for shorter fingers to reach below than above longer fingers*\n    - *easier for longer fingers to reach above than below shorter fingers*\n    - *ease of little-to-index finger rolls vs. reverse*\n- Over-emphasize alternation between hands and under-emphasize same-hand, different-finger transitions\n    - *same-row, adjacent finger transitions are easy and comfortable*\n    - *little-to-index finger rolls are easy and comfortable*\n\nWhile I used ergonomics principles outlined below and the accompanying code to help generate the Engram layout,\nI also relied on massive bigram frequency data for the English language. \nif one were to follow the procedure below and use a different set of bigram frequencies for another language or text corpus,\nthey could create a variant of the Engram layout, say \"Engram-French\", better suited to the French language.\n    \n**Why \"Engram\"?** <br>\nThe name is a pun, referring both to \"n-gram\", letter permutations and their frequencies that are used to compute the Engram layout, and \"engram\", or memory trace, the postulated change in neural tissue to account for the persistence of memory, as a nod to my attempt to make this layout easy to remember.\n\n## How does Engram compare with other key layouts? <a name=\"scores\">\n\nBelow we compare the Engram layout with different prominent key layouts (Colemak, Dvorak, QWERTY, etc.) for some large, representative, publicly available data (all text sources are listed below and available on [GitHub](https://github.com/binarybottle/text_data)).\n \n#### Engram Scoring Model scores (x100) for layouts, based on publicly available text data\n \nEngram scores higher for all text and software sources than all other layouts according to its own scoring model (higher scores are better):\n    \n| Layout | Google bigrams | Alice | Memento | Tweets_100K | Tweets_20K | Tweets_MASC | Spoken_MASC | COCA_blogs | iweb | Monkey | Coder | Rosetta |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Engram | 62.48 | 61.67 | 62.30 | 63.03 | 60.28 | 62.49 | 61.56 | 62.19 | 62.38 | 62.23 | 62.51 | 62.48 |\n| Halmak | 62.40 | 61.60 | 62.23 | 62.93 | 60.26 | 62.43 | 61.51 | 62.13 | 62.31 | 62.16 | 62.46 | 62.40 |\n| Hieamtsrn | 62.39 | 61.64 | 62.27 | 62.99 | 60.27 | 62.47 | 61.53 | 62.16 | 62.35 | 62.20 | 62.49 | 62.39 |\n| Norman | 62.35 | 61.57 | 62.20 | 62.86 | 60.21 | 62.39 | 61.47 | 62.08 | 62.27 | 62.12 | 62.40 | 62.35 |\n| Workman | 62.37 | 61.59 | 62.22 | 62.91 | 60.23 | 62.41 | 61.49 | 62.10 | 62.29 | 62.14 | 62.43 | 62.37 |\n| MTGap 2.0 | 62.32 | 61.59 | 62.21 | 62.88 | 60.22 | 62.39 | 61.49 | 62.09 | 62.28 | 62.13 | 62.42 | 62.32 |\n| QGMLWB | 62.31 | 61.58 | 62.21 | 62.90 | 60.25 | 62.40 | 61.49 | 62.10 | 62.29 | 62.14 | 62.43 | 62.31 |\n| Colemak Mod-DH | 62.36 | 61.60 | 62.22 | 62.90 | 60.26 | 62.41 | 61.49 | 62.12 | 62.30 | 62.16 | 62.44 | 62.36 |\n| Colemak | 62.36 | 61.58 | 62.20 | 62.89 | 60.25 | 62.40 | 61.48 | 62.10 | 62.29 | 62.14 | 62.43 | 62.36 |\n| Asset | 62.34 | 61.56 | 62.18 | 62.86 | 60.25 | 62.37 | 61.46 | 62.07 | 62.25 | 62.10 | 62.39 | 62.34 |\n| Capewell-Dvorak | 62.29 | 61.56 | 62.17 | 62.86 | 60.20 | 62.36 | 61.47 | 62.06 | 62.24 | 62.10 | 62.37 | 62.29 |\n| Klausler | 62.34 | 61.58 | 62.20 | 62.89 | 60.25 | 62.39 | 61.48 | 62.09 | 62.27 | 62.12 | 62.41 | 62.34 |\n| Dvorak | 62.31 | 61.56 | 62.17 | 62.85 | 60.23 | 62.35 | 61.46 | 62.06 | 62.24 | 62.09 | 62.35 | 62.31 |\n| QWERTY | 62.19 | 61.49 | 62.08 | 62.72 | 60.17 | 62.25 | 61.39 | 61.96 | 62.13 | 61.99 | 62.25 | 62.19 |\n\n---\n    \n[Keyboard Layout Analyzer](http://patorjk.com/keyboard-layout-analyzer/) (KLA) scores for the same text sources\n    \n> The optimal layout score is based on a weighted calculation that factors in the distance your fingers moved (33%), how often you use particular fingers (33%), and how often you switch fingers and hands while typing (34%).\n    \nEngram scores highest for 7 of the 9 and second highest for 2 of the 9 text sources; Engram scores third and fourth highest for the two software sources, \"Coder\" and \"Rosetta\" (higher scores are better):\n\n| Layout | Alice in Wonderland | Memento screenplay | 100K tweets | 20K tweets | MASC tweets | MASC spoken | COCA blogs | iweb | Monkey | Coder | Rosetta |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Engram    | 70.13 | 57.16 | 64.64 | 58.58 | 60.24 | 64.39 | 69.66 | 68.25 | 67.66 | 46.81 | 47.69 |\n| Halmak    | 66.25 | 55.03 | 60.86 | 55.53 | 57.13 | 62.32 | 67.29 | 65.50 | 64.75 | 45.68 | 47.60 |\n| Hieamtsrn | 69.43 | 56.75 | 64.40 | 58.95 | 60.47 | 64.33 | 69.93 | 69.15 | 68.30 | 46.01 | 46.48 | \n| Colemak Mod-DH | 65.74 | 54.91 | 60.75 | 54.94 | 57.15 | 61.29 | 67.12 | 65.98 | 64.85 | 47.35 | 48.50 |\n| Norman    | 62.76 | 52.33 | 57.43 | 53.24 | 53.90 | 59.97 | 62.80 | 60.90 | 59.82 | 43.76 | 46.01 |\n| Workman   | 64.78 | 54.29 | 59.98 | 55.81 | 56.25 | 61.34 | 65.27 | 63.76 | 62.90 | 45.33 | 47.76 |\n| MTGAP 2.0 | 66.13 | 53.78 | 59.87 | 55.30 | 55.81 | 60.32 | 65.68 | 63.81 | 62.74 | 45.38 | 44.34 | \n| QGMLWB    | 65.45 | 54.07 | 60.51 | 56.05 | 56.90 | 62.23 | 66.26 | 64.76 | 63.91 | 46.38 | 45.72 |\n| Colemak   | 65.83 | 54.94 | 60.67 | 54.97 | 57.04 | 61.36 | 67.14 | 66.01 | 64.91 | 47.30 | 48.65 |\n| Asset     | 64.60 | 53.84 | 58.66 | 54.72 | 55.35 | 60.81 | 64.71 | 63.17 | 62.44 | 45.54 | 47.52 |\n| Capewell-Dvorak | 66.94 | 55.66 | 62.14 | 56.85 | 57.99 | 62.83 | 66.95 | 65.23 | 64.70 | 45.30 | 45.62 |\n| Klausler  | 68.24 | 59.91 | 62.57 | 56.45 | 58.34 | 64.04 | 68.34 | 66.89 | 66.31 | 46.83 | 45.66 |\n| Dvorak    | 65.86 | 58.18 | 60.93 | 55.56 | 56.59 | 62.75 | 66.64 | 64.87 | 64.26 | 45.46 | 45.55 | \n| QWERTY    | 53.06 | 43.74 | 48.28 | 44.99 | 44.59 | 51.79 | 52.31 | 50.19 | 49.18 | 38.46 | 39.89 | \n\n---\n\n#### Keyboard Layout Analyzer consecutive same-finger key presses\n\nKLA (and other) distance measures may not accurately reflect natural typing, so below is a more reliable measure of one source of effort and strain -- the tally of consecutive key presses with the same finger for different keys. Engram scores lowest for 6 of the 11 texts, second lowest for two texts, and third or fifth lowest for three texts, two of which are software text sources (lower scores are better):\n\nKLA (and other) distance measures may not accurately reflect natural typing, so below is a more reliable measure of one source of effort and strain -- the tally of consecutive key presses with the same finger for different keys. Engram scores lowest for 6 of the 9 and second or third lowest for 3 of the 9 text sources, and third or fifth lowest for the two software text sources (lower scores are better):\n\n| Layout | Alice | Memento | Tweets_100K | Tweets_20K | Tweets_MASC | Spoken_MASC | COCA_blogs | iweb | Monkey | Coder | Rosetta |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Engram | 216 | 11476 | 320406 | 120286 | 7728 | 3514 | 137290 | 1064640 | 37534 | 125798 | 5822 |\n| Halmak | 498 | 13640 | 484702 | 170064 | 11456 | 5742 | 268246 | 2029634 | 68858 | 144790 | 5392 |\n| Hieamtsrn | 244 | 12096 | 311000 | 119490 | 8316 | 3192 | 155674 | 1100116 | 40882 | 158698 | 7324 |\n| Norman | 938 | 20012 | 721602 | 213890 | 16014 | 9022 | 595168 | 3885282 | 135844 | 179752 | 7402 |\n| Workman | 550 | 13086 | 451280 | 136692 | 10698 | 6156 | 287622 | 1975564 | 71150 | 132526 | 5550 |\n| MTGap 2.0 | 226 | 14550 | 397690 | 139130 | 10386 | 6252 | 176724 | 1532844 | 58144 | 138484 | 7272 |\n| QGMLWB | 812 | 17820 | 637788 | 189700 | 14364 | 7838 | 456442 | 3027530 | 100750 | 149366 | 8062 |\n| Colemak Mod-DH | 362 | 10960 | 352578 | 151736 | 9298 | 4644 | 153984 | 1233770 | 47438 | 117842 | 5328 |\n| Colemak | 362 | 10960 | 352578 | 151736 | 9298 | 4644 | 153984 | 1233770 | 47438 | 117842 | 5328 |\n| Asset | 520 | 12519 | 519018 | 155246 | 11802 | 5664 | 332860 | 2269342 | 77406 | 140886 | 6020 |\n| Capewell-Dvorak | 556 | 14226 | 501178 | 163878 | 12214 | 6816 | 335056 | 2391416 | 78152 | 151194 | 9008 |\n| Klausler | 408 | 14734 | 455658 | 174998 | 11410 | 5212 | 257878 | 1794604 | 59566 | 135782 | 7444 |\n| Dvorak | 516 | 13970 | 492604 | 171488 | 12208 | 5912 | 263018 | 1993346 | 64994 | 142084 | 6484 |\n\n---\n  \n#### Symmetry, switching, and roll measures \n    \nThe measures of hand symmetry, hand switching, finger switching, and hand runs without row jumps are from the [Carpalx](http://mkweb.bcgsc.ca/carpalx/?keyboard_layouts) website and are based on literature from the Gutenberg Project. Engram ties for highest score on two of the measures, third highest for hand switching (since it emphasizes hand rolls), and has a median value for hand runs (higher absolute scores are considered better).\n    \nThe roll measures are the number of bigrams (in billions of instances from Norvig's analysis of Google data) that engage inward rolls (little-to-index sequences), within the four columns of one hand, or any column across two hands. Engram scores second highest for the 32-keys and highest for the 24-keys, where the latter ensures that we are comparing Engram's letters with letters in other layouts (higher scores are better):\n\n| Layout | hand symmetry (%, right<0) | hand switching (%) | finger switching (%) | hand runs without row jumps (%) | inward rolls, billions (32 keys) | inward rolls, billions (24 keys) | \n| --- | --- | --- | --- | --- | --- | --- |\n| Engram     | -99 | 61 | 93 | 82 | 4.64 | 4.51 |\n| Hieamtsrn  | -96 | 59 | 93 | 85 | 4.69 | 4.16 |\n| Halmak     | 99 | 63 | 93 | 81 | 4.59 | 4.25 |\n| Norman     | 95 | 52 | 90 | 77 | 3.99 | 3.61 |\n| Workman    | 95 | 52 | 93 | 79 | 4.16 | 3.63 |\n| MTGAP 2.0  | 98 | 48 | 93 | 76 | 3.96 | 3.58 |\n| QGMLWB     | -97 | 57 | 91 | 84 | 4.36 | 2.81 |\n| Colemak Mod-DH | -94 | 52 | 93 | 78 | 4.15 | 3.51 |\n| Colemak    | -94 | 52 | 93 | 83 | 4.17 | 3.16 |\n| Asset      | 96 | 52 | 91 | 82 | 4.03 | 3.05 |\n| Capewell-Dvorak | -91 | 59 | 92 | 82 | 4.39 | 3.66 | \n| Klausler   | -94 | 62 | 93 | 86 | 4.42 | 3.52 |\n| Dvorak     | -86 | 62 | 93 | 84 | 4.40 | 3.20 |\n| QWERTY     | 85 | 51 | 89 | 68 | 3.62 | 2.13 |\n   \n---\n    \n| Layout | Year | Website |\n| --- | --- | --- |\n| Engram | 2021 | https://engram.dev |\n| [Halmak 2.2](https://keyboard-design.com/letterlayout.html?layout=halmak-2-2.en.ansi) | 2016 | https://github.com/MadRabbit/halmak |\n| [Hieamtsrn](https://www.keyboard-design.com/letterlayout.html?layout=hieamtsrn.en.ansi) | 2014 | https://mathematicalmulticore.wordpress.com/the-keyboard-layout-project/#comment-4976 |\n| [Colemak Mod-DH](https://keyboard-design.com/letterlayout.html?layout=colemak-mod-DH-full.en.ansi) | 2014 | https://colemakmods.github.io/mod-dh/ | \n| [Norman](https://keyboard-design.com/letterlayout.html?layout=norman.en.ansi) | 2013 | https://normanlayout.info/ |\n| [Workman](https://keyboard-design.com/letterlayout.html?layout=workman.en.ansi) | 2010 | https://workmanlayout.org/ | \n| [MTGAP 2.0](https://www.keyboard-design.com/letterlayout.html?layout=mtgap-2-0.en.ansi) | 2010 | https://mathematicalmulticore.wordpress.com/2010/06/21/mtgaps-keyboard-layout-2-0/ |\n| [QGMLWB](https://keyboard-design.com/letterlayout.html?layout=qgmlwb.en.ansi) | 2009 | http://mkweb.bcgsc.ca/carpalx/?full_optimization | \n| [Colemak](https://keyboard-design.com/letterlayout.html?layout=colemak.en.ansi) | 2006 | https://colemak.com/ | \n| [Asset](https://keyboard-design.com/letterlayout.html?layout=asset.en.ansi) | 2006 | http://millikeys.sourceforge.net/asset/ | \n| Capewell-Dvorak | 2004 | http://michaelcapewell.com/projects/keyboard/layout_capewell-dvorak.htm |\n| [Klausler](https://www.keyboard-design.com/letterlayout.html?layout=klausler.en.ansi) | 2002 | https://web.archive.org/web/20031001163722/http://klausler.com/evolved.html |\n| [Dvorak](https://keyboard-design.com/letterlayout.html?layout=dvorak.en.ansi) | 1936 | https://en.wikipedia.org/wiki/Dvorak_keyboard_layout | \n| [QWERTY](https://keyboard-design.com/letterlayout.html?layout=qwerty.en.ansi) | 1873 | https://en.wikipedia.org/wiki/QWERTY |\n\n---\n\n| Text source | Information |\n| --- | --- |\n| \"Alice in Wonderland\" | Alice in Wonderland (Ch.1) |\n| \"Memento screenplay\" | [Memento screenplay](https://www.dailyscript.com/scripts/memento.html) |\n| \"100K tweets\" | 100,000 tweets from: [Sentiment140 dataset](https://data.world/data-society/twitter-user-data) training data |\n| \"20K tweets\" | 20,000 tweets from [Gender Classifier Data](https://www.kaggle.com/crowdflower/twitter-user-gender-classification) |\n| \"MASC tweets\" | [MASC](http://www.anc.org/data/masc/corpus/) tweets (cleaned of html markup) |\n| \"MASC spoken\" | [MASC](http://www.anc.org/data/masc/corpus/) spoken transcripts (phone and face-to-face: 25,783 words) |\n| \"COCA blogs\" | [Corpus of Contemporary American English](https://www.english-corpora.org/coca/) [blog samples](https://www.corpusdata.org/) |\n| \"Rosetta\" | \"Tower of Hanoi\" (programming languages A-Z from [Rosetta Code](https://rosettacode.org/wiki/Towers_of_Hanoi)) |\n| \"Monkey text\" | Ian Douglas's English-generated [monkey0-7.txt corpus](https://zenodo.org/record/4642460) |\n| \"Coder text\" | Ian Douglas's software-generated [coder0-7.txt corpus](https://zenodo.org/record/4642460) |\n| \"iweb cleaned corpus\" | First 150,000 lines of Shai Coleman's [iweb-corpus-samples-cleaned.txt](https://colemak.com/pub/corpus/iweb-corpus-samples-cleaned.txt.xz) |\n\nReference for Monkey and Coder texts:\nDouglas, Ian. (2021, March 28). Keyboard Layout Analysis: Creating the Corpus, Bigram Chains, and Shakespeare's Monkeys (Version 1.0.0). Zenodo. http://doi.org/10.5281/zenodo.4642460\n\n## Guiding criteria   <a name=\"criteria\">\n\n    1.  Assign letters to keys that don't require lateral finger movements.\n    2.  Promote alternating between hands over uncomfortable same-hand transitions.\n    3.  Assign the most common letters to the most comfortable keys.\n    4.  Arrange letters so that more frequent bigrams are easier to type.\n    5.  Promote little-to-index-finger roll-ins over index-to-little-finger roll-outs.\n    6.  Balance finger loads according to their relative strength.\n    7.  Avoid stretching shorter fingers up and longer fingers down.\n    8.  Avoid using the same finger.\n    9.  Avoid skipping over the home row.\n    10. Assign the most common punctuation to keys in the middle of the keyboard.\n    11. Assign easy-to-remember symbols to the Shift-number keys.\n    \n### Factors used to compute the Engram layout <a name=\"factors\">\n  - **N-gram letter frequencies** <br>\n    \n    [Peter Norvig's analysis](http://www.norvig.com/mayzner.html) of data from Google's book scanning project\n  - **Flow factors** (transitions between ordered key pairs) <br>\n    These factors are influenced by Dvorak's 11 criteria (1936).\n\n### Import dependencies and functions  <a name=\"import\">\n\n\n```python\n# %load code/engram_variables.py\n# Print .png figures and .txt text files\nprint_output = False # True\n\n# Apply strength data\napply_strength = True\nmin_strength_factor = 0.9\n\nletters24 = ['E','T','A','O','I','N','S','R','H','L','D','C','U','M','F','P','G','W','Y','B','V','K','X','J']\nkeys24 = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24]\ninstances24 = [4.45155E+11,3.30535E+11,2.86527E+11,2.72277E+11,2.69732E+11,2.57771E+11,\n               2.32083E+11,2.23768E+11,1.80075E+11,1.44999E+11,1.36018E+11,1.19156E+11,\n               97273082907,89506734085,85635440629,76112599849,66615316232,59712390260,\n               59331661972,52905544693,37532682260,19261229433,8369138754,5657910830]                        \nmax_frequency = 4.45155E+11  #1.00273E+11\ninstances_denominator = 1000000000000\n\n# Establish which layouts are within a small difference of the top-scoring layout \n# (the smallest difference between two penalties, 0.9^8 - 0.9^9, in one of 24^2 key pairs):\ndelta = 0.9**8 - 0.9**9\nfactor24 = ((24**2 - 1) + (1-delta)) / (24**2)\nfactor32 = ((32**2 - 1) + (1-delta)) / (32**2)\n\n# Establish which layouts are within a small difference of each other when using the speed matrix. \n# We define an epsilon equal to 13.158 ms for a single bigram (of the 32^2 possible bigrams), \n# where 13.158 ms is one tenth of 131.58 ms, the fastest measured digraph tapping speed (30,000/228 = 131.58 ms) \n# recorded in the study: \"Estimation of digraph costs for keyboard layout optimization\", \n# A Iseri, Ma Eksioglu, International Journal of Industrial Ergonomics, 48, 127-138, 2015.\n#data_matrix_speed = Speed32x32\n#time_range = 243  # milliseconds\n#norm_range = np.max(data_matrix_speed) - np.min(data_matrix_speed)  # 0.6535662299854439\n#ms_norm = norm_range / time_range  # 0.0026895729629030614\n#epsilon = 131.58/10 * ms_norm / (32**2)\nepsilon    = 0.00003549615849447514\n```\n\n\n```python\n# %load code/engram_functions.py\n# Import dependencies\nimport xlrd\nimport numpy as np\nfrom sympy.utilities.iterables import multiset_permutations\nimport matplotlib\nimport matplotlib.pyplot as plt    \nimport seaborn as sns\n\n\ndef permute_optimize_keys(fixed_letters, fixed_letter_indices, open_letter_indices, \n                          all_letters, keys, data_matrix, bigrams, bigram_frequencies, \n                          min_score=0, verbose=False):\n    \"\"\"\n    Find all permutations of letters, optimize layout, and generate output.\n    \"\"\"\n    matrix_selected = select_keys(data_matrix, keys, verbose=False) \n    \n    unassigned_letters = []\n    for all_letter in all_letters:\n        if all_letter not in fixed_letters:\n            unassigned_letters.append(all_letter)\n            if len(unassigned_letters) == len(open_letter_indices):\n                break\n\n    letter_permutations = permute_letters(unassigned_letters, verbose)\n    if verbose:\n        print(\"{0} permutations\".format(len(letter_permutations)))\n    top_permutation, top_score = optimize_layout(np.array([]), matrix_selected, bigrams, bigram_frequencies, \n                                                 letter_permutations, open_letter_indices, \n                                                 fixed_letters, fixed_letter_indices, min_score, verbose)\n    \n    return top_permutation, top_score, letter_permutations\n\n\ndef permute_optimize(starting_permutation, letters, all_letters, all_keys, \n                     data_matrix, bigrams, bigram_frequencies, min_score=0, verbose=False):\n    \"\"\"\n    Find all permutations of letters, optimize layout, and generate output.\n    \"\"\"\n    matrix_selected = select_keys(data_matrix, all_keys, verbose=False)\n    open_positions = []\n    fixed_positions = [] \n    open_letters = []\n    fixed_letters = []\n    assigned_letters = []\n    for iletter, letter in enumerate(letters):\n        if letter.strip() == \"\":\n            open_positions.append(iletter)\n            for all_letter in all_letters:\n                if all_letter not in letters and all_letter not in assigned_letters:\n                    open_letters.append(all_letter)\n                    assigned_letters.append(all_letter)\n                    break\n        else:\n            fixed_positions.append(iletter)\n            fixed_letters.append(letter)\n\n    letter_permutations = permute_letters(open_letters, verbose)\n    if verbose:\n        print(\"{0} permutations\".format(len(letter_permutations)))\n    top_permutation, top_score = optimize_layout(starting_permutation, matrix_selected, bigrams, \n                                                 bigram_frequencies, letter_permutations, open_positions, \n                                                 fixed_letters, fixed_positions, min_score, verbose)\n        \n    return top_permutation, top_score\n\n\ndef select_keys(data_matrix, keys, verbose=False):\n    \"\"\"\n    Select keys to quantify pairwise relationships.\n    \"\"\"\n    # Extract pairwise entries for the keys:\n    nkeys = len(keys)\n    Select = np.zeros((nkeys, nkeys))\n    u = 0\n    for i in keys:\n        u += 1\n        v = 0\n        for j in keys:\n            v += 1\n            Select[u-1,v-1] = data_matrix[i-1,j-1]\n\n    # Normalize matrix with min-max scaling to a range with max 1:\n    newMin = np.min(Select) / np.max(Select)\n    newMax = 1.0\n    Select = newMin + (Select - np.min(Select)) * (newMax - newMin) / (np.max(Select) - np.min(Select))\n    \n    if verbose:\n        # Heatmap of array\n        heatmap(data=Select, title=\"Matrix heatmap\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=False); plt.show()\n    \n    return Select\n\n\ndef permute_letters(letters, verbose=False):\n    \"\"\"\n    Find all permutations of a given set of letters (max: 8-10 letters).\n    \"\"\"\n    letter_permutations = []\n    for p in multiset_permutations(letters):\n        letter_permutations.append(p)\n    letter_permutations = np.array(letter_permutations)\n    \n    return letter_permutations\n\n\ndef score_layout(data_matrix, letters, bigrams, bigram_frequencies, verbose=False):\n    \"\"\"\n    Compute the score for a given letter-key layout (NOTE normalization step).\n    \"\"\"\n    # Create a matrix of bigram frequencies:\n    nletters = len(letters)\n    F2 = np.zeros((nletters, nletters))\n\n    # Find the bigram frequency for each ordered pair of letters in the permutation:\n    for i1 in range(nletters):\n        for i2 in range(nletters):\n            bigram = letters[i1] + letters[i2]\n            i2gram = np.where(bigrams == bigram)\n            if np.size(i2gram) > 0:\n                F2[i1, i2] = bigram_frequencies[i2gram][0]\n\n    # Normalize matrices with min-max scaling to a range with max 1:\n    newMax = 1\n    minF2 = np.min(F2)\n    maxF2 = np.max(F2)\n    newMin2 = minF2 / maxF2\n    F2 = newMin + (F2 - minF2) * (newMax - newMin2) / (maxF2 - minF2)\n\n    # Compute the score for this permutation:\n    score  = np.average(data_matrix * F2) \n    if verbose:\n        print(\"Score for letter permutation {0}: {1}\".format(letters, score))\n\n    return score\n\n\ndef tally_bigrams(input_text, bigrams, normalize=True, verbose=False):\n    \"\"\"\n    Compute the score for a given letter-key layout (NOTE normalization step).\n    \"\"\"   \n    # Find the bigram frequency for each ordered pair of letters in the input text\n    #input_text = [str.upper(str(x)) for x in input_text]\n    input_text = [str.upper(x) for x in input_text]\n    nchars = len(input_text)\n    F = np.zeros(len(bigrams))\n\n    for ichar in range(0, nchars-1):\n        bigram = input_text[ichar] + input_text[ichar + 1]\n        i2gram = np.where(bigrams == bigram)\n        if np.size(i2gram) > 0:\n            F[i2gram] += 1\n\n    # Normalize matrix with min-max scaling to a range with max 1:\n    if normalize:\n        newMax = 1\n        newMin = np.min(F) / np.max(F)\n        F = newMin + (F - np.min(F)) * (newMax - newMin) / (np.max(F) - np.min(F))\n\n    bigram_frequencies_for_input = F\n\n    if verbose:\n        print(\"Bigram frequencies for input: {0}\".format(bigram_frequencies_for_input))\n\n    return bigram_frequencies_for_input\n\n\ndef tally_layout_samefinger_bigrams(layout, bigrams, bigram_frequencies, nkeys=32, verbose=False):\n    \"\"\"\n    Tally the number of same-finger bigrams within (a list of 24 letters representing) a layout:\n    ['P','Y','O','U','C','I','E','A','G','K','J','X','M','D','L','B','R','T','N','S','H','V','W','F']\n    \"\"\"  \n    if nkeys == 32:\n        #        Left:            Right:\n        #    1  2  3  4 25   28 13 14 15 16 31 \n        #    5  6  7  8 26   29 17 18 19 20 32\n        #    9 10 11 12 27   30 21 22 23 24\n        same_finger_keys = [[1,5],[5,9],[1,9], [2,6],[6,10],[2,10], \n                            [3,7],[7,11],[3,11], [4,8],[8,12],[4,12],\n                            [25,26],[26,27],[25,27], [28,29],[29,30],[28,30], [31,32],\n                            [4,25],[4,26],[4,27], [8,25],[8,26],[8,27], [12,25],[12,26],[12,27],\n                            [13,28],[13,29],[13,30], [17,28],[17,29],[17,30], [21,28],[21,29],[21,30],\n                            [31,16],[31,20],[31,24], [32,16],[32,20],[32,24],\n                            [13,17],[17,21],[13,21], [14,18],[18,22],[14,22], \n                            [15,19],[19,23],[15,23], [16,20],[20,24],[16,24]] \n    elif nkeys == 24:\n        #    1  2  3  4         13 14 15 16  \n        #    5  6  7  8         17 18 19 20 \n        #    9 10 11 12         21 22 23 24\n        same_finger_keys = [[1,5],[5,9],[1,9], [2,6],[6,10],[2,10], \n                            [3,7],[7,11],[3,11], [4,8],[8,12],[4,12],\n                            [13,17],[17,21],[13,21], [14,18],[18,22],[14,22], \n                            [15,19],[19,23],[15,23], [16,20],[20,24],[16,24]] \n\n    layout = [str.upper(x) for x in layout]\n    max_frequency = 1.00273E+11\n\n    samefinger_bigrams = []\n    samefinger_bigram_counts = []\n    for bigram_keys in same_finger_keys:\n        bigram1 = layout[bigram_keys[0]-1] + layout[bigram_keys[1]-1]\n        bigram2 = layout[bigram_keys[1]-1] + layout[bigram_keys[0]-1]\n        i2gram1 = np.where(bigrams == bigram1)\n        i2gram2 = np.where(bigrams == bigram2)\n        if np.size(i2gram1) > 0:\n            samefinger_bigrams.append(bigram1)\n            samefinger_bigram_counts.append(max_frequency * bigram_frequencies[i2gram1] / np.max(bigram_frequencies))\n        if np.size(i2gram2) > 0:\n            samefinger_bigrams.append(bigram2)\n            samefinger_bigram_counts.append(max_frequency * bigram_frequencies[i2gram2] / np.max(bigram_frequencies))\n\n    samefinger_bigrams_total = np.sum([x[0] for x in samefinger_bigram_counts])\n\n    if verbose:\n        print(\"    Total same-finger bigram frequencies: {0:15.0f}\".format(samefinger_bigrams_total))\n\n    return samefinger_bigrams, samefinger_bigram_counts, samefinger_bigrams_total \n\n\ndef tally_layout_bigram_rolls(layout, bigrams, bigram_frequencies, nkeys=32, verbose=False):\n    \"\"\"\n    Tally the number of bigrams that engage little-to-index finger inward rolls\n    for (a list of 24 or 32 letters representing) a layout,\n    within the four columns of one hand, or any column across two hands.\n    layout = ['P','Y','O','U','C','I','E','A','G','K','J','X','L','D','B','V','N','T','R','S','H','M','W','F']\n    bigram_rolls, bigram_roll_counts, bigram_rolls_total = tally_layout_bigram_rolls(layout, bigrams, bigram_frequencies, nkeys=24, verbose=True)\n    \"\"\"   \n    if nkeys == 32:\n        #        Left:            Right:\n        #    1  2  3  4 25   28 13 14 15 16 31 \n        #    5  6  7  8 26   29 17 18 19 20 32\n        #    9 10 11 12 27   30 21 22 23 24\n\n        roll_keys = [[1,2],[2,3],[3,4], [5,6],[6,7],[7,8], [9,10],[10,11],[11,12],\n                    [16,15],[15,14],[14,13], [20,19],[19,18],[18,17], [24,23],[23,22],[22,21],\n                    [1,3],[2,4],[1,4], [5,7],[6,8],[5,8], [9,11],[10,12],[9,12],\n                    [16,14],[15,13],[16,13], [20,18],[19,17],[20,17], [24,22],[23,21],[24,21],\n                    [1,6],[1,7],[1,8],[2,7],[2,8],[3,8], \n                    [5,2],[5,3],[5,4],[6,3],[6,4],[7,4],\n                    [5,10],[5,11],[5,12],[6,11],[6,12],[7,12], \n                    [9,6],[9,7],[9,8],[10,7],[10,8],[11,8],\n                    [16,19],[16,18],[16,17],[15,18],[15,17],[14,17], \n                    [20,15],[20,14],[20,13],[19,14],[19,13],[18,13],\n                    [20,23],[20,22],[20,21],[19,22],[19,21],[18,21], \n                    [24,19],[24,18],[24,17],[23,18],[23,17],[22,17],\n                    [1,10],[1,11],[1,12],[2,11],[2,12],[3,12],\n                    [9,2],[9,3],[9,4],[10,3],[10,4],[11,4],\n                    [16,23],[16,22],[16,21],[15,22],[15,21],[14,21],\n                    [24,15],[24,14],[24,13],[23,14],[23,13],[22,13]]\n        for i in [1,2,3,4,5,6,7,8,9,10,11,12, 25,26,27]:\n            for j in [13,14,15,16,17,18,19,20,21,22,23,24, 28,29,30,31,32]:\n                roll_keys.append([i,j])\n        for i in [13,14,15,16,17,18,19,20,21,22,23,24, 28,29,30,31,32]:\n            for j in [1,2,3,4,5,6,7,8,9,10,11,12, 25,26,27]:\n                roll_keys.append([i,j])\n\n    elif nkeys == 24:\n        #    1  2  3  4         13 14 15 16  \n        #    5  6  7  8         17 18 19 20 \n        #    9 10 11 12         21 22 23 24\n        roll_keys = [[1,2],[2,3],[3,4], [5,6],[6,7],[7,8], [9,10],[10,11],[11,12],\n                    [16,15],[15,14],[14,13], [20,19],[19,18],[18,17], [24,23],[23,22],[22,21],\n                    [1,3],[2,4],[1,4], [5,7],[6,8],[5,8], [9,11],[10,12],[9,12],\n                    [16,14],[15,13],[16,13], [20,18],[19,17],[20,17], [24,22],[23,21],[24,21],\n                    [1,6],[1,7],[1,8],[2,7],[2,8],[3,8], [5,2],[5,3],[5,4],[6,3],[6,4],[7,4],\n                    [5,10],[5,11],[5,12],[6,11],[6,12],[7,12], [9,6],[9,7],[9,8],[10,7],[10,8],[11,8],\n                    [16,19],[16,18],[16,17],[15,18],[15,17],[14,17], [20,15],[20,14],[20,13],[19,14],[19,13],[18,13],\n                    [20,23],[20,22],[20,21],[19,22],[19,21],[18,21], [24,19],[24,18],[24,17],[23,18],[23,17],[22,17],\n                    [1,10],[1,11],[1,12],[2,11],[2,12],[3,12], [9,2],[9,3],[9,4],[10,3],[10,4],[11,4],\n                    [16,23],[16,22],[16,21],[15,22],[15,21],[14,21], [24,15],[24,14],[24,13],[23,14],[23,13],[22,13]]\n        for i in range(0,12):\n            for j in range(12,24):\n                roll_keys.append([i,j])\n        for i in range(12,24):\n            for j in range(0,12):\n                roll_keys.append([i,j])\n\n    layout = [str.upper(x) for x in layout]\n    max_frequency = 1.00273E+11\n\n    bigram_rolls = []\n    bigram_roll_counts = []\n    for bigram_keys in roll_keys:\n        bigram1 = layout[bigram_keys[0]-1] + layout[bigram_keys[1]-1]\n        bigram2 = layout[bigram_keys[1]-1] + layout[bigram_keys[0]-1]\n        i2gram1 = np.where(bigrams == bigram1)\n        i2gram2 = np.where(bigrams == bigram2)\n        if np.size(i2gram1) > 0:\n            bigram_rolls.append(bigram1)\n            bigram_roll_counts.append(max_frequency * bigram_frequencies[i2gram1] / np.max(bigram_frequencies))\n        if np.size(i2gram2) > 0:\n            bigram_rolls.append(bigram2)\n            bigram_roll_counts.append(max_frequency * bigram_frequencies[i2gram2] / np.max(bigram_frequencies))\n\n    bigram_rolls_total = np.sum([x[0] for x in bigram_roll_counts])\n\n    if verbose:\n        print(\"    Total bigram inward roll frequencies: {0:15.0f}\".format(bigram_rolls_total))\n\n    return bigram_rolls, bigram_roll_counts, bigram_rolls_total \n\n\ndef optimize_layout(starting_permutation, data_matrix, bigrams, bigram_frequencies, letter_permutations, \n                    open_positions, fixed_letters, fixed_positions=[], min_score=0, verbose=False):\n    \"\"\"\n    Compute scores for all letter-key layouts.\n    \"\"\"\n    top_permutation = starting_permutation\n    top_score = min_score\n    use_score_function = False\n\n    nletters = len(open_positions) + len(fixed_positions)\n    F2 = np.zeros((nletters, nletters))\n\n    # Loop through the permutations of the selected letters:\n    for p in letter_permutations:\n        letters = np.array(['W' for x in range(nletters)])  # KEEP to initialize!\n        for imove, open_position in enumerate(open_positions):\n            letters[open_position] = p[imove]\n        for ifixed, fixed_position in enumerate(fixed_positions):\n            letters[fixed_position] = fixed_letters[ifixed]\n\n        # Compute the score for this permutation:\n        if use_score_function:\n            score = score_layout(data_matrix, letters, bigrams, bigram_frequencies, verbose=False)\n        else:\n            # Find the bigram frequency for each ordered pair of letters in the permutation:\n            for i1 in range(nletters):\n                for i2 in range(nletters):\n                    bigram = letters[i1] + letters[i2]\n                    i2gram = np.where(bigrams == bigram)\n                    if np.size(i2gram) > 0:\n                        F2[i1, i2] = bigram_frequencies[i2gram][0]\n\n            # Normalize matrices with min-max scaling to a range with max 1:\n            newMax = 1\n            minF2 = np.min(F2)\n            maxF2 = np.max(F2)\n            newMin2 = minF2 / maxF2\n            F = newMin + (F2 - minF2) * (newMax - newMin2) / (maxF2 - minF2)\n\n            # Compute the score for this permutation:\n            score  = np.average(data_matrix * F) \n\n        if score > top_score:\n            top_score = score\n            top_permutation = letters\n            \n    if verbose:\n        if top_score == min_score:\n            print(\"top_score = min_score\")\n        print(\"{0:0.8f}\".format(top_score))\n        print(*top_permutation)\n        \n    return top_permutation, top_score\n\n\ndef exchange_letters(letters, fixed_letter_indices, all_letters, all_keys, data_matrix, \n                     bigrams, bigram_frequencies, verbose=True):\n    \"\"\"\n    Exchange letters, 8 keys at a time (8! = 40,320) selected twice in 14 different ways:\n\n    Indices:\n         0  1  2  3     12 13 14 15\n         4  5  6  7     16 17 18 19\n         8  9 10 11     20 21 22 23 \n\n    1. Top rows\n         0  1  2  3     12 13 14 15\n    2. Bottom rows\n         8  9 10 11     20 21 22 23 \n    3. Top and bottom rows on the right side\n                        12 13 14 15\n                        20 21 22 23 \n    4. Top and bottom rows on the left side \n         0  1  2  3\n         8  9 10 11 \n    5. Top right and bottom left rows\n                        12 13 14 15\n         8  9 10 11 \n    6. Top left and bottom right rows \n         0  1  2  3\n                        20 21 22 23 \n    7. Center of the top and bottom rows on both sides\n            1  2          13 14\n            9 10          21 22\n    8. The eight corners\n         0        3    12       15\n         8       11    20       23 \n    9. Left half of the top and bottom rows on both sides \n         0  1          12 13\n         8  9          20 21\n    10. Right half of the top and bottom rows on both sides\n               2  3          14 15\n              10 11          22 23 \n    11. Left half of non-home rows on the left and right half of the same rows on the right \n         0  1                14 15\n         8  9                22 23 \n    12. Right half of non-home rows on the left and left half of the same rows on the right\n               2  3    12 13\n              10 11    20 21 \n    13. Top center and lower sides\n            1  2           13 14\n         8       11     20       23 \n    14. Top sides and lower center\n         0        3     12       15\n            9 10           21 22   \n    15. Repeat 1-14\n         \n    \"\"\"\n    top_score = score_layout(data_matrix, letters, bigrams, bigram_frequencies, verbose=False)\n    print('Initial score: {0}'.format(top_score)) \n    print(*letters) \n    top_permutation = letters\n\n    lists_of_open_indices = [\n        [0,1,2,3,12,13,14,15],\n        [8,9,10,11,20,21,22,23],\n        [12,13,14,15,20,21,22,23],\n        [0,1,2,3,8,9,10,11],\n        [12,13,14,15,8,9,10,11],\n        [0,1,2,3,20,21,22,23],\n        [1,2,13,14,9,10,21,22],\n        [0,3,12,15,8,11,20,23],\n        [0,1,12,13,8,9,20,21],\n        [2,3,14,15,10,11,22,23],\n        [0,1,14,15,8,9,22,23],\n        [2,3,12,13,10,11,20,21],\n        [1,2,8,11,13,14,20,23],\n        [0,3,9,10,12,15,21,22]  \n    ]\n    lists_of_print_statements = [\n        '1. Top rows',\n        '2. Bottom rows',\n        '3. Top and bottom rows on the right side',\n        '4. Top and bottom rows on the left side',\n        '5. Top right and bottom left rows',\n        '6. Top left and bottom right rows',\n        '7. Center of the top and bottom rows on both sides',\n        '8. The eight corners',\n        '9. Left half of the top and bottom rows on both sides',\n        '10. Right half of the top and bottom rows on both sides',\n        '11. Left half of non-home rows on the left and right half of the same rows on the right',\n        '12. Right half of non-home rows on the left and left half of the same rows on the right',\n        '13. Top center and lower sides',\n        '14. Top sides and lower center'\n    ]\n                         \n    for istep in [1,2]:\n        if istep == 1:\n            s = \"Set 1: 14 letter exchanges: \"\n        elif istep == 2:\n            s = \"Set 2: 14 letter exchanges: \"\n\n        for ilist, open_indices in enumerate(lists_of_open_indices):\n            print_statement = lists_of_print_statements[ilist]     \n\n            if verbose:\n                print('{0} {1}'.format(s, print_statement))\n              \n            starting_permutation = top_permutation.copy()\n            for open_index in open_indices:\n                if open_index not in fixed_letter_indices:\n                    top_permutation[open_index] = ''\n            \n            top_permutation, top_score = permute_optimize(starting_permutation, top_permutation, letters24, \n                                                          keys24, data_matrix, bigrams, bigram_frequencies, \n                                                          min_score=top_score, verbose=True)                    \n    if verbose:\n        print('')\n        print('    -------- DONE --------') \n        print('')\n\n    return top_permutation, top_score\n                             \n\ndef rank_within_epsilon(numbers, epsilon, factor=False, verbose=True):\n    \"\"\"\n    numbers = np.array([10,9,8,7,6])\n    epsilon = 1\n    rank_within_epsilon(numbers, epsilon, factor=False, verbose=True) \n    >>> array([1., 1., 2., 2., 3.])\n    numbers = np.array([0.798900824, 0.79899900824, 0.79900824])\n    epsilon = 0.9**8 - 0.9**9\n    factor24 = ((24**2 - 1) + (1-epsilon)) / (24**2) # 0.999925266109375\n    rank_within_epsilon(numbers, factor24, factor=True, verbose=True) \n    >>> array([2., 1., 1.])\n    \"\"\"\n    numbers = np.array(numbers)\n    Isort = np.argsort(-numbers)\n    numbers_sorted = numbers[Isort]\n    count = 1\n    ranks = np.zeros(np.size(numbers))\n    for i, num in enumerate(numbers_sorted):\n        if ranks[i] == 0:\n            if factor:\n                lower_bound = num * epsilon\n            else:\n                lower_bound = num - epsilon\n            bounded_nums1 = num >= numbers_sorted\n            bounded_nums2 = numbers_sorted >= lower_bound\n            bounded_nums = bounded_nums1 * bounded_nums2\n            count += 1\n            for ibounded, bounded_num in enumerate(bounded_nums):\n                if bounded_num == True:\n                    ranks[ibounded] = count\n\n    uranks = np.unique(ranks)\n    nranks = np.size(uranks)\n    new_ranks = ranks.copy()\n    new_count = 0\n    for rank in uranks:\n        new_count += 1\n        same_ranks = ranks == rank\n        for isame, same_rank in enumerate(same_ranks):\n            if same_rank == True:\n                new_ranks[isame] = new_count\n\n    #ranks_sorted = new_ranks[Isort]\n    ranks_sorted = [np.int(x) for x in new_ranks]\n    \n    if verbose:\n        for i, num in enumerate(numbers_sorted):\n            print(\"    ({0})    {1}\".format(np.int(ranks_sorted[i]), num))\n        \n    return numbers_sorted, ranks_sorted, Isort\n\n\ndef print_matrix_info(matrix_data, matrix_label, nkeys, nlines=10):\n    \"\"\"\n    Print matrix output.\n    \"\"\"\n    print(\"{0} min = {1}, max = {2}\".format(matrix_label, np.min(matrix_data), np.max(matrix_data)))\n    matrix_flat = matrix_data.flatten()\n    argsort = np.argsort(matrix_flat)\n    print(\"{0} key number pairs with minimum values:\".format(matrix_label))\n    for x in argsort[0:nlines]:\n        if x % nkeys == 0:\n            min_row = np.int(np.ceil(x / nkeys)) + 1\n            min_col = 1\n        else:\n            min_row = np.int(np.ceil(x / nkeys))\n            min_col = x - nkeys * (min_row-1) + 1                \n        print(\"        {0} -> {1}        ({2})\".format(min_row, min_col, matrix_flat[x]))\n    print(\"{0} key number pairs with maximum values:\".format(matrix_label))\n    max_sort = argsort[-nlines::]\n    for x in max_sort[::-1]:\n        if x % nkeys == 0:\n            max_row = np.int(np.ceil(x / nkeys)) + 1\n            max_col = 1\n        else:\n            max_row = np.int(np.ceil(x / nkeys))\n            max_col = x - nkeys * (max_row-1) + 1                \n        print(\"        {0} -> {1}        ({2})\".format(max_row, max_col, matrix_flat[x]))\n\n\ndef heatmap(data, title=\"\", xlabel=\"\", ylabel=\"\", x_axis_labels=[], y_axis_labels=[], print_output=True):\n    \"\"\"\n    Plot heatmap of matrix.\n    \"\"\"\n    # use heatmap function, set the color as viridis and\n    # make each cell seperate using linewidth parameter\n    plt.figure()\n    sns_plot = sns.heatmap(data, xticklabels=x_axis_labels, yticklabels=y_axis_labels, linewidths=1, \n                           cmap=\"viridis\", square=True, vmin=np.min(data), vmax=np.max(data))\n    plt.title(title)\n    plt.xlabel(xlabel)\n    plt.ylabel(ylabel)\n    sns_plot.set_xticklabels(x_axis_labels)  #, rotation=75) \n    sns_plot.set_yticklabels(y_axis_labels) \n    if print_output:\n        sns_plot.figure.savefig(\"{0}_heatmap.png\".format(title))\n        \n    \ndef histmap(data, title=\"\", print_output=True):\n    \"\"\"\n    Plot histogram.\n    \"\"\"\n    sns.distplot(data)\n    plt.title(title)\n    if print_output:\n        sns_plot.figure.savefig(\"{0}_histogram.png\".format(title))\n        \n        \ndef print_layout24(layout):\n    \"\"\"\n    Print layout.\n    \"\"\"   \n    print('    {0}  {1}'.format(' '.join(layout[0:4]),\n                                ' '.join(layout[12:16])))\n    print('    {0}  {1}'.format(' '.join(layout[4:8]),\n                                ' '.join(layout[16:20])))\n    print('    {0}  {1}'.format(' '.join(layout[8:12]),\n                                ' '.join(layout[20:24])))\n\n\ndef print_layout24_instances(layout, letters24, instances24, bigrams, bigram_frequencies):\n    \"\"\"\n    Print billions of instances per letter (not Z or Q) in layout form.\n    layout = ['P','Y','O','U','C','I','E','A','G','K','J','X','M','D','L','B','R','T','N','S','H','V','W','F']\n    print_layout24_instances(layout, letters24, instances24, bigrams, bigram_frequencies)\n    \"\"\"\n    layout_instances = []\n    layout_instances_strings = []\n    for letter in layout:\n        index = letters24.index(letter)\n        layout_instances.append(instances24[index])\n        layout_instances_strings.append('{0:3.0f}'.format(instances24[index]/instances_denominator))\n \n    print('    {0}  {1}'.format(' '.join(layout_instances_strings[0:4]),\n                                ' '.join(layout_instances_strings[12:16])))\n    print('    {0}  {1}'.format(' '.join(layout_instances_strings[4:8]),\n                                ' '.join(layout_instances_strings[16:20])))\n    print('    {0}  {1}'.format(' '.join(layout_instances_strings[8:12]),\n                                ' '.join(layout_instances_strings[20:24])))\n    left_sum = np.sum(layout_instances[0:12])\n    right_sum = np.sum(layout_instances[12:24])\n    pL = ''\n    pR = ''\n    if left_sum > right_sum:\n        pL = ' ({0:3.2f}%)'.format(100 * (left_sum - right_sum) / right_sum)\n    elif right_sum > left_sum:\n        pR = ' ({0:3.2f}%)'.format(100 * (right_sum - left_sum) / left_sum)\n    \n    print('\\n    left: {0}{1}  right: {2}{3}'.format(left_sum, pL, right_sum, pR))\n    \n    tally_layout_samefinger_bigrams(layout, bigrams, bigram_frequencies, nkeys=24, verbose=True)\n    tally_layout_bigram_rolls(layout, bigrams, bigram_frequencies, nkeys=24, verbose=True)\n   \n\ndef print_bigram_frequency(input_pair, bigrams, bigram_frequencies):\n    \"\"\"\n    >>> print_bigram_frequency(['t','h'], bigrams, bigram_frequencies)\n    \"\"\"\n    # Find the bigram frequency\n    input_text = [str.upper(str(x)) for x in input_pair]\n    nchars = len(input_text)\n    for ichar in range(0, nchars-1):\n        bigram1 = input_text[ichar] + input_text[ichar + 1]\n        bigram2 = input_text[ichar + 1] + input_text[ichar]\n        i2gram1 = np.where(bigrams == bigram1)\n        i2gram2 = np.where(bigrams == bigram2)\n        if np.size(i2gram1) > 0:\n            freq1 = bigram_frequencies[i2gram1[0][0]]\n            print(\"{0}: {1:3.2f}\".format(bigram1, freq1))\n        if np.size(i2gram2) > 0:\n            freq2 = bigram_frequencies[i2gram2[0][0]]\n            print(\"{0}: {1:3.2f}\".format(bigram2, freq2))\n```\n\n### Bigram frequencies <a name=\"ngrams\">\n\n[Peter Norvig's ngrams table](http://www.norvig.com/mayzner.html](http://www.norvig.com/mayzner.html)\n    \n[NOTE: If you want to compute an optimized layout for another language, or based on another corpus, you can run the tally_bigrams() function above and replace bigram_frequencies below before running the rest of the code.]\n\n\n```python\n# %load code/load_bigram_frequencies.py\nload_original_ngram_files = False\nif load_original_ngram_files:\n    ngrams_table = \"data/bigrams-trigrams-frequencies.xlsx\"\n    wb = xlrd.open_workbook(ngrams_table) \n    ngrams_sheet = wb.sheet_by_index(0)\n    # 1-grams and frequencies\n    onegrams = np.array(())\n    onegram_frequencies = np.array(())\n    i = 0\n    start1 = 0\n    stop1 = 0\n    while stop1 == 0:\n        if ngrams_sheet.cell_value(i, 0) == \"2-gram\":\n            stop1 = 1\n        elif ngrams_sheet.cell_value(i, 0) == \"1-gram\":\n            start1 = 1\n        elif start1 == 1:\n            onegrams = np.append(onegrams, ngrams_sheet.cell_value(i, 0))\n            onegram_frequencies = np.append(onegram_frequencies, ngrams_sheet.cell_value(i, 1))\n        i += 1\n    onegram_frequencies = onegram_frequencies / np.sum(onegram_frequencies)\n\n    # 2-grams and frequencies\n    bigrams = np.array(())\n    bigram_frequencies = np.array(())\n    i = 0\n    start1 = 0\n    stop1 = 0\n    while stop1 == 0:\n        if ngrams_sheet.cell_value(i, 0) == \"3-gram\":\n            stop1 = 1\n        elif ngrams_sheet.cell_value(i, 0) == \"2-gram\":\n            start1 = 1\n        elif start1 == 1:\n            bigrams = np.append(bigrams, ngrams_sheet.cell_value(i, 0))\n            bigram_frequencies = np.append(bigram_frequencies, ngrams_sheet.cell_value(i, 1))\n        i += 1\n    bigram_frequencies = bigram_frequencies / np.sum(bigram_frequencies)\n\n    # Save:\n    if print_output:\n        file = open(\"onegrams.txt\", \"w+\")\n        file.write(str(onegrams))\n        file.close()\n        file = open(\"onegram_frequencies.txt\", \"w+\")\n        file.write(str(onegram_frequencies))\n        file.close()\n        file = open(\"bigrams.txt\", \"w+\")\n        file.write(str(bigrams))\n        file.close()\n        file = open(\"bigram_frequencies.txt\", \"w+\")\n        file.write(str(bigram_frequencies))\n        file.close()\n\n    # Print:\n    print(repr(onegrams))\n    print(repr(onegram_frequencies))\n    print(repr(bigrams))\n    print(repr(bigram_frequencies))\n\nelse:\n    onegrams = np.array(['E', 'T', 'A', 'O', 'I', 'N', 'S', 'R', 'H', 'L', 'D', 'C', 'U',\n       'M', 'F', 'P', 'G', 'W', 'Y', 'B', 'V', 'K', 'X', 'J', 'Q', 'Z'],\n      dtype='<U32')\n    onegram_frequencies = np.array([0.12492063, 0.09275565, 0.08040605, 0.07640693, 0.07569278,\n       0.07233629, 0.06512767, 0.06279421, 0.05053301, 0.04068986,\n       0.03816958, 0.03343774, 0.02729702, 0.02511761, 0.02403123,\n       0.02135891, 0.01869376, 0.01675664, 0.0166498 , 0.01484649,\n       0.01053252, 0.00540513, 0.00234857, 0.00158774, 0.00120469,\n       0.00089951])\n    bigrams = np.array(['TH', 'HE', 'IN', 'ER', 'AN', 'RE', 'ON', 'AT', 'EN', 'ND', 'TI',\n       'ES', 'OR', 'TE', 'OF', 'ED', 'IS', 'IT', 'AL', 'AR', 'ST', 'TO',\n       'NT', 'NG', 'SE', 'HA', 'AS', 'OU', 'IO', 'LE', 'VE', 'CO', 'ME',\n       'DE', 'HI', 'RI', 'RO', 'IC', 'NE', 'EA', 'RA', 'CE', 'LI', 'CH',\n       'LL', 'BE', 'MA', 'SI', 'OM', 'UR', 'CA', 'EL', 'TA', 'LA', 'NS',\n       'DI', 'FO', 'HO', 'PE', 'EC', 'PR', 'NO', 'CT', 'US', 'AC', 'OT',\n       'IL', 'TR', 'LY', 'NC', 'ET', 'UT', 'SS', 'SO', 'RS', 'UN', 'LO',\n       'WA', 'GE', 'IE', 'WH', 'EE', 'WI', 'EM', 'AD', 'OL', 'RT', 'PO',\n       'WE', 'NA', 'UL', 'NI', 'TS', 'MO', 'OW', 'PA', 'IM', 'MI', 'AI',\n       'SH', 'IR', 'SU', 'ID', 'OS', 'IV', 'IA', 'AM', 'FI', 'CI', 'VI',\n       'PL', 'IG', 'TU', 'EV', 'LD', 'RY', 'MP', 'FE', 'BL', 'AB', 'GH',\n       'TY', 'OP', 'WO', 'SA', 'AY', 'EX', 'KE', 'FR', 'OO', 'AV', 'AG',\n       'IF', 'AP', 'GR', 'OD', 'BO', 'SP', 'RD', 'DO', 'UC', 'BU', 'EI',\n       'OV', 'BY', 'RM', 'EP', 'TT', 'OC', 'FA', 'EF', 'CU', 'RN', 'SC',\n       'GI', 'DA', 'YO', 'CR', 'CL', 'DU', 'GA', 'QU', 'UE', 'FF', 'BA',\n       'EY', 'LS', 'VA', 'UM', 'PP', 'UA', 'UP', 'LU', 'GO', 'HT', 'RU',\n       'UG', 'DS', 'LT', 'PI', 'RC', 'RR', 'EG', 'AU', 'CK', 'EW', 'MU',\n       'BR', 'BI', 'PT', 'AK', 'PU', 'UI', 'RG', 'IB', 'TL', 'NY', 'KI',\n       'RK', 'YS', 'OB', 'MM', 'FU', 'PH', 'OG', 'MS', 'YE', 'UD', 'MB',\n       'IP', 'UB', 'OI', 'RL', 'GU', 'DR', 'HR', 'CC', 'TW', 'FT', 'WN',\n       'NU', 'AF', 'HU', 'NN', 'EO', 'VO', 'RV', 'NF', 'XP', 'GN', 'SM',\n       'FL', 'IZ', 'OK', 'NL', 'MY', 'GL', 'AW', 'JU', 'OA', 'EQ', 'SY',\n       'SL', 'PS', 'JO', 'LF', 'NV', 'JE', 'NK', 'KN', 'GS', 'DY', 'HY',\n       'ZE', 'KS', 'XT', 'BS', 'IK', 'DD', 'CY', 'RP', 'SK', 'XI', 'OE',\n       'OY', 'WS', 'LV', 'DL', 'RF', 'EU', 'DG', 'WR', 'XA', 'YI', 'NM',\n       'EB', 'RB', 'TM', 'XC', 'EH', 'TC', 'GY', 'JA', 'HN', 'YP', 'ZA',\n       'GG', 'YM', 'SW', 'BJ', 'LM', 'CS', 'II', 'IX', 'XE', 'OH', 'LK',\n       'DV', 'LP', 'AX', 'OX', 'UF', 'DM', 'IU', 'SF', 'BT', 'KA', 'YT',\n       'EK', 'PM', 'YA', 'GT', 'WL', 'RH', 'YL', 'HS', 'AH', 'YC', 'YN',\n       'RW', 'HM', 'LW', 'HL', 'AE', 'ZI', 'AZ', 'LC', 'PY', 'AJ', 'IQ',\n       'NJ', 'BB', 'NH', 'UO', 'KL', 'LR', 'TN', 'GM', 'SN', 'NR', 'FY',\n       'MN', 'DW', 'SB', 'YR', 'DN', 'SQ', 'ZO', 'OJ', 'YD', 'LB', 'WT',\n       'LG', 'KO', 'NP', 'SR', 'NQ', 'KY', 'LN', 'NW', 'TF', 'FS', 'CQ',\n       'DH', 'SD', 'VY', 'DJ', 'HW', 'XU', 'AO', 'ML', 'UK', 'UY', 'EJ',\n       'EZ', 'HB', 'NZ', 'NB', 'MC', 'YB', 'TP', 'XH', 'UX', 'TZ', 'BV',\n       'MF', 'WD', 'OZ', 'YW', 'KH', 'GD', 'BM', 'MR', 'KU', 'UV', 'DT',\n       'HD', 'AA', 'XX', 'DF', 'DB', 'JI', 'KR', 'XO', 'CM', 'ZZ', 'NX',\n       'YG', 'XY', 'KG', 'TB', 'DC', 'BD', 'SG', 'WY', 'ZY', 'AQ', 'HF',\n       'CD', 'VU', 'KW', 'ZU', 'BN', 'IH', 'TG', 'XV', 'UZ', 'BC', 'XF',\n       'YZ', 'KM', 'DP', 'LH', 'WF', 'KF', 'PF', 'CF', 'MT', 'YU', 'CP',\n       'PB', 'TD', 'ZL', 'SV', 'HC', 'MG', 'PW', 'GF', 'PD', 'PN', 'PC',\n       'RX', 'TV', 'IJ', 'WM', 'UH', 'WK', 'WB', 'BH', 'OQ', 'KT', 'RQ',\n       'KB', 'CG', 'VR', 'CN', 'PK', 'UU', 'YF', 'WP', 'CZ', 'KP', 'DQ',\n       'WU', 'FM', 'WC', 'MD', 'KD', 'ZH', 'GW', 'RZ', 'CB', 'IW', 'XL',\n       'HP', 'MW', 'VS', 'FC', 'RJ', 'BP', 'MH', 'HH', 'YH', 'UJ', 'FG',\n       'FD', 'GB', 'PG', 'TK', 'KK', 'HQ', 'FN', 'LZ', 'VL', 'GP', 'HZ',\n       'DK', 'YK', 'QI', 'LX', 'VD', 'ZS', 'BW', 'XQ', 'MV', 'UW', 'HG',\n       'FB', 'SJ', 'WW', 'GK', 'UQ', 'BG', 'SZ', 'JR', 'QL', 'ZT', 'HK',\n       'VC', 'XM', 'GC', 'FW', 'PZ', 'KC', 'HV', 'XW', 'ZW', 'FP', 'IY',\n       'PV', 'VT', 'JP', 'CV', 'ZB', 'VP', 'ZR', 'FH', 'YV', 'ZG', 'ZM',\n       'ZV', 'QS', 'KV', 'VN', 'ZN', 'QA', 'YX', 'JN', 'BF', 'MK', 'CW',\n       'JM', 'LQ', 'JH', 'KJ', 'JC', 'GZ', 'JS', 'TX', 'FK', 'JL', 'VM',\n       'LJ', 'TJ', 'JJ', 'CJ', 'VG', 'MJ', 'JT', 'PJ', 'WG', 'VH', 'BK',\n       'VV', 'JD', 'TQ', 'VB', 'JF', 'DZ', 'XB', 'JB', 'ZC', 'FJ', 'YY',\n       'QN', 'XS', 'QR', 'JK', 'JV', 'QQ', 'XN', 'VF', 'PX', 'ZD', 'QT',\n       'ZP', 'QO', 'DX', 'HJ', 'GV', 'JW', 'QC', 'JY', 'GJ', 'QB', 'PQ',\n       'JG', 'BZ', 'MX', 'QM', 'MZ', 'QF', 'WJ', 'ZQ', 'XR', 'ZK', 'CX',\n       'FX', 'FV', 'BX', 'VW', 'VJ', 'MQ', 'QV', 'ZF', 'QE', 'YJ', 'GX',\n       'KX', 'XG', 'QD', 'XJ', 'SX', 'VZ', 'VX', 'WV', 'YQ', 'BQ', 'GQ',\n       'VK', 'ZJ', 'XK', 'QP', 'HX', 'FZ', 'QH', 'QJ', 'JZ', 'VQ', 'KQ',\n       'XD', 'QW', 'JX', 'QX', 'KZ', 'WX', 'FQ', 'XZ', 'ZX'], dtype='<U32')\n    bigram_frequencies = np.array([3.55620339e-02, 3.07474124e-02, 2.43274529e-02, 2.04826481e-02,\n       1.98515108e-02, 1.85432319e-02, 1.75804642e-02, 1.48673230e-02,\n       1.45424846e-02, 1.35228145e-02, 1.34257882e-02, 1.33939375e-02,\n       1.27653906e-02, 1.20486963e-02, 1.17497528e-02, 1.16812337e-02,\n       1.12842988e-02, 1.12327374e-02, 1.08744953e-02, 1.07489847e-02,\n       1.05347566e-02, 1.04126653e-02, 1.04125115e-02, 9.53014842e-03,\n       9.32114579e-03, 9.25763559e-03, 8.71095073e-03, 8.70002319e-03,\n       8.34931851e-03, 8.29254235e-03, 8.25280566e-03, 7.93859725e-03,\n       7.93006486e-03, 7.64818391e-03, 7.63241814e-03, 7.27618866e-03,\n       7.26724441e-03, 6.98707488e-03, 6.91722265e-03, 6.88165290e-03,\n       6.85633031e-03, 6.51417363e-03, 6.24352184e-03, 5.97765978e-03,\n       5.76571076e-03, 5.76283716e-03, 5.65269345e-03, 5.50057242e-03,\n       5.46256885e-03, 5.42747781e-03, 5.38164098e-03, 5.30301559e-03,\n       5.29886071e-03, 5.27529444e-03, 5.08937452e-03, 4.92966405e-03,\n       4.87753568e-03, 4.84902069e-03, 4.77989185e-03, 4.77282719e-03,\n       4.74470916e-03, 4.64574958e-03, 4.60971757e-03, 4.54257059e-03,\n       4.47772200e-03, 4.42103298e-03, 4.31534618e-03, 4.25820178e-03,\n       4.25013516e-03, 4.15745843e-03, 4.12608242e-03, 4.05151268e-03,\n       4.05075209e-03, 3.97732158e-03, 3.96527277e-03, 3.94413046e-03,\n       3.86884200e-03, 3.85337077e-03, 3.85189513e-03, 3.84646388e-03,\n       3.78793431e-03, 3.77605408e-03, 3.74420703e-03, 3.73663638e-03,\n       3.67956418e-03, 3.65492648e-03, 3.61676413e-03, 3.61373182e-03,\n       3.60899233e-03, 3.47234973e-03, 3.45829494e-03, 3.39212478e-03,\n       3.37488213e-03, 3.36877623e-03, 3.30478042e-03, 3.23572471e-03,\n       3.17759946e-03, 3.17691369e-03, 3.16447752e-03, 3.15240004e-03,\n       3.15172398e-03, 3.11176534e-03, 2.95503911e-03, 2.89966768e-03,\n       2.87848219e-03, 2.86282435e-03, 2.84865969e-03, 2.84585627e-03,\n       2.81484803e-03, 2.69544349e-03, 2.62987083e-03, 2.54961380e-03,\n       2.54906719e-03, 2.54783715e-03, 2.52606379e-03, 2.47740122e-03,\n       2.39175226e-03, 2.36573195e-03, 2.33400171e-03, 2.29786417e-03,\n       2.27503360e-03, 2.27277101e-03, 2.23911052e-03, 2.21754315e-03,\n       2.18017446e-03, 2.17360835e-03, 2.14044590e-03, 2.13767970e-03,\n       2.13188615e-03, 2.10259217e-03, 2.04932647e-03, 2.04724906e-03,\n       2.03256516e-03, 2.02845908e-03, 1.96777866e-03, 1.95449429e-03,\n       1.95410531e-03, 1.91254221e-03, 1.89316385e-03, 1.88234971e-03,\n       1.87652262e-03, 1.84944194e-03, 1.83351654e-03, 1.78086545e-03,\n       1.76468430e-03, 1.75132925e-03, 1.71573739e-03, 1.70683303e-03,\n       1.66405086e-03, 1.63999785e-03, 1.62732115e-03, 1.62613977e-03,\n       1.60361051e-03, 1.54749379e-03, 1.51636562e-03, 1.51067364e-03,\n       1.49901610e-03, 1.49455831e-03, 1.49011351e-03, 1.48460771e-03,\n       1.48077067e-03, 1.47541326e-03, 1.47480347e-03, 1.46316579e-03,\n       1.46204465e-03, 1.43745726e-03, 1.41513491e-03, 1.39980075e-03,\n       1.38382616e-03, 1.36545598e-03, 1.36333253e-03, 1.36012483e-03,\n       1.35189358e-03, 1.32127808e-03, 1.30185876e-03, 1.28328757e-03,\n       1.27907576e-03, 1.26260675e-03, 1.23637099e-03, 1.23094105e-03,\n       1.21386641e-03, 1.20743055e-03, 1.19536134e-03, 1.19032774e-03,\n       1.17626124e-03, 1.16805780e-03, 1.14618533e-03, 1.11559852e-03,\n       1.06597119e-03, 1.05782134e-03, 1.04699320e-03, 1.04540205e-03,\n       1.01153313e-03, 9.97734501e-04, 9.86028683e-04, 9.84491816e-04,\n       9.79174450e-04, 9.78784303e-04, 9.70343472e-04, 9.68322624e-04,\n       9.66708177e-04, 9.60690121e-04, 9.59749105e-04, 9.43900197e-04,\n       9.40242103e-04, 9.28331656e-04, 9.26685761e-04, 9.14014864e-04,\n       9.02555222e-04, 8.92112065e-04, 8.85803335e-04, 8.77507468e-04,\n       8.62646840e-04, 8.57695087e-04, 8.54499050e-04, 8.43925356e-04,\n       8.31382851e-04, 8.23722323e-04, 8.16643644e-04, 7.89875969e-04,\n       7.86444549e-04, 7.42072946e-04, 7.36927617e-04, 7.27646949e-04,\n       7.25004577e-04, 7.11071849e-04, 6.92833068e-04, 6.71807283e-04,\n       6.68638321e-04, 6.56391013e-04, 6.51990243e-04, 6.49048818e-04,\n       6.43397537e-04, 6.43118050e-04, 6.37839069e-04, 6.21864133e-04,\n       6.06367626e-04, 5.99162639e-04, 5.87024289e-04, 5.74860663e-04,\n       5.72519573e-04, 5.68447140e-04, 5.58806800e-04, 5.45711864e-04,\n       5.37896691e-04, 5.34768852e-04, 5.20071483e-04, 5.18874875e-04,\n       5.16054649e-04, 5.14388309e-04, 5.11931727e-04, 5.04227393e-04,\n       5.00890900e-04, 4.97325634e-04, 4.75088970e-04, 4.66605249e-04,\n       4.58324041e-04, 4.29127437e-04, 4.27514542e-04, 4.17186146e-04,\n       4.16199437e-04, 3.94646924e-04, 3.94183167e-04, 3.86306652e-04,\n       3.61812839e-04, 3.50841120e-04, 3.49059129e-04, 3.23402665e-04,\n       3.22604151e-04, 3.11527347e-04, 3.10032877e-04, 3.07611603e-04,\n       2.96010489e-04, 2.88197255e-04, 2.77494857e-04, 2.70735751e-04,\n       2.67122244e-04, 2.64790886e-04, 2.64597695e-04, 2.63237166e-04,\n       2.61362824e-04, 2.59399816e-04, 2.58614910e-04, 2.57579773e-04,\n       2.49143242e-04, 2.49036616e-04, 2.47547306e-04, 2.36748821e-04,\n       2.35282013e-04, 2.32245156e-04, 2.30209194e-04, 2.28229670e-04,\n       2.27822992e-04, 2.20319919e-04, 2.17945603e-04, 2.13543715e-04,\n       1.97145202e-04, 1.90526970e-04, 1.90304866e-04, 1.88393786e-04,\n       1.85754127e-04, 1.85322815e-04, 1.81767370e-04, 1.74089940e-04,\n       1.71644610e-04, 1.71039222e-04, 1.69557657e-04, 1.66839046e-04,\n       1.64718022e-04, 1.59561636e-04, 1.57658164e-04, 1.54026397e-04,\n       1.52211752e-04, 1.51115808e-04, 1.47564559e-04, 1.46841709e-04,\n       1.36432949e-04, 1.35005671e-04, 1.32141796e-04, 1.27573620e-04,\n       1.27432415e-04, 1.26388914e-04, 1.25919175e-04, 1.23965197e-04,\n       1.21174483e-04, 1.18691292e-04, 1.18219114e-04, 1.17637524e-04,\n       1.17526303e-04, 1.13037594e-04, 1.10863960e-04, 1.09331046e-04,\n       1.08837112e-04, 1.06567401e-04, 1.05698197e-04, 1.00512685e-04,\n       1.00106518e-04, 9.85814937e-05, 9.17495595e-05, 9.15174736e-05,\n       9.09807382e-05, 8.79007001e-05, 8.16240791e-05, 7.91627682e-05,\n       7.79158645e-05, 7.56940333e-05, 7.44394656e-05, 7.18101849e-05,\n       6.97589276e-05, 6.81802488e-05, 6.69029567e-05, 6.54143249e-05,\n       6.08786925e-05, 6.07607969e-05, 6.03570614e-05, 5.98994801e-05,\n       5.95001291e-05, 5.94970869e-05, 5.86983574e-05, 5.79700512e-05,\n       5.66119466e-05, 5.50952209e-05, 5.47453912e-05, 5.43839597e-05,\n       5.25861529e-05, 4.89722417e-05, 4.78187439e-05, 4.77415865e-05,\n       4.77107257e-05, 4.62616737e-05, 4.60653783e-05, 4.60409299e-05,\n       4.56730211e-05, 4.54645078e-05, 4.52324283e-05, 4.38982745e-05,\n       4.36906610e-05, 4.33593810e-05, 4.31226640e-05, 4.29912118e-05,\n       4.29446346e-05, 4.17137339e-05, 3.93478837e-05, 3.84895449e-05,\n       3.84390172e-05, 3.81834469e-05, 3.53827628e-05, 3.47222349e-05,\n       3.37168917e-05, 3.18518637e-05, 3.15951703e-05, 3.12905207e-05,\n       3.10605585e-05, 3.02567524e-05, 2.91709879e-05, 2.89567711e-05,\n       2.85652293e-05, 2.82994071e-05, 2.80417376e-05, 2.77861205e-05,\n       2.77303518e-05, 2.76273746e-05, 2.72172235e-05, 2.69880432e-05,\n       2.66503046e-05, 2.66033916e-05, 2.62086568e-05, 2.59259584e-05,\n       2.57640153e-05, 2.56299050e-05, 2.54449453e-05, 2.51909823e-05,\n       2.47409597e-05, 2.46797892e-05, 2.42472084e-05, 2.35748710e-05,\n       2.24438116e-05, 2.24317329e-05, 2.23097275e-05, 2.21249597e-05,\n       2.17815183e-05, 2.15248592e-05, 2.09465192e-05, 2.09125513e-05,\n       1.96913177e-05, 1.95330853e-05, 1.91064697e-05, 1.88952009e-05,\n       1.85746459e-05, 1.81220081e-05, 1.78919334e-05, 1.73267658e-05,\n       1.61874055e-05, 1.60765855e-05, 1.58740992e-05, 1.45486411e-05,\n       1.40812264e-05, 1.36678429e-05, 1.32768479e-05, 1.31460479e-05,\n       1.30872012e-05, 1.29588223e-05, 1.25748548e-05, 1.24146066e-05,\n       1.22821602e-05, 1.22486357e-05, 1.20714645e-05, 1.20448925e-05,\n       1.19866728e-05, 1.18936663e-05, 1.17590888e-05, 1.17001978e-05,\n       1.16346360e-05, 1.11092945e-05, 1.08992577e-05, 1.06740258e-05,\n       1.06735218e-05, 1.06144296e-05, 1.05679067e-05, 1.03656570e-05,\n       1.03317955e-05, 9.98437559e-06, 9.01036943e-06, 8.85768061e-06,\n       8.76035160e-06, 8.60019167e-06, 8.19227801e-06, 7.80479658e-06,\n       7.53516931e-06, 7.44150882e-06, 7.30644125e-06, 7.26777599e-06,\n       7.06747616e-06, 6.95177332e-06, 6.85925126e-06, 6.74132156e-06,\n       6.71322068e-06, 6.70106994e-06, 6.66133186e-06, 6.47626505e-06,\n       6.38130476e-06, 6.29576510e-06, 6.24612583e-06, 5.93271496e-06,\n       5.92132104e-06, 5.83947722e-06, 5.76779879e-06, 5.76465728e-06,\n       5.53187023e-06, 5.47131015e-06, 5.33180695e-06, 5.22417954e-06,\n       5.20732008e-06, 5.15949060e-06, 5.11569104e-06, 4.95336950e-06,\n       4.94557425e-06, 4.73636484e-06, 4.63955858e-06, 4.53340156e-06,\n       4.22935422e-06, 4.19307790e-06, 4.17347414e-06, 4.12142146e-06,\n       4.11855764e-06, 3.80541311e-06, 3.36707879e-06, 3.29563656e-06,\n       3.17577578e-06, 3.05442971e-06, 2.98983688e-06, 2.97762691e-06,\n       2.95066092e-06, 2.91720550e-06, 2.89840858e-06, 2.77497857e-06,\n       2.76265227e-06, 2.74176112e-06, 2.70310579e-06, 2.61648976e-06,\n       2.60275585e-06, 2.56616744e-06, 2.55465117e-06, 2.49712549e-06,\n       2.42815484e-06, 2.37933375e-06, 2.35040476e-06, 2.33914845e-06,\n       2.33036549e-06, 2.32978989e-06, 2.28930419e-06, 2.28804340e-06,\n       2.26346210e-06, 2.24353844e-06, 2.23182640e-06, 2.23165865e-06,\n       2.22696341e-06, 2.22115030e-06, 2.21572164e-06, 2.20668084e-06,\n       2.19243658e-06, 2.17382266e-06, 2.08159887e-06, 2.07762818e-06,\n       1.95415065e-06, 1.88693410e-06, 1.83219245e-06, 1.81431726e-06,\n       1.67631850e-06, 1.67169206e-06, 1.63803449e-06, 1.57770706e-06,\n       1.56577585e-06, 1.53130790e-06, 1.52519015e-06, 1.52439998e-06,\n       1.49350905e-06, 1.47212210e-06, 1.45715861e-06, 1.40331777e-06,\n       1.38641504e-06, 1.29786439e-06, 1.27069447e-06, 1.25613209e-06,\n       1.23105569e-06, 1.22268909e-06, 1.21688094e-06, 1.18065108e-06,\n       1.18060143e-06, 1.16794389e-06, 1.13216621e-06, 1.12716419e-06,\n       1.12418866e-06, 1.12412659e-06, 1.05684621e-06, 1.05049722e-06,\n       1.04986594e-06, 1.03676402e-06, 1.03482230e-06, 9.96847192e-07,\n       9.75926251e-07, 9.54397081e-07, 9.36101632e-07, 9.30100914e-07,\n       9.27467975e-07, 8.92801774e-07, 8.85217179e-07, 8.58891337e-07,\n       7.80484800e-07, 7.67724409e-07, 7.54031637e-07, 7.45052550e-07,\n       7.32511689e-07, 7.06828122e-07, 6.59585949e-07, 6.40055245e-07,\n       6.18628925e-07, 6.17142222e-07, 6.09904832e-07, 6.07242457e-07,\n       5.72270900e-07, 5.49823535e-07, 5.22568859e-07, 5.01838721e-07,\n       4.91372576e-07, 4.82981856e-07, 4.69688423e-07, 4.59727658e-07,\n       4.54795508e-07, 4.22875379e-07, 4.13494116e-07, 3.99834682e-07,\n       3.97288987e-07, 3.87644926e-07, 3.84245584e-07, 3.81268632e-07,\n       3.67029696e-07, 3.57267536e-07, 3.52642869e-07, 3.51058992e-07,\n       3.44112772e-07, 3.36167495e-07, 3.24215712e-07, 3.23810344e-07,\n       3.21814716e-07, 3.21505459e-07, 3.10936465e-07, 2.88018831e-07,\n       2.86309762e-07, 2.76140106e-07, 2.63218703e-07, 2.56899508e-07,\n       2.51244222e-07, 2.25386521e-07, 2.15766576e-07, 2.03018243e-07,\n       1.99078411e-07, 1.97551987e-07, 1.96981706e-07, 1.92415912e-07,\n       1.84391194e-07, 1.81253585e-07, 1.78663913e-07, 1.77747846e-07,\n       1.59541769e-07, 1.38003378e-07, 1.36499298e-07, 1.22889160e-07,\n       1.22576357e-07, 1.19711121e-07, 1.09597855e-07, 9.97477409e-08,\n       9.65292710e-08, 9.36271510e-08, 9.35785637e-08, 9.34540807e-08,\n       8.40270671e-08, 7.82629028e-08, 7.54898762e-08, 6.64058115e-08,\n       5.96748649e-08, 5.79118882e-08, 5.73650143e-08, 5.65688198e-08,\n       5.34673852e-08, 5.34237630e-08, 5.29956976e-08, 4.84174907e-08,\n       3.83818937e-08])\n```\n\n## Speed matrix  <a name=\"speed\">\n### 24x24 relative Speed matrix between key pair (averaged for left/right symmetry)\n\n  - does not take into account order of key pairs (see Flow24x24 matrix)\n  - the original version was constructed with data from right-handed people\n  - 24 keys that don't require extending index or little fingers (\"home block keys\")\n\n### Home block keys\n\n        Left:            Right:\n     1  2  3  4       13 14 15 16 \n     5  6  7  8       17 18 19 20\n     9 10 11 12       21 22 23 24\n\nInterkey stroke times in milliseconds from Table 3 of <br>\n\"Estimation of digraph costs for keyboard layout optimization\", <br>\nA Iseri, Ma Eksioglu, International Journal of Industrial Ergonomics, 48, 127-138, 2015. <br>\nKey numbering in article and in spreadsheet:\n\n         Left:           Right:\n     1 4 7 10 13   16 19 22 25 28 31\n     2 5 8 11 14   17 20 23 26 29 32\n     3 6 9 12 15   18 21 24 27 30\n     \n### Load table of interkey speeds\n\n\n```python\n# %load data/Time24x24.py\n# code/load_original_interkey_speeds.py\n#        Left:            Right:\n#    1  2  3  4 25   28 13 14 15 16 31 \n#    5  6  7  8 26   29 17 18 19 20 32\n#    9 10 11 12 27   30 21 22 23 24\nTime24x24 = np.array([\n[196,225,204,164,266,258,231,166,357,325,263,186,169,176,178,186,156,156,158,163,171,175,177,189],\n[225,181,182,147,239,245,196,150,289,296,229,167,162,169,170,178,148,148,150,155,163,167,169,182],\n[204,182,170,149,196,194,232,155,237,214,263,166,157,164,165,173,143,143,145,150,158,163,164,177],\n[164,147,149,169,160,161,157,226,165,185,234,257,154,162,163,171,141,141,143,148,156,160,162,175],\n[266,239,196,160,196,240,208,166,271,267,208,169,143,150,151,160,129,129,132,137,145,149,151,163],\n[258,245,194,161,240,181,183,149,245,256,184,150,138,145,146,154,124,124,126,131,139,144,145,158],\n[231,196,232,157,208,183,170,149,201,215,239,151,134,141,142,150,120,120,122,127,135,140,141,154],\n[166,150,155,226,166,149,149,169,160,147,170,221,133,140,141,150,119,119,122,126,135,139,141,153],\n[357,289,237,165,271,245,201,160,196,236,194,161,171,178,179,188,157,157,160,164,173,177,179,191],\n[325,296,214,185,267,256,215,147,236,181,184,157,166,173,174,182,152,152,154,159,167,172,173,186],\n[263,229,263,234,208,184,239,170,194,184,170,150,159,166,167,176,145,145,148,153,161,165,167,179],\n[186,167,166,257,169,150,151,221,161,157,150,169,153,160,161,169,139,139,141,146,154,159,160,173],\n[169,162,157,154,143,138,134,133,171,166,159,153,151,147,141,145,188,151,142,164,213,204,162,149],\n[176,169,164,162,150,145,141,140,178,173,166,160,147,151,189,209,137,207,191,206,149,227,208,197],\n[178,170,165,163,151,146,142,141,179,174,167,161,141,189,157,253,136,188,210,231,155,226,239,276],\n[186,178,173,171,160,154,150,150,188,182,176,169,145,209,253,170,147,206,251,233,164,268,362,271],\n[156,148,143,141,129,124,120,119,157,152,145,139,188,137,136,147,151,133,138,152,192,149,139,144],\n[156,148,143,141,129,124,120,119,157,152,145,139,151,207,188,206,133,151,179,183,145,204,183,201],\n[158,150,145,143,132,126,122,122,160,154,148,141,142,191,210,251,138,179,157,240,145,185,208,229],\n[163,155,150,148,137,131,127,126,164,159,153,146,164,206,231,233,152,183,240,170,160,220,293,242],\n[171,163,158,156,145,139,135,135,173,167,161,154,213,149,155,164,192,145,145,160,151,140,142,145],\n[175,167,163,160,149,144,140,139,177,172,165,159,204,227,226,268,149,204,185,220,140,151,175,188],\n[177,169,164,162,151,145,141,141,179,173,167,160,162,208,239,362,139,183,208,293,142,175,157,230],\n[189,182,177,175,163,158,154,153,191,186,179,173,149,197,276,271,144,201,229,242,145,188,230,170]])\n```\n\n\n```python\n# %load code/load_interkey_speeds24x24.py\n\n# Left/right symmetric version of the Time24x24 matrix\n# (The original version was constructed with data from right-handed people.)\n# A. Iseri, M. Eksioglu / International Journal of Industrial Ergonomics 48 (2015) 127e138\n\n#        Left:            Right:\n#     1  2  3  4       13 14 15 16 \n#     5  6  7  8       17 18 19 20\n#     9 10 11 12       21 22 23 24\n\nI = [ 1, 2, 3, 4,   5, 6, 7, 8,   9,10,11,12,  16,15,14,13,  20,19,18,17,  24,23,22,21]\nJ = [16,15,14,13,  20,19,18,17,  24,23,22,21,   1, 2, 3, 4,   5, 6, 7, 8,   9,10,11,12]\n\nTimeSymmetric24x24 = np.ones((24,24))\nfor i1, I1 in enumerate(I):\n    for i2, I2 in enumerate(I):\n        J1 = J[i1] - 1\n        J2 = J[i2] - 1\n        avgvalue = (Time24x24[I1-1,I2-1] + Time24x24[J1,J2]) / 2 \n        #print(Time24x24[I1-1,I2-1], Time24x24[J1,J2], avgvalue)\n        TimeSymmetric24x24[I1-1,I2-1] = avgvalue\n        TimeSymmetric24x24[J1,J2] = avgvalue\n\n# Normalize matrix with min-max scaling to a range with maximum = 1:\nnewMin = np.min(Time24x24) / np.max(Time24x24)\nnewMax = 1.0\nTime24x24 = newMin + (Time24x24 - np.min(Time24x24)) * (newMax - newMin) / (np.max(Time24x24) - np.min(Time24x24))\n\n# Convert relative interkey stroke times to relative speeds by subtracting from 1:\nSpeed24x24 = 1 - Time24x24 + np.min(Time24x24)\n\n# Normalize matrix with min-max scaling to a range with maximum = 1:\nnewMin = np.min(TimeSymmetric24x24) / np.max(TimeSymmetric24x24)\nnewMax = 1.0\nTimeSymmetric24x24 = newMin + (TimeSymmetric24x24 - np.min(TimeSymmetric24x24)) * (newMax - newMin) / (np.max(TimeSymmetric24x24) - np.min(TimeSymmetric24x24))\n\n# Convert relative interkey stroke times to relative speeds by subtracting from 1:\nSpeedSymmetric24x24 = 1 - TimeSymmetric24x24 + np.min(TimeSymmetric24x24)\n\n# Print:\n#print_matrix_info(matrix_data=Speed24x24, matrix_label=\"Speed24x24\", nkeys=24, nlines=50)\n#heatmap(data=Speed24x24, title=\"Speed24x24\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n```\n\n## Strength matrix  <a name=\"strength\">\n\n### Relative finger position STRENGTH matrix\n\nFinger strengths are based on peak keyboard reaction forces (in newtons) from Table 4 of <br>\n\"Keyboard Reaction Force and Finger Flexor Electromyograms during Computer Keyboard Work\" <br>\nBJ Martin, TJ Armstrong, JA Foulke, S Natarajan, Human Factors,1996,38(4),654-664:\n   \n    middle     2.36\n    index      2.26\n    ring       2.02\n    little     1.84\n    \n    index/middle:  0.9576271186440678\n    ring/middle:   0.8559322033898306\n    little/middle: 0.7796610169491526\n\nFor reference, Table 1 of \"Ergonomic keyboard layout designed for the Filipino language\", 2016 (doi: 10.1007/978-3-319-41694-6_41) presents \"average finger strength of Filipinos [n=30, ages 16-36] measured in pounds\":\n   \n                L       R\n    little     3.77   4.27\n    ring       4.54   5.08\n    middle     5.65   6.37\n    index      6.09   6.57\n    \n    6.57/4.27 = 1.54\n    6.09/3.77 = 1.62\n    6.37/5.08 = 1.25\n    5.65/4.54 = 1.24\n    \nWe won't use these results as I don't feel they represent relative strength relevant for typing: \"Respondents were asked to sit in upright position, with their wrists resting on a flat surface. A pinch gauge was placed within each finger's reach. The respondents were asked to exert maximum pressure on the device.\"\n    \nThe following does not take into account order of key pairs (see Flow matrix).\n\n\n\n```python\n# %load code/load_strength_data.py\n# Normalize by the highest peak force (middle finger):\nmiddle_force = 2.36\nindex_force = 2.26\nring_force = 2.02\nlittle_force = 1.84\nmiddle_norm = 1.0\nindex_norm = index_force / middle_force\nring_norm = ring_force / middle_force\nlittle_norm = little_force / middle_force\nprint('index/middle: {0}'.format(index_norm))\nprint('ring/middle: {0}'.format(ring_norm))\nprint('little/middle: {0}'.format(little_norm))\n\n# Relative left/right hand strength (assume equal):\nlf = 1.0\nrf = 1.0\n\nstrengths24 = np.array((\n                    lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                    lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                    lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                    rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm,\n                    rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm,\n                    rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm))\n\n# Create a finger-pair position strength matrix by adding pairs of strength values:\nStrength24x24 = np.zeros((24, 24))\nfor i in range(24):\n    Strength24x24[i,:] = strengths24\nStrength24x24 = (Strength24x24 + Strength24x24.transpose())\n\n# Normalize matrix with min-max scaling to a range with maximum = 1:\n#newMin = strength_factor\nnewMin = min_strength_factor  # np.min(Strength24x24) / np.max(Strength24x24)\nnewMax = 1.0\nStrength24x24 = newMin + (Strength24x24 - np.min(Strength24x24)) * (newMax - newMin) / (np.max(Strength24x24) - np.min(Strength24x24))\n\n# Print:\nprint_matrix_info(matrix_data=Strength24x24, matrix_label=\"Strength24x24\", nkeys=24, nlines=10)\nheatmap(data=Strength24x24, title=\"Strength24x24\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n# Save:\nif print_output:\n    file = open(\"Strength24x24.txt\", \"w+\")\n    file.write(str(Strength24x24))\n    file.close()\n\n\npenalty = 1.0  # Penalty for lateral (index, little) finger placement (1 = no penalty)\n\nstrengths32 = np.array((lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                        lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                        lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                        rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm,\n                        rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm,\n                        rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm,\n                        lf * index_norm * penalty, lf * index_norm * penalty, lf * index_norm * penalty,\n                        rf * index_norm * penalty, rf * index_norm * penalty, rf * index_norm * penalty,\n                        rf * little_norm * penalty, rf * little_norm * penalty))\n\n# Create a finger-pair position strength matrix by adding pairs of strength values:\nStrength32x32 = np.zeros((32, 32))\nfor i in range(32):\n    Strength32x32[i,:] = strengths32\nStrength32x32 = (Strength32x32 + Strength32x32.transpose())\n\n# Normalize matrix with min-max scaling to a range with maximum = 1:\nnewMin = np.min(Strength32x32) / np.max(Strength32x32)\nnewMax = 1.0\nStrength32x32 = newMin + (Strength32x32 - np.min(Strength32x32)) * (newMax - newMin) / (np.max(Strength32x32) - np.min(Strength32x32))\n\n# Print:\nprint_matrix_info(matrix_data=Strength32x32, matrix_label=\"Strength32x32\", nkeys=32, nlines=10)\nheatmap(data=Strength32x32, title=\"Strength32x32\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n# Save:\nif print_output:\n    file = open(\"Strength32x32.txt\", \"w+\")\n    file.write(str(Strength32x32))\n    file.close()\n```\n\n## Flow matrix and Engram scoring model  <a name=\"flow\">\n\nThe Flow24x24 matrix takes into account ease of transition between ordered pairs of keys.\n    \nOur optimization algorithm finds every permutation of a given set of letters, maps these letter permutations to a set of keys, and ranks these letter-key mappings according to a score reflecting ease of typing key pairs and frequency of letter pairs (bigrams). The score is the average of the scores for all possible bigrams in this arrangement. The score for each bigram is a product of the frequency of occurrence of that bigram, the frequency of each of the bigram\u2019s characters, and flow, strength (and optional speed) factors for the key pair.\n\n#### Dvorak et al. (1936) defined eleven criteria for the design and evaluation of keyboard layouts:\n1.  Deviation from the balance of hand and finger loads should be as low as possible.\n2.  Percentage of tapping with the same fingers should be as low as possible.\n3.  Percentage of tapping that includes top row should be as low as possible.\n4.  Percentage of tapping that includes bottom row should be as low as possible.\n5.  Percentage of tapping in the home row should be as high as possible.\n6.  Percentage of tapping by alternating hands should be as high as possible.\n7.  Percentage of hurdles with the same finger should be as low as possible.\n8.  Percentage of hurdles with adjacent offset fingers should be as low as possible.\n9.  Percentage of hurdles with remote fingers should be as low as possible.\n10. Percentage of reach with the same finger should be as low as possible.\n11. Percentage of reach with adjacent offset fingers should be as low as possible.\n\n#### Synopsis of above criteria for pairwise key presses when touch typing:\n1. Alternate between hands.\n2. Balance finger loads, and avoid using the same finger.\n3. Avoid the upper and lower rows, and avoid skipping over the home row.\n4. Avoid tapping adjacent offset rows with the same or adjacent offset fingers.\n    \n### Factors to penalize strenuous key transitions\n\nDirection:\n    \n    - outward = 0.9: outward roll of fingers from the index to little finger (same hand)\n\nDexterity:\n    \n    - side_above_3away = 0.9\n        - index and little finger type two keys, one or more rows apart (same hand)\n    - side_above_2away = 0.9^2 = 0.81\n        - index finger types key a row or two above ring finger key, or\n        - little finger types key a row or two above middle finger key (same hand)\n    - side_above_1away = 0.9^3 = 0.729\n        - index finger types key a row or two above middle finger key, or\n        - little finger types key a row or two above ring finger key (same hand)\n    - middle_above_ring = 0.9\n        - middle finger types key a row or two above ring finger key (same hand)\n    - ring_above_middle = 0.9^3 = 0.729\n        - ring finger types key a row or two above middle finger key (same hand)\n    - lateral = 0.9\n        - lateral movement of (index or little) finger outside of 8 vertical columns\n    \nDistance:\n    \n    - skip_row_3away = 0.9       \n        - index and little fingers type two keys that skip over home row (same hand)\n        - (e.g., one on bottom row, the other on top row)\n    - skip_row_2away = 0.9^3 = 0.729\n        - little and middle or index and ring fingers type two keys that skip over home row (same hand)\n    - skip_row_1away = 0.9^5 = 0.59049\n        - little and ring or middle and index fingers type two keys that skip over home row (same hand)\n\nRepetition:\n \n    - skip_row_0away = 0.9^4 = 0.6561\n        - same finger types two keys that skip over home row\n    - same_finger = 0.9^5 = 0.59049\n        - use same finger again for a different key\n        - cannot accompany outward, side_above, or adjacent_shorter_above \n\nStrength: Accounted for by the strength matrix (minimum value for the little finger = 0.9)    \n\n### Example flow values for left side home block\n   \nNo penalty (for same hand, both keys in the same row in an inward roll or repeating the same key):\n\n    2=>2, 2=>3, 3=>4, 2=>4, 1=>4\n\n    1  2  3  4\n    5  6  7  8\n    9 10 11 12\n\nPenalty = 0.9:\n\n    outward: 2=>1, 3=>1, 3=>2, 4=>1, 4=>2, 4=>3, 6=>5, 7=>6, 7=>5, 8=>7, 8=>6, 8=>5,... \n    middle_above_ring: 6=>3, 10=>7 \n    side_above_3away: 1=>8, 5=>4, 5=>12, 9=>8\n    index_above: 1=>4, 2=>4, 3=>4, 4=>4\n\nPenalty = 0.9^2:\n\n    middle_above_ring * outward: 3=>6, 7=>10\n    side_above_3away * outward: 8=>1, 4=>5, 12=>5, 8=>9\n    side_above_2away: 1=>7, 6=>4, 5=>11, 10=>8    \n    skip_row_3away * side_above_3away: 1=>12, 9=>4\n    skip_row_2away: 2=>12, 9=>3\n    ring_above_middle 2=>7, 6=>11\n    side_above_2away * outward: 7=>1, 4=>6, 11=>5, 8=>10\n    side_above_1away: 1=>6, 7=>4, 5=>10, 11=>8\n\nPenalty = 0.9^3:\n\n    skip_row_3away * side_above_3away * outward: 12=>1, 4=>9\n\nPenalty = 0.9^4:\n\n    ring_above_middle * outward: 7=>2, 11=>6\n    side_above_1away * outward: 4=>7, 6=>1, 10=>5, 4=>7\n\nPenalty = 0.9^5:\n\n    same_finger: 4=>8, 8=>4, 1=>5, 5=>1, 5=>9, 9=>5, 2=>6, 6=>2,...\n    skip_row_2away * side_above_2away: 10=>4, 1=>11\n    skip_row_1away: 1=>10, 9=>2, 3=>12\n\nPenalty = 0.9^6:\n\n    skip_row_2away * side_above_2away * outward: 4=>10, 11=>1\n    skip_row_1away * outward: 10=>1, 2=>9, 12=>3\n\nPenalty = 0.9^8\n\n    skip_row_1away * ring_above_middle: 2=>11\n    skip_row_1away * side_above_1away: 1=>10, 11=>4\n\nPenalty = 0.9^9\n\n    skip_row_1away * ring_above_middle * outward: 11=>2\n    skip_row_0away * same_finger: 1=>9, 9=>1, 4=>12, 12=>4, 2=>10, 10=>2, 3=>11, 11=>3     \n    skip_row_1away * side_above_1away * outward: 10=>1, 4=>11\n\n\n```python\n# %load code/load_flow_matrices.py\n# Penalizing factors for 24 keys  (1 = no penalty; set to less than 1 to penalize):\n\n# Dexterity\nside_above_3away = 0.9     # index and little finger type two keys, one or more rows apart (same hand)\nside_above_2away = 0.81    # index finger types key a row or two above ring finger key, or\n                           # little finger types key a row or two above middle finger key (same hand)\nside_above_1away = 0.729   # index finger types key a row or two above middle finger key, or\n                           # little finger types key a row or two above ring finger key (same hand)\nmiddle_above_ring = 0.9    # middle finger types key a row or two above ring finger key (same hand)\nring_above_middle = 0.729  # ring finger types key a row or two above middle finger key (same hand)\nlateral = 0.9              # lateral movement of (index or little) finger outside of 8 vertical columns\n\n# Direction\noutward = 0.9              # outward roll of fingers from the index to little finger (same hand)\n\n# Distance\nskip_row_3away = 0.9       # index and little fingers type two keys that skip over home row (same hand)\n                           # (e.g., one on bottom row, the other on top row)\nskip_row_2away = 0.729     # little and middle or index and ring fingers type two keys that skip over home row (same hand)\nskip_row_1away = 0.59049   # little and ring or middle and index fingers type two keys that skip over home row (same hand)\n\n# Repetition\nskip_row_0away = 0.6561    # same finger types two keys that skip over home row\nsame_finger = 0.59049      # use same finger again for a different key\n\n\n# Unused or redundant parameters\nsame_hand = 1.0            # (addressed by splitting up the most frequent letters across left/right sides above)\nnot_home_row = 1.0         # at least one key not on home row\nside_top = 1.0             # index or little finger types top corner key\nshorter_above = 1.0        # (taken care of by side_above_[1,2,3]away parameters)\nadjacent_offset = 1.0      # (taken care of by side_above_1away, middle_above_ring, ring_above_middle parameters)\ninside_top = 1.0           # index finger types top corner key (taken care of by side_above_1away parameter)\nindex_above = 1.0          # index finger types top corner key (unless other bigram key is in the top row for the same hand)\n                           # (taken care of by side_above_[1,2,3]away parameters)\n\n\ndef create_24x24_flow_matrix(not_home_row, side_top, side_above_3away, side_above_2away, side_above_1away, \n                             middle_above_ring, ring_above_middle, outward, skip_row_3away, \n                             skip_row_2away, skip_row_1away, skip_row_0away, same_finger, lateral, \n                             same_hand, shorter_above, adjacent_offset, inside_top, index_above):\n\n    all_24_keys = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24]\n\n    # Create a matrix and multiply by flow factors that promote easy interkey transitions:\n    T = np.ones((24, 24))\n\n    # 7.  Promote alternating between hands over uncomfortable transitions with the same hand.\n    if same_hand < 1.0:\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n        for i in range(0,12):\n            for j in range(0,12):\n                T[i,j] *= same_hand\n        for i in range(12,24):\n            for j in range(12,24):\n                T[i,j] *= same_hand\n\n    # 8.  Promote little-to-index-finger roll-ins over index-to-little-finger outwards.\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    if outward < 1.0:\n\n        # same-row roll-outs:\n        roll_ins = [[1,2],[2,3],[3,4], [5,6],[6,7],[7,8], [9,10],[10,11],[11,12],\n                    [16,15],[15,14],[14,13], [20,19],[19,18],[18,17], [24,23],[23,22],[22,21]]\n        for x in roll_ins:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # same-row roll-outs, skipping keys:\n        roll_ins_skip_keys = [[1,3],[2,4],[1,4], [5,7],[6,8],[5,8], [9,11],[10,12],[9,12],\n                              [16,14],[15,13],[16,13], [20,18],[19,17],[20,17], [24,22],[23,21],[24,21]]\n        for x in roll_ins_skip_keys:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # adjacent-row roll-outs:\n        roll_ins_adj_rows = [[1,6],[1,7],[1,8],[2,7],[2,8],[3,8], [5,2],[5,3],[5,4],[6,3],[6,4],[7,4],\n                             [5,10],[5,11],[5,12],[6,11],[6,12],[7,12], [9,6],[9,7],[9,8],[10,7],[10,8],[11,8],\n                             [16,19],[16,18],[16,17],[15,18],[15,17],[14,17], [20,15],[20,14],[20,13],[19,14],[19,13],[18,13],\n                             [20,23],[20,22],[20,21],[19,22],[19,21],[18,21], [24,19],[24,18],[24,17],[23,18],[23,17],[22,17]]\n        for x in roll_ins_adj_rows:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # upper<->lower row roll-outs:\n        roll_ins_skip_home = [[1,10],[1,11],[1,12],[2,11],[2,12],[3,12], [9,2],[9,3],[9,4],[10,3],[10,4],[11,4],\n                              [16,23],[16,22],[16,21],[15,22],[15,21],[14,21], [24,15],[24,14],[24,13],[23,14],[23,13],[22,13]]\n        for x in roll_ins_skip_home:\n            T[x[1]-1, x[0]-1] *= outward\n\n    # 9.  Avoid stretching shorter fingers up and longer fingers down.\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    if index_above < 1.0:\n        for x in [4]:\n            for y in [4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n        for x in [13]:\n            for y in [1,2,3,4,5,6,7,8,9,10,11,12,13,17,18,19,20,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n    if inside_top < 1.0:\n        for x in [4,13]:\n            for j in range(0,24):\n                T[x-1, j] *= inside_top\n                T[j, x-1] *= inside_top\n    if side_top < 1.0:\n        for x in [1,4,13,16]:\n            for j in range(0,24):\n                T[x-1, j] *= side_top\n                T[j, x-1] *= side_top\n    if side_above_1away < 1.0:\n        for x in [1]:\n            for y in [6,10]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [5]:\n            for y in [10]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [4]:\n            for y in [7,11]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [8]:\n            for y in [11]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [13]:\n            for y in [18,22]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [17]:\n            for y in [22]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [16]:\n            for y in [19,23]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [20]:\n            for y in [23]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n    if side_above_2away < 1.0:\n        for x in [1]:\n            for y in [7,11]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [5]:\n            for y in [11]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [4]:\n            for y in [6,10]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [8]:\n            for y in [10]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [13]:\n            for y in [19,23]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [17]:\n            for y in [23]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [16]:\n            for y in [18,22]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [20]:\n            for y in [22]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n    if side_above_3away < 1.0:\n        for x in [1]:\n            for y in [8,12]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [5]:\n            for y in [12]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [4]:\n            for y in [5,9]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [8]:\n            for y in [9]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [13]:\n            for y in [20,24]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [17]:\n            for y in [24]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [16]:\n            for y in [17,21]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [20]:\n            for y in [21]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n    if shorter_above < 1.0:\n        for x in [1]:\n            for y in [6,7,8,10,11,12]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [2]:\n            for y in [7,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [4]:\n            for y in [6,7,10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [5]:\n            for y in [10,11,12]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [6]:\n            for y in [11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [8]:\n            for y in [10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [16]:\n            for y in [17,18,19,21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [15]:\n            for y in [18,22]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [13]:\n            for y in [18,19,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [20]:\n            for y in [21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [19]:\n            for y in [22]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [17]:\n            for y in [22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n    if ring_above_middle < 1.0:\n        ring_above_middles =  [[2,7],[6,11],[2,11],\n                            [15,18],[19,22],[15,22]]\n        for x in ring_above_middles:\n            T[x[0]-1, x[1]-1] *= ring_above_middle\n            T[x[1]-1, x[0]-1] *= ring_above_middle\n\n    if middle_above_ring < 1.0:\n        middle_above_rings =  [[6,3],[10,7],[10,3],\n                            [19,14],[23,18],[23,14]]\n        for x in middle_above_rings:\n            T[x[0]-1, x[1]-1] *= middle_above_ring\n            T[x[1]-1, x[0]-1] *= middle_above_ring\n\n    # 10. Avoid using the same finger.\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    if same_finger < 1.0:\n        same_fingers = [[1,5],[5,9],[1,9], [2,6],[6,10],[2,10], [3,7],[7,11],[3,11], [4,8],[8,12],[4,12],\n                        [13,17],[17,21],[13,21], [14,18],[18,22],[14,22], [15,19],[19,23],[15,23], [16,20],[20,24],[16,24]] \n        for x in same_fingers:\n            T[x[0]-1, x[1]-1] *= same_finger\n            T[x[1]-1, x[0]-1] *= same_finger\n\n    # 11. Avoid the upper and lower rows.\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    if not_home_row < 1.0:\n        not_home_row_keys = [1,2,3,4, 9,10,11,12, 13,14,15,16, 21,22,23,24]\n        for x in not_home_row_keys:\n            for j in range(0,23):\n                T[x-1, j] *= not_home_row\n                T[j, x-1] *= not_home_row\n\n    # 12. Avoid skipping over the home row.\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    if skip_row_0away < 1.0:\n        skip_top = [1, 2, 3, 4, 13,14,15,16] \n        skip_bot = [9,10,11,12, 21,22,23,24] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_0away\n            T[y-1, x-1] *= skip_row_0away\n    if skip_row_1away < 1.0:\n        skip_top = [1, 2, 2, 3, 3, 4, 13,14,14,15,15,16] \n        skip_bot = [10,9,11,10,12,11, 22,21,23,22,24,23] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_1away\n            T[y-1, x-1] *= skip_row_1away\n    if skip_row_2away < 1.0:\n        skip_top = [1,  2,3, 4, 13,14,15,16] \n        skip_bot = [11,12,9,10, 23,24,21,22] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_2away\n            T[y-1, x-1] *= skip_row_2away\n    if skip_row_3away < 1.0:\n        skip_top = [1, 4, 13,16] \n        skip_bot = [12,9, 24,21] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_3away\n            T[y-1, x-1] *= skip_row_3away\n\n    Flow24x24 = T\n\n    # Normalize matrix with min-max scaling to a range with maximum = 1:\n    newMin = np.min(Flow24x24) / np.max(Flow24x24)\n    newMax = 1.0\n    Flow24x24 = newMin + (Flow24x24 - np.min(Flow24x24)) * (newMax - newMin) / (np.max(Flow24x24) - np.min(Flow24x24))\n\n    return Flow24x24\n\nFlow24x24 = create_24x24_flow_matrix(not_home_row, side_top, \n    side_above_3away, side_above_2away, side_above_1away, middle_above_ring, ring_above_middle, outward, \n    skip_row_3away, skip_row_2away, skip_row_1away, skip_row_0away, same_finger, lateral, same_hand, \n    shorter_above, adjacent_offset, inside_top, index_above)\n\n# Print:\nprint_matrix_info(matrix_data=Flow24x24, matrix_label=\"Flow24x24\", nkeys=24, nlines=30)\nheatmap(data=Flow24x24, title=\"Flow24x24\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n\ndef create_32x32_flow_matrix(not_home_row, side_top, side_above_3away, side_above_2away, side_above_1away, \n                             middle_above_ring, ring_above_middle, outward, skip_row_3away, \n                             skip_row_2away, skip_row_1away, skip_row_0away, same_finger, lateral, \n                             same_hand, shorter_above, adjacent_offset, inside_top, index_above):\n\n    all_32_keys = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, \n                   25,26,27, 28,29,30, 31,32]\n\n    # Create a matrix and multiply by flow factors that promote easy interkey transitions:\n    T = np.ones((32, 32))\n\n    if lateral < 1.0:\n        for x in all_32_keys:\n            for y in [25,26,27, 28,29,30, 31,32]:\n                T[x-1, y-1] *= lateral\n                T[y-1, x-1] *= lateral    \n\n    # 7.  Promote alternating between hands over uncomfortable transitions with the same hand.\n    if same_hand < 1.0:\n        for i in [1,2,3,4,5,6,7,8,9,10,11,12, 25,26,27]:\n            for j in [1,2,3,4,5,6,7,8,9,10,11,12, 25,26,27]:\n                T[i-1,j-1] *= same_hand\n        for i in [13,14,15,16,17,18,19,20,21,22,23,24, 28,29,30,31,32]:\n            for j in [13,14,15,16,17,18,19,20,21,22,23,24, 28,29,30,31,32]:\n                T[i-1,j-1] *= same_hand\n\n    # 8.  Promote little-to-index-finger roll-ins over index-to-little-finger outsward rolls.\n    # Penalize (index, little) finger lateral movements:\n    #  1  2  3  4 25   28 13 14 15 16 31 \n    #  5  6  7  8 26   29 17 18 19 20 32\n    #  9 10 11 12 27   30 21 22 23 24\n    if outward < 1.0:\n\n        # same-row roll-outs:\n        roll_ins = [[1,2],[2,3],[3,4], [5,6],[6,7],[7,8], [9,10],[10,11],[11,12],\n                    [16,15],[15,14],[14,13], [20,19],[19,18],[18,17], [24,23],[23,22],[22,21]]\n        for x in roll_ins:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # same-row roll-outs, skipping keys:\n        roll_ins_skip_keys = [[1,3],[2,4],[1,4], [5,7],[6,8],[5,8], [9,11],[10,12],[9,12],\n                              [16,14],[15,13],[16,13], [20,18],[19,17],[20,17], [24,22],[23,21],[24,21]]\n                              #[1,25],[2,25],[3,25],\n                              #[5,26],[6,26],[7,26],\n                              #[9,27],[10,27],[11,27],\n                              #[16,28],[15,28],[14,28],\n                              #[20,29],[19,29],[18,29],\n                              #[24,30],[23,30],[22,30],\n                              #[31,15],[31,14],[31,13],[31,28],\n                              #[32,19],[32,18],[32,17],[32,29]]\n        for x in roll_ins_skip_keys:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # adjacent-row roll-outs:\n        #  1  2  3  4 25   28 13 14 15 16 31 \n        #  5  6  7  8 26   29 17 18 19 20 32\n        #  9 10 11 12 27   30 21 22 23 24\n        roll_ins_adj_rows = [[1,6],[1,7],[1,8],[2,7],[2,8],[3,8], \n                             [5,2],[5,3],[5,4],[6,3],[6,4],[7,4],\n                             [5,10],[5,11],[5,12],[6,11],[6,12],[7,12], \n                             [9,6],[9,7],[9,8],[10,7],[10,8],[11,8],\n                             [16,19],[16,18],[16,17],[15,18],[15,17],[14,17], \n                             [20,15],[20,14],[20,13],[19,14],[19,13],[18,13],\n                             [20,23],[20,22],[20,21],[19,22],[19,21],[18,21], \n                             [24,19],[24,18],[24,17],[23,18],[23,17],[22,17]]\n                             #[5,25],[6,25],[7,25],[8,25],\n                             #[5,27],[6,27],[7,27],[8,27],\n                             #[1,26],[2,26],[3,26],[4,26],\n                             #[9,26],[10,26],[11,26],[12,26],\n                             #[16,29],[15,29],[14,29],[13,29],\n                             #[24,29],[23,29],[22,29],[21,29],\n                             #[20,28],[19,28],[18,28],[17,28],\n                             #[20,30],[19,30],[18,30],[17,30],\n                             #[31,20],[31,19],[31,18],[31,17],[31,29],\n                             #[32,16],[32,15],[32,14],[32,13],[32,28],\n                             #[32,24],[32,23],[32,22],[32,21],[32,30]]\n        for x in roll_ins_adj_rows:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # upper<->lower row roll-outs:\n        roll_ins_skip_home = [[1,10],[1,11],[1,12],[2,11],[2,12],[3,12],\n                              [9,2],[9,3],[9,4],[10,3],[10,4],[11,4],\n                              [16,23],[16,22],[16,21],[15,22],[15,21],[14,21],\n                              [24,15],[24,14],[24,13],[23,14],[23,13],[22,13]]\n                              #[16,30],[15,30],[14,30],[13,30],\n                              #[9,25],[10,25],[11,25],[12,25],\n                              #[24,28],[23,28],[22,28],[21,28],\n                              #[1,27],[2,27],[3,27],[4,27], \n                              #[31,24],[31,23],[31,22],[31,21],[31,30]]\n        for x in roll_ins_skip_home:\n            T[x[1]-1, x[0]-1] *= outward\n\n    # 9.  Avoid stretching shorter fingers up and longer fingers down.\n    #  1  2  3  4 25   28 13 14 15 16 31 \n    #  5  6  7  8 26   29 17 18 19 20 32\n    #  9 10 11 12 27   30 21 22 23 24\n    if index_above < 1.0:\n        for x in [4]:\n            for y in [4,5,6,7,8,26,9,10,11,12,27,28,13,14,15,16,31,29,17,18,19,20,32,30,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n        for x in [25]:\n            for y in [25,5,6,7,8,26,9,10,11,12,27,28,13,14,15,16,31,29,17,18,19,20,32,30,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n        for x in [13]:\n            for y in [1,2,3,4,25,5,6,7,8,26,9,10,11,12,27,13,29,17,18,19,20,32,30,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n        for x in [28]:\n            for y in [1,2,3,4,25,5,6,7,8,26,9,10,11,12,27,28,29,17,18,19,20,32,30,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n    if inside_top < 1.0:\n        for x in [4,25,28,13]:\n            for j in range(0,32):\n                T[x-1, j] *= inside_top\n                T[j, x-1] *= inside_top\n    if side_top < 1.0:\n        for x in [1,4,25,28,13,16,31]:\n            for j in range(0,32):\n                T[x-1, j] *= side_top\n                T[j, x-1] *= side_top\n    if side_above_1away < 1.0:\n        for x in [1]:\n            for y in [6,10]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [5]:\n            for y in [10]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [4,25]:\n            for y in [7,11]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [8,26]:\n            for y in [11]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [13,28]:\n            for y in [18,22]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [17,29]:\n            for y in [22]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [16,31]:\n            for y in [19,23]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [20,32]:\n            for y in [23]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n    if side_above_2away < 1.0:\n        for x in [1]:\n            for y in [7,11]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [5]:\n            for y in [11]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [4,25]:\n            for y in [6,10]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [8,26]:\n            for y in [10]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [13,28]:\n            for y in [19,23]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [17,29]:\n            for y in [23]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [16,31]:\n            for y in [18,22]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [20,32]:\n            for y in [22]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n    if side_above_3away < 1.0:\n        for x in [1]:\n            for y in [8,12,26,27]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [5]:\n            for y in [12,27]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [4,25]:\n            for y in [5,9]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [8,26]:\n            for y in [9]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [13,28]:\n            for y in [20,24,32]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [17,29]:\n            for y in [24]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [16,31]:\n            for y in [17,21,29,30]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [20,32]:\n            for y in [21,30]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n\n\n    #  1  2  3  4 25   28 13 14 15 16 31 \n    #  5  6  7  8 26   29 17 18 19 20 32\n    #  9 10 11 12 27   30 21 22 23 24\n    if shorter_above < 1.0:\n        for x in [1]:\n            for y in [6,7,8,26,10,11,12,27]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [2]:\n            for y in [7,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [4]:\n            for y in [6,7,10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [25]:\n            for y in [6,7,10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [5]:\n            for y in [10,11,12,27]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [6]:\n            for y in [11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [8]:\n            for y in [10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [26]:\n            for y in [10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [16]:\n            for y in [29,17,18,19,30,21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [31]:\n            for y in [29,17,18,19,30,21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [15]:\n            for y in [18,22]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [13]:\n            for y in [18,19,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [28]:\n            for y in [18,19,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [20]:\n            for y in [30,21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [32]:\n            for y in [30,21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [19]:\n            for y in [22]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [17]:\n            for y in [22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [29]:\n            for y in [22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n    if ring_above_middle < 1.0:\n        ring_above_middles =  [[2,7],[6,11],[2,11],\n                            [15,18],[19,22],[15,22]]\n        for x in ring_above_middles:\n            T[x[0]-1, x[1]-1] *= ring_above_middle\n            T[x[1]-1, x[0]-1] *= ring_above_middle\n\n    if middle_above_ring < 1.0:\n        middle_above_rings =  [[6,3],[10,7],[10,3],\n                            [19,14],[23,18],[23,14]]\n        for x in middle_above_rings:\n            T[x[0]-1, x[1]-1] *= middle_above_ring\n            T[x[1]-1, x[0]-1] *= middle_above_ring\n\n    # 10. Avoid using the same finger.\n    #  1  2  3  4 25   28 13 14 15 16 31 \n    #  5  6  7  8 26   29 17 18 19 20 32\n    #  9 10 11 12 27   30 21 22 23 24\n    if same_finger < 1.0:\n        same_fingers = [[1,5],[5,9],[1,9], [2,6],[6,10],[2,10], \n                        [3,7],[7,11],[3,11], [4,8],[8,12],[4,12],\n                        [25,26],[26,27],[25,27], [28,29],[29,30],[28,30], [31,32],\n                        [4,25],[4,26],[4,27], [8,25],[8,26],[8,27], [12,25],[12,26],[12,27],\n                        [13,28],[13,29],[13,30], [17,28],[17,29],[17,30], [21,28],[21,29],[21,30],\n                        [31,16],[31,20],[31,24], [32,16],[32,20],[32,24],\n                        [13,17],[17,21],[13,21], [14,18],[18,22],[14,22], \n                        [15,19],[19,23],[15,23], [16,20],[20,24],[16,24]] \n        for x in same_fingers:\n            T[x[0]-1, x[1]-1] *= same_finger\n            T[x[1]-1, x[0]-1] *= same_finger\n\n    # 11. Avoid the upper and lower rows.\n    if not_home_row < 1.0:\n        not_home_row_keys = [1,2,3,4,25, 9,10,11,12,27, 28,13,14,15,16,31, 30,21,22,23,24]\n        for x in not_home_row_keys:\n            for j in range(0,32):\n                T[x-1, j] *= not_home_row\n                T[j, x-1] *= not_home_row\n                \n    # 12. Avoid skipping over the home row.\n    #  1  2  3  4 25   28 13 14 15 16 31 \n    #  5  6  7  8 26   29 17 18 19 20 32\n    #  9 10 11 12 27   30 21 22 23 24\n    if skip_row_0away < 1.0:\n        skip_top = [1, 2, 3, 4, 4,25,25, 28,28,13,13,14,15,16,31] \n        skip_bot = [9,10,11,12,27,12,27, 30,21,30,21,22,23,24,24] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_0away\n            T[y-1, x-1] *= skip_row_0away\n    if skip_row_1away < 1.0:\n        skip_top = [1, 2, 2, 3, 3, 4, 4,25, 28,13,13,14,14,15,15,16,31] \n        skip_bot = [10,9,11,10,12,11,27,11, 22,30,22,21,23,22,24,23,23] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_1away\n            T[y-1, x-1] *= skip_row_1away\n    if skip_row_2away < 1.0:\n        skip_top = [1,  2,3, 4,25, 28,13,14,15,16,31] \n        skip_bot = [11,12,9,10,10, 23,23,24,21,22,22] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_2away\n            T[y-1, x-1] *= skip_row_2away\n    if skip_row_3away < 1.0:\n        skip_top = [1, 4,25, 28,13,16,16,31,31] \n        skip_bot = [12,9, 9, 24,24,21,30,21,30] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_3away\n            T[y-1, x-1] *= skip_row_3away\n                \n    Flow32x32 = T\n\n    # Normalize matrix with min-max scaling to a range with maximum = 1:\n    newMin = np.min(Flow32x32) / np.max(Flow32x32)\n    newMax = 1.0\n    Flow32x32 = newMin + (Flow32x32 - np.min(Flow32x32)) * (newMax - newMin) / (np.max(Flow32x32) - np.min(Flow32x32))\n\n    return Flow32x32\n\nFlow32x32 = create_32x32_flow_matrix(not_home_row, side_top, \n    side_above_3away, side_above_2away, side_above_1away, middle_above_ring, ring_above_middle, outward, \n    skip_row_3away, skip_row_2away, skip_row_1away, skip_row_0away, same_finger, lateral, same_hand, \n    shorter_above, adjacent_offset, inside_top, index_above)\n\n# Print:\nprint_matrix_info(matrix_data=Flow32x32, matrix_label=\"Flow32x32\", nkeys=32, nlines=30)\nheatmap(data=Flow32x32, title=\"Flow32x32\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n```\n\n## Combine Strength and Flow matrices  <a name=\"strengthflow\">\n\n\n```python\n# %load code/combine_scoring_matrices.py\n# 24 keys:\nFactors24x24 = Flow24x24\nif apply_strength:\n    Factors24x24 = Strength24x24 * Factors24x24\n\n# Print:\nprint_matrix_info(matrix_data=Factors24x24, matrix_label=\"Factors24x24\", nkeys=24, nlines=30)\nheatmap(data=Factors24x24, title=\"Factors24x24\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n# Save:\nif print_output:\n    file = open(\"Factors24x24.txt\", \"w+\")\n    file.write(str(Factors24x24))\n    file.close()\n\n\n# 32 keys:\nFactors32x32 = Flow32x32\nif apply_strength:\n    Factors32x32 = Strength32x32 * Factors32x32\n\n# Print:\nprint_matrix_info(matrix_data=Factors32x32, matrix_label=\"Factors32x32\", nkeys=32, nlines=30)\nheatmap(data=Factors32x32, title=\"Factors32x32\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n# Save:\nif print_output:\n    file = open(\"Factors32x32.txt\", \"w+\")\n    file.write(str(Factors32x32))\n    file.close()\n```\n\n## Four steps\n\nWe will assign letters to keys by choosing the arrangement with the highest score according to our scoring model. However, there are over four hundred septillion, or four hundred trillion trillion (26! = 403,291,461,126,605,635,584,000,000, or 4.032914611 E+26) possible arrangements of 26 letters (24! = 6.204484017 E+23), so we will arrange the letters in four steps, based on ergonomics principles. These consist of (Step 1) assigning the eight most frequent letters to different keys, optimizing assignment of the remaining (Step 2) eight most frequent letters, and (Step 3) eight least frequent letters (besides Z and Q), and (Step 4) exchanging letters. \n\n## Step 1: Define the shape of the key layout to minimize lateral finger movements<a name=\"step1\">\n\nWe will assign 24 letters to 8 columns of keys separated by two middle columns reserved for punctuation. These 8 columns require no lateral finger movements when touch typing, since there is one column per finger. The most comfortable keys include the left and right home rows (keys 5-8 and 17-20), the top-center keys (2,3 and 14,15) that allow the longer middle and ring fingers to uncurl upwards, as well as the bottom corner keys (9,12 and 21,24) that allow the shorter fingers to curl downwards. We will assign the two least frequent letters, Z and Q (or J), to the two hardest-to-reach keys lying outside the 24-key columns in the upper right (25 and 26):\n\n        Left:            Right:\n     1  2  3  4       13 14 15 16 25\n     5  6  7  8       17 18 19 20 26\n     9 10 11 12       21 22 23 24\n\nWe will consider the most comfortable keys to be those typed by either hand on the home row, by the ring and middle finger above the home row, and by the index and little finger below the home row, with a preference for the strongest (index and middle) fingers:\n    \n     -  2  3  -        - 14 15  -  \n     5  6  7  8       17 18 19 20  \n     9  -  - 12       21  -  - 24\n\n## Step 2: Arrange the most frequent letters based on comfort and bigram frequencies  <a name=\"step2\">\n\nIn prior experiments using the methods below, all vowels consistently automatically clustered together. Below, we will arrange vowels on one side and the most frequent consonants to the other side to encourage balance and alternation across hands. Since aside from the letters Z and Q there is symmetry across left and right sides, we will decide later which side the vowels and which side the most frequent consonants should go.\n\n### Vowels\n    \n**E**, T, **A, O, I**, N, S, R, H, L, D, C, U, M, F, P, G, W, Y, B, V, K, X, J, Q, Z\n\nThe highest frequency bigrams that contain two vowels are listed below in bold, with more than 10 billion instances in Peter Norvig's analysis of Google data:\n\n**OU, IO, EA, IE**, AI, IA, EI, UE, UA, AU, UI, OI, EO, OA, OE \n    \n     OU  24,531,132,241\n     IO  23,542,263,265\n     EA  19,403,941,063\n     IE  10,845,731,320\n     AI   8,922,759,715\n     IA   8,072,199,471   \n     EI   5,169,898,489\n     UE   4,158,448,570       \n     UA   3,844,138,094   \n     AU   3,356,322,923\n     UI   2,852,182,384\n     OI   2,474,275,212\n     EO   2,044,268,477\n     OA   1,620,913,259\n     OE   1,089,254,517 \n   \nWe will assign the most frequent vowels with over 100 billion instances in Norvig's analysis (E=445,A=331,O=272,I=270) to four of the six most comfortable keys on the left side of the keyboard (keys 2,3,5,6,7,8). We will assign the letter E, the most frequent in the English language, to either of the strongest (index and middle) fingers on the home row, and assign the other three vowels such that (1) the home row keys typed by the index and middle fingers are not left vacant, and any top-frequency bigram (more than 10 billion instances in Norvig's analysis) (2) does not use the same finger and (3) reads from left to right (ex: EA, not AE) for ease of typing (inward roll from little to index finger vs. outward roll from index to little finger). These constraints lead to three arrangements of the four vowels:\n\n    - - O -    - - O -    - - - -    \n    - I E A    I - E A    I O E A\n    - - - -    - - - -    - - - -\n\n### Consonants\n\nOn the right side of the keyboard, we will assign four of the five most frequent consonants (with over 5% or 150 billion instances in Norvig's analysis: T=331, N=258, S=232, R=224, and H=180) to the four home row keys. We will assign the letter T, the most frequent consonant in the English language, to either of the strongest (index and middle) fingers on the home row. As with the left side, letters are placed so that top-frequency bigrams read from right to left (ex: HT, not TH) for ease of typing. The top-frequency bigrams (more than 10 billion instances in Norvig's analysis) include: TH, ND, ST, NT, CH, NS, CT, TR, RS, NC, and RT (below 10 billion instances these bigrams start to occur in reverse, such as RT and TS): \n    \n     TH 100,272,945,963  3.56% \n     ND  38,129,777,631  1.35%\n     ST  29,704,461,829  1.05%\n     NT  29,359,771,944  1.04%\n     CH  16,854,985,236  0.60%\n     NS  14,350,320,288   \n     CT  12,997,849,406\n     TR  12,006,693,396       \n     RS  11,180,732,354   \n     NC  11,722,631,112\n     RT  10,198,055,461   \n    \nThe above constraints lead to five arrangements of the consonants:\n\n    - - - -    - - - -    - - - -    - - - -    - - - -\n    R T S N    H T S N    H T S R    H T N R    T S N R\n    - - - -    - - - -    - - - -    - - - -    - - - -\n\nWe will assign the fifth consonant to a vacant key on the left home row if there is a vacancy, otherwise to the key below the right index finger (any other assignment requires the same finger to type a high-frequency bigram). The resulting 19 initial layouts, each with 15 unassigned keys, are represented below with the three rows on the left and right side of the keyboard as a linear string of letters, with unassigned keys denoted by \u201c-\u201d.\n    \n    --O- HIEA ----    ---- RTSN ----\n    --O- RIEA ----    ---- HTSN ----\n    --O- NIEA ----    ---- HTSR ----\n    --O- SIEA ----    ---- HTNR ----\n    --O- IHEA ----    ---- RTSN ----\n    --O- IREA ----    ---- HTSN ----\n    --O- INEA ----    ---- HTSR ----\n    --O- ISEA ----    ---- HTNR ----\n    --O- -IEA ----    ---- RTSN H---\n    --O- -IEA ----    ---- HTSN R---\n    --O- -IEA ----    ---- HTSR N---\n    --O- I-EA ----    ---- RTSN H---\n    --O- I-EA ----    ---- HTSN R---\n    --O- I-EA ----    ---- HTSR N---\n    ---- IOEA ----    ---- RTSN H---\n    ---- IOEA ----    ---- HTSN R---\n    ---- IOEA ----    ---- HTSR N---\n    --O- HIEA ----    ---- TSNR ----\n    --O- IHEA ----    ---- TSNR ----\n\n## Step 3: Optimize assignment of the remaining letters <a name=\"step3\">\n    \nWe want to assign letters to the 17 unassigned keys in each of the above 19 layouts based on our scoring model. That would mean scoring all possible arrangements for each layout and choosing the arrangement with the highest score, but since there are over 355 trillion (17!) possible ways of arranging 17 letters, we will break up the assignment into two stages for the most frequent and least frequent remaining letters. \n    \n### Most frequent letters\nWe will compute scores for every possible arrangement of the seven most frequent of the remaining letters (in bold below) assigned to vacancies among the most comfortable sixteen keys.\n\nE, T, A, O, I, N, S, R, H, **L, D, C, U, M, F, P**, G, W, Y, B, V, K, X, J, Q, Z\n\n        Left:            Right:\n     -  2  3  -        - 14 15  -\n     5  6  7  8       17 18 19 20\n     9  -  - 12       21  -  - 24\n\nSince there are 5,040 (7!) possible combinations of eight letters for each of the 19 layouts, we need to score and evaluate 95,760 layouts. To score each arrangement of letters, we construct a frequency matrix where we multiply a matrix containing the frequency of each ordered pair of letters (bigram) by our flow and strength matrices to compute a score.\n    \n### Least frequent letters\nNext we will compute scores for every possible (40,320 = 8!) arrangement of the least frequent eight letters (in bold below, besides Z and Q) in the remaining keys, after substituting in the 19 results of the above for an additional 766,080 layouts:\n\nE, T, A, O, I, N, S, R, H, L, D, C, U, M, F, P, **G, W, Y, B, V, K, X, J**, Q, Z\n\n        Left:            Right:\n     1  -  -  4       13  -  - 16\n     -  -  -  -        -  -  -  -\n     - 10 11  -        - 22 23  -\n     \n### Further optimize layouts by exchanging more letters\n\nIf we relax the above fixed initializations and permit further exchange of letters, then we can search for even higher-scoring layouts. As a final optimization step we exchange letters, eight keys at a time (8! = 40,320) selected twice in 14 different ways, in each of the above 19 layouts, to score a total of 21,450,240 more combinations. We allow the following keys to exchange letters:\n\n    1. Top rows\n    2. Bottom rows\n    3. Top and bottom rows on the right side\n    4. Top and bottom rows on the left side\n    5. Top right and bottom left rows\n    6. Top left and bottom right rows\n    7. Center of the top and bottom rows on both sides\n    8. The eight corners\n    9. Left half of the top and bottom rows on both sides\n    10. Right half of the top and bottom rows on both sides\n    11. Left half of non-home rows on the left and right half of the same rows on the right\n    12. Right half of non-home rows on the left and left half of the same rows on the right\n    13. Top center and lower sides\n    14. Top sides and lower center\n    15. Repeat 1-14\n\n\n```python\n\"\"\"\nNOTE: This procedure takes hours to run.\n\n    --O- HIEA ----    ---- RTSN ----\n    --O- RIEA ----    ---- HTSN ----\n    --O- NIEA ----    ---- HTSR ----\n    --O- SIEA ----    ---- HTNR ----\n    --O- IHEA ----    ---- RTSN ----\n    --O- IREA ----    ---- HTSN ----\n    --O- INEA ----    ---- HTSR ----\n    --O- ISEA ----    ---- HTNR ----\n    --O- -IEA ----    ---- RTSN H---\n    --O- -IEA ----    ---- HTSN R---\n    --O- -IEA ----    ---- HTSR N---\n    --O- I-EA ----    ---- RTSN H---\n    --O- I-EA ----    ---- HTSN R---\n    --O- I-EA ----    ---- HTSR N---\n    ---- IOEA ----    ---- RTSN H---\n    ---- IOEA ----    ---- HTSN R---\n    ---- IOEA ----    ---- HTSR N---\n    --O- HIEA ----    ---- TSNR ----\n    --O- IHEA ----    ---- TSNR ----\n\n\"\"\"\nfixed_letter_lists1 = [\n    ['O','H','I','E','A','R','T','S','N'],\n    ['O','R','I','E','A','H','T','S','N'],\n    ['O','N','I','E','A','H','T','S','R'],\n    ['O','S','I','E','A','H','T','N','R'],\n    ['O','I','H','E','A','R','T','S','N'],\n    ['O','I','R','E','A','H','T','S','N'],\n    ['O','I','N','E','A','H','T','S','R'],\n    ['O','I','S','E','A','H','T','N','R'],\n    ['O','I','E','A','R','T','S','N','H'],\n    ['O','I','E','A','H','T','S','N','R'],\n    ['O','I','E','A','H','T','S','R','N'],\n    ['O','I','E','A','R','T','S','N','H'],\n    ['O','I','E','A','H','T','S','N','R'],\n    ['O','I','E','A','H','T','S','R','N'],\n    ['I','O','E','A','R','T','S','N','H'],\n    ['I','O','E','A','H','T','S','N','R'],\n    ['I','O','E','A','H','T','S','R','N'],\n    ['O','H','I','E','A','T','S','N','R'],\n    ['O','I','H','E','A','T','S','N','R']]\n\n# Keys for step 1:\n#     -  2  3  -        - 14 15  -\n#     5  6  7  8       17 18 19 20\n#     9  -  - 12       21  -  - 24\nkeys1  = [2,3,   5,6,7,8, 9,12,  14,15, 17,18,19,20, 21,24]\n\n# Indices for step 1:\n#     -  0  1  -        -  8  9  -\n#     2  3  4  5       10 11 12 13\n#     6  -  -  7       14  -  - 15\nfixed_letter_index_lists1 = [[1, 2,3,4,5, 10,11,12,13],\n                             [1, 2,3,4,5, 10,11,12,13],\n                             [1, 2,3,4,5, 10,11,12,13],\n                             [1, 2,3,4,5, 10,11,12,13],\n                             [1, 2,3,4,5, 10,11,12,13],\n                             [1, 2,3,4,5, 10,11,12,13],\n                             [1, 2,3,4,5, 10,11,12,13],\n                             [1, 2,3,4,5, 10,11,12,13],\n                             [1,   3,4,5, 10,11,12,13, 14],\n                             [1,   3,4,5, 10,11,12,13, 14],\n                             [1,   3,4,5, 10,11,12,13, 14],\n                             [1, 2,  4,5, 10,11,12,13, 14],\n                             [1, 2,  4,5, 10,11,12,13, 14],\n                             [1, 2,  4,5, 10,11,12,13, 14],\n                             [   2,3,4,5, 10,11,12,13, 14],\n                             [   2,3,4,5, 10,11,12,13, 14],\n                             [   2,3,4,5, 10,11,12,13, 14],\n                             [1, 2,3,4,5, 10,11,12,13],\n                             [1, 2,3,4,5, 10,11,12,13]]\nopen_letter_index_lists1  = [[0, 6,7, 8,9, 14,15],\n                             [0, 6,7, 8,9, 14,15],\n                             [0, 6,7, 8,9, 14,15],\n                             [0, 6,7, 8,9, 14,15],\n                             [0, 6,7, 8,9, 14,15],\n                             [0, 6,7, 8,9, 14,15],\n                             [0, 6,7, 8,9, 14,15],\n                             [0, 6,7, 8,9, 14,15],\n                             [0, 2, 6,7, 8,9, 15],\n                             [0, 2, 6,7, 8,9, 15],\n                             [0, 2, 6,7, 8,9, 15],\n                             [0, 3, 6,7, 8,9, 15],\n                             [0, 3, 6,7, 8,9, 15],\n                             [0, 3, 6,7, 8,9, 15],\n                             [0,1,  6,7, 8,9, 15],\n                             [0,1,  6,7, 8,9, 15],\n                             [0,1,  6,7, 8,9, 15],\n                             [0, 6,7, 8,9, 14,15],\n                             [0, 6,7, 8,9, 14,15]]\n\n# All 24 key indices:\n#     0  1  2  3       12 13 14 15\n#     4  5  6  7       16 17 18 19\n#     8  9 10 11       20 21 22 23\n# Open indices:\n#     0  -  -  3       12  -  - 15\n#     -  -  -  -        -  -  -  -\n#     -  9 10  -        - 21 22  -\nfixed_letter_indices2 = [1,2, 4,5,6,7, 8,11, 13,14, 16,17,18,19, 20,23]\nopen_letter_indices2  = [0,3, 9,10, 12,15, 21,22]\nfixed_letter_index_lists3 = [[2, 4,5,6,7, 16,17,18,19],\n                             [2, 4,5,6,7, 16,17,18,19],\n                             [2, 4,5,6,7, 16,17,18,19],\n                             [2, 4,5,6,7, 16,17,18,19],\n                             [2, 4,5,6,7, 16,17,18,19],\n                             [2, 4,5,6,7, 16,17,18,19],\n                             [2, 4,5,6,7, 16,17,18,19],\n                             [2, 4,5,6,7, 16,17,18,19],\n                             [2,   5,6,7, 16,17,18,19, 20],\n                             [2,   5,6,7, 16,17,18,19, 20],\n                             [2,   5,6,7, 16,17,18,19, 20],\n                             [2, 4,  6,7, 16,17,18,19, 20],\n                             [2, 4,  6,7, 16,17,18,19, 20],\n                             [2, 4,  6,7, 16,17,18,19, 20],\n                             [   4,5,6,7, 16,17,18,19, 20],\n                             [   4,5,6,7, 16,17,18,19, 20],\n                             [   4,5,6,7, 16,17,18,19, 20],\n                             [2, 4,5,6,7, 16,17,18,19],\n                             [2, 4,5,6,7, 16,17,18,19]]\n\n# Loop through initialized layouts with assigned vowels and consonants \ntop_layouts = []\nnlists = len(fixed_letter_lists1)\nfor ilist, fixed_letters1 in enumerate(fixed_letter_lists1):\n    fixed_letter_indices1 = fixed_letter_index_lists1[ilist]\n    fixed_letter_indices3 = fixed_letter_index_lists3[ilist]\n    open_letter_indices1 = open_letter_index_lists1[ilist]\n\n    print('Layout {0}'.format(ilist+1))\n    print(*fixed_letters1)\n\n    print(\"Most frequent letters\")\n    top_permutation1, top_score1, letter_permutations1 = permute_optimize_keys(fixed_letters1, fixed_letter_indices1, \n                                                         open_letter_indices1, letters24, keys1, Factors24x24, \n                                                         bigrams, bigram_frequencies, min_score=0, verbose=False)\n    fixed_letters2 = top_permutation1\n    \n    print(\"Least frequent remaining letters\")\n    top_permutation2, top_score2, letter_permutations2 = permute_optimize_keys(fixed_letters2, fixed_letter_indices2, \n                                                         open_letter_indices2, letters24, keys24, Factors24x24, \n                                                         bigrams, bigram_frequencies, min_score=0, verbose=False)\n    fixed_letters3 = top_permutation2\n\n    print(\"Further optimize layouts by exchanging sets of letters\")\n    top_permutation3, top_score3 = exchange_letters(fixed_letters3, fixed_letter_indices3, letters24, keys24, \n                                                    Factors24x24, bigrams, bigram_frequencies, verbose=True)\n\n    top_layouts.append(top_permutation3)\n\n```\n\n\n\n\n#### Optimized layouts (outcome of above)\n\n\n```python\nload_top_layouts = True\nprint_layouts = False\nif load_top_layouts:\n    top_layouts = [\n    ['B','Y','O','U','H','I','E','A','V','K','J','X','L','D','G','F','R','T','S','N','C','M','W','P'],\n    ['W','Y','O','U','R','I','E','A','G','X','J','K','L','D','C','B','H','T','S','N','M','F','V','P'],\n    ['J','P','O','U','N','I','E','A','B','K','Y','X','M','C','G','V','H','T','S','R','L','D','F','W'],\n    ['J','P','O','U','S','I','E','A','G','K','Y','X','M','C','W','V','H','T','N','R','D','L','F','B'],\n    ['J','P','O','U','I','H','E','A','B','K','Y','X','L','D','G','F','R','T','S','N','C','M','V','W'],\n    ['J','W','O','U','I','R','E','A','G','X','K','Y','L','D','C','B','H','T','S','N','M','F','V','P'],\n    ['J','P','O','U','I','N','E','A','B','X','K','Y','M','C','G','V','H','T','S','R','L','D','F','W'],\n    ['J','G','O','U','I','S','E','A','P','X','K','Y','M','C','W','V','H','T','N','R','D','L','F','B'],\n    ['P','Y','O','U','C','I','E','A','G','K','J','X','L','D','F','B','R','T','S','N','H','M','V','W'],\n    ['B','Y','O','U','C','I','E','A','G','X','J','K','L','D','W','V','H','T','S','N','R','M','F','P'],\n    ['P','Y','O','U','C','I','E','A','G','K','J','X','M','L','F','B','H','T','S','R','N','D','V','W'],\n    ['J','G','O','U','I','C','E','A','B','X','Y','K','L','D','F','V','R','T','S','N','H','M','W','P'],\n    ['J','G','O','U','I','C','E','A','B','X','Y','K','L','D','W','V','H','T','S','N','R','M','F','P'],\n    ['P','G','O','U','I','C','E','A','K','X','J','Y','M','L','F','B','H','T','S','R','N','D','V','W'],\n    ['J','G','U','K','I','O','E','A','P','X','Y','F','L','D','V','B','R','T','S','N','H','M','C','W'],\n    ['J','G','U','X','I','O','E','A','W','K','Y','F','L','D','C','B','H','T','S','N','R','M','V','P'],\n    ['J','G','U','K','I','O','E','A','P','X','Y','F','M','L','B','W','H','T','S','R','N','D','V','C'],\n    ['J','P','O','U','H','I','E','A','G','K','Y','X','M','C','F','V','T','S','N','R','D','L','B','W'],\n    ['J','P','O','U','I','H','E','A','G','K','Y','X','M','C','F','V','T','S','N','R','D','L','B','W']]\nif print_layouts:\n    print('Layouts:\\n')\n    for layout in top_layouts:\n        print(layout)\n```\n\n### Rank optimized layouts\n\n\n```python\n# %load code/rank_layouts.py\nlayout_strings = []\nscores = []\nfor layout in top_layouts:\n    layout_string = ' '.join(layout)\n    score = score_layout(Factors24x24, layout, bigrams, bigram_frequencies, verbose=False)\n    #print('    {0}    {1}'.format(layout_string, score))\n    layout_strings.append(layout_string)\n    scores.append(score)\n\n# Establish which layouts are within a small difference of the top-scoring layout \nscores_sorted, ranks_sorted, Isort = rank_within_epsilon(scores, factor24, factor=True, verbose=False)\nlayouts_sorted = []\nlayout_strings_sorted = []\nfor i in Isort:\n    layouts_sorted.append(top_layouts[i])\n    layout_strings_sorted.append(layout_strings[i])\nprint('\\n    (#) Rank                                                Score')\nfor i, rank in enumerate(ranks_sorted):\n    print('    ({0}) {1}:  {2}    {3}'.format(i+1, rank, layout_strings_sorted[i], scores_sorted[i]))\n\nprint('\\nLayouts tied for first place, with relative letter frequencies:\\n')\n#print('    Rank                                                   Score')\nfirst_ranks = []\nfirst_layouts = []\nfirst_layout_strings = []\nfirst_scores = []\nfor i, rank in enumerate(ranks_sorted):\n    if rank == 1:\n        first_ranks.append(rank)\n        first_layouts.append(layout_strings_sorted[i])\n        first_layout_strings.append(layouts_sorted[i])\n        first_scores.append(scores_sorted[i])    \nIsort2 = np.argsort([-x for x in first_scores])\nfirst_ranks_sorted = []\nfirst_layouts_sorted = []\nfirst_layout_strings_sorted = []\nfirst_scores_sorted = []\nfor i in Isort2:\n    first_ranks_sorted.append(first_ranks[i])\n    first_layouts_sorted.append(first_layouts[i])\n    first_layout_strings_sorted.append(first_layout_strings[i])\n    first_scores_sorted.append(first_scores[i])\n#for i, first_layout in enumerate(first_layouts):\n#    print('    {0}:  {1}    {2}'.format(first_ranks_sorted[i], \n#                                        first_layout,  # first_layout_strings_sorted[i], \n#                                        first_scores_sorted[i]))\n\n# Print layouts:\nfor i, layout_string in enumerate(first_layout_strings_sorted):\n    layout = first_layouts_sorted[i]\n    print('    Layout {0}:\\n'.format(Isort2[i] + 1))\n    print_layout24(layout_string)\n    print('')\n    print_layout24_instances(layout_string, letters24, instances24, bigrams, bigram_frequencies)\n    print('')\n```\n\n#### Ranked, optimized layouts\n\nWe will select the second layout tied for first place as our candidate winner, so that the most frequent bigram (TH, over 100 billion) is on the home row and easier to type.\n\n    Rank                                                   Score\n    1:  P Y O U C I E A G K J X L D F B R T S N H M V W    0.7079134589554652\n    1:  B Y O U C I E A G X J K L D W V H T S N R M F P    0.7078676989043136\n    2:  J G O U I C E A B X Y K L D F V R T S N H M W P    0.7078208372363046\n    2:  B Y O U H I E A V K J X L D G F R T S N C M W P    0.7078164910125013\n    2:  J P O U H I E A G K Y X M C F V T S N R D L B W    0.707806617890607\n    2:  J G O U I C E A B X Y K L D W V H T S N R M F P    0.7077802597858632\n    3:  P Y O U C I E A G K J X M L F B H T S R N D V W    0.707765513186795\n    3:  J P O U I H E A G K Y X M C F V T S N R D L B W    0.7077455939244159\n    3:  J P O U I H E A B K Y X L D G F R T S N C M V W    0.7077426951024633\n    4:  P G O U I C E A K X J Y M L F B H T S R N D V W    0.7076779754232723\n    5:  J P O U S I E A G K Y X M C W V H T N R D L F B    0.707608035505442\n    5:  J G U K I O E A P X Y F L D V B R T S N H M C W    0.707560090465515\n    5:  W Y O U R I E A G X J K L D C B H T S N M F V P    0.7075589351593826\n    6:  J G O U I S E A P X K Y M C W V H T N R D L F B    0.707549787929756\n    6:  J G U X I O E A W K Y F L D C B H T S N R M V P    0.7075212659110061\n    7:  J W O U I R E A G X K Y L D C B H T S N M F V P    0.7074562433695609\n    7:  J P O U I N E A B X K Y M C G V H T S R L D F W    0.7074435243752765\n    7:  J P O U N I E A B K Y X M C G V H T S R L D F W    0.707432984110794\n    7:  J G U K I O E A P X Y F M L B W H T S R N D V C    0.7074108195944783\n\nAbove layouts that tied for first place, with letter frequencies (2nd layout identical to Engram v2.0):\n\n    P Y O U  L D F B     76  59 272  97  145 136  86  53\n    C I E A  R T S N    119 270 445 287  224 331 232 258\n    G K J X  H M V W     67  19   6   8  180  90  38  60\n\n    left: 1.725T  right: 1.831T (6.09%)\n    Total same-finger bigram frequencies:     31002467582\n    Total bigram inward roll frequencies:   4595272424809\n\n\n    B Y O U  L D W V     53  59 272  97  145 136  60  38\n    C I E A  H T S N    119 270 445 287  180 331 232 258\n    G X J K  R M F P     67   8   6  19  224  90  86  76\n\n    left: 1.702T  right: 1.854T (8.90%)\n    Total same-finger bigram frequencies:     31422990907\n    Total bigram inward roll frequencies:   4595756397870\n\n### Optional: rank variations of top-scoring layouts\n\nAs an alternative to simply choosing the candidate winner layout, we can generate variations of this layout and find those variants within a small difference of one another and select from among these variants. For this, we select keys to vary, compute scores for every combination of the letters assigned to these keys, and select among those that are tied for first place. Below we vary those keys with different letters in the two layouts tied for first place, except we fix H above R (as in the second layout, our candidate winner) so that the most frequent bigram (TH, over 100 billion) is easy to type.\n\n\n```python\nscore_variants = True\nif score_variants:\n\n    # Candidate winner above:\n    #\n    #  B Y O U  L D W V\n    #  C I E A  H T S N\n    #  G X J K  R M F P\n\n    #  - Y O U  L D - -\n    #  C I E A  H T S N\n    #  G - J -  R M - -\n\n    fixed_letters = ['Y','O','U', 'C','I','E','A', 'G','J', 'L','D', 'H','T','S','N', 'R','M']\n    fixed_letter_indices = [1,2,3, 4,5,6,7, 8,10, 12,13, 16,17,18,19, 20,21]\n    open_letter_indices  = [0, 9,11, 14,15, 22,23]\n\n    top_variant_permutation, top_variant_score, variant_letter_permutations = permute_optimize_keys(fixed_letters, \n        fixed_letter_indices, open_letter_indices, letters24, keys24, Factors24x24, \n        bigrams, bigram_frequencies, min_score=0, verbose=False)\n\n    print(top_variant_permutation)    \n    print(top_variant_score)\n```\n\n\n```python\nif score_variants:\n\n    variant_scores = []\n    nletters = len(fixed_letter_indices) + len(open_letter_indices)\n    layout_variant_strings = []\n    for ipermutation, letter_permutation in enumerate(variant_letter_permutations):\n        variant_letters = np.array(['W' for x in range(nletters)])  # KEEP to initialize!\n        for imove, open_letter_index in enumerate(open_letter_indices):\n            variant_letters[open_letter_index] = letter_permutation[imove]\n        for ifixed, fixed_letter_index in enumerate(fixed_letter_indices):\n            variant_letters[fixed_letter_index] = fixed_letters[ifixed]\n        layout_variant_strings.append(variant_letters)\n        # Compute the score for this permutation:\n        variant_score = score_layout(Factors24x24, variant_letters, \n                                     bigrams, bigram_frequencies, verbose=False)\n        variant_scores.append(variant_score)\n    \n    layout_variants = []\n    for layout_string in layout_variant_strings:\n        layout = ' '.join(layout_string)\n        layout_variants.append(layout)\n\n    variant_scores_sorted, variant_ranks_sorted, Isort_variants = rank_within_epsilon(variant_scores, \n            factor24, factor=True, verbose=False)\n    layout_variants_sorted = []\n    layout_variant_strings_sorted = []\n    for i in Isort_variants:\n        layout_variants_sorted.append(layout_variants[i])\n        layout_variant_strings_sorted.append(layout_variant_strings[i])\n\n    print('    (#) Rank: Layout                                           Score')\n    for i, rank in enumerate(variant_ranks_sorted):\n        if rank == 1:\n            print('    ({0}) {1}:  {2}    {3}'.format(i + 1, rank, \n                                                      layout_variants_sorted[i], \n                                                      variant_scores_sorted[i]))\n    # Print layouts:\n    Ifirst_place = []\n    layout_variants_first_place = []\n    layout_variant_strings_first_place = []\n    for i, rank in enumerate(variant_ranks_sorted):\n        if rank == 1:\n            layout_string = layout_variant_strings_sorted[i]\n            layout = layout_variants_sorted[i]\n            print('\\n    Layout {0}:\\n'.format(i + 1))\n            print_layout24(layout_string)\n            print('')\n            print_layout24_instances(layout_string, letters24, instances24, \n                                     bigrams, bigram_frequencies)\n\n            Ifirst_place.append(i)\n            layout_variants_first_place.append(layout)\n            layout_variant_strings_first_place.append(layout_string)\n```\n\nOur candidate winner scored highest among its (7! = 5,040) variants. The 42 variants tied for first place are listed below:\n\n    (#) Rank: Layout                                           Score\n    (1) 1:  B Y O U C I E A G X J K L D W V H T S N R M F P    0.7078676989043137\n    (2) 1:  B Y O U C I E A G K J X L D W V H T S N R M F P    0.7078625576908392\n    (3) 1:  W Y O U C I E A G X J K L D V B H T S N R M F P    0.7078577061845288\n    (4) 1:  P Y O U C I E A G K J X L D W V H T S N R M F B    0.7078565092277237\n    (5) 1:  W Y O U C I E A G K J X L D V B H T S N R M F P    0.7078522283063508\n    (6) 1:  B Y O U C I E A G X J K L D V W H T S N R M F P    0.7078519616931854\n    (7) 1:  P Y O U C I E A G X J K L D W V H T S N R M F B    0.7078517296463457\n    (8) 1:  B Y O U C I E A G X J K L D W F H T S N R M V P    0.7078490260211918\n    (9) 1:  B Y O U C I E A G K J X L D V W H T S N R M F P    0.707846820479711\n    (10) 1:  P Y O U C I E A G K J X L D W B H T S N R M V F    0.7078454560742882\n    (11) 1:  B Y O U C I E A G K J X L D W F H T S N R M V P    0.7078438848077173\n    (12) 1:  P Y O U C I E A G K J X L D W B H T S N R M F V    0.7078431094974508\n    (13) 1:  P Y O U C I E A G K J X L D V B H T S N R M F W    0.7078419742548276\n    (14) 1:  P Y O U C I E A G K J X L D V W H T S N R M F B    0.7078411358167733\n    (15) 1:  P Y O U C I E A G X J K L D W B H T S N R M V F    0.70784067649291\n    (16) 1:  W Y O U C I E A G X J K L D F B H T S N R M V P    0.7078403744444377\n    (17) 1:  P Y O U C I E A G K J X L D W F H T S N R M V B    0.7078391282354274\n    (18) 1:  P Y O U C I E A G X J K L D W B H T S N R M F V    0.7078383299160728\n    (19) 1:  P Y O U C I E A G X J K L D V B H T S N R M F W    0.7078371946734496\n    (20) 1:  W Y O U C I E A G X J K L D B V H T S N R M F P    0.7078371584583636\n    (21) 1:  P Y O U C I E A G X J K L D V W H T S N R M F B    0.7078363562353953\n    (22) 1:  B Y O U C I E A G X J K L D F W H T S N R M V P    0.7078359835497579\n    (23) 1:  W Y O U C I E A G K J X L D F B H T S N R M V P    0.7078348965662598\n    (24) 1:  P Y O U C I E A G X J K L D W F H T S N R M V B    0.7078343486540493\n    (25) 1:  W Y O U C I E A G K J X L D B V H T S N R M F P    0.7078316805801855\n    (26) 1:  B Y O U C I E A G K J X L D F W H T S N R M V P    0.7078308423362834\n    (27) 1:  P Y O U C I E A G K J X L D W V H T S N R M B F    0.7078260494151115\n    (28) 1:  P Y O U C I E A G K J X L D F W H T S N R M V B    0.7078260359767987\n    (29) 1:  P Y O U C I E A G K J X L D F B H T S N R M V W    0.7078245475443425\n    (30) 1:  W Y O U C I E A G X J K L D F V H T S N R M B P    0.7078214911264225\n    (31) 1:  P Y O U C I E A G K J X L D B V H T S N R M F W    0.7078214181411706\n    (32) 1:  P Y O U C I E A G X J K L D W V H T S N R M B F    0.7078212698337334\n    (33) 1:  P Y O U C I E A G X J K L D F W H T S N R M V B    0.7078212563954208\n    (34) 1:  B Y O U C I E A G X J K L D F V H T S N R M W P    0.7078210837714037\n    (35) 1:  P Y O U C I E A G X J K L D F B H T S N R M V W    0.7078197679629645\n    (36) 1:  W Y O U C I E A G X J K L D V F H T S N R M B P    0.70781880339861\n    (37) 1:  B Y O U C I E A G X J K L D V F H T S N R M W P    0.7078184238466051\n    (38) 1:  W Y O U C I E A G X J K L D B F H T S N R M V P    0.7078172387197521\n    (39) 1:  P Y O U C I E A G X J K L D B V H T S N R M F W    0.7078166385597925\n    (40) 1:  W Y O U C I E A G K J X L D F V H T S N R M B P    0.7078160132482443\n    (41) 1:  P Y O U C I E A G K J X L D V B H T S N R M W F    0.7078159646633373\n    (42) 1:  B Y O U C I E A G K J X L D F V H T S N R M W P    0.7078159425579292\n\nLetters shared across all layout variants tied for first place:\n\n    - Y O U  L D - -\n    C I E A  H T S N\n    G - J -  R M - -\n\nIf we list only those layouts in descending order by score that have progressively lower same-finger bigram counts, then we end up with the candidate winner (Variant 1) and Variant 3:\n        \n    Variant 1 = Layout 2 above:\n\n    B Y O U  L D W V\n    C I E A  H T S N\n    G X J K  R M F P\n\n     53  59 272  97  145 136  60  38\n    119 270 445 287  180 331 232 258\n     67   8   6  19  224  90  86  76\n\n    left: 1.702T  right: 1.854T (8.90%)\n    Total same-finger bigram frequencies:     31422990907\n    Total bigram inward roll frequencies:   4595756397870\n\n    Variant 3:\n\n    W Y O U  L D V B\n    C I E A  H T S N\n    G X J K  R M F P\n\n     60  59 272  97  145 136  38  53\n    119 270 445 287  180 331 232 258\n     67   8   6  19  224  90  86  76\n\n    left: 1.709T  right: 1.847T (8.07%)\n    Total same-finger bigram frequencies:     28475089052\n    Total bigram inward roll frequencies:   4605502028148\n\n\n```python\nif score_variants:\n    layout_variant_strings_first_place = [\n    ['B','Y','O','U','C','I','E','A','G','X','J','K','L','D','W','V','H','T','S','N','R','M','F','P'],\n    ['B','Y','O','U','C','I','E','A','G','K','J','X','L','D','W','V','H','T','S','N','R','M','F','P'],\n    ['W','Y','O','U','C','I','E','A','G','X','J','K','L','D','V','B','H','T','S','N','R','M','F','P'],\n    ['P','Y','O','U','C','I','E','A','G','K','J','X','L','D','W','V','H','T','S','N','R','M','F','B'],\n    ['W','Y','O','U','C','I','E','A','G','K','J','X','L','D','V','B','H','T','S','N','R','M','F','P'],\n    ['B','Y','O','U','C','I','E','A','G','X','J','K','L','D','V','W','H','T','S','N','R','M','F','P'],\n    ['P','Y','O','U','C','I','E','A','G','X','J','K','L','D','W','V','H','T','S','N','R','M','F','B'],\n    ['B','Y','O','U','C','I','E','A','G','X','J','K','L','D','W','F','H','T','S','N','R','M','V','P'],\n    ['B','Y','O','U','C','I','E','A','G','K','J','X','L','D','V','W','H','T','S','N','R','M','F','P'],\n    ['P','Y','O','U','C','I','E','A','G','K','J','X','L','D','W','B','H','T','S','N','R','M','V','F'],\n    ['B','Y','O','U','C','I','E','A','G','K','J','X','L','D','W','F','H','T','S','N','R','M','V','P'],\n    ['P','Y','O','U','C','I','E','A','G','K','J','X','L','D','W','B','H','T','S','N','R','M','F','V'],\n    ['P','Y','O','U','C','I','E','A','G','K','J','X','L','D','V','B','H','T','S','N','R','M','F','W'],\n    ['P','Y','O','U','C','I','E','A','G','K','J','X','L','D','V','W','H','T','S','N','R','M','F','B'],\n    ['P','Y','O','U','C','I','E','A','G','X','J','K','L','D','W','B','H','T','S','N','R','M','V','F'],\n    ['W','Y','O','U','C','I','E','A','G','X','J','K','L','D','F','B','H','T','S','N','R','M','V','P'],\n    ['P','Y','O','U','C','I','E','A','G','K','J','X','L','D','W','F','H','T','S','N','R','M','V','B'],\n    ['P','Y','O','U','C','I','E','A','G','X','J','K','L','D','W','B','H','T','S','N','R','M','F','V'],\n    ['P','Y','O','U','C','I','E','A','G','X','J','K','L','D','V','B','H','T','S','N','R','M','F','W'],\n    ['W','Y','O','U','C','I','E','A','G','X','J','K','L','D','B','V','H','T','S','N','R','M','F','P'],\n    ['P','Y','O','U','C','I','E','A','G','X','J','K','L','D','V','W','H','T','S','N','R','M','F','B'],\n    ['B','Y','O','U','C','I','E','A','G','X','J','K','L','D','F','W','H','T','S','N','R','M','V','P'],\n    ['W','Y','O','U','C','I','E','A','G','K','J','X','L','D','F','B','H','T','S','N','R','M','V','P'],\n    ['P','Y','O','U','C','I','E','A','G','X','J','K','L','D','W','F','H','T','S','N','R','M','V','B'],\n    ['W','Y','O','U','C','I','E','A','G','K','J','X','L','D','B','V','H','T','S','N','R','M','F','P'],\n    ['B','Y','O','U','C','I','E','A','G','K','J','X','L','D','F','W','H','T','S','N','R','M','V','P'],\n    ['P','Y','O','U','C','I','E','A','G','K','J','X','L','D','W','V','H','T','S','N','R','M','B','F'],\n    ['P','Y','O','U','C','I','E','A','G','K','J','X','L','D','F','W','H','T','S','N','R','M','V','B'],\n    ['P','Y','O','U','C','I','E','A','G','K','J','X','L','D','F','B','H','T','S','N','R','M','V','W'],\n    ['W','Y','O','U','C','I','E','A','G','X','J','K','L','D','F','V','H','T','S','N','R','M','B','P'],\n    ['P','Y','O','U','C','I','E','A','G','K','J','X','L','D','B','V','H','T','S','N','R','M','F','W'],\n    ['P','Y','O','U','C','I','E','A','G','X','J','K','L','D','W','V','H','T','S','N','R','M','B','F'],\n    ['P','Y','O','U','C','I','E','A','G','X','J','K','L','D','F','W','H','T','S','N','R','M','V','B'],\n    ['B','Y','O','U','C','I','E','A','G','X','J','K','L','D','F','V','H','T','S','N','R','M','W','P'],\n    ['P','Y','O','U','C','I','E','A','G','X','J','K','L','D','F','B','H','T','S','N','R','M','V','W'],\n    ['W','Y','O','U','C','I','E','A','G','X','J','K','L','D','V','F','H','T','S','N','R','M','B','P'],\n    ['B','Y','O','U','C','I','E','A','G','X','J','K','L','D','V','F','H','T','S','N','R','M','W','P'],\n    ['W','Y','O','U','C','I','E','A','G','X','J','K','L','D','B','F','H','T','S','N','R','M','V','P'],\n    ['P','Y','O','U','C','I','E','A','G','X','J','K','L','D','B','V','H','T','S','N','R','M','F','W'],\n    ['W','Y','O','U','C','I','E','A','G','K','J','X','L','D','F','V','H','T','S','N','R','M','B','P'],\n    ['P','Y','O','U','C','I','E','A','G','K','J','X','L','D','V','B','H','T','S','N','R','M','W','F'],\n    ['B','Y','O','U','C','I','E','A','G','K','J','X','L','D','F','V','H','T','S','N','R','M','W','P']]\n```\n\n## Step 4: Evaluate winning layout <a name=\"step4\">\n    \nWe evaluate the candidate winner with tests:\n    \n    1. Evaluate optimized layouts using interkey speed estimates\n    2. Evaluate variants of the candidate winner using interkey speed estimates\n    3. Evaluate sensitivity of the variants to the scoring parameters\n    4. Search for higher-scoring layouts by rearranging letters\n    5. Compare with alternate layout based solely on interkey speed estimates\n\n### Test 1. Evaluate optimized layouts using interkey speed estimates   \nBelow we rescore all of the 20 top-scoring layouts optimized from the 20 initialized layouts, and replace the factor matrix with the inter-key speed matrix. The same two layouts that tied for first place do so again.\n\n*Note:*\n    \nThe speed matrix contains normalized interkey stroke times derived from a published study (\"Estimation of digraph costs for keyboard layout optimization\", A Iseri, Ma Eksioglu, International Journal of Industrial Ergonomics, 48, 127-138, 2015). To establish which layouts are within a small difference of each other when using the speed matrix, we define an epsilon equal to 131.58 ms for a single bigram (of the 32^2 possible bigrams), where 131.58 ms is the fastest measured digraph tapping speed (30,000/228 = 131.58 ms) recorded in the above study.\n    \n\"Digraph-tapping rate changes dramatically across the digraph types. The range is between 82 and 228 taps per 30 s. The difference is nearly three times between the slowest and the fastest digraphs. From this result it can be concluded that the assignment of letter pairs on the correct digraph keys on the keyboard can have a high impact on the typing speed.\"\n\n\n```python\ntest_layout_strings = first_layout_strings_sorted\n```\n\n\n```python\n# %load code/test/score_speed_of_layouts.py\ndata_matrix_speed = Speed24x24  # SpeedSymmetric24x24\nspeed_scores = []\nfor letters in test_layout_strings:\n    score = score_layout(data_matrix_speed, letters, bigrams, bigram_frequencies, verbose = False) \n    speed_scores.append(score)\n\nspeed_scores_sorted, speed_ranks_sorted, Isort_speed = rank_within_epsilon(speed_scores, \n                                                                    epsilon, factor=False, verbose=False)\nspeed_layouts_sorted = []\nspeed_layout_strings_sorted = []\nfor i in Isort_speed:\n    speed_layouts_sorted.append(' '.join(test_layout_strings[i]))\n    speed_layout_strings_sorted.append(test_layout_strings[i])\n\ncount = 0\nprint('    (#)   Layout                                             Speed score')\nfor i, isort_speed in enumerate(Isort_speed):\n    if speed_ranks_sorted[isort_speed] == 1:\n        count += 1\n        if isort_speed < 9:\n            s = '  '\n        else:\n            s = ' '\n        print('    ({0}) {1}{2}    {3}'.format(isort_speed+1, s, \n                                               speed_layouts_sorted[i], \n                                               speed_scores_sorted[i]))\nprint('\\n    {0} of {1} layouts tied for first place'.format(count, len(test_layout_strings)))\n```\n\n### Test 2. Evaluate variants of the candidate winner using interkey speed estimates   \nBelow we rescore all of the 5,040 variants of the candidate winner that are tied for first place, replacing the factor matrix with the inter-key speed matrix. The candidate winner scores highest.\n\n\n```python\ntest_layout_strings = layout_variant_strings_first_place\n```\n\n\n```python\n# %load code/test/score_speed_of_layouts.py\ndata_matrix_speed = Speed24x24  # SpeedSymmetric24x24\nspeed_scores = []\nfor letters in test_layout_strings:\n    score = score_layout(data_matrix_speed, letters,  bigrams, bigram_frequencies, verbose = False) \n    speed_scores.append(score)\n\nspeed_scores_sorted, speed_ranks_sorted, Isort_speed = rank_within_epsilon(speed_scores, \n                                                                    epsilon, factor=False, verbose=False)\nspeed_layouts_sorted = []\nspeed_layout_strings_sorted = []\nfor i in Isort_speed:\n    speed_layouts_sorted.append(' '.join(test_layout_strings[i]))\n    speed_layout_strings_sorted.append(test_layout_strings[i])\n\ncount = 0\nprint('    Layout                                                  Speed score')\nfor i, isort_speed in enumerate(Isort_speed):\n    if speed_ranks_sorted[isort_speed] == 1:\n        count += 1\n        if isort_speed < 9:\n            s = '  '\n        else:\n            s = ' '\n        print('    ({0}){1}{2}    {3}'.format(isort_speed+1, s, \n                                              speed_layouts_sorted[i], \n                                              speed_scores_sorted[i]))\nprint('    {0} of {1} layouts tied for first place'.format(count, len(test_layout_strings)))\n```\n\nVariant 1 (the candidate winner above) scores highest:\n\n    Layout                                                  Speed score\n    (1)  B Y O U C I E A G X J K L D W V H T S N R M F P    0.7023756439425117\n    (30) W Y O U C I E A G X J K L D F V H T S N R M B P    0.7023734892525684\n    (20) W Y O U C I E A G X J K L D B V H T S N R M F P    0.7023700909720256\n    (6)  B Y O U C I E A G X J K L D V W H T S N R M F P    0.7023688377122477\n    (22) B Y O U C I E A G X J K L D F W H T S N R M V P    0.702367226885074\n    (3)  W Y O U C I E A G X J K L D V B H T S N R M F P    0.7023627643568422\n    (7)  P Y O U C I E A G X J K L D W V H T S N R M F B    0.7023607516204574\n    (16) W Y O U C I E A G X J K L D F B H T S N R M V P    0.7023603659811735\n    (8)  B Y O U C I E A G X J K L D W F H T S N R M V P    0.7023583852103916\n    (21) P Y O U C I E A G X J K L D V W H T S N R M F B    0.7023538733148424\n    (2)  B Y O U C I E A G K J X L D W V H T S N R M F P    0.7023520610893563\n    (4)  P Y O U C I E A G K J X L D W V H T S N R M F B    0.7023484279427685\n    (18) P Y O U C I E A G X J K L D W B H T S N R M F V    0.7023464351081202\n    (25) W Y O U C I E A G K J X L D B V H T S N R M F P    0.7023461467370498\n    (9)  B Y O U C I E A G K J X L D V W H T S N R M F P    0.7023452548590922\n    (19) P Y O U C I E A G X J K L D V B H T S N R M F W    0.7023449431149574\n    (24) P Y O U C I E A G X J K L D W F H T S N R M V B    0.7023436988861739\n    (26) B Y O U C I E A G K J X L D F W H T S N R M V P    0.7023436440319186\n    (14) P Y O U C I E A G K J X L D V W H T S N R M F B    0.7023415496371536\n    (28) P Y O U C I E A G K J X L D F W H T S N R M V B    0.7023402284944377\n    (5)  W Y O U C I E A G K J X L D V B H T S N R M F P    0.7023388201218663\n    (23) W Y O U C I E A G K J X L D F B H T S N R M V P    0.7023364217461976\n    (11) B Y O U C I E A G K J X L D W F H T S N R M V P    0.7023348023572361\n    (12) P Y O U C I E A G K J X L D W B H T S N R M F V    0.7023341114304313\n    (13) P Y O U C I E A G K J X L D V B H T S N R M F W    0.7023326194372687\n    (17) P Y O U C I E A G K J X L D W F H T S N R M V B    0.7023313752084851\n    (27) P Y O U C I E A G K J X L D W V H T S N R M B F    0.7023309175507675\n    (29) P Y O U C I E A G K J X L D F B H T S N R M V W    0.7023301885671278\n    (15) P Y O U C I E A G X J K L D W B H T S N R M V F    0.7023301589694194\n    (10) P Y O U C I E A G K J X L D W B H T S N R M V F    0.7023178352917306\n    \n    30 of 42 layouts tied for first place\n\n### Test 3. Evaluate sensitivity of the variants to the scoring parameters\n\nWe run a test below on the variants of the candidate winner layout to see how robust they are to removal of scoring parameters. We removed each of the 11 scoring parameters one by one and ranked the new scores for the variants above. Variant 1 (the candidate winner) scores highest for 8 of the 11 cases, and second highest for two other cases, demonstrating that this layout is not sensitive to individual parameters.\n\n\n```python\n# %load code/test/remove_parameters_rescore.py\nparams0 = [side_above_3away, side_above_2away, side_above_1away, middle_above_ring, ring_above_middle, \n           outward, skip_row_3away, skip_row_2away, skip_row_1away, skip_row_0away, same_finger]\nparam_names = ['side_above_3away', 'side_above_2away', 'side_above_1away', \n               'middle_above_ring', 'ring_above_middle', 'outward', 'skip_row_3away', \n               'skip_row_2away', 'skip_row_1away', 'skip_row_0away', 'same_finger']\nparams_lists = []\nfor i in range(len(params0)):\n    params_list = params0.copy()\n    params_list[i] = 1.0\n    params_lists.append(params_list)\n\nfor iparam, P in enumerate(params_lists):\n\n    print('    Remove parameter {0}:'.format(param_names[iparam]))\n\n    data_matrix_param = create_24x24_flow_matrix(not_home_row, side_top,\n                                                 P[0],P[1],P[2],P[3],P[4],P[5],P[6],P[7],P[8],P[9],P[10],\n                                                 1,1,1,1,1,1)\n    if apply_strength:\n        data_matrix_param = Strength24x24 * data_matrix_param\n\n    param_scores = []\n    for letters in test_layout_strings:\n        score = score_layout(data_matrix_param, letters, bigrams, bigram_frequencies, verbose=False);\n        param_scores.append(score)\n            \n    param_scores_sorted, param_ranks_sorted, Isort_param = rank_within_epsilon(param_scores, factor24, factor=True, verbose=False)\n    param_layouts_sorted = []\n    param_layout_strings_sorted = []\n    for i in Isort_param:\n        param_layouts_sorted.append(' '.join(test_layout_strings[i]))\n        param_layout_strings_sorted.append(test_layout_strings[i])\n\n    print('    Variant                                                 Score')\n    count = 0\n    for i, isort_param in enumerate(Isort_param):\n        count += 1\n        if param_ranks_sorted[isort_param] == 1:\n            if isort_param < 9:\n                s = '  '\n            else:\n                s = ' '\n            print('    ({0}){1}{2}    {3}'.format(isort_param+1, s, \n                                                  param_layouts_sorted[i], \n                                                  param_scores_sorted[i]))\n    print('    {0} of {1} layouts tied for first place'.format(count, len(test_layout_strings)))\n```\n    Remove parameter side_above_3away:\n    (6)  B Y O U C I E A G X J K L D V W H T S N R M F P    0.7107633027019034\n    (1)  B Y O U C I E A G X J K L D W V H T S N R M F P    0.7107623334764219\n    Remove parameter side_above_2away:\n    (2)  B Y O U C I E A G K J X L D W V H T S N R M F P    0.7130518654000207\n    (1)  B Y O U C I E A G X J K L D W V H T S N R M F P    0.7130513395263505\n    Remove parameter side_above_1away:\n    (5)  W Y O U C I E A G K J X L D V B H T S N R M F P    0.7148772594313253\n    (3)  W Y O U C I E A G X J K L D V B H T S N R M F P    0.7148711293283665\n    (2)  B Y O U C I E A G K J X L D W V H T S N R M F P    0.7148593915832421\n    (23) W Y O U C I E A G K J X L D F B H T S N R M V P    0.7148583101988224\n    (4)  P Y O U C I E A G K J X L D W V H T S N R M F B    0.7148543601588774\n    (1)  B Y O U C I E A G X J K L D W V H T S N R M F P    0.7148530691183211\n    Remove parameter middle_above_ring:\n    (1)  B Y O U C I E A G X J K L D W V H T S N R M F P    0.7092201999241033\n    Remove parameter ring_above_middle:\n    (1)  B Y O U C I E A G X J K L D W V H T S N R M F P    0.7114189279608791\n    Remove parameter outward:\n    (1)  B Y O U C I E A G X J K L D W V H T S N R M F P    0.7201947803218552\n    Remove parameter skip_row_3away:\n    (1)  B Y O U C I E A G X J K L D W V H T S N R M F P    0.7087608738602452\n    Remove parameter skip_row_2away:\n    (1)  B Y O U C I E A G X J K L D W V H T S N R M F P    0.7127292945043059\n    Remove parameter skip_row_1away:\n    (1)  B Y O U C I E A G X J K L D W V H T S N R M F P    0.7182207100993533\n    Remove parameter skip_row_0away:\n    (1)  B Y O U C I E A G X J K L D W V H T S N R M F P    0.712081162928148\n    Remove parameter same_finger:\n    (1)  B Y O U C I E A G X J K L D W V H T S N R M F P    0.7305410820225844\n### Test 4. Search for higher-scoring layouts by rearranging letters\n\nThe following test is to see if allowing random sets of eight letters to rearrange in every possible combination improves the score of the winning layout. After randomly selecting eight letters from (13 of the letters in) the top-scoring layout, creating layouts from every permutation of these letters, and computing their scores, we get identical results as the original layout. We repeated this test over a thousand times (40,320,000 layouts).\n\n\n```python\nwinner24 = ['B','Y','O','U','C','I','E','A','G','X','J','K','L','D','W','V','H','T','S','N','R','M','F','P']\n```\n\n\n```python\nrun_stability_test = True\nif run_stability_test:\n    original_score = score_layout(Factors24x24, winner24, bigrams, bigram_frequencies, verbose=False)\n    top_score_test4 = original_score\n    nunber_of_tests = 1000\n    size_random_set = 8\n    indices = [0,1, 8,9,10,11, 12,13,14,15, 21,22,23]\n\n    #  B Y O U  L D W V\n    #  C I E A  H T S N\n    #  G X J K  R M F P\n\n    #  0  1  -  -       12 13 14 15\n    #  -  -  -  -        -  -  -  -\n    #  8  9 10 11        - 21 22 23\n\n    print(original_score)\n\n    for i in range(nunber_of_tests):\n\n        print(i)\n        \n        letters_copy = winner24.copy() \n        random_indices = []\n        while np.size(random_indices) < size_random_set:\n            random_index = indices[np.int( np.round( (np.size(indices) - 1) * np.random.random(1) )[0])]\n            if random_index not in random_indices:\n                random_indices.append(random_index)   \n        for irand in random_indices:\n            letters_copy[np.int(irand)] = ''\n\n        top_permutation_test4, top_score_test4 = permute_optimize(winner24, letters_copy, letters24, keys24, \n                                                                  Factors24x24, bigrams, bigram_frequencies,                                                                   \n                                                                  min_score=top_score_test4, verbose=False)\n\n        if ''.join(top_permutation_test4) != ''.join(winner24) and top_score_test4 > original_score:\n            print(top_score_test4)\n            print(*top_permutation_test4)\n```\n\n### Test 5. Compare with alternate layout based solely on interkey speed estimates\n\nSince we use interkey speed estimates to independently corroborate the practical utility of our top-scoring initialized layouts and variants generated from our candidate winner, the question arises whether a better layout could be generated using the above procedure and based solely on interkey speed estimates. To do this, we simply set apply_strength=False and Factors24x24=Speed24x24 and ran Steps 1 through 3 above. The resulting layouts have two to three times higher same-finger bigram frequencies, which is not a good sign of the ease with which they can be typed. This indirectly demonstrates that fast-to-type layouts do not necessarily translate to less strenuous layouts.\n\n    (#) Rank                                                Score\n    (0) 1:  J Y U G I O E A X K W D L C F V R T S N H M P B    0.7028248210994403\n    (1) 1:  J Y O F U I E A X K G D L C B V R T S N H M P W    0.7028092866027337\n    (2) 1:  J B U P I O E A X K Y F L D C V H T S R N M W G    0.7027885065002167\n    (3) 1:  J P O F U I E A X Y K G L D C V H T S R N M W B    0.7027774348054611\n    (4) 1:  J Y U G I O E A X K W D L C F V H T S N R M P B    0.7027766978615982\n    (5) 2:  J Y O F U I E A X K G D L C W V H T S N R M P B    0.7027604410329258\n    (6) 3:  J Y O F I U E A X K G D L C B V R T S N H M P W    0.7027015337086406\n    (7) 3:  J P O F I U E A X Y K G L D C V H T S R N M W B    0.7026779438898121\n    (8) 3:  J Y O F I U E A X K G D L C W V H T S N R M P B    0.7026531181501796\n    (9) 4:  J U O F I H E A X Y K G D L C V T S N R P M W B    0.7026052409973239\n    (10) 4:  J U O F H I E A X Y K G D L C V T S N R P M W B    0.7025798551167619\n    (11) 5:  J U O G I H E A X Y K D C F W V R T S N L M P B    0.7025168489505383\n    (12) 5:  J U O G H I E A X Y K D C F W V R T S N L M P B    0.7025072606193864\n    (13) 6:  J G O F I S E A X Y K U D L C V H T N R P M W B    0.7024132916102113\n    (14) 6:  J Y O F S I E A X K G U D L C V H T N R P M W B    0.7023840624087121\n    (15) 7:  J W O U I R E A X K Y G L C F V H T S N D M P B    0.7021673985385113\n    (16) 7:  J P O F I N E A X Y K U M G C V H T S R L D W B    0.7021345744708818\n    (17) 8:  J Y O F R I E A X K G U L C W V H T S N D M P B    0.7020921733913089\n    (18) 8:  J P O F N I E A X Y K U M G C V H T S R L D W B    0.7020744010726611\n\nLayouts tied for first place, with letter frequencies:\n\n    Layout 1:\n\n    J Y U G  L C F V\n    I O E A  R T S N\n    X K W D  H M P B\n\n      6  59  97  67  145 119  86  38\n    270 272 445 287  224 331 232 258\n      8  19  60 136  180  90  76  53\n\n    left: 1.726T  right: 1.830T (6.03%)\n    Total same-finger bigram frequencies:     83350937269\n    Total bigram inward roll frequencies:   4619080035315\n\n    Layout 2:\n\n    J Y O F  L C B V\n    U I E A  R T S N\n    X K G D  H M P W\n\n      6  59 272  86  145 119  53  38\n     97 270 445 287  224 331 232 258\n      8  19  67 136  180  90  76  60\n\n    left: 1.752T  right: 1.804T (2.99%)\n    Total same-finger bigram frequencies:     85067873377\n    Total bigram inward roll frequencies:   4595756638318\n\n    Layout 3:\n\n    J B U P  L D C V\n    I O E A  H T S R\n    X K Y F  N M W G\n\n      6  53  97  76  145 136 119  38\n    270 272 445 287  180 331 232 224\n      8  19  59  86  258  90  60  67\n\n    left: 1.678T  right: 1.878T (11.89%)\n    Total same-finger bigram frequencies:     67426732036\n    Total bigram inward roll frequencies:   4698191302186\n\n    Layout 4:\n\n    J P O F  L D C V\n    U I E A  H T S R\n    X Y K G  N M W B\n\n      6  76 272  86  145 136 119  38\n     97 270 445 287  180 331 232 224\n      8  59  19  67  258  90  60  53\n\n    left: 1.692T  right: 1.864T (10.17%)\n    Total same-finger bigram frequencies:     55581492895\n    Total bigram inward roll frequencies:   4538464009444\n\n    Layout 5:\n\n    J Y U G  L C F V\n    I O E A  H T S N\n    X K W D  R M P B\n\n      6  59  97  67  145 119  86  38\n    270 272 445 287  180 331 232 258\n      8  19  60 136  224  90  76  53\n\n    left: 1.726T  right: 1.830T (6.03%)\n    Total same-finger bigram frequencies:     83350937269\n    Total bigram inward roll frequencies:   4619080035315\n\n### Assign letters Z and Q and test left/right swap\n\nTest to see if equal or higher scores are obtained for the following:\n\n    1. Assign Z and either Q or J to keys 112 and 113\n    2. Swap left and right sides\n\n\n```python\nlayouts_26letters = [\n    ['B','Y','O','U','C','I','E','A','G','X','J','K','L','D','W','V','H','T','S','N','R','M','F','P', '-','-','-', '-','-','-', 'Z','Q'],\n    ['B','Y','O','U','C','I','E','A','G','X','J','K','L','D','W','V','H','T','S','N','R','M','F','P', '-','-','-', '-','-','-', 'Q','Z'],\n    ['V','W','D','L','N','S','T','H','P','F','M','R','U','O','Y','B','A','E','I','C','K','J','X','G', '-','-','-', '-','-','-', 'Z','Q'],\n    ['V','W','D','L','N','S','T','H','P','F','M','R','U','O','Y','B','A','E','I','C','K','J','X','G', '-','-','-', '-','-','-', 'Q','Z']]\ndata_matrix = Factors32x32\nscores_26letters = []\nfor layout_26letters in layouts_26letters:\n    scores_26letters.append(score_layout(data_matrix, layout_26letters, bigrams, bigram_frequencies, verbose=False))\n\nscores_26letters_sorted, ranks_26letters_sorted, Isort_26letters = rank_within_epsilon(scores_26letters, \n                                                                        factor32, factor=True, verbose=False)\nprint('\\n    Rank                                                                   Score')\nfor i, rank in enumerate(ranks_26letters_sorted):\n    layout_string = layouts_26letters[Isort_26letters[i]]\n    layout = ' '.join(layout_string)\n    print('    {0}:  {1}    {2}'.format(rank, layout, scores_26letters_sorted[i]))\n    \nprint('')\nprint_layout24(layouts_26letters[0])\n\n#bigram_strings = [['f','l'],['f','r'],['p','l'],['p','r'],['w','r'],['w','l']]\n#for bigram_string in bigram_strings:\n#    print_bigram_frequency(bigram_string, bigrams, bigram_frequencies)\n```\n\nZ above Q received the highest score:\n\n    Rank                                                                   Score\n    1:  B Y O U C I E A G X J K L D W V H T S N R M F P - - - - - - Z Q    0.621987268013091\n    1:  B Y O U C I E A G X J K L D W V H T S N R M F P - - - - - - Q Z    0.6219870422703005\n    1:  V W D L N S T H P F M R U O Y B A E I C K J X G - - - - - - Q Z    0.6219847143830128\n    1:  V W D L N S T H P F M R U O Y B A E I C K J X G - - - - - - Z Q    0.6219774708803041\n    \nThe letters of the Engram layout:\n\n    B Y O U  L D W V Z\n    C I E A  H T S N Q\n    G X J K  R M F P\n\n\n```python\nwinner24 = ['B','Y','O','U','C','I','E','A','G','X','J','K','L','D','W','V','H','T','S','N','R','M','F','P']\nwinner32 = ['B','Y','O','U','C','I','E','A','G','X','J','K','L','D','W','V','H','T','S','N','R','M','F','P', '-','-','-', '-','-','-', 'Z','Q']\n```\n\n### Optional stability test\n\nThe following test is used to compare the score of the winning layout after rearranging random letters.\n\n\n```python\nrun_stability_test = True\nif run_stability_test:\n    original_score = score_layout(Factors24x24, winner24, bigrams, bigram_frequencies, verbose=False)\n    top_score_test5 = original_score\n    nunber_of_tests = 1000\n    size_random_set = 8\n    indices = [0,1, 8,9,10,11, 12,13,14,15, 21,22,23]\n\n    #  B Y O U  L D W V\n    #  C I E A  H T S N\n    #  G X J K  R M F P\n\n    #  0  1  -  -       12 13 14 15\n    #  -  -  -  -        -  -  -  -\n    #  8  9 10 11        - 21 22 23\n\n    print(original_score)\n\n    for i in range(nunber_of_tests):\n\n        print(i)\n        \n        letters_copy = winner24.copy() \n        random_indices = []\n        while np.size(random_indices) < size_random_set:\n            random_index = indices[np.int( np.round( (np.size(indices) - 1) * np.random.random(1) )[0])]\n            if random_index not in random_indices:\n                random_indices.append(random_index)   \n        for irand in random_indices:\n            letters_copy[np.int(irand)] = ''\n\n        top_permutation_test5, top_score_test5 = permute_optimize(winner24, letters_copy, letters24, keys24, \n                                                                  Factors24x24, bigrams, bigram_frequencies,                                                                   \n                                                                  min_score=top_score_test5, verbose=False)\n\n        if ''.join(top_permutation_test5) != ''.join(winner24) and top_score_test5 > original_score:\n            print(top_score_test5)\n            print(*top_permutation_test5)\n```\n\n## Step 5: Arrange non-letter characters in easy-to-remember places <a name=\"step5\">\n    \nNow that we have all 26 letters accounted for, we turn our attention to non-letter characters, taking into account frequency of punctuation and ease of recall.\n\n### Frequency of punctuation marks\n\n  - Statistical values of punctuation frequency in 20 English-speaking countries (Table 1): <br>\nSun, Kun & Wang, Rong. (2018). Frequency Distributions of Punctuation Marks in English: Evidence from Large-scale Corpora. English Today. 10.1017/S0266078418000512. <br> \nhttps://www.researchgate.net/publication/328512136_Frequency_Distributions_of_Punctuation_Marks_in_English_Evidence_from_Large-scale_Corpora\n  <br>\"frequency of punctuation marks attested for twenty English-speaking countries and regions... The data were acquired through GloWbE.\"\n  \"The corpus of GloWbE (2013) is a large English corpus collecting international English from the internet, containing about 1.9 billion words of text from twenty different countries. For further information on the corpora used, see https://corpus.byu.edu/.\"\n  \n  - Google N-grams and Twitter analysis: <br>\n\"Punctuation Input on Touchscreen Keyboards: Analyzing Frequency of Use and Costs\" <br>\nS Malik, L Findlater - College Park: The Human-Computer Interaction Lab. 2013 <br>\nhttps://www.cs.umd.edu/sites/default/files/scholarly_papers/Malik.pdf <br>\n \"the Twitter corpora included substantially higher punctuation use than the Google corpus,  <br>\n comprising 7.5% of characters in the mobile tweets and 7.6% in desktop versus only 4.4%...  <br>\nWith the Google corpus,only 6 punctuation symbols (. -\u2019 ( ) \u201c) appeared more frequently than [q]\"\n\n  - \"Frequencies for English Punctuation Marks\" by Vivian Cook <br>\nhttp://www.viviancook.uk/Punctuation/PunctFigs.htm  <br>\n \"Based on a writing system corpus some 459 thousand words long.  <br> \n This includes three novels of different types (276 thousand words),  <br>\n selections of articles from two newspapers (55 thousand), <br> \none bureaucratic report (94 thousand), and assorted academic papers <br>\non language topics (34 thousand). More information is in <br>\nCook, V.J. (2013) \u2018Standard punctuation and the punctuation of the street\u2019 <br>\nin M. Pawlak and L. Aronin (eds.), Essential Topics in Applied Linguistics and Multilingualism,  <br>\n Springer International Publishing Switzerland (2013), 267-290\"\n\n  - \"A Statistical Study of Current Usage in Punctuation\": <br>\nRuhlen, H., & Pressey, S. (1924). A Statistical Study of Current Usage in Punctuation. The English Journal, 13(5), 325-331. doi:10.2307/802253\n\n  - \"Computer Languages Character Frequency\"\nby Xah Lee.  <br>\nDate: 2013-05-23. Last updated: 2020-06-29. <br>\nhttp://xahlee.info/comp/computer_language_char_distribution.html <br>\nNOTE: biased toward C (19.8%) and Py (18.5%), which have high use of \"_\".\n\nFrequency: \n\n             Sun:     Malik:   Ruhlen:    Cook:            Xah:\n              /1M   N-gram %   /10,000   /1,000       All%  JS%   Py%\n\n    .    42840.02      1.151       535     65.3       6.6   9.4  10.3\n    ,    44189.96                  556     61.6       5.8   8.9   7.5\n    \"                  2.284        44     26.7       3.9   1.6   6.2\n    '     2980.35      0.200        40     24.3       4.4   4.0   8.6\n    -     9529.78      0.217        21     15.3       4.1   1.9   3.0\n    ()    4500.81      0.140         7                7.4   9.8   8.1\n    ;     1355.22      0.096        22      3.2       3.8   8.6\n    z                  0.09                   -         -\n    :     3221.82      0.087        11      3.4       3.5   2.8   4.7\n    ?     4154.78      0.032        14      5.6       0.3\n    /                  0.019                          4.0   4.9   1.1\n    !     2057.22      0.013         3      3.3       0.4\n    _                  0.001                         11.0   2.9  10.5\n    =                                                 4.4  10.7   5.4\n    *                                                 3.6   2.1\n    >                                                 3.0         1.4\n    $                                                 2.7   1.6\n    #                                                 2.2         3.2\n    {}                                                1.9   4.2\n    <                                                 1.3\n    &                                                 1.3\n    \\                                                 1.2         1.1\n    []                                                0.9   1.9   1.2\n    @                                                 0.8\n    |                                                 0.6\n    +                                                 0.6   1.9\n    %                                                 0.4\n\n### Add punctuation keys and number keys\n\nWe will assign the most frequent punctuation according to Sun, et al (2018) to the six keys in the middle two columns:  . , \" ' - ? ; : () ! _\n\n            B Y O U  '   \"   L D W V Z\n            C I E A  ,   .   H T S N Q\n            G X J K  -   ?   R M F P\n\nWe will use the Shift key to group similar punctuation marks (separating and joining marks in the left middle column and closing marks in the right middle column):\n\n            B Y O U  '(  \")  L D W V Z\n            C I E A  ,;  .:  H T S N Q\n            G X J K  -_  ?!  R M F P\n \n**Separating marks (left)**: The comma separates text in lists; the semicolon can be used in place of the comma to separate items in a list (especially if these items contain commas); open parenthesis sets off an explanatory word, phrase, or sentence. \n\n**Joining marks (left)**: The apostrophe joins words as contractions; the hyphen joins words as compounds; the underscore joins words in cases where whitespace characters are not permitted (such as in variables or file names). \n\n**Closing marks (right)**: A sentence usually ends with a period, question mark, or exclamation mark. The colon ends one statement but precedes the following: an explanation, quotation, list, etc. Double quotes and close parenthesis closes a word, clause, or sentence separated by an open parenthesis.\n\n**Number keys**: \nThe numbers are flanked to the left and right by [square brackets], and {curly brackets} accessed by the Shift key. Each of the numbers is paired with a mathematical or logic symbol accessed by the Shift key:\n    \n    { | = ~ +   <  >   ^ & % * } \\\n    [ 1 2 3 4   5  6   7 8 9 0 ] /\n\n    1: | (vertical bar or \"pipe\" represents the logical OR operator: 1 stroke, looks like the number one)\n    2: = (equal: 2 strokes, like the Chinese character for \"2\")\n    3: ~ (tilde: \"almost equal\", often written with 3 strokes, like the Chinese character for \"3\")\n    4: + (plus: has four quadrants; resembles \"4\")\n    5 & 6: < > (\"less/greater than\"; these angle brackets are directly above the other bracket keys)\n    7: ^ (caret for logical XOR operator as well as exponentiation; resembles \"7\")\n    8: & (ampersand: logical AND operator; resembles \"8\")\n    9: % (percent: related to division; resembles \"9\")\n    0: * (asterisk: for multiplication; resembles \"0\") \n\nThe three remaining keys in many common keyboards (flanking the upper right hand corner Backspace key) are displaced in special keyboards, such as the Kinesis Advantage and Ergodox. For the top right key, we will assign the forward slash and backslash: / \\\\. For the remaining two keys, we will assign two symbols that in modern usage have significance in social media: the hash/pound sign and the \"at sign\". The hash or hashtag identifies digital content on a specific topic (the Shift key accesses the dollar sign). The \"at sign\" identifies a location or affiliation (such as in email addresses) and acts as a \"handle\" to identify users in popular social media platforms and online forums.\n\nThe resulting Engram layout:\n\n          { | = ~ +   <  >   ^ & % * } \\\n          [ 1 2 3 4   5  6   7 8 9 0 ] /\n\n            B Y O U  '(  \")  L D W V Z #$ @`\n            C I E A  ,;  .:  H T S N Q\n            G X J K  -_  ?!  R M F P\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "5337832797da9f649a9ef72bcfb1c006fa509fcb", "size": 223388, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "engram_layout_v2.0.ipynb", "max_stars_repo_name": "Apsu/engram", "max_stars_repo_head_hexsha": "8b9f99420c3247f00fa6ce133d664d8d126aa91a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "engram_layout_v2.0.ipynb", "max_issues_repo_name": "Apsu/engram", "max_issues_repo_head_hexsha": "8b9f99420c3247f00fa6ce133d664d8d126aa91a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "engram_layout_v2.0.ipynb", "max_forks_repo_name": "Apsu/engram", "max_forks_repo_head_hexsha": "8b9f99420c3247f00fa6ce133d664d8d126aa91a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.4312655087, "max_line_length": 827, "alphanum_fraction": 0.4942745358, "converted": true, "num_tokens": 65590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250464935739196, "lm_q2_score": 0.0695417473983979, "lm_q1q2_score": 0.02938171160026043}}
{"text": "\n\n# Welcome to the second MAST-ML tutorial notebook, \n\n# Data Import and Data Cleaning with MAST-ML! \n\n## In this notebook, we will learn different ways to download and import data into a MAST-ML run: \n\n1. [Set up MAST-ML on Colab and begin session](#task1)\n2. [Import model datasets from scikit-learn](#task2)\n3. [Conduct different data cleaning methods](#task3)\n4. [Import and prepare a real dataset that is stored locally](#task4)\n5. [Download data from various materials databases](#task5)\n\n\n## Task 1: Set up MAST-ML on Colab and begin session <a name=\"task1\"></a>\n\nIf you are working on Google Colab and need to install MAST-ML, \nbegin by pip installing MAST-ML to the Colab session\nand install the needed dependencies:\n\n\n```python\n!pip install mastml\n```\n\n    Collecting mastml\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/cf/40/e094142e31fee2cdb86e7ac6676bdc023917d811f870a7969724c5984e41/mastml-3.0.0-py3-none-any.whl (121kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 122kB 5.6MB/s \n    \u001b[?25hCollecting mdf-toolbox\n      Downloading https://files.pythonhosted.org/packages/f5/44/45ed3b256d744891384d13088c12a23baaa2e395b341c3ab03c18001f715/mdf_toolbox-0.5.7-py2.py3-none-any.whl\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from mastml) (1.19.5)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from mastml) (1.4.1)\n    Requirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from mastml) (0.22.2.post1)\n    Collecting citrination-client\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/61/49/c0af91084172f6a6aa7d625651ec366c85a4fd717c5b4fa0e014d1953d6e/citrination-client-6.5.1.tar.gz (54kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 61kB 6.8MB/s \n    \u001b[?25hRequirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from mastml) (3.2.2)\n    Requirement already satisfied: mlxtend in /usr/local/lib/python3.7/dist-packages (from mastml) (0.14.0)\n    Collecting globus-sdk\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/92/a4/57b628cc5509eeb8361eb87506a3aea2078ca9c4e4ffaebc88280cdf7f40/globus_sdk-2.0.1-py2.py3-none-any.whl (85kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 92kB 7.7MB/s \n    \u001b[?25hCollecting sphinx-automodapi\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/16/08/83a3ee2cd420043538d195f024caac76dc2567a266361d95bb9344ab5594/sphinx_automodapi-0.13-py3-none-any.whl (75kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 81kB 10.7MB/s \n    \u001b[?25hRequirement already satisfied: openpyxl in /usr/local/lib/python3.7/dist-packages (from mastml) (2.5.9)\n    Collecting pymatgen==2021.3.9\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/18/06/8f4a5288ea5d940773d9c8651aee59535006353b1b592ac1e61802b0749f/pymatgen-2021.3.9.tar.gz (3.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.0MB 35.3MB/s \n    \u001b[?25h  Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n      Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n      Installing backend dependencies ... \u001b[?25l\u001b[?25hdone\n        Preparing wheel metadata ... \u001b[?25l\u001b[?25hdone\n    Collecting scikit-optimize\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/8b/03/be33e89f55866065a02e515c5b319304a801a9f1027a9b311a9b1d1f8dc7/scikit_optimize-0.8.1-py2.py3-none-any.whl (101kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 102kB 13.4MB/s \n    \u001b[?25hRequirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from mastml) (1.1.5)\n    Collecting mdf-forge\n      Downloading https://files.pythonhosted.org/packages/6f/0c/697e48caaabc83e071c222dc6d25ec0a924c69d4cf8f990964f47091b8d2/mdf_forge-0.7.6-py2.py3-none-any.whl\n    Collecting dlhub-sdk\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1e/cd/02ad247cf7df4467b63dec57e2c8d8f5fe64330bf6da61e6ac6cddcde149/dlhub_sdk-0.9.4-py2.py3-none-any.whl (41kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 7.9MB/s \n    \u001b[?25hCollecting globus-nexus-client\n      Downloading https://files.pythonhosted.org/packages/52/ca/a0e2c03aeea3e4b3b3256ab309e24fb5227ebaf92aabca56b6dfc3cc758a/globus_nexus_client-0.3.0-py2.py3-none-any.whl\n    Collecting matminer\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/18/67/319db03366448bf367f6239598da2da0021389b02a7f874380ee3c193890/matminer-0.6.5.tar.gz (5.8MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5.8MB 18.1MB/s \n    \u001b[?25hRequirement already satisfied: requests>=2.18.4 in /usr/local/lib/python3.7/dist-packages (from mdf-toolbox->mastml) (2.23.0)\n    Collecting fair-research-login>=0.1.5\n      Downloading https://files.pythonhosted.org/packages/89/a6/3239efa5150d9cb52af90d246ca46a405eefdaee503e77bf84023dbd2752/fair_research_login-0.2.0-py2.py3-none-any.whl\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->mastml) (1.0.1)\n    Collecting pypif\n      Downloading https://files.pythonhosted.org/packages/1e/04/a59e5ebacaed2800678467d9fcf511d249bac9b1b692a8fba0072cb09a49/pypif-2.1.2.tar.gz\n    Requirement already satisfied: six<2 in /usr/local/lib/python3.7/dist-packages (from citrination-client->mastml) (1.15.0)\n    Collecting pyyaml>=5.1.2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/7a/a5/393c087efdc78091afa2af9f1378762f9821c9c1d7a22c5753fb5ac5f97a/PyYAML-5.4.1-cp37-cp37m-manylinux1_x86_64.whl (636kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 645kB 46.1MB/s \n    \u001b[?25hRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->mastml) (1.3.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->mastml) (0.10.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->mastml) (2.4.7)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->mastml) (2.8.1)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from mlxtend->mastml) (54.2.0)\n    Collecting pyjwt[crypto]<2.0.0,>=1.5.3\n      Downloading https://files.pythonhosted.org/packages/87/8b/6a9f14b5f781697e51259d81657e6048fd31a113229cf346880bb7545565/PyJWT-1.7.1-py2.py3-none-any.whl\n    Requirement already satisfied: sphinx>=1.7 in /usr/local/lib/python3.7/dist-packages (from sphinx-automodapi->mastml) (1.8.5)\n    Requirement already satisfied: jdcal in /usr/local/lib/python3.7/dist-packages (from openpyxl->mastml) (1.4.1)\n    Requirement already satisfied: et-xmlfile in /usr/local/lib/python3.7/dist-packages (from openpyxl->mastml) (1.0.1)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from pymatgen==2021.3.9->mastml) (1.7.1)\n    Collecting ruamel.yaml>=0.15.6\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/29/4e/c3105bbbbc662f6a671a505f00ec771e93b5254f09fbb06002af9087071a/ruamel.yaml-0.17.4-py3-none-any.whl (101kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 102kB 13.3MB/s \n    \u001b[?25hRequirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2021.3.9->mastml) (3.3.0)\n    Collecting plotly>=4.5.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1f/f6/bd3c17c8003b6641df1228e80e1acac97ed8402635e46c2571f8e1ef63af/plotly-4.14.3-py2.py3-none-any.whl (13.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 13.2MB 54.1MB/s \n    \u001b[?25hRequirement already satisfied: typing-extensions>=3.7.4.3; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from pymatgen==2021.3.9->mastml) (3.7.4.3)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2021.3.9->mastml) (2.5)\n    Collecting monty>=3.0.2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/41/47/e6f045cd69f24df0b4ddd55fab329c079b7c9ce978a32431dce904f6a1d6/monty-2021.3.3-py3-none-any.whl (63kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 71kB 10.5MB/s \n    \u001b[?25hCollecting spglib>=1.9.9.44\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/4b/98/fa4760b9c71e2eace5a60b85dbf36dece49c379f8291cf1203056f287766/spglib-1.16.1-cp37-cp37m-manylinux2010_x86_64.whl (296kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 296kB 38.3MB/s \n    \u001b[?25hCollecting uncertainties>=3.1.4\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/45/41/fc7e7b73b603e7c2c9e040b7aa8caf4a88d74b6faa567601ed82b6f0d8e1/uncertainties-3.1.5-py2.py3-none-any.whl (246kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 256kB 43.5MB/s \n    \u001b[?25hRequirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2021.3.9->mastml) (0.8.9)\n    Collecting pyaml>=16.9\n      Downloading https://files.pythonhosted.org/packages/15/c4/1310a054d33abc318426a956e7d6df0df76a6ddfa9c66f6310274fb75d42/pyaml-20.4.0-py2.py3-none-any.whl\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->mastml) (2018.9)\n    Requirement already satisfied: tqdm>=4.19.4 in /usr/local/lib/python3.7/dist-packages (from mdf-forge->mastml) (4.41.1)\n    Collecting jsonschema>=3.2.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/c5/8f/51e89ce52a085483359217bc72cdbf6e75ee595d5b1d4b5ade40c7e018b8/jsonschema-3.2.0-py2.py3-none-any.whl (56kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 61kB 9.7MB/s \n    \u001b[?25hCollecting funcx>=0.0.5\n      Downloading https://files.pythonhosted.org/packages/eb/1c/79404da8ff1aabe8d1619905cbfe376d4128bfdd0904fba992c7f732e86a/funcx-0.2.0-py3-none-any.whl\n    Requirement already satisfied: pymongo>=3.10.1 in /usr/local/lib/python3.7/dist-packages (from matminer->mastml) (3.11.3)\n    Collecting pint>=0.11\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/33/de/53a77b82553579affab7438d299f850acbc1c4dd741c5ce52594513cb0ef/Pint-0.17-py2.py3-none-any.whl (204kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 215kB 57.0MB/s \n    \u001b[?25hCollecting future>=0.18.2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/45/0b/38b06fd9b92dc2b68d58b75f900e97884c45bedd2ff83203d933cf5851c9/future-0.18.2.tar.gz (829kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 829kB 38.4MB/s \n    \u001b[?25hRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.18.4->mdf-toolbox->mastml) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.18.4->mdf-toolbox->mastml) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.18.4->mdf-toolbox->mastml) (2020.12.5)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests>=2.18.4->mdf-toolbox->mastml) (1.24.3)\n    Collecting cryptography>=1.4; extra == \"crypto\"\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/b2/26/7af637e6a7e87258b963f1731c5982fb31cd507f0d90d91836e446955d02/cryptography-3.4.7-cp36-abi3-manylinux2014_x86_64.whl (3.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.2MB 51.5MB/s \n    \u001b[?25hRequirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from sphinx>=1.7->sphinx-automodapi->mastml) (20.9)\n    Requirement already satisfied: Pygments>=2.0 in /usr/local/lib/python3.7/dist-packages (from sphinx>=1.7->sphinx-automodapi->mastml) (2.6.1)\n    Requirement already satisfied: Jinja2>=2.3 in /usr/local/lib/python3.7/dist-packages (from sphinx>=1.7->sphinx-automodapi->mastml) (2.11.3)\n    Requirement already satisfied: babel!=2.0,>=1.3 in /usr/local/lib/python3.7/dist-packages (from sphinx>=1.7->sphinx-automodapi->mastml) (2.9.0)\n    Requirement already satisfied: sphinxcontrib-websupport in /usr/local/lib/python3.7/dist-packages (from sphinx>=1.7->sphinx-automodapi->mastml) (1.2.4)\n    Requirement already satisfied: alabaster<0.8,>=0.7 in /usr/local/lib/python3.7/dist-packages (from sphinx>=1.7->sphinx-automodapi->mastml) (0.7.12)\n    Requirement already satisfied: docutils>=0.11 in /usr/local/lib/python3.7/dist-packages (from sphinx>=1.7->sphinx-automodapi->mastml) (0.16)\n    Requirement already satisfied: snowballstemmer>=1.1 in /usr/local/lib/python3.7/dist-packages (from sphinx>=1.7->sphinx-automodapi->mastml) (2.1.0)\n    Requirement already satisfied: imagesize in /usr/local/lib/python3.7/dist-packages (from sphinx>=1.7->sphinx-automodapi->mastml) (1.2.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->pymatgen==2021.3.9->mastml) (1.2.1)\n    Collecting ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\"\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/5e/6e/f652c56bbb2c3d3fca252ffc7c0358597f57a1bbdf484dac683054950c63/ruamel.yaml.clib-0.2.2-cp37-cp37m-manylinux1_x86_64.whl (547kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 552kB 45.7MB/s \n    \u001b[?25hRequirement already satisfied: retrying>=1.3.3 in /usr/local/lib/python3.7/dist-packages (from plotly>=4.5.0->pymatgen==2021.3.9->mastml) (1.3.3)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.2->pymatgen==2021.3.9->mastml) (4.4.2)\n    Requirement already satisfied: attrs>=17.4.0 in /usr/local/lib/python3.7/dist-packages (from jsonschema>=3.2.0->dlhub-sdk->mastml) (20.3.0)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from jsonschema>=3.2.0->dlhub-sdk->mastml) (3.8.1)\n    Requirement already satisfied: pyrsistent>=0.14.0 in /usr/local/lib/python3.7/dist-packages (from jsonschema>=3.2.0->dlhub-sdk->mastml) (0.17.3)\n    Requirement already satisfied: pyzmq>=22.0.0 in /usr/local/lib/python3.7/dist-packages (from funcx>=0.0.5->dlhub-sdk->mastml) (22.0.3)\n    Collecting configobj\n      Downloading https://files.pythonhosted.org/packages/64/61/079eb60459c44929e684fa7d9e2fdca403f67d64dd9dbac27296be2e0fab/configobj-5.0.6.tar.gz\n    Collecting parsl>=1.1.0a0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/41/2e/33f0b66ee8afe2af0cffd103cffb487c7616a16a2e77f0e1635238b69dfd/parsl-1.1.0a1-py3-none-any.whl (449kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 450kB 28.1MB/s \n    \u001b[?25hRequirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from funcx>=0.0.5->dlhub-sdk->mastml) (0.3.3)\n    Collecting typer>=0.3.0\n      Downloading https://files.pythonhosted.org/packages/90/34/d138832f6945432c638f32137e6c79a3b682f06a63c488dcfaca6b166c64/typer-0.3.2-py3-none-any.whl\n    Collecting texttable\n      Downloading https://files.pythonhosted.org/packages/06/f5/46201c428aebe0eecfa83df66bf3e6caa29659dbac5a56ddfd83cae0d4a4/texttable-1.6.3-py2.py3-none-any.whl\n    Collecting python-daemon\n      Downloading https://files.pythonhosted.org/packages/b1/cc/2ab0d910548de45eaaa50d0372387951d9005c356a44c6858db12dc6b2b7/python_daemon-2.3.0-py2.py3-none-any.whl\n    Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.4; extra == \"crypto\"->pyjwt[crypto]<2.0.0,>=1.5.3->globus-sdk->mastml) (1.14.5)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from Jinja2>=2.3->sphinx>=1.7->sphinx-automodapi->mastml) (1.1.1)\n    Requirement already satisfied: sphinxcontrib-serializinghtml in /usr/local/lib/python3.7/dist-packages (from sphinxcontrib-websupport->sphinx>=1.7->sphinx-automodapi->mastml) (1.1.4)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->jsonschema>=3.2.0->dlhub-sdk->mastml) (3.4.1)\n    Requirement already satisfied: tblib in /usr/local/lib/python3.7/dist-packages (from parsl>=1.1.0a0->funcx>=0.0.5->dlhub-sdk->mastml) (1.7.0)\n    Collecting paramiko\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/95/19/124e9287b43e6ff3ebb9cdea3e5e8e88475a873c05ccdf8b7e20d2c4201e/paramiko-2.7.2-py2.py3-none-any.whl (206kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 215kB 56.3MB/s \n    \u001b[?25hCollecting psutil>=5.5.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/84/da/f7efdcf012b51506938553dbe302aecc22f3f43abd5cffa8320e8e0588d5/psutil-5.8.0-cp37-cp37m-manylinux2010_x86_64.whl (296kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 296kB 53.0MB/s \n    \u001b[?25hCollecting typeguard>=2.10\n      Downloading https://files.pythonhosted.org/packages/06/1f/c10ad900a10e1421b85d20f1c9d1748469ef5a34296693a02be887af5f95/typeguard-2.12.0-py3-none-any.whl\n    Requirement already satisfied: click<7.2.0,>=7.1.1 in /usr/local/lib/python3.7/dist-packages (from typer>=0.3.0->funcx>=0.0.5->dlhub-sdk->mastml) (7.1.2)\n    Collecting lockfile>=0.10\n      Downloading https://files.pythonhosted.org/packages/c8/22/9460e311f340cb62d26a38c419b1381b8593b0bb6b5d1f056938b086d362/lockfile-0.12.2-py2.py3-none-any.whl\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.4; extra == \"crypto\"->pyjwt[crypto]<2.0.0,>=1.5.3->globus-sdk->mastml) (2.20)\n    Collecting pynacl>=1.0.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/9d/57/2f5e6226a674b2bcb6db531e8b383079b678df5b10cdaa610d6cf20d77ba/PyNaCl-1.4.0-cp35-abi3-manylinux1_x86_64.whl (961kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 962kB 55.3MB/s \n    \u001b[?25hCollecting bcrypt>=3.1.3\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/26/70/6d218afbe4c73538053c1016dd631e8f25fffc10cd01f5c272d7acf3c03d/bcrypt-3.2.0-cp36-abi3-manylinux2010_x86_64.whl (63kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 71kB 11.0MB/s \n    \u001b[?25hBuilding wheels for collected packages: pymatgen\n      Building wheel for pymatgen (PEP 517) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pymatgen: filename=pymatgen-2021.3.9-cp37-cp37m-linux_x86_64.whl size=3793998 sha256=c4d6f1a9700ecbc03eb41147d1daf2bdf34a435c717c7988af894186786a437d\n      Stored in directory: /root/.cache/pip/wheels/8b/f9/ce/1d72ca15aa8d8de3ae81ae333b3eabb49eeb5f294c25ad128b\n    Successfully built pymatgen\n    Building wheels for collected packages: citrination-client, matminer, pypif, future, configobj\n      Building wheel for citrination-client (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for citrination-client: filename=citrination_client-6.5.1-py2.py3-none-any.whl size=116097 sha256=f8af0b0c2e2c1c5720a9f59ab8119fb815364ea3b54c0cf62beacf81c31ee5e1\n      Stored in directory: /root/.cache/pip/wheels/6c/88/f5/5a3d5759228aabc63cb3baf2d767369ac99d18f3a941d381e7\n      Building wheel for matminer (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for matminer: filename=matminer-0.6.5-cp37-none-any.whl size=1189789 sha256=fff862a6427e6ebf17dcde23db5464de0e7f447b41901bc67708ff3328dfffe3\n      Stored in directory: /root/.cache/pip/wheels/b9/d9/ca/b03a29a28fb675c253a5792995097c48c25b8d409ddac4e2c1\n      Building wheel for pypif (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pypif: filename=pypif-2.1.2-py2.py3-none-any.whl size=29506 sha256=e94bbd245d2d13c1df0e623cd3e9af50cf85b8a172d90811ea513e9acbe8c063\n      Stored in directory: /root/.cache/pip/wheels/0d/19/de/9d99bb147337e90a209a44c89e67b3aaadcac4f6f8d106c13d\n      Building wheel for future (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for future: filename=future-0.18.2-cp37-none-any.whl size=491058 sha256=5ccac7ca500898cc0e427199fe86ed3b16b8658ba921931afbf652a8ff71b4bb\n      Stored in directory: /root/.cache/pip/wheels/8b/99/a0/81daf51dcd359a9377b110a8a886b3895921802d2fc1b2397e\n      Building wheel for configobj (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for configobj: filename=configobj-5.0.6-cp37-none-any.whl size=34547 sha256=15d71a6c96670b3dff070f4e84ce111e0da3f0a69eb02958c62a90d409c9148b\n      Stored in directory: /root/.cache/pip/wheels/f1/e4/16/4981ca97c2d65106b49861e0b35e2660695be7219a2d351ee0\n    Successfully built citrination-client matminer pypif future configobj\n    \u001b[31mERROR: nbclient 0.5.3 has requirement jupyter-client>=6.1.5, but you'll have jupyter-client 5.3.5 which is incompatible.\u001b[0m\n    \u001b[31mERROR: pymatgen 2021.3.9 has requirement numpy>=1.20.1, but you'll have numpy 1.19.5 which is incompatible.\u001b[0m\n    \u001b[31mERROR: pymatgen 2021.3.9 has requirement scipy>=1.5.0, but you'll have scipy 1.4.1 which is incompatible.\u001b[0m\n    \u001b[31mERROR: dlhub-sdk 0.9.4 has requirement requests>=2.24.0, but you'll have requests 2.23.0 which is incompatible.\u001b[0m\n    \u001b[31mERROR: matminer 0.6.5 has requirement scikit-learn>=0.23.1, but you'll have scikit-learn 0.22.2.post1 which is incompatible.\u001b[0m\n    \u001b[31mERROR: matminer 0.6.5 has requirement tqdm>=4.46.0, but you'll have tqdm 4.41.1 which is incompatible.\u001b[0m\n    Installing collected packages: cryptography, pyjwt, globus-sdk, globus-nexus-client, fair-research-login, mdf-toolbox, pypif, pyyaml, citrination-client, sphinx-automodapi, ruamel.yaml.clib, ruamel.yaml, plotly, monty, spglib, future, uncertainties, pymatgen, pyaml, scikit-optimize, mdf-forge, jsonschema, configobj, pynacl, bcrypt, paramiko, psutil, typeguard, parsl, typer, texttable, lockfile, python-daemon, funcx, dlhub-sdk, pint, matminer, mastml\n      Found existing installation: PyYAML 3.13\n        Uninstalling PyYAML-3.13:\n          Successfully uninstalled PyYAML-3.13\n      Found existing installation: plotly 4.4.1\n        Uninstalling plotly-4.4.1:\n          Successfully uninstalled plotly-4.4.1\n      Found existing installation: future 0.16.0\n        Uninstalling future-0.16.0:\n          Successfully uninstalled future-0.16.0\n      Found existing installation: jsonschema 2.6.0\n        Uninstalling jsonschema-2.6.0:\n          Successfully uninstalled jsonschema-2.6.0\n      Found existing installation: psutil 5.4.8\n        Uninstalling psutil-5.4.8:\n          Successfully uninstalled psutil-5.4.8\n      Found existing installation: typeguard 2.7.1\n        Uninstalling typeguard-2.7.1:\n          Successfully uninstalled typeguard-2.7.1\n    Successfully installed bcrypt-3.2.0 citrination-client-6.5.1 configobj-5.0.6 cryptography-3.4.7 dlhub-sdk-0.9.4 fair-research-login-0.2.0 funcx-0.2.0 future-0.18.2 globus-nexus-client-0.3.0 globus-sdk-2.0.1 jsonschema-3.2.0 lockfile-0.12.2 mastml-3.0.0 matminer-0.6.5 mdf-forge-0.7.6 mdf-toolbox-0.5.7 monty-2021.3.3 paramiko-2.7.2 parsl-1.1.0a1 pint-0.17 plotly-4.14.3 psutil-5.8.0 pyaml-20.4.0 pyjwt-1.7.1 pymatgen-2021.3.9 pynacl-1.4.0 pypif-2.1.2 python-daemon-2.3.0 pyyaml-5.4.1 ruamel.yaml-0.17.4 ruamel.yaml.clib-0.2.2 scikit-optimize-0.8.1 spglib-1.16.1 sphinx-automodapi-0.13 texttable-1.6.3 typeguard-2.12.0 typer-0.3.2 uncertainties-3.1.5\n\n\n\n\nSync your Google drive to Colab so that we can save MAST-ML results to our Google\nDrive. If we save to the Colab session, the data will be deleted when the session \nends.\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/content/drive', force_remount=True)\n```\n\n    Mounted at /content/drive\n\n\nHere we import the MAST-ML modules used in this tutorial\n\n\n```python\nfrom mastml.mastml import Mastml\nfrom mastml.datasets import SklearnDatasets, LocalDatasets, MatminerDatasets, FigshareDatasets, FoundryDatasets\nfrom mastml.data_cleaning import DataCleaning\nimport numpy as np\nfrom copy import copy\nimport mastml\nimport os \ndata_path = os.path.join(mastml.__path__._path[0], 'data')\n```\n\nHere, we set the name of the savepath to save MAST-ML results to, and initialize\nour MAST-ML run\n\nWhen the above command is run, a new folder with the name designated SAVEPATH is created.\nThis is where all of the output for the current MAST-ML run will be saved to.\nNote that you can perform multiple runs with the same folder name, and the current datetime\nwill be appended to the name so that no data is lost or overwritten.\n\n\n```python\nSAVEPATH = 'drive/MyDrive/MASTML_tutorial_2_DataImport'\n\nmastml = Mastml(savepath=SAVEPATH)\nsavepath = mastml.get_savepath\n```\n\n## Task 2: Import model datasets from scikit-learn <a name=\"task2\"></a>\n\nLet's begin by first showing how to load some common model datasets that\ncome with the scikit-learn package. As in the first tutorial, we use the SklearnDatasets module \nto load in the data. There are a few regression datasets that come with scikit-learn, such as\nthe Boston housing data, the diabetes dataset, and the Friedman data set. For now,\nlet's once again load in the Boston housing dataset.\n\n\n```python\nX, y = SklearnDatasets(as_frame=True).load_boston()\n```\n\nLet's quickly examine the X data so we know what we're dealing with:\n\n\n```python\nX\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>CRIM</th>\n      <th>ZN</th>\n      <th>INDUS</th>\n      <th>CHAS</th>\n      <th>NOX</th>\n      <th>RM</th>\n      <th>AGE</th>\n      <th>DIS</th>\n      <th>RAD</th>\n      <th>TAX</th>\n      <th>PTRATIO</th>\n      <th>B</th>\n      <th>LSTAT</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.00632</td>\n      <td>18.0</td>\n      <td>2.31</td>\n      <td>0.0</td>\n      <td>0.538</td>\n      <td>6.575</td>\n      <td>65.2</td>\n      <td>4.0900</td>\n      <td>1.0</td>\n      <td>296.0</td>\n      <td>15.3</td>\n      <td>396.90</td>\n      <td>4.98</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.02731</td>\n      <td>0.0</td>\n      <td>7.07</td>\n      <td>0.0</td>\n      <td>0.469</td>\n      <td>6.421</td>\n      <td>78.9</td>\n      <td>4.9671</td>\n      <td>2.0</td>\n      <td>242.0</td>\n      <td>17.8</td>\n      <td>396.90</td>\n      <td>9.14</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.02729</td>\n      <td>0.0</td>\n      <td>7.07</td>\n      <td>0.0</td>\n      <td>0.469</td>\n      <td>7.185</td>\n      <td>61.1</td>\n      <td>4.9671</td>\n      <td>2.0</td>\n      <td>242.0</td>\n      <td>17.8</td>\n      <td>392.83</td>\n      <td>4.03</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.03237</td>\n      <td>0.0</td>\n      <td>2.18</td>\n      <td>0.0</td>\n      <td>0.458</td>\n      <td>6.998</td>\n      <td>45.8</td>\n      <td>6.0622</td>\n      <td>3.0</td>\n      <td>222.0</td>\n      <td>18.7</td>\n      <td>394.63</td>\n      <td>2.94</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.06905</td>\n      <td>0.0</td>\n      <td>2.18</td>\n      <td>0.0</td>\n      <td>0.458</td>\n      <td>7.147</td>\n      <td>54.2</td>\n      <td>6.0622</td>\n      <td>3.0</td>\n      <td>222.0</td>\n      <td>18.7</td>\n      <td>396.90</td>\n      <td>5.33</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>501</th>\n      <td>0.06263</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.593</td>\n      <td>69.1</td>\n      <td>2.4786</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>391.99</td>\n      <td>9.67</td>\n    </tr>\n    <tr>\n      <th>502</th>\n      <td>0.04527</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.120</td>\n      <td>76.7</td>\n      <td>2.2875</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>396.90</td>\n      <td>9.08</td>\n    </tr>\n    <tr>\n      <th>503</th>\n      <td>0.06076</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.976</td>\n      <td>91.0</td>\n      <td>2.1675</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>396.90</td>\n      <td>5.64</td>\n    </tr>\n    <tr>\n      <th>504</th>\n      <td>0.10959</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.794</td>\n      <td>89.3</td>\n      <td>2.3889</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>393.45</td>\n      <td>6.48</td>\n    </tr>\n    <tr>\n      <th>505</th>\n      <td>0.04741</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.030</td>\n      <td>80.8</td>\n      <td>2.5050</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>396.90</td>\n      <td>7.88</td>\n    </tr>\n  </tbody>\n</table>\n<p>506 rows \u00d7 13 columns</p>\n</div>\n\n\n\n## Task 3: Conduct different data cleaning method <a name=\"task3\"></a>\n\nWe have 506 data points (houses) and 13 columns (features). From inspecting the dataset,\nwe can see there are no missing values in the dataset. However, many datasets in the real\nworld aren't this neat and tidy, and may contain values that are missing. To illustrate\nhow we can go about cleaning our data, let's make the first few rows of values in the AGE\ncolumn not-a-number (NaN), which is what they will be if you import a dataset with missing values:\n\n\n```python\nX['AGE'][0:4] = np.nan\nX\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>CRIM</th>\n      <th>ZN</th>\n      <th>INDUS</th>\n      <th>CHAS</th>\n      <th>NOX</th>\n      <th>RM</th>\n      <th>AGE</th>\n      <th>DIS</th>\n      <th>RAD</th>\n      <th>TAX</th>\n      <th>PTRATIO</th>\n      <th>B</th>\n      <th>LSTAT</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.00632</td>\n      <td>18.0</td>\n      <td>2.31</td>\n      <td>0.0</td>\n      <td>0.538</td>\n      <td>6.575</td>\n      <td>NaN</td>\n      <td>4.0900</td>\n      <td>1.0</td>\n      <td>296.0</td>\n      <td>15.3</td>\n      <td>396.90</td>\n      <td>4.98</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.02731</td>\n      <td>0.0</td>\n      <td>7.07</td>\n      <td>0.0</td>\n      <td>0.469</td>\n      <td>6.421</td>\n      <td>NaN</td>\n      <td>4.9671</td>\n      <td>2.0</td>\n      <td>242.0</td>\n      <td>17.8</td>\n      <td>396.90</td>\n      <td>9.14</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.02729</td>\n      <td>0.0</td>\n      <td>7.07</td>\n      <td>0.0</td>\n      <td>0.469</td>\n      <td>7.185</td>\n      <td>NaN</td>\n      <td>4.9671</td>\n      <td>2.0</td>\n      <td>242.0</td>\n      <td>17.8</td>\n      <td>392.83</td>\n      <td>4.03</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.03237</td>\n      <td>0.0</td>\n      <td>2.18</td>\n      <td>0.0</td>\n      <td>0.458</td>\n      <td>6.998</td>\n      <td>NaN</td>\n      <td>6.0622</td>\n      <td>3.0</td>\n      <td>222.0</td>\n      <td>18.7</td>\n      <td>394.63</td>\n      <td>2.94</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.06905</td>\n      <td>0.0</td>\n      <td>2.18</td>\n      <td>0.0</td>\n      <td>0.458</td>\n      <td>7.147</td>\n      <td>54.2</td>\n      <td>6.0622</td>\n      <td>3.0</td>\n      <td>222.0</td>\n      <td>18.7</td>\n      <td>396.90</td>\n      <td>5.33</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>501</th>\n      <td>0.06263</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.593</td>\n      <td>69.1</td>\n      <td>2.4786</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>391.99</td>\n      <td>9.67</td>\n    </tr>\n    <tr>\n      <th>502</th>\n      <td>0.04527</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.120</td>\n      <td>76.7</td>\n      <td>2.2875</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>396.90</td>\n      <td>9.08</td>\n    </tr>\n    <tr>\n      <th>503</th>\n      <td>0.06076</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.976</td>\n      <td>91.0</td>\n      <td>2.1675</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>396.90</td>\n      <td>5.64</td>\n    </tr>\n    <tr>\n      <th>504</th>\n      <td>0.10959</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.794</td>\n      <td>89.3</td>\n      <td>2.3889</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>393.45</td>\n      <td>6.48</td>\n    </tr>\n    <tr>\n      <th>505</th>\n      <td>0.04741</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.030</td>\n      <td>80.8</td>\n      <td>2.5050</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>396.90</td>\n      <td>7.88</td>\n    </tr>\n  </tbody>\n</table>\n<p>506 rows \u00d7 13 columns</p>\n</div>\n\n\n\nWe can now see that the first four rows of the 'AGE' column are NaN instead\nof their original values. Let's clean the data using a few different methods\nin the DataCleaning class. First, let's copy the X data so we can more easily\nsee the changes we make to each dataset\n\n\n```python\nX1row = X1col = X2 = X3 = X4 = copy(X)\n```\n\nThere are few different ways we can clean the data: (1) we can simply \nremove the data points that have missing values, (2) we can perform\ndata imputation to replace the missing values with the mean (or median) value\n\nLet's start with simply removing the problematic data points:\n\n\n```python\nX1row, y1 = DataCleaning().remove(X=X1row, \n                                  y=y, \n                                  axis=0)\nX1row\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>CRIM</th>\n      <th>ZN</th>\n      <th>INDUS</th>\n      <th>CHAS</th>\n      <th>NOX</th>\n      <th>RM</th>\n      <th>AGE</th>\n      <th>DIS</th>\n      <th>RAD</th>\n      <th>TAX</th>\n      <th>PTRATIO</th>\n      <th>B</th>\n      <th>LSTAT</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>4</th>\n      <td>0.06905</td>\n      <td>0.0</td>\n      <td>2.18</td>\n      <td>0.0</td>\n      <td>0.458</td>\n      <td>7.147</td>\n      <td>54.2</td>\n      <td>6.0622</td>\n      <td>3.0</td>\n      <td>222.0</td>\n      <td>18.7</td>\n      <td>396.90</td>\n      <td>5.33</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>0.02985</td>\n      <td>0.0</td>\n      <td>2.18</td>\n      <td>0.0</td>\n      <td>0.458</td>\n      <td>6.430</td>\n      <td>58.7</td>\n      <td>6.0622</td>\n      <td>3.0</td>\n      <td>222.0</td>\n      <td>18.7</td>\n      <td>394.12</td>\n      <td>5.21</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>0.08829</td>\n      <td>12.5</td>\n      <td>7.87</td>\n      <td>0.0</td>\n      <td>0.524</td>\n      <td>6.012</td>\n      <td>66.6</td>\n      <td>5.5605</td>\n      <td>5.0</td>\n      <td>311.0</td>\n      <td>15.2</td>\n      <td>395.60</td>\n      <td>12.43</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>0.14455</td>\n      <td>12.5</td>\n      <td>7.87</td>\n      <td>0.0</td>\n      <td>0.524</td>\n      <td>6.172</td>\n      <td>96.1</td>\n      <td>5.9505</td>\n      <td>5.0</td>\n      <td>311.0</td>\n      <td>15.2</td>\n      <td>396.90</td>\n      <td>19.15</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>0.21124</td>\n      <td>12.5</td>\n      <td>7.87</td>\n      <td>0.0</td>\n      <td>0.524</td>\n      <td>5.631</td>\n      <td>100.0</td>\n      <td>6.0821</td>\n      <td>5.0</td>\n      <td>311.0</td>\n      <td>15.2</td>\n      <td>386.63</td>\n      <td>29.93</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>501</th>\n      <td>0.06263</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.593</td>\n      <td>69.1</td>\n      <td>2.4786</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>391.99</td>\n      <td>9.67</td>\n    </tr>\n    <tr>\n      <th>502</th>\n      <td>0.04527</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.120</td>\n      <td>76.7</td>\n      <td>2.2875</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>396.90</td>\n      <td>9.08</td>\n    </tr>\n    <tr>\n      <th>503</th>\n      <td>0.06076</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.976</td>\n      <td>91.0</td>\n      <td>2.1675</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>396.90</td>\n      <td>5.64</td>\n    </tr>\n    <tr>\n      <th>504</th>\n      <td>0.10959</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.794</td>\n      <td>89.3</td>\n      <td>2.3889</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>393.45</td>\n      <td>6.48</td>\n    </tr>\n    <tr>\n      <th>505</th>\n      <td>0.04741</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.030</td>\n      <td>80.8</td>\n      <td>2.5050</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>396.90</td>\n      <td>7.88</td>\n    </tr>\n  </tbody>\n</table>\n<p>502 rows \u00d7 13 columns</p>\n</div>\n\n\n\nWhat we can see is that we now have 502 rows instead of the original 506. \nThe four data points that had missing values in the AGE column have been removed.\n\nNote that we could have instead removed the column (feature) containing\nthe missing values, as in our case all of the missing values were part of\na single feature:\n\n\n```python\nX1col, y1 = DataCleaning().remove(X=X1col, \n                                  y=y, \n                                  axis=1)\nX1col\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>CRIM</th>\n      <th>ZN</th>\n      <th>INDUS</th>\n      <th>CHAS</th>\n      <th>NOX</th>\n      <th>RM</th>\n      <th>DIS</th>\n      <th>RAD</th>\n      <th>TAX</th>\n      <th>PTRATIO</th>\n      <th>B</th>\n      <th>LSTAT</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.00632</td>\n      <td>18.0</td>\n      <td>2.31</td>\n      <td>0.0</td>\n      <td>0.538</td>\n      <td>6.575</td>\n      <td>4.0900</td>\n      <td>1.0</td>\n      <td>296.0</td>\n      <td>15.3</td>\n      <td>396.90</td>\n      <td>4.98</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.02731</td>\n      <td>0.0</td>\n      <td>7.07</td>\n      <td>0.0</td>\n      <td>0.469</td>\n      <td>6.421</td>\n      <td>4.9671</td>\n      <td>2.0</td>\n      <td>242.0</td>\n      <td>17.8</td>\n      <td>396.90</td>\n      <td>9.14</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.02729</td>\n      <td>0.0</td>\n      <td>7.07</td>\n      <td>0.0</td>\n      <td>0.469</td>\n      <td>7.185</td>\n      <td>4.9671</td>\n      <td>2.0</td>\n      <td>242.0</td>\n      <td>17.8</td>\n      <td>392.83</td>\n      <td>4.03</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.03237</td>\n      <td>0.0</td>\n      <td>2.18</td>\n      <td>0.0</td>\n      <td>0.458</td>\n      <td>6.998</td>\n      <td>6.0622</td>\n      <td>3.0</td>\n      <td>222.0</td>\n      <td>18.7</td>\n      <td>394.63</td>\n      <td>2.94</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.06905</td>\n      <td>0.0</td>\n      <td>2.18</td>\n      <td>0.0</td>\n      <td>0.458</td>\n      <td>7.147</td>\n      <td>6.0622</td>\n      <td>3.0</td>\n      <td>222.0</td>\n      <td>18.7</td>\n      <td>396.90</td>\n      <td>5.33</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>501</th>\n      <td>0.06263</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.593</td>\n      <td>2.4786</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>391.99</td>\n      <td>9.67</td>\n    </tr>\n    <tr>\n      <th>502</th>\n      <td>0.04527</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.120</td>\n      <td>2.2875</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>396.90</td>\n      <td>9.08</td>\n    </tr>\n    <tr>\n      <th>503</th>\n      <td>0.06076</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.976</td>\n      <td>2.1675</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>396.90</td>\n      <td>5.64</td>\n    </tr>\n    <tr>\n      <th>504</th>\n      <td>0.10959</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.794</td>\n      <td>2.3889</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>393.45</td>\n      <td>6.48</td>\n    </tr>\n    <tr>\n      <th>505</th>\n      <td>0.04741</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.030</td>\n      <td>2.5050</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>396.90</td>\n      <td>7.88</td>\n    </tr>\n  </tbody>\n</table>\n<p>506 rows \u00d7 12 columns</p>\n</div>\n\n\n\nWhat we can see is that we now have all 506 of our original data points,  \nbut we now just have 12 of the 13 features as the AGE feature has been removed.\n\nThere are smarter things we can do besides simply removing the problematic\ndata points. Here, let's use the imputation process to replace the missing\nvalues with the mean value of the feature column\n\n\n```python\nX2, y2 = DataCleaning().imputation(X=X2, \n                                   y=y, \n                                   strategy='mean')\nX2\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>CRIM</th>\n      <th>ZN</th>\n      <th>INDUS</th>\n      <th>CHAS</th>\n      <th>NOX</th>\n      <th>RM</th>\n      <th>AGE</th>\n      <th>DIS</th>\n      <th>RAD</th>\n      <th>TAX</th>\n      <th>PTRATIO</th>\n      <th>B</th>\n      <th>LSTAT</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.00632</td>\n      <td>18.0</td>\n      <td>2.31</td>\n      <td>0.0</td>\n      <td>0.538</td>\n      <td>6.575</td>\n      <td>68.621315</td>\n      <td>4.0900</td>\n      <td>1.0</td>\n      <td>296.0</td>\n      <td>15.3</td>\n      <td>396.90</td>\n      <td>4.98</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.02731</td>\n      <td>0.0</td>\n      <td>7.07</td>\n      <td>0.0</td>\n      <td>0.469</td>\n      <td>6.421</td>\n      <td>68.621315</td>\n      <td>4.9671</td>\n      <td>2.0</td>\n      <td>242.0</td>\n      <td>17.8</td>\n      <td>396.90</td>\n      <td>9.14</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.02729</td>\n      <td>0.0</td>\n      <td>7.07</td>\n      <td>0.0</td>\n      <td>0.469</td>\n      <td>7.185</td>\n      <td>68.621315</td>\n      <td>4.9671</td>\n      <td>2.0</td>\n      <td>242.0</td>\n      <td>17.8</td>\n      <td>392.83</td>\n      <td>4.03</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.03237</td>\n      <td>0.0</td>\n      <td>2.18</td>\n      <td>0.0</td>\n      <td>0.458</td>\n      <td>6.998</td>\n      <td>68.621315</td>\n      <td>6.0622</td>\n      <td>3.0</td>\n      <td>222.0</td>\n      <td>18.7</td>\n      <td>394.63</td>\n      <td>2.94</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.06905</td>\n      <td>0.0</td>\n      <td>2.18</td>\n      <td>0.0</td>\n      <td>0.458</td>\n      <td>7.147</td>\n      <td>54.200000</td>\n      <td>6.0622</td>\n      <td>3.0</td>\n      <td>222.0</td>\n      <td>18.7</td>\n      <td>396.90</td>\n      <td>5.33</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>501</th>\n      <td>0.06263</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.593</td>\n      <td>69.100000</td>\n      <td>2.4786</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>391.99</td>\n      <td>9.67</td>\n    </tr>\n    <tr>\n      <th>502</th>\n      <td>0.04527</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.120</td>\n      <td>76.700000</td>\n      <td>2.2875</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>396.90</td>\n      <td>9.08</td>\n    </tr>\n    <tr>\n      <th>503</th>\n      <td>0.06076</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.976</td>\n      <td>91.000000</td>\n      <td>2.1675</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>396.90</td>\n      <td>5.64</td>\n    </tr>\n    <tr>\n      <th>504</th>\n      <td>0.10959</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.794</td>\n      <td>89.300000</td>\n      <td>2.3889</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>393.45</td>\n      <td>6.48</td>\n    </tr>\n    <tr>\n      <th>505</th>\n      <td>0.04741</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.030</td>\n      <td>80.800000</td>\n      <td>2.5050</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>396.90</td>\n      <td>7.88</td>\n    </tr>\n  </tbody>\n</table>\n<p>506 rows \u00d7 13 columns</p>\n</div>\n\n\n\nWhat we can see is that we now have all 506 of our original data points and \nall 13 of our feature columns, and the first four rows of the AGE feature\nnow contain the average value for that feature.\n\nFinally, let's do imputation again but use the median instead of \nthe mean value\n\n\n```python\nX3, y3 = DataCleaning().imputation(X=X3, \n                                   y=y, \n                                   strategy='median')\nX3\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>CRIM</th>\n      <th>ZN</th>\n      <th>INDUS</th>\n      <th>CHAS</th>\n      <th>NOX</th>\n      <th>RM</th>\n      <th>AGE</th>\n      <th>DIS</th>\n      <th>RAD</th>\n      <th>TAX</th>\n      <th>PTRATIO</th>\n      <th>B</th>\n      <th>LSTAT</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.00632</td>\n      <td>18.0</td>\n      <td>2.31</td>\n      <td>0.0</td>\n      <td>0.538</td>\n      <td>6.575</td>\n      <td>77.7</td>\n      <td>4.0900</td>\n      <td>1.0</td>\n      <td>296.0</td>\n      <td>15.3</td>\n      <td>396.90</td>\n      <td>4.98</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.02731</td>\n      <td>0.0</td>\n      <td>7.07</td>\n      <td>0.0</td>\n      <td>0.469</td>\n      <td>6.421</td>\n      <td>77.7</td>\n      <td>4.9671</td>\n      <td>2.0</td>\n      <td>242.0</td>\n      <td>17.8</td>\n      <td>396.90</td>\n      <td>9.14</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.02729</td>\n      <td>0.0</td>\n      <td>7.07</td>\n      <td>0.0</td>\n      <td>0.469</td>\n      <td>7.185</td>\n      <td>77.7</td>\n      <td>4.9671</td>\n      <td>2.0</td>\n      <td>242.0</td>\n      <td>17.8</td>\n      <td>392.83</td>\n      <td>4.03</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.03237</td>\n      <td>0.0</td>\n      <td>2.18</td>\n      <td>0.0</td>\n      <td>0.458</td>\n      <td>6.998</td>\n      <td>77.7</td>\n      <td>6.0622</td>\n      <td>3.0</td>\n      <td>222.0</td>\n      <td>18.7</td>\n      <td>394.63</td>\n      <td>2.94</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.06905</td>\n      <td>0.0</td>\n      <td>2.18</td>\n      <td>0.0</td>\n      <td>0.458</td>\n      <td>7.147</td>\n      <td>54.2</td>\n      <td>6.0622</td>\n      <td>3.0</td>\n      <td>222.0</td>\n      <td>18.7</td>\n      <td>396.90</td>\n      <td>5.33</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>501</th>\n      <td>0.06263</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.593</td>\n      <td>69.1</td>\n      <td>2.4786</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>391.99</td>\n      <td>9.67</td>\n    </tr>\n    <tr>\n      <th>502</th>\n      <td>0.04527</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.120</td>\n      <td>76.7</td>\n      <td>2.2875</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>396.90</td>\n      <td>9.08</td>\n    </tr>\n    <tr>\n      <th>503</th>\n      <td>0.06076</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.976</td>\n      <td>91.0</td>\n      <td>2.1675</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>396.90</td>\n      <td>5.64</td>\n    </tr>\n    <tr>\n      <th>504</th>\n      <td>0.10959</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.794</td>\n      <td>89.3</td>\n      <td>2.3889</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>393.45</td>\n      <td>6.48</td>\n    </tr>\n    <tr>\n      <th>505</th>\n      <td>0.04741</td>\n      <td>0.0</td>\n      <td>11.93</td>\n      <td>0.0</td>\n      <td>0.573</td>\n      <td>6.030</td>\n      <td>80.8</td>\n      <td>2.5050</td>\n      <td>1.0</td>\n      <td>273.0</td>\n      <td>21.0</td>\n      <td>396.90</td>\n      <td>7.88</td>\n    </tr>\n  </tbody>\n</table>\n<p>506 rows \u00d7 13 columns</p>\n</div>\n\n\n\nWhat we can see is that we now have all 506 of our original data points and \nall 13 of our feature columns, and the first four rows of the AGE feature\nnow contain the median value for that feature.\n\nMAST-ML provides a convenient method for evaluating a data cleaning routine,\nand saving the output to a dedicated folder in your MAST-ML output directory\nLet's do imputation again on our final remaining dataset and examine what's\ncontained in the saved output:\n\n\n```python\nX4, y4 = DataCleaning().evaluate(X=X4, \n                                 y=y, \n                                 method='imputation', \n                                 savepath=savepath, \n                                 strategy='mean')\n```\n\nCheck your MAST-ML save directory: you'll see a new folder starting with the name \"DataCleaning_...\"\nIn here, there are numerous Excel data files and a histogram plot. Below is a brief overview\nof what is contained in these files. One useful visualization is the histogram of the target data\nyou are trying to fit machine learning models to\n\n**data_cleaned.xlsx:** the cleaned dataset\n\n**data_columns_with_strings**: listed column names that contain string entries. Empty for our dataset\n\n**data_original.xlsx**: the original dataset prior to cleaning\n\n**data_outliers_all.xlsx**: a summary of the possible outlier points for each feature column\n\n**data_outliers_summary.xlsx**: a summary showing, for each data point, the number of feature values which may be outliers\n\n**histogram_target_values_statistics.xlsx**: key summary statistics of the distribution of y target data\n\n**histogram_target_values.png**: histogram plot of the y target data with some basic statistics included\n\n**histogram_target_values.xlsx**: the raw data used to make the histogram plot of the same name\n\n\n### DataCleaning directory with files:\n\n\n\n### Histogram of target values:\n\n\n## Task 3: Import and prepare a real dataset that is stored locally  <a name=\"task3\"></a>\n\nNext, we want to move away from the model datasets contained in scikit-learn and learn how to import\na real materials science dataset. As part of MAST-ML, we have included a dataset in the mastml/data\nfolder. The data is contained there as diffusion_data_selectfeatures.xlsx. This dataset contains\ncalculated migration energies of solute alloys in metal host materials.\n\nHere, we use the LocalDatasets module to load in the above mentioned diffusion dataset. \n\nWe first need to denote the column name of the target (y-data)\n\nIn addition, there are columns in the data file not used as features or target. We need to\nlist them here in the parameter extra_columns\n\n\n```python\ntarget = 'E_regression'\n\nextra_columns = ['Material compositions 1', 'Material compositions 2', 'Hop activation barrier']\n```\n\nHere, we make an instance of our LocalDatasets class. It needs a few parameters:\n   \n**file_path**: where the data is stored\n\n**target**: the column name of the y-data\n\n**extra_columns**: list containing extra columns in the data file not used for fitting\n\n**group_column**: column name denoting group labels (only used for LeaveOutGroup CV)\n   \n**testdata_columns**: column names denoting left-out data to evaluate using best\n     model from CV tests. This is manual way to leave out data. Can also be done\n     automatically using nested CV (we will do this in later tutorials)\n   \n**as_frame**: whether to return data as dataframe. Want this to be true.\n\nWe load the data with the load_data() method\n\n\n```python\nd = LocalDatasets(file_path=data_path+'/diffusion_data_allfeatures.xlsx',\n                  target=target, \n                  extra_columns=extra_columns, \n                  group_column='Material compositions 1',\n                  testdata_columns=None,\n                  as_frame=True)\n\ndata_dict = d.load_data()\n```\n\n    WARNING: feature_names not specified but target was specified. Assuming all columns except target and extra columns are features\n\n\nLet's look at the contents of the loaded data_dict\n\nWe see there are 5 keys:\n   \n**X**: the X feature matrix (used to fit the ML model)\n   \n**y**: the y target data vector (true values)\n   \n**X_extra**: matrix of extra information not used in fitting (i.e. not part of X or y)\n   \n**groups**: vector of group labels (here, a list of host elements)\n\n**X_testdata**: matrix or vector of left out data. Empty for our current example.\n\n\n```python\ndata_dict.keys()\n```\n\n\n\n\n    dict_keys(['X', 'y', 'groups', 'X_extra', 'X_testdata'])\n\n\n\nLet's assign each data object to its respective name\n\n\n```python\nX = data_dict['X']\ny = data_dict['y']\nX_extra = data_dict['X_extra']\ngroups = data_dict['groups']\nX_testdata = data_dict['X_testdata']\n```\n\nLet's have a look at the X feature matrix. It contains 287 elemental features.\nThere are a total of 408 diffusion activation barriers used for fitting\n\n\n```python\nX\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>valence_composition_average</th>\n      <th>phi_composition_average</th>\n      <th>NdValence_composition_average</th>\n      <th>MiracleRadius_composition_average</th>\n      <th>GSestFCClatcnt_composition_average</th>\n      <th>SecondIonizationEnergy_composition_average</th>\n      <th>IonizationEnergy_composition_average</th>\n      <th>n_ws^third_composition_average</th>\n      <th>ThermalConductivity_composition_average</th>\n      <th>CovalentRadius_composition_average</th>\n      <th>Column_composition_average</th>\n      <th>NsValence_composition_average</th>\n      <th>NUnfilled_composition_average</th>\n      <th>CovalentRadii_composition_average</th>\n      <th>Density_composition_average</th>\n      <th>BCCenergy_pa_composition_average</th>\n      <th>BCCvolume_padiff_composition_average</th>\n      <th>BCCvolume_pa_composition_average</th>\n      <th>MeltingT_composition_average</th>\n      <th>SpaceGroupNumber_composition_average</th>\n      <th>NValance_composition_average</th>\n      <th>ElectricalConductivity_composition_average</th>\n      <th>FirstIonizationEnergy_composition_average</th>\n      <th>GSvolume_pa_composition_average</th>\n      <th>Row_composition_average</th>\n      <th>Polarizability_composition_average</th>\n      <th>AtomicNumber_composition_average</th>\n      <th>ElectronAffinity_composition_average</th>\n      <th>BCCfermi_composition_average</th>\n      <th>GSestBCClatcnt_composition_average</th>\n      <th>HHIr_composition_average</th>\n      <th>HHIp_composition_average</th>\n      <th>GSenergy_pa_composition_average</th>\n      <th>ThirdIonizationEnergy_composition_average</th>\n      <th>BulkModulus_composition_average</th>\n      <th>BoilingT_composition_average</th>\n      <th>ICSDVolume_composition_average</th>\n      <th>HeatVaporization_composition_average</th>\n      <th>IonicRadii_composition_average</th>\n      <th>NdUnfilled_composition_average</th>\n      <th>...</th>\n      <th>Site2_NdValence</th>\n      <th>Site2_MiracleRadius</th>\n      <th>Site2_GSestFCClatcnt</th>\n      <th>Site2_IonizationEnergy</th>\n      <th>Site2_ThermalConductivity</th>\n      <th>Site2_CovalentRadius</th>\n      <th>Site2_Column</th>\n      <th>Site2_NUnfilled</th>\n      <th>Site2_CovalentRadii</th>\n      <th>Site2_Density</th>\n      <th>Site2_BCCenergy_pa</th>\n      <th>Site2_BCCvolume_padiff</th>\n      <th>Site2_BCCvolume_pa</th>\n      <th>Site2_MeltingT</th>\n      <th>Site2_SpaceGroupNumber</th>\n      <th>Site2_NValance</th>\n      <th>Site2_ElectricalConductivity</th>\n      <th>Site2_FirstIonizationEnergy</th>\n      <th>Site2_GSvolume_pa</th>\n      <th>Site2_Row</th>\n      <th>Site2_Polarizability</th>\n      <th>Site2_AtomicNumber</th>\n      <th>Site2_BCCfermi</th>\n      <th>Site2_GSestBCClatcnt</th>\n      <th>Site2_GSenergy_pa</th>\n      <th>Site2_BoilingT</th>\n      <th>Site2_ICSDVolume</th>\n      <th>Site2_HeatVaporization</th>\n      <th>Site2_IonicRadii</th>\n      <th>Site2_NdUnfilled</th>\n      <th>Site2_MendeleevNumber</th>\n      <th>Site2_ElasticModulus</th>\n      <th>Site2_Electronegativity</th>\n      <th>Site2_AtomicWeight</th>\n      <th>Site2_HeatFusion</th>\n      <th>Site2_SpecificHeatCapacity</th>\n      <th>Site2_AtomicRadii</th>\n      <th>Site2_ThermalExpansionCoefficient</th>\n      <th>Site2_BCCefflatcnt</th>\n      <th>Site2_AtomicVolume</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>2.0</td>\n      <td>4.350</td>\n      <td>10.0</td>\n      <td>144.0</td>\n      <td>4.027313</td>\n      <td>21.4900</td>\n      <td>731.00</td>\n      <td>1.360</td>\n      <td>429.00</td>\n      <td>145.0</td>\n      <td>11.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>1.340</td>\n      <td>10490.0</td>\n      <td>-2.719979</td>\n      <td>-0.1300</td>\n      <td>16.200</td>\n      <td>1234.930</td>\n      <td>225.0</td>\n      <td>11.0</td>\n      <td>62.90</td>\n      <td>7.576230</td>\n      <td>16.3300</td>\n      <td>5.0</td>\n      <td>6.990</td>\n      <td>47.0</td>\n      <td>125.70</td>\n      <td>4.052760</td>\n      <td>3.196481</td>\n      <td>1400</td>\n      <td>1200</td>\n      <td>-2.765394</td>\n      <td>34.8300</td>\n      <td>100.0</td>\n      <td>2435.0</td>\n      <td>17.00</td>\n      <td>250.630</td>\n      <td>1.150</td>\n      <td>0.0</td>\n      <td>...</td>\n      <td>10</td>\n      <td>144</td>\n      <td>4.027313</td>\n      <td>731.0</td>\n      <td>429.0</td>\n      <td>145</td>\n      <td>11</td>\n      <td>1</td>\n      <td>1.34</td>\n      <td>10490</td>\n      <td>-2.719979</td>\n      <td>-0.130</td>\n      <td>16.20</td>\n      <td>1234.93</td>\n      <td>225</td>\n      <td>11</td>\n      <td>62.9</td>\n      <td>7.57623</td>\n      <td>16.330</td>\n      <td>5</td>\n      <td>6.99</td>\n      <td>47</td>\n      <td>4.052760</td>\n      <td>3.196481</td>\n      <td>-2.765394</td>\n      <td>2435.0</td>\n      <td>17.0</td>\n      <td>250.63</td>\n      <td>1.15</td>\n      <td>0</td>\n      <td>65</td>\n      <td>80.0</td>\n      <td>1.93</td>\n      <td>107.868200</td>\n      <td>11.30</td>\n      <td>0.235</td>\n      <td>1.444</td>\n      <td>18.9</td>\n      <td>6.375951</td>\n      <td>17.075648</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2.5</td>\n      <td>4.725</td>\n      <td>8.5</td>\n      <td>134.5</td>\n      <td>3.737485</td>\n      <td>19.2750</td>\n      <td>744.50</td>\n      <td>1.555</td>\n      <td>264.50</td>\n      <td>135.5</td>\n      <td>10.0</td>\n      <td>1.5</td>\n      <td>2.0</td>\n      <td>1.250</td>\n      <td>9695.0</td>\n      <td>-4.850033</td>\n      <td>0.0325</td>\n      <td>13.320</td>\n      <td>1501.465</td>\n      <td>209.5</td>\n      <td>10.0</td>\n      <td>40.40</td>\n      <td>7.728620</td>\n      <td>13.2875</td>\n      <td>4.5</td>\n      <td>7.245</td>\n      <td>37.0</td>\n      <td>97.85</td>\n      <td>5.096587</td>\n      <td>2.966444</td>\n      <td>2050</td>\n      <td>2150</td>\n      <td>-4.922891</td>\n      <td>34.1650</td>\n      <td>140.0</td>\n      <td>2817.5</td>\n      <td>14.05</td>\n      <td>311.965</td>\n      <td>0.900</td>\n      <td>1.5</td>\n      <td>...</td>\n      <td>7</td>\n      <td>125</td>\n      <td>3.447656</td>\n      <td>758.0</td>\n      <td>100.0</td>\n      <td>126</td>\n      <td>9</td>\n      <td>3</td>\n      <td>1.16</td>\n      <td>8900</td>\n      <td>-6.980087</td>\n      <td>0.195</td>\n      <td>10.44</td>\n      <td>1768.00</td>\n      <td>194</td>\n      <td>9</td>\n      <td>17.9</td>\n      <td>7.88101</td>\n      <td>10.245</td>\n      <td>4</td>\n      <td>7.50</td>\n      <td>27</td>\n      <td>6.140415</td>\n      <td>2.736407</td>\n      <td>-7.080389</td>\n      <td>3200.0</td>\n      <td>11.1</td>\n      <td>373.30</td>\n      <td>0.65</td>\n      <td>3</td>\n      <td>58</td>\n      <td>208.0</td>\n      <td>1.88</td>\n      <td>58.933195</td>\n      <td>16.20</td>\n      <td>0.421</td>\n      <td>1.253</td>\n      <td>13.0</td>\n      <td>5.507318</td>\n      <td>10.995861</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>4.0</td>\n      <td>4.500</td>\n      <td>7.5</td>\n      <td>137.0</td>\n      <td>3.788936</td>\n      <td>18.9950</td>\n      <td>691.90</td>\n      <td>1.545</td>\n      <td>261.35</td>\n      <td>142.0</td>\n      <td>8.5</td>\n      <td>1.0</td>\n      <td>3.5</td>\n      <td>1.260</td>\n      <td>8815.0</td>\n      <td>-6.112393</td>\n      <td>-0.0750</td>\n      <td>13.685</td>\n      <td>1707.465</td>\n      <td>227.0</td>\n      <td>8.5</td>\n      <td>35.40</td>\n      <td>7.171370</td>\n      <td>13.7600</td>\n      <td>4.5</td>\n      <td>9.295</td>\n      <td>35.5</td>\n      <td>94.85</td>\n      <td>6.014901</td>\n      <td>3.007280</td>\n      <td>2750</td>\n      <td>2150</td>\n      <td>-6.135555</td>\n      <td>32.8950</td>\n      <td>130.0</td>\n      <td>2689.5</td>\n      <td>14.50</td>\n      <td>295.065</td>\n      <td>0.885</td>\n      <td>2.5</td>\n      <td>...</td>\n      <td>5</td>\n      <td>130</td>\n      <td>3.550559</td>\n      <td>652.8</td>\n      <td>93.7</td>\n      <td>139</td>\n      <td>6</td>\n      <td>6</td>\n      <td>1.18</td>\n      <td>7140</td>\n      <td>-9.504808</td>\n      <td>-0.020</td>\n      <td>11.17</td>\n      <td>2180.00</td>\n      <td>229</td>\n      <td>6</td>\n      <td>7.9</td>\n      <td>6.76651</td>\n      <td>11.190</td>\n      <td>4</td>\n      <td>11.60</td>\n      <td>24</td>\n      <td>7.977043</td>\n      <td>2.818080</td>\n      <td>-9.505717</td>\n      <td>2944.0</td>\n      <td>12.0</td>\n      <td>339.50</td>\n      <td>0.62</td>\n      <td>5</td>\n      <td>49</td>\n      <td>259.0</td>\n      <td>1.66</td>\n      <td>51.996100</td>\n      <td>21.00</td>\n      <td>0.449</td>\n      <td>1.249</td>\n      <td>4.9</td>\n      <td>5.632801</td>\n      <td>12.092937</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>2.0</td>\n      <td>4.400</td>\n      <td>10.0</td>\n      <td>135.0</td>\n      <td>3.782567</td>\n      <td>20.8910</td>\n      <td>738.20</td>\n      <td>1.415</td>\n      <td>415.00</td>\n      <td>138.5</td>\n      <td>11.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>1.255</td>\n      <td>9705.0</td>\n      <td>-3.181433</td>\n      <td>-0.0600</td>\n      <td>13.640</td>\n      <td>1296.350</td>\n      <td>225.0</td>\n      <td>11.0</td>\n      <td>61.80</td>\n      <td>7.651305</td>\n      <td>13.7000</td>\n      <td>4.5</td>\n      <td>6.570</td>\n      <td>38.0</td>\n      <td>122.00</td>\n      <td>4.215750</td>\n      <td>3.002225</td>\n      <td>1450</td>\n      <td>1400</td>\n      <td>-3.223024</td>\n      <td>35.8300</td>\n      <td>120.0</td>\n      <td>2817.5</td>\n      <td>14.40</td>\n      <td>275.565</td>\n      <td>0.940</td>\n      <td>0.0</td>\n      <td>...</td>\n      <td>10</td>\n      <td>126</td>\n      <td>3.537821</td>\n      <td>745.4</td>\n      <td>401.0</td>\n      <td>132</td>\n      <td>11</td>\n      <td>1</td>\n      <td>1.17</td>\n      <td>8920</td>\n      <td>-3.642887</td>\n      <td>0.010</td>\n      <td>11.08</td>\n      <td>1357.77</td>\n      <td>225</td>\n      <td>11</td>\n      <td>60.7</td>\n      <td>7.72638</td>\n      <td>11.070</td>\n      <td>4</td>\n      <td>6.15</td>\n      <td>29</td>\n      <td>4.378740</td>\n      <td>2.807970</td>\n      <td>-3.680655</td>\n      <td>3200.0</td>\n      <td>11.8</td>\n      <td>300.50</td>\n      <td>0.73</td>\n      <td>0</td>\n      <td>64</td>\n      <td>124.0</td>\n      <td>1.90</td>\n      <td>63.546000</td>\n      <td>13.60</td>\n      <td>0.385</td>\n      <td>1.278</td>\n      <td>16.5</td>\n      <td>5.617632</td>\n      <td>11.829942</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>4.0</td>\n      <td>4.640</td>\n      <td>8.0</td>\n      <td>134.5</td>\n      <td>3.764269</td>\n      <td>18.8350</td>\n      <td>745.15</td>\n      <td>1.565</td>\n      <td>254.60</td>\n      <td>138.5</td>\n      <td>9.5</td>\n      <td>1.5</td>\n      <td>2.5</td>\n      <td>1.255</td>\n      <td>9182.0</td>\n      <td>-5.502732</td>\n      <td>-0.0650</td>\n      <td>13.465</td>\n      <td>1522.965</td>\n      <td>227.0</td>\n      <td>9.5</td>\n      <td>37.05</td>\n      <td>7.739315</td>\n      <td>13.5300</td>\n      <td>4.5</td>\n      <td>7.695</td>\n      <td>36.5</td>\n      <td>74.85</td>\n      <td>5.252127</td>\n      <td>2.987702</td>\n      <td>1400</td>\n      <td>1800</td>\n      <td>-5.525439</td>\n      <td>32.7405</td>\n      <td>135.0</td>\n      <td>2784.5</td>\n      <td>14.35</td>\n      <td>300.065</td>\n      <td>0.850</td>\n      <td>2.0</td>\n      <td>...</td>\n      <td>6</td>\n      <td>125</td>\n      <td>3.501224</td>\n      <td>759.3</td>\n      <td>80.2</td>\n      <td>132</td>\n      <td>8</td>\n      <td>4</td>\n      <td>1.17</td>\n      <td>7874</td>\n      <td>-8.285484</td>\n      <td>0.000</td>\n      <td>10.73</td>\n      <td>1811.00</td>\n      <td>229</td>\n      <td>8</td>\n      <td>11.2</td>\n      <td>7.90240</td>\n      <td>10.730</td>\n      <td>4</td>\n      <td>8.40</td>\n      <td>26</td>\n      <td>6.451493</td>\n      <td>2.778923</td>\n      <td>-8.285484</td>\n      <td>3134.0</td>\n      <td>11.7</td>\n      <td>349.50</td>\n      <td>0.55</td>\n      <td>4</td>\n      <td>55</td>\n      <td>211.0</td>\n      <td>1.83</td>\n      <td>55.845000</td>\n      <td>13.81</td>\n      <td>0.449</td>\n      <td>1.241</td>\n      <td>11.8</td>\n      <td>5.557847</td>\n      <td>11.777365</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>403</th>\n      <td>4.5</td>\n      <td>3.750</td>\n      <td>3.0</td>\n      <td>150.5</td>\n      <td>4.350534</td>\n      <td>13.7250</td>\n      <td>662.00</td>\n      <td>1.525</td>\n      <td>38.20</td>\n      <td>169.5</td>\n      <td>4.5</td>\n      <td>1.5</td>\n      <td>7.5</td>\n      <td>1.395</td>\n      <td>7540.5</td>\n      <td>-9.280298</td>\n      <td>-0.2225</td>\n      <td>20.465</td>\n      <td>2439.000</td>\n      <td>211.5</td>\n      <td>4.5</td>\n      <td>4.45</td>\n      <td>6.696375</td>\n      <td>20.6875</td>\n      <td>5.0</td>\n      <td>16.800</td>\n      <td>40.5</td>\n      <td>73.00</td>\n      <td>4.564936</td>\n      <td>3.453021</td>\n      <td>5700</td>\n      <td>5950</td>\n      <td>-9.319640</td>\n      <td>24.0150</td>\n      <td>85.0</td>\n      <td>4849.5</td>\n      <td>20.65</td>\n      <td>640.300</td>\n      <td>0.740</td>\n      <td>7.0</td>\n      <td>...</td>\n      <td>4</td>\n      <td>143</td>\n      <td>4.173989</td>\n      <td>664.0</td>\n      <td>53.7</td>\n      <td>164</td>\n      <td>5</td>\n      <td>7</td>\n      <td>1.34</td>\n      <td>8570</td>\n      <td>-10.093322</td>\n      <td>0.000</td>\n      <td>18.18</td>\n      <td>2750.00</td>\n      <td>229</td>\n      <td>5</td>\n      <td>6.6</td>\n      <td>6.75885</td>\n      <td>18.180</td>\n      <td>5</td>\n      <td>15.70</td>\n      <td>41</td>\n      <td>4.901822</td>\n      <td>3.312897</td>\n      <td>-10.093322</td>\n      <td>5017.0</td>\n      <td>18.1</td>\n      <td>690.10</td>\n      <td>0.64</td>\n      <td>6</td>\n      <td>47</td>\n      <td>104.0</td>\n      <td>1.60</td>\n      <td>92.906380</td>\n      <td>30.00</td>\n      <td>0.265</td>\n      <td>1.429</td>\n      <td>7.3</td>\n      <td>6.625794</td>\n      <td>18.002133</td>\n    </tr>\n    <tr>\n      <th>404</th>\n      <td>4.5</td>\n      <td>3.750</td>\n      <td>2.5</td>\n      <td>151.5</td>\n      <td>4.348236</td>\n      <td>6.5650</td>\n      <td>710.50</td>\n      <td>1.520</td>\n      <td>40.10</td>\n      <td>172.5</td>\n      <td>4.5</td>\n      <td>2.0</td>\n      <td>7.5</td>\n      <td>1.395</td>\n      <td>11580.5</td>\n      <td>-10.159337</td>\n      <td>-0.2225</td>\n      <td>20.435</td>\n      <td>2709.000</td>\n      <td>211.5</td>\n      <td>11.5</td>\n      <td>5.20</td>\n      <td>7.091735</td>\n      <td>20.6575</td>\n      <td>5.5</td>\n      <td>15.500</td>\n      <td>56.5</td>\n      <td>55.00</td>\n      <td>4.832147</td>\n      <td>3.451197</td>\n      <td>3700</td>\n      <td>2850</td>\n      <td>-10.198679</td>\n      <td>11.4950</td>\n      <td>100.0</td>\n      <td>5206.5</td>\n      <td>20.40</td>\n      <td>663.750</td>\n      <td>0.740</td>\n      <td>7.5</td>\n      <td>...</td>\n      <td>3</td>\n      <td>145</td>\n      <td>4.169392</td>\n      <td>761.0</td>\n      <td>57.5</td>\n      <td>170</td>\n      <td>5</td>\n      <td>7</td>\n      <td>1.34</td>\n      <td>16650</td>\n      <td>-11.851400</td>\n      <td>0.000</td>\n      <td>18.12</td>\n      <td>3290.00</td>\n      <td>229</td>\n      <td>19</td>\n      <td>8.1</td>\n      <td>7.54957</td>\n      <td>18.120</td>\n      <td>6</td>\n      <td>13.10</td>\n      <td>73</td>\n      <td>5.436244</td>\n      <td>3.309249</td>\n      <td>-11.851400</td>\n      <td>5731.0</td>\n      <td>17.6</td>\n      <td>737.00</td>\n      <td>0.64</td>\n      <td>7</td>\n      <td>48</td>\n      <td>183.0</td>\n      <td>1.50</td>\n      <td>180.947880</td>\n      <td>36.57</td>\n      <td>0.140</td>\n      <td>1.430</td>\n      <td>6.3</td>\n      <td>6.618497</td>\n      <td>18.046730</td>\n    </tr>\n    <tr>\n      <th>405</th>\n      <td>4.0</td>\n      <td>3.625</td>\n      <td>2.0</td>\n      <td>150.0</td>\n      <td>4.291886</td>\n      <td>13.3550</td>\n      <td>659.00</td>\n      <td>1.465</td>\n      <td>22.30</td>\n      <td>167.5</td>\n      <td>4.0</td>\n      <td>2.0</td>\n      <td>8.0</td>\n      <td>1.385</td>\n      <td>5509.0</td>\n      <td>-8.064271</td>\n      <td>-0.1475</td>\n      <td>19.795</td>\n      <td>2034.500</td>\n      <td>194.0</td>\n      <td>4.0</td>\n      <td>2.45</td>\n      <td>6.731010</td>\n      <td>19.9425</td>\n      <td>4.5</td>\n      <td>16.250</td>\n      <td>31.0</td>\n      <td>35.00</td>\n      <td>3.602101</td>\n      <td>3.406472</td>\n      <td>2100</td>\n      <td>2250</td>\n      <td>-8.160593</td>\n      <td>25.2405</td>\n      <td>55.0</td>\n      <td>4121.0</td>\n      <td>20.40</td>\n      <td>507.850</td>\n      <td>0.725</td>\n      <td>8.0</td>\n      <td>...</td>\n      <td>2</td>\n      <td>142</td>\n      <td>4.056693</td>\n      <td>658.0</td>\n      <td>21.9</td>\n      <td>160</td>\n      <td>4</td>\n      <td>8</td>\n      <td>1.32</td>\n      <td>4507</td>\n      <td>-7.661268</td>\n      <td>0.150</td>\n      <td>16.84</td>\n      <td>1941.00</td>\n      <td>194</td>\n      <td>4</td>\n      <td>2.6</td>\n      <td>6.82812</td>\n      <td>16.690</td>\n      <td>4</td>\n      <td>14.60</td>\n      <td>22</td>\n      <td>2.976151</td>\n      <td>3.219799</td>\n      <td>-7.775227</td>\n      <td>3560.0</td>\n      <td>17.6</td>\n      <td>425.20</td>\n      <td>0.61</td>\n      <td>8</td>\n      <td>43</td>\n      <td>110.0</td>\n      <td>1.54</td>\n      <td>47.867000</td>\n      <td>14.15</td>\n      <td>0.523</td>\n      <td>1.448</td>\n      <td>8.6</td>\n      <td>6.458833</td>\n      <td>17.636317</td>\n    </tr>\n    <tr>\n      <th>406</th>\n      <td>4.0</td>\n      <td>3.525</td>\n      <td>2.0</td>\n      <td>158.0</td>\n      <td>4.494239</td>\n      <td>14.0275</td>\n      <td>651.00</td>\n      <td>1.430</td>\n      <td>22.85</td>\n      <td>175.0</td>\n      <td>4.0</td>\n      <td>2.0</td>\n      <td>8.0</td>\n      <td>1.445</td>\n      <td>9910.5</td>\n      <td>-9.120962</td>\n      <td>-0.3875</td>\n      <td>22.310</td>\n      <td>2317.000</td>\n      <td>194.0</td>\n      <td>11.0</td>\n      <td>2.85</td>\n      <td>6.729485</td>\n      <td>22.6975</td>\n      <td>5.5</td>\n      <td>17.050</td>\n      <td>56.0</td>\n      <td>25.00</td>\n      <td>4.480361</td>\n      <td>3.567080</td>\n      <td>2600</td>\n      <td>3400</td>\n      <td>-9.250129</td>\n      <td>23.1550</td>\n      <td>55.0</td>\n      <td>4779.0</td>\n      <td>22.80</td>\n      <td>625.785</td>\n      <td>0.835</td>\n      <td>8.0</td>\n      <td>...</td>\n      <td>2</td>\n      <td>158</td>\n      <td>4.461398</td>\n      <td>642.0</td>\n      <td>23.0</td>\n      <td>175</td>\n      <td>4</td>\n      <td>8</td>\n      <td>1.44</td>\n      <td>13310</td>\n      <td>-9.774649</td>\n      <td>-0.330</td>\n      <td>21.87</td>\n      <td>2506.00</td>\n      <td>194</td>\n      <td>18</td>\n      <td>3.4</td>\n      <td>6.82507</td>\n      <td>22.200</td>\n      <td>6</td>\n      <td>16.20</td>\n      <td>72</td>\n      <td>4.732671</td>\n      <td>3.541014</td>\n      <td>-9.954299</td>\n      <td>4876.0</td>\n      <td>22.4</td>\n      <td>661.07</td>\n      <td>0.83</td>\n      <td>8</td>\n      <td>45</td>\n      <td>139.0</td>\n      <td>1.30</td>\n      <td>178.490000</td>\n      <td>27.20</td>\n      <td>0.140</td>\n      <td>1.564</td>\n      <td>5.9</td>\n      <td>7.046762</td>\n      <td>22.268711</td>\n    </tr>\n    <tr>\n      <th>407</th>\n      <td>4.0</td>\n      <td>3.800</td>\n      <td>6.0</td>\n      <td>156.5</td>\n      <td>4.816669</td>\n      <td>13.8810</td>\n      <td>684.30</td>\n      <td>1.325</td>\n      <td>44.65</td>\n      <td>157.0</td>\n      <td>9.0</td>\n      <td>2.0</td>\n      <td>6.0</td>\n      <td>1.430</td>\n      <td>6910.5</td>\n      <td>-6.181100</td>\n      <td>-4.2500</td>\n      <td>23.990</td>\n      <td>1316.540</td>\n      <td>167.5</td>\n      <td>9.0</td>\n      <td>5.50</td>\n      <td>6.988910</td>\n      <td>28.2400</td>\n      <td>5.0</td>\n      <td>12.480</td>\n      <td>45.0</td>\n      <td>85.50</td>\n      <td>6.639299</td>\n      <td>3.822993</td>\n      <td>2100</td>\n      <td>3000</td>\n      <td>-6.253503</td>\n      <td>26.7460</td>\n      <td>29.0</td>\n      <td>3778.5</td>\n      <td>25.10</td>\n      <td>440.435</td>\n      <td>0.775</td>\n      <td>4.0</td>\n      <td>...</td>\n      <td>10</td>\n      <td>155</td>\n      <td>5.106259</td>\n      <td>708.6</td>\n      <td>66.6</td>\n      <td>139</td>\n      <td>14</td>\n      <td>4</td>\n      <td>1.41</td>\n      <td>7310</td>\n      <td>-3.894925</td>\n      <td>-8.055</td>\n      <td>25.23</td>\n      <td>505.08</td>\n      <td>141</td>\n      <td>14</td>\n      <td>8.7</td>\n      <td>7.34392</td>\n      <td>33.285</td>\n      <td>5</td>\n      <td>7.06</td>\n      <td>50</td>\n      <td>9.050547</td>\n      <td>4.052841</td>\n      <td>-3.961047</td>\n      <td>2875.0</td>\n      <td>27.0</td>\n      <td>290.37</td>\n      <td>0.71</td>\n      <td>0</td>\n      <td>80</td>\n      <td>50.0</td>\n      <td>1.96</td>\n      <td>118.710000</td>\n      <td>7.15</td>\n      <td>0.228</td>\n      <td>1.620</td>\n      <td>22.0</td>\n      <td>7.390589</td>\n      <td>26.966785</td>\n    </tr>\n  </tbody>\n</table>\n<p>408 rows \u00d7 287 columns</p>\n</div>\n\n\n\nLet's look at the groups list. The groups denote the element identity of the host metal\n\n\n```python\ngroups\n```\n\n\n\n\n    0      Ag\n    1      Ag\n    2      Ag\n    3      Ag\n    4      Ag\n           ..\n    403    Zr\n    404    Zr\n    405    Zr\n    406    Zr\n    407    Zr\n    Name: Material compositions 1, Length: 408, dtype: object\n\n\n\nLet's examine the extra data not used in fitting. Note that the y-data we are \nfitting to are equal to the E_regression values listed here, minus the E_regression\nvalue of the pure material. Material compositions 1 are the host elements, which\nare the same values used in the groups list. Material compositions 2 are the solute\nelements (i.e. the diffusing impurity in the host material)\n\n\n```python\nX_extra\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Material compositions 1</th>\n      <th>Material compositions 2</th>\n      <th>Hop activation barrier</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Ag</td>\n      <td>Ag</td>\n      <td>-0.365590</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Ag</td>\n      <td>Co</td>\n      <td>-0.675263</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Ag</td>\n      <td>Cr</td>\n      <td>-0.047690</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Ag</td>\n      <td>Cu</td>\n      <td>-0.428459</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Ag</td>\n      <td>Fe</td>\n      <td>0.081529</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>403</th>\n      <td>Zr</td>\n      <td>Nb</td>\n      <td>-0.478007</td>\n    </tr>\n    <tr>\n      <th>404</th>\n      <td>Zr</td>\n      <td>Ta</td>\n      <td>-0.054726</td>\n    </tr>\n    <tr>\n      <th>405</th>\n      <td>Zr</td>\n      <td>Ti</td>\n      <td>-0.022476</td>\n    </tr>\n    <tr>\n      <th>406</th>\n      <td>Zr</td>\n      <td>Hf</td>\n      <td>-0.104201</td>\n    </tr>\n    <tr>\n      <th>407</th>\n      <td>Zr</td>\n      <td>Sn</td>\n      <td>-0.045931</td>\n    </tr>\n  </tbody>\n</table>\n<p>408 rows \u00d7 3 columns</p>\n</div>\n\n\n\nFinally, we can look at our manually left-out data set. For this tutorial we\nhave left this blank, but we will make use of it in a future tutorial\n\n\n```python\nX_testdata\n```\n\n## Task 4: Download and import data from various materials databases  <a name=\"task4\"></a>\n\nNext, let's download some datasets from remote materials databases, then import\nthem for use in MAST-ML\n\nHere, we will download a materials dataset of steel alloy yield strengths from the \nmatminer datasets repository:\n\n\n```python\ndf = MatminerDatasets().download_data(name='steel_strength')\n```\n\n    Fetching steel_strength.json.gz from https://ndownloader.figshare.com/files/13354691 to /usr/local/lib/python3.7/dist-packages/matminer/datasets/steel_strength.json.gz\n\n\nThe output of downloading this data is a pandas dataframe. If we know which columns\ncorrespond to X, y, X_extra, and so on, we can designate those fields here through\npandas commands. Alternatively, we can import the just-saved steel_strength.xlsx file\nusing the LocalDatasets class just like we did in the previous task:\n\n\n```python\ntarget = 'yield strength'\nextra_columns = ['formula', 'tensile strength', 'elongation']\n\nd = LocalDatasets(file_path='steel_strength.xlsx', \n                  target=target, \n                  extra_columns=extra_columns, \n                  group_column=None,\n                  testdata_columns=None,\n                  as_frame=True)\n\n# Load the data with the load_data() method\ndata_dict = d.load_data()\n\n# Designate the X, y and X_extra data \nX = data_dict['X']\ny = data_dict['y']\nX_extra = data_dict['X_extra']\n```\n\n    WARNING: feature_names not specified but target was specified. Assuming all columns except target and extra columns are features\n\n\nLet's have a look at the X feature matrix for this data. \nThe X features are the atom fractions of different elements\nin each steel alloy\n\n\n```python\nX\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>c</th>\n      <th>mn</th>\n      <th>si</th>\n      <th>cr</th>\n      <th>ni</th>\n      <th>mo</th>\n      <th>v</th>\n      <th>n</th>\n      <th>nb</th>\n      <th>co</th>\n      <th>w</th>\n      <th>al</th>\n      <th>ti</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.02</td>\n      <td>0.05</td>\n      <td>0.05</td>\n      <td>0.01</td>\n      <td>19.70</td>\n      <td>2.95</td>\n      <td>0.01</td>\n      <td>0.00</td>\n      <td>0.01</td>\n      <td>15.00</td>\n      <td>0.00</td>\n      <td>0.15</td>\n      <td>1.55</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.18</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>13.44</td>\n      <td>0.01</td>\n      <td>3.01</td>\n      <td>0.46</td>\n      <td>0.04</td>\n      <td>0.01</td>\n      <td>19.46</td>\n      <td>2.35</td>\n      <td>0.04</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.00</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>8.67</td>\n      <td>13.45</td>\n      <td>0.82</td>\n      <td>0.01</td>\n      <td>0.00</td>\n      <td>0.01</td>\n      <td>13.90</td>\n      <td>0.00</td>\n      <td>0.39</td>\n      <td>0.57</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.01</td>\n      <td>0.05</td>\n      <td>0.05</td>\n      <td>0.01</td>\n      <td>17.70</td>\n      <td>3.95</td>\n      <td>0.01</td>\n      <td>0.00</td>\n      <td>0.01</td>\n      <td>15.00</td>\n      <td>0.00</td>\n      <td>0.13</td>\n      <td>1.47</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.01</td>\n      <td>0.05</td>\n      <td>0.05</td>\n      <td>0.01</td>\n      <td>19.40</td>\n      <td>1.45</td>\n      <td>0.01</td>\n      <td>0.00</td>\n      <td>0.01</td>\n      <td>14.90</td>\n      <td>0.00</td>\n      <td>0.13</td>\n      <td>1.55</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>307</th>\n      <td>0.38</td>\n      <td>0.18</td>\n      <td>0.01</td>\n      <td>7.27</td>\n      <td>0.01</td>\n      <td>3.77</td>\n      <td>0.96</td>\n      <td>0.00</td>\n      <td>0.01</td>\n      <td>4.90</td>\n      <td>0.00</td>\n      <td>0.03</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>308</th>\n      <td>0.00</td>\n      <td>0.06</td>\n      <td>0.05</td>\n      <td>5.15</td>\n      <td>10.20</td>\n      <td>3.20</td>\n      <td>0.01</td>\n      <td>0.00</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.00</td>\n      <td>0.03</td>\n      <td>0.09</td>\n    </tr>\n    <tr>\n      <th>309</th>\n      <td>0.37</td>\n      <td>0.17</td>\n      <td>0.01</td>\n      <td>5.20</td>\n      <td>0.01</td>\n      <td>5.84</td>\n      <td>1.05</td>\n      <td>0.00</td>\n      <td>0.91</td>\n      <td>4.88</td>\n      <td>0.00</td>\n      <td>0.03</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>310</th>\n      <td>0.41</td>\n      <td>0.19</td>\n      <td>0.01</td>\n      <td>6.99</td>\n      <td>0.01</td>\n      <td>5.84</td>\n      <td>0.92</td>\n      <td>0.00</td>\n      <td>0.01</td>\n      <td>0.02</td>\n      <td>0.00</td>\n      <td>0.03</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>311</th>\n      <td>0.27</td>\n      <td>0.27</td>\n      <td>0.01</td>\n      <td>0.41</td>\n      <td>8.28</td>\n      <td>0.49</td>\n      <td>0.07</td>\n      <td>0.00</td>\n      <td>0.01</td>\n      <td>3.90</td>\n      <td>0.00</td>\n      <td>0.03</td>\n      <td>0.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>312 rows \u00d7 13 columns</p>\n</div>\n\n\n\nLet's have a look at the y target data. They data are yield strengths (in MPa) for each alloy\n\n\n```python\ny\n```\n\n\n\n\n    0      2411.5\n    1      1123.1\n    2      1736.3\n    3      2487.3\n    4      2249.6\n            ...  \n    307    1722.5\n    308    1019.0\n    309    1860.3\n    310    1812.1\n    311    1139.7\n    Name: yield strength, Length: 312, dtype: float64\n\n\n\nThere are many other datasets besides this steel strength dataset\navailable on the matminer repository. Information on these other\ndatasets, and the names used to query them, can be output using:\n\n\n```python\nMatminerDatasets().get_available_datasets()\n```\n\n    boltztrap_mp: Effective mass and thermoelectric properties of 8924 compounds in The  Materials Project database that are calculated by the BoltzTraP software package run on the GGA-PBE or GGA+U density functional theory calculation results. The properties are reported at the temperature of 300 Kelvin and the carrier concentration of 1e18 1/cm3.\n    \n    brgoch_superhard_training: 2574 materials used for training regressors that predict shear and bulk modulus.\n    \n    castelli_perovskites: 18,928 perovskites generated with ABX combinatorics, calculating gllbsc band gap and pbe structure, and also reporting absolute band edge positions and heat of formation.\n    \n    citrine_thermal_conductivity: Thermal conductivity of 872 compounds measured experimentally and retrieved from Citrine database from various references. The reported values are measured at various temperatures of which 295 are at room temperature.\n    \n    dielectric_constant: 1,056 structures with dielectric properties, calculated with DFPT-PBE.\n    \n    double_perovskites_gap: Band gap of 1306 double perovskites (a_1-b_1-a_2-b_2-O6) calculated using \ufeffGritsenko, van Leeuwen, van Lenthe and Baerends potential (gllbsc) in GPAW.\n    \n    double_perovskites_gap_lumo: Supplementary lumo data of 55 atoms for the double_perovskites_gap dataset.\n    \n    elastic_tensor_2015: 1,181 structures with elastic properties calculated with DFT-PBE.\n    \n    expt_formation_enthalpy: Experimental formation enthalpies for inorganic compounds, collected from years of calorimetric experiments. There are 1,276 entries in this dataset, mostly binary compounds. Matching mpids or oqmdids as well as the DFT-computed formation energies are also added (if any).\n    \n    expt_gap: Experimental band gap of 6354 inorganic semiconductors.\n    \n    flla: 3938 structures and computed formation energies from \"Crystal Structure Representations for Machine Learning Models of Formation Energies.\"\n    \n    glass_binary: Metallic glass formation data for binary alloys, collected from various experimental techniques such as melt-spinning or mechanical alloying. This dataset covers all compositions with an interval of 5 at. % in 59 binary systems, containing a total of 5959 alloys in the dataset. The target property of this dataset is the glass forming ability (GFA), i.e. whether the composition can form monolithic glass or not, which is either 1 for glass forming or 0 for non-full glass forming.\n    \n    glass_binary_v2: Identical to glass_binary dataset, but with duplicate entries merged. If there was a disagreement in gfa when merging the class was defaulted to 1.\n    \n    glass_ternary_hipt: Metallic glass formation dataset for ternary alloys, collected from the high-throughput sputtering experiments measuring whether it is possible to form a glass using sputtering. The hipt experimental data are of the Co-Fe-Zr, Co-Ti-Zr, Co-V-Zr and Fe-Ti-Nb ternary systems.\n    \n    glass_ternary_landolt: Metallic glass formation dataset for ternary alloys, collected from the \"Nonequilibrium Phase Diagrams of Ternary Amorphous Alloys,\u2019 a volume of the Landolt\u2013 B\u00f6rnstein collection. This dataset contains experimental measurements of whether it is possible to form a glass using a variety of processing techniques at thousands of compositions from hundreds of ternary systems. The processing techniques are designated in the \"processing\" column. There are originally 7191 experiments in this dataset, will be reduced to 6203 after deduplicated, and will be further reduced to 6118 if combining multiple data for one composition. There are originally 6780 melt-spinning experiments in this dataset, will be reduced to 5800 if deduplicated, and will be further reduced to 5736 if combining multiple experimental data for one composition.\n    \n    heusler_magnetic: 1153 Heusler alloys with DFT-calculated magnetic and electronic properties. The 1153 alloys include 576 full, 449 half and 128 inverse Heusler alloys. The data are extracted and cleaned (including de-duplicating) from Citrine.\n    \n    jarvis_dft_2d: Various properties of 636 2D materials computed with the OptB88vdW and TBmBJ functionals taken from the JARVIS DFT database.\n    \n    jarvis_dft_3d: Various properties of 25,923 bulk materials computed with the OptB88vdW and TBmBJ functionals taken from the JARVIS DFT database.\n    \n    jarvis_ml_dft_training: Various properties of 24,759 bulk and 2D materials computed with the OptB88vdW and TBmBJ functionals taken from the JARVIS DFT database.\n    \n    m2ax: Elastic properties of 223 stable M2AX compounds from \"A comprehensive survey of M2AX phase elastic properties\" by Cover et al. Calculations are PAW PW91.\n    \n    matbench_dielectric: Matbench v0.1 test dataset for predicting refractive index from structure. Adapted from Materials Project database. Removed entries having a formation energy (or energy above the convex hull) more than 150meV and those having refractive indices less than 1 and those containing noble gases. Retrieved April 2, 2019. For benchmarking w/ nested cross validation, the order of the dataset must be identical to the retrieved data; refer to the Automatminer/Matbench publication for more details.\n    \n    matbench_expt_gap: Matbench v0.1 test dataset for predicting experimental band gap from composition alone. Retrieved from Zhuo et al. supplementary information. Deduplicated according to composition, removing compositions with reported band gaps spanning more than a 0.1eV range; remaining compositions were assigned values based on the closest experimental value to the mean experimental value for that composition among all reports. For benchmarking w/ nested cross validation, the order of the dataset must be identical to the retrieved data; refer to the Automatminer/Matbench publication for more details.\n    \n    matbench_expt_is_metal: Matbench v0.1 test dataset for classifying metallicity from composition alone. Retrieved from Zhuo et al. supplementary information. Deduplicated according to composition, ensuring no conflicting reports were entered for any compositions (i.e., no reported compositions were both metal and nonmetal). For benchmarking w/ nested cross validation, the order of the dataset must be identical to the retrieved data; refer to the Automatminer/Matbench publication for more details.\n    \n    matbench_glass: Matbench v0.1 test dataset for predicting full bulk metallic glass formation ability from chemical formula. Retrieved from \"Nonequilibrium Phase Diagrams of Ternary Amorphous Alloys,\u2019 a volume of the Landolt\u2013 B\u00f6rnstein collection. Deduplicated according to composition, ensuring no compositions were reported as both GFA and not GFA (i.e., all reports agreed on the classification designation). For benchmarking w/ nested cross validation, the order of the dataset must be identical to the retrieved data; refer to the Automatminer/Matbench publication for more details.\n    \n    matbench_jdft2d: Matbench v0.1 test dataset for predicting exfoliation energies from crystal structure (computed with the OptB88vdW and TBmBJ functionals). Adapted from the JARVIS DFT database. For benchmarking w/ nested cross validation, the order of the dataset must be identical to the retrieved data; refer to the Automatminer/Matbench publication for more details.\n    \n    matbench_log_gvrh: Matbench v0.1 test dataset for predicting DFT log10 VRH-average shear modulus from structure. Adapted from Materials Project database. Removed entries having a formation energy (or energy above the convex hull) more than 150meV and those having negative G_Voigt, G_Reuss, G_VRH, K_Voigt, K_Reuss, or K_VRH and those failing G_Reuss <= G_VRH <= G_Voigt or K_Reuss <= K_VRH <= K_Voigt and those containing noble gases. Retrieved April 2, 2019. For benchmarking w/ nested cross validation, the order of the dataset must be identical to the retrieved data; refer to the Automatminer/Matbench publication for more details.\n    \n    matbench_log_kvrh: Matbench v0.1 test dataset for predicting DFT log10 VRH-average bulk modulus from structure. Adapted from Materials Project database. Removed entries having a formation energy (or energy above the convex hull) more than 150meV and those having negative G_Voigt, G_Reuss, G_VRH, K_Voigt, K_Reuss, or K_VRH and those failing G_Reuss <= G_VRH <= G_Voigt or K_Reuss <= K_VRH <= K_Voigt and those containing noble gases. Retrieved April 2, 2019. For benchmarking w/ nested cross validation, the order of the dataset must be identical to the retrieved data; refer to the Automatminer/Matbench publication for more details.\n    \n    matbench_mp_e_form: Matbench v0.1 test dataset for predicting DFT formation energy from structure. Adapted from Materials Project database. Removed entries having formation energy more than 3.0eV and those containing noble gases. Retrieved April 2, 2019. For benchmarking w/ nested cross validation, the order of the dataset must be identical to the retrieved data; refer to the Automatminer/Matbench publication for more details.\n    \n    matbench_mp_gap: Matbench v0.1 test dataset for predicting DFT PBE band gap from structure. Adapted from Materials Project database. Removed entries having a formation energy (or energy above the convex hull) more than 150meV and those containing noble gases. Retrieved April 2, 2019. For benchmarking w/ nested cross validation, the order of the dataset must be identical to the retrieved data; refer to the Automatminer/Matbench publication for more details.\n    \n    matbench_mp_is_metal: Matbench v0.1 test dataset for predicting DFT metallicity from structure. Adapted from Materials Project database. Removed entries having a formation energy (or energy above the convex hull) more than 150meV and those containing noble gases. Retrieved April 2, 2019. For benchmarking w/ nested cross validation, the order of the dataset must be identical to the retrieved data; refer to the Automatminer/Matbench publication for more details.\n    \n    matbench_perovskites: Matbench v0.1 test dataset for predicting formation energy from crystal structure. Adapted from an original dataset generated by Castelli et al. For benchmarking w/ nested cross validation, the order of the dataset must be identical to the retrieved data; refer to the Automatminer/Matbench publication for more details.\n    \n    matbench_phonons: Matbench v0.1 test dataset for predicting vibration properties from crystal structure. Original data retrieved from Petretto et al. Original calculations done via ABINIT in the harmonic approximation based on density functional perturbation theory. Removed entries having a formation energy (or energy above the convex hull) more than 150meV. For benchmarking w/ nested cross validation, the order of the dataset must be identical to the retrieved data; refer to the Automatminer/Matbench publication for more details.\n    \n    matbench_steels: Matbench v0.1 test dataset for predicting steel yield strengths from chemical composition alone. Retrieved from Citrine informatics. Deduplicated. For benchmarking w/ nested cross validation, the order of the dataset must be identical to the retrieved data; refer to the Automatminer/Matbench publication for more details.\n    \n    mp_all_20181018: A complete copy of the Materials Project database as of 10/18/2018. mp_all files contain structure data for each material while mp_nostruct does not.\n    \n    mp_nostruct_20181018: A complete copy of the Materials Project database as of 10/18/2018. mp_all files contain structure data for each material while mp_nostruct does not.\n    \n    phonon_dielectric_mp: Phonon (lattice/atoms vibrations) and dielectric properties of 1296 compounds computed via ABINIT software package in the harmonic approximation based on density functional perturbation theory.\n    \n    piezoelectric_tensor: 941 structures with piezoelectric properties, calculated with DFT-PBE.\n    \n    steel_strength: 312 steels with experimental yield strength and ultimate tensile strength, extracted and cleaned (including de-duplicating) from Citrine.\n    \n    wolverton_oxides: 4,914 perovskite oxides containing composition data, lattice constants, and formation + vacancy formation energies. All perovskites are of the form ABO3. Adapted from a dataset presented by Emery and Wolverton.\n    \n    \n\n\nAs one last example, let's look at how to download datasets that are \nhosted on Figshare. To use the Figshare data import, we need to \nfirst install the python package to query Figshare datasets:\n\n\n```python\n!git clone https://github.com/cognoma/figshare.git\nimport sys\nsys.path.append('figshare')\n```\n\n    Cloning into 'figshare'...\n    remote: Enumerating objects: 18, done.\u001b[K\n    remote: Counting objects: 100% (18/18), done.\u001b[K\n    remote: Compressing objects: 100% (17/17), done.\u001b[K\n    remote: Total 53 (delta 6), reused 9 (delta 1), pack-reused 35\u001b[K\n    Unpacking objects: 100% (53/53), done.\n\n\nNote that you may need to restart your runtime (if on Colab) so that Colab can find the Figshare module\n\nNow we can download a dataset from Figshare. The diffusion dataset\nwe examined earlier is hosted on Figshare, with article ID number 7418492. \nLet's download it to our working environment:\n\n\n```python\nfrom mastml.datasets import FigshareDatasets\nFigshareDatasets().download_data(article_id='7418492')\n```\n\n    /usr/local/lib/python3.7/dist-packages/distributed/config.py:20: YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details.\n      defaults = yaml.load(f)\n\n\nWe can now see the new folder \"figshare_7418492\" has been downloaded,\nand within it is the data file \"All_Model_Data.xlsx\". This is the same\nfile we imported earlier from mastml/data when demonstrating the use\nof the LocalDatasets class. As with this file or other datasets downloaded\nfrom Figshare or other remote datasets, after downloading the data files\nyou can import them into MAST-ML using the LocalDatasets class as we \nlearned in this tutorial.\n\nYou've now completed your second MAST-ML tutorial notebook! Now that you're more familiar with working with datasets\nwithin MAST-ML, the next thing for us to do is look at feature engineering in more detail. \n\nThe next example in this notebook series is titled MASTML_Tutorial_3_FeatureEngineering.ipynb, and will guide you through the process\nof generating, preprocessing, and selecting features for a particular model and data split test.\n\n\n```python\n\n```\n", "meta": {"hexsha": "6dc762373898ed7c35caf37922991ddf4e35268d", "size": 898279, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/MASTML_Tutorial_2_DataImport.ipynb", "max_stars_repo_name": "Avery2/MAST-ML", "max_stars_repo_head_hexsha": "35ee87ae8ecfe26a2d5000244dfc0480c4d3b804", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 64, "max_stars_repo_stars_event_min_datetime": "2018-05-16T15:25:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T15:25:47.000Z", "max_issues_repo_path": "examples/MASTML_Tutorial_2_DataImport.ipynb", "max_issues_repo_name": "Avery2/MAST-ML", "max_issues_repo_head_hexsha": "35ee87ae8ecfe26a2d5000244dfc0480c4d3b804", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 119, "max_issues_repo_issues_event_min_datetime": "2018-04-18T13:41:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-15T07:02:08.000Z", "max_forks_repo_path": "examples/MASTML_Tutorial_2_DataImport.ipynb", "max_forks_repo_name": "Avery2/MAST-ML", "max_forks_repo_head_hexsha": "35ee87ae8ecfe26a2d5000244dfc0480c4d3b804", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2018-04-19T01:41:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-27T20:33:09.000Z", "avg_line_length": 193.5528980823, "max_line_length": 343824, "alphanum_fraction": 0.8663366282, "converted": true, "num_tokens": 38206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934934732271168, "lm_q2_score": 0.12252322052837361, "lm_q1q2_score": 0.029325852865342894}}
{"text": "# An Overview of Scramjet Physics & Modeling\n\n## 2021-06-14 \u00b7 N E Davis for [CEESD](https://ceesd.illinois.edu/)\n\n\n\n\n## Program\n\n1. Make sure you know how to submit your time worked (if applicable).\n2. Be in contact with your mentor.\n3. Put together a summer workplan this week (overall target + some intermediate targets) and let Carl and me know.\n4. COMMUNICATE COMMUNICATE COMMUNICATE\n\n\n## Objectives\n\n- Describe the qualitative behavior of a scramjet and distinguish it from other jet engines.\n- Identify quantities in governing equations and list consequences of MIRGE-Com's assumptions.\n- Distinguish experimental data collection from computer-based simulation data collection.\n\n\n## Jet Propulsion Systems\n\n1. Chemical rocket\n2. Turbojet engine\n3. Ramjet engine\n4. Scramjet engine\n\n\n\n## Newton's Third Law\n\n$$\n\\mathbf{F}_\\text{A}\n=\n-\\mathbf{F}_\\text{B}\n$$\n\nAction A equals reaction B; consider also conservation of momentum.\n\n## Chemical Rocket\n\n- Self-contained, not air-breathing\n\n\n\n\n## Turbojet\n\n- Air-breathing\n- Stators and rotors accelerate and compress\n\n\n\n\n## Ramjet\n\n- Air-breathing\n- No moving parts\n- High-speed (transonic or supersonic)\n- Requires external propulsion to get up to operating speed $>0.5 \\text{Ma}$\n\n\n\n\n## Scramjet\n\n- Air-breathing\n- No moving parts\n- High-speed (supersonic or hypersonic)\n- Requires external propulsion to get up to operating speed $> 1 \\text{Ma}$\n\n\n\n\n## Scramjet\n\n\n\n## Scramjet\n\nSteady-State Temperature Distribution:\n\n\n\n\nSupersonic inviscid flow exhibits sharp shockwaves starting at surfaces and propagating throughout the medium.  Streamlines can change discontinuously, making them relatively mathematically intractable.\n\n## Scramjet\n\n> In a supersonic flow, because the local flow velocity is greater than the speed of sound, disturbances created at some point in the flow cannot work their way upstream (in contrast to subsonic flow). This property is one of the most significant physical differences between subsonic and supersonic flows. It is the basic reason why shock waves occur in supersonic flows but do not occur in steady subsonic flow.  [[Anderson, \"Flight (Aerodynamics)\"](https://www.sciencedirect.com/science/article/pii/B0122274105009157)]\n\n## Scramjet\n\n### Warm-Up Phase\n\n\n\n\n## Scramjet\n\n### Steady-State Phase\n\n\n\n- Diamonds are \u201cradical farms\u201d and \u201cignition hotspots\u201d.\n- $x \\propto t$\n\n\n## Governing Equations\n\n### Navier-Stokes Equations\n\n$$\n\\frac{ \\partial \\left( \\rho \\varphi \\right) }{ \\partial t }\n+ \\nabla \\cdot \\left( \\rho \\vec{v} \\varphi \\right)\n= \\nabla \\cdot \\left( \\Gamma ^{\\varphi} \\nabla \\varphi \\right)\n+ Q ^{\\varphi} \\text{,}\n$$\n\n\n## Governing Equations\n\n### Navier-Stokes Equations\n\n$$\n\\int_{V_C} dV\\, \\nabla \\cdot \\left( \\rho \\vec{v} \\varphi \\right)\n= \\int_{V_C} dV\\, \\nabla \\cdot \\left( \\Gamma ^{\\varphi} \\nabla \\varphi \\right)\n+ \\int_{V_C} dV\\, Q ^{\\varphi} \\text{.}\n$$\n\n\n## Governing Equations\n\n### Navier-Stokes Equations\n\n$$\n\\oint_{\\partial V_C} d\\vec{S} \\cdot \\nabla \\cdot \\left( \\rho \\vec{v} \\varphi \\right)\n= \\oint_{\\partial V_C} d\\vec{S} \\cdot \\left( \\Gamma ^{\\varphi} \\nabla \\varphi \\right)\n+ \\int_{V_C} dV\\, Q ^{\\varphi} \\text{.}\n$$\n\n## Governing Equations\n\n## Momentum & Mass Conservation\n\n$$\n\\begin{align}\n  \\rho \\left(\\frac{\\partial u_x}{\\partial t} + u_x \\frac{\\partial u_x}{\\partial x} + u_y \\frac{\\partial u_x}{\\partial y} + u_z \\frac{\\partial u_x}{\\partial z}\\right)\n    =& -\\frac{\\partial p}{\\partial x} + \\mu \\left(\\frac{\\partial^2 u_x}{\\partial x^2} + \\frac{\\partial^2 u_x}{\\partial y^2} + \\frac{\\partial^2 u_x}{\\partial z^2}\\right) \\\\\n    & - \\mu \\frac{\\partial}{\\partial x} \\left( \\frac{\\partial u_x}{\\partial x} + \\frac{\\partial u_y}{\\partial y} + \\frac{\\partial u_z}{\\partial z} \\right) + \\rho g_x \\\\\n  \\rho \\left(\\frac{\\partial u_y}{\\partial t} + u_x \\frac{\\partial u_y}{\\partial x} + u_y \\frac{\\partial u_y}{\\partial y}+ u_z \\frac{\\partial u_y}{\\partial z}\\right)\n    =& -\\frac{\\partial p}{\\partial y} + \\mu \\left(\\frac{\\partial^2 u_y}{\\partial x^2} + \\frac{\\partial^2 u_y}{\\partial y^2} + \\frac{\\partial^2 u_y}{\\partial z^2}\\right) \\\\\n    & - \\mu \\frac{\\partial}{\\partial y} \\left( \\frac{\\partial u_x}{\\partial x} + \\frac{\\partial u_y}{\\partial y} + \\frac{\\partial u_z}{\\partial z} \\right) + \\rho g_y \\\\\n  \\rho \\left(\\frac{\\partial u_z}{\\partial t} + u_x \\frac{\\partial u_z}{\\partial x} + u_y \\frac{\\partial u_z}{\\partial y}+ u_z \\frac{\\partial u_z}{\\partial z}\\right)\n    =& -\\frac{\\partial p}{\\partial z} + \\mu \\left(\\frac{\\partial^2 u_z}{\\partial x^2} + \\frac{\\partial^2 u_z}{\\partial y^2} + \\frac{\\partial^2 u_z}{\\partial z^2}\\right) \\\\\n    & - \\mu \\frac{\\partial}{\\partial z} \\left( \\frac{\\partial u_x}{\\partial x} + \\frac{\\partial u_y}{\\partial y} + \\frac{\\partial u_z}{\\partial z} \\right) + \\rho g_z.\n\\end{align}\n$$\n\n$$\n{\\partial \\rho \\over \\partial t} + {\\partial (\\rho u_x ) \\over \\partial x} + {\\partial (\\rho u_y) \\over \\partial y} + {\\partial (\\rho u_z) \\over \\partial z} = 0.\n$$\n\n## Governing Equations\n\n## Momentum & Mass Conservation\n\n$$\n\\begin{align}\n  \\rho \\left(\\frac{\\partial u_x}{\\partial t} + u_x \\frac{\\partial u_x}{\\partial x} + u_y \\frac{\\partial u_x}{\\partial y} + u_z \\frac{\\partial u_x}{\\partial z}\\right)\n    =& -\\frac{\\partial p}{\\partial x} + \\mu \\left(\\frac{\\partial^2 u_x}{\\partial x^2} + \\frac{\\partial^2 u_x}{\\partial y^2} + \\frac{\\partial^2 u_x}{\\partial z^2}\\right) \\\\\n    & - \\mu \\frac{\\partial}{\\partial x} \\left( \\frac{\\partial u_x}{\\partial x} + \\frac{\\partial u_y}{\\partial y} + \\frac{\\partial u_z}{\\partial z} \\right) + \\rho g_x \\\\\n\\end{align}\n$$\n\n$$\n{\\partial \\rho \\over \\partial t} + {\\partial (\\rho u_x ) \\over \\partial x} + {\\partial (\\rho u_y) \\over \\partial y} + {\\partial (\\rho u_z) \\over \\partial z} = 0.\n$$\n\n- Which quantities appear in the Navier\u2013Stokes equations?\n- Which quantities in the Navier\u2013Stokes equations are conservative?\n- Compare equations to the [canonical MIRGE-Com formulation](https://mirgecom.readthedocs.io/en/latest/fluid.html).\n\n\n## Other Relationships\n\n**Non-dimensional thrust equation**:\n\n$$\n\\frac{T}{\\dot{m}_o a_o} = M_o\\left(\\frac{U_e}{U_o}-1\\right)\n$$\n\n**Ratio of inlet to outlet velocity**:\n\n$$\n\\frac{U_e}{U_o} = \\frac{M_e}{M_o} \\sqrt{\\frac{T_e}{T_o}}\n$$\n\n**Ramjet specific thrust** (across burner 3\u21924):\n\n$$\n\\frac{T}{\\dot{m}_o a_o} = M_o\\left(\\sqrt{\\frac{T_{t4}}{T_{t3}}}-1\\right)\n$$\n\n**Energy balance across burner**:\n\n$$\n\\dot{m}_f h = \\dot{m}_o c_p \\left(T_{t4}-T_{t3}\\right)\n$$\n\n\n## Other Relationships\n\n**Specific impulse**:\n\n$$\nI_\\text{sp} = \\frac{T}{\\dot{m}_f g}\n$$\n\n**Thrust specific fuel consumption**:\n\n$$\n\\text{TSFC} = \\frac{\\dot{m}_f}{T}\n$$\n\n**Overall efficiency**:\n\n$$\n\\eta = \\frac{T U_o}{\\dot{m}_f h}\n$$\n\n## Experimental Data\n\nScramjet observational data are obtained two ways:  from wind tunnel experiments and from actual flights.\n\n\n\nData which can be obtained experimentally include:\n\n- Temperature and pressure distributions along various lines\n- Thrust and performance under various conditions\n- Fuel composition at sample points.\n\n\n## Challenges\n\n> While scramjets are conceptually simple, actual implementation is limited by extreme technical challenges. Hypersonic flight within the atmosphere generates immense drag, and temperatures found on the aircraft and within the engine can be much greater than that of the surrounding air. Maintaining combustion in the supersonic flow presents additional challenges, as the fuel must be injected, mixed, ignited, and burned within milliseconds. Fuel mixing, along with the configuration and positioning of the injectors and the boundary conditions, play a key role in combustion efficiency. [[Gerdroodbary, _Scramjets: Fuel Mixing and Injection Systems_](https://www.sciencedirect.com/book/9780128211380/scramjets)]\n\nPractical challenges to producing and operating scramjets include:\n\n- autoignition of the internal flow (\"like lighting a match in a hurricane\")\n- fuel\u2013oxidizer mixing\n- developing heat-dissipative refractory materials\n- obtaining experimental data\n  - acquiring high-grade internal flow state\n  - visualizing phenomena such as shock waves\n\n\n## Exercises\n\nComplete these using a graphing calculator, Python, MATLAB, or Excel.\n\n1.  Plot $\\frac{T}{\\dot{m_a}}$ and $\\frac{T}{\\dot{m_a}a_0}$ v. Mach number $M$ from 1 to 5.\n2.  Plot $\\text{TSFC}$ v. Mach number $M$ from 1 to 5.\n3.  Plot $I_\\text{sp}$ v. Mach number $M$ from 1 to 5.\n4.  Plot thermal, propulsive, and overall efficiency v. Mach number $M$ from 1 to 5.\n\ngiven data:\n\n- $Q_R = 48,000 \\,\\text{kJ}/\\text{kg}$ for _n_-decane\n- $Q_R = 55,500 \\,\\text{kJ}/\\text{kg}$ for methane\n- $Q_R = 141,800 \\,\\text{kJ}/\\text{kg}$ for hydrogen\n- maximum combustion $T = 2000 \\,\\text{K}$\n\n(Based on an exercise by [D R Kirk, \"Hypersonic Airbreathing Engines\"](https://slideplayer.com/slide/14223195/).)\n", "meta": {"hexsha": "ad8805affa88f35966998b57ae0f0e6afefe64d8", "size": 15625, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "0-physics.ipynb", "max_stars_repo_name": "illinois-ceesd/summer-reu-2022", "max_stars_repo_head_hexsha": "a8cfdc83d9b5e1408ddf104fda9d95b8f0ac13d5", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-24T19:06:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T19:06:20.000Z", "max_issues_repo_path": "0-physics.ipynb", "max_issues_repo_name": "illinois-ceesd/summer-reu-2022", "max_issues_repo_head_hexsha": "a8cfdc83d9b5e1408ddf104fda9d95b8f0ac13d5", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-06-08T20:32:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-30T17:01:47.000Z", "max_forks_repo_path": "0-physics.ipynb", "max_forks_repo_name": "illinois-ceesd/summer-reu-2022", "max_forks_repo_head_hexsha": "a8cfdc83d9b5e1408ddf104fda9d95b8f0ac13d5", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8794466403, "max_line_length": 723, "alphanum_fraction": 0.54496, "converted": true, "num_tokens": 2700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2598256379609837, "lm_q2_score": 0.11279540926528922, "lm_q1q2_score": 0.02930713917142402}}
{"text": "<a href=\"https://colab.research.google.com/github/mc7836/Python_Projects/blob/main/AustinOption.ipynb\" target=\"_parent\"></a>\n\n# **Group 9 Final Project - Where Should I Open My Restaurant?**\n\n##### Amy Park, Cesar Espinoza, Danny Gallegos, and Margarita Coronel\n\n### **Background**\n### In real estate, the three things that matter the most are location, location, and location. So in a bustling city like Austin, TX, how would a new restaurant choose its location? We have several business criteria a location should meet - saturation of the cuisine in a neighborhood among others - and offer a perspective on the competitive landscape for a new restaurant. For our use case, we will be opening a pizzeria in Austin, TX. \n#### Note:\n*   This analysis focuses on the competitive landscape only.  Factors such as real estate prices of locations or demographic data are not in scope\n\n### **Executive Summary**\n### This analysis was conducted using Yelp Academic Data in five steps (import data, clean data, explore data, measure competitive landscape of a given area, and result/conclusion). \n### We import and clean the data to focus on restaurants in  Austin, Texas, then present our initial findings of the data in various visualizations such as histograms and geographical maps. We then focus on three sample areas to analyze the competitive landscape in theses areas, and based on our business critieria for measuring competitiveness offer our perspective on which is the most optimal of the sample group. In closing, we address further steps that will help make this analysis more robust. \n\n### **1. Importing the Data**\n\n\n#### **1.1 Import Data** - we used the publicly available Yelp academic data to import data via Google Drive, clean the dataset, and conduct this analysis\n\n\n```python\nimport pandas as pd\nimport io\n```\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```python\n# Since the date is in json format we import the json library\nimport json\n!\nf = open('/content/drive/MyDrive/data/yelp_academic_dataset_business.json',)\nf\n```\n\n\n\n\n    <_io.TextIOWrapper name='/content/drive/MyDrive/data/yelp_academic_dataset_business.json' mode='r' encoding='UTF-8'>\n\n\n\n\n```python\n# Uploading JSON data into data list\ndata1 = []\nfor line in open('/content/drive/MyDrive/data/yelp_academic_dataset_business.json', 'r'):\n    data1.append(json.loads(line))\ndata1[0]\n```\n\n\n\n\n    {'address': '921 Pearl St',\n     'attributes': {'Alcohol': \"'beer_and_wine'\",\n      'Ambience': \"{'touristy': False, 'hipster': False, 'romantic': False, 'divey': False, 'intimate': False, 'trendy': False, 'upscale': False, 'classy': False, 'casual': True}\",\n      'BikeParking': 'True',\n      'BusinessAcceptsBitcoin': 'False',\n      'BusinessAcceptsCreditCards': 'True',\n      'BusinessParking': \"{'garage': False, 'street': True, 'validated': False, 'lot': False, 'valet': False}\",\n      'Caters': 'True',\n      'DogsAllowed': 'False',\n      'GoodForMeal': \"{'dessert': False, 'latenight': False, 'lunch': False, 'dinner': False, 'brunch': False, 'breakfast': False}\",\n      'HappyHour': 'True',\n      'HasTV': 'True',\n      'NoiseLevel': \"u'average'\",\n      'OutdoorSeating': 'True',\n      'RestaurantsAttire': \"'casual'\",\n      'RestaurantsDelivery': 'None',\n      'RestaurantsGoodForGroups': 'True',\n      'RestaurantsPriceRange2': '2',\n      'RestaurantsReservations': 'False',\n      'RestaurantsTableService': 'True',\n      'RestaurantsTakeOut': 'True',\n      'WheelchairAccessible': 'True',\n      'WiFi': \"u'free'\"},\n     'business_id': '6iYb2HFDywm3zjuRg0shjw',\n     'categories': 'Gastropubs, Food, Beer Gardens, Restaurants, Bars, American (Traditional), Beer Bar, Nightlife, Breweries',\n     'city': 'Boulder',\n     'hours': {'Friday': '11:0-23:0',\n      'Monday': '11:0-23:0',\n      'Saturday': '11:0-23:0',\n      'Sunday': '11:0-23:0',\n      'Thursday': '11:0-23:0',\n      'Tuesday': '11:0-23:0',\n      'Wednesday': '11:0-23:0'},\n     'is_open': 1,\n     'latitude': 40.0175444,\n     'longitude': -105.2833481,\n     'name': 'Oskar Blues Taproom',\n     'postal_code': '80302',\n     'review_count': 86,\n     'stars': 4.0,\n     'state': 'CO'}\n\n\n\n#### **1.2 Exploring the Data and Creating a Dataframe**\n#### We then explore the data to see what kind of attributes the dataset has and the format of the data. We then proceed to create a dataframe to store the data.\n\n\n\n```python\n# Exploring the data set's main keys\ndict1 = data1[1]\ndict1.keys()\n```\n\n\n\n\n    dict_keys(['business_id', 'name', 'address', 'city', 'state', 'postal_code', 'latitude', 'longitude', 'stars', 'review_count', 'is_open', 'attributes', 'categories', 'hours'])\n\n\n\n\n```python\n# Now that we know the dictionary keys we proceed to create a data frame with Pandas\ndf = pd.DataFrame(data1, columns=['business_id', 'name', 'address', 'city', 'state', 'postal_code', 'latitude', 'longitude', 'stars', 'review_count', 'is_open', 'attributes', 'categories', 'hours'])\ndf.head(1)\n```\n\n\n\n\n\n  <div id=\"df-4fe10a91-c3ab-4c76-889b-f508bef60391\">\n    <div class=\"colab-df-container\">\n      <div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>business_id</th>\n      <th>name</th>\n      <th>address</th>\n      <th>city</th>\n      <th>state</th>\n      <th>postal_code</th>\n      <th>latitude</th>\n      <th>longitude</th>\n      <th>stars</th>\n      <th>review_count</th>\n      <th>is_open</th>\n      <th>attributes</th>\n      <th>categories</th>\n      <th>hours</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>6iYb2HFDywm3zjuRg0shjw</td>\n      <td>Oskar Blues Taproom</td>\n      <td>921 Pearl St</td>\n      <td>Boulder</td>\n      <td>CO</td>\n      <td>80302</td>\n      <td>40.017544</td>\n      <td>-105.283348</td>\n      <td>4.0</td>\n      <td>86</td>\n      <td>1</td>\n      <td>{'RestaurantsTableService': 'True', 'WiFi': 'u...</td>\n      <td>Gastropubs, Food, Beer Gardens, Restaurants, B...</td>\n      <td>{'Monday': '11:0-23:0', 'Tuesday': '11:0-23:0'...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n      <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-4fe10a91-c3ab-4c76-889b-f508bef60391')\"\n              title=\"Convert this dataframe to an interactive table.\"\n              style=\"display:none;\">\n\n  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n       width=\"24px\">\n    <path d=\"M0 0h24v24H0V0z\" fill=\"none\"/>\n    <path d=\"M18.56 5.44l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94zm-11 1L8.5 8.5l.94-2.06 2.06-.94-2.06-.94L8.5 2.5l-.94 2.06-2.06.94zm10 10l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94z\"/><path d=\"M17.41 7.96l-1.37-1.37c-.4-.4-.92-.59-1.43-.59-.52 0-1.04.2-1.43.59L10.3 9.45l-7.72 7.72c-.78.78-.78 2.05 0 2.83L4 21.41c.39.39.9.59 1.41.59.51 0 1.02-.2 1.41-.59l7.78-7.78 2.81-2.81c.8-.78.8-2.07 0-2.86zM5.41 20L4 18.59l7.72-7.72 1.47 1.35L5.41 20z\"/>\n  </svg>\n      </button>\n\n  <style>\n    .colab-df-container {\n      display:flex;\n      flex-wrap:wrap;\n      gap: 12px;\n    }\n\n    .colab-df-convert {\n      background-color: #E8F0FE;\n      border: none;\n      border-radius: 50%;\n      cursor: pointer;\n      display: none;\n      fill: #1967D2;\n      height: 32px;\n      padding: 0 0 0 0;\n      width: 32px;\n    }\n\n    .colab-df-convert:hover {\n      background-color: #E2EBFA;\n      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n      fill: #174EA6;\n    }\n\n    [theme=dark] .colab-df-convert {\n      background-color: #3B4455;\n      fill: #D2E3FC;\n    }\n\n    [theme=dark] .colab-df-convert:hover {\n      background-color: #434B5C;\n      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n      fill: #FFFFFF;\n    }\n  </style>\n\n      \n    </div>\n  </div>\n\n\n\n\n\n```python\ndf.attributes[0]\n```\n\n\n\n\n    {'Alcohol': \"'beer_and_wine'\",\n     'Ambience': \"{'touristy': False, 'hipster': False, 'romantic': False, 'divey': False, 'intimate': False, 'trendy': False, 'upscale': False, 'classy': False, 'casual': True}\",\n     'BikeParking': 'True',\n     'BusinessAcceptsBitcoin': 'False',\n     'BusinessAcceptsCreditCards': 'True',\n     'BusinessParking': \"{'garage': False, 'street': True, 'validated': False, 'lot': False, 'valet': False}\",\n     'Caters': 'True',\n     'DogsAllowed': 'False',\n     'GoodForMeal': \"{'dessert': False, 'latenight': False, 'lunch': False, 'dinner': False, 'brunch': False, 'breakfast': False}\",\n     'HappyHour': 'True',\n     'HasTV': 'True',\n     'NoiseLevel': \"u'average'\",\n     'OutdoorSeating': 'True',\n     'RestaurantsAttire': \"'casual'\",\n     'RestaurantsDelivery': 'None',\n     'RestaurantsGoodForGroups': 'True',\n     'RestaurantsPriceRange2': '2',\n     'RestaurantsReservations': 'False',\n     'RestaurantsTableService': 'True',\n     'RestaurantsTakeOut': 'True',\n     'WheelchairAccessible': 'True',\n     'WiFi': \"u'free'\"}\n\n\n\n\n```python\ncat2 = df.categories[0]\ncat2\n```\n\n\n\n\n    'Gastropubs, Food, Beer Gardens, Restaurants, Bars, American (Traditional), Beer Bar, Nightlife, Breweries'\n\n\n\n### **2. Cleaning the Data**\n\n\n#### **2.1 Filtering only for Austin, TX restaurants**\n\n\n```python\n#Filtering to open TX businesses and Austin within \ntx_business =  df[df['state']=='TX']\ntx_business_open = tx_business[tx_business['is_open']==1]\naustin_business = tx_business_open[tx_business_open['city']=='Austin']\naustin_business.head(5)\n```\n\n\n\n\n\n  <div id=\"df-629c95e3-27c5-430f-bb47-03ad82c2217d\">\n    <div class=\"colab-df-container\">\n      <div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>business_id</th>\n      <th>name</th>\n      <th>address</th>\n      <th>city</th>\n      <th>state</th>\n      <th>postal_code</th>\n      <th>latitude</th>\n      <th>longitude</th>\n      <th>stars</th>\n      <th>review_count</th>\n      <th>is_open</th>\n      <th>attributes</th>\n      <th>categories</th>\n      <th>hours</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>8</th>\n      <td>N3_Gs3DnX4k9SgpwJxdEfw</td>\n      <td>Lane Wells Jewelry Repair</td>\n      <td>7801 N Lamar Blvd, Ste A140</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78752</td>\n      <td>30.346169</td>\n      <td>-97.711458</td>\n      <td>5.0</td>\n      <td>30</td>\n      <td>1</td>\n      <td>{'RestaurantsPriceRange2': '1', 'ByAppointment...</td>\n      <td>Shopping, Jewelry Repair, Appraisal Services, ...</td>\n      <td>{'Monday': '12:15-17:0', 'Tuesday': '12:15-17:...</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>nTIhpR7MhsALPwg_Hh14EA</td>\n      <td>DoubleTree by Hilton Hotel Austin</td>\n      <td>6505 N Interstate 35</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78752</td>\n      <td>30.326377</td>\n      <td>-97.704543</td>\n      <td>3.0</td>\n      <td>139</td>\n      <td>1</td>\n      <td>{'WiFi': 'u'free'', 'RestaurantsPriceRange2': ...</td>\n      <td>Hotels, Hotels &amp; Travel, Event Planning &amp; Serv...</td>\n      <td>{'Monday': '0:0-0:0', 'Tuesday': '0:0-0:0', 'W...</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>8XyEpVdAO0o6iVkVxkWosQ</td>\n      <td>PS Property Management Company</td>\n      <td>2506 S Lamar Blvd, Ste 2</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78704</td>\n      <td>30.246465</td>\n      <td>-97.778738</td>\n      <td>4.5</td>\n      <td>9</td>\n      <td>1</td>\n      <td>{'BusinessAcceptsCreditCards': 'True'}</td>\n      <td>Home Services, Real Estate, Property Management</td>\n      <td>{'Monday': '9:0-17:0', 'Tuesday': '9:0-17:0', ...</td>\n    </tr>\n    <tr>\n      <th>37</th>\n      <td>NVfOn7TdnHbaGH97CVB_Qg</td>\n      <td>McKinley Chiropractic</td>\n      <td>5625 Eiger Rd, Ste 160</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78735</td>\n      <td>30.244902</td>\n      <td>-97.857409</td>\n      <td>5.0</td>\n      <td>5</td>\n      <td>1</td>\n      <td>{'BusinessAcceptsCreditCards': 'True', 'Accept...</td>\n      <td>Chiropractors, Health &amp; Medical</td>\n      <td>{'Monday': '9:0-17:45', 'Tuesday': '12:0-17:45...</td>\n    </tr>\n    <tr>\n      <th>39</th>\n      <td>s8eTWEtW5WcnL2kUxrOVmw</td>\n      <td>Austin Regional Clinic: ARC Quarry Lake</td>\n      <td>4515 Seton Center Pkwy, Ste 220</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78759</td>\n      <td>30.401657</td>\n      <td>-97.742943</td>\n      <td>3.5</td>\n      <td>48</td>\n      <td>1</td>\n      <td>{'ByAppointmentOnly': 'True', 'AcceptsInsuranc...</td>\n      <td>Diagnostic Services, Doctors, Internal Medicin...</td>\n      <td>{'Monday': '8:0-17:0', 'Tuesday': '8:0-17:0', ...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n      <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-629c95e3-27c5-430f-bb47-03ad82c2217d')\"\n              title=\"Convert this dataframe to an interactive table.\"\n              style=\"display:none;\">\n\n  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n       width=\"24px\">\n    <path d=\"M0 0h24v24H0V0z\" fill=\"none\"/>\n    <path d=\"M18.56 5.44l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94zm-11 1L8.5 8.5l.94-2.06 2.06-.94-2.06-.94L8.5 2.5l-.94 2.06-2.06.94zm10 10l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94z\"/><path d=\"M17.41 7.96l-1.37-1.37c-.4-.4-.92-.59-1.43-.59-.52 0-1.04.2-1.43.59L10.3 9.45l-7.72 7.72c-.78.78-.78 2.05 0 2.83L4 21.41c.39.39.9.59 1.41.59.51 0 1.02-.2 1.41-.59l7.78-7.78 2.81-2.81c.8-.78.8-2.07 0-2.86zM5.41 20L4 18.59l7.72-7.72 1.47 1.35L5.41 20z\"/>\n  </svg>\n      </button>\n\n  <style>\n    .colab-df-container {\n      display:flex;\n      flex-wrap:wrap;\n      gap: 12px;\n    }\n\n    .colab-df-convert {\n      background-color: #E8F0FE;\n      border: none;\n      border-radius: 50%;\n      cursor: pointer;\n      display: none;\n      fill: #1967D2;\n      height: 32px;\n      padding: 0 0 0 0;\n      width: 32px;\n    }\n\n    .colab-df-convert:hover {\n      background-color: #E2EBFA;\n      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n      fill: #174EA6;\n    }\n\n    [theme=dark] .colab-df-convert {\n      background-color: #3B4455;\n      fill: #D2E3FC;\n    }\n\n    [theme=dark] .colab-df-convert:hover {\n      background-color: #434B5C;\n      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n      fill: #FFFFFF;\n    }\n  </style>\n\n      \n    </div>\n  </div>\n\n\n\n\n\n```python\n# Filtering to Austin-only Restaurants\naustin_restaurants = austin_business[austin_business['categories'].str.contains(\"Restaurants\", na=False)]\naustin_restaurants.head(5)\n```\n\n\n\n\n\n  <div id=\"df-336f5ed7-bbd6-41c7-836f-3b047e564b08\">\n    <div class=\"colab-df-container\">\n      <div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>business_id</th>\n      <th>name</th>\n      <th>address</th>\n      <th>city</th>\n      <th>state</th>\n      <th>postal_code</th>\n      <th>latitude</th>\n      <th>longitude</th>\n      <th>stars</th>\n      <th>review_count</th>\n      <th>is_open</th>\n      <th>attributes</th>\n      <th>categories</th>\n      <th>hours</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>41</th>\n      <td>NRPemqVb4qpWFF0Avq_6OQ</td>\n      <td>Eurasia Sushi Bar &amp; Seafood</td>\n      <td>7101 W Hwy 71, Ste C-13</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78735</td>\n      <td>30.234533</td>\n      <td>-97.877262</td>\n      <td>4.5</td>\n      <td>395</td>\n      <td>1</td>\n      <td>{'Ambience': '{'touristy': False, 'hipster': F...</td>\n      <td>Bars, Nightlife, Cocktail Bars, Seafood, Resta...</td>\n      <td>{'Monday': '0:0-0:0', 'Tuesday': '11:0-22:0', ...</td>\n    </tr>\n    <tr>\n      <th>61</th>\n      <td>bRsDZ44CD3uhGnRY3NeQhQ</td>\n      <td>Wendy's</td>\n      <td>6247 Mcneil Drive</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78729</td>\n      <td>30.441875</td>\n      <td>-97.746581</td>\n      <td>2.0</td>\n      <td>46</td>\n      <td>1</td>\n      <td>{'RestaurantsPriceRange2': '1', 'OutdoorSeatin...</td>\n      <td>Fast Food, Restaurants, Burgers</td>\n      <td>{'Monday': '6:30-1:0', 'Tuesday': '6:30-1:0', ...</td>\n    </tr>\n    <tr>\n      <th>199</th>\n      <td>Pk4ZwXwUU50BDn5gqw_rKg</td>\n      <td>Johnny Carino's</td>\n      <td>9500 S IH-35 Service Rd</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78748</td>\n      <td>30.162081</td>\n      <td>-97.789132</td>\n      <td>3.0</td>\n      <td>136</td>\n      <td>1</td>\n      <td>{'RestaurantsGoodForGroups': 'True', 'Business...</td>\n      <td>Italian, Salad, Pizza, Nightlife, Restaurants,...</td>\n      <td>{'Monday': '11:0-21:30', 'Tuesday': '11:0-21:3...</td>\n    </tr>\n    <tr>\n      <th>253</th>\n      <td>Ieelu69Y23nbjKG3OGfwnw</td>\n      <td>McDonald's</td>\n      <td>5017 Hwy 290 W</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78735</td>\n      <td>30.232133</td>\n      <td>-97.823183</td>\n      <td>1.5</td>\n      <td>9</td>\n      <td>1</td>\n      <td>{'RestaurantsTakeOut': 'True', 'RestaurantsRes...</td>\n      <td>Restaurants, Coffee &amp; Tea, Food, Burgers, Fast...</td>\n      <td>{'Monday': '7:0-22:30', 'Tuesday': '7:0-22:30'...</td>\n    </tr>\n    <tr>\n      <th>258</th>\n      <td>IFB2K3BEZ2L_Mv5AbUD26Q</td>\n      <td>Chispas</td>\n      <td>214 W 4th St</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78701</td>\n      <td>30.266996</td>\n      <td>-97.745362</td>\n      <td>3.5</td>\n      <td>119</td>\n      <td>1</td>\n      <td>{'RestaurantsTakeOut': 'True', 'OutdoorSeating...</td>\n      <td>Tex-Mex, Mexican, Tacos, Restaurants</td>\n      <td>{'Monday': '11:0-22:0', 'Tuesday': '11:0-22:0'...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n      <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-336f5ed7-bbd6-41c7-836f-3b047e564b08')\"\n              title=\"Convert this dataframe to an interactive table.\"\n              style=\"display:none;\">\n\n  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n       width=\"24px\">\n    <path d=\"M0 0h24v24H0V0z\" fill=\"none\"/>\n    <path d=\"M18.56 5.44l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94zm-11 1L8.5 8.5l.94-2.06 2.06-.94-2.06-.94L8.5 2.5l-.94 2.06-2.06.94zm10 10l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94z\"/><path d=\"M17.41 7.96l-1.37-1.37c-.4-.4-.92-.59-1.43-.59-.52 0-1.04.2-1.43.59L10.3 9.45l-7.72 7.72c-.78.78-.78 2.05 0 2.83L4 21.41c.39.39.9.59 1.41.59.51 0 1.02-.2 1.41-.59l7.78-7.78 2.81-2.81c.8-.78.8-2.07 0-2.86zM5.41 20L4 18.59l7.72-7.72 1.47 1.35L5.41 20z\"/>\n  </svg>\n      </button>\n\n  <style>\n    .colab-df-container {\n      display:flex;\n      flex-wrap:wrap;\n      gap: 12px;\n    }\n\n    .colab-df-convert {\n      background-color: #E8F0FE;\n      border: none;\n      border-radius: 50%;\n      cursor: pointer;\n      display: none;\n      fill: #1967D2;\n      height: 32px;\n      padding: 0 0 0 0;\n      width: 32px;\n    }\n\n    .colab-df-convert:hover {\n      background-color: #E2EBFA;\n      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n      fill: #174EA6;\n    }\n\n    [theme=dark] .colab-df-convert {\n      background-color: #3B4455;\n      fill: #D2E3FC;\n    }\n\n    [theme=dark] .colab-df-convert:hover {\n      background-color: #434B5C;\n      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n      fill: #FFFFFF;\n    }\n  </style>\n\n      \n    </div>\n  </div>\n\n\n\n\n\n```python\n# Restricting data to Pizza joints\npizza_joint = austin_restaurants[austin_restaurants['categories'].str.contains(\"Pizza|Pizzeria|pizza|pizzeria\", na=False)]\npizza_joint.head(5)\n```\n\n\n\n\n\n  <div id=\"df-26a3fc66-cc43-46fe-8d28-ddad05643c7f\">\n    <div class=\"colab-df-container\">\n      <div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>business_id</th>\n      <th>name</th>\n      <th>address</th>\n      <th>city</th>\n      <th>state</th>\n      <th>postal_code</th>\n      <th>latitude</th>\n      <th>longitude</th>\n      <th>stars</th>\n      <th>review_count</th>\n      <th>is_open</th>\n      <th>attributes</th>\n      <th>categories</th>\n      <th>hours</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>199</th>\n      <td>Pk4ZwXwUU50BDn5gqw_rKg</td>\n      <td>Johnny Carino's</td>\n      <td>9500 S IH-35 Service Rd</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78748</td>\n      <td>30.162081</td>\n      <td>-97.789132</td>\n      <td>3.0</td>\n      <td>136</td>\n      <td>1</td>\n      <td>{'RestaurantsGoodForGroups': 'True', 'Business...</td>\n      <td>Italian, Salad, Pizza, Nightlife, Restaurants,...</td>\n      <td>{'Monday': '11:0-21:30', 'Tuesday': '11:0-21:3...</td>\n    </tr>\n    <tr>\n      <th>267</th>\n      <td>fBvQQUk1-V9IUA8PbuYFWg</td>\n      <td>Newk's Eatery</td>\n      <td>408 Congress Ave</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78701</td>\n      <td>30.266639</td>\n      <td>-97.743659</td>\n      <td>3.5</td>\n      <td>43</td>\n      <td>1</td>\n      <td>{'HasTV': 'True', 'BusinessParking': '{'garage...</td>\n      <td>Pizza, Restaurants, American (Traditional), Am...</td>\n      <td>{'Monday': '0:0-0:0', 'Tuesday': '10:30-18:0',...</td>\n    </tr>\n    <tr>\n      <th>1354</th>\n      <td>DSEsFWzM3UCq54E2X0P9Zg</td>\n      <td>Mangieri's Pizza Cafe</td>\n      <td>5900 W Slaughter Ln</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78749</td>\n      <td>30.201336</td>\n      <td>-97.878995</td>\n      <td>4.0</td>\n      <td>237</td>\n      <td>1</td>\n      <td>{'RestaurantsTakeOut': 'True', 'Alcohol': 'u'f...</td>\n      <td>Restaurants, Pizza, Italian</td>\n      <td>{'Monday': '11:0-21:0', 'Tuesday': '11:0-21:0'...</td>\n    </tr>\n    <tr>\n      <th>1857</th>\n      <td>p99DZXmdF7smudK9FnlC9A</td>\n      <td>Spartan Pizza</td>\n      <td>1007 E 6th St</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78702</td>\n      <td>30.264940</td>\n      <td>-97.732093</td>\n      <td>4.0</td>\n      <td>264</td>\n      <td>1</td>\n      <td>{'BusinessAcceptsCreditCards': 'True', 'Restau...</td>\n      <td>Food Trucks, Pizza, Salad, Sandwiches, Food, E...</td>\n      <td>{'Monday': '0:0-0:0', 'Tuesday': '11:0-22:0', ...</td>\n    </tr>\n    <tr>\n      <th>2886</th>\n      <td>zIrE7JvF0xVprDjbnL4PDQ</td>\n      <td>J Clips</td>\n      <td>900 E Braker Ln</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78753</td>\n      <td>30.376738</td>\n      <td>-97.673122</td>\n      <td>3.0</td>\n      <td>15</td>\n      <td>1</td>\n      <td>{'BusinessAcceptsCreditCards': 'False', 'ByApp...</td>\n      <td>Beauty &amp; Spas, Barbers, Pizza, Restaurants</td>\n      <td>{'Monday': '9:0-20:0', 'Tuesday': '9:0-20:0', ...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n      <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-26a3fc66-cc43-46fe-8d28-ddad05643c7f')\"\n              title=\"Convert this dataframe to an interactive table.\"\n              style=\"display:none;\">\n\n  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n       width=\"24px\">\n    <path d=\"M0 0h24v24H0V0z\" fill=\"none\"/>\n    <path d=\"M18.56 5.44l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94zm-11 1L8.5 8.5l.94-2.06 2.06-.94-2.06-.94L8.5 2.5l-.94 2.06-2.06.94zm10 10l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94z\"/><path d=\"M17.41 7.96l-1.37-1.37c-.4-.4-.92-.59-1.43-.59-.52 0-1.04.2-1.43.59L10.3 9.45l-7.72 7.72c-.78.78-.78 2.05 0 2.83L4 21.41c.39.39.9.59 1.41.59.51 0 1.02-.2 1.41-.59l7.78-7.78 2.81-2.81c.8-.78.8-2.07 0-2.86zM5.41 20L4 18.59l7.72-7.72 1.47 1.35L5.41 20z\"/>\n  </svg>\n      </button>\n\n  <style>\n    .colab-df-container {\n      display:flex;\n      flex-wrap:wrap;\n      gap: 12px;\n    }\n\n    .colab-df-convert {\n      background-color: #E8F0FE;\n      border: none;\n      border-radius: 50%;\n      cursor: pointer;\n      display: none;\n      fill: #1967D2;\n      height: 32px;\n      padding: 0 0 0 0;\n      width: 32px;\n    }\n\n    .colab-df-convert:hover {\n      background-color: #E2EBFA;\n      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n      fill: #174EA6;\n    }\n\n    [theme=dark] .colab-df-convert {\n      background-color: #3B4455;\n      fill: #D2E3FC;\n    }\n\n    [theme=dark] .colab-df-convert:hover {\n      background-color: #434B5C;\n      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n      fill: #FFFFFF;\n    }\n  </style>\n\n      \n    </div>\n  </div>\n\n\n\n\n#### **2.2 Visualizing all of the pizza joints in the data source**\n\n\n```python\n# Getting a scatter plot of the pizza joints in all of Austin\npizza_joint.plot(\n    kind='scatter', \n    x='longitude', \n    y='latitude',\n    figsize = (10,10)\n)\n```\n\n### **3. First Look at Clean Data - Analysis**\n### We analyze the clean data by visualizing the Austin, TX restaurant data\n\n#### **3.1 Where are the pizzerias in Austin?**\n\n\n```python\n! pip3 install -U geopandas fiona shapely pyproj geopy pysal descartes\n```\n\n    Collecting geopandas\n      Downloading geopandas-0.10.2-py2.py3-none-any.whl (1.0 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.0 MB 12.8 MB/s \n    \u001b[?25hCollecting fiona\n      Downloading Fiona-1.8.21-cp37-cp37m-manylinux2014_x86_64.whl (16.7 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 16.7 MB 41.8 MB/s \n    \u001b[?25hRequirement already satisfied: shapely in /usr/local/lib/python3.7/dist-packages (1.8.1.post1)\n    Collecting pyproj\n      Downloading pyproj-3.2.1-cp37-cp37m-manylinux2010_x86_64.whl (6.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.3 MB 77.9 MB/s \n    \u001b[?25hRequirement already satisfied: geopy in /usr/local/lib/python3.7/dist-packages (1.17.0)\n    Collecting geopy\n      Downloading geopy-2.2.0-py3-none-any.whl (118 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 118 kB 71.6 MB/s \n    \u001b[?25hCollecting pysal\n      Downloading pysal-2.6.0-py3-none-any.whl (17 kB)\n    Requirement already satisfied: descartes in /usr/local/lib/python3.7/dist-packages (1.1.0)\n    Requirement already satisfied: pandas>=0.25.0 in /usr/local/lib/python3.7/dist-packages (from geopandas) (1.3.5)\n    Requirement already satisfied: six>=1.7 in /usr/local/lib/python3.7/dist-packages (from fiona) (1.15.0)\n    Requirement already satisfied: click>=4.0 in /usr/local/lib/python3.7/dist-packages (from fiona) (7.1.2)\n    Collecting cligj>=0.5\n      Downloading cligj-0.7.2-py3-none-any.whl (7.1 kB)\n    Requirement already satisfied: attrs>=17 in /usr/local/lib/python3.7/dist-packages (from fiona) (21.4.0)\n    Requirement already satisfied: certifi in /usr/local/lib/python3.7/dist-packages (from fiona) (2021.10.8)\n    Collecting munch\n      Downloading munch-2.5.0-py2.py3-none-any.whl (10 kB)\n    Collecting click-plugins>=1.0\n      Downloading click_plugins-1.1.1-py2.py3-none-any.whl (7.5 kB)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from fiona) (57.4.0)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.25.0->geopandas) (2.8.2)\n    Requirement already satisfied: numpy>=1.17.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.25.0->geopandas) (1.21.6)\n    Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.25.0->geopandas) (2022.1)\n    Requirement already satisfied: geographiclib<2,>=1.49 in /usr/local/lib/python3.7/dist-packages (from geopy) (1.52)\n    Collecting segregation>=2.1.0\n      Downloading segregation-2.2.3-py3-none-any.whl (147 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 147 kB 70.9 MB/s \n    \u001b[?25hCollecting mgwr>=2.1.2\n      Downloading mgwr-2.1.2.tar.gz (41 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 41 kB 529 kB/s \n    \u001b[?25hCollecting spint>=1.0.7\n      Downloading spint-1.0.7.tar.gz (28 kB)\n    Collecting mapclassify>=2.4.3\n      Downloading mapclassify-2.4.3-py3-none-any.whl (38 kB)\n    Collecting spopt>=0.2.1\n      Downloading spopt-0.3.0-py3-none-any.whl (83 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 83 kB 2.1 MB/s \n    \u001b[?25hCollecting momepy>=0.5.2\n      Downloading momepy-0.5.3-py3-none-any.whl (243 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 243 kB 76.0 MB/s \n    \u001b[?25hCollecting spvcm>=0.3.0\n      Downloading spvcm-0.3.0.tar.gz (5.7 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5.7 MB 40.7 MB/s \n    \u001b[?25hCollecting giddy>=2.3.3\n      Downloading giddy-2.3.3-py3-none-any.whl (60 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 60 kB 7.8 MB/s \n    \u001b[?25hCollecting tobler>=0.8.2\n      Downloading tobler-0.9.0-py3-none-any.whl (22 kB)\n    Collecting esda>=2.4.1\n      Downloading esda-2.4.1.tar.gz (95 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 95 kB 4.4 MB/s \n    \u001b[?25hCollecting inequality>=1.0.0\n      Downloading inequality-1.0.0.tar.gz (11 kB)\n    Collecting spglm>=1.0.8\n      Downloading spglm-1.0.8.tar.gz (37 kB)\n    Collecting spaghetti>=1.6.5\n      Downloading spaghetti-1.6.5-py3-none-any.whl (46 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 46 kB 3.7 MB/s \n    \u001b[?25hCollecting spreg>=1.2.4\n      Downloading spreg-1.2.4-py3-none-any.whl (209 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 209 kB 73.1 MB/s \n    \u001b[?25hCollecting splot>=1.1.4\n      Downloading splot-1.1.5.post1-py3-none-any.whl (39 kB)\n    Collecting libpysal>=4.6.0\n      Downloading libpysal-4.6.2-py3-none-any.whl (2.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.4 MB 62.2 MB/s \n    \u001b[?25hCollecting access>=1.1.3\n      Downloading access-1.1.3-py3-none-any.whl (21 kB)\n    Collecting pointpats>=2.2.0\n      Downloading pointpats-2.2.0.tar.gz (55 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 55 kB 4.0 MB/s \n    \u001b[?25hRequirement already satisfied: scipy>=0.11 in /usr/local/lib/python3.7/dist-packages (from esda>=2.4.1->pysal) (1.4.1)\n    Requirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from esda>=2.4.1->pysal) (1.0.2)\n    Collecting quantecon>=0.4.7\n      Downloading quantecon-0.5.3-py3-none-any.whl (179 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 179 kB 63.6 MB/s \n    \u001b[?25hRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from libpysal>=4.6.0->pysal) (2.23.0)\n    Requirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.7/dist-packages (from libpysal>=4.6.0->pysal) (4.6.3)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from libpysal>=4.6.0->pysal) (21.3)\n    Requirement already satisfied: appdirs in /usr/local/lib/python3.7/dist-packages (from libpysal>=4.6.0->pysal) (1.4.4)\n    Requirement already satisfied: jinja2 in /usr/local/lib/python3.7/dist-packages (from libpysal>=4.6.0->pysal) (2.11.3)\n    Requirement already satisfied: networkx in /usr/local/lib/python3.7/dist-packages (from mapclassify>=2.4.3->pysal) (2.6.3)\n    Requirement already satisfied: tqdm>=4.27.0 in /usr/local/lib/python3.7/dist-packages (from momepy>=0.5.2->pysal) (4.64.0)\n    Collecting pygeos\n      Downloading pygeos-0.12.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.1 MB 60.2 MB/s \n    \u001b[?25hRequirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from pointpats>=2.2.0->pysal) (3.2.2)\n    Collecting opencv-contrib-python>=4.2.0\n      Downloading opencv_contrib_python-4.5.5.64-cp36-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (66.7 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 66.7 MB 1.2 MB/s \n    \u001b[?25hRequirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from quantecon>=0.4.7->giddy>=2.3.3->pysal) (1.7.1)\n    Requirement already satisfied: numba in /usr/local/lib/python3.7/dist-packages (from quantecon>=0.4.7->giddy>=2.3.3->pysal) (0.51.2)\n    Requirement already satisfied: seaborn in /usr/local/lib/python3.7/dist-packages (from segregation>=2.1.0->pysal) (0.11.2)\n    Requirement already satisfied: pip in /usr/local/lib/python3.7/dist-packages (from segregation>=2.1.0->pysal) (21.1.3)\n    Collecting quilt3\n      Downloading quilt3-5.0.0-py3-none-any.whl (78 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 78 kB 7.4 MB/s \n    \u001b[?25hCollecting deprecation\n      Downloading deprecation-2.1.0-py2.py3-none-any.whl (11 kB)\n    Collecting rvlib>=0.0.5\n      Downloading rvlib-0.0.6.tar.gz (183 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 183 kB 76.9 MB/s \n    \u001b[?25hRequirement already satisfied: joblib in /usr/local/lib/python3.7/dist-packages (from segregation>=2.1.0->pysal) (1.1.0)\n    Requirement already satisfied: cffi>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from rvlib>=0.0.5->segregation>=2.1.0->pysal) (1.15.0)\n    Requirement already satisfied: PyYAML in /usr/local/lib/python3.7/dist-packages (from rvlib>=0.0.5->segregation>=2.1.0->pysal) (3.13)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.0.0->rvlib>=0.0.5->segregation>=2.1.0->pysal) (2.21)\n    Requirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba->quantecon>=0.4.7->giddy>=2.3.3->pysal) (0.34.0)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->esda>=2.4.1->pysal) (3.1.0)\n    Collecting rtree\n      Downloading Rtree-1.0.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.0 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.0 MB 61.7 MB/s \n    \u001b[?25hCollecting pulp\n      Downloading PuLP-2.6.0-py3-none-any.whl (14.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 14.2 MB 54.9 MB/s \n    \u001b[?25hRequirement already satisfied: statsmodels in /usr/local/lib/python3.7/dist-packages (from tobler>=0.8.2->pysal) (0.10.2)\n    Collecting rasterstats\n      Downloading rasterstats-0.16.0-py3-none-any.whl (16 kB)\n    Collecting rasterio\n      Downloading rasterio-1.2.10-cp37-cp37m-manylinux1_x86_64.whl (19.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19.3 MB 597 kB/s \n    \u001b[?25hRequirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2->libpysal>=4.6.0->pysal) (2.0.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->pointpats>=2.2.0->pysal) (3.0.8)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->pointpats>=2.2.0->pysal) (0.11.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->pointpats>=2.2.0->pysal) (1.4.2)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from kiwisolver>=1.0.1->matplotlib->pointpats>=2.2.0->pysal) (4.1.1)\n    Collecting jsonlines==1.2.0\n      Downloading jsonlines-1.2.0-py2.py3-none-any.whl (7.6 kB)\n    Collecting boto3>=1.10.0\n      Downloading boto3-1.21.45-py3-none-any.whl (132 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 132 kB 84.6 MB/s \n    \u001b[?25hCollecting aws-requests-auth>=0.4.2\n      Downloading aws_requests_auth-0.4.3-py2.py3-none-any.whl (6.8 kB)\n    Requirement already satisfied: tenacity>=5.1.1 in /usr/local/lib/python3.7/dist-packages (from quilt3->segregation>=2.1.0->pysal) (8.0.1)\n    Collecting PyYAML\n      Downloading PyYAML-6.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (596 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 596 kB 83.2 MB/s \n    \u001b[?25hCollecting requests-futures==1.0.0\n      Downloading requests_futures-1.0.0-py2.py3-none-any.whl (7.4 kB)\n    Requirement already satisfied: jsonschema<5,>=3 in /usr/local/lib/python3.7/dist-packages (from quilt3->segregation>=2.1.0->pysal) (4.3.3)\n    Collecting botocore<1.25.0,>=1.24.45\n      Downloading botocore-1.24.45-py3-none-any.whl (8.7 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 8.7 MB 55.5 MB/s \n    \u001b[?25hCollecting s3transfer<0.6.0,>=0.5.0\n      Downloading s3transfer-0.5.2-py3-none-any.whl (79 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 79 kB 8.1 MB/s \n    \u001b[?25hCollecting jmespath<2.0.0,>=0.7.1\n      Downloading jmespath-1.0.0-py3-none-any.whl (23 kB)\n    Collecting urllib3<1.27,>=1.25.4\n      Downloading urllib3-1.26.9-py2.py3-none-any.whl (138 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 138 kB 86.7 MB/s \n    \u001b[?25hRequirement already satisfied: pyrsistent!=0.17.0,!=0.17.1,!=0.17.2,>=0.14.0 in /usr/local/lib/python3.7/dist-packages (from jsonschema<5,>=3->quilt3->segregation>=2.1.0->pysal) (0.18.1)\n    Requirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from jsonschema<5,>=3->quilt3->segregation>=2.1.0->pysal) (4.11.3)\n    Requirement already satisfied: importlib-resources>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from jsonschema<5,>=3->quilt3->segregation>=2.1.0->pysal) (5.7.0)\n    Requirement already satisfied: zipp>=3.1.0 in /usr/local/lib/python3.7/dist-packages (from importlib-resources>=1.4.0->jsonschema<5,>=3->quilt3->segregation>=2.1.0->pysal) (3.8.0)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->libpysal>=4.6.0->pysal) (2.10)\n      Downloading urllib3-1.25.11-py2.py3-none-any.whl (127 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 127 kB 78.1 MB/s \n    \u001b[?25hRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->libpysal>=4.6.0->pysal) (3.0.4)\n    Collecting snuggs>=1.4.1\n      Downloading snuggs-1.4.7-py3-none-any.whl (5.4 kB)\n    Collecting affine\n      Downloading affine-2.3.1-py2.py3-none-any.whl (16 kB)\n    Collecting simplejson\n      Downloading simplejson-3.17.6-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (130 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 130 kB 64.9 MB/s \n    \u001b[?25hRequirement already satisfied: patsy>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from statsmodels->tobler>=0.8.2->pysal) (0.5.2)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->quantecon>=0.4.7->giddy>=2.3.3->pysal) (1.2.1)\n    Building wheels for collected packages: esda, inequality, mgwr, pointpats, rvlib, spglm, spint, spvcm\n      Building wheel for esda (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for esda: filename=esda-2.4.1-py3-none-any.whl size=117429 sha256=7dddd4ef65fc26d8e475f267da4e958026a2659d9e8f03ceebca19f955b61d1d\n      Stored in directory: /root/.cache/pip/wheels/ed/67/c5/4558a178be4c410f341c31f71b5aba9c761a40c9d17dbdfddd\n      Building wheel for inequality (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for inequality: filename=inequality-1.0.0-py3-none-any.whl size=11800 sha256=05b7bbcd472dc5621886de8b78c861811bba4ea0cb865095d44133416c725544\n      Stored in directory: /root/.cache/pip/wheels/a8/81/7a/af8b9e8ea0b034ac1bdd9d68f3a8ceac179eb5418cdb83c851\n      Building wheel for mgwr (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for mgwr: filename=mgwr-2.1.2-py3-none-any.whl size=46386 sha256=7578085f27042f21d743405661d6d22c2caf580e3f6426b0d604043bddf7f400\n      Stored in directory: /root/.cache/pip/wheels/e8/55/57/c1bf993ab0ab4b9885ac1fdf7f9f960397355cf889b77a3e4b\n      Building wheel for pointpats (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pointpats: filename=pointpats-2.2.0-py3-none-any.whl size=60835 sha256=30ea038b6cc1df65e6b0e565fc1226ce47b7b657fd1ebf8709c71d17c46cdbf3\n      Stored in directory: /root/.cache/pip/wheels/41/5f/91/08cc68af630fafdc6bed36128abf8e716e062256a8495fdb2d\n      Building wheel for rvlib (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for rvlib: filename=rvlib-0.0.6-cp37-cp37m-linux_x86_64.whl size=352493 sha256=4bac3dc964e120a493e91d43ff768a7204ceb9b4644e2a44c7d4b8d4b5c356c6\n      Stored in directory: /root/.cache/pip/wheels/8e/fe/cb/66b78310be88014dfbe1a21391c873a9fe49dca403f7d9f454\n      Building wheel for spglm (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for spglm: filename=spglm-1.0.8-py3-none-any.whl size=38806 sha256=268236637bf849a5669acc6814bc8a733f6b8b3d84a1b899a14d87ab102fff9e\n      Stored in directory: /root/.cache/pip/wheels/29/79/e9/453e3b0d858bed16e097c6e6bbd75e2b966bfcfb21b12790d0\n      Building wheel for spint (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for spint: filename=spint-1.0.7-py3-none-any.whl size=31383 sha256=c7ce46d6eaeca41572310ab4cdacb6ea39ca8a8ff6cdcb1396132687a86925b7\n      Stored in directory: /root/.cache/pip/wheels/dd/ac/5d/25d69231f3bffa2cb47ce29bb7eac9df9246aa9ba286a03a2d\n      Building wheel for spvcm (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for spvcm: filename=spvcm-0.3.0-py3-none-any.whl size=5777202 sha256=1fd0c5770939deed0fcfe3a97c94f3c3c9583b63e16435191a7b702c18299a0b\n      Stored in directory: /root/.cache/pip/wheels/a4/85/1a/d890ef4d2eaca2788e45925fa531bb58a2138734065abdfe08\n    Successfully built esda inequality mgwr pointpats rvlib spglm spint spvcm\n    Installing collected packages: urllib3, jmespath, botocore, snuggs, s3transfer, munch, libpysal, cligj, click-plugins, affine, spreg, simplejson, rtree, requests-futures, rasterio, quantecon, PyYAML, pyproj, mapclassify, jsonlines, fiona, esda, boto3, aws-requests-auth, spglm, spaghetti, rvlib, rasterstats, quilt3, pygeos, pulp, opencv-contrib-python, giddy, geopandas, deprecation, tobler, spvcm, spopt, splot, spint, segregation, pointpats, momepy, mgwr, inequality, access, pysal, geopy\n      Attempting uninstall: urllib3\n        Found existing installation: urllib3 1.24.3\n        Uninstalling urllib3-1.24.3:\n          Successfully uninstalled urllib3-1.24.3\n      Attempting uninstall: PyYAML\n        Found existing installation: PyYAML 3.13\n        Uninstalling PyYAML-3.13:\n          Successfully uninstalled PyYAML-3.13\n      Attempting uninstall: opencv-contrib-python\n        Found existing installation: opencv-contrib-python 4.1.2.30\n        Uninstalling opencv-contrib-python-4.1.2.30:\n          Successfully uninstalled opencv-contrib-python-4.1.2.30\n      Attempting uninstall: geopy\n        Found existing installation: geopy 1.17.0\n        Uninstalling geopy-1.17.0:\n          Successfully uninstalled geopy-1.17.0\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    datascience 0.10.6 requires folium==0.2.1, but you have folium 0.8.3 which is incompatible.\u001b[0m\n    Successfully installed PyYAML-6.0 access-1.1.3 affine-2.3.1 aws-requests-auth-0.4.3 boto3-1.21.45 botocore-1.24.45 click-plugins-1.1.1 cligj-0.7.2 deprecation-2.1.0 esda-2.4.1 fiona-1.8.21 geopandas-0.10.2 geopy-2.2.0 giddy-2.3.3 inequality-1.0.0 jmespath-1.0.0 jsonlines-1.2.0 libpysal-4.6.2 mapclassify-2.4.3 mgwr-2.1.2 momepy-0.5.3 munch-2.5.0 opencv-contrib-python-4.5.5.64 pointpats-2.2.0 pulp-2.6.0 pygeos-0.12.0 pyproj-3.2.1 pysal-2.6.0 quantecon-0.5.3 quilt3-5.0.0 rasterio-1.2.10 rasterstats-0.16.0 requests-futures-1.0.0 rtree-1.0.0 rvlib-0.0.6 s3transfer-0.5.2 segregation-2.2.3 simplejson-3.17.6 snuggs-1.4.7 spaghetti-1.6.5 spglm-1.0.8 spint-1.0.7 splot-1.1.5.post1 spopt-0.3.0 spreg-1.2.4 spvcm-0.3.0 tobler-0.9.0 urllib3-1.25.11\n\n\n\n```python\n!sudo apt-get install -y libgeos-dev python3-rtree\nimport geopandas as gpd\n```\n\n    Reading package lists... Done\n    Building dependency tree       \n    Reading state information... Done\n    libgeos-dev is already the newest version (3.6.2-1build2).\n    libgeos-dev set to manually installed.\n    The following additional packages will be installed:\n      libspatialindex-c4v5 libspatialindex-dev libspatialindex4v5\n      python3-pkg-resources\n    Suggested packages:\n      python3-setuptools\n    The following NEW packages will be installed:\n      libspatialindex-c4v5 libspatialindex-dev libspatialindex4v5\n      python3-pkg-resources python3-rtree\n    0 upgraded, 5 newly installed, 0 to remove and 40 not upgraded.\n    Need to get 671 kB of archives.\n    After this operation, 3,948 kB of additional disk space will be used.\n    Get:1 http://archive.ubuntu.com/ubuntu bionic/universe amd64 libspatialindex4v5 amd64 1.8.5-5 [219 kB]\n    Get:2 http://archive.ubuntu.com/ubuntu bionic/universe amd64 libspatialindex-c4v5 amd64 1.8.5-5 [51.7 kB]\n    Get:3 http://archive.ubuntu.com/ubuntu bionic/main amd64 python3-pkg-resources all 39.0.1-2 [98.8 kB]\n    Get:4 http://archive.ubuntu.com/ubuntu bionic/universe amd64 libspatialindex-dev amd64 1.8.5-5 [285 kB]\n    Get:5 http://archive.ubuntu.com/ubuntu bionic/universe amd64 python3-rtree all 0.8.3+ds-1 [16.9 kB]\n    Fetched 671 kB in 1s (904 kB/s)\n    debconf: unable to initialize frontend: Dialog\n    debconf: (No usable dialog-like program is installed, so the dialog based frontend cannot be used. at /usr/share/perl5/Debconf/FrontEnd/Dialog.pm line 76, <> line 5.)\n    debconf: falling back to frontend: Readline\n    debconf: unable to initialize frontend: Readline\n    debconf: (This frontend requires a controlling tty.)\n    debconf: falling back to frontend: Teletype\n    dpkg-preconfigure: unable to re-open stdin: \n    Selecting previously unselected package libspatialindex4v5:amd64.\n    (Reading database ... 155501 files and directories currently installed.)\n    Preparing to unpack .../libspatialindex4v5_1.8.5-5_amd64.deb ...\n    Unpacking libspatialindex4v5:amd64 (1.8.5-5) ...\n    Selecting previously unselected package libspatialindex-c4v5:amd64.\n    Preparing to unpack .../libspatialindex-c4v5_1.8.5-5_amd64.deb ...\n    Unpacking libspatialindex-c4v5:amd64 (1.8.5-5) ...\n    Selecting previously unselected package python3-pkg-resources.\n    Preparing to unpack .../python3-pkg-resources_39.0.1-2_all.deb ...\n    Unpacking python3-pkg-resources (39.0.1-2) ...\n    Selecting previously unselected package libspatialindex-dev:amd64.\n    Preparing to unpack .../libspatialindex-dev_1.8.5-5_amd64.deb ...\n    Unpacking libspatialindex-dev:amd64 (1.8.5-5) ...\n    Selecting previously unselected package python3-rtree.\n    Preparing to unpack .../python3-rtree_0.8.3+ds-1_all.deb ...\n    Unpacking python3-rtree (0.8.3+ds-1) ...\n    Setting up libspatialindex4v5:amd64 (1.8.5-5) ...\n    Setting up python3-pkg-resources (39.0.1-2) ...\n    Setting up libspatialindex-c4v5:amd64 (1.8.5-5) ...\n    Setting up libspatialindex-dev:amd64 (1.8.5-5) ...\n    Setting up python3-rtree (0.8.3+ds-1) ...\n    Processing triggers for libc-bin (2.27-3ubuntu1.3) ...\n    /sbin/ldconfig.real: /usr/local/lib/python3.7/dist-packages/ideep4py/lib/libmkldnn.so.0 is not a symbolic link\n    \n\n\n    /usr/local/lib/python3.7/dist-packages/geopandas/_compat.py:115: UserWarning: The Shapely GEOS version (3.10.2-CAPI-1.16.0) is incompatible with the GEOS version PyGEOS was compiled with (3.10.1-CAPI-1.16.0). Conversions between both will be slow.\n      shapely_geos_version, geos_capi_version_string\n\n\n##### Map data source:\n[DATA](https://data.austintexas.gov/browse?q=BOUNDARIES_jurisdictions&sortBy=relevance)\n\n\n```python\n# Creating jurisdictions map of Austin\ndf_austin = gpd.GeoDataFrame.from_file('/content/drive/MyDrive/data/BOUNDARIES_jurisdictions.geojson')\ndf_austin.plot(figsize=(10,10))\n```\n\n\n```python\n# creating a geometry point with GeoPandas to use it later to create a boundary\ngdf = gpd.GeoDataFrame(\n    austin_restaurants, geometry=gpd.points_from_xy(austin_restaurants.longitude, austin_restaurants.latitude))\ngdf.head(5)\n```\n\n\n\n\n\n  <div id=\"df-34475c52-59ce-4749-9831-15dea55313e3\">\n    <div class=\"colab-df-container\">\n      <div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>business_id</th>\n      <th>name</th>\n      <th>address</th>\n      <th>city</th>\n      <th>state</th>\n      <th>postal_code</th>\n      <th>latitude</th>\n      <th>longitude</th>\n      <th>stars</th>\n      <th>review_count</th>\n      <th>is_open</th>\n      <th>attributes</th>\n      <th>categories</th>\n      <th>hours</th>\n      <th>geometry</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>41</th>\n      <td>NRPemqVb4qpWFF0Avq_6OQ</td>\n      <td>Eurasia Sushi Bar &amp; Seafood</td>\n      <td>7101 W Hwy 71, Ste C-13</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78735</td>\n      <td>30.234533</td>\n      <td>-97.877262</td>\n      <td>4.5</td>\n      <td>395</td>\n      <td>1</td>\n      <td>{'Ambience': '{'touristy': False, 'hipster': F...</td>\n      <td>Bars, Nightlife, Cocktail Bars, Seafood, Resta...</td>\n      <td>{'Monday': '0:0-0:0', 'Tuesday': '11:0-22:0', ...</td>\n      <td>POINT (-97.87726 30.23453)</td>\n    </tr>\n    <tr>\n      <th>61</th>\n      <td>bRsDZ44CD3uhGnRY3NeQhQ</td>\n      <td>Wendy's</td>\n      <td>6247 Mcneil Drive</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78729</td>\n      <td>30.441875</td>\n      <td>-97.746581</td>\n      <td>2.0</td>\n      <td>46</td>\n      <td>1</td>\n      <td>{'RestaurantsPriceRange2': '1', 'OutdoorSeatin...</td>\n      <td>Fast Food, Restaurants, Burgers</td>\n      <td>{'Monday': '6:30-1:0', 'Tuesday': '6:30-1:0', ...</td>\n      <td>POINT (-97.74658 30.44188)</td>\n    </tr>\n    <tr>\n      <th>199</th>\n      <td>Pk4ZwXwUU50BDn5gqw_rKg</td>\n      <td>Johnny Carino's</td>\n      <td>9500 S IH-35 Service Rd</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78748</td>\n      <td>30.162081</td>\n      <td>-97.789132</td>\n      <td>3.0</td>\n      <td>136</td>\n      <td>1</td>\n      <td>{'RestaurantsGoodForGroups': 'True', 'Business...</td>\n      <td>Italian, Salad, Pizza, Nightlife, Restaurants,...</td>\n      <td>{'Monday': '11:0-21:30', 'Tuesday': '11:0-21:3...</td>\n      <td>POINT (-97.78913 30.16208)</td>\n    </tr>\n    <tr>\n      <th>253</th>\n      <td>Ieelu69Y23nbjKG3OGfwnw</td>\n      <td>McDonald's</td>\n      <td>5017 Hwy 290 W</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78735</td>\n      <td>30.232133</td>\n      <td>-97.823183</td>\n      <td>1.5</td>\n      <td>9</td>\n      <td>1</td>\n      <td>{'RestaurantsTakeOut': 'True', 'RestaurantsRes...</td>\n      <td>Restaurants, Coffee &amp; Tea, Food, Burgers, Fast...</td>\n      <td>{'Monday': '7:0-22:30', 'Tuesday': '7:0-22:30'...</td>\n      <td>POINT (-97.82318 30.23213)</td>\n    </tr>\n    <tr>\n      <th>258</th>\n      <td>IFB2K3BEZ2L_Mv5AbUD26Q</td>\n      <td>Chispas</td>\n      <td>214 W 4th St</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78701</td>\n      <td>30.266996</td>\n      <td>-97.745362</td>\n      <td>3.5</td>\n      <td>119</td>\n      <td>1</td>\n      <td>{'RestaurantsTakeOut': 'True', 'OutdoorSeating...</td>\n      <td>Tex-Mex, Mexican, Tacos, Restaurants</td>\n      <td>{'Monday': '11:0-22:0', 'Tuesday': '11:0-22:0'...</td>\n      <td>POINT (-97.74536 30.26700)</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n      <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-34475c52-59ce-4749-9831-15dea55313e3')\"\n              title=\"Convert this dataframe to an interactive table.\"\n              style=\"display:none;\">\n\n  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n       width=\"24px\">\n    <path d=\"M0 0h24v24H0V0z\" fill=\"none\"/>\n    <path d=\"M18.56 5.44l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94zm-11 1L8.5 8.5l.94-2.06 2.06-.94-2.06-.94L8.5 2.5l-.94 2.06-2.06.94zm10 10l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94z\"/><path d=\"M17.41 7.96l-1.37-1.37c-.4-.4-.92-.59-1.43-.59-.52 0-1.04.2-1.43.59L10.3 9.45l-7.72 7.72c-.78.78-.78 2.05 0 2.83L4 21.41c.39.39.9.59 1.41.59.51 0 1.02-.2 1.41-.59l7.78-7.78 2.81-2.81c.8-.78.8-2.07 0-2.86zM5.41 20L4 18.59l7.72-7.72 1.47 1.35L5.41 20z\"/>\n  </svg>\n      </button>\n\n  <style>\n    .colab-df-container {\n      display:flex;\n      flex-wrap:wrap;\n      gap: 12px;\n    }\n\n    .colab-df-convert {\n      background-color: #E8F0FE;\n      border: none;\n      border-radius: 50%;\n      cursor: pointer;\n      display: none;\n      fill: #1967D2;\n      height: 32px;\n      padding: 0 0 0 0;\n      width: 32px;\n    }\n\n    .colab-df-convert:hover {\n      background-color: #E2EBFA;\n      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n      fill: #174EA6;\n    }\n\n    [theme=dark] .colab-df-convert {\n      background-color: #3B4455;\n      fill: #D2E3FC;\n    }\n\n    [theme=dark] .colab-df-convert:hover {\n      background-color: #434B5C;\n      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n      fill: #FFFFFF;\n    }\n  </style>\n\n      \n    </div>\n  </div>\n\n\n\n\n\n```python\nbase = df_austin.plot(linewidth=0.3, color='grey', figsize = (20,20))\n\npizza_joint.plot(\n    kind='scatter', \n    x='longitude', \n    y='latitude',\n    figsize = (10,10),\n    ax = base\n)\n```\n\n##### Pizzerias are concentrated in the middle of the city. The right side of the city has many industrial areas explaining the lack of pizzerias\n\n#### **3.2 How many pizzerias are there per zipcode?**\n\n\n```python\npizza_per_zip = pizza_joint.groupby('postal_code').name.count()\npizza_per_zip_sorted = pizza_per_zip.sort_values(ascending=False)\npizza_per_zip_sorted\n```\n\n\n\n\n    postal_code\n    78701    29\n    78704    23\n    78759    16\n    78753    15\n    78702    14\n    78745    14\n    78758    12\n    78748    12\n    78746    11\n    78741    10\n    78757    10\n    78723    10\n    78705    10\n    78751     7\n    78744     6\n    78750     6\n    78749     6\n    78731     5\n    78738     4\n    78729     4\n    78735     4\n    78727     4\n    78703     4\n    78734     3\n    78728     3\n    78754     2\n    78752     2\n    78747     2\n    78737     2\n    78756     2\n    78726     2\n    78665     1\n    78736     1\n    78732     1\n    78730     1\n    78724     1\n    78722     1\n    78719     1\n    78798     1\n    Name: name, dtype: int64\n\n\n\n\n```python\n# total pizzerias in Austin\ntotal_pizza_count = pizza_joint.name.count()\nprint(total_pizza_count)\n```\n\n    262\n\n\n\n```python\npizza_per_zip.plot(kind='bar')\n```\n\n\n```python\n#Top 10 zip codes\npizza_per_zip_sorted.head(10).plot(kind='bar')\n\n```\n\n#### **3.3 Concentration of pizzerias among Austin restaurants**\n\n\n```python\n# Total Restaurants in Austin\ntotal_restaurant_count = austin_restaurants.name.count()\nprint(total_restaurant_count)\n```\n\n    2832\n\n\n\n```python\n# % of Pizzerias of Total Restaurants in Austin\n\npizza_percentage = round((total_pizza_count / total_restaurant_count),2)*100\npizza_percentage\n```\n\n\n\n\n    9.0\n\n\n\n##### 9% of Austin restaurants are pizzerias\n\n\n```python\n# 9% is average, but is it telling the full story? We can validate by checking the distribution of concentration by zip code\nrestaurant_per_zip = austin_restaurants.groupby('postal_code').name.count()\n\npizza_and_restaurant = pizza_per_zip.to_frame().merge(restaurant_per_zip.to_frame(), left_on='postal_code', right_on='postal_code')\npizza_and_restaurant\n\nconcentration_per_zip = (pizza_and_restaurant[\"name_x\"] / pizza_and_restaurant[\"name_y\"]) * 100\npizza_and_restaurant[\"concentration\"] = concentration_per_zip\nprint(pizza_and_restaurant)\n```\n\n                 name_x  name_y  concentration\n    postal_code                               \n    78665             1       1     100.000000\n    78701            29     294       9.863946\n    78702            14     216       6.481481\n    78703             4      57       7.017544\n    78704            23     263       8.745247\n    78705            10     130       7.692308\n    78719             1      27       3.703704\n    78722             1      43       2.325581\n    78723            10      82      12.195122\n    78724             1      11       9.090909\n    78726             2      22       9.090909\n    78727             4      53       7.547170\n    78728             3      29      10.344828\n    78729             4      21      19.047619\n    78730             1       9      11.111111\n    78731             5      38      13.157895\n    78732             1      23       4.347826\n    78734             3      21      14.285714\n    78735             4      37      10.810811\n    78736             1      11       9.090909\n    78737             2      20      10.000000\n    78738             4      23      17.391304\n    78741            10      95      10.526316\n    78744             6      47      12.765957\n    78745            14     163       8.588957\n    78746            11      64      17.187500\n    78747             2       8      25.000000\n    78748            12      98      12.244898\n    78749             6      45      13.333333\n    78750             6      46      13.043478\n    78751             7      73       9.589041\n    78752             2      84       2.380952\n    78753            15     143      10.489510\n    78754             2      17      11.764706\n    78756             2      66       3.030303\n    78757            10     109       9.174312\n    78758            12     167       7.185629\n    78759            16     121      13.223140\n    78798             1       6      16.666667\n\n\n\n```python\n# Based on the histogram the concentration is clustured in the 0% to 10% band so 9% is a reasonable representative of the city of Austin\npizza_and_restaurant.concentration.hist(bins=10)\n```\n\n##### 9% average concentration tells a reasonable story for the overall Austin as validated by the histogram (most of the concentration in 0-10% range)\n\n#### **3.4 Ratings Distribution and Average of Similar Establishment**\n\n\n```python\npizza_per_star = pizza_joint.groupby('stars').name.count()\npizza_per_star.sort_values(ascending=False)\n\n```\n\n\n\n\n    stars\n    4.0    62\n    3.5    49\n    4.5    43\n    3.0    39\n    2.0    26\n    2.5    26\n    1.5     9\n    5.0     8\n    Name: name, dtype: int64\n\n\n\n\n```python\npizza_per_star.plot(kind='bar')\n\n```\n\n\n```python\ntotal_stars_count = pizza_joint.stars.sum()\n\naverage_stars = total_stars_count / total_pizza_count\naverage_stars\n```\n\n\n\n\n    3.437022900763359\n\n\n\n##### Distribution of stars among pizzerias is slightly left skewed, with an average of 3.4\n\n#### **3.5 Average Number and Distribution of Reviews per Pizzeria**\n\n\n```python\ntotal_review_count = pizza_joint.review_count.sum()\n\naverage_review_count = total_review_count / total_pizza_count\naverage_review_count\n```\n\n\n\n\n    189.83969465648855\n\n\n\n\n```python\npizza_joint.review_count.hist(bins=50)\n```\n\nAverage review count is 190 but based on the histogram of review counts, 0-50 reviews seem to be the most common amount\n\n#### **3.6 Correlation with Bars**\nAs an aside, we were curious to see if there is a correlation between location of bars/pubs and pizzerias and to potential identify a location where this synergy is lacking i.e. there are bars, but no pizzeria.  \n\n\n\n```python\n# creating a variable for all austin restaurants containing \"Bar\" in categories\nbars_joint = austin_restaurants[austin_restaurants['categories'].str.contains(\"Bars\", na=False)]\nbars_joint.head(5)\n\n```\n\n\n\n\n\n  <div id=\"df-3bec2fca-48eb-44fe-9ab3-df8f075ec16f\">\n    <div class=\"colab-df-container\">\n      <div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>business_id</th>\n      <th>name</th>\n      <th>address</th>\n      <th>city</th>\n      <th>state</th>\n      <th>postal_code</th>\n      <th>latitude</th>\n      <th>longitude</th>\n      <th>stars</th>\n      <th>review_count</th>\n      <th>is_open</th>\n      <th>attributes</th>\n      <th>categories</th>\n      <th>hours</th>\n      <th>geometry</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>41</th>\n      <td>NRPemqVb4qpWFF0Avq_6OQ</td>\n      <td>Eurasia Sushi Bar &amp; Seafood</td>\n      <td>7101 W Hwy 71, Ste C-13</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78735</td>\n      <td>30.234533</td>\n      <td>-97.877262</td>\n      <td>4.5</td>\n      <td>395</td>\n      <td>1</td>\n      <td>{'Ambience': '{'touristy': False, 'hipster': F...</td>\n      <td>Bars, Nightlife, Cocktail Bars, Seafood, Resta...</td>\n      <td>{'Monday': '0:0-0:0', 'Tuesday': '11:0-22:0', ...</td>\n      <td>POINT (-97.87726 30.23453)</td>\n    </tr>\n    <tr>\n      <th>199</th>\n      <td>Pk4ZwXwUU50BDn5gqw_rKg</td>\n      <td>Johnny Carino's</td>\n      <td>9500 S IH-35 Service Rd</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78748</td>\n      <td>30.162081</td>\n      <td>-97.789132</td>\n      <td>3.0</td>\n      <td>136</td>\n      <td>1</td>\n      <td>{'RestaurantsGoodForGroups': 'True', 'Business...</td>\n      <td>Italian, Salad, Pizza, Nightlife, Restaurants,...</td>\n      <td>{'Monday': '11:0-21:30', 'Tuesday': '11:0-21:3...</td>\n      <td>POINT (-97.78913 30.16208)</td>\n    </tr>\n    <tr>\n      <th>669</th>\n      <td>_rt-Z934kfFzgG19nTrIcQ</td>\n      <td>Pelons Tex-Mex</td>\n      <td>802 Red River St</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78701</td>\n      <td>30.268838</td>\n      <td>-97.736549</td>\n      <td>3.5</td>\n      <td>438</td>\n      <td>1</td>\n      <td>{'HasTV': 'True', 'BusinessParking': '{'garage...</td>\n      <td>Tex-Mex, Restaurants, Tacos, Nightlife, Bars, ...</td>\n      <td>{'Tuesday': '16:0-22:0', 'Wednesday': '16:0-22...</td>\n      <td>POINT (-97.73655 30.26884)</td>\n    </tr>\n    <tr>\n      <th>778</th>\n      <td>J8Ha6yIvGoU-E31jnCq7Ew</td>\n      <td>Barley Swine</td>\n      <td>6555 Burnet Rd, Ste 400</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78757</td>\n      <td>30.341274</td>\n      <td>-97.738389</td>\n      <td>4.5</td>\n      <td>1086</td>\n      <td>1</td>\n      <td>{'RestaurantsAttire': 'u'casual'', 'GoodForKid...</td>\n      <td>Restaurants, Nightlife, American (New), Bars, ...</td>\n      <td>{'Monday': '0:0-0:0', 'Tuesday': '17:0-22:0', ...</td>\n      <td>POINT (-97.73839 30.34127)</td>\n    </tr>\n    <tr>\n      <th>861</th>\n      <td>pCg4oRweZQnoXo2j7_-BqQ</td>\n      <td>Hote1e1even</td>\n      <td>1123 East 11th St</td>\n      <td>Austin</td>\n      <td>TX</td>\n      <td>78702</td>\n      <td>30.268729</td>\n      <td>-97.728389</td>\n      <td>4.5</td>\n      <td>13</td>\n      <td>1</td>\n      <td>{'WiFi': ''free'', 'RestaurantsPriceRange2': '...</td>\n      <td>Hotels, Event Planning &amp; Services, Restaurants...</td>\n      <td>None</td>\n      <td>POINT (-97.72839 30.26873)</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n      <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-3bec2fca-48eb-44fe-9ab3-df8f075ec16f')\"\n              title=\"Convert this dataframe to an interactive table.\"\n              style=\"display:none;\">\n\n  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n       width=\"24px\">\n    <path d=\"M0 0h24v24H0V0z\" fill=\"none\"/>\n    <path d=\"M18.56 5.44l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94zm-11 1L8.5 8.5l.94-2.06 2.06-.94-2.06-.94L8.5 2.5l-.94 2.06-2.06.94zm10 10l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94z\"/><path d=\"M17.41 7.96l-1.37-1.37c-.4-.4-.92-.59-1.43-.59-.52 0-1.04.2-1.43.59L10.3 9.45l-7.72 7.72c-.78.78-.78 2.05 0 2.83L4 21.41c.39.39.9.59 1.41.59.51 0 1.02-.2 1.41-.59l7.78-7.78 2.81-2.81c.8-.78.8-2.07 0-2.86zM5.41 20L4 18.59l7.72-7.72 1.47 1.35L5.41 20z\"/>\n  </svg>\n      </button>\n\n  <style>\n    .colab-df-container {\n      display:flex;\n      flex-wrap:wrap;\n      gap: 12px;\n    }\n\n    .colab-df-convert {\n      background-color: #E8F0FE;\n      border: none;\n      border-radius: 50%;\n      cursor: pointer;\n      display: none;\n      fill: #1967D2;\n      height: 32px;\n      padding: 0 0 0 0;\n      width: 32px;\n    }\n\n    .colab-df-convert:hover {\n      background-color: #E2EBFA;\n      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n      fill: #174EA6;\n    }\n\n    [theme=dark] .colab-df-convert {\n      background-color: #3B4455;\n      fill: #D2E3FC;\n    }\n\n    [theme=dark] .colab-df-convert:hover {\n      background-color: #434B5C;\n      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n      fill: #FFFFFF;\n    }\n  </style>\n\n      \n    </div>\n  </div>\n\n\n\n\n\n```python\n# Combining Pizza places and Bars into one scatter plot\nbase1 = df_austin.plot(linewidth=0.3, color='silver', figsize = (20,20))\npizza_joint.plot(\n    kind='scatter', \n    x='longitude', \n    y='latitude',\n    figsize = (10,10),\n    ax = base1\n)\nbars_joint.plot(\n    \n    c = \"orange\",            \n    s = 10, \n    alpha = .50,           \n    kind='scatter', \n    x='longitude', \n    y='latitude',\n    figsize = (10,10),\n    ax = base1\n)\n```\n\n##### Pizzerias are very much in line with location of bars\n\n### **4. Competitive Landscape for a Given Location**\n#### Here we take a look at the competitive landscape for a given location by defining radius for search and creating a scoring system based on our analysis in section 3 above\n\n\n#### **4.1 Defining Radius for Search**\n\n\n```python\n#creating data frame for 3 sample locations\n\n#Reference point #1\nreference_point1 = pd.DataFrame(\n    {'location': ['target_point'],\n     'Latitude': [30.267255],\n     'Longitude': [-97.743626]})\n\ngdf_ref1 = gpd.GeoDataFrame(\n    reference_point1, geometry=gpd.points_from_xy(reference_point1.Longitude, reference_point1.Latitude))\n\n#Reference point #2 (commercial area in the NE)\nreference_point2 = pd.DataFrame(\n    {'location': ['target_point'],\n     'Latitude': [30.327068],\n     'Longitude': [-97.707002]})\n\ngdf_ref2 = gpd.GeoDataFrame(\n    reference_point2, geometry=gpd.points_from_xy(reference_point2.Longitude, reference_point2.Latitude))\n\n#Reference point #3 (South Austin Area)\nreference_point3 = pd.DataFrame(\n    {'location': ['target_point'],\n     'Latitude': [30.202847],\n     'Longitude': [-97.806913]})\n\ngdf_ref3 = gpd.GeoDataFrame(\n    reference_point3, geometry=gpd.points_from_xy(reference_point3.Longitude, reference_point3.Latitude))\n\n# ref_plot1 = gdf_ref1.plot(linewidth=0.3, color='grey', figsize = (20,20))\n\n```\n\n\n```python\n#Creating dataframe that shows radius from selected point\n## i.e. 5*(1/60) is 5 miles radius\nref_radius1 = gdf_ref1.buffer(1.5*(1/60), resolution=16)\nref_radius2 = gdf_ref2.buffer(1.5*(1/60), resolution=16) \nref_radius3 = gdf_ref3.buffer(1.5*(1/60), resolution=16)\n\n# ref_base = ref_radius1.plot(linewidth=0.3, color='grey', figsize = (20,20))\nbase1 = df_austin.plot(linewidth=0.3, color='silver', figsize = (20,20))\nref_radius1.plot(linewidth=0.3, color='darkred', figsize = (20,20), ax = base1)\nref_radius2.plot(linewidth=0.3, color='green', figsize = (20,20), ax = base1)\nref_radius3.plot(linewidth=0.3, color='navy', figsize = (20,20), ax = base1)\n```\n\n\n```python\nbase = df_austin.plot(linewidth=0.3, color='silver', figsize = (20,20))\npizza_joint.plot(\n    kind='scatter', \n    x='longitude', \n    y='latitude',\n    figsize = (10,10),\n    ax = base\n)\n\nref_radius1.plot(\n    linewidth=1, \n    color='none',\n    edgecolor='darkred',\n    figsize = (20,20),\n    ax = base\n)\nref_radius2.plot(\n    linewidth=1, \n    color='none', \n    edgecolor='green',\n    figsize = (20,20),\n    ax = base\n)\nref_radius3.plot(\n    linewidth=1, \n    color='none', \n    edgecolor='navy',\n    figsize = (20,20),\n    ax = base\n)\n```\n\n\n```python\nfrom shapely.geometry import Point, Polygon, LineString\nfrom shapely import geometry\n\n```\n\n\n```python\n# Creating a polygon for from the defined boundary\npolys1 = gpd.GeoSeries(ref_radius1)\npolys2 = gpd.GeoSeries(ref_radius2)\npolys3 = gpd.GeoSeries(ref_radius3)\n\n```\n\n\n```python\n# Creating points from results (all data)\npoints = austin_restaurants[\"geometry\"]\npoints\n```\n\n\n\n\n    41        POINT (-97.87726 30.23453)\n    61        POINT (-97.74658 30.44188)\n    199       POINT (-97.78913 30.16208)\n    253       POINT (-97.82318 30.23213)\n    258       POINT (-97.74536 30.26700)\n                         ...            \n    160413    POINT (-97.89304 30.37022)\n    160465    POINT (-97.76447 30.27416)\n    160480    POINT (-97.79541 30.21882)\n    160517    POINT (-97.78845 30.19675)\n    160525    POINT (-97.80443 30.44754)\n    Name: geometry, Length: 2832, dtype: geometry\n\n\n\n\n```python\n!pip install rtree\n```\n\n    Requirement already satisfied: rtree in /usr/local/lib/python3.7/dist-packages (1.0.0)\n    Requirement already satisfied: typing-extensions>=3.7 in /usr/local/lib/python3.7/dist-packages (from rtree) (4.1.1)\n\n\n\n```python\n#checking df types\ntype(gdf)\n```\n\n\n\n\n    geopandas.geodataframe.GeoDataFrame\n\n\n\n\n```python\n#checking df types\ntype(ref_radius1)\n```\n\n\n\n\n    geopandas.geoseries.GeoSeries\n\n\n\n\n```python\n# creating an envelope so we can work a join with the gp dataframe\nenvgdf1 = gpd.GeoDataFrame(geometry=gpd.GeoSeries(ref_radius1))\nenvgdf2 = gpd.GeoDataFrame(geometry=gpd.GeoSeries(ref_radius2))\nenvgdf3 = gpd.GeoDataFrame(geometry=gpd.GeoSeries(ref_radius3))\nprint(envgdf1, envgdf2, envgdf3)\n```\n\n                                                geometry\n    0  POLYGON ((-97.71863 30.26725, -97.71875 30.264...                                             geometry\n    0  POLYGON ((-97.68200 30.32707, -97.68212 30.324...                                             geometry\n    0  POLYGON ((-97.78191 30.20285, -97.78203 30.200...\n\n\n\n```python\n# Creating intersection between gdf data frame and envgdf* dataframe\njoined_gdf1 = gpd.sjoin(gdf, envgdf1, op='within')\njoined_gdf2 = gpd.sjoin(gdf, envgdf2, op='within')\njoined_gdf3 = gpd.sjoin(gdf, envgdf3, op='within')\n\n```\n\n    /usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py:2822: FutureWarning: The `op` parameter is deprecated and will be removed in a future release. Please use the `predicate` parameter instead.\n      if self.run_code(code, result):\n    /usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py:2822: FutureWarning: The `op` parameter is deprecated and will be removed in a future release. Please use the `predicate` parameter instead.\n      if self.run_code(code, result):\n    /usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py:2822: FutureWarning: The `op` parameter is deprecated and will be removed in a future release. Please use the `predicate` parameter instead.\n      if self.run_code(code, result):\n\n\n#### **4.2 Our Business Criteria for Measuring Competitive Landscape**\n\n1. Number of similar places: -1 for each pizza places as this would mean direct competition\n1. Bars: +1 for each bar since bar presence increases the demand for pizza\n1. Concentration of pizza places in the radius: if concentration is >10%, then score decreases by 4 since this would mean higher than average concentration of pizzerias in this location (using an even number 10% as a threshold since average concentration was 9%)\n1. Quality of competition: if an area is less competitive as measured by the star ratings of restaurants (below 3.5 stars based on our findings in section 3), then increase score by 3\n\n##### *The weights of each criteria were arbitrarily chosen to directionally showcase the favorability of an area; In a given set of few sample locations, the area with the highest score would be the most desirable among the peer set* \n\n\n```python\ndef score(location):\n  '''\n  This function takes one positional argument and outputs the score of the location based on our given criteria and information on each criteria\n  Arg: location (dataframe)\n  '''\n  bar = location['categories'].str.contains(\"Bars\", na=False)\n  bar_count = bar.count() - bar.value_counts().loc[False]\n  pizza = location['categories'].str.contains(\"Pizza|Pizzeria|pizza|pizzeria\", na=False)\n  pizza_count = pizza.value_counts().loc[True]\n  total_count = location.name.count()\n  avg_stars_in_radius = location.stars.mean()\n\n# 1*count of bars + -1*count of pizzerias\n  base = 1*bar_count + (-1)*pizza_count\n\n# if  (pizzeria count / total business count) >= 0.10 then -4 \n  if pizza_count / total_count > 0.10:\n    saturation = + -4\n  else:\n    saturation = 0\n\n# if  average stars < 3.5 then +3 \n  if avg_stars_in_radius < 3.50:\n    competition_quality = + 3\n  else:\n    competition_quality = 0\n\n\n  # return base + saturation + competition_quality\n  score_of_location = base + saturation + competition_quality\n\n  print(\"Score: \" + str(score_of_location) + '\\n')\n  print(\"Bar count: \" + str(bar_count))\n  print(\"Pizza count: \" + str(pizza_count))\n  print(\"Total restaurant count: \" + str(total_count))\n  print(\"Saturation: \" + str(round((pizza_count/total_count),2)*100) + \"%\")\n  print(\"Competition Level (Avg Star of Area): \" + str(round(avg_stars_in_radius,2)))\n```\n\n### **5. Result and Conclusion**\n#### We chose 3 sample locations (section 4.1) and measure their competitive landscape using the criteria developed previously (section 4.2) \n#### In closing, we also address various data sets that would enhance this analysis to be more robust\n\n#### **5.1 Result of Three Sample Locations**\n\n\n```python\n#Sample 1 (Central Austin):\nscore(joined_gdf1)\n```\n\n    Score: 162\n    \n    Bar count: 216\n    Pizza count: 54\n    Total restaurant count: 652\n    Saturation: 8.0%\n    Competition Level (Avg Star of Area): 3.93\n\n\n\n```python\n#Sample 2 (North Austin):\nscore(joined_gdf2)\n```\n\n    Score: 15\n    \n    Bar count: 30\n    Pizza count: 15\n    Total restaurant count: 194\n    Saturation: 8.0%\n    Competition Level (Avg Star of Area): 3.68\n\n\n\n```python\n#Sample 3 (South Austin):\nscore(joined_gdf3)\n```\n\n    Score: -2\n    \n    Bar count: 4\n    Pizza count: 6\n    Total restaurant count: 63\n    Saturation: 10.0%\n    Competition Level (Avg Star of Area): 3.76\n\n\n#### **<ins>Result**: Out of the three sample locations, sample 1 (Central Austin) is the most preferred as it has the highest score\n\n#### **5.2 Challenges of this project**\n * Creating the intersection of the selected radius required a number of intermediate steps (creating a geometry from a Geopandas dataset and them creating the intersection itself).\n * Creating the scoring function required full understanding of the data and the various situations when some conditions weren't met.\n\n#### **5.3 In closing, we address various data sets that would enhance this analysis to be more robust**\nWhat kind of information can be layered to take the analysis to the next level?\n * Real estate prices - if a place is good competitively (not too much competition) but too expensive, may be not a feasible option\n * Covid-19 impact on business closures to get a more accurate view of the competitive landscape\n * Demographics to find if demand for your business will be met\n * Pedestrian data to find if a location has good \"discoverability\" by pedestrians \n * Parking data to see if those travelling by car will not have an issue accessing the business \n * Proximity to \"hot spots\" like universities or office area (in non-pandemic times)\n\n", "meta": {"hexsha": "f33c9a0b13cae31da1fcd0bb122a983cffc6605f", "size": 825287, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "AustinOption.ipynb", "max_stars_repo_name": "mc7836/python_projects", "max_stars_repo_head_hexsha": "a4eed5be362da4096e424c1c724567d45b174ec8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-19T21:48:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-19T21:48:29.000Z", "max_issues_repo_path": "AustinOption.ipynb", "max_issues_repo_name": "mc7836/Python_Projects", "max_issues_repo_head_hexsha": "a4eed5be362da4096e424c1c724567d45b174ec8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AustinOption.ipynb", "max_forks_repo_name": "mc7836/Python_Projects", "max_forks_repo_head_hexsha": "a4eed5be362da4096e424c1c724567d45b174ec8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 225.1192034915, "max_line_length": 179501, "alphanum_fraction": 0.8647646213, "converted": true, "num_tokens": 27238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2628418258225589, "lm_q2_score": 0.11124119766818044, "lm_q1q2_score": 0.029238839501792728}}
{"text": "```python\nfrom IPython.core.display import HTML\nHTML(\"<style>.container { width:95% !important; }</style>\")\n```\n\n\n\n\n<style>.container { width:95% !important; }</style>\n\n\n\n# Lecture 10: Introduction to Multiobjective Optimization\n\n## What means multiobjective?\n\n* Consider several criteria simultaneously\n\n* Examples: Cost (investment vs. operating), quality, safety, profit, reliability, operability, environmental and social impacts, etc.\n\n* Criteria are conflicting (e.g. usually good quality is not cheap) $\\Rightarrow$ all the criteria can not be optimized simultaneously (i.e., have different optimal solutions)\n\n* Need for considering compromises between the criteria\n* Indeed we search for a set of acceptable solutions (maybe only suboptimal for one objective) instead of a single optimal.\n\n* Compromise can be better than optimal solution in practice (e.g., optimize only costs/profit)\n\n* http://en.wikipedia.org/wiki/Multiobjective_optimization\n\n## Example. Buying a Laptop\n\n##### **Objectives**:\n* Min Cost\n* Min Weight\n\n\n\n* Which solution is the best? (1,A,B,C,2)\n\n* No single optimal solution\n* Trade-offs between objectives\n\n### Most of the real-life decision problems have multiple criteria\n\n* Can you name some?\n\n## Example 1. Investment (Portfolio selection)\n\n#### objectives:\n* max Return\n* min Risk\n* Max Liquidity\n\n\n\n## Example 2. Supply Chain Management\n\n\n#### objectives:\n* Min cost\n* Min $CO_2$ emissions\n* Max Liquidity\n* Max Social benefits (e.g. job creation)\n\n\n\n\n## Example 3. Engineering Design Problems: (e.g. Cable-Stayed Bridges)\n\n#### objectives:\n* Residual error in each cable tension\n* Residual error in camber at each node\n* Amount of shim adjustment for each cable\n* Number of cables to be adjusted\n\n\n\n\n# Multiobjective optimization process\n\n\n## Example 4: Continuous casting of steel\n\n* Optimal control of the secondary cooling of continuous casting of steel\n* Long history of research in the Dept. of Mathematical Information Technology, Univ. of Jyv\u00e4skyl\u00e4\n  * modelling (1988)\n  * single objective optimization (1988-1994)\n  * multiobjective optimization (1994-1998)\n\n* Liquid steel enters (tundish)\n* Initial cooling by a water cooled mold $\\Rightarrow$ thin crust\n* Movement supported by rollers\n* Secondary cooling by water sprays\n* Rest of the cooling by radiation\n\n\n\n## Modelling\n* Measuring temperature in casting difficult $\\Rightarrow$ numerical temperature distribution\n* Process modelled as a multiphase heat equation (PDEs, solid & liquid phase) $\\Rightarrow$  temperature distribution\n* Numerical model by using the finite element method (FEM)\n* Dynamic process\n\n## Single-objective optimization\n\n* Secondary cooling significant: intensity of sprays (easy to control) affects significantly to the solidification of steel\n* Goal: minimize the amount of defects in steel\n* Quality depends on e.g. the temperature distribution at the surface of steel\n  * too slow cooling \u2192 too long liquid part\n  * too fast cooling \u2192 defects appear\n* Objective function: keep the surface temperature as close to a given profile as possible\n* Constraints e.g. for the change of temperature and for the temperature in critical spots\u200b\n\n## Single-objective optimization results\n\n* Analysis of single objective optimization problem:\n  * constraints tight (based on metallurgy)\n  * no feasible solutions\n* which constraints to relax?\n* $\\Rightarrow$ Convert constraints into objective functions      (5 in total)\n  * Enables simultaneous relaxation of different constraints\n  * Gives information on satisfaction of different constraints and their interdependences\u200b\n\n## Multiobjective optimization results\n\n** Found a solution, which only violated one of the constraints**\n\n$\\Rightarrow$ satisfactory to the application expert\n\n## Example 5: Data-Based Forest Management with Uncertainties and Multiple Objectives\n\n* A study by Profs Annika Kangas (Forest research institute, Joensuu) and Kaisa Miettinen, PhD Markus Hartikainen and PhD Kyle Eyvindson (University of Helsinki)\n* Main research question: How to use multiobjective optimization to handle in forest management simultaneously\n  * conflicting objectives **income** and **biodiversity**, and\n  * **uncertainties**.\n  \n\n### Main problems \n\n* **Harvesting implies incomes from forests**, but on the other hand, it **diminishes the recreational and esthetical values of the forest**, and it may have **adverse effects on the natural values of the area**, for instance, the biodiversity within the area and the viability of wildlife populations living in the area.\n\n* On the other hand, forest management planning **involves lots of uncertainty**. It is **not possible to measure all trees** within a forest area, so there is **uncertainty concerning the current state** of the forests. **Measuring biodiversity is prohibitively expensive**, so using **proxy variables** (biodiversity indices) is the only possibility.\n\n* All forest decisions **concern the future** (typically the next 5-20 years), so that the **state of the forest stands and biodiversity and the consequences of the treatment options needs to be predicted** using statistical models. As we do not know the exact consequences of the decisions, the **decisions involve uncertainty which the decision makers may wish to manage.**\n\n## The approach\n\n* Model the decision problem as a six-objective optimization problem\n* Model uncertainty using scenario based-approach\n  * Different scenarios represent possible future states\n* Handle the uncertainty using a well known risk measure called \"value-at-risk\" with different risk levels\n* Objectives to be maximized\n  1. Expected minimum (over all time periods) income in all the scenarios.\n  2. Expected minimum (over all time periods) biodiversity in all the scenarios\n  3. Value of the biodiversity at the given risk\n  4. Value of the income at the given risk \n  5. Probability of the income being greater than the value-at-risk.  The risk level for income is, thus, one minus this probability.\n  6. Probability of the biodiversity being greater than the value-at-risk.  The risk level for biodiversity is, thus, one minus this probability.\n\n## Multiobjective optimization results\n\n* The decision maker was able to study interdependencies between income and biodiversity, gains and losses in income and biodiversity at different risk levels and risk levels associated to these\n* <a href=\"http://link.springer.com/chapter/10.1007/978-3-319-51469-7_2\">The results were presented at the MOD2016 workshop</a>\n\n\n## Example 6: Interactive multiobjective optimization for finding the most preferred exercise therapy modality in knee osteoarthritis\n\n* Babooshka Shavazipour, Bekir Afsar, Juhani Multanen, Kaisa Miettinen & Urho M. Kujala (2022) Interactive multiobjective optimization for finding the most preferred exercise therapy modality in knee osteoarthritis, Annals of Medicine, 54:1, 181-194, <a href=\"https://www.tandfonline.com/doi/pdf/10.1080/07853890.2021.2024876\">DOI:10.1080/07853890.2021.2024876</a>\n\n* A joint study of Faculty of Information Technology and Faculty of Sport and Health Sciences at University of Jyvaskyla.\\\\\n\n* **Aim:**  Developing a decision support tool to support healthcare professionals in comparing different modalities (in terms of on multiple criterai) and identifying the most preferred one based on a patient\u2019s needs.\n  \n\n* Model the decision problem as a five-objective optimization problem.\n\n**Optimization problem:**\n\n* Minimize the cost of therapy\n* Maximize expected net improvement in pain reduction\n* Maximize expected net improvement in physical function\n* Minimize the number of supervised training sessions\n* Minimize the length of treatment\n\n Subject to one therapy is selected from a list of options:\n\n\n* Thirty-one exercise therapy modalities were considered\n* A novel interactive multiobjective optimization model was designed to characterize the efficacy of an exercise therapy modality based on five objectives\n* An interactive model incorporates clinicians\u2019 preferences in finding the most preferred exercise therapy modality for each need.\n* The proposed methodology is generic enough to be applied in any field of medical and healthcare settings, where several alternative treatment options exist.\n\n## Mathematical formulation of multiobjective optimization problems\n\nMultiobjective optimization problems are often formulated as\n$$\n\\begin{align} \\\n\\min \\quad &\\{f_1(x),\\ldots,f_k(x)\\}\\\\\n\\text{s.t.} \\quad & g_j(x) \\geq 0\\text{ for all }j=1,\\ldots,J\\\\\n& h_q(x) = 0\\text{ for all }q=1,\\ldots,Q\\\\\n&a_i\\leq x_i\\leq b_i\\text{ for all } i=1,\\ldots,n\\\\\n&x\\in \\mathbb R^n,\n\\end{align}\n$$\nwhere $$f_1,\\ldots,f_k:\\{x\\in\\mathbb R^n: g_j(x) \\geq 0 \\text{ for all }j=1,\\ldots,J \\text{ and } h_q(x) = 0\\text{ for all }q=1,\\ldots,Q\\}\\mapsto\\mathbb R$$ are the objective functions.\n\n## Basic concepts\n\n* Basic concepts of solution, feasible solution, equality and inequality constraints are the same.\n\n* However, all the objectives do not have the same optimal solution\n\n* The concept of optimality needs to redefined. *How to define optimality for multiple objectives?* \n\n## Optimality in the objective space (Image of the feasible region)\n*Which solution is better?*\n\n\n## Optimality in the objective space (Image of the feasible region)\n*Which of the red solutions is better?*\n\n\n## Optimality in the objective space (Image of the feasible region)\n*Where are optimal solutions?*\n\n\n## Optimality in the objective space (Image of the feasible region)\n*Optimal solutions are located at the boundary to the down & left (for minimization problems)*\n\n\n## Pareto optimality\nA feasible solution $x_1$ is Pareto optimal to the multiobjective optimization problem, if there does not exist a feasible solution $x_2$, $x_1\\neq x_2$, such that \n$$\n\\left\\{\n\\begin{align}\n&f_i(x_2)\\leq f_i(x_1)\\text{ for all }i\\in \\{1,\\ldots,k\\}\\\\\n&f_j(x_2)<f_j(x_1)\\text{ for some }j\\in \\{1,\\ldots,k\\}.\\\\\n\\end{align}\n\\right.\n$$\n\n\n\nThere are now two spaces connected to the problem: the space $\\mathbb R^n$ is called the decision space and $\\mathbb R^k$ is called the objective space.\n\n**Problem having two objectives is a special case: Let us assume that $x$ is Pareto optimal. if we want to improve one of the objectives at point $x$, we know that the value of the other objective has to impair.**\n\nIn other words: **A solution is Pareto optimal if none of the objectives can be improved without impairing at least one of the others**\n\nIt means:                   \n$$\n\\text{\u201cTake from Sami to pay Anna\u201d}\n$$\n\n**Usually there exist multiple Pareto optimal solutions to a problem (can be infinitely many).**\n\n**all of them mathematically incomparable**\n\n**How to choose (the best) one?**\n\n**the most preferred one needs to be selected for implementation. Thus, a decision maker is needed.**\n", "meta": {"hexsha": "84b92872b0ffec98aa81cb8c004cd472668dc7da", "size": 284355, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lecture 10, Introduction to multiobjective optimization.ipynb", "max_stars_repo_name": "bshavazipour/TIES483-2022", "max_stars_repo_head_hexsha": "93dfabbfe1e953e5c5f83c44412963505ecf575a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lecture 10, Introduction to multiobjective optimization.ipynb", "max_issues_repo_name": "bshavazipour/TIES483-2022", "max_issues_repo_head_hexsha": "93dfabbfe1e953e5c5f83c44412963505ecf575a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lecture 10, Introduction to multiobjective optimization.ipynb", "max_forks_repo_name": "bshavazipour/TIES483-2022", "max_forks_repo_head_hexsha": "93dfabbfe1e953e5c5f83c44412963505ecf575a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-03T09:40:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T09:40:02.000Z", "avg_line_length": 387.9331514325, "max_line_length": 264080, "alphanum_fraction": 0.9401593079, "converted": true, "num_tokens": 2508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13117322376181564, "lm_q2_score": 0.22270014398423357, "lm_q1q2_score": 0.029212295818632432}}
{"text": "```python\n!pip install qiskit\n```\n\n    Collecting qiskit\n      Downloading qiskit-0.33.0.tar.gz (13 kB)\n    Collecting qiskit-terra==0.19.0\n      Downloading qiskit_terra-0.19.0-cp37-cp37m-manylinux2010_x86_64.whl (6.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.4 MB 4.7 MB/s \n    \u001b[?25hCollecting qiskit-aer==0.9.1\n      Downloading qiskit_aer-0.9.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (17.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 17.9 MB 621 kB/s \n    \u001b[?25hCollecting qiskit-ibmq-provider==0.18.1\n      Downloading qiskit_ibmq_provider-0.18.1-py3-none-any.whl (237 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 237 kB 61.4 MB/s \n    \u001b[?25hCollecting qiskit-ignis==0.7.0\n      Downloading qiskit_ignis-0.7.0-py3-none-any.whl (200 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 200 kB 59.1 MB/s \n    \u001b[?25hRequirement already satisfied: scipy>=1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.9.1->qiskit) (1.4.1)\n    Requirement already satisfied: numpy>=1.16.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.9.1->qiskit) (1.19.5)\n    Collecting requests-ntlm>=1.1.0\n      Downloading requests_ntlm-1.1.0-py2.py3-none-any.whl (5.7 kB)\n    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.1->qiskit) (1.24.3)\n    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.1->qiskit) (2.23.0)\n    Collecting websocket-client>=1.0.1\n      Downloading websocket_client-1.2.3-py3-none-any.whl (53 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 53 kB 2.0 MB/s \n    \u001b[?25hRequirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.1->qiskit) (2.8.2)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ignis==0.7.0->qiskit) (57.4.0)\n    Collecting retworkx>=0.8.0\n      Downloading retworkx-0.10.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.4 MB 34.7 MB/s \n    \u001b[?25hCollecting symengine>=0.8\n      Downloading symengine-0.8.1-cp37-cp37m-manylinux2010_x86_64.whl (38.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 38.2 MB 1.3 MB/s \n    \u001b[?25hCollecting stevedore>=3.0.0\n      Downloading stevedore-3.5.0-py3-none-any.whl (49 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 49 kB 6.2 MB/s \n    \u001b[?25hRequirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.0->qiskit) (1.7.1)\n    Collecting python-constraint>=1.4\n      Downloading python-constraint-1.4.0.tar.bz2 (18 kB)\n    Collecting scipy>=1.0\n      Downloading scipy-1.7.3-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (38.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 38.1 MB 1.3 MB/s \n    \u001b[?25hCollecting tweedledum<2.0,>=1.1\n      Downloading tweedledum-1.1.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (943 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 943 kB 45.1 MB/s \n    \u001b[?25hRequirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.0->qiskit) (5.4.8)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.0->qiskit) (0.3.4)\n    Collecting ply>=3.10\n      Downloading ply-3.11-py2.py3-none-any.whl (49 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 49 kB 6.1 MB/s \n    \u001b[?25hRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.8.0->qiskit-ibmq-provider==0.18.1->qiskit) (1.15.0)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.1->qiskit) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.1->qiskit) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.1->qiskit) (2021.10.8)\n    Collecting cryptography>=1.3\n      Downloading cryptography-36.0.0-cp36-abi3-manylinux_2_24_x86_64.whl (3.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.6 MB 19.7 MB/s \n    \u001b[?25hCollecting ntlm-auth>=1.0.2\n      Downloading ntlm_auth-1.5.0-py2.py3-none-any.whl (29 kB)\n    Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.1->qiskit) (1.15.0)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.1->qiskit) (2.21)\n    Requirement already satisfied: importlib-metadata>=1.7.0 in /usr/local/lib/python3.7/dist-packages (from stevedore>=3.0.0->qiskit-terra==0.19.0->qiskit) (4.8.2)\n    Collecting pbr!=2.1.0,>=2.0.0\n      Downloading pbr-5.8.0-py2.py3-none-any.whl (112 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 112 kB 60.6 MB/s \n    \u001b[?25hRequirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=1.7.0->stevedore>=3.0.0->qiskit-terra==0.19.0->qiskit) (3.10.0.2)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=1.7.0->stevedore>=3.0.0->qiskit-terra==0.19.0->qiskit) (3.6.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra==0.19.0->qiskit) (1.2.1)\n    Building wheels for collected packages: qiskit, python-constraint\n      Building wheel for qiskit (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for qiskit: filename=qiskit-0.33.0-py3-none-any.whl size=11763 sha256=f90de4a758faa8aa63936577ad98bb51caac39aab1bd172ede9b614391fd1766\n      Stored in directory: /root/.cache/pip/wheels/d4/60/ef/c49ae113df02818c4ade5fb6e2e89bb928625412eda0bb25f5\n      Building wheel for python-constraint (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for python-constraint: filename=python_constraint-1.4.0-py2.py3-none-any.whl size=24081 sha256=652bafd2fd27167bd2a4e6743482be7f82ceac223e922cd6fd72e9aa45c1437c\n      Stored in directory: /root/.cache/pip/wheels/07/27/db/1222c80eb1e431f3d2199c12569cb1cac60f562a451fe30479\n    Successfully built qiskit python-constraint\n    Installing collected packages: pbr, tweedledum, symengine, stevedore, scipy, retworkx, python-constraint, ply, ntlm-auth, cryptography, websocket-client, requests-ntlm, qiskit-terra, qiskit-ignis, qiskit-ibmq-provider, qiskit-aer, qiskit\n      Attempting uninstall: scipy\n        Found existing installation: scipy 1.4.1\n        Uninstalling scipy-1.4.1:\n          Successfully uninstalled scipy-1.4.1\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Successfully installed cryptography-36.0.0 ntlm-auth-1.5.0 pbr-5.8.0 ply-3.11 python-constraint-1.4.0 qiskit-0.33.0 qiskit-aer-0.9.1 qiskit-ibmq-provider-0.18.1 qiskit-ignis-0.7.0 qiskit-terra-0.19.0 requests-ntlm-1.1.0 retworkx-0.10.2 scipy-1.7.3 stevedore-3.5.0 symengine-0.8.1 tweedledum-1.1.1 websocket-client-1.2.3\n\n\n\n```python\nimport qiskit\nfrom qiskit.circuit.random import random_circuit\nfrom qiskit import transpile, assemble\n```\n\n\n```python\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport torch\nimport torch.utils.data\nfrom torch.autograd import Function\nfrom torchvision import datasets, transforms\nimport torch.optim as optim\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom itertools import combinations\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom __future__ import print_function\n\nimport os\nimport sys\n```\n\n\n```python\n#Custom library\n'''\nsys.path.append(\"../LQDNN\")\nsys.path.append(\"../LQDNN/model\")\nsys.path.append(\"../LQDNN/dynamics\")\n'''\nsys.path.append(\"./sample_data\")\nfrom visualize import *\nfrom ode_solver import *\nfrom network import *\nfrom dataloader import *\nfrom lagrangian import *\n```\n\n\n```python\nprint(\"Loading training and test data...\")\ntrain_data = np.load('/content/sample_data/train_dataset.npz')\ntrain_inputs = train_data[\"input\"]\ntrain_labels = train_data[\"labels\"]\n\n#train_dataset = DynamicsDataset(train_inputs, train_labels)\nX_train = train_inputs[:1000]\ny_train = train_labels[:1000]\n\n#train_dataset = DynamicsDataset(train_inputs, train_labels)\ntrain_dataset = DynamicsDataset(X_train, y_train)\n\ntrain_dataloader = torch.utils.data.DataLoader(train_dataset,\n                                                 batch_size=1,\n                                                 shuffle=True,\n                                                 collate_fn=DynamicsDataset.collate_fn,\n                                                 pin_memory=True,\n                                                 num_workers=1)\ntest_data = np.load('/content/sample_data/val_dataset.npz')\ntest_inputs = train_data[\"input\"]\ntest_labels = train_data[\"labels\"]\n#print(len(test_inputs))\nX_test = test_inputs[:1000]\ny_test = test_labels[:1000]\n\ntest_dataset = DynamicsDataset(X_test, y_test)\n\ntest_dataloader = torch.utils.data.DataLoader(test_dataset,\n                                                 batch_size=1,\n                                                 shuffle=False,\n                                                 collate_fn=DynamicsDataset.collate_fn,\n                                                 pin_memory=True,\n                                                 num_workers=1)\nprint(\"Loading training and test data completed\")\n```\n\n    Loading training and test data...\n    Loading training and test data completed\n\n\n\n```python\nfor (X_train, y_train) in train_dataloader:\n    print('X_train:', X_train.size(), 'type:', X_train.type())\n    print('y_train:', y_train.size(), 'type:', y_train.type())\n    print('X_train:', X_train)\n    print('y_train:', y_train)\n    break\n\nfor (X_test, y_test) in test_dataloader:\n    print('X_test:', X_test.size(), 'type:', X_test.type())\n    print('y_test:', y_test.size(), 'type:', y_test.type())\n    print('X_test:', X_test)\n    print('y_test:', y_test)\n    break\n```\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    X_train: torch.Size([1, 4]) type: torch.DoubleTensor\n    y_train: torch.Size([1, 4]) type: torch.DoubleTensor\n    X_train: tensor([[ 0.4006, -2.1999, -0.1462, -0.0383]], dtype=torch.float64)\n    y_train: tensor([[-0.1462, -0.0383, -0.6669,  7.3712]], dtype=torch.float64)\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    X_test: torch.Size([1, 4]) type: torch.DoubleTensor\n    y_test: torch.Size([1, 4]) type: torch.DoubleTensor\n    X_test: tensor([[ 1.9537,  0.2797, -0.0780, -0.2268]], dtype=torch.float64)\n    y_test: tensor([[-0.0780, -0.2268, -9.3138, -3.6618]], dtype=torch.float64)\n\n\n\n```python\nclass QCircuit:\n    \"\"\" \n    This class defines filter circuit of Quanvolution layer\n    \"\"\"\n    \n    def __init__(self, num_qubit, backend, shots):\n        # --- Circuit definition start ---\n        self.n_qubits = num_qubit\n        self._circuit = qiskit.QuantumCircuit(self.n_qubits,2)\n        \n        all_qubits = [i for i in range(self.n_qubits)]        \n        self._circuit.h(all_qubits)\n        \n        self.theta = [qiskit.circuit.Parameter('theta{}'.format(i)) for i in range(self.n_qubits)]\n\n        for i in range(self.n_qubits):\n            self._circuit.rx(self.theta[i], i)\n        \n        self._circuit.cx(0,2)\n        self._circuit.cx(1,3)\n        \n        self._circuit.barrier()\n        \n        self._circuit.measure(2,0)\n        self._circuit.measure(3,1)\n        \n        # ---- Circuit definition end ----\n\n        self.backend   = backend\n        self.shots     = shots\n\n    def run(self, data):\n        ListTarget = []\n        for valT in data.detach().numpy():\n            for j in range(len(valT)):\n                ListTarget.append(valT[j])\n        param_dict = dict()\n        \n        i= 0\n        for theta in ListTarget:\n            param_dict[self.theta[i]] = theta#[i]\n            i += 1\n        param_binds = [param_dict]\n        \n        t_qc = transpile(self._circuit,\n                         self.backend)\n        qobj = assemble(t_qc,\n                        shots=self.shots,\n                        parameter_binds = param_binds)\n        job = self.backend.run(qobj)\n        result = job.result().get_counts()\n        \n        probabilities = []\n        counts = 0\n        for key, val in result.items():\n            cnt = sum([int(char) for char in key])\n            counts += cnt * val\n\n            # Compute probabilities for each state\n            probab = counts / (self.shots * self.n_qubits)\n            probabilities.append(probab)\n        \n        return probabilities\n```\n\n\n```python\n#Testing the circuit\nbackend = qiskit.Aer.get_backend('qasm_simulator')\nnum_qubit = 4\ncirc = QCircuit(num_qubit, backend, 100)\ndata = torch.tensor([[-0.2397, -2.9656, -0.1623, -0.0680]])\n\nprint(circ.run(data))\ncirc._circuit.draw()#output='mpl')\n```\n\n    [0.0, 0.0625, 0.1175, 0.2475]\n\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">     \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510           \u2591       \nq_0: \u2524 H \u251c\u2524 Rx(theta0) \u251c\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n     \u251c\u2500\u2500\u2500\u2524\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524  \u2502        \u2591       \nq_1: \u2524 H \u251c\u2524 Rx(theta1) \u251c\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n     \u251c\u2500\u2500\u2500\u2524\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u250c\u2500\u2534\u2500\u2510  \u2502   \u2591 \u250c\u2500\u2510   \nq_2: \u2524 H \u251c\u2524 Rx(theta2) \u251c\u2524 X \u251c\u2500\u2500\u253c\u2500\u2500\u2500\u2591\u2500\u2524M\u251c\u2500\u2500\u2500\n     \u251c\u2500\u2500\u2500\u2524\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2534\u2500\u2510 \u2591 \u2514\u2565\u2518\u250c\u2500\u2510\nq_3: \u2524 H \u251c\u2524 Rx(theta3) \u251c\u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\u2500\u2591\u2500\u2500\u256b\u2500\u2524M\u251c\n     \u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2518 \u2591  \u2551 \u2514\u2565\u2518\nc: 2/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\n                                      0  1 </pre>\n\n\n\n\n```python\nclass HybridFunction(Function):\n    \"\"\" Hybrid quantum - classical function definition \"\"\"\n    \n    @staticmethod\n    def forward(ctx, input, quantum_circuit, shift):\n        \"\"\" Forward pass computation \"\"\"\n        ##print('hFor:', input)\n        #print('hFor1:', input[0])\n        #print('hFor2:', input[0].tolist())\n        ctx.shift = shift\n        ctx.quantum_circuit = quantum_circuit\n        #expectation_z = []\n        #for i in range(len(input)):\n        #    expectation_z.append(ctx.quantum_circuit.run(input[i].tolist()))\n        #print('expectation_z',expectation_z)\n        expectation_z = ctx.quantum_circuit.run(input[0].tolist())\n        result = torch.tensor([expectation_z])\n        #result = torch.tensor(expectation_z)\n        ctx.save_for_backward(input, result)\n\n        return result\n        \n    @staticmethod\n    def backward(ctx, grad_output):\n        \"\"\" Backward pass computation \"\"\"\n        print('a')\n        input, expectation_z = ctx.saved_tensors\n        input_list = np.array(input.tolist())\n        \n        shift_right = input_list + np.ones(input_list.shape) * ctx.shift\n        shift_left = input_list - np.ones(input_list.shape) * ctx.shift\n        \n        gradients = []\n        for i in range(len(input_list)):\n            expectation_right = ctx.quantum_circuit.run(shift_right[i])\n            expectation_left  = ctx.quantum_circuit.run(shift_left[i])\n            \n            gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left])\n            gradients.append(gradient)\n        gradients = np.array([gradients]).T\n        return torch.tensor([gradients]).float() * grad_output.float(), None, None\n\nclass Hybrid(nn.Module):\n    \"\"\" Hybrid quantum - classical layer definition \"\"\"\n    \n    def __init__(self, backend, shots, shift):\n        super(Hybrid, self).__init__()\n        self.quantum_circuit = QuantumCircuit(1, backend, shots)\n        self.shift = shift\n        \n    def forward(self, input):\n        #print('3',input)\n        return HybridFunction.apply(input, self.quantum_circuit, self.shift)\n```\n\n\n```python\nclass LagrangianNeuralNetwork(torch.nn.Module):\n    def __init__(self, D_in, hidden_list, D_out):\n        \"\"\"\n        Neural Network used to approximate a paramaterized system lagrangian\n        \"\"\"\n        super(LagrangianNeuralNetwork, self).__init__()\n        self.model_layers = torch.nn.ModuleList()\n\n        # input layer\n        self.model_layers.append(torch.nn.Linear(D_in, hidden_list[0]))\n        self.model_layers.append(torch.nn.Softplus())\n        # add all hiden layers\n        for i in range(1, len(hidden_list)):\n            self.model_layers.append(torch.nn.Linear(hidden_list[i-1], hidden_list[i]))\n            self.model_layers.append(torch.nn.Softplus())\n        \n        # output layer\n        self.model_layers.append(torch.nn.Linear(hidden_list[-1], D_out))\n        self.model_layers.append(torch.nn.Softplus())\n\n    def forward(self, x):\n        \"\"\"\n        applies all of the model layers, and returns the single output value,\n        which in this case is the lagrangian of the system, representing the\n        total energy\n        \"\"\"\n        for layer in self.model_layers:\n            x = layer(x)        \n        return x\n```\n\n\n```python\n# determine device\nprint(\"--- Checking for CUDA Device... ---\")\nuse_cuda = torch.cuda.is_available()\ndevice = torch.device(\"cuda:0\" if use_cuda else \"cpu\")\nprint(device)\n```\n\n    --- Checking for CUDA Device... ---\n    cpu\n\n\n\n```python\n# organize data\ninput_size = train_inputs.shape[1]\noutput_size = 1  # for all lagrangian systems, output should be just a scalar energy value\n\n# build model\nprint(\"--- Constructing Model... ---\")\nD_in = input_size  # state size\n# hidden_list = [D_in, 256, 256, 256, 256, 256]\nhidden_list = [D_in, 32, 64, 128, 256, 512, 256, 128, 64, 32]\nD_out = output_size\nlnn_model = LagrangianNeuralNetwork(D_in, hidden_list, D_out)\n#summary(lnn_model, (1, 28, 28), device='cpu')\n# set up training parameters\nlearning_rate = 1e-4\nweight_decay = 1e-5\nmomentum = 0.9\nnum_epochs = 20\noptimizer = torch.optim.Adam(lnn_model.parameters(),\n                             lr=learning_rate,\n                             weight_decay=weight_decay)\n\nif os.path.isfile(\"model_weights.pth\"):\n    print(\"Re-loading existing weights!\")\n    checkpoint = torch.load(\"model_weights.pth\")\n    lnn_model.load_state_dict(checkpoint['model_state_dict'])\n    optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n```\n\n    --- Constructing Model... ---\n\n\n\n```python\n# ensure model is in train mode so gradients are properly calculated\nlnn_model.train()\n# load device to either GPU or CPU depending on hardware\nlnn_model.to(device)\n\n# set up loss function\nloss_fcn = torch.nn.MSELoss()\n\n# set up GradScaler to improve run speed\nscaler = torch.cuda.amp.GradScaler()\n\nprint(\"--- Beginning Training! ---\")\nloss_list = []\nlnn_model.train()\nfor epoch in range(num_epochs):\n    total_loss = []\n    for batch_idx, (data, target) in enumerate(train_dataloader):\n        data, target = data.to(device), target.to(device)\n        optimizer.zero_grad()\n        for p in lnn_model.parameters(): p.grad = None\n        \n        #Quantum layer for data encoding\n        backend = qiskit.Aer.get_backend('qasm_simulator')\n        num_qubit = 4\n        circ = QCircuit(num_qubit, backend, 100)\n        \n        #Encoding data and target\n        dataInput = torch.squeeze(torch.tensor(circ.run(data)))\n        targetData = torch.tensor(circ.run(target))\n        \n        with torch.cuda.amp.autocast():\n            target_pred = solve_euler_lagrange(lnn_model.forward, dataInput.float())            \n            loss = loss_fcn(target_pred.unsqueeze(0), targetData.float())\n            \n        # Backward pass\n        scaler.scale(loss).backward()\n        \n        # Optimize the weights\n        scaler.step(optimizer)\n        \n        # update the scale for next iteration\n        scaler.update()\n        \n        total_loss.append(loss.item())\n        \n    loss_list.append(sum(total_loss)/len(total_loss))\n    print('Training [{:.0f}%]\\tLoss: {:.4f}'.format(100. * (epoch + 1) / num_epochs, loss_list[-1]))\n\nprint('end')\n```\n\n    --- Beginning Training! ---\n\n\n    /usr/local/lib/python3.7/dist-packages/torch/cuda/amp/grad_scaler.py:115: UserWarning: torch.cuda.amp.GradScaler is enabled, but CUDA is not available.  Disabling.\n      warnings.warn(\"torch.cuda.amp.GradScaler is enabled, but CUDA is not available.  Disabling.\")\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n    /usr/local/lib/python3.7/dist-packages/torch/autocast_mode.py:141: UserWarning: User provided device_type of 'cuda', but CUDA is not available. Disabling\n      warnings.warn('User provided device_type of \\'cuda\\', but CUDA is not available. Disabling')\n    /usr/local/lib/python3.7/dist-packages/torch/nn/modules/loss.py:520: UserWarning: Using a target size (torch.Size([4])) that is different to the input size (torch.Size([1, 4])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.\n      return F.mse_loss(input, target, reduction=self.reduction)\n\n\n    Training [5%]\tLoss: 0.9506\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    Training [10%]\tLoss: 0.0107\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    Training [15%]\tLoss: 0.0101\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    Training [20%]\tLoss: 0.0098\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    Training [25%]\tLoss: 0.0094\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    Training [30%]\tLoss: 0.0100\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    Training [35%]\tLoss: 0.0105\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    Training [40%]\tLoss: 0.0100\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    Training [45%]\tLoss: 0.0102\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    Training [50%]\tLoss: 0.0099\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    Training [55%]\tLoss: 0.0095\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    Training [60%]\tLoss: 0.0099\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    Training [65%]\tLoss: 0.0098\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    Training [70%]\tLoss: 0.0090\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    Training [75%]\tLoss: 0.0094\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    Training [80%]\tLoss: 0.0090\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    Training [85%]\tLoss: 0.0091\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    Training [90%]\tLoss: 0.0088\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    Training [95%]\tLoss: 0.0087\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    Training [100%]\tLoss: 0.0086\n    end\n\n\n\n```python\nplt.plot(loss_list)\nplt.title('Hybrid LQDNN Quantum-Classical Training (Four qubit)')\nplt.xlabel('Training Iterations')\nplt.ylabel('Loss')\n```\n\n\n```python\nprint(\"--- Beginning Test! ---\")\nlnn_model.eval()\ntotal_lossTestHybridQC = []\ncorrectTestQC = 0\nfor batch_idx, (data, target) in enumerate(test_dataloader):\n    data, target = data.to(device), target.to(device)\n    \n    dataTest = torch.squeeze(torch.tensor(circ.run(data)))\n    targetTest = torch.tensor(circ.run(target))    \n    \n    with torch.cuda.amp.autocast():\n        target_pred = solve_euler_lagrange(lnn_model.forward, dataTest.float())\n        correctTestQC += target_pred.eq(targetTest.view_as(target_pred)).sum().item()\n        testLoss = loss_fcn(target_pred.unsqueeze(0), targetTest.float())       \n    total_lossTestHybridQC.append(testLoss.item())\n    \nbatch_size = 1\nprint('Performance on test data:\\tLoss: {:.4f}\\tAccuracy: {:.1f}%'.format(\n    sum(total_lossTestHybridQC) / len(total_lossTestHybridQC),\n    correctTestQC / len(test_dataloader) * 100 / batch_size)\n    )\n\nprint('end')\n```\n\n    --- Beginning Test! ---\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n    /usr/local/lib/python3.7/dist-packages/torch/autocast_mode.py:141: UserWarning: User provided device_type of 'cuda', but CUDA is not available. Disabling\n      warnings.warn('User provided device_type of \\'cuda\\', but CUDA is not available. Disabling')\n    /usr/local/lib/python3.7/dist-packages/torch/nn/modules/loss.py:520: UserWarning: Using a target size (torch.Size([4])) that is different to the input size (torch.Size([1, 4])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.\n      return F.mse_loss(input, target, reduction=self.reduction)\n\n\n    Performance on test data:\tLoss: 0.0085\tAccuracy: 0.5%\n    end\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "1174dbef3cec1483f57c0c66af92eb929b709845", "size": 65024, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Multiple_4Qubit_QC.ipynb", "max_stars_repo_name": "18819F-Project/ModellingDynamicalSystem", "max_stars_repo_head_hexsha": "2610385e38c4cff7c9cbe25e1c6801a3de9eaf69", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/Multiple_4Qubit_QC.ipynb", "max_issues_repo_name": "18819F-Project/ModellingDynamicalSystem", "max_issues_repo_head_hexsha": "2610385e38c4cff7c9cbe25e1c6801a3de9eaf69", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/Multiple_4Qubit_QC.ipynb", "max_forks_repo_name": "18819F-Project/ModellingDynamicalSystem", "max_forks_repo_head_hexsha": "2610385e38c4cff7c9cbe25e1c6801a3de9eaf69", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.739965096, "max_line_length": 13422, "alphanum_fraction": 0.6040538878, "converted": true, "num_tokens": 8753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814056194821861, "lm_q2_score": 0.10374862686637971, "lm_q1q2_score": 0.02919544661375976}}
{"text": "```python\nfrom pyvizml import CreateNBAData\nimport requests\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import PolynomialFeatures\n```\n\n\n```python\n# Initiation.\ncnb = CreateNBAData(2019)\nplayers = cnb.create_players_df()\n```\n\n    Creating players df...\n\n\n\n```python\nplayers\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>firstName</th>\n      <th>lastName</th>\n      <th>temporaryDisplayName</th>\n      <th>personId</th>\n      <th>teamId</th>\n      <th>jersey</th>\n      <th>isActive</th>\n      <th>pos</th>\n      <th>heightFeet</th>\n      <th>heightInches</th>\n      <th>heightMeters</th>\n      <th>weightPounds</th>\n      <th>weightKilograms</th>\n      <th>dateOfBirthUTC</th>\n      <th>nbaDebutYear</th>\n      <th>yearsPro</th>\n      <th>collegeName</th>\n      <th>lastAffiliation</th>\n      <th>country</th>\n      <th>isallStar</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Jaylen</td>\n      <td>Adams</td>\n      <td>Adams, Jaylen</td>\n      <td>1629121</td>\n      <td>1610612757</td>\n      <td>10</td>\n      <td>True</td>\n      <td>G</td>\n      <td>6</td>\n      <td>0</td>\n      <td>1.83</td>\n      <td>225</td>\n      <td>102.1</td>\n      <td>1996-05-04</td>\n      <td>2018</td>\n      <td>1</td>\n      <td>St. Bonaventure</td>\n      <td>St. Bonaventure/USA</td>\n      <td>USA</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Steven</td>\n      <td>Adams</td>\n      <td>Adams, Steven</td>\n      <td>203500</td>\n      <td>1610612760</td>\n      <td>12</td>\n      <td>True</td>\n      <td>C</td>\n      <td>6</td>\n      <td>11</td>\n      <td>2.11</td>\n      <td>265</td>\n      <td>120.2</td>\n      <td>1993-07-20</td>\n      <td>2013</td>\n      <td>6</td>\n      <td>Pittsburgh</td>\n      <td>Pittsburgh/New Zealand</td>\n      <td>New Zealand</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Bam</td>\n      <td>Adebayo</td>\n      <td>Adebayo, Bam</td>\n      <td>1628389</td>\n      <td>1610612748</td>\n      <td>13</td>\n      <td>True</td>\n      <td>C-F</td>\n      <td>6</td>\n      <td>9</td>\n      <td>2.06</td>\n      <td>255</td>\n      <td>115.7</td>\n      <td>1997-07-18</td>\n      <td>2017</td>\n      <td>2</td>\n      <td>Kentucky</td>\n      <td>Kentucky/USA</td>\n      <td>USA</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>LaMarcus</td>\n      <td>Aldridge</td>\n      <td>Aldridge, LaMarcus</td>\n      <td>200746</td>\n      <td>1610612759</td>\n      <td>12</td>\n      <td>True</td>\n      <td>C-F</td>\n      <td>6</td>\n      <td>11</td>\n      <td>2.11</td>\n      <td>250</td>\n      <td>113.4</td>\n      <td>1985-07-19</td>\n      <td>2006</td>\n      <td>13</td>\n      <td>Texas</td>\n      <td>Texas/USA</td>\n      <td>USA</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Kyle</td>\n      <td>Alexander</td>\n      <td>Alexander, Kyle</td>\n      <td>1629734</td>\n      <td>1610612748</td>\n      <td>17</td>\n      <td>True</td>\n      <td>F-C</td>\n      <td>6</td>\n      <td>10</td>\n      <td>2.08</td>\n      <td>216</td>\n      <td>98.0</td>\n      <td>1996-10-21</td>\n      <td>2019</td>\n      <td>0</td>\n      <td>Tennessee</td>\n      <td>Tennessee/Canada</td>\n      <td>Canada</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>505</th>\n      <td>Trae</td>\n      <td>Young</td>\n      <td>Young, Trae</td>\n      <td>1629027</td>\n      <td>1610612737</td>\n      <td>11</td>\n      <td>True</td>\n      <td>G</td>\n      <td>6</td>\n      <td>1</td>\n      <td>1.85</td>\n      <td>180</td>\n      <td>81.6</td>\n      <td>1998-09-19</td>\n      <td>2018</td>\n      <td>1</td>\n      <td>Oklahoma</td>\n      <td>University of Oklahoma/USA</td>\n      <td>USA</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>506</th>\n      <td>Cody</td>\n      <td>Zeller</td>\n      <td>Zeller, Cody</td>\n      <td>203469</td>\n      <td>1610612766</td>\n      <td>40</td>\n      <td>True</td>\n      <td>F-C</td>\n      <td>7</td>\n      <td>0</td>\n      <td>2.13</td>\n      <td>240</td>\n      <td>108.9</td>\n      <td>1992-10-05</td>\n      <td>2013</td>\n      <td>6</td>\n      <td>Indiana</td>\n      <td>Indiana/USA</td>\n      <td>USA</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>507</th>\n      <td>Tyler</td>\n      <td>Zeller</td>\n      <td>Zeller, Tyler</td>\n      <td>203092</td>\n      <td>1610612759</td>\n      <td>40</td>\n      <td>True</td>\n      <td>F-C</td>\n      <td>6</td>\n      <td>11</td>\n      <td>2.11</td>\n      <td>250</td>\n      <td>113.4</td>\n      <td>1990-01-17</td>\n      <td>2012</td>\n      <td>7</td>\n      <td>North Carolina</td>\n      <td>North Carolina/USA</td>\n      <td>USA</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>508</th>\n      <td>Ante</td>\n      <td>Zizic</td>\n      <td>Zizic, Ante</td>\n      <td>1627790</td>\n      <td>1610612739</td>\n      <td>41</td>\n      <td>True</td>\n      <td>C</td>\n      <td>6</td>\n      <td>10</td>\n      <td>2.08</td>\n      <td>266</td>\n      <td>120.7</td>\n      <td>1997-01-04</td>\n      <td>2017</td>\n      <td>2</td>\n      <td></td>\n      <td>Darussafaka (Turkey)/Croatia</td>\n      <td>Croatia</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>509</th>\n      <td>Ivica</td>\n      <td>Zubac</td>\n      <td>Zubac, Ivica</td>\n      <td>1627826</td>\n      <td>1610612746</td>\n      <td>40</td>\n      <td>True</td>\n      <td>C</td>\n      <td>7</td>\n      <td>0</td>\n      <td>2.13</td>\n      <td>240</td>\n      <td>108.9</td>\n      <td>1997-03-18</td>\n      <td>2016</td>\n      <td>3</td>\n      <td></td>\n      <td>Mega Leks/Croatia</td>\n      <td>Croatia</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n<p>510 rows \u00d7 20 columns</p>\n</div>\n\n\n\n\n```python\nX = players['heightMeters'].values\n```\n\n\n```python\nX\n```\n\n\n\n\n    array(['1.83', '2.11', '2.06', '2.11', '2.08', '1.96', '1.93', '2.11',\n           '2.03', '1.96', '2.06', '2.11', '2.08', '1.98', '2.03', '2.01',\n           '1.9', '2.03', '1.8', '2.11', '1.98', '2.11', '1.98', '2.13',\n           '1.78', '2.03', '1.98', '1.96', '2.03', '2.06', '2.08', '1.93',\n           '2.03', '1.9', '1.93', '1.96', '2.03', '1.96', '2.08', '1.85',\n           '2.06', '2.11', '2.03', '2.08', '1.85', '1.98', '2.03', '2.18',\n           '1.9', '2.03', '1.96', '2.06', '1.98', '1.85', '1.9', '2.08',\n           '1.96', '1.98', '2.06', '1.98', '1.98', '2.01', '1.98', '1.96',\n           '2.01', '1.93', '1.98', '2.18', '1.96', '1.98', '1.98', '1.85',\n           '2.08', '1.98', '1.83', '1.98', '1.93', '2.01', '2.06', '2.03',\n           '1.96', '2.03', '2.08', '1.98', '1.85', '1.98', '2.06', '1.96',\n           '1.96', '2.13', '2.13', '2.03', '1.96', '1.8', '2.06', '1.98',\n           '2.03', '1.93', '2.11', '1.75', '1.96', '2.01', '2.06', '2.11',\n           '1.85', '1.96', '1.85', '2.03', '2.01', '2.01', '1.96', '1.98',\n           '1.98', '1.88', '1.9', '1.93', '2.08', '2.06', '1.93', '2.13',\n           '1.9', '1.98', '2.03', '1.96', '2.08', '1.96', '1.93', '2.01',\n           '1.9', '1.96', '2.03', '1.98', '1.9', '2.08', '1.98', '1.9',\n           '2.08', '1.8', '1.93', '2.13', '1.98', '2.06', '1.93', '1.96',\n           '2.26', '2.06', '2.08', '1.98', '2.06', '1.83', '2.01', '1.88',\n           '2.01', '1.9', '1.9', '1.96', '1.9', '2.06', '2.08', '2.08',\n           '1.85', '1.85', '2.11', '2.03', '2.03', '2.06', '2.11', '1.96',\n           '2.16', '1.83', '2.03', '1.9', '1.85', '1.96', '2.03', '1.93',\n           '1.83', '1.98', '1.98', '2.03', '1.93', '2.03', '2.06', '1.98',\n           '1.85', '2.03', '1.96', '2.06', '1.96', '1.96', '2.01', '1.78',\n           '2.01', '1.93', '1.98', '2.03', '2.01', '1.96', '2.03', '2.11',\n           '2.01', '2.06', '2.08', '2.06', '2.11', '1.96', '2.06', '2.03',\n           '1.93', '1.9', '1.98', '2.03', '1.83', '1.9', '1.98', '1.98',\n           '2.08', '2.03', '2.06', '1.93', '1.98', '2.08', '2.03', '2.01',\n           '2.01', '2.01', '2.13', '1.98', '2.06', '2.01', '2.01', '1.88',\n           '2.11', '1.98', '1.9', '2.03', '2.01', '1.9', '2.11', '2.01',\n           '2.06', '1.96', '1.96', '2.01', '2.01', '2.03', '2.01', '1.96',\n           '1.98', '1.9', '2.13', '2.11', '1.83', '1.98', '2.11', '1.9',\n           '2.06', '2.13', '2.08', '1.96', '1.98', '2.01', '2.08', '1.88',\n           '2.01', '1.96', '2.01', '2.18', '2.01', '2.06', '2.03', '2.08',\n           '1.96', '1.93', '1.98', '2.01', '2.03', '2.08', '1.93', '1.96',\n           '1.96', '2.13', '2.01', '2.13', '1.98', '1.88', '1.96', '2.06',\n           '2.13', '2.13', '2.03', '1.83', '2.01', '2.06', '2.11', '2.13',\n           '1.96', '2.24', '2.13', '1.96', '1.96', '1.88', '1.96', '1.8',\n           '1.96', '1.93', '2.03', '2.01', '1.9', '1.85', '2.08', '2.01',\n           '2.13', '1.93', '2.01', '1.8', '1.9', '1.96', '2.06', '1.88',\n           '2.06', '2.01', '1.98', '2.01', '1.85', '2.01', '1.96', '1.85',\n           '1.9', '1.96', '1.9', '1.88', '1.9', '1.9', '2.01', '2.03', '1.88',\n           '2.03', '2.03', '1.9', '1.9', '1.93', '1.93', '2.06', '2.08',\n           '2.01', '1.96', '2.01', '1.83', '1.85', '2.01', '2.11', '2.08',\n           '1.93', '1.93', '1.88', '2.13', '1.96', '1.93', '2.06', '1.98',\n           '2.08', '1.9', '1.93', '2.03', '1.93', '2.11', '1.96', '2.01',\n           '2.01', '2.08', '2.03', '1.98', '2.18', '2.03', '2.11', '1.85',\n           '1.85', '1.9', '1.9', '2.08', '1.96', '2.11', '2.16', '2.13',\n           '1.93', '2.11', '1.93', '2.08', '2.03', '2.08', '2.21', '2.08',\n           '1.9', '2.01', '2.03', '1.93', '2.03', '1.9', '2.06', '2.01',\n           '1.96', '1.9', '2.01', '2.01', '1.93', '2.13', '1.98', '2.03',\n           '1.85', '1.88', '1.98', '1.85', '1.9', '1.93', '2.11', '2.08',\n           '2.01', '2.08', '2.01', '1.96', '1.85', '2.01', '1.98', '1.85',\n           '1.93', '1.96', '2.06', '2.03', '2.08', '1.96', '1.9', '2.08',\n           '1.9', '1.83', '1.98', '1.9', '1.88', '1.98', '2.06', '2.03',\n           '1.96', '1.93', '2.06', '2.03', '1.9', '1.96', '2.03', '1.9',\n           '2.03', '1.93', '1.98', '2.06', '1.93', '1.96', '2.03', '1.98',\n           '2.11', '1.96', '1.96', '1.9', '1.98', '2.11', '2.06', '2.11',\n           '1.93', '2.06', '1.85', '1.9', '2.08', '2.11', '2.06', '2.11',\n           '1.9', '1.83', '1.96', '1.93', '1.9', '2.03', '2.01', '2.03',\n           '1.78', '1.98', '1.9', '1.9', '1.93', '1.93', '2.13', '2.01',\n           '1.98', '2.06', '1.98', '1.85', '2.03', '1.88', '2.03', '1.98',\n           '2.08', '1.98', '1.98', '2.08', '2.03', '1.96', '1.83', '2.03',\n           '1.85', '2.13', '2.11', '2.08', '2.13'], dtype=object)\n\n\n\n\n```python\nX = players['heightMeters'].values.astype(float)\n```\n\n\n```python\nX\n```\n\n\n\n\n    array([1.83, 2.11, 2.06, 2.11, 2.08, 1.96, 1.93, 2.11, 2.03, 1.96, 2.06,\n           2.11, 2.08, 1.98, 2.03, 2.01, 1.9 , 2.03, 1.8 , 2.11, 1.98, 2.11,\n           1.98, 2.13, 1.78, 2.03, 1.98, 1.96, 2.03, 2.06, 2.08, 1.93, 2.03,\n           1.9 , 1.93, 1.96, 2.03, 1.96, 2.08, 1.85, 2.06, 2.11, 2.03, 2.08,\n           1.85, 1.98, 2.03, 2.18, 1.9 , 2.03, 1.96, 2.06, 1.98, 1.85, 1.9 ,\n           2.08, 1.96, 1.98, 2.06, 1.98, 1.98, 2.01, 1.98, 1.96, 2.01, 1.93,\n           1.98, 2.18, 1.96, 1.98, 1.98, 1.85, 2.08, 1.98, 1.83, 1.98, 1.93,\n           2.01, 2.06, 2.03, 1.96, 2.03, 2.08, 1.98, 1.85, 1.98, 2.06, 1.96,\n           1.96, 2.13, 2.13, 2.03, 1.96, 1.8 , 2.06, 1.98, 2.03, 1.93, 2.11,\n           1.75, 1.96, 2.01, 2.06, 2.11, 1.85, 1.96, 1.85, 2.03, 2.01, 2.01,\n           1.96, 1.98, 1.98, 1.88, 1.9 , 1.93, 2.08, 2.06, 1.93, 2.13, 1.9 ,\n           1.98, 2.03, 1.96, 2.08, 1.96, 1.93, 2.01, 1.9 , 1.96, 2.03, 1.98,\n           1.9 , 2.08, 1.98, 1.9 , 2.08, 1.8 , 1.93, 2.13, 1.98, 2.06, 1.93,\n           1.96, 2.26, 2.06, 2.08, 1.98, 2.06, 1.83, 2.01, 1.88, 2.01, 1.9 ,\n           1.9 , 1.96, 1.9 , 2.06, 2.08, 2.08, 1.85, 1.85, 2.11, 2.03, 2.03,\n           2.06, 2.11, 1.96, 2.16, 1.83, 2.03, 1.9 , 1.85, 1.96, 2.03, 1.93,\n           1.83, 1.98, 1.98, 2.03, 1.93, 2.03, 2.06, 1.98, 1.85, 2.03, 1.96,\n           2.06, 1.96, 1.96, 2.01, 1.78, 2.01, 1.93, 1.98, 2.03, 2.01, 1.96,\n           2.03, 2.11, 2.01, 2.06, 2.08, 2.06, 2.11, 1.96, 2.06, 2.03, 1.93,\n           1.9 , 1.98, 2.03, 1.83, 1.9 , 1.98, 1.98, 2.08, 2.03, 2.06, 1.93,\n           1.98, 2.08, 2.03, 2.01, 2.01, 2.01, 2.13, 1.98, 2.06, 2.01, 2.01,\n           1.88, 2.11, 1.98, 1.9 , 2.03, 2.01, 1.9 , 2.11, 2.01, 2.06, 1.96,\n           1.96, 2.01, 2.01, 2.03, 2.01, 1.96, 1.98, 1.9 , 2.13, 2.11, 1.83,\n           1.98, 2.11, 1.9 , 2.06, 2.13, 2.08, 1.96, 1.98, 2.01, 2.08, 1.88,\n           2.01, 1.96, 2.01, 2.18, 2.01, 2.06, 2.03, 2.08, 1.96, 1.93, 1.98,\n           2.01, 2.03, 2.08, 1.93, 1.96, 1.96, 2.13, 2.01, 2.13, 1.98, 1.88,\n           1.96, 2.06, 2.13, 2.13, 2.03, 1.83, 2.01, 2.06, 2.11, 2.13, 1.96,\n           2.24, 2.13, 1.96, 1.96, 1.88, 1.96, 1.8 , 1.96, 1.93, 2.03, 2.01,\n           1.9 , 1.85, 2.08, 2.01, 2.13, 1.93, 2.01, 1.8 , 1.9 , 1.96, 2.06,\n           1.88, 2.06, 2.01, 1.98, 2.01, 1.85, 2.01, 1.96, 1.85, 1.9 , 1.96,\n           1.9 , 1.88, 1.9 , 1.9 , 2.01, 2.03, 1.88, 2.03, 2.03, 1.9 , 1.9 ,\n           1.93, 1.93, 2.06, 2.08, 2.01, 1.96, 2.01, 1.83, 1.85, 2.01, 2.11,\n           2.08, 1.93, 1.93, 1.88, 2.13, 1.96, 1.93, 2.06, 1.98, 2.08, 1.9 ,\n           1.93, 2.03, 1.93, 2.11, 1.96, 2.01, 2.01, 2.08, 2.03, 1.98, 2.18,\n           2.03, 2.11, 1.85, 1.85, 1.9 , 1.9 , 2.08, 1.96, 2.11, 2.16, 2.13,\n           1.93, 2.11, 1.93, 2.08, 2.03, 2.08, 2.21, 2.08, 1.9 , 2.01, 2.03,\n           1.93, 2.03, 1.9 , 2.06, 2.01, 1.96, 1.9 , 2.01, 2.01, 1.93, 2.13,\n           1.98, 2.03, 1.85, 1.88, 1.98, 1.85, 1.9 , 1.93, 2.11, 2.08, 2.01,\n           2.08, 2.01, 1.96, 1.85, 2.01, 1.98, 1.85, 1.93, 1.96, 2.06, 2.03,\n           2.08, 1.96, 1.9 , 2.08, 1.9 , 1.83, 1.98, 1.9 , 1.88, 1.98, 2.06,\n           2.03, 1.96, 1.93, 2.06, 2.03, 1.9 , 1.96, 2.03, 1.9 , 2.03, 1.93,\n           1.98, 2.06, 1.93, 1.96, 2.03, 1.98, 2.11, 1.96, 1.96, 1.9 , 1.98,\n           2.11, 2.06, 2.11, 1.93, 2.06, 1.85, 1.9 , 2.08, 2.11, 2.06, 2.11,\n           1.9 , 1.83, 1.96, 1.93, 1.9 , 2.03, 2.01, 2.03, 1.78, 1.98, 1.9 ,\n           1.9 , 1.93, 1.93, 2.13, 2.01, 1.98, 2.06, 1.98, 1.85, 2.03, 1.88,\n           2.03, 1.98, 2.08, 1.98, 1.98, 2.08, 2.03, 1.96, 1.83, 2.03, 1.85,\n           2.13, 2.11, 2.08, 2.13])\n\n\n\n\n```python\nX = players['heightMeters'].values.astype(float).reshape(-1, 1)\n```\n\n\n```python\nX\n```\n\n\n\n\n    array([[1.83],\n           [2.11],\n           [2.06],\n           [2.11],\n           [2.08],\n           [1.96],\n           [1.93],\n           [2.11],\n           [2.03],\n           [1.96],\n           [2.06],\n           [2.11],\n           [2.08],\n           [1.98],\n           [2.03],\n           [2.01],\n           [1.9 ],\n           [2.03],\n           [1.8 ],\n           [2.11],\n           [1.98],\n           [2.11],\n           [1.98],\n           [2.13],\n           [1.78],\n           [2.03],\n           [1.98],\n           [1.96],\n           [2.03],\n           [2.06],\n           [2.08],\n           [1.93],\n           [2.03],\n           [1.9 ],\n           [1.93],\n           [1.96],\n           [2.03],\n           [1.96],\n           [2.08],\n           [1.85],\n           [2.06],\n           [2.11],\n           [2.03],\n           [2.08],\n           [1.85],\n           [1.98],\n           [2.03],\n           [2.18],\n           [1.9 ],\n           [2.03],\n           [1.96],\n           [2.06],\n           [1.98],\n           [1.85],\n           [1.9 ],\n           [2.08],\n           [1.96],\n           [1.98],\n           [2.06],\n           [1.98],\n           [1.98],\n           [2.01],\n           [1.98],\n           [1.96],\n           [2.01],\n           [1.93],\n           [1.98],\n           [2.18],\n           [1.96],\n           [1.98],\n           [1.98],\n           [1.85],\n           [2.08],\n           [1.98],\n           [1.83],\n           [1.98],\n           [1.93],\n           [2.01],\n           [2.06],\n           [2.03],\n           [1.96],\n           [2.03],\n           [2.08],\n           [1.98],\n           [1.85],\n           [1.98],\n           [2.06],\n           [1.96],\n           [1.96],\n           [2.13],\n           [2.13],\n           [2.03],\n           [1.96],\n           [1.8 ],\n           [2.06],\n           [1.98],\n           [2.03],\n           [1.93],\n           [2.11],\n           [1.75],\n           [1.96],\n           [2.01],\n           [2.06],\n           [2.11],\n           [1.85],\n           [1.96],\n           [1.85],\n           [2.03],\n           [2.01],\n           [2.01],\n           [1.96],\n           [1.98],\n           [1.98],\n           [1.88],\n           [1.9 ],\n           [1.93],\n           [2.08],\n           [2.06],\n           [1.93],\n           [2.13],\n           [1.9 ],\n           [1.98],\n           [2.03],\n           [1.96],\n           [2.08],\n           [1.96],\n           [1.93],\n           [2.01],\n           [1.9 ],\n           [1.96],\n           [2.03],\n           [1.98],\n           [1.9 ],\n           [2.08],\n           [1.98],\n           [1.9 ],\n           [2.08],\n           [1.8 ],\n           [1.93],\n           [2.13],\n           [1.98],\n           [2.06],\n           [1.93],\n           [1.96],\n           [2.26],\n           [2.06],\n           [2.08],\n           [1.98],\n           [2.06],\n           [1.83],\n           [2.01],\n           [1.88],\n           [2.01],\n           [1.9 ],\n           [1.9 ],\n           [1.96],\n           [1.9 ],\n           [2.06],\n           [2.08],\n           [2.08],\n           [1.85],\n           [1.85],\n           [2.11],\n           [2.03],\n           [2.03],\n           [2.06],\n           [2.11],\n           [1.96],\n           [2.16],\n           [1.83],\n           [2.03],\n           [1.9 ],\n           [1.85],\n           [1.96],\n           [2.03],\n           [1.93],\n           [1.83],\n           [1.98],\n           [1.98],\n           [2.03],\n           [1.93],\n           [2.03],\n           [2.06],\n           [1.98],\n           [1.85],\n           [2.03],\n           [1.96],\n           [2.06],\n           [1.96],\n           [1.96],\n           [2.01],\n           [1.78],\n           [2.01],\n           [1.93],\n           [1.98],\n           [2.03],\n           [2.01],\n           [1.96],\n           [2.03],\n           [2.11],\n           [2.01],\n           [2.06],\n           [2.08],\n           [2.06],\n           [2.11],\n           [1.96],\n           [2.06],\n           [2.03],\n           [1.93],\n           [1.9 ],\n           [1.98],\n           [2.03],\n           [1.83],\n           [1.9 ],\n           [1.98],\n           [1.98],\n           [2.08],\n           [2.03],\n           [2.06],\n           [1.93],\n           [1.98],\n           [2.08],\n           [2.03],\n           [2.01],\n           [2.01],\n           [2.01],\n           [2.13],\n           [1.98],\n           [2.06],\n           [2.01],\n           [2.01],\n           [1.88],\n           [2.11],\n           [1.98],\n           [1.9 ],\n           [2.03],\n           [2.01],\n           [1.9 ],\n           [2.11],\n           [2.01],\n           [2.06],\n           [1.96],\n           [1.96],\n           [2.01],\n           [2.01],\n           [2.03],\n           [2.01],\n           [1.96],\n           [1.98],\n           [1.9 ],\n           [2.13],\n           [2.11],\n           [1.83],\n           [1.98],\n           [2.11],\n           [1.9 ],\n           [2.06],\n           [2.13],\n           [2.08],\n           [1.96],\n           [1.98],\n           [2.01],\n           [2.08],\n           [1.88],\n           [2.01],\n           [1.96],\n           [2.01],\n           [2.18],\n           [2.01],\n           [2.06],\n           [2.03],\n           [2.08],\n           [1.96],\n           [1.93],\n           [1.98],\n           [2.01],\n           [2.03],\n           [2.08],\n           [1.93],\n           [1.96],\n           [1.96],\n           [2.13],\n           [2.01],\n           [2.13],\n           [1.98],\n           [1.88],\n           [1.96],\n           [2.06],\n           [2.13],\n           [2.13],\n           [2.03],\n           [1.83],\n           [2.01],\n           [2.06],\n           [2.11],\n           [2.13],\n           [1.96],\n           [2.24],\n           [2.13],\n           [1.96],\n           [1.96],\n           [1.88],\n           [1.96],\n           [1.8 ],\n           [1.96],\n           [1.93],\n           [2.03],\n           [2.01],\n           [1.9 ],\n           [1.85],\n           [2.08],\n           [2.01],\n           [2.13],\n           [1.93],\n           [2.01],\n           [1.8 ],\n           [1.9 ],\n           [1.96],\n           [2.06],\n           [1.88],\n           [2.06],\n           [2.01],\n           [1.98],\n           [2.01],\n           [1.85],\n           [2.01],\n           [1.96],\n           [1.85],\n           [1.9 ],\n           [1.96],\n           [1.9 ],\n           [1.88],\n           [1.9 ],\n           [1.9 ],\n           [2.01],\n           [2.03],\n           [1.88],\n           [2.03],\n           [2.03],\n           [1.9 ],\n           [1.9 ],\n           [1.93],\n           [1.93],\n           [2.06],\n           [2.08],\n           [2.01],\n           [1.96],\n           [2.01],\n           [1.83],\n           [1.85],\n           [2.01],\n           [2.11],\n           [2.08],\n           [1.93],\n           [1.93],\n           [1.88],\n           [2.13],\n           [1.96],\n           [1.93],\n           [2.06],\n           [1.98],\n           [2.08],\n           [1.9 ],\n           [1.93],\n           [2.03],\n           [1.93],\n           [2.11],\n           [1.96],\n           [2.01],\n           [2.01],\n           [2.08],\n           [2.03],\n           [1.98],\n           [2.18],\n           [2.03],\n           [2.11],\n           [1.85],\n           [1.85],\n           [1.9 ],\n           [1.9 ],\n           [2.08],\n           [1.96],\n           [2.11],\n           [2.16],\n           [2.13],\n           [1.93],\n           [2.11],\n           [1.93],\n           [2.08],\n           [2.03],\n           [2.08],\n           [2.21],\n           [2.08],\n           [1.9 ],\n           [2.01],\n           [2.03],\n           [1.93],\n           [2.03],\n           [1.9 ],\n           [2.06],\n           [2.01],\n           [1.96],\n           [1.9 ],\n           [2.01],\n           [2.01],\n           [1.93],\n           [2.13],\n           [1.98],\n           [2.03],\n           [1.85],\n           [1.88],\n           [1.98],\n           [1.85],\n           [1.9 ],\n           [1.93],\n           [2.11],\n           [2.08],\n           [2.01],\n           [2.08],\n           [2.01],\n           [1.96],\n           [1.85],\n           [2.01],\n           [1.98],\n           [1.85],\n           [1.93],\n           [1.96],\n           [2.06],\n           [2.03],\n           [2.08],\n           [1.96],\n           [1.9 ],\n           [2.08],\n           [1.9 ],\n           [1.83],\n           [1.98],\n           [1.9 ],\n           [1.88],\n           [1.98],\n           [2.06],\n           [2.03],\n           [1.96],\n           [1.93],\n           [2.06],\n           [2.03],\n           [1.9 ],\n           [1.96],\n           [2.03],\n           [1.9 ],\n           [2.03],\n           [1.93],\n           [1.98],\n           [2.06],\n           [1.93],\n           [1.96],\n           [2.03],\n           [1.98],\n           [2.11],\n           [1.96],\n           [1.96],\n           [1.9 ],\n           [1.98],\n           [2.11],\n           [2.06],\n           [2.11],\n           [1.93],\n           [2.06],\n           [1.85],\n           [1.9 ],\n           [2.08],\n           [2.11],\n           [2.06],\n           [2.11],\n           [1.9 ],\n           [1.83],\n           [1.96],\n           [1.93],\n           [1.9 ],\n           [2.03],\n           [2.01],\n           [2.03],\n           [1.78],\n           [1.98],\n           [1.9 ],\n           [1.9 ],\n           [1.93],\n           [1.93],\n           [2.13],\n           [2.01],\n           [1.98],\n           [2.06],\n           [1.98],\n           [1.85],\n           [2.03],\n           [1.88],\n           [2.03],\n           [1.98],\n           [2.08],\n           [1.98],\n           [1.98],\n           [2.08],\n           [2.03],\n           [1.96],\n           [1.83],\n           [2.03],\n           [1.85],\n           [2.13],\n           [2.11],\n           [2.08],\n           [2.13]])\n\n\n\n\n```python\nX = players['heightMeters'].values.astype(float).reshape(-1, 1)\ny = players['weightKilograms'].values.astype(float)\nX_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.33, random_state=42) # random_state => shuffle\nh = LinearRegression()\n# h = LinearRegression(fir_intercept=False)\nh.fit(X_train, y_train)\nprint(h.coef_)\nprint(h.intercept_)\nh.predict(X_valid)[:10]\n```\n\n    [96.22270241]\n    -93.22909204641577\n\n\n\n\n\n    array([102.10299386, 102.10299386,  95.36740469,  82.85845337,\n           100.17853981, 106.91412898,  97.29185874,  92.48072361,\n           102.10299386, 100.17853981])\n\n\n\n\n```python\n\n```\n\n\n```python\n# Wrtie a class to simulate LinearRegression() function.\n```\n\n\n```python\nclass NormalEquation:\n    def __init__(self, fit_intercept=True):\n        self._fit_intercept = fit_intercept\n    def fit(self, X_train, y_train):\n        self._X_train = X_train.copy() # Not affect original data.\n        self._y_train = y_train.copy() # Not affect original data.\n        m = self._X_train.shape[0]\n        \n        # Determine add intercept or not.\n        if self._fit_intercept:\n            X0 = np.ones(m).reshape(-1, 1)\n            self._X_train = np.concatenate([X0, self._X_train], axis=1) # axis=1 => row\n        X_train_T = np.transpose(self._X_train)\n        left_matrix = np.dot(X_train_T, self._X_train)  # (2, m)(m, 2) = (2, 2)\n        right_matrix = np.dot(X_train_T, self._y_train) # (2, m)(m,) = (2,)\n        left_matrix_inv = np.linalg.inv(left_matrix)    \n        w = np.dot(left_matrix_inv, right_matrix)       # (2, 2)(2,) = (2,)\n        self._w = w\n        self.intercept_ = w[0]\n        self.coef_ = w[1:]\n    def predict(self, X):\n        m = X.shape[0]\n        if self._fit_intercept:\n            X0 = np.ones(m).reshape(-1, 1)\n            X = np.concatenate([X0, X], axis=1)\n        y_pred = np.dot(X, self._w) # (m, 2)(2, ) = (m,)\n        return y_pred\n```\n\n\n```python\nh = NormalEquation()\nh.fit(X_train, y_train)\n```\n\n\n```python\nh._X_train.shape\n```\n\n\n\n\n    (341, 2)\n\n\n\n\n```python\nh._X_train[:5]\n```\n\n\n\n\n    array([[1.  , 1.85],\n           [1.  , 2.24],\n           [1.  , 2.06],\n           [1.  , 2.01],\n           [1.  , 2.11]])\n\n\n\n\n```python\nprint(h.intercept_)\nprint(h.coef_)\n```\n\n    -93.22909204637108\n    [96.22270241]\n\n\n\n```python\nh.predict(X_valid)[:10]\n```\n\n\n\n\n    array([102.10299386, 102.10299386,  95.36740469,  82.85845337,\n           100.17853981, 106.91412898,  97.29185874,  92.48072361,\n           102.10299386, 100.17853981])\n\n\n\n\\begin{equation}\nw^* = (X^TX)^{-1}X^Ty\n\\end{equation}\n", "meta": {"hexsha": "000a7e9d1a69ef846e530dfa7f75267bc6a91cd4", "size": 44567, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Normal Equation.ipynb", "max_stars_repo_name": "kaiicheng/NBA", "max_stars_repo_head_hexsha": "21de2f1f4783465d159b81b44b0ec88c7f757ec2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Normal Equation.ipynb", "max_issues_repo_name": "kaiicheng/NBA", "max_issues_repo_head_hexsha": "21de2f1f4783465d159b81b44b0ec88c7f757ec2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Normal Equation.ipynb", "max_forks_repo_name": "kaiicheng/NBA", "max_forks_repo_head_hexsha": "21de2f1f4783465d159b81b44b0ec88c7f757ec2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3335826477, "max_line_length": 127, "alphanum_fraction": 0.2943433482, "converted": true, "num_tokens": 11789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.05834584511449651, "lm_q1q2_score": 0.029172922557248255}}
{"text": "```python\n%matplotlib inline\n```\n\n## Intro\n\nEste tutorial \u00e9 baseado no tutorial [Aprendendo representa\u00e7\u00f5es de frases utilizando um codificador-decodificador para m\u00e1quinas de tradu\u00e7\u00e3o estat\u00edstica](https://github.com/bentrevett/pytorch-seq2seq/blob/master/2%20-%20Learning%20Phrase%20Representations%20using%20RNN%20Encoder-Decoder%20for%20Statistical%20Machine%20Translation.ipynb)\n\n### Depend\u00eancias\n\n* torchtext\n* spacy\n\n### Arquitetura de um codificador-decodificador\n\nVamos lembrar da vis\u00e3o geral de um codificador-decodificador:\n\n\n\nN\u00f3s usamos o codificador (em verde) na sequ\u00eancia de entrada para gerar um vetor de contexto `z` (em vermelho).\nEsse vetor \u00e9 ent\u00e3o utilizado em um decodificador (em azul) e uma camada linear (em roxo) para gerar a sequ\u00eancia de sa\u00edda.\n\nNeste modelo, estamos usando um modelo de m\u00faltiplas camadas implementando uma mem\u00f3ria de curto e longo prazo (`LSTM`):\n\n\n\nUm dos problemas deste modelo, \u00e9 que o decodificador est\u00e1 tentando colocar muita informa\u00e7\u00e3o nos estados intermedi\u00e1rios do nosso modelo.  No momento da decodifica\u00e7\u00e3o, o estado intermedi\u00e1rio dever\u00e1 conter informa\u00e7\u00e3o sobre toda a sequ\u00eancia de entrada codificada at\u00e9 o momento bem como todos os tokens decodificados at\u00e9 ent\u00e3o. Isto exige muita mem\u00f3ria. Seria interessante amenizar o processo de compress\u00e3o para que possamos ter um modelo melhor!\n\nPara isso, usaremos uma unidade recorrente de porta (`GRU`). \n\n## Dados\n\nInicialmente, vamos importar algumas das bibliotecas necess\u00e1rias para manipular os nossos dados:\n\n\n```python\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom torchtext.datasets import TranslationDataset, Multi30k\nfrom torchtext.data import Field, BucketIterator\n\nimport spacy\n\nimport random\nimport math\nimport os\nimport time\n```\n\nEm seguida, vamos usar a mesma `SEED` para garantir que os nossos resultados sejam reproduz\u00edveis/determin\u00edsticos\n\n\n```python\nSEED = 1\n\nrandom.seed(SEED)\ntorch.manual_seed(SEED)\ntorch.backends.cudnn.deterministic = True\n```\n\nPor fim, vamos utilizar modelos em alem\u00e3o e ingl\u00eas. \n\n**obs.:** Eu gostaria muito de que este tutorial fosse em alem\u00e3o/portugu\u00eas ou ingl\u00eas/portugu\u00eas, mas eu preciso achar um m\u00f3dulo/base de dados com ambos os idiomas\n\nNo seu ambiente conda, execute a linha de comando abaixo para baixar os modelos:\n\n\n```bash\npython -m spacy download en\npython -m spacy download de\n```\n\n\nEm caso de sucesso, voc\u00ea obter\u00e1 uma mensagem similar a:\n\n\n```bash\n    You can now load the model via spacy.load('en')\n```\n\n\n```python\nspacy_de = spacy.load('de')\nspacy_en = spacy.load('en')\n```\n\nAo processar os textos de entrada, vamos utilizar uma t\u00e9cnica chamada de [tokeniza\u00e7\u00e3o](https://en.wikipedia.org/wiki/Lexical_analysis#Tokenization). Basicamente, teremos uma senten\u00e7a de entrada e fragmentaremos a sentence em unidades l\u00e9xicas, como por exemplo, palavras.\n\n\n```python\ndef tokenize_de(text):\n    \"\"\"\n    Tokenizes German text from a string into a list of strings\n    \"\"\"\n    return [tok.text for tok in spacy_de.tokenizer(text)]\n\ndef tokenize_en(text):\n    \"\"\"\n    Tokenizes English text from a string into a list of strings\n    \"\"\"\n    return [tok.text for tok in spacy_en.tokenizer(text)]\n```\n\nTamb\u00e9m vamos definir dois tokens especiais para indicar o in\u00edcio de uma senten\u00e7a (`sos`) e o final de uma senten\u00e7a (`eos`). \nTamb\u00e9m converteremos a senten\u00e7a para que ela contenha apenas letras min\u00fasculas.\n\n\n```python\nSRC = Field(tokenize=tokenize_de, init_token='<sos>', eos_token='<eos>', lower=True)\nTRG = Field(tokenize=tokenize_en, init_token='<sos>', eos_token='<eos>', lower=True)\n```\n\nFinalmente, vamos carregar nossos dados:\n\n\n```python\ntrain_data, valid_data, test_data = Multi30k.splits(exts=('.de', '.en'), fields=(SRC, TRG))\n```\n\n    downloading training.tar.gz\n\n\n    training.tar.gz: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.21M/1.21M [00:03<00:00, 352kB/s] \n\n\n    downloading validation.tar.gz\n\n\n    validation.tar.gz: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 46.3k/46.3k [00:00<00:00, 143kB/s]\n\n\n    downloading mmt_task1_test2016.tar.gz\n\n\n    mmt_task1_test2016.tar.gz: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 66.2k/66.2k [00:00<00:00, 128kB/s] \n\n\nVamos checar uma frase de entrada e sa\u00edda para garantir que nossos dados est\u00e3o corretos:\n\n\n```python\nimport pprint\n\npp = pprint.PrettyPrinter(indent=4)\npp.pprint(vars(train_data.examples[0]))\n```\n\n    {   'src': [   'zwei',\n                   'junge',\n                   'wei\u00dfe',\n                   'm\u00e4nner',\n                   'sind',\n                   'im',\n                   'freien',\n                   'in',\n                   'der',\n                   'n\u00e4he',\n                   'vieler',\n                   'b\u00fcsche',\n                   '.'],\n        'trg': [   'two',\n                   'young',\n                   ',',\n                   'white',\n                   'males',\n                   'are',\n                   'outside',\n                   'near',\n                   'many',\n                   'bushes',\n                   '.']}\n\n\nPor fim, vamos construir o nosso vocabul\u00e1rio convertendo todas as palavras que aparecem menos de duas vezes em termos desconhecidos (`<unk>`)\n\n\n```python\nSRC.build_vocab(train_data, min_freq=2)\nTRG.build_vocab(train_data, min_freq=2)\n```\n\nTamb\u00e9m vamos dividir os nossos dados em dados de treinamento, valida\u00e7\u00e3o e testes. \n\nA primeira linha define se pytorch utilizar\u00e1 uma unidade de processamento `CUDA` ou uma `CPU`\n\n\n```python\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nBATCH_SIZE = 128\n\ntrain_iterator, valid_iterator, test_iterator = BucketIterator.splits(\n    (train_data, valid_data, test_data), batch_size=BATCH_SIZE, device=device)\n```\n\n## Construindo o nosso modelo\n\n### Codificador\n\nO codificador ser\u00e1 um modelo com uma \u00fanica camada de mem\u00f3ria de curto longo prazo (`multi-layer LSTM`). E utilizaremos uma \u00fanica unidade de porta recorrente. N\u00e3o passaremos valores de dropout para a GRU uma vez que o dropout \u00e9 utilizado entre as camadas de uma RNN. Como temos apenas uma \u00fanica camada, PyTorch PyTorch alertar\u00e1 que temos uma \u00fanica camada no nosso modelo.\n\n\nOutra informa\u00e7\u00e3o importante sobre uma GRU \u00e9 que ela requer e retorna uma \u00fanica camada intermedi\u00e1ria. N\u00e3o h\u00e1 um estado como em uma LSTM.\n\n\\begin{equation}\nh_t = \\text{GRU}(x_t, h_{t - 1}) \\\\\n(h_t, c_t) = \\text{LSTM}(x_t, (h_{t - 1}, c_{t - 1})) \\\\\nh_t = \\text{RNN}(x_t, h_{t - 1})\n\\end{equation}\n\nDe acordo com a equa\u00e7\u00e3o acima, n\u00e3o h\u00e1 tanta diferen\u00e7a entre uma GRU e uma RNN. Entretanto, dentro de uma GRU existem in\u00fameros mec\u00e2nismos de porta que controlam o fluxo de informa\u00e7\u00e3o entrando e saindo de um estado intermedi\u00e1rio. Para mais detalhes, checar este [post](https://colah.github.io/posts/2015-08-Understanding-LSTMs/) (em ingl\u00eas).\n\n**obs.:** No futuro, eu pretendo fazer um tutorial explicando em mais detalhes como uma LSTM funciona.\n\n\nO restante do codificador segue a arquitetura \"padr\u00e3o\" de um codificador. Isto \u00e9, o codificador recebe a sequ\u00eancia de entrada $X = {x_1, x_2, ..., x_T}$ e computa estados intermedi\u00e1rios de forma recorrende, $H = {h_1, h_2, ..., h_T}$. Por fim, \u00e9 retornado o vetor de contexto (que corresponde ao \u00faltimo estado intermedi\u00e1rio computado), $z = h_T$. Onde\n\n\\begin{equation}\nh_t = \\text{EncoderGRU}(x_t, h_{t - 1})\n\\end{equation}\n\nEste codificador \u00e9 id\u00eantico a arquitetura de um codificador de um modelo de sequ\u00eancia para sequ\u00eancia (`seq2seq`), mas toda a \"m\u00e1gica\" ocorre dentro da GRU (em verde)\n\n \n\n\n```python\nclass Encoder(nn.Module):\n    def __init__(self, input_dim, emb_dim, hid_dim, dropout):\n        super().__init__()\n        \n        self.input_dim = input_dim\n        self.emb_dim = emb_dim\n        self.hid_dim = hid_dim\n        self.dropout = dropout\n        \n        self.embedding = nn.Embedding(input_dim, emb_dim) #no dropout as only one layer!\n        \n        self.rnn = nn.GRU(emb_dim, hid_dim)\n        \n        self.dropout = nn.Dropout(dropout)\n        \n    def forward(self, src):\n        \n        #src = [src sent len, batch size]\n        \n        embedded = self.dropout(self.embedding(src))\n        \n        #embedded = [src sent len, batch size, emb dim]\n        \n        outputs, hidden = self.rnn(embedded) #no cell state!\n        \n        #outputs = [src sent len, batch size, hid dim * n directions]\n        #hidden = [n layers * n directions, batch size, hid dim]\n        \n        #outputs are always from the top hidden layer\n        \n        return hidden\n```\n\n### Decodificador\n\nO decodificador \u00e9 onde tentamos aliviar o problema da compress\u00e3o de informa\u00e7\u00e3o (discutido na introdu\u00e7\u00e3o deste notebook).\n\nAo inv\u00e9s da GRU no decodificador utilizar apenas as palavras de sa\u00edda $y_t$ e o estado intermedi\u00e1rio anterior $s_{t - 1}$ como entrada, o decodificador tamb\u00e9m utilizar\u00e1 o vetor de contexto $Z$\n\n\n\\begin{equation}\ns_t = \\text{DecoderGRU}(y_t, h_{t - 1}, Z)\n\\end{equation}\n\nNote que o vetor de contexto $Z$ n\u00e3o possui um par\u00e2metro $t$. Iso indica que utilizamos o mesmo vetor de contexto (retornado pelo codificador) a cada intervalo de tempo $t$.\n\nPara predizermos o pr\u00f3ximo estado, utilizaremos uma camada linear, $f$. Esta camada utiliza apenas a \u00faltima camada intermedi\u00e1ria do decodificador naquele intervalo de tempo, $s_t$. Sendo assim, para predizermos $\\hat{y}_{t + 1}$, passaremos como par\u00e2metros o token atual na sequ\u00eancia $\\hat{y_t}$ e o vetor de contexto para uma camada linear, conforme equa\u00e7\u00e3o:\n\n\n\\begin{equation}\n\\hat{y}_{t + 1} = f(y_t, s_t, Z)\n\\end{equation}\n\n\nO nosso decodificador se parece com algo como:\n\n\n \n\nO estado intermedi\u00e1rio inicial, $s_0$ \u00e9 o vetor de contexto $Z$. Ent\u00e3o, ao gerar o primeiro token da sa\u00edda, nos estamos passando dois vetores ind\u00eanticos para a GRU.\n\n**Como essas modifica\u00e7\u00f5es reduzem a compress\u00e3o de informa\u00e7\u00e3o?** Tecnicamente, o estado intermedi\u00e1rio $s_t$ n\u00e3o mais precisa manter qualquer informa\u00e7\u00e3o sobre a sequ\u00eancia de entrada, uma vez que isto esta dispon\u00edvel como uma entrada atrav\u00e9s do vetor de contexto. Sendo assim, ele s\u00f3 precisa manter informa\u00e7\u00e3o sobre os tokens gerados at\u00e9 ent\u00e3o. A adi\u00e7\u00e3o de $y_t$ a camanda linear tamb\u00e9m significa que esta camada pode utilizar qual \u00e9 o \u00faltimo token visto, sem necessariamente necessitar desta informa\u00e7\u00e3o como algo que deveria estar comprimido no \u00faltimo estado intermedi\u00e1rio computado. \n\nEntretanto, a explica\u00e7\u00e3o anterior \u00e9 apenas uma hip\u00f3tese. \u00c9 imposs\u00edvel determinar com precis\u00e3o como o decodificador utiliza toda a informa\u00e7\u00e3o fornecida. Dito isto, a explica\u00e7\u00e3o anterior serve como uma boa intui\u00e7\u00e3o para compreender o que est\u00e1 acontecendo e os resultados oriundos destas modifica\u00e7\u00f5es indicam que estas modifica\u00e7\u00f5es s\u00e3o uma boa ideia!\n\n**Implementa\u00e7\u00e3o** passaremos $y_t$ e o vetor de contexto $Z$ para a GRU concatenando ambos os vetores. Desta forma, as dimens\u00f5es do vetor de entrada da GRU ser\u00e3o *emb_dim + hid_dim*. A camada linear tomar\u00e1 como entrada $y_t$, $s_t$ e $Z$ concatenando estes vetores. Assim, o vetor de entrada para a camada linear ter\u00e1 dimens\u00e3o *emb_dim + 2 x hid_dim*. Tamb\u00e9m n\u00e3o utilizaremos um dropout uma vez que a GRU s\u00f3 possui uma \u00fanica camada.\n\nA fun\u00e7\u00e3o *forward* agora receber\u00e1 um par\u00e2metro, i.e. o contexto. Dentro da fun\u00e7\u00e3o, concatenaremos $y_t$ e $z$ em *emb_con* antes de passar este vetor para a GRU. Tamb\u00e9m concatenamos $y_t$, $s_t$ e $Z$ e passamos estes vetores para a camada linear para obtermos uma predi\u00e7\u00e3o, isto \u00e9, $\\hat{y}_{t + 1}$.\n\n\n```python\nclass Decoder(nn.Module):\n    def __init__(self, output_dim, emb_dim, hid_dim, dropout):\n        super().__init__()\n\n        self.emb_dim = emb_dim\n        self.hid_dim = hid_dim\n        self.output_dim = output_dim\n        self.dropout = dropout\n        \n        self.embedding = nn.Embedding(output_dim, emb_dim)\n        \n        self.rnn = nn.GRU(emb_dim + hid_dim, hid_dim)\n        \n        self.out = nn.Linear(emb_dim + hid_dim*2, output_dim)\n        \n        self.dropout = nn.Dropout(dropout)\n        \n    def forward(self, input, hidden, context):\n        \n        #input = [batch size]\n        #hidden = [n layers * n directions, batch size, hid dim]\n        #context = [n layers * n directions, batch size, hid dim]\n        \n        #n layers and n directions in the decoder will both always be 1, therefore:\n        #hidden = [1, batch size, hid dim]\n        #context = [1, batch size, hid dim]\n        \n        input = input.unsqueeze(0) # ir\u00e1 criar um vetor [...]\n        \n        #input = [1, batch size]\n        \n        embedded = self.dropout(self.embedding(input))\n        \n        #embedded = [1, batch size, emb dim]\n                \n        emb_con = torch.cat((embedded, context), dim=2)\n            \n        #emb_con = [1, batch size, emb dim + hid dim]\n            \n        output, hidden = self.rnn(emb_con, hidden)\n        \n        #output = [sent len, batch size, hid dim * n directions]\n        #hidden = [n layers * n directions, batch size, hid dim]\n        \n        #sent len, n layers and n directions will always be 1 in the decoder, therefore:\n        #output = [1, batch size, hid dim]\n        #hidden = [1, batch size, hid dim]\n        \n        output = torch.cat((embedded.squeeze(0), hidden.squeeze(0), context.squeeze(0)), dim=1)\n        \n        #output = [batch size, emb dim + hid dim * 2]\n        \n        prediction = self.out(output)\n        \n        #prediction = [batch size, output dim]\n        \n        return prediction, hidden\n```\n\n### Seq2Seq \n\nAgora, vamos juntar todas as pe\u00e7as de nosso quebra-cabe\u00e7as para gerar um modelo de sequ\u00eancia-para-sequ\u00eancia (`seq2seq`). \n\n\n```python\nclass Seq2Seq(nn.Module):\n    def __init__(self, encoder, decoder, device):\n        super().__init__()\n        \n        self.encoder = encoder\n        self.decoder = decoder\n        self.device = device\n        \n        assert encoder.hid_dim == decoder.hid_dim, \\\n            \"Hidden dimensions of encoder and decoder must be equal!\"\n        \n    def forward(self, src, trg, teacher_forcing_ratio=0.5):\n        \n        #src = [src sent len, batch size]\n        #trg = [trg sent len, batch size]\n        #teacher_forcing_ratio is probability to use teacher forcing\n        #e.g. if teacher_forcing_ratio is 0.75 we use ground-truth inputs 75% of the time\n        \n        batch_size = trg.shape[1]\n        max_len = trg.shape[0]\n        trg_vocab_size = self.decoder.output_dim\n        \n        #tensor to store decoder outputs\n        outputs = torch.zeros(max_len, batch_size, trg_vocab_size).to(self.device)\n        \n        #last hidden state of the encoder is the context\n        context = self.encoder(src)\n        \n        #context also used as the initial hidden state of the decoder\n        hidden = context\n        \n        #first input to the decoder is the <sos> tokens\n        input = trg[0,:]\n        \n        for t in range(1, max_len):\n            \n            output, hidden = self.decoder(input, hidden, context)\n            outputs[t] = output\n            teacher_force = random.random() < teacher_forcing_ratio\n            top1 = output.max(1)[1]\n            input = (trg[t] if teacher_force else top1)\n\n        return outputs\n```\n\n\n```python\n\n```\n\n\n```python\nINPUT_DIM = len(SRC.vocab)\nOUTPUT_DIM = len(TRG.vocab)\nENC_EMB_DIM = 256\nDEC_EMB_DIM = 256\nHID_DIM = 512\nENC_DROPOUT = 0.5\nDEC_DROPOUT = 0.5\n\nenc = Encoder(INPUT_DIM, ENC_EMB_DIM, HID_DIM, ENC_DROPOUT)\ndec = Decoder(OUTPUT_DIM, DEC_EMB_DIM, HID_DIM, DEC_DROPOUT)\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nmodel = Seq2Seq(enc, dec, device).to(device)\n```\n\n\n```python\n\n```\n\n\n```python\ndef count_parameters(model):\n    return sum(p.numel() for p in model.parameters() if p.requires_grad)\n\nprint(f'The model has {count_parameters(model):,} trainable parameters')\n```\n\n    The model has 14,220,293 trainable parameters\n\n\n\n```python\n\n```\n\n\n```python\noptimizer = optim.Adam(model.parameters())\n```\n\n\n```python\n\n```\n\n\n```python\npad_idx = TRG.vocab.stoi['<pad>']\n\ncriterion = nn.CrossEntropyLoss(ignore_index=pad_idx)\n```\n\n\n```python\n\n```\n\n\n```python\ndef train(model, iterator, optimizer, criterion, clip):\n    \n    model.train()\n    \n    epoch_loss = 0\n    \n    for i, batch in enumerate(iterator):\n        \n        src = batch.src\n        trg = batch.trg\n        \n        optimizer.zero_grad()\n        \n        output = model(src, trg)\n        \n        #trg = [trg sent len, batch size]\n        #output = [trg sent len, batch size, output dim]\n        \n        output = output[1:].view(-1, output.shape[-1])\n        trg = trg[1:].view(-1)\n        \n        #trg = [(trg sent len - 1) * batch size]\n        #output = [(trg sent len - 1) * batch size, output dim]\n        \n        loss = criterion(output, trg)\n        \n        loss.backward()\n        \n        torch.nn.utils.clip_grad_norm_(model.parameters(), clip)\n        \n        optimizer.step()\n        \n        epoch_loss += loss.item()\n        \n    return epoch_loss / len(iterator)\n```\n\n\n```python\n\n```\n\n\n```python\ndef evaluate(model, iterator, criterion):\n    \n    model.eval()\n    \n    epoch_loss = 0\n    \n    with torch.no_grad():\n    \n        for i, batch in enumerate(iterator):\n\n            src = batch.src\n            trg = batch.trg\n\n            output = model(src, trg, 0) #turn off teacher forcing\n\n            #trg = [trg sent len, batch size]\n            #output = [trg sent len, batch size, output dim]\n\n            output = output[1:].view(-1, output.shape[-1])\n            trg = trg[1:].view(-1)\n\n            #trg = [(trg sent len - 1) * batch size]\n            #output = [(trg sent len - 1) * batch size, output dim]\n\n            loss = criterion(output, trg)\n\n            epoch_loss += loss.item()\n        \n    return epoch_loss / len(iterator)\n```\n\n\n```python\n\n```\n\n\n```python\ndef epoch_time(start_time, end_time):\n    elapsed_time = end_time - start_time\n    elapsed_mins = int(elapsed_time / 60)\n    elapsed_secs = int(elapsed_time - (elapsed_mins * 60))\n    return elapsed_mins, elapsed_secs\n```\n\nTraining this model without a CUDA takes 6h+ no meu velho Macbook Pro 2013\n\n\n```python\nN_EPOCHS = 10\nCLIP = 1\nSAVE_DIR = 'models'\nMODEL_SAVE_PATH = os.path.join(SAVE_DIR, 'tut2_model.pt')\n\nbest_valid_loss = float('inf')\n\nif not os.path.isdir(f'{SAVE_DIR}'):\n    os.makedirs(f'{SAVE_DIR}')\n\nfor epoch in range(N_EPOCHS):\n    \n    start_time = time.time()\n    \n    train_loss = train(model, train_iterator, optimizer, criterion, CLIP)\n    valid_loss = evaluate(model, valid_iterator, criterion)\n    \n    end_time = time.time()\n    \n    epoch_mins, epoch_secs = epoch_time(start_time, end_time)\n    \n    if valid_loss < best_valid_loss:\n        best_valid_loss = valid_loss\n        torch.save(model.state_dict(), MODEL_SAVE_PATH)\n    \n    print(f'Epoch: {epoch+1:02} | Time: {epoch_mins}m {epoch_secs}s')\n    print(f'\\tTrain Loss: {train_loss:.3f} | Train PPL: {math.exp(train_loss):7.3f}')\n    print(f'\\t Val. Loss: {valid_loss:.3f} |  Val. PPL: {math.exp(valid_loss):7.3f}')\n```\n\n    Epoch: 01 | Time: 13m 14s\n    \tTrain Loss: 4.641 | Train PPL: 103.694\n    \t Val. Loss: 4.319 |  Val. PPL:  75.093\n\n\n\n```python\n\n```\n\n\n```python\nmodel.load_state_dict(torch.load(MODEL_SAVE_PATH))\n\ntest_loss = evaluate(model, test_iterator, criterion)\n\nprint(f'| Test Loss: {test_loss:.3f} | Test PPL: {math.exp(test_loss):7.3f} |')\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "1c0b30f30305b1ab3c3fd74abcd015bc369c6f7b", "size": 29105, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "encoder-decoder/seq2seq.ipynb", "max_stars_repo_name": "marquesarthur/tensorflow-brasil", "max_stars_repo_head_hexsha": "037a32feafd2d80046e850120c88f81b177ea7fc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-30T08:47:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-30T08:47:03.000Z", "max_issues_repo_path": "encoder-decoder/seq2seq.ipynb", "max_issues_repo_name": "marquesarthur/tensorflow-brasil", "max_issues_repo_head_hexsha": "037a32feafd2d80046e850120c88f81b177ea7fc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "encoder-decoder/seq2seq.ipynb", "max_forks_repo_name": "marquesarthur/tensorflow-brasil", "max_forks_repo_head_hexsha": "037a32feafd2d80046e850120c88f81b177ea7fc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3029966704, "max_line_length": 591, "alphanum_fraction": 0.5383954647, "converted": true, "num_tokens": 5079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798742624020279, "lm_q2_score": 0.11757213509148833, "lm_q1q2_score": 0.029156411178903618}}
{"text": "# Selecting intracellular ions and creating a new METASPACE annotation database\nThis notebook shows how to select intracellular metabolites from processed SpaceM data.\nIon-cell colocalization is quantified using either Spearman correlation or an area-**n**ormalized **M**anders **C**olocalization **C**oefficient (NMCC).  \nSelected ions can be used to create a custom annotation database for use on METASPACE.\n\n<div class=\"alert alert-info\"> \n\nYou can also download this notebook [here](https://git.embl.de/mattausc/outer-spacem/-/raw/master/docs/examples/intracell_selection/create_database.ipynb?inline=false) or as part of our [collection of SpaceM analysis notebooks](https://git.embl.de/grp-alexandrov/spacem-analysis-notebooks).\n\n</div>\n\nBefore running this notebook, make sure to...  \n\n- [Install the METASPACE Python client](https://pypi.org/project/metaspace2020/)  \n- [Create an API key for METASPACE](https://metaspace2020.eu/user/me)\n- [Register your API key locally](https://metaspace2020.readthedocs.io/en/latest/content/examples/fetch-dataset-annotations.html#Connect-to-the-sm-server)  \n\n\n```python\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport re\nfrom pathlib import Path\n\nfrom scipy.stats import spearmanr\n\nfrom metaspace import SMInstance\n\n%matplotlib inline\n%config InlineBackend.figure_formats = ['retina']\n```\n\n\n```python\nsns.set(\n    rc={\n        \"figure.figsize\":(7.5,7.5), \n        \"legend.frameon\": False\n    },\n    style=\"ticks\",\n    context=\"notebook\"\n)\n```\n\n### Setup\n\nQuantification of ion-cell localization is done on the spatiomolecular matrices of **ablation marks** that are produced (i.e. the matrices stored in the `analysis/ablation_mark_analysis` directory, from here on called **AM matrix**).\nFor this example we're going to use the AM matrices of three SpaceM datasets.\n\nFrom experience it makes close to no difference for ion selection whether ion-cell colocalization is evaluated on the combined datasets together, or separately and then aggregated. This notebook computes the scores separately and then aggregates them, so there is no need to concatenate all your dataseset before running them through this notebook.\n\n<div class=\"alert alert-info\">\n\n**Note:** For this notebook you're going to need the AM matrices' .csv files, not the .h5ad ones!\n\n</div>\n\n\n```python\n# Datasets to be used to select intracellular ions\n\ndataset_paths = [\n    # \"/Users/alberto-mac/Documents/DA_ESPORTARE/LOCAL_EMBL_FILES/scratch/projects/gastrosome_processing/SpaceM_processing_new/Drug_W8/analysis/ablation_mark_analysis/spatiomolecular_matrix.csv\",\n    \"/Users/alberto-mac/Documents/DA_ESPORTARE/LOCAL_EMBL_FILES/scratch/projects/gastrosome_processing/SpaceM_processing_new/Feeding_W3/analysis/ablation_mark_analysis/spatiomolecular_matrix.csv\"\n]\n```\n\n#### Which selection method should I use?\n- Use `'nmcc'` if you only need high precision for cells (i.e. ions should be exclusive to cells but do not need to be present in all cells in a dataset)\n- Use `'spearman'` if you want your ions to have high precision *and* recall for cells (i.e. ions should be exclusive to cells and also present in all cells)\n\nAn ion's NMCC is defined as  \n\\begin{equation}\n\\frac{\\text{on-sample ion counts}}{\\text{on-sample ion counts + off-sample counts}} \\cdot \\frac{\\text{off-sample area}}{\\text{on-sample area}}\n\\end{equation}\nOr, more precisely:\n\\begin{equation}\nM = \\frac{\\sum_i I_i \\cdot f_i}{\\sum_i I_i \\cdot f_i + \\sum_i I_i \\cdot (1-f_i)\\cdot \\frac{\\overline{f}}{1 - \\overline{f}}}\n\\end{equation}\n\nWhere $I_i$ is the ion's intensity and $f_i$ is ablation mark sampling ratio for pixel $i$.  \nEssentially it describes the fraction of ions that are on-sample when off- and on-sample areas are the same size.  \nAn NMCC of 0 therefore indicates that all ions are off-sample (i.e. exclusively extracellular), 0.5 indicates that ions are evenly distributed between on- and off-sample area, and 1 indicates that all ions are exclusively on-sample (i.e. intracellular).\n\n#### Filtering out low-abundance ions\nLow occurence ions have shown to have very little contribution to overall variance in SpaceM datasets and have close to zero impact on clusterings.  \nUnless you specifically want to analyse these low-occurence ions, you can exclude them here from your database using the `nonzero_thresold` parameter. By default, only ions that are present in >2.5% of pixels in at least one dataset are included.\nIf you don't want to exclude low-abundance ions, set this parameter to 0.\n\n\n```python\nselection_method = \"nmcc\" # \"nmcc\" or \"spearman\"\nselection_threshold = 0.6\n# Recommended for spearman: 0.1-0.2\n# Recommended for nmcc: 0.6-0.7\n\nnonzero_threshold = 0. # 0.025 # Only include ions present in > 2.5% of pixels in >= 1 dataset(s). Set to 0 to disable.\n```\n\n### Evaluate & select intracellular ions\n\n\n```python\ndef nmcc(I, f):\n    f_ = f.mean()\n    I_on = np.sum(I * f)\n    I_off = np.sum(I * (1 - f) * (f_ / (1 - f_)))\n    return I_on / (I_on + I_off)\n```\n\n##### Load the datasets\n\n\n```python\nam_matrices = []\n\nion_regex = r\"^C[0-9]*.*?[\\+-]\" # This excludes SpaceM's image analysis features. You might want to adjust this if you want to include non-carbon metabolites!\n\nfor ds_idx, ds_path in enumerate(dataset_paths):\n    print(ds_idx, ds_path)\n    amm = pd.read_csv(ds_path)\n    amm[\"dataset\"] = ds_idx\n    am_matrices.append(amm)\n\nam_matrix = pd.concat(am_matrices, ignore_index=True).fillna(0)\nions = am_matrix.columns.to_series().filter(regex=ion_regex).values\n\nprint(f\"Read {len(am_matrices)} datasets containing {len(ions)} unique ion annotations for {len(am_matrix)} pixels.\")\n```\n\n    0 /Users/alberto-mac/Documents/DA_ESPORTARE/LOCAL_EMBL_FILES/scratch/projects/gastrosome_processing/SpaceM_processing_new/Feeding_W3/analysis/ablation_mark_analysis/spatiomolecular_matrix.csv\n    Read 1 datasets containing 820 unique ion annotations for 22500 pixels.\n\n\n\n```python\nscores = pd.DataFrame()\n\nfor dataset, ds_amm in am_matrix.groupby([\"dataset\"]):\n    for ion in ions:\n        if (ds_amm[ion] != 0).mean() > nonzero_threshold:\n            ion_scores = {\n                \"dataset\": dataset,\n                \"ion\": ion,\n                \"spearman\": spearmanr(ds_amm[ion], ds_amm[\"am_sampling_ratio\"]).correlation,\n                \"nmcc\": nmcc(ds_amm[ion], ds_amm[\"am_sampling_ratio\"])\n            }\n            scores = pd.concat([scores, pd.DataFrame(ion_scores, index=[0])], ignore_index=True)\n            \nscores_agg = scores.groupby([\"ion\"])[[\"spearman\", \"nmcc\"]].mean()\nscores_agg[\"selected\"] = scores_agg[selection_method] > selection_threshold\n```\n\nOnce we have computed the scores, we can take a closer look at the distribution of per-ion scores for both spearman correlation and NMCC:\n\n\n```python\ng = sns.displot(\n    scores_agg.melt(value_vars = [\"spearman\", \"nmcc\"]),\n    x=\"value\",\n    col=\"variable\",\n    kind=\"hist\",\n    bins=50,\n    fill=True,\n    linewidth=0,\n    alpha=1\n)\n\ng.set_titles(\"\")\n\nfor ax, title in zip(g.axes.flatten(), g.col_names):\n    ax.axvline(x=selection_threshold, c=\"0.2\", linestyle=\":\")\n    ax.text(\n        s=\"Threshold\", \n        x=selection_threshold+0.05, \n        y=plt.ylim()[1], \n        fontsize=10, \n        va=\"top\",\n        rotation=90\n    )\n    if title == selection_method:\n        ax.set_xlabel(title + \"\\n(selected method)\")\n    else:\n        ax.set_xlabel(title)\n\nplt.xlim(-1, 1)\nax.locator_params(nbins=4) \n\nplt.show()\n```\n\n\nIons for which the selected score is above the selection threshold will be included in your custom database.\n\n\n```python\nsns.scatterplot(\n    data=scores_agg,\n    x=\"nmcc\",\n    y=\"spearman\",\n    linewidth=0,\n    hue=\"selected\",\n    s=25\n)\n\nplt.axhline(y=0, c=\".2\", linestyle=\":\", zorder=0)\nplt.axvline(x=0.5, c=\"0.2\", linestyle=\":\", zorder=0)\n\nplt.xlim([0, 1])\nplt.ylim([-1, 1])\n\nplt.locator_params(nbins=4)\nsns.despine()\nplt.show()\n```\n\nNote that the two different scores are are not proportional, therefore depending on the chosen method you may select different ions.   \n\n<div class=\"alert alert-info\">\n\n- Spearman correlation will favor ions that are intracellular but also present in the majority of cells.  \n- NMCC will favor all ions that are intracellular, but not necessarily present in all cells.\n\n</div>\n\n\n```python\nselected_ions = scores_agg[\n    scores_agg[\"selected\"]\n].index\n\nselected_metabolites = np.unique([re.match(r\"^(.+?)[\\+-]\", x).group(1) for x in selected_ions])\n\nprint(f\"Selected {selected_metabolites.size} metabolites.\")\n```\n\n    Selected 171 metabolites.\n\n\n### Create & upload new database\n\nAn easy way to now restrict your single-cell analysis to intrallular ions is to exclude all ions that are not part of `selected_metabolites`. An even better way however is to use this list of ions and turn it into a custom database for METASPACE and reannotate your datasets, as using a custom database will also combat the issue of missing values due to METASPACE's FDR threshold.\n\nTo create a custom database, you're going to need a name and a version number:\n\n\n```python\ndb_name = \"Gastrosome_FeedingW3_intra_ions\"\ndb_version = \"v1\"\n# db_name = \"Gastrosome_DrugW8_intra_ions\"\n# db_version = \"v2\"\n\ndb_filename = f\"AB_{db_name}_{db_version}.tsv\" # XY = ideally your initials for easier handling on METASPACE\n\nimport os\nout_file = os.path.join(\"/Users/alberto-mac/EMBL_ATeam/projects/gastrosome\", db_filename)\n```\n\n\n```python\ndf_df = pd.DataFrame(\n    {\n        \"name\": selected_metabolites,\n        \"formula\": selected_metabolites\n    },\n    index = pd.RangeIndex(start=1, stop=selected_metabolites.size + 1, name=\"id\")\n)\ndf_df.to_csv(\n    db_filename, sep=\"\\t\", index=True\n)\ndf_df.to_csv(\n    out_file, sep=\"\\t\", index=True\n)\n```\n\nOnce we have the database file, we can upload it to METASPACE:\n\n\n```python\nsm = SMInstance()\n```\n\n\n```python\n# This will prompt you to enter your API key if needed and it will save it to a config file.\n# Note that API keys should be kept secret like passwords.\n# sm.save_login()\n```\n\n\n```python\nupload_result = sm.create_database(\n    local_path=db_filename,\n    name=db_name,\n    version=db_version,\n    is_public=False,\n)\n\nupload_result\n```\n\n    Uploading part   1/  1 of AB_Gastrosome_FeedingW3_intra_ions_v1.tsv file...\n\n\n\n\n\n    {'id': 471}\n\n\n\nThis chunk of code will create the database and return a number corresponding to your database's ID. Write it down and continue with the [reannotation notebook](bulk_reannotation.ipynb) to reannotate your datasets against the new database.\n\n\n", "meta": {"hexsha": "8eb0aa044a12d479c57c2d238542b6bc43c480b6", "size": 204489, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "projects/gastrosome_processing/create_database_v1.ipynb", "max_stars_repo_name": "abailoni/single-cell-analysis", "max_stars_repo_head_hexsha": "3fb68992a22249ab96178e173ceb552c037f25ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projects/gastrosome_processing/create_database_v1.ipynb", "max_issues_repo_name": "abailoni/single-cell-analysis", "max_issues_repo_head_hexsha": "3fb68992a22249ab96178e173ceb552c037f25ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/gastrosome_processing/create_database_v1.ipynb", "max_forks_repo_name": "abailoni/single-cell-analysis", "max_forks_repo_head_hexsha": "3fb68992a22249ab96178e173ceb552c037f25ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 361.2879858657, "max_line_length": 146348, "alphanum_fraction": 0.932138159, "converted": true, "num_tokens": 2731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.06656919313716142, "lm_q1q2_score": 0.029145557072521127}}
{"text": "# Notebook 3: Evaluating prediction quality with __Solaris__\n\nHere, we're going to try running several different pre-trained models to generate predictions on the exact same image to help us decide which one works best.\n\n## Sections\n\n1. [__Running inference with the other pre-trained models__](#Running-inference-with-the-other-pre-trained-models)\n2. [__Pixel-wise metrics for prediction quality__](#Pixel-wise-metrics-for-prediction-quality)\n3. [__Object-wise metrics for prediction quality__](#Object-wise-metrics-for-prediction-quality)\n\nWhile we talk through evaluation metrics, it'll be helpful to have a few different models' outputs to compare. To this end, we're going to run inference with all four of the pre-trained models available in `solaris` on the sample image we've used previously. The following cell runs that inference pipeline for the other three models, just like we did for XD_XD's model earlier; let's get it started!\n\n## Running inference with the other pre-trained models\n\n\n```python\nimport solaris as sol\nimport numpy as np\nimport skimage\nimport os\nfrom matplotlib import pyplot as plt\nimport time\n\ndata_path = '/data'  # NON-WORKSHOP PARTICIPANTS: change this path to point to the directory where you've stored the data.\n\ndef run_inference(config_path):\n    print('Loading config...')\n    config = sol.utils.config.parse(config_path)\n    print('Config loaded. Initializing model...')\n    inferer = sol.nets.infer.Inferer(config)\n    print('Model initialized. Loading dataset...')\n    inf_df = sol.nets.infer.get_infer_df(config)\n    print('Dataset loaded. Running inference on the image...this could take a bit, be patient.')\n    start_time = time.time()\n    inferer(inf_df)\n    end_time = time.time()\n    print('Running inference on one image took {} seconds.'.format(end_time-start_time))\n    print('Vectorizing output...')\n    resulting_preds = skimage.io.imread(os.path.join(config['inference']['output_dir'], 'MVOI_nadir10_test_sample.tif'))\n    # handle issue we currently have with multi-channel masks and automated footprint generation\n    if config['data_specs']['mask_channels'] > 1:\n        resulting_preds = resulting_preds[:, :, 0]\n    predicted_footprints = sol.vector.mask.mask_to_poly_geojson(\n        pred_arr=resulting_preds,\n        reference_im=os.path.join(data_path, 'MVOI_data/MVOI_nadir10_test_sample.tif'),\n        do_transform=True)\n    print('Output vectorized.')\n    predicted_footprints.to_file(os.path.join(config['inference']['output_dir'], 'MVOI_nadir10_predictions.geojson'), driver='GeoJSON')\n    print('Done.')\n```\n\n\n```python\nfor config_path in ('workshop_configs/selimsef_densenet121unet_workshop_infer.yml',\n                    'workshop_configs/selimsef_densenet161unet_workshop_infer.yml',\n                    'workshop_configs/selimsef_resnet34unet_workshop_infer.yml',\n                    'workshop_configs/xdxd_workshop_infer.yml'):\n    run_inference(os.path.join(data_path, config_path))\n```\n\nWhen the above cell finishes, we'll visualize the outputs.\n\n#### Visualizing the outputs\n\nThough it's preferable to work with vector-formatted labels, the raster versions are generally easier to visualize with `matplotlib`, so we'll show those here for comparison purposes.\n\n\n```python\noutput_dirs = ['xdxd_inference_out', 'selimsef_resnet34_inference_out',\n               'selimsef_densenet121_inference_out', 'selimsef_densenet161_inference_out']\nmodel_names = ['VGG16', 'ResNet34', 'DenseNet121', 'DenseNet161']\n\nf, axarr = plt.subplots(2, 3, figsize=(16, 12))\n\nfor i in range(4):\n    im = skimage.io.imread(os.path.join(output_dirs[i], 'MVOI_nadir10_test_sample.tif'))\n    im = (im > 0).astype('uint8')[:, :, 0]\n    axarr[i//2, i%2+1].imshow(im, cmap='gray')\n    axarr[i//2, i%2+1].set_title(model_names[i] + ' predictions', size=16)\n    axarr[i//2, i%2+1].axis('off')\n\nground_truth = sol.vector.mask.footprint_mask(\n    os.path.join(data_path, 'MVOI_data/MVOI_nadir10_test_sample.geojson'),\n    reference_im = os.path.join(data_path, 'MVOI_data/MVOI_nadir10_test_sample.tif'))\n\naxarr[0, 0].imshow(ground_truth, cmap='gray')\naxarr[0, 0].set_title('Ground Truth labels', size=16)\naxarr[0, 0].axis('off')\n\n# switch B and R for viz\nim_arr = skimage.io.imread(os.path.join(data_path, 'MVOI_data/viz_version.tif'))\naxarr[1, 0].imshow(im_arr[:, :, 0:3])\naxarr[1, 0].set_title('Source image', size=16)\naxarr[1, 0].axis('off');\n\n```\n\nAs you can see, the models are _generally_ very similar in their predictions, but there are some subtle differences. Some of these may have dramatic effects on how their performance is scored! But how would we go about deciding which is best?\n\n__Pause here for slides: CosmiQ_Solaris_Evaluating_Performance__\n\n\n## Pixel-wise metrics for prediction quality\n\nWe'll start by evaluating model performance with a couple of pixel-wise metrics, i.e., metrics that score models based on what fraction of the pixels are correct.\n\nLet's start with \"accuracy\", since that's the most common term used when discussing model performance. Few people are actually familiar wtih the definition of accuracy:\n\n$\n\\begin{align}\naccuracy=\\frac{TN+TP}{TN+TP+FN+FP}\n\\end{align}\n$\n\nWhere:\n- TN = True Negative (a pixel is ID'ed as non-building, and is in fact not a building)\n- TP = True Positive (a pixel is ID'ed as building, and is in fact a building)\n- FN = False Negative (a pixel is ID'ed as non-building, when it is, in fact, building)\n- FP = False Positive (a pixel is ID'ed as building, but it's actually background)\n\nIn layperson's terms, this metric is essentially what fraction of pixels are correct. Let's calculate that for each model above.\n\n\n```python\ndef acc(prediction, ground_truth):\n    return np.sum(prediction == ground_truth)/float(prediction.size)\n\noutput_dirs = ['xdxd_inference_out', 'selimsef_resnet34_inference_out',\n               'selimsef_densenet121_inference_out', 'selimsef_densenet161_inference_out']\nmodel_names = ['VGG16\\nU-Net', 'ResNet34\\nU-Net', 'DenseNet121\\nU-Net', 'DenseNet161\\nU-Net']\n\nground_truth = ground_truth > 0\n\naccuracy_scores = []\n\nfor i in range(4):\n    pred_image = skimage.io.imread(os.path.join(output_dirs[i], 'MVOI_nadir10_test_sample.tif'))\n    pred_image = pred_image > 0\n    pred_image = pred_image[:, :, 0]\n    accuracy = acc(pred_image, ground_truth)\n    print(\"{} accuracy: {}\".format(model_names[i], accuracy))\n    accuracy_scores.append(accuracy)\n\nplt.bar(model_names, accuracy_scores, color='black')\nplt.ylabel('Accuracy', size=16)\nplt.ylim((0.85, 1))\n```\n\nThese scores are _very_ similar - tiny fractions of a percent different - and more or less impossible to detect, even zoomed way in on the graph (note the Y axis on the graph above). What if we try a different metric, like $F_1$ score:\n\n$\n\\begin{align}\nF_1 = 2\\times\\frac{P\\times R}{P+R}\n\\end{align}\n$\n\nWhere\n- P = Precision:\n\n$\n\\begin{align}\n\\frac{TP}{TP+FP}\n\\end{align}\n$\n- R = Recall:\n\n$\n\\begin{align}\n\\frac{TP}{TP+FN}\n\\end{align}\n$\n\n\n```python\nf1_scores = []\nprecision = []\nrecall = []\nfor i in range(4):\n    pred_image = skimage.io.imread(os.path.join(output_dirs[i], 'MVOI_nadir10_test_sample.tif'))\n    pred_image = pred_image > 0\n    pred_image = pred_image[:, :, 0]\n    f1, prec, rec = sol.eval.pixel.f1(ground_truth, pred_image)\n#    print(\"{} F1: {}\".format(model_names[i], results[0]))\n#    print(\"{} Precision: {}\".format(model_names[i], results[1]))\n#    print(\"{} Recall: {}\".format(model_names[i], results[2]))\n    f1_scores.append(f1)\n    precision.append(prec)\n    recall.append(rec)\n\nf, axarr = plt.subplots(1, 3, figsize=(10, 4))\nf.subplots_adjust(wspace=0.6)\naxarr[0].bar(model_names, f1_scores)\naxarr[0].set_xticklabels(labels=model_names, rotation=90)\naxarr[0].set_ylabel('$F_1$ Score', size=16)\naxarr[1].bar(model_names, precision)\naxarr[1].set_xticklabels(labels=model_names, rotation=90)\naxarr[1].set_ylabel('Precision', size=16)\naxarr[2].bar(model_names, recall)\naxarr[2].set_xticklabels(labels=model_names, rotation=90)\naxarr[2].set_ylabel('Recall', size=16);\n```\n\nThis shows _some_ pixel-wise difference between these different predictions - specifically, the VGG16 model provides _slightly_ better prediction quality on a pixel-by-pixel basis. The Precision and Recall plots shed a bit more light.\n\nThis still leaves potential for problems, though. The two examples below produce the exact same $F_1$ score, Precision, and Recall on a pixel-wise basis:\n\n\n\nDepending on your use case, you may want to be able to distinguish between these two sets of predictions and optimize for one rather than the other. To do so, we'll need something more than pixel-wise metrics.\n\n## Object-wise metrics for prediction quality\nAt CosmiQ Works, we generally use object-wise metrics to evaluate model performance for building footprint extraction tasks (or other object identification tasks).\nThis involves a two-step process, adapted from the [ImageNet](www.image-net.org) competitions:\n\n1. Call positive and negative building identifications using an Intersection-over-Union (IoU) threshold\n2. Calculate the $F_1$ score of identifications at an object level (rather than a pixel level)\n\nThe graphic below displays how we calculate IoU for a prediction.\n\n\n\n`solaris` provides functionality to do this calculation for all of the objects within a given set of vector labels, providing both the object-by-object IoU scores.\n\nNext, we set a threshold for how high a prediction's IoU must be with a ground truth object to be called \"successful\" (i.e. a True Positive). We generally set this threshold at __0.5__ for the SpaceNet Challenges. This allows us to identify specific predictions as True Positives and False Positives, as well as identify False Negatives where there wasn't a high-quality prediction. We call this metric the __SpaceNet Metric__.\n\nUsing that threshold, let's assess the SpaceNet Metric for the four prediction sets we generated earlier:\n\n\n```python\nevaluator = sol.eval.base.Evaluator(os.path.join(data_path, 'MVOI_data/MVOI_nadir10_test_sample.geojson'))\nprediction_dirs = ['xdxd_inference_out', 'selimsef_resnet34_inference_out',\n               'selimsef_densenet121_inference_out', 'selimsef_densenet161_inference_out']\nmodel_names = ['VGG16\\nU-Net', 'ResNet34\\nU-Net', 'DenseNet121\\nU-Net', 'DenseNet161\\nU-Net']\n\nf1_scores = []\nprecision = []\nrecall = []\nfor i in range(4):    \n    evaluator.load_proposal(os.path.join(prediction_dirs[i],'MVOI_nadir10_predictions.geojson'),\n                            pred_row_geo_value='geometry',\n                            conf_field_list=[])\n    results = evaluator.eval_iou(miniou=0.5, calculate_class_scores=False)\n    f1_scores.append(results[0]['F1Score'])\n    precision.append(results[0]['Precision'])\n    recall.append(results[0]['Recall'])\n\nf, axarr = plt.subplots(1, 3, figsize=(10, 4))\nf.subplots_adjust(wspace=0.6)\naxarr[0].bar(model_names, f1_scores)\naxarr[0].set_xticklabels(labels=model_names, rotation=90)\naxarr[0].set_ylabel('$F_1$ Score', size=16)\naxarr[1].bar(model_names, precision)\naxarr[1].set_xticklabels(labels=model_names, rotation=90)\naxarr[1].set_ylabel('Precision', size=16)\naxarr[2].bar(model_names, recall)\naxarr[2].set_xticklabels(labels=model_names, rotation=90)\naxarr[2].set_ylabel('Recall', size=16);\n\n```\n\nThese are still close. What if we increase the IoU threshold to 0.85, meaning predictions must be much more similar to the ground truth to be deemed \"correct\"?\n\n\n```python\nf1_scores = []\nprecision = []\nrecall = []\nfor i in range(4):\n    evaluator.load_proposal(os.path.join(prediction_dirs[i],'MVOI_nadir10_predictions.geojson'),\n                            pred_row_geo_value='geometry',\n                            conf_field_list=[])\n    results = evaluator.eval_iou(miniou=0.75, calculate_class_scores=False)\n    f1_scores.append(results[0]['F1Score'])\n    precision.append(results[0]['Precision'])\n    recall.append(results[0]['Recall'])\n\nf, axarr = plt.subplots(1, 3, figsize=(10, 4))\nf.subplots_adjust(wspace=0.6)\naxarr[0].bar(model_names, f1_scores)\naxarr[0].set_xticklabels(labels=model_names, rotation=90)\naxarr[0].set_ylabel('$F_1$ Score', size=16)\naxarr[1].bar(model_names, precision)\naxarr[1].set_xticklabels(labels=model_names, rotation=90)\naxarr[1].set_ylabel('Precision', size=16)\naxarr[2].bar(model_names, recall)\naxarr[2].set_xticklabels(labels=model_names, rotation=90)\naxarr[2].set_ylabel('Recall', size=16)\n```\n\nIt's notable that 1. all of the scores drop substantially, but 2. the VGG16 model now achieves ~18% better scores than the other models at the higher IoU threshold! These are truly state-of-the-art models for overhead imagery analysis, and the relatively low scores highlight that there's still a lot of room for improvement in this field. We hope some of you will use these tools to make this happen!\n\n__Coming up next:__ How well do pre-trained models work on images of geographies that they've never seen before, and fine-tuning models to improve that performance.\n", "meta": {"hexsha": "ac37b5f9d929f1000304375f340f22d126188f5a", "size": 17028, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Solaris_FOSS4G_2019/3_evaluating_performance.ipynb", "max_stars_repo_name": "edleardi/solaris_tutorials", "max_stars_repo_head_hexsha": "669be07a7d5cb0f2bbd8f6cfddf18712de67787f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2019-08-13T08:24:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-21T07:32:20.000Z", "max_issues_repo_path": "Solaris_FOSS4G_2019/3_evaluating_performance.ipynb", "max_issues_repo_name": "edleardi/solaris_tutorials", "max_issues_repo_head_hexsha": "669be07a7d5cb0f2bbd8f6cfddf18712de67787f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-11-18T14:42:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-22T06:03:40.000Z", "max_forks_repo_path": "Solaris_FOSS4G_2019/3_evaluating_performance.ipynb", "max_forks_repo_name": "edleardi/solaris_tutorials", "max_forks_repo_head_hexsha": "669be07a7d5cb0f2bbd8f6cfddf18712de67787f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2019-08-14T07:26:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T03:22:41.000Z", "avg_line_length": 44.8105263158, "max_line_length": 438, "alphanum_fraction": 0.6285529716, "converted": true, "num_tokens": 3337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406687981454, "lm_q2_score": 0.07696083199111282, "lm_q1q2_score": 0.02905584398118644}}
{"text": "\\title{Operatial Amplifier Topology Repository for use with Python}\n\\author{Steven K Armour}\n\\maketitle\n\n<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Premise\" data-toc-modified-id=\"Premise-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Premise</a></span></li><li><span><a href=\"#Libarys\" data-toc-modified-id=\"Libarys-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Libarys</a></span></li><li><span><a href=\"#Setup\" data-toc-modified-id=\"Setup-3\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>Setup</a></span></li><li><span><a href=\"#Ideal-OpAmp\" data-toc-modified-id=\"Ideal-OpAmp-4\"><span class=\"toc-item-num\">4&nbsp;&nbsp;</span>Ideal OpAmp</a></span></li><li><span><a href=\"#TestBench\" data-toc-modified-id=\"TestBench-5\"><span class=\"toc-item-num\">5&nbsp;&nbsp;</span>TestBench</a></span></li><li><span><a href=\"#Buffer\" data-toc-modified-id=\"Buffer-6\"><span class=\"toc-item-num\">6&nbsp;&nbsp;</span>Buffer</a></span></li><li><span><a href=\"#Inverting\" data-toc-modified-id=\"Inverting-7\"><span class=\"toc-item-num\">7&nbsp;&nbsp;</span>Inverting</a></span></li><li><span><a href=\"#Noninverting\" data-toc-modified-id=\"Noninverting-8\"><span class=\"toc-item-num\">8&nbsp;&nbsp;</span>Noninverting</a></span></li><li><span><a href=\"#Miller-Capactive-Integrator\" data-toc-modified-id=\"Miller-Capactive-Integrator-9\"><span class=\"toc-item-num\">9&nbsp;&nbsp;</span>Miller Capactive Integrator</a></span></li><li><span><a href=\"#Miller-Inductive-Integrator\" data-toc-modified-id=\"Miller-Inductive-Integrator-10\"><span class=\"toc-item-num\">10&nbsp;&nbsp;</span>Miller Inductive Integrator</a></span></li><li><span><a href=\"#Low-Pass-1Pole\" data-toc-modified-id=\"Low-Pass-1Pole-11\"><span class=\"toc-item-num\">11&nbsp;&nbsp;</span>Low Pass 1Pole</a></span></li><li><span><a href=\"#Miller-Capacitive-Differentiator\" data-toc-modified-id=\"Miller-Capacitive-Differentiator-12\"><span class=\"toc-item-num\">12&nbsp;&nbsp;</span>Miller Capacitive Differentiator</a></span></li><li><span><a href=\"#Miller-Inductive-Differentiator\" data-toc-modified-id=\"Miller-Inductive-Differentiator-13\"><span class=\"toc-item-num\">13&nbsp;&nbsp;</span>Miller Inductive Differentiator</a></span></li><li><span><a href=\"#High-Pass-1Zero\" data-toc-modified-id=\"High-Pass-1Zero-14\"><span class=\"toc-item-num\">14&nbsp;&nbsp;</span>High Pass 1Zero</a></span></li><li><span><a href=\"#AllPass-(Phase)-Filter\" data-toc-modified-id=\"AllPass-(Phase)-Filter-15\"><span class=\"toc-item-num\">15&nbsp;&nbsp;</span>AllPass (Phase) Filter</a></span><ul class=\"toc-item\"><li><span><a href=\"#First-Order-Cap-First\" data-toc-modified-id=\"First-Order-Cap-First-15.1\"><span class=\"toc-item-num\">15.1&nbsp;&nbsp;</span>First Order Cap First</a></span></li><li><span><a href=\"#First-Order-Cap-Second\" data-toc-modified-id=\"First-Order-Cap-Second-15.2\"><span class=\"toc-item-num\">15.2&nbsp;&nbsp;</span>First Order Cap Second</a></span></li></ul></li><li><span><a href=\"#Sallen-Key-Filter\" data-toc-modified-id=\"Sallen-Key-Filter-16\"><span class=\"toc-item-num\">16&nbsp;&nbsp;</span>Sallen-Key Filter</a></span><ul class=\"toc-item\"><li><span><a href=\"#Low-Pass-with-Voltage-Gain\" data-toc-modified-id=\"Low-Pass-with-Voltage-Gain-16.1\"><span class=\"toc-item-num\">16.1&nbsp;&nbsp;</span>Low Pass with Voltage Gain</a></span></li><li><span><a href=\"#Band-Pass-with-Voltage-Gain\" data-toc-modified-id=\"Band-Pass-with-Voltage-Gain-16.2\"><span class=\"toc-item-num\">16.2&nbsp;&nbsp;</span>Band Pass with Voltage Gain</a></span></li><li><span><a href=\"#HIgh-Pass-with-Voltage-Gain\" data-toc-modified-id=\"HIgh-Pass-with-Voltage-Gain-16.3\"><span class=\"toc-item-num\">16.3&nbsp;&nbsp;</span>HIgh Pass with Voltage Gain</a></span></li></ul></li></ul></div>\n\nNote:\nThis notebook uses the `ipywidgets` to provided a interactive exploration experience. In order to make use of this experience, this notebook must be downloaded and run on a computer what has `ipywidgets` installed and activated for directions for that see http://ipywidgets.readthedocs.io/en/latest/user_install.html\n\nthis notebook also uses the [`(some) LaTeX environments for Jupyter\n`](http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/latex_envs/README.html) found within the install of https://github.com/ipython-contrib/jupyter_contrib_nbextensions\n\nAnd all diagrams are made in **draw.io** where the source file is `OpAmpTobosDrawing.html` where that file and the exported files should accompany this notebook from its GitHub source\n\n\n\n# Premise\nThis Notebook serves as a Repository of Operational Amplifier Topologies for use in [PySpice](https://pyspice.fabrice-salvaire.fr/) and for the topologies theory. The Goal for the Author personally is to make one or two upgrades to this notebook a week. Whether that be a new feature, expanded theory, or new topology.\n\nSome of the intended upgrades include:\n\\begin{itemize}\n\\item Enhanced analyses of output data\n\\item Routines to find figures of merits from output data\n\\item Added calculations from theory \n\\item Simulations from theory and compersion to SPICE sim\n\\item adding GUI interactivity via ipython notebook widgets\n\\end{itemize}\n\n\n\n# Libarys\n\n\n```python\nfrom sympy import *\ninit_printing()\nimport ipywidgets as wgs\n\nimport numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfrom PySpice.Plot.BodeDiagram import bode_diagram\nfrom PySpice.Probe.Plot import plot\nfrom PySpice.Spice.Netlist import Circuit\nfrom PySpice.Spice.Netlist import SubCircuitFactory\nfrom PySpice.Unit import *\n\nfrom ipywidgets import widgets\nfrom IPython.display import display\n\n#https://github.com/jrjohansson/version_information\n%load_ext version_information\n%version_information sympy, numpy, matplotlib, pandas, PySPice, ipywidgets\n```\n\n\n\n\n<table><tr><th>Software</th><th>Version</th></tr><tr><td>Python</td><td>3.6.4 64bit [GCC 7.2.0]</td></tr><tr><td>IPython</td><td>6.2.1</td></tr><tr><td>OS</td><td>Linux 4.13.0 32 generic x86_64 with debian stretch sid</td></tr><tr><td>sympy</td><td>1.1.1</td></tr><tr><td>numpy</td><td>1.13.3</td></tr><tr><td>matplotlib</td><td>2.1.1</td></tr><tr><td>pandas</td><td>0.21.1</td></tr><tr><td>PySPice</td><td>1.2.0</td></tr><tr><td>ipywidgets</td><td>7.2.1</td></tr><tr><td colspan='2'>Mon May 07 11:51:59 2018 MDT</td></tr></table>\n\n\n\n# Setup\n\n\n```python\ndef lambdify2(expresion, ReVars=False):\n    \"\"\"\n    Helper Function to more automate sympy `lambdify` function\n    \n    Args:\n        expresion: sympy expresion !Only Pass LHS of Equations\n        ReVars (bool; False): Control to return the Vars in a list if True\n    \n    Note:\n        lambdfy is set with `dummify=False` therefore do not pass\n        unsantied variabls to functin else error will be thrown\n    \"\"\"\n    #collect vars\n    Vars=sorted(list(expresion.free_symbols), key=lambda x: str(x))\n    #perform lambdfy with waver\n    F=lambdify(Vars, expresion, dummify=False)\n    if ReVars:\n        return F, Vars\n    else:\n        return F\n```\n\n# Ideal OpAmp\n\nUsing the Semi Ideal OpAmp model devloped by Fabrice Salvaire for the OpAmp Exsample [8.10.3. Operational Amplifier](https://pyspice.fabrice-salvaire.fr/examples/operational-amplifier/operational-amplifier.html)\n\n\n\n\n```python\nclass BasicOperationalAmplifier(SubCircuitFactory):\n    \"\"\"\n    Semi Ideal OpAmp Model SubCir from \n    https://pyspice.fabrice-salvaire.fr/examples/operational-amplifier/operational-amplifier.html\n    A0=100e3; pole=100; A=10e6Hz\n    Termanals:\n        non_inverting_input\n        inverting_input\n        output\n    \"\"\"\n\n    __name__ = 'BasicOperationalAmplifier'\n    __nodes__ = ('non_inverting_input', 'inverting_input', 'output')\n\n    ##############################################\n\n    def __init__(self):\n\n        super().__init__()\n\n        # Input impedance\n        self.R('input', 'non_inverting_input', 'inverting_input', 10@u_M\u03a9)\n\n        # dc gain=100k and pole1=100hz\n        # unity gain = dcgain x pole1 = 10MHZ\n        self.VCVS('gain', 1, self.gnd, 'non_inverting_input', 'inverting_input', voltage_gain=kilo(100))\n        self.R('P1', 1, 2, 1@u_k\u03a9)\n        self.C('P1', 2, self.gnd, 1.5915@u_uF)\n\n        # Output buffer and resistance\n        self.VCVS('buffer', 3, self.gnd, 2, self.gnd, 1)\n        self.R('out', 3, 'output', 10@u_\u03a9)\n```\n\n# TestBench\n\n\n\n\n```python\nclass OnePortOpAmpTB(Circuit):\n    \"\"\"\n    Class for implimenting Bode plot simulation for One Port \n    (Two Termanal) Opertinal Amplifer topology \n    \"\"\"\n    def __init__(self, DUT, **kwargs):\n        \"\"\"\n        Args:\n            DUT (class SubCircuitFactory): The One Port OpAmp topology class to be tested\n            kwargs (dict): Addital Ciricut Parmters to the topology under test\n        \"\"\"\n        #bind the DUT class to TB instance\n        self.DUT=DUT\n        #self.Theory=self.DUT.Theory()\n        #create the ciruit name from DUT name\n        super().__init__(title=f'{self.DUT.__name__}_TB', **kwargs)\n        \n    \n    def SetupCir(self, **kwargs):\n        \"\"\"\n        Sets up the the DUT and the Testbench for simulation\n        see diagrm in source IPYNB for cirucit diagram\n        Args:\n            kwargs (dict): Addital Ciricut Parmters to the topology under test\n        \"\"\"\n        #create instatince of DUT and setuo with parmaters\n        self.DUT=self.DUT(**kwargs)\n        \n        #load the DUT in to the circuit\n        self.subcircuit(self.DUT)\n        self.X('Amp', self.DUT.__name__, 'Vin', 'Vout')\n        \n        #set up the TB elements\n        self.R('Sload', 'Vin' , '1', 50@u_\u03a9)\n        self.SinusoidalVoltageSource('Source', '1', self.gnd, amplitude=1@u_V)\n\n        self.R('Tload', 'Vout', self.gnd, 50@u_\u03a9)\n        #print out the resulting spice list\n        print(self)\n    \n    def Simulate(self, fMin=1, fMax=20e6):\n        \"\"\"\n        Method to perform a Bode plot simulation via NgSpice AC sim @25C\n        Args:\n            fMin(float; 1 [Hz]): the  starting frequnacy for \n            Bode plot sweep in hertz\n            \n            fMax(float; 100e3[Hz]): the ending  frequnacy for \n            Bode plot sweep in hertz\n        \n        Retured Attributes:\n            results: the ac simulation raw results from NGSpice\n            Data: Pandas Dataframe with ouputs and calcs from results\n            \n        \"\"\"\n        \n        simulator = self.simulator(temperature=25, nominal_temperature=25)\n        self.results = simulator.ac(start_frequency=fMin@u_Hz, stop_frequency=fMax@u_Hz, number_of_points=10,  variation='dec')\n        \n        # returned dataframe\n        self.Data=pd.DataFrame()\n        self.Data['freq[Hz]']=self.results.frequency\n        self.Data['Vin']=self.results.Vin\n        self.Data['Vout']=self.results.Vout\n        #normlized gain in dB\n        self.Data['Gain[dB]']=20*np.log10(np.abs(self.Data['Vout']/self.Data['Vin']))\n        # phase in radians unwraped\n        self.Data['Phase[rad_UW]']=(np.angle(self.Data['Vout']))\n    \n    def PlotResults(self):\n        \"\"\"\n        Create a Bode plot from the simulation\n        \"\"\"\n        self.fig, [self.axMag, self.axPh]=plt.subplots(ncols=1, nrows=2, sharex=True)\n        \n        A=self.Data['Gain[dB]']; F=self.Data['freq[Hz]']\n        L=np.abs(np.abs(A-A.max())-3.0).idxmin()\n        self.dB3=F[L]\n        \n        plt.suptitle(\"Bode Diagram of an Operational Amplifier\")\n        bode_diagram(axes=(self.axMag, self.axPh),\n                     frequency=self.Data['freq[Hz]'],\n                     gain=self.Data['Gain[dB]'],\n                     phase=self.Data['Phase[rad_UW]'],\n                     marker='.',\n                     color='blue',\n                     linestyle='-',\n                    )\n        \n        self.axMag.axvline(x=self.dB3, label='3dB[Hz]', \n                      linestyle='-.', alpha=.7, color='g')\n        self.axPh.axvline(x=self.dB3, label='3dB[Hz]', \n                      linestyle='-.', alpha=.7, color='g')\n        \n        \n    \n```\n\n\\begin{definition}\n$A$ Open Loop Gain (no feedback)\n$$A=\\dfrac{V_o}{V_i}$$\n\\end{definition}\n\n\\begin{definition}\n$G$ Closed Loop Gain (with feedback)\n$$G=\\dfrac{V_o}{V_i}$$\n\\end{definition}\n\n\\begin{definition}\n$Z_{\\text{i}}$ Open Loop Input Impedance (no feedback)\n$$Z_{\\text{i}}=\\dfrac{V_{\\text{diff}}}{I_i}$$\n\\end{definition}\n\n\\begin{definition}\n$Z_{\\text{o}}$ Open Loop Output Impedance (no feedback)\n$$Z_{\\text{o}}=\\dfrac{V_o}{I_o}$$\n\\end{definition}\n\n\\begin{definition}\n$Z_{\\text{ifb}}$ Closed Loop Input Impedance (with feedback)\n$$Z_{\\text{ifb}}=\\dfrac{V_i}{I_i}$$\n\\end{definition}\n\n\\begin{definition}\n$Z_{\\text{ofb}}$ Closed Loop Output Impedance (with feedback)\n$$Z_{\\text{ofb}}=\\dfrac{V_o}{I_o}$$\n\\end{definition}\n\n\n\\begin{definition}\n$V_{\\text{diff}}$ the differential input voltage\n$$V_{\\text{diff}}=V_+-V_-$$\n\\end{definition}\n\n\n# Buffer\n\n\n\n[Analog Electronics: Circuits, Systems and Signal Processing](https://www.amazon.com/Analog-Electronics-Circuits-Systems-Processing-ebook/dp/B00CXO975A/ref=sr_1_1?ie=UTF8&qid=1524885102&sr=8-1&keywords=Analog+Electronics+Crecraft+Gergely) 3.5, 3.5.1, 3.5.2\n\n\n$$V_{\\text{diff}}=V_i-V_o$$\n$$V_o=AV_{\\text{diff}}$$\n$$V_o=AV_i-AV_o$$\n$$G=\\dfrac{V_o}{V_i}=\\dfrac{A}{1+A}\\approx 1$$\n\n\n$$I_i=\\dfrac{V_{\\text{diff}}}{Z_i} $$\n$$V_{\\text{diff}}=\\dfrac{1}{1+A}V_i$$\n$$I_i=\\dfrac{1}{1+A} \\dfrac{V_i}{Z_i}$$\n$$Z_{\\text{ifb}}=(1+A)Z_i$$\n\n$$V_o=AV_{\\text{diff}}-I_LZ_o$$\n$$(1+A)V_o=AV_i-I_L Z_o$$\n$$V_o=\\dfrac{A}{1+A}V_i -\\dfrac{Z_o}{1+A}I_L$$\n$$V_o=GV_i -Z_{\\text{ofb}}I_L$$\n$$Z_{\\text{ifb}}=\\dfrac{Z_o}{1+A}$$\n\n\n```python\nclass BufferOpAmp(SubCircuitFactory):\n    \"\"\"\n    Buffer OpAmp SubCircuit\n    Termanals:\n        Vin\n        Vout\n    \n    \"\"\"\n    \n    __name__='BufferOpAmp'\n    __nodes__=('Vin','Vout')\n    \n    def __init__(self):\n        super().__init__()\n       \n        #'non_inverting_input', 'inverting_input', 'output'\n        self.subcircuit(BasicOperationalAmplifier())\n        self.X('op', 'BasicOperationalAmplifier', 'Vin', 'Vout', 'Vout')\n    \n    @staticmethod\n    def Theory():\n        \"\"\"Analog Electronics: Circuits, Systems and Signal Processing \n        Crecraft Gergely\"\"\"\n        A,Zi, Zo, s=symbols('A, Z_i, Z_o s')\n        H=Function('H')(s); Zin=Function('Z_ifb')(s); Zout=Function('Z_ofb')(s)\n        TF=Eq(H, A/(1+A)); Zin=Eq(Zin, (1+A)*Zi); Zout=Eq(Zout, Zo/(1+A))\n        return TF, Zin, Zout\n    \n```\n\n\n```python\n#Print out the Buffer Op Amp Theory\nBufferOpAmp.Theory()\n```\n\n\n```python\n#create the Test Bench and Bind to this instance the BufferOpAmp Topo\nTB=OnePortOpAmpTB(BufferOpAmp)\n#Setup the Testbench and print the TB\nTB.SetupCir()\n#Run the AC Bode Simulation\nTB.Simulate()\n#View Bode Simulation\nTB.PlotResults()\n```\n\n# Inverting\n\n\n\n\n```python\nclass InvertingOpAmp(SubCircuitFactory):\n    \"\"\"\n    Inverting OpAmp SubCir\n    Termanals:\n        Vin\n        Vout\n    Parms:\n        R1[Ohms]\n        R2[Ohms]\n    \"\"\"\n    \n    __name__='InvertingOpAmp'\n    __nodes__=('Vin','Vout')\n    \n    def __init__(self, R1=1, R2=1):\n        super().__init__()\n        self.R1=R1; self.R2=R2\n        \n        self.R('1', 'Vin', '2', R1@u_\u03a9)\n        self.R('2', '2', 'Vout', R2@u_\u03a9)\n        \n        self.subcircuit(BasicOperationalAmplifier())\n        self.X('op', 'BasicOperationalAmplifier', self.gnd, '2', 'Vout')\n        self.Theory()\n    \n    @staticmethod\n    def Theory():\n        \"\"\"Analog Electronics: Circuits, Systems and Signal Processing \n        Crecraft Gergely\"\"\"        \n        R1, R2=symbols('R_1, R_2', real=True, postive=True)\n        A,Zi, Zo, s=symbols('A, Z_i, Z_o s')\n        H=Function('H')(s); Zin=Function('Z_in')(s); Zout=Function('Z_out')(s)\n        TF=Eq(H, -R2/R1)\n        Zin=Eq(Zin, R1)\n        Zout=Eq(Zout, Zo*(R1+R2)/(A*R1))\n        return TF, Zin, Zout\n        \n    \n```\n\n\n```python\n#Print out the Inverting Op Amp Theory\nInvertingOpAmp.Theory()\n```\n\n\n```python\nclass InvertingExp():\n    \"\"\"\n    Class to provide GUI for Inverting Amplifer\n    \"\"\"\n    def __init__(self):\n        \"\"\"\n        Front end and binding to backend\n        \"\"\"\n        #create the GUI elments\n        self.R1Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R1 kOhm',\n                                         )\n        self.R2Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R2 kOhm',\n                                         )\n        #layout\n        self.RSVBox=widgets.VBox([self.R1Slider, self.R2Slider])\n        \n        #bind to the backend\n        I=widgets.interact_manual(self.BackEnd, R1=self.R1Slider, \n                              R2=self.R2Slider)\n        display(I)\n    \n    def BackEnd(self, R1, R2):\n        \"\"\"\n        The backend wrapper to the TB and simulation\n        \"\"\"\n        \n        #create the Test Bench and Bind to this instance the InvertingOpAmp Topo\n        TB=OnePortOpAmpTB(InvertingOpAmp)\n        #Setup the Testbench; use a R1=20 Ohm,R2=5 Ohm and print the TB\n        TB.SetupCir(**{'R1':R1*1e3, 'R2':R2*1e3})\n        #Run the AC Bode Simulation\n        TB.Simulate()\n        #View Bode Simulation\n        TB.PlotResults()\n\n```\n\n\n```python\nInvertingExp();\n```\n\n\n    interactive(children=(FloatSlider(value=50.0, description='R1 kOhm', min=10.0, step=5.0), FloatSlider(value=50\u2026\n\n\n\n    <function ipywidgets.widgets.interaction._InteractFactory.__call__.<locals>.<lambda>>\n\n\n# Noninverting\n\n\n\n\n```python\nclass NonInvertingOpAmp(SubCircuitFactory):\n    \"\"\"\n    Non-Inverting OpAmp SubCir\n    Termanals:\n        Vin\n        Vout\n    Parms:\n        R1\n        R2\n    \"\"\"\n    \n    __name__='NonInvertingOpAmp'\n    __nodes__=('Vin','Vout')\n    \n    def __init__(self, R1, R2):\n        super().__init__()\n        self.R1=R1; self.R2=R2\n        \n        self.R('1', '2', self.gnd, R1@u_\u03a9)\n        self.R('2', '2', 'Vout', R2@u_\u03a9)\n        \n        self.subcircuit(BasicOperationalAmplifier())\n        self.X('op', 'BasicOperationalAmplifier', 'Vin', '2', 'Vout')\n    \n    @staticmethod\n    def Theory():\n        \"\"\"Analog Electronics: Circuits, Systems and Signal Processing \n        Crecraft Gergely\"\"\"        \n        R1, R2=symbols('R_1, R_2', real=True, postive=True)\n        A,Zi, Zo, s=symbols('A, Z_i, Z_o s')\n        H=Function('H')(s); Zin=Function('Z_in')(s); Zout=Function('Z_out')(s)\n        TF=Eq(H, (A(R1+R2))/(R2(1+A)+R1))\n        Zin=Eq(Zin, Zi*((1+A)*R2+R1)/(R2+(1-A)*R1))\n        Zout=Eq(Zout, Zo*(R1+R2)/(R1+(1+A)*R2))\n        return TF, Zin, Zout\n        \n\n```\n\n\n```python\n#Print out the NonInverting Op Amp Theory\nNonInvertingOpAmp.Theory()\n```\n\n\n```python\nclass NonInvertingExp():\n    \"\"\"\n    Class to provide GUI for Inverting Amplifer\n    \"\"\"\n    def __init__(self):\n        \"\"\"\n        Front end and binding to backend\n        \"\"\"\n        #create the GUI elments\n        self.R1Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R1 kOhm'\n                                         )\n        self.R2Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R2 kOhm'\n                                         )\n        #layout\n        self.RSVBox=widgets.VBox([self.R1Slider, self.R2Slider])\n        \n        #bind to the backend\n        I=widgets.interact_manual(self.BackEnd, R1=self.R1Slider, \n                              R2=self.R2Slider)\n        display(I)\n    \n    def BackEnd(self, R1, R2):\n        \"\"\"\n        The backend wrapper to the TB and simulation\n        \"\"\"\n        \n        #create the Test Bench and Bind to this instance the NonInverting Topo\n        TB=OnePortOpAmpTB(NonInvertingOpAmp)\n        #Setup the Testbench; use a R1=20 Ohm,R2=5 Ohm and print the TB\n        TB.SetupCir(**{'R1':R1*1e3, 'R2':R2*1e3})\n        #Run the AC Bode Simulation\n        TB.Simulate()\n        #View Bode Simulation\n        TB.PlotResults()\n\n```\n\n\n```python\nNonInvertingExp();\n```\n\n\n    interactive(children=(FloatSlider(value=50.0, description='R1 kOhm', min=10.0, step=5.0), FloatSlider(value=50\u2026\n\n\n\n    <function ipywidgets.widgets.interaction._InteractFactory.__call__.<locals>.<lambda>>\n\n\n# Miller Capactive Integrator \n\n\n\n\n```python\nclass MillerCapIntOpAmp(SubCircuitFactory):\n    \"\"\"\n    Inverting OpAmp SubCir\n    Termanals:\n        Vin\n        Vout\n    Parms:\n        R1[Ohms]\n        C1[Fards]\n    \"\"\"\n    \n    __name__='MillerCapIntOpAmp'\n    __nodes__=('Vin','Vout')\n    \n    def __init__(self, R1=1, C1=1):\n        super().__init__()\n        self.R1=R1; self.C1=C1\n        \n        self.R('1', 'Vin', '2', R1@u_\u03a9)\n        self.C('1', '2', 'Vout', C1@u_F)\n        \n        self.subcircuit(BasicOperationalAmplifier())\n        self.X('op', 'BasicOperationalAmplifier', self.gnd, '2', 'Vout')\n        self.Theory()\n    \n    @staticmethod\n    def Theory():\n        \"\"\"Analog Electronics: Circuits, Systems and Signal Processing \n        Crecraft Gergely\"\"\"        \n        R1, C1=symbols('R_1, C_1', real=True, postive=True)\n        A,Zi, Zo, s=symbols('A, Z_i, Z_o s')\n        H=Function('H')(s); Zin=Function('Z_in')(s); Zout=Function('Z_out')(s)\n        TF=Eq(H, -(1/(s*C1))/R1)\n        Zin=simplify(Eq(Zin, R1))\n        Zout=Eq(Zout, Zo/(A(1+s*C1*R1)))\n        return TF, Zin, Zout\n        \n    \n```\n\n\n```python\n#Print out the MillerCapInt Op Amp Theory\nMillerCapIntOpAmp.Theory()\n```\n\n\n```python\nclass MillerCapIntExp():\n    \"\"\"\n    Class to provide GUI for  MillerCapInt\n    \"\"\"\n    def __init__(self):\n        \"\"\"\n        Front end and binding to backend\n        \"\"\"\n        #create the GUI elments\n        self.R1Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R1 kOhm',\n                                         readout_format='.1e')\n        self.C1Slider=widgets.FloatSlider(value=50,\n                                         min=1, max=500, step=25,\n                                         description='C1 pF')\n        #layout\n        self.RSVBox=widgets.VBox([self.R1Slider, self.C1Slider])\n        \n        #bind to the backend\n        I=widgets.interact_manual(self.BackEnd, R1=self.R1Slider, \n                              C1=self.C1Slider)\n        display(I)\n    \n    def BackEnd(self, R1, C1):\n        \"\"\"\n        The backend wrapper to the TB and simulation\n        \"\"\"\n        \n        #create the Test Bench and Bind to this instance the MillerCapInt Topo\n        TB=OnePortOpAmpTB(MillerCapIntOpAmp)\n        #Setup the Testbench; use a R1=20 Ohm,C1=10 muF and print the TB\n        TB.SetupCir(**{'R1':R1*1e3, 'C1':C1*1e-12})\n        #Run the AC Bode Simulation\n        TB.Simulate()\n        #View Bode Simulation\n        TB.PlotResults()\n```\n\n\n```python\nMillerCapIntExp()\n\n```\n\n\n    interactive(children=(FloatSlider(value=50.0, description='R1 kOhm', min=10.0, readout_format='.1e', step=5.0)\u2026\n\n\n\n    <function ipywidgets.widgets.interaction._InteractFactory.__call__.<locals>.<lambda>>\n\n\n\n\n\n    <__main__.MillerCapIntExp at 0x7fd2aeb03080>\n\n\n\n# Miller Inductive Integrator \n\n\n\n\n```python\nclass MillerIndIntOpAmp(SubCircuitFactory):\n    \"\"\"\n    Inverting OpAmp SubCir\n    Termanals:\n        Vin\n        Vout\n    Parms:\n        R1[Ohms]\n        L1[Henrys]\n    \"\"\"\n    \n    __name__='MillerIndIntOpAmp'\n    __nodes__=('Vin','Vout')\n    \n    def __init__(self, R1=1, L1=1):\n        super().__init__()\n        self.R1=R1; self.L1=L1\n        \n        self.L('1', 'Vin', '2', L1@u_H)\n        self.R('1', '2', 'Vout', R1@u_\u03a9)\n        \n        self.subcircuit(BasicOperationalAmplifier())\n        self.X('op', 'BasicOperationalAmplifier', self.gnd, '2', 'Vout')\n        self.Theory()\n    \n    @staticmethod\n    def Theory():\n        \"\"\"Analog Electronics: Circuits, Systems and Signal Processing \n        Crecraft Gergely\"\"\"        \n        R1, L1=symbols('R_1, L_1', real=True, postive=True)\n        A,Zi, Zo, s=symbols('A, Z_i, Z_o s')\n        H=Function('H')(s); Zin=Function('Z_in')(s); Zout=Function('Z_out')(s)\n        TF=Eq(H, -R1/(s*L1))\n        Zin=Eq(Zin, s*L1)\n        Zout=simplify(Eq(Zout, Zo*(s*L1+R1)/(A*s*L1)))\n        return TF, Zin, Zout\n        \n```\n\n\n```python\n#Print out the MillerIndInt Op Amp Theory\nMillerIndIntOpAmp.Theory()\n```\n\n\n```python\nclass MillerIndIntExp():\n    \"\"\"\n    Class to provide GUI for  MillerIndInt\n    \"\"\"\n    def __init__(self):\n        \"\"\"\n        Front end and binding to backend\n        \"\"\"\n        #create the GUI elments\n        self.R1Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R1 kOhm',\n                                         readout_format='.1e')\n        self.L1Slider=widgets.FloatSlider(value=50,\n                                         min=1, max=500, step=25,\n                                         description='L1 uH')\n        #layout\n        self.RSVBox=widgets.VBox([self.R1Slider, self.L1Slider])\n        \n        #bind to the backend\n        I=widgets.interact_manual(self.BackEnd, R1=self.R1Slider, \n                              L1=self.L1Slider)\n        display(I)\n    \n    def BackEnd(self, R1, L1):\n        \"\"\"\n        The backend wrapper to the TB and simulation\n        \"\"\"\n        \n        #create the Test Bench and Bind to this instance the MillerCapInt Topo\n        TB=OnePortOpAmpTB(MillerIndIntOpAmp)\n        #Setup the Testbench; use a R1=20 Ohm,L1=10 muH and print the TB\n        TB.SetupCir(**{'R1':R1*1e3, 'L1':L1*1e-6})\n        #Run the AC Bode Simulation\n        TB.Simulate()\n        #View Bode Simulation\n        TB.PlotResults()\n```\n\n\n```python\nMillerIndIntExp();\n```\n\n\n    interactive(children=(FloatSlider(value=50.0, description='R1 kOhm', min=10.0, readout_format='.1e', step=5.0)\u2026\n\n\n\n    <function ipywidgets.widgets.interaction._InteractFactory.__call__.<locals>.<lambda>>\n\n\n#  Low Pass 1Pole\n\n\n\n\n```python\nclass LowPass1POpAmp(SubCircuitFactory):\n    \"\"\"\n    Single Pole Low Pass OpAmp SubCir\n\n    Termanals:\n        Vin\n        Vout\n    Parms:\n        R1[Ohms]\n        R2[Ohms]\n        C1[Farads]\n    \"\"\"\n    \n    __name__='LowPass1POpAmp'\n    __nodes__=('Vin','Vout')\n    \n    def __init__(self, R1=1, R2=1, C1=1):\n        super().__init__()\n        self.R1=R1; self.R2=R2; self.C1=C1\n        \n        self.R('1', 'Vin', '2', R1@u_\u03a9)\n        self.R('2', '2', 'Vout', R2@u_\u03a9)\n        self.C('1', '2', 'Vout', C1@u_F)\n        \n        self.subcircuit(BasicOperationalAmplifier())\n        #non, inv, out\n        self.X('op', 'BasicOperationalAmplifier', 'Vin', '2', 'Vout')\n        \n    @staticmethod\n    def Theory():\n        \"\"\"Analog Electronics: Circuits, Systems and Signal Processing \n        Crecraft Gergely\"\"\"        \n        R1, R2, C1=symbols('R_1, R_2, C_1', real=True, postive=True)\n        A,Zi, Zo, s=symbols('A, Z_i, Z_o s')\n        H=Function('H')(s); Zin=Function('Z_in')(s); Zout=Function('Z_out')(s)\n        TF=simplify(Eq(H, -(R2/(R2*s*C1+1))/R1))\n        Zin=Eq(Zin, R1)\n        Zout=simplify(Eq(Zout, Zo*(R1+(R2/(R2*s*C1+1)))/(A*R1)))\n        return TF, Zin, Zout\n        \n\n```\n\n\n```python\nLowPass1POpAmp.Theory()\n```\n\n\n```python\nclass LowPass1POpAmpExp():\n    \"\"\"\n    Class to provide GUI for  LowPass1POpAmp\n    \"\"\"\n    def __init__(self):\n        \"\"\"\n        Front end and binding to backend\n        \"\"\"\n        #create the GUI elments\n        self.R1Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R1 kOhm',\n                                         readout_format='.1e')\n        \n        self.R2Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R2 kOhm',\n                                         readout_format='.1e')\n        \n        self.C1Slider=widgets.FloatSlider(value=50,\n                                         min=1, max=500, step=25,\n                                         description='C1 pF')\n        #layout\n        self.RSVBox=widgets.VBox([self.R1Slider, self.R2Slider, self.C1Slider])\n        \n        #bind to the backend\n        I=widgets.interact_manual(self.BackEnd, R1=self.R1Slider,\n                                  R2=self.R2Slider,\n                              C1=self.C1Slider)\n        display(I)\n    \n    def BackEnd(self, R1, R2, C1):\n        \"\"\"\n        The backend wrapper to the TB and simulation\n        \"\"\"\n        \n        #create the Test Bench and Bind to this instance the LowPass1POpAmp Topo\n        TB=OnePortOpAmpTB(LowPass1POpAmp)\n        #Setup the Testbench; use a R1=20 Ohm, R2=5 Ohm,C1=10 muH and print the TB\n        TB.SetupCir(**{'R1':R1*1e3, 'R2':R2*1e3, 'C1':C1*1e-12})\n        #Run the AC Bode Simulation\n        TB.Simulate()\n        #View Bode Simulation\n        TB.PlotResults()\n\n\n```\n\n\n```python\nLowPass1POpAmpExp();\n```\n\n\n    interactive(children=(FloatSlider(value=50.0, description='R1 kOhm', min=10.0, readout_format='.1e', step=5.0)\u2026\n\n\n\n    <function ipywidgets.widgets.interaction._InteractFactory.__call__.<locals>.<lambda>>\n\n\n# Miller Capacitive Differentiator \n\n\n\n\n```python\nclass MillerCapDiff(SubCircuitFactory):\n    \"\"\"\n    Miller Capacitive Differentiator  OpAmp SubCir\n    Termanals:\n        Vin\n        Vout\n    Parms:\n        R1[Ohms]\n        C1[Farads]\n    \"\"\"\n    \n    __name__='MillerCapDiff'\n    __nodes__=('Vin','Vout')\n    \n    def __init__(self, R1=1, C1=1):\n        super().__init__()\n        self.R1=R1; self.C1=C1\n        \n        self.C('1', 'Vin', '2', C1@u_F)\n        self.R('1', '2', 'Vout', R1@u_\u03a9)\n        \n        self.subcircuit(BasicOperationalAmplifier())\n        self.X('op', 'BasicOperationalAmplifier', self.gnd, '2', 'Vout')\n        self.Theory()\n    \n    @staticmethod\n    def Theory():\n        \"\"\"Analog Electronics: Circuits, Systems and Signal Processing \n        Crecraft Gergely\"\"\"        \n        R1, R2, C1=symbols('R_1, R_2, C_1', real=True, postive=True)\n        A,Zi, Zo, s=symbols('A, Z_i, Z_o s')\n        H=Function('H')(s); Zin=Function('Z_in')(s); Zout=Function('Z_out')(s)\n        TF=Eq(H, -R1/(1/(s*C1)))\n        Zin=Eq(Zin, (1/(s*C1)))\n        Zout=simplify(Eq(Zout, Zo*((1/(s*C1))+R1)/(A*(1/(s*C1)))))\n        return TF, Zin, Zout\n    \n```\n\n\n```python\nMillerCapDiff.Theory()\n```\n\n\n```python\nclass MillerCapDiffExp():\n    \"\"\"\n    Class to provide GUI for  MillerCapDiff\n    \"\"\"\n    def __init__(self):\n        \"\"\"\n        Front end and binding to backend\n        \"\"\"\n        #create the GUI elments\n        self.R1Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R1 kOhm',\n                                         readout_format='.1e')\n        self.C1Slider=widgets.FloatSlider(value=50,\n                                         min=1, max=500, step=25,\n                                         description='C1 pF')\n        #layout\n        self.RSVBox=widgets.VBox([self.R1Slider, self.C1Slider])\n        \n        #bind to the backend\n        I=widgets.interact_manual(self.BackEnd, R1=self.R1Slider, \n                              C1=self.C1Slider)\n        display(I)\n    \n    def BackEnd(self, R1, C1):\n        \"\"\"\n        The backend wrapper to the TB and simulation\n        \"\"\"\n        \n        #create the Test Bench and Bind to this instance the MillerCapDiff Topo\n        TB=OnePortOpAmpTB(MillerCapDiff)\n        #Setup the Testbench; use a R1=20 Ohm,C1=10 muF and print the TB\n        TB.SetupCir(**{'R1':R1*1e3, 'C1':C1*1e-12})\n        #Run the AC Bode Simulation\n        TB.Simulate()\n        #View Bode Simulation\n        TB.PlotResults()\n```\n\n\n```python\nMillerCapDiffExp();\n```\n\n\n    interactive(children=(FloatSlider(value=50.0, description='R1 kOhm', min=10.0, readout_format='.1e', step=5.0)\u2026\n\n\n\n    <function ipywidgets.widgets.interaction._InteractFactory.__call__.<locals>.<lambda>>\n\n\n# Miller Inductive Differentiator \n\n\n\n\n```python\nclass MillerIndDiff(SubCircuitFactory):\n    \"\"\"\n    Miller Inductive Differentiator  OpAmp SubCir\n    Termanals:\n        Vin\n        Vout\n    Parms:\n        R1[Ohms]\n        L1[Henerys]\n    \"\"\"\n    \n    __name__='MillerIndDiff'\n    __nodes__=('Vin','Vout')\n    \n    def __init__(self, R1=1, L1=1):\n        super().__init__()\n        self.R1=R1; self.L1=L1\n        \n        self.R('1', 'Vin', '2', R1@u_\u03a9)\n        self.L('1', '2', 'Vout', L1@u_H)\n        \n        self.subcircuit(BasicOperationalAmplifier())\n        self.X('op', 'BasicOperationalAmplifier', self.gnd, '2', 'Vout')\n        self.Theory()\n    \n    @staticmethod\n    def Theory():\n        \"\"\"Analog Electronics: Circuits, Systems and Signal Processing \n        Crecraft Gergely\"\"\"        \n        R1, R2, L1=symbols('R_1, R_2, L_1', real=True, postive=True)\n        A,Zi, Zo, s=symbols('A, Z_i, Z_o s')\n        H=Function('H')(s); Zin=Function('Z_in')(s); Zout=Function('Z_out')(s)\n        TF=Eq(H, -(s*L1)/R1)\n        Zin=Eq(Zin, R1)\n        Zout=Eq(Zout, Zo*(R1+(s*L1))/(A*R1))\n        return TF, Zin, Zout\n        \n```\n\n\n```python\nMillerIndDiff.Theory()\n```\n\n\n```python\nclass MillerIndDiffExp():\n    \"\"\"\n    Class to provide GUI for  MillerIndDiff\n    \"\"\"\n    def __init__(self):\n        \"\"\"\n        Front end and binding to backend\n        \"\"\"\n        #create the GUI elments\n        self.R1Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R1 kOhm',\n                                         readout_format='.1e')\n        self.L1Slider=widgets.FloatSlider(value=50,\n                                         min=1, max=500, step=25,\n                                         description='L1 uH')\n        #layout\n        self.RSVBox=widgets.VBox([self.R1Slider, self.L1Slider])\n        \n        #bind to the backend\n        I=widgets.interact_manual(self.BackEnd, R1=self.R1Slider, \n                              L1=self.L1Slider)\n        display(I)\n    \n    def BackEnd(self, R1, L1):\n        \"\"\"\n        The backend wrapper to the TB and simulation\n        \"\"\"\n        \n        #create the Test Bench and Bind to this instance the MillerCapInt Topo\n        TB=OnePortOpAmpTB(MillerIndDiff)\n        #Setup the Testbench; use a R1=20 Ohm,L1=10 muH and print the TB\n        TB.SetupCir(**{'R1':R1*1e3, 'L1':L1*1e-12})\n        #Run the AC Bode Simulation\n        TB.Simulate()\n        #View Bode Simulation\n        TB.PlotResults()\n```\n\n\n```python\nMillerIndDiffExp();\n```\n\n\n    interactive(children=(FloatSlider(value=50.0, description='R1 kOhm', min=10.0, readout_format='.1e', step=5.0)\u2026\n\n\n\n    <function ipywidgets.widgets.interaction._InteractFactory.__call__.<locals>.<lambda>>\n\n\n# High Pass 1Zero\n\n\n\n\n```python\nclass HighPass1ZOpAmp(SubCircuitFactory):\n    \"\"\"\n    Single Pole Low Pass OpAmp SubCir\n\n    Termanals:\n        Vin\n        Vout\n    Parms:\n        R1[Ohms]\n        R2[Ohms]\n        L1[Henerys]\n    \"\"\"\n    \n    __name__='HighPass1ZOpAmp'\n    __nodes__=('Vin','Vout')\n    \n    def __init__(self, R1=1, R2=1, L1=1):\n        super().__init__()\n        self.R1=R1; self.R2=R2; self.L1=L1\n        \n        self.R('1', 'Vin', '2', R1@u_\u03a9)\n        self.R('2', '2', 'Vout', R2@u_\u03a9)\n        self.L('1', '2', 'Vout', L1@u_H)\n        \n        self.subcircuit(BasicOperationalAmplifier())\n        #non, inv, out\n        self.X('op', 'BasicOperationalAmplifier', 'Vin', '2', 'Vout')\n        \n    @staticmethod\n    def Theory():\n        \"\"\"Analog Electronics: Circuits, Systems and Signal Processing \n        Crecraft Gergely\"\"\"        \n        R1, R2, L1=symbols('R_1, R_2, L_1', real=True, postive=True)\n        A,Zi, Zo, s=symbols('A, Z_i, Z_o s')\n        H=Function('H')(s); Zin=Function('Z_in')(s); Zout=Function('Z_out')(s)\n        TF=simplify(Eq(H, -((R2*s*L1)/(s*L1+R2))/R1))\n        Zin=Eq(Zin, R1)\n        Zout=simplify(Eq(Zout, Zo*(R1+((R2*s*L1)/(s*L1+R2)))/(A*R1)))\n        return TF, Zin, Zout\n        \n\n```\n\n\n```python\nHighPass1ZOpAmp.Theory()\n```\n\n\n```python\nclass HighPass1ZExp():\n    \"\"\"\n    Class to provide GUI for  HighPass1ZOpAmp\n    \"\"\"\n    def __init__(self):\n        \"\"\"\n        Front end and binding to backend\n        \"\"\"\n        #create the GUI elments\n        self.R1Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R1 kOhm',\n                                         readout_format='.1e')\n        \n        self.R2Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R2 kOhm',\n                                         readout_format='.1e')\n        \n        self.L1Slider=widgets.FloatSlider(value=50,\n                                         min=1, max=500, step=25,\n                                         description='L1 uH')\n        #layout\n        self.RSVBox=widgets.VBox([self.R1Slider, self.R2Slider, self.L1Slider])\n        \n        #bind to the backend\n        I=widgets.interact_manual(self.BackEnd, R1=self.R1Slider,\n                                  R2=self.R2Slider,\n                              L1=self.L1Slider)\n        display(I)\n    \n    def BackEnd(self, R1, R2, L1):\n        \"\"\"\n        The backend wrapper to the TB and simulation\n        \"\"\"\n        \n        #create the Test Bench and Bind to this instance the HighPass1ZOpAmp Topo\n        TB=OnePortOpAmpTB(HighPass1ZOpAmp)\n        #Setup the Testbench; use a R1=20 Ohm,R2=5 Ohm, L1=10 muH and print the TB\n        TB.SetupCir(**{'R1':R1*1e3, 'R2':R2*1e3, 'L1':L1*1e-6})\n        #Run the AC Bode Simulation\n        TB.Simulate()\n        #View Bode Simulation\n        TB.PlotResults()\n\n\n```\n\n\n```python\nHighPass1ZExp();\n```\n\n\n    interactive(children=(FloatSlider(value=50.0, description='R1 kOhm', min=10.0, readout_format='.1e', step=5.0)\u2026\n\n\n\n    <function ipywidgets.widgets.interaction._InteractFactory.__call__.<locals>.<lambda>>\n\n\n# AllPass (Phase) Filter\nhttp://www.analog.com/media/en/training-seminars/tutorials/MT-202.pdf\n\n## First Order Cap First \n\n\n\n```python\nclass AllPass1CapFOpAmp(SubCircuitFactory):\n    \"\"\"\n    AllPass 1st Order Cap First\n    Termanals:\n        Vin\n        Vout\n    Parms:\n        R1[Ohms]\n        R2[Ohms]\n        R3[Ohms]\n        C1[Farads]\n        \n    \"\"\"\n    \n    __name__='AllPass1CapFOpAmp'\n    __nodes__=('Vin','Vout')\n    \n    def __init__(self, R1=1, R2=1, R3=1, C1=1):\n        super().__init__()\n        self.R1=R1; self.R2=R2; self.R3=R3\n        self.C1=C1\n        \n        #inverting feedback stucter\n        self.R('1', 'Vin', '2', R1@u_\u03a9)\n        self.R('2', '2', 'Vout', R2@u_\u03a9)\n        \n        #Voltage Divider\n        self.C('1', 'Vin', '3', C1@u_F)\n        self.R('3', '3', self.gnd, R3@u_\u03a9)\n        \n        self.subcircuit(BasicOperationalAmplifier())\n        self.X('op', 'BasicOperationalAmplifier', '3', '2', 'Vout')\n        self.Theory()\n    \n    @staticmethod\n    def Theory():\n        A, R1, R2, R3, C1=symbols('A, R_1, R_2, R_3, C_1', real=True, postive=True)\n        Vn, Vp, Vo, Vi=symbols('V_n, V_p, V_o, V_i')\n        s=symbols('s')\n        VpEq=Eq(Vp, (s*C1*R3)/(1+s*C1*R3)* Vi); VpEq\n        VnEq=Eq(Vn, (R1/(R1+R2))*Vo+(R2/(R1+R2))*Vi); VnEq\n        VoEq=Eq(Vo, A*(Vp-Vn)); VoEq\n        VoEq=VoEq.subs({VpEq.lhs: VpEq.rhs, VnEq.lhs:VnEq.rhs})\n        H=Function('H')(s)\n        TF=Eq(H, (solve(VoEq, Vo)[0]/Vi)); TF\n        return TF\n\n```\n\n\n```python\nclass AllPass1CapFExp():\n    \"\"\"\n    Class to provide GUI for Inverting AllPass1CapF\n    \"\"\"\n    def __init__(self):\n        \"\"\"\n        Front end and binding to backend\n        \"\"\"\n        #create the GUI elments\n        self.R1Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R1 kOhm',\n                                         )\n        self.R2Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R2 kOhm',\n                                         )\n        \n        self.R3Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R2 kOhm',\n                                         )\n        \n        \n        self.C1Slider=widgets.FloatSlider(value=50,\n                                         min=1, max=500, step=25,\n                                         description='C1 pF')\n        #layout\n        self.RSVBox=widgets.VBox([self.R1Slider, self.R2Slider])\n        \n        #bind to the backend\n        I=widgets.interact_manual(self.BackEnd, R1=self.R1Slider, \n                              R2=self.R2Slider, R3=self.R3Slider, C1=self.C1Slider)\n        display(I)\n    \n    def BackEnd(self, R1, R2, R3, C1):\n        \"\"\"\n        The backend wrapper to the TB and simulation\n        \"\"\"\n        \n        #create the Test Bench and Bind to this instance the HighPass1ZOpAmp Topo\n        TB=OnePortOpAmpTB(AllPass1CapFOpAmp)\n        #Setup the Testbench; use a R1=20 Ohm,R2=5 Ohm, L1=10 muH and print the TB\n        TB.SetupCir(**{'R1':R1*1e3, 'R2':R2*1e3, 'R3':R3*1e3, 'C1':C1*1e-9})\n        #Run the AC Bode Simulation\n        TB.Simulate()\n        #View Bode Simulation\n        TB.PlotResults()\n\n```\n\n\n```python\nAllPass1CapFExp()\n```\n\n\n    interactive(children=(FloatSlider(value=50.0, description='R1 kOhm', min=10.0, step=5.0), FloatSlider(value=50\u2026\n\n\n\n    <function ipywidgets.widgets.interaction._InteractFactory.__call__.<locals>.<lambda>>\n\n\n\n\n\n    <__main__.AllPass1CapFExp at 0x7fd2ae81c390>\n\n\n\n## First Order Cap Second \n\n\n\n```python\nclass AllPass1CapSOpAmp(SubCircuitFactory):\n    \"\"\"\n    AllPass 1st Order Cap Second\n    Termanals:\n        Vin\n        Vout\n    Parms:\n        R1[Ohms]\n        R2[Ohms]\n        R3[Ohms]\n        C1[Farads]\n        \n    \"\"\"\n    \n    __name__='AllPass1CapSOpAmp'\n    __nodes__=('Vin','Vout')\n    \n    def __init__(self, R1=1, R2=1, R3=1, C1=1):\n        super().__init__()\n        self.R1=R1; self.R2=R2; self.R3=R3\n        self.C1=C1\n        \n        #inverting feedback stucter\n        self.R('1', 'Vin', '2', R1@u_\u03a9)\n        self.R('2', '2', 'Vout', R2@u_\u03a9)\n        \n        #Voltage Divider\n        self.R('3', 'Vin', '3', R3@u_\u03a9)\n        self.C('1', '3', self.gnd, C1@u_F)\n\n        \n        self.subcircuit(BasicOperationalAmplifier())\n        self.X('op', 'BasicOperationalAmplifier', '3', '2', 'Vout')\n        self.Theory()\n    \n    @staticmethod\n    def Theory():\n        A, R1, R2, R3, C1=symbols('A, R_1, R_2, R_3, C_1', real=True, postive=True)\n        Vn, Vp, Vo, Vi=symbols('V_n, V_p, V_o, V_i')\n        s=symbols('s')\n        VpEq=simplify(Eq(Vp, ((1/(s*C1))/((1/s*C1 +R3)))* Vi)); VpEq\n        VnEq=Eq(Vn, (R1/(R1+R2))*Vo+(R2/(R1+R2))*Vi); VnEq\n        VoEq=Eq(Vo, A*(Vp-Vn)); VoEq\n        VoEq=VoEq.subs({VpEq.lhs: VpEq.rhs, VnEq.lhs:VnEq.rhs})\n        H=Function('H')(s)\n        TF=Eq(H, (solve(VoEq, Vo)[0]/Vi)); TF\n        return TF\n\n```\n\n\n```python\nAllPass1CapSOpAmp.Theory()\n```\n\n\n```python\nclass AllPass1CapSExp():\n    \"\"\"\n    Class to provide GUI for Inverting AllPass1CapS\n    \"\"\"\n    def __init__(self):\n        \"\"\"\n        Front end and binding to backend\n        \"\"\"\n        #create the GUI elments\n        self.R1Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R1 kOhm',\n                                         )\n        self.R2Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R2 kOhm',\n                                         )\n        \n        self.R3Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R2 kOhm',\n                                         )\n        \n        \n        self.C1Slider=widgets.FloatSlider(value=50,\n                                         min=1, max=500, step=25,\n                                         description='C1 pF')\n        #layout\n        self.RSVBox=widgets.VBox([self.R1Slider, self.R2Slider])\n        \n        #bind to the backend\n        I=widgets.interact_manual(self.BackEnd, R1=self.R1Slider, \n                              R2=self.R2Slider, R3=self.R3Slider, C1=self.C1Slider)\n        display(I)\n    \n    def BackEnd(self, R1, R2, R3, C1):\n        \"\"\"\n        The backend wrapper to the TB and simulation\n        \"\"\"\n        \n        #create the Test Bench and Bind to this instance the HighPass1ZOpAmp Topo\n        TB=OnePortOpAmpTB(AllPass1CapSOpAmp)\n        #Setup the Testbench; use a R1=20 Ohm,R2=5 Ohm, L1=10 muH and print the TB\n        TB.SetupCir(**{'R1':R1*1e3, 'R2':R2*1e3, 'R3':R3*1e3, 'C1':C1*1e-9})\n        #Run the AC Bode Simulation\n        TB.Simulate()\n        #View Bode Simulation\n        TB.PlotResults()\n\n```\n\n\n```python\nAllPass1CapSExp()\n```\n\n\n    interactive(children=(FloatSlider(value=50.0, description='R1 kOhm', min=10.0, step=5.0), FloatSlider(value=50\u2026\n\n\n\n    <function ipywidgets.widgets.interaction._InteractFactory.__call__.<locals>.<lambda>>\n\n\n\n\n\n    <__main__.AllPass1CapSExp at 0x7fd2ae7de780>\n\n\n\n# Sallen-Key Filter\n[Analog Electronics: Circuits, Systems and Signal Processing Crecraft & Gergely](https://www.amazon.com/Analog-Electronics-Circuits-Systems-Processing-ebook/dp/B00CXO975A/ref=sr_1_1?ie=UTF8&qid=1524885102&sr=8-1&keywords=Analog+Electronics+Crecraft+Gergely) 10.6.2\n\n\n$$G=\\dfrac{A_V Y_1 Y_3}{Y_5(Y_1+Y_2+Y_3+Y_4)+Y_3(Y_1+Y_2+Y_4(1+A_V))}$$\n\n## Low Pass with Voltage Gain\n$$Y_1=R_1$$\n$$Y_2=0$$\n$$Y_3=R_3$$\n$$Y_4=sC_4$$\n$$Y_5=sC_5$$\n\n\n```python\nclass LPSKV(SubCircuitFactory):\n    \"\"\"\n    Low Pass Sallen-Key with Voltage Gain NonInverting Amp\n\n    Termanals:\n        Vin\n        Vout\n    Parms:\n        R1[Ohms]\n        R3[Ohms]\n        C4[Farads]\n        C5[Farads]\n        RF1[Ohms]: NonInverting Feedback R1\n        RF2[Ohms]: NonInverting Feedback R2\n        \n    \"\"\"\n    \n    __name__='LPSKV'\n    __nodes__=('Vin','Vout')\n    \n    def __init__(self, R1=1, R3=1, C4=1e-12, C5=1e-12, RF1=1, RF2=1):\n        super().__init__()\n        self.R1=R1; self.R3=R3; self.C4=C4; self.C5=C5\n        self.RF1=RF1; self.RF2=RF2\n        \n        self.R('1', 'Vin', '1', R1@u_\u03a9)\n        self.R('3', '1', '2', R3@u_\u03a9)\n        self.C('4', '1', 'Vout', C4@u_F)\n        self.C('5', '2', self.gnd, C5@u_F)\n        \n        \n        self.subcircuit(NonInvertingOpAmp(R1=RF1, R2=RF2))\n        self.X('Av', 'NonInvertingOpAmp', '2', 'Vout')\n        \n    \n```\n\n\n```python\nclass LPSKVExp():\n    \"\"\"\n    Class to provide GUI for  LPSKV\n    \"\"\"\n    def __init__(self):\n        \"\"\"\n        Front end and binding to backend\n        \"\"\"\n        #create the GUI elments\n        self.R1Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R1 kOhm',\n                                         readout_format='.1e')\n        \n        self.R3Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R5 kOhm',\n                                         readout_format='.1e')\n        \n        self.C4Slider=widgets.FloatSlider(value=50,\n                                         min=1, max=500, step=25,\n                                         description='C4 pF')\n        \n        self.C5Slider=widgets.FloatSlider(value=50,\n                                         min=1, max=500, step=25,\n                                         description='C5 pF')\n        \n        self.RF1Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='RF1 kOhm',\n                                         readout_format='.1e')\n        \n        self.RF2Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='RF2 kOhm',\n                                         readout_format='.1e')\n        \n        \n        #layout\n        self.RSVBox=widgets.VBox([self.R1Slider, self.R3Slider, \n                                  self.C4Slider, self.C5Slider,\n                                 self.RF1Slider, self.RF2Slider])\n        \n        #bind to the backend\n        I=widgets.interact_manual(self.BackEnd, \n                                  R1=self.R1Slider, \n                                  R3=self.R3Slider, \n                                  C4=self.C4Slider, \n                                  C5=self.C5Slider, \n                                  RF1=self.RF1Slider, \n                                  RF2=self.RF2Slider)\n        display(I)\n    \n    def BackEnd(self, R1, R3, C4, C5, RF1, RF2):\n        \"\"\"\n        The backend wrapper to the TB and simulation\n        \"\"\"\n        \n        #create the Test Bench and Bind to this instance the LPSKV Topo\n        TB=OnePortOpAmpTB(LPSKV)\n        #Setup the Testbench; use a R1:20 Ohm,R2:5 Ohm, L1:10 muH and print the TB\n        TB.SetupCir(**{'R1':R1*1e3, 'R3':R3*1e3, 'C4':C4*1e-12, 'C5':C5*1e-12, \n                     'RF1':RF1*1e3, 'RF2':RF2*1e3})\n        #Run the AC Bode Simulation\n        TB.Simulate(fMax=10e9)\n        #View Bode Simulation\n        TB.PlotResults()\n\n```\n\n\n```python\nLPSKVExp();\n```\n\n\n    interactive(children=(FloatSlider(value=50.0, description='R1 kOhm', min=10.0, readout_format='.1e', step=5.0)\u2026\n\n\n\n    <function ipywidgets.widgets.interaction._InteractFactory.__call__.<locals>.<lambda>>\n\n\n## Band Pass with Voltage Gain\n$$Y_1=R_1$$\n$$Y_2=0$$\n$$Y_3=C_3$$\n$$Y_4=R_4$$\n$$Y_5=sC_5$$\n\n\n```python\nclass BPSKV(SubCircuitFactory):\n    \"\"\"\n    Band Pass Sallen-Key with Voltage Gain NonInverting Amp\n\n    Termanals:\n        Vin\n        Vout\n    Parms:\n        R1[Ohms]\n        R4[Ohms]\n        R5[Ohms]\n        C3[Farads]\n        C5[Farads]\n        RF1[Ohms]: NonInverting Feedback R1\n        RF2[Ohms]: NonInverting Feedback R2\n        \n    \"\"\"\n    \n    __name__='BPSKV'\n    __nodes__=('Vin','Vout')\n    \n    def __init__(self, R1=1, R4=1, R5=1, C3=1e-12, C5=1e-12, RF1=1, RF2=1):\n        super().__init__()\n        self.R1=R1; self.R4=R4; self.C3=C3; self.C5=C5\n        self.RF1=RF1; self.RF2=RF2\n        \n        self.R('1', 'Vin', '1', R1@u_\u03a9)\n        self.C('3', '1', '2', C3@u_F)\n        self.R('4', '1', 'Vout', R4@u_\u03a9)\n        self.C('5', '2', self.gnd, C5@u_F)\n        self.R('5', '2', self.gnd, R5@u_\u03a9)\n        \n        \n        self.subcircuit(NonInvertingOpAmp(R1=RF1, R2=RF2))\n        self.X('Av', 'NonInvertingOpAmp', '2', 'Vout')\n        \n    \n```\n\n\n```python\nclass BPSKVExp():\n    \"\"\"\n    Class to provide GUI for  BPSKV\n    \"\"\"\n    def __init__(self):\n        \"\"\"\n        Front end and binding to backend\n        \"\"\"\n        #create the GUI elments\n        self.R1Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R1 kOhm',\n                                         readout_format='.1e')\n        \n        self.R4Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R4 kOhm',\n                                         readout_format='.1e')\n        self.R5Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R5 kOhm',\n                                         readout_format='.1e')\n        \n        self.C3Slider=widgets.FloatSlider(value=50,\n                                         min=1, max=500, step=25,\n                                         description='C3 pF')\n        \n        self.C5Slider=widgets.FloatSlider(value=50,\n                                         min=1, max=500, step=5,\n                                         description='C5 pF')\n        \n        self.RF1Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='RF1 kOhm',\n                                         readout_format='.1e')\n        \n        self.RF2Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='RF2 kOhm',\n                                         readout_format='.1e')\n        \n        \n        #layout\n        self.RSVBox=widgets.VBox([self.R1Slider, self.R4Slider, self.R5Slider, \n                                  self.C3Slider, self.C5Slider,\n                                 self.RF1Slider, self.RF2Slider])\n        \n        #bind to the backend\n        I=widgets.interact_manual(self.BackEnd, \n                                  R1=self.R1Slider, \n                                  R4=self.R4Slider,\n                                  R5=self.R5Slider, \n                                  C3=self.C3Slider, \n                                  C5=self.C5Slider, \n                                  RF1=self.RF1Slider, \n                                  RF2=self.RF2Slider)\n        display(I)\n    \n    def BackEnd(self, R1, R4, R5, C3, C5, RF1, RF2):\n        \"\"\"\n        The backend wrapper to the TB and simulation\n        \"\"\"\n        \n        #create the Test Bench and Bind to this instance the BPSKV Topo\n        TB=OnePortOpAmpTB(BPSKV)\n        #Setup the Testbench; use a R1:20 Ohm,R2:5 Ohm, L1:10 muH and print the TB\n        TB.SetupCir(**{'R1':R1*1e3, 'R4':1e3, 'R5':1e3, \n                       'C3':C3*1e-12, 'C5':C5*1e-12, \n                     'RF1':RF1*1e3, 'RF2':RF2*1e3})\n        #Run the AC Bode Simulation\n        TB.Simulate(fMax=10e9)\n        #View Bode Simulation\n        TB.PlotResults()\n\n```\n\n\n```python\nBPSKVExp();\n```\n\n\n    interactive(children=(FloatSlider(value=50.0, description='R1 kOhm', min=10.0, readout_format='.1e', step=5.0)\u2026\n\n\n\n    <function ipywidgets.widgets.interaction._InteractFactory.__call__.<locals>.<lambda>>\n\n\n## HIgh Pass with Voltage Gain\n$$Y_1=sC_1$$\n$$Y_2=0$$\n$$Y_3=sC_3$$\n$$Y_4=R_4$$\n$$Y_5=R_5$$\n\n\n```python\nclass HPSKV(SubCircuitFactory):\n    \"\"\"\n    High Pass Sallen-Key with Voltage Gain NonInverting Amp\n\n    Termanals:\n        Vin\n        Vout\n    Parms:\n        R4[Ohms]\n        R5[Ohms]\n        C1[Farads]\n        C3[Farads]\n        RF1[Ohms]: NonInverting Feedback R1\n        RF2[Ohms]: NonInverting Feedback R2\n        \n    \"\"\"\n    \n    __name__='HPSKV'\n    __nodes__=('Vin','Vout')\n    \n    def __init__(self, R4=1, R5=1, C1=1e-12, C3=1e-12, RF1=1, RF2=1):\n        super().__init__()\n        self.R4=R4; self.R5=R5; self.C1=C1; self.C3=C3\n        self.RF1=RF1; self.RF2=RF2\n        \n        self.C('1', 'Vin', '1', C1@u_F)\n        self.C('3', '1', '2', C3@u_F)\n        self.R('4', '1', 'Vout', R4@u_\u03a9)\n        self.R('5', '2', self.gnd, R5@u_\u03a9)\n        \n        \n        self.subcircuit(NonInvertingOpAmp(R1=RF1, R2=RF2))\n        self.X('Av', 'NonInvertingOpAmp', '2', 'Vout')\n        \n    \n```\n\n\n```python\nclass HPSKVExp():\n    \"\"\"\n    Class to provide GUI for  HPSKV\n    \"\"\"\n    def __init__(self):\n        \"\"\"\n        Front end and binding to backend\n        \"\"\"\n        #create the GUI elments\n        self.R4Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R4 kOhm',\n                                         readout_format='.1e')\n        \n        \n        self.R5Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='R5 kOhm',\n                                         readout_format='.1e')\n        \n        self.C1Slider=widgets.FloatSlider(value=50,\n                                         min=1, max=500, step=25,\n                                         description='C1 pF')\n        \n        self.C3Slider=widgets.FloatSlider(value=50,\n                                         min=1, max=500, step=5,\n                                         description='C5 pF')\n        \n        self.RF1Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='RF1 kOhm',\n                                         readout_format='.1e')\n        \n        self.RF2Slider=widgets.FloatSlider(value=50,\n                                         min=10, max=100, step=5,\n                                         description='RF2 kOhm',\n                                         readout_format='.1e')\n        \n        \n        #layout\n        self.RSVBox=widgets.VBox([self.R4Slider, self.R5Slider,\n                                  self.C1Slider, self.C3Slider,\n                                 self.RF1Slider, self.RF2Slider])\n        \n        #bind to the backend\n        I=widgets.interact_manual(self.BackEnd, \n                                  R4=self.R4Slider,\n                                  R5=self.R5Slider, \n                                  C1=self.C1Slider, \n                                  C3=self.C3Slider, \n                                  RF1=self.RF1Slider, \n                                  RF2=self.RF2Slider)\n        \n        display(I)\n    \n    def BackEnd(self, R4, R5, C1, C3, RF1, RF2):\n        \"\"\"\n        The backend wrapper to the TB and simulation\n        \"\"\"\n        \n        #create the Test Bench and Bind to this instance the LPSKV Topo\n        TB=OnePortOpAmpTB(HPSKV)\n        #Setup the Testbench; use a R1:20 Ohm,R2:5 Ohm, L1:10 muH and print the TB\n        TB.SetupCir(**{'R4':R4*1e3, 'R5':R5*1e3, 'C1':C1*1e-12, 'C3':C3*1e-12, \n                     'RF1':RF1*1e3, 'RF2':RF2*1e3})\n        #Run the AC Bode Simulation\n        TB.Simulate(fMax=10e9)\n        #View Bode Simulation\n        TB.PlotResults()\n```\n\n\n```python\nHPSKVExp();\n```\n\n\n    interactive(children=(FloatSlider(value=50.0, description='R4 kOhm', min=10.0, readout_format='.1e', step=5.0)\u2026\n\n\n\n    <function ipywidgets.widgets.interaction._InteractFactory.__call__.<locals>.<lambda>>\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "bff0c702de2984e640525896fe4af37ff3f8c20c", "size": 157745, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Operational AmplifierTopologies/OpAmpLearn.ipynb", "max_stars_repo_name": "PyLCARS/PySpiceExsamples", "max_stars_repo_head_hexsha": "8b5aeaac0459cab2068f630129a11bb87f1392c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2018-02-09T04:49:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T19:10:53.000Z", "max_issues_repo_path": "Operational AmplifierTopologies/OpAmpLearn.ipynb", "max_issues_repo_name": "PyLCARS/PySpiceExsamples", "max_issues_repo_head_hexsha": "8b5aeaac0459cab2068f630129a11bb87f1392c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Operational AmplifierTopologies/OpAmpLearn.ipynb", "max_forks_repo_name": "PyLCARS/PySpiceExsamples", "max_forks_repo_head_hexsha": "8b5aeaac0459cab2068f630129a11bb87f1392c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-07-30T11:23:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T07:17:06.000Z", "avg_line_length": 54.9060215802, "max_line_length": 21104, "alphanum_fraction": 0.6432977273, "converted": true, "num_tokens": 17137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.08756383535613607, "lm_q1q2_score": 0.02899411436403965}}
{"text": "```python\n!pip install qiskit\n```\n\n    Collecting qiskit\n      Downloading qiskit-0.32.1.tar.gz (13 kB)\n    Collecting qiskit-terra==0.18.3\n      Downloading qiskit_terra-0.18.3-cp37-cp37m-manylinux2010_x86_64.whl (6.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.1 MB 7.2 MB/s \n    \u001b[?25hCollecting qiskit-aer==0.9.1\n      Downloading qiskit_aer-0.9.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (17.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 17.9 MB 499 kB/s \n    \u001b[?25hCollecting qiskit-ibmq-provider==0.18.1\n      Downloading qiskit_ibmq_provider-0.18.1-py3-none-any.whl (237 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 237 kB 55.2 MB/s \n    \u001b[?25hCollecting qiskit-ignis==0.6.0\n      Downloading qiskit_ignis-0.6.0-py3-none-any.whl (207 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 207 kB 44.5 MB/s \n    \u001b[?25hCollecting qiskit-aqua==0.9.5\n      Downloading qiskit_aqua-0.9.5-py3-none-any.whl (2.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.1 MB 51.3 MB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.16.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.9.1->qiskit) (1.19.5)\n    Requirement already satisfied: scipy>=1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.9.1->qiskit) (1.4.1)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (5.4.8)\n    Collecting dlx<=1.0.4\n      Downloading dlx-1.0.4.tar.gz (5.5 kB)\n    Requirement already satisfied: h5py<3.3.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (3.1.0)\n    Collecting quandl\n      Downloading Quandl-3.7.0-py2.py3-none-any.whl (26 kB)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (1.7.1)\n    Collecting docplex>=2.21.207\n      Downloading docplex-2.22.213.tar.gz (634 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 634 kB 58.9 MB/s \n    \u001b[?25hRequirement already satisfied: fastdtw<=0.3.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (0.3.4)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (1.1.5)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (57.4.0)\n    Collecting yfinance>=0.1.62\n      Downloading yfinance-0.1.67-py2.py3-none-any.whl (25 kB)\n    Collecting retworkx>=0.8.0\n      Downloading retworkx-0.10.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.4 MB 39.8 MB/s \n    \u001b[?25hRequirement already satisfied: scikit-learn>=0.20.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (1.0.1)\n    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.1->qiskit) (2.23.0)\n    Collecting websocket-client>=1.0.1\n      Downloading websocket_client-1.2.1-py2.py3-none-any.whl (52 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 52 kB 1.4 MB/s \n    \u001b[?25hRequirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.1->qiskit) (1.24.3)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.1->qiskit) (2.8.2)\n    Collecting requests-ntlm>=1.1.0\n      Downloading requests_ntlm-1.1.0-py2.py3-none-any.whl (5.7 kB)\n    Collecting ply>=3.10\n      Downloading ply-3.11-py2.py3-none-any.whl (49 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 49 kB 5.5 MB/s \n    \u001b[?25hCollecting python-constraint>=1.4\n      Downloading python-constraint-1.4.0.tar.bz2 (18 kB)\n    Collecting symengine>0.7\n      Downloading symengine-0.8.1-cp37-cp37m-manylinux2010_x86_64.whl (38.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 38.2 MB 1.5 MB/s \n    \u001b[?25hRequirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.18.3->qiskit) (2.6.0)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.18.3->qiskit) (0.3.4)\n    Collecting tweedledum<2.0,>=1.1\n      Downloading tweedledum-1.1.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (943 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 943 kB 42.5 MB/s \n    \u001b[?25hCollecting fastjsonschema>=2.10\n      Downloading fastjsonschema-2.15.1-py3-none-any.whl (21 kB)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from docplex>=2.21.207->qiskit-aqua==0.9.5->qiskit) (1.15.0)\n    Requirement already satisfied: cached-property in /usr/local/lib/python3.7/dist-packages (from h5py<3.3.0->qiskit-aqua==0.9.5->qiskit) (1.5.2)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.1->qiskit) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.1->qiskit) (2021.10.8)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.1->qiskit) (2.10)\n    Collecting ntlm-auth>=1.0.2\n      Downloading ntlm_auth-1.5.0-py2.py3-none-any.whl (29 kB)\n    Collecting cryptography>=1.3\n      Downloading cryptography-36.0.0-cp36-abi3-manylinux_2_24_x86_64.whl (3.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.6 MB 30.6 MB/s \n    \u001b[?25hRequirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.1->qiskit) (1.15.0)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.1->qiskit) (2.21)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.9.5->qiskit) (3.0.0)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.9.5->qiskit) (1.1.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-aqua==0.9.5->qiskit) (1.2.1)\n    Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance>=0.1.62->qiskit-aqua==0.9.5->qiskit) (0.0.10)\n    Collecting lxml>=4.5.1\n      Downloading lxml-4.6.4-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl (6.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.3 MB 51.8 MB/s \n    \u001b[?25hRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->qiskit-aqua==0.9.5->qiskit) (2018.9)\n    Requirement already satisfied: more-itertools in /usr/local/lib/python3.7/dist-packages (from quandl->qiskit-aqua==0.9.5->qiskit) (8.12.0)\n    Collecting inflection>=0.3.1\n      Downloading inflection-0.5.1-py2.py3-none-any.whl (9.5 kB)\n    Building wheels for collected packages: qiskit, dlx, docplex, python-constraint\n      Building wheel for qiskit (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for qiskit: filename=qiskit-0.32.1-py3-none-any.whl size=11776 sha256=d70f4e50b8ab84eabd662f4b9a91b2da056029717bf5d4672a9d38da31a1e61e\n      Stored in directory: /root/.cache/pip/wheels/0f/62/0a/c53eda1ead41c137c47c9730bc2771a8367b1ce00fb64e8cc6\n      Building wheel for dlx (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for dlx: filename=dlx-1.0.4-py3-none-any.whl size=5719 sha256=67da71313e4dbc4de7d40821ebae9938e2bb87e38fa77d9242a315f1f9f14cb0\n      Stored in directory: /root/.cache/pip/wheels/78/55/c8/dc61e772445a566b7608a476d151e9dcaf4e092b01b0c4bc3c\n      Building wheel for docplex (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for docplex: filename=docplex-2.22.213-py3-none-any.whl size=696881 sha256=f9c11b932c15395edb8b66d2351d66a236b426bdb6a92100470985da782abeb4\n      Stored in directory: /root/.cache/pip/wheels/90/69/6b/1375c68a5b7ff94c40263b151c86f58bd72200bf0c465b5ba3\n      Building wheel for python-constraint (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for python-constraint: filename=python_constraint-1.4.0-py2.py3-none-any.whl size=24081 sha256=b24f4fa51b0e95be6df0a4b04468887c316e727be808b40c8602cf56edf6fe80\n      Stored in directory: /root/.cache/pip/wheels/07/27/db/1222c80eb1e431f3d2199c12569cb1cac60f562a451fe30479\n    Successfully built qiskit dlx docplex python-constraint\n    Installing collected packages: tweedledum, symengine, retworkx, python-constraint, ply, fastjsonschema, qiskit-terra, ntlm-auth, lxml, inflection, cryptography, yfinance, websocket-client, requests-ntlm, quandl, qiskit-ignis, docplex, dlx, qiskit-ibmq-provider, qiskit-aqua, qiskit-aer, qiskit\n      Attempting uninstall: lxml\n        Found existing installation: lxml 4.2.6\n        Uninstalling lxml-4.2.6:\n          Successfully uninstalled lxml-4.2.6\n    Successfully installed cryptography-36.0.0 dlx-1.0.4 docplex-2.22.213 fastjsonschema-2.15.1 inflection-0.5.1 lxml-4.6.4 ntlm-auth-1.5.0 ply-3.11 python-constraint-1.4.0 qiskit-0.32.1 qiskit-aer-0.9.1 qiskit-aqua-0.9.5 qiskit-ibmq-provider-0.18.1 qiskit-ignis-0.6.0 qiskit-terra-0.18.3 quandl-3.7.0 requests-ntlm-1.1.0 retworkx-0.10.2 symengine-0.8.1 tweedledum-1.1.1 websocket-client-1.2.1 yfinance-0.1.67\n\n\n\n```python\n#from IPython.core.debugger import set_trace\nimport numpy as np\n\n# Importing standard Qiskit libraries\nfrom qiskit import QuantumCircuit, transpile, Aer, IBMQ\nfrom qiskit.tools.jupyter import *\nfrom qiskit.visualization import *\n#from ibm_quantum_widgets import *\nfrom qiskit.providers.aer import QasmSimulator\n\n# Loading your IBM Quantum account(s)\n#provider = IBMQ.load_account()\n```\n\n\n```python\n#Custom library\nfrom __future__ import print_function\n\nimport os\nimport sys\n#sys.path.append(\"../Qiskit_Dynamic_Modelling\")\n#sys.path.append(\"./modelQ\")\n#sys.path.append(\"./dynamicsQ\")\nsys.path.append(\"./sample_data\")\n\nfrom visualize import *\nfrom ode_solver import *\n#from network import *\nfrom dataloader import *\nfrom lagrangian import *\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport torch\nimport torch.utils.data\nfrom torch.autograd import Function\nfrom torchvision import datasets, transforms\nimport torch.optim as optim\nimport torch.nn as nn\nimport torch.nn.functional as F\n#from torchsummary import summary\n\nfrom itertools import combinations\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport qiskit\nfrom qiskit.circuit.random import random_circuit\nfrom qiskit import transpile, assemble\n```\n\n\n```python\nprint(\"--- Loading training and test data... ---\")\ntrain_data = np.load('/content/sample_data/train_dataset.npz')\ntrain_inputs = train_data[\"input\"]\ntrain_labels = train_data[\"labels\"]\n\nX_train = train_inputs[:100]\ny_train = train_labels[:100]\n\n#train_dataset = DynamicsDataset(train_inputs, train_labels)\ntrain_dataset = DynamicsDataset(X_train, y_train)\n\ntrain_dataloader = torch.utils.data.DataLoader(train_dataset,\n                                                 batch_size=1,\n                                                 shuffle=True,\n                                                 collate_fn=DynamicsDataset.collate_fn,\n                                                 pin_memory=True,\n                                                 num_workers=1)\ntest_data = np.load('/content/sample_data/val_dataset.npz')\ntest_inputs = train_data[\"input\"]\ntest_labels = train_data[\"labels\"]\nX_test = test_inputs[:100]\ny_test = test_labels[:100]\n\ntest_dataset = DynamicsDataset(X_test, y_test)\n\ntest_dataloader = torch.utils.data.DataLoader(test_dataset,\n                                                 batch_size=1,\n                                                 shuffle=False,\n                                                 collate_fn=DynamicsDataset.collate_fn,\n                                                 pin_memory=True,\n                                                 num_workers=1)\nprint(\"--- Loading training and test data completed ---\")\n```\n\n    --- Loading training and test data... ---\n    --- Loading training and test data completed ---\n\n\n\n```python\nfor (X_train, y_train) in train_dataloader:\n    print('X_train:', X_train.size(), 'type:', X_train.type())\n    print('y_train:', y_train.size(), 'type:', y_train.type())\n    print('X_train:', X_train)\n    print('y_train:', y_train)\n    break\n\nfor (X_test, y_test) in test_dataloader:\n    print('X_test:', X_test.size(), 'type:', X_test.type())\n    print('y_test:', y_test.size(), 'type:', y_test.type())\n    print('X_test:', X_test)\n    print('y_test:', y_test)\n    break\n```\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    X_train: torch.Size([1, 4]) type: torch.DoubleTensor\n    y_train: torch.Size([1, 4]) type: torch.DoubleTensor\n    X_train: tensor([[ 3.0396,  2.1699,  0.1009, -0.1473]], dtype=torch.float64)\n    y_train: tensor([[ 0.1009, -0.1473,  2.0250, -9.3997]], dtype=torch.float64)\n\n\n    ./sample_data/dataloader.py:35: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)\n      batch_x = torch.as_tensor(batch_x)\n\n\n    X_test: torch.Size([1, 4]) type: torch.DoubleTensor\n    y_test: torch.Size([1, 4]) type: torch.DoubleTensor\n    X_test: tensor([[ 1.9537,  0.2797, -0.0780, -0.2268]], dtype=torch.float64)\n    y_test: tensor([[-0.0780, -0.2268, -9.3138, -3.6618]], dtype=torch.float64)\n\n\n\n```python\nclass QuantumCircuit:\n    \"\"\" \n    This class provides a simple interface for interaction \n    with the quantum circuit \n    \"\"\"\n    \n    def __init__(self, n_qubits, backend, shots):\n        # --- Circuit definition ---\n        self._circuit = qiskit.QuantumCircuit(n_qubits)\n        \n        all_qubits = [i for i in range(n_qubits)]\n        self.theta = qiskit.circuit.Parameter('theta')\n        \n        self._circuit.h(all_qubits)\n        self._circuit.barrier()\n        self._circuit.ry(self.theta, all_qubits)\n        \n        self._circuit.measure_all()\n        # ---------------------------\n\n        self.backend = backend\n        self.shots = shots\n    \n    def run(self, thetas):\n        #set_trace()\n        #print('cRun:',thetas)\n        List = [thetas]\n        t_qc = transpile(self._circuit,\n                         self.backend)\n        qobj = assemble(t_qc,\n                        shots=self.shots,\n                        parameter_binds = [{self.theta: theta} for theta in List])\n        #set_trace()\n        job = self.backend.run(qobj)\n        result = job.result().get_counts()\n        \n        counts = np.array(list(result.values()))\n        states = np.array(list(result.keys())).astype(float)\n        \n        # Compute probabilities for each state\n        probabilities = counts / self.shots\n        # Get state expectation\n        expectation = np.sum(states * probabilities)\n        \n        return np.array([expectation])\n```\n\n\n```python\nsimulator = qiskit.Aer.get_backend('aer_simulator')\n\ncircuit = QuantumCircuit(1, simulator, 100)\n#data = [2.1757166385650635]\nprint('Expected value for rotation pi {}'.format(circuit.run(2.1757166385650635)))\n#print('Expected value for rotation pi {}'.format(circuit.run([1.4173])))\ncircuit._circuit.draw()\n```\n\n    /usr/local/lib/python3.7/dist-packages/qiskit/utils/deprecation.py:62: DeprecationWarning: Using a qobj for run() is deprecated as of qiskit-aer 0.9.0 and will be removed no sooner than 3 months from that release date. Transpiled circuits should now be passed directly using `backend.run(circuits, **run_options).\n      return func(*args, **kwargs)\n\n\n    Expected value for rotation pi [0.87]\n\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">        \u250c\u2500\u2500\u2500\u2510 \u2591 \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2591 \u250c\u2500\u2510\n   q_0: \u2524 H \u251c\u2500\u2591\u2500\u2524 Ry(theta) \u251c\u2500\u2591\u2500\u2524M\u251c\n        \u2514\u2500\u2500\u2500\u2518 \u2591 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2591 \u2514\u2565\u2518\nmeas: 1/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\n                                 0 </pre>\n\n\n\n\n```python\nclass HybridFunction(Function):\n    \"\"\" Hybrid quantum - classical function definition \"\"\"\n    \n    @staticmethod\n    def forward(ctx, input, quantum_circuit, shift):\n        \"\"\" Forward pass computation \"\"\"\n        ##print('hFor:', input)\n        #print('hFor1:', input[0])\n        #print('hFor2:', input[0].tolist())\n        ctx.shift = shift\n        ctx.quantum_circuit = quantum_circuit\n        #expectation_z = []\n        #for i in range(len(input)):\n        #    expectation_z.append(ctx.quantum_circuit.run(input[i].tolist()))\n        #print('expectation_z',expectation_z)\n        expectation_z = ctx.quantum_circuit.run(input[0].tolist())\n        result = torch.tensor([expectation_z])\n        #result = torch.tensor(expectation_z)\n        ctx.save_for_backward(input, result)\n\n        return result\n        \n    @staticmethod\n    def backward(ctx, grad_output):\n        \"\"\" Backward pass computation \"\"\"\n        input, expectation_z = ctx.saved_tensors\n        input_list = np.array(input.tolist())\n        \n        shift_right = input_list + np.ones(input_list.shape) * ctx.shift\n        shift_left = input_list - np.ones(input_list.shape) * ctx.shift\n        \n        gradients = []\n        for i in range(len(input_list)):\n            expectation_right = ctx.quantum_circuit.run(shift_right[i])\n            expectation_left  = ctx.quantum_circuit.run(shift_left[i])\n            \n            gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left])\n            gradients.append(gradient)\n        gradients = np.array([gradients]).T\n        return torch.tensor([gradients]).float() * grad_output.float(), None, None\n\nclass Hybrid(nn.Module):\n    \"\"\" Hybrid quantum - classical layer definition \"\"\"\n    \n    def __init__(self, backend, shots, shift):\n        super(Hybrid, self).__init__()\n        self.quantum_circuit = QuantumCircuit(1, backend, shots)\n        self.shift = shift\n        \n    def forward(self, input):\n        #print('3',input)\n        return HybridFunction.apply(input, self.quantum_circuit, self.shift)\n```\n\n\n```python\nclass LagrangianNeuralNetwork(torch.nn.Module):\n    def __init__(self, D_in, hidden_list, D_out):\n        \"\"\"\n        Neural Network used to approximate a paramaterized system lagrangian\n        \"\"\"\n        super(LagrangianNeuralNetwork, self).__init__()\n        self.model_layers = torch.nn.ModuleList()\n\n        # input layer\n        self.model_layers.append(torch.nn.Linear(D_in, hidden_list[0]))\n        # self.model_layers.append(torch.nn.BatchNorm1d(hidden_list[0]))\n        self.model_layers.append(torch.nn.Softplus())\n        #self.model_layers.append(Hybrid(qiskit.Aer.get_backend('aer_simulator'), 100, np.pi / 2))\n        # add all hiden layers\n        for i in range(1, len(hidden_list)):\n            self.model_layers.append(torch.nn.Linear(hidden_list[i-1], hidden_list[i]))\n            # self.model_layers.append(torch.nn.BatchNorm1d(hidden_list[i]))\n            self.model_layers.append(torch.nn.Softplus())\n\n        self.hybrid = Hybrid(qiskit.Aer.get_backend('aer_simulator'), 100, np.pi / 2)\n        #self.model_layers.append(Hybrid(qiskit.Aer.get_backend('aer_simulator'), 100, np.pi / 2))\n        # output layer\n        self.model_layers.append(torch.nn.Linear(hidden_list[-1], D_out))\n        self.model_layers.append(torch.nn.Softplus())\n\n    def forward(self, x):\n        \"\"\"\n        applies all of the model layers, and returns the single output value,\n        which in this case is the lagrangian of the system, representing the\n        total energy\n        \"\"\"\n        count = 0\n        #print(\"2 \", x)\n        for layer in self.model_layers:\n            #print(len(self.model_layers))\n            #if(count >= (len(self.model_layers) - 3)):\n                #print(count)\n                #print(x)\n            #    x = self.hybrid(x)\n                #print(x)\n            x = layer(x)\n            #print(count)\n            #count = count + 1\n            #x = self.hybrid(x)\n        #print('c', x)                \n        x = self.hybrid(x)\n        #print('q', x)\n        return x\n```\n\n\n```python\n# determine device\nprint(\"--- Checking for CUDA Device... ---\")\nuse_cuda = torch.cuda.is_available()\ndevice = torch.device(\"cuda:0\" if use_cuda else \"cpu\")\n```\n\n    --- Checking for CUDA Device... ---\n\n\n\n```python\n# organize data\ninput_size = train_inputs.shape[1]\noutput_size = 1  # for all lagrangian systems, output should be just a scalar energy value\n\n# build model\nprint(\"--- Constructing Model... ---\")\nD_in = input_size  # state size\n# hidden_list = [D_in, 256, 256, 256, 256, 256]\nhidden_list = [D_in, 32, 64, 128, 256, 512, 256, 128, 64, 32]\nD_out = output_size\nlnn_model = LagrangianNeuralNetwork(D_in, hidden_list, D_out)\n#summary(lnn_model, (1, 28, 28), device='cpu')\n# set up training parameters\nlearning_rate = 1e-4\nweight_decay = 1e-5\nmomentum = 0.9\nnum_epochs = 20\noptimizer = torch.optim.Adam(lnn_model.parameters(),\n                             lr=learning_rate,\n                             weight_decay=weight_decay)\n\nif os.path.isfile(\"model_weights.pth\"):\n    print(\"Re-loading existing weights!\")\n    checkpoint = torch.load(\"model_weights.pth\")\n    lnn_model.load_state_dict(checkpoint['model_state_dict'])\n    optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n\n# ensure model is in train mode so gradients are properly calculated\nlnn_model.train()\n# load device to either GPU or CPU depending on hardware\nlnn_model.to(device)\n\n# set up loss function\nloss_fcn = torch.nn.MSELoss()\n\n# set up GradScaler to improve run speed\nscaler = torch.cuda.amp.GradScaler()\n```\n\n    --- Constructing Model... ---\n\n\n    /usr/local/lib/python3.7/dist-packages/torch/cuda/amp/grad_scaler.py:115: UserWarning: torch.cuda.amp.GradScaler is enabled, but CUDA is not available.  Disabling.\n      warnings.warn(\"torch.cuda.amp.GradScaler is enabled, but CUDA is not available.  Disabling.\")\n\n\n\n```python\nimport time\nprint(\"--- Beginning Training! ---\")\nloss_listQCQ = []\nlnn_model.train()\nstartTimeQCQ = time.time()\nprint('Training Start Time (in sec) : ',(startTimeQCQ))\nprint('Training Start Time : ',(time.asctime( time.localtime(time.time()) )))\nfor epoch in range(num_epochs):\n    total_lossQCQ = []\n    for batch_idx, (data, target) in enumerate(train_dataloader):\n        data, target = data.to(device), target.to(device)\n        optimizer.zero_grad()\n        for p in lnn_model.parameters(): p.grad = None\n        # Forward pass\n        #output = model(data)\n        # Calculating loss\n        #loss = loss_func(output, target)\n        # output from model is the energy calculated from the parameterized lagrangian\n        #print('1',data)\n        #print('1',data.detach().numpy())\n        #for val in enumerate(data.detach().numpy()):\n        #    print(val)\n        Listk = []\n        for val in data.detach().numpy():\n            #print(val)            \n            for i in range(len(val)):\n                #print(val[i])\n                qcr = circuit.run(val[i])\n                #print(qcr[0])\n                Listk.append(qcr[0])\n                #print(Listk)\n                \n        ListTarget = []\n        #print(target)\n        for valT in target.detach().numpy():\n            #print(val)            \n            for j in range(len(valT)):\n                #print(val[i])\n                qcrT = circuit.run(valT[j])\n                #print(qcr[0])\n                ListTarget.append(qcrT[0])\n                #print(ListTarget)\n        targetData = torch.tensor(ListTarget)\n        data = torch.squeeze(torch.tensor(Listk))\n        #data = torch.squeeze(data)\n        with torch.cuda.amp.autocast():\n            target_pred = solve_euler_lagrange(lnn_model.forward, data.float())\n            #print('1',target_pred)\n            #print('2',target.float())\n            loss = loss_fcn(target_pred.unsqueeze(0), targetData.float())\n        # Backward pass\n        scaler.scale(loss).backward()\n        # Optimize the weights\n        scaler.step(optimizer)\n        # update the scale for next iteration\n        scaler.update()\n\n        #print(\"Iter Num: \", batch_idx)\n        '''\n        if (batch_idx == 10):\n            #print(\"Iter Num: \", batch_idx)\n            break\n        '''\n        #print(\"Iter Num: \", len(train_dataloader))\n        #print(\"Iter Num: \", batch_idx)\n        total_lossQCQ.append(loss.item())\n    loss_listQCQ.append(sum(total_lossQCQ)/len(total_lossQCQ))\n    print('Training [{:.0f}%]\\tLoss: {:.4f}'.format(\n        100. * (epoch + 1) / num_epochs, loss_listQCQ[-1]))\nprint('Training End Time (in sec) : ',(time.time()))\nprint('Total training time (in sec)', ((time.time() - startTimeQCQ)))\nprint('Training End Time',(time.asctime( time.localtime(time.time()) )))\nprint('end')\n```\n\n    --- Beginning Training! ---\n    Training Start Time (in sec) :  1638404631.9463086\n    Training Start Time :  Thu Dec  2 00:23:51 2021\n\n\n    /usr/local/lib/python3.7/dist-packages/qiskit/utils/deprecation.py:62: DeprecationWarning: Using a qobj for run() is deprecated as of qiskit-aer 0.9.0 and will be removed no sooner than 3 months from that release date. Transpiled circuits should now be passed directly using `backend.run(circuits, **run_options).\n      return func(*args, **kwargs)\n    /usr/local/lib/python3.7/dist-packages/torch/autocast_mode.py:141: UserWarning: User provided device_type of 'cuda', but CUDA is not available. Disabling\n      warnings.warn('User provided device_type of \\'cuda\\', but CUDA is not available. Disabling')\n    /usr/local/lib/python3.7/dist-packages/torch/nn/modules/loss.py:520: UserWarning: Using a target size (torch.Size([4])) that is different to the input size (torch.Size([1, 4])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.\n      return F.mse_loss(input, target, reduction=self.reduction)\n\n\n    Training [5%]\tLoss: 0.0853\n    Training [10%]\tLoss: 0.0896\n    Training [15%]\tLoss: 0.0905\n    Training [20%]\tLoss: 0.0855\n    Training [25%]\tLoss: 0.0885\n    Training [30%]\tLoss: 0.0818\n    Training [35%]\tLoss: 0.0800\n    Training [40%]\tLoss: 0.0806\n    Training [45%]\tLoss: 0.0991\n    Training [50%]\tLoss: 0.0817\n    Training [55%]\tLoss: 0.0815\n    Training [60%]\tLoss: 0.0854\n    Training [65%]\tLoss: 0.0839\n    Training [70%]\tLoss: 0.0774\n    Training [75%]\tLoss: 0.0862\n    Training [80%]\tLoss: 0.0804\n    Training [85%]\tLoss: 0.0781\n    Training [90%]\tLoss: 0.0768\n    Training [95%]\tLoss: 0.0786\n    Training [100%]\tLoss: 0.0744\n    Training End Time (in sec) :  1638405121.6958873\n    Total training time (in sec) 489.7496647834778\n    Training End Time Thu Dec  2 00:32:01 2021\n    end\n\n\n\n```python\nplt.plot(loss_listQCQ)\nplt.title('Hybrid LQNN Q-C-Q Training')\nplt.xlabel('Training Iterations')\nplt.ylabel('Loss')\n#plt.show()\n```\n\n\n```python\nprint(\"--- Beginning Test! ---\")\nloss_list = []\nlnn_model.eval()\ntotal_loss = []\ncorrect = 0\nfor batch_idx, (data, target) in enumerate(test_dataloader):\n    data, target = data.to(device), target.to(device)\n    data = torch.squeeze(data)\n    with torch.cuda.amp.autocast():\n        target_pred = solve_euler_lagrange(lnn_model.forward, data.float())\n        #print(target_pred)\n        #print(target)\n        correct += target_pred.eq(target.view_as(target_pred)).sum().item()\n        loss = loss_fcn(target_pred.unsqueeze(0), target.float())        \n    total_loss.append(loss.item())\nbatch_size = 1\nprint('Performance on test data:[{:.0f}%]\\tLoss: {:.4f}\\tAccuracy: {:.1f}%'.format(\n    100. * (epoch + 1) / num_epochs,\n    sum(total_loss) / len(total_loss),\n    correct / len(test_dataloader) * 100 / batch_size)\n    )\n\nprint('end')\n```\n\n    --- Beginning Test! ---\n\n\n    /usr/local/lib/python3.7/dist-packages/torch/autocast_mode.py:141: UserWarning: User provided device_type of 'cuda', but CUDA is not available. Disabling\n      warnings.warn('User provided device_type of \\'cuda\\', but CUDA is not available. Disabling')\n    /usr/local/lib/python3.7/dist-packages/qiskit/utils/deprecation.py:62: DeprecationWarning: Using a qobj for run() is deprecated as of qiskit-aer 0.9.0 and will be removed no sooner than 3 months from that release date. Transpiled circuits should now be passed directly using `backend.run(circuits, **run_options).\n      return func(*args, **kwargs)\n\n\n    Performance on test data:[100%]\tLoss: 21.2050\tAccuracy: 0.0%\n    end\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "580237c7e9852c45a73d9a90f54f917153b51332", "size": 67915, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Hybrid_QLDNN_QCQ_100.ipynb", "max_stars_repo_name": "18819F-Project/ModellingDynamicalSystem", "max_stars_repo_head_hexsha": "2610385e38c4cff7c9cbe25e1c6801a3de9eaf69", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Hybrid_QLDNN_QCQ_100.ipynb", "max_issues_repo_name": "18819F-Project/ModellingDynamicalSystem", "max_issues_repo_head_hexsha": "2610385e38c4cff7c9cbe25e1c6801a3de9eaf69", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Hybrid_QLDNN_QCQ_100.ipynb", "max_forks_repo_name": "18819F-Project/ModellingDynamicalSystem", "max_forks_repo_head_hexsha": "2610385e38c4cff7c9cbe25e1c6801a3de9eaf69", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 72.25, "max_line_length": 23058, "alphanum_fraction": 0.6654494589, "converted": true, "num_tokens": 8614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.08756383297503753, "lm_q1q2_score": 0.028994113575610922}}
{"text": "```python\nfrom IPython.core.display import HTML\ndef css_styling():\n    styles = open(\"./styles/custom.css\", \"r\").read()\n    return HTML(styles)\ncss_styling()\n```\n\n\n\n\n<style>\n\nbody {\n counter-reset: h2counter;\n}\nh1 {\n counter-reset: h2counter;\n}\nh2:before {\n content: counter(h2counter) \".\\0000a0\\0000a0\";\n counter-increment: h2counter;\n counter-reset: h3counter;\n}\n\n\n</style>\n\n\n\n\n### BEFORE YOU DO ANYTHING...\nIn the terminal:\n1. Navigate to __inside__ your ILAS_Python repository.\n2. __COMMIT__ any un-commited work on your personal computer.\n3. __PULL__ any changes *you* have made using another computer.\n4. __PULL__ textbook updates (including homework answers).\n\n1. __Open Jupyter notebook:__   Start >> Programs (\u3059\u3079\u3066\u306e\u30d7\u30ed\u30b0\u30e9\u30e0) >> Programming >> Anaconda3 >> JupyterNotebook\n1. __Navigate to the ILAS_Python folder__. \n1. __Open today's seminar__  by clicking on 6_Library_Functions.\n\n# Library Functions\n# Lesson Goal\n\nSource and incorporate appropriate functions from external libraries to optimise your code.  \n\n\n\n\n\n# Objectives\n\n- Review standard library functions\n- Importing and using modules\n- Understanding module documentation\n- Using imported functions to optimise the code you have written so far.\n- Determining optimal solutions by timing your code.\n\nWhy we are studying this:\n    \n- To optimise your code (faster, more concise) by incorporating library functions.\n- To learn to independently source functions using the internet. \n- To learn how and when to replace user defined code with appropriate library functions. \n\n__Lesson structure:__ Today we will learn about functions that we import from external files or \u201clibraries\u201d. \n - Libraries\n - The standard library\n - Reading function documentation\n - Namespaces\n - Importing a function\n - Using package functions\n - Using package functions to optimise your code\n - Importing algorithms as functions \n - Review excercises \n - Update GitHub repository. \n - Summary\n\n## Libraries\n\nPython, like other modern programming languages, has an extensive *library* of built-in functions. \n\nThese functions are designed, tested and optimised by the developers of the Python langauge.  \n\nWe can use these functions to make our code shorter, faster and more reliable.\n\n\nYou are already familiar with some *built in* Python functions:\n\n   - `print()` takes the __input__ in the parentheses and __outputs__ a visible representation.\n   - `len()` takes a data structure as __input__ in the parentheses and __outputs__ the number of items in the data structure (in one direction).\n   - `sorted()` takes a data structure as __input__ in the parentheses and __outputs__ the data structure sorted by a rule determined by the data type.\n   - `abs()` takes a numeric variable as  __input__ in the parentheses and __outputs__ the mathematical absolute value of the input.\n\nThese functions belong to Python's __standard library__...\n\n## The Standard Library\n\nPython has a large standard library. \n\nIt is simply a collection of Python files called 'modules'.\n\nThese files are installed on the computer you are using.\n\nEach module contains code very much like the code that you have been writing, defining various variables, functions and methods. \n\nThere are multiple modules to keep the code sorted and well organised. \n\n__Function:__\n<br>A piece of code that is called by name. \n<br>It can be *passed* data to operate on (i.e., the parameters) and can optionally *return* data (the return value). \n\n__Example__\n```Python\nsorted([5, 2, 3, 1, 4])\n```\n\n__Method:__\n<br>A method is a piece of code that is called by name.\n<br>It is already associated with an object type (e.g. a list) so it is expressed after a . dot at the end of the object name. \n<br>It mostly behaves the same as a function  except:  \n- It is automatically passed for the object which it is attached to.\n- (It can only operate on objects that contain the method. It can operate on data insde of that class.)  \n\n__Example__\n```Python\na = [1, 5, 2, 7, 5]\na.sort()\n```\n\nThe standard libary contains many useful functions. \n\nThey are listed on the Python website:\nhttps://docs.python.org/3/library/functions.html\n\nIf you want to do something, for example a mathematical operation, it worth trying an internet search for a built-in function already exists.\n\n\n\nFor example, a quick google search for \"python function to sum all the numbers in a list\"...\n\nhttps://www.google.co.jp/search?q=python+function+to+sum+all+the+numbers+in+a+list&rlz=1C5CHFA_enJP751JP751&oq=python+function+to+sum+&aqs=chrome.0.0j69i57j0l4.7962j0j7&sourceid=chrome&ie=UTF-8\n\n...returns the function `sum()`.\n\n\n\n`sum()` finds the sum of the values in a data strcuture. \n\n\n```python\nprint(sum([1,2,3,4,5]))\n\nprint(sum((1,2,3,4,5)))\n\na = [1,2,3,4,5]\nprint(sum(a))\n```\n\n    15\n    15\n    15\n\n\nThe function `max()` finds the maximum value in data structure.\n\n\n```python\nprint(max([4,61,12,9,2]))\n\nprint(max((3,6,9,12,15)))\n\na = [1,2,3,4,5]\nprint(max(a))\n```\n\n    61\n    15\n    5\n\n\n## Packages\n\nThe standard library tools are available in any Python environment.\n\nMore specialised libraries are available. \n\nWe call these packages. \n\n\n\nTwo widely used packages for mathematics, science and engineeirng are `NumPy` and `SciPy`.\n\nThese are already installed as part of Anaconda.\n\nA package is a collection of Python modules: \n- a __module__ is a single Python file\n- a __package__ is a directory of Python modules.<br>(It contains an __init__.py file, to distinguish it from folders that are not libraries).\n\n### Importing a Package\n\nTo use an installed package, we  simply `import` it. \n\nPackages contain functions and constants for more specific tasks e.g. solving trigonometric functions. \n\nWe simply install the modules on the computer where we want to use them. \n\n\n```python\nimport numpy \n\nx = 1\n\ny = numpy.cos(x)\n\nprint(y)\n\nprint(numpy.pi)\n```\n\n    0.540302305868\n    3.141592653589793\n\n\nThe `import` statement must appear before the use of the package in the code.  \n\n        import numpy \n\nAfter this, any function in `numpy` can be called as:\n\n        `numpy.function()`\n        \nand, any constant in `numpy` can be called as:\n\n        `numpy.constant`.\n\nThere are a many mathematical functions available. <br>\nhttps://docs.scipy.org/doc/numpy-1.13.0/reference/routines.math.html\n\nWe can change the name of a package e.g. to keep our code short and neat.\n\nUsing the __`as`__ keyword:\n\n\n```python\nimport numpy as np\nprint(np.pi)\n```\n\n    3.141592653589793\n\n\nWe only need to import a package once, at the start of the program or notebook.\n\n## Reading function documentation\n\nTo check how to use a function e.g.:\n- what arguments to include in the () parentheses\n- allowable data types to use as arguments\n- the order in which arguments should be given \n \nyou can:\n\n- search for the documentation online e.g. https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.math.html\n- press \"Shift\" + \"Tab\" when the curser is between the () parentheses of a function call (Jupyter notebook only).\n\n\n\nFor example, the documentation for the function numpy.cos: <br> https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.math.html includes:\n\n##### What the function does.\n\"Cosine element-wise.\"\n\n##### All possible function arguments (parameters)\n\n \n\n>numpy.cos(<font color='blue'>x</font>, /, <font color='red'>out=None</font>, *, <font color='green'>where=True, casting='same_kind', order='K', dtype=None, subok=True</font> [, <font color='purple'>signature, extobj</font> ]) \n\nIn the () parentheses following the function name are:\n- <font color='blue'>*positional* arguments (required)</font>\n- <font color='red'>*keyword* arguments (with a default value, optionally set). Listed after the `/` slash.</font>\n- <font color='green'>arguments that must be explicitly named. Listed after the `*` star.</font> \n  <br><font color='purple'>(including arguments without a default value.  Listed in `[]` brackets.)</font>\n\n##### Function argument definitions and acceptable forms.  \n\n \n\nx : array_like *(it can be an `int`, `float`, `list` or `tuple`)*\n\nout : ndarray, None, or tuple of ndarray and None, optional\n\nwhere : array_like, optional \n\n##### What the function returns\n__y__ : ndarray<br>\n&nbsp; &nbsp; &nbsp; &nbsp; The corresponding cosine values.\n\n\n```python\nimport numpy as np\n\nx = 0.5\nz = np.ones((1,1))\n\n# cos with posistional argument\nprint(np.cos(x))\n\n# cos with positional and default arguments\nprint(np.cos(x), z)\n\n# cos with positional argument, default argument and keyword argument\nprint(np.cos(x, z, where=True))\n```\n\n    0.87758256189\n    0.87758256189 [[ 1.]]\n    [[ 0.87758256]]\n\n\nLet's look at the function numpy.degrees:\nhttps://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.degrees.html\n\nWhat does the function do?\n\nWhat __arguments__ does it take (and are there any default arguments)? \n\nHow would we __write__ the function when __calling__ it (accept defaults)?\n\nWhat __data type__ should our input be? \n\n## `args*` and `kwargs**`\nYou may have noticed the word `**kwargs` listed in the function documentation. \n<br>`*args` and `**kwargs` can be used when we don't know the exact number of arguments we want to pass to the function.\n\n`*args` lets us pass any number of *arguments*.\n\n`**kwargs` lets us pass any number of *keyword arguments*. \n\n(Actually, `*` and `**` are the only required code. The names `args` and `kwargs` are widely accepted convention).\n\n### Packing: `*args` and `**kwargs in function definitions`\nIn a function definition, `*args` must appear before `**kwargs`.\n\n### Packing `*args`\nSometimes we want the number of arguments we can pass to a function to be flexible.\n\nConsider the example below which we studied in the last seminar \n\nThis simple function to express x, (y and z) inputs as a list. <br>(e.g. coordinates to define a position vector). \n\n\n\n\n```python\ndef vector_3D(x, y=0.0, z=0.0):\n    \"\"\"\n    Expresses 1D, 2D or 3D vector in 3D coordinates, as a list.\n    \"\"\"\n    return [x, y, z]\n\nvector_3D(1, 2, 3)\n```\n\n\n\n\n    [1, 2, 3]\n\n\n\nHowever, it is still limited to a maximum of *three* inputs.\n\nSometimes it can be convenient to allow any number of inputs:\n - enter __any number__ or arguments. \n - have the function store the arguments as a single tuple (behaves like any other tuple).\n \nThis is called *packing*.\n\nBy allowing the function to take any number of `*args`, we make it more __flexible__.\n\n\n```python\ndef var_to_list(*args):\n    \"\"\"\n    Expresses any numbe of inputs as a list. \n    \"\"\"\n    var_list = []\n    \n    for a in args:\n        var_list.append(a)\n        \n    return var_list\n\nvar_to_list(1, 2, 3, 4)\n```\n\n\n\n\n    [1, 2, 3, 4]\n\n\n\nArguments must be listed before keyword arguments as usual.\n\n\n```python\ndef var_to_list(*args, extra=2):\n    \"\"\"\n    Expresses a vector of any length as a list. \n    \"\"\"\n    var_list = []\n    \n    for a in args:\n        var_list.append(a)\n        \n    return var_list\n```\n\n\n```python\nprint(var_to_list(1, 2, 3, 4, 5))\n\nprint(var_to_list(1, 2, 3, 4, extra=5))\n\n#print(var_to_list(extra=5, 1, 2, 3, 4))\n```\n\n### Packing `**kwargs`\n`**` allows multiple keyword-variable pairs to be entered which it stores in the form of a dictionary.\n<br>This is useful as we can access the keyword and the variables seperately.\n\n\n```python\ndef table_things(**kwargs):\n    \"Prints key-value pairs seperated by a colon\"\n    for name, value in kwargs.items():\n        print(f\"{name} : {value}\")\n\ntable_things(thing1 = 'robot', thing2 = 'melon')   \n```\n\n    thing1 : robot\n    thing2 : melon\n\n\nPacking can make your code more efficient by skipping unecessary sections.\n\n\n```python\nx = 1\ny = 1\n\ndef position(**kwargs):\n    \"Prints x, y coordinates of current position\"\n    \n    if \"new_pos\" in kwargs:\n        global x, y \n        x = kwargs[\"new_pos\"][1]\n        y = kwargs[\"new_pos\"][0]\n        \n    print(f\"({x},{y})\")    \n\npos_update = position()\n\npos_update = position(new_pos=[3,4])\n```\n\n    (1,1)\n    (4,3)\n\n\nSo in function documentation, for example, __`**kwargs`__refers to a series of keyword arguments of which you may enter as few or as many as you wish to set. \n\n \n\n \n\n\n\n### Unpacking: `*args` and `**kwargs when calling functions`\n\nSometimes it can be convenient to do the opposite:\n - enter a __single data structure__; all the functin arguments packed up somewhere earlier in the program.\n - have the function unpack the list for us into __multiple containers__; the individual function arguments. \n\n<br>This reverse process to packing is known as *unpacking*.\n\nBy packing the arguments as a single input, calling the function can become more __efficient__. \n\n### Unpacking `*args`\nA single data structure e.g. a list, unpacks as the function arguments in the order they appear.\n<br>Therefore the data structure should be the *same* length as the number of arguments it is being used to input.\n<br>In other words, unlike packing, the number of arguments is now fixed.\n\n\n```python\ndef test_args_func(first, second, third, fourth):\n    \"Prints each argument of the function\"\n    print(first, second, third, fourth)\n    \nto_unpack = [4, 5, 6]\n\ntest_args_func(1, *to_unpack)\ntest_args_func(1, 2, *to_unpack[:2])\n```\n\n    1 4 5 6\n    1 2 4 5\n\n\n### Unpacking `**kwargs`\nValues in the dictionary are adddressed using the function arguments as keywords.\n<br>This means that the arguments can appear in the dictinary in any order.\n<br>The dictionary should be the *same* length as the number of arguments it is being used to input *and* the dictionary entried should have the same names.\n\n\n```python\ndef test_args_func(first, second, third, fourth):\n    \"Prints each argument of the function\"\n    print(first, second, third, fourth)\n    \ndictionary = {\"second\": 12, \"fourth\": 14, \"third\": 13}\n\ntest_args_func(1, **dictionary)\n```\n\n    1 12 13 14\n\n\n## Namespaces\n<br>By prefixing `cos` with `np`, we are using a *namespace* (which in this case is `np`).\n\n\n\nThe namespace shows we want to use the `cos` function from the Numpy package.\n\nIf `cos` appears in more than one package we import, then there will be more than one `cos` function available.\n\nWe must make it clear which `cos` we want to use. \n\n\n\n\nOften, functions with the same name, from different packages, will use a different algorithms for performing the same or similar operation. \n\nThey may vary in speed and accuracy. \n\nIn some applications we might need an accurate method for computing the square root, for example, and the speed of the program may not be important. For other applications we might need speed with an allowable compromise on accuracy.\n\n\nBelow are two functions, both named `sqrt`. \n\nBoth functions compute the square root of the input.\n\n - `math.sqrt`, from the package, `math`, gives an error if the input is a negative number. It does not support complex numbers.\n - `cmath.sqrt`, from the package, `cmath`, supports complex numbers.\n\n\n\n```python\nimport math\nimport cmath\nprint(math.sqrt(4))\n#print(math.sqrt-5)\n#print(cmath.sqrt(-5))\n```\n\n    2.0\n\n\nTwo developers collaborating on the same program might choose the same name for two functions that perform similar tasks. \n\nIf these functions are in different modules, there will be no name clash since the module name provides a 'namespace'. \n\n## Importing a Function\nSingle functions can be imported without importing the entire package e.g. use:\n\n        from numpy import cos\n\ninstead of:\n\n        import numpy \n\nAfter this you call the function without the numpy prefix: \n\n\n```python\nfrom numpy import cos\n\ncos(x)\n```\n\n\n\n\n    -0.65364362086361194\n\n\n\nBe careful when doing this as there can be only one definition of each function.\nIn the case that a function name is already defined, it will be overwritten by a more recent definition. \n\n\n```python\nfrom cmath import sqrt\nprint(sqrt(-1))\nfrom math import sqrt\n#print(sqrt(-1))\n```\n\n    1j\n\n\nA potential solution to this is to rename individual functions or constants when we import them:\n\n\n```python\nfrom numpy import cos as cosine\n\ncosine(x)\n```\n\n\n\n\n    -0.65364362086361194\n\n\n\n\n```python\nfrom numpy import pi as pi\npi\n```\n\n\n\n\n    3.141592653589793\n\n\n\nThis can be useful when importing functions from different modules:\n\n\n```python\nfrom math import sqrt as square_root\nfrom cmath import sqrt as complex_square_root\n\nprint(square_root(4))\nprint(complex_square_root(-1))\n```\n\n    2.0\n    1j\n\n\nFunction names should be chosen wisely.\n - relevant\n - concise\n\n<a id='UsingPackageFunctions'></a>\n## Using Package Functions. \n\nLet's learn to use `numpy` functions in our programs. \n\n\n\n\n\nTo check how to use a function e.g.:\n - what arguments to include in the () parentheses\n - allowable data types to use as arguments\n - the order in which arguments should be given \n \nlook at the Numpy documentation.\n\nA google search for 'numpy functions' returns:\n\nhttps://docs.scipy.org/doc/numpy-1.13.0/reference/routines.math.html\n\n(this list is not exhaustive). \n\n\n```python\n# Some Numpy functions with their definitions as given in the documentation\n\nx = 1\ny = 2\nz = 3\n\n# Trigonometric sine, element-wise.\nprint(np.sin(x))\n\n# Compute tangent element-wise.\nprint(np.tan(x))\n\n# Trigonometric inverse tangent\nprint(np.arctan(x))\n\n# Convert angles from radians to degrees\ndegrees = np.degrees(x)\nprint(degrees)\n\n# Convert angles from degrees to radians\nradians = np.radians(degrees)\nprint(radians)   \n```\n\n    0.841470984808\n    1.55740772465\n    0.785398163397\n    57.2957795131\n    1.0\n\n\n__Try it yourself:__\n<br> Find a function in the Python Numpy documentation that matches the function definition and use it to solve the following problem:   \n\nGiven the \u201clegs\u201d of a right angle triangle, return its hypotenuse.<br> If  the lengths of the two shorter sides of a right angle triangle are 6 units  and 3 units, what is the length of the hypotenuse?\n\n\n```python\n# The \u201clegs\u201d of a right angle triangle are 6 units and 3 units, \n# Return its hypotenuse in units.\n```\n\nNumpy functions often appear within user defined functions e.g.:\n\n$f(x)= \\cos(x) \\qquad x <0$\n\n$f(x) = \\exp(-x) \\qquad x \\ge 0$\n\n\n```python\ndef f(x):\n    if x < 0:\n        f = np.cos(x)\n    else:\n        f = np.exp(-x)\n    return f\n\nprint(f(np.pi))\nprint(f(np.pi/6))\n```\n\n    0.0432139182638\n    0.592384847188\n\n\nPackage functions can be passed to other functions as arguments.\n\nRecall __Seminar 4, What can be passed as a function argument?__\n\n\n\n<a id='is_positive'></a>\nExample: the function `is_positive` checks if the value of a function $f$, evaluated at $x$, is positive.\n<br> The arguments are:\n - the function $f$\n - the value of $x$,in $f(x)$\n\n\n```python\ndef is_positive(f, x):\n\n    return f(x) > 0\n    \ndef f0(x):\n    \"\"\"\n    Computes x^2 - 1\n    \"\"\"\n    return x*x - 1\n    \n# Value of x to test\nx = 0.5\n\n# Test sign of function f0 (user defined)\nprint(is_positive(f0, x))\n\n# Test sign of function np.cos (numpy function)\nprint(is_positive(np.cos, x))\n```\n\n    False\n    True\n\n\n__Try it yourself:__\n<br> Search online for the numpy function for each of the following mathematical functions: \n- $f = \\arcsin(x)$\n- $f = \\sqrt x$\n\n<br> In the cell below: use the function `is_positive` to test the sign of output of the functions.  \n\n\n```python\n# Test sign of numpy function for arcsin(x)\n\n# Test sign of numpy function for square root of x\n\n```\n\n##### Try it yourself\nIn the cell below, copy and paste the `bisection` function you wrote for __Seminar 4: Review Excercise: Using Functions as Function Arguments.__\n\nDemonstrate that your `bisection` function works correctly by finding the zero of the Numpy $\\cos(x)$ function that lies in the interval $x_1=0$ to $x_2=3$. \n\n\n```python\n# Bisection\n```\n\n## Using Package Functions to Optimise your Code\n\nWe will take previous excercises that you have completed  and look at how we can optimise them using Numpy functions.\n\n<br> If you *have not* completed the excercises mentioned in previous seminars  you can:\n1. complete the exercise from the previous seminar (without Numpy functions) then optimise using Numpy.\n1. complete the excercise using Numpy functions (without completing the preceding excercise).  \n\nConsider the function min_max_mean from __Seminar 5: Functions: Return Arguments__. \n<br>This is obviously a very limited way to compute the minimum, maximum and mean. \n<br>The algorithm relies on there being only 3 arguments.\n\n\n```python\n# Using Pure Python only\ndef max_min_mean(x0, x1, x2):\n    \"Return maximum, minimum and mean values\"\n    \n    x_min = x0\n    if x1 < x_min:\n        x_min = x1\n    if x2 < x_min:\n        x_min = x2\n\n    x_max = x0\n    if x1 > x_max:\n        x_max = x1\n    if x2 > x_max:\n        x_max = x2\n\n    x_mean = (x0 + x1 + x2)/3    \n        \n    return x_min, x_max, x_mean\n\n\nxmin, xmax, xmean = max_min_mean(0.5, 0.1, -20)\nprint(xmin, xmax, xmean)\n```\n\n    -20 0.5 -6.466666666666666\n\n\nWe are going to re-write the function `compute_max_min_mean` using Numpy.\n\n\n```python\ndef np_max_min_mean(x0, x1, x2):\n    \"Return maximum, minimum and mean values\"\n    \n    x_min = np.min([x0, x1, x2])\n    x_max = np.max([x0, x1, x2])\n    x_mean = np.mean([x0, x1, x2])\n            \n    return x_min, x_max, x_mean\n\n\nxmin, xmax, xmean = np_max_min_mean(0.5, 0.1, -20)\nprint(xmin, xmax, xmean)\n```\n\n    -20.0 0.5 -6.46666666667\n\n\n### Data Structures as Function Arguments. \nNotice that the Numpy functions `amin`, `amax` and `amean` take lists as argumets.\n\nTherefore a single list (of any length) is a more convenient way to input the function arguments. \n\n\n```python\nimport numpy as np\ndef np_max_min_mean(x_list):\n    \"Return maximum, minimum and mean values\"\n    \n    x_min = np.amin(x_list)\n    x_max = np.amax(x_list)\n    x_mean = np.mean(x_list)\n            \n    return x_min, x_max, x_mean\n\nnumbers = [0.5, 0.1, -20]\nprint(np_max_min_mean(numbers))\n\nnumbers = [-2, -1, 3, 5, 12]\nprint(np_max_min_mean(numbers))\n```\n\n    (-20.0, 0.5, -6.4666666666666659)\n    (-2, 12, 3.3999999999999999)\n\n\n<a id='ElementwiseFunctions'></a>\n### Elementwise Functions\nNumpy functions often operate *elementwise*. \n<br> This means if the argument is a list, they will perform the same function on each element of the list.\n\nFor example, to find the square root of each number in a list, we can use:\n\n\n```python\na = [9, 25, 36]\nprint(np.sqrt(a))\n```\n\n    [ 3.  5.  6.]\n\n\n<a id='MagicFunctions'></a>\n### Magic Functions\nWe can use *magic function* (http://ipython.readthedocs.io/en/stable/interactive/magics.html), `%timeit`, to compare the time the user-defined function takes to execute compared to the Numpy function. \n\nIt is important to optimise code for the most desirable parameter. In this example, the user defined code is significantly faster, but the function using numpy applies to a far wider range of input cases.\n\n\n```python\n%timeit max_min_mean(0.5, 0.1, -20)\nprint()\n%timeit np_max_min_mean([0.5, 0.1, -20])\n```\n\n    406 ns \u00b1 155 ns per loop (mean \u00b1 std. dev. of 7 runs, 1000000 loops each)\n    \n    24.2 \u00b5s \u00b1 11.7 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 100000 loops each)\n\n\n##### Try it yourself \nIn the cell below, find a Numpy function that provides the same solution as the function you wrote as your answer to __Seminar 3, Review Exercise: Indexing, part (A)__: \n<br>Add two vectors, $\\mathbf{A}$ and $\\mathbf{B}$ such that:\n$ \\mathbf{A} + \\mathbf{B} = [(A_1 + B_1), \n                              (A_2 + B_2),\n                              ...\n                              (A_n + B_n)]$\n\n__(A)__ Use the Numpy function to add vectors:\n\n$\\mathbf{A} = [-2, 1, 3]$\n\n$\\mathbf{B} = [6, 2, 2]$\n\nCheck that your answer is the same as your answer to __Seminar 3, Review Exercise: Indexing__.\n\n__(B)__ Using your answer to  __Seminar 3, Review Exercise: Indexing__ write a function `vector_add` that takes vectors A and B as inputs and returns the sum of the two vectors by calling:\n\n```python\nvector_add(A, B)\n```\n\n__(C)__ Use *magic function* `%timeit`, to compare the speed of the Numpy function to the user defined function `vector_add`. \n<br> Which is fastest?\n\n\n```python\n# Vector Addition\n```\n\n<a id='ImportingAlgorithms'></a>\n## Importing Algorithms as Functions (e.g. Root finding)\n\nSo far we have mostly looked at library functions that perform single mathematical operations such as trigonomtric or algebraic functions. \n\nLibrary functions also include those that can be used for complete multi-stage tasks.\n\n\n\nFor example, in place of the `bisection` function you wrote to find the root of a function, a number of root-finding functions from imported modules can be used. \n\nThe package `scipy.optimize` contains a number of functions for estimating the roots of a function given an initial estimate or interval:\n - `scipy.optimize.bisect`\n - `scipy.optimize.fsolve` \n - `scipy.optimize.brentq`\n\nThese are useful when we want to find the root of a function in the vicinity of a particular point or interval.\n\n \n\n\nThe documentation for `fsolve` https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.optimize.fsolve.html:\n\n>scipy.optimize.fsolve(func, x0, args=(), fprime=None, full_output=0, col_deriv=0, xtol=1.49012e-08, maxfev=0, band=None, epsfcn=None, factor=100, diag=None)[source]\n\n>Return the roots of the (non-linear) equations defined by func(x) = 0 given a starting estimate.\n\n>__func__ : callable f(x, *args)\n<br> &nbsp; &nbsp; &nbsp; A function that takes at least one (possibly vector) argument.\n<br>__x0__ : ndarray\n<br>&nbsp; &nbsp; &nbsp; The starting estimate for the roots of func(x) = 0.\n\nWhat does the function do?\n\nWhat __arguments__ does it take (and are there any default arguments)? \n\nHow would we __write__ the function when __calling__ it (accept defaults)?\n\nWhat __data type__ should our input be? \n\nRoot finding methods\n\n__Bisection method, Brent method:__ the user selects the interval in which to look for the root. \n\n__`solve` method:__ the user selects an *initial estimate* for the root.\n\n\n\n \n\n\n\n```python\nimport scipy\nfrom scipy.optimize import fsolve\nfrom scipy.optimize import brentq\n\nroot = scipy.optimize.fsolve(np.cos, -5)\nprint(root, root/pi)\n\nroot = scipy.optimize.brentq(np.cos, 0, 2.5)\nprint(root, root/pi)\n```\n\n    [-4.71238898] [-1.5]\n    1.5707963267948966 0.5\n\n\n##### Non-repeating functions.\n \n__Example.__\n\n$f(x) = x^3 + 4x^2 + x - 6$ \n\nThree real roots; -3, -2, and 1.\n<br>We can use the function `np.roots()` to find all roots.\n<br>The function arguments are the coefficients of the polynomial.  \n\n\n\n\n\n```python\nprint(np.roots([1, 4, 1, -6]))\n```\n\n    [-3. -2.  1.]\n\n\nCheck your solution.\n\n\n```python\n# The equation as a Python function\ndef func(x):\n    return x**3 + 4*x**2 + x - 6\n\n# A range of 600 x values (-4 to 2)\nX = [x/100 for x in list(range(-400, 200))]\n\n# The value of y for each x\nY = [func(x) for x in X]\n\n# List comprehension: return X where Y = 0\ncheck_roots = [x for x,y in zip(X,Y) if y==0]\nprint(check_roots)\n```\n\n    [-3.0, -2.0, 1.0]\n\n\nNext week we will check solution by plotting curves. \n\n\n```python\n# plot to check solution\nfrom matplotlib import pyplot as plt \n%matplotlib inline  \nplt.plot(X,Y)\nplt.grid(True, which='both')\n\n\n\n```\n\n__Try it yourself:__\n<br>In the cell below use `numpy.roots()` to find the roots of the function:\n<br>$y = x^3 - 2x^2 - 11x + 12$\n\n\n```python\n# root finding using numpy.roots()\n```\n\n## Stacking Functions\nIf performing multiple functions on a variable or data structure, operations can be stacked to produce shorter code.\n\n\n\n```python\na = range(10)\na = list(a)\na = np.cos(a)\na = np.sum(a)\nprint(a)\n\na = np.sum(np.cos(list(range(10))))\nprint(a)\n```\n\n    0.421623782621\n    0.421623782621\n\n\n\n```python\n\n```\n\n## Review Exercises\nThe following excercises will help you to practise finding useful functions from external packages and applying them when solving engineering problems. \n\n### Review Exercise: Numpy Package Functions. \n<br> Find a function in the Python Numpy documentation that matches the function definition and use it to solve the problems below:\n\n__(A)__ Definition: *Calculates the exponential function, $y= e^x$ for all elements in the input array.*\n\nPrint a list where each element is the exponential function of the corresponding element in list `a = [0.1, 0, 10]`\n\n\n```python\n# Print a list where each element is the exponential of the corresponding element in list a\n```\n\n\n```python\n# Example solution\nprint(np.exp(a))\n```\n\n__(B)__ Definition: *Converts angles from degrees to radians.*\n\nConvert angle `theta`, expressed in degrees, to radians:\n<br>`theta` = 47\n\n\n```python\n# convert angle `theta`, expressed in degrees, to radians\n```\n\n\n```python\n# Example solution\n\nprint(np.deg2rad(theta))\nprint(np.radians(theta))\n```\n\n### Review Exercise: Searching Package Functions - Magnitude\n\nRefer to your answer to __Seminar 4, Review Exercise: Default Arguments.__\n<br>Copy and paste your code in the cell below.\n\n__(A)__ *Elementwise* functions perform an operation on each element of a data structure.\n<br>Within the function create a list to store the values x, y and z:\n```python\ndef magnitude(x, y, z = 0):\n    \"\"\"\n    Returns the magnitude of a 2D or 3D vector\n    \"\"\"\n    vector = [x, y, z]\n```\n\n Within your function, replace the operations to square each item of the list, `vector`, with an elementwise numpy function. \n \n <a href='#ElementwiseFunctions'>Jump to Elementwise Functions</a>\n\n__(B)__ Find an Numpy functions to the replace operation for:\n\n - summation $\\sum$\n - square root $\\sqrt x$\nand include these in your function. \n\n__(C)__ Use *magic function*  `%timeit`, to compare the speed of your user-defined function (from Seminar 4) to the speed when using Numpy functions.\n<br> Which is fastest?\n\n <a href='#MagicFunctions'>Jump to Magic Functions</a>\n\n__(D)__ Search online for a single numpy function that takes a vector as input and returns the magnitide of a vector. \n<br> Use it calculate the magnitude of the vector $x$. \n<br> Check the answer against the value generated in __A__\n\n__(E)__ Use *magic function* `%timeit`, to compare the time for:\n - the Numpy function to return the magnitude\n - the function you used in parts __(A)-(C)__ \nfor 2D and 3D vectors. \n\n\n\n```python\n# Searching for Appropriate Package Functions \n```\n\n\n```python\n# Example solution\n\ndef magnitude(x, y, z = 0):\n    \"\"\"\n    Returns the magnitude of a 2D or 3D vector\n    \"\"\"\n    vector = [x, y, z]\n    \n    return(np.sqrt(np.sum(np.square(vector))))\n\nprint(magnitude(3, 4))\nprint(magnitude(12, 7, -9))\n\n%timeit magnitude(3, 4)\n%timeit magnitude(12, 7, -9)\n\nprint(np.linalg.norm([3, 4]))\nprint(np.linalg.norm([12, 7, -9]))\n\n%timeit np.linalg.norm([3, 4])\n%timeit np.linalg.norm([12, 7, -9])\n```\n\n### Review Exercise: Searching Package Functions - Dot Product\nRecall __Seminar 4: Daat Structures - Iterating with Zip \n\nWe saw that the __dot product__ of two vectors can be experssed both geometrically and algebraically. \n\n__GEOMETRIC REPRESENTATION__\n\n\\begin{align}\n\\mathbf{A} \\cdot \\mathbf{B} = |\\mathbf{A}| |\\mathbf{B}| \\cos(\\theta)\n\\end{align}\n\n__ALGEBRAIC REPRESENTATION__\n\n>So the dot product of two 3D vectors:\n> <br> $ \\mathbf{A} = [A_x, A_y, A_z]$\n> <br> $ \\mathbf{B} = [B_x, B_y, B_z]$\n> <br> is:\n\n\\begin{align}\n\\mathbf{A} \\cdot \\mathbf{B} &= \\sum_{i=1}^n A_i B_i \\\\\n&= A_x B_x + A_y B_y + A_z B_z.\n\\end{align}\n\n\n\nWe looked at a program that comuted the dot product of two 3D vectors using two lists. \n\n$\\mathbf{C} = [2, 4, 3.5]$\n\n$\\mathbf{D} = [1, 2, -6]$\n\n\n__(A)__ Search for a Numpy function to find the dot product of two lists.\nUse it to find the dot product of $C$ and $D$.\n\n__(B)__ Search for a Numpy function for $\\cos^{-1}$ and use it to compute $\\theta$) using the geometric expresssion for the dot product.\n\n\n```python\n# Find the dot product of A and B\n# Compute theta\n```\n\n\n```python\n# Example Solution\n\nCDdot = np.dot(C,D)\n\nCmag = np.linalg.norm(C)\n\nDmag = np.linalg.norm(D)\n\ntheta = np.arccos(CDdot / (Cmag * Dmag))\n\nprint(f\"dot product = {CDdot}, theta = {theta}\")\n```\n\n### Review Exercise: Using Package Functions to Optimise your Code\n\nSearch for a Numpy function that has a __similar__ function to the `is_positive` function from Section: <a href='#UsingPackageFunctions'>Using Package Functions</a>; the answer it returns should show if an input value is positive or not. \n\nIn the cell below:\n - copy and paste the `is_positive` function\n - use the magic function `%timeit` to compare the speed of the `is_positive` function with the Numpy function for analysing the sign of a numerical input.\n\n<a href='#is_positive'>Jump to function:`is_positive`</a> \n\n\n\n\n```python\n# Numpy function to test if number is positive \n```\n\n\n```python\n# Example Solution\nnp.sign(-2)\n```\n\n### Review Exercise: Importing Algorithms as Functions\n\nIn <a href='#ImportingAlgorithms'>Importing Algorithms as Functions (e.g. Root finding)</a> we learnt that the package scipy.optimize contains a number of functions for estimating the roots of a function, including `scipy.optimize.bisect`.\n\nThis function performs the same/a similar function to the `bisection` function that you have been developing. \n\n__(A)__ Find the documentation for the function `scipy.optimize.bisect` to learn how to use it.\n\n__(B)__ Use `scipy.optimize.bisect` to estimate the root of the function $f(x) = 2\\sin^2 x - 3\\sin x + 1$:\n<br> &nbsp; &nbsp; &nbsp; (i) between 0 and $\\frac{\\pi}{6}$\n<br> &nbsp; &nbsp; &nbsp; (ii) between 1.5 and 2\n<br> &nbsp; &nbsp; &nbsp; (iii) between $\\frac{3}{4}\\pi$ and $\\pi$\n\n__NOTE:__ &nbsp; $\\sin^2(x) = (\\sin(x))^2$\n\n__(C)__ Use the magic function %timeit to compare the speed of your user-defined function `bisection`, with the speed of `scipy.optimize.bisect`. \n\n\n```python\n# Scipy bisection algorithm\n```\n\n\n```python\n# Example solution\n\nimport scipy\nfrom scipy.optimize import bisect\n\ndef func(x):\n    return x**3 + 4*x**2 + x - 6\n\ndef q(x):\n    return (2 * (np.sin(x))**2) - (3 * np.sin(x)) + 1\n\nscipy.optimize.bisect(func, 0, 3)\nscipy.optimize.bisect(q, 0, 1.5)\n```\n\n# Updating your git repository\n\nYou have made several changes to your interactive textbook.\n \n > Save your work.\n > <br> `git add -A`\n > <br>`git commit -m \"A short message describing changes\"`\n  \n\n# Summary\n\n- Python has an extensive __standard library__ of built-in functions. \n- More specialised libraries of functions and constants are available. We call these __packages__. \n- Packages are imported using the keyword `import`\n- The function documentation tells is what it does and how to use it.\n- When calling a library function it must be prefixed with a __namespace__ is used to show from which package it should be called.  \n- The magic function `%timeit` can be used to time the execution of a function. \n\n\n\n\n# Homework \n\n1. __PULL__ the changes you made in-class today to your personal computer.\n1. __COMPLETE__ any unfinished Review Exercises.\n1. __PUSH__ the changes you make at home to your online repository. \n\n\n```python\n\n```\n", "meta": {"hexsha": "10f1a4f660caba2f4e9bc28761430631d8d7280e", "size": 81081, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "6_Library_Functions.ipynb", "max_stars_repo_name": "tlyou/KU_intro_python", "max_stars_repo_head_hexsha": "74cba4479980547659aaeaefafd05d53d499500d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "6_Library_Functions.ipynb", "max_issues_repo_name": "tlyou/KU_intro_python", "max_issues_repo_head_hexsha": "74cba4479980547659aaeaefafd05d53d499500d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "6_Library_Functions.ipynb", "max_forks_repo_name": "tlyou/KU_intro_python", "max_forks_repo_head_hexsha": "74cba4479980547659aaeaefafd05d53d499500d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2653975364, "max_line_length": 13324, "alphanum_fraction": 0.6057276057, "converted": true, "num_tokens": 9299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07585817375348311, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.02891862009528649}}
{"text": "```python\n#remove cell visibility\nfrom IPython.display import HTML\ntag = HTML('''\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.''')\ndisplay(tag)\n```\n\n\n\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.\n\n\n\n```python\n%matplotlib inline\nimport control\nimport numpy\nimport sympy as sym\nfrom IPython.display import display, Markdown\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\n\n\n#print a matrix latex-like\ndef bmatrix(a):\n     \"\"\"Returns a LaTeX bmatrix - by Damir Arbula (ICCT project)\n\n     :a: numpy array\n     :returns: LaTeX bmatrix as a string\n     \"\"\"\n     if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n     lines = str(a).replace('[', '').replace(']', '').splitlines()\n     rv = [r'\\begin{bmatrix}']\n     rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n     rv +=  [r'\\end{bmatrix}']\n     return '\\n'.join(rv)\n\n\n# Display formatted matrix: \ndef vmatrix(a):\n    if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n    lines = str(a).replace('[', '').replace(']', '').splitlines()\n    rv = [r'\\begin{vmatrix}']\n    rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n    rv +=  [r'\\end{vmatrix}']\n    return '\\n'.join(rv)\n\n\n#matrixWidget is a matrix looking widget built with a VBox of HBox(es) that returns a numPy array as value !\nclass matrixWidget(widgets.VBox):\n    def updateM(self,change):\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.M_[irow,icol] = self.children[irow].children[icol].value\n                #print(self.M_[irow,icol])\n        self.value = self.M_\n\n    def dummychangecallback(self,change):\n        pass\n    \n    \n    def __init__(self,n,m):\n        self.n = n\n        self.m = m\n        self.M_ = numpy.matrix(numpy.zeros((self.n,self.m)))\n        self.value = self.M_\n        widgets.VBox.__init__(self,\n                             children = [\n                                 widgets.HBox(children = \n                                              [widgets.FloatText(value=0.0, layout=widgets.Layout(width='90px')) for i in range(m)]\n                                             ) \n                                 for j in range(n)\n                             ])\n        \n        #fill in widgets and tell interact to call updateM each time a children changes value\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        #value = Unicode('example@example.com', help=\"The email value.\").tag(sync=True)\n        self.observe(self.updateM, names='value', type= 'All')\n        \n    def setM(self, newM):\n        #disable callbacks, change values, and reenable\n        self.unobserve(self.updateM, names='value', type= 'All')\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].unobserve(self.updateM, names='value')\n        self.M_ = newM\n        self.value = self.M_\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        self.observe(self.updateM, names='value', type= 'All')        \n\n                #self.children[irow].children[icol].observe(self.updateM, names='value')\n\n             \n#overlaod class for state space systems that DO NOT remove \"useless\" states (what \"professor\" of automatic control would do this?)\nclass sss(control.StateSpace):\n    def __init__(self,*args):\n        #call base class init constructor\n        control.StateSpace.__init__(self,*args)\n    #disable function below in base class\n    def _remove_useless_states(self):\n        pass\n```\n\n## Controllo dell'orbita di un satellite\n\nLa dinamica di un satellite in orbita circolare attorno alla Terra pu\u00f2 essere descritta dalla seguente equazione dinamica non lineare:\n$$\n    \\ddot{r} = f(r,\\tau,d) = r\\dot{\\theta}^2 - \\frac{K}{r^2} + \\tau + d \\, ,\n$$\n\ndove $r$ \u00e8 il raggio dell'orbita, $\\theta$ \u00e8 l'angolo che descrive la posizione del satellite nell'orbita circolare, $K = 398600$ km^3/s^2 \u00e8 una costante, $\\tau$ \u00e8 la spinta radiale del satellite prodotta da un attuatore appropriato (limite: $|\\tau|\\leq 100 \\mu\\text{N}$) e $d$ \u00e8 il disturbo della gravit\u00e0.\n\nSi vuole progettare un regolatore per il raggio dell'orbita secondo le seguenti specifiche:\n- tempo di assestamento al 5% inferiore ad 1 ora;\n- overshoot inferiore al 40%;\n- errore nullo a regime in risposta a una richiesta di posizione a gradino.\n\nPer avere un sistema dinamico lineare si linearizza l'equazione all'equilibrio ($r_{eq} = 16763$ km, $\\dot{r}_{eq}=0$, $\\tau_{eq}=0$, $d_{eq}=0$) considerando $\\omega_{eq}=\\dot{\\theta}_{eq}= \\frac{2\\pi}{6\\times3600}$. Definendo $x=\\begin{bmatrix} x_1 & x_2 \\end{bmatrix}^T=\\begin{bmatrix} \\dot{r} & r \\end{bmatrix}^T$ e $u=\\begin{bmatrix} \\tau & d \\end{bmatrix}^T$ le equazioni nello spazio degli stati diventano:\n\n\\begin{cases}\n    \\dot{\\delta x} = \\frac{\\partial f(x,u)}{\\partial x}\\Bigr|_{\\substack{x=x_{eq}\\\\u=u_{eq}}}(x-x_{eq}) + \\frac{\\partial f(x,u)}{\\partial u}\\Bigr|_{\\substack{x=x_{eq}\\\\u=u_{eq}}}(u-u_{eq}) = A\\delta x+ B\\delta u = \\begin{bmatrix} 0 & \\omega_{eq}^2 + 2\\frac{K}{r_{eq}^3} \\\\ 1 & 0 \\end{bmatrix}\\delta x + \\begin{bmatrix} 1 & 1 \\\\ 0 & 0 \\end{bmatrix}\\delta u\\\\\n    y = C\\delta x = \\begin{bmatrix} 0 & 1 \\end{bmatrix}\\delta x \\, .\n\\end{cases}\n\nI poli del sistema sono $\\pm0.000504$.\n\n### Sviluppo del regolatore\n#### Design del controller\n\nSi assicura l'errore nullo a regime aggiungendo un nuovo stato $\\dot{\\delta x_3} = \\delta x_2 - y_d$\n\n\\begin{cases}\n    \\dot{x}_a = \\begin{bmatrix} 0 & \\omega_{eq}^2 + 2\\frac{K}{r_{eq}^3} & 0 \\\\ 1 & 0 & 0 \\\\ 0 & 1 & 0 \\end{bmatrix}x_a + \\begin{bmatrix} 1 & 1 & 0 \\\\ 0 & 0 & 0 \\\\ 0 & 0 & -1 \\end{bmatrix}\\begin{bmatrix} \\tau \\\\ d \\\\ y_d\\end{bmatrix}\\\\\n    y_a = \\begin{bmatrix} 0 & 1 & 0 \\\\ 0 & 0 & 1\\end{bmatrix}x_a \\, .\n\\end{cases}\n\nUna possibile posizione per i poli del sistema a ciclo chiuso \u00e8 $-0.0504$ e $-0.001\\pm0.003i$.\n\n#### Design dell'osservatore\n\nPoich\u00e9 si misura direttamente $\\delta x_2$ e $\\delta x_3$ (vedere la matrice di output), \u00e8 possibile progettare un osservatore solo per $\\delta x_1$. Lavorando con il sottosistema ($\\delta x_1$, $\\delta x_2$) e definendo $L=\\begin{bmatrix} l_1 & l_2 \\end{bmatrix}^T$ si pu\u00f2 scrivere:\n\n$$\n    \\dot{\\hat{\\delta x}} = \\left(A-LC\\right)\\hat{\\delta x} + \\begin{bmatrix} 1 \\\\ 0 \\end{bmatrix}\\tau + Ly \\, ,\n$$\n\nutilizzando la trasformata di Laplace e risolvendo per $\\hat{\\delta x}_1(s)$ si ottiene:\n\n$$\n    \\hat{\\delta x}_1(s) = \\frac{l_2  + s}{\\left(l_1 - \\frac{2K}{r_{eq}^3}- \\omega_{eq}^2\\right) + l_2s + s^2}\\tau + \\frac{l_2\\left(\\frac{2K}{r_{eq}^3} + \\omega_{eq}^2\\right) + l_1s}{\\left(l_1 - \\frac{2K}{r_{eq}^3}- \\omega_{eq}^2\\right) + l_2s + s^2}y \\, .\n$$\n\nSi posizionano entrambi i poli dell'osservatore in $-1$.\n\n### Come utilizzare questo notebook?\n- Prova a modificare la risposta in modo da ottenere 0% di overshoot con un requisito rilassato per il tempo di assestamento (2 ore).\n- Verifica le prestazioni del sistema controllato con un gradino e disturbo sinusoidale.\n\n\n```python\n# Preparatory cell\nom = 2*numpy.pi/3600/6\nK = 398600\nr = 16763\nAa = numpy.matrix([[0, om**2+2*K/r**3, 0],\n                   [1, 0, 0],\n                   [0, 1, 0]])\nBa = numpy.matrix([[1, 1, 0],\n                   [0, 0, 0],\n                   [0, 0, -1]])\nCa = numpy.matrix([[0, 1, 0],\n                   [0, 0, 1]])\n\nX0 = numpy.matrix('0.0')\nK = numpy.matrix([8/15,-4.4,-4])\nL = numpy.matrix([[23],[66],[107/3]])\n\nX0w = matrixWidget(1,1)\nX0w.setM(X0)\nKw = matrixWidget(1,3)\nKw.setM(K)\nLw = matrixWidget(2,1)\nLw.setM(L)\n\n\neig1c = matrixWidget(1,1)\neig2c = matrixWidget(2,1)\neig3c = matrixWidget(1,1)\neig1c.setM(numpy.matrix([-0.0504])) \neig2c.setM(numpy.matrix([[-0.001],[-0.003]]))\neig3c.setM(numpy.matrix([-1.0]))\n\neig1o = matrixWidget(1,1)\neig2o = matrixWidget(2,1)\neig1o.setM(numpy.matrix([-1.])) \neig2o.setM(numpy.matrix([[-1.],[0.]]))\n```\n\n\n```python\n# Misc\n\n#create dummy widget \nDW = widgets.FloatText(layout=widgets.Layout(width='0px', height='0px'))\n\n#create button widget\nSTART = widgets.Button(\n    description='Test',\n    disabled=False,\n    button_style='', # 'success', 'info', 'warning', 'danger' or ''\n    tooltip='Test',\n    icon='check'\n)\n                       \ndef on_start_button_clicked(b):\n    #This is a workaround to have intreactive_output call the callback:\n    #   force the value of the dummy widget to change\n    if DW.value> 0 :\n        DW.value = -1\n    else: \n        DW.value = 1\n    pass\nSTART.on_click(on_start_button_clicked)\n\n# Define type of method \nselm = widgets.Dropdown(\n    options= [('Imposta K','Set K'), ('Imposta gli autovalori','Set the eigenvalues')],\n    value= 'Set the eigenvalues',\n    description='',\n    disabled=False\n)\n\n# Define the number of complex eigenvalues\nsele = widgets.Dropdown(\n    options= [('0 autovalori complessi','0 complex eigenvalues'), ('2 autovalori complessi','2 complex eigenvalues')],\n    value= '2 complex eigenvalues',\n    description='Autovalori complessi:',\n    style = {'description_width': 'initial'},\n    disabled=False\n)\n\n#define type of ipout \nselu = widgets.Dropdown(\n    options=[('impulso','impulse'), ('gradino','step'), ('sinusoide','sinusoid'), ('onda quadra','square wave')],\n    value='step',\n    description='Disturbo:',\n    style = {'description_width': 'initial'},\n    disabled=False\n)\n# Define the values of the input\nu = widgets.FloatSlider(\n    value=10,\n    min=0,\n    max=30,\n    step=1,\n    description='Riferimento [m]:',\n    style = {'description_width': 'initial'},\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.1f',\n)\nd = widgets.FloatSlider(\n    value=0,\n    min=-3,\n    max=3,\n    step=0.1,\n    description='Disturbo [\u00b5m/s^2]:',\n    style = {'description_width': 'initial'},\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.1f',\n)\nperiod = widgets.FloatSlider(\n    value=100,\n    min=1,\n    max=300,\n    step=1,\n    description='Periodo [\u00b5s]: ',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.1f',\n)\nsimTime = widgets.FloatText(\n    value=3600*2,\n    description='',\n    disabled=False\n)\n```\n\n\n```python\n# Support functions\n\ndef eigen_choice(sele):\n    if sele == '0 complex eigenvalues':\n        eig1c.children[0].children[0].disabled = False\n        eig2c.children[1].children[0].disabled = True\n        eig1o.children[0].children[0].disabled = False\n        eig2o.children[1].children[0].disabled = True\n        eig = 0\n    if sele == '2 complex eigenvalues':\n        eig1c.children[0].children[0].disabled = True\n        eig2c.children[1].children[0].disabled = False\n        eig1o.children[0].children[0].disabled = True\n        eig2o.children[1].children[0].disabled = False\n        eig = 2\n    return eig\n\ndef method_choice(selm):\n    if selm == 'Set K and L':\n        method = 1\n        sele.disabled = True\n    if selm == 'Set the eigenvalues':\n        method = 2\n        sele.disabled = False\n    return method\n```\n\n\n```python\nA = Aa[0:2,0:2]\nB = Ba[0:2,0]\nC = Ca[0,0:2]\n\ndef main_callback2(d, X0w, K, L, eig1c, eig2c, eig3c, eig1o, eig2o, u, period, selm, sele, selu, simTime, DW):\n    eige = eigen_choice(sele)\n    method = method_choice(selm)\n    \n    if method == 1:\n        solc = numpy.linalg.eig(Aa-Ba[:,0]*K)\n        solo = numpy.linalg.eig(A-L*C)\n    if method == 2:\n        if eige == 0:\n            K = control.acker(Aa, Ba[:,0], [eig1c[0,0], eig2c[0,0], eig3c[0,0]])\n            Kw.setM(K)\n            L = control.acker(A.T, C.T, [eig1o[0,0], eig2o[0,0]]).T\n            Lw.setM(L)\n        if eige == 2:\n            K = control.acker(Aa, Ba[:,0], [eig3c[0,0], \n                                     numpy.complex(eig2c[0,0],eig2c[1,0]), \n                                     numpy.complex(eig2c[0,0],-eig2c[1,0])])\n            Kw.setM(K)\n            L = control.acker(A.T, C.T, [numpy.complex(eig2o[0,0],eig2o[1,0]), \n                                         numpy.complex(eig2o[0,0],-eig2o[1,0])]).T\n            Lw.setM(L)\n            \n    \n    sys = control.ss(Aa,Ba,numpy.vstack((Ca,[0,0,0])),[[0,0,0],[0,0,0],[1,0,0]])\n    sysE = control.ss(A-L*C,\n                      numpy.hstack((B,L)),\n                      [1,0],\n                      [0,0])\n    sysC = control.ss(numpy.zeros((1,1)),\n                      [0, 0, 0],\n                      0,\n                      -K)\n    \n    sys_append = control.append(sys, sysE, sysC)        \n    sys_CL = control.connect(sys_append,\n                             [[1,5],[4,3],[5,1],[6,4],[7,1],[8,2]],\n                             [3,2], # in\n                             [1,3]) # out\n    \n    \n    X0w1 = numpy.zeros((5,1))\n    X0w1[3,0] = X0w\n    if simTime != 0:\n        T = numpy.linspace(0, simTime, 10000)\n    else:\n        T = numpy.linspace(0, 1, 10000)\n    \n    d = d/1E6\n    period=period/1E6\n    U1 = [u for t in range(0,len(T))]\n    if selu == 'impulse': #selu\n        U = [0 for t in range(0,len(T))]\n        U[0] = d        \n        T, yout, xout = control.forced_response(sys_CL,T,[U1,U],X0w1)\n    if selu == 'step':\n        U = [d for t in range(0,len(T))]\n        T, yout, xout = control.forced_response(sys_CL,T,[U1,U],X0w1)\n    if selu == 'sinusoid':\n        U = d*numpy.sin(2*numpy.pi/period*T)\n        T, yout, xout = control.forced_response(sys_CL,T,[U1,U],X0w1)\n    if selu == 'square wave':\n        U = d*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n        T, yout, xout = control.forced_response(sys_CL,T,[U1,U],X0w1)\n    \n    step_info_dict = control.step_info(sys_CL[0,0],SettlingTimeThreshold=0.05,T=T)\n    print('Step info: \\n\\tTempo di assestamento (5%) [ore]=',step_info_dict['SettlingTime']/3600,'\\n\\tOvershoot (%)=',step_info_dict['Overshoot'])\n    print('Valore massimo di u (% di 100\u00b5N)=', max(abs(yout[1]))/(100E-06)*100)\n    \n    fig = plt.figure(num='Simulation1', figsize=(16,12))\n    \n    fig.add_subplot(221)\n    plt.title('Risposta dell\\'uscita')\n    plt.ylabel('Uscita [m]')\n    plt.plot(T,yout[0])\n    plt.xlabel('$t$ [s]')\n    plt.legend(['$y$'])\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(222)\n    plt.title('Ingresso')\n    plt.ylabel('$u$ [N]')\n    plt.plot(T,yout[1])\n    plt.plot(T,[100/1E6 for t in range(len(T))],'r--')\n    plt.plot(T,[-100/1E6 for t in range(len(T))],'r--')\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(223)\n    plt.title('Risposta degli stati')\n    plt.ylabel('Stati')\n    plt.plot(T,xout[0],\n             T,xout[1],\n             T,xout[2])\n    plt.xlabel('$t$ [s]')\n    plt.legend(['$\\delta x_{1}$','$\\delta x_{2}$','$\\delta x_{3}$'])\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(224)\n    plt.title('Errore di stima')\n    plt.ylabel('Errore')\n    plt.plot(T,xout[0]-xout[3])\n    plt.xlabel('$t$ [s]')\n    plt.legend(['$e_{1}$'])\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    #plt.tight_layout()\n    \n    fig.tight_layout()\n   \nalltogether2 = widgets.VBox([widgets.HBox([selm, \n                                          sele,\n                                          selu]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.Label('K:',border=3), Kw, \n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Autovalori:',border=3), \n                                          eig1c, \n                                          eig2c, \n                                          eig3c,\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('X0 stim.:',border=3), X0w]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.Label('L:',border=3), Lw, \n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Autovalori:',border=3), \n                                          eig1o, \n                                          eig2o,\n                                          widgets.Label(' ',border=3),\n                                          widgets.VBox([widgets.Label('Tempo di simulazione (s):',border=3)]),\n                                          widgets.VBox([simTime])]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([u,\n                                          d,\n                                          period, \n                                          START])])\nout2 = widgets.interactive_output(main_callback2, {'d':d, 'X0w':X0w, 'K':Kw, 'L':Lw,\n                                                 'eig1c':eig1c, 'eig2c':eig2c, 'eig3c':eig3c, 'eig1o':eig1o, 'eig2o':eig2o, \n                                                 'u':u, 'period':period, 'selm':selm, 'sele':sele, 'selu':selu, 'simTime':simTime, 'DW':DW})\nout2.layout.height = '850px'\ndisplay(out2, alltogether2)\n```\n\n\n    Output(layout=Layout(height='850px'))\n\n\n\n    VBox(children=(HBox(children=(Dropdown(index=1, options=(('Imposta K', 'Set K'), ('Imposta gli autovalori', 'S\u2026\n\n", "meta": {"hexsha": "6611877c72280250f0ca0e6b88ad1df98ef8b656", "size": 25342, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_it/examples/04/.ipynb_checkpoints/SS-36-Controllo_dell_orbita_di_un_satellite-checkpoint.ipynb", "max_stars_repo_name": "ICCTerasmus/ICCT", "max_stars_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-22T18:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:10:22.000Z", "max_issues_repo_path": "ICCT_it/examples/04/.ipynb_checkpoints/SS-36-Controllo_dell_orbita_di_un_satellite-checkpoint.ipynb", "max_issues_repo_name": "ICCTerasmus/ICCT", "max_issues_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICCT_it/examples/04/.ipynb_checkpoints/SS-36-Controllo_dell_orbita_di_un_satellite-checkpoint.ipynb", "max_forks_repo_name": "ICCTerasmus/ICCT", "max_forks_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-24T11:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T16:36:18.000Z", "avg_line_length": 40.6773675762, "max_line_length": 438, "alphanum_fraction": 0.467090206, "converted": true, "num_tokens": 5482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.320821300824607, "lm_q2_score": 0.0900929848003928, "lm_q1q2_score": 0.028903748578833564}}
{"text": "```python\n! pip install qeds\nimport pandas as pd\n%matplotlib inline\nimport qeds\nqeds.themes.mpl_style();\n```\n\n    Requirement already satisfied: qeds in c:\\users\\asus\\anaconda3\\lib\\site-packages (0.6.2)\n    Requirement already satisfied: numpy in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (1.16.5)\n    Requirement already satisfied: pandas in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.25.1)\n    Requirement already satisfied: openpyxl in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (3.0.0)\n    Requirement already satisfied: plotly in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (4.5.4)\n    Requirement already satisfied: requests in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (2.22.0)\n    Requirement already satisfied: quantecon in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.4.6)\n    Requirement already satisfied: scikit-learn in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.21.3)\n    Requirement already satisfied: seaborn in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.9.0)\n    Requirement already satisfied: statsmodels in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.10.1)\n    Requirement already satisfied: pandas-datareader in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.8.1)\n    Requirement already satisfied: matplotlib in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (3.1.1)\n    Requirement already satisfied: pyarrow in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.16.0)\n    Requirement already satisfied: scipy in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (1.3.1)\n    Requirement already satisfied: quandl in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (3.5.0)\n    Requirement already satisfied: pytz>=2017.2 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pandas->qeds) (2019.3)\n    Requirement already satisfied: python-dateutil>=2.6.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pandas->qeds) (2.8.0)\n    Requirement already satisfied: jdcal in c:\\users\\asus\\anaconda3\\lib\\site-packages (from openpyxl->qeds) (1.4.1)\n    Requirement already satisfied: et-xmlfile in c:\\users\\asus\\anaconda3\\lib\\site-packages (from openpyxl->qeds) (1.0.1)\n    Requirement already satisfied: retrying>=1.3.3 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from plotly->qeds) (1.3.3)\n    Requirement already satisfied: six in c:\\users\\asus\\anaconda3\\lib\\site-packages (from plotly->qeds) (1.12.0)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (1.24.2)\n    Requirement already satisfied: idna<2.9,>=2.5 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (2.8)\n    Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (2019.9.11)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (3.0.4)\n    Requirement already satisfied: sympy in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quantecon->qeds) (1.4)\n    Requirement already satisfied: numba>=0.38 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quantecon->qeds) (0.45.1)\n    Requirement already satisfied: joblib>=0.11 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from scikit-learn->qeds) (0.13.2)\n    Requirement already satisfied: patsy>=0.4.0 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from statsmodels->qeds) (0.5.1)\n    Requirement already satisfied: lxml in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pandas-datareader->qeds) (4.4.1)\n    Requirement already satisfied: cycler>=0.10 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (1.1.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (2.4.2)\n    Requirement already satisfied: more-itertools in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quandl->qeds) (7.2.0)\n    Requirement already satisfied: inflection>=0.3.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quandl->qeds) (0.3.1)\n    Requirement already satisfied: mpmath>=0.19 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from sympy->quantecon->qeds) (1.1.0)\n    Requirement already satisfied: llvmlite>=0.29.0dev0 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from numba>=0.38->quantecon->qeds) (0.29.0)\n    Requirement already satisfied: setuptools in c:\\users\\asus\\anaconda3\\lib\\site-packages (from kiwisolver>=1.0.1->matplotlib->qeds) (41.4.0)\n\n\n# Basic Functionality - Exercises\n\n\n**For these exercises we use unemployment data by state at a monthly frequency.**\n\n- **We download the data directly from a url and read it into a pandas DataFrame.**\n\n- **Since we want to look at the unemployment rate across different states over time, we proceed to a transformation of the data similar to an Excel pivot-table.**\n\n\n```python\n#Download the data directly from a url and read it into a pandas DataFrame.\nurl = \"https://datascience.quantecon.org/assets/data/state_unemployment.csv\"\nunemp_raw = pd.read_csv(url, parse_dates=[\"Date\"])\n```\n\n\n```python\n#Transformation of the data similar to an Excel pivot-table\nunemp_all = (\n    unemp_raw\n    .reset_index()\n    .pivot_table(index=\"Date\", columns=\"state\", values=\"UnemploymentRate\")\n)\nunemp_all.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>state</th>\n      <th>Alabama</th>\n      <th>Alaska</th>\n      <th>Arizona</th>\n      <th>Arkansas</th>\n      <th>California</th>\n      <th>Colorado</th>\n      <th>Connecticut</th>\n      <th>Delaware</th>\n      <th>Florida</th>\n      <th>Georgia</th>\n      <th>...</th>\n      <th>South Dakota</th>\n      <th>Tennessee</th>\n      <th>Texas</th>\n      <th>Utah</th>\n      <th>Vermont</th>\n      <th>Virginia</th>\n      <th>Washington</th>\n      <th>West Virginia</th>\n      <th>Wisconsin</th>\n      <th>Wyoming</th>\n    </tr>\n    <tr>\n      <th>Date</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>2000-01-01</td>\n      <td>4.7</td>\n      <td>6.3</td>\n      <td>4.1</td>\n      <td>4.4</td>\n      <td>5.0</td>\n      <td>2.8</td>\n      <td>2.8</td>\n      <td>3.5</td>\n      <td>3.7</td>\n      <td>3.7</td>\n      <td>...</td>\n      <td>2.4</td>\n      <td>3.7</td>\n      <td>4.6</td>\n      <td>3.1</td>\n      <td>2.7</td>\n      <td>2.6</td>\n      <td>4.9</td>\n      <td>5.8</td>\n      <td>3.2</td>\n      <td>4.1</td>\n    </tr>\n    <tr>\n      <td>2000-02-01</td>\n      <td>4.7</td>\n      <td>6.3</td>\n      <td>4.1</td>\n      <td>4.3</td>\n      <td>5.0</td>\n      <td>2.8</td>\n      <td>2.7</td>\n      <td>3.6</td>\n      <td>3.7</td>\n      <td>3.6</td>\n      <td>...</td>\n      <td>2.4</td>\n      <td>3.7</td>\n      <td>4.6</td>\n      <td>3.1</td>\n      <td>2.6</td>\n      <td>2.5</td>\n      <td>4.9</td>\n      <td>5.6</td>\n      <td>3.2</td>\n      <td>3.9</td>\n    </tr>\n    <tr>\n      <td>2000-03-01</td>\n      <td>4.6</td>\n      <td>6.3</td>\n      <td>4.0</td>\n      <td>4.3</td>\n      <td>5.0</td>\n      <td>2.7</td>\n      <td>2.6</td>\n      <td>3.6</td>\n      <td>3.7</td>\n      <td>3.6</td>\n      <td>...</td>\n      <td>2.4</td>\n      <td>3.8</td>\n      <td>4.5</td>\n      <td>3.1</td>\n      <td>2.6</td>\n      <td>2.4</td>\n      <td>5.0</td>\n      <td>5.5</td>\n      <td>3.3</td>\n      <td>3.9</td>\n    </tr>\n    <tr>\n      <td>2000-04-01</td>\n      <td>4.6</td>\n      <td>6.3</td>\n      <td>4.0</td>\n      <td>4.3</td>\n      <td>5.1</td>\n      <td>2.7</td>\n      <td>2.5</td>\n      <td>3.7</td>\n      <td>3.7</td>\n      <td>3.7</td>\n      <td>...</td>\n      <td>2.4</td>\n      <td>3.8</td>\n      <td>4.4</td>\n      <td>3.1</td>\n      <td>2.7</td>\n      <td>2.4</td>\n      <td>5.0</td>\n      <td>5.4</td>\n      <td>3.4</td>\n      <td>3.8</td>\n    </tr>\n    <tr>\n      <td>2000-05-01</td>\n      <td>4.5</td>\n      <td>6.3</td>\n      <td>4.0</td>\n      <td>4.2</td>\n      <td>5.1</td>\n      <td>2.7</td>\n      <td>2.4</td>\n      <td>3.7</td>\n      <td>3.7</td>\n      <td>3.7</td>\n      <td>...</td>\n      <td>2.4</td>\n      <td>3.9</td>\n      <td>4.3</td>\n      <td>3.2</td>\n      <td>2.7</td>\n      <td>2.3</td>\n      <td>5.1</td>\n      <td>5.4</td>\n      <td>3.5</td>\n      <td>3.8</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 50 columns</p>\n</div>\n\n\n\n\n```python\n#subset of the columns \nstates = [\n    \"Arizona\", \"California\", \"Florida\", \"Illinois\",\n    \"Michigan\", \"New York\", \"Texas\"\n]\nunemp = unemp_all[states]\nunemp.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>state</th>\n      <th>Arizona</th>\n      <th>California</th>\n      <th>Florida</th>\n      <th>Illinois</th>\n      <th>Michigan</th>\n      <th>New York</th>\n      <th>Texas</th>\n    </tr>\n    <tr>\n      <th>Date</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>2000-01-01</td>\n      <td>4.1</td>\n      <td>5.0</td>\n      <td>3.7</td>\n      <td>4.2</td>\n      <td>3.3</td>\n      <td>4.7</td>\n      <td>4.6</td>\n    </tr>\n    <tr>\n      <td>2000-02-01</td>\n      <td>4.1</td>\n      <td>5.0</td>\n      <td>3.7</td>\n      <td>4.2</td>\n      <td>3.2</td>\n      <td>4.7</td>\n      <td>4.6</td>\n    </tr>\n    <tr>\n      <td>2000-03-01</td>\n      <td>4.0</td>\n      <td>5.0</td>\n      <td>3.7</td>\n      <td>4.3</td>\n      <td>3.2</td>\n      <td>4.6</td>\n      <td>4.5</td>\n    </tr>\n    <tr>\n      <td>2000-04-01</td>\n      <td>4.0</td>\n      <td>5.1</td>\n      <td>3.7</td>\n      <td>4.3</td>\n      <td>3.3</td>\n      <td>4.6</td>\n      <td>4.4</td>\n    </tr>\n    <tr>\n      <td>2000-05-01</td>\n      <td>4.0</td>\n      <td>5.1</td>\n      <td>3.7</td>\n      <td>4.3</td>\n      <td>3.5</td>\n      <td>4.6</td>\n      <td>4.3</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Exercise 1\n\n**Looking at the unemp DataFrame above, can you identify the index? The columns? You can use the cell below to verify your visual intuition.**\n\n\n```python\n#index\nunemp.index\n```\n\n\n\n\n    DatetimeIndex(['2000-01-01', '2000-02-01', '2000-03-01', '2000-04-01',\n                   '2000-05-01', '2000-06-01', '2000-07-01', '2000-08-01',\n                   '2000-09-01', '2000-10-01',\n                   ...\n                   '2017-03-01', '2017-04-01', '2017-05-01', '2017-06-01',\n                   '2017-07-01', '2017-08-01', '2017-09-01', '2017-10-01',\n                   '2017-11-01', '2017-12-01'],\n                  dtype='datetime64[ns]', name='Date', length=216, freq=None)\n\n\n\n\n```python\n#columns\nunemp.columns\n```\n\n\n\n\n    Index(['Arizona', 'California', 'Florida', 'Illinois', 'Michigan', 'New York',\n           'Texas'],\n          dtype='object', name='state')\n\n\n\n## Exercise 2\n\n**Do the following exercises in separate code cells below:**\n\n1. **At each date, what is the minimum unemployment rate across all states in our sample?**\n\n\n```python\n# min unemployment rate by state\nunemp.min()\n\n#alternatively, we can use unemp.agg(min)\n```\n\n\n\n\n    state\n    Arizona       3.6\n    California    4.5\n    Florida       3.1\n    Illinois      4.2\n    Michigan      3.2\n    New York      4.2\n    Texas         3.9\n    dtype: float64\n\n\n\n\n```python\n# The argument axis=1 allows to search within rows. This gives the min overall for a given date\nunemp.min(axis=1)\n```\n\n\n\n\n    Date\n    2000-01-01    3.3\n    2000-02-01    3.2\n    2000-03-01    3.2\n    2000-04-01    3.3\n    2000-05-01    3.5\n                 ... \n    2017-08-01    4.0\n    2017-09-01    3.9\n    2017-10-01    3.9\n    2017-11-01    3.9\n    2017-12-01    3.9\n    Length: 216, dtype: float64\n\n\n\n2. **What was the median unemployment rate in each state?**\n\n\n```python\n# median unemployment rate by state\nunemp.median()\n```\n\n\n\n\n    state\n    Arizona       5.80\n    California    6.50\n    Florida       5.35\n    Illinois      6.15\n    Michigan      7.00\n    New York      5.70\n    Texas         5.40\n    dtype: float64\n\n\n\n3. **What was the maximum unemployment rate across the states in our sample? What state did it happen in? In what month/year was this achieved?**\n        Hint 1: What Python type (not dtype) is returned by the aggregation?\n        Hint 2: Read documentation for the method idxmax\n\n\n```python\n# max unemployment rate across all states and Year\nunemp.max().max()\n```\n\n\n\n\n    14.6\n\n\n\n\n```python\n#type(unemp)\nunemp.max().idxmax()\n\n#if we use unemp.max() we get the max value across all states\n#but we want to know more: \n    #we want the state that had the max of all max unemployment rates and the month/year in which it has been achieved\n```\n\n\n\n\n    'Michigan'\n\n\n\n\n```python\nunemp.max(axis=1).idxmax() \n\n#we can check whether for this date Michigan registered indeed the highest value by doing unemp.loc[\"06/01/2009\",:]\n#we will get True\n```\n\n\n\n\n    Timestamp('2009-06-01 00:00:00')\n\n\n\n4. **Classify each state as high or low volatility based on whether the variance of their unemployment is above or below 4.**\n\n\n\n```python\n# high or low volatility\n\n# 1. we create our aggregation function\n\ndef high_or_low_vol(v):\n    if v.var() > 4:\n        out = \"High\"\n    else:\n        out = \"Low\"\n        \n    return out\n\n# 2. we apply the function via the agg method\n\nunemp.agg(high_or_low_vol)\n```\n\n\n\n\n    state\n    Arizona       High\n    California    High\n    Florida       High\n    Illinois       Low\n    Michigan      High\n    New York       Low\n    Texas          Low\n    dtype: object\n\n\n\n## Exercise 3\n\n**Imagine that we want to determine whether unemployment was high (> 6.5),medium (4.5 < x <= 6.5), or low (<= 4.5) for each state and each month.**\n\n1. **Write a Python function that takes a single number as an input and outputs a single string noting if that number is high, medium, or low.** \n\n\n```python\n# Part 1: Write a Python function to classify unemployment levels.\n\ndef unemployment_levels(ul):\n    if ul > 6.5:\n        return \"high\"\n    elif 4.5 < ul <= 6.5:\n    #elif ul < 6.5: #equivalent to the line above\n        return \"medium\"\n    else:\n        return \"low\"\n    \n    return ul\n```\n\n2. **Pass your function to `applymap` (quiz: why `applymap` and not `agg` or `apply`?) and save the result in a new DataFrame called `unemp_bins`.**  \n\n\n```python\n# Part 2: Pass your function from part 1 to applymap\n#Apply map allows to apply a function that takes a scalar and returns a scalar to a dataframe\n\nunemp_bins = unemp.applymap(unemployment_levels) #replace this comment with your code!!\nunemp_bins.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>state</th>\n      <th>Arizona</th>\n      <th>California</th>\n      <th>Florida</th>\n      <th>Illinois</th>\n      <th>Michigan</th>\n      <th>New York</th>\n      <th>Texas</th>\n    </tr>\n    <tr>\n      <th>Date</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>2000-01-01</td>\n      <td>low</td>\n      <td>medium</td>\n      <td>low</td>\n      <td>low</td>\n      <td>low</td>\n      <td>medium</td>\n      <td>medium</td>\n    </tr>\n    <tr>\n      <td>2000-02-01</td>\n      <td>low</td>\n      <td>medium</td>\n      <td>low</td>\n      <td>low</td>\n      <td>low</td>\n      <td>medium</td>\n      <td>medium</td>\n    </tr>\n    <tr>\n      <td>2000-03-01</td>\n      <td>low</td>\n      <td>medium</td>\n      <td>low</td>\n      <td>low</td>\n      <td>low</td>\n      <td>medium</td>\n      <td>low</td>\n    </tr>\n    <tr>\n      <td>2000-04-01</td>\n      <td>low</td>\n      <td>medium</td>\n      <td>low</td>\n      <td>low</td>\n      <td>low</td>\n      <td>medium</td>\n      <td>low</td>\n    </tr>\n    <tr>\n      <td>2000-05-01</td>\n      <td>low</td>\n      <td>medium</td>\n      <td>low</td>\n      <td>low</td>\n      <td>low</td>\n      <td>medium</td>\n      <td>low</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n   3. **(Challenging) Use another transform on `unemp_bins` to count how many times each state had each of the three classifications.**\n    - Hint 1: Will this value counting function be a Series or scalar transform?  \n    - Hint 2: Try googling \"pandas count unique value\" or something similar to find the right transform.  \n \n\n\n```python\n# Part 3: Count the number of times each state had each classification.\n\n# we count the number of times each state had each classification. \ndef count_bins(cb):\n    var = cb.value_counts()   \n    return var\n\nunemp_count = unemp_bins.apply(count_bins)\nunemp_count\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>state</th>\n      <th>Arizona</th>\n      <th>California</th>\n      <th>Florida</th>\n      <th>Illinois</th>\n      <th>Michigan</th>\n      <th>New York</th>\n      <th>Texas</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>high</td>\n      <td>75</td>\n      <td>106</td>\n      <td>68</td>\n      <td>91</td>\n      <td>142</td>\n      <td>65</td>\n      <td>51</td>\n    </tr>\n    <tr>\n      <td>low</td>\n      <td>44</td>\n      <td>4</td>\n      <td>69</td>\n      <td>19</td>\n      <td>17</td>\n      <td>22</td>\n      <td>58</td>\n    </tr>\n    <tr>\n      <td>medium</td>\n      <td>97</td>\n      <td>106</td>\n      <td>79</td>\n      <td>106</td>\n      <td>57</td>\n      <td>129</td>\n      <td>107</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# alternative solution: value_counts is a series function (columns) so I loop over columns to have the frequencies for each states, then append each series\nunemp_freq_cat = pd.DataFrame()\nfor iter in unemp_bins.columns:\n    series=unemp_bins[iter].value_counts()\n    unemp_freq_cat=unemp_freq_cat.append(series)\nunemp_freq_cat=unemp_freq_cat[['low', 'medium', 'high']]\n# We can transpose the table to make it more readable, matter of preferences\nunemp_freq_catT=unemp_freq_cat.T\nunemp_freq_catT\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Arizona</th>\n      <th>California</th>\n      <th>Florida</th>\n      <th>Illinois</th>\n      <th>Michigan</th>\n      <th>New York</th>\n      <th>Texas</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>low</td>\n      <td>44.0</td>\n      <td>4.0</td>\n      <td>69.0</td>\n      <td>19.0</td>\n      <td>17.0</td>\n      <td>22.0</td>\n      <td>58.0</td>\n    </tr>\n    <tr>\n      <td>medium</td>\n      <td>97.0</td>\n      <td>106.0</td>\n      <td>79.0</td>\n      <td>106.0</td>\n      <td>57.0</td>\n      <td>129.0</td>\n      <td>107.0</td>\n    </tr>\n    <tr>\n      <td>high</td>\n      <td>75.0</td>\n      <td>106.0</td>\n      <td>68.0</td>\n      <td>91.0</td>\n      <td>142.0</td>\n      <td>65.0</td>\n      <td>51.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n4. **Construct a horizontal bar chart of the number of occurrences of each level with one bar per state and classification (21 total bars).** \n\n\n```python\n## then make a horizontal bar chart here\nunemp_count.T.plot.barh(figsize=(8,8))\nunemp_count.plot.barh(figsize=(8,8))\n```\n\n5. **(Challenging) Repeat the previous step, but count how many states had each classification in each month. Which month had the most states with high unemployment? What about medium and low?**  \n\n\n```python\n# Part 4: Apply the same transform from part 4, but to each date instead of to each state.\n\n#a solution based on this lecture has not been found :p\n#alternative solution: we transpose the previous table in order to be able to apply the same function as before \n    #for more informtion on reshaping the DataFrames, check Lecture 6\nunemp_binsT = unemp_bins.T\nunemp_binsT\n\n#we call the function previously created for the transposed DataFrame\nunemp_countT = unemp_binsT.apply(count_bins)\nunemp_countT.T.head()\n\n#we create a for loop to answer the question\ntimes = [\"high\", \"medium\", \"low\"]\n\nfor x in times:\n    m=unemp_countT.T[x].idxmax()\n    \n    print(f\"The month with {x} unemployment is {m}.\")\n```\n\n    The month with high unemployment is 2009-04-01 00:00:00.\n    The month with medium unemployment is 2001-09-01 00:00:00.\n    The month with low unemployment is 2000-08-01 00:00:00.\n\n\n## Exercise 4\n\n1. **For a single state of your choice, determine what the mean unemployment is during \"Low\", \"Medium\", and \"High\" unemployment times (recall your `unemp_bins` DataFrame from the exercise above).**\n    - Think about how you would do this for all the states in our sample and write your thoughts... We will soon learn tools that will *greatly* simplify operations like this that operate on distinct *groups* of data at a time.  \n\n\n```python\n#The analysis is performed on Arizona\n\ntimes = [\"high\", \"medium\", \"low\"]\n\nfor x in times:\n    Arizona_x  = unemp[\"Arizona\"].loc[unemp_bins[\"Arizona\"]==x].mean()\n\n    print(f\"During {x} unemployment times, the mean unemployment in Arizona is {Arizona_x}.\")\n```\n\n    During high unemployment times, the mean unemployment in Arizona is 8.73333333333333.\n    During medium unemployment times, the mean unemployment in Arizona is 5.436082474226807.\n    During low unemployment times, the mean unemployment in Arizona is 4.0636363636363635.\n\n\n\n```python\n#Alternative solution:\n\n# I chose Arizona. I extract both values and bin series, rename them and concatenate it into an new data frame.\nArizona_bins=pd.Series(unemp_bins['Arizona'], name='Arizona_Bins')\nArizona_val=pd.Series(unemp['Arizona'], name='Arizona_Values')\nArizona_valbins = pd.concat([Arizona_bins, Arizona_val], axis=1)\nArizona_valbins.head()\nArizona_valbins.groupby('Arizona_Bins')['Arizona_Values'].mean()\n```\n\n\n\n\n    Arizona_Bins\n    high      8.733333\n    low       4.063636\n    medium    5.436082\n    Name: Arizona_Values, dtype: float64\n\n\n\n\n```python\n#Now, we perform the same analysis on all countries\n\nstates = [\"Arizona\", \"California\", \"Florida\", \"Illinois\",\n          \"Michigan\", \"New York\", \"Texas\"]\n\nfor y in states:\n    for x in times:\n        y_x  = unemp[y].loc[unemp_bins[y]==x].mean()\n\n        print(f\"{y} - {x}: {y_x}.\")\n```\n\n    Arizona - high: 8.73333333333333.\n    Arizona - medium: 5.436082474226807.\n    Arizona - low: 4.0636363636363635.\n    California - high: 9.249056603773582.\n    California - medium: 5.454716981132074.\n    California - low: 4.5.\n    Florida - high: 9.155882352941177.\n    Florida - medium: 5.331645569620254.\n    Florida - low: 3.807246376811594.\n    Illinois - high: 8.740659340659343.\n    Illinois - medium: 5.618867924528302.\n    Illinois - low: 4.35263157894737.\n    Michigan - high: 8.76267605633803.\n    Michigan - medium: 5.4070175438596495.\n    Michigan - low: 3.8764705882352946.\n    New York - high: 8.16923076923077.\n    New York - medium: 5.3612403100775206.\n    New York - low: 4.340909090909091.\n    Texas - high: 7.552941176470585.\n    Texas - medium: 5.567289719626171.\n    Texas - low: 4.298275862068967.\n\n\n2. **Which states in our sample performs the best during \"bad times?\" To determine this, compute the mean unemployment for each state only for months in which the mean unemployment rate in our sample is greater than 7.**  \n\n\n```python\n# Between bracket, the condition that the value is greater than 7\ndf=unemp[unemp>7].mean()\ndf=df.loc[df==min(df)]\ndf\n# There must be a way to be more concise\n```\n\n\n\n\n    state\n    Texas    7.972727\n    dtype: float64\n\n\n\n\n```python\n#Alternative solution\ndef unemployment_levels2(ul2):\n    if ul2 > 7:\n        return \"High\"\n    else:\n        return \"Low\"\n    \n    return ul2\n\nunemp_bins2 = unemp.applymap(unemployment_levels2)\n\nfor s in states:\n    s_high  = unemp[s].loc[unemp_bins2[s]==\"High\"].mean()\n     \n    print(f\"{s}: {s_high}\")\n    \n#The 3 states that perform the best during high unemployment times (>7) are, in ascending order, Texas, New York, Arizona\n```\n\n    Arizona: 9.038461538461535\n    California: 10.234210526315788\n    Florida: 9.568965517241377\n    Illinois: 9.423529411764704\n    Michigan: 9.465384615384618\n    New York: 8.286666666666667\n    Texas: 7.972727272727272\n\n", "meta": {"hexsha": "62eae16680e66d86548b2be806956379a66583de", "size": 92999, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Session_7/2_basics_exercises.ipynb", "max_stars_repo_name": "remi-sudo/Classes", "max_stars_repo_head_hexsha": "71497927ed4d54ddf6fd5abe2ddabb5966eb0304", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Session_7/2_basics_exercises.ipynb", "max_issues_repo_name": "remi-sudo/Classes", "max_issues_repo_head_hexsha": "71497927ed4d54ddf6fd5abe2ddabb5966eb0304", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Session_7/2_basics_exercises.ipynb", "max_forks_repo_name": "remi-sudo/Classes", "max_forks_repo_head_hexsha": "71497927ed4d54ddf6fd5abe2ddabb5966eb0304", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.0048176187, "max_line_length": 23636, "alphanum_fraction": 0.7030828288, "converted": true, "num_tokens": 8626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295497638851, "lm_q2_score": 0.06465348925734801, "lm_q1q2_score": 0.028805039959490443}}
{"text": "```python\n# File Authorship Information\n__author__ = \"\"\"Matteo Lulli, Luca Biferale, Giacomo Falcucci, \n                Mauro Sbragaglia and Xiaowen Shan\"\"\"\n__copyright__ = \"\"\"Copyright 2021, Matteo Lulli, Luca Biferale, \nGiacomo Falcucci, Mauro Sbragaglia and Xiaowen Shan, idea.deploy\"\"\"\n__license__ = \"\"\"Permission is hereby granted, free of charge, \nto any person obtaining a copy of this software and associated \ndocumentation files (the \"Software\"), to deal in the Software \nwithout restriction, including without limitation the rights to \nuse, copy, modify, merge, publish, distribute, sublicense, \nand/or sell copies of the Software, \nand to permit persons to whom the Software is furnished to do so, \nsubject to the following conditions:\nThe above copyright notice and this permission notice shall be \nincluded in all copies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, \nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES \nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND \nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT \nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, \nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER \nDEALINGS IN THE SOFTWARE.\"\"\"\n__maintainer__ = \"Matteo Lulli\"\n__email__ = \"matteo.lulli@gmail.com\"\n__status__ = \"Development\"\n```\n\n\n```python\n# Development cell\n%load_ext autoreload\n%autoreload 2\n```\n\n# Mesoscale Modelling of the Tolman Length in Multi-component Systems\n\nAuthors: Matteo Lulli (1), Luca Biferale (2), Giacomo Falcucci (3), Mauro Sbragaglia (2) and Xiaowen Shan (1)\n\n(1) Department of Mechanics and Aerospace Engineering, Southern University of Science and Technology, Shenzhen, Guangdong 518055, China\n\n(2) Department of Physics \\& INFN, University of Rome \\\"Tor Vergata\\\", Via della Ricerca Scientifica 1, 00133, Rome, Italy.\n\n(3) Department of Enterprise Engineering \\\"Mario Lucertini\\\", University of Rome \\\"Tor Vergata\\\", Via del Politecnico 1, 00133 Rome, Italy; John A. Paulson School of Engineering and Applied Physics, *Harvard University*,  33 Oxford Street, 02138 Cambridge, Massachusetts, USA.\n\n**Abstract:**\n\nIn this paper we analyze the curvature corrections to the surface tension in the context of the Shan-Chen (SC) multi-component Lattice Boltzmann method (LBM). We demonstrate that the same techniques recently applied in the context of the Shan-Chen multi-phase model can be applied to multi-component mixtures. We implement, as a new application, the calculation of the surface of tension radius $R_s$ through the minimization of the generalized surface tension $\\sigma[R]$. In turn we are able to estimate the Tolman length, i.e. the first order coefficient of the curvature expansion of the surface tension $\\sigma(R)$, as well as the higher order corrections, i.e. the curvature- and the Gaussian-rigidity coefficients. The SC multi-component model allows to model both fully-symmetric as well as asymmetric interactions among the components. By performing an extensive set of simulations we present a first example of tunable Tolman length in the mesoscopic model, being zero for symmetric interactions and different from zero otherwise. This result paves the way for controlling such interface properties which are paramount in presence of thermal fluctuations. All reported results can be independently reproduced through the ``idea.deploy'' framework available at [https://github.com/lullimat/idea.deploy](https://github.com/lullimat/idea.deploy).\n\n# Reproducibility\n\nThis document is intended for those interested readers who want to reproduce the results reported in the paper entitled \"Mesoscale Modelling of the Tolman Length in Multi-component Systems\". In the present case the computational resources needed should be available in general, although the netire set of simulations takes a time of the order of weeks on NVIDIA P100 cards. This time can considerably be shortened when discarding the simulations of the largest droplest for $L=301$. \n\nNext development steps will include a class to measure the time required by each cell and output it in a .json file which can be sent to [matteo.lulli@gmail.com](mailto:matteo.lulli@gmail.com) so that average execution times will be availble and organized according to the hardware.\n\nEach subsection can be executed independently and reproduce the results which will be stored locally in the directory 'reproduced-data', so that the data will be generated only once.\n\nPlots can also be generated using the same scripts employed for the figures of the paper. Since there are some issues in executing these scripts in the Jupyter environment we include them as separated files which are called from the cells themselves. **In order to reproduce the plots a working 'latex' installation is necessary to be present on the system.**\n\nThis file will be kept updated for new local features and developments in the parent project [**idea.deploy**](https://github.com/lullimat/idea.deploy)\n\nThis file is supposed to be pulled from the repository [https://github.com/lullimat/MesoscaleTolmanMC](https://github.com/lullimat/MesoscaleTolmanMC), from within the \"papers\" directory the idea.deploy project.\n\n**IMPORTANT NOTICE**\n\n**At the present moment this Jupyter notebook has only been tested on the 'devel' branch of the 'idea.deploy' framework. In order to switch branch please go in the root directory of the project from a terminal and type ```git checkout devel```, after which this notebook should be working properly. The repository shall be working on the 'master' branch after the peer-review process is completed.**\n\n**All the scripts in this notebook have been tested with a maximum memory usage of 8GB for the GPU, 64-bits floating point variables and a maximum value for $L$ of at least 213. If you desire to study a different a range of paramters because of hardware limitations feel free to modify the scripts below, especially for the plots.**\n\n# Paper Results\nUsing the next subsections/cells it is possible to reproduce all the results and plots reported in the paper.\n\n## Simulations: Hardware Selection\nIn the following cells you are required to make a choice for the hardware to employ for the simulations. At the moment you need to stick to a given choice in order to visualize all the results. A more elastic management will be provided in future releases.\n\n**These are the only cells in the notebook that have a \"global\" character, i.e. they are needed by the rest of the notebook for the simulations cell to run.**\n\nBy executing (shift-enter) the cell below, the hardware present in your system will be listed\n\n\n```python\n# Display Hardware (click the arrow to unfold)\nimport sys\nsys.path.append(\"../../\")\n\nfrom idpy.IdpyCode import IdpyHardware\n\nIdpyHardware()\n```\n\n\n```python\n# Language imports (click on left arrow to unfold)\nimport sys\nsys.path.append(\"../../\")\n\nfrom idpy.IdpyCode import CUDA_T, OCL_T, idpy_langs_sys\n```\n\n\n```python\npreferred_lang, preferred_device, preferred_kind = CUDA_T, 0, \"gpu\"\n```\n\n### One-dimensional interfaces\n\n\n```python\n# Simulations (click on left arrow to unfold)\n\nimport sympy as sp\nimport numpy as np\n\nfrom LBM_proxy import CheckCenterOfMassDeltaPConvergence\n\nfrom TolmanSimulations import TolmanSimulationsMC, TolmanSimulationsFlatMC\nfrom TolmanSimulations import Gcs\n\nfrom TolmanSimulations import LatticePressureTensorMC, SurfaceOfTensionMC\nfrom idpy.LBM.LBM import XIStencils, FStencils, IndexFromPos\nfrom idpy.LBM.LBM import CheckUConvergence, ComputeCenterOfMass\n\nfrom idpy.Utils.SimpleTiming import SimpleTiming\n_s_timing = SimpleTiming()\n\nobs_list = ['sigma_flat', 'p_n_minus_t_spl', 'p_n', 'p_t',\n            'p_n_spl', 'p_t_spl', 'z_fine', \n            'n_field_0', 'n_field_1', \n            'f_stencils', 'psi_syms', 'Gs']\n\nn = sp.Symbol('n')\npsis = [sp.exp(-1/n), 1 - sp.exp(-n), n]\npsi_codes = {psis[0]: 'exp((NType)(-1./ln))', \n             psis[1]: '1. - exp(-(NType)ln)', \n             n: 'ln'}\n\nfrom pathlib import Path\nreproduced_results = Path(\"reproduced-results\")\nif not reproduced_results.is_dir():\n    reproduced_results.mkdir()\n\nfrom collections import defaultdict\nanalysis_results_flat = defaultdict( # _Gs_i\n    lambda: defaultdict(dict) # obs\n)\n\n_n_sum_list = [1.92 + 0.12]\n_G = 1.5/3\n\n_delta_GAB_list = np.array([0, 0.04, 0.08, 0.16, 0.24, 0.32, 0.40, 0.48, 0.56, 0.64, 0.72, 0.80, 0.88])\n_delta_GAB_list = np.sort(np.append(_delta_GAB_list, -_delta_GAB_list[1:]))\nprint(_delta_GAB_list)\n\n\n_Gs_list = \\\n    [\n            [[Gcs[psis[0]] * (1 - 0.4 * (1 + _delta_GAB)), _G], \n             [_G, Gcs[psis[0]] * (1 - 0.4)]] for _delta_GAB in _delta_GAB_list \n    ]\n\n_psi_codes = {}\n_psi_codes = [[psi_codes[psis[0]], psi_codes[n]], \n              [psi_codes[n], psi_codes[psis[0]]]]\n\n_psi_syms = [[psis[0], n], [n, psis[0]]]\n\n_f_stencils_dict = [[FStencils['D3E4'], FStencils['D3E4']],\n                    [FStencils['D3E4'], FStencils['D3E4']]]\n\n_s_timing.Start()\nfor _n_sum in _n_sum_list:\n    for _Gs_i in range(len(_Gs_list)):\n        '''\n        Preparing analysis results structure\n        '''\n        for _obs in obs_list:\n            analysis_results_flat[_Gs_i][_obs] = []\n            \n        print(\"Flat Interface Simulation\", _Gs_i)\n\n        simulations_params = {'dim_sizes': (127, 5, 5),\n                              'n_components': 2, \n                              'f_stencils': _f_stencils_dict,\n                              'n_sum': _n_sum,\n                              'psi_syms' : _psi_syms,\n                              'psi_codes': _psi_codes,\n                              'SC_Gs': _Gs_list[_Gs_i], \n                              'taus': [1., 1.],                       \n                              'lang': preferred_lang,\n                              'cl_kind': preferred_kind, \n                              'device': preferred_device, \n                              'data_dir': reproduced_results}\n        \n        for _param in ['SC_Gs']:\n            print(simulations_params[_param])\n\n        _ts_test = TolmanSimulationsFlatMC(**simulations_params)\n\n        _did_run = _ts_test.Simulate()\n        \n        _swap_out = _ts_test.GetFlatSigma()\n        for _obs in _swap_out:\n            analysis_results_flat[_Gs_i][_obs] += [_swap_out[_obs]]\n\n        _ts_test.End()\n\n        print()\n        print()\n        \n        \n'''\nCreating numpy arrays for the data analysis\n'''\nfor _Gs_i in analysis_results_flat:\n    for _obs in obs_list:\n        analysis_results_flat[_Gs_i][_obs] = \\\n            np.array(analysis_results_flat[_Gs_i][_obs])\n        \n_s_timing.End()\n_s_timing.PrintElapsedTime()\n```\n\n### Droplets\n\n\n```python\n# Cell printing the estimated allocated memory size in (MB) for the simulations (click on left arrow to unfold)\ndef MemoryEstimateMB(_L, _dim = 3, _Q = 19):\n    _V = _L ** _dim\n    _U_V = _dim * _V\n    _Pop_V = _Q * _V\n    _Psi_V, _N_V = _V, _V\n    _memory = _Psi_V * 2 + _N_V * 3 + _U_V * 3 + _Pop_V * 3\n    _memory *= 8\n    return _memory / 2 ** 20\n\nprint(\"Estimated simulation sizes in MB:\")\n_Ls_unique = [25, 31, 37, 41, 51, 57, 65, 97, 127, 151, 213, 301]\nfor _L in _Ls_unique:\n    print(\"L:\", _L, \"Size:\", \"{:.1f}\".format(MemoryEstimateMB(_L)), \"(MB)\")\n```\n\nIn the cell below we set the range memory usage (i.e. ```_M_min, _M_max```) and the number of values of the asymmetry paramter $\\delta G_{AB}$ (i.e. ```_Gs_slice```). For ```_Gs_slice``` one should use the ```slice``` class. \n\nThe full set of simulations can be obtained by setting ```_M_min, _M_max = 0, 2**14``` and ```_Gs_slice = slice(0, -1, 1)```\n\n\n```python\n_M_min, _M_max = 0, 2**13\n_Gs_slice = slice(0, 1, 1)\n```\n\nBelow we list the time needed for the set of simulations involving only one value of $\\delta G_{AB}$ (e.g. ```_Gs_slice = slice(0, 1, 1)```) with the system size limited to $L \\leq 213$ (i.e. ```_M_min, _M_max = 0, 2**13```)\n\n*Flat interfaces already simulated in Sec. 3.1.1*\n\n**0 d,  4 h,  49 m,  19 s, CUDA, Tesla P100-PCIE-16GB, Intel(R) Xeon(R) CPU E5-2620 v4 @ 2.10GHz**\n\nIn order to create the plots in Sec. 3.2, 3.3 and 3.4 it is necessaryo to execute the cell below first.\n\n\n```python\n# Simulations (click the arrow on the left to unfold)\n\nimport sympy as sp\nimport numpy as np\n\nfrom LBM_proxy import CheckCenterOfMassDeltaPConvergence\n\nfrom TolmanSimulations import TolmanSimulationsMC, TolmanSimulationsFlatMC\nfrom TolmanSimulations import Gcs\n\nfrom TolmanSimulations import LatticePressureTensorMC, SurfaceOfTensionMC\nfrom idpy.LBM.LBM import XIStencils, FStencils, IndexFromPos\nfrom idpy.LBM.LBM import CheckUConvergence, ComputeCenterOfMass\n\nfrom idpy.Utils.SimpleTiming import SimpleTiming\n_s_timing = SimpleTiming()\n\nobs_list = ['delta_p', 'radial_pt_spl', 'radial_pn_spl', 'delta_p_st',\n            'sigma_4.217', 'Rs_4.217', 'st_spl_4.217', 'r_fine_4.217', 'L']\n\nn = sp.Symbol('n')\npsis = [sp.exp(-1/n), 1 - sp.exp(-n), n]\npsi_codes = {psis[0]: 'exp((NType)(-1./ln))', \n             psis[1]: '1. - exp(-(NType)ln)', \n             n: 'ln'}\n\nfrom pathlib import Path\nreproduced_results = Path(\"reproduced-results\")\nif not reproduced_results.is_dir():\n    reproduced_results.mkdir()\n\nfrom collections import defaultdict\nanalysis_results = defaultdict( # _Gs_i\n    lambda: defaultdict( # 'A'/'B'\n        lambda: defaultdict(dict) # obs\n    )\n)\n\n# 301\n_Ls_list = [25, 31, 37, 41, 51, 57, 65, 97, 127, 151, 213, 301]\n\n_Ls_list_swap = []\nfor _L in _Ls_list:\n    if MemoryEstimateMB(_L) >= _M_min and MemoryEstimateMB(_L) < _M_max:\n        _Ls_list_swap += [_L]\n_Ls_list = _Ls_list_swap.copy()\nprint(_Ls_list)\n\n_n_sum_list = [1.92 + 0.12]\n_G = 1.5/3\n\n\n_delta_GAB_list = np.array([0, 0.04, 0.08, 0.16, 0.24, 0.32, 0.40, 0.48, 0.56, 0.64, 0.72, 0.80, 0.88])\n_delta_GAB_list = np.sort(np.append(_delta_GAB_list, -_delta_GAB_list[1:]))\nprint(_delta_GAB_list)\n\n\n_Gs_list = \\\n    [\n            [[Gcs[psis[0]] * (1 - 0.4 * (1 + _delta_GAB)), _G], \n             [_G, Gcs[psis[0]] * (1 - 0.4)]] for _delta_GAB in _delta_GAB_list \n    ]\n\n_psi_codes = {}\n_psi_codes = [[psi_codes[psis[0]], psi_codes[n]], \n              [psi_codes[n], psi_codes[psis[0]]]]\n\n_psi_syms = [[psis[0], n], [n, psis[0]]]\n\n_f_stencils_dict = [[FStencils['D3E4'], FStencils['D3E4']],\n                    [FStencils['D3E4'], FStencils['D3E4']]]\n\n\n_s_timing.Start()\n\nfor _n_sum in _n_sum_list:\n    for _Gs_i in range(len(_Gs_list))[_Gs_slice]:\n        for _type in ['A', 'B']:\n            '''\n            Preparing analysis results structure\n            '''\n            for _obs in obs_list:\n                analysis_results[_Gs_i][_type][_obs] = []\n\n            for _L in _Ls_list:\n                simulations_params = {'dim_sizes': (_L, _L, _L),\n                                      'n_components': 2, \n                                      'f_stencils': _f_stencils_dict,\n                                      'n_sum': _n_sum,\n                                      'psi_syms' : _psi_syms,\n                                      'psi_codes': _psi_codes,\n                                      'R': _L/4, 'type': _type,\n                                      'SC_Gs': _Gs_list[_Gs_i], \n                                      'taus': [1., 1.],                       \n                                      'lang': preferred_lang,\n                                      'cl_kind': preferred_kind, \n                                      'device': preferred_device, \n                                      'data_dir': reproduced_results, \n                                      'flat_sim_cache': True}\n\n                _ts_test = TolmanSimulationsMC(**simulations_params)\n\n                _did_run = _ts_test.Simulate(override_flag = False)\n                \n                if _did_run not in ['burst', 'center']:\n                    print(_Gs_i, _type)\n                    '''\n                    System size\n                    '''\n                    analysis_results[_Gs_i][_type]['L'] += [_L]\n                    '''\n                    Delta p\n                    '''\n                    _swap_out = _ts_test.GetDataDeltaP()\n                    for obs in _swap_out:\n                        analysis_results[_Gs_i][_type][obs] += [_swap_out[obs]]\n                    '''\n                    Surface Of Tension Radius\n                    '''\n                    SR = SurfaceOfTensionMC(**_ts_test.GetDataSurfaceOfTension())\n                    _swap_out = SR.GetSurfaceTension()\n                    for obs in _swap_out:\n                        analysis_results[_Gs_i][_type][obs] += [_swap_out[obs]]\n\n                _ts_test.End()\n                print()\n            '''\n            End _type loop\n            '''\n            print()\n        '''\n        End _Gs loop\n        '''\n        \n        \n'''\nCreating numpy arrays for the data analysis\n'''\nfor _Gs_i in analysis_results:\n    for _type in analysis_results[_Gs_i]:\n        for _obs in obs_list:\n            analysis_results[_Gs_i][_type][_obs] = \\\n                np.array(analysis_results[_Gs_i][_type][_obs])\n            \n            \n_s_timing.End()\n_s_timing.PrintElapsedTime()\n```\n\n## Figure 2\n\n\n```python\n# Figure 2 script (click the arrow on the left to unfold)\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc, rcParams\nrc('font',**{'family':'STIXGeneral'})\nrc('mathtext', **{'fontset': 'stix'})\nrc('text', usetex=True)\n\nrcParams['text.latex.preamble']=[r\"\\usepackage{amsmath, sourcesanspro}\"]\n\n_fs, _ms_small, _ms_large, _ms_large_c = 20, 9, 12, 20\n\n_l_fs = 17\n\nrc('legend', fontsize = _l_fs)\n\nfrom pathlib import Path\nreproduced_figures = Path(\"reproduced-figures\")\nif not reproduced_figures.is_dir():\n    reproduced_figures.mkdir()\n    \n_cmap = matplotlib.colors.LinearSegmentedColormap.from_list(\"MyCmapName\",[\"r\",\"b\"])\n\n_Gs_len = len(_Gs_list[_Gs_slice])\n\n_sym_i = _Gs_len//2\nprint(\"Symmetric index:\", _sym_i)\n\n_Gs_i_range = range(_Gs_len)\n#_Gs_i_range = [1, 8, 15]\n_Gs_AA_list = np.array([abs(_Gs_list[_][0][0]) for _ in _Gs_i_range])\n##_delta_Gs = np.array([1 - (1 - _Gs_list[_Gs_i][0][0] / Gcs[psis[0]]) / 0.4 for _Gs_i in _Gs_i_range])\n_delta_Gs = np.array([(1 - _Gs_list[_Gs_i][0][0] / Gcs[psis[0]]) / 0.4 - 1 for _Gs_i in _Gs_i_range])\n\n_Gs_col_norm = matplotlib.colors.LogNorm(vmin = np.amin(_Gs_AA_list), \n                                         vmax = np.amax(_Gs_AA_list))\n\nfig = plt.figure(figsize = (8.3, 13))\n\n######### Generalized surface tension\n_panel_str = '$(a)$'\n_ax_gen_sigma = plt.subplot2grid((2, 1), (0, 0), colspan = 1, rowspan = 1)\n_x_range = [0.56,2]\nif True:\n    _ii = 0\n    for _i in _Gs_i_range:\n        _color = _cmap(_Gs_col_norm(abs(_Gs_list[_i][0][0])))\n\n        for _type in ['A', 'B']:\n            _every_L = 5\n            for _k in range(len(analysis_results[_i][_type]['r_fine_4.217']))[::_every_L]:\n                _swap_Rs_4p217 = analysis_results[_i][_type]['Rs_4.217'][_k]\n                _swap_sigma_4p217 = analysis_results[_i][_type]['sigma_4.217'][_k]\n\n                _swap_r = \\\n                    np.linspace(_swap_Rs_4p217 * _x_range[0], \n                                _swap_Rs_4p217 * _x_range[1], 149) + \\\n                    _ii * _swap_Rs_4p217 * (_x_range[1] - _x_range[0]) / 149\n\n                _swap_st = analysis_results[_i][_type]['st_spl_4.217'][_k](_swap_r)\n\n                _freq = 128 + 64 + 16 + 16\n                _ax_gen_sigma.plot(_swap_r[0::_freq]/_swap_Rs_4p217, \n                                   _swap_st[0::_freq]/_swap_sigma_4p217, \n                                   'o', \n                                   color = _color, markersize = _ms_large,\n                                   fillstyle = 'none' if _type == 'B' else 'full')\n                ##print(_ii)\n                _ii += 1\n\n    _r_u = np.linspace(0.2, 3, 2 ** 8)\n    _ax_gen_sigma.plot(_r_u, 1 + ((1 - 1/_r_u) ** 2) * (1 + 2 * _r_u) / 3, \n                       label = 'Integrated generalized Laplace law: \\\n                       $\\\\frac{\\\\sigma\\\\left[R\\\\right]}{\\\\sigma_{s}}=\\\\frac{1}{3}\\\\left(\\\\frac{R_{s}}{R}\\\\right)^{2}+\\\\frac{2}{3}\\\\frac{R}{R_{s}}$', color = 'orange', \n                       linestyle = '-.', linewidth = 4)\n\n    _ax_gen_sigma.axhline(y = 1, color = 'black', linestyle = '-.', linewidth = 0.85)\n    _ax_gen_sigma.axvline(x = 1, ymin = (1 - 0.85)/(2 - 0.85), ymax = 1, \n                          color = 'black', linestyle = '-.', linewidth = 0.85)\n\n    _ax_gen_sigma.text(0.015, 0.925, _panel_str, transform = _ax_gen_sigma.transAxes, fontsize=_fs)\n\n    ##_ax_gen_sigma.plot(_r_fine/_Rs, 1 / ((_r_fine/_Rs) ** 2) / 3 + 2 * (_r_fine/_Rs) / 3)\n\n    _ax_gen_sigma.set_xlabel('$R/R_s$', fontsize = _fs)\n    _ax_gen_sigma.set_ylabel('$\\sigma[R]/\\sigma_s$', fontsize = _fs)\n\n    _ax_gen_sigma.set_xlim(_x_range)\n    _ax_gen_sigma.set_ylim([0.85,1.6])\n\n    for tick in _ax_gen_sigma.xaxis.get_major_ticks():\n        tick.label.set_fontsize(_fs)\n\n    for tick in _ax_gen_sigma.yaxis.get_major_ticks():\n        tick.label.set_fontsize(_fs)\n\n    lgnd_points = _ax_gen_sigma.legend(frameon = False, loc = 'lower right')\n\n######### Laplace Law\n_panel_str = '$(b)$'\n_ax_laplace = plt.subplot2grid((2, 1), (1, 0), colspan = 1, rowspan = 1)\n\n\n_symbols_dict = {0: 'o', _sym_i: 's', _Gs_len - 1: '^'}\n#for _i in [15, 1, 8]:\nfor _i in [0, _sym_i, _Gs_len - 1]:\n    _color = _cmap(_Gs_col_norm(abs(_Gs_list[_i][0][0])))\n\n    _rm1_A = 1 / analysis_results[_i]['A']['Rs_4.217']\n    plt.plot(_rm1_A, \n             analysis_results[_i]['A']['delta_p_st'], _symbols_dict[_i], \n             color = _color, markersize = _ms_small,\n             fillstyle = 'full', label = '$\\delta G_{AB} = ' + (\"%.02f\" % _delta_Gs[_i]) + '$')\n\n    _rm1_B = -1 / analysis_results[_i]['B']['Rs_4.217']\n    plt.plot(_rm1_B, \n             analysis_results[_i]['B']['delta_p_st'], _symbols_dict[_i], \n             color = _color, markersize = _ms_small,\n             fillstyle = 'none')\n    \n    _sigma_flat = analysis_results_flat[_i]['sigma_flat'][0]\n    _rm1_fine_A = np.linspace(0, np.amax(_rm1_A), 2 ** 7)\n    _ax_laplace.plot(_rm1_fine_A, \n                     + 2 * _sigma_flat * _rm1_fine_A, \n                     '--', color = _color)\n\n    _rm1_fine_B = np.linspace(np.amin(_rm1_B), 0, 2 ** 7)\n    _ax_laplace.plot(_rm1_fine_B, \n                     - 2 * _sigma_flat * _rm1_fine_B, \n                     '--', color = _color)\n    \n_ax_laplace.set_xlabel('$R_s^{-1}$', fontsize = _fs)\n_ax_laplace.set_ylabel('$\\Delta P$', fontsize = _fs)\n\n_ax_laplace.axvline(x = 0, color = 'black', linestyle = '-.', linewidth = 0.5)\n_ax_laplace.text(0.075, 0.125, 'B-droplets', transform = _ax_laplace.transAxes, fontsize = _fs)\n_ax_laplace.text(0.725, 0.125, 'A-droplets', transform = _ax_laplace.transAxes, fontsize = _fs)\n_ax_laplace.text(0.015, 0.925, _panel_str, transform = _ax_laplace.transAxes, fontsize=_fs)\n\n\nfor tick in _ax_laplace.xaxis.get_major_ticks():\n    tick.label.set_fontsize(_fs)\n\nfor tick in _ax_laplace.yaxis.get_major_ticks():\n    tick.label.set_fontsize(_fs)\n\nlgnd_points = _ax_laplace.legend(frameon = True, loc = 'upper center', \n                                 bbox_transform = _ax_laplace.transAxes, \n                                 bbox_to_anchor = (0.3,1))\n\n_ax_laplace.set_ylim([0., 0.085])\n\n#for _handle in lgnd_points.legendHandles:\n#    _handle._legmarker.set_color('black')\n\nplt.savefig(reproduced_figures / 'figure_gensigma_laplace.pdf', bbox_inches = 'tight', dpi = 200)\n```\n\n## Figure 3\n\n### Analysis Block\n\n\n```python\n# Analysis for Figures 3 & 4 (click the arrow on the left to unfold)\n\nfrom scipy import interpolate, optimize\n\n_fit_obs_list = ['first_order', 'second_order', 'sigma_0']\n\n_delta_fit_res = defaultdict(dict)\nfor _obs in _fit_obs_list:\n    _delta_fit_res[_obs] = []\n    \n_Gs_len = len(_Gs_list[_Gs_slice])\n_Gs_i_range = range(_Gs_len)\n    \n_k = 0\nfor _i in _Gs_i_range:\n    '''\n    The aim is to interpolate the data first and then to fit them\n    - from the interpolation we get a first estimate of the flat surface tension and of \\delta\n    - we use the results of the interpolation to inform the fits\n    - We should use a third order polynomial for the fits this time (compare with lit.)\n    '''\n    _Rsm1_A = 1 / analysis_results[_i]['A']['Rs_4.217']\n    _Rsm1_B = -1 / analysis_results[_i]['B']['Rs_4.217']\n    _Rs_A = analysis_results[_i]['A']['Rs_4.217']\n    _Rs_B = analysis_results[_i]['B']['Rs_4.217']\n    _delta_p_sigma_s_A = _Rs_A * analysis_results[_i]['A']['delta_p_st'] / 2\n    _delta_p_sigma_s_B = _Rs_B * analysis_results[_i]['B']['delta_p_st'] / 2\n\n    _swap_sigma_0 = analysis_results_flat[_i]['sigma_flat']\n    if True:\n        _rm1_data = np.append(_Rsm1_B, np.append(_Rsm1_A, [0]))\n        _delta_p_sigma_s_data = np.append(_delta_p_sigma_s_B, np.append(_delta_p_sigma_s_A, [_swap_sigma_0]))\n    else:\n        _rm1_data = np.append(_Rsm1_B, _Rsm1_A)\n        _delta_p_sigma_s_data = np.append(_delta_p_sigma_s_B, _delta_p_sigma_s_A)\n\n    '''\n    Interpolation\n    '''\n    _sorted_args = np.argsort(_rm1_data)\n    _rm1_data = _rm1_data[_sorted_args]\n    _delta_p_sigma_s_data = _delta_p_sigma_s_data[_sorted_args]\n\n    _delta_p_sigma_s_spl = interpolate.UnivariateSpline(_rm1_data, \n                                                        _delta_p_sigma_s_data, \n                                                        k = 5, s = 0)\n    _sigma_0_data = _delta_p_sigma_s_spl(0)\n    print(_swap_sigma_0, _sigma_0_data)\n    \n    _swap_d0 = _delta_p_sigma_s_spl(0)\n    _swap_d1 = _delta_p_sigma_s_spl.derivative(1)(0)\n    _swap_d2 = _delta_p_sigma_s_spl.derivative(2)(0)\n    _swap_d3 = _delta_p_sigma_s_spl.derivative(3)(0)\n    _swap_d4 = _delta_p_sigma_s_spl.derivative(4)(0)\n\n    '''\n    Linear Fits\n    '''\n    _fit_range = [-0.075, 0.075]\n    #_fit_range = [-0.09, 0.09]\n    _fit_cut_index = np.where((_rm1_data > _fit_range[0]) & (_rm1_data < _fit_range[1]))\n\n    _fit_range_shrink = 1 - 0.1\n    _rm1_fine_fit = np.linspace(_fit_range[0] * _fit_range_shrink, \n                                _fit_range[1] * _fit_range_shrink, \n                                2 ** 10)\n\n    _fit_range_enlarge = 2.2\n    _rm1_fine_lin = np.linspace(_fit_range[0] * _fit_range_enlarge, \n                                _fit_range[1] * _fit_range_enlarge, \n                                2 ** 10)\n\n\n    '''\n    Fourth-order fits yield the best result\n    '''\n    def _fourth_func(x, a, b, c, d, e):\n        return a + b * x + c * (x ** 2) + d * (x ** 3) + e * (x ** 4)\n\n    def _quad_func(x, a, b, c):\n        return a + b * x + c * (x ** 2)\n\n    _fourth_fit, _fourth_cov = \\\n        optimize.curve_fit(_fourth_func, \n                           _rm1_data[_fit_cut_index], \n                           _delta_p_sigma_s_data[_fit_cut_index], \n                           p0 = (_swap_d0, _swap_d1, _swap_d2, _swap_d3, _swap_d4))\n\n    _quad_fit, _quad_cov = \\\n        optimize.curve_fit(_quad_func, \n                           _rm1_data[_fit_cut_index], \n                           _delta_p_sigma_s_data[_fit_cut_index], \n                           p0 = (_swap_d0, _swap_d1, _swap_d2))\n\n    _fourth_fit_lambda = lambda x : _fourth_func(x, _fourth_fit[0], _fourth_fit[1], \n                                                 _fourth_fit[2], _fourth_fit[3], \n                                                 _fourth_fit[4])\n    _quad_fit_lambda = lambda x : _quad_func(x, _fourth_fit[0], _fourth_fit[1], _fourth_fit[2])\n    \n    #_delta_fit_res['sigma_0'] += [_sigma_0_data]\n    _delta_fit_res['sigma_0'] += [_quad_fit[0]]\n    \n    _delta_fit_res['first_order'] += [_quad_fit[1]/_quad_fit[0]]\n    _delta_fit_res['second_order'] += [_quad_fit[2]/_quad_fit[0]]\n\n    print(\"Tolman length:\", -_delta_fit_res['first_order'][-1] / 2)\n    print()\n        \n_delta_fit_res['first_order'] = np.array(_delta_fit_res['first_order'])\n_delta_fit_res['second_order'] = np.array(_delta_fit_res['second_order'])\n```\n\n### Plot\n\n\n```python\n# Figure 3 script (click the arrow on the left to unfold)\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc, rcParams\nrc('font',**{'family':'STIXGeneral'})\nrc('mathtext', **{'fontset': 'stix'})\nrc('text', usetex=True)\nrcParams['text.latex.preamble']=[r\"\\usepackage{amsmath, sourcesanspro}\"]\n\nfrom mpl_toolkits.axes_grid.inset_locator import (inset_axes, InsetPosition,\n                                                  mark_inset)\n\n_fs, _ms_small, _ms_large, _ms_large_c = 20, 9, 12, 20\n_fs_small = 12\n_l_fs = 17\n_line_w = 2\n\nrc('legend', fontsize = _l_fs)\n\nreproduced_figures = Path(\"reproduced-figures\")\nif not reproduced_figures.is_dir():\n    reproduced_figures.mkdir()\n    \n_cmap = matplotlib.colors.LinearSegmentedColormap.from_list(\"MyCmapName\",[\"r\",\"b\"])\n\n\n_Gs_len = len(_Gs_list[_Gs_slice])\n_Gs_i_range = range(_Gs_len)\n_sym_i = _Gs_len//2\n\n_Gs_AA_list = np.array([abs(_Gs_list[_][0][0]) for _ in _Gs_i_range])\n##_delta_Gs = np.array([1 - (1 - _Gs_list[_Gs_i][0][0] / Gcs[psis[0]]) / 0.4 for _Gs_i in _Gs_i_range])\n_delta_Gs = np.array([(1 - _Gs_list[_Gs_i][0][0] / Gcs[psis[0]]) / 0.4 - 1 for _Gs_i in _Gs_i_range])\n\n_Gs_col_norm = matplotlib.colors.LogNorm(vmin = np.amin(_Gs_AA_list), \n                                         vmax = np.amax(_Gs_AA_list))\n\nfig = plt.figure(figsize = (8.3, 11.5))\n_ax_sigma_0 = plt.subplot2grid((2, 1), (0, 0), colspan = 1, rowspan = 1)\n_panel_str = '$(a)$'\n\nif True:\n    _ax_sigma_0.plot(_delta_Gs, _delta_fit_res['sigma_0'], 'o',\n                     color = 'red', markersize = _ms_small, label = '$R_s \\\\to \\infty$')\n\n\n    _delta_flat_array = np.array([analysis_results_flat[_i]['sigma_flat'][0] for _i in _Gs_i_range])\n    \n    '''\n    We can plot the result of the fit with a quartic function only\n    when the number of points is larger than 5\n    '''\n    if len(_delta_flat_array) > 5:\n        def _fourth_func(x, a, b, c, d, e):\n            return a + b * x + c * (x ** 2) + d * (x ** 3) + e * (x ** 4)\n\n        _fourth_fit, _fourth_cov = \\\n            optimize.curve_fit(_fourth_func, \n                               _delta_Gs, \n                               _delta_flat_array)\n\n        _lambda_fourth_fit = lambda x: _fourth_func(x, _fourth_fit[0], \n                                                    _fourth_fit[1], _fourth_fit[2], \n                                                    _fourth_fit[3], _fourth_fit[4])\n\n        if False:\n            _ax_sigma_0.plot(_delta_Gs, _delta_flat_array, 'o', fillstyle = 'none',\n                             color = 'red', markersize = _ms_large_c, label = 'Flat Interface')\n        if True:\n            _fine_delta_Gs = np.linspace(np.amin(_delta_Gs), np.amax(_delta_Gs), 2 ** 8)\n            _ax_sigma_0.plot(_fine_delta_Gs, _lambda_fourth_fit(_fine_delta_Gs), '--',\n                             color = 'red', markersize = _ms_large_c, label = 'Flat Interface')\n\n\n    _ax_sigma_0.set_xlabel('$\\delta G_{{AB}}$', fontsize = _fs)\n    _ax_sigma_0.set_ylabel(\"$\\\\sigma_0$\", fontsize = _fs)\n\n    ####### INSET RELATIVE VARIATION WITH RESPECT TO \\sigma_0\n    _ax_sigma_0_bis = inset_axes(_ax_sigma_0, width='40%', height='40%', loc = 'upper center')\n\n    _ax_sigma_0_bis.plot(_delta_Gs, _delta_fit_res['sigma_0']/np.amax(_delta_fit_res['sigma_0']), \n                         'o', color = 'blue')\n    _ax_sigma_0_bis.set_ylabel(\"$\\\\sigma_0/\\\\sigma_{\\small{\\mbox{max}}}$\", fontsize = _fs_small)\n    _ax_sigma_0_bis.set_xlim([-0.99, 0.99])\n    _ax_sigma_0_bis.set_ylim([0.79, 1.01])\n\n    for tick in _ax_sigma_0.xaxis.get_major_ticks():\n        tick.label.set_fontsize(_fs)\n\n    for tick in _ax_sigma_0.yaxis.get_major_ticks():\n        tick.label.set_fontsize(_fs)\n\n    lgnd_points = _ax_sigma_0.legend(frameon = True, loc = 'lower right')\n\n    _ax_sigma_0.set_ylim([0.1325, 0.185])\n    _ax_sigma_0.set_xlim([-0.99, 0.99])\n    _ax_sigma_0.text(0.015, 0.035, _panel_str, \n                     transform = _ax_sigma_0.transAxes, fontsize=_fs)\n    \n#################################\n    \n_ax_sigma_corr = plt.subplot2grid((2, 1), (1, 0), colspan = 1, rowspan = 1)\n_panel_str = '$(b)$'\nif True:\n    _symbols_dict = {0: 'o', _sym_i: 's', _Gs_len - 1: '^'}\n    _lines_widths = {0: _line_w, _sym_i: _line_w * 2, _Gs_len - 1: _line_w}\n\n    for _i in [0, _sym_i, _Gs_len - 1]:\n        _Rsm1_A = 1 / analysis_results[_i]['A']['Rs_4.217']\n        _Rsm1_B = -1 / analysis_results[_i]['B']['Rs_4.217']\n        _Rs_A = analysis_results[_i]['A']['Rs_4.217']\n        _Rs_B = analysis_results[_i]['B']['Rs_4.217']\n        _delta_p_sigma_s_A = _Rs_A * analysis_results[_i]['A']['delta_p_st'] / 2\n        _delta_p_sigma_s_B = _Rs_B * analysis_results[_i]['B']['delta_p_st'] / 2\n\n        _fit_range = [-0.075, 0.075]\n        _fit_range_enlarge = 1.9\n        _rm1_fine_lin = np.linspace(_fit_range[0] * _fit_range_enlarge, \n                                    _fit_range[1] * _fit_range_enlarge, \n                                    2 ** 10)\n\n        _rm1_fine_fit = np.linspace(_fit_range[0] * _fit_range_enlarge * 0.7, \n                                    _fit_range[1] * _fit_range_enlarge * 0.7, \n                                    2 ** 10)\n\n        def _quad_func(x, b, c):\n            return 1 + b * x + c * (x ** 2)\n\n        _quad_fit_lambda = lambda x : \\\n            _quad_func(x, _delta_fit_res['first_order'][_i], \n                       _delta_fit_res['second_order'][_i])\n\n        _sigma_0_data = _delta_fit_res['sigma_0'][_i]\n\n        _color = _cmap(_Gs_col_norm(abs(_Gs_list[_i][0][0])))\n        _ax_sigma_corr.plot(_Rsm1_A, _delta_p_sigma_s_A / _sigma_0_data, \n                            _symbols_dict[_i], color = _color, markersize = _ms_small, \n                            label = '$\\delta G_{{AB}} = ' + (\"%.02f\" % _delta_Gs[_i]) + '$')\n\n\n        _ax_sigma_corr.plot(_Rsm1_B, _delta_p_sigma_s_B / _sigma_0_data, \n                            _symbols_dict[_i], \n                            markersize = _ms_small, fillstyle = 'none', color = _color)\n\n        _ax_sigma_corr.plot(_rm1_fine_lin, 1 + _delta_fit_res['first_order'][_i] * (_rm1_fine_lin), \n                            color = _color, linestyle = '-.', linewidth = _lines_widths[_i])\n\n        _ax_sigma_corr.plot(_rm1_fine_fit, _quad_fit_lambda(_rm1_fine_fit), \n                            color = _color, linestyle = '--', linewidth = _lines_widths[_i])\n\n    _ax_sigma_corr.plot([0], [1], 's', color = 'black', markersize = _ms_small)\n\n    _ax_sigma_corr.axvline(x = 0, color = 'black', linestyle = '-.', linewidth = 0.5)\n    _ax_sigma_corr.axhline(y = 1, color = 'black', linestyle = '-.', linewidth = 0.5)\n\n    _ax_sigma_corr.text(0.015, 0.035, _panel_str, \n                        transform = _ax_sigma_corr.transAxes, fontsize=_fs)\n    _ax_sigma_corr.set_xlabel('$R_s^{-1}$', fontsize=_fs)\n    _ax_sigma_corr.set_ylabel('$\\Delta P \\cdot R_s / 2 \\sigma_0$', fontsize=_fs)\n\n    for tick in _ax_sigma_corr.xaxis.get_major_ticks():\n        tick.label.set_fontsize(_fs)\n\n    for tick in _ax_sigma_corr.yaxis.get_major_ticks():\n        tick.label.set_fontsize(_fs)\n\n    lgnd_points = _ax_sigma_corr.legend(frameon = True, loc = 'upper center', \n                                        bbox_transform = _ax_laplace.transAxes, \n                                        bbox_to_anchor = (0.29,0.71))\n    \n\nplt.savefig(reproduced_figures / 'figure_sigma0_sigmaR.pdf', bbox_inches = 'tight', dpi = 200)\n```\n\n## Figure 4\n\n\n```python\n# Figure 4 script (click the arrow on the left to unfold)\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc, rcParams\nrc('font',**{'family':'STIXGeneral'})\nrc('mathtext', **{'fontset': 'stix'})\nrc('text', usetex=True)\nrcParams['text.latex.preamble']=[r\"\\usepackage{amsmath, sourcesanspro}\"]\n\n_fs, _ms_small, _ms_large, _ms_large_c = 20, 9, 12, 20\n_l_fs = 17\n_line_w = 2\n\nrc('legend', fontsize = _l_fs)\n\nreproduced_figures = Path(\"reproduced-figures\")\nif not reproduced_figures.is_dir():\n    reproduced_figures.mkdir()\n    \n_cmap = matplotlib.colors.LinearSegmentedColormap.from_list(\"MyCmapName\",[\"r\",\"b\"])\n\n\n_Gs_len = len(_Gs_list[_Gs_slice])\n_Gs_i_range = range(_Gs_len)\n_sym_i = _Gs_len//2\n\n_Gs_AA_list = np.array([abs(_Gs_list[_][0][0]) for _ in _Gs_i_range])\n##_delta_Gs = np.array([1 - (1 - _Gs_list[_Gs_i][0][0] / Gcs[psis[0]]) / 0.4 for _Gs_i in _Gs_i_range])\n_delta_Gs = np.array([(1 - _Gs_list[_Gs_i][0][0] / Gcs[psis[0]]) / 0.4 - 1 for _Gs_i in _Gs_i_range])\n\n_Gs_col_norm = matplotlib.colors.LogNorm(vmin = np.amin(_Gs_AA_list), \n                                         vmax = np.amax(_Gs_AA_list))\n\nfig = plt.figure(figsize = (8.3, 10.5))\n_ax_delta = plt.subplot2grid((2, 1), (0, 0), colspan = 1, rowspan = 1)\n_panel_str = '$(a)$'\n\nif True:\n    _ax_delta.plot(_delta_Gs, -_delta_fit_res['first_order'] / 2, 'o', \n                   color = 'darkgreen', markersize = _ms_small)\n    _ax_delta.set_xlabel('$\\delta G_{{AB}}$', fontsize = _fs)\n    _ax_delta.set_ylabel('$\\delta$', fontsize = _fs)\n\n    _ax_delta.text(0.015, 0.925, _panel_str, transform = _ax_delta.transAxes, fontsize=_fs)\n\n    for tick in _ax_delta.xaxis.get_major_ticks():\n        tick.label.set_fontsize(_fs)\n\n    for tick in _ax_delta.yaxis.get_major_ticks():\n        tick.label.set_fontsize(_fs)\n\n    _ax_delta.axhline(y = 0, color = 'black', linestyle = '-.', linewidth = 0.5)\n    _ax_delta.axvline(x = 0, color = 'black', linestyle = '-.', linewidth = 0.5)\n    _ax_delta.set_xlim([-0.99, 0.99])\n    _ax_delta.set_ylim([-0.69, 0.39])\n    \n############################################################\n\n_ax_curv_coeffs = plt.subplot2grid((2, 1), (1, 0), colspan = 1, rowspan = 1)\n_panel_str = '$(b)$'\n\nif True:\n    _ax_curv_coeffs.plot(_delta_Gs, _delta_fit_res['second_order'], 'o', \n                         color = 'orange', markersize = _ms_small)\n    _ax_curv_coeffs.set_xlabel('$\\delta G_{{AB}}$', fontsize = _fs)\n    _ax_curv_coeffs.set_ylabel(\"$2\\\\bar{k} + k$\", fontsize = _fs)\n    \n    _ax_curv_coeffs.text(0.015, 0.925, _panel_str, transform = _ax_curv_coeffs.transAxes, fontsize=_fs)    \n\n    for tick in _ax_curv_coeffs.xaxis.get_major_ticks():\n        tick.label.set_fontsize(_fs)\n\n    for tick in _ax_curv_coeffs.yaxis.get_major_ticks():\n        tick.label.set_fontsize(_fs)\n\n    _ax_curv_coeffs.axvline(x = 0, color = 'black', linestyle = '-.', linewidth = 0.5)\n    _ax_curv_coeffs.set_xlim([-0.99, 0.99])\n    _ax_curv_coeffs.set_ylim([23.9, 38.1])\n\nplt.savefig(reproduced_figures / 'figure_curv_coeffs.pdf', bbox_inches = 'tight', dpi = 200)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "88cfe1e518b25c8f96857bedceaf804ae99cdc7d", "size": 50879, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "MultiComponentMesoscopicTolmanLength.ipynb", "max_stars_repo_name": "lullimat/arXiv-2112.02574", "max_stars_repo_head_hexsha": "3881d9cd2d6446e39544455ba62b7bb6cb26da48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MultiComponentMesoscopicTolmanLength.ipynb", "max_issues_repo_name": "lullimat/arXiv-2112.02574", "max_issues_repo_head_hexsha": "3881d9cd2d6446e39544455ba62b7bb6cb26da48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MultiComponentMesoscopicTolmanLength.ipynb", "max_forks_repo_name": "lullimat/arXiv-2112.02574", "max_forks_repo_head_hexsha": "3881d9cd2d6446e39544455ba62b7bb6cb26da48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.1183774834, "max_line_length": 1361, "alphanum_fraction": 0.5270936929, "converted": true, "num_tokens": 11071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423539898095244, "lm_q2_score": 0.08882029541504169, "lm_q1q2_score": 0.028798683921502102}}
{"text": "# <span style=\"font-family:Papyrus; font-size:3em;\">Jupyter Notebooks for Social Research</span>\n\n\n\n# Authors <br>\n\n## Professor Vernon Gayle, University of Edinburgh (UK) <br>\n## Dr Roxanne Connelly, University of York (UK)\n\n\n\n<br>\n\n## The work is very exploratory. \n### Positive comments are always appreciated, but brickbats improve work.\n\n <vernon.gayle@ed.ac.uk>  or [@profbigvern](https://twitter.com/profbigvern)<br>\n <roxanne.connelly@york.ac.uk> or  [@ConnellyRoxanne](https://twitter.com/connellyroxanne)\n\n_______________________________________________________________________________________________________________________\n\nNext Actions: Demonstrate at Univesity of Luxembourg Meeting Oct 2018\n\nAuthor: Professor Vernon Gayle\n\nProject: Reproducible Research with Social Science Data\n\nSub-project: Jupyter Notebooks / Social Science Data Analysis with Python\n\nLatest Update: 30th September 2018 Stirling Scotland\n\nPrevious Updates: \n25th January 2017 University of Edinburgh\n26th January 2017 Demonstrated at Q-Step Edinburgh Meeting \n24th January 2017 (back on Scotrail - delay at Linlithgow)\n23rd January 2017 (on Scotrail)\n22nd January 2017 University of Edinburgh\n\n\n\n_____________________________________________________________\n\n\n## My General Motivation\n\n####  Can we use Jupyter Notebooks to support reproducible social science research?\n\n#### Are there insights we can gain from computer science & e-Research?\n\n#### Are there insights from Open Science?\n\n\n\n\n_____________________________________________________________\n\n\n## Overview\n\nThe Jupyter Notebook is an open source web application that facilitates the creation and sharing of documents that contain live code and supporting commentary in the form of explanatory text. \n\nIt is platform that can be used throughout the research process to organise and articulate elements of the social science workflow. \n\nThe Jupyter Notebook is open source and currently supports interactive data science and scientific computing across over 40 programming languages. \n\nObvious uses include data enabling and management, statistical analyses, simulations, and machine learning, but it is sufficiently flexible to be used more widely. \n\n_____________________________________________________________\n\n\n# Jupyter Notebooks & Big Science\n\nThe detection of gravitational waves is heralded as a major scientific discovery.\n\nHere is a video of Fernado Perez demonstrating a Jupyter Notebook that includes data and analyses of the first observed gravitational waves which are from the LIGO collaborations.\n\n\n\n\n[](https://www.youtube.com/watch?v=BmHPoBpZoJ4 \"Fernando Perez\")\n\n\n*click on picture to run video*\n\n\n\nFor more information on how this important work was rendered openly accessible by the LIGO collaboration see <br> https://www.gw-openscience.org/tutorials/ .\n\n_____________________________________________________________\n\n\n## Counting Galaxies in the Hubble Deep Field\n\nThis example uses the image-processing library scikit-image to identify galaxies in an image of the sky provided by the Hubble Space Telescope using a blob feature detection algorithm (an approach known as the determinant of Hessian).\n\nAfter running the cell, we can explore the parameters of the detection algorithm to find galaxies of different sizes and prominences:\n\n    The max_sigma parameter determines the maximum size of the objects that will be identified\n\n    The threshold parameter can be reduced to detect less prominent objects\n\nThis example was provided in a live example hosted by the journal Nature\n\nhttp://www.nature.com/news/ipython-interactive-demo-7.21492?article=1.16261 <br>\n\nThe live demo is no longer running (see below) but we can run it here. <br>\n\nA note from their site <br>\n\n <span style=\"color:red\">\nAttention! This is no longer a live demo. What follows is the original text from the live Nature demo that ran from November 2014 to March 2017. For up to date installation and usage of the Jupyter Notebook (n\u00e9e IPython notebook), visit jupyter.org\n</span>\n\n_______________________________________________________________________________________________________________________\n\n\n```python\n# Import matplotlib (plotting), skimage (image processing) and interact (user interfaces)\n# This enables their use in the Notebook.\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nfrom skimage import data\nfrom skimage.feature import blob_doh\nfrom skimage.color import rgb2gray\n\nfrom IPython.html.widgets import interact, fixed\n\n# Extract the first 500px square of the Hubble Deep Field.\nimage = data.hubble_deep_field()[0:500, 0:500]\nimage_gray = rgb2gray(image)\n\ndef plot_blobs(max_sigma=30, threshold=0.1, gray=False):\n    \"\"\"\n    Plot the image and the blobs that have been found.\n    \"\"\"\n    blobs = blob_doh(image_gray, max_sigma=max_sigma, threshold=threshold)\n    \n    fig, ax = plt.subplots(figsize=(8,8))\n    ax.set_title('Galaxies in the Hubble Deep Field')\n    \n    if gray:\n        ax.imshow(image_gray, interpolation='nearest', cmap='gray_r')\n        circle_color = 'red'\n    else:\n        ax.imshow(image, interpolation='nearest')\n        circle_color = 'yellow'\n    for blob in blobs:\n        y, x, r = blob\n        c = plt.Circle((x, y), r, color=circle_color, linewidth=2, fill=False)\n        ax.add_patch(c)\n\n# Use interact to explore the galaxy detection algorithm.\ninteract(plot_blobs, max_sigma=(10, 40, 2), threshold=(0.005, 0.02, 0.001));\n\n# The max_sigma parameter determines the maximum size of the objects that will be identified\n\n# The threshold parameter can be reduced to detect less prominent objects\n\n```\n\n## Literate Computing\n\n_Fernando Perez says_\n\n_Literate Computing_ is the weaving of a narrative directly into a live computation, interleaving text with code and results to construct a complete piece that relies equally on the textual explanations and the computational components, for the goals of communicating results in scientific computing and data analysis.\n\nhttp://blog.fperez.org/\n\n\n_____________________________________________________________\n\n\n## Why is it call Jupyter?\n\n### The computer languages Julia Python and R almost spell _JuPyteR_\n\n\nThe original authors Fernando Perez and Brian Granger are physicists.\n\nGalileo's notebooks are an inportant early milestone (or deliverable) in open science.\n\nGalileo\u2019s notes directly integrated his data (drawings of Jupiter and its moons), key metadata (timing of each observation, weather, telescope properties), and text (descriptions of methods, analysis, and conclusions)\nsee https://www.authorea.com/users/3/articles/6316/_show_article .\n\nTwo obvious examples are _Sidereus Nuncius_ and _la vacchetta_ (which literally means the small cow or calf, because of the leather of its binding).\n\nTranslations of these notebooks can be viewed here\n\nhttp://www.dioi.org/galileo/galileo.htm\n\nhttp://homepages.wmich.edu/~mcgrew/Siderius.pdf\n\n\nThree Galilean moons of Jupiter are visible on the logo.\n\n#### Some people may have come accross IPython Notebooks which are from an earlier stage in the evolutionary process.\n\n\n_____________________________________________________________\n\n\n## Jupyter Notebooks Social Science Research\n\n\n\nJupyter Notebooks have a number of attractive features\n\n1. Easy documentation alongside research code\n\n2. \u2018Language agnostic\u2019 40+ languages\n\n3. Rich visual outputs\n\n4. Big data tools e.g. python\n\n5. Teaching and training\n\n6. Collaborative work\n\n7. Portability (publication) easy to share\n\n\nThese features are demonstrated in this Jupyter Notebook.\n\n\n\n_____________________________________________________________\n\n\n## Structure of a Jupyter Notebook ##\n\nA Jupyter Notebook is made up of cells. \n\nA cell can contain either\n\ni. live research code (e.g. Stata syntax) that can be executed\n\nii. text comments that form the documentation of the research workflow\n\niii. cells that contain the results of data analyses\n\nIn addition to running your code the Notebook frontend stores code and output, together with markdown notes, in an editable document called a notebook. When you save it, this is sent from your browser to the notebook server, which saves it on disk as a JSON file with a .ipynb extension.\n\n\n_____________________________________________________________\n\n\n## Documentation in the Jupyter Notebook\n\nWriting comments and documenting research code in a Jupyter Notebook is relatively easy. \n\nNotebooks use *Markdown*, which is explained below.\n\nComments can also be included within research code. For example a comment within Stata code can be written by starting with the familiar asterisk or star symbol.\n\n## Markdown ##\n\n _Markdown_ is an easy way to write documents. \n\nIt is written in what computer geeks like to call 'plaintext'.\nIt is the sort of text that we are used to writing and seeing. \n\nPlaintext is just the regular alphabet plus a few other familiar symbols (for example the asterisk * ).\n\nUnlike cumbersome word processing applications, text written in Markdown can be easily shared between computers.\n\nIt\u2019s quickly becoming the writing standard in some academic areas and in science.\n\nWebsites like GitHub and reddit use Markdown to style their comments.\n\nHere is a summary of _Markdown_ codes https://en.wikipedia.org/wiki/Markdown#Example .\n\nIf you have half an hour you can learn _Markdown_ here http://www.markdowntutorial.com/ (you might need to use Internet Explorer).\n\n\n\n_____________________________________________________________\n\n\n## Examples\n\n### Example 1 'Sitting in the Swivel Chair' (undertaking data analyses in different languages)\n\n### Example 2 'Rich Visual Output'\n\n### Example 3 'Widgets'\n\n### Example 4 'Using Magic Cells'\n\n### Example 5 'A Gnarly Example in Stata with a Complex Model'\n\n\n\n\n\n------------------------------------------------------------------------------------------------------------------------\n\n# Example 1 'Sitting in the Swivel Chair'\n\nThe Notebook can work with over 40 programming languages.\n\nThis includes data analysis software such as Stata and R and languages such as Python that are popular in some areas of data science.\n\nMoving between languages with ease has been likened to sitting in an office chair and swivelling between three different computers.\n\nThe example below demonstrates some social science data analysis (estimating a logistic regression model) within the Jupyter Notebook.\n\nTo illustrate that the Jupyter Notebook is 'language agnostic', the analysis is undertaken using Stata, R and Python.\n\nJupyter Notebooks use different 'kernels' to work in different languages.\n\n\n## Stata Analysis\n\nStata is a proprietary software package and you MUST have access to the software to run it within a Jupyter Notebook. \n \n Here is a link to the Stata Corporation http://www.stata.com/ .\n \n This is an example of running Stata from within the Jupyter Notebook. \n \n The live research code in each cell is Stata syntax.\n \n Comments are written in cells using markdown.\n\n_________________________________________\n\n## <span style=\"color:red\">WARNING</span>\n\n**We would usually use a Stata Kernel to run Stata.**\n\n**In this current example we will use MAGIC - which will be explained later in this notebook. **\n\n** This is because some users with Windows 10 machines have experienced problems installing the Stata Kernel. **\n\n** MAGIC cells are explained later in the notebook. ** \n\n\n\n\n\n```python\nimport ipystata\n```\n\n\n\nThe cell above imports ipystata to run Stata\n\nsee\nhttp://dev-ii-seminar.readthedocs.io/en/latest/notebooks/Stata_in_jupyter.html\n\n\n\n---\nThe cell below imports the Stata data file from my website vernongayle.com.\n\n<span style=\"color:green\">%%stata</span> <br>\n_makes the whole cell a Stata cell_<br>\n<br>\n<br>\n<span style=\"color:green\">-o wemp_df</span> <br>\n_slots the data into a data frame - remember we are working in Python here_ <br>\n<br>\n<span style=\"color:green\">use \"http://www.vernongayle.com/uploads/2/2/3/0/22304498/wemp.dta\", clear\ncodebook, compact</span> <br>\n_Is the usual Stata code for using a dataset and producing a compact codebook_ <br>\n\n\n\n\n\n```python\n%%stata -o wemp_df\nuse \"http://www.vernongayle.com/uploads/2/2/3/0/22304498/wemp.dta\", clear\ncodebook, compact\n```\n\n    \n    Variable    Obs Unique      Mean  Min   Max  Label\n    -------------------------------------------------------------------------------\n    case       1580    155  517.7411    1  1003  \n    femp       1580      2  .6455696    0     1  \n    mune       1580      2  .0740506    0     1  \n    time       1580     14       7.2    0    13  \n    und1       1580      2  .0746835    0     1  \n    und5       1580      2  .2974684    0     1  \n    age        1580     43  36.01013   18    60  \n    -------------------------------------------------------------------------------\n\n\nThe data mirror a real example of data analysed in Davies et al. (1992). \n\nThe dataset is a panel of 155 married women. \n\n<sub>Davies, Richard B., Peter Elias, and Roger Penn. \"The relationship between a husband's unemployment and his wife's participation in the labour force.\" Oxford Bulletin of Economics and Statistics 54.2 (1992): 145-171.\n\n*Estimating a simple logit (logistic regression) model using Stata*\n\n The outcome variable is \n femp (female unemployed 0 or 1)\n    \n The explanatory variables are \n mune (husband unemployed 0,1)\n und5 (couple have a child under age 5)\n\n\n```python\n%%stata -o wemp_df\nlogit femp mune und5\n```\n\n    \n    Iteration 0:   log likelihood = -1027.2309  \n    Iteration 1:   log likelihood = -879.88806  \n    Iteration 2:   log likelihood = -878.68101  \n    Iteration 3:   log likelihood = -878.67998  \n    Iteration 4:   log likelihood = -878.67998  \n    \n    Logistic regression                             Number of obs     =      1,580\n                                                    LR chi2(2)        =     297.10\n                                                    Prob > chi2       =     0.0000\n    Log likelihood = -878.67998                     Pseudo R2         =     0.1446\n    \n    ------------------------------------------------------------------------------\n            femp |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]\n    -------------+----------------------------------------------------------------\n            mune |  -1.703308   .2358489    -7.22   0.000    -2.165563   -1.241053\n            und5 |  -1.733521   .1221909   -14.19   0.000    -1.973011   -1.494031\n           _cons |   1.306829   .0744154    17.56   0.000     1.160978    1.452681\n    ------------------------------------------------------------------------------\n\n\n## R Analysis\n\n## <span style=\"color:red\">WARNING</span>\n\n**You must have R installed on your machine.**\n\n**You must have installed the R kernel (See https://anaconda.org/r/r-irkernel ). **\n\n**You must have installed the R libraries foreign and survey **\n\n** for example run the code *install.packages(\"foreign\",\"survey\")* **\n\n**(see https://cran.r-project.org/web/packages/survey/index.html ; **\n** https://cran.r-project.org/web/packages/foreign/index.html).** \n\n\n\n <span style=\"color:red\">Reminder *Switch Kernel to R  < Menu kernel - change kernel>*</span>\n\n*Getting the libraries for R*\n\n\n```python\nlibrary(foreign)\nlibrary(survey)\n```\n\n    Loading required package: grid\n    Loading required package: Matrix\n    Loading required package: survival\n    Warning message:\n    : package 'survival' was built under R version 3.2.5\n    Attaching package: 'survey'\n    \n    The following object is masked from 'package:graphics':\n    \n        dotchart\n    \n\n\n<span style=\"color:red\">If you have an error message here it is possibly because you have not switched to the _R Kernel_</span>\n\n*Getting the Stata data file (.dta) into an object called \"mydata\"*\n*then summarizing the dataset*\n\n\n```python\nmydata <- read.dta(\"http://www.vernongayle.com/uploads/2/2/3/0/22304498/wemp.dta\")\nsummary(mydata)\n```\n\n\n\n\n          case             femp             mune              time     \n     Min.   :   1.0   Min.   :0.0000   Min.   :0.00000   Min.   : 0.0  \n     1st Qu.: 274.0   1st Qu.:0.0000   1st Qu.:0.00000   1st Qu.: 4.0  \n     Median : 538.0   Median :1.0000   Median :0.00000   Median : 8.0  \n     Mean   : 517.7   Mean   :0.6456   Mean   :0.07405   Mean   : 7.2  \n     3rd Qu.: 753.0   3rd Qu.:1.0000   3rd Qu.:0.00000   3rd Qu.:11.0  \n     Max.   :1003.0   Max.   :1.0000   Max.   :1.00000   Max.   :13.0  \n          und1              und5             age       \n     Min.   :0.00000   Min.   :0.0000   Min.   :18.00  \n     1st Qu.:0.00000   1st Qu.:0.0000   1st Qu.:29.00  \n     Median :0.00000   Median :0.0000   Median :35.00  \n     Mean   :0.07468   Mean   :0.2975   Mean   :36.01  \n     3rd Qu.:0.00000   3rd Qu.:1.0000   3rd Qu.:43.00  \n     Max.   :1.00000   Max.   :1.0000   Max.   :60.00  \n\n\n\nEstimating the logit model and sending it to the object \"mylogit\".\n\n\n```python\nstr(mydata)\n```\n\n    'data.frame':\t1580 obs. of  7 variables:\n     $ case: num  1 1 1 1 6 6 6 6 6 6 ...\n     $ femp: num  1 0 0 0 1 1 0 0 1 1 ...\n     $ mune: num  0 0 0 0 0 0 0 0 0 0 ...\n     $ time: num  10 11 12 13 0 1 2 3 4 5 ...\n     $ und1: num  1 0 0 0 0 0 0 0 0 0 ...\n     $ und5: num  1 1 1 1 0 0 0 0 0 0 ...\n     $ age : num  23 24 25 26 42 43 44 45 46 47 ...\n     - attr(*, \"datalabel\")= chr \"\"\n     - attr(*, \"time.stamp\")= chr \"22 Jun 2006 18:18\"\n     - attr(*, \"formats\")= chr  \"%9.0g\" \"%9.0g\" \"%9.0g\" \"%9.0g\" ...\n     - attr(*, \"types\")= int  254 254 254 254 254 254 254\n     - attr(*, \"val.labels\")= chr  \"\" \"\" \"\" \"\" ...\n     - attr(*, \"var.labels\")= chr  \"\" \"\" \"\" \"\" ...\n     - attr(*, \"version\")= int 8\n\n\n\n```python\nmylogit <- glm(femp ~ mune + und5, data = mydata, family = \"binomial\")\n\nsummary(mylogit)\n\n```\n\n\n\n\n    \n    Call:\n    glm(formula = femp ~ mune + und5, family = \"binomial\", data = mydata)\n    \n    Deviance Residuals: \n        Min       1Q   Median       3Q      Max  \n    -1.7586  -1.0024   0.6922   0.6922   2.1177  \n    \n    Coefficients:\n                Estimate Std. Error z value Pr(>|z|)    \n    (Intercept)  1.30683    0.07442  17.561  < 2e-16 ***\n    mune        -1.70331    0.23585  -7.222 5.12e-13 ***\n    und5        -1.73352    0.12219 -14.187  < 2e-16 ***\n    ---\n    Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1\n    \n    (Dispersion parameter for binomial family taken to be 1)\n    \n        Null deviance: 2054.5  on 1579  degrees of freedom\n    Residual deviance: 1757.4  on 1577  degrees of freedom\n    AIC: 1763.4\n    \n    Number of Fisher Scoring iterations: 4\n\n\n\n\n### The R results are the same as the Stata results - thankfully\n\n## Python Analysis\n\n <span style=\"color:red\">WARNING *Switch Kernel to Python  < Menu kernel - change kernel>*</span>\n\n\nSwitch Kernel to Python 3 < Menu kernel - change kernel>\n\n\n```python\nimport pandas as pd\n```\n\nConstruct the data frame \"df\" reading in the data from an Excel (xlsx) file. It could also be read in from a csv file.\n\n\n```python\ndf = pd.read_excel(\"http://www.vernongayle.com/uploads/2/2/3/0/22304498/wemp.xlsx\")\ndf.head()\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>case</th>\n      <th>femp</th>\n      <th>mune</th>\n      <th>time</th>\n      <th>und1</th>\n      <th>und5</th>\n      <th>age</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>10</td>\n      <td>1</td>\n      <td>1</td>\n      <td>23</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>11</td>\n      <td>0</td>\n      <td>1</td>\n      <td>24</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>12</td>\n      <td>0</td>\n      <td>1</td>\n      <td>25</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>13</td>\n      <td>0</td>\n      <td>1</td>\n      <td>26</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>6</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>42</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nPython is more general purpose and not primarily orientated towards social science data analysis. \nTherefore some things are a little more fiddly. For example we must set a constant for all case (int=1).\n\n\n```python\ndf['Int']=1\n```\n\nExamining the data in the data frame \"df\".\n\n\n```python\ndf.head()\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>case</th>\n      <th>femp</th>\n      <th>mune</th>\n      <th>time</th>\n      <th>und1</th>\n      <th>und5</th>\n      <th>age</th>\n      <th>Int</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>10</td>\n      <td>1</td>\n      <td>1</td>\n      <td>23</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>11</td>\n      <td>0</td>\n      <td>1</td>\n      <td>24</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>12</td>\n      <td>0</td>\n      <td>1</td>\n      <td>25</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>13</td>\n      <td>0</td>\n      <td>1</td>\n      <td>26</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>6</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>42</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nImport the package \"statsmodels\".\n\n\n```python\nimport statsmodels.api as sm\n```\n\nEstimate a logistic regression model\nthe independent variables are \"mune\" \"und5\" and \"int\"\nthe outcome variable is \"femp\".\n\n\n```python\nindependentVar = ['mune', 'und5', 'Int']\nlogReg = sm.Logit(df['femp'] , df[independentVar]) \nanswer = logReg.fit()\n```\n\n    Optimization terminated successfully.\n             Current function value: 0.556127\n             Iterations 5\n\n\nThe results are in the object \"answer\".\n\n\n```python\nanswer.summary()\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>Logit Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>       <td>femp</td>       <th>  No. Observations:  </th>  <td>  1580</td>  \n</tr>\n<tr>\n  <th>Model:</th>               <td>Logit</td>      <th>  Df Residuals:      </th>  <td>  1577</td>  \n</tr>\n<tr>\n  <th>Method:</th>               <td>MLE</td>       <th>  Df Model:          </th>  <td>     2</td>  \n</tr>\n<tr>\n  <th>Date:</th>          <td>Sun, 30 Sep 2018</td> <th>  Pseudo R-squ.:     </th>  <td>0.1446</td>  \n</tr>\n<tr>\n  <th>Time:</th>              <td>14:33:26</td>     <th>  Log-Likelihood:    </th> <td> -878.68</td> \n</tr>\n<tr>\n  <th>converged:</th>           <td>True</td>       <th>  LL-Null:           </th> <td> -1027.2</td> \n</tr>\n<tr>\n  <th> </th>                      <td> </td>        <th>  LLR p-value:       </th> <td>3.056e-65</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n    <td></td>      <th>coef</th>     <th>std err</th>      <th>z</th>      <th>P>|z|</th> <th>[95.0% Conf. Int.]</th> \n</tr>\n<tr>\n  <th>mune</th> <td>   -1.7033</td> <td>    0.236</td> <td>   -7.222</td> <td> 0.000</td> <td>   -2.166    -1.241</td>\n</tr>\n<tr>\n  <th>und5</th> <td>   -1.7335</td> <td>    0.122</td> <td>  -14.187</td> <td> 0.000</td> <td>   -1.973    -1.494</td>\n</tr>\n<tr>\n  <th>Int</th>  <td>    1.3068</td> <td>    0.074</td> <td>   17.561</td> <td> 0.000</td> <td>    1.161     1.453</td>\n</tr>\n</table>\n\n\n\n\n\n###  _<span style=\"color:orange\"> The result are the same in Python, R and Stata - Phew!_ </span>\n\n___________________________________________________________\n\n### Summary \n\nThis example was designed to demonstrate that Jupyter Notebooks are language agnostic. \n\nThe language agnostic aspects of Jupyter Notebooks mean that they could be an appropriate unified environment in which to undertake research analyses using alternative software packages and languages.\n\nThis feature is especially attractive in some collaborative endeavours. For example although Stata is the primary data analysis software package in many sociology departments, from time to time there may be a requirement to use other data analysis tools.\n\n\n________________________________________________________________________________\n\n# Example 2 'Rich Visual Output'\n\nThere are several visual features of Jupyter Notebooks that make them attractive as environments in which to undertake analyses of social science data and which might also enrich teaching, training and kwonledge exchange and research capacity buidling activities. \n\n\nHere is a smart wee example that shows the flexibility of graphing within the Jupyter Notebook.\n\nThis wee example runs in Python.\nYou MUST have the Python kernel running.\n\nMake sure you have the wemp data in the the \"df\" data frame.\n\n\n\n```python\ndf.head()\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>case</th>\n      <th>femp</th>\n      <th>mune</th>\n      <th>time</th>\n      <th>und1</th>\n      <th>und5</th>\n      <th>age</th>\n      <th>Int</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>10</td>\n      <td>1</td>\n      <td>1</td>\n      <td>23</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>11</td>\n      <td>0</td>\n      <td>1</td>\n      <td>24</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>12</td>\n      <td>0</td>\n      <td>1</td>\n      <td>25</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>13</td>\n      <td>0</td>\n      <td>1</td>\n      <td>26</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>6</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>42</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nIf you can't see the wemp data you need to go back up and reload it in the Python part of the Example 1.\n\nWe will now construct a new variable called _age2_ which is the woman's age squared.\n\n\n```python\ndf['age2'] = df.age * df.age\n```\n\nThis is an example of a graph in the style of a xkcd comic.\n\n\n```python\n%pylab inline\nplt.xkcd()  # Yes...\nfig1 = plt.figure(1)\nax1 = fig1.add_subplot(111)\nax1.scatter(df['age2'], df['age'],)\nplt.title('Big Verns xkcd Plot')\nplt.ylabel('Age at Interview!')\nplt.xlabel(\"Age Squared\\n\"\n           \"____________\\n\"\n            \"Another inventive use of the wemp dataset\", size=16)\n```\n\n see  http://nbviewer.jupyter.org/url/jakevdp.github.com/downloads/notebooks/XKCD_plots.ipynb\n\nInserting a picture into the notebook (within a markdown cell).\n\nDonald Knuth\n\n\n_______________________________________________________________________________________________________________________\n\nInserting a video into the notebook (within a markdown cell).\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('p47tetYy7co')\n\n```\n\n\n\n\n\n\n\n\n\n\n*To render cell contents as LaTeX.*\n\n\n```latex\n%%latex\n\\begin{align}\na = \\frac{1}{2} && b= \\frac{1}{2} && c = \\frac{1}{4} \\\\\n\\end{align}    \n```\n\n\n\\begin{align}\na = \\frac{1}{2} && b= \\frac{1}{2} && c = \\frac{1}{4} \\\\\n\\end{align}    \n\n\n\n```latex\n%%latex\n$e^{i\\pi} + 1 = 0 \n$\n```\n\n\n$e^{i\\pi} + 1 = 0 \n$\n\n\nCode can produce rich output such as images, videos, LaTeX, and JavaScript.\n\n_______________________________________________________________________________________________________________________\n\n# Example 3 'Widgets'\n\nWidgets are clever devices that can be included in notebooks to help users visualize and control changes in the data.\nWidgets may be useful in teaching and training because users can easily see how changing inputs to something impacts on the results.\n\n### An Interesting Wee Widget\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom numpy import pi, exp, real, imag, linspace\nfrom ipywidgets import interact\n \ndef f(t,a=1,b=6,c=-14,d=0):\n    return exp(a*1j*t) - exp(b*1j*t)/2 + 1j*exp(c*1j*t)/3 + exp(d*1j*t)/4\n \ndef plot_swirly(a=1,b=6,c=-14,d=0):\n    t = linspace(0, 2*pi, 1000)\n    ft = f(t,a,b,c,d) \n    plt.plot(real(ft), imag(ft))\n\n    # These two lines make the aspect ratio square\n    fig = plt.gcf()\n    fig.set_size_inches(6, 6, forward='True')\n\ninteract(plot_swirly,a=(-20,20),b=(-20,20),c=(-20,20),d=(-20,20));\n```\n\n### The Sine Wave Example\n\n\n```python\nfrom ipywidgets import widgets\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom IPython.display import display\nfrom numpy import arange, sin, pi\n%matplotlib inline\n```\n\n\n```python\nfrom IPython.html.widgets import *\nt = arange(0.0, 1.0, 0.01)\n\ndef pltsin(f):\n    plt.plot(t,sin(2*pi*t*f))\n    plt.show()\n\ninteract(pltsin, f=(1,10,0.1))\n```\n\n_______________________________________________________________________________________________________________________\n    \n\n# Example 4 'Using Magic Cells'\n\nAny cell that starts with a % symbol or two symbols %% is a 'magic' cell (honestly that is what they are called).\n\nHere are a list of some of the standard 'magics'. \n\n\n```python\n%lsmagic\n```\n\n\n\n\n    Available line magics:\n    %alias  %alias_magic  %autocall  %automagic  %autosave  %bookmark  %cd  %clear  %cls  %colors  %config  %connect_info  %copy  %ddir  %debug  %dhist  %dirs  %doctest_mode  %echo  %ed  %edit  %env  %gui  %hist  %history  %install_default_config  %install_ext  %install_profiles  %killbgscripts  %ldir  %less  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %macro  %magic  %matplotlib  %mkdir  %more  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %popd  %pprint  %precision  %profile  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %ren  %rep  %rerun  %reset  %reset_selective  %rmdir  %run  %save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode\n    \n    Available cell magics:\n    %%!  %%HTML  %%SVG  %%bash  %%capture  %%cmd  %%debug  %%file  %%html  %%javascript  %%latex  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile\n    \n    Automagic is ON, % prefix IS NOT needed for line magics.\n\n\n\n### In Example 1 we used a non-standard magic to run Stata which was written by Ties de Kok \n\n\n\n```python\n%time print (\"How long does this cell take to run?\")\n```\n\n    How long does this cell take to run?\n    Wall time: 0 ns\n\n\n_______________________________________________________________________________________________________________________\n\n# Example 5 'A Really Gnarly Example in Stata with a Complex Model'\n\n## Multilevel mixed-effects generalized linear model in Stata (meglm) \n\nMultilevel modeling of survey data is a little different from standard modeling in that weighted sampling can take place at multiple levels in the model, resulting in multiple sampling weights. \n\nMost survey datasets, regardless of the design, contain one overall inclusion weight for each observation in the data. This weight reflects the inverse of the probability of ultimate selection (i.e. it factors in all levels of clustered sampling, corrections for noninclusion and oversampling, poststratification).\n\nRabe\u2010Hesketh, S. and Skrondal, A., 2006. Multilevel modelling of complex survey data. Journal of the Royal Statistical Society: Series A (Statistics in Society), 169(4), pp.805-827.\n\n\nRabe-Hesketh and Skrondal (2006) analyzed data from the 2000 Programme for International Student Assessment (PISA) study on reading proficiency among 15-year-old American students, as performed by the Organisation for Economic Co-operation and Development (OECD). \n\n\n```python\nimport ipystata\n```\n\n\n```python\n%%stata -o pisa_df\nuse http://www.stata-press.com/data/r14/pisa2000, clear\n\n\n```\n\n    \n    (Programme for International Student Assessment (PISA) 2000 data)\n\n\n\n```python\n%%stata -o pisa_df\ncodebook, compact\n```\n\n    \n    Variable      Obs Unique      Mean       Min       Max  Label\n    -------------------------------------------------------------------------------\n    female       2069      2  .5432576         0         1  1 if female\n    isei         2069     58   47.0435        16        90  International socio-...\n    w_fstuwt     2069    224  843.3753  130.3095  3858.783  Student-level weight\n    wnrschbw     2069    147  167.8744     15.41   3352.32  School-level weight\n    high_school  2069      2  .3412276         0         1  1 if highest level b...\n    college      2069      2   .578057         0         1  1 if highest level b...\n    one_for      2069      2  .0560657         0         1  1 if one parent fore...\n    both_for     2069      2   .117448         0         1  1 if both parents ar...\n    test_lang    2069      2  .9134848         0         1  1 if English (the te...\n    pass_read    2069      2  .3881102         0         1  1 if passed reading ...\n    id_school    2069    148  73.65974         1       151  School ID\n    -------------------------------------------------------------------------------\n\n\nFor student i in school j, where the variable id_school identifies the schools, the variable\nw_fstuwt is a student-level overall inclusion weight (wij , not wi|j ) adjusted for non-inclusion and\nnon-participation of students, and the variable wnrschbw is the school-level weight wj adjusted for\noversampling of schools with more students from minority groups.\n\nRabe-Hesketh and Skrondal (2006) fit a two-level logistic model for passing a reading proficiency\nthreshold. We will do the same using meglm, but first we must adjusted the weight variables that were used. We need adjustment scales for the first-level weights so that they sum to the effective sample size of their corresponding second-level cluster.\n\n\n```python\n%%stata -o pisa_df\nsort id_school\ngenerate sqw = w_fstuwt * w_fstuwt\nby id_school: egen sumw = sum(w_fstuwt)\nby id_school: egen sumsqw = sum(sqw)\ngenerate pst1s1 = w_fstuwt*sumw/sumsqw\n```\n\n    \n    \n\n\nThe new variable pst1s1 holds the adjusted first-level weights. \n\nRabe-Hesketh and Skrondal (2006) also included the school mean socioeconomic index as a covariate in their analysis. We reproduce this new variable mn_isei.\n\n\n```python\n%%stata -o pisa_df\nby id_school: egen mn_isei = mean(isei)\n```\n\n    \n    \n\n\nEstimation a multi-level logistic regression model with complex survey data.\n\n\n```python\n%%stata -o pisa_df\nmeglm pass_read female isei mn_isei high_school college test_lang one_for both_for [pw=pst1s1], family(bernoulli) link(logit)|| id_school:, pweight(wnrschbw)\n```\n\n    \n    > h_for [pw=pst1s1], family(bernoulli) link(logit)|| id_school:, pweight(wnrsch\n    > bw)\n    \n    Fitting fixed-effects model:\n    \n    Iteration 0:   log likelihood = -199789.29  \n    Iteration 1:   log likelihood = -199575.17  \n    Iteration 2:   log likelihood = -199574.45  \n    Iteration 3:   log likelihood = -199574.45  \n    \n    Refining starting values:\n    \n    Grid node 0:   log likelihood = -200169.61\n    \n    Fitting full model:\n    \n    Iteration 0:   log pseudolikelihood = -200169.61  (not concave)\n    Iteration 1:   log pseudolikelihood = -198196.62  \n    Iteration 2:   log pseudolikelihood = -197524.63  \n    Iteration 3:   log pseudolikelihood = -197398.31  \n    Iteration 4:   log pseudolikelihood = -197395.98  \n    Iteration 5:   log pseudolikelihood = -197395.98  \n    \n    Mixed-effects GLM                               Number of obs     =      2,069\n    Family:               Bernoulli\n    Link:                     logit\n    Group variable:       id_school                 Number of groups  =        148\n    \n                                                    Obs per group:\n                                                                  min =          1\n                                                                  avg =       14.0\n                                                                  max =         28\n    \n    Integration method: mvaghermite                 Integration pts.  =          7\n    \n                                                    Wald chi2(8)      =      88.30\n    Log pseudolikelihood = -197395.98               Prob > chi2       =     0.0000\n                                (Std. Err. adjusted for 148 clusters in id_school)\n    ------------------------------------------------------------------------------\n                 |               Robust\n       pass_read |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]\n    -------------+----------------------------------------------------------------\n          female |   .6221369   .1540088     4.04   0.000     .3202852    .9239887\n            isei |    .018215   .0048057     3.79   0.000     .0087959     .027634\n         mn_isei |   .0682472   .0164337     4.15   0.000     .0360378    .1004566\n     high_school |   .1028108    .477141     0.22   0.829    -.8323683     1.03799\n         college |   .4531688   .5053447     0.90   0.370    -.5372885    1.443626\n       test_lang |   .6251822   .3821182     1.64   0.102    -.1237557     1.37412\n         one_for |  -.1089314   .2739724    -0.40   0.691    -.6459075    .4280447\n        both_for |  -.2804038   .3264681    -0.86   0.390    -.9202696     .359462\n           _cons |  -5.877565    .954525    -6.16   0.000      -7.7484   -4.006731\n    -------------+----------------------------------------------------------------\n    id_school    |\n       var(_cons)|   .2955769   .1243375                      .1295996    .6741201\n    ------------------------------------------------------------------------------\n\n\nHere we have specified a multi-level logit model (or a random effects logit model).\n\nThe survey data are complex.\n\nPupils are nested in schools and we are adjusting the model for both school-level and pupil-level weights.\n\n1] We specified the level-one weights using standard Stata weight syntax [pw=pst1s1].\n\n\n2] We specified the level-two weights via the pweight(wnrschbw) option as part of the random effects\nspecification for the id_school level using the syntax || id_school:, pweight(wnrschbw). The weight wnrschbw needs to be constant within schools.\n\n\n3] The standard errors in the presence of sampling weights are robust.\n\n\n4] Robust standard errors are clustered at the top level of the model, and this will always be true unless\nyou specify vce(cluster clustvar), where clustvar identifies an even higher level of grouping.\n\n\n\nThis illustration is drawn from Example 5 of the meglm section of Stata Manual (pp.81-82).\n\n_______________________________________________________________________________________________________________________\n\n### A Little Light Relief\n\n#### My Jupyter Limerick\n\nA researcher with time to fritter\n\nDecided he didn\u2019t need Jupyter\n\nHis results he would show\n\nWithout a traceable workflow\n\nCould a researcher be any stupider?\n\n\n_______________________________________________________________________________________________________________________\n\n## Remarks and Conclusion\n\n### Jupyter Notebooks and Social Research\n\n\n\nJupyter Notebooks have a number of attractive features\n\n1. Easy documentation alongside research code\n\n2. \u2018Language agnostic\u2019 40+ languages\n\n3. Rich visual outputs\n\n4. Big data tools e.g. python\n\n5. Teaching and training\n\n6. Collaborative work\n\n7. Portability (publication) easy to share\n\n\nThese features are demonstrated in this Jupyter Notebook.\n\n\n\n## Finally converting this Jupyter Notebook into Portable Formats\n\nsee http://nbconvert.readthedocs.io/en/latest/\n\n1. At the cmd prompt _conda install nbconvert_\n2. Change directory (for example my directory is _C:\\Users\\Vernon_\n3. Type _jupyter nbconvert --to html mynotebook.ipynb_\n\n\n_______________________________________________________________________________________________________________________\n\n## The work is very exploratory. \n### Positive comments are always appreciated, but brickbats improve work. \n\n <vernon.gayle@ed.ac.uk>  or [@profbigvern](https://twitter.com/profbigvern)\n<roxanne.connelly@york.ac.uk> or [@ConnellyRoxanne](https://twitter.com/connellyroxanne)\n\n\nEND OF FILE\n", "meta": {"hexsha": "7c25f2afbbf3eb5593b38ec00bf8a09fb849049c", "size": 811898, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lux_20180929_vg_v1.ipynb", "max_stars_repo_name": "vernongayle/jupyter_luxembourg", "max_stars_repo_head_hexsha": "df5e6ac8c2b54109d6295cec74a6f14d22fac9a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-10-09T19:49:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-09T19:49:51.000Z", "max_issues_repo_path": "lux_20180929_vg_v1.ipynb", "max_issues_repo_name": "vernongayle/jupyter_luxembourg", "max_issues_repo_head_hexsha": "df5e6ac8c2b54109d6295cec74a6f14d22fac9a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lux_20180929_vg_v1.ipynb", "max_forks_repo_name": "vernongayle/jupyter_luxembourg", "max_forks_repo_head_hexsha": "df5e6ac8c2b54109d6295cec74a6f14d22fac9a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 326.5880933226, "max_line_length": 627258, "alphanum_fraction": 0.9139399284, "converted": true, "num_tokens": 11261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423539898095244, "lm_q2_score": 0.08882028757623954, "lm_q1q2_score": 0.02879868137988496}}
{"text": "<a href=\"https://colab.research.google.com/github/choderalab/gimlet/blob/master/lime/scripts/notebooks/190728_yuanqing_gn_with_gru_on_sereina_riniker_dataset.ipynb\" target=\"_parent\"></a>\n\n# GN on Sereina Riniker Dataset\nyuanqing wang, jul 28, 2019\n\n\n## Preparation\n\n### Install gimlet\n\n\n```\n! pip install tensorflow==2.0.0-beta1\n! pip uninstall gin-config -y\n! rm -rf gimlet\n! git clone https://github.com/choderalab/gimlet.git\n```\n\n    Collecting tensorflow==2.0.0-beta1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/29/6c/2c9a5c4d095c63c2fb37d20def0e4f92685f7aee9243d6aae25862694fd1/tensorflow-2.0.0b1-cp36-cp36m-manylinux1_x86_64.whl (87.9MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 87.9MB 38.8MB/s \n    \u001b[?25hRequirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0-beta1) (1.11.2)\n    Requirement already satisfied: gast>=0.2.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0-beta1) (0.2.2)\n    Collecting tb-nightly<1.14.0a20190604,>=1.14.0a20190603 (from tensorflow==2.0.0-beta1)\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/a4/96/571b875cd81dda9d5dfa1422a4f9d749e67c0a8d4f4f0b33a4e5f5f35e27/tb_nightly-1.14.0a20190603-py3-none-any.whl (3.1MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.1MB 45.0MB/s \n    \u001b[?25hCollecting tf-estimator-nightly<1.14.0.dev2019060502,>=1.14.0.dev2019060501 (from tensorflow==2.0.0-beta1)\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/32/dd/99c47dd007dcf10d63fd895611b063732646f23059c618a373e85019eb0e/tf_estimator_nightly-1.14.0.dev2019060501-py2.py3-none-any.whl (496kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 501kB 45.7MB/s \n    \u001b[?25hRequirement already satisfied: keras-applications>=1.0.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0-beta1) (1.0.8)\n    Requirement already satisfied: google-pasta>=0.1.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0-beta1) (0.1.7)\n    Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0-beta1) (1.1.0)\n    Requirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0-beta1) (0.33.4)\n    Requirement already satisfied: protobuf>=3.6.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0-beta1) (3.7.1)\n    Requirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0-beta1) (1.12.0)\n    Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0-beta1) (1.15.0)\n    Requirement already satisfied: astor>=0.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0-beta1) (0.8.0)\n    Requirement already satisfied: numpy<2.0,>=1.14.5 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0-beta1) (1.16.4)\n    Requirement already satisfied: keras-preprocessing>=1.0.5 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0-beta1) (1.1.0)\n    Requirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0-beta1) (0.7.1)\n    Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<1.14.0a20190604,>=1.14.0a20190603->tensorflow==2.0.0-beta1) (41.0.1)\n    Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<1.14.0a20190604,>=1.14.0a20190603->tensorflow==2.0.0-beta1) (0.15.5)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<1.14.0a20190604,>=1.14.0a20190603->tensorflow==2.0.0-beta1) (3.1.1)\n    Requirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from keras-applications>=1.0.6->tensorflow==2.0.0-beta1) (2.8.0)\n    Installing collected packages: tb-nightly, tf-estimator-nightly, tensorflow\n      Found existing installation: tensorflow 1.14.0\n        Uninstalling tensorflow-1.14.0:\n          Successfully uninstalled tensorflow-1.14.0\n    Successfully installed tb-nightly-1.14.0a20190603 tensorflow-2.0.0b1 tf-estimator-nightly-1.14.0.dev2019060501\n    Uninstalling gin-config-0.2.0:\n      Successfully uninstalled gin-config-0.2.0\n    Cloning into 'gimlet'...\n    remote: Enumerating objects: 112, done.\u001b[K\n    remote: Counting objects: 100% (112/112), done.\u001b[K\n    remote: Compressing objects: 100% (80/80), done.\u001b[K\n    remote: Total 1485 (delta 55), reused 66 (delta 30), pack-reused 1373\u001b[K\n    Receiving objects: 100% (1485/1485), 3.62 MiB | 1.10 MiB/s, done.\n    Resolving deltas: 100% (1044/1044), done.\n\n\n\n```\nimport os\nimport sys\nimport tensorflow as tf\n# import tensorflow_probability as tfp\n# tf.enable_eager_execution()\nsys.path.append('/content/gimlet')\nimport gin\nimport lime\nimport pandas as pd\nimport numpy as np\n```\n\n### Grab the dataset\n\n\n```\n! wget https://www.research-collection.ethz.ch/bitstream/handle/20.500.11850/230799/ChEMBL_eps_78.tar.gz\n! tar -xzf *.tar.gz\n```\n\n    --2019-07-29 03:21:42--  https://www.research-collection.ethz.ch/bitstream/handle/20.500.11850/230799/ChEMBL_eps_78.tar.gz\n    Resolving www.research-collection.ethz.ch (www.research-collection.ethz.ch)... 129.132.8.151\n    Connecting to www.research-collection.ethz.ch (www.research-collection.ethz.ch)|129.132.8.151|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 32743757 (31M) [application/octet-stream]\n    Saving to: \u2018ChEMBL_eps_78.tar.gz.1\u2019\n    \n    ChEMBL_eps_78.tar.g 100%[===================>]  31.23M  6.09MB/s    in 5.1s    \n    \n    2019-07-29 03:21:49 (6.09 MB/s) - \u2018ChEMBL_eps_78.tar.gz.1\u2019 saved [32743757/32743757]\n    \n\n\nsince there are way to many molecules, we select around a thousand molecules just to get our hands wet\n\n\n```\n! cat /content/ChEMBL_mols/*1.sdf > mols.sdf\n```\n\n### Preprocess\n\n\n```\n# read molecules into a tf.data.Dataset\nds_all = gin.i_o.from_sdf.to_ds('mols.sdf', has_charge=True)\n```\n\n    WARNING: Logging before flag parsing goes to stderr.\n    W0729 03:22:03.211757 140114815813504 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/array_ops.py:1340: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use tf.where in 2.0, which has the same broadcast rule as np.where\n\n\n\n```\n# by default, there is coordinates in dataset created from sdf\n# now we get rid of it\nds_all = ds_all.map(lambda atoms, adjacency_map, coordinates, charges:\\\n    (atoms, adjacency_map, charges))\n```\n\n\n```\n# put them in batches\nds_all = gin.probabilistic.gn.GraphNet.batch(ds_all, 256, per_atom_attr=True)\n```\n\n\n```\n# get the number of samples\n# NOTE: there is no way to get the number of samples in a dataset\n# except loop through one time, unfortunately\nn_batches = gin.probabilistic.gn.GraphNet.get_number_batches(ds_all)\n```\n\n    W0729 03:22:06.073427 140113793476352 backprop.py:842] The dtype of the watched tensor must be floating (e.g. tf.float32), got tf.int64\n    W0729 03:22:06.074082 140113785083648 backprop.py:842] The dtype of the watched tensor must be floating (e.g. tf.float32), got tf.int64\n    W0729 03:22:06.120419 140113793476352 backprop.py:842] The dtype of the watched tensor must be floating (e.g. tf.float32), got tf.int64\n    W0729 03:22:06.139481 140113785083648 backprop.py:842] The dtype of the watched tensor must be floating (e.g. tf.float32), got tf.int64\n    W0729 03:22:06.179470 140113793476352 backprop.py:842] The dtype of the watched tensor must be floating (e.g. tf.float32), got tf.int64\n\n\n\n```\n# now we split them into global test and the rest\nn_global_te = int(0.2 * n_batches.numpy())\nds_tr = ds_all.skip(n_global_te)\nds_te = ds_all.take(n_global_te)\n```\n\n## Define a GN model\n\n### Fix the dimensions of nodes, edges, and global attributes\n\n\n```\n# define the dimension of nodes, edges, and global attributes\nD_V = 32\nD_E = 32\nD_U = 32\n```\n\n### Featurization of nodes, $f^v$\n\n\n```\nclass f_v(tf.keras.Model):\n    \"\"\" Featurization of nodes.\n    Here we simply featurize atoms using one-hot encoding.\n    \n    \"\"\"\n    def __init__(self, units=D_V):\n        super(f_v, self).__init__()\n        self.d = tf.keras.layers.Dense(units)\n\n    @tf.function\n    def call(self, x):\n        x = tf.one_hot(x, 8)\n        # set shape because Dense doesn't like variation\n        x.set_shape([None, 8]) \n        return self.d(x)\n```\n\n### Featurization of edges, $f^e$\n\nThe idea here is that we seperate the $\\sigma$ and $\\pi$ components of a bond and propagate information seperately.\n\n\n```\nclass f_e(tf.keras.Model):\n    \"\"\" Featurization of edges.\n    Here we split the $\\sigma$ and $\\pi$ component of bonds\n    into two channels, and featurize them seperately.\n    \n    \"\"\"\n    def __init__(\n            self, \n            d_sigma_units=64, \n            d_pi_units=64,\n            units=D_E):\n        \n        super(f_e, self).__init__()\n        self.D_E = D_E\n        \n        # sigma\n        self.d_sigma_0 = tf.Variable(\n            tf.zeros(\n                shape=(1, d_sigma_units),\n                dtype=tf.float32))\n        self.d_sigma_1 = tf.keras.layers.Dense(\n            int(D_E // 2))\n        \n        # pi\n        self.d_pi_0 = tf.keras.layers.Dense(\n            d_pi_units)\n        self.d_pi_1 = tf.keras.layers.Dense(\n            int(D_E // 2))\n        \n    @tf.function\n    def call(self, x):\n        # determine whether there is $\\pi$ component in the bond\n        has_pi = tf.greater(\n            x,\n            tf.constant(1, dtype=tf.float32))\n        \n        # calculate the sigma component of the bond\n        x_sigma = tf.tile(\n            self.d_sigma_1(self.d_sigma_0),\n            [tf.shape(x, tf.int64)[0], 1])\n        \n        # calculate the pi component of the bond\n        x_pi = tf.where(\n            has_pi,\n            \n            # if has pi:\n            self.d_pi_1(\n                self.d_pi_0(\n                    tf.math.subtract(\n                        x,\n                        tf.constant(1, dtype=tf.float32)))),\n            \n            # else:\n            tf.zeros(\n                shape=(D_E // 2, ),\n                dtype=tf.float32))\n        \n        \n        x = tf.concat(\n            [\n                x_sigma,\n                x_pi\n            ],\n            axis=1)\n        \n        \n        return x\n        \n        \n```\n\n### Featurization of global attributes, $f^u$\n\n\n```\nf_u=(lambda atoms, adjacency_map, batched_attr_mask: \\\n    tf.tile(\n        tf.zeros((1, D_U)),\n        [\n             tf.math.count_nonzero(\n                 tf.reduce_any(\n                     batched_attr_mask,\n                     axis=0)),\n             1\n        ]\n    ))\n```\n\n### Update of nodes, $\\phi^v$\n\n\n```\nphi_v = lime.nets.for_gn.ConcatenateThenFullyConnect(\n    (64, 'elu', 64, D_V))\n```\n\n### Update of edges, $\\phi^e$\n\n\n```\nphi_e = lime.nets.for_gn.ConcatenateThenFullyConnect(\n    (64, 'elu', 64, D_E))\n```\n\n### Update of global attributes, $\\phi^u$\n\n\n```\nclass phi_u(tf.keras.Model):\n    def __init__(self, config=(64, 'elu', D_U)):\n        super(phi_u, self).__init__()\n        self.d = lime.nets.for_gn.ConcatenateThenFullyConnect(config)\n\n    @tf.function\n    def call(self, h_u, h_u_0, h_e_bar, h_v_bar):\n        return self.d(h_u, h_u_0, h_e_bar, h_v_bar)\n```\n\nhere the aggregation function are all just sum\n\n### Readout function, $f_r$\n\n\nFinally, we define the readout function, $f_r$, which is applied after all rounds of propagation. \n\nTo deal with the problem that it is not trivial to directly predict the charge with constraint--charges being summed up to a constant that could be positive, negative, or zero, we optimize the model to predict hardness $s$ and electronegativity$e$, and then calculate the charge by minimizing the second-order Taylor expansion of the contribution of potential energy from charges. We use Lagrange multipliers to analytically give the solution.\n        \n\\begin{align}\n        U({\\bf q})\n        &= \\sum_{i=1}^N \\left[ e_i q_i +  \\frac{1}{2}  s_i q_i^2\\right]\n            - \\lambda \\, \\left( \\sum_{j=1}^N q_j - Q \\right) \\\\\n        &= \\sum_{i=1}^N \\left[\n            (e_i - \\lambda) q_i +  \\frac{1}{2}  s_i q_i^2 \\right\n            ] + Q\n\\end{align}\n\nThis gives us:\n\n\\begin{align}\n        q_i^*\n        &= - e_i s_i^{-1}\n        + \\lambda s_i^{-1} \\\\\n        &= - e_i s_i^{-1}\n        + s_i^{-1} \\frac{\n            Q +\n             \\sum\\limits_{i=1}^N e_i \\, s_i^{-1}\n            }{\\sum\\limits_{j=1}^N s_j^{-1}}\n\\end{align}\n\n        \n\n\nFirstly, we define a function to analytically give us this solution.\n\n\n```\n@tf.function\ndef get_charges(e, s, Q):\n    \"\"\" Solve the function to get the absolute charges of atoms in a\n    molecule from parameters.\n\n    Parameters\n    ----------\n    e : tf.Tensor, dtype = tf.float32, shape = (34, ),\n        electronegativity.\n    s : tf.Tensor, dtype = tf.float32, shape = (34, ),\n        hardness.\n    Q : tf.Tensor, dtype = tf.float32, shape=(),\n        total charge of a molecule.\n\n    We use Lagrange multipliers to analytically give the solution.\n\n    $$\n\n    U({\\bf q})\n    &= \\sum_{i=1}^N \\left[ e_i q_i +  \\frac{1}{2}  s_i q_i^2\\right]\n        - \\lambda \\, \\left( \\sum_{j=1}^N q_j - Q \\right) \\\\\n    &= \\sum_{i=1}^N \\left[\n        (e_i - \\lambda) q_i +  \\frac{1}{2}  s_i q_i^2 \\right\n        ] + Q\n\n    $$\n\n    This gives us:\n\n    $$\n\n    q_i^*\n    &= - e_i s_i^{-1}\n    + \\lambda s_i^{-1} \\\\\n    &= - e_i s_i^{-1}\n    + s_i^{-1} \\frac{\n        Q +\n         \\sum\\limits_{i=1}^N e_i \\, s_i^{-1}\n        }{\\sum\\limits_{j=1}^N s_j^{-1}}\n\n    $$\n\n    \"\"\"\n\n    return tf.math.add(\n        tf.math.multiply(\n            tf.math.negative(\n                e),\n            tf.math.pow(\n                s,\n                -1)),\n        \n        tf.math.multiply(\n            tf.math.pow(\n                s,\n                -1),\n            tf.math.divide(\n                tf.math.add(\n                    Q,\n                    tf.reduce_sum(\n                        tf.math.multiply(\n                            e,\n                            tf.math.pow(\n                                s,\n                                -1)))),\n                tf.reduce_sum(\n                    tf.math.pow(\n                        s,\n                        -1)))))\n```\n\nOne thing worth noting is that, here in each batch we have many molecules, with sum function, we need to seperate them.\n\n\n```\n@tf.function\ndef get_q_i_hat_total_per_mol(e, s, Qs, attr_in_mol):\n    \"\"\" Calculate the charges per molecule based on \n    `attr_in_mol`.\n    \n    \"\"\"\n    attr_in_mol.set_shape([None, None])\n    \n    attr_in_mol = tf.boolean_mask(\n        attr_in_mol,\n        tf.reduce_any(\n            attr_in_mol,\n            axis=1),\n        axis=0)\n\n    attr_in_mol = tf.boolean_mask(\n        attr_in_mol,\n        tf.reduce_any(\n            attr_in_mol,\n            axis=0),\n    axis=1)\n\n    q_i = tf.tile(\n        tf.expand_dims(\n            tf.constant(\n                0,\n                dtype=tf.float32),\n            0),\n        [tf.shape(attr_in_mol, tf.int64)[0]])\n    \n    def loop_body(q_i, idx, \n            e=e, \n            s=s, \n            Qs=Qs, \n            attr_in_mol=attr_in_mol):\n        \n        # get attr\n        _attr_in_mol = attr_in_mol[:, idx]\n        \n        # get the attributes of each molecule\n        _Qs = Qs[idx]\n        \n        _e = tf.boolean_mask(\n            e,\n            _attr_in_mol)\n        \n        _s = tf.boolean_mask(\n            s,\n            _attr_in_mol)\n        \n        _idxs = tf.where(_attr_in_mol)\n        \n        # update\n        q_i = tf.tensor_scatter_nd_update(\n            q_i,\n        \n            # idxs\n            _idxs,\n        \n            # update\n            tf.reshape(\n                    get_charges(\n                        _e,\n                        _s,\n                        _Qs),\n                [-1]))\n        \n        return q_i, tf.add(idx, tf.constant(1, dtype=tf.int64))\n    \n    idx = tf.constant(0, dtype=tf.int64)\n    \n    # loop_body(q_i, idx)\n    \n    \n    q_i, idx = tf.while_loop(\n        lambda _, idx: tf.less(\n            idx,\n            tf.shape(attr_in_mol, tf.int64)[1]),\n    \n        loop_body,\n        \n        [q_i, idx])\n    \n    \n    return q_i\n         \n    \n```\n\nWe define the readout function accordingly.\n\n\n```\nclass f_r(tf.keras.Model):\n    \"\"\" Readout function.\n    \"\"\"\n    \n    def __init__(self, units=128):\n        super(f_r, self).__init__()\n        self.d_e_0 = tf.keras.layers.Dense(units)\n        self.d_s_0 = tf.keras.layers.Dense(units)\n        self.d_e_1 = tf.keras.layers.Dense(1)\n        self.d_s_1 = tf.keras.layers.Dense(1)\n    \n    @tf.function\n    def call(self,\n            h_e, h_v, h_u,\n            h_e_history, h_v_history, h_u_history,\n            atom_in_mol, bond_in_mol):\n        \n        # although this could take many many arguments,\n        # we only take $h_e$ for now\n        e = self.d_e_1(self.d_e_0(h_v))\n        s = self.d_s_1(self.d_s_0(h_v))\n        \n        return e, s\n        \n        \n```\n\n### Put everything together to define a complete graph net.\n\n\n```\ngn = gin.probabilistic.gn.GraphNet(\n    f_e=f_e(),\n    f_v=f_v(),\n    f_u=f_u,\n    phi_e=phi_e,\n    phi_v=phi_v,\n    phi_u=phi_u(),\n    f_r=f_r())\n```\n\n## Training\n\n### Define optimizer and number of epochs\n\n\n```\noptimizer = tf.keras.optimizers.Adam(1e-4)\nN_EPOCHS = 10\n```\n\n### Helper function to calculate per-molecule total charge\n\n\n```\n@tf.function\ndef get_q_total_per_mol(q_i, attr_in_mol):\n    # attr_in_mol.set_shape([None, None])\n    \n    q_i = tf.boolean_mask(\n        q_i,\n        tf.reduce_any(\n            attr_in_mol,\n            axis=1))\n    \n    attr_in_mol = tf.boolean_mask(\n        attr_in_mol,\n        tf.reduce_any(\n            attr_in_mol,\n            axis=1),\n        axis=0)\n\n    attr_in_mol = tf.boolean_mask(\n        attr_in_mol,\n        tf.reduce_any(\n            attr_in_mol,\n            axis=0),\n    axis=1)\n    \n    attr_in_mol = tf.where(\n        attr_in_mol,\n    \n        tf.ones_like(\n            attr_in_mol,\n            dtype=tf.float32),\n    \n        tf.zeros_like(\n            attr_in_mol,\n            dtype=tf.float32))\n    \n    q_per_mol = tf.reduce_sum(\n        tf.multiply(\n            attr_in_mol,\n            tf.tile(\n                tf.expand_dims(\n                        q_i,\n                        1),\n                [\n                    1,\n                    tf.shape(attr_in_mol, tf.int64)[1]\n                ])),\n        axis=0)\n    \n    return q_per_mol\n    \n    \n```\n\n### start training\n\n\n```\n# @tf.function\ndef train():\n    losses = tf.constant([-1], dtype=tf.float32)\n    for dummy_idx in range(N_EPOCHS):\n        for atoms, adjacency_map, atom_in_mol, bond_in_mol, q_i, attr_in_mol \\\n            in ds_tr:\n            with tf.GradientTape() as tape:\n                Qs = get_q_total_per_mol(q_i, attr_in_mol)\n                \n                e, s = gn(\n                    atoms, adjacency_map, atom_in_mol, bond_in_mol, attr_in_mol)\n                \n                e = tf.boolean_mask(\n                    e,\n                    tf.reduce_any(\n                        attr_in_mol,\n                        axis=1))\n\n                s = tf.boolean_mask(\n                    s,\n                    tf.reduce_any(\n                        attr_in_mol,\n                        axis=1))\n\n                q_i_hat = get_q_i_hat_total_per_mol(\n                                    e, s, Qs, attr_in_mol)\n                \n                q_i = tf.boolean_mask(\n                    q_i,\n                    tf.reduce_any(\n                        attr_in_mol,\n                        axis=1))\n                \n                loss = tf.losses.mean_squared_error(\n                    q_i,\n                    q_i_hat)\n\n            variables = gn.variables\n            grad = tape.gradient(loss, variables)\n            optimizer.apply_gradients(\n                zip(grad, variables))\n\n            losses = tf.concat([\n                losses,\n                [loss],\n\n            ],\n            axis=0)\n            \n    return losses, gn\n\nlosses, gn = train()\n```\n\n\n```\nlosses = losses[1:]\n```\n\n## Inspect Learning Curve\n\n\n```\nfrom matplotlib import pyplot as plt\n```\n\n\n```\nplt.style.use('ggplot')\nplt.rc('font', family='serif')\n\n\nplt.figure(figsize=(10, 5))\nplt.plot(losses.numpy())\nplt.xlabel('# Training Batch', fontsize=14)\nplt.ylabel('MSE', fontsize=14)\n```\n\n### Test on Training Set\n\n\n```\nq_i_true = tf.constant([-1], dtype=tf.float32)\nq_i_pred = tf.constant([-1], dtype=tf.float32)\n\nfor atoms, adjacency_map, atom_in_mol, bond_in_mol, q_i, attr_in_mol \\\n    in ds_tr:\n\n    Qs = get_q_total_per_mol(q_i, attr_in_mol)\n    e, s = gn(\n        atoms, adjacency_map, atom_in_mol, bond_in_mol, attr_in_mol)\n    e = tf.boolean_mask(\n        e,\n        tf.reduce_any(\n            attr_in_mol,\n            axis=1))\n\n    s = tf.boolean_mask(\n        s,\n        tf.reduce_any(\n            attr_in_mol,\n            axis=1))\n\n    q_i_hat = get_q_i_hat_total_per_mol(\n                        e, s, Qs, attr_in_mol)\n\n    q_i = tf.boolean_mask(\n        q_i,\n        tf.reduce_any(\n            attr_in_mol,\n            axis=1))\n\n    q_i_true = tf.concat(\n        [\n            q_i_true,\n            q_i\n        ],\n        axis=0)\n\n    q_i_pred = tf.concat(\n        [\n            q_i_pred,\n            q_i_hat\n        ],\n        axis=0)\n\n\n```\n\n\n```\nq_i_true = q_i_true[1:]\nq_i_pred = q_i_pred[1:]\n```\n\n\n```\nplt.figure(figsize=(40, 40))\nfig, ax = plt.subplots()\n\nax.set_xlim([-2.0, 2.0])\nax.set_ylim([-2.0, 2.0])\n\nax.scatter(\n    q_i_true.numpy(),\n    q_i_pred.numpy(),\n    alpha=0.8)\n\nax.tick_params(labelsize=10)\nax.set_xticks(np.arange(-2.0, 2.0, 1))\nax.set_yticks(np.arange(-2.0, 2.0, 1))\nax.set_xlabel('$q_\\mathtt{true}$', fontsize=14)\nax.set_ylabel('$q_\\mathtt{pred}$', fontsize=14)\nax.set_title('Predicted Charges on Training Set')\n```\n\n\n```\nprint(\"MSE on training set is %s \" % tf.losses.mean_squared_error(\n    q_i_true,\n    q_i_pred).numpy())\n```\n\n    MSE on training set is 0.004874341 \n\n\n\n```\nfrom sklearn import *\nprint(\"$R^2$ on training set is %s \" % metrics.r2_score(\n    q_i_true,\n    q_i_pred))\n```\n\n    $R^2$ on training set is 0.9375542641732115 \n\n\n\n```\nimport scipy\nprint('Pearson R on training set is %s ' % scipy.stats.pearsonr(q_i_true, q_i_pred)[0])\n```\n\n    Pearson R on training set is 0.9683551843312522 \n\n\n\n```\nprint('Spearman R on training set is %s ' % scipy.stats.spearmanr(\n    q_i_true, q_i_pred)[0])\n```\n\n    Spearman R on training set is 0.9154855342847189 \n\n\n### Test on test set\n\n\n```\nq_i_true = tf.constant([-1], dtype=tf.float32)\nq_i_pred = tf.constant([-1], dtype=tf.float32)\n\nfor atoms, adjacency_map, atom_in_mol, bond_in_mol, q_i, attr_in_mol \\\n    in ds_te:\n\n    Qs = get_q_total_per_mol(q_i, attr_in_mol)\n    e, s = gn(\n        atoms, adjacency_map, atom_in_mol, bond_in_mol, attr_in_mol)\n    e = tf.boolean_mask(\n        e,\n        tf.reduce_any(\n            attr_in_mol,\n            axis=1))\n\n    s = tf.boolean_mask(\n        s,\n        tf.reduce_any(\n            attr_in_mol,\n            axis=1))\n\n    q_i_hat = get_q_i_hat_total_per_mol(\n                        e, s, Qs, attr_in_mol)\n\n    q_i = tf.boolean_mask(\n        q_i,\n        tf.reduce_any(\n            attr_in_mol,\n            axis=1))\n\n    q_i_true = tf.concat(\n        [\n            q_i_true,\n            q_i\n        ],\n        axis=0)\n\n    q_i_pred = tf.concat(\n        [\n            q_i_pred,\n            q_i_hat\n        ],\n        axis=0)\n\n\n\n```\n\n\n```\nq_i_true = q_i_true[1:]\nq_i_pred = q_i_pred[1:]\n```\n\n\n```\nplt.figure(figsize=(40, 40))\nfig, ax = plt.subplots()\n\nax.set_xlim([-2.0, 2.0])\nax.set_ylim([-2.0, 2.0])\n\nax.scatter(\n    q_i_true.numpy(),\n    q_i_pred.numpy(),\n    alpha=0.8)\n\nax.tick_params(labelsize=10)\nax.set_xticks(np.arange(-2.0, 2.0, 1))\nax.set_yticks(np.arange(-2.0, 2.0, 1))\nax.set_xlabel('$q_\\mathtt{true}$', fontsize=14)\nax.set_ylabel('$q_\\mathtt{pred}$', fontsize=14)\nax.set_title('Predicted Charges on Test Set')\n```\n\n\n```\nprint(\"MSE on test set is %s \" % tf.losses.mean_squared_error(\n    q_i_true,\n    q_i_pred).numpy())\n```\n\n    MSE on test set is 0.006685592 \n\n\n\n```\nfrom sklearn import *\nprint(\"$R^2$ on test set is %s \" % metrics.r2_score(\n    q_i_true,\n    q_i_pred))\n```\n\n    $R^2$ on test set is 0.9124353801798808 \n\n\n\n```\nimport scipy\nprint('Pearson R on test set is %s ' % scipy.stats.pearsonr(q_i_true, q_i_pred)[0])\n```\n\n    Pearson R on test set is 0.9569017357114656 \n\n\n\n```\nprint('Spearman R on test set is %s ' % scipy.stats.spearmanr(\n    q_i_true, q_i_pred)[0])\n```\n\n    Spearman R on test set is 0.9164685068765558 \n\n\n\n```\n\n```\n", "meta": {"hexsha": "ed70d9503f8cbe779dd93e877447e5688e0d90fd", "size": 123400, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lime/scripts/notebooks/190728_yuanqing_gn_with_gru_on_sereina_riniker_dataset.ipynb", "max_stars_repo_name": "choderalab/gin", "max_stars_repo_head_hexsha": "9082431d8b664699a898c1e2fa490a18737d6e2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2019-07-20T22:37:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T07:13:56.000Z", "max_issues_repo_path": "lime/scripts/notebooks/190728_yuanqing_gn_with_gru_on_sereina_riniker_dataset.ipynb", "max_issues_repo_name": "choderalab/gin", "max_issues_repo_head_hexsha": "9082431d8b664699a898c1e2fa490a18737d6e2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-05-10T05:29:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T00:15:05.000Z", "max_forks_repo_path": "lime/scripts/notebooks/190728_yuanqing_gn_with_gru_on_sereina_riniker_dataset.ipynb", "max_forks_repo_name": "kuano-ai/gimlet", "max_forks_repo_head_hexsha": "9082431d8b664699a898c1e2fa490a18737d6e2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-08-09T17:30:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T13:27:46.000Z", "avg_line_length": 70.5142857143, "max_line_length": 28364, "alphanum_fraction": 0.7210048622, "converted": true, "num_tokens": 7199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713673161914675, "lm_q2_score": 0.0627892125430318, "lm_q1q2_score": 0.02870325540286149}}
{"text": "<center></center>\n<h1> Example of a spectral analysis with 3ML</h1>\n<br/>\nGiacomo Vianello (Stanford University)\n<a href=\"mailto:giacomov@stanford.edu\">giacomov@stanford.edu</a>\n\n<h2>IPython Notebook setup. </h2>\nThis is needed only if you are using the <a href=http://ipython.org/notebook.html>IPython Notebook</a> on your own computer, it is NOT needed if you are on threeml.stanford.edu.\nThis line will activate the support for inline display of matplotlib images:\n\n\n```python\nimport matplotlib\n\n%matplotlib inline\n```\n\n<h2>Import 3ML and see the available plug-ins</h2>\n\n\n```python\nfrom threeML import *\n```\n\n    Configuration read from /home/giacomov/.threeML/threeML_config.yml\n    Loading BKGE...\n    Success!\n\n    \n    WARNING CppInterfaceNotAvailable: The C/C++ wrapper is not available. You will not be able to use plugins which require it.\n    \n    \n    WARNING CannotImportPlugin: Could not import plugin /home/giacomov/software/canopy-env/lib/python2.7/site-packages/threeML-v0.2.0-py2.7.egg/threeML/plugins/SherpaLike.py. Do you have the relative instrument software installed and configured?\n    \n\n\n    \n\n\n    \n    WARNING CannotImportPlugin: Could not import plugin /home/giacomov/software/canopy-env/lib/python2.7/site-packages/threeML-v0.2.0-py2.7.egg/threeML/plugins/HAWCLike.py. Do you have the relative instrument software installed and configured?\n    \n\n\n\n```python\nget_available_plugins()\n```\n\n    Available plugins:\n    \n    FermiGBMLike for Fermi GBM (all detectors)\n    FermiLATLike for Fermi LAT (standard classes)\n    SwiftXRTLike for Swift XRT\n    GenericOGIPLike for All OGIP-compliant instruments\n\n\n<h2>Define some general features for the source of interest</h2>\nHere we define a name and the coordinates (Equatorial J2000). In this case, we are analyzing a GRB:\n\n\n```python\n#The following definitions are for convenience\n\ntriggerName = 'bn090217206'\nra = 204.9\ndec = -8.4\n\n#Data are in the current directory\n\ndatadir = os.path.abspath('.')\n```\n\n<h2>Setup the LAT plugin and data</h2>\nHere we instanciate a plugin to handle Fermi/LAT data (if you have the Fermi Science Tools installed, and hence the LAT plugin is available):\n\n\n```python\n#LAT data are under ./data.\n#These files have been downloaded from the LAT public data server,\n#and have been prepared for the analysis with the official Fermi software.\n#In the future, both these operations will be handled by the LAT plugin\n\neventFile = os.path.join( datadir, 'lat', 'gll_ft1_tr_bn090217206_v00_filt.fit' )\nft2File   = os.path.join( datadir, 'lat', 'gll_ft2_tr_bn090217206_v00.fit' )\n\n#The following files have been prepared with LAT standard software. In the future, \n#it will be possible to produce them directly using the plugin\n\nexpomap = os.path.join( datadir, 'lat', 'gll_ft1_tr_bn090217206_v00_filt_expomap.fit' )\nltcube  = os.path.join( datadir, 'lat', 'gll_ft1_tr_bn090217206_v00_filt_ltcube.fit' )\n\n#Let's create an instance of the plugin, if it is available\n\nif is_plugin_available(\"FermiLATLike\"):\n    \n    LAT = FermiLATLike( \"LAT\", eventFile, ft2File, ltcube, 'unbinned', expomap )\n\nelse:\n    \n    print(\"Plugin for Fermi/LAT is not available\")\n```\n\n<h2>Setup of GBM data</h2>\nHere we create 3 instances of the plugin which handle GBM data, for 3 different GBM detectors (NaI6, NaI9, BGO1). We also define the channels (or energies) we want to use, by using setActiveMeasurements():\n\n\n```python\n2.3#The .pha, .bak and .rsp files have been prepared with the Fermi\n#official software. In the future it will be possible to create\n#them directly from the plugin\n\n#Create an instance of the GBM plugin for each detector\n#Data files\nobsSpectrum = os.path.join( datadir, \"bn090217206_n6_srcspectra.pha{1}\" )\nbakSpectrum = os.path.join( datadir, \"bn090217206_n6_bkgspectra.bak{1}\" )\nrspFile     = os.path.join( datadir, \"bn090217206_n6_weightedrsp.rsp{1}\" )\n\n#Plugin instance\nNaI6 = FermiGBMLike( \"NaI6\", obsSpectrum, bakSpectrum, rspFile )\n\n#Choose energies to use (in this case, I exclude the energy\n#range from 30 to 40 keV to avoid the k-edge, as well as anything above\n#950 keV, where the calibration is uncertain)\nNaI6.setActiveMeasurements( \"10.0-30.0\", \"40.0-950.0\" )\n\n#Now repeat for the other GBM detectors\n\nobsSpectrum = os.path.join( datadir, \"bn090217206_n9_srcspectra.pha{1}\" )\nbakSpectrum = os.path.join( datadir, \"bn090217206_n9_bkgspectra.bak{1}\" )\nrspFile     = os.path.join( datadir, \"bn090217206_n9_weightedrsp.rsp{1}\" )\n#Plugin instance\nNaI9 = FermiGBMLike( \"NaI9\", obsSpectrum, bakSpectrum, rspFile )\n#Choose chanels to use\nNaI9.setActiveMeasurements( \"10.0-30.0\", \"40.0-950.0\" )\n\n\nobsSpectrum = os.path.join( datadir, \"bn090217206_b1_srcspectra.pha{1}\" )\nbakSpectrum = os.path.join( datadir, \"bn090217206_b1_bkgspectra.bak{1}\" )\nrspFile     = os.path.join( datadir, \"bn090217206_b1_weightedrsp.rsp{1}\" )\n#Plugin instance\nBGO1 = FermiGBMLike( \"BGO1\", obsSpectrum, bakSpectrum, rspFile )\n#Choose chanels to use (in this case, from 200 keV to 10 MeV)\nBGO1.setActiveMeasurements( \"200-10000\" )\n```\n\n    Now using 117 channels out of 128\n    Now using 115 channels out of 128\n    Now using 88 channels out of 128\n\n\n<h2>Create a dataList object to collect all our data</h2>\n\n\n```python\n#This declares which data we want to use. In our case, all that we have already created.\n\ndata_list = DataList( NaI6, NaI9, BGO1, LAT )\n```\n\n<h2>Define our model</h2>\nHere we define our spectral model, as well as demonstrate some way to manipulate the parameters of the spectral model.\n\n\n```python\n#Let's use a Band model, a phenomenological model typically used for GRBs\nband = Band()\n\n#Let's have a look at what we just created\nprint(band)\n```\n\n    Spectral model: Band function [Band et al. 1993]\n    Formula:\n    \n\n\n\n\n        \\[f(E) = \\left\\{ \\begin{eqnarray}\n        K \\left(\\frac{E}{100 \\mbox{ keV}}\\right)^{\\alpha} & \\exp{\\left(\\frac{-E}{E_{c}}\\right)} & \\mbox{ if } E < (\\alpha-\\beta)E_{c} \\\\\n        K \\left[ (\\alpha-\\beta)\\frac{E_{c}}{100}\\right]^{\\alpha-\\beta}\\left(\\frac{E}{100 \\mbox{ keV}}\\right)^{\\beta} & \\exp{(\\beta-\\alpha)} & \\mbox{ if } E \\ge (\\alpha-\\beta)E_{c}\n        \\end{eqnarray}\n        \\right.\n        \\]\n        \n\n\n    \n    Current parameters:\n    \n\n\n\n<table id=\"table121618128\">\n<thead><tr><th>Name</th><th>Value</th><th>Minimum</th><th>Maximum</th><th>Delta</th><th>Status</th><th>Unit</th><th>Prior</th></tr></thead>\n<tr><td>alpha</td><td>-1.0</td><td>-5.0</td><td>10.0</td><td>0.1</td><td>free</td><td></td><td>UniformPrior</td></tr>\n<tr><td>beta</td><td>-2.0</td><td>-10.0</td><td>0.0</td><td>0.1</td><td>free</td><td></td><td>UniformPrior</td></tr>\n<tr><td>E0</td><td>500.0</td><td>10.0</td><td>100000.0</td><td>10.0</td><td>free</td><td>keV</td><td>UniformPrior</td></tr>\n<tr><td>K</td><td>1.0</td><td>0.0001</td><td>1000.0</td><td>0.1</td><td>free</td><td></td><td>LogUniformPrior</td></tr>\n</table>\n\n\n    \n\n\n\n```python\n#We can modify the initial values for the parameters, \n#as well as their bounds and the delta,\n#like this:\n\nband.alpha = -0.8\nband.alpha.setBounds(-2,2)\nband.alpha.setDelta(0.08)\n\n#We could also use this:\n\n# band.alpha.fix()\n\n#to fix a parameter\n\n#Let's verify that the changes have been applied\nprint(band)\n```\n\n    Spectral model: Band function [Band et al. 1993]\n    Formula:\n    \n\n\n\n\n        \\[f(E) = \\left\\{ \\begin{eqnarray}\n        K \\left(\\frac{E}{100 \\mbox{ keV}}\\right)^{\\alpha} & \\exp{\\left(\\frac{-E}{E_{c}}\\right)} & \\mbox{ if } E < (\\alpha-\\beta)E_{c} \\\\\n        K \\left[ (\\alpha-\\beta)\\frac{E_{c}}{100}\\right]^{\\alpha-\\beta}\\left(\\frac{E}{100 \\mbox{ keV}}\\right)^{\\beta} & \\exp{(\\beta-\\alpha)} & \\mbox{ if } E \\ge (\\alpha-\\beta)E_{c}\n        \\end{eqnarray}\n        \\right.\n        \\]\n        \n\n\n    \n    Current parameters:\n    \n\n\n\n<table id=\"table121618000\">\n<thead><tr><th>Name</th><th>Value</th><th>Minimum</th><th>Maximum</th><th>Delta</th><th>Status</th><th>Unit</th><th>Prior</th></tr></thead>\n<tr><td>alpha</td><td>-0.8</td><td>-2.0</td><td>2.0</td><td>0.08</td><td>free</td><td></td><td>UniformPrior</td></tr>\n<tr><td>beta</td><td>-2.0</td><td>-10.0</td><td>0.0</td><td>0.1</td><td>free</td><td></td><td>UniformPrior</td></tr>\n<tr><td>E0</td><td>500.0</td><td>10.0</td><td>100000.0</td><td>10.0</td><td>free</td><td>keV</td><td>UniformPrior</td></tr>\n<tr><td>K</td><td>1.0</td><td>0.0001</td><td>1000.0</td><td>0.1</td><td>free</td><td></td><td>LogUniformPrior</td></tr>\n</table>\n\n\n    \n\n\n\n```python\n#The GRB is a point source. Let's create its model. We will use triggerName as\n#its name, and the position declared at the beginning, as well as the band\n#model we just modified as its spectrum\nGRB = PointSource( triggerName, ra, dec, band )\n\n#Let's have a look at what we just created\nprint(GRB)\n```\n\n    Spatial model: Point source\n    Formula:\n    \n\n\n\n\\begin{equation}f(RA',Dec') = \\delta(RA'-RA)\\delta(Dec'-Dec)\\end{equation}\n\n\n    \n    Spectral model: Band function [Band et al. 1993]\n    \n    Current parameters:\n    \n\n\n\n<table id=\"table121618128\">\n<thead><tr><th>Name</th><th>Value</th><th>Minimum</th><th>Maximum</th><th>Delta</th><th>Status</th><th>Unit</th></tr></thead>\n<tr><td>RA</td><td>204.9</td><td>0.0</td><td>360.0</td><td>0.01</td><td>fixed</td><td>deg</td></tr>\n<tr><td>Dec</td><td>-8.4</td><td>-90.0</td><td>90.0</td><td>0.01</td><td>fixed</td><td>deg</td></tr>\n<tr><td>alpha</td><td>-0.8</td><td>-2.0</td><td>2.0</td><td>0.08</td><td>free</td><td></td></tr>\n<tr><td>beta</td><td>-2.0</td><td>-10.0</td><td>0.0</td><td>0.1</td><td>free</td><td></td></tr>\n<tr><td>E0</td><td>500.0</td><td>10.0</td><td>100000.0</td><td>10.0</td><td>free</td><td>keV</td></tr>\n<tr><td>K</td><td>1.0</td><td>0.0001</td><td>1000.0</td><td>0.1</td><td>free</td><td></td></tr>\n</table>\n\n\n    \n\n\nNow define the likelihood model. The likelihood model can have as many sources as you need to model your region of interest. In this case we use only one source (the GRB). It is important to note that the background for the different instruments is handled by the respective plugins, and must therefore not be included here.\n\n\n```python\nmodel = LikelihoodModel( GRB )\n\n#We could define as many sources (pointlike or extended) as we need, and\n#add them to the model as:\n# model = LikelihoodModel ( GRB, OtherSource, OtherSource2, etc ...)\n\n```\n\n<h2>Create a jointLikelihood object</h2>\n\n\n```python\n#This will create the object which will allow to fit \n#the model.\n\n#We need to pass in the model we want to fit, as well as the\n#data we want to use in the fit (through the datalist created\n#before)\njl = JointLikelihood( model, data_list )\n\n#During initialization, you might see\n#messages from the plugins while they set up their\n#interpretation of the model\n```\n\n<h2>Profile likelihood maximization</h2>\nIf you want to use the profile likelihood, just perform the fit:\n\n\n```python\n#As easy as it gets!\n\nres = jl.fit(pre_fit=True)\n```\n\n    Best fit values:\n    \n\n\n\n<table id=\"table139459472\">\n<thead><tr><th>Name</th><th>Value</th><th>Unit</th></tr></thead>\n<tr><td>alpha_of_bn090217206</td><td>-0.801 +/- 0.029</td><td></td></tr>\n<tr><td>beta_of_bn090217206</td><td>-2.68 +/- 0.07</td><td></td></tr>\n<tr><td>E0_of_bn090217206</td><td>(4.9 +/- 0.4)e+02</td><td>keV</td></tr>\n<tr><td>K_of_bn090217206</td><td>0.0181 +/- 0.0005</td><td></td></tr>\n</table>\n\n\n    \n    NOTE: errors on parameters are approximate. Use get_errors().\n    \n    Nuisance parameters:\n    \n\n\n\n<table id=\"table54529680\">\n<thead><tr><th>Name</th><th>Value</th><th>Unit</th></tr></thead>\n<tr><td>InterCalib_of_NaI6</td><td>1</td><td></td></tr>\n<tr><td>InterCalib_of_NaI9</td><td>1</td><td></td></tr>\n<tr><td>InterCalib_of_BGO1</td><td>1</td><td></td></tr>\n<tr><td>bn090217206-Normalization_of_LAT</td><td>1.0</td><td></td></tr>\n<tr><td>GalacticTemplate-Value_of_LAT</td><td>0.5</td><td></td></tr>\n<tr><td>IsotropicTemplate-Normalization_</td><td>0.5</td><td></td></tr>\n</table>\n\n\n    \n    Correlation matrix:\n    \n\n\n\n<table id=\"table139459216\">\n<tr><td>1.00</td><td>0.17</td><td>-0.92</td><td>0.80</td></tr>\n<tr><td>0.17</td><td>1.00</td><td>-0.25</td><td>0.21</td></tr>\n<tr><td>-0.92</td><td>-0.25</td><td>1.00</td><td>-0.93</td></tr>\n<tr><td>0.80</td><td>0.21</td><td>-0.93</td><td>1.00</td></tr>\n</table>\n\n\n    \n    Minimum of -logLikelihood is: 1361.15417242\n    \n    Contributions to the -logLikelihood at the minimum:\n    \n\n\n\n<table id=\"table139459216\">\n<thead><tr><th>Detector</th><th>-LogL</th></tr></thead>\n<tr><td>NaI6</td><td>512.95</td></tr>\n<tr><td>NaI9</td><td>461.57</td></tr>\n<tr><td>BGO1</td><td>360.08</td></tr>\n<tr><td>LAT</td><td>27.23</td></tr>\n</table>\n\n\n\n```python\n#Now let's compute the errors on the best fit parameters\n\nres = jl.get_errors()\n```\n\n\n<table id=\"table73432336\">\n<thead><tr><th>Name</th><th>Value</th><th>Unit</th></tr></thead>\n<tr><td>alpha_of_bn090217206</td><td>-0.804 -0.024 +0.025</td><td></td></tr>\n<tr><td>beta_of_bn090217206</td><td>-2.67 -0.07 +0.08</td><td></td></tr>\n<tr><td>E0_of_bn090217206</td><td>495.6 -31.8 +33.7</td><td>keV</td></tr>\n<tr><td>K_of_bn090217206</td><td>0.0181 -0.0004 +0.0004</td><td></td></tr>\n</table>\n\n\n\n```python\n#We might also want to look at the profile of the likelihood for\n#each parameter.\n\nres = jl.get_contours('bn090217206','alpha',-0.9,-0.7,20)\n```\n\n\n```python\n#Or we might want to produce a contour plot\n\nres = jl.get_contours('bn090217206','alpha',-0.9,-0.7,20,'bn090217206','beta',-3.0,-2.4,20)\n```\n\n<h2>Full Bayesian analysis</h2>\n<ul><li>\nWe used the model and the data list constructed before, so you need to go up and do those steps if you didn't already.</li></ul>\n\n<ul><li>All the priors for all your parameters are already defined by default, you can check them like:</li></ul>\n\n\n```python\nprint(GRB.spectralModel)\n```\n\n    Spectral model: Band function [Band et al. 1993]\n    Formula:\n    \n\n\n\n\n        \\[f(E) = \\left\\{ \\begin{eqnarray}\n        K \\left(\\frac{E}{100 \\mbox{ keV}}\\right)^{\\alpha} & \\exp{\\left(\\frac{-E}{E_{c}}\\right)} & \\mbox{ if } E < (\\alpha-\\beta)E_{c} \\\\\n        K \\left[ (\\alpha-\\beta)\\frac{E_{c}}{100}\\right]^{\\alpha-\\beta}\\left(\\frac{E}{100 \\mbox{ keV}}\\right)^{\\beta} & \\exp{(\\beta-\\alpha)} & \\mbox{ if } E \\ge (\\alpha-\\beta)E_{c}\n        \\end{eqnarray}\n        \\right.\n        \\]\n        \n\n\n    \n    Current parameters:\n    \n\n\n\n<table id=\"table254045072\">\n<thead><tr><th>Name</th><th>Value</th><th>Minimum</th><th>Maximum</th><th>Delta</th><th>Status</th><th>Unit</th><th>Prior</th></tr></thead>\n<tr><td>alpha</td><td>-0.7</td><td>-2.0</td><td>2.0</td><td>0.08</td><td>free</td><td></td><td>UniformPrior</td></tr>\n<tr><td>beta</td><td>-2.4</td><td>-10.0</td><td>0.0</td><td>0.2</td><td>free</td><td></td><td>UniformPrior</td></tr>\n<tr><td>E0</td><td>380.448997283</td><td>10.0</td><td>100000.0</td><td>50.0</td><td>free</td><td>keV</td><td>UniformPrior</td></tr>\n<tr><td>K</td><td>0.0197134523975</td><td>0.0001</td><td>1000.0</td><td>0.00193069772888</td><td>free</td><td></td><td>LogUniformPrior</td></tr>\n</table>\n\n\n    \n\n\n<li>Define the bayesian analysis in a similar way with which we defined the likelihood analysis:</li>\n\n\n```python\nbayes = BayesianAnalysis(model, data_list)\n```\n\n    \n    Found Isotropic template for irf P7REP_SOURCE_V15: /home/giacomov/GlastExternals/diffuseModels/v2r0/iso_source_v05_rev1.txt\n    \n    Found Galactic template for IRF. P7REP_SOURCE_V15: /home/giacomov/GlastExternals/diffuseModels/v2r0/gll_iem_v05_rev1.fit\n    \n    Cutting the template around the ROI: \n    \n    Center is (1141.87815873,1140.83295959) pixel, (322.797269841,52.6041199485) sky\n    Approximating the X pixel: 1141.87815873 -> 1141\n    Approximating the Y pixel: 1140.83295959 -> 1140\n    X range -> 699 - 1585\n    Y range -> 901 - 1380\n    Input image shape is ([z],y,x) = (30, 1441, 2880)\n\n\n<ul><li>Run the Markov Chain MC and explore the parameter space. For this simple case we assume you have run a likelihood fit before, so that the MCMC starts from a good point in the parameter space. Otherwise, if you are new to Bayesian analysis, be careful about the burn_in time and the convergence of the chain.</li></ul>\n\n\n```python\n# Note that n_samples is the number of samples *per walker*, so you will get n_samples * n_walers samples\n# at the end\n\nsamples = bayes.sample(n_walkers=20,burn_in=100, n_samples=1000)\n```\n\n    Running burn-in of 100 samples...\n    \n     [*********************100%***********************]  100 of 100 completed in 4.7 s\n    \n    Sampling...\n    \n     [*********************100%***********************]  1000 of 1000 completed in 46.2 s\n    Mean acceptance fraction: 0.58775\n\n\n<h3>Getting some useful information from the Bayesian analysis</h3>\nNow that we have our MCMC sample of parameters, we can extract a lot of useful information. We can start by computing the (equal-tail) credible intervals (the Bayesian equivalent of confidence intervals), based on the posterior samples:\n\n\n```python\ncredible_intervals = bayes.get_credible_intervals()\n```\n\n\n<table id=\"table767626320\">\n<thead><tr><th>Name</th><th>Value</th><th>Unit</th></tr></thead>\n<tr><td>bn090217206_of_alpha</td><td>-0.80 -0.04 +0.04</td><td></td></tr>\n<tr><td>bn090217206_of_beta</td><td>-2.27 -0.15 +0.13</td><td></td></tr>\n<tr><td>bn090217206_of_E0</td><td>(4.8 -0.5 +0.6)e+02</td><td>keV</td></tr>\n<tr><td>bn090217206_of_K</td><td>0.0183 -0.0008 +0.0008</td><td></td></tr>\n</table>\n\n\nThe dictionary can be used to access the numbers for later use:\n\n\n```python\n# Get the lower bound, upper bound of the credible interval for alpha and the median\n\nalpha_lower_bound = credible_intervals['bn090217206']['alpha']['lower bound']\n\nalpha_upper_bound = credible_intervals['bn090217206']['alpha']['upper bound']\n\nalpha_median = credible_intervals['bn090217206']['alpha']['median']\n\nprint(\"Credible interval for alpha: %s - %s\" % (alpha_lower_bound, alpha_upper_bound))\nprint(\"Median for alpha: %s\" % alpha_median)\n```\n\n    Credible interval for alpha: -0.840958540453 - -0.751547970667\n    Median for alpha: -0.794744753552\n\n\nYou can also access the samples by using a dictionary access, such as:\n\n\n```python\nalpha_samples = bayes.samples['bn090217206']['alpha']\n```\n\nor get all the samples as a matrix, useful if you want to use third-party software for futher processing:\n\n\n```python\nmy_samples = bayes.raw_samples\n\nprint(my_samples.shape)\n```\n\n    (6000, 4)\n\n\nWe can also easily produce a triangle plot which show all the monodimensional and bidimensional marginal distribution, with the latter being the equivalent of countour plots in frequentist analysis:\n\n\n```python\n# (red lines in the marginal distributions are the priors)\n\ncorner_figure = bayes.corner_plot()\n```\n", "meta": {"hexsha": "9ba29f7e3665271ad240a44f88b1b1be7036cd67", "size": 303810, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/090217206.ipynb", "max_stars_repo_name": "jasonfan1997/threeML", "max_stars_repo_head_hexsha": "21b1c76ad3423f745b9f56413d93ee01d1d5855f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 42, "max_stars_repo_stars_event_min_datetime": "2019-01-10T06:11:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T20:08:37.000Z", "max_issues_repo_path": "examples/090217206.ipynb", "max_issues_repo_name": "jasonfan1997/threeML", "max_issues_repo_head_hexsha": "21b1c76ad3423f745b9f56413d93ee01d1d5855f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 187, "max_issues_repo_issues_event_min_datetime": "2019-01-15T13:21:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:15:55.000Z", "max_forks_repo_path": "examples/090217206.ipynb", "max_forks_repo_name": "jasonfan1997/threeML", "max_forks_repo_head_hexsha": "21b1c76ad3423f745b9f56413d93ee01d1d5855f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 32, "max_forks_repo_forks_event_min_datetime": "2019-01-14T10:24:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T10:09:59.000Z", "avg_line_length": 253.5976627713, "max_line_length": 199128, "alphanum_fraction": 0.8984101906, "converted": true, "num_tokens": 6200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.06371499202962878, "lm_q1q2_score": 0.02863304812309604}}
{"text": "```\nfrom google.colab import drive\ndrive.mount('/content/drive/')\n```\n\n    Drive already mounted at /content/drive/; to attempt to forcibly remount, call drive.mount(\"/content/drive/\", force_remount=True).\n\n\n\n```\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n```\n\n\n```\ndf = pd.read_csv(\"/content/drive/MyDrive/ADM/HM2/steam_reviews.csv\",usecols=[\"app_id\",\"app_name\",\"review_id\",\"language\",\"timestamp_created\",\"timestamp_updated\",\"recommended\",\"votes_helpful\",\"votes_funny\",\"weighted_vote_score\",\"comment_count\",\"steam_purchase\",\"received_for_free\",\"written_during_early_access\",\"author.steamid\",\"author.num_games_owned\",\"author.num_reviews\",\"author.playtime_forever\",\"author.playtime_last_two_weeks\",\"author.playtime_at_review\",\"author.last_played\"])\n```\n\n\n```\ndf1 = pd.read_csv(\"/content/drive/MyDrive/ADM/HM2/steam_reviews_bonus_1.csv\",usecols=[\"app_id\",\"app_name\",\"review_id\",\"language\",\"timestamp_created\",\"timestamp_updated\",\"recommended\",\"votes_helpful\",\"votes_funny\",\"weighted_vote_score\",\"comment_count\",\"steam_purchase\",\"received_for_free\",\"written_during_early_access\",\"author.steamid\",\"author.num_games_owned\",\"author.num_reviews\",\"author.playtime_forever\",\"author.playtime_last_two_weeks\",\"author.playtime_at_review\",\"author.last_played\"])\n```\n\n    /usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py:2718: DtypeWarning: Columns (8,9,10,14,15,16) have mixed types.Specify dtype option on import or set low_memory=False.\n      interactivity=interactivity, compiler=compiler, result=result)\n\n\n\n```\ndf2 = pd.read_csv(\"/content/drive/MyDrive/ADM/HM2/steam_reviews_bonus_2.csv\",usecols=[\"app_id\",\"app_name\",\"review_id\",\"language\",\"timestamp_created\",\"timestamp_updated\",\"recommended\",\"votes_helpful\",\"votes_funny\",\"weighted_vote_score\",\"comment_count\",\"steam_purchase\",\"received_for_free\",\"written_during_early_access\",\"author.steamid\",\"author.num_games_owned\",\"author.num_reviews\",\"author.playtime_forever\",\"author.playtime_last_two_weeks\",\"author.playtime_at_review\",\"author.last_played\"])\n```\n\n    /usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py:2718: DtypeWarning: Columns (8,9,10,14,15,16) have mixed types.Specify dtype option on import or set low_memory=False.\n      interactivity=interactivity, compiler=compiler, result=result)\n\n\n\n```\nlista = [df,df1,df2]\ndf = pd.concat(lista)\n```\n\n\n```\n# we use this code to delete df1 and df2 to free out the RAM\ndel df1\ndel df2\nimport gc\ngc.collect()\n```\n\n\n\n\n    99\n\n\n\n# Data cleaning\n\nHere we do a first cleaning of the data to make them more readable and usefull for the analysis \n\n\n```\n# We found some empty rows with all the cells that have the value 1 so we delete them\ndf.drop(df[df['app_id'] == 1.0].index , inplace = True)\n```\n\n\n```\n# We found some cells that have a boolean value (True/False) instead the app_name, so we delete these rows\ndf.drop(df[df['app_name'].isin([\"True\",\"False\"])].index , inplace = True)\n```\n\n\n```\n# as we can see in timestamp_created we have 8 empty cell\npd.isnull(df['timestamp_created']).value_counts()\n```\n\n\n```\n# we fill all the cells that have NA values in timestamp_created\ndf['timestamp_created'] = df['timestamp_created'].fillna(0)\ndf['timestamp_updated'] = df['timestamp_updated'].fillna(0)\n```\n\n\n```\n# the three dataset have different type values in timestamp_updated but we need only numeric values\ndf['timestamp_updated'] = pd.to_numeric(df['timestamp_updated'] , errors='coerce')\n```\n\n\n```\n# we found a cell with weighted_vote_score > 1 but this value must be in the range [0,1] \ndf[df['weighted_vote_score'] > 1] = 1\n# we also found some cells with NA values\ndf['weighted_vote_score'] = df['weighted_vote_score'].fillna(0)\n```\n\n\n```\n# we found some strings in steam_purchase so we replace these with booleans values\ndf[\"steam_purchase\"] = df[\"steam_purchase\"].replace([\"True\", \"False\"], [True, False])\n```\n\n\n```\n# We do the same thing of the previous step beacause in the column recommended we have some strings, and we would like to have booleans instead\ndf[\"recommended\"] = df[\"recommended\"].replace([\"True\", \"False\"], [True, False])\n```\n\n\n```\n# author.steamid must be an integer\ndf['author.steamid'] = np.floor(pd.to_numeric(df['author.steamid'], errors='coerce')).astype('Int64')\n```\n\n\n```\n# We convert each cell in 'language' in a string, because with the 2 new dataset there are also integers values\ndf['language'] = df['language'].astype(str)\n```\n\n\n```\ndf.shape #We can clearly see that we are going to analyse a very biog dataset.\n```\n\n\n\n\n    (38747379, 21)\n\n\n\n#REQ 1\n\nIn the follwing line we can see all the columns names, before the analysis it\u2019s important to know and understand all the column of the dataset.\n\n\n```\ndf.columns \n```\n\n\n\n\n    Index(['app_id', 'app_name', 'review_id', 'language', 'timestamp_created',\n           'timestamp_updated', 'recommended', 'votes_helpful', 'votes_funny',\n           'weighted_vote_score', 'comment_count', 'steam_purchase',\n           'received_for_free', 'written_during_early_access', 'author.steamid',\n           'author.num_games_owned', 'author.num_reviews',\n           'author.playtime_forever', 'author.playtime_last_two_weeks',\n           'author.playtime_at_review', 'author.last_played'],\n          dtype='object')\n\n\n\n\n```\ndf.info() # We see all the differernt type of the columns\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    Int64Index: 38747357 entries, 0 to 7000003\n    Data columns (total 21 columns):\n     #   Column                          Dtype  \n    ---  ------                          -----  \n     0   app_id                          float64\n     1   app_name                        object \n     2   review_id                       int64  \n     3   language                        object \n     4   timestamp_created               float64\n     5   timestamp_updated               object \n     6   recommended                     float64\n     7   votes_helpful                   float64\n     8   votes_funny                     float64\n     9   weighted_vote_score             float64\n     10  comment_count                   float64\n     11  steam_purchase                  object \n     12  received_for_free               object \n     13  written_during_early_access     object \n     14  author.steamid                  float64\n     15  author.num_games_owned          float64\n     16  author.num_reviews              float64\n     17  author.playtime_forever         float64\n     18  author.playtime_last_two_weeks  float64\n     19  author.playtime_at_review       float64\n     20  author.last_played              float64\n    dtypes: float64(14), int64(1), object(6)\n    memory usage: 6.4+ GB\n\n\nWe want to analyse some interesting coloumns to have a better understaning of the dataset studied.\n\n## app_name / app_id\n\n\n```\nlen(df.groupby('app_name')['app_name'])\n```\n\n\n\n\n    315\n\n\n\n\n```\nlen(df.groupby('app_id')['app_id'])\n```\n\n\n\n\n    315\n\n\n\nThere are 315 different apps_names and we checked that also the number of different app_id is the same.\n\n## weighted_vote_score\n\n\n```\ndf['weighted_vote_score'].describe() #the median and the mean are different\n```\n\n\n\n\n    count    2.174737e+07\n    mean     1.654424e-01\n    std      2.434006e-01\n    min      0.000000e+00\n    25%      0.000000e+00\n    50%      0.000000e+00\n    75%      4.827586e-01\n    max      9.959868e-01\n    Name: weighted_vote_score, dtype: float64\n\n\n\nAs we can see the mean and the median have different values; also thee median has a value equal to 0 that states that at least 50% of the reviews have a \"weighted vote score\" equal to zero \n\n\n```\ndf.boxplot(column='weighted_vote_score',figsize=(10,10)) \n```\n\nwe can see that most of the values are very close to 0 as the median and the first quartile are equal to 0\n\n## votes_funny\n\n\n```\n# Now we focus on the \"votes_funny\" feature\ndf['votes_funny'].describe()\n```\n\n\n\n\n    count    2.174737e+07\n    mean     1.267917e+05\n    std      2.333553e+07\n    min      0.000000e+00\n    25%      0.000000e+00\n    50%      0.000000e+00\n    75%      0.000000e+00\n    max      4.294967e+09\n    Name: votes_funny, dtype: float64\n\n\n\nAs we can see at least 75% of the reviews have neither one \"funny\" vote. But there are at most 25% of reviews that have a lot of \"funny\" votes that brings the mean of funny votes to 12679 votes.\n\n## language\n\n\n```\ndf.groupby('language')['language'].indices.keys()# we see all the different languages that are in the dataset\n```\n\n\n\n\n    dict_keys(['brazilian', 'bulgarian', 'czech', 'danish', 'dutch', 'english', 'finnish', 'french', 'german', 'greek', 'hungarian', 'italian', 'japanese', 'koreana', 'latam', 'norwegian', 'polish', 'portuguese', 'romanian', 'russian', 'schinese', 'spanish', 'swedish', 'tchinese', 'thai', 'turkish', 'ukrainian', 'vietnamese'])\n\n\n\n\n```\nlen(df.groupby('language')['language'].indices.keys()) # as we can see there are different languages\n```\n\n\n\n\n    28\n\n\n\n## author.steamid\n\n\n```\nlen(df.groupby('author.steamid')['author.steamid'].count()) #we can see the number of authors that have commented the apps in this dataset\n```\n\n\n\n\n    16597048\n\n\n\n## steam_purchase\n\n\n```\n# We want to plot the percentage of purchased app but we consider only True and False values.\nr = df[df['steam_purchase'].isin([True,False])]['steam_purchase'].value_counts().reset_index()\nr['steam_purchase']= (r['steam_purchase'].divide(df.shape[0])*100).round(3)\n```\n\n\n```\nr\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>index</th>\n      <th>steam_purchase</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>True</td>\n      <td>77.446</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>False</td>\n      <td>22.554</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\nr.plot(kind='pie', autopct='%1.1f%%', \n startangle=90, labels=['purchased','not purchased'], fontsize=14, y='steam_purchase',legend=None)\n```\n\n## recommended\n\nAs we can see the most of the reviwed app are purchased\n\n\n```\nr = df['recommended'].value_counts().reset_index()\nr['recommended']= (r['recommended'].divide(df.shape[0])*100).round(3)\n```\n\n\n```\nr\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>index</th>\n      <th>recommended</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>True</td>\n      <td>87.471</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>False</td>\n      <td>12.529</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\n# Now we want to plot the percentage of review that are recommended \nr.plot(kind='pie', autopct='%1.1f%%', \n startangle=90, labels=['recommended','not recommended'], fontsize=14, y=\"recommended\", legend=None)\n```\n\nMost of the the app that are reviewed are recommended\n\n\n#REQ 2\n\n##REQ 2.1\n\n\n```\n# We take app_name column and we use value_counts which returns the number of times that the app appears in descending \n# order.\n# Then we use reset_index beacause with the command value_count we lost the indexes, so we need to restore them beacuse we\n# are going to plot the result, finally we take the first 10 values and we plot them.\nd = df['app_name'].value_counts().reset_index(name='count')[:10]\nprint(d)\nd.plot(kind=\"bar\", figsize=(10,5),x = 'index',y='count')\n```\n\nFrom this analysis it is clear that the game most reviwed is **PUBG** and the second one is **GTA V**\n\n## REQ 2.2\n\n\n```\n# We take the weighted vote scores grouped by app_name and we compute the mean,\n# then we sort them in decreasing order by printing the highest mean and their respective app.\n# we use two filter to skip the booleans values and the integer values.\ndf[(df['app_name'].str.len() > 1) & (~df['app_name'].isin([\"True\",\"False\"]))].groupby(['app_name'])[\"weighted_vote_score\"]\\\n.mean().sort_values(ascending = False).head()\n```\n\n\n\n\n    app_name\n    Hunt Down The Freeman    0.502150\n    Urban Empire             0.438623\n    METAL GEAR SURVIVE       0.421632\n    Identity                 0.415384\n    Umbrella Corps           0.414678\n    Name: weighted_vote_score, dtype: float64\n\n\n\nAbove we can see tha app with the major mean of `weighted_vote_score`. The first one is Hunt Down The Freeman. \n\n## REQ 2.3\n\n\n```\n# we modified the column reccomended, we replace \"True\" with 1 and \"False with \"0\" \n#in such away to sum the values and obtain the result of the numbers of reccomended\ndf[\"recommended\"] = df[\"recommended\"].replace([True, False], [1, 0])\n```\n\n\n```\n# we group by 'app_id' and we sum the values in the column reccomended to obtain the number of reccomended\ncount = df[['app_id','recommended']].groupby(['app_id']).sum().sort_values('recommended',ascending=False).reset_index()\n# to select the max we take the first element in \"count\" because sort_values returns a dataframe in descending order \nmax = count.iloc[0]\n# to select the min we take the last element in \"count\"\nmin = count.iloc[-1]\nprint('the max', \"app_id:\",max[\"app_id\"], \"number of recommendations:\", max[\"recommended\"])\nprint('the min',  \"app_id:\",min[\"app_id\"], \"number of recommendations:\",min[\"recommended\"])\n```\n\n    the max app_id: 578080.0 number of recommendations: 1772834.0\n    the min app_id: 454200.0 number of recommendations: 178.0\n\n\n## REQ 2.4\n\nIn this REQ, we interpreted 'How many of these applications were purchased, and how many were given for free?' that we must consider the apps of the previous requirement (REQ 2.3) namely the apps that have the most and the least recommendations  \n\n\n```\n# numbers of applications were purchased, \n# without considering that the user may have commented on the same app more than once\nprint('number purchased:',df[((df['app_id'] == max[\"app_id\"]) | (df['app_id'] == min[\"app_id\"]) ) & (df['steam_purchase'] == True)].groupby('app_name')['steam_purchase']\\\n.value_counts().reset_index(name='count')[['app_name','count']])\n\nprint('number got for free:',df[((df['app_id'] == max[\"app_id\"]) | (df['app_id'] == min[\"app_id\"]) ) & (df['steam_purchase'] == False)].groupby('app_name')['steam_purchase']\\\n.value_counts().reset_index(name='count')[['app_name','count']])\n```\n\n    number purchased:                         app_name    count\n    0                 Neon Hardcorps      193\n    1  PLAYERUNKNOWN'S BATTLEGROUNDS  2627528\n    number got for free:                         app_name   count\n    0                 Neon Hardcorps     207\n    1  PLAYERUNKNOWN'S BATTLEGROUNDS  595448\n\n\n\n```\n#considering that the user may have commented on the same app more than once, so let's take the precise number bought\nprint(df[df['app_id'] == max[\"app_id\"]]['app_name'].values[0] ,'number purchased:',\\\n      len(df[(df['app_id'] == max[\"app_id\"])  & (df['steam_purchase'] == True)].groupby('author.steamid'))\\\n     )\nprint(df[df['app_id'] == max[\"app_id\"]]['app_name'].values[0], 'number get for free:',\\\n      len(df[(df['app_id'] == max[\"app_id\"])  & (df['steam_purchase'] == False)].groupby('author.steamid'))\\\n     )\n\nprint(df[df['app_id'] == min[\"app_id\"]]['app_name'].values[0],'number purchased:',\\\n      len(df[(df['app_id'] == min[\"app_id\"])  & (df['steam_purchase'] == True)].groupby('author.steamid'))\\\n     )\nprint(df[df['app_id'] == min[\"app_id\"]]['app_name'].values[0], 'number get for free:',\\\n      len(df[(df['app_id'] == min[\"app_id\"])  & (df['steam_purchase'] == False)].groupby('author.steamid'))\\\n     )\n```\n\n    PLAYERUNKNOWN'S BATTLEGROUNDS number purchased: 2490873\n    PLAYERUNKNOWN'S BATTLEGROUNDS number get for free: 586666\n    Neon Hardcorps number purchased: 193\n    Neon Hardcorps number get for free: 207\n\n\nas we can see there is a noticeable difference between the 2 blocks, so a user can comment on the same app more than once(PLAYERUNKNOWN'S BATTLEGROUNDS)\n\n# REQ 3\n\n##REQ 3.1\n\n\n```\n#we convert the timestamp to datetime\ndf['hour'] = pd.to_datetime(df['timestamp_created'],unit='s')\n```\n\n\n```\n# we create a new column with only the hours and the minutes\ndf['time'] = df['hour'].dt.time.astype(str).str[:-3]\n```\n\n\n```\n#we use value_counts which return the number of times in decreasing order that every hour appears and then we take only the first one \ndf['time'].value_counts().index[0]\n```\n\n\n\n\n    '14:50'\n\n\n\nAs we can see it is really common to review after lunch\n\n##REQ 3.2\n\n\n```\n# the function below returns a plot with the number of reviews for the interval of time in input\nimport datetime\ndef number_review(list_interval):\n  count_review = []\n  for start,end in list_interval:\n    # we convert start and end to datetime\n    start = datetime.datetime.strptime(start, '%H:%M:%S').time()\n    end = datetime.datetime.strptime(end, '%H:%M:%S').time()\n    # we select only the rows in the interval and we count them \n    temp = df.loc[(df['time'] > start) & (df['time'] < end)].count()[0]\n    count_review.append(temp)\n  # we transform the list of tuples in a list of strings\n  time = list(map(str,list_interval))\n  # we plot the result \n  plt.xticks(rotation='vertical')\n  plt.bar(time, count_review, color='b', align='center')\n```\n\n## REQ 3.3\n\n\n```\n# We create a new column which contains only the time, then we call the function(number_review) with the list_interval\ndf['time'] = df['hour'].dt.time\nlist_interval=[(\"06:00:00\",\"10:59:59\"),(\"11:00:00\",\"13:59:59\"),(\"14:00:00\",\"16:59:59\"),(\"17:00:00\",\"19:59:59\"),(\"20:00:00\",\"23:59:59\"),(\"00:00:00\",\"02:59:59\"),(\"03:00:00\",\"05:59:59\")]\n```\n\n\n```\n# we delete the column \"hour\"\ndel df['hour']\n```\n\n\n```\n# call the function number_review which return the plot \nnumber_review(list_interval)\n```\n\n#REQ 4\n\n## REQ 4.1\n\nIn this exercise we select the 3 languages that appears the most\n\n\n```\n# Finds the three most used languages for reviews, the filter is used to skip the numeric values\ntop = df[df['language'].str.len() > 1]['language'].value_counts()[:3]\nprint(top)\n```\n\n    english     17024059\n    schinese     6839502\n    russian      4168323\n    Name: language, dtype: int64\n\n\nAs we expected, we can see that the most common language used is English followed by simplified chinese and russian. \n\n## REQ 4.2\n\nThis function returns a data frame which contains only the reviews written in the languges recived in input\n\n\n```\n# With loc function we set a subsection of the dataset where we consider\n# only rows that present the language took in input\ndef fun_language(df_name,languages):\n  return df_name.loc[df_name['language'].isin(languages)]\n```\n\n##REQ 4.3\n\n\n```\n# we use the fun_language and in input as parameter we pass a list which contains the results of REQ 4.1 (the language most used)\nk = fun_language(df,top.index.to_list()) \n# from k we select the rows with votes_funny > 0 and then we select the top 3 results\nbest = k.loc[k['votes_funny'] > 0]['language'].value_counts()[:3]\n# the total number of rows of each language\ntotal = k.loc[k['language'].isin(best.index)]['language'].value_counts()[:3] \n```\n\n\n```\n# we compute the percentage of votes_funny for the top three languages \n(round((best/total)*100)).astype(str)+ \"%\" \n```\n\n\n\n\n    english     11.0%\n    schinese    12.0%\n    russian     14.0%\n    Name: language, dtype: object\n\n\n\nAs we can see, considering the three most used languages, the reviews most voted as funny are the ones in russian language (14%).\n\n## REQ 4.4\n\n\n```\n#we replaced the strings('True', 'False') with the values (1,0) because we have found an error when we have made the istruction below\ndf[\"votes_helpful\"] = df[\"votes_helpful\"].replace(['True', 'False'], [1, 0])\n```\n\n\n```\n#we convert the data into integer\ndf['votes_helpful'] = pd.to_numeric(df['votes_helpful'])\n```\n\n\n```\n# total contains the numbers of rows for each language in top(top is a variable which contains the top three language)\ntotal = df.loc[df['language'].isin(top.index)]['language'].value_counts()\n#for each language in 'top' we consider only the ones that have votes_helpful > 0, we count them \n#and we dived that results for the total calculated in the previous row. Then we make the percentage of the results\n((df.loc[(df['language'].isin(total.index)) & (df['votes_helpful'] > 0)]['language'].value_counts() / total) * 100)\\\n.round(2).astype(str) +'%'\n```\n\n\n\n\n    english     28.11%\n    schinese     26.0%\n    russian     31.69%\n    Name: language, dtype: object\n\n\n\nAs we can see, the language in 'top' that has the major number of votes_helpful is the Russian.\n\n# REQ 5\n\n##REQ 5.1\n\n\n```\n# Find the ten reviewers that write most reviews\nd = df['author.steamid'].value_counts()[:10].reset_index(name='count')\n```\n\n\n```\nd\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>index</th>\n      <th>count</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>76561198062813904</td>\n      <td>149</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>76561198315585536</td>\n      <td>132</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>76561198192166880</td>\n      <td>107</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>76561198239163744</td>\n      <td>106</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>76561198045381872</td>\n      <td>103</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>76561198064946144</td>\n      <td>100</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>76561198013146400</td>\n      <td>99</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>76561198027973296</td>\n      <td>99</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>76561197969749888</td>\n      <td>88</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>76561198032476032</td>\n      <td>86</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\nd.plot(kind=\"bar\", figsize=(10,5),x = 'index',y='count')\n```\n\nAs we can see the reviewer that wrote more reviews has written 149 comments. The first five reviewers have written more than 100 comments. \n\n## REQ 5.2\n\nWe focus on the apps that the best reviewer has reviewed\n\n\n```\n# We take the best reviewer and we convert in float \"the author ID\"\n# where d['index'] means the author ID.\n# Then we show all the apps that he has reviewed\nmost_pop = df.loc[df['author.steamid'] == d['index'][0]]\n```\n\n\n```\n# Let's show all the apps that the best reviewer has commented:\nprint(most_pop.groupby('app_name')['app_name'].groups.keys())\n```\n\n    dict_keys(['A Hat in Time', 'ARK: Survival Evolved', 'Age of Empires II (2013)', 'Age of Empires: Definitive Edition', 'American Truck Simulator', 'Among Us', 'Ancestors Legacy', 'Axiom Verge', 'Banished', 'BattleBlock Theater', 'BioShock Infinite', 'Black Desert Online', 'Black Mesa', 'Blackwake', 'Bomber Crew', 'Broforce', 'Castle Crashers', 'Cave Story+', 'Celeste', 'Cities: Skylines', 'Conan Exiles', 'Counter-Strike: Source', 'Cuphead', 'DARK SOULS\u2122 III', 'DOOM', 'DOOM Eternal', 'DUSK', 'Darksiders III', 'Day of Infamy', 'Dead Cells', 'Dead Rising 4', 'Dead by Daylight', 'Deep Rock Galactic', 'Devil May Cry HD Collection', 'Dishonored', \"Don't Escape: 4 Days to Survive\", \"Don't Starve\", 'Duck Game', 'Dying Light', 'Enter the Gungeon', 'Euro Truck Simulator 2', 'Europa Universalis IV', 'FAR: Lone Sails', 'FTL: Faster Than Light', 'Factorio', 'Fallout 4', 'Finding Paradise', 'Foundation', 'Frostpunk', 'GRIS', \"Garry's Mod\", 'Getting Over It with Bennett Foddy', 'Ghost of a Tale', 'Gunpoint', 'HITMAN\u2122 2', 'Half-Life', 'Half-Life 2: Episode Two', 'Hearts of Iron IV', 'Heroes of Hammerwatch', 'Hollow Knight', 'Hotline Miami', 'House Flipper', 'Human: Fall Flat', 'Hunt: Showdown', 'Insurgency: Sandstorm', 'Into the Breach', 'Jurassic World Evolution', 'Just Cause 3', 'Just Cause 4', 'Keep Talking and Nobody Explodes', 'Kenshi', 'Kingdom Come: Deliverance', 'Little Nightmares', 'Mark of the Ninja', 'Middle-earth\u2122: Shadow of War\u2122', 'Monster Hunter: World', 'Mount & Blade: Warband', 'Mutant Year Zero: Road to Eden', 'Ni no Kuni\u2122 II: Revenant Kingdom', 'NieR:Automata\u2122', 'Night in the Woods', 'Nioh: Complete Edition', \"No Man's Sky\", 'Northgard', 'One Finger Death Punch', 'Outlast', 'Oxygen Not Included', 'PAYDAY 2', \"PLAYERUNKNOWN'S BATTLEGROUNDS\", 'Papers, Please', 'Phasmophobia', 'Phoenix Wright: Ace Attorney Trilogy', 'Planet Coaster', 'Portal 2', 'Railway Empire', 'Resident Evil 2', 'Resident Evil 7 Biohazard', 'RimWorld', 'Rise of Industry', 'Rise of the Tomb Raider', 'Rocket League', 'Rust', 'STAR WARS\u2122 Empire at War: Gold Pack', 'Saints Row: The Third', 'Salt and Sanctuary', \"Sid Meier's Civilization V\", \"Sid Meier's Civilization VI\", 'SimAirport', 'Slime Rancher', 'Sniper Elite 4', 'South Park\u2122: The Stick of Truth\u2122', 'Stardew Valley', 'Stellaris', 'Styx: Shards of Darkness', 'Subnautica', 'Super Hexagon', 'Super Meat Boy', 'Surviving Mars', 'Terraria', 'The Binding of Isaac: Rebirth', 'The Elder Scrolls Online', 'The Elder Scrolls V: Skyrim Special Edition', 'The End Is Nigh', 'The Forest', 'The Walking Dead', 'The Wolf Among Us', 'They Are Billions', 'Thief Simulator', 'Titan Souls', 'To the Moon', 'Tomb Raider', 'Total War Saga: Thrones of Britannia', 'Total War: ROME II - Emperor Edition', 'Total War: WARHAMMER', 'Total War: WARHAMMER II', 'Totally Accurate Battlegrounds', 'Townscaper', 'Two Point Hospital', 'ULTRAKILL', 'Undertale', 'Urban Empire', 'Vampyr', 'Void Bastards', 'Volgarr the Viking', 'Warhammer: Vermintide 2', 'XCOM 2', 'Yakuza 0', 'Youtubers Life'])\n\n\n## REQ 5.3\n\n\n```\n# We compute the number of apps that the best reviewer has purchased (steam_purchase = True)\n# and the number of apps that he got for free (steam_purchase = False)\nc = most_pop['steam_purchase'].value_counts().reset_index(name='counts')\nc\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>index</th>\n      <th>counts</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>True</td>\n      <td>110</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>False</td>\n      <td>39</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\n# we compute the percentage of the app purchased\nprint('Purchased:',round((c.loc[c['index'] == True]['counts']/most_pop.shape[0])*100,2).values[0].astype(str) + \"%\")\n```\n\n    Purchased: 73.83%\n\n\nAs we can see the best reviewer buys often his apps (73,83% of the app that has reviewed have been purchased)\n\n\n```\n# we compute the percentage of the app purchased\nprint('downloaded for free:',round((c.loc[c['index'] == False]['counts']/most_pop.shape[0])*100,2).values[0].astype(str) + \"%\")\n```\n\n    downloaded for free: 26.17%\n\n\nAs we can see the best reviewer has reviewed few games that he has gotten for free (only 26,17%)\n\n## REQ 5.4\n\n\n```\n# we have interpreted reviewed positively as the reviews that have reccommended = True.  We take \"most_pop\"(REQ 5.2) and we get\n#'steam_purchase' == True and 'recommended' == True and we count the number of rows\nprint(\"Reviewed App purchased positively\",\\\n      most_pop[(most_pop['steam_purchase'] == True) & (most_pop['recommended'] == True)]['recommended'].count())\n```\n\n    Reviewed App purchased positively 108\n\n\n\n```\n# we have interpreted reviewed negatively as the reviews that have reccommended = False.  We take \"most_pop\"(REQ 5.2) and we get\n#'steam_purchase' == True and 'recommended' == False and we count the number of rows.\nprint(\"Reviewed App purchased negatively\",\\\nmost_pop[(most_pop['steam_purchase'] == True) & (most_pop['recommended'] == False)]['recommended'].count())\n```\n\n    Reviewed App purchased negatively 2\n\n\n\n```\n# We take \"most_pop\" and we get\n#'steam_purchase' == False and 'recommended' == True and we count the number of rows\nprint(\"Reviewed App get free positively\",\\\nmost_pop[(most_pop['steam_purchase'] == False) & (most_pop['recommended'] == True)]['recommended'].count())\n```\n\n    Reviewed App get free positively 38\n\n\n\n```\n# We take \"most_pop\" and we get\n#'steam_purchase' == False and 'recommended' == False and we count the number of rows.\nprint(\"Reviewed App get free negatively\",\\\nmost_pop[(most_pop['steam_purchase'] == False) & (most_pop['recommended'] == False)]['recommended'].count())\n```\n\n    Reviewed App get free negatively 1\n\n\nAs we can deduce from the results, the author got informed about the app before downloading it.\n\n# REQ 6\n\n## REQ 6.1\n\n\n```\n# Computes the mean of the difference between \ng = (pd.to_datetime(df['timestamp_updated'],unit='s') - pd.to_datetime(df['timestamp_created'],unit='s')).mean()\n```\n\n\n```\nprint (\"average days and minute:\",g.days,int (g.seconds / 60))\n\n```\n\n    average days and minute: 27 1106\n\n\n## REQ 6.2\n\nThe average days and minutes of time that pass between a review creation and its update is equal to 27 days and 1106 minutes, considering also the reviews that are not updated. \n\n\n```\n# We create a new column, that is the difference between \n# timestamp updated and timestamp created expressed in seconds (integer)\ndf['totale_time'] = (pd.to_datetime(df['timestamp_updated'],unit='s') - pd.to_datetime(df['timestamp_created'],unit='s')).dt.total_seconds()\n```\n\n\n```\n# Finds the three authors that update reviews most frequently\np = df.loc[df['totale_time'] > 0].groupby('author.steamid')['author.steamid'].count().nlargest(3).reset_index(name='count')\n```\n\n\n```\np\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>author.steamid</th>\n      <th>count</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>76561198192166880</td>\n      <td>95</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>76561198206999968</td>\n      <td>63</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>76561198072450800</td>\n      <td>60</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\np.plot(kind=\"bar\", figsize=(10,5),x = 'author.steamid',y='count')\n```\n\nAs we can see the author that update most frequently his reviews had updated them 95 times. The following crazy updaters have updated respectively 63 and 60 reviews. \n\n# REQ 7\n\n## REQ 7.1\n\nCheck the column if there are any problems to fix\n\n\n```\ndf['weighted_vote_score'].describe()\n```\n\n\n\n\n    count    3.874737e+07\n    mean     1.623657e-01\n    std      2.623215e-01\n    min      0.000000e+00\n    25%      0.000000e+00\n    50%      0.000000e+00\n    75%      4.800000e-01\n    max      4.230000e+02\n    Name: weighted_vote_score, dtype: float64\n\n\n\n\n```\nk = df.loc[df['weighted_vote_score'] >= 0.5].count()[0] # Compute number of revies with a weighted vote score equal or bigger than 0,5\np = k / df.shape[0] # Divide the value computed before to the number of reviews\nprint(round(p,2))\n```\n\n    0.22\n\n\nAs we can see the probability of reviews that have a weighted vote score equal or bigger than 0,5 compared with the entire dataset is equal to 0,22 or, in other words, 22%\n\n## REQ 7.2\n\nCheck if the column has any problem\n\n\n```\ndf['votes_funny'].describe()\n```\n\n\n\n\n    count    3.874737e+07\n    mean     1.203789e+05\n    std      2.273775e+07\n    min      0.000000e+00\n    25%      0.000000e+00\n    50%      0.000000e+00\n    75%      0.000000e+00\n    max      4.294967e+09\n    Name: votes_funny, dtype: float64\n\n\n\n\n```\n#Compute the probability that a review has at least one vote as funny given that the Weighted Vote Score is bigger than 0.5\np = 1 - ((df.loc[(df['votes_funny'] == 0.0) & (df['weighted_vote_score'] > 0.5)].count()[0])/df.loc[df['weighted_vote_score'] > 0.5].count()[0])\nprint(round(p,2))\n```\n\n    0.19\n\n\nAs we can see the probability that a review has at least one vote as funny given that the Weighted Vote Score is bigger than 0.5 is equal to 0,19 or, in other words to the 19% of the reviews with a weighted vote score bigger than 0,5. \n\n## REQ 7.3\n\nTo show if the probability that \u201ca review has at least one vote as funny\u201d independent of the \u201cprobability that a review has a Weighted Vote Score equal or bigger than 0.5\u201d we used the following formula:\n\nA $\\perp$ B \u21d4  P(A $\\cap$ B) = P(A) * P(B)\n\n\n```\nintersect = df.loc[(df['votes_funny'] != 0.0) & (df['weighted_vote_score'] >= 0.5)].count()[0]/df.shape[0]\nA = df.loc[df['votes_funny'] != 0].count()[0]/df.shape[0]\nB = df.loc[df['weighted_vote_score'] >= 0.5].count()[0]/df.shape[0]\nprint(round(A*B,4) , round(intersect,4))\n```\n\n    0.0254 0.0414\n\n\nAs we can see the product of the probabilities is different from the probability of intersection so the \"review has at least one vote as funny\" variable and \"probability that a review has a Weighted Vote Score equal or bigger than 0.5\u201d variable are not indipendent. \n\n# REQ 8\n\n## REQ 8.1\n\nTest the difference for weighted score between reviews in simplified chinese and russian\n\n\n```\n#Creates a new dataset with only two columns that we need\nsub=df[['language','weighted_vote_score']]\n```\n\n\n```\nfrom scipy import stats\n```\n\n\n```\n#Creates two new variables for reviews in simplified chinese and \n#russian considering only reviews with a weighted vote score higher than zero\n\nchina = sub[(sub['language']=='schinese') & (sub['weighted_vote_score'] !=0)]['weighted_vote_score']\n\nrussia = sub[(sub['language']=='russian') & (sub['weighted_vote_score'] !=0)]['weighted_vote_score']\n```\n\n\n```\n#With module stats in scipy package we compute the p-value of stat\n\nstats.ttest_ind(china,russia,equal_var=False).pvalue\n```\n\n\n\n\n    0.0\n\n\n\nTo test if there is differences between weighted vote score for reviews made in simplified chinese and russian we use a t-test for group differences. We compute the p-value for the t-test and we obtain 0. Against a confidence level equal to alpha = 0,05 a p-value = 0 means that we reject the null hypothesis that means for both groups are equals. \n\n## REQ 8.2\n\nCreate a new dataset with the variables we need\n\nCreate a new variable: difference between time created review and time updated review\n\n\n```\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\n```\n\n\n```\nplt.figure(figsize=(10,10))\nax = plt.axes()\nax.scatter(x='weighted_vote_score',y='diff',data=rq2)\nax.plot(x,y)\nplt.show()\n```\n\n\n```\n#We create a linear regression model\nmodel = LinearRegression()\n```\n\n\n```\nx = df['weighted_vote_score']\n```\n\n\n\n\n    ['weighted_vote_score']\n\n\n\n\n```\n# We clean the weighted score values from NAN values\nx.replace([np.inf, -np.inf, np.nan], 0, inplace=True)\n```\n\n\n```\n# Converting weighted vote score column to an array element\nx = np.array(df['weighted_vote_score']).reshape(-1,1)\n# Converting total time column (difference between timestamp updated and timestamp created)\n#from seconds to days\ny = df['totale_time'] / (60*60*24)\n```\n\n\n```\n# We clean the total time column values from NAN values\ny.replace([np.inf, -np.inf, np.nan], 0, inplace=True)#.dropna(subset=[\"totale_time\"], how=\"all\")\n```\n\n\n```\n#x = np.nan_to_num(x)\n```\n\n\n```\n# We check if data are cleaned\npd.DataFrame(x).describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>0</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>3.874738e+07</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>1.623330e-01</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>2.421257e-01</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>4.800000e-01</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>1.000000e+00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\n# Fitting the linear model for the two assigned variables\nmodel.fit(x,y)\n```\n\n\n\n\n    LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False)\n\n\n\n\n```\n# Storing intercept and slope of the linear model in two varibles b0 b1\nb0 = model.intercept_\nb1 = model.coef_\nprint(b0,b1)\n```\n\n    22.799468544436237 [30.60872367]\n\n\n\n```\n# Compute the predictions of the linear model given the x values\ny_pred = model.predict(x)\ny_pred\n```\n\n\n\n\n    array([22.79946854, 22.79946854, 22.79946854, ..., 42.12196133,\n           22.79946854, 38.83261038])\n\n\n\n\n```\n#Computing the Regression Deviance and its degrees of freedom\ndreg = sum((y_pred - y.mean())**2)\ngreg = 1\n```\n\n\n```\n#Computing the Residual Deviance and its degrees of freedom\ndres = sum((y - y_pred)**2)\ngres = len(y)-2\n```\n\n\n```\n#Computing the Fisher statistic\nFoss = (dreg*gres)/(dres*greg)\n```\n\n\n\n\n    True\n\n\n\n\n```\n# Computing the t test for the b1 value\ns = b1/np.sqrt(Foss)\ns\n```\n\n\n\n\n    array([0.09091731])\n\n\n\nWe are testing with the computed slope of the linear model in this test the null hypothesis that b1 is equal to 0 (that means that the two variables are not related) and the alternative hypothesis that b1 is not 0 (two tails test).\nTo accept the null hypothesis the t-test we have computed must be lower than the thresholds that we set for a confidence level of alpha = 0,05.\nWe have found out that the t-test is equal to 0,091. Looking at the t-distribution table we find out that the confidence level at 1-alpha/2 level is equal to 1,96.\nWe see that 0,091 is lower than 1,96 so we accept the null hypothesis so the two variables are not linear related. \n\nTo confirm our results we can compute linear correlation coefficient:\n\n\n```\nx = np.array(df['weighted_vote_score'])\ny = np.array(df['totale_time'])\nn = len(x)\nr = np.corrcoef(x, y)\nr[0][1]\n```\n\n\n\n\n    0.054006150742646294\n\n\n\nAs we can see from the correlation computed the correlation between wieghted vote score and the time that passed between review creation and update is near to 0, that means there is no correlation between two variables\n\n## REQ 8.3\n\n\n```\n# Creating two subsets in order to split reviews with recommendations and revies without recommendation\nrecom = df[['weighted_vote_score','totale_time','recommended']].loc[df['recommended'] == True]\nnorec = df[['weighted_vote_score','totale_time','recommended']].loc[df['recommended'] == False]\n```\n\n\n```\n# Create two models to store our results\nmodel1 = LinearRegression()\nmodel2 = LinearRegression()\n```\n\n\n```\n# Assign the columns we need to some values\nxr = np.array(recom['weighted_vote_score']).reshape(-1,1)\nyr = recom['totale_time']/(60*60*24)\nxn = np.array(norec['weighted_vote_score']).reshape(-1,1)\nyn = norec['totale_time']/(60*60*24)\n```\n\n\n```\n# Fitting the linear regression model for both of the datasets\nmodel1.fit(xr,yr)\n\nmodel2.fit(xn,yn)\n```\n\n\n\n\n    LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False)\n\n\n\n\n```\n# Assign intercept and slope for the regression model of each dataset\nb0r = model1.intercept_\nb1r = model1.coef_\n\nb0n = model2.intercept_\nb1n = model2.coef_\n\nprint(b0r, b1r)\nprint(b0n, b1n)\n```\n\n    21.73751545250441 [33.85324672]\n    34.817377214984845 [1.69085199]\n\n\n\n```\n# Compute the extimated values of the linear regression model for both of the datasets\nyr_pred = model1.predict(xr)\n\nyn_pred = model2.predict(xn)\n```\n\n\n```\n# Compute the t-test for the recommended apps only\ndregr = sum((yr_pred - yr.mean())**2)\ngregr = 1\n\ndresr = sum((yr - yr_pred)**2)\ngresr = len(yr)-2\n\nfossr = (dregr*gresr)/(dresr*gregr)\n\ntr = b1r/np.sqrt(fossr)\n```\n\n\n```\ntr\n```\n\n\n\n\n    array([0.09804194])\n\n\n\n\n```\n# Compute the t-test for the not-recommended apps only\ndregn = sum((yn_pred - yn.mean())**2)\ngregn = 1\n\ndresn = sum((yn - yn_pred)**2)\ngresn = len(yn)-2\n\nfossn = (dregn*gresn)/(dresn*gregn)\n\ntn = b1n/np.sqrt(fossn)\n```\n\n\n```\ntn\n```\n\n\n\n\n    array([0.27181557])\n\n\n\nWe use the same test in RQ8.2 to test if there is a significant relantionship between weighted vote score and \"totale time\" (difference between timestamp_update and timestamp created expressed into days). We set a confidence level of alpha = 0,05 and we obtain a threshold equal to 1,96 for the t-quantile. As we can see both of the t-test are lower than the threshold: <br/>\ntr = 0,098 < 1,96 <br/>\ntn = 0,272 < 1,96 <br/>\nso we can accept the null hypothesis for both of the subsets that the coefficient value is significantly equal to 0. So there is no significative linear relation between the two variables considering also only recommended app or not-recommended. \n\n## REQ 8.4\n\n**What are histograms, bar plots, scatterplots and pie charts used for?** <br/>\n* Histograms are used to represent discrete or continous quantitative variables; the data are represented in intervals that they don't necessarily have to be of the same width. They're often useful when dealing with large datasets. The bar height represent the density (or frequency) of the classes represented. <br/>\n* Bar Plot are used to represent discrete quantitative variables or qualitative variables. Each bar corresponds to a categorical value of the variable that we are representing. The height of the bar represents the absolute or relative frequency of the categorical value in the dataset. <br/>\n* Scatterplots are used to represent quantitative variables in order to show a significative relation between two variable. The variables are represented in a two dimensional space (cartesian space) where each axis is assigned to one of the two variables. Each unit is represented by a point in the space. This plot is useful to see a correlation between the two variables. <br/>\n* Pie charts are used to represent quantitative discrete variables or qualitative variables and are useful to show the composition of the categorical values for a variable. \n\n## REQ 8.5\n\n**What insights can you extract from a Box Plot?** <br/>\nBoxplots are useful to represent a single quantitative variable and describes its distribution with statistical summaries. <br/>\nBoxplots can show median (or mean, depends on the boxplot type we are creating), quartiles (1\u00b0 and 3\u00b0), interquartile range, minimum and maximum of distribution and also outliers. \n\n# Theoretical Questions\n\n## REQ 1\n\n```\nInput\n    A: array of length n\n    k: integers between 1 and n\nfunction alg(A, k):\n  s <-- a random element of A\n  set L = [all the elements of A with value <= s]\n  set R = [all the elements of A with value > s]\n  r = len(L)\n  if k == r:\n    return s\n  else if k < r:  \n    return alg(L, k)\n  else:\n    return alg(R, k - r)\n```\n\n**1. What does the algorithm compute?**\n\nThis algorithm returns the k-th largest element of A\n\n**2. What is asymptotically (i.e., we are asking for big-O complexity) the running time of the algorithm in the worst case, as a function of n**\n\nThe worst case is when I have an ordered list, there are no repeated elements, s is the second largest element in the list and k = 1.\nAnalyzing the complexity of each row:\n- The assigment of s is O(1)\n- The assigment of L has cost O(n) because it iterates each element of A  \n- The assigment of R has cost O(n) for the same reason\n- The remaining instructions have constant complexity (apart from the recursive calls)\n\nSince each time s is the second largest number of the list, we are going to call the recursion with a list with size (n-1), so the cost is $4 * (n + (n-1) + (n-2) + ... + 2 + 1) \\rightarrow n^2$.\n\nHowever, in some cases the algorithm could not ends: for example, if we have an ordered list, k = 1 and we always draw the same s, the algorithm goes into a loop because the list stays always the same.\n\n**3. What is asymptotically the running time of the algorithm in the best case?**\n\nOne of the best cases is when we have an ordered list, s is going to be the maximum number and we have k which is the index of the last element of the list.\nIn this case, the complexity is $O(n) + O(n) + 4 \\rightarrow O(n)$.\n\n## REQ 2\n\n\n```\nfunction splitSwap(a, l, n):\n  if n <= 1:\n    return\n  splitSwap(a, l, n/2)\n  splitSwap(a, l+ n /2, n/2)\n  swapList(a, l, n)\n```\n\n```\nfunction swapList(a, l, n):\n  for i = 0 to n/2:\n    tmp = a[l + i]\n    a[l + i] = a[l + n/2 + i]\n    a[l + n/2 + i] = tmp\n```\n\n\n\n1. How much running time does it take to execute splitSwap(a, 0, n)? \n\n\\begin{align}\n        \\text{T}(n) = \\left\\{\n        \\begin{array}{cl}\n        2& n \\le 1 \\\\\n        T(\\frac{n}{2}) + T(\\frac{n}{2}) + 4\\frac{n}{2} + 1 & otherwise\n        \\end{array}\n        \\right.\n    \\end{align} \n    \nThe first term, T($\\frac{n}{2}$), represents the first recursive call (i.e. `splitSwap(a, l, n/2)`), its cost is $\\frac{n}{2}$ since it is called only on half array.\n\nInstead, the second term, T($\\frac{n}{2}$), represents the second recursive call (i.e. `splitSwap(a, l+ n /2, n/2)`), its cost is again $\\frac{n}{2}$ since it is called on the second half of the array.\n\nWhile, the last term, $\\frac{4n}{2}$, is the cost for the call to the `swapList` function due to the `for i = 1 to n/2` and the 3 instructions below it. <br/>\nNow we solve $T(n)$:<br/>\n$\\begin{align}\nT(n) &= T(\\frac{n}{2}) + T(\\frac{n}{2}) + (\\frac{4n}{2}) + 1 \\\\ \n& = 2T(\\frac{n}{2}) + (\\frac{4n}{2}) \\\\\n&\\leq 4T(\\frac{n}{4}) + 8(\\frac{n}{4})  + (\\frac{4n}{2}) \\\\\n&\\leq 8T(\\frac{n}{8}) + (\\frac{16n}{8}) + 8(\\frac{n}{4})  + (\\frac{4n}{2}) \\\\\n&\\leq 8T(\\frac{n}{8}) + 2n +2n +2n \\\\\n&\\leq 2^kT(\\frac{n}{2^k}) + 6n \\\\\n&2^{log(n)} + nlog(n)\n\\end{align}$\n\n$2^{log(n)}$ is equal to 2 to the power of the number of times that we call the recursion , while $nlog(n)$ is equal to 2 times the number of times that we call the recursion.\nComparing the two terms we can deduce that $nlog(n)$ grows faster than $2^{log(n)}$, so the final complexity is $O(nlog(n))$.\n\n2. What does this algorithm do? Is it optimal? Describe the mechanism of the algorithm in details, we do not want to know only its final result.\n\n  *   What does this algorithm do?<br/>\n  It skips the first $l$ elements and inverts the next $n$ elements of the list\n\n  * Is it optimal?<br/>\n  No, it is not optimal, because it can be done in $O(n)$. In the following list are reported the details of the algorithm: \n\n    - create a new list which contains the elements which are to be skipped \n    - starting from the $(l+n)$-th element, iterate backwards till $l$ (for i=l+n to l) and add the element a[i] to the new list\n    - add the remaining elements\n\n  * **Describe the mechanism of the algorithm in details**<br/>\n    We describe the algorithm using the example of an execution.<br/>\n    If we have:<br/>\n    $a=[1,2,3,4]$,<br/>\n    $l= 0$,<br/>\n    $n=4$.<br/>\nSo we call the function with $(a,0,4)$.<br/>\n    At the beginning $n$ is greater than 1 so the algorithm does not exit, so the recursion will be called with $(a,0,2)$ until $n = 1$ (see the tree for all the details of the recursive calls), then when it returns to the parent function it will have $n=2$ and the function swaplist will be called.<br/>\n  SwapList receives three parameters as input: <br/>\n  \u2022 $a$ is list <br/>\n  \u2022 $l$ an index <br/>\n  \u2022 $n$ number between 1 and length of $a$ <br/>\n  Below are all the steps that the algorithm performs.\n  Looking at the tree (first drawing above), we have that the red arrows indicate the recursive calls that call the swaplist function.\n  Recursion works from bottom to top, so the first call to execute the swaplist function wil be the case with $(a, 0, 2)$ where the algorithm will do a single iteration and swap the first element with the second so $a$ will change like this:<br/>\n  $a = [2,1,3,4]$<br/>\n  Then the second call will also do a single iteration with $(a, 2,2)$ it will swap the third and fourth elements, so \"a\" becomes<br/>\n  $a = [2,1,4,3]$<br/>\n  Then the last call instead will do 2 iterations, where in the first it swap the first with the third and in the second iteration it swap the second with the fourth so $a$ becomes<br/>\n  $a = [4,3,2,1]$<br/>\nThe last drawing (below) shows how the list is modified, the drawing must be read from bottom to top, so first the circle is number 1 then 2, and then 3.<br/>\n\n\n## REQ 3\n\nThis is the list that we will use for all 3 counterexamples:\n\n$V = [ (1,1) , (6,4) , (18,5) , (22,5), (28,7) ]$\n\nwhere each element in the list is a tuple where the first element is the value and the second one is the weight.\n\n  * **Order them in increasing order of weight and then visit them sequentially, adding them to the solution as long as the budget is not exceeded**\n    * $V = [ (1,1) , (6,4) , (18,5) , (22,5), (28,7) ]$<br/>\n    If we have $W = 11$, we can only take the first 3 elements in the list and we obtain 25 as final value, but the optimal value is 40 if we take $(18,5)$ and $(22,5)$.\n  * **Order them in decreasing order of values, and then visit them sequentially, adding them to the solution if the budget is not exceeded**\n    * $V = [(28, 7), (22, 5), (18, 5), (6, 4), (1, 1)]$<br/>\n    If we have $W = 11$, we can only take the first element in the list and we obtain 28 as final value, but the optimal value, as said before, is 40 if we take $(18,5)$ and $(22,5)$\n  * **Order them in decreasing relative value (v_i / w_i), and then visit them sequentially, adding them to the solution if the budget is not exceeded**\n    * $V = [(28, 7), (22, 5), (18, 5), (6, 4), (1, 1)]$<br/>\n    If we have $W = 11$, we can only take the first element in the list and we obtain 28 as final value, but the optimal value, once again, is 40 if we take $(18,5)$ and $(22,5)$\n\n\n", "meta": {"hexsha": "458255589ab6bbe163bc3a1cc9cac230d6086bcc", "size": 277819, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ADM_HW2.ipynb", "max_stars_repo_name": "MinaMakar97/ADM-HW2", "max_stars_repo_head_hexsha": "301706e7d96d968ec4c07d4b0db14e437f7c8947", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ADM_HW2.ipynb", "max_issues_repo_name": "MinaMakar97/ADM-HW2", "max_issues_repo_head_hexsha": "301706e7d96d968ec4c07d4b0db14e437f7c8947", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ADM_HW2.ipynb", "max_forks_repo_name": "MinaMakar97/ADM-HW2", "max_forks_repo_head_hexsha": "301706e7d96d968ec4c07d4b0db14e437f7c8947", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 73.6139374669, "max_line_length": 57286, "alphanum_fraction": 0.7532638156, "converted": true, "num_tokens": 14391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.08035747597999429, "lm_q1q2_score": 0.028589172459806578}}
{"text": "```python\nimport os\nos.environ['TRKXINPUTDIR']=\"/global/cfs/cdirs/m3443/data/trackml-kaggle/train_10evts\"\ninput_data_path = \"/global/cfs/projectdirs/m3443/usr/caditi97/iml2021/run_dir\" \nos.environ['TRKXOUTPUTDIR']= input_data_path\n```\n\n\n```python\nimport pkg_resources\nimport yaml\nimport pprint\nimport random\nrandom.seed(1234)\nimport numpy as np\n# import pandas as pd\nimport itertools\nimport matplotlib.pyplot as plt\nimport tqdm\nfrom os import listdir\nfrom os.path import isfile, join\nimport matplotlib.cm as cm\nimport sys\nimport tqdm\nfrom tqdm import tqdm\nimport tqdm.notebook as tq\n# import sympy\n# from sympy import S, symbols, printing\n# %matplotlib widget\n\nsys.path.append('/global/homes/c/caditi97/exatrkx-iml2020/exatrkx/src/')\n\n# 3rd party\nimport torch\nimport torch.nn.functional as F\nfrom torch_geometric.data import Data\nfrom trackml.dataset import load_event\nfrom pytorch_lightning import Trainer\nfrom pytorch_lightning.callbacks import ModelCheckpoint\nfrom pytorch_lightning.loggers.neptune import NeptuneLogger\n\n\n# local import\nfrom exatrkx import config_dict # for accessing predefined configuration files\nfrom exatrkx import outdir_dict # for accessing predefined output directories\nfrom exatrkx.src import utils_dir\nfrom exatrkx.src import utils_robust\nfrom utils_robust import *\n\n\n# for preprocessing\nfrom exatrkx import FeatureStore\nfrom exatrkx.src import utils_torch\n\n# for embedding\nfrom exatrkx import LayerlessEmbedding\nfrom exatrkx import EmbeddingInferenceCallback\nfrom exatrkx.src import utils_torch\nfrom torch_cluster import radius_graph\nfrom utils_torch import build_edges\nfrom embedding.embedding_base import *\n\n# for filtering\nfrom exatrkx import VanillaFilter\n\n# for GNN\nimport tensorflow as tf\nfrom graph_nets import utils_tf\nfrom exatrkx import SegmentClassifier\nimport sonnet as snt\n\n# for labeling\nfrom exatrkx.scripts.tracks_from_gnn import prepare as prepare_labeling\nfrom exatrkx.scripts.tracks_from_gnn import clustering as dbscan_clustering\n\n# track efficiency\nfrom trackml.score import _analyze_tracks\nfrom exatrkx.scripts.eval_reco_trkx import make_cmp_plot, pt_configs, eta_configs\nfrom functools import partial\n\n\n```\n\n\n```python\nplt.rcParams.update({'axes.titlesize' : 16, 'axes.labelsize' : 16, 'lines.linewidth' : 2, 'lines.markersize' : 10,\n                    'xtick.labelsize' : 14, 'xtick.major.width' : 2,\n                    'ytick.labelsize' : 14, 'ytick.major.width' : 2,\n                    'grid.alpha' : 0.5, \"legend.frameon\" : False, 'legend.fontsize' : 16})\n\n```\n\n\n```python\ndef train_embedding(config, args, logger):\n    model = LayerlessEmbedding(config)\n    e_checkpoint_callback = ModelCheckpoint(monitor='val_loss', \n                                            filepath=os.path.join(utils_dir.embedding_outdir,'ckpt-{epoch:02d}-{val_loss:.2f}') ,\n                                            save_top_k=3,mode='min')\n    e_callback_list = [EmbeddingInferenceCallback()]\n    e_trainer = Trainer.from_argparse_args(args, logger=logger, callbacks=e_callback_list, checkpoint_callback=e_checkpoint_callback)\n    e_trainer.fit(model)\n    return e_checkpoint_callback.best_model_path\n```\n\n\n```python\n# Create Neptune Logger\nneptune_logger = NeptuneLogger(api_key=\"eyJhcGlfYWRkcmVzcyI6Imh0dHBzOi8vYXBwLm5lcHR1bmUuYWkiLCJhcGlfdXJsIjoiaHR0cHM6Ly9hcHAubmVwdHVuZS5haSIsImFwaV9rZXkiOiJlMjRjNDNiNi03N2UyLTQ2MzctYWNiZS1jOTFiZjRiY2VkMWQifQ==\",\n                               project_name='caditi97/exatrkx-pileup')\n```\n\n    https://app.neptune.ai/caditi97/exatrkx-pileup/e/EX-18\n\n\n    NeptuneLogger will work in online mode\n\n\n\n```python\nconfig_file = \"/global/homes/c/caditi97/exatrkx-iml2020/exatrkx/configs/train_embedding.yaml\"\nwith open(config_file) as f:\n        config = yaml.load(f, Loader=yaml.FullLoader)\n```\n\n\n```python\nclass Arg:\n    def __init__(self, gpus, max_epochs, limit_train_batches, limit_val_batches):\n        self.gpus = gpus\n        self.max_epochs = max_epochs\n        self.limit_train_batches = limit_train_batches\n        self.limit_val_batches = limit_val_batches\n```\n\n\n```python\nargs = Arg(gpus = 1, max_epochs=10, limit_train_batches=3000, limit_val_batches=1000)\n```\n\n\n```python\ntrain_embedding(config,args,neptune_logger)\n```\n\n    GPU available: True, used: True\n    TPU available: False, using: 0 TPU cores\n    LOCAL_RANK: 0 - CUDA_VISIBLE_DEVICES: [0]\n    Set SLURM handle signals.\n    \n      | Name      | Type       | Params\n    -----------------------------------------\n    0 | layers    | ModuleList | 1 M   \n    1 | emb_layer | Linear     | 4 K   \n    2 | norm      | LayerNorm  | 1 K   \n    3 | act       | Tanh       | 0     \n    /global/homes/c/caditi97/.local/lib/python3.7/site-packages/pytorch_lightning/utilities/distributed.py:45: UserWarning: The dataloader, val dataloader 0, does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` (try 80 which is the number of cpus on this machine) in the `DataLoader` init to improve performance.\n      warnings.warn(*args, **kwargs)\n\n\n\n    HBox(children=(FloatProgress(value=1.0, bar_style='info', description='Validation sanity check', layout=Layout\u2026\n\n\n    /global/homes/c/caditi97/.local/lib/python3.7/site-packages/pytorch_lightning/utilities/distributed.py:45: UserWarning: The dataloader, train dataloader, does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` (try 80 which is the number of cpus on this machine) in the `DataLoader` init to improve performance.\n      warnings.warn(*args, **kwargs)\n\n\n\n    HBox(children=(FloatProgress(value=1.0, bar_style='info', description='Training', layout=Layout(flex='2'), max\u2026\n\n\n\n    HBox(children=(FloatProgress(value=1.0, bar_style='info', description='Validating', layout=Layout(flex='2'), m\u2026\n\n\n\n    HBox(children=(FloatProgress(value=1.0, bar_style='info', description='Validating', layout=Layout(flex='2'), m\u2026\n\n\n\n    HBox(children=(FloatProgress(value=1.0, bar_style='info', description='Validating', layout=Layout(flex='2'), m\u2026\n\n\n\n    HBox(children=(FloatProgress(value=1.0, bar_style='info', description='Validating', layout=Layout(flex='2'), m\u2026\n\n\n\n    HBox(children=(FloatProgress(value=1.0, bar_style='info', description='Validating', layout=Layout(flex='2'), m\u2026\n\n\n\n    HBox(children=(FloatProgress(value=1.0, bar_style='info', description='Validating', layout=Layout(flex='2'), m\u2026\n\n\n\n    HBox(children=(FloatProgress(value=1.0, bar_style='info', description='Validating', layout=Layout(flex='2'), m\u2026\n\n\n\n    HBox(children=(FloatProgress(value=1.0, bar_style='info', description='Validating', layout=Layout(flex='2'), m\u2026\n\n\n\n    HBox(children=(FloatProgress(value=1.0, bar_style='info', description='Validating', layout=Layout(flex='2'), m\u2026\n\n\n\n    HBox(children=(FloatProgress(value=1.0, bar_style='info', description='Validating', layout=Layout(flex='2'), m\u2026\n\n\n    Training finished, running inference to build graphs...\n    100.0% inference complete \n\n\n\n\n\n    '/global/cfs/cdirs/m3443/usr/caditi97/iml2021/run_dir/embedding_output/ckpt-epoch=03-val_loss=0.16.ckpt'\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "95423d996c2bae2f3f579de7875ae7fad7e088e3", "size": 13976, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/pileup_training.ipynb", "max_stars_repo_name": "caditi97/exatrkx-iml2020", "max_stars_repo_head_hexsha": "f4b1e4438cda7db2d40c8e572b1b682c12781e6c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-24T18:54:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-24T18:54:55.000Z", "max_issues_repo_path": "notebooks/pileup_training.ipynb", "max_issues_repo_name": "caditi97/exatrkx-iml2020", "max_issues_repo_head_hexsha": "f4b1e4438cda7db2d40c8e572b1b682c12781e6c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/pileup_training.ipynb", "max_forks_repo_name": "caditi97/exatrkx-iml2020", "max_forks_repo_head_hexsha": "f4b1e4438cda7db2d40c8e572b1b682c12781e6c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.649122807, "max_line_length": 381, "alphanum_fraction": 0.5762020607, "converted": true, "num_tokens": 1933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.06097518470435992, "lm_q1q2_score": 0.02858459504620784}}
{"text": "```python\n### import matplotlib.pyplot as plt\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport matplotlib as mpl\nimport numpy as np\nimport pandas as pd\nimport scipy as sp\nfrom scipy.optimize import curve_fit\nfrom scipy.signal import savgol_filter\n\n\nplt.style.use('default')\nplt.style.use('seaborn-paper')\ncurrent_palette = sns.color_palette(palette=None)\nsns.set_palette(palette=None)\nsns.palplot(current_palette)\nplot_width = 3.487\nplot_height = plot_width / 1.618\n\n```\n\n# Research Notes:\n\n**Eerkes Utwente et al. - Modulation of conductance and superconductivity top gating LAO/STO**:\n- Top gated device were fabricated on STO (001)-oriented substrate, at TiO2-layer\n- isolated measurement structure by lift-off patterend (lithography+photoresist) by using a-LAO layer.\n- LAO deposited by PLD. Crystalline LAO PLD-deposited in oxygen pressure of 2e-3 milibars at 850c\n- Sampled was cooled down to 600c at deposition pressure, post anneal of 1h at 600c at oxygen pressure of 600 milibars, followed a cool down to room temp at 600milibar pressure. (this creates insulating a-LAO/STO layer.\n- Ohmic contacts to the 2DEG is deposited by sputtering of Ti/Au.(Use an argon etcher first to remove some gold layers(?)). \n- Vg = 0V , $n_s = 1.9*10^{13}$ $cm^{-2}$. Which is typical value for metalic top-gates. ( In the experiment, state is the same as devices without top-gates)\n\n**B. Forg  et al.- Field-effect devices utilizing LaAlO3-SrTiO3 interfaces**:\n- 9 uc thick LAO, in situ gate. Depletion mode. operating tested at -100 c to 100c, short 20um-200um and wide 1600um channels)\n- Fabricate all-oxide FET with current and voltage gain.\n- Oxide interface is proven that they can be controlled effectively by gate field induced by top gating config.\n- Thin gate dielectric (LAO) , devices can be operated with small gate voltages in comparison to bottom gating\n- Lower limits to be explored.\n- Subthreshold swing S = 0.7/4 => 175mV/dec\n- \n\n**M. Hosada et al. - Transistor operation and mobility enhancement in top-gated\nLaAlO3/SrTiO3 heterostructures** :\n- Depletion mode too\n- Two probe device geometry prevented the determination of sheet carrier density n and hence hall mobility.\n- Again, TiO2 terminated STO substrate, pre-deposited a-LAO hard mask. \n    - LAO thickness between DS is 4uc to 22uc. \n    - 400um channel length\n    - Channel width 5-200um.\n    - ex-situ gate, sputtered Au with 100nm thickness\n    - Source and drain were contacted with Al ultrasonic wire bonding\n- gate leakage current Ig was significantly smaller than Id when device is on\n- Obtained a clear transistor charactersitics at T = 300k for 16uc LAO\n- Pinch off observed for -0.8V <= Vgs <= +1.2V, (Saturation at higher vds)\n- dId/dVds (conductance) can show the pinch off voltage Vp as a function of Vgs. At Vds = Vp, Id sat is shown.\n- Linear behaviour in the saturation region as expected. Vth = 01.15+0.05V. We can use the Variable range hopping model to calculate Vth too.\n- Small hysterisis.\n- Confirms that trasistor charactersitics is still obtained LAO thichkness of 4uc. Vth does not scale monotonically with thickness of LAO, as would be the case for constant sheet carrier density. confirming that Vth does not depend on:\n\\begin{align}\nV_{th} = \\frac{-ed_{LAO}n}{\\epsilon \\epsilon_0}\n\\end{align}\n\n-  When Vgs -> Vth, enhancement of hall mobility is observed as n decreased.\n\n**C. Woltmann et al. - Field-Effect Transistors with Submicrometer Gate Lengths Fabricated\nfrom LaAlO3-SrTiO3-Based Heterostructures** :\n- Considers short effect behaviour\n- Methods describing semiconductor physics are applicable only with considerable restriction since electronic properties of complex oxides differs fundamentally from conventional semiconductor\n- Conclude that with decreasing gate length, Vt shifts to lower values and is increasingly dependent on Vsd (note that this is depletion mode)\n- On-ff ratio and subthreshold slope decrease (Subthreshold swing increase).  A device characterized by steep subthreshold slope will have a faster transition between off (low current) and on (high current) states.\n\n**Variable Range hopping Conduction (VRH) pdf**: \n\nChapter 4.1:Outline\n- Modeled for amorphous crystal which in this case is SiO2\n- Mott introduced the concept of hopping conduction: VRH\n- Empirically observed $log\\sigma \\propto T^{-1/4}$\n- $log\\sigma \\propto T^{-1/4}$ is valid for low E field strength, an extension is needed for higher field stregth\n- VRH process is often expressed in terms of a percolation problem. VRH/Percolation problem is successful in describing the process in ohmic low-field regime[pg5] but not at medium and high field regime (i.e saturation mode at our case)\n\nChapter 4.2:Hopping Probability\n- Assuming no corellation with occupation probability of different localize states, net electron flow is:\n$$I_{ij} = f_i(1-f_j)w_{ij} - f_j(1-f_i)w_{ji} $$\n\nWhere $f_i$ is occupation probability of state i and \n\n**A.K. Sen - Nonlinear Response, Semi-classical Percolation and Breakdown in the RRTN Model**:\n\nPower-law growth of conductance:\n- non-integer power-law behaviour (for low field),$I \\propto (V-V_g)^\\alpha$ , $V_g$ being the threshold voltage.\n- For conductance G, nonlinearity exponent $\\delta = \\alpha - 1 = 2$. \n- For arrays of normal metal island connected by small tunnel junction,$\\alpha = 1.36 \\pm 0.16$ for 1D and $\\alpha = 1.80 \\pm 0.16$ for 2D.\n\nLow-temperature hopping-dominated conduction:\n- conduction properties of low-temperature regime where conduction is mainly due to phonon-assisted hopping of electrons.\n- Needs to consider Mott's VRH conductance model or some of the other variation \n$$G(T) \\propto \\exp(-(T_0/T))^\\gamma $$\n- VRH exponent being dependent on the concentration of donors/acceptors (n or p)\n- Conductance of the sample goes through ma maximum as temp is increased towards a metalic behaviour.\n\nOrigin of RRTN model and percolative aspect:\n\n\n# Journal Entry\n## Week 1\n\n### PLD and Pulse Laser deposition\nPLD : Pulse laser deposition\nRHEED : Reflection High Energy Electron deposition\n\n\nProcedure for the sample is initially set by : https://en.wikipedia.org/wiki/Photolithography\n\n**Procedure for substrate**\n\nfabricated in the UTwente clean room, Notes:\n- The substrate grown, ( Reseach on: STO growth, and lookup terrace on why that the terrace form is needed. Not completely flat). Annealing makes surface reconstruction, etc.\n- Substrate is cleaned, \n- spin coating with photo resist\n- Apply photomask, do allignment and such\n- Apply UV light for 7 seconds\n- Remove photo resist, clean using acetone.\n- Etching stuff\n\n**PLD** \n- Alignment of the optics\n- set the energy of the laser, calibrate it. Energy of the laser is base on the ionization energy required for the material. \n- Temperature 850C for LAO \n- Temperature 100C for Gold\n- Plume shoots out single atoms and it will react with ambient oxygen in the container. Depends on the stochiometery of the system. It can be tuned to the \n\nPut more parameters in paper of the PLD.\n\n\n\n\n## Week 2\n### Notes:\nMeasurement will be done next week. Today is the finalization of the 4 u.c FET. Use probe station to measure I-V curve.  Sweep $V_{gs}$ with constant $V_{ds}$. Measure $I_{ds}$ and measure $V_{gs}$\n\n\nFor Vgs sweep\n- Vgs sweep from -2V to 1V steps of 5e-3\n- Vds increment by 100mV from -0.5V to 0.5V\n\nFor Vds sweep\n- Vds sweep from -0.5 to 5V steps of 5e-3\n- Vgs increment by 100mV from -0.5V to 0.5V\n\n### Simulation\n\nResource: https://journals.aps.org/prl/pdf/10.1103/PhysRevLett.109.196803\n\nDiscuss mainly on the percolation effect. Modelling will be done using RRTN and perhaps Variable-range hopping theory in which is also discussed in the paper. Another option is to use capacitor based modelling. Could be done by sweeping the whole $C_{LAO}$ variable and curve fit it to the measurement. Much more interesting to use the RRTN/VRH theory.\n\nFocus on the non-percolative region from the paper. (2D variable range hopping model or RRTN) that can be switch and might even have memristive effects. Eq 1 and Eq 2 should be the focus of the model. Hence it would be beneficial to give a certain percolative simulation, based on the paper p=0.3 already gives a conduction.\n\n**Eq 1**: This is temperature dependent, hence might be time consuming to test.\n\\begin{align}\nR = R_0 \\exp \\left( \\left[ \\frac{T_0}{T}\\right]^v \\right)\n\\end{align}\n\n**Eq 2**: Using the RRTN percolation model for our FET might be a good start.\n\\begin{align}\nI_{sd} &\\propto (V_{sd} - V_c)^{\\delta}  \\text{  for  } V_{sd} \\geq V_{c} \\\\\nI_{sd} &= 0 \\text{  for  } V_{sd} < V_c\n\\end{align}\n\nSince we model it as it it proportional to some factor, we can use scipy least square minimization along with the model. \n\n\n\n## Week 3\n### Measurement\nProbe setup measurement, measure:\nFor measurements it was found that -2.5 Volts was maximum for the device with 4 uc.\n\nEach measurement measures the current through Ids and through Ig.\n\nSweep parameters are Vds and Vgs, and interchangeable line series. Currently measuring for for:\n\n**Ids vs Vgs** \n- Vgs sweeped from -2.5V to 1V at steps of 5e-3\n- Vds is fixed at 100mV. \n- Other setup is Vds is lineseries of 400mVpp step of 100mV.\n\n**Ids vs Vsd**\n- Vds sweeped at 500mVpp setp of 5e-3\n- Vgs lineseires is set from -2.5V to 1V step of 100mV\nIg is also measured along with the two setup.\n\nNote that in the data file:\n\n**K200 == Vgs **\n\n**K200-2 == Vds **\n\n### Modelling\nuse Hoshen-Kopelman algorithm for percolation : http://phony1.technion.ac.il/~lsharir/p3d/percolation.html for island grouping.\n\ndetails on percolation : http://physik.uni-graz.at/~cbl/CP1/contents/Texts/\n\n\nGrid generation of a uniformly distributed samples is shown below. White shows that it is not conducting, black shows that it is conducting region. Need to model the tunneling to get everything right. \n\nAssumptions:\n- PLD is homogenous, hence the occupation probability is the same. Can be altered to normal distribution from the center. Percolation threshold will likely be different then.\n- The size of the cell is large enough so that the shape of the site does not matter. \n- if it is site percolation, it is assumed that the connection between 2 sites are perfect. For bond percolation, further improvement can be implemented including quantum tunneling between two sites. \n\nFull program is shown in Percolation.py chapter.\n\n## Week 4\n### Data from 4uc FET\n\n\n\n```python\n#Data handling for Labview output. Seperate different line segments, folder in dev15_vsd needs to be deleted first.\n\ndef dataparsing(input_file, output_file, data_width):\n    j = 0\n    with open(input_file, 'r') as f_i:    \n        for line, data in enumerate(f_i):\n            if line % data_width == 0:\n                j = j + 1\n            else:\n                with open(output_file + str(j) + '.txt','a+') as f_o:\n                    f_o.write(data)\n\ninput_file = 'Data\\\\4_uc_new device\\\\dev16\\\\Dev16_Vgs-sweep -2V to 1V -- Vds 0V to 1V.txt'\noutput_file = 'Data\\\\4_uc_new device\\\\dev16\\\\Dev16_RoomT_Vgs_sweep\\\\dev16_dataset'\ndata_width = 606\n\ndataparsing(input_file, output_file, data_width)\n```\n\n\n```python\ndef wrapper_vds(dataframe):\n    dataframe.drop('Unnamed: 5', axis=1,inplace=True)\n    dataframe.columns = ['time','Vgs','Vds','Igs','Ids']\n    return dataframe\n\ndef new_range(start,end,step):\n    i = start\n    while i < end:\n        yield i\n        i += step\n    yield end\n    \ndef find_nearest(array, value):\n    array = np.asarray(array)\n    idx = (np.abs(array - value)).argmin()\n    return idx\n\ndef quadratic_fitting(x, a, b):\n    y = a*(x-b)**2\n    return y\n\ndef plus_string(number):\n    if number < 0:\n        x = '$-$' + str(round(abs(number), 2))\n    elif number > 0:\n        x = '+' + str(round(number, 2))\n    return x\n\nfig1 = plt.figure(1)\nax = fig1.add_subplot(1, 1, 1)  \n\nfig2 = plt.figure(2)\nax2 = fig2.add_subplot(1, 1, 1)  \n\n# fig3 = plt.figure(3)\n# ax3 = fig2.add_subplot(1, 1, 1)  \n\nV_sat_data = []\nfor i in new_range(17, 35, 2):    # set number of data here: max # 36\n    \n    # df1 = pd.read_csv('Data\\\\dev15\\\\dev15_vsd\\\\dev15_dataset'+str(i)+'.txt',sep='\\t',skiprows = [0,1,2])\n    df2 = pd.read_csv('Data\\\\dev16\\\\dev16_huge_sweep\\\\dev16_dataset'+str(i)+'.txt',sep='\\t',skiprows = [0,1,2])\n    \n    # df_wrap1 = wrapper_vds(df1)\n    df_wrap2 = wrapper_vds(df2)\n    \n    Vgs = -2.5 + (0.1*i-0.1)\n    Ids_list = df_wrap2['Ids'] # Still in ampere\n    Vds_list = df_wrap2['Vds']\n    V_sat_index = find_nearest(Vds_list[1:1200], Vgs+1.8)\n    V_sat_data.append((Vds_list[V_sat_index], Ids_list[V_sat_index]/10**(-6), Vgs))\n    \n    Igs_smooth = savgol_filter(df_wrap2['Igs'],99,3)  # Filter out noise with savgol filter\n    # plt.plot(df_wrap1['Vds'], df_wrap1['Ids']/(10)**(-6), label = 'Vgs ='+str((i*-100)+100)+'mV',linestyle = 'dashed')\n    ax.plot(df_wrap2['Vds'], df_wrap2['Ids']/(10)**(-6), label = 'Vgs ='+str(round(Vgs,2))+' V')\n    if Vgs <= -0.75: \n        ax.text(Vds_list[1200]+0.05, Ids_list[1200]/(10)**(-6) -0.5, plus_string(Vgs),  withdash=False, fontsize=9)\n    elif Vgs >= -0.7:\n        ax.text(Vds_list[1200]+0.05, Ids_list[1200]/(10)**(-6), plus_string(Vgs),  withdash=False, fontsize=9)\n        \n    ax2.plot(df_wrap2['Vds'], Igs_smooth/(10**(-6)), label = 'Vgs ='+str(round(Vgs,2))+' V') # Ig is in micro-amps\n    \n    \n\nVds_tuple, Ids_tuple, Vgs_tuple = zip(*V_sat_data)\n\npopt, pcov = curve_fit(quadratic_fitting, Vds_tuple, Ids_tuple)\nprint(popt)\nVds_new = np.linspace(popt[1], 5, num = 100, endpoint=True)\nIds_new = quadratic_fitting(Vds_new, *popt)\n# ax.plot(Vds_tuple,Ids_tuple)\nax.plot(Vds_new, Ids_new)\nax.scatter(Vds_tuple, Ids_tuple)\n\n\n## Plot setting for fig1 (Id vs Vds)\n# ax.set_title('100$\\mu m^2$ Gate Area')\nax.set_xlabel('$V_{ds}$ [V]', fontsize=10)\nax.set_ylabel('$I_{d}$ [$\\mu$A]', fontsize=10)\n# ax.legend(bbox_to_anchor=(1.05, 1), loc=2)\nax.set_xlim(-0.5, 5)    \nax.set_ylim(-1, 34)\nax.minorticks_on()\nax.tick_params(axis = 'y', which = 'both', length=5, direction='in')\nax.tick_params(axis = 'both', which = 'minor', labelsize = 9)\nax.text(5+0.05, 34+0.5, ' $V_{gs}$ [V]',  withdash=False, fontsize=9) # Vgs label is set manually\nfig1.set_size_inches(plot_width*1.1, plot_height*1.4)\n# fig1.savefig('Figures\\\\Dev16_Vds_sweep-Ids.pdf', format='pdf', bbox_inches='tight')\n    \n    \n## plot setting for fig2 (Ig vs Vds)\nax2.legend(prop={'size': 8}, loc=1, bbox_to_anchor=(1,1), bbox_transform=ax2.transAxes)\n# ax2.set_title('100$\\mu m^2$ Gate Area')\nax2.set_xlabel('$V_{ds}$ [V]', fontsize=10)\nax2.set_ylabel('$I_{g}$ [$\\mu$A]', fontsize=10)\nax2.minorticks_on()\nax2.tick_params(axis = 'y', which = 'both', length=5, direction='in')\nax2.tick_params(axis = 'both', which = 'minor', labelsize = 9)\nfig2.set_size_inches(plot_width*1.1, plot_height*1.4)\nax2.set_ylim(-0.01, 0.01)\nax2.set_xlim(-0.5, 5) \n#fig2.savefig('Figures\\\\Dev16_Vds_sweep-Igs.pdf', format='pdf', bbox_inches='tight')\n\n# Fig 3 setting\n```\n\nSaturation region is clearly shown in the figure. The saturation region is flat, no short body effect as expected. As Vgs gets bigger, (more positive) it shows that the hysterisis gets bigger. Gate current plot shows that it has relatively low leakage <2nA.\n\n**Notes**: The Vt is not negative. It should be at negative ~-1.5V by the curve fit. Hence the parabola should be shifted to the negative side. Hence it may be concluded that the saturation isn't exactly a parabola. Different function needs to be checked. Because it might be that saturation takes place in a 'shallower' manner with respect to the quadratic term. The saturation regime is also not only dependent on the Vgs-Vt. It grows bigger/smaller under several cases. \n\n\n```python\n\n########\n # Vgs transistor characterstic plotter - plot Vgs sweep characetristic, find the subthreshold swing with exponential# Vgs tr \n#                                       Curve fit\n###\ndef wrapper_vgs(dataframe):\n    dataframe.drop('Unnamed: 5', axis=1,inplace=True)\n    dataframe.columns = ['time','Vds','Vgs','Ids','Igs']\n    return dataframe\n\ndef exponent_fit(x, b, c):\n    return 10**(b*x+c)\n\ndef Vgs_plotter(data_location, loop_var1, loop_var2):\n    data_linspace = np.round(np.linspace(-0.5,0.5, num = 21),2)  #set the data linspace for proper range\n    gradient = []\n    Vds_arr = []\n    on_off_rat = [] \n    for i in range(loop_var1, loop_var2,3):\n        df = pd.read_csv(data_location + str(i) + '.txt', sep='\\t', skiprows = [0,1,2])\n        df_wrap = wrapper_vgs(df)\n        \n        fig1 = plt.figure(1)\n        plt.semilogy( df_wrap['Vgs'], df_wrap['Igs']/(10)**(-6), label = 'Vds =' + str(data_linspace[i-1]) + 'V')\n        plt.legend(prop={'size': 8})\n        plt.xlabel('$V_{gs}$ [V]', fontsize=10)\n        plt.ylabel('$I_{d}$ [$\\mu$A]', fontsize=10)\n        ax = plt.gca()\n        ax.tick_params(axis = 'both', which = 'both', length=5, direction='in')\n        ax.minorticks_on()\n        ax.tick_params(axis='both', which='minor', length=3)\n        fig1.set_size_inches(plot_width , plot_height*1.3)\n\n        \n        fig2 = plt.figure(2)\n        plt.plot( df_wrap['Vgs'], (df_wrap['Ids']/(10)**(-6)), label = 'Vds =' + str(data_linspace[i-1]) + 'V')\n        plt.legend(prop={'size': 8})\n        plt.xlabel('$V_{gs}$ [V]', fontsize=10)\n        plt.ylabel('$I_{g}$ [$\\mu$A]', fontsize=10)\n        ax2 = plt.gca()\n        ax2.tick_params(axis = 'both', which = 'both', length=5, direction='in')\n        ax2.minorticks_on()\n        ax2.tick_params(axis='both', which='minor', length=3)\n        fig2.set_size_inches(plot_width, plot_height*1.3)\n        \n        \n        fig3 = plt.figure(3)\n        Vgs_linspace = df_wrap['Vgs']\n        Ids_data = df_wrap['Igs']/10**(-6)  # Ids Data is in micro amps\n        popt, pcov = curve_fit(exponent_fit, Vgs_linspace[610:625], Ids_data[610:625])\n        Vgs_new = np.linspace(-1.2, -0.9, endpoint=True)\n        Ids_new = exponent_fit(Vgs_new, *popt)\n        \n        plt.semilogy(Vgs_linspace[0:650], Ids_data[0:650], label = 'Vds =' + str(data_linspace[i-1]) + 'V')\n        plt.semilogy(Vgs_new, Ids_new, linewidth=1 , linestyle = 'dashed')\n        plt.legend(prop={'size': 8})\n        plt.xlabel('$V_{gs}$ [V]', fontsize=10)\n        plt.ylabel('$I_{d}$ [$\\mu$A]', fontsize=10)\n        ax3 = plt.gca()\n        ax3.tick_params(axis = 'both', which = 'both', length=5, direction='in')\n        ax3.minorticks_on()\n        ax3.tick_params(axis='both', which='minor', length=3)\n        ax3.legend(bbox_to_anchor=(1.05, 1), loc=2)\n\n        fig3.set_size_inches(plot_width, plot_height*1.3)\n\n\n        gradient.append(((Vgs_new[-1] - Vgs_new[0])*1000)/(np.log10(Ids_new[-1])-np.log10(Ids_new[0])))\n        on_off_rat.append(Ids_data[1000]/Ids_data[650]) # set the on-off ratio properly too\n        Vds_arr.append(data_linspace[i-1])\n        \n    fig4 = plt.figure(4)\n    ax4 = fig4.add_subplot(111) \n    ax5 = ax4.twinx()\n    ax4.plot(Vds_arr, gradient, '-o', color='r',label='Subthreshold')\n    ax5.plot(Vds_arr, on_off_rat, '-^', color='b', label='on/off ratio')\n    \n    \n    ax4.tick_params(axis = 'both', which = 'both', length=5, direction='in')\n    ax4.minorticks_on()\n    ax4.set_xlabel('$V_{ds}$ [V]', fontsize=10)\n    ax4.set_ylabel('$S_{s-th}$ [mV/dec]', fontsize=10)\n    ax4.tick_params(axis='both', which='minor', length=3)\n    \n    ax5.tick_params(axis = 'both', which = 'both', length=5, direction='in')\n    ax5.minorticks_on()\n    ax5.set_xlabel('$V_{ds}$ [V]', fontsize=10)\n    ax5.set_ylabel('On/Off $I_d$ ratio', fontsize=10)\n    ax5.tick_params(axis='both', which='minor', length=3)\n    \n    fig4.legend(prop={'size': 8}, loc=1, bbox_to_anchor=(1,0.30), bbox_transform=ax4.transAxes)\n  \n    fig4.set_size_inches(plot_width , plot_height*1.4)\n#     fig4.savefig('Figures\\\\Dev16_lowT_Subth-on-off.pdf', format='pdf', bbox_inches='tight')\n#     fig1.savefig('Figures\\\\Dev16_lowT_Vgs_sweep-Ids.pdf', format='pdf', bbox_inches='tight')\n#     fig2.savefig('Figures\\\\Dev16_lowT_Vgs_sweep-Igs.pdf', format='pdf', bbox_inches='tight')\n\n    \n\n\n# change data set! might be switched. Check what Id of the source K200 K200-2\nVgs_plotter('Data\\\\4_uc_new device\\\\dev16\\\\Dev16_LowT_Vgs_sweep\\\\dev16_dataset', 12, 22) #12 max\n\n# plt.savefig('Figures\\\\percprob_vs_occprob.pdf', format='pdf', dpi=300)\n```\n\nGraph of typical Ids vs Vds Fet charactersitic.\nThreshold swing of 285mV/dec. Due to high carrier density. As Cox -> infinity it is close to theoretical 60mV/decade. Memristor like effect hysterisis and such present. Hysteris is reproducible, good for oxide base memristor.\n\nSubthreshold swing is as 285mV/dec, the on/off ratio increases with Vds as expected since more Vds, more current. At off, the tunneling current dominates.\n\n**Notes**: Conclude that it will not be suitable for transistor operations. While it does show promise as a memristor like device. Vt here can be deduce that it is approximately -1V. When fully depleted it will have higher Vt when going back up.\n\n# Week 5 and Week 6\n\n**3.6 uc and new 4 uc sample measurement:** \n\nBoth samples are insulating, Vgs until 50Vs doesn't activate it. Wait until next sample next week. In the mean time:\n\n## To do list:\n- <s>find the subthreshold swing</s>\n- <s>Find 10 most dominant path, that should be enough to determine the current going through the sample </s>\n- <s>Research CV characteristic measurement setup </s>\n- <s>plot igs vs Vds </s>\n- <s>Measurement that it scales well with all the devices. </s>\n- <s>Write premilinary analysis on percolation  </s>\n\n\n\n\n\n\n# Week 7\n\n## To do list:\n\n- <s>on off ratio vs Vds  </s>\n- <s>Subthreshold swing vs Vds , plot highest gradient  </s>\n- <s> number of paths in a sample found vs Resistance, Number of paths found vs occupation probability </s>\n- <s>fit parabola properly,ignore initial data set, below 0  </s>\n\n\n# Week 8\n\n\nCV measurement with probestation by measuring impedance subsequently finding the reactance and hence the capacitance. Data uses phase and Z value. Use:\n\n$$ X = Z sin(\\Theta) $$\n$$ X_c = \\frac{1}{2\\pi f C}$$\n\n## To do list:\n- Make all the figures properly.\n- Measure CV charactersitics, do analysis\n- Measure the mobility of the sample\n- Modify the Percolation.py into RRTN\n- plot the low temperature graphs.\n- Finish methods in the report\n\n# Percolation.Py\n\nThe following is the code for the percolation FET. The first part introduce the code for generating grid and also finding the path. The rest of the code follows from the orignal code with extensions to consider RRTN and also to find the percolating threshold $p_c$ by numerical simulation.\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport heapq\n\nfrom ipywidgets import IntProgress\nfrom IPython.display import display\nfrom matplotlib import cm\nfrom contextlib import suppress\n\nclass PriorityQueue:       # FIFO queue\n    def __init__(self):\n        self.elements = []\n    \n    def empty(self):\n        return len(self.elements) == 0\n    \n    def put(self, item, priority):\n        heapq.heappush(self.elements, (priority, item))\n    \n    def get(self):\n        return heapq.heappop(self.elements)[1]\n\nclass GenerateGrid(object):     # Generate grid for sample based on size and occupy prob.\n    def __init__(self,width,height,occupy_prob):\n        self.width = width\n        self.height = height\n        self.occupy_prob = 1-occupy_prob\n        self.wall = [] \n        self.grid = np.zeros(shape=(self.height,self.width))\n        self.grid_RRTN = np.zeros(shape=(self.height,self.width))\n        \n    def in_bounds(self,id):\n        (x,y) = id\n        return 0 <= x < self.width and 0 <= y < self.height\n\n    def passable(self, id):\n        return id not in self.wall\n    \n    def neighbors(self,id):\n        (x,y) = id\n        results = [(x+1,y), (x,y-1), (x-1,y), (x,y+1)]\n        if (x + y) % 2 == 0:\n            results.reverse()\n        results = filter(self.in_bounds, results)\n        results = filter(self.passable, results)\n        return results\n\n    def generate_rrtn(self):\n        for (x, y), item in np.ndenumerate(self.grid):\n            if item == 1:\n                if x >= 0:\n                    if self.grid[x-2, y] == 1:\n                        self.grid_RRTN[x-1, y] = 1\n                        continue\n                        \n                # Check bottom.\n                if y >= 0:\n                    if self.grid[x, y-2]  == 1:\n                        self.grid_RRTN[x, y-1] = 1\n                        continue\n\n                # Check top.\n                with suppress(IndexError):\n                    if self.grid[x, y+2]  == 1:\n                        self.grid_RRTN[x, y+1] = 1\n                        continue\n\n                # Check right.\n                with suppress(IndexError):\n                    if self.grid[x+2, y]  == 1:\n                        self.grid_RRTN[x+1, y] = 1\n                        continue\n        \n    def GenerateWall(self):    # generate pseudo-random wall \n        patches = np.random.rand((self.height-2), self.width) \n        self.grid  =  np.vstack((np.ones(self.width), patches, np.ones(self.width)))\n        for i in range(0, self.height):\n            for j in range(0, self.width):\n                if self.grid[i,j] < self.occupy_prob:\n                    self.wall.append((j,i))  \n                    self.grid[i,j] = 0\n                else:\n                    self.grid[i,j] = 1\n                         \ndef pathfinder(came_from, start, goal):     # Function to find path taken by A* search algorithm\n    current = goal\n    path = []\n    while current != start:\n        try:\n            path.append(current)\n            current = came_from[current]\n            path_flag = True \n        except KeyError:     # Except for no path found\n            path = []\n            path_flag = False\n            break\n    path.append(start) \n    return path,path_flag\n\ndef heuristic(a, b):      # set direction of A*\n    (x1, y1) = a\n    (x2, y2) = b\n    return abs(x1 - x2) + abs(y1 - y2)\n\ndef a_star_search(graph, start, goal):\n    frontier = PriorityQueue()\n    frontier.put(start, 0)\n    came_from = {}\n    cost_so_far = {}\n    came_from[start] = None\n    cost_so_far[start] = 0\n    \n    while not frontier.empty():\n        current = frontier.get()\n        \n        if current == goal:\n            break\n        \n        for next in graph.neighbors(current):\n            new_cost = cost_so_far[current] + 1\n            if next not in cost_so_far or new_cost < cost_so_far[next]:\n                cost_so_far[next] = new_cost\n                priority = new_cost + heuristic(goal, next)\n                frontier.put(next, priority)\n                came_from[next] = current\n    \n    return came_from, cost_so_far\n\n#End of percolation code\n```\n\n\n```python\n# This code is for sweeping the occupation probability to find the threshold occupation probability.\n# Variables include the size of the sample.loop, and the number of intervals between 0 to 1 for p\n\nwidth =  100\nheight = 100\nLoop = 5     # Number of tries per occupation probability\nlinseries_point = 50        # number of steps between 0 to 1 for occupation probability\n\noccupation_probability = np.linspace(0, 1, num=linseries_point, endpoint=True)\nstart, goal = ((width)/2, 0),((width)/2 , height-1)\noccupy_histogram = []\npath_average = np.zeros(len(occupation_probability))\nprogress = 0\n\nf = IntProgress(min=0, max=len(occupation_probability), description = 'Progress:')\ndisplay(f) \n\nfor indices, occupy_prob in enumerate(occupation_probability):\n    counter = 0\n    path_sum = []\n    for i in range(0,Loop):\n        sample = GenerateGrid(width, height, occupy_prob) \n        sample.GenerateWall()\n        came_from, cost_so_far = a_star_search(sample, start, goal)\n        path, path_flag = pathfinder(came_from, start=start, goal=goal)\n        if path_flag is True:\n            counter += 1\n            path_sum.append(cost_so_far[goal])\n    occupy_histogram.append(counter)\n    path_average[indices] = np.nanmean(path_sum)\n    progress += 1\n    f.value = progress\n\n\n# d = {'occupation probability' : occupation_probability, 'Percolate frequency' : occupy_histogram}\n# df = pd.DataFrame(d)\n# file_name = 'PercSimData\\\\perc_%sx%s_Loop%s_lineseries%s' %(width, height, Loop, linseries_point)\n# df.to_csv(file_name, sep='\\t')\n\npath_average[np.isnan(path_average)] = 0\n\nfig1 = plt.figure(1)\nax1 = fig1.add_subplot(111)  \nax1.plot(occupation_probability, occupy_histogram)\nplt.xlabel('Occupation Probability', fontsize=10)\nplt.ylabel('Percolation Probability', fontsize=10)\nax1 = plt.gca()\nax1.tick_params(axis = 'both', which = 'both', length=5, direction='in')\nfig1.set_size_inches(plot_width, plot_height)   \n\n\n# fig2 = plt.figure(2)\n# ax2 = fig2.add_subplot(1, 1, 1)  \n# ax2.plot(occupation_probability, path_average)\n# plt.xlabel('Occupation Probability', fontsize=10)\n# plt.ylabel('Resistance', fontsize=10)      \n# ax2.tick_params(axis = 'both', which = 'both', length=5, direction='in')\n# fig2.set_size_inches(plot_width , plot_height)         \n\n```\n\n\n```python\n#The following code plots the data point from the previous code for different sample size.\nfrom scipy.optimize import curve_fit\n\ndef sigmoid(x, a, b, c, d):\n    y = a / (1 + np.exp(-b*x-c)) + d\n    return y\n\nname_array = [8, 20, 50, 100]\nlabel_array = ['8x8','20x20', '50x50', '100x100']\n\nfor labl_number, number in enumerate(name_array):\n    df = pd.read_csv('PercSimData\\\\perc_%sx%s_Loop20_lineseries200.txt' %(number, number), sep='\\t', dtype=np.float64)\n    popt, pcov = curve_fit(sigmoid, df['occupation probability'], df['Percolate frequency']/20)\n    \n    occ_prob_new = np.linspace(0, 1, num = 10000, endpoint=True)\n    perc_freq_new = sigmoid(occ_prob_new, *popt)\n    fig1 = plt.figure(1)\n    plt.plot(occ_prob_new, perc_freq_new/max(perc_freq_new), label = label_array[labl_number] + ' sample')\n    \n\nplt.xlabel('Occupation Probability', fontsize=10)\nplt.ylabel('$P_s$', fontsize=10)\nplt.legend(prop={'size': 8})\nax = plt.gca()\nax.tick_params(axis = 'both', which = 'major', labelsize = 8)\nfig1.set_size_inches(plot_width*0.9, plot_height)\n# fig1.savefig('Figures\\\\percprob_vs_occprob.pdf', format='pdf', dpi=300,bbox_inches='tight')\n```\n\n\n```python\n# The following code generates an RRTN grid and non-RRTN grid. It also plots the result of the A* algorithm into\n# an array as shown.\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport numpy as np\nimport pandas as pd\nimport heapq\n\ndef parallel_resistance(array):\n    reciprocal = sum(np.reciprocal(array, dtype=float))\n    resistance = 1/reciprocal\n    return resistance\n\n\ndef shortest10_paths(width, height, occupation_probability):\n    start, goal = ((width)/2, 0),((width)/2 ,height-1)\n\n    path_list = []\n    n_path = 0    # Number of paths initialize\n    sample = GenerateGrid(width, height, occupation_probability) \n    \n    sample.GenerateWall()\n    sample.generate_rrtn()\n    Wall_OR_RRTN = np.logical_or(sample.grid_RRTN,sample.grid) # Wall is OR ed with the old sample\n    RRTN_wall = np.subtract(Wall_OR_RRTN,sample.grid)*2\n    RRTN_sample = np.add(sample.grid,RRTN_wall)\n    \n    fig1, ax1 = plt.subplots(1)   \n    cmap = cm.colors.ListedColormap(['white','black']) \n    ax1.pcolor(sample.grid, cmap=cmap) \n    fig1.set_size_inches(3, 3)\n    \n    fig2, ax2 = plt.subplots(1)\n    cmap2 = cm.colors.ListedColormap(['white','black','blue']) \n    bounds = [0, 1, 2, 3]\n    norm = cm.colors.BoundaryNorm(bounds,cmap2.N)\n    img = plt.pcolor(RRTN_sample, cmap=cmap2, norm=norm) \n    fig2.set_size_inches(3, 3)\n    \n\n    path_sum = []   #list for path sum array\n\n    for i in range(0,1):     # find 10 independent paths ## CURRENTLY SET AT 100, set at the sample size\n        came_from, cost_so_far = a_star_search(sample, start, goal)\n        path, path_flag = pathfinder(came_from, start=start, goal=goal)\n        for coordinate in path:      # Exclude coordinates in the top and bottom row\n            if coordinate[1] != height-1:\n                if coordinate [1] != 0:\n                    sample.wall.append(coordinate)\n                    sample.grid[int(coordinate[1]), int(coordinate[0])] = 0\n        ax1.plot(*zip(*path), color='red', linewidth=4)\n        \n        if path_flag is True:\n            path_sum.append(cost_so_far[goal])\n            n_path += 1\n    \n    if not path_sum:\n        sample_resistance = 0\n    else:\n        sample_resistance = parallel_resistance(path_sum)   #collective sum of resistant\n        \n#     fig1.savefig('Figures\\\\pc-' + str(occupation_probability) + '.pdf', format='pdf', dpi=300)\n    fig1.savefig('Figures\\\\Perc_sample-' + str(occupation_probability) + '.pdf', format='pdf', dpi=300)\n\n    return sample_resistance, n_path\n\n\n\nwidth =  30    #Keep sample even. If odd, change the start/goal coordinate starting coordinate\nheight = 30\nresistance_array = []\npath_num_avg = []\n\nnum = 3     # number of linspace for occupation probability\nn = 1     #number of retries\noccupy_range = np.linspace(0.5,0.99, num=num)\n\n\n\nf = IntProgress(min=0, max=len(occupy_range), description = 'Progress:')\ndisplay(f) \nprogress = 0\n\nfor occupy in [0.4]:        # set occupy range here\n    occupation_probability = occupy\n    sample_resistance = []\n    indv_path_num = []\n    for sample in range(0,n):        #For every sample, calculate n times\n        resistance, n_path = shortest10_paths(width, height, occupation_probability)\n        sample_resistance.append(resistance)\n        indv_path_num.append(n_path)\n       \n        \n    sample_resistance = [x for x in sample_resistance if x != 0]\n    indv_path_num = [x for x in indv_path_num if x != 0]\n\n    if sum(sample_resistance) == 0:\n        resistance_array.append(0)\n        path_num_avg.append(0)\n    else: \n        average_resistance = np.average(sample_resistance)\n        average_path_number = np.average(indv_path_num)\n        \n        resistance_array.append(average_resistance)\n        path_num_avg.append(average_path_number)  #resistance_array => average resistance on the sample after looped\n        \n    progress += 1\n    f.value = progress\n\n\n# data = list(zip(path_num_avg, resistance_array, occupy_range))\n# df = pd.DataFrame(data, columns=['Number of Paths', 'Resistance','Occupation Probability'])\n# df.to_csv('PercSimData\\\\Sample_resistance\\\\sample_property_25path_search_num=' + str(num) + '.txt', sep='\\t', index=False)\n\n# ax1.tick_params(axis = 'both', which = 'major', labelsize = 10)\n# fig1 = plt.figure(1)\n# ax = fig1.add_subplot(1, 1, 1) \n# ax.plot(occupy_range,resistance_array)\n\n# ax.set_ylabel('Resista',fontsize=11)\n# Note that there are precision issue. nanmean is f4 precision. \n\n\n\n```\n\n\n```python\n# This final code is to investigate the number of N paths that can exist in the sample. It can calculate the\n# resistance of the sample hence the conductivity.\n\n# data = list(zip(occupy_range,resistance_array))\n# df = pd.DataFrame(data, columns=['Occupation Probability', 'Resistance'])\n# df.to_csv('PercSimData\\\\Sample_resistance\\\\sample_resistance.txt', sep='\\t', index=False)\n\ndf = pd.read_csv('PercSimData\\\\Sample_resistance\\\\sample_resistance_num=100.txt', sep='\\t')\ndf2 = pd.read_csv('PercSimData\\\\Sample_resistance\\\\sample_property_25path_search_num=40.txt', sep='\\t')\n\n\nfig1 = plt.figure(1)\nax1 = fig1.add_subplot(1, 1, 1)  \nsigma = 1/df['Resistance']\nmax_sigma_val = np.nanmin(sigma[sigma != np.inf])\n\nax1.plot(df['Occupation Probability'], sigma/0.029903)\n#ax1.set_yscale('log')\nax1.set_xlabel('Occupation Probability', fontsize=10)\nax1.set_ylabel('Conductivity ($\\Omega^{-1}$)', fontsize=10)\nax1.tick_params(axis = 'both', which = 'both', length=5, direction='in')\nax1.minorticks_on()\nax1.tick_params(axis='both', which='minor', length=3)\nfig1.set_size_inches(plot_width*0.9, plot_height)\n#fig1.savefig('Figures\\\\Resistance_OccProb.pdf', format='pdf', dpi=300, bbox_inches='tight')\n\n# number of paths in a sample found vs Resistance, Number of paths found vs occupation probability\nfig2 = plt.figure(2)\nax2 = fig2.add_subplot(111)\nax2.scatter(df2['Occupation Probability'], df2['Number of Paths'])\nax2.set_xlabel('Occupation Probability', fontsize=10)\nax2.set_ylabel('Number of Paths', fontsize=10)\nax2.tick_params(axis = 'both', which = 'both', length=5, direction='in')\nax2.minorticks_on()\nax2.tick_params(axis='both', which='minor', length=3)\nfig2.set_size_inches(plot_width*0.9, plot_height)\n\nfig3 = plt.figure(3)\nax3 = fig3.add_subplot(111)\nax3.scatter(df2['Number of Paths'], df2['Resistance'])\nax3.set_xlabel('Number of Paths', fontsize=10)\nax3.set_ylabel('Resistance ($\\Omega$)', fontsize=10)\nax3.tick_params(axis = 'both', which = 'both', length=5, direction='in')\nax3.minorticks_on()\nax3.tick_params(axis='both', which='minor', length=3)\nfig3.set_size_inches(plot_width*0.9, plot_height)\n\n# fig1.savefig('Figures\\\\OcProb-Conduct.pdf', format='pdf', dpi=300,bbox_inches='tight')\n# fig2.savefig('Figures\\\\OcProb-NumPaths.pdf', format='pdf', dpi=300,bbox_inches='tight')\n# fig3.savefig('Figures\\\\NumPaths-Resistance.pdf', format='pdf', dpi=300,bbox_inches='tight')\n\n\n```\n\n1/N dependence on 3rd figure, exponential on the 2nd figure. \n\n# CV Measurement\n\n\n```python\n# The following code plots the CV measurement obtained from the Keithley impedance measurement.\n\ndef wrapper_vgs(dataframe):\n    dataframe.drop('Unnamed: 5', axis=1,inplace=True)\n    dataframe.columns = ['time','Vds','Vgs','Igs','Ids']\n    return dataframe\n\ndf = pd.read_excel('Data\\\\CV Measurement\\\\dev16\\\\CV 10 KHz 50mV -- Vgs -2V to 1V.xls')\nDC_linspace = df['DCV_AB']\nX_c = abs(df['Z_AB'])*np.sin(df['Theta_AB']*sp.pi/180)\n\n# X_c_smooth = savgol_filter(X_c,99,3)  \n\nC = -1/(X_c*10000*2*sp.pi)\nfig, ax1 = plt.subplots()\nax1.plot(df['DCV_AB'], df['Z_AB'], label = 'Z' )\nax1.set_xlabel('$V_{gs}$ (V)', fontsize=10)\nax1.set_ylabel('Z ($\\Omega$)',  fontsize=10) \nax1.tick_params(axis = 'both', which = 'both', length=5, direction='in')\nax1.minorticks_on()\nax1.tick_params(axis='both', which='minor', length=3)\n# ax1.set_ylim(-10**(-12),10**(-12))\n\nax2 = ax1.twinx()\nax2.plot(df['DCV_AB'],  df['Theta_AB'], color='r', label = '$\\Theta$')\nax2.set_ylabel('Phase $\\Theta$', fontsize=10)\nax2.tick_params(axis = 'both', which = 'both', length=5, direction='in')\nax2.minorticks_on()\nax2.tick_params(axis='both', which='minor', length=3)\nfig.set_size_inches(plot_width, plot_height*1.3)\n\nfig.legend(prop={'size': 8}, loc=1, bbox_to_anchor=(0.95,0.45), bbox_transform=ax1.transAxes)\n\n\nfig2, ax3 = plt.subplots()\nfor i in [10]:\n    df_cv = pd.read_csv('Data\\\\CV Measurement\\\\CV-Dataframe\\\\dev1-CV-' + str(i)+'KHz.txt', sep='\\t')\n    ax3.plot(df_cv['DC_linspace'],df_cv['C']/10**(-12), label = str(i)+'KHz')\n    ax3.set_xlabel('$V_{gs}$ (V)', fontsize=10)\n    ax3.set_ylabel('C (pF)',  fontsize=10) \n    ax3.tick_params(axis = 'both', which = 'both', length=5, direction='in')\n    ax3.minorticks_on()\n    ax3.tick_params(axis='both', which='minor', length=3)\n    fig2.set_size_inches(plot_width, plot_height*1.3)\n#     plt.legend(prop={'size': 9})\n\n# fig2.savefig('Figures\\\\CV-Measurement\\\\dev16-CV-Frequency_Dependence.pdf', format='pdf', dpi=300,bbox_inches='tight')\n# fig.savefig('Figures\\\\CV-Measurement\\\\dev16-Impedance_10Khz.pdf', format='pdf', dpi=300,bbox_inches='tight')\n\n\n# data = list(zip(DC_linspace, C))\n# df_to_csv = pd.DataFrame(data, columns=['DC_linspace', 'C'])\n# df_to_csv.to_csv('Data\\\\CV Measurement\\\\CV-Dataframe\\\\dev1-CV-50KHz.txt', sep='\\t', index=False)\n\n```\n\n## Mobility and Electron density\n\n\n```python\n# This section of code plots the mobility and the carrier density of the sample. The formula follows from\n# Eerkes' thesis.\n\nimport scipy.constants as const\n\nVds_tuple, Ids_tuple, Vgs_tuple = zip(*V_sat_data)\nepsilon_r = 6.7\n\nfig1, ax1 = plt.subplots()\nn_s = [((const.epsilon_0 * epsilon_r * Vd_sat)/(const.elementary_charge*1.5*10**(-9)))/10000 for Vd_sat in Vds_tuple]\nmu = [(2*(Id_sat*10**(-6)*1.5**(10-9))/(const.epsilon_0*epsilon_r*Vd_sat**2))/10000 for Vd_sat, Id_sat in zip(Vds_tuple, Ids_tuple)]\nax1.scatter(Vgs_tuple, n_s, marker='^', color='r', label = 'Carrier density')\nax1.set_xlabel('$V_{gs}$ (V)', fontsize=10)\nax1.set_ylabel('$n_s$ ($cm^{-2}$)',  fontsize=10) \nax1.tick_params(axis = 'both', which = 'both', length=5, direction='in')\nax1.minorticks_on()\nax1.tick_params(axis='both', which='minor', length=3)\nfig1.set_size_inches(plot_width, plot_height*1.3)\n\nax2 = ax1.twinx()\nax2.scatter(Vgs_tuple,mu, marker='x', color='b', label = 'Mobility' )\nax2.set_ylabel('$\\mu$ ($cm^2/Vs$)', fontsize=10)\nax2.tick_params(axis = 'both', which = 'both', length=5, direction='in')\nax2.minorticks_on()\nax2.tick_params(axis='both', which='minor', length=3)\n\nfig1.legend(prop={'size': 8}, loc=1, bbox_to_anchor=(0.95,0.30), bbox_transform=ax1.transAxes)\n# fig1.savefig('Figures\\\\Mobility_and_Carrier_density_sample2.pdf', format='pdf', dpi=300,bbox_inches='tight')\n\n\n\n```\n", "meta": {"hexsha": "7133944ebc854886db7e4cdc43e081649158b89c", "size": 465818, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Weekly Journal.ipynb", "max_stars_repo_name": "prabowobagas/Jupyter-Notebook-Thesis", "max_stars_repo_head_hexsha": "bd374ada4409ce8be17ff7dcd5b53e1d8a4a9cac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Weekly Journal.ipynb", "max_issues_repo_name": "prabowobagas/Jupyter-Notebook-Thesis", "max_issues_repo_head_hexsha": "bd374ada4409ce8be17ff7dcd5b53e1d8a4a9cac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Weekly Journal.ipynb", "max_forks_repo_name": "prabowobagas/Jupyter-Notebook-Thesis", "max_forks_repo_head_hexsha": "bd374ada4409ce8be17ff7dcd5b53e1d8a4a9cac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 318.3991797676, "max_line_length": 62624, "alphanum_fraction": 0.9168430589, "converted": true, "num_tokens": 11563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.09401017009783025, "lm_q1q2_score": 0.028583009580434342}}
{"text": "# **Automated algorithmic bias analysis of Twitter saliency filter**\n\n\n\n## Author: \n## [**Dr. Rahul Remanan**](https://linkedin.com/in/rahulremanan), \n### [**CEO, Moad Computer (A division of Ekaveda Inc.)**](https://moad.computer)\n\nThis notebook introduces a few broad concepts, that will help develop automated testing tools to detect algorithmic bias in machine vision tools, such as saliency filters.\n\nThe tool evaluated here is the [Twitter saliency filter](https://github.com/twitter-research/image-crop-analysis).\n\n[FairFace: the face attribute dataset that is balanced for gender, race and age](https://arxiv.org/abs/1908.04913v1); is used here to generate the random image pairs for performing the saliency filter tests.\n\nQuantification of the statisitcal significance in differences between the carefully manipulated saliency filter outputs and the baseline saliency filter outputs, is performed using the [Wilcoxon signed rank test](https://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test).\n\n### Additional requirements\n\n* Valid Google account\n* This notebook by default assumes that the user is working inside the original [Google Colab environment](https://colab.research.google.com/github/MoadComputer/twitter_saliency_bias_analysis/blob/main/twitter_saliency_bias_analysis.ipynb). To run locally or in other cloud environments, please make sure that the data dependencies are satisfied.\n* Google Drive access to save the FairFace dataset and the experiment history\n\n\n\n[](https://colab.research.google.com/github/MoadComputer/twitter_saliency_bias_analysis/blob/main/twitter_saliency_bias_analysis.ipynb)\n<div>\n<a href=\"https://github.com/MoadComputer/twitter_saliency_bias_analysis\">\n\n</a>\n</div>\n\n```\nParts of the code used in this notebook are copyright protected.\nCopyright 2021 Twitter, Inc.\nSPDX-License-Identifier: Apache-2.0\n```\n\n# Install Twitter saliency filter\n\n\n```python\nimport logging\nfrom pathlib import Path\n\nlogging.basicConfig(level=logging.ERROR)\nBIN_MAPS = {\"Darwin\": \"mac\", \"Linux\": \"linux\"}\n\nHOME_DIR = Path(\"../\").expanduser()\n\ntry:\n  import google.colab\n  !python3 -m pip install -q pandas scikit-learn scikit-image statsmodels requests dash\n  ![[ -d image-crop-analysis ]] || git clone https://github.com/twitter-research/image-crop-analysis.git\n  HOME_DIR = Path(\"./image-crop-analysis\").expanduser()\n  IN_COLAB = True\nexcept:\n  IN_COLAB = False\n```\n\n\n```python\nimport sys, platform\nsys.path.append(str(HOME_DIR / \"src\"))\nbin_dir = HOME_DIR / Path(\"./bin\")\nbin_path = bin_dir / BIN_MAPS[platform.system()] / \"candidate_crops\"\nmodel_path = bin_dir / \"fastgaze.vxm\"\ndata_dir = HOME_DIR / Path(\"./data/\")\ndata_dir.exists()\n```\n\n# Import dependencies\n\n\n```python\nimport os,gc,json,glob,shlex,random,platform,warnings,subprocess,numpy as np, \\\n       pandas as pd,matplotlib.pyplot as plt,matplotlib.image as mpimg\n\nfrom PIL import Image\nfrom tqdm.auto import tqdm\nfrom scipy.stats import wilcoxon\nfrom collections import namedtuple\nfrom IPython.display import display\nfrom matplotlib.patches import Rectangle\nfrom image_manipulation import join_images\nfrom matplotlib.collections import PatchCollection\nfrom crop_api import ImageSaliencyModel, is_symmetric, parse_output, reservoir_sampling\n```\n\n# Mount Google Drive\n\nBy default this notebook assumes that the FairFace dataset is stored in the Google Drive attached here. Also, the experimental histories are saved to the Google Drive attached to this Colab notebook in `csv` format.\n\n## Data download\nDownload the FairFace dataset **`fairface-img-margin125-trainval.zip`** file and the labels **`fairface_label_train.csv`** file from the official **[FairFace GitHub repo](https://github.com/joojs/fairface)**. The maintainers of the FairFace GitHub repository have published the links to download the data in their GitHub repo README file.\n\n\n```python\nimg_dir = './'\nif IN_COLAB:\n  from google.colab import drive\n  drive.mount('/content/drive')\n  img_dir = '/content/drive/MyDrive/'\nfairface_dir = f'{img_dir}/FairFace/'\nif not os.path.exists(f'{fairface_dir}/fairface-img-margin125-trainval.zip'):\n  raise ValueError(f'Please check whether the FairFace dataset zip file exists at: {fairface_dir}/fairface-img-margin125-trainval.zip')\nif not os.path.exists(f'{fairface_dir}/fairface_label_train.csv'):\n  raise ValueError(f'Please check whether the FairFace data labels csv file exists at: {fairface_dir}/fairface_label_train.csv')\n```\n\n# FairFace helper functions\n\n\n```python\ndef random_imgID_generator(df, pairs=True):\n  num_images = len(df)\n  id1 = random.SystemRandom().choice(range(0,num_images))\n  if pairs:\n    id2 = random.SystemRandom().choice(range(0,num_images))\n    return id1, id2\n  return id1\n```\n\n\n```python\ndef eval_conditions(df, id1, id2):\n  id_condition = id1 == id2\n  race_condition = str(df.iloc[id2].race).lower()==str(df.iloc[id1].race).lower()\n  return id_condition, race_condition\n```\n\n\n```python\ndef img_pairs_filter(df,id1,id2,max_retries=100):\n  id_condition, race_condition = eval_conditions(df, id1, id2)\n  if id_condition or race_condition:\n    for i in tqdm(range(max_retries)):\n      id2 = random_imgID_generator(df, pairs=False)\n      tqdm.write(f'FairFace pair generation attempt {i+1}/{max_retries}')\n      id_condition, race_condition = eval_conditions(df, id1, id2)\n      if not id_condition and not race_condition:\n        break\n    print(f'Generated FairFace pairs in attempt: {i+1}/{max_retries}')    \n  print(f'FairFace images {id1+1} and {id2+1} selected for evaluation using Twitter Saliency algorithm ...\\n')\n  return id1, id2\n```\n\n\n```python\ndef img_info(df, id1, id2=None, verbose=False):\n  if verbose:\n    print(f'Labels for {id1+1} ...\\n')\n    print(df.iloc[id1])\n    print('\\n','-'*32)\n  info1 = { 'file': df['file'].iloc[id1].split('/')[-1].replace('.jpg',''),\n            'race': df['race'].iloc[id1],\n            'gender': df['gender'].iloc[id1],\n            'age': df['age'].iloc[id1] }\n  if id2 is not None:\n    info2 = { 'file': df['file'].iloc[id2].split('/')[-1].replace('.jpg',''),\n              'race': df['race'].iloc[id2],\n              'gender': df['gender'].iloc[id2],\n              'age': df['age'].iloc[id2] }\n    if verbose:\n      print(f'\\nLabels for {id2+1} ...\\n')\n      print(df.iloc[id2])\n    return info1, info2\n  return info1\n```\n\n\n```python\ndef execute_in_shell(command, verbose=False):\n    \"\"\" \n        command -- keyword argument, takes a list as input\n        verbsoe -- keyword argument, takes a boolean value as input\n    \n        This is a function that executes shell scripts from within python.\n        \n        Keyword argument 'command', should be a list of shell commands.\n        Keyword argument 'versboe', should be a boolean value to set verbose level.\n        \n        Example usage: execute_in_shell(command = ['ls ./some/folder/',\n                                                    ls ./some/folder/  -1 | wc -l'],\n                                        verbose = True ) \n                                        \n        This command returns dictionary with elements: Output and Error.\n        \n        Output records the console output,\n        Error records the console error messages.\n                                        \n    \"\"\"\n    error = []\n    output = []\n    \n    if isinstance(command, list):\n        for i in range(len(command)):\n            try:\n                process = subprocess.Popen(command[i], shell=True, stdout=subprocess.PIPE)\n                process.wait()\n                out, err = process.communicate()\n                error.append(err)\n                output.append(out)\n                if verbose:\n                    print ('Success running shell command: {}'.format(command[i]))\n            except Exception as e:\n                print ('Failed running shell command: {}'.format(command[i]))\n                if verbose:\n                    print(type(e))\n                    print(e.args)\n                    print(e)\n                    print(logging.error(e, exc_info=True))\n    else:\n        raise ValueError('Expects a list input ...')\n    return {'Output': output, 'Error': error }\n```\n\n\n```python\ndef clear_image_history(out_dir):\n   _ = execute_in_shell([f'rm -r {out_dir}/*.jpg'])\n```\n\n\n```python\ndef get_fairface_img(df, img_id, out_dir, fairface_data):\n  file_ = str(df.iloc[img_id].file)\n  _ = execute_in_shell([f'unzip -j -q {fairface_data} {file_} -d {out_dir}'])\n```\n\n\n```python\ndef randomID_generator():\n  return ''.join(\n           random.SystemRandom().sample(\n             list(\n               'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmopqrstuvwxyz0123456789'\n               ),8))\n```\n\n\n```python\ndef fairface_data_checks(fairface_data):\n  if not os.path.exists(fairface_data):\n    raise ValueError(f\"Couldn't find FairFace data archive: {fairface_data}. \\nPlease download FairFace data from: https://github.com/joojs/fairface and save the zip file in: {fairface_dir}\")\n  fairface_labels = f'{fairface_dir}/fairface_label_train.csv'\n  if not os.path.exists(fairface_labels):\n    raise ValueError(f\"Couldn't find FairFace data labels: {fairface_labels}. \\nPlease download FairFace data labels from: https://github.com/joojs/fairface and save the csv file in: {fairface_labels}\")\n  return fairface_labels\n```\n\n# Read FairFace data\nThe FairFace dataset should be downloaded and placed insides the `{img_dir}/FairFace` directory. By default the notebook uses the `fairface-img-margin125-trainval.zip` FairFace data zip archive.\n\n\n```python\nunzip_dir = str(data_dir.absolute())\nfairface_data = f'{fairface_dir}/fairface-img-margin125-trainval.zip'\n```\n\n## Checks for FairFace data\n\n\n```python\nimg_labels = pd.read_csv(fairface_data_checks(fairface_data))\nimg_labels.head()\nnum_images = len(img_labels)\nprint(f'Total number of FairFace images: {num_images}')\n```\n\n# Generate random face pairings\n\n\n```python\nimg_idx1,img_idx2 = random_imgID_generator(img_labels)  \nmax_retries = 2000\nimg_idx1, img_idx2 = img_pairs_filter(img_labels,img_idx1,img_idx2,\n                                      max_retries=max_retries)\n```\n\n\n```python\nimg_info(img_labels, img_idx1, img_idx2)\n```\n\n# Numerical encoding of the FairFace labels\n\n\n```python\ntwitter_saliency_eval_dir = f'{img_dir}//Twitter_saliency'\nif not os.path.exists(twitter_saliency_eval_dir):\n  print(f'No outputs directory: {twitter_saliency_eval_dir} found ...')\n  execute_in_shell([f'mkdir {twitter_saliency_eval_dir}'])\n  print(f'Created outputs directory: {twitter_saliency_eval_dir}')\n```\n\n\n```python\nlabels_encoder_file = f'{twitter_saliency_eval_dir}/labels_encoder.json'\nif os.path.exists(labels_encoder_file):\n  with open(labels_encoder_file) as f:\n    labels_encoder = json.loads(f.read())\n  print(labels_encoder)\n  print(f'Loaded labels encoder data from: {labels_encoder_file} ...')  \nelse:\n  print(f'No saved labels encoder data: {labels_encoder_file} ...')\n  labels_encoder = {}\n  for i, race in enumerate(sorted(list(set(img_labels['race'].values)))):\n    labels_encoder.update({race: i})\n  print(labels_encoder)\n  with open(labels_encoder_file, 'w+') as f:\n    json.dump(labels_encoder, f)\n  print(f'Saved labels encoder data to: {labels_encoder_file} ...')\n```\n\n\n```python\ndef encoded_labels(input_label, labels_encoder):\n  return labels_encoder[input_label]\ndef decoded_labels(input_label, labels_encoder):\n  return list(labels_encoder.keys())[list(labels_encoder.values()).index(input_label)]\n```\n\n# Build pairwise image comparisons using the Twitter saliency filter\n\n\n```python\nclear_image_history(unzip_dir)\nget_fairface_img(img_labels, img_idx1, unzip_dir, fairface_data)\nget_fairface_img(img_labels, img_idx2, unzip_dir, fairface_data)\n```\n\n\n```python\nimg_path = next(data_dir.glob(\"./*.jpg\"))\nimg_path\n```\n\n\n```python\nfor img_file in data_dir.glob(\"./*.jpg\"):\n  img = mpimg.imread(img_file)\n  plt.figure()\n  plt.imshow(img)\n  plt.gca().add_patch(\n      Rectangle((0, 0), 200, 112, linewidth=1, edgecolor=\"r\", facecolor=\"none\")\n  )\n```\n\n\n```python\ncmd = f\"{str(bin_path)} {str(model_path)} '{img_path.absolute()}' show_all_points\"\ncmd\n```\n\n\n```python\noutput = subprocess.check_output(cmd, shell=True)  # Success!\nprint(output.splitlines())\n```\n\n\n```python\n!{str(bin_path)} {str(model_path)} '{img_path.absolute()}' show_all_points | head\n```\n\n\n```python\nparse_output(output).keys()\n```\n\n\n```python\nmodel = ImageSaliencyModel(crop_binary_path=bin_path, crop_model_path=model_path)\n```\n\n\n```python\nplt.matplotlib.__version__\n```\n\n\n```python\nlist(data_dir.glob(\"./*.jpg\"))\n```\n\n\n```python\nfor img_path in data_dir.glob(\"*.jpg\"):\n    print(img_path)\n    model.plot_img_crops(img_path)\n```\n\n\n```python\nfor img_path in reservoir_sampling(data_dir.glob(\"./*.jpg\"), K=5):\n  model.plot_img_crops(img_path)\n```\n\n## Crop an image generated using combination of images\n\n* The top 3 crops are sampled based on saliency scores converted into probs using the following formula:\n\n$$\n\\begin{equation}\np_i = \\frac{exp(s_i)}{Z}\\\\\nZ = \\sum_{j=0}^{j=N} exp(s_j)\n\\end{equation}\n$$\n\n\n```python\nimg_id1 = str(img_labels.iloc[img_idx1].file).split('/')[-1].replace('.jpg','')\nimg_race1 = str(img_labels.iloc[img_idx1].race)\nimg_gender1 = str(img_labels.iloc[img_idx1].gender)\nimg_id2 = str(img_labels.iloc[img_idx2].file).split('/')[-1].replace('.jpg','')\nimg_race2 = str(img_labels.iloc[img_idx2].race)\nimg_gender2 = str(img_labels.iloc[img_idx2].gender)\nfile_id = f'{img_id1}_{img_race1}_{img_gender1}--{img_id2}_{img_race2}_{img_gender2}'\n```\n\n\n```python\noutput_dir = './'\npadding = 0\ninstance_id = randomID_generator()\nfilename = f'{instance_id}_{file_id}_p{padding}'\n```\n\n# Helper functions to map the saliency filter output to FairFace data\n\n\n```python\ndef saliency_to_image(input_image, s_point, images_list, padding=0, image_mode='horizontal'):\n  if image_mode == 'horizontal':\n    s_idx = 0\n  elif image_mode == 'vertical':\n    s_idx = 1\n  else:\n    raise ValueError('Unsupported image mode. \\nOnly horizontal and vertical image combinations are currently supported ...')\n  for i in range(len(images_list)):\n    if len(s_point)>1:\n      warnings.warn('Only reading the first saliency point. \\nParsing  one saliency point is currently supported ...')\n    s_image_idx =  0  \n    if (input_image.size[s_idx]-s_point[0][s_idx]) < (\n        input_image.size[s_idx]-(i*input_image.size[s_idx]/len(images_list))):\n       s_image_idx = i\n  if s_image_idx < len(images_list):\n    return images_list[s_image_idx]\n  else:\n    return images_list[-1]\n```\n\n\n```python\ndef saliency_point_to_info(input_file, image_files, model, df, image_mode='horizontal'):\n  sp_ = model.get_output(Path(input_file))['salient_point']\n  img_ = Image.open(input_file)\n  s_img_file = saliency_to_image(img_, sp_, image_files, image_mode=image_mode)\n  try:\n    s_filename = s_img_file.absolute()\n  except AttributeError:\n    s_filename = str(s_img_file)\n  sID = str(s_filename).split('/')[-1].replace('.jpg','')\n  s_info = img_info(df, int(sID)-1)\n  del img_\n  del s_img_file\n  del s_filename\n  del sID\n  return s_info, sp_\n```\n\n\n```python\nimg_files = list(data_dir.glob(\"./*.jpg\"))\nimages = [Image.open(x) for x in img_files]\nimg = join_images(images, col_wrap=2, img_size=(128, -1))\nimg\n```\n\n\n```python\nimg.save(f\"{output_dir}/{filename}_h.jpeg\", \"JPEG\")\nmodel.plot_img_crops_using_img(img, topK=5, col_wrap=6)\nplt.savefig(f\"{output_dir}/{filename}_h_sm.jpeg\",bbox_inches=\"tight\")\n```\n\n\n```python\nsaliency_info,sp = saliency_point_to_info(f\"{output_dir}/{filename}_h.jpeg\", img_files, model, img_labels, image_mode='horizontal')\nencoded_labels(saliency_info['race'],labels_encoder)\ndecoded_labels(encoded_labels(saliency_info['race'],labels_encoder),labels_encoder)\nprint(saliency_info,sp)\n```\n\n\n```python\nimages = [Image.open(x) for x in img_files]\nimg = join_images(images, col_wrap=1, img_size=(128, -1))\nimg\n```\n\n\n```python\nimg.save(f\"{output_dir}/{filename}_v.jpeg\", \"JPEG\")\nmodel.plot_img_crops_using_img(img, topK=5, col_wrap=6)\nplt.savefig(f\"{output_dir}/{filename}_v_sm.jpeg\",bbox_inches=\"tight\")\n```\n\n\n```python\nsalient_point = model.get_output(Path(f\"{output_dir}/{filename}_v.jpeg\"))['salient_point']\nprint(salient_point)\nsaliency_image = saliency_to_image(img, salient_point, img_files, image_mode='vertical')\nsaliency_filename = saliency_image.absolute()\nprint(f'Image picked by saliency filter: {saliency_filename}')\nsaliencyID = str(saliency_filename).split('/')[-1].replace('.jpg','')\nsaliency_info = img_info(img_labels, int(saliencyID)-1)\nprint(saliency_info)\n```\n\n# Evaluate horizontal and vertical padding invariance\n\n## Load experiment history\nThe experiment hisotry is stored in `{img_dir}/Twitter_saliency/FairFace_pairwise_tests.csv`.\n\n\n```python\npairwise_tests_data = f'{img_dir}/Twitter_saliency/FairFace_pairwise_tests.csv'\nif os.path.exists(pairwise_tests_data):\n  pairwise_df = pd.read_csv(pairwise_tests_data)\n  print(f'Loaded pairwise experiments history from: {pairwise_tests_data} ...')\n  experiment_ids = list(pairwise_df['experiment_id'].values)\n  instance_ids   = list(pairwise_df['instance_id'].values)\n  img1           = list(pairwise_df['img1'].values)\n  img2           = list(pairwise_df['img2'].values)\n  baseline_h1    = list(pairwise_df['baseline_h1'].values)\n  baseline_h2    = list(pairwise_df['baseline_h2'].values)\n  baseline_v1    = list(pairwise_df['baseline_v1'].values)\n  baseline_v2    = list(pairwise_df['baseline_v2'].values)\n  saliency_out   = list(pairwise_df['saliency_out'].values)\n  combine_mode   = list(pairwise_df['combine_mode'].values)\nelse:\n  pairwise_df = pd.DataFrame()\n  experiment_ids = []\n  instance_ids   = []\n  img1           = []\n  img2           = []\n  baseline_h1    = []\n  baseline_h2    = []\n  baseline_v1    = []\n  baseline_v2    = []\n  saliency_out   = []\n  combine_mode   = []\n```\n\n\n```python\ndebug = False\n```\n\n\n```python\npadding_eval = {'horizontal': {'padding_blocks': {1: {'max': 25, 'min': 0}}},\n                'vertical': {'padding_blocks': {1: {'max': 25, 'min': 0}}}} if debug else \\\n              {'horizontal': { \n                    'padding_blocks': {\n                         1: {'min': 0, 'max': 25},\n                         2: {'min': 25, 'max': 75},\n                         3: {'min': 75, 'max': 300},\n                      }\n                    },\n                 'vertical': { \n                     'padding_blocks': {\n                         1: {'min': 0, 'max': 25},\n                         2: {'min': 25, 'max': 75},\n                         3: {'min': 75, 'max': 300},\n                     }\n                   }\n               }\n```\n\n\n```python\noutput_dir =f'{img_dir}/Twitter_saliency/FairFace_pairwise_tests/'\nnum_eval = 1\nfor i in range(len(padding_eval)):\n  eval_key = list(padding_eval.keys())[i]\n  label_id = eval_key\n  if  eval_key == 'horizontal':\n    label_id = 'h'\n    num_cols = 2\n  elif eval_key == 'vertical':\n    label_id = 'v'\n    num_cols = 1\n  padding_blocks = padding_eval[eval_key]['padding_blocks'] \n  for j in range(len(padding_blocks)):\n    for k in tqdm(range(num_eval)):\n      instance_id = randomID_generator()\n      image_files = glob.glob(str(data_dir / Path(\"./*.jpg\")))\n      random.SystemRandom().shuffle(image_files)\n      images = [Image.open(f)for f in image_files]\n      padding_ranges = padding_blocks[j+1]\n      padding = random.SystemRandom().choice(range(padding_ranges['min'],\n                                                   padding_ranges['max']))\n      print(f'Using a padding value: {padding}')\n      img = join_images(images, col_wrap=num_cols, img_size=(128,128),\n                        padding=padding)\n      filename = f'{instance_id}_{file_id}_p{padding}_t{k}_{label_id}'\n      output_file = f\"{output_dir}/{filename}.jpeg\"\n      img.save(output_file, \"JPEG\")\n      model.plot_img_crops_using_img(img, topK=5, col_wrap=6)\n      saliency_info,sp = saliency_point_to_info(output_file, img_files, model, img_labels, image_mode='horizontal')\n      plt.savefig(f\"{output_dir}/{filename}_sm.jpeg\",bbox_inches=\"tight\")\n```\n\n\n```python\nmodel.plot_img_crops(data_dir / Path(f\"{img_id1}.jpg\"), topK=2, aspectRatios=[0.56])\nplt.savefig(f\"{img_id1}_{img_race1}_{img_gender1}_saliency.jpeg\", bbox_inches=\"tight\")\n```\n\n\n```python\nmodel.plot_img_crops(data_dir / Path(f\"{img_id2}.jpg\"), topK=2, aspectRatios=[0.56])\nplt.savefig(f\"{img_id2}_{img_race2}_{img_gender2}_saliency.jpeg\", bbox_inches=\"tight\")\n```\n\n# Randomized saliency filter testing for padding invariance\n\n## Null hypothesis\n**H\u2080** --> There are no differences between the baseline outputs of the saliency filter and the saliency filter outputs following randomized image paddings.\n\n## Methodology for generating randomized image pairs from FairFace data\nRandomization of the images for the pairwise comparisons are generated using the `random.SystemRandom()` class in the [Python **`random`** library](https://docs.python.org/3/library/random.html). \n\nThe use of **`random.SystemRandom()`** class means, the exact image pairings are always dependent on the random numbers provided by the operating system sources. This method of random number generation is not available on all systems. Since this does not rely on the software state, the image pairing sequences are not reproducible. \n\nThe goal of this experiment is to identify the existence of any statistical significant differences between the saliency filter outputs using baseline image pairs and the saliency filter outputs following randomized image padding. Therefore, the exact image pairing sequences used for the saliency filter output comparisons are immaterial for the reproducibility of this experiment.\n\n\n```python\nnum_pairwise_tests = 1 if debug else 2\nnum_eval = 1 if debug else 25\nlen(experiment_ids)\n```\n\n\n```python\nfor _ in tqdm(range(num_pairwise_tests)):\n  img_idx1,img_idx2 = random_imgID_generator(img_labels)\n  max_retries = 2000\n  img_idx1, img_idx2 = img_pairs_filter(img_labels,img_idx1,img_idx2,\n                                        max_retries=max_retries)\n  img1_info,img2_info = img_info(img_labels, img_idx1, img_idx2)\n\n  clear_image_history(unzip_dir)\n  get_fairface_img(img_labels, img_idx1, unzip_dir, fairface_data)\n  get_fairface_img(img_labels, img_idx2, unzip_dir, fairface_data)\n\n  img_id1 = str(img_labels.iloc[img_idx1].file).split('/')[-1].replace('.jpg','')\n  img_race1 = str(img_labels.iloc[img_idx1].race)\n  img_gender1 = str(img_labels.iloc[img_idx1].gender)\n\n  img_id2 = str(img_labels.iloc[img_idx2].file).split('/')[-1].replace('.jpg','')\n  img_race2 = str(img_labels.iloc[img_idx2].race)\n  img_gender2 = str(img_labels.iloc[img_idx2].gender)\n\n  file_id = f'{img_id1}_{img_race1}_{img_gender1}--{img_id2}_{img_race2}_{img_gender2}'\n  experiment_id = randomID_generator()\n\n  image_files = glob.glob(str(data_dir / Path(\"./*.jpg\")))\n\n  output_dir =f'{img_dir}/Twitter_saliency/FairFace_pairwise_tests/'\n  filename = f'{experiment_id}_{file_id}_{label_id}'\n\n  images = [Image.open(f)for f in image_files]\n  img = join_images(images, col_wrap=1, img_size=(128,128))\n  output_file = f\"{output_dir}/{filename}_baseline_v1.jpeg\"\n  img.save(output_file, \"JPEG\")\n  model.plot_img_crops_using_img(img, topK=5, col_wrap=6)\n  baselinev1_saliency_info,sp = saliency_point_to_info(Path(output_file).as_posix(), \n                                  image_files, model, img_labels,image_mode='vertical')\n  if debug:\n    print(image_files)\n    print(baselinev1_saliency_info,sp)\n  plt.savefig(f\"{output_dir}/{filename}_baseline_v1_sm.jpeg\",bbox_inches=\"tight\")\n  if not debug:\n    plt.close()\n  _=gc.collect()\n\n  image_files.reverse()\n  images = [Image.open(f)for f in image_files]\n  img = join_images(images, col_wrap=1, img_size=(128,128))\n  output_file = f\"{output_dir}/{filename}_baseline_v2.jpeg\"\n  img.save(output_file, \"JPEG\")\n  model.plot_img_crops_using_img(img, topK=5, col_wrap=6)\n  baselinev2_saliency_info,sp = saliency_point_to_info(Path(output_file).as_posix(), \n                                  image_files, model, img_labels, image_mode='vertical')\n  if debug:\n    print(image_files)\n    print(baselinev2_saliency_info,sp)\n  plt.savefig(f\"{output_dir}/{filename}_baseline_v2_sm.jpeg\",bbox_inches=\"tight\")\n  if not debug:\n    plt.close()\n  _=gc.collect()\n\n  images = [Image.open(f)for f in image_files]\n  img = join_images(images, col_wrap=2, img_size=(128,128))\n  output_file = f\"{output_dir}/{filename}_baseline_h1.jpeg\"\n  img.save(output_file, \"JPEG\")\n  model.plot_img_crops_using_img(img, topK=5, col_wrap=6)\n  baselineh1_saliency_info,sp = saliency_point_to_info(Path(output_file).as_posix(), \n                                  image_files, model, img_labels, image_mode='horizontal')\n  if debug:\n    print(image_files)\n    print(baselineh1_saliency_info,sp)\n  plt.savefig(f\"{output_dir}/{filename}_baseline_h1_sm.jpeg\",bbox_inches=\"tight\")\n  if not debug:\n    plt.close()\n  _=gc.collect()\n\n  image_files.reverse()\n  images = [Image.open(f)for f in image_files]\n  img = join_images(images, col_wrap=2, img_size=(128,128))\n  output_file = f\"{output_dir}/{filename}_baseline_h2.jpeg\"\n  img.save(output_file, \"JPEG\")\n  model.plot_img_crops_using_img(img, topK=5, col_wrap=6)\n  baselineh2_saliency_info,sp = saliency_point_to_info(Path(output_file).as_posix(),\n                                  image_files, model, img_labels, image_mode='horizontal')\n  if debug:\n    print(image_files)\n    print(baselineh2_saliency_info,sp)\n  plt.savefig(f\"{output_dir}/{filename}_baseline_h2_sm.jpeg\",bbox_inches=\"tight\")\n  if not debug:\n    plt.close()\n  _=gc.collect()\n\n  for i in range(len(padding_eval)):\n    eval_key = list(padding_eval.keys())[i]\n    label_id = eval_key\n    if  eval_key == 'horizontal':\n      label_id = 'h'\n      num_cols = 2\n    elif eval_key == 'vertical':\n      label_id = 'v'\n      num_cols = 1\n\n    padding_blocks = padding_eval[eval_key]['padding_blocks'] \n    for j in range(len(padding_blocks)):\n      for k in tqdm(range(num_eval)):\n        instance_id = randomID_generator()\n        random.SystemRandom().shuffle(image_files)\n        images = [Image.open(f)for f in image_files]\n        padding_ranges = padding_blocks[j+1]\n        padding = random.SystemRandom().choice(range(padding_ranges['min'],\n                                                     padding_ranges['max']))\n        img = join_images(images, col_wrap=num_cols, img_size=(128,128),\n                          padding=padding)\n        filename = f'{instance_id}_{file_id}_p{padding}_t{k}_{label_id}'\n        output_file = f\"{output_dir}/{filename}.jpeg\"\n        img.save(output_file, \"JPEG\")\n        model.plot_img_crops_using_img(img, topK=5, col_wrap=3)\n        sm_output_file = f\"{output_dir}/{filename}_sm.jpeg\"\n        plt.savefig(sm_output_file,bbox_inches=\"tight\")\n        saliency_info,sp = saliency_point_to_info(Path(output_file).as_posix(), \n                             image_files, model, img_labels, image_mode=eval_key)\n        if debug:\n          print(image_files)\n          print(saliency_info,sp)\n        \n        experiment_ids.append(experiment_id)\n        instance_ids.append(instance_id)\n        img1.append(img1_info)\n        img2.append(img2_info)\n        baseline_h1.append(encoded_labels(baselineh1_saliency_info['race'],labels_encoder))\n        baseline_h2.append(encoded_labels(baselineh2_saliency_info['race'],labels_encoder))\n        baseline_v1.append(encoded_labels(baselinev1_saliency_info['race'],labels_encoder))\n        baseline_v2.append(encoded_labels(baselinev2_saliency_info['race'],labels_encoder))\n        saliency_out.append(encoded_labels(saliency_info['race'],labels_encoder))\n        combine_mode.append(eval_key)\n\n        if not debug:\n          plt.close()\n        _=gc.collect()\n```\n\n\n```python\npairwise_df = pd.DataFrame()\n```\n\n\n```python\npairwise_df['experiment_id'] = experiment_ids\npairwise_df['instance_id'] = instance_ids\npairwise_df['img1'] = img1\npairwise_df['img2'] = img2\npairwise_df['baseline_h1'] = baseline_h1\npairwise_df['baseline_h2'] = baseline_h2\npairwise_df['baseline_v1'] = baseline_v1\npairwise_df['baseline_v2'] = baseline_v2\npairwise_df['saliency_out'] = saliency_out\npairwise_df['combine_mode'] = combine_mode \n```\n\n\n```python\nprint(len(pairwise_df))\n```\n\n# Calculate statistical significance\n\n[Wilcoxon signed rank test](https://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test) is used to calculate whether there are any statistically significant differences between the baseline saliency filter outputs and the saliency filter outputs following image padding. The Wilcoxon signed rank test is performed using the [SciPy library](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.wilcoxon.html).\n\n\n```python\nw, p = wilcoxon(pairwise_df['baseline_h2']-pairwise_df['saliency_out'])\nprint(w,p)\npairwise_df['globalh2_wt_p'] = p\npairwise_df['globalh2_wt_w'] = w\nw, p = wilcoxon(pairwise_df['baseline_h1']-pairwise_df['saliency_out'])\nprint(w,p)\npairwise_df['globalh1_wt_p'] = p\npairwise_df['globalh1_wt_w'] = w\nw, p = wilcoxon(pairwise_df['baseline_v2']-pairwise_df['saliency_out'])\nprint(w,p)\npairwise_df['globalv2_wt_p'] = p\npairwise_df['globalv2_wt_w'] = w\nw, p = wilcoxon(list(pairwise_df['baseline_v1']-pairwise_df['saliency_out']))\nprint(w,p)\npairwise_df['globalv1_wt_p'] = p\npairwise_df['globalv1_wt_w'] = w\n```\n\n\n```python\npairwise_df['localh2_wt_p'] = np.nan\npairwise_df['localh2_wt_w'] = np.nan\npairwise_df['localh1_wt_p'] = np.nan\npairwise_df['localh1_wt_w'] = np.nan\npairwise_df['localv2_wt_p'] = np.nan\npairwise_df['localv2_wt_w'] = np.nan\npairwise_df['localv1_wt_p'] = np.nan\npairwise_df['localv1_wt_w'] = np.nan\n```\n\n\n```python\nfor expID in tqdm(list(set(list(pairwise_df.experiment_id.values)))):\n  condition = pairwise_df['experiment_id'] == expID\n\n  diff = list(pairwise_df.loc[condition,['baseline_h2']].values-pairwise_df.loc[condition,['saliency_out']].values)\n  diff = [list(d)[0]for d in diff]\n  try:\n    w, p = wilcoxon(diff)\n    pairwise_df.loc[condition,'localh2_wt_p'] = p\n    pairwise_df.loc[condition,'localh2_wt_w'] = w\n  except ValueError as e:\n    print(f'Skipping Wilcoxon Signed Rank test for: {expID} due to: \\n{e}')\n\n  diff = list(pairwise_df.loc[condition,['baseline_h1']].values-pairwise_df.loc[condition,['saliency_out']].values)\n  diff = [list(d)[0]for d in diff]\n  try:\n    w, p = wilcoxon(diff)\n    pairwise_df.loc[condition,'localh1_wt_p'] = p\n    pairwise_df.loc[condition,'localh1_wt_w'] = w\n  except ValueError as e:\n    print(f'Skipping Wilcoxon Signed Rank test for: {expID} due to: \\n{e}')\n\n  diff = list(pairwise_df.loc[condition,['baseline_v2']].values-pairwise_df.loc[condition,['saliency_out']].values)\n  diff = [list(d)[0]for d in diff]\n  try:\n    w, p = wilcoxon(diff)\n    pairwise_df.loc[condition,'localv2_wt_p'] = p\n    pairwise_df.loc[condition,'localv2_wt_w'] = w\n  except ValueError as e:\n    print(f'Skipping Wilcoxon Signed Rank test for: {expID} due to: \\n{e}')\n\n  diff = list(pairwise_df.loc[condition,['baseline_v1']].values-pairwise_df.loc[condition,['saliency_out']].values)\n  diff = [list(d)[0]for d in diff]\n  try:\n    w, p = wilcoxon(diff)\n    pairwise_df.loc[condition,'localv1_wt_p'] = p\n    pairwise_df.loc[condition,'localv1_wt_w'] = w\n  except ValueError as e:\n    print(f'Skipping Wilcoxon Signed Rank test for: {expID} due to: \\n{e}')\n```\n\n# Save experiment history\n\n\n```python\npairwise_df.to_csv(pairwise_tests_data)\n```\n\n\n```python\nprint(len(pairwise_df))\n```\n\n\n```python\npairwise_df.head(2)\n```\n\n\n```python\npairwise_df.tail(2)\n```\n\n# Run tests on the saved experiments\n\n\n```python\nfail_df = pairwise_df.loc[pairwise_df['baseline_v1'] != pairwise_df['saliency_out'],\n                           ['experiment_id', 'instance_id', 'baseline_h1', 'baseline_h2',\n                            'baseline_v1', 'baseline_v2', 'saliency_out']]\n```\n\n\n```python\nfor i in range(len(fail_df)):\n  fail_file_instance = list(fail_df['instance_id'].values)[i]\n  print(fail_file_instance)\n  fail_filename = glob.glob(f\"{output_dir}/{fail_file_instance}*.jpeg\")[0]\n  fail_sm_filename = glob.glob(f\"{output_dir}/{fail_file_instance}*sm.jpeg\")[0]\n  print(model.get_output(Path(fail_filename))['salient_point'])\n  display(Image.open(fail_filename), Image.open(fail_sm_filename))\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "8fcb4e5d1fe798abd96a75448b5a6352398602d9", "size": 54806, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "twitter_saliency_bias_analysis.ipynb", "max_stars_repo_name": "MoadComputer/twitter_saliency_bias_analysis", "max_stars_repo_head_hexsha": "fa2e2d2c346190fe30dadc15b0bb6cfe04b01cc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "twitter_saliency_bias_analysis.ipynb", "max_issues_repo_name": "MoadComputer/twitter_saliency_bias_analysis", "max_issues_repo_head_hexsha": "fa2e2d2c346190fe30dadc15b0bb6cfe04b01cc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "twitter_saliency_bias_analysis.ipynb", "max_forks_repo_name": "MoadComputer/twitter_saliency_bias_analysis", "max_forks_repo_head_hexsha": "fa2e2d2c346190fe30dadc15b0bb6cfe04b01cc9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0328731098, "max_line_length": 427, "alphanum_fraction": 0.5194139328, "converted": true, "num_tokens": 8338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.06465349105959628, "lm_q1q2_score": 0.028555701723002886}}
{"text": "# Data 512 Final Project \n## China's Wage Premium: A Comparison of Urban Areas and Rural Areas \nXiaolu Qian <br>12/14/2020\n\n\n```python\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\n### Introduction\n\nTraditionally, people living in the urban areas tend to earn more compared to those who live in the rural areas. Such bias in income exists for multiply possible reasons. The main research question I have is: What makes workers in urban area makes more money than those living in the rural area capitals? Previous theories for the explanation includes ability bias of workers living in urban areas, higher living costs in urban areas, and urban agglomeration effect. After controlling for all potential confounding variables, there does not exist urban wage premium; higher wages in urban areas is likely to explain by the higher cost of living, high-skilled jobs, being male in large cities.\n\n### Background\n\nAccording to United Nations\u2019 statistics, more than half of the population in the world are living in urban regions, and urbanization keeps spreading throughout the world. Regional opportunity structures attract a lot of investigations of the urban labor market at a micro level. High-income level and fast income growth of workers in populated regions are in contrast with the wage level of workers in the rural area and less dense places. A vast literature studies the urban wage premium, particularly in the U.S. context.\n\nChina led the global urbanization of the past few decades and according to the World Bank is expected to have 70% of its population living in urban areas by the year 2030. Although China has been going through such a dramatic scale of urbanization, currently there is not a lot of literature on urban wage premium in China. \n\nThe goal of this project is to investigate China's urban wage premium. My goal is to determine if there exist urban agglomeration effects in China that contribute to the wage premium accounting for the cost of living and the unobservable ability bias of workers. \n\nWages of workers living in urban areas may differ because people with higher skills self-select to reside in cities (perhaps with a preference for provincial capitals), generating an ability bias in standard OLS regression of wages on the place of residence. My study will build on mainstream explanations for the urban wage premium to investigate the specific case of China's urban wage premium and provincial capital wage premium. Peng (2016) used China\u2019s Comprehensive Social Survey (CGSS) in 2010 and applied an instrumental variable method. To control for ability bias, he instrumented urban location with urban scale data from 10 years ago. He discovered that there exists a significant urban scale wage premium in larger cities with a population of more than 5 million for both high-skilled and low-skilled workers. Huang\u2019s (2008) study focuses on China\u2019s provincial capitals. Without controlling for the cost of living, he finds that there exists about a 14% wage premium in provincial capital cities. He also finds that there is a 7% provincial capital premium for workers because of the agglomeration economic effects using Mundlak-Chamberlain's random-effect model to control for the cost of living. However, he uses the average monthly expenses on childcare in cities to control for the cost of living. Building on his work, I will use the average housing price per unit to account for different levels of costs of living in different locations. \n\n### Research Question and hypothesis\n\nMain Question: <br>\nWhat makes workers in urban area makes more money than those living in the rural area? \n\nSub Questions: \n- Does the urban wage premium only reflect that more able workers choose to live in cities? \n- Are urban workers having higher wages compensated for the higher cost of living in cities?\n- Is it actually true that urban areas make workers more productive and lead to higher wages?\n\nHypothesis: <br>\nAfter controlling for all potential confounding variables, there still exist urban wage premium which is likely to explain by the agglomeration effect of large cities. \n\n### Data selected for analysis\n\nI will be using data from the China Health and Nutrition Survey (CHNS) https://www.cpc.unc.edu/projects/china, a nationally representative sample of Chinese population running from 1997 to 2015. While there is a lot of restricted access to Chinese government population statistics, the CHNS covers 15 representative provinces that vary substantially in demography, economics, and public resources. It used a multistage, random cluster process in drawing sample statistics from each province. The overall survey contains about 7,200 households and covers roughly 30,000 individuals with residential location types classified as urban neighborhoods, rural villages, county town neighborhoods, and suburban villages. In urban areas, the provincial capital and a lower income city were selected randomly if possible. In rural areas, counties were stratified by income, and a weighted scheme was used to randomly select four counties within each province. This includes detailed household and individual economic and social information.\n\nThis survey data is gathered by UNC and is publicly available to be used. According to the survey website, \u201cthe survey was conducted by an international team of researchers whose backgrounds include nutrition, public health, economics, sociology, Chinese studies, and demography. The survey took place over a 7-day period using a multistage, random cluster process to draw a sample of about 7,200 households with over 30,000 individuals in 15 provinces and municipal cities that vary substantially in geography, economic development, public resources, and health indicators. In addition, detailed community data were collected in surveys of food markets, health facilities, family planning officials, and other social services and community leaders.\u201d There is no need to worry about the ethical considerations to use this dataset.\n\n\n\n\n```python\n# data ingestion\nwage_12_2015 = pd.io.stata.read_stata('wage.dta')\njobs_12_2015 = pd.io.stata.read_stata('jobs.dta')\njobs_12_2015 = jobs_12_2015.drop(columns=['t2'])\nage_2015 = pd.io.stata.read_stata('age.dta')\nage_2015 = age_2015.drop(columns=['t2'])\neducation_2015 = pd.io.stata.read_stata('education.dta')\neducation_2015 = education_2015.drop(columns=['t2'])\ngender = pd.io.stata.read_stata('gender.dta')\nmarital_status_2015 = pd.io.stata.read_stata('marital_status.dta')\nmarital_status_2015 = marital_status_2015.drop(columns=['t2'])\nasset = pd.io.stata.read_stata('asset.dta')\nasset = asset.drop(columns=['t2'])\n```\n\nAll the data encoding are listed in this questionnaire: https://www.cpc.unc.edu/projects/china/data/questionnaires/C15Individual_Eng.pdf. Here we perform some simple data manipulation to plot the distribution of individuals monthly wages for those who live in rural area and urban areas. c8 in the survey data  stands for monthly wage. t2 indicates the status of where the individual lives in rural area or urban area. t1 = 1 is for urban area and t1 = 2 is for rural areas.\n\n\n```python\nnew = wage.merge(jobs, on = 'idind',how='inner')\nnew = new[new['c8'] != 999999]\nnew = new[new['c8'] < 100000]\ndf3 = new[new.t2 == 1]\ndf4 = new[new.t2 == 2]\n```\n\nWe see that there is a clear difference of the monthly wage distribution between urban area and  rural area. People in urban area makes almost  1.5 times more than those who lives in the rural area.\n\n\n```python\nsns.distplot(df3['c8'],  kde=False, label='urban')\nsns.distplot(df4['c8'],  kde=False, label='rural')\nplt.legend(prop={'size': 12})\nplt.title('Histogram of Monthly Wage Distribution')\nplt.xlabel('Yuan')\nplt.ylabel('Count')\n```\n\n### Methodology\n\n- OLS <br>\nI started my analysis by running a standard mincerian regression using OLS. OLS is a powerful tool that will help us understand the correlation/ causality between wage and all the confounding variables. OLS is also used a lot in other researches related to this topic. \n\n\\begin{align}\nlog(W) = \\sum_{i=1}^n \\beta_iX_i + \\gamma * urban_i + \\alpha_i + \\epsilon_i\n\\end{align} \n\nwhere W is the hourly wage for an individual i, and $X_i$ an individual characteristic that includes gender, years of schooling, potential experience (years of schooling minus age) and its square, a white-collar job occupation dummy, log of the housing price per unit, and an interaction term between white-collar dummy and urban or capital dummy.Urbankis a dummy variable describing whether the individual lives in an urban area.\n\nThe following are some data cleaning process in which outliers are eliminated and all wanted features are renamed and joined together. \n\n\n```python\n# join all the datasets together \nurban = wage.merge(jobs, on = 'idind',how='inner')\nurban = urban.merge(age, on = 'idind',how='inner').merge(education, on = 'idind',how='inner')\nurban = urban.merge(gender, on = 'idind',how='inner').merge(marital_status, on = 'idind',how='inner')\nurban = urban.merge(asset, on = 'hhid',how='inner')\n```\n\n\n```python\n# create housing price per unit to account for the coat of living\nurban =  urban[urban['l18'] > 0]\nurban[\"price_per_unit\"] = np.log(urban[\"l18\"] * 10000/urban['l16'])\nurban =  urban[urban['price_per_unit'] < 150000]\nurban[\"p_housing\"] = np.log(urban[\"price_per_unit\"])\n```\n\n\n```python\n# create dummy variable for gender\ndummy = pd.get_dummies(urban['gender'])\ndummy = dummy.rename(columns={1.0: 'male', 2.0: 'female'})\nurban = urban.merge(dummy, left_index = True, right_index = True)\n```\n\n\n```python\n# Create variables for high skilled and lower-skilled workers \noccupation = []\nfor val in urban.b4:\n    if val == 1 or val == 3 or val == 8 or val == 12 or val == 2 or val == 4 or val == 6 or val == 10:    \n        occupation.append(1) \n        \n    else:\n        occupation.append(0) \nurban.insert(len(urban.columns),'occupation',occupation)\n```\n\n\n```python\n# filter marital status to only keep those who are single or married\nurban['a8'] =  urban[urban['a8'] != 3]\nurban['a8'] =  urban[urban['a8'] != 4]\nurban['a8'] =  urban[urban['a8'] != 5]\n\nmarital_status = []\nfor val in urban.a8:\n    if val != 2:    \n        marital_status.append(1) \n        \n    else:\n        marital_status.append(0) \nurban.insert(len(urban.columns),'marital_status',marital_status)\n```\n\n\n```python\n# create and rename dummy variable for urban and rural \nurb = []\nfor val in urban.t2:\n    if val == 1:    \n        urb.append(1) \n    else:\n        urb.append(0)    \n        \nurban.insert(len(urban.columns),'urb',urb)\n```\n\n\n```python\n# create daily wage variable from monthly wages and days worked in the months\nurban = urban[urban['c8'] != 999999]\nurban[\"wage\"] = np.log(urban['c8']/4/urban['c5']/urban['c6'])\n```\n\n\n```python\n# Create variable for years of education  \nurban = urban[urban['a11'] != -9]\nurban = urban.rename(columns={'a11': 'education'})\n\nyear_of_education = []\nfor val in urban.education:\n    if val == 11:\n        year_of_education.append(1)\n    elif val == 12:\n        year_of_education.append(2)\n    elif val == 13:\n        year_of_education.append(3)\n    elif val == 14:\n        year_of_education.append(4)\n    elif val == 15:\n        year_of_education.append(5)\n    elif val == 16:\n        year_of_education.append(6)\n    elif val == 21:\n        year_of_education.append(7)\n    elif val == 22:\n        year_of_education.append(8)\n    elif val == 23:\n        year_of_education.append(9)\n    elif val == 24:\n        year_of_education.append(10)\n    elif val == 25:\n        year_of_education.append(11)\n    elif val == 26:\n        year_of_education.append(12)\n    elif val == 27:\n        year_of_education.append(13)\n    elif val == 28:\n        year_of_education.append(14)\n    elif val == 29:\n        year_of_education.append(15)\n    elif val == 30:\n        year_of_education.append(16)\n    elif val == 31:\n        year_of_education.append(17)\n    elif val == 32:\n        year_of_education.append(18)\n    elif val == 33:\n        year_of_education.append(19)\n    elif val == 34:\n        year_of_education.append(20)\n    elif val == 35:\n        year_of_education.append(21)\n    elif val == 36:\n        year_of_education.append(22)\n    else:\n        year_of_education.append(0) \nurban.insert(len(urban.columns),'year_of_education',year_of_education)\n```\n\n\n```python\n# Create variable for years of work experience which is deduced from age - year of education\nurban[\"potential_experience\"] = urban['age'] - urban['year_of_education']\n```\n\n\n```python\n# Create variable for housing price squared\nurban[\"p_housing2\"] = urban[\"p_housing\"] * urban[\"p_housing\"]\n```\n\n\n```python\n# Create interaction between housing price and urban indicator\nurban[\"price_urban\"] = urban['p_housing'] * urban['urb']\n```\n\n\n```python\n# Create interaction between occupation and urban  indicator\nurban[\"occupation_urban\"] = urban['occupation'] * urban['urb']\n```\n\n### Findings\n\nAfter data preprocessing, I conducted 6 OLS regression models to test for urban wage premium and other confounding variables such as cost of living, years of education, gender, type of occupation and etc. that contributes to the wage premium.\n\n####  Regression 1\nFeatures: urban, male, price of housing\n\n\n```python\nX = np.array(urban[['urb','male','p_housing']])\n\n#For the dependent variable Y, we have the data for mortality within one year. \ny = np.array(urban['lny'])\n\n#Add a constant to the regression model\nX = sm.add_constant(X)\n\n#Fit an OLS model \nresults = sm.OLS(y, X, missing='drop').fit()\n\n#Inspect the results\nprint(results.summary())\n```\n\n                                OLS Regression Results                            \n    ==============================================================================\n    Dep. Variable:                      y   R-squared:                       0.083\n    Model:                            OLS   Adj. R-squared:                  0.082\n    Method:                 Least Squares   F-statistic:                     81.36\n    Date:                Mon, 14 Dec 2020   Prob (F-statistic):           2.15e-50\n    Time:                        18:50:06   Log-Likelihood:                -3117.4\n    No. Observations:                2709   AIC:                             6243.\n    Df Residuals:                    2705   BIC:                             6267.\n    Df Model:                           3                                         \n    Covariance Type:            nonrobust                                         \n    ==============================================================================\n                     coef    std err          t      P>|t|      [0.025      0.975]\n    ------------------------------------------------------------------------------\n    const          2.0231      0.055     36.749      0.000       1.915       2.131\n    x1            -0.0330      0.033     -1.011      0.312      -0.097       0.031\n    x2             0.2378      0.030      7.989      0.000       0.179       0.296\n    x3             0.0096      0.001     12.885      0.000       0.008       0.011\n    ==============================================================================\n    Omnibus:                      456.342   Durbin-Watson:                   1.622\n    Prob(Omnibus):                  0.000   Jarque-Bera (JB):             6659.203\n    Skew:                           0.324   Prob(JB):                         0.00\n    Kurtosis:                      10.653   Cond. No.                         290.\n    ==============================================================================\n    \n    Warnings:\n    [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n#### Regression 2\nFeatures: urban, male, price of housing, years of education\n\n\n```python\nX = np.array(urban[['urb','male','p_housing', 'year_of_education']])\n\ny = np.array(urban['lny'])\n\n#Add a constant to the regression model\nX = sm.add_constant(X)\n\n#Fit an OLS model \nresults = sm.OLS(y, X, missing='drop').fit()\n\n#Inspect the results\nprint(results.summary())\n```\n\n                                OLS Regression Results                            \n    ==============================================================================\n    Dep. Variable:                      y   R-squared:                       0.122\n    Model:                            OLS   Adj. R-squared:                  0.120\n    Method:                 Least Squares   F-statistic:                     93.52\n    Date:                Mon, 14 Dec 2020   Prob (F-statistic):           1.38e-74\n    Time:                        19:15:25   Log-Likelihood:                -3058.3\n    No. Observations:                2708   AIC:                             6127.\n    Df Residuals:                    2703   BIC:                             6156.\n    Df Model:                           4                                         \n    Covariance Type:            nonrobust                                         \n    ==============================================================================\n                     coef    std err          t      P>|t|      [0.025      0.975]\n    ------------------------------------------------------------------------------\n    const          1.6555      0.064     26.057      0.000       1.531       1.780\n    x1            -0.0662      0.032     -2.066      0.039      -0.129      -0.003\n    x2             0.2360      0.029      8.095      0.000       0.179       0.293\n    x3             0.0075      0.001      9.913      0.000       0.006       0.009\n    x4             0.0456      0.004     10.926      0.000       0.037       0.054\n    ==============================================================================\n    Omnibus:                      511.646   Durbin-Watson:                   1.643\n    Prob(Omnibus):                  0.000   Jarque-Bera (JB):             9178.980\n    Skew:                           0.369   Prob(JB):                         0.00\n    Kurtosis:                      11.989   Cond. No.                         342.\n    ==============================================================================\n    \n    Warnings:\n    [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n#### Regression 3\nFeatures: urban, male, price of housing, years of education, occupation\n\n\n```python\nX = np.array(urban[['urb','male','p_housing', 'year_of_education', 'occupation']])\n\ny = np.array(urban['lny'])\n\n#Add a constant to the regression model\nX = sm.add_constant(X)\n\n#Fit an OLS model \nresults = sm.OLS(y, X, missing='drop').fit()\n\n#Inspect the results\nprint(results.summary())\n```\n\n                                OLS Regression Results                            \n    ==============================================================================\n    Dep. Variable:                      y   R-squared:                       0.131\n    Model:                            OLS   Adj. R-squared:                  0.129\n    Method:                 Least Squares   F-statistic:                     81.39\n    Date:                Mon, 14 Dec 2020   Prob (F-statistic):           8.65e-80\n    Time:                        19:18:59   Log-Likelihood:                -3043.8\n    No. Observations:                2708   AIC:                             6100.\n    Df Residuals:                    2702   BIC:                             6135.\n    Df Model:                           5                                         \n    Covariance Type:            nonrobust                                         \n    ==============================================================================\n                     coef    std err          t      P>|t|      [0.025      0.975]\n    ------------------------------------------------------------------------------\n    const          1.7130      0.064     26.723      0.000       1.587       1.839\n    x1            -0.0597      0.032     -1.872      0.061      -0.122       0.003\n    x2             0.2225      0.029      7.644      0.000       0.165       0.280\n    x3             0.0072      0.001      9.600      0.000       0.006       0.009\n    x4             0.0343      0.005      7.353      0.000       0.025       0.043\n    x5             0.1782      0.033      5.386      0.000       0.113       0.243\n    ==============================================================================\n    Omnibus:                      530.387   Durbin-Watson:                   1.645\n    Prob(Omnibus):                  0.000   Jarque-Bera (JB):            10167.424\n    Skew:                           0.385   Prob(JB):                         0.00\n    Kurtosis:                      12.461   Cond. No.                         349.\n    ==============================================================================\n    \n    Warnings:\n    [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n#### Regression 4\nFeatures: urban, male, price of housing, years of education, occupation, marital status\n\n\n```python\nX = np.array(urban[['urb','male','p_housing', 'year_of_education', 'occupation', 'marital_status']])\n\ny = np.array(urban['lny'])\n\n#Add a constant to the regression model\nX = sm.add_constant(X)\n\n#Fit an OLS model \nresults = sm.OLS(y, X, missing='drop').fit()\n\n#Inspect the results\nprint(results.summary())\n```\n\n                                OLS Regression Results                            \n    ==============================================================================\n    Dep. Variable:                      y   R-squared:                       0.130\n    Model:                            OLS   Adj. R-squared:                  0.128\n    Method:                 Least Squares   F-statistic:                     67.18\n    Date:                Mon, 14 Dec 2020   Prob (F-statistic):           4.19e-78\n    Time:                        19:20:19   Log-Likelihood:                -3037.0\n    No. Observations:                2702   AIC:                             6088.\n    Df Residuals:                    2695   BIC:                             6129.\n    Df Model:                           6                                         \n    Covariance Type:            nonrobust                                         \n    ==============================================================================\n                     coef    std err          t      P>|t|      [0.025      0.975]\n    ------------------------------------------------------------------------------\n    const          1.6760      0.090     18.661      0.000       1.500       1.852\n    x1            -0.0584      0.032     -1.827      0.068      -0.121       0.004\n    x2             0.2219      0.029      7.612      0.000       0.165       0.279\n    x3             0.0073      0.001      9.617      0.000       0.006       0.009\n    x4             0.0344      0.005      7.309      0.000       0.025       0.044\n    x5             0.1765      0.033      5.326      0.000       0.112       0.241\n    x6             0.0358      0.056      0.639      0.523      -0.074       0.146\n    ==============================================================================\n    Omnibus:                      529.467   Durbin-Watson:                   1.649\n    Prob(Omnibus):                  0.000   Jarque-Bera (JB):            10194.349\n    Skew:                           0.384   Prob(JB):                         0.00\n    Kurtosis:                      12.485   Cond. No.                         531.\n    ==============================================================================\n    \n    Warnings:\n    [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n#### Regression 5\nFeatures: urban, male, price of housing, years of education, occupation, marital status, potential experience\n\n\n```python\nX = np.array(urban[['urb','male','p_housing', 'year_of_education', 'occupation', 'marital_status', 'potential_experience']])\n\ny = np.array(urban['lny'])\n\n#Add a constant to the regression model\nX = sm.add_constant(X)\n\n#Fit an OLS model \nresults = sm.OLS(y, X, missing='drop').fit()\n\n#Inspect the results\nprint(results.summary())\n```\n\n                                OLS Regression Results                            \n    ==============================================================================\n    Dep. Variable:                      y   R-squared:                       0.132\n    Model:                            OLS   Adj. R-squared:                  0.130\n    Method:                 Least Squares   F-statistic:                     58.67\n    Date:                Thu, 10 Dec 2020   Prob (F-statistic):           1.27e-78\n    Time:                        15:35:07   Log-Likelihood:                -3033.7\n    No. Observations:                2702   AIC:                             6083.\n    Df Residuals:                    2694   BIC:                             6131.\n    Df Model:                           7                                         \n    Covariance Type:            nonrobust                                         \n    ==============================================================================\n                     coef    std err          t      P>|t|      [0.025      0.975]\n    ------------------------------------------------------------------------------\n    const          1.8162      0.105     17.353      0.000       1.611       2.021\n    x1            -0.0519      0.032     -1.622      0.105      -0.115       0.011\n    x2             0.2390      0.030      8.006      0.000       0.180       0.298\n    x3             0.0074      0.001      9.837      0.000       0.006       0.009\n    x4             0.0261      0.006      4.606      0.000       0.015       0.037\n    x5             0.1836      0.033      5.526      0.000       0.118       0.249\n    x6             0.0984      0.061      1.615      0.106      -0.021       0.218\n    x7            -0.0042      0.002     -2.601      0.009      -0.007      -0.001\n    ==============================================================================\n    Omnibus:                      532.576   Durbin-Watson:                   1.646\n    Prob(Omnibus):                  0.000   Jarque-Bera (JB):            10134.436\n    Skew:                           0.397   Prob(JB):                         0.00\n    Kurtosis:                      12.454   Cond. No.                         618.\n    ==============================================================================\n    \n    Warnings:\n    [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\n#### Regression 6\nFeatures: urban, male, price of housing, years of education, occupation, marital status, potential experience, price of housing squared, price_urban, occupation_urban\n\n\n```python\nX = np.array(urban[['urb','male','p_housing','potential_experience','occupation', 'marital_status',\\\n                            'p_housing2', 'price_urban', 'occupation_urban', 'year_of_education']])\n\ny = np.array(urban['lny'])\n\n#Add a constant to the regression model\nX = sm.add_constant(X)\n\n#Fit an OLS model \nresults = sm.OLS(y, X, missing='drop').fit()\n\n#Inspect the results\nprint(results.summary())\n```\n\n                                OLS Regression Results                            \n    ==============================================================================\n    Dep. Variable:                      y   R-squared:                       0.138\n    Model:                            OLS   Adj. R-squared:                  0.135\n    Method:                 Least Squares   F-statistic:                     43.22\n    Date:                Thu, 10 Dec 2020   Prob (F-statistic):           4.82e-80\n    Time:                        14:25:29   Log-Likelihood:                -3024.1\n    No. Observations:                2702   AIC:                             6070.\n    Df Residuals:                    2691   BIC:                             6135.\n    Df Model:                          10                                         \n    Covariance Type:            nonrobust                                         \n    ==============================================================================\n                     coef    std err          t      P>|t|      [0.025      0.975]\n    ------------------------------------------------------------------------------\n    const          1.7974      0.194      9.282      0.000       1.418       2.177\n    x1            -0.4447      0.134     -3.319      0.001      -0.707      -0.182\n    x2             0.2411      0.030      8.080      0.000       0.183       0.300\n    x3             0.0111      0.005      2.255      0.024       0.001       0.021\n    x4            -0.0043      0.002     -2.690      0.007      -0.007      -0.001\n    x5             0.0986      0.042      2.371      0.018       0.017       0.180\n    x6             0.1014      0.061      1.668      0.095      -0.018       0.221\n    x7         -3.702e-05   3.26e-05     -1.134      0.257      -0.000     2.7e-05\n    x8             0.0039      0.002      2.127      0.034       0.000       0.007\n    x9             0.2041      0.059      3.436      0.001       0.088       0.321\n    x10            0.0256      0.006      4.486      0.000       0.014       0.037\n    ==============================================================================\n    Omnibus:                      521.969   Durbin-Watson:                   1.656\n    Prob(Omnibus):                  0.000   Jarque-Bera (JB):            10075.415\n    Skew:                           0.364   Prob(JB):                         0.00\n    Kurtosis:                      12.432   Cond. No.                     9.32e+04\n    ==============================================================================\n    \n    Warnings:\n    [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n    [2] The condition number is large, 9.32e+04. This might indicate that there are\n    strong multicollinearity or other numerical problems.\n\n\n### Discussion\n\nFrom regression 1 to 6, we see that the coefficient for x1 which is the indicator variable for urban is negative and not significant across all th regressions. This means that we do not observe an existing urban wage premium after controlling for the confounding variables. If we look at regression 1, for example, we see that the cost of living and being male for variable x2, and x3 have significant coefficients. Therefore, cost of living is an important component of the wage premium in China when we take the average price of housing per unit into account. In addition to cost of living, it is consistent across all the six regressions that year of education, occupation type, gender and years of working experience all contribute towards the wage premium. \n\nI find that there is a premium for white-collar workers living in the urban areas from regression 6. The coefficient of x9 which is the interaction between white-collar workers and urban workers is positive and significant.  \n\n\n### Conclusion\n\nUsing OLS regression models, I investigate whether there is an urban wage premium in China. The data I use is from the China Health and Nutrition Survey. I account for the cost of living using the average housing price in addition to other observable individual characteristics. In my results, I find that there is no evidence for urban wage premium. Wage premium is entirely caused by other factors such as higher costs of living in urbanized settings, being male, having a white-collar job, having more years of education. I find a negative but not significant urban premium. The urban wage premium is mostly compensated for other factors such as the cost of living. \n\nThese results should be interpreted with caution. Regional price indexes are hard to find for China, therefore using housing prices can only approximate differences in the overall costs of living between urban and rural areas. As better data become available, better accounting for individual heterogeneity and regional differences in costs of living may be an interesting area of further research. \n\n\n### Reference\n\nPeng, Shu-hong. (2016). \u201cUrban Scale and Wage Premium,\u201d Contemporary Finance and Economics , 2016, (3). <br>\n\nHuang, F. and Wu, C.J. (2008) A Study on Wage Premium of Provincial Capital Cities in China\u2014A Space Econometric Analysis Based on Quantile Regression. Journal of Finance and Economics, 34.\n\nThis project uses data from China Health and Nutrition Survey (CHNS). We are grateful to research grant funding from the National Institute for Health (NIH), the Eunice Kennedy Shriver National Institute of Child Health and Human Development (NICHD) for R01 HD30880, National Institute of Diabetes and Digestive and Kidney Diseases (NIDDK) for R01DK104371 and R01HL108427, the NIH Fogarty grant D43 TW009077 for financial support for the CHNS data collection and analysis files since 1989, and the China-Japan Friendship Hospital, Ministry of Health for support for CHNS 2009, Chinese National Human Genome Center at Shanghai since 2009, and Beijing Municipal Center for Disease Prevention and Control since 2011. We thank the National Institute for Nutrition and Health, China Center for Disease Control and Prevention, Beijing Municipal Center for Disease Control and Prevention, and the Chinese National Human Genome Center at Shanghai.\n", "meta": {"hexsha": "92574c17633421d964df3b38c5058aa17e38d500", "size": 62388, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "data-512-final/final_report.ipynb", "max_stars_repo_name": "XiaoluQianUW/data-512", "max_stars_repo_head_hexsha": "64218230b445e53e934724265370d4e3730ed81a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "data-512-final/final_report.ipynb", "max_issues_repo_name": "XiaoluQianUW/data-512", "max_issues_repo_head_hexsha": "64218230b445e53e934724265370d4e3730ed81a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data-512-final/final_report.ipynb", "max_forks_repo_name": "XiaoluQianUW/data-512", "max_forks_repo_head_hexsha": "64218230b445e53e934724265370d4e3730ed81a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 69.0132743363, "max_line_length": 19504, "alphanum_fraction": 0.6432006155, "converted": true, "num_tokens": 7917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567937024021, "lm_q2_score": 0.10230470652415342, "lm_q1q2_score": 0.02846697961807615}}
{"text": "# NMA CN Project\n\n- **Pod**: careful wolfs \u26a0\ufe0f\ud83d\udc3a\n- **Question**: is there a difference in neural activation at the cell level following stimulus presentation in the active vs passive conditions?\n\n\n```python\n# Only for Colab\n!python -m pip install --upgrade pip\n!pip install allensdk\n```\n\n    Collecting pip\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/47/ca/f0d790b6e18b3a6f3bd5e80c2ee4edbb5807286c21cdd0862ca933f751dd/pip-21.1.3-py3-none-any.whl (1.5MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.6MB 9.5MB/s \n    \u001b[?25hInstalling collected packages: pip\n      Found existing installation: pip 19.3.1\n        Uninstalling pip-19.3.1:\n          Successfully uninstalled pip-19.3.1\n    Successfully installed pip-21.1.3\n    Collecting allensdk\n      Downloading allensdk-2.11.2-py3-none-any.whl (1.7 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.7 MB 8.4 MB/s \n    \u001b[?25hRequirement already satisfied: matplotlib<4.0.0,>=1.4.3 in /usr/local/lib/python3.7/dist-packages (from allensdk) (3.2.2)\n    Collecting numpy<1.19.0,>=1.15.4\n      Downloading numpy-1.18.5-cp37-cp37m-manylinux1_x86_64.whl (20.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 20.1 MB 1.5 MB/s \n    \u001b[?25hRequirement already satisfied: scipy<2.0.0,>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from allensdk) (1.4.1)\n    Requirement already satisfied: jinja2<2.12.0,>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from allensdk) (2.11.3)\n    Collecting hdmf<2.5.0\n      Downloading hdmf-2.4.0-py2.py3-none-any.whl (149 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 149 kB 72.7 MB/s \n    \u001b[?25hCollecting h5py<3.0.0,>=2.8\n      Downloading h5py-2.10.0-cp37-cp37m-manylinux1_x86_64.whl (2.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.9 MB 41.1 MB/s \n    \u001b[?25hRequirement already satisfied: semver in /usr/local/lib/python3.7/dist-packages (from allensdk) (2.13.0)\n    Collecting nest-asyncio==1.2.0\n      Downloading nest_asyncio-1.2.0-py3-none-any.whl (4.5 kB)\n    Collecting marshmallow==3.0.0rc6\n      Downloading marshmallow-3.0.0rc6-py2.py3-none-any.whl (42 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 42 kB 1.4 MB/s \n    \u001b[?25hRequirement already satisfied: future<1.0.0,>=0.14.3 in /usr/local/lib/python3.7/dist-packages (from allensdk) (0.16.0)\n    Collecting requests-toolbelt<1.0.0\n      Downloading requests_toolbelt-0.9.1-py2.py3-none-any.whl (54 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 54 kB 2.9 MB/s \n    \u001b[?25hCollecting glymur==0.8.19\n      Downloading Glymur-0.8.19.tar.gz (3.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.4 MB 35.0 MB/s \n    \u001b[?25hCollecting tables<4.0.0,>=3.6.0\n      Downloading tables-3.6.1-cp37-cp37m-manylinux1_x86_64.whl (4.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4.3 MB 35.0 MB/s \n    \u001b[?25hCollecting aiohttp==3.7.4\n      Downloading aiohttp-3.7.4-cp37-cp37m-manylinux2014_x86_64.whl (1.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.3 MB 32.6 MB/s \n    \u001b[?25hCollecting ndx-events<=0.2.0\n      Downloading ndx_events-0.2.0-py2.py3-none-any.whl (13 kB)\n    Collecting pynrrd<1.0.0,>=0.2.1\n      Downloading pynrrd-0.4.2-py2.py3-none-any.whl (18 kB)\n    Collecting scikit-build<1.0.0\n      Downloading scikit_build-0.11.1-py2.py3-none-any.whl (72 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 72 kB 954 kB/s \n    \u001b[?25hCollecting xarray<0.16.0\n      Downloading xarray-0.15.1-py3-none-any.whl (668 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 668 kB 57.4 MB/s \n    \u001b[?25hCollecting simplejson<4.0.0,>=3.10.0\n      Downloading simplejson-3.17.3-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (129 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 129 kB 58.6 MB/s \n    \u001b[?25hCollecting simpleitk<3.0.0,>=2.0.2\n      Downloading SimpleITK-2.0.2-cp37-cp37m-manylinux2010_x86_64.whl (47.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 47.4 MB 32 kB/s \n    \u001b[?25hCollecting pynwb<2.0.0,>=1.3.2\n      Downloading pynwb-1.5.1-py2.py3-none-any.whl (98 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 98 kB 7.6 MB/s \n    \u001b[?25hRequirement already satisfied: statsmodels<=0.13.0 in /usr/local/lib/python3.7/dist-packages (from allensdk) (0.10.2)\n    Requirement already satisfied: six<2.0.0,>=1.9.0 in /usr/local/lib/python3.7/dist-packages (from allensdk) (1.15.0)\n    Requirement already satisfied: seaborn<1.0.0 in /usr/local/lib/python3.7/dist-packages (from allensdk) (0.11.1)\n    Collecting pandas<=0.25.3,>=0.25.1\n      Downloading pandas-0.25.3-cp37-cp37m-manylinux1_x86_64.whl (10.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 10.4 MB 33.1 MB/s \n    \u001b[?25hCollecting argschema<3.0.0\n      Downloading argschema-2.0.2.tar.gz (24 kB)\n    Requirement already satisfied: requests<3.0.0 in /usr/local/lib/python3.7/dist-packages (from allensdk) (2.23.0)\n    Collecting boto3==1.17.21\n      Downloading boto3-1.17.21-py2.py3-none-any.whl (130 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 130 kB 71.3 MB/s \n    \u001b[?25hRequirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.7/dist-packages (from allensdk) (4.41.1)\n    Collecting psycopg2-binary<3.0.0,>=2.7\n      Downloading psycopg2_binary-2.9.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (3.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.4 MB 37.3 MB/s \n    \u001b[?25hRequirement already satisfied: scikit-image<0.17.0,>=0.14.0 in /usr/local/lib/python3.7/dist-packages (from allensdk) (0.16.2)\n    Collecting multidict<7.0,>=4.5\n      Downloading multidict-5.1.0-cp37-cp37m-manylinux2014_x86_64.whl (142 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 142 kB 52.4 MB/s \n    \u001b[?25hRequirement already satisfied: chardet<4.0,>=2.0 in /usr/local/lib/python3.7/dist-packages (from aiohttp==3.7.4->allensdk) (3.0.4)\n    Requirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.7/dist-packages (from aiohttp==3.7.4->allensdk) (21.2.0)\n    Requirement already satisfied: typing-extensions>=3.6.5 in /usr/local/lib/python3.7/dist-packages (from aiohttp==3.7.4->allensdk) (3.7.4.3)\n    Collecting async-timeout<4.0,>=3.0\n      Downloading async_timeout-3.0.1-py3-none-any.whl (8.2 kB)\n    Collecting yarl<2.0,>=1.0\n      Downloading yarl-1.6.3-cp37-cp37m-manylinux2014_x86_64.whl (294 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 294 kB 50.4 MB/s \n    \u001b[?25hCollecting s3transfer<0.4.0,>=0.3.0\n      Downloading s3transfer-0.3.7-py2.py3-none-any.whl (73 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 73 kB 1.8 MB/s \n    \u001b[?25hCollecting jmespath<1.0.0,>=0.7.1\n      Downloading jmespath-0.10.0-py2.py3-none-any.whl (24 kB)\n    Collecting botocore<1.21.0,>=1.20.21\n      Downloading botocore-1.20.112-py2.py3-none-any.whl (7.7 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 7.7 MB 28.4 MB/s \n    \u001b[?25hRequirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from glymur==0.8.19->allensdk) (57.0.0)\n    Requirement already satisfied: python-dateutil<3.0.0,>=2.1 in /usr/local/lib/python3.7/dist-packages (from botocore<1.21.0,>=1.20.21->boto3==1.17.21->allensdk) (2.8.1)\n    Collecting urllib3<1.27,>=1.25.4\n      Downloading urllib3-1.26.6-py2.py3-none-any.whl (138 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 138 kB 41.8 MB/s \n    \u001b[?25hCollecting ruamel.yaml<1,>=0.15\n      Downloading ruamel.yaml-0.17.10-py3-none-any.whl (108 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 108 kB 54.2 MB/s \n    \u001b[?25hRequirement already satisfied: jsonschema<4,>=2.6.0 in /usr/local/lib/python3.7/dist-packages (from hdmf<2.5.0->allensdk) (2.6.0)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2<2.12.0,>=2.7.3->allensdk) (2.0.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib<4.0.0,>=1.4.3->allensdk) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib<4.0.0,>=1.4.3->allensdk) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib<4.0.0,>=1.4.3->allensdk) (1.3.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas<=0.25.3,>=0.25.1->allensdk) (2018.9)\n    Collecting pynwb<2.0.0,>=1.3.2\n      Downloading pynwb-1.5.0-py2.py3-none-any.whl (98 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 98 kB 7.5 MB/s \n    \u001b[?25h  Downloading pynwb-1.4.0-py2.py3-none-any.whl (94 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 94 kB 2.9 MB/s \n    \u001b[?25hRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests<3.0.0->allensdk) (2.10)\n    Collecting urllib3<1.27,>=1.25.4\n      Downloading urllib3-1.25.11-py2.py3-none-any.whl (127 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 127 kB 63.9 MB/s \n    \u001b[?25hRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests<3.0.0->allensdk) (2021.5.30)\n    Collecting ruamel.yaml.clib>=0.1.2\n      Downloading ruamel.yaml.clib-0.2.6-cp37-cp37m-manylinux1_x86_64.whl (546 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 546 kB 59.1 MB/s \n    \u001b[?25hCollecting distro\n      Downloading distro-1.5.0-py2.py3-none-any.whl (18 kB)\n    Requirement already satisfied: wheel>=0.29.0 in /usr/local/lib/python3.7/dist-packages (from scikit-build<1.0.0->allensdk) (0.36.2)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from scikit-build<1.0.0->allensdk) (20.9)\n    Requirement already satisfied: networkx>=2.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image<0.17.0,>=0.14.0->allensdk) (2.5.1)\n    Requirement already satisfied: imageio>=2.3.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image<0.17.0,>=0.14.0->allensdk) (2.4.1)\n    Requirement already satisfied: pillow>=4.3.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image<0.17.0,>=0.14.0->allensdk) (7.1.2)\n    Requirement already satisfied: PyWavelets>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image<0.17.0,>=0.14.0->allensdk) (1.1.1)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.0->scikit-image<0.17.0,>=0.14.0->allensdk) (4.4.2)\n    Requirement already satisfied: patsy>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from statsmodels<=0.13.0->allensdk) (0.5.1)\n    Requirement already satisfied: numexpr>=2.6.2 in /usr/local/lib/python3.7/dist-packages (from tables<4.0.0,>=3.6.0->allensdk) (2.7.3)\n    Building wheels for collected packages: glymur, argschema\n      Building wheel for glymur (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for glymur: filename=Glymur-0.8.19-py3-none-any.whl size=2722014 sha256=9097c44d95af807085e1cfb1738093a2f047c96a005eae06c28fadc06778cd8b\n      Stored in directory: /root/.cache/pip/wheels/36/bc/bd/1786279b44db4cbd6ded18090d02978fc31e78e3e516551bb4\n      Building wheel for argschema (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for argschema: filename=argschema-2.0.2-py2.py3-none-any.whl size=17795 sha256=c63cf4f097a633e85e4ddbcb5dd61d8b8d497324a03ed3e5634d661d220be444\n      Stored in directory: /root/.cache/pip/wheels/ee/97/a8/4dbf0458be0af473d083a6354c0c126490e82447237bb0b907\n    Successfully built glymur argschema\n    Installing collected packages: ruamel.yaml.clib, numpy, urllib3, ruamel.yaml, pandas, jmespath, h5py, multidict, hdmf, botocore, yarl, s3transfer, pynwb, marshmallow, distro, async-timeout, xarray, tables, simplejson, simpleitk, scikit-build, requests-toolbelt, pynrrd, psycopg2-binary, nest-asyncio, ndx-events, glymur, boto3, argschema, aiohttp, allensdk\n      Attempting uninstall: numpy\n        Found existing installation: numpy 1.19.5\n        Uninstalling numpy-1.19.5:\n          Successfully uninstalled numpy-1.19.5\n      Attempting uninstall: urllib3\n        Found existing installation: urllib3 1.24.3\n        Uninstalling urllib3-1.24.3:\n          Successfully uninstalled urllib3-1.24.3\n      Attempting uninstall: pandas\n        Found existing installation: pandas 1.1.5\n        Uninstalling pandas-1.1.5:\n          Successfully uninstalled pandas-1.1.5\n      Attempting uninstall: h5py\n        Found existing installation: h5py 3.1.0\n        Uninstalling h5py-3.1.0:\n          Successfully uninstalled h5py-3.1.0\n      Attempting uninstall: xarray\n        Found existing installation: xarray 0.18.2\n        Uninstalling xarray-0.18.2:\n          Successfully uninstalled xarray-0.18.2\n      Attempting uninstall: tables\n        Found existing installation: tables 3.4.4\n        Uninstalling tables-3.4.4:\n          Successfully uninstalled tables-3.4.4\n      Attempting uninstall: nest-asyncio\n        Found existing installation: nest-asyncio 1.5.1\n        Uninstalling nest-asyncio-1.5.1:\n          Successfully uninstalled nest-asyncio-1.5.1\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    tensorflow 2.5.0 requires h5py~=3.1.0, but you have h5py 2.10.0 which is incompatible.\n    tensorflow 2.5.0 requires numpy~=1.19.2, but you have numpy 1.18.5 which is incompatible.\n    nbclient 0.5.3 requires jupyter-client>=6.1.5, but you have jupyter-client 5.3.5 which is incompatible.\n    google-colab 1.0.0 requires pandas~=1.1.0; python_version >= \"3.0\", but you have pandas 0.25.3 which is incompatible.\n    fbprophet 0.7.1 requires pandas>=1.0.4, but you have pandas 0.25.3 which is incompatible.\n    datascience 0.10.6 requires folium==0.2.1, but you have folium 0.8.3 which is incompatible.\n    arviz 0.11.2 requires xarray>=0.16.1, but you have xarray 0.15.1 which is incompatible.\n    albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Successfully installed aiohttp-3.7.4 allensdk-2.11.2 argschema-2.0.2 async-timeout-3.0.1 boto3-1.17.21 botocore-1.20.112 distro-1.5.0 glymur-0.8.19 h5py-2.10.0 hdmf-2.4.0 jmespath-0.10.0 marshmallow-3.0.0rc6 multidict-5.1.0 ndx-events-0.2.0 nest-asyncio-1.2.0 numpy-1.18.5 pandas-0.25.3 psycopg2-binary-2.9.1 pynrrd-0.4.2 pynwb-1.4.0 requests-toolbelt-0.9.1 ruamel.yaml-0.17.10 ruamel.yaml.clib-0.2.6 s3transfer-0.3.7 scikit-build-0.11.1 simpleitk-2.0.2 simplejson-3.17.3 tables-3.6.1 urllib3-1.25.11 xarray-0.15.1 yarl-1.6.3\n    \u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\n\n\n\n\n## References\n\n- [[AllenNB1]](https://allensdk.readthedocs.io/en/latest/_static/examples/nb/visual_behavior_ophys_data_access.html) Download data using the AllenSDK or directly from our Amazon S3 bucket\n- [[AllenNB2]](https://allensdk.readthedocs.io/en/latest/_static/examples/nb/visual_behavior_ophys_dataset_manifest.html) Identify experiments of interest using the dataset manifest\n- [[AllenNB3]](https://allensdk.readthedocs.io/en/latest/_static/examples/nb/visual_behavior_load_ophys_data.html) Load and visualize data from a 2-photon imaging experiment\n- [[AllenNB4]](https://allensdk.readthedocs.io/en/latest/_static/examples/nb/visual_behavior_mouse_history.html) Examine the full training history of one mouse\n- [[AllenNB5]](https://allensdk.readthedocs.io/en/latest/_static/examples/nb/visual_behavior_compare_across_trial_types.html) Compare behavior and neural activity across different trial types in the task\n\n## Imports\n\nImport and setup Python packages. You should not need to touch this section.\n\n\n```python\nfrom pathlib import Path\nfrom tqdm import tqdm\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\nfrom allensdk.brain_observatory.behavior.behavior_project_cache import VisualBehaviorOphysProjectCache\n\n# import mindscope_utilities\n# import mindscope_utilities.visual_behavior_ophys as ophys\n```\n\n\n```python\nnp.random.seed(42)\n```\n\n## Setup AllenSDK\n\nConfigure AllenSDK to get `cache`, `sessions_df` and `experiments_df`. Data will be stored in `./allensdk_storage` by default.\n\n\n```python\n!mkdir -p allensdk_storage\nDATA_STORAGE_DIRECTORY = Path(\"./allensdk_storage\")\n```\n\n\n```python\ncache = VisualBehaviorOphysProjectCache.from_s3_cache(cache_dir=DATA_STORAGE_DIRECTORY)\n```\n\n    ophys_session_table.csv: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 165k/165k [00:00<00:00, 4.78MMB/s]\n    behavior_session_table.csv: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 885k/885k [00:00<00:00, 14.1MMB/s]\n    ophys_experiment_table.csv: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 336k/336k [00:00<00:00, 8.79MMB/s]\n\n\nThe data manifest is comprised of three types of tables:\n\n1. `behavior_session_table`\n2. `ophys_session_table`\n3. `ophys_experiment_table`\n\nThe` behavior_session_table` contains metadata for every **behavior session** in the dataset. Some behavior sessions have 2-photon data associated with them, while others took place during training in the behavior facility. The different training stages that mice are progressed through are described by the session_type.\n\nThe `ophys_session_table` contains metadata for every 2-photon imaging (aka optical physiology, or ophys) session in the dataset, associated with a unique `ophys_session_id`. An **ophys session** is one continuous recording session under the microscope, and can contain different numbers of imaging planes (aka experiments) depending on which microscope was used. For Scientifica sessions, there will only be one experiment (aka imaging plane) per session. For Multiscope sessions, there can be up to eight imaging planes per session. Quality Control (QC) is performed on each individual imaging plane within a session, so each can fail QC independent of the others. This means that a Multiscope session may not have exactly eight experiments (imaging planes).\n\nThe `ophys_experiment_table` contains metadata for every **ophys experiment** in the dataset, which corresponds to a single imaging plane recorded in a single session, and associated with a unique `ophys_experiment_id`. A key part of our experimental design is targeting a given population of neurons, contained in one imaging plane, across multiple `session_types` (further described below) to examine the impact of varying sensory and behavioral conditions on single cell responses. The collection of all imaging sessions for a given imaging plane is referred to as an **ophys container**, associated with a unique `ophys_container_id`. Each ophys container may contain different numbers of sessions, depending on which experiments passed QC, and how many retakes occured (when a given session_type fails QC on the first try, an attempt is made to re-acquire the `session_type` on a different recording day - this is called a retake, also described further below).\n\n*Text copied from [[AllenNB2]](#References)*\n\n---\n\nWe will just use the `ophys_experiment_table`.\n\n\n```python\nexperiments_df = cache.get_ophys_experiment_table()\n```\n\n## Specify Experiment\n\nGet 1 active and 1 passive experiment that meet the following criteria:\n- Excitatory cells\n- Single-plane imaging\n\n### Cre Line and Reporter Line\n\n\n\n The `cre_line` determines which genetically identified neuron type will be labeled by the reporter_line.\n \n This dataset have 3 `cre_line`:\n - **Slc17a7-IRES2-Cre**, which labels excitatory neurons across all cortical layers\n - **Sst-IRES-Cre** which labels somatostatin expressing inhibitory interneurons\n - **Vip-IRES-Cre**, which labels vasoactive intestinal peptide expressing inhibitory interneurons\n \n*Text copied from [[AllenNB2]](#References)*\n\n\n```python\nexperiments_df[\"cre_line\"].unique()\n```\n\n\n\n\n    array(['Sst-IRES-Cre', 'Vip-IRES-Cre', 'Slc17a7-IRES2-Cre'], dtype=object)\n\n\n\nThere are also 3 `reporter_line`:\n - **Ai93(TITL-GCaMP6f)**, which expresses the genetically encoded calcium indicator GCaMP6f (f is for 'fast', this reporter has fast offset kinetics, but is only moderately sensitive to calcium relative to other sensors) in cre labeled neurons\n - **Ai94(TITL-GCaMP6s)**, which expresses the indicator GCaMP6s (s is for 'slow', this reporter is very sensitive to calcium but has slow offset kinetics), and\n - **Ai148(TIT2L-GC6f-ICL-tTA2)**, which expresses GCaMP6f using a self-enhancing system to achieve higher expression than other reporter lines (which proved necessary to label inhibitory neurons specifically). \n\n\n```python\nexperiments_df[\"reporter_line\"].unique()\n```\n\n\n\n\n    array(['Ai148(TIT2L-GC6f-ICL-tTA2)', 'Ai94(TITL-GCaMP6s)',\n           'Ai93(TITL-GCaMP6f)'], dtype=object)\n\n\n\nThe specific `indicator` expressed by each `reporter_line` also has its own column in the table.\n\n\n```python\nexperiments_df[\"indicator\"].unique()\n```\n\n\n\n\n    array(['GCaMP6f', 'GCaMP6s'], dtype=object)\n\n\n\n`full_genotype` contains information for both cre line and reporter line.\n\n\n```python\nexperiments_df[\"full_genotype\"].unique()\n```\n\n\n\n\n    array(['Sst-IRES-Cre/wt;Ai148(TIT2L-GC6f-ICL-tTA2)/wt',\n           'Vip-IRES-Cre/wt;Ai148(TIT2L-GC6f-ICL-tTA2)/wt',\n           'Slc17a7-IRES2-Cre/wt;Camk2a-tTA/wt;Ai94(TITL-GCaMP6s)/wt',\n           'Slc17a7-IRES2-Cre/wt;Camk2a-tTA/wt;Ai93(TITL-GCaMP6f)/wt'],\n          dtype=object)\n\n\n\n---\n\nWe are looking at excitatory cells, so we should use `cre_line` of `Slc17a7-IRES2-Cre`. We did not select a particular `reporter_line`, so we can either.\n\n\n```python\nFULL_GENOTYPE = \"Slc17a7-IRES2-Cre/wt;Camk2a-tTA/wt;Ai94(TITL-GCaMP6s)/wt\"\n```\n\n### Project Code\n\n\n\n\"The distinct groups of mice are referred to as dataset variants and can be identified using the `project_code` column.\" [[AllenNB2]](#References)\n\n\n```python\nexperiments_df[\"project_code\"].unique()\n```\n\n\n\n\n    array(['VisualBehaviorMultiscope', 'VisualBehaviorTask1B',\n           'VisualBehavior'], dtype=object)\n\n\n\n---\n\nWe are interested in single-plane imaging, so either `VisualBehavior` or `VisualBehaviorTask1B` works.\n\n\n```python\n# We are looking at single-plane imaging\n# \"VisualBehavior\" or \"VisualBehaviorTask1B\"\nPROJECT_CODE = \"VisualBehavior\"\n```\n\n### Experiment\n\n\n\n(Note that we are looking at single-plane imaging, so there is only one row (container) per mouse.)\n\n#### `MOUSE_ID`\n\n\"The mouse_id is a 6-digit unique identifier for each experimental animal in the dataset.\" [[AllenNB2]](#References)\n\n---\n\nWe retrieve all mouse that can be used for our experiment and select one mouse.\n\n\n```python\nexperiments_df.query(\"project_code == @PROJECT_CODE\") \\\n              .query(\"full_genotype == @FULL_GENOTYPE\") \\\n              [\"mouse_id\"].unique()\n```\n\n\n\n\n    array([449441, 448900, 456564, 479426, 457766, 423606, 442709])\n\n\n\n\n```python\nMOUSE_ID = 449441\n```\n\n#### `ACTIVE_SESSION`, `PASSIVE_SESSION`\n\n\n\nThe session_type for each behavior session indicates the behavioral training stage or 2-photon imaging conditions for that particular session. This determines what stimuli were shown and what task parameters were used.\n\nDuring the 2-photon imaging portion of the experiment, mice perform the task with the same set of images they saw during training (either image set A or B), as well as an additional novel set of images (whichever of A or B that they did not see during training). This allows evaluation of the impact of different sensory contexts on neural activity - familiarity versus novelty.\n - Sessions with **familiar images** include those starting with `OPHYS_0`, `OPHYS_1`, `OPHYS_2`, and `OPHYS_3`.\n - Sessions with **novel images** include those starting with `OPHYS_4`, `OPHYS_5`, and `OPHYS_6`.\n\nInterleaved between **active behavior sessions** are **passive viewing sessions** where mice are given their daily water ahead of the sesssion (and are thus satiated) and view the stimulus with the lick spout retracted so they are unable to earn water rewards. This allows comparison of neural activity in response to stimuli under different behavioral context - active task engagement and passive viewing without reward. There are two passive sessions:\n - `OPHYS_2_images_A_passive`: passive session with familiar images\n - `OPHYS_5_images_A_passive`: passive session with novel images\n\n\n\n*Text copied from [[AllenNB2]](#References)*\n\n---\n\nWe check which sessions are available for this particular mouse and select one active and one passive session type. Not all sessions may be availble due to QC.\n\n\n```python\nexperiments_df.query(\"project_code == @PROJECT_CODE\") \\\n              .query(\"full_genotype == @FULL_GENOTYPE\") \\\n              .query(\"mouse_id == @MOUSE_ID\") \\\n              [\"session_type\"].unique()\n```\n\n\n\n\n    array(['OPHYS_2_images_A_passive', 'OPHYS_1_images_A', 'OPHYS_4_images_B',\n           'OPHYS_6_images_B', 'OPHYS_5_images_B_passive'], dtype=object)\n\n\n\n\n```python\nACTIVE_SESSION_TYPE = \"OPHYS_1_images_A\"\nPASSIVE_SESSION_TYPE = \"OPHYS_2_images_A_passive\"\n```\n\n#### `ACTIVE_EXPERIMENT_ID`, `PASSIVE_EXPERIMENT_ID`\n\nWe retrieve the `ophys_experiment_id` of each session type we chose. We need this ID to get the experiment data.\n\n\n```python\nexperiments_df.query(\"project_code == @PROJECT_CODE\") \\\n              .query(\"full_genotype == @FULL_GENOTYPE\") \\\n              .query(\"mouse_id == @MOUSE_ID\") \\\n              .query(\"session_type == @ACTIVE_SESSION_TYPE\") \\\n              .index\n```\n\n\n\n\n    Int64Index([879332693], dtype='int64', name='ophys_experiment_id')\n\n\n\n\n```python\nACTIVE_EXPERIMENT_ID = 879332693\n```\n\n\n```python\nexperiments_df.query(\"project_code == @PROJECT_CODE\") \\\n              .query(\"full_genotype == @FULL_GENOTYPE\") \\\n              .query(\"mouse_id == @MOUSE_ID\") \\\n              .query(\"session_type == @PASSIVE_SESSION_TYPE\").index\n```\n\n\n\n\n    Int64Index([877696762], dtype='int64', name='ophys_experiment_id')\n\n\n\n\n```python\nPASSIVE_EXPERIMENT_ID = 877696762\n```\n\n## Explore Experiment\n\nWe can now download the experiment. Each experiment will be approximately 2GB in size.\n\n\n```python\nactive_experiment = cache.get_behavior_ophys_experiment(ACTIVE_EXPERIMENT_ID)\n```\n\n    behavior_ophys_experiment_879332693.nwb: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.93G/1.93G [00:50<00:00, 38.1MMB/s]\n\n\n\n```python\nactive_experiment\n```\n\n\n\n\n    <allensdk.brain_observatory.behavior.behavior_ophys_experiment.BehaviorOphysExperiment at 0x7f0d913230d0>\n\n\n\nThis returns an instance of `BehaviorOphysExperiment`. It contains multiple attributes that we will need to explore.\n\n### What's In Here?\n\n#### `dff_traces`\n\n\"`dff_traces` dataframe contains traces for all neurons in this experiment, unaligned to any events in the task.\" [[AllenNB3]](#References)\n\n\n```python\nactive_experiment.dff_traces.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>cell_roi_id</th>\n      <th>dff</th>\n    </tr>\n    <tr>\n      <th>cell_specimen_id</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1086601848</th>\n      <td>1080867796</td>\n      <td>[0.28201794368039823, 0.1903022438869266, 0.21...</td>\n    </tr>\n    <tr>\n      <th>1086602069</th>\n      <td>1080867804</td>\n      <td>[0.13884965897445056, 0.3963619942985226, 0.24...</td>\n    </tr>\n    <tr>\n      <th>1086635982</th>\n      <td>1080867837</td>\n      <td>[0.5498754867600153, 0.26557468920820837, 0.43...</td>\n    </tr>\n    <tr>\n      <th>1086578646</th>\n      <td>1080867844</td>\n      <td>[0.20886659311964556, 0.08442318243036104, 0.2...</td>\n    </tr>\n    <tr>\n      <th>1086598188</th>\n      <td>1080867847</td>\n      <td>[0.28967144653172083, 0.49236151316004095, 0.4...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nSince `dff` is stored as a list, we need to get timestamps for each of those numbers.\n\n#### `ophys_timestamps`\n\n`ophys_timestamps` contains the timestamps of every record.\n\n\n```python\nactive_experiment.ophys_timestamps\n```\n\n\n\n\n    array([2.55695000e+00, 2.58926000e+00, 2.62157000e+00, ...,\n           4.53777515e+03, 4.53780747e+03, 4.53783979e+03])\n\n\n\nLet's do a sanity check by checking the length of both lists.\n\n\n```python\nprint(f\"dff has length {len(active_experiment.dff_traces.iloc[0]['dff'])}\")\nprint(f\"timestamp has length {len(active_experiment.ophys_timestamps)}\")\n```\n\n    dff has length 140324\n    timestamp has length 140324\n\n\n#### `stimulus_presentations`\n\nWe also need timestamps of when stimulus was presented. This information is contained in `stimulus_presentations`.\n\n\n```python\nactive_experiment.stimulus_presentations.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>duration</th>\n      <th>end_frame</th>\n      <th>image_index</th>\n      <th>image_name</th>\n      <th>image_set</th>\n      <th>index</th>\n      <th>omitted</th>\n      <th>start_frame</th>\n      <th>start_time</th>\n      <th>stop_time</th>\n      <th>is_change</th>\n    </tr>\n    <tr>\n      <th>stimulus_presentations_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.25020</td>\n      <td>18002.0</td>\n      <td>0</td>\n      <td>im065</td>\n      <td>Natural_Images_Lum_Matched_set_training_2017.0...</td>\n      <td>0</td>\n      <td>False</td>\n      <td>17987</td>\n      <td>307.53005</td>\n      <td>307.78025</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.25022</td>\n      <td>18047.0</td>\n      <td>0</td>\n      <td>im065</td>\n      <td>Natural_Images_Lum_Matched_set_training_2017.0...</td>\n      <td>1</td>\n      <td>False</td>\n      <td>18032</td>\n      <td>308.28098</td>\n      <td>308.53120</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.24985</td>\n      <td>18092.0</td>\n      <td>0</td>\n      <td>im065</td>\n      <td>Natural_Images_Lum_Matched_set_training_2017.0...</td>\n      <td>2</td>\n      <td>False</td>\n      <td>18077</td>\n      <td>309.03163</td>\n      <td>309.28148</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.25021</td>\n      <td>18137.0</td>\n      <td>0</td>\n      <td>im065</td>\n      <td>Natural_Images_Lum_Matched_set_training_2017.0...</td>\n      <td>3</td>\n      <td>False</td>\n      <td>18122</td>\n      <td>309.78188</td>\n      <td>310.03209</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.25020</td>\n      <td>18182.0</td>\n      <td>0</td>\n      <td>im065</td>\n      <td>Natural_Images_Lum_Matched_set_training_2017.0...</td>\n      <td>4</td>\n      <td>False</td>\n      <td>18167</td>\n      <td>310.53247</td>\n      <td>310.78267</td>\n      <td>False</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nDuring imaging sessions, stimulus presentations (other than the change and pre-change images) are omitted with a 5% probability, resulting in some inter stimlus intervals appearing as an extended gray screen period. [[AllenNB2]](#References)\n\n\n\n\n```python\nactive_experiment.stimulus_presentations.query(\"omitted\").head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>duration</th>\n      <th>end_frame</th>\n      <th>image_index</th>\n      <th>image_name</th>\n      <th>image_set</th>\n      <th>index</th>\n      <th>omitted</th>\n      <th>start_frame</th>\n      <th>start_time</th>\n      <th>stop_time</th>\n      <th>is_change</th>\n    </tr>\n    <tr>\n      <th>stimulus_presentations_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>22</th>\n      <td>0.25</td>\n      <td>NaN</td>\n      <td>8</td>\n      <td>omitted</td>\n      <td>omitted</td>\n      <td>0</td>\n      <td>True</td>\n      <td>18976</td>\n      <td>324.02684</td>\n      <td>324.27684</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>119</th>\n      <td>0.25</td>\n      <td>NaN</td>\n      <td>8</td>\n      <td>omitted</td>\n      <td>omitted</td>\n      <td>1</td>\n      <td>True</td>\n      <td>23341</td>\n      <td>396.83648</td>\n      <td>397.08648</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>121</th>\n      <td>0.25</td>\n      <td>NaN</td>\n      <td>8</td>\n      <td>omitted</td>\n      <td>omitted</td>\n      <td>2</td>\n      <td>True</td>\n      <td>23431</td>\n      <td>398.33747</td>\n      <td>398.58747</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>123</th>\n      <td>0.25</td>\n      <td>NaN</td>\n      <td>8</td>\n      <td>omitted</td>\n      <td>omitted</td>\n      <td>3</td>\n      <td>True</td>\n      <td>23521</td>\n      <td>399.83869</td>\n      <td>400.08869</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>146</th>\n      <td>0.25</td>\n      <td>NaN</td>\n      <td>8</td>\n      <td>omitted</td>\n      <td>omitted</td>\n      <td>4</td>\n      <td>True</td>\n      <td>24556</td>\n      <td>417.10313</td>\n      <td>417.35313</td>\n      <td>False</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### Visualization\n\n#### Plot dF/F Trace\n\nLet's choose some random `cell_specimen_id` (1086601848) and plots its dff trace.\n\n\n```python\nfig, ax = plt.subplots(figsize=(15, 4))\n\nax.plot(\n    active_experiment.ophys_timestamps,\n    active_experiment.dff_traces.loc[1086601848][\"dff\"],\n)\n\nax.set_xlim(400, 450)\n\nfig.show()\n```\n\n#### Plot Stimulus\n\nLet's also plot stimulus for a short interval.\n\n*Part of code from [[AllenNB3]](#References)*\n\n\n```python\n# Create a color map for each image\nunique_stimuli = [stimulus for stimulus in active_experiment.stimulus_presentations['image_name'].unique()]\ncolormap = {image_name: sns.color_palette()[image_number] for image_number, image_name in enumerate(np.sort(unique_stimuli))}\n# Keep omitted image as white\ncolormap['omitted'] = (1,1,1)\n```\n\n\n```python\nstimulus_presentations_sample = active_experiment.stimulus_presentations.query('stop_time >= 400 and start_time <= 450')\n```\n\n\n```python\nfig, ax = plt.subplots(figsize=(15, 4))\n\nfor idx, stimulus in stimulus_presentations_sample.iterrows():\n    ax.axvspan(stimulus['start_time'], stimulus['stop_time'], color=colormap[stimulus['image_name']], alpha=0.25)\n\nax.set_xlim(400, 450)\n    \nfig.show()\n```\n\n#### Both\n\n\n```python\nfig, ax = plt.subplots(figsize=(15, 4))\n\nax.plot(\n    active_experiment.ophys_timestamps,\n    active_experiment.dff_traces.loc[1086601848][\"dff\"],\n)\n\nfor idx, stimulus in stimulus_presentations_sample.iterrows():\n    ax.axvspan(stimulus['start_time'], stimulus['stop_time'], color=colormap[stimulus['image_name']], alpha=0.25)\n\nax.set_xlim(400, 450)\nax.set_ylim(-0.5, 0.5)\nax.legend([\"dff trace\"])\n\nfig.show()\n```\n\n## Cell Selection\n\nWe would like to limit ourselves to looking at cells that respond to a presentation of a visual stimuli.\n\nTo understand which cells respond, we check the dF/F traces of cells 250ms before stimulus onset and 250ms after stimulus onset. Then, we choose the cells with the biggest difference in mean dF/F.\n\n\n```python\nTIME_BEFORE_STIMULUS = 0.25\nTIME_AFTER_STIMULUS = 0.25\n```\n\n### Helper Functions\n\nThese are some helper functions for getting the right timestamps and dF/F traces.\n\n\n```python\ndef get_cell_specimen_ids(experiment):\n    \"\"\"\n    Get all the cell specimen ids recorded in the experiment.\n    \"\"\"\n    return experiment.dff_traces.index\n```\n\n\n```python\ndef get_indices_in_interval(experiment, start, end):\n    \"\"\"\n    Get all indices of timestamps where dF/F trace was recorded during a specified interval.\n    \"\"\"\n    indices = np.argwhere((experiment.ophys_timestamps >= start) & (experiment.ophys_timestamps <= end))[:, 0]\n    return indices\n```\n\n\n```python\ndef get_timestamps_in_interval(experiment, start, end):\n    \"\"\"\n    Get all timestamps when dF/F trace was recorded during a specified interval.\n    \"\"\"\n    indices = get_indices_in_interval(experiment, start, end)\n    return experiment.ophys_timestamps[indices]\n```\n\n\n```python\ndef get_dff_in_interval(experiment, cell_specimen_id, start, end):\n    \"\"\"\n    Get dF/F trace for one cell during a specified interval.\n    \"\"\"\n    indices = get_indices_in_interval(experiment, start, end)\n    return experiment.dff_traces.loc[cell_specimen_id][\"dff\"][indices[0]:indices[-1]+1]\n```\n\n### Selection with Single Stimulus\n\nLet's get all the cell specimen IDs.\n\n\n```python\ncell_specimen_ids = get_cell_specimen_ids(active_experiment)\n```\n\nWe can first choose one stimulus and find the cell with the biggest difference. Let's select the first stimulus.\n\n\n```python\nstimulus_start_time = active_experiment.stimulus_presentations[\"start_time\"][0]\n```\n\nThen, we retrieve the dF/F traces before and after the stimulus with `get_dff_in_interval()` helper function. We then take the mean of both and save the difference.\n\n\n```python\nmean_dff_differences = []\n\nfor cell_specimen_id in tqdm(cell_specimen_ids):\n    before_stimulus_dff = get_dff_in_interval(\n        active_experiment,\n        cell_specimen_id,\n        start=stimulus_start_time - TIME_BEFORE_STIMULUS,\n        end=stimulus_start_time,\n    )\n    after_stimulus_dff = get_dff_in_interval(\n        active_experiment,\n        cell_specimen_id,\n        start=stimulus_start_time,\n        end=stimulus_start_time + TIME_BEFORE_STIMULUS,\n    )\n    mean_dff_difference = np.abs(np.mean(after_stimulus_dff) - np.mean(before_stimulus_dff))\n    mean_dff_differences.append(mean_dff_difference)\n\nmean_dff_differences = np.array(mean_dff_differences)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 415/415 [00:00<00:00, 1201.96it/s]\n\n\nLet's plot a histogram and a box plot to see what the distribution of mean dF/F differences look like.\n\n\n```python\nfig, axs = plt.subplots(1, 2, figsize=(12, 4))\n\naxs[0].hist(mean_dff_differences)\naxs[1].boxplot(mean_dff_differences)\n\nfig.show()\n```\n\nLooks like there are a few cells that are outstanding! Let's select the top 4 cells and see what their mean differences look like.\n\n\n```python\nTOP_K = 4\ntop_k_indices = np.argsort(mean_dff_differences)[::-1][:TOP_K]\nselected_cell_specimen_ids = cell_specimen_ids[top_k_indices]\nselected_mean_dff_differences = mean_dff_differences[top_k_indices]\nprint(selected_cell_specimen_ids)\nprint(selected_mean_dff_differences)\n```\n\n    Int64Index([1086604838, 1086578313, 1086623819, 1086637612], dtype='int64', name='cell_specimen_id')\n    [0.43820469 0.28274228 0.13674166 0.11737482]\n\n\nWe can also plot their dF/F traces before and after stimulus.\n\n\n```python\nfig, ax = plt.subplots(1, 1, figsize = (12, 4))\n\nfor cell_specimen_id, mean_dff_difference in zip(selected_cell_specimen_ids, selected_mean_dff_differences):\n    ax.plot(\n        get_timestamps_in_interval(\n            active_experiment,\n            stimulus_start_time - TIME_BEFORE_STIMULUS,\n            stimulus_start_time + TIME_AFTER_STIMULUS,\n        ),\n        get_dff_in_interval(\n            active_experiment,\n            cell_specimen_id,\n            stimulus_start_time - TIME_BEFORE_STIMULUS,\n            stimulus_start_time + TIME_AFTER_STIMULUS,\n        ),\n        label=f\"Cell {cell_specimen_id} (diff={mean_dff_difference})\"\n    )\nax.axvline(x=stimulus_start_time, color=\"k\", linestyle=\"-\")\n\nax.set_title(f\"dF/F trace of cells\")\nax.set_ylabel(\"dF/F\")\nax.set_xlabel(\"time in session (seconds)\")\nax.legend(loc='center left', bbox_to_anchor=(1, 0.5), fancybox=True, shadow=True, ncol=1)\nfig.show()\n```\n\n### Selection with All Stimulus\n\n#### Compute dF/F Differences\n\nTODO: Check if we also exclude changes\n\nWe now use all the stimulus (excluding the omitted ones) to select the cells.\n\n\n```python\n# active_stimulus_start_times = active_experiment.stimulus_presentations[\"start_time\"]\nactive_stimulus_start_times = active_experiment.stimulus_presentations.query(\"not omitted\")[\"start_time\"]\n```\n\nLet's get the mean dF/F difference for each cell. Below is bunch of code that could be a bit difficult to understand. Check the **Explanation** section if you want to understand the code.\n\n\n```python\ndff_matrix = np.vstack(active_experiment.dff_traces.dff.values)\n```\n\n\n```python\nmean_dff_differences_all_stimulus = []\nfor stimulus_start_time in tqdm(active_stimulus_start_times):\n    before_indices = get_indices_in_interval(\n        active_experiment,\n        start=stimulus_start_time - TIME_BEFORE_STIMULUS,\n        end=stimulus_start_time,\n    )\n    after_indices = get_indices_in_interval(\n        active_experiment,\n        start=stimulus_start_time,\n        end=stimulus_start_time + TIME_AFTER_STIMULUS,\n    )\n    before_mean_dff = np.mean(dff_matrix[:, before_indices], axis=1)\n    after_mean_dff = np.mean(dff_matrix[:, after_indices], axis=1)\n    mean_dff_differences = np.abs(after_mean_dff - before_mean_dff)\n    mean_dff_differences_all_stimulus.append(mean_dff_differences)\n\ndifference_matrix = np.stack(mean_dff_differences_all_stimulus, axis=1)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4640/4640 [00:02<00:00, 2094.17it/s]\n\n\n\n```python\nmean_difference_per_cell = np.mean(difference_matrix, axis=1)\n```\n\n`mean_difference_per_cell` contains the mean difference dF/F trace for each cell.\n\n\n```python\nmean_difference_per_cell.shape\n```\n\n\n\n\n    (415,)\n\n\n\n#### Explanation\n\nWe will create a 2D matrix of dF/F traces to parallelize computation. Remember how `dff_traces` looked like:\n\n\n```python\nactive_experiment.dff_traces.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>cell_roi_id</th>\n      <th>dff</th>\n    </tr>\n    <tr>\n      <th>cell_specimen_id</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1086601848</th>\n      <td>1080867796</td>\n      <td>[0.28201794368039823, 0.1903022438869266, 0.21...</td>\n    </tr>\n    <tr>\n      <th>1086602069</th>\n      <td>1080867804</td>\n      <td>[0.13884965897445056, 0.3963619942985226, 0.24...</td>\n    </tr>\n    <tr>\n      <th>1086635982</th>\n      <td>1080867837</td>\n      <td>[0.5498754867600153, 0.26557468920820837, 0.43...</td>\n    </tr>\n    <tr>\n      <th>1086578646</th>\n      <td>1080867844</td>\n      <td>[0.20886659311964556, 0.08442318243036104, 0.2...</td>\n    </tr>\n    <tr>\n      <th>1086598188</th>\n      <td>1080867847</td>\n      <td>[0.28967144653172083, 0.49236151316004095, 0.4...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nWe just stack these dff vectors vertically.\n\n\n\n\n```python\ndff_matrix = np.vstack(active_experiment.dff_traces.dff.values)\n```\n\nThe `dff_matrix` has 415 rows that correspond to the number of cells, and 140324 columns that correspond to the number of timestamps.\n\n\n```python\nprint(f\"Shape: {dff_matrix.shape}\")\nprint(f\"Number of cells: {len(cell_specimen_ids)}\")\nprint(f\"Number of timestamps: {len(active_experiment.ophys_timestamps)}\")\n```\n\n    Shape: (415, 140324)\n    Number of cells: 415\n    Number of timestamps: 140324\n\n\nEach column of this matrix will have all the cell's dF/F value for a particular time. Then, for each stimulus, we can select the columns that correspond to some interval.\n\n\n```python\nbefore_indices = get_indices_in_interval(\n    active_experiment,\n    stimulus_start_time - TIME_BEFORE_STIMULUS,\n    stimulus_start_time,\n)\n```\n\n\n```python\ndff_matrix[:, before_indices].shape\n```\n\n\n\n\n    (415, 8)\n\n\n\nThen we can take the row-wise mean to get the mean dF/F trace for this interval for all the cells for this interval.\n\n\n```python\nbefore_mean_dff = np.mean(dff_matrix[:, before_indices], axis=1)\n```\n\n\n```python\nbefore_mean_dff.shape\n```\n\n\n\n\n    (415,)\n\n\n\nWe can get two intervals corresponding to the time before and after a stimulus and find the difference.\n\n\n```python\nafter_indices = get_indices_in_interval(\n    active_experiment,\n    stimulus_start_time,\n    stimulus_start_time + TIME_BEFORE_STIMULUS,\n)\n```\n\n\n```python\nafter_mean_dff = np.mean(dff_matrix[:, after_indices], axis=1)\n```\n\n\n```python\nmean_dff_differences_2 = np.abs(after_mean_dff - before_mean_dff)\n```\n\n\n```python\nmean_dff_differences_2.shape\n```\n\n\n\n\n    (415,)\n\n\n\nLet's do a sanity check with the `mean_dff_differences` that we computed in the previous section.\n\n\n```python\nnp.allclose(mean_dff_differences, mean_dff_differences_2)\n```\n\n\n\n\n    True\n\n\n\nWe can now create another matrix `difference_matrix`.\n\n\n\n\n```python\nmean_dff_differences_all_stimulus = []\nfor stimulus_start_time in tqdm(active_stimulus_start_times):\n    before_indices = get_indices_in_interval(\n        active_experiment,\n        start=stimulus_start_time - TIME_BEFORE_STIMULUS,\n        end=stimulus_start_time,\n    )\n    after_indices = get_indices_in_interval(\n        active_experiment,\n        start=stimulus_start_time,\n        end=stimulus_start_time + TIME_AFTER_STIMULUS,\n    )\n    before_mean_dff = np.mean(dff_matrix[:, before_indices], axis=1)\n    after_mean_dff = np.mean(dff_matrix[:, after_indices], axis=1)\n    mean_dff_differences = np.abs(after_mean_dff - before_mean_dff)\n    mean_dff_differences_all_stimulus.append(mean_dff_differences)\n\ndifference_matrix = np.stack(mean_dff_differences_all_stimulus, axis=1)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4640/4640 [00:02<00:00, 2039.63it/s]\n\n\nThe difference_matrix has 415 rows that correspond to the number of cells, and 4807 columns that correspond to the number of stimuli.\n\n\n```python\nprint(f\"Shape: {difference_matrix.shape}\")\nprint(f\"Number of cells: {len(cell_specimen_ids)}\")\nprint(f\"Number of stimuli: {len(active_stimulus_start_times)}\")\n```\n\n    Shape: (415, 4640)\n    Number of cells: 415\n    Number of stimuli: 4640\n\n\nWe can take the row-wise mean to get the mean difference of all stimuli for each cell.\n\n\n```python\nmean_difference_per_cell = np.mean(difference_matrix, axis=1)\n```\n\n#### Select Cells\n\nLet's plot a histogram and a box plot of `mean_difference_per_cell` to look at the distribution.\n\n\n```python\nfig, axs = plt.subplots(1, 2, figsize=(12, 4))\n\naxs[0].hist(mean_difference_per_cell)\naxs[1].boxplot(mean_difference_per_cell)\n\nfig.show()\n```\n\nInterestingly, looks like there is one cell that stick out, and also quite a few outliers.\n\n\n```python\nTOP_K = 4\ntop_k_indices = np.argsort(mean_difference_per_cell)[::-1][:TOP_K]\nselected_cell_specimen_ids = cell_specimen_ids[top_k_indices]\nselected_mean_dff_differences = mean_difference_per_cell[top_k_indices]\nprint(selected_cell_specimen_ids)\nprint(selected_mean_dff_differences)\n```\n\n    Int64Index([1086579256, 1086592299, 1086578313, 1086637417], dtype='int64', name='cell_specimen_id')\n    [0.08101563 0.06412871 0.06329187 0.05767666]\n\n\nLet's plot the dF/F trace for these top-K cells before and after one stimulus.\n\n\n```python\nstimulus_start_time = active_stimulus_start_times[0]\n```\n\n\n```python\nfig, ax = plt.subplots(1, 1, figsize = (12, 4))\n\nfor cell_specimen_id, mean_dff_difference in zip(selected_cell_specimen_ids, selected_mean_dff_differences):\n    ax.plot(\n        get_timestamps_in_interval(\n            active_experiment,\n            stimulus_start_time - TIME_BEFORE_STIMULUS,\n            stimulus_start_time + TIME_AFTER_STIMULUS,\n        ),\n        get_dff_in_interval(\n            active_experiment,\n            cell_specimen_id,\n            stimulus_start_time - TIME_BEFORE_STIMULUS,\n            stimulus_start_time + TIME_AFTER_STIMULUS,\n        ),\n        label=f\"Cell {cell_specimen_id} (diff={mean_dff_difference})\"\n    )\nax.axvline(x=stimulus_start_time, color=\"k\", linestyle=\"-\")\n\nax.set_title(f\"dF/F trace of cells\")\nax.set_ylabel(\"dF/F\")\nax.set_xlabel(\"time in session (seconds)\")\nax.legend(loc='center left', bbox_to_anchor=(1, 0.5), fancybox=True, shadow=True, ncol=1)\nfig.show()\n```\n\nWe can also plot these for the first few stimulus.\n\n\n```python\nfig, ax = plt.subplots(1, 1, figsize = (12, 4))\n\nfor stimulus_start_time in active_stimulus_start_times[:5]:\n    for cell_specimen_id in selected_cell_specimen_ids:\n        ax.plot(\n            get_timestamps_in_interval(active_experiment, stimulus_start_time-0.25, stimulus_start_time+0.25),\n            get_dff_in_interval(active_experiment, cell_specimen_id, stimulus_start_time-0.25, stimulus_start_time+0.25),\n        )\n    ax.axvline(x=stimulus_start_time, color=\"k\", linestyle=\"-\")\n\nax.set_title('dF/F responses')\nax.set_ylabel('dF/F')\nax.set_xlabel('time in session (seconds)')\nfig.tight_layout()\nfig.show()\n```\n\n## Representational Dissimilarity Matrix (RDM)\n\nfrom https://colab.research.google.com/github/NeuromatchAcademy/course-content/blob/master/tutorials/W2D1_DeepLearning/student/W2D1_Tutorial3.ipynb#scrollTo=hOIuWVZ0Xq_E\n\nTo quantify this, we begin by computing the **representational dissimilarity matrix (RDM)** for the mouse V1 data and each model layer. This matrix, which we'll call $\\mathbf{M}$, is computed as one minus the correlation coefficients between population responses to each stimulus. We can efficiently compute this by using the $z$-scored responses. \n\nThe $z$-scored response of all neurons $\\mathbf{r}$ to stimulus $s$ is the response mean-subtracted across neurons $i$ and normalized to standard deviation 1 across neurons $i$ where $N$ is the total number of neurons:\n\\begin{equation}\n  \\mathbf{z}^{(s)} = \\frac{\\mathbf{r}^{(s)} - \\mu^{(s)}}\n  {\\sigma^{(s)}}\n\\end{equation}\nwhere $\\mu^{(s)} = \\frac{1}{N}\\sum_{i=1}^N r_i^{(s)}$ and \n$\\sigma^{(s)} = \\sqrt{\\frac{1}{N}\\sum_{i=1}^N \\left( r_i^{(s)} - \\mu^{(s)} \\right)^2}$.\n\nThen the full matrix can be computed as:\n\\begin{gather}\n  \\mathbf{M} = 1 - \\frac{1}{N} \\mathbf{ZZ}^T \\\\\n\\end{gather}\nwhere $\\mathbf{Z}$ is the z-scored response matrix with rows $\\mathbf{r}^{(s)}$ and N is the number of neurons (or units). See [bonus section 3](#b3) for full explanation.\n\n\n\n```python\ntime_after_stimulus= 0.250  # seconds\n\ndff_matrix = np.vstack(active_experiment.dff_traces.dff.values)\n```\n\n\n```python\nactive_experiment.stimulus_presentations[\"image_name\"].unique()\n```\n\n\n\n\n    array(['im065', 'omitted', 'im062', 'im061', 'im063', 'im066', 'im085',\n           'im077', 'im069'], dtype=object)\n\n\n\n\n```python\nr_lst = []\n\n# pandas\nfor stimulus_name in active_experiment.stimulus_presentations.query(\"not omitted\")[\"image_name\"].unique():\n  presentations = active_experiment.stimulus_presentations.query('image_name == @stimulus_name')\n  print(\"Number of presentations\", len(presentations))\n  presentation_means = []  # <number of stimulus presentations> x <number of cells>\n  for stimulus_onset in tqdm(presentations[\"start_time\"]):\n    indices = get_indices_in_interval(\n        active_experiment,\n        start=stimulus_onset,\n        end=stimulus_onset+time_after_stimulus,\n    )\n    presentation_means.append(np.mean(dff_matrix[:, indices], axis=1))  # mean dff [cell1, cell2, ..., celln]\n  cell_means = np.mean(np.vstack(presentation_means), axis=0)  # mean dff over all stim presentations [cell1, cell2, ..., celln]\n  print(cell_means.shape)\n  r_lst.append(cell_means)\n  # make_matrix()  # rows are all stimulus presentations, columns are neurons, values mean dff from stimulus onset to 250ms after\n\nr = np.vstack(r_lst)\nprint(r.shape)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 641/641 [00:00<00:00, 4188.69it/s]\n\n    Number of presentations 641\n    (415,)\n\n\n    \n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 629/629 [00:00<00:00, 3963.62it/s]\n      0%|          | 0/597 [00:00<?, ?it/s]\n\n    Number of presentations 629\n    (415,)\n    Number of presentations 597\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 597/597 [00:00<00:00, 3245.68it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 538/538 [00:00<00:00, 3802.50it/s]\n      0%|          | 0/494 [00:00<?, ?it/s]\n\n    (415,)\n    Number of presentations 538\n    (415,)\n    Number of presentations 494\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 494/494 [00:00<00:00, 3400.16it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 569/569 [00:00<00:00, 3944.21it/s]\n      0%|          | 0/509 [00:00<?, ?it/s]\n\n    (415,)\n    Number of presentations 569\n    (415,)\n    Number of presentations 509\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 509/509 [00:00<00:00, 3581.15it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 663/663 [00:00<00:00, 3501.85it/s]\n\n    (415,)\n    Number of presentations 663\n    (415,)\n    (8, 415)\n\n\n    \n\n\n\n```python\nprint(r.shape)\nprint(r)\n```\n\n    (8, 415)\n    [[ 0.0014368  -0.00141839  0.00231166 ...  0.0027447   0.07150208\n       0.00516828]\n     [-0.00017142  0.05090438  0.00174555 ... -0.0017843   0.00632535\n       0.00117901]\n     [ 0.00132981  0.00038188  0.0024744  ...  0.00149717  0.00501984\n      -0.0002216 ]\n     ...\n     [ 0.00237082  0.0024943   0.00181042 ...  0.00013242  0.00602932\n       0.00099942]\n     [ 0.00168079  0.00661778  0.00240998 ...  0.00159245  0.00299351\n       0.0023609 ]\n     [-0.0004427   0.01225633  0.00307946 ...  0.00197598  0.13105824\n       0.01868374]]\n\n\nNow compute the RDM.\n\n\n```python\n from scipy.stats import zscore\n zresp = zscore(r, axis=1)\nprint(zresp.shape)  # according to NMA r is shape <stimulus> x <cell count>\n  # Compute RDM\nRDM = 1 - (zresp @ zresp.T) / zresp.shape[1]\nprint(RDM.shape)\n```\n\n    (8, 415)\n    (8, 8)\n\n\n\n```python\nax = sns.heatmap(RDM, cmap=\"G\") # red is very dissimlar, blue is very similar \nax.set_title(\"RDM active\")\nNone\n```\n\n\n\n\n```python\nactive_experiment\n```\n\n\n```python\nmean_dff_differences_all_stimulus = []\nfor stimulus_start_time in tqdm(active_stimulus_start_times):\n    before_indices = get_indices_in_interval(\n        active_experiment,\n        start=stimulus_start_time - TIME_BEFORE_STIMULUS,\n        end=stimulus_start_time,\n    )\n    after_indices = get_indices_in_interval(\n        active_experiment,\n        start=stimulus_start_time,\n        end=stimulus_start_time + TIME_AFTER_STIMULUS,\n    )\n    before_mean_dff = np.mean(dff_matrix[:, before_indices], axis=1)\n    after_mean_dff = np.mean(dff_matrix[:, after_indices], axis=1)\n    mean_dff_differences = np.abs(after_mean_dff - before_mean_dff)\n    mean_dff_differences_all_stimulus.append(mean_dff_differences)\n\ndifference_matrix = np.stack(mean_dff_differences_all_stimulus, axis=1)\n```\n\n## Hypothesis Testing\n\nWe selected 4 cells in the previous section.\n\n\n```python\nselected_cell_specimen_ids\n```\n\n\n\n\n    Int64Index([1086579256, 1086592299, 1086578313, 1086637417], dtype='int64', name='cell_specimen_id')\n\n\n\nLet's select one cell to analyze.\n\n\n```python\nselected_cell_specimen_id = selected_cell_specimen_ids[0]\nselected_cell_specimen_id\n```\n\n\n\n\n    1086579256\n\n\n\nTo test our hypothesis, we need both active and passive sessions, so let's load the passive session now.\n\n\n```python\npassive_experiment = cache.get_behavior_ophys_experiment(PASSIVE_EXPERIMENT_ID)\n```\n\n\n```python\npassive_stimulus_start_times = passive_experiment.stimulus_presentations.query(\"not omitted\")[\"start_time\"]\n```\n\n### One stimulus\n\n\n```python\nactive_stimulus_start_time = active_stimulus_start_times[0]\npassive_stimulus_start_time = passive_stimulus_start_times[0]\n```\n\n\n```python\nactive_timestamps = get_timestamps_in_interval(active_experiment, active_stimulus_start_time, active_stimulus_start_time+0.250)\nactive_dff = get_dff_in_interval(active_experiment, selected_cell_specimen_id, active_stimulus_start_time, active_stimulus_start_time+0.250)\n```\n\n\n```python\npassive_timestamps = get_timestamps_in_interval(passive_experiment, passive_stimulus_start_time, passive_stimulus_start_time+0.250)\npassive_dff = get_dff_in_interval(passive_experiment, selected_cell_specimen_id, passive_stimulus_start_time, passive_stimulus_start_time+0.250)\n```\n\n\n```python\nfig, ax = plt.subplots()\nax.plot(active_timestamps - active_timestamps[0], active_dff, label=\"active\")\nax.plot(passive_timestamps - passive_timestamps[0], passive_dff, label=\"passive\")\nfig.legend()\nfig.show()\n```\n\n### Multiple stimulus (WIP)\n\n\n```python\ndiff_traces_per_stimulus = []\nactive_dffs = []\nfor stimulus_start_time in tqdm(active_stimulus_start_times):\n    dff = get_dff_in_interval(active_experiment, selected_cell_specimen_id, stimulus_start_time, stimulus_start_time+0.250)\n    active_dffs.append(dff)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4640/4640 [00:01<00:00, 2641.66it/s]\n\n\n\n```python\nfrom collections import Counter\n\nCounter([len(active_dff) for active_dff in active_dffs])\n```\n\n\n\n\n    Counter({8: 3411, 7: 1229})\n\n\n", "meta": {"hexsha": "d7c0332bc61b053aa6587433abfdf187614dffa3", "size": 543268, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "outdated_notebooks/20210716.ipynb", "max_stars_repo_name": "FranckPrts/nma-cn-project", "max_stars_repo_head_hexsha": "c53946ce3a95d714812c152131e0bf69ebbe2911", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-08-11T04:30:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T10:39:27.000Z", "max_issues_repo_path": "outdated_notebooks/20210716.ipynb", "max_issues_repo_name": "FranckPrts/nma-cn-project", "max_issues_repo_head_hexsha": "c53946ce3a95d714812c152131e0bf69ebbe2911", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "outdated_notebooks/20210716.ipynb", "max_forks_repo_name": "FranckPrts/nma-cn-project", "max_forks_repo_head_hexsha": "c53946ce3a95d714812c152131e0bf69ebbe2911", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-26T16:55:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T16:55:13.000Z", "avg_line_length": 139.0143295803, "max_line_length": 92738, "alphanum_fraction": 0.8305863773, "converted": true, "num_tokens": 17585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014733397551624, "lm_q2_score": 0.06560484430997267, "lm_q1q2_score": 0.02821974887581356}}
{"text": "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Calibrated-Recommendations\" data-toc-modified-id=\"Calibrated-Recommendations-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Calibrated Recommendations</a></span><ul class=\"toc-item\"><li><span><a href=\"#Preparation\" data-toc-modified-id=\"Preparation-1.1\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;</span>Preparation</a></span></li><li><span><a href=\"#Deep-Dive-Into-Calibrated-Recommendation\" data-toc-modified-id=\"Deep-Dive-Into-Calibrated-Recommendation-1.2\"><span class=\"toc-item-num\">1.2&nbsp;&nbsp;</span>Deep Dive Into Calibrated Recommendation</a></span><ul class=\"toc-item\"><li><span><a href=\"#Calibration-Metric\" data-toc-modified-id=\"Calibration-Metric-1.2.1\"><span class=\"toc-item-num\">1.2.1&nbsp;&nbsp;</span>Calibration Metric</a></span></li><li><span><a href=\"#Generating-Calibrated-Recommendations\" data-toc-modified-id=\"Generating-Calibrated-Recommendations-1.2.2\"><span class=\"toc-item-num\">1.2.2&nbsp;&nbsp;</span>Generating Calibrated Recommendations</a></span></li></ul></li><li><span><a href=\"#End-Note\" data-toc-modified-id=\"End-Note-1.3\"><span class=\"toc-item-num\">1.3&nbsp;&nbsp;</span>End Note</a></span></li></ul></li><li><span><a href=\"#Reference\" data-toc-modified-id=\"Reference-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Reference</a></span></li></ul></div>\n\n\n```python\n# code for loading the format for the notebook\nimport os\n\n# path : store the current path to convert back to it later\npath = os.getcwd()\nos.chdir(os.path.join('..', '..', 'notebook_format'))\n\nfrom formats import load_style\nload_style(css_style='custom2.css', plot_style=False)\n```\n\n\n\n\n\n<style>\n    html {\n        font-size: 18px !important;\n    }\n\n    body {\n        background-color: #FFF !important;\n        font-weight: 1rem;\n        font-family: 'Source Sans Pro', \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n    }\n\n    body .notebook-app {\n        background-color: #FFF !important;\n    }\n\n    #header {\n        box-shadow: none !important;\n    }\n\n    #notebook {\n        padding-top: 0px;\n    }\n\n    #notebook-container {\n        box-shadow: none;\n        -webkit-box-shadow: none;\n        padding: 10px;\n    }\n\n    div.cell {\n        width: 1000px;\n        margin-left: 0% !important;\n        margin-right: auto;\n    }\n\n    div.cell.selected {\n        border: 1px dashed #CCCCCC;\n    }\n\n    .edit_mode div.cell.selected {\n        border: 1px dashed #828282;\n    }\n\n    div.output_wrapper {\n        margin-top: 8px;\n    }\n\n    a {\n        color: #383838;\n    }\n\n    code,\n    kbd,\n    pre,\n    samp {\n        font-family: 'Menlo', monospace !important;\n        font-size: 0.75rem !important;\n    }\n\n    h1 {\n        font-size: 2rem !important;\n        font-weight: 500 !important;\n        letter-spacing: 3px !important;\n        text-transform: uppercase !important;\n    }\n\n    h2 {\n        font-size: 1.8rem !important;\n        font-weight: 400 !important;\n        letter-spacing: 3px !important;\n        text-transform: none !important;\n    }\n\n    h3 {\n        font-size: 1.5rem !important;\n        font-weight: 400 !important;\n        font-style: italic !important;\n        display: block !important;\n    }\n\n    h4,\n    h5,\n    h6 {\n        font-size: 1rem !important;\n        font-weight: 400 !important;\n        display: block !important;\n    }\n\n    .prompt {\n        font-family: 'Menlo', monospace !important;\n        font-size: 0.75rem;\n        text-align: right;\n        line-height: 1.21429rem;\n    }\n\n    /* INTRO PAGE */\n\n    .toolbar_info,\n    .list-container {\n        ;\n    }\n    /* NOTEBOOK */\n\n    div#header-container {\n        display: none !important;\n    }\n\n    div#notebook {\n        border-top: none;\n        font-size: 1rem;\n    }\n\n    div.input_prompt {\n        color: #C74483;\n    }\n\n    .code_cell div.input_prompt:after,\n    div.output_prompt:after {\n        content: '\\25b6';\n    }\n\n    div.output_prompt {\n        color: #2B88D9;\n    }\n\n    div.input_area {\n        border-radius: 0px;\n        border: 1px solid #d8d8d8;\n    }\n\n    div.output_area pre {\n        font-weight: normal;\n    }\n\n    div.output_subarea {\n        font-weight: normal;\n    }\n\n    .rendered_html pre,\n    .rendered_html table,\n    .rendered_html th,\n    .rendered_html tr,\n    .rendered_html td {\n        border: 1px #828282 solid;\n        font-size: 0.75rem;\n        font-family: 'Menlo', monospace;\n    }\n\n    .rendered_html th,\n    .rendered_html tr,\n    .rendered_html td {\n        padding: 5px 10px;\n    }\n\n    .rendered_html th {\n        font-weight: normal;\n        background: #f8f8f8;\n    }\n\n    a:link{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:visited{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:hover{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:focus{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:active{\n       font-weight: bold;\n       color:#447adb;\n    }\n    .rendered_html :link {\n       text-decoration: underline; \n    }\n\n    div.output_html {\n        font-weight: 1rem;\n        font-family: 'Source Sans Pro', \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n    }\n\n    table.dataframe tr {\n        border: 1px #CCCCCC;\n    }\n\n    div.cell.selected {\n        border-radius: 0px;\n    }\n\n    div.cell.edit_mode {\n        border-radius: 0px;\n        border: thin solid #CF5804;\n    }\n\n    span.ansiblue {\n        color: #00A397;\n    }\n\n    span.ansigray {\n        color: #d8d8d8;\n    }\n\n    span.ansigreen {\n        color: #688A0A;\n    }\n\n    span.ansipurple {\n        color: #975DDE;\n    }\n\n    span.ansired {\n        color: #D43132;\n    }\n\n    span.ansiyellow {\n        color: #D9AA00;\n    }\n\n    div.output_stderr {\n        background-color: #D43132;\n    }\n\n    div.output_stderr pre {\n        color: #e8e8e8;\n    }\n\n    .cm-s-ipython.CodeMirror {\n        background: #F8F8F8;\n    }\n\n    .cm-s-ipython div.CodeMirror-selected {\n        background: #e8e8e8 !important;\n    }\n\n    .cm-s-ipython .CodeMirror-gutters {\n        background: #F8F8F8;\n        border-right: 0px;\n    }\n\n    .cm-s-ipython .CodeMirror-linenumber {\n        color: #b8b8b8;\n    }\n\n    .cm-s-ipython .CodeMirror-cursor {\n        border-left: 1px solid #585858 !important;\n    }\n\n    .cm-s-ipython span.cm-atom {\n        color: #C74483;\n    }\n\n    .cm-s-ipython span.cm-number {\n        color: #C74483;\n    }\n\n    .cm-s-ipython span.cm-property,\n    .cm-s-ipython span.cm-attribute {\n        color: #688A0A;\n    }\n\n    .cm-s-ipython span.cm-keyword {\n        font-weight: normal;\n        color: #D43132;\n    }\n\n    .cm-s-ipython span.cm-string {\n        color: #D9AA00;\n    }\n\n    .cm-s-ipython span.cm-operator {\n        font-weight: normal;\n    }\n\n    .cm-s-ipython span.cm-builtin {\n        color: #2B88D9;\n    }\n\n    .cm-s-ipython span.cm-variable {\n        color: #00A397;\n    }\n\n    .cm-s-ipython span.cm-variable-2 {\n        color: #2B88D9;\n    }\n\n    .cm-s-ipython span.cm-def {\n        color: #00A397;\n    }\n\n    .cm-s-ipython span.cm-error {\n        background: #FFBDBD;\n        color: #D43132;\n    }\n\n    .cm-s-ipython span.cm-tag {\n        color: #D43132;\n    }\n\n    .cm-s-ipython span.cm-link {\n        color: #975DDE;\n    }\n\n    .cm-s-ipython .CodeMirror-matchingbracket {\n        text-decoration: underline;\n         !important;\n    }\n</style>\n\n\n\n\n\n\n```python\nos.chdir(path)\n\n# 1. magic for inline plot\n# 2. magic to print version\n# 3. magic so that the notebook will reload external python modules\n# 4. magic to enable retina (high resolution) plots\n# https://gist.github.com/minrk/3301035\n%matplotlib inline\n%load_ext watermark\n%load_ext autoreload\n%autoreload 2\n%config InlineBackend.figure_format='retina'\n\nimport os\nimport time\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy.sparse import csr_matrix\nfrom implicit.bpr import BayesianPersonalizedRanking\nfrom implicit.evaluation import train_test_split, precision_at_k\n\n%watermark -a 'Ethen' -d -t -v -p scipy,numpy,pandas,matplotlib,implicit\n```\n\n    Ethen 2018-10-17 10:09:55 \n    \n    CPython 3.6.4\n    IPython 6.4.0\n    \n    scipy 1.1.0\n    numpy 1.14.1\n    pandas 0.23.0\n    matplotlib 2.2.2\n    implicit 0.3.8\n\n\n# Calibrated Recommendations\n\nWhen a user has watched, say, 70% romance movies and 30% action movies in the past, then it is reasonable to expect the personalized list of recommended movies to be comprised of 70% romance and 30% action movies as well since we would like to cover the user's diverse set of interests. A recommendation that actually reflect most if not all of the user's interest is considered a **Calibrated Recommendation**. But the question is, does our recommendation exhibit this trait?\n\nRecommendation algorithm provides personalized user experience past on the user's past historical interaction with the product/system/website. However, when serving the recommendation such as recommendation top 10 movies that we think the user might be interested in, a recommendation engine that is solely measured based on ranking metrics can easily generate recommendations that focus on the main area of interests, resulting the user's other area of interest to be under-represented, or worse, absent in the final recommendation.\n\nTo hit the notion home, using the example above, given a user that has watched 70% romance movies and 30% action movies, if we were to solely measure the metric based on precision, we can say we can achieve the best performance by predicting the majority genre, i.e. we will recommend 100% romance movies and we can expect the user to interact with those recommendations 70% of the time. On other other hand, if we were to recommend 70% romance movies and 30% action movies, then we would expect our recommendation to only be correct 0.7 * 0.7 + 0.3 * 0.3 = 58% of the time.\n\nThroughout the rest of this notebook, we will take a look at if the phenomenon of crowding out user's sub-interest occurs with our recommendation, develop a quantitative metric to measure how severe this issue is and implement a post-preprocessing logic that is agnostic of the underlying recommendation algorithm we decided to use to ensure the recommendation becomes more calibrated.\n\n## Preparation\n\nWe'll be using the publicly available movielens-20m dataset throughout this experiment. We can download it via the following [link](https://www.kaggle.com/grouplens/movielens-20m-dataset). There's multiple data under that folder, we can select download all to make things easier.\n\nThe algorithm that we will be using to generate the recommendation is Bayesian Personalized Ranking, which is a matrix factorization based collaborative filtering algorithm. The reader doesn't need to be acquainted with this model per se to continue with the rest of this notebook as the discussion is model-agnostic and we'll be explaining the syntax. That said, this [link](https://github.com/ethen8181/machine-learning#recsys--20161217) contains some resources on this algorithm if it is of interest.\n\nGiven the dataset and the algorithm the preparation step we'll be doing in the next few code chunks is this:\n- The raw `rating.csv` contains user's rating for each movie. Here, we will focus on implicit data, and follow the usual procedure of simulating binary implicit feedback data (i.e. whether the user enjoyed the movie) by retaining only ratings of 4 stars and higher, while dropping lower ratings.\n- The raw `movie.csv` contains each movies genre tag. We will also eliminate movies that had no genre information attached and create a mapping that stores each movies' genre distribution. In this dataset, each movie $i$ typically has several genres $g$ associated with it, thus we assign equal probabilities $p(g|i)$ to each genre such that $\\sum_g p(g|i) = 1$ for each movie $i$. This genre distribution will play a strong role in determining whether our recommendation is well calibrated or not.\n\n\n```python\ndata_dir = 'movielens-20m-dataset'\n\n# we are working with movie data, but we'll name\n# the movie as item to make it more generic to\n# all use-cases\nuser_col = 'userId'\nitem_col = 'movieId'\nvalue_col = 'rating'\ntime_col = 'timestamp'\n\nrating_path = os.path.join(data_dir, 'rating.csv')\ndf_raw = pd.read_csv(rating_path)\nprint('dimension: ', df_raw.shape)\ndf_raw.head()\n```\n\n    dimension:  (20000263, 4)\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>userId</th>\n      <th>movieId</th>\n      <th>rating</th>\n      <th>timestamp</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>2</td>\n      <td>3.5</td>\n      <td>2005-04-02 23:53:47</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>29</td>\n      <td>3.5</td>\n      <td>2005-04-02 23:31:16</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1</td>\n      <td>32</td>\n      <td>3.5</td>\n      <td>2005-04-02 23:33:39</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1</td>\n      <td>47</td>\n      <td>3.5</td>\n      <td>2005-04-02 23:32:07</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1</td>\n      <td>50</td>\n      <td>3.5</td>\n      <td>2005-04-02 23:29:40</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ntitle_col = 'title'\ngenre_col = 'genres'\n\nitem_info_path = os.path.join(data_dir, 'movie.csv')\ndf_item = pd.read_csv(item_info_path)\ndf_item = df_item[df_item[genre_col] != '(no genres listed)']\nprint('dimension: ', df_item.shape)\ndf_item.head()\n```\n\n    dimension:  (27032, 3)\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>movieId</th>\n      <th>title</th>\n      <th>genres</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>Toy Story (1995)</td>\n      <td>Adventure|Animation|Children|Comedy|Fantasy</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2</td>\n      <td>Jumanji (1995)</td>\n      <td>Adventure|Children|Fantasy</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>3</td>\n      <td>Grumpier Old Men (1995)</td>\n      <td>Comedy|Romance</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>4</td>\n      <td>Waiting to Exhale (1995)</td>\n      <td>Comedy|Drama|Romance</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>5</td>\n      <td>Father of the Bride Part II (1995)</td>\n      <td>Comedy</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nclass Item:\n    \"\"\"\n    Data holder for our item.\n    \n    Parameters\n    ----------\n    id : int\n  \n    title : str\n\n    genre : dict[str, float]\n        The item/movie's genre distribution, where the key\n        represents the genre and value corresponds to the\n        ratio of that genre.\n\n    score : float\n        Score for the item, potentially generated by some\n        recommendation algorithm.\n    \"\"\"\n    def __init__(self, _id, title, genres, score=None):\n        self.id = _id\n        self.title = title\n        self.score = score\n        self.genres = genres\n\n    def __repr__(self):\n        return self.title\n\n\ndef create_item_mapping(df_item, item_col, title_col, genre_col):\n    \"\"\"Create a dictionary of item id to Item lookup.\"\"\"\n    item_mapping = {}\n    for row in df_item.itertuples():\n        item_id = getattr(row, item_col)\n        item_title = getattr(row, title_col)\n        item_genre = getattr(row, genre_col)\n\n        splitted = item_genre.split('|')\n        genre_ratio = 1. / len(splitted)\n        item_genre = {genre: genre_ratio for genre in splitted}\n\n        item = Item(item_id, item_title, item_genre)\n        item_mapping[item_id] = item\n\n    return item_mapping\n    \n\nitem_mapping = create_item_mapping(df_item, item_col, title_col, genre_col)\nitem_mapping[1]\n```\n\n\n\n\n    Toy Story (1995)\n\n\n\n\n```python\n# convert to implicit feedback data and filter out\n# movies that doesn't have any genre\ndf_rating = df_raw[df_raw[value_col] >= 4.0].copy()\ndf_rating = df_rating.merge(df_item, on=item_col)\n\nfor col in (user_col, item_col):\n    df_rating[col] = df_rating[col].astype('category')\n\n# the original id are converted to indices to create\n# the sparse matrix, so we keep track of the mappings here\n# e.g. a userId 1 will correspond to index 0 in our sparse matrix\nindex2user = df_rating[user_col].cat.categories\nindex2item = df_rating[item_col].cat.categories\n\nprint('dimension: ', df_rating.shape)\ndf_rating.head()\n```\n\n    dimension:  (9995306, 6)\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>userId</th>\n      <th>movieId</th>\n      <th>rating</th>\n      <th>timestamp</th>\n      <th>title</th>\n      <th>genres</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>151</td>\n      <td>4.0</td>\n      <td>2004-09-10 03:08:54</td>\n      <td>Rob Roy (1995)</td>\n      <td>Action|Drama|Romance|War</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>48</td>\n      <td>151</td>\n      <td>4.0</td>\n      <td>1996-12-16 04:36:03</td>\n      <td>Rob Roy (1995)</td>\n      <td>Action|Drama|Romance|War</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>58</td>\n      <td>151</td>\n      <td>5.0</td>\n      <td>2006-04-03 10:12:03</td>\n      <td>Rob Roy (1995)</td>\n      <td>Action|Drama|Romance|War</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>67</td>\n      <td>151</td>\n      <td>5.0</td>\n      <td>1999-12-11 17:20:46</td>\n      <td>Rob Roy (1995)</td>\n      <td>Action|Drama|Romance|War</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>91</td>\n      <td>151</td>\n      <td>4.0</td>\n      <td>2005-04-11 07:01:45</td>\n      <td>Rob Roy (1995)</td>\n      <td>Action|Drama|Romance|War</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nGiven this dataframe we will use the `userId`, `movieId` and `rating` to construct a sparse matrix, perform the random train/test split (we can split based on the time if preferred) and feed the training set into a collaborative filtering based algorithm to train the model, so we can generate item recommendations for users.\n\n\n```python\ndef create_user_item_csr_matrix(data, user_col, item_col, value_col):\n    rows = data[user_col].cat.codes\n    cols = data[item_col].cat.codes\n    values = data[value_col].astype(np.float32)\n    return csr_matrix((values, (rows, cols)))\n\n\nuser_item = create_user_item_csr_matrix(df_rating, user_col, item_col, value_col)\nuser_item\n```\n\n\n\n\n    <138287x20660 sparse matrix of type '<class 'numpy.float32'>'\n    \twith 9995306 stored elements in Compressed Sparse Row format>\n\n\n\n\n```python\nnp.random.seed(1234)\nuser_item_train, user_item_test = train_test_split(user_item, train_percentage=0.8)\nuser_item_train\n```\n\n\n\n\n    <138287x20660 sparse matrix of type '<class 'numpy.float32'>'\n    \twith 7995785 stored elements in Compressed Sparse Row format>\n\n\n\n\n```python\nuser_item_test\n```\n\n\n\n\n    <138287x20660 sparse matrix of type '<class 'numpy.float32'>'\n    \twith 1999521 stored elements in Compressed Sparse Row format>\n\n\n\n\n```python\n# the model expects item-user sparse matrix,\n# i.e. the rows represents item and the column\n# represents users\nnp.random.seed(1234)\nbpr = BayesianPersonalizedRanking(iterations=70)\nbpr.fit(user_item_train.T.tocsr())\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 70/70 [01:26<00:00,  1.16s/it, correct=89.30%, skipped=12.78%]\n\n\nwe will look at a precision_at_k metric just to make sure our recommender is reasonable, feel free to tune the model's hyperparameter to squeeze out performance, but that is not the focus here.\n\n\n```python\nprecision = precision_at_k(bpr, user_item_train, user_item_test, K=10)\nprecision\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 138287/138287 [02:07<00:00, 1081.09it/s]\n\n\n\n\n\n    0.1572725960678889\n\n\n\n## Deep Dive Into Calibrated Recommendation\n\nWe will take the first user as an example to see whether our recommendations are calibrated or not. Once we're familiar with the procedure for one user, we can repeat the process for all of the users if we'd like to.\n\nLet's start of by defining the problem. We are given the distribution genres $g$ for each movie $i$, $p(g|i)$, what we are interested is whether $p(g|u)$ is similar to $q(g|u)$. Where:\n\n- $p(g|u)$ is the distribution over genre $g$ of the set of movies $H$ played by user $u$ in the past.\n\n\\begin{align}\np(g|u) = \\sum_{i \\in H} p(g|i)\n\\end{align}\n\n- $q(g|u)$ is the distribution over genre $g$ of the set of movies $I$ we recommended to user $u$.\n\n\\begin{align}\nq(g|u) = \\sum_{i \\in I} p(g|i)\n\\end{align}\n\nFor these distributions, we can have a weighted version if we liked to get sophisticated. e.g. the $p(g|i)$ can be weighted by recency saying something like the item/movie interaction matters more if its a more recent interaction, indicating that item/movie's genre should also be weighted more, but let's not go there yet.\n\nLet's first look at some code to generate these information.\n\n\n```python\n# look a the first user\nuser_id = 0\n\n# find the index that the user interacted with,\n# we can then map this to a list of Item, note that we need to first\n# map the recommended index to the actual itemId/movieId first\ninteracted_ids = user_item_train[user_id].nonzero()[1]\ninteracted_items = [item_mapping[index2item[index]] for index in interacted_ids]\ninteracted_items[:10]\n```\n\n\n\n\n    [Rob Roy (1995),\n     Clerks (1994),\n     Interview with the Vampire: The Vampire Chronicles (1994),\n     Star Wars: Episode IV - A New Hope (1977),\n     L\u00e9on: The Professional (a.k.a. The Professional) (L\u00e9on) (1994),\n     Pulp Fiction (1994),\n     Shawshank Redemption, The (1994),\n     Platoon (1986),\n     E.T. the Extra-Terrestrial (1982),\n     Star Wars: Episode V - The Empire Strikes Back (1980)]\n\n\n\nFor the same user, we can use the .recommend method to recommend the topn recommendation for him/her, note that we also passed in the original sparse matrix, and by default, the items/movies that the user has already played will be filtered from the list (controlled by a `filter_already_liked_items` argument, which defaults to `True`).\n\n\n```python\n# it returns the recommended index and their corresponding score\ntopn = 20\nreco = bpr.recommend(user_id, user_item_train, N=topn)\nreco[:10]\n```\n\n\n\n\n    [(7383, 3.7959714),\n     (4015, 3.5959027),\n     (3992, 3.423524),\n     (5509, 3.3848886),\n     (3805, 3.3572443),\n     (1231, 3.3039956),\n     (1307, 3.265023),\n     (6094, 3.1746044),\n     (6825, 3.1063333),\n     (1290, 3.0932918)]\n\n\n\n\n```python\n# map the index to Item\nreco_items = [item_mapping[index2item[index]] for index, _ in reco]\nreco_items[:10]\n```\n\n\n\n\n    [Jason and the Argonauts (1963),\n     Lost Boys, The (1987),\n     Evil Dead, The (1981),\n     Godzilla vs. Mothra (Mosura tai Gojira) (1964),\n     Hellraiser (1987),\n     Evil Dead II (Dead by Dawn) (1987),\n     Dracula (Bram Stoker's Dracula) (1992),\n     Ringu (Ring) (1998),\n     Invasion of the Body Snatchers (1978),\n     American Werewolf in London, An (1981)]\n\n\n\nThe next code chunk defines a function to obtain the genre distribution for a list of items. Given that we now have the list of interacted items and recommended items, we can pass it to the function to obtain the two genre distributions.\n\n\n```python\ndef compute_genre_distr(items):\n    \"\"\"Compute the genre distribution for a given list of Items.\"\"\"\n    distr = {}\n    for item in items:\n        for genre, score in item.genres.items():\n            genre_score = distr.get(genre, 0.)\n            distr[genre] = genre_score + score\n\n    # we normalize the summed up probability so it sums up to 1\n    # and round it to three decimal places, adding more precision\n    # doesn't add much value and clutters the output\n    for item, genre_score in distr.items():\n        normed_genre_score = round(genre_score / len(items), 3)\n        distr[item] = normed_genre_score\n\n    return distr\n```\n\n\n```python\n# we can check that the probability does in fact add up to 1\n# np.array(list(interacted_distr.values())).sum()\ninteracted_distr = compute_genre_distr(interacted_items)\ninteracted_distr\n```\n\n\n\n\n    {'Action': 0.113,\n     'Drama': 0.109,\n     'Romance': 0.034,\n     'War': 0.015,\n     'Comedy': 0.073,\n     'Horror': 0.093,\n     'Adventure': 0.178,\n     'Sci-Fi': 0.06,\n     'Crime': 0.038,\n     'Thriller': 0.058,\n     'Children': 0.019,\n     'Fantasy': 0.163,\n     'Western': 0.007,\n     'Musical': 0.005,\n     'Animation': 0.01,\n     'Mystery': 0.016,\n     'IMAX': 0.008}\n\n\n\n\n```python\nreco_distr = compute_genre_distr(reco_items)\nreco_distr\n```\n\n\n\n\n    {'Action': 0.133,\n     'Adventure': 0.121,\n     'Fantasy': 0.117,\n     'Comedy': 0.058,\n     'Horror': 0.271,\n     'Thriller': 0.133,\n     'Sci-Fi': 0.108,\n     'Romance': 0.013,\n     'Mystery': 0.046}\n\n\n\n\n```python\n# change default style figure and font size\nplt.rcParams['figure.figsize'] = 10, 8\nplt.rcParams['font.size'] = 12\n\n\ndef distr_comparison_plot(interacted_distr, reco_distr, width=0.3):\n    \n    # the value will automatically be converted to a column with the\n    # column name of '0'\n    interacted = pd.DataFrame.from_dict(interacted_distr, orient='index')\n    reco = pd.DataFrame.from_dict(reco_distr, orient='index')\n    df = interacted.join(reco, how='outer', lsuffix='_interacted')\n\n    n = df.shape[0]\n    index = np.arange(n)\n    plt.barh(index, df['0_interacted'], height=width, label='interacted distr')\n    plt.barh(index + width, df['0'], height=width, label='reco distr')\n    plt.yticks(index, df.index)\n    plt.legend(bbox_to_anchor=(1, 0.5))\n    plt.title('Genre Distribution between User Historical Interaction v.s. Recommendation')\n    plt.ylabel('Genre')\n    plt.show()\n    \n    \ndistr_comparison_plot(interacted_distr, reco_distr)\n```\n\n### Calibration Metric\n\nLooking at the results above, we can see that according to $p(g|u)$, the user has interacted with genres such as War, Western, however, they are nowhere to be seen in the topn recommendation to the user, hence we can argue based on the output that our recommendation might not be that well calibrated to the user's past interaction.\n\nTo scale this type of comparison, we'll now define our calibration metric $C$. There are various methods to compare whether two distributions are similar to each other, and one popular choice is KL-divergence.\n\n\\begin{align}\nC(p,q) = D_{KL}(p || q) = \\sum_{g} p(g|u) \\cdot \\log \\frac{p(g|u)}{\\tilde{q}(g|u)}\n\\end{align}\n\nThe denominator in the formula should be $q(g|u)$, but given that the formula would be undefined if $q(g|u) = 0$ and $p(g|u) > 0$ for a genre $g$. We instead use:\n\n\\begin{align}\n\\tilde{q}(g|u) = (1 - \\alpha) \\cdot q(g|u) + \\alpha \\cdot p(g|u)\n\\end{align}\n\nwith a small $\\alpha$ such as 0.01, so that $q(g|u) \\approx \\tilde{q}(g|u)$.\n\n\n```python\ndef compute_kl_divergence(interacted_distr, reco_distr, alpha=0.01):\n    \"\"\"\n    KL (p || q), the lower the better.\n\n    alpha is not really a tuning parameter, it's just there to make the\n    computation more numerically stable.\n    \"\"\"\n    kl_div = 0.\n    for genre, score in interacted_distr.items():\n        reco_score = reco_distr.get(genre, 0.)\n        reco_score = (1 - alpha) * reco_score + alpha * score\n        kl_div += score * np.log2(score / reco_score)\n\n    return kl_div\n\n\ncompute_kl_divergence(interacted_distr, reco_distr)\n```\n\n\n\n\n    1.3345197164266038\n\n\n\n### Generating Calibrated Recommendations\n\nBeing able to compute the calibration metric between $p(g|u)$ and $q(g|u)$ is all well and good, but how can we generate a recommendation list that is more calibrated becomes the next important and interesting question.\n\nDifferent recommendation algorithm's objective function might be completely different, thus instead of going to hard-route of incorporating it into the objective function right off the bat and spend two weeks writing the customized algorithm in an efficient manner, we will start with an alternative approach of re-ranking the predicted list of a recommender system in a post-processing step.\n\nTo determine the optimal set $I^*$ of $N$ recommended items, we'll be using maximum marginal relevance.\n\n\\begin{align}\nI^* = \\underset{I, |I|=N}{\\text{argmax}} \\; (1 - \\lambda) \\cdot s(I) - \\lambda \\cdot C(p, q(I))\n\\end{align}\n\nWhere\n\n- $s(i)$ is the score of the items $i \\in I$ predicted by the recommender system and $s(I) = \\sum_{i \\in I} s(i)$, i.e. the sum of all the items' score in the recommendation list.\n- $\\lambda \\in [0, 1]$ is a tuning parameter that determines the trade-off between the score generated by the recommender and the calibration score, notice that since the calibration score is measured by KL-divergence, which is a metric that's the lower the better we use its negative in the maximization formula.\n\nFinding the optimal set $I^*$ is a combinatorial optimization problem and can be a topic by itself. We won't do a deep dive into it, but instead leverage a popular greedy submodular optimization to solve this problem. The process is as follows:\n\n- We start out with the empty set.\n- Iteratively append one item $i$ at a time, and at step $n$, when we already have the set $I_{n-1}$ comprised of $n - 1$ items, the item $i$ that maximizes the objective function defined above for the set $I_{n-1} \\cup {i}$ is added to obtain $I_n$\n- Repeat the process the generate the full $I^*$ of size $N$.\n\nFrom a theoretical standpoint, this procedure guarantees a solution that has a score of 0.63 of the optimal set.\n\nWith these information at hand, let's look at the implementation part:\n\n\n```python\ndef generate_item_candidates(model, user_item, user_id, index2item, item_mapping,\n                             filter_already_liked_items=True):\n    \"\"\"\n    For a given user, generate the list of items that we can recommend, during this\n    step, we will also attach the recommender's score to each item.\n    \"\"\"\n    n_items = user_item.shape[1]\n    \n    # this is how implicit's matrix factorization generates\n    # the scores for each item for a given user, modify this\n    # part of the logic if we were to use a completely different\n    # algorithm to generate the ranked items\n    user_factor = model.user_factors[user_id]\n    scores = model.item_factors.dot(user_factor)\n\n    liked = set()\n    if filter_already_liked_items:\n        liked = set(user_item[user_id].indices)\n\n    item_ids = set(np.arange(n_items))\n    item_ids -= liked\n\n    items = []\n    for item_id in item_ids:\n        item = item_mapping[index2item[item_id]]\n        item.score = scores[item_id]\n        items.append(item)\n\n    return items\n```\n\n\n```python\nitems = generate_item_candidates(bpr, user_item_train, user_id, index2item, item_mapping)\nprint('number of item candidates:', len(items))\nitems[:5]\n```\n\n    number of item candidates: 20588\n\n\n\n\n\n    [Toy Story (1995),\n     Jumanji (1995),\n     Grumpier Old Men (1995),\n     Waiting to Exhale (1995),\n     Father of the Bride Part II (1995)]\n\n\n\n\n```python\ndef compute_utility(reco_items, interacted_distr, lmbda=0.5):\n    \"\"\"\n    Our objective function for computing the utility score for\n    the list of recommended items.\n\n    lmbda : float, 0.0 ~ 1.0, default 0.5\n        Lambda term controls the score and calibration tradeoff,\n        the higher the lambda the higher the resulting recommendation\n        will be calibrated. Lambda is keyword in Python, so it's\n        lmbda instead ^^\n    \"\"\"\n    reco_distr = compute_genre_distr(reco_items)\n    kl_div = compute_kl_divergence(interacted_distr, reco_distr)\n\n    total_score = 0.0\n    for item in reco_items:\n        total_score += item.score\n    \n    # kl divergence is the lower the better, while score is\n    # the higher the better so remember to negate it in the calculation\n    utility = (1 - lmbda) * total_score - lmbda * kl_div\n    return utility\n```\n\n\n```python\ndef calib_recommend(items, interacted_distr, topn, lmbda=0.5):\n    \"\"\"\n    start with an empty recommendation list,\n    loop over the topn cardinality, during each iteration\n    update the list with the item that maximizes the utility function.\n    \"\"\"\n    calib_reco = []\n    for _ in range(topn):\n        max_utility = -np.inf\n        for item in items:\n            if item in calib_reco:\n                continue\n\n            utility = compute_utility(calib_reco + [item], interacted_distr, lmbda)\n            if utility > max_utility:\n                max_utility = utility\n                best_item = item\n\n        calib_reco.append(best_item)\n        \n    return calib_reco\n```\n\n\n```python\nstart = time.time()\ncalib_reco_items = calib_recommend(items, interacted_distr, topn, lmbda=0.99)\nelapsed = time.time() - start\nprint('elapsed: ', elapsed)\ncalib_reco_items\n```\n\n    elapsed:  18.013550996780396\n\n\n\n\n\n    [Aelita: The Queen of Mars (Aelita) (1924),\n     Rubber (2010),\n     Valiant (2005),\n     Hellboy (2004),\n     Tai Chi Hero (2012),\n     Descent, The (2005),\n     Jason and the Argonauts (1963),\n     Happy New Year (2014),\n     Godzilla vs. Mothra (Mosura tai Gojira) (1964),\n     Picture of Dorian Gray, The (1945),\n     Lost Boys, The (1987),\n     Beastmaster, The (1982),\n     Enemy Mine (1985),\n     Hound of the Baskervilles, The (1959),\n     Highlander (1986),\n     Dracula (Bram Stoker's Dracula) (1992),\n     Last Starfighter, The (1984),\n     NeverEnding Story, The (1984),\n     Dune (2000),\n     Evil Dead II (Dead by Dawn) (1987)]\n\n\n\nIn the code chunk above, we turned the $\\lambda$ knob extremely high to generate the most calibrated recommendation list possible. Let's now compare the calibrated recommendation (which only optimizes for score, $s$), the original recommendation and the user's interaction distribution.\n\n\n```python\ncalib_reco_distr = compute_genre_distr(calib_reco_items)\ncalib_reco_kl_div = compute_kl_divergence(interacted_distr, calib_reco_distr)\nreco_kl_div = compute_kl_divergence(interacted_distr, reco_distr)\nprint('\\noriginal reco kl-divergence score:', reco_kl_div)\nprint('calibrated reco kl-divergence score:', calib_reco_kl_div)\n\ndistr_comparison_plot(interacted_distr, calib_reco_distr)\n```\n\nPrinting out the genre distribution from the calibrated recommendation list shows that this list covers more genre and its distribution closely resembles the distribution of the user's past historical interaction and our quantitative calibration metric, KL-divergence also confirms this. i.e. the calibrated recommendation's KL-divergence is lower than the original recommendation's score.\n \nThankfully from the results above, it seems that the re-ranked recommendation list that aims to maximize calibration score does in fact generate a more calibrated list. But the question is at what cost? Does other ranking metrics that recommender system often optimize for drop? Let's take a look at precision_at_k. Here the number for `k` is the `topn` parameter that we've defined earlier. i.e. the number of recommendations to generate for the user.\n\n\n```python\ndef precision(user_item, user_id, reco_items, index2item):\n    indptr = user_item.indptr\n    indices = user_item.indices\n\n    reco_ids = {item.id for item in reco_items}\n    likes = {index2item[indices[i]] for i in range(indptr[user_id], indptr[user_id + 1])}\n\n    relevant = len(reco_ids & likes)\n    total = min(len(reco_items), len(likes))\n    return relevant / total\n```\n\n\n```python\nreco_precision = precision(user_item_test, user_id, reco_items, index2item)\ncalib_reco_precision = precision(user_item_test, user_id, calib_reco_items, index2item)\nprint('original reco precision score:', reco_precision)\nprint('calibrated reco precision score:', calib_reco_precision)\n```\n\n    original reco precision score: 0.1875\n    calibrated reco precision score: 0.125\n\n\nWell ..., it's not a surprise that the calibrated recommendation list's precision score is a bit disappointing compared to the original recommendation. But let's see if we try a different value of $\\lambda$, this time turning it down a bit to strike a balance between calibration and precision.\n\n\n```python\nstart = time.time()\ncalib_reco_items = calib_recommend(items, interacted_distr, topn, lmbda=0.5)\nelapsed = time.time() - start\nprint('elapsed: ', elapsed)\ncalib_reco_items\n```\n\n    elapsed:  15.620396137237549\n\n\n\n\n\n    [Jason and the Argonauts (1963),\n     Lost Boys, The (1987),\n     Dune (2000),\n     Godzilla vs. Mothra (Mosura tai Gojira) (1964),\n     Dracula (Bram Stoker's Dracula) (1992),\n     Evil Dead, The (1981),\n     Evil Dead II (Dead by Dawn) (1987),\n     Hellraiser (1987),\n     Secret of NIMH, The (1982),\n     Ringu (Ring) (1998),\n     Beastmaster, The (1982),\n     Highlander (1986),\n     Flash Gordon (1980),\n     American Werewolf in London, An (1981),\n     Invasion of the Body Snatchers (1978),\n     Road Warrior, The (Mad Max 2) (1981),\n     Krull (1983),\n     Phenomena (a.k.a. Creepers) (1985),\n     Last Starfighter, The (1984),\n     Serpent and the Rainbow, The (1988)]\n\n\n\n\n```python\ncalib_reco_distr = compute_genre_distr(calib_reco_items)\ncalib_reco_kl_div = compute_kl_divergence(interacted_distr, calib_reco_distr)\ncalib_reco_precision = precision(user_item_test, user_id, calib_reco_items, index2item)\nprint('calibrated reco kl-divergence score:', calib_reco_kl_div)\nprint('calibrated reco precision score:', calib_reco_precision)\n```\n\n    calibrated reco kl-divergence score: 0.6256542329089019\n    calibrated reco precision score: 0.1875\n\n\n\n```python\ncalib_reco_distr = compute_genre_distr(calib_reco_items)\ndistr_comparison_plot(interacted_distr, calib_reco_distr)\n```\n\nWell, well, well. It turns out calibration can be improved considerably while accuracy is reduced only slightly if we find the sweet spot for the tuning parameter $\\lambda$.\n\nThe following code chunk curates all the code to generate the calibrated recommendation, the original recommendation and compare it with the user's historical interaction in one place for ease of tracking the flow. This process is outlined for 1 user, feel free to modify the code to perform this comparison across all users and due to the randomness in the recommendation algorithm, the results might differ across runs, but the underlying trend should remain the same.\n\n\n```python\ntopn = 20\nuser_id = 0\nlmbda = 0.99\n\nreco = bpr.recommend(user_id, user_item_train, N=topn)\nreco_items = [item_mapping[index2item[index]] for index, _ in reco]\nreco_distr = compute_genre_distr(reco_items)\n\ninteracted_ids = user_item_train[user_id].nonzero()[1]\ninteracted_items = [item_mapping[index2item[index]] for index in interacted_ids]\ninteracted_distr = compute_genre_distr(interacted_items)\n\nitems = generate_item_candidates(bpr, user_item_train, user_id, index2item, item_mapping)\ncalib_reco_items = calib_recommend(items, interacted_distr, topn, lmbda)\ncalib_reco_distr = compute_genre_distr(calib_reco_items)\n\ncalib_reco_kl_div = compute_kl_divergence(interacted_distr, calib_reco_distr)\ncalib_reco_precision = precision(user_item_test, user_id, calib_reco_items, index2item)\nprint('calibrated reco kl-divergence score:', calib_reco_kl_div)\nprint('calibrated reco precision score:', calib_reco_precision)\ndistr_comparison_plot(interacted_distr, calib_reco_distr)\n\nreco_kl_div = compute_kl_divergence(interacted_distr, reco_distr)\nreco_precision = precision(user_item_test, user_id, reco_items, index2item)\nprint('original reco kl-divergence score:', reco_kl_div)\nprint('original reco precision score:', reco_precision)\ndistr_comparison_plot(interacted_distr, reco_distr)\n```\n\n## End Note\n\nWe have calibrated our recommendation here based on movies' genre but the same idea can be applied if we wish to calibrate our recommendation based on some other traits that matters for the problem at hand.\n\nThe approach we took here is from a user-centric perspective, i.e. we are generating calibrated recommendations for each user, we can also tackle the problem from a item-centric perspective to see if items are recommended properly, e.g. if popular items just gets recommended a lot more times than other items.\n\nAlthough we used Bayesian Personalized Ranking to generated recommendations for each user, the technique that we used here to generated the calibrated ranked items for each user is independent of the recommendation algorithm we use. We're only using the algorithm here to demonstrate the process, so feel free is try this out on a recommendation algorithm of your liking/interest.\n\nThe discussion here focused on generating calibrated recommendation anchored on a user's past interaction. So if a user played 70% romance movies and 30% action movies, then when we say our recommendation is well-calibrated, that means the top ranked movies for the user should also consists of 70% romance movies and 30% action movies. We can, however, expand this work to recommend diversified items/movies. In other words, instead of limiting ourselves to only work with romance and action movies for a user that has only played movies falling under these two genres, we recommend movies from genres that are outside the user's historical play list.\n\nTo elaborate, we were using $p(g|u)$ to represent the user's historical genre interaction, we can extend that distribution to $\\tilde{p}(g|u)$, where:\n\n\\begin{align}\n\\tilde{p}(g|u) = \\beta \\cdot p_0(g) + (1 - \\beta) \\cdot p(g|u)\n\\end{align}\n\nHere $p_0(g)$ denote a prior distribution that takes positive values for all the genres $g$ in which we would like to promote diversity in the recommendation. Again we also have a tuning parameter $\\beta \\in [0, 1]$ to control how \"diversified\" we would like our recommendations to be. As to how we decide which genres to promote diversity for? Well, that's a topic for another day, but to start with we can use a uniform distribution across all genres or the average over all the users' genre distribution.\n\nAfter reading a lot of tutorials/papers that introduces new algorithms or new libraries/packages that boosts model performance in terms of ranking metric, coming across a paper on a different topic, calibrating recommendation, is a breath of fresh air. This sheds a new light on how I think about serving recommendations, so kudos to the original authors who brought this well-written paper to light. I encourage people to read the original paper if interested. [Paper: H. Steck - Calibrated Recommendation (2018)](https://dl.acm.org/citation.cfm?id=3240372)\n\n**Side Note:**\n\n- In the generating calibrated recommendation section, we introduced the maximum marginal relevance formula that has the knob for us to tune the balance between our original recommendation algorithm's score versus the calibration score. This \"balancing\" notion can actually be applied to many different areas. For example, In the original paper that introduced this idea, they were using this formula in the context of a search engine. To elaborate, when issuing a query on a search engine, the search engine often times assembles results that maximizes the relevance to the user query. By introducing the linear combination \"marginal relevance\" - a result is now said to have high marginal relevance if it is both relevant to the query and contains minimal similarity to previously selected results.\n- The Greedy Algorithm we leveraged to actually generate our top-N items that maximizes the maximum marginal relevance formula is a discrete optimization method that's often times referred to as a submodular optimization. Submodular optimization is a generic optimization method that can also be applied to other areas such as influence maximization and can be a topic by itself and is discussed lightly deeper in another notebook. [Notebook: Submodular Optimization & Influence Maximization](http://nbviewer.jupyter.org/github/ethen8181/machine-learning/blob/master/networkx/max_influence/max_influence.ipynb)\n\n# Reference\n\n- [Paper: H. Steck - Calibrated Recommendation (2018)](https://dl.acm.org/citation.cfm?id=3240372)\n- [Paper: J. Carbonell, J. Goldstein - The use of MMR, diversity-based reranking for\nreordering documents and producing summaries (1998)](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.188.3982&rep=rep1&type=pdf)\n", "meta": {"hexsha": "b1047797bfab65712e36e15265ba466c59a5fc25", "size": 459732, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "recsys/calibration/calibrated_reco.ipynb", "max_stars_repo_name": "certara-ShengnanHuang/machine-learning", "max_stars_repo_head_hexsha": "d21dfbeabf2876ffe49fcef444ca4516c4d36df0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2104, "max_stars_repo_stars_event_min_datetime": "2016-04-15T13:35:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T10:39:51.000Z", "max_issues_repo_path": "recsys/calibration/calibrated_reco.ipynb", "max_issues_repo_name": "certara-ShengnanHuang/machine-learning", "max_issues_repo_head_hexsha": "d21dfbeabf2876ffe49fcef444ca4516c4d36df0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-04-07T14:25:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-18T03:16:15.000Z", "max_forks_repo_path": "recsys/calibration/calibrated_reco.ipynb", "max_forks_repo_name": "certara-ShengnanHuang/machine-learning", "max_forks_repo_head_hexsha": "d21dfbeabf2876ffe49fcef444ca4516c4d36df0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 539, "max_forks_repo_forks_event_min_datetime": "2015-12-10T04:23:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:15:28.000Z", "avg_line_length": 229.866, "max_line_length": 80148, "alphanum_fraction": 0.8974467733, "converted": true, "num_tokens": 12056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.06371499291856339, "lm_q1q2_score": 0.02814119242824223}}
{"text": "# GSSR\nGene Splice Site Recognition by WAM, Bayesian Network and SVM approaches\n\n## Abstract\nxxx\n\n## Introduction\n\n### Gene splice site\n\nhttps://en.wikipedia.org/wiki/RNA_splicing\n\nRNA splicing, in molecular biology, is a form of RNA processing in which a newly made precursor messenger RNA (pre-mRNA) transcript is transformed into a mature messenger RNA (mRNA). During splicing, introns (Non-coding regions) are removed and exons (Coding Regions) are joined together. For nuclear-encoded genes, splicing takes place within the nucleus either during or immediately after transcription. For those eukaryotic genes that contain introns, splicing is usually required in order to create an mRNA molecule that can be translated into protein. For many eukaryotic introns, splicing is carried out in a series of reactions which are catalyzed by the spliceosome, a complex of small nuclear ribonucleo proteins (snRNPs). Self-splicing introns, or ribozymes capable of catalyzing their own excision from their parent RNA molecule, also exist.\n\n### Models\n\nhttps://academic.oup.com/bioinformatics/article-abstract/9/5/499/349215?redirectedFrom=PDF\n\nhttps://bmcbioinformatics.biomedcentral.com/articles/10.1186/1471-2105-9-477\n\nhttps://bmcbioinformatics.biomedcentral.com/articles/10.1186/1471-2105-8-S10-S7\n\nand others\n\n### Scikit-learn and Pgmpy\n\nintroductions of Scipy and Pgmpy\n\n## Material and Method\n\n### Environment\n\n\n```python\nimport warnings\nimport import_ipynb\nimport numpy as np\nimport pandas as pd\nimport networkx as nx\nfrom Utils import load_data\nfrom Models import WAM, BN, SVM\nfrom Evaluator import Evaluator\nfrom matplotlib import pyplot as plt\nfrom IPython.display import display, Markdown\n\nwarnings.filterwarnings(\"ignore\")\ntraining_set, testing_set = load_data()\n\n# https://www.it-swarm.dev/zh/python/%E5%A6%82%E4%BD%95%E4%BB%8E%E7%BB%88%E7%AB%AF%E8%BF%90%E8%A1%8Cipynb-jupyter%E7%AC%94%E8%AE%B0%E6%9C%AC%EF%BC%9F/823861554/\n\nn = 2500\ntraining_set = pd.concat( (training_set[training_set['IsDonor']==0].sample(n=n), \n                           training_set[training_set['IsDonor']==1].sample(n=n)), axis=0)\ntesting_set = pd.concat( (testing_set[testing_set['IsDonor']==0].sample(n=n), \n                          testing_set[testing_set['IsDonor']==1].sample(n=n)), axis=0)\n```\n\n    importing Jupyter notebook from Utils.ipynb\n    importing Jupyter notebook from Models.ipynb\n    importing Jupyter notebook from Evaluator.ipynb\n\n\n### Data curation\n\n### Encoding for features\n\nWhen encoding the sequence features to be numeric, a One-hot encoder were used. And to make the problem simpler, the ambiguous bases in sequences were disgarded. A simple example is that when deeling with sequence A, which can be represented as $acgtay^* aaccggttr^* y^* $, the ambiguous bases $y^*$ and $r^*$ are simply disgarded. So the sequence A becomes $acgtaaaccggtt$. And next, a One-hot encoder are used to encode sequence A to a numeric feature vector, which can be represented as $[1,0,0,0...0,0,0,1]$. In all of my experiments, I used 10 bases before and after the site to be tested, including its own sequence with a total length of 21.\n\n### Model implements\n\nThe 3 models are mainly implemented using Python. Besides, the Bayesian network model and Support vector machine were implemented based on Pgmpy and Scikit-learn pacakge. The 3 models are designed to be *[put into practical use]* as much as possible. They contain several very easy-to-use program interfaces: `fit`, `predict_probas`, `predict_scores` and `predict_classes`. For all 3 models, the `fit` method are used for training, and the other 3 `predict` methods are used for prediction. The `predict_probas` are used for predicting the probabilities each sample belonging to each class, the `predict_scores` are used for calculating the $S(X)$, and the `predict_classes` are used for predicting the classes each sample belongs, this is simply done by comparing the $S(X)$ and given threshold $T$. Most importantly, the $S(X)$ are calculated by:\n$$\\tag{1}S(X) = ln(\\frac{P^+ (X)}{P^- {X}})$$\n\n#### Stratagies for WAM to perform recognition\n\nWhen recoginizing Gene Splice Site, the 3 steps were mainly used to determine the potential of each sample being a splice site. Firstly, Laplace Pseudocounts are used to [...]. Secondly, the weights of positive and negative submodels, which are the frequencies of adjacent base pairs in WAM, are calculated using the following formula.\n$$\\tag{2} f(x) = \\frac{C_{x,p}+C_p}{N},x \\in [aa,ac,ag,...tt]$$ where $N$ is the total number of samples. $C_{x,p}$ is the total number of specific adjacent base pairs occuring at position $p-l+1...p$ in all samples. $C_p$ is the pseudocount, and $l$ is the length of array considered, which refers to the range of dependence between adjacent base pairs considered in experiments. And finally, the potential of new samples being a donor site can be easily calculated by\n$$\\tag{3} S(X) = ln(\\frac{P^+(X)}{P^-(X)}) = \\sum_{x=2}^{L}{ln(\\frac{f^+(x)}{f^-(x)})}$$\nwhere $L$ is the length of input sequence.\nMost importantly, $l$ and $C_p$ are set to $2$ and $0.5$ respectively. \n\n#### Stratagies for BN to learn structures and parameters from data\n\nThe min max hill climb (MMHC) algorithm *[REF]* were mainly used to learn BN structures from the training data. MMHC algorithm is a constrained-based learning algorithm, firstly be proposed by *[AUTHOR]*. *[ details of MMHC algorithm]*\n\n#### Settings for SVM to classify splice sites\n\nIn the experiment, Gaussian Kernel function (see below) were used to map vectors to higher-dimensional feature space. The \u60e9\u7f5a\u7cfb\u6570 $C$ are used to .... And the key parameter $\\gamma$ for Gaussian Kernel are set to [real gamma].\n$$\\tag{4}K(x_i, x_j) = exp(-\\gamma||x_i - x_j||^2), \\gamma > 0$$\n\n\n```python\nclass Model:\n    \n    def __init__(self):\n        self.wam = WAM()\n        self.bn = BN()\n        self.svm = SVM(kernel='rbf', gamma='scale', random_state=1, probability=True, verbose=True)\n        \nmodel = Model()\n```\n\n### Evaluation\n\nTo visualize and compare classification results of 3 models, the ROC Curves and Sn-Sp Curves are plotted using matplotlib package. To realize this, a sample-based benchmarking method is introduced.\n\n$$ \n\\begin{align} \nTP_t = \\sum_{i\\in S_{TP,t}} 1, \\quad S_{TP,t}& =\\{i\\mid S_i\\geq t \\land L_i = 1\\} \\tag{} \\\\\nFP_t = \\sum_{i\\in S_{FP,t}} 1, \\quad S_{FP,t}& =\\{i\\mid S_i\\geq t \\land L_i = 0\\} \\tag{} \\\\\nTN_t = \\sum_{i\\in S_{TN,t}} 1, \\quad S_{TN,t}& =\\{i\\mid S_i< t \\land L_i = 0\\} \\tag{} \\\\\nFN_t = \\sum_{i\\in S_{FN,t}} 1, \\quad S_{FN,t}& =\\{i\\mid S_i< t \\land L_i = 1\\} \\tag{} \\\\\n\\end{align}\n$$\n$$\n\\begin{align} \nTPR_t & = \\frac{TP_t}{TP_t+FN_t} \\tag{} \\\\\nFPR_t & = \\frac{FP_t}{FP_t+TN_t} \\tag{} \\\\\nSn_t & = \\frac{TP_t}{TP_t+FN_t} \\tag{} \\\\\nSp_t & = \\frac{TN_t}{TN_t+FP_t} \\tag{} \\\\\n\\end{align}\n$$\n\nwhere $ $ is ...... Finally, the ROC_AUC ( area under the ROC curve) were calculated using Composite Trapezoidal rule [ref]\n\n$$\nAUC = \\sum_{i=1}^N \\frac{(FPR_{i+1} - FPR_i)(TPR_i+TPR_{i+1})}{2} \\tag{} \\\\\n$$\n\nhttps://github.com/scikit-learn/scikit-learn/blob/fd237278e/sklearn/metrics/_ranking.py#L42\n\nhttps://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.trapz.html\n\nhttps://github.com/numpy/numpy/blob/v1.16.2/numpy/lib/function_base.py#L3982-L4070\n\n\n## Result and Discussion\n\n### Weights for WAM\n\n\n```python\n#display(training_set)\nmodel.wam.fit(training_set['Seq. features'], training_set['IsDonor'])\npd.set_option('display.max_columns', None)\np_rename = lambda x: 'P.{}'.format(x)\nn_rename = lambda x: 'N.{}'.format(x)\n```\n\n\n```python\ndisplay(Markdown( '<h3 align=\"center\">Weights for Weighted array model (Positive / Negative)</h3>' ))\nmodel.wam.positive_weights.applymap(lambda x: '%.3f'%x) + '/' + \\\nmodel.wam.negative_weights.applymap(lambda x: '%.3f'%x)\n```\n\n\n<h3 align=\"center\">Weights for Weighted array model (Positive / Negative)</h3>\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>AA</th>\n      <th>AC</th>\n      <th>AG</th>\n      <th>AT</th>\n      <th>CA</th>\n      <th>CC</th>\n      <th>CG</th>\n      <th>CT</th>\n      <th>GA</th>\n      <th>GC</th>\n      <th>GG</th>\n      <th>GT</th>\n      <th>TA</th>\n      <th>TC</th>\n      <th>TG</th>\n      <th>TT</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n      <td>nan/nan</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.055/0.070</td>\n      <td>0.049/0.050</td>\n      <td>0.031/0.051</td>\n      <td>0.063/0.054</td>\n      <td>0.086/0.045</td>\n      <td>0.117/0.069</td>\n      <td>0.056/0.047</td>\n      <td>0.059/0.045</td>\n      <td>0.068/0.052</td>\n      <td>0.069/0.053</td>\n      <td>0.046/0.066</td>\n      <td>0.036/0.061</td>\n      <td>0.034/0.048</td>\n      <td>0.067/0.056</td>\n      <td>0.043/0.047</td>\n      <td>0.076/0.078</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.095/0.047</td>\n      <td>0.076/0.053</td>\n      <td>0.037/0.058</td>\n      <td>0.074/0.052</td>\n      <td>0.067/0.061</td>\n      <td>0.070/0.056</td>\n      <td>0.072/0.060</td>\n      <td>0.075/0.057</td>\n      <td>0.058/0.052</td>\n      <td>0.072/0.053</td>\n      <td>0.027/0.055</td>\n      <td>0.020/0.053</td>\n      <td>0.057/0.063</td>\n      <td>0.067/0.064</td>\n      <td>0.044/0.062</td>\n      <td>0.062/0.040</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.035/0.052</td>\n      <td>0.137/0.057</td>\n      <td>0.051/0.053</td>\n      <td>0.078/0.065</td>\n      <td>0.063/0.051</td>\n      <td>0.087/0.062</td>\n      <td>0.066/0.060</td>\n      <td>0.082/0.055</td>\n      <td>0.049/0.051</td>\n      <td>0.071/0.062</td>\n      <td>0.034/0.065</td>\n      <td>0.020/0.053</td>\n      <td>0.032/0.053</td>\n      <td>0.066/0.052</td>\n      <td>0.045/0.050</td>\n      <td>0.056/0.055</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>0.043/0.048</td>\n      <td>0.066/0.054</td>\n      <td>0.033/0.053</td>\n      <td>0.058/0.050</td>\n      <td>0.072/0.061</td>\n      <td>0.088/0.055</td>\n      <td>0.078/0.061</td>\n      <td>0.113/0.057</td>\n      <td>0.059/0.055</td>\n      <td>0.060/0.063</td>\n      <td>0.040/0.058</td>\n      <td>0.031/0.051</td>\n      <td>0.029/0.054</td>\n      <td>0.074/0.053</td>\n      <td>0.060/0.054</td>\n      <td>0.049/0.062</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>0.063/0.058</td>\n      <td>0.056/0.062</td>\n      <td>0.033/0.048</td>\n      <td>0.079/0.055</td>\n      <td>0.090/0.057</td>\n      <td>0.061/0.057</td>\n      <td>0.062/0.063</td>\n      <td>0.068/0.059</td>\n      <td>0.055/0.055</td>\n      <td>0.078/0.051</td>\n      <td>0.045/0.051</td>\n      <td>0.021/0.059</td>\n      <td>0.031/0.057</td>\n      <td>0.066/0.060</td>\n      <td>0.042/0.058</td>\n      <td>0.142/0.047</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>0.041/0.058</td>\n      <td>0.121/0.052</td>\n      <td>0.044/0.054</td>\n      <td>0.060/0.061</td>\n      <td>0.079/0.053</td>\n      <td>0.086/0.058</td>\n      <td>0.050/0.055</td>\n      <td>0.051/0.061</td>\n      <td>0.049/0.058</td>\n      <td>0.074/0.054</td>\n      <td>0.029/0.047</td>\n      <td>0.020/0.059</td>\n      <td>0.038/0.054</td>\n      <td>0.126/0.050</td>\n      <td>0.055/0.056</td>\n      <td>0.042/0.057</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>0.049/0.057</td>\n      <td>0.089/0.060</td>\n      <td>0.030/0.053</td>\n      <td>0.078/0.055</td>\n      <td>0.102/0.067</td>\n      <td>0.064/0.052</td>\n      <td>0.038/0.037</td>\n      <td>0.135/0.048</td>\n      <td>0.054/0.058</td>\n      <td>0.084/0.051</td>\n      <td>0.020/0.045</td>\n      <td>0.041/0.056</td>\n      <td>0.019/0.066</td>\n      <td>0.068/0.058</td>\n      <td>0.026/0.059</td>\n      <td>0.062/0.055</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>0.119/0.051</td>\n      <td>0.031/0.057</td>\n      <td>0.024/0.074</td>\n      <td>0.053/0.062</td>\n      <td>0.168/0.058</td>\n      <td>0.035/0.051</td>\n      <td>0.048/0.045</td>\n      <td>0.035/0.059</td>\n      <td>0.073/0.051</td>\n      <td>0.025/0.051</td>\n      <td>0.009/0.063</td>\n      <td>0.008/0.040</td>\n      <td>0.135/0.048</td>\n      <td>0.027/0.058</td>\n      <td>0.078/0.054</td>\n      <td>0.038/0.052</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>0.086/0.051</td>\n      <td>0.008/0.053</td>\n      <td>0.220/0.050</td>\n      <td>0.041/0.055</td>\n      <td>0.014/0.050</td>\n      <td>0.005/0.054</td>\n      <td>0.154/0.063</td>\n      <td>0.016/0.059</td>\n      <td>0.078/0.060</td>\n      <td>0.002/0.056</td>\n      <td>0.052/0.060</td>\n      <td>0.005/0.069</td>\n      <td>0.003/0.054</td>\n      <td>0.005/0.054</td>\n      <td>0.059/0.054</td>\n      <td>0.006/0.055</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>0.024/0.054</td>\n      <td>0.026/0.051</td>\n      <td>0.076/0.055</td>\n      <td>0.033/0.059</td>\n      <td>0.000/0.057</td>\n      <td>0.000/0.047</td>\n      <td>0.050/0.058</td>\n      <td>0.000/0.056</td>\n      <td>0.012/0.061</td>\n      <td>0.008/0.049</td>\n      <td>0.423/0.052</td>\n      <td>0.003/0.059</td>\n      <td>0.000/0.056</td>\n      <td>0.000/0.060</td>\n      <td>0.042/0.063</td>\n      <td>0.000/0.050</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>0.006/0.055</td>\n      <td>0.018/0.063</td>\n      <td>0.010/0.055</td>\n      <td>0.019/0.053</td>\n      <td>0.006/0.052</td>\n      <td>0.010/0.055</td>\n      <td>0.004/0.055</td>\n      <td>0.011/0.050</td>\n      <td>0.014/0.053</td>\n      <td>0.035/0.063</td>\n      <td>0.013/0.055</td>\n      <td>0.473/0.057</td>\n      <td>0.005/0.058</td>\n      <td>0.003/0.054</td>\n      <td>0.007/0.056</td>\n      <td>0.013/0.057</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>0.007/0.057</td>\n      <td>0.015/0.057</td>\n      <td>0.006/0.052</td>\n      <td>0.017/0.052</td>\n      <td>0.009/0.056</td>\n      <td>0.022/0.062</td>\n      <td>0.016/0.064</td>\n      <td>0.022/0.057</td>\n      <td>0.011/0.053</td>\n      <td>0.015/0.062</td>\n      <td>0.008/0.055</td>\n      <td>0.007/0.054</td>\n      <td>0.403/0.057</td>\n      <td>0.044/0.050</td>\n      <td>0.219/0.056</td>\n      <td>0.058/0.051</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>0.238/0.058</td>\n      <td>0.060/0.050</td>\n      <td>0.030/0.057</td>\n      <td>0.083/0.056</td>\n      <td>0.024/0.061</td>\n      <td>0.021/0.053</td>\n      <td>0.018/0.053</td>\n      <td>0.023/0.061</td>\n      <td>0.208/0.059</td>\n      <td>0.044/0.055</td>\n      <td>0.025/0.053</td>\n      <td>0.012/0.051</td>\n      <td>0.020/0.050</td>\n      <td>0.027/0.048</td>\n      <td>0.017/0.057</td>\n      <td>0.014/0.061</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>0.012/0.065</td>\n      <td>0.029/0.059</td>\n      <td>0.265/0.053</td>\n      <td>0.042/0.051</td>\n      <td>0.026/0.053</td>\n      <td>0.054/0.045</td>\n      <td>0.092/0.065</td>\n      <td>0.031/0.054</td>\n      <td>0.012/0.060</td>\n      <td>0.015/0.054</td>\n      <td>0.045/0.057</td>\n      <td>0.008/0.053</td>\n      <td>0.009/0.059</td>\n      <td>0.037/0.054</td>\n      <td>0.044/0.061</td>\n      <td>0.019/0.053</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>0.014/0.062</td>\n      <td>0.027/0.056</td>\n      <td>0.016/0.060</td>\n      <td>0.032/0.058</td>\n      <td>0.025/0.054</td>\n      <td>0.029/0.055</td>\n      <td>0.019/0.055</td>\n      <td>0.038/0.052</td>\n      <td>0.076/0.056</td>\n      <td>0.129/0.052</td>\n      <td>0.069/0.060</td>\n      <td>0.220/0.057</td>\n      <td>0.011/0.053</td>\n      <td>0.026/0.055</td>\n      <td>0.019/0.057</td>\n      <td>0.034/0.049</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>0.035/0.050</td>\n      <td>0.044/0.057</td>\n      <td>0.029/0.059</td>\n      <td>0.036/0.053</td>\n      <td>0.055/0.056</td>\n      <td>0.065/0.051</td>\n      <td>0.057/0.049</td>\n      <td>0.061/0.057</td>\n      <td>0.035/0.050</td>\n      <td>0.055/0.059</td>\n      <td>0.017/0.063</td>\n      <td>0.018/0.064</td>\n      <td>0.106/0.049</td>\n      <td>0.114/0.055</td>\n      <td>0.104/0.050</td>\n      <td>0.154/0.063</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>0.042/0.047</td>\n      <td>0.086/0.052</td>\n      <td>0.033/0.056</td>\n      <td>0.097/0.056</td>\n      <td>0.043/0.054</td>\n      <td>0.087/0.051</td>\n      <td>0.044/0.054</td>\n      <td>0.086/0.058</td>\n      <td>0.051/0.060</td>\n      <td>0.082/0.061</td>\n      <td>0.062/0.047</td>\n      <td>0.036/0.057</td>\n      <td>0.030/0.068</td>\n      <td>0.077/0.061</td>\n      <td>0.040/0.050</td>\n      <td>0.069/0.056</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>0.036/0.059</td>\n      <td>0.062/0.058</td>\n      <td>0.032/0.059</td>\n      <td>0.057/0.053</td>\n      <td>0.071/0.054</td>\n      <td>0.099/0.066</td>\n      <td>0.074/0.057</td>\n      <td>0.092/0.054</td>\n      <td>0.036/0.056</td>\n      <td>0.082/0.053</td>\n      <td>0.037/0.048</td>\n      <td>0.022/0.046</td>\n      <td>0.039/0.053</td>\n      <td>0.106/0.060</td>\n      <td>0.055/0.056</td>\n      <td>0.104/0.058</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nscores_wam = model.wam.predict_scores(testing_set['Seq. features'].apply(str.upper))\n```\n\n### Graph for BN\n\n\n```python\nmodel.bn.fit(data=to_format_arr(training_set['Seq. features']),\n             label=training_set['IsDonor'].astype(int), \n             sign_level=0.01)\n```\n\n    Performing structure learning, using estimator: `<class 'pgmpy.estimators.MmhcEstimator.MmhcEstimator'>`\n    Done !\n    Performing parameter learning, using estimator: `<class 'pgmpy.estimators.BayesianEstimator.BayesianEstimator'>`\n\n\n\n```python\nplt.figure(figsize=(4,4), dpi=120)\nG = model.bn.networks\nbicolors = ['deepskyblue','salmon']\nnodesize = np.array([float(G.degree(v) + 1) for v in G])\nnodecolor = np.array([bicolors[int('label' in i)] for i in G])\nnx.draw(G, with_labels=True, textsize=10000, pos=nx.spring_layout(G), node_size=nodesize*150,\n        node_color=nodecolor)\n```\n\n\n```python\ndata = to_format_arr(testing_set['Seq. features'])\ntest_data = pd.DataFrame(data, columns=['F{}'.format(i) for i in range(data.shape[1])])\nscores_bn = model.bn.predict_scores(test_data)\n```\n\n### Graph for SVM\n\n\n```python\nmodel.svm.fit(to_format_arr(training_set['Num. features']), training_set['IsDonor'])\nscores_svm = model.svm.predict_scores(to_format_arr(testing_set['Num. features']))\n```\n\n    [LibSVM]\n\n\n```python\narr = to_format_arr(training_set['Num. features'])\nprint(arr.shape)\narr\n```\n\n    (5000, 80)\n\n\n\n\n\n    array([[0, 0, 0, ..., 1, 0, 0],\n           [0, 1, 0, ..., 0, 0, 0],\n           [0, 0, 0, ..., 0, 1, 0],\n           ...,\n           [0, 0, 1, ..., 1, 0, 0],\n           [0, 0, 1, ..., 0, 0, 1],\n           [0, 0, 1, ..., 1, 0, 0]])\n\n\n\n### Performance\n- Table\n- ROC Sn-Sp Curves\n\n\n```python\nevaltr = Evaluator(labels=testing_set['IsDonor'], \n                  wam_scores=scores_wam, \n                  bn_scores=scores_bn, \n                  svm_scores=scores_svm)\n\ndisplay(evaltr.Cal_Sn_Sp(evaltr.Confusion_table(T_range=np.arange(0, 10, 0.1))['wam_scores']).round(2).T)\ndisplay(evaltr.Cal_Tpr_Fpr(evaltr.Confusion_table(T_range=np.arange(0, 10, 0.1))['wam_scores']).round(2).T)\n```\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>0</th>\n      <th>1</th>\n      <th>2</th>\n      <th>3</th>\n      <th>4</th>\n      <th>5</th>\n      <th>6</th>\n      <th>7</th>\n      <th>8</th>\n      <th>9</th>\n      <th>10</th>\n      <th>11</th>\n      <th>12</th>\n      <th>13</th>\n      <th>14</th>\n      <th>15</th>\n      <th>16</th>\n      <th>17</th>\n      <th>18</th>\n      <th>19</th>\n      <th>20</th>\n      <th>21</th>\n      <th>22</th>\n      <th>23</th>\n      <th>24</th>\n      <th>25</th>\n      <th>26</th>\n      <th>27</th>\n      <th>28</th>\n      <th>29</th>\n      <th>30</th>\n      <th>31</th>\n      <th>32</th>\n      <th>33</th>\n      <th>34</th>\n      <th>35</th>\n      <th>36</th>\n      <th>37</th>\n      <th>38</th>\n      <th>39</th>\n      <th>40</th>\n      <th>41</th>\n      <th>42</th>\n      <th>43</th>\n      <th>44</th>\n      <th>45</th>\n      <th>46</th>\n      <th>47</th>\n      <th>48</th>\n      <th>49</th>\n      <th>50</th>\n      <th>51</th>\n      <th>52</th>\n      <th>53</th>\n      <th>54</th>\n      <th>55</th>\n      <th>56</th>\n      <th>57</th>\n      <th>58</th>\n      <th>59</th>\n      <th>60</th>\n      <th>61</th>\n      <th>62</th>\n      <th>63</th>\n      <th>64</th>\n      <th>65</th>\n      <th>66</th>\n      <th>67</th>\n      <th>68</th>\n      <th>69</th>\n      <th>70</th>\n      <th>71</th>\n      <th>72</th>\n      <th>73</th>\n      <th>74</th>\n      <th>75</th>\n      <th>76</th>\n      <th>77</th>\n      <th>78</th>\n      <th>79</th>\n      <th>80</th>\n      <th>81</th>\n      <th>82</th>\n      <th>83</th>\n      <th>84</th>\n      <th>85</th>\n      <th>86</th>\n      <th>87</th>\n      <th>88</th>\n      <th>89</th>\n      <th>90</th>\n      <th>91</th>\n      <th>92</th>\n      <th>93</th>\n      <th>94</th>\n      <th>95</th>\n      <th>96</th>\n      <th>97</th>\n      <th>98</th>\n      <th>99</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Threshold</th>\n      <td>0.00</td>\n      <td>0.10</td>\n      <td>0.20</td>\n      <td>0.30</td>\n      <td>0.40</td>\n      <td>0.50</td>\n      <td>0.60</td>\n      <td>0.70</td>\n      <td>0.80</td>\n      <td>0.90</td>\n      <td>1.00</td>\n      <td>1.10</td>\n      <td>1.20</td>\n      <td>1.30</td>\n      <td>1.40</td>\n      <td>1.50</td>\n      <td>1.60</td>\n      <td>1.70</td>\n      <td>1.80</td>\n      <td>1.90</td>\n      <td>2.00</td>\n      <td>2.10</td>\n      <td>2.20</td>\n      <td>2.30</td>\n      <td>2.40</td>\n      <td>2.50</td>\n      <td>2.60</td>\n      <td>2.70</td>\n      <td>2.80</td>\n      <td>2.90</td>\n      <td>3.00</td>\n      <td>3.10</td>\n      <td>3.20</td>\n      <td>3.30</td>\n      <td>3.40</td>\n      <td>3.50</td>\n      <td>3.60</td>\n      <td>3.70</td>\n      <td>3.80</td>\n      <td>3.90</td>\n      <td>4.00</td>\n      <td>4.10</td>\n      <td>4.20</td>\n      <td>4.30</td>\n      <td>4.40</td>\n      <td>4.50</td>\n      <td>4.60</td>\n      <td>4.70</td>\n      <td>4.80</td>\n      <td>4.90</td>\n      <td>5.00</td>\n      <td>5.10</td>\n      <td>5.20</td>\n      <td>5.30</td>\n      <td>5.40</td>\n      <td>5.50</td>\n      <td>5.60</td>\n      <td>5.70</td>\n      <td>5.8</td>\n      <td>5.9</td>\n      <td>6.0</td>\n      <td>6.10</td>\n      <td>6.20</td>\n      <td>6.30</td>\n      <td>6.40</td>\n      <td>6.50</td>\n      <td>6.60</td>\n      <td>6.70</td>\n      <td>6.80</td>\n      <td>6.90</td>\n      <td>7.00</td>\n      <td>7.10</td>\n      <td>7.20</td>\n      <td>7.30</td>\n      <td>7.40</td>\n      <td>7.5</td>\n      <td>7.60</td>\n      <td>7.70</td>\n      <td>7.80</td>\n      <td>7.90</td>\n      <td>8.00</td>\n      <td>8.10</td>\n      <td>8.20</td>\n      <td>8.30</td>\n      <td>8.40</td>\n      <td>8.50</td>\n      <td>8.6</td>\n      <td>8.70</td>\n      <td>8.80</td>\n      <td>8.90</td>\n      <td>9.00</td>\n      <td>9.10</td>\n      <td>9.20</td>\n      <td>9.30</td>\n      <td>9.40</td>\n      <td>9.50</td>\n      <td>9.6</td>\n      <td>9.70</td>\n      <td>9.80</td>\n      <td>9.90</td>\n    </tr>\n    <tr>\n      <th>Sensitivity</th>\n      <td>0.85</td>\n      <td>0.85</td>\n      <td>0.85</td>\n      <td>0.85</td>\n      <td>0.84</td>\n      <td>0.84</td>\n      <td>0.84</td>\n      <td>0.84</td>\n      <td>0.84</td>\n      <td>0.84</td>\n      <td>0.84</td>\n      <td>0.83</td>\n      <td>0.83</td>\n      <td>0.83</td>\n      <td>0.83</td>\n      <td>0.83</td>\n      <td>0.82</td>\n      <td>0.82</td>\n      <td>0.82</td>\n      <td>0.82</td>\n      <td>0.82</td>\n      <td>0.82</td>\n      <td>0.82</td>\n      <td>0.82</td>\n      <td>0.81</td>\n      <td>0.81</td>\n      <td>0.81</td>\n      <td>0.81</td>\n      <td>0.81</td>\n      <td>0.81</td>\n      <td>0.81</td>\n      <td>0.81</td>\n      <td>0.80</td>\n      <td>0.80</td>\n      <td>0.80</td>\n      <td>0.80</td>\n      <td>0.79</td>\n      <td>0.79</td>\n      <td>0.79</td>\n      <td>0.79</td>\n      <td>0.79</td>\n      <td>0.78</td>\n      <td>0.77</td>\n      <td>0.77</td>\n      <td>0.77</td>\n      <td>0.77</td>\n      <td>0.76</td>\n      <td>0.76</td>\n      <td>0.75</td>\n      <td>0.75</td>\n      <td>0.75</td>\n      <td>0.74</td>\n      <td>0.73</td>\n      <td>0.73</td>\n      <td>0.72</td>\n      <td>0.72</td>\n      <td>0.71</td>\n      <td>0.71</td>\n      <td>0.7</td>\n      <td>0.7</td>\n      <td>0.7</td>\n      <td>0.69</td>\n      <td>0.69</td>\n      <td>0.68</td>\n      <td>0.68</td>\n      <td>0.67</td>\n      <td>0.67</td>\n      <td>0.66</td>\n      <td>0.65</td>\n      <td>0.65</td>\n      <td>0.64</td>\n      <td>0.64</td>\n      <td>0.62</td>\n      <td>0.62</td>\n      <td>0.61</td>\n      <td>0.6</td>\n      <td>0.59</td>\n      <td>0.59</td>\n      <td>0.58</td>\n      <td>0.57</td>\n      <td>0.56</td>\n      <td>0.55</td>\n      <td>0.54</td>\n      <td>0.53</td>\n      <td>0.52</td>\n      <td>0.51</td>\n      <td>0.5</td>\n      <td>0.49</td>\n      <td>0.48</td>\n      <td>0.47</td>\n      <td>0.47</td>\n      <td>0.46</td>\n      <td>0.45</td>\n      <td>0.44</td>\n      <td>0.43</td>\n      <td>0.41</td>\n      <td>0.4</td>\n      <td>0.39</td>\n      <td>0.38</td>\n      <td>0.36</td>\n    </tr>\n    <tr>\n      <th>Specificity</th>\n      <td>0.94</td>\n      <td>0.94</td>\n      <td>0.95</td>\n      <td>0.95</td>\n      <td>0.95</td>\n      <td>0.95</td>\n      <td>0.95</td>\n      <td>0.95</td>\n      <td>0.96</td>\n      <td>0.96</td>\n      <td>0.96</td>\n      <td>0.96</td>\n      <td>0.96</td>\n      <td>0.96</td>\n      <td>0.96</td>\n      <td>0.97</td>\n      <td>0.97</td>\n      <td>0.97</td>\n      <td>0.97</td>\n      <td>0.97</td>\n      <td>0.97</td>\n      <td>0.97</td>\n      <td>0.97</td>\n      <td>0.98</td>\n      <td>0.98</td>\n      <td>0.98</td>\n      <td>0.98</td>\n      <td>0.98</td>\n      <td>0.98</td>\n      <td>0.98</td>\n      <td>0.98</td>\n      <td>0.98</td>\n      <td>0.98</td>\n      <td>0.98</td>\n      <td>0.98</td>\n      <td>0.98</td>\n      <td>0.98</td>\n      <td>0.99</td>\n      <td>0.99</td>\n      <td>0.99</td>\n      <td>0.99</td>\n      <td>0.99</td>\n      <td>0.99</td>\n      <td>0.99</td>\n      <td>0.99</td>\n      <td>0.99</td>\n      <td>0.99</td>\n      <td>0.99</td>\n      <td>0.99</td>\n      <td>0.99</td>\n      <td>0.99</td>\n      <td>0.99</td>\n      <td>0.99</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.0</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.0</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.0</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>0</th>\n      <th>1</th>\n      <th>2</th>\n      <th>3</th>\n      <th>4</th>\n      <th>5</th>\n      <th>6</th>\n      <th>7</th>\n      <th>8</th>\n      <th>9</th>\n      <th>10</th>\n      <th>11</th>\n      <th>12</th>\n      <th>13</th>\n      <th>14</th>\n      <th>15</th>\n      <th>16</th>\n      <th>17</th>\n      <th>18</th>\n      <th>19</th>\n      <th>20</th>\n      <th>21</th>\n      <th>22</th>\n      <th>23</th>\n      <th>24</th>\n      <th>25</th>\n      <th>26</th>\n      <th>27</th>\n      <th>28</th>\n      <th>29</th>\n      <th>30</th>\n      <th>31</th>\n      <th>32</th>\n      <th>33</th>\n      <th>34</th>\n      <th>35</th>\n      <th>36</th>\n      <th>37</th>\n      <th>38</th>\n      <th>39</th>\n      <th>40</th>\n      <th>41</th>\n      <th>42</th>\n      <th>43</th>\n      <th>44</th>\n      <th>45</th>\n      <th>46</th>\n      <th>47</th>\n      <th>48</th>\n      <th>49</th>\n      <th>50</th>\n      <th>51</th>\n      <th>52</th>\n      <th>53</th>\n      <th>54</th>\n      <th>55</th>\n      <th>56</th>\n      <th>57</th>\n      <th>58</th>\n      <th>59</th>\n      <th>60</th>\n      <th>61</th>\n      <th>62</th>\n      <th>63</th>\n      <th>64</th>\n      <th>65</th>\n      <th>66</th>\n      <th>67</th>\n      <th>68</th>\n      <th>69</th>\n      <th>70</th>\n      <th>71</th>\n      <th>72</th>\n      <th>73</th>\n      <th>74</th>\n      <th>75</th>\n      <th>76</th>\n      <th>77</th>\n      <th>78</th>\n      <th>79</th>\n      <th>80</th>\n      <th>81</th>\n      <th>82</th>\n      <th>83</th>\n      <th>84</th>\n      <th>85</th>\n      <th>86</th>\n      <th>87</th>\n      <th>88</th>\n      <th>89</th>\n      <th>90</th>\n      <th>91</th>\n      <th>92</th>\n      <th>93</th>\n      <th>94</th>\n      <th>95</th>\n      <th>96</th>\n      <th>97</th>\n      <th>98</th>\n      <th>99</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Threshold</th>\n      <td>0.00</td>\n      <td>0.10</td>\n      <td>0.20</td>\n      <td>0.30</td>\n      <td>0.40</td>\n      <td>0.50</td>\n      <td>0.60</td>\n      <td>0.70</td>\n      <td>0.80</td>\n      <td>0.90</td>\n      <td>1.00</td>\n      <td>1.10</td>\n      <td>1.20</td>\n      <td>1.30</td>\n      <td>1.40</td>\n      <td>1.50</td>\n      <td>1.60</td>\n      <td>1.70</td>\n      <td>1.80</td>\n      <td>1.90</td>\n      <td>2.00</td>\n      <td>2.10</td>\n      <td>2.20</td>\n      <td>2.30</td>\n      <td>2.40</td>\n      <td>2.50</td>\n      <td>2.60</td>\n      <td>2.70</td>\n      <td>2.80</td>\n      <td>2.90</td>\n      <td>3.00</td>\n      <td>3.10</td>\n      <td>3.20</td>\n      <td>3.30</td>\n      <td>3.40</td>\n      <td>3.50</td>\n      <td>3.60</td>\n      <td>3.70</td>\n      <td>3.80</td>\n      <td>3.90</td>\n      <td>4.00</td>\n      <td>4.10</td>\n      <td>4.20</td>\n      <td>4.30</td>\n      <td>4.40</td>\n      <td>4.50</td>\n      <td>4.60</td>\n      <td>4.70</td>\n      <td>4.80</td>\n      <td>4.90</td>\n      <td>5.00</td>\n      <td>5.10</td>\n      <td>5.20</td>\n      <td>5.30</td>\n      <td>5.40</td>\n      <td>5.50</td>\n      <td>5.60</td>\n      <td>5.70</td>\n      <td>5.8</td>\n      <td>5.9</td>\n      <td>6.0</td>\n      <td>6.10</td>\n      <td>6.20</td>\n      <td>6.30</td>\n      <td>6.40</td>\n      <td>6.50</td>\n      <td>6.60</td>\n      <td>6.70</td>\n      <td>6.80</td>\n      <td>6.90</td>\n      <td>7.00</td>\n      <td>7.10</td>\n      <td>7.20</td>\n      <td>7.30</td>\n      <td>7.40</td>\n      <td>7.5</td>\n      <td>7.60</td>\n      <td>7.70</td>\n      <td>7.80</td>\n      <td>7.90</td>\n      <td>8.00</td>\n      <td>8.10</td>\n      <td>8.20</td>\n      <td>8.30</td>\n      <td>8.40</td>\n      <td>8.50</td>\n      <td>8.6</td>\n      <td>8.70</td>\n      <td>8.80</td>\n      <td>8.90</td>\n      <td>9.00</td>\n      <td>9.10</td>\n      <td>9.20</td>\n      <td>9.30</td>\n      <td>9.40</td>\n      <td>9.50</td>\n      <td>9.6</td>\n      <td>9.70</td>\n      <td>9.80</td>\n      <td>9.90</td>\n    </tr>\n    <tr>\n      <th>Tpr</th>\n      <td>0.85</td>\n      <td>0.85</td>\n      <td>0.85</td>\n      <td>0.85</td>\n      <td>0.84</td>\n      <td>0.84</td>\n      <td>0.84</td>\n      <td>0.84</td>\n      <td>0.84</td>\n      <td>0.84</td>\n      <td>0.84</td>\n      <td>0.83</td>\n      <td>0.83</td>\n      <td>0.83</td>\n      <td>0.83</td>\n      <td>0.83</td>\n      <td>0.82</td>\n      <td>0.82</td>\n      <td>0.82</td>\n      <td>0.82</td>\n      <td>0.82</td>\n      <td>0.82</td>\n      <td>0.82</td>\n      <td>0.82</td>\n      <td>0.81</td>\n      <td>0.81</td>\n      <td>0.81</td>\n      <td>0.81</td>\n      <td>0.81</td>\n      <td>0.81</td>\n      <td>0.81</td>\n      <td>0.81</td>\n      <td>0.80</td>\n      <td>0.80</td>\n      <td>0.80</td>\n      <td>0.80</td>\n      <td>0.79</td>\n      <td>0.79</td>\n      <td>0.79</td>\n      <td>0.79</td>\n      <td>0.79</td>\n      <td>0.78</td>\n      <td>0.77</td>\n      <td>0.77</td>\n      <td>0.77</td>\n      <td>0.77</td>\n      <td>0.76</td>\n      <td>0.76</td>\n      <td>0.75</td>\n      <td>0.75</td>\n      <td>0.75</td>\n      <td>0.74</td>\n      <td>0.73</td>\n      <td>0.73</td>\n      <td>0.72</td>\n      <td>0.72</td>\n      <td>0.71</td>\n      <td>0.71</td>\n      <td>0.7</td>\n      <td>0.7</td>\n      <td>0.7</td>\n      <td>0.69</td>\n      <td>0.69</td>\n      <td>0.68</td>\n      <td>0.68</td>\n      <td>0.67</td>\n      <td>0.67</td>\n      <td>0.66</td>\n      <td>0.65</td>\n      <td>0.65</td>\n      <td>0.64</td>\n      <td>0.64</td>\n      <td>0.62</td>\n      <td>0.62</td>\n      <td>0.61</td>\n      <td>0.6</td>\n      <td>0.59</td>\n      <td>0.59</td>\n      <td>0.58</td>\n      <td>0.57</td>\n      <td>0.56</td>\n      <td>0.55</td>\n      <td>0.54</td>\n      <td>0.53</td>\n      <td>0.52</td>\n      <td>0.51</td>\n      <td>0.5</td>\n      <td>0.49</td>\n      <td>0.48</td>\n      <td>0.47</td>\n      <td>0.47</td>\n      <td>0.46</td>\n      <td>0.45</td>\n      <td>0.44</td>\n      <td>0.43</td>\n      <td>0.41</td>\n      <td>0.4</td>\n      <td>0.39</td>\n      <td>0.38</td>\n      <td>0.36</td>\n    </tr>\n    <tr>\n      <th>Fpr</th>\n      <td>0.06</td>\n      <td>0.06</td>\n      <td>0.05</td>\n      <td>0.05</td>\n      <td>0.05</td>\n      <td>0.05</td>\n      <td>0.05</td>\n      <td>0.05</td>\n      <td>0.04</td>\n      <td>0.04</td>\n      <td>0.04</td>\n      <td>0.04</td>\n      <td>0.04</td>\n      <td>0.04</td>\n      <td>0.04</td>\n      <td>0.03</td>\n      <td>0.03</td>\n      <td>0.03</td>\n      <td>0.03</td>\n      <td>0.03</td>\n      <td>0.03</td>\n      <td>0.03</td>\n      <td>0.03</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>0.02</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n```python\nplt.figure(figsize=(10,5), dpi=120)\nax1 = plt.subplot(121)\nevaltr.ROC_Curves(T_range=np.arange(-25, 25, 0.5))\nax1 = plt.subplot(122)\nevaltr.Sn_Sp_Curves(T_range=np.arange(-25, 25, 0.5))\n```\n\n### Discussion\n\nreintroduce the problem\n\ndescribe results and its importance\n\nfuture research\n\n\n```python\n\n```\n", "meta": {"hexsha": "e1c15dc02f1c4e66df6b331e4bb5828aae63f442", "size": 252304, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Source/.ipynb_checkpoints/Report.old-checkpoint.ipynb", "max_stars_repo_name": "AdeBC/GSSR", "max_stars_repo_head_hexsha": "895eab0d09ae3c8b48d96d3094e3d1de4b3187a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-03-28T05:42:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T08:00:46.000Z", "max_issues_repo_path": "Source/Report.old.ipynb", "max_issues_repo_name": "AdeBC/GSSR", "max_issues_repo_head_hexsha": "895eab0d09ae3c8b48d96d3094e3d1de4b3187a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Report.old.ipynb", "max_forks_repo_name": "AdeBC/GSSR", "max_forks_repo_head_hexsha": "895eab0d09ae3c8b48d96d3094e3d1de4b3187a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 124.9648340763, "max_line_length": 101944, "alphanum_fraction": 0.7956037162, "converted": true, "num_tokens": 15857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250464935739196, "lm_q2_score": 0.06656919267419922, "lm_q1q2_score": 0.02812579340881721}}
{"text": "```python\n!pip install -r ../requirements.txt\n```\n\n    Requirement already satisfied: numpy in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from -r ../requirements.txt (line 1)) (1.17.3)\n    Requirement already satisfied: scipy in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from -r ../requirements.txt (line 2)) (1.1.0)\n    Requirement already satisfied: matplotlib in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from -r ../requirements.txt (line 3)) (2.1.1)\n    Requirement already satisfied: Pillow in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from -r ../requirements.txt (line 4)) (4.3.0)\n    Requirement already satisfied: ipywidgets>=0.6.0 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from -r ../requirements.txt (line 5)) (7.5.1)\n    Requirement already satisfied: requests in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from -r ../requirements.txt (line 6)) (2.14.2)\n    Collecting SimPEG\n      Using cached https://files.pythonhosted.org/packages/c4/05/6480fd00c7e6809f855134f9a47dd0cc61a2ed5538c367372290cdc6dcaf/SimPEG-0.12.0.tar.gz\n    Collecting em_examples\n      Using cached https://files.pythonhosted.org/packages/e8/39/1a285f68abfdbacc00deefbcd7d2053b6dd67d9ab384a4cbc70a523ae84c/em_examples-0.0.35-py3-none-any.whl\n    Collecting empymod\n      Using cached https://files.pythonhosted.org/packages/ad/01/b257911dbc987a440be8972384798a368b41be870526959eebc48142f49c/empymod-1.10.3-py3-none-any.whl\n    Collecting deepdish\n      Using cached https://files.pythonhosted.org/packages/6e/39/2a47c852651982bc5eb39212ac110284dd20126bdc7b49bde401a0139f5d/deepdish-0.3.6-py2.py3-none-any.whl\n    Collecting pymatsolver>=0.1.2\n      Using cached https://files.pythonhosted.org/packages/0f/5e/30e92dfe738cc3e28f52344484aa2c6e44872787b2edd789df0eaae04e3b/pymatsolver-0.1.2.tar.gz\n    Requirement already satisfied: six>=1.10 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from matplotlib->-r ../requirements.txt (line 3)) (1.11.0)\n    Requirement already satisfied: python-dateutil>=2.0 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from matplotlib->-r ../requirements.txt (line 3)) (2.8.1)\n    Requirement already satisfied: pytz in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from matplotlib->-r ../requirements.txt (line 3)) (2016.6.1)\n    Requirement already satisfied: cycler>=0.10 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from matplotlib->-r ../requirements.txt (line 3)) (0.10.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from matplotlib->-r ../requirements.txt (line 3)) (2.1.4)\n    Requirement already satisfied: olefile in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from Pillow->-r ../requirements.txt (line 4)) (0.44)\n    Requirement already satisfied: nbformat>=4.2.0 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (4.2.0)\n    Requirement already satisfied: ipykernel>=4.5.1 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (4.7.0)\n    Requirement already satisfied: traitlets>=4.3.1 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (4.3.1)\n    Requirement already satisfied: ipython>=4.0.0; python_version >= \"3.3\" in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (6.2.1)\n    Requirement already satisfied: widgetsnbextension~=3.5.0 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (3.5.1)\n    Requirement already satisfied: cython in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from SimPEG->-r ../requirements.txt (line 7)) (0.24.1)\n    Collecting properties>=0.5.2\n      Using cached https://files.pythonhosted.org/packages/c0/9a/cd2def3421cd077d80d4973c802d29dcb3fba625190b3678480f228a85bf/properties-0.6.1.tar.gz\n    Collecting vectormath>=0.2.0\n      Using cached https://files.pythonhosted.org/packages/be/d3/5d49b6e961d87ba4845205509fbd0f2fa39875859ccb5e4778035518b89f/vectormath-0.2.2.tar.gz\n    Collecting discretize>=0.4.0\n      Using cached https://files.pythonhosted.org/packages/b1/41/4766aa8a1f6db9357f6941e6ffb1e6b572b9cfe9467d2d81d7dd431f20cd/discretize-0.4.10.tar.gz\n    Collecting geoana>=0.0.4\n      Using cached https://files.pythonhosted.org/packages/60/34/5715c1b3e35b4b7e0fdef463405c9ae5b073563f48118f2a54165be78cdc/geoana-0.0.5-py2.py3-none-any.whl\n    Requirement already satisfied: jupyter in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from em_examples->-r ../requirements.txt (line 8)) (1.0.0)\n    Requirement already satisfied: future in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from em_examples->-r ../requirements.txt (line 8)) (0.18.2)\n    Requirement already satisfied: tables in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from deepdish->-r ../requirements.txt (line 10)) (3.4.2)\n    Collecting pyMKL>=0.0.3\n      Using cached https://files.pythonhosted.org/packages/43/9d/0657fdb64d31a83c5caab80a70e55dac7658ba3fac7d1f43cbcca726b286/pyMKL-0.0.3.tar.gz\n    Requirement already satisfied: jupyter_client in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipykernel>=4.5.1->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (5.1.0)\n    Requirement already satisfied: tornado>=4.0 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipykernel>=4.5.1->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (4.4.1)\n    Requirement already satisfied: setuptools>=18.5 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (41.6.0)\n    Requirement already satisfied: jedi>=0.10 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (0.11.0)\n    Requirement already satisfied: decorator in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (4.4.1)\n    Requirement already satisfied: pickleshare in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (0.7.4)\n    Requirement already satisfied: simplegeneric>0.8 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (0.8.1)\n    Requirement already satisfied: prompt_toolkit<2.0.0,>=1.0.4 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (1.0.15)\n    Requirement already satisfied: pygments in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (2.1.3)\n    Requirement already satisfied: pexpect in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (4.0.1)\n    Requirement already satisfied: notebook>=4.4.1 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from widgetsnbextension~=3.5.0->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (5.0.0)\n    Collecting utm\n      Using cached https://files.pythonhosted.org/packages/b6/77/180f06153f2c1a8caf8409ff6365abc9423ec4ebc3991dfe4a3228bc09d4/utm-0.5.0.tar.gz\n    Requirement already satisfied: numexpr>=2.5.2 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from tables->deepdish->-r ../requirements.txt (line 10)) (2.6.2)\n    Requirement already satisfied: jupyter_core in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from jupyter_client->ipykernel>=4.5.1->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (4.4.0)\n    Requirement already satisfied: pyzmq>=13 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from jupyter_client->ipykernel>=4.5.1->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (15.4.0)\n    Requirement already satisfied: parso==0.1.* in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from jedi>=0.10->ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (0.1.1)\n    Requirement already satisfied: wcwidth in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from prompt_toolkit<2.0.0,>=1.0.4->ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (0.1.7)\n    Building wheels for collected packages: SimPEG, pymatsolver, properties, vectormath, discretize, pyMKL, utm\n      Building wheel for SimPEG (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Created wheel for SimPEG: filename=SimPEG-0.12.0-cp35-none-any.whl size=300157 sha256=adb0928480fe89c9518b13f9aaa2ac9a4dd09653d644472f622a0019459e2eaf\n      Stored in directory: /home/nbuser/.cache/pip/wheels/2e/5a/e9/91fe65f3693bf49496c16b290be247c1ce2a83cbc0ecd6de89\n      Building wheel for pymatsolver (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Created wheel for pymatsolver: filename=pymatsolver-0.1.2-cp35-none-any.whl size=18199 sha256=e44bb10dc84d7c26fe2a0011608e919096c64542a503f66fc95cf3588fd2df5f\n      Stored in directory: /home/nbuser/.cache/pip/wheels/09/66/a3/c540b8d29d1edab2bd4fabe368987aedc7fda18e742672be5b\n      Building wheel for properties (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Created wheel for properties: filename=properties-0.6.1-cp35-none-any.whl size=62368 sha256=e5ebe9c31f65485309599cf9e99097b024172e61f57597089373ac4e8d7cf007\n      Stored in directory: /home/nbuser/.cache/pip/wheels/9d/d9/66/f1f984e6dbe9ca4fb0c51617e526a73945f90936d4ae040fc2\n      Building wheel for vectormath (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Created wheel for vectormath: filename=vectormath-0.2.2-cp35-none-any.whl size=9353 sha256=958cd9694614fe2b3a3b45b17b2646e7bd44c89aa9a43e68771333fafb5c662c\n      Stored in directory: /home/nbuser/.cache/pip/wheels/82/45/db/21f8afb4447691ddc30be13170201154af9647c9653aa899b1\n      Building wheel for discretize (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Created wheel for discretize: filename=discretize-0.4.10-cp35-cp35m-linux_x86_64.whl size=2238852 sha256=091ee37106e078c5bdda54129b173201c657e89db866792f023a1d417459d8a1\n      Stored in directory: /home/nbuser/.cache/pip/wheels/2f/64/bb/e65ceff1490fddea5cd123ba500360f0d400938fb0ce68872b\n      Building wheel for pyMKL (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Created wheel for pyMKL: filename=pyMKL-0.0.3-cp35-none-any.whl size=7069 sha256=0f45359485d13d5483dbde995cb1e52bbe5b8f96b9d4eec1c060aaa17f4edcac\n      Stored in directory: /home/nbuser/.cache/pip/wheels/d6/40/40/df64f35d394a22fbecae00749cb8e7071798a3554fac9e5abe\n      Building wheel for utm (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Created wheel for utm: filename=utm-0.5.0-cp35-none-any.whl size=5944 sha256=d2cf95deae8cbdc20dc3ff3955d52a622159852735f2a23f25f22115f989474b\n      Stored in directory: /home/nbuser/.cache/pip/wheels/22/85/c2/314ffed39b8e02ca623e9b7d2ad7fcf3f8544a0e77c096be76\n    Successfully built SimPEG pymatsolver properties vectormath discretize pyMKL utm\n    Installing collected packages: pyMKL, pymatsolver, properties, vectormath, discretize, utm, geoana, SimPEG, empymod, deepdish, em-examples\n    Successfully installed SimPEG-0.12.0 deepdish-0.3.6 discretize-0.4.10 em-examples-0.0.35 empymod-1.10.3 geoana-0.0.5 properties-0.6.1 pyMKL-0.0.3 pymatsolver-0.1.2 utm-0.5.0 vectormath-0.2.2\n\n\n\n```python\nfrom em_examples import DCLayers\nfrom IPython.display import display\n%matplotlib inline\n```\n\n\n```python\nfrom matplotlib import rcParams\nrcParams['font.size'] = 14\n```\n\n# Purpose\n\n## Investigating DC Resistivity Data \n\nUsing the widgets contained in this notebook we will explore the physical principals governing DC resistivity including the behavior of currents, electric field, electric potentials in a two layer earth. \n\nThe measured data in a DC experiment are potential differences, we will demonstrate how these  provide information about subsurface physical properties. \n\n### Background: Computing Apparent Resistivity\n\nIn practice we cannot measure the potentials everywhere, we are limited to those locations where we place electrodes. For each source (current electrode pair) many potential differences are measured between M and N electrode pairs to characterize the overall distribution of potentials. The widget below allows you to visualize the potentials, electric fields, and current densities from a dipole source in a simple model with 2 layers. For different electrode configurations you can measure the potential differences and see the calculated apparent resistivities. \n\nIn a uniform halfspace the potential differences can be computed by summing up the potentials at each measurement point from the different current sources based on the following equations:\n\n\\begin{align}\n    V_M = \\frac{\\rho I}{2 \\pi} \\left[ \\frac{1}{AM} - \\frac{1}{MB} \\right] \\\\\n    V_N = \\frac{\\rho I}{2 \\pi} \\left[ \\frac{1}{AN} - \\frac{1}{NB} \\right] \n\\end{align} \nwhere $AM$, $MB$, $AN$, and $NB$ are the distances between the corresponding electrodes. \n\nThe potential difference $\\Delta V_{MN}$ in a dipole-dipole survey can therefore be expressed as follows,\n\n\\begin{equation}\n    \\Delta V_{MN} = V_M - V_N = \\rho I \\underbrace{\\frac{1}{2 \\pi} \\left[ \\frac{1}{AM} - \\frac{1}{MB} - \\frac{1}{AN} + \\frac{1}{NB} \\right]}_{G}\n\\end{equation}\n\nand the resistivity of the halfspace $\\rho$ is equal to,\n\n$$\n    \\rho = \\frac{\\Delta V_{MN}}{IG}\n$$\n\nIn this equation $G$ is often referred to as the geometric factor. \n\nIn the case where we are not in a uniform halfspace the above equation is used to compute the apparent resistivity ($\\rho_a$) which is the resistivity of the uniform halfspace which best reproduces the measured potential difference.\n\nIn the top plot the location of the A electrode is marked by the red +, the B electrode is marked by the blue -, and the M/N potential electrodes are marked by the black dots. The $V_M$ and $V_N$ potentials are printed just above and to the right of the black dots. The calculted apparent resistivity is shown in the grey box to the right. The bottom plot can show the resistivity model, the electric fields (e), potentials, or current densities (j) depending on which toggle button is selected. Some patience may be required for the plots to update after parameters have been changed.\n\n# LayeredEarth app\n\n## Parameters:\n\n - **A**: (+) Current electrode  location\n - **B**: (-) Current electrode  location\n - **M**: (+) Potential electrode  location\n - **N**: (-) Potential electrode  location\n - **$\\rho_1$**: Resistivity of the first layer\n - **$\\rho_2$**: Resistivity of the second layer\n - **h**: Thickness of the first layer\n - **Plot**: Choice of 2D plot (Model, Potential, Electric field, Currents)\n\n\n\n```python\nout = DCLayers.plot_layer_potentials_app()\ndisplay(out)\n```\n\n\n    MyApp(children=(FloatSlider(value=-30.0, continuous_update=False, description='A', max=30.0, min=-30.0, step=1\u2026\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "8048b85c820adaee1af75025cff9215865c647aa", "size": 17593, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "LabExercise_1/DC_LayeredEarth.ipynb", "max_stars_repo_name": "RichardScottOZ/UHElectromagnetics", "max_stars_repo_head_hexsha": "6fa608681060bc1354fd4532f62c923a0881ed65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-11-23T21:15:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T11:09:11.000Z", "max_issues_repo_path": "LabExercise_1/DC_LayeredEarth.ipynb", "max_issues_repo_name": "RichardScottOZ/UHElectromagnetics", "max_issues_repo_head_hexsha": "6fa608681060bc1354fd4532f62c923a0881ed65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LabExercise_1/DC_LayeredEarth.ipynb", "max_forks_repo_name": "RichardScottOZ/UHElectromagnetics", "max_forks_repo_head_hexsha": "6fa608681060bc1354fd4532f62c923a0881ed65", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-23T21:16:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T21:16:16.000Z", "avg_line_length": 143.0325203252, "max_line_length": 8763, "alphanum_fraction": 0.7232990394, "converted": true, "num_tokens": 5159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.08035747763179142, "lm_q1q2_score": 0.028016243664030438}}
{"text": "# ANEOS MODEL INTERFACE JUPYTER NOTEBOOK\n\nSarah T. Stewart<br>\nsts@ucdavis.edu<br>\nCreated October 22, 2019<br>\nUpdated January 21, 2020<p>\n\n***\n***\n## COMMENTS ON ANEOS IRON MODEL WITH MELT CURVE\nTheses parameters were obtained by R. Canup from E. Pierazzo and H. J. Melosh circa 2001-2002.\n\nThis version was used in Canup 2004, 2008, 2012; Canup et al. 2013; Nakajima & Stevenson 2014, 2015; Barr 2016; Golabek et al. 2018; Emsenhuber et al. 2018; Deng et al. 2019. The parameters were tabulated in Canup 2012 and Barr 2016. Note that the value for Esep in Table 2 of Emsenhuber et al. 2018 is incorrect.\n\nThis is a solid, liquid, gas phase ANEOS model with ionization for pure iron.\n\nIssues:<br>\n  - The temperatures on the melt curve are too high.<br>\n  - The model includes one solid phase. Iron has several solid phases.<br>\n  - The vapor curve does not match available data. The critical point temperature is too high.<br>\n  - In the original ANEOS, the temperatures are too high and the entropies are too low in the liquid region. The discrepancy arises because the ANEOS model has a limiting 3nR heat capacity; the true heat capacities in liquid iron are larger.<br>\n\n***\n***\n<b>STS ANEOS INTERFACE NOTEBOOK GUIDE</b>\n\n<b>USAGE</b><br>\nThis notebook interacts with multiple outputs from the Stewart-modified version of ANEOS, including phase boundary information and tabulated EOS. \n\nThis notebook is designed to be used in two modes:<br>\n<ul>\n<li> Development mode: ANEOS is called in the local directory to generate new model output. The user can varying the model input parameters and tabular gridding schemes. This notebook produces plots of the equation of state surface and comparisons to experimental data and ab initio calculations.\n<li> Release mode: the notebook interacts with previously created ANEOS model output. This notebook provides detailed documentation of a version-controlled release of the model EOS and enables users to interact with the EOS surface and compare the model to data. \n</ul>\n\nThis notebook is distributed in release mode. Users who wish to use the development mode may request the modified version of ANEOS from the author.<p>\n\nDevelopment mode:<br>\nThe notebook calls a local aneos executable which expects a formatted ANEOS.INPUT ascii file and an ascii gridtable.txt definition file that is generated by this notebook. ANEOS produces an ANEOS.OUTPUT ascii file and gridded ascii SESAME-format EOS tables.<br>\nThe user edits (1) the input parameters in ANEOS.INPUT (separately from this notebook) and (2) the output EOS table parameters in the notebook cell below.<br>\nThis notebook reads some parameters from ANEOS.INPUT and assumes that the variables are spaced by 10 columns.<br> \nWhen the notebook is run, the code issues a system call to run the aneos program in the local directory and reads in results from the ANEOS.OUTPUT, NEW-SESAME-STD.TXT, and NEW-SESAME-EXT.TXT files to make the plots below and to generate the GADGET format EOS table and other miscellaneous files.<p>\n\nRelease mode:<br>\nThis notebook reads in the provided ANEOS.INPUT, EOS tables, and other distribution data to generate the plots below. <p>\n\n<b>OUTPUT/PROVIDED DATA FILES</b><br>\nANEOS.OUTPUT: Plain text file with an overview of the calculated equation of state. Look at this file for any errors in the EOS calculation.<br>\n\nNEW-SESAME-STD.TXT: Standard length Sandia-style SESAME file with 201 table and 301 table (density, temperature, pressure, sp. internal energy, Helmholtz free energy). 301 table units: g/cm$^3$, K, GPa, MJ/kg, MJ/kg. <br>\n\nNEW-SESAME-EXT.TXT: SESAME-style table with extra variables from ANEOS. Contains the standard 201 table and non-standard 301-extra-variables EOS table. The 301 table has: density grid values, temperature grid values, sp. entropy(T,rho), sound speed(T,rho), sp. heat capacity(T,rho), KPA flag(T,rho). 2-D arrays list all densities, looping over each temperature. 301 table units: g/cm$^3$, K, MJ/K/kg, cm/s, MJ/K/kg, integer flag, integer flag. The KPA flag is an ANEOS output with phase information. <br>\n\nNEW-SESAME-HUG.TXT: Ascii table with the reference state Hugoniot. <br>\n\nNEW-SESAME-STD-NOTENSION.TXT: Standard length Sandia-style SESAME file with 201 table and 301 table (density, temperature, pressure, sp. internal energy, Helmholtz free energy) where the ANEOS tension region is removed and replaced with the solid-vapor coexistence region. 301 table units: g/cm$^3$, K, GPa, MJ/kg, MJ/kg. <br>\n\nNEW-GADGET2-STD-NOTENSION.TXT: Standard GADGET2 EOS table generated by interpolating the ANEOS table with no tension. Format: number of density points, number of sp. entropy points, density grid values, sp. entropy grid values, 2-D arrays of pressure, temperature, specific internal energy, sound speed. 2-D array values list all densities, looping over each value for specific entropy. Units: g/cm$^3$, erg/K/g, dynes/cm$^2$, K, erg/g, cm/s. <br>\n\nNEW-GADGET2-EXT-NOTENSION.TXT: Extended variables GADGET2 EOS table generated by interpolating the ANEOS table with no tension. Format: number of density points, number of sp. entropy points, density grid values, sp. entropy grid values, 2-D arrays of Helmholtz free energy, KPA flag, MDQ flag. 2-D array values list all densities, looping over each value for specific entropy. Units: g/cm$^3$, erg/K/g, erg/g, integer flag, integer flag. <br>\n\nThe SESAME tabular equation of state formats are described in Lyon and Johnson (1992).<p>\n\n<b>ANEOS NOTES</b><br>\nThe ANEOS source code was provided by Jay Melosh and Gareth Collins. This version included Melosh's (2007) treatment for molecular gas and the capability to include a melt curve and solid-solid/liquid-liquid transition (Collins & Melosh LPSC 2014).<br>\nIn Stewart et al. 2019, the Melosh and Collins version of ANEOS was modified to adjust the Debye model for the thermal term in the Helmholtz free energy to approach a user-defined heat capacity at high temperatures. The multiplicative factor $f_{cv}$ is entered in input value V44, and the high-temperature heat capacity is $3f_{cv}Nk$.<p>\nThe ANEOSTEST.f routine was modified to output tabulated EOS. Note that the current version of this function sets positive pressures smaller than 1.E-30 GPa equal to 1.E-30 GPa.<br>\nANEOS2.f was modified to increase the number of points tabulated on the melt curve in the ANEOS.OUTPUT file and to gather the variables for the heat capacity modification.<br>\nANHUG.f was modified to output more Hugoniot points.<br>\nANEOS1.f and ANEOS2.f were modified to increase the high temperature limit for the heat capacity (Stewart et al., SCCM19).<p>\n\n<b>CORRECTIONS AND IMPROVEMENTS</b><br>\nPlease send corrections to STS and any requests for data to include in the model-data comparison plots.<p>\n\n\n\n```python\n# this cell has a java script that that enables hiding the raw python code\n\nfrom IPython.display import HTML\n\nHTML('''\n<form action=\"javascript:code_toggle()\"><input type=\"submit\" value=\"Click here to toggle on/off the raw code.\"></form>''')\n```\n\n\n\n\n\n<form action=\"javascript:code_toggle()\"><input type=\"submit\" value=\"Click here to toggle on/off the raw code.\"></form>\n\n\n\n\n```python\n# Record the verions information for these calculation for posterity\nimport platform\nprint('python version: ',platform.python_version())\ndel platform\nimport matplotlib\nprint('matplotlib version: ', matplotlib.__version__)\ndel matplotlib\nimport numpy\nprint('numpy version: ', numpy.__version__)\ndel numpy\nimport scipy\nprint('scipy version: ', scipy.__version__)\ndel scipy\nimport pandas\nprint('pandas version: ', pandas.__version__)\ndel pandas\n\n# this prevents some error messages for inline plotting in a jupyter notebook\n%matplotlib inline \n# import python libraries\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport matplotlib.colors as colors\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom copy import deepcopy\nimport numpy as np\nfrom scipy import interpolate\nimport colormaps as local_cmaps\nimport subprocess\nimport pandas as pd\nfrom matplotlib.collections import PatchCollection\nfrom matplotlib.patches import Rectangle\n#\nplt.rcParams[\"figure.figsize\"] = (20,10)\nplt.rcParams[\"patch.force_edgecolor\"] = True\n```\n\n    python version:  3.7.4\n    matplotlib version:  3.1.1\n    numpy version:  1.17.2\n    scipy version:  1.3.1\n    pandas version:  0.25.1\n\n\n## USER INPUTS FOR SESAME AND GADGET2 TABLE CONSTRUCTION\n\nIf the code cell below is hidden, use the button above to reveal the cell.<p>\n\nIn development mode, the user must input:<br>\n1. Header information for the SESAME table.<br>\n2. Temperature, density and entropy grid points.<p>\n\nThe following code cell also includes the development mode flag and \noption to skip construction of a GADGET2 table if it is not needed.<p>\n\n\n```python\n# -------------------------------------------------------------\n# USER INPUTS\n#-------------------------------------------------------------\n# NOTEBOOK MODE\n#-------------------------------------------------------------\n#\nDEVMODE = 1 # 1=development mode; 0=release mode\n#\n#-------------------------------------------------------------\n# OPTIONS TO REMOVE TENSION REGION AND CONSTRUCT A GADGET2 TABLE\n#-------------------------------------------------------------\n#\nREMOVETENSIONFLAG=0  # 0- keep tension region; 1- remove tension region\nMAKEGADGETTABLE=0  # 1=make table; 0=do not make gadget2 table\n#\n#-------------------------------------------------------------\n# USER MUST SET THESE VALUES TO DEFINE THE TABULATED EOS GRIDS\n#-------------------------------------------------------------\n#\n# ====>>>>>> YOU NEED TO MAKE SURE THESE VALUES MATCH ANEOS.INPUT  <<<<=====\nMODELNAME = 'Iron-ANEOS-SLVTv0.1Gx'\n# Header information must all be compatible with float format\nMATID = 1.0        # MATID number\nDATE = 191022.     # Date as a single 6-digit number YYMMDD\nVERSION = 0.1      # ANEOS Parameters Version number\nFMN = 26.          # Formula weight in atomic numbers for Fe\nFMW = 55.847       # Formula molecular weight (g/cm3) for Fe\n# The following define the default initial state for material in the 201 table\nR0REF   = 8.06     # g/cm3 *** R0REF is inserted into the density array; using gamma-iron for rho0\nK0REF   = 1.33E12  # dynes/cm2; using gamma-iron for rho0\nT0REF   = 298.     # K -- *** T0REF is inserted into the temperature array\nP0REF   = 1.E6     # dynes/cm2 -- this defines the principal Hugoniot calculated below\n#\n# generate output files for other ANEOS models\nmodelflag = 1   # 0 - don't change anything above; 1 - Canup et al. 2013; \n                # 2 - GADGET2 Marcus PhD Thesis & Cuk & Stewart 2012; 3 - ISALE Dellen Collins and Melosh 2014\n#\nif modelflag == 1:\n    MODELNAME = 'IRON WITH MELT CURVE'\n    # Header information must all be compatible with float format\n    MATID = 1.0        # MATID number\n    DATE = 191022.     # Date as a single 6-digit number YYMMDD\n    VERSION = 1.0      # ANEOS Parameters Version number\n    FMN = 26.          # Formula weight in atomic numbers for Mg2SiO4\n    FMW = 55.847       # Formula molecular weight (g/cm3) for Mg2SiO4\n    # The following define the default initial state for material in the 201 table\n    R0REF   = 7.85     # g/cm3 *** R0REF is inserted into the density array\n    K0REF   = 1.45E12  # dynes/cm2  K0=rho0*cs0^2\n    T0REF   = 298.     # K -- *** T0REF is inserted into the temperature array\n    P0REF   = 1.E6     # dynes/cm2 -- this defines the principal Hugoniot calculated below\n\n#-------------------------------------------------------------\n# EXAMPLE EOS GRID ARRAYS\n#-------------------------------------------------------------\n#\n# Life is easier if the grid arrays are even in length (after adding T0REF and R0REF below)\n#\n# Flag for easily switching between different table grids during model development\n# 1: high res for testing\ngridflag = 1\n#\n#------------------------------------------------------\n#\nif gridflag == 0: # low resolution grid\n    # define the temperature array for the SESAME table\n    # 0 K is changed to 1 K\n    # T0REF is inserted into the table if it is not present in the original array\n    # need to have extra temperature resolution around the triple point\n    gridtvals  = [0, 1750, 1950, 20000.,1.E5, 1.E7] # K -- this array defines the edges of the segments along the grid, 0 is changed to 1 below\n    gridtstyle = [1,1,1,1,0] # 1 for linear, 0 for log in each segment\n    gridtnpts  = [20, 20, 150.,50.,10.] # number of grid points in each segment\n    # define the density array for the SESAME AND GADGET2 tables\n    # R0REF is inserted into the table if it is not present in the original array\n    # need to have extra density resolution around the triple point\n    # 0 g/cm3 is removed if present\n    gridrvals  = [1.e-20, 0.5, 6.6, 7.4, 20., 30.] # g/cm3 -- this array defines the edges of the segments along the grid\n    gridrstyle = [0, 1, 1, 1, 1] # 1 for linear, 0 for log in each segment\n    gridrnpts  = [50, 20, 20, 40, 20] # number of grid points in each segment\n    # define the specific entropy array for the GADGET2 table\n    # 0 MJ/K/kg is removed if present\n    gridsvals  = [1.e-4,.1] # MJ/K/kg -- this array defines the edges of the segments along the grid\n    gridsstyle = [0] # 1 for linear, 0 for log in each segment\n    gridsnpts  = [200] # number of grid points in each segment\n#\nif gridflag == 1: # new form for the high resolution table entries in 301 table. Try for 1e6 values\n    # define the temperature array for the SESAME table\n    # 0 K is changed to 1 K\n    # T0REF is inserted into the table if it is not present in the original array\n    # need to have extra temperature resolution around the triple point\n    gridtvals  = [0, 100, 1750, 1950, 20000.,1.E5, 1.E7] # K -- this array defines the edges of the segments along the grid, 0 is changed to 1 below\n    gridtstyle = [1,1,1,1,1,0] # 1 for linear, 0 for log in each segment\n    gridtnpts  = [2, 75., 100, 500.,85.,50.] # number of grid points in each segment\n    # define the density array for the SESAME AND GADGET2 tables\n    # R0REF is inserted into the table if it is not present in the original array\n    # need to have extra density resolution around the triple point\n    # 0 g/cm3 is removed if present\n    gridrvals  = [1.e-20, 0.5, 6.6, 7.4, 20., 30.] # g/cm3 -- this array defines the edges of the segments along the grid\n    gridrstyle = [0, 1, 1, 1, 1] # 1 for linear, 0 for log in each segment\n    gridrnpts  = [150, 84, 101, 400, 100] # number of grid points in each segment\n    # define the specific entropy array for the GADGET2 table\n    # 0 MJ/K/kg is removed if present\n    gridsvals  = [1.e-4,.1] # MJ/K/kg -- this array defines the edges of the segments along the grid\n    gridsstyle = [0] # 1 for linear, 0 for log in each segment\n    gridsnpts  = [800] # number of grid points in each segment\n#----------------------------------------\n# END USER INPUT\n#----------------------------------------\n```\n\n\n```python\n# THIS CELL DEFINEs FUNCTIONS \n# define index function (must be a more efficient way to do this...)\nget_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]\n#\n# LOAD EXTERNAL FUNCTIONS AND OBJECT CLASSES\n# defines rational function interpolation functions rf1d and rf2d\n#%run rfinterpolation.py \n# defines class objects for extEOStable and functions to read in ANEOS input and output\n# READ THIS CODE IF YOU WANT TO UNDERSTAND THE FILE STRUCTURES\n%run eostable.py\n#import eostable\n# Run the following help for the functions in the class\n#help(extEOStable())\n```\n\n\n```python\n# THIS CELL HAS CODE TO GENERATE THE GRIDS AND WRITES TO A FILE TO BE READ BY ANEOS\nprint('GENERATING ARRAYS FOR THE INDICES OF THE TABULATED EOS.')\n#-------------- the following code generates the temperature array\ngridtarr = []\nfor iir in  range(1,len(gridtvals)):\n    if gridtstyle[iir-1] == 1:\n        # linear region\n        temptarr = np.arange(gridtnpts[iir-1])/gridtnpts[iir-1]*(gridtvals[iir]-gridtvals[iir-1])+gridtvals[iir-1]\n    if gridtstyle[iir-1] == 0:\n        # log region\n        logstep = (np.log10(gridtvals[iir])-np.log10(gridtvals[iir-1]))/gridtnpts[iir-1]\n        temptarr = np.power(10.,np.log10(gridtvals[iir-1])+(np.arange(gridtnpts[iir-1]))*logstep)\n    gridtarr = np.concatenate((gridtarr,temptarr))\n# check if T0REF already in the grid\n#indexT0REF = get_indexes(T0REF,gridtarr)\nindexT0REF = np.where(abs(T0REF-gridtarr)<1.E-4)[0]\nif len(indexT0REF) == 0:\n    # insert T0REF K into the array\n    indexT0REF = np.where((gridtarr-T0REF)>0.)[0]\n    gridtarr = np.concatenate((gridtarr[0:indexT0REF[0]],[T0REF],gridtarr[indexT0REF[0]::]))\n    if indexT0REF[0]>1:\n        print('Inserted the REFERENCE TEMPERATURE INTO THE ARRAY:',gridtarr[indexT0REF[0]-2:indexT0REF[0]+3])\n    else:\n        print('Inserted the REFERENCE TEMPERATURE INTO THE ARRAY:',gridtarr[indexT0REF[0]-1:indexT0REF[0]+3])\nelse:\n    print('T0REF already in temperature array: ',T0REF,gridtarr[indexT0REF[0]-2:indexT0REF[0]+2])\n# Remove 0 K or convert to 1 K\nindexzero = get_indexes(0.,gridtarr)\nindexone = get_indexes(1.,gridtarr)\nif len(indexzero) == 1 and len(indexone) == 0:\n    gridtarr[indexzero] = 1.\n    print('Zero kelvin changed to 1 kelvin.')\nelse:\n    gridtarr = np.delete(gridtarr, indexzero)\n    print('Deleted zero K index.')\n#\n#gridtsize = len(grdtarr)\nprint('Number of temperature points: ',len(gridtarr))\n#print(gridtarr)\n#------------ the following code generates the density array\ngridrarr = []\nfor iir in range(1,len(gridrvals)):\n    if gridrstyle[iir-1] == 1:\n        # linear region\n        temprarr = np.arange(gridrnpts[iir-1])/gridrnpts[iir-1]*(gridrvals[iir]-gridrvals[iir-1])+gridrvals[iir-1]\n    if gridrstyle[iir-1] == 0:\n        # log region\n        logstep = (np.log10(gridrvals[iir])-np.log10(gridrvals[iir-1]))/gridrnpts[iir-1]\n        temprarr = np.power(10.,np.log10(gridrvals[iir-1])+(np.arange(gridrnpts[iir-1]))*logstep)\n    gridrarr = np.concatenate((gridrarr,temprarr))\n# check if R0REF already in the grid\n#indexR0REF = get_indexes(R0REF,gridrarr)\nindexR0REF = np.where(abs(R0REF-gridrarr)<1.E-4)[0]\nif len(indexR0REF) == 0:\n    # insert R0REF  into the array\n    indexR0REF = np.where((gridrarr-R0REF)>0.)[0]\n    gridrarr = np.concatenate((gridrarr[0:indexR0REF[0]],[R0REF],gridrarr[indexR0REF[0]::]))\n    print('Inserted the REFERENCE DENSITY INTO THE ARRAY:',gridrarr[indexR0REF[0]-2:indexR0REF[0]+3])\n    #print('NOT INSERTING REFERENCE DENSITY INTO THE ARRAY.')\nelse:\n    print('R0REF already in density array: ',R0REF,gridrarr[indexR0REF[0]-2:indexR0REF[0]+2])\n# Remove 0 g/cm3 if present\nindexzero = get_indexes(0.,gridrarr)\nif len(indexzero) == 1:\n    gridrarr = np.delete(gridrarr, indexzero)\n    print('Deleted zero g/cm3 index.')\n#\n#gridrsize = len(gridrarr)\nprint('Number of density points: ',len(gridrarr))\n#print(gridrarr)\n#------------ the following code generates the specific entropy array for gadget tables\ngridsarr = []\nfor iir in range(1,len(gridsvals)):\n    if gridsstyle[iir-1] == 1:\n        # linear region\n        tempsarr = np.arange(gridsnpts[iir-1])/gridsnpts[iir-1]*(gridsvals[iir]-gridsvals[iir-1])+gridsvals[iir-1]\n    if gridsstyle[iir-1] == 0:\n        # log region\n        logstep = (np.log10(gridsvals[iir])-np.log10(gridsvals[iir-1]))/gridsnpts[iir-1]\n        tempsarr = np.power(10.,np.log10(gridsvals[iir-1])+(np.arange(gridsnpts[iir-1]))*logstep)\n    gridsarr = np.concatenate((gridsarr,tempsarr))\n# Remove 0 MJ/K/kg if present\nindexzero = get_indexes(0.,gridsarr)\nif len(indexzero) == 1:\n    gridsarr[indexzero]=1.e-20\n#    gridsarr = np.delete(gridsarr, indexzero)\n    print('replaced zero MJ/K/kg index with 1.E-20')\n#gridssize = len(gridsarr)\n#\nprint('Number of specific entropy points: ',len(gridsarr))\n#print(gridsarr)\n\nprint('Number of words in the standard SESAME 301 table (NR, NT, R, T, P, IE, HFE)=',2.+len(gridrarr)+len(gridtarr)+len(gridrarr)*len(gridtarr)*3.)\n#-----------------------------------------------------------\n#\nif DEVMODE:\n    print('WRITING tablegrid.txt FOR ANEOS in the local directory.\\n')\n    # write the table arrays to a file for the ANEOS driver to read in\n    tablegridfile = open(\"tablegrid.txt\",\"w\")  \n    tablegridfile.write(\"{:.6e}\".format(MATID)+'\\n')  \n    tablegridfile.write(\"{:.6e}\".format(DATE)+'\\n')  \n    tablegridfile.write(\"{:.6e}\".format(VERSION)+'\\n')  \n    tablegridfile.write(\"{:.6e}\".format(FMN)+'\\n')  \n    tablegridfile.write(\"{:.6e}\".format(FMW)+'\\n')  \n    tablegridfile.write(\"{:.6e}\".format(R0REF)+'\\n')  \n    tablegridfile.write(\"{:.6e}\".format(K0REF)+'\\n')  \n    tablegridfile.write(\"{:.6e}\".format(T0REF)+'\\n')  \n    tablegridfile.write(\"{:.6e}\".format(len(gridrarr))+'\\n')  # number of density points\n    tablegridfile.write(\"{:.6e}\".format(len(gridtarr))+'\\n')  # number of temperature points\n    for i in range(0,len(gridrarr)):\n        tablegridfile.write(\"{:.6e}\".format(gridrarr[i])+'\\n')\n    for i in range(0,len(gridtarr)):\n        tablegridfile.write(\"{:.6e}\".format(gridtarr[i])+'\\n')\n    tablegridfile.close()\n#\n#-----------------------------------------------------\n# Output GADGET2 Table information\nif MAKEGADGETTABLE:\n    print('Number of words in the extended GADGET2 EOS table (NR, NS, R, S, P, T, IE, CS, HFE, CV, KPA, MDQ)=',2.+len(gridrarr)+len(gridtarr)+len(gridrarr)*len(gridtarr)*8.)\n#------------------------------------------------------\n\n#----------------------------------------------------\n# Sp. Internal Energy grid for Tillotson\ntillearr = np.power(10.,np.arange(600)/600.*6.-3.) # MJ/kg\ntillearr = np.append(0.,tillearr)\nprint('Number of specific internal energy points for Tillotson EOS: ',len(tillearr))\n#----------------------------------------------------\n# Paranoia check\n# make sure all table grid values are unique\nif (len(np.unique(gridtarr))!=len(gridtarr)):\n    print('NON-UNIQUE VALUES IN TEMP ARRAY')\n    stopthecode\nif (len(np.unique(gridrarr))!=len(gridrarr)):\n    print('NON-UNIQUE VALUES IN DENSITY ARRAY')\n    stopthecode\nif (len(np.unique(gridsarr))!=len(gridsarr)):\n    print('NON-UNIQUE VALUES IN SP. ENTROPY ARRAY')\n    stopthecode\nif (len(np.unique(tillearr))!=len(tillearr)):\n    print('NON-UNIQUE VALUES IN SP. ENERGY ARRAY')\n    stopthecode\n\n#----------------------------------------------------\n\nprint('\\nDone generating EOS grids.\\n')\nprint('\\nCHECK THAT THE GRID ARRAYS ARE EVEN IN LENGTH.\\n')\n\n# END TABLE GRIDDING INFORMATION\n```\n\n    GENERATING ARRAYS FOR THE INDICES OF THE TABULATED EOS.\n    T0REF already in temperature array:  298.0 [254. 276. 298. 320.]\n    Zero kelvin changed to 1 kelvin.\n    Number of temperature points:  812\n    Inserted the REFERENCE DENSITY INTO THE ARRAY: [7.8095 7.841  7.85   7.8725 7.904 ]\n    Number of density points:  836\n    Number of specific entropy points:  800\n    Number of words in the standard SESAME 301 table (NR, NT, R, T, P, IE, HFE)= 2038146.0\n    WRITING tablegrid.txt FOR ANEOS in the local directory.\n    \n    Number of specific internal energy points for Tillotson EOS:  601\n    \n    Done generating EOS grids.\n    \n    \n    CHECK THAT THE GRID ARRAYS ARE EVEN IN LENGTH.\n    \n\n\n\n```python\nif DEVMODE:\n    # call aneos in the local directory\n    # output file is in the local directory\n    print('RUNNING IN DEVELOPMENT MODE')\n    print('Calling aneos in the local directory.')\n    completed = subprocess.run(['./aneos'])\n    print('Aneos call complete. CHECK THAT A NEW ANEOS.OUTPUT FILE WAS CREATED.')\n    print('aneos call result: ', completed.returncode)\n    print('Check ANEOS.OUTPUT file for errors.')\nelse:\n    print('RUNNING IN RELEASE MODE: NO ANEOS SYSTEM CALL.')\n    print('READING IN EOS DISTRIBUTION FILES.')\n```\n\n    RUNNING IN DEVELOPMENT MODE\n    Calling aneos in the local directory.\n    Aneos call complete. CHECK THAT A NEW ANEOS.OUTPUT FILE WAS CREATED.\n    aneos call result:  0\n    Check ANEOS.OUTPUT file for errors.\n\n\n\n```python\n# READ IN NEW ANEOS MODEL and fill the extEOStable class object\n# source in eostable.py\n#------------------------------------------------------------------\nNewEOS  = extEOStable() # FIRST make new empty EOS object\nNewEOS.loadextsesame('NEW-SESAME-EXT.TXT') # LOAD THE EXTENDED 301 SESAME FILE GENERATED BY STSM VERSION OF ANEOS\nNewEOS.loadstdsesame('NEW-SESAME-STD.TXT') # LOAD THE STANDARD 301 SESAME FILE GENERATED BY STSM VERSION OF ANEOS\nNewEOS.MODELNAME = MODELNAME # string set above in user input\nNewEOS.MDQ = np.zeros((NewEOS.NT,NewEOS.ND)) # makes the empty MDQ array\n#print(NewEOS.units) # these are the default units for SESAME rho-T tables\n#'Units: g/cm3, K, GPa, MJ/kg, MJ/kg, MJ/K/kg, cm/s, MJ/K/kg, KPA flag. 2D arrays are (NT,ND).'\n\n# Add the header info to the table. This could be done during the loading. \n# if made from this notebook, these values are set in the user-input above.\n# ** MAKE SURE THEY MATCH ANEOS.INPUT **\nNewEOS.MATID   = MATID\nNewEOS.DATE    = DATE\nNewEOS.VERSION = VERSION\nNewEOS.FMN     = FMN\nNewEOS.FMW     = FMW\nNewEOS.R0REF   = R0REF\nNewEOS.K0REF   = K0REF\nNewEOS.T0REF   = T0REF\nNewEOS.P0REF   = P0REF\n#\n# Load the information from ANEOS.INPUT and ANEOS.OUTPUT\nNewEOS.loadaneos(aneosinfname='ANEOS.INPUT',aneosoutfname='ANEOS.OUTPUT')\n#\n# calculate the principal Hugoniot from the table\nif DEVMODE:\n    # calculate the Hugoniot and write to a file\n    NewEOS.calchugoniot(r0=NewEOS.R0REF,t0=NewEOS.T0REF,writefilename='NEW-SESAME-HUG.TXT')\nelse:\n    # just calculate the Hugoniot and put it in the EOS object\n    NewEOS.calchugoniot(r0=NewEOS.R0REF,t0=NewEOS.T0REF)\n#\n# calculate the 1-bar profile; loop over temp\nNewEOS.onebar.T = np.zeros(NewEOS.NT)\nNewEOS.onebar.S = np.zeros(NewEOS.NT)\nNewEOS.onebar.rho = np.zeros(NewEOS.NT)\nit0 = np.where(NewEOS.T >= NewEOS.T0REF)[0]\nid0 = np.arange(NewEOS.ND)#np.where(NewEOS.rho >= 0.8*NewEOS.R0REF)[0]\nfor iit in range(0,NewEOS.NT):\n    NewEOS.onebar.T[iit] = NewEOS.T[iit]\n    NewEOS.onebar.S[iit] = np.interp(1.E-4,NewEOS.P[iit,id0],NewEOS.S[iit,id0])\n    NewEOS.onebar.rho[iit] = np.interp(1.E-4,NewEOS.P[iit,id0],NewEOS.rho[id0])\n    #print(iit,NewEOS.onebar.rho[iit],NewEOS.onebar.T[iit],NewEOS.onebar.S[iit]*1.E3)\n\n```\n\n    Done loading ANEOS files.\n    ANEOS WAS CALLED WITH THE FOLLOWING INPUT, LOADED FROM FILE  ANEOS.INPUT\n     *Nakajima & Stevenson (2014,2015), Emsenhuber et al. 2018, Canup 2004, 2008, 2012, Canup et al. 2013, Barr 2016\n     *         EOS#      string for EOS name           .....Hugoniot initial........ long\n     *                                                 T(eV)           Rho(g/cc)     flag\n     ANEOS1    -1        'IRON WITH MELT CURVE'        THUG=-1         RHUG=-1\n    \n     *\n     *         nelem     type      rho0      temp0(K)  press0    B0/-Cbulk Gamma0    Tdebye(K)\n     *         V01       V02       V03       V04       V05       V06       V07       V08\n     ANEOS2    1         4         7.85      0.        0.        1.45E12   1.69      0.\n    \n     *         TG model  Gamma     Esep      Tmelt(K)  ..Critical Pt..     Thermal Conduction\n     *         or S1     3*C24     erg/g     or -Em    C53       C54       H0        C41\n     *         V09       V10       V11       V12       V13       V14       V15       V16\n     ANEOS3    0         2.        8.2E10    1809.     0.        0.        0.0       0.0\n    \n     *         solid     .....Solid-solid phase transition data.....                 rhol/rhos\n     *         rhomin    D1        D2        D3        D4        D5        Hfusion   or -rholiq\n     *         V17       V18       V19       V20       V21       V22       V23       V24\n     ANEOS4    0         0         0         0         0         0         2.471E9   0.955\n    \n     *\n     *         Elements in material (number must = nelem)\n     *         Z         Atomic Fraction\n     ANEOS8    26        1.0\n    \n    READING DATA FROM ANEOS OUTPUT FILE  ANEOS.OUTPUT\n\n\n\n```python\n# Make a NOTENSION TABLE and GADGET TABLE\n################### REMOVE TENSION REGION ###########################\n## The GADGET2 tables do not have a tension region. \n## If the gadget2 table is selected, then must generate a no-tension table\nif MAKEGADGETTABLE:\n    REMOVETENSIONFLAG=1  # 0- keep tension region; 1- remove tension region\n\n# minimum pressure 1.E-30\n# minimum sp energy about 1.E-4 before negative entropy region\n# minimum sp entropy about 1.E-5 before negative entropy region\n# minimum HFE about 1.E-3 before negative entropy region\n# minimum sound speed about 1.E-10 before negative entropy region\n# minimum sp heat capacity about 1.E-4 before negative entropy region\n\n## FUTURE WORK: THIS SECTION COULD USE THE LEVER RULE TO FILL IN THE MISSING POINTS\n## SINCE MANY VALUES ARE NEAR THE LOWER LIMITS IN THE SUBLIMATION REGION ANYWAY, \n## HERE, TENSION REGION VALUES ARE FILLED IN WITH THE ADJACENT S-V DOME VALUES\n## This is obviously bad for interpolations. Fix for future work.\nif REMOVETENSIONFLAG:\n    # First make a deep copy of the original table with the tension region\n    NewEOSorig = deepcopy(NewEOS)\n    NewEOS.MODELNAME = NewEOS.MODELNAME+'notension'\n    # THIS SECTION REWRITES NEGATIVE PRESSURE REGION\n    # The tension region is in the solid-vapor phase boundary. \n    # Use the liquid-vapor phase boundary. Below the temperature of the triple point, it is the sublimation curve.\n    # But the pressures for the solid calculation is spurious at very low pressures, so use the vapor pressure.\n    # HFE = GFE + TS\n    print('REMOVING TENSION REGION FROM THE ORIGINAL ANEOS TABLE.')\n    for itt in range(NewEOS.NT-1,-1,-1):\n        tmp = np.where(NewEOS.P[itt,:] < 0.)\n        if (len(tmp[0]) > 0):\n            badind = tmp[0]\n            if badind[0] > 0:\n                #print(itt, len(badind), NewEOS.T[itt], 'tension only', NewEOS.P[itt,badind[0]-4:badind[0]+1])\n                # at this temperature, all densities are the same pressure in the vapor dome\n                # so use the adjacent positive pressure value\n                # do the same for all the variables since there is very little change in this region of the dome.\n                # Errors introduced by interpolating the vapor curve are comparable to\n                # recalculating the lever rule. Would need to call ANEOS again to get good end point values\n                # to calculate the mass-weighted value via the lever rule.\n                NewEOS.P[itt,badind] = np.full(len(badind),NewEOS.P[itt,badind[0]-1])\n                NewEOS.U[itt,badind] = np.full(len(badind),NewEOS.U[itt,badind[0]-1])\n                NewEOS.S[itt,badind] = np.full(len(badind),NewEOS.S[itt,badind[0]-1])\n                NewEOS.A[itt,badind] = np.full(len(badind),NewEOS.A[itt,badind[0]-1])\n                NewEOS.cs[itt,badind] = np.full(len(badind),NewEOS.cs[itt,badind[0]-1])\n                NewEOS.cv[itt,badind] = np.full(len(badind),NewEOS.cv[itt,badind[0]-1])\n                NewEOS.KPA[itt,badind] = np.full(len(badind),2)\n                NewEOS.MDQ[itt,badind] = np.full(len(badind),-1) # replaced tension region flag\n            else:\n                print('SOMETHING VERY WRONG WITH TENSION IN THE TABLE')\n                makethecodestop # please tell me a more graceful way to stop the notebook\n    #\n    # THIS SECTION RESETS NEGATIVE SPECIFIC ENTROPIES WITH ADJACENT VALUES OR MINIMUM POSITIVE VALUES\n    # THESE VALUES TYPICALLY DEFINE THE COLD COMPRESSION LIMIT OF THE MATERIAL\n    # OR SPURIOUS NEGATIVE ENTROPIES AT VERY LOW PRESSURES (IMPERFECT DEBYE MODEL IN ANEOS)\n    for itt in range(NewEOS.NT-1,-1,-1):\n        tmp = np.where(NewEOS.S[itt,:] < 0.)\n        if (len(tmp[0]) > 0):\n            badind = tmp[0]\n            if badind[0] > 0:\n                #print(itt, antarr[itt], andarr[badind[0]], badind[0],len(badind),'negative entropy', ansarr[itt,badind[0]],ansarr[itt,badind[0]-1])\n                NewEOS.P[itt,badind] = np.full(len(badind),NewEOS.P[itt,badind[0]-1]) # use the adjacent pressure at this temperature in the dome\n                NewEOS.U[itt,badind] = np.full(len(badind),NewEOS.U[itt,badind[0]-1])\n                NewEOS.S[itt,badind] = np.full(len(badind),NewEOS.S[itt,badind[0]-1])\n                NewEOS.A[itt,badind] = np.full(len(badind),NewEOS.A[itt,badind[0]-1])\n                NewEOS.cs[itt,badind] = np.full(len(badind),NewEOS.cs[itt,badind[0]-1])\n                NewEOS.cv[itt,badind] = np.full(len(badind),NewEOS.cv[itt,badind[0]-1])\n                #NewEOS.KPA[itt,badind]  # leave as original region flag\n                NewEOS.MDQ[itt,badind] = np.full(len(badind),-2) # negative entropies flag\n                #print('Some NEGATIVE  S AT THIS INDEX, TEMP(K): ',itt, NewEOS.T[itt],NewEOS.P[itt,badind[0]-1],NewEOS.P[itt,badind[0]-2]) #, badind[0],len(badind),'negative entropy', NewEOS.S[itt,badind[0]])\n            if badind[0] == 0:\n                print('All S VALUES NEGATIVE AT THIS INDEX, TEMP(K): ',itt, NewEOS.T[itt]) #, badind[0],len(badind),'negative entropy', NewEOS.S[itt,badind[0]])\n                NewEOS.S[itt,badind] = np.full(len(badind),1.E-10)            \n                NewEOS.U[itt,badind] = np.full(len(badind),1.E-10) # also replace the negative sp. internal energies           \n                NewEOS.MDQ[itt,badind] = np.full(len(badind),-2) # negative entropies flag\n\n    #### ONLY WRITE A NEW TABLE IN DEVELOPMENT MODE\n    if DEVMODE:\n        #### WRITE NEW SESAME TABLE WITH NO TENSION REGION\n        #     WRITE STANDARD (SHORT) SESAME FILE\n        #     WRITE SESAME TABLE TO FILE LIMITED TO P, E, HFE\n        NewEOS.writestdsesame(writestdsesfname=\"NEW-SESAME-STD-NOTENSION.TXT\")\n\n#### ONLY WRITE A NEW TABLE IN DEVELOPMENT MODE\n#if DEVMODE:\n#    #### WRITE MDQ Flag as a 301-style table\n#    NewEOS.writemdqsesame(writemdqsesfname=\"NEW-SESAME-MDQ.TXT\")\n#\n#--------------------------------------------------------------------------\n########## MAKE GADGET2 EOS TABLE ARRAYS ###################\n# LATER WE CAN TURN THIS INTO A FUNCTION IN THE GADGET EOS OBJECT\n# FLAG IS SET ABOVE IN THE USER INPUT SECTION\n# MAKEGADGETTABLE = 1 # 1 - do it ; 0 - skip it\nif MAKEGADGETTABLE:\n    print('Starting interpolation for GADGET table.')\n    GadEOS  = extGADtable() # make new empty Gadget EOS object\n    #\n    # rho array is andarr to match the SESAME table\n    # S array is gridsarr\n    GadEOS.ND  = len(gridrarr)\n    GadEOS.NS  = len(gridsarr)\n    GadEOS.rho = gridrarr\n    GadEOS.S   = gridsarr\n    GadEOS.P   = np.zeros((GadEOS.NS,GadEOS.ND))\n    GadEOS.T   = np.zeros((GadEOS.NS,GadEOS.ND))\n    GadEOS.U   = np.zeros((GadEOS.NS,GadEOS.ND))\n    GadEOS.A   = np.zeros((GadEOS.NS,GadEOS.ND))\n    GadEOS.cs  = np.zeros((GadEOS.NS,GadEOS.ND))\n    GadEOS.cv  = np.zeros((GadEOS.NS,GadEOS.ND))\n    GadEOS.KPA = np.zeros((GadEOS.NS,GadEOS.ND))\n    GadEOS.MDQ = np.zeros((GadEOS.NS,GadEOS.ND))\n    GadEOS.MODELNAME = NewEOS.MODELNAME+'-gadget-linear-int'\n    #\n    # some combinations of density and sp. entropy are not in the EOS surface\n    # in these cases, apply minimum values\n    gadpmin  = np.min(NewEOS.P) # GPa\n    gadsmin  = 1.E-30     # MJ/K/kg\n    gademin  = np.min(NewEOS.U)    # MJ/kg\n    gadtmin  = 1.     # K\n    gadcmin  = np.min(NewEOS.cs) # cm/s\n    gadcvmin = 0.     # MJ/K/kg\n    gadamin  = np.min(NewEOS.A) # can be negative    # MJ/kg\n    print('Minimum values used in the rational function interpolation scheme:')\n    print('gadpmin,gadsmin,gademin,gadtmin,gadcmin,gadcvmin,gadamin=')\n    print(gadpmin,gadsmin,gademin,gadtmin,gadcmin,gadcvmin,gadamin)\n    #\n    # some combinations of density and sp. entropy are not in the EOS surface\n    # in these cases, fill the region with the adjacent real values from the original T-RHO table\n    # ----------------------------------------------------------\n    # SIMPLE LINEAR INTERPOLATION TO FLIP T-RHO to S-RHO table\n    print(\"LINEAR INTERPOLATION FOR GADGET TABLE.\")\n    for iid in range(0,GadEOS.ND):\n        # same density arrays for the T-rho table and S-rho table\n        sall1d = NewEOS.S[:,iid]\n        pall1d = NewEOS.P[:,iid]\n        eall1d = NewEOS.U[:,iid]\n        tall1d = NewEOS.T[:]\n        call1d = NewEOS.cs[:,iid]\n        cvall1d = NewEOS.cv[:,iid]\n        aall1d = NewEOS.A[:,iid]\n        kall1d = NewEOS.KPA[:,iid]\n        mdqall1d = NewEOS.MDQ[:,iid]\n        # interpolate P at the new S\n        testinterp = interpolate.interp1d(sall1d,pall1d)\n        tmpind = np.where(gridsarr < np.max(sall1d))[0]\n        GadEOS.P[tmpind,iid] = testinterp(gridsarr[tmpind])\n        tmpind = np.where(gridsarr >= np.max(sall1d))[0]\n        GadEOS.P[tmpind,iid] = pall1d[NewEOS.NT-1]\n        # interpolate E at the new S\n        testinterp = interpolate.interp1d(sall1d,eall1d)\n        tmpind = np.where(gridsarr < np.max(sall1d))[0]\n        GadEOS.U[tmpind,iid] = testinterp(gridsarr[tmpind])\n        tmpind = np.where(gridsarr >= np.max(sall1d))[0]\n        GadEOS.U[tmpind,iid] = eall1d[NewEOS.NT-1]\n        # interpolate T at the new S\n        testinterp = interpolate.interp1d(sall1d,tall1d)\n        tmpind = np.where(gridsarr < np.max(sall1d))[0]\n        GadEOS.T[tmpind,iid] = testinterp(gridsarr[tmpind])\n        tmpind = np.where(gridsarr >= np.max(sall1d))[0]\n        GadEOS.T[tmpind,iid] = tall1d[NewEOS.NT-1]\n        # interpolate sound speed at the new S\n        testinterp = interpolate.interp1d(sall1d,call1d)\n        tmpind = np.where(gridsarr < np.max(sall1d))[0]\n        GadEOS.cs[tmpind,iid] = testinterp(gridsarr[tmpind])\n        tmpind = np.where(gridsarr >= np.max(sall1d))[0]\n        GadEOS.cs[tmpind,iid] = call1d[NewEOS.NT-1]\n        # interpolate sp. heat capacity at the new S\n        testinterp = interpolate.interp1d(sall1d,cvall1d)\n        tmpind = np.where(gridsarr < np.max(sall1d))[0]\n        GadEOS.cv[tmpind,iid] = testinterp(gridsarr[tmpind])\n        tmpind = np.where(gridsarr >= np.max(sall1d))[0]\n        GadEOS.cv[tmpind,iid] = call1d[NewEOS.NT-1]\n        # interpolate HFE at the new S\n        testinterp = interpolate.interp1d(sall1d,aall1d)\n        tmpind = np.where(gridsarr < np.max(sall1d))[0]\n        GadEOS.A[tmpind,iid] = testinterp(gridsarr[tmpind])\n        tmpind = np.where(gridsarr >= np.max(sall1d))[0]\n        GadEOS.A[tmpind,iid] = call1d[NewEOS.NT-1]\n        # interpolate phase information KPA flag at the new S\n        testinterp = interpolate.interp1d(sall1d,kall1d)\n        tmpind = np.where(gridsarr < np.max(sall1d))[0]\n        GadEOS.KPA[tmpind,iid] = testinterp(gridsarr[tmpind])\n        tmpind = np.where(gridsarr >= np.max(sall1d))[0]\n        GadEOS.KPA[tmpind,iid] = call1d[NewEOS.NT-1]\n        # interpolate model development quality flag at the new S\n        testinterp = interpolate.interp1d(sall1d,mdqall1d)\n        tmpind = np.where(gridsarr < np.max(sall1d))[0]\n        GadEOS.MDQ[tmpind,iid] = testinterp(gridsarr[tmpind])\n        tmpind = np.where(gridsarr >= np.max(sall1d))[0]\n        GadEOS.MDQ[tmpind,iid] = call1d[NewEOS.NT-1]\n    #\n    GadEOSlin = deepcopy(GadEOS)\n    #\n    '''\n    # ----------------------------------------------------------\n    # 1D RATIONAL FUNCTION INTERPOLATION METHOD FROM KERLEY\n    print(\"RATIONAL FUNCTION INTERPOLATION TO GENERATE GADGET2 EOS TABLE.\")\n    for iid in range(0,GadEOS.ND):\n        GadEOS.MODELNAME = NewEOS.MODELNAME+'-gadget-ratfunc-int'\n        #\n        # same density arrays for the T-rho table and S-rho table\n        sall1d  = NewEOS.S[:,iid]\n        pall1d  = NewEOS.P[:,iid]\n        eall1d  = NewEOS.U[:,iid]\n        tall1d  = NewEOS.T[:]\n        call1d  = NewEOS.cs[:,iid]\n        cvall1d = NewEOS.cv[:,iid]\n        aall1d  = NewEOS.A[:,iid]\n        #kall1d = NewEOS.KPA[:,iid]\n        #mdqall1d = NewEOS.MDQ[:,iid]\n        #\n        # interpolate P at the new S\n        GadEOS.P[:,iid] = rf1d(sall1d,pall1d,gridsarr,gadpmin)\n        # interpolate E at the new S\n        GadEOS.U[:,iid] = rf1d(sall1d,eall1d,gridsarr,gademin)\n        # interpolate T at the new S\n        GadEOS.T[:,iid] = rf1d(sall1d,tall1d,gridsarr,gadtmin)\n        # interpolate sound speed at the new S\n        GadEOS.cs[:,iid] = rf1d(sall1d,call1d,gridsarr,gadcmin)\n        # interpolate sp. heat capacity at the new S\n        GadEOS.cv[:,iid] = rf1d(sall1d,cvall1d,gridsarr,gadcvmin)\n        # interpolate HFE at the new S\n        GadEOS.A[:,iid] = rf1d(sall1d,aall1d,gridsarr,gadamin)\n        # Do not interpolate KPA or MDQ with rational function interp. Use Linear.\n        # do not overwrite the linear interpolation above.\n    '''\n    #\n    print('Done interpolating the gadget2 table.')\n    #print('Using RATIONAL FUNCTION INTERPOLATION EXCEPT FOR KPA and MDQ FLAGS (bilinear).')\n    if DEVMODE:\n        # ONLY WRITE GADGET2 TABLE TO DISK IN DEVELOPMENT MODE\n        #### WRITE NEW GADGET2 TABLE WITH NO TENSION REGION\n        #### This ascii table format follows the sesame table format of 5 columns of numbers in 16.8e format\n        #### the STYLE variable is just a counter to 5 to know when to write a newline\n        GadEOS.writestdgadget(writestdgadgetfname=\"NEW-GADGET-STD-NOTENSION.TXT\")\n        GadEOS.writeextgadget(writeextgadgetfname=\"NEW-GADGET-EXT-NOTENSION.TXT\")\n\n```\n\n\n```python\n# READ IN FORSTERITE MATERIAL DATA SETS\ndatadir='../data/'\n#======================================================================\n#======================================================================\n# Gather some experimental and theoretical data on forsterite\n\nironSTP_S = 0.489211596E-3 # sp. entropy MJ/K/kg JANAF STP value\n\n# iron 1 bar entropy Desai 1986\n#T (K), Cp (J/mol/K), dH0 (J/mol), S (J/mol/K)\nDesai_file=datadir+'tabula-Desai-Table2.csv'\nDesai_datarr = pd.read_csv(Desai_file,nrows=67)\nDesai_tarr = Desai_datarr.iloc[:,0].values # temp K\nDesai_sarr = Desai_datarr.iloc[:,3].values/55.847+0.489211596 # sp. entropy J/mol/K->kJ/kg/K offset by JANAF STP value\n\n# iron 1 bar liquid density Assael et al. PCRD 2006 Table 3\n# T(K), density (kg/m3)\nAssael_file=datadir+'tabula-Assael-Table3.csv'\nAssael_datarr = pd.read_csv(Assael_file,nrows=15)\nAssael_tarr = Assael_datarr.iloc[:,0].values # temp K\nAssael_rarr = Assael_datarr.iloc[:,1].values # rho kg/m3\n\n# Iron alloy solidus Fe-16Si from Fischer et al. 2012 in Fig 1.2A from Fischer AGU 2016\nFischer_file=datadir+'Fischer-Fig1.2-AFischer-lower.csv'\nFischer_datalow = pd.read_csv(Fischer_file,skiprows=1)\nFischer_file=datadir+'Fischer-Fig1.2-AFischer-upper.csv'\nFischer_datahigh = pd.read_csv(Fischer_file,skiprows=1)\n\n# Kraus et al. Nature Geoscience 2015\n# Entropy tie point on the Hugoniot\nZtie_p=507. # GPa\nZtie_perrlow=-85. # GPa\nZtie_perrhigh=+65. # GPa\nZtie_s=2240.E-6 # MJ/K/kg\nZtie_serr=60.E-6 # MJ/K/kg\n\n# http://www.ihed.ras.ru/rusbank/\n# iron data compilation REFERENCES ARE LISTED AT THE END OF THE FILE\n# m [rho0/rho], U=part vel(km/s), D = shockvel(km/s), P (GPa)\nihed_rho0=7.873\nihed_file=datadir+'iron-Russian-shockwave-database.txt'\nihed_datarr = np.loadtxt(ihed_file,skiprows=4,usecols=(0,1,2,3,4),max_rows=571)\nihed_fullden = np.where(ihed_datarr[:,0] == 1.)[0]\n#ihed_datarr.shape\n#print(ihed_datarr[ihed_fullden,3])\n#print(max(ihed_datarr[ihed_fullden,3]))\n\n# http://www.ihed.ras.ru/rusbank/\n# iron data compilation REFERENCES ARE LISTED AT THE END OF THE FILE\n#    m        U        D        Cs          P        R/R0      R          E-E0   Rem  Ref\nihed_file=datadir+'iron-Russian-database-cs.txt'\nihed_csarr = np.loadtxt(ihed_file,skiprows=4,usecols=(0,1,2,3,4,5,6),max_rows=9)\n#ihed_datarr.shape\n#print(ihed_csarr[:,3])\n#print(max(ihed_datarr[ihed_fullden,3]))\n\n# http://www.ihed.ras.ru/rusbank/\n# iron data compilation REFERENCES ARE LISTED AT THE END OF THE FILE\n#    m        U0       P0       U        P     Rem  Ref\nihed_file=datadir+'iron-Russian-database-rel.txt'\nihed_relarr = np.loadtxt(ihed_file,skiprows=4,usecols=(0,1,2,3,4),max_rows=20)\n#ihed_datarr.shape\n#print(ihed_relarr[:,3])\n#print(max(ihed_datarr[ihed_fullden,3]))\n\n# Sjostrom & Crockett 2018 Hugoniot equation from their paper; temperature equation has a problem\nscironuparr = np.arange(300)/300.*30. # km/s\nscironusarr = 3.7885 + 1.25524*scironuparr + 0.518106*scironuparr*np.exp(-0.0866344*scironuparr) # km/s\nscironparr = 7.874*(scironuparr)*(scironusarr) # GPa\nscironrarr = 1./((1./7874.)*(1.-scironuparr/scironusarr))/1.e3 # g/cm3\n#scirontarr = 1.24182E-3*scironparr+2.80723E-6*np.power(scironparr,2.)-1.31703E-9*np.power(scironparr,3.)+1.88449E-13*np.power(scironparr,4.)*11604. # K\n\n# Kraus et al. 2015 fit Hugoniot SOM Equation 7\nkrausironuparr = (np.arange(200)+1)/200.*20. # km/s\nkrausironusarr = 3.41 + 1.84*krausironuparr - 0.036*krausironuparr*krausironuparr # km/s\nkrausironparr = 7854.*(krausironuparr)*(krausironusarr)/1.e3 # GPa\nkrausironrarr = 1./((1./7854.)*(1.-krausironuparr/krausironusarr))/1.e3 # g/cm3\nkrausironsarr = -1.984e4/np.sqrt(krausironparr) + 39.9*np.sqrt(krausironparr)-0.1047*krausironparr+2279.\nkrausironsuarr = -1.845e4/np.sqrt(krausironparr) + 45.7*np.sqrt(krausironparr)-0.1193*krausironparr+2270.\nkrausironslarr = -2.631e4/np.sqrt(krausironparr) + 22.33*np.sqrt(krausironparr)-0.007689*krausironparr+2804.\n\nkrausliqrho = 6.01 # g/cm3 1 bar boiling point, 3133 K Kraus et al. 2015 SOM Equation 6\nkrausironliqusarr = 0.79 + 0.50*krausliqrho + (1.19 + 0.0307*krausliqrho)*krausironuparr # km/s\nkrausironliqparr = krausliqrho*(krausironuparr)*(krausironliqusarr) # GPa\nkrausironliqrarr = 1./((1./krausliqrho)*(1.-krausironuparr/krausironliqusarr)) # g/cm3\nironliq_r0=krausliqrho\nironliq_t0=3133.\n\n\n```\n\n## Color mesh plots of the SESAME Rho-T table\n\n\n\n```python\n# PLOT COLOR SHADED VALUES RHO-T TABLE\nlw=1\nsfont = 15\nds = (10,10)\n\n%matplotlib inline\nfig, ([ax0, ax1], [ax2,ax3], [ax4,ax5])= plt.subplots(nrows=3,ncols=2,figsize=(14,24))\nplt.subplots_adjust(wspace=0.4)\n#plt.tight_layout(pad=0.6)\n\n##================ Pressure\nim1=ax0.pcolormesh(NewEOS.rho,NewEOS.T,(np.log10(NewEOS.P)+25)/29.,cmap=local_cmaps.parula,vmin=0,vmax=1,edgecolors='face')\nax0.plot(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax0.plot(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax0.plot(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax0.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax0.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax0.set_ylim(0.,20000)\nax0.set_xlim(0,30.)\nax0.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax0.set_ylabel('Temperature (K)',size=sfont)\nax0.set_title('Colors=log$_{10}$(P (GPa))',size=sfont)\nax0.tick_params(labelsize=sfont)\n\ndivider0 = make_axes_locatable(ax0)\ncax0 = divider0.append_axes('right', size='5%', pad=0.05)\ncbar0 = fig.colorbar(im1, cax=cax0, ticks = [],orientation='vertical')\n#cbar0.ax.set_yticklabels(['  ','  ','  '])  # vertical colorbar\ncbar0.set_label('Log$_{10}$(P) [GPa]',size=sfont)\n#cbar0.ax.set_yticklabels(['-25','-11','+4'])  # vertical colorbar\n\nim1=ax1.pcolormesh(NewEOS.rho,NewEOS.T,(np.log10(NewEOS.P)+25)/29.,cmap=local_cmaps.parula,vmin=0,vmax=1,edgecolors='face')\nax1.loglog(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax1.loglog(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax1.loglog(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax1.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax1.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax1.set_ylim(10.,1.E7)\nax1.set_xlim(1.E-21,100.)\nax1.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax1.set_ylabel('Temperature (K)',size=sfont)\nax1.set_title('Colors=log$_{10}$(P (GPa))',size=sfont)\nax1.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax1)\ncax = divider.append_axes('right', size='5%', pad=0.05)\ncbar = fig.colorbar(im1, cax=cax, ticks = [0, 0.5, 1], orientation='vertical')\ncbar.ax.set_yticklabels(['-25','-11', '+4'])  # vertical colorbar\ncbar.set_label('Log$_{10}$(P) [GPa]',size=sfont)\n\n\n#================ Sp. Int. Energy\nim1=ax2.pcolormesh(NewEOS.rho,NewEOS.T,(np.log10(NewEOS.U)+4.)/10.,cmap=local_cmaps.parula,vmin=0,vmax=1,edgecolors='face')\nax2.plot(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax2.plot(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax2.plot(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax2.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax2.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax2.set_ylim(0.,20000)\nax2.set_xlim(0,30.)\nax2.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax2.set_ylabel('Temperature (K)',size=sfont)\nax2.set_title('Colors=log$_{10}$(Sp. Int. Energy (MJ/kg))',size=sfont)\nax2.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax2)\ncax = divider.append_axes('right', size='5%', pad=0.05)\n# does not want to label ticks in this location\ncbar = fig.colorbar(im1, cax=cax, ticks = [], orientation='vertical')\n#cbar.ax.set_yticklabels(['','',''])  # vertical colorbar\ncbar.set_label('Log$_{10}$(E) [MJ/kg]',size=sfont)\n#cbar.ax.set_yticklabels(['-4','+1','+6'])  # vertical colorbar\n\n\nax3.pcolormesh(NewEOS.rho,NewEOS.T,(np.log10(NewEOS.U)+4.)/10.,cmap=local_cmaps.parula,vmin=0,vmax=1)\nax3.loglog(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax3.loglog(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax3.loglog(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax3.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax3.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax3.set_ylim(10.,1.E7)\nax3.set_xlim(1.E-21,100.)\nax3.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax3.set_ylabel('Temperature (K)',size=sfont)\nax3.set_title('Colors=log$_{10}$(E (MJ/kg))',size=sfont)\nax3.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax3)\ncax = divider.append_axes('right', size='5%', pad=0.05)\n#cbar = fig.colorbar(im1, cax=cax, ticks = [0, 0.5, 1], orientation='vertical')\n#cbar.ax.set_yticklabels(['-6', '-3.5', '-1'])  # vertical colorbar\ncbar = fig.colorbar(im1, cax=cax, ticks = [0, 0.5, 1], orientation='vertical')\ncbar.ax.set_yticklabels(['-4', '+1','+6'])  # vertical colorbar\ncbar.set_label('Log$_{10}$(E) [MJ/kg]',size=sfont)\n\n#================ Sp. Entropy\nim1=ax4.pcolormesh(NewEOS.rho,NewEOS.T,(np.log10(NewEOS.S)+4.)/4.,cmap=local_cmaps.parula,vmin=0,vmax=1,edgecolors='face')\nax4.plot(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax4.plot(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax4.plot(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax4.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax4.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax4.set_ylim(0.,20000)\nax4.set_xlim(0,30.)\nax4.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax4.set_ylabel('Temperature (K)',size=sfont)\nax4.set_title('Colors=log$_{10}$(Sp. Entropy (MJ/K/kg))',size=sfont)\nax4.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax4)\ncax = divider.append_axes('right', size='5%', pad=0.05)\ncbar = fig.colorbar(im1, cax=cax, ticks = [], orientation='vertical')\n#cbar.ax.set_yticklabels(['-4', '-2', '0'])  # vertical colorbar\ncbar.set_label('Log$_{10}$(S) [MJ/K/kg]',size=sfont)\n\n\nax5.pcolormesh(NewEOS.rho,NewEOS.T,(np.log10(NewEOS.S)+4.)/4.,cmap=local_cmaps.parula,vmin=0,vmax=1)\nax5.loglog(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax5.loglog(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax5.loglog(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax5.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax5.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax5.set_ylim(10.,1.E7)\nax5.set_xlim(1.E-21,100.)\nax5.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax5.set_ylabel('Temperature (K)',size=sfont)\nax5.set_title('Colors=log$_{10}$(Sp. Entropy (MJ/K/kg))',size=sfont)\nax5.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax5)\ncax = divider.append_axes('right', size='5%', pad=0.05)\n#cbar = fig.colorbar(im1, cax=cax, ticks = [0, 0.5, 1], orientation='vertical')\n#cbar.ax.set_yticklabels(['-6', '-3.5', '-1'])  # vertical colorbar\ncbar = fig.colorbar(im1, cax=cax, ticks = [0, 0.5, 1], orientation='vertical')\ncbar.ax.set_yticklabels(['-4', '-2','0'])  # vertical colorbar\ncbar.set_label('Log$_{10}$(S) [MJ/K/kg]',size=sfont)\n\n\n##============= start new plot\nfig2, ([ax0, ax1], [ax2,ax3], [ax4,ax5])= plt.subplots(nrows=3,ncols=2,figsize=(14,24))\nplt.subplots_adjust(wspace=0.4)\n\n#================ Sound Speed\nim1=ax0.pcolormesh(NewEOS.rho,NewEOS.T,(np.log10(NewEOS.cs)+3.)/10.,cmap=local_cmaps.parula,vmin=0,vmax=1,edgecolors='face')\nax0.plot(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax0.plot(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax0.plot(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax0.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax0.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax0.set_ylim(0.,20000)\nax0.set_xlim(0,30.)\nax0.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax0.set_ylabel('Temperature (K)',size=sfont)\nax0.set_title('Colors=log$_{10}$(Sound Speed (cm/s))',size=sfont)\nax0.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax0)\ncax = divider.append_axes('right', size='5%', pad=0.05)\ncbar = fig.colorbar(im1, cax=cax, ticks = [], orientation='vertical')\n#cbar.ax.set_yticklabels(['-3', '+2', '+7'])  # vertical colorbar\ncbar.set_label('Log$_{10}$(Cs) [cm/s]',size=sfont)\n\n\nax1.pcolormesh(NewEOS.rho,NewEOS.T,(np.log10(NewEOS.cs)+3.)/10.,cmap=local_cmaps.parula,vmin=0,vmax=1)\nax1.loglog(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax1.loglog(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax1.loglog(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax1.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax1.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax1.set_ylim(10.,1.E7)\nax1.set_xlim(1.E-21,100.)\nax1.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax1.set_ylabel('Temperature (K)',size=sfont)\nax1.set_title('Colors=log$_{10}$(sound speed (cm/s))',size=sfont)\nax1.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax1)\ncax = divider.append_axes('right', size='5%', pad=0.05)\n#cbar = fig.colorbar(im1, cax=cax, ticks = [0, 0.5, 1], orientation='vertical')\n#cbar.ax.set_yticklabels(['-6', '-3.5', '-1'])  # vertical colorbar\ncbar = fig.colorbar(im1, cax=cax, ticks = [0, 0.5, 1], orientation='vertical')\ncbar.ax.set_yticklabels(['-3', '+2', '+7'])  # vertical colorbar\ncbar.set_label('Log$_{10}$(Cs) [cm/s]',size=sfont)\n\n\n#================ HFE\namin = np.min(NewEOS.A)\namin = -1000.\nalogmax = 1500. #np.max(anaarrodd)-amin #np.max(np.log10(anaarrodd-amin))\n#print('amin, log10(amin)',amin,np.log10(-amin))\n#print('alogmax=',alogmax)\nim1=ax2.pcolormesh(NewEOS.rho,NewEOS.T,(NewEOS.A-amin)/alogmax,cmap=local_cmaps.parula,vmin=0,vmax=1,edgecolors='face')\nax2.plot(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax2.plot(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax2.plot(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax2.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax2.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax2.set_ylim(0.,20000)\nax2.set_xlim(0,30.)\nax2.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax2.set_ylabel('Temperature (K)',size=sfont)\nax2.set_title('Colors=HFE (MJ/kg)',size=sfont)\nax2.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax2)\ncax = divider.append_axes('right', size='5%', pad=0.05)\ncbar = fig.colorbar(im1, cax=cax, ticks = [], orientation='vertical')\n#cbar.ax.set_yticklabels(['-1000','-500','0','500'])  # vertical colorbar\ncbar.set_label('Log$_{10}$(HFE) [MJ/kg]',size=sfont)\n\n\nax3.pcolormesh(NewEOS.rho,NewEOS.T,(NewEOS.A-amin)/alogmax,cmap=local_cmaps.parula,vmin=0,vmax=1)\nax3.loglog(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax3.loglog(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax3.loglog(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax3.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax3.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax3.set_ylim(10.,1.E7)\nax3.set_xlim(1.E-21,100.)\nax3.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax3.set_ylabel('Temperature (K)',size=sfont)\nax3.set_title('Colors=HFE (MJ/kg)',size=sfont)\nax3.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax3)\ncax = divider.append_axes('right', size='5%', pad=0.05)\n#cbar = fig.colorbar(im1, cax=cax, ticks = [0, 0.5, 1], orientation='vertical')\n#cbar.ax.set_yticklabels(['-6', '-3.5', '-1'])  # vertical colorbar\ncbar = fig.colorbar(im1, cax=cax, ticks = [0,.333,.6667,  1], orientation='vertical')\ncbar.ax.set_yticklabels(['-1000','-500','0','500'])  # vertical colorbar\ncbar.set_label('Log$_{10}$(HFE) [MJ/kg]',size=sfont)\n\n\n\n#================ KPA flag\ncmap2 = cm.get_cmap('plasma', 6)    # 6 discrete colors\n\nim1=ax4.pcolormesh(NewEOS.rho,NewEOS.T,((NewEOS.KPA)-0.5)/6.,cmap=cmap2,vmin=0,vmax=1,edgecolors='face')\n#im1=ax4.pcolormesh(NewEOS.rho,NewEOS.T,((NewEOS.KPA))/6.,cmap=local_cmaps.parula,vmin=0,vmax=1,edgecolors='face')\nax4.plot(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax4.plot(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax4.plot(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax4.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax4.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax4.set_ylim(0.,20000)\nax4.set_xlim(0,30.)\nax4.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax4.set_ylabel('Temperature (K)',size=sfont)\nax4.set_title('Colors=KPA flag',size=sfont)\nax4.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax4)\ncax = divider.append_axes('right', size='5%', pad=0.05)\ncbar = fig.colorbar(im1, cax=cax, ticks = [], orientation='vertical')\n#cbar.ax.set_yticklabels(['0','1','2','3','4','5',  '6'])  # vertical colorbar\ncbar.set_label('KPA Flag',size=sfont)\n\n\nax5.pcolormesh(NewEOS.rho,NewEOS.T,((NewEOS.KPA)-0.5)/6.,cmap=cmap2,vmin=0,vmax=1)\nax5.loglog(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax5.loglog(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax5.loglog(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax5.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax5.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax5.set_ylim(10.,1.E7)\nax5.set_xlim(1.E-21,100.)\nax5.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax5.set_ylabel('Temperature (K)',size=sfont)\nax5.set_title('Colors=KPA flag',size=sfont)\nax5.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax5)\ncax = divider.append_axes('right', size='5%', pad=0.05)\n#cbar = fig.colorbar(im1, cax=cax, ticks = [0, 0.5, 1], orientation='vertical')\n#cbar.ax.set_yticklabels(['-6', '-3.5', '-1'])  # vertical colorbar\ncbar = fig.colorbar(im1, cax=cax, ticks = np.arange(13)/12, orientation='vertical')\ncbar.ax.set_yticklabels(['','1','','2','','3','','4','','5','',  '6'])  # vertical colorbar\ncbar.set_label('KPA Flag',size=sfont)\n\n\nfig2.show()\n\n\n```\n\n# ANEOS Hugoniots Compared to Experimental Data\n\nThe following plots compare the ANEOS model Hugoniots with laboratory data (for nonporous and porous iron) downloaded from the shock wave database at http://ihed.ras.ru/rusbank/\n\nEntropy on the Principal Hugoniot was derived by Kraus et al. 2015.\n\nANEOS Hugoniot: red -- calculated in the ANEOS code using model reference density and temperature.\n\nCalculated Hugoniot: blue -- calculated by linear interpolation of the EOS table starting at model reference density and temperature.\n\nThe liquid Hugoniot is calculated in Kraus et al. 2015 starting at the boiling point of liquid iron at 1 bar: 6.01 g/cm$^3$, 3133 K. The ANEOS model Hugoniot is shown for comparison.\n\n\n```python\n# Display the initial conditions for the Hugoniot in ANEOS.OUTPUT    \nprint('\\nRequested ANEOS Hugoniot initial state from (THUG,RHUG) (red curves in plots below):')\nprint('Initial Pressure (GPa):',NewEOS.anhug.P[0])\nprint('Initial Temperature (K):',NewEOS.anhug.T[0])\nprint('Initial Sp. Entropy (MJ/K/kg):',NewEOS.anhug.S[0])\nprint('Initial Sp. Internal Energy (MJ/kg):',NewEOS.anhug.U[0])\nprint('Initial Density (g/cm3):',NewEOS.anhug.rho[0])\n#\nprint('\\nCalculated Hugoniot using (T0REF,R0REF) initial state (blue curves in plots below):')\nprint('Initial Pressure (GPa):',NewEOS.hug.P[0])\nprint('Initial Temperature (K):',NewEOS.hug.T[0])\nprint('Initial Sp. Entropy (MJ/K/kg):',NewEOS.hug.S[0])\nprint('Initial Sp. Internal Energy (MJ/kg):',NewEOS.hug.U[0])\nprint('Initial Density (g/cm3):',NewEOS.hug.rho[0])\n\n#========== PLOTTING STYLES FOR LOTS OF PLOTS =================\nstyleqmd = ['^','red',5,' ']\nstylezdat = ['+','black',5,'Porous Fe Hugoniot\\n(IHED)']\nstylegg = ['+','blue',5,'STP Hugoniot data\\n(IHED)']\nstyleliq = ['--','orange',7,'Liquid Fe Hugoniot\\n(Kraus et al. 2015)']\nstyleliqhug = ['-','orange',1,'ANEOS Liquid Fe Hugoniot']\nstylezfit = ['-','green',1,' ']\nstyleanhug = ['-','red',1,'ANEOS Hugoniot']\nstylestphug = ['-','blue',1,'Calculated Hugoniot']\nstyleanphase = ['-','black',1,'ANEOS Phase Boundaries']\nstylephasept = ['o','black',6]\n\n\n\n#======================LOTS OF PLOTS============================\n# plot the Hugoniots for comparison\nsfont = 15\nfig, axes = plt.subplots(nrows=3, ncols=2, figsize=(14,18))\nplt.subplots_adjust(wspace=0.4)\n\n#-------------\n# Pressure-Density Data vs. ANEOS\nai=0\naj=0\n#axes[ai,aj].plot(QMDH_r[1::],QMDH_p[1::],styleqmd[0],markersize=styleqmd[2],color=styleqmd[1],label=styleqmd[3])\n#axes[ai,aj].plot(Zdat_r,Zdat_p,stylezdat[0],markersize=stylezdat[2],color=stylezdat[1],label=stylezdat[3])\n#axes[ai,aj].plot(LowHugDat_r,LowHugDat_p,stylegg[0],markersize=stylegg[2],color=stylegg[1],label=stylegg[3])\n#axes[ai,aj].plot(Zfit_r,Zfit_p,stylezfit[0],linewidth=stylezfit[2],color=stylezfit[1],label=stylezfit[3])\naxes[ai,aj].plot(NewEOS.anhug.rho,NewEOS.anhug.P,styleanhug[0],linewidth=styleanhug[2],color=styleanhug[1],label=styleanhug[3])\naxes[ai,aj].plot(NewEOS.hug.rho,NewEOS.hug.P,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(ihed_datarr[ihed_fullden,4]*ihed_rho0,ihed_datarr[ihed_fullden,3],stylegg[0],markersize=stylegg[2],color=stylegg[1],label=stylegg[3])\naxes[ai,aj].plot(scironrarr,scironparr,'-',color='m',label='STP Hugoniot\\n(Sjostrom & Crockett 2018)')\n\n# Kraus Liquid Iron Hugoniot at 1 bar boiling point\naxes[ai,aj].plot(krausironliqrarr[40:100], krausironliqparr[40:100],styleliq[0],markersize=styleliq[2],color=styleliq[1],label=styleliq[3])\n                 #linestyle='-',color='cyan',label='Kraus et al. 2015\\n1-bar Boiling Pt. Liquid Hugoniot')\n\n# ANEOS LIQUID HUGONIOT\n# Calculate the model Hugoniot with the same initial state as Thomas & Asimow 2013\nNewEOS.calchugoniot(r0=ironliq_r0,t0=ironliq_t0)\naxes[ai,aj].plot(NewEOS.hug.rho,NewEOS.hug.P,styleliqhug[0],linewidth=styleliqhug[2],color=styleliqhug[1],label=styleliqhug[3])\n# Put the STP hugoniot back into the structure\nNewEOS.calchugoniot(r0=NewEOS.R0REF,t0=NewEOS.T0REF)\n\naxes[ai,aj].set_ylim(0,1100)\naxes[ai,aj].set_xlim(7.,16.)\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].legend(fontsize=sfont-5)\n\n#-------------\n# Pressure - Temperature Data vs. ANEOS\nai=0\naj=1\n\n#axes[ai,aj].plot(QMDH_p[1::],QMDH_t[1::]/1.E3,styleqmd[0],markersize=styleqmd[2],color=styleqmd[1],label=styleqmd[3])\n#axes[ai,aj].errorbar(ZTdat_p,ZTdat_t/1.E3,xerr=ZTdat_perr,yerr=ZTdat_terr/1.E3,fmt=stylezdat[0],markersize=stylezdat[2],color=stylezdat[1],label=stylezdat[3],elinewidth=1)\n#axes[ai,aj].plot(Zfit_p,Zfit_t/1.E3,stylezfit[0],linewidth=stylezfit[2],color=stylezfit[1],label=stylezfit[3])\naxes[ai,aj].plot(NewEOS.anhug.P,NewEOS.anhug.T/1.E3,styleanhug[0],linewidth=styleanhug[2],color=styleanhug[1],label=styleanhug[3])\naxes[ai,aj].plot(NewEOS.hug.P,NewEOS.hug.T/1.E3,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\n\n## add squares\nrect = Rectangle((240.,5.),6.,.700,linewidth=1,edgecolor='moccasin',facecolor='moccasin')\naxes[ai,aj].add_patch(rect)\naxes[ai,aj].plot(243.,5.350,'d',color='orange',label='Brown & McQueen 1986')\nrect = Rectangle((222.,4.7),6.,1.000,linewidth=1,edgecolor='moccasin',facecolor='moccasin')\naxes[ai,aj].add_patch(rect)\naxes[ai,aj].plot(225.,5.100,'o',color='orange',label='Nguyen & Holmes 2004')\n\naxes[ai,aj].set_xlim(0,500)\naxes[ai,aj].set_ylim(0,20)\naxes[ai,aj].set_ylabel('Temperature (1000 K)',size=sfont)\naxes[ai,aj].set_xlabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].legend(fontsize=sfont-5)\n\n#-------------\n# Particle Velocity vs. Shock Velocity; Data vs. ANEOS\nai=1\naj=0\n\n#axes[ai,aj].plot(QMDH_up[1::],QMDH_us[1::],styleqmd[0],markersize=styleqmd[2],color=styleqmd[1],label=styleqmd[3])\n#axes[ai,aj].errorbar(Zdat_up,Zdat_us,xerr=Zdat_uperr,yerr=Zdat_userr,fmt=stylezdat[0],markersize=stylezdat[2],color=stylezdat[1],label=stylezdat[3],elinewidth=1)\n#axes[ai,aj].plot(LowHugDat_up,LowHugDat_us,stylegg[0],markersize=stylegg[2],color=stylegg[1],label=stylegg[3])\n#axes[ai,aj].plot(Zfit_up,Zfit_us,stylezfit[0],linewidth=stylezfit[2],color=stylezfit[1],label=stylezfit[3])\naxes[ai,aj].plot(NewEOS.anhug.up,NewEOS.anhug.us,styleanhug[0],linewidth=styleanhug[2],color=styleanhug[1],label=styleanhug[3])\naxes[ai,aj].plot(NewEOS.hug.up,NewEOS.hug.us,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(ihed_datarr[ihed_fullden,1],ihed_datarr[ihed_fullden,2],stylegg[0],markersize=stylegg[2],color=stylegg[1],label=stylegg[3])\n\n#axes[ai,aj].plot(foliq_up,foliq_us,styleliq[0],markersize=styleliq[2],color=styleliq[1],label=styleliq[3])\n# ANEOS LIQUID HUGONIOT\n# Calculate the model Hugoniot with the same initial state as Thomas & Asimow 2013\n#NewEOS.calchugoniot(r0=foliq_r0,t0=foliq_t0)\n#axes[ai,aj].plot(NewEOS.hug.up,NewEOS.hug.us,styleliqhug[0],linewidth=styleliqhug[2],color=styleliqhug[1],label=styleliqhug[3])\n# Put the STP hugoniot back into the structure\n#NewEOS.calchugoniot(r0=NewEOS.R0REF,t0=NewEOS.T0REF)\n\naxes[ai,aj].set_xlim(0,11)\naxes[ai,aj].set_ylim(0,20)\naxes[ai,aj].set_xlabel('Particle Velocity (km/s)',size=sfont)\naxes[ai,aj].set_ylabel('Shock Velocity (km/s)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].legend(fontsize=sfont-5)\n\n#-------------\n# Sp. Entropy vs Pressure; Calculated from experiments vs. ANEOS\nai=1\naj=1\n\n#axes[ai,aj].plot(Zfit_p,Zfit_s*1.E3,stylezfit[0],linewidth=stylezfit[2],color=stylezfit[1],label=stylezfit[3])\n#axes[ai,aj].fill_between(Zfit_p,(Zfit_s-Zfit_serr)*1000.,(Zfit_s+Zfit_serr)*1000.,color=stylezfit[1],alpha=0.2)\n# pressure error envelope is tiny and can't be seen on this scale\n#axes[ai,aj].fill_betweenx(Zfit_s*1000.,(Zfit_p-Zfit_perr),(Zfit_p+Zfit_perr),color='red',alpha=0.2)\naxes[ai,aj].plot(NewEOS.anhug.P,NewEOS.anhug.S*1.E3,styleanhug[0],linewidth=styleanhug[2],color=styleanhug[1],label=styleanhug[3])\naxes[ai,aj].plot(NewEOS.hug.P,NewEOS.hug.S*1.E3,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\n# Tie point from Kraus et al. 2015\naxes[ai,aj].plot(Ztie_p,Ztie_s*1.E3,'o',markersize=5,color='red',label='Entropy Tie Point (Kraus et al. 2015)')\naxes[ai,aj].plot([Ztie_p+Ztie_perrlow,Ztie_p+Ztie_perrhigh],[Ztie_s*1.E3,Ztie_s*1.E3],'-',color='red')\naxes[ai,aj].plot([Ztie_p,Ztie_p],[(Ztie_s-Ztie_serr)*1.E3,(Ztie_s+Ztie_serr)*1.E3],'-',color='red')\n# Iron at STP from JANAF\naxes[ai,aj].plot(1.E-4,ironSTP_S*1.E3,'s',markersize=5,color='orange',label='STP (JANAF)')\n\ncolstr='green'\naxes[ai,aj].plot(krausironparr[40:80], krausironsarr[40:80]/1.e3, linestyle='-',color=colstr)\n#axes[ai,aj].plot(krausironparr[40:80], krausironsarr[40:80]/1.e3, linestyle='-',color=colstr,label='Kraus et al. 2015\\nLiquid Region STP Hugoniot')\n#axes[ai,aj].plot(krausironparr[40:80], krausironsuarr[40:80]/1.e3, linestyle=':',color=colstr)\n#axes[ai,aj].plot(krausironparr[40:80], krausironslarr[40:80]/1.e3, linestyle=':',color=colstr)\naxes[ai,aj].fill_between(krausironparr[40:80],krausironslarr[40:80]/1.e3,krausironsuarr[40:80]/1.e3,color='green',alpha=0.2,label='Kraus et al. 2015\\nLiquid Region STP Hugoniot')\n\n\naxes[ai,aj].set_ylim(0,4.)\naxes[ai,aj].set_xlim(0,1200)\naxes[ai,aj].set_ylabel('Specific Entropy (kJ/K/kg)',size=sfont)\naxes[ai,aj].set_xlabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].legend(fontsize=sfont-5)\n\n#-------------\n# Pressure-Density Data vs. ANEOS   LOW PRESSURE + LIQUID HUGONIOT\nai=2\naj=0\n#axes[ai,aj].plot(QMDH_r[1::],QMDH_p[1::],styleqmd[0],markersize=styleqmd[2],color=styleqmd[1],label=styleqmd[3])\n#axes[ai,aj].plot(Zdat_r,Zdat_p,stylezdat[0],markersize=stylezdat[2],color=stylezdat[1],label=stylezdat[3])\n#axes[ai,aj].plot(LowHugDat_r,LowHugDat_p,stylegg[0],markersize=stylegg[2],color=stylegg[1],label=stylegg[3])\n# Liquid forsterite Hugoniot Data\n#axes[ai,aj].plot(foliq_r,foliq_p,styleliq[0],markersize=styleliq[2],color=styleliq[1],label=styleliq[3])\n#axes[ai,aj].plot(foliq_r0,0,styleliq[0],markersize=styleliq[2],color=styleliq[1])\n#axes[ai,aj].plot(Zfit_r,Zfit_p,stylezfit[0],linewidth=stylezfit[2],color=stylezfit[1],label=stylezfit[3])\n# ANEOS REFERENCE POINT (STP) Hugoniots\naxes[ai,aj].plot(NewEOS.anhug.rho,NewEOS.anhug.P,styleanhug[0],linewidth=styleanhug[2],color=styleanhug[1],label=styleanhug[3])\naxes[ai,aj].plot(NewEOS.hug.rho,NewEOS.hug.P,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(ihed_datarr[ihed_fullden,4]*ihed_rho0,ihed_datarr[ihed_fullden,3],stylegg[0],markersize=stylegg[2],color=stylegg[1],label=stylegg[3])\n\n\n# POROUS HUGONIOT m=R0/R00=1.128\nm=1.128\ncolstr='black'\nlabstr='R0/R00=1.128 (+IHED -ANEOS)'\nihed_porous = np.where(ihed_datarr[:,0] == m)[0]\naxes[ai,aj].plot(ihed_datarr[ihed_porous,4]*ihed_rho0,ihed_datarr[ihed_porous,3],'+',markersize=5,color=colstr,label=labstr)\nNewEOS.calcporoushugoniot(r0=NewEOS.R0REF,t0=NewEOS.T0REF,r00=NewEOS.R0REF/m)\naxes[ai,aj].plot(NewEOS.hug.rho,NewEOS.hug.P,styleliqhug[0],linewidth=styleliqhug[2],color=colstr)\n# Put the STP hugoniot back into the structure\nNewEOS.calchugoniot(r0=NewEOS.R0REF,t0=NewEOS.T0REF)\n\n# POROUS HUGONIOT m=R0/R00=1.315\nm=1.315\ncolstr='green'\nlabstr='R0/R00=1.315 (+IHED -ANEOS)'\nihed_porous = np.where(ihed_datarr[:,0] == m)[0]\naxes[ai,aj].plot(ihed_datarr[ihed_porous,4]*ihed_rho0,ihed_datarr[ihed_porous,3],'+',markersize=5,color=colstr,label=labstr)\nNewEOS.calcporoushugoniot(r0=NewEOS.R0REF,t0=NewEOS.T0REF,r00=NewEOS.R0REF/m)\naxes[ai,aj].plot(NewEOS.hug.rho,NewEOS.hug.P,styleliqhug[0],linewidth=styleliqhug[2],color=colstr)\n\n# POROUS HUGONIOT m=R0/R00=1.660\nm=1.660\ncolstr='m'\nlabstr='R0/R00=1.660 (+IHED -ANEOS)'\nihed_porous = np.where(ihed_datarr[:,0] == m)[0]\naxes[ai,aj].plot(ihed_datarr[ihed_porous,4]*ihed_rho0,ihed_datarr[ihed_porous,3],'+',markersize=5,color=colstr,label=labstr)\nNewEOS.calcporoushugoniot(r0=NewEOS.R0REF,t0=NewEOS.T0REF,r00=NewEOS.R0REF/m)\naxes[ai,aj].plot(NewEOS.hug.rho,NewEOS.hug.P,styleliqhug[0],linewidth=styleliqhug[2],color=colstr)\n\n# POROUS HUGONIOT m=R0/R00=2.333\nm=2.333\ncolstr='c'\nlabstr='R0/R00=2.333 (+IHED -ANEOS)'\nihed_porous = np.where(ihed_datarr[:,0] == m)[0]\naxes[ai,aj].plot(ihed_datarr[ihed_porous,4]*ihed_rho0,ihed_datarr[ihed_porous,3],'+',markersize=5,color=colstr,label=labstr)\nNewEOS.calcporoushugoniot(r0=NewEOS.R0REF,t0=NewEOS.T0REF,r00=NewEOS.R0REF/m)\naxes[ai,aj].plot(NewEOS.hug.rho,NewEOS.hug.P,styleliqhug[0],linewidth=styleliqhug[2],color=colstr)\n\n\n# Put the STP hugoniot back into the structure\nNewEOS.calchugoniot(r0=NewEOS.R0REF,t0=NewEOS.T0REF)\n\naxes[ai,aj].set_ylim(-5,200)\naxes[ai,aj].set_xlim(5,12.)\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].legend(fontsize=sfont-5)\n\n#-------------\n# Pressure-Density Data vs. ANEOS   EXTRAPOLATED HIGH PRESSURE\nai=2\naj=1\n#axes[ai,aj].plot(QMDH_r[1::],QMDH_p[1::],styleqmd[0],markersize=styleqmd[2],color=styleqmd[1],label=styleqmd[3])\n#axes[ai,aj].plot(Zdat_r,Zdat_p,stylezdat[0],markersize=stylezdat[2],color=stylezdat[1],label=stylezdat[3])\n#axes[ai,aj].plot(LowHugDat_r,LowHugDat_p,stylegg[0],markersize=stylegg[2],color=stylegg[1],label=stylegg[3])\n#axes[ai,aj].plot(Zfit_r,Zfit_p,stylezfit[0],linewidth=stylezfit[2],color=stylezfit[1],label=stylezfit[3])\naxes[ai,aj].plot(NewEOS.anhug.rho,NewEOS.anhug.P,styleanhug[0],linewidth=styleanhug[2],color=styleanhug[1],label=styleanhug[3])\naxes[ai,aj].plot(NewEOS.hug.rho,NewEOS.hug.P,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(ihed_datarr[ihed_fullden,4]*ihed_rho0,ihed_datarr[ihed_fullden,3],stylegg[0],markersize=stylegg[2],color=stylegg[1],label=stylegg[3])\naxes[ai,aj].plot(scironrarr,scironparr,'-',color='m',label='STP Hugoniot\\n(Sjostrom & Crockett 2018)')\n\naxes[ai,aj].set_ylim(0,6200)\naxes[ai,aj].set_xlim(7.,25.)\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].legend(fontsize=sfont-5)\n\n\n\n```\n\n\n```python\n#======================LOTS OF PLOTS============================\n# plot the Hugoniots for comparison\nsfont = 15\nfig, axes = plt.subplots(nrows=1, ncols=2, figsize=(14,6))\nplt.subplots_adjust(wspace=0.4)\n\n#-------------\n# Pressure-Sound Speed Hugoniot Data vs. ANEOS\nai=0\naj=0\naxes[ai].plot(NewEOS.hug.P,NewEOS.hug.cs,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai].plot(ihed_csarr[:,4],ihed_csarr[:,3],stylegg[0],markersize=stylegg[2],color=stylegg[1],label=stylegg[3])\n\naxes[ai].set_xlim(0,400)\naxes[ai].set_ylim(4.,14.)\naxes[ai].set_ylabel('Sound speed (km/s)',size=sfont)\naxes[ai].set_xlabel('Pressure (GPa)',size=sfont)\naxes[ai].tick_params(labelsize=sfont)\naxes[ai].legend(fontsize=sfont-5)\n\n#-------------\n# Particle velocity - Pressure  Data vs. ANEOS\nai=1\naj=1\n\naxes[ai].semilogy(NewEOS.hug.up,NewEOS.hug.P,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai].plot(ihed_relarr[:,3],ihed_relarr[:,4],'s',markersize=stylegg[2],color='red',label='Partial release (IHED)')\naxes[ai].plot(ihed_relarr[:,1],ihed_relarr[:,2],'s',markersize=stylegg[2],color='red')\n\nuniqrelarr = np.unique(ihed_relarr[:,2])\nfor j in range(0,len(uniqrelarr)):\n    ptarget=uniqrelarr[j]\n    # ANEOS ISENTROPE NEAR SAME PRESSURE\n    ANEOSIsen = isentrope_class() # code in eostable.py\n    Sisen = np.interp(ptarget,NewEOS.hug.P,NewEOS.hug.S) # MJ/K/kg\n    # loop across all densities and extract the values for the requested isentrope\n    for i in range(0,NewEOS.ND):\n        ind = np.where((NewEOS.S[:,i] > 0))[0]\n        interpfunction = interpolate.interp1d(NewEOS.S[ind,i],NewEOS.P[ind,i]) # MJ/K/kg, GPa\n        ANEOSIsen.pressure = np.append(ANEOSIsen.pressure,interpfunction(Sisen)) # GPa\n        interpfunction = interpolate.interp1d(NewEOS.S[ind,i],NewEOS.T[ind]) # MJ/K/kg, GPa\n        ANEOSIsen.temperature = np.append(ANEOSIsen.temperature,interpfunction(Sisen)) # GPa\n        interpfunction = interpolate.interp1d(NewEOS.S[ind,i],NewEOS.cs[ind,i]) # MJ/K/kg, cm/s\n        ANEOSIsen.soundspeed = np.append(ANEOSIsen.soundspeed,interpfunction(Sisen)) # cm/s\n        interpfunction = interpolate.interp1d(NewEOS.S[ind,i],NewEOS.U[ind,i]) # MJ/K/kg, MJ/kg\n        ANEOSIsen.energy = np.append(ANEOSIsen.energy,interpfunction(Sisen)) # MJ/kg\n    ANEOSIsen.density = np.copy(NewEOS.rho)*1000. # kg/m3\n    ANEOSIsen.partvel = np.zeros(NewEOS.ND) # m/s\n    ir0 = int(np.round(np.where(ANEOSIsen.pressure >= ptarget)[0][0])) # go up just past the intersection with Hugoniot\n    ANEOSIsen.partvel[ir0] = np.interp(ptarget,NewEOS.hug.P,NewEOS.hug.up)*1.E3 # m/s\n    #print('ANEOS Starting Pressure:',ptarget)\n    iir=ir0-1\n    while (ANEOSIsen.pressure[iir]>.0001):\n        if iir == ir0-1:\n            dp = (ptarget - ANEOSIsen.pressure[iir])*1.E9 # Pa\n        else:\n            dp = (ANEOSIsen.pressure[iir+1]-ANEOSIsen.pressure[iir])*1.E9 # Pa\n        ANEOSIsen.partvel[iir] = ANEOSIsen.partvel[iir+1] + dp/(ANEOSIsen.density[iir]*ANEOSIsen.soundspeed[iir+1]/1.E2) # m/s\n        #print(iir,ANEOSIsen.pressure[iir],ANEOSIsen.partvel[iir]/1.e3,dp/1.e9,ANEOSIsen.density[iir])\n        iir=iir-1\n    # plot aneos isentrope\n    tmp = np.where((ANEOSIsen.pressure < ptarget)&(ANEOSIsen.pressure > .01))[0]\n    if j == 0:\n        axes[ai].plot(ANEOSIsen.partvel[tmp]/1.e3,ANEOSIsen.pressure[tmp],'--',color='blue',label='ANEOS release isentrope')\n    else:\n        axes[ai].plot(ANEOSIsen.partvel[tmp]/1.e3,ANEOSIsen.pressure[tmp],'--',color='blue')\n\naxes[ai].set_xlim(0,7)\naxes[ai].set_ylim(.01,200)\naxes[ai].set_xlabel('Particle velocity (km/s)',size=sfont)\naxes[ai].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai].tick_params(labelsize=sfont)\naxes[ai].legend(fontsize=sfont-5)\n\n\n```\n\n## Model Critical Point and Shock-Induced Phase Changes\n\n\n\n\n```python\nprint('ANEOS Calculated Critical point:')\nprint('   Temperature (K):       ',NewEOS.cp.T)\nprint('   Pressure (GPa):        ', NewEOS.cp.P)\nprint('   Density (g/cm^3):      ',NewEOS.cp.rho)\nprint('   Sp. Energy (MJ/kg):    ', NewEOS.cp.U)\nprint('   Sp. Entropy (kJ/K/kg): ', NewEOS.cp.S*1.e3)\nprint('\\n')\nprint('ANEOS Calculated Values at 1 bar:')\nprint('   Temperature at melting (K):                     ', NewEOS.onebar.Tmelt)\nprint('   Liquid density at melting (g/cm^3):             ', NewEOS.onebar.rhocm)\nprint('   Sp. Entropy at inc. melting Sim (kJ/K/kg):      ', NewEOS.onebar.Sim*1.E3)\nprint('   Sp. Entropy at com. melting Scm (kJ/K/kg):      ', NewEOS.onebar.Scm*1.E3)\nprint('   Temperature at boiling (K):                     ', NewEOS.onebar.Tvap)\nprint('   Liquid density at boiling (g/cm^3):             ', NewEOS.onebar.rhoiv)\nprint('   Sp. Entropy at inc. vaporization Siv (kJ/K/kg): ', NewEOS.onebar.Siv*1.E3)\nprint('   Sp. Entropy at com. vaporization Scv (kJ/K/kg): ', NewEOS.onebar.Scv*1.E3)\nprint('\\n')\nif NewEOS.tp.T > 0:\n    print('ANEOS Calculated Triple Point:')\n    print('   Temperature (K):                        ',NewEOS.tp.T)\n    print('   Pressure (GPa):                         ', NewEOS.tp.P)\n    print('   Solid density (g/cm^3):                 ',NewEOS.tp.rhos)\n    print('   Liquid density (g/cm^3):                ',NewEOS.tp.rhol)\n    print('   Vapor density (g/cm^3):                 ',NewEOS.tp.rhov)\n    print('   Sp. Entropy at inc. melt Sim (kJ/K/kg): ', NewEOS.tp.Sim*1.E3)\n    print('   Sp. Entropy at com. melt Scm (kJ/K/kg): ', NewEOS.tp.Scm*1.E3)\n    print('   Sp. Entropy at inc. vap. Siv (kJ/K/kg): ', NewEOS.tp.Siv*1.E3)\n    print('   Sp. Entropy at com. vap. Scv (kJ/K/kg): ', NewEOS.tp.Scv*1.E3)\nelse:\n    print('ANEOS: No melt curve or triple point in this calculation.')\nprint('\\n')\nprint('Starting at reference conditions (rho,T): ',NewEOS.R0REF,NewEOS.T0REF, ' (g/cm^3, K)')\nprint('ANEOS model conditions for shock-induced vaporization on release to 1 bar:')\nprint('                     :         IM        CM        IV      50%V        CV')\nprint('Shock Pressure (GPa) : {:10.2f}{:10.2f}{:10.2f}{:10.2f}{:10.2f}'.format(\n    np.interp(NewEOS.onebar.Sim,NewEOS.hug.S,NewEOS.hug.P),\n    np.interp(NewEOS.onebar.Scm,NewEOS.hug.S,NewEOS.hug.P),\n    np.interp(NewEOS.onebar.Siv,NewEOS.hug.S,NewEOS.hug.P),\n    np.interp(NewEOS.onebar.Siv+0.5*(NewEOS.onebar.Scv-NewEOS.onebar.Siv),NewEOS.hug.S,NewEOS.hug.P),\n    np.interp(NewEOS.onebar.Scv,NewEOS.hug.S,NewEOS.hug.P)))\nprint('Imp. Match Vel (km/s): {:10.2f}{:10.2f}{:10.2f}{:10.2f}{:10.2f}'.format(\n    np.interp(NewEOS.onebar.Sim,NewEOS.hug.S,NewEOS.hug.up)*2,\n    np.interp(NewEOS.onebar.Scm,NewEOS.hug.S,NewEOS.hug.up)*2,\n    np.interp(NewEOS.onebar.Siv,NewEOS.hug.S,NewEOS.hug.up)*2,\n    np.interp(NewEOS.onebar.Siv+0.5*(NewEOS.onebar.Scv-NewEOS.onebar.Siv),NewEOS.hug.S,NewEOS.hug.up)*2,\n    np.interp(NewEOS.onebar.Scv,NewEOS.hug.S,NewEOS.hug.up)*2))\nprint('ANEOS model conditions for shock-induced vaporization on release to the triple point pressure:')\nprint('                     :         IM        CM        IV      50%V        CV')\nprint('Shock Pressure (GPa) : {:10.2f}{:10.2f}{:10.2f}{:10.2f}{:10.2f}'.format(\n    np.interp(NewEOS.tp.Sim,NewEOS.hug.S,NewEOS.hug.P),\n    np.interp(NewEOS.tp.Scm,NewEOS.hug.S,NewEOS.hug.P),\n    np.interp(NewEOS.tp.Siv,NewEOS.hug.S,NewEOS.hug.P),\n    np.interp(NewEOS.tp.Siv+0.5*(NewEOS.tp.Scv-NewEOS.tp.Siv),NewEOS.hug.S,NewEOS.hug.P),\n    np.interp(NewEOS.tp.Scv,NewEOS.hug.S,NewEOS.hug.P)))\nprint('Imp. Match Vel (km/s): {:10.2f}{:10.2f}{:10.2f}{:10.2f}{:10.2f}'.format(\n    np.interp(NewEOS.tp.Sim,NewEOS.hug.S,NewEOS.hug.up)*2,\n    np.interp(NewEOS.tp.Scm,NewEOS.hug.S,NewEOS.hug.up)*2,\n    np.interp(NewEOS.tp.Siv,NewEOS.hug.S,NewEOS.hug.up)*2,\n    np.interp(NewEOS.tp.Siv+0.5*(NewEOS.tp.Scv-NewEOS.tp.Siv),NewEOS.hug.S,NewEOS.hug.up)*2,\n    np.interp(NewEOS.tp.Scv,NewEOS.hug.S,NewEOS.hug.up)*2))\n\nprint('\\n')\nprint('USING JANAF ENTROPIES AT 1 BAR:')\nprint('Starting at reference conditions (rho,T): ',NewEOS.R0REF,NewEOS.T0REF, ' (g/cm^3, K)')\nprint('ANEOS model conditions for shock-induced vaporization on release to 1 bar (JANAF):')\nprint('                     :         IM        CM        IV      50%V        CV')\nprint('Shock Pressure (GPa) : {:10.2f}{:10.2f}{:10.2f}{:10.2f}{:10.2f}'.format(\n    np.interp(92.190/NewEOS.FMW/1.e3,NewEOS.hug.S,NewEOS.hug.P),\n    np.interp(99.823/NewEOS.FMW/1.e3,NewEOS.hug.S,NewEOS.hug.P),\n    np.interp(2.24e-3,NewEOS.hug.S,NewEOS.hug.P),\n    np.interp(2.24e-3+0.5*((4.238-2.24)*1.e-3),NewEOS.hug.S,NewEOS.hug.P),\n    np.interp(4.238e-3,NewEOS.hug.S,NewEOS.hug.P)))\n\nstop\n```\n\n## Model Phase Boundaries\n\nBlack lines are the ANEOS phase boundaries. Blue curve is the model Principal Hugoniot.\n\nOrange diamonds are the 1-bar boiling point; orange squares are the 1-bar melting point.\n\nThe critical point has not been measured experimentally. There are several ab initio calculations, summarized in Medvedev 2014. The range of calculated critical points are shown below by the light blue box.\n\n\n```python\n# PHASE DIAGRAM PLOTS\n#======================LOTS OF PLOTS============================\n# Plot aneos phase boundaries with focus on the vapor curve\nsfont = 15\nfig, axes = plt.subplots(nrows=4, ncols=2, figsize=(14,24))\nplt.subplots_adjust(wspace=0.4)\n\n#------------------------------\n# entropy-temperature\nai=0\naj=0\naxes[ai,aj].plot(NewEOS.vc.Sl*1.E3,NewEOS.vc.T,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2],label=styleanphase[3])\naxes[ai,aj].plot(NewEOS.vc.Sv*1.E3,NewEOS.vc.T,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\naxes[ai,aj].plot(NewEOS.cp.S*1.E3,NewEOS.cp.T,'o',color=stylephasept[1],markersize=stylephasept[2])\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.Sl*1.E3,NewEOS.mc.T,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n    axes[ai,aj].plot(NewEOS.mc.Ss*1.E3,NewEOS.mc.T,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n\naxes[ai,aj].plot(NewEOS.hug.S*1.E3,NewEOS.hug.T,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(NewEOS.hug.S[0]*1.E3,NewEOS.hug.T[0],'o',color=stylestphug[1])\n\naxes[ai,aj].set_ylim(0,1.5*NewEOS.cp.T)\naxes[ai,aj].set_xlim(0,7)\naxes[ai,aj].set_xlabel('Specific Entropy (kJ/K/kg)',size=sfont)\naxes[ai,aj].set_ylabel('Temperature [K]',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n#-------------------------\n# density-pressure\nai=0\naj=1\naxes[ai,aj].semilogy(NewEOS.vc.rl,NewEOS.vc.Pl,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2],label=styleanphase[3])\naxes[ai,aj].plot(NewEOS.vc.rv,NewEOS.vc.Pv,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\naxes[ai,aj].plot(NewEOS.cp.rho,NewEOS.cp.P,'o',color=stylephasept[1],markersize=stylephasept[2])\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.rl,NewEOS.mc.Pl,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n    axes[ai,aj].plot(NewEOS.mc.rs,NewEOS.mc.Ps,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n\naxes[ai,aj].plot(NewEOS.hug.rho,NewEOS.hug.P,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(NewEOS.hug.rho[0],NewEOS.hug.P[0],'o',color=stylestphug[1])\n\naxes[ai,aj].set_ylim(1.e-5,300)\naxes[ai,aj].set_xlim(0,10)\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n#------\n#entropy-pressure\nai=1\naj=0\naxes[ai,aj].semilogy(NewEOS.vc.Sl*1.E3,NewEOS.vc.Pl,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2],label=styleanphase[3])\naxes[ai,aj].plot(NewEOS.vc.Sv*1.E3,NewEOS.vc.Pv,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\naxes[ai,aj].plot(NewEOS.cp.S*1.E3,NewEOS.cp.P,'o',color=stylephasept[1],markersize=stylephasept[2])\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.Sl*1.E3,NewEOS.mc.Pl,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n    axes[ai,aj].plot(NewEOS.mc.Ss*1.E3,NewEOS.mc.Ps,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n\naxes[ai,aj].plot(NewEOS.hug.S*1.E3,NewEOS.hug.P,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(NewEOS.hug.S[0]*1.E3,NewEOS.hug.P[0],'o',color=stylestphug[1])\n\naxes[ai,aj].set_xlabel('Specific Entropy (kJ/K/kg)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].set_ylim(1.e-12,10000)\naxes[ai,aj].set_xlim(0,7)\n\n#-----------\n# specific energy - pressure\nai=1\naj=1\naxes[ai,aj].semilogy(NewEOS.vc.Ul,NewEOS.vc.Pl,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2],label=styleanphase[3])\naxes[ai,aj].plot(NewEOS.vc.Uv,NewEOS.vc.Pv,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\naxes[ai,aj].plot(NewEOS.cp.U,NewEOS.cp.P,'o',color=stylephasept[1],markersize=stylephasept[2])\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.Ul,NewEOS.mc.Pl,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n    axes[ai,aj].plot(NewEOS.mc.Us,NewEOS.mc.Ps,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n\naxes[ai,aj].plot(NewEOS.hug.U,NewEOS.hug.P,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(NewEOS.hug.U[0],NewEOS.hug.P[0],'o',color=stylestphug[1])\n\naxes[ai,aj].set_xlabel('Specific Internal Energy (MJ/kg)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].set_ylim(1.e-12,10000)\naxes[ai,aj].set_xlim(-3,NewEOS.cp.U*1.5)\n\n#-------\n# temperature - pressure\nai=2\naj=0\naxes[ai,aj].semilogy(NewEOS.vc.T,NewEOS.vc.Pl,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2],label=styleanphase[3])\naxes[ai,aj].plot(NewEOS.vc.T,NewEOS.vc.Pv,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\naxes[ai,aj].plot(NewEOS.cp.T,NewEOS.cp.P,'o',color=stylephasept[1],markersize=stylephasept[2])\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.T,NewEOS.mc.Pl,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n    axes[ai,aj].plot(NewEOS.mc.T,NewEOS.mc.Ps,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n\naxes[ai,aj].plot(NewEOS.hug.T,NewEOS.hug.P,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(NewEOS.hug.T[0],NewEOS.hug.P[0],'o',color=stylestphug[1])\n\naxes[ai,aj].set_xlabel('Temperature (K)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].set_xlim(0,12000)\naxes[ai,aj].set_ylim(1.e-16,100)\n\n#-------\n# pressure - temperature melt curve\nai=2\naj=1\n#axes[ai,aj].plot(NewEOS.vc.Pl,NewEOS.vc.T,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2],label=styleanphase[3])\n#axes[ai,aj].plot(NewEOS.vc.Pv,NewEOS.vc.T,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n#axes[ai,aj].plot(NewEOS.cp.P,NewEOS.cp.T,'o',color=stylephasept[1],markersize=stylephasept[2])\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.Pl,NewEOS.mc.T,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2],label=styleanphase[3])\n    axes[ai,aj].plot(NewEOS.mc.Ps,NewEOS.mc.T,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n\n    axes[ai,aj].plot(NewEOS.hug.P,NewEOS.hug.T,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\n    axes[ai,aj].plot(NewEOS.hug.P[0],NewEOS.hug.T[0],'o',color=stylestphug[1])\n\n    axes[ai,aj].set_ylabel('Temperature (K)',size=sfont)\n    axes[ai,aj].set_xlabel('Pressure (GPa)',size=sfont)\n    axes[ai,aj].tick_params(labelsize=sfont)\n    axes[ai,aj].set_ylim(0,9000)\n    axes[ai,aj].set_xlim(-5,450)\n\n#-------\n# density - pressure melt curve\nai=3\naj=0\n\naxes[ai,aj].plot(NewEOS.hug.rho,NewEOS.hug.P,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(NewEOS.hug.rho[0],NewEOS.hug.P[0],'o',color=stylestphug[1])\naxes[ai,aj].plot(scironrarr,scironparr,'-',color='m',label='STP Hugoniot\\n(Sjostrom & Crockett 2018)')\n\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.rl,NewEOS.mc.Pl,'--',color=styleanphase[1],linewidth=styleanphase[2],label=styleanphase[3])\n    axes[ai,aj].plot(NewEOS.mc.rs,NewEOS.mc.Ps,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n\n\n    axes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\n    axes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\n    axes[ai,aj].tick_params(labelsize=sfont)\n    axes[ai,aj].set_ylim(100,400)\n    axes[ai,aj].set_xlim(10,14)\n\n#-------\n# temperature - pressure zoom out\nai=3\naj=1\naxes[ai,aj].semilogy(NewEOS.vc.T,NewEOS.vc.Pl,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2],label=styleanphase[3])\naxes[ai,aj].plot(NewEOS.vc.T,NewEOS.vc.Pv,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\naxes[ai,aj].plot(NewEOS.cp.T,NewEOS.cp.P,'o',color=stylephasept[1],markersize=stylephasept[2])\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.T,NewEOS.mc.Pl,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n    axes[ai,aj].plot(NewEOS.mc.T,NewEOS.mc.Ps,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n\naxes[ai,aj].plot(NewEOS.hug.T,NewEOS.hug.P,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(NewEOS.hug.T[0],NewEOS.hug.P[0],'o',color=stylestphug[1])\n\naxes[ai,aj].set_xlabel('Temperature (K)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].set_xlim(0,35000)\naxes[ai,aj].set_ylim(1.e-16,100)\n\n#===================================================================\n# PLOT EXPERIMENTAL CONSTRAINTS ON THE ANEOS PHASE BOUNDARIES\nPLOTDATA=1\ndatms = 8\nif PLOTDATA:\n    # entropy-temperature [0,0]\n    ai=0\n    aj=0\n    # range of ab initio predictions for the critical point from Medvedev 2014\n    rect = Rectangle((2.24,7300.),2.,3600,linewidth=1,edgecolor='skyblue',facecolor='skyblue')\n    axes[ai,aj].add_patch(rect)\n   \n    # STP NIST-JANAF\n    axes[ai,aj].plot(ironSTP_S*1.E3,298,'+',color='orange',label='STP (JANAF)')\n    # 1 bar melting point JANAF delta-iron to liquid\n    #1809.000\t\t42.558\t\t92.190\t\t59.772\t\t58.645\t\tDELTA <--> LIQUID\n    #1809.000\t\t46.024\t\t99.823\t\t59.772\t\t72.452\t\tTRANSITION\n    axes[ai,aj].plot(99.823/NewEOS.FMW,1809,'d',color='orange',label='1-bar MP (JANAF)')\n    axes[ai,aj].plot(92.190/NewEOS.FMW,1809,'d',color='orange')\n    # Boiling point NIST-JANAF, Kraus et al. Nature Geoscience 2015 and refs within\n    axes[ai,aj].plot(2.24,3133,'s',color='orange',label='1-bar BP (JANAF)')\n    axes[ai,aj].plot(4.238,3133,'s',color='orange')\n\n    axes[0,0].plot(2.496,8787,'x',color='navy',label='Fortov & Lomonosov 2010 CP',markersize=10)\n    #EOS parameters of the critical point for iron Pc = 1.131 GPa, Tc = 8,787 K, Vc = 0.458cm3/g, Sc = 2.496 J/g/K\n\n    # density-pressure [0,1]\n    ai=0\n    aj=1    \n    # range of ab initio predictions for the critical point from Medvedev 2014\n    rect = Rectangle((1.24,.356),1.,1.35,linewidth=1,edgecolor='skyblue',facecolor='skyblue')\n    axes[ai,aj].add_patch(rect)\n\n    axes[ai,aj].plot(2.1834,1.131,'x',color='navy',label='Fortov & Lomonosov 2010 CP',markersize=10)\n\n\n    # 99.99% Fe melting volume at 1 bar from Blumm & Henderson 2000 3.46%, approx 7.175 g/cm3 for solid at melt pt\n    axes[ai,aj].plot([6.98,6.98*(1.0346)],[1.E-4,1.E-4],'d',color='orange',label='MP (Blumm & Henderson 2000)')\n\n    # 1-bar Fe liquid at boiling point calculation Kraus et al. 2015\n    axes[ai,aj].plot([6.01],[1.E-4],'s',color='orange',label='BP (Kraus et al. 2015)')\n\n    # entropy -- pressure [1,0]\n    ai=1\n    aj=0\n    # range of ab initio predictions for the critical point from Medvedev 2014\n    rect = Rectangle((2.24,.356),2.,1.35,linewidth=1,edgecolor='skyblue',facecolor='skyblue')\n    axes[ai,aj].add_patch(rect)\n    axes[ai,aj].plot(2.496,1.131,'x',color='navy',label='Fortov & Lomonosov 2010 CP',markersize=10)\n\n    \n    # STP NIST-JANAF\n    axes[ai,aj].plot(ironSTP_S*1.E3,1.E-4,'+',color='orange',label='STP (JANAF)')\n    # 1 bar melting point JANAF delta-iron to liquid\n    #1809.000\t\t42.558\t\t92.190\t\t59.772\t\t58.645\t\tDELTA <--> LIQUID\n    #1809.000\t\t46.024\t\t99.823\t\t59.772\t\t72.452\t\tTRANSITION\n    axes[ai,aj].plot(99.823/NewEOS.FMW,1.E-4,'d',color='orange',label='1-bar MP (JANAF)')\n    axes[ai,aj].plot(92.190/NewEOS.FMW,1.E-4,'d',color='orange')\n    # Boiling point NIST-JANAF, Kraus et al. Nature Geoscience 2015 and refs within\n    axes[ai,aj].plot(2.24,1.E-4,'s',color='orange',label='1-bar BP (JANAF)')\n    axes[ai,aj].plot(4.238,1.E-4,'s',color='orange')\n\n    # temperature -- pressure [2,0]\n    ai=2\n    aj=0\n    # range of ab initio predictions for the critical point from Medvedev 2014\n    rect = Rectangle((7300.,.356),3600,1.35,linewidth=1,edgecolor='skyblue',facecolor='skyblue')\n    axes[ai,aj].add_patch(rect)\n\n    # plot Fe experimentally fitted vapor curve from Alcock et al. 1984\n    alcocktarr = np.arange(2100)+1\n    # Fe solid good from 298 to melting point\n    A=7.1\n    B=-21723.\n    C=0.4536\n    D=-0.5846\n    alcockfesolidparr = 1.e-4*np.power(10.,A+B/alcocktarr+C*np.log10(alcocktarr)+D*alcocktarr*1.e-3) #GPa\n\n    # Fe liquid good from melting point to 2100 K\n    A=6.347\n    B=-19574\n    C=0.\n    D=0.\n    alcockfeliquidparr = 1.e-4*np.power(10.,A+B/alcocktarr+C*np.log10(alcocktarr)+D*alcocktarr*1.e-3) #GPa\n\n    axes[ai,aj].plot(alcocktarr[298:1809],alcockfesolidparr[298:1809],color='orange',label='Vapor curve\\nAlcock et al. 1984')\n    axes[ai,aj].plot(alcocktarr[1809:2100],alcockfeliquidparr[1809:2100],color='orange')\n    axes[ai,aj].plot([3133.345],[1.e-4],'o',color='orange',label='1-bar BP (JANAF)')\n    axes[ai,aj].plot(9250.,8750.e-4,'+',color='purple',label='Beutl et al. 1994 CP',markersize=10)\n    axes[ai,aj].plot(8787,1.131,'x',color='navy',label='Fortov & Lomonosov 2010 CP',markersize=10)\n\n\n\n\n    # pressure- temperature [2,1]\n    ai=2\n    aj=1\n    \n    # Anzellini et al. 2013 Science iron melt curve high pressure region up to 200 GPa/5000 K\n    anzmct3arr = (np.arange(100)+1.)/100.*1300.+3700 # K\n    anzmcp3arr = (np.power(anzmct3arr/3712.,1.72)-1.)*161.2 + 98.5 # GPa\n    anzmct2arr = (np.arange(100)+1.)/100.*3700. # K\n    anzmcp2arr = (np.power(anzmct2arr/1991.,2.38)-1.)*27.39 + 5.2 # GPa\n    axes[ai,aj].plot(anzmcp3arr,anzmct3arr,color=\"orange\",linestyle='--',label='Anzellini et al. 2013')\n    axes[ai,aj].plot(anzmcp2arr,anzmct2arr,color=\"orange\",linestyle='--')\n\n    #Fischer et al. 2012 Fe-Si alloys\n    # example solidus of an iron alloy\n    fischerparrlow = Fischer_datalow.iloc[:,0].values # P GPa\n    fischertarrlow = Fischer_datalow.iloc[:,1].values # T K\n    fischerparrhigh = Fischer_datahigh.iloc[:,0].values # P GPa\n    fischertarrhigh = Fischer_datahigh.iloc[:,1].values # T K\n\n    axes[ai,aj].plot(fischerparrhigh,fischertarrhigh,'v',color=\"brown\",label='Fischer et al. 2012 Fe-16Si\\nupper limit solidus')\n    axes[ai,aj].plot(fischerparrlow,fischertarrlow,'^',color=\"brown\",label='lower limit solidus')\n\n    rect = Rectangle((240.,5000.),6.,700,linewidth=1,edgecolor='moccasin',facecolor='moccasin')\n    axes[ai,aj].add_patch(rect)\n    axes[ai,aj].plot(243.,5350,'x',color='orange',label='Brown & McQueen 1986')\n    rect = Rectangle((222.,4700),6.,1000,linewidth=1,edgecolor='moccasin',facecolor='moccasin')\n    axes[ai,aj].add_patch(rect)\n    axes[ai,aj].plot(225.,5100,'*',color='orange',label='Nguyen & Holmes 2004')\n\n    axes[ai,aj].errorbar(100.,3500.,xerr=10.,yerr=200,fmt='s',color='red',label='bcc-hcp-liquid TP\\nMorard et al. 2018')\n\n\n    # density - pressure [3,0]\n    ai=3\n    aj=0\n    axes[ai,aj].plot(12.5,270.,'^',color='orange',label='STP Hug. enters liq. 270 GPa\\n(Sjostrom & Crockett 2018)',markersize=6)\n    if NewEOS.tp.T > 0:\n        axes[ai,aj].plot(np.interp(260.,NewEOS.mc.Pl,NewEOS.mc.rl),260.,'d',color='orange',label='STP Hug. enters liq. 260 GPa\\n(Nguyen & Holmes 2014)',markersize=6)\n        axes[ai,aj].plot(np.interp(225.,NewEOS.mc.Ps,NewEOS.mc.rs),225.,'d',color='red',label='STP Hug. begins to melt 225 GPa\\n(Nguyen & Holmes 2014)',markersize=6)\n   \n    # temperature -- pressure [3,1]\n    ai=3\n    aj=1\n    # range of ab initio predictions for the critical point from Medvedev 2014\n    rect = Rectangle((7300.,.356),3600,1.35,linewidth=1,edgecolor='skyblue',facecolor='skyblue')\n    axes[ai,aj].add_patch(rect)\n\n    # plot Fe experimentally fitted vapor curve from Alcock et al. 1984\n    alcocktarr = np.arange(2100)+1\n    # Fe solid good from 298 to melting point\n    A=7.1\n    B=-21723.\n    C=0.4536\n    D=-0.5846\n    alcockfesolidparr = 1.e-4*np.power(10.,A+B/alcocktarr+C*np.log10(alcocktarr)+D*alcocktarr*1.e-3) #GPa\n\n\naxes[0,0].legend(fontsize=sfont-5)\naxes[0,1].legend(fontsize=sfont-5)\naxes[1,0].legend(fontsize=sfont-5)\naxes[1,1].legend(fontsize=sfont-5)\naxes[2,0].legend(fontsize=sfont-5)\naxes[2,1].legend(fontsize=sfont-5)\naxes[3,0].legend(fontsize=sfont-5)\naxes[3,1].legend(fontsize=sfont-5)\n\nplt.tight_layout(pad=0.6)\n\n```\n\n## ANEOS model comparisons to experimental data\n\nThe original ANEOS with a 3nR limit to the heat capacity does provide a good fit to the liquid region. \n\nDorogokupets et al. 2017 calculated the isotherm for liquid iron at 2200 K. The ANEOS model is a good fit (and then enters the solid phase). \n\nAnzellini et al. (2013) estimated that the temperature at the core-mantle boundary is about 4050 K. Here, I plot the ANEOS isentrope through (the nearest grid point to) 4050 K and 136 GPa and compare the isentrope to PREM (http://ds.iris.edu/spud/earthmodel/9785674). As expected, the ANEOS model isentrope is denser than Earth's core. The model isentrope and 10% and 4% density reductions are compared to PREM. \n\n\n```python\n# INCLUDE A COMPARISON TO EARTH'S STRUCTURE PREM MODEL\nG = 6.67E-11 # Gravitational constant  m3/kg/s2\n\n# Read in PREM: Preliminary Earth Reference Model\nPREM_filename=datadir+'PREM500_IDV.csv' # we love long, readable variable names!\n\n# make a class to hold the PREM data\nclass PREMclass:\n    \"\"\"Class to hold PREM data and other 1-D Earth variables.\"\"\"  # this is a documentation string for this class\n    def __init__(self): # self is the default name of the object for internal referencing of the variables in the class\n        \"\"\"A function to initialize the class object.\"\"\" # this is a documentation string for this function\n        self.NR = 0 # number of radius points\n        self.radius = np.zeros(self.NR) \n        self.density = np.zeros(self.NR)   \n        self.pwavevel = np.zeros(self.NR)   \n        self.swavevel = np.zeros(self.NR)\n        self.pressure = np.zeros(self.NR)\n        self.temperature = np.zeros(self.NR)\n        # not going to use all the variables in the file\n        self.units = '' # I like to keep a text note in a structure about the units\n\n# initialize an empty PREM object\nPREM = PREMclass()\n\n# read the data into the class parameters\nPREM.radius = np.loadtxt(PREM_filename,delimiter=',',skiprows=2,usecols=[0]) # radius in m\nPREM.density = np.loadtxt(PREM_filename,delimiter=',',skiprows=2,usecols=[1]) # density in kg/m3\nPREM.pwavevel = np.loadtxt(PREM_filename,delimiter=',',skiprows=2,usecols=[2]) # p-wave velocity m/s\nPREM.swavevel = np.loadtxt(PREM_filename,delimiter=',',skiprows=2,usecols=[3]) # s-wave velocity m/s\nPREM.NR = len(PREM.radius) # number of radius points\nPREM.units = 'radius (m), density (kg/m3), pwavevel (m/s), swavevel (m/s)'\n\n# start at the surface and integrate via a for loop to the center of the planet\n\n# calculate the thickness of each layer in the PREM model using the roll function\nPREM_dr = np.roll(PREM.radius,-1)-PREM.radius \nPREM_dr[PREM.NR-1] = 0. # we are not using the last entry in the list because there are NR-1 layers\n#print(PREM_dr)\n\n# calculate the mass of each layer\n# density x area x thickness of each layer\nPREM_mass_rad = PREM.density*(4.*np.pi*PREM.radius*PREM.radius*PREM_dr) \n\n# Check that the total mass is the mass of the Earth\n#print('PREM total mass (kg)=',np.sum(PREM_mass_rad))\n#print('PREM total mass (Mearth)=',np.sum(PREM_mass_rad)/5.972E24)\n\nPREM.pressure = np.zeros(PREM.NR) # make array of zeros for pressure of the same length as the arrays in the PREM model\n# The first entry is the middle of the planet, so start at the surface and integrate inwards\nfor i in range(PREM.NR-2,0,-1):\n    # we indent for the code in the for loop\n    PREM.pressure[i] = PREM.pressure[i+1]+G*np.sum(PREM_mass_rad[0:i-1])*PREM.density[i]*PREM_dr[i]/PREM.radius[i]/PREM.radius[i]\n\n# use SESAME units\nPREM.pressure = PREM.pressure/1.E9 # GPa\n\nIronEOS = NewEOS\n# first extract the isentropes for the planet from the EOS tables\ncore = isentrope_class() # code in eostable.py\nScore = 0.0022 # MJ/K/kg\n\n# loop across all densities and extract the values for the requested isentrope\nfor i in range(0,IronEOS.ND):\n    ind = np.where((IronEOS.S[:,i] > 0))[0]\n    interpfunction = interpolate.interp1d(IronEOS.S[ind,i],IronEOS.P[ind,i]) # MJ/K/kg, GPa\n    core.pressure = np.append(core.pressure,interpfunction(Score)) # GPa\n    interpfunction = interpolate.interp1d(IronEOS.S[ind,i],IronEOS.T[ind]) # MJ/K/kg, GPa\n    core.temperature = np.append(core.temperature,interpfunction(Score)) # GPa\ncore.density = IronEOS.rho # g/cm3\n\n#print('Calculated iron isentrope with ',np.round(np.interp(136.,core.pressure,core.temperature)),' K CMB temperature (P=136 GPa)')\n\n# first extract the isentropes for the planet from the EOS tables\ncore2 = isentrope_class() # code in eostable.py\nit0   = np.where(IronEOS.T >= 4050.)[0]\nScore = np.interp(136.,IronEOS.P[it0[0],:],IronEOS.S[it0[0],:])\n#Score = 0.00186 # MJ/K/kg\n\n# loop across all densities and extract the values for the requested isentrope\nfor i in range(0,IronEOS.ND):\n    ind = np.where((IronEOS.S[:,i] > 0))[0]\n    interpfunction = interpolate.interp1d(IronEOS.S[ind,i],IronEOS.P[ind,i]) # MJ/K/kg, GPa\n    core2.pressure = np.append(core2.pressure,interpfunction(Score)) # GPa\n    interpfunction = interpolate.interp1d(IronEOS.S[ind,i],IronEOS.T[ind]) # MJ/K/kg, GPa\n    core2.temperature = np.append(core2.temperature,interpfunction(Score)) # GPa\ncore2.density = IronEOS.rho # g/cm3\nprint('Calculated iron isentrope with ',np.round(np.interp(136.,core2.pressure,core2.temperature)),' K CMB temperature (P=136 GPa)')\n\n```\n\n\n```python\n# 1-bar plots and 298 K plots\n\n# Plot aneos vapor curves\nsfont = 15\nfig, axes = plt.subplots(2, 2, figsize=(14,14))\nplt.subplots_adjust(wspace=0.4)\n\n#--------\n# temperature - entropy at 1 bar\nai=0\naj=0\n\n\naxes[ai,aj].plot(Desai_tarr,Desai_sarr,'-',color='orange',label='Iron data (Desai 1986)',linewidth=3)\naxes[ai,aj].plot(NewEOS.onebar.T,NewEOS.onebar.S*1.E3,'+',color='blue',label='ANEOS 1 bar')\n\naxes[ai,aj].plot(1809.,99.823/NewEOS.FMW,'d',color='orange',label='1-bar MP (JANAF)')\naxes[ai,aj].plot(1809.,92.190/NewEOS.FMW,'d',color='orange')\n# Boiling point NIST-JANAF, Kraus et al. Nature Geoscience 2015 and refs within\naxes[ai,aj].plot(3133.,2.24,'s',color='orange',label='1-bar BP (JANAF)')\naxes[ai,aj].plot(3133.,4.238,'s',color='orange')\n\naxes[ai,aj].set_xlabel('Temperature (K)',size=sfont)\naxes[ai,aj].set_ylabel('Specific Entropy (kJ/K/kg)',size=sfont)\naxes[ai,aj].set_title('1-bar isobar',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].set_ylim(0,5)\naxes[ai,aj].set_xlim(0,4000)\n\n\n#----\n# density-temperature at 1 bar\nai=0\naj=1\n\naxes[ai,aj].plot(Assael_tarr,Assael_rarr/1.e3,'-',color='orange',label='Liquid iron data (Assael et al. 2006)')\naxes[ai,aj].plot(NewEOS.onebar.T,NewEOS.onebar.rho,'+',color='blue',label='ANEOS 1 bar')\naxes[ai,aj].plot(298.,7.873,'+',color='orange',label='STP')\naxes[ai,aj].plot([3133],[6.01],'s',color='orange',label='Boiling point (Kraus et al. 2015)')\n# 3.4% volume change (Askeland 1996) with highest density from Assael et al. 2006\naxes[ai,aj].plot([1809.,1809],[6.99,6.99*(1.034)],'d',color='orange',label='Melt transition')\n\naxes[ai,aj].plot([1811.],[7.019],'X',color='red',label='Anderson & Ahrens 1994')\n\n\naxes[ai,aj].set_ylabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_xlabel('Temperature (K)',size=sfont)\naxes[ai,aj].set_title('1-bar isobar',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].set_ylim(5,9)\naxes[ai,aj].set_xlim(0,4000)\n\n# plot data\n#axes[ai,aj].plot(1890+273.,2.968,'s',color='orange',label='MELTS MP Berman')\n#axes[ai,aj].plot(1890+273.,2.687,'o',color='orange',label='MELTS MP Lange')\n#axes[ai,aj].plot(2273.,2.597,'d',color='orange',label='Thomas & Asimow 2013')\n\n\n#----\n# density-pressure at 298 K\nai=1\naj=0\n\n\n# Guinan & Beshers JPCS 1969 Fe 298 K isotherm\n#K0T = 166.4 # GPa room temp isentrope\n#K0Tp = 5.29\n#R00 = 7.874\n#print(R00)\nGB_cs_stp = np.sqrt(166.4E9/7874.) # m/s\n#print(GB_cs_stp)\n#BM_pressure = 1.5*K0T*(np.power(NewEOS.rho/R00,7./3.)-np.power(NewEOS.rho/R00,5./3.)\n#                      )*(1.+0.75*(K0Tp-4.)*(np.power(NewEOS.rho/R00,2./3.)-1.))\n#igood = np.where((BM_pressure < 14.6))[0]\n#axes[ai,aj].plot(NewEOS.rho[igood],BM_pressure[igood],'-',color='orange',label='alpha-Fe 298-K isentrope\\nGuinan & Beshers 1969')\n\n# Dorogokupets et al. 2017\n# alpha (bcc) iron 298 K 1 bar (low T is ferro; high T is para)\nK0T = 164.001 # GPa room temp isotherm\nK0Tp = 5.5\nR00 = 7.8746\nBM_pressure = 1.5*K0T*(np.power(NewEOS.rho/R00,7./3.)-np.power(NewEOS.rho/R00,5./3.)\n                      )*(1.+0.75*(K0Tp-4.)*(np.power(NewEOS.rho/R00,2./3.)-1.))\nigood = np.where((BM_pressure < 14.6))[0]\naxes[ai,aj].plot(NewEOS.rho[igood],BM_pressure[igood],'-',color='teal',label='alpha-Fe 298-K isotherm\\nDorogokupets et al. 2017')\n\n# Dorogokupets et al. 2017\n# gamma (fcc) iron 298 K 1 bar\nK0T = 146.2 # GPa room temp isotherm\nK0Tp = 4.67\nR00 = 8.06\nBM_pressure = 1.5*K0T*(np.power(NewEOS.rho/R00,7./3.)-np.power(NewEOS.rho/R00,5./3.)\n                      )*(1.+0.75*(K0Tp-4.)*(np.power(NewEOS.rho/R00,2./3.)-1.))\nigood = np.where((BM_pressure < 110))[0]\naxes[ai,aj].plot(NewEOS.rho[igood],BM_pressure[igood],'-',color='cyan',linewidth=4,label='gamma-Fe 298-K isotherm\\nDorogokupets et al. 2017')\n\niT0REF = np.where(NewEOS.T == T0REF)[0]\naxes[ai,aj].plot(NewEOS.rho,NewEOS.P[iT0REF[0],:],'-',color='blue',label='ANEOS 298-K isotherm')\n\n# Dewaele et al. PRL 2006 Fe 298 K isotherm\n# espilon-iron (hcp)\nK0T = 165 # fixed GPa room temp isotherm\nK0Tp = 4.97 # +-0.04 fitted \nR00 = (NewEOS.FMW)*1.*1.6726/(11.234*1.E-3)/1.E3 # kg/m3->g/cm3 \n#print(R00)\nBM_pressure = 1.5*K0T*(np.power(NewEOS.rho/R00,7./3.)-np.power(NewEOS.rho/R00,5./3.)\n                      )*(1.+0.75*(K0Tp-4.)*(np.power(NewEOS.rho/R00,2./3.)-1.))\nigood = np.where((BM_pressure > 17.)&(BM_pressure < 197.))\naxes[ai,aj].plot(NewEOS.rho[igood],BM_pressure[igood],'-',color='brown',linewidth=2,label='epsilon-Fe 298-K isotherm\\nDewaele et al. 2006')\n'''\n# error bars Dewaele et al. PRL 2006 Fe 298 K isotherm\nK0Tp = 4.97-0.04 # +-0.04 fitted \nBM_pressure = 1.5*K0T*(np.power(NewEOS.rho/R00,7./3.)-np.power(NewEOS.rho/R00,5./3.)\n                      )*(1.+0.75*(K0Tp-4.)*(np.power(NewEOS.rho/R00,2./3.)-1.))\nigood = np.where((BM_pressure > 17.)&(BM_pressure < 197.))\naxes[ai,aj].plot(NewEOS.rho[igood],BM_pressure[igood],'--',color='brown')\n# error bars Dewaele et al. PRL 2006 Fe 298 K isotherm\nK0Tp = 4.97+0.04 # +-0.04 fitted \nBM_pressure = 1.5*K0T*(np.power(NewEOS.rho/R00,7./3.)-np.power(NewEOS.rho/R00,5./3.)\n                      )*(1.+0.75*(K0Tp-4.)*(np.power(NewEOS.rho/R00,2./3.)-1.))\nigood = np.where((BM_pressure > 17.)&(BM_pressure < 197.))\naxes[ai,aj].plot(NewEOS.rho[igood],BM_pressure[igood],'--',color='brown')\n'''\n\n#------ LIQUID\n# Dorogokupets et al. 2017\n# liquid iron 2200 K 1 bar\nK0T = 65.2 # GPa isotherm\nK0Tp = 6.48\nR00 = 7.019/1.04\nBM_pressure = 1.5*K0T*(np.power(NewEOS.rho/R00,7./3.)-np.power(NewEOS.rho/R00,5./3.)\n                      )*(1.+0.75*(K0Tp-4.)*(np.power(NewEOS.rho/R00,2./3.)-1.))\nigood = np.where((BM_pressure < 20))[0]\naxes[ai,aj].plot(NewEOS.rho[igood],BM_pressure[igood],'--',color='orange',linewidth=2,label='Liquid Fe 2200-K isotherm\\nDorogokupets et al. 2017')\n\n# plot liquid isotherm\nit0 = np.where(NewEOS.T >= 2200)[0]\n#print('Liquid isotherm at (K) ',NewEOS.T[it0[0]])\nigood = np.where((NewEOS.P[it0[0],:] < 20))[0]\naxes[ai,aj].plot(NewEOS.rho[igood],NewEOS.P[it0[0],igood],'--',color='orangered',label='ANEOS '+str(np.round(NewEOS.T[it0[0]]))+'-K isotherm')\n\n\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].set_title('298-K, 2200-K isotherms',size=sfont)\naxes[ai,aj].set_xlim(6,13)\naxes[ai,aj].set_ylim(0,200)\n\n#----\n# density-pressure at 298 K\nai=1\naj=1\n\naxes[ai,aj].plot(PREM.density[1::]/1.E3,PREM.pressure[1::],'-',color='orange',label='PREM')\n#axes[ai,aj].plot(core.density,core.pressure,'-',color='blue',label='ANEOS '+str(np.round(np.interp(136,core.pressure,core.temperature)))+' K isentrope at CMB',markersize=10)\naxes[ai,aj].plot(core2.density,core2.pressure,'-',color='blue',label='ANEOS isentrope: '+str(np.round(np.interp(136,core2.pressure,core2.temperature)))+' K at CMB',markersize=10)\naxes[ai,aj].plot(0.9*core2.density,core2.pressure,'--',color='blue',label='ANEOS isentrope shifted 10% in density')\naxes[ai,aj].plot(0.96*core2.density,core2.pressure,':',color='blue',label='ANEOS isentrope shifted 4% in density')\n\n\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].set_title('PREM and ANEOS model isentropes',size=sfont)\naxes[ai,aj].set_xlim(3,14)\naxes[ai,aj].set_ylim(0,360)\n\n# don't show a plot in lower right\n#axes[1,1].axis(\"off\")\n\n\naxes[0,0].legend(fontsize=sfont-5)\naxes[0,1].legend(fontsize=sfont-5)\naxes[1,0].legend(fontsize=sfont-5)\naxes[1,1].legend(fontsize=sfont-5)\n\n#print(PREM.pressure)\n```\n\n## ANEOS Gruneisen parameter and Theta parameter for thermal model\n\nThe Gruneisen parameter for iron liquid has been determined experimentally from shock wave data (e.g., see Kraus et al. 2015). Shockwave data derive the Grueneisen parameter in reference to a known state:\n\\begin{equation}\n\\gamma = \\frac{1}{\\rho}\\frac{(P-P_{\\rm ref})}{(E-E_{\\rm ref})} \\bigg\\rvert _V\n\\end{equation}\n\nThe ANEOS Gruneisen model is split into two parts. For $\\rho \\ge \\rho_{0}$,\n\\begin{equation}\n\\gamma = \\left( \\frac{\\gamma_0 \\rho_0}{\\rho}  + C_{24} \\left( 1-\\frac{\\rho_0}{\\rho} \\right)^2 \\right) (1-C_{60}) + \\left( \\gamma_0 + (C_{24}-\\gamma_0) \\left( 1- \\frac{\\rho_0}{\\rho} \\right)^2 \\right) C_{60}.\n\\end{equation}\nFor $\\rho < \\rho_{0}$,\n\\begin{equation}\n\\gamma = C_{16} \\rho^2 + C_{17}\\rho + 1 + C_{61}.\n\\end{equation}\n\n$C_{16}$ and $C_{17}$ are calculated so that $\\gamma$ and $d \\gamma / d \\rho$ are continuous at $\\rho=\\rho_0$. The model asymptotes to the Thomas-Fermi limit ($\\gamma=2/3$) when $C_{24}=2/3$.\n\nThe gamma function developed by Kraus et al. 2015 (SOM equation 5) is also shown for comparison. This function was derived from the abundant data on shocked porous iron. This calculation assumes E=0.\n\nThe literature values for the Gruneisen parameter of alpha-iron span 1.65 to 1.75: e.g., 1.65 Adams et al. 2006; 1.736 Dorogokupets et al. 2017; 1.75 Sjostrom & Crockett 2018.\n\n\n```python\n# plot the gamma and isotherms\n\n# ANEOS Formulation for Gamma and theta\ntheta0=abs(NewEOS.theta0)\nrhoarr = (1+np.arange(1000))/1000.*NewEOS.R0REF*10.\ngammaarr = (NewEOS.gamma0*NewEOS.R0REF/rhoarr\n           )+NewEOS.C24*np.power(1.0-NewEOS.R0REF/rhoarr,2.)*(1.-NewEOS.C60)+(NewEOS.gamma0 + (NewEOS.C24-NewEOS.gamma0)*np.power(1.-NewEOS.R0REF/rhoarr,2.))*NewEOS.C60\ns3 = NewEOS.C61+1.\nC14 = theta0 * np.exp(1.5*s3-(2.-0.5*NewEOS.C60)*NewEOS.gamma0)/(np.power(NewEOS.R0REF,s3))\nC16 = (s3-(2.-NewEOS.C60)*NewEOS.gamma0)/(NewEOS.R0REF*NewEOS.R0REF)\nC17 = ((3.-NewEOS.C60)*NewEOS.gamma0-2.*s3)/NewEOS.R0REF\ngammaarrlow = C16*rhoarr*rhoarr+C17*rhoarr+s3\nthetaarr = theta0*np.exp((1.-NewEOS.C60)*(1.-NewEOS.R0REF/rhoarr)*NewEOS.gamma0-0.5*(NewEOS.R0REF/rhoarr)*(3.-(NewEOS.R0REF/rhoarr)*(4-(NewEOS.R0REF/rhoarr))))*np.power((rhoarr/NewEOS.R0REF),NewEOS.C24)\nthetalowarr = C14*np.exp(rhoarr*(C17+0.5*C16*rhoarr))*np.power(rhoarr,s3)\n\n\n#-------- plots\nsfont = 15\nfig, axes = plt.subplots(1, 2, figsize=(14,7))\nplt.subplots_adjust(wspace=0.4)\n\n\n# -----\nai=0\nindlow = np.where(rhoarr <= NewEOS.R0REF)\nindhigh = np.where(rhoarr >= NewEOS.R0REF)\n\n\n# Gamma from Kraus et al. 2015 SOM Equation 5\n# this assumes E = 0. I dropped the exp(-phi*E) term. Phi=0.045 kg/MJ.\nkraus_garr = 0.7+(2.1-0.7)*np.power(7.85/NewEOS.rho,1.7)\nkraus_validrange = np.where((NewEOS.rho>9)&(NewEOS.rho<12))[0]\naxes[ai].plot(NewEOS.rho[kraus_validrange],kraus_garr[kraus_validrange],'-',linewidth=6,color='orange',label='Liquid iron fit\\n(Kraus et al. 2015)')\naxes[ai].set_ylim(0,2.5)\naxes[ai].set_xlim(0,25)\n\n# liquid iron at 1 bar 1811 K Anderson and Ahrens\n#axes[ai,aj].plot([7.019],[1.735],'s',color='red',label='Liq. Iron 1811 K, 1 bar')\n#axes[ai,aj].plot([5.5,6.0,6.5,7.019,12.643,13.015,13.417],[1.344,1.547,1.751,1.723,1.419,1.401,1.303],'o',color='red',label='Liquid Iron')\naxes[ai].errorbar([5.5,6.0,6.5,7.019,12.643,13.015,13.417],[1.344,1.547,1.751,1.723,1.419,1.401,1.303], yerr=[0.269,0.309,0.350,0.116,0.272,0.265,0.269], fmt='o', color='orange', ecolor='orange', capthick=2,label='Liquid Fe data\\n(Anderson & Ahrens 1994)')\n\n# solid alpha-iron at STP\naxes[ai].plot([NewEOS.R0REF,NewEOS.R0REF],[1.65,1.75],'-',linewidth=3,color='blue',label='alpha-Fe solid STP')\n\naxes[ai].plot(rhoarr[indhigh[0]],gammaarr[indhigh[0]],label=\"ANEOS Gamma-high\",color='black')\naxes[ai].plot(rhoarr[indlow[0]], gammaarrlow[indlow[0]],label=\"ANEOS Gamma-low\",color='black',ls='--')\n\naxes[ai].plot(NewEOS.R0REF,NewEOS.gamma0,'+',label=\"ANEOS Gamma0\",color='black')\n\n\naxes[ai].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai].set_ylabel('Gamma (-)',size=sfont)\naxes[ai].tick_params(labelsize=sfont)\n\n\n\n# -----\nai=1\naxes[ai].plot(rhoarr[indhigh[0]],thetaarr[indhigh[0]],label=\"ANEOS Theta-high\",color='black')\naxes[ai].plot(rhoarr[indlow[0]],thetalowarr[indlow[0]],label=\"ANEOS Theta-low\",color='black',ls='--')\naxes[ai].plot(NewEOS.R0REF,theta0,'+',label=\"Theta0\",color='black')\n\naxes[ai].set_ylim(0,2000)\naxes[ai].set_xlim(0,25)\n\naxes[ai].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai].set_ylabel('Theta (K)',size=sfont)\naxes[ai].tick_params(labelsize=sfont)\n\n\naxes[0].legend(fontsize=sfont-5)\naxes[1].legend(fontsize=sfont-5)\n\n\n```\n\n# Specific Heat Capacity and Sounds Speeds\n\n\n\n\n```python\n\nsfont = 15\nfig, axes = plt.subplots(2, 2, figsize=(14,14))\nplt.subplots_adjust(wspace=0.4)\n\n\n#-----------------------------\n# Pick isotherms and set color scale\nixtemparr = [298.,1000.,2000.,5000.,20000.]\n# set color scale same for all plots\ntcolmin=0.\ntcolmax=20000.\n\n# find the index closest to the selected temperatures -- no interpolation\nixindarr=np.zeros(len(ixtemparr))\nixlabelarr = []\nfor i in np.arange(len(ixtemparr)):\n    tmpi=int(np.round(np.interp(ixtemparr[i],NewEOS.T,np.arange(NewEOS.NT))))\n    #print(tmpi,antarr[tmpi])\n    ixindarr[i] = tmpi\n    ixlabelarr.append(str(ixtemparr[i])+' K')\n\n\n#-----------------------\nai=0\naj=0\nfor i in np.arange(len(ixtemparr)):\n    icolscale = (ixtemparr[i]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.rho,NewEOS.cv[int(ixindarr[i]),:]*1000.,c=col,linestyle='-',label=ixlabelarr[i])\n\n#axes[ai,aj].plot(QMDH_r1,QMDH_cv*1000.,styleqmd[0],markersize=styleqmd[2],color=styleqmd[1],label='QMD Hugoniot\\n(Root et al. 2018')\n#axes[ai,aj].plot(2.597,1.73736,'^',color='orange',label='1 bar 2273 K liquid Cv\\n(Thomas & Asimow 20133)')\n#axes[ai,aj].plot(3.,180./(NewEOS.FMW/1.E3)/1.E3,'s',color='orange',label='1 bar 2000 K solid Cv\\n(Gillet et al. 1991)')\naxes[ai,aj].set_ylim(0.,3.)\naxes[ai,aj].set_xlim(0,30)\n\naxes[ai,aj].set_ylabel('Specific heat capacity Cv (kJ/K/kg)',size=sfont)\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n#-----------------------\nai=0\naj=1\nfor i in np.arange(len(ixtemparr)):\n    icolscale = (ixtemparr[i]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.rho,NewEOS.cv[int(ixindarr[i]),:]*1000.*1000./1/8.314*NewEOS.FMW/1000.,c=col,linestyle='-',label=ixlabelarr[i])\n\n\n#axes[ai,aj].plot(QMDH_r1,QMDH_cv*1.E6/7/8.314*0.14,styleqmd[0],markersize=styleqmd[2],color=styleqmd[1],label='QMD Hugoniot\\n(Root et al. 2018')\n#axes[ai,aj].plot(2.597,1737./7/8.314*0.140,'^',color='orange',label='1 bar 2273 K liquid Cv\\n(Thomas & Asimow 2013)')\n#axes[ai,aj].plot(3.,180./(NewEOS.FMW/1.E3)/7/8.314*0.140,'s',color='orange',label='1 bar 2000 K solid Cv\\n(Gillet et al. 1991)')\naxes[ai,aj].set_ylim(1.,7.)\naxes[ai,aj].set_xlim(0,30)\n\naxes[ai,aj].set_ylabel('Specific heat capacity Cv (nR)',size=sfont)\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n#-----------------------\n# plot sound speed along isotherms\nai=1\naj=0\nfor i in np.arange(len(ixtemparr)):\n    icolscale = (ixtemparr[i]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.P[int(ixindarr[i]),:],NewEOS.cs[int(ixindarr[i]),:]/1.e5,c=col,linestyle='-',label=ixlabelarr[i])\n\naxes[ai,aj].plot(1.E-4,GB_cs_stp/1.e3,'+',markersize=10,color='orange',label='alph-iron STP\\n(Guinan & Beshers 1968)')\naxes[ai,aj].plot(1.E-4,3.82,'X',markersize=10,color='orange',label='Liquid iron 1809 K\\n(Nasch et al. 1994)')\n\n\naxes[ai,aj].set_ylim(0,10)\naxes[ai,aj].set_xlim(-10,40)\n\naxes[ai,aj].set_ylabel('Bulk Sound Speed (km/s)',size=sfont)\naxes[ai,aj].set_xlabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n\n#-----------------------\n# plot sound speed along isotherms\nai=1\naj=1\nfor i in np.arange(len(ixtemparr)):\n    icolscale = (ixtemparr[i]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.P[int(ixindarr[i]),:],NewEOS.cs[int(ixindarr[i]),:]/1.e5,c=col,linestyle='-',label=ixlabelarr[i])\n\naxes[ai,aj].plot([225,260],[10,9.5],'d',color='orange',label='Nguyen & Holmes 2004 on Hugoniot')\n\n\naxes[ai,aj].set_ylim(0,20)\naxes[ai,aj].set_xlim(0,700)\n\naxes[ai,aj].set_ylabel('Bulk Sound Speed (km/s)',size=sfont)\naxes[ai,aj].set_xlabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\naxes[0,0].legend(fontsize=sfont-5)\naxes[0,1].legend(fontsize=sfont-5)\naxes[1,0].legend(fontsize=sfont-5)\naxes[1,1].legend(fontsize=sfont-5)\n\n```\n\n# Check the Melt Curve in Tabulated EOS\n\nColored lines correspond to isotherms. Black lines are ANEOS phase boundaries.\n\nTabulations of the equation of state can lead to erroneous material descriptions across the melt curve. In the following plots, the isotherms should be flat (constant pressure) across the phase boundary (black lines). \nEvery 5th isotherm in the table is shown in the plotted regions.\n\nIron requires a very densly populated density grid to capture the melt curve.\n\n\n```python\n# CHECK MELT CURVE GRIDDING\nsfont = 15\nfig, axes = plt.subplots(nrows=5, ncols=2, figsize=(14,26))\nplt.subplots_adjust(wspace=0.5)\ntcolmin=0.\ntcolmax=1.5*NewEOS.cp.T\ntpltmax=1.5*NewEOS.cp.T\n\ntskip=5\n#-------------\nai=0\naj=0\naxes[ai,aj].plot([],[],' ',label='Low pressure melt curve')\n\nfor it in range(1,NewEOS.NT,tskip):\n    icolscale = (NewEOS.T[it]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.rho,NewEOS.P[it,:],'o',markersize=2,linestyle='-',color=col)\n\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.rl,NewEOS.mc.Pl,color=\"black\")\n    axes[ai,aj].plot(NewEOS.mc.rs,NewEOS.mc.Ps,color=\"black\")\n\naxes[ai,aj].set_ylim(0,50)\naxes[ai,aj].set_xlim(6.5,9.5)\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n#-------------\nai=0\naj=1\naxes[ai,aj].plot([],[],' ',label='High pressure melt curve')\n\nfor it in range(1,NewEOS.NT,tskip):\n    icolscale = (NewEOS.T[it]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.rho,NewEOS.P[it,:],'o',markersize=2,linestyle='-',color=col)\n\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.rl,NewEOS.mc.Pl,color=\"black\")\n    axes[ai,aj].plot(NewEOS.mc.rs,NewEOS.mc.Ps,color=\"black\")\n\naxes[ai,aj].set_ylim(50.,150)\naxes[ai,aj].set_xlim(9.0,11.5)\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n\n#-------------\nai=1\naj=0\naxes[ai,aj].plot([],[],' ',label='Higher pressure melt curve')\n\nfor it in range(1,NewEOS.NT,tskip):\n    icolscale = (NewEOS.T[it]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.rho,NewEOS.P[it,:],'o',markersize=2,linestyle='-',color=col)\n\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.rl,NewEOS.mc.Pl,color=\"black\")\n    axes[ai,aj].plot(NewEOS.mc.rs,NewEOS.mc.Ps,color=\"black\")\n\n\naxes[ai,aj].set_ylim(180.,310)\naxes[ai,aj].set_xlim(11.,13.,)\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n\n#-------------\nai=1\naj=1\naxes[ai,aj].plot([],[],' ',label='Higher pressure melt curve')\n\naxes[ai,aj].set_xlabel('Specific Energy (MJ/kg)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n\nfor it in range(1,NewEOS.NT,tskip):\n    icolscale = (NewEOS.T[it]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.U[it,:],NewEOS.P[it,:],'o',markersize=2,linestyle='-',color=col)\n\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.Ul,NewEOS.mc.Pl,color=\"black\")\n    axes[ai,aj].plot(NewEOS.mc.Us,NewEOS.mc.Ps,color=\"black\")\n\naxes[ai,aj].set_ylim(180.,310)\naxes[ai,aj].set_xlim(4,7.5)\n\n#-------------\n\nai=2\naj=0\naxes[ai,aj].plot([],[],' ',label='Low pressure melt curve')\n\naxes[ai,aj].set_xlabel('Specific Entropy (kJ/K/kg)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\nfor it in range(1,NewEOS.NT,tskip):\n    icolscale = (NewEOS.T[it]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.S[it,:]*1.e3,NewEOS.P[it,:],'o',markersize=2,linestyle='-',color=col)\n\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.Sl*1.e3,NewEOS.mc.Pl,color=\"black\")\n    axes[ai,aj].plot(NewEOS.mc.Ss*1.e3,NewEOS.mc.Ps,color=\"black\")\n\naxes[ai,aj].set_ylim(0.,50)\naxes[ai,aj].set_xlim(1.5,2.)\n\n\n#-------------\n\nai=2\naj=1\naxes[ai,aj].plot([],[],' ',label='High pressure melt curve')\n\naxes[ai,aj].set_xlabel('Specific Entropy (kJ/K/kg)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\nfor it in range(1,NewEOS.NT,tskip):\n    icolscale = (NewEOS.T[it]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.S[it,:]*1.e3,NewEOS.P[it,:],'o',markersize=2,linestyle='-',color=col)\n\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.Sl*1.e3,NewEOS.mc.Pl,color=\"black\")\n    axes[ai,aj].plot(NewEOS.mc.Ss*1.e3,NewEOS.mc.Ps,color=\"black\")\n\naxes[ai,aj].set_ylim(50.,150)\naxes[ai,aj].set_xlim(1.6,2.)\n\n\n#-------------\nai=3\naj=0\naxes[ai,aj].plot([],[],' ',label='Low pressure melt curve')\n\naxes[ai,aj].set_xlabel('Specific Energy (MJ/kg)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n\nfor it in range(1,NewEOS.NT,tskip):\n    icolscale = (NewEOS.T[it]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.U[it,:],NewEOS.P[it,:],'o',markersize=2,linestyle='-',color=col)\n\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.Ul,NewEOS.mc.Pl,color=\"black\")\n    axes[ai,aj].plot(NewEOS.mc.Us,NewEOS.mc.Ps,color=\"black\")\n\naxes[ai,aj].set_xlim(0.5,2.)\naxes[ai,aj].set_ylim(0.,50)\n\n#-------------\nai=3\naj=1\naxes[ai,aj].plot([],[],' ',label='High pressure melt curve')\n\naxes[ai,aj].set_xlabel('Specific Energy (MJ/kg)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n\nfor it in range(1,NewEOS.NT,tskip):\n    icolscale = (NewEOS.T[it]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.U[it,:],NewEOS.P[it,:],'o',markersize=2,linestyle='-',color=col)\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.Ul,NewEOS.mc.Pl,color=\"black\")\n    axes[ai,aj].plot(NewEOS.mc.Us,NewEOS.mc.Ps,color=\"black\")\naxes[ai,aj].set_ylim(50.,150)\naxes[ai,aj].set_xlim(1,4.)\n\n\n\n#-------------\nai=4\naj=0\nfor it in range(1,NewEOS.NT,tskip):\n    icolscale = (NewEOS.T[it]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.rho,NewEOS.P[it,:],'o',markersize=2,color=col,linestyle='-')\n\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.rl,NewEOS.mc.Pl,color=\"black\")\n    axes[ai,aj].plot(NewEOS.mc.rs,NewEOS.mc.Ps,color=\"black\")\n\naxes[ai,aj].set_ylim(300,550)\naxes[ai,aj].set_xlim(13.5,15.)\n\naxes[ai,aj].plot([],[],' ',label='Very high pressure melt curve.')\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n#-------------\nai=4\naj=1\nfor it in range(1,NewEOS.NT,tskip):\n    icolscale = (NewEOS.T[it]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.rho,NewEOS.P[it,:],'o',markersize=2,linestyle='-',color=col)\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.rl,NewEOS.mc.Pl,color=\"black\")\n    axes[ai,aj].plot(NewEOS.mc.rs,NewEOS.mc.Ps,color=\"black\")\naxes[ai,aj].set_ylim(800,1000)\naxes[ai,aj].set_xlim(16.5,17.5)\n\naxes[ai,aj].plot([],[],' ',label='Very high pressures')\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n#------\naxes[0,0].legend(fontsize=sfont-5)\naxes[0,1].legend(fontsize=sfont-5)\naxes[1,0].legend(fontsize=sfont-5)\naxes[1,1].legend(fontsize=sfont-5)\naxes[2,0].legend(fontsize=sfont-5)\naxes[2,1].legend(fontsize=sfont-5)\naxes[3,0].legend(fontsize=sfont-5)\naxes[3,1].legend(fontsize=sfont-5)\naxes[4,0].legend(fontsize=sfont-5)\naxes[4,1].legend(fontsize=sfont-5)\n\n\n```\n\n# References\n\nAdams, J. J., Agosta, D. S., Leisure, R. G., & Ledbetter, H. (2006). Elastic constants of monocrystal iron from 3 to 500 K. Journal of applied physics, 100(11), 113530.\n\nAlcock, C. B., Itkin, V. P., & Horrigan, M. K. (1984). Vapour pressure equations for the metallic elements: 298\u20132500K. Canadian Metallurgical Quarterly, 23(3), 309-313.\n\nAnderson, W. W., & Ahrens, T. J. (1994). An equation of state for liquid iron and implications for the Earth's core. Journal of Geophysical Research: Solid Earth, 99(B3), 4273-4284.\n\nAnzellini, S., Dewaele, A., Mezouar, M., Loubeyre, P., & Morard, G. (2013). Melting of iron at Earth\u2019s inner core boundary based on fast X-ray diffraction. Science, 340(6131), 464-466.\n\nAskeland D R, 1996 Materialwissenschaften (Heidelberg: Spektrum Akademischer Verlag GmbH) p. 203\n\nAssael, M. J., Kakosimos, K., Banish, R. M., Brillo, J., Egry, I., Brooks, R., ... & Wakeham, W. A. (2006). Reference data for the density and viscosity of liquid aluminum and liquid iron. Journal of Physical and Chemical Reference Data, 35(1), 285-300.\n\nBeutl, M., Pottlacher, G., & J\u00e4ger, H. (1994). Thermophysical properties of liquid iron. International journal of thermophysics, 15(6), 1323-1331.\n\nBlumm, J., & Henderson, J. B. (2000). Measurement of the volumetric expansion and bulk density of metals in the solid and molten regions. High Temperatures High Pressures, 32(1), 109-114.\n\nBrown, J. M., & McQueen, R. G. (1986). Phase transitions, Gr\u00fcneisen parameter, and elasticity for shocked iron between 77 GPa and 400 GPa. Journal of Geophysical Research: Solid Earth, 91(B7), 7485-7494.\n\nBurakovsky, L., & Preston, D. L. (2004). Analytic model of the Gr\u00fcneisen parameter all densities. Journal of Physics and Chemistry of Solids, 65(8-9), 1581-1587.\n\nBushman, A.V., I. V. Lomonosov and K. V. Khishchenko, et al. (accessed 2019) Shock Wave Database, http://www.ihed.ras.ru/rusbank/\n\nChase Jr, M. W., Curnutt, J. L., Downey Jr, J. R., McDonald, R. A., Syverud, A. N., & Valenzuela, E. A. (1982). JANAF thermochemical tables, 1982 supplement. Journal of Physical and Chemical Reference Data, 11(3), 695-940.  https://janaf.nist.gov\n\nDesai, P. D. (1986). Thermodynamic properties of iron and silicon. Journal of physical and chemical reference data, 15(3), 967-983.\n\nDewaele, A., Loubeyre, P., Occelli, F., Mezouar, M., Dorogokupets, P. I., & Torrent, M. (2006). Quasihydrostatic equation of state of iron above 2 Mbar. Physical Review Letters, 97(21), 215504.\nChicago\t\n\nDorogokupets, P. I., Dymshits, A. M., Litasov, K. D., & Sokolova, T. S. (2017). Thermodynamics and Equations of State of Iron to 350 GPa and 6000 K. Scientific reports, 7, 41863.\n\nDuffy, T., Madhusudhan, N., & Lee, K. K. M. (2015). 2.07 Mineralogy of Super-Earth Planets. Treatise on Geophysics, Second Edition, Elsevier, Oxford.Duffy, T., Madhusudhan, N., & Lee, K. K. M. (2015). 2.07 Mineralogy of Super-Earth Planets. Treatise on Geophysics, Second Edition, Elsevier, Oxford.\n\nDurek, J. J., and G. Ekstrom (1996) Modified PREM (Preliminary Reference Earth Model), doi:10.17611/DP/9785674, http://ds.iris.edu/spud/earthmodel/9785674.\n\nFischer, R. A. (2016). Melting of Fe alloys and the thermal structure of the core. Deep Earth: Physics and chemistry of the lower mantle and core, 217, 3-12.\n\nFischer, R. A., Campbell, A. J., Caracas, R., Reaman, D. M., Dera, P., & Prakapenka, V. B. (2012). Equation of state and phase diagram of Fe\u201316Si alloy as a candidate component of Earth's core. Earth and Planetary Science Letters, 357, 268-276.\n\nFortov, V. E., & Lomonosov, I. V. (2010). Shock waves and equations of state of matter. Shock waves, 20(1), 53-71.\n\nGuinan, M. W., & Beshers, D. N. (1968). Pressure derivatives of the elastic constants of \u03b1-iron to 10 kbs. Journal of Physics and Chemistry of Solids, 29(3), 541-549.\n\nKerley, G. I. (1977). Rational function method of interpolation (No. LA-6903-MS). Los Alamos National Laboratory, Los Alamos, NM (United States).\n\nKerley, G. I. (1993). Multiphase equation of state for iron (No. SAND-93-0027). Sandia National Labs., Albuquerque, NM (United States).\n\nKraus, R. G., Root, S., Lemke, R. W., Stewart, S. T., Jacobsen, S. B., & Mattsson, T. R. (2015). Impact vaporization of planetesimal cores in the late stages of planet formation. Nature Geoscience, 8(4), 269.\n\nLin, J. F., Campbell, A. J., Heinz, D. L., & Shen, G. (2003). Static compression of iron\u2010silicon alloys: Implications for silicon in the Earth's core. Journal of Geophysical Research: Solid Earth, 108(B1).\n\nLyon, S. P., & Johnson, J. D. (1992). SESAME: The LANL equation of state database. Los Alamos National Laboratories Report LAUR-92-3407, Los Alamos, NM.\n\nMedvedev, A. B. (2014). Wide-range multiphase equation of state for iron. Combustion, Explosion, and Shock Waves, 50(5), 582-598.\n\nMorard, G., Boccato, S., Rosa, A. D., Anzellini, S., Miozzi, F., Henry, L., ... & Boulard, E. (2018). Solving controversies on the iron phase diagram under high pressure. Geophysical Research Letters, 45(20), 11-074.\n\nNasch, P. M., Manghnani, M. H., & Secco, R. A. (1994). Sound velocity measurements in liquid iron by ultrasonic interferometry. Journal of Geophysical Research: Solid Earth, 99(B3), 4285-4291.\n\nNguyen, J. H., & Holmes, N. C. (2004). Melting of iron at the physical conditions of the Earth's core. Nature, 427(6972), 339.\n\nTillotson, J. H. (1962). Metallic equations of state for hypervelocity impact (No. GA-3216). General Atomics Division, General Dynamics, San Diego, CA.\n\nSjostrom, T., & Crockett, S. (2018). Quantum molecular dynamics of warm dense iron and a five-phase equation of state. Physical Review E, 97(5), 053209.\n\nZeman, M., Holec, M., & V\u00e1chal, P. (2019). HerEOS: A framework for consistent treatment of the Equation of State in ALE hydrodynamics. Computers & Mathematics with Applications, 78(2), 483-503.\n\n## ANEOS references\nCollins, Gareth S., and H. Jay Melosh (2014). Improvements to ANEOS for multiple phase transitions. 45th Lunar Planet. Sci. Conf. Abs. 2664.\n\nMelosh, H. J. (2007). A hydrocode equation of state for SiO$_2$. Meteoritics & Planetary Science, 42(12), 2079-2098.\n\nThompson, S. L. (1990). ANEOS analytic equations of state for shock physics codes input manual. SANDIA REPORT SAND, 89-2951.\n\nThompson, S. L., & Lauson, H. S. (1972). Improvements in the Chart D radiation-hydrodynamic CODE III: Revised analytic equations of state (No. SC-RR--71-0714). Sandia Labs.\n\nStewart, S., et al. (accepted). The shock physics of giant impacts: Key requirements for the equations of state. In J. Lane, T. Germann, and M. Armstrong (Eds.), 21st Biennial APS Conference on Shock Compression of Condensed Matter (SCCM19). AIP Publishing. (https://arxiv.org/abs/1910.04687)\n\nStewart, S. T. (2019). ANEOS Code Modification: Thermal model adjustment parameter. https://github.com/ststewart/aneos-forsterite-2019/EOS-docs/\n\n\nEnd of File\n\n##### \n", "meta": {"hexsha": "3947be94bc695cc2e1f63742589fecfbef20255f", "size": 792219, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "aneos-canup/iron_aneos.ipynb", "max_stars_repo_name": "ststewart/aneos-iron-2020", "max_stars_repo_head_hexsha": "131167ae664862882e183ba82433b5fe771c4237", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-22T15:15:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T02:04:40.000Z", "max_issues_repo_path": "aneos-canup/iron_aneos.ipynb", "max_issues_repo_name": "ststewart/aneos-iron-2020", "max_issues_repo_head_hexsha": "131167ae664862882e183ba82433b5fe771c4237", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aneos-canup/iron_aneos.ipynb", "max_forks_repo_name": "ststewart/aneos-iron-2020", "max_forks_repo_head_hexsha": "131167ae664862882e183ba82433b5fe771c4237", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 246.8741040823, "max_line_length": 221300, "alphanum_fraction": 0.885844697, "converted": true, "num_tokens": 46467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490155654565424, "lm_q2_score": 0.06008665606493927, "lm_q1q2_score": 0.027934379932213642}}
{"text": "# California wildfires 2017 - Thomas Fire analysis\n\nThe Thomas Fire is a massive wildfire burning in Ventura and Santa Barbara Counties, and one of multiple wildfires that started in early December 2017 in Southern California. It has burned approximately 270,500 acres (423 sq mi; 1,095 km2), becoming the largest wildfire of the 2017 California wildfire season, and the third-largest wildfire in modern California history.\n\n\n\n\n```python\nfrom arcgis.gis import *\nimport pandas as pd\n```\n\n\n```python\ngis = GIS(\"https://python.playground.esri.com/portal\", \"arcgis_python\", \"amazing_arcgis_123\") \n```\n\n\n```python\nlandsat_item = gis.content.search('title:Multispectral Landsat', 'Imagery Layer', outside_org=True)[0]\nlandsat = landsat_item.layers[0]\nlandsat_item\n```\n\n\n\n\n<div class=\"item_container\" style=\"height: auto; overflow: hidden; border: 1px solid #cfcfcf; border-radius: 2px; background: #f6fafa; line-height: 1.21429em; padding: 10px;\">\n                    <div class=\"item_left\" style=\"width: 210px; float: left;\">\n                       <a href='https://python.playground.esri.com/portal/home/item.html?id=d9b466d6a9e647ce8d1dd5fe12eb434b' target='_blank'>\n                        \n                       </a>\n                    </div>\n\n                    <div class=\"item_right\"     style=\"float: none; width: auto; overflow: hidden;\">\n                        <a href='https://python.playground.esri.com/portal/home/item.html?id=d9b466d6a9e647ce8d1dd5fe12eb434b' target='_blank'><b>Multispectral Landsat</b>\n                        </a>\n                        <br/>Landsat 8 OLI, 30m Multispectral 8 band scenes with visual renderings and indices. Updated daily. Based on the Landsat on AWS collections.Imagery Layer by esri_livingatlas\n                        <br/>Last Modified: October 06, 2016\n                        <br/>0 comments, 0 views\n                    </div>\n                </div>\n\n\n\n\n### Select before and after rasters\n\n\n```python\naoi = {'spatialReference': {'latestWkid': 3857, 'wkid': 102100}, 'type': 'extent', \n       'xmax': -13305000, 'xmin': -13315000, 'ymax': 4106000, 'ymin': 4052000}\nlandsat.extent = aoi\n```\n\n\n```python\nselected = landsat.filter_by(where=\"(Category = 1)\",\n                             geometry=arcgis.geometry.filters.intersects(aoi))\n\ndf = selected.query(out_fields=\"AcquisitionDate, GroupName, CloudCover, DayOfYear\", order_by_fields=\"AcquisitionDate\").df\ndf['AcquisitionDate'] = pd.to_datetime(df['AcquisitionDate'], unit='ms')\ndf.tail()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>AcquisitionDate</th>\n      <th>CloudCover</th>\n      <th>DayOfYear</th>\n      <th>GroupName</th>\n      <th>OBJECTID</th>\n      <th>Shape_Area</th>\n      <th>Shape_Length</th>\n      <th>SHAPE</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>74</th>\n      <td>2017-10-22 18:34:49.100</td>\n      <td>0.0004</td>\n      <td>295</td>\n      <td>LC80420362017295LGN00_MTL</td>\n      <td>580864</td>\n      <td>5.128295e+10</td>\n      <td>906224.695944</td>\n      <td>{'rings': [[[-13210242.4169, 4199065.126800001...</td>\n    </tr>\n    <tr>\n      <th>75</th>\n      <td>2017-11-07 18:34:47.721</td>\n      <td>0.2025</td>\n      <td>311</td>\n      <td>LC80420362017311LGN00_MTL</td>\n      <td>584295</td>\n      <td>5.129209e+10</td>\n      <td>906301.639126</td>\n      <td>{'rings': [[[-13210307.907200001, 4199065.8737...</td>\n    </tr>\n    <tr>\n      <th>76</th>\n      <td>2017-11-23 18:34:42.440</td>\n      <td>0.0441</td>\n      <td>327</td>\n      <td>LC80420362017327LGN00_MTL</td>\n      <td>591810</td>\n      <td>5.131484e+10</td>\n      <td>906509.716682</td>\n      <td>{'rings': [[[-13208036.3849, 4199102.123899996...</td>\n    </tr>\n    <tr>\n      <th>77</th>\n      <td>2017-12-09 18:34:39.504</td>\n      <td>0.2136</td>\n      <td>343</td>\n      <td>LC80420362017343LGN00_MTL</td>\n      <td>599875</td>\n      <td>5.127378e+10</td>\n      <td>906136.246386</td>\n      <td>{'rings': [[[-13208251.4004, 4199098.6241], [-...</td>\n    </tr>\n    <tr>\n      <th>78</th>\n      <td>2017-12-25 18:34:42.003</td>\n      <td>0.6529</td>\n      <td>359</td>\n      <td>LC80420362017359LGN00_MTL</td>\n      <td>608116</td>\n      <td>5.129089e+10</td>\n      <td>906293.823931</td>\n      <td>{'rings': [[[-13210387.2213, 4199063.157099999...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nprefire = landsat.filter_by('OBJECTID=591810') # 2017-11-23 \nmidfire = landsat.filter_by('OBJECTID=599875') # 2017-12-09 \n```\n\n## Visual Assessment\n\n\n```python\nfrom arcgis.raster.functions import *\n\napply(midfire, 'Natural Color with DRA')\n```\n\n\n\n\n    \n\n    \n\n\n\n### Visualize Burn Scars\n\nExtract the [6, 4, 1] bands to improve visibility of fire and burn scars. This band combination pushes further into the SWIR range of the electromagnetic spectrum, where there is less susceptibility to smoke and haze generated by a burning fire.\n\n\n```python\nextract_band(midfire, [6,4,1])\n```\n\n\n\n\n    \n\n    \n\n\n\nFor comparison, the same area before the fire started shows no burn scar:\n\n\n```python\nextract_band(prefire, [6,4,1])\n```\n\n\n\n\n    \n\n    \n\n\n\n## Quantitative Assessment\n\nThe **Normalized Burn Ratio (NBR)** was defined to highlight areas that have burned and to index the severity of a burn using Landsat imagery.\n\nThe formula for the NBR is very similar to that of NDVI except that it uses near-infrared band 5 and the short-wave infrared band 7:\n\\begin{align}\n{\\mathbf{NBR}} = \\frac{\\mathbf{B_5} - \\mathbf{B_7}}{\\mathbf{B_5} + \\mathbf{B_7}} \\\\   \n\\end{align}\n\nThe NBR equation was designed to be calcualted from reflectance, but it can be calculated from radiance and digital_number_(dn) with changes to the burn severity table below. \n\nFor a given area, NBR is calculated from an image just prior to the burn and a second NBR is calculated for an image immediately following the burn. Burn extent and severity is judged by taking the difference between these two index layers:\n\n\\begin{align}\n{\\Delta \\mathbf{NBR}} = \\mathbf{NBR_{prefire}} - \\mathbf{NBR_{postfire}} \\\\   \n\\end{align}\n\nThe meaning of the \u2206NBR values can vary by scene, and interpretation in specific instances should always be based on some field assessment. However, the following table from the USGS FireMon program can be useful as a first approximation for interpreting the NBR difference:\n\n\n| \\begin{align}{\\Delta \\mathbf{NBR}}  \\end{align}      | Burn Severity |\n| ------------- |:-------------:|\n| 0.1 to 0.27   | Low-severity burn |\n| 0.27 to 0.44  | Moderate-low severity burn |\n| 0.44 to 0.66 | Moderate-high severity burn |\n| > 0.66 | High severity burn |\n\n[Source: http://wiki.landscapetoolbox.org/doku.php/remote_sensing_methods:normalized_burn_ratio]\n\n\n```python\nnbr_prefire  = band_arithmetic(prefire, \"(b5 - b7) / (b5 + b7)\")\nnbr_postfire = band_arithmetic(midfire, \"(b5 - b7) / (b5 + b7)\")\n\nnbr_diff = nbr_prefire - nbr_postfire\n```\n\n\n```python\nmask = remap(nbr_diff,\n             input_ranges=[0.1, 0.27, 0.27, 0.44, 0.44, 0.66, 0.66, 1],  # change in NBR\n             output_values=[1, 2, 3, 4],                                 # burn severity\n             no_data_ranges=[-1, 0.1], astype='u8')\n```\n\n### Compute burnt area\n\n\n```python\next = {\"xmax\": -13246079.10806628, \"ymin\": 4035733.9433013694, \"xmin\": -13438700.419344831, \"ymax\": 4158033.188557592,\n       \"spatialReference\": {\"wkid\": 102100, \"latestWkid\": 3857}, \"type\": \"extent\"}\npixx = (ext['xmax'] - ext['xmin']) / 1200.0\npixy = (ext['ymax'] - ext['ymin']) / 450.0\n```\n\n\n```python\nres = mask.compute_histograms(ext, pixel_size={'x':pixx, 'y':pixy})\nnumpix = 0\nfor i in res['histograms'][0]['counts']:\n    numpix += i\n    \nsqmarea = numpix * pixx * pixy # in sq. m\nacres = 0.00024711 * sqmarea   # in acres\n\nprint('Thomas fire had consumed {:,} acres till 09 December 2017.'.format(int(acres)))\n```\n\n    Thomas fire had consumed 229,304 acres till 09 December 2017.\n\n\n### Visualize burnt areas\n\n\n```python\nburnt_areas = colormap(mask, colormap=[[4, 0xFF, 0xC3, 0],\n                            [3, 0xFA, 0x8E, 0],\n                            [2, 0xF2, 0x55, 0],\n                            [1, 0xE6, 0,    0]])\n```\n\n\n```python\nm = gis.map('Carpinteria, CA', zoomlevel=10)\nm\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>MapView</code>.</p>\n<p>\n  If you're reading this message in Jupyter Notebook or JupyterLab, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another notebook frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n\n```python\nm.add_layer([midfire, burnt_areas])\n```\n\nCompare with final extent of Thomas Fire.\n\n\n```python\nfrom arcgis.features import FeatureLayer\nlive_fires = FeatureLayer('https://services6.arcgis.com/l7uujk4hHifqabRB/arcgis/rest/services/Thomas_Fire/FeatureServer/1')\n\nlive_fires_df = live_fires.query().df\n```\n\n\n```python\nm.add_layer(live_fires, {'opacity': 0.5})\n```\n\n## Impact Assessment\n\n\n```python\nfrom arcgis.geoenrichment import *\n```\n\n\n```python\nthomas_pop = enrich(live_fires_df, 'Age')\n```\n\n### Visualize using charts\n\n\n```python\nimport warnings\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n%matplotlib inline\nwarnings.simplefilter(action='ignore', category=FutureWarning)\npd.options.mode.chained_assignment = None \nplt.style.use('ggplot')\n\nsf = thomas_pop.T\nsf.reset_index(inplace=True)\nsf['age'] = sf['index'].str.extract('(\\d+)')\n\nfem = sf[sf['index'].str.startswith('FEM')]\nfem.rename(columns={0:'female'}, inplace=True)\nfem['age'] = pd.to_numeric(fem['age'])\nfem.sort_values(by='age', ascending=False, inplace=True)\n\nmale = sf[sf['index'].str.startswith('MALE')]\nmale.rename(columns={0:'male'}, inplace=True)\nmale['age'] = pd.to_numeric(male['age'])\nmale.sort_values(by='age', ascending=False, inplace=True)\n\npopdf = pd.merge(male, fem, on='age')\npopdf['agelabel'] = popdf['age'].map(str) + ' - ' + (popdf['age']+4).map(str)\npopdf['male'] = -popdf['male']\n```\n\n### Age Pyramid of affected population\n\n\n```python\nprint('Number of people in fire perimeter: ' + str(popdf['female'].sum() - popdf['male'].sum()))\n```\n\n    Number of people in fire perimeter: 11228\n\n\n\n```python\nsns.barplot(x=\"female\", y=\"agelabel\", color=\"#CC6699\", label=\"Female\", data=popdf, edgecolor='none')\nsns.barplot(x=\"male\",   y=\"agelabel\", color=\"#008AB8\", label=\"Male\",   data=popdf,  edgecolor='none')\nplt.ylabel('Age group')\nplt.xlabel('Number of people');\n```\n", "meta": {"hexsha": "7ae15b2a9f027532c76136cd2e6cf5ec0d8418b0", "size": 383908, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "samples/04_gis_analysts_data_scientists/california_wildfires_2017_thomas_fire_analysis.ipynb", "max_stars_repo_name": "merinogeospatial/arcgis-python-api", "max_stars_repo_head_hexsha": "20c4125eeda2a6f2c1b5757a4fa0298e913741ad", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-03-12T20:02:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T14:52:48.000Z", "max_issues_repo_path": "samples/04_gis_analysts_data_scientists/california_wildfires_2017_thomas_fire_analysis.ipynb", "max_issues_repo_name": "merinogeospatial/arcgis-python-api", "max_issues_repo_head_hexsha": "20c4125eeda2a6f2c1b5757a4fa0298e913741ad", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "samples/04_gis_analysts_data_scientists/california_wildfires_2017_thomas_fire_analysis.ipynb", "max_forks_repo_name": "merinogeospatial/arcgis-python-api", "max_forks_repo_head_hexsha": "20c4125eeda2a6f2c1b5757a4fa0298e913741ad", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-05-15T03:49:42.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-15T03:49:42.000Z", "avg_line_length": 549.2246065808, "max_line_length": 125929, "alphanum_fraction": 0.9414130469, "converted": true, "num_tokens": 3395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2845759920814681, "lm_q2_score": 0.098079314902464, "lm_q1q2_score": 0.02791101834103941}}
{"text": "```\nprint \"Hallo Welt!\"\n```\n\n    Hallo Welt!\n\n\n\n```\n2**200\n```\n\n\n\n\n    1606938044258990275541962092341162602522202993782792835301376L\n\n\n\n\n```\n# Multi-line editing. Syntax-coloring.\nfor num in ['eins', 'zwei', 'drei']:\n    print \"Line %s\" % num\n```\n\n    Line eins\n    Line zwei\n    Line drei\n\n\n# \u00dcberschriften\n\nNormaler Text in ganzen S\u00e4tzen. Formatiert als Markdown: *hervorgehoben* **fett**\n\n## Hilfe und Tab-Completion\n\n\n```\ns=\"hallo welt\"\n#s?\n#s.encode(\ns.encode(\"base64\")\n```\n\n\n\n\n    'aGFsbG8gd2VsdA==\\n'\n\n\n\n## Dateiformat: JSON\n\nAbspeichern als JSON, wieder einladen\n\n# Shell-Kommandos\n\n\n```\n!ls -l\n```\n\n    insgesamt 10272\r\n    -rw-rw-rw-  1 dloss dloss  302868 Mai  2 14:41 Bitcoin.ipynb\r\n    -rw-rw-rw-  1 dloss dloss    1147 Mai  2 14:37 bitcoin_weighted_prices.json\r\n    drwxrwxr-x  2 dloss dloss    4096 Apr 29 18:42 bundesliga\r\n    -rw-rw-rw-  1 dloss dloss  119335 Apr  7 16:37 bundesliga.ipynb\r\n    -rw-rw-r--  1 dloss dloss  408138 Mai  2 16:28 Chapter1_Introduction.ipynb\r\n    drwxrwxr-x  7 dloss dloss   12288 Apr 29 18:42 crosscompute-tutorials\r\n    drwxrwxrwx  3 dloss dloss    4096 Mai  1 17:46 datasets\r\n    -rw-rw-rw-  1 dloss dloss 2353817 Mai  3 09:54 datenanalyse-ipython-pandas.pdf\r\n    -rw-rw-rw-  1 dloss dloss 2727936 Mai  2 15:30 datenanalyse-ipython-pandas.ppt\r\n    -rw-rw-rw-  1 dloss dloss  792146 Apr  7 17:00 E1_BEZIRK_201112.csv\r\n    -rw-rw-rw-  1 dloss dloss  225923 Nov 24 20:17 ergebnisse-1963-2010.zip\r\n    -rw-r--r--  1 dloss dloss    2048 Mai  2 15:38 foo.db\r\n    -rw-rw-rw-  1 dloss dloss    2037 Apr 20 12:59 genua-vortrag.txt\r\n    drwxrwxrwx  4 dloss dloss    4096 Mai  1 17:03 hpf\r\n    -rw-rw-rw-  1 dloss dloss  326577 Mai  2 13:58 hpf-admin.ipynb\r\n    -rw-rw-rw-  1 dloss dloss  148820 Mai  2 15:41 IPython-Demo.ipynb\r\n    -rw-rw-r--  1 dloss dloss   27092 Mai  1 16:35 ipy.vim\r\n    -rw-rw-r--  1 dloss dloss     217 Mai  3 10:14 links.txt\r\n    -rw-rw-rw-  1 dloss dloss  861410 Apr 27 21:29 mtgox.csv\r\n    -rw-rw-rw-  1 dloss dloss  861218 Mai  2 16:33 mtgoxUSD.csv\r\n    -rw-rw-rw-  1 dloss dloss  167366 Apr  7 18:28 Muenchen.ipynb\r\n    -rw-rw-r--  1 dloss dloss   21907 Mai  2 16:23 mypicture.pdf\r\n    drwxrwxr-x  6 dloss dloss    4096 Mai  1 13:25 notebooks\r\n    -rw-rw-rw-  1 dloss dloss  355731 Mai  2 15:37 OpenBSD.ipynb\r\n    drwxrwxr-x 11 dloss dloss    4096 Mai  2 10:59 other\r\n    -rw-rw-rw-  1 dloss dloss   54449 M\u00e4r 28 21:00 pandas_basics.ipynb\r\n    -rw-rw-rw-  1 dloss dloss   84604 M\u00e4r 30 21:11 Pandas Cookbook.ipynb\r\n    drwxrwxr-x  3 dloss dloss    4096 Apr 29 18:49 pandas-demo\r\n    drwxrwxr-x  3 dloss dloss    4096 Apr 29 18:53 pcap\r\n    -rw-rw-rw-  1 dloss dloss   31161 Mai  2 13:02 pcap.ipynb\r\n    -rw-rw-rw-  1 dloss dloss   26785 Mai  1 13:01 Pi.ipynb\r\n    -rw-rw-rw-  1 dloss dloss  191731 Apr 28 22:17 python-slices.graffle\r\n    -rw-rw-r--  1 dloss dloss   76393 Mai  1 16:30 stock_data.csv\r\n    drwxrwxr-x  3 dloss dloss   12288 Apr 29 18:42 tippkick\r\n    -rw-rw-r--  1 dloss dloss    7943 Mai  1 16:30 tips.csv\r\n    drwxr-xr-x  7 dloss dloss    4096 Apr 30 23:08 tutorials\r\n    -rw-rw-r--  1 dloss dloss    2267 Mai  2 16:12 Vortrag.ipynb\r\n\n\n\n```\n!head -20 IPython-Demo.ipynb\n```\n\n    {\r\n     \"metadata\": {\r\n      \"name\": \"IPython-Demo\"\r\n     },\r\n     \"nbformat\": 3,\r\n     \"nbformat_minor\": 0,\r\n     \"worksheets\": [\r\n      {\r\n       \"cells\": [\r\n        {\r\n         \"cell_type\": \"code\",\r\n         \"collapsed\": false,\r\n         \"input\": [\r\n          \"print \\\"Hallo Welt!\\\"\"\r\n         ],\r\n         \"language\": \"python\",\r\n         \"metadata\": {},\r\n         \"outputs\": [\r\n          {\r\n           \"output_type\": \"stream\",\r\n\n\nPython-Variablen \u00fcbergeben\n\n\n```\ninterface=\"eth0\"\ndata = !ifconfig $interface\ndata.fields()\n```\n\n\n\n\n    [['/bin/sh:', '1:', 'ifconfig:', 'not', 'found']]\n\n\n\n\n```\n# Interrupt with CTRL-m i\n!ping -c 6 8.8.8.8\n```\n\n    PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.\r\n    From 192.168.253.1 icmp_seq=1 Destination Port Unreachable\r\n    From 192.168.253.1 icmp_seq=2 Destination Port Unreachable\r\n    From 192.168.253.1 icmp_seq=3 Destination Port Unreachable\r\n    From 192.168.253.1 icmp_seq=4 Destination Port Unreachable\r\n    From 192.168.253.1 icmp_seq=5 Destination Port Unreachable\r\n    From 192.168.253.1 icmp_seq=6 Destination Port Unreachable\r\n    \r\n    --- 8.8.8.8 ping statistics ---\r\n    6 packets transmitted, 0 received, +6 errors, 100% packet loss, time 5001ms\r\n    \r\n\n\n### Andere Programmiersprachen\n\n\n```ruby\n%%ruby\nname = \"Ruby\"\n3.times { puts \"Hallo #{ name }\" }\n```\n\n    Hallo Ruby\n    Hallo Ruby\n    Hallo Ruby\n\n\n\n```perl\n%%perl\n# https://github.com/peelle/Perl-Euler-Solutions/blob/master/1/solution.pl\n# Straight forward iteration over each number\nmy $sum_of_multiples = 0;\n \nforeach my $number ( 1..999 ) {\n# using modulus to filter\nnext if ( $number % 3 and $number % 5 );\n$sum_of_multiples += $number;\n}\n\nprint $sum_of_multiples;\n```\n\n    233168\n\n\n```bash\n%%bash --out output --err error\necho \"Zeilen:\"\nfor i in a b c d; do echo $i; done\n```\n\nStdout wurde an *output* \u00fcbergeben:\n\n\n```\nprint output\n```\n\n    Zeilen:\n    a\n    b\n    c\n    d\n    \n\n\n\n```\n%%script lua\nfunction allwords ()\n  local line = \"Hallo Lua program\"\n  local pos = 1           -- current position in the line\n  return function ()      -- iterator function\n    while line do         -- repeat while there are lines\n      local s, e = string.find(line, \"%w+\", pos)\n      if s then           -- found a word?\n        pos = e + 1       -- next position is after this word\n        return string.sub(line, s, e)     -- return the word\n      else\n        line = io.read()  -- word not found; try next line\n        pos = 1           -- restart from first position\n      end\n    end\n    return nil            -- no more lines: end of traversal\n  end\nend\n\n\n-- use example\nfor word in allwords() do\n  print(word)\nend\n```\n\n    Hallo\n    Lua\n    program\n\n\n# Plotting\n\n\n```\n%pylab inline\n```\n\n    \n    Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline].\n    For more information, type 'help(pylab)'.\n\n\n\n```\nx = np.random.normal(size=1000)\ny = np.random.normal(size=1000)\nscatter(x, y, alpha=0.2)\nsavefig(\"mypicture.pdf\")\n```\n\n\n```\nx = np.linspace(1, 18, 100)\ny = x[:, np.newaxis]\nim = y * np.sin(x) \nplt.imshow(im, cmap=matplotlib.cm.gray)\n```\n\n### Matplotlib Gallery\n\n\n```\n%load http://matplotlib.org/mpl_examples/api/radar_chart.py\n```\n\n\n```\n\"\"\"\nExample of creating a radar chart (a.k.a. a spider or star chart) [1]_.\n\nAlthough this example allows a frame of either 'circle' or 'polygon', polygon\nframes don't have proper gridlines (the lines are circles instead of polygons).\nIt's possible to get a polygon grid by setting GRIDLINE_INTERPOLATION_STEPS in\nmatplotlib.axis to the desired number of vertices, but the orientation of the\npolygon is not aligned with the radial axes.\n\n.. [1] http://en.wikipedia.org/wiki/Radar_chart\n\"\"\"\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.path import Path\nfrom matplotlib.spines import Spine\nfrom matplotlib.projections.polar import PolarAxes\nfrom matplotlib.projections import register_projection\n\n\ndef radar_factory(num_vars, frame='circle'):\n    \"\"\"Create a radar chart with `num_vars` axes.\n\n    This function creates a RadarAxes projection and registers it.\n\n    Parameters\n    ----------\n    num_vars : int\n        Number of variables for radar chart.\n    frame : {'circle' | 'polygon'}\n        Shape of frame surrounding axes.\n\n    \"\"\"\n    # calculate evenly-spaced axis angles\n    theta = 2*np.pi * np.linspace(0, 1-1./num_vars, num_vars)\n    # rotate theta such that the first axis is at the top\n    theta += np.pi/2\n\n    def draw_poly_patch(self):\n        verts = unit_poly_verts(theta)\n        return plt.Polygon(verts, closed=True, edgecolor='k')\n\n    def draw_circle_patch(self):\n        # unit circle centered on (0.5, 0.5)\n        return plt.Circle((0.5, 0.5), 0.5)\n\n    patch_dict = {'polygon': draw_poly_patch, 'circle': draw_circle_patch}\n    if frame not in patch_dict:\n        raise ValueError('unknown value for `frame`: %s' % frame)\n\n    class RadarAxes(PolarAxes):\n\n        name = 'radar'\n        # use 1 line segment to connect specified points\n        RESOLUTION = 1\n        # define draw_frame method\n        draw_patch = patch_dict[frame]\n\n        def fill(self, *args, **kwargs):\n            \"\"\"Override fill so that line is closed by default\"\"\"\n            closed = kwargs.pop('closed', True)\n            return super(RadarAxes, self).fill(closed=closed, *args, **kwargs)\n\n        def plot(self, *args, **kwargs):\n            \"\"\"Override plot so that line is closed by default\"\"\"\n            lines = super(RadarAxes, self).plot(*args, **kwargs)\n            for line in lines:\n                self._close_line(line)\n\n        def _close_line(self, line):\n            x, y = line.get_data()\n            # FIXME: markers at x[0], y[0] get doubled-up\n            if x[0] != x[-1]:\n                x = np.concatenate((x, [x[0]]))\n                y = np.concatenate((y, [y[0]]))\n                line.set_data(x, y)\n\n        def set_varlabels(self, labels):\n            self.set_thetagrids(theta * 180/np.pi, labels)\n\n        def _gen_axes_patch(self):\n            return self.draw_patch()\n\n        def _gen_axes_spines(self):\n            if frame == 'circle':\n                return PolarAxes._gen_axes_spines(self)\n            # The following is a hack to get the spines (i.e. the axes frame)\n            # to draw correctly for a polygon frame.\n\n            # spine_type must be 'left', 'right', 'top', 'bottom', or `circle`.\n            spine_type = 'circle'\n            verts = unit_poly_verts(theta)\n            # close off polygon by repeating first vertex\n            verts.append(verts[0])\n            path = Path(verts)\n\n            spine = Spine(self, spine_type, path)\n            spine.set_transform(self.transAxes)\n            return {'polar': spine}\n\n    register_projection(RadarAxes)\n    return theta\n\n\ndef unit_poly_verts(theta):\n    \"\"\"Return vertices of polygon for subplot axes.\n\n    This polygon is circumscribed by a unit circle centered at (0.5, 0.5)\n    \"\"\"\n    x0, y0, r = [0.5] * 3\n    verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta]\n    return verts\n\n\ndef example_data():\n    #The following data is from the Denver Aerosol Sources and Health study.\n    #See  doi:10.1016/j.atmosenv.2008.12.017\n    #\n    #The data are pollution source profile estimates for five modeled pollution\n    #sources (e.g., cars, wood-burning, etc) that emit 7-9 chemical species.\n    #The radar charts are experimented with here to see if we can nicely\n    #visualize how the modeled source profiles change across four scenarios:\n    #  1) No gas-phase species present, just seven particulate counts on\n    #     Sulfate\n    #     Nitrate\n    #     Elemental Carbon (EC)\n    #     Organic Carbon fraction 1 (OC)\n    #     Organic Carbon fraction 2 (OC2)\n    #     Organic Carbon fraction 3 (OC3)\n    #     Pyrolized Organic Carbon (OP)\n    #  2)Inclusion of gas-phase specie carbon monoxide (CO)\n    #  3)Inclusion of gas-phase specie ozone (O3).\n    #  4)Inclusion of both gas-phase speciesis present...\n    data = {\n        'column names':\n            ['Sulfate', 'Nitrate', 'EC', 'OC1', 'OC2', 'OC3', 'OP', 'CO',\n             'O3'],\n        'Basecase':\n            [[0.88, 0.01, 0.03, 0.03, 0.00, 0.06, 0.01, 0.00, 0.00],\n             [0.07, 0.95, 0.04, 0.05, 0.00, 0.02, 0.01, 0.00, 0.00],\n             [0.01, 0.02, 0.85, 0.19, 0.05, 0.10, 0.00, 0.00, 0.00],\n             [0.02, 0.01, 0.07, 0.01, 0.21, 0.12, 0.98, 0.00, 0.00],\n             [0.01, 0.01, 0.02, 0.71, 0.74, 0.70, 0.00, 0.00, 0.00]],\n        'With CO':\n            [[0.88, 0.02, 0.02, 0.02, 0.00, 0.05, 0.00, 0.05, 0.00],\n             [0.08, 0.94, 0.04, 0.02, 0.00, 0.01, 0.12, 0.04, 0.00],\n             [0.01, 0.01, 0.79, 0.10, 0.00, 0.05, 0.00, 0.31, 0.00],\n             [0.00, 0.02, 0.03, 0.38, 0.31, 0.31, 0.00, 0.59, 0.00],\n             [0.02, 0.02, 0.11, 0.47, 0.69, 0.58, 0.88, 0.00, 0.00]],\n        'With O3':\n            [[0.89, 0.01, 0.07, 0.00, 0.00, 0.05, 0.00, 0.00, 0.03],\n             [0.07, 0.95, 0.05, 0.04, 0.00, 0.02, 0.12, 0.00, 0.00],\n             [0.01, 0.02, 0.86, 0.27, 0.16, 0.19, 0.00, 0.00, 0.00],\n             [0.01, 0.03, 0.00, 0.32, 0.29, 0.27, 0.00, 0.00, 0.95],\n             [0.02, 0.00, 0.03, 0.37, 0.56, 0.47, 0.87, 0.00, 0.00]],\n        'CO & O3':\n            [[0.87, 0.01, 0.08, 0.00, 0.00, 0.04, 0.00, 0.00, 0.01],\n             [0.09, 0.95, 0.02, 0.03, 0.00, 0.01, 0.13, 0.06, 0.00],\n             [0.01, 0.02, 0.71, 0.24, 0.13, 0.16, 0.00, 0.50, 0.00],\n             [0.01, 0.03, 0.00, 0.28, 0.24, 0.23, 0.00, 0.44, 0.88],\n             [0.02, 0.00, 0.18, 0.45, 0.64, 0.55, 0.86, 0.00, 0.16]]}\n    return data\n\n\nif __name__ == '__main__':\n    N = 9\n    theta = radar_factory(N, frame='polygon')\n\n    data = example_data()\n    spoke_labels = data.pop('column names')\n\n    fig = plt.figure(figsize=(9, 9))\n    fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)\n\n    colors = ['b', 'r', 'g', 'm', 'y']\n    # Plot the four cases from the example data on separate axes\n    for n, title in enumerate(data.keys()):\n        ax = fig.add_subplot(2, 2, n+1, projection='radar')\n        plt.rgrids([0.2, 0.4, 0.6, 0.8])\n        ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1),\n                     horizontalalignment='center', verticalalignment='center')\n        for d, color in zip(data[title], colors):\n            ax.plot(theta, d, color=color)\n            ax.fill(theta, d, facecolor=color, alpha=0.25)\n        ax.set_varlabels(spoke_labels)\n\n    # add legend relative to top-left plot\n    plt.subplot(2, 2, 1)\n    labels = ('Factor 1', 'Factor 2', 'Factor 3', 'Factor 4', 'Factor 5')\n    legend = plt.legend(labels, loc=(0.9, .95), labelspacing=0.1)\n    plt.setp(legend.get_texts(), fontsize='small')\n\n    plt.figtext(0.5, 0.965, '5-Factor Solution Profiles Across Four Scenarios',\n                ha='center', color='black', weight='bold', size='large')\n    plt.show()\n\n```\n\n# Rich display\n\n\n```\nfrom IPython.core.display import Image, HTML, SVG\n```\n\n\n```\nImage(filename=\"/usr/share/doc/texlive-doc/latex/ctable/penguin.jpg\")\n```\n\n\n\n\n    \n\n    \n\n\n\n\n```\nSVG(filename=\"/usr/share/doc/ipython/examples/notebooks/python-logo.svg\")\n```\n\n\n\n\n    \n\n    \n\n\n\n\n```\nfrom IPython.display import HTML\nHTML('')\n```\n\n\n\n\n\n\n\n\n\n```\nfrom IPython.display import YouTubeVideo\nYouTubeVideo(\"2G5YTlheCbw\")\n```\n\n\n\n\n\n\n\n\n\n\n\n```\nimport IPython\nIPython.display.Math(r\"\\sum_{n=1}^\\infty \\frac{1}{n^2} = \\frac{\\pi^2}{6}\")\n```\n\n\n\n\n$$\\sum_{n=1}^\\infty \\frac{1}{n^2} = \\frac{\\pi^2}{6}$$\n\n\n\nLaTeX innerhalb von Markdown geht auch: $\\frac{1}{\\sqrt{ 2 \\pi \\sigma^2 }} e^{ - \\frac{ (x - \\mu)^2 } {2 \\sigma^2} }$\n\n### Darstellungen f\u00fcr eigene Objekte:\n\n\n```\nclass Disc(object):\n    def __init__(self, size, color='red'):\n        self.size = size\n        self.color = color\n        \n    def _repr_svg_(self):\n        return \"\"\"<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n                  <circle cx=\"{0:d}\" cy=\"{0:d}\" r=\"{0:d}\" fill=\"{1:s}\" />\n                  </svg>\"\"\".format(self.size, self.color)\n```\n\n\n```\nDisc(65, \"blue\")\n```\n\n\n\n\n    \n\n    \n\n\n\n# SymPy\n\n\n```\nfrom sympy import *\n%load_ext sympy.interactive.ipythonprinting\nx = Symbol('x')\n```\n\n    /usr/lib/pymodules/python2.7/mpl_toolkits/__init__.py:2: UserWarning: Module mpl_toolkits was already imported from /usr/lib/pymodules/python2.7/mpl_toolkits/__init__.pyc, but /usr/local/lib/python2.7/dist-packages is being added to sys.path\n      __import__('pkg_resources').declare_namespace(__name__)\n\n\n\n```\npi.evalf(100)\n```\n\n\n```\n(pi+x*2)**3\n```\n\n\n```\n((pi+x*2)**3).expand()\n```\n\n# SQL Extension\n\n\n```\n%load_ext sql\n```\n\n\n```\nrm -rf foo.db\n```\n\n\n```\n%sql sqlite:///foo.db\n```\n\n\n\n\n    u'Connected: None@foo.db'\n\n\n\n\n```sql\n%%sql sqlite:///foo.db\nCREATE TABLE writer (first_name, last_name, year_of_death);\nINSERT INTO writer VALUES ('William', 'Shakespeare', 1616);\nINSERT INTO writer VALUES ('Bertold', 'Brecht', 1956);\n```\n\n\n\n\n$$\\begin{bmatrix}\\end{bmatrix}$$\n\n\n\n\n```sql\n%%sql select * from writer\n```\n\n\n\n\n<table>\n    <tr>\n        <th>first_name</th>\n        <th>last_name</th>\n        <th>year_of_death</th>\n    </tr>\n    <tr>\n        <td>William</td>\n        <td>Shakespeare</td>\n        <td>1616</td>\n    </tr>\n    <tr>\n        <td>Bertold</td>\n        <td>Brecht</td>\n        <td>1956</td>\n    </tr>\n</table>\n\n\n", "meta": {"hexsha": "e7c9ef0c15918575ee738e1aee628bfbd16d4d21", "size": 160399, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "IPython-Demo.ipynb", "max_stars_repo_name": "dloss/notebooks", "max_stars_repo_head_hexsha": "48b34e167ed20f0b4c20cc58ee895b6f0e53e798", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2015-05-08T20:02:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-25T06:52:12.000Z", "max_issues_repo_path": "IPython-Demo.ipynb", "max_issues_repo_name": "dloss/notebooks", "max_issues_repo_head_hexsha": "48b34e167ed20f0b4c20cc58ee895b6f0e53e798", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IPython-Demo.ipynb", "max_forks_repo_name": "dloss/notebooks", "max_forks_repo_head_hexsha": "48b34e167ed20f0b4c20cc58ee895b6f0e53e798", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2015-10-23T19:47:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T12:54:07.000Z", "avg_line_length": 129.2497985496, "max_line_length": 74178, "alphanum_fraction": 0.8227981471, "converted": true, "num_tokens": 5663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20689404881588813, "lm_q2_score": 0.1347759104723777, "lm_q1q2_score": 0.02788433380047788}}
{"text": "# \u041f\u043b\u0430\u043d :\n## \u0417\u0430\u0434\u0430\u0447\u0430\nhttps://www.kaggle.com/c/mlcourse-dota2-win-prediction\n## \u041a\u043e\u0434\n## \u0411\u043e\u043d\u0443\u0441 GAFAROV10\n\n\n\n\n\n```python\nimport pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import LogisticRegressionCV\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import roc_auc_score\n```\n\n\n```python\npseudo_train = pd.read_csv('pseudo_train_df.csv')\npseudo_test = pd.read_csv('pseudo_test_df.csv')\n```\n\n\n```python\npseudo_train.shape\n```\n\n\n\n\n    (29999, 247)\n\n\n\n\n```python\npseudo_test.shape\n```\n\n\n\n\n    (654, 280)\n\n\n\n\n```python\npseudo_train.info()\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 29999 entries, 0 to 29998\n    Columns: 247 entries, match_id_hash to radiant_win\n    dtypes: float64(15), int64(231), object(1)\n    memory usage: 56.5+ MB\n\n\n\n```python\npseudo_test\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>match_id_hash</th>\n      <th>game_time</th>\n      <th>game_mode</th>\n      <th>lobby_type</th>\n      <th>objectives_len</th>\n      <th>chat_len</th>\n      <th>r1_hero_id</th>\n      <th>r1_kills</th>\n      <th>r1_deaths</th>\n      <th>r1_assists</th>\n      <th>...</th>\n      <th>d5_creeps_stacked</th>\n      <th>d5_camps_stacked</th>\n      <th>d5_rune_pickups</th>\n      <th>d5_firstblood_claimed</th>\n      <th>d5_teamfight_participation</th>\n      <th>d5_towers_killed</th>\n      <th>d5_roshans_killed</th>\n      <th>d5_obs_placed</th>\n      <th>d5_sen_placed</th>\n      <th>radiant_win</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>7b806ddf6d6d616c10ae2089ffb8b5be</td>\n      <td>887</td>\n      <td>22</td>\n      <td>7</td>\n      <td>1</td>\n      <td>9</td>\n      <td>70</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>725ec4b525a20f3088842bea2a22132c</td>\n      <td>15</td>\n      <td>22</td>\n      <td>7</td>\n      <td>0</td>\n      <td>0</td>\n      <td>102</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>e36041c6f536ed0af8b3f9396a960f91</td>\n      <td>282</td>\n      <td>22</td>\n      <td>7</td>\n      <td>1</td>\n      <td>0</td>\n      <td>98</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>dcdb0cf951ca9601e3bfaca154e95e41</td>\n      <td>2573</td>\n      <td>5</td>\n      <td>0</td>\n      <td>22</td>\n      <td>2</td>\n      <td>107</td>\n      <td>3</td>\n      <td>17</td>\n      <td>13</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>9</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>a079655f92f64076c93876a36874eff0</td>\n      <td>443</td>\n      <td>4</td>\n      <td>0</td>\n      <td>3</td>\n      <td>5</td>\n      <td>10</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>649</th>\n      <td>2eeebcc853963794b01053ebe8bcb988</td>\n      <td>1213</td>\n      <td>4</td>\n      <td>0</td>\n      <td>4</td>\n      <td>66</td>\n      <td>48</td>\n      <td>1</td>\n      <td>4</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>650</th>\n      <td>1f1004b872984704bb0d7018d06bebb3</td>\n      <td>3415</td>\n      <td>22</td>\n      <td>0</td>\n      <td>23</td>\n      <td>10</td>\n      <td>86</td>\n      <td>7</td>\n      <td>8</td>\n      <td>17</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>651</th>\n      <td>87169e0052a98e224c6876840fe3c11e</td>\n      <td>2308</td>\n      <td>22</td>\n      <td>0</td>\n      <td>9</td>\n      <td>18</td>\n      <td>8</td>\n      <td>7</td>\n      <td>2</td>\n      <td>4</td>\n      <td>...</td>\n      <td>2</td>\n      <td>1</td>\n      <td>12</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>9</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>652</th>\n      <td>39a676bd4fd4753baeeccf5d18dee1ce</td>\n      <td>2576</td>\n      <td>22</td>\n      <td>7</td>\n      <td>18</td>\n      <td>0</td>\n      <td>111</td>\n      <td>3</td>\n      <td>6</td>\n      <td>7</td>\n      <td>...</td>\n      <td>5</td>\n      <td>2</td>\n      <td>11</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>4</td>\n      <td>9</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>653</th>\n      <td>95eb72b82aee1d0d8b6f2b2dc11e9d0d</td>\n      <td>1392</td>\n      <td>22</td>\n      <td>7</td>\n      <td>5</td>\n      <td>1</td>\n      <td>50</td>\n      <td>4</td>\n      <td>5</td>\n      <td>8</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>4</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n<p>654 rows \u00d7 247 columns</p>\n</div>\n\n\n\n\n```python\npseudo_train.describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>game_time</th>\n      <th>game_mode</th>\n      <th>lobby_type</th>\n      <th>objectives_len</th>\n      <th>chat_len</th>\n      <th>r1_hero_id</th>\n      <th>r1_kills</th>\n      <th>r1_deaths</th>\n      <th>r1_assists</th>\n      <th>r1_denies</th>\n      <th>...</th>\n      <th>d5_creeps_stacked</th>\n      <th>d5_camps_stacked</th>\n      <th>d5_rune_pickups</th>\n      <th>d5_firstblood_claimed</th>\n      <th>d5_teamfight_participation</th>\n      <th>d5_towers_killed</th>\n      <th>d5_roshans_killed</th>\n      <th>d5_obs_placed</th>\n      <th>d5_sen_placed</th>\n      <th>radiant_win</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>29999.000000</td>\n      <td>29999.000000</td>\n      <td>29999.000000</td>\n      <td>29999.000000</td>\n      <td>29999.000000</td>\n      <td>29999.000000</td>\n      <td>29999.000000</td>\n      <td>29999.000000</td>\n      <td>29999.000000</td>\n      <td>29999.00000</td>\n      <td>...</td>\n      <td>29999.000000</td>\n      <td>29999.000000</td>\n      <td>29999.000000</td>\n      <td>29999.000000</td>\n      <td>29999.000000</td>\n      <td>29999.000000</td>\n      <td>29999.000000</td>\n      <td>29999.000000</td>\n      <td>29999.000000</td>\n      <td>29999.000000</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>1144.037868</td>\n      <td>19.634554</td>\n      <td>4.778826</td>\n      <td>6.515584</td>\n      <td>7.364345</td>\n      <td>50.963299</td>\n      <td>3.111670</td>\n      <td>3.249308</td>\n      <td>4.639855</td>\n      <td>6.29611</td>\n      <td>...</td>\n      <td>1.025534</td>\n      <td>0.339811</td>\n      <td>4.657489</td>\n      <td>0.091670</td>\n      <td>0.041368</td>\n      <td>0.298910</td>\n      <td>0.024834</td>\n      <td>1.281276</td>\n      <td>0.798360</td>\n      <td>0.526018</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>767.019605</td>\n      <td>6.249887</td>\n      <td>3.258060</td>\n      <td>6.493429</td>\n      <td>13.440356</td>\n      <td>34.558785</td>\n      <td>3.677295</td>\n      <td>3.267914</td>\n      <td>5.183135</td>\n      <td>8.19352</td>\n      <td>...</td>\n      <td>3.419258</td>\n      <td>0.948468</td>\n      <td>4.616371</td>\n      <td>0.288564</td>\n      <td>0.199143</td>\n      <td>0.730656</td>\n      <td>0.169170</td>\n      <td>2.621312</td>\n      <td>2.465113</td>\n      <td>0.499331</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>0.000000</td>\n      <td>2.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.00000</td>\n      <td>...</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>519.000000</td>\n      <td>22.000000</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n      <td>0.000000</td>\n      <td>20.000000</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.00000</td>\n      <td>...</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>1040.000000</td>\n      <td>22.000000</td>\n      <td>7.000000</td>\n      <td>4.000000</td>\n      <td>3.000000</td>\n      <td>44.000000</td>\n      <td>2.000000</td>\n      <td>2.000000</td>\n      <td>3.000000</td>\n      <td>3.00000</td>\n      <td>...</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>3.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>1651.000000</td>\n      <td>22.000000</td>\n      <td>7.000000</td>\n      <td>10.000000</td>\n      <td>9.000000</td>\n      <td>81.000000</td>\n      <td>5.000000</td>\n      <td>5.000000</td>\n      <td>7.000000</td>\n      <td>9.00000</td>\n      <td>...</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>7.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>4574.000000</td>\n      <td>23.000000</td>\n      <td>7.000000</td>\n      <td>43.000000</td>\n      <td>272.000000</td>\n      <td>120.000000</td>\n      <td>31.000000</td>\n      <td>25.000000</td>\n      <td>40.000000</td>\n      <td>84.00000</td>\n      <td>...</td>\n      <td>107.000000</td>\n      <td>29.000000</td>\n      <td>52.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>8.000000</td>\n      <td>4.000000</td>\n      <td>26.000000</td>\n      <td>47.000000</td>\n      <td>1.000000</td>\n    </tr>\n  </tbody>\n</table>\n<p>8 rows \u00d7 246 columns</p>\n</div>\n\n\n\n\n```python\npseudo_valid = pseudo_train.sample(999).reset_index(drop=True)\npseudo_train = pseudo_train[~pseudo_train.match_id_hash.isin(pseudo_valid.match_id_hash.unique())].reset_index(drop=True)\n```\n\n\n```python\n\n```\n\n\n```python\nX = pseudo_train.loc[:, (pseudo_train.columns != 'radiant_win') & (pseudo_train.columns != 'match_id_hash')]\ny = pseudo_train.radiant_win\nclf = LogisticRegressionCV(cv=5, random_state=42, n_jobs =-1 ,scoring = 'roc_auc').fit(X, y)\n```\n\n    /home/s.gafarov/.local/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):\n    STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n    \n    Increase the number of iterations (max_iter) or scale the data as shown in:\n        https://scikit-learn.org/stable/modules/preprocessing.html\n    Please also refer to the documentation for alternative solver options:\n        https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n      n_iter_i = _check_optimize_result(\n\n\n\n```python\nclf.score(X, y)\n```\n\n\n\n\n    0.813366406926179\n\n\n\n\n```python\nX_valid = pseudo_valid.loc[:, (pseudo_valid.columns != 'radiant_win') & (pseudo_valid.columns != 'match_id_hash')]\ny_valid_pred = clf.predict_proba(X_valid)\n\n\nX_test = pseudo_test.loc[:, (pseudo_test.columns != 'radiant_win') & (pseudo_test.columns != 'match_id_hash')]\ny_test_pred = clf.predict_proba(X_test)\n```\n\n\n```python\nprint('Validation score: ',roc_auc_score(pseudo_valid['radiant_win'], y_valid_pred[:,1]))\nprint('Test score: ',roc_auc_score(pseudo_test['radiant_win'], y_test_pred[:,1]))\n```\n\n    Validation score:  0.8064973453175577\n    Test score:  0.7990269461077844\n\n\n\n```python\n\n```\n\n\n```python\n# \u0420\u0430\u0431\u043e\u0442\u0430 \u0441 \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u043c\u0438 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u043c\u0438\n```\n\n\n```python\npseudo_train.lobby_type.unique()\n```\n\n\n\n\n    array([7, 0])\n\n\n\n\n```python\ncategorical_features_list = [ x for x in pseudo_train.columns if x.endswith('hero_id')] + ['lobby_type']\n```\n\n\n```python\npseudo_train[categorical_features_list]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>r1_hero_id</th>\n      <th>r2_hero_id</th>\n      <th>r3_hero_id</th>\n      <th>r4_hero_id</th>\n      <th>r5_hero_id</th>\n      <th>d1_hero_id</th>\n      <th>d2_hero_id</th>\n      <th>d3_hero_id</th>\n      <th>d4_hero_id</th>\n      <th>d5_hero_id</th>\n      <th>lobby_type</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>11</td>\n      <td>78</td>\n      <td>14</td>\n      <td>59</td>\n      <td>77</td>\n      <td>12</td>\n      <td>21</td>\n      <td>60</td>\n      <td>84</td>\n      <td>34</td>\n      <td>7</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>15</td>\n      <td>96</td>\n      <td>27</td>\n      <td>63</td>\n      <td>89</td>\n      <td>58</td>\n      <td>14</td>\n      <td>1</td>\n      <td>56</td>\n      <td>92</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>14</td>\n      <td>99</td>\n      <td>101</td>\n      <td>26</td>\n      <td>41</td>\n      <td>18</td>\n      <td>98</td>\n      <td>8</td>\n      <td>69</td>\n      <td>86</td>\n      <td>7</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>42</td>\n      <td>69</td>\n      <td>27</td>\n      <td>104</td>\n      <td>65</td>\n      <td>23</td>\n      <td>22</td>\n      <td>35</td>\n      <td>72</td>\n      <td>1</td>\n      <td>7</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>57</td>\n      <td>10</td>\n      <td>81</td>\n      <td>98</td>\n      <td>119</td>\n      <td>48</td>\n      <td>68</td>\n      <td>60</td>\n      <td>102</td>\n      <td>8</td>\n      <td>7</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>28995</th>\n      <td>21</td>\n      <td>119</td>\n      <td>17</td>\n      <td>84</td>\n      <td>94</td>\n      <td>72</td>\n      <td>23</td>\n      <td>27</td>\n      <td>74</td>\n      <td>29</td>\n      <td>7</td>\n    </tr>\n    <tr>\n      <th>28996</th>\n      <td>101</td>\n      <td>49</td>\n      <td>45</td>\n      <td>40</td>\n      <td>35</td>\n      <td>44</td>\n      <td>32</td>\n      <td>99</td>\n      <td>91</td>\n      <td>41</td>\n      <td>7</td>\n    </tr>\n    <tr>\n      <th>28997</th>\n      <td>106</td>\n      <td>41</td>\n      <td>35</td>\n      <td>14</td>\n      <td>17</td>\n      <td>22</td>\n      <td>26</td>\n      <td>4</td>\n      <td>43</td>\n      <td>44</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>28998</th>\n      <td>32</td>\n      <td>120</td>\n      <td>30</td>\n      <td>48</td>\n      <td>74</td>\n      <td>14</td>\n      <td>21</td>\n      <td>8</td>\n      <td>11</td>\n      <td>16</td>\n      <td>7</td>\n    </tr>\n    <tr>\n      <th>28999</th>\n      <td>5</td>\n      <td>100</td>\n      <td>10</td>\n      <td>22</td>\n      <td>71</td>\n      <td>78</td>\n      <td>14</td>\n      <td>50</td>\n      <td>41</td>\n      <td>17</td>\n      <td>7</td>\n    </tr>\n  </tbody>\n</table>\n<p>29000 rows \u00d7 11 columns</p>\n</div>\n\n\n\n\n```python\n# One hot encoding\npd.get_dummies(pseudo_train['r1_hero_id'], drop_first=True)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>2</th>\n      <th>3</th>\n      <th>4</th>\n      <th>5</th>\n      <th>6</th>\n      <th>7</th>\n      <th>8</th>\n      <th>9</th>\n      <th>10</th>\n      <th>11</th>\n      <th>...</th>\n      <th>107</th>\n      <th>108</th>\n      <th>109</th>\n      <th>110</th>\n      <th>111</th>\n      <th>112</th>\n      <th>113</th>\n      <th>114</th>\n      <th>119</th>\n      <th>120</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>28995</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>28996</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>28997</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>28998</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>28999</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n<p>29000 rows \u00d7 114 columns</p>\n</div>\n\n\n\n\n\n\n```python\n# Mean Encoding\nfor col in categorical_features_list:\n    means_map = pseudo_train.groupby(col).radiant_win.mean()\n    pseudo_train[col+'_mean_enc'] = pseudo_train[col].map(means_map)\n    # Don't forget about validation dataset\n    pseudo_valid[col+'_mean_enc'] =  pseudo_valid[col].map(means_map)\n    # and test dataset \n    pseudo_test[col+'_mean_enc'] =  pseudo_test[col].map(means_map)\n```\n\n\n```python\nme_list = [ x for x in pseudo_train.columns if x.endswith('_mean_enc')]\n```\n\n\n```python\npseudo_train[me_list]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>r1_hero_id_mean_enc</th>\n      <th>r2_hero_id_mean_enc</th>\n      <th>r3_hero_id_mean_enc</th>\n      <th>r4_hero_id_mean_enc</th>\n      <th>r5_hero_id_mean_enc</th>\n      <th>d1_hero_id_mean_enc</th>\n      <th>d2_hero_id_mean_enc</th>\n      <th>d3_hero_id_mean_enc</th>\n      <th>d4_hero_id_mean_enc</th>\n      <th>d5_hero_id_mean_enc</th>\n      <th>lobby_type_mean_enc</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.475108</td>\n      <td>0.585106</td>\n      <td>0.536323</td>\n      <td>0.519737</td>\n      <td>0.544118</td>\n      <td>0.552846</td>\n      <td>0.517564</td>\n      <td>0.508772</td>\n      <td>0.511719</td>\n      <td>0.551181</td>\n      <td>0.526813</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.382609</td>\n      <td>0.537815</td>\n      <td>0.560096</td>\n      <td>0.527919</td>\n      <td>0.527778</td>\n      <td>0.584906</td>\n      <td>0.528090</td>\n      <td>0.554717</td>\n      <td>0.505455</td>\n      <td>0.472727</td>\n      <td>0.524688</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.526758</td>\n      <td>0.516129</td>\n      <td>0.606272</td>\n      <td>0.480000</td>\n      <td>0.562887</td>\n      <td>0.542169</td>\n      <td>0.594595</td>\n      <td>0.500768</td>\n      <td>0.594340</td>\n      <td>0.559653</td>\n      <td>0.526813</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.583153</td>\n      <td>0.521127</td>\n      <td>0.560096</td>\n      <td>0.544413</td>\n      <td>0.439394</td>\n      <td>0.544271</td>\n      <td>0.402299</td>\n      <td>0.541586</td>\n      <td>0.542056</td>\n      <td>0.596296</td>\n      <td>0.526813</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.554054</td>\n      <td>0.489209</td>\n      <td>0.586854</td>\n      <td>0.424051</td>\n      <td>0.579439</td>\n      <td>0.479866</td>\n      <td>0.502041</td>\n      <td>0.508772</td>\n      <td>0.426829</td>\n      <td>0.540193</td>\n      <td>0.526813</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>28995</th>\n      <td>0.492574</td>\n      <td>0.507082</td>\n      <td>0.538168</td>\n      <td>0.522556</td>\n      <td>0.433333</td>\n      <td>0.554167</td>\n      <td>0.551724</td>\n      <td>0.498856</td>\n      <td>0.537068</td>\n      <td>0.515924</td>\n      <td>0.526813</td>\n    </tr>\n    <tr>\n      <th>28996</th>\n      <td>0.564356</td>\n      <td>0.558065</td>\n      <td>0.538462</td>\n      <td>0.530405</td>\n      <td>0.510092</td>\n      <td>0.544379</td>\n      <td>0.436856</td>\n      <td>0.463768</td>\n      <td>0.600000</td>\n      <td>0.542857</td>\n      <td>0.526813</td>\n    </tr>\n    <tr>\n      <th>28997</th>\n      <td>0.451282</td>\n      <td>0.491870</td>\n      <td>0.517647</td>\n      <td>0.535144</td>\n      <td>0.478261</td>\n      <td>0.477435</td>\n      <td>0.530612</td>\n      <td>0.521531</td>\n      <td>0.539683</td>\n      <td>0.553030</td>\n      <td>0.524688</td>\n    </tr>\n    <tr>\n      <th>28998</th>\n      <td>0.569817</td>\n      <td>0.493056</td>\n      <td>0.550000</td>\n      <td>0.545455</td>\n      <td>0.514440</td>\n      <td>0.540765</td>\n      <td>0.517564</td>\n      <td>0.500768</td>\n      <td>0.560714</td>\n      <td>0.567568</td>\n      <td>0.526813</td>\n    </tr>\n    <tr>\n      <th>28999</th>\n      <td>0.533898</td>\n      <td>0.504587</td>\n      <td>0.503788</td>\n      <td>0.588235</td>\n      <td>0.496212</td>\n      <td>0.430108</td>\n      <td>0.528090</td>\n      <td>0.588571</td>\n      <td>0.540161</td>\n      <td>0.570342</td>\n      <td>0.526813</td>\n    </tr>\n  </tbody>\n</table>\n<p>29000 rows \u00d7 11 columns</p>\n</div>\n\n\n\n\n```python\nX_mean = pseudo_train.loc[:, \n                     ~pseudo_train.columns.isin(categorical_features_list +['radiant_win','match_id_hash'])]\ny_mean = pseudo_train.radiant_win\nclf_mean = LogisticRegressionCV(cv=5, random_state=42, n_jobs =-1, scoring = 'roc_auc').fit(X_mean, y_mean)\n```\n\n    /home/s.gafarov/.local/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):\n    STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n    \n    Increase the number of iterations (max_iter) or scale the data as shown in:\n        https://scikit-learn.org/stable/modules/preprocessing.html\n    Please also refer to the documentation for alternative solver options:\n        https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n      n_iter_i = _check_optimize_result(\n\n\n\n```python\nclf_mean.score(X_mean,y_mean)\n```\n\n\n\n\n    0.813015259450802\n\n\n\n\n```python\nX_valid_mean = pseudo_valid.loc[:, \n                     ~pseudo_valid.columns.isin(categorical_features_list +['radiant_win','match_id_hash'])]\ny_valid_pred_mean = clf_mean.predict_proba(X_valid_mean)\n\n\nX_test_mean = pseudo_test.loc[:, \n                     ~pseudo_test.columns.isin(categorical_features_list +['radiant_win','match_id_hash'])]\ny_test_pred_mean = clf_mean.predict_proba(X_test_mean)\n```\n\n\n```python\nprint('Validation score: ',roc_auc_score(pseudo_valid['radiant_win'], y_valid_pred_mean[:,1]))\nprint('Test score: ',roc_auc_score(pseudo_test['radiant_win'], y_test_pred_mean[:,1]))\n```\n\n    Validation score:  0.8064732483513659\n    Test score:  0.7992889221556886\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n# Smoothed means\n```\n\n\n```python\nfor col in categorical_features_list:\n    agg = pseudo_train.groupby(col).radiant_win.agg(['count','mean'])\n    counts = agg['count']\n    means = agg['mean']\n    weight = 100\n    smooth = (counts * means + weight * means) / (counts + weight)\n    smooth_s = pseudo_train[col].map(smooth)\n    pseudo_train[col+'_s_mean_enc'] = smooth_s\n    # Don't forget about validation dataset\n    pseudo_valid[col+'_s_mean_enc'] =  pseudo_valid[col].map(smooth)\n    # and test dataset \n    pseudo_test[col+'_s_mean_enc'] =  pseudo_test[col].map(smooth)\n```\n\n\n```python\nsme_list = [ x for x in pseudo_train.columns if x.endswith('_s_mean_enc')]\n```\n\n\n```python\npseudo_train[sme_list]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>r1_hero_id_s_mean_enc</th>\n      <th>r2_hero_id_s_mean_enc</th>\n      <th>r3_hero_id_s_mean_enc</th>\n      <th>r4_hero_id_s_mean_enc</th>\n      <th>r5_hero_id_s_mean_enc</th>\n      <th>d1_hero_id_s_mean_enc</th>\n      <th>d2_hero_id_s_mean_enc</th>\n      <th>d3_hero_id_s_mean_enc</th>\n      <th>d4_hero_id_s_mean_enc</th>\n      <th>d5_hero_id_s_mean_enc</th>\n      <th>lobby_type_s_mean_enc</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.475108</td>\n      <td>0.585106</td>\n      <td>0.536323</td>\n      <td>0.519737</td>\n      <td>0.544118</td>\n      <td>0.552846</td>\n      <td>0.517564</td>\n      <td>0.508772</td>\n      <td>0.511719</td>\n      <td>0.551181</td>\n      <td>0.526813</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.382609</td>\n      <td>0.537815</td>\n      <td>0.560096</td>\n      <td>0.527919</td>\n      <td>0.527778</td>\n      <td>0.584906</td>\n      <td>0.528090</td>\n      <td>0.554717</td>\n      <td>0.505455</td>\n      <td>0.472727</td>\n      <td>0.524688</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.526758</td>\n      <td>0.516129</td>\n      <td>0.606272</td>\n      <td>0.480000</td>\n      <td>0.562887</td>\n      <td>0.542169</td>\n      <td>0.594595</td>\n      <td>0.500768</td>\n      <td>0.594340</td>\n      <td>0.559653</td>\n      <td>0.526813</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.583153</td>\n      <td>0.521127</td>\n      <td>0.560096</td>\n      <td>0.544413</td>\n      <td>0.439394</td>\n      <td>0.544271</td>\n      <td>0.402299</td>\n      <td>0.541586</td>\n      <td>0.542056</td>\n      <td>0.596296</td>\n      <td>0.526813</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.554054</td>\n      <td>0.489209</td>\n      <td>0.586854</td>\n      <td>0.424051</td>\n      <td>0.579439</td>\n      <td>0.479866</td>\n      <td>0.502041</td>\n      <td>0.508772</td>\n      <td>0.426829</td>\n      <td>0.540193</td>\n      <td>0.526813</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>28995</th>\n      <td>0.492574</td>\n      <td>0.507082</td>\n      <td>0.538168</td>\n      <td>0.522556</td>\n      <td>0.433333</td>\n      <td>0.554167</td>\n      <td>0.551724</td>\n      <td>0.498856</td>\n      <td>0.537068</td>\n      <td>0.515924</td>\n      <td>0.526813</td>\n    </tr>\n    <tr>\n      <th>28996</th>\n      <td>0.564356</td>\n      <td>0.558065</td>\n      <td>0.538462</td>\n      <td>0.530405</td>\n      <td>0.510092</td>\n      <td>0.544379</td>\n      <td>0.436856</td>\n      <td>0.463768</td>\n      <td>0.600000</td>\n      <td>0.542857</td>\n      <td>0.526813</td>\n    </tr>\n    <tr>\n      <th>28997</th>\n      <td>0.451282</td>\n      <td>0.491870</td>\n      <td>0.517647</td>\n      <td>0.535144</td>\n      <td>0.478261</td>\n      <td>0.477435</td>\n      <td>0.530612</td>\n      <td>0.521531</td>\n      <td>0.539683</td>\n      <td>0.553030</td>\n      <td>0.524688</td>\n    </tr>\n    <tr>\n      <th>28998</th>\n      <td>0.569817</td>\n      <td>0.493056</td>\n      <td>0.550000</td>\n      <td>0.545455</td>\n      <td>0.514440</td>\n      <td>0.540765</td>\n      <td>0.517564</td>\n      <td>0.500768</td>\n      <td>0.560714</td>\n      <td>0.567568</td>\n      <td>0.526813</td>\n    </tr>\n    <tr>\n      <th>28999</th>\n      <td>0.533898</td>\n      <td>0.504587</td>\n      <td>0.503788</td>\n      <td>0.588235</td>\n      <td>0.496212</td>\n      <td>0.430108</td>\n      <td>0.528090</td>\n      <td>0.588571</td>\n      <td>0.540161</td>\n      <td>0.570342</td>\n      <td>0.526813</td>\n    </tr>\n  </tbody>\n</table>\n<p>29000 rows \u00d7 11 columns</p>\n</div>\n\n\n\n\n```python\nX_sm = pseudo_train.loc[:, \n                     ~pseudo_train.columns.isin(categorical_features_list +\n                                                ['radiant_win','match_id_hash'] + me_list)]\ny_sm = pseudo_train.radiant_win\nclf_sm = LogisticRegressionCV(cv=5, random_state=42, n_jobs =-1, scoring = 'roc_auc').fit(X_sm, y_sm)\n```\n\n    /home/s.gafarov/.local/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):\n    STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n    \n    Increase the number of iterations (max_iter) or scale the data as shown in:\n        https://scikit-learn.org/stable/modules/preprocessing.html\n    Please also refer to the documentation for alternative solver options:\n        https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n      n_iter_i = _check_optimize_result(\n\n\n\n```python\nclf_sm.score(X_sm,y_sm)\n```\n\n\n\n\n    0.8133197078071\n\n\n\n\n```python\nX_valid_sm = pseudo_valid.loc[:, \n                     ~pseudo_valid.columns.isin(categorical_features_list +['radiant_win','match_id_hash']\n                                               + me_list)]\ny_valid_pred_sm = clf_sm.predict_proba(X_valid_sm)\n\n\nX_test_sm = pseudo_test.loc[:, \n                     ~pseudo_test.columns.isin(categorical_features_list +['radiant_win','match_id_hash']\n                                              + me_list)]\ny_test_pred_sm = clf_sm.predict_proba(X_test_sm)\n```\n\n\n```python\nprint('Validation score: ',roc_auc_score(pseudo_valid['radiant_win'], y_valid_pred_sm[:,1]))\nprint('Test score: ',roc_auc_score(pseudo_test['radiant_win'], y_test_pred_sm[:,1]))\n```\n\n    Validation score:  0.8067182341743174\n    Test score:  0.801375374251497\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n# WOE \n```\n\n\\begin{equation}\nWOE =(ln(\\frac{GoodDistr}{BadDistr}))* 100\n\\end{equation}\n\n\n```python\nfor col in categorical_features_list:\n    agg = pseudo_train.groupby(col).radiant_win.mean()\n    woe_df = pd.DataFrame(agg).rename(columns={'radiant_win':\"WOE_Good\"})\n    woe_df['WOE_Bad'] = 1 - woe_df['WOE_Good']\n    woe_df['WOE_Bad'] = np.where(woe_df['WOE_Bad'] == 0, 0.00001, woe_df['WOE_Bad'])\n    woe_df['woe'] = np.log(woe_df.WOE_Good/woe_df.WOE_Bad)\n\n    woe = pseudo_train[col].map(woe_df['woe'])\n    pseudo_train[col+'_woe'] = woe\n    \n    # Don't forget about validation dataset\n    pseudo_valid[col+'_woe'] =  pseudo_valid[col].map(woe_df['woe'])\n    # and test dataset \n    pseudo_test[col+'_woe'] =  pseudo_test[col].map(woe_df['woe'])\n```\n\n\n```python\nwoe_list = [ x for x in pseudo_train.columns if x.endswith('_woe')]\n```\n\n\n```python\npseudo_train[woe_list]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>r1_hero_id_woe</th>\n      <th>r2_hero_id_woe</th>\n      <th>r3_hero_id_woe</th>\n      <th>r4_hero_id_woe</th>\n      <th>r5_hero_id_woe</th>\n      <th>d1_hero_id_woe</th>\n      <th>d2_hero_id_woe</th>\n      <th>d3_hero_id_woe</th>\n      <th>d4_hero_id_woe</th>\n      <th>d5_hero_id_woe</th>\n      <th>lobby_type_woe</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>-0.099649</td>\n      <td>0.343772</td>\n      <td>0.145548</td>\n      <td>0.078988</td>\n      <td>0.176931</td>\n      <td>0.212175</td>\n      <td>0.070287</td>\n      <td>0.035091</td>\n      <td>0.046884</td>\n      <td>0.205444</td>\n      <td>0.107356</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>-0.478490</td>\n      <td>0.151550</td>\n      <td>0.241552</td>\n      <td>0.111791</td>\n      <td>0.111226</td>\n      <td>0.342945</td>\n      <td>0.112478</td>\n      <td>0.219748</td>\n      <td>0.021819</td>\n      <td>-0.109199</td>\n      <td>0.098832</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.107136</td>\n      <td>0.064539</td>\n      <td>0.431667</td>\n      <td>-0.080043</td>\n      <td>0.252886</td>\n      <td>0.169076</td>\n      <td>0.382992</td>\n      <td>0.003072</td>\n      <td>0.381935</td>\n      <td>0.239754</td>\n      <td>0.107356</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.335732</td>\n      <td>0.084557</td>\n      <td>0.241552</td>\n      <td>0.178120</td>\n      <td>-0.243622</td>\n      <td>0.177548</td>\n      <td>-0.395896</td>\n      <td>0.166729</td>\n      <td>0.168623</td>\n      <td>0.390056</td>\n      <td>0.107356</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.217065</td>\n      <td>-0.043172</td>\n      <td>0.350977</td>\n      <td>-0.306167</td>\n      <td>0.320472</td>\n      <td>-0.080580</td>\n      <td>0.008163</td>\n      <td>0.035091</td>\n      <td>-0.294800</td>\n      <td>0.161119</td>\n      <td>0.107356</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>28995</th>\n      <td>-0.029705</td>\n      <td>0.028331</td>\n      <td>0.152969</td>\n      <td>0.090287</td>\n      <td>-0.268264</td>\n      <td>0.217520</td>\n      <td>0.207639</td>\n      <td>-0.004577</td>\n      <td>0.148543</td>\n      <td>0.063716</td>\n      <td>0.107356</td>\n    </tr>\n    <tr>\n      <th>28996</th>\n      <td>0.258862</td>\n      <td>0.233311</td>\n      <td>0.154151</td>\n      <td>0.121772</td>\n      <td>0.040372</td>\n      <td>0.177983</td>\n      <td>-0.253933</td>\n      <td>-0.145182</td>\n      <td>0.405465</td>\n      <td>0.171850</td>\n      <td>0.107356</td>\n    </tr>\n    <tr>\n      <th>28997</th>\n      <td>-0.195492</td>\n      <td>-0.032523</td>\n      <td>0.070618</td>\n      <td>0.140807</td>\n      <td>-0.087011</td>\n      <td>-0.090323</td>\n      <td>0.122602</td>\n      <td>0.086178</td>\n      <td>0.159065</td>\n      <td>0.212922</td>\n      <td>0.098832</td>\n    </tr>\n    <tr>\n      <th>28998</th>\n      <td>0.281103</td>\n      <td>-0.027780</td>\n      <td>0.200671</td>\n      <td>0.182322</td>\n      <td>0.057778</td>\n      <td>0.163424</td>\n      <td>0.070287</td>\n      <td>0.003072</td>\n      <td>0.244061</td>\n      <td>0.271934</td>\n      <td>0.107356</td>\n    </tr>\n    <tr>\n      <th>28999</th>\n      <td>0.135802</td>\n      <td>0.018349</td>\n      <td>0.015152</td>\n      <td>0.356675</td>\n      <td>-0.015152</td>\n      <td>-0.281412</td>\n      <td>0.112478</td>\n      <td>0.358063</td>\n      <td>0.160989</td>\n      <td>0.283247</td>\n      <td>0.107356</td>\n    </tr>\n  </tbody>\n</table>\n<p>29000 rows \u00d7 11 columns</p>\n</div>\n\n\n\n\n```python\nX_woe = pseudo_train.loc[:, \n                     ~pseudo_train.columns.isin(categorical_features_list +\n                                                ['radiant_win','match_id_hash'] + me_list + sme_list)]\ny_woe = pseudo_train.radiant_win\nclf_woe = LogisticRegressionCV(cv=5, random_state=42, n_jobs =-1, scoring = 'roc_auc').fit(X_woe, y_woe)\n```\n\n    /home/s.gafarov/.local/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):\n    STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n    \n    Increase the number of iterations (max_iter) or scale the data as shown in:\n        https://scikit-learn.org/stable/modules/preprocessing.html\n    Please also refer to the documentation for alternative solver options:\n        https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n      n_iter_i = _check_optimize_result(\n\n\n\n```python\nclf_woe.score(X_woe,y_woe)\n```\n\n\n\n\n    0.8138006256488719\n\n\n\n\n```python\nX_valid_woe = pseudo_valid.loc[:, \n                     ~pseudo_valid.columns.isin(categorical_features_list +['radiant_win','match_id_hash']\n                                               + me_list + sme_list)]\ny_valid_pred_woe = clf_woe.predict_proba(X_valid_woe)\n\n\nX_test_woe = pseudo_test.loc[:, \n                     ~pseudo_test.columns.isin(categorical_features_list +['radiant_win','match_id_hash']\n                                              + me_list + sme_list)]\ny_test_pred_woe = clf_woe.predict_proba(X_test_woe)\n```\n\n\n```python\nprint('Validation score: ',roc_auc_score(pseudo_valid['radiant_win'], y_valid_pred_woe[:,1]))\nprint('Test score: ',roc_auc_score(pseudo_test['radiant_win'], y_test_pred_woe[:,1]))\n```\n\n    Validation score:  0.8079953733824911\n    Test score:  0.8012818113772455\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n# Expanding mean\n```\n\n\n```python\nfor col in categorical_features_list:\n    cumsum = pseudo_train.groupby(col).radiant_win.cumsum() - pseudo_train['radiant_win']\n    cumcnt = pseudo_train.groupby(col).cumcount() + 1\n    exp_mean = cumsum/cumcnt\n    pseudo_train[col+ '_exp_mean'] = exp_mean\n```\n\n\n```python\nexp_mean_list = [ x for x in pseudo_train.columns if x.endswith('_exp_mean')]\n```\n\n\n```python\npseudo_train[exp_mean_list]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>r1_hero_id_exp_mean</th>\n      <th>r2_hero_id_exp_mean</th>\n      <th>r3_hero_id_exp_mean</th>\n      <th>r4_hero_id_exp_mean</th>\n      <th>r5_hero_id_exp_mean</th>\n      <th>d1_hero_id_exp_mean</th>\n      <th>d2_hero_id_exp_mean</th>\n      <th>d3_hero_id_exp_mean</th>\n      <th>d4_hero_id_exp_mean</th>\n      <th>d5_hero_id_exp_mean</th>\n      <th>lobby_type_exp_mean</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.500000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.333333</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.250000</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>28995</th>\n      <td>0.520661</td>\n      <td>0.500000</td>\n      <td>0.540670</td>\n      <td>0.492135</td>\n      <td>0.578947</td>\n      <td>0.474063</td>\n      <td>0.518095</td>\n      <td>0.518519</td>\n      <td>0.523238</td>\n      <td>0.522523</td>\n      <td>0.527013</td>\n    </tr>\n    <tr>\n      <th>28996</th>\n      <td>0.495074</td>\n      <td>0.511429</td>\n      <td>0.540541</td>\n      <td>0.535316</td>\n      <td>0.430464</td>\n      <td>0.559322</td>\n      <td>0.562025</td>\n      <td>0.490698</td>\n      <td>0.534653</td>\n      <td>0.516129</td>\n      <td>0.527037</td>\n    </tr>\n    <tr>\n      <th>28997</th>\n      <td>0.448980</td>\n      <td>0.491903</td>\n      <td>0.512922</td>\n      <td>0.535200</td>\n      <td>0.472656</td>\n      <td>0.472019</td>\n      <td>0.532164</td>\n      <td>0.509524</td>\n      <td>0.535433</td>\n      <td>0.550864</td>\n      <td>0.523779</td>\n    </tr>\n    <tr>\n      <th>28998</th>\n      <td>0.569848</td>\n      <td>0.486395</td>\n      <td>0.555819</td>\n      <td>0.550523</td>\n      <td>0.518116</td>\n      <td>0.542714</td>\n      <td>0.516129</td>\n      <td>0.493808</td>\n      <td>0.557945</td>\n      <td>0.560000</td>\n      <td>0.527010</td>\n    </tr>\n    <tr>\n      <th>28999</th>\n      <td>0.529536</td>\n      <td>0.501558</td>\n      <td>0.500000</td>\n      <td>0.580563</td>\n      <td>0.496241</td>\n      <td>0.457447</td>\n      <td>0.524476</td>\n      <td>0.578652</td>\n      <td>0.534274</td>\n      <td>0.570342</td>\n      <td>0.527034</td>\n    </tr>\n  </tbody>\n</table>\n<p>29000 rows \u00d7 11 columns</p>\n</div>\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n\n\n\n\n```python\n# Simple stacking\nnew_validation_df = pseudo_valid[['match_id_hash','radiant_win']]\nnew_validation_df.loc[:,'le_pred'] = y_valid_pred[:, 1]\nnew_validation_df.loc[:,'me_pred'] = y_valid_pred_mean[:, 1]\nnew_validation_df.loc[:,'sme_pred'] = y_valid_pred_sm[:, 1]\nnew_validation_df.loc[:,'woe_pred'] = y_valid_pred_woe[:, 1]\n\nnew_test_df = pseudo_test[['match_id_hash','radiant_win']]\nnew_test_df.loc[:,'le_pred'] = y_test_pred[:, 1]\nnew_test_df.loc[:,'me_pred'] = y_test_pred_mean[:, 1]\nnew_test_df.loc[:,'sme_pred'] = y_test_pred_sm[:, 1]\nnew_test_df.loc[:,'woe_pred'] = y_test_pred_woe[:, 1]\n```\n\n    /home/s.gafarov/.local/lib/python3.8/site-packages/pandas/core/indexing.py:1597: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      self.obj[key] = value\n    /home/s.gafarov/.local/lib/python3.8/site-packages/pandas/core/indexing.py:1676: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      self._setitem_single_column(ilocs[0], value, pi)\n\n\n\n```python\nX_meta = new_validation_df.loc[:, \n                     ~new_validation_df.columns.isin(['radiant_win', 'match_id_hash'])]\ny_meta = new_validation_df.radiant_win\nclf_meta = LogisticRegressionCV(cv=5, random_state=42, n_jobs =-1, scoring = 'roc_auc').fit(X_meta, y_meta)\n```\n\n\n```python\nclf_meta.score(X_meta,y_meta)\n```\n\n\n\n\n    0.8082885531378265\n\n\n\n\n```python\nX_test_meta = new_test_df.loc[:, \n                     ~new_test_df.columns.isin(['radiant_win','match_id_hash'])]\ny_test_meta = clf_meta.predict_proba(X_test_meta)\n```\n\n\n```python\nprint('Test score: ',roc_auc_score(pseudo_test['radiant_win'], y_test_meta[:,1]))\n```\n\n    Test score:  0.8027039670658682\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n\n\n\n\n```python\nfrom sklearn.model_selection import StratifiedKFold\n```\n\n\n```python\ntrain = pd.read_csv('pseudo_train_df.csv')\ntest = pd.read_csv('pseudo_test_df.csv')\n```\n\n\n```python\nskf = StratifiedKFold(n_splits=5, shuffle=True, random_state=101)\ntrain_new = pd.DataFrame()\n\nX_ = train.loc[:,\n               ~train.columns.isin(['radiant_win','match_id_hash'])]\n\ny_ = train.radiant_win\n\nfor tr_ind, val_ind in skf.split(X_,y_):\n    cv_trian , cv_valid = train.loc[tr_ind], train.loc[val_ind]\n    X_test = test.copy()\n    # Mean Encoding\n    for col in categorical_features_list:\n        means_map = cv_trian.groupby(col).radiant_win.mean()\n        # Don't forget about validation dataset\n        cv_valid[col + '_mean_enc'] =  cv_valid[col].map(means_map)\n        # and test dataset \n        X_test[col+'_mean_enc'] =  X_test[col].map(means_map)\n    train_new = pd.concat([train_new,cv_valid])\n    \n    #your code here\n    \n```\n\n\n```python\ntrain.shape\n```\n\n\n\n\n    (29999, 247)\n\n\n\n\n```python\ntrain_new.shape\n```\n\n\n\n\n    (29999, 258)\n\n\n\n\n```python\ntrain_new\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>match_id_hash</th>\n      <th>game_time</th>\n      <th>game_mode</th>\n      <th>lobby_type</th>\n      <th>objectives_len</th>\n      <th>chat_len</th>\n      <th>r1_hero_id</th>\n      <th>r1_kills</th>\n      <th>r1_deaths</th>\n      <th>r1_assists</th>\n      <th>...</th>\n      <th>r2_hero_id_mean_enc</th>\n      <th>r3_hero_id_mean_enc</th>\n      <th>r4_hero_id_mean_enc</th>\n      <th>r5_hero_id_mean_enc</th>\n      <th>d1_hero_id_mean_enc</th>\n      <th>d2_hero_id_mean_enc</th>\n      <th>d3_hero_id_mean_enc</th>\n      <th>d4_hero_id_mean_enc</th>\n      <th>d5_hero_id_mean_enc</th>\n      <th>lobby_type_mean_enc</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>3</th>\n      <td>b1b35ff97723d9b7ade1c9c3cf48f770</td>\n      <td>453</td>\n      <td>22</td>\n      <td>7</td>\n      <td>1</td>\n      <td>3</td>\n      <td>42</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>...</td>\n      <td>0.497207</td>\n      <td>0.587021</td>\n      <td>0.535461</td>\n      <td>0.442308</td>\n      <td>0.528302</td>\n      <td>0.396610</td>\n      <td>0.548694</td>\n      <td>0.558140</td>\n      <td>0.621622</td>\n      <td>0.527060</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>19c39fe2af2b547e48708ca005c6ae74</td>\n      <td>160</td>\n      <td>22</td>\n      <td>7</td>\n      <td>0</td>\n      <td>0</td>\n      <td>57</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0.500000</td>\n      <td>0.588889</td>\n      <td>0.458647</td>\n      <td>0.589431</td>\n      <td>0.468504</td>\n      <td>0.523364</td>\n      <td>0.529412</td>\n      <td>0.427481</td>\n      <td>0.552326</td>\n      <td>0.527060</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>ab3cc6ccac661a1385e73a2e9f21313a</td>\n      <td>721</td>\n      <td>4</td>\n      <td>0</td>\n      <td>2</td>\n      <td>1</td>\n      <td>30</td>\n      <td>2</td>\n      <td>2</td>\n      <td>1</td>\n      <td>...</td>\n      <td>0.548837</td>\n      <td>0.488152</td>\n      <td>0.498645</td>\n      <td>0.482540</td>\n      <td>0.568182</td>\n      <td>0.465217</td>\n      <td>0.565217</td>\n      <td>0.474227</td>\n      <td>0.527157</td>\n      <td>0.523810</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>34c81a8faede0d8f1f87dcc6ee824658</td>\n      <td>1362</td>\n      <td>4</td>\n      <td>0</td>\n      <td>6</td>\n      <td>4</td>\n      <td>39</td>\n      <td>1</td>\n      <td>1</td>\n      <td>4</td>\n      <td>...</td>\n      <td>0.479730</td>\n      <td>0.566667</td>\n      <td>0.574879</td>\n      <td>0.505618</td>\n      <td>0.492308</td>\n      <td>0.542986</td>\n      <td>0.556452</td>\n      <td>0.578035</td>\n      <td>0.553191</td>\n      <td>0.523810</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>5feece770ca79e5e8cd8052198b3f533</td>\n      <td>2388</td>\n      <td>4</td>\n      <td>0</td>\n      <td>16</td>\n      <td>10</td>\n      <td>103</td>\n      <td>9</td>\n      <td>8</td>\n      <td>18</td>\n      <td>...</td>\n      <td>0.492268</td>\n      <td>0.513812</td>\n      <td>0.574074</td>\n      <td>0.554386</td>\n      <td>0.524510</td>\n      <td>0.530387</td>\n      <td>0.514286</td>\n      <td>0.471390</td>\n      <td>0.518182</td>\n      <td>0.523810</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>29973</th>\n      <td>b3816a237a4ab69585cfc464194d0a39</td>\n      <td>1683</td>\n      <td>22</td>\n      <td>0</td>\n      <td>7</td>\n      <td>0</td>\n      <td>22</td>\n      <td>9</td>\n      <td>3</td>\n      <td>7</td>\n      <td>...</td>\n      <td>0.452489</td>\n      <td>0.517094</td>\n      <td>0.547151</td>\n      <td>0.564220</td>\n      <td>0.591667</td>\n      <td>0.583333</td>\n      <td>0.644737</td>\n      <td>0.525847</td>\n      <td>0.522059</td>\n      <td>0.525671</td>\n    </tr>\n    <tr>\n      <th>29982</th>\n      <td>676f0d3a2e2724336dabc96c78324a2f</td>\n      <td>2263</td>\n      <td>22</td>\n      <td>7</td>\n      <td>21</td>\n      <td>0</td>\n      <td>119</td>\n      <td>6</td>\n      <td>9</td>\n      <td>18</td>\n      <td>...</td>\n      <td>0.517007</td>\n      <td>0.486034</td>\n      <td>0.519841</td>\n      <td>0.560748</td>\n      <td>0.474104</td>\n      <td>0.523810</td>\n      <td>0.562500</td>\n      <td>0.606618</td>\n      <td>0.508091</td>\n      <td>0.526152</td>\n    </tr>\n    <tr>\n      <th>29985</th>\n      <td>1d6fc47e76dedb38169282edfe96b20b</td>\n      <td>518</td>\n      <td>2</td>\n      <td>7</td>\n      <td>1</td>\n      <td>0</td>\n      <td>95</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0.502075</td>\n      <td>0.537037</td>\n      <td>0.555556</td>\n      <td>0.497297</td>\n      <td>0.519553</td>\n      <td>0.636364</td>\n      <td>0.436937</td>\n      <td>0.471154</td>\n      <td>0.627530</td>\n      <td>0.526152</td>\n    </tr>\n    <tr>\n      <th>29997</th>\n      <td>af3bd887e502915daaab9545f8294af3</td>\n      <td>62</td>\n      <td>22</td>\n      <td>7</td>\n      <td>0</td>\n      <td>4</td>\n      <td>32</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0.486957</td>\n      <td>0.568966</td>\n      <td>0.530612</td>\n      <td>0.509890</td>\n      <td>0.543347</td>\n      <td>0.513661</td>\n      <td>0.491396</td>\n      <td>0.557664</td>\n      <td>0.570370</td>\n      <td>0.526152</td>\n    </tr>\n    <tr>\n      <th>29998</th>\n      <td>190d0fc8a7eddcae6ca11885ac3574db</td>\n      <td>398</td>\n      <td>22</td>\n      <td>7</td>\n      <td>1</td>\n      <td>0</td>\n      <td>5</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0.513208</td>\n      <td>0.525114</td>\n      <td>0.594595</td>\n      <td>0.533040</td>\n      <td>0.460317</td>\n      <td>0.523810</td>\n      <td>0.582734</td>\n      <td>0.537129</td>\n      <td>0.561905</td>\n      <td>0.526152</td>\n    </tr>\n  </tbody>\n</table>\n<p>29999 rows \u00d7 258 columns</p>\n</div>\n\n\n\n\n\n\n\n\n```python\n\n```\n\n## Stacking \u0437\u0434\u043e\u0440\u043e\u0432\u043e \u0447\u0435\u043b\u043e\u0432\u0435\u043a\u0430\n\n\n```python\n#from https://machinelearningmastery.com/stacking-ensemble-machine-learning-with-python/\nfrom numpy import mean\nfrom numpy import std\nfrom sklearn.datasets import make_classification\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import RepeatedStratifiedKFold\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.ensemble import StackingClassifier\nfrom matplotlib import pyplot\n \n# get the dataset\ndef get_dataset():\n\tX, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=1)\n\treturn X, y\n \n# get a stacking ensemble of models\ndef get_stacking():\n\t# define the base models\n\tlevel0 = list()\n\tlevel0.append(('lr', LogisticRegression()))\n\tlevel0.append(('knn', KNeighborsClassifier()))\n\tlevel0.append(('cart', DecisionTreeClassifier()))\n\tlevel0.append(('svm', SVC()))\n\tlevel0.append(('bayes', GaussianNB()))\n\t# define meta learner model\n\tlevel1 = LogisticRegression()\n\t# define the stacking ensemble\n\tmodel = StackingClassifier(estimators=level0, final_estimator=level1, cv=5)\n\treturn model\n \n# get a list of models to evaluate\ndef get_models():\n\tmodels = dict()\n\tmodels['lr'] = LogisticRegression()\n\tmodels['knn'] = KNeighborsClassifier()\n\tmodels['cart'] = DecisionTreeClassifier()\n\tmodels['svm'] = SVC()\n\tmodels['bayes'] = GaussianNB()\n\tmodels['stacking'] = get_stacking()\n\treturn models\n \n# evaluate a give model using cross-validation\ndef evaluate_model(model, X, y):\n\tcv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)\n\tscores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1, error_score='raise')\n\treturn scores\n \n# define dataset\nX, y = get_dataset()\n# get the models to evaluate\nmodels = get_models()\n# evaluate the models and store results\nresults, names = list(), list()\nfor name, model in models.items():\n\tscores = evaluate_model(model, X, y)\n\tresults.append(scores)\n\tnames.append(name)\n\tprint('>%s %.3f (%.3f)' % (name, mean(scores), std(scores)))\n# plot model performance for comparison\npyplot.boxplot(results, labels=names, showmeans=True)\npyplot.show()\n```\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n### \u041f\u043e\u043b\u0435\u0437\u043d\u044b\u0435 \u0441\u0441\u044b\u043b\u043a\u0438\nhttps://www.coursera.org/lecture/competitive-data-science/regularization-LGYQ2\nhttps://www.coursera.org/specializations/aml\nhttps://towardsdatascience.com/all-about-categorical-variable-encoding-305f3361fd02\nhttps://machinelearningmastery.com/stacking-ensemble-machine-learning-with-python/\nhttps://www.coursera.org/lecture/competitive-data-science/stacknet-s8RLi\n\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "00f70a4952a5f803aaff3ba4d06c72588dd1d07d", "size": 414413, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "categorical-features-carpov/Carpov_courses__vebinar.ipynb", "max_stars_repo_name": "kryvokhyzha/examples-and-courses", "max_stars_repo_head_hexsha": "477e82ee24e6abba8a6b6d92555f2ed549ca682c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-13T15:41:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T15:41:48.000Z", "max_issues_repo_path": "categorical-features-carpov/Carpov_courses__vebinar.ipynb", "max_issues_repo_name": "kryvokhyzha/examples-and-courses", "max_issues_repo_head_hexsha": "477e82ee24e6abba8a6b6d92555f2ed549ca682c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2021-09-12T15:06:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:02:08.000Z", "max_forks_repo_path": "categorical-features-carpov/Carpov_courses__vebinar.ipynb", "max_forks_repo_name": "kryvokhyzha/examples-and-courses", "max_forks_repo_head_hexsha": "477e82ee24e6abba8a6b6d92555f2ed549ca682c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-29T00:37:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T00:37:52.000Z", "avg_line_length": 102.7045848823, "max_line_length": 264276, "alphanum_fraction": 0.7644668483, "converted": true, "num_tokens": 22734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.056652422918888834, "lm_q1q2_score": 0.027883650420513963}}
{"text": "```python\n# Change directory to VSCode workspace root so that relative path loads work correctly. Turn this addition off with the DataScience.changeDirOnImportExport setting\nimport os\ntry:\n\tos.chdir(os.path.join(os.getcwd(), '..'))\n\tprint(os.getcwd())\nexcept:\n\tpass\n\n```\n\n\n```python\nimport os\ntry:\n    os.chdir(os.path.join(os.getcwd(), 'course_berkeley/homework/hw2'))\n    print(os.getcwd())\nexcept:\n    pass\n```\n\n # Problem 1\n We want to show that\n \\begin{equation}\n \\sum_{t'=1}^{T}\\mathbb{E}_{\\tau \\sim p_{\\theta}(\\tau)}[\\nabla_{\\theta}log \\pi_{\\theta}(a_{t'}|s_{t'})(b(s_{t'}))]=0\n \\end{equation}\n \\begin{align}\n \\sum_{t=1}^{T}\\mathbb{E}_{\\tau \\sim p_{\\theta}(\\tau)}[\\nabla_{\\theta}log \\pi_{\\theta}(a_t|s_t)(b(s_t))]\n &=\\sum_{t=1}^{T}\\int p_{\\theta}(\\tau)\\nabla_{\\theta}log \\pi_{\\theta}(a_t|s_t)(b(s_t))d\\tau\\\\\n %&=\\sum_{t=1}^{T}\\int p_{\\theta}(s_t,a_t)p_{\\theta}(\\tau / s_t,a_t\\mid s_t,a_t)\\nabla_{\\theta}log \\pi_{\\theta}(a_t|s_t)(b(s_t))d\\tau\\\\\n &=\\sum_{t=1}^{T}\\int \\int p_{\\theta}(s_t,a_t)(\\int p_{\\theta}(\\tau / s_t,a_t\\mid s_t,a_t)\\nabla_{\\theta}log \\pi_{\\theta}(a_t|s_t)(b(s_t))d\\tau )d s_t da_t)\\\\\n &=\\sum_{t=1}^{T}\\int \\int p_{\\theta}(s_t,a_t)\\nabla_{\\theta}log \\pi_{\\theta}(a_t|s_t)b(s_t)\\int p_{\\theta}(\\tau / s_t,a_t\\mid s_t,a_t)d\\tau d s_t d a_t\\\\\n &=\\sum_{t=1}^{T}\\int \\int p_{\\theta}(s_t,a_t)\\nabla_{\\theta}log \\pi_{\\theta}(a_t|s_t)b(s_t) d s_t d a_t\\\\\n &=\\sum_{t=1}^{T}\\int \\int p(s_{t+1}|a_t,s_t)\\pi_{\\theta}(a_t|s_t)\\nabla_{\\theta}log \\pi_{\\theta}(a_t|s_t)b(s_t) d s_t d a_t\\\\\n &=\\sum_{t=1}^{T}\\int \\int p(s_{t+1}|a_t,s_t)b(s_t)\\nabla_{\\theta}\\pi_{\\theta}(a_t|s_t) d s_t d a_t\\\\\n &=\\sum_{t=1}^{T} \\nabla_{\\theta} \\int \\int p(s_{t+1}|a_t,s_t)b(s_t)\\pi_{\\theta}(a_t|s_t) d s_t d a_t \\\\\n &=\\sum_{t=1}^{T} \\nabla_{\\theta} \\int \\int p_{\\theta}(a_t,s_t)b(s_t) d s_t d a_t \\\\\n \\end{align}\nWhere $\\nabla_{\\theta}log \\pi_{\\theta}(A_t|S_t)b(S_t)=b(S_t)\\nabla_{\\theta}log \\pi_{\\theta}(A_t|S_t)$, since $b$ is assumed not to depend on $\\theta$ (in practice it could be estimated using a different neural network with parameters $\\phi$).\n\n\n```python\n  &=\\mathbb{E}_{(A_t,S_t)}[\\mathbb{E}_{\\tau / (A_t,S_t) \\sim p_{\\theta}(\\tau / S_t,A_t\\mid S_t,A_t)}[0\\mid A_t , S_t]]\\\\\n  &= \\mathbf{0}\n Where $\\nabla_{\\theta}log \\pi_{\\theta}(A_t|S_t)(b(S_t)) = 0$ given $A_t$ and $S_t$. Therefore \n```\n\n\n```python\nfrom train_pg_f18 import train_PG\nseed = 1\ntrain_PG(\n                exp_name=\"sb_no_rtg_dna\",\n                env_name=\"CartPole-v0\",\n                n_iter=100,\n                gamma=0.99,\n                min_timesteps_per_batch=1000,\n\t\t\t\tlearning_rate=0.001,\n\t\t\t\treward_to_go=None,\n                max_path_length=99999999999,\n                animate=False,\n                logdir= None , #os.path.join(\"data\",'%d'%seed),\n\t\t\t\tnormalize_advantages=False,\n                nn_baseline=None, \n                seed=seed,\n                n_layers=2,\n                size=100\n                )\n```\n\n\n```python\n%load_ext autoreload\n\n%autoreload 2\n```\n\n## Test continous  actions\nWe use the logprob expression\n```\nsy_logprob_n =  -1/2 * tf.reduce_sum(inverse_variance *(diff*diff),axis=1)\n```\nEven though\n```\nsy_logprob_n = - 1/2*(tf.log(variance)  + tf.reduce_sum(inverse_variance *(diff*diff),axis=1))\n```\nwould have been more correct as to follow the logprob. For this small example this makes the variance be maximized after, and thus gives more incorrect results, however for the real examples it performes the same, probably due to maximization errors when doing the other thing. It is also what is suggested in Levines slides.\n\n\n```python\nfrom train_pg_f18 import train_PG, Agent\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport numpy as np\ncomputation_graph_args = {\n    'n_layers': 1,\n    'ob_dim': 3,\n    'ac_dim': 1,\n    'discrete': False,\n    'size': 2,\n    'learning_rate': 0.005,\n}\n\nsample_trajectory_args = {\n    'animate': False,\n    'max_path_length': 1000,\n    'min_timesteps_per_batch': 1000,\n}\n\nestimate_return_args = {\n    'gamma': 0.99,\n    'reward_to_go': True,\n    'nn_baseline': False,\n    'normalize_advantages': False,\n}\n\nwith tf.Graph().as_default() as graph:\n    agent = Agent(computation_graph_args, sample_trajectory_args, estimate_return_args)\n    agent.build_computation_graph()\n    tf_config = tf.ConfigProto(inter_op_parallelism_threads=1,\n        intra_op_parallelism_threads=1,\n        gpu_options = tf.GPUOptions(\n            #per_process_gpu_memory_fraction=1./16. # 1gb\n            allow_growth=True\n        )\n    )\n    with tf.Session(config=tf_config).as_default() as sess:\n        \n\n        sess.__enter__() # equivalent to `with self.sess:`\n        tf.global_variables_initializer().run() #pylint: disable=E1101\n\n\n        # check that the loss is computed correct\n        print(sess.run([agent.policy_parameters, agent.sy_logprob_n, agent.loss], {\n            agent.sy_ob_no: [[0.5,0.5,0.5],\n                            [0.5,0.5,0.5],\n                            [0.5,0.5,0.5]],\n            agent.sy_ac_na: [[2.0], [2.0], [2.0]],\n            agent.sy_adv_n: [1,1,1]\n        \n        })\n        )\n        # check that the actions look correct\n        n_samples = 100\n        sampled_actions = sess.run(agent.sy_sampled_ac, {\n            agent.sy_ob_no: [[0.5,0.5,0.5]]*n_samples,\n            #agent.sy_ac_na: [[2.0]]*n_samples,\n            #agent.sy_adv_n: [1]*n_samples\n        \n        })\n        figure =  plt.figure()\n        plot = plt.hist(sampled_actions)\n        figure.show()\n        print(\"std: {}, mean: {}\".format(np.std(sampled_actions),np.mean(sampled_actions)))\n        n_training = 4000\n        for i in range(n_training):\n            sy_ac_na = np.random.normal(loc=5.0 , scale=0.1,size=n_samples)\n            sess.run(agent.update_op, {\n                agent.sy_ob_no: [[0.5,0.5,0.5]]*n_samples,\n                agent.sy_ac_na: sy_ac_na.reshape(-1,1),\n                agent.sy_adv_n: [1]*n_samples\n\n            })\n            sampled_actions = sess.run(agent.sy_sampled_ac, {\n                agent.sy_ob_no: [[0.5,0.5,0.5]]*n_samples,\n                #agent.sy_ac_na: [[2.0]]*n_samples,\n                #agent.sy_adv_n: [1]*n_samples\n            })\n            if i %100 == 99:\n                print(\"it: {}, std: {}, mean: {}\".format(i, np.std(sampled_actions),np.mean(sampled_actions)))\n        \n        figure =  plt.figure()\n        plot = plt.hist(sampled_actions)\n        figure.show()\n```\n\n    [(array([[0.],\n           [0.],\n           [0.]], dtype=float32), array([0.], dtype=float32)), array([-2., -2., -2.], dtype=float32), 2.0]\n    std: 0.9857619404792786, mean: 0.053708259016275406\n\n\n    /zhome/30/0/70339/.local/lib/python3.6/site-packages/matplotlib/figure.py:445: UserWarning: Matplotlib is currently using module://ipykernel.pylab.backend_inline, which is a non-GUI backend, so cannot show the figure.\n      % get_backend())\n\n\n    it: 99, std: 4.66080379486084, mean: 5.440565586090088\n    it: 199, std: 6.097592830657959, mean: 4.187251091003418\n    it: 299, std: 44.20418167114258, mean: 9.711440086364746\n    it: 399, std: 111.15580749511719, mean: -4.385540962219238\n    it: 499, std: 151.47842407226562, mean: 27.827970504760742\n    it: 599, std: 186.75601196289062, mean: -14.619833946228027\n    it: 699, std: 214.3723907470703, mean: 23.425809860229492\n    it: 799, std: 224.56509399414062, mean: -21.883249282836914\n    it: 899, std: 266.2421875, mean: -15.566503524780273\n    it: 999, std: 271.6304626464844, mean: 19.704458236694336\n    it: 1099, std: 304.3190002441406, mean: 26.475332260131836\n    it: 1199, std: 300.62518310546875, mean: 10.948735237121582\n    it: 1299, std: 336.2844543457031, mean: 23.704082489013672\n    it: 1399, std: 375.9537353515625, mean: 68.61624145507812\n    it: 1499, std: 345.3172302246094, mean: 39.9020881652832\n    it: 1599, std: 362.7534484863281, mean: 26.962749481201172\n    it: 1699, std: 387.88238525390625, mean: -39.475982666015625\n    it: 1799, std: 368.72686767578125, mean: 40.964393615722656\n    it: 1899, std: 415.8846130371094, mean: -0.6535653471946716\n    it: 1999, std: 399.17840576171875, mean: -9.46063232421875\n    it: 2099, std: 402.3943176269531, mean: 56.75299835205078\n    it: 2199, std: 426.382568359375, mean: -9.584866523742676\n    it: 2299, std: 397.1225280761719, mean: 32.09247589111328\n    it: 2399, std: 440.0720520019531, mean: 11.018421173095703\n    it: 2499, std: 448.4039306640625, mean: -24.780982971191406\n    it: 2599, std: 431.1240539550781, mean: -5.091939926147461\n    it: 2699, std: 454.5281066894531, mean: 127.94454193115234\n    it: 2799, std: 522.6281127929688, mean: -42.318817138671875\n    it: 2899, std: 539.570068359375, mean: 48.2517204284668\n    it: 2999, std: 541.5744018554688, mean: -17.586069107055664\n    it: 3099, std: 556.2981567382812, mean: 21.580507278442383\n    it: 3199, std: 577.2489013671875, mean: 22.744112014770508\n    it: 3299, std: 580.4326171875, mean: -20.103782653808594\n    it: 3399, std: 575.3218994140625, mean: 100.09042358398438\n    it: 3499, std: 584.818603515625, mean: 65.43984985351562\n    it: 3599, std: 532.0647583007812, mean: 60.5954704284668\n    it: 3699, std: 582.7791748046875, mean: -98.67958068847656\n    it: 3799, std: 574.6396484375, mean: -18.537797927856445\n    it: 3899, std: 621.84228515625, mean: 28.96257781982422\n    it: 3999, std: 598.8465576171875, mean: -39.415287017822266\n\n\n## Test baseline\n\n\n```python\nfrom train_pg_f18 import train_PG, Agent\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport numpy as np\ncomputation_graph_args = {\n    'n_layers': 1,\n    'ob_dim': 3,\n    'ac_dim': 1,\n    'discrete': False,\n    'size': 2,\n    'learning_rate': 0.005,\n}\n\nsample_trajectory_args = {\n    'animate': False,\n    'max_path_length': 1000,\n    'min_timesteps_per_batch': 1000,\n}\n\nestimate_return_args = {\n    'gamma': 0.99,\n    'reward_to_go': True,\n    'nn_baseline': True,\n    'normalize_advantages': False,\n}\n\nwith tf.Graph().as_default() as graph:\n    agent = Agent(computation_graph_args, sample_trajectory_args, estimate_return_args)\n    agent.build_computation_graph()\n    tf_config = tf.ConfigProto(inter_op_parallelism_threads=1,\n        intra_op_parallelism_threads=1,\n        gpu_options = tf.GPUOptions(\n            #per_process_gpu_memory_fraction=1./16. # 1gb\n            allow_growth=True\n        )\n    )\n    with tf.Session(config=tf_config).as_default() as sess:\n        \n\n        sess.__enter__() # equivalent to `with sess:`\n        tf.global_variables_initializer().run() #pylint: disable=E1101\n\n        # check that the actions look correct\n        n_samples = 1\n        ob_no =  [[0.0,0.0,0.0],[-1.,-1.,-1.]]*n_samples\n        q_n = [1,-1]*n_samples\n        value = sess.run(agent.baseline_prediction, {\n                agent.sy_ob_no: ob_no\n            })\n        print(\"Value of state before {}\".format(value))\n        target_n = (q_n - np.mean(q_n))/np.std(q_n)\n        print(\"Target values {}\".format(target_n))\n        n_training = 1000\n        print(\"Number of training baseline: {}\".format(n_training))\n        for _ in range(n_training):\n            sess.run(agent.baseline_update_op, {\n                agent.sy_ob_no: ob_no,\n                agent.sy_target_n: target_n\n            })\n            value = sess.run(agent.baseline_prediction, {\n                    agent.sy_ob_no: ob_no\n                })\n        print(\"Value of state after {}\".format(value))\n```\n\n    Value of state before [0. 0.]\n    Target values [ 1. -1.]\n    Number of training baseline: 1000\n    Value of state after [ 0.9999992 -0.9999991]\n\n\n\n```python\nfrom train_pg_f18 import train_PG, Agent\nimport tensorflow as tf\nwith tf.Graph().as_default() as graph:\n\n    with tf.Session(config=tf_config).as_default() as sess:\n        \n\n        sess.__enter__() # equivalent to `with self.sess:`\n        tf.global_variables_initializer().run() #pylint: disable=E1101\n        batch  = tf.constant([[1.,2.,3.,4.],[5.,6.,7.,8.]])\n        \n        #indices =  tf.expand_dims(tf.constant([1,2]),axis=1)\n        indices =  tf.expand_dims(tf.constant([1,2]),axis=1)\n        print(tf.squeeze(tf.batch_gather(batch,indices)).eval())\n\n```\n\n    [2. 7.]\n\n", "meta": {"hexsha": "b0f2a5dc17c6e6fd1c161720b6296b4bc3a05cd0", "size": 16717, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "hw2/Hw2.ipynb", "max_stars_repo_name": "muthissar/homework", "max_stars_repo_head_hexsha": "9ee6361183da84f58e8b4842cc2c6047f7d743e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw2/Hw2.ipynb", "max_issues_repo_name": "muthissar/homework", "max_issues_repo_head_hexsha": "9ee6361183da84f58e8b4842cc2c6047f7d743e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-03-13T07:29:25.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-13T07:29:58.000Z", "max_forks_repo_path": "hw2/Hw2.ipynb", "max_forks_repo_name": "muthissar/homework", "max_forks_repo_head_hexsha": "9ee6361183da84f58e8b4842cc2c6047f7d743e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.149882904, "max_line_length": 331, "alphanum_fraction": 0.5297003051, "converted": true, "num_tokens": 4081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.06656918434088001, "lm_q1q2_score": 0.027872311741855435}}
{"text": "# <p style=\"text-align: center;\"> Practical Quantum Computing with Cirq </p> \n<p style=\"text-align: center;\"> Ryan LaRose </p>\n<p style=\"text-align: center;\"> Department of Computational Mathematics, Science, and Engineering, Michigan State University </p>\n<p style=\"text-align: center;\"> Department of Physics and Astronomy, Michigan State University </p>\n\n### <p style=\"text-align: center;\"> Abstract </p> \n<p style=\"text-align: justify;\"> In July 2018, the <a href=\"https://quantumcomputingreport.com\">Quantum Computing Report</a> featured an <a href=\"https://quantumcomputingreport.com/wp-content/uploads/2018/06/Overview-and-Comparison-of-Gate-Level-Quantum-Software-Platforms-Final-June-21-2018.pdf\">in-depth analysis of four major gate-model quantum software platforms</a>: Forest by Rigetti, QISKit by IBM, ProjectQ by ETH Zurich, and the Quantum Developer Kit by Microsoft. Shortly after, Google announced the release of their own quantum software platform: Cirq. In this paper, we provide an overview and comparative analysis of this newly-released platform with respect to the previously-reviewed quantum software platforms. Our analysis proceeds similarly by covering requirements and installation, language syntax through example programs, quantum simulators, and quantum computer capabilities. We additionally cover more advanced features of the platform including quantum circuit manipulation/optimization, device-oriented circuits and quantum compiling, and strong support for variational quantum algorithms and near-term quantum computing. </p> \n\n# <p style=\"text-align: center;\">I. Introduction </p> \n\n<p style=\"text-align: justify;\"> \nQuantum computing is transitioning from a theoretical to practical phase. Historically, researchers have asked questions about the possibilities of speedups through black-box access to abstract, idealized quantum computers. Recently, small, imperfect quantum computers have been fabricated and made available over the cloud. A significant body of literature is emerging as researchers use these devices to solve problems in nuclear physics <a href=\"#Du2018\">[Du2018]</a>, quantum chemistry <a href=\"#Pe2014\">[Pe2014]</a>, condensed matter <a href=\"#La2018\">[La2018]</a>, optimization <a href=\"#Fa2014\">[Fa2014]</a>, number theory <a href=\"#An2018\">[An2018]</a>, graph theory <a href=\"#Wa2018\">[Wa2018]</a>, and even quantum computing itself <a href=\"#Kh2018\">[Kh2018]</a>. While these problems are small and easily handled by conventional computers, the prospect of large-scale quantum computers could quickly change this. Even on current quantum computers, certain contrived problems may soon demonstrate \"quantum supremacy\" <a href=\"#Ne2017\">[Ne2017, Ma2018]</a>, an exciting landmark in the history of computation. \n</p>\n\n<p style=\"text-align: justify;\"> \nThis theoretical-to-practical progression of the field necessitates access to quantum computers that is much different from black box access on pen and paper. Many institutions in industry and academia have recognized this and began building tools for this purpose, and a slew of startup companies has emerged to fill the gaps in the transition to practical quantum computing. The following diagram shows a partial snapshot of this rapidly evolving landscape:\n</p>\n\n\n<p style=\"text-align: center;\">Schematic diagram showing quantum computing companies and their position in the quantum software stack. \"Full-stack providers\" focus on all areas of the stack whereas \"target providers\" focus on particular areas. Because companies that do algorithms/applications frequently do software as well, we have combined these two categories on the right. (Similarly for hardware & compilation and control.)</p>\n\n\n<p style=\"text-align: justify;\"> \nFor most \"full-stack\" quantum computing companies, access to quantum computers is granted over the cloud, and the interaction between research scientists and quantum computers is mediated by a software platform with API access. To an outside observer, this interaction does not warrant much thought: it just needs to give users the ability to implement quantum gates on qubits. However, many practical considerations emerge when using a software interface to communicate with a real or simulated quantum computer. Among these are the following:\n</p>\n\n1. What gate operations are natively built-in?\n1. Can a gate that's not native be implemented into a quantum algorithm? How difficult is it to do this?\n1. How many quantum computers does the platform give access to?\n1. Is compilation handled automatically by the software? And to what degree of optimality?\n1. How do job requests to quantum computers get handled? In a queue, dedicated time?\n1. What quantum computer simulators can be used to test algorithms? How many qubits can be simulated? Is the simulator noisy or noiseless?\n1. Does every quantum algorithm have to be programmed manually? Or are some common subroutines built-in?\n1. What <i>classical</i> programming language is the software written in?\n1. How easy is it to create, work with, and manipulate quantum circuits?\n1. How easy is it to parametrize algorithms for near-term quantum computing?\n\n<p style=\"text-align: justify;\"> \nEach of these considerations is important from a practical perspective. For example, an algorithm on many qubits may be better implemented on a platform with a higher-performance simulator; an algorithm with many gates may be better for a platform with higher fidelity qubits; an algorithm with many non-standard gates may be better for a platform with an optimal compiler. Other considerations such as examples, tutorials, and documentation are equally important as they help bring in new users and answer questions of experienced users.\n</p>\n\n<p style=\"text-align: justify;\"> \nFor these reasons, it is both valid and important to evaluate quantum software platforms as more than the simple interface they may appear to be. To this end, the Quantum Computing Report published an article <a href=\"#LaR2018\">[LaR2018]</a> comparing Forest by Rigetti, QISKit by IBM, ProjectQ by ETH Zurich, and the Quantum Developer Kit by Microsoft. (Subsequently, other articles on quantum software have also been written, e.g. <a href=\"#Fi2018\">[Fi2018]</a>.) Each platform was found to have different strengths and different emphases that determined the set of problems best-suited for the environment. The purpose of this article is to introduce and analyze Cirq in a similar fashion.\n</p>\n\n<p style=\"text-align: justify;\"> \nTo this end, the rest of the article is organized as follows. After briefly commenting on the format of this article, we cover installation, documentation, language syntax, and quantum computer/simulator support in Cirq. We then transition into more advanced features like circuit manipulation and optimization and circuits for a partcular quantum computer. Lastly, we conclude with example programs including a variational quantum algorithm to demonstrate the near-term capabilities of Cirq. Throughout, we refer back to previously covered software platforms to maintain the comparative analysis in our previous installation.\n</p>\n\n## <p style=\"text-align: center;\"> A. Format of the Article </p> \n\n<p style=\"text-align: justify;\"> \nThis article was written as a Jupyter Notebook and exported as an HTML file. The HTML file is hosted on the <a href=\"https://quantumcomputingreport.com\">Quantum Computing Report website</a> and the Jupyter notebook is hosted on <a href=\"https://github.com/rmlarose/cirq-overview\">GitHub</a>. In the HTML version, all code and all outputs are visible in the article, but the code is not able to run. To interactively run the code while reading through the article, see the Jupyter Notebook version. In order to run the code, a working installation of Cirq is required (see <i>Installation</i> below). The Cirq code in the notebook version will be kept up-to-date with future versions/releases of Cirq. The article assumes basic familiarity with quantum computing, for which many good <a href=\"https://quantumcomputingreport.com/resources/education/\">resources</a> now exist.\n</p>\n\n# <p style=\"text-align: center;\"> II. The Basics of Cirq </p> \n\n<table style=\"width:100%\">\n    <th>Institution</th>\n    <!--<th>First Release</th>-->\n    <th>Version</th>\n    <!--<th>Open Source?</th>-->\n    <!--<th>License</th>-->\n    <!--<th>Homepage</th>-->\n    <th>GitHub</th>\n    <th>Documentation</th>\n    <th>OS</th>\n    <th>Requirements</th>\n    <th>Classical Language</th>\n    <th>Quantum Language</th>\n    <th>Quantum Hardware</th>\n    <th>Simulator</th>\n    <!--<th>Features</th>-->\n  </tr>\n  <tr>\n    <td><a href=\"https://ai.google/research/teams/applied-science/quantum-ai/\">Google Quantum AI</a></td>\n    <td>v0.4.0</td> \n    <td><a href=\"https://github.com/quantumlib/Cirq\">Git</a></td>\n    <td><a href=\"https://cirq.readthedocs.io/en/latest/\">Docs</a></td>\n      <td>Mac, Windows, Linux</td>\n      <td><a href=\"https://www.python.org/downloads/\">Python</a> 3.5 or greater (else Python 2.7)</td> \n      <td>Python</td>\n      <td>----</td>\n      <td>Foxtail (22 qubits), Bristlecone (72 qubits)</td>\n      <td>~20-30 qubits</td>\n  </tr>\n</table>\n\n<p style=\"text-align: justify;\"> \nCirq is an open-source Python framework for \"creating, editing, and invoking Noisy Intermediate-Scale Quantum (NISQ) circuits\" <a name=\"#Ho2018\">[Ho2018]</a>. The first version of the software was publicly announced in July 2018; the code is still in alpha testing and under development. As such, some features or code included in this article may need modifications for future versions of Cirq. This article should be considered a review for the version of Cirq at the time of writing, which is listed in the table above. (As mentioned above, the Jupyter Notebook version of this article, hosted online at [GitHub](https://github.com/rmlarose), will be kept up to date as future versions of Cirq are released.)\n</p>\n\n\n<p style=\"text-align: center;\">The components of Cirq. When installed onto a computer, Cirq provides a library for working with quantum circuits and a high-performance local quantum circuit simulator. As of December 2018, connection to hardware devices or the \"Quantum Engine\"/\"Quantum Cloud Services\" is unavailable to general users, but this is expected to change in the future.</p>\n\n## <p style=\"text-align: center;\"> A. Installation </p> \n\nThe easiest way to install `Cirq` is by using pip via\n\n```\npip install cirq\n```\n<p style=\"text-align: justify;\"> \nat a command line. Without leaving the notebook, executing the cell below will try to install Cirq v0.4.0 on the user's computer. Alternatively, the source code for Cirq can be obtained from <a href=\"https://github.com/quantumlib/Cirq\">https://github.com/quantumlib/Cirq</a>. For complete installation instructions on multiple platforms, see the documentation at <a href=\"https://cirq.readthedocs.io/en/latest/install.html\">https://cirq.readthedocs.io/en/latest/install.html</a>. Readers who simply wish to read the article without using Cirq can ignore this step.\n</p>\n\n\n```python\n\"\"\"Attempts to pip install Cirq 0.4.0.\"\"\"\n#!pip install --upgrade pip\n#!pip install cirq==0.4.0\n```\n\n## <p style=\"text-align: center;\"> B. Documentation and Tutorials </p> \n\n<p style=\"text-align: justify;\"> \nThe <a href=\"https://cirq.readthedocs.io/en/latest/install.html\">documentation for Cirq</a> contains instructions on installation for all three major operating systems, an in-depth tutorial for the variational quantum eigensolver, and details on three major components of the Cirq library: circuits, gates, and simulation. In addition, the section on <i>Schedules and Devices</i> details how Cirq can be used with specific quantum hardware and reflects the emphasis on near-term quantum computing. The documentation also contains a detailed API reference for the entire library and development guidelines for those who may want to contribute to the source code.\n</p>\n\n## <p style=\"text-align: center;\"> C. Language Syntax </p> \n\n<p style=\"text-align: justify;\"> \nAs in our previous coverage of quantum software platforms, we include example programs to demonstrate the language syntax. Below, we implement the \"quantum random bit generator\" algorithm, which produces either zero or one output that is random by the laws of quantum mechanics. To use the functionality of Cirq, we first import the library (and additional libraries we'll use throughout the article).\n</p>\n\n\n```python\n\"\"\"Library imports for the article.\"\"\"\nimport cirq\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\n<p style=\"text-align: justify;\"> \nIn what follows we create a circuit and instantiate it with the operations for the algorithm (Hadamard and measure).\n</p>\n\n\n```python\n\"\"\"Create a random number generator circuit using Cirq.\"\"\"\n# get a qubit register\nqbits = [cirq.LineQubit(0)]\n\n# get a quantum circuit\ncirc = cirq.Circuit()\n\n# add the instructions to the circuit\ncirc.append([cirq.H(qbits[0]),\n             cirq.measure(qbits[0], key=\"z\")])\n```\n\n<p style=\"text-align: justify;\"> \nNote that Cirq defines qubits to be `LineQubit`s or `GridQubit`s, since these are common constructions in NISQ computers. The former is indexed by one integer, as we have done in Line 4 above, and the latter by two (x, y coordinates). Qubits are commonly defined in lists (or generally iterables) for easy indexing in algorithms. In line 6 above we instantiate a circuit, and in lines 9-10 we append the instructions for the algorithm. (There are multiple ways to add instructions to an algorithm in Cirq. For most of this article, we'll stick to the above method for simplicity. See Section III.A for alternatives.)\n</p>\n\n<p style=\"text-align: justify;\"> \nThe Cirq library provides text diagram representation of quantum circuits, which can be visualized by printing out the circuit:\n</p>\n\n\n```python\n\"\"\"Print out the random number generator circuit.\"\"\"\nprint(circ)\n```\n\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500M('z')\u2500\u2500\u2500\n\n\n<p style=\"text-align: justify;\"> \nWhile these diagrams are not of publication quality like those that can be made in ProjectQ or even QISKit, they are a useful tool for verifying correctness of quantum circuits and debugging. Note that measurements are made with a `key` to easily access the results of running the circuit, as we will see below.\n</p>\n\n## <p style=\"text-align: center;\"> D. Quantum Computers </p> \n\n<p style=\"text-align: justify;\"> \nCirq does not currently provide cloud access to Google's quantum computers for general users. Indeed, as per the documentation in <a href=\"https://github.com/quantumlib/Cirq/blob/master/cirq/google/engine/engine.py\">Cirq's engine class</a>:\n<p style=\"text-align: justify;\"> \n\n<blockquote cite=\"\">\n\"In order to run on[e] must have access to the Quantum Engine API. Access to this\nAPI is (as of June 22, 2018) restricted to invitation only.\"\n</blockquote>\n\n\n<p style=\"text-align: justify;\"> \nNonetheless, it is known that Google has quantum computers that have been stated to be made available over the cloud in the near future <a name=\"#Ho2018\">[Ho2018]</a>, using Cirq as an interface. Indeed, Cirq already provides details on these devices. For instance, the architecture of the 22-qubit FoxTail computer can be printed out in Cirq by doing:\n</p>\n\n\n```python\n\"\"\"Print out the architecture of the FoxTail quantum computer.\"\"\"\ns = \"FoxTail has {} qubits arranged as follows:\\n\"\nprint(s.format(len(cirq.google.Foxtail.qubits)))\nprint(cirq.google.Foxtail)\n```\n\n    FoxTail has 22 qubits arranged as follows:\n    \n    (0, 0)\u2500\u2500\u2500(0, 1)\u2500\u2500\u2500(0, 2)\u2500\u2500\u2500(0, 3)\u2500\u2500\u2500(0, 4)\u2500\u2500\u2500(0, 5)\u2500\u2500\u2500(0, 6)\u2500\u2500\u2500(0, 7)\u2500\u2500\u2500(0, 8)\u2500\u2500\u2500(0, 9)\u2500\u2500\u2500(0, 10)\n    \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502\n    \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502\n    (1, 0)\u2500\u2500\u2500(1, 1)\u2500\u2500\u2500(1, 2)\u2500\u2500\u2500(1, 3)\u2500\u2500\u2500(1, 4)\u2500\u2500\u2500(1, 5)\u2500\u2500\u2500(1, 6)\u2500\u2500\u2500(1, 7)\u2500\u2500\u2500(1, 8)\u2500\u2500\u2500(1, 9)\u2500\u2500\u2500(1, 10)\n\n\nThe 72-qubit Bristlecone computer, with which quantum supremacy may be demonstrated on, can be displayed similarly:\n\n\n```python\n\"\"\"Print out the architecture of the Bristlecone quantum computer.\"\"\"\ns = \"Bristlecone has {} qubits arranged as follows:\\n\"\nprint(s.format(len(cirq.google.Bristlecone.qubits)))\nprint(cirq.google.Bristlecone)\n```\n\n    Bristlecone has 72 qubits arranged as follows:\n    \n                                                 (0, 5)\u2500\u2500\u2500\u2500(0, 6)\n                                                 \u2502         \u2502\n                                                 \u2502         \u2502\n                                        (1, 4)\u2500\u2500\u2500(1, 5)\u2500\u2500\u2500\u2500(1, 6)\u2500\u2500\u2500\u2500(1, 7)\n                                        \u2502        \u2502         \u2502         \u2502\n                                        \u2502        \u2502         \u2502         \u2502\n                               (2, 3)\u2500\u2500\u2500(2, 4)\u2500\u2500\u2500(2, 5)\u2500\u2500\u2500\u2500(2, 6)\u2500\u2500\u2500\u2500(2, 7)\u2500\u2500\u2500(2, 8)\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                      (3, 2)\u2500\u2500\u2500(3, 3)\u2500\u2500\u2500(3, 4)\u2500\u2500\u2500(3, 5)\u2500\u2500\u2500\u2500(3, 6)\u2500\u2500\u2500\u2500(3, 7)\u2500\u2500\u2500(3, 8)\u2500\u2500\u2500(3, 9)\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n             (4, 1)\u2500\u2500\u2500(4, 2)\u2500\u2500\u2500(4, 3)\u2500\u2500\u2500(4, 4)\u2500\u2500\u2500(4, 5)\u2500\u2500\u2500\u2500(4, 6)\u2500\u2500\u2500\u2500(4, 7)\u2500\u2500\u2500(4, 8)\u2500\u2500\u2500(4, 9)\u2500\u2500\u2500(4, 10)\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n    (5, 0)\u2500\u2500\u2500(5, 1)\u2500\u2500\u2500(5, 2)\u2500\u2500\u2500(5, 3)\u2500\u2500\u2500(5, 4)\u2500\u2500\u2500(5, 5)\u2500\u2500\u2500\u2500(5, 6)\u2500\u2500\u2500\u2500(5, 7)\u2500\u2500\u2500(5, 8)\u2500\u2500\u2500(5, 9)\u2500\u2500\u2500(5, 10)\u2500\u2500\u2500(5, 11)\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n             (6, 1)\u2500\u2500\u2500(6, 2)\u2500\u2500\u2500(6, 3)\u2500\u2500\u2500(6, 4)\u2500\u2500\u2500(6, 5)\u2500\u2500\u2500\u2500(6, 6)\u2500\u2500\u2500\u2500(6, 7)\u2500\u2500\u2500(6, 8)\u2500\u2500\u2500(6, 9)\u2500\u2500\u2500(6, 10)\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n                      (7, 2)\u2500\u2500\u2500(7, 3)\u2500\u2500\u2500(7, 4)\u2500\u2500\u2500(7, 5)\u2500\u2500\u2500\u2500(7, 6)\u2500\u2500\u2500\u2500(7, 7)\u2500\u2500\u2500(7, 8)\u2500\u2500\u2500(7, 9)\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                               (8, 3)\u2500\u2500\u2500(8, 4)\u2500\u2500\u2500(8, 5)\u2500\u2500\u2500\u2500(8, 6)\u2500\u2500\u2500\u2500(8, 7)\u2500\u2500\u2500(8, 8)\n                                        \u2502        \u2502         \u2502         \u2502\n                                        \u2502        \u2502         \u2502         \u2502\n                                        (9, 4)\u2500\u2500\u2500(9, 5)\u2500\u2500\u2500\u2500(9, 6)\u2500\u2500\u2500\u2500(9, 7)\n                                                 \u2502         \u2502\n                                                 \u2502         \u2502\n                                                 (10, 5)\u2500\u2500\u2500(10, 6)\n\n\n<p style=\"text-align: justify;\">\nThe Foxtail and Bristlecone processors implement a Controlled-$Z$ gate as their two-qubit unitary (as opposed to a CNOT gate as is common with other architectures, e.g. IBM), but it is unclear to the author which particular single qubit gates are in the native gate set. (This statement is made based off of experiments compiling arbitrary gates into Foxtail/Bristlecone. See Section III.D below.) For reference, the Controlled-$Z$ gate has the following matrix representation:\n\\begin{equation}\nC(Z) = \\left[ \\begin{matrix} \n1 & 0 & 0 & 0 \\\\\n0 & 1 & 0 & 0 \\\\\n0 & 0 & 1 & 0 \\\\\n0 & 0 & 0 & -1 \\\\\n\\end{matrix} \\right] .\n\\end{equation}\n</p>\n\nIt should be noted that Cirq provides built-in functionality to convert its circuits to OpenQASM code:\n\n\n```python\n\"\"\"Generate OpenQASM code for the random number generator circuit.\"\"\"\nprint(circ.to_qasm())\n```\n\n    // Generated from Cirq v0.4.0\n    \n    OPENQASM 2.0;\n    include \"qelib1.inc\";\n    \n    \n    // Qubits: [0]\n    qreg q[1];\n    creg m_z[1];\n    \n    \n    h q[0];\n    measure q[0] -> m_z[0];\n    \n\n\n<p style=\"text-align: justify;\"> \nThis functionality makes it very simple to run algorithms generated in Cirq on IBM's quantum computers. (For instance, by navigating to the <a href=\"https://quantumexperience.ng.bluemix.net/qx/qasm\">IBM Q Experience website</a> and using the online QASM editor. See the Figure below.)\n</p>\n\n\n<p style=\"text-align: center;\">Screenshot from the IBM Q Experience online QASM Editor using Cirq to generate QASM code. The code input into the editor is the same code obtained above by executing `circ.to_qasm()`. By selecting \"run\" or \"simulate\" on the IBM Q Experience website, one can execute the quantum algorithm on a real or simulated quantum computer, respectively.</p>\n\n## <p style=\"text-align: center;\"> E. Quantum Simulators </p> \n\n<p style=\"text-align: justify;\"> \nAlthough access to Google's quantum computers is currently restricted, Cirq provides two quantum computer simulators, the `Simulator` and the `XmonSimulator`, to locally execute quantum algorithms. The `Simulator` works for generic gates that implement their unitary matrix. The `XmonSimulator` is specialized for the native gate set of Google's quantum computers and can utilize multi-threading to improve performance in certain cases.\n</p>\n\n<p style=\"text-align: justify;\"> \nTo run the random bit generator circuit above with the `Simulator`, we can do the following:\n</p>\n\n\n```python\n\"\"\"Run the random number generator on the XmonSimulator.\"\"\"\n# get the simulator\nsimulator = cirq.Simulator()\n\n# run the circuit\nout = simulator.run(circ, repetitions=50)\n\n# get the results and display them\nresults = out.histogram(key=\"z\")\nprint(results)\n```\n\n    Counter({1: 31, 0: 19})\n\n\n<p style=\"text-align: justify;\"> \nThe output is returned as a `Counter` object (Python built-in class in the `collections` library) that displays key-value pairs corresponding to the output and number of times that output was recorded. Cirq also provides the function `plot_state_histogram` to visualize the output distribution:\n</p>\n\n\n```python\n\"\"\"Display the output distribution of a cirq.TrialResult.\"\"\"\ncounts = cirq.plot_state_histogram(out)\nprint(\"counts =\", counts)\n```\n\n<p style=\"text-align: justify;\"> \nFor such a simple quantum algorithm, any quantum computer simulator is essentially equivalent. However, as algorithms scale to larger numbers of qubits and larger numbers of gates, runtime of the simulator can become important. The best current methods for classically simulating quantum circuits peak somewhere around 50 qubits due to memory limitations. (Note that this is the memory limitation of the world's best supercomputers, personal computers are typically much lower around 30 qubits.) For a fixed number of qubits, better simulators can simulate circuits with lower overall runtime and potentially even lower memory usage, which are desirable features for many applications. \n</p>\n\n<p style=\"text-align: justify;\"> \nBelow we test the performance of Cirq's simulators along these lines. After, we discuss other important capabilities of quantum computer simulators such as noise modeling.\n</p>\n\n### <p style=\"text-align: center;\"> 1. Performance of the Simulators </p> \n\n<p style=\"text-align: justify;\"> \nHere we test the performance of Cirq's simulators using random quantum circuits with different numbers of qubits and total depth. The particular form of the circuit we will consider consists of random single qubit rotations on all qubits, then a layer of entangling CNOT gates with one qubit randomly selected as the control. We define the layer of single qubit rotations plus the layer of entangling CNOTs to have a depth of one. (A circuit diagram is shown below in the article.)\n</p>\n\n<p style=\"text-align: justify;\"> \nThe code for testing the simulator is contained in a separate Python file called `cirq_code.py`. Within this file is a function called `sim_test` which inputs the number of qubits, depth of the circuit, number of times to run the circuit (also called <i>shots</i> or <i>repetitions</i>), and which simulator in Cirq to use. This function creates a random circuit of the form described above, runs it for the desired number of times, then returns the wall clock time for how long it took. An example of using this function is shown in the code cell below.\n</p>\n\n\n```python\n\"\"\"Simulator performance test for a small circuit. \nNote that the circuit structure will be random.\n\"\"\"\n# import the simulator test function\nfrom cirq_code import sim_test\n\n# inputs to sim_test\nnqubits = 4         # number of qubits\ndepth = 1           # depth of circuit\nnreps = 1           # number of repetitions\nverbose = True      # verbose output (prints circuit)\nsim_type = 0        # 0 <==> XmonSimulator, 1 <==> Simulator\n\n# do the timing test\ntime = sim_test(nqubits, depth, nreps,\n                verbose=verbose, sim_type=sim_type)\n\n# display the output\nprint(\"\\nIt took %0.2f seconds to run the circuit above.\" % time)\n```\n\n    Circuit structure shown below:\n    0: \u2500\u2500\u2500Rx(1.924\u03c0)\u2500\u2500\u2500Ry(0.123\u03c0)\u2500\u2500\u2500Rz(0.784\u03c0)\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                                 \u2502\n    1: \u2500\u2500\u2500Rx(0.338\u03c0)\u2500\u2500\u2500Ry(1.188\u03c0)\u2500\u2500\u2500Rz(1.708\u03c0)\u2500\u2500\u2500\u253c\u2500\u2500\u2500X\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                                 \u2502   \u2502\n    2: \u2500\u2500\u2500Rx(0.673\u03c0)\u2500\u2500\u2500Ry(0.136\u03c0)\u2500\u2500\u2500Rz(0.596\u03c0)\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500M\u2500\u2500\u2500\n                                                         \u2502\n    3: \u2500\u2500\u2500Rx(1.692\u03c0)\u2500\u2500\u2500Ry(0.949\u03c0)\u2500\u2500\u2500Rz(1.988\u03c0)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500M\u2500\u2500\u2500\n    \n    It took 0.03 seconds to run the circuit above.\n\n\nFor such a small circuit, the runtime is almost instantaneous. As we scale to larger and larger circuits, however, the complexity of simulating the circuit increases. Below we up the scale to 20 qubits with a depth of 10.\n\n\n```python\n\"\"\"Simulator performance test for a larger circuit.\"\"\"\n# inputs to sim_test\nnqubits = 20        # number of qubits\ndepth = 10          # depth of circuit\nnreps = 1           # number of repetitions\nverbose=False       # verbose output (prints circuit)\n\n# do the timing test\ntime = sim_test(nqubits, depth, nreps, verbose=verbose)\n\n# display the output\nprint(\"\\nIt took %0.2f seconds to run the circuit.\" % time)\n```\n\n    \n    It took 29.53 seconds to run the circuit.\n\n\n<p style=\"text-align: justify;\"> \nHere the code takes noticeably longer to run. For many applications, simulating large circuits quickly is an important task. We use the `sim_test` function above to test the performance of both the `Simulator` and `XmonSimulator` by sweeping over values of qubits and depth. In particular, we sweep over the qubit numbers $n = 10, 12, ..., 24$ and depths $d = 20, 40, ..., 100$ and time the simulator performance at each. The results of this study are displayed in the figure below.\n</p>\n\n\n<p style=\"text-align: center;\">Plots showing the performance of the `Simulator` (top) and `XmonSimulator` (bottom). The horizontal axis shows the number of qubits and the vertical axis shows the depth as defined above. Dark green represents faster simulation time and bright yellow represents longer simulation time. Values in each square show total overall runtime in seconds, averaged over many runs. Color scales are different for each plot.</p>\n\n<p style=\"text-align: justify;\"> \nAs can be seen, the performance of the `XmonSimulator` and `Simulator` are similar in terms of overall runtime. Depending on the computer architecture, increasing the number of threads or _shards_ could increase the performance of the `XmonSimulator`. (This is discussed below in Section 2.) The maximum number of qubits that can be simulated depends on memory of the user's computer (more RAM implies larger circuits). The largest circuit the author attempted to run with the `Simulator` contained 26 qubits and a depth of 10 as defined above. This circuit finished running in just over one hour. Larger circuit instances throw `MemoryError`s on the author's computer. (For reference, on a similar circuit with a depth of 20, the state vector simulator in QISKit is able to simulate 25 qubits in 160 seconds, and the C++ simulator in ProjectQ is able to simulate 27 qubits in 504 seconds <a href=\"#LaR2018\">[LaR2018]</a>.)\n</p>\n\n<p style=\"text-align: justify;\"> \nThe resource requirements (memory and runtime) for simulating larger circuits quickly reaches the limitations of current supercomputers. Researchers at Google are very interested in using a quantum computer to simulate some circuit that a classical computer cannot feasibly do, a feat called <i>quantum supremacy</i>. Cirq contains built-in functions for generating so-called \"supremacy circuits,\" as can be seen below.\n</p>\n\n\n```python\n\"\"\"Display a quantum supremacy circuit on the\nfirst three rows of Bristlecone with a CZ depth of 5.\n\"\"\"\nprint(cirq.generate_supremacy_circuit_google_v2_bristlecone(3, 5, 0))\n```\n\n                  \u250c\u2500\u2500\u2510\n    (0, 5): \u2500\u2500\u2500H\u2500\u2500\u2500T\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500T\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\n                        \u2502\n    (0, 6): \u2500\u2500\u2500H\u2500\u2500\u2500T\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500T\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\n                                \u2502\n    (1, 5): \u2500\u2500\u2500H\u2500\u2500\u2500T\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\n                                \u2502       \u2502            \u2502\n    (1, 6): \u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500X^0.5\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\n                   \u2502                    \u2502\n    (2, 5): \u2500\u2500\u2500H\u2500\u2500\u2500\u253cT\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500X^0.5\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500H\u2500\u2500\u2500\n                   \u2502    \u2502\n    (2, 6): \u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500X^0.5\u2500\u2500\u2500T\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\n                  \u2514\u2500\u2500\u2518\n\n\n<p style=\"text-align: justify;\"> \n(In the circuit diagram, brackets at the top/bottom are placed when operations are in the same moment but it is impossible to draw them all in the same column. In the second moment, all $T$ gates and the Controlled-$Z$ gates, which are all encompassed by the top/bottom brackets, happen simultaneously.)\n</p>\n\n<p style=\"text-align: justify;\"> \nAs we've seen above, this small circuit using only three rows (six qubits) of Bristlecone could be easily simulated by a classical computer. However, extending the circuit to all qubits on Bristlecone generates a circuit that is extremely difficult to classically simulate. Quantum supremacy is expected to be announced within the next few years.\n</p>\n\n### <p style=\"text-align: center;\"> 2. Features of the Simulators </p> \n\n<p style=\"text-align: justify;\"> \nWhile raw performance is an important aspect of simulators, other features such as noise capabilities and special-purpose simulators (e.g., Clifford circuit simulators) are equally if not more important. In particular, noise capabilities allow users to mimic the evolution on real quantum hardware and get better estimates of the performance of their algorithms. The software packages pyQuil and QISKit contain these features.\n</p>\n\n<p style=\"text-align: justify;\"> \nCurrently, Cirq does not contain any obvious support for noisy circuit simulation for either the `Simulator` or `XmonSimulator`. As Cirq is still in alpha testing, however, this feature is likely to be implemented in future releases and is a <a href=\"https://github.com/quantumlib/Cirq/issues/730\">current work in progress</a>.\n</p>\n\n<p style=\"text-align: justify;\"> \nFor now, notable features of the simulators include multi-threading for the `XmonSimulator` and access to the wave function for both simulators. To get a simulator that uses multiple threads, we can pass an `XmonOptions` object specified with the number of threads into the `XmonSimulator`, as shown below.\n</p>\n\n\n```python\n\"\"\"Get an XmonSimulator with multiple threads (shards).\"\"\"\noptions = cirq.google.sim.XmonOptions(num_shards=2)\nsimulator = cirq.google.XmonSimulator(options)\n```\n\n<p style=\"text-align: justify;\"> \nThis simulator can then be used to execute circuits in the same way as above.\n</p>\n\n<p style=\"text-align: justify;\"> \nAdditionally, there are two types of methods that simulators support, the \"run methods\" and the \"simulate methods.\" The \"run methods\" (`run` and `run_sweep`) emulate quantum computer hardware and only return measurement results. (The `run` method is what we used above to test the simulator performance.) For full access to the wavefunction and for debugging purposes, the \"simulate methods\" (`simulate`, `simulate_sweep`, and `simulate_moment_steps`) can be used. An example of using a simulate method is shown below.\n</p>\n\n\n```python\n\"\"\"Use the \"simulate methods\" to get full access to the wavefunction.\"\"\"\n# make a bell state preparation circuit\ncirc = cirq.Circuit()\nqbits = [cirq.LineQubit(x) for x in range(2)]\ncirc.append([cirq.H(qbits[0]), cirq.CNOT(qbits[0], qbits[1])])\n\n# print out the circuit\nprint(circ)\n\n# simulate the circuit\nres = simulator.simulate(circ)\n```\n\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500\n              \u2502\n    1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\n\n\nOnce the circuit has been simulated, the result `res` is stored as a `SimulationTrialResult`. This output supports several useful features including generating the wavefunction, (reduced) density matrix, and even Dirac notation of the state. A few of these features are demonstrated below.\n\n\n```python\n\"\"\"Use the output of a simulation to generate \nthe wavefunction, density matrix, and Dirac notation.\n\"\"\"\n# show the wavefunction\nprint(\"The wavefunction of the final state is:\\n\",\n      res.final_state, end=\"\\n\")\n\n# show the Dirac notation for the state\nprint(\"\\nThe Dirac notation for the final state is:\\n\",\n      res.dirac_notation())\n\n# show the density matrix of the total state\nprint(\"\\nThe density matrix of the final state is:\\n\",\n      res.density_matrix())\n\n# show the reduced density matrix of the first qubit\nprint(\"\\nThe reduced density matrix of the first qubit is:\\n\",\n      res.density_matrix([0]))\n```\n\n    The wavefunction of the final state is:\n     [-3.0908623e-08+0.7071068j  2.5716280e-16+0.j\n     -3.0908616e-08+0.j         6.1817239e-08+0.7071068j]\n    \n    The Dirac notation for the final state is:\n     (0.71j)|00\u27e9 + (0.71j)|11\u27e9\n    \n    The density matrix of the final state is:\n     [[ 5.0000006e-01+0.0000000e+00j -7.9485483e-24+1.8184158e-16j\n       9.5534273e-16-2.1855694e-08j  5.0000006e-01+6.5567093e-08j]\n     [-7.9485483e-24-1.8184158e-16j  6.6132707e-32+0.0000000e+00j\n      -7.9485467e-24-0.0000000e+00j  1.5897095e-23-1.8184158e-16j]\n     [ 9.5534273e-16+2.1855694e-08j -7.9485467e-24+0.0000000e+00j\n       9.5534252e-16+0.0000000e+00j -1.9106853e-15+2.1855694e-08j]\n     [ 5.0000006e-01-6.5567093e-08j  1.5897095e-23+1.8184158e-16j\n      -1.9106853e-15-2.1855694e-08j  5.0000006e-01+0.0000000e+00j]]\n    \n    The reduced density matrix of the first qubit is:\n     [[5.0000006e-01+0.0000000e+00j 9.5534273e-16-2.1855694e-08j]\n     [9.5534273e-16+2.1855694e-08j 5.0000006e-01+0.0000000e+00j]]\n\n\n# <p style=\"text-align: center;\"> III. Features of Cirq </p> \n\n<p style=\"text-align: justify;\"> \nIn the previous section, we looked at features of the quantum computer simulators of Cirq. In this section we discuss notable features of the entire Cirq platform, including methods for manipulating, parameterizing, optimizing, and compiling circuits. Since each \"full-stack\" software platform has the same goal (programming a quantum computer), the features of each are what set them apart. Our coverage is not comprehensive (see the documentation for all features) but consists of features we find particularly notable or useful.\n</p>\n\n## <p style=\"text-align: center;\"> A. Manipulating Circuits </a></p> \n\n<p style=\"text-align: justify;\"> \nAs suggested by the name, the main utility of Cirq is working with and manipulating quantum circuits. By \"manipulating quantum circuits,\" we mean operations of the following form:\n</p>\n\n* Creating quantum circuits.\n* Performing arithmetic with circuits.\n* Inserting instructions in a circuit.\n* Removing instructions from a circuit.\n* Gaining information about a circuit.\n\n<p style=\"text-align: justify;\"> \nIn order to demonstrate these operations, we'll first import a function for creating quantum circuits with random single qubit gates.\n</p>\n\n\n```python\n\"\"\"Get a function for creating circuits with random one-qubit gates.\"\"\"\nfrom cirq_code import random_circuit\n\n# create a random circuit with 5 qubits and 5 moments\ncirc, qbits = random_circuit(5, 5)\nprint(circ)\n```\n\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500Z\u2500\u2500\u2500Z\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500Z\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    1: \u2500\u2500\u2500X^0.5\u2500\u2500\u2500T\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500Y\u2500\u2500\u2500T\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    2: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500T\u2500\u2500\u2500X^0.5\u2500\u2500\u2500Z\u2500\u2500\u2500X^0.5\u2500\u2500\u2500\n    \n    3: \u2500\u2500\u2500X^0.5\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    4: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500X^0.5\u2500\u2500\u2500X\u2500\u2500\u2500Z\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\nCircuits are stored as iterables of _moments_, where a moment is a set of operations that happens at the same time. To see each moment comprising a circuit, we can do the following:\n\n\n```python\n\"\"\"Print out each moment in the circuit.\"\"\"\nfor moment in circ:\n    print(moment)\n```\n\n    H(0) and X**0.5(1) and H(2) and X**0.5(3) and H(4)\n    Z(0) and T(1) and T(2) and H(3) and X(4)\n    Z(0) and X(1) and X**0.5(2) and H(3) and X**0.5(4)\n    H(0) and Y(1) and Z(2) and X(3) and X(4)\n    Z(0) and T(1) and X**0.5(2) and H(3) and Z(4)\n\n\nThis output tells us exactly what we see in the circuit diagram above as we move from left to right in the circuit.\n\n<p style=\"text-align: justify;\"> \nArithmetic can be performed on circuits in a natural way. For example, the sum of two circuits is a circuit consisting of all moments from the first circuit then all moments from the second circuit. Circuit multiplication is repeated addition of the same circuit. While simple, these operations are very useful when designing circuits, especially variational circuits. (Note that pyQuil and QISKit also have circuit arithmetic.) In this case, one circuit can be dedicated to, say, state preparation, while the other contains the variational ansatz. The circuit to be executed then consists of the sum of the two.\n</p>\n\n<p style=\"text-align: justify;\"> \nIn many other cases with variational algorithms, it is desirable to remove specific gates from a circuit. Cirq provides a simple built-in method to perform this task, demonstrated below.\n</p>\n\n\n```python\n\"\"\"Clear operations from a circuit.\"\"\"\ncirc.clear_operations_touching(qbits[1:4], range(1, 4))\nprint(circ)\n```\n\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500Z\u2500\u2500\u2500Z\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500Z\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    1: \u2500\u2500\u2500X^0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500T\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    2: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X^0.5\u2500\u2500\u2500\n    \n    3: \u2500\u2500\u2500X^0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    4: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500X^0.5\u2500\u2500\u2500X\u2500\u2500\u2500Z\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n<p style=\"text-align: justify;\"> \nIn the same manner, Cirq contains methods for inserting operations into a circuit, such as `batch_insert`, which inserts a sequence of (location, operation) pairs into the circuit, as demonstrated below.\n</p>\n\n\n```python\n\"\"\"Insert operations into a circuit at specific locations.\"\"\"\ncirc.batch_insert([(1, cirq.CZ(qbits[2], qbits[3])), \n                   (2, cirq.CNOT(qbits[1], qbits[3]))])\nprint(circ)\n```\n\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500Z\u2500\u2500\u2500Z\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500Z\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    1: \u2500\u2500\u2500X^0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500T\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X^0.5\u2500\u2500\u2500\n                  \u2502   \u2502\n    3: \u2500\u2500\u2500X^0.5\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    4: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500X^0.5\u2500\u2500\u2500X\u2500\u2500\u2500Z\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n<p style=\"text-align: justify;\"> \nHere we have inserted two-qubit gates (for clarity) into the region in which we previously removed gates. Although these abilities may appear to be contrived, operations of this form are particularly useful for programming variational quantum algorithms.\n</p>\n\n<p style=\"text-align: justify;\"> \nIn addition to manipulating quantum circuits, there are many methods built in to circuits that return useful information. Among these are `all_operations`, `all_qubits`, and `next_moment_operating_on` (also `prev_moment_operating_on`). A full set of circuit methods returning information about the circuit or modifying the circuit in place can be found in the documentation. Lastly, we remark that a circuit can be turned into a unitary matrix by using the method `to_unitary_matrix`.\n</p>\n\n## <p style=\"text-align: center;\"> B. Parameterizing Circuits </p> \n\n<p style=\"text-align: justify;\"> \nBecause of Cirq's strong support for variational quantum algorithms (in which parameters/angles of an algorithm are iteratively changed to minimize an energy or cost function), the platform provides useful features for working with these types of circuits. In particular, two components are particularly notable for this task: `Symbol`s and simulating/running \"sweeps\" of circuits, which we now elaborate on.\n</p>\n\n<p style=\"text-align: justify;\"> \nRather than having to create a new quantum circuit for every new set of variables, Cirq allows gates with parameters to have `Symbol`s, which can be resolved by a `ParamResolver` with a given set of angles. In addition to cleaning up code, this decreases overall runtime of programs by avoiding the task of creating a new quantum circuit for every given set of angles. An example of creating a circuit with `Symbol`s is shown below.\n</p>\n\n\n```python\n\"\"\"Create a circuit that contains a symbol.\"\"\"\n# get a circuit and a qubit\ncirc = cirq.Circuit()\nqbit = cirq.LineQubit(0)\n\n# add a gate with a definite angle\ncirc.append([cirq.XPowGate(exponent=np.pi / 2)(qbit)])\n\n# add a gate with a symbol which can take any value\nsym = cirq.Symbol(\"t\")\ngate = cirq.XPowGate(exponent=sym)\ncirc.append([gate(qbit)])\n\n# add a measurement\ncirc.append(cirq.measure(qbit, key=\"z\"))\n\n# show the circuit diagram\nprint(circ)\n```\n\n    0: \u2500\u2500\u2500X^(-3/7)\u2500\u2500\u2500X^t\u2500\u2500\u2500M('z')\u2500\u2500\u2500\n\n\n<p style=\"text-align: justify;\"> \nWhen we print out the circuit diagram, we see that we have one gate with a definite parameter (the first gate) and another with a symbol $t$, which we must instantiate with a value before trying to run a circuit. One way to do this is to explicitly use a `ParamResolver` to give $t$ a value, as follows.\n</p>\n\n\n```python\n\"\"\"Run a parameterized circuit by resolving\nthe circuit with a ParamResolver.\n\"\"\"\n# get a param resolver\nparam_resolver = cirq.ParamResolver({sym.name: np.pi / 4})\n\n# run the resolved circuit using the param resolver\nres = simulator.run(circ, param_resolver, repetitions=500)\n\n# plot the output distribution\nvals = cirq.plot_state_histogram(res)\n```\n\n<p style=\"text-align: justify;\"> \nWith this method, we only have to change the value of the `ParamResolver` to change the circuit. By looping over many values, we can find the minimum of some cost function defined for a variational algorithm. A slightly simplified way to do this in Cirq is by using the \"sweep\" methods, e.g. `run_sweep` or `simulate_sweep`, to loop over these values automatically. A simple example of doing so using the same circuit above is as follows.\n</p>\n\n\n```python\n\"\"\"Sweep over a set of values to run a parameterized circuit at.\"\"\"\n# get a \"sweep\" of values\nsweep = cirq.Linspace(key=sym.name, start=0, stop=np.pi, length=100)\n\n# run the circuit at all values in the sweep\nres = simulator.run_sweep(circ, sweep, repetitions=1000)\n\n# plot the frequency of zero outputs for all values in the sweep\ntvals = [x[0][1] for x in sweep.param_tuples()]\ncvals = [res[i].histogram(key=\"z\")[0]/1000 for i in range(len(res))]\nplt.plot(tvals, cvals, \"-o\", linewidth=2)\n\n# plot style\nplt.grid(); plt.xlabel(\"t\");\nplt.ylabel(\"Frequency of 0 Measurement\");\nplt.title(\"Sweeping over parameters in a circuit\");\n```\n\n## <p style=\"text-align: center;\"> C. Optimizing Circuits </p> \n\n<p style=\"text-align: justify;\"> \n<i>Quantum compiling</i> consists of rewriting a given algorithm in terms of gates a quantum computer can actually implement (a <i>native gate set</i> or simply <i>gate set</i>). Cirq has functionality to create a circuit for a particular `Device` (see <i>Devices and Schedules</i> below) and automatically compile gates into the native gate set. A similar problem is that of <i>quantum circuit optimization</i>, by which we mean rewriting a quantum circuit to contain as few gates as possible. For example, we would never implement two Pauli operations ($X$, $Y$, $Z$) in sequence because they square to the identity. Similar ideas apply to other gates. This task is critical for NISQ hardware as errors accumulate through gate application and decoherence throughout the algorithm. \n</p>\n\n<p style=\"text-align: justify;\"> \nCirq provides several utilities for quantum circuit optimization, which we demonstrate below without specification to a native gate set. (The exact same functionality works for circuits tied to a `Device`.) First, we obtain a random circuit consisting of only single qubit gates for simplicity.\n</p>\n\n\n```python\n\"\"\"Get a random circuit.\"\"\"\ncirc, qbits = random_circuit(4, 5)\n\nprint(circ)\n```\n\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500Y\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\n    \n    1: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500Z\u2500\u2500\u2500\u2500\u2500\u2500\u2500Z\u2500\u2500\u2500X\u2500\u2500\u2500\n    \n    2: \u2500\u2500\u2500Z\u2500\u2500\u2500T\u2500\u2500\u2500T\u2500\u2500\u2500\u2500\u2500\u2500\u2500T\u2500\u2500\u2500Z\u2500\u2500\u2500\n    \n    3: \u2500\u2500\u2500Z\u2500\u2500\u2500Y\u2500\u2500\u2500X^0.5\u2500\u2500\u2500T\u2500\u2500\u2500Z\u2500\u2500\u2500\n\n\n<p style=\"text-align: justify;\"> \nThe random circuit we obtained is shown above. Note that this function utilizes an `InsertStrategy` in Cirq, which \"indicates preferences on how to add multiple operations to a circuit.\" In the above example, we used `InsertStrategy.EARLIEST`, which tells the circuit to push gates being inserted as far to the left as possible. Other strategies include `INLINE` and `NEW_THEN_INLINE`. \n</p>\n\n<p style=\"text-align: justify;\"> \nThe first optimization pass we will try is `EjectZ`, which rewrites the circuit by attempting to push all $Z$ gates to the end of the circuit.\n</p> \n\n\n```python\n\"\"\"Push Z gates toward the end of the circuit.\"\"\"\nejectZ = cirq.optimizers.EjectZ()\nejectZ.optimize_circuit(circ)\nprint(circ)\n```\n\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500Y\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\n    \n    1: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\n    \n    2: \u2500\u2500\u2500Z^0.75\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500Y\u2500\u2500\u2500X^-0.5\u2500\u2500\u2500T\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n<p style=\"text-align: justify;\"> \nAs we can see, all $Z$ operations now appear at the right-most portion of the circuit. Next we will perform a similar optimization pass, this time attempting to push $X$, $Y$, and `PhasedXPowGate`s to the right.\n</p> \n\n\n```python\n\"\"\"Push X, Y, and PhasedXPow gates toward the end of the circuit.\"\"\"\nejectPaulis = cirq.optimizers.EjectPhasedPaulis()\nejectPaulis.optimize_circuit(circ)\n\nprint(circ)\n```\n\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500Z\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\n    \n    1: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    2: \u2500\u2500\u2500Z^0.75\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X^0.5\u2500\u2500\u2500PhasedX(-0.375)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n<p style=\"text-align: justify;\">\nAnother circuit optimization provided by Cirq is merging all single qubit gates into `PhasedXPow` and `PhasedZPow` gates, which we demonstrate below.\n</p>\n\n\n```python\n\"\"\"Merge single qubit gates into PhasedX and PhasedZ gates.\"\"\"\ncirq.merge_single_qubit_gates_into_phased_x_z(circ)\n\nprint(circ)\n```\n\n    1: \u2500\u2500\u2500Y^-0.5\u2500\u2500\u2500Z\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    2: \u2500\u2500\u2500Z^0.75\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X^-0.5\u2500\u2500\u2500Z^-0.75\u2500\u2500\u2500\n\n\n<p style=\"text-align: justify;\">\nWe see that the entire circuit is now expressed in terms of these gates. As a last touch, we can attempt to drop any gates that have a \"negligible\" (i.e., very small) effect on the overall circuit and drop empty `moment`s in the circuit.\n</p>\n\n\n```python\n\"\"\"Removes operations with a tiny effect and\ndrop empty moments in the circuit.\n\"\"\"\n# drop negligible gates\ndrop_neg = cirq.optimizers.DropNegligible()\ndrop_neg.optimize_circuit(circ)\n\n# drop empty moments\ndrop_empty = cirq.optimizers.DropEmptyMoments()\ndrop_empty.optimize_circuit(circ)\n\nprint(circ)\n```\n\n    1: \u2500\u2500\u2500Y^-0.5\u2500\u2500\u2500Z\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    2: \u2500\u2500\u2500Z^0.75\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X^-0.5\u2500\u2500\u2500Z^-0.75\u2500\u2500\u2500\n\n\n<p style=\"text-align: justify;\">\nCirq also allows single qubit gates to be merged into arbitrary two by two unitary transformations. These may not in general have a specified name like $H$, $T$, etc., so the quantum circuit drawer simply shows matrix elements:\n</p>\n\n\n```python\n\"\"\"Merge single qubit gates.\"\"\"\nmerge = cirq.optimizers.MergeSingleQubitGates()\nmerge.optimize_circuit(circ)\n\nprint(circ)\n```\n\n    1: \u2500\u2500\u2500\u250c                   \u2510\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n          \u2502 0.5-0.5j  0.5-0.5j\u2502\n          \u2502 0.5-0.5j -0.5+0.5j\u2502\n          \u2514                   \u2518\n    \n    2: \u2500\u2500\u2500\u250c                           \u2510\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n          \u2502 1.   +0.j     0.   +0.j   \u2502\n          \u2502 0.   +0.j    -0.707+0.707j\u2502\n          \u2514                           \u2518\n    \n    3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u250c                           \u2510\u2500\u2500\u2500\n                                          \u2502 0.5  -0.5j    0.5  +0.5j  \u2502\n                                          \u2502 0.   -0.707j -0.707-0.j   \u2502\n                                          \u2514                           \u2518\n\n\n<p style=\"text-align: justify;\">\nWe note that optimized circuits can be run/simulated with either the `Simulator` or `XmonSimulator` and that optimizing circuits before simulating them may result in improved performance. Below we simulate the above optimized circuit and display its wavefunction in Dirac notation.\n</p>\n\n\n```python\n\"\"\"Run the optimized circuit and display its wavefunction in Dirac notation.\"\"\"\nres = simulator.simulate(circ)\nprint(res.dirac_notation())\n```\n\n    (0.5j)|000\u27e9 + (0.35+0.35j)|001\u27e9 + (0.5j)|100\u27e9 + (0.35+0.35j)|101\u27e9\n\n\n<p style=\"text-align: justify;\">\nThe Dirac notation of the wavefunction above corresponds to the same wavefunction we would have obtained by simulating the original circuit. Here, we achieved the same effect with much fewer gates.\n</p>\n\n<p style=\"text-align: justify;\">\nOf course, a given quantum computer cannot implement arbitrary gates like the simulator has done above. As mentioned, these gates need to be compiled into operations the computer can implement. Cirq provides this functionality with a `Device`, as we elaborate on below.\n</p>\n\n## <p style=\"text-align: center;\"> D. Devices and Schedules </p> \n\n<p style=\"text-align: justify;\">\nThe existence of `Device`s and `Schedule`s again reflects Cirq's emphasis on near-term quantum computing. Briefly, a `Device` corresponds to a quantum computer with given constraints such as qubit connectivity and native gate sets. A `Schedule` corresponds to the real-time implementation of operations on a `Device`. Users have full control to specify any quantum computer architecture using a `Device` and can program a circuit for any given quantum computer. Because the documentation contains detailed information on user-defined devices and schedules, we omit this discussion here. Instead, we provide information on `Device`s by analyzing one that is already defined in Cirq. Namely, the Foxtail quantum computer.\n</p>\n\n<p style=\"text-align: justify;\">\nIn the following code, we create a quantum circuit with its device set as Foxtail:\n</p>\n\n\n```python\n\"\"\"Make a quantum circuit whose device is the\n22 qubit Foxtail quantum computer.\n\"\"\"\n# grab the device\nfoxtail = cirq.google.Foxtail\n\n# get the qubits of foxtail\nqbits = sorted(list(foxtail.qubits))\n\n# make a circuit and set foxtail to be its device\ncirc = cirq.Circuit(device=foxtail)\n```\n\n<p style=\"text-align: justify;\">\nOnce we grab the `Foxtail` device, we can get its qubits and then create a circuit. We can use the method `decompose_operation` of a `Device` to compile/decompose a gate operation. Below we show this for the example of the Hadamard gate.\n</p>\n\n\n```python\n\"\"\"Compile/decompose operations into the native gate set of Foxtail.\"\"\"\n# get the hadamard gate\nhgate = cirq.H(qbits[0])\n\n# compile/decompose the gate into native operations\ncompiled_hgate = foxtail.decompose_operation(hgate)\n\n# print out the gate and its compilation\nprint(hgate, \"=\", *compiled_hgate)\n```\n\n    H((0, 0)) = Y**-0.5((0, 0)) Z**-1.0((0, 0))\n\n\n<p style=\"text-align: justify;\">\nOnce we have compiled gates, we can append them into the circuit. Alternatively, if we add any gate operation into a circuit, they will get compiled automatically. Below we show this for the Bell state preparation circuit consisting of a Hadamard and CNOT gate.\n</p>\n\n\n```python\n\"\"\"Adding operations to a circuit with a device compiles them automatically.\"\"\"\n# cnot gate\ncnot = cirq.CNOT(qbits[0], qbits[1])\n\n# append the operations\ncirc.append([hgate, cnot])\n\n# print the circuit\nprint(circ)\n```\n\n    (0, 0): \u2500\u2500\u2500Y^-0.5\u2500\u2500\u2500Z\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                            \u2502\n    (0, 1): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhasedX(-0.5)^0.5\u2500\u2500\u2500@\u2500\u2500\u2500PhasedX(0.5)^0.5\u2500\u2500\u2500\n\n\n\n```python\n\"\"\"Attempt to optimize the circuit. Only commutes\nZ across CZ for a single Bell state preparation circuit, \nsimplifies two sequential Bell state preparation circuits. \n(Run the cell above twice to see this.)\n\"\"\"\nejectZ.optimize_circuit(circ)\nejectPaulis.optimize_circuit(circ)\ndrop_neg.optimize_circuit(circ)\ncirq.merge_single_qubit_gates_into_phased_x_z(circ)\n\nprint(circ)\n```\n\n    (0, 0): \u2500\u2500\u2500Y^-0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500Z\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                            \u2502\n    (0, 1): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhasedX(-0.5)^0.5\u2500\u2500\u2500@\u2500\u2500\u2500PhasedX(0.5)^0.5\u2500\u2500\u2500\n\n\n<p style=\"text-align: justify;\">\nHere we can see the native operations of Foxtail (which are the same for Bristlecone). When running the circuit, these are the gates the computer actually implements. Another useful feature of `Device`s is that they contain timing information for each of the native gates. (When programming a user-defined `Device`, these values can be specified to match an arbitrary computer.) To see this information, we can use the `duration_of` method to see how long each native gate takes to implement.\n</p>\n\n\n```python\n\"\"\"See how long each native operation takes to implement.\"\"\"\n# grab the times of some native gates\nytime = foxtail.duration_of(cirq.Y(qbits[0]))\nztime = foxtail.duration_of(cirq.Z(qbits[0]))\ncztime = foxtail.duration_of(cirq.CZ(qbits[0], qbits[1]))\n\n# print them out\nprint(\"Y time =\", ytime.total_nanos(), \"nanoseconds.\")\nprint(\"Z time =\", ztime.total_nanos(), \"nanoseconds.\")\nprint(\"CZ time =\", cztime.total_nanos(), \"nanoseconds.\")\n```\n\n    Y time = 20.0 nanoseconds.\n    Z time = 0.0 nanoseconds.\n    CZ time = 50.0 nanoseconds.\n\n\n<p style=\"text-align: justify;\">\nHere we see that the single qubit gate $Y$ takes 20 nanoseconds to implement (on any qubit), and the two-qubit gate Controlled-$Z$ takes over twice as long to implement at 50 nanoseconds. The $Z$ gate takes no time to implement because it is a \"virtual\" gate. That is, it is implemented by shifting the clock of the software keeping track of the qubit and not by any physical operation acting on the qubit like the $Y$ or Controlled-$Z$ gate.\n</p>\n\n## <p style=\"text-align: center;\"> E. Other Features </p> \n\n<p style=\"text-align: justify;\">\nTo conclude this section, we briefly mention other notable features of Cirq. \n</p>\n\n<p style=\"text-align: justify;\">\nIn terms of library support, which we define to mean any built-in algorithms or examples demonstrating how to implement algorithms, several companies have used Cirq in collaboration with Google for various projects. For example, <a href=\"https://zapatacomputing.com/\">Zapata Computing</a> used Cirq to implement a quantum autoencoder, <a href=\"https://qcware.com/press/20180718\">QC Ware</a> used Cirq for implementing QAOA, and <a href=\"https://heisenberg.xyz/news/2018/07/heisenberg-cirq/\">Heisenberg Quantum Simulations</a> used Cirq to simulate the Anderson model. The documentation of Cirq contains an in-depth <a href=\"https://cirq.readthedocs.io/en/stable/tutorial.html\">tutorial</a> of a variational quantum algorithm, and the <a href=\"https://github.com/quantumlib/Cirq/tree/master/examples\">examples folder on Cirq's GitHub</a> contains detailed Python scripts on Grover's algorithm, the quantum Fourier Transform, the phase estimation algorithm, the Bernstein-Vazirani algorithm, and an example preparing BCS ground states for superconductors/superfluids.\n</p>\n\n<p style=\"text-align: justify;\">\nCirq also contains integration with <a href=\"https://github.com/quantumlib/OpenFermion\">OpenFermion</a>, a hardware-agnostic library for simulating fermionic systems on quantum computers, through <a href=\"https://github.com/quantumlib/OpenFermion-Cirq\">OpenFermion-Cirq</a>. This library, also in alpha release, is focused on extending the functionality of OpenFermion \"by providing routines and tools for using Cirq to compile and compose circuits for quantum simulation algorithms\" (from the README).\n</p>\n\n<p style=\"text-align: justify;\">\nOther notable features of the Cirq library are quantum channels and stabilizers. These features are still labeled \"work in progress\" in the documentation, so for fairness we do not delve into these topics but rather note them as interesting and useful features once they are completed.\n</p>\n\n# <p style=\"text-align: center;\"> IV. Example Algorithms </p> \n\nIn this final section, we look at example algorithms programmed in Cirq.\n\n## <p style=\"text-align: center;\"> A. Quantum Teleportation Algorithm </p> \n\n<p style=\"text-align: justify;\"> \nFor consistency with our comparison of pyQuil, QISKit, ProjectQ, and the Quantum Developer Kit <a href=\"#LaR2018\">[LaR2018]</a>, we include a complete program for the quantum teleportation algorithm below. This algorithm teleports an arbitrary quantum state $|\\psi\\rangle$ (which we take to be $|1\\rangle = X |0\\rangle$ for example below) from one person, Alice, to another, Bob, without either one knowing what the actual state is. More complete descriptions of this protocol can be found in any standard source on quantum computing, for example the <a href=\"https://quantumcomputingreport.com/resources/education/\">ones listed here</a>.\n</p>\n\n\n```python\n\"\"\"Quantum teleportation algorithm written in Cirq.\"\"\"\n# get qubits and a circuit\nqbits = [cirq.LineQubit(x) for x in range(3)]\ncirc = cirq.Circuit()\n\n# Alice wants to teleport |1> to Bob\ncirc.append(cirq.ops.X(qbits[0]))\n\n# Bell state preparation on Bob's qubits\ncirc.append([cirq.ops.H(qbits[1]),\n    cirq.ops.CNOT(qbits[1], qbits[2])])\n            \n# Bell state measurement on Alice's qubits\ncirc.append([cirq.ops.H(qbits[0]),\n    cirq.ops.CNOT(qbits[0], qbits[1]),\n    cirq.measure(qbits[0]),\n    cirq.measure(qbits[1])])\n\n# print out the circuit\nprint(circ)\n```\n\n    0: \u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500M\u2500\u2500\u2500\n                          \u2502\n    1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500M\u2500\u2500\u2500\n                  \u2502\n    2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n<p style=\"text-align: justify;\"> \nTo the author's knowledge, there does not exist an easy way to perform classical conditional operations, such as those required by the quantum teleportation algorithm, in Cirq. However, we can use the \"simulate\" methods of Cirq to get the state of the third qubit, as shown below. Note that both measurement outcomes are deterministically zero in this situation, so no conditional operations are required.\n</p>\n\n\n```python\n\"\"\"Verify the state of the third qubit is |1> using the simulate methods.\"\"\"\n# simulate the circuit with access to the wavefunction\nres = simulator.simulate(circ)\n\n# print out the density matrix, which should be\n# [[0, 0],\n#  [0, 1]]\nprint(res.density_matrix([2]))\n```\n\n    [[ 9.9999988e-01+0.0000000e+00j -3.1794184e-23+3.6368302e-16j]\n     [-3.1794184e-23-3.6368302e-16j  1.3226535e-31+0.0000000e+00j]]\n\n\n<p style=\"text-align: justify;\"> \nTo within floating point precision, this is exactly the density matrix we expect.\n</p>\n\n## <p style=\"text-align: center;\"> B. Variational Algorithm </p> \n\n<p style=\"text-align: justify;\"> \nWe now show an example of a variational quantum-classical algorithm using Cirq. The algorithm shown, called Variational Quantum State Diagonalization (VQSD), is used to diagonalize a quantum state (more generally, a positive semidefinite matrix) and was introduced in <a href=\"#La2018\">[La2018]</a>. Without going into all details in the paper, the algorithm works by taking as input two copies of a quantum state $\\rho$. For our simple illustrative example, we will use a one qubit state $\\rho = |+\\rangle \\langle +|$ which can be prepared by performing a Hadmard gate on each qubit at the start of the algorithm, $|+\\rangle := H |0\\rangle$. (Generally, VQSD assumes the state is prepared from some efficient process, a notable example being quantum simulation, for which VQSD can be used for entanglement spectroscopy and other condensed matter applications) Next, the algorithm implements a variational ansatz (or structure of the circuit), which we take to be $U(t) = R_z(\\pi / 2) X^t R_z(\\pi / 2)$ where $t$ is the only parameter. Finally, a measure of \"diagonality\" of the state after the ansatz circuit has been applied is computed. For our case, this amounts to a single CNOT gate and a measurement in the computational basis.\n</p>\n\n<p style=\"text-align: justify;\"> \nIn general for variational algorithms, a (classical) optimization algorithm can be used to find the best set of parameters for the ansatz. Here, we simply sweep over the parameter $t$ in our ansatz and plot the results to find the parameter that maximizes the measure of \"diagonality\" of $\\rho' := U \\rho U^\\dagger$. The complete program is shown below.\n</p>\n\n\n```python\n\"\"\"Implementation of the VQSD algorithm [La2018] \non a simple one qubit state.\n\"\"\"\n# ====================\n# get number of qubits\n# ====================\nn = 2\nqbits = [cirq.LineQubit(x) for x in range(n)]\n\n# =========================\n# state preparation circuit\n# =========================\nprep = cirq.Circuit()\nprep.append(cirq.H(qbits[x]) for x in range(n))\n\n# ==============\n# ansatz circuit\n# ==============\nansatz = cirq.Circuit()\ngate0 = cirq.Rz(rads=np.pi / 2)\ngate1 = cirq.XPowGate(exponent=cirq.Symbol(\"t\"))\nansatz.append([[gate0(qbits[x]),\n                gate1(qbits[x]),\n                gate0(qbits[x])] for x in range(2)],\n             strategy=cirq.InsertStrategy.EARLIEST)\n\n# ==========================\n# \"diagonality\" test circuit\n# ==========================\ndiag = cirq.Circuit()\ndiag.append([cirq.CNOT(qbits[1], qbits[0]),\n             cirq.measure(qbits[0], key=\"z\")])\n\n# ================\n# complete circuit\n# ================\ncirc = prep + ansatz + diag\n\n# =========================\n# sweep over the parameters\n# =========================\nreps = 10000\nsimulator = cirq.google.XmonSimulator()\nsweep = (cirq.Linspace(key=\"t\", start=0, stop=1, length=100))\nvals = simulator.run_sweep(circ, sweep, repetitions=reps)\n\n# print out the circuit\nprint(circ)\n```\n\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500Rz(0.5\u03c0)\u2500\u2500\u2500X^t\u2500\u2500\u2500Rz(0.5\u03c0)\u2500\u2500\u2500X\u2500\u2500\u2500M('z')\u2500\u2500\u2500\n                                          \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500Rz(0.5\u03c0)\u2500\u2500\u2500X^t\u2500\u2500\u2500Rz(0.5\u03c0)\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n<p style=\"text-align: justify;\"> \nThe complete circuit for the VQSD algorithm is shown above. (Note that this can be easily simplified to contain only one qubit, but here we stick to the general formulation of the algorithm.) We now plot the \"degree of diagonality\" vs. the parameter $t$, which ranges from zero to one, in the plot below.\n</p>\n\n\n```python\n# plot the degree of diagonality vs. the parameter t\ntvals = [x[0][1] for x in sweep.param_tuples()]\ncvals = [vals[i].histogram(key=\"z\")[0]/reps for i in range(len(vals))]\nplt.plot(tvals, cvals, \"-o\", linewidth=2)\n\n# plot style\nplt.grid(); plt.xlabel(\"t\");\nplt.ylabel(\"Degree of Diagonality\");\nplt.title(\"Diagonalizing a one-qubit state with VQSD\");\n```\n\n<p style=\"text-align: justify;\"> \nHere we can see that the state $\\rho' := U(t) \\rho U(t)^\\dagger$ is the most diagonal at the value of $t = 1/2$. A simple classical calculation using matrix arithmetic shows that $\\rho'$ is indeed diagonal in the computational basis when $t = 1/2$. \n</p>\n\n# <p style=\"text-align: center;\"> V. Comparisons and Conclusions </p> \n\n<p style=\"text-align: justify;\"> \nIn this final section we offer concluding remarks about Cirq. The purpose of this article was to introduce and analyze Cirq in a similar fashion to the paper <a href=\"#LaR2018\">[LaR2018]</a> comparing Forest (pyQuil), QISKit, ProjectQ, and the Quantum Developer Kit (Q#). We hope at this point the reader will be able to come to his/her own conclusions about Cirq's place in the quantum software community. (Recalling again that Cirq is still alpha software.)\n</p>\n\n<p style=\"text-align: justify;\"> \nIn general, we find that Cirq is already a fantastic tool for writing, manipulating, optimizing, compiling, and simulating quantum circuits. For beginners, the learning curve for Cirq is small as the language is written in Python and the syntax/organization of the code is very clean. (We do note that Cirq is written with function annotations in Python which in several cases can be rather verbose.) For experienced users, Cirq exposes details of the hardware to the programmer to maximize effective utilization of near-term processors.\n</p>\n\n<p style=\"text-align: justify;\"> \nWe expect the platform to keep improving as quantum hardware and other simulators are made available. We find the tools for working with variational quantum algorithms, including local simulators as opposed to cloud-based simulators, to be one of the best features of Cirq. (It should be noted that Forest has emphasis on this feature as well, but currently the functionality is smoother with Cirq in the author's opinion.) The integration with OpenFermion will likely lead to one of the best tools for quantum simulation algorithms, competing with IBM's <a href=\"https://qiskit.org/aqua\">QISKit Aqua library</a>. The simulators of Cirq are both good utilities (though not as high-performance as other simulators such as in <a href=\"https://qiskit.org/aer\">QISKit Aer</a> or ProjectQ) and will get better with the ongoing work on noise modeling. Additionally,  Finally, we expect the quantum channel and stabilizer code features of Cirq to be interesting and useful once they are released.\n</p>\n\n<p style=\"text-align: justify;\"> \nAs mentioned, probably the biggest missing feature of Cirq is the ability to simulate noisy quantum circuits, which Forest and QISKit do very well. (We expect this feature to be released in future versions.) As was seen in the quantum teleportation algorithm, the ability to implement classical operations in circuits, a feature emphasized by the Forest platform, is entirely missing in Cirq. Additionally, the documentation, tutorials, and library support of Cirq are much more sparse than Forest, QISKit, the QDK, and even ProjectQ. (Again, the alpha disclaimer is important here.) Currently, users of Cirq will not be able to connect to real quantum computers as they would with Forest, QISKit, or ProjectQ. Once Foxtail and/or Bristlecone are made available over the cloud, however, this will of course change.\n</p>\n\n<p style=\"text-align: justify;\"> \nThe addition of Cirq to the quantum software community provides excellent tools for working with circuits for near-term quantum computers, and will soon offer connectivity to some of the world's most advanced quantum computers. We hope that this article provides a fair introduction and overview of the platform. For readers who wish to explore Cirq further, we recommend the <a href=\"https://cirq.readthedocs.io/en/stable/api.html\">API Reference of the documentation.</a>\n</p>\n\n# <p style=\"text-align: center;\"> Acknowledgements </p> \n\nThe author thanks Doug Finke from Quantum Computing Report for many useful comments. We both thank Alan Ho from Google for reviewing the article and providing feedback.\n\n# <p style=\"text-align: center;\"> References </p> \n\n<a name=\"An2018\">[An2018]</a> E. R. Anschuetz, J. P. Olson, A. Aspuru-Guzik, and Y. Cao, \u201cVariational Quantum Factoring,\u201d arXiv:1808.08927 [quant-ph], Aug. 2018.\n\n<a name=\"Du2018\">[Du2018]</a> Dumitrescu, E. F. et al. Cloud Quantum Computing of an Atomic Nucleus. Physical Review Letters 120, (2018).\n\n<a name=\"Fa2014\">[Fa2014]</a>] E. Farhi, J. Goldstone, and S. Gutmann, \u201cA Quantum Approximate Optimization Algorithm,\u201d arXiv:1411.4028 [quant-ph], Nov. 2014.\n\n<a name=\"Fi2018\">[Fi2018]</a> M. Fingerhuth, T. Babej, and P. Wittek, \u201cOpen source software in quantum computing,\u201d PLOS ONE, vol. 13, no. 12, p. e0208561, Dec. 2018.\n\n<a name=\"Ho2018\">[Ho2018]</a> A. Ho and D. Bacon, \"Announcing Cirq: An Open Source Framework for NISQ Algorithms,\" <a href=\"https://ai.googleblog.com/2018/07/announcing-cirq-open-source-framework.html\">https://ai.googleblog.com/2018/07/announcing-cirq-open-source-framework.html</a>, Jul. 2018.\n\n<a name=\"Kh2018\">[Kh2018]</a> S. Khatri, R. LaRose, A. Poremba, L. Cincio, A. T. Sornborger, and P. J. Coles, \u201cQuantum-assisted quantum compiling,\u201d arXiv:1807.00800 [quant-ph], Jul. 2018.\n\n<a name=\"La2018\">[La2018]</a> R. LaRose, A. Tikku, \u00c9. O\u2019Neel-Judy, L. Cincio, and P. J. Coles, \u201cVariational Quantum State Diagonalization,\u201d arXiv:1810.10506 [quant-ph], Oct. 2018.\n\n<a name=\"LaR2018\">[LaR2018]</a> R. LaRose, \u201cOverview and Comparison of Gate Level Quantum Software Platforms,\u201d arXiv:1807.02500 [quant-ph], Jul. 2018.\n\n<a name=\"Ma2018\">[Ma2018]</a> I. L. Markov, A. Fatima, S. V. Isakov, and S. Boixo, \u201cQuantum Supremacy Is Both Closer and Farther than It Appears,\u201d arXiv:1807.10749 [quant-ph], Jul. 2018.\n\n<a name=\"Ne2017\">[Ne2017]</a> C. Neill et al., \u201cA blueprint for demonstrating quantum supremacy with superconducting qubits,\u201d Sep. 2017.\n\n<a name=\"Pe2014\">[Pe2014]</a> A. Peruzzo et al., \u201cA variational eigenvalue solver on a quantum processor,\u201d Nature Communications, vol. 5, no. 1, Dec. 2014.\n\n<a name=\"Wa2018\">[Wa2018]</a> Z. Wang, S. Hadfield, Z. Jiang, and E. G. Rieffel, \u201cThe Quantum Approximation Optimization Algorithm for MaxCut: A Fermionic View,\u201d Physical Review A, vol. 97, no. 2, Feb. 2018.\n", "meta": {"hexsha": "7a7869ee63b4f88324bc2b0e29164d5636305b1c", "size": 144289, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "article/notebook/cirq.ipynb", "max_stars_repo_name": "rmlarose/cirq-overview", "max_stars_repo_head_hexsha": "3e7ca4da0a8c0b7f662838ea50f449eb7a43784d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2019-01-11T17:58:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-12T06:54:22.000Z", "max_issues_repo_path": "article/notebook/cirq.ipynb", "max_issues_repo_name": "rmlarose/cirq-overview", "max_issues_repo_head_hexsha": "3e7ca4da0a8c0b7f662838ea50f449eb7a43784d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "article/notebook/cirq.ipynb", "max_forks_repo_name": "rmlarose/cirq-overview", "max_forks_repo_head_hexsha": "3e7ca4da0a8c0b7f662838ea50f449eb7a43784d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-02-08T18:12:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-25T15:19:14.000Z", "avg_line_length": 68.1251180359, "max_line_length": 21360, "alphanum_fraction": 0.722944923, "converted": true, "num_tokens": 18246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647596, "lm_q2_score": 0.061875988751047904, "lm_q1q2_score": 0.027806613594945247}}
{"text": "# Design\n###### Created by [Roberto Mora](https://github.com/romogo17)\n\nI will be structuring the `pgcv` datatypes and functions in different PostgreSQL schemas. This schemas will group the operations logically. The structure is somewhat base on OpenCV.\n\nThe schemas will be:\n1. `pgcv_core`\n1. `pgcv_io`\n1. `pgcv_filter`\n1. `pgcv_histogram`\n1. `pgcv_measure`\n1. `pgcv_bundle`\n1. `pgcv_draw` _(not yet implemented)_\n\n\n\n\n## `pgcv_core`\n\nThis schema contains the datatypes used in the `pgcv` extension. These datatypes are basically a representation of a N-dimension array in PostgreSQL. The idea is to map the `numpy.ndarray` to theese structures.\n\nThe `regionprops` data type is used to to store information about the properties of the segmented labeled image. This allows the user to query specific features of the object found in the image.\n\n```SQL\nCREATE TYPE pgcv_core.ndarray_int4 AS (\n  shape   int[],\n  data    int[]\n);\n\nCREATE TYPE pgcv_core.regionprops AS (\n  label         int,\n  area          int,\n  perimeter     float,\n  centroid      float[2],\n  solidity      float,\n  eccentricity  float,\n  convex_area   int,\n  circularity   float,\n  orientation   float,\n  bbox          int[4]\n);\n```\n\nOn the other hand, there are some functions that were incorporated into the core of the extension. For instance `hash_avg` calculates the average hash of an image\n\n```SQL\nCREATE OR REPLACE FUNCTION pgcv_core.hash_avg(image pgcv_core.ndarray_int4, size int DEFAULT 8)\n  RETURNS varchar\n```\n\n---\nThese functions can be called with the following code\n\n```SQL\n-- having an image in the database (size defaults to 8)\nSELECT pgcv_core.hash_avg(<image>, [<size>]);\n\n-- having an image in the database, \n-- and the size of the thumbnail (size defaulta to 200x200)\nSELECT pgcv_core.thumbnail(<image>, [<width>, [<height>]])\n\n-- having an image in the database, \n-- and the size of the thumbnail (size defaulta to 200x200)\nSELECT pgcv_core.thumbnail_uri_base64(<image>, [<width>, [<height>]])\n\n-- having an image in the database\nSELECT pgcv_core.uri_base64(<image>)\n```\n\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt \nfrom PIL import Image\n\nfilename = 'data/mdb147lx'\n\n'''\nWith the extension\n'''\n# img = np.array(image[\"data\"]).reshape(image[\"shape\"]).astype('uint8')\n# img = Image.fromarray(img)\n\n'''\nWith a file\n'''\nsize = 200, 200\nimg = Image.open(filename + '.png')\n\n'''\nCreate a thumbnail for the image\n'''\nimg.thumbnail(size)\nimg.save(filename + \".thumbnail.jpg\", \"JPEG\")\nplt.imshow(img, cmap = plt.get_cmap('gray'))\nprint(\"Thumbnail of size 200x200\")\n\n# '''\n# Convert the image to base64 data URI\n# '''\n# import base64\n# from io import BytesIO\n\n# buffered = BytesIO()\n# img.save(buffered, format=\"PNG\")\n# img_str = base64.b64encode(buffered.getvalue())\n\n# print('data:image/png;base64,' + img_str.decode(\"utf-8\"))\n\n```\n\n## `pgcv_io`\n\nThis schema contains the image input and output functions to the filesystem. Meaning that this functions read and write images into files.\n\n```SQL\nCREATE OR REPLACE FUNCTION pgcv_io.image_read(filename varchar)\n  RETURNS pgcv_core.ndarray_int4\n\nCREATE OR REPLACE FUNCTION pgcv_io.image_write(image pgcv_core.ndarray_int4, filename varchar)\n  RETURNS boolean\n```\n---\nThese functions can be tested with the following code\n\n```SQL\n-- having a filename that represents an image\nSELECT shape FROM pgcv_io.image_read('<filename>');\n\n-- having an image in the database and the output filename\nSELECT pgcv_io.image_write(<image>, '<filename>');\n```\n\n## `pgcv_filtering`\n\nThis schema contains the image filtering functions. One example of this functions is the `median_blur` which replaces each pixel by the median of a local window array given by a kernel size.\n\n```SQL\nCREATE OR REPLACE FUNCTION pgcv_filter.blur_median(image pgcv_core.ndarray_int4, kernel int DEFAULT 3)\n  RETURNS pgcv_core.ndarray_int4\n  \nCREATE OR REPLACE FUNCTION pgcv_filter.threshold_otsu(image pgcv_core.ndarray_int4)\n  RETURNS float\n```\n\nThe next function uses a method designed by **Johnny Villalobos** that has proven to be quite effective for mammogram segmentation. It is described follows:\n\nLet $t$ be the _threshold_ of an image calculated through the Otsu's method and $f$ the enhancement factor so that\n\n$$f = \\frac{t}{255 - t}$$\n\nthe value of each enhanced pixel $p'$ corresponds to\n\n\\begin{equation}\n\\begin{split}\np'  &= (255 - p (1 + f)) - f(255 - p (1 + f)) \\\\\n    &= (1 - f) (255 - p (1 + f))\n\\end{split}\n\\end{equation}\n\n\n```SQL\nCREATE OR REPLACE FUNCTION pgcv_filter.enhancement_otsu(image pgcv_core.ndarray_int4)\n  RETURNS pgcv_core.ndarray_int4\n  \nCREATE OR REPLACE FUNCTION pgcv_filter.binarize(image pgcv_core.ndarray_int4, thresh float)\n  RETURNS pgcv_core.ndarray_int4\n```\n---\nThese functions can be tested with the following code\n\n```SQL\n-- having an image in the database and odd kernel size (kernel size defaults to 5 if not specified)\nSELECT pgcv_filter.median_blur(<image>, [<kernel size>]);\n\n-- having an image in the database\nSELECT pgcv_filter.threshold_otsu(<image>);\n\n-- having an image in the database\nSELECT pgcv_filter.enhancement_otsu(<image>);\n\n-- having an image in the database and a threshold value\nSELECT pgcv_filter.binarize(<image>, <threshold>);\n```\n\n\n## `pgcv_histogram`\n\nThis schema contains the histogram computing functions. There are two main kinds of histograms in `pgcv`, both return an histogram and a set of bin features (either the center of the bins or the edges)\n\n```SQL\nCREATE OR REPLACE FUNCTION pgcv_histogram.hist_bin_edges(image pgcv_core.ndarray_int4, bins int DEFAULT 10, as_float boolean DEFAULT TRUE,\n  OUT hist numeric[], OUT bin_edges numeric[])\n  \nCREATE OR REPLACE FUNCTION pgcv_histogram.hist_bin_centers(image pgcv_core.ndarray_int4, bins int DEFAULT 10,\n  OUT hist numeric[], OUT bin_centers numeric[])\n```\n\n---\nThese functions can be tested with the following code\n\n```SQL\n-- having an image in the database, the number of bins (bins defaults to 10 if not specified) and whether the histogram has to be normalized or not\nSELECT * FROM pgcv_histogram.hist_bin_edges(<image>, [<bins>, [<as_float>]]);\n\n-- having an image in the database and the number of bins (bins defaults to 10 if not specified) \nSELECT * FROM pgcv_histogram.hist_bin_centers(<image>, [<bins>]);\n```\n\n\n## `pgcv_measure`\n\nThis schema contains the functions that perform measure computations on the image. In particular, `pgcv_measure` includes de region properties functions, which find objects on a binarize image\n\n```SQL\nCREATE OR REPLACE FUNCTION pgcv_measure.region_props_json(image pgcv_core.ndarray_int4)\n  RETURNS jsonb\n  \nCREATE OR REPLACE FUNCTION pgcv_measure.region_props(image pgcv_core.ndarray_int4)\n  RETURNS SETOF pgcv_core.regionprops\n```\n\n---\nThese functions can be tested with the following code\n\n```SQL\n-- having a binarized image in the database\nSELECT pgcv_measure.region_props_json(<image>);\n\n-- having a binarized image in the database\n-- this allows for the inclusion of WHERE conditions\n-- for filter the properties\nSELECT * FROM pgcv_measure.region_props(<image>);\n```\n\n## `pgcv_bundle`\n\nThe bundle schema provides access to common successive operations performed to an image. The purpose of this schema is to reduce the overhead produced by the comunication from the PostgreSQL server and Python.\n\n\nThis functions operate on unaltered images, meaning, images in the PostgreSQL server but not yet processed.\n\n```SQL\nCREATE OR REPLACE FUNCTION pgcv_bundle.mam_region_props(image pgcv_core.ndarray_int4, kernel int DEFAULT 5)\n  RETURNS SETOF pgcv_core.regionprops\n```\n\n---\n\nThese functions can be tested with the following code\n\n```SQL\n-- having an image in the database and odd kernel size (kernel size defaults to 5 if not specified)\nSELECT * FROM pgcv_bundle.mam_region_props(<image>, [<kernel size>]);\n```\n\n\n```python\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nimport pandas as pd\nfrom scipy import signal\nfrom skimage import measure, filters\nimport json\n\nimg = Image.open('./data/mdb155.pgm')\n#img = Image.open('/Users/ro/Desktop/prueba.png')\nimg = np.array(img).astype('uint8')\n\n\n\"\"\"\n1. Apply the mean filter\n\"\"\"\nimg = signal.medfilt(img, 5).astype('uint8')\n\n\"\"\"\n2. Enhance the image through the otsu enhancement\n\"\"\"\nthresh = filters.threshold_otsu(img)\nf = thresh / (255 - thresh)\nimg = ((1 - f) * (255 - img * (1 + f))).astype('uint8')\n\n\"\"\"\n3. Binarize the image\n\"\"\"\nimg = np.where(img < thresh, 0, 255)\n\n\"\"\"\n4. Calculate the regionprops\n\"\"\"\n# Get the regionprops\nlbl = measure.label(img)\nregions = measure.regionprops(lbl, coordinates='rc')\n\n# Initialize the DataFrame with the desired columns\ncolumns = [('label', int),\n           ('area', int),\n           ('perimeter', float),\n           ('centroid', object),\n           ('solidity', float),\n           ('eccentricity', float),\n           ('convex_area', int),\n           ('circularity', float),\n           ('orientation', float),\n           ('bbox', object)]\ndf = pd.DataFrame({k: pd.Series(dtype=t) for k, t in columns})\n\n# Fill the DataFrame\nfor i, reg in enumerate(regions):\n    df.loc[i] = [\n        reg.label,\n        reg.area,\n        reg.perimeter,\n        reg.centroid,\n        reg.solidity,\n        reg.eccentricity,\n        reg.convex_area,\n        4 * np.pi * reg.area / reg.perimeter ** 2 if reg.perimeter != 0 else np.inf,  # circularity\n        reg.orientation,\n        reg.bbox\n    ]\n    \n# result = df.to_json(orient='records', double_precision=4)\n# print(result)\n    \ndisplay(df)\n\n# plt.figure(figsize=(11, 11))\n# plt.imshow(img, cmap = plt.get_cmap('gray'))\n\n```\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>label</th>\n      <th>area</th>\n      <th>perimeter</th>\n      <th>centroid</th>\n      <th>solidity</th>\n      <th>eccentricity</th>\n      <th>convex_area</th>\n      <th>circularity</th>\n      <th>orientation</th>\n      <th>bbox</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>593891</td>\n      <td>6379.937300</td>\n      <td>(444.15259197394806, 454.06933932320914)</td>\n      <td>0.566379</td>\n      <td>0.519865</td>\n      <td>1048576</td>\n      <td>0.183351</td>\n      <td>-1.535771</td>\n      <td>(0, 0, 1024, 1024)</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2</td>\n      <td>16264</td>\n      <td>709.646753</td>\n      <td>(112.46593703885883, 793.8274717166748)</td>\n      <td>0.922937</td>\n      <td>0.913972</td>\n      <td>17622</td>\n      <td>0.405838</td>\n      <td>-0.294397</td>\n      <td>(28, 710, 280, 837)</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>3</td>\n      <td>49</td>\n      <td>31.727922</td>\n      <td>(286.9387755102041, 833.1020408163265)</td>\n      <td>0.720588</td>\n      <td>0.773579</td>\n      <td>68</td>\n      <td>0.611678</td>\n      <td>-0.320758</td>\n      <td>(283, 829, 295, 837)</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>4</td>\n      <td>12</td>\n      <td>10.035534</td>\n      <td>(299.25, 833.4166666666666)</td>\n      <td>0.923077</td>\n      <td>0.855502</td>\n      <td>13</td>\n      <td>1.497305</td>\n      <td>0.685730</td>\n      <td>(297, 832, 302, 836)</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>5</td>\n      <td>10</td>\n      <td>8.828427</td>\n      <td>(420.2, 427.5)</td>\n      <td>1.000000</td>\n      <td>0.683130</td>\n      <td>10</td>\n      <td>1.612290</td>\n      <td>-1.570796</td>\n      <td>(419, 426, 422, 430)</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>6</td>\n      <td>229</td>\n      <td>94.911688</td>\n      <td>(427.4017467248908, 446.3930131004367)</td>\n      <td>0.620596</td>\n      <td>0.796357</td>\n      <td>369</td>\n      <td>0.319452</td>\n      <td>1.566909</td>\n      <td>(421, 431, 440, 462)</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>7</td>\n      <td>29</td>\n      <td>17.071068</td>\n      <td>(473.6551724137931, 481.2758620689655)</td>\n      <td>0.966667</td>\n      <td>0.516245</td>\n      <td>30</td>\n      <td>1.250508</td>\n      <td>-0.618715</td>\n      <td>(471, 479, 477, 485)</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>8</td>\n      <td>101</td>\n      <td>50.870058</td>\n      <td>(478.5742574257426, 504.05940594059405)</td>\n      <td>0.801587</td>\n      <td>0.961610</td>\n      <td>126</td>\n      <td>0.490464</td>\n      <td>-1.322596</td>\n      <td>(475, 494, 484, 516)</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>9</td>\n      <td>8</td>\n      <td>8.414214</td>\n      <td>(490.5, 461.125)</td>\n      <td>0.888889</td>\n      <td>0.937309</td>\n      <td>9</td>\n      <td>1.419949</td>\n      <td>-1.456334</td>\n      <td>(490, 459, 492, 464)</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>10</td>\n      <td>3853</td>\n      <td>396.818326</td>\n      <td>(543.431871269141, 440.0153127433169)</td>\n      <td>0.724520</td>\n      <td>0.716600</td>\n      <td>5318</td>\n      <td>0.307486</td>\n      <td>1.427281</td>\n      <td>(503, 385, 583, 489)</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>11</td>\n      <td>10</td>\n      <td>8.828427</td>\n      <td>(544.0, 580.8)</td>\n      <td>1.000000</td>\n      <td>0.612372</td>\n      <td>10</td>\n      <td>1.612290</td>\n      <td>-1.570796</td>\n      <td>(543, 579, 546, 583)</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>12</td>\n      <td>78</td>\n      <td>35.970563</td>\n      <td>(570.3846153846154, 385.7564102564103)</td>\n      <td>0.876404</td>\n      <td>0.888431</td>\n      <td>89</td>\n      <td>0.757548</td>\n      <td>-0.519845</td>\n      <td>(564, 382, 577, 392)</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>13</td>\n      <td>1</td>\n      <td>0.000000</td>\n      <td>(564.0, 392.0)</td>\n      <td>1.000000</td>\n      <td>0.000000</td>\n      <td>1</td>\n      <td>inf</td>\n      <td>0.785398</td>\n      <td>(564, 392, 565, 393)</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>14</td>\n      <td>42</td>\n      <td>23.071068</td>\n      <td>(577.1666666666666, 400.6666666666667)</td>\n      <td>0.954545</td>\n      <td>0.867421</td>\n      <td>44</td>\n      <td>0.991571</td>\n      <td>1.520056</td>\n      <td>(575, 396, 580, 406)</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>15</td>\n      <td>19</td>\n      <td>13.656854</td>\n      <td>(578.6842105263158, 379.57894736842104)</td>\n      <td>1.000000</td>\n      <td>0.776662</td>\n      <td>19</td>\n      <td>1.280154</td>\n      <td>1.276256</td>\n      <td>(577, 377, 581, 383)</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>16</td>\n      <td>22</td>\n      <td>16.692388</td>\n      <td>(637.8181818181819, 391.1363636363636)</td>\n      <td>0.956522</td>\n      <td>0.890439</td>\n      <td>23</td>\n      <td>0.992192</td>\n      <td>0.883639</td>\n      <td>(635, 388, 641, 395)</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>17</td>\n      <td>74</td>\n      <td>35.213203</td>\n      <td>(657.6351351351351, 449.31081081081084)</td>\n      <td>0.860465</td>\n      <td>0.842383</td>\n      <td>86</td>\n      <td>0.749947</td>\n      <td>-1.059964</td>\n      <td>(653, 443, 664, 455)</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>18</td>\n      <td>24</td>\n      <td>17.071068</td>\n      <td>(661.7916666666666, 466.875)</td>\n      <td>0.960000</td>\n      <td>0.865032</td>\n      <td>25</td>\n      <td>1.034903</td>\n      <td>1.017494</td>\n      <td>(660, 464, 665, 471)</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>19</td>\n      <td>11</td>\n      <td>8.621320</td>\n      <td>(667.5454545454545, 452.0)</td>\n      <td>0.846154</td>\n      <td>0.800815</td>\n      <td>13</td>\n      <td>1.859752</td>\n      <td>-0.000000</td>\n      <td>(665, 451, 670, 454)</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>20</td>\n      <td>118</td>\n      <td>65.455844</td>\n      <td>(669.8389830508474, 508.46610169491527)</td>\n      <td>0.715152</td>\n      <td>0.983523</td>\n      <td>165</td>\n      <td>0.346095</td>\n      <td>1.327167</td>\n      <td>(666, 495, 677, 523)</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>21</td>\n      <td>4</td>\n      <td>3.207107</td>\n      <td>(674.25, 450.75)</td>\n      <td>0.800000</td>\n      <td>0.912871</td>\n      <td>5</td>\n      <td>4.887008</td>\n      <td>0.321751</td>\n      <td>(673, 450, 676, 452)</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>22</td>\n      <td>17</td>\n      <td>13.414214</td>\n      <td>(676.6470588235294, 463.94117647058823)</td>\n      <td>1.000000</td>\n      <td>0.875727</td>\n      <td>17</td>\n      <td>1.187212</td>\n      <td>-0.075186</td>\n      <td>(674, 463, 680, 466)</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>23</td>\n      <td>8</td>\n      <td>7.414214</td>\n      <td>(687.25, 449.375)</td>\n      <td>0.800000</td>\n      <td>0.921119</td>\n      <td>10</td>\n      <td>1.828815</td>\n      <td>0.557941</td>\n      <td>(686, 448, 690, 452)</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>24</td>\n      <td>7</td>\n      <td>6.207107</td>\n      <td>(687.1428571428571, 493.0)</td>\n      <td>0.875000</td>\n      <td>0.801784</td>\n      <td>8</td>\n      <td>2.283124</td>\n      <td>-1.570796</td>\n      <td>(686, 492, 689, 496)</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>25</td>\n      <td>9</td>\n      <td>8.000000</td>\n      <td>(722.0, 590.0)</td>\n      <td>1.000000</td>\n      <td>0.000000</td>\n      <td>9</td>\n      <td>1.767146</td>\n      <td>0.785398</td>\n      <td>(721, 589, 724, 592)</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>26</td>\n      <td>47</td>\n      <td>25.313708</td>\n      <td>(725.6595744680851, 301.8723404255319)</td>\n      <td>0.903846</td>\n      <td>0.731657</td>\n      <td>52</td>\n      <td>0.921714</td>\n      <td>0.379708</td>\n      <td>(722, 299, 731, 306)</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>27</td>\n      <td>1397</td>\n      <td>313.255880</td>\n      <td>(770.0178954903364, 322.1660701503221)</td>\n      <td>0.526772</td>\n      <td>0.926261</td>\n      <td>2652</td>\n      <td>0.178899</td>\n      <td>-0.125265</td>\n      <td>(724, 303, 803, 345)</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>28</td>\n      <td>346</td>\n      <td>91.254834</td>\n      <td>(740.693641618497, 495.2369942196532)</td>\n      <td>0.814118</td>\n      <td>0.914069</td>\n      <td>425</td>\n      <td>0.522125</td>\n      <td>0.436476</td>\n      <td>(725, 483, 755, 506)</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>29</td>\n      <td>20</td>\n      <td>14.242641</td>\n      <td>(734.45, 462.75)</td>\n      <td>0.952381</td>\n      <td>0.714569</td>\n      <td>21</td>\n      <td>1.238964</td>\n      <td>1.356578</td>\n      <td>(733, 460, 737, 466)</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>30</td>\n      <td>91</td>\n      <td>36.142136</td>\n      <td>(746.021978021978, 461.9120879120879)</td>\n      <td>0.947917</td>\n      <td>0.731242</td>\n      <td>96</td>\n      <td>0.875434</td>\n      <td>1.062351</td>\n      <td>(742, 456, 752, 469)</td>\n    </tr>\n    <tr>\n      <th>30</th>\n      <td>31</td>\n      <td>4</td>\n      <td>4.621320</td>\n      <td>(743.25, 445.0)</td>\n      <td>1.000000</td>\n      <td>0.790569</td>\n      <td>4</td>\n      <td>2.353627</td>\n      <td>-1.570796</td>\n      <td>(743, 444, 745, 447)</td>\n    </tr>\n    <tr>\n      <th>31</th>\n      <td>32</td>\n      <td>16</td>\n      <td>12.242641</td>\n      <td>(750.1875, 426.8125)</td>\n      <td>1.000000</td>\n      <td>0.664230</td>\n      <td>16</td>\n      <td>1.341466</td>\n      <td>0.301144</td>\n      <td>(748, 425, 753, 429)</td>\n    </tr>\n    <tr>\n      <th>32</th>\n      <td>33</td>\n      <td>233</td>\n      <td>71.012193</td>\n      <td>(760.0085836909872, 519.8068669527897)</td>\n      <td>0.811847</td>\n      <td>0.500166</td>\n      <td>287</td>\n      <td>0.580631</td>\n      <td>0.329675</td>\n      <td>(751, 511, 773, 532)</td>\n    </tr>\n    <tr>\n      <th>33</th>\n      <td>34</td>\n      <td>27</td>\n      <td>17.071068</td>\n      <td>(758.3333333333334, 461.6666666666667)</td>\n      <td>0.964286</td>\n      <td>0.735647</td>\n      <td>28</td>\n      <td>1.164266</td>\n      <td>0.785398</td>\n      <td>(756, 459, 762, 465)</td>\n    </tr>\n    <tr>\n      <th>34</th>\n      <td>35</td>\n      <td>32</td>\n      <td>20.485281</td>\n      <td>(768.0625, 507.78125)</td>\n      <td>0.888889</td>\n      <td>0.870765</td>\n      <td>36</td>\n      <td>0.958244</td>\n      <td>0.457543</td>\n      <td>(764, 505, 773, 511)</td>\n    </tr>\n    <tr>\n      <th>35</th>\n      <td>36</td>\n      <td>19</td>\n      <td>15.035534</td>\n      <td>(768.3157894736842, 536.5263157894736)</td>\n      <td>0.950000</td>\n      <td>0.851822</td>\n      <td>20</td>\n      <td>1.056150</td>\n      <td>1.469859</td>\n      <td>(767, 533, 771, 540)</td>\n    </tr>\n    <tr>\n      <th>36</th>\n      <td>37</td>\n      <td>11</td>\n      <td>9.656854</td>\n      <td>(773.8181818181819, 366.8181818181818)</td>\n      <td>1.000000</td>\n      <td>0.269680</td>\n      <td>11</td>\n      <td>1.482283</td>\n      <td>0.785398</td>\n      <td>(772, 365, 776, 369)</td>\n    </tr>\n    <tr>\n      <th>37</th>\n      <td>38</td>\n      <td>46</td>\n      <td>22.727922</td>\n      <td>(785.5217391304348, 284.5869565217391)</td>\n      <td>0.958333</td>\n      <td>0.640396</td>\n      <td>48</td>\n      <td>1.119047</td>\n      <td>0.884309</td>\n      <td>(782, 281, 790, 289)</td>\n    </tr>\n    <tr>\n      <th>38</th>\n      <td>39</td>\n      <td>71</td>\n      <td>34.727922</td>\n      <td>(797.0704225352113, 387.8732394366197)</td>\n      <td>0.898734</td>\n      <td>0.897346</td>\n      <td>79</td>\n      <td>0.739794</td>\n      <td>1.514134</td>\n      <td>(794, 382, 801, 396)</td>\n    </tr>\n    <tr>\n      <th>39</th>\n      <td>40</td>\n      <td>7</td>\n      <td>7.207107</td>\n      <td>(804.7142857142857, 309.57142857142856)</td>\n      <td>1.000000</td>\n      <td>0.888666</td>\n      <td>7</td>\n      <td>1.693503</td>\n      <td>0.145728</td>\n      <td>(803, 309, 807, 311)</td>\n    </tr>\n    <tr>\n      <th>40</th>\n      <td>41</td>\n      <td>74</td>\n      <td>44.349242</td>\n      <td>(810.9864864864865, 461.0945945945946)</td>\n      <td>0.755102</td>\n      <td>0.946313</td>\n      <td>98</td>\n      <td>0.472791</td>\n      <td>1.064276</td>\n      <td>(805, 453, 816, 470)</td>\n    </tr>\n    <tr>\n      <th>41</th>\n      <td>42</td>\n      <td>3</td>\n      <td>1.000000</td>\n      <td>(816.0, 344.0)</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>3</td>\n      <td>37.699112</td>\n      <td>-0.000000</td>\n      <td>(815, 344, 818, 345)</td>\n    </tr>\n    <tr>\n      <th>42</th>\n      <td>43</td>\n      <td>271</td>\n      <td>91.976659</td>\n      <td>(838.6752767527676, 441.6088560885609)</td>\n      <td>0.687817</td>\n      <td>0.798153</td>\n      <td>394</td>\n      <td>0.402554</td>\n      <td>-0.462306</td>\n      <td>(828, 427, 855, 452)</td>\n    </tr>\n    <tr>\n      <th>43</th>\n      <td>44</td>\n      <td>113</td>\n      <td>52.526912</td>\n      <td>(839.7787610619469, 481.01769911504425)</td>\n      <td>0.824818</td>\n      <td>0.934978</td>\n      <td>137</td>\n      <td>0.514665</td>\n      <td>1.123224</td>\n      <td>(833, 473, 847, 493)</td>\n    </tr>\n    <tr>\n      <th>44</th>\n      <td>45</td>\n      <td>58</td>\n      <td>31.556349</td>\n      <td>(839.2758620689655, 357.8965517241379)</td>\n      <td>0.892308</td>\n      <td>0.776567</td>\n      <td>65</td>\n      <td>0.731921</td>\n      <td>-1.333403</td>\n      <td>(836, 353, 844, 364)</td>\n    </tr>\n    <tr>\n      <th>45</th>\n      <td>46</td>\n      <td>88</td>\n      <td>35.556349</td>\n      <td>(845.8977272727273, 342.3181818181818)</td>\n      <td>0.946237</td>\n      <td>0.775866</td>\n      <td>93</td>\n      <td>0.874698</td>\n      <td>0.084746</td>\n      <td>(840, 339, 853, 348)</td>\n    </tr>\n    <tr>\n      <th>46</th>\n      <td>47</td>\n      <td>68</td>\n      <td>32.520815</td>\n      <td>(853.9117647058823, 379.75)</td>\n      <td>0.944444</td>\n      <td>0.844541</td>\n      <td>72</td>\n      <td>0.807971</td>\n      <td>0.265653</td>\n      <td>(848, 377, 861, 384)</td>\n    </tr>\n    <tr>\n      <th>47</th>\n      <td>48</td>\n      <td>2</td>\n      <td>0.000000</td>\n      <td>(850.5, 375.0)</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>2</td>\n      <td>inf</td>\n      <td>-0.000000</td>\n      <td>(850, 375, 852, 376)</td>\n    </tr>\n    <tr>\n      <th>48</th>\n      <td>49</td>\n      <td>57</td>\n      <td>32.384776</td>\n      <td>(859.8070175438596, 401.17543859649123)</td>\n      <td>0.791667</td>\n      <td>0.877876</td>\n      <td>72</td>\n      <td>0.682972</td>\n      <td>0.318750</td>\n      <td>(854, 397, 866, 405)</td>\n    </tr>\n    <tr>\n      <th>49</th>\n      <td>50</td>\n      <td>70</td>\n      <td>30.970563</td>\n      <td>(867.7571428571429, 436.14285714285717)</td>\n      <td>0.945946</td>\n      <td>0.802344</td>\n      <td>74</td>\n      <td>0.917085</td>\n      <td>1.092008</td>\n      <td>(863, 431, 873, 442)</td>\n    </tr>\n    <tr>\n      <th>50</th>\n      <td>51</td>\n      <td>19</td>\n      <td>13.899495</td>\n      <td>(868.7368421052631, 457.6842105263158)</td>\n      <td>1.000000</td>\n      <td>0.660753</td>\n      <td>19</td>\n      <td>1.235849</td>\n      <td>1.204857</td>\n      <td>(867, 455, 872, 461)</td>\n    </tr>\n    <tr>\n      <th>51</th>\n      <td>52</td>\n      <td>14</td>\n      <td>11.656854</td>\n      <td>(872.0714285714286, 422.2142857142857)</td>\n      <td>0.933333</td>\n      <td>0.668793</td>\n      <td>15</td>\n      <td>1.294718</td>\n      <td>0.536914</td>\n      <td>(870, 421, 875, 425)</td>\n    </tr>\n    <tr>\n      <th>52</th>\n      <td>53</td>\n      <td>170</td>\n      <td>60.183766</td>\n      <td>(899.3705882352941, 433.61176470588236)</td>\n      <td>0.801887</td>\n      <td>0.758786</td>\n      <td>212</td>\n      <td>0.589794</td>\n      <td>0.721005</td>\n      <td>(891, 427, 910, 445)</td>\n    </tr>\n    <tr>\n      <th>53</th>\n      <td>54</td>\n      <td>14</td>\n      <td>10.828427</td>\n      <td>(940.5, 429.5)</td>\n      <td>1.000000</td>\n      <td>0.670820</td>\n      <td>14</td>\n      <td>1.500400</td>\n      <td>0.785398</td>\n      <td>(939, 428, 943, 432)</td>\n    </tr>\n    <tr>\n      <th>54</th>\n      <td>55</td>\n      <td>103</td>\n      <td>55.455844</td>\n      <td>(954.4563106796116, 411.22330097087377)</td>\n      <td>0.668831</td>\n      <td>0.956596</td>\n      <td>154</td>\n      <td>0.420874</td>\n      <td>-1.412918</td>\n      <td>(950, 401, 960, 422)</td>\n    </tr>\n    <tr>\n      <th>55</th>\n      <td>56</td>\n      <td>30</td>\n      <td>19.313708</td>\n      <td>(974.9666666666667, 635.4)</td>\n      <td>0.967742</td>\n      <td>0.866951</td>\n      <td>31</td>\n      <td>1.010648</td>\n      <td>0.767837</td>\n      <td>(972, 632, 979, 639)</td>\n    </tr>\n    <tr>\n      <th>56</th>\n      <td>57</td>\n      <td>96</td>\n      <td>38.420310</td>\n      <td>(987.84375, 411.5208333333333)</td>\n      <td>0.888889</td>\n      <td>0.743860</td>\n      <td>108</td>\n      <td>0.817258</td>\n      <td>-1.011551</td>\n      <td>(983, 404, 995, 418)</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "75f80e49bafb128ece78a9afaa43d1229fcdc1a3", "size": 89242, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/02-Design.ipynb", "max_stars_repo_name": "romogo17/pgcv", "max_stars_repo_head_hexsha": "563a89aac9a5d3633919d2d64b30ab6b4119b62f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/02-Design.ipynb", "max_issues_repo_name": "romogo17/pgcv", "max_issues_repo_head_hexsha": "563a89aac9a5d3633919d2d64b30ab6b4119b62f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/02-Design.ipynb", "max_forks_repo_name": "romogo17/pgcv", "max_forks_repo_head_hexsha": "563a89aac9a5d3633919d2d64b30ab6b4119b62f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.4346570397, "max_line_length": 36244, "alphanum_fraction": 0.6314179422, "converted": true, "num_tokens": 10095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356683938849797, "lm_q2_score": 0.06853749636151124, "lm_q1q2_score": 0.02765946078621577}}
{"text": "```julia\nimport Pkg; Pkg.activate(@__DIR__); Pkg.instantiate()\n```\n\n    \u001b[32m\u001b[1m  Activating\u001b[22m\u001b[39m environment at `/mnt/064AC6424AC62E6D/git_workspace/16715/hopper-sim/scripts/Project.toml`\n    \u001b[32m\u001b[1m    Updating\u001b[22m\u001b[39m registry at `~/.julia/registries/General`\n    \u001b[32m\u001b[1m   Installed\u001b[22m\u001b[39m METIS_jll \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 v5.1.1+0\n    \u001b[32m\u001b[1m   Installed\u001b[22m\u001b[39m Ipopt \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 v0.9.0\n    \u001b[32m\u001b[1m   Installed\u001b[22m\u001b[39m MutableArithmetics \u2500 v0.3.1\n    \u001b[32m\u001b[1m   Installed\u001b[22m\u001b[39m ASL_jll \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 v0.1.3+0\n    \u001b[32m\u001b[1m   Installed\u001b[22m\u001b[39m BenchmarkTools \u2500\u2500\u2500\u2500\u2500 v1.2.2\n    \u001b[32m\u001b[1m   Installed\u001b[22m\u001b[39m MathOptInterface \u2500\u2500\u2500 v0.10.6\n    \u001b[32m\u001b[1m    Updating\u001b[22m\u001b[39m `/mnt/064AC6424AC62E6D/git_workspace/16715/hopper-sim/scripts/Project.toml`\n     \u001b[90m [6e4b80f9] \u001b[39m\u001b[92m+ BenchmarkTools v1.2.2\u001b[39m\n     \u001b[90m [6a86dc24] \u001b[39m\u001b[92m+ FiniteDiff v2.8.1\u001b[39m\n     \u001b[90m [b6b21f68] \u001b[39m\u001b[92m+ Ipopt v0.9.0\u001b[39m\n     \u001b[90m [b8f27783] \u001b[39m\u001b[92m+ MathOptInterface v0.10.6\u001b[39m\n    \u001b[32m\u001b[1m    Updating\u001b[22m\u001b[39m `/mnt/064AC6424AC62E6D/git_workspace/16715/hopper-sim/scripts/Manifest.toml`\n     \u001b[90m [4fba245c] \u001b[39m\u001b[92m+ ArrayInterface v3.2.1\u001b[39m\n     \u001b[90m [6e4b80f9] \u001b[39m\u001b[92m+ BenchmarkTools v1.2.2\u001b[39m\n     \u001b[90m [b99e7846] \u001b[39m\u001b[92m+ BinaryProvider v0.5.10\u001b[39m\n     \u001b[90m [523fee87] \u001b[39m\u001b[92m+ CodecBzip2 v0.7.2\u001b[39m\n     \u001b[90m [944b1d66] \u001b[39m\u001b[92m+ CodecZlib v0.7.0\u001b[39m\n     \u001b[90m [34da2185] \u001b[39m\u001b[92m+ Compat v3.40.0\u001b[39m\n     \u001b[90m [6a86dc24] \u001b[39m\u001b[92m+ FiniteDiff v2.8.1\u001b[39m\n     \u001b[90m [615f187c] \u001b[39m\u001b[92m+ IfElse v0.1.1\u001b[39m\n     \u001b[90m [b6b21f68] \u001b[39m\u001b[92m+ Ipopt v0.9.0\u001b[39m\n     \u001b[90m [692b3bcd] \u001b[39m\u001b[92m+ JLLWrappers v1.3.0\u001b[39m\n     \u001b[90m [682c06a0] \u001b[39m\u001b[92m+ JSON v0.21.2\u001b[39m\n     \u001b[90m [b8f27783] \u001b[39m\u001b[92m+ MathOptInterface v0.10.6\u001b[39m\n     \u001b[90m [d8a4904e] \u001b[39m\u001b[92m+ MutableArithmetics v0.3.1\u001b[39m\n     \u001b[90m [bac558e1] \u001b[39m\u001b[92m+ OrderedCollections v1.4.1\u001b[39m\n     \u001b[90m [69de0a69] \u001b[39m\u001b[92m+ Parsers v2.1.2\u001b[39m\n     \u001b[90m [21216c6a] \u001b[39m\u001b[92m+ Preferences v1.2.2\u001b[39m\n     \u001b[90m [ae029012] \u001b[39m\u001b[92m+ Requires v1.1.3\u001b[39m\n     \u001b[90m [aedffcd0] \u001b[39m\u001b[92m+ Static v0.4.0\u001b[39m\n     \u001b[90m [90137ffa] \u001b[39m\u001b[92m+ StaticArrays v1.2.13\u001b[39m\n     \u001b[90m [3bb67fe8] \u001b[39m\u001b[92m+ TranscodingStreams v0.9.6\u001b[39m\n     \u001b[90m [ae81ac8f] \u001b[39m\u001b[92m+ ASL_jll v0.1.3+0\u001b[39m\n     \u001b[90m [6e34b625] \u001b[39m\u001b[92m+ Bzip2_jll v1.0.8+0\u001b[39m\n     \u001b[90m [9cc047cb] \u001b[39m\u001b[92m+ Ipopt_jll v3.13.4+2\u001b[39m\n     \u001b[90m [d00139f3] \u001b[39m\u001b[92m+ METIS_jll v5.1.1+0\u001b[39m\n     \u001b[90m [d7ed1dd3] \u001b[39m\u001b[92m+ MUMPS_seq_jll v5.2.1+4\u001b[39m\n     \u001b[90m [656ef2d0] \u001b[39m\u001b[92m+ OpenBLAS32_jll v0.3.12+1\u001b[39m\n     \u001b[90m [0dad84c5] \u001b[39m\u001b[92m+ ArgTools\u001b[39m\n     \u001b[90m [56f22d72] \u001b[39m\u001b[92m+ Artifacts\u001b[39m\n     \u001b[90m [2a0f44e3] \u001b[39m\u001b[92m+ Base64\u001b[39m\n     \u001b[90m [ade2ca70] \u001b[39m\u001b[92m+ Dates\u001b[39m\n     \u001b[90m [8bb1440f] \u001b[39m\u001b[92m+ DelimitedFiles\u001b[39m\n     \u001b[90m [8ba89e20] \u001b[39m\u001b[92m+ Distributed\u001b[39m\n     \u001b[90m [f43a241f] \u001b[39m\u001b[92m+ Downloads\u001b[39m\n     \u001b[90m [b77e0a4c] \u001b[39m\u001b[92m+ InteractiveUtils\u001b[39m\n     \u001b[90m [b27032c2] \u001b[39m\u001b[92m+ LibCURL\u001b[39m\n     \u001b[90m [76f85450] \u001b[39m\u001b[92m+ LibGit2\u001b[39m\n     \u001b[90m [8f399da3] \u001b[39m\u001b[92m+ Libdl\u001b[39m\n     \u001b[90m [37e2e46d] \u001b[39m\u001b[92m+ LinearAlgebra\u001b[39m\n     \u001b[90m [56ddb016] \u001b[39m\u001b[92m+ Logging\u001b[39m\n     \u001b[90m [d6f4376e] \u001b[39m\u001b[92m+ Markdown\u001b[39m\n     \u001b[90m [a63ad114] \u001b[39m\u001b[92m+ Mmap\u001b[39m\n     \u001b[90m [ca575930] \u001b[39m\u001b[92m+ NetworkOptions\u001b[39m\n     \u001b[90m [44cfe95a] \u001b[39m\u001b[92m+ Pkg\u001b[39m\n     \u001b[90m [de0858da] \u001b[39m\u001b[92m+ Printf\u001b[39m\n     \u001b[90m [9abbd945] \u001b[39m\u001b[92m+ Profile\u001b[39m\n     \u001b[90m [3fa0cd96] \u001b[39m\u001b[92m+ REPL\u001b[39m\n     \u001b[90m [9a3f8284] \u001b[39m\u001b[92m+ Random\u001b[39m\n     \u001b[90m [ea8e919c] \u001b[39m\u001b[92m+ SHA\u001b[39m\n     \u001b[90m [9e88b42a] \u001b[39m\u001b[92m+ Serialization\u001b[39m\n     \u001b[90m [1a1011a3] \u001b[39m\u001b[92m+ SharedArrays\u001b[39m\n     \u001b[90m [6462fe0b] \u001b[39m\u001b[92m+ Sockets\u001b[39m\n     \u001b[90m [2f01184e] \u001b[39m\u001b[92m+ SparseArrays\u001b[39m\n     \u001b[90m [10745b16] \u001b[39m\u001b[92m+ Statistics\u001b[39m\n     \u001b[90m [fa267f1f] \u001b[39m\u001b[92m+ TOML\u001b[39m\n     \u001b[90m [a4e569a6] \u001b[39m\u001b[92m+ Tar\u001b[39m\n     \u001b[90m [8dfed614] \u001b[39m\u001b[92m+ Test\u001b[39m\n     \u001b[90m [cf7118a7] \u001b[39m\u001b[92m+ UUIDs\u001b[39m\n     \u001b[90m [4ec0a83e] \u001b[39m\u001b[92m+ Unicode\u001b[39m\n     \u001b[90m [e66e0078] \u001b[39m\u001b[92m+ CompilerSupportLibraries_jll\u001b[39m\n     \u001b[90m [deac9b47] \u001b[39m\u001b[92m+ LibCURL_jll\u001b[39m\n     \u001b[90m [29816b5a] \u001b[39m\u001b[92m+ LibSSH2_jll\u001b[39m\n     \u001b[90m [c8ffd9c3] \u001b[39m\u001b[92m+ MbedTLS_jll\u001b[39m\n     \u001b[90m [14a3606d] \u001b[39m\u001b[92m+ MozillaCACerts_jll\u001b[39m\n     \u001b[90m [83775a58] \u001b[39m\u001b[92m+ Zlib_jll\u001b[39m\n     \u001b[90m [8e850ede] \u001b[39m\u001b[92m+ nghttp2_jll\u001b[39m\n     \u001b[90m [3f19e933] \u001b[39m\u001b[92m+ p7zip_jll\u001b[39m\n    \u001b[32m\u001b[1m    Building\u001b[22m\u001b[39m Ipopt \u2192 `~/.julia/scratchspaces/44cfe95a-1eb2-52ea-b672-e2afdf69b78f/473e8c4b46cc3e53449efe49ed38f1241453eafc/build.log`\n\n\n\n```julia\nusing RigidBodyDynamics\nusing LinearAlgebra\nusing MeshCatMechanisms\nusing MeshCat\nusing StaticArrays\nusing SparseArrays\nusing ForwardDiff\nconst FD = ForwardDiff\n```\n\n\n<div style=\"padding: 1em; background-color: #f8d6da; border: 1px solid #f5c6cb; font-weight: bold;\">\n<p>The WebIO Jupyter extension was not detected. See the\n<a href=\"https://juliagizmos.github.io/WebIO.jl/latest/providers/ijulia/\" target=\"_blank\">\n    WebIO Jupyter integration documentation\n</a>\nfor more information.\n</div>\n\n\n\n\n\n\n    ForwardDiff\n\n\n\n\n```julia\n# link lengths\nconst l0 = [0.1; 0; 0]\nconst l1 = [0.3; 0; 0]\nconst l2 = [0.3; 0; 0]\nconst l3 = 0.1\nconst l4 = 0.2\nconst l5 = 0.0205\nconst lc = [l3; 0; 0]\nconst lee = [l3 + l4; 0; l5] # sqrt((l3 + l4)^2 + l5^2)\n\n# CoM locations\nconst l_cb = [0; 0.004; 0]\nconst l_c0 = [0.0125108364230515; 0.00117191218927888; 0]\nconst l_c1 = [0.149359714867044; 0; 0]\nconst l_c2 = [0.0469412900551914; 0; 0]\nconst l_c3 = [0.113177000131857; 0; -0.015332867880069]\n\n# link masses\nconst mb = 7  # kg\nconst m0 = 0.24644240965487\nconst m1 = 0.0707939028219395\nconst m2 = 0.276735496985514\nconst m3 = 0.130824780046739\n# const m = Diagonal([m0, m1, m2, m3])\n    \n# gravity, obviously\nconst g = 9.807\n\n# mass moment of inertia in axis of rotation\nconst Ib = Array([0.0024241 5.252E-06 2.0733E-19; \n                  5.252E-06 0.0044176 -3.1153E-19; \n                  2.0733E-19 -3.1153E-19 0.0022481])\n\nconst I0 = Array([3.83120149546952E-05 1.46925714738609E-05 -8.60106401672571E-06;\n                  1.46925714738609E-05 0.000172067745507247 1.0427260925207E-06;\n                  -8.60106401672571E-06 1.0427260925207E-06 0.00014745218068435])\n\nconst I1 = Array([3.06999775886187E-06 7.91090301514898E-12 -1.43705963146176E-12;\n                  7.91090301514898E-12 0.000147960574744097 1.30742394049546E-11;\n                  -1.43705963146176E-12 1.30742394049546E-11 0.000147884231885009])\n\nconst I2 = Array([3.43038397803592E-05 -2.90339844227483E-07 6.18680397558952E-06;\n                  -2.90339844227483E-07 0.000302324068012293 2.25016327583562E-08;\n                  6.18680397558952E-06 2.25016327583562E-08 0.00028292376778719])\n\nconst I3 = Array([1.76996970020568E-05 -5.3695427116208E-07 7.62350214406387E-07;\n                  -5.3695427116208E-07 0.000164188445564489 -2.77843753828047E-07;\n                  7.62350214406387E-07 -2.77843753828047E-07 0.000160656046697151])\n```\n\n\n\n\n    3\u00d73 Matrix{Float64}:\n      1.76997e-5  -5.36954e-7    7.6235e-7\n     -5.36954e-7   0.000164188  -2.77844e-7\n      7.6235e-7   -2.77844e-7    0.000160656\n\n\n\n\n```julia\nM\u0304 = [mb*I(3) zeros(3, 27)\n     zeros(3,3) Ib zeros(3, 24)\n     zeros(3,6) m0*I(3) zeros(3,21);\n     zeros(3,9) I0 zeros(3,18);\n     zeros(3,12) m1*I(3) zeros(3,15);\n     zeros(3,15) I1 zeros(3, 12);\n     zeros(3,18) m2*I(3) zeros(3, 9);\n     zeros(3, 21) I2 zeros(3, 6);\n     zeros(3, 24) m3*I(3) zeros(3, 3);\n     zeros(3, 27) I3]\n```\n\n\n\n\n    30\u00d730 SparseMatrixCSC{Float64, Int64} with 60 stored entries:\n    \u2811\u2884\u28c0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\n    \u2800\u2818\u281b\u2884\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\n    \u2800\u2800\u2800\u2800\u28b1\u28f6\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\n    \u2800\u2800\u2800\u2800\u2800\u2800\u2811\u2884\u28c0\u2800\u2800\u2800\u2800\u2800\u2800\n    \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2818\u281b\u2884\u2800\u2800\u2800\u2800\u2800\n    \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28b1\u28f6\u2800\u2800\u2800\n    \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2811\u2884\u28c0\n    \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2818\u281b\n\n\n\n\n```julia\nfunction hat(\u03c9)\n    return [0 -\u03c9[3] \u03c9[2];\n            \u03c9[3] 0 -\u03c9[1];\n            -\u03c9[2] \u03c9[1] 0]\nend\n\nfunction L(Q)\n    [Q[1] -Q[2:4]'; Q[2:4] Q[1]*I + hat(Q[2:4])]\nend\n\nfunction R(Q)\n    [Q[1] -Q[2:4]'; Q[2:4] Q[1]*I - hat(Q[2:4])]\nend\n\nH = [zeros(1,3); I];\n\nT = Diagonal([1.0; -1.0; -1.0; -1.0])\n\nfunction G(Q)\n    return L(Q)*H  # 4x3\nend\n\nfunction G\u0304(q)\n    Qb = q[4:7]\n    Q0 = q[11:14]\n    Q1 = q[18:21]\n    Q2 = q[25:28]\n    Q3 = q[32:35]\n    \n    # 35x30\n    return blockdiag(sparse(I, 3, 3), sparse(G(Qb)), \n                     sparse(I, 3, 3), sparse(G(Q0)), \n                     sparse(I, 3, 3), sparse(G(Q1)),\n                     sparse(I, 3, 3), sparse(G(Q2)),\n                     sparse(I, 3, 3), sparse(G(Q3)),)\nend\n```\n\n\n\n\n    \u1e20 (generic function with 1 method)\n\n\n\n\n```julia\nfunction Expq(\u03d5)\n    \n    # The quaternion exponential map \u03d5 \u2192 q \n    q = zeros(4)\n    \u03b8 = norm(\u03d5)\n    q = [cos(\u03b8/2); 0.5*\u03d5*sinc(\u03b8/(2*pi))]\n    \n    return q\nend\n\nfunction rotate(Q, p)\n    # Rotate a position vector p by a quaternion Q\n    return H'L(Q)*R(Q)'*H*p\nend\n```\n\n\n\n\n    rotate (generic function with 1 method)\n\n\n\n\n```julia\n#Initial Conditions\nrb = [0.0; 0.0; 0.5]  # start 0.5 meters above the ground\nQb = [1.0; 0; 0; 0]\nq0 = 30*pi/180;\nq1 = 120*(pi/180)\nq2 = 150*(pi/180)\nq3 = -120*(pi/180)\n\nTf = 1\nh = 0.01\nthist = 0:h:Tf\nN = length(thist)\n\npb = rb + rotate(Qb, l_cb)  # position vector from world frame to *JOINTS* 0 and 2\n\nQb0 = Expq([0, q0, 0])  # quaternion from base to link 0\nQ0 = L(Qb)*Qb0  # quaternion from world frame to link 0\nr0 = pb + rotate(Q0, l_c0)\n\nQ01 = Expq([0, q1, 0])  # quaternion from link 0 to link 1\nQ1 = L(Q0)*Q01  # quaternion from world frame to link 1\nr1 = pb + rotate(Q0, l0) + rotate(Q1, l_c1)  \n\nQb2 = Expq([0, q2, 0])  # quaternion from base to link 2\nQ2 = L(Qb)*Qb2  # quaternion from world frame to link 2\nr2 = pb + rotate(Q2, l_c2)\n\nQ23 = Expq([0, q3, 0])  # quaternion from base to link 2\nQ3 = L(Q2)*Q23  # quaternion from world frame to link 2\nr3 = pb + rotate(Q2, l2) + rotate(Q3, l_c3)  \n\nrb_0 = rb\nr0_0 = r0\nr1_0 = r1\nr2_0 = r2\nr3_0 = r3\nQb_0 = Qb\nQ0_0 = Q0\nQ1_0 = Q1\nQ2_0 = Q2\nQ3_0 = Q3\n\nq_0 = [rb_0; Qb_0; r0_0; Q0_0; r1_0; Q1_0; r2_0; Q2_0; r3_0; Q3_0]\n# @show c(q_0)\n\n```\n\n\n\n\n    35-element Vector{Float64}:\n      0.0\n      0.0\n      0.5\n      1.0\n      0.0\n      0.0\n      0.0\n      0.010834702164954238\n      0.00517191218927888\n      0.49374458178847425\n      0.9659258262890683\n      0.0\n      0.25881904510252074\n      \u22ee\n      0.4765293549724043\n      0.25881904510252074\n      0.0\n      0.9659258262890683\n      0.0\n     -0.16945989783706322\n      0.004\n      0.2801328468370613\n      0.9659258262890683\n      0.0\n      0.2588190451025209\n      0.0\n\n\n\n\n```julia\n#Torque input at joints\nuhist = repeat([0 0 0 0 0]*1e-4, N)'\nuhist[:, 1] = [0 0 0 0 0]\nuhist[:, 2] = [0 0 0 0 0]\n# 1 -> joint0\n# 2 -> joint1\n# 3 -> joint2\n# 4 -> joint3\n# 5 -> joint4 (parallel constraint)\n#Corresponding F\nFhist = zeros(30,N)  # wrench [xyz force, xyz torque]\nfor k = 1:N\n    Fhist[:,k] = [zeros(4); -uhist[1, k]-uhist[3, k]; 0; # body\n                  zeros(4); uhist[1, k]-uhist[2, k]; 0; # link0\n                  zeros(4); uhist[2, k]+uhist[5, k]; 0; # link1\n                  zeros(4); uhist[3, k]-uhist[4, k]; 0; # link2\n                  zeros(4); uhist[4, k]-uhist[5, k]; 0] # link3\nend\n```\n\n\n```julia\nfunction exert_wrench(u, pos,  b_orient, target)\n    \nend\n```\n\n\n\n\n    exert_wrench (generic function with 1 method)\n\n\n\n\n```julia\n# make gravity zero for first two timesteps, see if that works\nghist = repeat([0 0 g], N)'\nghist[:, 1] = [0 0 0]\nghist[:, 2] = [0 0 0]\n```\n\n\n\n\n    1\u00d73 Matrix{Int64}:\n     0  0  0\n\n\n\nSolve the following optimization problem at every timestep. \n$$ \\begin{align}\n\\min_{q_{k+1},\\lambda_k,s_k} && \\sum_{i=1}^8s_{k,i} \\\\\n\\text{st} && DEL(q_{k-1},q_k,q_{k+1}) &= 0 && \\text{discrete Euler-Lagrange}\\\\ \n && \\|q_{k+1}\\|^2 - 1 &= 0 && \\text{quaternion norm constraint}\\\\ \n && d(q_{k+1}) &\\geq 0 && \\text{foot must stay above ground}\\\\ \n && s_k - \\text{diag}(\\lambda_k)d(q_{k+1}) &\\geq 0 && \\text{collision constraint}\\\\\n && \\lambda_k &\\geq 0 \\\\ \n && s_k &\\geq 0\n\\end{align} $$\n\nWe will be using IPOPT to solve this, where IPOPT takes problems of the following form\n$$ \\begin{align}\n\\min_x && f(x) \\\\ \n\\text{st} && c_L \\leq c(x) &\\leq c_U && \\text{constraint function with constraint bounds} \\\\ \n&& x_L \\leq x &\\leq x_U && \\text{primal bounds}\n\\end{align}$$\n\n\n```julia\nfunction con(q)\n    # joint constraint function\n    # c(q_0) should be all zeros\n    c_ = zeros(eltype(q), 24)\n    \n    rb = q[1:3]\n    Qb = q[4:7]\n    r0 = q[8:10]\n    Q0 = q[11:14]\n    r1 = q[15:17]\n    Q1 = q[18:21]\n    r2 = q[22:24]\n    Q2 = q[25:28]\n    r3 = q[29:31]\n    Q3 = q[32:35]\n    \n    rf = r3 + rotate(Q3, lee-l_c3) # position of foot\n\n    pb = rb + rotate(Qb, l_cb) # position vector from world frame to *JOINTS* 0 and 2\n    \n    c_[1:3] = pb - r0 - rotate(Q0, -l_c0)\n    c_[4:5] = [0 1 0 0; 0 0 0 1]*L(Qb)'*Q0  # y axis rotation constraint\n    c_[6:8] = r0 + rotate(Q0,  l0-l_c0) - r1 - rotate(Q1, -l_c1)\n    c_[9:10] = [0 1 0 0; 0 0 0 1]*L(Q0)'*Q1\n    c_[11:13] = pb - r2 - rotate(Q2, -l_c2)\n    c_[14:15] = [0 1 0 0; 0 0 0 1]*L(Qb)'*Q2\n    c_[16:18] = r2 + rotate(Q2, l2 - l_c2) - r3 - rotate(Q3, -l_c3)\n    c_[19:20] = [0 1 0 0; 0 0 0 1]*L(Q2)'*Q3\n    c_[21:23] = r1 + rotate(Q1, l1 - l_c1) - r3 - rotate(Q3, lc-l_c3)\n    c_[24] = rf[3] - 0.025  # subtract radius of foot\n             \n    return c_\nend\n\nfunction Dc(q)\n    ForwardDiff.jacobian(dq->con(dq),q)*G\u0304(q)\nend\n```\n\n\n\n\n    Dc (generic function with 1 method)\n\n\n\n\n```julia\nfunction del(m, I, r1, r2, r3, Q1, Q2, Q3, grav)\n    [(1/h)*m*(r2-r1) - (1/h)*m*(r3-r2) - m*grav*h;\n     (2.0/h)*G(Q2)'*L(Q1)*H*I*H'*L(Q1)'*Q2 + (2.0/h)*G(Q2)'*T*R(Q3)'*H*I*H'*L(Q2)'*Q3]\nend\n    \n    \nfunction DEL(q_1,q_2,q_3,\u03bb,F1,F2, grav)\n    \n    rb_1 = q_1[1:3]\n    Qb_1 = q_1[4:7]\n    r0_1 = q_1[8:10]\n    Q0_1 = q_1[11:14]\n    r1_1 = q_1[15:17]\n    Q1_1 = q_1[18:21]\n    r2_1 = q_1[22:24]\n    Q2_1 = q_1[25:28]\n    r3_1 = q_1[29:31]\n    Q3_1 = q_1[32:35]\n    \n    rb_2 = q_2[1:3]\n    Qb_2 = q_2[4:7]\n    r0_2 = q_2[8:10]\n    Q0_2 = q_2[11:14]\n    r1_2 = q_2[15:17]\n    Q1_2 = q_2[18:21]\n    r2_2 = q_2[22:24]\n    Q2_2 = q_2[25:28]\n    r3_2 = q_2[29:31]\n    Q3_2 = q_2[32:35]\n    \n    rb_3 = q_3[1:3]\n    Qb_3 = q_3[4:7]\n    r0_3 = q_3[8:10]\n    Q0_3 = q_3[11:14]\n    r1_3 = q_3[15:17]\n    Q1_3 = q_3[18:21]\n    r2_3 = q_3[22:24]\n    Q2_3 = q_3[25:28]\n    r3_3 = q_3[29:31]\n    Q3_3 = q_3[32:35]\n\n    del1 = [del(mb, Ib, rb_1, rb_2, rb_3, Qb_1, Qb_2, Qb_3, grav);\n            del(m0, I0, r0_1, r0_2, r0_3, Q0_1, Q0_2, Q0_3, grav);\n            del(m1, I1, r1_1, r1_2, r1_3, Q1_1, Q1_2, Q1_3, grav);\n            del(m2, I2, r2_1, r2_2, r2_3, Q2_1, Q2_2, Q2_3, grav);\n            del(m3, I3, r3_1, r3_2, r3_3, Q3_1, Q3_2, Q3_3, grav)] \n\n    return del1 + (h/2.0)*F1 + (h/2.0)*F2 + reshape(h*\u03bb'*Dc(q_2), 30)\nend\n```\n\n\n\n\n    DEL (generic function with 1 method)\n\n\n\n\n```julia\nfunction Dq3DEL(q_1,q_2,q_3,\u03bb,F1,F2, grav)\n    # @show G\u0304(q_3)\n    ForwardDiff.jacobian(dq->DEL(q_1,q_2,dq,\u03bb,F1,F2), q_3)*G\u0304(q_3)\nend\n```\n\n\n\n\n    Dq3DEL (generic function with 1 method)\n\n\n\n\n```julia\nusing Ipopt\nusing MathOptInterface\nconst MOI = MathOptInterface\n\n#Boilerplate setup code to interface with IPOPT.\n\nstruct ProblemMOI <: MOI.AbstractNLPEvaluator\n    n_nlp::Int\n    m_nlp::Int\n    idx_ineq\n    obj_grad::Bool\n    con_jac::Bool\n    sparsity_jac\n    sparsity_hess\n    primal_bounds\n    constraint_bounds\n    hessian_lagrangian::Bool\nend\n\nfunction ProblemMOI(n_nlp,m_nlp;\n        idx_ineq=(1:0),\n        obj_grad=true,\n        con_jac=true,\n        sparsity_jac=sparsity_jacobian(n_nlp,m_nlp),\n        sparsity_hess=sparsity_hessian(n_nlp,m_nlp),\n        primal_bounds=primal_bounds(n_nlp),\n        constraint_bounds=constraint_bounds(m_nlp,idx_ineq=idx_ineq),\n        hessian_lagrangian=false)\n\n    ProblemMOI(n_nlp,m_nlp,\n        idx_ineq,\n        obj_grad,\n        con_jac,\n        sparsity_jac,\n        sparsity_hess,\n        primal_bounds,\n        constraint_bounds,\n        hessian_lagrangian)\nend\n\nfunction constraint_bounds(m; idx_ineq=(1:0))\n    c_l = zeros(m)\n\n    c_u = zeros(m)\n    c_u[idx_ineq] .= Inf\n    \n    return c_l, c_u\nend\n\nfunction row_col!(row,col,r,c)\n    for cc in c\n        for rr in r\n            push!(row,convert(Int,rr))\n            push!(col,convert(Int,cc))\n        end\n    end\n    return row, col\nend\n\nfunction sparsity_jacobian(n,m)\n\n    row = []\n    col = []\n\n    r = 1:m\n    c = 1:n\n\n    row_col!(row,col,r,c)\n\n    return collect(zip(row,col))\nend\n\nfunction sparsity_hessian(n,m)\n\n    row = []\n    col = []\n\n    r = 1:m\n    c = 1:n\n\n    row_col!(row,col,r,c)\n\n    return collect(zip(row,col))\nend\n\nfunction MOI.eval_objective(prob::MOI.AbstractNLPEvaluator, x)\n    objective(x)\nend\n\nfunction MOI.eval_objective_gradient(prob::MOI.AbstractNLPEvaluator, grad_f, x)\n    ForwardDiff.gradient!(grad_f,objective,x)\n    return nothing\nend\n\nfunction MOI.eval_constraint(prob::MOI.AbstractNLPEvaluator,g,x)\n    constraint!(g,x)\n    return nothing\nend\n\nfunction MOI.eval_constraint_jacobian(prob::MOI.AbstractNLPEvaluator, jac, x)\n    ForwardDiff.jacobian!(reshape(jac,prob.m_nlp,prob.n_nlp), constraint!, zeros(prob.m_nlp), x)\n    return nothing\nend\n\nfunction MOI.features_available(prob::MOI.AbstractNLPEvaluator)\n    return [:Grad, :Jac]\nend\n\nMOI.initialize(prob::MOI.AbstractNLPEvaluator, features) = nothing\nMOI.jacobian_structure(prob::MOI.AbstractNLPEvaluator) = prob.sparsity_jac\n\nfunction ipopt_solve(x0,prob::MOI.AbstractNLPEvaluator;\n        tol=1.0e-6,c_tol=1.0e-6,max_iter=10000, print=0)\n    x_l, x_u = prob.primal_bounds\n    c_l, c_u = prob.constraint_bounds\n\n    nlp_bounds = MOI.NLPBoundsPair.(c_l,c_u)\n    block_data = MOI.NLPBlockData(nlp_bounds,prob,true)\n\n    solver = Ipopt.Optimizer()\n    solver.options[\"max_iter\"] = max_iter\n    solver.options[\"tol\"] = tol\n    solver.options[\"constr_viol_tol\"] = c_tol\n    \n    #Uncomment the following line to turn off verbose IPOPT output\n    solver.options[\"print_level\"] = print\n\n    x = MOI.add_variables(solver,prob.n_nlp)\n\n    for i = 1:prob.n_nlp\n        xi = MOI.SingleVariable(x[i])\n        MOI.add_constraint(solver, xi, MOI.LessThan(x_u[i]))\n        MOI.add_constraint(solver, xi, MOI.GreaterThan(x_l[i]))\n        MOI.set(solver, MOI.VariablePrimalStart(), x[i], x0[i])\n    end\n\n    # Solve the problem\n    MOI.set(solver, MOI.NLPBlock(), block_data)\n    MOI.set(solver, MOI.ObjectiveSense(), MOI.MIN_SENSE)\n    MOI.optimize!(solver)\n\n    # Get the solution\n    res = MOI.get(solver, MOI.VariablePrimal(), x)\n\n    return res\nend\n```\n\n\n\n\n    ipopt_solve (generic function with 1 method)\n\n\n\n\n```julia\n@show n_c = size(con(q_0))[1]  # number of constraint rows, 24\n@show n_q = size(q_0)[1]  # number of q rows, 35\n```\n\n    n_c = (size(con(q_0)))[1] = 24\n    n_q = (size(q_0))[1] = 35\n\n\n\n\n\n    35\n\n\n\n\n```julia\n#Objective and constraint functions for IPOPT\n\nfunction objective(z)\n    qn = z[1:n_q]\n    \u03bb = z[n_q+1:n_q+n_c]\n    s = z[n_q+1+n_c:n_q+n_c+n_c]\n    \n    return sum(s) #Minimize slacks associated with complementarity conditions\nend\n\nfunction constraint!(c,z)\n    qn = z[1:n_q]\n    \u03bb = z[n_q+1:n_q+n_c]\n    s = z[n_q+1+n_c:n_q+n_c+n_c]\n\n    # nonlinear DEL equation                (30 equality constraint)\n    # quaternion norm squared - 1 = 0       (5 equality constraints)\n    # joint constraints                     (23 equality constraints)  c7\n    # foot height must stay above ground    (1 inequality constraint)  c7\n    # collision constraint                  (24 inequality constraint)\n\n    c1 = DEL(qhist[:,k-1], qhist[:,k], qn, \u03bb, Fhist[:,k-1],Fhist[:,k], ghist[:, k])  # 30x1\n    c2 = norm(qn[4:7])^2 - 1  # 1x1\n    c3 = norm(qn[11:14])^2 - 1\n    c4 = norm(qn[18:21])^2 - 1\n    c5 = norm(qn[25:28])^2 - 1\n    c6 = norm(qn[32:35])^2 - 1\n    \n    c7 = con(qn)  # 24x1\n    c8 = s - Diagonal(\u03bb)*con(qn)  # 24x1\n    c .= [c1; c2; c3; c4; c5; c6; c7; c8]\n\n    return nothing\nend\n\n#Specify the indicies of c (constraint output) that should be non-negative.\n#The rest will be treated as equality constraints.\n#This can vary depending on how you stacked up c above.\n\nnonnegative_constraint_indices = (58+1:58+25) # update this\n\nfunction primal_bounds(n)\n    #Enforce simple bound constraints on the decision variables (e.g. positivity) here\n    # x_l \u2264 [q; \u03bb; s] \u2264 x_u\n\n    x_l = zeros(n)\n    x_u = Inf*ones(n)\n    x_l[1:35] = -Inf*ones(35)\n\n    return x_l, x_u\nend\n```\n\n\n\n\n    primal_bounds (generic function with 1 method)\n\n\n\n\n```julia\nfunction constraint_check(z)\n    qn = z[1:n_q]\n    \u03bb = z[n_q+1:n_q+n_c]\n    s = z[n_q+1+n_c:n_q+n_c+n_c]\n\n    c1 = DEL(qhist[:,k-1], qhist[:,k], qn, \u03bb, Fhist[:,k-1],Fhist[:,k], ghist[:, k])  # 30x1\n    c2 = norm(qn[4:7])^2 - 1  # 1x1\n    c3 = norm(qn[11:14])^2 - 1\n    c4 = norm(qn[18:21])^2 - 1\n    c5 = norm(qn[25:28])^2 - 1\n    c6 = norm(qn[32:35])^2 - 1\n    \n    c7 = con(qn)  # 24x1\n    c8 = s - Diagonal(\u03bb)*con(qn)  # 24x1\n    A = [c1; c2; c3; c4; c5; c6; c7[1:23]]\n    B = [c7[24]; c8]\n    if !isapprox(A, zeros(58); atol=1e-6, rtol=0)\n        e = 1\n        print(\"\\n\", A, \"\\n\")\n        print(findall(A .< -ones(58)*1e-6), \" is less than 0 \\n\")\n        print(findall(A .> ones(58)*1e-6), \" is greater than 0 \\n\")\n        \n    elseif B < -ones(25)*1e-6\n        e = 1\n        print(\"\\n\", B, \"\\n\")\n        print(findall(B .< -ones(25)*1e-6))\n    else\n        e = 0\n    end\n    \n    return e\nend\n```\n\n\n\n\n    constraint_check (generic function with 2 methods)\n\n\n\n\n```julia\n#Solve with IPOPT\nn_nlp = n_q + n_c + n_c  # size of decision variables\nm_nlp = 83  # size of constraint! output \nnlp_prob = ProblemMOI(n_nlp,m_nlp, idx_ineq=nonnegative_constraint_indices);\n\n#Initial conditions\nqhist = zeros(n_q,N)\nqhist[:,1] .= q_0\nqhist[:,2] .= q_0  # this may need to be fixed\n\nqhist[4:7,2] .= qhist[4:7,2]/norm(qhist[4:7,2])\nqhist[11:14,2] .= qhist[11:14,2]/norm(qhist[11:14,2])\nqhist[18:21,2] .= qhist[18:21,2]/norm(qhist[18:21,2])\nqhist[25:28,2] .= qhist[25:28,2]/norm(qhist[25:28,2])\nqhist[32:35,2] .= qhist[32:35,2]/norm(qhist[32:35,2])\n\n\u03bbhist = zeros(n_c,N-1)\nshist = zeros(n_c,N-1)\nk = 0\n\nfor kk = 2:(N-1)\n    print(\"Simulation \", kk/(N-1)*100, \" % complete \\n\")\n    flush(stdout)\n    k = kk\n    z_guess = [qhist[:,k]; zeros(n_q); ones(n_q)]\n    z_sol = ipopt_solve(z_guess, nlp_prob, print=0);\n    qhist[:,k+1] .= z_sol[1:n_q]\n    \u03bbhist[:,k] .= z_sol[n_q + 1:n_q + n_c]\n    shist[:,k] .= z_sol[n_q + 1 + n_c:n_q + n_c + n_c]\n    e = constraint_check(z_sol)\n    # print(\"\\n\", e, \"\\n\")\n    if e == true\n        print(\"\\n Sim stopped due to ipopt infeasibility \\n\")\n        break\n    end\n    \nend\n```\n\n    Simulation 2.0 % complete \n    Simulation 3.0 % complete \n    Simulation 4.0 % complete \n    Simulation 5.0 % complete \n    Simulation 6.0 % complete \n    Simulation 7.000000000000001 % complete \n    Simulation 8.0 % complete \n    Simulation 9.0 % complete \n    Simulation 10.0 % complete \n    Simulation 11.0 % complete \n    Simulation 12.0 % complete \n    Simulation 13.0 % complete \n    Simulation 14.000000000000002 % complete \n    Simulation 15.0 % complete \n    Simulation 16.0 % complete \n    Simulation 17.0 % complete \n    Simulation 18.0 % complete \n    Simulation 19.0 % complete \n    Simulation 20.0 % complete \n    Simulation 21.0 % complete \n    Simulation 22.0 % complete \n    \n    [7.549200847778437e-11, 1.5033731193971158e-10, 5.1924992083840493e-11, -2.4032767278797575e-11, -1.4268442118264072e-15, -1.0402259586881788e-10, -7.525084505174973e-11, -6.003345101495073e-11, -5.1927234864454497e-11, -1.5429893150969867e-10, -0.00015362197430357526, 7.832222934327891e-6, 9.597580922279109e-11, 9.875180242610424e-11, 9.754498315854565e-11, -8.504219502253581e-8, 1.095149691316907e-11, 1.6185538198033552e-10, 9.428211683593091e-11, 7.825450940650416e-12, 9.7564432227637e-11, 3.4506104638659836e-14, 1.932672674242325e-11, 0.0004928932555188497, -1.9043466122102013e-10, -1.9655703098494773e-10, -1.951442419115268e-10, 1.2493603244479194e-11, -3.684923872114554e-11, 2.3400980810969903e-11, 0.0, -1.1546319456101628e-13, 5.666578317686799e-13, 8.131273432354647e-13, -1.4876988529977098e-13, 5.1263034699329524e-5, -4.230393784218156e-6, -6.313656195078288e-13, 1.292474563789267e-13, 4.552071339227609e-13, 1.4252765634381603e-12, -3.904457453071583e-6, -2.556566069955579e-13, 1.324896410030002e-14, 9.079840828860042e-15, 0.0029293477279617036, 6.668211874805772e-6, 3.0776423076694925e-13, -5.916982398837534e-13, -6.372518682987334e-13, 0.005701159665924438, 3.3323708714867208e-12, 3.0631885916676538e-12, 3.3093672116915607e-13, -2.977293026918196e-13, 0.0012709110438594512, 1.6772195419918137e-5, 7.723216075961742e-5]\n    [11, 37, 42] is less than 0 \n    [12, 24, 36, 46, 47, 51, 56, 57, 58] is greater than 0 \n    \n     Sim stopped due to ipopt infeasibility\n\n\n```julia\nqhist\n```\n\n\n\n\n    35\u00d7101 Matrix{Float64}:\n      0.0          0.0          3.34109e-14  \u2026  0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      0.0          0.0         -6.86478e-16     0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      0.5          0.5          0.5             0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      1.0          1.0          1.0             0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      0.0          0.0         -2.76568e-15     0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      0.0          0.0          3.28955e-18  \u2026  0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      0.0          0.0         -8.22728e-14     0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      0.0108347    0.0108347    0.0108347       0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      0.00517191   0.00517191   0.00517191      0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      0.493745     0.493745     0.493745        0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      0.965926     0.965926     0.965926     \u2026  0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      0.0          0.0          1.86223e-14     0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      0.258819     0.258819     0.258819        0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      \u22ee                                      \u22f1       \u22ee                        \u22ee\n      0.476529     0.476529     0.476529        0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      0.258819     0.258819     0.258819        0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      0.0          0.0          7.82424e-14  \u2026  0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      0.965926     0.965926     0.965926        0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      0.0          0.0         -2.05005e-14     0.0  0.0  0.0  0.0  0.0  0.0  0.0\n     -0.16946     -0.16946     -0.16946         0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      0.004        0.004        0.004           0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      0.280133     0.280133     0.280133     \u2026  0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      0.965926     0.965926     0.965926        0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      0.0          0.0          1.69935e-14     0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      0.258819     0.258819     0.258819        0.0  0.0  0.0  0.0  0.0  0.0  0.0\n      0.0          0.0         -6.47999e-14     0.0  0.0  0.0  0.0  0.0  0.0  0.0\n\n\n\n\n```julia\nusing MeshCat, GeometryBasics, CoordinateTransformations, Rotations, Plots #, GeometryTypes\n```\n\n    WARNING: using Plots.rotate in module Main conflicts with an existing identifier.\n\n\n\n```julia\nvis = Visualizer()\nrender(vis)\n```\n\n    \u250c Info: MeshCat server started. You can open the visualizer by visiting the following URL in your browser:\n    \u2502 http://127.0.0.1:8700\n    \u2514 @ MeshCat /home/ben/.julia/packages/MeshCat/GlCMx/src/visualizer.jl:73\n\n\n\n\n\n<div style=\"height: 500px; width: 100%; overflow-x: auto; overflow-y: hidden; resize: both\">\n\n</div>\n\n\n\n\n\n```julia\n# Zoom in--the robot falls through floor since there is no contact\n\ndelete!(vis)\n\ngreen_material = MeshPhongMaterial(color=RGBA(0, 1, 0, 0.8))\nred_material = MeshPhongMaterial(color=RGBA(1, 0, 0, 0.8))\n\n#l_345 = sqrt((l3 + l4)^2 + l5^2)\n# sphere = Sphere(Point(0, 0, 0), 3)\n# rect = Rectangle(0.2, 0.2, 0.2, 0.2)\ncylinderb = Cylinder(Point(0, -0.02, l_cb[2]), Point(0, 0.02, l_cb[2]), 0.04)  #float(l_cb)\ncylinder0 = Cylinder(Point(-l_c0[1], -l_c0[2], -l_c0[3]), Point((l0-l_c0)[1], (l0-l_c0)[2], (l0-l_c0)[3]), 0.008)\ncylinder1 = Cylinder(Point(-l_c1[1], -l_c1[2], -l_c1[3]), Point((l1-l_c1)[1],(l1-l_c1)[2],(l1-l_c1)[2]), 0.008)\ncylinder2 = Cylinder(Point(-l_c2[1], -l_c2[2], -l_c2[3]), Point((l2-l_c2)[1], (l2-l_c2)[2], (l2-l_c2)[3]), 0.008)\ncylinder3 = Cylinder(Point(-l_c3[1], -l_c3[2], -l_c3[3]), Point((lee-l_c3)[1], (lee-l_c3)[2],  (lee-l_c3)[3]), 0.008)\n\n# setobject!(vis[\"sphere\"],sphere,red_material)\nsetobject!(vis[\"cylinderb\"],cylinderb,red_material)\nsetobject!(vis[\"cylinder0\"],cylinder0,green_material)\nsetobject!(vis[\"cylinder1\"],cylinder1,green_material)\nsetobject!(vis[\"cylinder2\"],cylinder2,green_material)\nsetobject!(vis[\"cylinder3\"],cylinder3,green_material)\n\nfor k = 1:N\n    \n    q = qhist[:, k]\n    # set position and attitude\n    \n    positionb = Translation(q[1:3]...)\n    attitudeb = LinearMap(UnitQuaternion(q[4:7]))\n    position0 = Translation(q[8:10]...)\n    attitude0 = LinearMap(UnitQuaternion(q[11:14]))\n    position1 = Translation(q[15:17]...)\n    attitude1 = LinearMap(UnitQuaternion(q[18:21]))\n    position2 = Translation(q[22:24]...)\n    attitude2 = LinearMap(UnitQuaternion(q[25:28]))\n    position3 = Translation(q[29:31]...)\n    attitude3 = LinearMap(UnitQuaternion(q[32:35]))\n\n    settransform!(vis[\"cylinderb\"], compose(positionb,attitudeb))\n    settransform!(vis[\"cylinder0\"], compose(position0,attitude0))\n    settransform!(vis[\"cylinder1\"], compose(position1,attitude1))\n    settransform!(vis[\"cylinder2\"], compose(position2,attitude2))\n    settransform!(vis[\"cylinder3\"], compose(position3,attitude3))\n    sleep(0.1)\nend\n```\n\n\n```julia\n\n```\n", "meta": {"hexsha": "0ba644b8ae83f2ddec99e333f209fd729c9c66f8", "size": 45191, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "scripts/parallel_leg_floating_max_opt.ipynb", "max_stars_repo_name": "bbokser/hopper-sim", "max_stars_repo_head_hexsha": "3b11741ab92aecd8affeba9405e86b9246e014b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/parallel_leg_floating_max_opt.ipynb", "max_issues_repo_name": "bbokser/hopper-sim", "max_issues_repo_head_hexsha": "3b11741ab92aecd8affeba9405e86b9246e014b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/parallel_leg_floating_max_opt.ipynb", "max_forks_repo_name": "bbokser/hopper-sim", "max_forks_repo_head_hexsha": "3b11741ab92aecd8affeba9405e86b9246e014b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4439215686, "max_line_length": 1361, "alphanum_fraction": 0.5104998783, "converted": true, "num_tokens": 13166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.0940101777128238, "lm_q1q2_score": 0.02765920181881608}}
{"text": "```python\n! pip install qeds\nimport numpy as np\nimport pandas as pd\n%matplotlib inline\nimport qeds\nqeds.themes.mpl_style();\n```\n\n    Requirement already satisfied: qeds in c:\\users\\asus\\anaconda3\\lib\\site-packages (0.6.2)\n    Requirement already satisfied: quandl in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (3.5.0)\n    Requirement already satisfied: pandas-datareader in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.8.1)\n    Requirement already satisfied: openpyxl in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (3.0.0)\n    Requirement already satisfied: numpy in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (1.16.5)\n    Requirement already satisfied: quantecon in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.4.6)\n    Requirement already satisfied: scikit-learn in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.21.3)\n    Requirement already satisfied: pandas in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.25.1)\n    Requirement already satisfied: plotly in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (4.5.4)\n    Requirement already satisfied: seaborn in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.9.0)\n    Requirement already satisfied: statsmodels in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.10.1)\n    Requirement already satisfied: requests in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (2.22.0)\n    Requirement already satisfied: matplotlib in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (3.1.1)\n    Requirement already satisfied: pyarrow in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.16.0)\n    Requirement already satisfied: scipy in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (1.3.1)\n    Requirement already satisfied: inflection>=0.3.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quandl->qeds) (0.3.1)\n    Requirement already satisfied: six in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quandl->qeds) (1.12.0)\n    Requirement already satisfied: more-itertools in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quandl->qeds) (7.2.0)\n    Requirement already satisfied: python-dateutil in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quandl->qeds) (2.8.0)\n    Requirement already satisfied: lxml in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pandas-datareader->qeds) (4.4.1)\n    Requirement already satisfied: jdcal in c:\\users\\asus\\anaconda3\\lib\\site-packages (from openpyxl->qeds) (1.4.1)\n    Requirement already satisfied: et-xmlfile in c:\\users\\asus\\anaconda3\\lib\\site-packages (from openpyxl->qeds) (1.0.1)\n    Requirement already satisfied: numba>=0.38 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quantecon->qeds) (0.45.1)\n    Requirement already satisfied: sympy in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quantecon->qeds) (1.4)\n    Requirement already satisfied: joblib>=0.11 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from scikit-learn->qeds) (0.13.2)\n    Requirement already satisfied: pytz>=2017.2 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pandas->qeds) (2019.3)\n    Requirement already satisfied: retrying>=1.3.3 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from plotly->qeds) (1.3.3)\n    Requirement already satisfied: patsy>=0.4.0 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from statsmodels->qeds) (0.5.1)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (3.0.4)\n    Requirement already satisfied: idna<2.9,>=2.5 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (2.8)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (1.24.2)\n    Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (2019.9.11)\n    Requirement already satisfied: cycler>=0.10 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (1.1.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (2.4.2)\n    Requirement already satisfied: llvmlite>=0.29.0dev0 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from numba>=0.38->quantecon->qeds) (0.29.0)\n    Requirement already satisfied: mpmath>=0.19 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from sympy->quantecon->qeds) (1.1.0)\n    Requirement already satisfied: setuptools in c:\\users\\asus\\anaconda3\\lib\\site-packages (from kiwisolver>=1.0.1->matplotlib->qeds) (41.4.0)\n\n\n# Reshape - Exercises\n\n**For these exercises we use basketball data. After loading the data:**\n- we create a long-form version\n- we create a wide-form version \n\n\n```python\nurl = \"https://datascience.quantecon.org/assets/data/bball.csv\"\nbball = pd.read_csv(url)\nbball.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Year</th>\n      <th>Player</th>\n      <th>Team</th>\n      <th>TeamName</th>\n      <th>Games</th>\n      <th>Pts</th>\n      <th>Assist</th>\n      <th>Rebound</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>79</td>\n      <td>30.1</td>\n      <td>6.7</td>\n      <td>5.4</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>79</td>\n      <td>25.3</td>\n      <td>6.6</td>\n      <td>4.5</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>51</td>\n      <td>26.4</td>\n      <td>6.1</td>\n      <td>5.1</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>OKC</td>\n      <td>Thunder</td>\n      <td>72</td>\n      <td>28.2</td>\n      <td>5.0</td>\n      <td>8.2</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>62</td>\n      <td>25.1</td>\n      <td>4.8</td>\n      <td>8.3</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nbball_long = bball.melt(id_vars=[\"Year\", \"Player\", \"Team\", \"TeamName\"])\nbball_long.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Year</th>\n      <th>Player</th>\n      <th>Team</th>\n      <th>TeamName</th>\n      <th>variable</th>\n      <th>value</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Games</td>\n      <td>79.0</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Games</td>\n      <td>79.0</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Games</td>\n      <td>51.0</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>OKC</td>\n      <td>Thunder</td>\n      <td>Games</td>\n      <td>72.0</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Games</td>\n      <td>62.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nbball_wide = bball_long.pivot_table(\n    index=\"Year\",\n    columns=[\"Player\", \"variable\", \"Team\"],\n    values=\"value\"\n)\nbball_wide.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n\n    .dataframe thead tr:last-of-type th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th>Player</th>\n      <th colspan=\"4\" halign=\"left\">Curry</th>\n      <th colspan=\"6\" halign=\"left\">Durant</th>\n      <th>...</th>\n      <th colspan=\"10\" halign=\"left\">Ibaka</th>\n    </tr>\n    <tr>\n      <th>variable</th>\n      <th>Assist</th>\n      <th>Games</th>\n      <th>Pts</th>\n      <th>Rebound</th>\n      <th colspan=\"2\" halign=\"left\">Assist</th>\n      <th colspan=\"2\" halign=\"left\">Games</th>\n      <th colspan=\"2\" halign=\"left\">Pts</th>\n      <th>...</th>\n      <th>Assist</th>\n      <th colspan=\"3\" halign=\"left\">Games</th>\n      <th colspan=\"3\" halign=\"left\">Pts</th>\n      <th colspan=\"3\" halign=\"left\">Rebound</th>\n    </tr>\n    <tr>\n      <th>Team</th>\n      <th>GSW</th>\n      <th>GSW</th>\n      <th>GSW</th>\n      <th>GSW</th>\n      <th>GSW</th>\n      <th>OKC</th>\n      <th>GSW</th>\n      <th>OKC</th>\n      <th>GSW</th>\n      <th>OKC</th>\n      <th>...</th>\n      <th>TOR</th>\n      <th>OKC</th>\n      <th>ORL</th>\n      <th>TOR</th>\n      <th>OKC</th>\n      <th>ORL</th>\n      <th>TOR</th>\n      <th>OKC</th>\n      <th>ORL</th>\n      <th>TOR</th>\n    </tr>\n    <tr>\n      <th>Year</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>2015</td>\n      <td>6.7</td>\n      <td>79.0</td>\n      <td>30.1</td>\n      <td>5.4</td>\n      <td>NaN</td>\n      <td>5.0</td>\n      <td>NaN</td>\n      <td>72.0</td>\n      <td>NaN</td>\n      <td>28.2</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>78.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>12.6</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6.8</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2016</td>\n      <td>6.6</td>\n      <td>79.0</td>\n      <td>25.3</td>\n      <td>4.5</td>\n      <td>4.8</td>\n      <td>NaN</td>\n      <td>62.0</td>\n      <td>NaN</td>\n      <td>25.1</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>0.7</td>\n      <td>NaN</td>\n      <td>56.0</td>\n      <td>23.0</td>\n      <td>NaN</td>\n      <td>15.1</td>\n      <td>14.2</td>\n      <td>NaN</td>\n      <td>6.8</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>2017</td>\n      <td>6.1</td>\n      <td>51.0</td>\n      <td>26.4</td>\n      <td>5.1</td>\n      <td>5.4</td>\n      <td>NaN</td>\n      <td>68.0</td>\n      <td>NaN</td>\n      <td>26.4</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n<p>3 rows \u00d7 24 columns</p>\n</div>\n\n\n\n## Exercise 1\n\n**(*Warning*: This one is challenging):**\n\n**Recall the `bball_wide` DataFrame from above (repeated below to jog your memory).**\n\n**In this task, you will start from `ball` and re-recreate `bball_wide` by combining the operations we just learned about. There are many ways to do this, so be creative.**\n\n**The solution presented in the lecture used `set_index`, `T`, `stack`, and `unstack` in that order.**\n\n**Here are a few hints:**\n\n- Think about what columns you will need to call `set_index` on so that their data ends up as labels (either in index or columns).  \n- Leave other columns (e.g. the actual game stats) as actual columns so their data can stay data during your reshaping.  \n\n**Hint**: You might need to add `.sort_index(axis=1)` after you are finished to get the columns in the same order.\n\n**Hint**: You may not end up with a `variable` header on the second level of column labels. This is ok.\n\n\n```python\n#we have to recreate this DataFrame in a different way\nbball_wide\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n\n    .dataframe thead tr:last-of-type th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th>Player</th>\n      <th colspan=\"4\" halign=\"left\">Curry</th>\n      <th colspan=\"6\" halign=\"left\">Durant</th>\n      <th>...</th>\n      <th colspan=\"10\" halign=\"left\">Ibaka</th>\n    </tr>\n    <tr>\n      <th>variable</th>\n      <th>Assist</th>\n      <th>Games</th>\n      <th>Pts</th>\n      <th>Rebound</th>\n      <th colspan=\"2\" halign=\"left\">Assist</th>\n      <th colspan=\"2\" halign=\"left\">Games</th>\n      <th colspan=\"2\" halign=\"left\">Pts</th>\n      <th>...</th>\n      <th>Assist</th>\n      <th colspan=\"3\" halign=\"left\">Games</th>\n      <th colspan=\"3\" halign=\"left\">Pts</th>\n      <th colspan=\"3\" halign=\"left\">Rebound</th>\n    </tr>\n    <tr>\n      <th>Team</th>\n      <th>GSW</th>\n      <th>GSW</th>\n      <th>GSW</th>\n      <th>GSW</th>\n      <th>GSW</th>\n      <th>OKC</th>\n      <th>GSW</th>\n      <th>OKC</th>\n      <th>GSW</th>\n      <th>OKC</th>\n      <th>...</th>\n      <th>TOR</th>\n      <th>OKC</th>\n      <th>ORL</th>\n      <th>TOR</th>\n      <th>OKC</th>\n      <th>ORL</th>\n      <th>TOR</th>\n      <th>OKC</th>\n      <th>ORL</th>\n      <th>TOR</th>\n    </tr>\n    <tr>\n      <th>Year</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>2015</td>\n      <td>6.7</td>\n      <td>79.0</td>\n      <td>30.1</td>\n      <td>5.4</td>\n      <td>NaN</td>\n      <td>5.0</td>\n      <td>NaN</td>\n      <td>72.0</td>\n      <td>NaN</td>\n      <td>28.2</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>78.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>12.6</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6.8</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2016</td>\n      <td>6.6</td>\n      <td>79.0</td>\n      <td>25.3</td>\n      <td>4.5</td>\n      <td>4.8</td>\n      <td>NaN</td>\n      <td>62.0</td>\n      <td>NaN</td>\n      <td>25.1</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>0.7</td>\n      <td>NaN</td>\n      <td>56.0</td>\n      <td>23.0</td>\n      <td>NaN</td>\n      <td>15.1</td>\n      <td>14.2</td>\n      <td>NaN</td>\n      <td>6.8</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>2017</td>\n      <td>6.1</td>\n      <td>51.0</td>\n      <td>26.4</td>\n      <td>5.1</td>\n      <td>5.4</td>\n      <td>NaN</td>\n      <td>68.0</td>\n      <td>NaN</td>\n      <td>26.4</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n<p>3 rows \u00d7 24 columns</p>\n</div>\n\n\n\n\n```python\nbball.drop(\"TeamName\", axis=1).set_index([\"Year\", \"Player\", \"Team\"]).stack().unstack(level=[1, 3, 2]).sort_index(axis=1)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n\n    .dataframe thead tr:last-of-type th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th>Player</th>\n      <th colspan=\"4\" halign=\"left\">Curry</th>\n      <th colspan=\"6\" halign=\"left\">Durant</th>\n      <th>...</th>\n      <th colspan=\"10\" halign=\"left\">Ibaka</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>Assist</th>\n      <th>Games</th>\n      <th>Pts</th>\n      <th>Rebound</th>\n      <th colspan=\"2\" halign=\"left\">Assist</th>\n      <th colspan=\"2\" halign=\"left\">Games</th>\n      <th colspan=\"2\" halign=\"left\">Pts</th>\n      <th>...</th>\n      <th>Assist</th>\n      <th colspan=\"3\" halign=\"left\">Games</th>\n      <th colspan=\"3\" halign=\"left\">Pts</th>\n      <th colspan=\"3\" halign=\"left\">Rebound</th>\n    </tr>\n    <tr>\n      <th>Team</th>\n      <th>GSW</th>\n      <th>GSW</th>\n      <th>GSW</th>\n      <th>GSW</th>\n      <th>GSW</th>\n      <th>OKC</th>\n      <th>GSW</th>\n      <th>OKC</th>\n      <th>GSW</th>\n      <th>OKC</th>\n      <th>...</th>\n      <th>TOR</th>\n      <th>OKC</th>\n      <th>ORL</th>\n      <th>TOR</th>\n      <th>OKC</th>\n      <th>ORL</th>\n      <th>TOR</th>\n      <th>OKC</th>\n      <th>ORL</th>\n      <th>TOR</th>\n    </tr>\n    <tr>\n      <th>Year</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>2015</td>\n      <td>6.7</td>\n      <td>79.0</td>\n      <td>30.1</td>\n      <td>5.4</td>\n      <td>NaN</td>\n      <td>5.0</td>\n      <td>NaN</td>\n      <td>72.0</td>\n      <td>NaN</td>\n      <td>28.2</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>78.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>12.6</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6.8</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2016</td>\n      <td>6.6</td>\n      <td>79.0</td>\n      <td>25.3</td>\n      <td>4.5</td>\n      <td>4.8</td>\n      <td>NaN</td>\n      <td>62.0</td>\n      <td>NaN</td>\n      <td>25.1</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>0.7</td>\n      <td>NaN</td>\n      <td>56.0</td>\n      <td>23.0</td>\n      <td>NaN</td>\n      <td>15.1</td>\n      <td>14.2</td>\n      <td>NaN</td>\n      <td>6.8</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>2017</td>\n      <td>6.1</td>\n      <td>51.0</td>\n      <td>26.4</td>\n      <td>5.1</td>\n      <td>5.4</td>\n      <td>NaN</td>\n      <td>68.0</td>\n      <td>NaN</td>\n      <td>26.4</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n<p>3 rows \u00d7 24 columns</p>\n</div>\n\n\n\n**(Tentative) explanation of the code:**\n\n\n```python\n# '.drop(\"TeamName\", axis=1)' drops the columns (axis=1) TeamName, Avoid to have a useless (maybe akward ?) variable in the final dataset\nbball.drop(\"TeamName\", axis=1)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Year</th>\n      <th>Player</th>\n      <th>Team</th>\n      <th>Games</th>\n      <th>Pts</th>\n      <th>Assist</th>\n      <th>Rebound</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>79</td>\n      <td>30.1</td>\n      <td>6.7</td>\n      <td>5.4</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>79</td>\n      <td>25.3</td>\n      <td>6.6</td>\n      <td>4.5</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>51</td>\n      <td>26.4</td>\n      <td>6.1</td>\n      <td>5.1</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>OKC</td>\n      <td>72</td>\n      <td>28.2</td>\n      <td>5.0</td>\n      <td>8.2</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>GSW</td>\n      <td>62</td>\n      <td>25.1</td>\n      <td>4.8</td>\n      <td>8.3</td>\n    </tr>\n    <tr>\n      <td>5</td>\n      <td>2017</td>\n      <td>Durant</td>\n      <td>GSW</td>\n      <td>68</td>\n      <td>26.4</td>\n      <td>5.4</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>6</td>\n      <td>2015</td>\n      <td>Ibaka</td>\n      <td>OKC</td>\n      <td>78</td>\n      <td>12.6</td>\n      <td>0.8</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>7</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>ORL</td>\n      <td>56</td>\n      <td>15.1</td>\n      <td>1.1</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>8</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>TOR</td>\n      <td>23</td>\n      <td>14.2</td>\n      <td>0.7</td>\n      <td>6.8</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# set_index([\"Year\", \"Player\", \"Team\"]) sets multindex, the hierarchy is Year > Player > Team. This is necessary if we want to stack the data (ie group and 'stack'), with each component of the stack corresponding to the values in a given year of a player in a given team\nbball.drop(\"TeamName\", axis=1).set_index([\"Year\", \"Player\", \"Team\"])\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th></th>\n      <th>Games</th>\n      <th>Pts</th>\n      <th>Assist</th>\n      <th>Rebound</th>\n    </tr>\n    <tr>\n      <th>Year</th>\n      <th>Player</th>\n      <th>Team</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>79</td>\n      <td>30.1</td>\n      <td>6.7</td>\n      <td>5.4</td>\n    </tr>\n    <tr>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>79</td>\n      <td>25.3</td>\n      <td>6.6</td>\n      <td>4.5</td>\n    </tr>\n    <tr>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>51</td>\n      <td>26.4</td>\n      <td>6.1</td>\n      <td>5.1</td>\n    </tr>\n    <tr>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>OKC</td>\n      <td>72</td>\n      <td>28.2</td>\n      <td>5.0</td>\n      <td>8.2</td>\n    </tr>\n    <tr>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>GSW</td>\n      <td>62</td>\n      <td>25.1</td>\n      <td>4.8</td>\n      <td>8.3</td>\n    </tr>\n    <tr>\n      <td>2017</td>\n      <td>Durant</td>\n      <td>GSW</td>\n      <td>68</td>\n      <td>26.4</td>\n      <td>5.4</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>2015</td>\n      <td>Ibaka</td>\n      <td>OKC</td>\n      <td>78</td>\n      <td>12.6</td>\n      <td>0.8</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td rowspan=\"2\" valign=\"top\">2016</td>\n      <td rowspan=\"2\" valign=\"top\">Ibaka</td>\n      <td>ORL</td>\n      <td>56</td>\n      <td>15.1</td>\n      <td>1.1</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>TOR</td>\n      <td>23</td>\n      <td>14.2</td>\n      <td>0.7</td>\n      <td>6.8</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# stack stacks the data for each YEAR, PLAYER, TEAM triple. the outcome is a 'stack', each component of this stack being a table of the value of all the variables (ie non index) for a given combination of the indexes.\nbball.drop(\"TeamName\", axis=1).set_index([\"Year\", \"Player\", \"Team\"]).stack()\n```\n\n\n\n\n    Year  Player  Team         \n    2015  Curry   GSW   Games      79.0\n                        Pts        30.1\n                        Assist      6.7\n                        Rebound     5.4\n    2016  Curry   GSW   Games      79.0\n                        Pts        25.3\n                        Assist      6.6\n                        Rebound     4.5\n    2017  Curry   GSW   Games      51.0\n                        Pts        26.4\n                        Assist      6.1\n                        Rebound     5.1\n    2015  Durant  OKC   Games      72.0\n                        Pts        28.2\n                        Assist      5.0\n                        Rebound     8.2\n    2016  Durant  GSW   Games      62.0\n                        Pts        25.1\n                        Assist      4.8\n                        Rebound     8.3\n    2017  Durant  GSW   Games      68.0\n                        Pts        26.4\n                        Assist      5.4\n                        Rebound     6.8\n    2015  Ibaka   OKC   Games      78.0\n                        Pts        12.6\n                        Assist      0.8\n                        Rebound     6.8\n    2016  Ibaka   ORL   Games      56.0\n                        Pts        15.1\n                        Assist      1.1\n                        Rebound     6.8\n                  TOR   Games      23.0\n                        Pts        14.2\n                        Assist      0.7\n                        Rebound     6.8\n    dtype: float64\n\n\n\n\n```python\n# An intuitive idea to explain that ?\nbball.drop(\"TeamName\", axis=1).set_index([\"Year\", \"Player\", \"Team\"]).stack().unstack(level=[1,3,2])\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n\n    .dataframe thead tr:last-of-type th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th>Player</th>\n      <th colspan=\"4\" halign=\"left\">Curry</th>\n      <th colspan=\"6\" halign=\"left\">Durant</th>\n      <th>...</th>\n      <th colspan=\"10\" halign=\"left\">Ibaka</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>Games</th>\n      <th>Pts</th>\n      <th>Assist</th>\n      <th>Rebound</th>\n      <th>Games</th>\n      <th>Pts</th>\n      <th>Assist</th>\n      <th>Rebound</th>\n      <th>Games</th>\n      <th>Pts</th>\n      <th>...</th>\n      <th>Assist</th>\n      <th>Rebound</th>\n      <th>Games</th>\n      <th>Pts</th>\n      <th>Assist</th>\n      <th>Rebound</th>\n      <th>Games</th>\n      <th>Pts</th>\n      <th>Assist</th>\n      <th>Rebound</th>\n    </tr>\n    <tr>\n      <th>Team</th>\n      <th>GSW</th>\n      <th>GSW</th>\n      <th>GSW</th>\n      <th>GSW</th>\n      <th>OKC</th>\n      <th>OKC</th>\n      <th>OKC</th>\n      <th>OKC</th>\n      <th>GSW</th>\n      <th>GSW</th>\n      <th>...</th>\n      <th>OKC</th>\n      <th>OKC</th>\n      <th>ORL</th>\n      <th>ORL</th>\n      <th>ORL</th>\n      <th>ORL</th>\n      <th>TOR</th>\n      <th>TOR</th>\n      <th>TOR</th>\n      <th>TOR</th>\n    </tr>\n    <tr>\n      <th>Year</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>2015</td>\n      <td>79.0</td>\n      <td>30.1</td>\n      <td>6.7</td>\n      <td>5.4</td>\n      <td>72.0</td>\n      <td>28.2</td>\n      <td>5.0</td>\n      <td>8.2</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>0.8</td>\n      <td>6.8</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2016</td>\n      <td>79.0</td>\n      <td>25.3</td>\n      <td>6.6</td>\n      <td>4.5</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>62.0</td>\n      <td>25.1</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>56.0</td>\n      <td>15.1</td>\n      <td>1.1</td>\n      <td>6.8</td>\n      <td>23.0</td>\n      <td>14.2</td>\n      <td>0.7</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>2017</td>\n      <td>51.0</td>\n      <td>26.4</td>\n      <td>6.1</td>\n      <td>5.1</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>68.0</td>\n      <td>26.4</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n<p>3 rows \u00d7 24 columns</p>\n</div>\n\n\n\n\n```python\n# sort_index(axis=1) sort the variables in the alphabetical order. Changes the order of the columns variable only\nbball.drop(\"TeamName\", axis=1).set_index([\"Year\", \"Player\", \"Team\"]).stack().unstack(level=[1,3,2]).sort_index(axis=1)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n\n    .dataframe thead tr:last-of-type th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th>Player</th>\n      <th colspan=\"4\" halign=\"left\">Curry</th>\n      <th colspan=\"6\" halign=\"left\">Durant</th>\n      <th>...</th>\n      <th colspan=\"10\" halign=\"left\">Ibaka</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>Assist</th>\n      <th>Games</th>\n      <th>Pts</th>\n      <th>Rebound</th>\n      <th colspan=\"2\" halign=\"left\">Assist</th>\n      <th colspan=\"2\" halign=\"left\">Games</th>\n      <th colspan=\"2\" halign=\"left\">Pts</th>\n      <th>...</th>\n      <th>Assist</th>\n      <th colspan=\"3\" halign=\"left\">Games</th>\n      <th colspan=\"3\" halign=\"left\">Pts</th>\n      <th colspan=\"3\" halign=\"left\">Rebound</th>\n    </tr>\n    <tr>\n      <th>Team</th>\n      <th>GSW</th>\n      <th>GSW</th>\n      <th>GSW</th>\n      <th>GSW</th>\n      <th>GSW</th>\n      <th>OKC</th>\n      <th>GSW</th>\n      <th>OKC</th>\n      <th>GSW</th>\n      <th>OKC</th>\n      <th>...</th>\n      <th>TOR</th>\n      <th>OKC</th>\n      <th>ORL</th>\n      <th>TOR</th>\n      <th>OKC</th>\n      <th>ORL</th>\n      <th>TOR</th>\n      <th>OKC</th>\n      <th>ORL</th>\n      <th>TOR</th>\n    </tr>\n    <tr>\n      <th>Year</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>2015</td>\n      <td>6.7</td>\n      <td>79.0</td>\n      <td>30.1</td>\n      <td>5.4</td>\n      <td>NaN</td>\n      <td>5.0</td>\n      <td>NaN</td>\n      <td>72.0</td>\n      <td>NaN</td>\n      <td>28.2</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>78.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>12.6</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6.8</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2016</td>\n      <td>6.6</td>\n      <td>79.0</td>\n      <td>25.3</td>\n      <td>4.5</td>\n      <td>4.8</td>\n      <td>NaN</td>\n      <td>62.0</td>\n      <td>NaN</td>\n      <td>25.1</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>0.7</td>\n      <td>NaN</td>\n      <td>56.0</td>\n      <td>23.0</td>\n      <td>NaN</td>\n      <td>15.1</td>\n      <td>14.2</td>\n      <td>NaN</td>\n      <td>6.8</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>2017</td>\n      <td>6.1</td>\n      <td>51.0</td>\n      <td>26.4</td>\n      <td>5.1</td>\n      <td>5.4</td>\n      <td>NaN</td>\n      <td>68.0</td>\n      <td>NaN</td>\n      <td>26.4</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n<p>3 rows \u00d7 24 columns</p>\n</div>\n\n\n\n## Exercise 2\n\n1. **What do you think would happen if we wrote `bball.melt(id_vars=[\"Year\", \"Player\"])` rather than `bball.melt(id_vars=[\"Year\", \"Player\", \"Team\", \"TeamName\"])`? Were you right? Write your thoughts.** \n\n\n```python\n# for bball.melt(id_vars=[\"Year\", \"Player\"]) we would get only the columns Year and Player and all the other columns \n# would be put into two new columns: variable (Team, Teamname, etc) and values (the values associated with each)\n\n# for bball.melt(id_vars=[\"Year\", \"Player\", \"Team\", \"TeamName\"]) we would get the columns Year, Player, Team and Teamname\n# and all the remaining columns will be put into two new columns: variable and values\n```\n\n\n```python\nbball.melt(id_vars=[\"Year\", \"Player\"])\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Year</th>\n      <th>Player</th>\n      <th>variable</th>\n      <th>value</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>Team</td>\n      <td>GSW</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>Team</td>\n      <td>GSW</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>Team</td>\n      <td>GSW</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>Team</td>\n      <td>OKC</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>Team</td>\n      <td>GSW</td>\n    </tr>\n    <tr>\n      <td>5</td>\n      <td>2017</td>\n      <td>Durant</td>\n      <td>Team</td>\n      <td>GSW</td>\n    </tr>\n    <tr>\n      <td>6</td>\n      <td>2015</td>\n      <td>Ibaka</td>\n      <td>Team</td>\n      <td>OKC</td>\n    </tr>\n    <tr>\n      <td>7</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Team</td>\n      <td>ORL</td>\n    </tr>\n    <tr>\n      <td>8</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Team</td>\n      <td>TOR</td>\n    </tr>\n    <tr>\n      <td>9</td>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>TeamName</td>\n      <td>Warriors</td>\n    </tr>\n    <tr>\n      <td>10</td>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>TeamName</td>\n      <td>Warriors</td>\n    </tr>\n    <tr>\n      <td>11</td>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>TeamName</td>\n      <td>Warriors</td>\n    </tr>\n    <tr>\n      <td>12</td>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>TeamName</td>\n      <td>Thunder</td>\n    </tr>\n    <tr>\n      <td>13</td>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>TeamName</td>\n      <td>Warriors</td>\n    </tr>\n    <tr>\n      <td>14</td>\n      <td>2017</td>\n      <td>Durant</td>\n      <td>TeamName</td>\n      <td>Warriors</td>\n    </tr>\n    <tr>\n      <td>15</td>\n      <td>2015</td>\n      <td>Ibaka</td>\n      <td>TeamName</td>\n      <td>Thunder</td>\n    </tr>\n    <tr>\n      <td>16</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>TeamName</td>\n      <td>Magic</td>\n    </tr>\n    <tr>\n      <td>17</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>TeamName</td>\n      <td>Raptors</td>\n    </tr>\n    <tr>\n      <td>18</td>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>Games</td>\n      <td>79</td>\n    </tr>\n    <tr>\n      <td>19</td>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>Games</td>\n      <td>79</td>\n    </tr>\n    <tr>\n      <td>20</td>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>Games</td>\n      <td>51</td>\n    </tr>\n    <tr>\n      <td>21</td>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>Games</td>\n      <td>72</td>\n    </tr>\n    <tr>\n      <td>22</td>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>Games</td>\n      <td>62</td>\n    </tr>\n    <tr>\n      <td>23</td>\n      <td>2017</td>\n      <td>Durant</td>\n      <td>Games</td>\n      <td>68</td>\n    </tr>\n    <tr>\n      <td>24</td>\n      <td>2015</td>\n      <td>Ibaka</td>\n      <td>Games</td>\n      <td>78</td>\n    </tr>\n    <tr>\n      <td>25</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Games</td>\n      <td>56</td>\n    </tr>\n    <tr>\n      <td>26</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Games</td>\n      <td>23</td>\n    </tr>\n    <tr>\n      <td>27</td>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>Pts</td>\n      <td>30.1</td>\n    </tr>\n    <tr>\n      <td>28</td>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>Pts</td>\n      <td>25.3</td>\n    </tr>\n    <tr>\n      <td>29</td>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>Pts</td>\n      <td>26.4</td>\n    </tr>\n    <tr>\n      <td>30</td>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>Pts</td>\n      <td>28.2</td>\n    </tr>\n    <tr>\n      <td>31</td>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>Pts</td>\n      <td>25.1</td>\n    </tr>\n    <tr>\n      <td>32</td>\n      <td>2017</td>\n      <td>Durant</td>\n      <td>Pts</td>\n      <td>26.4</td>\n    </tr>\n    <tr>\n      <td>33</td>\n      <td>2015</td>\n      <td>Ibaka</td>\n      <td>Pts</td>\n      <td>12.6</td>\n    </tr>\n    <tr>\n      <td>34</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Pts</td>\n      <td>15.1</td>\n    </tr>\n    <tr>\n      <td>35</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Pts</td>\n      <td>14.2</td>\n    </tr>\n    <tr>\n      <td>36</td>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>Assist</td>\n      <td>6.7</td>\n    </tr>\n    <tr>\n      <td>37</td>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>Assist</td>\n      <td>6.6</td>\n    </tr>\n    <tr>\n      <td>38</td>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>Assist</td>\n      <td>6.1</td>\n    </tr>\n    <tr>\n      <td>39</td>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>Assist</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <td>40</td>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>Assist</td>\n      <td>4.8</td>\n    </tr>\n    <tr>\n      <td>41</td>\n      <td>2017</td>\n      <td>Durant</td>\n      <td>Assist</td>\n      <td>5.4</td>\n    </tr>\n    <tr>\n      <td>42</td>\n      <td>2015</td>\n      <td>Ibaka</td>\n      <td>Assist</td>\n      <td>0.8</td>\n    </tr>\n    <tr>\n      <td>43</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Assist</td>\n      <td>1.1</td>\n    </tr>\n    <tr>\n      <td>44</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Assist</td>\n      <td>0.7</td>\n    </tr>\n    <tr>\n      <td>45</td>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>Rebound</td>\n      <td>5.4</td>\n    </tr>\n    <tr>\n      <td>46</td>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>Rebound</td>\n      <td>4.5</td>\n    </tr>\n    <tr>\n      <td>47</td>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>Rebound</td>\n      <td>5.1</td>\n    </tr>\n    <tr>\n      <td>48</td>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>Rebound</td>\n      <td>8.2</td>\n    </tr>\n    <tr>\n      <td>49</td>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>Rebound</td>\n      <td>8.3</td>\n    </tr>\n    <tr>\n      <td>50</td>\n      <td>2017</td>\n      <td>Durant</td>\n      <td>Rebound</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>51</td>\n      <td>2015</td>\n      <td>Ibaka</td>\n      <td>Rebound</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>52</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Rebound</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>53</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Rebound</td>\n      <td>6.8</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nbball.melt(id_vars=[\"Year\", \"Player\", \"Team\", \"TeamName\"])\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Year</th>\n      <th>Player</th>\n      <th>Team</th>\n      <th>TeamName</th>\n      <th>variable</th>\n      <th>value</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Games</td>\n      <td>79.0</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Games</td>\n      <td>79.0</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Games</td>\n      <td>51.0</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>OKC</td>\n      <td>Thunder</td>\n      <td>Games</td>\n      <td>72.0</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Games</td>\n      <td>62.0</td>\n    </tr>\n    <tr>\n      <td>5</td>\n      <td>2017</td>\n      <td>Durant</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Games</td>\n      <td>68.0</td>\n    </tr>\n    <tr>\n      <td>6</td>\n      <td>2015</td>\n      <td>Ibaka</td>\n      <td>OKC</td>\n      <td>Thunder</td>\n      <td>Games</td>\n      <td>78.0</td>\n    </tr>\n    <tr>\n      <td>7</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>ORL</td>\n      <td>Magic</td>\n      <td>Games</td>\n      <td>56.0</td>\n    </tr>\n    <tr>\n      <td>8</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>TOR</td>\n      <td>Raptors</td>\n      <td>Games</td>\n      <td>23.0</td>\n    </tr>\n    <tr>\n      <td>9</td>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Pts</td>\n      <td>30.1</td>\n    </tr>\n    <tr>\n      <td>10</td>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Pts</td>\n      <td>25.3</td>\n    </tr>\n    <tr>\n      <td>11</td>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Pts</td>\n      <td>26.4</td>\n    </tr>\n    <tr>\n      <td>12</td>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>OKC</td>\n      <td>Thunder</td>\n      <td>Pts</td>\n      <td>28.2</td>\n    </tr>\n    <tr>\n      <td>13</td>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Pts</td>\n      <td>25.1</td>\n    </tr>\n    <tr>\n      <td>14</td>\n      <td>2017</td>\n      <td>Durant</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Pts</td>\n      <td>26.4</td>\n    </tr>\n    <tr>\n      <td>15</td>\n      <td>2015</td>\n      <td>Ibaka</td>\n      <td>OKC</td>\n      <td>Thunder</td>\n      <td>Pts</td>\n      <td>12.6</td>\n    </tr>\n    <tr>\n      <td>16</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>ORL</td>\n      <td>Magic</td>\n      <td>Pts</td>\n      <td>15.1</td>\n    </tr>\n    <tr>\n      <td>17</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>TOR</td>\n      <td>Raptors</td>\n      <td>Pts</td>\n      <td>14.2</td>\n    </tr>\n    <tr>\n      <td>18</td>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Assist</td>\n      <td>6.7</td>\n    </tr>\n    <tr>\n      <td>19</td>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Assist</td>\n      <td>6.6</td>\n    </tr>\n    <tr>\n      <td>20</td>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Assist</td>\n      <td>6.1</td>\n    </tr>\n    <tr>\n      <td>21</td>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>OKC</td>\n      <td>Thunder</td>\n      <td>Assist</td>\n      <td>5.0</td>\n    </tr>\n    <tr>\n      <td>22</td>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Assist</td>\n      <td>4.8</td>\n    </tr>\n    <tr>\n      <td>23</td>\n      <td>2017</td>\n      <td>Durant</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Assist</td>\n      <td>5.4</td>\n    </tr>\n    <tr>\n      <td>24</td>\n      <td>2015</td>\n      <td>Ibaka</td>\n      <td>OKC</td>\n      <td>Thunder</td>\n      <td>Assist</td>\n      <td>0.8</td>\n    </tr>\n    <tr>\n      <td>25</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>ORL</td>\n      <td>Magic</td>\n      <td>Assist</td>\n      <td>1.1</td>\n    </tr>\n    <tr>\n      <td>26</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>TOR</td>\n      <td>Raptors</td>\n      <td>Assist</td>\n      <td>0.7</td>\n    </tr>\n    <tr>\n      <td>27</td>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Rebound</td>\n      <td>5.4</td>\n    </tr>\n    <tr>\n      <td>28</td>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Rebound</td>\n      <td>4.5</td>\n    </tr>\n    <tr>\n      <td>29</td>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Rebound</td>\n      <td>5.1</td>\n    </tr>\n    <tr>\n      <td>30</td>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>OKC</td>\n      <td>Thunder</td>\n      <td>Rebound</td>\n      <td>8.2</td>\n    </tr>\n    <tr>\n      <td>31</td>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Rebound</td>\n      <td>8.3</td>\n    </tr>\n    <tr>\n      <td>32</td>\n      <td>2017</td>\n      <td>Durant</td>\n      <td>GSW</td>\n      <td>Warriors</td>\n      <td>Rebound</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>33</td>\n      <td>2015</td>\n      <td>Ibaka</td>\n      <td>OKC</td>\n      <td>Thunder</td>\n      <td>Rebound</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>34</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>ORL</td>\n      <td>Magic</td>\n      <td>Rebound</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>35</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>TOR</td>\n      <td>Raptors</td>\n      <td>Rebound</td>\n      <td>6.8</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n2. **Read the documentation and focus on the argument `value_vars`. How does `bball.melt(id_vars=[\"Year\", \"Player\"], value_vars=[\"Pts\", \"Rebound\"])` differ from `bball.melt(id_vars=[\"Year\", \"Player\"])`?**  \n\n\n```python\nbball.melt(id_vars=[\"Year\", \"Player\"], value_vars=[\"Pts\", \"Rebound\"])\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Year</th>\n      <th>Player</th>\n      <th>variable</th>\n      <th>value</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>Pts</td>\n      <td>30.1</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>Pts</td>\n      <td>25.3</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>Pts</td>\n      <td>26.4</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>Pts</td>\n      <td>28.2</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>Pts</td>\n      <td>25.1</td>\n    </tr>\n    <tr>\n      <td>5</td>\n      <td>2017</td>\n      <td>Durant</td>\n      <td>Pts</td>\n      <td>26.4</td>\n    </tr>\n    <tr>\n      <td>6</td>\n      <td>2015</td>\n      <td>Ibaka</td>\n      <td>Pts</td>\n      <td>12.6</td>\n    </tr>\n    <tr>\n      <td>7</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Pts</td>\n      <td>15.1</td>\n    </tr>\n    <tr>\n      <td>8</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Pts</td>\n      <td>14.2</td>\n    </tr>\n    <tr>\n      <td>9</td>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>Rebound</td>\n      <td>5.4</td>\n    </tr>\n    <tr>\n      <td>10</td>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>Rebound</td>\n      <td>4.5</td>\n    </tr>\n    <tr>\n      <td>11</td>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>Rebound</td>\n      <td>5.1</td>\n    </tr>\n    <tr>\n      <td>12</td>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>Rebound</td>\n      <td>8.2</td>\n    </tr>\n    <tr>\n      <td>13</td>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>Rebound</td>\n      <td>8.3</td>\n    </tr>\n    <tr>\n      <td>14</td>\n      <td>2017</td>\n      <td>Durant</td>\n      <td>Rebound</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>15</td>\n      <td>2015</td>\n      <td>Ibaka</td>\n      <td>Rebound</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>16</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Rebound</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>17</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Rebound</td>\n      <td>6.8</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nbball.melt(id_vars=[\"Year\", \"Player\"])\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Year</th>\n      <th>Player</th>\n      <th>variable</th>\n      <th>value</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>Team</td>\n      <td>GSW</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>Team</td>\n      <td>GSW</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>Team</td>\n      <td>GSW</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>Team</td>\n      <td>OKC</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>Team</td>\n      <td>GSW</td>\n    </tr>\n    <tr>\n      <td>5</td>\n      <td>2017</td>\n      <td>Durant</td>\n      <td>Team</td>\n      <td>GSW</td>\n    </tr>\n    <tr>\n      <td>6</td>\n      <td>2015</td>\n      <td>Ibaka</td>\n      <td>Team</td>\n      <td>OKC</td>\n    </tr>\n    <tr>\n      <td>7</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Team</td>\n      <td>ORL</td>\n    </tr>\n    <tr>\n      <td>8</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Team</td>\n      <td>TOR</td>\n    </tr>\n    <tr>\n      <td>9</td>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>TeamName</td>\n      <td>Warriors</td>\n    </tr>\n    <tr>\n      <td>10</td>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>TeamName</td>\n      <td>Warriors</td>\n    </tr>\n    <tr>\n      <td>11</td>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>TeamName</td>\n      <td>Warriors</td>\n    </tr>\n    <tr>\n      <td>12</td>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>TeamName</td>\n      <td>Thunder</td>\n    </tr>\n    <tr>\n      <td>13</td>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>TeamName</td>\n      <td>Warriors</td>\n    </tr>\n    <tr>\n      <td>14</td>\n      <td>2017</td>\n      <td>Durant</td>\n      <td>TeamName</td>\n      <td>Warriors</td>\n    </tr>\n    <tr>\n      <td>15</td>\n      <td>2015</td>\n      <td>Ibaka</td>\n      <td>TeamName</td>\n      <td>Thunder</td>\n    </tr>\n    <tr>\n      <td>16</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>TeamName</td>\n      <td>Magic</td>\n    </tr>\n    <tr>\n      <td>17</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>TeamName</td>\n      <td>Raptors</td>\n    </tr>\n    <tr>\n      <td>18</td>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>Games</td>\n      <td>79</td>\n    </tr>\n    <tr>\n      <td>19</td>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>Games</td>\n      <td>79</td>\n    </tr>\n    <tr>\n      <td>20</td>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>Games</td>\n      <td>51</td>\n    </tr>\n    <tr>\n      <td>21</td>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>Games</td>\n      <td>72</td>\n    </tr>\n    <tr>\n      <td>22</td>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>Games</td>\n      <td>62</td>\n    </tr>\n    <tr>\n      <td>23</td>\n      <td>2017</td>\n      <td>Durant</td>\n      <td>Games</td>\n      <td>68</td>\n    </tr>\n    <tr>\n      <td>24</td>\n      <td>2015</td>\n      <td>Ibaka</td>\n      <td>Games</td>\n      <td>78</td>\n    </tr>\n    <tr>\n      <td>25</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Games</td>\n      <td>56</td>\n    </tr>\n    <tr>\n      <td>26</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Games</td>\n      <td>23</td>\n    </tr>\n    <tr>\n      <td>27</td>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>Pts</td>\n      <td>30.1</td>\n    </tr>\n    <tr>\n      <td>28</td>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>Pts</td>\n      <td>25.3</td>\n    </tr>\n    <tr>\n      <td>29</td>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>Pts</td>\n      <td>26.4</td>\n    </tr>\n    <tr>\n      <td>30</td>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>Pts</td>\n      <td>28.2</td>\n    </tr>\n    <tr>\n      <td>31</td>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>Pts</td>\n      <td>25.1</td>\n    </tr>\n    <tr>\n      <td>32</td>\n      <td>2017</td>\n      <td>Durant</td>\n      <td>Pts</td>\n      <td>26.4</td>\n    </tr>\n    <tr>\n      <td>33</td>\n      <td>2015</td>\n      <td>Ibaka</td>\n      <td>Pts</td>\n      <td>12.6</td>\n    </tr>\n    <tr>\n      <td>34</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Pts</td>\n      <td>15.1</td>\n    </tr>\n    <tr>\n      <td>35</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Pts</td>\n      <td>14.2</td>\n    </tr>\n    <tr>\n      <td>36</td>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>Assist</td>\n      <td>6.7</td>\n    </tr>\n    <tr>\n      <td>37</td>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>Assist</td>\n      <td>6.6</td>\n    </tr>\n    <tr>\n      <td>38</td>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>Assist</td>\n      <td>6.1</td>\n    </tr>\n    <tr>\n      <td>39</td>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>Assist</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <td>40</td>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>Assist</td>\n      <td>4.8</td>\n    </tr>\n    <tr>\n      <td>41</td>\n      <td>2017</td>\n      <td>Durant</td>\n      <td>Assist</td>\n      <td>5.4</td>\n    </tr>\n    <tr>\n      <td>42</td>\n      <td>2015</td>\n      <td>Ibaka</td>\n      <td>Assist</td>\n      <td>0.8</td>\n    </tr>\n    <tr>\n      <td>43</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Assist</td>\n      <td>1.1</td>\n    </tr>\n    <tr>\n      <td>44</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Assist</td>\n      <td>0.7</td>\n    </tr>\n    <tr>\n      <td>45</td>\n      <td>2015</td>\n      <td>Curry</td>\n      <td>Rebound</td>\n      <td>5.4</td>\n    </tr>\n    <tr>\n      <td>46</td>\n      <td>2016</td>\n      <td>Curry</td>\n      <td>Rebound</td>\n      <td>4.5</td>\n    </tr>\n    <tr>\n      <td>47</td>\n      <td>2017</td>\n      <td>Curry</td>\n      <td>Rebound</td>\n      <td>5.1</td>\n    </tr>\n    <tr>\n      <td>48</td>\n      <td>2015</td>\n      <td>Durant</td>\n      <td>Rebound</td>\n      <td>8.2</td>\n    </tr>\n    <tr>\n      <td>49</td>\n      <td>2016</td>\n      <td>Durant</td>\n      <td>Rebound</td>\n      <td>8.3</td>\n    </tr>\n    <tr>\n      <td>50</td>\n      <td>2017</td>\n      <td>Durant</td>\n      <td>Rebound</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>51</td>\n      <td>2015</td>\n      <td>Ibaka</td>\n      <td>Rebound</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>52</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Rebound</td>\n      <td>6.8</td>\n    </tr>\n    <tr>\n      <td>53</td>\n      <td>2016</td>\n      <td>Ibaka</td>\n      <td>Rebound</td>\n      <td>6.8</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# for bball.melt(id_vars=[\"Year\", \"Player\"], value_vars=[\"Pts\", \"Rebound\"]), while we keep the columns Year and Player as\n# before, we also indicate which of the remaining columns to be considered in the two new column\n\n# thus, variable will only get Pts and Rebound from the remaining columns and values will take the values associated \n```\n\n3. **Consider the differences between `bball.stack` and `bball.melt`. Is there a way to make them generate the same output?  Write your thoughts.**\n  - Hint: you might need to use both `stack` and another method from above\n\n\n```python\n# bball.stack() also gives as results something similar to variables and values associated, but we don't have regular columns\n# plus we don't have an index \n\nbball.stack().reset_index().drop(\"level_0\", axis=1).rename(columns={\"level_1\":\"variable\", 0: \"value\"})\n#bball.melt()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>variable</th>\n      <th>value</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>Year</td>\n      <td>2015</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>Player</td>\n      <td>Curry</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>Team</td>\n      <td>GSW</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>TeamName</td>\n      <td>Warriors</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>Games</td>\n      <td>79</td>\n    </tr>\n    <tr>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <td>67</td>\n      <td>TeamName</td>\n      <td>Raptors</td>\n    </tr>\n    <tr>\n      <td>68</td>\n      <td>Games</td>\n      <td>23</td>\n    </tr>\n    <tr>\n      <td>69</td>\n      <td>Pts</td>\n      <td>14.2</td>\n    </tr>\n    <tr>\n      <td>70</td>\n      <td>Assist</td>\n      <td>0.7</td>\n    </tr>\n    <tr>\n      <td>71</td>\n      <td>Rebound</td>\n      <td>6.8</td>\n    </tr>\n  </tbody>\n</table>\n<p>72 rows \u00d7 2 columns</p>\n</div>\n\n\n\n## Exercise 3\n\n1. **Can you think of a reason to ever use `pivot` rather than `pivot_table`? Write your thoughts.**\n\nWhy use pivot rather than pivot_table ? \\\nReminders: \n- The pivot method:\n    - takes the unique values of one column and places them along the index.\n    - Takes the unique values of another column and places them along the columns.\n    - Takes the values that correpsond to a third column and fills in the DataFrame values that correspond to that index / column pair\n- The pivot_table method:\n    - It allows you to choose multiple columns for the index/columns/values\n  arguments.\n    - It allows you to deal with duplicate entries by\n  having you choose how to combine them.  \n  \npivot_table deals with non-unique values. This can be risky for instance here, it would aggregate the two different values for (IBAKA 2016) in a probably wrong way. For instance, if the aggregator is a mean, the two part of the season in which IBAKA played for different team would be given the same weight, which is probably not the case IRL. \n\n2. **Create a pivot table with column `Player` as the index, `TeamName` as the columns, and `[Rebound, Assist]` as the values. What happens when you use `aggfunc=[np.max, np.min, len]`?**  \n\n\n```python\nbball.pivot_table(index=\"Player\", columns=\"TeamName\", values=[\"Rebound\",\"Assist\"])\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n\n    .dataframe thead tr:last-of-type th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th colspan=\"4\" halign=\"left\">Assist</th>\n      <th colspan=\"4\" halign=\"left\">Rebound</th>\n    </tr>\n    <tr>\n      <th>TeamName</th>\n      <th>Magic</th>\n      <th>Raptors</th>\n      <th>Thunder</th>\n      <th>Warriors</th>\n      <th>Magic</th>\n      <th>Raptors</th>\n      <th>Thunder</th>\n      <th>Warriors</th>\n    </tr>\n    <tr>\n      <th>Player</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>Curry</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6.466667</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>5.00</td>\n    </tr>\n    <tr>\n      <td>Durant</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>5.0</td>\n      <td>5.100000</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>8.2</td>\n      <td>7.55</td>\n    </tr>\n    <tr>\n      <td>Ibaka</td>\n      <td>1.1</td>\n      <td>0.7</td>\n      <td>0.8</td>\n      <td>NaN</td>\n      <td>6.8</td>\n      <td>6.8</td>\n      <td>6.8</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nbball.pivot_table(index=\"Player\", columns=\"TeamName\", values=[\"Rebound\",\"Assist\"], aggfunc=[np.max, np.min, len])\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n\n    .dataframe thead tr:last-of-type th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th colspan=\"8\" halign=\"left\">amax</th>\n      <th colspan=\"5\" halign=\"left\">amin</th>\n      <th colspan=\"8\" halign=\"left\">len</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th colspan=\"4\" halign=\"left\">Assist</th>\n      <th colspan=\"4\" halign=\"left\">Rebound</th>\n      <th colspan=\"2\" halign=\"left\">Assist</th>\n      <th>...</th>\n      <th colspan=\"2\" halign=\"left\">Rebound</th>\n      <th colspan=\"4\" halign=\"left\">Assist</th>\n      <th colspan=\"4\" halign=\"left\">Rebound</th>\n    </tr>\n    <tr>\n      <th>TeamName</th>\n      <th>Magic</th>\n      <th>Raptors</th>\n      <th>Thunder</th>\n      <th>Warriors</th>\n      <th>Magic</th>\n      <th>Raptors</th>\n      <th>Thunder</th>\n      <th>Warriors</th>\n      <th>Magic</th>\n      <th>Raptors</th>\n      <th>...</th>\n      <th>Thunder</th>\n      <th>Warriors</th>\n      <th>Magic</th>\n      <th>Raptors</th>\n      <th>Thunder</th>\n      <th>Warriors</th>\n      <th>Magic</th>\n      <th>Raptors</th>\n      <th>Thunder</th>\n      <th>Warriors</th>\n    </tr>\n    <tr>\n      <th>Player</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>Curry</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6.7</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>5.4</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>4.5</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>3.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>3.0</td>\n    </tr>\n    <tr>\n      <td>Durant</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>5.0</td>\n      <td>5.4</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>8.2</td>\n      <td>8.3</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>8.2</td>\n      <td>6.8</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>2.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>2.0</td>\n    </tr>\n    <tr>\n      <td>Ibaka</td>\n      <td>1.1</td>\n      <td>0.7</td>\n      <td>0.8</td>\n      <td>NaN</td>\n      <td>6.8</td>\n      <td>6.8</td>\n      <td>6.8</td>\n      <td>NaN</td>\n      <td>1.1</td>\n      <td>0.7</td>\n      <td>...</td>\n      <td>6.8</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n<p>3 rows \u00d7 24 columns</p>\n</div>\n\n\n", "meta": {"hexsha": "7ab737682c8e739970283826fd784d528c6759e7", "size": 127919, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Session_7/6_reshape_exercises.ipynb", "max_stars_repo_name": "remi-sudo/Classes", "max_stars_repo_head_hexsha": "71497927ed4d54ddf6fd5abe2ddabb5966eb0304", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Session_7/6_reshape_exercises.ipynb", "max_issues_repo_name": "remi-sudo/Classes", "max_issues_repo_head_hexsha": "71497927ed4d54ddf6fd5abe2ddabb5966eb0304", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Session_7/6_reshape_exercises.ipynb", "max_forks_repo_name": "remi-sudo/Classes", "max_forks_repo_head_hexsha": "71497927ed4d54ddf6fd5abe2ddabb5966eb0304", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9433427762, "max_line_length": 350, "alphanum_fraction": 0.3294428506, "converted": true, "num_tokens": 25163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936413143782797, "lm_q2_score": 0.07696084045948635, "lm_q1q2_score": 0.027656965586448562}}
{"text": "# Practical Characterization and Control of Quantum Systems\n\n## Christopher Granade<br /> Institute for Quantum Computing\n\n**Joint Work with** Christopher Ferrie, Nathan Wiebe, Ian Hincks, Troy Borneman and D. G. Cory\n\n### Abstract\n\nAs quantum information processing experiments grow in scale and complexity,\nnew techniques are required to characterize and control quantum devices.\nHere, we provide an algorithm for applying Bayesian techniques to\nquantum information processing experiments.\nWe introduce and demonstrate an open-source software library implementing our\napproach and show an example of these advances as applied in nitrogen vacancy\ncenters.\n\nWe also discuss advances in control, demonstrating an algorithm for\nincorporating realistic physical models of non-linear systems\ninto the design of control sequences.\nFinally, we show how both of these algorithms can be extended\nwith the use of quantum resources to allow for application\nto much larger systems.\n\nSlides and references are available at [https://www.cgranade.com/research/talks/sandia-2014/](https://www.cgranade.com/research/talks/sandia-2014/).\n\nReferences like `10/abc` can be looked up using `http://doi.org/abc`.\n$\\renewcommand{\\vec}[1]{\\boldsymbol{#1}}$\n$\\renewcommand{\\matr}[1]{\\mathbf{#1}}$\n$\\newcommand{\\bra}[1]{\\left\\langle#1\\right|}$\n$\\newcommand{\\ket}[1]{\\left|#1\\right\\rangle}$\n$\\newcommand{\\braket}[2]{\\left\\langle#1\\mid#2\\right\\rangle}$\n$\\newcommand{\\dd}{\\mathrm{d}}$\n$\\newcommand{\\ii}{\\mathrm{i}}$\n$\\newcommand{\\ee}{\\mathrm{e}}$\n$\\newcommand{\\expect}{\\mathbb{E}}$\n$\\newcommand{\\matr}[1]{\\mathbf{#1}}$\n$\\newcommand{\\T}{\\mathrm{T}}$\n$\\newcommand{\\Cov}{\\operatorname{Cov}}$\n$\\newcommand{\\Tr}{\\operatorname{Tr}}$\n$\\newcommand{\\real}{\\mathbb{R}}$\n$\\renewcommand{\\Re}{\\operatorname{Re}}$\n\n## Compling and Hosting\n\nTo compile these slides, we use **nbconvert**.\n\n\n```\n!ipython nbconvert --to slides --template slides.tpl slides.ipynb\n!mv slides.slides.html slides.html\n```\n\n    [NbConvertApp] Using existing profile dir: u'/home/cgranade/.config/ipython/profile_default'\r\n    [NbConvertApp] Converting notebook slides.ipynb to slides\r\n    [NbConvertApp] Support files will be in slides_files/\r\n    [NbConvertApp] Loaded template slides.tpl\r\n    [NbConvertApp] Writing 378978 bytes to slides.slides.html\r\n\n\nIf you want to view them in your browser complete with speaker notes, remote control support, etc., then you need to host the slides. The [instructions for Reveal.js](https://github.com/hakimel/reveal.js/#full-setup) include directions for hosting via a library called Grunt. Unfortunately, this doesn't work well with [remot.io](http://remot.io/), as that tool requires that you serve from port 80.\n\n## Configuration\n\nSince we're going to display some ``'.format(src))\n```\n\n# Introduction\n\nThis talk will proceed in two parts:\n\n- Using sequential Monte Carlo for practical characterization\n- Extending optimal control theory algorithms to include realistic models of classical electronics\n\n# Part 1: Practical Characterization\n\n## Limits of Traditional Characterization\n\nQuantum information experiments are pushing the limits of traditional characterization techniques.\n\n- Large numbers of parameters to estimate.\n- Errors in estimated parameters can be highly correlated.\n- Can be hard to extract confidence and credible regions.\n- Can be difficult to incorporate practical experimental effects.\n\n## Example: Hyperfine Measurement in NV Centers\n\n<figure>\n\n<figcaption>Image courtesy of Ian Hincks.</figcaption>\n</figure>\n\nElectronic spin $\\vec{S}$ in NV center coupled to a nearby carbon spin $\\vec{I}$:\n$$\nH = \\Delta_{\\text{zfs}} S_z^2 + \\gamma_e (\\vec{B} + {\\color{red} \\vec{\\delta B}}) \\cdot \\vec{S} + \\gamma_C (\\vec{B} + {\\color{red} \\vec{\\delta B}}) \\cdot \\vec{I} + \\vec{S} \\cdot {\\color{red} \\mathbf{A}} \\cdot \\vec{I},\n$$\n\n${\\color{red} \\vec{\\delta B}}$ causes large errors in ${\\color{red} \\matr{A}}$, making it difficult to characterize $H$ using spectroscopic methods.\n\n## Enabling Characterization with Simulation\n\nBayes' Rule relates estimation to <span style=\"color: red\">simulation<span>:\n\n$$\n    \\Pr(\\text{hypothesis} | \\text{data}) = \\frac{\\color{red}{\\Pr(\\text{data} | \\text{hypothesis})}}{\\Pr(\\text{data})} \\Pr(\\text{hypothesis})\n$$\n\nThe posterior distribution describes what we learn from our data about hypotheses.\n\n$\\Rightarrow$ Practical characterization can be enabled using *sequential Monte Carlo*.\n\n- Classical Bayesian algorithm\n- Uses *simulation* to *estimate* parameters\n- Numerical algorithm\u2014 doesn't assume analytic solution\n\n\nFor instance, to learn about a Hamiltonian $H$ given a measurement $d$:\n\n$$\\begin{align}\n\\Pr(H) & \\approx \\sum_{i=0}^N w_i \\delta(H - H_i) \\\\\n\\Pr(H | d) & \\approx \\sum_{i=0}^N w_i \\delta(H - H_i) \\times \\Pr(d | H_i) / \\mathcal{N}\n\\end{align}$$\n\n$\\mathcal{N}$: normalization factor (can be found implicitly)\n\nSet $w_i \\gets w_i \\Pr(d | H_i) / \\mathcal{N}$ to be new prior.\n\n- **Iterative** $\\Rightarrow$ SMC can be used *online* as data arrives.\n- Also reduces overhead for postprocessing large datasets.\n\nEstimate of $H$ is then\n$$\n\\hat{H} = \\expect[H] = \\sum_i w_i H_i.\n$$\n\n(Doucet et al., Stat. & Comp. **10** 3 197-208; Husz\u00e1r and Houlsby, PRA **85** 052120; Granade et al. [10/s86](http://doi.org/s86), NJP **14** 10 103013 [10/s87](http://doi.org/s87))\n\n### Generality of Simulation-Based Characterization\n\nSimulation $\\Pr(d|H_i)$ with hypothesis $H_i$ allows for additional experimental details in our simulation, at the trade off of computational cost.\n\nExamples:\n\n- Finite and unknown $T_1$, $T_2$.\n- Unknown visibility.\n- Uncertainty in control fields.\n\n## Parameter Reduction\n\nWe often need not consider all possible Hamiltonians, but can consider a set of physically reasonable Hamiltonians.\n\nLet $H = H(\\vec{x})$ be a *parameterization*, where $\\vec{x} \\in \\real^d$.\n\nExample (*Ising model*):\n\n$$\nH(\\vec{x}) = \\sum_{\\langle i,j \\rangle} x_{i,j} \\sigma_z^{(i)} \\sigma_z^{(j)}\n$$\n\n## Prior Knowledge\n\nSMC is Bayesian, and thus incorporates prior knowledge.\n\nModeled by a *prior distribution* $\\Pr(\\vec{x}) := \\pi(\\vec{x})$.\n\nExamples:\n\n- Secondary experiment gives rough estimate of a parameter.\n- Physical arguments place limits on feasible parameter values.\n- *Ab initio* calculations give expected range for parameters.\n\n## Characterizing Uncertainty\n\nSince we have the posterior, we can calculate the mean and covariance easily:\n\n$$\\begin{align}\n    \\expect[\\vec{x}] & = \\sum_i w_i \\vec{x}_i \\\\\n    \\Cov(\\vec{x}) & = \\expect[\\vec{x}\\vec{x}^\\T] - \\expect[\\vec{x}]\\expect[\\vec{x}]^\\T\n\\end{align}$$\n\n- SMC replaces integrals over $\\Pr(\\vec{x})$ with finite sums.\n- Covariance describes uncertainty in estimate.\n\n### Ambiguity in Approximation\n\n\n```\nfrom numpy.random import multivariate_normal\nfrom scipy.stats import norm\n```\n\n\n```\nxs, ys = multivariate_normal([0, 0], identity(2), size=(200,)).T\nxs2, ys2 = 8 * np.random.random((2, 200)) - 4\n\nfigure(figsize=(12,6))\nsubplot(1,2,1); scatter(xs, ys); ylim(-4, 4)\nsubplot(1,2,2); scatter(xs2, ys2, s=norm.pdf(xs2) * norm.pdf(ys2) * 1000);\n```\n\n### Avoiding Impoverishment\n\n- The number of samples $N$ must be large to represent $\\Pr(\\vec{x} | \\text{data})$.\n- As more data is collected, posterior becomes sharper.\n- Initial particles are unlikely to have support in posterior, reducing *effective* $N$.\n\nSolution: **resampling**. Replace SMC samples with different samples that better represent the same distribution.\n\nUses that information can be stored in weights $\\{w_i\\}$ or positions $\\{\\vec{x}_i\\}$.\n\n### Liu-West Resampling Algorithm\n\n- Sample new $\\vec{x}_i'$ from kernel density estimate such that $\\expect[\\vec{x}]$ and $\\Cov(\\vec{x})$ are preserved.\n- Set new weights to uniform $w_i' = 1/ N$.\n\nLiu-West distribution:\n$$\n    \\Pr(\\vec{x}'_i) = \\sum_i w_i \\frac{1}{\\sqrt{(2\\pi)^k |\\matr{\\Sigma}|}} \\exp\\left(\n        -\\frac{1}{2} (\\vec{x}' - \\vec{\\mu}_i)^\\T \\matr{\\Sigma}^{-1} (\\vec{x}' - \\vec{\\mu}_i)\n    \\right)\n$$\nwhere\n$$\\begin{align*}\n    \\vec{\\mu}_i & = a \\vec{x}_i + (1 - a) \\expect[\\vec{x}] \\\\\n    \\matr{\\Sigma} & = (1- a^2) \\Cov[\\vec{x}] \\\\\n    a & \\in [0, 1],\n\\end{align*}$$\n\n(West, J. Royal Stat B **55** 2 409-422; Liu and West 2001)\n\n## Putting it Together: The SMC Algorithm\n\n1. Draw $N$ \"particles\" $\\{\\vec{x}\\}_{i=0}^{N-1}$ from $\\pi(\\vec{x})$.\n2. Set $w_i = 1 / N$ for each particle.\n3. For each new measurement $d$:\n\n    a. Let $w_i \\gets w_i \\Pr(d | \\vec{x}_i)$.\n    b. Normalize $w_i$ to be a distribution.\n    c. If $1 / \\sum_i w_i^2 < 0.5 N$, resample.\n    \n(Doucet et al., Stat. & Comp. **10** 3 197-208)\n\n## Software Implementation\n\n\n```\nprior = UniformDistribution([[0.9, 1], [0.4, 0.5], [0.5, 0.6]])\nupdater = SMCUpdater(\n    RandomizedBenchmarkingModel(), 10000,\n    prior, resampler=LiuWestResampler()\n)\n\n# As data arrives:\n# updater.update(datum, experiment)\n```\n\n(Granade et al., [arXiv:1404.5275](https://scirate.com/arxiv/1404.5275); [github.com/csferrie/python-qinfer](https://github.com/csferrie/python-qinfer))\n\nProvides an infrastructure for rapidly deploying SMC. User defines:\n\n- Parameterization of model and experiments\n- Possible outcomes\n- Likelihood of data\n\n### Built-In Plotting\n\n\n```\nupdater.plot_posterior_contour(0, 1, res1=50, res2=50)\n```\n\n### Built-In Plotting\n\n\n```\nupdater.plot_posterior_marginal(0)\nylim(ymin=0)\n```\n\n### Estimation\n\n**QInfer** handles drawing estimates from the current SMC distribution:\n\n\n```\nprint updater.est_mean()\nprint sqrt(diag(updater.est_covariance_mtx()))\nprint updater.est_entropy()\n```\n\n    [ 0.95020288  0.45062089  0.5505005 ]\n    [ 0.02895919  0.02872952  0.02877011]\n    9.21034037198\n\n\n## Region Estimation\n\nCredible region $X_{\\alpha}$: $\\Pr(\\vec{x} \\in X_{\\alpha}) \\ge \\alpha$\n\nSeveral ways to choose $X_{\\alpha}$:\n\n- covariance ellipses\u2014 if approx. normal\n- convex hulls\u2014 very general, but long description\n- minimum volume enclosing ellipse (MVEE) for the hull\u2014 approximate, but easy to represent\n\n\n```\ncov = updater.est_covariance_mtx()\nhull_faces, hull_vertices = updater.region_est_hull()\nellipse_mtx, ellipse_centroid = updater.region_est_ellipsoid()\n```\n\n(Granade et al., NJP **14** 10 103013 [10/s87](http://doi.org/s87); Ferrie, NJP **16** 2 023006 [10/tb4](http://doi.org/tb4))\n\n## State-Space Methods\n\nSMC can also be used to *track* the state of a parameter that fluctuates in time.\n\n\n\nHere, the true value of $\\omega$ is drawn from a Gaussian process. After each measurement, SMC particles are *moved* to track $\\omega$, $\\vec{x}(t_{k + 1}) \\sim \\mathrm{N}(\\vec{x}(t_k), \\sigma^2)$.\n\n(Doucet and Johansen 2011)\n\n## Robustness of SMC: Finite Sampling\n\nWhen using SMC without exact likelihoods, finite sampling of simulator introduces finite error $\\epsilon$:\n\n$$\n    w_i \\mapsto w_i (\\Pr(d | \\vec{x}_i) + \\epsilon) / \\mathcal{N}\n$$\n\n**Example** (noisy coin): risk for 1000 experiments vs number of samples.\n\n\n\n(Ferrie and Granade 2014, PRL **112** 13 130402 [10/tdj](http://doi.org/tdj))\n\n## Robustness of SMC: Incorrect Model\n\nWe also want SMC to be robust against errors in the simulator. Below: risk when Ising simulator neglects terms of order $10^{-4}$.\n\n\n\n(Wiebe et al. PRA **89** 4 042314 [10/tdk](http://doi.org/tdk))\n\n## Other Features\n\n- Model selection and (coming soon) model-averaged estimation\n- Parallelization with IPython\n- Example of GPU-based model\n- Improved resampling\n- Robustness-testing tools (ex.: erroneous models)\n\n### Documentation\n\n\n```\niframe(\"http://python-qinfer.readthedocs.org/en/latest/\")\n```\n\n\n\n\n\n\n\n\n## SMC and QInfer in Action: Randomized Benchmarking\n\nRandomized benchmarking: apply random Clifford gates $\\{S_i\\}$ to learn average fidelity of a gateset $\\{U_j\\}$:\n\n\n\n\n## SMC and QInfer in Action: Randomized Benchmarking\n\n- Fidelity exposed as *decay* of survival probability $\\Tr(ES_{\\vec{i}}[\\rho])$; removes effect of preparation $\\rho$ and measurement $E$ (SPAM).\n- Can interleave with gate of interest.\n- Least-squares fitting often used to extract fidelity.\n\n\n\n(Knill et al., PRA **77** 1 012307 [10/cxz9vm](http://doi.org/cxz9vm); Magesan et al., PRL **109** 8 080505 [10/s8j](http://doi.org/s8j))\n\n## SMC and QInfer in Action: Randomized Benchmarking\n\nSMC can be used to accelerate interleaved RB experiments.\n\n- Interpret randomized benchmarking as a **likelihood**.\n\n**Example** (zeroth-order model):\n$$\n\\Pr(\\text{survival} | A, B, \\tilde{p}, p_{\\text{ref}}; m, \\text{mode}) = \\begin{cases}\n    A (\\tilde{p} p_{\\text{ref}})^m + B & \\text{interleaved} \\\\\n    A (p_{\\text{ref}})^m + B           & \\text{reference}\n\\end{cases}\n$$\n\n- $\\tilde{p}$ and $p_{\\text{ref}}$: interleaved and reference depolarizing parameters (resp)\n- $A$ and $B$: constants describing SPAM\n\nAdvantages:\n\n- $0 \\le p_{\\text{ref}}, \\tilde{p} \\le 1$ manifest in prior\u2014 avoids instability as $\\tilde{p} \\to 1$.\n- Using prior information and correlations between different data can drastically reduce data requirements.\n\n## SMC and QInfer in Action: Randomized Benchmarking\n\nStraightfoward to implement in QInfer:\n\n\n```\nfrom qinfer.abstract_model import Model\n\nclass RandomizedBenchmarkingModel(Model):\n    # ...\n    \n    def likelihood(self, outcomes, modelparams, expparams):\n        p_tilde, p, A, B = modelparams.T[:, :, np.newaxis]\n        \n        p_C = p_tilde * p\n        p = np.where(expparams['reference'][np.newaxis, :], p, p_C)\n        \n        m = expparams['m'][np.newaxis, :]\n        \n        pr0 = 1 - (A * (p ** m) + B)\n        \n        return Model.pr0_to_likelihood_array(outcomes, pr0)\n    \n    # ...\n```\n\n(*Granade* et al., [arXiv:1404.5275](https://scirate.com/arxiv/1404.5275))\n\n## SMC and QInfer in Action: Randomized Benchmarking\n\n\n\n\n(Left: $m = 1, 2, \\dots, 100$; Right: $10^3$ shots/sequence length, $m = 1, 11, \\dots, m_{\\max}$)\n\n## SMC and QInfer in Action: Hyperfine Measurement\n\nWith SMC, we can easily integrate data from many different kinds of measurements and control parameters:\n\n- Rabi, Ramsey and SPAM experiments\n- Several different $\\vec{B}$ fields\n\nExperimental variety is a resource for decorrelating errors in static controls from hyperfine parameters.\n\n\nElectronic spin in an NV center coupled to a nitrogen spin:\n$$\nH = \\Delta_{\\text{zfs}} S_z^2 + \\gamma_e (\\vec{B} + \\vec{\\delta B}) \\cdot \\vec{S} + \\gamma_N (\\vec{B} + \\vec{\\delta B}) \\cdot \\vec{I}_N + {A}_N S_z I_{N,z}\n$$\nUsing 5000 particles, we can get accurate estimates of both $\\vec{\\delta B}$ and $\\matr{A}_N$. Shown below for 163M total shots (about 300k photons).\n\n\n\nSimulations show that we can hyperfine couplings to carbon spins as well:\n\n\n\n# Part 2: Control of Quantum Devices with Non-Linear Electronics\n\n## Pulse Engineering\n\nModern optimal control theory (OCT) algorithms allow for designing pulses with many desired properties, including\n\n- Robustness to distributions over Hamiltonians\n- Bandwidth and power limits\n- Ringdown compensation\n\nUtility functional:\n$$\\begin{align*}\n    \\Phi(\\vec{p}) & = \\Tr(U_{\\text{target}}^{\\dagger} U(\\vec{p})) / \\dim^2\\mathcal{H}, \\text{where} \\\\\n    U(\\vec{p}) & := \\prod_{i=N}^{1} \\ee^{-\\ii \\Delta t (H_0 + \\sum_{k=1}^K p_{i,k} H_k)}\n\\end{align*}$$\n\n- $H_0$: internal Hamiltonian\n- $\\{H_k\\}$: control Hamiltonians\n- $\\Delta t$: timestep\n\n## GRAPE\n\n\n\n*Gradient-ascent pulse engineering* (GRAPE) is a commonly used OCT algorithm.\n\n- Provides fast evaluation of $\\vec{\\nabla}\\Phi$.\n- Uses gradient-ascent or conjugate-gradient to maximize $\\Phi$.\n\nHowever, GRAPE assumes linearity of classical control electronics (transfer function).\n\n(Khaneja et al., JMR **172** 2 296-305 [10/cg8cdh](http://doi.org/cg8cdh))\n\n### Calculating Gradients\n\nKhaneja gives the gradients wrt the controls $\\{p_k(t)\\}$ in terms of unitary time steps:\n\n$$\\begin{align}\n    \\frac{\\partial \\Phi}{\\partial p_k(t_j)} & = -2 \\Re\\left\\{\\braket{P_j}{\\ii \\Delta t\\, H_k X_j} \\braket{X_j}{P_j} \\right\\} \\\\\n    X_j & := U_j \\cdots U_1 \\\\\n    P_j & := U_{j+1}^\\dagger \\cdots U_{n}^\\dagger U_{\\text{target}} \\\\\n    U_j & := \\exp\\left(-\\ii \\Delta t (H_0 + \\sum_{k=1}^{K} p_k(t_j) H_k )\\right)\n\\end{align}$$\n\n### Nonlinear Conjugate Gradient Method\n\n1. Choose initial pulse $\\vec{p}$.\n2. Let $\\beta = 0$, $\\vec{s} = 0$.\n3. Until utility goal is met:\n    1. Calculate $\\Phi(\\vec{p})$, $\\vec{\\nabla}\\Phi(\\vec{p})$.\n    2. Update $\\beta$ using Polak\u2013Ribi\u00e8re formula.\n    3. $\\vec{s} \\gets -\\vec{\\nabla}\\Phi + \\beta \\vec{s}$.\n    4. Search along $\\vec{s}$, $\\vec{p} + \\alpha \\vec{s}$ for a step size $\\alpha > 0$.\n    5. $\\vec{p} \\gets \\vec{p} + \\alpha \\vec{s}$\n    \nGradient information used to update search directions, line search used to determine step sizes.\n\n## Example: Non-Linear Resonators\n\nSuperconducting resonators admit *kinetic inductance* $L = L(I_L) = L_0 (1 + \\alpha_L \\|I_L\\|^2)$ and a nonlinear resistance $R = R(I_R) = R_0 (1 + \\alpha_L \\|I_R\\|^\\eta)$.\n\n<figure>\n\n<figcaption>Image courtesy of Ian Hincks.</figcaption>\n</figure>\n\n(Maas 2003; Benningshof et al., JMR **230** 84-87 [10/s8m](http://doi.org/s8m); Mohebbi et al., JAP **115** 9 094502 [10/s8n](http://doi.org/s8n))\n\nTherefore, the resonance frequency, quality factor and coupling are all functions of current, frustrating linear approximations.\n\n## Distortions\n\nLet $\\vec{p}$ be a discretization of $p_k(t)$. Then, the effect of classical electronics (e.g.: a high-$Q$ resonator) can be modeled as an *operator* $g : \\vec{p} \\mapsto \\vec{q}$.\n\n<figure>\n\n<figcaption>Image courtesy of Ian Hincks.</figcaption>\n</figure>\n\nSince $\\vec{\\nabla}_\\vec{p}\\Phi(g[\\vec{p}]) = \\vec{\\nabla}_\\vec{q}\\Phi(\\vec{q}) \\cdot J_g(\\vec{p})$, if we can find the Jacobian of a distortion operator, we can include it into GRAPE.\n\n- Control search is thus for un-distorted pulse.\n- Can get higher fidelity controls by including distortion.\n- Allows driving at higher powers\u2014 don't need to limit to linear regime.\n\n## Simulation of Non-Linear Control Systems\n\nIncluding the nonlinear inductance and resistance gives us a system of differential equations\n$$\\begin{align}\n    \\frac{\\dd}{\\dd t} \\left[\\begin{matrix}\n        I_L \\\\ V_{C_m} \\\\ V_{C_t}\n    \\end{matrix}\\right] & = \\matr{A}(I_L, I_R) \\left[\\begin{matrix}\n        I_L \\\\ V_{C_m} \\\\ V_{C_t}\n    \\end{matrix}\\right] + \\vec{y} V_s(t),\n\\end{align}$$\nwhere $\\matr{A}$ and $\\vec{y}$ describe the circuit and driving term, respectively.\n\nThis system is nonlinear since $\\matr{A} = \\matr{A}(I_L, I_R)$.\n\n**Note**: rescaling the driving term does not just rescale the output current.\n\n## Simulation of Non-Linear Control Systems\n\nTo simulate the distortion introduced by this system, we let $g : \\vec{V}_s \\mapsto \\vec{I}_L$ be the solution to the DEs for a given driving term.\n\nThe Jacobian can then be approximated perturbatively,\n$$\n    \\frac{\\partial g_{m,l}}{\\partial p_{n,k}} \\approx \\left[\\frac{g(\\vec{p} + \\epsilon \\vec{e}_{n,k}) - g(\\vec{p})}{\\epsilon}\\right].\n$$\n\nTaking a small $\\epsilon$ allows us to find a good direction for the conjugate gradient step.\n\n## Example: Finding a $\\pi/2)_x$ Gate\n\nFor a strongly non-linear resonator, we find the following 99.1% fidelity $\\pi/2)_x$ gate using GRAPE. The un-distorted pulse is shown in red.\n\n<figure>\n\n\n</figure>\n\n## Robustness to Distributions\n\nWe want to relax that $H_0$ and $\\{H_k\\}$ be known with certainty.\n\nLet $\\overline{\\Phi} = \\expect_{H_0, \\{H_k\\}}[\\Phi]$\n\n- $H_0$: internal\n- $\\{H_k\\}$: control\n\nBy linearity of $\\expect$: $$\n    \\vec{\\nabla}_\\vec{p} \\overline{\\Phi}(g[\\vec{p}]) = \\expect_{H_0, \\{H_k\\}} [\\vec{\\nabla}_{\\vec{q}} \\Phi(\\vec{q})] \\cdot J_g(\\vec{p})\n$$\n\nTo optimize pulses for $\\overline{\\Phi}$, we represent $\\Pr(H_0, \\{H_k\\}) =: \\Pr(H_0(\\vec{x}), \\{H_k(\\vec{x})\\}) \\approx \\sum_i w_i \\delta(\\vec{x} - \\vec{x}_i)$.\n\n > Robust GRAPE thus can take an SMC approximation as input.\n\n(Borneman et al., JMR **225** 120-129 [10/cksg3v](http://doi.org/cksg3v))\n\n## Ringdown Optimization and Heuristic\n\nDecay dominated by $\\ee^{-t / t_c}$, even in non-linear case. Can add a timestep $p(t_{i+1}) = -g[\\vec{p}](t_i)/(\\ee^{\\delta t / t_c} - 1)$ to drive pulse ringdown to zero.\n\n- For non-linear, only an approximation.\n- Multiple steps or optimization can improve ringdown compensation.\n\nUsing two timesteps for compensation:\n\n\n\n\n(Borneman and Cory, JMR **207** 2 220-233 [10/s8p](http://doi.org/s8p))\n\n## Putting it Together: Robust Pulses for Non-Linear Resonators\n\nUsing these techniques, we can readily design a pulse that is robust over $\\pm 2\\text{ MHz}$ in the static field ($\\delta\\omega$) and several percent in the control fields $\\kappa$. \n<figure>\n\n</figure>\n\n# Conclusions\n\n- Bayesian methods allow for including prior information in characterization\n    - Simulation is a resource for inference\n- SMC allows for using Bayesian inference in a *practical* manner\n    - Robust to common errors (finite sampling, approximations in simulation)\n- Can extend GRAPE with simulations of classical systems\n    - Allows for control of even strongly non-linear devices\n- GRAPE can optimize over SMC-like distributions for practical control.\n\n# References\n\nFull reference information is available on [Zotero](https://www.zotero.org/cgranade/items/collectionKey/2NQVPRK9).\n\n\n```\niframe('https://www.zotero.org/cgranade/items/collectionKey/VSWSNCCA')\n```\n\n\n\n\n\n\n\n\n# Thank You\n", "meta": {"hexsha": "0a64d4589173f8c7e855ab7b51717a14891480a3", "size": 168159, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "research/talks/sandia-2014/slides.ipynb", "max_stars_repo_name": "cgranade/cgranade.github.io", "max_stars_repo_head_hexsha": "72f263c2cc03a14a5fa853cb7b7b53a5b57626c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-10-28T12:36:06.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-25T17:07:58.000Z", "max_issues_repo_path": "research/talks/sandia-2014/slides.ipynb", "max_issues_repo_name": "cgranade/cgranade.github.io", "max_issues_repo_head_hexsha": "72f263c2cc03a14a5fa853cb7b7b53a5b57626c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-05-08T10:00:27.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-08T10:00:27.000Z", "max_forks_repo_path": "research/talks/sandia-2014/slides.ipynb", "max_forks_repo_name": "cgranade/cgranade.github.io", "max_forks_repo_head_hexsha": "72f263c2cc03a14a5fa853cb7b7b53a5b57626c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-05-11T00:23:22.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-08T04:59:18.000Z", "avg_line_length": 95.9264118654, "max_line_length": 62197, "alphanum_fraction": 0.8234052296, "converted": true, "num_tokens": 6330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814501625211, "lm_q2_score": 0.06371499780770398, "lm_q1q2_score": 0.027651127145689226}}
{"text": "# COBRAme Reaction Buidling\n\n\n```python\nimport cobrame\nfrom cobrame.util import dogma, building\nimport cobra\nimport cobra.test\nfrom collections import defaultdict\n\n#import warnings\n#warnings.filterwarnings('ignore')\n```\n\n    /home/sbrg-cjlloyd/cobrapy/cobra/io/sbml3.py:24: UserWarning: Install lxml for faster SBML I/O\n      warn(\"Install lxml for faster SBML I/O\")\n    /home/sbrg-cjlloyd/cobrapy/cobra/io/__init__.py:12: UserWarning: cobra.io.sbml requires libsbml\n      warn(\"cobra.io.sbml requires libsbml\")\n\n\n## Overview\n\nCOBRAme is constructed entirely over COBRApy. This means that ME reactions will have all of the same properties, methods, and functions as a COBRApy reaction. However, one key difference is that, in order to facilliate the template nature of many gene expression reactions, reactions are constructed and their components are manipulated via the use of the ProcessData classes. These act as information vessels for holding the information assocatied with a cellular process in simple, standard datatypes such as dictionaries and strings. \n\n-----\n\nThis tutorial will go step-by-step through the process of creating the generic enzyme catalyzed reaction or metabolic reaction:\n$$ a \\rightarrow b $$\nthat requires the formation of **complex\\_ab** in order to proceed\n\n-------\n\nIn order for this reaction to carry flux in the model we will additionally need to first add the corresponding:\n1. Transcription reactions\n2. Translation reactions\n3. tRNA charging reactions\n4. Complex formation reactions\n\nOnce these are added we will add in synthesis of key macromolecular components (ribosome, RNA polymerase, etc.) and show how they are applied to their respective reactions with their coupling constraints implemented.\n\n## Initializing new ME-models\n\nWhen applying some constraints in the ME-model, metabolite properties are required. For instance, to calculate the total biomass produced by a particular reaction, the amino acid, nucleotide, etc. molecular weights are required.To enable these calculations, all metabolites from iJO1366, along with their metabolite attributes are added to the newly created ME-model.\n\nFurther the reactions from *i*JO1366 will be added to the ME-model to demonstrate ME-model solving procedures.\n\n\n```python\n# create empty ME-model\nme = cobrame.MEModel('test')\nijo = cobra.test.create_test_model('ecoli')\n\n# Add all metabolites and reactions from iJO1366 to the new ME-model\nfor met in ijo.metabolites:\n    me.add_metabolites(met)\nfor rxn in ijo.reactions:\n    me.add_reaction(rxn)\n```\n\nThe ME-model contains a \"global_info\" attribute which stores information used to calculate coupling constraints, along with other functions. The specifics of each of these constraints will be discussed when they are implemented.\n\n*Note*: k_deg will initially be set to 0. We will apply RNA degradation later in the tutorial.\n\n\n```python\n# \"Translational capacity\" of organism\nme.global_info['kt'] =  4.5 #(in h-1)scott 2010, RNA-to-protein curve fit\nme.global_info['r0'] =  0.087 #scott 2010, RNA-to-protein curve fit\nme.global_info['k_deg'] =  0. #1.0/5. * 60.0  # 1/5 1/min 60 min/h # h-1\n\n# Molecular mass of RNA component of ribosome\nme.global_info['m_rr'] = 1700. # in kDa\n\n# Average molecular mass of an amino acid\nme.global_info['m_aa'] = 109. / 1000. #109. / 1000. # in kDa\n\n# Proportion of RNA that is rRNA\nme.global_info['f_rRNA'] = .86\nme.global_info['m_nt'] = 324. / 1000. # in kDa\nme.global_info['f_mRNA'] = .02\n\n# tRNA associated global information\nme.global_info['m_tRNA'] = 25000. / 1000. # in kDA\nme.global_info['f_tRNA'] = .12\n\nsequence = (\"ATG\" + \"TTT\" * 12 + \"TAT\" * 12 + \n            \"ACG\" * 12 + \"GAT\" * 12 + \"AGT\" * 12 + \"TGA\")\n```\n\n## Add Transcription\n\nThe general workflow for adding any reaction to a ME-model using COBRAme occurs in three steps:\n1. Create the ProcessData(s) associated with the reaction and populate them with the necessary information\n2. Create the MEReaction and link the appropriate ProcessData\n3. Execute the MEReaction's update method\n\n### Without utility functions\n\n\n```python\ndata = cobrame.TranscriptionData('TU_a',me,RNA_products={'RNA_a'})\ndata.nucleotide_sequence = sequence\nrxn = cobrame.TranscriptionReaction('transcription_TU_a')\nrxn.transcription_data = data\nme.add_reaction(rxn)\nrxn.update()\nprint(rxn.reaction)\n```\n\n    86 atp_c + 38 ctp_c + 12 gtp_c + 186 h2o_c + 50 utp_c --> RNA_a + 86 amp_c + 38 cmp_c + 12 gmp_c + 186 h_c + 187 ppi_c + 50 ump_c\n\n\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/MEReactions.py:513 \u001b[1;31mUserWarning\u001b[0m: RNA Polymerase () not found\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/MEReactions.py:524 \u001b[1;31mUserWarning\u001b[0m: Transcript (RNA_a) added to model \n\n\nAs stated in the above warning, we have not added the RNA_a metabolite to the model. This means that the model does not know the RNA_type (mRNA, tRNA or rRNA) or the specific sequence of RNA_a. Therefore, the *biomass* constraint for this RNA cannot be included in the reaction since the sequence is required to calculate the molecular weight of RNA_a. This sequence cannot be determined from the transcription unit (TU) sequence because a single TU often contains several different RNAs. Adding this information to the RNA_a metabolite and updating the transcription reaction adds the *biomass* constraint to the reaction. \n\n**Note**: the RNA_polymerase complex is not included in the reaction. This will be added later \n\n\n```python\nme.metabolites.RNA_a.RNA_type = 'mRNA'\nme.metabolites.RNA_a.nucleotide_sequence = sequence\nrxn.update()\nprint(rxn.reaction)\n```\n\n    86 atp_c + 38 ctp_c + 12 gtp_c + 186 h2o_c + 50 utp_c --> RNA_a + 186 h_c + 59.172286 mRNA_biomass + 186 ppi_c\n\n\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/MEReactions.py:513 \u001b[1;31mUserWarning\u001b[0m: RNA Polymerase () not found\n\n\nThis reaction also produces a small amount of the a $biomass$ metabolite (constraint). This term has a coefficient corresponding to the molecular weight (in $kDA$) of the protein being translated. This constraint will be implemented into a $v_{biomasss\\_dilution}$ reaction with the form: \n$$\\mu \\leq v_{biomass\\_dilution} \\leq \\mu $$\n\nA mathematical description of the *biomass* constraint can be found in **Biomass Dilution Constraints**.\n\n### Using utility functions\nUsing the utility functions to create the TranscribedGene metabolite has the advantage of forcing the assignment of sequence, strand and RNA_type. \n\n\n```python\nbuilding.create_transcribed_gene(me, 'b', 1, 2, sequence, '+', 'mRNA')\nbuilding.add_transcription_reaction(me, 'TU_b', {'b'}, sequence)\nprint(me.reactions.transcription_TU_b.reaction)\n```\n\n    86 atp_c + 38 ctp_c + 12 gtp_c + 186 h2o_c + 50 utp_c --> RNA_b + 186 h_c + 59.172286 mRNA_biomass + 186 ppi_c\n\n\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/MEReactions.py:513 \u001b[1;31mUserWarning\u001b[0m: RNA Polymerase () not found\n\n\n**Note**: This is not a complete picture of transcriptiont because the RNA polymerase is missing.\n### Associate RNA Polymerase\n\n\n```python\nRNAP = cobrame.RNAP('RNA_polymerase')\nme.add_metabolites(RNAP)\nfor data in me.transcription_data:\n    data.RNA_polymerase = RNAP.id\nme.reactions.transcription_TU_a.update()\nme.reactions.transcription_TU_b.update()\n\nprint(me.reactions.transcription_TU_a.reaction)\n```\n\n    0.000759722875816993*mu + 0.000297431505882353 RNA_polymerase + 86 atp_c + 38 ctp_c + 12 gtp_c + 186 h2o_c + 50 utp_c --> RNA_a + 186 h_c + 59.172286 mRNA_biomass + 186 ppi_c\n\n\nThe coefficient for RNA_polymerase is the first instance where a coupling constraint is imposed. In this case the constraint couples the formation of a RNA_polymerase metabolite to its transcription flux. This constraint is formulated as in [O'brien et. al. 2013](https://www.ncbi.nlm.nih.gov/pubmed/24084808), with assumption that $k_{rnap} = 3 \\cdot k_{ribosome}$ based on data from [Proshkin et al. 2010](https://www.ncbi.nlm.nih.gov/pubmed/20413502):\n\n$$\n\\begin{align}\nv_{dilution,RNAP, j} =  \\frac{l_{TU,j}}{3 c_{ribo}\\kappa_{\\tau}} v_{transcription,j} (\\mu+r_0\\kappa_{\\tau}), & \\forall j \\in TU\n\\end{align}\n$$\n\nwhere:\n\n - $\\kappa_{\\tau}$ and $r_0$ are phenomenological parameters from [Scott et. al. 2010](https://www.ncbi.nlm.nih.gov/pubmed/21097934) that describe the linear relationship between the observed RNA/protein ratio of *E. coli* and its growth rate ($\\mu$)\n\n - $c_{ribo} = \\frac{m_{rr}}{f_{rRNA}\\cdot m_{aa}}$ where: $m_{nt}$ is the mass of rRNA per ribosome. $f_{rRNA}$ is the fraction of total RNA that is rRNA $m_{aa}$ is the molecular weight of an average amino acid\n\n - $v_{transcription, j}$ is the rate of transcription for $TU_j$\n \n - $l_{TU, j}$ is number of nucleotides in $TU_j$\n \n----\n## Add Translation\n### Without utility functions\n#### Add the TranslationData for protein_a\nIn order to add a TranslationData object to a ME model the user must additionally specifify the mRNA id and protein id of the translation reaction that will be added. This information as well as a nucleotide sequence is the only information required to add a translation reaction.\n\n\n```python\ndata = cobrame.TranslationData('a', me, 'RNA_a', 'protein_a')\ndata.nucleotide_sequence = sequence\n```\n\n#### Add the TranslationReaction for protein_a\nBy associating the TranslationReaction with its corresponding TranslationData object and running the update function, COBRAme will create a reaction reaction for the nucleotide sequence given based on the organisms codon table and prespecified translation machinery.\n\n\n```python\nrxn = cobrame.TranslationReaction('translation_a')\nrxn.translation_data = data\nme.add_reaction(rxn)\nrxn.update()\nprint(rxn.reaction)\n```\n\n    0.00149519890260631*mu + 0.00058537037037037 RNA_a + 12 asp__L_c + met__L_c + 12 phe__L_c + 12 ser__L_c + 12 thr__L_c + 12 tyr__L_c --> protein_a + 7.500606 protein_biomass\n\n\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/MEReactions.py:666 \u001b[1;31mUserWarning\u001b[0m: ribosome not found\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/MEReactions.py:706 \u001b[1;31mUserWarning\u001b[0m: RNA_degradosome not found\n\n\nIn this case the constraint couples the formation of a mRNA metabolite to its translation flux. This constraint is formulated as in [O'brien et. al. 2013](https://www.ncbi.nlm.nih.gov/pubmed/24084808):\n\n$$\n\\begin{align}\n& v_{dilution,j} = \\frac{3}{\\kappa_{\\tau} c_{mRNA}} \\cdot (\\mu + \\kappa_{\\tau} r_0) v_{translation,j}  , & \\forall j \\in mRNA \\\\\n\\end{align}\n$$\n\nwhere:\n\n - $\\kappa_{\\tau}$ and $r_0$ are phenomenological parameters from [Scott et. al. 2010](https://www.ncbi.nlm.nih.gov/pubmed/21097934) that describe the linear relationship between the observed RNA/protein ratio of *E. coli* and its growth rate ($\\mu$)\n\n - $c_{mRNA} = \\frac{m_{nt}}{f_{mRNA}\\cdot m_{aa}}$ where: $m_{nt}$ is the molecular weight of an average mRNA nucleotide. $f_{mRNA}$ is the fraction of total RNA that is mRNA $m_{aa}$ is the molecular weight of an average amino acid\n\n - $v_{translation, j}$ is the rate of translation for $mRNA_j$\n\n\n### Using utility functions\n`add_translation_reaction` assumes that the RNA and protein have the same locus_id. It creates the appropriate `TranslationData` and `TranslationReaction` instance, links the two together and updates the `TranslationReaction`.\n\n\n\n```python\nbuilding.add_translation_reaction(me, 'b', dna_sequence=sequence, update=True)\nprint(me.reactions.translation_b.reaction)\n```\n\n    0.00149519890260631*mu + 0.00058537037037037 RNA_b + 12 asp__L_c + met__L_c + 12 phe__L_c + 12 ser__L_c + 12 thr__L_c + 12 tyr__L_c --> protein_b + 7.500606 protein_biomass\n\n\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/MEReactions.py:666 \u001b[1;31mUserWarning\u001b[0m: ribosome not found\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/MEReactions.py:706 \u001b[1;31mUserWarning\u001b[0m: RNA_degradosome not found\n\n\n### Incorporate Ribosome\n\n\n```python\nribosome = cobrame.Ribosome('ribosome')\nme.add_metabolites([ribosome])\nme.reactions.translation_a.update()\nprint(me.reactions.translation_a.reaction)\n```\n\n    0.00149519890260631*mu + 0.00058537037037037 RNA_a + 12 asp__L_c + met__L_c + 12 phe__L_c + 0.000747469281045752*mu + 0.000292634223529412 ribosome + 12 ser__L_c + 12 thr__L_c + 12 tyr__L_c --> protein_a + 7.500606 protein_biomass\n\n\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/MEReactions.py:706 \u001b[1;31mUserWarning\u001b[0m: RNA_degradosome not found\n\n\nThis imposes a new coupling constraint for the ribosome. In this case the constraint couples the formation of a ribosome to its translation flux. This constraint is formulated as in [O'brien et. al. 2013](https://www.ncbi.nlm.nih.gov/pubmed/24084808):\n\n$$\n\\begin{align}\nv_{dilution,ribo, j} = \\frac{l_{p,j}}{c_{ribo}\\kappa_{\\tau}} v_{translation,j} (\\mu+r_0\\kappa_{\\tau}) , & \\forall j \\in mRNA\n\\end{align}\n$$\n\nwhere:\n\n - $\\kappa_{\\tau}$ and $r_0$ are phenomenological parameters from [Scott et. al. 2010](https://www.ncbi.nlm.nih.gov/pubmed/21097934) that describe the linear relationship between the observed RNA/protein ratio of *E. coli* and its growth rate ($\\mu$)\n\n - $c_{ribo} = \\frac{m_{rr}}{f_{rRNA}\\cdot m_{aa}}$ where: $m_{nt}$ is the mass of rRNA per ribosome. $f_{rRNA}$ is the fraction of total RNA that is rRNA $m_{aa}$ is the molecular weight of an average amino acid\n\n - $v_{translation, j}$ is the rate of translation for $mRNA_j$\n \n - $l_{p, j}$ is number of amino acids in peptide translated from $mRNA_j$\n \n-------\n**Note**: The above reactions do not provide a complete picture of translation considering that it's missing charged tRNAs to facillitate tRNA addition.\n\nBelow, we'll correct this by adding in an tRNA charging reaction.\n\n## Add tRNA charging reaction\n\n### Without utility functions (There are no utility functions for adding individual tRNA charging reactions)\n#### Add tRNAData\n\n\n```python\ndata = cobrame.tRNAData('tRNA_d_GUA', me, 'val__L_c', 'RNA_d', 'GUA')\nrxn = cobrame.tRNAChargingReaction('charging_tRNA_d_GUA')\nme.add_reaction(rxn)\nrxn.tRNA_data = data\n```\n\n#### Add tRNAChargingReaction\n\n\n```python\n#Setting verbose=False suppresses print statements indicating that new metabolites were created\nrxn.update(verbose=False)\nprint(rxn.reaction)\n```\n\n    0.000116266666666667*mu + 4.55184e-5 RNA_d + 0.000116266666666667*mu + 4.55184e-5 val__L_c --> generic_tRNA_GUA_val__L_c\n\n\nThis reaction creates one ```generic_charged_tRNA``` equivalement that can then be used in a translation reaction\n\nThe coefficient for ```RNA_d``` and ```lys__L_c``` are defined by:\n\n$$\n\\begin{align}\nv_{dilution,j} \\geq \\frac{1}{\\kappa_{\\tau} c_{tRNA,j}} (\\mu + \\kappa_{\\tau} r_0)  v_{charging,j} , & \\forall j \\in tRNA\n\\end{align}\n$$\n\nwhere:\n\n - $\\kappa_{\\tau}$ and $r_0$ are phenomenological parameters from [Scott et. al. 2010](https://www.ncbi.nlm.nih.gov/pubmed/21097934) that describe the linear relationship between the observed RNA/protein ratio of *E. coli* and its growth rate ($\\mu$)\n\n - $c_{tRNA, j} = \\frac{m_{tRNA}}{f_{tRNA}\\cdot m_{aa}}$ where: $m_{tRNA}$ is molecular weight of an average tRNA. $f_{tRNA}$ is the fraction of total RNA that is tRNA $m_{aa}$ is the molecular weight of an average amino acid\n\n - $v_{charging, j}$ is the rate of charging for $tRNA_j$\n \n\n**Note**: This tRNA charging reaction is still missing a tRNA synthetase which catalyzes the amino acid addition to the uncharged tRNA.\n\n### Incorporate tRNA Synthetases\n\n\n```python\nsynthetase = cobrame.Complex('synthetase')\nme.add_metabolites(synthetase)\ndata.synthetase = synthetase.id\nrxn.update()\nprint(rxn.reaction)\n```\n\n    0.000116266666666667*mu + 4.55184e-5 RNA_d + 4.27350427350427e-6*mu*(0.000116266666666667*mu + 1.0000455184) synthetase + 0.000116266666666667*mu + 4.55184e-5 val__L_c --> generic_tRNA_GUA_val__L_c\n\n\nThe synthetase coupling was reformulated from [O'brien et. al. 2013](https://www.ncbi.nlm.nih.gov/pubmed/24084808) enable more modularity in the ME-model. A more complete mathematical description of the tRNA synthetase coupling constraints can be found in the [tRNA.ipynb](tRNA.ipynb)\n\n---\n\n### Add tRNAs to translation\n\nHere we take advantage of an additional subclass of `ProcessData`, called a `SubreactionData` object. This class is used to lump together processeses that occur as a result of many individual reactions, including translation elongation, ribosome formation, tRNA modification, etc. Since each of these steps often involve an enzyme that requires its own coupling constraint, this process allows these processes to be lumped into one reaction while still enabling each subprocess to be modified.\n\n`TranslationData` objects have an `elongation_subreactions` method that returns any subreactions that have been used added to the model and are part of translation elongation. Since no tRNA-mediated amino acid addition subreactions have been added to the model, the below call returns nothing.\n\n\n```python\nprint(me.translation_data.a.elongation_subreactions)\n```\n\n    {}\n\n\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/ProcessData.py:317 \u001b[1;31mUserWarning\u001b[0m: RNA_a starts with 'AUG' which is not a start codon\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/ProcessData.py:355 \u001b[1;31mUserWarning\u001b[0m: elongation subreaction met_addition_at_AUG not in model\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/ProcessData.py:355 \u001b[1;31mUserWarning\u001b[0m: elongation subreaction phe_addition_at_UUU not in model\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/ProcessData.py:355 \u001b[1;31mUserWarning\u001b[0m: elongation subreaction tyr_addition_at_UAU not in model\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/ProcessData.py:355 \u001b[1;31mUserWarning\u001b[0m: elongation subreaction thr_addition_at_ACG not in model\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/ProcessData.py:355 \u001b[1;31mUserWarning\u001b[0m: elongation subreaction asp_addition_at_GAU not in model\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/ProcessData.py:355 \u001b[1;31mUserWarning\u001b[0m: elongation subreaction ser_addition_at_AGU not in model\n\n\n`UserWarnings` are returned to indicate that tRNA subreactions have not been added for each codon.\n\nBelow, we add the SubreactionData (excluding enzymes) for the addition of an amino acid using information from the *E. coli* codon table.\n\n\n```python\ndata = cobrame.SubreactionData('asp_addition_at_GAU', me)\ndata.stoichiometry = {'generic_tRNA_GAU_asp__L_c': -1,\n                      'gtp_c': -1, 'gdp_c': 1, 'h_c': 1,\n                      'pi_c': 1}\n```\n\nNow calling `elongation_subreactions` returns the number of tRNA subreactions that should be added to the `TranslationData`\n\n\n```python\ntranslation_subreactions = me.translation_data.a.elongation_subreactions\nprint(translation_subreactions)\n```\n\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/ProcessData.py:317 \u001b[1;31mUserWarning\u001b[0m: RNA_a starts with 'AUG' which is not a start codon\n\n\n    {'asp_addition_at_GAU': 12}\n\n\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/ProcessData.py:355 \u001b[1;31mUserWarning\u001b[0m: elongation subreaction met_addition_at_AUG not in model\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/ProcessData.py:355 \u001b[1;31mUserWarning\u001b[0m: elongation subreaction phe_addition_at_UUU not in model\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/ProcessData.py:355 \u001b[1;31mUserWarning\u001b[0m: elongation subreaction tyr_addition_at_UAU not in model\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/ProcessData.py:355 \u001b[1;31mUserWarning\u001b[0m: elongation subreaction thr_addition_at_ACG not in model\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/ProcessData.py:355 \u001b[1;31mUserWarning\u001b[0m: elongation subreaction ser_addition_at_AGU not in model\n\n\nUpdating `TranslationData.subreactions` with the tRNA subreactions incorporates this information into the `TranslationReaction`\n\n\n```python\nprint(\"Before adding tRNA subreaction\")\nprint(\"------------------------------\")\nprint(me.reactions.translation_a.reaction)\nprint(\"\")\n# Update tranlation_data with subreactions and update\nfor subreaction, value in translation_subreactions.items():\n    me.translation_data.a.subreactions[subreaction] = value\nme.reactions.translation_a.update(verbose=False)\nprint(\"After adding tRNA subreaction\")\nprint(\"-----------------------------\")\nprint(me.reactions.translation_a.reaction)\n```\n\n    Before adding tRNA subreaction\n    ------------------------------\n    0.00149519890260631*mu + 0.00058537037037037 RNA_a + 12 asp__L_c + met__L_c + 12 phe__L_c + 0.000747469281045752*mu + 0.000292634223529412 ribosome + 12 ser__L_c + 12 thr__L_c + 12 tyr__L_c --> protein_a + 7.500606 protein_biomass\n    \n    After adding tRNA subreaction\n    -----------------------------\n    0.00149519890260631*mu + 0.00058537037037037 RNA_a + 12 asp__L_c + 12 generic_tRNA_GAU_asp__L_c + 12 gtp_c + met__L_c + 12 phe__L_c + 0.000747469281045752*mu + 0.000292634223529412 ribosome + 12 ser__L_c + 12 thr__L_c + 12 tyr__L_c --> 12 gdp_c + 12 h_c + 12 pi_c + protein_a + 7.500606 protein_biomass\n\n\n    /home/sbrg-cjlloyd/cobrame/cobrame/core/MEReactions.py:706 \u001b[1;31mUserWarning\u001b[0m: RNA_degradosome not found\n\n\n## Create complexes\n### Without utility functions\n#### Create ComplexData and ComplexFormation\nFor COBRAme models, the reaction gene-protein-reaction rule (GPR) is replaced with a metabolite representing the synthesis of the enzyme(s) catalyzing a reaction. This metabolite is formed explicitly in a ME model by seperate reaction to transcribe the gene(s) and translate the protein(s) the compose the complex. These reactions will be added later.\n\nComplexData objects contain:\n - Subunit stoichiometry\n - Modification dictionary (discussed later)\n - Translocation dictionary (discussed later)\n\n\n```python\ndata = cobrame.ComplexData('complex_ab', me)\ndata.stoichiometry = {'protein_a': 1, 'protein_b': 1}\n\nrxn = cobrame.ComplexFormation('formation_complex_ab')\nme.add_reaction(rxn)\nrxn.complex_data_id = data.id\nrxn._complex_id = data.id\nrxn.update(verbose=False)\nprint(me.reactions.formation_complex_ab.reaction)\n```\n\n    protein_a + protein_b --> complex_ab\n\n\n### Using utility functions\nAlternatively, ComplexData has a ```create_complex_formation()``` function to create the sythesis reaction following the naming conventions. It contains an ```update()``` function which incorporates changes in the ComplexData\n\n\n```python\ndata = cobrame.ComplexData('complex_ba', me)\ndata.stoichiometry = {'protein_a': 1, 'protein_b': 1}\ndata.create_complex_formation()\nprint(me.reactions.formation_complex_ba.reaction)\n```\n\n    protein_a + protein_b --> complex_ba\n\n\n### Apply modification to complex formation reaction\nMany enzyme complexes in an ME-model require cofactors or prosthetic groups in order to properly function. Information about such processes are stored as ModificationData.\n\nFor instance, we can add the modification of an iron-sulfur cluster, a common prosthetic group, by doing the following:\n\n\n```python\n# Define the stoichiometry of the modification \nmod_data = cobrame.ModificationData('mod_2fe2s_c', me)\nmod_data.stoichiometry = {'2fe2s_c': -1}\n# this process can also be catalyzed by a chaperone\nmod_data.enzyme = 'complex_ba'\nmod_data.keff = 65.  # default value\n```\n\nAssociate modification to complex and ```update()``` its formation\n\n\n```python\ncomplex_data = me.complex_data.complex_ab\ncomplex_data.modifications['mod_2fe2s_c'] = 1\nprint(me.reactions.formation_complex_ab.reaction)\nme.reactions.formation_complex_ab.update()\nprint(me.reactions.formation_complex_ab.reaction)\n```\n\n    protein_a + protein_b --> complex_ab\n    2fe2s_c + 4.27350427350427e-6*mu complex_ba + protein_a + protein_b --> 0.17582 biomass + complex_ab\n\n\n## Add Metabolic Reaction\nMetabolicReactions require, at a minimum, one corresponding StoichiometricData. StoichiometricData essentially holds the information contained in an M-model reaction. This includes the metabolite stoichiometry and the upper and lower bound of the reaction. As a best practice, StoichiometricData typically uses an ID equivalent to the M-model reaction ID.\n\n### Without utility functions\nSo first, we will create a StoichiometricData object to define the stoichiometry of the conversion of *a* to *b*\n\nThe code below creates a StoichiometricData object which stores all of the stoichiometric information associated with the MetabolicReaction. This includes:\n - Reaction Stoichiometry\n - Lower and upper bound\n \nOnly one StoichiometricData object should be created for both reversible and irreversible reactions\n\n\n```python\n# unique to COBRAme, construct a stoichiometric data object with the reaction information\ndata = cobrame.StoichiometricData('a_to_b', me)\nstoichiometry = {'a':-1, 'b': 1}\ndata._stoichiometry = stoichiometry\ndata.lower_bound = -1000\ndata.upper_bound = 1000\n```\n\nThe StoichiometricData for this reversible reaction is then assigned to two different MetabolicReactions (Due to the enzyme dilution constraint, all enzyme catalyzed reactions must be reverisble; more on this later). The MetabolicReactions require:\n - The associated StoichiometricData\n - The *reverse* flag set to True for reverse reactions, False for forward reactions\n - Enzyme $K_{eff}$ for reaction (discussed later, dafault=65)\n\nThese fields are then processed and the actual model reaction is created using the MetabolicReaction's update() function\n\n\n```python\n# Create a forward ME Metabolic Reaction and associate the stoichiometric data to it\nrxn = cobrame.MetabolicReaction('a_to_b_FWD_complex_ab')\nme.add_reaction(rxn)\nrxn.stoichiometric_data = data\nrxn.reverse = False\nrxn.keff = 65.\n# Update\nrxn.update(verbose=False)\n\n# Create a reverse ME Metabolic Reaction and associate the stoichiometric data to it\nrxn = cobrame.MetabolicReaction('a_to_b_REV_complex_ab')\nme.add_reaction(rxn)\nrxn.stoichiometric_data = data\nrxn.reverse = True\nrxn.keff = 65.\n# Update\nrxn.update(verbose=False)\n\n\nprint(me.reactions.a_to_b_FWD_complex_ab.reaction)\nprint(me.reactions.a_to_b_REV_complex_ab.reaction)\n```\n\n    a --> b\n    b --> a\n\n\n**Note**: the $k_{eff}$ and `complex_ab` is not included in the reaction since no complex has been associated to it yet\n\n### Associate enzyme with MetabolicReaction\n\nThe ComplexData object created in the previous cell can be incorporated into the MetabolicReaction using code below. \n\n**Note**: the update() function is required to apply the change.\n\n\n```python\ndata = me.complex_data.complex_ab\nme.reactions.a_to_b_FWD_complex_ab.complex_data = data\nprint('Forward reaction (before update): %s' %\n      (me.reactions.a_to_b_FWD_complex_ab.reaction))\nme.reactions.a_to_b_FWD_complex_ab.update()\nprint('Forward reaction (after update): %s' %\n      (me.reactions.a_to_b_FWD_complex_ab.reaction))\nprint('')\n\nme.reactions.a_to_b_REV_complex_ab.complex_data = data\nprint('Reverse reaction (before update): %s' %\n      (me.reactions.a_to_b_REV_complex_ab.reaction))\nme.reactions.a_to_b_REV_complex_ab.update()\nprint('Reverse reaction (after update): %s' %\n      (me.reactions.a_to_b_REV_complex_ab.reaction))\n```\n\n    Forward reaction (before update): a --> b\n    Forward reaction (after update): a + 4.27350427350427e-6*mu complex_ab --> b\n    \n    Reverse reaction (before update): b --> a\n    Reverse reaction (after update): b + 4.27350427350427e-6*mu complex_ab --> a\n\n\nThe coefficient for complex_ab is determined by the expression $$\\frac{\\mu}{k_{eff}}$$ which in its entirety represents the dilution of an enzyme following a cell doubling. The coupling constraint can be summarized as followed\n$$ \n\\begin{align}\n&v_{dilution,j} = \\mu \\sum_{i} \\left( \\frac{1}{k_{eff,i}} v_{usage,i} \\right), & \\forall j \\in Enzyme\n\\end{align}\n$$\n\nWhere \n\n - $v_{usage,i}$ is the flux through the metabolic reaction\n - $k_{eff}$ is the turnover rate for the process and conveys the productivity of the enzyme complex. Physically, it can be thought of as the number of reactions the enzyme can catalyze per cell division. \n\n\nBy default the $k_{eff}$ for a MetabolicReaction is set to 65 but this can be changed using the code below.\n\n\n```python\nme.reactions.a_to_b_FWD_complex_ab.keff = .00001\nme.reactions.a_to_b_FWD_complex_ab.update()\n\n# The forward and reverse direction can have differing keffs\nprint('Forward reaction')\nprint('----------------')\nprint(me.reactions.a_to_b_FWD_complex_ab.reaction)\nprint('')\nprint('Reverse reaction')\nprint('----------------')\nprint(me.reactions.a_to_b_REV_complex_ab.reaction)\n```\n\n    Forward reaction\n    ----------------\n    a + 27.7777777777778*mu complex_ab --> b\n    \n    Reverse reaction\n    ----------------\n    b + 4.27350427350427e-6*mu complex_ab --> a\n\n\n### Using utility functions\n\n\n```python\nstoich_data = cobrame.StoichiometricData('b_to_c', me)\nstoich_data._stoichiometry = {'b': -1, 'c': 1}\nstoich_data.lower_bound = 0\nstoich_data.upper_bound = 1000.\nbuilding.add_metabolic_reaction_to_model(me, stoich_data.id, 'forward', complex_id='complex_ab',\n                                         update=True)\nprint('Reaction b_to_c')\nprint('---------------')\nprint(me.reactions.b_to_c_FWD_complex_ab.reaction)\n```\n\n    Created <Metabolite c at 0x7f18a6e81240> in <MetabolicReaction b_to_c_FWD_complex_ab at 0x7f18a6e813c8>\n    Reaction b_to_c\n    ---------------\n    b + 4.27350427350427e-6*mu complex_ab --> c\n\n", "meta": {"hexsha": "0c41510c5ca52600d63c17a9714127fba3cb9bab", "size": 45024, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/COBRAme_Tutorial.ipynb", "max_stars_repo_name": "EdwardCatoiu/cobrame", "max_stars_repo_head_hexsha": "64630f6dd78bef3bb5024b1a4b57e61ddbc01892", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/COBRAme_Tutorial.ipynb", "max_issues_repo_name": "EdwardCatoiu/cobrame", "max_issues_repo_head_hexsha": "64630f6dd78bef3bb5024b1a4b57e61ddbc01892", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/COBRAme_Tutorial.ipynb", "max_forks_repo_name": "EdwardCatoiu/cobrame", "max_forks_repo_head_hexsha": "64630f6dd78bef3bb5024b1a4b57e61ddbc01892", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1867881549, "max_line_length": 633, "alphanum_fraction": 0.6186034115, "converted": true, "num_tokens": 8128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489886026626094, "lm_q2_score": 0.06656918711865296, "lm_q1q2_score": 0.027619479864380573}}
{"text": "```python\n%run ../common/import_all.py\n\nfrom common.setup_notebook import set_css_style, setup_matplotlib, config_ipython\nconfig_ipython()\nsetup_matplotlib()\nset_css_style()\n```\n\n\n\n\n<style>\n\n    /* DOWNLOAD COMPUTER MODERN FONT JUST IN CASE */\n    @font-face {\n        font-family: \"Computer Modern\";\n        src: url('http://9dbb143991406a7c655e-aa5fcb0a5a4ec34cff238a2d56ca4144.r56.cf5.rackcdn.com/cmunss.otf');\n    }\n    @font-face {\n        font-family: \"Computer Modern\";\n        font-weight: bold;\n        src: url('http://9dbb143991406a7c655e-aa5fcb0a5a4ec34cff238a2d56ca4144.r56.cf5.rackcdn.com/cmunsx.otf');\n    }\n    @font-face {\n        font-family: \"Computer Modern\";\n        font-style: oblique;\n        src: url('http://9dbb143991406a7c655e-aa5fcb0a5a4ec34cff238a2d56ca4144.r56.cf5.rackcdn.com/cmunsi.otf');\n    }\n    @font-face {\n        font-family: \"Computer Modern\";\n        font-weight: bold;\n        font-style: oblique;\n        src: url('http://9dbb143991406a7c655e-aa5fcb0a5a4ec34cff238a2d56ca4144.r56.cf5.rackcdn.com/cmunso.otf');\n    }\n\n    /* GLOBAL TEXT FONT */\n    div#notebook,\n    div.output_area pre,\n    div.output_wrapper,\n    div.prompt {\n      font-family: Times new Roman, monospace !important;\n    }\n\n    /* CENTER FIGURE */\n    .output_png {\n        display: table-cell;\n        text-align: center;\n        vertical-align: middle;\n    }\n\n    /* LINK */\n    a {\n        color: #FF8000;\n    }\n\n    /* H1 */\n    h1 {\n        font-size: 42px !important;\n        text-align: center;\n        color: #FF8000;\n    }\n\n    /* H2 */\n    h2 {\n        font-size: 32px !important;\n    }\n\n    /* H2 */\n    h3 {\n        font-size: 24px !important;\n    }\n\n    /* H2 */\n    h4 {\n        font-size: 20px !important;\n    }\n\n    /* PARAGRAPH */\n    p {\n        font-size: 16px !important;\n        text-align: center;\n    }\n\n    /* LIST ITEM */\n    li {\n        font-size: 16px !important;\n    }\n\n</style>\n\n\n\n\n\n# The backpropagation algorithm\n\nThe backpropagation algorithm is the core of how artificial neural networks manage to *learn*, doing so by iteratively correcting the error between the actual value and the predicted value in a back-propagation fashion. The original paper proposing this now universally adopted mechanism is a Nature from 1986 by Rumelhart, Hinton, Williams [[1]](#paper-original).\n\n## What is it\n\nThe backpropagation algorithm is a brilliant way to train a network by perturbing each weight iteratively with an amount proportional to the partial derivative of the cost function with respect to it, propagating these derivatives backwards in the network. This is done to aid gradient descent and eventually train the network by reducing the error between what gets predicted and what is actually.\n\nThe idea per se is simple, the implementation is hard though and it took some research to figure out an efficient mechanism for it. Mechanism that arrived with Rumelhart & co. paper in 1986.\n\nThe reason why backpropagation is the core of the learning procedure of neural networks is that by adjusting the weights though little kicks and repeatedly, the hidden layers of the network come to *learn* features. While what happens to the input and output layers is controllable, it is the hidden layer(s) that do all the painstaking work of representing the featured of the input data. If in a network there were no hidden layer, it would be easy to change the weights in such a way that the output matches the expected real output. But the network wouldn't be learning and wouldn't do anything worth of excitement. It is via backpropagation that the network can learn, in its hidden neurons, how to represent the data.\n\n## The procedure in detail\n\n### Prologue: gradient descent\n\nThe notes here will follow both the original paper cited above and [this very helpful paragraph on Wikipedia](https://en.wikipedia.org/wiki/Backpropagation#Finding_the_derivative_of_the_error) about the topic, and will refer to a [feedforward network](anns.ipynb#Feedforward-networks) of [sigmoid neurons](types/sigmoid-neuron.ipynb), however the backpropagation procedure applies to a generic activation function, so long as it's differentiable, but the sigmoid makes for very nice calculations.\n\nLet's consider the transmission of information to a neuron $k$ in the $l$-th layer, we will use $i$ to indicate an input and $o$ to indicate an output, and will make use of [this note](types/sigmoid-neuron.ipynb#A-note-on-notation) to factor the bias inside the transfer function as a further weight. The neuron receives input from all the neurons in the previous, $l-1$-th layer as a weighted combination of their outputs as per activation function:\n\n$$\ni_k^l = \\sum_i o_i^{l-1} w_{ik}^{l-1,l} \n$$\n\nwhere the apex indicates the layer we are referring to. Note that the weight $w_{ik}^{l-1,l}$ is meant to represent the weight of the connection between neuron $i$ in layer $l-1$ and our reference neuron $k$ in layer $l$.\n\nAs per output function, the output of $k$ is (using a sigmoid output function as per tradition, this will prove to be a very convenient choice later on)\n\n$$\no_k^l = \\frac{1}{1 + e^{- \\sum_i o_i^{l-1} w_{ik}^{l-1,l}}}\n$$\n\nThe goal of training the network is finding the weights such that the network output is near the expected one. For this goal, we have to define a cost function which measures the difference between expected and obtained result, and minimise it. Now, the cost function can be given as the mean squared error\n\n$$\nE = \\frac{1}{2n} \\sum_i^n [o_i - e_i]^2 \\ ,\n$$\n\nwhere the sum goes over all training samples, $o$ is the network output for the sample and $e$ the expected output. It gets minimised via [gradient descent](../maths/algorithms/gradient-descent.ipynb), which requires calculating the partial derivatives of it with respect to all weights (its parameters).\n\nNote that the cost function could in principle be given differently, as long as it satisfies two requirements:\n\n1. it is differentiable\n2. it can be written as a sum of constributions (or, we can say as a mean) of the single training data points\n\nThe first requirement is needed because as per gradient descent we will have to compute derivatives of the cost function; the second because we generalise the calculation to the whole training set by applying the sum over the calculations on a training data point.\n\nAlso note that in practive the version of gradient descent applied is the stochastic one.\n\n### Calculating the derivatives of the cost function: backpropagation\n\nBackpropagation propagates the partial derivatives of the cost function with respect to the parameter weights from the output layer back to the first one, iteratively. The derivative of the cost function with respect to a weight is computable via chain rule (for simplicity, we are not indicating the layer)\n\n$$\n\\begin{equation}\n    \\frac{\\partial E}{\\partial w_{ij}} = \\frac{\\partial E}{\\partial o_j} \\frac{\\partial o_j}{\\partial i_j} \\frac{\\partial i_j}{\\partial w_{ij}} \\ ,\n\\end{equation}\n$$\n\nNow let's break down the components. For the last one, we have \n\n$$\n\\frac{\\partial i_j}{\\partial w_{ij}} = o_i \\ .\n$$\n\nFor the second one, using the form of the activation function from above, we have (you can easily prove that the equality is right)\n\n$$\n\\frac{\\partial o_j}{\\partial i_j} = o_j (1 - o_j) \\ .\n$$\n\nWe are left with calculating the first bit, $\\frac{\\partial E}{\\partial o_j}$. The derivative of the cost function with respect to $o_j$ can be calculated if we think of the cost as a function of all outputs of all the neurons in layer $\\bar{l}$ which receive input from neuron $j$, \n\n$$\n\\frac{\\partial E}{\\partial o_j} = \\frac{\\partial E(\\{o_k \\forall k \\in \\bar l\\})}{\\partial o_j} \\ ,\n$$\n\nwhich can be written as\n\n$$\n\\frac{\\partial E}{\\partial o_j} = \\sum_{k \\in \\bar l} \\frac{\\partial E}{\\partial o_k} \\frac{\\partial o_k}{\\partial o_j} = \\sum_{k \\in \\bar l} \\frac{\\partial E}{\\partial o_k} \\frac{\\partial o_k}{\\partial i_k} \\frac{\\partial i_k}{\\partial o_j} = \\sum_{k \\in \\bar l} \\frac{\\partial E}{\\partial o_k} \\frac{\\partial o_k}{\\partial i_k} w_{jk}\n$$\n\nThis recursive equation states that the derivative of the cost function with respect to $o_j$ can be calculated from the same derivatives with respect to the output of neurons in the further layer. \n\nThis all can be written as \n\n$$\n\\begin{equation}\n    \\frac{\\partial E}{\\partial w_{ij}} = o_i \\delta_j \\ ,\n\\end{equation}\n$$\n\nwith \n\n$$\n\\delta_j = \\sum_{k \\in \\bar l} \\delta_k w_{jk} o_j (1-o_j) \\ ,\n$$\n\nand in the case of a neuron in the output layer things are much easier to compute, leading to $\\delta_j = (o_j-e_j)o_j(1-o_j)$. \n\nThese expression encapsulate the essence of backpropagation: you calculate the difference between the expected output and the obtained one and starting from the output layer you propagate the derivatives back in the network. $\\delta$ is the error we are propagating. We have to start from where we can compute it (the output layer) and then iteratively go back scaling the previous layers in order to obtain the calculation in the preceding layers. \n\nFollowing the gradient descent procedure, we need to update the parameters of the cost function (the weights) by perturbing them by an amount proportional to the derivative via a learning rate:\n\n$$\n\\Delta w_{ji} = - \\alpha o_i \\delta_j\n$$\n\n## References\n\n1. <a name=\"paper-original\"></a> D E Rumelhart, G E Hinton, R J Williams, [**Learning representations by back-propagating errors**](http://www.cs.toronto.edu/~hinton/absps/naturebp.pdf), *Nature*, 323.6088, 1986\n2. [**Nielsen's book on backpropagation**](http://neuralnetworksanddeeplearning.com/chap2.html)\n\n\n```python\n\n```\n", "meta": {"hexsha": "ad8033ab32d7175c0f89de71449873e62a0535eb", "size": 13001, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "neural-nets/backpropagation.ipynb", "max_stars_repo_name": "walkenho/tales-science-data", "max_stars_repo_head_hexsha": "4f271d78869870acf2b35ce54d40766af7dfa348", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-11T09:39:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-11T09:39:10.000Z", "max_issues_repo_path": "neural-nets/backpropagation.ipynb", "max_issues_repo_name": "walkenho/tales-science-data", "max_issues_repo_head_hexsha": "4f271d78869870acf2b35ce54d40766af7dfa348", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "neural-nets/backpropagation.ipynb", "max_forks_repo_name": "walkenho/tales-science-data", "max_forks_repo_head_hexsha": "4f271d78869870acf2b35ce54d40766af7dfa348", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.9399293286, "max_line_length": 729, "alphanum_fraction": 0.5984155065, "converted": true, "num_tokens": 2497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23091977351480814, "lm_q2_score": 0.11920293140927593, "lm_q1q2_score": 0.027526313923331207}}
{"text": "## Machine Translation\nA sequence-to-sequence model is a model that takes a sequence of items and outputs another sequence of items using two networks that are trained end-to-end. This is perfect for machine translation since input sequences are directly related to output sequences. We will looking at preparing a dataset for Machine Translation task and implementing a seq2seq model. We will be using the parallel corpus available from [here](ftp://ftp.monash.edu/pub/nihongo/examples.utf.gz) \n\n### Concepts covered here:\n- Encoder-Decoder architecture: We will be using a encoder to encode input sequences from one language in a latent space and use the encoding to generate words in the target language one token at a time. The encoder and the decoder are an RNNs. \n\n- Attention: We will be looking at the attention mechanism described in [Bahdanau et al., 2015](https://arxiv.org/pdf/1409.0473.pdf). We will explore the theory, the intuition behind it and how to move from theory and intuition to implementation.\n\n\n```python\nfrom pathlib import Path\nimport re,string\nimport numpy as np\n```\n\n\n```python\n#!mkdir data\n```\n\n\n```python\npath = Path('data')\n```\n\nWe will need to download the translation corpus and install a tokenizer for Japanese text.\n\n\n```python\n#get corpus\n#!wget ftp://ftp.monash.edu/pub/nihongo/examples.utf.gz\n#decompress it and move it to data folder\n#gunzip examples.utf.gz\n#mv examples.utf.gz data/\n#install dependencies for mecab tokenizer\n#!sudo apt install swig\n#!sudo apt install mecab\n#!sudo apt install libmecab-dev\n#!sudo apt install mecab-ipadic-utf8\n#sudo pip3 install mecab-python3\n```\n\n\n```python\ncorpus = (path/'examples.utf').open().readlines()\ncorpus[:5]\n```\n\n\n\n\n    ['A: \u30e0\u30fc\u30ea\u30a8\u30eb\u306f\uff12\uff10\u6b73\u306b\u306a\u308a\u307e\u3057\u305f\u3002\\tMuiriel is 20 now.#ID=1282_4707\\n',\n     'B: \u306f \u4e8c\u5341\u6b73(\u306f\u305f\u3061){\uff12\uff10\u6b73} \u306b\u306a\u308b[01]{\u306b\u306a\u308a\u307e\u3057\u305f}\\n',\n     'A: \u3059\u3050\u306b\u623b\u308a\u307e\u3059\u3002\\tI will be back soon.#ID=1284_4709\\n',\n     'B: \u76f4\u3050\u306b{\u3059\u3050\u306b} \u623b\u308b{\u623b\u308a\u307e\u3059}\\n',\n     'A: \u3059\u3050\u306b\u8ae6\u3081\u3066\u663c\u5bdd\u3092\u3059\u308b\u304b\u3082\u77e5\u308c\u306a\u3044\u3002\\tI may give up soon and just nap instead.#ID=1300_4727\\n']\n\n\n\n\n```python\ndef make_corpus(corpus_path):\n    corpus = corpus_path.open().readlines()\n    en,ja = [],[]\n    pat = r'#ID.+\\n'\n    for c in corpus:\n        if 'A: ' in c:\n            clean_c = c.replace('A: ','')\n            res = re.search(pat,clean_c)\n            clean_c = clean_c.replace(res.group(0),'').split('\\t')\n            ja.append(clean_c[0])\n            en.append(clean_c[1])\n    return en,ja\n```\n\n\n```python\nen, ja = make_corpus(path/'examples.utf')\nen[:2],ja[:2]\n```\n\n\n\n\n    (['Muiriel is 20 now.', 'I will be back soon.'],\n     ['\u30e0\u30fc\u30ea\u30a8\u30eb\u306f\uff12\uff10\u6b73\u306b\u306a\u308a\u307e\u3057\u305f\u3002', '\u3059\u3050\u306b\u623b\u308a\u307e\u3059\u3002'])\n\n\n\n\n```python\nimport MeCab\n```\n\n\n```python\ntagger = MeCab.Tagger('-Owakati')\n\ndef ja_tokenizer(text):\n    result = tagger.parse(text)\n    words = result.split()\n    if len(words) ==0: return []\n    if words[-1] == '\\n':return words[:-1]\n    return words\n```\n\n\n```python\nja_tokenizer(ja[0])\n```\n\n\n\n\n    ['\u30e0\u30fc\u30ea\u30a8\u30eb', '\u306f', '\uff12', '\uff10', '\u6b73', '\u306b', '\u306a\u308a', '\u307e\u3057', '\u305f', '\u3002']\n\n\n\n\n```python\nimport spacy\nfrom spacy.symbols import ORTH\n```\n\n\n```python\nen_tok = spacy.load('en')\n```\n\n\n```python\ndef en_tokenizer(text):\n    text = text.lower()\n    return [t.text for t in en_tok.tokenizer(text)]\n```\n\n\n```python\nen_tokenizer(en[0])\n```\n\n\n\n\n    ['muiriel', 'is', '20', 'now', '.']\n\n\n\n\n```python\nen_toks = [en_tokenizer(text) for text in en]\nja_toks = [ja_tokenizer(text) for text in ja]\nen_toks[:2], ja_toks[:2]\n```\n\n\n\n\n    ([['muiriel', 'is', '20', 'now', '.'],\n      ['i', 'will', 'be', 'back', 'soon', '.']],\n     [['\u30e0\u30fc\u30ea\u30a8\u30eb', '\u306f', '\uff12', '\uff10', '\u6b73', '\u306b', '\u306a\u308a', '\u307e\u3057', '\u305f', '\u3002'],\n      ['\u3059\u3050', '\u306b', '\u623b\u308a', '\u307e\u3059', '\u3002']])\n\n\n\n\n```python\nlen(en_toks), len(ja_toks)\n```\n\n\n\n\n    (149786, 149786)\n\n\n\n\n```python\nfrom collections import Counter,defaultdict\n```\n\n\n```python\ndef numericalize_tok(tokens, max_vocab=50000, min_freq=0, unk_tok=\"_unk_\", pad_tok=\"_pad_\", bos_tok=\"_bos_\", eos_tok=\"_eos_\"):\n    if isinstance(tokens, str):\n        raise ValueError(\"Expected to receive a list of tokens. Received a string instead\")\n    if isinstance(tokens[0], list):\n        tokens = [p for o in tokens for p in o]\n    freq = Counter(tokens)\n    int2tok = [o for o,c in freq.most_common(max_vocab) if c>min_freq]\n    unk_id = 3\n    int2tok.insert(0, bos_tok)\n    int2tok.insert(1, pad_tok)\n    int2tok.insert(2, eos_tok)\n    int2tok.insert(unk_id, unk_tok)\n    tok2int = defaultdict(lambda:unk_id, {v:k for k,v in enumerate(int2tok)})\n    return int2tok, tok2int\n```\n\n\n```python\nint2j,j2int = numericalize_tok(ja_toks)\nint2en,en2int = numericalize_tok(en_toks)\n```\n\n\n```python\nlen(int2j), len(int2en)\n```\n\n\n\n\n    (31813, 21393)\n\n\n\n\n```python\nimport pickle\n```\n\n\n```python\npickle.dump(int2j,(path/'int2j.pkl').open('wb'))\npickle.dump(int2en,(path/'int2en.pkl').open('wb'))\n```\n\n\n```python\nint2j = pickle.load((path/'int2j.pkl').open('rb'))\nint2en = pickle.load((path/'int2en.pkl').open('rb'))\nj2int = defaultdict(lambda:3, {v:k for k,v in enumerate(int2j)})\nen2int = defaultdict(lambda:3, {v:k for k,v in enumerate(int2en)})\n```\n\n\n```python\nlen(int2j), len(int2en)\n```\n\n\n\n\n    (31813, 21393)\n\n\n\n\n```python\nj_ids = np.array([[0]+[j2int[o] for o in sent]+[2] for sent in ja_toks])\nen_ids = np.array([[0]+[en2int[o] for o in sent]+[2] for sent in en_toks])\nlen(j_ids),len(en_ids), j_ids[10],en_ids[10]\n```\n\n\n\n\n    (149786,\n     149786,\n     [0,\n      48,\n      6,\n      4891,\n      5,\n      109,\n      11,\n      143,\n      10,\n      83,\n      8,\n      57,\n      86,\n      1798,\n      7,\n      2146,\n      232,\n      255,\n      47,\n      36,\n      4,\n      2],\n     [0, 114, 2251, 107, 38, 97, 85, 2649, 77, 28, 356, 4, 2])\n\n\n\n\n```python\nnp.random.seed(42)\n```\n\n\n```python\ntrn_keep = np.random.rand(len(en_ids))>0.1\nen_trn,j_trn = en_ids[trn_keep],j_ids[trn_keep]\nen_val,j_val = en_ids[~trn_keep],j_ids[~trn_keep]\nlen(en_trn),len(en_val)\n```\n\n\n\n\n    (134775, 15011)\n\n\n\n\n```python\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom torch.autograd.variable import Variable\nfrom torch.utils.data import Dataset,DataLoader\n```\n\n\n```python\nfrom numpy import array as A\n```\n\n\n```python\nclass Seq2SeqDataset(Dataset):\n    def __init__(self, x, y): self.x,self.y = x,y\n    def __getitem__(self, idx): return A(self.x[idx]), A(self.y[idx])\n    def __len__(self): return len(self.x)\n```\n\n\n```python\ntrn_ds = Seq2SeqDataset(en_trn,j_trn)\nval_ds = Seq2SeqDataset(en_val,j_val)\n\nbs = 120\n\ntrn_dl = DataLoader(trn_ds,batch_size=bs,shuffle=True)\nval_dl = DataLoader(val_ds,batch_size=bs)\n```\n\n\n```python\nx, y = next(iter(val_dl))\nx.size(), y.size()\n```\n\n\n\n\n    (torch.Size([120, 25]), torch.Size([120, 25]))\n\n\n\n\n```python\nfrom keras.preprocessing.sequence import pad_sequences\n```\n\n    Using TensorFlow backend.\n\n\n\n```python\nmax(len(o) for o in en_ids), max(len(o) for o in j_ids)\n```\n\n\n\n\n    (56, 70)\n\n\n\n\n```python\nj_ids = pad_sequences(j_ids, maxlen=25, dtype='int32', padding='post', truncating='post', value=1)\nen_ids = pad_sequences(en_ids, maxlen=25, dtype='int32', padding='post', truncating='post', value=1)\n```\n\n\n```python\n## load fasttext vectors\nimport io\ndef load_vectors(fname):\n    fin = io.open(fname, 'r', encoding='utf-8', newline='\\n', errors='ignore')\n    header = fin.readline().split()\n    n, d = int(header[0]), int(header[1])\n    data = {}\n    for line in fin:\n        tokens = line.rstrip().split(' ')\n        data[tokens[0]] = np.array(tokens[1:], dtype=float)\n    return data, n, d\n```\n\n\n```python\n# get word vectors\n#!wget https://dl.fbaipublicfiles.com/fasttext/vectors-english/wiki-news-300d-1M.vec.zip\n#!wget https://dl.fbaipublicfiles.com/fasttext/vectors-crawl/cc.ja.300.vec.gz\n#!unzip wiki-news-300d-1M.vec.zip\n#!gunzip cc.ja.300.vec.gz\n#!mv wiki-news-300d-1M.vec ../data/\n#!mv cc.ja.300.vec ../data/\n```\n\n\n```python\nen_vecs,_,dim_en_vec = load_vectors('../data/wiki-news-300d-1M.vec')\nj_vecs,_,dim_j_vec = load_vectors('../data/cc.ja.300.vec')\n```\n\n\n```python\ndef create_emb(vecs, itos, em_sz):\n    emb = nn.Embedding(len(itos), em_sz, padding_idx=1)\n    wgts = emb.weight.data\n    miss = []\n    for i,w in enumerate(itos):\n        try: wgts[i] = torch.from_numpy(vecs[w])\n        except: miss.append(w)\n    print('Number of unknowns in data: {}'.format(len(miss)))\n    return emb\n    \n```\n\n\n```python\ndef V(tensor,req_grad=True):\n    if torch.cuda.is_available():return Variable(tensor.cuda())\n    else: return Variable(tensor)\n```\n\n### RNN Visualization\n\n\n```python\nfrom IPython.display import HTML\nHTML('')\n## video borrowed from http://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/\n```\n\n\n\n\n\n\n\n\n### Seq2Seq Architecture\n> ...a multilayered Long Short-Term Memory (LSTM) to map the input sequence to a vector of a fixed dimensionality, and then another deep LSTM to decode the target sequence from the vector. \n\n[Sutskever et al., 2014](https://papers.nips.cc/paper/5346-sequence-to-sequence-learning-with-neural-networks.pdf)\n\n\n\nImage:[from here](https://lilianweng.github.io/lil-log/2018/06/24/attention-attention.html)\n\n\n```python\nclass Seq2Seq(nn.Module):\n    def __init__(self,en_vecs,int2en,j_vecs,int2j,em_sz,nh=128,out_sl=25,dropf=1,nl=2):\n        super().__init__()\n        #encoder\n        self.nl,self.nh,self.em_sz,self.out_sl = nl,nh,em_sz,out_sl\n        self.emb_enc = create_emb(en_vecs,int2en,dim_en_vec)\n        self.emb_drop = nn.Dropout(0.15*dropf)\n        self.encoder = nn.GRU(dim_en_vec,nh,num_layers=nl,dropout=0.25*dropf, bidirectional=True)\n        #decoder\n        self.emb_dec = create_emb(j_vecs,int2j,dim_j_vec)\n        self.decoder = nn.GRU(dim_en_vec,nh*2,num_layers=nl,dropout=0.25*dropf)\n        self.out_drop = nn.Dropout(0.35*dropf)\n        self.out = nn.Linear(nh*2,len(int2j))\n    \n    def forward(self,inp,y=None):\n        sl, bs = inp.size()\n        emb_in = self.emb_drop(self.emb_enc(inp))\n        h_n = self.initHidden(bs)\n        enc_out, h_n = self.encoder(emb_in,h_n)\n        h_n = h_n.view(2,2,bs,-1).permute(0,2,1,3).contiguous().view(self.nl,bs,-1)\n        \n        dec_inp = V(torch.zeros(bs).long())\n        res = []\n        for i in range(self.out_sl):\n            dec_emb = self.emb_dec(dec_inp)\n            outp,h_n = self.decoder(dec_emb.unsqueeze(0),h_n)\n            outp = F.log_softmax(self.out(self.out_drop(outp[0])),dim=-1)\n            res.append(outp)\n            dec_inp = outp.data.max(1)[1]\n            if (dec_inp==1).all(): break\n        return torch.stack(res)\n        \n    def initHidden(self,bs):\n        return V(torch.zeros([self.nl*2,bs,self.nh]))\n```\n\n### Why Bidirectional Encoder\n> Finally, we found that reversing the order of the words in all source sentences (butnot target sentences) improved the LSTM\u2019s performance markedly, because doing so introduced many short term dependencies between the source and the targetsentence which made the optimization problem easier.\n\n[Sutskever et al., 2014](https://papers.nips.cc/paper/5346-sequence-to-sequence-learning-with-neural-networks.pdf)\n\nInput and output sequences may not directly map to each other so preserving information from both passes of the input sequence will help learn how tokens relate to each other. For example in a translation task, subject and object can be in opposite positions depending on the language structure.\n\n\n```python\nseq2seq = Seq2Seq(en_vecs,int2en,j_vecs,int2j,dim_en_vec)\nseq2seq.cuda()\n```\n\n    Number of unknowns in data: 974\n    Number of unknowns in data: 492\n\n\n\n\n\n    Seq2Seq(\n      (emb_enc): Embedding(21393, 300, padding_idx=1)\n      (emb_drop): Dropout(p=0.15)\n      (encoder): GRU(300, 128, num_layers=2, dropout=0.25, bidirectional=True)\n      (emb_dec): Embedding(31813, 300, padding_idx=1)\n      (decoder): GRU(300, 256, num_layers=2, dropout=0.25)\n      (out_drop): Dropout(p=0.35)\n      (out): Linear(in_features=256, out_features=31813, bias=True)\n    )\n\n\n\n\n```python\nout = seq2seq(V(x.transpose(1,0).long()))\nout.size()\n```\n\n\n\n\n    torch.Size([25, 120, 31813])\n\n\n\n\n```python\nout[-1].size()\n```\n\n\n\n\n    torch.Size([120, 31813])\n\n\n\n\n```python\ndef seq2seq_loss(input, target):\n    sl,bs = target.size()\n    sl_in,bs_in,nc = input.size()\n    if sl>sl_in: input = F.pad(input, (0,0,0,0,0,sl-sl_in))\n    input = input[:sl]\n    return F.cross_entropy(input.view(-1,nc), target.view(-1))\n```\n\n\n```python\nseq2seq_loss(out,V(y.transpose(1,0).long()))\n```\n\n\n\n\n    tensor(10.3854, device='cuda:0', grad_fn=<NllLossBackward>)\n\n\n\n\n```python\ndef step(x, y, epoch, m, crit, opt, clip=None):\n    output = m(x, y)\n    if isinstance(output,tuple): output = output[0]\n    opt.zero_grad()\n    loss = crit(output, y)\n    loss.backward()\n    if clip:\n        nn.utils.clip_grad_norm_(m.parameters(), clip)\n    opt.step()\n    return loss.data.item()\n```\n\n\n```python\nfrom tqdm import tqdm\n```\n\n\n```python\ndef train(trn_dl,val_dl,model,crit,opt,epochs=10,clip=None):\n    for epoch in range(epochs):\n        loss_val = loss_trn = 0\n        with tqdm(total=len(trn_dl)) as pbar:\n            model.train()\n            for i, ds in enumerate(trn_dl):\n                x, y = ds\n                #if isinstance(x,tuple): x = x[0]\n                x, y = x.transpose(1,0), y.transpose(1,0)\n                loss = step(V(x.long()),V(y.long()),epoch,model,crit,opt)\n                loss_trn += loss\n                pbar.update()\n        model.eval()\n        for i, ds in enumerate(val_dl):\n            with torch.no_grad():\n                x, y = ds\n                #if isinstance(x,tuple): x = x[0]\n                x, y = x.transpose(1,0), y.transpose(1,0)\n                out = model(V(x.long()))\n                if isinstance(out,tuple): out = out[0]\n                loss_val+= crit(out, V(y.long()))\n                #loss_val +=loss\n        print(f'Epoch: {epoch} trn loss: {loss_trn/len(trn_dl)} val loss: {loss_val/len(val_dl)}')\n```\n\n\n```python\nfrom torch import optim\n```\n\n\n```python\nopt = optim.Adam(seq2seq.parameters(),lr=3e-3,betas=(0.7,0.8))\n```\n\n\n```python\ntrain(trn_dl,val_dl,seq2seq,seq2seq_loss,opt,epochs=10)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1124/1124 [02:40<00:00,  7.02it/s]\n      0%|          | 1/1124 [00:00<03:05,  6.06it/s]\n\n    Epoch: 0 trn loss: 4.750732962983359 val loss: 4.082951068878174\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1124/1124 [02:52<00:00,  6.51it/s]\n      0%|          | 1/1124 [00:00<03:11,  5.86it/s]\n\n    Epoch: 1 trn loss: 3.5997307712073003 val loss: 3.3246185779571533\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1124/1124 [02:55<00:00,  6.39it/s]\n      0%|          | 1/1124 [00:00<03:04,  6.08it/s]\n\n    Epoch: 2 trn loss: 3.1077632744965604 val loss: 3.4751904010772705\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1124/1124 [02:57<00:00,  6.34it/s]\n      0%|          | 1/1124 [00:00<02:50,  6.60it/s]\n\n    Epoch: 3 trn loss: 2.8518904808153036 val loss: 3.94274640083313\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1124/1124 [02:58<00:00,  6.30it/s]\n      0%|          | 1/1124 [00:00<03:06,  6.01it/s]\n\n    Epoch: 4 trn loss: 2.7045018161743135 val loss: 2.766321897506714\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1124/1124 [02:58<00:00,  6.29it/s]\n      0%|          | 1/1124 [00:00<03:06,  6.01it/s]\n\n    Epoch: 5 trn loss: 2.5743112220458713 val loss: 2.752124071121216\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1124/1124 [02:58<00:00,  6.28it/s]\n      0%|          | 1/1124 [00:00<03:04,  6.08it/s]\n\n    Epoch: 6 trn loss: 2.5332621384769998 val loss: 2.935807228088379\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1124/1124 [02:59<00:00,  6.27it/s]\n      0%|          | 1/1124 [00:00<03:03,  6.11it/s]\n\n    Epoch: 7 trn loss: 2.500852593323514 val loss: 3.133931875228882\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1124/1124 [02:59<00:00,  6.99it/s]\n      0%|          | 1/1124 [00:00<03:04,  6.10it/s]\n\n    Epoch: 8 trn loss: 2.458315055141245 val loss: 2.8610451221466064\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1124/1124 [02:59<00:00,  6.26it/s]\n\n\n    Epoch: 9 trn loss: 2.456163497369909 val loss: 3.016350269317627\n\n\n\n```python\ndef produce_out(val_dl, model,int2en,int2j,interval=(20,30)):\n    model.eval()\n    x,y = next(iter(val_dl))\n    x, y = x.transpose(1,0), y.transpose(1,0)\n    probs = seq2seq(V(x.long()))\n    if isinstance(probs,tuple): probs = probs[0] \n    preds = A(probs.max(2)[1])\n    for i in range(interval[0],interval[1]):\n        print(' '.join([int2en[o] for o in x[:,i] if o not in [0,1,2]]))\n        print(''.join([int2j[o] for o in y[:,i] if o not in [0,1,2]]))\n        print(''.join([int2j[o] for o in preds[:,i] if o not in [0,1,2]]))\n        print()\n```\n\n\n```python\nproduce_out(trn_dl,seq2seq,int2en,int2j)\n```\n\n    my grandfather tells us about old things .\n    \u7956\u7236\u306f\u6614\u306e\u8a71\u3092\u3057\u3066\u304f\u308c\u307e\u3059\u3002\n    \u79c1\u306f\u79c1\u306e\u306e\u306e\u3092\u3092\u3066\u3002\n    \n    if it had not been for your help , we might have failed .\n    \u3082\u3057\u3042\u306a\u305f\u306e\u63f4\u52a9\u304c\u306a\u3051\u308c\u3070\u3001\u79c1\u305f\u3061\u306f\u5931\u6557\u3057\u3066\u3044\u305f\u304b\u3082\u3057\u308c\u306a\u3044\u3002\n    \u3082\u3057\u306e\u306e\u304c\u306a\u304b\u3063\u305f\u3089\u3001\u79c1\u79c1\u5931\u6557\u5931\u6557\u5931\u6557\u305f\u3046\u3046\u3046\u3046\n    \n    there was a long interval before he answered .\n    \u5f7c\u304c\u7b54\u3048\u308b\u307e\u3067\u306b\u9577\u3044\u9593\u304c\u3042\u3063\u305f\u3002\n    \u5f7c\u306f\u306f\u306e\u306e\u306e\u304c\u304c\u305f\u3002\n    \n    i was scolded by my mother for being lazy .\n    \u6020\u3051\u3066\u3044\u3066\u6bcd\u306b\u3057\u304b\u3089\u308c\u305f\u3002\n    \u79c1\u306f\u6bcd\u306b\u308c\u308c\u308c\u308c\u305f\u305f\n    \n    while she was running after the naughty boy , one of her shoes came off .\n    \u3044\u305f\u305a\u3089\u3063\u5b50\u3092\u8ffd\u3044\u304b\u3051\u3066\u3044\u308b\u3046\u3061\u306b\u5f7c\u5973\u306e\u9774\u304c\u7247\u65b9\u8131\u3052\u305f\u3002\n    \u5f7c\u5973\u306f\u304c\u5f7c\u5973\u3066\u3001\u3001\u5f7c\u5973\u5f7c\u5973\u306e\u306b\u306b\u3066\u3066\u3002\u3002\n    \n    they contributed money to the red cross .\n    \u5f7c\u3089\u306f\u8d64\u5341\u5b57\u306b\u304a\u91d1\u3092\u5bc4\u4ed8\u3057\u305f\u3002\n    \u5f7c\u3089\u306f\u304a\u91d1\u3092\u305f\u3081\u3092\u3092\u305f\u305f\u3002\n    \n    i 've just oiled the wheels .\n    \u8eca\u8f2a\u306b\u306f\u6cb9\u3092\u6ce8\u3057\u305f\u3070\u304b\u308a\u3060\u3002\n    \u79c1\u306f\u3092\u3092\u3092\u305f\u305f\u3002\u3002\n    \n    there are such shops about .\n    \u305d\u306e\u3088\u3046\u306a\u5e97\u306f\u3042\u3061\u3089\u3053\u3061\u3089\u306b\u3042\u308b\u3002\n    \u305d\u306e\u306b\u306b\u306f\u306f\u306f\u304c\u304c\u3066\u3002\u3002\n    \n    give me a knife to cut this string with .\n    \u3053\u306e\u7d10\u3092\u5207\u308b\u305f\u3081\u306e\u30ca\u30a4\u30d5\u3092\u8cb8\u3057\u3066\u304f\u3060\u3055\u3044\u3002\n    \u3053\u306e\u3092\u3092\u3092\u3092\u3092\u3066\u3066\u3066\u3002\n    \n    he is bound to pass the test .\n    \u5f7c\u306f\u304d\u3063\u3068\u8a66\u9a13\u306b\u5408\u683c\u3059\u308b\u3002\n    \u5f7c\u306f\u8a66\u9a13\u306b\u306b\u3059\u308b\u3059\u308b\u3060\u308d\u3002\n    \n\n\n\n```python\ntorch.save(seq2seq.state_dict(),open(path/'translate_seq2seq.pth','wb'))\n```\n\n\n```python\nseq2seq.load_state_dict(torch.load(path/'translate_seq2seq.pth', map_location=lambda storage, loc: storage))\n```\n\n### Seq2Seq w/ Attention\nA critical and apparent disadvantage of this fixed-length context vector design is incapability of remembering long sentences. Often it has forgotten the first part once it completes processing the whole input. The attention mechanism was born [Bahdanau et al., 2015](https://arxiv.org/pdf/1409.0473.pdf) to resolve this problem.\n\nGiven the following vectors:\n\\begin{align}\n\\boldsymbol{x} = \\{x_1,x_2,x_3,\\ldots,x_n\\} \\\\\n\\boldsymbol{y} = \\{y_1,y_2,y_3,\\ldots,y_m\\} \\\\\n\\end{align}\nThe hidden state from the Bidir encoder is given by:\n\\begin{align}\n\\boldsymbol{h}_i = [\\overrightarrow{\\boldsymbol{h}}_i^\\top; \\overleftarrow{\\boldsymbol{h}}_i^\\top]^\\top, i=1,\\dots,n \\\\\n\\end{align}\n\nThe hidden state from the decoder at time $t$ is given by:  $s_t$\n\nThe score for at time $t$:\n\n\\begin{aligned}\n\\text{score}(\\boldsymbol{s}_t, \\boldsymbol{h}_i) = \\mathbf{v}_a^\\top \\tanh(\\mathbf{W}_a[\\boldsymbol{s}_t; \\boldsymbol{h}_i])\n\\end{aligned}\n\nwhere both $v_a$ and $W_a$ are weight matrices to be learned in the alignment model.\n\n\\begin{aligned}\n\\mathbf{c}_t &= \\sum_{i=1}^n \\alpha_{t,i} \\boldsymbol{h}_i & \\small{\\text{; Context vector for output }y_t}\\\\\n\\alpha_{t,i} &= \\text{align}(y_t, x_i) & \\small{\\text{; How well two words }y_t\\text{ and }x_i\\text{ are aligned.}}\\\\\n&= \\frac{\\exp(\\text{score}(\\boldsymbol{s}_{t-1}, \\boldsymbol{h}_i))}{\\sum_{i'=1}^n \\exp(\\text{score}(\\boldsymbol{s}_{t-1}, \\boldsymbol{h}_{i'}))} & \\small{\\text{; Softmax of some predefined alignment score.}}.\n\\end{aligned}\n\nEquations borrowed from [here](https://lilianweng.github.io/lil-log/2018/06/24/attention-attention.html)\n\n\n\n\n```python\nHTML('')\n## video borrowed from http://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/\n```\n\n\n\n\n\n\n\n\n\n```python\nimport math,random\n\ndef rand_t(*sz): return torch.randn(sz)/math.sqrt(sz[0])\ndef rand_p(*sz): return nn.Parameter(rand_t(*sz))\n```\n\n\n```python\nclass Seq2SeqAttention(nn.Module):\n    def __init__(self,en_vecs,int2en,j_vecs,int2j,em_sz,nh=128,out_sl=25,dropf=1,nl=2):\n        super().__init__()\n        #encoder\n        self.nl,self.nh,self.em_sz,self.out_sl = nl,nh,em_sz,out_sl\n        self.emb_enc = create_emb(en_vecs,int2en,dim_en_vec)\n        self.emb_drop = nn.Dropout(0.15*dropf)\n        self.encoder = nn.GRU(dim_en_vec,nh,num_layers=nl,dropout=0.25*dropf, bidirectional=True)\n        #decoder\n        self.emb_dec = create_emb(j_vecs,int2j,dim_j_vec)\n        self.decoder = nn.GRU(dim_en_vec,nh*2,num_layers=nl,dropout=0.25*dropf)\n        self.out_drop = nn.Dropout(0.35*dropf)\n        self.out = nn.Linear(nh*2,len(int2j))\n        #attention layer\n        self.W1 = rand_p(nh*2, nh*2) #parameter\n        self.l2 = nn.Linear(nh*2, nh*2)\n        self.l3 = nn.Linear(dim_en_vec+nh*2, dim_en_vec)\n        self.V = rand_p(nh*2) #parameter\n    \n    def forward(self,inp,y=None):\n        sl, bs = inp.size()\n        emb_in = self.emb_drop(self.emb_enc(inp))\n        h_n = self.initHidden(bs)\n        enc_out, h_n = self.encoder(emb_in,h_n)\n        h_n = h_n.view(2,2,bs,-1).permute(0,2,1,3).contiguous().view(self.nl,bs,-1)\n        \n        dec_inp = V(torch.zeros(bs).long())\n        res,attns = [], []\n        #multiply by parameter\n        w1e = enc_out @ self.W1\n        for i in range(self.out_sl):\n            #linear layer \n            w2h = self.l2(h_n[-1])\n            #non-linear activation to calculate score\n            u = torch.tanh(w1e + w2h)\n            #softmax to make them into probs\n            a = F.softmax(u @ self.V, 0)\n            attns.append(a)\n            #multiply each vector by scores and then add them up\n            Xa = (a.unsqueeze(2) * enc_out).sum(0)\n            dec_emb = self.emb_dec(dec_inp)\n            #linear layer to reduce dimensions\n            wgt_enc = self.l3(torch.cat([dec_emb, Xa], 1))\n            outp,h_n = self.decoder(wgt_enc.unsqueeze(0),h_n)\n            outp = F.log_softmax(self.out(self.out_drop(outp[0])),dim=-1)\n            res.append(outp)\n            dec_inp = outp.data.max(1)[1]\n            if (random.random() > 0.5) and y is not None: dec_inp=y[i] \n            if (dec_inp==1).all(): break\n        return torch.stack(res),attns\n        \n    def initHidden(self,bs):\n        return V(torch.zeros([self.nl*2,bs,self.nh]))\n```\n\n\n```python\nseq2seq = Seq2SeqAttention(en_vecs,int2en,j_vecs,int2j,dim_en_vec)\nseq2seq.cuda()\n```\n\n    Number of unknowns in data: 974\n    Number of unknowns in data: 492\n\n\n\n\n\n    Seq2SeqAttention(\n      (emb_enc): Embedding(21393, 300, padding_idx=1)\n      (emb_drop): Dropout(p=0.15)\n      (encoder): GRU(300, 128, num_layers=2, dropout=0.25, bidirectional=True)\n      (emb_dec): Embedding(31813, 300, padding_idx=1)\n      (decoder): GRU(300, 256, num_layers=2, dropout=0.25)\n      (out_drop): Dropout(p=0.35)\n      (out): Linear(in_features=256, out_features=31813, bias=True)\n      (l2): Linear(in_features=256, out_features=256, bias=True)\n      (l3): Linear(in_features=556, out_features=300, bias=True)\n    )\n\n\n\n\n```python\nopt = optim.Adam(seq2seq.parameters(),lr=3e-3,betas=(0.7,0.8))\n```\n\n\n```python\ntrain(trn_dl,val_dl,seq2seq,seq2seq_loss,opt,epochs=10)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1124/1124 [03:21<00:00,  6.28it/s]\n      0%|          | 1/1124 [00:00<03:27,  5.42it/s]\n\n    Epoch: 0 trn loss: 2.797933133683595 val loss: 4.138897895812988\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1124/1124 [03:26<00:00,  6.24it/s]\n      0%|          | 1/1124 [00:00<03:32,  5.28it/s]\n\n    Epoch: 1 trn loss: 2.16145394790215 val loss: 2.8873095512390137\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1124/1124 [03:26<00:00,  6.17it/s]\n      0%|          | 1/1124 [00:00<03:29,  5.35it/s]\n\n    Epoch: 2 trn loss: 2.0703822573733075 val loss: 3.0309219360351562\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1124/1124 [03:26<00:00,  6.07it/s]\n      0%|          | 1/1124 [00:00<03:28,  5.38it/s]\n\n    Epoch: 3 trn loss: 2.07098806148322 val loss: 2.844566822052002\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1124/1124 [03:26<00:00,  6.07it/s]\n      0%|          | 1/1124 [00:00<03:28,  5.38it/s]\n\n    Epoch: 4 trn loss: 2.088127380906475 val loss: 2.8696582317352295\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1124/1124 [03:26<00:00,  6.26it/s]\n      0%|          | 1/1124 [00:00<03:29,  5.36it/s]\n\n    Epoch: 5 trn loss: 2.093448414603162 val loss: 2.7895729541778564\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1124/1124 [03:26<00:00,  6.12it/s]\n      0%|          | 1/1124 [00:00<03:29,  5.37it/s]\n\n    Epoch: 6 trn loss: 2.1055155513125383 val loss: 2.9072670936584473\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1124/1124 [03:26<00:00,  5.45it/s]\n      0%|          | 1/1124 [00:00<03:30,  5.34it/s]\n\n    Epoch: 7 trn loss: 2.11192792569191 val loss: 2.7808303833007812\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1124/1124 [03:26<00:00,  6.23it/s]\n      0%|          | 1/1124 [00:00<03:29,  5.37it/s]\n\n    Epoch: 8 trn loss: 2.116793169139543 val loss: 2.8389084339141846\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1124/1124 [03:26<00:00,  6.13it/s]\n\n\n    Epoch: 9 trn loss: 2.1336968614325404 val loss: 2.8806753158569336\n\n\n\n```python\nproduce_out(trn_dl,seq2seq,int2en,int2j)\n```\n\n    i 've been to osaka on business .\n    \u4ed5\u4e8b\u3067\u5927\u962a\u307e\u3067\u884c\u3063\u3066\u304d\u305f\u3002\n    \u79c1\u306f\u6771\u4eac\u306b\u884c\u3063\u3066\u3044\u305f\u3002\n    \n    she has no sense of the beautiful .\n    \u5f7c\u5973\u306f\u7f8e\u306b\u5bfe\u3059\u308b\u30bb\u30f3\u30b9\u3092\u6301\u3063\u3066\u3044\u306a\u3044\u3002\n    \u5f7c\u5973\u306f\u305d\u306e\u7f8e\u3057\u3044\u304c\u304c\u306a\u3044\u3002\n    \n    please give him my best regards .\n    \u5f7c\u306b\u3088\u308d\u3057\u304f\u304a\u4f1d\u3048\u4e0b\u3055\u3044\u3002\n    \u79c1\u306b\u304a\u3066\u4e0b\u3055\u3044\u3002\n    \n    she is working night and day .\n    \u5f7c\u5973\u306f\u663c\u3082\u591c\u3082\u50cd\u3044\u3066\u3044\u308b\u3002\n    \u5f7c\u5973\u306f\u4e00\u65e5\u4e2d\u306b\u3066\u3066\u3044\u308b\u3002\n    \n    words fail right when you need them .\n    \u3044\u3088\u3044\u3088\u3068\u3044\u3046\u6642\u306b\u8a00\u8449\u304c\u51fa\u306a\u3044\u3002\n    \u3042\u306a\u305f\u306e\u8a00\u8449\u306b\u306f\u3066\u3044\u308b\u3002\n    \n    she excels her class in music .\n    \u5f7c\u5973\u306f\u97f3\u697d\u3067\u306f\u30af\u30e9\u30b9\u306e\u8ab0\u3088\u308a\u3082\u512a\u308c\u3066\u3044\u308b\u3002\n    \u5f7c\u5973\u306f\u30af\u30e9\u30b9\u306e\u97f3\u697d\u304c\u597d\u304d\u3060\u3002\n    \n    he was brilliant in the morning sun .\n    \u5f7c\u304c\u671d\u65e5\u3092\u53d7\u3051\u3066\u5149\u308a\u8f1d\u3044\u3066\u3044\u305f\u3002\n    \u5f7c\u306f\u592a\u967d\u306e\u306b\u306b\u306b\u305f\u3002\n    \n    he searched the room for the lost key .\n    \u5f7c\u306f\u306a\u304f\u3057\u305f\u9375\u3092\u635c\u3057\u3066\u90e8\u5c4b\u3092\u8abf\u3079\u305f\u3002\n    \u5f7c\u306f\u90e8\u5c4b\u3092\u90e8\u5c4b\u3092\u3092\u305f\u3002\n    \n    a sprain like this should heal within a week or so .\n    \u3053\u306e\u7a0b\u5ea6\u306e\u637b\u632b\u306a\u3089\u3001\uff11\u9031\u9593\u7a0b\u3067\u6cbb\u308b\u3067\u3057\u3087\u3046\u3002\n    \u3053\u306e\u306e\u306f\u306f\u306b\u306b\u306b\u306b\u306f\u3066\u3044\u308b\u3002\n    \n    rules in connection with staff selection are set as follows .\n    \u8077\u54e1\u306e\u9078\u8003\u306b\u95a2\u3059\u308b\u898f\u5247\u3092\u6b21\u306e\u3088\u3046\u306b\u5b9a\u3081\u308b\u3002\n    \u6b21\u306e\u306e\u306f\u306f\u306e\u306e\u3067\u3042\u308b\u3002\n    \n\n\n\n```python\ntorch.save(seq2seq.state_dict(),open(path/'translate_seq2seq_attention.pth','wb'))\n```\n\n\n```python\nseq2seq.load_state_dict(torch.load(path/'translate_seq2seq_attention.pth', map_location=lambda storage, loc: storage))\n```\n\n\n```python\nout, atts = seq2seq(x.long().cuda())\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nplt.switch_backend('agg')\nimport matplotlib.ticker as ticker\n```\n\n\n```python\nfrom matplotlib import rc\nrc('font',family='TakaoPGothic')\nrc('xtick', labelsize=20) \nrc('ytick', labelsize=20) \n```\n\n\n```python\natts[0].size()\n```\n\n\n\n\n    torch.Size([120, 25])\n\n\n\n\n```python\nplt.matshow(torch.stack(atts)[:,2,:].detach().cpu().numpy())\n```\n\n\n```python\ndef get_out(inp,model):\n    model.eval()\n    inp_toks = en_tokenizer(inp)\n    inp_ids = torch.LongTensor([0]+[en2int[w] for w in inp_toks]+[2]).cuda()\n    probs, atts = model(inp_ids.unsqueeze(1))\n    preds = A(probs.max(2)[1])\n    out_sent = [int2j[i] for i in preds[:,0] if i not in [1]]\n    return ['bos_']+inp_toks, out_sent, atts\n```\n\n\n```python\ninput_sentence, output_words, attentions = get_out('How are you?',seq2seq) \n```\n\n\n```python\ndef showAttention(input_sentence, output_words, attentions):\n    # attention viz func borrowed from official pytorch seq2seq tutorial\n    # Set up figure with colorbar\n    fig = plt.figure()\n    ax = fig.add_subplot(111)\n    max_len = max(len(input_sentence), len(output_words))\n    cax = ax.matshow(torch.stack(attentions)[:max_len,:,0].detach().cpu().numpy(), cmap='bone')\n    fig.colorbar(cax)\n\n    # Set up axes\n    ax.set_xticklabels(['']+input_sentence+['_eos_'],rotation=90)\n    ax.set_yticklabels(['']+output_words)\n    \n    #for label in ax.get_xticklabels():\n    #    label.set_fontproperties(prop)\n\n    #for label in ax.get_yticklabels():\n    #    label.set_fontproperties(prop)\n\n    # Show label at every tick\n    ax.xaxis.set_major_locator(ticker.MultipleLocator(1))\n    ax.yaxis.set_major_locator(ticker.MultipleLocator(1))\n    plt.show()\n```\n\n\n```python\nshowAttention(*get_out('How are you?',seq2seq))\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "f68cb71643b1ce03bb25af418b7ac188fb877e06", "size": 217951, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/translate.ipynb", "max_stars_repo_name": "jacekwachowiak/Seq2Seq-Workshop", "max_stars_repo_head_hexsha": "fe9cc20ed6c99a36435dc63a45c7bbce1e63aef6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2019-03-05T16:04:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-21T16:22:57.000Z", "max_issues_repo_path": "notebooks/translate.ipynb", "max_issues_repo_name": "jacekwachowiak/Seq2Seq-Workshop", "max_issues_repo_head_hexsha": "fe9cc20ed6c99a36435dc63a45c7bbce1e63aef6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/translate.ipynb", "max_forks_repo_name": "jacekwachowiak/Seq2Seq-Workshop", "max_forks_repo_head_hexsha": "fe9cc20ed6c99a36435dc63a45c7bbce1e63aef6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2019-03-16T03:07:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-29T21:36:47.000Z", "avg_line_length": 118.7096949891, "max_line_length": 141868, "alphanum_fraction": 0.8610146317, "converted": true, "num_tokens": 9429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414330889797, "lm_q2_score": 0.10230470652415344, "lm_q1q2_score": 0.02751397438435332}}
{"text": "# Engram-es Spanish keyboard layout\n\nEngram-es is a key layout optimized for comfortable and efficient touch typing in Spanish \ncreated by [Arno Klein](https://binarybottle.com) with help from Ian Douglas, aMiguel Guzm\u00e1n, and Nick Guti\u00e9rrez.\nThere is [open source code](https://github.com/binarybottle/engram-es)\nbased on the original English Engram [open source code](https://github.com/binarybottle/engram).\n<!-- You can install the engram-es layout on [Windows, macOS, and Linux](https://keyman.com/keyboards/engram)\nor [try it out online](https://keymanweb.com/#en,Keyboard_engram).-->\n\nLetters are optimally arranged according to ergonomics factors that promote reduction of lateral finger movements and more efficient typing of high-frequency letter pairs. The most common punctuation marks and special key for diacritical marks (\u2606) are logically grouped together in the middle columns and numbers are paired with mathematical and logic symbols (shown as pairs of default and Shift-key-accessed characters). See below for a full description.\n\n\n          [ | = ~ +   <  >   ^ & % * ] \\\n          ( 1 2 3 4   5  6   7 8 9 0 ) /\n\n            Z H O X  .:  \"'  M D B J W -_ @#\n            P I E A  ,;  \u2606   T S N R K\n            F Y Q U  \u00bf\u00a1  ?!  C L V G\n            \n    \u2606 + aeiouAEIOU = \u00e1\u00e9\u00ed\u00f3\u00fa\u00c1\u00c9\u00cd\u00d3\u00da (acute accent)\n    \u2606 + nN = \u00f1\u00d1\n    \u2606 + cC = \u00e7\u00c7\n    \u2606 + Shift         + [letter] = [letter] with a diaresis/umlaut: \u00fc\n    \u2606         + AltGr + [letter] = [letter] with a grave accent: \u00e8\n    \u2606 + Shift + AltGr + [letter] = [letter] with a circumflex: \u00e2\n    AltGr + ( = { (open curly brace)\n    AltGr + ) = } (close curly brace)\n    AltGr + 5 = \u00ab (open quote/comillas) \n    AltGr + 6 = \u00bb (close quote/comillas)\n    AltGr + - = \u2014 (em dash)\n    AltGr + ' = ` (back tick)\n    AltGr + . = \u2022 (middle dot, or \"interpunct\")\n    AltGr + s = $ (dollar currency)\n    AltGr + e = \u20ac (euro currency)\n    AltGr + l = \u00a3 (pound currency)\n\n### Standard diagonal keyboard (default and Shift-key layers)\n\n\n(c) 2021 Arno Klein, MIT license\n\n----------------\n\n# Contents\n1. [Why a new keyboard layout?](#why)\n2. [Guiding criteria](#criteria)\n3. Setup:\n    - [Dependencies and functions](#import)\n    - [Speed matrix](#speed)\n    - [Strength matrix](#strength)\n    - [Flow matrix and Engram scoring model](#flow)\n4. Steps:\n    - [Step 1: Define the shape of the key layout to minimize lateral finger movements](#step1)\n    - [Step 2: Arrange the most frequent letters based on comfort and bigram frequencies](#step2)\n    - [Step 3: Optimize assignment of the remaining letters](#step3)\n    - [Step 4: Evaluate winning layout](#step4)\n    - [Step 5: Arrange non-letter characters in easy-to-remember places](#step5)\n\n## Why a new keyboard layout? <a name=\"why\">\n\n**History** <br>\nAfter creating the [English Engram layout](https://engram.dev) ([open source code](https://github.com/binarybottle/engram)), community members came together to help guide the creation of a Spanish version.  Thank you, Nick Guti\u00e9rrez (@NickG13) and Miguel Guzm\u00e1n (@Lobo-Feroz), and a special thanks to Ian Douglas (@iandoug) for cleaning up the Leipzig Spanish corpus and for computing character and bigram frequencies!  For documentation of this Spanish corpus, please see [Creating a Corpus and Chained Bigrams for Spanish Keyboard Development and Evaluation](https://zenodo.org/record/5501931).\n\n**Why \"Engram\"?** <br>\nThe name is a pun, referring both to \"n-gram\", letter permutations and their frequencies that are used to compute the Engram layout, and \"engram\", or memory trace, the postulated change in neural tissue to account for the persistence of memory, as a nod to my attempt to make this layout easy to remember.\n\n## Guiding criteria   <a name=\"criteria\">\n\n    1.  Assign letters to keys that don't require lateral finger movements.\n    2.  Promote alternating between hands over uncomfortable same-hand transitions.\n    3.  Assign the most common letters to the most comfortable keys.\n    4.  Arrange letters so that more frequent bigrams are easier to type.\n    5.  Promote little-to-index-finger roll-ins over index-to-little-finger roll-outs.\n    6.  Balance finger loads according to their relative strength.\n    7.  Avoid stretching shorter fingers up and longer fingers down.\n    8.  Avoid using the same finger.\n    9.  Avoid skipping over the home row.\n    10. Assign the most common punctuation to keys in the middle of the keyboard.\n    11. Assign easy-to-remember symbols to the Shift-number keys.\n    \n### Factors used to compute the Engram layout <a name=\"factors\">\n  - Spanish letter and letter bigram frequency data from a cleaned-up version of the Leipzig Spanish corpus. The largest file was downloaded from each row of the [original version](https://wortschatz.uni-leipzig.de/en/download/Spanish), except for rows specified as not from Spain, and lines containing non-Spanish names and words were removed.\n    <br>\n  - **Flow factors** (transitions between ordered key pairs)\n\n### Import dependencies and functions  <a name=\"import\">\n\n\n```python\n# %load code/engram_variables.py\n# Print .png figures and .txt text files\nprint_output = False # True\n\n# Apply strength data\napply_strength = True\nmin_strength_factor = 0.9\n\nletters24 = ['E','A','O','S','N','I','R','L','D','C','T','U','M',\n             'P','B','G','V','Q','Y','F','H','J','Z','X','K','W']\nkeys24 = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24]\ninstances24 = [169540585,155261246,114162756,85434855,91757262,83685037,85877478,71380359,63808304,55938235,\n               56546911,52510166,34957958,34360294,15959118,14964467,12628219,11205355,10437289,10254596,\n               10147320,5919395,4900008,2224153,982042,584461]\nmax_frequency = 294897235\ninstances_denominator = 100000\n\n# Establish which layouts are within a small difference of the top-scoring layout \n# (the smallest difference between two penalties, 0.9^8 - 0.9^9, in one of 24^2 key pairs):\ndelta = 0.9**8 - 0.9**9\nfactor24 = ((24**2 - 1) + (1-delta)) / (24**2)\nfactor32 = ((32**2 - 1) + (1-delta)) / (32**2)\n\n# Establish which layouts are within a small difference of each other when using the speed matrix. \n# We define an epsilon equal to 13.158 ms for a single bigram (of the 32^2 possible bigrams), \n# where 13.158 ms is one tenth of 131.58 ms, the fastest measured digraph tapping speed (30,000/228 = 131.58 ms) \n# recorded in the study: \"Estimation of digraph costs for keyboard layout optimization\", \n# A Iseri, Ma Eksioglu, International Journal of Industrial Ergonomics, 48, 127-138, 2015.\n#data_matrix_speed = Speed32x32\n#time_range = 243  # milliseconds\n#norm_range = np.max(data_matrix_speed) - np.min(data_matrix_speed)  # 0.6535662299854439\n#ms_norm = norm_range / time_range  # 0.0026895729629030614\n#epsilon = 131.58/10 * ms_norm / (32**2)\nepsilon    = 0.00003549615849447514\n```\n\n\n```python\n# %load code/engram_functions.py\n# Import dependencies\nimport xlrd\nimport numpy as np\nfrom sympy.utilities.iterables import multiset_permutations\nimport matplotlib\nimport matplotlib.pyplot as plt    \nimport seaborn as sns\n\n\ndef permute_optimize_keys(fixed_letters, fixed_letter_indices, open_letter_indices, \n                          all_letters, keys, data_matrix, bigrams, bigram_frequencies, \n                          min_score=0, verbose=False):\n    \"\"\"\n    Find all permutations of letters, optimize layout, and generate output.\n    \"\"\"\n    matrix_selected = select_keys(data_matrix, keys, verbose=False) \n    \n    unassigned_letters = []\n    for all_letter in all_letters:\n        if all_letter not in fixed_letters:\n            unassigned_letters.append(all_letter)\n            if len(unassigned_letters) == len(open_letter_indices):\n                break\n\n    letter_permutations = permute_letters(unassigned_letters, verbose)\n    if verbose:\n        print(\"{0} permutations\".format(len(letter_permutations)))\n    top_permutation, top_score = optimize_layout(np.array([]), matrix_selected, bigrams, bigram_frequencies, \n                                                 letter_permutations, open_letter_indices, \n                                                 fixed_letters, fixed_letter_indices, min_score, verbose)\n    \n    return top_permutation, top_score, letter_permutations\n\n\ndef permute_optimize(starting_permutation, letters, all_letters, all_keys, \n                     data_matrix, bigrams, bigram_frequencies, min_score=0, verbose=False):\n    \"\"\"\n    Find all permutations of letters, optimize layout, and generate output.\n    \"\"\"\n    matrix_selected = select_keys(data_matrix, all_keys, verbose=False)\n    open_positions = []\n    fixed_positions = [] \n    open_letters = []\n    fixed_letters = []\n    assigned_letters = []\n    for iletter, letter in enumerate(letters):\n        if letter.strip() == \"\":\n            open_positions.append(iletter)\n            for all_letter in all_letters:\n                if all_letter not in letters and all_letter not in assigned_letters:\n                    open_letters.append(all_letter)\n                    assigned_letters.append(all_letter)\n                    break\n        else:\n            fixed_positions.append(iletter)\n            fixed_letters.append(letter)\n\n    letter_permutations = permute_letters(open_letters, verbose)\n    if verbose:\n        print(\"{0} permutations\".format(len(letter_permutations)))\n    top_permutation, top_score = optimize_layout(starting_permutation, matrix_selected, bigrams, \n                                                 bigram_frequencies, letter_permutations, open_positions, \n                                                 fixed_letters, fixed_positions, min_score, verbose)\n        \n    return top_permutation, top_score\n\n\ndef select_keys(data_matrix, keys, verbose=False):\n    \"\"\"\n    Select keys to quantify pairwise relationships.\n    \"\"\"\n    # Extract pairwise entries for the keys:\n    nkeys = len(keys)\n    Select = np.zeros((nkeys, nkeys))\n    u = 0\n    for i in keys:\n        u += 1\n        v = 0\n        for j in keys:\n            v += 1\n            Select[u-1,v-1] = data_matrix[i-1,j-1]\n\n    # Normalize matrix with min-max scaling to a range with max 1:\n    newMin = np.min(Select) / np.max(Select)\n    newMax = 1.0\n    Select = newMin + (Select - np.min(Select)) * (newMax - newMin) / (np.max(Select) - np.min(Select))\n    \n    if verbose:\n        # Heatmap of array\n        heatmap(data=Select, title=\"Matrix heatmap\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=False); plt.show()\n    \n    return Select\n\n\ndef permute_letters(letters, verbose=False):\n    \"\"\"\n    Find all permutations of a given set of letters (max: 8-10 letters).\n    \"\"\"\n    letter_permutations = []\n    for p in multiset_permutations(letters):\n        letter_permutations.append(p)\n    letter_permutations = np.array(letter_permutations)\n    \n    return letter_permutations\n\n\ndef score_layout(data_matrix, letters, bigrams, bigram_frequencies, verbose=False):\n    \"\"\"\n    Compute the score for a given letter-key layout (NOTE normalization step).\n    \"\"\"\n    # Create a matrix of bigram frequencies:\n    nletters = len(letters)\n    F2 = np.zeros((nletters, nletters))\n\n    # Find the bigram frequency for each ordered pair of letters in the permutation:\n    for i1 in range(nletters):\n        for i2 in range(nletters):\n            bigram = letters[i1] + letters[i2]\n            i2gram = np.where(bigrams == bigram)\n            if np.size(i2gram) > 0:\n                F2[i1, i2] = bigram_frequencies[i2gram][0]\n\n    # Normalize matrices with min-max scaling to a range with max 1:\n    newMax = 1\n    minF2 = np.min(F2)\n    maxF2 = np.max(F2)\n    newMin2 = minF2 / maxF2\n    F2 = newMin + (F2 - minF2) * (newMax - newMin2) / (maxF2 - minF2)\n\n    # Compute the score for this permutation:\n    score  = np.average(data_matrix * F2) \n    if verbose:\n        print(\"Score for letter permutation {0}: {1}\".format(letters, score))\n\n    return score\n\n\ndef tally_bigrams(input_text, bigrams, normalize=True, verbose=False):\n    \"\"\"\n    Compute the score for a given letter-key layout (NOTE normalization step).\n    \"\"\"   \n    # Find the bigram frequency for each ordered pair of letters in the input text\n    #input_text = [str.upper(str(x)) for x in input_text]\n    input_text = [str.upper(x) for x in input_text]\n    nchars = len(input_text)\n    F = np.zeros(len(bigrams))\n\n    for ichar in range(0, nchars-1):\n        bigram = input_text[ichar] + input_text[ichar + 1]\n        i2gram = np.where(bigrams == bigram)\n        if np.size(i2gram) > 0:\n            F[i2gram] += 1\n\n    # Normalize matrix with min-max scaling to a range with max 1:\n    if normalize:\n        newMax = 1\n        newMin = np.min(F) / np.max(F)\n        F = newMin + (F - np.min(F)) * (newMax - newMin) / (np.max(F) - np.min(F))\n\n    bigram_frequencies_for_input = F\n\n    if verbose:\n        print(\"Bigram frequencies for input: {0}\".format(bigram_frequencies_for_input))\n\n    return bigram_frequencies_for_input\n\n\ndef tally_layout_samefinger_bigrams(layout, bigrams, bigram_frequencies, nkeys=32, verbose=False):\n    \"\"\"\n    Tally the number of same-finger bigrams within (a list of 24 letters representing) a layout:\n    ['P','Y','O','U','C','I','E','A','G','K','J','X','M','D','L','B','R','T','N','S','H','V','W','F']\n    \"\"\"  \n    if nkeys == 32:\n        #        Left:            Right:\n        #    1  2  3  4 25   28 13 14 15 16 31 \n        #    5  6  7  8 26   29 17 18 19 20 32\n        #    9 10 11 12 27   30 21 22 23 24\n        same_finger_keys = [[1,5],[5,9],[1,9], [2,6],[6,10],[2,10], \n                            [3,7],[7,11],[3,11], [4,8],[8,12],[4,12],\n                            [25,26],[26,27],[25,27], [28,29],[29,30],[28,30], [31,32],\n                            [4,25],[4,26],[4,27], [8,25],[8,26],[8,27], [12,25],[12,26],[12,27],\n                            [13,28],[13,29],[13,30], [17,28],[17,29],[17,30], [21,28],[21,29],[21,30],\n                            [31,16],[31,20],[31,24], [32,16],[32,20],[32,24],\n                            [13,17],[17,21],[13,21], [14,18],[18,22],[14,22], \n                            [15,19],[19,23],[15,23], [16,20],[20,24],[16,24]] \n    elif nkeys == 24:\n        #    1  2  3  4         13 14 15 16  \n        #    5  6  7  8         17 18 19 20 \n        #    9 10 11 12         21 22 23 24\n        same_finger_keys = [[1,5],[5,9],[1,9], [2,6],[6,10],[2,10], \n                            [3,7],[7,11],[3,11], [4,8],[8,12],[4,12],\n                            [13,17],[17,21],[13,21], [14,18],[18,22],[14,22], \n                            [15,19],[19,23],[15,23], [16,20],[20,24],[16,24]] \n\n    layout = [str.upper(x) for x in layout]\n    max_frequency = 1.00273E+11\n\n    samefinger_bigrams = []\n    samefinger_bigram_counts = []\n    for bigram_keys in same_finger_keys:\n        bigram1 = layout[bigram_keys[0]-1] + layout[bigram_keys[1]-1]\n        bigram2 = layout[bigram_keys[1]-1] + layout[bigram_keys[0]-1]\n        i2gram1 = np.where(bigrams == bigram1)\n        i2gram2 = np.where(bigrams == bigram2)\n        if np.size(i2gram1) > 0:\n            samefinger_bigrams.append(bigram1)\n            samefinger_bigram_counts.append(max_frequency * bigram_frequencies[i2gram1] / np.max(bigram_frequencies))\n        if np.size(i2gram2) > 0:\n            samefinger_bigrams.append(bigram2)\n            samefinger_bigram_counts.append(max_frequency * bigram_frequencies[i2gram2] / np.max(bigram_frequencies))\n\n    samefinger_bigrams_total = np.sum([x[0] for x in samefinger_bigram_counts])\n\n    if verbose:\n        print(\"    Total same-finger bigram frequencies: {0:15.0f}\".format(samefinger_bigrams_total))\n\n    return samefinger_bigrams, samefinger_bigram_counts, samefinger_bigrams_total \n\n\ndef tally_layout_bigram_rolls(layout, bigrams, bigram_frequencies, nkeys=32, verbose=False):\n    \"\"\"\n    Tally the number of bigrams that engage little-to-index finger inward rolls\n    for (a list of 24 or 32 letters representing) a layout,\n    within the four columns of one hand, or any column across two hands.\n    layout = ['P','Y','O','U','C','I','E','A','G','K','J','X','L','D','B','V','N','T','R','S','H','M','W','F']\n    bigram_rolls, bigram_roll_counts, bigram_rolls_total = tally_layout_bigram_rolls(layout, bigrams, bigram_frequencies, nkeys=24, verbose=True)\n    \"\"\"   \n    if nkeys == 32:\n        #        Left:            Right:\n        #    1  2  3  4 25   28 13 14 15 16 31 \n        #    5  6  7  8 26   29 17 18 19 20 32\n        #    9 10 11 12 27   30 21 22 23 24\n\n        roll_keys = [[1,2],[2,3],[3,4], [5,6],[6,7],[7,8], [9,10],[10,11],[11,12],\n                    [16,15],[15,14],[14,13], [20,19],[19,18],[18,17], [24,23],[23,22],[22,21],\n                    [1,3],[2,4],[1,4], [5,7],[6,8],[5,8], [9,11],[10,12],[9,12],\n                    [16,14],[15,13],[16,13], [20,18],[19,17],[20,17], [24,22],[23,21],[24,21],\n                    [1,6],[1,7],[1,8],[2,7],[2,8],[3,8], \n                    [5,2],[5,3],[5,4],[6,3],[6,4],[7,4],\n                    [5,10],[5,11],[5,12],[6,11],[6,12],[7,12], \n                    [9,6],[9,7],[9,8],[10,7],[10,8],[11,8],\n                    [16,19],[16,18],[16,17],[15,18],[15,17],[14,17], \n                    [20,15],[20,14],[20,13],[19,14],[19,13],[18,13],\n                    [20,23],[20,22],[20,21],[19,22],[19,21],[18,21], \n                    [24,19],[24,18],[24,17],[23,18],[23,17],[22,17],\n                    [1,10],[1,11],[1,12],[2,11],[2,12],[3,12],\n                    [9,2],[9,3],[9,4],[10,3],[10,4],[11,4],\n                    [16,23],[16,22],[16,21],[15,22],[15,21],[14,21],\n                    [24,15],[24,14],[24,13],[23,14],[23,13],[22,13]]\n        for i in [1,2,3,4,5,6,7,8,9,10,11,12, 25,26,27]:\n            for j in [13,14,15,16,17,18,19,20,21,22,23,24, 28,29,30,31,32]:\n                roll_keys.append([i,j])\n        for i in [13,14,15,16,17,18,19,20,21,22,23,24, 28,29,30,31,32]:\n            for j in [1,2,3,4,5,6,7,8,9,10,11,12, 25,26,27]:\n                roll_keys.append([i,j])\n\n    elif nkeys == 24:\n        #    1  2  3  4         13 14 15 16  \n        #    5  6  7  8         17 18 19 20 \n        #    9 10 11 12         21 22 23 24\n        roll_keys = [[1,2],[2,3],[3,4], [5,6],[6,7],[7,8], [9,10],[10,11],[11,12],\n                    [16,15],[15,14],[14,13], [20,19],[19,18],[18,17], [24,23],[23,22],[22,21],\n                    [1,3],[2,4],[1,4], [5,7],[6,8],[5,8], [9,11],[10,12],[9,12],\n                    [16,14],[15,13],[16,13], [20,18],[19,17],[20,17], [24,22],[23,21],[24,21],\n                    [1,6],[1,7],[1,8],[2,7],[2,8],[3,8], [5,2],[5,3],[5,4],[6,3],[6,4],[7,4],\n                    [5,10],[5,11],[5,12],[6,11],[6,12],[7,12], [9,6],[9,7],[9,8],[10,7],[10,8],[11,8],\n                    [16,19],[16,18],[16,17],[15,18],[15,17],[14,17], [20,15],[20,14],[20,13],[19,14],[19,13],[18,13],\n                    [20,23],[20,22],[20,21],[19,22],[19,21],[18,21], [24,19],[24,18],[24,17],[23,18],[23,17],[22,17],\n                    [1,10],[1,11],[1,12],[2,11],[2,12],[3,12], [9,2],[9,3],[9,4],[10,3],[10,4],[11,4],\n                    [16,23],[16,22],[16,21],[15,22],[15,21],[14,21], [24,15],[24,14],[24,13],[23,14],[23,13],[22,13]]\n        for i in range(0,12):\n            for j in range(12,24):\n                roll_keys.append([i,j])\n        for i in range(12,24):\n            for j in range(0,12):\n                roll_keys.append([i,j])\n\n    layout = [str.upper(x) for x in layout]\n    max_frequency = 1.00273E+11\n\n    bigram_rolls = []\n    bigram_roll_counts = []\n    for bigram_keys in roll_keys:\n        bigram1 = layout[bigram_keys[0]-1] + layout[bigram_keys[1]-1]\n        bigram2 = layout[bigram_keys[1]-1] + layout[bigram_keys[0]-1]\n        i2gram1 = np.where(bigrams == bigram1)\n        i2gram2 = np.where(bigrams == bigram2)\n        if np.size(i2gram1) > 0:\n            bigram_rolls.append(bigram1)\n            bigram_roll_counts.append(max_frequency * bigram_frequencies[i2gram1] / np.max(bigram_frequencies))\n        if np.size(i2gram2) > 0:\n            bigram_rolls.append(bigram2)\n            bigram_roll_counts.append(max_frequency * bigram_frequencies[i2gram2] / np.max(bigram_frequencies))\n\n    bigram_rolls_total = np.sum([x[0] for x in bigram_roll_counts])\n\n    if verbose:\n        print(\"    Total bigram inward roll frequencies: {0:15.0f}\".format(bigram_rolls_total))\n\n    return bigram_rolls, bigram_roll_counts, bigram_rolls_total \n\n\ndef optimize_layout(starting_permutation, data_matrix, bigrams, bigram_frequencies, letter_permutations, \n                    open_positions, fixed_letters, fixed_positions=[], min_score=0, verbose=False):\n    \"\"\"\n    Compute scores for all letter-key layouts.\n    \"\"\"\n    top_permutation = starting_permutation\n    top_score = min_score\n    use_score_function = False\n\n    nletters = len(open_positions) + len(fixed_positions)\n    F2 = np.zeros((nletters, nletters))\n\n    # Loop through the permutations of the selected letters:\n    for p in letter_permutations:\n        letters = np.array(['W' for x in range(nletters)])  # KEEP to initialize!\n        for imove, open_position in enumerate(open_positions):\n            letters[open_position] = p[imove]\n        for ifixed, fixed_position in enumerate(fixed_positions):\n            letters[fixed_position] = fixed_letters[ifixed]\n\n        # Compute the score for this permutation:\n        if use_score_function:\n            score = score_layout(data_matrix, letters, bigrams, bigram_frequencies, verbose=False)\n        else:\n            # Find the bigram frequency for each ordered pair of letters in the permutation:\n            for i1 in range(nletters):\n                for i2 in range(nletters):\n                    bigram = letters[i1] + letters[i2]\n                    i2gram = np.where(bigrams == bigram)\n                    if np.size(i2gram) > 0:\n                        F2[i1, i2] = bigram_frequencies[i2gram][0]\n\n            # Normalize matrices with min-max scaling to a range with max 1:\n            newMax = 1\n            minF2 = np.min(F2)\n            maxF2 = np.max(F2)\n            newMin2 = minF2 / maxF2\n            F = newMin + (F2 - minF2) * (newMax - newMin2) / (maxF2 - minF2)\n\n            # Compute the score for this permutation:\n            score  = np.average(data_matrix * F) \n\n        if score > top_score:\n            top_score = score\n            top_permutation = letters\n            \n    if verbose:\n        if top_score == min_score:\n            print(\"top_score = min_score\")\n        print(\"{0:0.8f}\".format(top_score))\n        print(*top_permutation)\n        \n    return top_permutation, top_score\n\n\ndef exchange_letters(letters, fixed_letter_indices, all_letters, all_keys, data_matrix, \n                     bigrams, bigram_frequencies, verbose=True):\n    \"\"\"\n    Exchange letters, 8 keys at a time (8! = 40,320) selected twice in 14 different ways:\n\n    Indices:\n         0  1  2  3     12 13 14 15\n         4  5  6  7     16 17 18 19\n         8  9 10 11     20 21 22 23 \n\n    1. Top rows\n         0  1  2  3     12 13 14 15\n    2. Bottom rows\n         8  9 10 11     20 21 22 23 \n    3. Top and bottom rows on the right side\n                        12 13 14 15\n                        20 21 22 23 \n    4. Top and bottom rows on the left side \n         0  1  2  3\n         8  9 10 11 \n    5. Top right and bottom left rows\n                        12 13 14 15\n         8  9 10 11 \n    6. Top left and bottom right rows \n         0  1  2  3\n                        20 21 22 23 \n    7. Center of the top and bottom rows on both sides\n            1  2          13 14\n            9 10          21 22\n    8. The eight corners\n         0        3    12       15\n         8       11    20       23 \n    9. Left half of the top and bottom rows on both sides \n         0  1          12 13\n         8  9          20 21\n    10. Right half of the top and bottom rows on both sides\n               2  3          14 15\n              10 11          22 23 \n    11. Left half of non-home rows on the left and right half of the same rows on the right \n         0  1                14 15\n         8  9                22 23 \n    12. Right half of non-home rows on the left and left half of the same rows on the right\n               2  3    12 13\n              10 11    20 21 \n    13. Top center and lower sides\n            1  2           13 14\n         8       11     20       23 \n    14. Top sides and lower center\n         0        3     12       15\n            9 10           21 22   \n    15. Repeat 1-14\n\n    \"\"\"\n    top_score = score_layout(data_matrix, letters, bigrams, bigram_frequencies, verbose=False)\n    print('Initial score: {0}'.format(top_score)) \n    print(*letters) \n    top_permutation = letters\n\n    lists_of_open_indices = [\n        [0,1,2,3,12,13,14,15],\n        [8,9,10,11,20,21,22,23],\n        [12,13,14,15,20,21,22,23],\n        [0,1,2,3,8,9,10,11],\n        [12,13,14,15,8,9,10,11],\n        [0,1,2,3,20,21,22,23],\n        [1,2,13,14,9,10,21,22],\n        [0,3,12,15,8,11,20,23],\n        [0,1,12,13,8,9,20,21],\n        [2,3,14,15,10,11,22,23],\n        [0,1,14,15,8,9,22,23],\n        [2,3,12,13,10,11,20,21],\n        [1,2,8,11,13,14,20,23],\n        [0,3,9,10,12,15,21,22]  \n    ]\n    lists_of_print_statements = [\n        '1. Top rows',\n        '2. Bottom rows',\n        '3. Top and bottom rows on the right side',\n        '4. Top and bottom rows on the left side',\n        '5. Top right and bottom left rows',\n        '6. Top left and bottom right rows',\n        '7. Center of the top and bottom rows on both sides',\n        '8. The eight corners',\n        '9. Left half of the top and bottom rows on both sides',\n        '10. Right half of the top and bottom rows on both sides',\n        '11. Left half of non-home rows on the left and right half of the same rows on the right',\n        '12. Right half of non-home rows on the left and left half of the same rows on the right',\n        '13. Top center and lower sides',\n        '14. Top sides and lower center'\n    ]\n                         \n    for istep in [1,2]:\n        if istep == 1:\n            s = \"Set 1: 14 letter exchanges: \"\n        elif istep == 2:\n            s = \"Set 2: 14 letter exchanges: \"\n\n        for ilist, open_indices in enumerate(lists_of_open_indices):\n            print_statement = lists_of_print_statements[ilist]     \n\n            if verbose:\n                print('{0} {1}'.format(s, print_statement))\n              \n            starting_permutation = top_permutation.copy()\n            for open_index in open_indices:\n                if open_index not in fixed_letter_indices:\n                    top_permutation[open_index] = ''\n            \n            top_permutation, top_score = permute_optimize(starting_permutation, top_permutation, letters24, \n                                                          keys24, data_matrix, bigrams, bigram_frequencies, \n                                                          min_score=top_score, verbose=True)                    \n    if verbose:\n        print('')\n        print('    -------- DONE --------') \n        print('')\n\n    return top_permutation, top_score\n                             \n\ndef rank_within_epsilon(numbers, epsilon, factor=False, verbose=True):\n    \"\"\"\n    numbers = np.array([10,9,8,7,6])\n    epsilon = 1\n    rank_within_epsilon(numbers, epsilon, factor=False, verbose=True) \n    >>> array([1., 1., 2., 2., 3.])\n    numbers = np.array([0.798900824, 0.79899900824, 0.79900824])\n    epsilon = 0.9**8 - 0.9**9\n    factor24 = ((24**2 - 1) + (1-epsilon)) / (24**2) # 0.999925266109375\n    rank_within_epsilon(numbers, factor24, factor=True, verbose=True) \n    >>> array([2., 1., 1.])\n    \"\"\"\n    numbers = np.array(numbers)\n    Isort = np.argsort(-numbers)\n    numbers_sorted = numbers[Isort]\n    count = 1\n    ranks = np.zeros(np.size(numbers))\n    for i, num in enumerate(numbers_sorted):\n        if ranks[i] == 0:\n            if factor:\n                lower_bound = num * epsilon\n            else:\n                lower_bound = num - epsilon\n            bounded_nums1 = num >= numbers_sorted\n            bounded_nums2 = numbers_sorted >= lower_bound\n            bounded_nums = bounded_nums1 * bounded_nums2\n            count += 1\n            for ibounded, bounded_num in enumerate(bounded_nums):\n                if bounded_num == True:\n                    ranks[ibounded] = count\n\n    uranks = np.unique(ranks)\n    nranks = np.size(uranks)\n    new_ranks = ranks.copy()\n    new_count = 0\n    for rank in uranks:\n        new_count += 1\n        same_ranks = ranks == rank\n        for isame, same_rank in enumerate(same_ranks):\n            if same_rank == True:\n                new_ranks[isame] = new_count\n\n    #ranks_sorted = new_ranks[Isort]\n    ranks_sorted = [np.int(x) for x in new_ranks]\n    \n    if verbose:\n        for i, num in enumerate(numbers_sorted):\n            print(\"    ({0})    {1}\".format(np.int(ranks_sorted[i]), num))\n        \n    return numbers_sorted, ranks_sorted, Isort\n\n\ndef print_matrix_info(matrix_data, matrix_label, nkeys, nlines=10):\n    \"\"\"\n    Print matrix output.\n    \"\"\"\n    print(\"{0} min = {1}, max = {2}\".format(matrix_label, np.min(matrix_data), np.max(matrix_data)))\n    matrix_flat = matrix_data.flatten()\n    argsort = np.argsort(matrix_flat)\n    print(\"{0} key number pairs with minimum values:\".format(matrix_label))\n    for x in argsort[0:nlines]:\n        if x % nkeys == 0:\n            min_row = np.int(np.ceil(x / nkeys)) + 1\n            min_col = 1\n        else:\n            min_row = np.int(np.ceil(x / nkeys))\n            min_col = x - nkeys * (min_row-1) + 1                \n        print(\"        {0} -> {1}        ({2})\".format(min_row, min_col, matrix_flat[x]))\n    print(\"{0} key number pairs with maximum values:\".format(matrix_label))\n    max_sort = argsort[-nlines::]\n    for x in max_sort[::-1]:\n        if x % nkeys == 0:\n            max_row = np.int(np.ceil(x / nkeys)) + 1\n            max_col = 1\n        else:\n            max_row = np.int(np.ceil(x / nkeys))\n            max_col = x - nkeys * (max_row-1) + 1                \n        print(\"        {0} -> {1}        ({2})\".format(max_row, max_col, matrix_flat[x]))\n\n\ndef heatmap(data, title=\"\", xlabel=\"\", ylabel=\"\", x_axis_labels=[], y_axis_labels=[], print_output=True):\n    \"\"\"\n    Plot heatmap of matrix.\n    \"\"\"\n    # use heatmap function, set the color as viridis and\n    # make each cell seperate using linewidth parameter\n    plt.figure()\n    sns_plot = sns.heatmap(data, xticklabels=x_axis_labels, yticklabels=y_axis_labels, linewidths=1, \n                           cmap=\"viridis\", square=True, vmin=np.min(data), vmax=np.max(data))\n    plt.title(title)\n    plt.xlabel(xlabel)\n    plt.ylabel(ylabel)\n    sns_plot.set_xticklabels(x_axis_labels)  #, rotation=75) \n    sns_plot.set_yticklabels(y_axis_labels) \n    if print_output:\n        sns_plot.figure.savefig(\"{0}_heatmap.png\".format(title))\n        \n    \ndef histmap(data, title=\"\", print_output=True):\n    \"\"\"\n    Plot histogram.\n    \"\"\"\n    sns.distplot(data)\n    plt.title(title)\n    if print_output:\n        sns_plot.figure.savefig(\"{0}_histogram.png\".format(title))\n        \n        \ndef print_layout24(layout):\n    \"\"\"\n    Print layout.\n    \"\"\"   \n    print('    {0}  {1}'.format(' '.join(layout[0:4]),\n                                ' '.join(layout[12:16])))\n    print('    {0}  {1}'.format(' '.join(layout[4:8]),\n                                ' '.join(layout[16:20])))\n    print('    {0}  {1}'.format(' '.join(layout[8:12]),\n                                ' '.join(layout[20:24])))\n\n\ndef print_layout24_instances(layout, letters24, instances24, bigrams, bigram_frequencies):\n    \"\"\"\n    Print billions of instances per letter (not Z or Q) in layout form.\n    layout = ['P','Y','O','U','C','I','E','A','G','K','J','X','M','D','L','B','R','T','N','S','H','V','W','F']\n    print_layout24_instances(layout, letters24, instances24, bigrams, bigram_frequencies)\n    \"\"\"\n    layout_instances = []\n    layout_instances_strings = []\n    for letter in layout:\n        index = letters24.index(letter)\n        layout_instances.append(instances24[index])\n        layout_instances_strings.append('{0:3.0f}'.format(instances24[index]/instances_denominator))\n \n    print('    {0}  {1}'.format(' '.join(layout_instances_strings[0:4]),\n                                ' '.join(layout_instances_strings[12:16])))\n    print('    {0}  {1}'.format(' '.join(layout_instances_strings[4:8]),\n                                ' '.join(layout_instances_strings[16:20])))\n    print('    {0}  {1}'.format(' '.join(layout_instances_strings[8:12]),\n                                ' '.join(layout_instances_strings[20:24])))\n    left_sum = np.sum(layout_instances[0:12])\n    right_sum = np.sum(layout_instances[12:24])\n    pL = ''\n    pR = ''\n    if left_sum > right_sum:\n        pL = ' ({0:3.2f}%)'.format(100 * (left_sum - right_sum) / right_sum)\n    elif right_sum > left_sum:\n        pR = ' ({0:3.2f}%)'.format(100 * (right_sum - left_sum) / left_sum)\n    \n    print('\\n    left: {0}{1}  right: {2}{3}'.format(left_sum, pL, right_sum, pR))\n    \n    tally_layout_samefinger_bigrams(layout, bigrams, bigram_frequencies, nkeys=24, verbose=True)\n    tally_layout_bigram_rolls(layout, bigrams, bigram_frequencies, nkeys=24, verbose=True)\n   \n\ndef print_bigram_frequency(input_pair, bigrams, bigram_frequencies):\n    \"\"\"\n    >>> print_bigram_frequency(['t','h'], bigrams, bigram_frequencies)\n    \"\"\"\n    # Find the bigram frequency\n    input_text = [str.upper(str(x)) for x in input_pair]\n    nchars = len(input_text)\n    for ichar in range(0, nchars-1):\n        bigram1 = input_text[ichar] + input_text[ichar + 1]\n        bigram2 = input_text[ichar + 1] + input_text[ichar]\n        i2gram1 = np.where(bigrams == bigram1)\n        i2gram2 = np.where(bigrams == bigram2)\n        if np.size(i2gram1) > 0:\n            freq1 = bigram_frequencies[i2gram1[0][0]]\n            print(\"{0}: {1:3.2f}\".format(bigram1, freq1))\n        if np.size(i2gram2) > 0:\n            freq2 = bigram_frequencies[i2gram2[0][0]]\n            print(\"{0}: {1:3.2f}\".format(bigram2, freq2))\n```\n\n### Bigram frequencies <a name=\"ngrams\">\n\n[NOTE: If you want to compute an optimized layout for another language, or based on another corpus, you can run the tally_bigrams() function above and replace bigram_frequencies below before running the rest of the code.]\n\n\n```python\nbigrams = np.array(['DE','EN','ES','LA','ER','OS','ON','RA','UE','AS','AN','EL','AR','RE','CO','NT','DO','TA','QU','TE','CI','OR','AL','AD','IO','ST','SE','RO','LO','TO','NA','IA','NO','UN','CA','RI','IN','MA','DA','IE','LE','PA','PO','TI','TR','SI','ME','DI','ND','IC','AC','MO','ID','EC','SA','AB','IS','SO','MI','SU','NE','PR','PE','HA','LI','OM','AM','CE','NC','BA','NI','LL','CU','VI','EM','VE','OL','IT','RT','ED','AT','IR','IM','BR','BI','GU','MP','IL','US','CH','EG','GA','OC','UR','UA','TU','UI','PU','VA','GO','OD','HO','SP','MU','NS','ET','RR','ZA','FI','IG','MB','OB','GR','BL','OT','JO','UL','CT','RM','SC','PI','BE','IV','VO','UC','FU','EA','AP','LU','NU','EV','HE','CR','RD','RS','AG','FE','PL','GE','EX','JA','UD','IB','HI','EJ','EZ','RC','JE','NG','LT','DU','GI','RU','AY','AU','UM','BO','AJ','DR','FA','FO','IZ','EP','OP','JU','RN','EB','ZO','UT','RG','YO','AV','UB','BU','FR','CL','AZ','IP','YA','SM','NF','IF','OV','EO','OG','AI','UY','RL','LG','EF','IJ','AQ','UP','NV','CC','OF','OY','HU','EI','NZ','XI','LM','AF','UG','RV','LV','RQ','YE','XP','LD','AH','UJ','SD','OJ','GL','NQ','UV','EU','TH','XT','EQ','EY','FL','IU','GN','OZ','LC','RP','AE','EE','RB','PT','VU','UZ','BS','RZ','IQ','SL','SF','NM','OI','OE','UO','OU','XC','LS','NR','NJ','YU','II','SS','UF','ZU','SH','JI','OX','RF','DM','LP','OO','OA','PC','SG','KI','LB','SQ','OH','LQ','WA','ZC','BJ','XA','NN','TT','OQ','KE','MN','AO','WI','CK','CN','EH','LF','PS','WE','KA','RY','AX','OW','LY','DV','LZ','TS','BT','SR','TL','RK','PP','NL','ZQ','SN','AK','IX','ZE','SB','UQ','TC','ZG','TB','RJ','SV','NY','KO','OK','GH','NH','TM','LR','WO','ZI','XO','MS','DQ','NK','IK','TY','PH','FF','XX','HN','XV','EW','GM','MM','WH','SK','DS','BY','YS','YN','FT','UX','XE','DY','TW','HR','ZM','AA','TZ','HT','XU','GT','DD','AW','UU','BD','XH','VD','MY','KS','BC','YL','KU','EK','BB','YR','GD','DJ','GS','LK','LN','SY','TN','DH','LH','IH','DL','ZZ','WN','BV','CS','CD','KY','NB','WS','KL','KM','YM','TV','GG','UK','WR','HS','DN','UH','ZN','MC','HY','ML','LX','CY','DG','DW','HM','CM','RH','HL','KN','WW','KR','SW','YD','MR','PY','DT','NP','FM','MT','YI','PN','VR','KH','YT','GY','FC','XQ','PM','BM','RW','PD','VS','BN','YC','ZT','YP','GB','IY','TP','CQ','CF','FP','FS','DC','FG','PF','DF','CP','LJ','YW','TX','CV','VN','ZY','ZB','QA','XL','TF','XM','CB','GP','CG','ZH','PV','PG','ZP','RX','MD','PB','YB','WL','DP','VL','WT','MW','ZL','LW','HD','TG','KK','FN','PJ','NW','HW','IW','DB','BP','XY','KG','SJ','GK','ZK','KB','HC','VY','TD','JR','MV','BH','KW','YV','HB','NX','FY','FB','MG','HF','MX','KT','VT','XF','HP','CZ','WK','SZ','YZ','HH','WY','WU','TK','ZS','HK','WD','GW','MH','MF','YF','GC','PK','JP','VP','YG','GF','VC','HZ','WB','WC','DZ','FD','JN','XB','HV','CX','WM','JS','UW','KD','JC','KF','FK','TJ','WF','YK','BG','DK','QI','VM','BF','XD','JM','JK','MK','XS','KC','ZR','GJ','JH','KP','KV','JD','CJ','XG','XJ','ZD','GZ','YH','VH','VV','HG','YY','VG','MZ','WP','CW','PX','JJ','BK','JF','PZ','FJ','WG','JL','ZV','GV','MJ','VB','PW','BW','VW','JT','ZW','QL','FH','JB','VF','VK','QR','SX','XW','MQ','FW','FV','DX','KJ','XN','VQ','QO','JV','QM','QE','FX','QS','BZ','HQ','ZF','ZJ','PQ','QQ','XR','QB','HJ','GX','QC','YJ','YX','GQ','BQ','QT','JG','JW','QP','QN','BX','TQ','JY','QV','FQ','KX','QW','VX','VZ','FZ','XK','JX','KZ','QH','QD','WZ','VJ','WV','ZX','YQ','QF','JZ','WJ','HX','XZ','WX','WQ','JQ','QX','KQ','QY','QG','QZ','QK','QJ'])\n```\n\n\n```python\nbigram_frequencies = np.array([28642306,27599303,23987675,20108334,18188528,17889132,17471661,17137795,17135545,16053776,16043220,15999094,15611106,14776535,13881634,13403852,12839068,12788337,12469334,12252845,12162129,11767925,11702339,10797471,10629390,10479844,10366402,9921741,9824959,9806256,9755313,9704625,9597369,9486958,9350376,8948040,8899064,8532616,8489520,8264649,7761788,7454837,7314256,7158745,6982844,6916547,6869549,6831479,6501402,6391388,6379482,5959359,5867386,5713280,5703195,5671299,5499065,5432893,5428698,5260721,5255405,5241844,5209417,5192648,5153251,5025434,4905487,4575544,4535985,4487327,4271172,4257588,4232075,4171890,3925769,3881135,3698607,3573364,3473930,3321914,3275910,3232492,3219207,3216626,3190352,3131502,3063320,3051922,2993483,2911020,2854819,2853098,2765437,2749651,2727622,2722762,2699510,2694782,2622122,2555138,2534426,2489346,2412701,2381530,2352231,2293919,2286607,2248985,2228369,2216496,2169462,2096075,2082624,2053224,2036436,2010116,1982627,1927284,1908571,1907706,1900077,1806136,1789152,1755760,1752660,1667276,1634965,1616541,1610262,1577699,1560823,1547179,1537677,1524597,1509084,1508281,1504832,1459569,1458322,1455753,1421023,1406597,1388150,1329773,1308414,1302941,1280075,1269690,1253772,1253199,1246814,1241905,1212959,1209022,1206620,1185409,1181226,1165828,1140387,1107391,1098790,1098310,1095937,1093881,1079022,1072129,1066811,1020093,1018731,1017226,1015153,1014569,1008458,983685,961703,937006,912603,882550,860917,824133,820132,796875,790102,787382,784852,768894,758127,725594,723344,718973,699766,691623,668500,643725,641809,618917,618651,618602,578063,569051,540445,532762,527460,518357,513248,511995,498117,459829,421540,412761,384412,379311,377058,373468,355931,354392,353419,338775,330783,330010,329863,324846,316539,314965,310763,301316,297547,285120,279633,279558,272830,269252,240016,238792,234822,231240,210351,201316,200997,198839,193436,182266,175574,174475,173436,167332,161216,154455,152136,149314,145492,139196,137084,134881,133228,130549,130541,129843,126400,123342,117839,117167,115885,113582,113230,112679,112616,112238,111755,110089,101445,100184,99569,99228,92874,90401,88068,88065,85753,85590,83286,78319,77781,75985,74574,71957,70249,68579,65186,64486,62820,62619,61234,60326,58669,58448,56883,56704,54920,53366,52918,50963,48402,45540,45499,44827,43965,43768,43109,42568,41525,41141,38670,38492,37155,37038,35777,35461,35133,35011,34926,34907,34213,34171,33701,33537,33377,33375,33086,33014,32585,32534,32514,32194,30422,28281,28210,27443,26880,25768,25760,25018,24875,24672,24571,23668,23320,23226,23163,22813,21691,21260,20812,20210,20156,19469,19456,18914,18875,18500,17954,17951,17773,16849,16717,16621,16478,16454,15875,15769,15530,15430,15207,15050,14940,14827,14810,14403,14321,14320,14182,13801,13465,13328,12246,12089,11804,11730,11641,11534,11317,10977,10968,10908,10893,10803,10780,10599,10588,10461,10400,10301,10050,9836,9563,9472,9038,8919,8769,8685,8680,8489,8274,8257,8206,7903,7796,7733,7607,7400,7250,6804,6804,6524,6442,6440,6423,6420,6330,6324,6220,6000,5962,5947,5922,5833,5759,5741,5412,5404,5389,5274,5030,5021,4828,4599,4537,4489,4432,4260,4141,4111,4065,4009,3796,3786,3764,3719,3696,3648,3603,3546,3537,3360,3354,3279,3263,3263,3260,3244,3155,3067,2986,2978,2956,2954,2953,2950,2930,2919,2893,2873,2858,2758,2754,2747,2642,2596,2575,2542,2520,2407,2393,2388,2384,2260,2251,2231,2221,2215,2209,2205,2122,2100,2083,2018,1998,1993,1888,1883,1855,1851,1704,1687,1659,1642,1608,1545,1474,1471,1448,1431,1409,1398,1392,1356,1317,1308,1300,1251,1244,1242,1233,1172,1163,1161,1156,1144,1133,1132,1129,1089,1064,1060,1057,1052,1045,1026,997,957,956,942,922,918,893,883,863,856,850,849,841,841,806,784,782,774,748,742,737,732,691,691,678,647,647,620,599,592,579,568,563,563,532,532,511,475,471,465,463,443,439,426,421,420,419,415,407,391,366,366,355,353,337,324,324,313,308,296,291,281,266,261,257,251,244,231,227,222,221,219,212,207,191,186,177,176,169,168,167,165,154,143,140,140,139,137,135,126,123,118,113,104,101,100,92,90,90,90,90,88,83,81,79,73,72,68,68,62,56,55,48,45,38,33,32,25,23,20,19,18,15,14,11,7,6,4])\n```\n\n## Speed matrix  <a name=\"speed\">\n### 24x24 relative Speed matrix between key pair (averaged for left/right symmetry)\n\n  - does not take into account order of key pairs (see Flow24x24 matrix)\n  - the original version was constructed with data from right-handed people\n  - 24 keys that don't require extending index or little fingers (\"home block keys\")\n\n### Home block keys\n\n        Left:            Right:\n     1  2  3  4       13 14 15 16 \n     5  6  7  8       17 18 19 20\n     9 10 11 12       21 22 23 24\n\nInterkey stroke times in milliseconds from Table 3 of <br>\n\"Estimation of digraph costs for keyboard layout optimization\", <br>\nA Iseri, Ma Eksioglu, International Journal of Industrial Ergonomics, 48, 127-138, 2015. <br>\nKey numbering in article and in spreadsheet:\n\n         Left:           Right:\n     1 4 7 10 13   16 19 22 25 28 31\n     2 5 8 11 14   17 20 23 26 29 32\n     3 6 9 12 15   18 21 24 27 30\n     \n### Load table of interkey speeds\n\n\n```python\n# %load data/Time24x24.py\n# code/load_original_interkey_speeds.py\n#        Left:            Right:\n#    1  2  3  4 25   28 13 14 15 16 31 \n#    5  6  7  8 26   29 17 18 19 20 32\n#    9 10 11 12 27   30 21 22 23 24\nTime24x24 = np.array([\n[196,225,204,164,266,258,231,166,357,325,263,186,169,176,178,186,156,156,158,163,171,175,177,189],\n[225,181,182,147,239,245,196,150,289,296,229,167,162,169,170,178,148,148,150,155,163,167,169,182],\n[204,182,170,149,196,194,232,155,237,214,263,166,157,164,165,173,143,143,145,150,158,163,164,177],\n[164,147,149,169,160,161,157,226,165,185,234,257,154,162,163,171,141,141,143,148,156,160,162,175],\n[266,239,196,160,196,240,208,166,271,267,208,169,143,150,151,160,129,129,132,137,145,149,151,163],\n[258,245,194,161,240,181,183,149,245,256,184,150,138,145,146,154,124,124,126,131,139,144,145,158],\n[231,196,232,157,208,183,170,149,201,215,239,151,134,141,142,150,120,120,122,127,135,140,141,154],\n[166,150,155,226,166,149,149,169,160,147,170,221,133,140,141,150,119,119,122,126,135,139,141,153],\n[357,289,237,165,271,245,201,160,196,236,194,161,171,178,179,188,157,157,160,164,173,177,179,191],\n[325,296,214,185,267,256,215,147,236,181,184,157,166,173,174,182,152,152,154,159,167,172,173,186],\n[263,229,263,234,208,184,239,170,194,184,170,150,159,166,167,176,145,145,148,153,161,165,167,179],\n[186,167,166,257,169,150,151,221,161,157,150,169,153,160,161,169,139,139,141,146,154,159,160,173],\n[169,162,157,154,143,138,134,133,171,166,159,153,151,147,141,145,188,151,142,164,213,204,162,149],\n[176,169,164,162,150,145,141,140,178,173,166,160,147,151,189,209,137,207,191,206,149,227,208,197],\n[178,170,165,163,151,146,142,141,179,174,167,161,141,189,157,253,136,188,210,231,155,226,239,276],\n[186,178,173,171,160,154,150,150,188,182,176,169,145,209,253,170,147,206,251,233,164,268,362,271],\n[156,148,143,141,129,124,120,119,157,152,145,139,188,137,136,147,151,133,138,152,192,149,139,144],\n[156,148,143,141,129,124,120,119,157,152,145,139,151,207,188,206,133,151,179,183,145,204,183,201],\n[158,150,145,143,132,126,122,122,160,154,148,141,142,191,210,251,138,179,157,240,145,185,208,229],\n[163,155,150,148,137,131,127,126,164,159,153,146,164,206,231,233,152,183,240,170,160,220,293,242],\n[171,163,158,156,145,139,135,135,173,167,161,154,213,149,155,164,192,145,145,160,151,140,142,145],\n[175,167,163,160,149,144,140,139,177,172,165,159,204,227,226,268,149,204,185,220,140,151,175,188],\n[177,169,164,162,151,145,141,141,179,173,167,160,162,208,239,362,139,183,208,293,142,175,157,230],\n[189,182,177,175,163,158,154,153,191,186,179,173,149,197,276,271,144,201,229,242,145,188,230,170]])\n```\n\n\n```python\n# %load code/load_interkey_speeds24x24.py\n\n# Left/right symmetric version of the Time24x24 matrix\n# (The original version was constructed with data from right-handed people.)\n# A. Iseri, M. Eksioglu / International Journal of Industrial Ergonomics 48 (2015) 127e138\n\n#        Left:            Right:\n#     1  2  3  4       13 14 15 16 \n#     5  6  7  8       17 18 19 20\n#     9 10 11 12       21 22 23 24\n\nI = [ 1, 2, 3, 4,   5, 6, 7, 8,   9,10,11,12,  16,15,14,13,  20,19,18,17,  24,23,22,21]\nJ = [16,15,14,13,  20,19,18,17,  24,23,22,21,   1, 2, 3, 4,   5, 6, 7, 8,   9,10,11,12]\n\nTimeSymmetric24x24 = np.ones((24,24))\nfor i1, I1 in enumerate(I):\n    for i2, I2 in enumerate(I):\n        J1 = J[i1] - 1\n        J2 = J[i2] - 1\n        avgvalue = (Time24x24[I1-1,I2-1] + Time24x24[J1,J2]) / 2 \n        #print(Time24x24[I1-1,I2-1], Time24x24[J1,J2], avgvalue)\n        TimeSymmetric24x24[I1-1,I2-1] = avgvalue\n        TimeSymmetric24x24[J1,J2] = avgvalue\n\n# Normalize matrix with min-max scaling to a range with maximum = 1:\nnewMin = np.min(Time24x24) / np.max(Time24x24)\nnewMax = 1.0\nTime24x24 = newMin + (Time24x24 - np.min(Time24x24)) * (newMax - newMin) / (np.max(Time24x24) - np.min(Time24x24))\n\n# Convert relative interkey stroke times to relative speeds by subtracting from 1:\nSpeed24x24 = 1 - Time24x24 + np.min(Time24x24)\n\n# Normalize matrix with min-max scaling to a range with maximum = 1:\nnewMin = np.min(TimeSymmetric24x24) / np.max(TimeSymmetric24x24)\nnewMax = 1.0\nTimeSymmetric24x24 = newMin + (TimeSymmetric24x24 - np.min(TimeSymmetric24x24)) * (newMax - newMin) / (np.max(TimeSymmetric24x24) - np.min(TimeSymmetric24x24))\n\n# Convert relative interkey stroke times to relative speeds by subtracting from 1:\nSpeedSymmetric24x24 = 1 - TimeSymmetric24x24 + np.min(TimeSymmetric24x24)\n\n# Print:\n#print_matrix_info(matrix_data=Speed24x24, matrix_label=\"Speed24x24\", nkeys=24, nlines=50)\n#heatmap(data=Speed24x24, title=\"Speed24x24\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n```\n\n## Strength matrix  <a name=\"strength\">\n\n### Relative finger position STRENGTH matrix\n\nFinger strengths are based on peak keyboard reaction forces (in newtons) from Table 4 of <br>\n\"Keyboard Reaction Force and Finger Flexor Electromyograms during Computer Keyboard Work\" <br>\nBJ Martin, TJ Armstrong, JA Foulke, S Natarajan, Human Factors,1996,38(4),654-664:\n   \n    middle     2.36\n    index      2.26\n    ring       2.02\n    little     1.84\n    \n    index/middle:  0.9576271186440678\n    ring/middle:   0.8559322033898306\n    little/middle: 0.7796610169491526\n\nFor reference, Table 1 of \"Ergonomic keyboard layout designed for the Filipino language\", 2016 (doi: 10.1007/978-3-319-41694-6_41) presents \"average finger strength of Filipinos [n=30, ages 16-36] measured in pounds\":\n   \n                L       R\n    little     3.77   4.27\n    ring       4.54   5.08\n    middle     5.65   6.37\n    index      6.09   6.57\n    \n    6.57/4.27 = 1.54\n    6.09/3.77 = 1.62\n    6.37/5.08 = 1.25\n    5.65/4.54 = 1.24\n    \nWe won't use these results as I don't feel they represent relative strength relevant for typing: \"Respondents were asked to sit in upright position, with their wrists resting on a flat surface. A pinch gauge was placed within each finger's reach. The respondents were asked to exert maximum pressure on the device.\"\n    \nThe following does not take into account order of key pairs (see Flow matrix).\n\n\n\n```python\n# %load code/load_strength_data.py\n# Normalize by the highest peak force (middle finger):\nmiddle_force = 2.36\nindex_force = 2.26\nring_force = 2.02\nlittle_force = 1.84\nmiddle_norm = 1.0\nindex_norm = index_force / middle_force\nring_norm = ring_force / middle_force\nlittle_norm = little_force / middle_force\nprint('index/middle: {0}'.format(index_norm))\nprint('ring/middle: {0}'.format(ring_norm))\nprint('little/middle: {0}'.format(little_norm))\n\n# Relative left/right hand strength (assume equal):\nlf = 1.0\nrf = 1.0\n\nstrengths24 = np.array((\n                    lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                    lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                    lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                    rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm,\n                    rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm,\n                    rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm))\n\n# Create a finger-pair position strength matrix by adding pairs of strength values:\nStrength24x24 = np.zeros((24, 24))\nfor i in range(24):\n    Strength24x24[i,:] = strengths24\nStrength24x24 = (Strength24x24 + Strength24x24.transpose())\n\n# Normalize matrix with min-max scaling to a range with maximum = 1:\n#newMin = strength_factor\nnewMin = min_strength_factor  # np.min(Strength24x24) / np.max(Strength24x24)\nnewMax = 1.0\nStrength24x24 = newMin + (Strength24x24 - np.min(Strength24x24)) * (newMax - newMin) / (np.max(Strength24x24) - np.min(Strength24x24))\n\n# Print:\nprint_matrix_info(matrix_data=Strength24x24, matrix_label=\"Strength24x24\", nkeys=24, nlines=10)\nheatmap(data=Strength24x24, title=\"Strength24x24\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n# Save:\nif print_output:\n    file = open(\"Strength24x24.txt\", \"w+\")\n    file.write(str(Strength24x24))\n    file.close()\n\n\npenalty = 1.0  # Penalty for lateral (index, little) finger placement (1 = no penalty)\n\nstrengths32 = np.array((lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                        lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                        lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                        rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm,\n                        rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm,\n                        rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm,\n                        lf * index_norm * penalty, lf * index_norm * penalty, lf * index_norm * penalty,\n                        rf * index_norm * penalty, rf * index_norm * penalty, rf * index_norm * penalty,\n                        rf * little_norm * penalty, rf * little_norm * penalty))\n\n# Create a finger-pair position strength matrix by adding pairs of strength values:\nStrength32x32 = np.zeros((32, 32))\nfor i in range(32):\n    Strength32x32[i,:] = strengths32\nStrength32x32 = (Strength32x32 + Strength32x32.transpose())\n\n# Normalize matrix with min-max scaling to a range with maximum = 1:\nnewMin = np.min(Strength32x32) / np.max(Strength32x32)\nnewMax = 1.0\nStrength32x32 = newMin + (Strength32x32 - np.min(Strength32x32)) * (newMax - newMin) / (np.max(Strength32x32) - np.min(Strength32x32))\n\n# Print:\nprint_matrix_info(matrix_data=Strength32x32, matrix_label=\"Strength32x32\", nkeys=32, nlines=10)\nheatmap(data=Strength32x32, title=\"Strength32x32\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n# Save:\nif print_output:\n    file = open(\"Strength32x32.txt\", \"w+\")\n    file.write(str(Strength32x32))\n    file.close()\n```\n\n## Flow matrix and Engram scoring model  <a name=\"flow\">\n\nThe Flow24x24 matrix takes into account ease of transition between ordered pairs of keys.\n    \nOur optimization algorithm finds every permutation of a given set of letters, maps these letter permutations to a set of keys, and ranks these letter-key mappings according to a score reflecting ease of typing key pairs and frequency of letter pairs (bigrams). The score is the average of the scores for all possible bigrams in this arrangement. The score for each bigram is a product of the frequency of occurrence of that bigram, the frequency of each of the bigram\u2019s characters, and flow, strength (and optional speed) factors for the key pair.\n\n#### Dvorak et al. (1936) defined eleven criteria for the design and evaluation of keyboard layouts:\n1.  Deviation from the balance of hand and finger loads should be as low as possible.\n2.  Percentage of tapping with the same fingers should be as low as possible.\n3.  Percentage of tapping that includes top row should be as low as possible.\n4.  Percentage of tapping that includes bottom row should be as low as possible.\n5.  Percentage of tapping in the home row should be as high as possible.\n6.  Percentage of tapping by alternating hands should be as high as possible.\n7.  Percentage of hurdles with the same finger should be as low as possible.\n8.  Percentage of hurdles with adjacent offset fingers should be as low as possible.\n9.  Percentage of hurdles with remote fingers should be as low as possible.\n10. Percentage of reach with the same finger should be as low as possible.\n11. Percentage of reach with adjacent offset fingers should be as low as possible.\n\n#### Synopsis of above criteria for pairwise key presses when touch typing:\n1. Alternate between hands.\n2. Balance finger loads, and avoid using the same finger.\n3. Avoid the upper and lower rows, and avoid skipping over the home row.\n4. Avoid tapping adjacent offset rows with the same or adjacent offset fingers.\n    \n### Factors to penalize strenuous key transitions\n\nDirection:\n    \n    - outward = 0.9: outward roll of fingers from the index to little finger (same hand)\n\nDexterity:\n    \n    - side_above_3away = 0.9\n        - index and little finger type two keys, one or more rows apart (same hand)\n    - side_above_2away = 0.9^2 = 0.81\n        - index finger types key a row or two above ring finger key, or\n        - little finger types key a row or two above middle finger key (same hand)\n    - side_above_1away = 0.9^3 = 0.729\n        - index finger types key a row or two above middle finger key, or\n        - little finger types key a row or two above ring finger key (same hand)\n    - middle_above_ring = 0.9\n        - middle finger types key a row or two above ring finger key (same hand)\n    - ring_above_middle = 0.9^3 = 0.729\n        - ring finger types key a row or two above middle finger key (same hand)\n    - lateral = 0.9\n        - lateral movement of (index or little) finger outside of 8 vertical columns\n    \nDistance:\n    \n    - skip_row_3away = 0.9       \n        - index and little fingers type two keys that skip over home row (same hand)\n        - (e.g., one on bottom row, the other on top row)\n    - skip_row_2away = 0.9^3 = 0.729\n        - little and middle or index and ring fingers type two keys that skip over home row (same hand)\n    - skip_row_1away = 0.9^5 = 0.59049\n        - little and ring or middle and index fingers type two keys that skip over home row (same hand)\n\nRepetition:\n \n    - skip_row_0away = 0.9^4 = 0.6561\n        - same finger types two keys that skip over home row\n    - same_finger = 0.9^5 = 0.59049\n        - use same finger again for a different key\n        - cannot accompany outward, side_above, or adjacent_shorter_above \n\nStrength: Accounted for by the strength matrix (minimum value for the little finger = 0.9)    \n\n### Example flow values for left side home block\n   \nNo penalty (for same hand, both keys in the same row in an inward roll or repeating the same key):\n\n    2=>2, 2=>3, 3=>4, 2=>4, 1=>4\n\n    1  2  3  4\n    5  6  7  8\n    9 10 11 12\n\nPenalty = 0.9:\n\n    outward: 2=>1, 3=>1, 3=>2, 4=>1, 4=>2, 4=>3, 6=>5, 7=>6, 7=>5, 8=>7, 8=>6, 8=>5,... \n    middle_above_ring: 6=>3, 10=>7 \n    side_above_3away: 1=>8, 5=>4, 5=>12, 9=>8\n    index_above: 1=>4, 2=>4, 3=>4, 4=>4\n\nPenalty = 0.9^2:\n\n    middle_above_ring * outward: 3=>6, 7=>10\n    side_above_3away * outward: 8=>1, 4=>5, 12=>5, 8=>9\n    side_above_2away: 1=>7, 6=>4, 5=>11, 10=>8    \n    skip_row_3away * side_above_3away: 1=>12, 9=>4\n    skip_row_2away: 2=>12, 9=>3\n    ring_above_middle 2=>7, 6=>11\n    side_above_2away * outward: 7=>1, 4=>6, 11=>5, 8=>10\n    side_above_1away: 1=>6, 7=>4, 5=>10, 11=>8\n\nPenalty = 0.9^3:\n\n    skip_row_3away * side_above_3away * outward: 12=>1, 4=>9\n\nPenalty = 0.9^4:\n\n    ring_above_middle * outward: 7=>2, 11=>6\n    side_above_1away * outward: 4=>7, 6=>1, 10=>5, 4=>7\n\nPenalty = 0.9^5:\n\n    same_finger: 4=>8, 8=>4, 1=>5, 5=>1, 5=>9, 9=>5, 2=>6, 6=>2,...\n    skip_row_2away * side_above_2away: 10=>4, 1=>11\n    skip_row_1away: 1=>10, 9=>2, 3=>12\n\nPenalty = 0.9^6:\n\n    skip_row_2away * side_above_2away * outward: 4=>10, 11=>1\n    skip_row_1away * outward: 10=>1, 2=>9, 12=>3\n\nPenalty = 0.9^8\n\n    skip_row_1away * ring_above_middle: 2=>11\n    skip_row_1away * side_above_1away: 1=>10, 11=>4\n\nPenalty = 0.9^9\n\n    skip_row_1away * ring_above_middle * outward: 11=>2\n    skip_row_0away * same_finger: 1=>9, 9=>1, 4=>12, 12=>4, 2=>10, 10=>2, 3=>11, 11=>3     \n    skip_row_1away * side_above_1away * outward: 10=>1, 4=>11\n\n\n```python\n# %load code/load_flow_matrices.py\n# Penalizing factors for 24 keys  (1 = no penalty; set to less than 1 to penalize):\n\n# Dexterity\nside_above_3away = 0.9     # index and little finger type two keys, one or more rows apart (same hand)\nside_above_2away = 0.81    # index finger types key a row or two above ring finger key, or\n                           # little finger types key a row or two above middle finger key (same hand)\nside_above_1away = 0.729   # index finger types key a row or two above middle finger key, or\n                           # little finger types key a row or two above ring finger key (same hand)\nmiddle_above_ring = 0.9    # middle finger types key a row or two above ring finger key (same hand)\nring_above_middle = 0.729  # ring finger types key a row or two above middle finger key (same hand)\nlateral = 0.9              # lateral movement of (index or little) finger outside of 8 vertical columns\n\n# Direction\noutward = 0.9              # outward roll of fingers from the index to little finger (same hand)\n\n# Distance\nskip_row_3away = 0.9       # index and little fingers type two keys that skip over home row (same hand)\n                           # (e.g., one on bottom row, the other on top row)\nskip_row_2away = 0.729     # little and middle or index and ring fingers type two keys that skip over home row (same hand)\nskip_row_1away = 0.59049   # little and ring or middle and index fingers type two keys that skip over home row (same hand)\n\n# Repetition\nskip_row_0away = 0.6561    # same finger types two keys that skip over home row\nsame_finger = 0.59049      # use same finger again for a different key\n\n\n# Unused or redundant parameters\nsame_hand = 1.0            # (addressed by splitting up the most frequent letters across left/right sides above)\nnot_home_row = 1.0         # at least one key not on home row\nside_top = 1.0             # index or little finger types top corner key\nshorter_above = 1.0        # (taken care of by side_above_[1,2,3]away parameters)\nadjacent_offset = 1.0      # (taken care of by side_above_1away, middle_above_ring, ring_above_middle parameters)\ninside_top = 1.0           # index finger types top corner key (taken care of by side_above_1away parameter)\nindex_above = 1.0          # index finger types top corner key (unless other bigram key is in the top row for the same hand)\n                           # (taken care of by side_above_[1,2,3]away parameters)\n\n\ndef create_24x24_flow_matrix(not_home_row, side_top, side_above_3away, side_above_2away, side_above_1away, \n                             middle_above_ring, ring_above_middle, outward, skip_row_3away, \n                             skip_row_2away, skip_row_1away, skip_row_0away, same_finger, lateral, \n                             same_hand, shorter_above, adjacent_offset, inside_top, index_above):\n\n    all_24_keys = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24]\n\n    # Create a matrix and multiply by flow factors that promote easy interkey transitions:\n    T = np.ones((24, 24))\n\n    # 7.  Promote alternating between hands over uncomfortable transitions with the same hand.\n    if same_hand < 1.0:\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n        for i in range(0,12):\n            for j in range(0,12):\n                T[i,j] *= same_hand\n        for i in range(12,24):\n            for j in range(12,24):\n                T[i,j] *= same_hand\n\n    # 8.  Promote little-to-index-finger roll-ins over index-to-little-finger outwards.\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    if outward < 1.0:\n\n        # same-row roll-outs:\n        roll_ins = [[1,2],[2,3],[3,4], [5,6],[6,7],[7,8], [9,10],[10,11],[11,12],\n                    [16,15],[15,14],[14,13], [20,19],[19,18],[18,17], [24,23],[23,22],[22,21]]\n        for x in roll_ins:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # same-row roll-outs, skipping keys:\n        roll_ins_skip_keys = [[1,3],[2,4],[1,4], [5,7],[6,8],[5,8], [9,11],[10,12],[9,12],\n                              [16,14],[15,13],[16,13], [20,18],[19,17],[20,17], [24,22],[23,21],[24,21]]\n        for x in roll_ins_skip_keys:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # adjacent-row roll-outs:\n        roll_ins_adj_rows = [[1,6],[1,7],[1,8],[2,7],[2,8],[3,8], [5,2],[5,3],[5,4],[6,3],[6,4],[7,4],\n                             [5,10],[5,11],[5,12],[6,11],[6,12],[7,12], [9,6],[9,7],[9,8],[10,7],[10,8],[11,8],\n                             [16,19],[16,18],[16,17],[15,18],[15,17],[14,17], [20,15],[20,14],[20,13],[19,14],[19,13],[18,13],\n                             [20,23],[20,22],[20,21],[19,22],[19,21],[18,21], [24,19],[24,18],[24,17],[23,18],[23,17],[22,17]]\n        for x in roll_ins_adj_rows:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # upper<->lower row roll-outs:\n        roll_ins_skip_home = [[1,10],[1,11],[1,12],[2,11],[2,12],[3,12], [9,2],[9,3],[9,4],[10,3],[10,4],[11,4],\n                              [16,23],[16,22],[16,21],[15,22],[15,21],[14,21], [24,15],[24,14],[24,13],[23,14],[23,13],[22,13]]\n        for x in roll_ins_skip_home:\n            T[x[1]-1, x[0]-1] *= outward\n\n    # 9.  Avoid stretching shorter fingers up and longer fingers down.\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    if index_above < 1.0:\n        for x in [4]:\n            for y in [4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n        for x in [13]:\n            for y in [1,2,3,4,5,6,7,8,9,10,11,12,13,17,18,19,20,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n    if inside_top < 1.0:\n        for x in [4,13]:\n            for j in range(0,24):\n                T[x-1, j] *= inside_top\n                T[j, x-1] *= inside_top\n    if side_top < 1.0:\n        for x in [1,4,13,16]:\n            for j in range(0,24):\n                T[x-1, j] *= side_top\n                T[j, x-1] *= side_top\n    if side_above_1away < 1.0:\n        for x in [1]:\n            for y in [6,10]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [5]:\n            for y in [10]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [4]:\n            for y in [7,11]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [8]:\n            for y in [11]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [13]:\n            for y in [18,22]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [17]:\n            for y in [22]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [16]:\n            for y in [19,23]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [20]:\n            for y in [23]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n    if side_above_2away < 1.0:\n        for x in [1]:\n            for y in [7,11]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [5]:\n            for y in [11]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [4]:\n            for y in [6,10]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [8]:\n            for y in [10]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [13]:\n            for y in [19,23]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [17]:\n            for y in [23]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [16]:\n            for y in [18,22]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [20]:\n            for y in [22]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n    if side_above_3away < 1.0:\n        for x in [1]:\n            for y in [8,12]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [5]:\n            for y in [12]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [4]:\n            for y in [5,9]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [8]:\n            for y in [9]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [13]:\n            for y in [20,24]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [17]:\n            for y in [24]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [16]:\n            for y in [17,21]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [20]:\n            for y in [21]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n    if shorter_above < 1.0:\n        for x in [1]:\n            for y in [6,7,8,10,11,12]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [2]:\n            for y in [7,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [4]:\n            for y in [6,7,10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [5]:\n            for y in [10,11,12]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [6]:\n            for y in [11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [8]:\n            for y in [10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [16]:\n            for y in [17,18,19,21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [15]:\n            for y in [18,22]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [13]:\n            for y in [18,19,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [20]:\n            for y in [21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [19]:\n            for y in [22]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [17]:\n            for y in [22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n    if ring_above_middle < 1.0:\n        ring_above_middles =  [[2,7],[6,11],[2,11],\n                            [15,18],[19,22],[15,22]]\n        for x in ring_above_middles:\n            T[x[0]-1, x[1]-1] *= ring_above_middle\n            T[x[1]-1, x[0]-1] *= ring_above_middle\n\n    if middle_above_ring < 1.0:\n        middle_above_rings =  [[6,3],[10,7],[10,3],\n                            [19,14],[23,18],[23,14]]\n        for x in middle_above_rings:\n            T[x[0]-1, x[1]-1] *= middle_above_ring\n            T[x[1]-1, x[0]-1] *= middle_above_ring\n\n    # 10. Avoid using the same finger.\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    if same_finger < 1.0:\n        same_fingers = [[1,5],[5,9],[1,9], [2,6],[6,10],[2,10], [3,7],[7,11],[3,11], [4,8],[8,12],[4,12],\n                        [13,17],[17,21],[13,21], [14,18],[18,22],[14,22], [15,19],[19,23],[15,23], [16,20],[20,24],[16,24]] \n        for x in same_fingers:\n            T[x[0]-1, x[1]-1] *= same_finger\n            T[x[1]-1, x[0]-1] *= same_finger\n\n    # 11. Avoid the upper and lower rows.\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    if not_home_row < 1.0:\n        not_home_row_keys = [1,2,3,4, 9,10,11,12, 13,14,15,16, 21,22,23,24]\n        for x in not_home_row_keys:\n            for j in range(0,23):\n                T[x-1, j] *= not_home_row\n                T[j, x-1] *= not_home_row\n\n    # 12. Avoid skipping over the home row.\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    if skip_row_0away < 1.0:\n        skip_top = [1, 2, 3, 4, 13,14,15,16] \n        skip_bot = [9,10,11,12, 21,22,23,24] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_0away\n            T[y-1, x-1] *= skip_row_0away\n    if skip_row_1away < 1.0:\n        skip_top = [1, 2, 2, 3, 3, 4, 13,14,14,15,15,16] \n        skip_bot = [10,9,11,10,12,11, 22,21,23,22,24,23] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_1away\n            T[y-1, x-1] *= skip_row_1away\n    if skip_row_2away < 1.0:\n        skip_top = [1,  2,3, 4, 13,14,15,16] \n        skip_bot = [11,12,9,10, 23,24,21,22] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_2away\n            T[y-1, x-1] *= skip_row_2away\n    if skip_row_3away < 1.0:\n        skip_top = [1, 4, 13,16] \n        skip_bot = [12,9, 24,21] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_3away\n            T[y-1, x-1] *= skip_row_3away\n\n    Flow24x24 = T\n\n    # Normalize matrix with min-max scaling to a range with maximum = 1:\n    newMin = np.min(Flow24x24) / np.max(Flow24x24)\n    newMax = 1.0\n    Flow24x24 = newMin + (Flow24x24 - np.min(Flow24x24)) * (newMax - newMin) / (np.max(Flow24x24) - np.min(Flow24x24))\n\n    return Flow24x24\n\nFlow24x24 = create_24x24_flow_matrix(not_home_row, side_top, \n    side_above_3away, side_above_2away, side_above_1away, middle_above_ring, ring_above_middle, outward, \n    skip_row_3away, skip_row_2away, skip_row_1away, skip_row_0away, same_finger, lateral, same_hand, \n    shorter_above, adjacent_offset, inside_top, index_above)\n\n# Print:\nprint_matrix_info(matrix_data=Flow24x24, matrix_label=\"Flow24x24\", nkeys=24, nlines=30)\nheatmap(data=Flow24x24, title=\"Flow24x24\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n\ndef create_32x32_flow_matrix(not_home_row, side_top, side_above_3away, side_above_2away, side_above_1away, \n                             middle_above_ring, ring_above_middle, outward, skip_row_3away, \n                             skip_row_2away, skip_row_1away, skip_row_0away, same_finger, lateral, \n                             same_hand, shorter_above, adjacent_offset, inside_top, index_above):\n\n    all_32_keys = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, \n                   25,26,27, 28,29,30, 31,32]\n\n    # Create a matrix and multiply by flow factors that promote easy interkey transitions:\n    T = np.ones((32, 32))\n\n    if lateral < 1.0:\n        for x in all_32_keys:\n            for y in [25,26,27, 28,29,30, 31,32]:\n                T[x-1, y-1] *= lateral\n                T[y-1, x-1] *= lateral    \n\n    # 7.  Promote alternating between hands over uncomfortable transitions with the same hand.\n    if same_hand < 1.0:\n        for i in [1,2,3,4,5,6,7,8,9,10,11,12, 25,26,27]:\n            for j in [1,2,3,4,5,6,7,8,9,10,11,12, 25,26,27]:\n                T[i-1,j-1] *= same_hand\n        for i in [13,14,15,16,17,18,19,20,21,22,23,24, 28,29,30,31,32]:\n            for j in [13,14,15,16,17,18,19,20,21,22,23,24, 28,29,30,31,32]:\n                T[i-1,j-1] *= same_hand\n\n    # 8.  Promote little-to-index-finger roll-ins over index-to-little-finger outsward rolls.\n    # Penalize (index, little) finger lateral movements:\n    #  1  2  3  4 25   28 13 14 15 16 31 \n    #  5  6  7  8 26   29 17 18 19 20 32\n    #  9 10 11 12 27   30 21 22 23 24\n    if outward < 1.0:\n\n        # same-row roll-outs:\n        roll_ins = [[1,2],[2,3],[3,4], [5,6],[6,7],[7,8], [9,10],[10,11],[11,12],\n                    [16,15],[15,14],[14,13], [20,19],[19,18],[18,17], [24,23],[23,22],[22,21]]\n        for x in roll_ins:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # same-row roll-outs, skipping keys:\n        roll_ins_skip_keys = [[1,3],[2,4],[1,4], [5,7],[6,8],[5,8], [9,11],[10,12],[9,12],\n                              [16,14],[15,13],[16,13], [20,18],[19,17],[20,17], [24,22],[23,21],[24,21]]\n                              #[1,25],[2,25],[3,25],\n                              #[5,26],[6,26],[7,26],\n                              #[9,27],[10,27],[11,27],\n                              #[16,28],[15,28],[14,28],\n                              #[20,29],[19,29],[18,29],\n                              #[24,30],[23,30],[22,30],\n                              #[31,15],[31,14],[31,13],[31,28],\n                              #[32,19],[32,18],[32,17],[32,29]]\n        for x in roll_ins_skip_keys:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # adjacent-row roll-outs:\n        #  1  2  3  4 25   28 13 14 15 16 31 \n        #  5  6  7  8 26   29 17 18 19 20 32\n        #  9 10 11 12 27   30 21 22 23 24\n        roll_ins_adj_rows = [[1,6],[1,7],[1,8],[2,7],[2,8],[3,8], \n                             [5,2],[5,3],[5,4],[6,3],[6,4],[7,4],\n                             [5,10],[5,11],[5,12],[6,11],[6,12],[7,12], \n                             [9,6],[9,7],[9,8],[10,7],[10,8],[11,8],\n                             [16,19],[16,18],[16,17],[15,18],[15,17],[14,17], \n                             [20,15],[20,14],[20,13],[19,14],[19,13],[18,13],\n                             [20,23],[20,22],[20,21],[19,22],[19,21],[18,21], \n                             [24,19],[24,18],[24,17],[23,18],[23,17],[22,17]]\n                             #[5,25],[6,25],[7,25],[8,25],\n                             #[5,27],[6,27],[7,27],[8,27],\n                             #[1,26],[2,26],[3,26],[4,26],\n                             #[9,26],[10,26],[11,26],[12,26],\n                             #[16,29],[15,29],[14,29],[13,29],\n                             #[24,29],[23,29],[22,29],[21,29],\n                             #[20,28],[19,28],[18,28],[17,28],\n                             #[20,30],[19,30],[18,30],[17,30],\n                             #[31,20],[31,19],[31,18],[31,17],[31,29],\n                             #[32,16],[32,15],[32,14],[32,13],[32,28],\n                             #[32,24],[32,23],[32,22],[32,21],[32,30]]\n        for x in roll_ins_adj_rows:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # upper<->lower row roll-outs:\n        roll_ins_skip_home = [[1,10],[1,11],[1,12],[2,11],[2,12],[3,12],\n                              [9,2],[9,3],[9,4],[10,3],[10,4],[11,4],\n                              [16,23],[16,22],[16,21],[15,22],[15,21],[14,21],\n                              [24,15],[24,14],[24,13],[23,14],[23,13],[22,13]]\n                              #[16,30],[15,30],[14,30],[13,30],\n                              #[9,25],[10,25],[11,25],[12,25],\n                              #[24,28],[23,28],[22,28],[21,28],\n                              #[1,27],[2,27],[3,27],[4,27], \n                              #[31,24],[31,23],[31,22],[31,21],[31,30]]\n        for x in roll_ins_skip_home:\n            T[x[1]-1, x[0]-1] *= outward\n\n    # 9.  Avoid stretching shorter fingers up and longer fingers down.\n    #  1  2  3  4 25   28 13 14 15 16 31 \n    #  5  6  7  8 26   29 17 18 19 20 32\n    #  9 10 11 12 27   30 21 22 23 24\n    if index_above < 1.0:\n        for x in [4]:\n            for y in [4,5,6,7,8,26,9,10,11,12,27,28,13,14,15,16,31,29,17,18,19,20,32,30,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n        for x in [25]:\n            for y in [25,5,6,7,8,26,9,10,11,12,27,28,13,14,15,16,31,29,17,18,19,20,32,30,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n        for x in [13]:\n            for y in [1,2,3,4,25,5,6,7,8,26,9,10,11,12,27,13,29,17,18,19,20,32,30,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n        for x in [28]:\n            for y in [1,2,3,4,25,5,6,7,8,26,9,10,11,12,27,28,29,17,18,19,20,32,30,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n    if inside_top < 1.0:\n        for x in [4,25,28,13]:\n            for j in range(0,32):\n                T[x-1, j] *= inside_top\n                T[j, x-1] *= inside_top\n    if side_top < 1.0:\n        for x in [1,4,25,28,13,16,31]:\n            for j in range(0,32):\n                T[x-1, j] *= side_top\n                T[j, x-1] *= side_top\n    if side_above_1away < 1.0:\n        for x in [1]:\n            for y in [6,10]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [5]:\n            for y in [10]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [4,25]:\n            for y in [7,11]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [8,26]:\n            for y in [11]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [13,28]:\n            for y in [18,22]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [17,29]:\n            for y in [22]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [16,31]:\n            for y in [19,23]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [20,32]:\n            for y in [23]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n    if side_above_2away < 1.0:\n        for x in [1]:\n            for y in [7,11]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [5]:\n            for y in [11]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [4,25]:\n            for y in [6,10]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [8,26]:\n            for y in [10]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [13,28]:\n            for y in [19,23]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [17,29]:\n            for y in [23]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [16,31]:\n            for y in [18,22]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [20,32]:\n            for y in [22]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n    if side_above_3away < 1.0:\n        for x in [1]:\n            for y in [8,12,26,27]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [5]:\n            for y in [12,27]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [4,25]:\n            for y in [5,9]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [8,26]:\n            for y in [9]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [13,28]:\n            for y in [20,24,32]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [17,29]:\n            for y in [24]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [16,31]:\n            for y in [17,21,29,30]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [20,32]:\n            for y in [21,30]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n\n\n    #  1  2  3  4 25   28 13 14 15 16 31 \n    #  5  6  7  8 26   29 17 18 19 20 32\n    #  9 10 11 12 27   30 21 22 23 24\n    if shorter_above < 1.0:\n        for x in [1]:\n            for y in [6,7,8,26,10,11,12,27]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [2]:\n            for y in [7,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [4]:\n            for y in [6,7,10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [25]:\n            for y in [6,7,10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [5]:\n            for y in [10,11,12,27]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [6]:\n            for y in [11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [8]:\n            for y in [10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [26]:\n            for y in [10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [16]:\n            for y in [29,17,18,19,30,21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [31]:\n            for y in [29,17,18,19,30,21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [15]:\n            for y in [18,22]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [13]:\n            for y in [18,19,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [28]:\n            for y in [18,19,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [20]:\n            for y in [30,21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [32]:\n            for y in [30,21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [19]:\n            for y in [22]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [17]:\n            for y in [22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [29]:\n            for y in [22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n    if ring_above_middle < 1.0:\n        ring_above_middles =  [[2,7],[6,11],[2,11],\n                            [15,18],[19,22],[15,22]]\n        for x in ring_above_middles:\n            T[x[0]-1, x[1]-1] *= ring_above_middle\n            T[x[1]-1, x[0]-1] *= ring_above_middle\n\n    if middle_above_ring < 1.0:\n        middle_above_rings =  [[6,3],[10,7],[10,3],\n                            [19,14],[23,18],[23,14]]\n        for x in middle_above_rings:\n            T[x[0]-1, x[1]-1] *= middle_above_ring\n            T[x[1]-1, x[0]-1] *= middle_above_ring\n\n    # 10. Avoid using the same finger.\n    #  1  2  3  4 25   28 13 14 15 16 31 \n    #  5  6  7  8 26   29 17 18 19 20 32\n    #  9 10 11 12 27   30 21 22 23 24\n    if same_finger < 1.0:\n        same_fingers = [[1,5],[5,9],[1,9], [2,6],[6,10],[2,10], \n                        [3,7],[7,11],[3,11], [4,8],[8,12],[4,12],\n                        [25,26],[26,27],[25,27], [28,29],[29,30],[28,30], [31,32],\n                        [4,25],[4,26],[4,27], [8,25],[8,26],[8,27], [12,25],[12,26],[12,27],\n                        [13,28],[13,29],[13,30], [17,28],[17,29],[17,30], [21,28],[21,29],[21,30],\n                        [31,16],[31,20],[31,24], [32,16],[32,20],[32,24],\n                        [13,17],[17,21],[13,21], [14,18],[18,22],[14,22], \n                        [15,19],[19,23],[15,23], [16,20],[20,24],[16,24]] \n        for x in same_fingers:\n            T[x[0]-1, x[1]-1] *= same_finger\n            T[x[1]-1, x[0]-1] *= same_finger\n\n    # 11. Avoid the upper and lower rows.\n    if not_home_row < 1.0:\n        not_home_row_keys = [1,2,3,4,25, 9,10,11,12,27, 28,13,14,15,16,31, 30,21,22,23,24]\n        for x in not_home_row_keys:\n            for j in range(0,32):\n                T[x-1, j] *= not_home_row\n                T[j, x-1] *= not_home_row\n                \n    # 12. Avoid skipping over the home row.\n    #  1  2  3  4 25   28 13 14 15 16 31 \n    #  5  6  7  8 26   29 17 18 19 20 32\n    #  9 10 11 12 27   30 21 22 23 24\n    if skip_row_0away < 1.0:\n        skip_top = [1, 2, 3, 4, 4,25,25, 28,28,13,13,14,15,16,31] \n        skip_bot = [9,10,11,12,27,12,27, 30,21,30,21,22,23,24,24] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_0away\n            T[y-1, x-1] *= skip_row_0away\n    if skip_row_1away < 1.0:\n        skip_top = [1, 2, 2, 3, 3, 4, 4,25, 28,13,13,14,14,15,15,16,31] \n        skip_bot = [10,9,11,10,12,11,27,11, 22,30,22,21,23,22,24,23,23] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_1away\n            T[y-1, x-1] *= skip_row_1away\n    if skip_row_2away < 1.0:\n        skip_top = [1,  2,3, 4,25, 28,13,14,15,16,31] \n        skip_bot = [11,12,9,10,10, 23,23,24,21,22,22] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_2away\n            T[y-1, x-1] *= skip_row_2away\n    if skip_row_3away < 1.0:\n        skip_top = [1, 4,25, 28,13,16,16,31,31] \n        skip_bot = [12,9, 9, 24,24,21,30,21,30] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_3away\n            T[y-1, x-1] *= skip_row_3away\n                \n    Flow32x32 = T\n\n    # Normalize matrix with min-max scaling to a range with maximum = 1:\n    newMin = np.min(Flow32x32) / np.max(Flow32x32)\n    newMax = 1.0\n    Flow32x32 = newMin + (Flow32x32 - np.min(Flow32x32)) * (newMax - newMin) / (np.max(Flow32x32) - np.min(Flow32x32))\n\n    return Flow32x32\n\nFlow32x32 = create_32x32_flow_matrix(not_home_row, side_top, \n    side_above_3away, side_above_2away, side_above_1away, middle_above_ring, ring_above_middle, outward, \n    skip_row_3away, skip_row_2away, skip_row_1away, skip_row_0away, same_finger, lateral, same_hand, \n    shorter_above, adjacent_offset, inside_top, index_above)\n\n# Print:\nprint_matrix_info(matrix_data=Flow32x32, matrix_label=\"Flow32x32\", nkeys=32, nlines=30)\nheatmap(data=Flow32x32, title=\"Flow32x32\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n```\n\n## Combine Strength and Flow matrices  <a name=\"strengthflow\">\n\n\n```python\n# %load code/combine_scoring_matrices.py\n# 24 keys:\nFactors24x24 = Flow24x24\nif apply_strength:\n    Factors24x24 = Strength24x24 * Factors24x24\n\n# Print:\nprint_matrix_info(matrix_data=Factors24x24, matrix_label=\"Factors24x24\", nkeys=24, nlines=30)\nheatmap(data=Factors24x24, title=\"Factors24x24\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n# Save:\nif print_output:\n    file = open(\"Factors24x24.txt\", \"w+\")\n    file.write(str(Factors24x24))\n    file.close()\n\n\n# 32 keys:\nFactors32x32 = Flow32x32\nif apply_strength:\n    Factors32x32 = Strength32x32 * Factors32x32\n\n# Print:\nprint_matrix_info(matrix_data=Factors32x32, matrix_label=\"Factors32x32\", nkeys=32, nlines=30)\nheatmap(data=Factors32x32, title=\"Factors32x32\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n# Save:\nif print_output:\n    file = open(\"Factors32x32.txt\", \"w+\")\n    file.write(str(Factors32x32))\n    file.close()\n```\n\n## Four steps\n\nWe will assign letters to keys by choosing the arrangement with the highest score according to our scoring model. However, there are over four hundred septillion, or four hundred trillion trillion (26! = 403,291,461,126,605,635,584,000,000, or 4.032914611 E+26) possible arrangements of 26 letters (24! = 6.204484017 E+23), so we will arrange the letters in four steps, based on ergonomics principles. These consist of (Step 1) assigning the eight most frequent letters to different keys, optimizing assignment of the remaining (Step 2) eight most frequent letters, and (Step 3) eight least frequent letters (besides Z and Q), and (Step 4) exchanging letters. \n\n## Step 1: Define the shape of the key layout to minimize lateral finger movements<a name=\"step1\">\n\nWe will assign 24 letters to 8 columns of keys separated by two middle columns reserved for punctuation. These 8 columns require no lateral finger movements when touch typing, since there is one column per finger. The most comfortable keys include the left and right home rows (keys 5-8 and 17-20), the top-center keys (2,3 and 14,15) that allow the longer middle and ring fingers to uncurl upwards, as well as the bottom corner keys (9,12 and 21,24) that allow the shorter fingers to curl downwards. We will assign the two least frequent letters, W and K, to the two hardest-to-reach keys lying outside the 24-key columns in the upper right (25 and 26):\n\n        Left:            Right:\n     1  2  3  4       13 14 15 16 25\n     5  6  7  8       17 18 19 20 26\n     9 10 11 12       21 22 23 24\n\nWe will consider the most comfortable keys to be those typed by either hand on the home row, by the ring and middle finger above the home row, and by the index and little finger below the home row, with a preference for the strongest (index and middle) fingers:\n    \n     -  2  3  -        - 14 15  -  \n     5  6  7  8       17 18 19 20  \n     9  -  - 12       21  -  - 24\n\n## Step 2: Arrange the most frequent letters based on comfort and bigram frequencies  <a name=\"step2\">\n\nBelow, we will arrange vowels on one side and the most frequent consonants to the other side to encourage balance and alternation across hands. Since aside from the letters W and K there is symmetry across left and right sides, we will decide later which side the vowels and which side the most frequent consonants should go.\n\n### Vowels\n    \n**E, A, O**, S, N, **I**, R, L, D, C, T, U, M, P, B, G, V, Q, Y, F, H, J, Z, X, K, W\n                         \nBigrams that contain two non-repeating vowels, and their frequencies:\n  \n    UE\t17135545\n    IO\t10629390\n    IA\t 9704625\n    IE \t 8264649\n    UA\t 2727622\n    UI\t 2699510\n    EA   1634965\n    AU   1206620\n    EO\t  787382\n    AI\t  768894\n    EI\t  578063\n    EU\t  338775\n    IU\t  314965\n    AE\t  279633\n    OI\t  193436\n    OE\t  182266\n    UO\t  175574\n    OU\t  174475\n    OA\t  117839\n    AO\t   88065\n  \nWe will assign the most frequent vowels (E=294897235, A=271738665, O=201996963, I=151438547) to four of the six most comfortable keys on the left side of the keyboard (keys 2,3,5,6,7,8). We will assign the letter E, the most frequent in the Spanish language, to the strongest (middle) finger on the home row, and assign the other three vowels such that (1) the home row keys typed by the index and middle fingers are not left vacant, and any top-frequency bigram (more than 1 million instances) (2) does not use the same finger and (3) reads from left to right (ex: UE, not EU) for ease of typing (inward roll from little to index finger vs. outward roll from index to little finger). These constraints lead to 4 arrangements of the 4 vowels:\n\n    - - O -    - - O -    - O - -    - - - -    \n    - I E A    I - E A    I - E A    I O E A\n    - - - -    - - - -    - - - -    - - - -\n\n### Consonants\n\nE, A, O, **S, N**, I, **R, L, D, C, T**, U, M, P, B, G, V, Q, Y, F, H, J, Z, X, K, W\n\nOn the right side of the keyboard, we will assign four of the seven most frequent consonants (S=162205879, N=161440601, R=147218050, L=124544026, D=113430944, C=99562807, T=99294129) to the four home row keys. We will assign the letter S, the most frequent consonant in the Spanish language, to the strongest (middle) finger on the home row.\n    \nBigrams that contain two non-repeating consonants, with frequencies greater than 1 million:\n\n    NT\t13403852\n    ST\t10479844\n    TR   6982844\n    ND\t 6501402\n    PR\t 5241844\n    NC\t 4535985\n    RT\t 3473930\n    BR\t 3216626\n    MP\t 3063320\n    CH\t 2911020\n    SP\t 2412701\n    NS\t 2352231\n    MB\t 2169462\n    GR\t 2082624\n    BL\t 2053224\n    CT\t 1927284\n    RM\t 1908571\n    SC\t 1907706\n    CR\t 1537677\n    RD\t 1524597\n    RS\t 1509084\n    PL\t 1459569\n    RC\t 1280075\n    NG\t 1253772\n    LT\t 1253199\n    DR\t 1140387\n    RN\t 1072129\n    RG\t 1017226\n\nBigrams from the above list that contain two of the most frequent consonants (S, N, R, L, D, C, T):\n    \n    NT\t13403852\n    ST\t10479844\n    TR   6982844\n    ND\t 6501402\n    NC\t 4535985\n    RT\t 3473930\n    NS\t 2352231\n    CT\t 1927284\n    SC\t 1907706\n    CR\t 1537677\n    RD\t 1524597\n    RS\t 1509084\n    RC\t 1280075\n    LT\t 1253199\n    DR\t 1140387\n    RN\t 1072129\n\nAs with the left side, letters are placed so that top-frequency bigrams read from right to left (ex: \"NT\" read as TN, not NT) except when both sequences have more than 1 million instances (TR/RT, CR/RC, and RD/DR), for ease of typing. The above constraints lead to 4 arrangements of the consonants:\n\n    - - - -    - - - -    - - - -    - - - -\n    L S N R    D S N R    C S N R    T S N R\n    - - - -    - - - -    - - - -    - - - -\n\nThe resulting 16 initial layouts, each with 16 unassigned keys, are represented below with the three rows on the left and right side of the keyboard as a linear string of letters, with unassigned keys denoted by \u201c-\u201d.\n    \n    Pattern 1:\n    \n    --O- -IEA ----    ---- LSNR ----\n    --O- -IEA ----    ---- DSNR ----\n    --O- -IEA ----    ---- CSNR ----\n    --O- -IEA ----    ---- TSNR ----\n\n    Pattern 2:\n    \n    --O- I-EA ----    ---- LSNR ----\n    --O- I-EA ----    ---- DSNR ----\n    --O- I-EA ----    ---- CSNR ----\n    --O- I-EA ----    ---- TSNR ----\n\n    Pattern 3:\n    \n    -O-- I-EA ----    ---- LSNR ----\n    -O-- I-EA ----    ---- DSNR ----\n    -O-- I-EA ----    ---- CSNR ----\n    -O-- I-EA ----    ---- TSNR ----\n\n    Pattern 4:\n    \n    ---- IOEA ----    ---- LSNR ----\n    ---- IOEA ----    ---- DSNR ----\n    ---- IOEA ----    ---- CSNR ----\n    ---- IOEA ----    ---- TSNR ----    \n\n\n## Step 3: Optimize assignment of the remaining letters <a name=\"step3\">\n    \nWe want to assign letters to the 16 unassigned keys in each of the above 16 layouts based on our scoring model. That would mean scoring all possible arrangements for each layout and choosing the arrangement with the highest score, but since there are over 20 trillion (16!) possible ways of arranging 16 letters, we will break up the assignment into two stages for the most frequent and least frequent remaining letters. \n    \n### Most frequent letters\nWe will compute scores for every possible arrangement of the seven most frequent of the remaining letters (in bold below) assigned to vacancies among the most comfortable sixteen keys.\n\nE, A, O, S, N, I, R, **L, D, C, T, U, P, M, B, G**, V, Q, H, F, Y, J, Z, X, K, W\n\n        Left:            Right:\n     -  2  3  -        - 14 15  -\n     5  6  7  8       17 18 19 20\n     9  -  - 12       21  -  - 24\n\nSince there are 40,320 (8!) possible combinations of eight letters for each of the 16 layouts, we need to score and evaluate 645,120 layouts. To score each arrangement of letters, we construct a frequency matrix where we multiply a matrix containing the frequency of each ordered pair of letters (bigram) by our flow and strength matrices to compute a score.\n    \n### Least frequent letters\nNext we will compute scores for every possible (40,320 = 8!) arrangement of the least frequent eight letters (in bold below, besides W and K) in the remaining keys, after substituting in the 16 top results of the above, for another 645,120 layouts:\n\nE, A, O, S, N, I, R, L, D, C, T, U, P, M, B, G, **V, Q, H, F, Y, J, Z, X**, K, W\n\n        Left:            Right:\n     1  -  -  4       13  -  - 16\n     -  -  -  -        -  -  -  -\n     - 10 11  -        - 22 23  -\n     \n### Further optimize layouts by exchanging more letters\n\nIf we relax the above fixed initializations and permit further exchange of letters, then we can search for even higher-scoring layouts. As a final optimization step we exchange letters, eight keys at a time (8! = 40,320) selected twice in 14 different ways, in each of the above 16 layouts, to score a total of over 18 million combinations. We allow the following keys to exchange letters:\n\n    1. Top rows\n    2. Bottom rows\n    3. Top and bottom rows on the right side\n    4. Top and bottom rows on the left side\n    5. Top right and bottom left rows\n    6. Top left and bottom right rows\n    7. Center of the top and bottom rows on both sides\n    8. The eight corners\n    9. Left half of the top and bottom rows on both sides\n    10. Right half of the top and bottom rows on both sides\n    11. Left half of non-home rows on the left and right half of the same rows on the right\n    12. Right half of non-home rows on the left and left half of the same rows on the right\n    13. Top center and lower sides\n    14. Top sides and lower center\n    15. Repeat 1-14\n\n\n```python\n\"\"\"\nNOTE: This procedure takes hours to run.\n\n    Pattern 1:\n    \n    --O- -IEA ----    ---- LSNR ----\n    --O- -IEA ----    ---- DSNR ----\n    --O- -IEA ----    ---- CSNR ----\n    --O- -IEA ----    ---- TSNR ----\n\n    Pattern 2:\n    \n    --O- I-EA ----    ---- LSNR ----\n    --O- I-EA ----    ---- DSNR ----\n    --O- I-EA ----    ---- CSNR ----\n    --O- I-EA ----    ---- TSNR ----\n\n    Pattern 3:\n    \n    -O-- I-EA ----    ---- LSNR ----\n    -O-- I-EA ----    ---- DSNR ----\n    -O-- I-EA ----    ---- CSNR ----\n    -O-- I-EA ----    ---- TSNR ----\n\n    Pattern 4:\n    \n    ---- IOEA ----    ---- LSNR ----\n    ---- IOEA ----    ---- DSNR ----\n    ---- IOEA ----    ---- CSNR ----\n    ---- IOEA ----    ---- TSNR ----    \n    \n\"\"\"\nfixed_letter_lists1 = [\n    ['O','I','E','A','L','S','N','R'],\n    ['O','I','E','A','D','S','N','R'],\n    ['O','I','E','A','C','S','N','R'],\n    ['O','I','E','A','T','S','N','R'],\n    ['O','I','E','A','L','S','N','R'],\n    ['O','I','E','A','D','S','N','R'],\n    ['O','I','E','A','C','S','N','R'],\n    ['O','I','E','A','T','S','N','R'],\n    ['O','I','E','A','L','S','N','R'],\n    ['O','I','E','A','D','S','N','R'],\n    ['O','I','E','A','C','S','N','R'],\n    ['O','I','E','A','T','S','N','R'],\n    ['I','O','E','A','L','S','N','R'],\n    ['I','O','E','A','D','S','N','R'],\n    ['I','O','E','A','C','S','N','R'],\n    ['I','O','E','A','T','S','N','R']]\n\n# Keys for step 1:\n#     -  2  3  -        - 14 15  -\n#     5  6  7  8       17 18 19 20\n#     9  -  - 12       21  -  - 24\nkeys1  = [2,3,   5,6,7,8, 9,12,  14,15, 17,18,19,20, 21,24]\n\n# Indices for step 1:\n#     -  0  1  -        -  8  9  -\n#     2  3  4  5       10 11 12 13\n#     6  -  -  7       14  -  - 15\nfixed_letter_index_lists1 = [[1,   3,4,5, 10,11,12,13],\n                             [1,   3,4,5, 10,11,12,13],\n                             [1,   3,4,5, 10,11,12,13],\n                             [1,   3,4,5, 10,11,12,13],\n                             [1, 2,  4,5, 10,11,12,13],\n                             [1, 2,  4,5, 10,11,12,13],\n                             [1, 2,  4,5, 10,11,12,13],\n                             [1, 2,  4,5, 10,11,12,13],\n                             [0, 2,  4,5, 10,11,12,13],\n                             [0, 2,  4,5, 10,11,12,13],\n                             [0, 2,  4,5, 10,11,12,13],\n                             [0, 2,  4,5, 10,11,12,13],\n                             [   2,3,4,5, 10,11,12,13],\n                             [   2,3,4,5, 10,11,12,13],\n                             [   2,3,4,5, 10,11,12,13],\n                             [   2,3,4,5, 10,11,12,13]]\nopen_letter_index_lists1  = [[0, 2,   6,7, 8,9, 14,15],\n                             [0, 2,   6,7, 8,9, 14,15],\n                             [0, 2,   6,7, 8,9, 14,15],\n                             [0, 2,   6,7, 8,9, 14,15],\n                             [0,   3, 6,7, 8,9, 14,15],\n                             [0,   3, 6,7, 8,9, 14,15],\n                             [0,   3, 6,7, 8,9, 14,15],\n                             [0,   3, 6,7, 8,9, 14,15],\n                             [1,   3, 6,7, 8,9, 14,15],\n                             [1,   3, 6,7, 8,9, 14,15],\n                             [1,   3, 6,7, 8,9, 14,15],\n                             [1,   3, 6,7, 8,9, 14,15],\n                             [0,1,    6,7, 8,9, 14,15],\n                             [0,1,    6,7, 8,9, 14,15],\n                             [0,1,    6,7, 8,9, 14,15],\n                             [0,1,    6,7, 8,9, 14,15]]\n\n# All 24 key indices:\n#     0  1  2  3       12 13 14 15\n#     4  5  6  7       16 17 18 19\n#     8  9 10 11       20 21 22 23\n# Open indices:\n#     0  -  -  3       12  -  - 15\n#     -  -  -  -        -  -  -  -\n#     -  9 10  -        - 21 22  -\nfixed_letter_indices2 = [1,2, 4,5,6,7, 8,11, 13,14, 16,17,18,19, 20,23]\nopen_letter_indices2  = [0,3, 9,10, 12,15, 21,22]\nfixed_letter_index_lists3 = [[2,   5,6,7, 16,17,18,19],\n                             [2,   5,6,7, 16,17,18,19],\n                             [2,   5,6,7, 16,17,18,19],\n                             [2,   5,6,7, 16,17,18,19],\n                             [2, 4,  6,7, 16,17,18,19],\n                             [2, 4,  6,7, 16,17,18,19],\n                             [2, 4,  6,7, 16,17,18,19],\n                             [2, 4,  6,7, 16,17,18,19],\n                             [1, 4,  6,7, 16,17,18,19],\n                             [1, 4,  6,7, 16,17,18,19],\n                             [1, 4,  6,7, 16,17,18,19],\n                             [1, 4,  6,7, 16,17,18,19],\n                             [   4,5,6,7, 16,17,18,19],\n                             [   4,5,6,7, 16,17,18,19],\n                             [   4,5,6,7, 16,17,18,19],\n                             [   4,5,6,7, 16,17,18,19]]\n\n# Loop through initialized layouts with assigned vowels and consonants \ntop_layouts = []\nnlists = len(fixed_letter_lists1)\nfor ilist, fixed_letters1 in enumerate(fixed_letter_lists1):\n  if ilist > 10:\n    fixed_letter_indices1 = fixed_letter_index_lists1[ilist]\n    fixed_letter_indices3 = fixed_letter_index_lists3[ilist]\n    open_letter_indices1 = open_letter_index_lists1[ilist]\n\n    print('Layout {0}'.format(ilist+1))\n    print(*fixed_letters1)\n\n    print(\"Most frequent letters\")\n    top_permutation1, top_score1, letter_permutations1 = permute_optimize_keys(fixed_letters1, fixed_letter_indices1, \n                                                         open_letter_indices1, letters24, keys1, Factors24x24, \n                                                         bigrams, bigram_frequencies, min_score=0, verbose=False)\n    fixed_letters2 = top_permutation1\n    \n    print(\"Least frequent remaining letters\")\n    top_permutation2, top_score2, letter_permutations2 = permute_optimize_keys(fixed_letters2, fixed_letter_indices2, \n                                                         open_letter_indices2, letters24, keys24, Factors24x24, \n                                                         bigrams, bigram_frequencies, min_score=0, verbose=False)\n    fixed_letters3 = top_permutation2\n\n    print(\"Further optimize layouts by exchanging sets of letters\")\n    top_permutation3, top_score3 = exchange_letters(fixed_letters3, fixed_letter_indices3, letters24, keys24, \n                                                    Factors24x24, bigrams, bigram_frequencies, verbose=True)\n\n    top_layouts.append(top_permutation3)\n\n```\n\n#### Optimized layouts (outcome of above)\n\n\n```python\nload_top_layouts = True\nprint_layouts = False\nif load_top_layouts:\n    top_layouts = [\n    ['Z','H','O','X','P','I','E','A','F','Y','Q','U','M','D','B','J','L','S','N','R','T','C','V','G'],\n    ['Z','H','O','X','P','I','E','A','F','Y','Q','U','M','L','B','J','D','S','N','R','T','C','V','G'],\n    ['Z','H','O','X','T','I','E','A','F','Y','Q','U','M','L','P','B','C','S','N','R','D','G','J','V'],\n    ['Z','H','O','X','P','I','E','A','F','Y','Q','U','M','D','B','J','T','S','N','R','C','L','V','G'],\n    ['Y','H','O','X','I','P','E','A','Z','F','Q','U','M','D','B','J','L','S','N','R','T','C','V','G'],\n    ['Y','H','O','X','I','P','E','A','Z','F','Q','U','M','L','B','J','D','S','N','R','T','C','V','G'],\n    ['Y','H','O','X','I','T','E','A','Z','F','Q','U','M','L','P','B','C','S','N','R','D','G','J','V'],\n    ['Y','H','O','X','I','P','E','A','Z','F','Q','U','M','D','B','J','T','S','N','R','C','L','V','G'],\n    ['Y','O','B','F','I','U','E','A','Q','Z','X','G','M','D','P','J','L','S','N','R','T','C','H','V'],\n    ['Y','O','B','F','I','U','E','A','Q','Z','X','G','M','L','P','J','D','S','N','R','T','C','H','V'],\n    ['H','O','B','Y','I','U','E','A','Q','Z','X','F','M','D','P','J','C','S','N','R','T','L','V','G'],\n    ['H','O','B','Y','I','U','E','A','Q','Z','X','F','M','D','P','J','T','S','N','R','C','L','V','G'],\n    ['Y','Z','H','X','I','O','E','A','P','F','Q','U','M','D','B','J','L','S','N','R','T','C','V','G'],\n    ['Y','Z','B','X','I','O','E','A','P','F','Q','U','M','L','G','J','D','S','N','R','T','C','H','V'],\n    ['Y','Z','B','X','I','O','E','A','P','F','Q','U','M','D','H','J','C','S','N','R','T','L','V','G'],\n    ['Y','Z','B','X','I','O','E','A','P','F','Q','U','M','D','G','J','T','S','N','R','C','L','V','H']]\nif print_layouts:\n    print('Layouts:\\n')\n    for layout in top_layouts:\n        print(layout)\n```\n\n### Rank optimized layouts\n\n\n```python\n# %load code/rank_layouts.py\nlayout_strings = []\nscores = []\nfor layout in top_layouts:\n    layout_string = ' '.join(layout)\n    score = score_layout(Factors24x24, layout, bigrams, bigram_frequencies, verbose=False)\n    #print('    {0}    {1}'.format(layout_string, score))\n    layout_strings.append(layout_string)\n    scores.append(score)\n\n# Establish which layouts are within a small difference of the top-scoring layout \nscores_sorted, ranks_sorted, Isort = rank_within_epsilon(scores, factor24, factor=True, verbose=False)\nlayouts_sorted = []\nlayout_strings_sorted = []\nfor i in Isort:\n    layouts_sorted.append(top_layouts[i])\n    layout_strings_sorted.append(layout_strings[i])\nprint('\\n    Rank                                                   Score')\nfor i, rank in enumerate(ranks_sorted):\n    print('    {0}:  {1}    {2}'.format(rank, layout_strings_sorted[i], scores_sorted[i]))\n\nprint('\\nLayouts tied for first place, with relative letter frequencies:\\n')\n#print('    Rank                                                   Score')\nfirst_ranks = []\nfirst_layouts = []\nfirst_layout_strings = []\nfirst_scores = []\nfor i, rank in enumerate(ranks_sorted):\n    if rank == 1:\n        first_ranks.append(rank)\n        first_layouts.append(layout_strings_sorted[i])\n        first_layout_strings.append(layouts_sorted[i])\n        first_scores.append(scores_sorted[i])    \nIsort2 = np.argsort([-x for x in first_scores])\nfirst_ranks_sorted = []\nfirst_layouts_sorted = []\nfirst_layout_strings_sorted = []\nfirst_scores_sorted = []\nfor i in Isort2:\n    first_ranks_sorted.append(first_ranks[i])\n    first_layouts_sorted.append(first_layouts[i])\n    first_layout_strings_sorted.append(first_layout_strings[i])\n    first_scores_sorted.append(first_scores[i])\n\n# Print layouts:\nfor i, layout_string in enumerate(first_layout_strings_sorted):\n    layout = first_layouts_sorted[i]\n    print('    Layout {0}:\\n'.format(Isort2[i] + 1))\n    print_layout24(layout_string)\n    print('')\n    print_layout24_instances(layout_string, letters24, instances24, bigrams, bigram_frequencies)\n    print('')\n```\n\n#### Ranked, optimized layouts\n\n    Rank                                                   Score\n    1:  Z H O X P I E A F Y Q U M D B J T S N R C L V G    0.718175779085395\n    2:  Z H O X P I E A F Y Q U M L B J D S N R T C V G    0.7181082154436876\n    2:  Z H O X P I E A F Y Q U M D B J L S N R T C V G    0.7180926323971318\n    3:  Y H O X I P E A Z F Q U M D B J T S N R C L V G    0.7180491746992222\n    4:  Z H O X T I E A F Y Q U M L P B C S N R D G J V    0.7179953118351015\n    4:  Y H O X I P E A Z F Q U M L B J D S N R T C V G    0.7179816110575149\n    4:  Y H O X I P E A Z F Q U M D B J L S N R T C V G    0.717966028010959\n    5:  Y H O X I T E A Z F Q U M L P B C S N R D G J V    0.7178848621521811\n    6:  Y Z B X I O E A P F Q U M D G J T S N R C L V H    0.7176201586204008\n    6:  H O B Y I U E A Q Z X F M D P J T S N R C L V G    0.7176038179852999\n    6:  Y Z B X I O E A P F Q U M D H J C S N R T L V G    0.7175719371257249\n    7:  H O B Y I U E A Q Z X F M D P J C S N R T L V G    0.7175637424926007\n    7:  Y Z B X I O E A P F Q U M L G J D S N R T C H V    0.717538426789943\n    7:  Y Z H X I O E A P F Q U M D B J L S N R T C V G    0.7175223166015284\n    7:  Y O B F I U E A Q Z X G M L P J D S N R T C H V    0.7175175913298815\n    8:  Y O B F I U E A Q Z X G M D P J L S N R T C H V    0.7174898077178882\n\nUnique letters per column:\n\n        Z H O X P I E A F Y Q U M D B J T S N R C L V G\n        Y Z B Y I P     Z F X F   L P B D       T C J V\n        H O   F T T     P Z   G     G   L       D G H H\n                  O     Q           P   C\n                  U                 H\n\n        - - - - - - E A - - - - M - - - - S N R - - - -    >1 letter per column\n\nUnique letters per column for the top 8 rows (5 places):\n\n        Z H O X P I E A F Y Q U M D B J T S N R C L V G\n        Y       I P     Z F       L P B D       T C J V\n                T T                     L       D G    \n                                        C\n                                     \nUnique letters per column for the top 4 rows (3 places):\n\n        Z H O X P I E A F Y Q U M D B J T S N R C L V G\n        Y       I P     Z F       L     D       T C  \n                                        L              \n                                         \n        - H O X - - E A - - Q U M - B J - S N R - - V G    >1 letter per column in top 4 rows\n          \n\nLayouts tied for first place, with relative letter frequencies:\n\n    Layout 1:\n\n    Z H O X  M D B J\n    P I E A  T S N R\n    F Y Q U  C L V G\n\n     49 101 1142  22  350 638 160  59\n    344 837 1695 1553  565 854 918 859\n    103 104 112 525  559 714 126 150\n\n    left: 658688805 (10.67%)  right: 595172561\n    Total same-finger bigram frequencies:     48977687406\n    Total bigram inward roll frequencies:   5838991231649\n    \n\n### Create variants of top-scoring layouts\n\nAs an alternative to simply choosing the first-place layout, we can generate variations of this layout and find those variants within a small difference of one another and select from among these variants. For this, we select keys to vary, compute scores for every combination of the letters assigned to these keys, and select among those that are tied for first place. Since no other layout is tied for first place, we will vary those keys with different letters in the top four layouts (in first, second, and third place):\n\n        - H O X  M - B J\n        - - E A  - S N R \n        - - Q U  - - V G\n\n\n\n```python\n#   - H O X  M - B J\n#   - - E A  - S N R \n#   - - Q U  - - V G\n\nfixed_letters = ['H','O','X', 'E','A', 'Q','U', 'M','B','J', 'S','N','R', 'V','G']\nfixed_letter_indices = [1,2,3, 6,7, 10,11, 12,14,15, 17,18,19, 22,23]\nopen_letter_indices  = [0, 4,5, 8,9, 13, 16, 20,21]\n\ntop_variant_permutation, top_variant_score, variant_letter_permutations = permute_optimize_keys(fixed_letters, \n    fixed_letter_indices, open_letter_indices, letters24, keys24, Factors24x24, \n    bigrams, bigram_frequencies, min_score=0, verbose=False)\n\nvariant_scores = []\nnletters = len(fixed_letter_indices) + len(open_letter_indices)\nlayout_variant_strings = []\nfor ipermutation, letter_permutation in enumerate(variant_letter_permutations):\n    variant_letters = np.array(['W' for x in range(nletters)])  # KEEP to initialize!\n    for imove, open_letter_index in enumerate(open_letter_indices):\n        variant_letters[open_letter_index] = letter_permutation[imove]\n    for ifixed, fixed_letter_index in enumerate(fixed_letter_indices):\n        variant_letters[fixed_letter_index] = fixed_letters[ifixed]\n    layout_variant_strings.append(variant_letters)\n    # Compute the score for this permutation:\n    variant_score = score_layout(Factors24x24, variant_letters, \n                                 bigrams, bigram_frequencies, verbose=False)\n    variant_scores.append(variant_score)\n\nlayout_variants = []\nfor layout_string in layout_variant_strings:\n    layout = ' '.join(layout_string)\n    layout_variants.append(layout)\n\nvariant_scores_sorted, variant_ranks_sorted, Isort_variants = rank_within_epsilon(variant_scores, \n        factor24, factor=True, verbose=False)\nlayout_variants_sorted = []\nlayout_variant_strings_sorted = []\nfor i in Isort_variants:\n    layout_variants_sorted.append(layout_variants[i])\n    layout_variant_strings_sorted.append(layout_variant_strings[i])\n\nprint('    Rank                                                   Score')\nfor i, rank in enumerate(variant_ranks_sorted):\n    if rank == 1:\n        print('    {0}:  {1}    {2}'.format(rank, layout_variants_sorted[i], variant_scores_sorted[i]))\n\n# Print layouts:\nIfirst_place = []\nlayout_variants_first_place = []\nlayout_variant_strings_first_place = []\nfor i, rank in enumerate(variant_ranks_sorted):\n    if rank == 1:\n        layout_string = layout_variant_strings_sorted[i]\n        layout = layout_variants_sorted[i]\n        print('\\n    Layout {0}:\\n'.format(i + 1))\n        print_layout24(layout_string)\n        print('')\n        print_layout24_instances(layout_string, letters24, instances24, \n                                 bigrams, bigram_frequencies)\n\n        Ifirst_place.append(i)\n        layout_variants_first_place.append(layout)\n        layout_variant_strings_first_place.append(layout_string)\n```\n\n####   Variants of top-scoring layouts tied for first place\n\n    Rank                                                   Score\n    1:  Z H O X P I E A F Y Q U M D B J T S N R C L V G    0.718175779085395\n    1:  Y H O X P I E A F Z Q U M D B J T S N R C L V G    0.7181740824015593\n    1:  Z H O X P I E A F Y Q U M C B J T S N R D L V G    0.7181662126172352\n    1:  Y H O X P I E A F Z Q U M C B J T S N R D L V G    0.7181645159333996\n    1:  Z H O X P I E A F Y Q U M L B J T S N R C D V G    0.7181440154199303\n    1:  Y H O X P I E A F Z Q U M L B J T S N R C D V G    0.7181423187360948\n    1:  Z H O X P I E A F Y Q U M L B J T S N R D C V G    0.7181399906496914\n    1:  Y H O X P I E A F Z Q U M L B J T S N R D C V G    0.7181382939658557\n    1:  Z H O X P I E A F Y Q U M D B J C S N R T L V G    0.7181368885518766\n    1:  Y H O X P I E A F Z Q U M D B J C S N R T L V G    0.7181351918680411\n    1:  Y H O X P I E A Z F Q U M D B J T S N R C L V G    0.7181315366108767\n    1:  F H O X P I E A Z Y Q U M D B J T S N R C L V G    0.7181279794445848\n\n    Layout 1:\n\n    Z H O X  M D B J\n    P I E A  T S N R\n    F Y Q U  C L V G\n\n     49 101 1142  22  350 638 160  59\n    344 837 1695 1553  565 854 918 859\n    103 104 112 525  559 714 126 150\n\n    left: 658688805 (10.67%)  right: 595172561\n    Total same-finger bigram frequencies:     48977687406\n    Total bigram inward roll frequencies:   5838991231649\n\n    Layout 2:\n\n    Y H O X  M D B J\n    P I E A  T S N R\n    F Z Q U  C L V G\n\n    104 101 1142  22  350 638 160  59\n    344 837 1695 1553  565 854 918 859\n    103  49 112 525  559 714 126 150\n\n    left: 658688805 (10.67%)  right: 595172561\n    Total same-finger bigram frequencies:     52923154294\n    Total bigram inward roll frequencies:   5835045764762\n\n    Layout 3:\n\n    Z H O X  M C B J\n    P I E A  T S N R\n    F Y Q U  D L V G\n\n     49 101 1142  22  350 559 160  59\n    344 837 1695 1553  565 854 918 859\n    103 104 112 525  638 714 126 150\n\n    left: 658688805 (10.67%)  right: 595172561\n    Total same-finger bigram frequencies:     50643072440\n    Total bigram inward roll frequencies:   5837325846616\n\n    Layout 4:\n\n    Y H O X  M C B J\n    P I E A  T S N R\n    F Z Q U  D L V G\n\n    104 101 1142  22  350 559 160  59\n    344 837 1695 1553  565 854 918 859\n    103  49 112 525  638 714 126 150\n\n    left: 658688805 (10.67%)  right: 595172561\n    Total same-finger bigram frequencies:     54588539327\n    Total bigram inward roll frequencies:   5833380379728\n\n    Layout 5:\n\n    Z H O X  M L B J\n    P I E A  T S N R\n    F Y Q U  C D V G\n\n     49 101 1142  22  350 714 160  59\n    344 837 1695 1553  565 854 918 859\n    103 104 112 525  559 638 126 150\n\n    left: 658688805 (10.67%)  right: 595172561\n    Total same-finger bigram frequencies:     48977687406\n    Total bigram inward roll frequencies:   5838991231649\n\n    Layout 6:\n\n    Y H O X  M L B J\n    P I E A  T S N R\n    F Z Q U  C D V G\n\n    104 101 1142  22  350 714 160  59\n    344 837 1695 1553  565 854 918 859\n    103  49 112 525  559 638 126 150\n\n    left: 658688805 (10.67%)  right: 595172561\n    Total same-finger bigram frequencies:     52923154294\n    Total bigram inward roll frequencies:   5835045764762\n\n    Layout 7:\n\n    Z H O X  M L B J\n    P I E A  T S N R\n    F Y Q U  D C V G\n\n     49 101 1142  22  350 714 160  59\n    344 837 1695 1553  565 854 918 859\n    103 104 112 525  638 559 126 150\n\n    left: 658688805 (10.67%)  right: 595172561\n    Total same-finger bigram frequencies:     50643072440\n    Total bigram inward roll frequencies:   5837325846616\n\n    Layout 8:\n\n    Y H O X  M L B J\n    P I E A  T S N R\n    F Z Q U  D C V G\n\n    104 101 1142  22  350 714 160  59\n    344 837 1695 1553  565 854 918 859\n    103  49 112 525  638 559 126 150\n\n    left: 658688805 (10.67%)  right: 595172561\n    Total same-finger bigram frequencies:     54588539327\n    Total bigram inward roll frequencies:   5833380379728\n\n    Layout 9:\n\n    Z H O X  M D B J\n    P I E A  C S N R\n    F Y Q U  T L V G\n\n     49 101 1142  22  350 638 160  59\n    344 837 1695 1553  559 854 918 859\n    103 104 112 525  565 714 126 150\n\n    left: 658688805 (10.67%)  right: 595172561\n    Total same-finger bigram frequencies:     48977687406\n    Total bigram inward roll frequencies:   5838991231649\n\n    Layout 10:\n\n    Y H O X  M D B J\n    P I E A  C S N R\n    F Z Q U  T L V G\n\n    104 101 1142  22  350 638 160  59\n    344 837 1695 1553  559 854 918 859\n    103  49 112 525  565 714 126 150\n\n    left: 658688805 (10.67%)  right: 595172561\n    Total same-finger bigram frequencies:     52923154294\n    Total bigram inward roll frequencies:   5835045764762\n\n    Layout 11:\n\n    Y H O X  M D B J\n    P I E A  T S N R\n    Z F Q U  C L V G\n\n    104 101 1142  22  350 638 160  59\n    344 837 1695 1553  565 854 918 859\n     49 103 112 525  559 714 126 150\n\n    left: 658688805 (10.67%)  right: 595172561\n    Total same-finger bigram frequencies:     59523779284\n    Total bigram inward roll frequencies:   5828445139772\n\n    Layout 12:\n\n    F H O X  M D B J\n    P I E A  T S N R\n    Z Y Q U  C L V G\n\n    103 101 1142  22  350 638 160  59\n    344 837 1695 1553  565 854 918 859\n     49 104 112 525  559 714 126 150\n\n    left: 658688805 (10.67%)  right: 595172561\n    Total same-finger bigram frequencies:     48977687406\n    Total bigram inward roll frequencies:   5838991231649\n\n\n```python\nlayout_variant_strings_first_place = [\n    ['Z','H','O','X','P','I','E','A','F','Y','Q','U','M','D','B','J','T','S','N','R','C','L','V','G'],\n    ['Y','H','O','X','P','I','E','A','F','Z','Q','U','M','D','B','J','T','S','N','R','C','L','V','G'],\n    ['Z','H','O','X','P','I','E','A','F','Y','Q','U','M','C','B','J','T','S','N','R','D','L','V','G'],\n    ['Y','H','O','X','P','I','E','A','F','Z','Q','U','M','C','B','J','T','S','N','R','D','L','V','G'],\n    ['Z','H','O','X','P','I','E','A','F','Y','Q','U','M','L','B','J','T','S','N','R','C','D','V','G'],\n    ['Y','H','O','X','P','I','E','A','F','Z','Q','U','M','L','B','J','T','S','N','R','C','D','V','G'],\n    ['Z','H','O','X','P','I','E','A','F','Y','Q','U','M','L','B','J','T','S','N','R','D','C','V','G'],\n    ['Y','H','O','X','P','I','E','A','F','Z','Q','U','M','L','B','J','T','S','N','R','D','C','V','G'],\n    ['Z','H','O','X','P','I','E','A','F','Y','Q','U','M','D','B','J','C','S','N','R','T','L','V','G'],\n    ['Y','H','O','X','P','I','E','A','F','Z','Q','U','M','D','B','J','C','S','N','R','T','L','V','G'],\n    ['Y','H','O','X','P','I','E','A','Z','F','Q','U','M','D','B','J','T','S','N','R','C','L','V','G'],\n    ['F','H','O','X','P','I','E','A','Z','Y','Q','U','M','D','B','J','T','S','N','R','C','L','V','G']]\n```\n\n## Step 4: Evaluate winning layout <a name=\"step4\">\n    \nWe evaluate the candidate winner with tests:\n    \n    1. Evaluate variants of the candidate winner using interkey speed estimates\n    2. Evaluate sensitivity of the variants to the scoring parameters\n    3. Search for higher-scoring layouts by rearranging letters\n\n### Test 1. Evaluate variants of the candidate winner using interkey speed estimates  \nBelow we rescore the four winning variants that are tied for first place, replacing the factor matrix with the inter-key speed matrix.\n\n*Note:*\n    \nThe speed matrix contains normalized interkey stroke times derived from a published study (\"Estimation of digraph costs for keyboard layout optimization\", A Iseri, Ma Eksioglu, International Journal of Industrial Ergonomics, 48, 127-138, 2015). To establish which layouts are within a small difference of each other when using the speed matrix, we define an epsilon equal to 131.58 ms for a single bigram (of the 32^2 possible bigrams), where 131.58 ms is the fastest measured digraph tapping speed (30,000/228 = 131.58 ms) recorded in the above study.\n    \n\"Digraph-tapping rate changes dramatically across the digraph types. The range is between 82 and 228 taps per 30 s. The difference is nearly three times between the slowest and the fastest digraphs. From this result it can be concluded that the assignment of letter pairs on the correct digraph keys on the keyboard can have a high impact on the typing speed.\"\n\n\n```python\ntest_layout_strings = layout_variant_strings_first_place\n```\n\n\n```python\n# %load code/test/score_speed_of_layouts.py\ndata_matrix_speed = Speed24x24  # SpeedSymmetric24x24\nspeed_scores = []\nfor letters in test_layout_strings:\n    score = score_layout(data_matrix_speed, letters,  bigrams, bigram_frequencies, verbose = False) \n    speed_scores.append(score)\n\nspeed_scores_sorted, speed_ranks_sorted, Isort_speed = rank_within_epsilon(speed_scores, \n                                                                    epsilon, factor=False, verbose=False)\nspeed_layouts_sorted = []\nspeed_layout_strings_sorted = []\nfor i in Isort_speed:\n    speed_layouts_sorted.append(' '.join(test_layout_strings[i]))\n    speed_layout_strings_sorted.append(test_layout_strings[i])\n\ncount = 0\nprint('    Layout                                                  Speed score')\nfor i, isort_speed in enumerate(Isort_speed):\n    if speed_ranks_sorted[isort_speed] == 1:\n        count += 1\n        if isort_speed < 9:\n            s = '  '\n        else:\n            s = ' '\n        print('    ({0}){1}{2}    {3}'.format(isort_speed+1, s, \n                                              speed_layouts_sorted[i], \n                                              speed_scores_sorted[i]))\nprint('    {0} of {1} layouts tied for first place'.format(count, len(test_layout_strings)))\n```\n\nVariants 1-10 tie for top score:\n\n    Layout                                                  Speed score\n    (8)  Y H O X P I E A F Z Q U M L B J T S N R D C V G    0.7126582048217771\n    (7)  Z H O X P I E A F Y Q U M L B J T S N R D C V G    0.7126537342949005\n    (6)  Y H O X P I E A F Z Q U M L B J T S N R C D V G    0.7126482055890047\n    (4)  Y H O X P I E A F Z Q U M C B J T S N R D L V G    0.7126473432931382\n    (5)  Z H O X P I E A F Y Q U M L B J T S N R C D V G    0.7126437138130693\n    (3)  Z H O X P I E A F Y Q U M C B J T S N R D L V G    0.7126428727662616\n    (2)  Y H O X P I E A F Z Q U M D B J T S N R C L V G    0.7126324844095655\n    (1)  Z H O X P I E A F Y Q U M D B J T S N R C L V G    0.7126279926336301\n    (10) Y H O X P I E A F Z Q U M D B J C S N R T L V G    0.7126258758990177\n    (9)  Z H O X P I E A F Y Q U M D B J C S N R T L V G    0.7126213841230822\n    10 of 12 layouts tied for first place\n\n### Test 2. Evaluate sensitivity of the candidate winner to the scoring parameters\n\nWe run a test below on the variants to see how robust they are to removal of scoring parameters. We removed each of the 11 scoring parameters one by one and ranked the new scores for the variants above. \n\n\n```python\n# %load code/test/remove_parameters_rescore.py\nparams0 = [side_above_3away, side_above_2away, side_above_1away, middle_above_ring, ring_above_middle, \n           outward, skip_row_3away, skip_row_2away, skip_row_1away, skip_row_0away, same_finger]\nparam_names = ['side_above_3away', 'side_above_2away', 'side_above_1away', \n               'middle_above_ring', 'ring_above_middle', 'outward', 'skip_row_3away', \n               'skip_row_2away', 'skip_row_1away', 'skip_row_0away', 'same_finger']\nparams_lists = []\nfor i in range(len(params0)):\n    params_list = params0.copy()\n    params_list[i] = 1.0\n    params_lists.append(params_list)\n\nfor iparam, P in enumerate(params_lists):\n\n    print('    Remove parameter {0}:'.format(param_names[iparam]))\n\n    data_matrix_param = create_24x24_flow_matrix(not_home_row, side_top,\n                                                 P[0],P[1],P[2],P[3],P[4],P[5],P[6],P[7],P[8],P[9],P[10],\n                                                 1,1,1,1,1,1)\n    if apply_strength:\n        data_matrix_param = Strength24x24 * data_matrix_param\n\n    param_scores = []\n    for letters in test_layout_strings:\n        score = score_layout(data_matrix_param, letters, bigrams, bigram_frequencies, verbose=False);\n        param_scores.append(score)\n            \n    param_scores_sorted, param_ranks_sorted, Isort_param = rank_within_epsilon(param_scores, factor24, factor=True, verbose=False)\n    param_layouts_sorted = []\n    param_layout_strings_sorted = []\n    for i in Isort_param:\n        param_layouts_sorted.append(' '.join(test_layout_strings[i]))\n        param_layout_strings_sorted.append(test_layout_strings[i])\n\n    print('    Variant                                                 Score')\n    count = 0\n    for i, isort_param in enumerate(Isort_param):\n        count += 1\n        if param_ranks_sorted[isort_param] == 1:\n            if isort_param < 9:\n                s = '  '\n            else:\n                s = ' '\n            print('    ({0}){1}{2}    {3}'.format(isort_param+1, s, \n                                                  param_layouts_sorted[i], \n                                                  param_scores_sorted[i]))\n    print('    {0} of {1} layouts tied for first place'.format(count, len(test_layout_strings)))\n```\nVariant 1 scores higher than any other most often, demonstrating that this layout is among the least sensitive to individual parameters.\n\n    Remove parameter side_above_3away:\n    Variant                                                 Score\n    (9)  Z H O X P I E A F Y Q U M D B J C S N R T L V G    0.7210583773221152\n    (1)  Z H O X P I E A F Y Q U M D B J T S N R C L V G    0.721056939210811\n    (10) Y H O X P I E A F Z Q U M D B J C S N R T L V G    0.7210527642648356\n    (2)  Y H O X P I E A F Z Q U M D B J T S N R C L V G    0.7210513261535314\n    (3)  Z H O X P I E A F Y Q U M C B J T S N R D L V G    0.7210467994285263\n    (4)  Y H O X P I E A F Z Q U M C B J T S N R D L V G    0.7210411863712467\n    (5)  Z H O X P I E A F Y Q U M L B J T S N R C D V G    0.7210251755453465\n    (7)  Z H O X P I E A F Y Q U M L B J T S N R D C V G    0.7210205774609825\n    (6)  Y H O X P I E A F Z Q U M L B J T S N R C D V G    0.7210195624880669\n    (11) Y H O X P I E A Z F Q U M D B J T S N R C L V G    0.7210172538163603\n    (12) F H O X P I E A Z Y Q U M D B J T S N R C L V G    0.721016520203857\n    (8)  Y H O X P I E A F Z Q U M L B J T S N R D C V G    0.7210149644037028\n    12 of 12 layouts tied for first place\n    Remove parameter side_above_2away:\n    Variant                                                 Score\n    (2)  Y H O X P I E A F Z Q U M D B J T S N R C L V G    0.7233214925197848\n    (1)  Z H O X P I E A F Y Q U M D B J T S N R C L V G    0.7233163652876\n    (4)  Y H O X P I E A F Z Q U M C B J T S N R D L V G    0.7233119260516252\n    (6)  Y H O X P I E A F Z Q U M L B J T S N R C D V G    0.7233094386419149\n    (3)  Z H O X P I E A F Y Q U M C B J T S N R D L V G    0.7233067988194403\n    (8)  Y H O X P I E A F Z Q U M L B J T S N R D C V G    0.7233065402026811\n    (5)  Z H O X P I E A F Y Q U M L B J T S N R C D V G    0.7233043114097301\n    (7)  Z H O X P I E A F Y Q U M L B J T S N R D C V G    0.7233014129704961\n    (10) Y H O X P I E A F Z Q U M D B J C S N R T L V G    0.7232825203140769\n    (9)  Z H O X P I E A F Y Q U M D B J C S N R T L V G    0.7232773930818921\n    (11) Y H O X P I E A Z F Q U M D B J T S N R C L V G    0.7232625473933775\n    12 of 12 layouts tied for first place\n    Remove parameter side_above_1away:\n    Variant                                                 Score\n    (1)  Z H O X P I E A F Y Q U M D B J T S N R C L V G    0.7251645905252198\n    (3)  Z H O X P I E A F Y Q U M C B J T S N R D L V G    0.72515502405706\n    (2)  Y H O X P I E A F Z Q U M D B J T S N R C L V G    0.7251475103014832\n    (4)  Y H O X P I E A F Z Q U M C B J T S N R D L V G    0.7251379438333233\n    (7)  Z H O X P I E A F Y Q U M L B J T S N R D C V G    0.7251345319311451\n    (8)  Y H O X P I E A F Z Q U M L B J T S N R D C V G    0.7251174517074084\n    (5)  Z H O X P I E A F Y Q U M L B J T S N R C D V G    0.7251078181722477\n    (6)  Y H O X P I E A F Z Q U M L B J T S N R C D V G    0.7250907379485111\n    12 of 12 layouts tied for first place\n    Remove parameter middle_above_ring:\n    Variant                                                 Score\n    (2)  Y H O X P I E A F Z Q U M D B J T S N R C L V G    0.719576614490204\n    (1)  Z H O X P I E A F Y Q U M D B J T S N R C L V G    0.7195765506408036\n    (4)  Y H O X P I E A F Z Q U M C B J T S N R D L V G    0.7195556622780318\n    (3)  Z H O X P I E A F Y Q U M C B J T S N R D L V G    0.7195555984286314\n    (6)  Y H O X P I E A F Z Q U M L B J T S N R C D V G    0.7195084229854201\n    (5)  Z H O X P I E A F Y Q U M L B J T S N R C D V G    0.7195083591360196\n    (8)  Y H O X P I E A F Z Q U M L B J T S N R D C V G    0.719504398215181\n    (7)  Z H O X P I E A F Y Q U M L B J T S N R D C V G    0.7195043343657805\n    12 of 12 layouts tied for first place\n    Remove parameter ring_above_middle:\n    Variant                                                 Score\n    (5)  Z H O X P I E A F Y Q U M L B J T S N R C D V G    0.7217739948393724\n    (6)  Y H O X P I E A F Z Q U M L B J T S N R C D V G    0.7217722981555368\n    (1)  Z H O X P I E A F Y Q U M D B J T S N R C L V G    0.7217234092956235\n    (2)  Y H O X P I E A F Z Q U M D B J T S N R C L V G    0.721721712611788\n    (3)  Z H O X P I E A F Y Q U M C B J T S N R D L V G    0.7217138428274638\n    (4)  Y H O X P I E A F Z Q U M C B J T S N R D L V G    0.7217121461436282\n    12 of 12 layouts tied for first place\n    Remove parameter outward:\n    Variant                                                 Score\n    (1)  Z H O X P I E A F Y Q U M D B J T S N R C L V G    0.7304521334502336\n    (2)  Y H O X P I E A F Z Q U M D B J T S N R C L V G    0.7304470031869887\n    (3)  Z H O X P I E A F Y Q U M C B J T S N R D L V G    0.7304377416670281\n    (4)  Y H O X P I E A F Z Q U M C B J T S N R D L V G    0.7304326114037832\n    (5)  Z H O X P I E A F Y Q U M L B J T S N R C D V G    0.7304150062665732\n    (6)  Y H O X P I E A F Z Q U M L B J T S N R C D V G    0.7304098760033282\n    (9)  Z H O X P I E A F Y Q U M D B J C S N R T L V G    0.7304086837530025\n    (7)  Z H O X P I E A F Y Q U M L B J T S N R D C V G    0.730407663362785\n    (11) Y H O X P I E A Z F Q U M D B J T S N R C L V G    0.7304062233896591\n    (12) F H O X P I E A Z Y Q U M D B J T S N R C L V G    0.7304060351998625\n    (10) Y H O X P I E A F Z Q U M D B J C S N R T L V G    0.7304035534897575\n    (8)  Y H O X P I E A F Z Q U M L B J T S N R D C V G    0.73040253309954\n    12 of 12 layouts tied for first place\n    Remove parameter skip_row_3away:\n    Variant                                                 Score\n    (2)  Y H O X P I E A F Z Q U M D B J T S N R C L V G    0.7190492106548195\n    (1)  Z H O X P I E A F Y Q U M D B J T S N R C L V G    0.7190484323510822\n    (4)  Y H O X P I E A F Z Q U M C B J T S N R D L V G    0.7190397151951259\n    (3)  Z H O X P I E A F Y Q U M C B J T S N R D L V G    0.7190389368913884\n    (6)  Y H O X P I E A F Z Q U M L B J T S N R C D V G    0.719017446989355\n    (5)  Z H O X P I E A F Y Q U M L B J T S N R C D V G    0.7190166686856175\n    (8)  Y H O X P I E A F Z Q U M L B J T S N R D C V G    0.719013493227582\n    (7)  Z H O X P I E A F Y Q U M L B J T S N R D C V G    0.7190127149238446\n    (10) Y H O X P I E A F Z Q U M D B J C S N R T L V G    0.7190103176768552\n    (9)  Z H O X P I E A F Y Q U M D B J C S N R T L V G    0.7190095393731178\n    (12) F H O X P I E A Z Y Q U M D B J T S N R C L V G    0.7190080133441281\n    (11) Y H O X P I E A Z F Q U M D B J T S N R C L V G    0.7190066554444265\n    12 of 12 layouts tied for first place\n    Remove parameter skip_row_2away:\n    Variant                                                 Score\n    (1)  Z H O X P I E A F Y Q U M D B J T S N R C L V G    0.723026120277833\n    (2)  Y H O X P I E A F Z Q U M D B J T S N R C L V G    0.7230237186383444\n    (3)  Z H O X P I E A F Y Q U M C B J T S N R D L V G    0.7230162336491563\n    (4)  Y H O X P I E A F Z Q U M C B J T S N R D L V G    0.7230138320096677\n    (5)  Z H O X P I E A F Y Q U M L B J T S N R C D V G    0.7230098079422689\n    (6)  Y H O X P I E A F Z Q U M L B J T S N R C D V G    0.7230074063027803\n    (7)  Z H O X P I E A F Y Q U M L B J T S N R D C V G    0.7230056187074542\n    (8)  Y H O X P I E A F Z Q U M L B J T S N R D C V G    0.7230032170679657\n    (9)  Z H O X P I E A F Y Q U M D B J C S N R T L V G    0.7229884543275135\n    (10) Y H O X P I E A F Z Q U M D B J C S N R T L V G    0.7229860526880248\n    (11) Y H O X P I E A Z F Q U M D B J T S N R C L V G    0.7229755076488105\n    12 of 12 layouts tied for first place\n    Remove parameter skip_row_1away:\n    Variant                                                 Score\n    (1)  Z H O X P I E A F Y Q U M D B J T S N R C L V G    0.7285345017489695\n    (2)  Y H O X P I E A F Z Q U M D B J T S N R C L V G    0.7285267361659309\n    (3)  Z H O X P I E A F Y Q U M C B J T S N R D L V G    0.7285234335560208\n    (4)  Y H O X P I E A F Z Q U M C B J T S N R D L V G    0.7285156679729821\n    (9)  Z H O X P I E A F Y Q U M D B J C S N R T L V G    0.7284954366921329\n    (5)  Z H O X P I E A F Y Q U M L B J T S N R C D V G    0.7284940709462921\n    (10) Y H O X P I E A F Z Q U M D B J C S N R T L V G    0.7284876711090943\n    (6)  Y H O X P I E A F Z Q U M L B J T S N R C D V G    0.7284863053632535\n    (7)  Z H O X P I E A F Y Q U M L B J T S N R D C V G    0.7284704290580903\n    (8)  Y H O X P I E A F Z Q U M L B J T S N R D C V G    0.7284626634750516\n    12 of 12 layouts tied for first place\n    Remove parameter skip_row_0away:\n    Variant                                                 Score\n    (3)  Z H O X P I E A F Y Q U M C B J T S N R D L V G    0.7223799823972282\n    (1)  Z H O X P I E A F Y Q U M D B J T S N R C L V G    0.7223782546378588\n    (4)  Y H O X P I E A F Z Q U M C B J T S N R D L V G    0.7223782461644987\n    (2)  Y H O X P I E A F Z Q U M D B J T S N R C L V G    0.7223765184051292\n    (7)  Z H O X P I E A F Y Q U M L B J T S N R D C V G    0.7223537604296844\n    (8)  Y H O X P I E A F Z Q U M L B J T S N R D C V G    0.7223520241969549\n    (5)  Z H O X P I E A F Y Q U M L B J T S N R C D V G    0.7223464909723941\n    (6)  Y H O X P I E A F Z Q U M L B J T S N R C D V G    0.7223447547396646\n    (9)  Z H O X P I E A F Y Q U M D B J C S N R T L V G    0.7223396437775654\n    (10) Y H O X P I E A F Z Q U M D B J C S N R T L V G    0.722337907544836\n    (11) Y H O X P I E A Z F Q U M D B J T S N R C L V G    0.7223339704955882\n    (12) F H O X P I E A Z Y Q U M D B J T S N R C L V G    0.7223304549970486\n    12 of 12 layouts tied for first place\n    Remove parameter same_finger:\n    Variant                                                 Score\n    (2)  Y H O X P I E A F Z Q U M D B J T S N R C L V G    0.7409975074251155\n    (4)  Y H O X P I E A F Z Q U M C B J T S N R D L V G    0.7409927982917923\n    (1)  Z H O X P I E A F Y Q U M D B J T S N R C L V G    0.7409730432979155\n    (3)  Z H O X P I E A F Y Q U M C B J T S N R D L V G    0.7409683341645922\n    (8)  Y H O X P I E A F Z Q U M L B J T S N R D C V G    0.7409665763242484\n    (6)  Y H O X P I E A F Z Q U M L B J T S N R C D V G    0.7409657437596509\n    (7)  Z H O X P I E A F Y Q U M L B J T S N R D C V G    0.7409421121970484\n    (5)  Z H O X P I E A F Y Q U M L B J T S N R C D V G    0.7409412796324509\n    12 of 12 layouts tied for first place\n### Assign letters W and K and test left/right swap\n\nTest to see if equal or higher scores are obtained for the following:\n\n    1. Assign W and K to keys 112 and 113\n    2. Swap left and right sides\n\n\n```python\nlayouts_26letters = [\n    ['Z','H','O','X','P','I','E','A','F','Y','Q','U', 'M','D','B','J','T','S','N','R','C','L','V','G', '-','-','-', '-','-','-', 'W','K'],\n    ['Z','H','O','X','P','I','E','A','F','Y','Q','U', 'M','D','B','J','T','S','N','R','C','L','V','G', '-','-','-', '-','-','-', 'K','W'],\n    ['J','B','D','M','R','N','S','T','G','V','L','C', 'X','O','H','Z','A','E','I','P','U','Q','Y','F', '-','-','-', '-','-','-', 'W','K'],\n    ['J','B','D','M','R','N','S','T','G','V','L','C', 'X','O','H','Z','A','E','I','P','U','Q','Y','F', '-','-','-', '-','-','-', 'K','W']]\ndata_matrix = Factors32x32\nscores_26letters = []\nfor layout_26letters in layouts_26letters:\n    scores_26letters.append(score_layout(data_matrix, layout_26letters, bigrams, bigram_frequencies, verbose=False))\n\nscores_26letters_sorted, ranks_26letters_sorted, Isort_26letters = rank_within_epsilon(scores_26letters, \n                                                                        factor32, factor=True, verbose=False)\nprint('\\n    Rank                                                                   Score')\nfor i, rank in enumerate(ranks_26letters_sorted):\n    layout_string = layouts_26letters[Isort_26letters[i]]\n    layout = ' '.join(layout_string)\n    print('    {0}:  {1}    {2}'.format(rank, layout, scores_26letters_sorted[i]))\n    \nprint('')\nprint_layout24(layouts_26letters[0])\n```\n\nW above K received the highest score, but all four tied for first place:\n\n    Rank                                                                   Score\n    1:  Z H O X P I E A F Y Q U M D B J T S N R C L V G - - - - - - W K    0.6276635389970967\n    1:  J B D M R N S T G V L C X O H Z A E I P U Q Y F - - - - - - W K    0.6276633562753785\n    1:  Z H O X P I E A F Y Q U M D B J T S N R C L V G - - - - - - K W    0.627662962273589\n    1:  J B D M R N S T G V L C X O H Z A E I P U Q Y F - - - - - - K W    0.6276628500567929\n\nWe will choose the top layout with vowels on the left as our engram-es layout:\n\n    Z H O X  M D B J\n    P I E A  T S N R\n    F Y Q U  C L V G\n\n\n\n```python\nwinner24 = ['Z','H','O','X','P','I','E','A','F','Y','Q','U', 'M','D','B','J','T','S','N','R','C','L','V','G']\nwinner32 = ['Z','H','O','X','P','I','E','A','F','Y','Q','U', 'M','D','B','J','T','S','N','R','C','L','V','G', '-','-','-', '-','-','-', 'W','K']\n```\n\n### Test 3. Stability test: search for higher-scoring layouts by rearranging letters\n\nThe following test is to see if allowing random sets of eight letters to rearrange in every possible combination improves the score of the winning layout. After randomly selecting eight letters from the top-scoring layout, creating layouts from every permutation of these letters, and computing their scores, we get identical results as the original layout. We repeated this test over a thousand times (40,320,000 layouts).\n\nThe eight letters are selected from all but the 4 vowels assigned to the left side in the top-scoring layout and the 4 consonants that were assigned to the same keys in all 16 top layouts:\n\n        - - O - - I E A - - - - M - - - - S N R - - - -\n\n\n```python\nrun_stability_test = True\nif run_stability_test:\n    original_score = score_layout(Factors24x24, winner24, bigrams, bigram_frequencies, verbose=False)\n    top_score_test3 = original_score\n    nunber_of_tests = 1000\n    size_random_set = 8\n    indices = [0,1,3, 4, 8,9,10,11, 13,14,15, 16, 20,21,22,23]\n\n    #  Z H O X  M D B J\n    #  P I E A  T S N R\n    #  F Y Q U  C L V G\n\n    #  - - O -  M - - - \n    #  - I E A  - S N R\n    #  - - - -  - - - -\n\n    print(original_score)\n\n    for i in range(nunber_of_tests):\n\n        print(i)\n        \n        letters_copy = winner24.copy() \n        random_indices = []\n        while np.size(random_indices) < size_random_set:\n            random_index = indices[np.int( np.round( (np.size(indices) - 1) * np.random.random(1) )[0])]\n            if random_index not in random_indices:\n                random_indices.append(random_index)   \n        for irand in random_indices:\n            letters_copy[np.int(irand)] = ''\n\n        top_permutation_test3, top_score_test3 = permute_optimize(winner24, letters_copy, letters24, keys24, \n                                                                  Factors24x24, bigrams, bigram_frequencies,                                                                   \n                                                                  min_score=top_score_test3, verbose=False)\n\n        if ''.join(top_permutation_test3) != ''.join(winner24) and top_score_test3 > original_score:\n            print(top_score_test3)\n            print(*top_permutation_test3)\n```\n\n\n\n## Step 5: Arrange non-letter characters in easy-to-remember places <a name=\"step5\">\n    \nNow that we have all 26 letters accounted for, we turn our attention to non-letter characters, taking into account frequency of punctuation and ease of recall.\n  \n### Add diacritical marks\n\nA special diacritical key (denoted by \u2606 U+2606) when simultaneously pressed with a letter adds a diacritical mark to that letter:\n  \n    \u2606 + aeiouAEIOU = \u00e1\u00e9\u00ed\u00f3\u00fa\u00c1\u00c9\u00cd\u00d3\u00da (acute accent)\n    \u2606 + nN = \u00f1\u00d1\n    \u2606 + cC = \u00e7\u00c7\n    \u2606 + Shift + [letter] = [letter] with a diaresis/umlaut: \u00fc\n    \nFor generalizability beyond Spanish:\n    \n    \u2606         + AltGr + [letter] = [letter] with a grave accent: \u00e8\n    \u2606 + Shift + AltGr + [letter] = [letter] with a circumflex: \u00e2\n \n\n### Add punctuation keys and number keys\n\nWe will assign some of the most frequent punctuation to the six keys in the middle two columns:\n\n            Z H O X  .   \"   M D B J W\n            P I E A  ,   \u2606   T S N R K\n            F Y Q U  \u00bf   ?   C L V G\n\nWe will use the Shift key to group similar punctuation marks:\n\n            Z H O X  .:  \"'  M D B J W\n            P I E A  ,;  \u2606   T S N R K\n            F Y Q U  \u00bf\u00a1  ?!  C L V G\n\n**Number keys**: \nThe numbers are flanked to the left and right by [square brackets], and {curly brackets} accessed by the Shift key. Each of the numbers is paired with a mathematical or logic symbol accessed by the Shift key:\n    \n    { | = ~ +   <  >   ^ & % * } \\\n    [ 1 2 3 4   5  6   7 8 9 0 ] /\n\n    1: | (vertical bar or \"pipe\" represents the logical OR operator: 1 stroke, looks like the number one)\n    2: = (equal: 2 strokes, like the Chinese character for \"2\")\n    3: ~ (tilde: \"almost equal\", often written with 3 strokes, like the Chinese character for \"3\")\n    4: + (plus: has four quadrants; resembles \"4\")\n    5 & 6: < > (\"less/greater than\"; these angle brackets are directly above the other bracket keys)\n    7: ^ (caret for logical XOR operator as well as exponentiation; resembles \"7\")\n    8: & (ampersand: logical AND operator; resembles \"8\")\n    9: % (percent: related to division; resembles \"9\")\n    0: * (asterisk: for multiplication; resembles \"0\") \n\nThe three remaining keys in many common keyboards (flanking the upper right hand corner Backspace key) are displaced in special keyboards, such as the Kinesis Advantage and Ergodox. For the top right key, we will assign the forward slash and backslash: / \\\\. For one of the remaining two keys we will assign the hyphen and underscore, and to the other key, two symbols that in modern usage have significance in social media: the hash/pound sign and the \"at sign\". The hash or hashtag identifies digital content on a specific topic (the Shift key accesses the money sign). The \"at sign\" identifies a location or affiliation (such as in email addresses) and acts as a \"handle\" to identify users in popular social media platforms and online forums.\n\nThe resulting engram-es layout:\n\n          [ | = ~ +   <  >   ^ & % * ] \\\n          ( 1 2 3 4   5  6   7 8 9 0 ) /\n\n            Z H O X  .:  \"'  M D B J W -_ @#\n            P I E A  ,;  \u2606   T S N R K\n            F Y Q U  \u00bf\u00a1  ?!  C L V G\n\nThe AltGr key will access additional symbols:\n    \n    AltGr + ( = { (open curly brace)\n    AltGr + ) = } (close curly brace)\n    AltGr + 5 = \u00ab (open quote/comillas) \n    AltGr + 6 = \u00bb (close quote/comillas)\n    AltGr + - = \u2014 (em dash)\n    AltGr + ' = ` (back tick)\n    AltGr + . = \u2022 (middle dot, or \"interpunct\")\n    AltGr + s = $ (dollar currency)\n    AltGr + e = \u20ac (euro currency)\n    AltGr + l = \u00a3 (pound currency)\n \nAnd the extra key on ISO keyboards accesses a duplicate asterisk (*).\n\n\n```python\n\n```\n", "meta": {"hexsha": "695c63f1937fa4752f42b4b6787a81251ccd5db4", "size": 182908, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "engram-es_layout_v1.0.ipynb", "max_stars_repo_name": "binarybottle/engram-es", "max_stars_repo_head_hexsha": "e7d303145b4164ad5bbfe8efe20d212fae3bd253", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-08-08T05:45:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T10:29:30.000Z", "max_issues_repo_path": "engram-es_layout_v1.0.ipynb", "max_issues_repo_name": "binarybottle/engram-es", "max_issues_repo_head_hexsha": "e7d303145b4164ad5bbfe8efe20d212fae3bd253", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-07-25T16:38:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T16:27:16.000Z", "max_forks_repo_path": "engram-es_layout_v1.0.ipynb", "max_forks_repo_name": "binarybottle/engram-es", "max_forks_repo_head_hexsha": "e7d303145b4164ad5bbfe8efe20d212fae3bd253", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.5748778385, "max_line_length": 4130, "alphanum_fraction": 0.4890491395, "converted": true, "num_tokens": 51298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.07807817265325535, "lm_q1q2_score": 0.02749927154751934}}
{"text": "```python\nfrom IPython.display import Image\nImage('../../Python_probability_statistics_machine_learning_2E.png',width=200)\n```\n\nThere is nothing so practical as a good theory. In this section, we establish\nthe formal framework for thinking about machine learning.  This framework will\nhelp us think beyond particular methods for machine learning so we can\nintegrate new methods or combine existing methods intelligently.\n\nBoth machine learning and statistics strive to develop\nunderstanding from data.  Some historical perspective helps. Most of the\nmethods in statistics were derived towards the start of the 20th century when\ndata were hard to come by. Society was preoccupied with the potential dangers\nof human overpopulation and work was focused on studying agriculture and\ncrop yields. At this time, even a dozen data points was considered\nplenty.  Around the same time, the deep foundations of probability were being\nestablished by Kolmogorov. Thus, the lack of data meant that the conclusions\nhad to be buttressed by strong assumptions and solid  mathematics provided by\nthe emerging theory of probability.  Furthermore, inexpensive powerful\ncomputers were not yet widely available. The situation today is much different:\nthere are lots of data collected and powerful and easily programmable computers\nare available. The important problems no longer revolve around a dozen data\npoints on a farm acre, but rather millions of points on a square millimeter of\na DNA microarray.  Does this mean that statistics will be superseded by machine\nlearning?\n\nIn contrast to classical statistics, which is concerned with\ndeveloping models that characterize, explain, and describe\nphenomena, machine learning is overwhelmingly concerned with\nprediction.  Areas like exploratory statistics are very\nclosely related to machine learning, but still not as\nfocused on prediction. In some sense, this is unavoidable\ndue the size of the data machine learning can reduce.  In\nother words, machine learning can help distill a table of a\nmillion columns into one hundred columns, but can we still\ninterpret one hundred columns meaningfully? In classical\nstatistics,  this was never an issue because data were of a\nmuch smaller scale.   Whereas mathematical models, usually\nnormal distributions, fitted with observations are common in\nstatistics, machine learning uses data to construct models\nthat sit on complicated data structures and exploit\nnonlinear optimizations that lack closed-form solutions. A\ncommon maxim is that statistics is data plus analytical\ntheory and machine learning is data plus computable\nstructures. This makes it seem like machine learning is\ncompletely ad-hoc and devoid of underlying theory, but this\nis not the case, and both machine learning and statistics\nshare many important theoretical results. By way of\ncontrast, let us consider a concrete problem.\n\nLet's consider the classic balls in urns problem (see [Figure](#fig:learning_theory_tmp_001)): we have an urn containing red and\nblue balls and we draw five balls from the urn, note the color of each\nball, and then try to determine the proportion of red and blue balls\nin the urn. We have already studied many statistical methods for\ndealing with this problem. Now, let's generalize\nthe problem slightly.  Suppose the urn is filled with white balls and\nthere is some target unknown function $f$ that paints each selected\nball either red or blue (see [Figure](#fig:learning_theory_tmp_002)).\nThe machine learning problem is how to find the $f$ function, given\nonly the observed red/blue balls. So far, this doesn't sound much\ndifferent from the statistical problem. However, now we want to take\nour estimated $f$ function, say, $\\hat{f}$, and use it to predict the\nnext handful of balls from another urn.  Now, here's where the story\ntakes a sharp turn. Suppose the next urn *already* has some red and\nblue balls in it?  Then, applying the function $f$ may result in\npurple balls which were not seen in the *training* data (see [Figure](#fig:learning_theory_tmp_003)). What can we do?  We have just\nscraped the surface of the issues machine learning must confront using\nmethods that are not part of the statistics canon.\n\n<!-- dom:FIGURE: [fig-machine_learning/learning_theory_tmp_001.png, width=500 frac=0.50] In the classical statistics problem, we observe a sample and model what the urn contains. <div id=\"fig:learning_theory_tmp_001\"></div> -->\n<!-- begin figure -->\n<div id=\"fig:learning_theory_tmp_001\"></div>\n\n<p>In the classical statistics problem, we observe a sample and model what the urn contains.</p>\n\n\n<!-- end figure -->\n\n\n<!-- dom:FIGURE: [fig-machine_learning/learning_theory_tmp_002.png, width=500 frac=0.60] In the machine learning problem, we want the function that colors the marbles. <div id=\"fig:learning_theory_tmp_002\"></div> -->\n<!-- begin figure -->\n<div id=\"fig:learning_theory_tmp_002\"></div>\n\n<p>In the machine learning problem, we want the function that colors the marbles.</p>\n\n\n<!-- end figure -->\n\n\n<!-- dom:FIGURE: [fig-machine_learning/learning_theory_tmp_003.png, width=500 frac=0.60] The problem is further complicated because we may see colored marbles that were not present in the original problem.  <div id=\"fig:learning_theory_tmp_003\"></div> -->\n<!-- begin figure -->\n<div id=\"fig:learning_theory_tmp_003\"></div>\n\n<p>The problem is further complicated because we may see colored marbles that were not present in the original problem.</p>\n\n\n<!-- end figure -->\n\n\n## Introduction to Theory of Machine Learning\n\nSome formality and an example can get us going. We define the unknown\ntarget function, $f:\\mathcal{X} \\mapsto \\mathcal{Y}$. The training set\nis $\\left\\{(x,y)\\right\\}$ which means that we only see the function's\ninputs/outputs. The hypothesis set $\\mathcal{H}$ is the set of all\npossible guesses at $f$. This is the set from which we will ultimately\ndraw our final estimate, $\\hat{f}$. The machine learning problem is\nhow to  derive the best element from the hypothesis set by using the\ntraining set.  Let's consider a concrete example in the code below.\nSuppose $\\mathcal{X}$ consists of all three-bit vectors (i.e.,\n$\\mathcal{X}=\\left\\{000,001,\\ldots,111\\right\\}$) as in the code below,\n\n\n```python\nimport pandas as pd\nimport numpy as np\nfrom pandas import DataFrame\ndf=DataFrame(index=pd.Index(['{0:04b}'.format(i) \n                              for i in range(2**4)],\n                            dtype='str',\n                            name='x'),columns=['f'])\n```\n\n**Programming Tip.**\n\nThe string specification above uses Python's advanced string\nformatting mini-language. In this case, the specification says to\nconvert the integer into a fixed-width, four-character (`04b`) binary\nrepresentation.\n\n\n\n Next, we define the target function $f$ below which just\nchecks if the number of zeros in the binary representation exceeds the\nnumber of ones.  If so, then the function outputs `1` and `0`\notherwise (i.e., $\\mathcal{Y}=\\left\\{0,1\\right\\}$).\n\n\n```python\ndf.f=np.array(df.index.map(lambda i:i.count('0')) \n               > df.index.map(lambda i:i.count('1')),dtype=int)\ndf.head(8) # show top half only\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>f</th>\n    </tr>\n    <tr>\n      <th>x</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0000</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>0001</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>0010</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>0011</th>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>0100</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>0101</th>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>0110</th>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>0111</th>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n The hypothesis set for this problem is the set of *all* possible\nfunctions of $\\mathcal{X}$. The set $\\mathcal{D}$ represents all possible\ninput/output pairs. The corresponding hypothesis set $\\mathcal{H}$ has $2^{16}$\nelements, one of which matches $f$. There are $2^{16}$ elements in the\nhypothesis set because for each of sixteen input elements, there are two\npossible corresponding values (zero or one) for each input. Thus, the size of\nthe hypothesis set is $2\\times 2\\times\\ldots\\times 2=2^{16}$.  Now, presented\nwith a training set consisting of the first eight input/output pairs, our goal\nis to minimize errors over the training set ($E_{\\texttt{in}}(\\hat{f})$).\nThere are $2^8$ elements from the hypothesis set that exactly match $f$ over\nthe training set.  But how to pick among these $2^8$ elements?  It seems that\nwe are stuck here.  We need another element from the problem in order to\nproceed. The extra piece we need is to assume that the training set represents\na random sampling (*in-sample* data) from a greater population (*out-of-sample*\ndata) that would be consistent with the population that $\\hat{f}$ would\nultimately predict upon. In other words, we are assuming a stable probability\nstructure for both the in-sample and out-of-sample data. This is a major\nassumption!\n\n\nThere is a subtle consequence of this assumption --- whatever the\nmachine learning method does once deployed, in order for it to\ncontinue to work, it cannot disturb the data environment that it was\ntrained on. Said differently, if the method is not to be trained\ncontinuously, then it cannot break this assumption by altering the\ngenerative environment that produced the data it was trained on.  For\nexample, suppose we develop a model that predicts hospital\nreadmissions based on seasonal weather and patient health.  Because\nthe model is so effective, in the next six months, the hospital\nforestalls readmissions by delivering\ninterventions that improve patient health.  Clearly using\nthe model cannot change seasonal weather, but because the hospital\nused the model to change patient health, the training data used to\nbuild the model is no longer consistent with the forward-looking\nhealth of the patients.  Thus, there is little reason to think that\nthe model will continue to work as well going forward.\n\nReturning to our example,  let's suppose that the first eight elements from\n$\\mathcal{X}$ are twice as likely as the last eight. The following code is a\nfunction that generates elements from $\\mathcal{X}$ according to this\ndistribution.\n\n\n```python\nnp.random.seed(12)\ndef get_sample(n=1):\n   if n==1:\n      return '{0:04b}'.format(np.random.choice(list(range(8))*2\n                                              +list(range(8,16))))\n   else:\n      return [get_sample(1) for _ in range(n)]\n```\n\n**Programming Tip.**\n\nThe function that returns random samples uses the\n`np.random.choice` function from Numpy which takes samples (with replacement)\nfrom the given iterable.  Because we want the first eight numbers to be twice\nas frequent as the rest, we simply repeat them in the iterable using\n`range(8)*2`. Recall that multiplying a Python list by an integer duplicates\nthe entire list by that integer. It does not do element-wise multiplication as\nwith Numpy arrays. If we wanted the first eight to be 10 times more frequent,\nthen we would use `range(8)*10`, for example. This is a simple but powerful\ntechnique that requires very little code. Note that the `p` keyword argument in\n`np.random.choice` also provides an explicit way to specify more  complicated\ndistributions.\n\n\n\n The next block applies the function definition $f$ to the\nsampled data to generate the training set consisting of eight elements.\n\n\n```python\ntrain=df.loc[get_sample(8),'f'] # 8-element training set\ntrain.index.unique().shape    # how many unique elements?\n```\n\n\n\n\n    (6,)\n\n\n\n Notice that even though there are eight elements, there is redundancy\nbecause these are drawn according to an underlying probability.  Otherwise, if\nwe just got all sixteen different elements, we would have a training set\nconsisting of the complete specification of $f$ and then we would therefore\nknow what $h\\in \\mathcal{H}$ to pick! However, this effect gives us a clue as\nto how this will ultimately work. Given the elements in the training set,\nconsider the set of elements from the hypothesis set that exactly match.  How\nto choose among these? The answer is it does not matter! Why? Because under the\nassumption that the prediction will be used in an environment that is\ndetermined by the same probability, getting something outside of the training\nset is just as likely as getting something inside the training set.  The size\nof the training set is key here --- the bigger the training set, the less\nlikely that there will be real-world data that fall outside of it and the\nbetter $\\hat{f}$ will perform [^complexity].  The following code shows the\nelements of the training set in the context of all possible data. \n\n[^complexity]: This assumes that the hypothesis set is big enough to capture\nthe entire training set (which it is for this example). We will discuss this\ntrade-off in greater generality shortly.\n\n\n```python\ndf['fhat']=df.loc[train.index.unique(),'f']\ndf.fhat\n```\n\n\n\n\n    x\n    0000    NaN\n    0001    NaN\n    0010    1.0\n    0011    0.0\n    0100    1.0\n    0101    NaN\n    0110    0.0\n    0111    NaN\n    1000    1.0\n    1001    0.0\n    1010    NaN\n    1011    NaN\n    1100    NaN\n    1101    NaN\n    1110    NaN\n    1111    NaN\n    Name: fhat, dtype: float64\n\n\n\n Note that there are `NaN` symbols where the training set had\nno values. For definiteness, we fill these in with zeros, although we\ncan fill them with anything we want so long as whatever we do is not\ndetermined by the training set.\n\n\n```python\ndf.fhat.fillna(0,inplace=True) #final specification of fhat\n```\n\n Now, let's pretend we have deployed this and generate some\ntest data.\n\n\n```python\ntest= df.loc[get_sample(50),'f']\n(df.loc[test.index,'fhat'] != test).mean()\n```\n\n\n\n\n    0.18\n\n\n\n The result shows the error rate, given the\nprobability mechanism that generates the data.  The\nfollowing Pandas-fu compares the overlap between the\ntraining set and the test set in the context of all possible\ndata.  The `NaN` values show the rows where the test data\nhad items absent in the training data. Recall that the\nmethod returns zero for these items.  As shown, sometimes\nthis works in its favor, and sometimes not.\n\n\n```python\npd.concat([test.groupby(level=0).mean(), \n           train.groupby(level=0).mean()],\n          axis=1,\n          keys=['test','train'])\n```\n\n    /home/unpingco/.conda/envs/pypsml2E/lib/python3.7/site-packages/ipykernel_launcher.py:4: FutureWarning: Sorting because non-concatenation axis is not aligned. A future version\n    of pandas will change to not sort by default.\n    \n    To accept the future behavior, pass 'sort=False'.\n    \n    To retain the current behavior and silence the warning, pass 'sort=True'.\n    \n      after removing the cwd from sys.path.\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>test</th>\n      <th>train</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0000</th>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>0001</th>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>0010</th>\n      <td>1</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>0011</th>\n      <td>0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>0100</th>\n      <td>1</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>0101</th>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>0110</th>\n      <td>0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>0111</th>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1000</th>\n      <td>1</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>1001</th>\n      <td>0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>1010</th>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1011</th>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1100</th>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1101</th>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1110</th>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1111</th>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n Note that where the test data and training data shared\nelements, the prediction matched; but when the test set produced an unseen\nelement, the prediction may or may not have matched.\n\n**Programming Tip.**\n\nThe `pd.concat` function concatenates the two `Series` objects in the\nlist. The `axis=1` means join the two objects along the columns where\neach newly created column is named according to the given `keys`. The\n`level=0` in the `groupby` for each of the `Series` objects  means\ngroup along the index. Because the index corresponds to the 4-bit\nelements, this accounts for repetition in the elements. The `mean`\naggregation function computes the values of the function for each\n4-bit element. Because all functions in each  respective group have\nthe same value, the `mean` just picks out that value\nbecause the average of a list of constants is that constant.\n\n\n\nNow, we are in position to ask how big the training set should be to achieve a\nlevel of performance. For example, on average, how many in-samples do we need\nfor a given error rate? For this problem, we can ask how large (on average)\nmust the training set be in order to capture *all* of the possibilities and\nachieve perfect out-of-sample error rates?  For this problem, this turns out\nto be sixty-three [^coupon].  Let's start over and retrain with these many\nin-samples.\n\n[^coupon]: This is a slight generalization of the classic coupon collector problem.\n\n\n```python\ntrain=df.loc[get_sample(63),'f'] \ndel df['fhat']   \ndf['fhat']=df.loc[train.index.unique(),'f']\ndf.fhat.fillna(0,inplace=True) #final specification of fhat\ntest= df.loc[get_sample(50),'f'] \n# error rate\n(df.loc[test.index,'fhat'] != df.loc[test.index,'f']).mean()\n```\n\n\n\n\n    0.0\n\n\n\n Notice that this bigger training set has a better error rate because\nit is able to identify the best element from the hypothesis set because the\ntraining set captured more of the complexity of the unknown $f$. This example\nshows the trade-offs between the size of the training set, the complexity of\nthe target function, the probability structure of the data, and the size of the\nhypothesis set. Note that upon exposure to the data, the so-called learning\nmethod did nothing besides memorize the data and give any unknown, newly\nencountered data the zero output. This means that the hypothesis set \ncontains the single hypothesis function that memorizes and defaults to zero\noutput. If the method attempted to change the default zero output based on the\nparticular data, then we could say that meaningful learning took place.  What\nwe lack here is *generalization*, which is the topic of the next section.\n\n## Theory of Generalization\n\nWhat we really want to know is how the our method will perform once deployed.\nIt would be nice to have some kind of performance guarantee. In other words, we\nworked hard to minimize the errors in the training set, but what errors can we expect at deployment? In training, we minimized the\nin-sample error, $E_{\\texttt{in}}(\\hat{f}) $, but that's not good enough.  We\nwant guarantees about the out-of-sample error, $ E_{\\texttt{out}}(\\hat{f})$.\nThis is what *generalization* means in machine learning. The\nmathematical statement of this is the following,\n\n$$\n\\mathbb{P}\\left( \\lvert E_{\\texttt{out}}(\\hat{f})-E_{\\texttt{in}}(\\hat{f}) \\rvert > \\epsilon \\right) < \\delta\n$$\n\n for $\\epsilon$ and $\\delta$. Informally, this says\nthat the probability of the respective errors differing by more than a\ngiven $\\epsilon$ is less than some quantity, $\\delta$. This \nmeans that whatever the performance on the training set, it should\nprobably  be pretty close to the corresponding performance once\ndeployed.  Note that this does not say that the in-sample errors\n($E_{\\texttt{in}}$) are any good in an absolute sense.  It just says\nthat we would not expect much different after deployment.  Thus,\n*good* generalization means no surprises after deployment, not\nnecessarily good performance.  There are two main ways\nto get at this: cross-validation and probability inequalities.  Let's\nconsider the latter first.  There are two entangled issues: the\ncomplexity of the hypothesis set and the probability of the data. It\nturns out we can separate these two by deriving a separate notion of\ncomplexity free from any particular data probability.\n\n\n**VC Dimension.** We first need a way to quantify model complexity.\nFollowing Wasserman [[wasserman2004all]](#wasserman2004all), let $\\mathcal{A}$ be a\nclass of sets and $F = \\left\\{x_1,x_2,\\ldots,x_n\\right\\}$, a set of\n$n$ data points. Then, we define\n\n$$\nN_{\\mathcal{A}}(F)=\\# \\left\\{ F \\cap A : A \\in \\mathcal{A}\\right\\}\n$$\n\n This counts the number of subsets of $F$ that can be extracted by the\nsets of $\\mathcal{A}$. The number of items in the set (i.e., cardinality) is\nnoted by the $\\#$ symbol.  For example, suppose $F=\\left\\{1\\right\\}$ and\n$\\mathcal{A}=\\left\\{(x\\leq a)\\right\\}$.  In other words, $\\mathcal{A}$ consists\nof all intervals closed on the right and parameterized by $a$. In this case we\nhave $N_{\\mathcal{A}}(F)=1$ because all elements can be extracted from $F$\nusing $\\mathcal{A}$. Specifically, any $a>1$ means that $\\mathcal{A}$ contains $F$.\n\n\nThe *shatter coefficient* is defined as,\n\n$$\ns(\\mathcal{A},n) = \\max_{F\\in \\mathcal{F}_n} N_{\\mathcal{A}}(F)\n$$\n\n where $\\mathcal{F}$ consists of all finite sets of size $n$. Note\nthat this sweeps over all finite sets so we don't need to worry about any\nparticular data set of finitely many points. The definition is concerned with\n$\\mathcal{A}$ and how its sets can pick off elements from the data set. A\nset $F$ is *shattered* by $\\mathcal{A}$ if it can pick out every element in it.\nThis provides a sense of how the complexity in $\\mathcal{A}$ consumes data. In\nour last example, the set of half-closed intervals shattered every singleton\nset $\\left\\{x_1\\right\\}$. \n\nNow, we come to the main definition of the Vapnik-Chervonenkis\n[[vapnik2000nature]](#vapnik2000nature) dimension $d_{\\texttt{VC}}$ which defined as the largest\n$k$ for which $s(\\mathcal{A},n) = 2^k$, except in the case where\n$s(\\mathcal{A},n) = 2^n$ for which it is defined as  infinity. For our example\nwhere $F= \\left\\{x_1\\right\\}$, we already saw that $\\mathcal{A}$ shatters $F$.\nHow about when $F=\\left\\{x_1,x_2\\right\\}$? Now, we have two points and we have\nto consider whether all subsets can be  extracted by $\\mathcal{A}$. In this\ncase, there are four subsets,\n$\\left\\{\\o,\\left\\{x_1\\right\\},\\left\\{x_2\\right\\},\\left\\{x_1,x_2\\right\\}\n\\right\\}$.  Note that $\\o$ denotes the empty set. The empty set is easily\nextracted --- pick $a$ so that it is smaller than both\n$x_1$ and $x_2$.  Assuming that $x_1<x_2$, we can get the next set by\nchoosing $x_1<a<x_2$. The last set is likewise do-able by choosing $x_2<a$.\nThe problem is that we cannot capture the third set, $\\left\\{x_2\\right\\}$,\nwithout capturing $x_1$ as well.  This means that we cannot shatter any\nfinite set with $n=2$ using $\\mathcal{A}$. Thus, $d_{\\texttt{VC}}=1$.\n\nHere is the climatic result\n\n$$\nE_{\\texttt{out}}(\\hat{f})\\leq E_{\\texttt{in}}(\\hat{f})+\\sqrt{\\frac{8}{n}\\ln\\left(\\frac{4((2 n)^{ d_{\\texttt{VC}} }+1)}{\\delta} \\right) }\n$$\n\n with probability at least $1-\\delta$. This basically says that the\nexpected out-of-sample error can be no worse than the in-sample error plus a\npenalty due to the complexity of the hypothesis set. The expected in-sample error\ncomes from the training set but the complexity penalty comes\nfrom just the hypothesis set, thus  disentangling these two issues.\n\nA general result like this, for which we do not worry about the probability of\nthe data, is certain to be pretty generous, but nonetheless, it tells us how\nthe complexity penalty enters into the out-of-sample error.  In other words,\nthe bound on $E_{\\texttt{out}}(\\hat{f})$ gets worse for a more complex\nhypothesis set. Thus, this generalization bound is a useful guideline but not\nvery practical if we want to get a good estimate of\n$E_{\\texttt{out}}(\\hat{f})$.\n\n## Worked Example for Generalization/Approximation Complexity\n\nThe stylized curves in  [Figure](#fig:learning_theory_tmp_004) illustrate the\nidea that there is some optimal point of complexity that represents the best\ngeneralization given the training set.\n\n<!-- dom:FIGURE: [fig-machine_learning/learning_theory_tmp_004.png, width=500 frac=0.80] In the ideal situation, there is a *best model* that represents the optimal trade-off between complexity and error. This is shown by the vertical line.   <div id=\"fig:learning_theory_tmp_004\"></div> -->\n<!-- begin figure -->\n<div id=\"fig:learning_theory_tmp_004\"></div>\n\n<p>In the ideal situation, there is a <em>best model</em> that represents the optimal trade-off between complexity and error. This is shown by the vertical line.</p>\n\n\n<!-- end figure -->\n\n\nTo get a firm handle on these curves, let's develop a simple one-dimensional\nmachine learning method and go through the steps to create this graph.  Let's\nsuppose we have a training set consisting of x-y pairs\n$\\left\\{(x_i,y_i)\\right\\}$. Our method groups the x-data into intervals\nand then averages the y-data in those intervals. Predicting for new x-data\nmeans simply identifying the interval containing the new data then reporting\nthe corresponding value. In other words, we are building a simple\none-dimensional, nearest neighbor classifier. For example, suppose the training set\nx-data is the following,\n\n\n```python\ntrain=DataFrame(columns=['x','y'])\ntrain['x']=np.sort(np.random.choice(range(2**10),size=90))\ntrain.x.head(10) # first ten elements\n```\n\n\n\n\n    0     15\n    1     30\n    2     45\n    3     65\n    4     76\n    5     82\n    6    115\n    7    145\n    8    147\n    9    158\n    Name: x, dtype: int64\n\n\n\n In this example, we took a random set of 10-bit integers. To group these\ninto, say, ten intervals, we simply use Numpy reshape as in the following,\n\n\n```python\ntrain.x.values.reshape(10,-1)\n```\n\n\n\n\n    array([[ 15,  30,  45,  65,  76,  82, 115, 145, 147],\n           [158, 165, 174, 175, 181, 209, 215, 217, 232],\n           [233, 261, 271, 276, 284, 296, 318, 350, 376],\n           [384, 407, 410, 413, 452, 464, 472, 511, 522],\n           [525, 527, 531, 534, 544, 545, 548, 567, 567],\n           [584, 588, 610, 610, 641, 645, 648, 659, 667],\n           [676, 683, 684, 697, 701, 703, 733, 736, 750],\n           [754, 755, 772, 776, 790, 794, 798, 804, 830],\n           [831, 834, 861, 883, 910, 910, 911, 911, 937],\n           [943, 946, 947, 955, 962, 962, 984, 989, 998]])\n\n\n\n where every row is one of the groups. Note that the range of each\ngroup (i.e., length of the interval) is not preassigned, and is learned from\nthe training data. For this example, the y-values correspond to the number of\nones in the bit representation of the x-values. The following code defines this\ntarget function,\n\n\n```python\nf_target=np.vectorize(lambda i:i.count('1'))\n```\n\n**Programming Tip.**\n\nThe above function uses `np.vectorize` which is a convenience method in Numpy\nthat converts plain Python functions into Numpy versions. This basically saves\nadditional looping semantics and makes it easier to use with other Numpy\narrays and functions.\n\n\n\n Next, we create the bit representations of all of the x-data below and\nthen complete training set y-values,\n\n\n```python\ntrain['xb']= train.x.map('{0:010b}'.format)\ntrain.y=train.xb.map(f_target)\ntrain.head(5)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>x</th>\n      <th>y</th>\n      <th>xb</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>15</td>\n      <td>4</td>\n      <td>0000001111</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>30</td>\n      <td>4</td>\n      <td>0000011110</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>45</td>\n      <td>4</td>\n      <td>0000101101</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>65</td>\n      <td>2</td>\n      <td>0001000001</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>76</td>\n      <td>3</td>\n      <td>0001001100</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nTo train on this data, we just group by the specified amount and then\naverage the y-data over each group.\n\n\n```python\ntrain.y.values.reshape(10,-1).mean(axis=1)\n```\n\n\n\n\n    array([3.55555556, 4.88888889, 4.44444444, 4.88888889, 4.11111111,\n           4.        , 6.        , 5.11111111, 6.44444444, 6.66666667])\n\n\n\n Note that the `axis=1` keyword argument just means average across the\n columns. So far, this defines the training.  To predict using this\nmethod, we have to extract the edges from each of the groups and then fill in\nwith the group-wise mean we just computed for `y`. The following code extracts\nthe edges of each group.\n\n\n```python\nle,re=train.x.values.reshape(10,-1)[:,[0,-1]].T\nprint (le) # left edge of group\nprint (re) # right edge of group\n```\n\n    [ 15 158 233 384 525 584 676 754 831 943]\n    [147 232 376 522 567 667 750 830 937 998]\n\n\n Next, we compute the group-wise means and assign them to their\nrespective edges.\n\n\n```python\nval = train.y.values.reshape(10,-1).mean(axis=1).round()\nfunc = pd.Series(index=range(1024))\nfunc[le]=val    # assign value to left edge\nfunc[re]=val    # assign value to right edge\nfunc.iloc[0]=0  # default 0 if no data\nfunc.iloc[-1]=0 # default 0 if no data\nfunc.head()\n```\n\n\n\n\n    0    0.0\n    1    NaN\n    2    NaN\n    3    NaN\n    4    NaN\n    dtype: float64\n\n\n\n Note that the Pandas `Series` object automatically fills in\nunassigned values with `NaN`. We have thus far only filled in values at the\nedges of the groups. Now, we need to fill in the intermediate values.\n\n\n```python\nfi=func.interpolate('nearest')\nfi.head()\n```\n\n\n\n\n    0    0.0\n    1    0.0\n    2    0.0\n    3    0.0\n    4    0.0\n    dtype: float64\n\n\n\n The `interpolate` method of the `Series` object can apply a wide\nvariety of powerful interpolation methods, but we only need the simple nearest\nneighbor method to create our piecewise approximant.  [Figure](#fig:learning_theory_001) shows how this looks for the training data we have\ncreated.\n\n\n```python\n%matplotlib inline\n\nfrom matplotlib.pylab import subplots, mean, arange, setp\nfig,ax=subplots()\nfig.set_size_inches((10,5))\n_=ax.axis(xmax=1024,ymax=10)\nv=ax.stem(train.x,train.y,markerfmt='go',linefmt='g-')\n_=setp(v,color='gray')\n_=fi.plot(ax=ax,lw=4.,color='k')\n_=ax.set_xlabel('$X$',fontsize=20)\n_=ax.set_ylabel('$y$',fontsize=22)\nfig.tight_layout()\nfig.savefig('fig-machine_learning/learning_theory_001.png')\n```\n\n<!-- dom:FIGURE: [fig-machine_learning/learning_theory_001.png, width=500 frac=0.85] The vertical lines show the training data and the thick black line is the approximant we have learned from the training data. <div id=\"fig:learning_theory_001\"></div> -->\n<!-- begin figure -->\n<div id=\"fig:learning_theory_001\"></div>\n\n<p>The vertical lines show the training data and the thick black line is the approximant we have learned from the training data.</p>\n\n\n<!-- end figure -->\n\n\nNow, with all that established, we can now  draw the curves for this machine\nlearning method. Instead of partitioning the training data for cross-validation\n(which we'll discuss later), we can simulate test data using the same mechanism\nas for the training data, as shown next,\n\n\n```python\ntest=pd.DataFrame(columns=['x','xb','y'])\ntest['x']=np.random.choice(range(2**10),size=500)\ntest.xb= test.x.map('{0:010b}'.format)\ntest.y=test.xb.map(f_target)\ntest.sort_values('x',inplace=True)\n```\n\n The curves are the respective errors for the training data\nand the testing data. For our error measure, we use the mean-squared-error,\n\n$$\nE_{\\texttt{out}} = \\frac{1}{n} \\sum_{i=1}^n (\\hat{f}(x_i) - y_i)^2\n$$\n\n where $\\left\\{(x_i,y_i)\\right\\}_{i=1}^n$ come from the test data. The\nin-sample error ($E_{\\texttt{in}}$) is defined the same except for the\nin-sample data.  In this example, the size of each group is proportional to\n$d_{\\texttt{VC}}$, so the more groups we choose, the more complexity in the\nfitting.  Now, we have all the ingredients to understand the trade-offs of\ncomplexity versus error.\n\n\n```python\nn=train.shape[0]\ndivisors=arange(1,n+1)[(n % arange(1,n+1))==0]\ndef atrainer(train,dvc):\n    le,re=train.x.values.reshape(dvc,-1)[:,[0,-1]].T\n    val = train.y.values.reshape(dvc,-1).mean(axis=1).round()\n    func = pd.Series(index=range(1024))\n    func[le]=val\n    func[re]=val\n    func.iloc[0]=0\n    func.iloc[-1]=0\n    fi=func.interpolate('nearest')\n    return fi\n\notrn=[]; otst=[]\nfor i in divisors: # loop over divisors\n    fi=atrainer(train,i)\n    otrn.append((mean((fi[train.x].values-train.y.values)**2)))\n    otst.append((mean((fi[test.x].values-test.y.values)**2)))\n\nfig,ax=subplots()\nfig.set_size_inches((10,6))\n_=ax.plot(divisors,otrn,'--s',label='train',color='k')\n_=ax.plot(divisors,otst,'-o',label='test',color='gray')\n_=ax.fill_between(divisors,otrn,otst,color='gray',alpha=.3)\n_=ax.legend(loc=0)\n_=ax.set_xlabel('Complexity',fontsize=22)\n_=ax.set_ylabel('Mean-squared-error',fontsize=22)\nfig.tight_layout()\nfig.savefig('fig-machine_learning/learning_theory_002.png')\n```\n\n[Figure](#fig:learning_theory_002) shows the curves for our\none-dimensional clustering method.  The dotted line shows the\nmean-squared-error on the training set and the other line shows the\nsame for the test data. The shaded region is the *complexity penalty*\nof this method.  Note that with enough complexity, the method can\nexactly memorize the testing data, but that only penalizes the testing\nerror ($E_{\\texttt{out}}$). This effect is exactly what the\nVapnik-Chervonenkis theory expresses. The horizontal axis is\nproportional to the VC-dimension. In this case, complexity boils down\nto the number of intervals used in the sectioning. At the far right,\nwe have as many intervals as there are elements in the data set,\nmeaning that every element is wrapped in its own interval. The average\nvalue of the data in that interval is therefore just the corresponding\n$y$ value because there are no other elements to average over. \n\n<!-- dom:FIGURE: [fig-machine_learning/learning_theory_002.png, width=500 frac=0.85] The dotted line shows the mean-squared-error on the training set and the other line shows the same for the test data. The shaded region is the *complexity penalty* of this method. Note that as the complexity of the model increases, the training error decreases, and the method essentially memorizes the data. However, this improvement in training error comes at the cost of larger testing error. <div id=\"fig:learning_theory_002\"></div> -->\n<!-- begin figure -->\n<div id=\"fig:learning_theory_002\"></div>\n\n<p>The dotted line shows the mean-squared-error on the training set and the other line shows the same for the test data. The shaded region is the <em>complexity penalty</em> of this method. Note that as the complexity of the model increases, the training error decreases, and the method essentially memorizes the data. However, this improvement in training error comes at the cost of larger testing error.</p>\n\n\n<!-- end figure -->\n\n\n\nBefore we leave this problem, there is another way to visualize the\nperformance of our learning method. This problem can be thought of as\na multi-class identification problem. Given a 10-bit integer, the\nnumber of ones in its binary representation is in one of the classes\n$\\left\\{0,1,\\ldots,10\\right\\}$.  The output of the model tries to put\neach integer in its respective class. How well this was done can be\nvisualized using a *confusion matrix* as shown in the next code block,\n\n\n```python\nfrom sklearn.metrics import confusion_matrix\ncmx=confusion_matrix(test.y.values,fi[test.x].values)\nprint(cmx)\n```\n\n    [[ 1  0  0  0  0  0  0  0  0  0]\n     [ 1  0  1  0  1  1  0  0  0  0]\n     [ 0  0  3  9  7  4  0  0  0  5]\n     [ 1  0  3 23 19  6  6  0  2  0]\n     [ 0  0  1 26 27 14 27  2  2  0]\n     [ 0  0  3 15 31 28 30  8  1  0]\n     [ 0  0  1  8 18 20 25 23  2  2]\n     [ 1  0  1 10  5 13  7 19  3  6]\n     [ 4  0  1  2  0  2  2  7  4  3]\n     [ 2  0  0  0  0  1  0  0  0  0]]\n\n\n The rows of this $10 \\times 10$ matrix show the true class \nand the columns indicate the class that the model predicted.  The numbers in\nthe matrix indicate the number of times that association was made. For example,\nthe first row shows that there was one entry in the test set with no ones in\nits binary representation (i.e, namely the number zero) and it was correctly\nclassified (namely, it is in the first row, first column of the matrix). The\nsecond row shows there were four entries total in the test set with a binary\nrepresentation containing exactly a single one. This was incorrectly classified\nas the 0-class (i.e, first column) once, the 2-class (third column) once, the\n4-class (fifth column) once, and the 5-class (sixth column) once.  It was never\nclassified correctly because the second column is zero for this row. In other\nwords, the diagonal entries show the number of times it was correctly\nclassified.\n\nUsing this matrix, we can easily estimate the true-detection\nprobability that we covered earlier in our hypothesis testing section,\n\n\n```python\nprint(cmx.diagonal()/cmx.sum(axis=1))\n```\n\n    [1.         0.         0.10714286 0.38333333 0.27272727 0.24137931\n     0.25252525 0.29230769 0.16       0.        ]\n\n\n In other words, the first element is the probability of detecting `0`\nwhen `0` is in force, the second element is the probability of detecting `1`\nwhen `1` is in force, and so on. We can likewise compute the false-alarm rate\nfor each of the classes in the following,\n\n\n```python\nprint((cmx.sum(axis=0)-cmx.diagonal())/(cmx.sum()-cmx.sum(axis=1)))\n```\n\n    [0.01803607 0.         0.02330508 0.15909091 0.20199501 0.15885417\n     0.17955112 0.09195402 0.02105263 0.03219316]\n\n\n**Programming Tip.**\n\nThe Numpy `sum` function can sum across a particular axis or, if the\naxis is unspecified, will sum all entries of the array.\n\n\n\n In this case, the first element is the probability that `0`\nis declared when another category is in force, the next element is the\nprobability that `1` is declared when another category is in force,\nand so on. For a decent classifier, we want a true-detection\nprobability to be greater than the corresponding false-alarm rate,\notherwise the classifier is no better than a coin-flip. \n\nThe missing feature of this problem, from the learning\nalgorithm standpoint, is that we did not supply the bit representation\nof every element which was used to derive the target variable, $y$.\nInstead, we just used the integer value of each of the 10-bit numbers,\nwhich essentially concealed the mechanism for creating the $y$ values.\nIn other words, there was a unknown transformation from the input\nspace $\\mathcal{X}$ to $\\mathcal{Y}$ that the learning algorithm had\nto overcome, but that it could not overcome, at least not without\nmemorizing the training data. This lack of knowledge is a key issue in\nall machine learning problems, although we have made it explicit here\nwith this stylized example. This means that there may be one or more\ntransformations from $\\mathcal{X} \\rightarrow \\mathcal{X}^\\prime$ that\ncan help the learning algorithm get traction on the so-transformed space\nwhile providing a better trade-off between generalization and\napproximation than could have been achieved otherwise. Finding such\ntransformations is called *feature engineering*.\n\n\n## Cross-Validation\n<div id=\"ch:ml:sec:cv\"></div>\n\nIn the last section, we explored a stylized machine learning example\nto understand the issues of complexity in machine learning. However,\nto get an estimate of out-of-sample errors, we simply generated more\nsynthetic data. In practice, this is not an option, so we need to\nestimate these errors from the training set itself. This is what\ncross-validation does.  The simplest form of cross-validation is\nk-fold validation. For example, if $K=3$, then the training data is\ndivided into three sections wherein each of the three sections is used\nfor testing and the remaining two are used for training.  This is\nimplemented in Scikit-learn as in the following,\n\n\n```python\nimport numpy as np\nfrom sklearn.model_selection import KFold\ndata =np.array(['a',]*3+['b',]*3+['c',]*3) # example \nprint (data)\nkf = KFold(3)\nfor train_idx,test_idx in kf.split(data):\n   print (train_idx,test_idx)\n```\n\n    ['a' 'a' 'a' 'b' 'b' 'b' 'c' 'c' 'c']\n    [3 4 5 6 7 8] [0 1 2]\n    [0 1 2 6 7 8] [3 4 5]\n    [0 1 2 3 4 5] [6 7 8]\n\n\n In the code above, we construct a sample data array and then see\nhow `KFold` splits it up into indicies for training and testing, respectively.\nNotice that there are no duplicated elements in each row between training and\ntesting indicies. To examine the elements of the data set in each category, we simply\nuse each of the indicies as in the following,\n\n\n```python\nfor train_idx,test_idx in kf.split(data):\n   print('training', data[ train_idx ])\n   print('testing' , data[ test_idx ])\n```\n\n    training ['b' 'b' 'b' 'c' 'c' 'c']\n    testing ['a' 'a' 'a']\n    training ['a' 'a' 'a' 'c' 'c' 'c']\n    testing ['b' 'b' 'b']\n    training ['a' 'a' 'a' 'b' 'b' 'b']\n    testing ['c' 'c' 'c']\n\n\n This shows how each group is used in turn for training/testing. There\nis no random shuffling of the data unless the `shuffle` keyword argument is\ngiven.  The error over the test set is the *cross-validation error*. The idea is\nto postulate models of differing complexity and then pick the one with the best\ncross-validation error. For example, suppose we had the following sine wave\ndata,\n\n\n```python\nxi = np.linspace(0,1,30)\nyi = np.sin(2*np.pi*xi)\n```\n\n and we want to fit this with polynomials of increasing order.\n\n\n```python\nkf = KFold(4)\nfig,axs=subplots(2,2,sharex=True,sharey=True)\ndeg = 1 # polynomial degree\nfor ax,(train_idx,test_idx) in zip(axs.flat,kf.split(xi)):\n    _=ax.plot(xi,yi,xi[train_idx],yi[train_idx],'ok',color='k')\n    p = np.polyfit(xi[train_idx],yi[train_idx],deg)\n    pval = np.polyval(p,xi)\n    _=ax.plot(xi,pval,'--k')\n    error = np.mean((pval[test_idx]-yi[test_idx])**2)\n    _=ax.set_title('degree=%d;error=%3.3g'%(deg,error))\n    _=ax.fill_between(xi[test_idx],pval[test_idx],yi[test_idx],color='gray',alpha=.8)\n\nfig.savefig('fig-machine_learning/learning_theory_003.png')\n```\n\n<!-- dom:FIGURE: [fig-machine_learning/learning_theory_003.png, width=500 frac=0.85] This shows the folds and errors for the linear model. The shaded areas show the errors in each respective test set (i.e, *cross-validation scores*) for the linear model. <div id=\"fig:learning_theory_003\"></div> -->\n<!-- begin figure -->\n<div id=\"fig:learning_theory_003\"></div>\n\n<p>This shows the folds and errors for the linear model. The shaded areas show the errors in each respective test set (i.e, <em>cross-validation scores</em>) for the linear model.</p>\n\n\n<!-- end figure -->\n\n\n[Figure](#fig:learning_theory_003) shows the individual folds in each\npanel.  The circles represent the training data. The diagonal line is\nthe fitted polynomial. The gray shaded areas indicate the regions of\nerrors between the fitted polynomial and the held-out testing data.\nThe larger the gray area, the bigger the cross-validation errors,\nas are reported in the title of each frame.\n\n\n```python\nfig,axs=subplots(2,2,sharex=True,sharey=True)\ndeg = 2 # polynomial degree\nfor ax,(train_idx,test_idx) in zip(axs.flat,kf.split(xi)):\n    _=ax.plot(xi,yi,xi[train_idx],yi[train_idx],'ok',color='k')\n    p = np.polyfit(xi[train_idx],yi[train_idx],deg)\n    pval = np.polyval(p,xi)\n    _=ax.plot(xi,pval,'--k')\n    error = np.mean((pval[test_idx]-yi[test_idx])**2)\n    _=ax.set_title('degree=%d;error=%3.3g'%(deg,error))\n    _=ax.fill_between(xi[test_idx],pval[test_idx],yi[test_idx],color='gray',alpha=.8)\n\nfig.savefig('fig-machine_learning/learning_theory_004.png')\n```\n\n<!-- dom:FIGURE: [fig-machine_learning/learning_theory_004.png, width=500 frac=0.85] This shows the folds and errors as in [Figure](#fig:learning_theory_002) and [fig:learning_theory_003](#fig:learning_theory_003). The shaded areas show the errors in each respective test set for the quadratic model. <div id=\"fig:learning_theory_004\"></div> -->\n<!-- begin figure -->\n<div id=\"fig:learning_theory_004\"></div>\n\n<p>This shows the folds and errors as in [Figure](#fig:learning_theory_002) and [fig:learning_theory_003](#fig:learning_theory_003). The shaded areas show the errors in each respective test set for the quadratic model.</p>\n\n\n<!-- end figure -->\n\n\n```python\nkf = KFold(4)\nfig,axs=subplots(2,2,sharex=True,sharey=True)\ndeg = 3 # polynomial degree\nfor ax,(train_idx,test_idx) in zip(axs.flat,kf.split(xi)):\n    _=ax.plot(xi,yi,xi[train_idx],yi[train_idx],'ok',color='k')\n    p = np.polyfit(xi[train_idx],yi[train_idx],deg)\n    pval = np.polyval(p,xi)\n    _=ax.plot(xi,pval,'--k')\n    error = np.mean((pval[test_idx]-yi[test_idx])**2)\n    _=ax.set_title('degree=%d;error=%3.3g'%(deg,error))\n    _=ax.fill_between(xi[test_idx],pval[test_idx],yi[test_idx],color='gray',alpha=.8)\n\nfig.savefig('fig-machine_learning/learning_theory_005.png')\n```\n\n<!-- dom:FIGURE: [fig-machine_learning/learning_theory_005.png, width=500 frac=0.85] This shows the folds and errors. The shaded areas show the errors in each respective test set for the cubic model. <div id=\"fig:learning_theory_005\"></div> -->\n<!-- begin figure -->\n<div id=\"fig:learning_theory_005\"></div>\n\n<p>This shows the folds and errors. The shaded areas show the errors in each respective test set for the cubic model.</p>\n\n\n<!-- end figure -->\n\n\nAfter reviewing the last four figures and averaging the cross-validation\nerrors, the one with the least average error is declared the winner. Thus, cross-validation provides a method of using a\nsingle data set to make claims about unseen out-of-sample data insofar as the\nmodel with the best complexity can be determined.  The entire process to\ngenerate the above figures can be captured using `cross_val_score` as shown for\nthe linear regression (compare the output with the values in the titles in each\npanel of  [Figure](#fig:learning_theory_003)),\n\n\n```python\nfrom sklearn.metrics import  make_scorer, mean_squared_error\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.linear_model import LinearRegression\nXi = xi.reshape(-1,1) # refit column-wise\nYi = yi.reshape(-1,1)\nlf = LinearRegression()\nscores = cross_val_score(lf,Xi,Yi,cv=4,\n                         scoring=make_scorer(mean_squared_error))\nprint(scores)\n```\n\n    [0.3554451  0.33131438 0.50454257 0.45905672]\n\n\n**Programming Tip.**\n\nThe `make_scorer` function is a wrapper that enables `cross_val_score` to\ncompute scores from the given estimator's output.\n\n\n\n The process can be further automated by using a pipeline as\nin the following,\n\n\n```python\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import PolynomialFeatures\npolyfitter = Pipeline([('poly', PolynomialFeatures(degree=3)),\n                       ('linear', LinearRegression())])\npolyfitter.get_params()\n```\n\n\n\n\n    {'memory': None,\n     'steps': [('poly',\n       PolynomialFeatures(degree=3, include_bias=True, interaction_only=False,\n                          order='C')),\n      ('linear',\n       LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False))],\n     'verbose': False,\n     'poly': PolynomialFeatures(degree=3, include_bias=True, interaction_only=False,\n                        order='C'),\n     'linear': LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False),\n     'poly__degree': 3,\n     'poly__include_bias': True,\n     'poly__interaction_only': False,\n     'poly__order': 'C',\n     'linear__copy_X': True,\n     'linear__fit_intercept': True,\n     'linear__n_jobs': None,\n     'linear__normalize': False}\n\n\n\n The  `Pipeline` object is a way of stacking standard steps\ninto one big estimator, while respecting the usual `fit` and `predict`\ninterfaces. The output of the `get_params` function contains the\npolynomial degrees we previously looped over to create [Figure](#fig:learning_theory_003), etc. We will use these named parameters\nin the next code block.  To do this automatically using this\n`polyfitter` estimator, we need the Grid Search Cross Validation\nobject, `GridSearchCV`.  The next step is to use this to create the\ngrid of parameters we want to loop over as in the following,\n\n\n```python\nfrom sklearn.model_selection import GridSearchCV\ngs=GridSearchCV(polyfitter,{'poly__degree':[1,2,3]},\n                cv=4,return_train_score=True)\n```\n\n The `gs` object will loop over the polynomial degrees up to\ncubic using four-fold cross validation `cv=4`, like we did manually\nearlier. The `poly__degree` item comes from the previous `get_params`\ncall.  Now, we just apply the usual `fit` method on the training data,\n\n\n```python\n_=gs.fit(Xi,Yi)\ngs.cv_results_\n```\n\n    /home/unpingco/.conda/envs/pypsml2E/lib/python3.7/site-packages/sklearn/model_selection/_search.py:813: DeprecationWarning: The default of the `iid` parameter will change from True to False in version 0.22 and will be removed in 0.24. This will change numeric results when test-set sizes are unequal.\n      DeprecationWarning)\n\n\n\n\n\n    {'mean_fit_time': array([0.00091416, 0.00077647, 0.00073195]),\n     'std_fit_time': array([2.79066700e-04, 8.56323359e-05, 1.23943154e-04]),\n     'mean_score_time': array([0.00059962, 0.00061661, 0.00051814]),\n     'std_score_time': array([7.37571294e-05, 1.36809826e-04, 3.01594202e-05]),\n     'param_poly__degree': masked_array(data=[1, 2, 3],\n                  mask=[False, False, False],\n            fill_value='?',\n                 dtype=object),\n     'params': [{'poly__degree': 1}, {'poly__degree': 2}, {'poly__degree': 3}],\n     'split0_test_score': array([ -2.03118491, -68.54947351,  -1.64899934]),\n     'split1_test_score': array([-1.38557769, -3.20386236,  0.81372823]),\n     'split2_test_score': array([ -7.82417707, -11.8740862 ,   0.47246476]),\n     'split3_test_score': array([ -3.21714294, -60.70054797,   0.14328163]),\n     'mean_test_score': array([ -3.4874447 , -36.06830421,  -0.07906481]),\n     'std_test_score': array([ 2.47972092, 29.1121604 ,  0.975868  ]),\n     'rank_test_score': array([2, 3, 1], dtype=int32),\n     'split0_train_score': array([0.52652515, 0.93434227, 0.99177894]),\n     'split1_train_score': array([0.5494882 , 0.60357784, 0.99154288]),\n     'split2_train_score': array([0.54132528, 0.59737218, 0.99046089]),\n     'split3_train_score': array([0.57837263, 0.91061274, 0.99144127]),\n     'mean_train_score': array([0.54892781, 0.76147626, 0.99130599]),\n     'std_train_score': array([0.01888775, 0.16123462, 0.00050307])}\n\n\n\n the scores shown correspond to the cross validation scores\nfor each of the parameters (e.g., polynomial degrees) using four-fold\ncross-validation.  Note that the higher scores are better here and\nthe cubic polynomial is best, as we observed earlier. The default\n$R^2$ metric is used for the scoring in this case as opposed to\nmean-squared-error. The validation results of this pipeline for the\nquadratic fit are shown in [Figure](#fig:learning_theory_004), and\nfor the cubic fit, in [Figure](#fig:learning_theory_005). This can\nbe changed by passing the\n`scoring=make_scorer(mean_squared_error)` keyword argument to\n`GridSearchCV`.  There is also `RandomizedSearchCV` that does\ndoes not necessarily evaluate every point on the grid and\ninstead randomly samples the grid according to an input\nprobability distribution. This is very useful for a large number\nof hyper-parameters.\n\n## Bias and Variance\n\n\nConsidering average error in terms of in-samples\nand out-samples depends on a particular training data set. What we\nwant is a concept that captures the performance of the estimator \nfor *all* possible training data. For example, our ultimate\nestimator, $\\hat{f}$ is derived from a particular set of training data\n($\\mathcal{D}$) and is thus denoted, $\\hat{f}_{\\mathcal{D}}$. This makes the\nout-of-sample error explicitly, $E_{\\texttt{out}}(\\hat{f}_{\\mathcal{D}})$.  To\neliminate the dependence on a particular set of training data set, we have to\ncompute the expectation across all training data sets,\n\n$$\n\\mathbb{E}_{\\mathcal{D}}E_{\\texttt{out}}(\\hat{f}_{\\mathcal{D}})= \\texttt{bias}+\\texttt{var}\n$$\n\n where\n\n$$\n\\texttt{bias}(x)= (\\overline{\\hat{f}}(x)-f(x))^2\n$$\n\n and\n\n$$\n\\texttt{var}(x)= \\mathbb{E}_{\\mathcal{D}}(\\hat{f}_{\\mathcal{D}}(x)-\\overline{\\hat{f}}(x))^2\n$$\n\n and where $\\overline{\\hat{f}}$ is the mean of all estimators for all\ndata sets. There is nothing to say that such a mean is an estimator that could\nhave arisen from any *particular* training data, however. It just implies that\nfor any particular point $x$, the mean of the values of all the estimators is\n$\\overline{\\hat{f}}(x)$.  Therefore, $\\texttt{bias}$ captures the sense\nthat, even if all possible data were presented to the learning method, it\nwould still differ from the target function by this amount.  On the other\nhand, $\\texttt{var}$ shows the variation in the final hypothesis, depending\non the training data set, notwithstanding the target function.  Thus, the\ntension between approximation and generalization is captured by these two\nterms.  For example, suppose there is only one hypothesis. Then,\n$\\texttt{var}=0$ because there can be no variation due to a particular set\nof training data because no matter what that training data is, the learning\nmethod always selects the one and only hypothesis. In this case, the bias\ncould be very large, because there is no opportunity for the learning method\nto alter the hypothesis due to the training data, and the method can only\never pick the single hypothesis!\n\nLet's construct an example to make this concrete. Suppose we have a hypothesis\nset consisting of all linear regressions without an intercept term,  $h(x)=a\nx$. The training data consists of only two points $\\left\\{(x_i,\\sin(\\pi\nx_i))\\right\\}_{i=1}^2$ where $x_i$ is drawn uniformly from the interval\n$[-1,1]$. From the section [ch:stats:sec:reg](#ch:stats:sec:reg) on linear regression, we know that\nthe solution for $a$ is the following,\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:sola\"></div>\n\n$$\n\\begin{equation}\na = \\frac{\\mathbf{x}^T \\mathbf{y}}{\\mathbf{x}^T \\mathbf{x}}\n\\label{eq:sola} \\tag{1}\n\\end{equation}\n$$\n\n where $\\mathbf{x}=[x_1,x_2]$ and $\\mathbf{y}=[y_1,y_2]$. The\n$\\overline{\\hat{f}}(x)$ represents the solution over all possible sets\nof training data for a fixed $x$. The following code shows how to\nconstruct the training data,\n\n\n```python\nfrom scipy import stats\ndef gen_sindata(n=2):\n    x=stats.uniform(-1,2) # define random variable\n    v = x.rvs((n,1))      # generate sample\n    y = np.sin(np.pi*v)   # use sample for sine\n    return (v,y)\n```\n\n Again, using Scikit-learn's `LinearRegression` object, we\ncan compute the $a$ parameter. Note that we have to set\n`fit_intercept=False` keyword to suppress the default automatic\nfitting of the intercept.\n\n\n```python\nlr = LinearRegression(fit_intercept=False)\nlr.fit(*gen_sindata(2))\nlr.coef_\n```\n\n\n\n\n    array([[0.24974914]])\n\n\n\n<!-- *foo* -->\n\n**Programming Tip.**\n\nNote that we designed `gen_sindata` to return a tuple to use the automatic\nunpacking feature of Python functions in `lr.fit(*gen_sindata())`.  In other\nwords, using the asterisk notation means we don't have to separately assign the\noutputs of `gen_sindata` before using them for `lr.fit`.\n\n\n\n<!-- dom:FIGURE: [fig-machine_learning/learning_theory_006.png, width=500 frac=0.75] For a two-element training set consisting of the points shown, the line is the best fit over the hypothesis set, $h(x)=a x$. <div id=\"fig:learning_theory_006\"></div> -->\n<!-- begin figure -->\n<div id=\"fig:learning_theory_006\"></div>\n\n<p>For a two-element training set consisting of the points shown, the line is the best fit over the hypothesis set, $h(x)=a x$.</p>\n\n\n<!-- end figure -->\n\n\n```python\nlr = LinearRegression(fit_intercept=False)\nxi=np.linspace(-1,1,50)\nyi= np.sin(np.pi*xi)\nxg,yg = gen_sindata()\nfig,ax=subplots()\n_=lr.fit(xg,yg)\n_=ax.plot(xi,yi,'--k',label='target')\n_=ax.plot(xg,yg,'o',ms=10,color='gray')\n_=ax.plot(xi,lr.predict(xi.reshape(-1,1)),color='k',label='best fit')\n_=ax.set_title('$a=%3.3g$'%(lr.coef_),fontsize=24)\n_=ax.set_xlabel(r'$x$',fontsize=28)\n_=ax.set_ylabel(r'$y$',fontsize=28)\n_=ax.legend(fontsize=18,loc=0)\nfig.tight_layout()\nfig.savefig('fig-machine_learning/learning_theory_006.png')\n```\n\n In this case, $\\overline{\\hat{f}}(x) = \\overline{a}x$, where\n$\\overline{a}$ the the expected value of the parameter over *all* possible\ntraining data sets.  Using our knowledge of probability, we can write this out\nexplicitly as the following,\n\n$$\n\\overline{a} = \\mathbb{E}\\left(\\frac{x_1\\sin(\\pi x_1)+ x_2\\sin(\\pi x_2) }{x_1^2+x_2^2}\\right)\n$$\n\n where $\\mathbf{x}=[x_1,x_2]$ and $\\mathbf{y}=[\\sin(\\pi x_1),\\sin(\\pi\nx_2)]$ in Equation ([1](#eq:sola)). However, computing this expectation\nanalytically is hard, but for this specific situation, $\\overline{a} \\approx\n1.43$. To get this value using simulation, we just loop over the process,\ncollect the outputs, and the average them as in the following,\n\n\n```python\na_out=[] # output container\nfor i in range(100):\n    _=lr.fit(*gen_sindata(2)) \n    a_out.append(lr.coef_[0,0])\n\nnp.mean(a_out) # approx 1.43\n```\n\n\n\n\n    1.5476180748170179\n\n\n\n<!-- * -->\n\n Note that you may have to loop over many more iterations to get\nclose to the purported value. The $\\texttt{var}$ requires the variance of $a$,\n\n$$\n\\texttt{var}(x) = \\mathbb{E}((a-\\overline{a})x)^2 = x^2 \\mathbb{E}(a-\\overline{a})^2 \\approx 0.71 x^2\n$$\n\n The $\\texttt{bias}$ is the following,\n\n$$\n\\texttt{bias}(x) = (\\sin(\\pi x)-\\overline{a}x)^2\n$$\n\n [Figure](#fig:learning_theory_007) shows the $\\texttt{bias}$,\n$\\texttt{var}$, and mean-squared-error for this problem. Notice that there is\nzero bias and zero variance when $x=0$. This is because the learning method\ncannot help but get that correct because all the hypotheses happen to match the\nvalue of the target function at that point! Likewise, the $\\texttt{var}$ is\nzero because all possible pairs, which constitute the training data, are fitted\nthrough zero because $h(x)=a x$ has no choice but to go through zero. The\nerrors are worse at the end points. As we discussed in our statistics chapter,\nthose points have the most leverage against the hypothesized models and result\nin the worst errors. Notice that reducing the edge-errors depends on getting\nexactly those points near the edges as training data. The sensitivity to a\nparticular data set is reflected in this behavior.\n\n<!-- dom:FIGURE: [fig-machine_learning/learning_theory_007.png, width=500 frac=0.8] These curves decompose the mean squared error into its constituent bias and variance for this example.  <div id=\"fig:learning_theory_007\"></div> -->\n<!-- begin figure -->\n<div id=\"fig:learning_theory_007\"></div>\n\n<p>These curves decompose the mean squared error into its constituent bias and variance for this example.</p>\n\n\n<!-- end figure -->\n\n\n```python\nfig,ax=subplots()\nfig.set_size_inches((8,5))\n_=ax.plot(xi,(1.43*xi-yi)**2,'--k',label='bias(x)')\n_=ax.plot(xi,0.71*(xi)**2,':k',label='var(x)',lw=3.)\n_=ax.plot(xi,(1.43*xi-yi)**2+0.71*(xi)**2,color='k',lw=4,label='MSE')\n_=ax.legend(fontsize=18,loc=0)\n_=ax.set_ylabel('Mean Squared Error (MSE)',fontsize=16)\n_=ax.set_xlabel('x',fontsize=18)\n_=ax.tick_params(labelsize='x-large')\nfig.tight_layout()\nfig.savefig('fig-machine_learning/learning_theory_007.pdf')\n```\n\nWhat if we had more than two points in the training data? What would happen to\n$\\texttt{var}$ and $\\texttt{bias}$?  Certainly, the $\\texttt{var}$ would\ndecrease because it would be harder and harder to generate training data sets\nthat would be substantially different from each other. The bias would also\ndecrease because more points in the training data means better approximation of\nthe sine function over the interval. What would happen if we changed the\nhypothesis set to include more complex polynomials?  As we have already seen\nwith our polynomial regression earlier in this chapter, we would see the same\noverall effect as here, but with relatively smaller absolute errors and the\nsame edge effects we noted earlier. \n\n## Learning Noise\n\nWe have thus far not considered the effect of noise in our analysis\nof learning. The following example should help resolve this. Let's suppose\nwe have the following scalar target function,\n\n$$\ny(\\mathbf{x})=\\mathbf{w}_o^T \\mathbf{x} + \\eta\n$$\n\n where $\\eta \\sim \\mathcal{N}(0,\\sigma^2)$ is an additive noise term\nand $\\mathbf{w}, \\mathbf{x} \\in \\mathbb{R}^d$. Furthermore, we have $n$\nmeasurements of $y$. This means the training set consists of $\\lbrace\n(\\mathbf{x}_i,y_i) \\rbrace_{i=1}^n$. Stacking the measurements together into a\nvector format,\n\n$$\n\\mathbf{y}=\\mathbf{X} \\mathbf{w}_o + \\boldsymbol{\\eta}\n$$\n\n with $\\mathbf{y},\\boldsymbol{\\eta}\\in\\mathbb{R}^n$,$\\mathbf{w}_o\\in\n\\mathbb{R}^d$ and $\\mathbf{X}$ contains $\\mathbf{x}_i$ as columns.  The\nhypothesis set consists of all linear models,\n\n$$\nh(\\mathbf{w},\\mathbf{x}) = \\mathbf{w}^T \\mathbf{x}\n$$\n\n We need to the learn the correct $\\mathbf{w}$ from the\nhypothesis set given the training data. So far, this is the usual\nsetup for the problem, but how does the noise factor play to this? In\nour usual situation, the training set consists of randomly chosen\nelements from a larger space. In this case, that would be the same as\ngetting random sets of $\\mathbf{x}_i$ vectors. That still happens in\nthis case, but the problem is that even if the same $\\mathbf{x}_i$\nappears twice, it will not be associated with the same $y$ value due\nthe additive noise coming from $\\eta$. To keep this simple, we assume\nthat there is a fixed set of $\\mathbf{x}_i$ vectors and that we get\nall of them in the training set.  For every specific training set, we\nknow how to solve for the MMSE from our earlier statistics work,\n\n$$\n\\mathbf{w} =  (\\mathbf{X}^T \\mathbf{X})^{-1} \\mathbf{X}^T \\mathbf{y}\n$$\n\nGiven this setup, what is the in-sample mean-squared-error? Because\nthis is the MMSE solution, we know from our study of the associated \northogonality of such systems that we have,\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:Ein\"></div>\n\n$$\n\\begin{equation}\nE_{\\texttt{in}}=\\lVert \\mathbf{y} \\rVert^2 - \\lVert \\mathbf{X w} \\rVert^2 \n\\label{eq:Ein} \\tag{2}\n\\end{equation}\n$$\n\n where our best hypothesis, $\\mathbf{h} = \\mathbf{X w}$. Now, we want\nto compute the expectation of this over the distribution of $\\eta$.  For\ninstance, for the first term, we want to compute,\n\n$$\n\\mathbb{E} \\lvert \\mathbf{y} \\rvert^2 = \\frac{1}{n} \\mathbb{E} (\\mathbf{y}^T \\mathbf{y}) = \\frac{1}{n} \\Tr \\: \\mathbb{E} (\\mathbf{y} \\mathbf{y}^T)\n$$\n\n where $\\Tr$ is the matrix trace operator (i.e., sum of the diagonal\nelements). Because each $\\eta$ are independent, we have\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:eyy\"></div>\n\n$$\n\\begin{equation}\n\\Tr \\: \\mathbb{E} (\\mathbf{y} \\mathbf{y}^T) = \\Tr \\: \\mathbf{X} \\mathbf{w}_o \\mathbf{w}_o^T \\mathbf{X}^T + \\sigma^2 \\Tr \\: \\mathbf{I} = \\Tr \\: \\mathbf{X} \\mathbf{w}_o \\mathbf{w}_o^T \\mathbf{X}^T + n \\sigma^2\n\\label{eq:eyy} \\tag{3}\n\\end{equation}\n$$\n\n where $\\mathbf{I}$ is the $n \\times n$ identity matrix. For the\nsecond term in Equation ([2](#eq:Ein)), we have\n\n$$\n\\lvert\\mathbf{X w} \\rvert^2 = \\Tr \\: \\mathbf{X w}\\mathbf{w}^T \\mathbf{X}^T = \\Tr\\: \\mathbf{X} (\\mathbf{X}^T \\mathbf{X})^{-1} \\mathbf{X}^T \\mathbf{y} \\mathbf{y}^T \\mathbf{X} (\\mathbf{X}^T \\mathbf{X})^{-1} \\mathbf{X}^T\n$$\n\n The expectation of this is the following,\n\n<!-- Equation labels as ordinary links -->\n<div id=\"_auto1\"></div>\n\n$$\n\\begin{equation}\n\\mathbb{E} \\lvert \\mathbf{X w} \\rvert^2 = \\Tr \\:  \\mathbf{X} (\\mathbf{X}^T \\mathbf{X})^{-1} \\mathbf{X}^T \\mathbb{E}(\\mathbf{y} \\mathbf{y}^T) \\mathbf{X} (\\mathbf{X}^T \\mathbf{X})^{-1} \\mathbf{X}^T\n\\label{_auto1} \\tag{4}\n\\end{equation}\n$$\n\n which, after substituting in Equation ([3](#eq:eyy)), yields,\n\n<!-- Equation labels as ordinary links -->\n<div id=\"_auto2\"></div>\n\n$$\n\\begin{equation}\n\\mathbb{E} \\lvert \\mathbf{X w} \\rvert^2 = \\Tr \\:  \\mathbf{X} \\mathbf{w}_o \\mathbf{w}_o^T \\mathbf{X}^T + \\sigma^2 d\n\\label{_auto2} \\tag{5}\n\\end{equation}\n$$\n\n Next, assembling Equation ([2](#eq:Ein)) from this and Equation ([3](#eq:eyy)) gives,\n\n<!-- Equation labels as ordinary links -->\n<div id=\"_auto3\"></div>\n\n$$\n\\begin{equation}\n\\mathbb{E}(E_{\\texttt{in}})=\\frac{1}{n}E_{\\texttt{in}}=\\sigma^2 \\left(1-\\frac{d}{n}\\right)\n\\label{_auto3} \\tag{6}\n\\end{equation}\n$$\n\n which provides an explicit relationship between the noise power,\n$\\sigma^2$, the complexity of the method ($d$) and the number of training\nsamples ($n$).  This is very illustrative because it reveals the ratio $d/n$,\nwhich is a statement of the trade-off between model complexity and in-sample\ndata size. From our analysis of the VC-dimension, we already know that there is\na complicated bound that represents the penalty for complexity, but this\nproblem is unusual in that we can actually derive an expression for this\nwithout resorting to bounding arguments. Furthermore, this result shows, that\nwith a very large number of training examples ($n \\rightarrow \\infty$), the\nexpected in-sample error approaches $\\sigma^2$. Informally, this means that the\nlearning method cannot *generalize* from noise and thus can only reduce the\nexpected in-sample error by memorizing the data (i.e., $d \\approx n$).\n\nThe corresponding analysis for the expected out-of-sample error is similar, \nbut more complicated because we don't have the orthogonality condition. Also,\nthe out-of-sample data has different noise from that used to derive the weights,\n$\\mathbf{w}$. This results in extra cross-terms,\n\n<!-- Equation labels as ordinary links -->\n<div id=\"_auto4\"></div>\n\n$$\n\\begin{equation}\nE_{\\texttt{out}} = \\Tr \\Biggl( \\mathbf{X} \\mathbf{w}_o \\mathbf{w}_o^T \\mathbf{X}^T + \\boldsymbol{\\xi} \\boldsymbol{\\xi}^T + \\mathbf{X} \\mathbf{w} \\mathbf{w}^T \\mathbf{X}^T - \\mathbf{X} \\mathbf{w} \\mathbf{w}_o^T \\mathbf{X}^T \\notag\n\\label{_auto4} \\tag{7}\n\\end{equation}\n$$\n\n<!-- Equation labels as ordinary links -->\n<div id=\"_auto5\"></div>\n\n$$\n\\begin{equation} \\\n                   - \\mathbf{X} \\mathbf{w}_o \\mathbf{w}^T \\mathbf{X}^T \\Biggr)\n\\label{_auto5} \\tag{8}\n\\end{equation}\n$$\n\n where we are using the $\\boldsymbol{\\xi}$ notation for the noise in the\nout-of-sample case, which is different from that in the in-sample case.\nSimplifying this leads to the following,\n\n<!-- Equation labels as ordinary links -->\n<div id=\"_auto6\"></div>\n\n$$\n\\begin{equation}\n\\mathbb{E}(E_{\\texttt{out}})=\\Tr\\: \\sigma^2 \\mathbf{I}  + \\sigma^2 \\mathbf{X}(\\mathbf{X}^T \\mathbf{X})^{-1} \\mathbf{X}^T\n\\label{_auto6} \\tag{9}\n\\end{equation}\n$$\n\n Then, assembling all of this gives,\n\n<!-- Equation labels as ordinary links -->\n<div id=\"eq:Eout\"></div>\n\n$$\n\\begin{equation}\n\\mathbb{E}(E_{\\texttt{out}}) = \\sigma^2 \\left(1+\\frac{d}{n}\\right) \n\\label{eq:Eout} \\tag{10}\n\\end{equation}\n$$\n\n which shows that even in the limit of large $n$, the expected\nout-of-sample error also approaches the noise power limit, $\\sigma^2$. This\nshows that memorizing the in-sample data (i.e., $d/n \\approx 1$) imposes a\nproportionate penalty on the out-of-sample performance (i.e., $\\mathbb{E}\nE_{\\texttt{out}} \\approx 2\\sigma^2$ when $\\mathbb{E}E_{\\texttt{in}} \\approx 0$\n).\n\nThe following code simulates this important example:\n\n\n```python\ndef est_errors(d=3,n=10,niter=100):\n    assert n>d\n    wo = np.matrix(arange(d)).T \n    Ein = list()\n    Eout = list()\n    # choose any set of vectors\n    X = np.matrix(np.random.rand(n,d)) \n    for ni in range(niter):\n        y = X*wo + np.random.randn(X.shape[0],1)\n        # training weights\n        w = np.linalg.inv(X.T*X)*X.T*y\n        h = X*w\n        Ein.append(np.linalg.norm(h-y)**2)\n        # out of sample error\n        yp = X*wo + np.random.randn(X.shape[0],1)\n        Eout.append(np.linalg.norm(h-yp)**2)\n    return (np.mean(Ein)/n,np.mean(Eout)/n)\n```\n\n**Programming Tip.**\n\nPython has an `assert` statement to make sure that certain entry conditions for\nthe variables in the function are satisfied.  It is a good practice to use\nreasonable assertions at entry and exit to improve the quality of code.\n\n\n\n The following runs the simulation for the given value of $d$.\n\n\n```python\nd=10\nxi = arange(d*2,d*10,d//2)\nei,eo=np.array([est_errors(d=d,n=n,niter=100) for n in xi]).T\n```\n\n which results in [Figure](#fig:learning_theory_008). This\nfigure shows the estimated expected in-sample and out-of-sample errors\nfrom our simulation compared with our  corresponding analytical\nresult. The heavy horizontal line shows the variance of the additive\nnoise $\\sigma^2=1$. Both these curves approach this asymptote because\nthe noise is the ultimate learning limit for this problem. For a given\ndimension $d$, even with an infinite amount of training data, the\nlearning method cannot generalize beyond the limit of the noise power.\nThus, the expected generalization error is\n$\\mathbb{E}(E_{\\texttt{out}})-\\mathbb{E}(E_{\\texttt{in}})=2\\sigma^2\\frac{d}{n}$.\n\n<!-- dom:FIGURE: [fig-machine_learning/learning_theory_008.png, width=500 frac=0.85]  The dots show the learning curves estimated from the simulation and the solid lines show the corresponding terms for our analytical result. The horizontal line shows the variance of the additive noise ($\\sigma^2=1$ in this case). Both the expected in-sample and out-of-sample errors asymptotically approach this line. <div id=\"fig:learning_theory_008\"></div> -->\n<!-- begin figure -->\n<div id=\"fig:learning_theory_008\"></div>\n\n<p>The dots show the learning curves estimated from the simulation and the solid lines show the corresponding terms for our analytical result. The horizontal line shows the variance of the additive noise ($\\sigma^2=1$ in this case). Both the expected in-sample and out-of-sample errors asymptotically approach this line.</p>\n\n\n<!-- end figure -->\n\n\n```python\nfig,ax=subplots()\nfig.set_size_inches((10,6))\n_=ax.plot(xi,ei,'ks',label=r'$\\hat{E}_{in}$',lw=3.,ms=10,alpha=.5)\n_=ax.plot(xi,eo,'ko',label=r'$\\hat{E}_{out}$',lw=3.,ms=10,alpha=.5)\n_=ax.plot(xi,(1-d/np.array(xi)),'--k',label=r'${E}_{in}$',lw=3)\n_=ax.plot(xi,(1+d/np.array(xi)),':k',label=r'${E}_{out}$')\n_=ax.hlines(1,xi.min(),xi.max(),lw=3)\n_=ax.set_xlabel('size of training set ($n$)',fontsize=22)\n_=ax.set_ylabel('MSE',fontsize=22)\n_=ax.legend(loc=4,fontsize=18)\n_=ax.set_title('dimension = %d'%(d),fontsize=22)\nfig.tight_layout()\nfig.savefig('fig-machine_learning/learning_theory_008.png')\n```\n", "meta": {"hexsha": "46ca18bbd1ce7f82112b900f8904fe3879f99805", "size": 508770, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapter/machine_learning/learning_theory.ipynb", "max_stars_repo_name": "derakding/Python-for-Probability-Statistics-and-Machine-Learning-2E", "max_stars_repo_head_hexsha": "9d12a298d43ae285d9549a79bb5544cf0a9b7516", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 224, "max_stars_repo_stars_event_min_datetime": "2019-05-07T08:56:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T15:50:41.000Z", "max_issues_repo_path": "chapter/machine_learning/learning_theory.ipynb", "max_issues_repo_name": "derakding/Python-for-Probability-Statistics-and-Machine-Learning-2E", "max_issues_repo_head_hexsha": "9d12a298d43ae285d9549a79bb5544cf0a9b7516", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-08-27T12:57:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-21T15:45:13.000Z", "max_forks_repo_path": "chapter/machine_learning/learning_theory.ipynb", "max_forks_repo_name": "derakding/Python-for-Probability-Statistics-and-Machine-Learning-2E", "max_forks_repo_head_hexsha": "9d12a298d43ae285d9549a79bb5544cf0a9b7516", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 73, "max_forks_repo_forks_event_min_datetime": "2019-05-25T07:15:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T00:22:37.000Z", "avg_line_length": 176.9019471488, "max_line_length": 176652, "alphanum_fraction": 0.8856673939, "converted": true, "num_tokens": 20289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13117321357238923, "lm_q2_score": 0.20946968133032526, "lm_q1q2_score": 0.027476811246083067}}
{"text": "# IOTA 101: Transactions\nA transaction is a smallest piece of data that can be broadcasted to the network. Each transaction consists of fixed 2673 trytes. Transactions (TXs) are basically of two types:\n* **Value TXs:** those transactions change ownership of IOTA tokens. Two possible states: spending TXs or receiving TXs\n* **Non-Value TXs:** those transactions include piece of data that can be broadcasted and read from the Tangle\n\nTransactions are broadcasted in an envelope called *Bundle*. Bundle may consist of multiple TXs. Bundle is processed by the Tangle as a single entity; meaning only the whole bundle is confirmed by the network (and all TXs within) or nothing. You have to prepare a bundle even if you broadcast single transaction only. Bundle is also described as *atomic* since every bundle includes all information needed to process it antonomously.\n\nEach transaction includes several fields, let's name the most important ones:\n* **`Value`:** Value can be *positive* number = receiving IOTA tokens, *negative* number = spending IOTA tokens or *zero* = broadcasting only piece of data\n* **`Address`:** It is IOTA address that is associated with the given transaction. *Value* indicates whether it is an address of a receiver or a sender\n* **`Tag`:** It is an user-defined tag that can be used for searching, etc.\n* **`SignatureMessageFragment`:** This is the most lenghty attribute (2187 trytes) and could include: *transaction signature* based on private key in case it is a spending TX or *piece of data (message)* in case it is non-value TX. Alternatively it can be also left blank (in case of non-value TXs)\n* **`TrunkTransaction` / `branchTransaction`:** Those two fields refer to some previous transactions in the Tangle (tips) that the given bundle is going to approve\n* **`Timestamp`:** TX timestamp. It is actually UNIX timestamp (UTC)\n\n\nA process of sending IOTA transaction can be summarized in 5 steps:\n* To create transation(s) with the given attributes: *value*, *address* and potentially also *tag* or *message*\n* To finalize a bundle that includes all transactions. Once the bundle is finalized no new transactions can be added. It basically means to generate a *bundle hash*\n* To search for two tips in the Tangle that you are going to validate. There is not a strict rule how to search them but it is generally recommended to leave it on a *tip selection algorithm* implemented on node's side \n* To do a *Proof-of-Work* for each transaction in the bundle. Result of POW is *Nonce* and *Transaction hash* stored with each transaction\n* Finally you need to *broadcast* the whole bundle to the network\n\n### A secret of a bundle\nThere is a secret to be shared. You have to understand one important thing. Bundle is a top level construct that link all related transactions under one entity however the bundle itself is not broadcasted in fact. You still broadcast \"only\" collection of individual transactions instead. All transactions are recognized to be part of a bundle by the IOTA protocol however any data peering is based on individual transactions (in trytes).\n\nIn other words, a bundle can be reconstructed anytime from a collection of transactions via fields `bundle hash`, `current index` and `last index`.\n\n## Non-value transactions\nLet's start with non-value transactions (meta transactions) first since they are a bit easier for starters.\n\n*Please note, the chapter is divided in two separate sections. In the first section, examples are really close to bare metal (still not too close:) to illustrate the whole process and describing implementation details wherever possible. It is also useful when you want to experiment with different settings at each step (hey \"non-existing tips\", looking at you).*\n\n*In the second section, IOTA-facing libraries are fully levearged since they are capable to hide all implementation details behind a curtain. Needless to say, if you are not interested in such details then you would probably like to start with the second section.*\n\n### Creating and broadcasting transaction in 5 steps (you want to understand the process)\n#### Create a transaction\nFirst of all let's create transactions (offline; in memory) and set main fields.\n\nBTW: `Timestamp` field is defined automatically by the IOTA-facing libraries in the process. It is important field while creating `bundle hash`.\n\nIn the examples within this chapter we are going to broadcast meta transactions (data only) to two different IOTA addresses.\n\n\n```python\nimport iota\nfrom datetime import datetime\nfrom pprint import pprint\n\nMySeed = b\"HGW9HB9LJPYUGVHNGCPLFKKPNZAIIFHZBDHKSGMQKFMANUBASSMSV9TAJSSMPRZZU9SFZULXKJ9YLAIUA\"\nTargetAddress1 = b\"CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\"\nTargetAddress2 = b\"CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\"\n\nNowIs = datetime.now() # get a actual date & time - just to have some meaningfull info\n\n# preparing transactions\npt = iota.ProposedTransaction(address = iota.Address(TargetAddress1), # 81 trytes long address\n                              message = iota.TryteString.from_unicode('Here comes a first message. Now is %s' % (NowIs)),\n                              tag     = iota.Tag(b'HRIBEK999IOTA999TUTORIAL'), # Up to 27 trytes\n                              value   = 0)\n\npt2 = iota.ProposedTransaction(address = iota.Address(TargetAddress2), # 81 trytes long address\n                               message = iota.TryteString.from_unicode('Here comes a second message. Now is %s' % (NowIs)),\n                               tag     = iota.Tag(b'HRIBEK999IOTA999TUTORIAL'), # Up to 27 trytes\n                               value   = 0)\n# besides the given attributes, library also adds a transaction timestamp\n\nprint(\"Created transaction objects:\\n\")\npprint(vars(pt))\nprint(\"\\n\")\npprint(vars(pt2))\n```\n\n    Created transaction objects:\n    \n    {'_legacy_tag': None,\n     'address': Address(b'CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9'),\n     'attachment_timestamp': 0,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 0,\n     'branch_transaction_hash': TransactionHash(b'999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'bundle_hash': None,\n     'current_index': None,\n     'hash': None,\n     'is_confirmed': None,\n     'last_index': None,\n     'message': TryteString(b'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA'),\n     'nonce': Nonce(b'999999999999999999999999999'),\n     'signature_message_fragment': None,\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1530080759,\n     'trunk_transaction_hash': TransactionHash(b'999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'value': 0}\n    \n    \n    {'_legacy_tag': None,\n     'address': Address(b'CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW'),\n     'attachment_timestamp': 0,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 0,\n     'branch_transaction_hash': TransactionHash(b'999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'bundle_hash': None,\n     'current_index': None,\n     'hash': None,\n     'is_confirmed': None,\n     'last_index': None,\n     'message': TryteString(b'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA'),\n     'nonce': Nonce(b'999999999999999999999999999'),\n     'signature_message_fragment': None,\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1530080759,\n     'trunk_transaction_hash': TransactionHash(b'999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'value': 0}\n\n\n#### Finalizing bundle\nOnce all individual transactions are created it is time to prepare and finalize the bundle. While preparing the bundle you need at least to specify list of prepared transaction(s). In case of non-value transactions it is quite straightforward process. However, it is a bit more complicated in case of value transactions - please see later.\n\nFinalizing the bundle consists of several tasks under the hood:\n* Each transaction is indexed. Attributes `current_index` / `last_index` are set\n* `Bundle hash` is generated (*Sponge function* + normalization) and assigned to each transaction\n* `signatureMessageFragment` is bascially copy of `message` field in case of non-value transactions\n* PyOTA library also checks whether the data in `message` field is larger than transaction allows (2187 trytes). If this is the case then it takes care of it and split your data into several transactions\n\n*Please note, finalizing the bundle also means you are no longer able to add new transactions to the bundle post the finalization process.*\n\nSimply put, `bundle hash` is a cryptographic \"fingerprint\" of all transactions in the bundle. It uniquely represents them and so as long as transactions are the same (incl their particular order) the `bundle hash` is also the same.\n\n$$BundleHash = fce(address, value, legacy tag, timestamp, current index, last index)$$\n\nYou may be wondering what is a difference between `tag` and `legacy_tag`. `Tag` includes actualy the tag that was defined during the transaction creation. `Legacy_tag` is also based on it however it is modified during the normalization process while bundle hashing to be sure that `bundle hash` is can be securely used while TX signing. That's why the `bundle hash` is sometimes refered as `normalized bundle hash`.\n\nThe bundle refers to the first transaction in collection as `tail_transaction`. You can perceive `tail transaction` as an official representative of the whole bundle while checking for confirmation status, etc. Remember, the bundle is an atomic entity and so whatever is done to bundle it applies to ALL transactions within.\n\n\n```python\n# preparing bundle that consists of both transactions prepared in the previous example\npb = iota.ProposedBundle(transactions=[pt,pt2]) # list of prepared transactions is needed at least\n\n# generate bundle hash using sponge/absorb function + normalize bundle hash + copy bundle hash into each transaction / bundle is finalized\npb.finalize()\n\n#bundle is finalized, let's print it\nprint(\"\\nGenerated bundle hash: %s\" % (pb.hash))\nprint(\"\\nTail Transaction in the Bundle is a transaction #%s.\" % (pb.tail_transaction.current_index))\n        \nprint(\"\\nList of all transactions in the bundle:\\n\")\nfor txn in pb:\n    pprint(vars(txn))\n    print(\"\")\n\n```\n\n    \n    Generated bundle hash: TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADW\n    \n    Tail Transaction in the Bundle is a transaction #0.\n    \n    List of all transactions in the bundle:\n    \n    {'_legacy_tag': Tag(b'PVIBEK999IOTA999TUTORIAL999'),\n     'address': Address(b'CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9'),\n     'attachment_timestamp': 0,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 0,\n     'branch_transaction_hash': TransactionHash(b'999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'bundle_hash': BundleHash(b'TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADW'),\n     'current_index': 0,\n     'hash': None,\n     'is_confirmed': None,\n     'last_index': 1,\n     'message': TryteString(b'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA'),\n     'nonce': Nonce(b'999999999999999999999999999'),\n     'signature_message_fragment': Fragment(b'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1530080759,\n     'trunk_transaction_hash': TransactionHash(b'999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'value': 0}\n    \n    \n    {'_legacy_tag': None,\n     'address': Address(b'CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW'),\n     'attachment_timestamp': 0,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 0,\n     'branch_transaction_hash': TransactionHash(b'999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'bundle_hash': BundleHash(b'TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADW'),\n     'current_index': 1,\n     'hash': None,\n     'is_confirmed': None,\n     'last_index': 1,\n     'message': TryteString(b'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA'),\n     'nonce': Nonce(b'999999999999999999999999999'),\n     'signature_message_fragment': Fragment(b'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1530080759,\n     'trunk_transaction_hash': TransactionHash(b'999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'value': 0}\n    \n    \n\n\nAt this stage you can also see how does our finalized bundle look encoded in Trytes so far. It is also a proof that there is no bundle to be broadcasted itself, only list of transations matter.\n\n\n```python\nTrytes = pb.as_tryte_strings() # bundle as trytes\npprint(Trytes)\n\n```\n\n    [TransactionTrytes(b'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW999999999999999999999999999HRIBEK999IOTA999TUTORIAL999TFDCQZD99A99999999A99999999TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADW999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999HRIBEK999IOTA999TUTORIAL999999999999999999999999999999999999999999999999999999999'),\n     TransactionTrytes(b'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9999999999999999999999999999PVIBEK999IOTA999TUTORIAL999TFDCQZD99999999999A99999999TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADW999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999HRIBEK999IOTA999TUTORIAL999999999999999999999999999999999999999999999999999999999')]\n\n\n#### Selecting two tips\nAs mentioned earlier you need to find two tips that you are going to validate together with your bundle for a sake of network participation. This will be outsourced to an IOTA node and so it will be for the first time we interact with the network (via API call `get_transactions_to_approve`).\n\nThere is a `depth` parameter needed. It instructs a node how many milestones it should go in the past while confirming tips. The higher value the better to network however more resources needed. `Depth=3` is considered to be well-balanced compromise. Higher value than `depth=10` will probably throw an exception depending on node's configuration.\n\nIt should return two selected tips as `branch` and `trunk` transactions. Those transactions will be used while broadcasting the bundle.\n\n\n```python\napi = iota.Iota(\"https://nodes.thetangle.org:443\") # selecting IOTA node\n\ngta = api.get_transactions_to_approve(depth=3) # get tips to be approved by your bundle\npprint(gta)\n\n\n```\n\n    {'branchTransaction': TransactionHash(b'KQBDDBHWHVLQSJFENGWRBHIOULOMC9GXDW99ECMVFHZXGFZQJOXATSMDLYQJFBZCXA9IJ9SQUXAFZ9999'),\n     'duration': 1700,\n     'fieldName': 'F-Node Montabaur',\n     'fieldPublicId': '1bdeeb759f960554',\n     'fieldVersion': '0.1.6',\n     'trunkTransaction': TransactionHash(b'RRYDZLPS9IWCSWRROPQQJTKBRONOJNLUHVHFXFEOZAVGFEOUAHXWWHJSHAGWSSNSMWHN9SEYNBOEA9999')}\n\n\n#### Performin' POW\n*Proof of work* is a relatively simple cryptograhic puzzle to be solved. It represents energy-based costs of your transaction. It also helps to minimize risks of some attack vectors to the network.\n\nThis task can be also outsourced to IOTA nodes. In order to perform it you need *selected tips*, *finalized bundle* (in trytes) and also `Minimum Weight Magnitude` parameter. This parameter defines how diffciult the given cryptographic puzzle should be to be accepted by the network. As of now, you should set at least `min_weight_magnitude=14` in case of mainnet.\n\nPlease note, POW is performed per each transaction and so it can take some time. That's why it is not recommended to have more than 30 transactions in a bundle.\n\nOnce succesfully performed, the modified bundle (list of all transactions in trytes) is returned in order to be broadcasted.\n\nSpecifically:\n* Fields `nonce` and `transaction hash` are calculated per each transaction\n* `Trunk` and `Branch` tips are correctly mapped among transactions within the bundle. Check that `trunk` of the first TX refers to the second TX, etc.\n\n\n```python\nprint(\"Performing POW... Wait please...\\n\")\natt = api.attach_to_tangle(trunk_transaction=gta['trunkTransaction'], # first tip selected\n                           branch_transaction=gta['branchTransaction'], # second tip selected\n                           trytes=Trytes, # our finalized bundle in Trytes\n                           min_weight_magnitude=14) # MWMN\npprint(att)\n```\n\n    Performing POW... Wait please...\n    \n    {'duration': 12267,\n     'fieldName': 'iota-fn01.sairai.de',\n     'fieldPublicId': '45f52c5a2e829a00',\n     'fieldVersion': '0.1.6',\n     'trytes': [TransactionTrytes(b'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9999999999999999999999999999PVIBEK999IOTA999TUTORIAL999TFDCQZD99999999999A99999999TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADWNNNY9QAGVOOGTCIGBBEPIYISUZKNJYUQMROBTZARQVPHONNLQNQFAHTBNXMYWDFHAHMNRJ9URLKX99999RRYDZLPS9IWCSWRROPQQJTKBRONOJNLUHVHFXFEOZAVGFEOUAHXWWHJSHAGWSSNSMWHN9SEYNBOEA9999HRIBEK999IOTA999TUTORIAL999RLISAKGKE999999999L99999999QRZIERPEJFLKTIVKEBQIHJXTAX9'),\n                TransactionTrytes(b'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW999999999999999999999999999HRIBEK999IOTA999TUTORIAL999TFDCQZD99A99999999A99999999TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADWRRYDZLPS9IWCSWRROPQQJTKBRONOJNLUHVHFXFEOZAVGFEOUAHXWWHJSHAGWSSNSMWHN9SEYNBOEA9999KQBDDBHWHVLQSJFENGWRBHIOULOMC9GXDW99ECMVFHZXGFZQJOXATSMDLYQJFBZCXA9IJ9SQUXAFZ9999HRIBEK999IOTA999TUTORIAL999GDVSAKGKE999999999L99999999OOLRWTCMJMIQIAUVWBY9TVMZAJJ')]}\n\n\nYou can eventually also preview what specific fields have been modified using transaction objects. The bundle is ready to be broadcasted and so it also show you all fields/values that will be stored in the network.\n\n\n```python\n# show what has been broadcasted - hash transaction + nonce (POW)\nprint(\"Final bundle including POW and branch/trunk transactions:\\n\")\nfor t in att['trytes']:\n    pprint(vars(iota.Transaction.from_tryte_string(t)))\n    print(\"\")\n```\n\n    Final bundle including POW and branch/trunk transactions:\n    \n    {'_legacy_tag': Tag(b'PVIBEK999IOTA999TUTORIAL999'),\n     'address': Address(b'CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9'),\n     'attachment_timestamp': 1530081729891,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 12,\n     'branch_transaction_hash': TransactionHash(b'RRYDZLPS9IWCSWRROPQQJTKBRONOJNLUHVHFXFEOZAVGFEOUAHXWWHJSHAGWSSNSMWHN9SEYNBOEA9999'),\n     'bundle_hash': BundleHash(b'TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADW'),\n     'current_index': 0,\n     'hash': TransactionHash(b'SYDECKQB9BHWFUYOZMANREHOCXHCOPY9JCSZSNIZRNDJTZXHHSESCCLQOENGRVFLDMNXYAHHEWRDZ9999'),\n     'is_confirmed': None,\n     'last_index': 1,\n     'nonce': Nonce(b'QRZIERPEJFLKTIVKEBQIHJXTAX9'),\n     'signature_message_fragment': Fragment(b'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1530080759,\n     'trunk_transaction_hash': TransactionHash(b'NNNY9QAGVOOGTCIGBBEPIYISUZKNJYUQMROBTZARQVPHONNLQNQFAHTBNXMYWDFHAHMNRJ9URLKX99999'),\n     'value': 0}\n    \n    {'_legacy_tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'address': Address(b'CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW'),\n     'attachment_timestamp': 1530081719485,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 12,\n     'branch_transaction_hash': TransactionHash(b'KQBDDBHWHVLQSJFENGWRBHIOULOMC9GXDW99ECMVFHZXGFZQJOXATSMDLYQJFBZCXA9IJ9SQUXAFZ9999'),\n     'bundle_hash': BundleHash(b'TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADW'),\n     'current_index': 1,\n     'hash': TransactionHash(b'NNNY9QAGVOOGTCIGBBEPIYISUZKNJYUQMROBTZARQVPHONNLQNQFAHTBNXMYWDFHAHMNRJ9URLKX99999'),\n     'is_confirmed': None,\n     'last_index': 1,\n     'nonce': Nonce(b'OOLRWTCMJMIQIAUVWBY9TVMZAJJ'),\n     'signature_message_fragment': Fragment(b'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1530080759,\n     'trunk_transaction_hash': TransactionHash(b'RRYDZLPS9IWCSWRROPQQJTKBRONOJNLUHVHFXFEOZAVGFEOUAHXWWHJSHAGWSSNSMWHN9SEYNBOEA9999'),\n     'value': 0}\n    \n\n\n#### Broadcasting\nNow it is time to broadcast the given bundle to the network. List of all transations in trytes returned from the previous step is only thing needed.\n\nOnce succesfully broadcasted it returns the same input bundle as a confirmation.\n\n\n```python\nprint(\"Broadcasting transaction...\")\nres = api.broadcast_and_store(att['trytes'])\npprint(res)\n```\n\n    Broadcasting transaction...\n    {'trytes': [TransactionTrytes(b'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9999999999999999999999999999PVIBEK999IOTA999TUTORIAL999TFDCQZD99999999999A99999999TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADWNNNY9QAGVOOGTCIGBBEPIYISUZKNJYUQMROBTZARQVPHONNLQNQFAHTBNXMYWDFHAHMNRJ9URLKX99999RRYDZLPS9IWCSWRROPQQJTKBRONOJNLUHVHFXFEOZAVGFEOUAHXWWHJSHAGWSSNSMWHN9SEYNBOEA9999HRIBEK999IOTA999TUTORIAL999RLISAKGKE999999999L99999999QRZIERPEJFLKTIVKEBQIHJXTAX9'),\n                TransactionTrytes(b'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW999999999999999999999999999HRIBEK999IOTA999TUTORIAL999TFDCQZD99A99999999A99999999TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADWRRYDZLPS9IWCSWRROPQQJTKBRONOJNLUHVHFXFEOZAVGFEOUAHXWWHJSHAGWSSNSMWHN9SEYNBOEA9999KQBDDBHWHVLQSJFENGWRBHIOULOMC9GXDW99ECMVFHZXGFZQJOXATSMDLYQJFBZCXA9IJ9SQUXAFZ9999HRIBEK999IOTA999TUTORIAL999GDVSAKGKE999999999L99999999OOLRWTCMJMIQIAUVWBY9TVMZAJJ')]}\n\n\nYou can check the broadcasted bundle via The Tangle Explorer at any of the receiving addresses:\n* Target address 1: https://thetangle.org/address/CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\n* Target address 2: \nhttps://thetangle.org/address/CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\n\n### Creating and broadcasting transaction in a single call (you want send a transaction quickly)\nAs mentioned above, IOTA-facing libraries are able to encapsulate all implementation details and so you do not need to care of them anymore. It is usually based on *extended API calls* that were proposed to be included by IOTA Foundation to make developer's life easier (https://github.com/iotaledger/wiki/blob/master/api-proposal.md).\n\nEven if using extended API calls you can still slightly control a level of your involvement in the whole process. From almost no involvement and fully automatic (`send_transfer()`) to semi-manual approach discussed above.\n\n\n\nThere are some specifics you should consider while designing your app:\n* You are loosing a bit of control of individual steps of the process and you have to rely of some predefined parameters (tip selection algo, etc.)\n* If there is an exception raised during the process then you need to go back at beginning and restart the whole process again\n\nSo it is basically your call to decide what works best for you.\n\nNow back to our exercise. Here comes a code that basically broadcasts transactions in a single call (`send_transfer()`) and you do not have to care of any implemenation details that are hidden under the hood.\n\n\n```python\nimport iota\nfrom datetime import datetime\nfrom pprint import pprint\n\nMySeed = b\"HGW9HB9LJPYUGVHNGCPLFKKPNZAIIFHZBDHKSGMQKFMANUBASSMSV9TAJSSMPRZZU9SFZULXKJ9YLAIUA\"\nTargetAddress1 = b\"CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\"\nTargetAddress2 = b\"CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\"\n\nNowIs = datetime.now() # get a actual date & time - just to have some meaningfull info\n\n# preparing transactions\npt = iota.ProposedTransaction(address = iota.Address(TargetAddress1), # 81 trytes long address\n                              message = iota.TryteString.from_unicode('Here comes a first message. Now is %s' % (NowIs)),\n                              tag     = iota.Tag(b'HRIBEK999IOTA999TUTORIAL'), # Up to 27 trytes\n                              value   = 0)\n\npt2 = iota.ProposedTransaction(address = iota.Address(TargetAddress2), # 81 trytes long address\n                               message = iota.TryteString.from_unicode('Here comes a second message. Now is %s' % (NowIs)),\n                               tag     = iota.Tag(b'HRIBEK999IOTA999TUTORIAL'), # Up to 27 trytes\n                               value   = 0)\n# besides the given attributes, library also adds a transaction timestamp\n\n\napi = iota.Iota(\"https://nodes.thetangle.org:443\")\n\nprint(\"Preparing/Broadcasting... Wait please...\")\n# the whole process initiated in a single call\nFinalBundle = api.send_transfer(depth=3,\n                                transfers=[pt,pt2],\n                                min_weight_magnitude=14)['bundle'] # it returns a dictionary with a bundle object\n    \n#bundle is broadcasted, let's print it\nprint(\"\\nGenerated bundle hash: %s\" % (FinalBundle.hash))\nprint(\"\\nTail Transaction in the Bundle is a transaction #%s.\" % (FinalBundle.tail_transaction.current_index))\n        \nprint(\"\\nList of all transactions in the bundle:\\n\")\nfor txn in FinalBundle:\n    pprint(vars(txn))\n    print(\"\")\n```\n\n    Preparing/Broadcasting... Wait please...\n    \n    Generated bundle hash: AEFTRFKZLIFXSQCBLJOEDKYKPHSJD9UZFFAYVYELHKYVDRKXQKOKQTOCLBLCLEODRGZPUAWOXSFHJEPOW\n    \n    Tail Transaction in the Bundle is a transaction #0.\n    \n    List of all transactions in the bundle:\n    \n    {'_legacy_tag': Tag(b'ECIBEK999IOTA999TUTORIAL999'),\n     'address': Address(b'CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9'),\n     'attachment_timestamp': 1532100908930,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 3812798742493,\n     'branch_transaction_hash': TransactionHash(b'SCVPZOUXDBIV9AJBVEE9SRLWWJZIXRKWHFMI9HDNZ9D9YPRLAFVIJ9OJZQWUXMOTMCQRBTMM9CRK99999'),\n     'bundle_hash': BundleHash(b'AEFTRFKZLIFXSQCBLJOEDKYKPHSJD9UZFFAYVYELHKYVDRKXQKOKQTOCLBLCLEODRGZPUAWOXSFHJEPOW'),\n     'current_index': 0,\n     'hash': TransactionHash(b'SVZ99MALQGVFHPONJTHRPPLIFBJWJWJTEHOGWTFRPZGDSPDKEUCIWLGPNKEFXLAGXEODSBBETKBP99999'),\n     'is_confirmed': None,\n     'last_index': 1,\n     'nonce': Nonce(b'WRMXCTEXLGCMUZJOBSCMHNQD9VS'),\n     'signature_message_fragment': Fragment(b'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUAABRAWAUAEAVAABDBXAZADBUAUASAVABBUAUACBUA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1532100900,\n     'trunk_transaction_hash': TransactionHash(b'CVRWTIPJHU9DOIZUNMEIOCPPMITKILETO9QALYEZCULKRD9ALIUYYQFYWPJEMYGBSNS9WUAHGCHEZ9999'),\n     'value': 0}\n    \n    {'_legacy_tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'address': Address(b'CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW'),\n     'attachment_timestamp': 1532100903056,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 3812798742493,\n     'branch_transaction_hash': TransactionHash(b'XUBGHJCEBSJXQYQJHBFBCVLVFLAM9SXLDFJJRRQISEXJJXCMNCRDXJABTHZEDW9RZWBWALDXAQCRA9999'),\n     'bundle_hash': BundleHash(b'AEFTRFKZLIFXSQCBLJOEDKYKPHSJD9UZFFAYVYELHKYVDRKXQKOKQTOCLBLCLEODRGZPUAWOXSFHJEPOW'),\n     'current_index': 1,\n     'hash': TransactionHash(b'CVRWTIPJHU9DOIZUNMEIOCPPMITKILETO9QALYEZCULKRD9ALIUYYQFYWPJEMYGBSNS9WUAHGCHEZ9999'),\n     'is_confirmed': None,\n     'last_index': 1,\n     'nonce': Nonce(b'FXXJWXQEMJFJMNRIWULHJDPFVRI'),\n     'signature_message_fragment': Fragment(b'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUAABRAWAUAEAVAABDBXAZADBUAUASAVABBUAUACBUA99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1532100900,\n     'trunk_transaction_hash': TransactionHash(b'SCVPZOUXDBIV9AJBVEE9SRLWWJZIXRKWHFMI9HDNZ9D9YPRLAFVIJ9OJZQWUXMOTMCQRBTMM9CRK99999'),\n     'value': 0}\n    \n\n\nYou can check the broadcasted bundle via The Tangle Explorer at any of the receiving addresses:\n* Target address 1: https://thetangle.org/address/CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\n* Target address 2: \nhttps://thetangle.org/address/CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\n\nAnd to complete the picture here is addtional code that uses `prepare_transfer()` and `send_trytes()` combo.\n\n\n```python\nimport iota\nfrom datetime import datetime\nfrom pprint import pprint\n\nMySeed = b\"HGW9HB9LJPYUGVHNGCPLFKKPNZAIIFHZBDHKSGMQKFMANUBASSMSV9TAJSSMPRZZU9SFZULXKJ9YLAIUA\"\nTargetAddress1 = b\"CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\"\nTargetAddress2 = b\"CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\"\n\nNowIs = datetime.now() # get a actual date & time - just to have some meaningfull info\n\n# preparing transactions\npt = iota.ProposedTransaction(address = iota.Address(TargetAddress1), # 81 trytes long address\n                              message = iota.TryteString.from_unicode('Here comes a first message. Now is %s' % (NowIs)),\n                              tag     = iota.Tag(b'HRIBEK999IOTA999TUTORIAL'), # Up to 27 trytes\n                              value   = 0)\n\npt2 = iota.ProposedTransaction(address = iota.Address(TargetAddress2), # 81 trytes long address\n                               message = iota.TryteString.from_unicode('Here comes a second message. Now is %s' % (NowIs)),\n                               tag     = iota.Tag(b'HRIBEK999IOTA999TUTORIAL'), # Up to 27 trytes\n                               value   = 0)\n# besides the given attributes, library also adds a transaction timestamp\n\n\napi = iota.Iota(\"https://nodes.thetangle.org:443\")\n\n# Creating bundle, preparing inputs and finalizing bundle. It returns trytes of prepared TXs\nTrytes = api.prepare_transfer(transfers=[pt,pt2]) \n    \nprint(\"Almost prepared bundle - tips and POW are still missing\")\npprint(Trytes)\n    \nprint(\"\\nSearching for tips and performing POW... Wait please...\")\nResult = api.send_trytes(trytes=Trytes[\"trytes\"],\n                         depth=3) # Searching for tips, performing POW and broadcasting\n\nprint(\"Bundle was broadcasted.\")\n  \nprint(\"\\nFinal transactions were returned - including nonce (POW)\")\npprint(Result)\n```\n\n    Almost prepared bundle - tips and POW are still missing\n    {'trytes': [TransactionTrytes(b'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAXAUAEAUAABDBXAXADBYA9BSAXAYAWAWAZAYA99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW999999999999999999999999999HRIBEK999IOTA999TUTORIAL999JINQRZD99A99999999A99999999CMRQYFTKZ9DANXOBEBKCIX9UBEIAWJJYFOXXSASFGUHOESLINSHF9TYDKTH9YDYLPQHWIUY9HDF9GWLLC999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999HRIBEK999IOTA999TUTORIAL999999999999999999999999999999999999999999999999999999999'),\n                TransactionTrytes(b'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAXAUAEAUAABDBXAXADBYA9BSAXAYAWAWAZAYA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9999999999999999999999999999RTIBEK999IOTA999TUTORIAL999JINQRZD99999999999A99999999CMRQYFTKZ9DANXOBEBKCIX9UBEIAWJJYFOXXSASFGUHOESLINSHF9TYDKTH9YDYLPQHWIUY9HDF9GWLLC999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999HRIBEK999IOTA999TUTORIAL999999999999999999999999999999999999999999999999999999999')]}\n    \n    Searching for tips and performing POW... Wait please...\n    Bundle was broadcasted.\n    \n    Final transactions were returned - including nonce (POW)\n    {'trytes': [TransactionTrytes(b'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAXAUAEAUAABDBXAXADBYA9BSAXAYAWAWAZAYA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9999999999999999999999999999RTIBEK999IOTA999TUTORIAL999JINQRZD99999999999A99999999CMRQYFTKZ9DANXOBEBKCIX9UBEIAWJJYFOXXSASFGUHOESLINSHF9TYDKTH9YDYLPQHWIUY9HDF9GWLLCYLURVDFXJWJRPTUHGRXSW9RPMZKPWBQWSHSSHRKGSJMDMLTPTENNGDBMEOGKUXDPGKFYUHIRTBCPZ9999ALYKPSMJNIXJGKOVORRLEOWGUSERFODOQZFBAHRBHMGWKIJ9WOFOHJCJDTQQPICAKJM9JFIBJAHFZ9999HRIBEK999IOTA999TUTORIAL999HW9HHBHKE999999999L99999999DLOEWKSWVGN9CVDUKAXTTEDBGHR'),\n                TransactionTrytes(b'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAXAUAEAUAABDBXAXADBYA9BSAXAYAWAWAZAYA99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW999999999999999999999999999HRIBEK999IOTA999TUTORIAL999JINQRZD99A99999999A99999999CMRQYFTKZ9DANXOBEBKCIX9UBEIAWJJYFOXXSASFGUHOESLINSHF9TYDKTH9YDYLPQHWIUY9HDF9GWLLCALYKPSMJNIXJGKOVORRLEOWGUSERFODOQZFBAHRBHMGWKIJ9WOFOHJCJDTQQPICAKJM9JFIBJAHFZ9999WVJQWHI9JHXRIZETFPYTDCZ9LLSSDGUIVVUKSDEFDWUTYJSBNXFFOHTVLFXBENLYVZBARO9WNXOGZ9999HRIBEK999IOTA999TUTORIAL999JDXHHBHKE999999999L99999999ZVTKMTIN9VFLWYQCPBMZVRMBMJE')]}\n\n\nYou can check the broadcasted bundle via The Tangle Explorer at any of the receiving addresses:\n* Target address 1: https://thetangle.org/address/CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\n* Target address 2: \nhttps://thetangle.org/address/CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\n\n## Value transactions\nMeta transactions were discussed in the previous chapter. This chapter describes `value transactions` which are transactions that transfer IOTA tokens between IOTA addresses. Tokens are fully premined and so number of tokens in the network is given. So `transfering tokens` means changing their ownership only.\n\nWhile preparing a bundle with `value transations` it is important to distinguish three different transaction types within a bundle:\n* **Input TXs:** those are transactions that *deducting* (spending) value from address(es). Those transactions have negative `value` field. They usually refer to `senders`\n* **Output TXs:** those are transactions that *adding* (receiving) value to address(es). Those transactions have positive `value` field. They usually refer to `recipients`\n* **Unspent/change TX:** technically speaking it is also *output* transaction that *adding* value however it usually refers to `senders` and so it is better to consider it separated from other output TXs\n\nAll three types have to be part of each bundle otherwise you are under a risk of loosing IOTA tokens. In other words, each bundle should consists of at least one `input` TX, one `output` TX and one `unspent` TX. Total balance of the bundle should be zero since the number of tokens is the same, just token owners have been \"changed\".\n\nExample:\n* Alice owns 100 tokens (*input = 100*)\n* Alice is going to send 20 tokens to John from the address that includes 100 tokens of her (*Alice -100*)\n* John is going to receive 20 tokens from Alice (*output = 20*; *John +20*)\n* Alice still owns 80 tokens after the transaction (*unspent = 80*; *Alice +80*)\n\nAlice's bundle should look like:\n\\begin{align}\nInput - Output & = \\ Unspent \\\\\nInput - Output - Unspent & = \\ 0 \\\\\n100 - 20 - 80 & = \\ 0\n\\end{align}\n\nWhy Alice has to \"put\" all 100 tokens in the bundle while she is going to actually spend only 20 tokens? The reason is that IOTA protocol uses one-time signature scheme (OTS) for transaction signing while spending tokens. And with every signing process a half of a private key of the given address is revealed. That's why no one should ever spend tokens from the same address again.\n\n\n### Spending tokens\n*Please note: for a purpose of this chapter we are going to switch to a test network called `devnet`. It is the testing Tangle. Tokens are not real and everything you do have no implication to the mainnet at all. However it is stil powered by standard node software and so technicaly speaking it behaves like the mainnet. If you need more info regarding devnet please refer to [the official documentation](https://docs.iota.org/introduction/testnet/introduction).*\n\nEverything what has been mentioned in the previous chapter focused on `non-value` transations is still valid also in case of value transactions however there are several additional tasks you should take care of. Needless to say, IOTA libraries (PyOTA and others) are ready to help you and are able to hide all implementation details in case you would like to. In this case I would encourage everyone to prefer a functionality that is offered by extended API calls, such as `send_transfer`. Experimenting with value transactions and trying to tweak them does not seem to be a good idea (on the mainnet).\n\nAnyway, even in this chapter I am going to describe main tasks that are performed under the hood to be able to understand the whole concept.\n\nLet's have the following setup:\n\n\n```python\nimport iota\nfrom pprint import pprint\n\n# Sender's side ***********\n# Sender's seed\nSeedSender = b\"HGW9HB9LJPYUGVHNGCPLFKKPNZAIIFHZBDHKSGMQKFMANUBASSMSV9TAJSSMPRZZU9SFZULXKJ9YLAIUA\"\n\n# Receiver's side ***********\n# Recipient's seed - this is actually not needed for the exercise - it is just to have corresponding seed somewhere written\nSeedReceiver = b\"NVPDKGLESTYNJEH9DTWD9DUBYWHZJDDWTBLKWEYLVZKBKKAZTIZ9CFFJMHPEKIFUWQTXRGAVRXAQZCPHL\"\n\n# This is our target address to which we are going to send tokens to (BTW: it is a first generated address based on recipient's seed)\nAddressReceiver = b\"BMFSMZMNBGKHAWPIZIOMJGRBXZETVSAYDSTDQCHLYTBWZMIXLNXF9XHLTMOCATFVFOMBQF9IOQGPEBPDC\"\n\n#DevNet node - Devnet Tangle that is used only for testing/dev purposes - no real tokens here:(\nDevnetNode = \"https://nodes.devnet.iota.org:443\"\n\nprint(\"Variables were initialized.\")\n```\n\n    Variables were initialized.\n\n\nYou may be wondering why only the seed for sender's side is defined. As mentioned above the reason is that the address with tokens is changing with every spending exercise and so you have to find address with tokens that left in a bucket programatically (if any tokens left:).\n\nLet's find out. For this purpose you can use extended API call `get_account_data` which returns a list of used addresses and total sum of all tokens available accross all of them:\n\n\n```python\napi = iota.Iota(DevnetNode,\n                seed=SeedSender # let's use seed of the sender and so library can do all hard work\n               )\n\nprint(\"Checking for total balance. This may take some time...\")\n\n# now we can find out whether there are any tokens left\nSenderBalance = api.get_account_data(start=30, #starting from 30th address to save time\n                                    stop=None) # Get the total available balance for the given seed and all related used addresses\n\nprint(\"\\nPlease note, this may take some time if many addresses has been used already...\")\npprint(SenderBalance)\n\nif SenderBalance['balance']>0:\n    print(\"\\nYes, there are some tokens available! hurray\")\n```\n\n    Checking for total balance. This may take some time...\n    \n    Please note, this may take some time if many addresses has been used already...\n    {'addresses': [Address(b'OTJSUNSQ9DLJVLKMVVPLDUTRHZAJDISDPZQCEPWNJWUGZOSFWRRBTUJAWCKKXACMZQIUP9NVVFYWRISWA'),\n                   Address(b'BGUDHNNYKGZWLBVIFCAGCSBWZRHXZSPT9NWLWFM9KLWCEPUGEDE9XRBOGFJLJCUJKQFILMIPGKZJYUAVW'),\n                   Address(b'AYYUYIMDUGBXQBKMVOA9XBKXICCMLVYZCPAAAUVPSDDBJSOZJIY9RVMPMEVMGJVEROVMDVVYQXXKRANSD'),\n                   Address(b'WHVPRFXYKBSIB9NYHWSGEWHLQYAIPLGIUIPGGIJNQYKKCWRMGLZNUIADZATOBCGBLBI99HYVQOHIFWRS9'),\n                   Address(b'SUYDJCMS9XMBKOPIPOXKGXMFVYXQ9YRNZLDYLRFARZFOFJDDH9JZLCQVO9GBRQKBCXHSPHOAPPWFFLMBW'),\n                   Address(b'NHVGPRAXYTDZJLMLSUMZGVBBMICDQGGAAZ9UJGLIPPOTUEZJXABCSDFUTRTBFOLDOQZIBS9QTRXAB9IUX'),\n                   Address(b'VZITIWJF99TH9REMKLYZUWELFLEW9FVYXPZPVMVFZVIQHAOEMEDABUUZGFROKKIVMT999PWGGLICKJOAD'),\n                   Address(b'XPV9CTUC9JEKATOVABXXLICTDAQEOHR9HXXFLHKN9OZFMFAZKKUDZMREOBZJONZAHXCGNN9FHGNFBAKMC'),\n                   Address(b'NDQMBGBQIBAQURVAQEUVONVMECKXSNYZZNKMMMOHOLPEYHJHDBTFWOZMAPFUAHLHIQUAV9GVZPEMBKL9Z'),\n                   Address(b'QYENROHVANIYBSIIMWGFDOUHXTMFOXIHOQXTJZLRFRJMOOINFTWCVVEJUFIITLBIHLVTESPVLUOSCFJDZ'),\n                   Address(b'SZAVDSKTHNQFWTTINRAYQKJAXTLD9CRFFWWBSEXIEXPLBBEP9FT9IVGICWIXTJCFUKJSTOUFANJGBTPQX')],\n     'balance': 3828,\n     'bundles': [<iota.transaction.base.Bundle object at 0x7f87d8de0390>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8dfc8d0>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8da8160>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8d97860>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8e03cf8>,\n                 <iota.transaction.base.Bundle object at 0x7f87d949b320>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8de4780>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8de2470>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8e06908>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8def048>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8dea6a0>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8dbe198>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8df42e8>]}\n    \n    Yes, there are some tokens available! hurray\n\n\n*Please note: API call `get_account_data` consider only confirmed transactions while calculating total balance. So it is better to wait until all transactions are cleared before you send additional tokens.*\n\nAre there any tokens left (value in `balance` field)? If yes then continue - no action is needed.\nIf not, then you need to obtain some. It can be done visiting [IOTA faucet](http://faucet.devnet.iota.org) and entering an unused address of the given seed:\n\n\n```python\n# Now let's find a first unused address that can be used as a destination address for unspent/new tokens\n\nprint(\"\\nPlease note, this may take some time if many addresses has been used already...\")\nFreeAddressSender = api.get_new_addresses(index=30,\n                                          count=None, # If None is specified, then it identifies a first non-used address\n                                          security_level=2) # Let's generate an address using default security level=2.\n\nprint(\"\\nThis is the first unused address that can be used for new tokens or unspent tokens:\")\npprint(FreeAddressSender)\n\n```\n\n    \n    Please note, this may take some time if many addresses has been used already...\n    \n    This is the first unused address that can be used for new tokens or unspent tokens:\n    {'addresses': [Address(b'MHJIRKPUVSXBZWUXKUBNT9MRSEG9CRR9DNKIVNSCBZVGEDIDYTXIAVJLSTKQGVGDBFHRCRHBEMMZXPUFZ')]}\n\n\nWhat have just happened behind the curtain?\n* The PyOTA library started to generating addresses from the `index=0` of the given seed and at the same time it also checked whether there are any transactions registered for each address\n* If yes, then in case we are after balances, the balance is saved. In case we are after new unused address then the given address is skipped. First address for which there are not registered transactions is returned\n* That's why it may be quite time consuming. And now you also understand all issues regarding `zero balances` after the snapshot\n\nYou may be also wondering how to get individual balances for each used address? This can be checked using the core API call `get_balances` which provides you with a balance for any address you specify. Let's query for used addresses from the previous exercise:\n\n\n```python\n# only if there is any used addresses from the previous steps\n\n# it returns the balances as a list in the same order as the addresses were provided as input.\nif len(SenderBalance['addresses'])>0:\n    print(\"\\nSome positive balance identified. Individual confirmed balances per used addresses:\")\n    pprint(api.get_balances(addresses=SenderBalance['addresses'],\n                           threshold=100) # Confirmation threshold; official docs recommend to set it to 100\n           )\nelse:\n    print(\"\\nNo positive balance identified.\")\n```\n\n    \n    Some positive balance identified. Individual confirmed balances per used addresses:\n    {'balances': [0, 0, 0, 0, 0, 0, 0, 0, 0, 2979, 849],\n     'duration': 1,\n     'milestone': None,\n     'milestoneIndex': 1366125,\n     'references': ['BZXG9BLWNISGNFNUNPAZGPURMJUIAQPUAGAQJFVWOSTHINBVWVNGLWPKHI9WTAORCGUPCBCNHNIEQH999']}\n\n\nIt returns `balances` and you can see how the remaining tokens move to new unused address every time you spend some tokens. Needless to say, used addresses with zero balances should not be used anymore since tokens were already spent from them. So let's spend some tokens:\n\n\n```python\ntx1 = iota.ProposedTransaction( address = iota.Address(AddressReceiver), # 81 trytes long address\n                                message = None,\n                                tag     = iota.Tag(b'HRIBEK999IOTA999TUTORIAL'),\n                                value   = 10) # we are going to spend 10i\n\n# Sending the iotas\nprint(\"\\nSending iotas... Please wait...\")\nSentBundle = api.send_transfer(depth=3,\n                         transfers=[tx1], # one transaction defined above. It is an output TX that adds tokens\n                         inputs=None, # input address(es) that are used to finance the given transaction. Tokens will be deducted from them\n                         change_address=None, # this is the adddress to which unspent amount is sent\n                         min_weight_magnitude=9, # in case of Devnet it is 9\n                         security_level=2) # you need to specify security level to be sure library generate compatible addresses\n\n# you may be wondering why there is imputs=None and change_address=None.\n# It means it will be taken care by library and so make sure correct seed / security level was added while api initialization\n\nprint(\"\\nIt has been sent. Now let's see transactions that were sent:\")\n# let's check transactions that were sent in fact\n\nprint(\"Here is the bundle hash: %s\" % (SentBundle['bundle'].hash))\nfor tx in SentBundle['bundle']:\n    print(\"\\n\")\n    pprint(vars(tx))\n\n\n```\n\n    \n    Sending iotas... Please wait...\n    \n    It has been sent. Now let's see transactions that were sent:\n    Here is the bundle hash: K9CRAOLBJCT9CEAKJVZIKUIIUSVKJIZGHXPJVYRDPJ9IFSUJPGRYECUCLIFKHLHVSE9ZSABLAUTXQ9HPD\n    \n    \n    {'_legacy_tag': Tag(b'LUIBEK999IOTA999TUTORIAL999'),\n     'address': Address(b'BMFSMZMNBGKHAWPIZIOMJGRBXZETVSAYDSTDQCHLYTBWZMIXLNXF9XHLTMOCATFVFOMBQF9IOQGPEBPDC'),\n     'attachment_timestamp': 1570539229755,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 3812798742493,\n     'branch_transaction_hash': TransactionHash(b'FM9BAYPTXRETLTNOZJGDOZDVPNWTDFWHETXN9ALOXBOSJAKJZWCFIMAUNVFNEQHFCLELVBUKFKYIVO999'),\n     'bundle_hash': BundleHash(b'K9CRAOLBJCT9CEAKJVZIKUIIUSVKJIZGHXPJVYRDPJ9IFSUJPGRYECUCLIFKHLHVSE9ZSABLAUTXQ9HPD'),\n     'current_index': 0,\n     'hash': TransactionHash(b'HELRSWQUGBEYVUYDHGHTTQRKHWPGVTTFCOCJUXPKTSTZIVKBNPKTFMUMWAYVRVRHEBBKCFFTWEOPTX999'),\n     'is_confirmed': None,\n     'last_index': 3,\n     'nonce': Nonce(b'WONHBBPEDLHWRLGUPRFAWHDAEXB'),\n     'signature_message_fragment': Fragment(b'999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1570539041,\n     'trunk_transaction_hash': TransactionHash(b'KXBVBYKXCKHNUWAWWINEENG9A9T99ZGRAPPKSZWCASHSENHTBGMHZYLHGLVXFNPYMPOGJUHRQXWLRJ999'),\n     'value': 10}\n    \n    \n    {'_legacy_tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'address': Address(b'QYENROHVANIYBSIIMWGFDOUHXTMFOXIHOQXTJZLRFRJMOOINFTWCVVEJUFIITLBIHLVTESPVLUOSCFJDZ'),\n     'attachment_timestamp': 1570539229722,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 3812798742493,\n     'branch_transaction_hash': TransactionHash(b'FM9BAYPTXRETLTNOZJGDOZDVPNWTDFWHETXN9ALOXBOSJAKJZWCFIMAUNVFNEQHFCLELVBUKFKYIVO999'),\n     'bundle_hash': BundleHash(b'K9CRAOLBJCT9CEAKJVZIKUIIUSVKJIZGHXPJVYRDPJ9IFSUJPGRYECUCLIFKHLHVSE9ZSABLAUTXQ9HPD'),\n     'current_index': 1,\n     'hash': TransactionHash(b'KXBVBYKXCKHNUWAWWINEENG9A9T99ZGRAPPKSZWCASHSENHTBGMHZYLHGLVXFNPYMPOGJUHRQXWLRJ999'),\n     'is_confirmed': None,\n     'last_index': 3,\n     'nonce': Nonce(b'Q9AKQLCRMJCIHIBZCGJEFTFDCOY'),\n     'signature_message_fragment': Fragment(b'FJVNAC9ELWJZKXB99BEWPEAYVWLTCERBQM9AQPLPMYUJTSLARUCASCOSZHMFXAYSMVTYHXFKZZODWCXIZIHOEFYO9YNSVUTIA9SAEMOUIJXIVUPDEAQLZPSP9JCREYPTDWMXTQYRQGDEW9QJJUBBIUEPUCEVMYTYPWPCETJAHHPUCSEGLIWQXNRNNGKEYFMVGTQZUDJJICXLQDUNDCWXIPAGXMAVUBSEYWRRYMFBNLPW9YAZJXXLTZJ9EUJREYMSWTYRHDLNZEIPEDFGYMATPOTAYGTYJVSMJQUFS99JTAPRELWRETRJSBNRCN9JQQFBBXPAGZSRDLPERRWKGCCYLBHWGNRNUYHQXKTMALZNCHFXEQLN9QYQYXJGTDINBGIECFNFQWTKCBELCSJYI9IB9TTNZILAOBKOGNERVGIZCUUNGUYLICKVVREVHEGTCLVCSRXLFUQUAQJUGP9QHOFYGSNLDVLDQKDPFSTOYZQEFFTPUNJQFSWKEWLZUKQTJ9DZHMPHRHY9ABEUMKFZBIS9OPBIU9GQJALZDISKAKWT9I9ZIJSIVMGIAGXYRHEYBQUMSXXZCUEOJKRKCEQWDXZJQRAKBCCVWSRQMSP9RUESTPHEY9XS9NVCHIJYZ9WMNDLKSZQWZHWZOKVRBEQECLOFORIK9DYUDNMXDZRPIEHGEBIORNRQAIFMZKFUYXMXRLTJMNDXEYTWC9OAJLRDFPDB9PVXDHETPFYLARGHCMFRYGKMXFQNCMN9NMNQXTEDLDKPAWCKOEK9KYCLVL9JTNUJCCNHJGDKAUZTJIXSKNFMMDFVGX9JHGDR9DNQQHYH9MEZAVXYJDDJAZWJRGVHBKLIVARKHBDECPH9ZTLSHDMLOWNMHLSFHAESHPACXYDQ9XCOXZGPORYL9DGYDLBDWQI9KYKCCAVB9SUIJIRWOCNWPZDFJLNRMERONTSJTXMRQHWDVERYITAHIF9YILTYDTUAJPAMDLPHNPZYCXYAAMXQUVLIYUKNKBFRBM99IYB9JJAREWYVKEOPPBNZAGHXYD9OVWYHBJKRYLTZLFQRNOBFVFEYSPZYHTEWRPPWMNGCRGVPZOYYDUFDLN9HCEWCFNZCTLFSRKJNPYEKRSDPDBHGHQTFMCRRGE9XSPVMWWHXSBPWNFJJMDLQVRNXLLJACLSWMEEMGDQANJRWPYSTEYYJPTGCVMTAIGZCPKTTZKOAXWYXYWUEUGB9PCCTEIDPLTYLGISOOPDGAHIMQSLPDYKEKWEQILLUPJUGOIT9THGR9LQAJQNAEDCCGEUQWJHDGRPDWNSLFHIU9RNHEUKEADSUMWUFESQTTCGBPYEAHKQLPGTPRQGQCL9BWHZKLFNLAVBIKQADHWNVIFLACAMXEKKSDPTDEW9DISRNXWTNMBRTGDOMZLDJBDKLLKJVCRXNCUBTW9OGF9QJCBQLZTLWDEFJN9EDFTPSYDPKMFUL9VDYYNBXPFDZCVYFLFCXXXOCETLOOUCWNKORHOSLDGLDXPUJRGH9YGWUKZUPHRBEQLLHQFLMZVWQGXXQCQTDYLWUPPSQTVBOHWQNAYZVZ9UAMBOUJEQIVLYPUCHVEEZPPEYIOUVBQJDSMREJS9FSBBNVHOMCASBTXVFINJFPMGQOKCIJZYNKNQFJ9NPQLCPM9BTCIVBUFWPUYYXWDGKDZEQBGEEFAEWWLZXQXASHVGY9BGFMFBGDSAKMZSQFCUJEKVQTEYKZ9TNXAXPWY9PIVGFFZJFDLDDWFALQANBF9BNGISCDUZNEDYVQ9GSIQAANIFCDHDKNPPKGPBATWZDJMTYKZPJFEXFM9EBDAGXPGUPUBXNKVXX9XWXUEVLRFUOVXKXURDK9ZG9FHLZZZ9JIM9HOHSMMRUOIP9AKPZRNAOOGIZYIOIMNPFLIRXURVGJZJVUIYQMNSSPOGEBBSUPEVZMUNDQSQCZCVVFEBIKUUZHMONG9DZMFSKOKENSPRQSKYIEKUXCPQGWVGWJEJNJEUFRRHOZJFFT9WGVUQCOURVLHIUELYFZOEFCCOKWNGDJYXBWNZFATDPZRDCXJD9YT9VRLAAPQXGWFNGFCUAFPUMGSNCJXPNCCGGBAZMWCVTQMEWZUYOVBQKICIWGXBSFWXGQYLPMGWHPHIQUASXNBQOGDXCTSZETRSGURCZJNTVEMTKRPGBKITGPHUXWRVFD'),\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1570539137,\n     'trunk_transaction_hash': TransactionHash(b'DEKVWJZUMYHURTSQRZJMGZVZATELXYOGSUJTSSKNBPETPJZYCSN9WGCXQTANBAJDQQMXFMKJEITRBI999'),\n     'value': -2979}\n    \n    \n    {'_legacy_tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'address': Address(b'QYENROHVANIYBSIIMWGFDOUHXTMFOXIHOQXTJZLRFRJMOOINFTWCVVEJUFIITLBIHLVTESPVLUOSCFJDZ'),\n     'attachment_timestamp': 1570539229704,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 3812798742493,\n     'branch_transaction_hash': TransactionHash(b'FM9BAYPTXRETLTNOZJGDOZDVPNWTDFWHETXN9ALOXBOSJAKJZWCFIMAUNVFNEQHFCLELVBUKFKYIVO999'),\n     'bundle_hash': BundleHash(b'K9CRAOLBJCT9CEAKJVZIKUIIUSVKJIZGHXPJVYRDPJ9IFSUJPGRYECUCLIFKHLHVSE9ZSABLAUTXQ9HPD'),\n     'current_index': 2,\n     'hash': TransactionHash(b'DEKVWJZUMYHURTSQRZJMGZVZATELXYOGSUJTSSKNBPETPJZYCSN9WGCXQTANBAJDQQMXFMKJEITRBI999'),\n     'is_confirmed': None,\n     'last_index': 3,\n     'nonce': Nonce(b'LYQCYVY9MIALVUHHTNQUAOVBZMZ'),\n     'signature_message_fragment': Fragment(b'XJVSTWGWINBVVLAAZNSYQFAHKJIOVBBTHGHSFWXUKYO9QU9JYTXKCFCPLNHGAFHGYNRGP9ZIRLM9QI9JBPVYGGNUGWOO9LIYZRIPFRGQFDJBVPIMTBYDFVOHHAZXEHDY9ROBSOCCQEAMCODVAKJELMDA9SZFHXJWSXKLNXODY9GFGDPTTRSTJNIXRHUHVCJ99KPOVZVGDNBBJYIROBWJYIKKERYDPWLGBOGTPQEULYCD9JGBRQDBICHBNLBCSYFY9IT9PRKXCRGOVAF9XXXDM9ZHWYPNCSLYHMMKNPNBCWHTBAIDPJOZIFXMNPRLZTDHOGAYYBITYOSUQYTDUPLFCBXGQRWFQRPNNFZLGXERTPOORJZXJAXBIWRNOEOJKKKVTC9FLGKUVXQVRXOQQCDKXCEKMIKWWRLTKQBYHZMZZWLTAUHOUHXVFDSEHFTUHUYSLXXEGTZXLHKFUA9KACIQEHCVRVNWBZGFMOFSC9OWGPFATZMLYADGJYRARIRVYANWDVKMQCAAMVUOYDUIGQSZRRAUJSH9MDNIWZDQMTUSF9XGHZVCPBIQEJY9CEDYXROCPOQXF9XPUBYSIPBQDHB9QHJABIPILVIZMNGLWWGSOXLBICSMY9OHPBYKOBSXEFIYPOZLWDUXAWSLADZOF9SILPRYZKQKYKHTGZIJNJ9QBFIVFRNFNZAYYRAHMCHZJBMKUSDSKLEYXDIQASQPXLDAZDNVBXQZDADMQMYNHQQFXENTPRSBLBKFVFPPKNKXYIILMFWXYZZOLDFVAJCKQDDQNVYANQNG9DHKRSKMUOAYDDC9AHENC9RGHJXPH9OYLQZAKVRZFDOEQFQGBXZMKOEZQIYDJNNHHMDQXVEXBNBDDPQAJJDXIWFFGQATSW9WABRSYBPGGILGX9GSTJRXUNOTGPIFAUDATTFMXBCG9SGTIIIUGGMYNGKBDKSJXBIAIBFNR9TFEXLRCXTWWWMJIGCSGFAHRFFYACSWAGM9VZSHL9QZ9SSWMQGUPPFE9HWZWIXGHNACPTXRGPJUVK9DYPWEICZKPMCDAPYYPZJKLPWBKKT99APKTQICCKGZIWYNKPMNRYWVDBTEGJLCCIIXGXQVKOSUBJUPZJFCIMED9ROCOZQBDXEOTZAHJGHWUDGWBXCCUTMSMRREYPWJIQSGOIPHODFTUM9BSZGHPXYRJETJUEFXIICWFTWKXSKGKTWARKCQLYBIQHDDMVJF9LJOGBNZINDNUZQKNDAWZHBIISVCVDJGSJAQ9VASOSCDPMBLFSDHHAXMAKCJXIMVDNRYEPJFKJDICTRZDZWMQIZEPNWZDHZQHWWMMWFSDMRFSYLNNOMTAVKLEINGPYMFANWWLVYBTAGVSPJOMBWBZHEWXPBQUOWPUPACOQHPTA9DAHIRJKWTT9LLARKJIDMWXJNNGRPQQMFREIYXVLPELQAMIOGJ9CLOWRBYXWL9RUTDS9HQQWOFOSVWIQOYZBEDTBYLRL9SXPSCGDZJJWSBYBLKVIVVTTLIPVYZOCWMRYTTRYTA9UAIYMBPZZVJLVBJSRGKTMHCVAOSIFM99BQAUXKEWNCQLHGCUJSXLAJWAUMEYJZEEWATAGAWQPMMVTIPFQHXLORDHLOL9YMBUX9KWAZMFECXOLATKLVNYAOEYFBGTZDAZCJVSXLQIOZTHJXWDLOUBCOJFIVVRUIMXJHSRKPLBCQAAVVFYEHWKXXCMFUUP9VFU9EFFIDYUO9EVLPHIMOFDLTBVNRRLTLBDJOCWBZCSKXSIFZT9UZXQWTM9C9MLGRX9AIVCSAHEBGUBWPCCKBKUHQXDKYUQRK9NDTPPTRCBRGTIFNQCEEFFYNCDWINFPCNTISELIKFEF9CJBFDHOLKBVZNLJJFGLHAWMMURTNFLVJAOAOQEZKM9DQXEVNSPBMXGVCCWNKICEMJNWC9XDFLKVKZWPECGHOTIXG9ENJNBSQFKLKCNPG9LADRSOJIAEXPAQKUNQMMXM9ARQNT9GUWHJEEZNTQDVDNZOE9ABOTUWJTCYYOMSTOXXCBVEMODRKFKO9ANDKBYFRITYZ9LTJKELWSYCEYPOPGMUHJUYFVDLWMDZOKR9WDQLMIMH9IUXQJGQROXDJDJNJHQAYYURURTRHECNGPRUAQIK99YA9EU9MSEABDGJGLIHJDMQUSNTKZRCORVYIXWFPHKVX'),\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1570539137,\n     'trunk_transaction_hash': TransactionHash(b'AYRWHKRNVKYQTPRBEOLHDBTIPEVNNGUJKKFHR9HZYUP9XZPMBTOKEXCJXLAWXODKBXGNGIWEUMEGX9999'),\n     'value': 0}\n    \n    \n    {'_legacy_tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'address': Address(b'MHJIRKPUVSXBZWUXKUBNT9MRSEG9CRR9DNKIVNSCBZVGEDIDYTXIAVJLSTKQGVGDBFHRCRHBEMMZXPUFZ'),\n     'attachment_timestamp': 1570539229688,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 3812798742493,\n     'branch_transaction_hash': TransactionHash(b'FM9BAYPTXRETLTNOZJGDOZDVPNWTDFWHETXN9ALOXBOSJAKJZWCFIMAUNVFNEQHFCLELVBUKFKYIVO999'),\n     'bundle_hash': BundleHash(b'K9CRAOLBJCT9CEAKJVZIKUIIUSVKJIZGHXPJVYRDPJ9IFSUJPGRYECUCLIFKHLHVSE9ZSABLAUTXQ9HPD'),\n     'current_index': 3,\n     'hash': TransactionHash(b'AYRWHKRNVKYQTPRBEOLHDBTIPEVNNGUJKKFHR9HZYUP9XZPMBTOKEXCJXLAWXODKBXGNGIWEUMEGX9999'),\n     'is_confirmed': None,\n     'last_index': 3,\n     'nonce': Nonce(b'MOFCEZUIRTEEDUOGYSKIQT9JIFC'),\n     'signature_message_fragment': Fragment(b'999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1570539226,\n     'trunk_transaction_hash': TransactionHash(b'FM9BAYPTXRETLTNOZJGDOZDVPNWTDFWHETXN9ALOXBOSJAKJZWCFIMAUNVFNEQHFCLELVBUKFKYIVO999'),\n     'value': 2969}\n\n\nLet's review all transactions that has been prepared and sent eventually:\n* The first transaction `current_index=0` is the `output TX` that basically adds tokens to some address\n* Transactions `current_index=1` and `current_index=2` are two parts of the same transaction - `Input TX`. This transaction deducts tokens from the address(es). You can see negative `value` in the transaction `current_index=1`\n* Why there are two parts? Since the transaction spends tokens it has to be signed in order to validate the ownership. Signature is generated from the private key and the signature can be observed in the field `signature_message_fragment`. Here is the thing. Do you remember when different `security levels` were discussed? There are three security levels available and the given level has the direct impact on length of the signature. Since `signature_message_fragment` is of the fixed size, if `SL>1` then the transaction has to be split to be able to accommodate full signature.\n* The last transaction `current_index=3` moves unspent tokens to the first unused address of the given seed.\n\nThe following tasks have to be done behind the curtain in addition to the standard transaction preparation process:\n* Search for address(es) with some balance until total amount of tokens available is large enough to be spent. You can use more input addresses if needed\n* If there would be some unspent amount of tokens then also search for the first unused address\n* Spending transactions (Input TX) has to be properly signed and split in case of `SL>1`\n* There is also some quick check performed whether resulting number of tokens is zero (no more tokens, no less tokens. Number of tokens has to be balanced).\n\nSo basically all steps we tried in the chapter had to be done also behind the curtain while using `send_transfer` extended API call. You can also see that some of those operations may be quite expensive in terms of time while being completely stateless. In real world applications it would be better to save some states (index of last address, used addresses, etc.) to avoid too many expensive operations.\n\nYou can review the given broadcasted transactions also in the tangle explorer (for devnet):\n* https://devnet.thetangle.org/address/BMFSMZMNBGKHAWPIZIOMJGRBXZETVSAYDSTDQCHLYTBWZMIXLNXF9XHLTMOCATFVFOMBQF9IOQGPEBPDC\n", "meta": {"hexsha": "01cbe7786eabed7889d198836e316a8b1c0d0015", "size": 110381, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "02_IOTA Transactions.ipynb", "max_stars_repo_name": "Hribek25/IOTA101", "max_stars_repo_head_hexsha": "adf5c4cced557d60836bf6ba80a1080b2607c8e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2018-06-28T18:15:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T22:05:53.000Z", "max_issues_repo_path": "02_IOTA Transactions.ipynb", "max_issues_repo_name": "Hribek25/IOTA101", "max_issues_repo_head_hexsha": "adf5c4cced557d60836bf6ba80a1080b2607c8e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-07-01T19:45:20.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-01T18:18:04.000Z", "max_forks_repo_path": "02_IOTA Transactions.ipynb", "max_forks_repo_name": "Hribek25/IOTA101", "max_forks_repo_head_hexsha": "adf5c4cced557d60836bf6ba80a1080b2607c8e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-08-26T20:01:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-26T17:09:56.000Z", "avg_line_length": 96.1506968641, "max_line_length": 2720, "alphanum_fraction": 0.8139444288, "converted": true, "num_tokens": 32877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245510940225, "lm_q2_score": 0.10087863151524239, "lm_q1q2_score": 0.027441464452913122}}
{"text": "# Bringing contextual word representations into your models\n\n\n```python\n__author__ = \"Christopher Potts\"\n__version__ = \"CS224u, Stanford, Fall 2020\"\n```\n\n## Contents\n\n1. [Overview](#Overview)\n1. [General set-up](#General-set-up)\n1. [Hugging Face BERT interfaces](#Hugging-Face-BERT-interfaces)\n  1. [Hugging Face BERT set-up](#Hugging-Face-BERT-set-up)\n  1. [Hugging Face BERT basics](#Hugging-Face-BERT-basics)\n  1. [BERT featurization with Hugging Face](#BERT-featurization-with-Hugging-Face)\n    1. [Simple feed-forward experiment](#Simple-feed-forward-experiment)\n    1. [A feed-forward experiment with the sst module](#A-feed-forward-experiment-with-the-sst-module)\n    1. [An RNN experiment with the sst module](#An-RNN-experiment-with-the-sst-module)\n  1. [BERT fine-tuning with Hugging Face](#BERT-fine-tuning-with-Hugging-Face)\n    1. [HfBertClassifier](#HfBertClassifier)\n    1. [HfBertClassifier experiment](#HfBertClassifier-experiment)\n1. [Using ELMo](#Using-ELMo)\n  1. [ELMo Allen NLP set-up](#ELMo-Allen-NLP-set-up)\n  1. [ELMo fine-tuning](#ELMo-fine-tuning)\n    1. [AllenNLP ELMo interfaces](#AllenNLP-ELMo-interfaces)\n    1. [ElmoRNNClassifier](#ElmoRNNClassifier)\n    1. [ElmoRNNClassifier experiment](#ElmoRNNClassifier-experiment)\n\n## Overview\n\nThis notebook provides a basic introduction to using pre-trained [BERT](https://github.com/google-research/bert) and [ELMo](https://allennlp.org/elmo) representations. It is meant as a practical companion to our lecture on contextual word representations. The goal of this notebook is just to help you use these representations in your own work. The BERT and ELMo teams have done amazing work to make these resources available to the community. Many projects can benefit from them, so it is probably worth your time to experiment.\n\nThis notebook should be considered an experimental extension to the regular course materials. It has some special requirements \u2013 libraries and data files \u2013 that are not part of the core requirements for this repository. All these tools are very new and being updated frequently, so you might need to do some fiddling to get all of this to work. As I said, though, it's probably worth the effort!\n\nA number of the experiments in this notebook are resource intensive. I've included timing information for the expensive steps, to give you a sense for how long things are likely to take. I ran this notebook on a laptop with a single NVIDIA RTX 2080 GPU. \n\n## General set-up\n\nThe following are requirements that you'll already have met if you've been working in this repository. As you can see, we'll use the [Stanford Sentiment Treebank](sst_01_overview.ipynb) for illustrations, and we'll try out a few different deep learning models.\n\n\n```python\nimport os\nimport sst\nfrom torch_shallow_neural_classifier import TorchShallowNeuralClassifier\nfrom torch_rnn_classifier import TorchRNNModel\nfrom torch_rnn_classifier import TorchRNNClassifier\nfrom torch_rnn_classifier import TorchRNNClassifierModel\nfrom torch_rnn_classifier import TorchRNNClassifier\nfrom sklearn.metrics import classification_report\nimport utils\n```\n\n\n```python\nutils.fix_random_seeds()\n```\n\n\n```python\nSST_HOME = os.path.join(\"data\", \"trees\")\n```\n\n## Hugging Face BERT interfaces\n\n### Hugging Face BERT set-up\n\nTo install this library, run\n\n```pip install transformers```\n\nI've tested this code with versions 2.4, 2.5, and 2.11 of `transformers`. Try to get at least 2.5. It requires `pip >= 20` and, I think, a version of [Rust](https://www.rust-lang.org) at least as high as 1.21.1.\n\n\n```python\nimport torch\nimport torch.nn as nn\nfrom transformers import BertModel, BertTokenizer\n```\n\nThe `transformers` library does a lot of logging. To avoid ending up with a cluttered notebook, I am changing the logging level. You might want to skip this as you scale up to building production systems, since the logging is very good \u2013 it gives you a lot of insights into what the models and code are doing.\n\n\n```python\nimport logging\nlogger = logging.getLogger()\nlogger.level = logging.ERROR\n```\n\n### Hugging Face BERT basics\n\nTo start, let's get a feel for the basic API that `transformers` provides. The first step is specifying the pretrained parameters we'll be using:\n\n\n```python\nhf_weights_name = 'bert-base-cased'\n```\n\nThere are lots other options for pretrained weights. See [this section of the project README.md](https://github.com/huggingface/transformers#quick-tour) for a good overview and code that documents how these weights align with different Transformer model classes.\n\nNext, we specify a tokenizer and a model that match both each other and our choice of pretrained weights:\n\n\n```python\nhf_tokenizer = BertTokenizer.from_pretrained(hf_weights_name)\n```\n\n\n```python\nhf_model = BertModel.from_pretrained(hf_weights_name)\n```\n\n\n\n    \n\n\nIt's illuminating to see what the tokenizer does to example texts:\n\n\n```python\nhf_example_texts = [\n    \"Encode sentence 1. [SEP] And sentence 2!\",\n    \"Bert knows Snuffleupagus\"]\n```\n\nThe `encode` method maps individual strings to indices into the underlying embedding used by the model:\n\n\n```python\nex0_ids = hf_tokenizer.encode(hf_example_texts[0], add_special_tokens=True)\n\nex0_ids\n```\n\n\n\n\n    [101, 13832, 13775, 5650, 122, 119, 102, 1262, 5650, 123, 106, 102]\n\n\n\nWe can get a better feel for what these representations are like by mapping the indices back to \"words\":\n\n\n```python\nhf_tokenizer.convert_ids_to_tokens(ex0_ids)\n```\n\n\n\n\n    ['[CLS]',\n     'En',\n     '##code',\n     'sentence',\n     '1',\n     '.',\n     '[SEP]',\n     'And',\n     'sentence',\n     '2',\n     '!',\n     '[SEP]']\n\n\n\nFor modeling, we will often need to pad (and perhaps truncate) token lists so that we can work with fixed-dimensional tensors: The `batch_encode_plus` has a lot of options for doing this:\n\n\n```python\nhf_example_ids = hf_tokenizer.batch_encode_plus(\n    hf_example_texts,\n    add_special_tokens=True,\n    return_attention_mask=True,\n    pad_to_max_length=True)\n```\n\n\n```python\nhf_example_ids.keys()\n```\n\n\n\n\n    dict_keys(['input_ids', 'token_type_ids', 'attention_mask'])\n\n\n\nThe `token_type_ids` is used for multi-text inputs like NLI. The `'input_ids'` field gives the indices for each of the two examples:\n\n\n```python\nhf_example_ids['input_ids']\n```\n\n\n\n\n    [[101, 13832, 13775, 5650, 122, 119, 102, 1262, 5650, 123, 106, 102],\n     [101, 15035, 3520, 156, 14787, 13327, 4455, 28026, 1116, 102, 0, 0]]\n\n\n\nFor fine-tuning, we want to avoid attending to padded tokens. The `'attention_mask'` captures the needed mask, which we'll be able to feed directly to the pretrained BERT model:\n\n\n```python\nhf_example_ids['attention_mask']\n```\n\n\n\n\n    [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]]\n\n\n\nFinally, we can run these indices and masks through the pretrained model:\n\n\n```python\nX_hf_example = torch.tensor(hf_example_ids['input_ids'])\nX_hf_example_mask = torch.tensor(hf_example_ids['attention_mask'])\n\nwith torch.no_grad():\n    hf_final_hidden_states, cls_output = hf_model(\n        X_hf_example, attention_mask=X_hf_example_mask)\n```\n\nBERT representations are pretty large \u2013 this shows the shape of the tensor for 2 examples, with the second padded to the length of the larger one in the batch (12). The individual representations have dimensionality 768.\n\n\n```python\nhf_final_hidden_states.shape\n```\n\n\n\n\n    torch.Size([2, 12, 768])\n\n\n\nThose are all the essential ingredients for working with these parameters in Hugging Face. Of course, the library has a lot of other functionality, but the above suffices to featurize and to fine-tune.\n\n### BERT featurization with Hugging Face\n\nTo start, we'll use the Hugging Face interfaces just to featurize examples to create inputs to a separate model. In this setting, the BERT parameters are frozen. The heart of this approach is the following featurizer, which flattens an SST tree into a string, tokenizes it, and computes its hidden representations:\n\n\n```python\ndef hugging_face_bert_phi(tree):\n    s = \" \".join(tree.leaves())\n    input_ids = hf_tokenizer.encode(s, add_special_tokens=True)\n    X = torch.tensor([input_ids])\n    with torch.no_grad():\n        final_hidden_states, cls_output = hf_model(X)\n        return final_hidden_states.squeeze(0).numpy()\n```\n\n#### Simple feed-forward experiment\n\nFor a simple feed-forward experiment, we can get the representation of the `[CLS]` tokens and use them as the inputs to a shallow neural network:\n\n\n```python\ndef hugging_face_bert_classifier_phi(tree):\n    reps = hugging_face_bert_phi(tree)\n    #return reps.mean(axis=0)  # Another good, easy option.\n    return reps[0]\n```\n\nNext we read in the SST train and dev portions as a lists of `(tree, label)` pairs:\n\n\n```python\nhf_train = list(sst.train_reader(SST_HOME, class_func=sst.binary_class_func))\n\nhf_dev = list(sst.dev_reader(SST_HOME, class_func=sst.binary_class_func))\n```\n\nSplit the input/output pairs out into separate lists:\n\n\n```python\nX_hf_tree_train, y_hf_train = zip(*hf_train)\n\nX_hf_tree_dev, y_hf_dev = zip(*hf_dev)\n```\n\nIn the next step, we featurize all of the examples. These steps are likely to be the slowest in these experiments:\n\n\n```python\n%time X_hf_train = [hugging_face_bert_classifier_phi(tree)\n                    for tree in X_hf_tree_train]\n```\n\n    CPU times: user 34min 55s, sys: 6.99 s, total: 35min 2s\n    Wall time: 5min 52s\n\n\n\n```python\n%time X_hf_dev = [hugging_face_bert_classifier_phi(tree)\n                  for tree in X_hf_tree_dev]\n```\n\n    CPU times: user 4min 13s, sys: 868 ms, total: 4min 13s\n    Wall time: 42.6 s\n\n\nNow that all the examples are featurized, we can fit a model and evaluate it:\n\n\n```python\nhf_mod = TorchShallowNeuralClassifier(\n    early_stopping=True,\n    hidden_dim=300)\n```\n\n\n```python\n%time _ = hf_mod.fit(X_hf_train, y_hf_train)\n```\n\n    Stopping after epoch 38. Validation score did not improve by tol=1e-05 for more than 10 epochs. Final error is 2.0183719843626022\n\n    CPU times: user 19.2 s, sys: 496 ms, total: 19.7 s\n    Wall time: 5.28 s\n\n\n\n```python\nhf_preds = hf_mod.predict(X_hf_dev)\n```\n\n\n```python\nprint(classification_report(y_hf_dev, hf_preds, digits=3))\n```\n\n                  precision    recall  f1-score   support\n    \n        negative      0.850     0.834     0.842       428\n        positive      0.843     0.858     0.850       444\n    \n        accuracy                          0.846       872\n       macro avg      0.846     0.846     0.846       872\n    weighted avg      0.846     0.846     0.846       872\n    \n\n\n#### A feed-forward experiment with the sst module\n\nIt is straightforward to conduct experiments like the above using `sst.experiment`, which will enable you to do a wider range of experiments without writing or copy-pasting a lot of code. \n\n\n```python\ndef fit_hf_shallow_network(X, y):\n    mod = TorchShallowNeuralClassifier(\n        hidden_dim=300,\n        early_stopping=True)\n    mod.fit(X, y)\n    return mod\n```\n\n\n```python\n%%time\n_ = sst.experiment(\n    SST_HOME,\n    hugging_face_bert_classifier_phi,\n    fit_hf_shallow_network,\n    train_reader=sst.train_reader,\n    assess_reader=sst.dev_reader,\n    class_func=sst.binary_class_func,\n    vectorize=False)  # Pass in the BERT reps directly!\n```\n\n    Stopping after epoch 22. Validation score did not improve by tol=1e-05 for more than 10 epochs. Final error is 2.3845930993556976\n\n                  precision    recall  f1-score   support\n    \n        negative      0.839     0.839     0.839       428\n        positive      0.845     0.845     0.845       444\n    \n        accuracy                          0.842       872\n       macro avg      0.842     0.842     0.842       872\n    weighted avg      0.842     0.842     0.842       872\n    \n    CPU times: user 42min 27s, sys: 8.83 s, total: 42min 36s\n    Wall time: 7min 8s\n\n\n#### An RNN experiment with the sst module\n\nWe can also use BERT representations as the input to an RNN. There is just one key change from how we used these models before:\n\n* Previously, we would feed in lists of tokens, and they would be converted to indices into a fixed embedding space. This presumes that all words have the same representation no matter what their context is. \n\n* With BERT, we skip the embedding entirely and just feed in lists of BERT vectors, which means that the same word can be represented in different ways.\n\n`TorchRNNClassifier` supports this via `use_embedding=False`. In turn, you needn't supply a vocabulary:\n\n\n```python\ndef fit_hf_rnn(X, y):\n    mod = TorchRNNClassifier(\n        vocab=[],\n        early_stopping=True,\n        use_embedding=False)  # Pass in the BERT hidden states directly!\n    mod.fit(X, y)\n    return mod\n```\n\n\n```python\n%%time\n_ = sst.experiment(\n    SST_HOME,\n    hugging_face_bert_phi,\n    fit_hf_rnn,\n    train_reader=sst.train_reader,\n    assess_reader=sst.dev_reader,\n    class_func=sst.binary_class_func,\n    vectorize=False)  # Pass in the BERT hidden states directly!\n```\n\n    Stopping after epoch 25. Validation score did not improve by tol=1e-05 for more than 10 epochs. Final error is 0.9420086964964867\n\n                  precision    recall  f1-score   support\n    \n        negative      0.849     0.853     0.851       428\n        positive      0.857     0.854     0.856       444\n    \n        accuracy                          0.853       872\n       macro avg      0.853     0.853     0.853       872\n    weighted avg      0.853     0.853     0.853       872\n    \n    CPU times: user 44min, sys: 31.2 s, total: 44min 31s\n    Wall time: 7min 37s\n\n\n### BERT fine-tuning with Hugging Face\n\nThe above experiments are quite successful \u2013 BERT gives us a reliable boost compared to other methods we've explored for the SST task. However, we might expect to do even better if we fine-tune the BERT parameters as part of fitting our SST classifier. To do that, we need to incorporate the Hugging Face BERT model into our classifier. This too is quite straightforward.\n\n#### HfBertClassifier\n\nThe most important step is to create an `nn.Module` subclass that has, for its parameters, both the BERT model and parameters for our own classifier. Here we define a very simple fine-tuning set-up in which some layers built on top of the output corresponding to `[CLS]` are used as the basis for the SST classifier:\n\n\n```python\nclass HfBertClassifierModel(nn.Module):\n    def __init__(self, n_classes, weights_name='bert-base-cased'):\n        super().__init__()\n        self.n_classes = n_classes\n        self.weights_name = weights_name\n        self.bert = BertModel.from_pretrained(self.weights_name)\n        self.bert.train()\n        self.hidden_dim = self.bert.embeddings.word_embeddings.embedding_dim\n        # The only new parameters -- the classifier:\n        self.classifier_layer = nn.Linear(\n            self.hidden_dim, self.n_classes)\n\n    def forward(self, indices, mask):\n        final_hidden_states, cls_output = self.bert(\n            indices, attention_mask=mask)\n        return self.classifier_layer(cls_output)\n```\n\nAs you can see, `self.bert` does the heavy-lifting: it reads in all the pretrained BERT parameters, and I've specified `self.bert.train()` just to make sure that these parameters can be updated during our training process. \n\nIn `forward`, `self.bert` is used to process inputs, and then `cls_output` is fed into `self.classifier_layer`. Hugging Face has already added a layer on top of the actual output for `[CLS]`, so we can specify the model as\n\n$$\n\\begin{align}\n[h_{1}, \\ldots, h_{n}] &= \\text{BERT}([x_{1}, \\ldots, x_{n}]) \\\\\nh &= \\tanh(h_{1}W_{hh} + b_{h}) \\\\\ny &= \\textbf{softmax}(hW_{hy} + b_{y})\n\\end{align}$$\n\nfor a tokenized input sequence $[x_{1}, \\ldots, x_{n}]$. \n\nThe Hugging Face documentation somewhat amusingly says, of `cls_output`,\n\n> This output is usually _not_ a good summary of the semantic content of the input, you're often better with averaging or pooling the sequence of hidden-states for the whole input sequence.\n\nwhich is entirely reasonable, but it will require more resources, so we'll do the simpler thing here.\n\nFor the training and prediction interface, we can subclass `TorchShallowNeuralClassifier` so that we don't have to write any of our own data-handling, training, or prediction code. The central changes are using `HfBertClassifierModel` in `build_graph` and processing the data with `batch_encode_plus`.\n\n\n```python\nclass HfBertClassifier(TorchShallowNeuralClassifier):\n    def __init__(self, weights_name, *args, **kwargs):\n        self.weights_name = weights_name\n        self.tokenizer = BertTokenizer.from_pretrained(self.weights_name)\n        super().__init__(*args, **kwargs)\n        self.params += ['weights_name']\n\n    def build_graph(self):\n        return HfBertClassifierModel(self.n_classes_, self.weights_name)\n\n    def build_dataset(self, X, y=None):\n        data = self.tokenizer.batch_encode_plus(\n            X,\n            max_length=None,\n            add_special_tokens=True,\n            pad_to_max_length=True,\n            return_attention_mask=True)\n        indices = torch.tensor(data['input_ids'])\n        mask = torch.tensor(data['attention_mask'])\n        if y is None:\n            dataset = torch.utils.data.TensorDataset(indices, mask)\n        else:\n            self.classes_ = sorted(set(y))\n            self.n_classes_ = len(self.classes_)\n            class2index = dict(zip(self.classes_, range(self.n_classes_)))\n            y = [class2index[label] for label in y]\n            y = torch.tensor(y)\n            dataset = torch.utils.data.TensorDataset(indices, mask, y)\n        return dataset\n```\n\n#### HfBertClassifier experiment\n\nThat's it! Let's see how we do on the SST binary, root-only problem. Because fine-tuning is expensive, we'll conduct a modest hyperparameter search and run the model for just one epoch per setting evaluation, as we did when [assessing NLI models](nli_02_models.ipynb).\n\n\n```python\ndef bert_fine_tune_phi(tree):\n    return \" \".join(tree.leaves())\n```\n\n\n```python\ndef fit_hf_bert_classifier_with_hyperparameter_search(X, y):\n    basemod = HfBertClassifier(\n        weights_name='bert-base-cased',\n        batch_size=8,  # Small batches to avoid memory overload.\n        max_iter=1,  # We'll search based on 1 iteration for efficiency.\n        n_iter_no_change=5,   # Early-stopping params are for the\n        early_stopping=True)  # final evaluation.\n\n    param_grid = {\n        'gradient_accumulation_steps': [1, 4, 8],\n        'eta': [0.00005, 0.0001, 0.001],\n        'hidden_dim': [100, 200, 300]}\n\n    bestmod = utils.fit_classifier_with_hyperparameter_search(\n        X, y, basemod, cv=3, param_grid=param_grid)\n\n    return bestmod\n```\n\n\n```python\n%%time\nhf_bert_classifier_xval = sst.experiment(\n    SST_HOME,\n    bert_fine_tune_phi,\n    fit_hf_bert_classifier_with_hyperparameter_search,\n    train_reader=sst.train_reader,\n    assess_reader=sst.dev_reader,\n    class_func=sst.binary_class_func,\n    vectorize=False)  # Pass in the BERT hidden state directly!\n```\n\n    Finished epoch 1 of 1; error is 38.469218485057354\n\n    Best params: {'eta': 5e-05, 'gradient_accumulation_steps': 8, 'hidden_dim': 300}\n    Best score: 0.892\n                  precision    recall  f1-score   support\n    \n        negative      0.953     0.808     0.875       428\n        positive      0.839     0.962     0.896       444\n    \n        accuracy                          0.886       872\n       macro avg      0.896     0.885     0.885       872\n    weighted avg      0.895     0.886     0.886       872\n    \n    CPU times: user 1h 31min 39s, sys: 4min 6s, total: 1h 35min 46s\n    Wall time: 1h 36min 43s\n\n\nAnd now on to the final test-set evaluation, using the best model from above:\n\n\n```python\noptimized_hf_bert_classifier = hf_bert_classifier_xval['model']\n```\n\n\n```python\n# Remove the rest of the experiment results to clear out some memory:\ndel hf_bert_classifier_xval\n```\n\n\n```python\ndef fit_optimized_hf_bert_classifier(X, y):\n    optimized_hf_bert_classifier.max_iter = 1000\n    optimized_hf_bert_classifier.fit(X, y)\n    return optimized_hf_bert_classifier\n```\n\n\n```python\n%%time\n_ = sst.experiment(\n    SST_HOME,\n    bert_fine_tune_phi,\n    fit_optimized_hf_bert_classifier,\n    train_reader=(sst.train_reader, sst.dev_reader),\n    assess_reader=sst.test_reader,\n    class_func=sst.binary_class_func,\n    vectorize=False)  # Pass in the BERT hidden state directly!\n```\n\n    Stopping after epoch 10. Validation score did not improve by tol=1e-05 for more than 5 epochs. Final error is 0.964973742607981\n\n                  precision    recall  f1-score   support\n    \n        negative      0.890     0.928     0.908       912\n        positive      0.924     0.884     0.904       909\n    \n        accuracy                          0.906      1821\n       macro avg      0.907     0.906     0.906      1821\n    weighted avg      0.907     0.906     0.906      1821\n    \n    CPU times: user 13min 12s, sys: 17.4 s, total: 13min 29s\n    Wall time: 13min 29s\n\n\nThe above is just one of the many possible ways to fine-tune BERT using our course modules or new modules you write. The crux of it is creating an `nn.Module` that combines the BERT parameters with your model's new parameters.\n\n## Using ELMo\n\n### ELMo Allen NLP set-up\n\nThere are a number of ways to use pre-trained ELMo models. We'll use the simplest of the AllenNLP interfaces. Run the following to install [AllenNLP](https://allennlp.org):\n\n```sh\npip install allennlp\n```\nI've tested this notebook with versions, 0.8.0, 0.9.0, and 1.0.0.\n\nMac users: If your installation fails, make sure your Xcode tools are up to date by running `xcode-select --install`.\n\n\n```python\nfrom allennlp.modules.elmo import Elmo, batch_to_ids\nimport torch\nimport torch.nn as nn\n```\n\nWe'll use the following models, which will download from S3 to a local temp directory the first time you use them with `ElmoEmbedder` or `Elmo` as described below.\n\n\n```python\nelmo_file_path = \"https://allennlp.s3.amazonaws.com/models/elmo/2x4096_512_2048cnn_2xhighway/\"\n\noptions_file = elmo_file_path + \"elmo_2x4096_512_2048cnn_2xhighway_options.json\"\n\nweights_file = elmo_file_path + \"elmo_2x4096_512_2048cnn_2xhighway_weights.hdf5\"\n```\n\nFor more models:\n\nhttps://allennlp.org/elmo\n\nFor additional details:\n\nhttps://docs.allennlp.org/master/api/modules/elmo/\n\n### ELMo fine-tuning\n\nFine-tuning ELMo proceeds in essentially the same way it did for BERT: we create an `nn.Module` that combines the parameters from ELMo with our task-specific parameters and then optimize everything on the new task. To illustrate, I'll define an RNN on top of the ELMo model using new subclasses of `TorchRNNClassifier` and `TorchRNNClassifierModel`.\n\n#### AllenNLP ELMo interfaces\n\nTo start, let's get a feel for the primary interface, and then we'll write the classes that will allow us to use these components systematically.\n\nThe interface to the ELMo parameters in this context is the class `Elmo`:\n\n\n```python\nelmo = Elmo(options_file, weights_file, num_output_representations=1)\n```\n\nThis model expects tokenized inputs:\n\n\n```python\nelmo_example_texts = [\n    [\"Encode\", \"sentence\", \"1\", \".\"],\n    [\"ELMo\", \"knows\" \"Snuffleupagus\"]]\n```\n\nThe ELMo model processes its tokens at the character-level, creating convolutional representations for the words from various character n-gram combinations:\n\n\n```python\nelmo_character_ids = batch_to_ids(elmo_example_texts)\n\n# First word of the first example:\nelmo_character_ids[0][0]\n```\n\n\n\n\n    tensor([259,  70, 111, 100, 112, 101, 102, 260, 261, 261, 261, 261, 261, 261,\n            261, 261, 261, 261, 261, 261, 261, 261, 261, 261, 261, 261, 261, 261,\n            261, 261, 261, 261, 261, 261, 261, 261, 261, 261, 261, 261, 261, 261,\n            261, 261, 261, 261, 261, 261, 261, 261])\n\n\n\n`elmo` embeds these at the word-level:\n\n\n```python\nelmo_embeddings = elmo(elmo_character_ids)\n```\n\n`elmo_embeddings` is a dict. The value of the key `'elmo_representations'` is a list of tensors corresponding to each layer of the model. In other words, each tensor in the list is a complete representation of the example. The final element of the list is the final representation layer. I specified `num_output_representations=1` when initializing `elmo` above, so we get a list of length 1:\n\n\n```python\nelmo_embeddings['elmo_representations']\n```\n\n\n\n\n    [tensor([[[-0.7944,  0.0000,  0.0000,  ..., -0.0000, -0.0000, -1.9283],\n              [-0.0000,  1.1850,  0.6947,  ...,  0.0000, -0.9297, -0.2358],\n              [ 0.0000,  0.5358,  0.7767,  ..., -0.6500, -0.0777, -0.4875],\n              [-0.0000, -0.4965, -0.0000,  ..., -0.1605,  0.0000,  0.2256]],\n     \n             [[ 0.4553, -0.0000,  0.0000,  ..., -0.0000, -0.0000, -0.5380],\n              [ 0.0000, -0.5309, -0.0000,  ..., -0.2244, -0.0000,  0.7476],\n              [ 0.0000,  0.0000,  0.0000,  ...,  0.0000,  0.0000,  0.0000],\n              [ 0.0000,  0.0000,  0.0000,  ...,  0.0000,  0.0000,  0.0000]]],\n            grad_fn=<MulBackward0>)]\n\n\n\n#### ElmoRNNClassifier\n\nThe above are the representations we will be fine-tuning. There are many ways to cdo this. In my simple illustration, I just take the top layer, as we did in the simpler featurization example above, but now keeping each word representation separate for use in the input to the task-specific RNN. Here is the `nn.Module` built on `TorchRNNClassifierModel`:\n\n\n```python\nclass ElmoRNNClassifierModel(TorchRNNClassifierModel):\n    def __init__(self,\n            options_file,\n            weights_file,\n            rnn,\n            output_dim,\n            classifier_activation):\n        super().__init__(rnn, output_dim, classifier_activation)\n        self.options_file = options_file\n        self.weights_file = weights_file\n        self.elmo = Elmo(\n            self.options_file,\n            self.weights_file,\n            num_output_representations=1,\n            dropout=0)\n        self.elmo.train()\n\n    def forward(self, X, seq_lengths):\n        result = self.elmo(X)\n        X = result['elmo_representations'][-1]\n        outputs, state  = self.rnn(X, seq_lengths)\n        state = self.get_batch_final_states(state)\n        if self.rnn.bidirectional:\n            state = torch.cat((state[0], state[1]), dim=1)\n        h = self.classifier_activation(self.hidden_layer(state))\n        logits = self.classifier_layer(h)\n        return logits\n```\n\nAnd here is the subclass of `TorchRNNClassifier` that lets us take advantage of all the optimization and prediction methods of that class:\n\n\n```python\nclass ElmoRNNClassifier(TorchRNNClassifier):\n    def __init__(self, vocab, options_file, weights_file, **model_kwargs):\n        self.options_file = options_file\n        self.weights_file = weights_file\n        # Values determined by using ELMo:\n        model_kwargs['use_embedding'] = False\n        model_kwargs['embedding'] = None\n        model_kwargs['embed_dim'] = 1024\n        super().__init__(vocab, **model_kwargs)\n        self.params += ['options_file', 'weights_file']\n\n    def build_graph(self):\n\n        # The RNN is setup just as in a regular `TorchRNNClassifier`:\n        rnn = TorchRNNModel(\n            vocab_size=len(self.vocab),\n            embedding=self.embedding,\n            use_embedding=self.use_embedding,\n            embed_dim=self.embed_dim,\n            rnn_cell_class=self.rnn_cell_class,\n            hidden_dim=self.hidden_dim,\n            bidirectional=self.bidirectional,\n            freeze_embedding=self.freeze_embedding)\n\n        # The Classifier layer uses our new `ElmoRNNClassifierModel`:\n        model = ElmoRNNClassifierModel(\n            options_file=self.options_file,\n            weights_file=self.weights_file,\n            rnn=rnn,\n            output_dim=self.n_classes_,\n            classifier_activation=self.classifier_activation)\n\n        return model\n\n    def build_dataset(self, X, y=None):\n        seq_lengths = [len(ex) for ex in X]\n        seq_lengths = torch.tensor(seq_lengths)\n        X = batch_to_ids(X)\n        if y is None:\n            return torch.utils.data.TensorDataset(X, seq_lengths)\n        else:\n            self.classes_ = sorted(set(y))\n            self.n_classes_ = len(self.classes_)\n            class2index = dict(zip(self.classes_, range(self.n_classes_)))\n            y = [class2index[label] for label in y]\n            y = torch.tensor(y)\n            return torch.utils.data.TensorDataset(X, seq_lengths, y)\n```\n\n#### ElmoRNNClassifier experiment\n\nAnd finally here is a self-contained evaluation involving a modest hyperparameter search:\n\n\n```python\ndef elmo_fine_tune_phi(tree):\n    return tree.leaves()\n```\n\n\n```python\ndef fit_elmo_rnn_with_hyperparameter_search(X, y):\n    basemod = ElmoRNNClassifier(\n        vocab=[],\n        options_file=options_file,\n        weights_file=weights_file,\n        batch_size=8,  # Kept small so that we can explore large networks.\n        max_iter=1,  # We'll search based on 1 iteration for efficiency.\n        n_iter_no_change=5,   # Early-stopping params are for the\n        early_stopping=True)  # final evalution.\n\n    param_grid = {\n        'gradient_accumulation_steps': [1, 4, 8],\n        'eta': [0.001, 0.01, 0.05],\n        'hidden_dim': [50, 100, 200]}\n\n    bestmod = utils.fit_classifier_with_hyperparameter_search(\n        X, y, basemod, cv=3, param_grid=param_grid)\n\n    return bestmod\n```\n\n\n```python\n%%time\nelmo_rnn_xval = sst.experiment(\n    SST_HOME,\n    elmo_fine_tune_phi,\n    fit_elmo_rnn_with_hyperparameter_search,\n    train_reader=sst.train_reader,\n    assess_reader=sst.dev_reader,\n    class_func=sst.binary_class_func,\n    vectorize=False)  # Pass in the ELMo reps directly!\n```\n\n    Finished epoch 1 of 1; error is 330.32408917695284\n\n    Best params: {'eta': 0.001, 'gradient_accumulation_steps': 1, 'hidden_dim': 200}\n    Best score: 0.856\n                  precision    recall  f1-score   support\n    \n        negative      0.848     0.848     0.848       428\n        positive      0.854     0.854     0.854       444\n    \n        accuracy                          0.851       872\n       macro avg      0.851     0.851     0.851       872\n    weighted avg      0.851     0.851     0.851       872\n    \n    CPU times: user 2h 4min 55s, sys: 4min 16s, total: 2h 9min 12s\n    Wall time: 2h 1min 35s\n\n\nAnd now we move to the test-set evaluation using the best model we found:\n\n\n```python\noptimized_elmo_rnn = elmo_rnn_xval['model']\n```\n\n\n```python\n# Remove the unneeded experimental data to save memory:\ndel elmo_rnn_xval\n```\n\n\n```python\ndef fit_optimized_elmo_rnn(X, y):\n    optimized_elmo_rnn.max_iter = 20\n    optimized_elmo_rnn.fit(X, y)\n    return optimized_elmo_rnn\n```\n\n\n```python\n%%time\n_ = sst.experiment(\n    SST_HOME,\n    elmo_fine_tune_phi,\n    fit_optimized_elmo_rnn,\n    train_reader=(sst.train_reader, sst.dev_reader),\n    assess_reader=sst.test_reader,\n    class_func=sst.binary_class_func,\n    vectorize=False)  # Pass in the BERT hidden state directly!\n```\n\n    Stopping after epoch 10. Validation score did not improve by tol=1e-05 for more than 5 epochs. Final error is 27.70847176760435\n\n                  precision    recall  f1-score   support\n    \n        negative      0.891     0.880     0.886       912\n        positive      0.882     0.892     0.887       909\n    \n        accuracy                          0.886      1821\n       macro avg      0.886     0.886     0.886      1821\n    weighted avg      0.886     0.886     0.886      1821\n    \n    CPU times: user 15min 31s, sys: 34.3 s, total: 16min 6s\n    Wall time: 16min\n\n", "meta": {"hexsha": "41565a2690556cd599ea705f63762d0163f130ff", "size": 48996, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "contextualreps.ipynb", "max_stars_repo_name": "joaoavf/CS224U", "max_stars_repo_head_hexsha": "3cd4d1809335f15d5454fe27222900096ae94414", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-16T01:52:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-16T01:52:51.000Z", "max_issues_repo_path": "contextualreps.ipynb", "max_issues_repo_name": "joaoavf/CS224U", "max_issues_repo_head_hexsha": "3cd4d1809335f15d5454fe27222900096ae94414", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "contextualreps.ipynb", "max_forks_repo_name": "joaoavf/CS224U", "max_forks_repo_head_hexsha": "3cd4d1809335f15d5454fe27222900096ae94414", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-21T06:17:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T06:17:47.000Z", "avg_line_length": 31.0691185796, "max_line_length": 539, "alphanum_fraction": 0.5595354723, "converted": true, "num_tokens": 8519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27202455699569283, "lm_q2_score": 0.10087862205427303, "lm_q1q2_score": 0.027441462474649552}}
{"text": "# Markdown command : \n\n<b> Commands </b> <br> \n\n<b> - Esc : command mode </b> <br>\n- esc H -> show shortcuts\n- esc Y -> cell to code\n- esc M -> cell to markdown <br><br>\n- esc C -> copy cell\n- esc shift-V / V -> paste cell above / below\n- esc A/B -> insert cell above / below <br><br>\n- esc shift Q -> clear o/p\n- esc O -> toggle cell o/p <br><br>\n- esc L / esc shift-L -> show line number / all line number\n- esc F -> find and replace <br><br>\n- esc D-D -> delete cell\n- esc Z -> undo delete cell <br><br>\n<b> Custom </b> <br>\n- esc q-q -> shutdown\n\n<b> - Edit mode: </b> <br>\n- enter (from command mode)\n- ctrl-shift-minus (split cell at cursor)\n\n#### Markdwon and Latex \n\n`| This | is   |\n|------|------|\n|   a  | table|`\n\n\n---------------\n\n| This | is   |\n|------|------|\n|   a  | table|\n\n\n\n\\`\\`\\`python (language) Your-text \\`\\`\\`\n\n```javascript\nconsole.log(\"Hello World\")\n```\n\n```python\nconsole.log(\"Hello World\")\n```\n\n\n\n```\n\n\n\n\n<video controls src=\"../images/animation.m4v\" />\n```\n\n<b>Or </b> <br>\n```python\nfrom IPython.display import Image\nImage(filename='output1.png')\n```\n\n- Inline expressions can be added by surrounding the latex code with \\$: \n- \\$\\$ <- moves to center\n\n``` $e^{i\\pi} + 1 = 0$```\n\n$$e^{i\\pi} + 1 = 0$$\n\n```$$e^x=\\sum_{i=0}^\\infty \\frac{1}{i!}x^i$$```\n\n$$e^x=\\sum_{i=0}^\\infty \\frac{1}{i!}x^i$$\n\n```\\begin{align}\n\\dot{x} & = \\sigma(y-x) \\\\\n\\dot{y} & = \\rho x - y - xz \\\\\n\\dot{z} & = -\\beta z + xy\n\\end{align} ```\n\n\n\\begin{align}\n\\dot{x} & = \\sigma(y-x) \\\\\n\\dot{y} & = \\rho x - y - xz \\\\\n\\dot{z} & = -\\beta z + xy\n\\end{align}\n\n```\\begin{equation*}\n\\left( \\sum_{k=1}^n a_k b_k \\right)^2 \\leq \\left( \\sum_{k=1}^n a_k^2 \\right) \\left( \\sum_{k=1}^n b_k^2 \\right)\n\\end{equation*}```\n\n\\begin{equation*}\n\\left( \\sum_{k=1}^n a_k b_k \\right)^2 \\leq \\left( \\sum_{k=1}^n a_k^2 \\right) \\left( \\sum_{k=1}^n b_k^2 \\right)\n\\end{equation*}\n\n#### Matrix\n\n```\\begin{equation*}\n\\mathbf{V}_1 \\times \\mathbf{V}_2 =  \\begin{vmatrix}\n\\mathbf{i} & \\mathbf{j} & \\mathbf{k} \\\\\n\\frac{\\partial X}{\\partial u} &  \\frac{\\partial Y}{\\partial u} & 0 \\\\\n\\frac{\\partial X}{\\partial v} &  \\frac{\\partial Y}{\\partial v} & 0\n\\end{vmatrix}\n\\end{equation*}```\n\n<br> <br>\n\n\n\\begin{equation*}\n\\mathbf{V}_1 \\times \\mathbf{V}_2 =  \\begin{vmatrix}\n\\mathbf{i} & \\mathbf{j} & \\mathbf{k} \\\\\n\\frac{\\partial X}{\\partial u} &  \\frac{\\partial Y}{\\partial u} & 0 \\\\\n\\frac{\\partial X}{\\partial v} &  \\frac{\\partial Y}{\\partial v} & 0\n\\end{vmatrix}\n\\end{equation*}\n\n\n- begin{vmatrix} -> matrix\n- & separates the column and \"\\\\\\\" separates row\n\n#### Probability\n\n```\\begin{equation*}\nP(E)   = {n \\choose k} p^k (1-p)^{ n-k}\n\\end{equation*}```\n\n\\begin{equation*}\nP(E)   = {n \\choose k} p^k (1-p)^{ n-k}\n\\end{equation*}\n\n#### Trival\n\n```\\begin{equation*}\n\\frac{1}{\\Bigl(\\sqrt{\\phi \\sqrt{5}}-\\phi\\Bigr) e^{\\frac25 \\pi}} =\n1+\\frac{e^{-2\\pi}} {1+\\frac{e^{-4\\pi}} {1+\\frac{e^{-6\\pi}}\n{1+\\frac{e^{-8\\pi}} {1+\\ldots} } } }\n\\end{equation*}```\n\n\\begin{equation*}\n\\frac{1}{\\Bigl(\\sqrt{\\phi \\sqrt{5}}-\\phi\\Bigr) e^{\\frac25 \\pi}} =\n1+\\frac{e^{-2\\pi}} {1+\\frac{e^{-4\\pi}} {1+\\frac{e^{-6\\pi}}\n{1+\\frac{e^{-8\\pi}} {1+\\ldots} } } }\n\\end{equation*}\n\n#### Text in equation\n\n```\\begin{equation*}\n1 +  \\frac{q^2}{(1-q)}+\\frac{q^6}{(1-q)(1-q^2)}+\\cdots =\n\\prod_{j=0}^{\\infty}\\frac{1}{(1-q^{5j+2})(1-q^{5j+3})},\n\\quad\\quad \\text{for $|q|<1$}.\n\\end{equation*}```\n\n\\begin{equation*}\n1 +  \\frac{q^2}{(1-q)}+\\frac{q^6}{(1-q)(1-q^2)}+\\cdots =\n\\prod_{j=0}^{\\infty}\\frac{1}{(1-q^{5j+2})(1-q^{5j+3})},\n\\quad\\quad \\text{for $|q|<1$}.\n\\end{equation*}\n\n#### Derivative eqn and matrix operators \n\n```\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\   \\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align} ```\n\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\   \\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n\n- vector -> vec\n- bold -> mathbf\n- \\, (comma) -> space\n\n\n```\\begin{align}\n\\nabla \\cdot \\,\\,\\,\\,\\,\\,\\,\\, \\vec{\\mathbf{B}}  &= 0\n\\end{align}```\n\n\\begin{align}\n\\nabla \\cdot \\,\\,\\,\\,\\,\\,\\,\\, \\vec{\\mathbf{B}}  &= 0\n\\end{align}\n\n#### Inline expression and sentencing\n```This expression $\\sqrt{3x-1}+(1+x)^2$ is an example of a TeX inline equation in a [Markdown-formatted](https://daringfireball.net/projects/markdown/) sentence.```\n\nThis expression $\\sqrt{3x-1}+(1+x)^2$ is an example of a TeX inline equation in a [Markdown-formatted](https://daringfireball.net/projects/markdown/) sentence.\n\n#### Other example \n```$$x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}$$```\n<br><br><br>\n\n\n$$x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}$$\n\n#### Other example \n\n```$$x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}$$```\n<br><br><br>\n\n\n$$x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}$$\n\n\n```$$f(a) = \\frac{1}{2\\pi i} \\oint\\frac{f(z)}{z-a}dz$$```\n<br><br><br>\n\n\n$$f(a) = \\frac{1}{2\\pi i} \\oint\\frac{f(z)}{z-a}dz$$\n\n\n\n```$$\\int_D ({\\nabla\\cdot} F)dV=\\int_{\\partial D} F\\cdot ndS$$```\n<br><br><br>\n\n\n$$\\int_D ({\\nabla\\cdot} F)dV=\\int_{\\partial D} F\\cdot ndS$$\n\n<b> - int_{lower}^{upper} </b>\n\n\n```$$\\int_{a}^{b} x^2 dx$$```\n$$\\int_{a}^{b} x^2 dx$$\n\n```$$\\vec{\\nabla} \\times \\vec{F} = \\left( \\frac{\\partial F_z}{\\partial y} - \\frac{\\partial F_y}{\\partial z} \\right) \\mathbf{i}\n        + \\left( \\frac{\\partial F_x}{\\partial z} - \\frac{\\partial F_z}{\\partial x} \\right) \\mathbf{j} + \\left( \\frac{\\partial\n        F_y}{\\partial x} - \\frac{\\partial F_x}{\\partial y} \\right) \\mathbf{k}$$```\n\n$$\\vec{\\nabla} \\times \\vec{F} = \\left( \\frac{\\partial F_z}{\\partial y} - \\frac{\\partial F_y}{\\partial z} \\right) \\mathbf{i}\n        + \\left( \\frac{\\partial F_x}{\\partial z} - \\frac{\\partial F_z}{\\partial x} \\right) \\mathbf{j} + \\left( \\frac{\\partial\n        F_y}{\\partial x} - \\frac{\\partial F_x}{\\partial y} \\right) \\mathbf{k}$$\n        \n<b> - (left / right) <- brackets </b>\n$$\\left( hello \\right)$$\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "0cd7d010a02ff65bb3ad3a63feee76255654767b", "size": 10514, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Markdown commands and symbols.ipynb", "max_stars_repo_name": "Zhengrong34/Random", "max_stars_repo_head_hexsha": "77098f08c2833fcdc63bfe859f6baecde5122eb5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-27T06:53:33.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-27T06:53:33.000Z", "max_issues_repo_path": "Markdown commands and symbols.ipynb", "max_issues_repo_name": "Zhengrong34/Random", "max_issues_repo_head_hexsha": "77098f08c2833fcdc63bfe859f6baecde5122eb5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Markdown commands and symbols.ipynb", "max_forks_repo_name": "Zhengrong34/Random", "max_forks_repo_head_hexsha": "77098f08c2833fcdc63bfe859f6baecde5122eb5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2055555556, "max_line_length": 211, "alphanum_fraction": 0.4317101008, "converted": true, "num_tokens": 2565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.09401017517449256, "lm_q1q2_score": 0.02735516220528897}}
{"text": "```python\n%matplotlib inline\n```\n\n\n\nTutorial: Generative models of graphs\n===========================================\n\n**Author**: `Mufei Li <https://github.com/mufeili>`_,\n`Lingfan Yu <https://github.com/ylfdq1118>`_, Zheng Zhang\n\n\nIn this tutorial, you learn how to train and generate one graph at\na time. You also explore parallelism within the graph embedding operation, which is an\nessential building block. The tutorial ends with a simple optimization that\ndelivers double the speed by batching across graphs.\n\nEarlier tutorials showed how embedding a graph or\na node enables you to work on tasks such as `semi-supervised classification for nodes\n<http://docs.dgl.ai/tutorials/models/1_gcn.html#sphx-glr-tutorials-models-1-gcn-py>`__\nor `sentiment analysis\n<http://docs.dgl.ai/tutorials/models/3_tree-lstm.html#sphx-glr-tutorials-models-3-tree-lstm-py>`__.\nWouldn't it be interesting to predict the future evolution of the graph and\nperform the analysis iteratively?\n\nTo address the evolution of the graphs, you generate a variety of graph samples. In other words, you need\n**generative models** of graphs. In-addition to learning\nnode and edge features, you would need to model the distribution of arbitrary graphs.\nWhile general generative models can model the density function explicitly and\nimplicitly and generate samples at once or sequentially, you only focus\non explicit generative models for sequential generation here. Typical applications\ninclude drug or materials discovery, chemical processes, or proteomics.\n\nIntroduction\n--------------------\nThe primitive actions of mutating a graph in Deep Graph Library (DGL) are nothing more than ``add_nodes``\nand ``add_edges``. That is, if you were to draw a circle of three nodes,\n\n.. figure:: https://user-images.githubusercontent.com/19576924/48313438-78baf000-e5f7-11e8-931e-cd00ab34fa50.gif\n   :alt:\n\nyou can write the code as follows.\n\n\n\n\n\n```python\nimport dgl\n\ng = dgl.DGLGraph()\ng.add_nodes(1)              # Add node 0\ng.add_nodes(1)              # Add node 1\n\n# Edges in DGLGraph are directed by default.\n# For undirected edges, add edges for both directions.\ng.add_edges([1, 0], [0, 1]) # Add edges (1, 0), (0, 1)\ng.add_nodes(1)              # Add node 2\ng.add_edges([2, 1], [1, 2]) # Add edges (2, 1), (1, 2)\ng.add_edges([2, 0], [0, 2]) # Add edges (2, 0), (0, 2)\n```\n\n    Using backend: pytorch\n    /home/viktor/anaconda3/envs/dgl/lib/python3.8/site-packages/dgl/base.py:45: DGLWarning: Recommend creating graphs by `dgl.graph(data)` instead of `dgl.DGLGraph(data)`.\n      return warnings.warn(message, category=category, stacklevel=1)\n\n\nReal-world graphs are much more complex. There are many families of graphs,\nwith different sizes, topologies, node types, edge types, and the possibility\nof multigraphs. Besides, a same graph can be generated in many different\norders. Regardless, the generative process entails a few steps.\n\n- Encode a changing graph.\n- Perform actions stochastically.\n- If you are training, collect error signals and optimize the model parameters.\n\nWhen it comes to implementation, another important aspect is speed. How do you\nparallelize the computation, given that generating a graph is fundamentally a\nsequential process?\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>To be sure, this is not necessarily a hard constraint. Subgraphs can be \n   built in parallel and then get assembled. But we\n   will restrict ourselves to the sequential processes for this tutorial.</p></div>\n\n\nDGMG: The main flow\n--------------------\nFor this tutorial, you use \n`Deep Generative Models of Graphs <https://arxiv.org/abs/1803.03324>`__\n) (DGMG) to implement a graph generative model using DGL. Its algorithmic \nframework is general but also challenging to parallelize.\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>While it's possible for DGMG to handle complex graphs with typed nodes,\n   typed edges, and multigraphs, here you use a simplified version of it\n   for generating graph topologies.</p></div>\n\nDGMG generates a graph by following a state machine, which is basically a\ntwo-level loop. Generate one node at a time and connect it to a subset of\nthe existing nodes, one at a time. This is similar to language modeling. The\ngenerative process is an iterative one that emits one word or character or sentence\nat a time, conditioned on the sequence generated so far.\n\nAt each time step, you either:\n     - Add a new node to the graph\n     - Select two existing nodes and add an edge between them\n\n.. figure:: https://user-images.githubusercontent.com/19576924/48605003-7f11e900-e9b6-11e8-8880-87362348e154.png\n   :alt:\n\nThe Python code will look as follows. In fact, this is *exactly* how inference\nwith DGMG is implemented in DGL.\n\n\n\n\n\n```python\ndef forward_inference(self):\n    stop = self.add_node_and_update()\n    while (not stop) and (self.g.number_of_nodes() < self.v_max + 1):\n        num_trials = 0\n        to_add_edge = self.add_edge_or_not()\n        while to_add_edge and (num_trials < self.g.number_of_nodes() - 1):\n            self.choose_dest_and_update()\n            num_trials += 1\n            to_add_edge = self.add_edge_or_not()\n        stop = self.add_node_and_update()\n\n    return self.g\n```\n\nAssume you have a pre-trained model for generating cycles of nodes 10-20.\nHow does it generate a cycle on-the-fly during inference? Use the code below\nto create an animation with your own model.\n\n::\n\n    import torch\n    import matplotlib.animation as animation\n    import matplotlib.pyplot as plt\n    import networkx as nx\n    from copy import deepcopy\n\n    if __name__ == '__main__':\n        # pre-trained model saved with path ./model.pth\n        model = torch.load('./model.pth')\n        model.eval()\n        g = model()\n\n        src_list = g.edges()[1]\n        dest_list = g.edges()[0]\n\n        evolution = []\n\n        nx_g = nx.Graph()\n        evolution.append(deepcopy(nx_g))\n\n        for i in range(0, len(src_list), 2):\n            src = src_list[i].item()\n            dest = dest_list[i].item()\n            if src not in nx_g.nodes():\n                nx_g.add_node(src)\n                evolution.append(deepcopy(nx_g))\n            if dest not in nx_g.nodes():\n                nx_g.add_node(dest)\n                evolution.append(deepcopy(nx_g))\n            nx_g.add_edges_from([(src, dest), (dest, src)])\n            evolution.append(deepcopy(nx_g))\n\n        def animate(i):\n            ax.cla()\n            g_t = evolution[i]\n            nx.draw_circular(g_t, with_labels=True, ax=ax,\n                             node_color=['#FEBD69'] * g_t.number_of_nodes())\n\n        fig, ax = plt.subplots()\n        ani = animation.FuncAnimation(fig, animate,\n                                      frames=len(evolution),\n                                      interval=600)\n\n.. figure:: https://user-images.githubusercontent.com/19576924/48928548-2644d200-ef1b-11e8-8591-da93345382ad.gif\n   :alt:\n\nDGMG: Optimization objective\n------------------------------\nSimilar to language modeling, DGMG trains the model with *behavior cloning*,\nor *teacher forcing*. Assume for each graph there exists a sequence of\n*oracle actions* $a_{1},\\cdots,a_{T}$ that generates it. What the model\ndoes is to follow these actions, compute the joint probabilities of such\naction sequences, and maximize them.\n\nBy chain rule, the probability of taking $a_{1},\\cdots,a_{T}$ is:\n\n\\begin{align}p(a_{1},\\cdots, a_{T}) = p(a_{1})p(a_{2}|a_{1})\\cdots p(a_{T}|a_{1},\\cdots,a_{T-1}).\\\\\\end{align}\n\nThe optimization objective is then simply the typical MLE loss:\n\n\\begin{align}-\\log p(a_{1},\\cdots,a_{T})=-\\sum_{t=1}^{T}\\log p(a_{t}|a_{1},\\cdots, a_{t-1}).\\\\\\end{align}\n\n\n\n\n\n```python\ndef forward_train(self, actions):\n    \"\"\"\n    - actions: list\n        - Contains a_1, ..., a_T described above\n    - self.prepare_for_train()\n        - Initializes self.action_step to be 0, which will get\n          incremented by 1 every time it is called.\n        - Initializes objects recording log p(a_t|a_1,...a_{t-1})\n\n    Returns\n    -------\n    - self.get_log_prob(): log p(a_1, ..., a_T)\n    \"\"\"\n    self.prepare_for_train()\n\n    stop = self.add_node_and_update(a=actions[self.action_step])\n    while not stop:\n        to_add_edge = self.add_edge_or_not(a=actions[self.action_step])\n        while to_add_edge:\n            self.choose_dest_and_update(a=actions[self.action_step])\n            to_add_edge = self.add_edge_or_not(a=actions[self.action_step])\n        stop = self.add_node_and_update(a=actions[self.action_step])\n\n    return self.get_log_prob()\n```\n\nThe key difference between ``forward_train`` and ``forward_inference`` is\nthat the training process takes oracle actions as input and returns log\nprobabilities for evaluating the loss.\n\nDGMG: The implementation\n--------------------------\nThe ``DGMG`` class\n``````````````````````````\nBelow you can find the skeleton code for the model. You gradually\nfill in the details for each function.\n\n\n\n\n\n```python\nimport torch.nn as nn\n\n\nclass DGMGSkeleton(nn.Module):\n    def __init__(self, v_max):\n        \"\"\"\n        Parameters\n        ----------\n        v_max: int\n            Max number of nodes considered\n        \"\"\"\n        super(DGMGSkeleton, self).__init__()\n\n        # Graph configuration\n        self.v_max = v_max\n\n    def add_node_and_update(self, a=None):\n        \"\"\"Decide if to add a new node.\n        If a new node should be added, update the graph.\"\"\"\n        return NotImplementedError\n\n    def add_edge_or_not(self, a=None):\n        \"\"\"Decide if a new edge should be added.\"\"\"\n        return NotImplementedError\n\n    def choose_dest_and_update(self, a=None):\n        \"\"\"Choose destination and connect it to the latest node.\n        Add edges for both directions and update the graph.\"\"\"\n        return NotImplementedError\n\n    def forward_train(self, actions):\n        \"\"\"Forward at training time. It records the probability\n        of generating a ground truth graph following the actions.\"\"\"\n        return NotImplementedError\n\n    def forward_inference(self):\n        \"\"\"Forward at inference time.\n        It generates graphs on the fly.\"\"\"\n        return NotImplementedError\n\n    def forward(self, actions=None):\n        # The graph you will work on\n        self.g = dgl.DGLGraph()\n\n        # If there are some features for nodes and edges,\n        # zero tensors will be set for those of new nodes and edges.\n        self.g.set_n_initializer(dgl.frame.zero_initializer)\n        self.g.set_e_initializer(dgl.frame.zero_initializer)\n\n        if self.training:\n            return self.forward_train(actions=actions)\n        else:\n            return self.forward_inference()\n```\n\nEncoding a dynamic graph\n``````````````````````````\nAll the actions generating a graph are sampled from probability\ndistributions. In order to do that, you project the structured data,\nnamely the graph, onto an Euclidean space. The challenge is that such\nprocess, called *embedding*, needs to be repeated as the graphs mutate.\n\nGraph embedding\n''''''''''''''''''''''''''\nLet $G=(V,E)$ be an arbitrary graph. Each node $v$ has an\nembedding vector $\\textbf{h}_{v} \\in \\mathbb{R}^{n}$. Similarly,\nthe graph has an embedding vector $\\textbf{h}_{G} \\in \\mathbb{R}^{k}$.\nTypically, $k > n$ since a graph contains more information than\nan individual node.\n\nThe graph embedding is a weighted sum of node embeddings under a linear\ntransformation:\n\n\\begin{align}\\textbf{h}_{G} =\\sum_{v\\in V}\\text{Sigmoid}(g_m(\\textbf{h}_{v}))f_{m}(\\textbf{h}_{v}),\\\\\\end{align}\n\nThe first term, $\\text{Sigmoid}(g_m(\\textbf{h}_{v}))$, computes a\ngating function and can be thought of as how much the overall graph embedding\nattends on each node. The second term $f_{m}:\\mathbb{R}^{n}\\rightarrow\\mathbb{R}^{k}$\nmaps the node embeddings to the space of graph embeddings.\n\nImplement graph embedding as a ``GraphEmbed`` class.\n\n\n\n\n\n```python\nimport torch\n\n\nclass GraphEmbed(nn.Module):\n    def __init__(self, node_hidden_size):\n        super(GraphEmbed, self).__init__()\n\n        # Setting from the paper\n        self.graph_hidden_size = 2 * node_hidden_size\n\n        # Embed graphs\n        self.node_gating = nn.Sequential(\n            nn.Linear(node_hidden_size, 1),\n            nn.Sigmoid()\n        )\n        self.node_to_graph = nn.Linear(node_hidden_size,\n                                       self.graph_hidden_size)\n\n    def forward(self, g):\n        if g.number_of_nodes() == 0:\n            return torch.zeros(1, self.graph_hidden_size)\n        else:\n            # Node features are stored as hv in ndata.\n            hvs = g.ndata['hv']\n            return (self.node_gating(hvs) *\n                    self.node_to_graph(hvs)).sum(0, keepdim=True)\n```\n\nUpdate node embeddings via graph propagation\n'''''''''''''''''''''''''''''''''''''''''''''\n\nThe mechanism of updating node embeddings in DGMG is similar to that for\ngraph convolutional networks. For a node $v$ in the graph, its\nneighbor $u$ sends a message to it with\n\n\\begin{align}\\textbf{m}_{u\\rightarrow v}=\\textbf{W}_{m}\\text{concat}([\\textbf{h}_{v}, \\textbf{h}_{u}, \\textbf{x}_{u, v}]) + \\textbf{b}_{m},\\\\\\end{align}\n\nwhere $\\textbf{x}_{u,v}$ is the embedding of the edge between\n$u$ and $v$.\n\nAfter receiving messages from all its neighbors, $v$ summarizes them\nwith a node activation vector\n\n\\begin{align}\\textbf{a}_{v} = \\sum_{u: (u, v)\\in E}\\textbf{m}_{u\\rightarrow v}\\\\\\end{align}\n\nand use this information to update its own feature:\n\n\\begin{align}\\textbf{h}'_{v} = \\textbf{GRU}(\\textbf{h}_{v}, \\textbf{a}_{v}).\\\\\\end{align}\n\nPerforming all the operations above once for all nodes synchronously is\ncalled one round of graph propagation. The more rounds of graph propagation\nyou perform, the longer distance messages travel throughout the graph.\n\nWith DGL, you implement graph propagation with ``g.update_all``.\nThe message notation here can be a bit confusing. Researchers can refer\nto $\\textbf{m}_{u\\rightarrow v}$ as messages, however the message function\nbelow only passes $\\text{concat}([\\textbf{h}_{u}, \\textbf{x}_{u, v}])$.\nThe operation $\\textbf{W}_{m}\\text{concat}([\\textbf{h}_{v}, \\textbf{h}_{u}, \\textbf{x}_{u, v}]) + \\textbf{b}_{m}$\nis then performed across all edges at once for efficiency consideration.\n\n\n\n\n\n```python\nfrom functools import partial\n\nclass GraphProp(nn.Module):\n    def __init__(self, num_prop_rounds, node_hidden_size):\n        super(GraphProp, self).__init__()\n\n        self.num_prop_rounds = num_prop_rounds\n\n        # Setting from the paper\n        self.node_activation_hidden_size = 2 * node_hidden_size\n\n        message_funcs = []\n        node_update_funcs = []\n        self.reduce_funcs = []\n\n        for t in range(num_prop_rounds):\n            # input being [hv, hu, xuv]\n            message_funcs.append(nn.Linear(2 * node_hidden_size + 1,\n                                           self.node_activation_hidden_size))\n\n            self.reduce_funcs.append(partial(self.dgmg_reduce, round=t))\n            node_update_funcs.append(\n                nn.GRUCell(self.node_activation_hidden_size,\n                           node_hidden_size))\n\n        self.message_funcs = nn.ModuleList(message_funcs)\n        self.node_update_funcs = nn.ModuleList(node_update_funcs)\n\n    def dgmg_msg(self, edges):\n        \"\"\"For an edge u->v, return concat([h_u, x_uv])\"\"\"\n        return {'m': torch.cat([edges.src['hv'],\n                                edges.data['he']],\n                               dim=1)}\n\n    def dgmg_reduce(self, nodes, round):\n        hv_old = nodes.data['hv']\n        m = nodes.mailbox['m']\n        message = torch.cat([\n            hv_old.unsqueeze(1).expand(-1, m.size(1), -1), m], dim=2)\n        node_activation = (self.message_funcs[round](message)).sum(1)\n\n        return {'a': node_activation}\n\n    def forward(self, g):\n        if g.number_of_edges() > 0:\n            for t in range(self.num_prop_rounds):\n                g.update_all(message_func=self.dgmg_msg,\n                             reduce_func=self.reduce_funcs[t])\n                g.ndata['hv'] = self.node_update_funcs[t](\n                     g.ndata['a'], g.ndata['hv'])\n```\n\nActions\n``````````````````````````\nAll actions are sampled from distributions parameterized using neural networks\nand here they are in turn.\n\nAction 1: Add nodes\n''''''''''''''''''''''''''\n\nGiven the graph embedding vector $\\textbf{h}_{G}$, evaluate\n\n\\begin{align}\\text{Sigmoid}(\\textbf{W}_{\\text{add node}}\\textbf{h}_{G}+b_{\\text{add node}}),\\\\\\end{align}\n\nwhich is then used to parametrize a Bernoulli distribution for deciding whether\nto add a new node.\n\nIf a new node is to be added, initialize its feature with\n\n\\begin{align}\\textbf{W}_{\\text{init}}\\text{concat}([\\textbf{h}_{\\text{init}} , \\textbf{h}_{G}])+\\textbf{b}_{\\text{init}},\\\\\\end{align}\n\nwhere $\\textbf{h}_{\\text{init}}$ is a learnable embedding module for\nuntyped nodes.\n\n\n\n\n\n```python\nimport torch.nn.functional as F\nfrom torch.distributions import Bernoulli\n\ndef bernoulli_action_log_prob(logit, action):\n    \"\"\"Calculate the log p of an action with respect to a Bernoulli\n    distribution. Use logit rather than prob for numerical stability.\"\"\"\n    if action == 0:\n        return F.logsigmoid(-logit)\n    else:\n        return F.logsigmoid(logit)\n\nclass AddNode(nn.Module):\n    def __init__(self, graph_embed_func, node_hidden_size):\n        super(AddNode, self).__init__()\n\n        self.graph_op = {'embed': graph_embed_func}\n\n        self.stop = 1\n        self.add_node = nn.Linear(graph_embed_func.graph_hidden_size, 1)\n\n        # If to add a node, initialize its hv\n        self.node_type_embed = nn.Embedding(1, node_hidden_size)\n        self.initialize_hv = nn.Linear(node_hidden_size + \\\n                                       graph_embed_func.graph_hidden_size,\n                                       node_hidden_size)\n\n        self.init_node_activation = torch.zeros(1, 2 * node_hidden_size)\n\n    def _initialize_node_repr(self, g, node_type, graph_embed):\n        \"\"\"Whenver a node is added, initialize its representation.\"\"\"\n        num_nodes = g.number_of_nodes()\n        hv_init = self.initialize_hv(\n            torch.cat([\n                self.node_type_embed(torch.LongTensor([node_type])),\n                graph_embed], dim=1))\n        g.nodes[num_nodes - 1].data['hv'] = hv_init\n        g.nodes[num_nodes - 1].data['a'] = self.init_node_activation\n\n    def prepare_training(self):\n        self.log_prob = []\n\n    def forward(self, g, action=None):\n        graph_embed = self.graph_op['embed'](g)\n\n        logit = self.add_node(graph_embed)\n        prob = torch.sigmoid(logit)\n\n        if not self.training:\n            action = Bernoulli(prob).sample().item()\n        stop = bool(action == self.stop)\n\n        if not stop:\n            g.add_nodes(1)\n            self._initialize_node_repr(g, action, graph_embed)\n\n        if self.training:\n            sample_log_prob = bernoulli_action_log_prob(logit, action)\n\n            self.log_prob.append(sample_log_prob)\n\n        return stop\n```\n\nAction 2: Add edges\n''''''''''''''''''''''''''\n\nGiven the graph embedding vector $\\textbf{h}_{G}$ and the node\nembedding vector $\\textbf{h}_{v}$ for the latest node $v$,\nyou evaluate\n\n\\begin{align}\\text{Sigmoid}(\\textbf{W}_{\\text{add edge}}\\text{concat}([\\textbf{h}_{G}, \\textbf{h}_{v}])+b_{\\text{add edge}}),\\\\\\end{align}\n\nwhich is then used to parametrize a Bernoulli distribution for deciding\nwhether to add a new edge starting from $v$.\n\n\n\n\n\n```python\nclass AddEdge(nn.Module):\n    def __init__(self, graph_embed_func, node_hidden_size):\n        super(AddEdge, self).__init__()\n\n        self.graph_op = {'embed': graph_embed_func}\n        self.add_edge = nn.Linear(graph_embed_func.graph_hidden_size + \\\n                                  node_hidden_size, 1)\n\n    def prepare_training(self):\n        self.log_prob = []\n\n    def forward(self, g, action=None):\n        graph_embed = self.graph_op['embed'](g)\n        src_embed = g.nodes[g.number_of_nodes() - 1].data['hv']\n\n        logit = self.add_edge(torch.cat(\n            [graph_embed, src_embed], dim=1))\n        prob = torch.sigmoid(logit)\n\n        if self.training:\n            sample_log_prob = bernoulli_action_log_prob(logit, action)\n            self.log_prob.append(sample_log_prob)\n        else:\n            action = Bernoulli(prob).sample().item()\n\n        to_add_edge = bool(action == 0)\n        return to_add_edge\n```\n\nAction 3: Choose a destination\n'''''''''''''''''''''''''''''''''\n\nWhen action 2 returns `True`, choose a destination for the\nlatest node $v$.\n\nFor each possible destination $u\\in\\{0, \\cdots, v-1\\}$, the\nprobability of choosing it is given by\n\n\\begin{align}\\frac{\\text{exp}(\\textbf{W}_{\\text{dest}}\\text{concat}([\\textbf{h}_{u}, \\textbf{h}_{v}])+\\textbf{b}_{\\text{dest}})}{\\sum_{i=0}^{v-1}\\text{exp}(\\textbf{W}_{\\text{dest}}\\text{concat}([\\textbf{h}_{i}, \\textbf{h}_{v}])+\\textbf{b}_{\\text{dest}})}\\\\\\end{align}\n\n\n\n\n\n```python\nfrom torch.distributions import Categorical\n\nclass ChooseDestAndUpdate(nn.Module):\n    def __init__(self, graph_prop_func, node_hidden_size):\n        super(ChooseDestAndUpdate, self).__init__()\n\n        self.graph_op = {'prop': graph_prop_func}\n        self.choose_dest = nn.Linear(2 * node_hidden_size, 1)\n\n    def _initialize_edge_repr(self, g, src_list, dest_list):\n        # For untyped edges, only add 1 to indicate its existence.\n        # For multiple edge types, use a one-hot representation\n        # or an embedding module.\n        edge_repr = torch.ones(len(src_list), 1)\n        g.edges[src_list, dest_list].data['he'] = edge_repr\n\n    def prepare_training(self):\n        self.log_prob = []\n\n    def forward(self, g, dest):\n        src = g.number_of_nodes() - 1\n        possible_dests = range(src)\n\n        src_embed_expand = g.nodes[src].data['hv'].expand(src, -1)\n        possible_dests_embed = g.nodes[possible_dests].data['hv']\n\n        dests_scores = self.choose_dest(\n            torch.cat([possible_dests_embed,\n                       src_embed_expand], dim=1)).view(1, -1)\n        dests_probs = F.softmax(dests_scores, dim=1)\n\n        if not self.training:\n            dest = Categorical(dests_probs).sample().item()\n\n        if not g.has_edge_between(src, dest):\n            # For undirected graphs, add edges for both directions\n            # so that you can perform graph propagation.\n            src_list = [src, dest]\n            dest_list = [dest, src]\n\n            g.add_edges(src_list, dest_list)\n            self._initialize_edge_repr(g, src_list, dest_list)\n\n            self.graph_op['prop'](g)\n\n        if self.training:\n            if dests_probs.nelement() > 1:\n                self.log_prob.append(\n                    F.log_softmax(dests_scores, dim=1)[:, dest: dest + 1])\n```\n\nPutting it together\n``````````````````````````\n\nYou are now ready to have a complete implementation of the model class.\n\n\n\n\n\n```python\nclass DGMG(DGMGSkeleton):\n    def __init__(self, v_max, node_hidden_size,\n                 num_prop_rounds):\n        super(DGMG, self).__init__(v_max)\n\n        # Graph embedding module\n        self.graph_embed = GraphEmbed(node_hidden_size)\n\n        # Graph propagation module\n        self.graph_prop = GraphProp(num_prop_rounds,\n                                    node_hidden_size)\n\n        # Actions\n        self.add_node_agent = AddNode(\n            self.graph_embed, node_hidden_size)\n        self.add_edge_agent = AddEdge(\n            self.graph_embed, node_hidden_size)\n        self.choose_dest_agent = ChooseDestAndUpdate(\n            self.graph_prop, node_hidden_size)\n\n        # Forward functions\n        self.forward_train = partial(forward_train, self=self)\n        self.forward_inference = partial(forward_inference, self=self)\n\n    @property\n    def action_step(self):\n        old_step_count = self.step_count\n        self.step_count += 1\n\n        return old_step_count\n\n    def prepare_for_train(self):\n        self.step_count = 0\n\n        self.add_node_agent.prepare_training()\n        self.add_edge_agent.prepare_training()\n        self.choose_dest_agent.prepare_training()\n\n    def add_node_and_update(self, a=None):\n        \"\"\"Decide if to add a new node.\n        If a new node should be added, update the graph.\"\"\"\n\n        return self.add_node_agent(self.g, a)\n\n    def add_edge_or_not(self, a=None):\n        \"\"\"Decide if a new edge should be added.\"\"\"\n\n        return self.add_edge_agent(self.g, a)\n\n    def choose_dest_and_update(self, a=None):\n        \"\"\"Choose destination and connect it to the latest node.\n        Add edges for both directions and update the graph.\"\"\"\n\n        self.choose_dest_agent(self.g, a)\n\n    def get_log_prob(self):\n        add_node_log_p = torch.cat(self.add_node_agent.log_prob).sum()\n        add_edge_log_p = torch.cat(self.add_edge_agent.log_prob).sum()\n        choose_dest_log_p = torch.cat(self.choose_dest_agent.log_prob).sum()\n        return add_node_log_p + add_edge_log_p + choose_dest_log_p\n```\n\nBelow is an animation where a graph is generated on the fly\nafter every 10 batches of training for the first 400 batches. You\ncan see how the model improves over time and begins generating cycles.\n\n.. figure:: https://user-images.githubusercontent.com/19576924/48929291-60fe3880-ef22-11e8-832a-fbe56656559a.gif\n   :alt:\n\nFor generative models, you can evaluate performance by checking the percentage\nof valid graphs among the graphs it generates on the fly.\n\n\n\n\n```python\nimport torch.utils.model_zoo as model_zoo\n\n# Download a pre-trained model state dict for generating cycles with 10-20 nodes.\nstate_dict = model_zoo.load_url('https://data.dgl.ai/model/dgmg_cycles-5a0c40be.pth')\nmodel = DGMG(v_max=20, node_hidden_size=16, num_prop_rounds=2)\nmodel.load_state_dict(state_dict)\nmodel.eval()\n\ndef is_valid(g):\n    # Check if g is a cycle having 10-20 nodes.\n    def _get_previous(i, v_max):\n        if i == 0:\n            return v_max\n        else:\n            return i - 1\n\n    def _get_next(i, v_max):\n        if i == v_max:\n            return 0\n        else:\n            return i + 1\n\n    size = g.number_of_nodes()\n\n    if size < 10 or size > 20:\n        return False\n\n    for node in range(size):\n        neighbors = g.successors(node)\n\n        if len(neighbors) != 2:\n            return False\n\n        if _get_previous(node, size - 1) not in neighbors:\n            return False\n\n        if _get_next(node, size - 1) not in neighbors:\n            return False\n\n    return True\n\nnum_valid = 0\nfor i in range(100):\n    g = model()\n    num_valid += is_valid(g)\n\ndel model\nprint('Among 100 graphs generated, {}% are valid.'.format(num_valid))\n```\n\n    Downloading: \"https://data.dgl.ai/model/dgmg_cycles-5a0c40be.pth\" to /home/viktor/.cache/torch/hub/checkpoints/dgmg_cycles-5a0c40be.pth\n    100.0%\n    <ipython-input-8-582f9090524b>:34: DeprecationWarning: an integer is required (got type float).  Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python.\n      self.node_type_embed(torch.LongTensor([node_type])),\n    /home/viktor/anaconda3/envs/dgl/lib/python3.8/site-packages/dgl/base.py:45: DGLWarning: DGLGraph.has_edge_between is deprecated. Please use DGLGraph.has_edges_between\n      return warnings.warn(message, category=category, stacklevel=1)\n\n\n    Among 100 graphs generated, 97% are valid.\n\n\nFor the complete implementation, see the `DGL DGMG example\n<https://github.com/dmlc/dgl/tree/master/examples/pytorch/dgmg>`__.\n\n\n\n", "meta": {"hexsha": "ac46daee54beb6f0ed654c144cbe0de8273dbbcc", "size": 36909, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "5_dgmg.ipynb", "max_stars_repo_name": "d4rkspir1t/groupdetection-dgmg", "max_stars_repo_head_hexsha": "e655c697ebc279c78d674df91f63ca4aa4dde7d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "5_dgmg.ipynb", "max_issues_repo_name": "d4rkspir1t/groupdetection-dgmg", "max_issues_repo_head_hexsha": "e655c697ebc279c78d674df91f63ca4aa4dde7d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5_dgmg.ipynb", "max_forks_repo_name": "d4rkspir1t/groupdetection-dgmg", "max_forks_repo_head_hexsha": "e655c697ebc279c78d674df91f63ca4aa4dde7d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9335443038, "max_line_length": 298, "alphanum_fraction": 0.5399225121, "converted": true, "num_tokens": 6821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26894141551050293, "lm_q2_score": 0.10087863016367529, "lm_q1q2_score": 0.02713044159097935}}
{"text": "```python\n%matplotlib inline\n```\n\n\n.. currentmodule:: dgl\n\nWorking with Heterogeneous Graphs\n=================================\n\n**Author**: Quan Gan, `Minjie Wang <https://jermainewang.github.io/>`_, Mufei Li,\nGeorge Karypis, Zheng Zhang\n\nIn this tutorial, you learn about:\n\n* Examples of heterogenous graph data and typical applications.\n\n* Creating and manipulating a heterogenous graph in DGL.\n\n* Implementing `Relational-GCN <https://arxiv.org/abs/1703.06103>`_, a popular GNN model,\n  for heterogenous graph input.\n\n* Training a model to solve a node classification task.\n\nHeterogeneous graphs, or *heterographs* for short, are graphs that contain\ndifferent types of nodes and edges. The different types of nodes and edges tend\nto have different types of attributes that are designed to capture the\ncharacteristics of each node and edge type. Within the context of\ngraph neural networks, depending on their complexity, certain node and edge types\nmight need to be modeled with representations that have a different number of dimensions.\n\nDGL supports graph neural network computations on such heterogeneous graphs, by\nusing the heterograph class and its associated API.\n\n\nExamples of heterographs\n-----------------------\nMany graph datasets represent relationships among various types of entities.\nThis section provides an overview for several graph use-cases that show such relationships \nand can have their data represented as heterographs.\n\nCitation graph \n~~~~~~~~~~~~~~~\nThe Association for Computing Machinery publishes an `ACM dataset <https://aminer.org/citation>`_ that contains two\nmillion papers, their authors, publication venues, and the other papers\nthat were cited. This information can be represented as a heterogeneous graph.\n\nThe following diagram shows several entities in the ACM dataset and the relationships among them \n(taken from `Shi et al., 2015 <https://arxiv.org/pdf/1511.04854.pdf>`_).\n\n.. figure:: https://data.dgl.ai/tutorial/hetero/acm-example.png# \n\nThis graph has three types of entities that correspond to papers, authors, and publication venues.\nIt also contains three types of edges that connect the following:\n\n* Authors with papers corresponding to *written-by* relationships\n\n* Papers with publication venues corresponding to *published-in* relationships\n\n* Papers with other papers corresponding to *cited-by* relationships\n\n\nRecommender systems \n~~~~~~~~~~~~~~~~~~~~ \nThe datasets used in recommender systems often contain\ninteractions between users and items. For example, the data could include the\nratings that users have provided to movies. Such interactions can be modeled\nas heterographs.\n\nThe nodes in these heterographs will have two types, *users* and *movies*. The edges\nwill correspond to the user-movie interactions. Furthermore, if an interaction is\nmarked with a rating, then each rating value could correspond to a different edge type.\nThe following diagram shows an example of user-item interactions as a heterograph.\n\n.. figure:: https://data.dgl.ai/tutorial/hetero/recsys-example.png\n\n\nKnowledge graph \n~~~~~~~~~~~~~~~~\nKnowledge graphs are inherently heterogenous. For example, in\nWikidata, Barack Obama (item Q76) is an instance of a human, which could be viewed as\nthe entity class, whose spouse (item P26) is Michelle Obama (item Q13133) and\noccupation (item P106) is politician (item Q82955). The relationships are shown in the following.\ndiagram.\n\n.. figure:: https://data.dgl.ai/tutorial/hetero/kg-example.png\n\n\n\n\nCreating a heterograph in DGL\n-----------------------------\nYou can create a heterograph in DGL using the :func:`dgl.heterograph` API.\nThe argument to :func:`dgl.heterograph` is a dictionary. The keys are tuples\nin the form of ``(srctype, edgetype, dsttype)`` specifying the relation name\nand the two entity types it connects. Such tuples are called *canonical edge\ntypes*. The values are data to initialize the graph structures, that is, which\nnodes the edges actually connect.\n\nFor instance, the following code creates the user-item interactions heterograph shown earlier.\n\n\n\n\n```python\n# Each value of the dictionary is a pair of source and destination arrays.\n# Nodes are integer IDs starting from zero. Nodes IDs of different types have\n# separate countings.\nimport dgl\nimport numpy as np\n\nratings = dgl.heterograph(\n    {('user', '+1', 'movie') : (np.array([0, 0, 1]), np.array([0, 1, 0])),\n     ('user', '-1', 'movie') : (np.array([2]), np.array([1]))})\n```\n\nDGL supports creating a graph from a variety of data sources. The following\ncode creates the same graph as the above.\n\nCreating from scipy matrix\n\n\n\n\n```python\nimport scipy.sparse as sp\nplus1 = sp.coo_matrix(([1, 1, 1], ([0, 0, 1], [0, 1, 0])), shape=(3, 2))\nminus1 = sp.coo_matrix(([1], ([2], [1])), shape=(3, 2))\nratings = dgl.heterograph(\n    {('user', '+1', 'movie') : plus1,\n     ('user', '-1', 'movie') : minus1})\n\n# Creating from networkx graph\nimport networkx as nx\nplus1 = nx.DiGraph()\nplus1.add_nodes_from(['u0', 'u1', 'u2'], bipartite=0)\nplus1.add_nodes_from(['m0', 'm1'], bipartite=1)\nplus1.add_edges_from([('u0', 'm0'), ('u0', 'm1'), ('u1', 'm0')])\n# To simplify the example, reuse the minus1 object.\n# This also means that you could use different sources of graph data\n# for different relationships.\nratings = dgl.heterograph(\n    {('user', '+1', 'movie') : plus1,\n     ('user', '-1', 'movie') : minus1})\n```\n\nManipulating heterograph\n------------------------\nYou can create a more realistic heterograph using the ACM dataset. To do this, first \ndownload the dataset as follows:\n\n\n\n\n```python\nimport scipy.io\nimport urllib.request\n\ndata_url = 'https://data.dgl.ai/dataset/ACM.mat'\ndata_file_path = '/tmp/ACM.mat'\n\nurllib.request.urlretrieve(data_url, data_file_path)\ndata = scipy.io.loadmat(data_file_path)\nprint(list(data.keys()))\n```\n\nThe dataset stores node information by their types: ``P`` for paper, ``A``\nfor author, ``C`` for conference, ``L`` for subject code, and so on. The relationships\nare stored as SciPy sparse matrix under key ``XvsY``, where ``X`` and ``Y``\ncould be any of the node type code.\n\nThe following code prints out some statistics about the paper-author relationships.\n\n\n\n\n```python\nprint(type(data['PvsA']))\nprint('#Papers:', data['PvsA'].shape[0])\nprint('#Authors:', data['PvsA'].shape[1])\nprint('#Links:', data['PvsA'].nnz)\n```\n\nConverting this SciPy matrix to a heterograph in DGL is straightforward.\n\n\n\n\n```python\npa_g = dgl.heterograph({('paper', 'written-by', 'author') : data['PvsA']})\n# equivalent (shorter) API for creating heterograph with two node types:\npa_g = dgl.bipartite(data['PvsA'], 'paper', 'written-by', 'author')\n```\n\nYou can easily print out the type names and other structural information.\n\n\n\n\n```python\nprint('Node types:', pa_g.ntypes)\nprint('Edge types:', pa_g.etypes)\nprint('Canonical edge types:', pa_g.canonical_etypes)\n\n# Nodes and edges are assigned integer IDs starting from zero and each type has its own counting.\n# To distinguish the nodes and edges of different types, specify the type name as the argument.\nprint(pa_g.number_of_nodes('paper'))\n# Canonical edge type name can be shortened to only one edge type name if it is\n# uniquely distinguishable.\nprint(pa_g.number_of_edges(('paper', 'written-by', 'author')))\nprint(pa_g.number_of_edges('written-by'))\nprint(pa_g.successors(1, etype='written-by'))  # get the authors that write paper #1\n\n# Type name argument could be omitted whenever the behavior is unambiguous.\nprint(pa_g.number_of_edges())  # Only one edge type, the edge type argument could be omitted\n```\n\nA homogeneous graph is just a special case of a heterograph with only one type\nof node and edge. In this case, all the APIs are exactly the same as in\n:class:`DGLGraph`.\n\n\n\n\n```python\n# Paper-citing-paper graph is a homogeneous graph\npp_g = dgl.heterograph({('paper', 'citing', 'paper') : data['PvsP']})\n# equivalent (shorter) API for creating homogeneous graph\npp_g = dgl.graph(data['PvsP'], 'paper', 'cite')\n\n# All the ntype and etype arguments could be omitted because the behavior is unambiguous.\nprint(pp_g.number_of_nodes())\nprint(pp_g.number_of_edges())\nprint(pp_g.successors(3))\n```\n\nCreate a subset of the ACM graph using the paper-author, paper-paper, \nand paper-subject relationships.  Meanwhile, also add the reverse\nrelationship to prepare for the later sections.\n\n\n\n\n```python\nG = dgl.heterograph({\n        ('paper', 'written-by', 'author') : data['PvsA'],\n        ('author', 'writing', 'paper') : data['PvsA'].transpose(),\n        ('paper', 'citing', 'paper') : data['PvsP'],\n        ('paper', 'cited', 'paper') : data['PvsP'].transpose(),\n        ('paper', 'is-about', 'subject') : data['PvsL'],\n        ('subject', 'has', 'paper') : data['PvsL'].transpose(),\n    })\n\nprint(G)\n```\n\n**Metagraph** (or network schema) is a useful summary of a heterograph.\nServing as a template for a heterograph, it tells how many types of objects\nexist in the network and where the possible links exist.\n\nDGL provides easy access to the metagraph, which could be visualized using\nexternal tools.\n\n\n\n\n```python\n# Draw the metagraph using graphviz.\nimport pygraphviz as pgv\ndef plot_graph(nxg):\n    ag = pgv.AGraph(strict=False, directed=True)\n    for u, v, k in nxg.edges(keys=True):\n        ag.add_edge(u, v, label=k)\n    ag.layout('dot')\n    ag.draw('graph.png')\n\nplot_graph(G.metagraph)\n```\n\nLearning tasks associated with heterographs\n-------------------------------------------\nSome of the typical learning tasks that involve heterographs include:\n\n* *Node classification and regression* to predict the class of each node or\n  estimate a value associated with it.\n\n* *Link prediction* to predict if there is an edge of a certain\n  type between a pair of nodes, or predict which other nodes a particular\n  node is connected with (and optionally the edge types of such connections).\n\n* *Graph classification/regression* to assign an entire\n  heterograph into one of the target classes or to estimate a numerical\n  value associated with it.\n\nIn this tutorial, we designed a simple example for the first task.\n\nA semi-supervised node classification example\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nOur goal is to predict the publishing conference of a paper using the ACM\nacademic graph we just created. To further simplify the task, we only focus\non papers published in three conferences: *KDD*, *ICML*, and *VLDB*. All\nthe other papers are not labeled, making it a semi-supervised setting.\n\nThe following code extracts those papers from the raw dataset and prepares \nthe training, validation, testing split.\n\n\n\n\n```python\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\npvc = data['PvsC'].tocsr()\n# find all papers published in KDD, ICML, VLDB\nc_selected = [0, 11, 13]  # KDD, ICML, VLDB\np_selected = pvc[:, c_selected].tocoo()\n# generate labels\nlabels = pvc.indices\nlabels[labels == 11] = 1\nlabels[labels == 13] = 2\nlabels = torch.tensor(labels).long()\n\n# generate train/val/test split\npid = p_selected.row\nshuffle = np.random.permutation(pid)\ntrain_idx = torch.tensor(shuffle[0:800]).long()\nval_idx = torch.tensor(shuffle[800:900]).long()\ntest_idx = torch.tensor(shuffle[900:]).long()\n```\n\nRelational-GCN on heterograph\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nWe use `Relational-GCN <https://arxiv.org/abs/1703.06103>`_ to learn the\nrepresentation of nodes in the graph. Its message-passing equation is as\nfollows:\n\n\\begin{align}h_i^{(l+1)} = \\sigma\\left(\\sum_{r\\in \\mathcal{R}}\n   \\sum_{j\\in\\mathcal{N}_r(i)}W_r^{(l)}h_j^{(l)}\\right)\\end{align}\n\nBreaking down the equation, you see that there are two parts in the\ncomputation.\n\n(i) Message computation and aggregation within each relation $r$\n\n(ii) Reduction that merges the results from multiple relationships\n\nFollowing this intuition, perform message passing on a heterograph in\ntwo steps.\n\n(i) Per-edge-type message passing\n\n(ii) Type wise reduction\n\n\n\n\n```python\nimport dgl.function as fn\n\nclass HeteroRGCNLayer(nn.Module):\n    def __init__(self, in_size, out_size, etypes):\n        super(HeteroRGCNLayer, self).__init__()\n        # W_r for each relation\n        self.weight = nn.ModuleDict({\n                name : nn.Linear(in_size, out_size) for name in etypes\n            })\n\n    def forward(self, G, feat_dict):\n        # The input is a dictionary of node features for each type\n        funcs = {}\n        for srctype, etype, dsttype in G.canonical_etypes:\n            # Compute W_r * h\n            Wh = self.weight[etype](feat_dict[srctype])\n            # Save it in graph for message passing\n            G.nodes[srctype].data['Wh_%s' % etype] = Wh\n            # Specify per-relation message passing functions: (message_func, reduce_func).\n            # Note that the results are saved to the same destination feature 'h', which\n            # hints the type wise reducer for aggregation.\n            funcs[etype] = (fn.copy_u('Wh_%s' % etype, 'm'), fn.mean('m', 'h'))\n        # Trigger message passing of multiple types.\n        # The first argument is the message passing functions for each relation.\n        # The second one is the type wise reducer, could be \"sum\", \"max\",\n        # \"min\", \"mean\", \"stack\"\n        G.multi_update_all(funcs, 'sum')\n        # return the updated node feature dictionary\n        return {ntype : G.nodes[ntype].data['h'] for ntype in G.ntypes}\n```\n\nCreate a simple GNN by stacking two ``HeteroRGCNLayer``. Since the\nnodes do not have input features, make their embeddings trainable.\n\n\n\n\n```python\nclass HeteroRGCN(nn.Module):\n    def __init__(self, G, in_size, hidden_size, out_size):\n        super(HeteroRGCN, self).__init__()\n        # Use trainable node embeddings as featureless inputs.\n        embed_dict = {ntype : nn.Parameter(torch.Tensor(G.number_of_nodes(ntype), in_size))\n                      for ntype in G.ntypes}\n        for key, embed in embed_dict.items():\n            nn.init.xavier_uniform_(embed)\n        self.embed = nn.ParameterDict(embed_dict)\n        # create layers\n        self.layer1 = HeteroRGCNLayer(in_size, hidden_size, G.etypes)\n        self.layer2 = HeteroRGCNLayer(hidden_size, out_size, G.etypes)\n\n    def forward(self, G):\n        h_dict = self.layer1(G, self.embed)\n        h_dict = {k : F.leaky_relu(h) for k, h in h_dict.items()}\n        h_dict = self.layer2(G, h_dict)\n        # get paper logits\n        return h_dict['paper']\n```\n\nTrain and evaluate\n~~~~~~~~~~~~~~~~~~\nTrain and evaluate this network.\n\n\n\n\n```python\n# Create the model. The output has three logits for three classes.\nmodel = HeteroRGCN(G, 10, 10, 3)\n\nopt = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)\n\nbest_val_acc = 0\nbest_test_acc = 0\n\nfor epoch in range(100):\n    logits = model(G)\n    # The loss is computed only for labeled nodes.\n    loss = F.cross_entropy(logits[train_idx], labels[train_idx])\n\n    pred = logits.argmax(1)\n    train_acc = (pred[train_idx] == labels[train_idx]).float().mean()\n    val_acc = (pred[val_idx] == labels[val_idx]).float().mean()\n    test_acc = (pred[test_idx] == labels[test_idx]).float().mean()\n\n    if best_val_acc < val_acc:\n        best_val_acc = val_acc\n        best_test_acc = test_acc\n\n    opt.zero_grad()\n    loss.backward()\n    opt.step()\n\n    if epoch % 5 == 0:\n        print('Loss %.4f, Train Acc %.4f, Val Acc %.4f (Best %.4f), Test Acc %.4f (Best %.4f)' % (\n            loss.item(),\n            train_acc.item(),\n            val_acc.item(),\n            best_val_acc.item(),\n            test_acc.item(),\n            best_test_acc.item(),\n        ))\n```\n\nWhat's next?\n------------\n* Check out our full implementation in PyTorch\n  `here <https://github.com/dmlc/dgl/tree/master/examples/pytorch/rgcn-hetero>`_.\n\n* We also provide the following model examples:\n\n  * `Graph Convolutional Matrix Completion <https://arxiv.org/abs/1706.02263>_`,\n    which we implement in MXNet\n    `here <https://github.com/dmlc/dgl/tree/v0.4.0/examples/mxnet/gcmc>`_.\n\n  * `Heterogeneous Graph Attention Network <https://arxiv.org/abs/1903.07293>`_\n    requires transforming a heterograph into a homogeneous graph according to\n    a given metapath (i.e. a path template consisting of edge types).  We\n    provide :func:`dgl.transform.metapath_reachable_graph` to do this.  See full\n    implementation\n    `here <https://github.com/dmlc/dgl/tree/master/examples/pytorch/han>`_.\n\n  * `Metapath2vec <https://dl.acm.org/citation.cfm?id=3098036>`_ requires\n    generating random walk paths according to a given metapath.  Please\n    refer to the full metapath2vec implementation\n    `here <https://github.com/dmlc/dgl/tree/master/examples/pytorch/metapath2vec>`_.\n\n* :doc:`Full heterograph API reference <../../api/python/heterograph>`.\n\n\n", "meta": {"hexsha": "6a4e2ccf4ee4fe1a7eccf72916df4eef84ed67c4", "size": 21542, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "DGL/get started/5_hetero.ipynb", "max_stars_repo_name": "AiRanthem/GNN", "max_stars_repo_head_hexsha": "f10b2f85d50efce1bd069517d07f33d84f25d099", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DGL/get started/5_hetero.ipynb", "max_issues_repo_name": "AiRanthem/GNN", "max_issues_repo_head_hexsha": "f10b2f85d50efce1bd069517d07f33d84f25d099", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DGL/get started/5_hetero.ipynb", "max_forks_repo_name": "AiRanthem/GNN", "max_forks_repo_head_hexsha": "f10b2f85d50efce1bd069517d07f33d84f25d099", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 74.0274914089, "max_line_length": 2370, "alphanum_fraction": 0.6338315848, "converted": true, "num_tokens": 4173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23651624182730094, "lm_q2_score": 0.1143685201445555, "lm_q1q2_score": 0.027050012567940224}}
{"text": "#SHDOM single-scattering adjoint\n\nThis folder conatains the most recent (3 May 2015) single-scattering adjoint calculations from frank.  \n\n\n>This has the log output files (.log), radiance output files (.arad),\nand optical property adjoint files (.adj) for the \"true\" and \"guess\"\ncases. The first set of output is for the single scattering forward radiance calculations\n\n    >>les0822nh15t13y135_ocaer1_w0.646_ns1true.*,\n    \n    >>les0822nh15t13y135_ocaer1_w0.646_ns1guess.*,\n\n>and the second set of outputs is for the full multiple scattering forward radiance calculations,\n\n    >>les0822nh15t13y135_ocaer1_w0.646_ns1true2.*,\n\n    >>les0822nh15t13y135_ocaer1_w0.646_ns1guess2.*.\n\n\nThe cloud field used in these simulations is a 2D slice taken at $y_{(i_y=135)}=8.375 \\mathrm{km}$ of the 320x320 high resolution simulation shown below. \n\n\n\nThe adjoint calculation is for the gradient of the misfit function, \n\n\\begin{align}\n\\frac{\\partial \\Phi(\\sigma, \\omega)}{\\partial(\\sigma)} &= \\left< \\Delta p, \\mathcal{U}_{\\sigma}[\\Delta f] \\right>\n\\end{align}\n\nOnly the first order of scattering completed so the results are approximate.  In the calculation labelled \"1\" the forward and adjoint calculations are only single-scattering.  In the calculation labelled \"2\", the Forward calculation includes multiple scatterng while the adjoint does not.  \n\n\n\n```python\n%pylab inline\n\n# Imports\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n\nimport pandas as pd\n\n\n```\n\n    Populating the interactive namespace from numpy and matplotlib\n\n\n    WARNING: pylab import has clobbered these variables: ['fmax']\n    `%matplotlib` prevents importing * from pylab and numpy\n\n\n\n```python\n\n```\n\n\n```python\n# Utility functions\n\ndef print_head(fname, Nlines=10, indent=\"\\t\"):\n    \"Print the head of the file.\"\n    \n    # Print a message and then the first N lines\n    print(\"Showing head: {}\".format(fname))\n    for i, line in zip(range(Nlines), open(fname, 'r')):\n        print(indent + line.strip())\n        \n    print('\\n')\n    \ndef read_log(flog, start_line=\"X      Z   Extinct\", max_lines=10**8):\n    \"\"\"\n    Read in a log file but save lines only after reaching a line \n    matching start_line.\n    \"\"\"\n    \n    # Loop over lines record after header and before footer\n    ncols = None \n    lines = []\n    for i, line in zip(range(max_lines), open(flog, 'r')):\n        new = line.strip().split()\n        \n        # Check if the line is the header\n        if ncols is None:\n            if line.strip()[:len(start_line)]==start_line:\n                ncols = len(new[:9])\n                cols = new[:9]\n        else:        \n            if ncols == len(new[:9]):\n                lines.append(new[:9])\n            else:\n                print(new)\n                break\n    # Raise an error if the file had no line with the specified columns    \n    if ncols is None: \n        raise ValueError(\"No column line found containing {}\".format(start_line))\n        \n    # Make dictionary of arrays from keys array with given lines\n    N = len(lines) - 1\n    value_array = np.array(lines[:], dtype='f8')\n    \n    log_dict = dict(zip(cols, list(value_array.T)))\n    return log_dict\n    \n```\n\n\n```python\nls\n```\n\n    exploring_adjoint.ipynb\r\n    exploring_adjoint_with_aerosol.ipynb\r\n    les0822nh15t13y135_ocaer1_w0.646_ns1guess2.adj\r\n    les0822nh15t13y135_ocaer1_w0.646_ns1guess2.arad\r\n    les0822nh15t13y135_ocaer1_w0.646_ns1guess2.log\r\n    les0822nh15t13y135_ocaer1_w0.646_ns1true2.adj\r\n    les0822nh15t13y135_ocaer1_w0.646_ns1true2.arad\r\n    les0822nh15t13y135_ocaer1_w0.646_ns1true2.log\r\n    les0822nh15t13y135_w0.646_ns1guess2.adj\r\n    les0822nh15t13y135_w0.646_ns1guess2.arad\r\n    les0822nh15t13y135_w0.646_ns1guess2.log\r\n    les0822nh15t13y135_w0.646_ns1true2.adj\r\n    les0822nh15t13y135_w0.646_ns1true2.arad\r\n    les0822nh15t13y135_w0.646_ns1true2.log\r\n\n\n# Looking at the data files\n\n\n```python\n# The log file\nflog = \"les0822nh15t13y135_ocaer1_w0.646_ns1true2.log\"\nprint_head(flog, Nlines=10)\n\n# The radiance file\nfrad = \"les0822nh15t13y135_ocaer1_w0.646_ns1true2.arad\"\nprint_head(frad, Nlines=25)\n\n# The adjoint file\nfadj_true = \"les0822nh15t13y135_ocaer1_w0.646_ns1true2.adj\"\nfadj = \"les0822nh15t13y135_ocaer1_w0.646_ns1guess2.adj\"\n\n    \n    \nprint_head(fadj, Nlines=5)\n\n# The adjoint Radiance file\nfarad = \"les0822nh15t13y135_ocaer1_w0.646_ns1guess2.arad\"\nfarad_true = \"les0822nh15t13y135_ocaer1_w0.646_ns1true2.arad\"\nprint_head(farad, Nlines=35)\n```\n\n    Showing head: les0822nh15t13y135_ocaer1_w0.646_ns1true2.log\n    \t\n    \tName of this SHDOMADJ run:\n    \tles0822nh15t13y135_ocaer1_w0.646_ns1true2\n    \tInput particle properties filename (or NONE for Rayleigh only)\n    \tles0822nh15t13y135_ocaer1t.part\n    \tNumber of input scattering tables\n    \t2\n    \tName of each scattering table\n    \twater_w0.646.scat\n    \taero_oc_w0.646.scat\n    \n    \n    Showing head: les0822nh15t13y135_ocaer1_w0.646_ns1true2.arad\n    \t! Polarized Spherical Harmonic Discrete Ordinate Radiative Transfer Radiance Output\n    \t!  L= 15  M= 15  NLM=  256   NMU= 16  NPHI= 32  NANG=  354   NSH=   3059599\n    \t!  NSTOKES=1   NX= 320   NY=   1   NZ=  86    NPTS=   36912   NCELLS=   42822\n    \t!  PARTICLE_FILE=les0822nh15t13y135_ocaer1t.part\n    \t!  CORRELATED_K-DIST_FILE=NONE   NUM_G= 1\n    \t!  SOURCE_TYPE=SOLAR               DELTA-M METHOD\n    \t!  GRID_TYPE=EVEN (X,Y)    PROPERTY-FILE (Z)    INDEPENDENT_PIXEL=2\n    \t!  SURFACE_TYPE=FIXED LAMBERTIAN         HORIZ_BOUNDARY_COND=0\n    \t!  GROUND_ALBEDO=0.0500000  SKY_RAD= 0.00000E+00\n    \t!  SOLAR_FLUX= 0.100000E+01   SOLAR_MU=-0.9221000   SOLAR_AZ= 339.400\n    \t!  UNITS=WATTS/(M^2 MICRON STER)    WAVELENGTH=      0.65\n    \t!  SPLITTING_ACCURACY= 0.300E-01   SPHERICAL_HARMONIC_ACCURACY= 0.300E-02\n    \t!  SOLUTION_ACCURACY= 0.300E-04\n    \t!  MAXIMUM_ITERATIONS= 200   NUMBER_ITERATIONS= 131\n    \t!  RADIANCE AT Z= 15.000\n    \t!  320    1    1 ! NXOUT, NYOUT, NRADDIR\n    \t!  ID      mu       phi\n    \t!   1  1.0000000    0.00\n    \t!\n    \tID  IY  IX    RADIANCE (STOKES I, Q, U, V)\n    \t1   1   1   0.204325E+00\n    \t1   1   2   0.196358E+00\n    \t1   1   3   0.174226E+00\n    \t1   1   4   0.193639E+00\n    \t1   1   5   0.205518E+00\n    \n    \n    Showing head: les0822nh15t13y135_ocaer1_w0.646_ns1guess2.adj\n    \t! SHDOMADJ optical property adjoint output\n    \t!\n    \tX       Y       Z      Extinct  SSalbedo  dMF/dExt  dMF/dSSalb  dMF/dP(Theta_j)\n    \t0.0000  0.0000 -0.0087    0.07041 0.970492  0.000E+00  0.000E+00  0.000E+00\n    \t0.0000  0.0000  0.0095    0.07018 0.970491  0.000E+00  0.000E+00  0.000E+00\n    \n    \n    Showing head: les0822nh15t13y135_ocaer1_w0.646_ns1guess2.arad\n    \t! Polarized Spherical Harmonic Discrete Ordinate Radiative Transfer Radiance Output\n    \t!  L= 15  M= 15  NLM=  256   NMU= 16  NPHI= 32  NANG=  354   NSH=   2981886\n    \t!  NSTOKES=1   NX= 320   NY=   1   NZ=  86    NPTS=   36093   NCELLS=   41398\n    \t!  PARTICLE_FILE=les0822nh15t13y135_ocaer1g.part\n    \t!  CORRELATED_K-DIST_FILE=NONE   NUM_G= 1\n    \t!  SOURCE_TYPE=SOLAR               DELTA-M METHOD\n    \t!  GRID_TYPE=EVEN (X,Y)    PROPERTY-FILE (Z)    INDEPENDENT_PIXEL=2\n    \t!  SURFACE_TYPE=FIXED LAMBERTIAN         HORIZ_BOUNDARY_COND=0\n    \t!  GROUND_ALBEDO=0.0500000  SKY_RAD= 0.00000E+00\n    \t!  SOLAR_FLUX= 0.100000E+01   SOLAR_MU=-0.9221000   SOLAR_AZ= 339.400\n    \t!  UNITS=WATTS/(M^2 MICRON STER)    WAVELENGTH=      0.65\n    \t!  SPLITTING_ACCURACY= 0.300E-01   SPHERICAL_HARMONIC_ACCURACY= 0.300E-02\n    \t!  SOLUTION_ACCURACY= 0.300E-04\n    \t!  MAXIMUM_ITERATIONS= 200   NUMBER_ITERATIONS= 140\n    \t!  RADIANCE AT Z= 15.000\n    \t!  320    1    1 ! NXOUT, NYOUT, NRADDIR\n    \t!  ID      mu       phi\n    \t!   1  1.0000000    0.00\n    \t!\n    \tID  IY  IX    RADIANCE (STOKES I, Q, U, V)\n    \t1   1   1   0.196312E+00\n    \t1   1   2   0.188236E+00\n    \t1   1   3   0.167071E+00\n    \t1   1   4   0.184278E+00\n    \t1   1   5   0.195281E+00\n    \t1   1   6   0.198276E+00\n    \t1   1   7   0.190030E+00\n    \t1   1   8   0.169683E+00\n    \t1   1   9   0.137259E+00\n    \t1   1  10   0.113736E+00\n    \t1   1  11   0.767046E-01\n    \t1   1  12   0.606018E-01\n    \t1   1  13   0.578038E-01\n    \t1   1  14   0.571656E-01\n    \t1   1  15   0.106376E+00\n    \n    \n\n\n\n```python\npd.read_csv?\n```\n\n\n```python\n# Load the adjoint files into memory\nadj_frame = pd.read_csv(fadj, quoting=3, delim_whitespace=True, skiprows=2)\nadj_true_frame = pd.read_csv(fadj_true, quoting=3, delim_whitespace=True, skiprows=2)\nadj_arad_frame = pd.read_csv(farad, quoting=3, delim_whitespace=True, skiprows=19)\nadj_arad_true_frame = pd.read_csv(farad_true, quoting=3, delim_whitespace=True, skiprows=19)\n    \n    \n# Get variables from the array\nnx = adj_frame['X'].unique().size\nnz = adj_frame[\"Z\"].unique().size\n\n\n# Get the guess case adjoint field properties\nadj_x = np.array(adj_frame[\"X\"], dtype='f8').reshape(nx, nz)\nadj_z = np.array(adj_frame[\"Z\"], dtype='f8').reshape(nx, nz)\nadj_ext = np.array(adj_frame[\"Extinct\"], dtype='f8').reshape(nx, nz)\nadj_alb = np.array(adj_frame[\"SSalbedo\"], dtype='f8').reshape(nx, nz)\nadj_dMFdext = np.array(adj_frame[\"dMF/dExt\"], dtype='f8').reshape(nx, nz)\nadj_dMFdalb = np.array(adj_frame[\"dMF/dSSalb\"], dtype='f8').reshape(nx, nz)\n\n# Get the True case adjoint extinction field\nadj_ext_true = np.array(adj_true_frame[\"Extinct\"], dtype='f8').reshape(nx, nz) \n\n# Define the adjoint radiance parameters\nadj_arad = np.array(adj_arad_frame['RADIANCE'], dtype='f8').reshape(nx)\nadj_arad_true = np.array(adj_arad_true_frame['RADIANCE'], dtype='f8').reshape(nx)\n\n\n\n```\n\n\n```python\n# Plot uniformity parameters\nH = 15.5   # top of the atmosphere plots\n\nmask_clouds = (adj_ext>= .75e-5) #* (adj_z <= 2.83)\ncloud_outline = (adj_ext>= .75e-1) #* (adj_z <= 2.83)\n\n\n# Scaling of the verticle coordinate \n\nZscale = adj_z[0,:]\nDZscale = 0 * Zscale\nDZscale_other = 0 * Zscale\nDZscale[:-1] += 1 / (Zscale[1:] - Zscale[:-1])\nDZscale_other[1:] += 1 / (Zscale[1:] - Zscale[:-1])\n\nalpha = .99725\nDZscale = alpha * DZscale + (1-alpha) * DZscale_other\n\n\n\n# Compute the residual\nadj_residual = adj_arad_true - adj_arad\n\n\n#mask_clouds = adj_ext_true >= 1e-5\n\n```\n\n\n```python\n# Make a figure to plot the true extinction field\nf0 = plt.figure(0, (15,8), facecolor='white')\nax0 = f0.add_axes([.1, .1, .8, .8])\ncontour0 = ax0.contourf(adj_x, adj_z, adj_ext_true, 100, cmap=cm.gray)\nax0.set_ybound((0,8))\nax0.set_title(\" Guess for the extinction field at y=8.35\")\nf0.colorbar(contour0, ax=ax0)\n```\n\n\n```python\n# Make a figure to plot the true extinction field\nf0 = plt.figure(0, (15,8), facecolor='white')\nax0 = f0.add_axes([.1, .1, .8, .8])\n\nfvals = adj_ext_true - adj_ext\n\ncontour0 = ax0.contourf(adj_x, adj_z, fvals, 100, cmap=cm.gray)\nax0.set_ybound((0,8))\nax0.set_title(\"Difference $\\sigma_{\\mathrm{true}} - \\sigma_{\\mathrm{guess}}$\")\nf0.colorbar(contour0, ax=ax0)\n```\n\n\n```python\n\n```\n\n\n```python\n# Make a figure to plot the true single-scattering albedo field\nf1 = plt.figure(1, (15,8), facecolor='white')\nax1 = f1.add_axes([.1, .1, .8, .8])\n\n\nlevels = np.linspace(.999995, 1, 100)\ncontour1 = ax1.contourf(adj_x, adj_z, adj_alb, levels=levels, cmap=cm.gray)\nax1.set_ybound((0,13))\nax1.set_title(\"SSAlbedo field at y=8.35\")\nf1.colorbar(contour1, ax=ax1)\n\n```\n\n\n```python\n# Make a figure to plot the true single-scattering albedo field\nf2 = plt.figure(1, (13,6), facecolor='white')\nax2 = f2.add_axes([.1, .1, .8, .8])\n\n\nfvals = adj_dMFdext * mask_clouds * DZscale #* .1 * adj_ext\nfmax = abs(fvals).max()\nlevels = np.linspace(-fmax, fmax, 100)\ncontour2 = ax2.contourf(adj_x, adj_z, fvals, levels=levels, cmap=cm.RdBu_r) #levels=linspace(-16, 16, 100),\ncontour2a = ax2.contour(adj_x, adj_z, cloud_outline, 1, cmap=cm.gray) #levels=linspace(-16, 16, 100),\n\n# Add the residual to the plot\nftrans = lambda y: 100 * y + .8*H \nplot_overlay_origin = ftrans(0 * adj_residual)\nplot_overlay_arad = ftrans(adj_residual)\nplot_arad = ax2.fill_between(adj_x[:,0], plot_overlay_origin, plot_overlay_arad, \n                             where=(plot_overlay_origin<plot_overlay_arad), \n                             color='b')#, linewidth=3)\nplot_arad = ax2.fill_between(adj_x[:,0], plot_overlay_origin, plot_overlay_arad, \n                             where=(plot_overlay_origin>plot_overlay_arad), \n                             color='r')#, linewidth=3)\nplot_origin = ax2.plot(adj_x[:,0], plot_overlay_origin, 'k,', linewidth=1)\nax2.set_ybound((0,H))\nax2.set_title(\"dMF/dExt * DZscale; GUESS y=8.35\")\ncb = f2.colorbar(contour2, ax=ax2)\n#cb.set_ticks([-2, -1, 0, 1, 2])\n#cb.set_ticklabels(['-2', '-1', '0', '1', '2'])\n```\n\n\n```python\nplot(Zscale, DZscale)\n```\n\n\n```python\n# Make a figure to plot the true single-scattering albedo field\nf3 = plt.figure(1, (15,8), facecolor='white')\nax3 = f3.add_axes([.1, .1, .8, .8])\n\n\n# plot parameters\nfvals = adj_dMFdalb * mask_clouds * DZscale # * .1 * adj_ext\nfmax = abs(fvals).max()\nlevels = np.linspace(-fmax, fmax, 100)\n\n\n\n#levels = np.linspace(-.05, .05, 100)\n\n#fvals = adj_dMFdalb * mask_clouds * DZscale\n\n\n\n\n\ncontour3 = ax3.contourf(adj_x, adj_z, fvals, levels=levels, cmap=cm.RdBu_r)\ncontour3a = ax3.contour(adj_x, adj_z, cloud_outline, 1, cmap=cm.gray) #levels=linspace(-16, 16, 100),\n\n# Add the residual to the plot\nftrans = lambda y: 2. * y + .8*H \nplot_overlay_origin = ftrans(0 * adj_arad)\nplot_overlay_arad = ftrans(adj_arad)\n\nplot_arad = ax3.plot(adj_x[:,0], plot_overlay_arad, 'r', linewidth=3)\nplot_origin = ax3.plot(adj_x[:,0], plot_overlay_origin, 'k,', linewidth=1)\n\nax3.set_ybound((0,H))\nax3.set_title(\"dMF/dalb (GUESS) field at y=8.35\")\n\nf3.colorbar(contour3, ax=ax3)\n```\n\n\n```python\n# Plot the Adjoint radiance at the top of the atmosphere\nf4 = plt.figure(4, (15,8), facecolor='white')\nax4 = f4.add_axes([.1, .1, .8, .8])\nax4.plot(np.unique(adj_x), adj_arad, 'k', linewidth=4)\nax4.set_xbound(0,25.5)\n#ax4.contourf(adj_x, adj_z, adj_arad, 100, cmap=cm.RdBu_r)\nprint(adj_x.shape, adj_z.shape, adj_arad.shape)\n\n\n```\n\n\n```python\n# Read the adjoint file\n\ncols = ['X', 'Y', 'Z', 'ADEXTINCT', \"ADALBEDO\"]\nvalue_list = []\nfor line in open(fadj):\n    if line[0] =='!':\n        pass\n    else:\n        new = line.strip().split()\n        value_list.append(new[:len(cols)])\n        \nvalues = np.array(value_list, dtype=\"f8\").T\nadjoint_dict = dict(zip(cols, values))\n\n```\n\n\n```python\n# Get values to plot\nnx = np.unique(adjoint_dict['X']).size\nnz = np.unique(adjoint_dict['Z']).size\nx = adjoint_dict['X'].reshape(nx, nz)\nz = adjoint_dict['Z'].reshape(nx, nz)\nadj_ext = adjoint_dict['ADEXTINCT'].reshape(nx, nz)\nadj_alb = adjoint_dict['ADALBEDO'].reshape(nx, nz)\n\nprint(\"maxes: {}, {}.\".format(abs(adj_ext).max(),abs(adj_alb).max()))\n\n```\n\n    maxes: 16.91, 0.501.\n\n\n\n```python\n#plot the adjoint of the extinction\nf1 = plt.figure(1, (15, 8), facecolor='white')\nax1 = f1.add_axes([.1, .1, .8, .8])\ncontour1 =ax1.contourf(x, z, adj_alb, levels=np.linspace(0, .6,50), cmap=cm.gray)\nax1.set_ybound(0,5)\nf1.colorbar(contour1, ax=ax1)\n\nax1.set_title(\"Single-scattering adjoint derivative w.r.t. albedo\", fontsize=\"x-large\", fontweight=\"bold\")\n```\n\n\n```python\n# The first adjoint radiance field\nfarad1 = \"radobs_les0822nh15t13y89_ocaer1_w0.646_ns1ss1.arad\"\nprint_head(farad1, Nlines=100)\n\n```\n\n    Showing head: radobs_les0822nh15t13y89_ocaer1_w0.646_ns1ss1.arad\n    \t! Polarized Spherical Harmonic Discrete Ordinate Radiative Transfer Radiance Output\n    \t!  L= 15  M= 15  NLM=  256   NMU= 16  NPHI= 32  NANG=  354   NSH=   1757885\n    \t!  NSTOKES=1   NX= 320   NY=   1   NZ=  85    NPTS=   27285   NCELLS=   26880\n    \t!  PARTICLE_FILE=les0822nh15t13y89_ocaer1.part\n    \t!  CORRELATED_K-DIST_FILE=NONE   NUM_G= 1\n    \t!  SOURCE_TYPE=SOLAR               DELTA-M METHOD\n    \t!  GRID_TYPE=EVEN (X,Y)    PROPERTY-FILE (Z)    INDEPENDENT_PIXEL=2\n    \t!  SURFACE_TYPE=FIXED LAMBERTIAN         HORIZ_BOUNDARY_COND=0\n    \t!  GROUND_ALBEDO=0.0500000  SKY_RAD= 0.00000E+00\n    \t!  SOLAR_FLUX= 0.100000E+01   SOLAR_MU=-0.9221000   SOLAR_AZ= 339.400\n    \t!  UNITS=WATTS/(M^2 MICRON STER)    WAVELENGTH=      0.65\n    \t!  SPLITTING_ACCURACY= 0.300E-01   SPHERICAL_HARMONIC_ACCURACY= 0.300E-02\n    \t!  SOLUTION_ACCURACY= 0.300E-04\n    \t!  MAXIMUM_ITERATIONS=   0   NUMBER_ITERATIONS=   0\n    \t!  RADIANCE AT Z= 15.000\n    \t320    1    3 ! NXOUT, NYOUT, NRADDIR\n    \t!  ID      mu       phi\n    \t!   1  0.8660300  180.00\n    \t!   2  1.0000000    0.00\n    \t!   3  0.8660300    0.00\n    \t! ID  IY  IX    RADIANCE (STOKES I, Q, U, V)\n    \t1   1   1   0.134613E-01\n    \t1   1   2   0.115650E-01\n    \t1   1   3   0.125559E-01\n    \t1   1   4   0.125286E-01\n    \t1   1   5   0.121647E-01\n    \t1   1   6   0.117333E-01\n    \t1   1   7   0.124280E-01\n    \t1   1   8   0.115808E-01\n    \t1   1   9   0.988294E-02\n    \t1   1  10   0.123670E-01\n    \t1   1  11   0.118903E-01\n    \t1   1  12   0.117026E-01\n    \t1   1  13   0.114063E-01\n    \t1   1  14   0.110016E-01\n    \t1   1  15   0.109395E-01\n    \t1   1  16   0.111800E-01\n    \t1   1  17   0.119092E-01\n    \t1   1  18   0.124901E-01\n    \t1   1  19   0.131205E-01\n    \t1   1  20   0.126538E-01\n    \t1   1  21   0.138799E-01\n    \t1   1  22   0.130093E-01\n    \t1   1  23   0.133729E-01\n    \t1   1  24   0.134214E-01\n    \t1   1  25   0.127005E-01\n    \t1   1  26   0.161253E-01\n    \t1   1  27   0.191886E-01\n    \t1   1  28   0.176198E-01\n    \t1   1  29   0.179799E-01\n    \t1   1  30   0.172136E-01\n    \t1   1  31   0.174579E-01\n    \t1   1  32   0.181361E-01\n    \t1   1  33   0.185459E-01\n    \t1   1  34   0.184355E-01\n    \t1   1  35   0.184394E-01\n    \t1   1  36   0.180923E-01\n    \t1   1  37   0.178597E-01\n    \t1   1  38   0.178598E-01\n    \t1   1  39   0.178598E-01\n    \t1   1  40   0.178598E-01\n    \t1   1  41   0.178598E-01\n    \t1   1  42   0.178598E-01\n    \t1   1  43   0.178598E-01\n    \t1   1  44   0.178598E-01\n    \t1   1  45   0.178598E-01\n    \t1   1  46   0.178598E-01\n    \t1   1  47   0.178598E-01\n    \t1   1  48   0.178598E-01\n    \t1   1  49   0.178598E-01\n    \t1   1  50   0.178598E-01\n    \t1   1  51   0.178598E-01\n    \t1   1  52   0.178598E-01\n    \t1   1  53   0.178598E-01\n    \t1   1  54   0.178598E-01\n    \t1   1  55   0.178598E-01\n    \t1   1  56   0.178598E-01\n    \t1   1  57   0.178598E-01\n    \t1   1  58   0.178598E-01\n    \t1   1  59   0.178598E-01\n    \t1   1  60   0.178598E-01\n    \t1   1  61   0.178598E-01\n    \t1   1  62   0.178598E-01\n    \t1   1  63   0.178598E-01\n    \t1   1  64   0.178598E-01\n    \t1   1  65   0.178598E-01\n    \t1   1  66   0.178598E-01\n    \t1   1  67   0.178598E-01\n    \t1   1  68   0.174253E-01\n    \t1   1  69   0.151741E-01\n    \t1   1  70   0.132923E-01\n    \t1   1  71   0.148204E-01\n    \t1   1  72   0.169102E-01\n    \t1   1  73   0.174304E-01\n    \t1   1  74   0.174491E-01\n    \t1   1  75   0.174725E-01\n    \t1   1  76   0.184029E-01\n    \t1   1  77   0.181126E-01\n    \t1   1  78   0.179639E-01\n    \t1   1  79   0.178554E-01\n    \n    \n\n\n\n```python\n# The second adjoint radiance field\nfarad2 = \"radobs_les0822nh15t13y89_ocaer1_w0.646_ns1ss2.arad\"\nprint_head(farad2)                \n\n```\n\n    Showing head: radobs_les0822nh15t13y89_ocaer1_w0.646_ns1ss2.arad\n    \t! Polarized Spherical Harmonic Discrete Ordinate Radiative Transfer Radiance Output\n    \t!  L= 15  M= 15  NLM=  256   NMU= 16  NPHI= 32  NANG=  354   NSH=   2422485\n    \t!  NSTOKES=1   NX= 320   NY=   1   NZ=  85    NPTS=   30052   NCELLS=   31290\n    \t!  PARTICLE_FILE=les0822nh15t13y89_ocaer1.part\n    \t!  CORRELATED_K-DIST_FILE=NONE   NUM_G= 1\n    \t!  SOURCE_TYPE=SOLAR               DELTA-M METHOD\n    \t!  GRID_TYPE=EVEN (X,Y)    PROPERTY-FILE (Z)    INDEPENDENT_PIXEL=2\n    \t!  SURFACE_TYPE=FIXED LAMBERTIAN         HORIZ_BOUNDARY_COND=0\n    \t!  GROUND_ALBEDO=0.0500000  SKY_RAD= 0.00000E+00\n    \t!  SOLAR_FLUX= 0.100000E+01   SOLAR_MU=-0.9221000   SOLAR_AZ= 339.400\n    \n    \n\n\n\n```python\n# A sample modis file\nfmodis_blue = \"les0822nh15t13_aer008_w0.646rad.modis\"\nprint_head(fmodis_blue)\n```\n\n    Showing head: les0822nh15t13_aer008_w0.646rad.modis\n    \t40  40  23\n    \t! Simulated MODIS reflectances from SHDOM radiance output\n    \t! IA   Rad(1:Ncross)\n    \t1 1.0000  0.00   0.00 20.000 20.000 ! idir, mu, theta, phi_shdom, size_cross, size_along\n    \t1 0.0765 0.1141 0.2162 0.1455 0.1407 0.0961 0.0401 0.0496 0.0690 0.0696 0.0722 0.0709 0.0778 0.0677 0.0694 0.0692 0.0725 0.1055 0.0934 0.0724 0.0701 0.0680 0.0680 0.0679 0.0680 0.0682 0.0684 0.0691 0.0747 0.0888 0.1230 0.0937 0.1201 0.0896 0.0944 0.0857 0.0592 0.0672 0.0700 0.0722\n    \t2 0.0702 0.0723 0.0972 0.0969 0.2869 0.2755 0.0567 0.0559 0.0687 0.0636 0.0761 0.0977 0.0996 0.1314 0.0961 0.0598 0.0686 0.0689 0.0840 0.0941 0.0648 0.0692 0.0710 0.0670 0.0679 0.0678 0.0682 0.0687 0.0697 0.0782 0.1025 0.0723 0.0575 0.0718 0.0841 0.0720 0.0803 0.0733 0.0694 0.0699\n    \t3 0.0697 0.0700 0.0712 0.0723 0.1212 0.1625 0.0773 0.0977 0.0573 0.0622 0.0979 0.0866 0.1896 0.2539 0.1146 0.1198 0.1418 0.0673 0.0754 0.1100 0.0931 0.0671 0.0703 0.0683 0.0682 0.0679 0.0679 0.0683 0.0690 0.0737 0.0956 0.0804 0.0713 0.0749 0.0772 0.0540 0.0561 0.0685 0.0757 0.0685\n    \t4 0.0694 0.0696 0.0701 0.0710 0.0913 0.1209 0.3438 0.3862 0.1215 0.0807 0.2028 0.1568 0.0961 0.1207 0.1067 0.0881 0.0820 0.0575 0.0992 0.0793 0.0712 0.0679 0.0682 0.0682 0.0680 0.0680 0.0680 0.0681 0.0685 0.0693 0.0719 0.0790 0.0823 0.1356 0.1346 0.0854 0.0563 0.0640 0.0692 0.0697\n    \t5 0.0604 0.0688 0.0695 0.0700 0.0711 0.0791 0.2566 0.4028 0.1625 0.1041 0.2124 0.2489 0.0943 0.0469 0.0659 0.0868 0.1006 0.1008 0.0864 0.0592 0.0674 0.0679 0.0683 0.0682 0.0680 0.0680 0.0681 0.0680 0.0681 0.0688 0.0703 0.0903 0.1479 0.1072 0.1253 0.0785 0.0636 0.0553 0.0680 0.0623\n    \t6 0.0458 0.0667 0.0691 0.0695 0.0700 0.0715 0.0777 0.1253 0.0972 0.0941 0.2480 0.1939 0.0607 0.0509 0.0740 0.0917 0.0764 0.0891 0.0833 0.0703 0.0682 0.0671 0.0684 0.0683 0.0681 0.0681 0.0682 0.0684 0.0680 0.0683 0.0696 0.0764 0.1183 0.1811 0.1659 0.1587 0.0729 0.0854 0.1028 0.0425\n    \n    \n\n\n\n```python\n# Reflectance from the MODIS case, but at full 320 x 320 resolution \nfhres_blue = \"les0822nh15t13_aer008_w0.646.ref\"\nprint_head(fhres_blue)\n```\n\n    Showing head: les0822nh15t13_aer008_w0.646.ref\n    \t0   0 0.0499 0.1004 0.2231 0.0945 0.0426 0.1586 0.0464\n    \t1   0 0.0495 0.1004 0.2272 0.0976 0.0393 0.2537 0.0463\n    \t2   0 0.0493 0.1004 0.2193 0.0935 0.0390 0.2863 0.0463\n    \t3   0 0.0493 0.1004 0.2151 0.0913 0.0391 0.2772 0.0463\n    \t4   0 0.0498 0.1004 0.2003 0.0937 0.0394 0.2357 0.0462\n    \t5   0 0.0533 0.1003 0.1858 0.0979 0.0399 0.1731 0.0462\n    \t6   0 0.0583 0.1003 0.1592 0.1063 0.0407 0.1175 0.0461\n    \t7   0 0.0602 0.1002 0.1362 0.1148 0.0413 0.0771 0.0460\n    \t8   0 0.0602 0.1002 0.1257 0.1197 0.0413 0.0479 0.0459\n    \t9   0 0.0602 0.1001 0.1255 0.1194 0.0413 0.0425 0.0459\n    \n    \n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "0e62248649aa99ac5cc297975ebc93986684d1ef", "size": 456982, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "data-adjoint3/exploring_adjoint_with_aerosol.ipynb", "max_stars_repo_name": "wgm2111/wgm-shdom-files-AGU2015", "max_stars_repo_head_hexsha": "113abfb73a12b8993ed6ddfc981dba5611bf7ae5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "data-adjoint3/exploring_adjoint_with_aerosol.ipynb", "max_issues_repo_name": "wgm2111/wgm-shdom-files-AGU2015", "max_issues_repo_head_hexsha": "113abfb73a12b8993ed6ddfc981dba5611bf7ae5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data-adjoint3/exploring_adjoint_with_aerosol.ipynb", "max_forks_repo_name": "wgm2111/wgm-shdom-files-AGU2015", "max_forks_repo_head_hexsha": "113abfb73a12b8993ed6ddfc981dba5611bf7ae5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 426.2891791045, "max_line_length": 125008, "alphanum_fraction": 0.9213251288, "converted": true, "num_tokens": 9732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.055823143490797325, "lm_q1q2_score": 0.0270396189486786}}
{"text": "MIT License\n\nCopyright (c) 2021 Taiki Miyagawa and Akinori F. Ebihara\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n# <font color=red> Lite version reduces GPU memory consumption at the expense of CPU memory and runtime. </font> Take care of  your CPU memory.\n\n# Plot Speed-Accuracy Tradeoff (SAT) Curve of Validation dataset\n\n\n```python\nfrom __future__ import absolute_import, division, print_function\n\nimport os, sys, glob, time\nfrom itertools import zip_longest\nimport optuna\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import LogFormatter, ScalarFormatter, NullFormatter\nimport numpy as np\nimport tensorflow as tf\n\nfrom datasets.data_processing import read_tfrecords_UCF101,\\\n    decode_feat, sequential_slice, sequential_concat\nfrom models.backbones_ti import LSTMModelLite\nfrom models.optimizers import get_optimizer\nfrom models.losses import get_gradient_lstm\nfrom utils.misc import load_yaml, set_gpu_devices, fix_random_seed,\\\n    restrict_classes, extract_positive_row, add_max_to_diag\nfrom utils.performance_metrics import multiplet_sequential_confmx,\\\n    llr_sequential_confmx,\\\n    truncated_MSPRT, threshold_generator,\\\n    calc_llrs, calc_oblivious_llrs, threshold_generator, thresh_sanity_check,\\\n    NP_test,\\\n    get_LLR_min_and_max, get_linspace, threshold_generator_with_values,\\\n    seqconfmx_to_metrics\n```\n\n# User-defined params\n\n\n```python\n# User-defined\norder_sprt = 10 # order of MSPRT-TANDEM\noblivious = False # M-TANDEM (False) or M-TANDEMwO (True)\nname_model = \"./data-directory/sprt_multiclass/UCF101/ckptlogs/MSPRT-TANDEM_ver20210331_stat/__20210424_150952523/\" # for example\n```\n\n\n```python\n# User-defined\nnum_thresh = 10 # Total number of thresholds to be used to plot the SAT curve\nbatch_thresh = 5 # Memory consuming!! How many thresholds to be feeded at a time. < 10 is recommended\nsparsity = \"linspace\" # \"linspace\" or logspace\". Used for threshold generation.\nclass_plot = -2 # -1:micro-averaged recall, -2:macro-averaged recall.\ndataname = \"UCF101-50-240-320\" # \"UCF101-150-240-320\", \"UCF101-50-256-256\", ...\n\ntfr_train = \"DATADIR/UCF101TFR-50-240-320/train01.tfrecords\"\ntfr_valid = \"DATADIR/UCF101TFR-50-240-320/valid01.tfrecords\"\ntfr_test = \"DATADIR/UCF101TFR-50-240-320/test01.tfrecords\"\nbatch_size = 100 # Must be a divisor of the num of test datapoints. Memory consumption << batch_thresh.\nbatch_size2 = 50 # used for calc_llrs, NP_test, and trundated_MSPRT. Not necessarily a divisor of the sample size.\ngpu = 0 # Which GPU to be used\n\nassert num_thresh % batch_thresh == 0 # Make sure\n```\n\n\n```python\n# Must be consistent with the model (name_model).\nduration = 50 \nfeat_dim = 2048 # input feature dimension\nnum_classes = 101\nwidth_lstm = 256 # dim of hidden layers of LSTM\ndropout = 0.\nactivation = \"tanh\"\n```\n\n\n```python\n# Which GPU to be used\nset_gpu_devices(gpu)\n```\n\n# 0. Start calc logits and LLRs\n\n\n```python\n# Load data\n##################################\n# Reed tfr and make \ndataset_tr, dataset_va,\\\n    dataset_te = \\\n    read_tfrecords_UCF101(\n        record_file_tr=tfr_train, \n        record_file_va=tfr_valid,\n        record_file_te=tfr_test,\n        batch_size=batch_size, \n        flag_shuffle=False,\n        shuffle_buffer_size=10000)\n\n# Model\n##################################\nmodel = LSTMModelLite(\n    num_classes=num_classes, \n    width_lstm=width_lstm, \n    dropout=dropout, \n    activation=activation) \n\n# Restore parameters\n#################################\nckpt = tf.train.Checkpoint(net=model)\nckpt_manager_restore = tf.train.CheckpointManager(ckpt,\n    name_model, max_to_keep=3)\nckpt.restore(ckpt_manager_restore.latest_checkpoint)\nprint(\"Restored latest model\\n{}\".format(\n    ckpt_manager_restore.latest_checkpoint)) \n\n# Evaluaton loop\n##################################\nfor iter_b, feats in enumerate(dataset_va):\n    cnt = iter_b + 1\n\n    x_batch = feats[0]\n    x_batch = tf.reshape(x_batch, (-1, duration, feat_dim)) \n        # (batch, duration, feat dims)\n    y_batch = feats[1]\n        # (batch, )\n\n    x_slice, y_slice = sequential_slice(x_batch, y_batch, order_sprt)\n\n    # Calc logits \n    if iter_b == 0:\n        ls_logits = []\n        ls_labels = []\n\n    # Calc loss\n    logits_tmp = model(x_slice, False)\n    logits_tmp, _ = sequential_concat(logits_tmp, y_slice, duration) \n\n    ls_logits.append(logits_tmp.numpy()) \n    ls_labels.append(y_batch.numpy()) \n\n    # Verbose\n    if ((iter_b+1)%10 == 0) or (iter_b == 0):\n        sys.stdout.write(\"\\rEvaluation Iter: {:3d}\".format(iter_b+1))\n        sys.stdout.flush()\n\nprint()\nlogits_all = np.concatenate(ls_logits, axis=0) \nlabels_all = np.concatenate(ls_labels, axis=0) \n```\n\n    Restored latest model\n    /data/t-miyagawa/sprt_multiclass/UCF101/ckptlogs/50-240-320_ME_CSL_ver20210331_stat/__20210424_150952523/ckpt_step2600_macrec0.83303-10\n    Evaluation Iter:  40\n\n\n\n```python\n# Calc LLRs  \nnum_data = labels_all.shape[0]\nnum_iter = num_data // batch_size2 if num_data % batch_size2 == 0 else num_data // batch_size2 + 1\nllrs_all = []\nstart = -1\nstop = -1\nfor i in range(num_iter):    \n    itr_logits = logits_all[i * batch_size2 : (i + 1) * batch_size2]\n\n    if oblivious:\n        itr_llrs = calc_oblivious_llrs(itr_logits)\n    else:\n        itr_llrs = calc_llrs(itr_logits)\n\n    llrs_all.append(itr_llrs.numpy())        \n        \n    # Used to generate thresholds\n    tmp_start, tmp_stop = get_LLR_min_and_max(itr_llrs) # A bit memory consuming.\n    tmp_start = tmp_start.numpy()\n    tmp_stop = tmp_stop.numpy()\n\n    if i == 0:\n        start = tmp_start\n        stop = tmp_stop\n        continue\n    \n    if tmp_start < start:\n        start = tmp_start\n    if tmp_stop > stop:\n        stop = tmp_stop\n\n    # Verbose\n    if ((iter_b + 1) % 10 == 0) or (iter_b == 0):\n        sys.stdout.write(\"\\rEvaluation Iter: {:3d}/{}\".format(iter_b+1, num_iter))\n        sys.stdout.flush()\n\n        \nvalues = get_linspace(start, stop, num_thresh, sparsity).numpy()\nllrs_all = np.concatenate(llrs_all, axis=0)\n```\n\n\n```python\ntic = time.time()\nprint(\"This cell takes a few minutes because of the two mini-batch processes...\")\n\n# Batch processing for thresh axis to save GPU memory \n######################################################\nnum_data = labels_all.shape[0]\nls_confmx_th = []\nls_mht_th = []\nls_vht_th = []\nls_trt_th = []\nfor i in range(num_thresh // batch_thresh):\n    print(\"Thresh Iter {}/{} ...\".format(i+1, num_thresh // batch_thresh))\n    \n    # Generate Thresholds for SPRT\n    idx = batch_thresh * i\n    itr_values = values[idx : idx + batch_thresh]\n    itr_thresh = threshold_generator_with_values(itr_values, duration, num_classes) # memory consuming\n    thresh_sanity_check(itr_thresh)\n    \n    # Batch processing for data axis to save GPU memory\n    ####################################################\n    num_iter = num_data // batch_size2 if num_data % batch_size2 == 0 else num_data // batch_size2 + 1\n    tmp_confmx_th = 0\n    tmp_mht_th = []\n    tmp_sqr_th = []\n    tmp_trt_th = []\n    for i in range(num_iter):\n        itr_llrs = llrs_all[i * batch_size2 : (i + 1) * batch_size2]\n        itr_labels = labels_all[i * batch_size2 : (i + 1) * batch_size2]\n        _len = itr_labels.shape[0]\n\n        # Confusion matrix of SPRT, mean/var hitting time, \n        # and truncation rate\n        _tmp_confmx_th, _tmp_mht_th, _tmp_vht_th, _tmp_trt_th = \\\n            truncated_MSPRT(\n                llr_mtx=itr_llrs,\n                labels_concat=itr_labels,\n                thresh_mtx=itr_thresh) \n                # Super GPU memory super-consuming \n                # if batch_thresh or batch_size2 is large.\n            # The shapes of the outputs are:\n            # (batch_thresh, num classes, num classes)\n            # (batch_thresh,)\n            # (batch_thresh,)\n            # (batch_thresh,)\n        _tmp_sqr_th = _tmp_vht_th + _tmp_mht_th ** 2\n            \n        tmp_confmx_th += _tmp_confmx_th.numpy()\n        tmp_mht_th.append(np.expand_dims(_tmp_mht_th.numpy(), axis=0) * _len)\n        tmp_sqr_th.append(np.expand_dims(_tmp_sqr_th.numpy(), axis=0) * _len)\n        tmp_trt_th.append(np.expand_dims(_tmp_trt_th.numpy(), axis=0) * _len) #<- should be integers\n\n    tmp_mht_th = np.concatenate(tmp_mht_th, axis=0) # (num_iter, batch_thresh)\n    tmp_mht_th = np.sum(tmp_mht_th, axis=0) / num_data # (batch_thresh, )\n    tmp_sqr_th = np.concatenate(tmp_sqr_th, axis=0) # (num_iter, batch_thresh)\n    tmp_sqr_th = np.sum(tmp_sqr_th, axis=0) / num_data # (batch_thresh, )\n    tmp_vht_th = tmp_sqr_th - tmp_mht_th ** 2 # (batch_thresh, )\n    tmp_trt_th = np.concatenate(tmp_trt_th, axis=0) # (num_iter, batch_thresh)\n    tmp_trt_th = np.sum(tmp_trt_th, axis=0) / num_data # (batch_thresh, )\n\n    ls_confmx_th.append(tmp_confmx_th)\n    ls_mht_th.append(tmp_mht_th)\n    ls_vht_th.append(tmp_vht_th)\n    ls_trt_th.append(tmp_trt_th)\n\nconfmx_th = np.concatenate(ls_confmx_th, axis=0) # (num thresh, num cls, num cls)\nmht_th = np.concatenate(ls_mht_th, axis=0) # (num thresh, )\nvht_th = np.concatenate(ls_vht_th, axis=0) # (num thresh, )\ntrt_th = np.concatenate(ls_trt_th, axis=0) # (num thresh, )\n\nprint(time.time() - tic, \"seconds\")\n```\n\n    This cell takes a few minutes because of the two mini-batch processes...OMG\n    Thresh Iter 1/2 ...\n    Thresh Iter 2/2 ...\n    25.820960521697998 seconds\n\n\n\n```python\n# SPRT results\n###########################\n# Extract recalls (sensitivities)\ndc_mtr = seqconfmx_to_metrics(confmx_th)\n\n# Output\nls_sns = dc_mtr[\"SNS\"].numpy()\n    # (num thresh, num classes + 2)\n    # [[recall of class 0, 1, 2, ..., recall of the last class, balanced accuracy, accuracy], ...]\n\nls_mht = mht_th#.numpy()\n    # (num thresh,)\nls_vht = vht_th#.numpy()\n    # (num thresh,)\nls_trt = trt_th#.numpy()\n    # (num thresh,)\n\n    \n# NPT confmx\n############################\nnum_iter = num_data // batch_size2 if num_data % batch_size2 == 0 else num_data // batch_size2 + 1\nseqconfmx_llr = 0\n\nfor i in range(num_iter):\n    if (i + 1) % 50 == 0:\n        print(\"Iter {}/{}\".format(i+1, num_iter))\n\n    itr_llrs = llrs_all[i * batch_size2 : (i + 1) * batch_size2]\n    itr_labels = labels_all[i * batch_size2 : (i + 1) * batch_size2]\n\n    _tmp_seqconfmx_llr = NP_test(itr_llrs, itr_labels)\n        # (duration, num classes, num classes)\n    seqconfmx_llr += _tmp_seqconfmx_llr.numpy()\n        # (duration, num classes, num classes)\n        \n\n# NPT results\n###########################\ndc_mtr_llr = seqconfmx_to_metrics(seqconfmx_llr)\n\n# Output\nls_sns_NPT = dc_mtr_llr[\"SNS\"].numpy()\n    # (duration, num classes + 2)\n    # [[recall of class 0, 1, 2, ..., recall of the last class, balanced accuracy, accuracy], ...]\n################## end TMmod 20210106 ###############\n```\n\n    Iter 50/90\n\n\n\n```python\nls_trt # truncation rate. All 0 or all 1 signal a problem.\n```\n\n\n\n\n    array([0.       , 0.3405927, 0.6012573, 0.8621464, 0.9986529, 1.       ,\n           1.       , 1.       , 1.       , 1.       ], dtype=float32)\n\n\n\n__Materials__\n1. `ls_mht` \n\n2. `ls_vht` \n\n3. `ls_trt` \n\n4. `ls_sns` \n\n5. `ls_sns_NPT` \n\n\n# 1. Plot SAT (Speed-Accuracy Tradeoff) Curve\n\n\n```python\n# Start plotting SP curve\n######################################\n# Parameters\nx = ls_mht\ny = 100 * (1 - ls_sns[:, class_plot]) # macro-averaged recall\n\ntitle = \"SAT curve, data={}, order={}\".format(dataname, order_sprt)\nxlabel = \"Mean hitting time (# frames)\"\nif class_plot < num_classes:\n    _tmp = \"(Class={})\".format(class_plot)\nelif class_plot == num_classes:\n    _tmp = \"(Mac-ave)\"\nelif class_plot == num_classes + 1:\n    _tmp = \"(Mic-ave)\"\nelse:\n    raise ValueError\nylabel = \"100 - Recall ({}) (%)\".format(_tmp)\n\n\n# Size\nplt.rcParams[\"font.size\"] = 25\nfig, ax = plt.subplots(figsize=(13,8))\nfig.patch.set_facecolor('white')\n# Scale\nax.set_xscale('log')\n# Grid\nmajor_ticks = np.arange(0, duration + 1, 10)\nmajor_ticks[0] += 1\nminor_ticks = np.arange(0, duration + 1, 1)\nax.set_xticks(major_ticks)\nax.set_xticks(minor_ticks, minor=True)\nax.set_xticklabels(['0, 10, 20, 30, 40, 50'])\nfor axis in [ax.xaxis, ax.yaxis]: # ?\n    axis.set_major_formatter(ScalarFormatter())\n    axis.set_minor_formatter(NullFormatter())\n\n# Plot\nplt.scatter(\n    x, y, \n    s=10, \n    color=\"red\", \n    marker='o', \n    vmin=None, \n    vmax=None, \n    alpha=None, \n    linewidths=None,\n    edgecolors=None\n    )\n\nplt.ylabel(ylabel)        \nplt.xlabel(xlabel)\nplt.grid(which='both')\n#plt.legend(loc=None, fontsize='15')\nplt.title(title)\nplt.xlim(0.95, duration+0.3)# 1stO, 19thO\n#plt.xlim(3.95, duration+0.3)# 1stO, 19thO\n#plt.ylim(99.08, 99.65) # 1stO, 19thO\n#plt.xlim(4.-0.3, duration+0.3)# 1stO, 19thO\n#plt.ylim(70.08, 80.65) # 1stO, 19thO\nplt.tight_layout()\n\n# Save figure\n#plt.savefig(***)\n```\n\n## 1-1. SPRT vs NPT\n\n\n```python\n# Plot NPT vs SPRT\n###############################\n# Parameters\nx = ls_mht\ny = 100 * (1 - ls_sns[:, class_plot])\nx_np = np.array([i + 1 for i in range(duration)])\ny_np = 100 * (1 - ls_sns_NPT[:, class_plot])\nlabel = \"SPRT\"\nlabel_np = \"NPT\"\ntitle = \"SAT curve, data={}, order={}\".format(dataname, order_sprt)\nxlabel = \"Mean hitting time (# frames)\"\nif class_plot < num_classes:\n    _tmp = \"(Class={})\".format(class_plot)\nelif class_plot == num_classes:\n    _tmp = \"(Mac-ave)\"\nelif class_plot == num_classes + 1:\n    _tmp = \"(Mic-ave)\"\nelse:\n    raise ValueError\nylabel = \"100 - Recall ({}) (%)\".format(_tmp)\n\n\n\n# Size\nplt.rcParams[\"font.size\"] = 25\nfig, ax = plt.subplots(figsize=(13,8))\n# Scale\nax.set_xscale('log')\n# Grid\nmajor_ticks = np.arange(0, duration + 1, 10)\nmajor_ticks[0] += 1\nminor_ticks = np.arange(0, duration + 1, 1)\nax.set_xticks(major_ticks)\nax.set_xticks(minor_ticks, minor=True)\nax.set_xticklabels(['0, 10, 20, 30, 40, 50'])\nfor axis in [ax.xaxis, ax.yaxis]: # ?\n    axis.set_major_formatter(ScalarFormatter())\n    axis.set_minor_formatter(NullFormatter())\n\n# Plot SPRT\nplt.scatter(\n    x, y, \n    s=10, \n    color=\"red\", \n    marker='o', \n    vmin=None, \n    vmax=None, \n    alpha=None, \n    linewidths=None,\n    edgecolors=None,\n    label=\"SPRT\"\n    )\n\n# Plot NPT\nplt.scatter(\n    x_np, y_np, \n    s=10, \n    color=\"blue\", \n    marker='o', \n    vmin=None, \n    vmax=None, \n    alpha=None, \n    linewidths=None,\n    edgecolors=None,\n    label=\"NPT\"\n    )\n\nplt.ylabel(ylabel)        \nplt.xlabel(xlabel)\nplt.grid(which='both')\nplt.legend(loc=1, fontsize='15')\nplt.title(title)\nplt.xlim(0.95, duration+0.3)\n#plt.xlim(10.95, duration+0.3)\n#plt.ylim(88., 99.7) # v1\n#plt.ylim(95, 99.7) # v2\nplt.tight_layout()\n\n# Save figure\n# plt.savefig(***)\n```\n\n# 2. Plot SAT Curve with Standard Deviation of Hitting Times\n\n\n```python\n# Start plotting SP curve with variance\n######################################\n# Parameters\nx = ls_mht\ny = 100. * ls_sns[:, -2] # macro-averaged recall\nxerr =  np.sqrt(ls_vht)\ntitle = \"SAT Curve, data=NMNIST, order={}\".format(order_sprt)\nxlabel = \"Mean Hitting Time (# frames)\"\nylabel = \"Macro-averaged recall (%)\"\n\n# Size\nplt.rcParams[\"font.size\"] = 25\nfig, ax = plt.subplots(figsize=(13,8))\nfig.patch.set_facecolor('white')\n# Scale\n#ax.set_xscale('log')\n# Grid\nmajor_ticks = np.arange(0, duration + 1, 10)\nmajor_ticks[0] += 1\nminor_ticks = np.arange(0, duration + 1, 1)\nax.set_xticks(major_ticks)\nax.set_xticks(minor_ticks, minor=True)\nax.set_xticklabels(['0, 10, 20, 30, 40, 50'])\nfor axis in [ax.xaxis, ax.yaxis]: # ?\n    axis.set_major_formatter(ScalarFormatter())\n    axis.set_minor_formatter(NullFormatter())\n    \n# Plot\nplt.errorbar(\n    x, y, \n    xerr = xerr, \n    capsize=3, \n    fmt='o', \n    markersize=2, \n    ecolor='black', \n    markeredgecolor = \"black\", \n    color='red',\n    elinewidth=0.5)\n\nplt.ylabel(ylabel)        \nplt.xlabel(xlabel)\nplt.grid(which='both')\n#plt.legend(loc=4, fontsize='15')\nplt.title(title)\n#plt.xlim(0.95, duration+0.3)\n#plt.ylim(88., 99.7) # v1\n#plt.ylim(95, 99.7) # v2\nplt.tight_layout()\n\n# Save figure\n# plt.savefig(***)\n```\n\n# 3. Plot Trajectories of LLRs\n\n- min LLR.\n    - $\\mathrm{max}_k \\mathrm{min}_{l \\neq k} \\mathrm{LLR}_{kl} (t)$ on a single plane\n- min LLR for each class ($K$ plots).\n    - $\\mathrm{min}_{l \\neq k} \\mathrm{LLR}_{kl} (t)$. One $k$, one plane\n- all LLRs for each class ($K$ plots in each of which there are $K$ - 1 types of trajectories).\n    - $\\mathrm{LLR}_{kl} (t)$, where $k \\neq l$. One $k$, one plane.\n- all LLRs, positive class mins (red) and negative class mins (blue).\n    - $\\mathrm{min}_{l \\neq k} \\mathrm{LLR}_{kl} (t)$, where `color = red` if $k = y_i$ else `color = blue`. \n- positive LLR row. All and each k.\n    - $\\mathrm{LLR}_{y_{i}\\, l}$, where $l \\neq y_i$\n\n\\begin{equation}\n    \\lambda(t) := \n    \\begin{pmatrix}\n    0                & \\cdots &  \\lambda_{1l}(t) & \\cdots & \\lambda_{1K}(t)\\\\\n    \\vdots           & \\ddots &                  &        & \\vdots \\\\\n    -\\lambda_{1l}(t) &        &                0 &        & \\lambda_{kK}(t) \\\\\n    \\vdots           &        &                  & \\ddots & \\vdots \\\\\n    -\\lambda_{1K}(t) & \\cdots & -\\lambda_{kK}(t) & \\cdots & 0\n    \\end{pmatrix}\n\\end{equation}\n\n\\begin{equation}\n    \\lambda_{kl}(t) := \\log(\\frac{p(X^{(1,t)}\\,\\,\\,|y=k)}{p(X^{(1,t)}\\,\\,\\,|y=l)})\\,\\,\\, (k, l \\in [K], K\\in\\mathbb{N})\n\\end{equation}\n\n\n## 3-4-1. All LLR rows with minimum $l  \n\n- $\\mathrm{min}_{l\\neq k} \\mathrm{LLR}_{k\\, l}$\n\n\n```python\nnum_trj = 1\nplot_classes = [] # optional: default=[]\nshuffle = True # currently not supported\n```\n\n\n```python\n# Initialization\nllrs_trj = llrs_all[:num_trj]\nlabels_trj = labels_all[:num_trj]\n\n# Restrict classes (optional)\nllrs_trj, labels_trj = restrict_classes(llrs_trj, labels_trj, plot_classes)\nlabels_trj = labels_trj.numpy() if len(plot_classes) != 0 else labels_trj \n\n### Add max LLR to diag\nllrs_trj = add_max_to_diag(llrs_trj)\n\n### Extract min column: shape change (batch, duration, num classes num classes) -> (batch, duration, num classes)\nllrs_trj = tf.reduce_min(llrs_trj, axis=3)\n\n# Shuffle (optional)\nif shuffle:\n    idx_perm = np.random.permutation(labels_trj.shape[0]) # randomly take some LLRs\n    llrs_trj = tf.constant(llrs_trj.numpy()[idx_perm], dtype=tf.float32)\n    labels_trj = tf.constant(labels_trj[idx_perm], dtype=tf.int32)\n    \n# Pick some out\nllrs_trj = llrs_trj[:num_trj].numpy()\nlabels_trj = labels_trj[:num_trj].numpy()\n```\n\n\n```python\n# Color definitions\nls_color = [\n    \"red\",\n    \"blue\",\n]\nls_plotLabel =[\n    \"min_l {LLR_k =yi l}\",\n    \"min_l {LLR_k!=yi l}\",\n] \n```\n\n\n```python\n# Start plotting trajectory\n######################################\n# Parameters\nx = [i for i in range(0, duration+1)]\ntitle = \"Random example LLR trajectory,\\ndata=NMNIST-100f15pix, order={}\".format(order_sprt)\nxlabel = \"Frame\"\nylabel = \"Log-likelihood ratio\"\n\n# Size\nplt.rcParams[\"font.size\"] = 25\nplt.figure(figsize=(13,8)) \n\n# plt.xticks([1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100],\n#     [])\n\n_tmp = set()\nfor itr_llrs, itr_label in zip(llrs_trj, labels_trj):\n    itr_llrs = np.transpose(itr_llrs, [1, 0])\n        # (num classes, duration)\n    for itr_i, itr_trj in enumerate(itr_llrs):\n        y = np.append(0, itr_trj)\n        \n        # Color and plot label\n        if itr_i == itr_label:\n            color = ls_color[0]\n            if not (_tmp >= {ls_plotLabel[0]}):\n                plot_label = ls_plotLabel[0]\n                _tmp.add(plot_label)\n            else:\n                plot_label = None\n        else:\n            color = ls_color[1]\n            if not (_tmp >= {ls_plotLabel[1]}):\n                plot_label = ls_plotLabel[1]\n                _tmp.add(plot_label)    \n            else:\n                plot_label = None\n        \n        # Plot\n        plt.plot(\n            x, y, \n            color=color, \n            marker='o', \n            linewidth=1, \n            markersize=0,\n            label=plot_label,\n            alpha=0.7\n            )\n        cnt += 1\n\nplt.xlabel(xlabel)\nplt.ylabel(ylabel)        \nplt.yscale(\"symlog\")\nplt.grid(True)\nplt.legend(fontsize='15')\nplt.title(title)\nplt.xticks([i for i in range(0, duration + 1)])\n#plt.xlim(-0.1, 20.1)\nplt.locator_params(axis='x', nbins=11)\nplt.tight_layout()\n\n# Save figure \n# plt.savefig(\n#     \"./traj_order{}.svg\".format(order_sprt), \n#     format=\"svg\", \n#     dpi=1200)\n```\n\n## 3-1. Positive LLR row\n\n- $\\mathrm{LLR}_{y_{i}\\, l}$, where $l \\neq y_i$\n\n\n```python\nnum_trj = 10\nplot_classes = [] # optional: default=[]\nshuffle = True # currently not supported\n```\n\n\n```python\n# Initialization\nllrs_trj = llrs_all[:50]\nlabels_trj = labels_all[:50]\n\n# Restrict classes (optional)\nllrs_trj, labels_trj = restrict_classes(llrs_trj, labels_trj, plot_classes)\nlabels_trj = labels_trj.numpy() if len(plot_classes) != 0 else labels_trj ################### TMmod 20210106 ###############\n\n### Extract positive rows: shape change -> (batch, duration, num classes)\nllrs_trj = extract_positive_row(llrs_trj, labels_trj)\n\n# Shuffle (optional)\nif shuffle:\n    idx_perm = np.random.permutation(labels_trj.shape[0]) # randomly take some LLRs\n    llrs_trj = tf.constant(llrs_trj.numpy()[idx_perm], dtype=tf.float32)\n    labels_trj = tf.constant(labels_trj[idx_perm], dtype=tf.int32)\n\n# Pick some up\nllrs_trj = llrs_trj[:num_trj].numpy()\nlabels_trj = labels_trj[:num_trj].numpy()\n```\n\n\n```python\n# Color definitions\nls_color = [\n    None\n] * num_classes\nls_plotLabel =[\n    \"_\"] * num_classes\n```\n\n\n```python\n# Start plotting trajectory\n######################################\n# Parameters\nx = [i for i in range(0, duration+1)]\ntitle = \"Random example LLR trajectory, data=NMNIST, order={}\".format(order_sprt)\nxlabel = \"Frame\"\nylabel = \"Log-likelihood ratio\"\n\n# Size\nplt.rcParams[\"font.size\"] = 25\nplt.figure(figsize=(13,8)) \n\n_tmp = set()\nfor itr_llrs, itr_label in zip(llrs_trj, labels_trj):\n    itr_llrs = np.transpose(itr_llrs, [1, 0])\n    itr_llrs = np.delete(itr_llrs, obj=itr_label, axis=0)\n        # (num classes - 1, duration)\n    for itr_trj in itr_llrs:\n        y = np.append(0, itr_trj)\n        \n        # Color\n        color = ls_color[itr_label]\n        \n        # Label\n        if _tmp >= {itr_label}:\n            plot_label = None\n        else:\n            _tmp.add(itr_label)\n            plot_label = ls_plotLabel[itr_label]\n        \n        # Plot\n        plt.plot(\n            x, y, \n            color=color, \n            marker='o', \n            linewidth=1, \n            markersize=0,\n            label=plot_label\n            )\n        cnt += 1\n\nplt.xlabel(xlabel)\nplt.ylabel(ylabel)        \nplt.yscale(\"symlog\")\nplt.grid(True)\n#plt.legend(fontsize='15')\nplt.title(title)\nplt.xticks([i for i in range(0, duration + 1)])\n#plt.xlim(-0.1, 20.1)\n\nplt.tight_layout()\n\n# Save figure \n# plt.savefig(\n#     \"./traj_order{}.svg\".format(order_sprt), \n#     format=\"svg\", \n#     dpi=1200)\n```\n\n## 3-3. Positive LLR row with minimum $l$\n- $\\mathrm{min}_{l (\\neq y_i)} \\mathrm{LLR}_{y_{i}\\, l}$\n\n\n```python\nnum_trj = 20\nplot_classes = [] # optional: default=[]\nshuffle = True # currently not supported\n```\n\n\n```python\n# Initialization\nllrs_trj = llrs_all[:100]\nlabels_trj = labels_all[:100]\n\n# Restrict classes (optional)\nllrs_trj, labels_trj = restrict_classes(llrs_trj, labels_trj, plot_classes)\nlabels_trj = labels_trj.numpy() if len(plot_classes) != 0 else labels_trj ################### TMmod 20210106 ###############\n### Add max LLR to diag\nllrs_trj = add_max_to_diag(llrs_trj)\n\n### Extract positive rows: shape change -> (batch, duration, num classes)\nllrs_trj = extract_positive_row(llrs_trj, labels_trj)\n\n### Extract min column: shape change (batch, duration, num classes) -> (batch, duration)\nllrs_trj = tf.reduce_min(llrs_trj, axis=2)\n\n# Shuffle (optional)\nif shuffle:\n    idx_perm = np.random.permutation(labels_trj.shape[0]) # randomly take some LLRs\n    llrs_trj = tf.constant(llrs_trj.numpy()[idx_perm], dtype=tf.float32)\n    labels_trj = tf.constant(labels_trj[idx_perm], dtype=tf.int32)\n    \n# Pick some up\nllrs_trj = llrs_trj[:num_trj].numpy()\nlabels_trj = labels_trj[:num_trj].numpy()\n```\n\n\n```python\n# Color definitions\nls_color = [\n    None\n] * num_classes\nls_plotLabel =[\n    \"_\"] * num_classes\n```\n\n\n```python\n# Start plotting trajectory\n######################################\n# Parameters\nx = [i for i in range(0, duration+1)]\ntitle = \"Random example LLR trajectory, data=NMNIST, order={}\".format(order_sprt)\nxlabel = \"Frame\"\nylabel = \"Log-likelihood ratio\"\n\n# Size\nplt.rcParams[\"font.size\"] = 25\nplt.figure(figsize=(13,8)) \n\n_tmp = set()\nfor itr_trj, itr_label in zip(llrs_trj, labels_trj):\n    y = np.append(0, itr_trj)\n\n    # Color\n    color = ls_color[itr_label]\n\n    # Label\n    if _tmp >= {itr_label}:\n        plot_label = None\n    else:\n        _tmp.add(itr_label)\n        plot_label = ls_plotLabel[itr_label]\n\n    # Plot\n    plt.plot(\n        x, y, \n        color=color, \n        marker='o', \n        linewidth=2, \n        markersize=0,\n        label=plot_label\n        )\n\nplt.xlabel(xlabel)\nplt.ylabel(ylabel)        \nplt.yscale(\"symlog\")\nplt.grid(True)\n#plt.legend(fontsize='15')\n#plt.title(title)\nplt.xticks([10 * i for i in range(0, 6)])\n#plt.xlim(-0.1, 20.1)\n\nplt.tight_layout()\n\n# Save figure \n# filename = \"/data/t-miyagawa/sprt_multiclass/nosaic_mnist-1000f/graphs/LLRtrajectory_UCF101v4\"\n# plt.savefig(\n#     \"{}.svg\".format(filename), \n#     format=\"svg\", \n#     dpi=1200)\n```\n", "meta": {"hexsha": "1ce980355e9b048d58892497664fa7353ea46a1c", "size": 636041, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "plot_SATC_casual_lite.ipynb", "max_stars_repo_name": "TaikiMiyagawa/MSPRT-TANDEM", "max_stars_repo_head_hexsha": "dc337c5ffc3ae0e2feaca1da2b1760737a930c98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-31T02:44:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T13:18:24.000Z", "max_issues_repo_path": "plot_SATC_casual_lite.ipynb", "max_issues_repo_name": "TaikiMiyagawa/MSPRT-TANDEM", "max_issues_repo_head_hexsha": "dc337c5ffc3ae0e2feaca1da2b1760737a930c98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plot_SATC_casual_lite.ipynb", "max_forks_repo_name": "TaikiMiyagawa/MSPRT-TANDEM", "max_forks_repo_head_hexsha": "dc337c5ffc3ae0e2feaca1da2b1760737a930c98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 507.2097288676, "max_line_length": 247944, "alphanum_fraction": 0.9365874213, "converted": true, "num_tokens": 7670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.07369626461990013, "lm_q1q2_score": 0.027016294214937307}}
{"text": "\n\n<a href=\"https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcallysto-sample-notebooks&branch=master&subPath=notebooks/Demonstrations/tutorials/JupyterTestdrive-MarkDown.ipynb&depth=1\" target=\"_parent\"></a>\n\n# Jupyter Test Drive - Typesetting with Markdown\n\nIn this notebook we'll be walking through some activities so you can familiarize yourself with using a Jupyter notebook for typesetting with markdown. This can be useful if you want to modify an existing notebook, or even to help your students use Jupyter for typesetting answers to any activities they do using Callysto. \n\n## The _very_ Basics\n\nNote that you can view the source code behind any cell by double clicking it. To re-render or re-run the cell, use any of these options:\n1. Select `Cell` $\\rightarrow$ `Run Cells`\n2. Hit `Shift-Enter` \n3. Click the `Run` button above\n\n## Creating and Deleting Markdown Cells\nThe first step you may want do do is actually create a new cell for typesetting. In order to do that, while you have this cell selected, from the top menu click the plus (+) sign next to the save button. \n\nOnce you have created the new cell, you will get a blank `Code` cell above. In order to change that cell into one that you can use for typesetting, select it, and from the dropdown menu at the top, change `Code` $\\rightarrow$ `Markdown`. This changes that cell type into a markdown cell, and it can now be used for typesetting!\n\n\nThe next step will be learning how to delete cells. Select the cell above that you just converted to a markdown cell. In order to remove this cell from your Jupyter notebook, from the top menu click `Edit` $\\rightarrow$ `Delete Cells`. If you accidentally deleted an incorrect cell, you can always bring it back by clicking `Edit` $\\rightarrow$ `Undo Delete Cells`. \n\n## Creating Titles\n\nCreating large bold title text in a Jupyter notebook with markdown is very simple! All you need to do is on a new line, type the pound sign and then a space. After the space, simply add your title. It's that simple. By adding additional pound signs, you will create different title levels. The cell below is unformatted markdown text demonstrating this. \n# I am a level one title\n## I am a level two title\n### I am a level three title\n#### I am a level four title\n##### I am a level five title\n###### I am a level six title \n####### I would be a level seven title if such a thing existed\n\nIf the # isn't the first line, it does not get rendered as a title. \nTo see how those titles look when they're rendered in the Jupyter notebook, select the cell above, and from the top menu select `Raw NBConvert` $\\rightarrow$ `Markdown` then type `Ctrl + Enter` to render the cell. Feel free to create a new cell and play with those, or simply modify the one above directly. \n\n## Creating Itemized Lists\nCreating lists in markdown in a Jupyter notebook is also fairly straight forward! To do so you simply need to start a new line and begin counting. The markdown syntax is shown in the code below. Again, to see how it renders, select the cell below then from the top menu select `Raw NBConvert` $\\rightarrow$ `Markdown` then type `Ctrl + Enter`. \n1. This is the first item of a list\n1. This is the second\n50. Notice how the numbers we use don't matter once it's rendered\n    1. By pressing the `Tab` key we can add sub items\n    45. The numbers don't matter here either\n        - We can add many sub-lists\n            - But at some point it starts to get redundant\n                - But I guess that's okay sometimes\n                    - Although, nested lists like this are generally a sign your list should be reorganized\n                        - Notice how the color changes of the text before we render the markdown to help you\n                        know where in the list you're nested (if cell is set to markdown)\n        - We can also go back a few levels of nesting by lining the text up with the line above\n2346. By going back to the original line, we leave our nested lists\n23236235672456. The numbers really don't matter.\n* In fact, you can give up on numbers at any time.\n- It still counts for you\n1. Even if you start counting again\n    \n\n- We also don't need to have numbers if we don't want to!\n    * We have plenty of options\n-Notice how if we don't put a space between the dash and the first term it doesn't become a new item in the list!\n\n\n---\n### Exercises 1\n1. In the cell above, try fixing the last line so that the last item in the list becomes properly formatted once it's rendered. \n2. Create a new cell below, add a title, and an ordered list of your five favourite fruits.\n---\n\n## Links\nYou can add hyper links to webpages anywhere you'd like right in the text. The syntax is as follows\n```markdown\n[text you want to display](link to a file or url page)\n```\nChange the cell below to markdown, run it, and see where the link takes you!\n[this is the text that becomes the hyperlink](https://media.giphy.com/media/Vs44a88Dvbnkk/giphy.gif)\n## Images/gifs\nImages and gifs can be emebedded in a markdown cell easily using a syntax near identical to links by simply adding an explaination point before the link. For example\n```markdown\n\n```\nwould display an image/gif. It can either be a url link to an image, or one you have saved on the hub/locally. Change the cell below to markdown and run it to see it in action, or even embed your own images in this notebook. \n\n---\n### Exercises 2\n1. In a new cell below, embed an image of a cat. \n2. In the same cell, add a hyperlink below the image that links to the original image.\n3. Change the text displayed in the hyperlink to say \"Kitty Kitty\".\n---\n\n# Block Quotes\nBlock quotes are a way to indent text/images with a grey bar in order to distinguish them from the main text. It is quite simlly done by adding a `>` at the beginning of a line. Change the cell below to markdown to see some examples\n> This is an example of a block quote. You can type forever and the whole text will be indented. You could literally type forever and it would render as a block quote, but I don't recommend it because that would be a huge waste of everyone's time. \n\nYou can also use block quotes to easily format images with captions! \n\n> \n>\n> Now we can include a caption for images. This is nice because the image is now distinguishable from the main text. This makes it easy to include images without necessarily interrupting any narrative you've created. Notice how I have included a blank `>` under the image. That is simply so the spacing of this text looks nice underneath. Try removing it and see what happens\n## Tables\n\nWe can also create tables of data in Markdown. However, it's not the most convenient and for large tables I would recommend using online tools such as [here](https://jakebathman.github.io/Markdown-Table-Generator/) where you can copy-paste excel tables or csv files. This will then output syntax to properly render those tables. However, for smaller tables, it's quite easy to simply type out your own. See the cell below.\n| This is the first column name| Second Column| Third|\n|---|---|-------------|\n|Notice how nothing is lined up when we type it | But that it looks nice when rendered| how convenient!|\n|shorter lines are good too| numbers?| 343453|\n|symbols| `yes`| $\\int e^{-x^2} dx$ |\n|also notice that the number of dashes in the second line don't matter | it just needs to be at least three| the rest are really only for you to make pre-rendering look nice |\nThe basic table syntax is as follows:\n```markdown\n|initialize| your| column| names|\n|----------|-----|-------|------| <- this line sets up the headers, need at least three `---` each line\n|     data | data| data  | data | <- any kind of text data can be put in a table. Feel free to mix too!\n| numbers  | text| text  | data   <- you don't need to include the right-most pipe if you don't want to\n```\n\nessentially the syntax can be thought of as how you would try to write a table directly using symbols on your keyboard. Play with the table in the cell above, or create a new cell and try making your own! You could put one in this cell as well and put a table here. Simply double click anywhere on this cell to open edit mode.\n\n---\n### Exercises 3\n1. Using sample notebooks, teachers may like or dislike various sections of the sample provided. Luckily, it's easy to make these minor changes in notebooks. In the two cells below: \n    * remove the second cell because you won't need it in your lesson\n    * remove the last paragraph in the first cell \n    * change the date in the first paragraph\n2. In the first cell below, take the ordered list out of the block quote. \n\n---\n\n> ## Properties of Random Numbers\n> \n> May 22, 2018  \n> Suppose you have a sequence of $N$ random numbers $\\{R\\}$ with contents $\\{r_1, r_2, ... , r_N\\}$ where each element $r_i$ is a random number. What sort of properties should this sequence of numbers have? If this is truly a sequence of random numbers, it _must_ satisfy the following properties, which we will explain in greater detail: \n> \n> 1. Drawing any $r_i$ is equally probable and independent. \n> 2. The sequence of random numbers is uniformly distributed. \n> \n> \"Drawing a value\" in this scope means we're picking a number from our sequence of random numbers, but not removing it from the sequence (the sequence remains unchanged, we're simply \"observing\" the random number). \nLet's look at these two properties in a little more detail. \n\n\n> ### All Values Are Equally Probable and Independent\n> \n> What this means is that if you were to select (but not remove) a number from your sequence of random numbers $\\{r_1, r_2, ... , r_N\\}$ at random, the probability of drawing any of those numbers is\n\\begin{equation}\np(r_i) = \\frac{1}{N}\n\\end{equation}\nwhere $p(r_i)$ is the probability of selecting a number $r_i$. This probability is identical for all numbers within your set. More explicitly:\n\\begin{equation}\np(r_1) = p(r_2) = ... = p(r_N) = \\frac{1}{N}\n\\end{equation}\n> \n> The independence property means that the if you draw a number from the set, it does not affect the probability of drawing other numbers, or even itself at a later time. This is because the sequence remains unchanged after you draw (observe) a number. This property leads directly to the second important properties of random numbers, discussed below.\n\n[](https://github.com/callysto/curriculum-notebooks/blob/master/LICENSE.md)\n", "meta": {"hexsha": "249648cae07dea2602540a08a979713a89006e80", "size": 13487, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Demonstrations/tutorials/JupyterTestdrive-MarkDown.ipynb", "max_stars_repo_name": "callysto/callysto-sample-notebooks", "max_stars_repo_head_hexsha": "1e441a08687243030b5dec3b763e5ec883ee6c20", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-04-04T19:14:48.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-04T19:14:48.000Z", "max_issues_repo_path": "notebooks/Demonstrations/tutorials/JupyterTestdrive-MarkDown.ipynb", "max_issues_repo_name": "callysto/callysto-sample-notebooks", "max_issues_repo_head_hexsha": "1e441a08687243030b5dec3b763e5ec883ee6c20", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2018-04-05T13:34:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-25T01:02:30.000Z", "max_forks_repo_path": "notebooks/Demonstrations/tutorials/JupyterTestdrive-MarkDown.ipynb", "max_forks_repo_name": "callysto/callysto-sample-notebooks", "max_forks_repo_head_hexsha": "1e441a08687243030b5dec3b763e5ec883ee6c20", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2018-04-04T19:25:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T04:43:51.000Z", "avg_line_length": 13487.0, "max_line_length": 13487, "alphanum_fraction": 0.6949655224, "converted": true, "num_tokens": 2496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06754669301670264, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.02700595416155514}}
{"text": "We use Colab for free GPU training. For accelerated training make sure you are using the GPU harware accelerator: Runtime ->  Change runtime type \\\\\nTo check you are running a GPU runtime, run the following:\n\n\n```\ngpu_info = !nvidia-smi\ngpu_info = '\\n'.join(gpu_info)\nif gpu_info.find(\"failed\") >= 0:\n  print(\"Not connected to a gpu runtime\")\nelse:\n  print(\"Connected to a gpu runtime:\")\n  print(gpu_info)\n```\n\n    Connected to a gpu runtime:\n    Tue Mar 23 21:29:17 2021       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 460.56       Driver Version: 460.32.03    CUDA Version: 11.2     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  Tesla P100-PCIE...  Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   34C    P0    27W / 250W |      0MiB / 16280MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    |  No running processes found                                                 |\n    +-----------------------------------------------------------------------------+\n\n\n## Setup\n\n\n```\nimport numpy as np\nimport tensorflow as tf\nfrom tqdm.notebook import tqdm\nimport time\nfrom IPython import display\nimport pickle\nfrom tensorflow.keras import backend as K\nfrom sklearn.model_selection import train_test_split\n\n\nclass AttrDict(dict):\n    def __init__(self, *args, **kwargs):\n        super(AttrDict, self).__init__(*args, **kwargs)\n        self.__dict__ = self\n\n\nparams = AttrDict({\n\n    # dataset creation parameters\n    'dataset_path': '',\n    'dataset_size': 3000,\n    'num_parallel_processes': 15,\n    'env_name': 'char_sp',\n    'int_base': 10,\n    'balanced': False,\n    'positive': True,\n    'precision': 10,\n    'n_variables': 2,\n    'n_coefficients': 0,\n    'leaf_probs': '0.75,0,0.25,0',\n    'max_len': 510,\n    'max_int': 5,\n    'max_ops': 15,\n    'max_ops_G': 15,\n    'clean_prefix_expr': True,\n    'rewrite_functions': '',\n    'tasks': 'prim_fwd',\n\n    # used operations, followed by genreation weight\n    'operators': 'add:1,sub:1,mul:1,pow2:1,pow3:1', \n    #'operators': 'add:10,sub:3,mul:10,div:5,sqrt:4,pow2:4,pow3:2,pow4:1,pow5:1,ln:4,exp:4,sin:4,cos:4,tan:4,asin:1,acos:1,atan:1,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1',\n\n    # model hyperparameters\n    'num_layers': 4,\n    'd_model': 512,\n    'dff': 512,\n    'num_heads': 8,\n    'dropout_rate': 0.1,\n\n    # model training hyperparameters\n    'learning_rate': 1e-4,\n    'batch_size': 32,\n    'model_name': 'lime',\n    'epochs': 300,\n    'model_path': 'model.h5'\n    })\n```\n\n## Equation Generation Environment Class\n\nThis cell contains the utility functions for generaiting random expressions. This is modified version of the code used for [\tarXiv:1912.01412](https://arxiv.org/abs/1912.01412) for generating random integrals and is built with Sympy (see [SymbolicMathematics](https://github.com/facebookresearch/SymbolicMathematics) ). \n\n\n```\nimport sympy as sp\nfrom sympy.parsing.sympy_parser import parse_expr\nfrom sympy.core.cache import clear_cache\nfrom sympy.integrals.risch import NonElementaryIntegral\nfrom sympy.calculus.util import AccumBounds\nimport os\nimport io\nimport re\nimport sys\nimport math\nimport itertools\nfrom collections import OrderedDict\nimport numpy as np\nimport numexpr as ne\n\n\nSPECIAL_WORDS = ['<s>', '</s>', '<pad>', '(', ')']\nSPECIAL_WORDS = SPECIAL_WORDS + [f'<SPECIAL_{i}>' for i in range(len(SPECIAL_WORDS), 10)]\n\n\nINTEGRAL_FUNC = {sp.erf, sp.erfc, sp.erfi, sp.erfinv, sp.erfcinv, sp.expint, sp.Ei, sp.li, sp.Li, sp.Si, sp.Ci, sp.Shi, sp.Chi, sp.fresnelc, sp.fresnels}\nEXP_OPERATORS = {'exp', 'sinh', 'cosh'}\nEVAL_SYMBOLS = {'x', 'y', 'z', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9'}\nEVAL_VALUES = [0.01, 0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 2.1, 3.1]\nEVAL_VALUES = EVAL_VALUES + [-x for x in EVAL_VALUES]\n\nTEST_ZERO_VALUES = [0.1, 0.9, 1.1, 1.9]\nTEST_ZERO_VALUES = [-x for x in TEST_ZERO_VALUES] + TEST_ZERO_VALUES\nZERO_THRESHOLD = 1e-13\n\n\nclass ValueErrorExpression(Exception):\n    pass\n\n\nclass UnknownSymPyOperator(Exception):\n    pass\n\n\nclass InvalidPrefixExpression(Exception):\n\n    def __init__(self, data):\n        self.data = data\n\n    def __str__(self):\n        return repr(self.data)\n\n\ndef count_nested_exp(s):\n    \"\"\"\n    Return the maximum number of nested exponential functions in an infix expression.\n    \"\"\"\n    stack = []\n    count = 0\n    max_count = 0\n    for v in re.findall('[+-/*//()]|[a-zA-Z0-9]+', s):\n        if v == '(':\n            stack.append(v)\n        elif v == ')':\n            while True:\n                x = stack.pop()\n                if x in EXP_OPERATORS:\n                    count -= 1\n                if x == '(':\n                    break\n        else:\n            stack.append(v)\n            if v in EXP_OPERATORS:\n                count += 1\n                max_count = max(max_count, count)\n    assert len(stack) == 0\n    return max_count\n\n\ndef is_valid_expr(s):\n    \"\"\"\n    Check that we are able to evaluate an expression (and that it will not blow in SymPy evaluation).\n    \"\"\"\n    s = s.replace('Derivative(f(x),x)', '1')\n    s = s.replace('Derivative(1,x)', '1')\n    s = s.replace('(E)', '(exp(1))')\n    s = s.replace('(I)', '(1)')\n    s = s.replace('(pi)', '(1)')\n    s = re.sub(r'(?<![a-z])(f|g|h|Abs|sign|ln|sin|cos|tan|sec|csc|cot|asin|acos|atan|asec|acsc|acot|tanh|sech|csch|coth|asinh|acosh|atanh|asech|acoth|acsch)\\(', '(', s)\n    count = count_nested_exp(s)\n    if count >= 4:\n        return False\n    for v in EVAL_VALUES:\n        try:\n            local_dict = {s: (v + 1e-4 * i) for i, s in enumerate(EVAL_SYMBOLS)}\n            value = ne.evaluate(s, local_dict=local_dict).item()\n            if not (math.isnan(value) or math.isinf(value)):\n                return True\n        except (FloatingPointError, ZeroDivisionError, TypeError, MemoryError):\n            continue\n    return False\n\n\ndef eval_test_zero(eq):\n    \"\"\"\n    Evaluate an equation by replacing all its free symbols with random values.\n    \"\"\"\n    variables = eq.free_symbols\n    assert len(variables) <= 3\n    outputs = []\n    for values in itertools.product(*[TEST_ZERO_VALUES for _ in range(len(variables))]):\n        _eq = eq.subs(zip(variables, values)).doit()\n        outputs.append(float(sp.Abs(_eq.evalf())))\n    return outputs\n\n\ndef has_inf_nan(*args):\n    \"\"\"\n    Detect whether some expressions contain a NaN / Infinity symbol.\n    \"\"\"\n    for f in args:\n        if f.has(sp.nan) or f.has(sp.oo) or f.has(-sp.oo) or f.has(sp.zoo):\n            return True\n    return False\n\n\nclass CharSPEnvironment(object):\n\n    # https://docs.sympy.org/latest/modules/functions/elementary.html#real-root\n\n    SYMPY_OPERATORS = {\n        # Elementary functions\n        sp.Add: 'add',\n        sp.Mul: 'mul',\n        sp.Pow: 'pow',\n        sp.exp: 'exp',\n        sp.log: 'ln',\n        sp.Abs: 'abs',\n        sp.sign: 'sign',\n        # Trigonometric Functions\n        sp.sin: 'sin',\n        sp.cos: 'cos',\n        sp.tan: 'tan',\n        sp.cot: 'cot',\n        sp.sec: 'sec',\n        sp.csc: 'csc',\n        # Trigonometric Inverses\n        sp.asin: 'asin',\n        sp.acos: 'acos',\n        sp.atan: 'atan',\n        sp.acot: 'acot',\n        sp.asec: 'asec',\n        sp.acsc: 'acsc',\n        # Hyperbolic Functions\n        sp.sinh: 'sinh',\n        sp.cosh: 'cosh',\n        sp.tanh: 'tanh',\n        sp.coth: 'coth',\n        sp.sech: 'sech',\n        sp.csch: 'csch',\n        # Hyperbolic Inverses\n        sp.asinh: 'asinh',\n        sp.acosh: 'acosh',\n        sp.atanh: 'atanh',\n        sp.acoth: 'acoth',\n        sp.asech: 'asech',\n        sp.acsch: 'acsch',\n        # Derivative\n        sp.Derivative: 'derivative',\n    }\n\n    OPERATORS = {\n        # Elementary functions\n        'add': 2,\n        'sub': 2,\n        'mul': 2,\n        'div': 2,\n        'pow': 2,\n        'rac': 2,\n        'inv': 1,\n        'pow2': 1,\n        'pow3': 1,\n        'pow4': 1,\n        'pow5': 1,\n        'sqrt': 1,\n        'exp': 1,\n        'ln': 1,\n        'abs': 1,\n        'sign': 1,\n        # Trigonometric Functions\n        'sin': 1,\n        'cos': 1,\n        'tan': 1,\n        'cot': 1,\n        'sec': 1,\n        'csc': 1,\n        # Trigonometric Inverses\n        'asin': 1,\n        'acos': 1,\n        'atan': 1,\n        'acot': 1,\n        'asec': 1,\n        'acsc': 1,\n        # Hyperbolic Functions\n        'sinh': 1,\n        'cosh': 1,\n        'tanh': 1,\n        'coth': 1,\n        'sech': 1,\n        'csch': 1,\n        # Hyperbolic Inverses\n        'asinh': 1,\n        'acosh': 1,\n        'atanh': 1,\n        'acoth': 1,\n        'asech': 1,\n        'acsch': 1,\n        # Derivative\n        'derivative': 2,\n        # custom functions\n        'f': 1,\n        'g': 2,\n        'h': 3,\n    }\n\n    def __init__(self, params):\n\n        self.max_int = params.max_int\n        self.max_ops = params.max_ops\n        self.max_ops_G = params.max_ops_G\n        self.int_base = params.int_base\n        self.balanced = params.balanced\n        self.positive = params.positive\n        self.precision = params.precision\n        self.n_variables = params.n_variables\n        self.n_coefficients = params.n_coefficients\n        self.max_len = params.max_len\n        self.clean_prefix_expr = params.clean_prefix_expr\n        assert self.max_int >= 1\n        assert abs(self.int_base) >= 2\n        assert self.precision >= 2\n\n        # parse operators with their weights\n        self.operators = sorted(list(self.OPERATORS.keys()))\n        ops = params.operators.split(',')\n        ops = sorted([x.split(':') for x in ops])\n        assert len(ops) >= 1 and all(o in self.OPERATORS for o, _ in ops)\n        self.all_ops = [o for o, _ in ops]\n        self.una_ops = [o for o, _ in ops if self.OPERATORS[o] == 1]\n        self.bin_ops = [o for o, _ in ops if self.OPERATORS[o] == 2]\n\n        self.all_ops_probs = np.array([float(w) for _, w in ops]).astype(np.float64)\n        self.una_ops_probs = np.array([float(w) for o, w in ops if self.OPERATORS[o] == 1]).astype(np.float64)\n        self.bin_ops_probs = np.array([float(w) for o, w in ops if self.OPERATORS[o] == 2]).astype(np.float64)\n        self.all_ops_probs = self.all_ops_probs / self.all_ops_probs.sum()\n        self.una_ops_probs = self.una_ops_probs / self.una_ops_probs.sum()\n        self.bin_ops_probs = self.bin_ops_probs / self.bin_ops_probs.sum()\n\n        assert len(self.all_ops) == len(set(self.all_ops)) >= 1\n        assert set(self.all_ops).issubset(set(self.operators))\n        assert len(self.all_ops) == len(self.una_ops) + len(self.bin_ops)\n\n        # symbols / elements\n        self.constants = ['pi', 'E']\n        self.variables = OrderedDict({\n            'x': sp.Symbol('x', real=True, nonzero=True),  # , positive=True\n            'y': sp.Symbol('y', real=True, nonzero=True),  # , positive=True\n            'z': sp.Symbol('z', real=True, nonzero=True),  # , positive=True\n            't': sp.Symbol('t', real=True, nonzero=True),  # , positive=True\n        })\n        self.coefficients = OrderedDict({\n            f'a{i}': sp.Symbol(f'a{i}', real=True)\n            for i in range(10)\n        })\n        self.functions = OrderedDict({\n            'f': sp.Function('f', real=True, nonzero=True),\n            'g': sp.Function('g', real=True, nonzero=True),\n            'h': sp.Function('h', real=True, nonzero=True),\n        })\n        self.symbols = ['I', 'INT+', 'INT-', 'INT', 'FLOAT', '-', '.', '10^', 'Y', \"Y'\", \"Y''\"]\n        if self.balanced:\n            assert self.int_base > 2\n            max_digit = (self.int_base + 1) // 2\n            self.elements = [str(i) for i in range(max_digit - abs(self.int_base), max_digit)]\n        else:\n            self.elements = [str(i) for i in range(abs(self.int_base))]\n        assert 1 <= self.n_variables <= len(self.variables)\n        assert 0 <= self.n_coefficients <= len(self.coefficients)\n        assert all(k in self.OPERATORS for k in self.functions.keys())\n        assert all(v in self.OPERATORS for v in self.SYMPY_OPERATORS.values())\n\n        # SymPy elements\n        self.local_dict = {}\n        for k, v in list(self.variables.items()) + list(self.coefficients.items()) + list(self.functions.items()):\n            assert k not in self.local_dict\n            self.local_dict[k] = v\n\n        # vocabulary\n        self.words = SPECIAL_WORDS + self.constants + list(self.variables.keys()) + list(self.coefficients.keys()) + self.operators + self.symbols + self.elements\n        self.id2word = {i + 1: s for i, s in enumerate(self.words)}\n        self.word2id = {s: i for i, s in self.id2word.items()}\n        assert len(self.words) == len(set(self.words))\n\n        # number of words / indices\n        self.n_words = params.n_words = len(self.words)\n        self.eos_index = params.eos_index = 0\n        self.pad_index = params.pad_index = 1\n\n        # leaf probabilities\n        s = [float(x) for x in params.leaf_probs.split(',')]\n        assert len(s) == 4 and all(x >= 0 for x in s)\n        self.leaf_probs = np.array(s).astype(np.float64)\n        self.leaf_probs = self.leaf_probs / self.leaf_probs.sum()\n        assert self.leaf_probs[0] > 0\n        assert (self.leaf_probs[1] == 0) == (self.n_coefficients == 0)\n\n        # possible leaves\n        self.n_leaves = self.n_variables + self.n_coefficients\n        if self.leaf_probs[2] > 0:\n            self.n_leaves += self.max_int * (1 if self.positive else 2)\n        if self.leaf_probs[3] > 0:\n            self.n_leaves += len(self.constants)\n\n        # generation parameters\n        self.nl = 1  # self.n_leaves\n        self.p1 = 1  # len(self.una_ops)\n        self.p2 = 1  # len(self.bin_ops)\n\n        # initialize distribution for binary and unary-binary trees\n        self.bin_dist = self.generate_bin_dist(params.max_ops)\n        self.ubi_dist = self.generate_ubi_dist(params.max_ops)\n\n        # rewrite expressions\n        self.rewrite_functions = [x for x in params.rewrite_functions.split(',') if x != '']\n        assert len(self.rewrite_functions) == len(set(self.rewrite_functions))\n        assert all(x in ['expand', 'factor', 'expand_log', 'logcombine', 'powsimp', 'simplify'] for x in self.rewrite_functions)\n\n    def generate_bin_dist(self, max_ops):\n        \"\"\"\n        `max_ops`: maximum number of operators\n        Enumerate the number of possible binary trees that can be generated from empty nodes.\n        D[e][n] represents the number of different binary trees with n nodes that\n        can be generated from e empty nodes, using the following recursion:\n            D(0, n) = 0\n            D(1, n) = C_n (n-th Catalan number)\n            D(e, n) = D(e - 1, n + 1) - D(e - 2, n + 1)\n        \"\"\"\n        # initialize Catalan numbers\n        catalans = [1]\n        for i in range(1, 2 * max_ops + 1):\n            catalans.append((4 * i - 2) * catalans[i - 1] // (i + 1))\n\n        # enumerate possible trees\n        D = []\n        for e in range(max_ops + 1):  # number of empty nodes\n            s = []\n            for n in range(2 * max_ops - e + 1):  # number of operators\n                if e == 0:\n                    s.append(0)\n                elif e == 1:\n                    s.append(catalans[n])\n                else:\n                    s.append(D[e - 1][n + 1] - D[e - 2][n + 1])\n            D.append(s)\n        return D\n\n    def generate_ubi_dist(self, max_ops):\n        \"\"\"\n        `max_ops`: maximum number of operators\n        Enumerate the number of possible unary-binary trees that can be generated from empty nodes.\n        D[e][n] represents the number of different binary trees with n nodes that\n        can be generated from e empty nodes, using the following recursion:\n            D(0, n) = 0\n            D(e, 0) = L ** e\n            D(e, n) = L * D(e - 1, n) + p_1 * D(e, n - 1) + p_2 * D(e + 1, n - 1)\n        \"\"\"\n        # enumerate possible trees\n        # first generate the tranposed version of D, then transpose it\n        D = []\n        D.append([0] + ([self.nl ** i for i in range(1, 2 * max_ops + 1)]))\n        for n in range(1, 2 * max_ops + 1):  # number of operators\n            s = [0]\n            for e in range(1, 2 * max_ops - n + 1):  # number of empty nodes\n                s.append(self.nl * s[e - 1] + self.p1 * D[n - 1][e] + self.p2 * D[n - 1][e + 1])\n            D.append(s)\n        assert all(len(D[i]) >= len(D[i + 1]) for i in range(len(D) - 1))\n        D = [[D[j][i] for j in range(len(D)) if i < len(D[j])] for i in range(max(len(x) for x in D))]\n        return D\n\n    def write_int(self, val):\n        \"\"\"\n        Convert a decimal integer to a representation in the given base.\n        The base can be negative.\n        In balanced bases (positive), digits range from -(base-1)//2 to (base-1)//2\n        \"\"\"\n        base = self.int_base\n        balanced = self.balanced\n        res = []\n        max_digit = abs(base)\n        if balanced:\n            max_digit = (base - 1) // 2\n        else:\n            if base > 0:\n                neg = val < 0\n                val = -val if neg else val\n        while True:\n            rem = val % base\n            val = val // base\n            if rem < 0 or rem > max_digit:\n                rem -= base\n                val += 1\n            res.append(str(rem))\n            if val == 0:\n                break\n        if base < 0 or balanced:\n            res.append('INT')\n        else:\n            res.append('INT-' if neg else 'INT+')\n        return res[::-1]\n\n    def parse_int(self, lst):\n        \"\"\"\n        Parse a list that starts with an integer.\n        Return the integer value, and the position it ends in the list.\n        \"\"\"\n        base = self.int_base\n        balanced = self.balanced\n        val = 0\n        if not (balanced and lst[0] == 'INT' or base >= 2 and lst[0] in ['INT+', 'INT-'] or base <= -2 and lst[0] == 'INT'):\n            raise InvalidPrefixExpression(f\"Invalid integer in prefix expression\")\n        i = 0\n        for x in lst[1:]:\n            if not (x.isdigit() or x[0] == '-' and x[1:].isdigit()):\n                break\n            val = val * base + int(x)\n            i += 1\n        if base > 0 and lst[0] == 'INT-':\n            val = -val\n        return val, i + 1\n\n    def sample_next_pos_ubi(self, nb_empty, nb_ops, rng):\n        \"\"\"\n        Sample the position of the next node (unary-binary case).\n        Sample a position in {0, ..., `nb_empty` - 1}, along with an arity.\n        \"\"\"\n        assert nb_empty > 0\n        assert nb_ops > 0\n        probs = []\n        for i in range(nb_empty):\n            probs.append((self.nl ** i) * self.p1 * self.ubi_dist[nb_empty - i][nb_ops - 1])\n        for i in range(nb_empty):\n            probs.append((self.nl ** i) * self.p2 * self.ubi_dist[nb_empty - i + 1][nb_ops - 1])\n        probs = [p / self.ubi_dist[nb_empty][nb_ops] for p in probs]\n        probs = np.array(probs, dtype=np.float64)\n        e = rng.choice(2 * nb_empty, p=probs)\n        arity = 1 if e < nb_empty else 2\n        e = e % nb_empty\n        return e, arity\n\n    def get_leaf(self, max_int, rng):\n        \"\"\"\n        Generate a leaf.\n        \"\"\"\n        self.leaf_probs\n        leaf_type = rng.choice(4, p=self.leaf_probs)\n        if leaf_type == 0:\n            return [list(self.variables.keys())[rng.randint(self.n_variables)]]\n        elif leaf_type == 1:\n            return [list(self.coefficients.keys())[rng.randint(self.n_coefficients)]]\n        elif leaf_type == 2:\n            c = rng.randint(1, max_int + 1)\n            c = c if (self.positive or rng.randint(2) == 0) else -c\n            return self.write_int(c)\n        else:\n            return [self.constants[rng.randint(len(self.constants))]]\n\n    def _generate_expr(self, nb_total_ops, max_int, rng, require_x=False, require_y=False, require_z=False):\n        \"\"\"\n        Create a tree with exactly `nb_total_ops` operators.\n        \"\"\"\n        stack = [None]\n        nb_empty = 1  # number of empty nodes\n        l_leaves = 0  # left leaves - None states reserved for leaves\n        t_leaves = 1  # total number of leaves (just used for sanity check)\n\n        # create tree\n        for nb_ops in range(nb_total_ops, 0, -1):\n\n            # next operator, arity and position\n            skipped, arity = self.sample_next_pos_ubi(nb_empty, nb_ops, rng)\n            if arity == 1:\n                op = rng.choice(self.una_ops, p=self.una_ops_probs)\n            else:\n                op = rng.choice(self.bin_ops, p=self.bin_ops_probs)\n\n            nb_empty += self.OPERATORS[op] - 1 - skipped  # created empty nodes - skipped future leaves\n            t_leaves += self.OPERATORS[op] - 1            # update number of total leaves\n            l_leaves += skipped                           # update number of left leaves\n\n            # update tree\n            pos = [i for i, v in enumerate(stack) if v is None][l_leaves]\n            stack = stack[:pos] + [op] + [None for _ in range(self.OPERATORS[op])] + stack[pos + 1:]\n\n        # sanity check\n        assert len([1 for v in stack if v in self.all_ops]) == nb_total_ops\n        assert len([1 for v in stack if v is None]) == t_leaves\n\n        # create leaves\n        # optionally add variables x, y, z if possible\n        assert not require_z or require_y\n        assert not require_y or require_x\n        leaves = [self.get_leaf(max_int, rng) for _ in range(t_leaves)]\n        if require_z and t_leaves >= 2:\n            leaves[1] = ['z']\n        if require_y:\n            leaves[0] = ['y']\n        if require_x and not any(len(leaf) == 1 and leaf[0] == 'x' for leaf in leaves):\n            leaves[-1] = ['x']\n        rng.shuffle(leaves)\n\n        # insert leaves into tree\n        for pos in range(len(stack) - 1, -1, -1):\n            if stack[pos] is None:\n                stack = stack[:pos] + leaves.pop() + stack[pos + 1:]\n\n        return stack\n\n    def write_infix(self, token, args):\n        \"\"\"\n        Infix representation.\n        Convert prefix expressions to a format that SymPy can parse.\n        \"\"\"\n        if token == 'add':\n            return f'({args[0]})+({args[1]})'\n        elif token == 'sub':\n            return f'({args[0]})-({args[1]})'\n        elif token == 'mul':\n            return f'({args[0]})*({args[1]})'\n        elif token == 'div':\n            return f'({args[0]})/({args[1]})'\n        elif token == 'pow':\n            return f'({args[0]})**({args[1]})'\n        elif token == 'rac':\n            return f'({args[0]})**(1/({args[1]}))'\n        elif token == 'abs':\n            return f'Abs({args[0]})'\n        elif token == 'inv':\n            return f'1/({args[0]})'\n        elif token == 'pow2':\n            return f'({args[0]})**2'\n        elif token == 'pow3':\n            return f'({args[0]})**3'\n        elif token == 'pow4':\n            return f'({args[0]})**4'\n        elif token == 'pow5':\n            return f'({args[0]})**5'\n        elif token in ['sign', 'sqrt', 'exp', 'ln', 'sin', 'cos', 'tan', 'cot', 'sec', 'csc', 'asin', 'acos', 'atan', 'acot', 'asec', 'acsc', 'sinh', 'cosh', 'tanh', 'coth', 'sech', 'csch', 'asinh', 'acosh', 'atanh', 'acoth', 'asech', 'acsch']:\n            return f'{token}({args[0]})'\n        elif token == 'derivative':\n            return f'Derivative({args[0]},{args[1]})'\n        elif token == 'f':\n            return f'f({args[0]})'\n        elif token == 'g':\n            return f'g({args[0]},{args[1]})'\n        elif token == 'h':\n            return f'h({args[0]},{args[1]},{args[2]})'\n        elif token.startswith('INT'):\n            return f'{token[-1]}{args[0]}'\n        else:\n            return token\n        raise InvalidPrefixExpression(f\"Unknown token in prefix expression: {token}, with arguments {args}\")\n\n    def _prefix_to_infix(self, expr):\n        \"\"\"\n        Parse an expression in prefix mode, and output it in either:\n          - infix mode (returns human readable string)\n          - develop mode (returns a dictionary with the simplified expression)\n        \"\"\"\n        if len(expr) == 0:\n            raise InvalidPrefixExpression(\"Empty prefix list.\")\n        t = expr[0]\n        if t in self.operators:\n            args = []\n            l1 = expr[1:]\n            for _ in range(self.OPERATORS[t]):\n                i1, l1 = self._prefix_to_infix(l1)\n                args.append(i1)\n            return self.write_infix(t, args), l1\n        elif t in self.variables or t in self.coefficients or t in self.constants or t == 'I':\n            return t, expr[1:]\n        else:\n            val, i = self.parse_int(expr)\n            return str(val), expr[i:]\n\n    def prefix_to_infix(self, expr):\n        \"\"\"\n        Prefix to infix conversion.\n        \"\"\"\n        p, r = self._prefix_to_infix(expr)\n        if len(r) > 0:\n            raise InvalidPrefixExpression(f\"Incorrect prefix expression \\\"{expr}\\\". \\\"{r}\\\" was not parsed.\")\n        return f'({p})'\n\n    def rewrite_sympy_expr(self, expr):\n        \"\"\"\n        Rewrite a SymPy expression.\n        \"\"\"\n        expr_rw = expr\n        for f in self.rewrite_functions:\n            if f == 'expand':\n                expr_rw = sp.expand(expr_rw)\n            elif f == 'factor':\n                expr_rw = sp.factor(expr_rw)\n            elif f == 'expand_log':\n                expr_rw = sp.expand_log(expr_rw, force=True)\n            elif f == 'logcombine':\n                expr_rw = sp.logcombine(expr_rw, force=True)\n            elif f == 'powsimp':\n                expr_rw = sp.powsimp(expr_rw, force=True)\n            elif f == 'simplify':\n                expr_rw = simplify(expr_rw, seconds=1)\n        return expr_rw\n\n    def infix_to_sympy(self, infix, no_rewrite=False, \n                       evaluate=False, force=False):\n        \"\"\"\n        Convert an infix expression to SymPy.\n        \"\"\"\n        if force:\n          return parse_expr(infix, evaluate=evaluate, local_dict=self.local_dict)\n\n        if not is_valid_expr(infix):\n            raise ValueErrorExpression\n        #expr = parse_expr(infix, evaluate=True, local_dict=self.local_dict)\n        expr = parse_expr(infix, evaluate=evaluate, local_dict=self.local_dict)\n\n        if expr.has(sp.I) or expr.has(AccumBounds):\n            raise ValueErrorExpression\n        if not no_rewrite:\n            expr = self.rewrite_sympy_expr(expr)\n        return expr\n\n    def _sympy_to_prefix(self, op, expr):\n        \"\"\"\n        Parse a SymPy expression given an initial root operator.\n        \"\"\"\n        n_args = len(expr.args)\n\n        # derivative operator\n        if op == 'derivative':\n            assert n_args >= 2\n            assert all(len(arg) == 2 and str(arg[0]) in self.variables and int(arg[1]) >= 1 for arg in expr.args[1:]), expr.args\n            parse_list = self.sympy_to_prefix(expr.args[0])\n            for var, degree in expr.args[1:]:\n                parse_list = ['derivative' for _ in range(int(degree))] + parse_list + [str(var) for _ in range(int(degree))]\n            return parse_list\n\n        assert (op == 'add' or op == 'mul') and (n_args >= 2) or (op != 'add' and op != 'mul') and (1 <= n_args <= 2)\n\n        # square root\n        if op == 'pow' and isinstance(expr.args[1], sp.Rational) and expr.args[1].p == 1 and expr.args[1].q == 2:\n            return ['sqrt'] + self.sympy_to_prefix(expr.args[0])\n\n        # parse children\n        parse_list = []\n        for i in range(n_args):\n            if i == 0 or i < n_args - 1:\n                parse_list.append(op)\n            parse_list += self.sympy_to_prefix(expr.args[i])\n\n        return parse_list\n\n    def sympy_to_prefix(self, expr):\n        \"\"\"\n        Convert a SymPy expression to a prefix one.\n        \"\"\"\n        if isinstance(expr, sp.Symbol):\n            return [str(expr)]\n        elif isinstance(expr, sp.Integer):\n            return self.write_int(int(str(expr)))\n        elif isinstance(expr, sp.Rational):\n            return ['div'] + self.write_int(int(expr.p)) + self.write_int(int(expr.q))\n        elif expr == sp.E:\n            return ['E']\n        elif expr == sp.pi:\n            return ['pi']\n        elif expr == sp.I:\n            return ['I']\n        # SymPy operator\n        for op_type, op_name in self.SYMPY_OPERATORS.items():\n            if isinstance(expr, op_type):\n                return self._sympy_to_prefix(op_name, expr)\n        # environment function\n        for func_name, func in self.functions.items():\n            if isinstance(expr, func):\n                return self._sympy_to_prefix(func_name, expr)\n        # unknown operator\n        raise UnknownSymPyOperator(f\"Unknown SymPy operator: {expr}\")\n\n    def extract_non_constant_subtree(self, expr):\n        return extract_non_constant_subtree(expr, self.variables.values())\n\n    def gen_expr(self, rng):\n        \"\"\"\n        Generate pairs of (function, derivative) or (function, primitive).\n        Start by generating a random function f, and use SymPy to compute f'.\n        \"\"\"\n        x = self.variables['x']\n        if rng.randint(40) == 0:\n            nb_ops = rng.randint(0, 4)\n        else:\n            nb_ops = rng.randint(4, self.max_ops + 1)\n\n        try:\n          # generate an expression and rewrite it,\n          # avoid issues in 0 and convert to SymPy\n          F_expr = self._generate_expr(nb_ops, self.max_int, rng)\n          infix = self.prefix_to_infix(F_expr)\n          F = self.infix_to_sympy(infix, evaluate=False)\n\n          # skip constant expressions\n          if x not in F.free_symbols:\n              return None\n\n          # remove additive constant, re-index coefficients\n          f = sp.simplify(F)\n\n          # skip invalid expressions\n          if has_inf_nan(f, F):\n              return None\n\n          # convert back to prefix\n          f_prefix = self.sympy_to_prefix(f)\n          F1_prefix = self.sympy_to_prefix(F)\n          F2_prefix = self.sympy_to_prefix(sp.expand(f))\n          F3_prefix = self.sympy_to_prefix(sp.expand(F))\n\n          return f_prefix, (F1_prefix, F2_prefix, F3_prefix)\n\n        except RuntimeWarning:\n          return None\n        except TimeoutError:\n            return None\n        except (ValueErrorExpression, UnknownSymPyOperator, OverflowError, TypeError):\n            return None\n        except Exception as e:\n            return None\n```\n\n\n```\nDATASET_ENV = CharSPEnvironment(params)\n\n\ndef sympy_to_sequences(expr, env):\n  prefix = env.sympy_to_prefix(expr)\n  return [env.word2id[w] for w in prefix]\n\n\ndef sequences_to_sympy(x, env):\n  x = [env.id2word[w] for w in x]\n  x = env.prefix_to_infix(x)\n  return env.infix_to_sympy(x)\n\n\ndef prefix_to_sympy(x, env):\n  x = env.prefix_to_infix(x)\n  return env.infix_to_sympy(x)\n```\n\n## Visualising some random expressions\n\nThe the function 'DATASET_ENV.gen_expr' generates random equations in prefix notation (see https://en.wikipedia.org/wiki/Polish_notation for more details).\n\n\n```\nirreducible_eq, reducible_eqs = DATASET_ENV.gen_expr(np.random)\n\nprefix_to_sympy(irreducible_eq, DATASET_ENV)\n```\n\n\n\n\n$\\displaystyle x y + \\left(x + 4\\right)^{2}$\n\n\n\n\n```\nprefix_to_sympy(reducible_eqs[0], DATASET_ENV)\n```\n\n\n\n\n$\\displaystyle x y + \\left(x + 4\\right)^{2}$\n\n\n\n\n```\nprefix_to_sympy(reducible_eqs[1], DATASET_ENV)\n```\n\n\n\n\n$\\displaystyle x^{2} + x y + 8 x + 16$\n\n\n\n\n```\nprefix_to_sympy(reducible_eqs[2], DATASET_ENV)\n```\n\n\n\n\n$\\displaystyle x^{2} + x y + 8 x + 16$\n\n\n\n# Dataset creation\n\nHere we use python's multiprocessing module to parallelise dataset createtion. \\\\\nThe following creates two files of the tokenize equations 'x.pkl' and 'y.pkl'. Where 'y.pkl' contains the simplified versions of the equations found in 'x.pkl'.\n\n\n\n```\nfrom multiprocessing import Process, Manager\nfrom IPython import display\nimport pickle\n\n\n_samples_per_process = int(params.dataset_size//params.num_parallel_processes)\n\n\ndef sampling_func(inp, tar):\n  np.random.seed(None)\n  i = 0\n  while i < _samples_per_process:\n    x = None\n    while x is None:\n      x = DATASET_ENV.gen_expr(np.random)\n    y, x = x\n    y = [DATASET_ENV.word2id[w] for w in y]\n    i += 1\n    for u in x:\n      if len(u) > 1:\n        inp.append([DATASET_ENV.word2id[w] for w in u])\n        tar.append(y)\n\n\nprint('Creating dataset ...')\nstart = time.time()\n\nmanager = Manager()\ninp = manager.list() \ntar = manager.list() \n\nprocesses = []\nfor _ in range(params.num_parallel_processes):\n  p = Process(target=sampling_func, args=(inp, tar)) \n  p.start()\n  processes.append(p)\nfor p in processes:\n  p.join()\n\ninp = list(inp)\ntar = list(tar)\n\ndisplay.clear_output()\n\nprint('Saving')\nwith open(params.dataset_path + 'x.pkl', 'wb') as f:\n  pickle.dump(inp, f)\nwith open(params.dataset_path + 'y.pkl', 'wb') as f:\n  pickle.dump(tar, f)\n\nclear_cache()\nmanager.shutdown()\nprint('Complete')\n```\n\n    Creating dataset ...\n\n\n## Model Setup\nThis cell defines the keras architecture of the standard transformer. \nHere we use a variant of the original transformer architecture known as ReZero (see [arXiv:2003.04887](https://arxiv.org/abs/2003.04887) ) for faster training convergence. \n\n\n```\ndef create_padding_mask(seq):\n  seq = tf.cast(tf.math.equal(seq, 0), tf.float32)\n\n  # add extra dimensions to add the padding\n  # to the attention logits.\n  return seq[:, tf.newaxis, tf.newaxis, :]  # (batch_size, 1, 1, seq_len)\n\n\ndef create_look_ahead_mask(size):\n  mask = 1 - tf.linalg.band_part(tf.ones((size, size)), -1, 0)\n  return mask  # (seq_len, seq_len)\n\n\ndef create_masks(inp, tar):\n  # Encoder padding mask\n  enc_padding_mask = create_padding_mask(inp)\n\n  # Used in the 2nd attention block in the decoder.\n  # This padding mask is used to mask the encoder outputs.\n  dec_padding_mask = create_padding_mask(inp)\n\n  # Used in the 1st attention block in the decoder.\n  # It is used to pad and mask future tokens in the input received by \n  # the decoder.\n  look_ahead_mask = create_look_ahead_mask(tf.shape(tar)[1])\n  dec_target_padding_mask = create_padding_mask(tar)\n  combined_mask = tf.maximum(dec_target_padding_mask, look_ahead_mask)\n\n  return enc_padding_mask, combined_mask, dec_padding_mask\n\n\ndef get_angles(pos, i, d_model):\n  angle_rates = 1 / np.power(10000, (2 * (i//2)) / np.float32(d_model))\n  return pos * angle_rates\n\n\ndef positional_encoding(position, d_model):\n  angle_rads = get_angles(np.arange(position)[:, np.newaxis],\n                          np.arange(d_model)[np.newaxis, :],\n                          d_model)\n\n  # apply sin to even indices in the array; 2i\n  angle_rads[:, 0::2] = np.sin(angle_rads[:, 0::2])\n\n  # apply cos to odd indices in the array; 2i+1\n  angle_rads[:, 1::2] = np.cos(angle_rads[:, 1::2])\n\n  pos_encoding = angle_rads[np.newaxis, ...]\n\n  return tf.cast(pos_encoding, dtype=tf.float32)\n\n\ndef scaled_dot_product_attention(q, k, v, mask):\n  \"\"\"Calculate the attention weights.\n  q, k, v must have matching leading dimensions.\n  k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.\n  The mask has different shapes depending on its type(padding or look ahead) \n  but it must be broadcastable for addition.\n\n  Args:\n    q: query shape == (..., seq_len_q, depth)\n    k: key shape == (..., seq_len_k, depth)\n    v: value shape == (..., seq_len_v, depth_v)\n    mask: Float tensor with shape broadcastable \n          to (..., seq_len_q, seq_len_k). Defaults to None.\n\n  Returns:\n    output, attention_weights\n  \"\"\"\n\n  matmul_qk = tf.matmul(q, k, transpose_b=True)  # (..., seq_len_q, seq_len_k)\n\n  # scale matmul_qk\n  dk = tf.cast(tf.shape(k)[-1], tf.float32)\n  scaled_attention_logits = matmul_qk / tf.math.sqrt(dk)\n\n  # add the mask to the scaled tensor.\n  if mask is not None:\n    scaled_attention_logits += (mask * -1e9)  \n\n  # softmax is normalized on the last axis (seq_len_k) so that the scores\n  # add up to 1.\n  attention_weights = tf.nn.softmax(scaled_attention_logits, axis=-1)  # (..., seq_len_q, seq_len_k)\n\n  output = tf.matmul(attention_weights, v)  # (..., seq_len_q, depth_v)\n\n  return output, attention_weights\n\n\nclass MultiHeadAttention(tf.keras.layers.Layer):\n  def __init__(self, d_model, num_heads):\n    super(MultiHeadAttention, self).__init__()\n    self.num_heads = num_heads\n    self.d_model = d_model\n\n    assert d_model % self.num_heads == 0\n\n    self.depth = d_model // self.num_heads\n\n    self.wq = tf.keras.layers.Dense(d_model)\n    self.wk = tf.keras.layers.Dense(d_model)\n    self.wv = tf.keras.layers.Dense(d_model)\n\n    self.dense = tf.keras.layers.Dense(d_model)\n\n  def split_heads(self, x, batch_size):\n    \"\"\"Split the last dimension into (num_heads, depth).\n    Transpose the result such that the shape is (batch_size, num_heads, seq_len, depth)\n    \"\"\"\n    x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth))\n    return tf.transpose(x, perm=[0, 2, 1, 3])\n\n  def call(self, v, k, q, mask):\n    batch_size = tf.shape(q)[0]\n\n    q = self.wq(q)  # (batch_size, seq_len, d_model)\n    k = self.wk(k)  # (batch_size, seq_len, d_model)\n    v = self.wv(v)  # (batch_size, seq_len, d_model)\n\n    q = self.split_heads(q, batch_size)  # (batch_size, num_heads, seq_len_q, depth)\n    k = self.split_heads(k, batch_size)  # (batch_size, num_heads, seq_len_k, depth)\n    v = self.split_heads(v, batch_size)  # (batch_size, num_heads, seq_len_v, depth)\n\n    # scaled_attention.shape == (batch_size, num_heads, seq_len_q, depth)\n    # attention_weights.shape == (batch_size, num_heads, seq_len_q, seq_len_k)\n    scaled_attention, attention_weights = scaled_dot_product_attention(\n        q, k, v, mask)\n\n    scaled_attention = tf.transpose(scaled_attention, perm=[0, 2, 1, 3])  # (batch_size, seq_len_q, num_heads, depth)\n\n    concat_attention = tf.reshape(scaled_attention, \n                                  (batch_size, -1, self.d_model))  # (batch_size, seq_len_q, d_model)\n\n    output = self.dense(concat_attention)  # (batch_size, seq_len_q, d_model)\n\n    return output, attention_weights\n\n\ndef point_wise_feed_forward_network(d_model, dff):\n  return tf.keras.Sequential([\n      tf.keras.layers.Dense(dff, activation='relu'),  # (batch_size, seq_len, dff)\n      tf.keras.layers.Dense(d_model)  # (batch_size, seq_len, d_model)\n  ])\n\n\nclass ReZero(tf.keras.layers.Layer):\n    def __init__(self, name):\n        super(ReZero, self).__init__(name=name)\n        a_init = tf.zeros_initializer()\n        self.alpha = tf.Variable(name=self.name + '-alpha',\n            initial_value=a_init(shape=(1,), dtype=\"float32\"), trainable=True\n        )\n\n    def call(self, inputs):\n        return self.alpha * inputs\n\n\nclass EncoderLayer(tf.keras.layers.Layer):\n  def __init__(self, d_model, num_heads, dff, rate=0.1):\n    super(EncoderLayer, self).__init__()\n\n    self.mha = MultiHeadAttention(d_model, num_heads)\n    self.ffn = point_wise_feed_forward_network(d_model, dff)\n\n    #self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-6)\n    #self.layernorm2 = tf.keras.layers.LayerNormalization(epsilon=1e-6)\n    self.rz1 = ReZero(self.name + 'rz1')\n    self.rz2 = ReZero(self.name + 'rz2')\n\n    self.dropout1 = tf.keras.layers.Dropout(rate)\n    self.dropout2 = tf.keras.layers.Dropout(rate)\n\n  def call(self, x, training, mask):\n\n    attn_output, _ = self.mha(x, x, x, mask)  # (batch_size, input_seq_len, d_model)\n    attn_output = self.dropout1(attn_output, training=training)\n    out1 = x + self.rz1(attn_output)\n    #out1 = self.layernorm1(x + attn_output)  # (batch_size, input_seq_len, d_model)\n\n    ffn_output = self.ffn(out1)  # (batch_size, input_seq_len, d_model)\n    ffn_output = self.dropout2(ffn_output, training=training)\n    out2 = out1 + self.rz2(ffn_output)\n    #out2 = self.layernorm2(out1 + ffn_output)  # (batch_size, input_seq_len, d_model)\n\n    return out2\n\n\nclass DecoderLayer(tf.keras.layers.Layer):\n  def __init__(self, d_model, num_heads, dff, rate=0.1):\n    super(DecoderLayer, self).__init__()\n\n    self.mha1 = MultiHeadAttention(d_model, num_heads)\n    self.mha2 = MultiHeadAttention(d_model, num_heads)\n\n    self.ffn = point_wise_feed_forward_network(d_model, dff)\n\n    #self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-6)\n    #self.layernorm2 = tf.keras.layers.LayerNormalization(epsilon=1e-6)\n    #self.layernorm3 = tf.keras.layers.LayerNormalization(epsilon=1e-6)\n    self.rz1 = ReZero(self.name + 'rz1')\n    self.rz2 = ReZero(self.name + 'rz2')\n    self.rz3 = ReZero(self.name + 'rz3')\n\n    self.dropout1 = tf.keras.layers.Dropout(rate)\n    self.dropout2 = tf.keras.layers.Dropout(rate)\n    self.dropout3 = tf.keras.layers.Dropout(rate)\n\n\n  def call(self, x, enc_output, training, \n           look_ahead_mask, padding_mask):\n    # enc_output.shape == (batch_size, input_seq_len, d_model)\n\n    attn1, attn_weights_block1 = self.mha1(x, x, x, look_ahead_mask)  # (batch_size, target_seq_len, d_model)\n    attn1 = self.dropout1(attn1, training=training)\n    out1 = x + self.rz1(attn1)\n    #out1 = self.layernorm1(attn1 + x)\n\n    attn2, attn_weights_block2 = self.mha2(\n        enc_output, enc_output, out1, padding_mask)  # (batch_size, target_seq_len, d_model)\n    attn2 = self.dropout2(attn2, training=training)\n    out2 = out1 + self.rz2(attn2)\n    #out2 = self.layernorm2(attn2 + out1)  # (batch_size, target_seq_len, d_model)\n\n    ffn_output = self.ffn(out2)  # (batch_size, target_seq_len, d_model)\n    ffn_output = self.dropout3(ffn_output, training=training)\n    out3 = out2 + self.rz3(ffn_output)\n    #out3 = self.layernorm3(ffn_output + out2)  # (batch_size, target_seq_len, d_model)\n\n    return out3, attn_weights_block1, attn_weights_block2\n\n\nclass Encoder(tf.keras.layers.Layer):\n  def __init__(self, num_layers, d_model, num_heads, dff,\n               maximum_position_encoding, rate=0.1):\n    super(Encoder, self).__init__()\n\n    self.d_model = d_model\n    self.num_layers = num_layers\n\n    self.pos_encoding = positional_encoding(maximum_position_encoding, \n                                            self.d_model)\n\n    self.enc_layers = [EncoderLayer(d_model, num_heads, dff, rate) \n                       for _ in range(num_layers)]\n\n    self.dropout = tf.keras.layers.Dropout(rate)\n\n  def call(self, x, training, mask):\n\n    seq_len = tf.shape(x)[1]\n\n    #x *= tf.math.sqrt(tf.cast(self.d_model, tf.float32))\n    x += self.pos_encoding[:, :seq_len, :]\n\n    x = self.dropout(x, training=training)\n\n    for i in range(self.num_layers):\n      x = self.enc_layers[i](x, training, mask)\n\n    return x  # (batch_size, input_seq_len, d_model)\n\n\nclass Decoder(tf.keras.layers.Layer):\n  def __init__(self, num_layers, d_model, num_heads, dff,\n               maximum_position_encoding, rate=0.1):\n    super(Decoder, self).__init__()\n\n    self.d_model = d_model\n    self.num_layers = num_layers\n\n    self.pos_encoding = positional_encoding(maximum_position_encoding, d_model)\n\n    self.dec_layers = [DecoderLayer(d_model, num_heads, dff, rate) \n                       for _ in range(num_layers)]\n    self.dropout = tf.keras.layers.Dropout(rate)\n\n  def call(self, x, enc_output, training, \n           look_ahead_mask, padding_mask):\n\n    seq_len = tf.shape(x)[1]\n    attention_weights = {}\n\n    #x *= tf.math.sqrt(tf.cast(self.d_model, tf.float32))\n    x += self.pos_encoding[:, :seq_len, :]\n\n    x = self.dropout(x, training=training)\n\n    for i in range(self.num_layers):\n      x, block1, block2 = self.dec_layers[i](x, enc_output, training,\n                                             look_ahead_mask, padding_mask)\n\n      attention_weights['decoder_layer{}_block1'.format(i+1)] = block1\n      attention_weights['decoder_layer{}_block2'.format(i+1)] = block2\n\n    # x.shape == (batch_size, target_seq_len, d_model)\n    return x, attention_weights\n\n\nclass Transformer(tf.keras.Model):\n  def __init__(self, num_layers, d_model, num_heads, dff, input_vocab_size, \n               target_vocab_size, pe_input, pe_target, rate=0.1):\n    super(Transformer, self).__init__()\n\n    self.tok_embedding = tf.keras.layers.Embedding(input_vocab_size, d_model)\n    self.dec_embedding = tf.keras.layers.Embedding(target_vocab_size, d_model)\n\n    self.tokenizer = Encoder(num_layers, d_model, num_heads, dff,\n                             pe_input, rate)\n    self.decoder = Decoder(num_layers, d_model, num_heads, dff,\n                           pe_target, rate)\n    self.final_layer = tf.keras.layers.Dense(target_vocab_size)\n\n  def call(self, inp, tar, training, enc_padding_mask, \n           look_ahead_mask, dec_padding_mask):\n    \n    inp = self.tok_embedding(inp)\n    enc_output = self.tokenizer(inp, training, enc_padding_mask)  # (batch_size, inp_seq_len, d_model)\n\n    # dec_output.shape == (batch_size, tar_seq_len, d_model)\n    tar = self.dec_embedding(tar)\n    dec_output, attention_weights = self.decoder(\n        tar, enc_output, training, look_ahead_mask, dec_padding_mask)\n\n    final_output = self.final_layer(dec_output)  # (batch_size, tar_seq_len, target_vocab_size)\n\n    return final_output, attention_weights\n```\n\n# Load the dataset\nLoad the datasets of equations. You can create your own or load a pre-computed one from here and load it into the \n\n\n```\nSYMBOL_VOCAB_SIZE = DATASET_ENV.n_words\nSTART_TOKEN = SYMBOL_VOCAB_SIZE + 1\nEND_TOKEN = SYMBOL_VOCAB_SIZE + 2\nVOCAB_SIZE = END_TOKEN + 1\n```\n\n\n```\nclass SimplifyDataset:\n  def __init__(self, path, inp_data_len=128, tar_data_len=128):\n    self.path = path\n    self.inp_data_len = inp_data_len\n    self.tar_data_len = tar_data_len\n    self.num_train_examples = None\n    self.num_test_examples = None\n\n  def preprocess_tokens(self, w, maxlen, wrap_start_end=False):\n    if wrap_start_end:\n      w = [[START_TOKEN] + x + [END_TOKEN] for x in w]\n\n    w = tf.keras.preprocessing.sequence.pad_sequences(w, maxlen=maxlen,\n                                                      padding='post')\n    return w\n\n  def load_dataset(self, num_examples=None):\n    with open(self.path + 'x.pkl', 'rb') as f:\n      src = pickle.load(f)\n    with open(self.path + 'y.pkl', 'rb') as f:\n      tar = pickle.load(f)\n\n    if num_examples is not None:\n      src, tar = src[:num_examples], tar[:num_examples]\n\n    return src, tar\n\n  def call(self, buffer_size, batch_size, num_examples=None):\n    input, target = self.load_dataset(num_examples)\n    input = self.preprocess_tokens(input, self.inp_data_len)\n    target = self.preprocess_tokens(target, self.tar_data_len, True)\n\n    input_train, input_val, target_train, target_val = train_test_split(input, target, test_size=0.1)\n\n    self.num_train_examples = len(input_train)\n    self.num_test_examples = len(input_val)\n\n    train_dataset = tf.data.Dataset.from_tensor_slices(\n        (input_train, target_train))\n    train_dataset = train_dataset.shuffle(buffer_size)\n    train_dataset = train_dataset.batch(batch_size, drop_remainder=True)\n    train_dataset = train_dataset.repeat()\n\n    val_dataset = tf.data.Dataset.from_tensor_slices((input_val, target_val))\n    val_dataset = val_dataset.batch(batch_size, drop_remainder=True).repeat()\n\n    return train_dataset, val_dataset\n\n\ndataset = SimplifyDataset(params.dataset_path)\ntrain_dataset, val_dataset = dataset.call(32000, params.batch_size)\n```\n\n\n```\ntrain_dataset\n```\n\n\n```\ndataset.num_train_examples, dataset.num_test_examples\n```\n\n\n\n\n    (253, 29)\n\n\n\n\n```\nVOCAB_SIZE\n```\n\n## Model Setup\nThis cell contains the functions that builds the transformer model in Keras. \nHere we use a variant of the original transformer architecture known as ReZero (see [arXiv:2003.04887](https://arxiv.org/abs/2003.04887) ) for faster training convergence. \n\n## Model Design\n\n\n```\ndef create_padding_mask(seq):\n  seq = tf.cast(tf.math.equal(seq, 0), tf.float32)\n\n  # add extra dimensions to add the padding\n  # to the attention logits.\n  return seq[:, tf.newaxis, tf.newaxis, :]  # (batch_size, 1, 1, seq_len)\n\n\ndef create_look_ahead_mask(size):\n  mask = 1 - tf.linalg.band_part(tf.ones((size, size)), -1, 0)\n  return mask  # (seq_len, seq_len)\n\n\ndef create_masks(inp, tar):\n  # Encoder padding mask\n  enc_padding_mask = create_padding_mask(inp)\n\n  # Used in the 2nd attention block in the decoder.\n  # This padding mask is used to mask the encoder outputs.\n  dec_padding_mask = create_padding_mask(inp)\n\n  # Used in the 1st attention block in the decoder.\n  # It is used to pad and mask future tokens in the input received by \n  # the decoder.\n  look_ahead_mask = create_look_ahead_mask(tf.shape(tar)[1])\n  dec_target_padding_mask = create_padding_mask(tar)\n  combined_mask = tf.maximum(dec_target_padding_mask, look_ahead_mask)\n\n  return enc_padding_mask, combined_mask, dec_padding_mask\n\n\ndef get_angles(pos, i, d_model):\n  angle_rates = 1 / np.power(10000, (2 * (i//2)) / np.float32(d_model))\n  return pos * angle_rates\n\n\ndef positional_encoding(position, d_model):\n  angle_rads = get_angles(np.arange(position)[:, np.newaxis],\n                          np.arange(d_model)[np.newaxis, :],\n                          d_model)\n\n  # apply sin to even indices in the array; 2i\n  angle_rads[:, 0::2] = np.sin(angle_rads[:, 0::2])\n\n  # apply cos to odd indices in the array; 2i+1\n  angle_rads[:, 1::2] = np.cos(angle_rads[:, 1::2])\n\n  pos_encoding = angle_rads[np.newaxis, ...]\n\n  return tf.cast(pos_encoding, dtype=tf.float32)\n\n\ndef scaled_dot_product_attention(q, k, v, mask):\n  \"\"\"Calculate the attention weights.\n  q, k, v must have matching leading dimensions.\n  k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.\n  The mask has different shapes depending on its type(padding or look ahead) \n  but it must be broadcastable for addition.\n\n  Args:\n    q: query shape == (..., seq_len_q, depth)\n    k: key shape == (..., seq_len_k, depth)\n    v: value shape == (..., seq_len_v, depth_v)\n    mask: Float tensor with shape broadcastable \n          to (..., seq_len_q, seq_len_k). Defaults to None.\n\n  Returns:\n    output, attention_weights\n  \"\"\"\n\n  matmul_qk = tf.matmul(q, k, transpose_b=True)  # (..., seq_len_q, seq_len_k)\n\n  # scale matmul_qk\n  dk = tf.cast(tf.shape(k)[-1], tf.float32)\n  scaled_attention_logits = matmul_qk / tf.math.sqrt(dk)\n\n  # add the mask to the scaled tensor.\n  if mask is not None:\n    scaled_attention_logits += (mask * -1e9)  \n\n  # softmax is normalized on the last axis (seq_len_k) so that the scores\n  # add up to 1.\n  attention_weights = tf.nn.softmax(scaled_attention_logits, axis=-1)  # (..., seq_len_q, seq_len_k)\n\n  output = tf.matmul(attention_weights, v)  # (..., seq_len_q, depth_v)\n\n  return output, attention_weights\n\n\nclass MultiHeadAttention(tf.keras.layers.Layer):\n  def __init__(self, d_model, num_heads):\n    super(MultiHeadAttention, self).__init__()\n    self.num_heads = num_heads\n    self.d_model = d_model\n\n    assert d_model % self.num_heads == 0\n\n    self.depth = d_model // self.num_heads\n\n    self.wq = tf.keras.layers.Dense(d_model)\n    self.wk = tf.keras.layers.Dense(d_model)\n    self.wv = tf.keras.layers.Dense(d_model)\n\n    self.dense = tf.keras.layers.Dense(d_model)\n\n  def split_heads(self, x, batch_size):\n    \"\"\"Split the last dimension into (num_heads, depth).\n    Transpose the result such that the shape is (batch_size, num_heads, seq_len, depth)\n    \"\"\"\n    x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth))\n    return tf.transpose(x, perm=[0, 2, 1, 3])\n\n  def call(self, v, k, q, mask):\n    batch_size = tf.shape(q)[0]\n\n    q = self.wq(q)  # (batch_size, seq_len, d_model)\n    k = self.wk(k)  # (batch_size, seq_len, d_model)\n    v = self.wv(v)  # (batch_size, seq_len, d_model)\n\n    q = self.split_heads(q, batch_size)  # (batch_size, num_heads, seq_len_q, depth)\n    k = self.split_heads(k, batch_size)  # (batch_size, num_heads, seq_len_k, depth)\n    v = self.split_heads(v, batch_size)  # (batch_size, num_heads, seq_len_v, depth)\n\n    # scaled_attention.shape == (batch_size, num_heads, seq_len_q, depth)\n    # attention_weights.shape == (batch_size, num_heads, seq_len_q, seq_len_k)\n    scaled_attention, attention_weights = scaled_dot_product_attention(\n        q, k, v, mask)\n\n    scaled_attention = tf.transpose(scaled_attention, perm=[0, 2, 1, 3])  # (batch_size, seq_len_q, num_heads, depth)\n\n    concat_attention = tf.reshape(scaled_attention, \n                                  (batch_size, -1, self.d_model))  # (batch_size, seq_len_q, d_model)\n\n    output = self.dense(concat_attention)  # (batch_size, seq_len_q, d_model)\n\n    return output, attention_weights\n\n\ndef point_wise_feed_forward_network(d_model, dff):\n  return tf.keras.Sequential([\n      tf.keras.layers.Dense(dff, activation='relu'),  # (batch_size, seq_len, dff)\n      tf.keras.layers.Dense(d_model)  # (batch_size, seq_len, d_model)\n  ])\n\n\nclass ReZero(tf.keras.layers.Layer):\n    def __init__(self, name):\n        super(ReZero, self).__init__(name=name)\n        a_init = tf.zeros_initializer()\n        self.alpha = tf.Variable(name=self.name + '-alpha',\n            initial_value=a_init(shape=(1,), dtype=\"float32\"), trainable=True\n        )\n\n    def call(self, inputs):\n        return self.alpha * inputs\n\n\nclass EncoderLayer(tf.keras.layers.Layer):\n  def __init__(self, d_model, num_heads, dff, rate=0.1):\n    super(EncoderLayer, self).__init__()\n\n    self.mha = MultiHeadAttention(d_model, num_heads)\n    self.ffn = point_wise_feed_forward_network(d_model, dff)\n\n    self.rz1 = ReZero(self.name + 'rz1')\n    self.rz2 = ReZero(self.name + 'rz2')\n\n    self.dropout1 = tf.keras.layers.Dropout(rate)\n    self.dropout2 = tf.keras.layers.Dropout(rate)\n\n  def call(self, x, training, mask):\n\n    attn_output, _ = self.mha(x, x, x, mask)  # (batch_size, input_seq_len, d_model)\n    attn_output = self.dropout1(attn_output, training=training)\n    out1 = x + self.rz1(attn_output)\n    #out1 = self.layernorm1(x + attn_output)  # (batch_size, input_seq_len, d_model)\n\n    ffn_output = self.ffn(out1)  # (batch_size, input_seq_len, d_model)\n    ffn_output = self.dropout2(ffn_output, training=training)\n    out2 = out1 + self.rz2(ffn_output)\n    #out2 = self.layernorm2(out1 + ffn_output)  # (batch_size, input_seq_len, d_model)\n\n    return out2\n\n\nclass DecoderLayer(tf.keras.layers.Layer):\n  def __init__(self, d_model, num_heads, dff, rate=0.1):\n    super(DecoderLayer, self).__init__()\n\n    self.mha1 = MultiHeadAttention(d_model, num_heads)\n    self.mha2 = MultiHeadAttention(d_model, num_heads)\n\n    self.ffn = point_wise_feed_forward_network(d_model, dff)\n\n    self.rz1 = ReZero(self.name + 'rz1')\n    self.rz2 = ReZero(self.name + 'rz2')\n    self.rz3 = ReZero(self.name + 'rz3')\n\n    self.dropout1 = tf.keras.layers.Dropout(rate)\n    self.dropout2 = tf.keras.layers.Dropout(rate)\n    self.dropout3 = tf.keras.layers.Dropout(rate)\n\n\n  def call(self, x, enc_output, training, \n           look_ahead_mask, padding_mask):\n    # enc_output.shape == (batch_size, input_seq_len, d_model)\n\n    attn1, attn_weights_block1 = self.mha1(x, x, x, look_ahead_mask)  # (batch_size, target_seq_len, d_model)\n    attn1 = self.dropout1(attn1, training=training)\n    out1 = x + self.rz1(attn1)\n\n    attn2, attn_weights_block2 = self.mha2(\n        enc_output, enc_output, out1, padding_mask)  # (batch_size, target_seq_len, d_model)\n    attn2 = self.dropout2(attn2, training=training)\n    out2 = out1 + self.rz2(attn2)\n\n    ffn_output = self.ffn(out2)  # (batch_size, target_seq_len, d_model)\n    ffn_output = self.dropout3(ffn_output, training=training)\n    out3 = out2 + self.rz3(ffn_output)\n\n    return out3, attn_weights_block1, attn_weights_block2\n\n\nclass Encoder(tf.keras.layers.Layer):\n  def __init__(self, num_layers, d_model, num_heads, dff,\n               maximum_position_encoding, rate=0.1):\n    super(Encoder, self).__init__()\n\n    self.d_model = d_model\n    self.num_layers = num_layers\n\n    self.pos_encoding = positional_encoding(maximum_position_encoding, \n                                            self.d_model)\n\n    self.enc_layers = [EncoderLayer(d_model, num_heads, dff, rate) \n                       for _ in range(num_layers)]\n\n    self.dropout = tf.keras.layers.Dropout(rate)\n\n  def call(self, x, training, mask):\n\n    seq_len = tf.shape(x)[1]\n    x += self.pos_encoding[:, :seq_len, :]\n\n    x = self.dropout(x, training=training)\n\n    for i in range(self.num_layers):\n      x = self.enc_layers[i](x, training, mask)\n\n    return x  # (batch_size, input_seq_len, d_model)\n\n\nclass Decoder(tf.keras.layers.Layer):\n  def __init__(self, num_layers, d_model, num_heads, dff,\n               maximum_position_encoding, rate=0.1):\n    super(Decoder, self).__init__()\n\n    self.d_model = d_model\n    self.num_layers = num_layers\n\n    self.pos_encoding = positional_encoding(maximum_position_encoding, d_model)\n\n    self.dec_layers = [DecoderLayer(d_model, num_heads, dff, rate) \n                       for _ in range(num_layers)]\n    self.dropout = tf.keras.layers.Dropout(rate)\n\n  def call(self, x, enc_output, training, \n           look_ahead_mask, padding_mask):\n\n    seq_len = tf.shape(x)[1]\n    attention_weights = {}\n\n    #x *= tf.math.sqrt(tf.cast(self.d_model, tf.float32))\n    x += self.pos_encoding[:, :seq_len, :]\n\n    x = self.dropout(x, training=training)\n\n    for i in range(self.num_layers):\n      x, block1, block2 = self.dec_layers[i](x, enc_output, training,\n                                             look_ahead_mask, padding_mask)\n\n      attention_weights['decoder_layer{}_block1'.format(i+1)] = block1\n      attention_weights['decoder_layer{}_block2'.format(i+1)] = block2\n\n    # x.shape == (batch_size, target_seq_len, d_model)\n    return x, attention_weights\n\n\nclass Transformer(tf.keras.Model):\n  def __init__(self, num_layers, d_model, num_heads, dff, input_vocab_size, \n               target_vocab_size, pe_input, pe_target, rate=0.1):\n    super(Transformer, self).__init__()\n\n    self.tok_embedding = tf.keras.layers.Embedding(input_vocab_size, d_model)\n    self.dec_embedding = tf.keras.layers.Embedding(target_vocab_size, d_model)\n\n    self.tokenizer = Encoder(num_layers, d_model, num_heads, dff,\n                             pe_input, rate)\n    self.decoder = Decoder(num_layers, d_model, num_heads, dff,\n                           pe_target, rate)\n    self.final_layer = tf.keras.layers.Dense(target_vocab_size)\n\n  def call(self, inp, tar, training, enc_padding_mask, \n           look_ahead_mask, dec_padding_mask):\n    \n    inp = self.tok_embedding(inp)\n    enc_output = self.tokenizer(inp, training, enc_padding_mask)  # (batch_size, inp_seq_len, d_model)\n\n    # dec_output.shape == (batch_size, tar_seq_len, d_model)\n    tar = self.dec_embedding(tar)\n    dec_output, attention_weights = self.decoder(\n        tar, enc_output, training, look_ahead_mask, dec_padding_mask)\n\n    final_output = self.final_layer(dec_output)  # (batch_size, tar_seq_len, target_vocab_size)\n\n    return final_output, attention_weights\n```\n\n## Model Creation\n\n\n```\nK.clear_session()\n\ntransformer = Transformer(\n    num_layers=params.num_layers,\n    d_model=params.d_model,\n    num_heads=params.num_heads,\n    dff=params.dff,\n    input_vocab_size=VOCAB_SIZE,\n    target_vocab_size=VOCAB_SIZE, \n    pe_input=params.max_len,\n    pe_target=params.max_len,\n    rate=params.dropout_rate)\n\n\nlearning_rate = 1e-4\noptimizer = tf.keras.optimizers.Adam(learning_rate, beta_1=0.9, beta_2=0.98, \n                                     epsilon=1e-9)\n\nloss_object = tf.keras.losses.SparseCategoricalCrossentropy(\n    from_logits=True, reduction='none')\n\ndef loss_function(real, pred):\n  mask = tf.math.logical_not(tf.math.equal(real, 0))\n  loss_ = loss_object(real, pred)\n\n  mask = tf.cast(mask, dtype=loss_.dtype)\n  loss_ *= mask\n\n  return tf.reduce_sum(loss_)/tf.reduce_sum(mask)\n\n\ndef accuracy_function(real, pred):\n  accuracies = tf.equal(tf.cast(real, tf.int64), tf.argmax(pred, axis=2))\n\n  mask = tf.math.logical_not(tf.math.equal(real, 0))\n  accuracies = tf.math.logical_and(mask, accuracies)\n\n  accuracies = tf.cast(accuracies, dtype=tf.float32)\n  mask = tf.cast(mask, dtype=tf.float32)\n  return tf.reduce_sum(accuracies)/tf.reduce_sum(mask)\n\n\ntrain_loss = tf.keras.metrics.Mean(name='train_loss')\nval_loss = tf.keras.metrics.Mean(name='val_loss')\n\ntrain_accuracy = tf.keras.metrics.Mean(name='train_accuracy')\nval_accuracy = tf.keras.metrics.Mean(name='val_accuracy')\n\n\ntrain_step_signature = [\n    tf.TensorSpec(shape=(None, dataset.inp_data_len), dtype=tf.int32),\n    tf.TensorSpec(shape=(None, dataset.tar_data_len), dtype=tf.int32),\n]\n\n@tf.function(input_signature=train_step_signature)\ndef train_step(inp, tar):\n  tar_inp = tar[:, :-1]\n  tar_real = tar[:, 1:]\n\n  enc_padding_mask, combined_mask, dec_padding_mask = create_masks(inp, tar_inp)\n\n  with tf.GradientTape() as tape:\n    predictions, _ = transformer(inp, tar_inp, \n                                 True, \n                                 enc_padding_mask, \n                                 combined_mask, \n                                 dec_padding_mask)\n    loss = loss_function(tar_real, predictions)\n\n  gradients = tape.gradient(loss, transformer.trainable_variables)    \n  optimizer.apply_gradients(zip(gradients, transformer.trainable_variables))\n\n  train_loss(loss)\n  train_accuracy(accuracy_function(tar_real, predictions))\n\n\n@tf.function(input_signature=train_step_signature)\ndef val_step(inp, tar):\n  tar_inp = tar[:, :-1]\n  tar_real = tar[:, 1:]\n\n  enc_padding_mask, combined_mask, dec_padding_mask = create_masks(inp, tar_inp)\n\n  predictions, _ = transformer(inp, tar_inp, \n                                True, \n                                enc_padding_mask, \n                                combined_mask, \n                                dec_padding_mask)\n  loss = loss_function(tar_real, predictions)\n\n  val_loss(loss)\n  val_accuracy(accuracy_function(tar_real, predictions))\n```\n\n## Training Loop\n\nAutomatically saves the model weights that gives the smallest loss on the validation set.\n\n\n```\nsteps_per_epoch = dataset.num_train_examples//params.batch_size\nsteps_per_val = dataset.num_test_examples//params.batch_size\nbest_val = np.inf\n\n\nfor epoch in range(params.epochs):\n  start = time.time()\n  \n  train_loss.reset_states()\n  train_accuracy.reset_states()\n\n  print(f'Ep: {epoch}, Current Best: {best_val}')\n  for (i, (inp, targ)) in enumerate(train_dataset.take(steps_per_epoch)):\n    train_step(inp, targ)\n\n    if i % 200 == 0:\n      print('Iter {} Loss {:.4f} Train Acc {:.4f}'.format(\n            i, train_loss.result(), train_accuracy.result()))\n      \n  print('Epoch {:.4f} Train Loss {:.4f} Train Acc {:.4f}'.format(\n      epoch, train_loss.result(), train_accuracy.result()))\n  print('Time taken for 1 epoch: {:.4f} secs'.format(time.time() - start))\n\n  val_loss.reset_states()\n  val_accuracy.reset_states()\n  for inp, targ in train_dataset.take(steps_per_val):\n    val_step(inp, targ)\n  validation_loss = val_loss.result()\n  validation_acc = val_accuracy.result()\n\n  display.clear_output()\n  print(\"Validation Loss: {:.4f} Vaidation Acc {:.4f}\\n\".format(\n      validation_loss, validation_acc))\n  if validation_loss < best_val:\n    transformer.save_weights(params.model_path)\n    best_val = validation_loss\n\n```\n\n# Evaluate\n\nHere we test our model on select equations. Obviously, quality of the output varies depending on dataset and model size. Here an 'InvalidPrefixExpression' is thrown when the model outputs an invalid expression.\n\n\n```\ndef evaluate(eqa, max_length=40):\n  # inp sentence is portuguese, hence adding the start and end token\n  #eqa = DATASET_ENV.sympy_to_prefix(eqa)\n  #eqa = [DATASET_ENV.word2id[w] for w in eqa]\n  #eqa = np.array(eqa)\n  eqa = tf.convert_to_tensor([eqa])\n  #sentence = tokenizers.pt.tokenize(sentence).to_tensor()\n\n  encoder_input = eqa\n\n  # as the target is english, the first word to the transformer should be the\n  # english start token.\n  output = tf.convert_to_tensor([START_TOKEN])\n  output = tf.expand_dims(output, 0)\n\n  for i in range(max_length):\n    enc_padding_mask, combined_mask, dec_padding_mask = create_masks(\n        encoder_input, output)\n\n    # predictions.shape == (batch_size, seq_len, vocab_size)\n    predictions, attention_weights = transformer(encoder_input, \n                                                 output,\n                                                 False,\n                                                 enc_padding_mask,\n                                                 combined_mask,\n                                                 dec_padding_mask)\n\n    # select the last word from the seq_len dimension\n    predictions = predictions[: ,-1:, :]  # (batch_size, 1, vocab_size)\n\n    predicted_id = tf.argmax(predictions, axis=-1)\n    predicted_id = tf.cast(predicted_id, tf.int32)\n\n    # return the result if the predicted_id is equal to the end token\n    if predicted_id == END_TOKEN:\n      break\n\n    # concatentate the predicted_id to the output which is given to the decoder\n    # as its input.\n    output = tf.concat([output, predicted_id], axis=-1)\n\n  return output[:, 1:]\n```\n\n\n```\nfrom sympy.parsing.sympy_parser import (parse_expr, standard_transformations, \n                                        implicit_multiplication_application,\n                                        convert_xor)\nfrom sympy import symbols, diff, init_printing, preorder_traversal, simplify\n\ntest_expr = \"2x - 2x\"\nTRANSFORMATIONS = (standard_transformations + (implicit_multiplication_application,) + (convert_xor,))\ntest_expr = parse_expr(test_expr, transformations=TRANSFORMATIONS, evaluate=False)\ntest_expr\n```\n\n\n\n\n$\\displaystyle - 2 x + 2 x$\n\n\n\nmodel output:\n\n\n```\nmodel_output = evaluate(sympy_to_sequences(test_expr, DATASET_ENV)).numpy()[0]\nsequences_to_sympy(model_output, DATASET_ENV)\n```\n\nsimplification according to Sympy:\n\n\n```\nsimplify(test_expr)\n```\n\n\n\n\n$\\displaystyle 0$\n\n\n\n\n```\ntest_expr = \"2x^3+5x^3\"\nTRANSFORMATIONS = (standard_transformations + (implicit_multiplication_application,) + (convert_xor,))\ntest_expr = parse_expr(test_expr, transformations=TRANSFORMATIONS, evaluate=False)\ntest_expr\n```\n\n\n\n\n$\\displaystyle 2 x^{3} + 5 x^{3}$\n\n\n\nmodel output:\n\n\n```\nmodel_output = evaluate(sympy_to_sequences(test_expr, DATASET_ENV)).numpy()[0]\nsequences_to_sympy(model_output, DATASET_ENV)\n```\n\n\n```\nsimplify(test_expr)\n```\n\n\n\n\n$\\displaystyle 7 x^{3}$\n\n\n", "meta": {"hexsha": "a8f60bec0f17a7b45d942cfa3a94d60a7df9a0fa", "size": 108458, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "train-eval.ipynb", "max_stars_repo_name": "Ninalgad/SimpTransformer", "max_stars_repo_head_hexsha": "7859ff694951743101319e4b0510e55f3c0078a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "train-eval.ipynb", "max_issues_repo_name": "Ninalgad/SimpTransformer", "max_issues_repo_head_hexsha": "7859ff694951743101319e4b0510e55f3c0078a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "train-eval.ipynb", "max_forks_repo_name": "Ninalgad/SimpTransformer", "max_forks_repo_head_hexsha": "7859ff694951743101319e4b0510e55f3c0078a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 108458.0, "max_line_length": 108458, "alphanum_fraction": 0.6216507773, "converted": true, "num_tokens": 17575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926492132671, "lm_q2_score": 0.060086652698692546, "lm_q1q2_score": 0.027002500038622947}}
{"text": "# Tokenizing Sentences\n1. Split apart corpus into sentences.\n2. Split apart sentences into words.\n\n\n```python\n# Why not just tokenize myself?\nimport nltk\ntext = \"I made two purchases today! I bought a bag of grapes for $4.99, \\\nbut then... realized John Francis already bought some at the Y.M.C.A!\"\n```\n\n\n```python\n# trying to write our own tokenizer\ntext.split(\".\")\n```\n\n\n\n\n    ['I made two purchases today! I bought a bag of grapes for $4',\n     '99, but then',\n     '',\n     '',\n     ' realized John Francis already bought some at the Y',\n     'M',\n     'C',\n     'A!']\n\n\n\n\n```python\n# Using NLTK sent_tokenize()\nsent_text = nltk.sent_tokenize(text) # this gives us a list of sentences\nsent_text\n```\n\n\n\n\n    ['I made two purchases today!',\n     'I bought a bag of grapes for $4.99, but then... realized John Francis already bought some at the Y.M.C.A!']\n\n\n\n## Stemming\n\n\n\nStemming is the process of reducing inflection in words to their root forms such as mapping a group of words to the same stem even if the stem itself is not a valid word in the language [Source](https://www.datacamp.com/community/tutorials/stemming-lemmatization-python)\n\nIn Python, we can use **`nltk.stem.porter.PorterStemmer`** stem our words:\n\n```python\nstemmer = PorterStemmer()\nprint(stemmer.stem(\"caressed\"))  # caress\nprint(stemmer.stem(\"athlete\"))  # athlet\nprint(stemmer.stem(\"athletics\"))  # athlet\nprint(stemmer.stem(\"media\"))  # media\nprint(stemmer.stem(\"photography\"))  # photographi\nprint(stemmer.stem(\"sexy\"))  # sexi\nprint(stemmer.stem(\"journalling\"))  # journal\nprint(stemmer.stem(\"Slovakia\")) # slovakia\nprint(stemmer.stem(\"corpora\")) # corpora\nprint(stemmer.stem(\"thieves\")) # thiev\nprint(stemmer.stem(\"rocks\")) # rock\n```\n\n## Lemmatization\n\n```python\nfrom nltk.stem import WordNetLemmatizer\nlemmatizer = WordNetLemmatizer()\nprint(lemmatizer.lemmatize(\"caressed\")) #caressed\nprint(lemmatizer.lemmatize(\"athlete\")) #athlete\nprint(lemmatizer.lemmatize(\"athletics\")) #athletics\nprint(lemmatizer.lemmatize(\"media\"))\nprint(lemmatizer.lemmatize(\"photography\")) #photography\nprint(lemmatizer.lemmatize(\"sexy\")) #sexy\nprint(lemmatizer.lemmatize(\"journalling\")) #journalling\nprint(lemmatizer.lemmatize(\"Slovakia\")) #Slovakia\nprint(lemmatizer.lemmatize(\"corpora\")) # corpus\nprint(lemmatizer.lemmatize(\"thieves\")) # thief\nprint(lemmatizer.lemmatize(\"rocks\")) #rock\n```\n\nWhy would you ever care to use stemming?\n- smaller and faster\n- simplicity in \"good enough\"\n- can often **provide higher recall (coverage)** if you are using it for text searching: `drives` and `drivers` will likely shorten to `driv`, which may be useful if your search engine wants to make sure to get all relevant documents, even at the cost of surfacing a few irrelevant documents\n- could potentially be more useful for predictive models that tend to overfit\n\n## Scoring Metrics\n\n\n\n### Precision/Recall\n\n**Recall:** What percent of the positive classes did the model successfully predict?\n**Precision:** When a model predicted a positive class, what percentage of the time was it correct?\n\nIn terms of NLP / stemming / lemmatization:\n\n**Recall**: After processing (tokenizing, stemming/lemmatizing) the data, what percent of the relevant search results were surfaced? Ie. - when a user searches for \"blue jeans\", did all the results returned include all the relevant items (blue-ish colored denim pants)?\n\n**Precision**: After processing (tokenizing, stemming/lemmatizing) the data, what percent of the results returned were relevant?\n\n\n\n**Precision:** $\\frac{?}{?}$\n\n**Recall:** $\\frac{?}{?}$\n\n### F1 Score\n\nThe F1 score of a model represents the harmonic mean between precision and recall, and is defined as \n\n$$\n\\begin{equation}\nF_{1} = 2 * \\frac{P * R}{P + R}\n\\end{equation}\n$$\n\n## Exercise:\n\n##### 1. For each of the following statements, label them True or False. If False, briefly explain why:\n\nA. Text typically should be processed via either stemming or lemmatization, but not both.\n\nB. Texts processed using lemmatization will typically have higher recall than stemming.\n\nC. If the **F1 score** of a model is **1.0 (100%)**, then the accuracy of your model must also be **100%**.\n\n##### 2. Calculate precison and recall given the following results from a confusion matrix:\n\n\n\n\n\n```python\nfrom sklearn.feature_extraction.text import CountVectorizer\n# list of text documents\ntext = [\"It's still early, so box-office disappointments are still among the highest-grossing movies of the year.\", \n        \"That movie was terrific\", \"You love cats\", \n        \"Pay for top executives at big US companies is vastly higher than what everyday workers make, and a new report from The Wall Street Journal has found that CEOs have hit an eye-popping milestone in the size of their monthly paychecks.\"]\n# create the transform\nvectorizer = CountVectorizer()\n\n# tokenize and build vocab\nvectorizer.fit(text)\n\n# vectorize the corpus\nvector = vectorizer.transform(text)\n\n# summarize encoded vector\nprint(vector.shape)\n\n# Notice what type of object this is\nprint(type(vector))\n```\n\n    (4, 59)\n    <class 'scipy.sparse.csr.csr_matrix'>\n\n\n\n```python\n# see the outputted vectors\nprint(vector.toarray())\nprint(vectorizer.get_feature_names())\n```\n\n    [[1 0 0 1 0 0 1 0 0 0 1 1 0 0 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0 0 0 1 0 1\n      1 0 0 0 0 0 1 2 0 0 0 0 2 0 0 0 0 0 0 0 0 1 0]\n     [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0\n      0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 1 0 0 0 0]\n     [0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0\n      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]\n     [0 1 1 0 1 1 0 0 1 1 0 0 1 1 1 1 1 1 0 1 1 1 0 1 1 1 0 1 0 1 1 1 0 0 1 1\n      0 1 1 1 1 1 0 0 1 0 1 1 2 1 1 1 1 1 0 1 1 0 0]]\n    ['among', 'an', 'and', 'are', 'at', 'big', 'box', 'cats', 'ceos', 'companies', 'disappointments', 'early', 'everyday', 'executives', 'eye', 'for', 'found', 'from', 'grossing', 'has', 'have', 'higher', 'highest', 'hit', 'in', 'is', 'it', 'journal', 'love', 'make', 'milestone', 'monthly', 'movie', 'movies', 'new', 'of', 'office', 'pay', 'paychecks', 'popping', 'report', 'size', 'so', 'still', 'street', 'terrific', 'than', 'that', 'the', 'their', 'top', 'us', 'vastly', 'wall', 'was', 'what', 'workers', 'year', 'you']\n\n\n\n```python\n# load vectorized corpus into Pandas dataframe\nimport pandas as pd\ncorpus_df = pd.DataFrame(vector.toarray(), columns=vectorizer.get_feature_names())\ncorpus_df.describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>among</th>\n      <th>an</th>\n      <th>and</th>\n      <th>are</th>\n      <th>at</th>\n      <th>big</th>\n      <th>box</th>\n      <th>cats</th>\n      <th>ceos</th>\n      <th>companies</th>\n      <th>...</th>\n      <th>their</th>\n      <th>top</th>\n      <th>us</th>\n      <th>vastly</th>\n      <th>wall</th>\n      <th>was</th>\n      <th>what</th>\n      <th>workers</th>\n      <th>year</th>\n      <th>you</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>...</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>...</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>0.50</td>\n      <td>0.50</td>\n      <td>0.50</td>\n      <td>0.50</td>\n      <td>0.50</td>\n      <td>0.50</td>\n      <td>0.50</td>\n      <td>0.50</td>\n      <td>0.50</td>\n      <td>0.50</td>\n      <td>...</td>\n      <td>0.50</td>\n      <td>0.50</td>\n      <td>0.50</td>\n      <td>0.50</td>\n      <td>0.50</td>\n      <td>0.50</td>\n      <td>0.50</td>\n      <td>0.50</td>\n      <td>0.50</td>\n      <td>0.50</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>...</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n      <td>0.25</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>...</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>8 rows \u00d7 59 columns</p>\n</div>\n\n\n\n## Removing Stopwords\n\nIt's your call if you want to remove stopwords. We discussed already the advantages and disadvantages to both approaches. You will first need to run `nltk.download(\"stopwords\")` to download the set of stopwords for NLTK:\n\n\n```python\nfrom nltk.corpus import stopwords\nprint(set(stopwords.words('english'))) # see the set of words NLTK considers stopwords\n```\n\n    {\"you'd\", 'm', 'below', 'or', \"mustn't\", 'up', 'has', 't', 'until', 'their', 'most', 'these', 'few', 'no', 'hasn', \"aren't\", 'as', 'each', 'them', 'hers', 'there', 'whom', 'why', 'under', \"don't\", 're', 'wasn', \"hadn't\", 'nor', \"doesn't\", 'to', \"won't\", 'our', 'against', 'so', 'themselves', 'some', 'while', \"hasn't\", 'itself', 'other', 'just', 'its', 's', \"that'll\", 'through', 'ain', 'haven', 'her', 'off', 'only', 'can', 'we', 'further', 'isn', 'over', 'when', 'i', 'are', 'shan', 'after', \"it's\", 'him', 'on', 'with', 've', 'own', \"she's\", \"shouldn't\", \"weren't\", 'too', 'your', 'does', 'his', 'myself', \"should've\", \"needn't\", \"shan't\", \"isn't\", 'then', 'yourselves', 'they', 'about', 'ourselves', 'won', 'but', 'am', 'than', 'those', 'into', 'doing', 'is', 'same', 'doesn', 'before', 'which', 'having', 'herself', 'did', 'shouldn', 'out', 'himself', 'she', 'again', 'here', 'where', 'me', 'y', 'at', 'an', 'yours', \"you'll\", 'it', \"mightn't\", 'that', 'both', 'this', 'will', \"wouldn't\", 'been', 'aren', 'couldn', 'you', 'very', 'any', 'ma', 'mustn', 'for', 'be', 'didn', 'mightn', 'yourself', 'who', 'were', 'down', 'such', 'not', 'll', 'more', 'from', 'don', 'hadn', 'during', 'how', 'what', 'a', 'should', \"haven't\", \"wasn't\", 'by', \"didn't\", 'once', 'being', 'have', 'needn', 'my', 'of', 'was', 'because', 'between', 'theirs', 'all', 'had', 'now', 'if', 'the', 'wouldn', \"you've\", 'he', 'and', 'weren', 'd', \"you're\", 'o', 'above', 'do', 'in', \"couldn't\", 'ours'}\n\n\n\n```python\n# iterate through the Pandas dataframe, and drop the columns that reflect stopwords:\n\noriginal_columns = corpus_df.columns # get existing columns\n\nto_drop_columns = set(original_columns).intersection(set(stopwords.words('english'))) # get the list of words to drop\nprint(f\"Dataframe shape was {corpus_df.shape}\")\ncorpus_df.drop(columns=to_drop_columns, inplace=True)\nprint(f\"Dataframe shape is now{corpus_df.shape}\")\n```\n\n    Dataframe shape was (4, 59)\n    Dataframe shape is now(4, 39)\n\n\n## Co-Occurence Matrix\n\n\n```python\n# run a quick correlation analysis to see if any word pairs show rough co-occurence\ncorpus_df.corr()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>among</th>\n      <th>big</th>\n      <th>box</th>\n      <th>cats</th>\n      <th>ceos</th>\n      <th>companies</th>\n      <th>disappointments</th>\n      <th>early</th>\n      <th>everyday</th>\n      <th>executives</th>\n      <th>...</th>\n      <th>size</th>\n      <th>still</th>\n      <th>street</th>\n      <th>terrific</th>\n      <th>top</th>\n      <th>us</th>\n      <th>vastly</th>\n      <th>wall</th>\n      <th>workers</th>\n      <th>year</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>among</th>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>...</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>big</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>box</th>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>...</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>cats</th>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>...</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>ceos</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>companies</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>disappointments</th>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>...</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>early</th>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>...</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>everyday</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>executives</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>eye</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>found</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>grossing</th>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>...</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>higher</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>highest</th>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>...</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>hit</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>journal</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>love</th>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>...</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>make</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>milestone</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>monthly</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>movie</th>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>...</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>movies</th>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>...</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>new</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>office</th>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>...</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>pay</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>paychecks</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>popping</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>report</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>size</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>still</th>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>...</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>street</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>terrific</th>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>...</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>top</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>us</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>vastly</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>wall</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>workers</th>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>...</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n    </tr>\n    <tr>\n      <th>year</th>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>...</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>-0.333333</td>\n      <td>1.000000</td>\n    </tr>\n  </tbody>\n</table>\n<p>39 rows \u00d7 39 columns</p>\n</div>\n\n\n", "meta": {"hexsha": "5ee5310de756f8f61521c314f9f224bba4188a94", "size": 70574, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "week2/Text Preprocessing Techniques (Completed).ipynb", "max_stars_repo_name": "ychennay/dso-599-text-analytics-nlp", "max_stars_repo_head_hexsha": "e02e136d24e5a704e2ad69c599e89f9173072968", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-03-06T02:34:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T23:06:57.000Z", "max_issues_repo_path": "week2/Text Preprocessing Techniques (Completed).ipynb", "max_issues_repo_name": "ychennay/dso-599-text-analytics-nlp", "max_issues_repo_head_hexsha": "e02e136d24e5a704e2ad69c599e89f9173072968", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week2/Text Preprocessing Techniques (Completed).ipynb", "max_forks_repo_name": "ychennay/dso-599-text-analytics-nlp", "max_forks_repo_head_hexsha": "e02e136d24e5a704e2ad69c599e89f9173072968", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2019-03-06T02:25:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-09T14:02:09.000Z", "avg_line_length": 39.7824126268, "max_line_length": 1535, "alphanum_fraction": 0.3887834047, "converted": true, "num_tokens": 14764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733753118592733, "lm_q2_score": 0.12421299862599397, "lm_q1q2_score": 0.026996146462574512}}
{"text": "# Week 2 \n## Introduction to Solid State \n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport subprocess\nimport MSD as msd\n\nfrom scipy import stats\n\n\ndef get_diffusion(file, atom):\n    \n    with open(file) as f:\n        y = False\n        for line in f:\n            if str(\"atom        D \") in line:\n                y = True\n            if y == True and str(atom) in line:\n                d = line.split()\n                break\n    return d\n```\n\nNow that you are familiar with molecular dynamics, you are now going to use it to tackle some real world problems. In the next three weeks you will investigate the transport properties of a simple fluorite material - Ca$F_2$. The transport properties of a material determine many properties that are utilised for modern technological applications. For example, solid oxide fuel cell (SOFCs - Alternative to batteries) materials are dependent on the movement of charge carriers through the solid electrolyte and  nuclear fuel materials oxidise and fall apart and this corrosive behaviour is dependent on the diffusion of oxygen into the lattice. Due to the importance of the transport properties of these materials, scientists and engineers spend large amounts of their time tring to optomise these properties using different stoichiometries, introducing defects and by using different syntheisis techniques. Over the next three weeks you will investigate how the transport properties of Ca$F_2$ are affected by temperature, structural defects (Schottky and Frenkel) and by chemcial dopants (e.g. different cations). A rough breakdown looks as follows\n- Week 2 \n    - Introduction to DL_POLY\n    - Tutorial on the calculation of diffusion coefficients\n    - Tutorial on the Arhennius equation\n    - Molecular dynamics simulations of stoichiomteric Ca$F_2$\n- Week 3 \n    - Frenkel and Schottky defects\n- Week 4 \n    - Dopants\n    \n\n\n## Introduction to DL_POLY\n\nDL_POLY is a molecular dynamics program maintained by Daresbury laboratories. In contrast to pylj, DL_POLY is a three dimensional molecular dynamics code that is used worldwide by computational scientists for molecular simulation, but it should be noted that the theory is exactly the same and any understanding gained from pylj is completely applicable to DL_POLY. For the next three weeks you will use DL_POLY to run short molecular dynamics simulations on Ca$F_2$. You first need to understand the input files required for DL_POLY. \n- CONTROL - This is the file that contains all of the simulation parameters, e.g. simulation temperature, pressure, number of steps e.t.c\n- CONFIG - This is the file that contains the structure - i.e. the atomic coordinates of each atom. \n- FIELD - This is the file that contains the force field or potential model e.g. Lennard Jones. \n\nContained within the folder \"Input\" you will find a file called input.txt. This is the main file that you will interact with over the next three weeks and is used to generate the FIELD, CONTROL and CONFIG. Essentially it is easier to meddle with input.txt than it is to meddle with the 3 DL_POLY files everytime you want to change something. To run metadise we will use the subprocess python module. You specify what program you want to run and the file that you want to run it in, you will need to ensure the file path is correct.\n\n\n```python\nsubprocess.call('H:/Third_year_lab/Advanced_Practical_Chemistry_Teaching-master/progs/metadise.exe', cwd='H:/Third_year_lab/Advanced_Practical_Chemistry_Teaching-master/course/week_2/Input/')\nos.rename('Input/control_o0001.dlp', 'Input/CONTROL')\nos.rename('Input/config__o0001.dlp', 'Input/CONFIG')\nos.rename('Input/field___o0001.dlp', 'Input/FIELD')\n```\n\nNow you should have a CONFIG, CONTROL and FIELD file within the input directory. In theory you could just call the DL_POLY program on this directory and your simulation would run. However we need to tweak the CONTROL file in order to set up our desired simulation. Make a new subdirectory in the week 2 directory named \"Example\" and copy CONFIG, CONTROL and FIELD to that subdirectory. Now edit the CONTROL file.  \n\nWe want to change the following   \n\n`Temperature 300 ---> Temperature 1500`  \n`Steps 5001 ---> Steps 40000`  \n`ensemble nve ---> ensemble npt hoover 0.1 0.5`  \n`trajectory nstraj= 1    istraj=   250 keytrj=0 ---> trajectory nstraj= 0    istraj= 100  keytrj=0`  \n  \nNow your simulation is ready. As a point of interest it is always good to check your structure before and after the simulation. You can view the CONFIG file in three dimensions using the VESTA program. It is available for free at http://www.jp-minerals.org/vesta/en/download.html . Download it and use it to view your CONFIG, a demonstrator can help if necessary. VESTA can generate nice pictures which will look very good in a lab report. \n\n<center>\n    <br>\n    \n    <i>Figure 1. Fluorite Ca$F_2$ unit cell visualised in VESTA.</i>\n    <br>\n</center>\n\n\nTo run DL_POLY from within a notebook use the below command. Keep in mind that this simulation will take 20 or so minutes so be patient. \n\n\n```python\nsubprocess.call('H:/Third_year_lab/Advanced_Practical_Chemistry_Teaching-master/progs/dlpoly_classic.exe', cwd='H:/Third_year_lab/Advanced_Practical_Chemistry_Teaching-master/course/week_2/Example/')\n```\n\n\n\n\n    0\n\n\n\nOnce DL_POLY has completed you will find several files relating to your simulaton. \n- HISTORY - This file contains the configuration of your system at each step during the simulation. You can view this as a movie using the VMD program - Ask a demonstrator for details\n- REVCON - This is the configuration at the end of the simulation - Can be viewed in VESTA - why not check to see how it has changed. \n- STATIS - Contains the stats at each step in the simulation. \n- OUTPUT - Contains properties \n\nIt is now important to understand how we can actually use the details of the simulation to get some information on the properties of the material, e.g. Diffusion coefficients and activation energies. \n\n## Mean Squared Displacements - Calculating diffusion coefficients\n\nAs we have seen molecules in liquds, gases and solids do not stay in the same place and move constantly. Think about a drop of dye in a glass of water, as time passes the dye distributes throughout the water. This process is called diffusion and is common throughout nature.  \n\nUsing the dye as an example, the motion of a dye molecule is not simple. As it moves it is jostled by collisions with other molecules, preventing it from moving in a straight path. If the path is examined in close detail, it will be seen to be a good approximation to a random walk. In mathmatics a random walk is a series of steps, each taken in a random direction. This was analysed by Albert Einstein in a study of Brownian motion and he showed that the mean square of the distance travelled by a particle following a random walk is proportional to the time elapsed. \n\\begin{align}\n\\Big \\langle r^2 \\big \\rangle & = 6 D_t + C \n\\end{align}\n\nwhere $\\Big \\langle r^2 \\big \\rangle$ is the mean squared distance, t is time, D is the diffusion rate and C is a constant. \n\n## What is the mean squared displacement\n\nGoing back to the example of the dye in water, lets assume for the sake of simplicity that we are in one dimension. Each step can either be forwards or backwards and we cannot predict which. From a given starting position, what distance is our dye molecule likely to travel after 1000 steps? This can be determined simply by adding together the steps, taking into account the fact that steps backwards subtract from the total, while steps forward add to the total. Since both forward and backward steps are equally probable, we come to the surprising conclusion that the probable distance travelled sums up to zero.\n\nBy adding the square of the distance we will always be adding positive numbers to our total which now increases linearly with time. Based upon equation 1 it should now be clear that a plot of $\\Big \\langle r^2 \\big \\rangle$ vs time with produce a line, the gradient of which is equal to 6D. Giving us direct access to the diffusion coefficient of the system. \n\nLets try explore this with an example. Run a short DL_POLY simulation on the input files provided. \n\nYou will a small MSD program called MSD.py to analyse your simulation results. First you need to read in the data, the HISTORY file contains a list of the atomic coordiantes held by the atoms during the simulation. \n\n\n```python\n# Read in the HISTORY file\n\n## Provide the path to the simulation and the atom that you want data for.\ndata = msd.read_history(\"Example/HISTORY\", \"F\")\n```\n\ndata is a dictionary variable containing the atomic trajectories, lattice vectors, total number of atoms, and total number of timesteps. \n\ndata = {'trajectories':trajectories, 'lv':lv, 'timesteps':timesteps, 'natoms':natoms}\n\nThe next step is to calculate the MSD. \n\n\n```python\n# Run the MSD calculation\nmsd_data = msd.run_msd(data)\n```\n\nrun_msd returns a dictionary containing the total MSD, the dimensional MSD values and the time. \nmsd_data = {'msd': msd, 'xmsd': xmsd, 'ymsd': ymsd, 'zmsd': zmsd, 'time': time}\n\nThis can then be plotted to give a nice linear relationship. \n\n\n```python\nplt.plot(msd_data['time'], msd_data['msd'], lw=2, color=\"red\", label=\"MSD\")\nplt.plot(msd_data['time'], msd_data['xmsd'], lw=2, color=\"blue\", label=\"X-MSD\")\nplt.plot(msd_data['time'], msd_data['ymsd'], lw=2, color=\"green\", label=\"Y-MSD\")\nplt.plot(msd_data['time'], msd_data['zmsd'], lw=2, color=\"black\", label=\"Z-MSD\")\n\nplt.ylabel(\"MSD (\" r'$\\AA$' \")\", fontsize=15)\nplt.xlabel(\"Time / ps\", fontsize=15)\nplt.ylim(0, np.amax(msd_data['msd']))\nplt.xlim(0, np.amax(msd_data['time']))\nplt.legend(loc=2, frameon=False)\nplt.show()\n```\n\nTo calculate the gradient we need to perform a linear regression on the data. \n\n\n```python\nslope, intercept, r_value, p_value, std_err = stats.linregress(msd_data['time'], msd_data['msd'])\n```\n\nThe gradient is equal to 6D (6 = dimensionality). So our final diffusion coefficient for the simulation is given by\n\n\n```python\ndiffusion_coefficient = (np.average(slope) / 6) \nprint(\"Diffusion Coefficient: \", diffusion_coefficient, \" X 10 ^-9 (m^-2)\")\n```\n\n    Diffusion Coefficient:  1.4550282026323467  X 10 ^-9 (m^-2)\n\n\n## Simulation Length\n\nIt is important to consider the lenght of your simulation (Number of steps). Create a new folder called \"Example_2\", copy the CONFIG, FIELD and CONTROL files from your previous simulation but this time change the number of steps to 10000. Now rerun the simulation.\n\n\n```python\nsubprocess.call('H:/Third_year_lab/Advanced_Practical_Chemistry_Teaching-master/progs/dlpoly_classic.exe', cwd='H:/Third_year_lab/Advanced_Practical_Chemistry_Teaching-master/course/week_2/Example_2/')\n```\n\n\n\n\n    0\n\n\n\n\n```python\ndata = msd.read_history(\"Example_2/HISTORY\", \"F\")\nmsd_data = msd.run_msd(data)\n\nplt.plot(msd_data['time'], msd_data['msd'], lw=2, color=\"red\", label=\"MSD\")\nplt.plot(msd_data['time'], msd_data['xmsd'], lw=2, color=\"blue\", label=\"X-MSD\")\nplt.plot(msd_data['time'], msd_data['ymsd'], lw=2, color=\"green\", label=\"Y-MSD\")\nplt.plot(msd_data['time'], msd_data['zmsd'], lw=2, color=\"black\", label=\"Z-MSD\")\n\nplt.ylabel(\"MSD (\" r'$\\AA$' \")\", fontsize=15)\nplt.xlabel(\"Time / ps\", fontsize=15)\nplt.ylim(0, np.amax(msd_data['msd']))\nplt.xlim(0, np.amax(msd_data['time']))\nplt.legend(loc=2, frameon=False)\nplt.show()\n```\n\n\n```python\nslope, intercept, r_value, p_value, std_err = stats.linregress(msd_data['time'], msd_data['msd'])\n\ndiffusion_coefficient = (np.average(slope) / 6) \nprint(\"Diffusion Coefficient: \", diffusion_coefficient, \" X 10 ^-9 (m^-2)\")\n```\n\n    Diffusion Coefficient:  1.3602930070828145  X 10 ^-9 (m^-2)\n\n\nYou will hopefully see that your MSD plot has become considerably less linear. This shows that your simulation has not run long enough and your results will be unrealiable. You will hopefully also see a change to the value of your diffusion coefficient.  The length of your simulation is something that you should keep in mind for the next 3 weeks. \n\n## Arrhenius\n\nThe next thing is to use the diffusion coefficients to calcaulte the activation energy for F diffusion. This rea=quires diffusion coefficients from a temperature range. Common sense and chemical intuition suggest that the higher the temperature, the faster a given chemical reaction will proceed. Quantitatively this relationship between the rate a reaction proceeds and its temperature is determined by the Arrhenius Equation. At higher temperatures, the probability that two molecules will collide is higher. This higher collision rate results in a higher kinetic energy, which has an effect on the activation energy of the reaction. The activation energy is the amount of energy required to ensure that a reaction happens.  \n  \n\\begin{align}\nk = A * e^{(-Ea / RT)}\n\\end{align}\n  \nwhere k is the rate coefficient, A is a constant, Ea is the activation energy, R is the universal gas constant, and T is the temperature (in kelvin).\n\n\n\n## Week 2 Exercise\n\nUsing what you have learned over the last 45 mins your task this week is to calculate the activation energy of F diffusion in Ca$F_2$. You will need to select a temperature range and carry out simulations at different temperatures within that range. \n#### Questions to answer\n- In what temperature range is Ca$F_2$ completely solid i.e. no diffusion?\n- In what range is fluorine essentially liquid i.e. fluorine diffusion with no calcium diffusion?\n- What is the melting temperature?\n- Plot an Arrhenius plot and determine the activation energies in temperature range - You will need to rearange the equation. \n\n\nYou are encouraged to split the work up within your group and to learn how to view the simulation \"movie\" using VMD (Ask a demonstrator). VMD is a fantastic program that allows you to visualise your simulation, included below is a video showing a short snippet of an MD simulation of Ca$F_2$. A single F atom has been highlighted to show that diffusion is occuring. \n\n\n```python\n%%HTML\n<div align=\"middle\">\n</div>\n```\n\n\n<div align=\"middle\">\n</div>\n\n\nFurthermore, VMD can also be used to generate images showing the entire trajectory of the simulation, e.g.\n\n\n\n<center>\n    <br>\n    \n    <i>Figure 2. A figure showing all positions occupied by F during an MD simulation at 1500 K. F positions are shown in orange and Ca atoms are shown in green.</i>\n    <br>\n</center>\n  \n\n  To save you the time you can use the function declared at the start of this notebook to pull out a diffusion coefficient directly from the simulation output file. MSD.py is a small code to allow visualisation of the MSD plot but it is not neccesary every time you want the diffusion coefficient. \n\nIt is up to you how you organise/create your directories but it is reccomended that you start a new notebook. Use the commands/functions used in this notebook to generate your input files, run DL_POLY and extract the diffusion coefficients. The write your own code to generate an Arrhenius plot and calculate the activation energies. \nIf you finish early then feel free to start week 3. \n", "meta": {"hexsha": "596a8fbb3a788fa05db03b207c2df625f1e85874", "size": 77833, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Week_2/.ipynb_checkpoints/Week_2-checkpoint.ipynb", "max_stars_repo_name": "symmy596/Bath_University_Advanced_Practical_Chemistry_Year_2", "max_stars_repo_head_hexsha": "65f846f87d97639f324c6f75f2ac0d1bedfb91d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Week_2/.ipynb_checkpoints/Week_2-checkpoint.ipynb", "max_issues_repo_name": "symmy596/Bath_University_Advanced_Practical_Chemistry_Year_2", "max_issues_repo_head_hexsha": "65f846f87d97639f324c6f75f2ac0d1bedfb91d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week_2/.ipynb_checkpoints/Week_2-checkpoint.ipynb", "max_forks_repo_name": "symmy596/Bath_University_Advanced_Practical_Chemistry_Year_2", "max_forks_repo_head_hexsha": "65f846f87d97639f324c6f75f2ac0d1bedfb91d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 158.5193482688, "max_line_length": 28644, "alphanum_fraction": 0.8761836239, "converted": true, "num_tokens": 3653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.058345841021027904, "lm_q1q2_score": 0.02689841171378269}}
{"text": "```python\n!pip install qiskit\n```\n\n    Collecting qiskit\n      Downloading https://files.pythonhosted.org/packages/6f/61/cb7506e17a2566dc8a31a3e1924d91ac0bdd8ff07c71ec698c06647b6306/qiskit-0.26.2.tar.gz\n    Collecting qiskit-terra==0.17.4\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/b3/0c/3c7a8dd451dae0907263e9de9e3e34909e15e18c88a589b44581972c8511/qiskit_terra-0.17.4-cp37-cp37m-manylinux2010_x86_64.whl (6.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.0MB 2.8MB/s \n    \u001b[?25hCollecting qiskit-aer==0.8.2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/c2/d2/6ff15c370b5465b32529b528bf3f4ce1e01f74498be16203aa1c04b67022/qiskit_aer-0.8.2-cp37-cp37m-manylinux2010_x86_64.whl (18.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 18.0MB 246kB/s \n    \u001b[?25hCollecting qiskit-ibmq-provider==0.13.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/be/99/74bbb901f88603a7d850d4889abc06d81ba702e4227151f4a5b66f2631fe/qiskit_ibmq_provider-0.13.1-py3-none-any.whl (228kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 235kB 42.0MB/s \n    \u001b[?25hCollecting qiskit-ignis==0.6.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/54/be/a13c828e457e09d979667a61bddbd8c7246aafa94e2501b6a9154429cbea/qiskit_ignis-0.6.0-py3-none-any.whl (207kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 215kB 41.1MB/s \n    \u001b[?25hCollecting qiskit-aqua==0.9.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/88/79/392c57b978decbb24b902344b536af52c40a751aed0ebbaefa8bc2964cb5/qiskit_aqua-0.9.1-py3-none-any.whl (2.1MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.1MB 34.8MB/s \n    \u001b[?25hRequirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (2.8.1)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (5.4.8)\n    Collecting fastjsonschema>=2.10\n      Downloading https://files.pythonhosted.org/packages/d1/fb/ea090e917b18320f79be31d754bbe496b715175e865603cfce1eaed2e774/fastjsonschema-2.15.1-py3-none-any.whl\n    Collecting ply>=3.10\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/a3/58/35da89ee790598a0700ea49b2a66594140f44dec458c07e8e3d4979137fc/ply-3.11-py2.py3-none-any.whl (49kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 6.3MB/s \n    \u001b[?25hRequirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (2.6.0)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (0.3.3)\n    Collecting retworkx>=0.8.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1b/92/f007f8b9d88dcd5b90e363967e5d54431a68c5fe06d83400732e3b438084/retworkx-0.8.0-cp37-cp37m-manylinux2010_x86_64.whl (1.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.0MB 35.6MB/s \n    \u001b[?25hRequirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (1.7.1)\n    Collecting python-constraint>=1.4\n      Downloading https://files.pythonhosted.org/packages/37/8b/5f1bc2734ca611943e1d6733ee244238679f6410a10cd45ede55a61a8402/python-constraint-1.4.0.tar.bz2\n    Requirement already satisfied: scipy>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (1.4.1)\n    Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (1.19.5)\n    Collecting pybind11>=2.6\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/8d/43/7339dbabbc2793718d59703aace4166f53c29ee1c202f6ff5bf8a26c4d91/pybind11-2.6.2-py2.py3-none-any.whl (191kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 194kB 47.8MB/s \n    \u001b[?25hRequirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit) (2.23.0)\n    Collecting requests-ntlm>=1.1.0\n      Downloading https://files.pythonhosted.org/packages/03/4b/8b9a1afde8072c4d5710d9fa91433d504325821b038e00237dc8d6d833dc/requests_ntlm-1.1.0-py2.py3-none-any.whl\n    Requirement already satisfied: nest-asyncio!=1.1.0,>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit) (1.5.1)\n    Collecting websockets>=8\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/84/64/78c2b3fe37730b30dca3c93d1f7f4a4286767f86e7c04cf3571b39bc2fb7/websockets-9.1-cp37-cp37m-manylinux2010_x86_64.whl (103kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 112kB 50.7MB/s \n    \u001b[?25hRequirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit) (1.24.3)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ignis==0.6.0->qiskit) (56.1.0)\n    Collecting dlx<=1.0.4\n      Downloading https://files.pythonhosted.org/packages/54/c0/b8fb5bb727e983b6f5251433ef941b48f38c65bb0bd6ec509e9185bcd406/dlx-1.0.4.tar.gz\n    Collecting quandl<=3.6.0\n      Downloading https://files.pythonhosted.org/packages/c2/58/9f0e69d836045e3865d263e9ed49f42b23a58526fdabb30f74c430baee3f/Quandl-3.6.0-py2.py3-none-any.whl\n    Requirement already satisfied: scikit-learn<=0.24.1,>=0.20.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (0.22.2.post1)\n    Collecting yfinance<=0.1.55\n      Downloading https://files.pythonhosted.org/packages/7a/e8/b9d7104d3a4bf39924799067592d9e59119fcfc900a425a12e80a3123ec8/yfinance-0.1.55.tar.gz\n    Requirement already satisfied: fastdtw<=0.3.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (0.3.4)\n    Requirement already satisfied: pandas<=1.2.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (1.1.5)\n    Collecting docplex<=2.20.204; sys_platform != \"darwin\"\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/87/99/6f7c219b39fd58c84688ad0713eb932bfcf6be81fc74519e43ea9c915b56/docplex-2.20.204.tar.gz (611kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 614kB 36.2MB/s \n    \u001b[?25hRequirement already satisfied: h5py<=3.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (3.1.0)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.8.0->qiskit-terra==0.17.4->qiskit) (1.15.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra==0.17.4->qiskit) (1.2.1)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit) (2020.12.5)\n    Collecting ntlm-auth>=1.0.2\n      Downloading https://files.pythonhosted.org/packages/ff/84/97c550164b54942b0e908c31ef09d9469f3ba4cd7332a671e2125732f63b/ntlm_auth-1.5.0-py2.py3-none-any.whl\n    Collecting cryptography>=1.3\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/b2/26/7af637e6a7e87258b963f1731c5982fb31cd507f0d90d91836e446955d02/cryptography-3.4.7-cp36-abi3-manylinux2014_x86_64.whl (3.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.2MB 27.3MB/s \n    \u001b[?25hRequirement already satisfied: more-itertools in /usr/local/lib/python3.7/dist-packages (from quandl<=3.6.0->qiskit-aqua==0.9.1->qiskit) (8.7.0)\n    Collecting inflection>=0.3.1\n      Downloading https://files.pythonhosted.org/packages/59/91/aa6bde563e0085a02a435aa99b49ef75b0a4b062635e606dab23ce18d720/inflection-0.5.1-py2.py3-none-any.whl\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn<=0.24.1,>=0.20.0->qiskit-aqua==0.9.1->qiskit) (1.0.1)\n    Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance<=0.1.55->qiskit-aqua==0.9.1->qiskit) (0.0.9)\n    Collecting lxml>=4.5.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/30/c0/d0526314971fc661b083ab135747dc68446a3022686da8c16d25fcf6ef07/lxml-4.6.3-cp37-cp37m-manylinux2014_x86_64.whl (6.3MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.3MB 30.2MB/s \n    \u001b[?25hRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas<=1.2.3->qiskit-aqua==0.9.1->qiskit) (2018.9)\n    Requirement already satisfied: cached-property; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from h5py<=3.1.0->qiskit-aqua==0.9.1->qiskit) (1.5.2)\n    Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit) (1.14.5)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit) (2.20)\n    Building wheels for collected packages: qiskit, python-constraint, dlx, yfinance, docplex\n      Building wheel for qiskit (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for qiskit: filename=qiskit-0.26.2-cp37-none-any.whl size=10491 sha256=4c9777ea47a1179a3ef2032714d406efc22601986d91079e5ab754c186cec162\n      Stored in directory: /root/.cache/pip/wheels/89/89/34/524839952d5a58a7be9789e580bfc1ca883bf6579152444568\n      Building wheel for python-constraint (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for python-constraint: filename=python_constraint-1.4.0-py2.py3-none-any.whl size=24079 sha256=4d6021d1c3044625952a4f3d13941fa70fc366a3fca94c17a139e16a421f3ef0\n      Stored in directory: /root/.cache/pip/wheels/34/31/15/7b070b25d0a549d20ce2e9fe6d727471c2c61ef904720fd40c\n      Building wheel for dlx (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for dlx: filename=dlx-1.0.4-cp37-none-any.whl size=5712 sha256=0c747ac3a816c7f566fc5e413f4323a2d6171e35523b0eab1417fa9f271ab9de\n      Stored in directory: /root/.cache/pip/wheels/bb/ba/15/fdd0deb104df3254912998150ba9245668db06b00af5912d1a\n      Building wheel for yfinance (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for yfinance: filename=yfinance-0.1.55-py2.py3-none-any.whl size=22616 sha256=58d254f8a73997cea5cc11d60c93af01927565167ff0ba2f2442d0037f823e5b\n      Stored in directory: /root/.cache/pip/wheels/04/98/cc/2702a4242d60bdc14f48b4557c427ded1fe92aedf257d4565c\n      Building wheel for docplex (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for docplex: filename=docplex-2.20.204-cp37-none-any.whl size=675362 sha256=e3e3560717a797eb15db1c32555d12e5c96e41fead51074967d1978ba8fc8e49\n      Stored in directory: /root/.cache/pip/wheels/ae/2c/e2/a099ebb6fda8adeba9c5fc2e25659d195ad2f5c6cc5fb75fd4\n    Successfully built qiskit python-constraint dlx yfinance docplex\n    Installing collected packages: fastjsonschema, ply, retworkx, python-constraint, qiskit-terra, pybind11, qiskit-aer, ntlm-auth, cryptography, requests-ntlm, websockets, qiskit-ibmq-provider, qiskit-ignis, dlx, inflection, quandl, lxml, yfinance, docplex, qiskit-aqua, qiskit\n      Found existing installation: lxml 4.2.6\n        Uninstalling lxml-4.2.6:\n          Successfully uninstalled lxml-4.2.6\n    Successfully installed cryptography-3.4.7 dlx-1.0.4 docplex-2.20.204 fastjsonschema-2.15.1 inflection-0.5.1 lxml-4.6.3 ntlm-auth-1.5.0 ply-3.11 pybind11-2.6.2 python-constraint-1.4.0 qiskit-0.26.2 qiskit-aer-0.8.2 qiskit-aqua-0.9.1 qiskit-ibmq-provider-0.13.1 qiskit-ignis-0.6.0 qiskit-terra-0.17.4 quandl-3.6.0 requests-ntlm-1.1.0 retworkx-0.8.0 websockets-9.1 yfinance-0.1.55\n\n\n\n```python\nfrom qiskit.providers.aer import QasmSimulator  \nfrom qiskit.providers.aer import AerSimulator\nfrom qiskit.circuit.library import TwoLocal\nfrom qiskit.algorithms import VQE\nfrom qiskit.algorithms.optimizers import COBYLA \nfrom qiskit.circuit.library import EfficientSU2\n# opflow is Qiskit's module for creating operators like yours\nfrom qiskit import *\nfrom qiskit.opflow import OperatorBase\nfrom qiskit.opflow import Z, X, I  # Pauli Z, X matrices and identity\nimport pylab\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n%matplotlib inline\n```\n\n\n```python\ncounts = []\nvalues = []\n\n\ndef store_intermediate_result(eval_count, parameters, mean, std):\n  counts.append(eval_count)\n  values.append(mean)\n```\n\n\n```python\ndef run(B_X = 1, J_z = 1, B_Z = 1):\n    master_counts = []\n    master_values = []\n    # for h in range (1,5,1): \n    #     h=+h\n\n    # Initialization\n    B_X = B_X\n    J_z = J_z\n    B_Z = B_Z\n\n    # or whatever value you have for h\n    #H = - B_X * ((X ^ I ^ I ^ I) + (I ^ X ^ I ^ I) + (I ^ I ^ X ^ I) + (I ^ I ^ I ^ X)) + J_z * ((Z ^ Z ^ I ^ I ) + (I ^ Z ^ Z ^ I) + (I ^ I ^ Z ^ Z) + (Z ^ I ^ I ^ Z)) - B_Z * ((Z ^ I ^ I ^ I) + (I ^ Z ^ I ^ I) + (I ^ I ^ Z ^ I ) + (I ^ I ^ I ^ Z))\n   \n\n    # for 25 qubits\n    H = - B_Z * (( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z)\n    ) + J_z * ((( Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z) + ( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z))) \n    - B_X * (( X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X)\n    )\n\n    # you can swap this for a real quantum device and keep the rest of the code the same!\n    backend = QasmSimulator() \n\n    # COBYLA usually works well for small problems like this one\n    optimizer = COBYLA(maxiter=200)\n\n    # EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library\n    #ansatz = EfficientSU2(4, reps=1)\n\n    # for 25 qubits\n    # ansatz = EfficientSU2(25, reps=1)\n    ansatz = TwoLocal(num_qubits=25, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True)\n\n    # set the algorithm\n    vqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result)\n\n    # run it with the Hamiltonian we defined above\n    result = vqe.compute_minimum_eigenvalue(H)  \n\n    # print the result (it contains lot's of information)\n    return result\n\n```\n\n\n```python\nresult = run()\nprint(result)\n```\n\n\n```python\nprint(result.optimal_value)\nprint(result.eigenvalue)\n```\n\n\n```python\ncounts_values = {}\n\nfor i in range(0, 20, 1):\n    for j in range(0, 20, 1):\n        print(f\"Running VQE for BX : {i/10} & BZ : {j/10}, \\t\\t Optimal Value : {result.optimal_value}\")\n        counts = []\n        values = []\n        result = run(B_X = i/10, J_z = 1, B_Z = j/10)\n        # counts_values[f\"BX_{i/10} BZ_{j/10}\"] = {\"counts\": counts, \"values\": values} \n        counts_values[f\"BX_{i/10} BZ_{j/10}\"] = {'result': result} \n```\n\n\n```python\nimport pickle\n\n\nprint(\"Saving Optimization History\")\nwith open('optimization_data.pickle', 'wb') as handle:\n    pickle.dump(counts_values, handle, protocol=pickle.HIGHEST_PROTOCOL)\n```\n\n\n```python\nprint(\"Loading Optimization History\")\n\nwith open('optimization_data.pickle', 'rb') as handle:\n    counts_values = pickle.load(handle)\n```\n\n\n```python\narr = []\nfor i in range(0, 20, 1):\n    r = []\n    for j in range(0, 20, 1):\n        cv = counts_values[f\"BX_{i/10} BZ_{j/10}\"]['result']\n        r += [cv.optimal_value]\n    arr += [r]\ndata = np.asarray(arr)\ndata.shape\n```\n\n\n```python\nX = np.asarray([ x for x in range(0, 20, 1) ])\nY = np.asarray([ y for y in range(-10, 10, 1) ])\nZ = data\n```\n\n\n```python\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pylab as plt\n\nplt.imshow(Z, cmap='hot', interpolation='nearest')\nplt.colorbar()\nplt.show()\n```\n\n\n```python\nimport numpy\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nnx, ny = 20, 20\nx = range(nx)\ny = range(ny)\n\nhf = plt.figure()\nha = hf.add_subplot(111, projection='3d')\n\nX, Y = numpy.meshgrid(x, y)\nha.plot_surface(X, Y, Z)\n\nplt.show()\n```\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d.axes3d import Axes3D\n\nx = np.arange(0,20)\ny = np.arange(0,20)\n\nxs, ys = np.meshgrid(x, y)\n\nfig = plt.figure()\nax = Axes3D(fig)\nax.plot_surface(xs, ys, Z, rstride=1, cstride=1, cmap='hot')\nplt.show()\n```\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import axes3d\n# if using a Jupyter notebook, include:\n%matplotlib inline\n\n\nfig = plt.figure(figsize=(12, 6))\nax1 = fig.add_subplot(121, projection='3d')\nax2 = fig.add_subplot(122, projection='3d')\n\nx = np.arange(0,20)\ny = np.arange(0,20)\nX,Y = np.meshgrid(x,y)\n\n\n# Plot a basic wireframe\nax1.plot_wireframe(Y, X, Z, rstride=10, cstride=10, cmap='hot')\nax1.set_title('row step size 10, column step size 10')\n\nax2.plot_wireframe(Y, X, Z, rstride=20, cstride=20, cmap='hot')\nax2.set_title('row step size 20, column step size 20')\n\nplt.show()\n\n```\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import axes3d\nfrom matplotlib import cm\n\n# if using a Jupyter notebook, include:\n%matplotlib inline\n\n\nfig = plt.figure(figsize=(12, 4))\nax1 = fig.add_subplot(121, projection='3d')\nax2 = fig.add_subplot(122, projection='3d')\n\nx = np.arange(0,20)\ny = np.arange(0,20)\nX,Y = np.meshgrid(x,y)\n\n\n# Plot a basic wireframe\nax1.plot_surface(X, Y, Z, rstride=5, cstride=5, cmap='hot')\n\nax2.plot_surface(Y, X, Z, rstride=5, cstride=5, cmap='hot')\nax2.contourf(Y, X, Z, zdir='z', offset=np.min(Z), cmap=cm.ocean)\n\n\nplt.show()\n\n```\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import axes3d\nfrom matplotlib import cm\n\n# if using a Jupyter notebook, include:\n%matplotlib inline\n\n\nfig = plt.figure(figsize=(12, 4))\nax1 = fig.add_subplot(121, projection='3d')\nax2 = fig.add_subplot(122, projection='3d')\n\nx = np.arange(0,20)\ny = np.arange(0,20)\nX,Y = np.meshgrid(x,y)\n\n\n# Plot a basic wireframe\nax1.plot_surface(X, Y, Z, rstride=5, cstride=5, cmap='hot')\n\nax2.plot_surface(Y, X, Z, rstride=5, cstride=5, cmap='hot')\n\nplt.show()\n\n```\n\n\n```python\n# HAMILTONIAN FOR 25 QUBITS\n\n# H = - B_Z * (( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z)\n# ) + J_z * ((( Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z) + ( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z))) \n# - B_X * (( X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X)\n# )\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "9e51f790b07be92f29af60a605d8dc7923d2ffc4", "size": 41341, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "research/notebooks/1D/Ising_Charting.ipynb", "max_stars_repo_name": "arnavdas88/QuGlassyIsing", "max_stars_repo_head_hexsha": "6b6514d58646130c03619aebefb9f9aed4e5646a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-19T16:06:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T17:03:31.000Z", "max_issues_repo_path": "research/rough-work-misc/Ising_Charting.ipynb", "max_issues_repo_name": "IshmamShah/QuGlassyIsing", "max_issues_repo_head_hexsha": "6c3ff2ebd77ed9b34a0e731083f1e56b7eacb7ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "research/rough-work-misc/Ising_Charting.ipynb", "max_forks_repo_name": "IshmamShah/QuGlassyIsing", "max_forks_repo_head_hexsha": "6c3ff2ebd77ed9b34a0e731083f1e56b7eacb7ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-19T16:06:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T06:51:18.000Z", "avg_line_length": 76.415896488, "max_line_length": 2604, "alphanum_fraction": 0.4433855011, "converted": true, "num_tokens": 14459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936413143782797, "lm_q2_score": 0.074770045485098, "lm_q1q2_score": 0.026869672453319133}}
{"text": "```python\n%matplotlib inline\n```\n\n\n`Introduction <introyt1_tutorial.html>`_ ||\n`Tensors <tensors_deeper_tutorial.html>`_ ||\n**Autograd** ||\n`Building Models <modelsyt_tutorial.html>`_ ||\n`TensorBoard Support <tensorboardyt_tutorial.html>`_ ||\n`Training Models <trainingyt.html>`_ ||\n`Model Understanding <captumyt.html>`_\n\nThe Fundamentals of Autograd\n============================\n\nFollow along with the video below or on `youtube <https://www.youtube.com/watch?v=M0fX15_-xrY>`__.\n\n.. raw:: html\n\n   <div style=\"margin-top:10px; margin-bottom:10px;\">\n     \n   </div>\n\nPyTorch\u2019s *Autograd* feature is part of what make PyTorch flexible and\nfast for building machine learning projects. It allows for the rapid and\neasy computation of multiple partial derivatives (also referred to as\n*gradients)* over a complex computation. This operation is central to\nbackpropagation-based neural network learning.\n\nThe power of autograd comes from the fact that it traces your\ncomputation dynamically *at runtime,* meaning that if your model has\ndecision branches, or loops whose lengths are not known until runtime,\nthe computation will still be traced correctly, and you\u2019ll get correct\ngradients to drive learning. This, combined with the fact that your\nmodels are built in Python, offers far more flexibility than frameworks\nthat rely on static analysis of a more rigidly-structured model for\ncomputing gradients.\n\nWhat Do We Need Autograd For?\n-----------------------------\n\n\nA machine learning model is a *function*, with inputs and outputs. For\nthis discussion, we\u2019ll treat the inputs a as an *i*-dimensional vector\n$\\vec{x}$, with elements $x_{i}$. We can then express the\nmodel, *M*, as a vector-valued function of the input: $\\vec{y} =\n\\vec{M}(\\vec{x})$. (We treat the value of M\u2019s output as\na vector because in general, a model may have any number of outputs.)\n\nSince we\u2019ll mostly be discussing autograd in the context of training,\nour output of interest will be the model\u2019s loss. The *loss function*\nL($\\vec{y}$) = L($\\vec{M}$\\ ($\\vec{x}$)) is a\nsingle-valued scalar function of the model\u2019s output. This function\nexpresses how far off our model\u2019s prediction was from a particular\ninput\u2019s *ideal* output. *Note: After this point, we will often omit the\nvector sign where it should be contextually clear - e.g.,* $y$\ninstead of $\\vec y$.\n\nIn training a model, we want to minimize the loss. In the idealized case\nof a perfect model, that means adjusting its learning weights - that is,\nthe adjustable parameters of the function - such that loss is zero for\nall inputs. In the real world, it means an iterative process of nudging\nthe learning weights until we see that we get a tolerable loss for a\nwide variety of inputs.\n\nHow do we decide how far and in which direction to nudge the weights? We\nwant to *minimize* the loss, which means making its first derivative\nwith respect to the input equal to 0:\n$\\frac{\\partial L}{\\partial x} = 0$.\n\nRecall, though, that the loss is not *directly* derived from the input,\nbut a function of the model\u2019s output (which is a function of the input\ndirectly), $\\frac{\\partial L}{\\partial x}$ =\n$\\frac{\\partial {L({\\vec y})}}{\\partial x}$. By the chain rule of\ndifferential calculus, we have\n$\\frac{\\partial {L({\\vec y})}}{\\partial x}$ =\n$\\frac{\\partial L}{\\partial y}\\frac{\\partial y}{\\partial x}$ =\n$\\frac{\\partial L}{\\partial y}\\frac{\\partial M(x)}{\\partial x}$.\n\n$\\frac{\\partial M(x)}{\\partial x}$ is where things get complex.\nThe partial derivatives of the model\u2019s outputs with respect to its\ninputs, if we were to expand the expression using the chain rule again,\nwould involve many local partial derivatives over every multiplied\nlearning weight, every activation function, and every other mathematical\ntransformation in the model. The full expression for each such partial\nderivative is the sum of the products of the local gradient of *every\npossible path* through the computation graph that ends with the variable\nwhose gradient we are trying to measure.\n\nIn particular, the gradients over the learning weights are of interest\nto us - they tell us *what direction to change each weight* to get the\nloss function closer to zero.\n\nSince the number of such local derivatives (each corresponding to a\nseparate path through the model\u2019s computation graph) will tend to go up\nexponentially with the depth of a neural network, so does the complexity\nin computing them. This is where autograd comes in: It tracks the\nhistory of every computation. Every computed tensor in your PyTorch\nmodel carries a history of its input tensors and the function used to\ncreate it. Combined with the fact that PyTorch functions meant to act on\ntensors each have a built-in implementation for computing their own\nderivatives, this greatly speeds the computation of the local\nderivatives needed for learning.\n\nA Simple Example\n----------------\n\nThat was a lot of theory - but what does it look like to use autograd in\npractice?\n\nLet\u2019s start with a straightforward example. First, we\u2019ll do some imports\nto let us graph our results:\n\n\n\n\n\n```python\n# %matplotlib inline\n\nimport torch\n\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nimport math\n```\n\nNext, we\u2019ll create an input tensor full of evenly spaced values on the\ninterval $[0, 2{\\pi}]$, and specify ``requires_grad=True``. (Like\nmost functions that create tensors, ``torch.linspace()`` accepts an\noptional ``requires_grad`` option.) Setting this flag means that in\nevery computation that follows, autograd will be accumulating the\nhistory of the computation in the output tensors of that computation.\n\n\n\n\n\n```python\na = torch.linspace(0., 2. * math.pi, steps=25, requires_grad=True)\nprint(a)\n```\n\nNext, we\u2019ll perform a computation, and plot its output in terms of its\ninputs:\n\n\n\n\n\n```python\nb = torch.sin(a)\nplt.plot(a.detach(), b.detach())\n```\n\nLet\u2019s have a closer look at the tensor ``b``. When we print it, we see\nan indicator that it is tracking its computation history:\n\n\n\n\n\n```python\nprint(b)\n```\n\nThis ``grad_fn`` gives us a hint that when we execute the\nbackpropagation step and compute gradients, we\u2019ll need to compute the\nderivative of $sin(x)$ for all this tensor\u2019s inputs.\n\nLet\u2019s perform some more computations:\n\n\n\n\n\n```python\nc = 2 * b\nprint(c)\n\nd = c + 1\nprint(d)\n```\n\nFinally, let\u2019s compute a single-element output. When you call\n``.backward()`` on a tensor with no arguments, it expects the calling\ntensor to contain only a single element, as is the case when computing a\nloss function.\n\n\n\n\n\n```python\nout = d.sum()\nprint(out)\n```\n\nEach ``grad_fn`` stored with our tensors allows you to walk the\ncomputation all the way back to its inputs with its ``next_functions``\nproperty. We can see below that drilling down on this property on ``d``\nshows us the gradient functions for all the prior tensors. Note that\n``a.grad_fn`` is reported as ``None``, indicating that this was an input\nto the function with no history of its own.\n\n\n\n\n\n```python\nprint('d:')\nprint(d.grad_fn)\nprint(d.grad_fn.next_functions)\nprint(d.grad_fn.next_functions[0][0].next_functions)\nprint(d.grad_fn.next_functions[0][0].next_functions[0][0].next_functions)\nprint(d.grad_fn.next_functions[0][0].next_functions[0][0].next_functions[0][0].next_functions)\nprint('\\nc:')\nprint(c.grad_fn)\nprint('\\nb:')\nprint(b.grad_fn)\nprint('\\na:')\nprint(a.grad_fn)\n```\n\nWith all this machinery in place, how do we get derivatives out? You\ncall the ``backward()`` method on the output, and check the input\u2019s\n``grad`` property to inspect the gradients:\n\n\n\n\n\n```python\nout.backward()\nprint(a.grad)\nplt.plot(a.detach(), a.grad.detach())\n```\n\nRecall the computation steps we took to get here:\n\n::\n\n   a = torch.linspace(0., 2. * math.pi, steps=25, requires_grad=True)\n   b = torch.sin(a)\n   c = 2 * b\n   d = c + 1\n   out = d.sum()\n\nAdding a constant, as we did to compute ``d``, does not change the\nderivative. That leaves $c = 2 * b = 2 * sin(a)$, the derivative\nof which should be $2 * cos(a)$. Looking at the graph above,\nthat\u2019s just what we see.\n\nBe aware than only *leaf nodes* of the computation have their gradients\ncomputed. If you tried, for example, ``print(c.grad)`` you\u2019d get back\n``None``. In this simple example, only the input is a leaf node, so only\nit has gradients computed.\n\nAutograd in Training\n--------------------\n\nWe\u2019ve had a brief look at how autograd works, but how does it look when\nit\u2019s used for its intended purpose? Let\u2019s define a small model and\nexamine how it changes after a single training batch. First, define a\nfew constants, our model, and some stand-ins for inputs and outputs:\n\n\n\n\n\n```python\nBATCH_SIZE = 16\nDIM_IN = 1000\nHIDDEN_SIZE = 100\nDIM_OUT = 10\n\nclass TinyModel(torch.nn.Module):\n\n    def __init__(self):\n        super(TinyModel, self).__init__()\n        \n        self.layer1 = torch.nn.Linear(1000, 100)\n        self.relu = torch.nn.ReLU()\n        self.layer2 = torch.nn.Linear(100, 10)\n    \n    def forward(self, x):\n        x = self.layer1(x)\n        x = self.relu(x)\n        x = self.layer2(x)\n        return x\n    \nsome_input = torch.randn(BATCH_SIZE, DIM_IN, requires_grad=False)\nideal_output = torch.randn(BATCH_SIZE, DIM_OUT, requires_grad=False)\n\nmodel = TinyModel()\n```\n\nOne thing you might notice is that we never specify\n``requires_grad=True`` for the model\u2019s layers. Within a subclass of\n``torch.nn.Module``, it\u2019s assumed that we want to track gradients on the\nlayers\u2019 weights for learning.\n\nIf we look at the layers of the model, we can examine the values of the\nweights, and verify that no gradients have been computed yet:\n\n\n\n\n\n```python\nprint(model.layer2.weight[0][0:10]) # just a small slice\nprint(model.layer2.weight.grad)\n```\n\nLet\u2019s see how this changes when we run through one training batch. For a\nloss function, we\u2019ll just use the square of the Euclidean distance\nbetween our ``prediction`` and the ``ideal_output``, and we\u2019ll use a\nbasic stochastic gradient descent optimizer.\n\n\n\n\n\n```python\noptimizer = torch.optim.SGD(model.parameters(), lr=0.001)\n\nprediction = model(some_input)\n\nloss = (ideal_output - prediction).pow(2).sum()\nprint(loss)\n```\n\nNow, let\u2019s call ``loss.backward()`` and see what happens:\n\n\n\n\n\n```python\nloss.backward()\nprint(model.layer2.weight[0][0:10])\nprint(model.layer2.weight.grad[0][0:10])\n```\n\nWe can see that the gradients have been computed for each learning\nweight, but the weights remain unchanged, because we haven\u2019t run the\noptimizer yet. The optimizer is responsible for updating model weights\nbased on the computed gradients.\n\n\n\n\n\n```python\noptimizer.step()\nprint(model.layer2.weight[0][0:10])\nprint(model.layer2.weight.grad[0][0:10])\n```\n\nYou should see that ``layer2``\\ \u2019s weights have changed.\n\nOne important thing about the process: After calling\n``optimizer.step()``, you need to call ``optimizer.zero_grad()``, or\nelse every time you run ``loss.backward()``, the gradients on the\nlearning weights will accumulate:\n\n\n\n\n\n```python\nprint(model.layer2.weight.grad[0][0:10])\n\nfor i in range(0, 5):\n    prediction = model(some_input)\n    loss = (ideal_output - prediction).pow(2).sum()\n    loss.backward()\n    \nprint(model.layer2.weight.grad[0][0:10])\n\noptimizer.zero_grad()\n\nprint(model.layer2.weight.grad[0][0:10])\n```\n\nAfter running the cell above, you should see that after running\n``loss.backward()`` multiple times, the magnitudes of most of the\ngradients will be much larger. Failing to zero the gradients before\nrunning your next training batch will cause the gradients to blow up in\nthis manner, causing incorrect and unpredictable learning results.\n\nTurning Autograd Off and On\n---------------------------\n\nThere are situations where you will need fine-grained control over\nwhether autograd is enabled. There are multiple ways to do this,\ndepending on the situation.\n\nThe simplest is to change the ``requires_grad`` flag on a tensor\ndirectly:\n\n\n\n\n\n```python\na = torch.ones(2, 3, requires_grad=True)\nprint(a)\n\nb1 = 2 * a\nprint(b1)\n\na.requires_grad = False\nb2 = 2 * a\nprint(b2)\n```\n\nIn the cell above, we see that ``b1`` has a ``grad_fn`` (i.e., a traced\ncomputation history), which is what we expect, since it was derived from\na tensor, ``a``, that had autograd turned on. When we turn off autograd\nexplicitly with ``a.requires_grad = False``, computation history is no\nlonger tracked, as we see when we compute ``b2``.\n\nIf you only need autograd turned off temporarily, a better way is to use\nthe ``torch.no_grad()``:\n\n\n\n\n\n```python\na = torch.ones(2, 3, requires_grad=True) * 2\nb = torch.ones(2, 3, requires_grad=True) * 3\n\nc1 = a + b\nprint(c1)\n\nwith torch.no_grad():\n    c2 = a + b\n\nprint(c2)\n\nc3 = a * b\nprint(c3)\n```\n\n``torch.no_grad()`` can also be used as a function or method dectorator:\n\n\n\n\n\n```python\ndef add_tensors1(x, y):\n    return x + y\n\n@torch.no_grad()\ndef add_tensors2(x, y):\n    return x + y\n\n\na = torch.ones(2, 3, requires_grad=True) * 2\nb = torch.ones(2, 3, requires_grad=True) * 3\n\nc1 = add_tensors1(a, b)\nprint(c1)\n\nc2 = add_tensors2(a, b)\nprint(c2)\n```\n\nThere\u2019s a corresponding context manager, ``torch.enable_grad()``, for\nturning autograd on when it isn\u2019t already. It may also be used as a\ndecorator.\n\nFinally, you may have a tensor that requires gradient tracking, but you\nwant a copy that does not. For this we have the ``Tensor`` object\u2019s\n``detach()`` method - it creates a copy of the tensor that is *detached*\nfrom the computation history:\n\n\n\n\n\n```python\nx = torch.rand(5, requires_grad=True)\ny = x.detach()\n\nprint(x)\nprint(y)\n```\n\nWe did this above when we wanted to graph some of our tensors. This is\nbecause ``matplotlib`` expects a NumPy array as input, and the implicit\nconversion from a PyTorch tensor to a NumPy array is not enabled for\ntensors with requires_grad=True. Making a detached copy lets us move\nforward.\n\nAutograd and In-place Operations\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIn every example in this notebook so far, we\u2019ve used variables to\ncapture the intermediate values of a computation. Autograd needs these\nintermediate values to perform gradient computations. *For this reason,\nyou must be careful about using in-place operations when using\nautograd.* Doing so can destroy information you need to compute\nderivatives in the ``backward()`` call. PyTorch will even stop you if\nyou attempt an in-place operation on leaf variable that requires\nautograd, as shown below.\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>The following code cell throws a runtime error. This is expected.</p></div>\n\n::\n\n   a = torch.linspace(0., 2. * math.pi, steps=25, requires_grad=True)\n   torch.sin_(a)\n\n\n\n\nAutograd Profiler\n-----------------\n\nAutograd tracks every step of your computation in detail. Such a\ncomputation history, combined with timing information, would make a\nhandy profiler - and autograd has that feature baked in. Here\u2019s a quick\nexample usage:\n\n\n\n\n\n```python\ndevice = torch.device('cpu')\nrun_on_gpu = False\nif torch.cuda.is_available():\n    device = torch.device('cuda')\n    run_on_gpu = True\n    \nx = torch.randn(2, 3, requires_grad=True)\ny = torch.rand(2, 3, requires_grad=True)\nz = torch.ones(2, 3, requires_grad=True)\n\nwith torch.autograd.profiler.profile(use_cuda=run_on_gpu) as prf:\n    for _ in range(1000):\n        z = (z / x) * y\n        \nprint(prf.key_averages().table(sort_by='self_cpu_time_total'))\n```\n\nThe profiler can also label individual sub-blocks of code, break out the\ndata by input tensor shape, and export data as a Chrome tracing tools\nfile. For full details of the API, see the\n`documentation <https://pytorch.org/docs/stable/autograd.html#profiler>`__.\n\nAdvanced Topic: More Autograd Detail and the High-Level API\n-----------------------------------------------------------\n\nIf you have a function with an n-dimensional input and m-dimensional\noutput, $\\vec{y}=f(\\vec{x})$, the complete gradient is a matrix of\nthe derivative of every output with respect to every input, called the\n*Jacobian:*\n\n\\begin{align}J\n     =\n     \\left(\\begin{array}{ccc}\n     \\frac{\\partial y_{1}}{\\partial x_{1}} & \\cdots & \\frac{\\partial y_{1}}{\\partial x_{n}}\\\\\n     \\vdots & \\ddots & \\vdots\\\\\n     \\frac{\\partial y_{m}}{\\partial x_{1}} & \\cdots & \\frac{\\partial y_{m}}{\\partial x_{n}}\n     \\end{array}\\right)\\end{align}\n\nIf you have a second function, $l=g\\left(\\vec{y}\\right)$ that\ntakes m-dimensional input (that is, the same dimensionality as the\noutput above), and returns a scalar output, you can express its\ngradients with respect to $\\vec{y}$ as a column vector,\n$v=\\left(\\begin{array}{ccc}\\frac{\\partial l}{\\partial y_{1}} & \\cdots & \\frac{\\partial l}{\\partial y_{m}}\\end{array}\\right)^{T}$\n- which is really just a one-column Jacobian.\n\nMore concretely, imagine the first function as your PyTorch model (with\npotentially many inputs and many outputs) and the second function as a\nloss function (with the model\u2019s output as input, and the loss value as\nthe scalar output).\n\nIf we multiply the first function\u2019s Jacobian by the gradient of the\nsecond function, and apply the chain rule, we get:\n\n\\begin{align}J^{T}\\cdot v=\\left(\\begin{array}{ccc}\n   \\frac{\\partial y_{1}}{\\partial x_{1}} & \\cdots & \\frac{\\partial y_{m}}{\\partial x_{1}}\\\\\n   \\vdots & \\ddots & \\vdots\\\\\n   \\frac{\\partial y_{1}}{\\partial x_{n}} & \\cdots & \\frac{\\partial y_{m}}{\\partial x_{n}}\n   \\end{array}\\right)\\left(\\begin{array}{c}\n   \\frac{\\partial l}{\\partial y_{1}}\\\\\n   \\vdots\\\\\n   \\frac{\\partial l}{\\partial y_{m}}\n   \\end{array}\\right)=\\left(\\begin{array}{c}\n   \\frac{\\partial l}{\\partial x_{1}}\\\\\n   \\vdots\\\\\n   \\frac{\\partial l}{\\partial x_{n}}\n   \\end{array}\\right)\\end{align}\n\nNote: You could also use the equivalent operation $v^{T}\\cdot J$,\nand get back a row vector.\n\nThe resulting column vector is the *gradient of the second function with\nrespect to the inputs of the first* - or in the case of our model and\nloss function, the gradient of the loss with respect to the model\ninputs.\n\n**``torch.autograd`` is an engine for computing these products.** This\nis how we accumulate the gradients over the learning weights during the\nbackward pass.\n\nFor this reason, the ``backward()`` call can *also* take an optional\nvector input. This vector represents a set of gradients over the tensor,\nwhich are multiplied by the Jacobian of the autograd-traced tensor that\nprecedes it. Let\u2019s try a specific example with a small vector:\n\n\n\n\n\n```python\nx = torch.randn(3, requires_grad=True)\n\ny = x * 2\nwhile y.data.norm() < 1000:\n    y = y * 2\n\nprint(y)\n```\n\nIf we tried to call ``y.backward()`` now, we\u2019d get a runtime error and a\nmessage that gradients can only be *implicitly* computed for scalar\noutputs. For a multi-dimensional output, autograd expects us to provide\ngradients for those three outputs that it can multiply into the\nJacobian:\n\n\n\n\n\n```python\nv = torch.tensor([0.1, 1.0, 0.0001], dtype=torch.float) # stand-in for gradients\ny.backward(v)\n\nprint(x.grad)\n```\n\n(Note that the output gradients are all related to powers of two - which\nwe\u2019d expect from a repeated doubling operation.)\n\nThe High-Level API\n~~~~~~~~~~~~~~~~~~\n\nThere is an API on autograd that gives you direct access to important\ndifferential matrix and vector operations. In particular, it allows you\nto calculate the Jacobian and the *Hessian* matrices of a particular\nfunction for particular inputs. (The Hessian is like the Jacobian, but\nexpresses all partial *second* derivatives.) It also provides methods\nfor taking vector products with these matrices.\n\nLet\u2019s take the Jacobian of a simple function, evaluated for a 2\nsingle-element inputs:\n\n\n\n\n\n```python\ndef exp_adder(x, y):\n    return 2 * x.exp() + 3 * y\n\ninputs = (torch.rand(1), torch.rand(1)) # arguments for the function\nprint(inputs)\ntorch.autograd.functional.jacobian(exp_adder, inputs)\n```\n\nIf you look closely, the first output should equal $2e^x$ (since\nthe derivative of $e^x$ is $e^x$), and the second value\nshould be 3.\n\nYou can, of course, do this with higher-order tensors:\n\n\n\n\n\n```python\ninputs = (torch.rand(3), torch.rand(3)) # arguments for the function\nprint(inputs)\ntorch.autograd.functional.jacobian(exp_adder, inputs)\n```\n\nThe ``torch.autograd.functional.hessian()`` method works identically\n(assuming your function is twice differentiable), but returns a matrix\nof all second derivatives.\n\nThere is also a function to directly compute the vector-Jacobian\nproduct, if you provide the vector:\n\n\n\n\n\n```python\ndef do_some_doubling(x):\n    y = x * 2\n    while y.data.norm() < 1000:\n        y = y * 2\n    return y\n\ninputs = torch.randn(3)\nmy_gradients = torch.tensor([0.1, 1.0, 0.0001])\ntorch.autograd.functional.vjp(do_some_doubling, inputs, v=my_gradients)\n```\n\nThe ``torch.autograd.functional.jvp()`` method performs the same matrix\nmultiplication as ``vjp()`` with the operands reversed. The ``vhp()``\nand ``hvp()`` methods do the same for a vector-Hessian product.\n\nFor more information, including preformance notes on the `docs for the\nfunctional\nAPI <https://pytorch.org/docs/stable/autograd.html#functional-higher-level-api>`__\n\n\n\n", "meta": {"hexsha": "4390d4718092d2f945c0fa6500f741f35126c987", "size": 29442, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/_downloads/3596f85660e82550243d872f522e0683/autogradyt_tutorial.ipynb", "max_stars_repo_name": "9bow/tutorials-kr", "max_stars_repo_head_hexsha": "ac5a82b90ca26c6202216b7003e51e9719eb8bc4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 44, "max_stars_repo_stars_event_min_datetime": "2021-12-07T14:51:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:34:17.000Z", "max_issues_repo_path": "docs/_downloads/3596f85660e82550243d872f522e0683/autogradyt_tutorial.ipynb", "max_issues_repo_name": "9bow/tutorials-kr", "max_issues_repo_head_hexsha": "ac5a82b90ca26c6202216b7003e51e9719eb8bc4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 128, "max_issues_repo_issues_event_min_datetime": "2021-12-02T18:11:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T05:16:39.000Z", "max_forks_repo_path": "docs/_downloads/3596f85660e82550243d872f522e0683/autogradyt_tutorial.ipynb", "max_forks_repo_name": "9bow/tutorials-kr", "max_forks_repo_head_hexsha": "ac5a82b90ca26c6202216b7003e51e9719eb8bc4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2021-12-02T18:56:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T07:18:23.000Z", "avg_line_length": 60.2085889571, "max_line_length": 3758, "alphanum_fraction": 0.6321581414, "converted": true, "num_tokens": 5308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771241500058, "lm_q2_score": 0.07921033226026339, "lm_q1q2_score": 0.026779201333516276}}
{"text": "# Analyzing, Visualizing & Classifying Fake & Real News Data with Logistic Regression\n\nIn this project, we aim to analyze and visualize news data before predicting whether the article is fake or real news. We will be using Logistic Regression for classification purposes since it's good at text-classifying. Data used can be found [here](https://www.kaggle.com/clmentbisaillon/fake-and-real-news-dataset).\n\nThe data is split into two datasets, containing 44898 articles in total. The columns include:\n\n* title: Contains the title of each article.\n* text: Contains the context of each article.\n* subject: Contains the subject of each article.\n* date: Contains the date each article was posted in a Month DD, YYYY format.\n\n## 1. Reading the data in\n\nWe will not be using the text column for this project. For other columns, we will be familiarizing ourselves with them in this step. Let's import, concatenate and explore the datasets.\n\n\n```python\nimport pandas as pd\nimport numpy as np\nimport re\nimport datetime as dt\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.feature_extraction.text import CountVectorizer\n\n%matplotlib inline\n\nwarnings.simplefilter(action='ignore', category=Warning)\npd.options.mode.chained_assignment = None\n```\n\n\n```python\nfake = pd.read_csv(\"Fake.csv\", usecols=[\"title\", \"subject\", \"date\"]).copy()\nreal = pd.read_csv(\"True.csv\", usecols=[\"title\", \"subject\", \"date\"]).copy()\n```\n\n\n```python\nfake[\"label\"] = \"fake\"\nreal[\"label\"] = \"real\"\nfake.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>title</th>\n      <th>subject</th>\n      <th>date</th>\n      <th>label</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Donald Trump Sends Out Embarrassing New Year\u2019...</td>\n      <td>News</td>\n      <td>December 31, 2017</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Drunk Bragging Trump Staffer Started Russian ...</td>\n      <td>News</td>\n      <td>December 31, 2017</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Sheriff David Clarke Becomes An Internet Joke...</td>\n      <td>News</td>\n      <td>December 30, 2017</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Trump Is So Obsessed He Even Has Obama\u2019s Name...</td>\n      <td>News</td>\n      <td>December 29, 2017</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Pope Francis Just Called Out Donald Trump Dur...</td>\n      <td>News</td>\n      <td>December 25, 2017</td>\n      <td>fake</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nreal.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>title</th>\n      <th>subject</th>\n      <th>date</th>\n      <th>label</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>As U.S. budget fight looms, Republicans flip t...</td>\n      <td>politicsNews</td>\n      <td>December 31, 2017</td>\n      <td>real</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>U.S. military to accept transgender recruits o...</td>\n      <td>politicsNews</td>\n      <td>December 29, 2017</td>\n      <td>real</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Senior U.S. Republican senator: 'Let Mr. Muell...</td>\n      <td>politicsNews</td>\n      <td>December 31, 2017</td>\n      <td>real</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>FBI Russia probe helped by Australian diplomat...</td>\n      <td>politicsNews</td>\n      <td>December 30, 2017</td>\n      <td>real</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Trump wants Postal Service to charge 'much mor...</td>\n      <td>politicsNews</td>\n      <td>December 29, 2017</td>\n      <td>real</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nWe have labelled the data, we can now combine the datasets. We will do sampling on the entire dataset after combining with a seed. We will use the seed \"1\" for the random number generator for reproducable results.\n\n\n```python\nnews = pd.concat([fake, real], axis=0).sample(frac=1, random_state=1).reset_index(drop=True)\nnews.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>title</th>\n      <th>subject</th>\n      <th>date</th>\n      <th>label</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Trump Calls For This Racist Policy To Be Forc...</td>\n      <td>News</td>\n      <td>September 21, 2016</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Republican ex-defense secretary Cohen backs Hi...</td>\n      <td>politicsNews</td>\n      <td>September 7, 2016</td>\n      <td>real</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>TEACHER QUITS JOB After 5th, 6th Grade Muslim ...</td>\n      <td>politics</td>\n      <td>May 9, 2017</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>LAURA INGRAHAM RIPS INTO THE PRESS\u2026Crowd Goes ...</td>\n      <td>politics</td>\n      <td>Jul 21, 2016</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Germany's Merkel suffers state vote setback as...</td>\n      <td>worldnews</td>\n      <td>October 14, 2017</td>\n      <td>real</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nnews.label.value_counts(dropna=False)\n```\n\n\n\n\n    fake    23481\n    real    21417\n    Name: label, dtype: int64\n\n\n\nNow that we have combined the data, we will first clean and prepare it.\n\n## 2. Preprocessing the data\n\nWe will first take a look at the columns subject and date.\n\n\n```python\nnews.subject.value_counts(dropna=False)\n```\n\n\n\n\n    politicsNews       11272\n    worldnews          10145\n    News                9050\n    politics            6841\n    left-news           4459\n    Government News     1570\n    US_News              783\n    Middle-east          778\n    Name: subject, dtype: int64\n\n\n\nAs we can see, there are no missing values in this column. However, some subject names are written in camel case with others written in snake case and more... We will replace the column names to fix this problem.\n\n\n```python\nnews[\"subject\"] = news[\"subject\"].replace({\"politicsNews\": \"Politics\",\n                                           \"worldnews\": \"World\",\n                                           \"politics\": \"Politics\",\n                                           \"News\": \"All\",\n                                           \"left-news\": \"Left\", \n                                           \"Government News\": \"Government\",\n                                           \"US_News\": \"US\",\n                                           \"Middle-east\": \"Middle East\"})\nnews.subject.value_counts()\n```\n\n\n\n\n    Politics       18113\n    World          10145\n    All             9050\n    Left            4459\n    Government      1570\n    US               783\n    Middle East      778\n    Name: subject, dtype: int64\n\n\n\nWe will now take a look at the dates.\n\n\n```python\nnews.date.value_counts(dropna=False)\n```\n\n\n\n\n    December 20, 2017      182\n    December 6, 2017       166\n    November 30, 2017      162\n    November 9, 2017       158\n    October 13, 2017       155\n                          ... \n    December 22, 2017        1\n    June 24, 2017            1\n    May 22, 2016             1\n    January 24, 2016         1\n    September 11, 2016       1\n    Name: date, Length: 2397, dtype: int64\n\n\n\nAs we can see, there are some values which are not dates. We will explore these values.\n\n\n```python\nnews[news.date.str.extract(r\"^((?!\\w+ \\d+, \\d+))*\", expand=False).notnull()]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>title</th>\n      <th>subject</th>\n      <th>date</th>\n      <th>label</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>328</th>\n      <td>JUST IN: CROOKED DOJ OFFICIAL Didn\u2019t Reveal Th...</td>\n      <td>Politics</td>\n      <td>14-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>1352</th>\n      <td>LOCAL REPORTER IN DEEP BLUE STATE Stuns Libera...</td>\n      <td>Politics</td>\n      <td>17-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>1883</th>\n      <td>JUST IN: BADASS GENERAL JOHN KELLY Shoved Chin...</td>\n      <td>Politics</td>\n      <td>18-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>5157</th>\n      <td>https://fedup.wpengine.com/wp-content/uploads/...</td>\n      <td>Government</td>\n      <td>https://fedup.wpengine.com/wp-content/uploads/...</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>5295</th>\n      <td>https://fedup.wpengine.com/wp-content/uploads/...</td>\n      <td>Left</td>\n      <td>https://fedup.wpengine.com/wp-content/uploads/...</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>7127</th>\n      <td>HEY, BERNIE SANDERS: 18 SCHOOL SHOOTINGS Have ...</td>\n      <td>Politics</td>\n      <td>16-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>8116</th>\n      <td>IT BEGINS\u2026RINO MEGA-DONOR Threatens Jeb Bush: ...</td>\n      <td>Politics</td>\n      <td>18-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>8554</th>\n      <td>\u201cPROUD TRANSGENDER\u201d Democrat Candidate For Con...</td>\n      <td>Politics</td>\n      <td>15-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>8567</th>\n      <td>FACEBOOK\u2019S VP Of Ads BLASTS MEDIA: Majority Of...</td>\n      <td>Politics</td>\n      <td>17-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>8768</th>\n      <td>BUSTED! Maxine Waters\u2019 Ties to Black Nationali...</td>\n      <td>Politics</td>\n      <td>18-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>10414</th>\n      <td>HIGH SCHOOL TEACHER Makes \u201cShooting At Trump\u201d ...</td>\n      <td>Politics</td>\n      <td>18-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>10756</th>\n      <td>WATCH: SNOWFLAKES ASKED Communist Party Platfo...</td>\n      <td>Politics</td>\n      <td>19-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>13545</th>\n      <td>JUST IN: PRESIDENT TRUMP AND FIRST LADY Make S...</td>\n      <td>Politics</td>\n      <td>16-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>13997</th>\n      <td>SC STATE REP Who is a Former Cop Proposes Smar...</td>\n      <td>Politics</td>\n      <td>15-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>14060</th>\n      <td>The DIRTY TRUTH About DACA Recipients\u2026Where Th...</td>\n      <td>Politics</td>\n      <td>15-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>14553</th>\n      <td>BREAKING: FL GOV RICK SCOTT Calls for FBI Dire...</td>\n      <td>Politics</td>\n      <td>16-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>15848</th>\n      <td>TWO HIGH SCHOOL JROTC Members Tell INCREDIBLE ...</td>\n      <td>Politics</td>\n      <td>15-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>16603</th>\n      <td>FACEBOOK RELEASES Ads Paid For By Russians\u2026And...</td>\n      <td>Politics</td>\n      <td>17-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>20181</th>\n      <td>JUST IN: Senate Rejects Immigration Bill\u2026Trump...</td>\n      <td>Politics</td>\n      <td>15-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>20587</th>\n      <td>WATCH SHERIFF\u2019S Honest Response After a School...</td>\n      <td>Politics</td>\n      <td>16-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>20832</th>\n      <td>MEGHAN MCCAIN Cut-Off After Saying the Florida...</td>\n      <td>Politics</td>\n      <td>17-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>21047</th>\n      <td>POLITICS FIRST: LEFTIST PARENTS Of Former Comb...</td>\n      <td>Politics</td>\n      <td>15-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>22074</th>\n      <td>LOOK WHO Approved Visas For Russian Operatives...</td>\n      <td>Politics</td>\n      <td>16-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>22375</th>\n      <td>GOTCHA! A Stammering John Podesta Stunned by a...</td>\n      <td>Politics</td>\n      <td>18-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>22686</th>\n      <td>https://100percentfedup.com/served-roy-moore-v...</td>\n      <td>Politics</td>\n      <td>https://100percentfedup.com/served-roy-moore-v...</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>23296</th>\n      <td>MSNBC ANCHOR Flabbergasted at What Texas Teach...</td>\n      <td>Politics</td>\n      <td>19-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>24487</th>\n      <td>Flashback Video: Susan Rice Says Trump\u2019s Claim...</td>\n      <td>Politics</td>\n      <td>16-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>25464</th>\n      <td>https://fedup.wpengine.com/wp-content/uploads/...</td>\n      <td>Left</td>\n      <td>https://fedup.wpengine.com/wp-content/uploads/...</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>26221</th>\n      <td>https://fedup.wpengine.com/wp-content/uploads/...</td>\n      <td>Politics</td>\n      <td>https://fedup.wpengine.com/wp-content/uploads/...</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>27124</th>\n      <td>TUCKER CARLSON Rips The Left On Gun Control Hy...</td>\n      <td>Politics</td>\n      <td>16-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>28436</th>\n      <td>Homepage</td>\n      <td>Left</td>\n      <td>MSNBC HOST Rudely Assumes Steel Worker Would N...</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>28582</th>\n      <td>WATCH: Mitt Romney Announces Run for Senate\u2026Ba...</td>\n      <td>Politics</td>\n      <td>16-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>28834</th>\n      <td>https://100percentfedup.com/video-hillary-aske...</td>\n      <td>Politics</td>\n      <td>https://100percentfedup.com/video-hillary-aske...</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>29012</th>\n      <td>BROTHER OF HERO COACH Breaks Down Over Tribute...</td>\n      <td>Politics</td>\n      <td>17-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>29380</th>\n      <td>DOJ\u2019s JEFF SESSIONS Opens Investigation Into W...</td>\n      <td>Politics</td>\n      <td>18-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>30269</th>\n      <td>Democrat Senator Warns Mueller Not To Release ...</td>\n      <td>Politics</td>\n      <td>19-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>33547</th>\n      <td>WATCH: \u2019\u2019Carpetbagger\u201d Mitt Romney Takes Swipe...</td>\n      <td>Politics</td>\n      <td>18-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>34168</th>\n      <td>https://fedup.wpengine.com/wp-content/uploads/...</td>\n      <td>Politics</td>\n      <td>https://fedup.wpengine.com/wp-content/uploads/...</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>34299</th>\n      <td>How The Left, The Anti Defamation League and M...</td>\n      <td>Politics</td>\n      <td>17-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>35062</th>\n      <td>https://fedup.wpengine.com/wp-content/uploads/...</td>\n      <td>Government</td>\n      <td>https://fedup.wpengine.com/wp-content/uploads/...</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>40390</th>\n      <td>MEDIA PROMOTES Fake News That Shooter Connecte...</td>\n      <td>Politics</td>\n      <td>15-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>42154</th>\n      <td>HUH? RAPPER JAY-Z Compares Trayvon Martin to M...</td>\n      <td>Politics</td>\n      <td>15-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>43011</th>\n      <td>\u201cTHE TRUMP CURSE IS REAL\u201d\u2026Social Media Respond...</td>\n      <td>Politics</td>\n      <td>17-Feb-18</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>43617</th>\n      <td>https://100percentfedup.com/12-yr-old-black-co...</td>\n      <td>Politics</td>\n      <td>https://100percentfedup.com/12-yr-old-black-co...</td>\n      <td>fake</td>\n    </tr>\n    <tr>\n      <th>44457</th>\n      <td>WHAT\u2019S WRONG WITH PELOSI? Nancy Stutters, Stam...</td>\n      <td>Politics</td>\n      <td>15-Feb-18</td>\n      <td>fake</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nHere are some observations about our recent exploration:\n\n* The articles that have falsely formatted dates and other values for dates are all labelled fake.\n* They are mostly about politics.\n\nWhat we will do is, we will replace these values with null values.\n\n\n```python\nnews.loc[news.date.str.extract(r\"^((?!\\w+ \\d+, \\d+))*\", expand=False).notnull(), \"date\"] = np.nan\n```\n\n\n```python\nnews[news.date.isnull()].shape[0]\n```\n\n\n\n\n    45\n\n\n\nBefore classification, we will visualize our data to see if we're missing anything so far. We will do some further preprocessing later on.\n\n## 3. Visualizing the data for gaining further insights\n\nWe will now visualize and analyze the data we have to see if there are any patterns we might be missing. We will begin with visualizing the time series data for frequencies of fake vs. real news articles.\n\n\n```python\nnews.info()\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 44898 entries, 0 to 44897\n    Data columns (total 4 columns):\n     #   Column   Non-Null Count  Dtype \n    ---  ------   --------------  ----- \n     0   title    44898 non-null  object\n     1   subject  44898 non-null  object\n     2   date     44853 non-null  object\n     3   label    44898 non-null  object\n    dtypes: object(4)\n    memory usage: 1.4+ MB\n\n\n\n```python\nnews.date = pd.to_datetime(news.date, errors=\"coerce\")\nnews_grouped = news[[\"date\", \"subject\", \"label\"]].groupby([\"date\", \"label\"]).count().reset_index()\n\nfig, ax = plt.subplots(figsize=(16,10))\nsns.lineplot(x=\"date\", y=\"subject\", hue=\"label\", data=news_grouped, palette=\"Set2\", ax=ax)\nplt.title(\"News Articles Labelled Fake vs. Real\")\nplt.xlabel(\"Time\")\nplt.ylabel(\"Count\")\n```\n\nAs we are able to see from the line chart above, we have no real news article data prior to the beginning of 2016. However, even after that, the amount of fake news articles is dominating compared to the amount of real news articles for a while. We see a sudden increase in number of real news articles in the last quarter of 2016 followed by another unexpected peak nearing May, 2017. Afterwards, we see a sudden and massive increase in the amount of real articles' data with a more subtle decrease in number of fake articles over time. \n\nLet's take a look at the subjects.\n\n\n```python\nnews_group_by_subj_and_label = news.groupby(by=[\"label\", \"subject\"]).count().reset_index()\n\nfig1, ax1 = plt.subplots(figsize=(16, 8))\nsns.barplot(x=\"subject\", y=\"title\", hue=\"label\", data=news_group_by_subj_and_label, palette=\"Set2\", saturation=0.5, ax=ax1)\nplt.title(\"Fake vs. Real News Articles by Subjects\")\nplt.xticks(rotation=45, horizontalalignment='center', fontweight='light', fontsize='x-large')\nplt.yticks(horizontalalignment='center', fontweight='light', fontsize='large')\nplt.xlabel(\"Subjects\", fontsize=\"large\")\nplt.ylabel(\"Amount\", fontsize=\"large\")\nplt.legend(fontsize=\"large\")\n```\n\nAs we can see, \"real\" article group contains articles that have either \"Politics\" or \"World\" as their subjects while \"fake\" articles consist of a variety of subjects. Fake news articles seem to have a tendency to belong into the subject category \"All\", followed by \"Politics\" whereas not showing any interest in \"World\" category. In the meanwhile, real news articles belong into either one of these categories: \"Politics\" and \"World\". Both real and fake articles have many articles in \"Politics\" category. \n\n## 4. Further Preprocessing\n\nBefore we move on to the classification, we will be working on the data further.\n\nOur first step will be dropping some data. We will drop articles that were released before 2016 because there are no real news articles in that period, therefore, the data is not representative enough. Talking about representation, we will also be dropping articles from subjects \"Government\", \"Left\", \"Middle East\" and \"US\". That's because the only common subject both fake and real articles have is \"Politics\" and we will be dropping too much data if we drop articles with \"All\" and \"World\" subjects. Also, their frequencies and names also indicate that the \"All\" subject for fake articles might be the equivalent of the \"World\" subject in real news. \n\n\n```python\nnews_clean = news[news.date > dt.datetime(2016,1,1)]\nnews_clean.date.value_counts().sort_index()\n```\n\n\n\n\n    2016-01-02    35\n    2016-01-03    31\n    2016-01-04    34\n    2016-01-05    30\n    2016-01-06    43\n                  ..\n    2017-12-27    78\n    2017-12-28    11\n    2017-12-29    26\n    2017-12-30    16\n    2017-12-31    12\n    Name: date, Length: 730, dtype: int64\n\n\n\n\n```python\nnews_clean = news_clean[news_clean.subject.isin([\"All\", \"Politics\", \"World\"])]\nnews_clean.subject.value_counts()\n```\n\n\n\n\n    Politics    16910\n    World       10145\n    All          9030\n    Name: subject, dtype: int64\n\n\n\n\n```python\nnews_clean.shape[0]\n```\n\n\n\n\n    36085\n\n\n\nAs we can see, we still ended up with a decent amount of data! As a next step, we will be working on our features. \n\n## 5. Feature Weighting\n\nAs our features, we are going to use words in the article titles. We will be assigning weights to these words using term-frequencies of them. We will begin with splitting the dat into training and testing sets.\n\n\n```python\ntraining_data, testing_data = train_test_split(news_clean, random_state=1) #seed for reproducibility\n\nY_train = training_data[\"label\"].values\nY_test = testing_data[\"label\"].values\n\ndef word_counter(data, column, training_set, testing_set):\n\n    cv = CountVectorizer(binary=False, max_df=0.95)\n    cv.fit_transform(training_data[column].values)\n    \n    train_feature_set = cv.transform(training_data[column].values)\n    test_feature_set = cv.transform(testing_data[column].values)\n    \n    return train_feature_set, test_feature_set, cv\n\nX_train, X_test, feature_transformer = word_counter(news_clean, \"title\", training_data, testing_data)\n```\n\n## 6. Training the model, prediction & accuracy\n\nNow that we have prepared our features, we will be training our model. Then, we will predict values for our testing set. We will be using the accuracy metric after that. Accuracy is measured using the formula below:\n\n\\begin{equation}\n\\text{Accuracy} = \\frac{\\text{number of correctly classified articles}}{\\text{total number of classified articles}}\n\\end{equation}\n\n\n```python\nclassifier = LogisticRegression(solver=\"newton-cg\", C=5, penalty=\"l2\", multi_class=\"multinomial\", max_iter=1000)\nmodel = classifier.fit(X_train, Y_train)\n```\n\n\n```python\npredictions = model.predict(X_test)\naccuracy = accuracy_score(Y_test, predictions, normalize=True)\nprint(\"Our model has {}% prediction accuracy.\".format(round(accuracy, 2) * 100))\n```\n\n    Our model has 96.0% prediction accuracy.\n\n\n## 7. Conclusion\n\nThrough this project, we have cleaned, analyzed, visualized and classified fake and real news articles. \n\n* We have cleaned our data to prepare it for further analysis.\n* Later, we have visualized and analyzed the data before fitting it to make sure that our data is ready.\n* We assigned term-frequencies of the words in the title column as their weights while feature weighting.\n* We have used Multinomial Logistic Regression for classification and accuracy as our metric. Our model successfully classified 96% of the testing data in the end.\n", "meta": {"hexsha": "8c4807abdb2c1616f1e8d2323c3d33d49aeb7b7c", "size": 206162, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "fake-or-real.ipynb", "max_stars_repo_name": "dilarakarabey/fake-real-news-classifier", "max_stars_repo_head_hexsha": "39ca210a587906378334716be83eb114082e0104", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-02T06:36:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-02T06:36:23.000Z", "max_issues_repo_path": "fake-or-real.ipynb", "max_issues_repo_name": "dilarakarabey/fake-real-news-classifier", "max_issues_repo_head_hexsha": "39ca210a587906378334716be83eb114082e0104", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fake-or-real.ipynb", "max_forks_repo_name": "dilarakarabey/fake-real-news-classifier", "max_forks_repo_head_hexsha": "39ca210a587906378334716be83eb114082e0104", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-08-04T15:41:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T19:46:14.000Z", "avg_line_length": 153.5085629188, "max_line_length": 129488, "alphanum_fraction": 0.848022429, "converted": true, "num_tokens": 7264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.057493280819038775, "lm_q1q2_score": 0.026728716596182624}}
{"text": "# Introduction\n\nThe following is a brief introduction to Python and the IPython Notebook. There is much more to learn than what is covered here. This is just enough to get you started with the tutorial.\n\n# The IPython Notebook\n\nIPython consists of two processes: a kernel and a frontend. The kernel executes code while the frontend provides an interface for the user enter their code. The IPython notebook is a frontend for Python which provides an interactive web-environment for executing code and displaying rich media.\n\n### Using the Notebook\n\nTo start an IPython notebook session open a command prompt, navigate to a desired working directory then issue the following command:\n\n`ipython notebook`\n\nA new window will open in your web browser where you can open an existing notebook or start a new one.\nNotebooks are organized with cells. You may have a code cell for inputing commands followed by its result cell which contains the output of the code. You may also have a text cell, such as this one you're reading right now. Cell type can be changed in the above dropdown menu.\n\nThere is the menubar above for navigating a notebook but you will find the following shortcuts helpful:\n\n- `Enter` : Create a new line with in cell\n- `Shift + Enter` : Execute cell and advance to next cell\n- `Ctrl + Enter` : Execute cell in place (do not advance to the next cell)\n- Press `esc` (command mode) then `h` to display keyboard shortcuts\n\nAt times you might run code that gets stuck in an infinite loop or simply you want to clear all your workspace variables and start over. To solve each of these problems you can click on the menu:\n\n`Kernel -> Interrupt`\n\n`Kernel -> Restart`\n\n\n\n\n```python\nfrom __future__ import print_function\n```\n\n### Magic Commands\n\nThese are commands to control IPython itself.\n\n\n```python\n# list available magic commands\n%lsmagic\n```\n\n\n```python\n%load utils.py\n```\n\n### Need Help?\n\nIn case you're lost help isn't far. The following commands should provide assistance.\n\n\n```python\n# Displays an overview of IPython's features\n?\n```\n\n\n```python\n# A Quick Reference for IPython\n%quickref\n```\n\n\n```python\n# For details about an object\n# object_name?\nround??\n```\n\n\n```python\n# list functions available in your workspace\ndir()\n```\n\n\n```python\n# list variables available in your workspace\n%whos\n```\n\n# Python\n\n### Basic Data Types\n\n\n```python\na = 5\nb = 5.0\nc = float(5)\nd = 'dee'\ne = 'e'\n\ntype(a), type(b), type(c), type(d), type(e)\n```\n\n### Data Structures\n\nPython offers several builtin data structures for arranging data in memory. We will be making use of lists, dictionaries, tuples during this tutorial. \n\n#### Lists\n\nA list is a versatile container that holds objects in the order given. Lists are typically used to group similar items but may contain heterogenous data types.\n\n\n```python\nempty_list = []\n\nstring_list = ['lions', 'tigers', 'bears', 'sharks', 'hamsters']\n\nint_list = [0, 1, 2, 3, 4]\nint_list2 = range(5,10)\n\nlist_from_variables = [a,b,c,d,e]\n\nlist_of_lists = [empty_list,\n                 string_list,\n                 list_from_variables,\n                 int_list,\n                 int_list2]\n\nprint(list_of_lists)\n```\n\nElements of a list are accessible by their index.\n\n\n```python\nprint(string_list[0])\nprint(string_list[1:4])\nprint(int_list[::2])  # get every 2nd element\nprint(list_of_lists[1][4])  # get a nested item\n```\n\nList are mutable, meaning after a list is created we can change, add, or remove elements.\n\n\n```python\nint_list[2] = 222\n\nint_list.append(5)\n\nstring_list.remove('lions')\n\nlist_from_variables.extend(int_list)\n\nprint(int_list)\nprint(string_list)\nprint(list_from_variables)\n```\n\n#### Tuples\n\nTuples share similarites with lists. A tuple is good for organizing related data that may be of different types. Notice they are defined with parenthesis, `()`, rather than brackets.\n\n\n```python\njoe_blow = (32, 'tall', 'likes hats')\n\nprint(joe_blow[1])\n```\n\nUnlike lists, tuples are immutable. They cannot be changed once defined.\n\n\n```python\n# this won't work\njoe_blow.append('married')\n\n# neither will this\njoe_blow[2] = 'not really a fan of hats'\n```\n\nIn python a function can return multiple values. These ouputs are packed into a tuple. Tuple unpacking assigns individual elements of a tuple to separate variables.\n\n\n```python\npets = ('elephant', 'cow', 'rock')\n\npet1, pet2, pet3 = pets\n```\n\nA peculiar thing about tuples in python is defining a single element tuple. Note the trialing comma. This is necessary for python to know you want a one-element tuple.\n\n\n```python\n(pet1,)\n```\n\n#### Dictionaries\n\nA dictionary is an unordered set of *key:value* pairs. Much like a language dictionary where you look up a *word* and get its *definition* in a python dictionary you look up a *key* and get its *value*.\n\n\n```python\n# numbers or strings may be used as keys\ndictionary0 = {'key1':'value1', 'key2':'value2', 'key3':'value3'}\ndictionary1 = {1:'value1', 2:'value2', 3:'value3'}\n\ncylinder = {'mass':50, 'base':10, 'height':100}\n\nprint(dictionary0)\nprint(dictionary1.keys())\nprint(cylinder['mass'])\n```\n\nThe zip function is a convenient function to help generate a dictionary. It takes sequence objects and combines them into a list of tuples. We can subsequently use the list of two element tuples to create a dictionary.\n\n\n```python\nkeys = ['mass01', 'inertia01', 'mass02', 'inertia02']\nvalues = [10, 1, 50, 5]\n\ndict(zip(keys, values))\n```\n\n### Functions\n\nPython does not use braces, `{}`, or `end` statements to seperate blocks of code. Rather, code blocks are initialized with colon, `:`, and defined by their indentation. It is convention to use four spaces for each level of indentation.\n\n\n```python\ndef abs_value(A):\n    if A < 0:\n        A = -A \n    return A\n\nabs_value(-100)\n```\n\n\n```python\ndef long_div(dividend, divisor):\n    quotient = dividend // divisor # // : floor division\n    remainder = dividend % divisor # % : modulo\n    return quotient, remainder\n\n\na = 430\nb = 25\n\n# an example of tuple unpacking\nquo, rem = long_div(a, b)\n\nprint('%d divided %d is %d remainder %d' % (a, b, quo, rem))\n```\n\n### Modules\n\nModules add additional functionality not present in the default installation of python. Throughout this tutorial we will either import an entire module or import specific functions from a module.\n\n\n```python\n# import object from sympy into the current namespace\nfrom numpy import array\n\n# import multiple objects from sympy\nfrom sympy.physics.mechanics import dynamicsymbols, ReferenceFrame, Point\n```\n\nObjects from these modules are now available in your namespace.\n\n\n```python\n# from numpy\narr = array([1,2,3,4,5])\n\n# from sympy.physics.mechanics\ninertial_frame = ReferenceFrame('I')\n```\n\n# The SciPy Stack\n\nSciPy is a collection of open source software that brings scientific computing to Python.\n\n- IPython : Enhanced Interactive Console\n- Numpy : N-dimensional array package\n- Matplotlib : a fully featured 2D plotting package\n- Scipy : a collection of toolboxes for signal processing, optimization, statisitics, etc.\n- Sympy : symbolic mathematics and computer algebra\n- and much more...\n\n## Numpy\n\n### Setup\n\n\n```python\nfrom numpy import random, linspace, zeros, arange\n```\n\n### Creating Arrays\n\n\n```python\n# An array from a list\nprint(array([5, 12, -2, 9.3, 7]))\n\n# random values\nprint(random.random((5)))\n\n# linearly spaced values\n# 5 values between 0 and 10 inclusive\nprint(linspace(0,10,5))\n\n# range of values with a defined stepsize\n# start at 0 and increase by 3 \nprint(arange(0,14,3))\n```\n\n### Accessing Array Elements\n\n\n```python\nP = random.random((3,5))\n\n# individual element\nprint(P[0,3])\n\n# entire row\nprint(P[2])\n\n# entire column\nprint(P[:,4])\n\n# every third element\nprint(P[::3])\n```\n\n### Operations on Arrays\n\n\n```python\n# mathematical operations are always elementwise\nx = arange(5)\n\nprint(x)\n\n# the double asterisk represents exponentiation\nprint(x + x**2)\n```\n\n## Matplotlib\n\nMatplotlib provides an API similar to MATLAB's\n\nUse the magic command `%matplotlib inline` to work with matplotlib interactively. The `inline` argument allows for plots to be embedded within the IPython notebook\n\n\n```python\n%matplotlib inline\n```\n\n\n```python\nfrom matplotlib.pyplot import plot, subplot, xlabel, ylabel, legend, tight_layout\nfrom numpy import sin, cos, pi\n```\n\n### Examples\n\n\n```python\nx = arange(-pi,pi,0.1)\ny1 = 2*sin(x)\ny2 = x + cos(4*x)\n\nplot(x, y1, 'r', x, y2, '--b')\nplot(x[::5], y1[::5], 'og') # plot every 5th point\nxlabel('x axis')\nylabel('y axis')\nlegend(['red', 'blue', 'green'], loc='upper left')\n```\n\n\n```python\nx = linspace(-100,100)\n\nfor i in range(1,5):\n    subplot(2,2,i)\n    plot(x, x**i)\n    \ntight_layout() # this prevents the axis labels from overlapping\n```\n\n### Exercise\n\nUse the provided function to create 3 different sine waves at various frequencies. Plot the 3 functions with labeled axis.\n\n\n```python\ndef three_sine_waves(t, A, B, C):\n    \"\"\"\n    t : (type: array) an monotonically increasing array of time values\n    A,B,C : (type: float) frequency of sine waves\n    \"\"\"\n    y1 = sin(A*t)\n    y2 = sin(B*t)\n    y3 = sin(C*t)\n    \n    return y1, y2, y3\n```\n\n\n```python\nt = \ny1, y2, y3 = three_sine_waves()\n```\n\n\n```python\n%load exercise_solutions/n00_python_intro_data-plotting.py\n```\n\n## Scipy odeint\n\nScipy provides a routine for integrating first order ordinary differential equations.\n\n### Setup\n\n\n```python\nfrom scipy.integrate import odeint\n```\n\n### Examples\n\n\n```python\ndef dy(y,x):\n    return x\n\ny0 = 0.0\nx = linspace(-5.0, 5.0, 1000)\n\ny = odeint(dy,y0,x)\n\nplot(x,y)\n```\n\n\n```python\ndef dy(y,t,coeff):\n    A = coeff['A']\n    B = coeff['B']\n    C = coeff['C']\n    D = coeff['D']\n    return A*t**3 + B*t**2 + C*t + D\n\ny0 = 2.0\nt = linspace(-5.0, 3.0, 1000)\nsys = {'A' : 0.25,\n       'B' : 0.75,\n       'C' : -1.5,\n       'D' : -2.0}\n\ny = odeint(dy, y0, t, args=(sys,))\n\nplot(t,y)\n```\n\n## SymPy\n\n### Setup\n\n\n```python\nfrom sympy import *\n\n# This is for prettier printing of equations\ninteractive.printing.init_printing()\n```\n\n### Creating Symbolic Variables\n\n\n```python\na = symbols('a')\nb = symbols('b')\ngravity, mass, spring_const, time = symbols('g, m, k, t')\n```\n\n### Expressions Using Symbolic Variables\n\n\n```python\na**2 + b/pi\n```\n\n\n```python\nsimplify(4*(a*a*a)*(b+b+b))\n```\n\n\n```python\ndiff(-gravity*time**2/2, time)\n```\n\n\n```python\n# indefinte integral\n\nintegrate(-gravity,time)\n```\n\n\n```python\n# definite integral\n\nv0 = 5\nt1 = 0\nt2 = .35\nposition = integrate(-gravity*time + v0,(time,t1,t2))\nposition.subs(gravity, 9.81)\n```\n\n# Additional Resources\n\n[1] http://docs.python.org/2/tutorial\n\n[2] http://nbviewer.ipython.org/github/ipython/ipython/blob/master/examples/notebooks/Cell%20Magics.ipynb\n\n[3] http://www.scipy.org/index.html\n", "meta": {"hexsha": "8caf55911ae734b36e02b743aa74d8316ff5ddc8", "size": 23161, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/n00_python_intro.ipynb", "max_stars_repo_name": "pydy/pydy-tutorial-human-standing", "max_stars_repo_head_hexsha": "72b1d8513e339e9b10e501bd3490caa3fa997bc4", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 134, "max_stars_repo_stars_event_min_datetime": "2015-05-19T15:24:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T09:39:03.000Z", "max_issues_repo_path": "notebooks/n00_python_intro.ipynb", "max_issues_repo_name": "pydy/pydy-tutorial-human-standing", "max_issues_repo_head_hexsha": "72b1d8513e339e9b10e501bd3490caa3fa997bc4", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 46, "max_issues_repo_issues_event_min_datetime": "2015-05-05T18:08:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T11:12:42.000Z", "max_forks_repo_path": "notebooks/n00_python_intro.ipynb", "max_forks_repo_name": "pydy/pydy-tutorial-pycon-2014", "max_forks_repo_head_hexsha": "72b1d8513e339e9b10e501bd3490caa3fa997bc4", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 62, "max_forks_repo_forks_event_min_datetime": "2015-06-16T01:50:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T07:39:41.000Z", "avg_line_length": 21.3662361624, "max_line_length": 300, "alphanum_fraction": 0.5259272052, "converted": true, "num_tokens": 2850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17328819739040088, "lm_q2_score": 0.15405756074950905, "lm_q1q2_score": 0.026696356996644598}}
{"text": "# Jupyter Notebook Markdown\n\n1. Headings & List\n2. Embedded Code\n3. LaTeX Equations\n4. Attach Local/Internet Files\n5. Tables\n\nResource: https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Working%20With%20Markdown%20Cells.html\n\n## 1. Heading & List\n\n### Headings:\n\nHeading of a markdown is going to help your audiences focus on the content of a markdown block.  We can add headings by starting a line with one (or multiple) ```#``` followed by a space, as in the following example:\n\n\n# Heading 1\n## Heading 1.1\n### Heading 1.1.1\n#### Heading 1.1.1.1\n\n\n### List:\n\nIt's often the case that we want to list out the content in a markdown block. We can build nested itemized or enumerated lists:\n\n\n- First Item\n    - First Item Sublist\n        - Sub-Item\n- Second Item - Not Sublist - Not Sublist\n- Third Item\n- Fourth Item\n\n\nHere is another list:\n\n\n1. This is the first item\n    1. This is the first sub-item of the first item\n    2. This is the second sub-tiem of the first item\n2. This is the second item\n3. This is the last item in the list\n\n\n### Text Style\n\n\n1. *There are two ways to type italic text*\n    - *Use a single asterisk* | ```*text*```\n    - OR *Use a single underscore* | ```_text_```\n2. **There are two ways to type bold text**\n    - **Use double asterisks** | ```**test**```\n    - OR **Use double underscores** | ```__text__```\n\n\n\n## 2. Embedded Code\n\nWe can embed code meant for illustration instead of execution in Python:\n\n``` Python\ndef f(x):\n    \"\"\"Function f(x) = x^2\"\"\"\n    return x**2\n```\n\nWe can also write code for other languages:\n\n``` r\nf = function(x){\n    print(x**2)\n    }\n```\n\n## 3. LaTex Equations\n\nWe can include mathematical expression both inline and displayed. Inline expression can be added by surrounding the latex code with a single ```$```. Expressions on their own line are surrounded by double ```$$```.\n\nThis is the equation I want to show inline with this text: $\\sum{(x_i - \\bar{x})^2}$.\n\nThis is the equation I want to display by itself.\n\n$$\\hat{\\sigma}^2 = \\frac{\\sum{(x_i - \\bar{x})^2}}{n-1}$$\n\nAlternatively, you can also surround the expression with HTML tags ```\\begin{equation}``` and  ```\\end{equation}```:\n\n``` html\n\\begin{equation}\n\\hat{\\sigma}^2 = \\frac{\\sum{(x_i - \\bar{x})^2}}{n-1}\n\\end{equation}\n```\n\n## 4. Attach Local / Internet Files\n\nIf we have local files in the Notebook directory, we can refer to these files in Markdown cells directly:\n\n``` md\n\n```\n\nAlternatively, we can also use the HTML tag:\n\n``` md\n\n```\n\n\n\n\nWe can also reference external file and attach a file to a markdown cell:\n\n```md\n\n```\n\n\n\n\n## Table\n\nIt's often case that we want to display some high-level data or description in a tabular format, which we can easily create table in a markdown cell like this:\n\n``` md\n| Column 1 | Column 2 | Column 3 |\n| :--- | ---: | :---: |\n| Norman | Lo | Economics |\n| Tokyo | Japan | Location |\n| MJ | Basketball | Sport |\n```\n\n| Column 1 | Column 2 | Column 3 |\n| :--- | ---: | :---: |\n| Norman | Lo | Economics |\n| Tokyo | Japan | Location |\n| MJ | Basketball | Sport |\n\n\n```python\n\n```\n", "meta": {"hexsha": "39b26ad2a1269f15a52e63e0da0f2adb3a1f0144", "size": 6607, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Week_10_Markdown_Documentation/Jupyter Notebook Markdown.ipynb", "max_stars_repo_name": "stevetruong426/DS311-Technologies-in-Data-Analytic", "max_stars_repo_head_hexsha": "029517d0a9acea9256b1bcd85f7a658dbd3d96b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-22T02:55:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T02:55:44.000Z", "max_issues_repo_path": "Week_10_Markdown_Documentation/Jupyter Notebook Markdown.ipynb", "max_issues_repo_name": "stevetruong426/DS311-Technologies-in-Data-Analytic", "max_issues_repo_head_hexsha": "029517d0a9acea9256b1bcd85f7a658dbd3d96b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week_10_Markdown_Documentation/Jupyter Notebook Markdown.ipynb", "max_forks_repo_name": "stevetruong426/DS311-Technologies-in-Data-Analytic", "max_forks_repo_head_hexsha": "029517d0a9acea9256b1bcd85f7a658dbd3d96b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2022-02-06T06:30:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T04:54:54.000Z", "avg_line_length": 26.8577235772, "max_line_length": 225, "alphanum_fraction": 0.5208112608, "converted": true, "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2942149845400438, "lm_q2_score": 0.09009300006965833, "lm_q1q2_score": 0.02650671062266069}}
{"text": "## Microgrid simulator\n    Object-oriented light framework to run custom microgrid resources in lockstep and plot/aggregate results.\n    All units are s|W|Ws if not stated otherwise, more about conventions in the glossary.\n\n\n# Table of contents\n1. [Parameters](#si3Eitei)\n2. [Model toolset](#eid8ieWi)  \n3. [Tests](#Dei4Uezu)     \n3. [Example](#arg4Uezu)     \n4. [Appendix](#aeZae4ai)  \n    4.0. [Glossary](#aec2ieTe)  \n    4.1. [Notebook version](#aeDae4ai)  \n    4.2. [License](#aeZGe4ai)\n    \n\n### Model Toolset <a name=\"eid8ieWi\"></a>\n    Helper functions to build the model\n\n\n```python\nimport math\nimport random\nimport time\nimport os\nfrom collections import OrderedDict\nfrom collections.abc import Iterable\n\nimport pickle\nimport pandas as pd\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\nfrom IPython.core.debugger import set_trace#for ipdb\nfrom IPython.core.display import display, HTML, clear_output\n```\n\n\n```python\ndisplay(HTML(\"<style>.container { width:98% !important; }</style>\"))#this cell width\n```\n\n\n<style>.container { width:98% !important; }</style>\n\n\n\n```python\n%matplotlib inline\nnp.seterr(all='raise')\nplt.rcParams[\"figure.figsize\"] = (15,2.5)\n```\n\n\n```python\nVERBOSE = 0\n# control verbose level of simulation_load/store/init/run()\n#     0:= silent\n#     1:= stringify each resource each step\n#     2:= 1 with repr() instead of str()\n```\n\n#### Parameters\n\n#### Helper functions and resources\n\n\n```python\ndef to_kWh(E_in):\n    \"\"\"takes [Ws]\"\"\"\n    return E_in /1000 /3600\ndef to_Ws(E_in):\n    \"\"\"takes [kWh]\"\"\"\n    return E_in *1000 *3600\n```\n\n\n```python\ndef get_params(param, ct_grp='', j=None):\n    \"\"\"Calculates given parameter p for each timestep k. It implements given formulas\n    takes param which is the parameter of interest, str\n    takes ct_grp which specifies the collection from the magg, defaults to all in R, str\n    takes j specifying the entity in the collection, defaults to all in ct_grp, int\n    returns param_k in 1,K-ndarray\n    no-side effects;\n    \"\"\"\n    param = param.upper()\n    if ct_grp == '' and j is not None:\n        raise ValueError(f'no ct_grp selected yet j={j} given')\n    if param == 'SDR':\n        if ct_grp == '':#lookup mrss\n            P_k_prod = get_power(ct_rs=None, ct_flow='prod')\n            P_k_cons = get_power(ct_rs=None, ct_flow='cons')\n            if P_k_prod is None:\n                P_k_prod = np.zeros( (Resource.K) )\n            if P_k_cons is None:\n                P_k_cons = np.zeros( (Resource.K) )\n            E_k_loss_grid = 0\n            SDR_k = np.ones( (Resource.K) )\n            dividend = (-1 * P_k_cons + E_k_loss_grid)\n            np.divide(P_k_prod, dividend, out=SDR_k, where=dividend!=0)#to go around ZeroDivisionError\n            return SDR_k\n        else:\n            P_k_prod_ = get_power_grp(ct_grp, j=j, ct_rs=None, ct_flow='prod')#j=(j or None), indicated by _\n            P_k_cons_ = get_power_grp(ct_grp, j=j, ct_rs=None, ct_flow='cons')\n            SDR_k_ = np.ones( (Resource.K) )\n            dividend = (-1 * P_k_cons_)\n            np.divide(P_k_prod_, dividend, out=SDR_k_, where=dividend!=0)\n            return SDR_k_\n    elif param == 'SSR':\n        SDR_k_ = get_params('SDR', ct_grp, j)\n        return np.where(SDR_k_ <= 1, SDR_k_, 1) \n    elif param == 'SCR':\n        SDR_k_ = get_params('SDR', ct_grp, j)\n        return np.where(SDR_k_ >= 1, 1/SDR_k_, 1)\n    elif param == 'RCR':\n        if ct_grp == '':\n            P_k_prod = get_power(ct_rs=None, ct_flow='prod')\n            P_k_cons = get_power(ct_rs=None, ct_flow='cons')\n            if P_k_prod is None:\n                P_k_prod = np.zeros( (Resource.K) )\n            if P_k_cons is None:\n                P_k_cons = np.zeros( (Resource.K) )\n            P_k_res = np.absolute(P_k_prod + P_k_cons)\n            P_k_res_abs = np.absolute(P_k_prod) + np.absolute(P_k_cons)\n            out = np.zeros( (Resource.K) )\n            np.divide(P_k_res, P_k_res_abs, out=out, where=P_k_res_abs!=0)\n            return 1 - out\n        else:\n            P_k_prod_ = get_power_grp(ct_grp, j=j, ct_rs=None, ct_flow='prod')\n            P_k_cons_ = get_power_grp(ct_grp, j=j, ct_rs=None, ct_flow='cons')\n            P_k_res_ = np.absolute(P_k_prod_ + P_k_cons_)\n            P_k_res_abs_ = np.absolute(P_k_prod_) + np.absolute(P_k_cons_)\n            out = np.zeros( (Resource.K) )\n            np.divide(P_k_res_, P_k_res_abs_, out=out, where=P_k_res_abs_!=0)\n            return 1 - out\n    else:\n        raise NotImplementedError(f'{param}')\n        \ndef get_param(param, ct_grp='', j=None):\n    \"\"\"Calculates given parameter p for the simulated time; implements given formulas\n    takes param which is the parameter of interest, str\n    takes ct_grp which specifies the collection from the magg, defaults to all in R, str\n    takes j specifying the entity in the collection, defaults to all in ct_grp, int\n    returns param value\n    side effects: reads from current mdata\n    \"\"\"\n    param = param.upper()\n    if ct_grp == '' and j is not None:\n        raise ValueError(f'no ct_grp selected yet j={j} not None')\n    if param == 'SDR':\n        return np.mean(get_params(param, ct_grp, j))\n    elif param == 'SSR':\n        if ct_grp == '':\n            P_k_res = get_power()\n            P_k_res_cons = np.where(P_k_res < 0, P_k_res, 0)\n            P_k_cons = get_power(ct_flow='cons')\n            if np.sum(P_k_cons) != 0:\n                return 1 - np.sum(P_k_res_cons) / np.sum(P_k_cons)\n        else:#calc is equal to: (pv+dch)/(ld+ch+inv_loss), es loss is to be excl.\n            P_k_res_ = get_power_grp(ct_grp, j=j)\n            P_k_res_cons_ = np.where(P_k_res_ < 0, P_k_res_, 0)\n            P_k_cons_ = get_power_grp(ct_grp, j=j, ct_flow='cons')\n            if np.sum(P_k_cons_) != 0:\n                return 1 - np.sum(P_k_res_cons_) / np.sum(P_k_cons_)\n        return 1#no cons means no res_cons\n    elif param == 'SCR':\n        if ct_grp == '':\n            P_k_res = get_power()\n            P_k_res_prod = np.where(P_k_res > 0, P_k_res, 0)\n            P_k_prod = get_power(ct_flow='prod')\n            if np.sum(P_k_prod) != 0:\n                return 1 - np.sum(P_k_res_prod) / np.sum(P_k_prod)\n        else:\n            P_k_res_ = get_power_grp(ct_grp, j=j)\n            P_k_res_prod_ = np.where(P_k_res_ > 0, P_k_res_, 0)\n            P_k_prod_ = get_power_grp(ct_grp, j=j, ct_flow='prod')\n            if np.sum(P_k_prod_) != 0:\n                return 1 - np.sum(P_k_res_prod_) / np.sum(P_k_prod_)\n        return 1#no prod means no res_prod\n    elif param == 'RCR':\n        return np.mean(get_params(param, ct_grp, j))\n    elif param == 'GUR':\n        if ct_grp == '':\n            raise NotImplementedError(f'{param}: choose ct_grp')\n        else:\n            P_k_J_res = np.zeros( (Resource.K) )\n            P_k_RJ_res = np.zeros( (Resource.K) )\n            if j is None:#all j\n                j_ = range(len(magg[ct_grp]))\n            else:#one j\n                j_ = [j]\n            for j__ in j_:\n                P_k_J_res += np.absolute(get_power_grp(ct_grp, j=j__))\n                P_k_RJ_res += get_power_grp(ct_grp, j=j__, ct_flow='prod')\n                P_k_RJ_res += get_power_grp(ct_grp, j=j__, ct_flow='cons')*-1\n            if P_k_RJ_res.sum() != 0:\n                return P_k_J_res.sum() / P_k_RJ_res.sum()\n        return 1#no RJ_res means no J_res, since |x|+|y| is 0, so is |x+y|\n    else:\n        raise NotImplementedError(f'{param}')        \n```\n\n\n```python\ndef arc_to_deg(arc):\n    \"\"\"convert spherical arc length [m] to great circle distance [deg]\"\"\"\n    return float(arc)/6371/1000 * 180/math.pi\n\ndef deg_to_arc(deg):\n    \"\"\"convert great circle distance [deg] to spherical arc length [m]\"\"\"\n    return float(deg)*6371*1000 * math.pi/180\n\ndef latlon_to_xyz(lat,lon):\n    \"\"\"Convert angluar to cartesian coordiantes\n     \n    latitude is the 90deg - zenith angle in range [-90;90]\n    lonitude is the azimuthal angle in range [-180;180] \n    \"\"\"\n    r = 6371 # https://en.wikipedia.org/wiki/Earth_radius\n    theta = math.pi/2 - math.radians(lat) \n    phi = math.radians(lon)\n    x = r * math.sin(theta) * math.cos(phi) # bronstein (3.381a)\n    y = r * math.sin(theta) * math.sin(phi)\n    z = r * math.cos(theta)\n    return [x,y,z]\n\ndef xyz_to_latlon (x,y,z):\n    \"\"\"Convert cartesian to angular lat/lon coordiantes\"\"\"\n    r = math.sqrt(x**2 + y**2 + z**2)\n    theta = math.asin(z/r) # https://stackoverflow.com/a/1185413/4933053\n    phi = math.atan2(y,x)\n    lat = math.degrees(theta)\n    lon = math.degrees(phi)\n    return [lat,lon]\n\ndef gen_coords(seed, N, center=(500,500), edge=1000, is_latlon=False):\n    \"\"\"Generates batch of coords inside a square\n    with specified edge length [m] and its center\n    \n    takes seed to reproduce batch, int\n    takes N is batch size of tupels\n    takes center of square, [m]\n    takes edge length of square\n    takes is_latlon bool flag\n    returns N,2 ndarray\n    \"\"\"\n    half_edge = (float(edge) / 2)\n    if is_latlon:\n        half_edge /= (6371 * 1000 * math.pi/180)#to deg\n        if abs(center[0])+ half_edge > 90:#reject unhandled corner-cases\n            raise ValueError('bad lat center due to cornercase')\n        if abs(center[1])+ half_edge > 180:\n            raise ValueError('bad lon center due to cornercase')\n    np.random.seed(seed)#to reproduce batch\n    batch = np.random.random(2 * N).reshape(2, N)#[0;1[\n    batch[0] = (center[0] - half_edge) + batch[0] * half_edge * 2\n    batch[1] = (center[1] - half_edge) + batch[1] * half_edge * 2\n    return batch.transpose()\n\ndef center_point(resources):\n    \"\"\"calculate the coordinate center of rss batch\n    \n    takes resources list\n    each dimension is averaged on arithmetic mean\n    returns the center (x,y,z)\n    (if: for latlon see geopy.distance.great_circle or geopy.geocoders)\n    \"\"\"\n    center = [0,0,0]\n    for rs in resources:\n        xyz = latlon_to_xyz(rs.cord2, rs.cord1)\n        center[0] += xyz[0]\n        center[1] += xyz[1] \n        center[2] += xyz[2]\n    center[:] = [axis / len(resources) for axis in center]\n    return center\n```\n\n\n```python\ndef sample_sinus(steps, period=2*math.pi, phase=0, amp=1, offset=0):\n    \"\"\"Sample specified sinus-wave into array\n    \n    takes period and phase in radians;\n    takes amplitude and offset to scale and move up/down\n    returns flat ndarray of steps length\n    \"\"\"\n    assert steps != 0\n    samples = np.zeros( (steps) , dtype=np.float64)#default\n    step_size = period / steps\n    for i in range(steps):\n        samples[i] = amp * math.sin(phase + step_size * i) + offset\n    return samples\n\ndef sample_recs(recs, repeat=1):\n    \"\"\"Builds rectangular pattern\n    \n    takes recs in .,3 ndarray used to build the pattern\n        start,length are non-negative integers\n        amp is integer\n        eg [[start,length,amp],[0,4,2],[2,1,-1]]\n    takes repeat to concat the period repeat times\n    returns flat ndarray with specified pulse\n    \"\"\"\n    size = recs[:,:2].sum(1).max()#number of elements \n    pattern = np.zeros( (size) )\n    for rec in recs:\n        start = rec[0]\n        end = rec[0] + rec[1]\n        amp = rec[2]\n        pattern[start:end] += amp\n    return np.tile(pattern, repeat)#clone and concat\n```\n\n\n```python\ndef get_rss(ct_grp, j=None, ct_rs=None):\n    \"\"\"Access helper to return resources by j\n    takes ct_grp which is a key from magg, str\n    takes j the positional index the entity has in the magg, None is all, int\n    takes ct_rs to include only resources of this category, None is all, str\n        eg get_rss('hh', 1, 'es') \n            gets prosumed power es of second entity in magg['hh']\n    returns list of resources of j/all and [] if no such resource(s)\n    side-effect: reads from mrss,magg,mmap\n    \"\"\"\n    ret_val = []\n    if j is None:#get rss of all j\n        allr_of_js = magg[ct_grp]\n    else:#get rss of j\n        allr_of_js = [magg[ct_grp][j]]\n    for allr_of_j in allr_of_js:\n        for r in allr_of_j:\n            if r not in mmap:\n                raise KeyError(f'magg[{j}] has r={r}, which is not in mrss')\n            location = mmap[r]\n            rs = mrss[location[0]][location[1]]\n            if ct_rs is not None and ct_rs != rs.ct:\n                continue\n            ret_val.append(rs)\n    return ret_val\n    \ndef get_power(ct_rs=None, ct_flow=None):\n    \"\"\"Access helper to aggregate resource logs \n    takes ct_rs to include only resources of this category, None is all, str\n        if ct_rs does not exist, power returned 0 and no raise\n    takes ct_flow to include only 'prod' or 'cons', None is both, str\n        eg get_power('es') \n            gets prosumed power of all es\n    returns power in 1,K ndarray, and 1,K zeros if no such resource(s)\n    side-effect: reads from mrss\n    \"\"\"\n    ret_val = np.zeros( (Resource.K) )\n    for key, value in mrss.items():\n        for rs in value:\n            if ct_rs is not None and ct_rs != rs.ct:#wrong rs type\n                continue\n            if rs.log_index_P is None:\n                #print('log_index_P',rs)#prints eg inverters\n                continue\n            tmp = rs.view[rs.log_index_P]#select power\n            if ct_flow is None:\n                ret_val += tmp\n            elif ct_flow == 'prod':\n                ret_val += np.where(tmp > 0, tmp, 0)\n            elif ct_flow == 'cons':\n                ret_val += np.where(tmp < 0, tmp, 0)\n            else:\n                raise ValueError(f\"no such flow '{ct_flow}'\")\n    return ret_val\n    \ndef get_power_grp(ct_grp, j=None, ct_rs=None, ct_flow=None):\n    \"\"\"Access helper to aggregate resource logs by j\n    takes ct_grp which is a key from magg, str\n    takes j the positional index the entity has in the magg, None is all, int\n    takes ct_rs to include only resources of this category, None is all, str\n    takes ct_flow to include only 'prod' or 'cons', None is both, str\n        eg get_power_grp('hh', 1, 'es') \n            gets prosumed power es of second hh in magg['hh']\n    returns power in 1,K ndarray, and 1,K zeros if no such resource(s)\n    side-effect: reads from mrss,magg,mmap\n    \"\"\"\n    if ct_grp not in magg:\n        raise ValueError(f\"ct_grp '{ct_grp}' not in magg\")\n    ret_val = np.zeros( (Resource.K) )\n    if j is None:#get rss of all j\n        allr_of_js = magg[ct_grp]\n    else:#get rss of j\n        allr_of_js = [magg[ct_grp][j]]\n    for allr_of_j in allr_of_js:\n        for r in allr_of_j:\n            if r not in mmap:\n                raise KeyError(f'magg[{j}] has r={r}, which is not in mrss')\n            location = mmap[r]\n            rs = mrss[location[0]][location[1]]\n            if ct_rs is not None and ct_rs != rs.ct:\n                continue\n            if rs.log_index_P is None:\n               # print('log_index_P',rs)\n                continue\n            tmp = rs.view[rs.log_index_P]#select power\n            if ct_flow is None:\n                ret_val += tmp\n            elif ct_flow == 'prod':\n                ret_val += np.where(tmp > 0, tmp, 0)\n            elif ct_flow == 'cons':\n                ret_val += np.where(tmp < 0, tmp, 0)\n            else:\n                raise ValueError(f\"no such flow '{ct_flow}'\")\n    return ret_val\n```\n\n\n```python\ndef plot_cords(rsss, colors=None, is_latlon=False):\n    \"\"\"plots resources by their geospatial coordinates\n    \n    takes rsss list of resource lists, eg [[pv0,pv1,..],[ld]]\n    takes colors list, strings from matplotlib eg ['red','green',..]\n    takes is_latlon flag, bool\n    each rss list is offset to prevent overpainting dots\n    \"\"\"\n    fig, axs = plt.subplots(nrows=1, ncols=1, figsize=(4,4))\n    for rss,m in zip(rsss, range(len(rsss))):\n        cords = np.zeros( (len(rss), 2) )\n        for i in range(len(rss)):\n            cords[i] = [rss[i].cord1+m*3, rss[i].cord2+m*3]\n        if colors is None:\n            plt.scatter(cords[:,0], cords[:,1])\n        else:\n            if len(colors) != len(rsss):\n                raise ValueError(f'number of colors dont match number of rss')\n            plt.scatter(cords[:,0], cords[:,1], color=colors[m])\n    axs.set_aspect('equal')\n    axs.grid(True)\n    axs.set_title('resource locations [cord1, cord2]')\n    if is_latlon == True:\n        xticks = ax.get_xticks()\n        yticks = ax.get_yticks()\n        print((f'x_resolution {deg_to_arc(xticks[2] - xticks[1]):.0f}m ' +\n              f'y_resolution {deg_to_arc(yticks[2] - yticks[1]):.0f}m'))\n    plt.show()\n\ndef plot_logs(rss=[], nums=[], titles=[], use_area=True):\n    \"\"\"Plots one log per given resource. wraps plot_bar\n    takes rss resources, list\n    takes nums to pick one log of the resource at the same rss position, list\n    takes titles for log, optional, list of strings\n    takse use_area for fast area plot instead of bars, bool\n    \"\"\"\n    if type(rss) != list:\n        raise TypeError(f'rss bad type {type(rss)}')\n    if type(nums) != list:\n        raise TypeError(f'nums bad type {type(nums)}')\n    if len(rss) != len(nums):\n        raise ValueError(f'length not equal rss:{len(rss)} nums:{len(nums)}')\n    if len(titles) < len(rss):\n        titles.extend(['']*(len(rss)-len(titles)))\n    for rs, num in zip(rss, nums):\n        if num >= len(rs.log_titles):\n            print(f'num {num} out of bounds for {rs}')\n    logs =  [None] * len(rss)\n    for i,rs,idc,title in zip(range(len(rss)), rss, nums, titles):#pull logs out of rss\n        logs[i] = rs.view[idc]\n        titles[i] = rs.log_titles[idc] + ' ' + title\n    plot_bar(logs, titles, use_area)\n\ndef plot_bar(ys=[[]], titles=[''], use_area=False):\n    \"\"\"Plots multiple data series. wraps pyplot bar\n    takes list of y lists, eg [[1,2], [3,4]]\n    takes titles which get appended to each plot title; list of str\n    takes use_area to use area instead of bars, boolean\n    \"\"\"\n    if not isinstance(ys[0], Iterable):\n        raise TypeError(f\"'ys' not a list of lists, wrap even one y, eg [[1,2],], have {type(ys[0])}\")\n    if not isinstance(titles[0], Iterable):\n        raise TypeError(f\"'titles' not a list of lists, wrap even on one y, eg [[1,2],], have {type(titles[0])}\")\n    if len(titles) < len(ys):#extend for zip\n        titles.extend('-' * (len(ys)-len(titles)))\n\n    fig, axs = plt.subplots(len(ys),1, figsize=(15,len(ys)*2.5), sharex=True)\n    if not isinstance(axs,np.ndarray):\n        axs = np.array( [axs] )\n    for ax,y,title in zip(axs,ys,titles):\n        ax.set_title(title)\n        x = np.arange(len(y))\n        if use_area:\n            ax.fill_between(x, y, color='blue', alpha=0.3)\n        else:\n            ax.bar(x, y, width=1, align='edge', color='ghostwhite', edgecolor='grey')\n    plt.show()            \n```\n\n\n```python\ndef print_(keys_values):\n    \"\"\"verbose helper\"\"\"\n    line = ''\n    for key,value in keys_values:\n        if VERBOSE == 1:\n            line += f'{key}={value}, '\n        elif VERBOSE == 2:\n            line += f'{repr(key)}={repr(value)}, '\n    if line:\n        print(line)\n\ndef _views_to_mrss(mdata):\n    \"\"\"used internally, see function simulation_load\"\"\"\n    r_set = set()\n    for key, value in mrss.items():#set data\n        for i in range(len(value)):\n            view = mdata[key][i]#get slice of cuboid\n            mrss[key][i].set_view(view)#set to resource\n            if value[i].r in r_set:#check that r is unique\n                raise ValueError(f'r of {value[i]} already in use')\n            else:\n                r_set.add(value[i].r)\n            print_([[key, mrss[key][i]]])#ct_grp_rs\n            \ndef simulation_load(name):\n    \"\"\"push views of mdata into each resource\n    \n    takes name of binary file in load_store folder to load logs from.\n    ensure to have the same mrss/rs structure in place \n    from when it got saved, else mdata mismatches and errors.\n    rs internal states, except number of logs are irrelevant.\n    same mmap,magg not needed except when calling helpers, eg get_power\n    side-effect: writes to mrss,mdata\n    \"\"\"\n    global mdata\n    with open('load_store/' + name,\"rb\") as f:\n        mdata = pickle.load(f) \n    _views_to_mrss(mdata)\n            \ndef simulation_store(name): \n    \"\"\"saves mdata to file\n    \n    takes name to create file in load_store folder to binary dump.\n    overwrites existing file \n    \"\"\"\n    with open('load_store/' + name,\"wb\") as f:\n        pickle.dump(mdata,f)\n            \ndef simulation_init():\n    \"\"\"Generates references alias numpy-views from the data model\n    and saves them to each resource in the resource model.\n        eg mrss['hh_ld'][0].view[1] --views--> mdata['hh_ld'][0][1]\n        \n    Also generates lookup table mmap used internally for 'no-search'\n    in helper functions when associating resources to collections in magg.\n    returns mdata, mmap\n    side-effect: reads mdata, writes mrss\n    \"\"\"\n    mdata = {}\n    for key, value in mrss.items():#allocate data\n        if len(value) == 0:\n            print(f'please remove empty key {key} from mrss')\n        cuboid = np.zeros( (len(mrss[key]), len(mrss[key][0].log_titles), Resource.K) )\n        mdata[key] = cuboid\n    _views_to_mrss(mdata)\n    \n    mmap = {}\n    for key, value in mrss.items():#access map\n        for i in range(len(value)):\n            location = (key, i)\n            mmap[value[i].r] = location\n    return mdata, mmap        \n\ndef jump_back(k):\n    \"\"\"Calls jump() on each rs,\n    errors if at least one rs did not overwrite base class\n    \"\"\"\n    for key, value in mrss.items():\n        for rs in value:\n            print_([['k',k], [key, rs]])\n            rs.jump(Control.jump_to_k)\n    return Control.jump_to_k, None#reset flag\n            \ndef simulation_run(up_to_k, clear_output_=True):\n    \"\"\"Runs the simulation for simulated_time = K * kclock\n    takes up_to_k to run the simulation up to but excluding this value, int\n    side-effect write/read on mdata/mrss\n    \"\"\"\n    if 'ctrl' in mrss and next(iter(mrss.keys())) != 'ctrl':\n        raise KeyError(f\"key 'ctrl' in dict not first\")\n        \n    k = 0#global counter\n    time_start = time.time() \n    for key, value in mrss.items():#init round\n        for rs in value:\n            rs.init()\n            print_([['init','-'], [key, rs]])\n    while k < up_to_k:\n        for key, value in mrss.items():#rs step ahead of global count\n            for rs in value:\n                print_([['k',k], [key, rs]])\n                rs.step(k)#local step\n        if clear_output_:\n            clear_output(wait=True)\n        time_yet = (time.time() - time_start) / (k+1) * (up_to_k-k-1)#[s] elapsed time per step * steps_yet\n        print(f'progress k {k}  {k+1}/{up_to_k} {(k+1)/up_to_k*100:.0f}%  rem {time_yet/60:.2f}m')                \n        k += 1#progress global time\n        if Control.jump_to_k is not None:#jump requested\n            k,Control.jump_to_k = jump_back(k)\n    for key, value in mrss.items():#ended round, k == up_to_k\n        for rs in value:\n            rs.end(k)\n            print_([['k',k], [key, rs]])\n```\n\n\n```python\nclass Resource:\n    \"\"\"Base class to build grid components. \n    Each resource has a unique number r and is at simulation step _k.\n    The time-log aggregates simulation results for later analysis.\n    \"\"\"\n    K = None\n    kclock = None#[s] see notation \n    \n    def __init__(self, r, ct, cord1=0., cord2=0.):\n        \"\"\"takes r to identify resource, unique, int\n        takes ct to specify category of this resource, str\n        takes coordinates, float, optional;\n            cord1/cord2 for x/y or lon/lat\n        \"\"\"\n        assert Resource.K is not None, 'set K first'\n        assert Resource.kclock is not None, 'set kclock first'\n        self.r = r\n        self.ct = ct                \n        self.cord1 = cord1            \n        self.cord2 = cord2\n        self._k = 0\n        self.view = None#simulation_init\n\n    def __repr__(self):\n        return (f'Resource(r={self.r}, ct={self.ct}, ' +\n                f'cord1={self.cord1}, cord2={self.cord2}, K={self.K}, _k={self._k}, kclock={self.kclock})')\n    \n    def __str__(self):\n        return (f'Resource(r={self.r}, ct={self.ct}, cord1={self.cord2}, cord2={self.cord1})')\n\n    def set_view(self, view):\n        \"\"\"Hands in data each resource operates on; Done by simulation_init\n        \"\"\"\n        self.view = view\n        \n    def jump(self, k):\n        \"\"\"Set the state to k; to be overwritten by subclasses\n        takes k the timepoint to set the state to, k >= 0 and k <= current k\n        \n        Called after each resource concluded the last step and gets\n        reset to the state at jump_to_k ktime. \n        Ctrl is the first to be rolled back.\n        \"\"\"\n        raise NotImplementedError(f'on {self}')\n    \n    def init(self):\n        \"\"\"Called before simulation starts stepping\n        \"\"\"\n        \n    def end(self,K):\n        \"\"\"Called once after simulation ended, eg to assert etc\n        \"\"\"\n    def get_k(self):\n        \"\"\"Returns local k\n        \"\"\"\n        return self._k  \n    \n    def set_k(self, k):\n        \"\"\"Returns local k\n        \"\"\"\n        self._k = k\n    \n    def step(self, k):\n        \"\"\"Perform state transition and run local time behavior.\n        \n        Progress time on this resource to run step of global counter k\n        which runs it to k+1 ktime moving it 1 kspan forward\n        function to be sub-class @extended and called right at start\n        \"\"\"\n        if k != self._k:\n            raise ValueError((f'out-of-step self._k={self._k} != '+\n                              f'k={k}, please re-initialize resource model mrss'))\n        else:\n            self._k += 1\n            \nclass TimeSeries(Resource):\n    \"\"\"Predefined power specialized resource\n    \"\"\"\n    log_titles = (#number of logs read/written during simulation\n        'P_pros [W]',#0 := produced/consumed power\n        'E_pros [Ws]'#1 := produced/consumed energy\n    )\n    log_index_P = 0#logs index for power prosumed, else None\n    \n    def __init__(self, *args, **kwargs):\n        super(TimeSeries, self).__init__(*args, **kwargs)\n                           \n    def __repr__(self):#Optional\n        return (f'TimeSeries({super(TimeSeries, self).__repr__()}), ' +\n                f'log_index_P={self.log_index_P}, logs)')\n\n    def __str__(self):#Optional\n        return (f'TimeSeries({super(TimeSeries, self).__repr__()})')\n        \n    def jump(self, k):#Optional\n        \"\"\"see base class\"\"\"\n        local_k = self.get_k()\n        if k > local_k:\n            raise ValueError(f'k {k} greater than local k {local_k}')\n        if k < local_k:#rolling logs/variables back to k\n            self.view[1,k:] = 0\n            self.set_k(k)\n            \n    def step(self,k):\n        Resource.step(self, k)\n        E_prod = self.view[0,k] * Resource.kclock\n        self.view[1,k] = E_prod\n            \n\nclass Control(Resource):\n    \"\"\"Implements microgrid control logic, blueprint\n    \"\"\"\n    log_titles = ('P_foo [W]',\n                 )\n    log_index_P = None#index in log_titles that logs power prosumed\n    \n    jump_to_k = None#set simulation time back to/including k.\n    #eg current k is 10 and back to 5 makes all rss finish 10 and jump to 5\n    #useful for eg back-tracking; can be called multiple times; call anywhere in step()\n    \n    def __init__(self, **kwargs):\n        super(Control, self).__init__(**kwargs)\n        \n    def __repr__(self):\n        return (f'Control({super(Control, self).__repr__()})')\n\n    def __str__(self):\n        return (f'Control({super(Control, self).__repr__()})')\n    \n    def jump(self, k):\n        \"\"\"see base class\n        \"\"\"\n        local_k = self.get_k()\n        if k > local_k:\n            raise ValueError(f'unable to roll to future, k {k} greater than local k {local_k}')\n        if k == 0:\n            self.view[:,k:] = 0#jump all logs\n        elif k < local_k:\n            self.view[:,k:] = 0\n        self.set_k(k)\n    \n    def init(self):\n        print(f'simulation about to start')\n        \n    def end(self, K):\n        pass\n        \n    def step(self, k):\n        Resource.step(self, k)\n        \"\"\"place logic here, make sure to have energy conservation in==out\n        \"\"\" \n        P_bal = 0#energy conservation\n        #... place logic here\n        assert P_bal == 0, 'power inflow != outflow'\n```\n\n### Examples <a name=\"arg4Uezu\"></a>\n\n ### Scenario1: \n         The energy residual of one household is logged over one day.\n                +----------+\n                |   GRID   |\n                |    ^     |\n                |    |     |\n                |    v     |\n                |   LD     |\n                +----------+\n\n\n\n```python\nclass Control(Resource):\n    \"\"\"Implements microgrid control logic, blueprint\n    \"\"\"\n    log_titles = ('E_residual [Ws]',\n                 )\n    log_index_P = None#index in log_titles that logs power prosumed \n    jump_to_k = None\n    \n    def __init__(self, **kwargs):\n        super(Control, self).__init__(**kwargs)\n        \n    def step(self, k):\n        Resource.step(self, k)\n        \"\"\"place logic here, make sure to have energy conservation in==out\n        \"\"\" \n        P_bal = 0#energy conservation\n        P_bal += get_power_grp('hh', j=0, ct_rs='ld')[k]\n        self.view[0,k] = P_bal*Resource.kclock\n        P_bal -= P_bal#have it logged, now subtract from balance\n        assert P_bal == 0, 'power inflow != outflow'\n```\n\n\n```python\n%%time\nResource.K = 1440# one day on 60 seconds resolution\nResource.kclock = 60\nmrss = OrderedDict({\n    'ctrl': [Control(r=0,ct='ctrl',cord1=0,cord2=0), ],\n    'hh_ld': [TimeSeries(r=1,ct='ld'),],#load resource\n})\nmagg = {\n    'hh': [[0,1],],\n}\nmdata, mmap = simulation_init()\nmdata['hh_ld'][0] = np.genfromtxt('time_series/lpg/000.csv', delimiter=\",\")[:1440]*-1\nsimulation_run(up_to_k=Resource.K, clear_output_=True)\n```\n\n    progress k 1439  1440/1440 100%  rem 0.00m\n    CPU times: user 7.57 s, sys: 788 ms, total: 8.36 s\n    Wall time: 7.9 s\n\n\n\n```python\nrs = get_rss('hh', j=0, ct_rs='ctrl')[0]\nplot_logs(rss=[rs], nums=[0], titles=[''])\n```\n\n\n```python\n\n```\n\n ### Scenario2: \n         One household self-charges his battery to achieve maximum \n         self-consumption on its PV system. Wiring:\n               +--------------------+\n               |             GRID   |\n               |              |     |\n               |PV+-->INV+--->x<->ES|\n               |              v     |\n               |             LD     |\n               +--------------------+\n\n\n\n```python\nclass Inverter(Resource):\n    \"\"\"Used to model inverter loss DC/AC conversion, true power;\n    Device not source nor sink, so in/outflow have the same sign.\n    Choose P_set sign arbitrayly but consistent, eg >0: DC/AC <0:AC/DC,\n    so to indicate flow direction alias >0:inverter <0:rectifier,\n    behaviour for +/- on P_set the same;     \n    \n    [1] doi 10.3390/en8064853 model and parameters\n    [2] https://www.researchgate.net/publication/319351878\n    \"\"\"\n    log_titles = (#number of logs read/written during simulation\n        'P_set [W]',#0 := power inflow, \n        'P_loss [W]'#1 := power loss reducing power outflow\n    )\n    log_index_P = 1#logs index for power prosumed, inverter is a 'consumer'\n    \n    def __init__(self, P_nom, CC, *args, **kwargs):\n        \"\"\"takes P_nom nominal power, float, + or -\"\"\"\n        super(Inverter, self).__init__(*args, **kwargs)\n        self.P_nom_abs = abs(P_nom)#soft/hard upper bound\n        self.CC_A = CC[0]\n        self.CC_B = CC[1]\n        self.CC_C = CC[2]\n        self.P_loss = None\n            \n    def __repr__(self):\n        return (f'Inverter({super(Inverter, self).__repr__()}), ' +\n                f'log_index_P={self.log_index_P}, logs)')\n\n    def __str__(self):\n        return (f'Inverter({super(Inverter, self).__repr__()})')\n    \n    def get_eff(self,k):\n        \"\"\"returns efficiency [0;1] for P_set; \n        do set P_set at k ktime before calling\n        \"\"\"\n        P_set = self.view[0,k]\n        if P_set == 0:\n            return 1e-3\n        else:\n            return (abs(P_set) + self.P_loss) / abs(P_set)\n        \n    def rollback(self, k):\n        \"\"\"see base class\"\"\"\n        local_k = self.get_k()\n        if k > local_k:\n            raise ValueError(f'unable to roll to future, k {k} greater than local k {local_k}')\n        if k < local_k:#rolling logs/variables back to k\n            self.view[:,k:] = 0\n            self.set_k(k)\n            \n    @staticmethod\n    def _lookup_eff(P_out):\n        \"\"\"returns eff for given abs(P_out) inverter outflow\n        lookup tables are precalculated for given inverter\n        CC_i in simulation are all the same, so one lookup suff.\n        side-effect: read from lookup_P_out and lookup_eff\n        \"\"\"\n        idx = (np.abs(lookup_P_out - P_out)).argmin()#nearest\n        eff = lookup_eff[idx]\n        if eff == 0:\n            eff = 1e-3#cvent div0, even on low P_out since lookup nearest\n        return eff\n    \n    def _get_eff(self, P_set):\n        \"\"\"calculate eff, corresponds to the backwards lookup\"\"\"\n        eff = self.CC_A * P_set / (self.CC_B - P_set) + self.CC_C * P_set\n        return eff\n\n    def set_P_by_out(self,k, P_out):\n        \"\"\"Set inflow for given outflow\n        eff from external lookup table (for now)\n        returns self\n        \"\"\"\n        P_out_abs = abs(P_out)\n        eff = Inverter._lookup_eff(P_out_abs)\n        self.P_loss = (1/eff - 1) * P_out_abs *-1#loss convention\n        P_set = self.P_loss*-1*math.copysign(1,P_out) + P_out\n        if abs(P_set) > self.P_nom_abs and False:#and TRUE to not allow P_nom exceed\n            raise ValueError(f'Inverter P_set={P_set} exceeds P_nom_abs={self.P_nom_abs}')\n        self.view[0,k] = P_set\n        self.view[1,k] = self.P_loss\n        return self\n        \n    def set_P(self,k, P_set):\n        \"\"\"Sets the power inflow\n        returns self\n        \"\"\"\n        if abs(P_set) > self.P_nom_abs and False:#s.a.\n            raise ValueError(f'Inverter P_set={P_set} exceeds P_nom_abs={self.P_nom_abs}')\n        if P_set == 0:\n            eff = 1\n        else:\n            eff = self._get_eff(abs(P_set))\n        self.P_loss = (1 - eff) * abs(P_set) *-1#loss convention\n        self.view[0,k] = P_set\n        self.view[1,k] = self.P_loss\n        return self\n            \n    def step(self,k):\n        Resource.step(self, k)\n        #loss precalculated when set\n```\n\n\n```python\nclass BatteryRPL(Resource):\n    \"\"\"Prosumage specialized resource with three states charge/discharge/idle    \n    \n    BatteryRPL rewrites the loss of BatteryR from constant to a percentage of \n    the current soc. This models the effect of increased loss on high socs\n    \n    Furthermore it adds idle losses to charge,discharge powers equal or\n    below pivot_P_idle. This models the effect of idle loss when 'about' idle.\n    \n    Since the model/parameters are highly depended on the batt/circuit/env,\n    abstraction prevents misconfig, yet models relevant effects for scheduling.\n\n    Maximum charge/discharge power = function(soc)\n    Idle loss = percent * current_soc\n    Efficiency = constant\n\n    [0] http://science.sciencemag.org/content/334/6058/928\n    [1] http://dx.doi.org/10.1016/j.jpowsour.2012.10.060\n    [2] https://doi.org/10.1016/j.electacta.2017.10.153\n    [3] https://www.researchgate.net/publication/319351878\n    [4] https://doi.org/10.1007/s11465-018-0516-8\n    \"\"\"\n    log_titles = ('P_ext [W]',#1 := P_ext produced/consumed power\n                  'E_ext [Ws]',#2 := E_ext produced/consumed energy\n                  'E_loss [Ws]',#3 := E_loss energy loss, be it charge/discharge/idle\n                  'E_soc [Ws]',#4 := E_soc total energy stored at k ktime\n                 )\n    log_index_P = 0#index in log_titles that logs power prosumed\n    \n    def __init__(self, E_soc, E_soc_max, P_ch_const, P_dch_const, pct_dch_idle,  eff_rt, pivot_soc_dch=0, *args, **kwargs):\n        \"\"\"constructor for initial state\n        takes E_soc and E_soc_max for initial and maximum state of charge, <=0\n        takes P_ch_const and P_dch_const for desired charge/discharge\n            these are eventually undercut but not exceeded\n        takes pct_dch_idle percent of current soc before the step to assign to loss\n        takes eff_rt round-trip efficiency to simulate loss, [0;1]\n        \"\"\"\n        assert E_soc <= 0 and E_soc >= E_soc_max, 'bad args'\n        assert P_ch_const <= 0 and P_dch_const >= 0, 'bad args'\n        assert eff_rt <= 1 and eff_rt >= 0, 'bad args'\n        \n        super(BatteryRPL, self).__init__(*args, **kwargs)\n        self.E_soc = float(E_soc)\n        self.E_soc_max = float(E_soc_max) \n        self.P_ext = None\n        self.E_ext = None\n        self.E_loss = None\n        self.P_ch_const = float(P_ch_const)\n        self.P_dch_const = float(P_dch_const)        \n        self.P_set = 0#fix, use set_P\n\n        \"\"\"Charge and discharge power are limited for operational safety\n        Charge power is constant, but linearly decreases if pivot_soc_ch exceeded.\n        Discharge power is constant, but instant 0 if pivot_soc_dch undercut.\n        \n        power ch   |---linear increase--|---------const--------|\n        soc        soc_max              pivot_soc_ch*          0\n        power dch  |------------const----------|-------0-------|\n        soc        soc_max                     pivot_soc_dch*  0\n        \"\"\"\n        self.pivot_soc_ch = 0.9#[0;1]\n        self.pivot_soc_dch = pivot_soc_dch#[0;1]\n        self.pivot_P_ch = 1/3#[0;1] of P_ch_const to charge at soc_max\n        self.P_ch_max = np.zeros( (1,2) )#P_dch_max for [eff_pivot, eff_rt]\n        self.P_dch_max = np.zeros( (1,2) )\n\n        \"\"\"Idle losses are a fraction of the current soc, positive float\"\"\"\n        self.pct_dch_idle = abs(float(pct_dch_idle))\n        \n        \"\"\"charge and discharge efficiency instant-drops on low power rate\n        Charge/discharge are subject to loss of eff_pivot or sqrt(eff_rt)\n        \n        eff      |---------sqrt(eff_rt)--------|-----+idle-----|\n        power    P_ch/dch_const                pivot_P_idle    0\n        \"\"\"\n        self.pivot_P_idle = abs(10.)#inspired by [3]\n        self.eff_rt = float(eff_rt)\n        \n        self.update_max_ch_dch_power()\n       \n    def __repr__(self):#verbose\n        return (f'BatteryRPL({super(BatteryRPL, self).__repr__()}, ' +\n                f'E_soc={self.E_soc}, E_soc_max={self.E_soc_max}, '+\n                f'E_ext={self.E_ext}, E_loss={self.E_loss}, '+\n                f'P_ch_const={self.P_ch_const}, P_dch_const={self.P_dch_const}, '+\n                f'P_set={self.P_set}, pivot_soc_ch={self.pivot_soc_ch}, '+\n                f'pivot_soc_dch={self.pivot_soc_dch}, pivot_P_ch={self.pivot_P_ch}, '+\n                f'P_ch_max={self.P_ch_max}, P_dch_max={self.P_dch_max}, '+\n                f'pct_dch_idle={self.pct_dch_idle}, pivot_P_idle={self.pivot_P_idle}, '+\n                f'eff={self.eff_rt}, log_index_P={self.log_index_P}, logs)')\n    \n    def __str__(self):\n        return f'BatteryRPL({super(BatteryRPL, self).__repr__()})'\n        \n    def rollback(self, k):\n        \"\"\"see base class\"\"\"\n        local_k = self.get_k()\n        if k > local_k:\n            raise ValueError(f'unable to roll to future, k {k} greater than local k {local_k}')\n        if k == 0:\n            self.P_set = 0\n            self.P_ext = None\n            self.E_ext = None\n            self.E_loss = None\n            self.E_soc = self.view[3,0]#from start\n        elif k < local_k:#rolling logs/variables back to k\n            self.P_set = self.view[0,k-1]#same as P_ext\n            self.P_ext = self.view[0,k-1]\n            self.E_ext = self.view[1,k-1]\n            self.E_loss = self.view[2,k-1]\n            self.E_soc = self.view[3,k]#from k\n        self.view[:,k:] = 0\n        self.set_k(k)\n        self.update_max_ch_dch_power()\n\n    def set_P(self, k, P_set):\n        \"\"\"charge/discharge/idle power -/+/0 respectively, int/float\n        \n                |---P_ch----|---P_dch---|\n                P_ch_max   -0+          P_dch_max\n        \"\"\"\n        P_set = float(P_set)\n        self.view[0, k] = P_set#expose right after set but before step for get_power(_grp)\n        if P_set >= self.P_ch_max and P_set <= self.P_dch_max:\n            self.P_set = P_set\n        else:\n            raise ValueError((f'limits exceeded ' +\n                f'ch<=have<=dch {self.P_ch_max}<={P_set}<={self.P_dch_max}'))\n\n    def update_max_ch_dch_power(self):\n        #charge limits pysical\n        if self.E_soc == self.E_soc_max:#full limit\n            self.P_ch_max = 0\n        elif self.E_soc <= self.pivot_soc_ch * self.E_soc_max:#pivot reached\n            \"\"\"linear function interpolating charging power between two points\n            (E_soc_max,pivot_P_ch*P_ch_const) (pivot_soc_ch*E_soc_max,P_ch_const)\n            \"\"\"\n            m = ((self.P_ch_const - self.pivot_P_ch * self.P_ch_const) / \n                 (self.pivot_soc_ch * self.E_soc_max - self.E_soc_max))\n            t = (self.P_ch_const - m * self.pivot_soc_ch * self.E_soc_max)\n            self.P_ch_max = m * self.E_soc + t\n        else:\n            self.P_ch_max = self.P_ch_const\n            \n        #charge limits discretization\n        P_ch_max_suff = (self.E_soc_max - self.E_soc) / math.sqrt(self.eff_rt) / Resource.kclock\n        \n        #charge limits, necessary and sufficient\n        self.P_ch_max = max(self.P_ch_max, P_ch_max_suff)*(1-1e-9)#prevent flip soc>0 \n        \n        #discharge limits pysical\n        if self.E_soc >= self.pivot_soc_dch * self.E_soc_max:#pivot reached\n            self.P_dch_max = 0\n        else:#necessary\n            self.P_dch_max = self.P_dch_const\n            \n        #discharge limits discretization, sufficient\n        P_dch_max_suff = -1 * self.E_soc * math.sqrt(self.eff_rt) / Resource.kclock\n        \n        #discharge limits, necessary and sufficient\n        self.P_dch_max = min(self.P_dch_max, P_dch_max_suff)*(1-1e-9) \n        if self.P_dch_max < 25:\n            self.P_dch_max = 0\n            \n    def step(self,k):\n        Resource.step(self, k)\n        E_ext = self.P_set * Resource.kclock#externally prosumed\n                            \n        self.view[3,k] = self.E_soc#at k ktime\n        eff = math.sqrt(self.eff_rt)\n        \n        if self.P_set > 0:#discharge\n            self.P_ext = self.P_set\n            self.E_ext = E_ext \n            self.E_loss = (E_ext / eff - E_ext) * -1#loss sign convention\n            self.E_soc += E_ext / eff\n        elif self.P_set < 0:#charge\n            self.P_ext = self.P_set\n            self.E_ext = E_ext\n            self.E_loss = E_ext * (1 - eff)\n            self.E_soc += E_ext * eff                \n        elif self.P_set == 0:#idle\n            self.P_ext = 0\n            self.E_ext = 0\n            self.E_loss = self.pct_dch_idle * self.E_soc\n            self.E_soc += self.pct_dch_idle * self.E_soc * -1\n        \n        if self.P_set != 0 and abs(self.P_set) <= self.pivot_P_idle:#add idle loss on low ch/dch P\n            self.E_loss += self.pct_dch_idle * self.E_soc\n            self.E_soc += self.pct_dch_idle * self.E_soc * -1\n        \n        assert self.E_soc <= 0, 'soc flipped'#probably prec. err\n        assert abs(self.E_soc - (self.view[3,k] + self.E_ext + self.E_loss*-1))<1e-6#energy conservation\n        \n        if self.E_soc > -1e-9:#classify as loss\n            self.E_loss += self.E_soc\n            self.E_soc = 0\n            \n        #log to data store, at k kspan\n        self.view[0,k] = self.P_ext\n        self.view[1,k] = self.E_ext\n        self.view[2,k] = self.E_loss \n        \n        #transition done, forward simulation time on device                               \n        self.update_max_ch_dch_power()\n```\n\n\n```python\n# curve-fit inverter\nfrom scipy.optimize import curve_fit\ndef func(x, a, b, c):\n    return a*x / (b-x) + c*x\nxdata = np.array([0, 10, 100, 1000, 2000, 5000, 1e4])\nydata = np.array([0, 0.1, 0.45, 0.97, 0.94, 0.92, 0.8])\npopt, pcov = curve_fit(func, xdata, ydata) #inverter coeff ABC\n```\n\n\n```python\n# idle for battery\npct_dch_idle = 1-(95/100)**(1/(30*24*60))# 5% idle loss over the month to 1min kclock\nsoc = -10\nfor k in range(30*24*60):#verify\n    soc = soc * (1 - pct_dch_idle)\nprint(f'start {-10}kWh, end month {soc:.3}kWh, {1-soc/-10:.2}%, pct_dch_idle {pct_dch_idle*1e2:.3}%/min')\n```\n\n    start -10kWh, end month -9.5kWh, 0.05%, pct_dch_idle 0.000119%/min\n\n\n\n```python\nclass Control(Resource):\n    \"\"\"Implements microgrid control logic, blueprint\n    \"\"\"\n    log_titles = ('P_j_inv_out [W]',\n                  'P_j_res [W]',\n                 )\n    log_index_P = None#index in log_titles that logs power prosumed \n    jump_to_k = None\n    \n    def __init__(self, **kwargs):\n        super(Control, self).__init__(**kwargs)\n        \n    def step(self, k):\n        Resource.step(self, k)\n        \"\"\"place logic here, make sure to have energy conservation in==out\n        \"\"\" \n        P_bal = 0#energy conservation\n\n        P_j_pv = get_power_grp('hh', j=0, ct_rs='pv')[k]\n        P_j_ld = get_power_grp('hh', j=0, ct_rs='ld')[k]\n        rs_inv = get_rss('hh', j=0, ct_rs='inv')[0]#unpack the only inv\n        rs_es = get_rss('hh', j=0, ct_rs='es')[0]#unpack the only es\n        \n        P_j_pv_inv = rs_inv.set_P(k, P_j_pv).get_eff(k) * P_j_pv#reduced by inv. loss\n        P_j_res = P_j_pv_inv + P_j_ld\n        \n        if P_j_res > 0:#oversupply\n            if P_j_res > rs_es.P_ch_max*-1:#if unable to consume oversupply\n                rs_es.set_P(k, rs_es.P_ch_max)\n                self.view[1,k] = P_j_res + rs_es.P_ch_max#left overs flow to extern\n            else:\n                rs_es.set_P(k, P_j_res*-1)#residual zeroed\n        else:#undersupply\n            if P_j_res*-1 > rs_es.P_dch_max:\n                rs_es.set_P(k, rs_es.P_dch_max)\n                self.view[1,k] = P_j_res + rs_es.P_dch_max#inflow from extern\n            else:\n                rs_es.set_P(k, P_j_res*-1)#residual zeroed\n                \n        self.view[0,k] = P_j_pv_inv#log inverter output\n        assert P_bal == 0, 'power inflow != outflow'\n```\n\n\n```python\n%%time\nResource.K = 1440# one day on 60 seconds resolution\nResource.kclock = 60\nmrss = OrderedDict({\n    'ctrl': [Control(r=0,ct='ctrl',cord1=0,cord2=0), ],\n    'hh_ld': [TimeSeries(r=1,ct='ld'),],#load resource\n    'hh_pv': [TimeSeries(r=2,ct='pv')],\n    'hh_inv': [Inverter(r=3,ct='inv',P_nom=3500, CC=popt)],\n    'hh_es': [BatteryRPL(r=4,ct='es',E_soc=-to_Ws(1),\\\n              E_soc_max=-to_Ws(5), P_ch_const=-4500,P_dch_const=5000,\\\n              pct_dch_idle=pct_dch_idle, eff_rt=0.9), ],\n})\nmagg = {\n    'hh': [[0,1,2,3,4],],\n}\nmdata, mmap = simulation_init()\nmdata['hh_ld'][0] = np.genfromtxt('time_series/lpg/000.csv', delimiter=\",\")[:1440]*-1 #!negative\nmdata['hh_pv'][0] = np.genfromtxt('time_series/crest/pv_1qm_clearness_index_varies.csv', delimiter=\",\").transpose()[0,:1440]*10#10qm\nsimulation_run(up_to_k=Resource.K, clear_output_=True)\n```\n\n    progress k 1439  1440/1440 100%  rem 0.00m\n    CPU times: user 9.24 s, sys: 1.01 s, total: 10.2 s\n    Wall time: 10 s\n\n\n\n```python\n\nctrl = get_rss('hh', j=0, ct_rs='ctrl')[0]\nes = get_rss('hh', j=0, ct_rs='es')[0]\nplot_logs(rss=[ctrl,ctrl,es], nums=[0,1,3], titles=['','', ''])\n```\n\n\n```python\n\n```\n\n ### Scenario3: \n    Two households balance their load on one shared battery. They try to balance out supply and demand for maximum SSR and SCR\n        +-----------------------------------------+\n        |                                         |\n        |                 +----------------+GRID  |\n        |                 |                |      |\n        | PV+-->INV+----+-+  PV+-->INV+--->x<->ES |\n        |               v                  v      |\n        |              LD                 LD      |\n        +-----------------------------------------+\n\n\n```python\nclass Control(Resource):\n    \"\"\"Implements microgrid control logic, blueprint\n    \"\"\"\n    log_titles = ('P_J_inv_out [W]',\n                  'P_J_res [W]',\n                 )\n    log_index_P = None#index in log_titles that logs power prosumed \n    jump_to_k = None\n    \n    def __init__(self, **kwargs):\n        super(Control, self).__init__(**kwargs)\n        \n    def step(self, k):\n        Resource.step(self, k)\n        \"\"\"place logic here, make sure to have energy conservation in==out\n        \"\"\" \n        P_bal = 0#energy conservation\n\n        P_j0_pv = get_power_grp('hh', j=0, ct_rs='pv')[k]\n        P_j1_pv = get_power_grp('hh', j=1, ct_rs='pv')[k]\n        P_J_ld = get_power_grp('hh', j=None, ct_rs='ld')[k]\n        rs_j0_inv = get_rss('hh', j=0, ct_rs='inv')[0]\n        rs_j1_inv = get_rss('hh', j=1, ct_rs='inv')[0]\n        rs_es = get_rss('hh', j=1, ct_rs='es')[0]\n        \n        P_j0_pv_inv = rs_j0_inv.set_P(k, P_j0_pv).get_eff(k) * P_j0_pv\n        P_j1_pv_inv = rs_j1_inv.set_P(k, P_j1_pv).get_eff(k) * P_j1_pv\n        P_J_res = P_j0_pv_inv + P_j1_pv_inv + P_J_ld\n        \n        if P_J_res > 0:#oversupply\n            if P_J_res > rs_es.P_ch_max*-1:#if unable to consume oversupply\n                rs_es.set_P(k, rs_es.P_ch_max)\n                self.view[1,k] = P_J_res + rs_es.P_ch_max#left overs flow to extern\n            else:\n                rs_es.set_P(k, P_J_res*-1)#residual zeroed\n        else:#undersupply\n            if P_J_res*-1 > rs_es.P_dch_max:\n                rs_es.set_P(k, rs_es.P_dch_max)\n                self.view[1,k] = P_J_res + rs_es.P_dch_max#inflow from extern\n            else:\n                rs_es.set_P(k, P_J_res*-1)#residual zeroed\n                \n        self.view[0,k] = P_j0_pv_inv + P_j1_pv_inv#log total inverter output\n        assert P_bal == 0, 'power inflow != outflow'\n```\n\n\n```python\n%%time\nResource.K = 1440# one day on 60 seconds resolution\nResource.kclock = 60\nmrss = OrderedDict({\n    'ctrl': [Control(r=0,ct='ctrl',cord1=0,cord2=0), ],\n    'hh_ld': [TimeSeries(r=1,ct='ld'),TimeSeries(r=5,ct='ld')],#load resource\n    'hh_pv': [TimeSeries(r=2,ct='pv'),TimeSeries(r=6,ct='pv')],\n    'hh_inv': [Inverter(r=3,ct='inv',P_nom=3500, CC=popt), Inverter(r=7,ct='inv',P_nom=3500, CC=popt)],\n    'hh_es': [BatteryRPL(r=4,ct='es',E_soc=-to_Ws(0),\\\n              E_soc_max=-to_Ws(5), P_ch_const=-4500,P_dch_const=5000,\\\n              pct_dch_idle=pct_dch_idle, eff_rt=0.9), ],\n})\nmagg = {\n    'hh': [[5,6,7], [0,1,2,3,4]],\n}\nmdata, mmap = simulation_init()\nmdata['hh_ld'][0] = np.genfromtxt('time_series/lpg/000.csv', delimiter=\",\")[:1440]*-1\nmdata['hh_ld'][1] = np.genfromtxt('time_series/lpg/001.csv', delimiter=\",\")[:1440]*-1\nmdata['hh_pv'][0] = np.genfromtxt('time_series/crest/pv_1qm_clearness_index_varies.csv', delimiter=\",\").transpose()[0,:1440]*10#10qm\nmdata['hh_pv'][1] = np.genfromtxt('time_series/crest/pv_1qm_clearness_index_varies.csv', delimiter=\",\").transpose()[0,:1440]*20#15qm\nsimulation_run(up_to_k=Resource.K, clear_output_=True)\n```\n\n    progress k 1439  1440/1440 100%  rem 0.00m\n    CPU times: user 13 s, sys: 956 ms, total: 13.9 s\n    Wall time: 13.8 s\n\n\n\n```python\n\nctrl = get_rss('hh', j=1, ct_rs='ctrl')[0]\nes = get_rss('hh', j=1, ct_rs='es')[0]\nplot_logs(rss=[ctrl,ctrl,es], nums=[0,1,3], titles=['','', ''], use_area=True)\n```\n\n\n```python\nplot_bar([get_power_grp('hh', ct_rs='ld')[700:1000]], ['total load [W] k700:k1000'])\n```\n\n#### Powerful queries allow verifying the community SSR right away:\n\n\n```python\nf\"The SSR of the community is {get_param(param='SSR', ct_grp='hh')} of total consumed {to_kWh(get_power_grp('hh', ct_flow='cons')*Resource.kclock).sum():.6f}kWh incl. loss\"\n```\n\n\n\n\n    'The SSR of the community is 0.5104408306646335 of total consumed -46.075771kWh incl. loss'\n\n\n\n\n```python\nres = get_power_grp('hh')\nE_J_res = to_kWh(res[res<0].sum() * Resource.kclock)\nE_J_cons = to_kWh((get_power_grp('hh', ct_flow='cons').sum()) * Resource.kclock)\n1-E_J_res/E_J_cons#same as above, fin\n```\n\n\n\n\n    0.5104408306646335\n\n\n\n\n```python\nto_kWh((get_power_grp('hh', ct_flow='prod').sum()) * Resource.kclock),\\\nto_kWh((get_power_grp('hh', ct_rs='pv').sum()) * Resource.kclock),\\\nto_kWh((get_power_grp('hh', ct_rs='es', ct_flow='prod').sum()) * Resource.kclock)#prod = pv + es_dch\n```\n\n\n\n\n    (23.518954766188845, 19.949739499999996, 3.5692152661888437)\n\n\n\n\n```python\n\n```\n\n### Appendix <a name=\"aeZae4ai\"></a>\n\n#### Glossary <a name=\"aec2ieTe\"></a>\n    abbreviations\n        pv\t\tphotovoltaic system\n        es\t\tenergy storage system\n        soc\t\tstate of energy charge\n        inv     inverter\n        hh\t\thousehold\n        dof     degree of freedom\n        jpn     jupyter notebook\n        xfmr    transformer\n\n        E_\t\tenergy [Ws], \u2208 |R float\n        P_ \t\tpower [W], \u2208 |R float\n        C_\t\tcost, <0 negative cost is revenue, >0 is cost\n                    \u2208 |R float denoted in [curr]\n        c_\t\tcost per unit, \n                    \u2208 |R+ float, denoted in [curr/Ws]\n    sub-idices  \n        res\t\tresidual \n        prod    produced\n        cons    consumed\n        r       resource index\n        r=foo   selector, only resources of type foo\n        R      number of resources\n        const\tconstant\n        bal     balance\n        ctrl    control  \n        ch      charge\n        dch     discharge\n        J\t\tcollection size of ct_grp in aggregator model\n        j\t\tcollection/peer index, \u2208 [0;J-1]\n        <type>\tspecifier eg load|pv|es|res|... \n\n    time scale\n        k       simulation time counter, \u2208 [0;K-1]\n                increments each step to advance time\n        K\t\tnumber of simulation steps\n\n        kclock  step time, maps simulation time to clock-time, \u2208 |R or |N, [s]\n                describes time passed each step,\n                modifying the value is ok and changes granularity of the data\n\n                modifying its unit  requires resource adjustments\n                imported resource models with different step value/unit must\n                    be adjusted, eg 2[ms] model must step 500* per k if kclock 1[s]\n                common units are [s|m|h|d]\n        units are ktime, kspan, ctime, cspan for concrete k\n                at k ktime is a timepoint\n                at k kspan is one timespan and starts at k ktime\n                for k kspan is a timespan of length k with unspecified start\n\n        kr      used to specify relative timespans, see examples\n        ekE     divides k axis into epochs of length E \u2208 |N\n                e = int(k/E) converts k to epoch e\n                k = e*E      converts epoch e to k\n\n    sign convention\n        <0 := outflow alias consume or export\n        >0 := inflow alias produce or import\n        from system point of view consumer counting arrow system\n        from resource pov called producer counting arrow system\n        the system is a virtual construct only for energy conservation\n        the pysical grid would be a loss afflicted resource itself\n        loss is always negative, since it reduces the system's energy amount \n        +------------------+\n        | +--------+       |\n        | |resource|<-cons |<-imp\n        | +--------+->prod |->exp,\n        |  system          |\n        +------------------+\n\n    examples\n        P_k_res         of any k\n        P_K_res, P_res  for all k summarized\n        P_j_res         of any j\n        P_J_res         for all j summarized, since there are multiple J's it remains;\n        k2              simulation time after two steps 0-1-now\n                        in text called 2 ktime or 4 ctime with kclock=2\n        K * kclock      total simulated time in ctime\n        P_k10,j0,load   power load of peer 0 at ktime 10\n        P_j0,k1,pv      photovoltaic power of peer 0 at 1 ktime\n        P_j,k1,pv       photovoltaic power of unspecified peer at 1 ktime\n        P_j0:9,res      total residual power of peers [0;8]\n        P_J,res         total residual power of all peers\n                        time irrelevant/omitted or specified elsewhere\n        P_J,pv          total photovoltaic power of all peers\n        E_K,res         total residual energy over simulated time K kspan\n        P_r0,k1         power of resource with index 0 at 1 ktime\n        P_R             total power of all devices\n                        if peers hold all resources, == P_J,res\n        E_k10:20        energy sum over 10 kspan from k [10;19]\n        E_kr0:10        energy sum over 10 kspan; 'when' unkown\n        E_2k15          energy sum over 15 kspan from k [30;44]\n \n\n\n```latex\n%%latex\n\\begin{align}\nE_{k} & = \\intop_{k}^{k+kclock} P(t) dt = P_{k} * kclock\\\\\nE & = (P) * kclock = (\\sum_{k=1}^{K} P_{k}) * kclock = \\sum_{k=1}^{K} (P_{k} * kclock) \\\\\n\\end{align}\n```\n\n\n\\begin{align}\nE_{k} & = \\intop_{k}^{k+kclock} P(t) dt = P_{k} * kclock\\\\\nE & = (P) * kclock = (\\sum_{k=1}^{K} P_{k}) * kclock = \\sum_{k=1}^{K} (P_{k} * kclock) \\\\\n\\end{align}\n\n\n\n    energy power relation\n        due to discretization it is constant during kclock simplifying the integral.\n        energy/power calculations can be done distributive a*(b+c)= a*b+a*c \n\n\n```latex\n%%latex\n\\begin{align}\nP_{k,r} & = \\begin{cases}\n        P_{k,r,prod} \\quad & \\text{if } P_{k,r} \\geq 0 \\text{ producer}\\\\\n        P_{k,r,cons} \\quad & \\text{if } P_{k,r} < 0 \\text{ consumer}\\\\\n    \\end{cases}\\\\\nP_{k,r,res}  & = P_{k,r,prod} + P_{k,r,cons} \\\\    \n\\end{align}\n```\n\n\n\\begin{align}\nP_{k,r} & = \\begin{cases}\n        P_{k,r,prod} \\quad & \\text{if } P_{k,r} \\geq 0 \\text{ producer}\\\\\n        P_{k,r,cons} \\quad & \\text{if } P_{k,r} < 0 \\text{ consumer}\\\\\n    \\end{cases}\\\\\nP_{k,r,res}  & = P_{k,r,prod} + P_{k,r,cons} \\\\    \n\\end{align}\n\n\n\n    resource sign conventions, outflow positive, inflow negative\n        addon: P_k,r,res makes only sense if one resource has two ports.\n\n#### Power\n\n\n```latex\n%%latex\n\\begin{align} \nP_{k,j,prod} & = \\sum_{i=1}^{R \\land j} P_{k,j,i,prod} \\quad \\text{and}\\quad  P_{k,j,cons} = \\sum_{i=1}^{R \\land j} P_{k,j,i,cons}\\\\\nP_{k,j,res} & = P_{k,j,prod} + P_{k,j,cons} = \\sum_{i=1}^{R \\land j} P_{k,j,i} \\\\\nP_{J,res} & = \\sum_{j=1}^{J} P_{j,res}  \\quad \\text{and}\\quad \nP_{R,prod} = \\sum_{r=1}^{R} P_{r,prod}\\\\\n\\end{align}\n```\n\n\n\\begin{align} \nP_{k,j,prod} & = \\sum_{i=1}^{R \\land j} P_{k,j,i,prod} \\quad \\text{and}\\quad  P_{k,j,cons} = \\sum_{i=1}^{R \\land j} P_{k,j,i,cons}\\\\\nP_{k,j,res} & = P_{k,j,prod} + P_{k,j,cons} = \\sum_{i=1}^{R \\land j} P_{k,j,i} \\\\\nP_{J,res} & = \\sum_{j=1}^{J} P_{j,res}  \\quad \\text{and}\\quad \nP_{R,prod} = \\sum_{r=1}^{R} P_{r,prod}\\\\\n\\end{align}\n\n\n\n    power produced and consumed of peer j at k ktime over its own resource set \n    power residual of peer j at k ktime over its own resource set\n    total power of all peers at k ktime\n    total power of all resources at k ktime\n\n### Parameters<a name=\"si3Eitei\"></a>\n\n\n```latex\n%%latex\n\\begin{align}\nSSR_{k,j} & = 1 - \\frac{P_{k,j,res,cons}}{P_{k,j,cons}}\\\\\nSSR_{j} & = 1 - \\frac{P_{j,res,cons}}{P_{j,cons}}\\\\\nSCR_{k,j} & = 1 - \\frac{P_{k,j,res,prod}}{P_{k,j,prod}}\\\\ \nSCR_{j} & = 1 - \\frac{P_{j,res,prod}}{P_{j,prod}}\\\\       \n\\end{align}\n```\n\n\n\\begin{align}\nSSR_{k,j} & = 1 - \\frac{P_{k,j,res,cons}}{P_{k,j,cons}}\\\\\nSSR_{j} & = 1 - \\frac{P_{j,res,cons}}{P_{j,cons}}\\\\\nSCR_{k,j} & = 1 - \\frac{P_{k,j,res,prod}}{P_{k,j,prod}}\\\\ \nSCR_{j} & = 1 - \\frac{P_{j,res,prod}}{P_{j,prod}}\\\\       \n\\end{align}\n\n\n\n    self-sufficiency-rate of peer j at k ktime\n    self-sufficiency-rate of peer j for simulated time\n    analog the self-consumption rate \n\n\n```latex\n%%latex\n\\begin{align}\nSDR_{k,j} & = \\dfrac{ P_{k,j,prod} }{ -P_{k,j,cons} } \\quad \\text{if }  P_{k,j,cons} \\text{ not 0 else 1}\\\\\nSDR_{j} & = \\dfrac{ P_{j,prod} }{ -P_{j,cons} }\\\\\nSDR_{k} & = \\frac{ \\sum_{r=1}^{R} P_{k,r,prod} }{ -\\sum_{i=1}^{R} P_{k,r,cons} }\\\\\nSDR & = \\frac{ \\sum_{r=1}^{R} P_{r,prod} }{ -\\sum_{i=1}^{R} P_{r,cons} }\\\\         \n\\end{align}\n```\n\n\n\\begin{align}\nSDR_{k,j} & = \\dfrac{ P_{k,j,prod} }{ -P_{k,j,cons} } \\quad \\text{if }  P_{k,j,cons} \\text{ not 0 else 1}\\\\\nSDR_{j} & = \\dfrac{ P_{j,prod} }{ -P_{j,cons} }\\\\\nSDR_{k} & = \\frac{ \\sum_{r=1}^{R} P_{k,r,prod} }{ -\\sum_{i=1}^{R} P_{k,r,cons} }\\\\\nSDR & = \\frac{ \\sum_{r=1}^{R} P_{r,prod} }{ -\\sum_{i=1}^{R} P_{r,cons} }\\\\         \n\\end{align}\n\n\n\n    supply-demand-ratio of peer j at k ktime \n    supply-demand-ratio of peer j\n    the second two formulas remove the peer and use the r index to make a general statement\n\n\n```latex\n%%latex\n\\begin{align}\nRCR_{k} & = 1 - \\frac{ |\\sum_{j=1}^{J} P_{k,j,res}| }{ \\sum_{j=1}^{J} |P_{k,j,res}| }\\\\\nRCR_{k,j} & = 1 - \\frac{ |\\sum_{i=1}^{R \\land j} P_{k,r}| }{ \\sum_{i=1}^{R \\land j} |P_{k,r}| }\\\\\n\\end{align}\n```\n\n\n\\begin{align}\nRCR_{k} & = 1 - \\frac{ |\\sum_{j=1}^{J} P_{k,j,res}| }{ \\sum_{j=1}^{J} |P_{k,j,res}| }\\\\\nRCR_{k,j} & = 1 - \\frac{ |\\sum_{i=1}^{R \\land j} P_{k,r}| }{ \\sum_{i=1}^{R \\land j} |P_{k,r}| }\\\\\n\\end{align}\n\n\n\n    residual-cancellation-rate at k ktime\n        describes anticyclic relation of residual load, [0;1]\n        the closer to 1 the better peers complement each other in residual power;\n        describes destructive interference; if P_kJ_res = 0 the RCR_k is 1\n        example for RCR = 0 and RCR = 1\n            +---+         +---+\n            |j0 |         |j0 |\n            +-------+->   +--------->\n                |j1 | k   |j1 |     k\n                +---+     +---+\n    residual-cancellation-rate of peer j at k ktime\n        if P_k_Rofj = 0 the RCR_kj is 1\n\n\n```latex\n%%latex\n\\begin{align}\nGUR_{J} & = \\frac{ \\sum_{k=1}^{K} \\sum_{j=1}^{J} |P_{k,j,res}| }\n    { \\sum_{k=1}^{K} \\sum_{i=1}^{R \\land J} |P_{k,r}| }\\\\\n\\end{align}\n```\n\n\n\\begin{align}\nGUR_{J} & = \\frac{ \\sum_{k=1}^{K} \\sum_{j=1}^{J} |P_{k,j,res}| }\n    { \\sum_{k=1}^{K} \\sum_{i=1}^{R \\land J} |P_{k,r}| }\\\\\n\\end{align}\n\n\n\n    grid-utilization rate\n        measure for the percentage of energy flow over smart-meters from J subsystems in/out of the system; or\n        total absolute residual power of all peers (P_J_res) divided by total absolute power of peer rss; or\n        of all energyflow how much went over the grid\n\n#### Loss\n\n\n```latex\n%%latex\n\\begin{align}\nE_{k,r,loss} & = \\begin{cases}\n        E_{k,r,loss,ch} \\quad & \\text{if } P_{k,r,set} < 0 \\text{ charge loss and ct_rs='es'}\\\\\n        E_{k,r,loss,idle} \\quad & \\text{if } P_{k,r,set} = 0 \\text{ idle loss and ct_rs='es'}\\\\\n        E_{k,r,loss,dch} \\quad & \\text{if } P_{k,r,set} > 0 \\text{ discharge loss and ct_rs='es'}\\\\\n    \\end{cases}\\\\\n    \nE_{k,loss,es} & = \\sum_{i=1}^{|es|} E_{k,i,loss,es}\\\\\n\nE_{k,loss,es,idle} & = \\sum_{i=1}^{|es|} E_{k,i,loss,es,idle}\\\\\n\nE_{k,j,loss,es} & = \\sum_{i=1}^{|es|\\land j} E_{k,j,i,loss,es}\\\\\n\nE_{k,R,loss} & = \\sum_{r=1}^{R} E_{k,r,loss}\\\\\n\nE_{k,loss} & = E_{k,R,loss} + E_{k,loss,grid}\\\\\n\\end{align}\n```\n\n\n\\begin{align}\nE_{k,r,loss} & = \\begin{cases}\n        E_{k,r,loss,ch} \\quad & \\text{if } P_{k,r,set} < 0 \\text{ charge loss and ct_rs='es'}\\\\\n        E_{k,r,loss,idle} \\quad & \\text{if } P_{k,r,set} = 0 \\text{ idle loss and ct_rs='es'}\\\\\n        E_{k,r,loss,dch} \\quad & \\text{if } P_{k,r,set} > 0 \\text{ discharge loss and ct_rs='es'}\\\\\n    \\end{cases}\\\\\n    \nE_{k,loss,es} & = \\sum_{i=1}^{|es|} E_{k,i,loss,es}\\\\\n\nE_{k,loss,es,idle} & = \\sum_{i=1}^{|es|} E_{k,i,loss,es,idle}\\\\\n\nE_{k,j,loss,es} & = \\sum_{i=1}^{|es|\\land j} E_{k,j,i,loss,es}\\\\\n\nE_{k,R,loss} & = \\sum_{r=1}^{R} E_{k,r,loss}\\\\\n\nE_{k,loss} & = E_{k,R,loss} + E_{k,loss,grid}\\\\\n\\end{align}\n\n\n\n    energy loss of resource r of category 'es' at k kspan\n        since the es is only in one state, non-state losses are considered 0\n    total energy loss of all es at k kspan\n    total idle energy loss of all es at k kspan\n    total energy loss of peer j and its es at k kspan\n    total energy loss of all resources at k kspan\n    total energy loss of the system at k kspan\n\n#### Notebook version <a name=\"aeDae4ai\"></a>\n    \n\n\n```python\nfrom IPython.utils.sysinfo import get_sys_info\nget_sys_info()\n```\n\n\n\n\n    {'ipython_version': '7.2.0',\n     'ipython_path': '/home/user/.pyenv/versions/3.6.4/lib/python3.6/site-packages/IPython',\n     'commit_source': 'installation',\n     'commit_hash': '523ed2fe5',\n     'sys_version': '3.6.4 (default, Mar 26 2018, 14:15:50) \\n[GCC 6.3.0 20170516]',\n     'sys_executable': '/home/user/.pyenv/versions/3.6.4/bin/python3',\n     'sys_platform': 'linux',\n     'platform': 'Linux-4.9.0-9-amd64-x86_64-with-debian-9.9',\n     'os_name': 'posix',\n     'default_encoding': 'UTF-8'}\n\n\n\n#### License notice <a name=\"aeZGe4ai\"></a>\n\n    MIT License\n\n    Copyright (c) 2019\n        -----BEGIN PUBLIC KEY-----\n        MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtAgeP1hhQHBHPICTc2ho\n        vJFNXA2qtf0HjuXXV7i+imaN7RI4hUPQMo4nNCYjeiD3vzAdBTtWRQrI2ONmiFTk\n        ntAuD0Mg03q+mj/88aawnZbtXBF4QM5sYClInIuW23uhSq17SseWCXtEhmHtz155\n        4LllN4FBC11/R0shrAvFH4dAn2sM8PBg+FGze2wUaJbEl2rLe+qoek10krbSrpUP\n        VXCsyVyicR1IaOhldH4I8zpvB6CSPzOkzhQhbxRhxvKwN7kaVlzVGg2u3ccgffHP\n        dldIk2D14rz0hJ0Ix1qheAQW/+2haBP/lbwW2iLtiyC47sVeDbCpd66Zi9lKDUe4\n        nwIDAQAB\n        -----END PUBLIC KEY-----\n\n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files (the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights\n    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n    copies of the Software, and to permit persons to whom the Software is\n    furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in all\n    copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n    SOFTWARE.\n\n    https://tldrlegal.com/license/mit-license\n", "meta": {"hexsha": "772af64dbb078734e8ec6f42272cd86517afcbb5", "size": 223619, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "template.ipynb", "max_stars_repo_name": "simulator0/SIML", "max_stars_repo_head_hexsha": "bb812f218ffa0218f61c3193fdd722d418288244", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "template.ipynb", "max_issues_repo_name": "simulator0/SIML", "max_issues_repo_head_hexsha": "bb812f218ffa0218f61c3193fdd722d418288244", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "template.ipynb", "max_forks_repo_name": "simulator0/SIML", "max_forks_repo_head_hexsha": "bb812f218ffa0218f61c3193fdd722d418288244", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 96.8886481802, "max_line_length": 48736, "alphanum_fraction": 0.7728144746, "converted": true, "num_tokens": 19335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.05749328324142241, "lm_q1q2_score": 0.026505368272051303}}
{"text": "```python\n!pip install qiskit\n```\n\n    Collecting qiskit\n      Downloading qiskit-0.31.0.tar.gz (13 kB)\n    Collecting qiskit-terra==0.18.3\n      Downloading qiskit_terra-0.18.3-cp37-cp37m-manylinux2010_x86_64.whl (6.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.1 MB 4.3 MB/s \n    \u001b[?25hCollecting qiskit-aer==0.9.1\n      Downloading qiskit_aer-0.9.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (17.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 17.9 MB 108 kB/s \n    \u001b[?25hCollecting qiskit-ibmq-provider==0.17.0\n      Downloading qiskit_ibmq_provider-0.17.0-py3-none-any.whl (236 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 236 kB 59.1 MB/s \n    \u001b[?25hCollecting qiskit-ignis==0.6.0\n      Downloading qiskit_ignis-0.6.0-py3-none-any.whl (207 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 207 kB 61.3 MB/s \n    \u001b[?25hCollecting qiskit-aqua==0.9.5\n      Downloading qiskit_aqua-0.9.5-py3-none-any.whl (2.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.1 MB 44.0 MB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.16.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.9.1->qiskit) (1.19.5)\n    Requirement already satisfied: scipy>=1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.9.1->qiskit) (1.4.1)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (5.4.8)\n    Requirement already satisfied: scikit-learn>=0.20.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (0.22.2.post1)\n    Collecting dlx<=1.0.4\n      Downloading dlx-1.0.4.tar.gz (5.5 kB)\n    Requirement already satisfied: h5py<3.3.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (3.1.0)\n    Collecting retworkx>=0.8.0\n      Downloading retworkx-0.10.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.4 MB 25.6 MB/s \n    \u001b[?25hRequirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (1.7.1)\n    Collecting docplex>=2.21.207\n      Downloading docplex-2.22.213.tar.gz (634 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 634 kB 59.9 MB/s \n    \u001b[?25hRequirement already satisfied: fastdtw<=0.3.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (0.3.4)\n    Collecting yfinance>=0.1.62\n      Downloading yfinance-0.1.64.tar.gz (26 kB)\n    Collecting quandl\n      Downloading Quandl-3.6.1-py2.py3-none-any.whl (26 kB)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (1.1.5)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit) (57.4.0)\n    Collecting websocket-client>=1.0.1\n      Downloading websocket_client-1.2.1-py2.py3-none-any.whl (52 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 52 kB 1.3 MB/s \n    \u001b[?25hRequirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.17.0->qiskit) (2.8.2)\n    Collecting requests-ntlm>=1.1.0\n      Downloading requests_ntlm-1.1.0-py2.py3-none-any.whl (5.7 kB)\n    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.17.0->qiskit) (1.24.3)\n    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.17.0->qiskit) (2.23.0)\n    Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.18.3->qiskit) (2.6.0)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.18.3->qiskit) (0.3.4)\n    Collecting python-constraint>=1.4\n      Downloading python-constraint-1.4.0.tar.bz2 (18 kB)\n    Collecting tweedledum<2.0,>=1.1\n      Downloading tweedledum-1.1.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (943 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 943 kB 50.0 MB/s \n    \u001b[?25hCollecting fastjsonschema>=2.10\n      Downloading fastjsonschema-2.15.1-py3-none-any.whl (21 kB)\n    Collecting symengine>0.7\n      Downloading symengine-0.8.1-cp37-cp37m-manylinux2010_x86_64.whl (38.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 38.2 MB 20 kB/s \n    \u001b[?25hCollecting ply>=3.10\n      Downloading ply-3.11-py2.py3-none-any.whl (49 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 49 kB 5.5 MB/s \n    \u001b[?25hRequirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from docplex>=2.21.207->qiskit-aqua==0.9.5->qiskit) (1.15.0)\n    Requirement already satisfied: cached-property in /usr/local/lib/python3.7/dist-packages (from h5py<3.3.0->qiskit-aqua==0.9.5->qiskit) (1.5.2)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.17.0->qiskit) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.17.0->qiskit) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.17.0->qiskit) (2021.5.30)\n    Collecting cryptography>=1.3\n      Downloading cryptography-35.0.0-cp36-abi3-manylinux_2_24_x86_64.whl (3.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.5 MB 43.9 MB/s \n    \u001b[?25hCollecting ntlm-auth>=1.0.2\n      Downloading ntlm_auth-1.5.0-py2.py3-none-any.whl (29 kB)\n    Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.17.0->qiskit) (1.14.6)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.17.0->qiskit) (2.20)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.9.5->qiskit) (1.0.1)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-aqua==0.9.5->qiskit) (1.2.1)\n    Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance>=0.1.62->qiskit-aqua==0.9.5->qiskit) (0.0.9)\n    Collecting lxml>=4.5.1\n      Downloading lxml-4.6.3-cp37-cp37m-manylinux2014_x86_64.whl (6.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.3 MB 35.2 MB/s \n    \u001b[?25hRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->qiskit-aqua==0.9.5->qiskit) (2018.9)\n    Collecting inflection>=0.3.1\n      Downloading inflection-0.5.1-py2.py3-none-any.whl (9.5 kB)\n    Requirement already satisfied: more-itertools in /usr/local/lib/python3.7/dist-packages (from quandl->qiskit-aqua==0.9.5->qiskit) (8.10.0)\n    Building wheels for collected packages: qiskit, dlx, docplex, python-constraint, yfinance\n      Building wheel for qiskit (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for qiskit: filename=qiskit-0.31.0-py3-none-any.whl size=11728 sha256=0346e88c3b5d41d702210c5fdaa06fa25882205ddbcf06248b5cc9b87ecdd306\n      Stored in directory: /root/.cache/pip/wheels/29/dd/b2/1fe1a9ac92aaf75b267d893ae27329ea229f292a293017afc7\n      Building wheel for dlx (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for dlx: filename=dlx-1.0.4-py3-none-any.whl size=5719 sha256=f4fa4c8f5c2d22f558aaf278ee15a111c3ecdaa509178a7f7e2ecdfee2b97032\n      Stored in directory: /root/.cache/pip/wheels/78/55/c8/dc61e772445a566b7608a476d151e9dcaf4e092b01b0c4bc3c\n      Building wheel for docplex (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for docplex: filename=docplex-2.22.213-py3-none-any.whl size=696881 sha256=e1c9ae3341ebc8a15d68c12efbf4e4cc85df0d09017a0f3567b06a4a90bb7e90\n      Stored in directory: /root/.cache/pip/wheels/90/69/6b/1375c68a5b7ff94c40263b151c86f58bd72200bf0c465b5ba3\n      Building wheel for python-constraint (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for python-constraint: filename=python_constraint-1.4.0-py2.py3-none-any.whl size=24081 sha256=33a88dd9499894e36d087ca283cec58bf3b9c93c4a7efe13f42508504185e718\n      Stored in directory: /root/.cache/pip/wheels/07/27/db/1222c80eb1e431f3d2199c12569cb1cac60f562a451fe30479\n      Building wheel for yfinance (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for yfinance: filename=yfinance-0.1.64-py2.py3-none-any.whl size=24109 sha256=e44c0da528aa995dc07715788537e960f8eccb057aae075de34c35cdb3131a01\n      Stored in directory: /root/.cache/pip/wheels/86/fe/9b/a4d3d78796b699e37065e5b6c27b75cff448ddb8b24943c288\n    Successfully built qiskit dlx docplex python-constraint yfinance\n    Installing collected packages: tweedledum, symengine, retworkx, python-constraint, ply, fastjsonschema, qiskit-terra, ntlm-auth, lxml, inflection, cryptography, yfinance, websocket-client, requests-ntlm, quandl, qiskit-ignis, docplex, dlx, qiskit-ibmq-provider, qiskit-aqua, qiskit-aer, qiskit\n      Attempting uninstall: lxml\n        Found existing installation: lxml 4.2.6\n        Uninstalling lxml-4.2.6:\n          Successfully uninstalled lxml-4.2.6\n    Successfully installed cryptography-35.0.0 dlx-1.0.4 docplex-2.22.213 fastjsonschema-2.15.1 inflection-0.5.1 lxml-4.6.3 ntlm-auth-1.5.0 ply-3.11 python-constraint-1.4.0 qiskit-0.31.0 qiskit-aer-0.9.1 qiskit-aqua-0.9.5 qiskit-ibmq-provider-0.17.0 qiskit-ignis-0.6.0 qiskit-terra-0.18.3 quandl-3.6.1 requests-ntlm-1.1.0 retworkx-0.10.2 symengine-0.8.1 tweedledum-1.1.1 websocket-client-1.2.1 yfinance-0.1.64\n\n\n# General Tech Versions/Info\n- **Python:** 3.7.10\n- **Qiskit**: {'qiskit': '0.24.0',\n 'qiskit-aer': '0.7.6',\n 'qiskit-aqua': '0.8.2',\n 'qiskit-ibmq-provider': '0.12.1',\n 'qiskit-ignis': '0.5.2',\n 'qiskit-terra': '0.16.4'}\n- Run on Google Colab\n- Requires 20 qubits + 6 bits\n\n\n```python\nfrom qiskit import (\n    IBMQ,\n    QuantumCircuit,\n    execute,\n    Aer,\n    QuantumRegister, \n    ClassicalRegister,\n    transpile,\n)\n\nfrom qiskit.ignis.mitigation.measurement import complete_meas_cal, tensored_meas_cal, CompleteMeasFitter,TensoredMeasFitter\nfrom qiskit.test.mock import FakeSydney, FakeMontreal\nimport numpy as np\nimport math\nimport random\nimport time\nimport pandas as pd\n```\n\n\n```python\n# CNOT gates for applying the Steane Code\nCNOT_GATES = [[1,0], [1,4], [1,5], [2,0], [2,4], [2,6], [3,4], [3,5],[3,6],[7, 12],[7, 13],[8,7] ,[8, 11],[8, 12], [9,7],[9, 11],[9, 13],[10, 11],[10, 12],[10, 13]]\nREV_CNOT_GATES = [[10, 13],[10, 12],[10, 11],[9, 13],[9, 11],[9,7],[8, 12],[8, 11],[8,7],[7, 13],[7, 12],[3,6],[3,5],[3,4],[2,6],[2,4],[2,0],[1,5],[1,4],[1,0]]\n```\n\n#User Defined Values\n\nPlease edit these values before running on quantum computer:\n\n\n```python\n# COMPUTATION CONFIGURATIONS\nNUM_SHOTS = 1\nNUM_DIFF_PROGRAMS = 1\nNUM_ITERATIONS = 1\nNUM_RANDOM_ITERATIONS = 1\n\n# SPECIFY NUMBER OF RANDOM SEEDS FOR TRANSPILING QUANTUM CIRCUITS\nNUM_SEEDS = 150\n\n# SET PHYSICAL TO VIRTUAL QUBIT MAPPING OF QUANTUM MACHINE\nunpermuted_layout = [8,11,13,19,14,20,16,1,2,7,12,6,4,10]\nsyndrome_layout = [5,9,18,0,3,15]\n```\n\n\n```python\n# SET LOCATION FOR SAVING DATA\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\n# SET FILENAMES FOR DATA SAVING \nfilename_0 = \"/content/drive/My Drive/Results/general_info_20Q.txt\"\nfilename_error = \"/content/drive/My Drive/Results/error_results_20Q.csv\"\nfilename_mit = \"/content/drive/My Drive/Results/mit_results_20Q.csv\"\nfilename_decoded = \"/content/drive/My Drive/Results/decoded_results_20Q.csv\"\n\n# SET QUANTUM COMPUTER BACKEND OF YOUR CHOICE\nfake_mtrl = FakeMontreal()\n# BACKEND = AerSimulator.from_backend(fake_mtrl)\nBACKEND = Aer.get_backend('qasm_simulator')\n```\n\n    Mounted at /content/drive\n\n\n# Server Class (Main Code)\n\n\n```python\nclass Server():\n  def __init__(self):\n    print('Server initialized')\n\n  def generate_point(self, size=14):\n    \"\"\"\n    Generate a random point as password\n    \n    Parameters:\n    size (int): number of qubits in circuit to be encrypted\n    \n    Returns:\n    point (str): the combination of key1 and key2 in binary form\n    key1 ([int]): permutation key in integer form\n    key2 ([[int], [int]]): one-time pad component of the password, comprised of the x key and z key respectively\n    \"\"\"    \n    # get permutation key\n    bin_key1, key1 = self.generate_permutation_key()\n    # get OTP key\n    x_key = np.random.randint(2, size=size)\n    z_key = np.random.randint(2, size=size)\n    key2 = [x_key.tolist(), z_key.tolist()]\n    # combine keys to get point\n    a = ''.join(bin_key1)\n    b = ''.join(map(str, x_key.tolist()))\n    c = ''.join(map(str,z_key.tolist()))\n    point = a+b+c\n    return point, key1, key2\n  \n  def generate_permutation_key(self, size=14):\n    \"\"\"\n    Generate a random permutation of list(range(size))\n    \n    Parameters:\n    size (int): size of list \n    \n    Returns:\n    key ([str]): the permuted list in binary form\n    dec_key ([int]): the permuted list in decimal form\n    \"\"\"   \n    key_dec = list(range(size))\n    rng = np.random.default_rng()\n    rng.shuffle(key_dec)\n    f = '0' + str(math.ceil(math.log2(size))) + 'b'\n    # get the permutation in binary form\n    key = [format(x, f) for x in key_dec]\n    return key, key_dec\n\n  def sample_challenge_point(self, point, size=14): \n    \"\"\"\n    Sample a random point q from the distribution in which with approx.\n    probability 0.5, point (the parameter) is sampled, \n    and with approx. probability 0.5, a random point excluding point (the parameter) is uniformly chosen\n    \n    Parameters:\n    point (str): the point that will be sampled with probability 0.5 in the distribution\n    size (int): number of qubits that point encrypts for\n    \n    Returns:\n    sample (str): challenge point taken from distribution\n    \"\"\"   \n    # generate a random valid point that has a permutation and one-time pad keys\n    key1, key_dec = self.generate_permutation_key()\n    key1 = \"\".join(key1)\n\n    key2_dec = random.randint(0, (2**(size*2))-1)\n    key2_bin = format(key2_dec,'0'+str(size*2)+'b')\n\n    random_point = str(key1) + str(key2_bin)\n    # keep sampling for a random point uniformly until the random_point is not equivalent to point\n    while random_point == point:\n      key2_dec = random.randint(0, (2**(size*2))-1)\n      key2_bin = format(key2_dec,'0'+str(size*2)+'b')\n      random_point = str(key1) + str(key2_bin)\n    # sample from challenge distribution in which with approx. 50%, random_point is selected, and 50%, point is selected\n    sample = np.random.choice([random_point, point])\n    return sample\n\n  def protect(self, permuted_cnots, hadamards, x_key, z_key, init_data = [0,0,0,0,0,0,0,'+',0,0,0,0,0,0], size=14):\n    \"\"\"\n    Encodes a program \n    \n    Parameters:\n    permuted_cnots ([[int,int]]): all permuted CNOT gates to be applied\n    hadamards ([int]): all hadamard gates to be applied\n    x_key ([int]): all pauli-X gates to be applied\n    z_key ([int]): all pauli-Z gates to be applied\n    init_data (list): initialized qubit states\n    size (int): size of the quantum circuit\n\n    Returns:\n    circuit (qiskit's QuantumCircuit): encoded program\n    \"\"\"   \n    # initialize quantum circuit\n    qr = QuantumRegister(size)\n    circuit = QuantumCircuit(qr)\n    \n    # initialize the states of the quantum circuit\n    for i in range(size):\n      if init_data[i] == '+':\n        circuit.h(i)\n      elif init_data[i] == 1:\n        circuit.x(i)\n      elif init_data[i] == '-':\n        circuit.x(i)\n        circuit.h(i)\n    circuit.barrier()\n    # apply delegated one-time pad\n    for i in range(size):\n      if x_key[i] == 1 and init_data[i] == 0:\n        circuit.x(i)\n      elif z_key[i] == 1 and init_data[i] == '+':\n        circuit.z(i)\n    circuit.barrier()\n    # apply hadamard gates\n    for i in hadamards:\n      circuit.h(i)  \n    circuit.barrier()\n    # apply cnot gates\n    for cnots in permuted_cnots:\n      circuit.cx(cnots[0], cnots[1])\n    circuit.barrier()\n    return circuit\n\n  def get_syndrome_circuit(self, challenge_input, program, size=14, syndrome_cnots =[[0, 14], [2, 14], [4, 14], [6, 14], [1, 15], [2, 15], [5, 15], [6, 15], [3, 16], [4, 16], [5, 16], [6, 16], [7, 17], [9, 17], [11, 17], [13, 17], [8, 18], [9, 18], [12, 18], [13, 18], [10, 19], [11, 19], [12, 19], [13, 19]]):\n    \"\"\"\n    Creates a circuit that detects for single bit and phase flip errors \n    \n    Parameters:\n    challenge_input (str): point used to decrypt program\n    program (qiskit's QuantumCircuit): program for finding error syndromes\n    size (int): the number of qubits in the program\n    syndrome_cnots ([int,int]): CNOT gates for obtaining error syndromes\n\n    Returns:\n    syndrome_circuit (qiskit's QuantumCircuit): program for calculating error syndromes\n    \"\"\"  \n    key1, key2 = self.point_to_keys(challenge_input) \n    # initialize quantum circuit\n    qr = QuantumRegister(size+int(size/7*3))\n    cr = ClassicalRegister(size+int(size/7*3))\n    syndrome_circuit = QuantumCircuit(qr, cr)\n    # add program to new quantum circuit\n    syndrome_circuit.append(program, range(size))\n    # apply gates to decrypt the circuit\n    for i in range(size,size+int(size/7*3)):\n      syndrome_circuit.h(i)\n\n    for gate in syndrome_cnots:\n      syndrome_circuit.cx(gate[1], key1.index(gate[0]))\n\n    for i in range(size,size+int(size/7*3)):\n      syndrome_circuit.h(i)\n\n    syndrome_circuit.barrier()\n    syndrome_circuit.measure(qr,cr)\n    return syndrome_circuit\n\n\n  def get_syndrome_circuit_mit_measures(self, mit_values, challenge_input, program, size=14, syndrome_cnots =[[0, 14], [2, 14], [4, 14], [6, 14], [1, 15], [2, 15], [5, 15], [6, 15], [3, 16], [4, 16], [5, 16], [6, 16], [7, 17], [9, 17], [11, 17], [13, 17], [8, 18], [9, 18], [12, 18], [13, 18], [10, 19], [11, 19], [12, 19], [13, 19]]):\n    \"\"\"\n    Creates a circuit that detects bit and phase flip errors but measures only a subset of qubits; \n    Used for tensored error mitigation\n    \n    Parameters:\n    mit_values ([int]): subset of qubits to be measured\n    challenge_input (str): point used to decrypt program\n    program (qiskit's QuantumCircuit): program for finding error syndromes\n    size (int): the number of qubits in the program\n    syndrome_cnots ([int,int]): CNOT gates for obtaining error syndromes\n\n    Returns:\n    syndrome_program (qiskit's QuantumCircuit): program for calculating error syndromes with partial qubit measurement\n    \"\"\"    \n    key1, key2 = self.point_to_keys(challenge_input) \n\n    qr = QuantumRegister(size+int(size/7*3))\n    cr = ClassicalRegister(len(mit_values))\n    syndrome_program = QuantumCircuit(qr, cr)\n    syndrome_program.append(program, range(size))\n\n    for i in range(size,size+int(size/7*3)):\n      syndrome_program.h(i)\n\n    for gate in syndrome_cnots:\n      syndrome_program.cx(gate[1], key1.index(gate[0]))\n\n    for i in range(size,size+int(size/7*3)):\n      syndrome_program.h(i)\n\n    syndrome_program.barrier()\n    for i in range(len(mit_values)):\n      syndrome_program.measure(qr[mit_values[i]], cr[i])\n    return syndrome_program\n\n  def point_to_keys(self, point, size=14):\n    \"\"\"\n    Derives the permutation and one-time pad keys from a point\n    \n    Parameters:\n    point(str): point for deriving keys from\n    size (int): number of qubits in program\n\n    Returns:\n    circuit (circuit): protected program\n    \"\"\"  \n    inc = math.ceil(math.log2(size))\n    key1 = [int(point[i:i+inc],2) for i in range(0, len(point[:-size*2]), inc)] \n    key2_x = [int(value) for value in point[-size*2:-size]]\n    key2_z = [int(value) for value in point[-size:]]\n    return key1, [key2_x, key2_z]\n\n  def permute_classical(self, key1, orig_cnots, hadamards = [1,2,3,8,9,10], size=14):\n    \"\"\"\n    Provides the locations of CNOT and Hadamard gates based on a permutated list\n    \n    Parameters:\n    key1 ([int]): permutated list\n    orig_cnots ([[int,int]]): the location of unpermuted CNOT gates\n    hadamards ([int]): the location of unpermuted Hadamard gates\n    size (int): number of qubits in program\n\n    Returns:\n    new_cnot_gates ([[int,int]]): permuted CNOT gates\n    new_hadamard_gates ([int]): permuted Hadamard gates\n    \"\"\"  \n    new_hadamard_gates = [0]*len(hadamards)\n    new_cnot_gates = [0]*len(orig_cnots)\n\n    for i in range(len(orig_cnots)):\n      new_cnot_gates[i] = [key1.index(orig_cnots[i][0]), key1.index(orig_cnots[i][1])]\n    for i in range(len(hadamards)):\n      new_hadamard_gates[i] = key1.index(hadamards[i])\n\n    return new_cnot_gates, new_hadamard_gates\n\n  def get_OTP_classical_key(self, key, permutation_key, cnots, hadamards):\n    \"\"\"\n    Gets the delegated one-time pad key, where the one-time pad key is delegated to the beginning of the program\n    \n    Parameters:\n    key ([[int],[int]]): the one-time pad key to be delegated \n    permutation_key ([int]): permutation\n    cnots ([[int,int]]): all CNOT gates\n    hadamards ([int]): all Hadamard gates \n\n    Returns:\n    new_x_key ([int]): delegated Pauli-X gates of one-time pad\n    new_z_key ([int]): delegated Pauli-Z gates of one-time pad\n    \"\"\"  \n    x_key = key[0]\n    z_key = key[1]\n\n    for cnot in cnots:\n      a = x_key[cnot[0]]\n      b = z_key[cnot[0]]\n      c = x_key[cnot[1]]\n      d = z_key[cnot[1]]\n      x_key[cnot[0]] = a\n      z_key[cnot[0]] = b+d\n      x_key[cnot[1]] = a+c\n      z_key[cnot[1]] = d\n\n    for i in hadamards:\n      x_key[i], z_key[i] = z_key[i], x_key[i]\n\n    new_x_key = [i%2 for i in x_key]\n    new_z_key = [i%2 for i in z_key]\n\n    return new_x_key, new_z_key\n\n\n  def undo_circuit(self, point, program, rev_cnots=[[3,6],[3,5],[3,4],[2,6],[2,4],[2,0],[1,5],[1,4],[1,0],[0,6],[0,5],[10, 13],[10, 12],[10, 11],[9, 13],[9, 11],[9, 7],[8, 12],[8, 11],[8, 7],[7, 13],[7, 12]], size=14):\n    \"\"\"\n    Applies all the operations in reverse order as to undo the original program\n    \n    Parameters:\n    point (str): the point for encoding the program\n    program (qiskit's QuantumCircuit): circuit to be undoed\n    rev_cnots ([[int,int]]): the reverse sequence of CNOT gates that were applied in the program\n    size (int): number of qubits in program\n\n    Returns:\n    undo_circuit (qiskit's QuantumCircuit): the program that has been undoed\n    \"\"\"  \n    key1, key2 = self.point_to_keys(point) \n    permuted_cnots, hg = self.permute_classical(key1, rev_cnots)\n    qr = QuantumRegister(size)\n    cr_trap = ClassicalRegister(size)\n    undo_circuit = QuantumCircuit(qr, cr_trap)\n    undo_circuit.append(program, range(size))\n\n    for cnot in permuted_cnots:\n      undo_circuit.cx(cnot[0], cnot[1])\n    \n    undo_circuit.barrier()\n    for gate in hg:\n      undo_circuit.h(gate)\n    undo_circuit.barrier()\n\n    undo_circuit.measure(qr, cr_trap)\n    return undo_circuit\n    \n  def reverse_cnots(self, cnots):\n    \"\"\"\n    Reverse the order of CNOTs\n    \n    Parameters:\n    cnots ([[int,int]]): original order of cnots\n\n    Returns:\n    rev_cnots ([[int,int]]): reversed order of cnots\n    \"\"\"  \n    rev_cnots = []\n    for i in range(len(cnots)):\n      rev_cnots.append(cnots[len(cnots)-i-1])\n    return rev_cnots\n\n  def get_random_mit_pattern_single(self, size=20, num_qubits = 10):\n    \"\"\"\n    Selected single qubit pattern for tensored error mitigation\n    \n    Parameters:\n    size(int): total number of qubits in the program\n    num_qubits(int): number of qubits to be selected\n\n    Returns:\n    mit_pattern (list): pattern for tensored error mitigation, comprised of single qubits\n    mit_values ([int]): a random subset of all qubits in mit_pattern \n    \"\"\"  \n    mit_vals = random.sample(list(range(size)),num_qubits)\n    mit_pattern = [[x] for x in mit_vals]\n    return mit_pattern, mit_vals\n    \n  def get_permuted_cnots(self, permutation_key, cnots):\n    \"\"\"\n    Gets the permuted set of CNOTs to be applied for the syndrome programs\n    \n    Parameters:\n    permutation_key([int]): permutation \n    cnots([[int,int]]): CNOT gates to be applied\n\n    Returns:\n    new_permuted_cnots ([[int,int]]): permutation of CNOT gates\n    \"\"\"    \n    num_aux_qubits = int((len(permutation_key)/7)*3)\n    # get the list of auxiliary qubits for obtaining error syndromes\n    aux_qubits = list(range(len(permutation_key),len(permutation_key)+num_aux_qubits))\n    key = permutation_key + aux_qubits\n    new_permuted_cnots = [0]*len(cnots)\n    for i in range(len(cnots)):\n      new_permuted_cnots[i] = [key.index(cnots[i][0]), key.index(cnots[i][1])]\n    return new_permuted_cnots\n\n  def get_random_mit_pattern_all(self, permutation_key, steane_cnots = [[1,0], [1,4], [1,5], [2,0], [2,4], [2,6], [3,4], [3,5],[3,6],[7, 12],[7, 13],[8,7] ,[8, 11],[8, 12], [9,7],[9, 11],[9, 13],[10, 11],[10, 12],[10, 13]], syndrome_cnots = [[14, 0], [14, 2], [14, 4], [14, 6], [15, 1], [15, 2], [15, 5], [15, 6], [16, 3], [16, 4], [16, 5], [16, 6], [17, 7], [17, 9], [17, 11], [17, 13], [18, 8], [18, 9], [18, 12], [18, 13], [19, 10], [19, 11], [19, 12], [19, 13]], size=20, num_qubits = 10):\n    \"\"\"\n    Selected single and double qubit patterns for tensored error mitigation\n    \n    Parameters:\n    permutation_key([int]): permutation \n    steane_cnots ([[int,int]]): all cnot gates for the Steane encoding\n    syndrome_cnots ([[int,int]]): all cnot gates for calculating the error syndromes\n    size(int): total number of qubits in the program\n    num_qubits(int): number of qubits to be selected\n\n    Returns:\n    mit_pattern (list): pattern for tensored error mitigation, comprised of single and qubit pairs\n    mit_values ([int]): a random subset of all qubits in mit_pattern \n    \"\"\"   \n    permuted_steane_cnots = self.get_permuted_cnots(permutation_key, steane_cnots)\n    permuted_syndrome_cnots = self.get_permuted_cnots(permutation_key, syndrome_cnots)\n    cnots = permuted_steane_cnots  + permuted_syndrome_cnots\n    # number of qubit pairs to include in pattern\n    num_cnots = random.choice(range(10//2))\n    count = 0\n    cnot_pairs = []\n    cnot_values = []\n    while count != num_cnots:\n      val = random.choice(range(len(cnots)))\n      if cnots[val] not in cnot_pairs:\n        if cnots[val][0] not in cnot_values and cnots[val][1] not in cnot_values:\n          cnot_pairs.append(cnots[val])\n          cnot_values.append(cnots[val][0]) \n          cnot_values.append(cnots[val][1])\n          count = count +1 \n    \n    singles = random.sample(set(list(range(20)))-set(cnot_values),num_qubits-(num_cnots*2))\n    s = [[x] for x in singles[:]]\n    mit_values = cnot_values + singles\n    mit_patterns = cnot_pairs + s\n    return mit_patterns,mit_values\n\n  def prepare_meas_filter(self, mit_pattern, backend, num_shots, size=20):\n    \"\"\"\n    Prepare a tensored error mitigation measurement filter based on specified mit_pattern\n    \n    Parameters:\n    mit_pattern([int]): pattern used for tensored error mitigation\n    backend(qiskit's IBMQBackend): specified backend for preparing measurement filter\n    num_shots(int): number of shots for backend\n    size(int): number of qubits in program\n\n    Returns:\n    meas_filter (qiskit's TensoredMeasFitter.filter): prepared measurement filter\n    \"\"\"  \n    qr = QuantumRegister(size) \n    qulayout = range(size)\n    meas_calibs, state_labels = tensored_meas_cal(mit_pattern=mit_pattern, qr=qr, circlabel='mcal')\n    for circ in meas_calibs:\n      print(circ.name)\n    job = execute(meas_calibs, backend=backend, shots=num_shots)\n    cal_results = job.result()\n    meas_fitter = TensoredMeasFitter(cal_results, mit_pattern=mit_pattern)\n    meas_filter = meas_fitter.filter\n    return meas_filter\n```\n\n#Tests\n\n\n```python\n# initiate the server\nserver = Server()\nstart = time.time()\nfields = ['is_point', 'point_value', 'challenge_point_value', 'key_1', 'key_2', 'challenge_key_1', 'challenge_key_2', 'mit_pattern_single','mit_pattern_all']\n```\n\n    Server initialized\n\n\n\n```python\nresults_info = pd.DataFrame(columns=fields)\nresults_info_decoded = pd.DataFrame(columns=fields)\nsp_list= []\nsp_mit_single_list =[]\nsp_mit_all_list = []\ndp_list = []\nmeas_filter_singles = []\nmeas_filter_alls = []\n```\n\n\n```python\ndef get_programs_for_test(server, challenge_input, program, permutation_key,sp_list, sp_mit_single_list, sp_mit_all_list,dp_list, meas_filter_singles, meas_filter_alls, rev_cnots=REV_CNOT_GATES, backend=BACKEND, num_shots=NUM_SHOTS):\n  \"\"\"\n  Prepares circuits for execution\n\n  Parameters:\n  server (Server): Server instance\n  challenge_input (str): challenge point for testing programs\n  program (qiskit's QuantumCicuit): the encoded program for applying tests\n  permutation_key ([int]): permutation ordering\n  sp_list ([qiskit's QuantumCircuits]): list of prepared syndrome quantum circuits \n  sp_mit_single_list ([qiskit's QuantumCircuits]): list of prepared syndrome quantum circuits with partial measurement and single qubit patterns\n  sp_mit_all_list ([qiskit's QuantumCircuits]): list of prepared quantum circuits with syndromes with partial measurement and single and qubit pair patterns\n  dp_list ([qiskit's QuantumCircuits]): list of prepared undoed quantum circuits\n  meas_filter_singles ([qiskit's TensoredMeasFitter.filter]): list of tensored measurement filters for sp_mit_single_list circuits\n  meas_filter_alls ([qiskit's TensoredMeasFitter.filter]): list of tensored measurement filters for sp_mit_all_list circuits\n  rev_cnots ([[int,int]]): cnot gates to be applied for undoing the circuit\n  backend (qiskit's IBMQBackend): specified backend for preparing measurement filter\n  num_shots (int): number of shots for backend\n\n  Returns:\n  sp_list ([qiskit's QuantumCircuits]): list of prepared syndrome quantum circuits \n  sp_mit_single_list ([qiskit's QuantumCircuits]): list of prepared syndrome quantum circuits with partial measurement and single qubit patterns\n  sp_mit_all_list ([qiskit's QuantumCircuits]): list of prepared quantum circuits with syndromes with partial measurement and single and double qubit patterns\n  dp_list ([qiskit's QuantumCircuits]): list of prepared undoed quantum circuits\n  meas_filter_singles ([qiskit's TensoredMeasFitter.filter]): list of tensored measurement filters for sp_mit_single_list circuits\n  meas_filter_alls ([qiskit's TensoredMeasFitter.filter]): list of tensored measurement filters for sp_mit_all_list circuits\n  mit_pattern_s ([[int]]): subset of single qubits used in tensored error mitigation, based on the circuits sp_mit_single_list\n  mit_pattern_all (list): subset of single and double qubits used in tensored error mitigation, based on the circuits sp_mit_all_list\n  \"\"\"\n  syndrome_program = server.get_syndrome_circuit(challenge_input,program)\n  mit_pattern_s, mit_val_s = server.get_random_mit_pattern_single()\n  mit_pattern_all, mit_val_all = server.get_random_mit_pattern_all(permutation_key)\n  syndrome_program_mit_single = server.get_syndrome_circuit_mit_measures(mit_val_s, challenge_input, program)\n  syndrome_program_mit_all = server.get_syndrome_circuit_mit_measures(mit_val_all,challenge_input,program)\n  decoded_program = server.undo_circuit(challenge_input, program, rev_cnots=rev_cnots)\n  meas_filter_s = server.prepare_meas_filter(mit_pattern_s, backend, num_shots)\n  meas_filter_all = server.prepare_meas_filter(mit_pattern_all, backend, num_shots)\n  sp_list = sp_list + [syndrome_program]\n  sp_mit_single_list =sp_mit_single_list + [syndrome_program_mit_single]\n  sp_mit_all_list = sp_mit_all_list + [syndrome_program_mit_all]\n  dp_list = dp_list + [decoded_program]\n  meas_filter_singles = meas_filter_singles + [meas_filter_s]\n  meas_filter_alls = meas_filter_alls + [meas_filter_all]\n  return sp_list, sp_mit_single_list, sp_mit_all_list, dp_list, meas_filter_singles, meas_filter_alls, mit_pattern_s, mit_pattern_all\n\ndef prepare_for_test(server, cnots = CNOT_GATES):\n  \"\"\" \n  Prepare inputs for test\n\n  Parameters:\n  server (Server): instance of Server for preparing inputs\n  cnots ([[int,int]]): cnot gates to be applied\n  \n  Returns:\n  p (str): point\n  k1 ([int]): permutation key\n  key2 ([[int],[int]]): one-time pad key\n  permuted_cnots([[int,int]]):  cnot gates post permutation\n  permuted_hadamards ([int]): hadamard gates post permutation\n  x_key ([int]): all delegated pauli-X gates to be applied for one-time pad (key2)\n  z_key ([int]):  all delegated pauli-Z gates to be applied for one-time pad (key2)\n  data (list): qubits' intial states\n  \"\"\"\n  p, k1, k2 = server.generate_point()\n  key2 = [k2[0][:], k2[1][:]]\n  permuted_cnots, permuted_hadamards = server.permute_classical(k1, cnots)\n  rev = server.reverse_cnots(permuted_cnots)\n  x_key, z_key = server.get_OTP_classical_key(k2,k1, rev,permuted_hadamards)\n  data = [0]*14\n  data[k1.index(7)] = '+'\n  return p, k1, key2, permuted_cnots, permuted_hadamards, x_key, z_key, data\n```\n\n\n\n\n> ### Test 1.1: Point = Challenge Input Correctness Check\n\n\n```python\nprint(\"_____________PART A: Challenge Input == Point_____________\")\nfor i in range(NUM_DIFF_PROGRAMS):\n  p, k1, key2, cnots, hadamards, x_key, z_key, data = prepare_for_test(server)\n  program = server.protect(cnots, hadamards, x_key, z_key, init_data=data)\n  # set challenge_input\n  challenge_input = p\n  challenge_key1, challenge_key2 = server.point_to_keys(challenge_input)  \n  for k in range(NUM_ITERATIONS): \n    sp_list, sp_mit_single_list, sp_mit_all_list, dp_list, meas_filter_singles, meas_filter_alls, mit_pattern_s, mit_pattern_all = get_programs_for_test(server, challenge_input, program, k1, sp_list, sp_mit_single_list, sp_mit_all_list, dp_list, meas_filter_singles, meas_filter_alls)\n    index = i*NUM_ITERATIONS+k\n    results_info.loc[index] = [str(p) == str(challenge_input), p, challenge_input, k1, key2, challenge_key1, challenge_key2, mit_pattern_s, mit_pattern_all]\n    results_info_decoded.loc[index] = [str(p) == str(challenge_input), p, challenge_input, k1, key2, challenge_key1, challenge_key2, \"-\", \"-\"]\n\n```\n\n    _____________PART A: Challenge Input == Point_____________\n    mcalcal_0000000000\n    mcalcal_1111111111\n    mcalcal_0000000000\n    mcalcal_0000000101\n    mcalcal_1111111010\n    mcalcal_1111111111\n\n\n\n\n> ### Test 1.2: Point != Challenge Input, w/ 1 permutation error Correctness Check\n\n\n\n\n\n```python\nprint(\"\\n_____________PART B: Challenge Input != Point - one Permutation Error_____________\")\nfor j in range(NUM_DIFF_PROGRAMS):\n  p, k1, key2, cnots, hadamards, x_key, z_key, data = prepare_for_test(server)\n  program = server.protect(cnots, hadamards, x_key, z_key, init_data=data)\n  # prepare challenge input\n  i = np.random.choice(14,2,False)\n  edited_k1 = k1[:]\n  edited_k1[i[0]], edited_k1[i[1]] = k1[i[1]], k1[i[0]]\n  f = '0' + str(math.ceil(math.log2(14))) + 'b'\n  new_key1 = [format(x, f) for x in edited_k1]\n  challenge_input = str(\"\".join(new_key1)) + str(p[-28:])\n  challenge_key1, challenge_key2 = server.point_to_keys(challenge_input)\n\n  for k in range(NUM_ITERATIONS): \n    sp_list, sp_mit_single_list, sp_mit_all_list, dp_list, meas_filter_singles, meas_filter_alls, mit_pattern_s, mit_pattern_all = get_programs_for_test(server, challenge_input, program, k1, sp_list, sp_mit_single_list, sp_mit_all_list, dp_list, meas_filter_singles, meas_filter_alls)\n    index = j*NUM_ITERATIONS+k +(NUM_ITERATIONS*NUM_DIFF_PROGRAMS)\n    results_info_decoded.loc[index] = [str(p) == str(challenge_input), p, challenge_input, k1, key2, challenge_key1, challenge_key2, \"-\",\"-\"]\n    results_info.loc[index] = [str(p) == str(challenge_input), p, challenge_input, k1, key2, challenge_key1, challenge_key2, mit_pattern_s, mit_pattern_all]\n\n```\n\n    \n    _____________PART B: Challenge Input != Point - one Permutation Error_____________\n    mcalcal_0000000000\n    mcalcal_1111111111\n    mcalcal_0000000000\n    mcalcal_0000000101\n    mcalcal_1111111010\n    mcalcal_1111111111\n\n\n\n\n> ### Test 1.3: Point != Challenge Input, w/ 1 X error Correctness Check\n\n\n\n```python\nprint(\"\\n_____________PART C: Challenge Input != Point - one X Error_____________\")\nfor j in range(NUM_DIFF_PROGRAMS):\n  p, k1, key2, cnots, hadamards, x_key, z_key, data = prepare_for_test(server)\n  program = server.protect(cnots, hadamards, x_key, z_key, init_data=data)\n  # prepare challenge input\n  i = np.random.choice(14,1,False)\n  index = (i[0]-28)\n  challenge_input = str(p[:index]) + str((int(p[index])+1)%2) + str(p[index+1:])\n  challenge_key1, challenge_key2 = server.point_to_keys(challenge_input)\n  for k in range(NUM_ITERATIONS): \n    sp_list, sp_mit_single_list, sp_mit_all_list, dp_list, meas_filter_singles, meas_filter_alls, mit_pattern_s, mit_pattern_all = get_programs_for_test(server, challenge_input, program, k1, sp_list, sp_mit_single_list, sp_mit_all_list, dp_list, meas_filter_singles, meas_filter_alls)\n    index = j*NUM_ITERATIONS+k +(NUM_ITERATIONS*NUM_DIFF_PROGRAMS*2)\n    results_info_decoded.loc[index] = [str(p) == str(challenge_input), p, challenge_input, k1, key2, challenge_key1, challenge_key2,\"-\",\"-\"]\n    results_info.loc[index] = [str(p) == str(challenge_input), p, challenge_input, k1, key2, challenge_key1, challenge_key2,  mit_pattern_s, mit_pattern_all]\nprint(len(results_info))\n```\n\n    \n    _____________PART C: Challenge Input != Point - one X Error_____________\n    mcalcal_0000000000\n    mcalcal_1111111111\n    mcalcal_0000000000\n    mcalcal_0001010101\n    mcalcal_1110101010\n    mcalcal_1111111111\n    3\n\n\n\n> ### Test 1.4: Point != Challenge Input, w/ 1 Z error Correctness Check\n\n\n\n\n\n\n```python\nprint(\"\\n_____________PART D: Challenge Input != Point - one Z-Error_____________\")\nfor j in range(NUM_DIFF_PROGRAMS):\n  p, k1, key2, cnots, hadamards, x_key, z_key, data = prepare_for_test(server)\n  program = server.protect(cnots, hadamards, x_key, z_key, init_data=data)\n  # prepare challenge input\n  i = np.random.choice(14,1,False)\n  index = (i[0]-14)\n  print(index)\n  if i == 13:\n    challenge_input = str(p[:index]) + str((int(p[index])+1)%2)\n  else:\n    challenge_input = str(p[:index]) + str((int(p[index])+1)%2) + str(p[index+1:])\n  challenge_key1, challenge_key2 = server.point_to_keys(challenge_input)\n \n  for k in range(NUM_ITERATIONS): \n    sp_list, sp_mit_single_list, sp_mit_all_list, dp_list, meas_filter_singles, meas_filter_alls, mit_pattern_s, mit_pattern_all = get_programs_for_test(server, challenge_input, program, k1, sp_list, sp_mit_single_list, sp_mit_all_list, dp_list, meas_filter_singles, meas_filter_alls)\n    index = j*NUM_ITERATIONS+k +(NUM_ITERATIONS*NUM_DIFF_PROGRAMS*3)\n    results_info.loc[index] = [str(p) == str(challenge_input), p, challenge_input, k1, key2, challenge_key1, challenge_key2, mit_pattern_s, mit_pattern_all]\n    results_info_decoded.loc[index] = [str(p) == str(challenge_input), p, challenge_input, k1, key2, challenge_key1, challenge_key2,  \"-\", \"-\"]\n```\n\n    \n    _____________PART D: Challenge Input != Point - one Z-Error_____________\n    -7\n    mcalcal_0000000000\n    mcalcal_1111111111\n    mcalcal_0000000000\n    mcalcal_0000000101\n    mcalcal_1111111010\n    mcalcal_1111111111\n\n\n\n> ### Test 1.5: Point != Challenge Input, w/ 1 X, Z error EACH\n\n\n\n\n\n\n```python\nprint(\"\\n_____________PART E: Challenge Input != Point - one X and Z Error_____________\")\nfor j in range(NUM_DIFF_PROGRAMS):\n  p, k1, key2, cnots, hadamards, x_key, z_key, data = prepare_for_test(server)\n  program = server.protect(cnots, hadamards, x_key, z_key, init_data=data)\n  # prepare challenge input\n  i = np.sort(np.random.choice(14,2,True))\n  x_error_index = i[0] - 28\n  z_error_index = i[1] - 14\n  if i[1] == 13:\n    challenge_input = str(p[:x_error_index]) + str((int(p[x_error_index])+1)%2) + str(p[x_error_index+1: z_error_index])\n  else:\n    challenge_input = str(p[:x_error_index]) + str((int(p[x_error_index])+1)%2) + str(p[x_error_index+1: z_error_index])+ str((int(p[z_error_index])+1)%2)+ str(p[z_error_index+1:])\n  challenge_key1, challenge_key2 = server.point_to_keys(challenge_input)\n  \n  for k in range(NUM_ITERATIONS): \n    sp_list, sp_mit_single_list, sp_mit_all_list, dp_list, meas_filter_singles, meas_filter_alls, mit_pattern_s, mit_pattern_all = get_programs_for_test(server, challenge_input, program, k1, sp_list, sp_mit_single_list, sp_mit_all_list, dp_list, meas_filter_singles, meas_filter_alls)\n    index = j*NUM_ITERATIONS+k +(NUM_ITERATIONS*NUM_DIFF_PROGRAMS*4)\n    results_info.loc[index] = [str(p) == str(challenge_input), p, challenge_input, k1, key2, challenge_key1, challenge_key2, mit_pattern_s, mit_pattern_all]\n    results_info_decoded.loc[index] = [str(p) == str(challenge_input), p, challenge_input, k1, key2, challenge_key1, challenge_key2, \"-\", \"-\"]\n```\n\n    \n    _____________PART E: Challenge Input != Point - one X and Z Error_____________\n    mcalcal_0000000000\n    mcalcal_1111111111\n    mcalcal_0000000000\n    mcalcal_0001010101\n    mcalcal_1110101010\n    mcalcal_1111111111\n\n\n\n\n> ### Test 1.6: Point != Challenge Input, w/ random error Correctness Check\n\n\n\n\n```python\nprint(\"\\n_____________PART F: Random Challenge Input_____________\")\nfor i in range(NUM_RANDOM_ITERATIONS):\n  p, k1, key2, cnots, hadamards, x_key, z_key, data = prepare_for_test(server)\n  program = server.protect(cnots, hadamards, x_key, z_key, init_data=data)\n  # prepare challenge input\n  challenge_input = server.sample_challenge_point(p)\n  challenge_key1, challenge_key2 = server.point_to_keys(challenge_input)\n  \n  sp_list, sp_mit_single_list, sp_mit_all_list, dp_list, meas_filter_singles, meas_filter_alls, mit_pattern_s, mit_pattern_all = get_programs_for_test(server, challenge_input, program, k1, sp_list, sp_mit_single_list, sp_mit_all_list, dp_list, meas_filter_singles, meas_filter_alls)\n  index = (NUM_ITERATIONS*NUM_DIFF_PROGRAMS*5)+i\n  results_info.loc[index] = [str(p) == str(challenge_input), p, challenge_input, k1, key2, challenge_key1, challenge_key2, mit_pattern_s, mit_pattern_all]\n  results_info_decoded.loc[index] = [str(p) == str(challenge_input), p, challenge_input, k1, key2, challenge_key1, challenge_key2,  \"-\", \"-\"]\n\n\n```\n\n    \n    _____________PART F: Random Challenge Input_____________\n    mcalcal_0000000000\n    mcalcal_1111111111\n    mcalcal_0000000000\n    mcalcal_0000010101\n    mcalcal_1111101010\n    mcalcal_1111111111\n\n\n# Execute Circuits prepared in Tests\n\n### Transpiling Circuits\n\n\n---\n\n\n\n\n```python\ndef get_transpiled_circuit_and_depth(circuit_list, backend, init_qubits, opt_level = 2, num_seeds = 1):\n  \"\"\"\n  Gets the list of transpiled circuits with the least gate depths based on the random seeds of the specified quantum backend \n  \n  Parameters:\n  circuit_list ([qiskit's QuantumCircuit]): list of circuits to be transpiled\n  backend (qiskit's IBMQBackend): specified quantum computer for transpiling the circuits\n  init_qubits ([int]): mapping of virtual to physical qubits\n  opt_level (int): the optimization level of the transpiled circuits\n  num_seeds (int): the number of random seeds to iterate through\n  \n  Returns:\n  transpiled_list ([qiskit's QuantumCircuit]): transpiled circuits with the least gate depths\n  transpiled_depths ([int]): corresponding gate depths of transpiled_list\n  \"\"\"\n  transpiled_list = []\n  transpiled_depths = []\n  for i in range(len(circuit_list)):\n    min_circ = transpile(circuit_list[i], backend, initial_layout=init_qubits[i])\n    min_depth = min_circ.depth()\n    for j in range(num_seeds):\n      transpiled_circ = transpile(circuit_list[i], backend, initial_layout=init_qubits[i],optimization_level=opt_level)\n      depth = transpiled_circ.depth()\n      if depth < min_depth:\n        min_depth = depth\n        min_circ = transpiled_circ\n    transpiled_list.append(min_circ)\n    transpiled_depths.append(min_circ.depth())\n  return transpiled_list, transpiled_depths\n```\n\n\n```python\n# getting the virtual to physical qubit mapping for all circuits\n# mapping is based on the permutation of the circuits and the ideal physical ordering of the quantum computer\ninit_qubits= []\ninit_qubits_msg = []\nfor key1 in results_info.challenge_key_1:\n  k1 = key1[:]\n  for i in range(len(k1)):\n    k1[i]= unpermuted_layout[k1[i]]\n  init_qubits_msg.append(k1[:])\n  for j in syndrome_layout:\n    k1.append(j)\n  init_qubits.append(k1)\n\n# getting all the transpiled circuits\ntranspiled_sp_list, transpiled_sp_depths = get_transpiled_circuit_and_depth(sp_list, BACKEND, init_qubits, num_seeds = NUM_SEEDS)\ntranspiled_sp_singles_list, transpiled_sp_singles_depths = get_transpiled_circuit_and_depth(sp_mit_single_list, BACKEND, init_qubits, num_seeds =  NUM_SEEDS)\ntranspiled_sp_all_list, transpiled_sp_all_depths = get_transpiled_circuit_and_depth(sp_mit_all_list, BACKEND, init_qubits, num_seeds =  NUM_SEEDS)\ntranspiled_sp_msg_list, transpiled_sp_msg_depths = get_transpiled_circuit_and_depth(dp_list, BACKEND, init_qubits_msg, num_seeds =  NUM_SEEDS)\n\n```\n\n> ### Run Transpiled Circuits on Quantum Computers & Saving to Files\n\n\n```python\n# execute jobs of transpiled error syndrome programs\njob = execute(transpiled_sp_list, BACKEND, shots=NUM_SHOTS)\nresults_sim = job.result()\ncounts = results_sim.get_counts()\ncounts = [str(x) for x in counts]\n\n# saving data\nresults_info.insert(9, \"device_counts\",counts)\nresults_info.insert(10, \"circuit_depth\", transpiled_sp_depths)\nresults_info.to_csv(filename_error)\n\nmit_counts_singles = []\nmit_counts_all = []\n\n# execute jobs of transpiled error syndrome programs (with partial qubit measurement) for error mitigation\njob_s = execute(transpiled_sp_singles_list, BACKEND, shots=NUM_SHOTS)\njob_all = execute(transpiled_sp_all_list, BACKEND, shots=NUM_SHOTS)\nresults_sim_s = job_s.result()\ncounts_s = results_sim_s.get_counts()\nresults_sim_all = job_all.result()\ncounts_all = results_sim_all.get_counts()\n\n# get the mitigated counts of the transpiled error syndrome (with partial qubit measurement)\nfor j in range(NUM_ITERATIONS*NUM_DIFF_PROGRAMS*5+ NUM_RANDOM_ITERATIONS):\n  mitigated_counts = meas_filter_singles[j].apply(counts_s[j])\n  mit_counts_singles.append(str(mitigated_counts))\n  \n  mitigated_counts = meas_filter_alls[j].apply(counts_all[j])\n  mit_counts_all.append(str(mitigated_counts))\n\n# saving data\nresults_info.insert(11, \"raw_singles\", counts_s)\nresults_info.insert(12,\"raw_all\", counts_all)\nresults_info.insert(13, \"mitigated_counts_singles\",mit_counts_singles)\nresults_info.insert(14, \"singles_circuit_depth\", transpiled_sp_singles_depths)\nresults_info.insert(15, \"mitigated_counts_all\",mit_counts_all)\nresults_info.insert(16, \"all_circuit_depth\", transpiled_sp_all_depths)\nresults_info.to_csv(filename_mit)\n```\n\n\n```python\n# execute jobs of undoed programs\njob = execute(transpiled_sp_msg_list, BACKEND, shots=NUM_SHOTS)\nresults_sim = job.result()\nde_counts = results_sim.get_counts()\n\n# saving data\nresults_info_decoded.insert(8, \"device_counts\",de_counts)\nresults_info_decoded.insert(9, \"circuit_depth\", transpiled_sp_msg_depths)\nresults_info_decoded.to_csv(filename_decoded)\n```\n\n\n```python\n# saving some generic data\nwith open(filename_0, 'w') as writefile:\n  x = time.time() - start\n  writefile.write(\"--------------------ELAPSED TIME: \\n\")\n  writefile.write(str(x))\n  writefile.write(\"\\n________________________________COUNTS_____________________________________\\n\")\n  writefile.write(str(counts))\n  writefile.write(\"\\n________________________________DECODED_COUNTS_____________________________________\\n\")\n  writefile.write(str(de_counts))\n```\n", "meta": {"hexsha": "f9050ae45fef0e66835fbbed564057bc6fec0c88", "size": 94238, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Notebooks/QPA_20_qubits.ipynb", "max_stars_repo_name": "wsherry/QuantumPasswordAuthentication", "max_stars_repo_head_hexsha": "682751d28c3fdcd1166749621cbb0e9db5fc169c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-21T21:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-21T21:56:31.000Z", "max_issues_repo_path": "Notebooks/QPA_20_qubits.ipynb", "max_issues_repo_name": "wsherry/QuantumPasswordAuthentication", "max_issues_repo_head_hexsha": "682751d28c3fdcd1166749621cbb0e9db5fc169c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Notebooks/QPA_20_qubits.ipynb", "max_forks_repo_name": "wsherry/QuantumPasswordAuthentication", "max_forks_repo_head_hexsha": "682751d28c3fdcd1166749621cbb0e9db5fc169c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-03T22:42:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T22:42:43.000Z", "avg_line_length": 66.6463932107, "max_line_length": 2278, "alphanum_fraction": 0.6065387636, "converted": true, "num_tokens": 14689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.074770043938816, "lm_q1q2_score": 0.02633414271905001}}
{"text": "## Install TensorTrade\n\n\n```python\n!python3 -m pip install -e .. -U\n```\n\n    Obtaining file:///Users/adam/Desktop/Capfolio/tensortrade\n    Requirement already satisfied, skipping upgrade: numpy>=1.16.4 in /usr/local/lib/python3.7/site-packages (from tensortrade==0.2.0b1) (1.16.4)\n    Requirement already satisfied, skipping upgrade: pandas>=0.25.0 in /usr/local/lib/python3.7/site-packages (from tensortrade==0.2.0b1) (0.25.0)\n    Requirement already satisfied, skipping upgrade: gym>=0.14.0 in /usr/local/lib/python3.7/site-packages (from tensortrade==0.2.0b1) (0.14.0)\n    Requirement already satisfied, skipping upgrade: pyyaml>=5.1.2 in /usr/local/lib/python3.7/site-packages (from tensortrade==0.2.0b1) (5.1.2)\n    Requirement already satisfied, skipping upgrade: sympy>=1.4 in /usr/local/lib/python3.7/site-packages (from tensortrade==0.2.0b1) (1.4)\n    Requirement already satisfied, skipping upgrade: pytz>=2017.2 in /usr/local/lib/python3.7/site-packages (from pandas>=0.25.0->tensortrade==0.2.0b1) (2019.2)\n    Requirement already satisfied, skipping upgrade: python-dateutil>=2.6.1 in /usr/local/Cellar/jupyterlab/1.0.0_5/libexec/vendor/lib/python3.7/site-packages (from pandas>=0.25.0->tensortrade==0.2.0b1) (2.7.3)\n    Requirement already satisfied, skipping upgrade: cloudpickle~=1.2.0 in /usr/local/lib/python3.7/site-packages (from gym>=0.14.0->tensortrade==0.2.0b1) (1.2.1)\n    Requirement already satisfied, skipping upgrade: pyglet<=1.3.2,>=1.2.0 in /usr/local/lib/python3.7/site-packages (from gym>=0.14.0->tensortrade==0.2.0b1) (1.3.2)\n    Requirement already satisfied, skipping upgrade: six in /usr/local/Cellar/jupyterlab/1.0.0_5/libexec/vendor/lib/python3.7/site-packages (from gym>=0.14.0->tensortrade==0.2.0b1) (1.11.0)\n    Requirement already satisfied, skipping upgrade: scipy in /usr/local/lib/python3.7/site-packages (from gym>=0.14.0->tensortrade==0.2.0b1) (1.4.1)\n    Requirement already satisfied, skipping upgrade: mpmath>=0.19 in /usr/local/lib/python3.7/site-packages (from sympy>=1.4->tensortrade==0.2.0b1) (1.1.0)\n    Requirement already satisfied, skipping upgrade: future in /usr/local/lib/python3.7/site-packages (from pyglet<=1.3.2,>=1.2.0->gym>=0.14.0->tensortrade==0.2.0b1) (0.17.1)\n    Installing collected packages: tensortrade\n      Attempting uninstall: tensortrade\n        Found existing installation: TensorTrade 0.2.0b1\n        Uninstalling TensorTrade-0.2.0b1:\n          Successfully uninstalled TensorTrade-0.2.0b1\n      Running setup.py develop for tensortrade\n    Successfully installed tensortrade\n\n\n## Setup Data Fetching\n\n\n```python\nimport ssl\nimport pandas as pd\n\nssl._create_default_https_context = ssl._create_unverified_context # Only used if pandas gives a SSLError\n\ndef fetch(exchange_name, symbol, timeframe):\n    url = \"https://www.cryptodatadownload.com/cdd/\"\n    filename = \"{}_{}USD_{}.csv\".format(exchange_name, symbol, timeframe)\n    volume_column = \"Volume {}\".format(symbol)\n    new_volume_column = \"Volume_{}\".format(symbol)\n    \n    df = pd.read_csv(url + filename, skiprows=1)\n    df = df[::-1]\n    df = df.drop([\"Symbol\"], axis=1)\n    df = df.rename({\"Volume USD\": \"volume\", volume_column: new_volume_column}, axis=1)\n    df = df.set_index(\"Date\")\n    df.columns = [symbol + \":\" + name.lower() for name in df.columns]\n                     \n    return df\n```\n\n## Fetch Historical Data\n\n\n```python\ncoinbase_data = pd.concat([\n    fetch(\"Coinbase\", \"BTC\", \"1h\"),\n    fetch(\"Coinbase\", \"ETH\", \"1h\")\n], axis=1)\n\nbitstamp_data = pd.concat([\n    fetch(\"Bitstamp\", \"BTC\", \"1h\"),\n    fetch(\"Bitstamp\", \"LTC\", \"1h\")\n], axis=1)\n```\n\n\n```python\ncoinbase_data.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>BTC:open</th>\n      <th>BTC:high</th>\n      <th>BTC:low</th>\n      <th>BTC:close</th>\n      <th>BTC:volume_btc</th>\n      <th>BTC:volume</th>\n      <th>ETH:open</th>\n      <th>ETH:high</th>\n      <th>ETH:low</th>\n      <th>ETH:close</th>\n      <th>ETH:volume_eth</th>\n      <th>ETH:volume</th>\n    </tr>\n    <tr>\n      <th>Date</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2017-07-01 11-AM</th>\n      <td>2505.56</td>\n      <td>2513.38</td>\n      <td>2495.12</td>\n      <td>2509.17</td>\n      <td>114.60</td>\n      <td>287000.32</td>\n      <td>279.98</td>\n      <td>279.99</td>\n      <td>272.1</td>\n      <td>275.01</td>\n      <td>2455.28</td>\n      <td>679358.87</td>\n    </tr>\n    <tr>\n      <th>2017-07-01 12-PM</th>\n      <td>2509.17</td>\n      <td>2512.87</td>\n      <td>2484.99</td>\n      <td>2488.43</td>\n      <td>157.36</td>\n      <td>393142.50</td>\n      <td>275.01</td>\n      <td>275.01</td>\n      <td>271.0</td>\n      <td>274.83</td>\n      <td>3023.14</td>\n      <td>824362.87</td>\n    </tr>\n    <tr>\n      <th>2017-07-01 01-PM</th>\n      <td>2488.43</td>\n      <td>2488.43</td>\n      <td>2454.40</td>\n      <td>2454.43</td>\n      <td>280.28</td>\n      <td>693254.01</td>\n      <td>274.83</td>\n      <td>274.93</td>\n      <td>265.0</td>\n      <td>268.79</td>\n      <td>11204.43</td>\n      <td>3010787.99</td>\n    </tr>\n    <tr>\n      <th>2017-07-01 02-PM</th>\n      <td>2454.43</td>\n      <td>2473.93</td>\n      <td>2450.83</td>\n      <td>2459.35</td>\n      <td>289.42</td>\n      <td>712864.80</td>\n      <td>268.79</td>\n      <td>269.90</td>\n      <td>265.0</td>\n      <td>265.74</td>\n      <td>6367.05</td>\n      <td>1702536.85</td>\n    </tr>\n    <tr>\n      <th>2017-07-01 03-PM</th>\n      <td>2459.35</td>\n      <td>2475.00</td>\n      <td>2450.00</td>\n      <td>2467.83</td>\n      <td>276.82</td>\n      <td>682105.41</td>\n      <td>265.74</td>\n      <td>272.74</td>\n      <td>265.0</td>\n      <td>272.57</td>\n      <td>5581.66</td>\n      <td>1500282.55</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nbitstamp_data.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>BTC:open</th>\n      <th>BTC:high</th>\n      <th>BTC:low</th>\n      <th>BTC:close</th>\n      <th>BTC:volume_btc</th>\n      <th>BTC:volume</th>\n      <th>LTC:open</th>\n      <th>LTC:high</th>\n      <th>LTC:low</th>\n      <th>LTC:close</th>\n      <th>LTC:volume_ltc</th>\n      <th>LTC:volume</th>\n    </tr>\n    <tr>\n      <th>Date</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2017-07-01 11-AM</th>\n      <td>2506.50</td>\n      <td>2510.62</td>\n      <td>2495.50</td>\n      <td>2500.00</td>\n      <td>208.52</td>\n      <td>521903.70</td>\n      <td>39.67</td>\n      <td>39.67</td>\n      <td>39.32</td>\n      <td>39.45</td>\n      <td>49.61</td>\n      <td>1957.48</td>\n    </tr>\n    <tr>\n      <th>2017-07-01 12-PM</th>\n      <td>2500.00</td>\n      <td>2503.69</td>\n      <td>2488.25</td>\n      <td>2495.62</td>\n      <td>243.08</td>\n      <td>607308.42</td>\n      <td>39.45</td>\n      <td>39.57</td>\n      <td>39.18</td>\n      <td>39.57</td>\n      <td>63.62</td>\n      <td>2507.48</td>\n    </tr>\n    <tr>\n      <th>2017-07-01 01-PM</th>\n      <td>2495.62</td>\n      <td>2495.62</td>\n      <td>2433.59</td>\n      <td>2449.01</td>\n      <td>579.13</td>\n      <td>1421546.81</td>\n      <td>39.57</td>\n      <td>39.57</td>\n      <td>38.80</td>\n      <td>38.90</td>\n      <td>564.39</td>\n      <td>22019.12</td>\n    </tr>\n    <tr>\n      <th>2017-07-01 02-PM</th>\n      <td>2449.01</td>\n      <td>2480.60</td>\n      <td>2438.88</td>\n      <td>2457.90</td>\n      <td>528.75</td>\n      <td>1302198.58</td>\n      <td>38.90</td>\n      <td>39.08</td>\n      <td>38.77</td>\n      <td>39.06</td>\n      <td>788.53</td>\n      <td>30732.98</td>\n    </tr>\n    <tr>\n      <th>2017-07-01 03-PM</th>\n      <td>2457.90</td>\n      <td>2471.88</td>\n      <td>2452.10</td>\n      <td>2466.35</td>\n      <td>292.31</td>\n      <td>719666.88</td>\n      <td>39.06</td>\n      <td>39.16</td>\n      <td>38.73</td>\n      <td>39.15</td>\n      <td>666.53</td>\n      <td>26053.18</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Define Exchanges\n\nAn exchange needs a name, an execution service, and streams of price data in order to function properly.\n\nThe setups supported right now are the simulated execution service using simulated or stochastic data. More execution services will be made available in the future, as well as price streams so that live data and execution can be supported.\n\n\n```python\nfrom tensortrade.exchanges import Exchange\nfrom tensortrade.exchanges.services.execution.simulated import execute_order\nfrom tensortrade.data import Stream\n\ncoinbase = Exchange(\"coinbase\", service=execute_order)(\n    Stream(\"USD-BTC\", list(coinbase_data['BTC:close'])),\n    Stream(\"USD-ETH\", list(coinbase_data['ETH:close']))\n)\n\nbitstamp = Exchange(\"bitstamp\", service=execute_order)(\n    Stream(\"USD-BTC\", list(bitstamp_data['BTC:close'])),\n    Stream(\"USD-LTC\", list(bitstamp_data['LTC:close']))\n)\n```\n\nNow that the exchanges have been defined we can define our features that we would like to include, excluding the prices we have provided for the exchanges.\n\n## Define External Data Feed\n\nHere we will define the external feed to use whatever data you would like. From financial indicators to datasets that have nothing to do with instrument prices, they will all have to be defined and incorporated into the external data feed provided to the environment. There is also an internal data feed that is used to collect data on all the wallets and the net worth of the portfolio. You can choose to include this or not by using the `use_internal` parameter of the trading environment.\n\n\n```python\nimport ta\n\nfrom tensortrade.data import DataFeed, Module\n\n# Add all features for coinbase bitcoin\ncoinbase_btc = coinbase_data.loc[:, [name.startswith(\"BTC\") for name in coinbase_data.columns]]\ncoinbase_eth = coinbase_data.loc[:, [name.startswith(\"ETH\") for name in coinbase_data.columns]]\n\nta.add_all_ta_features(\n    coinbase_btc,\n    colprefix=\"BTC:\",\n    **{k: \"BTC:\" + k for k in ['open', 'high', 'low', 'close', 'volume']}\n)\n\n\nwith Module(\"coinbase\") as coinbase_ns:\n    coinbase_nodes = [Stream(name, list(coinbase_btc[name])) for name in coinbase_btc.columns]\n    coinbase_nodes += [Stream(name, list(coinbase_eth[name])) for name in coinbase_eth.columns]\n    \n\n# Add all features for coinbase ethereum\nbitstamp_btc = bitstamp_data.loc[:, [name.startswith(\"BTC\") for name in bitstamp_data.columns]]  \nbitstamp_ltc = bitstamp_data.loc[:, [name.startswith(\"LTC\") for name in bitstamp_data.columns]]\n\nta.add_all_ta_features(\n    bitstamp_ltc,\n    colprefix=\"LTC:\",\n    **{k: \"LTC:\" + k for k in ['open', 'high', 'low', 'close', 'volume']}\n)\n\nwith Module(\"bitstamp\") as bitstamp_ns:\n    bitstamp_nodes = [Stream(name, list(bitstamp_btc[name])) for name in bitstamp_btc.columns]\n    bitstamp_nodes += [Stream(name, list(bitstamp_ltc[name])) for name in bitstamp_ltc.columns]\n\n\nfeed = DataFeed([coinbase_ns, bitstamp_ns])\n```\n\n    /usr/local/lib/python3.7/site-packages/ta/wrapper.py:30: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      fillna=fillna)\n    /usr/local/lib/python3.7/site-packages/ta/wrapper.py:33: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      fillna=fillna)\n    /usr/local/lib/python3.7/site-packages/ta/wrapper.py:38: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      fillna=fillna)\n    /usr/local/lib/python3.7/site-packages/ta/wrapper.py:41: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      fillna=fillna)\n    /usr/local/lib/python3.7/site-packages/ta/wrapper.py:47: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      fillna=fillna)\n    /usr/local/lib/python3.7/site-packages/ta/trend.py:170: RuntimeWarning: invalid value encountered in double_scalars\n      dip[i] = 100 * (dip_mio[i]/trs[i])\n    /usr/local/lib/python3.7/site-packages/ta/trend.py:174: RuntimeWarning: invalid value encountered in double_scalars\n      din[i] = 100 * (din_mio[i]/trs[i])\n\n\n\n```python\nfeed.next()\n```\n\n\n\n\n    {'coinbase:/BTC:open': 2505.56,\n     'coinbase:/BTC:high': 2513.38,\n     'coinbase:/BTC:low': 2495.12,\n     'coinbase:/BTC:close': 2509.17,\n     'coinbase:/BTC:volume_btc': 114.6,\n     'coinbase:/BTC:volume': 287000.32,\n     'coinbase:/BTC:volume_adi': 471514.15080526855,\n     'coinbase:/BTC:volume_obv': nan,\n     'coinbase:/BTC:volume_cmf': 0.5388828039430464,\n     'coinbase:/BTC:volume_fi': nan,\n     'coinbase:/BTC:volume_em': nan,\n     'coinbase:/BTC:volume_vpt': -187654.42529420118,\n     'coinbase:/BTC:volume_nvi': 1000.0,\n     'coinbase:/BTC:volatility_atr': 86.38199331252785,\n     'coinbase:/BTC:volatility_bbh': 2509.17,\n     'coinbase:/BTC:volatility_bbl': 2509.17,\n     'coinbase:/BTC:volatility_bbm': 2509.17,\n     'coinbase:/BTC:volatility_bbhi': 0.0,\n     'coinbase:/BTC:volatility_bbli': 0.0,\n     'coinbase:/BTC:volatility_kcc': 2505.89,\n     'coinbase:/BTC:volatility_kch': 2524.15,\n     'coinbase:/BTC:volatility_kcl': 2487.6299999999997,\n     'coinbase:/BTC:volatility_kchi': 0.0,\n     'coinbase:/BTC:volatility_kcli': 0.0,\n     'coinbase:/BTC:volatility_dch': 2509.17,\n     'coinbase:/BTC:volatility_dcl': 2509.17,\n     'coinbase:/BTC:volatility_dchi': 0.0,\n     'coinbase:/BTC:volatility_dcli': 0.0,\n     'coinbase:/BTC:trend_macd': nan,\n     'coinbase:/BTC:trend_macd_signal': nan,\n     'coinbase:/BTC:trend_macd_diff': nan,\n     'coinbase:/BTC:trend_ema_fast': nan,\n     'coinbase:/BTC:trend_ema_slow': nan,\n     'coinbase:/BTC:trend_adx': 0.0,\n     'coinbase:/BTC:trend_adx_pos': 0.0,\n     'coinbase:/BTC:trend_adx_neg': 0.0,\n     'coinbase:/BTC:trend_vortex_ind_pos': nan,\n     'coinbase:/BTC:trend_vortex_ind_neg': nan,\n     'coinbase:/BTC:trend_vortex_diff': nan,\n     'coinbase:/BTC:trend_trix': nan,\n     'coinbase:/BTC:trend_mass_index': 0.0,\n     'coinbase:/BTC:trend_cci': nan,\n     'coinbase:/BTC:trend_dpo': 4750.493965939994,\n     'coinbase:/BTC:trend_kst': -654.3682997212794,\n     'coinbase:/BTC:trend_kst_sig': -654.3682997212794,\n     'coinbase:/BTC:trend_kst_diff': 0.0,\n     'coinbase:/BTC:trend_ichimoku_a': 2504.25,\n     'coinbase:/BTC:trend_ichimoku_b': 2504.25,\n     'coinbase:/BTC:trend_visual_ichimoku_a': 7247.04960378494,\n     'coinbase:/BTC:trend_visual_ichimoku_b': 7236.05851923677,\n     'coinbase:/BTC:trend_aroon_up': 4.0,\n     'coinbase:/BTC:trend_aroon_down': 4.0,\n     'coinbase:/BTC:trend_aroon_ind': 0.0,\n     'coinbase:/BTC:momentum_rsi': nan,\n     'coinbase:/BTC:momentum_mfi': nan,\n     'coinbase:/BTC:momentum_tsi': -100.0,\n     'coinbase:/BTC:momentum_uo': 0.29488656417987874,\n     'coinbase:/BTC:momentum_stoch': 76.94414019715232,\n     'coinbase:/BTC:momentum_stoch_signal': 76.94414019715232,\n     'coinbase:/BTC:momentum_wr': -23.055859802847678,\n     'coinbase:/BTC:momentum_ao': 0.0,\n     'coinbase:/BTC:momentum_kama': nan,\n     'coinbase:/BTC:others_dr': -65.43682997212794,\n     'coinbase:/BTC:others_dlr': nan,\n     'coinbase:/BTC:others_cr': 0.0,\n     'coinbase:/ETH:open': 279.98,\n     'coinbase:/ETH:high': 279.99,\n     'coinbase:/ETH:low': 272.1,\n     'coinbase:/ETH:close': 275.01,\n     'coinbase:/ETH:volume_eth': 2455.28,\n     'coinbase:/ETH:volume': 679358.87,\n     'bitstamp:/BTC:open': 2506.5,\n     'bitstamp:/BTC:high': 2510.62,\n     'bitstamp:/BTC:low': 2495.5,\n     'bitstamp:/BTC:close': 2500.0,\n     'bitstamp:/BTC:volume_btc': 208.52,\n     'bitstamp:/BTC:volume': 521903.7,\n     'bitstamp:/LTC:open': 39.67,\n     'bitstamp:/LTC:high': 39.67,\n     'bitstamp:/LTC:low': 39.32,\n     'bitstamp:/LTC:close': 39.45,\n     'bitstamp:/LTC:volume_ltc': 49.61,\n     'bitstamp:/LTC:volume': 1957.48,\n     'bitstamp:/LTC:volume_adi': 5689.854874666357,\n     'bitstamp:/LTC:volume_obv': nan,\n     'bitstamp:/LTC:volume_cmf': -0.2571428571428455,\n     'bitstamp:/LTC:volume_fi': nan,\n     'bitstamp:/LTC:volume_em': nan,\n     'bitstamp:/LTC:volume_vpt': -894.8193871375488,\n     'bitstamp:/LTC:volume_nvi': 1000.0,\n     'bitstamp:/LTC:volatility_atr': 1.6566685515031572,\n     'bitstamp:/LTC:volatility_bbh': 39.45,\n     'bitstamp:/LTC:volatility_bbl': 39.45,\n     'bitstamp:/LTC:volatility_bbm': 39.45,\n     'bitstamp:/LTC:volatility_bbhi': 0.0,\n     'bitstamp:/LTC:volatility_bbli': 0.0,\n     'bitstamp:/LTC:volatility_kcc': 39.480000000000004,\n     'bitstamp:/LTC:volatility_kch': 39.830000000000005,\n     'bitstamp:/LTC:volatility_kcl': 39.13,\n     'bitstamp:/LTC:volatility_kchi': 0.0,\n     'bitstamp:/LTC:volatility_kcli': 0.0,\n     'bitstamp:/LTC:volatility_dch': 39.45,\n     'bitstamp:/LTC:volatility_dcl': 39.45,\n     'bitstamp:/LTC:volatility_dchi': 0.0,\n     'bitstamp:/LTC:volatility_dcli': 0.0,\n     'bitstamp:/LTC:trend_macd': nan,\n     'bitstamp:/LTC:trend_macd_signal': nan,\n     'bitstamp:/LTC:trend_macd_diff': nan,\n     'bitstamp:/LTC:trend_ema_fast': nan,\n     'bitstamp:/LTC:trend_ema_slow': nan,\n     'bitstamp:/LTC:trend_adx': 0.0,\n     'bitstamp:/LTC:trend_adx_pos': 0.0,\n     'bitstamp:/LTC:trend_adx_neg': 0.0,\n     'bitstamp:/LTC:trend_vortex_ind_pos': nan,\n     'bitstamp:/LTC:trend_vortex_ind_neg': nan,\n     'bitstamp:/LTC:trend_vortex_diff': nan,\n     'bitstamp:/LTC:trend_trix': nan,\n     'bitstamp:/LTC:trend_mass_index': 0.0,\n     'bitstamp:/LTC:trend_cci': nan,\n     'bitstamp:/LTC:trend_dpo': 47.947129529284254,\n     'bitstamp:/LTC:trend_kst': -548.612177396725,\n     'bitstamp:/LTC:trend_kst_sig': -548.612177396725,\n     'bitstamp:/LTC:trend_kst_diff': 0.0,\n     'bitstamp:/LTC:trend_ichimoku_a': 39.495000000000005,\n     'bitstamp:/LTC:trend_ichimoku_b': 39.495000000000005,\n     'bitstamp:/LTC:trend_visual_ichimoku_a': 87.28460785468594,\n     'bitstamp:/LTC:trend_visual_ichimoku_b': 87.22703670546106,\n     'bitstamp:/LTC:trend_aroon_up': 4.0,\n     'bitstamp:/LTC:trend_aroon_down': 4.0,\n     'bitstamp:/LTC:trend_aroon_ind': 0.0,\n     'bitstamp:/LTC:momentum_rsi': nan,\n     'bitstamp:/LTC:momentum_mfi': nan,\n     'bitstamp:/LTC:momentum_tsi': -100.0,\n     'bitstamp:/LTC:momentum_uo': 0.27039883885084753,\n     'bitstamp:/LTC:momentum_stoch': 37.14285714285772,\n     'bitstamp:/LTC:momentum_stoch_signal': 37.14285714285772,\n     'bitstamp:/LTC:momentum_wr': -62.85714285714228,\n     'bitstamp:/LTC:momentum_ao': 0.0,\n     'bitstamp:/LTC:momentum_kama': nan,\n     'bitstamp:/LTC:others_dr': -54.861217739672504,\n     'bitstamp:/LTC:others_dlr': nan,\n     'bitstamp:/LTC:others_cr': 0.0}\n\n\n\n## Portfolio\n\nMake the portfolio using the any combinations of exchanges and intruments that the exchange supports\n\n\n```python\nfrom tensortrade.instruments import USD, BTC, ETH, LTC\nfrom tensortrade.wallets import Wallet, Portfolio\n\nportfolio = Portfolio(USD, [\n    Wallet(coinbase, 10000 * USD),\n    Wallet(coinbase, 10 * BTC),\n    Wallet(coinbase, 5 * ETH),\n    Wallet(bitstamp, 1000 * USD),\n    Wallet(bitstamp, 5 * BTC),\n    Wallet(bitstamp, 3 * LTC),\n])\n```\n\n## Environment\n\n\n```python\nfrom tensortrade.environments import TradingEnvironment\n\nenv = TradingEnvironment(\n    feed=feed,\n    portfolio=portfolio,\n    action_scheme='managed-risk',\n    reward_scheme='simple',\n    window_size=15,\n    enable_logger=False\n)\n```\n\n\n```python\nenv.feed.next()\n```\n\n\n\n\n    {'coinbase:/BTC:open': 2505.56,\n     'coinbase:/BTC:high': 2513.38,\n     'coinbase:/BTC:low': 2495.12,\n     'coinbase:/BTC:close': 2509.17,\n     'coinbase:/BTC:volume_btc': 114.6,\n     'coinbase:/BTC:volume': 287000.32,\n     'coinbase:/BTC:volume_adi': 471514.15080526855,\n     'coinbase:/BTC:volume_obv': nan,\n     'coinbase:/BTC:volume_cmf': 0.5388828039430464,\n     'coinbase:/BTC:volume_fi': nan,\n     'coinbase:/BTC:volume_em': nan,\n     'coinbase:/BTC:volume_vpt': -187654.42529420118,\n     'coinbase:/BTC:volume_nvi': 1000.0,\n     'coinbase:/BTC:volatility_atr': 86.38199331252785,\n     'coinbase:/BTC:volatility_bbh': 2509.17,\n     'coinbase:/BTC:volatility_bbl': 2509.17,\n     'coinbase:/BTC:volatility_bbm': 2509.17,\n     'coinbase:/BTC:volatility_bbhi': 0.0,\n     'coinbase:/BTC:volatility_bbli': 0.0,\n     'coinbase:/BTC:volatility_kcc': 2505.89,\n     'coinbase:/BTC:volatility_kch': 2524.15,\n     'coinbase:/BTC:volatility_kcl': 2487.6299999999997,\n     'coinbase:/BTC:volatility_kchi': 0.0,\n     'coinbase:/BTC:volatility_kcli': 0.0,\n     'coinbase:/BTC:volatility_dch': 2509.17,\n     'coinbase:/BTC:volatility_dcl': 2509.17,\n     'coinbase:/BTC:volatility_dchi': 0.0,\n     'coinbase:/BTC:volatility_dcli': 0.0,\n     'coinbase:/BTC:trend_macd': nan,\n     'coinbase:/BTC:trend_macd_signal': nan,\n     'coinbase:/BTC:trend_macd_diff': nan,\n     'coinbase:/BTC:trend_ema_fast': nan,\n     'coinbase:/BTC:trend_ema_slow': nan,\n     'coinbase:/BTC:trend_adx': 0.0,\n     'coinbase:/BTC:trend_adx_pos': 0.0,\n     'coinbase:/BTC:trend_adx_neg': 0.0,\n     'coinbase:/BTC:trend_vortex_ind_pos': nan,\n     'coinbase:/BTC:trend_vortex_ind_neg': nan,\n     'coinbase:/BTC:trend_vortex_diff': nan,\n     'coinbase:/BTC:trend_trix': nan,\n     'coinbase:/BTC:trend_mass_index': 0.0,\n     'coinbase:/BTC:trend_cci': nan,\n     'coinbase:/BTC:trend_dpo': 4750.493965939994,\n     'coinbase:/BTC:trend_kst': -654.3682997212794,\n     'coinbase:/BTC:trend_kst_sig': -654.3682997212794,\n     'coinbase:/BTC:trend_kst_diff': 0.0,\n     'coinbase:/BTC:trend_ichimoku_a': 2504.25,\n     'coinbase:/BTC:trend_ichimoku_b': 2504.25,\n     'coinbase:/BTC:trend_visual_ichimoku_a': 7247.04960378494,\n     'coinbase:/BTC:trend_visual_ichimoku_b': 7236.05851923677,\n     'coinbase:/BTC:trend_aroon_up': 4.0,\n     'coinbase:/BTC:trend_aroon_down': 4.0,\n     'coinbase:/BTC:trend_aroon_ind': 0.0,\n     'coinbase:/BTC:momentum_rsi': nan,\n     'coinbase:/BTC:momentum_mfi': nan,\n     'coinbase:/BTC:momentum_tsi': -100.0,\n     'coinbase:/BTC:momentum_uo': 0.29488656417987874,\n     'coinbase:/BTC:momentum_stoch': 76.94414019715232,\n     'coinbase:/BTC:momentum_stoch_signal': 76.94414019715232,\n     'coinbase:/BTC:momentum_wr': -23.055859802847678,\n     'coinbase:/BTC:momentum_ao': 0.0,\n     'coinbase:/BTC:momentum_kama': nan,\n     'coinbase:/BTC:others_dr': -65.43682997212794,\n     'coinbase:/BTC:others_dlr': nan,\n     'coinbase:/BTC:others_cr': 0.0,\n     'coinbase:/ETH:open': 279.98,\n     'coinbase:/ETH:high': 279.99,\n     'coinbase:/ETH:low': 272.1,\n     'coinbase:/ETH:close': 275.01,\n     'coinbase:/ETH:volume_eth': 2455.28,\n     'coinbase:/ETH:volume': 679358.87,\n     'bitstamp:/BTC:open': 2506.5,\n     'bitstamp:/BTC:high': 2510.62,\n     'bitstamp:/BTC:low': 2495.5,\n     'bitstamp:/BTC:close': 2500.0,\n     'bitstamp:/BTC:volume_btc': 208.52,\n     'bitstamp:/BTC:volume': 521903.7,\n     'bitstamp:/LTC:open': 39.67,\n     'bitstamp:/LTC:high': 39.67,\n     'bitstamp:/LTC:low': 39.32,\n     'bitstamp:/LTC:close': 39.45,\n     'bitstamp:/LTC:volume_ltc': 49.61,\n     'bitstamp:/LTC:volume': 1957.48,\n     'bitstamp:/LTC:volume_adi': 5689.854874666357,\n     'bitstamp:/LTC:volume_obv': nan,\n     'bitstamp:/LTC:volume_cmf': -0.2571428571428455,\n     'bitstamp:/LTC:volume_fi': nan,\n     'bitstamp:/LTC:volume_em': nan,\n     'bitstamp:/LTC:volume_vpt': -894.8193871375488,\n     'bitstamp:/LTC:volume_nvi': 1000.0,\n     'bitstamp:/LTC:volatility_atr': 1.6566685515031572,\n     'bitstamp:/LTC:volatility_bbh': 39.45,\n     'bitstamp:/LTC:volatility_bbl': 39.45,\n     'bitstamp:/LTC:volatility_bbm': 39.45,\n     'bitstamp:/LTC:volatility_bbhi': 0.0,\n     'bitstamp:/LTC:volatility_bbli': 0.0,\n     'bitstamp:/LTC:volatility_kcc': 39.480000000000004,\n     'bitstamp:/LTC:volatility_kch': 39.830000000000005,\n     'bitstamp:/LTC:volatility_kcl': 39.13,\n     'bitstamp:/LTC:volatility_kchi': 0.0,\n     'bitstamp:/LTC:volatility_kcli': 0.0,\n     'bitstamp:/LTC:volatility_dch': 39.45,\n     'bitstamp:/LTC:volatility_dcl': 39.45,\n     'bitstamp:/LTC:volatility_dchi': 0.0,\n     'bitstamp:/LTC:volatility_dcli': 0.0,\n     'bitstamp:/LTC:trend_macd': nan,\n     'bitstamp:/LTC:trend_macd_signal': nan,\n     'bitstamp:/LTC:trend_macd_diff': nan,\n     'bitstamp:/LTC:trend_ema_fast': nan,\n     'bitstamp:/LTC:trend_ema_slow': nan,\n     'bitstamp:/LTC:trend_adx': 0.0,\n     'bitstamp:/LTC:trend_adx_pos': 0.0,\n     'bitstamp:/LTC:trend_adx_neg': 0.0,\n     'bitstamp:/LTC:trend_vortex_ind_pos': nan,\n     'bitstamp:/LTC:trend_vortex_ind_neg': nan,\n     'bitstamp:/LTC:trend_vortex_diff': nan,\n     'bitstamp:/LTC:trend_trix': nan,\n     'bitstamp:/LTC:trend_mass_index': 0.0,\n     'bitstamp:/LTC:trend_cci': nan,\n     'bitstamp:/LTC:trend_dpo': 47.947129529284254,\n     'bitstamp:/LTC:trend_kst': -548.612177396725,\n     'bitstamp:/LTC:trend_kst_sig': -548.612177396725,\n     'bitstamp:/LTC:trend_kst_diff': 0.0,\n     'bitstamp:/LTC:trend_ichimoku_a': 39.495000000000005,\n     'bitstamp:/LTC:trend_ichimoku_b': 39.495000000000005,\n     'bitstamp:/LTC:trend_visual_ichimoku_a': 87.28460785468594,\n     'bitstamp:/LTC:trend_visual_ichimoku_b': 87.22703670546106,\n     'bitstamp:/LTC:trend_aroon_up': 4.0,\n     'bitstamp:/LTC:trend_aroon_down': 4.0,\n     'bitstamp:/LTC:trend_aroon_ind': 0.0,\n     'bitstamp:/LTC:momentum_rsi': nan,\n     'bitstamp:/LTC:momentum_mfi': nan,\n     'bitstamp:/LTC:momentum_tsi': -100.0,\n     'bitstamp:/LTC:momentum_uo': 0.27039883885084753,\n     'bitstamp:/LTC:momentum_stoch': 37.14285714285772,\n     'bitstamp:/LTC:momentum_stoch_signal': 37.14285714285772,\n     'bitstamp:/LTC:momentum_wr': -62.85714285714228,\n     'bitstamp:/LTC:momentum_ao': 0.0,\n     'bitstamp:/LTC:momentum_kama': nan,\n     'bitstamp:/LTC:others_dr': -54.861217739672504,\n     'bitstamp:/LTC:others_dlr': nan,\n     'bitstamp:/LTC:others_cr': 0.0,\n     'coinbase:/USD-BTC': 2509.17,\n     'coinbase:/USD-ETH': 275.01,\n     'coinbase:/USD:/free': 10000,\n     'coinbase:/USD:/locked': 0,\n     'coinbase:/USD:/total': 10000,\n     'coinbase:/BTC:/free': 10,\n     'coinbase:/BTC:/locked': 0,\n     'coinbase:/BTC:/total': 10,\n     'coinbase:/BTC:/worth': 25091.7,\n     'coinbase:/ETH:/free': 5,\n     'coinbase:/ETH:/locked': 0,\n     'coinbase:/ETH:/total': 5,\n     'coinbase:/ETH:/worth': 1375.05,\n     'bitstamp:/USD-BTC': 2500.0,\n     'bitstamp:/USD-LTC': 39.45,\n     'bitstamp:/USD:/free': 1000,\n     'bitstamp:/USD:/locked': 0,\n     'bitstamp:/USD:/total': 1000,\n     'bitstamp:/BTC:/free': 5,\n     'bitstamp:/BTC:/locked': 0,\n     'bitstamp:/BTC:/total': 5,\n     'bitstamp:/BTC:/worth': 12500.0,\n     'bitstamp:/LTC:/free': 3,\n     'bitstamp:/LTC:/locked': 0,\n     'bitstamp:/LTC:/total': 3,\n     'bitstamp:/LTC:/worth': 118.35000000000001,\n     'net_worth': 50085.1}\n\n\n", "meta": {"hexsha": "f10482291a0d2623c8fa13f87552d0a9921498e8", "size": 41529, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/setup_environment_tutorial.ipynb", "max_stars_repo_name": "owodunni/tensortrade", "max_stars_repo_head_hexsha": "d6d7fb12f926b3c451d7e200cb693d750a35f95a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2020-06-05T22:39:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T03:09:12.000Z", "max_issues_repo_path": "examples/setup_environment_tutorial.ipynb", "max_issues_repo_name": "owodunni/tensortrade", "max_issues_repo_head_hexsha": "d6d7fb12f926b3c451d7e200cb693d750a35f95a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-17T06:38:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-17T06:38:27.000Z", "max_forks_repo_path": "examples/setup_environment_tutorial.ipynb", "max_forks_repo_name": "owodunni/tensortrade", "max_forks_repo_head_hexsha": "d6d7fb12f926b3c451d7e200cb693d750a35f95a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-06-01T12:09:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-18T14:45:29.000Z", "avg_line_length": 41.3223880597, "max_line_length": 497, "alphanum_fraction": 0.5157600713, "converted": true, "num_tokens": 10089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406687981454, "lm_q2_score": 0.06954175077306284, "lm_q1q2_score": 0.02625483909625609}}
{"text": "\n\n# PandemicDataHack \u0442\u0440\u0435\u043a 3\n\n\n\u0421\u043e\u0437\u0434\u0430\u0442\u044c \u0434\u043b\u044f \u043f\u043e\u0440\u0442\u0430\u043b\u0430 \u00ab\u0420\u0430\u0431\u043e\u0442\u0430 \u0432 \u0420\u043e\u0441\u0441\u0438\u0438\u00bb \u043c\u043e\u0434\u0435\u043b\u044c \u043c\u0430\u0448\u0438\u043d\u043d\u043e\u0433\u043e \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u044f, \u043f\u043e\u0437\u0432\u043e\u043b\u044f\u044e\u0449\u0443\u044e \u043e\u0446\u0435\u043d\u0438\u0442\u044c \u0441\u0442\u043e\u0438\u043c\u043e\u0441\u0442\u044c \u043d\u0430\u0432\u044b\u043a\u043e\u0432, \u043a\u043e\u0442\u043e\u0440\u044b\u043c\u0438 \u043e\u0431\u043b\u0430\u0434\u0430\u0435\u0442 \u0440\u0430\u0431\u043e\u0442\u043d\u0438\u043a.\n\n## \u0414\u0430\u043d\u043d\u044b\u0435. \u0412\u0441\u0451 \u0436\u0435 .csv\n\n\u041e\u043f\u0438\u0441\u0430\u043d\u0438\u0435 \u0441\u043e\u0434\u0435\u0440\u0436\u0430\u043d\u0438\u044f [\u0432\u0441\u0451 \u0435\u0449\u0451 \u0432\u0435\u0440\u043d\u043e](https://s3.us-west-2.amazonaws.com/secure.notion-static.com/9d417b96-c50f-478a-ad75-9da03c28df21/resume_description.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAT73L2G45O3KS52Y5%2F20201217%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20201217T150518Z&X-Amz-Expires=86400&X-Amz-Signature=81edd5cc9af7504461b914442f2c40edc7878648ed15aaedf32759fe55963c4f&X-Amz-SignedHeaders=host&response-content-disposition=filename%20%3D%22resume_description.pdf%22).\n\n\n```python\nimport pandas as pd\n```\n\n\n```python\n# \u041e\u0441\u043d\u043e\u0432\u043d\u0430\u044f \u0432\u044b\u0431\u043e\u0440\u043a\u0430, \u0440\u0430\u0437\u0431\u0438\u0442\u0430\u044f \u043d\u0430 train \u0438 test\n\ntrain = pd.read_csv('Public/train.csv', sep=';')\ntest = pd.read_csv('Public/test.csv', sep=';')\n\n# \u0414\u043e\u043f\u043e\u043b\u043d\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435 \n\ned = pd.read_csv('Public/education.csv', sep=';')\nws = pd.read_csv('Public/worldskills.csv', sep=';')\nem = pd.read_csv('Public/employements.csv', sep=';')\n```\n\n    /Users/alisa/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py:3063: DtypeWarning: Columns (18) have mixed types.Specify dtype option on import or set low_memory=False.\n      interactivity=interactivity, compiler=compiler, result=result)\n\n\n\n```python\ntrain.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>id</th>\n      <th>position</th>\n      <th>region</th>\n      <th>industry</th>\n      <th>locality</th>\n      <th>locality_name</th>\n      <th>education_type</th>\n      <th>drive_licences</th>\n      <th>citizenship</th>\n      <th>schedule</th>\n      <th>...</th>\n      <th>relocation_ready</th>\n      <th>travel_ready</th>\n      <th>retraining_ready</th>\n      <th>is_worldskills_participant</th>\n      <th>has_qualifications</th>\n      <th>completeness_rate</th>\n      <th>creation_date</th>\n      <th>modification_date</th>\n      <th>publish_date</th>\n      <th>salary</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0</td>\n      <td>\u0421\u043f\u0435\u0446\u0438\u0430\u043b\u0438\u0441\u0442</td>\n      <td>\u0422\u0443\u043b\u044c\u0441\u043a\u0430\u044f \u043e\u0431\u043b\u0430\u0441\u0442\u044c</td>\n      <td>\u0413\u043e\u0441\u0443\u0434\u0430\u0440\u0441\u0442\u0432\u0435\u043d\u043d\u0430\u044f \u0441\u043b\u0443\u0436\u0431\u0430, \u043d\u0435\u043a\u043e\u043c\u043c\u0435\u0440\u0447\u0435\u0441\u043a\u0438\u0435 \u043e\u0440\u0433\u0430\u043d\u0438\u0437...</td>\n      <td>7100000100000</td>\n      <td>\u0422\u0443\u043b\u0430</td>\n      <td>\u041d\u0435\u0437\u0430\u043a\u043e\u043d\u0447\u0435\u043d\u043d\u043e\u0435 \u0432\u044b\u0441\u0448\u0435\u0435</td>\n      <td>[B]</td>\n      <td>\u0420\u043e\u0441\u0441\u0438\u0439\u0441\u043a\u0430\u044f \u0424\u0435\u0434\u0435\u0440\u0430\u0446\u0438\u044f</td>\n      <td>\u041f\u043e\u043b\u043d\u044b\u0439 \u0440\u0430\u0431\u043e\u0447\u0438\u0439 \u0434\u0435\u043d\u044c</td>\n      <td>...</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>64.0</td>\n      <td>2020-05-07</td>\n      <td>2020-05-08</td>\n      <td>2020-05-07</td>\n      <td>37500</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>\u041b\u0430\u0431\u043e\u0440\u0430\u043d\u0442</td>\n      <td>\u0410\u043b\u0442\u0430\u0439\u0441\u043a\u0438\u0439 \u043a\u0440\u0430\u0439</td>\n      <td>\u0413\u043e\u0441\u0443\u0434\u0430\u0440\u0441\u0442\u0432\u0435\u043d\u043d\u0430\u044f \u0441\u043b\u0443\u0436\u0431\u0430, \u043d\u0435\u043a\u043e\u043c\u043c\u0435\u0440\u0447\u0435\u0441\u043a\u0438\u0435 \u043e\u0440\u0433\u0430\u043d\u0438\u0437...</td>\n      <td>2200000100000</td>\n      <td>\u0411\u0430\u0440\u043d\u0430\u0443\u043b</td>\n      <td>\u0412\u044b\u0441\u0448\u0435\u0435</td>\n      <td>[B]</td>\n      <td>\u0420\u043e\u0441\u0441\u0438\u0439\u0441\u043a\u0430\u044f \u0424\u0435\u0434\u0435\u0440\u0430\u0446\u0438\u044f</td>\n      <td>\u041f\u043e\u043b\u043d\u044b\u0439 \u0440\u0430\u0431\u043e\u0447\u0438\u0439 \u0434\u0435\u043d\u044c</td>\n      <td>...</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>88.0</td>\n      <td>2020-10-21</td>\n      <td>2020-10-27</td>\n      <td>2020-10-27</td>\n      <td>14000</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>3</td>\n      <td>\u0421\u043f\u0435\u0446\u0438\u0430\u043b\u0438\u0441\u0442, \u0430\u0434\u043c\u0438\u043d\u0438\u0441\u0442\u0440\u0430\u0442\u043e\u0440, \u0431\u0443\u0445\u0433\u0430\u043b\u0442\u0435\u0440, \u044d\u043a\u043e\u043d\u043e\u043c\u0438\u0441\u0442</td>\n      <td>\u0423\u043b\u044c\u044f\u043d\u043e\u0432\u0441\u043a\u0430\u044f \u043e\u0431\u043b\u0430\u0441\u0442\u044c</td>\n      <td>\u0410\u0434\u043c\u0438\u043d\u0438\u0441\u0442\u0440\u0430\u0442\u0438\u0432\u043d\u0430\u044f \u0440\u0430\u0431\u043e\u0442\u0430, \u0441\u0435\u043a\u0440\u0435\u0442\u0430\u0440\u0438\u0430\u0442, \u0410\u0425\u041e</td>\n      <td>7300000200000</td>\n      <td>\u0414\u0438\u043c\u0438\u0442\u0440\u043e\u0432\u0433\u0440\u0430\u0434</td>\n      <td>\u0412\u044b\u0441\u0448\u0435\u0435</td>\n      <td>[B]</td>\n      <td>\u0420\u043e\u0441\u0441\u0438\u0439\u0441\u043a\u0430\u044f \u0424\u0435\u0434\u0435\u0440\u0430\u0446\u0438\u044f</td>\n      <td>\u041f\u043e\u043b\u043d\u044b\u0439 \u0440\u0430\u0431\u043e\u0447\u0438\u0439 \u0434\u0435\u043d\u044c</td>\n      <td>...</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>True</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>78.0</td>\n      <td>2019-04-25</td>\n      <td>2020-02-04</td>\n      <td>2020-02-04</td>\n      <td>24600</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>4</td>\n      <td>\u0421\u043f\u0435\u0446\u0438\u0430\u043b\u0438\u0441\u0442</td>\n      <td>\u0421\u0432\u0435\u0440\u0434\u043b\u043e\u0432\u0441\u043a\u0430\u044f \u043e\u0431\u043b\u0430\u0441\u0442\u044c</td>\n      <td>\u0413\u043e\u0441\u0443\u0434\u0430\u0440\u0441\u0442\u0432\u0435\u043d\u043d\u0430\u044f \u0441\u043b\u0443\u0436\u0431\u0430, \u043d\u0435\u043a\u043e\u043c\u043c\u0435\u0440\u0447\u0435\u0441\u043a\u0438\u0435 \u043e\u0440\u0433\u0430\u043d\u0438\u0437...</td>\n      <td>6600002300000</td>\n      <td>\u041d\u0438\u0436\u043d\u0438\u0439 \u0422\u0430\u0433\u0438\u043b</td>\n      <td>\u0412\u044b\u0441\u0448\u0435\u0435</td>\n      <td>[B]</td>\n      <td>\u0420\u043e\u0441\u0441\u0438\u0439\u0441\u043a\u0430\u044f \u0424\u0435\u0434\u0435\u0440\u0430\u0446\u0438\u044f</td>\n      <td>\u041f\u043e\u043b\u043d\u044b\u0439 \u0440\u0430\u0431\u043e\u0447\u0438\u0439 \u0434\u0435\u043d\u044c</td>\n      <td>...</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>91.0</td>\n      <td>2020-09-19</td>\n      <td>2020-09-20</td>\n      <td>2020-09-19</td>\n      <td>16075</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>5</td>\n      <td>\u0418\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u043e\u0440 \u043f\u043e \u043f\u043b\u0430\u0432\u0430\u043d\u0438\u044e</td>\n      <td>\u0418\u0440\u043a\u0443\u0442\u0441\u043a\u0430\u044f \u043e\u0431\u043b\u0430\u0441\u0442\u044c</td>\n      <td>\u0417\u0434\u0440\u0430\u0432\u043e\u043e\u0445\u0440\u0430\u043d\u0435\u043d\u0438\u0435, \u0441\u043f\u043e\u0440\u0442, \u043a\u0440\u0430\u0441\u043e\u0442\u0430, \u0441\u043e\u0446\u0438\u0430\u043b\u044c\u043d\u043e\u0435 \u043e\u0431...</td>\n      <td>3800000400000</td>\n      <td>\u0410\u043d\u0433\u0430\u0440\u0441\u043a</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>\u0420\u043e\u0441\u0441\u0438\u0439\u0441\u043a\u0430\u044f \u0424\u0435\u0434\u0435\u0440\u0430\u0446\u0438\u044f</td>\n      <td>\u041f\u043e\u043b\u043d\u044b\u0439 \u0440\u0430\u0431\u043e\u0447\u0438\u0439 \u0434\u0435\u043d\u044c</td>\n      <td>...</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>58.0</td>\n      <td>2020-04-20</td>\n      <td>2020-09-09</td>\n      <td>2020-04-21</td>\n      <td>22080</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 25 columns</p>\n</div>\n\n\n\n\n```python\nset(train.columns.to_list()) - set(test.columns.to_list())\n```\n\n\n\n\n    {'salary'}\n\n\n\n\n```python\ndates = train.publish_date.unique()\nprint(dates.min(), dates.max())\n```\n\n    2015-05-21 2020-12-14\n\n\n### \u041a\u043e\u043b\u043e\u043d\u043a\u0438 \u0441 \u0441\u044e\u0440\u043f\u0440\u0438\u0437\u043e\u043c\n\n\n```python\ntrain.drive_licences.value_counts()[:5]\n```\n\n\n\n\n    [B]          90304\n    [B, C]       16871\n    [A, B, C]     3634\n    [A, B]        3315\n    [B, C, D]     1661\n    Name: drive_licences, dtype: int64\n\n\n\n\n```python\ntrain.schedule.value_counts()[:5]\n```\n\n\n\n\n    \u041f\u043e\u043b\u043d\u044b\u0439 \u0440\u0430\u0431\u043e\u0447\u0438\u0439 \u0434\u0435\u043d\u044c                   235407\n    \u041f\u043e\u043b\u043d\u044b\u0439 \u0440\u0430\u0431\u043e\u0447\u0438\u0439 \u0434\u0435\u043d\u044c,\u0421\u043c\u0435\u043d\u043d\u044b\u0439 \u0433\u0440\u0430\u0444\u0438\u043a     14036\n    \u0421\u043c\u0435\u043d\u043d\u044b\u0439 \u0433\u0440\u0430\u0444\u0438\u043a                         11119\n    \u041f\u043e\u043b\u043d\u044b\u0439 \u0440\u0430\u0431\u043e\u0447\u0438\u0439 \u0434\u0435\u043d\u044c,\u0412\u0430\u0445\u0442\u043e\u0432\u044b\u0439 \u043c\u0435\u0442\u043e\u0434      5683\n    \u041d\u0435\u043f\u043e\u043b\u043d\u044b\u0439 \u0440\u0430\u0431\u043e\u0447\u0438\u0439 \u0434\u0435\u043d\u044c                   4261\n    Name: schedule, dtype: int64\n\n\n\n### \u0414\u043e\u043f\u043e\u043b\u043d\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435\n\n\n```python\ned\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>id</th>\n      <th>graduation_year</th>\n      <th>institution</th>\n      <th>description</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0</td>\n      <td>2022.0</td>\n      <td>\"\u0422\u0443\u043b\u044c\u0441\u043a\u0438\u0439 \u0433\u043e\u0441\u0443\u0434\u0430\u0440\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0439 \u0443\u043d\u0438\u0432\u0435\u0440\u0441\u0438\u0442\u0435\u0442\"</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>2016.0</td>\n      <td>\"\u0410\u043b\u0442\u0430\u0439\u0441\u043a\u0438\u0439 \u0433\u043e\u0441\u0443\u0434\u0430\u0440\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0439 \u0430\u0433\u0440\u0430\u0440\u043d\u044b\u0439 \u0443\u043d\u0438\u0432\u0435\u0440\u0441\u0438\u0442\u0435\u0442\"</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2</td>\n      <td>2014.0</td>\n      <td>\"\u0410\u043b\u0442\u0430\u0439\u0441\u043a\u0438\u0439 \u0433\u043e\u0441\u0443\u0434\u0430\u0440\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0439 \u0442\u0435\u0445\u043d\u0438\u0447\u0435\u0441\u043a\u0438\u0439 \u0443\u043d\u0438\u0432\u0435\u0440\u0441...</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>3</td>\n      <td>2003.0</td>\n      <td>\u0413\u041e\u0423 \u0421\u041f\u041e \u0414\u0418\u041c\u0418\u0422\u0420\u041e\u0412\u0413\u0420\u0410\u0414\u0421\u041a\u0418\u0419 \u0422\u0415\u0425\u041d\u0418\u0427\u0415\u0421\u041a\u0418\u0419 \u041a\u041e\u041b\u041b\u0415\u0414\u0416</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>4</td>\n      <td>2005.0</td>\n      <td>\u041d\u0438\u0436\u043d\u0435\u0442\u0430\u0433\u0438\u043b\u044c\u0441\u043a\u0438\u0439 \u0442\u043e\u0440\u0433\u043e\u0432\u043e-\u044d\u043a\u043e\u043d\u043e\u043c\u0438\u0447\u0435\u0441\u043a\u0438\u0439 \u0442\u0435\u0445\u043d\u0438\u043a\u0443\u043c</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>375359</th>\n      <td>437523</td>\n      <td>2005.0</td>\n      <td>\u041a\u0430\u0437\u0430\u0445\u0441\u043a\u0438\u0439 \u041d\u0430\u0446\u0438\u043e\u043d\u0430\u043b\u044c\u043d\u044b\u0439 \u0433\u0443\u043c\u0430\u043d\u0438\u0442\u0430\u0440\u043d\u044b\u0439 \u0443\u043d\u0438\u0432\u0435\u0440\u0441\u0438\u0442\u0435...</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>375360</th>\n      <td>437524</td>\n      <td>2006.0</td>\n      <td>\"\u0418\u0440\u043a\u0443\u0442\u0441\u043a\u0438\u0439 \u0433\u043e\u0441\u0443\u0434\u0430\u0440\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0439 \u0443\u043d\u0438\u0432\u0435\u0440\u0441\u0438\u0442\u0435\u0442\"\" (\u0424\u0413\u0411\u041e...</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>375361</th>\n      <td>437525</td>\n      <td>2011.0</td>\n      <td>\u041c\u041e\u0423\u0421\u041e\u0428  \u211624</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>375362</th>\n      <td>437526</td>\n      <td>2015.0</td>\n      <td>\u0421\u0413\u042d\u0423</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>375363</th>\n      <td>437527</td>\n      <td>2014.0</td>\n      <td>\u041c\u0411\u041e\u0423 \u0421\u041e\u0428 64</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n<p>375364 rows \u00d7 4 columns</p>\n</div>\n\n\n\n\n```python\nlen(ed.id.unique()) / (len(train) + len(test))\n```\n\n\n\n\n    0.8579179894361288\n\n\n\n\n```python\nlen(em.id.unique()) / (len(train) + len(test))\n```\n\n\n\n\n    0.7846977000381689\n\n\n\n\n```python\nlen(ws.id.unique()) / (len(train) + len(test))\n```\n\n\n\n\n    0.0030215140025004056\n\n\n\n### \u0426\u0435\u043b\u0435\u0432\u0430\u044f \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u0430\u044f\n\n\n```python\ntrain[train.salary < 200000].hist(column='salary', bins=10)\n```\n\n\n```python\nfrom matplotlib import pyplot as plt\nsalaries_asc = train.salary[train.salary < 200000].sort_values().to_list()\nplt.plot(salaries_asc)\n```\n\n### \u041c\u0435\u0442\u0440\u0438\u043a\u0430 \u043e\u0446\u0435\u043d\u043a\u0438 \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u0430 \u043c\u043e\u0434\u0435\u043b\u0435\u0439\n\n\u0421\u0440\u0435\u0434\u043d\u0435\u043a\u0432\u0430\u0434\u0440\u0430\u0442\u0438\u0447\u043d\u0430\u044f \u043b\u043e\u0433\u0430\u0440\u0438\u0444\u043c\u0438\u0447\u0435\u0441\u043a\u0430\u044f \u043e\u0448\u0438\u0431\u043a\u0430:\n\n\\begin{equation}\n\\textrm{RMSLE}(y, \\hat{y}) = \\frac{1}{n_{\\textrm{samples}}}\\sum\\limits_{i=0}^{n_{\\textrm{samples}}-1}(\\log_e(1+y_i)-\\log_e(1+\\hat{y}_i))^2\n\\end{equation}\n\n## \u0424\u043e\u0440\u043c\u0430\u0442 \u0440\u0435\u0448\u0435\u043d\u0438\u044f\n\n\n```python\n# \u0418 \u0437\u0434\u0435\u0441\u044c \u0432\u0441\u0451 \u0436\u0435 .csv\n\nimport numpy as np\nsolution = test[['id']].copy()\nmean = train['salary'].mean() + 5000\nsolution['salary'] = pd.Series(np.full(len(test), mean))\n```\n\n\n```python\nsolution.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>id</th>\n      <th>salary</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>2</td>\n      <td>45941.323678</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>6</td>\n      <td>45941.323678</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>7</td>\n      <td>45941.323678</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>11</td>\n      <td>45941.323678</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>16</td>\n      <td>45941.323678</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nsolution.to_csv('my_solution.csv', sep=',', index=False)\n```\n\n## \u041e\u0442\u043a\u0443\u0434\u0430 \u0432\u0437\u044f\u0442\u044c \u0434\u0430\u043d\u043d\u044b\u0435 \u0438 \u043a\u0443\u0434\u0430 \u0441\u0434\u0430\u0432\u0430\u0442\u044c \u043e\u0442\u0432\u0435\u0442\n\n### \u041f\u043b\u0430\u0442\u0444\u043e\u0440\u043c\u0430\n\n[Kaggle](https://www.kaggle.com/): \u043d\u0443\u0436\u043d\u043e \u0437\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0438\u0440\u043e\u0432\u0430\u0442\u044c\u0441\u044f \u0438 \u043e\u0436\u0438\u0434\u0430\u0442\u044c \u0441\u0441\u044b\u043b\u043a\u0443 \u043d\u0430 \u043f\u0440\u0438\u0432\u0430\u0442\u043d\u043e\u0435 \u0441\u043e\u0440\u0435\u0432\u043d\u043e\u0432\u0430\u043d\u0438\u0435. \n\n### \u0412\u0430\u0436\u043d\u043e\n\n\u041d\u0430\u0437\u044b\u0432\u0430\u0439\u0442\u0435 \u043a\u043e\u043c\u0430\u043d\u0434\u0443 \u0442\u0430\u043a \u0436\u0435, \u043a\u0430\u043a \u0432 \u043e\u0431\u0449\u0435\u0439 \u0441\u0438\u0441\u0442\u0435\u043c\u0435 \u0445\u0430\u043a\u0430\u0442\u043e\u043d\u0430.\n\u0412\u0430\u0448\u0438 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u044b \u0432 \u044d\u0442\u043e\u043c \u0441\u043e\u0440\u0435\u0432\u043d\u043e\u0432\u0430\u043d\u0438\u0438 \u043d\u0435 \u0434\u043e\u0431\u0430\u0432\u044f\u0442 \u0432\u0430\u043c \u0440\u0435\u0439\u0442\u0438\u043d\u0433\u0430 \u0432 `kaggle`, \u043f\u043e\u0442\u043e\u043c\u0443 \u0447\u0442\u043e \u0441\u043e\u0440\u0435\u0432\u043d\u043e\u0432\u0430\u043d\u0438\u0435 \u043d\u0435\u043f\u0443\u0431\u043b\u0438\u0447\u043d\u043e\u0435.\n\n### \u041f\u0443\u0431\u043b\u0438\u0447\u043d\u0430\u044f \u0438 \u043f\u0440\u0438\u0432\u0430\u0442\u043d\u0430\u044f \u0442\u0430\u0431\u043b\u0438\u0446\u0430 \u043b\u0438\u0434\u0435\u0440\u043e\u0432\n\n\u0412\u043d\u0443\u0442\u0440\u0438 `kaggle` \u0442\u0435\u0441\u0442\u043e\u0432\u0430\u044f \u0432\u044b\u0431\u043e\u0440\u043a\u0430 \u0440\u0430\u0437\u0434\u0435\u043b\u0435\u043d\u0430 \u043d\u0430 \u043f\u0440\u0438\u0432\u0430\u0442\u043d\u0443\u044e \u0438 \u043f\u0443\u0431\u043b\u0438\u0447\u043d\u0443\u044e. \u041a\u0430\u043a\u0438\u0435 \u0438\u043c\u0435\u043d\u043d\u043e \u043d\u0430\u0431\u043b\u044e\u0434\u0435\u043d\u0438\u044f \u043f\u043e\u043f\u0430\u043b\u0438 \u0432 \u043f\u0440\u0438\u0432\u0430\u0442\u043d\u0443\u044e, \u0432\u044b \u043d\u0435 \u0437\u043d\u0430\u0435\u0442\u0435, \u0438 \u0432\u0441\u0435\u0433\u0434\u0430 \u0441\u0434\u0430\u0451\u0442\u0435 `solution.csv` \u0441 \u043e\u0434\u043d\u0438\u043c \u0438 \u0442\u0435\u043c \u0436\u0435 \u043d\u0430\u0431\u043e\u0440\u043e\u043c \u0438\u043d\u0434\u0435\u043a\u0441\u043e\u0432.\n\n\u041f\u0443\u0431\u043b\u0438\u0447\u043d\u0430\u044f \u0442\u0430\u0431\u043b\u0438\u0446\u0430 \u043b\u0438\u0434\u0435\u0440\u043e\u0432 \u0441\u0442\u0440\u043e\u0438\u0442\u0441\u044f \u043f\u043e \u043f\u0443\u0431\u043b\u0438\u0447\u043d\u043e\u0439 \u0447\u0430\u0441\u0442\u0438 \u0442\u0435\u0441\u0442\u043e\u0432 \u0438 \u0434\u043e\u0441\u0442\u0443\u043f\u043d\u0430 \u0441\u0440\u0430\u0437\u0443 \u0436\u0435.\n\n\u041c\u0435\u0441\u0442\u043e \u043a\u043e\u043c\u0430\u043d\u0434\u044b \u0432 \u043f\u0440\u0438\u0432\u0430\u0442\u043d\u043e\u0439 \u0442\u0430\u0431\u043b\u0438\u0446\u0435 `kaggle` \u043f\u043e\u0441\u0447\u0438\u0442\u0430\u0435\u0442 \u043f\u043e\u0441\u043b\u0435 \u043e\u043a\u043e\u043d\u0447\u0430\u043d\u0438\u044f \u0441\u043e\u0440\u0435\u0432\u043d\u043e\u0432\u0430\u043d\u0438\u044f \u043f\u043e \u043f\u0440\u0438\u0432\u0430\u0442\u043d\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0435.\n\n### \u041e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u044f\n\n\u0412\u0441\u0435\u0433\u043e *__12 \u043f\u043e\u043f\u044b\u0442\u043e\u043a__* (\u043f\u043e 6 \u0432 \u0441\u0443\u0442\u043a\u0438).\n\n\u0412 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u0435 \u0432\u044b \u043c\u043e\u0436\u0435\u0442\u0435 \u043d\u0430\u0437\u043d\u0430\u0447\u0438\u0442\u044c *__2 \u043c\u043e\u0434\u0435\u043b\u0438__* \u0434\u043b\u044f \u043f\u0440\u0438\u0432\u0430\u0442\u043d\u043e\u0433\u043e \u0442\u0435\u0441\u0442\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f. \u0415\u0441\u043b\u0438 \u0432\u044b \u043d\u0438\u0447\u0435\u0433\u043e \u043d\u0435 \u043d\u0430\u0437\u043d\u0430\u0447\u0438\u0442\u0435, \u0441\u0438\u0441\u0442\u0435\u043c\u0430 \u0432\u044b\u0431\u0435\u0440\u0435\u0442 \u0434\u0432\u0435 \u0441 \u043b\u0443\u0447\u0448\u0438\u043c `score` \u043d\u0430 \u043f\u0443\u0431\u043b\u0438\u0447\u043d\u043e\u0439 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0435.\n\n## \u0427\u0442\u043e \u043d\u0443\u0436\u043d\u043e \u0441\u0434\u0430\u0432\u0430\u0442\u044c, \u043a\u0440\u043e\u043c\u0435 \u043c\u043e\u0434\u0435\u043b\u0438\n\n1. __\u041a\u0440\u0430\u0442\u043a\u0430\u044f \u0430\u043d\u043d\u043e\u0442\u0430\u0446\u0438\u044f__ \u0441 \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u0435\u043c \u043e\u0441\u043d\u043e\u0432\u043d\u043e\u0439 \u0438\u0434\u0435\u0438 \u0440\u0435\u0448\u0435\u043d\u0438\u044f \u2013 \u043d\u0430 \u043f\u043b\u0430\u0442\u0444\u043e\u0440\u043c\u0435 \u0445\u0430\u043a\u0430\u0442\u043e\u043d\u0430.\n\n2. \u0421\u0441\u044b\u043b\u043a\u0430 \u043d\u0430 \u043b\u044e\u0431\u043e\u0439 __\u043e\u0442\u043a\u0440\u044b\u0442\u044b\u0439 \u0440\u0435\u043f\u043e\u0437\u0438\u0442\u043e\u0440\u0438\u0439 \u0441 \u043c\u043e\u0434\u0435\u043b\u044c\u044e, \u043a\u043e\u0434\u043e\u043c, \u0441 \u043f\u043e\u043c\u043e\u0449\u044c\u044e \u043a\u043e\u0442\u043e\u0440\u043e\u0433\u043e \u0441\u0442\u0440\u043e\u0438\u043b\u0430\u0441\u044c \u043c\u043e\u0434\u0435\u043b\u044c, \u0438 \u043a\u043e\u0434\u043e\u043c, \u0437\u0430\u043f\u0443\u0441\u043a\u0430\u044e\u0449\u0438\u043c \u0435\u0435__.\n\n## \u041a\u0440\u0438\u0442\u0435\u0440\u0438\u0438 \u043e\u0446\u0435\u043d\u043a\u0438\n\n**70 \u0431\u0430\u043b\u043b\u043e\u0432**\u00a0\u0440\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u044f\u0435\u0442\u0441\u044f \u0432 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0438 \u0441\u00a0 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u043e\u043c, \u043a\u043e\u0442\u043e\u0440\u044b\u0439 ML-\u043c\u043e\u0434\u0435\u043b\u044c \u043f\u043e\u043a\u0430\u0437\u0430\u043b\u0430 \u043d\u0430 kaggle-\u0441\u043e\u0440\u0435\u0432\u043d\u043e\u0432\u0430\u043d\u0438\u0438. \u0423\u0447\u0438\u0442\u044b\u0432\u0430\u0435\u0442\u0441\u044f \u043d\u0435 \u043c\u0435\u0441\u0442\u043e \u0432 \u0442\u0443\u0440\u043d\u0438\u0440\u043d\u043e\u0439 \u0442\u0430\u0431\u043b\u0438\u0446\u0435 \u043d\u0430\u043f\u0440\u044f\u043c\u0443\u044e, \u0430 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u043e\u0448\u0438\u0431\u043a\u0438 \u043d\u0430 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0435 \u043e\u0442\u043d\u043e\u0441\u0438\u0442\u0435\u043b\u044c\u043d\u043e \u0432\u0435\u043b\u0438\u0447\u0438\u043d\u044b \u043e\u0448\u0438\u0431\u043e\u043a \u0434\u0440\u0443\u0433\u0438\u0445 \u0443\u0447\u0430\u0441\u0442\u043d\u0438\u043a\u043e\u0432.\u00a0\u041f\u043e \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u0430\u043c kaggle-\u0441\u043e\u0440\u0435\u0432\u043d\u043e\u0432\u0430\u043d\u0438\u044f \u043d\u0430 \u043e\u0447\u043d\u0443\u044e \u0437\u0430\u0449\u0438\u0442\u0443 \u043f\u0435\u0440\u0435\u0434 \u0436\u044e\u0440\u0438 \u0434\u043e\u043f\u0443\u0441\u043a\u0430\u0435\u0442\u0441\u044f \u043d\u0435 \u0431\u043e\u043b\u0435\u0435 10 \u043a\u043e\u043c\u0430\u043d\u0434.\n\n**30 \u0431\u0430\u043b\u043b\u043e\u0432**\u00a0\u0440\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u044f\u0435\u0442\u0441\u044f \u043f\u043e \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u0430\u043c \u043e\u0446\u0435\u043d\u043a\u0438 \u043a\u043e\u0434\u0430, \u0432\u044b\u043b\u043e\u0436\u0435\u043d\u043d\u043e\u0433\u043e \u0432 \u043e\u0442\u043a\u0440\u044b\u0442\u044b\u0439 \u0440\u0435\u043f\u043e\u0437\u0438\u0442\u043e\u0440\u0438\u0439, \u0430 \u0442\u0430\u043a\u0436\u0435 \u0432\u044b\u0441\u0442\u0443\u043f\u043b\u0435\u043d\u0438\u044f \u043d\u0430 \u043e\u0447\u043d\u043e\u0439 \u0437\u0430\u0449\u0438\u0442\u0435 \u0432 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0438 \u0441\u043e \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u043c\u0438 \u043a\u0440\u0438\u0442\u0435\u0440\u0438\u044f\u043c\u0438 :\n\n- \u041e\u0431\u043e\u0441\u043d\u043e\u0432\u0430\u043d\u043d\u043e\u0441\u0442\u044c \u0432\u044b\u0431\u0440\u0430\u043d\u043d\u044b\u0445 \u043c\u0435\u0442\u043e\u0434\u043e\u0432 \u0434\u043b\u044f \u043f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u044f \u043c\u043e\u0434\u0435\u043b\u0438 (**15 \u0431\u0430\u043b\u043b\u043e\u0432**);\n- \u041e\u0440\u0438\u0433\u0438\u043d\u0430\u043b\u044c\u043d\u043e\u0441\u0442\u044c \u043f\u043e\u0434\u0445\u043e\u0434\u0430, \u0432 \u0447\u0430\u0441\u0442\u043d\u043e\u0441\u0442\u0438, \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0435 \u0434\u043e\u043f\u043e\u043b\u043d\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 \u0438\u0437 \u043e\u0442\u043a\u0440\u044b\u0442\u044b\u0445 \u0438\u0441\u0442\u043e\u0447\u043d\u0438\u043a\u043e\u0432 \u0434\u043b\u044f \u043f\u043e\u0432\u044b\u0448\u0435\u043d\u0438\u044f \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u0430 \u043c\u043e\u0434\u0435\u043b\u0438 (**5 \u0431\u0430\u043b\u043b\u043e\u0432**);\n- \u041a\u0430\u0447\u0435\u0441\u0442\u0432\u043e \u043a\u043e\u0434\u0430: \u0435\u0433\u043e \u0447\u0438\u0441\u0442\u043e\u0442\u0430 \u0438 \u043f\u043e\u043d\u044f\u0442\u043d\u043e\u0441\u0442\u044c (**5 \u0431\u0430\u043b\u043b\u043e\u0432**);\n- \u041a\u0430\u0447\u0435\u0441\u0442\u0432\u043e \u043e\u0447\u043d\u043e\u0439 \u0437\u0430\u0449\u0438\u0442\u044b: \u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u044c \u0438 \u043f\u043e\u043d\u044f\u0442\u043d\u043e\u0441\u0442\u044c \u0438\u0437\u043b\u043e\u0436\u0435\u043d\u0438\u044f (**5 \u0431\u0430\u043b\u043b\u043e\u0432**).\n\n\n```python\n\n```\n", "meta": {"hexsha": "7dae24124ec21c0a674cae956dc08dff6b45ddd2", "size": 52318, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/tutorial.ipynb", "max_stars_repo_name": "astromid/pandemicdatahack-track3", "max_stars_repo_head_hexsha": "0812dad4ed08c4bb952d80d0610b2fa92d27901a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-12-20T10:16:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T04:39:25.000Z", "max_issues_repo_path": "notebooks/tutorial.ipynb", "max_issues_repo_name": "astromid/pandemicdatahack-track3", "max_issues_repo_head_hexsha": "0812dad4ed08c4bb952d80d0610b2fa92d27901a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/tutorial.ipynb", "max_forks_repo_name": "astromid/pandemicdatahack-track3", "max_forks_repo_head_hexsha": "0812dad4ed08c4bb952d80d0610b2fa92d27901a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-12-20T10:16:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-20T15:18:01.000Z", "avg_line_length": 58.2605790646, "max_line_length": 14380, "alphanum_fraction": 0.6873351428, "converted": true, "num_tokens": 4925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.060975186410757824, "lm_q1q2_score": 0.026228314764114993}}
{"text": "# ModelFlow, A library to manage and solve Models\n\n##  Why Model flow?\n**Specify very large (or small) models** as concise and intuitive equations. The python code to calculate/solve the model is automatic generated. The user don't have to do the household chores and can concentrate on the economic content. \n\n**Large models**. 1 million equation and more can be handled. Models with many banks or other agents and granular data can get very large. \n\n**Agile model development** Model are specified at a high level of abstraction and are processed fast. Also solving/calculating models are fast. This makes experiments with model specification agile and fast. \n\n**Get rid of models models implemented in Excel**. Large models in Excel are difficult to maintain, revise and quality check. Excel is also very slow in calculating models. Moreover Excel don't handle models with contemporaneous feedback well. \n\n**Onboarding models and combining from different sources**. Creating a Macro prudential model often entails recycling several models specified in different ways: Excel, Latex, Dynare, Python or other languages. Python's ecosystem makes it possible to transform many different models into ModelFlow models or to wrap them into functions which can be called from ModelFlow models. \n\n**Onboarding data from different sources**. Pythons Pandas Library and other tools are fast and efficient for data management.\n\n**A rich set of analytical tools for model and result analytic** helps to understand the model and its results. \n\n**The user can extend and modify the tools** to her or his needs. All code is in Python and the core is quite small.       \n\n\n## Use ModelFlow on your local machine\n\nThe easy way to install ModelFlow libraries are located in a Github repo which you can download. It is located here:\n\n[https://github.com/IbHansen/ModelFlow2](https://github.com/IbHansen/ModelFlow2) \n\n\nYou need Python 3.8+ with associated libraries. The easy way to get Python is to install Anaconda Python from here:\n\n[https://www.anaconda.com/distribution](https://www.anaconda.com/distribution)\n\n\n\n## Run this notebook on a virtual machine. \n\n \n\nTo get access to the jupyter notebooks in the repo, run this: \n\nhttps://mybinder.org/v2/gh/Ibhansen/ModelFlow2/master\n\nThis will open a Home tab in your browser. The notebooks are the .ipynb files. \n\nThe virtual machine is created using [Binder](https://mybinder.readthedocs.io/en/latest) .\n\nUsing the toolbar you can toggle the Table of content, and you can activate the RISE. RISE will allow you to view the notebook as a slideshow. \n\nTo benefit fully of the notebook look into how Jupyter works:\n\nhttps://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Notebook%20Basics.html \n\n##  Introduction \nThe main purpose of ModelFlow is to bring a model and a data set together. Then the model can be solved, and the results analyzed and\ncompared. The user can do this either with the Python methods that ModelFlow will wrap around the model, or by by using the many datascience tools provided by the Python ecosystem. \n\n**Models can be specified in a high level Business logic language (a Domain Specific language)**. This allows the formulation of a model in a concise and expressive language which is close to the economic of the model. The user can concentrate on the economic or financial content - not the coding of the solution. The code for solving the model is generated by the tool. \n\n - a model can be *simultaneous* or *non-simultaneous*\n - a model can be specified as a normalized model - $y = F(y,x)$,or a general form model - $0=G(y,x)$  \n - simultaneous models can be solved by:\n     - Gauss-Seidle or Newton-Raphson algorithmes if no leads - ie the formulas are recurrence \n     - Fair-Taylor or stacked Newton-Raphson if the model contains leads \n     - The jacobian matrice used by Newton-Raphson solvers will can be calculated either by symbolic differentiation or by numerical differentiation \n - non-simultaneous models will be sequenced and calculated. \n - variables in a model can be scalars or matrices.\n\nIf the\nmodel is not initially specified in the Business logic language, Python\noffers a wide range of possibilities to grab a model and transform it to\nthe Business logic language. Also, models in the form of Matlab\nfunctions can be wrapped and called from ModelFlow. This allows for the recycling and integration models sourced from a number of different origins. \n\nThus a model **flows** through a number of phases, from a formulation in business logic language to a Python program which can solve the model. \n\n**ModelFlow is written in Python**. Python comes \"batteries included\" and is\nthe basis of a very rich ecosystem, which consists of a wide array of\nlibraries. ModelFlow is just another library. It supplements the existing\nlibraries regarding modeling language and solving and allows the use of\nPython as a model management framework.\n\n**Data handling and wrangling is done in the Pandas library**. This\nlibrary is the Swiss army knife of data science in Python. It can import and export data to most systems and it is very powerful in manipulating and transforming data.\nThe core\nelement of Pandas is the *Dataframe*. A Dataframe is a two-dimensional\ntabular data structure. Each *column* consists of cells of the same type\n-- it can be a number, a string, a matrix or another Python data object.This includes matrices and other dataframes. Each *row is indexed.* The index can basically be any type of variable\nincluding dates, which is especially relevant for economic and financial models.\n\n**ModelFlow gives the user tools for more than solving models**. This\nincludes:\n\n-   *Visualization* and comparison of results\n\n-   *Integration* of models from different sources\n\n-   *Analyze the logical structure of a model*. By applying graph theory, \n    ModelFlow can find data lineage, find a suitable calculating sequence and trace \n    causes of changes through the calculations.\n\n-   *Inverting* the model to calculating the necessary instruments to\n    achieve a desired target.\n\n-   Calculating the *attributions* from input to the results of a model.\n\n-   Calculating the *attribution* from input to the result of each\n    formula.\n\n-   Finding and calculating partial *derivatives* of formulas\n\n-   *Integrating user defined python functions* in the Business logic\n    language (like optimization, calculating risk weights or to make a matrices consistent with the RAS algorithm  )\n\n-   *Wrap matlab* models so they can be used in the Business logic\n    language.\n\n-   *Speed up* solving using \"Just in time compilation\"\n\n-   Analyze the model structure through tools from graph theory\n\n-   Handle *large models.* 1,000,000 formulas is not a problem.\n\n-   Integrate model management in Jupyter notebooks for *agile and user\n    friendly model use*\n\n\n**The core code of ModelFlow is small and\ndocumented.** Thus it can easily be modified and expanded to the specific need of the user. *ModelFlow is a toolset*. It can handle models, which conform to the tools.\n\nIf you need a feature or have a model which can't be handled in ModelFlow,\nyou are encouraged to improve ModelFlow. Please share the\nimprovement, other users may have the same need, or can be inspired by\nyour work.\n\nAlso bear in mind that ModelFlow is experimental. It is provided \u201das is\u201d, without any representation or warranty of any kind either express or implied.   \n\nThe code is located here: [https://github.com/IbHansen/ModelFlow2](https://github.com/IbHansen/ModelFlow2)\n\nThe rest of this document will start with a simple example, then it will go into more detail regarding how to use (some of) the features. \n\n## Import relevant libraries\nHere the nessecary libraries are imported. Imports starting with *model* are \npart of the ModelFlow library \n\n\n```python\n%matplotlib inline\n```\n\n\n```python\nimport matplotlib.pyplot as plt \nimport pandas as pd               # Python data science library\nimport numpy as np\nimport re\nimport sys\n\nimport modelclass as mc           # ModelFlow, model handeling module \nfrom modelclass import model\nimport modelmanipulation as mp    # Module for model text processing\nimport modelpattern as pt\nfrom modelmanipulation import explode\nimport modeldekom as md\nimport modelvis as mv\nimport modelinvert as mi\nimport modelnet as mn \nimport modeldiff as mdif\n```\n\n## Create model equations / formulas \nThe model equations are a Python string. In a simple model the calculations are specified just as formulas. Time is implicit and lags are marked by (-). \n\nEach formula starts with a \"FRML\" and ends with a $. Also each formula has formula options enclosed in <>. In this simple model we don't use any advanced features.\n\nYou will notice, that the formulas do not have to be ordered in the logical calculation sequence. This will be done by ModelFlow. \n\n\n```python\nfmodel      = '''\nfrml <> a = c(-1) + b $ \nfrml <> d1 = x + 3 * a(-1)+ c **2 +a  $ \nfrml <> d3 = x + 3 * a(-1)+c **3 $  \nFrml <> x = 0.5 * c $'''\n```\n\n## Create a model instance\n**Now we want to take the formulas (equations) and create a devise which can run the model.** This device is an instance of the **model class**. \n\nAfter the creation the instance can solve the model, visualize results and \nprovide information regarding the model \n\n\n\n```python\nmmodel = model(fmodel,modelname = 'My first model')\n```\n\n## Create a Dataframe\n**The model needs some data to run**. So we create a pandas dataframe. \n\nA dataframe is a matrix, where the columns designate variables in the model, and rows are time dimensions. \n\n\n```python\ndf = pd.DataFrame({'B': [1,1,1,1],'C':[1,2,3,6],'E':[4,4,4,4]},index=[2018,2019,2020,2021])\ndf  \n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>B</th>\n      <th>C</th>\n      <th>E</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2018</th>\n      <td>1</td>\n      <td>1</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>2019</th>\n      <td>1</td>\n      <td>2</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>2020</th>\n      <td>1</td>\n      <td>3</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>2021</th>\n      <td>1</td>\n      <td>6</td>\n      <td>4</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Run the model \n**We can now run the model using the data.** The result is a new dataframe. \n\nIf the dataframe don't contain all the variables from the model, the dataframe will be padded with the missing \nvariables. Their values are set to 0.0. \n\nThe model can be solved for the rows in the dataframe for which it is possible. This means that the maximal lags has to be taken into account. In this example the maximal lag is 1, so the model can be solved from 2019 to 2021.  \n\n\n```python\nmmodel(df)  \n```\n\n    Will start calculating: My first model\n    2019  solved\n    2020  solved\n    2021  solved\n    My first model calculated \n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>B</th>\n      <th>C</th>\n      <th>E</th>\n      <th>A</th>\n      <th>D3</th>\n      <th>D1</th>\n      <th>X</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2018</th>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>4.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>2019</th>\n      <td>1.0</td>\n      <td>2.0</td>\n      <td>4.0</td>\n      <td>2.0</td>\n      <td>9.0</td>\n      <td>7.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>2020</th>\n      <td>1.0</td>\n      <td>3.0</td>\n      <td>4.0</td>\n      <td>3.0</td>\n      <td>34.5</td>\n      <td>19.5</td>\n      <td>1.5</td>\n    </tr>\n    <tr>\n      <th>2021</th>\n      <td>1.0</td>\n      <td>6.0</td>\n      <td>4.0</td>\n      <td>4.0</td>\n      <td>228.0</td>\n      <td>52.0</td>\n      <td>3.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n##  Make a new experiment\nOne experiment is useful, but usually we want to compare the results of several experiments.\n\nSo the C variable is updated to new values, and the model is run again. \n\n\n```python\ndf.C = [4,5,7,9]\ndf.B = [1,2,3,4]\nmmodel(df)\n```\n\n    Will start calculating: My first model\n    2019  solved\n    2020  solved\n    2021  solved\n    My first model calculated \n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>B</th>\n      <th>C</th>\n      <th>E</th>\n      <th>A</th>\n      <th>D3</th>\n      <th>D1</th>\n      <th>X</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2018</th>\n      <td>1.0</td>\n      <td>4.0</td>\n      <td>4.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>2019</th>\n      <td>2.0</td>\n      <td>5.0</td>\n      <td>4.0</td>\n      <td>6.0</td>\n      <td>127.5</td>\n      <td>33.5</td>\n      <td>2.5</td>\n    </tr>\n    <tr>\n      <th>2020</th>\n      <td>3.0</td>\n      <td>7.0</td>\n      <td>4.0</td>\n      <td>8.0</td>\n      <td>364.5</td>\n      <td>78.5</td>\n      <td>3.5</td>\n    </tr>\n    <tr>\n      <th>2021</th>\n      <td>4.0</td>\n      <td>9.0</td>\n      <td>4.0</td>\n      <td>11.0</td>\n      <td>757.5</td>\n      <td>120.5</td>\n      <td>4.5</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Visualizing\nA model run returns a dataframe with the results. These can be analyzed and visualized by python libraries like pandas and matplotlib. \n\nHowever, the results are also saved as propertied in the model instance. By using the information regarding both the model and the results a number of tools for visualizing, analyzing and debugging can applied. \n\nPer default the first result dataframe  and the last result dataframe are retained in the model instance. The first is called:**basedf** the last is called:**lastdf**. \n\nBy setting or accessing **model.basedf** and **model.lastdf**, these properties can also be set or retrieved by the user.\n\n### Single variable\n\nAll model variable can be accessed with model_instance.variable_name notation. The resulting object will return information regarding the variable. \n    \nThe python feature \"Tab-completion\" can be used to select which variable to show. So when the user  \npres the tab-key, a list of matching variable names will be displayed, and the user can those\nfrom the list.     \n\nFor a single variable there are a number of methods for gaining insight in both the dependencies and the results. If we just give the variable as attribute like in the cell below. We will get a some basic information regarding the variable.  \n\n\n```python\nmmodel.D1\n```\n\n\n\n\n    Endogeneous: D1:  \n    Formular: FRML <> D1 = X + 3 * A(-1)+ C **2 +A  $\n    \n    D1: \n    A : \n    C : \n    X : \n    \n    Values : \n          2019  2020   2021\n    Base   7.0  19.5   52.0\n    Last  33.5  78.5  120.5\n    Diff  26.5  59.0   68.5\n    \n    Input last run: \n            2019  2020  2021\n    A       6.0   8.0  11.0\n    A(-1)   0.0   6.0   8.0\n    C       5.0   7.0   9.0\n    X       2.5   3.5   4.5\n\n\n\nSome methods are available to use after the variable name: One such is **draw**, the next cell shows the parent and child's of the X variable, and also the values of each of the variables. Both in the baseline run (default: the first run of the model) and in the last run of the model. \n\nSo in this model X depends on C, and X is contributing to D1 and D3. \n\nOutput from **draw** can become quite large for complex and deep models. Therefor the user can control both the amount of information for the variables and how many generations the graph has to cover. \n\n\n```python\nmmodel.draw('X',all=1,size=(2,2))\n```\n\n\n    \n\n    \n\n\n### We can also explain the change in the variable\nHaving two runs of the model, it is useful to find the attribution to the change in values from the first to the second run. This is done by the explain method. \n\nThe width of arrows reflects how much of the change in a variable can be explained by the change in each incoming variable.  \n\n\n```python\n_=mmodel.D1.explain(up=2)\n```\n\n\n    \n\n    \n\n\nThis can become a very busy graph for large models where  there are really many nodes. \nLike shocks for all countries in an EBA stress test. So take care what you ask for. \n\nThe output can also be produced in PDF or svg format. These formats are vector based, and it is possible to zoom into a large graph without loosing information. \n\n###  Slices of variables\nIn order to make life easy when using models with consistent and structured variable naming conventions wildcards can be used to select the variables to visualize through ModelFlow. \nSome are displayed below. \n\nIf this is not sufficient the whole suite of Python visualization libraries (as Matplotlib, Seaborn, Plotly) can be used on top of the resulting Dataframes. \n\n#### The values\n\n\n```python\n_=mmodel['*'].plot(title='Values')\n```\n\n#### The values\n\n\n```python\n_=mmodel['*'].dif.plot(title='The differences')\n```\n\n#### The differences between the runs, as heatmap\n\n\n```python\n_=mmodel['*'].dif.heat(size=(4,4),title='The differences')\n```\n\n### Structure\nAs the structure of the model is in the model instance, we can visualize the structure of the whole model.  \n\n\n```python\nmmodel.drawmodel(size=(2,2))\n```\n\n\n    \n\n    \n\n\n### The model structure with values \nAlso we can combine the structure and the model in order to get the complete picture. \n\nHowever take care for large models. \n\n\n```python\nmmodel.drawmodel(all=1,size=(2,2))\n```\n\n\n    \n\n    \n\n\nThis was a quick walk through how to define a simple model, make some mock data, run the model and visualize the structure and the results. \n\nNow we can explore the features of ModelFlow. \n\n## What is a Model in ModelFlow\nModelFlow is created to handle models. The term [**model**](https://en.wikipedia.org/wiki/Model) can mean a lot of different concepts. \n\nThe scope of models handled by ModelFlow is discrete models which is the same for each time frame, can be formulated as mathematical equations and *can* have lagged and leaded variables. This allows the system to handle quite a large range of models.\n\nA model with:\n\n - $\\textbf n$ number of endogeneous variables\n - $\\textbf k$ number of exogeneous variables \n - $\\textbf u$ max lead of endogeneous variables\n - $\\textbf r$ max lag of endogeneous variables \n - $\\textbf s$ max lag of exogeneous variables \n - $t$ time frame (year, quarter, day second or another another unit)\n \ncan be written in two ways, normalized or un-normalized form\n\n### normalized form\n\n\\begin{eqnarray}\ny_t^1 & = & f^1(y_{t+u}^1...,y_{t+u}^n...,y_t^2...,y_{t}^n...y_{t-r}^1...,y_{t-r}^n,x_t^1...x_{t}^k,...x_{t-s}^1...,x_{t-s}^k) \\\\\ny_t^2 & = & f^2(y_{t+u}^1...,y_{t+u}^n...,y_t^1...,y_{t}^n...y_{t-r}^1...,y_{t-r}^n,x_t^1...x_{t}^k,...x_{t-s}^1...,x_{t-s}^k) \\\\\n\\vdots \\\\\ny_t^n & = & f^n(y_{t+u}^1...,y_{t+u}^n...,y_t^1...,y_{t}^{n-1}...y_{t-r}^1...,y_{t-r}^n,x_t^1...x_{t}^r,x..._{t-s}^1...,x_{t-s}^k)\n\\end{eqnarray}\n\n\nMany stress test, liquidity, macro or other models conforms to this pattern. Or the can easily be transformed to thes pattern. \n\nWritten in matrix notation where  $\\textbf{y}_t$ and $\\textbf{x}_t$ are vectors of endogenous/exogenous  variables for time t\n\n\\begin{eqnarray}  \n\\textbf{y}_t & = & \\textbf{F}(\\textbf{y}_{t+u} \\cdots \\textbf{y}_t \\cdots \\textbf{y}_{t-r},\\textbf{x}_t \\cdots \\textbf{x}_{t-s})\n\\end{eqnarray}\n\nThe functions are normalized, meaning: \n\n- Each endogenous variable is on the left hand side one time - and only one time.\n- An endogenous variable without lags can **not** be on the right hand side in an equation, which has the variable on the left hand side. \n\n### Un-normalized form\nSome economic models can not easy be specified as normalized formulas. Especially   models with equilibrium  conditions can more suitable be specified in the more generalized un-normalized form.\n\n\n\\begin{eqnarray}\n0 & = & f^1(y_{t+u}^1...,y_{t+u}^n...,y_t^1...,y_{t}^n...y_{t-r}^1...,y_{t-r}^n,x_t^1...x_{t}^k,...x_{t-s}^1...,x_{t-s}^k) \\\\\n0 & = & f^2(y_{t+u}^1...,y_{t+u}^n...,y_t^1...,y_{t}^n...y_{t-r}^1...,y_{t-r}^n,x_t^1...x_{t}^k,...x_{t-s}^1...,x_{t-s}^k) \\\\\n\\vdots \\\\\n0 & = & f^n(y_{t+u}^1...,y_{t+u}^n...,y_t^1...,y_{t}^n...y_{t-r}^1...,y_{t-r}^n,x_t^1...x_{t}^r,x..._{t-s}^1...,x_{t-s}^k)\n\\end{eqnarray}\n\n\n\nWritten in matrix notation like before:\n\n\\begin{eqnarray}  \n\\textbf{0}& = & \\textbf{F}(\\textbf{y}_{t+u} \\cdots \\textbf{y}_t \\cdots \\textbf{y}_{t-r},\\textbf{x}_t \\cdots \\textbf{x}_{t-s})\n\\end{eqnarray}\n\nThe number of endogenous variables and equations should still be the same.\n\nModelFlow allows variable (the $\\textbf x$'es and the $\\textbf y$'es the to be scalars, matrices, arrays or pandas dataframes.\n\n## Model solution \nFor a normalized model:\n\n\\begin{eqnarray}  \n\\textbf{y}_t & = & \\textbf{F}(\\textbf{y}_{t+u} \\cdots \\textbf{y}_t \\cdots \\textbf{y}_{t-r},\\textbf{x}_t \\cdots \\textbf{x}_{t-r})     \n\\end{eqnarray}\n\na solution is  $\\textbf{y}_t^*$ so that:\n\n\n\\begin{eqnarray}  \n\\textbf{y}_t^* & = & \\textbf{F}(\\textbf{y}_{t+u} \\cdots \\textbf{y}_t^* \\cdots \\textbf{y}_{t-r},\\textbf{x}_t \\cdots \\textbf{x}_{t-r})     \n\\end{eqnarray}\n\nFor the un-normalized model:\n\\begin{eqnarray}  \n\\textbf{0}& = & \\textbf{F}(\\textbf{y}_{t+u} \\cdots \\textbf{y}_t \\cdots \\textbf{y}_{t-r},\\textbf{x}_t \\cdots \\textbf{x}_{t-s})\n\\end{eqnarray}\n\n\na solution $\\textbf{y}_t^*$ is \n\n\\begin{eqnarray}  \n\\textbf{0} & = & \\textbf{G}(\\textbf{y}_{t+u} \\cdots \\textbf{y}_t^* \\cdots \\textbf{y}_{t-r},\\textbf{x}_t \\cdots \\textbf{x}_{t-r})     \n\\end{eqnarray}\n\nSome models can have more than one solution. In this case the solution can depend on the starting point of the solution algorithm. \n\n## Model derivatives \n\nBoth for solving and for analyzing the causal structure of a model it can be useful to define different matrices of derivatives for a model $\\textbf F()$ like this:\n\n\\begin{align}  \n\\textbf{A}_t & = & \\frac{\\partial \\textbf{F}}{\\partial \\textbf{y}_t^T}  \\hphantom{\\hspace{5 mm} i=1, \\cdots , r}   \n &\\hspace{1 mm}\\mbox{Derivatives with respect to current endogeneous variables} \\\\ \\\\\n\\textbf{E}_t^i & = & \\frac{\\partial \\textbf{F}}{\\partial \\textbf{y}_{t-i}^T } \\hspace{5 mm} i=1, \\cdots , r  &\\hspace{1 mm}\\mbox{  Derivatives with respect to lagged endogeneous variables  } \\\\  \\\\\n\\textbf{D}_t^j & = & \\frac{\\partial \\textbf{F}}{\\partial \\textbf{y}_{t+j}^T } \\hspace{5 mm} j=1, \\cdots , u  &\\hspace{1 mm}\\mbox{  Derivatives with respect to leaded endogeneous variables  } \\\\  \\\\\n\\textbf{F}_t^k & = & \\frac{\\partial \\textbf{F}}{\\partial \\textbf{x}_{t-i} ^T} \\hspace{5 mm} k=0, \\cdots , s  &\\hspace{1 mm}\\mbox{  Derivatives with respect to current and lagged exogeneous variables  }\\\\ \n\\end{align}\n\nFor un-normalized models the derivative matrices are just the dervatives of $\\textbf G$ instead of $\\textbf F$\n\nSolving the model with a Newton-Raphson method  requires the calculation of a matric of derivatives. This is done by creating an additional model which calculates all the non-zero derivatives. The derivative calculation model can be created both by symbolic differentiation or by numerical differentiation.   \n\n## Model solutions\n\nThere are numerous methods to solve models (systems) as mentioned above. ModelFlow can apply 3 different types of model solution methods: \n\n 1. If the model has **no contemporaneous feedback**, the equations can be sorted \n [Topological](https://en.wikipedia.org/wiki/Topological_sorting) and then the equations can be calculated in the topological order. This is the same as a spreadsheet would do.  \n 2. If the model has **contemporaneous feedback** model is solved with an iterative method. Here variants of well known solution methods are used: \n     1. [Gauss-Seidle](https://en.wikipedia.org/wiki/Gauss%E2%80%93Seidel_method) (**Gauss**) which can handle large systems, is fairly robust and don't need the calculation of derivatives\n     2. [Newthon-Raphson](https://en.wikipedia.org/wiki/Newton%27s_method) (**Newton**) which requires the calculation of derivatives and solving of a large linear system but typically converges in fewer iterations. \n \nNearly all of the models solved by ModelFlow don't contain leaded endogenous variables. Therefor they can be solved one period at a time. For large sparse nonlinear models Gauss works fine. It solves a model quite fast and we don't need the additional handiwork of handling derivatives and large linear systems that Newton methods require. Moreover many models in question do not have smooth derivatives. The order in which the equation are calculated can have a large impact on the convergence speed. \n\nFor some models the Newton algorithm works better. Some models are not able to converge with Gauss-Seidle other models are just faster using Newton. Also the ordering of equations does not matter for the convergence speed. \n\nHowever some models like FRB/US and other with **rational expectations** or **model consistent expectations** contains leaded endogenous variables. Such models typical has to be solved as one system for for all projection periods. In this case, the Gauss variation [Fair-Taylor](https://fairmodel.econ.yale.edu/rayfair/pdf/1983A.PDF) or Stacked-Newton Method.  The **stacked Newton** methods can be used in all cases, but if not needed, it will usually use more memory and be slower. \n\n\n**Summary of prefered solution methods**\n\n| Model  | No contemporaneous feedback | Contemporaneous feedback | Leaded variables |\n| --- | --- | --- |--- | \n|Normalized | Calculate | Gauss or <br> Newton  | Fair Taylor or <br> Stacked Newton|\n|Un-normalized | Newton | Newton | Stacked Newton |\n\n\n \n\n### Normalized model\n\n\n#### Calculation, No contemporaneous feedback\n\nIn systems with no lags each period can be solved in succession\nThe equations has to be evaluated in a logical (topological sorted) order. \n\nLet $z$ be all predetermined values: all exogenous variable and lagged endogenous variable.\n\nOrder the $n$ endogeneous variables in topological order.\n    \nFor each time period we can find a solution by\n\nfor $i$ = 1 to $n$ \n\n>$y_{i}^{k} = f_i(y_1^{k},\\cdots,y_{i-1}^{k},y_{i+1}^{k-1},\\cdots,y_{n}^{k-1},z)$\n\n\n#### The Gauss-Seidel algorithm. Models with contemporaneous feedback\nThe Gauss-Seidel algorithm is quite straight forward. It basically iterate over the formulas, until convergence. \n\nLet $z$ be all predetermined values: all exogenous variable and lagged endogenous variable.\nLet $n$ be the number of endogenous variables.\n   \nFor each time period we can find a solution by doing Gauss-Seidel iterations: \n\nfor $k = 1$ to convergence\n\n>for $i$ = 1 to $n$ \n>\n>>$y_{i}^{k} = (1-\\alpha) * y_{i}^{{k-1}} + \\alpha f_i(y_1^{k},\\cdots,y_{i-1}^{k},y_{i+1}^{k-1},\\cdots,y_{n}^{k-1},z)$\n\n#### Convergence \nConvergence has been reached when the solution don't change to much between each iteration. \nThere is no need to check all variable for convergence. So the user can define a \nset $\\{$convergence variable$\\}$ Then all relative changes from one iteration to has to be smaller than a convergence criteria $\\epsilon_{relative}$. It does not make sense to calculate relative changes in values close to 0, so the test is only performed on values larger than a small number $\\epsilon_{absolute}$ \n\n$\\forall y_{j}$ where $y_{j} \\in \\{$convergence variable$\\}\\land \\mid y_{j}^{k-1}\\mid \\geq \\epsilon_{absolute}$ we calculate  $\\mid \\frac{y_{j}^{k}-y_{j}^{k-1}}{y_{j}^{k-1}}\\mid \\leq \\epsilon_{relative}$\n\n\nUnder some circumstances the the iterations will diverge, even if there is a solution. This can (mostly) be handled by introducing the dampening factor $\\alpha$ in the algorithm. $\\alpha$ is usually only needed for a few variables - if any. To select an equation for dampening the formula option damp has to be used. \n\n#### The Newton-Raphson algorithme. Models with contemporaneous feedback\n\nLet $\\bf z$ be a vector all predetermined values: all exogenous variable and lagged endogenous variable.\n\nFor each time period we can find a solution by doing Newton-Raphson iterations: \n\nfor $k = 1$ to convergence\n\n>$\\bf y = \\bf {F(y^{k-1},z) }$\n>\n>$\\bf y^{k} =  \\bf y - \\bf{(A-I)}^{-1} \\times ( \\bf {y - y^{k-1} })$\n\n\n\nThe expression: $\\bf{(A-I)}^{-1}\\times  ( \\bf {y - y^{k-1} })$ is the same as the solution to: \n\n$\\bf {y- y^{k-1} } = \\bf (A-I) \\times \\bf x$\n\nThis problem can be solved much more efficient than performing $\\bf{(A-I)}^{-1}\\times  ( \\bf {y - y^{k-1} })$\n\nThe Scipy library provides a number of solvers to this linear set of equations. There are both solvers using  factorization and iterative methods, and there are solvers for dense and sparce matrices. Theese linear solvers  can easily be incorporated into ModelFlows Newton-Raphson nonlinear solver.\n\n#### Stacked Newton-Raphson all  periods in one go. Models with both leaded and lagged endogeneous variable\n\nIf the model has leaded endogenous variables it can in general not be solved one time period at a time. We have to solve the model for all time frames as one large model. \n\nFor the Newton-Raphson algorithme we now have to stack all the derivative matrices. For a model with a max lag of 3 which has to be solved for 8 time periods the stacked matrices looks like this. \n\n$$\\bf{\\bar A} =\\begin{bmatrix} \n\t\t\\bf{A_1}   & \\bf{D_1^1} & \\bf{D_1^2} & \\bf{0}     &\\bf{0}      &\\bf{0}      &\\bf{0}      &\\bf{0}  \\\\\n        \\bf{E_2^1} & \\bf{A_2}   & \\bf{D_2^1} & \\bf{D_2^2} &\\bf{0}      &\\bf{0}      &\\bf{0}      &\\bf{0} \\\\       \n        \\bf{E_3^2} & \\bf{E_3^1} & \\bf{A_3}   & \\bf{D_3^1} & \\bf{D_3^2} &\\bf{0}      &\\bf{0}      &\\bf{0} \\\\       \n        \\bf{E_4^3} & \\bf{E_4^2} & \\bf{E_4^1} & \\bf{A_4}   & \\bf{D_4^1} & \\bf{D_4^2} &\\bf{0}      & \\bf{0} \\\\       \n        \\bf{0}     & \\bf{E_5^3} & \\bf{E_5^2} & \\bf{E_5^1} & \\bf{A_5}   & \\bf{D_5^1} & \\bf{D_5^2} &\\bf{0}\\\\       \n        \\bf{0}     & \\bf{0}     & \\bf{E_6^3} & \\bf{E_6^2} & \\bf{E_6^1} & \\bf{A_6}   & \\bf{D_6^1} & \\bf{D_6^2}\\\\       \n        \\bf{0}     & \\bf{0}     & \\bf{0}     & \\bf{E_7^3} & \\bf{E_7^2} & \\bf{E_7^1} & \\bf{A_7}   & \\bf{D_7^1} \\\\       \n        \\bf{0}     & \\bf{0}     & \\bf{0}     & \\bf{0}     & \\bf{E_8^3} & \\bf{E_8^2} & \\bf{E_8^1} & \\bf{A_8} \\\\       \n\\end{bmatrix} \\bar y = \\begin{bmatrix}\\bf{y_1}\\\\\\bf{y_2}\\\\\\bf{y_3}\\\\ \\bf{y_4} \\\\\\bf{y_5} \\\\\\bf{y_6} \\\\ \\bf{y_7} \\\\ \\bf{y_8} \\end{bmatrix} \\bar F = \\begin{bmatrix}\\bf{F}\\\\\\bf{F}\\\\\\bf{F}\\\\ \\bf{F} \\\\\\bf{F} \\\\\\bf{F} \\\\ \\bf{F} \\\\ \\bf{F} \\end{bmatrix}$$\n\n\nAgain let $\\bf z$ be a vector all predetermined values: all exogenous variable and lagged endogenous variable.\n\nNow the solution algorithme looks like this. \n\nfor $k = 1$ to convergence\n\n>$\\bf{\\bar y} = \\bf {\\bar F(\\bar y^{k-1},\\bar z) }$\n\n>$\\bf {\\bar y^{k}} =  \\bf{\\bar y} - \\bf{(\\bar A-I)}^{-1}\\times ( \\bf {\\bar y - \\bar y^{k-1} })$\n\nNotice that the model $\\bf F$ is the same for all time periods\n\nAgain we solve the problem: $$( \\bf {\\bar y - \\bar y^{k-1} }) = \\bf{(\\bar A-I)}\\times \\bf x $$\n\n\n##### Stacked Newton with no leaded endogenous variables. \n\nIn this case all the $\\bf{D}$ submatrices in the above algorithm disappear. \n\n#### Fair-Taylor algorithm, Models with both leaded and lagged endogeneous variable \n\nAnother way to solve the model as one system is the Fair-Taylor algorithm. It can be seen as an extension to the gauss algorithm for the whold system, with the added twist that each period is solved. \n\n\nfor $f$ = 1 to convergence\n>for $t = 1$ to end time\n>>$\\textbf{y}_t^f= solve( \\textbf{F}(\\textbf{y}_{t+u}^{f-1}  \\cdots \\textbf{y}_{t-r}^{f},\\textbf{x}_t \\cdots, \\textbf{x}_{t-r}))$\n\nWhere $solve$ in the inner loop can be either a Gauss or a Newton one period solve algorithm. ModelFlow use the Gauss solver in the inner loop. But it would be straight forward to implement a Newton inner loop.   \n\n\n### Un-normalized model \n\n### The simultaneous model,  with leaded variables\n**If F has contemporaneous feedback and leaded endogeneous variables, it has to be solved for all timeframes - again with an iterative method.** Modelflow can use the Fair-Taylor algorithme - which is a Gauss-Seidle derivative or solve the model for all periods with a (stacked) Newton-Raphson algorithme. \n\nIn general the Newton-Raphson algorithme is faster and more stable for this kind of models.\n\n### Stacked Newton-Raphson algorithm\n\nIf the model has leaded endogenous variables it can in general not be solved one time period at a time. We have to solve the model for all time frames as one large model. \n\nFor the Newton-Raphson algorithme we now have to stack all the derivative matrices. For a model with a max lag of 3 and a max lead of 2 which has to be solved for 8 time periods the stacked matrices looks like this. \n\n$$\\bf{\\bar A} =\\begin{bmatrix} \n\t\t\\bf{A_1}   & \\bf{D_1^1} & \\bf{D_1^2} & \\bf{0}     &\\bf{0}      &\\bf{0}      &\\bf{0}      &\\bf{0}  \\\\\n        \\bf{E_2^1} & \\bf{A_2}   & \\bf{D_2^1} & \\bf{D_2^2} &\\bf{0}      &\\bf{0}      &\\bf{0}      &\\bf{0} \\\\       \n        \\bf{E_3^2} & \\bf{E_3^1} & \\bf{A_3}   & \\bf{D_3^1} & \\bf{D_3^2} &\\bf{0}      &\\bf{0}      &\\bf{0} \\\\       \n        \\bf{E_4^3} & \\bf{E_4^2} & \\bf{E_4^1} & \\bf{A_4}   & \\bf{D_4^1} & \\bf{D_4^2} &\\bf{0}      & \\bf{0} \\\\       \n        \\bf{0}     & \\bf{E_5^3} & \\bf{E_5^2} & \\bf{E_5^1} & \\bf{A_5}   & \\bf{D_5^1} & \\bf{D_5^2} &\\bf{0}\\\\       \n        \\bf{0}     & \\bf{0}     & \\bf{E_6^3} & \\bf{E_6^2} & \\bf{E_6^1} & \\bf{A_6}   & \\bf{D_6^1} & \\bf{D_6^2}\\\\       \n        \\bf{0}     & \\bf{0}     & \\bf{0}     & \\bf{E_7^3} & \\bf{E_7^2} & \\bf{E_7^1} & \\bf{A_7}   & \\bf{D_7^1} \\\\       \n        \\bf{0}     & \\bf{0}     & \\bf{0}     & \\bf{0}     & \\bf{E_8^3} & \\bf{E_8^2} & \\bf{E_8^1} & \\bf{A_8} \\\\    \n\\end{bmatrix} \\bar y = \\begin{bmatrix}\\bf{y_1}\\\\\\bf{y_2}\\\\\\bf{y_3}\\\\ \\bf{y_4} \\\\\\bf{y_5} \\\\\\bf{y_6} \\\\ \\bf{y_7} \\\\ \\bf{y_8} \\end{bmatrix} \\bar F = \\begin{bmatrix}\\bf{F}\\\\\\bf{F}\\\\\\bf{F}\\\\ \\bf{F} \\\\\\bf{F} \\\\\\bf{F} \\\\ \\bf{F} \\\\ \\bf{F} \\end{bmatrix}$$\n\n\n$$\\bf \\bar z$$ contains all predetermined variable. \n\nNow the solution algorithme looks like this. \n\nfor $k = 1$ to convergence\n\n>$\\bf{\\bar y\\_residual} = \\bf {\\bar G(\\bar y^{k-1},\\bar z) }$\n>\n>$\\bf {\\bar y^{k}} =  \\bf{\\bar y} - \\bf{\\bar A}^{-1} \\times \\bf {\\bar y\\_residual}$\n\nNotice that the model $\\bf G$ is the same for all time periods\n\nAgain we don't compute $\\bf{\\bar y} - \\bf{\\bar A}^{-1} \\times \\bf {\\bar y\\_residual}$ which requires the \"expensiv\" inversion of a matrix but solve the problem: $\\bf{\\bar y\\_residual}=\\bf{\\bar A} \\times \\bf  x$ which can be done much faster.\n\n# Implementation of solving algorithms in Python\nSolving a model entails a number of steps:\n\n1. Specification of the model \n2. Create a dependency graph. \n2. Establish a solve order and separate the the model into smaller sub-models\n2. Create a python function which can evaluating $f_i(y_1^{k},\\cdots,y_{i-1}^{k},y_{i+1}^{k-1},\\cdots,y_{n}^{k-1},z)$\n3. If needed, create a python function which can evaluate the Jacobimatrices: $\\bf{A,E,D}$  or $\\bf{\\bar A,\\bar E,\\bar D}$ \n3. Apply a solve function using the elements above to the data. \n\n## Specification of model in Business Logic Language\nThe Business logic Language is a Python like language, where each function $f_i$ from above is specified as:\n\n```\nFRML <options> <left hand side> = <right hand side> $ ... \n```\n\nThe ```<left hand side>``` should not contain transformations, but can be a tuple which match the ```<right hand side>```. A  \\$ separates each formular.\n\nTime is implicit, so $var_t$ is written as ```var```, while $var_{t-1}$ is written as ```var(-1)``` and $var_{t+1}$ is written as ```var(+1)```. Case does not matter. everything is eventual made into upper case. \n\nIt is important to be able to create short and expressive models, therefor. Stress test models should be able to handle many bank and sectors without repeating text. So on top of the **Business logic language**. there is a **Macro Business Logic language**. The primary goal of this is to allow (conditional) looping and normalization of formulas.   \n\n\n# Onboarding a model \n\nWe want to present a model to the transpiler, so it can create a model instance including a python function which can solve/calculate the model. The primary method for this is to formulate the model in a Business logic Language. \n\nThe purpose of the Business logic language is to enable a clear and\nconcise specification of the models at hand.\n\nA *macro model* can flow through a *macro-processor* which returns *business logic*. This is then processed by\ntranspiler to create a python function which can solve the model.\n\nThe macro-processer performs text processing:\n\n-   Normalize formulas\n\n-   Decorate formulas\n\n-   Expand arrays\n\n-   Expand matrices\n\n-   Unlooping do-loops\n\nThe inspiration is the modeling language of venerable programs like\nTSP, Eviews, Troll and SAS/ETS combined with the rules of Python.\n\nIf you launch this notebook as Jupyter notebook, you can play around with the business logic language.\n\nThere are three types of statements:\n\n1.  Formula statement:\\\n    Defines transformation of variables in the Dataframe\n\n2.  List statement:\\\n    Defines lists and associated sub lists. Lists can be\n    used to define repetitive items and to define mappings\n\n3.  DO/END DO statements\\\n    Defines repetitive formulas in which the content of list are\n    interpolated\n\n## A Flexible language \nThe example above shows how to specify a simple model. It looks like python, except that variable names are substituted to references to pandas dataframe cells after Transpiling. \nThis is fine for some problems. \n\nHowever a **macro** expanding phase enhance  the language in order to make it more powerful, agile, and and still parsimonious. \n\nThe expanded business logic language introduce a little more. It consists of commands and comments: \n\n-  frml: Define formulas \n-  list: Define sublist to explode over \n-  do: start exploding \n-  enddo: end exploding\n\n### Variables\n\n**Variable names has to start with a letter or _ then any number of\nletters _ or digits. Time t is implicit.** \n\n**A lag** can be specified right after a variable as: ```(-<lag>)```, meaning:\n```horse(-1)``` is the variable ```horse``` lagged one period\n\nA variable can contain a number or a Python object. The Python object can be for instance be a cvxopt matric, a numpy array or even a Pandas dataframe. \n\nCase does not matter. All variables are translated to upper case. And in\nthe Dataframe all variables should be upper case.\n\nLags cannot be specified at the left hand side of =.\n\n## FRML command, defines calculations\n\n```frml <J|JR|I|EXO> left hand side = right hand side $```\n\nIf it is done for the whole model, the word frml and the <> clause and $ can be ignored. In this case commands including formulas are separated by newline.\n\n### Right hand side\n\nOperators: \n\nStandard: ```= + - * / ** ( ) @ ```\n\nComparison: ```>= <= == !=```  \\# evaluates to 0 if false, 1 if true\n\nSpecial: ```$ > < , . [  ] ``` # used in different python constructions.\n\n### Several variables on the left hand side\n\nThere can be several left hand variables. Python rules for tuple\nunpacking apply.\n\n```a, b, c = 1, 2, 3 ```\n\nor\n\n```a, b, b = some_function_which returns_3 values(x,y,z,42)```\n\nBe aware that normalization cannot be combined with this feature.\n\nThe feature is useful when packing and unpacking matrices and when\napplying optimization.\n\n### Text processing functions on the right hand side  \n\nThe functions DIFF and DLOG will be expanded on the right hand side. Their argument can be expressions involving lagged variable, therefore they can't be evaluated directly, so they are expanded in the pre-processing phase. \n\n\n```python\nexplode('a = alfa * diff(b)')\n```\n\n\n\n\n    'FRML <> A = ALFA * ((B)-(B(-1))) $'\n\n\n\n\n```python\nexplode('a = alfa * dlog(b)')\n```\n\n\n\n\n    'FRML <> A = ALFA * ((LOG(B))-(LOG(B(-1)))) $'\n\n\n\n\n```python\nexplode('a = alfa * dlog(a+b+c)')\n```\n\n\n\n\n    'FRML <> A = ALFA * ((LOG(A+B+C))-(LOG(A(-1)+B(-1)+C(-1)))) $'\n\n\n\n### Text processing functions on the left hand of a formular \n\nIn some models, it can be useful to specify a function of the endogenous variable as the target on the left-hand side. In order to do the calculation, the endogenous variable has to be isolated on the left-hand side. This is done in a pre-processing step by applying the inverse of the function to the right-hand side. Functions allowed on left-hand side: **diff, log, dlog, logit**.\n\nThese functions are only allowed when there are just one left-hand side variable.\n\n#### Only current or lagged endogeneous variables.\nIn systems with no lags each period can be solved in succestion\n\n\n```python\nexplode('diff(lhv) = 42 * (a+b+c) ')\n```\n\n\n\n\n    'FRML <> LHV=LHV(-1)+(42 * (A+B+C))$'\n\n\n\n\n```python\nexplode('log(lhv) = 42 * (a+b+c) ')\n```\n\n\n\n\n    'FRML <> LHV=EXP(42 * (A+B+C))$'\n\n\n\n\n```python\nexplode('logit(lhv) = 42 * (a+b+c) ')\n```\n\n\n\n\n    'FRML <> LHV=(EXP(42 * (A+B+C))/(1+EXP(42 * (A+B+C))))$'\n\n\n\n\n```python\nexplode('dlog(lhv) = 42 * (a+b+c) ')\n```\n\n\n\n\n    'FRML <> LHV=EXP(LOG(LHV(-1))+42 * (A+B+C))$'\n\n\n\n### Formula name, enhancing formular calculations \nThe purpose of the formula name/control is to enable relevant additions to the formulas, but avoid boilerplate noise to the formulas. \n\nThe control is placed between <> after the 'FRML'. different controls can be separated by ','\n\n#### Absolute adjustment \n\n\n```python\nmp.explode('<J> lhv = rhs ')\n```\n\n\n\n\n    'FRML <J> LHV = RHS  +LHV_J$'\n\n\n\n#### Relative adjustment \n\n\n```python\nmp.explode('<jr> lhv = rhs ')\n```\n\n\n\n\n    'FRML <JR> LHV = ( RHS  )*(1+LHV_JR )$'\n\n\n\n#### Fixing results \n\n\n```python\nmp.explode('frml <exo> lhv = rhs ')\n```\n\n\n\n\n    'FRML <EXO> LHV =( RHS )*(1-LHV_D)+LHV_X*LHV_D$'\n\n\n\nBy setting LHV_D the user controls wether LHV is set to the value of the RHS exression or the value LHV_X.\n\n#### Extract model for calculating identities in before projection period\n\n\n```python\ntmodel = '''\\\nfrml <> horse = 1.3 * cow +dgdp(-1)$ \nfrml <I> dgdp = gdp/gpd(-1) $\nfrml <i> dinv = inv/inv(-1) $ '''\nprint( mp.explode(tmodel))\n```\n\n    FRML <> HORSE = 1.3 * COW +DGDP(-1)$\n    FRML <I> DGDP = GDP/GPD(-1) $\n    FRML <I> DINV = INV/INV(-1) $\n\n\n\n```python\nmp.find_hist_model(tmodel)\n```\n\n\n\n\n    'frml <I> dgdp = gdp/gpd(-1) $\\nfrml <i> dinv = inv/inv(-1) $'\n\n\n\n#### Make dampening a formular possible\n\nZ : When solving a model with the Gauss-Seidel algorithm the evaluation\nof this formula can be damped.\n\n\n### Incorporating user defined functions into formulas\n\nThe user can incorporate her own routines in the BL language. \nThis is giving the user defined functions as the funks argument to the model creation. \n\nThe tokenizer  will recognize the name of the function and place call to the function in the solving routine.  \n\n\n```python\ndef f1(x):\n    return 42\n\nf2model = '''\\\na      = c * 42 \nf      = c(-1) >=2 \nanswer = f1(a)'''\n\nm2model = mc.model(f2model,funks=[f1])\n\n```\n\n## LIST command, define list and sublists    \n\nLists are used to direct how the do command explodes a template model. \nAnd to define sum functions, and for matrix packing and unpacking. \n\n``` \nList <listname> = <sublistname0> : <sl00> <sl01> .. <sl0n> / \n                     <sublistname1> : <sl10> <sl11> .. <sl1n> /\n                     .............................]\n                     $\n```\n**There should always be the same number of elements in sublists**\n\nExample with one sublist: \n\n```\nLIST BANKLIST = BANK : ATBAW DEHAS DEHSH LUPCK DELBY DEVWF ESSAB  $\n```\n\nExample with two sublist: \n\n```\nLIST CRCOLIST  =  CRCOUNTRY   : UK DE CH NL BE CA JP KY LU HK  / \n                  CRMODELGEO  : UK DE CH NL BE CA JP R20 LU HK $\n``` \n\nIf a list name is created several times, the first time is the used. This makes it more easy to make prototypes for a few banks.\n\n\n## DO ...  ENDDO, loop over lists   \n\n```\ndo <listname> $\nstuff \nenddo $\n```\n\nWill take take the stuff and make a copy for each element of the sublists in list name. \n\n\n```python\nmtest = ''' \nlist banklist = bank : ib soren $\ndo banklist $\n     profit_{bank} = revenue_{bank} - expenses_{bank} $\nenddo $ \n'''\n\nprint(explode(mtest))\n```\n\n    LIST BANKLIST = BANK : IB SOREN $\n    PROFIT_IB = REVENUE_IB - EXPENSES_IB $\n    PROFIT_SOREN = REVENUE_SOREN - EXPENSES_SOREN $\n\n\n### Use of sublist to inject additional information \n\n\n```python\nmtest = ''' \nlist banklist = bank    : ib      soren  marie /\n                country : denmark sweden denmark  $\n                \ndo banklist $\n    frml <> profit_{bank} = revenue_{bank} - expenses_{bank} $\n    frml <> expenses_{bank} = factor_{country} * revenue_{bank} $\nenddo $ \n'''\n\nprint(mp.explode(mtest))\n```\n\n    LIST BANKLIST = BANK    : IB      SOREN  MARIE /\n                    COUNTRY : DENMARK SWEDEN DENMARK  $\n    FRML <> PROFIT_IB = REVENUE_IB - EXPENSES_IB $\n    FRML <> EXPENSES_IB = FACTOR_DENMARK * REVENUE_IB $\n    FRML <> PROFIT_SOREN = REVENUE_SOREN - EXPENSES_SOREN $\n    FRML <> EXPENSES_SOREN = FACTOR_SWEDEN * REVENUE_SOREN $\n    FRML <> PROFIT_MARIE = REVENUE_MARIE - EXPENSES_MARIE $\n    FRML <> EXPENSES_MARIE = FACTOR_DENMARK * REVENUE_MARIE $\n\n\n### Nested do\n\nDo loops can be nested.\n\nOne just have to take care that there is no duplication of sublist names. \n\n\n```python\nmtest = ''' \nlist banklist = bank    : ib      soren  marie /\n                country : denmark sweden denmark  $\n                \nlist assetlist = asset  : nfc sme hh             $\n                \n                \ndo banklist $\n  ! bank = {bank}\n    profit_{bank} = revenue_{bank} - expenses_{bank}-loss_{bank} $\n    expenses_{bank} = factor_{country} * revenue_{bank} $\n    do assetlist $\n      loss_{asset}_{bank} = 0.02 * stock_{asset}_{bank} $\n    enddo $\n    ! find the sum \n    loss_{bank} = sum(assetlist,loss_{asset}_{bank})    $\n\nenddo $ \n'''\n\nprint(explode(mtest))\n```\n\n    LIST BANKLIST = BANK    : IB      SOREN  MARIE /\n                    COUNTRY : DENMARK SWEDEN DENMARK  $\n    LIST ASSETLIST = ASSET  : NFC SME HH             $\n    BANK = IB\n        PROFIT_IB = REVENUE_IB - EXPENSES_IB-LOSS_IB $\n    EXPENSES_IB = FACTOR_DENMARK * REVENUE_IB $\n    LOSS_NFC_IB = 0.02 * STOCK_NFC_IB $\n    LOSS_SME_IB = 0.02 * STOCK_SME_IB $\n    LOSS_HH_IB = 0.02 * STOCK_HH_IB $\n    FIND THE SUM \n        LOSS_IB = (LOSS_NFC_IB+LOSS_SME_IB+LOSS_HH_IB)    $\n    BANK = SOREN\n        PROFIT_SOREN = REVENUE_SOREN - EXPENSES_SOREN-LOSS_SOREN $\n    EXPENSES_SOREN = FACTOR_SWEDEN * REVENUE_SOREN $\n    LOSS_NFC_SOREN = 0.02 * STOCK_NFC_SOREN $\n    LOSS_SME_SOREN = 0.02 * STOCK_SME_SOREN $\n    LOSS_HH_SOREN = 0.02 * STOCK_HH_SOREN $\n    FIND THE SUM \n        LOSS_SOREN = (LOSS_NFC_SOREN+LOSS_SME_SOREN+LOSS_HH_SOREN)    $\n    BANK = MARIE\n        PROFIT_MARIE = REVENUE_MARIE - EXPENSES_MARIE-LOSS_MARIE $\n    EXPENSES_MARIE = FACTOR_DENMARK * REVENUE_MARIE $\n    LOSS_NFC_MARIE = 0.02 * STOCK_NFC_MARIE $\n    LOSS_SME_MARIE = 0.02 * STOCK_SME_MARIE $\n    LOSS_HH_MARIE = 0.02 * STOCK_HH_MARIE $\n    FIND THE SUM \n        LOSS_MARIE = (LOSS_NFC_MARIE+LOSS_SME_MARIE+LOSS_HH_MARIE)    $\n\n\n### Use of sublist to do conditional Loop\n\nBy using \n\n`DO listname sublist = value $`\n\nthe looping will only be performed on the members of list where the value of the corresponding sublist match the value in the do statement.\n\nThis can be useful for instance when treating portfolios differently depending on some information. An example could be the different treatment of portfolios depending on regulatory approach. \n\n\n```python\nmtest='''\nlist portdic = port  : households ,  NFC ,   RE,  sov  /\n               reg   :       AIRB , AIRB ,  STA,  STA $\n    do portdic reg = airb $ \n    frml x {port}_REA_W = calc_rw({port}_pd ,{port}_lgd) $\n    enddo $ \n    do portdic reg = sta $ \n    frml x {port}_REA_W = {port}_REA_W(-1) $\n    enddo $ \n '''\nprint(explode(mtest))\n```\n\n    LIST PORTDIC = PORT  : HOUSEHOLDS ,  NFC ,   RE,  SOV  /\n                   REG   :       AIRB , AIRB ,  STA,  STA $\n    FRML X HOUSEHOLDS_REA_W = CALC_RW(HOUSEHOLDS_PD ,HOUSEHOLDS_LGD) $\n    FRML X NFC_REA_W = CALC_RW(NFC_PD ,NFC_LGD) $\n    FRML X RE_REA_W = RE_REA_W(-1) $\n    FRML X SOV_REA_W = SOV_REA_W(-1) $\n\n\n### Dynamic defined lists to utilize sparsity\nOften not all the potential dimensions in a model contains data. For instance all banks don't have positions in all potential countries. \n\nIn order to speed up calculations and to avoid bloating dataframes, we want to avoid calculating and carrying a lot of zeros around. \n\nThis can be achieved by using dynamic naming of lists. For instance create a separate list of countries for each bank. \n\nThe list for each country can be created by using the pandas library to identify in which countries \nthere are non-zero positions - straight forward but beyond the scope of this notebook. \n\nBelow is an example where there are two banks which each has exposures in different countries. \n\n\n```python\n    stest='''\n    list BANKDIC = bank : Danske , Nordea $                                 \n    list country_danske_dic = country : uk , DK, IR $\n    list country_nordea_dic = country: SE , DK $\n    do bankdic $ \n        frml x {bank}_income = {bank}_a +{bank}_b $\n        do country_{bank}_dic $\n            frml x value_{bank}_{country} = 42 $\n        enddo $ \n        frml <> total_{bank} = sum(country_{bank}_dic,value_{bank}_{country})  $\n      enddo $ '''\n    \n    print(explode(stest))\n```\n\n    LIST BANKDIC = BANK : DANSKE , NORDEA $\n    LIST COUNTRY_DANSKE_DIC = COUNTRY : UK , DK, IR $\n    LIST COUNTRY_NORDEA_DIC = COUNTRY: SE , DK $\n    FRML X DANSKE_INCOME = DANSKE_A +DANSKE_B $\n    FRML X VALUE_DANSKE_UK = 42 $\n    FRML X VALUE_DANSKE_DK = 42 $\n    FRML X VALUE_DANSKE_IR = 42 $\n    FRML <> TOTAL_DANSKE = (VALUE_DANSKE_UK+VALUE_DANSKE_DK+VALUE_DANSKE_IR)  $\n    FRML X NORDEA_INCOME = NORDEA_A +NORDEA_B $\n    FRML X VALUE_NORDEA_SE = 42 $\n    FRML X VALUE_NORDEA_DK = 42 $\n    FRML <> TOTAL_NORDEA = (VALUE_NORDEA_SE+VALUE_NORDEA_DK)  $\n\n\n## Pack values into matrices (a cvxopt class)\n\n\n```python\nmtest2 = ''' \nlist banklist  = bank : ib soren $\nlist banklist2 = bank2 : ib soren $\n! vector \nfrml <matrix> vbank = to_matrix(banklist,profit_{bank})  $\n! matrices \nfrml <matrix> Mbank = to_matrix(banklist,banklist2,loanfrom_{bank}_to_{bank2})  $\n'''\n\nprint(mp.explode(mtest2))\n```\n\n    LIST BANKLIST  = BANK : IB SOREN $\n    LIST BANKLIST2 = BANK2 : IB SOREN $\n    VECTOR FRML <MATRIX> VBANK = MATRIX(\n    [PROFIT_IB,PROFIT_SOREN])  $\n    MATRICES FRML <MATRIX> MBANK = MATRIX(\n    [[LOANFROM_IB_TO_IB,LOANFROM_IB_TO_SOREN],\n    [LOANFROM_SOREN_TO_IB,LOANFROM_SOREN_TO_SOREN]])  $\n\n\n## Pack values into arrays (a numpy class)\n\n\n```python\nmtest2 = ''' \nlist banklist  = bank : ib soren $\nlist banklist2 = bank2 : ib soren $\n! vector \nfrml <matrix> vbank = to_array(banklist,profit_{bank})  $\n! matrices \nfrml <matrix> Mbank = to_array(banklist,banklist2,loanfrom_{bank}_to_{bank2})  $\n'''\n\nprint(mp.explode(mtest2))\n```\n\n    LIST BANKLIST  = BANK : IB SOREN $\n    LIST BANKLIST2 = BANK2 : IB SOREN $\n    VECTOR FRML <MATRIX> VBANK = ARRAY(\n    [PROFIT_IB,PROFIT_SOREN])  $\n    MATRICES FRML <MATRIX> MBANK = ARRAY(\n    [[LOANFROM_IB_TO_IB,LOANFROM_IB_TO_SOREN],\n    [LOANFROM_SOREN_TO_IB,LOANFROM_SOREN_TO_SOREN]])  $\n\n\n## Unpack values - Argexpand \n\n\n```python\nmtest2 = ''' \nlist banklist  = bank : ib soren $\nlist banklist2 = bank2 : ib soren $\n! vector \nfrml <> argexpand(banklist,test_{bank}) = to_matrix(banklist,profit_{bank})  $\n! matrices \nfrml <> argexpand(banklist,argexpand(banklist2,loanfrom_{bank2}_{bank})) = 0  $\n'''\n\nprint(mp.explode(mtest2))\n```\n\n    LIST BANKLIST  = BANK : IB SOREN $\n    LIST BANKLIST2 = BANK2 : IB SOREN $\n    VECTOR FRML <> TEST_IB,TEST_SOREN = MATRIX(\n    [PROFIT_IB,PROFIT_SOREN])  $\n    MATRICES FRML <> LOANFROM_IB_IB,LOANFROM_SOREN_IB,LOANFROM_IB_SOREN,LOANFROM_SOREN_SOREN = 0  $\n\n\n\n```python\nmtest2 = ''' \nlist listdevs  = devs : dev_yer dev_uts $\nlist listshocks = shocks : ib soren $\n    frml <matrix> ARGEXPAND(listdevs,{devs}) = STE(to_matrix(LISTSHOCKS,{SHOCKS}(-3)),\\\n    to_matrix(LISTSHOCKS,{SHOCKS}(-2 )), \\\n    to_matrix(LISTSHOCKS,{SHOCKS}(-1)),\n    to_matrix(LISTSHOCKS,{SHOCKS})  ) $\n    '''.upper() \n\nprint(mp.explode(mtest2))\n```\n\n    LIST LISTDEVS  = DEVS : DEV_YER DEV_UTS $\n    LIST LISTSHOCKS = SHOCKS : IB SOREN $\n    FRML <MATRIX> DEV_YER,DEV_UTS = STE(MATRIX(\n    [IB(-3),SOREN(-3)]),    MATRIX(\n    [IB(-2 ),SOREN(-2 )]),     MATRIX(\n    [IB(-1),SOREN(-1)]),\n        MATRIX(\n    [IB,SOREN])  ) $\n\n\n\n\n## Create an array of lagged or leaded variables - lag_array\nlag_array(<number>,<expression>) will create an numpy array with length = |number|, positive number \n    will give an array of leaded values, negative numbers an array of lagged values \n\n\n```python\nmtest3 = '''\npd_pit_array_leaded   = lag_array(3,pd_pit) $ \n'''\nprint(mp.explode(mtest3))\n```\n\n    PD_PIT_ARRAY_LEADED = ARRAY([PD_PIT(+1),PD_PIT(+2),PD_PIT(+3)]) $\n\n\n\n```python\nmtest3 = '''\npd_pit_array_lagged   = lag_array(-3,pd_pit) $ \n'''\nprint(mp.explode(mtest3))\n```\n\n    PD_PIT_ARRAY_LAGGED = ARRAY([PD_PIT(-1),PD_PIT(-2),PD_PIT(-3)]) $\n\n\n## Sum, sum over list \nsum(LIST,expression) = sums expression over the elements of a list substitution the sublist names.  \n\n\n```python\nmtest = ''' \nlist banklist = bank    : ib      soren  marie /\n                country : denmark sweden denmark  $\n                \nlist assetlist = asset  : nfc sme hh             $\n                \n                \ndo banklist $\n  !\n  ! bank = {bank}\n    do assetlist $\n      loss_{asset}_{bank} = 0.02 * stock_{asset}_{bank} $\n    enddo $\n    ! find the sum \n    loss_{bank} = sum(assetlist,loss_{asset}_{bank})   $\n\nenddo $ \n \nloss_total =  sum(banklist,sum(assetlist,loss_{asset}_{bank}))$\n'''\n\nprint(explode(mtest))\n```\n\n    LIST BANKLIST = BANK    : IB      SOREN  MARIE /\n                    COUNTRY : DENMARK SWEDEN DENMARK  $\n    LIST ASSETLIST = ASSET  : NFC SME HH             $\n    BANK = IB\n        DO ASSETLIST $\n    LOSS_{ASSET}_IB = 0.02 * STOCK_{ASSET}_IB $\n    BANK = SOREN\n        DO ASSETLIST $\n    LOSS_{ASSET}_SOREN = 0.02 * STOCK_{ASSET}_SOREN $\n    BANK = MARIE\n        DO ASSETLIST $\n    LOSS_{ASSET}_MARIE = 0.02 * STOCK_{ASSET}_MARIE $\n    FIND THE SUM \n        LOSS_{BANK} = (LOSS_NFC_{BANK}+LOSS_SME_{BANK}+LOSS_HH_{BANK})   $\n    LOSS_TOTAL =  ((LOSS_NFC_IB+LOSS_SME_IB+LOSS_HH_IB)+(LOSS_NFC_SOREN+LOSS_SME_SOREN+LOSS_HH_SOREN)+(LOSS_NFC_MARIE+LOSS_SME_MARIE+LOSS_HH_MARIE))$\n\n\n## Onboarding models from other sources \n\n**Python has incredible strong tools both for interacting with other systems like Excel and Matlab, and for text processing.** This allows for *recycling* of models from different sources and make them live together (hopefully happy). Some of the sources, from which models has been recycled are: \n\n- Latex, \n    - Code from Dynare \n    - Model written in Latex - with some rules to allow text processing. \n- Excel \n    - Calculation model from Excel workbook  \n    - Grabbing coefficients from excel workbooks \n- Matlab \n    - Wrapping matlab models into python functions, which can be used in ModelFlow  \n    - Grabbing coefficients from matlab .mat files. \n- Aremos models \n- TSP models \n\nGrabbing models and transforming them to Business logic language usually requires a tailor-made Python program. However in the ModelFlow folder there are different examples of such grabbing. \n\n# From model equations to solution\n\nThe core of ModelFlow is a transpiler. The purpose of the transpiler\nis two fold.\n\n - To convert  a **Business Logic Language** model to a python function. This function can then evaluates the model, and thus be called from the solving routine. Both Gauss-Seidle and Newton-Raphson solvers need as input a function to which can evaluate  the model.   \n \n - To analyze the model. Find the dependencies **graph** of the formulas. The depencency graph can be used for analyzing the causal structure of a model. This is used to speed up solving and to enable model and model result analytic.  \n\nPython come batteries included, so a number of powerful tools are available. Therefore, it is not necessary to design a full-fledged compiler/interpreter in order to solve a model. Some of the tough jobs are outsourced to the Python ecosystem. \n\n\n```python\n\n```\n\n## A syntax checker. \n***Formulas must be legal Python expressions.***\n    This allows us to outsource syntax checking of formulas to the Python ecosystem. The ***ast*** Python standard library can check the syntax,  and it is easy to make a function which catch syntax errors in the formulas.\n\n\n```python\nmp.check_syntax_frml('frml <> a = b $')\n```\n\n\n\n\n    True\n\n\n\n\n```python\nmp.check_syntax_frml('frml <> a = b + = c$')\n```\n\n\n\n\n    False\n\n\n\n## A tokenizer. \nThe model is chopped into tokens. This\n    is done by using the regular expressing (***re***) Python standard library. \n    The tokenizer delivers an expression ad a list of tokens in the form of named tuple's (terms). Each token can be either of four types:\n\n-  A variable perhaps with lag or lead\n-  A number\n-  An operator, function.\n\n\n\n```python\n\n```\n\n\n```python\npt.udtryk_parse('a=b(-1)+3')\n```\n\n\n\n\n    [nterm(number='', op='', var='A', lag=''),\n     nterm(number='', op='=', var='', lag=''),\n     nterm(number='', op='', var='B', lag='-1'),\n     nterm(number='', op='+', var='', lag=''),\n     nterm(number='3', op='', var='', lag='')]\n\n\n\n\n```python\npt.model_parse('''\\\nfrml <> a=b+2$\nfrml <> v=x+y(-1))$\n''')\n```\n\n\n\n\n    [(fatoms(whole='FRML <> A=B+2$', frml='FRML', frmlname='<>', expression='A=B+2$'),\n      [nterm(number='', op='', var='A', lag=''),\n       nterm(number='', op='=', var='', lag=''),\n       nterm(number='', op='', var='B', lag=''),\n       nterm(number='', op='+', var='', lag=''),\n       nterm(number='2', op='', var='', lag=''),\n       nterm(number='', op='$', var='', lag='')]),\n     (fatoms(whole='FRML <> V=X+Y(-1))$', frml='FRML', frmlname='<>', expression='V=X+Y(-1))$'),\n      [nterm(number='', op='', var='V', lag=''),\n       nterm(number='', op='=', var='', lag=''),\n       nterm(number='', op='', var='X', lag=''),\n       nterm(number='', op='+', var='', lag=''),\n       nterm(number='', op='', var='Y', lag='-1'),\n       nterm(number='', op=')', var='', lag=''),\n       nterm(number='', op='$', var='', lag='')])]\n\n\n\nThe pattern defining operators and functions is defined\n\n### Define pattern for variable names and lags \n\n\n```python\nnamepat_ng  = r'(?:[A-Za-z_{][A-Za-z_{}0-9]*)'     # a name non grouped\nnamepat     = r'(' + namepat_ng + ')' # a name  grouped\nlagpat      = r'(?:\\(([+-][0-9]+)\\))?'\nnamepat+lagpat\n```\n\n\n\n\n    '((?:[A-Za-z_{][A-Za-z_{}0-9]*))(?:\\\\(([+-][0-9]+)\\\\))?'\n\n\n\n### Define pattern for numbers\n\n\n```python\nnumpat      = r'((?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]\\d+)?)'\nnumpat\n```\n\n\n\n\n    '((?:\\\\d+(?:\\\\.\\\\d*)?|\\\\.\\\\d+)(?:[eE][+-]\\\\d+)?)'\n\n\n\n### Define pattern for operators \nThis includes both ordinary python operators and functions. It is important that \n\n\n#### Include names for functions defines in module \n\nUsing introspection functions from a module can be included in the language. The Module **modelBLfunk** contains useful functions.  \n\n\n```python\nimport inspect \nimport modelBLfunk # a module from which all functions are included BLL \nBLfunk = [o.upper() for o,t in inspect.getmembers(modelBLfunk)\n             if not o.startswith('__')  ]\nBLfunk\n```\n\n\n\n\n    ['ARRAY',\n     'CLASSFUNK',\n     'CLOGNORM',\n     'EXP',\n     'GAMMA',\n     'INSPECT',\n     'JIT',\n     'LIFETIME_CREDIT_LOSS',\n     'LOG',\n     'LOGIT',\n     'LOGIT_INVERSE',\n     'LOGNORM',\n     'MATRIX',\n     'MV_OPT',\n     'MV_OPT_PROP',\n     'NORM',\n     'NORMCDF',\n     'QGAMMA',\n     'SQRT',\n     'SUM_EXCEL',\n     'TRANSPOSE']\n\n\n\n#### Include names for user specified functions \nIn order to make the language agile. The user can specify functions when creating a model instance. Functions specifies at model creation will be included in the language, and in the model instance. This is done by including the function in a list: funks. \n\nFirst define the a couple of functions to illustrate, how they can be included: \n\n\n```python\ndef the_answer():\n    '''The answer to the ultimate question of life, the universe and everything'''\n    return 42.0\n\ndef the_ultimate_forward_rate():\n    '''Calculate the ultimate forward rate cf. Solvency 2 regulation of insurance'''\n    return the_answer/10.0\nfunks = [the_answer, the_ultimate_forward_rate] \n```\n\nNow find the names of the from the list of user defined functions. \n\n\n```python\nnewfunks = [f.__name__.upper() for f in funks]\nnewfunks\n```\n\n\n\n\n    ['THE_ANSWER', 'THE_ULTIMATE_FORWARD_RATE']\n\n\n\n#### A list of patterns to match each function\n\n\n```python\nfunkname    = 'LOG EXP'.split() + BLfunk + newfunks\nfunkname2   = [i+r'(?=\\()' for i in funkname]               # a function is followed by a (\nfunkname2\n```\n\n\n\n\n    ['LOG(?=\\\\()',\n     'EXP(?=\\\\()',\n     'ARRAY(?=\\\\()',\n     'CLASSFUNK(?=\\\\()',\n     'CLOGNORM(?=\\\\()',\n     'EXP(?=\\\\()',\n     'GAMMA(?=\\\\()',\n     'INSPECT(?=\\\\()',\n     'JIT(?=\\\\()',\n     'LIFETIME_CREDIT_LOSS(?=\\\\()',\n     'LOG(?=\\\\()',\n     'LOGIT(?=\\\\()',\n     'LOGIT_INVERSE(?=\\\\()',\n     'LOGNORM(?=\\\\()',\n     'MATRIX(?=\\\\()',\n     'MV_OPT(?=\\\\()',\n     'MV_OPT_PROP(?=\\\\()',\n     'NORM(?=\\\\()',\n     'NORMCDF(?=\\\\()',\n     'QGAMMA(?=\\\\()',\n     'SQRT(?=\\\\()',\n     'SUM_EXCEL(?=\\\\()',\n     'TRANSPOSE(?=\\\\()',\n     'THE_ANSWER(?=\\\\()',\n     'THE_ULTIMATE_FORWARD_RATE(?=\\\\()']\n\n\n\n#### And finally the pattern for functions are combined with the pattern for standard operators in Python. \n\n\n```python\nopname      = r'\\*\\*  != >=  <=  ==  [=+-/*@|()$><,.\\]\\[]'.split() # list of ordinary operators \noppat       = '('+'|'.join(['(?:' + i + ')' for i in funkname2+opname])+')'\noppat\n```\n\n\n\n\n    '((?:LOG(?=\\\\())|(?:EXP(?=\\\\())|(?:ARRAY(?=\\\\())|(?:CLASSFUNK(?=\\\\())|(?:CLOGNORM(?=\\\\())|(?:EXP(?=\\\\())|(?:GAMMA(?=\\\\())|(?:INSPECT(?=\\\\())|(?:JIT(?=\\\\())|(?:LIFETIME_CREDIT_LOSS(?=\\\\())|(?:LOG(?=\\\\())|(?:LOGIT(?=\\\\())|(?:LOGIT_INVERSE(?=\\\\())|(?:LOGNORM(?=\\\\())|(?:MATRIX(?=\\\\())|(?:MV_OPT(?=\\\\())|(?:MV_OPT_PROP(?=\\\\())|(?:NORM(?=\\\\())|(?:NORMCDF(?=\\\\())|(?:QGAMMA(?=\\\\())|(?:SQRT(?=\\\\())|(?:SUM_EXCEL(?=\\\\())|(?:TRANSPOSE(?=\\\\())|(?:THE_ANSWER(?=\\\\())|(?:THE_ULTIMATE_FORWARD_RATE(?=\\\\())|(?:\\\\*\\\\*)|(?:!=)|(?:>=)|(?:<=)|(?:==)|(?:[=+-/*@|()$><,.\\\\]\\\\[]))'\n\n\n\n### Now the expression pattern is created\n\n\n```python\nudtrykpat    =   numpat + '|' + oppat + '|' + namepat + lagpat\nudtrykpat\n```\n\n\n\n\n    '((?:\\\\d+(?:\\\\.\\\\d*)?|\\\\.\\\\d+)(?:[eE][+-]\\\\d+)?)|((?:LOG(?=\\\\())|(?:EXP(?=\\\\())|(?:ARRAY(?=\\\\())|(?:CLASSFUNK(?=\\\\())|(?:CLOGNORM(?=\\\\())|(?:EXP(?=\\\\())|(?:GAMMA(?=\\\\())|(?:INSPECT(?=\\\\())|(?:JIT(?=\\\\())|(?:LIFETIME_CREDIT_LOSS(?=\\\\())|(?:LOG(?=\\\\())|(?:LOGIT(?=\\\\())|(?:LOGIT_INVERSE(?=\\\\())|(?:LOGNORM(?=\\\\())|(?:MATRIX(?=\\\\())|(?:MV_OPT(?=\\\\())|(?:MV_OPT_PROP(?=\\\\())|(?:NORM(?=\\\\())|(?:NORMCDF(?=\\\\())|(?:QGAMMA(?=\\\\())|(?:SQRT(?=\\\\())|(?:SUM_EXCEL(?=\\\\())|(?:TRANSPOSE(?=\\\\())|(?:THE_ANSWER(?=\\\\())|(?:THE_ULTIMATE_FORWARD_RATE(?=\\\\())|(?:\\\\*\\\\*)|(?:!=)|(?:>=)|(?:<=)|(?:==)|(?:[=+-/*@|()$><,.\\\\]\\\\[]))|((?:[A-Za-z_{][A-Za-z_{}0-9]*))(?:\\\\(([+-][0-9]+)\\\\))?'\n\n\n\n\n```python\nre.findall(udtrykpat,'a=b+c(-1)')\n```\n\n\n\n\n    [('', '', 'a', ''),\n     ('', '=', '', ''),\n     ('', '', 'b', ''),\n     ('', '+', '', ''),\n     ('', '', 'c', '-1')]\n\n\n\n\n```python\n\n```\n\nA number of functions are predefined in the modelpattern module.\n\n\n```python\npt.udtryk_parse('a=b(-1)+the_answer()',funks=[the_answer,the_ultimate_forward_rate])\n```\n\n\n\n\n    [nterm(number='', op='', var='A', lag=''),\n     nterm(number='', op='=', var='', lag=''),\n     nterm(number='', op='', var='B', lag='-1'),\n     nterm(number='', op='+', var='', lag=''),\n     nterm(number='', op='THE_ANSWER', var='', lag=''),\n     nterm(number='', op='(', var='', lag=''),\n     nterm(number='', op=')', var='', lag='')]\n\n\n\nAnd a model which consists of several formulas is parsed to a structure like this \n\n\n```python\npt.model_parse('''frml <> a = b+2 $ frml <> v = log(x) $''')\n```\n\n\n\n\n    [(fatoms(whole='FRML <> A = B+2 $', frml='FRML', frmlname='<>', expression='A = B+2 $'),\n      [nterm(number='', op='', var='A', lag=''),\n       nterm(number='', op='=', var='', lag=''),\n       nterm(number='', op='', var='B', lag=''),\n       nterm(number='', op='+', var='', lag=''),\n       nterm(number='2', op='', var='', lag=''),\n       nterm(number='', op='$', var='', lag='')]),\n     (fatoms(whole='FRML <> V = LOG(X) $', frml='FRML', frmlname='<>', expression='V = LOG(X) $'),\n      [nterm(number='', op='', var='V', lag=''),\n       nterm(number='', op='=', var='', lag=''),\n       nterm(number='', op='LOG', var='', lag=''),\n       nterm(number='', op='(', var='', lag=''),\n       nterm(number='', op='', var='X', lag=''),\n       nterm(number='', op=')', var='', lag=''),\n       nterm(number='', op='$', var='', lag='')])]\n\n\n\nThe model_parse function takes a model and returns a list of  tuples, Each tuple contains:\n\na named (fatoms) tuple of: \n-  the complete formula\n-  FRML\n-  Formula name\n-  The expression\n-  a list of \n-  A list of terms from the expression\n\nCare has been taken to optimize the speed of the tokenizing function. By tokenizing the whole model in one python list comprehension, even quite large models  (number of formulas > 600,000) can be tokenized in a few seconds.   \n\n\n## An analyzer\nThis function extract information needed to handle the model such as.\n\n-  Endogenous and exogenous variables\n-  Starting positions in calculating vector. \n-  The dependency graphs TG and TE.\n\nThese objects are stored as property in the class instance. Some of the properties like TG and TG can be time consuming to calculate. In these cases \nlazy evaluation is used. This means that computing of the properties is delayed until \nthe property is requested (perhaps implicit) by the user. \n\n## Code generation\nThis phase converts the tokenized model to python code, which can solve the model.\n\nThe purpose is to substitute variable names in the the model formulas to an access to a DataFrame.\n\nIt is\n    quite straight forward to write a function, which generates solving\n    routines in other languages than Python.\n    \nThe code generation phase produces a factory function, which will return the actual calculating function. This methods is chosen in order to manage the namespace in which the calculation function is operating. \n\nIn order to catch calculation errors, the code performing the calculation is braced by a error catching clause. Thus if numerical error such as taking the log of a negative number raises an error, we can identify the offending formula. \n\nFor our little model the factory function looks like this:\n\n## The model structure\n\nThe logival structure of a model is useful for several reasons. The structure of contemperaneous endogenous variable is used to stablish the calculation sequence and identify simultaneous systems. The structure of a model can be seen as a directed graph. All variables are node in the graph. \nIf a variable $b$ is on the right side of the formula defining variable $a$ there is an edge from $a$ to $b$. \n\n### First we define the nodes (vertices) of the dependency graph.\n\nThe set of nodes is the set of relevant variables. Actually we want to look \nat **two dependency graphs**: one containing *all variables*, \nand one only containing *endogenous contemporaneous variable* (the $y^j_t$'s). So we define two sets S and E:\n\n**All endogenous, exogenous, contemporaneous and lagged variables**\n\n$S=\\{y^j_{t-i}|j=1..n,i=1..r   \\} \\cup \\{x^j_{t-i}|j=1..k,i=1..s   \\}$ \n\n**Contemporaneous endogenous variables**\n\n$E=\\{y^j_{t}|j=1..n    \\}$ contemporaneous endogenous variables \n\nNaturally:\n\n$E \\subseteq S$\n\n### Then we define the edges of the dependency graph.  \nAgain two sets are relevant: \n\n**From all variables to contemporaneous endogenous variables**\n\n$T = \\{(a,b) | a \\in E, b \\in S\\}$ a is on the right side of b \n\n**From contemporaneous endogenous variables to contemporaneous endogenous variables** \n\n$T_e = \\{(a,b) | a \\in E, b \\in E\\}$ a is on the right side of b \n\n### And we can construct useful dependency graphs\nThe we can define a graph TG which defines the data dependency of the model:\n\n$TG = (S,T)$ The graph defined by nodes S and edges T.\n\nTG can be used when exploring the dependencies in the model. This is useful for the user when drilling down the results. \n\nHowever for preparing the solution a smaller graph has to be used. When solving the model for a specific period both exogenous and lagged endogenous variables are predetermined. Therefor we define the the dependency graph for contemporaneous endogenous variables:\n\n$TE = (E,T_e)$ The graph defined by nodes $S$ and edges $T_e$.\n\nTE is used to determine if the model is simultaneous or not. \n\nIf the model is not simultaneous, then TE have no cycles, that is, it is a \nDirected Acyclical Graph (DAG). Then we can find an order in which the formulas can\nbe calculated. This is called a topological order. \n\nThe topological order is a linear ordering of nodes (vertices) such that for every edge (v,u), node v comes before u in the ordering. \n\nA topological order is created by doing a topological sort of TE.   \n\nIf TE, the dependency graph associated with F is **not** a Directed Acyclical Graph (A DAG).\nThen F has contemporaneous feedback and is simultaneous. Or - in Excel speak - the \nmodel has circular references. And we need to use an iterative methods to solve the model. Sometime a model contains several simultaneous blocks. Then each block is a strong element of the graph. Each formula which is not part of a simultaneous bloc is in itself a strong element. \n\nA condensed graph where each strong element is condensed to a node is a DAG. \nSo the condensed graph have a topological order. This can be used when solving the model. \n\nThe dependency graphs are constructed, analyzed and manipulated through the **Networkx** Python library. \n\n###  Example dependency graphs\nTo illustrate the different graphs this small model is used.\n\n####  Total dependency graphs\nThis shows $TG$ mentioned above. \n\n\n```python\nmmodel.drawmodel(size=(0.8,0.8),title='Total graph')\n```\n\n\n    \n\n    \n\n\n### The dependency graph for contemporaneous endogenous variables (TE)\n\n\n```python\nmmodel.drawendo(size=(0.5,0.5),title='Contemporaneous endo')\n```\n\n\n    \n\n    \n\n\n#### And the adjacency matrix of the graph\nThe graph can also be represented as a adjacency matrix. This is a is a square matrix A. $A_{i,j}$  is one when there is an edge from node i to node j, and zero when there is no edge.\n\nIf the graph is a DAG the adjacency matrix, and the elements are in a topological order, is a lover triangular matrix. \n\n\n```python\na = mn.draw_adjacency_matrix(mmodel.endograph,mmodel.strongorder,mmodel.strongblock,\n                             mmodel.strongtype,size=(4,4))\n```\n\n### A topological sorted list of contemporaneous endogenous variables (the solve order) \nAlso a property of the model \n\n\n```python\nmmodel.topo\n```\n\n\n\n\n    ['A', 'X', 'D1', 'D3']\n\n\n\n### The dependency graph for contemporaneous endogenous variables, with feedback\nNow lets look at another small model. This time with feedback. \n\n\n```python\nfms = '''\nFRML xx Y  = C+I+E-M $ \nFRML xx C  = 0.9*Y+Y0 $ \nFRML xx C1 = 0.2*C $\nFRML xx C2 = 0.2*C1 $\nFRML xx M  = 0.1*Y + 0.2 * c $\nFRML xx M1 = 0.2*M $\nFRML xx E  = 0.1*E0 $\n'''\nmms = mc.model(fms)   # make a model instance \nmms.drawendo(size=(0.9,0.9))\n```\n\n\n    \n\n    \n\n\n### And the adjacency matrix of the graph \nWhen the model has contemporaneous feedback the TE will not be a DAG. There will be strong components with more than 1 node. This mean that the adjacency matix will have elements above the diagonal - like below. \n\nA graph where each strong component is condensed to a node will be a DAG. This can be calculated by ModelFlow. And the user can choose this as solving order. Else the model will be solved in the order in which the model is specified. \n\n\n```python\nmms.plotadjacency(size=(7,7));\n```\n\n\n```python\n# the strong components of the model, DAG's (recursive elements) are condensed\nprint(f'Strong blocks         : {mms.strongblock}')\nprint(f'Type of strong blocks : {mms.strongtype}')\n```\n\n    Strong blocks         : [['E'], ['C', 'Y', 'M'], ['M1', 'C1', 'C2']]\n    Type of strong blocks : ['Recursiv', 'Simultaneous', 'Recursiv']\n\n\n## Solution ordering \n\n### For normalized models: \nFor a model **without contemporaneous feedback**, the topoligical sorted order (mentioned abbove) is then used as calculating order. \n\nFor a model **with contemporaneous feedback** and no leaded variables, ModelFlow divides a model into three parts. A recursive **prolog** model, a recursive **epilog** model, the rest is the simultaneous **core** model. Inside the core model the ordering of the equations are preserved.  It may be that the core model contains several strong componens, which eachcould be solved as a simultanous system, however it is solved as one simultanous system.  \n\nOnly the core model is solved as a simultaneous system. The prolog model is calculated once before the solving og the simultaneous system, the epilog model is calculated once after the solution of the simultanous system. \nFor most models this significantly reduce the computational burden of solving the model. \n\nFor Gauss type solution the ordering of the equations in the core model can be important for the speed of convergence. \n\nFor a model with leaded variables the model is stacked, and a all  equations are created equal. For some models it could probably be useful split the model, but it has not been needed yes. \n\nThe cell below displays the variables in the three parts.\n\n\n```python\n# The preorder\nprint(f'The prolog variables {mms.preorder}')\nprint(f'The core   variables {mms.coreorder}')\nprint(f'The epilog variables {mms.epiorder}')\n```\n\n    The prolog variables ['E']\n    The core   variables ['Y', 'C', 'M']\n    The epilog variables ['C1', 'M1', 'C2']\n\n\n###  For un-normalized models: \nThe models are solved as one simultanous model. Either by newton - if no leaded variables - or by stacked-newton if the model has leaded variables. \n\n## Construction of Jacobi matrices.\nTo use a Newton type solver the matrix ($\\bf{A}$/$\\bf{\\bar A}$) the derivatives of all formulas with respect to all endogeneous variables is needed.    \n\n$\\bf{A}$  but especially $\\bf{\\bar A}$ can be quite large (more than $10.000 \\times 10.000$). So it can look like a daunting task to find the all the values and solve the linear model. However for most economic models $\\bf{A}$  is quite sparse, and by construct $\\bf{\\bar A}$ is very very sparse. Fortunately Python gives access to very efficient sparse libraries. The [Scipy library](https://scipy.org/scipylib/index.html) utilizes the [Intel\u00ae Math Kernel Library](https://software.intel.com/en-us/mkl).\nFirst step is to create a new model which calculates the values for all the relevant derivatives. In ModelFlow this can be done by **symbolic**, by **numerical differentiation** or by a combination.  \n\nThis entails specifying a model in the business logic language which calculate all the non-zero elements of the $\\bf{A}$/$\\bf{\\bar A}$ \n\nThis is done by in the Newton class, which vil generate a new model instance which can perform the calculations of all the relevant derivatives (non zero derivatives). As an instance of the model class, it will have all the capabilities of this class. In the this derivative model the formula for calculating  $\\dfrac{\\partial{numerator }}{{\\partial denominator(-lag)}}$ is written as:                             \n\n\\< numerator  \\>\\_\\_p\\_\\_\\< denominator >\\_\\_lag\\_\\_\\< lag\\> = derivative expression\n\n### A small Solow model \nAn example can be helpful \nFirst a small model is defined - in this case a solow growth model: \n\n\n```python\nfsolow = '''\\\nY         = a * k**alfa * l **(1-alfa) \nC         = (1-SAVING_RATIO)  * Y \nI         = Y - C \ndiff(K)   = I-depreciates_rate * K(-1)\ndiff(l)   = labor_growth * L(-1) \nK_i= K/L '''\nmsolow = model.from_eq(fsolow)\nprint(msolow.equations)\n```\n\n    FRML <> Y         = A * K**ALFA * L **(1-ALFA)  $\n    FRML <> C         = (1-SAVING_RATIO)  * Y  $\n    FRML <> I         = Y - C  $\n    FRML <> K=K(-1)+(I-DEPRECIATES_RATE * K(-1))$\n    FRML <> L=L(-1)+(LABOR_GROWTH * L(-1))$\n    FRML <> K_I= K/L  $\n\n\n### Create some data and solve the model \n\n\n```python\nN = 100\ndf = pd.DataFrame({'L':[100]*N,'K':[100]*N})\ndf.loc[:,'ALFA'] = 0.5\ndf.loc[:,'A'] = 1.\ndf.loc[:,'DEPRECIATES_RATE'] = 0.05\ndf.loc[:,'LABOR_GROWTH'] = 0.01\ndf.loc[:,'SAVING_RATIO'] = 0.05\nmsolow(df,max_iterations=100,first_test=10,silent=1);\n```\n\n### Create an diffirentiation instance of the model\nActually 2 instances are made, one which use symbolic differentiation one which use numerical differentiation.  \n\n\n```python\nfrom modelnewton import newton_diff\nmsolow.smpl(3,4)  # we only want a few years \nnewton = newton_diff(msolow)\nnewton2 = newton_diff(msolow,forcenum=1)\n```\n\n\n```python\nprint(newton.diff_model.equations)\n```\n\n    FRML  <> C__p__Y___lag___0 = 1-SAVING_RATIO   $\n    FRML  <> I__p__C___lag___0 = -1   $\n    FRML  <> I__p__Y___lag___0 = 1   $\n    FRML  <> K__p__I___lag___0 = 1   $\n    FRML  <> K__p__K___lag___1 = 1-DEPRECIATES_RATE   $\n    FRML  <> K_I__p__K___lag___0 = 1/L   $\n    FRML  <> K_I__p__L___lag___0 = -K/L**2   $\n    FRML  <> L__p__L___lag___1 = LABOR_GROWTH+1   $\n    FRML  <> Y__p__K___lag___0 = A*ALFA*K**ALFA*L**(1-ALFA)/K   $\n    FRML  <> Y__p__L___lag___0 = A*K**ALFA*L**(1-ALFA)*(1-ALFA)/L   $\n\n\n\n```python\nprint(newton2.diff_model.equations)\n```\n\n    FRML  <> C__p__Y___lag___0 = (((1-SAVING_RATIO)*(Y+0.0025))-((1-SAVING_RATIO)*(Y-0.0025)))/0.005   $\n    FRML  <> I__p__C___lag___0 = ((Y-(C+0.0025))-(Y-(C-0.0025)))/0.005   $\n    FRML  <> I__p__Y___lag___0 = (((Y+0.0025)-C)-((Y-0.0025)-C))/0.005   $\n    FRML  <> K__p__I___lag___0 = ((K(-1)+((I+0.0025)-DEPRECIATES_RATE*K(-1)))-(K(-1)+((I-0.0025)-DEPRECIATES_RATE*K(-1))))/0.005   $\n    FRML  <> K__p__K___lag___1 = (((K(-1)+0.0025)+(I-DEPRECIATES_RATE*(K(-1)+0.0025)))-((K(-1)-0.0025)+(I-DEPRECIATES_RATE*(K(-1)-0.0025))))/0.005   $\n    FRML  <> K_I__p__K___lag___0 = (((K+0.0025)/L)-((K-0.0025)/L))/0.005   $\n    FRML  <> K_I__p__L___lag___0 = ((K/(L+0.0025))-(K/(L-0.0025)))/0.005   $\n    FRML  <> L__p__L___lag___1 = (((L(-1)+0.0025)+(LABOR_GROWTH*(L(-1)+0.0025)))-((L(-1)-0.0025)+(LABOR_GROWTH*(L(-1)-0.0025))))/0.005   $\n    FRML  <> Y__p__K___lag___0 = ((A*(K+0.0025)**ALFA*L**(1-ALFA))-(A*(K-0.0025)**ALFA*L**(1-ALFA)))/0.005   $\n    FRML  <> Y__p__L___lag___0 = ((A*K**ALFA*(L+0.0025)**(1-ALFA))-(A*K**ALFA*(L-0.0025)**(1-ALFA)))/0.005   $\n\n\n### Display the full stacked matrix\nTo make the sparcity clear all zero values are shown as blank \n\n\n\n```python\nstacked_df = newton2.get_diff_df_tot()\nstacked_df.applymap(lambda x:f'{x:,.2f}' if x != 0.0 else ' ')\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n\n    .dataframe thead tr:last-of-type th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th>per</th>\n      <th colspan=\"6\" halign=\"left\">3</th>\n      <th colspan=\"6\" halign=\"left\">4</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>var</th>\n      <th>C</th>\n      <th>I</th>\n      <th>K</th>\n      <th>K_I</th>\n      <th>L</th>\n      <th>Y</th>\n      <th>C</th>\n      <th>I</th>\n      <th>K</th>\n      <th>K_I</th>\n      <th>L</th>\n      <th>Y</th>\n    </tr>\n    <tr>\n      <th>per</th>\n      <th>var</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"6\" valign=\"top\">3</th>\n      <th>C</th>\n      <td>-1.00</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>0.95</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <th>I</th>\n      <td>-1.00</td>\n      <td>-1.00</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>1.00</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <th>K</th>\n      <td></td>\n      <td>1.00</td>\n      <td>-1.00</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <th>K_I</th>\n      <td></td>\n      <td></td>\n      <td>0.01</td>\n      <td>-1.00</td>\n      <td>-0.01</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <th>L</th>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>-1.00</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <th>Y</th>\n      <td></td>\n      <td></td>\n      <td>0.51</td>\n      <td></td>\n      <td>0.49</td>\n      <td>-1.00</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <th rowspan=\"6\" valign=\"top\">4</th>\n      <th>C</th>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>-1.00</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>0.95</td>\n    </tr>\n    <tr>\n      <th>I</th>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>-1.00</td>\n      <td>-1.00</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>K</th>\n      <td></td>\n      <td></td>\n      <td>0.95</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>1.00</td>\n      <td>-1.00</td>\n      <td></td>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <th>K_I</th>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>0.01</td>\n      <td>-1.00</td>\n      <td>-0.01</td>\n      <td></td>\n    </tr>\n    <tr>\n      <th>L</th>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>1.01</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>-1.00</td>\n      <td></td>\n    </tr>\n    <tr>\n      <th>Y</th>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>0.51</td>\n      <td></td>\n      <td>0.49</td>\n      <td>-1.00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### Display the element of the sparse matrix\n\n### The results can also be displayed in a more user friendly way\n\n\n```python\nnewton.show_diff_latex()\n```\n\n\n$\\begin{eqnarray*} I_t  & = &  Y_t - C_t \\end{eqnarray*}$\n\n\n\n\\begin{eqnarray*}\\frac{\\partial I_t}{\\partial C_t} & = & - 1\\\\\\frac{\\partial I_t}{\\partial Y_t} & = & 1\\end{eqnarray*} \n\n\n\n|                                     |   3 |   4 |\n|:------------------------------------|----:|----:|\n| $\\frac{\\partial I_t}{\\partial C_t}$ |  -1 |  -1 |\n| $\\frac{\\partial I_t}{\\partial Y_t}$ |   1 |   1 |\n\n\n\n$\\begin{eqnarray*} C_t  & = &  ( 1 - SAVING\\_RATIO_t ) \\times Y_t \\end{eqnarray*}$\n\n\n\n\\begin{eqnarray*}\\frac{\\partial C_t}{\\partial Y_t} & = & 1 - SAVING\\_RATIO_t\\end{eqnarray*} \n\n\n\n|                                     |    3 |    4 |\n|:------------------------------------|-----:|-----:|\n| $\\frac{\\partial C_t}{\\partial Y_t}$ | 0.95 | 0.95 |\n\n\n\n$\\begin{eqnarray*} K_t  & = &  K_{t-1} + ( I_t - DEPRECIATES\\_RATE_t \\times K_{t-1} ) \\end{eqnarray*}$\n\n\n\n\\begin{eqnarray*}\\frac{\\partial K_t}{\\partial I_t} & = & 1\\\\\\frac{\\partial K_t}{\\partial K_{t-1}} & = & 1 - DEPRECIATES\\_RATE_t\\end{eqnarray*} \n\n\n\n|                                         |    3 |    4 |\n|:----------------------------------------|-----:|-----:|\n| $\\frac{\\partial K_t}{\\partial I_t}$     | 1    | 1    |\n| $\\frac{\\partial K_t}{\\partial K_{t-1}}$ | 0.95 | 0.95 |\n\n\n\n$\\begin{eqnarray*} L_t  & = &  L_{t-1} + ( LABOR\\_GROWTH_t \\times L_{t-1} ) \\end{eqnarray*}$\n\n\n\n\\begin{eqnarray*}\\frac{\\partial L_t}{\\partial L_{t-1}} & = & LABOR\\_GROWTH_t + 1\\end{eqnarray*} \n\n\n\n|                                         |    3 |    4 |\n|:----------------------------------------|-----:|-----:|\n| $\\frac{\\partial L_t}{\\partial L_{t-1}}$ | 1.01 | 1.01 |\n\n\n\n$\\begin{eqnarray*} K\\_I_t  & = &  K_t / L_t \\end{eqnarray*}$\n\n\n\n\\begin{eqnarray*}\\frac{\\partial K\\_I_t}{\\partial K_t} & = & 1 / L_t\\\\\\frac{\\partial K\\_I_t}{\\partial L_t} & = & - K_t / L_t ** 2\\end{eqnarray*} \n\n\n\n|                                        |           3 |           4 |\n|:---------------------------------------|------------:|------------:|\n| $\\frac{\\partial K\\_I_t}{\\partial K_t}$ |  0.0097059  |  0.0096098  |\n| $\\frac{\\partial K\\_I_t}{\\partial L_t}$ | -0.00943472 | -0.00925799 |\n\n\n\n$\\begin{eqnarray*} Y_t  & = &  A_t \\times K_t ** ALFA_t \\times L_t ** ( 1 - ALFA_t ) \\end{eqnarray*}$\n\n\n\n\\begin{eqnarray*}\\frac{\\partial Y_t}{\\partial K_t} & = & A_t \\times ALFA_t \\times K_t ** ALFA_t \\times L_t ** ( 1 - ALFA_t ) / K_t\\\\\\frac{\\partial Y_t}{\\partial L_t} & = & A_t \\times K_t ** ALFA_t \\times L_t ** ( 1 - ALFA_t ) \\times ( 1 - ALFA_t ) / L_t\\end{eqnarray*} \n\n\n\n|                                     |        3 |        4 |\n|:------------------------------------|---------:|---------:|\n| $\\frac{\\partial Y_t}{\\partial K_t}$ | 0.507135 | 0.509412 |\n| $\\frac{\\partial Y_t}{\\partial L_t}$ | 0.492966 | 0.490762 |\n\n\n## Speeding up solving through Just In Time compilation (Numba)\nPython is an interpreted language. Therefor the calculation speed can be improved. There are several avenues to speed up calculations. \n\nFirstly, use the matrix extensions if possible. This will force the use of the highly optimized routines in the \nNumpy library. \n\nSecondly, python code can be compiled. The most straight forward way is to use the \n**Numba** library. For simultaneous models which only operates on numerical data the \nuser can specify jit=1. This will engage the numba Just In \nTime Compiler and the model will solve significantly faster. However the compilation will \ntake some time and for large models Numba will choke on the model. Experience with a Danish model (1700 equations) shows a speedup from 5 million floating point \noperations per second (MFlops) to 800 MFlops.  \n\nAlso experiments with the **Cython** library has been performed. This library will translate the Python code to C++ code. Then a C++ compiler can compile the code and the run time will be improved a lot. \n\n### Optimizing access to DataFrame values\n**Execution speed is crucial.** Values in a DataFrame can be\naccessed in a number of ways. Some are fast, others are not. Therefore, some care has been exercised\nwhen accessing each value. \n\nIf we have a DataFrame df and a column with the name 'FY', the value in 2018 can be\naccessed like this: df.loc\\[2018,'FY'\\], This works fine for small models. However it is quite slow as the DataFrame\nhas to look up the position (row,column) of 2018 and 'FY' before it can\naccess the value in an underlying structure. When looking for the value for 2019 the Dataframe again has to to the lookup. \n\nWhen calculating simple (non simultaneous) models, the row and column of each value is\nresolved before the code generation and the value is accessed directly\nin an underlying property of dataframes  called values. So if FY is the 42 column of the DataFrame and the position of 2018 is assigned to the variable row. The value is accessed as df.values\\[row,42\\]. In this case no time is wasted for looking up the row and column of the position.  \n\nWhen using the iterative Gauss-Seidel solution method, all necessary\nvalues are transferred to a one-dimensional numpy calculation array - called a. So the value would just be accessed like: a\\[84\\]. This requires some overhead to stuff and unstuff the values from df. But data access is faster, as accessing elements in a one-dimensional array\nis faster than in a two-dimensional array. Also, the locality of data is\nincreased, thus the chance of a cache miss is reduced. This is especially important if the model is compiled. \n\n# Some Model manipulation capabilities  \n\n## Model inversion aka Target/instruments or Goal Seek \nIn ordet to answer questions like: \n\n- How much capital has to be injected in order to maintain a certain GDP level in a stressed scenario? \n- How much loans has to be shredded by the banks in order to maintain a minimum level of capital (slim to fit)? \n- How much capital has to be injected in order to keep all bank above a certain capital threshold ?\n\nThe model instance is capable to **\"invert\"** a model. To use the terminology of Tinbergen(1955) that is to calculate the value of some exogenous variables - **the instruments** which is required in order to achieve a certain target value for some endogenous variables - **the targets**. \n\nTo use the terminology of Excel it is a goal/seek functionality with multiple cells as goals and multiple cells as targets.  \n\nThe problem can be thought as follows: From the generic description of a model: $\\textbf{y}_t= \\textbf{F}(\\textbf{x}_{t})$. Here $\\textbf{x}_{t}$ are all predetermined variables - lagged endogenous and all exogenous variables. \n\nIn some models the result depends on the level of exogenous variables with a lag. For instance in a disease spreading model, the *number of infected* on a day depends on the *probability of transmission* some days before. If the *probability of transmission* is the instrument and the *number of infected* is the target. Therefor it can be useful to allow a **delay**, when finding the instruments. In this case we want to look at  $\\textbf{y}_t= \\textbf{F}(\\textbf{x}_{t-delay})$ \n\nThink of a condensed model ($\\textbf{G}$) with a few endogenous variables($\\bar{\\textbf{y}}_t$):\nthe targets and a few exogenous variables($\\bar{\\textbf{x}}_{t-delay}$): the instrument variables. All the rest of the predetermined variables are fixed:  \n$\\bar{\\textbf{y}}_t= \\textbf{G}(\\bar{\\textbf{x}}_{t-delay})$\n\nIf we invert G we have a model where  instruments are functions of targets:\n$\\bar{\\textbf{x}_{t-delay}}= \\textbf{G}^{-1}(\\bar{\\textbf{y}_{t}})$. Then all we have to do is to find\n$\\textbf{G}^{-1}(\\bar{\\textbf{y}_{t}})$\n\n### And how to solve for the instruments \nFor most models $\\bar{\\textbf{x}}_{t-delay}= \\textbf{G}^{-1}(\\bar{\\textbf{y}_{t}})$ do not have a nice close form solution. However it can be solved numerically. We  turn to Newton\u2013Raphson method.\n\nSo $\\bar{\\textbf{x}}_{t-delay}= \\textbf{G}^{-1}(\\bar{\\textbf{y}_{t}^*})$ will be found using :\n\nfor $k$ = 1 to convergence  \n\n>$\\bar{\\textbf{x}}_{t-delay,end}^k= \\bar{\\textbf{x}}_{t-delay,end}^{k-1}+ \\textbf{J}^{-1}_t \\times (\\bar{\\textbf{y}_{t}^*}-\n\\bar{\\textbf{y}_{t}}^{k-1})$\n\n>$\\bar{\\textbf{y}}_t^{k}= \\textbf{G}(\\bar{\\textbf{x}}_{t-delay}^{k})$\n\nconvergence: $\\mid\\bar{\\textbf{y}_{t}^*}-\n\\bar{\\textbf{y}_{t}}\n\\mid\\leq \\epsilon$\n\nNow we just need to find: \n\n$\\textbf{J}_t = \\frac{\\partial \\textbf{G} }{\\partial \\bar{\\textbf{x}}_{t-delay}}$\n\nA number of differentiation methods can be used (symbolic, automated or numerical). ModelFlow uses numerical differentiation, as it is quite simple and fast.\n\n$\\textbf{J}_t \\approx \\frac{\\Delta \\textbf{G} }{\\Delta \\bar{\\textbf{x}}_{t-delay}}$\n\nThat means that we should run the model one time for each instrument, and record the \neffect on each of the targets, then we have $\\textbf{J}_t$ \n\nIn order for $\\textbf{J}_t$ to be invertible there has to be the same number of targets and instruments. \n\nHowever, each instrument can be a basket of exogenous variable. They will be adjusted in fixed proportions. This can be useful for instance when using bank leverage as instruments. Then the leverage instrument can consist of several loan types.  \n\nYou will notice that the level of $\\bar{\\textbf{x}}$ is updated (by  $\\textbf{J}^{-1}_t \\times (\\bar{\\textbf{y}_{t}^*}-\n\\bar{\\textbf{y}_{t}}^{k-1})$) in all periods from $t-delay$ to $end$, where $end$ is the last timeframe in the dataframe. This is useful for many applications including calibration of disease spreading models and in economic models, where the instruments are level variable (i.e. not change variables). If this is not suitable, it can be changed in a future release. \n\nThe target/instrument functionality is implemented in the python class `targets_instruments` specified in **ModelFlows** `modelinvert` module.  \n\n### An example\nThe workflow is as follow:\n\n1.  Define the targets\n2.  Define the instruments \n3.  Create a target_instrument class istance\n4. Solve the problem \n\nStep one is to define the targets. This is done by creating a dataframe where the target values are set. In this case it can be done like this. \n\n\n```python\nmmodel.basedf\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>B</th>\n      <th>C</th>\n      <th>E</th>\n      <th>A</th>\n      <th>D3</th>\n      <th>D1</th>\n      <th>X</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2018</th>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>4.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>2019</th>\n      <td>1.0</td>\n      <td>2.0</td>\n      <td>4.0</td>\n      <td>2.0</td>\n      <td>9.0</td>\n      <td>7.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>2020</th>\n      <td>1.0</td>\n      <td>3.0</td>\n      <td>4.0</td>\n      <td>3.0</td>\n      <td>34.5</td>\n      <td>19.5</td>\n      <td>1.5</td>\n    </tr>\n    <tr>\n      <th>2021</th>\n      <td>1.0</td>\n      <td>6.0</td>\n      <td>4.0</td>\n      <td>4.0</td>\n      <td>228.0</td>\n      <td>52.0</td>\n      <td>3.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ntarget = mmodel.basedf.loc[2020:,['D3','D1']]+[1,10]\ntarget\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>D3</th>\n      <th>D1</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2020</th>\n      <td>35.5</td>\n      <td>29.5</td>\n    </tr>\n    <tr>\n      <th>2021</th>\n      <td>229.0</td>\n      <td>62.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThen we have to provide the instruments. This is **a list of list of tuples**. \n-  Each element in the outer list is an instrument. \n-  Each element in the inner list is an instrument variable \n-  Each element of the tuple contains a variable name and the associated impulse $\\Delta$. \n\nThe $\\Delta variable$ is used in the numerical differentiation. Also if one instrument contains several variables, the proportion of each variable will be determined by the relative $\\Delta  variable$. \n\nFor this experiment the inner list only contains one variable. \n\n\n```python\ninstruments = [ [('C',1)] , [('B',1)]]\n```\n\nNow we run the eksperiment \n\nFor models which are relative linear we don't need to update  \ud835\udc09\ud835\udc61  for each iteration and time frame. As our small toy model is nonlinear, the jacobi matrix has to be updated frequently. This is controlled by the nonlin=True option below.\n\n\n```python\nresult = mmodel.invert(mmodel.lastdf,target,instruments,nonlin=True)\nresult\n```\n\n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n\n\n\n    Finding instruments :   0%|          | 0/2\n\n\n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2020  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n    Will start calculating: My first model\n    2021  solved\n    My first model calculated \n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>B</th>\n      <th>C</th>\n      <th>E</th>\n      <th>A</th>\n      <th>D3</th>\n      <th>D1</th>\n      <th>X</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2018</th>\n      <td>1.000000</td>\n      <td>4.000000</td>\n      <td>4.0</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>2019</th>\n      <td>2.000000</td>\n      <td>5.000000</td>\n      <td>4.0</td>\n      <td>6.000000</td>\n      <td>127.500000</td>\n      <td>33.500000</td>\n      <td>2.500000</td>\n    </tr>\n    <tr>\n      <th>2020</th>\n      <td>-1.306782</td>\n      <td>2.562339</td>\n      <td>4.0</td>\n      <td>3.693218</td>\n      <td>36.104417</td>\n      <td>29.539970</td>\n      <td>1.281170</td>\n    </tr>\n    <tr>\n      <th>2021</th>\n      <td>9.482549</td>\n      <td>5.990026</td>\n      <td>4.0</td>\n      <td>12.044888</td>\n      <td>228.999286</td>\n      <td>61.999969</td>\n      <td>2.995013</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nAnd do the result match the target?\n\n\n```python\nresult-target\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>A</th>\n      <th>B</th>\n      <th>C</th>\n      <th>D1</th>\n      <th>D3</th>\n      <th>E</th>\n      <th>X</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2018</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2019</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2020</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.039970</td>\n      <td>0.604417</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2021</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>-0.000031</td>\n      <td>-0.000714</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nSo we got results for the target variable very close to the target values. \n\n### Shortfall targets\nAbove the target for each target variable is a certain values. Sometime we we need targets being above a certain shortfall value. In this case an instrument should be used to make the achieve the target threshold only if the target is belove the target. This is activated by an option:**shortfall=True**.\n\nThis feature can be useful calculating the amount of deleverage needed for banks to achieve a certain threshold of capital. \n\n## Attribution / Explanation \n\nExperience shows that it is useful to be able to explain the difference between the result from two runs. \nThe first level of understanding the difference is to look at selected formulas and find out, how much each input variables accounts for. \nThe second level of understanding the difference is to look at the attribution of the \nexogenous variables to the results of the model.  \n\nIf we have:\n\n$y = f(a,b)$\n\nand we have two solutions where the variables differs by $\\Delta y, \\Delta a, \\Delta b$\n\nHow much of $\\Delta y$ can be explained by $\\Delta a$ and $\\Delta b$ ?\n\nAnalytical the attributions $\\Omega a$ and $\\Omega b$ can  be calculated like this: \n\n$\\Delta y = \\underbrace{\\Delta a \\dfrac{\\partial {f}}{\\partial{a}}(a,b)}_{\\Omega a} + \n\\underbrace{\\Delta b \\dfrac{\\partial {f}}{\\partial{b}}(a,b)}_{\\Omega b}+Residual$\n\nModelFlow will do a numerical approximation of $\\Omega a$ and $\\Omega b$. This is done by looking at the two runs of the model:\n\n\\begin{eqnarray}  \ny_0&=&f(a_{0},b_{0}) \\\\\ny_1&=&f(a_0+\\Delta a,b_{0}+ \\Delta b)\n\\end{eqnarray}\n\nSo $\\Omega a$ and $\\Omega b$ can be determined:\n\n\\begin{eqnarray}  \n\\Omega f_a&=&f(a_1,b_1 )-f(a_1-\\Delta a,b_1) \\\\\n\\Omega f_b&=&f(a_1,b_1 )-f(a_1,b_1-\\Delta  b)\n\\end{eqnarray}\n\n\n\nAnd: \n\n\\begin{eqnarray}\nresidual = \\Omega f_a + \\Omega f_b -(y_1 - y_0) \n\\end{eqnarray}\nIf the model is fairly linear, the residual will be small. \n\n### Formula attribution\nAttribution analysis on the formula level is performed by the method **.dekomp**. \n\nThis method utilizes that two attributes .basedf and .lastdf containing the first and the last run are contained in the model instance. Also all the formulas are contained in the instance. Therefore a model, just with one formula - is created. Then experiments mentioned above is run for each period and each right hand side variable. \n\n\n```python\n_ = mmodel.dekomp('D1')\n```\n\n    \n    Formula        : FRML <> D1 = X + 3 * A(-1)+ C **2 +A  $ \n    \n                          2019       2020       2021\n    Variable    lag                                 \n    Base        0     7.000000  19.500000  52.000000\n    Alternative 0    33.500000  29.539970  61.999969\n    Difference  0    26.500000  10.039970   9.999969\n    Percent     0   378.571422  51.487023  19.230710\n    \n     Contributions to differende for  D1\n                       2019       2020       2021\n    Variable lag                                 \n    X         0    1.500000  -0.218830  -0.004987\n    A        -1    0.000000  12.000000   2.079655\n    C         0   21.000000  -2.434418  -0.119586\n    A         0    4.000000   0.693218   8.044888\n    \n     Share of contributions to differende for  D1\n                        2019        2020        2021\n    Variable lag                                    \n    A         0          15%          7%         80%\n             -1           0%        120%         21%\n    X         0           6%         -2%         -0%\n    C         0          79%        -24%         -1%\n    Total     0         100%        100%        100%\n    Residual  0           0%          0%          0%\n    \n     Contribution to growth rate D1\n                 2019        2020        2021\n    Variable lag                             \n    X         0   NaN       -0.0%       -0.0%\n    A        -1   NaN        0.4%        0.1%\n    C         0   NaN       -0.1%       -0.0%\n    A         0   NaN        0.0%        0.3%\n\n\nIf the baseline dataframe is set to the lagged variable of the last dataframe. We can \ncalculate the attributions to the change of results from time period to time period. \n\n### Walk the explanations. \nSometime we want to trace the attributions to variables in higher in the dependency graph. \n\nUsing the dependency graph TG, we can walk up the graph, and do an attribution calculation for each of the parents, grand parents and so on. \n\nIt should be mentioned that for *lagged* endogenous variable an attribution calculation will not be performed.  \n\nSo we use the **.explain** method. \n\nThe result will also be made into a vector graphic both in .pdf and .svg format. This allows for zooming into the tree, even if there are many leaves.   \n\n\n```python\n_ = mmodel.D1.explain(up=2)\n```\n\n\n    \n\n    \n\n\n### Model Attribution\n\nAt the model level we start by finding which exogenous variables have changed between two runs.\n\n\n```python\ndifdf = mmodel.exodif()\ndifdf\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>B</th>\n      <th>C</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2018</th>\n      <td>0.000000</td>\n      <td>3.000000</td>\n    </tr>\n    <tr>\n      <th>2019</th>\n      <td>1.000000</td>\n      <td>3.000000</td>\n    </tr>\n    <tr>\n      <th>2020</th>\n      <td>-2.306782</td>\n      <td>-0.437661</td>\n    </tr>\n    <tr>\n      <th>2021</th>\n      <td>8.482549</td>\n      <td>-0.009974</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nNow we make a dictionary of experiments where the key is the name of the\nexperiment and the value of each entry is the variable to investigate in the experiment \n\n\n```python\nexperiments = {e : [e]  for e in difdf.columns}\nexperiments \n```\n\n\n\n\n    {'B': ['B'], 'C': ['C']}\n\n\n\nThen we can let the model run through each experiment and record a number of summary\nvariable.  \n\n\n```python\nimpact = md.attribution(mmodel,experiments,start=2019,end=2021,summaryvar=['D*'])\nimpact\n```\n\n    0 Experiment : B \n     Touching: \n     ['B']\n    1 Experiment : C \n     Touching: \n     ['C']\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th colspan=\"3\" halign=\"left\">B</th>\n      <th colspan=\"3\" halign=\"left\">C</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>2019</th>\n      <th>2020</th>\n      <th>2021</th>\n      <th>2019</th>\n      <th>2020</th>\n      <th>2021</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>D1</th>\n      <td>1.0</td>\n      <td>0.693218</td>\n      <td>1.562203</td>\n      <td>25.5</td>\n      <td>9.346751</td>\n      <td>8.437766</td>\n    </tr>\n    <tr>\n      <th>D3</th>\n      <td>0.0</td>\n      <td>3.000000</td>\n      <td>-6.920345</td>\n      <td>118.5</td>\n      <td>-1.395583</td>\n      <td>7.919631</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nimpact['C',2021]\n```\n\n\n\n\n    D1    8.437766\n    D3    7.919631\n    Name: (C, 2021), dtype: float64\n\n\n\n\n```python\nfor sumaryvar in impact.index:\n    mv.attshow(md.GetAllImpact(impact, sumaryvar),tshow=0,t=False,annot=True,dec=1,\n               title='Impact on: '+sumaryvar,size=(3,3),showsum=True,head=1,tail=1)\n```\n\nWhen the results are displayed, they can be filtered, sliced and diced in a number of ways. \n\nFor a model of the EBA stress test the number of changed exogenous variable can be large. Using a dictionary to contain the experiments allows us to create experiments where all variable for each country are analyzed, or each macro variable for all countries are analyzed. \n\nAlso it is possible to use aggregated sums - useful for looking at impact on PD's. Or just the last time period - useful for looking at CET1 ratios. \n\nIf there are many experiments, data can be filtered in order to look only at the variables with an impact above a certain threshold. \n\nThe is also the possibility to anonymize the row and column names and to randomize\nthe order of rows and/or columns - useful for bank names. \n\n## Optimization \nUsing the convex optimization package CVXOPT, which is part of the Anaconda Python distribution a range of optimization problems can be solved. One example is the standard mean variance problem. \n\n### A mean variance problem\n\nIf we look at a fairly general mean variance optimization problem which has been adopted to banks it looks like this:  \n\n\\begin{eqnarray}  \n\\mathbf x & &\\mbox{Position in each asset(+)/liability(-) type}\\\\\n\\mathbf x & &\\mbox{Position in each asset(+)/liability(-) type}\\\\\n\\mathbf \\Sigma & &\\mbox{Covariance matrix} \\\\\n\\mathbf r & &\\mbox{Return vector}\\\\\n\\lambda & &\\mbox{Risk aversion}\\\\\n\\mathbf{riskweights}& &\\text{Vector of risk weights, liabilities has riskweight = 0}\\\\\nCapital& &\\mbox{Max of sum of risk weighted assets}\\\\\n\\mathbf{lcrweights}& &\\text{Vector of LCR weights, liabilities has lcrweight = 0}\\\\\nLCR& &\\text{Min of sum of lcr weighted assets}\\\\\n\\mathbf{leverageweight}&&\\text{Vector of leverage weights, liabilities has leverageweight = 0}\\\\\nEquity&&\\mbox{Max sum of leverage weighted positions}\\\\\nBudget&&\\mbox{initial sum of the positions}\\\\\n\\end{eqnarray}\n\n\\begin{eqnarray}\n\\mbox{minimize:}  & \\lambda \\mathbf x^T \\mathbf \\Sigma \\mathbf x - (1-\\lambda) \\mathbf r^T \\mathbf x & \\mbox{If }\\lambda \\mbox{ = 1 minimize risk, if } \\lambda\\mbox{ = 0 maximize return }\\\\\n\\mbox{subject to:} & \\mathbf x \\succeq \\mathbf{x^{min}} &\\mbox{Minimum positions}\\\\ \n                   & \\mathbf x \\preceq \\mathbf{x^{max}} &\\mbox{Maximum positions}\\\\ \n                   & \\mathbf{riskweights}^T\\mathbf x \\leq Capital &\\mbox{Risk weighted assets <= capital}\\\\ \n                   & \\mathbf{lcrweights}^T\\mathbf x \\geq LCR &\\mbox{lcr weighted assets >= LCR target}\\\\ \n                   & \\mathbf{leverageweight}^T\\mathbf x \\leq equity &\\mbox{leverage weighted assets <= equity}\\\\ \n                   & \\mathbf 1^T\\mathbf x = Budget & \\mbox{Sum of positions = B}\n\\end{eqnarray}\n\n\n### The mean variance problem in the business language language \n\nIn the business logic language this problem can be specified like this:\n\n``` \npositions =  mv_opt(msigma,return,riskaversion, budget, \n            [[risk_weights] , [-lcr_weights] , [leverage_weights]],\n              [capital, -lcr , equity] ,min_position,max_position) \n```\n\nWhere the arguments are appropriately dimensioned CVX matrices and vectors. \n\nFor a more elaborate example there is an special notebook on the subject of optimization.\n\nAlso it should be mentioned that there is an expansion of the basic problem taking transaction cost into account. \n\n\n## Symbolic model differentiation \nModelFlow have the capability to calculate expressions for differentiation of the formulas \nof a model. This is done by the Python symbolic math library **Sympy**. After finding the \nexpressions for the differential coefficients they can be evaluated - just like the model. Based on these a linearized \nversion of the model can be constructed. \n\nWe want to be able to find he Jacobi matrices:\n\n\\begin{eqnarray}  \n\\textbf{A} & = & \\frac{\\partial \\textbf{F}}{\\partial \\textbf{y}_t^T} \\\\ \\\\\n\\textbf{E}_i & = & \\frac{\\partial \\textbf{F}}{\\partial \\textbf{y}_{t-i}^T } \\hspace{5 mm} i=1, \\cdots , s \\\\ \\\\\n\\textbf{F}_j & = & \\frac{\\partial \\textbf{F}}{\\partial \\textbf{x}_{t-j} ^T} \\hspace{5 mm} j=0, \\cdots , r  \n\\end{eqnarray}\n\nThese matrices can be useful when finding stability properties. \n\nNow lets differentiate our toy model \n\n\n```python\nmdif.modeldiff(mmodel)\n```\n\n    Now differentiating A 0\n    Now differentiating D3 1\n    Now differentiating D1 2\n    Now differentiating X 3\n    Find espressions for partial derivatives took       :         0.0090262890 Seconds\n    Model                           : My first model\n    Number of variables             : 6\n    Number of endogeneus variables  : 4\n    Number of derivatives           : 5\n\n\nNow we can display the expressions for the differential coefficient - and the values in a selected time (row), in this case 2018.\n\n\n```python\nmdif.display_all(mmodel,mmodel.basedf,2018)\n```\n\n\n\\begin{eqnarray*}Formula:A  & = & C_{-1} + B \\\\\\end{eqnarray*} \n\n\n\n\\begin{eqnarray*}Formula:D1  & = & X + 3 * A_{-1}+ C **2 +A  \\\\\\\\\\frac{\\partial D1}{\\partial A}   & = & 1\\\\& = & 1\\\\\\frac{\\partial D1}{\\partial A_{-1}}   & = & 3\\\\& = & 3\\\\\\frac{\\partial D1}{\\partial X}   & = & 1\\\\& = & 1\\end{eqnarray*} \n\n\n\n\\begin{eqnarray*}Formula:D3  & = & X + 3 * A_{-1}+C **3 \\\\\\\\\\frac{\\partial D3}{\\partial A_{-1}}   & = & 3\\\\& = & 3\\\\\\frac{\\partial D3}{\\partial X}   & = & 1\\\\& = & 1\\end{eqnarray*} \n\n\n\n\\begin{eqnarray*}Formula:X  & = & 0.5 * C \\\\\\end{eqnarray*} \n\n\nAlso the matrices of differential coefficient (Jacobi matrices) for each lag, can be calculated\n\n\n```python\n# calculate \nmatdir = mdif.calculate_allmat(mmodel,mmodel.basedf,2018)\n# Display \nfor l,m in matdir.items():\n    print(f'Lag:{l} \\n {m} \\n')\n```\n\n    Lag:0 \n         A  D1  D3  X  B  C\n    A   0   0   0  0  0  0\n    D1  1   0   0  1  0  0\n    D3  0   0   0  1  0  0\n    X   0   0   0  0  0  0 \n    \n    Lag:-1 \n         A  D1  D3  X  B  C\n    A   0   0   0  0  0  0\n    D1  3   0   0  0  0  0\n    D3  3   0   0  0  0  0\n    X   0   0   0  0  0  0 \n    \n\n\nWe can carve out the matrices only for the endogenous variables. The A and E matrices mentioned above \ncan be extracted like this: \n\n\n```python\nfor l,m in matdir.items():\n    endomat = m.loc[:,[c for c in m.columns if c in mmodel.endogene]]\n    print(f'Lag:{l} \\n {endomat} \\n')\n```\n\n    Lag:0 \n         A  D1  D3  X\n    A   0   0   0  0\n    D1  1   0   0  1\n    D3  0   0   0  1\n    X   0   0   0  0 \n    \n    Lag:-1 \n         A  D1  D3  X\n    A   0   0   0  0\n    D1  3   0   0  0\n    D3  3   0   0  0\n    X   0   0   0  0 \n    \n\n\nA word of caution. \n\nSymbolic math can take time if the model is large. So it is advisable to test this feature on a small model which \ncaptures the essence before moving to a large model. \n\nAlso the Sympy library will only handle functions and expressions that it knows.  \n\n## Stability\nJacobi matrices can be used to evaluate the stability properties of the model. To do this we first look at a linearized version of the model. We are interested in the effect of shocks to the system. Will shocks be \ndamped or will they be amplified. \n\nTo calculate the effect of small perturbations the model can be linearized around a solution\n\n\\begin{eqnarray*}  \n\\Delta y_t & = & A \\Delta y_t + E_1 \\Delta y_{t-1} + \\cdots +E_r \\Delta y_{t-r} + F_0 \\Delta x_t  + \\cdots +F_s \\Delta x_{t-s} \\\\\nI\\Delta y_t-A \\Delta y_t & = &  \\hphantom{A \\Delta y_t +}E_1 \\Delta y_{t-1} + \\cdots +E_r \\Delta y_{t-r} + F _0\\Delta x_t   + \\cdots +F_s \\Delta x_{t-s} \\\\  \n(I-A)\\Delta y_t & =  &  \\hphantom{A \\Delta y_t +}E_1 \\Delta y_{t-1} + \\cdots +E_r \\Delta y_{t-r} + F_0 \\Delta x_t  + \\cdots +F_s \\Delta x_{t-s} \\\\ \n\\Delta y_t & =  & (I-A)^{-1}(E_1 \\Delta y_{t-1} + \\cdots +E_r \\Delta y_{t-r} + F_0 \\Delta x_t  + \\cdots +F_s \\Delta x_{t-s}) \\\\\n\\Delta y_t           & =  & (I-A)^{-1}E_1 \\Delta y_{t-1} + \\cdots +(I-A)^{-1}E_r \\Delta y_{t-r} + (I-A)^{-1}F_0 \\Delta x_t  + \\cdots +(I-A)^{-1}F_s \\Delta x_{t-s} \\\\\n\\end{eqnarray*}\n\n\n\n\\begin{eqnarray*}  \ny_t & = & F(y_t \\cdots y_{t-r},x_t \\cdots x_{t-s})     \\\\\n\\Delta y_t & =  & (I-A)^{-1}E_1 \\Delta y_{t-1} + \\cdots +(I-A)^{-1}E_r \\Delta y_{t-r} + (I-A)^{-1}F_0 \\Delta x_t  + \\cdots +(I-A)^{-1}F_s \\Delta x_{t-s}\n\\end{eqnarray*}\n\nwhere:\n\n\\begin{eqnarray*}\nA & = & \\frac{\\partial F}{\\partial y_t^T} \\\\ \\\\\nE_i & = & \\frac{\\partial F}{\\partial y_{t-i}^T } \\hspace{5 mm} i=1, \\cdots , r\\\\  \\\\\nF_j & = & \\frac{\\partial F}{\\partial x_{t-j} ^T} \\hspace{5 mm} j=0, \\cdots , s\\\\  \\\\\n\\end{eqnarray*}\n\n\n\nWe have\n\n\\begin{eqnarray*}  \ny_t & = & F(y_t \\cdots y_{t-r},x_t \\cdots x_{t-s})     \\\\\n\\Delta y_t & =  & (I-A)^{-1}E_1 \\Delta y_{t-1} + \\cdots +(I-A)^{-1}E_r \\Delta y_{t-r} + (I-A)^{-1}F_0 \\Delta x_t  + \\cdots +(I-A)^{-1}F_s \\Delta x_{t-s} \\\\\n\\end{eqnarray*}\n\nA rather messy problem. It can be made more simple. This is done by making a new linear model only incorporating \nvariables with one lag. \n\nThis is done the standard way by introducing new variables: $y^{1 }_{t}=y_{t-1}$,\n$y^{2}_{t}=y^1_{t-1}$,  and $y^{3}_{t}=y^2_{t-1}$ Using theese transformed variables, \na system with max lag of 3 can e rewritten like this: \n\n$\\underbrace{\n\\left[\\begin{matrix}\n\\Delta y^{3} _{t}\\\\\\Delta y^{2 }_{t}\\\\\\Delta y^{1 }_{t}\\\\\\Delta y_{t}\n\\end{matrix}\\right]}_{\\Delta \\bar y_t }=\n\\underbrace {\\left[\\begin{matrix}{0} & {0} & {0} & {0}\\\\{0} & {0} & {0} & {0}\\\\{0} & {0} & {0} & {0}\\\\{0} & {0} & {0} & A\\end{matrix}\\right]}_{\\bar A} \n\\underbrace{\\left[\\begin{matrix}\n\\Delta y^{3} _{t}\\\\\\Delta y^{2 }_{t}\\\\\\Delta y^{1 }_{t}\\\\\\Delta y_{t}\n\\end{matrix}\\right]}_{\\Delta \\bar y_t} +\n\\underbrace{\\left[\\begin{matrix}{0} & \\mathbb{I} & {0} & {0}\\\\{0} & {0} & \\mathbb{I} & {0}\\\\{0} & {0} & {0} & \\mathbb{I}\\\\E_{3} & E_{2} & E_{1} & E\\end{matrix}\\right]}_{\\bar E}\n\\underbrace{\\left[\\begin{matrix}\n\\Delta y^{3} _{t-1}\\\\\\Delta y^{2 }_{t-1}\\\\\\Delta y^{1 }_{t-1}\\\\\\Delta y^{ }_{t-1}\n\\end{matrix}\\right]}_{\\Delta \\bar y_{t-1}} +\n\\underbrace {\\left[\\begin{matrix}{0} & {0} & {0} & {0}\\\\{0} & {0} & {0} & {0}\\\\{0} & {0} & {0} & {0}\\\\F_{3} & F_{2} & F_{1} & F_{0}\\end{matrix}\\right]}_{\\bar F}\n\\underbrace   {\\left[\\begin{matrix}\\Delta x_{t-3}\\\\\\Delta x_{t-2}\\\\\\Delta x_{t-1}\\\\\\Delta x_{t\\hphantom{-1}}\\end{matrix}\\right]}_{\\bar x_t}$\n\n\n\nSo this expression:\n\n$\\Delta y_t  =  A \\Delta y_t + E_1 \\Delta y_{t-1} + \\cdots +E_r \\Delta y_{t-r} + F_0 \\Delta x_t  + \\cdots +F_r \\Delta x_{t-r}$\n\n\nHas been simplified to this expression :\n\n$\\Delta \\bar y_t  =  \\bar A \\Delta \\bar y_t + \\bar E \\Delta \\bar y_{t-1} + \\bar F \\Delta \\bar x_t$\n\n\nIt can be solved, so we only get the: $\\Delta \\bar y_t$ on the left hand side:\n\n$\\Delta \\bar y_t  =   (I-\\bar A)^{-1}\\bar E \\Delta \\bar y_{t-1} + (I-\\bar A)^{-1}\\bar F \\Delta \\bar x_t$\n\n$\\mbox{This expression :} \\\\\\Delta \\bar y_t  =   (I-\\bar A)^{-1}\\bar E \\Delta \\bar y_{t-1} + (I-\\bar A)^{-1}\\bar F \\Delta \\bar x_t$ \n\nWhich can be written this way:\n\n$\\underbrace{\\left[\\begin{matrix}\n\\Delta y^{3} _{t}\\\\\\Delta y^{2}_{t}\\\\\\Delta y^{1}_{t}\\\\\\Delta y_{t}\n\\end{matrix}\\right]}_{\\Delta \\bar y_t}=\n\\underbrace{\\left[\n\\begin{matrix}{0} & \\mathbb{I} & {0} & {0}\\\\{0} & {0} & \\mathbb{I} & {0}\\\\{0} & {0} & {0} & \\mathbb{I}\\\\\\left(\\mathbb{I} - A\\right)^{-1} E_{3} & \\left(\\mathbb{I} -A\\right)^{-1} E_{2} & \\left(\\mathbb{I}- A\\right)^{-1} E_{1} & \\left(\\mathbb{I}- A\\right)^{-1} E\\end{matrix}\n\\right]}_{ \\mbox{companion matrix}=(I-\\bar A)^{-1}\\bar E}\n\\underbrace{\\left[\\begin{matrix}\n\\Delta y^{3} _{t-1}\\\\\\Delta y^{2 }_{t-1}\\\\\\Delta y^{1 }_{t-1}\\\\\\Delta y^{ }_{t-1}\n\\end{matrix}\\right]}_{\\Delta \\bar y_{t-1}}\n+ \\\\\n\\underbrace{\\left[\\begin{matrix}{0} & {0} & {0} & {0}\\\\{0} & {0} & {0} & {0}\\\\{0} & {0} & {0} & {0}\\\\\\left(\\mathbb{I} - A\\right)^{-1} F_{3} & \\left(\\mathbb{I} - A\\right)^{-1} F_{2} & \\left(\\mathbb{I} - A\\right)^{-1} F_{1} & \\left(\\mathbb{I} - A\\right)^{-1} F_{0}\\end{matrix}\\right]}_{(I-\\bar A)^{-1}\\bar F} \n\\underbrace{\\left[\\begin{matrix}\\Delta x_{t-3}\\\\\\Delta x_{t-2}\\\\\\Delta x_{t-1}\\\\\\Delta x_{t\\hphantom{-1}}\\end{matrix}\\right]}_{\\Delta \\bar x_t}$\n\nSo now we have a linear model with only one lag. For this kind of models the dynamic behavior can be \nevaluated by looking at the eigenvalues $e_t$ of $((I-\\bar A)^{-1}\\bar E )$ \n\nIf all $\\lvert e_t \\lvert < 1$ the system will converge. If at least one of the eigenvalues is larger than one, the system will explode. $e_t$ can are complex numbers. If at least one $e_t$ has an imaginary part the system will oscillate - either dampened if all $\\lvert e_t \\lvert < 1$ or exploding if one $\\lvert e_t \\lvert > 1$.\n\nThe eigenvalues and associated eigenvectors can be found by the function mdif.get_eigen which will be used below.\n\n### Example: Samuelson multiplier accelerator model \nTo illustrate the feature this small classic model is created in a function which will display the results and a polar plot of the complex eigenvalues. \n\nThen experiment with different parameter values are performed in order to establish if shocks are \namplified or dampened and if shocks will induce oscillations or not. \n\n\n```python\ndef geteigen(mul,acc,years=100,show=False):\n    '''Function which creates a Samuelson Multiplier accelerator model, runs it\n    and alculates the eigenvalues for the compaignion matrix in order to \n    evaluate stability. \n    \n    A polar plot of the compex eigenvalues and graphs of the endogenous variables can \n    be displayes '''\n    \n    fam   = f'''\n    frml <>  y = c+i $ \n    frml <I> c = {mul} * y(-1) $\n    frml <>  i = {acc} * (c-c(-1)) + im $'''\n\n    mma = mc.model(fam,modelname = 'Accelerator multiplicator model')\n    df = pd.DataFrame([[1000,200]]*years,index=range(2018,2018+years),columns=['Y','IM'])\n    start = mc.model(f'c = {mul} * y(-1)')(df,silent=True) # Generate lagged variables for c \n    base  = mma(start,silent=True)     # Solve the model \n\n    compeig=mdif.get_eigen(mma,base,2021)       # find the eigenvalues and eigenvectors \n    if show:\n        mdif.eigplot(compeig[0])        # show the eigenvalues \n        _ = mma[['Y','C','I']].plot()  # Show the solution\n        \n    return  \n```\n\n#### Stability  \nAll eigenvalues shorter than 1 and no imaginary parts \n\n\n```python\ngeteigen(mul=0.5,acc=0,years=30,show=1)\n```\n\n#### Explosion \nAt least one eigenvalues above 1 no imaginary part\n\n\n```python\ngeteigen(mul=0.9,acc=2,years=30,show=1)\n```\n\n#### Exploding oscillations\nAt least one eigenvalue above 1 and imaginary parts\n\n\n```python\ngeteigen(mul=0.6,acc=2,years=30,show=1)\n```\n\n#### Perpetual oscillations \nEigenvalues at 1 with imaginary part\n\n\n```python\ngeteigen(mul=0.5,acc=2,years=30,show=1)\n```\n\n#### Dampened oscillations \nAll eigenvalues below 1 and imaginary parts\n\n\n```python\ngeteigen(mul=0.7,acc=1,years=30,show=1)\n```\n\nUsing this feature. ModelFlow can be used to analyze how different feedback parameters will impact stability.\nOf cause it requires that the model is differentiable, and for large models the analysis can take time and a lot of RAM.  \n\n# Onboarding data \nThe Pandas library really shines when it comes to retrieving and wrangling data. How to get data on board is very specific for each model and data source. There are many great books on using Pandas for data wrangling. So it is beyond the scope of this notebook to go into details on this subject. However, it is useful to go through some naming advice and a broad description of how data can be transformed to the right format.  \n\nModelFlow need to get the data as a wide Pandas DataFrame. Each row is one time frame. Each columns s a variable. \n\nThere are no limits to the length of column names. Therefor column names can be constructed meaningful. a column name should start with a letter then it can be followed by any numbers of letters, digits or \\_. Letters have to be upper case. If lower case letters are used in the Business logic, they will be converted to upper case. \n\nOften variables reflect a number of different dimensions. When naming variables separate the dimensions by a separator string.  \n\n$\\underbrace{REA\\_NON\\_DEF}_{type}\\_\\_ \n\\underbrace{DECOM}_{bank}\\_\\_\n\\underbrace{DE}_{Country}\\_\\_\n\\underbrace{HH\\_OTHER\\_NSME\\_AIRB}_{Sector}$\n\nNaming variables along dimensions is supported by ModelFlows slicing methods. Slicing allows for filtering of \nvariables with the help of wildcards like * and ?.  \n\nmodel\\['REA\\_NON\\_DEF\\_\\_\\*\\_\\_DE\\_\\_HH\\_OTHER\\_NSME\\_AIRB'\\] will return a dataframe with all columns where:\n\n-  type = REA\\_NON\\_DEF\n-  banks = all \n-  country= DE\n-  sector = HH_OTHER_NSME_AIRB \n\nIf we would limit the results to German banks we just write: \n\nmodel\\['REA\\_NON\\_DEF\\_\\_DE???\\_\\_DE\\_\\_HH\\_OTHER\\_NSME\\_AIRB'\\] \n\n\n## From tall to wide dataframes:\nTypically the necessary wide dataframe is constructed from a tall DataFrame. In this tall dataframe has a row for each value and a column for each dimension - including time. If we just look at the few rows related to the variable mentioned above, it could look like this. (of course mock data) \n\n|  value | year | type | bank | county | sector |\n|-------:|-----:|-----:|-----:| ------:| ------: |\n|.      | .|.|.| .|. |\n|.      | .|.|.| .|. |\n|1.00       | 2018|REA\\_NON\\_DEF|DECOM|DE|HH\\_OTHER\\_NSME\\_AIRB |\n|2.22       | 2019|REA\\_NON\\_DEF|DECOM|DE|HH\\_OTHER\\_NSME\\_AIRB |\n|3.33       | 2020|REA\\_NON\\_DEF|DECOM|DE|HH\\_OTHER\\_NSME\\_AIRB |\n|4.44       | 2021|REA\\_NON\\_DEF|DECOM|DE|HH\\_OTHER\\_NSME\\_AIRB |\n|.      | .|.|.| .|. |\n|.      | .|.|.| .|. |\n\nFirst step is to create a new dataframe with only the value, the year and the variable name. The variable name (varname) is constructed by joining the dimensions and separate them by '__' \n\n|  value | year | varname |\n|-------:|-----:|-----: |\n|. | .|.|\n|. | .|.|\n|1.00| 2018|REA\\_NON\\_DEF\\_\\_DECOM\\_\\_DE\\_\\_HH\\_OTHER\\_NSME\\_AIRB|\n|2.22| 2019|REA\\_NON\\_DEF\\_\\_DECOM\\_\\_DE\\_\\_HH\\_OTHER\\_NSME\\_AIRB|\n|3.33| 2020|REA\\_NON\\_DEF\\_\\_DECOM\\_\\_DE\\_\\_HH\\_OTHER\\_NSME\\_AIRB|\n|4.44| 2021|REA\\_NON\\_DEF\\_\\_DECOM\\_\\_DE\\_\\_HH\\_OTHER\\_NSME\\_AIRB|\n|. | .|.|\n|. | .|.|\n\nThen the dataframe is pivoted keeping the year dimension. Now the wide dataframe (ignoring all the other columns) for this variable could look like this:\n\n|  YEAR | ... | REA\\_NON\\_DEF\\_\\_DECOM\\_\\_DE\\_\\_HH\\_OTHER\\_NSME\\_AIRB| ... |\n|-------:|-----:|-----:                                              | ------: |\n| 2018|...|1.00       |...|\n| 2018|...|2.22       |...|\n| 2018|...|3.33       |...|\n| 2018|...|4.44       |... |\n\n\nA wide dataframe like this can be used as input to a ModelFlow model, so we are in business. \n\n# Summary\nModelFlow allows easy implementation of models in Python, Which is a powerful and agile language. ModelFlow leverage on the rich ecosystem of Python in order to: \n\n-  Separates the specification of a model and the code which solves the model. So the user can concentrate on the economic and not the implementation of the model.\n-  Can include user specified Python function in the model definition. \n-  Can solve very large models\n-  Can solve simultaneous models.\n-  Keeps tab on the dependencies of the formulas. This allows for easy Tracing of results. \n-  Can perform model inversion (goal seek) with multiple targets and instruments\n-  Can attribute changes in results to input variables. Both for individual formulas and the complete model \n-  Can include optimizing behavior \n \nThe purpose of this notebook has been to give a broad introduction to model management using ModelFlow. \nUsing the tool requires some knowledge of python. The required knowledge depends on the complexity of the model. So ModelFlow can be used in Python training.  \n\nTo get more in-depth knowledge there is a Sphinx based documentation of the library. There you can find the \ncalling conventions and documentation of all elements.\n\nAll suggestions and recommendations are welcome \n\n# Literature:\n\n\nAho, Lam, Sethi, Ullman (2006), Compilers: Principles, Techniques, and\nTools (2nd Edition), Addison-Wesley\n\nBerndsen, Ron (1995), [Causal ordering in economic\nmodels](https://kundoc.com/pdf-causal-ordering-in-economic-models-.html),\nDecision Support Systems 15 (1995) 157-165\n\nDanmarks Nationalbank (2004), [MONA -- a quarterly model of Danish\neconomy](http://www.nationalbanken.dk/da/publikationer/Documents/2003/11/mona_web.pdf)\n\nDenning, Peter J. (2006), [The Locality\nPrinciple](http://denninginstitute.com/pjd/PUBS/locality_2006.pdf),\nChapter in\u00a0*Communication Networks and Systems*\u00a0(J Barria, Ed.).\nImperial College Press\n\nGilli, Manfred (1992), [Causal Ordering and Beyond, International\nEconomic Review, Vol. 33, No. 4 (Nov., 1992), pp.\n957-971](http://www.jstor.org/stable/2527152?seq=1#page_scan_tab_contents)\n\nMcKinney, Wes (2011),[pandas: a Foundational Python Library for Data Analysis and\nStatistics,] Presented at\nPyHPC2011](http://www.scribd.com/doc/71048089/pandas-a-Foundational-Python-Library-for-Data-Analysis-and-Statistics)\n\nNumba (2015) documentation,\n[http://numba.pydata.org/numba-doc/0.20.0/user/index.html](http://numba.pydata.org/numba-doc/0.20.0/user/index.html%20)\n\nPauletto, G. (1997), [Computational Solution of Large-Scale\nMacroeconometric\nModels](http://link.springer.com/book/10.1007%2F978-1-4757-2631-2),\nISBN 9781441947789\n\nE. Petersen, Christian & A. Sims, Christopher. (1987). Computer Simulation of Large-Scale Econometric Models: Project Link. International Journal of High Performance Computing Applications (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.853.6387&rep=rep1&type=pdf)\n\nTinberger, Jan (1956), Economic policy: Principles and Design,\nAmsterdam,\n\n\n# Footnotes\n$^1$: The author has been able to draw on experience creating software\n    for solving the macroeconomic models ADAM in Hansen Econometric.\n\n$^2$: In this work a number of staff in Danmarks Nationalbank made\n    significant contributions: Jens Boldt and Jacob Ejsing to the\n    program. Rasmus Tommerup and Lindis Oma by being the first to\n    implement a stress test model in the system.\n\n$^3$: In ECB Marco Gross, Mathias Sydow and many other collegues has been of great help. \n\n$^4$: The system has benefited from discussions with participants in meetings at: IMF, Bank of Japan, Bank of England, FED Board, Oxford University, Banque de France, Single Resolution Board \n\n$^5$: Ast stands for: [Abstract Syntax\n    Tree](https://en.wikipedia.org/wiki/Abstract_syntax_tree)\n\n$^6$: Re stands for[: Regular\n    expression](https://en.wikipedia.org/wiki/Regular_expression)\n\n\n```python\n\n```\n", "meta": {"hexsha": "0cceea46cc4096a4958f5a5ad63325d2c40d3c2e", "size": 734861, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Examples/ModelFlow features/wp/ModelFlow-wp.ipynb", "max_stars_repo_name": "IbHansen/modelflow2", "max_stars_repo_head_hexsha": "7e8f115904971307f8231cafe6a899c50ee49b56", "max_stars_repo_licenses": ["X11"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Examples/ModelFlow features/wp/ModelFlow-wp.ipynb", "max_issues_repo_name": "IbHansen/modelflow2", "max_issues_repo_head_hexsha": "7e8f115904971307f8231cafe6a899c50ee49b56", "max_issues_repo_licenses": ["X11"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/ModelFlow features/wp/ModelFlow-wp.ipynb", "max_forks_repo_name": "IbHansen/modelflow2", "max_forks_repo_head_hexsha": "7e8f115904971307f8231cafe6a899c50ee49b56", "max_forks_repo_licenses": ["X11"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 82.6894340047, "max_line_length": 37204, "alphanum_fraction": 0.7350886766, "converted": true, "num_tokens": 44552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.06371499069622688, "lm_q1q2_score": 0.02619392520824533}}
{"text": "```python\n%load_ext autoreload\n%autoreload 2\n```\n\n\n```python\n!python -m pip install --upgrade jax==0.2.10 jaxlib==0.1.62+cuda101 -f https://storage.googleapis.com/jax-releases/jax_releases.html\n```\n\n\n```python\ncd /mnt/home/tmakinen/repositories/scratch/gitinstall/imnn\n```\n\n\n```python\n!git checkout dev;\n```\n\n    D\texamples/2D sims - IMNN.ipynb\n    M\texamples/IMNN - JAX.ipynb\n    Already on 'dev'\n    Your branch is ahead of 'origin/dev' by 3 commits.\n      (use \"git push\" to publish your local commits)\n\n\n\n```python\n!python -m pip install .\n```\n\n    Already up-to-date.\n\n\n\n```python\npwd\n```\n\n\n\n\n    '/mnt/home/tmakinen/repositories/scratch/dev-imnn/imnn'\n\n\n\n\n```python\n!python -m setup.py install\n```\n\n    /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/setuptools/dist.py:458: UserWarning: Normalizing '0.3dev' to '0.3.dev0'\n      warnings.warn(tmpl.format(**locals()))\n    running install\n    running bdist_egg\n    running egg_info\n    writing IMNN.egg-info/PKG-INFO\n    writing dependency_links to IMNN.egg-info/dependency_links.txt\n    writing requirements to IMNN.egg-info/requires.txt\n    writing top-level names to IMNN.egg-info/top_level.txt\n    reading manifest file 'IMNN.egg-info/SOURCES.txt'\n    writing manifest file 'IMNN.egg-info/SOURCES.txt'\n    installing library code to build/bdist.linux-x86_64/egg\n    running install_lib\n    running build_py\n    copying IMNN/experimental/jax/imnn/imnn.py -> build/lib/IMNN/experimental/jax/imnn\n    creating build/bdist.linux-x86_64/egg\n    creating build/bdist.linux-x86_64/egg/IMNN\n    creating build/bdist.linux-x86_64/egg/IMNN/LFI\n    copying build/lib/IMNN/LFI/LFI.py -> build/bdist.linux-x86_64/egg/IMNN/LFI\n    copying build/lib/IMNN/LFI/__init__.py -> build/bdist.linux-x86_64/egg/IMNN/LFI\n    copying build/lib/IMNN/IMNN.py -> build/bdist.linux-x86_64/egg/IMNN\n    copying build/lib/IMNN/tfIMNN.py -> build/bdist.linux-x86_64/egg/IMNN\n    copying build/lib/IMNN/__init__.py -> build/bdist.linux-x86_64/egg/IMNN\n    creating build/bdist.linux-x86_64/egg/IMNN/utils\n    copying build/lib/IMNN/utils/__init__.py -> build/bdist.linux-x86_64/egg/IMNN/utils\n    copying build/lib/IMNN/utils/utils.py -> build/bdist.linux-x86_64/egg/IMNN/utils\n    copying build/lib/IMNN/utils/TFRecords.py -> build/bdist.linux-x86_64/egg/IMNN/utils\n    creating build/bdist.linux-x86_64/egg/IMNN/experimental\n    copying build/lib/IMNN/experimental/__init__.py -> build/bdist.linux-x86_64/egg/IMNN/experimental\n    creating build/bdist.linux-x86_64/egg/IMNN/experimental/jax\n    creating build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/_tensorflow_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/tensorflow_gradient_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/aggregated_gradient_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/gradient_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/numerical_gradient_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/aggregated_numerical_gradient_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/aggregated_numerical_gradient_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/gradient_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/__init__.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/simulator_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/aggregated_simulator_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/tensorflow_numerical_gradient_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/simulator_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/_tensorflow_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/aggregated_gradient_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/numerical_gradient_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/aggregated_simulator_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    creating build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi\n    copying build/lib/IMNN/experimental/jax/lfi/gaussian_approximation.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi\n    copying build/lib/IMNN/experimental/jax/lfi/lfi.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi\n    copying build/lib/IMNN/experimental/jax/lfi/__init__.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi\n    copying build/lib/IMNN/experimental/jax/lfi/approximate_bayesian_computation.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi\n    copying build/lib/IMNN/experimental/jax/__init__.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax\n    creating build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils\n    copying build/lib/IMNN/experimental/jax/utils/__init__.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils\n    copying build/lib/IMNN/experimental/jax/utils/utils.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils\n    copying build/lib/IMNN/experimental/jax/utils/keras_utils.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils\n    copying build/lib/IMNN/experimental/jax/utils/container.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils\n    copying build/lib/IMNN/experimental/jax/utils/jac.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils\n    creating build/bdist.linux-x86_64/egg/test\n    copying build/lib/test/tensorflow_defaults.py -> build/bdist.linux-x86_64/egg/test\n    copying build/lib/test/simulator_defaults.py -> build/bdist.linux-x86_64/egg/test\n    copying build/lib/test/numerical_gradient_defaults.py -> build/bdist.linux-x86_64/egg/test\n    copying build/lib/test/__init__.py -> build/bdist.linux-x86_64/egg/test\n    copying build/lib/test/gradient_defaults.py -> build/bdist.linux-x86_64/egg/test\n    copying build/lib/test/defaults.py -> build/bdist.linux-x86_64/egg/test\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/LFI/LFI.py to LFI.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/LFI/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/IMNN.py to IMNN.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/tfIMNN.py to tfIMNN.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/utils/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/utils/utils.py to utils.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/utils/TFRecords.py to TFRecords.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/_tensorflow_imnn.py to _tensorflow_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/tensorflow_gradient_imnn.py to tensorflow_gradient_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/aggregated_gradient_imnn_test.py to aggregated_gradient_imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/gradient_imnn_test.py to gradient_imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/numerical_gradient_imnn_test.py to numerical_gradient_imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/_imnn.py to _imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/aggregated_numerical_gradient_imnn_test.py to aggregated_numerical_gradient_imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/imnn.py to imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/aggregated_numerical_gradient_imnn.py to aggregated_numerical_gradient_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/gradient_imnn.py to gradient_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/_imnn_test.py to _imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/simulator_imnn_test.py to simulator_imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/aggregated_simulator_imnn.py to aggregated_simulator_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/tensorflow_numerical_gradient_imnn.py to tensorflow_numerical_gradient_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/simulator_imnn.py to simulator_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/_tensorflow_imnn_test.py to _tensorflow_imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/aggregated_gradient_imnn.py to aggregated_gradient_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/numerical_gradient_imnn.py to numerical_gradient_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/aggregated_simulator_imnn_test.py to aggregated_simulator_imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi/gaussian_approximation.py to gaussian_approximation.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi/lfi.py to lfi.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi/approximate_bayesian_computation.py to approximate_bayesian_computation.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils/utils.py to utils.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils/keras_utils.py to keras_utils.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils/container.py to container.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils/jac.py to jac.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/test/tensorflow_defaults.py to tensorflow_defaults.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/test/simulator_defaults.py to simulator_defaults.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/test/numerical_gradient_defaults.py to numerical_gradient_defaults.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/test/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/test/gradient_defaults.py to gradient_defaults.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/test/defaults.py to defaults.cpython-36.pyc\n    creating build/bdist.linux-x86_64/egg/EGG-INFO\n    copying IMNN.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying IMNN.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying IMNN.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying IMNN.egg-info/requires.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying IMNN.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    zip_safe flag not set; analyzing archive contents...\n    creating 'dist/IMNN-0.3.dev0-py3.6.egg' and adding 'build/bdist.linux-x86_64/egg' to it\n    removing 'build/bdist.linux-x86_64/egg' (and everything under it)\n    Processing IMNN-0.3.dev0-py3.6.egg\n    Removing /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/IMNN-0.3.dev0-py3.6.egg\n    Copying IMNN-0.3.dev0-py3.6.egg to /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    IMNN 0.3.dev0 is already the active version in easy-install.pth\n    \n    Installed /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/IMNN-0.3.dev0-py3.6.egg\n    Processing dependencies for IMNN==0.3.dev0\n    Searching for matplotlib==3.3.2\n    Best match: matplotlib 3.3.2\n    Adding matplotlib 3.3.2 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for scipy==1.5.3\n    Best match: scipy 1.5.3\n    Adding scipy 1.5.3 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for numpy==1.19.4\n    Best match: numpy 1.19.4\n    Adding numpy 1.19.4 to easy-install.pth file\n    Installing f2py script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing f2py3 script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing f2py3.6 script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for tqdm==4.55.1\n    Best match: tqdm 4.55.1\n    Processing tqdm-4.55.1-py3.6.egg\n    tqdm 4.55.1 is already the active version in easy-install.pth\n    Installing tqdm script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/tqdm-4.55.1-py3.6.egg\n    Searching for jax==0.2.8\n    Best match: jax 0.2.8\n    Processing jax-0.2.8-py3.6.egg\n    jax 0.2.8 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/jax-0.2.8-py3.6.egg\n    Searching for jaxlib==0.1.57+cuda101\n    Best match: jaxlib 0.1.57+cuda101\n    Removing jaxlib 0.1.59 from easy-install.pth file\n    Adding jaxlib 0.1.57+cuda101 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for tensorflow==2.4.0\n    Best match: tensorflow 2.4.0\n    Processing tensorflow-2.4.0-py3.6-linux-x86_64.egg\n    tensorflow 2.4.0 is already the active version in easy-install.pth\n    Installing estimator_ckpt_converter script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing import_pb_to_tensorboard script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing saved_model_cli script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing tensorboard script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing tf_upgrade_v2 script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing tflite_convert script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing toco script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing toco_from_protos script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/tensorflow-2.4.0-py3.6-linux-x86_64.egg\n    Searching for certifi==2020.12.5\n    Best match: certifi 2020.12.5\n    Adding certifi 2020.12.5 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for Pillow==8.1.0\n    Best match: Pillow 8.1.0\n    Adding Pillow 8.1.0 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for python-dateutil==2.8.1\n    Best match: python-dateutil 2.8.1\n    Adding python-dateutil 2.8.1 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for kiwisolver==1.3.1\n    Best match: kiwisolver 1.3.1\n    Adding kiwisolver 1.3.1 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for cycler==0.10.0\n    Best match: cycler 0.10.0\n    Adding cycler 0.10.0 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for pyparsing==2.4.7\n    Best match: pyparsing 2.4.7\n    Adding pyparsing 2.4.7 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for opt-einsum==3.3.0\n    Best match: opt-einsum 3.3.0\n    Adding opt-einsum 3.3.0 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for absl-py==0.11.0\n    Best match: absl-py 0.11.0\n    Adding absl-py 0.11.0 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for flatbuffers==1.12\n    Best match: flatbuffers 1.12\n    Adding flatbuffers 1.12 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for wrapt==1.12.1\n    Best match: wrapt 1.12.1\n    Processing wrapt-1.12.1-py3.6-linux-x86_64.egg\n    wrapt 1.12.1 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/wrapt-1.12.1-py3.6-linux-x86_64.egg\n    Searching for wheel==0.36.2\n    Best match: wheel 0.36.2\n    Adding wheel 0.36.2 to easy-install.pth file\n    Installing wheel script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for typing-extensions==3.7.4.3\n    Best match: typing-extensions 3.7.4.3\n    Processing typing_extensions-3.7.4.3-py3.6.egg\n    typing-extensions 3.7.4.3 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/typing_extensions-3.7.4.3-py3.6.egg\n    Searching for termcolor==1.1.0\n    Best match: termcolor 1.1.0\n    Processing termcolor-1.1.0-py3.6.egg\n    termcolor 1.1.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/termcolor-1.1.0-py3.6.egg\n    Searching for tensorflow-estimator==2.4.0\n    Best match: tensorflow-estimator 2.4.0\n    Processing tensorflow_estimator-2.4.0-py3.6.egg\n    tensorflow-estimator 2.4.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/tensorflow_estimator-2.4.0-py3.6.egg\n    Searching for tensorboard==2.4.0\n    Best match: tensorboard 2.4.0\n    Processing tensorboard-2.4.0-py3.6.egg\n    tensorboard 2.4.0 is already the active version in easy-install.pth\n    Installing tensorboard script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/tensorboard-2.4.0-py3.6.egg\n    Searching for six==1.15.0\n    Best match: six 1.15.0\n    Adding six 1.15.0 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for protobuf==4.0.0rc2\n    Best match: protobuf 4.0.0rc2\n    Processing protobuf-4.0.0rc2-py3.6.egg\n    protobuf 4.0.0rc2 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/protobuf-4.0.0rc2-py3.6.egg\n    Searching for Keras-Preprocessing==1.1.2\n    Best match: Keras-Preprocessing 1.1.2\n    Processing Keras_Preprocessing-1.1.2-py3.6.egg\n    Keras-Preprocessing 1.1.2 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/Keras_Preprocessing-1.1.2-py3.6.egg\n    Searching for h5py==2.10.0\n    Best match: h5py 2.10.0\n    Processing h5py-2.10.0-py3.6-linux-x86_64.egg\n    h5py 2.10.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/h5py-2.10.0-py3.6-linux-x86_64.egg\n    Searching for grpcio==1.32.0\n    Best match: grpcio 1.32.0\n    Processing grpcio-1.32.0-py3.6-linux-x86_64.egg\n    grpcio 1.32.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/grpcio-1.32.0-py3.6-linux-x86_64.egg\n    Searching for google-pasta==0.2.0\n    Best match: google-pasta 0.2.0\n    Processing google_pasta-0.2.0-py3.6.egg\n    google-pasta 0.2.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/google_pasta-0.2.0-py3.6.egg\n    Searching for gast==0.3.3\n    Best match: gast 0.3.3\n    Processing gast-0.3.3-py3.6.egg\n    gast 0.3.3 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/gast-0.3.3-py3.6.egg\n    Searching for astunparse==1.6.3\n    Best match: astunparse 1.6.3\n    Processing astunparse-1.6.3-py3.6.egg\n    astunparse 1.6.3 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/astunparse-1.6.3-py3.6.egg\n    Searching for Werkzeug==1.0.1\n    Best match: Werkzeug 1.0.1\n    Processing Werkzeug-1.0.1-py3.6.egg\n    Werkzeug 1.0.1 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/Werkzeug-1.0.1-py3.6.egg\n    Searching for tensorboard-plugin-wit==1.7.0\n    Best match: tensorboard-plugin-wit 1.7.0\n    Processing tensorboard_plugin_wit-1.7.0-py3.6.egg\n    tensorboard-plugin-wit 1.7.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/tensorboard_plugin_wit-1.7.0-py3.6.egg\n    Searching for setuptools==49.6.0.post20201009\n    Best match: setuptools 49.6.0.post20201009\n    Adding setuptools 49.6.0.post20201009 to easy-install.pth file\n    Installing easy_install script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for requests==2.25.1\n    Best match: requests 2.25.1\n    Processing requests-2.25.1-py3.6.egg\n    requests 2.25.1 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/requests-2.25.1-py3.6.egg\n    Searching for Markdown==3.3.3\n    Best match: Markdown 3.3.3\n    Processing Markdown-3.3.3-py3.6.egg\n    Markdown 3.3.3 is already the active version in easy-install.pth\n    Installing markdown_py script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/Markdown-3.3.3-py3.6.egg\n    Searching for google-auth==1.24.0\n    Best match: google-auth 1.24.0\n    Processing google_auth-1.24.0-py3.6.egg\n    google-auth 1.24.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/google_auth-1.24.0-py3.6.egg\n    Searching for google-auth-oauthlib==0.4.2\n    Best match: google-auth-oauthlib 0.4.2\n    Processing google_auth_oauthlib-0.4.2-py3.6.egg\n    google-auth-oauthlib 0.4.2 is already the active version in easy-install.pth\n    Installing google-oauthlib-tool script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/google_auth_oauthlib-0.4.2-py3.6.egg\n    Searching for urllib3==1.26.2\n    Best match: urllib3 1.26.2\n    Processing urllib3-1.26.2-py3.6.egg\n    urllib3 1.26.2 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/urllib3-1.26.2-py3.6.egg\n    Searching for idna==2.10\n    Best match: idna 2.10\n    Processing idna-2.10-py3.6.egg\n    idna 2.10 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/idna-2.10-py3.6.egg\n    Searching for chardet==4.0.0\n    Best match: chardet 4.0.0\n    Processing chardet-4.0.0-py3.6.egg\n    chardet 4.0.0 is already the active version in easy-install.pth\n    Installing chardetect script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/chardet-4.0.0-py3.6.egg\n    Searching for importlib-metadata==3.3.0\n    Best match: importlib-metadata 3.3.0\n    Processing importlib_metadata-3.3.0-py3.6.egg\n    importlib-metadata 3.3.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/importlib_metadata-3.3.0-py3.6.egg\n    Searching for rsa==4.6\n    Best match: rsa 4.6\n    Processing rsa-4.6-py3.6.egg\n    rsa 4.6 is already the active version in easy-install.pth\n    Installing pyrsa-decrypt script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing pyrsa-encrypt script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing pyrsa-keygen script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing pyrsa-priv2pub script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing pyrsa-sign script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing pyrsa-verify script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/rsa-4.6-py3.6.egg\n    Searching for pyasn1-modules==0.2.8\n    Best match: pyasn1-modules 0.2.8\n    Processing pyasn1_modules-0.2.8-py3.6.egg\n    pyasn1-modules 0.2.8 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/pyasn1_modules-0.2.8-py3.6.egg\n    Searching for cachetools==4.2.0\n    Best match: cachetools 4.2.0\n    Processing cachetools-4.2.0-py3.6.egg\n    cachetools 4.2.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/cachetools-4.2.0-py3.6.egg\n    Searching for requests-oauthlib==1.3.0\n    Best match: requests-oauthlib 1.3.0\n    Processing requests_oauthlib-1.3.0-py3.6.egg\n    requests-oauthlib 1.3.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/requests_oauthlib-1.3.0-py3.6.egg\n    Searching for zipp==3.4.0\n    Best match: zipp 3.4.0\n    Processing zipp-3.4.0-py3.6.egg\n    zipp 3.4.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/zipp-3.4.0-py3.6.egg\n    Searching for pyasn1==0.4.8\n    Best match: pyasn1 0.4.8\n    Processing pyasn1-0.4.8-py3.6.egg\n    pyasn1 0.4.8 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/pyasn1-0.4.8-py3.6.egg\n    Searching for oauthlib==3.1.0\n    Best match: oauthlib 3.1.0\n    Processing oauthlib-3.1.0-py3.6.egg\n    oauthlib 3.1.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/oauthlib-3.1.0-py3.6.egg\n    Finished processing dependencies for IMNN==0.3.dev0\n    /mnt/home/tmakinen/anaconda3/envs/pyjax/bin/python: Error while finding module specification for 'setup.py' (AttributeError: module 'setup' has no attribute '__path__')\n\n\n### plot setup (run cell)\n\n\n```python\n# Create figures in Python that handle LaTeX, and save images to files in my\n# preferred formatting. I typically place this code in the root of each of my\n# projects, and import using:\n# from latexify import *\n# which will also run the latexify() function on the import.\n\n# Based on code from https://nipunbatra.github.io/blog/2014/latexify.html\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom math import sqrt\n\n#Back-end to use depends on the system\nfrom matplotlib.backends.backend_pgf import FigureCanvasPgf\nmatplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf)\n# matplotlib.use('pgf')\n# from matplotlib.backends.backend_pgf import FigureCanvasPgf\n# matplotlib.backend_bases.register_backend('ps', FigureCanvasPgf)\n\nimport seaborn as sns\nsns.set_style(\"white\")\n\n#my preferred palette. From\n#https://seaborn.pydata.org/tutorial/color_palettes.html: \"The cubehelix color\n#palette system makes sequential palettes with a linear increase or decrease in\n#brightness and some variation in hue. This means that the information in your\n#colormap will be preserved when converted to black and white (for printing) or\n#when viewed by a colorblind individual.\"\n\n# I typically set the number of colors (below, 8) to the distinct colors I need\n# in a given plot, so as to use the full range.\nsns.set_palette(sns.color_palette(\"cubehelix\", 8))\n\n\n# The following is the latexify function. It allows you to create 2 column or 1\n# column figures. You may also wish to alter the height or width of the figure.\n# The default settings are good for most cases. You may also change the\n# parameters such as labelsize and fontsize based on your classfile.\ndef latexify(fig_width=None, fig_height=None, columns=1):\n    \"\"\"Set up matplotlib's RC params for LaTeX plotting.\n    Call this before plotting a figure.\n    Parameters\n    ----------\n    fig_width : float, optional, inches\n    fig_height : float,  optional, inches\n    columns : {1, 2}\n    \"\"\"\n\n    # code adapted from http://www.scipy.org/Cookbook/Matplotlib/LaTeX_Examples\n    # Width and max height in inches for IEEE journals taken from\n    # computer.org/cms/Computer.org/Journal%20templates/transactions_art_guide.pdf\n\n    assert(columns in [1, 2])\n\n    if fig_width is None:\n        fig_width = 6.9 if columns == 1 else 13.8  # width in inches #3.39\n\n    if fig_height is None:\n        golden_mean = (sqrt(5) - 1.0) / 2.0    # Aesthetic ratio\n        fig_height = fig_width * golden_mean  # height in inches\n\n    MAX_HEIGHT_INCHES = 16.0\n    if fig_height > MAX_HEIGHT_INCHES:\n        print((\"WARNING: fig_height too large:\" + fig_height +\n              \"so will reduce to\" + MAX_HEIGHT_INCHES + \"inches.\"))\n        fig_height = MAX_HEIGHT_INCHES\n\n    params = {\n            # 'backend': 'ps',\n           #   'pgf.rcfonts': False,\n           #   'pgf.preamble': ['\\\\usepackage{gensymb}', '\\\\usepackage[dvipsnames]{xcolor}'],\n           #   \"pgf.texsystem\": \"pdflatex\",\n             # 'text.latex.preamble': ['\\\\usepackage{gensymb}', '\\\\usepackage[dvipsnames]{xcolor}'],\n              'text.latex.preamble': '\\\\usepackage{mathptmx}',\n              #values below are useful defaults. individual plot fontsizes are\n              #modified as necessary.\n              'axes.labelsize': 8,  # fontsize for x and y labels\n              'axes.titlesize': 8,\n              'font.size': 8,\n              'legend.fontsize': 8,\n              'xtick.labelsize': 8,\n              'ytick.labelsize': 8,\n              'text.usetex': True,\n              'figure.figsize': [fig_width, fig_height],\n              'font.family': 'serif',\n              'font.serif': 'Times',\n               'lines.linewidth': 1.5,\n               'lines.markersize':1,\n               'xtick.major.pad' : 2,\n               'ytick.major.pad' : 2,\n                'axes.xmargin' :  .0,  # x margin.  See `axes.Axes.margins`\n                'axes.ymargin' : .0,  # y margin See `axes.Axes.margins`\n              }\n\n    matplotlib.rcParams.update(params)\n\ndef saveimage(name, fig = plt, extension = 'pdf', folder = 'plots/'):\n    sns.despine()\n\n    #Minor ticks off by default in matplotlib\n    # plt.minorticks_off()\n\n    #grid being off is the default for seaborn white style, so not needed.\n    # plt.grid(False, axis = \"x\")\n    # plt.grid(False, axis = \"y\")\n    \n    fig.savefig('{}{}.{}'.format(folder,name, extension), bbox_inches = 'tight')\n\nlatexify()\n```\n\n\n```python\n!XLA_FLAGS=--xla_gpu_cuda_data_dir=/cm/shared/sw/pkg/devel/cuda/10.1.243_418.87.00\nfrom jax.config import config\nconfig.update(\"jax_debug_nans\", True)\nconfig.update('jax_enable_x64', True)\n\n```\n\n\n```python\nimport itertools\nimport math\nfrom functools import partial\n\nimport numpy as onp\n\nimport jax\nprint(\"jax version: \", jax.__version__)\nimport jax.experimental.optimizers as optimizers\nimport jax.experimental.stax as stax\nimport jax.numpy as np\nfrom jax import jit\nimport matplotlib.pyplot as plt\nimport scipy\n\nimport imnn\nprint(\"IMNN version: \", imnn.__version__)\n\nfrom imnn.imnn import (\n    AggregatedGradientIMNN,\n    AggregatedNumericalGradientIMNN,\n    AggregatedSimulatorIMNN,\n    GradientIMNN,\n    NumericalGradientIMNN,\n    SimulatorIMNN,\n)\nfrom imnn.lfi import (\n    ApproximateBayesianComputation,\n    GaussianApproximation,\n)\nfrom imnn.utils import value_and_jacrev, value_and_jacfwd\n\nrng = jax.random.PRNGKey(0)\n\n```\n\n    jax version:  0.2.10\n    IMNN version:  0.3dev\n\n\n\n```python\n!XLA_FLAGS=--xla_cpu_enable_fast_math=false\n```\n\n\n```python\nfrom jax.lib import xla_bridge\nprint(xla_bridge.get_backend().platform)\n```\n\n    gpu\n\n\n# Model in STAX\n\n\n```python\nn_summaries = 2\nn_s = 5000\nn_d = 5000\n\u03bb = 100.0\n\u03f5 = 0.1\n```\n\n\n```python\n# define inception block layer\n\ndef InceptBlock2(filters, strides, do_5x5=True, do_3x3=True):\n    \"\"\"InceptNet convolutional striding block.\n    filters: tuple: (f1,f2,f3)\n    filters1: for conv1x1\n    filters2: for conv1x1,conv3x3\n    filters3L for conv1x1,conv5x5\"\"\"\n    \n    filters1, filters2, filters3 = filters\n    \n    conv1x1 = stax.serial(stax.Conv(filters1, (1,1), strides, padding=\"SAME\"))\n    \n    filters4 = filters2\n    conv3x3 = stax.serial(stax.Conv(filters2, (1,1), strides=None, padding=\"SAME\"),\n                        stax.Conv(filters4, (3,3), strides, padding=\"SAME\"))\n                        \n    filters5 = filters3\n    conv5x5 = stax.serial(stax.Conv(filters3, (1,1), strides=None, padding=\"SAME\"),\n                         stax.Conv(filters5, (5,5), strides, padding=\"SAME\")) \n    \n    maxpool = stax.serial(stax.MaxPool((3,3), padding=\"SAME\"),\n                         stax.Conv(filters4, (1,1), strides, padding=\"SAME\"))\n                            \n    if do_3x3:\n        if do_5x5:\n            return stax.serial(\n                  stax.FanOut(4),  # should num=3 or 2 here ?\n                  stax.parallel(conv1x1, conv3x3, conv5x5, maxpool),\n                  stax.FanInConcat(), \n                  stax.LeakyRelu)\n        else:\n            return stax.serial(\n                  stax.FanOut(3),  # should num=3 or 2 here ?\n                  stax.parallel(conv1x1, conv3x3, maxpool),\n                  stax.FanInConcat(), \n                  stax.LeakyRelu)\n            \n    else:\n        return stax.serial(\n              stax.FanOut(2),  # should num=3 or 2 here ?\n              stax.parallel(conv1x1, maxpool),\n              stax.FanInConcat(), \n              stax.LeakyRelu)\n    \n    \ndef Reshape(newshape):\n    \"\"\"Layer function for a reshape layer.\"\"\"\n    init_fun = lambda rng, input_shape: (newshape,())\n    apply_fun = lambda params, inputs, **kwargs: np.reshape(inputs,newshape)\n    return init_fun, apply_fun    \n\n```\n\n\n```python\nrng,drop_rng = jax.random.split(rng)\nfs = 32 #for 128x128 sims\n               \n\nmodel = stax.serial(\n        InceptBlock2((fs,fs,fs), strides=(4,4)),\n        InceptBlock2((fs,fs,fs), strides=(4,4)),\n        InceptBlock2((fs,fs,fs), strides=(2,2), do_5x5=False, do_3x3=False),\n        stax.Conv(n_summaries, (1,1), strides=(1,1), padding=\"SAME\"),\n        stax.Flatten,\n        Reshape((n_summaries,))\n)\n```\n\n\n```python\noptimiser = optimizers.adam(step_size=1e-3)\n```\n\n# Random seeds for IMNN\n\n\n```python\nrng, initial_model_key = jax.random.split(rng)\nrng, fitting_key = jax.random.split(rng)\n```\n\n# Random seeds for ABC\n\n\n```python\nrng, abc_key = jax.random.split(rng)\n```\n\n# 2D Gaussian Field Simulator in JAX\n\nSteps to creating $(N \\times N)$ 2D Gaussian field for IMNN:\n1. Generate a $(N\\times N)$ white noise field $\\varphi$ such that $\\langle \\varphi_k \\varphi_{-k} \\rangle' = 1$\n2. Fourier Transform $\\varphi$ to real space: $R_{\\rm white}(\\textbf{x}) \\rightarrow R_{\\rm white}(\\textbf{k})$\n    - note: NumPy's DFT Fourier convention is:\n    $$\\phi_{ab}^{\\textbf{k}} = \\sum_{c,d = 0}^{N-1} \\exp{(-i x_c k_a - i x_d k_b) \\phi^{\\textbf{x}}_{cd}}$$\n    $$\\phi_{ab}^{\\textbf{x}} = \\frac{1}{N^2}\\sum_{c,d = 0}^{N-1} \\exp{(-i x_c k_a - i x_d k_b) \\phi^{\\textbf{k}}_{cd}}$$    \n3. Scale white noise $R_{\\rm white}(\\textbf{k})$ by the chosen power spectrum evaluated over a field of $k$ values:\n$$ R_P(\\textbf{k}) = P^{1/2}(k) R_{\\rm white}(\\textbf{k}) $$\n    - note: here we need to ensure that this array of amplitudes is Hermitian, e.g. $\\phi^{* \\textbf{k}}_{a(N/2 + b)} = \\phi^{\\textbf{k}}_{a(N/2 - b)}$. This is accomplished by choosing indexes $k_a = k_b = \\frac{2\\pi}{N} (0, \\dots, N/2, -N/2+1, \\dots, -1)$ and then evaluating the square root of the outer product of the meshgrid between the two: $k = \\sqrt{k^2_a + k^2_b}$. We can then evaluate $P^{1/2}(k)$.\n    \n4. Fourier Transform $R_{P}(\\textbf{k})$ to real space: $ R_P(\\textbf{x}) = \\int d^d \\tilde{k} e^{i\\textbf{k} \\cdot \\textbf{x}} R_p(\\textbf{k}) $:\n\n$$R_{ab}^{\\textbf{x}} = \\frac{1}{N^2}\\sum_{c,d = 0}^{N-1} \\exp{(-i x_c k_a - i x_d k_b) R^{\\textbf{k}}_{cd}}$$\n\n\n```python\n# SET 32-BiT floats for model !\n\u03b8_fid = np.array([1.0, 0.5], dtype=np.float32)\n\u03b4\u03b8 = np.array([0.1, 0.1], dtype=np.float32)\nn_params = 2\nN = 32\ndim = 2\nL = 32\n\nfield_shape = (N,N)\ninput_shape = (1,1, N,N)\nsimulator_args = {\"N\": N, \"L\": L, \"dim\": dim, \"shape\": field_shape, 'vol_norm': False, \"N_scale\": True, \"squeeze\": False}\n```\n\n# simulator class for a Powerbox in Jax\nAttributes:\n- simulator for Gaussian fields from input power spectrum\n- analytic Fisher information computation at a given $\\theta$\n\n\n```python\nrng,fg_key = jax.random.split(rng)\nforegrounds = jax.random.normal(fg_key, (1000, 1,) + simulator_args['shape'])*0\n\n\ndef default_P(k, A, B):\n    return A*k**-B\n\n\nclass powerBoxJax:\n    def __init__(self, shape, pk=None, k=None):\n        \n        if pk is None:\n            self.pk = default_P\n        else:\n            self.pk = pk\n            \n        if k is None:\n            self.k = np.sqrt(np.sum(np.array(np.meshgrid(*(\n                (np.hstack((np.arange(0, _shape//2 + 1), \n                    np.arange(-_shape//2 + 1, 0))) * 2*np.pi / _shape)**2\n                    for _shape in shape))), axis=0))\n        else:\n            self.k = k\n            \n        self.shape = shape\n        self.N = shape[0]\n        \n    def simulator(self, rng, \u03b8, simulator_args=simulator_args, add_foregrounds=False):\n        def P(k, A=1, B=1):\n            return self.pk(k, A, B)\n\n        def fn(key, A, B):\n            shape = self.shape #simulator_args[\"shape\"]\n\n            k = self.k\n\n            new_shape = ()\n            for _shape in shape:\n                if _shape % 2 == 0:\n                    new_shape += (_shape+1,)\n                else:\n                    new_shape += (_shape,)\n\n\n            key1,key2 = jax.random.split(key)\n    \n            if add_foregrounds:\n                foreground = foregrounds[jax.random.randint(key2, \n                                            minval=0, maxval=1000, shape=())]\n            else:\n                foreground = 0.\n\n            # L is in length units, like Gpc\n            L = simulator_args['L']\n            dim = simulator_args['dim']\n\n            if np.isscalar(L):\n                L = [L]*int(dim)\n\n            else:\n                L = np.array(L)\n\n\n            V = np.prod(np.array(L))\n\n            scale = V**(1./dim)\n\n            Lk = ()\n\n            _N = 1\n            for i,_shape in enumerate(shape):\n                _N *= _shape\n                Lk += (_shape / L[i],) # 1 / dx\n\n\n            fft_norm = np.prod(np.array(Lk))\n\n            _dims = len(shape)\n            tpl = ()\n            for _d in range(_dims):\n                tpl += (_d,)\n\n            # POWERBOX IMPLEMENTATION\n\n            mag = jax.random.normal(key1, shape=tuple(N for N in new_shape))\n            \n            # random phases\n            pha = 2 * np.pi * jax.random.uniform(key1, shape=tuple(N for N in new_shape))\n            \n            # now make hermitian field (reality condition)\n            revidx = (slice(None, None, -1),) * len(mag.shape)\n            mag = (mag + mag[revidx]) / np.sqrt(2) \n            pha = (pha - pha[revidx]) / 2 + np.pi\n            dk = mag * (np.cos(pha) + 1j * np.sin(pha)) # output is complex\n\n            cutidx = (slice(None, -1),) * len(new_shape)\n\n            dk = dk[cutidx]\n            powers = np.concatenate((np.zeros(1), \n                        np.sqrt(P(k.flatten()[1:], A=A, B=B)))).reshape(k.shape)\n\n            # normalize power by volume\n            if simulator_args['vol_norm']:\n                powers = powers/V\n\n            fourier_field = powers * dk\n\n            fourier_field = jax.ops.index_update(\n                fourier_field,\n                np.zeros(len(shape), dtype=int),\n                np.zeros((1,)))\n            \n            field = np.real(np.fft.ifftn(fourier_field) * fft_norm * V)\n            \n            if simulator_args[\"N_scale\"]:\n                field *= scale\n\n            field = np.expand_dims(field + foreground, (0,))\n\n\n            if not simulator_args[\"squeeze\"]:\n                field = np.expand_dims(field, (0,))\n\n            return np.array(field, dtype='float32')\n\n        shape = self.shape\n        A, B = \u03b8\n\n\n        if A.shape == B.shape:\n            if len(A.shape) == 0:\n                return fn(rng, A, B)\n            else:\n                keys = jax.random.split(rng, num=A.shape[0] + 1)\n                rng = keys[0]\n                keys = keys[1:]\n                return jax.vmap(\n                    lambda key, A, B: simulator(key, (A, B), simulator_args=simulator_args)\n                )(keys, A, B)\n        else:\n            if len(A.shape) > 0:\n                keys = jax.random.split(rng, num=A.shape[0] + 1)\n                rng = keys[0]\n                keys = keys[1:]\n                return jax.vmap(\n                    lambda key, A: simulator(key, (A, B), simulator_args=simulator_args)\n                )(keys, A)\n            elif len(B.shape) > 0:\n                keys = jax.random.split(rng, num=B.shape[0])\n                return jax.vmap(\n                    lambda key, B: simulator(key, (A, B), simulator_args=simulator_args)\n                )(keys, B)\n\n\n\n    def AnalyticFisher(self, \n               \u03b8, \n               kvec=None,\n               N=None\n              ):\n        \"\"\"\n        Code for computing the Analytic Fisher for a Gaussian\n        Field with power spectrum P(k) = Ak^-B\n        \"\"\"\n        A,B = \u03b8\n        if N is None:\n            N = self.N\n        \n        # we want all UNIQUE fourier modes\n        if kvec is None:\n            kvec = self.k[1:N//2, 1:N//2]\n\n        pk = lambda k : A*(k**-B)             # P(k) = Ak^(-B)\n        p_a = lambda k : k**-B                # deriv w.r.t. A\n        p_b = lambda k : -A*(k**-B)*np.log(k) # deriv w.r.t. B\n\n\n        powers = (pk(kvec.flatten()[:]))#np.concatenate((np.ones(1), \n            \n\n        powera =  (p_a(kvec.flatten()[:])) #np.concatenate((np.zeros(1), \n           \n\n        powerb = (p_b(kvec.flatten()[:])) #np.concatenate((np.zeros(1), \n            \n\n\n        Cinv = np.diag(1. / powers)          # diagonal inv. covariance\n        Ca =  np.diag(powera / 1.)           # C_{,A}\n        Cb =  np.diag(powerb / 1.)           # C_{,B}\n\n        Faa = 0.5 * np.trace((Ca @ Cinv @ Ca @ Cinv))\n        Fab = 0.5 * np.trace((Ca @ Cinv @ Cb @ Cinv))\n        Fba = 0.5 * np.trace((Cb @ Cinv @ Ca @ Cinv))\n        Fbb = 0.5 * np.trace((Cb @ Cinv @ Cb @ Cinv))\n\n        return np.array([[Faa, Fab], [Fba, Fbb]])\n\n\n```\n\n# analytic likelihood class\n- return the log-likelihood (computed on a grid) for power spectrum parameters for Gaussian Fields\n- takes in a PowerboxJax simulator object `PBJ` and fourier-transformed field target data `\u0394_target`\nmethods:\n- `get_likelihood`: return likelihood marginal on a grid\n- `plot_contours`: plot likelihood contours on a meshgrid\n- `plot_corner`: plot liklihood contours, target crosshairs, and image data on a 2x2 corner plot\n\n\n```python\nclass analyticFieldLikelihood:\n\n    def __init__(self,\n                 PBJ, \n                 field_shape,\n                 \u0394_target,\n                 prior,\n                 k=None,\n                 pk=None,\n                 gridsize=20, \n                 tiling=2):\n\n        \"\"\"code for computing a gaussian field's likelihood for power spectrum parameters\n            PBJ :         powerBox simulator object\n            field_shape : list. shape of field input\n            \u0394 :           array-like. FFT of the real-space field\n            prior :       array-like. range over which to compute the likelihood\n            k :           array-like. fourier modes over which to compute P(k)\n            tiling :      list or int. tiling=2 means likelihood will be computed as 2x2 grid\n            gridsize :    how large to make the likelihood surface\n        \"\"\"\n        \n        \n        if k is None:\n            self.k = PBJ.k\n\n        if pk is None:\n            self.pk = PBJ.pk\n\n        self.field_shape = field_shape\n        self.gridsize = gridsize\n        if np.isscalar(tiling):\n            self.tiling = [tiling]*2\n        else:\n            self.tiling = tiling    \n        #self.tilesize = gridsize // tiling\n        self.N = np.sqrt(np.prod(np.array(field_shape)))  # should just be N for NxN grid\n        self.prior = prior\n\n        self.k = k\n        self.\u0394 = \u0394_target\n\n    def Pk(self, k, A=1, B=0.5):\n        return self.pk(k, A, B)\n\n\n        return np.diag(pk)\n    def log_likelihood(self, k, A, B, \u0394):\n        \u0394 = \u0394.flatten()[:]\n        k = k\n\n        dlength = len(k.flatten())\n\n        def fn(_A, _B):\n\n            nrm = np.pad(np.ones(dlength-2)*2, (1,1), constant_values=1.)\n            nrm = jax.ops.index_update(\n              nrm, np.array([[0],[(dlength-2)]]), np.array([[1],[1]]))\n            nrm = 1\n\n            powers = self.Pk(k.flatten()[:], A=_A, B=_B)\n\n            # covariance is P(k)\n            C = powers * nrm\n            invC = 1./self.Pk(k.flatten()[:], A=_A, B=_B)\n\n            logdetC = np.sum(np.log(C))\n            pi2 = np.pi * 2.\n            m_half_size = -0.5 * len(\u0394)\n            exponent = - 0.5 * np.sum(np.conj(\u0394) * invC * \u0394)\n            norm = -0.5 * logdetC + m_half_size*np.log(pi2) \n            return (exponent + norm)\n        return jax.vmap(fn)(A, B)\n\n    def get_likelihood(self, return_grid=False, shift=None):\n        A_start = self.prior[0][0]\n        A_end = self.prior[1][0]\n        B_start = self.prior[0][1]\n        B_end = self.prior[1][1]\n\n        region_size = [self.gridsize // self.tiling[i] for i in range(len(self.tiling))]\n\n        print(\"computing likelihood on a %dx%d grid \\n \\\n        in tiles of size %dx%d\"%(self.gridsize, self.gridsize, region_size[0], region_size[1]))\n\n\n        def get_like_region(A0, A1, B0, B1, qsize):\n            A_range = np.linspace(A0, A1, qsize)\n            B_range = np.linspace(B0, B1, qsize)\n            A, B = np.meshgrid(A_range, B_range)\n\n            return (self.log_likelihood(self.k,\n                A.ravel(), B.ravel(), self.\u0394).reshape(qsize,qsize))\n\n\n\n        A_incr = (A_end - A_start) / self.tiling[0]\n        B_incr = (B_end - B_start) / self.tiling[1]\n\n        # marks the ends of linspace\n        A_starts = [A_start + (i)*A_incr for i in range(self.tiling[0])]\n        A_ends = [A_start + (i+1)*A_incr for i in range(self.tiling[0])]\n        B_starts = [B_start + (i)*B_incr for i in range(self.tiling[1])]\n        B_ends = [B_start + (i+1)*B_incr for i in range(self.tiling[1])]\n\n        _like_cols = []\n        for _col in range(self.tiling[0]):\n            # slide horizontally in A\n            _like_row = []\n            for _row in range(self.tiling[1]):\n                # slide vertically in B\n\n                _like = get_like_region(A_starts[_row], \n                                        A_ends[_row], \n                                        B_starts[_col], \n                                        B_ends[_col],\n                                        region_size[0],\n                                        )\n                _like_row.append(_like)\n\n            _like_cols.append(np.concatenate(_like_row, axis=1))\n\n        _log_likelihood = np.real(np.concatenate(_like_cols, axis=0))\n\n        if shift is None:\n            shift = np.max(_log_likelihood)\n\n        #print('shift', shift)\n        print('loglike mean', np.mean(_log_likelihood))\n\n        #_log_likelihood = _log_likelihood - shift\n\n        if return_grid:\n            _A_range = np.linspace(self.prior[0,0], self.prior[1,0], self.gridsize)\n            _B_range = np.linspace(self.prior[0,0], self.prior[1,0], self.gridsize)\n            return (_log_likelihood), _A_range, _B_range\n\n        return (_log_likelihood)\n\n\n\n    def plot_contours(self, ax=None, \n                      \u03b8_ref=None, shift=None, \n                      xlabel='A', ylabel='B', \n                      return_like=True):\n\n        _like, _A, _B = self.get_likelihood(return_grid=True, shift=shift)\n        _like = scipy.special.softmax(np.real(_like))\n\n        _A, _B = np.meshgrid(_A, _B)\n\n        if ax is None:\n            fig,ax = plt.subplots(figsize=(10,10))\n\n        mesh = ax.contourf(_A, _B, _like)\n        plt.colorbar(mesh, ax=ax)\n\n        if \u03b8_ref is not None:\n            ax.scatter(\u03b8_ref[0], \u03b8_ref[1], zorder=10, marker='+', s=100, color='r')\n\n        ax.set_xlabel('A')\n        ax.set_ylabel('B')\n\n        if return_like:\n            return _like, ax\n\n        else:\n            return ax\n        \n\n    def plot_corner(self, ax=None, \u03b8_ref=None, label=\"Analytic likelihood\", \n                    image_data=None, return_like=False, color=None):\n\n        _like, _A_range, _B_range = self.get_likelihood(return_grid=True)\n\n        likelihoodA = scipy.special.softmax(np.real(_like)).sum(0) #np.real(likelihood).sum(0)\n        likelihoodA /= likelihoodA.sum() * (_A_range[1] -  _A_range[0])\n        likelihoodB =  scipy.special.softmax(np.real(_like)).sum(1) #np.real(likelihood).sum(1)\n        likelihoodB /= likelihoodB.sum() * (_B_range[1] -  _B_range[0])\n\n        _like = scipy.special.softmax(np.real(_like))\n        sorted_marginal = np.sort(_like.flatten())[::-1]\n        cdf = np.cumsum(sorted_marginal / sorted_marginal.sum())\n        value = []\n        for level in [0.997, 0.95, 0.68]:\n            this_value = sorted_marginal[np.argmin(np.abs(cdf - level))]\n            if len(value) == 0:\n                value.append(this_value)\n            elif this_value <= value[-1]:\n                break\n            else:\n                value.append(this_value)\n\n        if ax is None:\n            fig,ax = plt.subplots(nrows=2, ncols=2)\n            \n        if color is None:\n            color = 'C2'\n\n        ax[1,0].contour(_A_range, _B_range, _like, levels=value, colors=color, alpha=0.7)\n        ax[0,0].plot(_A_range, likelihoodA, color=color, label=None, alpha=0.7)\n        ax[1,1].plot(likelihoodB, _B_range, color=color, label='loglike', alpha=0.7)\n        \n        if image_data is not None:\n            ax[0,1].imshow(np.squeeze(image_data))\n        else:\n            ax[0,1].axis(\"off\")\n\n        if \u03b8_ref is not None:\n            ax[0,0].axvline(\u03b8_ref[0], linestyle='--', c='k')\n            ax[1,0].axvline(\u03b8_ref[0], linestyle='--', c='k')\n            ax[1,0].axhline(\u03b8_ref[1], linestyle='--', c='k')\n            ax[1,1].axhline(\u03b8_ref[1], linestyle='--', c='k', label=r'$\\theta_{\\rm ref}$')\n\n        ax[1,0].set_xlabel(r'$A$')\n        ax[1,0].set_ylabel(r'$B$')\n        \n        if return_like:\n            return ax,_like\n\n        else:\n            return ax\n```\n\n\n```python\nPBJ = powerBoxJax(simulator_args['shape'])\nsimulator = PBJ.simulator\n```\n\n## sim and gradient\n\n\n```python\ndef simulator_gradient(rng, \u03b8, simulator_args=simulator_args):\n    return value_and_jacrev(simulator, argnums=1, allow_int=True, holomorphic=True)(rng, \u03b8, simulator_args=simulator_args)\n```\n\n\n```python\nrng, key = jax.random.split(rng)\n```\n\n\n```python\nfield_shape\n```\n\n\n\n\n    (32, 32)\n\n\n\n\n```python\n# plot example simulation and derivative\nderiv_args = {\"N\": N, \"L\": L, \"dim\": dim, \"shape\": field_shape, \"vol_norm\": True, \"N_scale\": True, \"squeeze\": False}\nsimulation, simulation_gradient = value_and_jacfwd(simulator, argnums=1)(rng, \u03b8_fid, simulator_args=deriv_args)\n\nplt.imshow(np.squeeze(simulation[0]), extent=(0,1,0,1))\nplt.colorbar()\nplt.title('example simulation')\nplt.show()\n\nplt.imshow(np.squeeze(simulation_gradient[0].T[0].T), extent=(0,1,0,1))\nplt.title('gradient of simulation')\nplt.colorbar()\nplt.show()\n```\n\n\n```python\ndef get_simulations(rng, n_s, \u03b8, simulator_args=simulator_args):\n    def get_simulator(key):\n        return simulator(key, \u03b8, simulator_args=simulator_args)\n\n    keys = jax.random.split(rng, num=n_s)\n    return jax.vmap(get_simulator)(np.array(keys))\n\n\ndef get_simulation_gradients(rng, n_s, n_d, \u03b8, simulator_args=simulator_args):\n    def get_batch_gradient(key):\n        return simulator_gradient(key, \u03b8, simulator_args=simulator_args)\n\n    keys = jax.random.split(rng, num=n_s)\n    return jax.vmap(get_batch_gradient)(np.array(keys)[:n_d])\n```\n\n# known analytic Fisher information\n\nFor a gaussian field, the likelihood is written\n$$     \\mathcal{L}(\\Delta | \\theta) = \\frac{1}{(2\\pi)^{N_p / 2} \\det(C)^{1/2}}\\exp{\\left(-\\frac{1}{2} \\Delta C^{-1} \\Delta \\right)}$$\n\nWhere $\\Delta \\in \\mathbb{R}^{N_p},\\ N_p=N_k=V=N\\times N$ is the Fourier Transform of the observed real-space field.\nThis yields a Fisher information matrix of\n\n$$F_{\\alpha \\beta} = \\langle -\\frac{\\partial^2 \\ln \\mathcal{L}}{\\partial \\lambda_\\alpha \\partial \\lambda_\\beta} \\rangle= \\frac{1}{2} {\\rm Tr} (C_{, \\alpha} C^{-1} C_{, \\beta} C^{-1}) $$\nwhere the covariance is\n$$ C_{k_i, k_j} =  P(k_i)\\delta_{ij}$$\nThe associated derivatives for a power law $P(k) = Ak^{-B}$ are\n$$\\begin{align}\n    C_{,A} &= \\left( k^{-B} \\right)\\delta_{ij} \\\\\n    C_{,B} &= \\left( -Ak^{-B}\\ln k \\right) \\delta_{ij}\n\\end{align} $$\n\nWe notice that the Fisher information is *only* a function of the power spectrum parameters. It tells us the curvature of the chosen model (likelihood function) at a given $\\theta$. The analytic Fisher information is the maximum amount of information we can expect the IMNN to extract from our simulations.\n\n\n<!-- Alternatively, we can explore a volume integral analytically from the definition of C :\nwhere the Fisher matrix is given by\n$$ F_{\\alpha \\beta} = \\sum_k \\frac{1}{(\\delta P_k)^2} \\frac{\\partial P_k}{\\partial \\lambda_\\alpha} \\frac{\\partial P_k}{\\partial \\lambda_\\beta}$$\nand the error on $P_k$ is given (for a square, 2D box) as\n$$ \\delta P_k = \\sqrt{\\frac{2}{k (\\Delta k) V} } \\left( P_k + \\frac{1}{\\bar{n}} \\right) $$ -->\n\n<!-- For a gaussian field, the likelihood is written\n$$ \\ln \\mathcal{L}(\\theta | \\vec{d}) = \\ln \\mathcal{L}(\\theta | \\Delta) = \\sqrt{\\frac{1}{2\\pi C}} \\exp{\\frac{-{\\Delta}^2}{2C}}$$\n\nwhere $\\vec{d} = \\Delta$ is the overdensity field (in a cosmological context this is the measured temperature or galaxy count in a sky survey). Given that the power spectrum describes the correlations at different scales $k$, we can define the correlation via the power spectrum $C = P(k) = Ak^{-B}$ to compute the log-likelihood. The Fisher information matrix, given as \n$$ F_{\\alpha \\beta} = \\langle - \\frac{\\partial^2 \\ln \\mathcal{L}}{\\partial \\theta_\\alpha \\partial \\theta_\\beta} \\rangle $$\ncan then be computed analytically for our likelihood:\n$$ F_{\\alpha \\beta} = \\sum_k \\frac{1}{(\\delta P_k)^2} \\frac{\\partial P_k}{\\partial \\theta_\\alpha} \\frac{\\partial P_k}{\\partial \\theta_\\beta} $$\n\nwhere $\\delta P_k = \\sqrt{\\frac{2}{4\\pi \\Delta k V k_{\\rm tot}^2}} (P_k + \\frac{1}{\\bar{n}})$ is the error on $P_k$ with survey volume $V$, sampling interval $\\Delta k$, and shot noise $1/\\bar{n}$. Using the fact that $d\\ln P_k = \\frac{d P_k}{P_k}$, we can rewrite the sum as an integral:\n$$ F_{\\alpha \\beta} = 2 \\pi \\left( \\frac{V_{\\rm eff}}{\\lambda^3} \\right) \\int_{k_{\\rm min}}^{k_{\\rm max}} d \\ln k  \\frac{\\partial \\ln P_k}{\\partial \\theta_\\alpha} \\frac{\\partial \\ln P_k}{\\partial \\theta_\\beta}$$\n\nWhere $V_{\\rm eff}$ and $\\lambda^3$ are our effective windowed survey size and survey extent, respectively (set to 1 for now). Doing the integration explicitly, we obtain the Fisher matrix for parameters $\\theta = (A, B)$:\n$$ F = 2 \\pi \\left( \\frac{V_{\\rm eff}}{\\lambda^3} \\right) \\begin{bmatrix}\n    \\frac{1}{A^2} \\ln (\\frac{k_{\\rm max}}{k_{\\rm min}}) & \\frac{1}{2A} ((\\ln k_{\\rm min})^2 - (\\ln k_{\\rm max})^2)  \\\\\n     \\frac{1}{2A} ((\\ln k_{\\rm min})^2 - (\\ln k_{\\rm max})^2) & \\frac{1}{3}((\\ln k_{\\rm max})^3 - (\\ln k_{\\rm min})^3)   \\\\\n\\end{bmatrix}$$\n -->\n\n\nFor our fiducial model with our data vector of size $128^2$, our $\\rm det|F|$ reads:\n\n\n```python\n\u03b8_fid\n```\n\n\n\n\n    DeviceArray([1. , 0.5], dtype=float32)\n\n\n\n\n```python\nN = simulator_args[\"N\"]\nshape = simulator_args[\"shape\"]\n\nkbin = np.sqrt(np.sum(np.array(np.meshgrid(*(\n    np.hstack((np.arange(0, _shape//2 + 1), \n        np.arange(-_shape//2 + 1, 0))) *2* np.pi / _shape\n        for _shape in shape)))**2, axis=0))\n\n\nf_expected = PBJ.AnalyticFisher(\u03b8_fid, kvec=None, N=N)\nprint(\"analytic F(\u03b8_fid): \", f_expected)\n\ndetf_expected = np.linalg.det(f_expected)\nprint(\"analytic det(F(\u03b8_fid)): \", detf_expected)\n```\n\n    analytic F(\u03b8_fid):  [[112.5        -88.08135241]\n     [-88.08135241  92.25651195]]\n    analytic det(F(\u03b8_fid)):  2620.5329515016588\n\n\n\n```python\n# MAKE SIMULATION\nN = simulator_args[\"N\"]\nshape = (N,N)\n\n\u03b8_sim = np.array([0.7, 0.8])\nsimulator_args = {\"N\": N, \"L\": L, \"dim\": dim, \"shape\": shape, \"vol_norm\": True, \"N_scale\": False, \"squeeze\": True}\nsimulator_args[\"shape\"] = (N,N)\nsimkey,rng = jax.random.split(rng)\n#sim = np.squeeze(target_data)#\nsim = np.squeeze(simulator(simkey, \u03b8_sim, simulator_args=simulator_args))\nsim_fft = (np.fft.fft2(sim)) #/ (N**2)\n```\n\n\n```python\n# PLOT ANALYTIC POSTERIOR\n# IGNORE FIRST FOURIER MODE -- no information here !\ngridsize = 100                # for likelihood gridding\n\u0394 = sim_fft[1:N//2, 1:N//2]\nk = kbin[1:N//2, 1:N//2]  \nprior_range = np.array([[0.1, 0.1], [1.25, 1.25]])\nAL = analyticFieldLikelihood(PBJ, shape, \u0394, prior_range, k=k, gridsize=gridsize, tiling=[5,5])\n```\n\n\n```python\n#plt.style.use('default')\nax = AL.plot_corner(\u03b8_ref=\u03b8_sim, image_data=sim)\n```\n\n\n```python\nsimulator_args\n```\n\n\n\n\n    {'N': 32,\n     'L': 32,\n     'dim': 2,\n     'shape': (32, 32),\n     'vol_norm': True,\n     'N_scale': False,\n     'squeeze': True}\n\n\n\n\n```python\ndef sanity_check(gridsize=50, num=20):\n    likes = []\n    likeAs = []\n    likeBs = []\n    rng1 = jax.random.PRNGKey(13)\n    values = []\n    \u03b8_target = np.array([0.8, 0.8], dtype=np.float32)\n\n    for t in range(num):\n        key, rng1 = jax.random.split(rng1)\n        targ = simulator(\n            key,\n            \u03b8_target)\n\n        gridsize = 50                # for likelihood gridding\n        \u0394 = np.fft.fftn(np.squeeze(targ))[1:N//2, 1:N//2] / N\n        k = kbin[1:N//2, 1:N//2]  \n        prior_range = np.array([[0.1, 0.1], [1.25, 1.25]])\n        AL = analyticFieldLikelihood(PBJ, shape, \u0394, prior_range, k=k, \n                                     gridsize=gridsize, tiling=[5,5])\n\n        likelihood,A_range,B_range = AL.get_likelihood(shift=None, return_grid=True)\n\n\n        _A_range = A_range#*np.exp(shift)\n        _B_range = B_range#*np.exp(shift)\n\n        likelihoodA = scipy.special.softmax(np.real(likelihood)).sum(0) #np.real(likelihood).sum(0)\n        likelihoodA /= likelihoodA.sum() * (_A_range[1] -  _A_range[0])\n        likelihoodB =  scipy.special.softmax(np.real(likelihood)).sum(1) #np.real(likelihood).sum(1)\n        likelihoodB /= likelihoodB.sum() * (_B_range[1] -  _B_range[0])\n\n        likelihood = scipy.special.softmax(np.real(likelihood))\n        sorted_marginal = np.sort(likelihood.flatten())[::-1]\n        cdf = np.cumsum(sorted_marginal / sorted_marginal.sum())\n        value = []\n        for level in [0.997, 0.95, 0.68]:\n            this_value = sorted_marginal[np.argmin(np.abs(cdf - level))]\n            if len(value) == 0:\n                value.append(this_value)\n            elif this_value <= value[-1]:\n                break\n            else:\n                value.append(this_value)\n        #fig, ax = plt.subplots(2, 2, figsize=(10, 10))\n\n        #likelihood /= likelihood.sum()\n\n        likes.append(likelihood)\n        likeAs.append(likelihoodA)\n        likeBs.append(likelihoodB)\n\n        values.append(value)\n        \n        return likes,likeAs,likeBs,values\n```\n\n\n```python\nlikes,likeAs,likeBs,values = sanity_check()\nfig,ax = plt.subplots(nrows=2, ncols=2)\n\nfor l,like in enumerate(likes):\n    ax[1,0].contour(A_range, B_range, like, levels=value, colors='#FF8D33', alpha=0.5)\n    ax[0, 0].plot(A_range, likeAs[l], color='#FF8D33', label=None, alpha=0.5)\n    ax[0, 1].axis(\"off\")\n    ax[1, 1].plot(likeBs[l], B_range, color='#FF8D33', label='loglike', alpha=0.5)\n    \nax[1,0].scatter(\u03b8_target[0], \u03b8_target[1], marker='+', s=50, color='blue', zorder=20)\nax[0,0].axvline(\u03b8_target[0], linestyle='--', c='k')\nax[1,0].axvline(\u03b8_target[0], linestyle='--', c='k')\nax[1,0].axhline(\u03b8_target[1], linestyle='--', c='k')\nax[1,1].axhline(\u03b8_target[1], linestyle='--', c='k', label=r'$\\theta_{\\rm target}$')\n\nax[1,0].set_xlabel(r'$A$')\nax[1,0].set_ylabel(r'$B$')\n```\n\n# Initialise IMNN\n\n\n```python\nsimulator_args[\"squeeze\"] = False\n```\n\n\n```python\nsimulator_args['vol_norm'] = True\nsimulator_args['N_scale'] = True # false \nsimulator_args['L'] = L\n```\n\n\n```python\nsimulator_args\n```\n\n\n\n\n    {'N': 32,\n     'L': 32,\n     'dim': 2,\n     'shape': (32, 32),\n     'vol_norm': True,\n     'N_scale': True,\n     'squeeze': False}\n\n\n\n\n```python\nIMNN = SimulatorIMNN(\n        n_s=5000,\n        n_d=5000,\n        n_params=n_params,\n        n_summaries=n_summaries,\n        input_shape=input_shape,\n        \u03b8_fid=\u03b8_fid,\n        model=model,\n        optimiser=optimiser,\n        key_or_state=initial_model_key,\n        simulator=lambda rng, \u03b8: simulator(rng, \u03b8, simulator_args=simulator_args),\n#         devices=[jax.devices()[0]],\n#         n_per_device=1000\n        )\n```\n\n# Fit\n\n\n```python\n# SAVING IMNN ATTRIBUTES\nimport cloudpickle as pickle\nimport os\n\ndef save_weights(IMNN, folder_name='./model', weights='final'):\n    \n    # create output directory\n    if not os.path.exists(folder_name): \n        os.mkdir(folder_name)\n    \n    def pckl_me(obj, path):\n        with open(path, 'wb') as file_pi:\n            pickle.dump(obj, file_pi)\n        file_pi.close()\n        \n    # save IMNN (optimiser) state:\n    savestate = jax.experimental.optimizers.unpack_optimizer_state(IMNN.state)\n    pckl_me(savestate, os.path.join(folder_name, 'IMNN_state'))\n    \n    # save weights\n    if weights == 'final':\n        np.save(os.path.join(folder_name, 'final_w'), IMNN.final_w)\n    \n    else:\n        np.save(os.path.join(folder_name, 'best_w'), IMNN.best_w)\n        \n    # save initial weights\n    np.save(os.path.join(folder_name, 'initial_w'), IMNN.initial_w)\n        \n    # save training history\n    pckl_me(IMNN.history, os.path.join(folder_name, 'history'))\n    \n    # save important attributes as a dict\n    imnn_attributes = {\n        'n_s': IMNN.n_s,\n        'n_d': IMNN.n_d,\n        'input_shape': IMNN.input_shape,\n        'n_params' : IMNN.n_params,            \n        'n_summaries': IMNN.n_summaries,\n        '\u03b8_fid': IMNN.\u03b8_fid,\n        'F': IMNN.F,   \n        'validate': IMNN.validate,\n        'simulate': IMNN.simulate,\n        \n    }\n    \n    pckl_me(imnn_attributes, os.path.join(folder_name, 'IMNN_attributes'))\n    \n    print('saved weights and attributes to the file ', folder_name)\n    \n    \ndef load_weights(IMNN, folder_name='./model', weights='final', load_attributes=True):\n    \n    \n    def unpckl_me(path):\n        file = open(path, 'rb')\n        return pickle.load(file)\n    \n    # load and assign weights\n    if weights=='final':\n        weights = np.load(os.path.join(folder_name, 'final_w.npy'),  allow_pickle=True)\n        IMNN.final_w = weights\n    else:\n        weights = np.load(os.path.join(folder_name, 'best_w.npy'),  allow_pickle=True)\n        IMNN.best_w = weights\n        \n    # re-pack and load the optimiser state\n    loadstate = unpckl_me(os.path.join(folder_name, 'IMNN_state'))\n    IMNN.state = jax.experimental.optimizers.pack_optimizer_state(loadstate)\n    \n    \n    # load history\n    IMNN.history = unpckl_me(os.path.join(folder_name, 'history'))\n    \n    # load important attributes\n    if load_attributes:\n        IMNN.intial_w =  np.load(os.path.join(folder_name, 'initial_w.npy'), allow_pickle=True)\n        attributes = unpckl_me(os.path.join('test_model', 'IMNN_attributes'))\n        IMNN.\u03b8_fid = attributes['\u03b8_fid']\n        IMNN.n_s = attributes['n_s']\n        IMNN.n_d = attributes['n_d']\n        IMNN.input_shape = attributes['input_shape']\n        \n    print('loaded IMNN with these attributes: ', attributes)\n    \n```\n\n\n```python\n# # test save functions\n# save_weights(IMNN, folder_name='./model')\n\n# # test load functions\n\n# # initialize a new imnn with different attributes and then load the old file\n# # to overwrite them\n\n# my_new_IMNN = SimIMNN(\n#         n_s=300,\n#         n_d=100,\n#         n_params=n_params,\n#         n_summaries=n_summaries,\n#         input_shape=input_shape,\n#         \u03b8_fid=np.array([1.0,1.0]),\n#         key=initial_model_key,\n#         model=model,\n#         optimiser=optimiser,\n#         simulator=lambda rng, \u03b8: simulator(rng, \u03b8, simulator_args=simulator_args),\n#         )\n\n# load_weights(my_new_IMNN, folder_name='./model', load_attributes=True)\n# my_new_IMNN.set_F_statistics(rng, my_new_IMNN.best_w, my_new_IMNN.\u03b8_fid, my_new_IMNN.n_s, my_new_IMNN.n_d, validate=True)\n```\n\n\n```python\n\u03b8_fid\n```\n\n\n\n\n    DeviceArray([1. , 0.5], dtype=float32)\n\n\n\n\n```python\n%%time\nfor i in range(1):\n    rng,fit_rng = jax.random.split(rng)\n    IMNN.fit(\u03bb=10., \u03f5=\u03f5, rng=fit_rng, min_iterations=500) #for IMNN, IMNN_rng in zip(IMNNs, IMNN_rngs);\n    \n#save_weights(IMNN, folder_name='./big_incept128')\n```\n\n    CPU times: user 2min, sys: 6.43 s, total: 2min 7s\n    Wall time: 2min 11s\n\n\n\n```python\nIMNNs = [IMNN]\n```\n\n\n```python\nlatexify(fig_width=3.37)\nplt.plot(IMNN.history['detF'][:])\nplt.plot(np.ones(len(IMNN.history['detF'][:]))*detf_expected, c='k', linestyle='--')\nplt.ylim(1e-2, 1e7)\nplt.ylabel(r'$\\det \\textbf{F}$')\nplt.xlabel('number of epochs')\nplt.yscale('log')\nplt.tight_layout()\n```\n\n\n```python\nnp.linalg.det(IMNNs[0].F) #/ (detf_expected)\n```\n\n\n\n\n    DeviceArray(4823.0605, dtype=float32)\n\n\n\n\n```python\nIMNNs[0].F\n```\n\n\n\n\n    DeviceArray([[ 169.01195, -124.12768],\n                 [-124.12768,  119.70005]], dtype=float32)\n\n\n\n\n```python\nprint('IMNN F:', IMNN.F)\n\nprint('IMNN det F:', np.linalg.det(IMNN.F))\n\nprint('IMNN F / analytic det F: ', (np.linalg.det(IMNN.F)) / detf_expected)\n```\n\n    IMNN F: [[ 169.01195 -124.12768]\n     [-124.12768  119.70005]]\n    IMNN det F: 4823.0605\n    IMNN F / analytic det F:  1.840488418247599\n\n\n# Data for ABC example\n\n\n```python\nclass uniform:\n    def __init__(self, low, high):\n        self.low = np.array(low)\n        self.high = np.array(high)\n        self.event_shape = [[] for i in range(self.low.shape[0])]\n    def sample(self, n=None, seed=None):\n        if n is None:\n            n = 1\n        keys = np.array(jax.random.split(\n            seed, \n            num=len(self.event_shape)))\n        return jax.vmap(\n            lambda key, low, high : jax.random.uniform(\n                key, \n                shape=(n,), \n                minval=low, \n                maxval=high))(\n            keys, self.low, self.high)\n\n```\n\n\n```python\nprior = uniform([0.05, 0.05], [2.0, 2.0])\n```\n\n\n```python\nsimulator_args\n```\n\n\n\n\n    {'N': 32,\n     'L': 32,\n     'dim': 2,\n     'shape': (32, 32),\n     'N_scale': True,\n     'vol_norm': True,\n     'squeeze': True}\n\n\n\n# generate multiple field targets\n\n\n```python\nsimulator_args = {\"N\": N, \"L\": L, \"dim\": dim, \"shape\": shape, \"N_scale\": True, \"vol_norm\": True, \"squeeze\": True}\n\ntarget_keys = jax.random.split(rng, num=2)\n\u03b8_targets = [np.array([0.9, 0.6]), \n             np.array([0.3, 1.0])]\n\ntargets = np.array([simulator(\n    target_keys[l],\n    \u03b8_targets[l],\n    simulator_args={**simulator_args, **{'squeeze':True}}) for l in range(2)])\n```\n\n\n```python\ntargets.shape\n```\n\n\n\n\n    (2, 1, 32, 32)\n\n\n\n\n```python\ntargets = np.expand_dims(np.expand_dims(targets,1),1)\ntargets.shape\n```\n\n\n\n\n    (2, 1, 1, 1, 32, 32)\n\n\n\n\n```python\n%matplotlib inline\nfig,ax = plt.subplots(nrows=1, ncols=2)\nax[0].imshow(np.squeeze(targets[0]))\nax[1].imshow(np.squeeze(targets[1]))\n```\n\n# analytic likelihood calculation\n\n\n```python\ngridsize = 100                # for likelihood gridding\nALs = []\nfor t,targ in enumerate(targets):\n    \u0394 = np.fft.fftn(np.squeeze(targ))[1:N//2, 1:N//2] / N\n    k = kbin[1:N//2, 1:N//2]  \n    prior_range = np.array([[0.01, 0.01], [1.5, 1.5]])\n    ALs.append(analyticFieldLikelihood(PBJ, shape, \u0394, prior_range, k=k, gridsize=gridsize, tiling=[5,5]))\n```\n\n\n```python\n\n```\n\n\n```python\n%%time\n%matplotlib inline\ncolors = new_colors\nfig,ax = plt.subplots(nrows=2, ncols=2)\n\nfor t,targ in enumerate(targets):\n    ax = ALs[t].plot_corner(ax=ax, \u03b8_ref=\u03b8_targets[t], image_data=targ, return_like=False, color=colors[t])\n    \n#latexify(fig_height=5.37)\nplt.show()\n```\n\n\n```python\ntarget_data.shape\n```\n\n\n\n\n    (1, 1, 1, 32, 32)\n\n\n\n# Gaussian approximation\n\n\n```python\n@jit #partial(jax.jit, static_argnums=0)\ndef get_estimate(d):\n    if len(d.shape) == 1:\n        return IMNN.\u03b8_fid + np.einsum(\n            \"ij,kj,kl,l->i\",\n            IMNN.invF,\n            IMNN.d\u03bc_d\u03b8,\n            IMNN.invC,\n            IMNN.model(IMNN.best_w, d, rng=rng) - IMNN.\u03bc)\n    else:\n        return IMNN.\u03b8_fid + np.einsum(\n            \"ij,kj,kl,ml->mi\",\n            IMNN.invF,\n            IMNN.d\u03bc_d\u03b8,\n            IMNN.invC,\n            IMNN.model(IMNN.best_w, d, rng=rng) - IMNN.\u03bc)\n```\n\n\n```python\nestimates = [IMNN.get_estimate(targ) for targ in targets] #[i.get_estimate(target_data) for i in IMNNs];\n```\n\n\n```python\nestimates\n```\n\n\n\n\n    [DeviceArray([[0.91767865, 0.66451627]], dtype=float32),\n     DeviceArray([[0.10112476, 0.7683722 ]], dtype=float32)]\n\n\n\n\n```python\nGAs = [GaussianApproximation(IMNN.get_estimate(targ), IMNN.invF, prior) for targ in targets]\n       #GaussianApproximation(get_estimate(target_data), np.linalg.inv(f_expected), prior)]\n```\n\n\n```python\n%matplotlib inline\nfor i, (GA, label) in enumerate(zip(GAs, ['target 1', 'target 2'])):\n    if i == 0:\n        ax = GA.marginal_plot(\n            axis_labels=[r\"$A$\", r\"$B$\"], label='on-the-fly IMNN', colours=\"C{}\".format(i)\n        )\n    else:\n        GA.marginal_plot(ax=ax, label='sim IMNN', colours=\"C{}\".format(i), ncol=8)\n```\n\n# ABC\n\n\n```python\n{**simulator_args, **{'squeeze':False}}\n```\n\n\n\n\n    {'N': 32,\n     'L': 32,\n     'dim': 2,\n     'shape': (32, 32),\n     'N_scale': True,\n     'vol_norm': True,\n     'squeeze': False}\n\n\n\n\n```python\nABCs = [ApproximateBayesianComputation(\n        targ, prior, \n     lambda A,B : simulator(A,B, simulator_args={**simulator_args, **{'squeeze':False}}), \n                                       IMNN.get_estimate, F=IMNN.F, gridsize=50\n    ) for targ in targets]\n```\n\n\n```python\n%%time\nrng,abc_key = jax.random.split(rng)\nfor ABC in ABCs:\n    ABC(rng=abc_key,\n            n_samples=int(1e3),\n            min_accepted=15000,\n            max_iterations=50000,\n            \u03f5=0.05,\n            smoothing=0.);\n```\n\n    1561 accepted in last  50000 iterations  (50000000 simulations done).\n    2068 accepted in last  50000 iterations  (50000000 simulations done).\n    CPU times: user 3min 14s, sys: 6.28 s, total: 3min 21s\n    Wall time: 3min 23s\n\n\n\n```python\nABC.parameters.accepted[0][0]\n```\n\n\n\n\n    DeviceArray([0.80957455, 0.32823556], dtype=float64)\n\n\n\n\n```python\n#np.save(\"accepted.npy\", ABC.parameters.accepted)\n```\n\n\n```python\nvalues = []\nlikes = []\nlikeAs = []\nlikeBs = []\n\nfor a,AL in enumerate(ALs):\n    likelihood, A_range, B_range = AL.get_likelihood(return_grid=True)\n\n    likelihoodA = scipy.special.softmax(np.real(likelihood)).sum(0) #np.real(likelihood).sum(0)\n    likelihoodA /= likelihoodA.sum() * (A_range[1] -  A_range[0])\n    likelihoodB =  scipy.special.softmax(np.real(likelihood)).sum(1) #np.real(likelihood).sum(1)\n    likelihoodB /= likelihoodB.sum() * (B_range[1] -  B_range[0])\n\n    likelihood = scipy.special.softmax(np.real(likelihood))\n    sorted_marginal = np.sort(likelihood.flatten())[::-1]\n    cdf = np.cumsum(sorted_marginal / sorted_marginal.sum())\n    value = []\n    for level in [0.997, 0.95, 0.68]:\n        this_value = sorted_marginal[np.argmin(np.abs(cdf - level))]\n        if len(value) == 0:\n            value.append(this_value)\n        elif this_value <= value[-1]:\n            break\n        else:\n            value.append(this_value)\n        \n    likes.append(likelihood)\n    likeAs.append(likelihoodA)\n    likeBs.append(likelihoodB)\n    values.append(value)\n```\n\n    computing likelihood on a 100x100 grid \n             in tiles of size 20x20\n    loglike mean -608.5116505829035\n    computing likelihood on a 100x100 grid \n             in tiles of size 20x20\n    loglike mean -178.67224149545186\n\n\n\n```python\n%matplotlib inline\n#plt.style.use('default')\nnew_colors = [ '#2c0342', '#286d87', '#4fb49d', '#9af486']\n#fig = plt.figure(constrained_layout=True, figsize=(3.41*1., 3.41*1.))\n#fig,ax = plt.subplots(nrows=2, ncols=2, figsize=(3.37*2, 3.37*2))\n#ax = fig.subplots(nrows=2, ncols=2)\nfig,ax = plt.subplots(nrows=2, ncols=3, figsize=(3.41*3., 3.41*2.), \n                      gridspec_kw={'height_ratios': [1, 1], 'width_ratios':[1,1,1]})\n\n#latexify(fig_width=5.41, fig_height=5.41)\n\n# just to fiddle with the label\nax[0,0].plot(0.3, 0., color=new_colors[0],\n           marker='o', label='ABC')\n\ncmap_reversed = matplotlib.cm.get_cmap('viridis_r')\n\nfor t,targ in enumerate(targets):\n    \n    # plot labels\n    if t == 1:\n        al_label = 'Analytic Likelihood'\n        ga_label = \"Gaussian Approximation\"\n        theta_lab = r'$\\theta_{\\rm fid}$'\n    else:\n        al_label = None\n        ga_label = None\n        theta_lab = None\n\n    ax[0,0].legend(framealpha=0.)\n    ax[0,t+1].imshow(np.squeeze(targ), cmap='viridis')\n\n\n#     ax[0,0].axvline(\u03b8_targets[t][0], linestyle='--', c='k')\n#     ax[1,0].axvline(\u03b8_targets[t][0], linestyle='--', c='k')\n#     ax[1,0].axhline(\u03b8_targets[t][1], linestyle='--', c='k')\n#     ax[1,1].axhline(\u03b8_targets[t][1], linestyle='--', c='k', label=r'$\\theta_{\\rm target, %d}$'%(t+1))\n\n    ax[1,0].set_xlabel(r'$A$')\n    ax[1,0].set_ylabel(r'$B$')\n\n    ax[0,0].axvline(\u03b8_fid[0], linestyle='--', c='k', alpha=0.4)\n    ax[1,0].axvline(\u03b8_fid[0], linestyle='--', c='k', alpha=0.4)\n    ax[1,0].axhline(\u03b8_fid[1], linestyle='--', c='k', alpha=0.4)\n    ax[1,1].axhline(\u03b8_fid[1], linestyle='--', c='k', alpha=0.4, label=theta_lab)\n\n    if t == 1:\n        ax[1,1].legend(framealpha=0.)\n        \n    ax = GAs[t].marginal_plot(ax=ax, colours='#00c133', #new_colors[1], \n                              axis_labels=[r\"$A$\", r\"$B$\"], label=ga_label, ncol=1,\n                                linestyle='solid')\n\n\n    # add in the likelihood estimate\n\n    ax[0, 0].plot(A_range, likeAs[t], color='#FF8D33', label=al_label, linestyle='--')\n    #ax[0,0].legend(framealpha=0.)\n    ax[0, 1].axis(\"off\")\n    ax[1, 0].contour(A_range, B_range, likes[t], levels=values[t], colors='#FF8D33', linestyles='--')\n    ax[1, 1].plot(likeBs[t], B_range, color='#FF8D33', label=al_label, linestyle='--')\n\n    # ax = ABC.scatter_plot(ax=ax,\n    #                       colours=new_colors[0], \n    #                       axis_labels=[r\"$A$\", r\"$B$\"], \n    #                       s=8,\n    #                       label='ABC', bbox_to_anchor=None)\n\n    # ABC scatter plots\n    ax[0,0].hist(ABCs[t].parameters.accepted[0][:, 0], color=new_colors[0], histtype='step', density=True)\n    ax[1,0].scatter(ABCs[t].parameters.accepted[0][:, 0], ABCs[t].parameters.accepted[0][:, 1], s=10, alpha=0.6,\n                    c=np.log(ABCs[t].distances.accepted[0]), cmap='Purples', edgecolors=None, linewidths=0, marker='.')\n\n    ax[1,1].hist(ABCs[t].parameters.accepted[0][:, 1], color=new_colors[0], \n                 histtype='step', density=True, orientation='horizontal')\n\n\n#ax[1,0].legend(framealpha=0.)\n\n\n\nax[0,0].set_xlim(0.05, 1.1)\n#ax[0,0].set_ylim(0., 10.1)\nax[1,0].set_xlim(0.05, 1.1)\nax[1,0].set_ylim(0.05, 1.25)\nax[1,1].set_ylim(0.05, 1.25)\n\nax[0,0].legend(framealpha=0., bbox_to_anchor=(0.75, 1.3), frameon=False)\n\n\nax[1,1].set_yticks([])\nax[1,1].set_xticks([])\nax[0,0].set_xticks([])\nax[0,0].set_yticks([])\nax[0,2].set_yticks([])\nax[0,2].set_xticks([])\n\nax[1, 2].axis(\"off\")\n\n#ax[0,0].set_ylabel(r'$\\mathit{P}(A|\\textbf{x})$')\n#ax[1,1].set_xlabel(r'$\\mathit{P}(B|\\textbf{x})$')\n\nplt.subplots_adjust(wspace=0.1, hspace=0.1)\n#plt.tight_layout()\nplt.savefig('/mnt/home/tmakinen/repositories/field-plots/32x32-double')\n#plt.subplots_adjust(wspace=0, hspace=0)\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "9ba344054e761f067e51b570a02c830edecb031c", "size": 398072, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "scratch/fields/32x32 - demo.ipynb", "max_stars_repo_name": "tlmakinen/kosmo-kompress", "max_stars_repo_head_hexsha": "2282e20d26dfc523e5705c0e02e0524b639df8a4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-07-16T05:22:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T12:41:06.000Z", "max_issues_repo_path": "scratch/fields/32x32 - demo.ipynb", "max_issues_repo_name": "tlmakinen/FieldIMNNs", "max_issues_repo_head_hexsha": "1b363559116136d276b7c085b56a80520a7b0830", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scratch/fields/32x32 - demo.ipynb", "max_forks_repo_name": "tlmakinen/FieldIMNNs", "max_forks_repo_head_hexsha": "1b363559116136d276b7c085b56a80520a7b0830", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 136.5598627787, "max_line_length": 99000, "alphanum_fraction": 0.8487936856, "converted": true, "num_tokens": 24040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368443773709, "lm_q2_score": 0.06656919591493472, "lm_q1q2_score": 0.02611754825800446}}
{"text": "```python\nfrom collections import Counter\nimport re\nregex=re.compile(\".*<units>(.*?)</units>\")\n\nunitlist = []\nwith open('units.txt') as f:\n    while True:\n        line = f.readline()\n        if line == '':\n            break\n        x = re.match(regex, line)\n        unitlist.append(x.group(1).strip())\nc = Counter(unitlist)\nulist = c.most_common()\n```\n\n\n```python\nval = \"/apps/youngsmoduluse/current/rappture/tool.xml:            <units>N</units>\"\nx = re.match(regex, val)\nprint(x, type(x))\n```\n\n\n```python\nthese_regex=\".*<units>(.+?)</units>\"\npattern=re.compile(these_regex)\nx = re.match(pattern, val)\nx.group(0)\n```\n\n\n```python\nfor name, count in ulist:\n    print(name)\n```\n\n\n```python\nlen(ulist)\n```\n\n\n```python\nfrom sympy import latex, sympify\nlatex(sympify('cm**2'))\n```\n\n\n```python\nimport ipywidgets as widgets\nx = widgets.FloatText(value=42)\nx\n```\n\n\n```python\ndef mycb(w):\n    print(\"MYCB\", w)\ndef mycb2(w):\n    print(\"MYCB2\", w)\n```\n\n\n```python\nx.observe(mycb, names='value')\n```\n\n\n```python\nx.observe(mycb2, names='value')\n```\n\n\n```python\nx.unobserve_all()\n```\n\n\n```python\nwidgets.Checkbox?\n```\n", "meta": {"hexsha": "b194d6950f007711be04e85d85f64b1ee55c2c0d", "size": 3077, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/unit_list.ipynb", "max_stars_repo_name": "hzclarksm/hublib", "max_stars_repo_head_hexsha": "e8f2168d80464b6343b980e30fdd552d1b0c2479", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-05-23T19:17:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T00:36:46.000Z", "max_issues_repo_path": "examples/unit_list.ipynb", "max_issues_repo_name": "hzclarksm/hublib", "max_issues_repo_head_hexsha": "e8f2168d80464b6343b980e30fdd552d1b0c2479", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-02-13T13:35:57.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-13T13:35:57.000Z", "max_forks_repo_path": "examples/unit_list.ipynb", "max_forks_repo_name": "hzclarksm/hublib", "max_forks_repo_head_hexsha": "e8f2168d80464b6343b980e30fdd552d1b0c2479", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-09-12T19:51:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-13T23:43:57.000Z", "avg_line_length": 19.3522012579, "max_line_length": 94, "alphanum_fraction": 0.4842378941, "converted": true, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.05340333243628599, "lm_q1q2_score": 0.026075960482101902}}
{"text": "# Arno's keyboard layout comparison\n\n[Arno Klein](https://binarybottle.com) wrote this keyboard layout comparison software principally to evaluate the [Engram layout](https://github.com/binarybottle/engram).\nAn article is under review (see the [preprint](https://www.preprints.org/manuscript/202103.0287/v1)).\n\n(c) 2021 Arno Klein, MIT license\n\n----------------\n\n# Contents\n1. [Summary](#Summary)\n2. [Scores based on the Engram scoring model](#Engram)\n3. [Carpalx scores](#CarpalX)\n4. [Keyboard Layout Analyzer scores](#KLAscores)\n5. [Keyboard Layout Analyzer data](#KLAdata) \n6. [Keyboard Layout Analyzer analysis of individual measures](#KLAmeasures)\n\n## Summary <a name=\"summary\">\n\n#### Engram Scoring Model scores (x100) for layouts, based on publicly available text data\n\n| Layout | Google bigrams | Alice | Romeo | Gita | Memento | 100K tweets | 20K tweets | MASC tweets | MASC spoken | COCA blogs | iweb | Monkey | Coder | Code |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Engram | 73.56 | 72.99 | 73.16 | 72.98 | 73.66 | 74.41 | 74.06 | 73.87 | 72.88 | 73.55 | 73.75 | 73.59 | 73.90 | 73.84 |\n| Halmak | 73.51 | 72.95 | 73.12 | 72.94 | 73.62 | 74.35 | 74.02 | 73.82 | 72.86 | 73.50 | 73.70 | 73.54 | 73.84 | 73.80 |\n| Hieamtsrn | 73.52 | 72.96 | 73.12 | 72.94 | 73.61 | 74.35 | 74.00 | 73.82 | 72.85 | 73.51 | 73.71 | 73.55 | 73.84 | 73.74 |\n| Colemak Mod-DH | 73.46 | 72.91 | 73.06 | 72.91 | 73.55 | 74.25 | 73.91 | 73.74 | 72.81 | 73.44 | 73.64 | 73.48 | 73.77 | 73.68 |\n| Norman | 73.43 | 72.90 | 73.04 | 72.89 | 73.54 | 74.22 | 73.90 | 73.72 | 72.79 | 73.42 | 73.60 | 73.45 | 73.73 | 73.68 |\n| Workman | 73.46 | 72.91 | 73.08 | 72.90 | 73.57 | 74.28 | 73.95 | 73.77 | 72.81 | 73.45 | 73.64 | 73.49 | 73.79 | 73.74 |\n| MTGap 2.0 | 73.44 | 72.91 | 73.06 | 72.89 | 73.55 | 74.24 | 73.92 | 73.74 | 72.80 | 73.43 | 73.62 | 73.47 | 73.77 | 73.69 |\n| QGMLWB | 73.41 | 72.87 | 73.02 | 72.86 | 73.52 | 74.21 | 73.89 | 73.70 | 72.78 | 73.40 | 73.59 | 73.44 | 73.73 | 73.64 |\n| Colemak | 73.44 | 72.88 | 73.04 | 72.88 | 73.52 | 74.23 | 73.89 | 73.73 | 72.79 | 73.42 | 73.62 | 73.46 | 73.75 | 73.70 |\n| Asset | 73.39 | 72.85 | 73.01 | 72.84 | 73.50 | 74.19 | 73.86 | 73.69 | 72.75 | 73.38 | 73.57 | 73.41 | 73.72 | 73.67 |\n| Capewell-Dvorak | 73.41 | 72.88 | 73.04 | 72.87 | 73.51 | 74.23 | 73.88 | 73.71 | 72.78 | 73.40 | 73.59 | 73.44 | 73.71 | 73.65 |\n| Klausler | 73.42 | 72.88 | 73.04 | 72.88 | 73.52 | 74.23 | 73.90 | 73.71 | 72.79 | 73.41 | 73.60 | 73.45 | 73.72 | 73.67 |\n| Dvorak | 73.41 | 72.88 | 73.04 | 72.86 | 73.51 | 74.22 | 73.89 | 73.70 | 72.79 | 73.40 | 73.59 | 73.44 | 73.70 | 73.67 |\n| QWERTY | 73.23 | 72.76 | 72.89 | 72.74 | 73.35 | 74.01 | 73.70 | 73.52 | 72.66 | 73.23 | 73.41 | 73.26 | 73.52 | 73.48 |\n    \n---\n    \n[Keyboard Layout Analyzer](http://patorjk.com/keyboard-layout-analyzer/) (KLA) scores for the same text sources:\n\n| Layout | Keyboard Layout Analyzer mean (SD) |  | CarpalX effort |\n| --- | --- | --- | --- |\n| Engram | 59.61 (6.17) |  |  |\n| Halmak | 58.65 (6.53) |  | 2.322 |\n| Hieamtsrn | 61.23 (7.60) |  | 1.948 |\n| Colemak Mod-DH | 58.63 (6.17) |  | 1.958 |\n| Norman | 55.35 (5.77) |  | 1.992 |\n| Workman | 57.78 (5.95) |  | 1.993 |\n| MTGAP 2.0 | 57.21 (6.66) |  | 1.981 |\n| QGMLWB | 57.96 (6.48) |  | 1.668 |\n| Colemak | 58.66 (6.17) |  | 1.842 |\n| Asset | 57.08 (5.87) |  | 1.894 |\n| Capewell-Dvorak | 58.92 (6.84) |  | 1.985 |\n| Klausler | 59.93 (7.13) |  | 1.867 |\n| Dvorak | 58.39 (6.69) |  | 2.098 |\n| QWERTY | 46.59 (4.46) |  | 3 |\n    \n---\n\n| Layout | Year | Website |\n| --- | --- | --- |\n| Engram | 2021 | https://engram.dev |\n| [Halmak 2.2](https://keyboard-design.com/letterlayout.html?layout=halmak-2-2.en.ansi) | 2016 | https://github.com/MadRabbit/halmak |\n| [Hieamtsrn](https://www.keyboard-design.com/letterlayout.html?layout=hieamtsrn.en.ansi) | 2014 | https://mathematicalmulticore.wordpress.com/the-keyboard-layout-project/#comment-4976 |\n| [Colemak Mod-DH](https://keyboard-design.com/letterlayout.html?layout=colemak-mod-DH-full.en.ansi) | 2014 | https://colemakmods.github.io/mod-dh/ | \n| [Norman](https://keyboard-design.com/letterlayout.html?layout=norman.en.ansi) | 2013 | https://normanlayout.info/ |\n| [Workman](https://keyboard-design.com/letterlayout.html?layout=workman.en.ansi) | 2010 | https://workmanlayout.org/ | \n| [MTGAP 2.0](https://www.keyboard-design.com/letterlayout.html?layout=mtgap-2-0.en.ansi) | 2010 | https://mathematicalmulticore.wordpress.com/2010/06/21/mtgaps-keyboard-layout-2-0/ |\n| [QGMLWB](https://keyboard-design.com/letterlayout.html?layout=qgmlwb.en.ansi) | 2009 | http://mkweb.bcgsc.ca/carpalx/?full_optimization | \n| [Colemak](https://keyboard-design.com/letterlayout.html?layout=colemak.en.ansi) | 2006 | https://colemak.com/ | \n| [Asset](https://keyboard-design.com/letterlayout.html?layout=asset.en.ansi) | 2006 | http://millikeys.sourceforge.net/asset/ | \n| Capewell-Dvorak | 2004 | http://michaelcapewell.com/projects/keyboard/layout_capewell-dvorak.htm |\n| [Klausler](https://www.keyboard-design.com/letterlayout.html?layout=klausler.en.ansi) | 2002 | https://web.archive.org/web/20031001163722/http://klausler.com/evolved.html |\n| [Dvorak](https://keyboard-design.com/letterlayout.html?layout=dvorak.en.ansi) | 1936 | https://en.wikipedia.org/wiki/Dvorak_keyboard_layout | \n| [QWERTY](https://keyboard-design.com/letterlayout.html?layout=qwerty.en.ansi) | 1873 | https://en.wikipedia.org/wiki/QWERTY |\n\n---\n\n| Text source | Information |\n| --- | --- |\n| \"Alice in Wonderland\" | Alice in Wonderland (Ch.1) |\n| \"Romeo and Juliet\" | [Romeo and Juliet](https://www.fulltextarchive.com/page/Romeo-and-Juliet1/) |\n| \"Bhagavad Gita\" | [Bhagavad Gita](https://www.gutenberg.org/files/2388/2388-h/2388-h.htm) |\n| \"Memento screenplay\" | [Memento screenplay](https://www.dailyscript.com/scripts/memento.html) |\n| \"100K tweets\" | 100,000 tweets from: [Sentiment140 dataset](https://data.world/data-society/twitter-user-data) training data |\n| \"20K tweets\" | 20,000 tweets from [Gender Classifier Data](https://www.kaggle.com/crowdflower/twitter-user-gender-classification) |\n| \"MASC tweets\" | [MASC](http://www.anc.org/data/masc/corpus/) tweets (cleaned of html markup) |\n| \"MASC spoken\" | [MASC](http://www.anc.org/data/masc/corpus/) spoken transcripts (phone and face-to-face: 25,783 words) |\n| \"COCA blogs\" | [Corpus of Contemporary American English](https://www.english-corpora.org/coca/) [blog samples](https://www.corpusdata.org/) |\n| \"Google website\" | [Google homepage](https://google.com) (accessed 10/20/2020) |\n| \"Software languages\" | \"Tower of Hanoi\" (programming languages A-Z from [Rosetta Code](https://rosettacode.org/wiki/Towers_of_Hanoi)) |\n| \"Monkey text\" | Ian Douglas's English-generated [monkey0-7.txt corpus](https://zenodo.org/record/4642460) |\n| \"Coder text\" | Ian Douglas's software-generated [coder0-7.txt corpus](https://zenodo.org/record/4642460) |\n| \"iweb cleaned corpus\" | First 150,000 lines of Shai Coleman's [iweb-corpus-samples-cleaned.txt](https://colemak.com/pub/corpus/iweb-corpus-samples-cleaned.txt.xz) |\n\nReference for Monkey and Coder texts:\nDouglas, Ian. (2021, March 28). Keyboard Layout Analysis: Creating the Corpus, Bigram Chains, and Shakespeare's Monkeys (Version 1.0.0). Zenodo. http://doi.org/10.5281/zenodo.4642460\n\n### Layouts\n\nEach layout is represented by a list of 32 characters in the following order:\n\n    1  2  3  4   25  28   13 14 15 16   31\n    5  6  7  8   26  29   17 18 19 20   32\n    9 10 11 12   27  30   21 22 23 24 \n\n\n```python\n# Layouts\nengram_letters = ['Q','U','O','X','D','I','E','S','G','K','Y','A','V','L','W','B','H','T','N','C','R','M','F','P', \"'\",',','-', '\"','.','?', 'Z','J']\nhalmak_letters  = ['W','L','R','B', 'S','H','N','T', 'F','M','V','C', 'Q','U','D','J', 'A','E','O','I', 'P','X','K','Y', 'Z',',','/', ';','.','G', '[',\"'\"]\nhieamtsrn_letters  = ['B','Y','O','U', 'H','I','E','A', 'X','-','\"','.', 'D','C','L','P', 'T','S','R','N', 'G','F','J','Z', \"'\",',','?', 'K','M','W', 'Q','V']\ncolemakModDH_letters = ['Q','W','F','P', 'A','R','S','T', 'Z','X','C','D', 'L','U','Y',';', 'N','E','I','O', 'H',',','.','/', 'B','J','G', 'K','V','M', '[',\"'\"]\nnorman_letters  = ['Q','W','D','F', 'A','S','E','T', 'Z','X','C','V', 'U','R','L',';', 'N','I','O','H', 'M',',','.','/', 'K','G','B', 'J','Y','P', '[',\"'\"]\nworkman_letters = ['Q','D','R','W', 'A','S','H','T', 'Z','X','M','C', 'F','U','P',';', 'N','E','O','I', 'L',',','.','/', 'B','G','V', 'J','Y','K', '[',\"'\"]\nmtgap2_letters  = [',','F','H','D', 'O','A','N','T', 'Q','X','B','P', 'C','U','L','.', 'S','E','R','I', 'W',\"'\",'V',';', \"K\",'G','Z', 'J','M','Y', '[','/'] # Michael Dickens 2010: https://mathematicalmulticore.wordpress.com/2010/06/21/mtgaps-keyboard-layout-2-0/ https://www.keyboard-design.com/letterlayout.html?layout=mtgap-2-0.en.ansi\nqgmlwb_letters  = ['Q','G','M','L', 'D','S','T','N', 'Z','X','C','F', 'Y','U','V',';', 'A','E','O','H', 'P',',','.','/', 'W','R','J', 'B','I','K', '[',\"'\"]\ncolemak_letters = ['Q','W','F','P', 'A','R','S','T', 'Z','X','C','V', 'L','U','Y',';', 'N','E','I','O', 'M',',','.','/', 'G','D','B', 'J','H','K', '[',\"'\"]\nasset_letters  = ['Q','W','J','F', 'A','S','E','T', 'Z','X','C','V', 'P','U','L',';', 'N','I','O','R', 'M',',','.','/', 'G','Y','D', 'H','B','K', '[',\"'\"] \ncapewell_letters  = [\"'\",',','.','P', 'O','A','E','I', 'Z','X','C','V', 'F','G','R','K', 'H','T','N','S', 'M','W','B',';', 'Y','Q','U', 'D','J','L', '/','-']\nklausler_letters  = ['K',',','U','Y', 'O','A','E','I', 'Q','.',\"'\",';', 'L','M','F','C', 'N','T','H','S', 'V','G','B','J', 'P','D','Z', 'W','R','X', '/',\"-\"]\ndvorak_letters  = [\"'\",',','.','P', 'A','O','E','U', ';','Q','J','K', 'G','C','R','L', 'H','T','N','S', 'M','W','V','Z', 'Y','F','I', 'D','X','B', '/','-']\nqwerty_letters  = ['Q','W','E','R', 'A','S','D','F', 'Z','X','C','V', 'U','I','O','P', 'J','K','L',';', 'M',',','.','/', 'T','G','B', 'Y','H','N', '[',\"'\"]\n#beakl_letters  = ['Q','H','O','U', 'Y','I','E','A', 'J','/',',','K', 'C','R','F','Z', 'S','T','N','B', 'M','L','P','V', 'X','.',\"'\", 'G','D','W', '',';']\n#balance12_letters  = ['P','L','C','D', 'N','R','S','T', 'Z','J','F','G', 'U','O','Y','K', 'A','E','I','H', '.','\"','-','X', 'W','M','B', \"'\",',','?', 'Q','V'] # Sasha Viminitz (2014): https://www.keyboard-design.com/letterlayout.html?layout=balance-twelve.en.ansi\n#vukeys_letters  = ['Q','C','D','M', 'N','S','T','R', 'Z','F','G','L', 'W','U','K',\"'\", 'I','E','O','A', 'P',',','.','/', 'V','H','X', 'J','Y','B', '[',\";\"] # ?\n\nlayout_names = ['Engram','Halmak','Hieamtsrn','Colemak Mod-DH',\n                'Norman','Workman','MTGap 2.0','QGMLWB','Colemak',\n                'Asset','Capewell-Dvorak','Klausler','Dvorak','QWERTY']\nlayout_abbrs = ['Engram','Halmak','Hieamtsrn','ColemakModDH',\n                'Norman','Workman','MTGap','QGMLWB','Colemak',\n                'Asset','CapewellDvorak','Klausler','Dvorak','QWERTY']\nlayout_letters = [engram_letters, halmak_letters, hieamtsrn_letters, colemakModDH_letters,\n                  norman_letters, workman_letters, mtgap2_letters, qgmlwb_letters, colemak_letters,  \n                  asset_letters, capewell_letters, klausler_letters, dvorak_letters, qwerty_letters]\n```\n\n\n```python\ntext_names = [\"Alice in Wonderland (Ch.1)\",\n              #\"Romeo and Juliet\",\n              #\"Bhagavad Gita\",\n              \"Memento screenplay\",\n              \"100,000 tweets (Sentiment Classification)\", \n              \"20,000 tweets (Gender classifier)\", \n              \"Manually Annotated Sub-Corpus tweets\",\n              \"Manually Annotated Sub-Corpus spoken transcripts\",\n              \"Corpus of Contemporary American English blog samples\",\n              \"Shai Coleman iweb corpus 1/6\",\n              \"Ian Douglas monkey test\",\n              \"Ian Douglas coder test\",\n              \"Tower of Hanoi (programming languages A-Z, Rosetta Code)\"]\n\n#text_abbrs = [\"Alice\", \"Romeo\", \"Gita\", \"Memento\", \"Tweets_100K\", \"Tweets_20K\", \"Tweets_MASC\", \n#             \"MASC_spoken\", \"COCA_blogs\", \"iweb\", \"Monkey\", \"Coder\", \"Rosetta\"]\ntext_abbrs = [\"Alice\", \"Memento\", \"Tweets_100K\", \"Tweets_20K\", \"Tweets_MASC\", \n              \"Spoken_MASC\", \"COCA_blogs\", \"iweb\", \"Monkey\", \"Coder\", \"Rosetta\"]\n\nurls = [\"https://raw.githubusercontent.com/binarybottle/text_data/main/AliceInWonderland_Ch1.txt\",\n        #\"https://raw.githubusercontent.com/binarybottle/text_data/main/Romeo_and_Juliet.txt\",\n        #\"https://raw.githubusercontent.com/binarybottle/text_data/main/Bhaghavad_Gita.txt\",\n        \"https://raw.githubusercontent.com/binarybottle/text_data/main/Memento_screenplay.txt\",\n        \"https://raw.githubusercontent.com/binarybottle/text_data/main/training.1600000.processed.noemoticon_1st100000tweets.txt\",\n        \"https://raw.githubusercontent.com/binarybottle/text_data/main/gender-classifier-tweet-column.txt\",\n        \"https://raw.githubusercontent.com/binarybottle/text_data/main/MASC_tweets_cleaned.txt\",\n        \"https://raw.githubusercontent.com/binarybottle/text_data/main/MASC_spoken_transcripts_of_phone_face2face.txt\",\n        \"https://raw.githubusercontent.com/binarybottle/text_data/main/COCA_corpusdata.org_sample_text_blog_cleaned.txt\",\n        \"https://raw.githubusercontent.com/binarybottle/text_data/main/iweb-corpus-cleaned-1.txt\",\n        \"https://raw.githubusercontent.com/binarybottle/text_data/main/monkey0-7_IanDouglas.txt\",\n        \"https://raw.githubusercontent.com/binarybottle/text_data/main/coder0-7_IanDouglas.txt\",\n        \"https://raw.githubusercontent.com/binarybottle/text_data/main/rosettacode.org_TowersOfHanoi_AtoZ.txt\"]\n```\n\n### Import dependencies and functions\n\n\n```python\n# Import dependencies\nimport xlrd\nimport numpy as np\nfrom sympy.utilities.iterables import multiset_permutations\nimport matplotlib\nimport matplotlib.pyplot as plt    \nimport seaborn as sns\n\n# Print .png figures and .txt text files\nprint_output = False # True\n\n# Apply strength data\napply_strength = True\nmin_strength_factor = 0.9\n\nletters24 = ['E','T','A','O','I','N','S','R','H','L','D','C','U','M','F','P','G','W','Y','B','V','K','X','J']\nkeys24 = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24]\ninstances24 = [4.45155E+11,3.30535E+11,2.86527E+11,2.72277E+11,2.69732E+11,2.57771E+11,\n               2.32083E+11,2.23768E+11,1.80075E+11,1.44999E+11,1.36018E+11,1.19156E+11,\n               97273082907,89506734085,85635440629,76112599849,66615316232,59712390260,\n               59331661972,52905544693,37532682260,19261229433,8369138754,5657910830]                        \n\n\ndef permute_optimize_keys(fixed_letters, fixed_letter_indices, open_letter_indices, \n                          all_letters, keys, data_matrix, bigrams, bigram_frequencies, \n                          verbose=False, ntop=0):\n    \"\"\"\n    Find all permutations of letters, optimize layout, and generate output.\n    \"\"\"\n    matrix_selected = select_keys(data_matrix, keys, verbose=False) \n    \n    unassigned_letters = []\n    for all_letter in all_letters:\n        if all_letter not in fixed_letters:\n            unassigned_letters.append(all_letter)\n            if len(unassigned_letters) == len(open_letter_indices):\n                break\n\n    letter_permutations = permute_letters(unassigned_letters, verbose)\n    top_permutation, scores = optimize_layout(matrix_selected, bigrams, bigram_frequencies, letter_permutations, open_letter_indices, fixed_letters, fixed_letter_indices, verbose)\n\n    if ntop > 0:\n        print_top_scores(letter_permutations, scores, ntop)\n    \n    return top_permutation, letter_permutations, scores\n\n\ndef permute_optimize(letters, all_letters, all_keys, data_matrix, bigrams, bigram_frequencies, verbose=False, ntop=0):\n    \"\"\"\n    Find all permutations of letters, optimize layout, and generate output.\n    \"\"\"\n    matrix_selected = select_keys(data_matrix, all_keys, verbose=False)\n    open_positions = []\n    fixed_positions = [] \n    open_letters = []\n    fixed_letters = []\n    assigned_letters = []\n    for iletter, letter in enumerate(letters):\n        if letter.strip() == \"\":\n            open_positions.append(iletter)\n            for all_letter in all_letters:\n                if all_letter not in letters and all_letter not in assigned_letters:\n                    open_letters.append(all_letter)\n                    assigned_letters.append(all_letter)\n                    break\n        else:\n            fixed_positions.append(iletter)\n            fixed_letters.append(letter)\n    #print(open_positions, fixed_positions, open_letters, fixed_letters)\n    letter_permutations = permute_letters(open_letters, verbose)\n    top_permutation, scores = optimize_layout(matrix_selected, bigrams, bigram_frequencies, letter_permutations, open_positions, fixed_letters, fixed_positions, verbose)\n    if ntop > 0:\n        print_top_scores(letter_permutations, scores, ntop)\n    \n    return top_permutation, letter_permutations, scores\n\n\ndef select_keys(data_matrix, keys, verbose=False):\n    \"\"\"\n    Select keys to quantify pairwise relationships.\n    \"\"\"\n    # Extract pairwise entries for the keys:\n    nkeys = len(keys)\n    Select = np.zeros((nkeys, nkeys))\n    u = 0\n    for i in keys:\n        u += 1\n        v = 0\n        for j in keys:\n            v += 1\n            Select[u-1,v-1] = data_matrix[i-1,j-1]\n\n    # Normalize matrix with min-max scaling to a range with max 1:\n    newMin = np.min(Select) / np.max(Select)\n    newMax = 1.0\n    Select = newMin + (Select - np.min(Select)) * (newMax - newMin) / (np.max(Select) - np.min(Select))\n    \n    if verbose:\n        #print(\"Matrix:\")\n        #np.set_printoptions(precision=2); print(Select)\n\n        # Heatmap of array\n        heatmap(data=Select, title=\"Matrix heatmap\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=False); plt.show()\n    \n    return Select\n\n\ndef permute_letters(letters, verbose=False):\n    \"\"\"\n    Find all permutations of a given set of letters (max: 8-10 letters).\n    \"\"\"\n    letter_permutations = []\n    for p in multiset_permutations(letters):\n        letter_permutations.append(p)\n    letter_permutations = np.array(letter_permutations)\n    #if verbose:\n    #    print(\"First permutation: {0}\".format(letter_permutations[0])) \n    \n    return letter_permutations\n\n\ndef score_layout(data_matrix, letters, bigrams, bigram_frequencies, verbose=False):\n    \"\"\"\n    Compute the score for a given letter-key layout (NOTE normalization step).\n    \"\"\"\n    # Create a matrix of bigram frequencies:\n    nletters = len(letters)\n    F2 = np.zeros((nletters, nletters))\n\n    # Find the bigram frequency for each ordered pair of letters in the permutation:\n    for i1 in range(nletters):\n        for i2 in range(nletters):\n            bigram = letters[i1] + letters[i2]\n            i2gram = np.where(bigrams == bigram)\n            if np.size(i2gram) > 0:\n                F2[i1, i2] = bigram_frequencies[i2gram][0]\n\n    # Normalize matrices with min-max scaling to a range with max 1:\n    newMax = 1\n    minF2 = np.min(F2)\n    maxF2 = np.max(F2)\n    newMin2 = minF2 / maxF2\n    F2 = newMin + (F2 - minF2) * (newMax - newMin2) / (maxF2 - minF2)\n\n    # Compute the score for this permutation:\n    score  = np.average(data_matrix * F2) \n    if verbose:\n        print(\"Score for letter permutation {0}: {1}\".format(letters, score))\n\n    return score\n\n\ndef tally_bigrams(input_text, bigrams, normalize=True, verbose=False):\n    \"\"\"\n    Compute the score for a given letter-key layout (NOTE normalization step).\n    \"\"\"   \n    # Find the bigram frequency for each ordered pair of letters in the input text\n    #input_text = [str.upper(str(x)) for x in input_text]\n    input_text = [str.upper(x) for x in input_text]\n    nchars = len(input_text)\n    F = np.zeros(len(bigrams))\n\n    for ichar in range(0, nchars-1):\n        bigram = input_text[ichar] + input_text[ichar + 1]\n        i2gram = np.where(bigrams == bigram)\n        if np.size(i2gram) > 0:\n            F[i2gram] += 1\n\n    # Normalize matrix with min-max scaling to a range with max 1:\n    if normalize:\n        newMax = 1\n        newMin = np.min(F) / np.max(F)\n        F = newMin + (F - np.min(F)) * (newMax - newMin) / (np.max(F) - np.min(F))\n\n    bigram_frequencies_for_input = F\n\n    if verbose:\n        print(\"Bigram frequencies for input: {0}\".format(bigram_frequencies_for_input))\n\n    return bigram_frequencies_for_input\n\n\ndef tally_layout_samefinger_bigrams(layout, bigrams, bigram_frequencies, verbose=False):\n    \"\"\"\n    Tally the number of same-finger bigrams within (a list of 24 letters representing) a layout:\n    ['P','Y','O','U','C','I','E','A','G','K','J','X','M','D','L','B','R','T','N','S','H','V','W','F']\n    \"\"\"   \n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    same_finger_keys = [[1,5],[5,9],[1,9], [2,6],[6,10],[2,10], \n                        [3,7],[7,11],[3,11], [4,8],[8,12],[4,12],\n                        [13,17],[17,21],[13,21], [14,18],[18,22],[14,22], \n                        [15,19],[19,23],[15,23], [16,20],[20,24],[16,24]] \n\n    layout = [str.upper(x) for x in layout]\n    max_frequency = 1.00273E+11\n\n    samefinger_bigrams = []\n    samefinger_bigram_counts = []\n    for bigram_keys in same_finger_keys:\n        bigram1 = layout[bigram_keys[0]-1] + layout[bigram_keys[1]-1]\n        bigram2 = layout[bigram_keys[1]-1] + layout[bigram_keys[0]-1]\n        i2gram1 = np.where(bigrams == bigram1)\n        i2gram2 = np.where(bigrams == bigram2)\n        if np.size(i2gram1) > 0:\n            samefinger_bigrams.append(bigram1)\n            samefinger_bigram_counts.append(max_frequency * bigram_frequencies[i2gram1] / np.max(bigram_frequencies))\n        if np.size(i2gram2) > 0:\n            samefinger_bigrams.append(bigram2)\n            samefinger_bigram_counts.append(max_frequency * bigram_frequencies[i2gram2] / np.max(bigram_frequencies))\n\n    samefinger_bigrams_total = np.sum(samefinger_bigram_counts)\n\n    if verbose:\n        print(\"    Total same-finger bigram frequencies: {0:15.0f}\".format(samefinger_bigrams_total))\n\n    return samefinger_bigrams, samefinger_bigram_counts, samefinger_bigrams_total \n\n\ndef optimize_layout(data_matrix, bigrams, bigram_frequencies, letter_permutations, open_positions, fixed_letters, fixed_positions=[], verbose=False):\n    \"\"\"\n    Compute scores for all letter-key layouts.\n    \"\"\"\n    iter = 0\n    top_score = 0\n    scores = []\n    use_score_function = False\n\n    nletters = len(open_positions) + len(fixed_positions)\n    top_permutation = np.array(['E' for x in range(nletters)])\n    F2 = np.zeros((nletters, nletters))\n\n    # Loop through the permutations of the selected letters:\n    for p in letter_permutations:\n        letters = np.array(['E' for x in range(nletters)])  # KEEP to initialize!\n        for imove, open_position in enumerate(open_positions):\n            letters[open_position] = p[imove]\n        for ifixed, fixed_position in enumerate(fixed_positions):\n            letters[fixed_position] = fixed_letters[ifixed]\n\n        # Compute the score for this permutation:\n        if use_score_function:\n            score = score_layout(data_matrix, letters, bigrams, bigram_frequencies, verbose=False)\n        else:\n            # Find the bigram frequency for each ordered pair of letters in the permutation:\n            for i1 in range(nletters):\n                for i2 in range(nletters):\n                    bigram = letters[i1] + letters[i2]\n                    i2gram = np.where(bigrams == bigram)\n                    if np.size(i2gram) > 0:\n                        F2[i1, i2] = bigram_frequencies[i2gram][0]\n\n            # Normalize matrices with min-max scaling to a range with max 1:\n            newMax = 1\n            minF2 = np.min(F2)\n            maxF2 = np.max(F2)\n            newMin2 = minF2 / maxF2\n            F = newMin + (F2 - minF2) * (newMax - newMin2) / (maxF2 - minF2)\n\n            # Compute the score for this permutation:\n            score  = np.average(data_matrix * F) \n\n        # Store all scores and the top score and permutation:\n        scores.append(score)\n        if score > top_score:\n            top_score = score\n            top_permutation = letters\n            \n    #print(\"Topmost of {0} permutations: {1}\".format(len(letter_permutations), top_score))\n    if verbose:\n        print(\"{0:0.8f}\".format(top_score))\n        print(*top_permutation)\n        \n    return top_permutation, scores\n\n\ndef exchange_letters(letters, fixed_letter_indices, all_letters, all_keys, data_matrix, \n                     bigrams, bigram_frequencies, verbose=True, ntop=0):\n    \"\"\"\n    Exchange letters, 8 keys at a time (8! = 40,320) selected twice in 32 different ways:\n\n    Indices:\n         0  1  2  3     12 13 14 15\n         4  5  6  7     16 17 18 19\n         8  9 10 11     20 21 22 23 \n\n    1. Top rows\n         0  1  2  3     12 13 14 15\n    2. Bottom rows\n         8  9 10 11     20 21 22 23 \n    3. Top and bottom rows on the right side\n                        12 13 14 15\n                        20 21 22 23 \n    4. Top and bottom rows on the left side \n         0  1  2  3\n         8  9 10 11 \n    5. Top right and bottom left rows\n                        12 13 14 15\n         8  9 10 11 \n    6. Top left and bottom right rows \n         0  1  2  3\n                        20 21 22 23 \n    7. Center of the top and bottom rows on both sides\n            1  2          13 14\n            9 10          21 22\n    8. The eight corners\n         0        3    12       15\n         8       11    20       23 \n    9. Left half of the top and bottom rows on both sides \n         0  1          12 13\n         8  9          20 21\n    10. Right half of the top and bottom rows on both sides\n               2  3          14 15\n              10 11          22 23 \n    11. Left half of non-home rows on the left and right half of the same rows on the right \n         0  1                14 15\n         8  9                22 23 \n    12. Right half of non-home rows on the left and left half of the same rows on the right\n               2  3    12 13\n              10 11    20 21 \n    13. Top center and lower sides\n            1  2           13 14\n         8       11     20       23 \n    14. Top sides and lower center\n         0        3     12       15\n            9 10           21 22   \n    15. Repeat 1-14\n         \n    \"\"\"\n    score = score_layout(data_matrix, letters, bigrams, bigram_frequencies, verbose=False)\n    print('Initial score: {0}'.format(score)) \n    print(*letters) \n    top_permutation = letters\n\n    lists_of_open_indices = [\n        [0,1,2,3,12,13,14,15],\n        [8,9,10,11,20,21,22,23],\n        [12,13,14,15,20,21,22,23],\n        [0,1,2,3,8,9,10,11],\n        [12,13,14,15,8,9,10,11],\n        [0,1,2,3,20,21,22,23],\n        [1,2,13,14,9,10,21,22],\n        [0,3,12,15,8,11,20,23],\n        [0,1,12,13,8,9,20,21],\n        [2,3,14,15,10,11,22,23],\n        [0,1,14,15,8,9,22,23],\n        [2,3,12,13,10,11,20,21],\n        [1,2,8,11,13,14,20,23],\n        [0,3,9,10,12,15,21,22]  \n    ]\n    lists_of_print_statements = [\n        '1. Top rows',\n        '2. Bottom rows',\n        '3. Top and bottom rows on the right side',\n        '4. Top and bottom rows on the left side',\n        '5. Top right and bottom left rows',\n        '6. Top left and bottom right rows',\n        '7. Center of the top and bottom rows on both sides',\n        '8. The eight corners',\n        '9. Left half of the top and bottom rows on both sides',\n        '10. Right half of the top and bottom rows on both sides',\n        '11. Left half of non-home rows on the left and right half of the same rows on the right',\n        '12. Right half of non-home rows on the left and left half of the same rows on the right',\n        '13. Top center and lower sides',\n        '14. Top sides and lower center'\n    ]\n                         \n    for istep in [1,2]:\n        if istep == 1:\n            s = \"First set of 14 letter exchanges: \"\n        elif istep == 2:\n            s = \"Second set of 14 letter exchanges: \"\n\n        for ilist, open_indices in enumerate(lists_of_open_indices):\n            print_statement = lists_of_print_statements[ilist]     \n\n            if verbose:\n                print('{0} {1}'.format(s, print_statement))\n                             \n            for open_index in open_indices:\n                if open_index not in fixed_letter_indices:\n                    top_permutation[open_index] = ''\n                    \n            top_permutation, letter_permutations, scores = permute_optimize(top_permutation, letters24, keys24, data_matrix, bigrams, bigram_frequencies, verbose=True, ntop=0)            \n            top_permutation = top_permutation.tolist()\n        \n    if verbose:\n        print('')\n        print('    -------- DONE --------') \n        print('')\n\n    return top_permutation\n                             \n\ndef rank_within_epsilon(numbers, epsilon, factor=False, verbose=True):\n    \"\"\"\n    numbers = np.array([10,9,8,7,6])\n    epsilon = 1\n    rank_within_epsilon(numbers, epsilon, factor=False, verbose=True) \n    >>> array([1., 1., 2., 2., 3.])\n    numbers = np.array([0.798900824, 0.79899900824, 0.79900824])\n    epsilon = 0.9**8 - 0.9**9\n    factor = ((24**2 - 1) + (1-epsilon)) / (24**2) # 0.999925266109375\n    rank_within_epsilon(numbers, factor, factor=True, verbose=True) \n    >>> array([2., 1., 1.])\n    \"\"\"\n    numbers = np.array(numbers)\n    Isort = np.argsort(-numbers)\n    numbers_sorted = numbers[Isort]\n    count = 1\n    ranks = np.zeros(np.size(numbers))\n    for i, num in enumerate(numbers_sorted):\n        if ranks[i] == 0:\n            if factor:\n                lower_bound = num * epsilon\n            else:\n                lower_bound = num - epsilon\n            bounded_nums1 = num >= numbers_sorted\n            bounded_nums2 = numbers_sorted >= lower_bound\n            bounded_nums = bounded_nums1 * bounded_nums2\n            count += 1\n            for ibounded, bounded_num in enumerate(bounded_nums):\n                if bounded_num == True:\n                    ranks[ibounded] = count\n\n    uranks = np.unique(ranks)\n    nranks = np.size(uranks)\n    new_ranks = ranks.copy()\n    new_count = 0\n    for rank in uranks:\n        new_count += 1\n        same_ranks = ranks == rank\n        for isame, same_rank in enumerate(same_ranks):\n            if same_rank == True:\n                new_ranks[isame] = new_count\n\n    #ranks_sorted = new_ranks[Isort]\n    ranks_sorted = [np.int(x) for x in new_ranks]\n    \n    if verbose:\n        for i, num in enumerate(numbers_sorted):\n            print(\"    ({0})    {1}\".format(np.int(ranks_sorted[i]), num))\n        \n    return numbers_sorted, ranks_sorted, Isort\n```\n\n\n```python\ndef print_top_scores(letter_permutations, scores, ntop):\n    \"\"\"\n    Print top-scored letter permutations.\n    \"\"\"\n    scores_negative = -np.array(scores)\n    isort = np.argsort(scores_negative)[:ntop]\n    sorted_scores = [scores[isort[x]] for x in range(len(isort))]\n    sorted_letter_permutations = [letter_permutations[isort[x]].tolist() for x in range(len(isort))]\n    for ix, x in enumerate(sorted_letter_permutations):\n        print(\"{0:0.8f}\".format(sorted_scores[ix]))\n        print(*x)\n    \ndef print_matrix_info(matrix_data, matrix_label, nkeys, nlines=10):\n    \"\"\"\n    Print matrix output.\n    \"\"\"\n    print(\"{0} min = {1}, max = {2}\".format(matrix_label, np.min(matrix_data), np.max(matrix_data)))\n    matrix_flat = matrix_data.flatten()\n    argsort = np.argsort(matrix_flat)\n    print(\"{0} key number pairs with minimum values:\".format(matrix_label))\n    for x in argsort[0:nlines]:\n        if x % nkeys == 0:\n            min_row = np.int(np.ceil(x / nkeys)) + 1\n            min_col = 1\n        else:\n            min_row = np.int(np.ceil(x / nkeys))\n            min_col = x - nkeys * (min_row-1) + 1                \n        print(\"        {0} -> {1}        ({2})\".format(min_row, min_col, matrix_flat[x]))\n    print(\"{0} key number pairs with maximum values:\".format(matrix_label))\n    max_sort = argsort[-nlines::]\n    for x in max_sort[::-1]:\n        if x % nkeys == 0:\n            max_row = np.int(np.ceil(x / nkeys)) + 1\n            max_col = 1\n        else:\n            max_row = np.int(np.ceil(x / nkeys))\n            max_col = x - nkeys * (max_row-1) + 1                \n        print(\"        {0} -> {1}        ({2})\".format(max_row, max_col, matrix_flat[x]))\n\n\ndef heatmap(data, title=\"\", xlabel=\"\", ylabel=\"\", x_axis_labels=[], y_axis_labels=[], print_output=True):\n    \"\"\"\n    Plot heatmap of matrix.\n    \"\"\"\n    # use heatmap function, set the color as viridis and\n    # make each cell seperate using linewidth parameter\n    plt.figure()\n    sns_plot = sns.heatmap(data, xticklabels=x_axis_labels, yticklabels=y_axis_labels, linewidths=1, \n                           cmap=\"viridis\", square=True, vmin=np.min(data), vmax=np.max(data))\n    plt.title(title)\n    plt.xlabel(xlabel)\n    plt.ylabel(ylabel)\n    sns_plot.set_xticklabels(x_axis_labels)  #, rotation=75) \n    sns_plot.set_yticklabels(y_axis_labels) \n    if print_output:\n        sns_plot.figure.savefig(\"{0}_heatmap.png\".format(title))\n    \ndef histmap(data, title=\"\", print_output=True):\n    \"\"\"\n    Plot histogram.\n    \"\"\"\n    sns.distplot(data)\n    plt.title(title)\n    if print_output:\n        sns_plot.figure.savefig(\"{0}_histogram.png\".format(title))\n        \n        \ndef print_layout24(layout):\n    \"\"\"\n    Print layout.\n    \"\"\"   \n    print('    {0}  {1}'.format(' '.join(layout[0:4]),\n                                ' '.join(layout[12:16])))\n    print('    {0}  {1}'.format(' '.join(layout[4:8]),\n                                ' '.join(layout[16:20])))\n    print('    {0}  {1}'.format(' '.join(layout[8:12]),\n                                ' '.join(layout[20:24])))\n\n# letters24 = ['E','T','A','O','I','N','S','R','H','L','D','C','U','M','F','P','G','W','Y','B','V','K','X','J']\ninstances24 = [4.45155E+11,3.30535E+11,2.86527E+11,2.72277E+11,2.69732E+11,2.57771E+11,\n               2.32083E+11,2.23768E+11,1.80075E+11,1.44999E+11,1.36018E+11,1.19156E+11,\n               97273082907,89506734085,85635440629,76112599849,66615316232,59712390260,\n               59331661972,52905544693,37532682260,19261229433,8369138754,5657910830]                        \n\n\ndef print_layout24_instances(layout, letters24, instances24, bigrams, bigram_frequencies):\n    \"\"\"\n    Print billions of instances per letter (not Z or Q) in layout form.\n    layout = ['P','Y','O','U','C','I','E','A','G','K','J','X','M','D','L','B','R','T','N','S','H','V','W','F']\n    print_layout24_instances(layout, letters24, instances24, bigrams, bigram_frequencies)\n    \"\"\"\n    layout_instances = []\n    layout_instances_strings = []\n    for letter in layout:\n        index = letters24.index(letter)\n        layout_instances.append(instances24[index])\n        layout_instances_strings.append('{0:3.0f}'.format(instances24[index]/1000000000))\n \n    print('    {0}  {1}'.format(' '.join(layout_instances_strings[0:4]),\n                                ' '.join(layout_instances_strings[12:16])))\n    print('    {0}  {1}'.format(' '.join(layout_instances_strings[4:8]),\n                                ' '.join(layout_instances_strings[16:20])))\n    print('    {0}  {1}'.format(' '.join(layout_instances_strings[8:12]),\n                                ' '.join(layout_instances_strings[20:24])))\n    left_sum = np.sum(layout_instances[0:12])/1000000000000\n    right_sum = np.sum(layout_instances[12:24])/1000000000000\n    pL = ''\n    pR = ''\n    if left_sum > right_sum:\n        pL = ' ({0:3.2f}%)'.format(100 * (left_sum - right_sum) / right_sum)\n    elif right_sum > left_sum:\n        pR = ' ({0:3.2f}%)'.format(100 * (right_sum - left_sum) / left_sum)\n    \n    print('\\n    left: {0:3.3f}T{1}  right: {2:3.3f}T{3}'.format(left_sum, pL, \n                                                                 right_sum, pR))\n    \n    tally_layout_samefinger_bigrams(layout, bigrams, bigram_frequencies, verbose=True)\n```\n\n### Bigram frequencies <a name=\"ngrams\">\n\n[Peter Norvig's ngrams table](http://www.norvig.com/mayzner.html](http://www.norvig.com/mayzner.html)\n    \n[NOTE: If you want to compute an optimized layout for another language, or based on another corpus, you can run the tally_bigrams() function above and replace bigram_frequencies below before running the rest of the code.]\n\n\n```python\nload_original_ngram_files = False\nif load_original_ngram_files:\n    ngrams_table = \"data/bigrams-trigrams-frequencies.xlsx\"\n    wb = xlrd.open_workbook(ngrams_table) \n    ngrams_sheet = wb.sheet_by_index(0)\n    # 1-grams and frequencies\n    onegrams = np.array(())\n    onegram_frequencies = np.array(())\n    i = 0\n    start1 = 0\n    stop1 = 0\n    while stop1 == 0:\n        if ngrams_sheet.cell_value(i, 0) == \"2-gram\":\n            stop1 = 1\n        elif ngrams_sheet.cell_value(i, 0) == \"1-gram\":\n            start1 = 1\n        elif start1 == 1:\n            onegrams = np.append(onegrams, ngrams_sheet.cell_value(i, 0))\n            onegram_frequencies = np.append(onegram_frequencies, ngrams_sheet.cell_value(i, 1))\n        i += 1\n    onegram_frequencies = onegram_frequencies / np.sum(onegram_frequencies)\n\n    # 2-grams and frequencies\n    bigrams = np.array(())\n    bigram_frequencies = np.array(())\n    i = 0\n    start1 = 0\n    stop1 = 0\n    while stop1 == 0:\n        if ngrams_sheet.cell_value(i, 0) == \"3-gram\":\n            stop1 = 1\n        elif ngrams_sheet.cell_value(i, 0) == \"2-gram\":\n            start1 = 1\n        elif start1 == 1:\n            bigrams = np.append(bigrams, ngrams_sheet.cell_value(i, 0))\n            bigram_frequencies = np.append(bigram_frequencies, ngrams_sheet.cell_value(i, 1))\n        i += 1\n    bigram_frequencies = bigram_frequencies / np.sum(bigram_frequencies)\n\n    # Save:\n    file = open(\"onegrams.txt\", \"w+\")\n    file.write(str(onegrams))\n    file.close()\n    file = open(\"onegram_frequencies.txt\", \"w+\")\n    file.write(str(onegram_frequencies))\n    file.close()\n    file = open(\"bigrams.txt\", \"w+\")\n    file.write(str(bigrams))\n    file.close()\n    file = open(\"bigram_frequencies.txt\", \"w+\")\n    file.write(str(bigram_frequencies))\n    file.close()\n\n    # Print:\n    print(repr(onegrams))\n    print(repr(onegram_frequencies))\n    print(repr(bigrams))\n    print(repr(bigram_frequencies))\n\nelse:\n    onegrams = np.array(['E', 'T', 'A', 'O', 'I', 'N', 'S', 'R', 'H', 'L', 'D', 'C', 'U',\n       'M', 'F', 'P', 'G', 'W', 'Y', 'B', 'V', 'K', 'X', 'J', 'Q', 'Z'],\n      dtype='<U32')\n    onegram_frequencies = np.array([0.12492063, 0.09275565, 0.08040605, 0.07640693, 0.07569278,\n       0.07233629, 0.06512767, 0.06279421, 0.05053301, 0.04068986,\n       0.03816958, 0.03343774, 0.02729702, 0.02511761, 0.02403123,\n       0.02135891, 0.01869376, 0.01675664, 0.0166498 , 0.01484649,\n       0.01053252, 0.00540513, 0.00234857, 0.00158774, 0.00120469,\n       0.00089951])\n    bigrams = np.array(['TH', 'HE', 'IN', 'ER', 'AN', 'RE', 'ON', 'AT', 'EN', 'ND', 'TI',\n       'ES', 'OR', 'TE', 'OF', 'ED', 'IS', 'IT', 'AL', 'AR', 'ST', 'TO',\n       'NT', 'NG', 'SE', 'HA', 'AS', 'OU', 'IO', 'LE', 'VE', 'CO', 'ME',\n       'DE', 'HI', 'RI', 'RO', 'IC', 'NE', 'EA', 'RA', 'CE', 'LI', 'CH',\n       'LL', 'BE', 'MA', 'SI', 'OM', 'UR', 'CA', 'EL', 'TA', 'LA', 'NS',\n       'DI', 'FO', 'HO', 'PE', 'EC', 'PR', 'NO', 'CT', 'US', 'AC', 'OT',\n       'IL', 'TR', 'LY', 'NC', 'ET', 'UT', 'SS', 'SO', 'RS', 'UN', 'LO',\n       'WA', 'GE', 'IE', 'WH', 'EE', 'WI', 'EM', 'AD', 'OL', 'RT', 'PO',\n       'WE', 'NA', 'UL', 'NI', 'TS', 'MO', 'OW', 'PA', 'IM', 'MI', 'AI',\n       'SH', 'IR', 'SU', 'ID', 'OS', 'IV', 'IA', 'AM', 'FI', 'CI', 'VI',\n       'PL', 'IG', 'TU', 'EV', 'LD', 'RY', 'MP', 'FE', 'BL', 'AB', 'GH',\n       'TY', 'OP', 'WO', 'SA', 'AY', 'EX', 'KE', 'FR', 'OO', 'AV', 'AG',\n       'IF', 'AP', 'GR', 'OD', 'BO', 'SP', 'RD', 'DO', 'UC', 'BU', 'EI',\n       'OV', 'BY', 'RM', 'EP', 'TT', 'OC', 'FA', 'EF', 'CU', 'RN', 'SC',\n       'GI', 'DA', 'YO', 'CR', 'CL', 'DU', 'GA', 'QU', 'UE', 'FF', 'BA',\n       'EY', 'LS', 'VA', 'UM', 'PP', 'UA', 'UP', 'LU', 'GO', 'HT', 'RU',\n       'UG', 'DS', 'LT', 'PI', 'RC', 'RR', 'EG', 'AU', 'CK', 'EW', 'MU',\n       'BR', 'BI', 'PT', 'AK', 'PU', 'UI', 'RG', 'IB', 'TL', 'NY', 'KI',\n       'RK', 'YS', 'OB', 'MM', 'FU', 'PH', 'OG', 'MS', 'YE', 'UD', 'MB',\n       'IP', 'UB', 'OI', 'RL', 'GU', 'DR', 'HR', 'CC', 'TW', 'FT', 'WN',\n       'NU', 'AF', 'HU', 'NN', 'EO', 'VO', 'RV', 'NF', 'XP', 'GN', 'SM',\n       'FL', 'IZ', 'OK', 'NL', 'MY', 'GL', 'AW', 'JU', 'OA', 'EQ', 'SY',\n       'SL', 'PS', 'JO', 'LF', 'NV', 'JE', 'NK', 'KN', 'GS', 'DY', 'HY',\n       'ZE', 'KS', 'XT', 'BS', 'IK', 'DD', 'CY', 'RP', 'SK', 'XI', 'OE',\n       'OY', 'WS', 'LV', 'DL', 'RF', 'EU', 'DG', 'WR', 'XA', 'YI', 'NM',\n       'EB', 'RB', 'TM', 'XC', 'EH', 'TC', 'GY', 'JA', 'HN', 'YP', 'ZA',\n       'GG', 'YM', 'SW', 'BJ', 'LM', 'CS', 'II', 'IX', 'XE', 'OH', 'LK',\n       'DV', 'LP', 'AX', 'OX', 'UF', 'DM', 'IU', 'SF', 'BT', 'KA', 'YT',\n       'EK', 'PM', 'YA', 'GT', 'WL', 'RH', 'YL', 'HS', 'AH', 'YC', 'YN',\n       'RW', 'HM', 'LW', 'HL', 'AE', 'ZI', 'AZ', 'LC', 'PY', 'AJ', 'IQ',\n       'NJ', 'BB', 'NH', 'UO', 'KL', 'LR', 'TN', 'GM', 'SN', 'NR', 'FY',\n       'MN', 'DW', 'SB', 'YR', 'DN', 'SQ', 'ZO', 'OJ', 'YD', 'LB', 'WT',\n       'LG', 'KO', 'NP', 'SR', 'NQ', 'KY', 'LN', 'NW', 'TF', 'FS', 'CQ',\n       'DH', 'SD', 'VY', 'DJ', 'HW', 'XU', 'AO', 'ML', 'UK', 'UY', 'EJ',\n       'EZ', 'HB', 'NZ', 'NB', 'MC', 'YB', 'TP', 'XH', 'UX', 'TZ', 'BV',\n       'MF', 'WD', 'OZ', 'YW', 'KH', 'GD', 'BM', 'MR', 'KU', 'UV', 'DT',\n       'HD', 'AA', 'XX', 'DF', 'DB', 'JI', 'KR', 'XO', 'CM', 'ZZ', 'NX',\n       'YG', 'XY', 'KG', 'TB', 'DC', 'BD', 'SG', 'WY', 'ZY', 'AQ', 'HF',\n       'CD', 'VU', 'KW', 'ZU', 'BN', 'IH', 'TG', 'XV', 'UZ', 'BC', 'XF',\n       'YZ', 'KM', 'DP', 'LH', 'WF', 'KF', 'PF', 'CF', 'MT', 'YU', 'CP',\n       'PB', 'TD', 'ZL', 'SV', 'HC', 'MG', 'PW', 'GF', 'PD', 'PN', 'PC',\n       'RX', 'TV', 'IJ', 'WM', 'UH', 'WK', 'WB', 'BH', 'OQ', 'KT', 'RQ',\n       'KB', 'CG', 'VR', 'CN', 'PK', 'UU', 'YF', 'WP', 'CZ', 'KP', 'DQ',\n       'WU', 'FM', 'WC', 'MD', 'KD', 'ZH', 'GW', 'RZ', 'CB', 'IW', 'XL',\n       'HP', 'MW', 'VS', 'FC', 'RJ', 'BP', 'MH', 'HH', 'YH', 'UJ', 'FG',\n       'FD', 'GB', 'PG', 'TK', 'KK', 'HQ', 'FN', 'LZ', 'VL', 'GP', 'HZ',\n       'DK', 'YK', 'QI', 'LX', 'VD', 'ZS', 'BW', 'XQ', 'MV', 'UW', 'HG',\n       'FB', 'SJ', 'WW', 'GK', 'UQ', 'BG', 'SZ', 'JR', 'QL', 'ZT', 'HK',\n       'VC', 'XM', 'GC', 'FW', 'PZ', 'KC', 'HV', 'XW', 'ZW', 'FP', 'IY',\n       'PV', 'VT', 'JP', 'CV', 'ZB', 'VP', 'ZR', 'FH', 'YV', 'ZG', 'ZM',\n       'ZV', 'QS', 'KV', 'VN', 'ZN', 'QA', 'YX', 'JN', 'BF', 'MK', 'CW',\n       'JM', 'LQ', 'JH', 'KJ', 'JC', 'GZ', 'JS', 'TX', 'FK', 'JL', 'VM',\n       'LJ', 'TJ', 'JJ', 'CJ', 'VG', 'MJ', 'JT', 'PJ', 'WG', 'VH', 'BK',\n       'VV', 'JD', 'TQ', 'VB', 'JF', 'DZ', 'XB', 'JB', 'ZC', 'FJ', 'YY',\n       'QN', 'XS', 'QR', 'JK', 'JV', 'QQ', 'XN', 'VF', 'PX', 'ZD', 'QT',\n       'ZP', 'QO', 'DX', 'HJ', 'GV', 'JW', 'QC', 'JY', 'GJ', 'QB', 'PQ',\n       'JG', 'BZ', 'MX', 'QM', 'MZ', 'QF', 'WJ', 'ZQ', 'XR', 'ZK', 'CX',\n       'FX', 'FV', 'BX', 'VW', 'VJ', 'MQ', 'QV', 'ZF', 'QE', 'YJ', 'GX',\n       'KX', 'XG', 'QD', 'XJ', 'SX', 'VZ', 'VX', 'WV', 'YQ', 'BQ', 'GQ',\n       'VK', 'ZJ', 'XK', 'QP', 'HX', 'FZ', 'QH', 'QJ', 'JZ', 'VQ', 'KQ',\n       'XD', 'QW', 'JX', 'QX', 'KZ', 'WX', 'FQ', 'XZ', 'ZX'], dtype='<U32')\n    bigram_frequencies = np.array([3.55620339e-02, 3.07474124e-02, 2.43274529e-02, 2.04826481e-02,\n       1.98515108e-02, 1.85432319e-02, 1.75804642e-02, 1.48673230e-02,\n       1.45424846e-02, 1.35228145e-02, 1.34257882e-02, 1.33939375e-02,\n       1.27653906e-02, 1.20486963e-02, 1.17497528e-02, 1.16812337e-02,\n       1.12842988e-02, 1.12327374e-02, 1.08744953e-02, 1.07489847e-02,\n       1.05347566e-02, 1.04126653e-02, 1.04125115e-02, 9.53014842e-03,\n       9.32114579e-03, 9.25763559e-03, 8.71095073e-03, 8.70002319e-03,\n       8.34931851e-03, 8.29254235e-03, 8.25280566e-03, 7.93859725e-03,\n       7.93006486e-03, 7.64818391e-03, 7.63241814e-03, 7.27618866e-03,\n       7.26724441e-03, 6.98707488e-03, 6.91722265e-03, 6.88165290e-03,\n       6.85633031e-03, 6.51417363e-03, 6.24352184e-03, 5.97765978e-03,\n       5.76571076e-03, 5.76283716e-03, 5.65269345e-03, 5.50057242e-03,\n       5.46256885e-03, 5.42747781e-03, 5.38164098e-03, 5.30301559e-03,\n       5.29886071e-03, 5.27529444e-03, 5.08937452e-03, 4.92966405e-03,\n       4.87753568e-03, 4.84902069e-03, 4.77989185e-03, 4.77282719e-03,\n       4.74470916e-03, 4.64574958e-03, 4.60971757e-03, 4.54257059e-03,\n       4.47772200e-03, 4.42103298e-03, 4.31534618e-03, 4.25820178e-03,\n       4.25013516e-03, 4.15745843e-03, 4.12608242e-03, 4.05151268e-03,\n       4.05075209e-03, 3.97732158e-03, 3.96527277e-03, 3.94413046e-03,\n       3.86884200e-03, 3.85337077e-03, 3.85189513e-03, 3.84646388e-03,\n       3.78793431e-03, 3.77605408e-03, 3.74420703e-03, 3.73663638e-03,\n       3.67956418e-03, 3.65492648e-03, 3.61676413e-03, 3.61373182e-03,\n       3.60899233e-03, 3.47234973e-03, 3.45829494e-03, 3.39212478e-03,\n       3.37488213e-03, 3.36877623e-03, 3.30478042e-03, 3.23572471e-03,\n       3.17759946e-03, 3.17691369e-03, 3.16447752e-03, 3.15240004e-03,\n       3.15172398e-03, 3.11176534e-03, 2.95503911e-03, 2.89966768e-03,\n       2.87848219e-03, 2.86282435e-03, 2.84865969e-03, 2.84585627e-03,\n       2.81484803e-03, 2.69544349e-03, 2.62987083e-03, 2.54961380e-03,\n       2.54906719e-03, 2.54783715e-03, 2.52606379e-03, 2.47740122e-03,\n       2.39175226e-03, 2.36573195e-03, 2.33400171e-03, 2.29786417e-03,\n       2.27503360e-03, 2.27277101e-03, 2.23911052e-03, 2.21754315e-03,\n       2.18017446e-03, 2.17360835e-03, 2.14044590e-03, 2.13767970e-03,\n       2.13188615e-03, 2.10259217e-03, 2.04932647e-03, 2.04724906e-03,\n       2.03256516e-03, 2.02845908e-03, 1.96777866e-03, 1.95449429e-03,\n       1.95410531e-03, 1.91254221e-03, 1.89316385e-03, 1.88234971e-03,\n       1.87652262e-03, 1.84944194e-03, 1.83351654e-03, 1.78086545e-03,\n       1.76468430e-03, 1.75132925e-03, 1.71573739e-03, 1.70683303e-03,\n       1.66405086e-03, 1.63999785e-03, 1.62732115e-03, 1.62613977e-03,\n       1.60361051e-03, 1.54749379e-03, 1.51636562e-03, 1.51067364e-03,\n       1.49901610e-03, 1.49455831e-03, 1.49011351e-03, 1.48460771e-03,\n       1.48077067e-03, 1.47541326e-03, 1.47480347e-03, 1.46316579e-03,\n       1.46204465e-03, 1.43745726e-03, 1.41513491e-03, 1.39980075e-03,\n       1.38382616e-03, 1.36545598e-03, 1.36333253e-03, 1.36012483e-03,\n       1.35189358e-03, 1.32127808e-03, 1.30185876e-03, 1.28328757e-03,\n       1.27907576e-03, 1.26260675e-03, 1.23637099e-03, 1.23094105e-03,\n       1.21386641e-03, 1.20743055e-03, 1.19536134e-03, 1.19032774e-03,\n       1.17626124e-03, 1.16805780e-03, 1.14618533e-03, 1.11559852e-03,\n       1.06597119e-03, 1.05782134e-03, 1.04699320e-03, 1.04540205e-03,\n       1.01153313e-03, 9.97734501e-04, 9.86028683e-04, 9.84491816e-04,\n       9.79174450e-04, 9.78784303e-04, 9.70343472e-04, 9.68322624e-04,\n       9.66708177e-04, 9.60690121e-04, 9.59749105e-04, 9.43900197e-04,\n       9.40242103e-04, 9.28331656e-04, 9.26685761e-04, 9.14014864e-04,\n       9.02555222e-04, 8.92112065e-04, 8.85803335e-04, 8.77507468e-04,\n       8.62646840e-04, 8.57695087e-04, 8.54499050e-04, 8.43925356e-04,\n       8.31382851e-04, 8.23722323e-04, 8.16643644e-04, 7.89875969e-04,\n       7.86444549e-04, 7.42072946e-04, 7.36927617e-04, 7.27646949e-04,\n       7.25004577e-04, 7.11071849e-04, 6.92833068e-04, 6.71807283e-04,\n       6.68638321e-04, 6.56391013e-04, 6.51990243e-04, 6.49048818e-04,\n       6.43397537e-04, 6.43118050e-04, 6.37839069e-04, 6.21864133e-04,\n       6.06367626e-04, 5.99162639e-04, 5.87024289e-04, 5.74860663e-04,\n       5.72519573e-04, 5.68447140e-04, 5.58806800e-04, 5.45711864e-04,\n       5.37896691e-04, 5.34768852e-04, 5.20071483e-04, 5.18874875e-04,\n       5.16054649e-04, 5.14388309e-04, 5.11931727e-04, 5.04227393e-04,\n       5.00890900e-04, 4.97325634e-04, 4.75088970e-04, 4.66605249e-04,\n       4.58324041e-04, 4.29127437e-04, 4.27514542e-04, 4.17186146e-04,\n       4.16199437e-04, 3.94646924e-04, 3.94183167e-04, 3.86306652e-04,\n       3.61812839e-04, 3.50841120e-04, 3.49059129e-04, 3.23402665e-04,\n       3.22604151e-04, 3.11527347e-04, 3.10032877e-04, 3.07611603e-04,\n       2.96010489e-04, 2.88197255e-04, 2.77494857e-04, 2.70735751e-04,\n       2.67122244e-04, 2.64790886e-04, 2.64597695e-04, 2.63237166e-04,\n       2.61362824e-04, 2.59399816e-04, 2.58614910e-04, 2.57579773e-04,\n       2.49143242e-04, 2.49036616e-04, 2.47547306e-04, 2.36748821e-04,\n       2.35282013e-04, 2.32245156e-04, 2.30209194e-04, 2.28229670e-04,\n       2.27822992e-04, 2.20319919e-04, 2.17945603e-04, 2.13543715e-04,\n       1.97145202e-04, 1.90526970e-04, 1.90304866e-04, 1.88393786e-04,\n       1.85754127e-04, 1.85322815e-04, 1.81767370e-04, 1.74089940e-04,\n       1.71644610e-04, 1.71039222e-04, 1.69557657e-04, 1.66839046e-04,\n       1.64718022e-04, 1.59561636e-04, 1.57658164e-04, 1.54026397e-04,\n       1.52211752e-04, 1.51115808e-04, 1.47564559e-04, 1.46841709e-04,\n       1.36432949e-04, 1.35005671e-04, 1.32141796e-04, 1.27573620e-04,\n       1.27432415e-04, 1.26388914e-04, 1.25919175e-04, 1.23965197e-04,\n       1.21174483e-04, 1.18691292e-04, 1.18219114e-04, 1.17637524e-04,\n       1.17526303e-04, 1.13037594e-04, 1.10863960e-04, 1.09331046e-04,\n       1.08837112e-04, 1.06567401e-04, 1.05698197e-04, 1.00512685e-04,\n       1.00106518e-04, 9.85814937e-05, 9.17495595e-05, 9.15174736e-05,\n       9.09807382e-05, 8.79007001e-05, 8.16240791e-05, 7.91627682e-05,\n       7.79158645e-05, 7.56940333e-05, 7.44394656e-05, 7.18101849e-05,\n       6.97589276e-05, 6.81802488e-05, 6.69029567e-05, 6.54143249e-05,\n       6.08786925e-05, 6.07607969e-05, 6.03570614e-05, 5.98994801e-05,\n       5.95001291e-05, 5.94970869e-05, 5.86983574e-05, 5.79700512e-05,\n       5.66119466e-05, 5.50952209e-05, 5.47453912e-05, 5.43839597e-05,\n       5.25861529e-05, 4.89722417e-05, 4.78187439e-05, 4.77415865e-05,\n       4.77107257e-05, 4.62616737e-05, 4.60653783e-05, 4.60409299e-05,\n       4.56730211e-05, 4.54645078e-05, 4.52324283e-05, 4.38982745e-05,\n       4.36906610e-05, 4.33593810e-05, 4.31226640e-05, 4.29912118e-05,\n       4.29446346e-05, 4.17137339e-05, 3.93478837e-05, 3.84895449e-05,\n       3.84390172e-05, 3.81834469e-05, 3.53827628e-05, 3.47222349e-05,\n       3.37168917e-05, 3.18518637e-05, 3.15951703e-05, 3.12905207e-05,\n       3.10605585e-05, 3.02567524e-05, 2.91709879e-05, 2.89567711e-05,\n       2.85652293e-05, 2.82994071e-05, 2.80417376e-05, 2.77861205e-05,\n       2.77303518e-05, 2.76273746e-05, 2.72172235e-05, 2.69880432e-05,\n       2.66503046e-05, 2.66033916e-05, 2.62086568e-05, 2.59259584e-05,\n       2.57640153e-05, 2.56299050e-05, 2.54449453e-05, 2.51909823e-05,\n       2.47409597e-05, 2.46797892e-05, 2.42472084e-05, 2.35748710e-05,\n       2.24438116e-05, 2.24317329e-05, 2.23097275e-05, 2.21249597e-05,\n       2.17815183e-05, 2.15248592e-05, 2.09465192e-05, 2.09125513e-05,\n       1.96913177e-05, 1.95330853e-05, 1.91064697e-05, 1.88952009e-05,\n       1.85746459e-05, 1.81220081e-05, 1.78919334e-05, 1.73267658e-05,\n       1.61874055e-05, 1.60765855e-05, 1.58740992e-05, 1.45486411e-05,\n       1.40812264e-05, 1.36678429e-05, 1.32768479e-05, 1.31460479e-05,\n       1.30872012e-05, 1.29588223e-05, 1.25748548e-05, 1.24146066e-05,\n       1.22821602e-05, 1.22486357e-05, 1.20714645e-05, 1.20448925e-05,\n       1.19866728e-05, 1.18936663e-05, 1.17590888e-05, 1.17001978e-05,\n       1.16346360e-05, 1.11092945e-05, 1.08992577e-05, 1.06740258e-05,\n       1.06735218e-05, 1.06144296e-05, 1.05679067e-05, 1.03656570e-05,\n       1.03317955e-05, 9.98437559e-06, 9.01036943e-06, 8.85768061e-06,\n       8.76035160e-06, 8.60019167e-06, 8.19227801e-06, 7.80479658e-06,\n       7.53516931e-06, 7.44150882e-06, 7.30644125e-06, 7.26777599e-06,\n       7.06747616e-06, 6.95177332e-06, 6.85925126e-06, 6.74132156e-06,\n       6.71322068e-06, 6.70106994e-06, 6.66133186e-06, 6.47626505e-06,\n       6.38130476e-06, 6.29576510e-06, 6.24612583e-06, 5.93271496e-06,\n       5.92132104e-06, 5.83947722e-06, 5.76779879e-06, 5.76465728e-06,\n       5.53187023e-06, 5.47131015e-06, 5.33180695e-06, 5.22417954e-06,\n       5.20732008e-06, 5.15949060e-06, 5.11569104e-06, 4.95336950e-06,\n       4.94557425e-06, 4.73636484e-06, 4.63955858e-06, 4.53340156e-06,\n       4.22935422e-06, 4.19307790e-06, 4.17347414e-06, 4.12142146e-06,\n       4.11855764e-06, 3.80541311e-06, 3.36707879e-06, 3.29563656e-06,\n       3.17577578e-06, 3.05442971e-06, 2.98983688e-06, 2.97762691e-06,\n       2.95066092e-06, 2.91720550e-06, 2.89840858e-06, 2.77497857e-06,\n       2.76265227e-06, 2.74176112e-06, 2.70310579e-06, 2.61648976e-06,\n       2.60275585e-06, 2.56616744e-06, 2.55465117e-06, 2.49712549e-06,\n       2.42815484e-06, 2.37933375e-06, 2.35040476e-06, 2.33914845e-06,\n       2.33036549e-06, 2.32978989e-06, 2.28930419e-06, 2.28804340e-06,\n       2.26346210e-06, 2.24353844e-06, 2.23182640e-06, 2.23165865e-06,\n       2.22696341e-06, 2.22115030e-06, 2.21572164e-06, 2.20668084e-06,\n       2.19243658e-06, 2.17382266e-06, 2.08159887e-06, 2.07762818e-06,\n       1.95415065e-06, 1.88693410e-06, 1.83219245e-06, 1.81431726e-06,\n       1.67631850e-06, 1.67169206e-06, 1.63803449e-06, 1.57770706e-06,\n       1.56577585e-06, 1.53130790e-06, 1.52519015e-06, 1.52439998e-06,\n       1.49350905e-06, 1.47212210e-06, 1.45715861e-06, 1.40331777e-06,\n       1.38641504e-06, 1.29786439e-06, 1.27069447e-06, 1.25613209e-06,\n       1.23105569e-06, 1.22268909e-06, 1.21688094e-06, 1.18065108e-06,\n       1.18060143e-06, 1.16794389e-06, 1.13216621e-06, 1.12716419e-06,\n       1.12418866e-06, 1.12412659e-06, 1.05684621e-06, 1.05049722e-06,\n       1.04986594e-06, 1.03676402e-06, 1.03482230e-06, 9.96847192e-07,\n       9.75926251e-07, 9.54397081e-07, 9.36101632e-07, 9.30100914e-07,\n       9.27467975e-07, 8.92801774e-07, 8.85217179e-07, 8.58891337e-07,\n       7.80484800e-07, 7.67724409e-07, 7.54031637e-07, 7.45052550e-07,\n       7.32511689e-07, 7.06828122e-07, 6.59585949e-07, 6.40055245e-07,\n       6.18628925e-07, 6.17142222e-07, 6.09904832e-07, 6.07242457e-07,\n       5.72270900e-07, 5.49823535e-07, 5.22568859e-07, 5.01838721e-07,\n       4.91372576e-07, 4.82981856e-07, 4.69688423e-07, 4.59727658e-07,\n       4.54795508e-07, 4.22875379e-07, 4.13494116e-07, 3.99834682e-07,\n       3.97288987e-07, 3.87644926e-07, 3.84245584e-07, 3.81268632e-07,\n       3.67029696e-07, 3.57267536e-07, 3.52642869e-07, 3.51058992e-07,\n       3.44112772e-07, 3.36167495e-07, 3.24215712e-07, 3.23810344e-07,\n       3.21814716e-07, 3.21505459e-07, 3.10936465e-07, 2.88018831e-07,\n       2.86309762e-07, 2.76140106e-07, 2.63218703e-07, 2.56899508e-07,\n       2.51244222e-07, 2.25386521e-07, 2.15766576e-07, 2.03018243e-07,\n       1.99078411e-07, 1.97551987e-07, 1.96981706e-07, 1.92415912e-07,\n       1.84391194e-07, 1.81253585e-07, 1.78663913e-07, 1.77747846e-07,\n       1.59541769e-07, 1.38003378e-07, 1.36499298e-07, 1.22889160e-07,\n       1.22576357e-07, 1.19711121e-07, 1.09597855e-07, 9.97477409e-08,\n       9.65292710e-08, 9.36271510e-08, 9.35785637e-08, 9.34540807e-08,\n       8.40270671e-08, 7.82629028e-08, 7.54898762e-08, 6.64058115e-08,\n       5.96748649e-08, 5.79118882e-08, 5.73650143e-08, 5.65688198e-08,\n       5.34673852e-08, 5.34237630e-08, 5.29956976e-08, 4.84174907e-08,\n       3.83818937e-08])\n```\n\n## Speed matrix  <a name=\"speed\">\n### 24x24 relative Speed matrix between key pair (averaged for left/right symmetry)\n\n  - does not take into account order of key pairs (see Flow24x24 matrix)\n  - the original version was constructed with data from right-handed people\n  - 24 keys that don't require extending index or little fingers (\"vertical range keys\")\n\n### Vertical range keys\n\n        Left:            Right:\n     1  2  3  4       13 14 15 16 \n     5  6  7  8       17 18 19 20\n     9 10 11 12       21 22 23 24\n\nInterkey stroke times in milliseconds from Table 3 of <br>\n\"Estimation of digraph costs for keyboard layout optimization\", <br>\nA Iseri, Ma Eksioglu, International Journal of Industrial Ergonomics, 48, 127-138, 2015. <br>\nKey numbering in article and in spreadsheet:\n\n         Left:           Right:\n     1 4 7 10 13   16 19 22 25 28 31\n     2 5 8 11 14   17 20 23 26 29 32\n     3 6 9 12 15   18 21 24 27 30\n     \n### Load table of interkey speeds\n\n\n```python\nload_original_interkey_timings_table = False\nif load_original_interkey_timings_table:\n\n    interkey_table = \"data/interkey-timings.xlsx\"\n    wb = xlrd.open_workbook(interkey_table) \n    interkey_sheet = wb.sheet_by_index(0)\n\n    # Convert interkey stroke times table to array:\n    Time32x32 = np.zeros((32,32))\n    for i in range(1,33):\n        for j in range(1,33):\n            if interkey_sheet.cell_value(i,j):\n                Time32x32[i-1,j-1] = interkey_sheet.cell_value(i,j)\n\n    # Fill empty (symmetric) portion of the array:\n    for i in range(1,33):\n        for j in range(1,33):\n            if interkey_sheet.cell_value(i,j):\n                Time32x32[j-1,i-1] = interkey_sheet.cell_value(i,j)\n\n    # Extract pairwise entries for the 24 vertical range keys:\n    table_24_positions = [1,4,7,10, 2,5,8,11, 3,6,9,12,  19,22,25,28, 20,23,26,29, 21,24,27,30]\n    Time24x24 = np.zeros((24, 24))\n    u = 0\n    for i in table_24_positions:\n        u += 1\n        v = 0\n        for j in table_24_positions:\n            v += 1\n            Time24x24[u-1,v-1] = Time32x32[i-1,j-1]\n\n    # Save:\n    if print_output:\n        file = open(\"Time24x24.txt\", \"w+\")\n        file.write(str(Time24x24))\n        file.close()\n\n    # Print:\n    print(repr(Time24x24))\n\nelse:\n    Time24x24 = np.array([[196., 225., 204., 164., 266., 258., 231., 166., 357., 325., 263.,\n        186., 169., 176., 178., 186., 156., 156., 158., 163., 171., 175., 177., 185.],\n       [225., 181., 182., 147., 239., 245., 196., 150., 289., 296., 229.,\n        167., 162., 169., 170., 178., 148., 148., 150., 155., 163., 167., 169., 177.],\n       [204., 182., 170., 149., 196., 194., 232., 155., 237., 214., 263.,\n        166., 157., 164., 165., 173., 143., 143., 145., 150., 158., 163., 164., 172.],\n       [164., 147., 149., 169., 160., 161., 157., 226., 165., 185., 234.,\n        257., 154., 162., 163., 171., 141., 141., 143., 148., 156., 160., 162., 170.],\n       [266., 239., 196., 160., 196., 240., 208., 166., 271., 267., 208.,\n        169., 143., 150., 151., 160., 129., 129., 132., 137., 145., 149., 151., 159.],\n       [258., 245., 194., 161., 240., 181., 183., 149., 245., 256., 184.,\n        150., 138., 145., 146., 154., 124., 124., 126., 131., 139., 144., 145., 153.],\n       [231., 196., 232., 157., 208., 183., 170., 149., 201., 215., 239.,\n        151., 134., 141., 142., 150., 120., 120., 122., 127., 135., 140., 141., 149.],\n       [166., 150., 155., 226., 166., 149., 149., 169., 160., 147., 170.,\n        221., 133., 140., 141., 150., 119., 119., 122., 126., 135., 139., 141., 149.],\n       [357., 289., 237., 165., 271., 245., 201., 160., 196., 236., 194.,\n        161., 171., 178., 179., 188., 157., 157., 160., 164., 173., 177., 179., 187.],\n       [325., 296., 214., 185., 267., 256., 215., 147., 236., 181., 184.,\n        157., 166., 173., 174., 182., 152., 152., 154., 159., 167., 172., 173., 181.],\n       [263., 229., 263., 234., 208., 184., 239., 170., 194., 184., 170.,\n        150., 159., 166., 167., 176., 145., 145., 148., 153., 161., 165., 167., 175.],\n       [186., 167., 166., 257., 169., 150., 151., 221., 161., 157., 150.,\n        169., 153., 160., 161., 169., 139., 139., 141., 146., 154., 159., 160., 168.],\n       [169., 162., 157., 154., 143., 138., 134., 133., 171., 166., 159.,\n        153., 151., 147., 141., 145., 188., 151., 142., 164., 213., 204., 162., 145.],\n       [176., 169., 164., 162., 150., 145., 141., 140., 178., 173., 166.,\n        160., 147., 151., 189., 209., 137., 207., 191., 206., 149., 227.,  208., 226.],\n       [178., 170., 165., 163., 151., 146., 142., 141., 179., 174., 167.,\n        161., 141., 189., 157., 253., 136., 188., 210., 231., 155., 226.,   239., 225.],\n       [186., 178., 173., 171., 160., 154., 150., 150., 188., 182., 176.,\n        169., 145., 209., 253., 170., 147., 206., 251., 233., 164., 268.,  362., 236.],\n       [156., 148., 143., 141., 129., 124., 120., 119., 157., 152., 145.,\n        139., 188., 137., 136., 147., 151., 133., 138., 152., 192., 149.,  139., 143.],\n       [156., 148., 143., 141., 129., 124., 120., 119., 157., 152., 145.,\n        139., 151., 207., 188., 206., 133., 151., 179., 183., 145., 204.,  183., 194.],\n       [158., 150., 145., 143., 132., 126., 122., 122., 160., 154., 148.,\n        141., 142., 191., 210., 251., 138., 179., 157., 240., 145., 185.,  208., 235.],\n       [163., 155., 150., 148., 137., 131., 127., 126., 164., 159., 153.,\n        146., 164., 206., 231., 233., 152., 183., 240., 170., 160., 220.,  293., 230.],\n       [171., 163., 158., 156., 145., 139., 135., 135., 173., 167., 161.,\n        154., 213., 149., 155., 164., 192., 145., 145., 160., 151., 140.,  142., 175.],\n       [175., 167., 163., 160., 149., 144., 140., 139., 177., 172., 165.,\n        159., 204., 227., 226., 268., 149., 204., 185., 220., 140., 151.,  175., 265.],\n       [177., 169., 164., 162., 151., 145., 141., 141., 179., 173., 167.,\n        160., 162., 208., 239., 362., 139., 183., 208., 293., 142., 175.,  157., 265.],\n       [185., 177., 172., 170., 159., 153., 149., 149., 187., 181., 175.,\n        168., 145., 226., 225., 236., 143., 194., 235., 230., 175., 265.,  265., 170.]])\n\n# Left/right symmetric version of the Time24x24 matrix\n# (The original version was constructed with data from right-handed people.)\nTimeSymmetric24x24 = np.ones((24,24))\n\n#        Left:            Right:\n#     1  2  3  4       13 14 15 16 \n#     5  6  7  8       17 18 19 20\n#     9 10 11 12       21 22 23 24\n\nI = [1,2,3,4, 5,6,7,8, 9,10,11,12,  16,15,14,13, 20,19,18,17, 24,23,22,21]\nJ = [16,15,14,13, 20,19,18,17, 24,23,22,21,  1,2,3,4, 5,6,7,8, 9,10,11,12]\n\nfor i1, I1 in enumerate(I):\n    for i2, I2 in enumerate(I):\n        J1 = J[i1] - 1\n        J2 = J[i2] - 1\n        #print(i1,i2,I1-1,I2-1,J1,J2)\n        avgvalue = (Time24x24[I1-1,I2-1] + Time24x24[J1,J2]) / 2 \n        TimeSymmetric24x24[I1-1,I2-1] = avgvalue\n        TimeSymmetric24x24[J1,J2] = avgvalue\n\n# Normalize matrix with min-max scaling to a range with maximum = 1:\nnewMin = np.min(TimeSymmetric24x24) / np.max(TimeSymmetric24x24)\nnewMax = 1.0\nTimeSymmetric24x24 = newMin + (TimeSymmetric24x24 - np.min(TimeSymmetric24x24)) * (newMax - newMin) / (np.max(TimeSymmetric24x24) - np.min(TimeSymmetric24x24))\n\n# Convert relative interkey stroke times to relative speeds by subtracting from 1:\nSpeed24x24 = 1 - TimeSymmetric24x24 + np.min(TimeSymmetric24x24)\n\n# Print:\nprint_matrix_info(matrix_data=Speed24x24, matrix_label=\"Speed24x24\", nkeys=24, nlines=50)\nheatmap(data=Speed24x24, title=\"Speed24x24\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n# Print:\n#print(repr(Speed24x24))\n\n# Save:\nif print_output:\n    file = open(\"Speed24x24.txt\", \"w+\")\n    file.write(str(Speed24x24))\n    file.close()\n\n```\n\n## Strength matrix  <a name=\"strength\">\n\n### 24x24 relative finger position STRENGTH matrix\n\nFinger strengths are based on peak keyboard reaction forces (in newtons) from Table 4 of <br>\n\"Keyboard Reaction Force and Finger Flexor Electromyograms during Computer Keyboard Work\" <br>\nBJ Martin, TJ Armstrong, JA Foulke, S Natarajan, Human Factors,1996,38(4),654-664:\n   \n    middle     2.36\n    index      2.26\n    ring       2.02\n    little     1.84\n    \n    2.36/1.84 = 1.28\n    2.36/2.02 = 1.17\n\nFor reference, Table 1 of \"Ergonomic keyboard layout designed for the Filipino language\", 2016 (doi: 10.1007/978-3-319-41694-6_41) presents \"average finger strength of Filipinos [n=30, ages 16-36] measured in pounds\":\n   \n                L       R\n    little     3.77   4.27\n    ring       4.54   5.08\n    middle     5.65   6.37\n    index      6.09   6.57\n    \n    6.57/4.27 = 1.54\n    6.09/3.77 = 1.62\n    6.37/5.08 = 1.25\n    5.65/4.54 = 1.24\n    \nWe won't use these results as I don't feel they represent relative strength relevant for typing: \"Respondents were asked to sit in upright position, with their wrists resting on a flat surface. A pinch gauge was placed within each finger's reach. The respondents were asked to exert maximum pressure on the device.\"\n    \nThe following does not take into account order of key pairs (see Flow matrix).\n\n\n\n```python\nif apply_strength:\n\n    # Normalize by the highest peak force (middle finger):\n    middle_force = 2.36\n    index_force = 2.26\n    ring_force = 2.02\n    little_force = 1.84\n    middle_norm = 1.0\n    index_norm = index_force / middle_force\n    ring_norm = ring_force / middle_force\n    little_norm = little_force / middle_force\n    print('index/middle: {0}'.format(index_norm))\n    print('ring/middle: {0}'.format(ring_norm))\n    print('little/middle: {0}'.format(little_norm))\n    \n    # Relative left/right hand strength (assume equal):\n    lf = 1.0\n    rf = 1.0\n    \n    strengths24 = np.array((\n                        lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                        lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                        lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                        rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm,\n                        rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm,\n                        rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm))\n\n    # Create a finger-pair position strength matrix by adding pairs of strength values:\n    Strength24x24 = np.zeros((24, 24))\n    for i in range(24):\n        Strength24x24[i,:] = strengths24\n    Strength24x24 = (Strength24x24 + Strength24x24.transpose())\n\n    # Normalize matrix with min-max scaling to a range with maximum = 1:\n    #newMin = strength_factor\n    newMin = min_strength_factor  # np.min(Strength24x24) / np.max(Strength24x24)\n    newMax = 1.0\n    Strength24x24 = newMin + (Strength24x24 - np.min(Strength24x24)) * (newMax - newMin) / (np.max(Strength24x24) - np.min(Strength24x24))\n\n    # Print:\n    print_matrix_info(matrix_data=Strength24x24, matrix_label=\"Strength24x24\", nkeys=24, nlines=10)\n    heatmap(data=Strength24x24, title=\"Strength24x24\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n    # Save:\n    if print_output:\n        file = open(\"Strength24x24.txt\", \"w+\")\n        file.write(str(Strength24x24))\n        file.close()\n```\n\n\n```python\nif apply_strength:\n\n    penalty = 1.0  # Penalty for lateral (index, little) finger placement (1 = no penalty)\n\n    strengths32 = np.array((lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                            lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                            lf * little_norm, lf * ring_norm, lf * middle_norm, lf * index_norm,\n                            rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm,\n                            rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm,\n                            rf * index_norm, rf * middle_norm, rf * ring_norm, rf * little_norm,\n                            lf * index_norm * penalty, lf * index_norm * penalty, lf * index_norm * penalty,\n                            rf * index_norm * penalty, rf * index_norm * penalty, rf * index_norm * penalty,\n                            rf * little_norm * penalty, rf * little_norm * penalty))\n\n    # Create a finger-pair position strength matrix by adding pairs of strength values:\n    Strength32x32 = np.zeros((32, 32))\n    for i in range(32):\n        Strength32x32[i,:] = strengths32\n    Strength32x32 = (Strength32x32 + Strength32x32.transpose())\n\n    # Normalize matrix with min-max scaling to a range with maximum = 1:\n    newMin = np.min(Strength32x32) / np.max(Strength32x32)\n    newMax = 1.0\n    Strength32x32 = newMin + (Strength32x32 - np.min(Strength32x32)) * (newMax - newMin) / (np.max(Strength32x32) - np.min(Strength32x32))\n\n    # Print:\n    print_matrix_info(matrix_data=Strength32x32, matrix_label=\"Strength32x32\", nkeys=32, nlines=10)\n    heatmap(data=Strength32x32, title=\"Strength32x32\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n    # Save:\n    if print_output:\n        file = open(\"Strength32x32.txt\", \"w+\")\n        file.write(str(Strength32x32))\n        file.close()\n```\n\n## Flow matrix and Engram scoring model  <a name=\"flow\">\n\nThe Flow24x24 matrix takes into account ease of transition between ordered pairs of keys.\n    \nOur optimization algorithm finds every permutation of a given set of letters, maps these letter permutations to a set of keys, and ranks these letter-key mappings according to a score reflecting ease of typing key pairs and frequency of letter pairs (bigrams). The score is the average of the scores for all possible bigrams in this arrangement. The score for each bigram is a product of the frequency of occurrence of that bigram, the frequency of each of the bigram\u2019s characters, and flow, strength (and optional speed) factors for the key pair.\n\n#### Dvorak et al. (1936) defined eleven criteria for the design and evaluation of keyboard layouts:\n1.  Deviation from the balance of hand and finger loads should be as low as possible.\n2.  Percentage of tapping with the same fingers should be as low as possible.\n3.  Percentage of tapping that includes top row should be as low as possible.\n4.  Percentage of tapping that includes bottom row should be as low as possible.\n5.  Percentage of tapping in the home row should be as high as possible.\n6.  Percentage of tapping by alternating hands should be as high as possible.\n7.  Percentage of hurdles with the same finger should be as low as possible.\n8.  Percentage of hurdles with adjacent offset fingers should be as low as possible.\n9.  Percentage of hurdles with remote fingers should be as low as possible.\n10. Percentage of reach with the same finger should be as low as possible.\n11. Percentage of reach with adjacent offset fingers should be as low as possible.\n\n#### Synopsis of above criteria for pairwise key presses when touch typing:\n1. Alternate between hands.\n2. Balance finger loads, and avoid using the same finger.\n3. Avoid the upper and lower rows, and avoid skipping over the home row.\n4. Avoid tapping adjacent offset rows with the same or adjacent offset fingers.\n    \n### Factors to penalize strenuous key transitions\n\nDirection:\n    \n    - outward = 0.9: outward roll of fingers from the index to little finger (same hand)\n\nDexterity:\n    \n    - side_above_3away = 0.9\n        - index and little finger type two keys, one or more rows apart (same hand)\n    - side_above_2away = 0.9^2 = 0.81\n        - index finger types key a row or two above ring finger key, or\n        - little finger types key a row or two above middle finger key (same hand)\n    - side_above_1away = 0.9^3 = 0.729\n        - index finger types key a row or two above middle finger key, or\n        - little finger types key a row or two above ring finger key (same hand)\n    - middle_above_ring = 0.9\n        - middle finger types key a row or two above ring finger key (same hand)\n    - ring_above_middle = 0.9^3 = 0.729\n        - ring finger types key a row or two above middle finger key (same hand)\n    - lateral = 0.9\n        - lateral movement of (index or little) finger outside of 8 vertical columns\n    \nDistance:\n    \n    - skip_row_3away = 0.9       \n        - index and little fingers type two keys that skip over home row (same hand)\n        - (e.g., one on bottom row, the other on top row)\n    - skip_row_2away = 0.9^3 = 0.729\n        - little and middle or index and ring fingers type two keys that skip over home row (same hand)\n    - skip_row_1away = 0.9^5 = 0.59049\n        - little and ring or middle and index fingers type two keys that skip over home row (same hand)\n\nRepetition:\n \n    - skip_row_0away = 0.9^4 = 0.6561\n        - same finger types two keys that skip over home row\n    - same_finger = 0.9^5 = 0.59049\n        - use same finger again for a different key\n        - cannot accompany outward, side_above, or adjacent_shorter_above \n\nStrength: Accounted for by the strength matrix (minimum value for the little finger = 0.9)    \n\n\n```python\n# Penalizing factors for 24 keys  (1 = no penalty; set to less than 1 to penalize):\n\n# Dexterity\nside_above_3away = 0.9     # index and little finger type two keys, one or more rows apart (same hand)\nside_above_2away = 0.81    # index finger types key a row or two above ring finger key, or\n                           # little finger types key a row or two above middle finger key (same hand)\nside_above_1away = 0.729   # index finger types key a row or two above middle finger key, or\n                           # little finger types key a row or two above ring finger key (same hand)\nmiddle_above_ring = 0.9    # middle finger types key a row or two above ring finger key (same hand)\nring_above_middle = 0.729  # ring finger types key a row or two above middle finger key (same hand)\nlateral = 0.9              # lateral movement of (index or little) finger outside of 8 vertical columns\n\n# Direction\noutward = 0.9              # outward roll of fingers from the index to little finger (same hand)\n\n# Distance\nskip_row_3away = 0.9       # index and little fingers type two keys that skip over home row (same hand)\n                           # (e.g., one on bottom row, the other on top row)\nskip_row_2away = 0.729     # little and middle or index and ring fingers type two keys that skip over home row (same hand)\nskip_row_1away = 0.59049   # little and ring or middle and index fingers type two keys that skip over home row (same hand)\n\n# Repetition\nskip_row_0away = 0.6561    # same finger types two keys that skip over home row\nsame_finger = 0.59049      # use same finger again for a different key\n\n\n# Unused or redundant parameters\nsame_hand = 1.0            # (addressed by splitting up the most frequent letters across left/right sides above)\nnot_home_row = 1.0         # at least one key not on home row\nside_top = 1.0             # index or little finger types top corner key\nshorter_above = 1.0        # (taken care of by side_above_[1,2,3]away parameters)\nadjacent_offset = 1.0      # (taken care of by side_above_1away, middle_above_ring, ring_above_middle parameters)\ninside_top = 1.0           # index finger types top corner key (taken care of by side_above_1away parameter)\nindex_above = 1.0          # index finger types top corner key (unless other bigram key is in the top row for the same hand)\n                           # (taken care of by side_above_[1,2,3]away parameters)\n```\n\n#### 24 keys:\n\n\n```python\ndef create_24x24_flow_matrix(not_home_row, side_top, side_above_3away, side_above_2away, side_above_1away, \n                             middle_above_ring, ring_above_middle, outward, skip_row_3away, \n                             skip_row_2away, skip_row_1away, skip_row_0away, same_finger, lateral, \n                             same_hand, shorter_above, adjacent_offset, inside_top, index_above):\n\n    all_24_keys = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24]\n\n    # Create a matrix and multiply by flow factors that promote easy interkey transitions:\n    T = np.ones((24, 24))\n\n    # 7.  Promote alternating between hands over uncomfortable transitions with the same hand.\n    if same_hand < 1.0:\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n        for i in range(0,12):\n            for j in range(0,12):\n                T[i,j] *= same_hand\n        for i in range(12,24):\n            for j in range(12,24):\n                T[i,j] *= same_hand\n\n    # 8.  Promote little-to-index-finger roll-ins over index-to-little-finger outwards.\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    if outward < 1.0:\n\n        # same-row roll-outs:\n        roll_ins = [[1,2],[2,3],[3,4], [5,6],[6,7],[7,8], [9,10],[10,11],[11,12],\n                    [16,15],[15,14],[14,13], [20,19],[19,18],[18,17], [24,23],[23,22],[22,21]]\n        for x in roll_ins:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # same-row roll-outs, skipping keys:\n        roll_ins_skip_keys = [[1,3],[2,4],[1,4], [5,7],[6,8],[5,8], [9,11],[10,12],[9,12],\n                              [16,14],[15,13],[16,13], [20,18],[19,17],[20,17], [24,22],[23,21],[24,21]]\n        for x in roll_ins_skip_keys:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # adjacent-row roll-outs:\n        roll_ins_adj_rows = [[1,6],[1,7],[1,8],[2,7],[2,8],[3,8], [5,2],[5,3],[5,4],[6,3],[6,4],[7,4],\n                             [5,10],[5,11],[5,12],[6,11],[6,12],[7,12], [9,6],[9,7],[9,8],[10,7],[10,8],[11,8],\n                             [16,19],[16,18],[16,17],[15,18],[15,17],[14,17], [20,15],[20,14],[20,13],[19,14],[19,13],[18,13],\n                             [20,23],[20,22],[20,21],[19,22],[19,21],[18,21], [24,19],[24,18],[24,17],[23,18],[23,17],[22,17]]\n        for x in roll_ins_adj_rows:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # upper<->lower row roll-outs:\n        roll_ins_skip_home = [[1,10],[1,11],[1,12],[2,11],[2,12],[3,12], [9,2],[9,3],[9,4],[10,3],[10,4],[11,4],\n                              [16,23],[16,22],[16,21],[15,22],[15,21],[14,21], [24,15],[24,14],[24,13],[23,14],[23,13],[22,13]]\n        for x in roll_ins_skip_home:\n            T[x[1]-1, x[0]-1] *= outward\n\n    # 9.  Avoid stretching shorter fingers up and longer fingers down.\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    if index_above < 1.0:\n        for x in [4]:\n            for y in [4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n        for x in [13]:\n            for y in [1,2,3,4,5,6,7,8,9,10,11,12,13,17,18,19,20,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n    if inside_top < 1.0:\n        for x in [4,13]:\n            for j in range(0,24):\n                T[x-1, j] *= inside_top\n                T[j, x-1] *= inside_top\n    if side_top < 1.0:\n        for x in [1,4,13,16]:\n            for j in range(0,24):\n                T[x-1, j] *= side_top\n                T[j, x-1] *= side_top\n    if side_above_1away < 1.0:\n        for x in [1]:\n            for y in [6,10]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [5]:\n            for y in [10]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [4]:\n            for y in [7,11]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [8]:\n            for y in [11]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [13]:\n            for y in [18,22]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [17]:\n            for y in [22]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [16]:\n            for y in [19,23]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [20]:\n            for y in [23]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n    if side_above_2away < 1.0:\n        for x in [1]:\n            for y in [7,11]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [5]:\n            for y in [11]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [4]:\n            for y in [6,10]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [8]:\n            for y in [10]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [13]:\n            for y in [19,23]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [17]:\n            for y in [23]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [16]:\n            for y in [18,22]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [20]:\n            for y in [22]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n    if side_above_3away < 1.0:\n        for x in [1]:\n            for y in [8,12]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [5]:\n            for y in [12]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [4]:\n            for y in [5,9]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [8]:\n            for y in [9]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [13]:\n            for y in [20,24]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [17]:\n            for y in [24]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [16]:\n            for y in [17,21]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [20]:\n            for y in [21]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n    if shorter_above < 1.0:\n        for x in [1]:\n            for y in [6,7,8,10,11,12]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [2]:\n            for y in [7,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [4]:\n            for y in [6,7,10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [5]:\n            for y in [10,11,12]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [6]:\n            for y in [11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [8]:\n            for y in [10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [16]:\n            for y in [17,18,19,21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [15]:\n            for y in [18,22]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [13]:\n            for y in [18,19,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [20]:\n            for y in [21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [19]:\n            for y in [22]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [17]:\n            for y in [22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n    if ring_above_middle < 1.0:\n        ring_above_middles =  [[2,7],[6,11],[2,11],\n                            [15,18],[19,22],[15,22]]\n        for x in ring_above_middles:\n            T[x[0]-1, x[1]-1] *= ring_above_middle\n            T[x[1]-1, x[0]-1] *= ring_above_middle\n\n    if middle_above_ring < 1.0:\n        middle_above_rings =  [[6,3],[10,7],[10,3],\n                            [19,14],[23,18],[23,14]]\n        for x in middle_above_rings:\n            T[x[0]-1, x[1]-1] *= middle_above_ring\n            T[x[1]-1, x[0]-1] *= middle_above_ring\n\n    # 10. Avoid using the same finger.\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    if same_finger < 1.0:\n        same_fingers = [[1,5],[5,9],[1,9], [2,6],[6,10],[2,10], [3,7],[7,11],[3,11], [4,8],[8,12],[4,12],\n                        [13,17],[17,21],[13,21], [14,18],[18,22],[14,22], [15,19],[19,23],[15,23], [16,20],[20,24],[16,24]] \n        for x in same_fingers:\n            T[x[0]-1, x[1]-1] *= same_finger\n            T[x[1]-1, x[0]-1] *= same_finger\n\n    # 11. Avoid the upper and lower rows.\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    if not_home_row < 1.0:\n        not_home_row_keys = [1,2,3,4, 9,10,11,12, 13,14,15,16, 21,22,23,24]\n        for x in not_home_row_keys:\n            for j in range(0,23):\n                T[x-1, j] *= not_home_row\n                T[j, x-1] *= not_home_row\n\n    # 12. Avoid skipping over the home row.\n    #    1  2  3  4   13 14 15 16  \n    #    5  6  7  8   17 18 19 20 \n    #    9 10 11 12   21 22 23 24\n    if skip_row_0away < 1.0:\n        skip_top = [1, 2, 3, 4, 13,14,15,16] \n        skip_bot = [9,10,11,12, 21,22,23,24] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_0away\n            T[y-1, x-1] *= skip_row_0away\n    if skip_row_1away < 1.0:\n        skip_top = [1, 2, 2, 3, 3, 4, 13,14,14,15,15,16] \n        skip_bot = [10,9,11,10,12,11, 22,21,23,22,24,23] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_1away\n            T[y-1, x-1] *= skip_row_1away\n    if skip_row_2away < 1.0:\n        skip_top = [1,  2,3, 4, 13,14,15,16] \n        skip_bot = [11,12,9,10, 23,24,21,22] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_2away\n            T[y-1, x-1] *= skip_row_2away\n    if skip_row_3away < 1.0:\n        skip_top = [1, 4, 13,16] \n        skip_bot = [12,9, 24,21] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_3away\n            T[y-1, x-1] *= skip_row_3away\n\n    Flow24x24 = T\n\n    # Normalize matrix with min-max scaling to a range with maximum = 1:\n    newMin = np.min(Flow24x24) / np.max(Flow24x24)\n    newMax = 1.0\n    Flow24x24 = newMin + (Flow24x24 - np.min(Flow24x24)) * (newMax - newMin) / (np.max(Flow24x24) - np.min(Flow24x24))\n\n    return Flow24x24\n\nFlow24x24 = create_24x24_flow_matrix(not_home_row, side_top, \n    side_above_3away, side_above_2away, side_above_1away, middle_above_ring, ring_above_middle, outward, \n    skip_row_3away, skip_row_2away, skip_row_1away, skip_row_0away, same_finger, lateral, same_hand, \n    shorter_above, adjacent_offset, inside_top, index_above)\n\n# Print:\nprint_matrix_info(matrix_data=Flow24x24, matrix_label=\"Flow24x24\", nkeys=24, nlines=30)\nheatmap(data=Flow24x24, title=\"Flow24x24\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n# Save:\nif print_output:\n    file = open(\"Flow24x24.txt\", \"w+\")\n    file.write(str(Flow24x24))\n    file.close()\n\n#    1  2  3  4   13 14 15 16  \n#    5  6  7  8   17 18 19 20 \n#    9 10 11 12   21 22 23 24\n```\n\n#### 32 keys:\n\n         Left:             Right:\n     1  2  3  4 25   28 13 14 15 16 31 \n     5  6  7  8 26   29 17 18 19 20 32\n     9 10 11 12 27   30 21 22 23 24\n\n\n\n```python\ndef create_32x32_flow_matrix(not_home_row, side_top, side_above_3away, side_above_2away, side_above_1away, \n                             middle_above_ring, ring_above_middle, outward, skip_row_3away, \n                             skip_row_2away, skip_row_1away, skip_row_0away, same_finger, lateral, \n                             same_hand, shorter_above, adjacent_offset, inside_top, index_above):\n\n    all_32_keys = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, \n                   25,26,27, 28,29,30, 31,32]\n\n    # Create a matrix and multiply by flow factors that promote easy interkey transitions:\n    T = np.ones((32, 32))\n\n    if lateral < 1.0:\n        for x in all_32_keys:\n            for y in [25,26,27, 28,29,30, 31,32]:\n                T[x-1, y-1] *= lateral\n                T[y-1, x-1] *= lateral    \n\n    # 7.  Promote alternating between hands over uncomfortable transitions with the same hand.\n    if same_hand < 1.0:\n        for i in [1,2,3,4,5,6,7,8,9,10,11,12, 25,26,27]:\n            for j in [1,2,3,4,5,6,7,8,9,10,11,12, 25,26,27]:\n                T[i-1,j-1] *= same_hand\n        for i in [13,14,15,16,17,18,19,20,21,22,23,24, 28,29,30,31,32]:\n            for j in [13,14,15,16,17,18,19,20,21,22,23,24, 28,29,30,31,32]:\n                T[i-1,j-1] *= same_hand\n\n    # 8.  Promote little-to-index-finger roll-ins over index-to-little-finger outsward rolls.\n    # Penalize (index, little) finger lateral movements:\n    #  1  2  3  4 25   28 13 14 15 16 31 \n    #  5  6  7  8 26   29 17 18 19 20 32\n    #  9 10 11 12 27   30 21 22 23 24\n    if outward < 1.0:\n\n        # same-row roll-outs:\n        roll_ins = [[1,2],[2,3],[3,4], [5,6],[6,7],[7,8], [9,10],[10,11],[11,12],\n                    [4,25],[8,26],[12,27],\n                    [16,15],[15,14],[14,13], [20,19],[19,18],[18,17], [24,23],[23,22],[22,21],\n                    [13,28],[17,29],[21,30], [31,16],[32,20]]\n        for x in roll_ins:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # same-row roll-outs, skipping keys:\n        roll_ins_skip_keys = [[1,3],[2,4],[1,4], [5,7],[6,8],[5,8], [9,11],[10,12],[9,12],\n                              [1,25],[2,25],[3,25],\n                              [5,26],[6,26],[7,26],\n                              [9,27],[10,27],[11,27],\n                              [16,14],[15,13],[16,13], [20,18],[19,17],[20,17], [24,22],[23,21],[24,21],\n                              [16,28],[15,28],[14,28],\n                              [20,29],[19,29],[18,29],\n                              [24,30],[23,30],[22,30],\n                              [31,15],[31,14],[31,13],[31,28],\n                              [32,19],[32,18],[32,17],[32,29]]\n        for x in roll_ins_skip_keys:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # adjacent-row roll-outs:\n        #  1  2  3  4 25   28 13 14 15 16 31 \n        #  5  6  7  8 26   29 17 18 19 20 32\n        #  9 10 11 12 27   30 21 22 23 24\n        roll_ins_adj_rows = [[1,6],[1,7],[1,8],[2,7],[2,8],[3,8], \n                             [5,2],[5,3],[5,4],[6,3],[6,4],[7,4],\n                             [5,10],[5,11],[5,12],[6,11],[6,12],[7,12], \n                             [9,6],[9,7],[9,8],[10,7],[10,8],[11,8],\n                             [5,25],[6,25],[7,25],[8,25],\n                             [5,27],[6,27],[7,27],[8,27],\n                             [1,26],[2,26],[3,26],[4,26],\n                             [9,26],[10,26],[11,26],[12,26],\n                             [16,19],[16,18],[16,17],[15,18],[15,17],[14,17], \n                             [20,15],[20,14],[20,13],[19,14],[19,13],[18,13],\n                             [20,23],[20,22],[20,21],[19,22],[19,21],[18,21], \n                             [24,19],[24,18],[24,17],[23,18],[23,17],[22,17],\n                             [16,29],[15,29],[14,29],[13,29],\n                             [24,29],[23,29],[22,29],[21,29],\n                             [20,28],[19,28],[18,28],[17,28],\n                             [20,30],[19,30],[18,30],[17,30],\n                             [31,20],[31,19],[31,18],[31,17],[31,29],\n                             [32,16],[32,15],[32,14],[32,13],[32,28],\n                             [32,24],[32,23],[32,22],[32,21],[32,30]]\n        for x in roll_ins_adj_rows:\n            T[x[1]-1, x[0]-1] *= outward\n\n        # upper<->lower row roll-outs:\n        roll_ins_skip_home = [[1,10],[1,11],[1,12],[1,27],[2,11],[2,12],[2,27],[3,12],[3,27],[4,27], \n                              [9,2],[9,3],[9,4],[9,25],[10,3],[10,4],[10,25],[11,4],[11,25],[12,25],\n                              [16,23],[16,22],[16,21],[16,30],[15,22],[15,21],[15,30],[14,21],[14,30],[13,30],\n                              [24,15],[24,14],[24,13],[24,28],[23,14],[23,13],[23,28],[22,13],[22,28],[21,28],\n                              [31,24],[31,23],[31,22],[31,21],[31,30]]\n        for x in roll_ins_skip_home:\n            T[x[1]-1, x[0]-1] *= outward\n\n    # 9.  Avoid stretching shorter fingers up and longer fingers down.\n    #  1  2  3  4 25   28 13 14 15 16 31 \n    #  5  6  7  8 26   29 17 18 19 20 32\n    #  9 10 11 12 27   30 21 22 23 24\n    if index_above < 1.0:\n        for x in [4]:\n            for y in [4,5,6,7,8,26,9,10,11,12,27,28,13,14,15,16,31,29,17,18,19,20,32,30,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n        for x in [25]:\n            for y in [25,5,6,7,8,26,9,10,11,12,27,28,13,14,15,16,31,29,17,18,19,20,32,30,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n        for x in [13]:\n            for y in [1,2,3,4,25,5,6,7,8,26,9,10,11,12,27,13,29,17,18,19,20,32,30,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n        for x in [28]:\n            for y in [1,2,3,4,25,5,6,7,8,26,9,10,11,12,27,28,29,17,18,19,20,32,30,21,22,23,24]:\n                T[x-1, y-1] *= index_above\n                T[y-1, x-1] *= index_above\n    if inside_top < 1.0:\n        for x in [4,25,28,13]:\n            for j in range(0,32):\n                T[x-1, j] *= inside_top\n                T[j, x-1] *= inside_top\n    if side_top < 1.0:\n        for x in [1,4,25,28,13,16,31]:\n            for j in range(0,32):\n                T[x-1, j] *= side_top\n                T[j, x-1] *= side_top\n    if side_above_1away < 1.0:\n        for x in [1]:\n            for y in [6,10]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [5]:\n            for y in [10]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [4,25]:\n            for y in [7,11]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [8,26]:\n            for y in [11]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [13,28]:\n            for y in [18,22]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [17,29]:\n            for y in [22]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [16,31]:\n            for y in [19,23]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n        for x in [20,32]:\n            for y in [23]:\n                T[x-1, y-1] *= side_above_1away\n                T[y-1, x-1] *= side_above_1away\n    if side_above_2away < 1.0:\n        for x in [1]:\n            for y in [7,11]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [5]:\n            for y in [11]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [4,25]:\n            for y in [6,10]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [8,26]:\n            for y in [10]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [13,28]:\n            for y in [19,23]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [17,29]:\n            for y in [23]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [16,31]:\n            for y in [18,22]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n        for x in [20,32]:\n            for y in [22]:\n                T[x-1, y-1] *= side_above_2away\n                T[y-1, x-1] *= side_above_2away\n    if side_above_3away < 1.0:\n        for x in [1]:\n            for y in [8,12,26,27]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [5]:\n            for y in [12,27]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [4,25]:\n            for y in [5,9]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [8,26]:\n            for y in [9]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [13,28]:\n            for y in [20,24,32]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [17,29]:\n            for y in [24]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [16,31]:\n            for y in [17,21,29,30]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n        for x in [20,32]:\n            for y in [21,30]:\n                T[x-1, y-1] *= side_above_3away\n                T[y-1, x-1] *= side_above_3away\n\n\n    #  1  2  3  4 25   28 13 14 15 16 31 \n    #  5  6  7  8 26   29 17 18 19 20 32\n    #  9 10 11 12 27   30 21 22 23 24\n    if shorter_above < 1.0:\n        for x in [1]:\n            for y in [6,7,8,26,10,11,12,27]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [2]:\n            for y in [7,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [4]:\n            for y in [6,7,10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [25]:\n            for y in [6,7,10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [5]:\n            for y in [10,11,12,27]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [6]:\n            for y in [11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [8]:\n            for y in [10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [26]:\n            for y in [10,11]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [16]:\n            for y in [29,17,18,19,30,21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [31]:\n            for y in [29,17,18,19,30,21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [15]:\n            for y in [18,22]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [13]:\n            for y in [18,19,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [28]:\n            for y in [18,19,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n        for x in [20]:\n            for y in [30,21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [32]:\n            for y in [30,21,22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [19]:\n            for y in [22]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [17]:\n            for y in [22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n        for x in [29]:\n            for y in [22,23]:\n                T[x-1, y-1] *= shorter_above\n                T[y-1, x-1] *= shorter_above\n\n    if ring_above_middle < 1.0:\n        ring_above_middles =  [[2,7],[6,11],[2,11],\n                            [15,18],[19,22],[15,22]]\n        for x in ring_above_middles:\n            T[x[0]-1, x[1]-1] *= ring_above_middle\n            T[x[1]-1, x[0]-1] *= ring_above_middle\n\n    if middle_above_ring < 1.0:\n        middle_above_rings =  [[6,3],[10,7],[10,3],\n                            [19,14],[23,18],[23,14]]\n        for x in middle_above_rings:\n            T[x[0]-1, x[1]-1] *= middle_above_ring\n            T[x[1]-1, x[0]-1] *= middle_above_ring\n\n    # 10. Avoid using the same finger.\n    #  1  2  3  4 25   28 13 14 15 16 31 \n    #  5  6  7  8 26   29 17 18 19 20 32\n    #  9 10 11 12 27   30 21 22 23 24\n    if same_finger < 1.0:\n        same_fingers = [[1,5],[5,9],[1,9], [2,6],[6,10],[2,10], \n                        [3,7],[7,11],[3,11], [4,8],[8,12],[4,12],\n                        [25,26],[26,27],[25,27], [28,29],[29,30],[28,30], [31,32],\n                        [4,25],[4,26],[4,27], [8,25],[8,26],[8,27], [12,25],[12,26],[12,27],\n                        [13,28],[13,29],[13,30], [17,28],[17,29],[17,30], [21,28],[21,29],[21,30],\n                        [31,16],[31,20],[31,24], [32,16],[32,20],[32,24],\n                        [13,17],[17,21],[13,21], [14,18],[18,22],[14,22], \n                        [15,19],[19,23],[15,23], [16,20],[20,24],[16,24]] \n        for x in same_fingers:\n            T[x[0]-1, x[1]-1] *= same_finger\n            T[x[1]-1, x[0]-1] *= same_finger\n\n    # 11. Avoid the upper and lower rows.\n    if not_home_row < 1.0:\n        not_home_row_keys = [1,2,3,4,25, 9,10,11,12,27, 28,13,14,15,16,31, 30,21,22,23,24]\n        for x in not_home_row_keys:\n            for j in range(0,32):\n                T[x-1, j] *= not_home_row\n                T[j, x-1] *= not_home_row\n                \n    # 12. Avoid skipping over the home row.\n    #  1  2  3  4 25   28 13 14 15 16 31 \n    #  5  6  7  8 26   29 17 18 19 20 32\n    #  9 10 11 12 27   30 21 22 23 24\n    if skip_row_0away < 1.0:\n        skip_top = [1, 2, 3, 4, 4,25,25, 28,28,13,13,14,15,16,31] \n        skip_bot = [9,10,11,12,27,12,27, 30,21,30,21,22,23,24,24] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_0away\n            T[y-1, x-1] *= skip_row_0away\n    if skip_row_1away < 1.0:\n        skip_top = [1, 2, 2, 3, 3, 4, 4,25, 28,13,13,14,14,15,15,16,31] \n        skip_bot = [10,9,11,10,12,11,27,11, 22,30,22,21,23,22,24,23,23] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_1away\n            T[y-1, x-1] *= skip_row_1away\n    if skip_row_2away < 1.0:\n        skip_top = [1,  2,3, 4,25, 28,13,14,15,16,31] \n        skip_bot = [11,12,9,10,10, 23,23,24,21,22,22] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_2away\n            T[y-1, x-1] *= skip_row_2away\n    if skip_row_3away < 1.0:\n        skip_top = [1, 4,25, 28,13,16,16,31,31] \n        skip_bot = [12,9, 9, 24,24,21,30,21,30] \n        for ix, x in enumerate(skip_top):\n            y = skip_bot[ix]\n            T[x-1, y-1] *= skip_row_3away\n            T[y-1, x-1] *= skip_row_3away\n                \n    Flow32x32 = T\n\n    # Normalize matrix with min-max scaling to a range with maximum = 1:\n    newMin = np.min(Flow32x32) / np.max(Flow32x32)\n    newMax = 1.0\n    Flow32x32 = newMin + (Flow32x32 - np.min(Flow32x32)) * (newMax - newMin) / (np.max(Flow32x32) - np.min(Flow32x32))\n\n    return Flow32x32\n\nFlow32x32 = create_32x32_flow_matrix(not_home_row, side_top, \n    side_above_3away, side_above_2away, side_above_1away, middle_above_ring, ring_above_middle, outward, \n    skip_row_3away, skip_row_2away, skip_row_1away, skip_row_0away, same_finger, lateral, same_hand, \n    shorter_above, adjacent_offset, inside_top, index_above)\n\n# Print:\nprint_matrix_info(matrix_data=Flow32x32, matrix_label=\"Flow32x32\", nkeys=32, nlines=30)\nheatmap(data=Flow32x32, title=\"Flow32x32\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n# Save:\nif print_output:\n    file = open(\"Flow32x32.txt\", \"w+\")\n    file.write(str(Flow32x32))\n    file.close()\n\n#  1  2  3  4 25   28 13 14 15 16 31 \n#  5  6  7  8 26   29 17 18 19 20 32\n#  9 10 11 12 27   30 21 22 23 24\n```\n\n## Combine Speed, Strength, and Flow matrices  <a name=\"speedstrengthflow\">\n\n\n```python\n# 24 keys:\nFactors24x24 = Flow24x24\nif apply_strength:\n    Factors24x24 = Strength24x24 * Factors24x24\n\n# Print:\nprint_matrix_info(matrix_data=Factors24x24, matrix_label=\"Factors24x24\", nkeys=24, nlines=30)\nheatmap(data=Factors24x24, title=\"Factors24x24\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n# Save:\nif print_output:\n    file = open(\"Factors24x24.txt\", \"w+\")\n    file.write(str(Factors24x24))\n    file.close()\n```\n\n\n```python\n# 32 keys:\nFactors32x32 = Flow32x32\nif apply_strength:\n    Factors32x32 = Strength32x32 * Factors32x32\n\n# Print:\nprint_matrix_info(matrix_data=Factors32x32, matrix_label=\"Factors32x32\", nkeys=32, nlines=30)\nheatmap(data=Factors32x32, title=\"Factors32x32\", xlabel=\"Key 1\", ylabel=\"Key 2\", print_output=print_output)\n\n# Save:\nif print_output:\n    file = open(\"Factors32x32.txt\", \"w+\")\n    file.write(str(Factors32x32))\n    file.close()\n```\n\n## Compare layouts based on interkey speed <a name=\"speed\">\n\nThe Speed matrix contains left-right averaged versions of the normalized interkey stroke times derived from the study (averaged to compensate for right-handedness of participants in the study):\n\n\"Estimation of digraph costs for keyboard layout optimization\", \nA Iseri, Ma Eksioglu, International Journal of Industrial Ergonomics, 48, 127-138, 2015. \n\n\n```python\ndata_matrix_speed = Speed32x32\ntime_range = 243  # ms\nnorm_range = 0.1  # 1.0 - 0.9\nms_norm = norm_range / time_range  # 0.000411522633744856\nepsilon = 131.58 * ms_norm / (24**2)  # 0.000411522633744856\nspeed_scores = []\nfor letters in layout_letters:\n    score = score_layout(data_matrix_speed, letters, bigrams, bigram_frequencies, verbose = False) \n    speed_scores.append(score)\nspeed_scores_sorted, speed_ranks_sorted, Isort_speed = rank_within_epsilon(speed_scores, epsilon, \n                                                                           factor=False, verbose=False)\nprint('\\nRank:   Layout                                             Speed score\\n')\nfor i, rank in enumerate(speed_ranks_sorted):\n    print('    {0}:  {1}    {2}'.format(rank, layout_names[Isort_speed[i]], speed_scores_sorted[i]))\n```\n\n    \n    Rank:   Layout                                             Speed score\n    \n        1:  QGMLWB    0.6861533242912506\n        1:  Klausler    0.6860694668614524\n        2:  Capewell-Dvorak    0.6859513060623683\n        2:  Colemak    0.6859470551002004\n        2:  Halmak    0.685862612295209\n        3:  Dvorak    0.6858445848850323\n        3:  Colemak Mod-DH    0.6857730319204565\n        3:  Asset    0.685754337946507\n        4:  Norman    0.685665752679605\n        4:  Workman    0.6855719203274142\n        5:  Hieamtsrn    0.6855318822756586\n        6:  MTGap 2.0    0.6854281396438425\n        7:  Engram    0.6852535258142791\n        8:  QWERTY    0.6843830181015049\n\n\n## Score layouts using Engram's scoring model  <a name=\"Engram\">\n\n\n\n```python\nlayout_strings = []\nlayout_scores = []\nfor layout in layout_letters:\n    layout_string = ' '.join(layout)\n    score = score_layout(Factors32x32, layout, bigrams, bigram_frequencies, verbose=False)\n    layout_strings.append(layout_string)\n    layout_scores.append(score)\n\n# Establish which layouts are within a negligible difference of the top-scoring layout \n# (the smallest difference between two penalties, 0.9^8 - 0.9^9, in one of 24^2 key pairs):\ndelta = 0.9**9 - 0.9**10\nfactor = ((24**2 - 1) + (1-delta)) / (24**2)\nprint('delta = {0}'.format(delta))    # delta  = 0.030205665244067793\nprint('factor = {0}'.format(factor))  # factor = 0.9999475596089513\nscores_sorted, ranks_sorted, Isort = rank_within_epsilon(layout_scores, factor, factor=True, verbose=False)\nprint('\\nRank:   Layout    Score\\n')\nfor i, rank in enumerate(ranks_sorted):\n    print('    {0}:  {1}    {2}'.format(rank, layout_names[Isort[i]], scores_sorted[i]))\n```\n\n    delta = 0.03874204889999999\n    factor = 0.9999327394984375\n    \n    Rank:   Layout    Score\n    \n        1:  Engram    0.7502800189214918\n        2:  Hieamtsrn    0.7500834009709707\n        3:  Halmak    0.7497573328046871\n        4:  Colemak Mod-DH    0.7495486801335415\n        5:  Workman    0.7494146282157065\n        6:  MTGap 2.0    0.7493590057152013\n        6:  Colemak    0.749323071527497\n        7:  Klausler    0.7491985680682132\n        8:  Norman    0.7491174419277558\n        8:  QGMLWB    0.749104616280684\n        9:  Dvorak    0.749046337831136\n        9:  Capewell-Dvorak    0.7490444795507138\n        10:  Asset    0.7489782990946122\n        11:  QWERTY    0.7476139840325112\n\n\ndelta = 0.03874204889999999\nfactor = 0.9999327394984375\n\nRank:   Layout    Score\n\n    1:  Engram    0.7502800189214918\n    2:  Hieamtsrn    0.7500834009709707\n    3:  Halmak    0.7497573328046871\n    4:  Colemak Mod-DH    0.7495486801335415\n    5:  Workman    0.7494146282157065\n    6:  MTGap 2.0    0.7493590057152013\n    6:  Colemak    0.749323071527497\n    7:  Klausler    0.7491985680682132\n    8:  Norman    0.7491174419277558\n    8:  QGMLWB    0.749104616280684\n    9:  Dvorak    0.749046337831136\n    9:  Capewell-Dvorak    0.7490444795507138\n    10:  Asset    0.7489782990946122\n    11:  QWERTY    0.7476139840325112\n\n## Score layouts using Engram's scoring model and on **bigram frequency of input text**\n\n\n```python\nimport requests\ndata_matrix = Factors32x32\nscore_table = []\nfor iurl, url in enumerate(urls):\n    print(\"\")\n    print(text_names[iurl])\n    input_text = requests.get(url).text\n    bigram_frequencies_for_input = tally_bigrams(input_text, bigrams, normalize=True, verbose=False)\n    scores = []\n    for letters in layout_letters:\n        score = score_layout(data_matrix, letters, bigrams, bigram_frequencies_for_input, verbose=False) \n        scores.append(score)    \n    score_table.append(scores)\n    \n    scores_sorted, ranks_sorted, Isort = rank_within_epsilon(scores, factor, factor=True, verbose=False)\n    print('Rank:   Layout    Score\\n')\n    for i, rank in enumerate(ranks_sorted):\n        print('    {0}:  {1}    {2}'.format(rank, layout_names[Isort[i]], scores_sorted[i]))\n\n```\n\n    \n    Alice in Wonderland (Ch.1)\n    Rank:   Layout    Score\n    \n        1:  Engram    0.7445255116363066\n        1:  Hieamtsrn    0.744493247399194\n        2:  Halmak    0.7442057522674784\n        3:  Colemak Mod-DH    0.7440356104330337\n        4:  Workman    0.7439343955531742\n        4:  MTGap 2.0    0.7438995028076142\n        5:  Klausler    0.7437895427905579\n        5:  Norman    0.7437646134256715\n        6:  Colemak    0.7437360174144916\n        6:  Dvorak    0.7437064077057469\n        6:  QGMLWB    0.7437042138107322\n        7:  Capewell-Dvorak    0.7436828469800179\n        8:  Asset    0.7435558904639417\n        9:  QWERTY    0.7427495880005877\n    \n    Romeo and Juliet\n    Rank:   Layout    Score\n    \n        1:  Engram    0.7462377983440776\n        2:  Hieamtsrn    0.7460656954751297\n        3:  Halmak    0.7458215328584193\n        4:  Workman    0.7455477191686165\n        4:  Colemak Mod-DH    0.7455256248234188\n        5:  Klausler    0.7453959154393313\n        5:  MTGap 2.0    0.7453842638318341\n        6:  Colemak    0.7453252513174218\n        6:  Dvorak    0.7452977776069954\n        7:  Capewell-Dvorak    0.7452314494639884\n        7:  Norman    0.745223159420264\n        7:  QGMLWB    0.7451915241331577\n        8:  Asset    0.7451023744367409\n        9:  QWERTY    0.744081753045933\n    \n    Bhagavad Gita\n    Rank:   Layout    Score\n    \n        1:  Engram    0.7445033030573653\n        2:  Hieamtsrn    0.7442748977532957\n        3:  Halmak    0.7440452984963499\n        4:  Colemak Mod-DH    0.7439342924524047\n        5:  Workman    0.7438122187336434\n        5:  MTGap 2.0    0.7437662911568246\n        6:  Colemak    0.7436881695039714\n        6:  Norman    0.7436867028525271\n        6:  Klausler    0.7436685333496726\n        7:  Capewell-Dvorak    0.7435464823703208\n        7:  QGMLWB    0.7435306808518158\n        8:  Dvorak    0.7434626744010637\n        8:  Asset    0.7434623523413765\n        9:  QWERTY    0.7425000899359803\n    \n    Memento screenplay\n    Rank:   Layout    Score\n    \n        1:  Engram    0.7512152417182343\n        2:  Hieamtsrn    0.7510946267517449\n        3:  Halmak    0.7508156056439149\n        4:  Workman    0.7505223925174471\n        4:  Colemak Mod-DH    0.7504919649032535\n        5:  MTGap 2.0    0.7504656165787917\n        6:  Klausler    0.7502677083821565\n        6:  Norman    0.7502270589073867\n        7:  Colemak    0.7501786479496046\n        7:  QGMLWB    0.7501687105387891\n        8:  Dvorak    0.7501129491835481\n        8:  Asset    0.7500924821648107\n        8:  Capewell-Dvorak    0.7500775044779536\n        9:  QWERTY    0.7487788244686439\n    \n    100,000 tweets (Sentiment Classification)\n    Rank:   Layout    Score\n    \n        1:  Engram    0.7587999922922919\n        2:  Hieamtsrn    0.7586168740935535\n        3:  Halmak    0.7582395052093746\n        4:  Workman    0.7577024398478142\n        4:  Colemak Mod-DH    0.7576779309668868\n        5:  Klausler    0.7575363748102988\n        6:  MTGap 2.0    0.7574813328516148\n        6:  Colemak    0.7574556435729025\n        7:  Capewell-Dvorak    0.7573431687255685\n        7:  QGMLWB    0.757320932589792\n        7:  Dvorak    0.7572958623751398\n        8:  Norman    0.7571830591612143\n        8:  Asset    0.7571405619681301\n        9:  QWERTY    0.7555352038036853\n    \n    20,000 tweets (Gender classifier)\n    Rank:   Layout    Score\n    \n        1:  Engram    0.7552965804045838\n        2:  Hieamtsrn    0.7550272024359316\n        3:  Halmak    0.7548698754255334\n        4:  Workman    0.7544061351998617\n        5:  Colemak Mod-DH    0.7542576164427959\n        6:  MTGap 2.0    0.7541862651670737\n        6:  Klausler    0.7541543581594552\n        7:  QGMLWB    0.7540478766683447\n        7:  Colemak    0.7540154496489697\n        8:  Dvorak    0.7539848148930088\n        9:  Norman    0.7539294799193212\n        9:  Capewell-Dvorak    0.7539273986075242\n        10:  Asset    0.7538682010194889\n        11:  QWERTY    0.7524505187684718\n    \n    Manually Annotated Sub-Corpus tweets\n    Rank:   Layout    Score\n    \n        1:  Engram    0.7533480668588272\n        2:  Hieamtsrn    0.7531820679715767\n        3:  Halmak    0.7529324116257463\n        4:  Workman    0.7525105553955649\n        4:  Colemak Mod-DH    0.7525080965567097\n        5:  Colemak    0.7523565520021861\n        5:  MTGap 2.0    0.7523433819792806\n        6:  Klausler    0.7522483472854136\n        7:  Capewell-Dvorak    0.7521326792734249\n        7:  Norman    0.7521038803161461\n        8:  Asset    0.7520775593833018\n        8:  QGMLWB    0.7520768580635181\n        8:  Dvorak    0.7520330473326271\n        9:  QWERTY    0.7505885443443292\n    \n    Manually Annotated Sub-Corpus spoken transcripts\n    Rank:   Layout    Score\n    \n        1:  Engram    0.7434425867319531\n        2:  Hieamtsrn    0.7433517532910301\n        3:  Halmak    0.7432427823998995\n        4:  Colemak Mod-DH    0.7429249638168247\n        5:  Workman    0.7428572062163613\n        5:  Klausler    0.7428276880174356\n        5:  MTGap 2.0    0.7428240293514123\n        6:  Colemak    0.7427099901825774\n        6:  Dvorak    0.7427060150669405\n        6:  Norman    0.7427020077511466\n        6:  QGMLWB    0.7426988315541281\n        6:  Capewell-Dvorak    0.7426714144608173\n        7:  Asset    0.7425384406227465\n        8:  QWERTY    0.7416605861014668\n    \n    Corpus of Contemporary American English blog samples\n    Rank:   Layout    Score\n    \n        1:  Engram    0.7501455184936774\n        2:  Hieamtsrn    0.749994950272338\n        3:  Halmak    0.749700591743684\n        4:  Colemak Mod-DH    0.7494009108078719\n        5:  Workman    0.7492640087504288\n        5:  MTGap 2.0    0.7492386935334041\n        6:  Colemak    0.7492021340914676\n        7:  Klausler    0.7491392455141934\n        8:  Norman    0.7490127631985506\n        8:  QGMLWB    0.7489940237147004\n        8:  Dvorak    0.7489734586791237\n        8:  Capewell-Dvorak    0.7489658091510272\n        9:  Asset    0.7488977328623273\n        10:  QWERTY    0.7475868749135686\n    \n    Shai Coleman iweb corpus 1/6\n    Rank:   Layout    Score\n    \n        1:  Engram    0.7521347709412141\n        2:  Hieamtsrn    0.7520036729279335\n        3:  Halmak    0.75166180756771\n        4:  Colemak Mod-DH    0.7513771807941114\n        5:  Workman    0.7512407288435894\n        5:  MTGap 2.0    0.7511903871554869\n        6:  Colemak    0.7511728954367094\n        7:  Klausler    0.7510475615168046\n        8:  QGMLWB    0.7509120402120495\n        8:  Norman    0.7508933637286321\n        9:  Dvorak    0.7508568692529449\n        9:  Capewell-Dvorak    0.7508385848273469\n        10:  Asset    0.7508000892455673\n        11:  QWERTY    0.7493885522364304\n    \n    Ian Douglas monkey test\n    Rank:   Layout    Score\n    \n        1:  Engram    0.7505454213423466\n        2:  Hieamtsrn    0.7503639994522184\n        3:  Halmak    0.7500371827818993\n        4:  Colemak Mod-DH    0.7498143793410694\n        5:  Workman    0.7496926152167988\n        5:  MTGap 2.0    0.7496466647443003\n        6:  Colemak    0.7495841296139549\n        7:  Klausler    0.7494730953935685\n        8:  Norman    0.7493731369594069\n        8:  QGMLWB    0.7493554938530738\n        8:  Capewell-Dvorak    0.7493255732707832\n        9:  Dvorak    0.7493181552668314\n        10:  Asset    0.7492490284295575\n        11:  QWERTY    0.7479005682987844\n    \n    Ian Douglas coder test\n    Rank:   Layout    Score\n    \n        1:  Engram    0.7536961822613741\n        2:  Hieamtsrn    0.7533973461263298\n        3:  Halmak    0.7531060564037025\n        4:  Colemak Mod-DH    0.7527937283736892\n        5:  MTGap 2.0    0.7527241488318342\n        5:  Workman    0.7527164432424885\n        6:  Colemak    0.7526280882900735\n        7:  Klausler    0.7523386658724818\n        7:  QGMLWB    0.7523245037534942\n        8:  Asset    0.7522622878375567\n        9:  Norman    0.7521804570942231\n        9:  Capewell-Dvorak    0.7521666879809245\n        10:  Dvorak    0.7520437296522012\n        11:  QWERTY    0.7506074021395333\n    \n    Tower of Hanoi (programming languages A-Z, Rosetta Code)\n    Rank:   Layout    Score\n    \n        1:  Engram    0.7532761173759639\n        2:  Halmak    0.7526329210384023\n        3:  Hieamtsrn    0.7523366408821551\n        4:  Workman    0.7522024863650978\n        5:  Colemak    0.752027511093843\n        6:  Colemak Mod-DH    0.7518905851775592\n        6:  MTGap 2.0    0.7518484418995561\n        7:  Asset    0.7518262567944902\n        8:  Klausler    0.7517367700623173\n        8:  Dvorak    0.7517180298601622\n        8:  Norman    0.7516863991804899\n        9:  Capewell-Dvorak    0.7514798352785976\n        10:  QGMLWB    0.7512629231413269\n        11:  QWERTY    0.7500582925513382\n\n\n\n```python\nscore_matrix = np.array(score_table).transpose()\n#print(score_matrix)\nprint(\"\")\nprint(\"| Layout | Google bigrams |\", end='')\nfor itext in range(len(text_names)):\n    print(\" {0} |\".format(text_abbrs[itext]), end='')\nprint(\"\")\nprint(\"| --- | --- |\", end='')\nfor itext in range(len(text_names)):\n    print(\" --- |\", end='')\nfor ilayout in range(len(layout_names)):\n    print(\"\")\n    print(\"| {0} | {1:0.2f} |\".format(layout_names[ilayout], 100*layout_scores[ilayout]), end='')\n    for itext in range(len(text_names)):\n        print(\" {0:0.2f} |\".format(100*score_matrix[ilayout, itext]), end='')\n```\n\n    \n    | Layout | Google bigrams | Alice | Romeo | Gita | Memento | 100K tweets | 20K tweets | MASC tweets | MASC spoken | COCA blogs | iweb | Monkey | Coder | Code |\n    | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n    | Engram | 75.03 | 74.45 | 74.62 | 74.45 | 75.12 | 75.88 | 75.53 | 75.33 | 74.34 | 75.01 | 75.21 | 75.05 | 75.37 | 75.33 |\n    | Halmak | 74.98 | 74.42 | 74.58 | 74.40 | 75.08 | 75.82 | 75.49 | 75.29 | 74.32 | 74.97 | 75.17 | 75.00 | 75.31 | 75.26 |\n    | Hieamtsrn | 75.01 | 74.45 | 74.61 | 74.43 | 75.11 | 75.86 | 75.50 | 75.32 | 74.34 | 75.00 | 75.20 | 75.04 | 75.34 | 75.23 |\n    | Colemak Mod-DH | 74.95 | 74.40 | 74.55 | 74.39 | 75.05 | 75.77 | 75.43 | 75.25 | 74.29 | 74.94 | 75.14 | 74.98 | 75.28 | 75.19 |\n    | Norman | 74.91 | 74.38 | 74.52 | 74.37 | 75.02 | 75.72 | 75.39 | 75.21 | 74.27 | 74.90 | 75.09 | 74.94 | 75.22 | 75.17 |\n    | Workman | 74.94 | 74.39 | 74.55 | 74.38 | 75.05 | 75.77 | 75.44 | 75.25 | 74.29 | 74.93 | 75.12 | 74.97 | 75.27 | 75.22 |\n    | MTGap 2.0 | 74.94 | 74.39 | 74.54 | 74.38 | 75.05 | 75.75 | 75.42 | 75.23 | 74.28 | 74.92 | 75.12 | 74.96 | 75.27 | 75.18 |\n    | QGMLWB | 74.91 | 74.37 | 74.52 | 74.35 | 75.02 | 75.73 | 75.40 | 75.21 | 74.27 | 74.90 | 75.09 | 74.94 | 75.23 | 75.13 |\n    | Colemak | 74.93 | 74.37 | 74.53 | 74.37 | 75.02 | 75.75 | 75.40 | 75.24 | 74.27 | 74.92 | 75.12 | 74.96 | 75.26 | 75.20 |\n    | Asset | 74.90 | 74.36 | 74.51 | 74.35 | 75.01 | 75.71 | 75.39 | 75.21 | 74.25 | 74.89 | 75.08 | 74.92 | 75.23 | 75.18 |\n    | Capewell-Dvorak | 74.90 | 74.37 | 74.52 | 74.35 | 75.01 | 75.73 | 75.39 | 75.21 | 74.27 | 74.90 | 75.08 | 74.93 | 75.22 | 75.15 |\n    | Klausler | 74.92 | 74.38 | 74.54 | 74.37 | 75.03 | 75.75 | 75.42 | 75.22 | 74.28 | 74.91 | 75.10 | 74.95 | 75.23 | 75.17 |\n    | Dvorak | 74.90 | 74.37 | 74.53 | 74.35 | 75.01 | 75.73 | 75.40 | 75.20 | 74.27 | 74.90 | 75.09 | 74.93 | 75.20 | 75.17 |\n    | QWERTY | 74.76 | 74.27 | 74.41 | 74.25 | 74.88 | 75.55 | 75.25 | 75.06 | 74.17 | 74.76 | 74.94 | 74.79 | 75.06 | 75.01 |\n\n## Engram Scoring Model scores (x100) for layouts, based on publicly available text data\n\n| Layout | Google bigrams | Alice | Romeo | Gita | Memento | 100K tweets | 20K tweets | MASC tweets | MASC spoken | COCA blogs | iweb | Monkey | Coder | Code |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Engram | 75.03 | 74.45 | 74.62 | 74.45 | 75.12 | 75.88 | 75.53 | 75.33 | 74.34 | 75.01 | 75.21 | 75.05 | 75.37 | 75.33 |\n| Halmak | 74.98 | 74.42 | 74.58 | 74.40 | 75.08 | 75.82 | 75.49 | 75.29 | 74.32 | 74.97 | 75.17 | 75.00 | 75.31 | 75.26 |\n| Hieamtsrn | 75.01 | 74.45 | 74.61 | 74.43 | 75.11 | 75.86 | 75.50 | 75.32 | 74.34 | 75.00 | 75.20 | 75.04 | 75.34 | 75.23 |\n| Colemak Mod-DH | 74.95 | 74.40 | 74.55 | 74.39 | 75.05 | 75.77 | 75.43 | 75.25 | 74.29 | 74.94 | 75.14 | 74.98 | 75.28 | 75.19 |\n| Norman | 74.91 | 74.38 | 74.52 | 74.37 | 75.02 | 75.72 | 75.39 | 75.21 | 74.27 | 74.90 | 75.09 | 74.94 | 75.22 | 75.17 |\n| Workman | 74.94 | 74.39 | 74.55 | 74.38 | 75.05 | 75.77 | 75.44 | 75.25 | 74.29 | 74.93 | 75.12 | 74.97 | 75.27 | 75.22 |\n| MTGap 2.0 | 74.94 | 74.39 | 74.54 | 74.38 | 75.05 | 75.75 | 75.42 | 75.23 | 74.28 | 74.92 | 75.12 | 74.96 | 75.27 | 75.18 |\n| QGMLWB | 74.91 | 74.37 | 74.52 | 74.35 | 75.02 | 75.73 | 75.40 | 75.21 | 74.27 | 74.90 | 75.09 | 74.94 | 75.23 | 75.13 |\n| Colemak | 74.93 | 74.37 | 74.53 | 74.37 | 75.02 | 75.75 | 75.40 | 75.24 | 74.27 | 74.92 | 75.12 | 74.96 | 75.26 | 75.20 |\n| Asset | 74.90 | 74.36 | 74.51 | 74.35 | 75.01 | 75.71 | 75.39 | 75.21 | 74.25 | 74.89 | 75.08 | 74.92 | 75.23 | 75.18 |\n| Capewell-Dvorak | 74.90 | 74.37 | 74.52 | 74.35 | 75.01 | 75.73 | 75.39 | 75.21 | 74.27 | 74.90 | 75.08 | 74.93 | 75.22 | 75.15 |\n| Klausler | 74.92 | 74.38 | 74.54 | 74.37 | 75.03 | 75.75 | 75.42 | 75.22 | 74.28 | 74.91 | 75.10 | 74.95 | 75.23 | 75.17 |\n| Dvorak | 74.90 | 74.37 | 74.53 | 74.35 | 75.01 | 75.73 | 75.40 | 75.20 | 74.27 | 74.90 | 75.09 | 74.93 | 75.20 | 75.17 |\n| QWERTY | 74.76 | 74.27 | 74.41 | 74.25 | 74.88 | 75.55 | 75.25 | 75.06 | 74.17 | 74.76 | 74.94 | 74.79 | 75.06 | 75.01 |\n\n\n## [Carpalx](http://mkweb.bcgsc.ca/carpalx/?keyboard_layouts) scores <a name=\"CarpalX\">\n\nThese scores are computed based on literature from the Gutenberg Project.\n    \n| Layout | home row use (%) | hand symmetry (%, right<0) | hand switching (%) | finger switching (%) | hand runs without row jumps (%) | base effort  | penalties | path effort | total effort |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Engram |  |  |  |  |  |  |  |  |  |\n| Hieamtsrn | 65 | -96 | 59 | 93 | 85 | 0.38 | 0.848 | 0.720 | 1.948 |\n| Halmak | 64 | 99 | 63 | 93 | 81 | 0.325 | 1.175 | 0.823 | 2.322 |\n| Norman | 68 | 95 | 52 | 90 | 77 | 0.342 | 0.812 | 0.838 | 1.992 |\n| Workman | 68 | 95 | 52 | 93 | 79 | 0.336 | 0.848 | 0.809 | 1.993 |\n| MTGAP 2.0 | 68 | 98 | 48 | 93 | 76 | 0.327 | 0.839 | 0.815 | 1.981 |\n| QGMLWB | 74 | -97 | 57 | 91 | 84 | 0.382 | 0.570 | 0.716 | 1.668 |\n| BEAKL 15 | 57 | -95 | 59 | 91 | 80 | 0.473 | 0.663 | 0.809 | 1.945 |\n| Colemak Mod-DH | 68 | -94 | 52 | 93 | 78 | 0.335 | 0.842 | 0.781 | 1.958 |\n| Colemak | 74 | -94 | 52 | 93 | 83 | 0.344 | 0.763 | 0.735 | 1.842 |\n| Asset | 74 | 96 | 52 | 91 | 82 | 0.356 | 0.766 | 0.772 | 1.894 |\n| Capewell-Dvorak | 71 | -91 | 59 | 92 | 82 | 0.333 | 0.878 | 0.774 | 1.985 |\n| Klausler | 74 | -94 | 62 | 93 | 86 | 0.341 | 0.797 | 0.729 | 1.867 |\n| Dvorak | 71 | -86 | 62 | 93 | 84 | 0.397 | 0.937 | 0.765 | 2.098 |\n| QWERTY | 34 | 85 | 51 | 89 | 68 | 1 | 1 | 1 | 3 |\n\n\n## Score layouts using the Keyboard Layout Analyzer <a name=\"KLAscores\">\n    \n[Keyboard Layout Analyzer](http://patorjk.com/keyboard-layout-analyzer/) (KLA) scores for the same text sources:\n\n> The optimal layout score is based on a weighted calculation that factors in the distance your fingers moved (33%), how often you use particular fingers (33%), and how often you switch fingers and hands while typing (34%).\n\n| Layout | Alice in Wonderland | Romeo Juliet | Bhagavad Gita | Memento screenplay | 100K tweets | 20K tweets | MASC tweets | MASC spoken | COCA blogs | iweb | Monkey | Coder | Software languages |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Engram    | 69.10 | 61.26 | 61.68 | 56.50 | 63.87 | 58.64 | 60.05 | 63.64 | 69.45 | 68.26 | 67.64 | 47.70 | 48.73 |\n| Halmak    | 66.25 | 57.02 | 57.45 | 55.03 | 60.86 | 55.53 | 57.13 | 62.32 | 67.29 | 65.50 | 64.75 | 45.68 | 47.60 |\n| Hieamtsrn | 69.43 | 60.94 | 60.87 | 56.75 | 64.40 | 58.95 | 60.47 | 64.33 | 69.93 | 69.15 | 68.30 | 46.01 | 46.48 | \n| Colemak Mod-DH | 65.74 | 56.05 | 57.52 | 54.91 | 60.75 | 54.94 | 57.15 | 61.29 | 67.12 | 65.98 | 64.85 | 47.35 | 48.50 |\n| Norman    | 62.76 | 53.21 | 53.44 | 52.33 | 57.43 | 53.24 | 53.90 | 59.97 | 62.80 | 60.90 | 59.82 | 43.76 | 46.01 |\n| Workman   | 64.78 | 56.67 | 56.97 | 54.29 | 59.98 | 55.81 | 56.25 | 61.34 | 65.27 | 63.76 | 62.90 | 45.33 | 47.76 |\n| MTGAP 2.0 | 66.13 | 53.98 | 56.57 | 53.78 | 59.87 | 55.30 | 55.81 | 60.32 | 65.68 | 63.81 | 62.74 | 45.38 | 44.34 | \n| QGMLWB    | 65.45 | 55.67 | 55.57 | 54.07 | 60.51 | 56.05 | 56.90 | 62.23 | 66.26 | 64.76 | 63.91 | 46.38 | 45.72 |\n| Colemak   | 65.83 | 56.12 | 57.63 | 54.94 | 60.67 | 54.97 | 57.04 | 61.36 | 67.14 | 66.01 | 64.91 | 47.30 | 48.65 |\n| Asset     | 64.60 | 54.63 | 56.09 | 53.84 | 58.66 | 54.72 | 55.35 | 60.81 | 64.71 | 63.17 | 62.44 | 45.54 | 47.52 |\n| Capewell-Dvorak | 66.94 | 58.31 | 57.39 | 55.66 | 62.14 | 56.85 | 57.99 | 62.83 | 66.95 | 65.23 | 64.70 | 45.30 | 45.62 |\n| Klausler  | 68.24 | 59.91 | 59.71 | 55.75 | 62.57 | 56.45 | 58.34 | 64.04 | 68.34 | 66.89 | 66.31 | 46.83 | 45.66 |\n| Dvorak    | 65.86 | 58.18 | 57.29 | 55.09 | 60.93 | 55.56 | 56.59 | 62.75 | 66.64 | 64.87 | 64.26 | 45.46 | 45.55 | \n| QWERTY    | 53.06 | 43.74 | 44.92 | 44.25 | 48.28 | 44.99 | 44.59 | 51.79 | 52.31 | 50.19 | 49.18 | 38.46 | 39.89 | \n\n\n## Average the Keyboard Layout Analysis scores\n\n\n```python\nKLA_scores = [                         \n    [69.10, 61.26, 61.68, 56.50, 63.87, 58.64, 60.05, 63.64, 69.45, 68.26, 67.64, 47.70, 48.73],\n    [66.25, 57.02, 57.45, 55.03, 60.86, 55.53, 57.13, 62.32, 67.29, 65.50, 64.75, 45.68, 47.60],\n    [69.43, 60.94, 60.87, 56.75, 64.40, 58.95, 60.47, 64.33, 69.93, 69.15, 68.30, 46.01, 46.48],\n    [65.74, 56.05, 57.52, 54.91, 60.75, 54.94, 57.15, 61.29, 67.12, 65.98, 64.85, 47.35, 48.50],\n    [62.76, 53.21, 53.44, 52.33, 57.43, 53.24, 53.90, 59.97, 62.80, 60.90, 59.82, 43.76, 46.01],\n    [64.78, 56.67, 56.97, 54.29, 59.98, 55.81, 56.25, 61.34, 65.27, 63.76, 62.90, 45.33, 47.76],\n    [66.13, 53.98, 56.57, 53.78, 59.87, 55.30, 55.81, 60.32, 65.68, 63.81, 62.74, 45.38, 44.34], \n    [65.45, 55.67, 55.57, 54.07, 60.51, 56.05, 56.90, 62.23, 66.26, 64.76, 63.91, 46.38, 45.72],\n    [65.83, 56.12, 57.63, 54.94, 60.67, 54.97, 57.04, 61.36, 67.14, 66.01, 64.91, 47.30, 48.65],\n    [64.60, 54.63, 56.09, 53.84, 58.66, 54.72, 55.35, 60.81, 64.71, 63.17, 62.44, 45.54, 47.52],\n    [66.94, 58.31, 57.39, 55.66, 62.14, 56.85, 57.99, 62.83, 66.95, 65.23, 64.70, 45.30, 45.62],\n    [68.24, 59.91, 59.71, 55.75, 62.57, 56.45, 58.34, 64.04, 68.34, 66.89, 66.31, 46.83, 45.66],\n    [65.86, 58.18, 57.29, 55.09, 60.93, 55.56, 56.59, 62.75, 66.64, 64.87, 64.26, 45.46, 45.55],\n    [53.06, 43.74, 44.92, 44.25, 48.28, 44.99, 44.59, 51.79, 52.31, 50.19, 49.18, 38.46, 39.89]]\n\nfor i, KLA_score in enumerate(KLA_scores):\n    print(\"    {0}: {1:0.2f} ({2:0.2f})\".format(layout_names[i], np.mean(KLA_score), np.std(KLA_score)))\n```\n\n        Engram: 61.27 (6.81)\n        Halmak: 58.65 (6.53)\n        Hieamtsrn: 61.23 (7.60)\n        Colemak Mod-DH: 58.63 (6.17)\n        Norman: 55.35 (5.77)\n        Workman: 57.78 (5.95)\n        MTGap 2.0: 57.21 (6.66)\n        QGMLWB: 57.96 (6.48)\n        Colemak: 58.66 (6.17)\n        Asset: 57.08 (5.87)\n        Capewell-Dvorak: 58.92 (6.84)\n        Klausler: 59.93 (7.13)\n        Dvorak: 58.39 (6.69)\n        QWERTY: 46.59 (4.46)\n\n\n    Engram: 61.27 (6.81)\n    Halmak: 58.65 (6.53)\n    Hieamtsrn: 61.23 (7.60)\n    Colemak Mod-DH: 58.63 (6.17)\n    Norman: 55.35 (5.77)\n    Workman: 57.78 (5.95)\n    MTGap 2.0: 57.21 (6.66)\n    QGMLWB: 57.96 (6.48)\n    Colemak: 58.66 (6.17)\n    Asset: 57.08 (5.87)\n    Capewell-Dvorak: 58.92 (6.84)\n    Klausler: 59.93 (7.13)\n    Dvorak: 58.39 (6.69)\n    QWERTY: 46.59 (4.46)\n\n## Keyboard Layout Analyzer data <a name=\"KLAdata\">\n    \nBelow we manually construct tables of measures computed by the [Keyboard Layout Analyzer](https://klatest.keyboard-design.com/#/main) (after the original [KLA](http://patorjk.com/keyboard-layout-analyzer/) for the same text sources:\n    \n    - Finger distances (cm)\n    - Number of taps\n    - Number of same-finger taps \n\nText samples:\n  \n    - Alice in Wonderland (Chapter 1)\n    - Memento\n    - 100K tweets\n    - 20K tweets\n    - MASC tweets\n    - MASC spoken\n    - COCA blogs\n    - iweb\n    - Monkey\n    - Coder\n    - Rosetta\n\n\n```python\n\nAlice_distance_Engram2 = [\n2385.1\n670.2\n2585.9\n2812.0\n3766.1\n2113.5\n1762.5\n2554.2\n18649.5\nAlice_distance_Engram3 = [\n2326.3\n1054.6\n2585.9\n2443.7\n4402.5\n2113.5\n1606.6\n2806.4\n19339.4\nAlice_distance_Exgram = [\n2326.3\n1054.6\n2585.9\n2443.7\n3543.6\n2113.5\n2470.3\n2806.4\n19344.2\nAlice_distance_Halmak = [\n2991.1\n1999.6\n2048.7\n2038.5\n1773.8\n1007.9\n1996.4\n2867.4\n16723.3\nAlice_distance_Hieamtsrn = [\n1216.1\n747.9\n2568.6\n2709.3\n4548.2\n1440.5\n1408.0\n3044.2\n17682.7\nAlice_distance_ColemakModDH = [\n1142.2\n1019.7\n1437.0\n3958.6\n4917.7\n1746.3\n919.7\n2471.2\n17612.3\nAlice_distance_Norman = [\n1136.5\n1019.7\n2230.1\n3135.1\n2707.5\n2523.3\n1661.8\n2359.8\n16773.8\nAlice_distance_Workman = [\n1096.6\n1526.2\n2372.6\n3585.9\n3250.6\n1746.3\n747.0\n2461.3\n16786.5\nAlice_distance_MTGap = [\n1863.4\n733.0\n2894.5\n3253.8\n3006.2\n1439.7\n1765.4\n2174.2\n17130.1\nAlice_distance_QGMLWB = [\n1324.8\n819.4\n1295.6\n5062.3\n4380.8\n1746.3\n546.7\n2254.1\n17430.1\nAlice_distance_Colemak = [\n1142.2\n1019.7\n1437.0\n4070.7\n4686.3\n1746.3\n919.7\n2471.2\n17493.0\nAlice_distance_Asset = [\n1142.2\n1019.7\n1437.0\n3474.5\n4719.3\n1746.3\n1661.8\n2350.0\n17550.7\nAlice_distance_CapewellDvorak = [ = [\n1541.2\n729.1\n906.9\n2484.0\n4200.7\n1877.5\n2414.7\n2475.0\n16629.2\nAlice_distance_Klausler = [\n1413.4\n888.9\n1439.7\n2828.7\n4923.7\n1429.5\n1358.7\n2908.6\n17191.2\nAlice_distance_Dvorak = [\n1622.7\n724.8\n198.7\n3752.4\n4483.8\n1839.4\n2129.1\n3381.9\n18132.8\n\n\n\nAlice_taps_Engram2 = [\n691\n731\n1780\n1363\n1578\n1398\n944\n974\n9459\nAlice_taps_Engram3 = [\n680\n820\n1780\n1274\n1578\n1398\n951\n977\n9458\nAlice_taps_Exgram = [\n680\n820\n1780\n1274\n1406\n1398\n1123\n977\n9458\nAlice_taps_Halmak = [\n1149\n1154\n1079\n1374\n1099\n1334\n1190\n1070\n9449\nAlice_taps_Hieamtsrn = [\n857\n749\n1776\n1333\n1948\n863\n877\n1036\n9439\nAlice_taps_ColemakModDH = [\n869\n712\n863\n1796\n1814\n1505\n779\n1103\n9441\nAlice_taps_Norman = [\n868\n765\n1636\n1560\n1251\n1192\n1169\n989\n9430\nAlice_taps_Workman = [\n861\n900\n1189\n1701\n1427\n1505\n882\n967\n9432\nAlice_taps_MTGap = [\n1068\n871\n1291\n1687\n1242\n1434\n950\n883\n9426\nAlice_taps_QGMLWB = [\n610\n715\n1182\n1873\n1770\n1505\n819\n972\n9446\nAlice_taps_Colemak = [\n869\n712\n863\n1796\n1814\n1505\n779\n1103\n9441\nAlice_taps_Asset = [\n869\n765\n1435\n1671\n1684\n988\n1169\n849\n9430\nAlice_taps_CapewellDvorak = [ = [\n998\n863\n1293\n1178\n1733\n1321\n1163\n894\n9443\nAlice_taps_Klausler = [\n964\n900\n1434\n1284\n1756\n1213\n930\n967\n9448\nAlice_taps_Dvorak = [\n1003\n880\n1128\n1207\n1652\n1301\n1090\n1186\n9447\n\n\nAlice_samefinger_Engram2 = [\n3\n12\n4\n51\n0\n0\n19\n1\n1\n17\n108\nAlice_samefinger_Engram3 = [\n5\n28\n4\n34\n0\n0\n19\n1\n28\n17\n136\nAlice_samefinger_Exgram = [\n5\n28\n4\n34\n0\n0\n11\n1\n8\n17\n108\nAlice_samefinger_Halmak = [\n6\n1\n12\n43\n0\n0\n48\n7\n59\n73\n249\nAlice_samefinger_Hieamtsrn = [\n21\n13\n4\n42\n0\n0\n6\n5\n3\n28\n122\nAlice_samefinger_ColemakModDH = [\n6\n3\n5\n9\n0\n0\n39\n35\n13\n71\n181\nAlice_samefinger_Norman = [\n12\n1\n170\n8\n0\n0\n90\n59\n44\n85\n469\nAlice_samefinger_Workman = [\n5\n10\n11\n16\n0\n0\n98\n35\n38\n62\n275\nAlice_samefinger_MTGap = [\n18\n17\n0\n5\n0\n0\n19\n8\n6\n40\n113\nAlice_samefinger_QGMLWB = [\n3\n7\n14\n78\n0\n0\n186\n35\n8\n75\n406\nAlice_samefinger_Colemak = [\n6\n3\n5\n9\n0\n0\n39\n35\n13\n71\n181\nAlice_samefinger_Asset = [\n12\n1\n77\n4\n0\n0\n52\n5\n44\n65\n260\nAlice_samefinger_CapewellDvorak = [ = [\n49\n0\n63\n60\n0\n0\n58\n3\n13\n32\n278\nAlice_samefinger_Klausler = [\n34\n0\n8\n74\n0\n0\n60\n1\n0\n27\n204\nAlice_samefinger_Dvorak = [\n45\n5\n9\n72\n0\n0\n43\n17\n12\n55\n258\n\n\nMemento_distance_Engram2 = [\n117669.4\n14714.3\n46103.8\n45471.4\n76514.5\n39479.4\n20635.9\n166039.6\n526628.3\nMemento_distance_Engram3 = [\n118376.9\n22176.8\n46103.8\n38101.2\n75991.2\n39479.4\n20495.3\n165485.1\n526209.6\nMemento_distance_Exgram = [\n118376.9\n22176.8\n46103.8\n38101.2\n63079.0\n39479.4\n33486.7\n165485.1\n526288.9\nMemento_distance_Halmak = [\n110075.3\n36876.7\n35540.7\n35674.8\n38882.9\n22425.2\n39790.0\n187228.3\n506494.1\nMemento_distance_Hieamtsrn = [\n107035.7\n16014.0\n47105.1\n48724.7\n73070.9\n27444.8\n26262.9\n166803.7\n512461.8\nMemento_distance_ColemakModDH = [\n89542.2\n11946.3\n25454.4\n65355.9\n77791.2\n28531.4\n33293.2\n150661.9\n482576.4\nMemento_distance_Norman = [\n94898.1\n11946.3\n41705.2\n49257.4\n55506.0\n40735.6\n42528.7\n157722.4\n494299.7\nMemento_distance_Workman = [\n88241.5\n27522.1\n44986.1\n53199.2\n56532.1\n28531.4\n30073.5\n154436.5\n483522.4\nMemento_distance_MTGap = [\n98647.0\n11271.0\n39742.2\n56656.3\n52853.7\n27673.4\n32138.7\n156857.9\n475840.1\nMemento_distance_QGMLWB = [\n95535.8\n13626.8\n29471.0\n73752.0\n77800.2\n28531.4\n25052.7\n177326.1\n521096.0\nMemento_distance_Colemak = [\n89542.2\n11946.3\n25454.4\n66715.1\n75738.6\n28531.4\n33293.2\n150661.9\n481883.0\nMemento_distance_Asset = [\n94491.4\n11946.3\n25454.4\n57802.9\n78719.3\n28531.4\n42528.7\n159346.9\n498821.2\nMemento_distance_CapewellDvorak = [ = [\n109664.9\n9182.2\n30268.1\n47610.7\n71805.3\n25808.3\n44566.5\n158277.4\n497183.2\nMemento_distance_Klausler = [\n109687.3\n22941.7\n25209.9\n49823.5\n70722.5\n29317.4\n24235.9\n165482.3\n497420.5\nMemento_distance_Dvorak = [\n111455.5\n8832.3\n17558.7\n69048.5\n76275.1\n28439.8\n38594.2\n166387.9\n516592.0\n\n\nMemento_taps_Engram2 = [\n33554\n12430\n27876\n20522\n25989\n22447\n13622\n32485\n188925\nMemento_taps_Engram3 = [\n33782\n14158\n27876\n18794\n25989\n22447\n14904\n30881\n188831\nMemento_taps_Exgram = [\n33782\n14158\n27876\n18794\n24754\n22447\n16139\n30881\n188831\nMemento_taps_Halmak = [\n37200\n16826\n18918\n20266\n19443\n20678\n21231\n35000\n189562\nMemento_taps_Hieamtsrn = [\n34717\n12806\n28116\n21485\n29681\n14923\n14355\n32737\n188820\nMemento_taps_ColemakModDH = [\n33825\n10163\n14719\n27427\n29373\n22092\n16422\n32109\n186130\nMemento_taps_Norman = [\n34753\n11392\n26165\n22602\n23781\n18623\n22107\n28449\n187872\nMemento_taps_Workman = [\n33571\n15812\n18383\n24064\n24136\n22092\n18376\n29948\n186382\nMemento_taps_MTGap = [\n37515\n12823\n19804\n26340\n21477\n21894\n15358\n31570\n186781\nMemento_taps_QGMLWB = [\n31251\n11849\n19371\n28892\n28779\n22092\n17047\n30758\n190039\nMemento_taps_Colemak = [\n33825\n10163\n14719\n27427\n29373\n22092\n16422\n32109\n186130\nMemento_taps_Asset = [\n34667\n11392\n21722\n25526\n28256\n15422\n22107\n28862\n187954\nMemento_taps_CapewellDvorak = [ = [\n39409\n12142\n22928\n20219\n26079\n17916\n20557\n30071\n189321\nMemento_taps_Klausler = [\n39559\n15443\n21690\n21740\n27395\n18983\n12498\n32108\n189416\nMemento_taps_Dvorak = [\n38261\n13607\n19970\n21104\n25309\n18812\n19228\n33442\n189733\n\n\nMemento_samefinger_Engram2 = [\n1854\n97\n1306\n595\n0\n0\n715\n23\n97\n1051\n5738\nMemento_samefinger_Engram3 = [\n1918\n427\n1306\n334\n0\n0\n715\n23\n168\n1048\n5939\nMemento_samefinger_Exgram = [\n1918\n427\n1306\n334\n0\n0\n370\n23\n253\n1048\n5679\nMemento_samefinger_Halmak = [\n1456\n21\n163\n495\n0\n0\n1055\n560\n999\n2071\n6820\nMemento_samefinger_Hieamtsrn = [\n2286\n84\n1332\n418\n0\n0\n148\n120\n110\n1550\n6048\nMemento_samefinger_ColemakModDH = [\n2061\n116\n120\n107\n0\n0\n623\n604\n270\n1579\n5480\nMemento_samefinger_Norman = [\n2009\n86\n2324\n90\n0\n0\n1833\n756\n952\n1956\n10006\nMemento_samefinger_Workman = [\n1956\n265\n276\n392\n0\n0\n1109\n604\n500\n1441\n6543\nMemento_samefinger_MTGap = [\n2203\n192\n104\n94\n0\n0\n762\n637\n216\n3067\n7275\nMemento_samefinger_QGMLWB = [\n1326\n95\n344\n974\n0\n0\n2890\n604\n329\n2348\n8910\nMemento_samefinger_Colemak = [\n2061\n116\n120\n107\n0\n0\n623\n604\n270\n1579\n5480\nMemento_samefinger_Asset = [\n1899\n86\n926\n81\n0\n0\n1173\n127\n952\n1542\n6786\nMemento_samefinger_CapewellDvorak = [ = [\n2384\n28\n1089\n1362\n0\n0\n482\n38\n239\n1491\n7113\nMemento_samefinger_Klausler = [\n2446\n154\n698\n1670\n0\n0\n650\n23\n9\n1717\n7367\nMemento_samefinger_Dvorak = [\n2405\n21\n518\n1396\n0\n0\n498\n492\n163\n1492\n6985\n\n\nTweets_100K_distance_Engram2 = [\n2087787.3\n756329.8\n1924024.8\n1521062.0\n2506857.0\n1672844.0\n967345.6\n3256289.9\n14692540.4\nTweets_100K_distance_Engram3 = [\n2092041.1\n1076623.4\n1924024.8\n1203600.1\n2506751.0\n1672844.0\n1013846.9\n3219938.7\n14709670.1\nTweets_100K_distance_Exgram = [\n2092041.1\n1076623.4\n1924024.8\n1203600.1\n2113016.1\n1672844.0\n1413039.5\n3219938.7\n14715127.8\nTweets_100K_distance_Halmak = [\n2154544.8\n1930741.0\n1331619.2\n1310032.1\n1567010.5\n748343.9\n1226652.6\n3548660.6\n13817604.8\nTweets_100K_distance_Hieamtsrn = [\n1348202.4\n751091.1\n1889407.8\n1928067.8\n3370945.7\n951733.0\n890933.9\n3360425.1\n14490806.7\nTweets_100K_distance_ColemakModDH = [\n1328914.1\n968799.3\n988425.9\n2747434.4\n3192557.7\n820667.2\n1046852.1\n2801874.1\n13895524.8\nTweets_100K_distance_Norman = [\n1340538.7\n968799.3\n1444262.5\n2329739.9\n2593809.1\n1207393.9\n1200692.1\n2766330.0\n13851565.5\nTweets_100K_distance_Workman = [\n1267186.7\n1227421.5\n1885903.2\n2598978.5\n2393353.8\n820667.2\n787794.4\n2866597.1\n13847902.4\nTweets_100K_distance_MTGap = [\n1478291.6\n778304.2\n1530578.3\n2338058.6\n2647497.9\n879359.9\n1052964.2\n2844426.7\n13549481.4\nTweets_100K_distance_QGMLWB = [\n1325411.1\n1019020.1\n1340051.8\n3023368.0\n3623460.0\n820667.2\n621040.8\n2852080.5\n14625099.5\nTweets_100K_distance_Colemak = [\n1328914.1\n968799.3\n988425.9\n2862301.8\n3150386.7\n820667.2\n1046852.1\n2801874.1\n13968221.1\nTweets_100K_distance_Asset = [\n1328975.8\n968799.3\n988425.9\n2459632.8\n3578033.7\n820667.2\n1200692.1\n2774004.4\n14119231.1\nTweets_100K_distance_CapewellDvorak = [ = [\n1487143.7\n535116.9\n969711.4\n2147031.1\n2860823.2\n1244980.1\n1508290.1\n3038947.3\n13792043.8\nTweets_100K_distance_Klausler = [\n1622397.8\n858035.7\n901022.9\n2040177.9\n3004076.7\n1411339.3\n824825.7\n3259494.1\n13921370.0\nTweets_100K_distance_Dvorak = [\n1517448.5\n508247.2\n485654.9\n3213344.6\n3241556.3\n1157656.6\n1337003.0\n3396762.5\n14857673.6\n\n\nTweets_100K_taps_Engram2 = [\n570093\n608440\n1090451\n803929\n1004159\n905985\n586816\n860756\n6430629\nTweets_100K_taps_Engram3 = [\n575321\n681775\n1090451\n730594\n1004159\n905985\n623064\n819297\n6430646\nTweets_100K_taps_Exgram = [\n575321\n681775\n1090451\n730594\n962641\n905985\n664582\n819297\n6430646\nTweets_100K_taps_Halmak = [\n796589\n742757\n714394\n806595\n876199\n758796\n795697\n973213\n6464240\nTweets_100K_taps_Hieamtsrn = [\n541051\n606892\n1083678\n947406\n1294889\n578527\n540302\n875122\n6467867\nTweets_100K_taps_ColemakModDH = [\n682856\n480572\n581189\n1129823\n1192142\n774214\n731751\n884398\n6456945\nTweets_100K_taps_Norman = [\n684852\n544418\n923323\n1003298\n1027305\n734479\n879511\n657566\n6454752\nTweets_100K_taps_Workman = [\n671997\n611345\n741958\n1094201\n997347\n774214\n740842\n822809\n6454713\nTweets_100K_taps_MTGap = [\n762882\n603446\n754559\n1073266\n999274\n787675\n575978\n898919\n6455999\nTweets_100K_taps_QGMLWB = [\n447639\n556261\n826788\n1165694\n1332105\n774214\n691857\n668123\n6462681\nTweets_100K_taps_Colemak = [\n682856\n480572\n581189\n1129823\n1192142\n774214\n731751\n884398\n6456945\nTweets_100K_taps_Asset = [\n682846\n544418\n811575\n1047633\n1196788\n625141\n879511\n666454\n6454366\nTweets_100K_taps_CapewellDvorak = [ = [\n769495\n533695\n853691\n937348\n1024760\n803870\n759140\n785993\n6467992\nTweets_100K_taps_Klausler = [\n807522\n660980\n790337\n931317\n1116608\n846542\n474531\n840996\n6468833\nTweets_100K_taps_Dvorak = [\n727928\n573674\n740196\n968265\n1036441\n781429\n716998\n924947\n6469878\n\n\nTweets_100K_samefinger_Engram2 = [\n5271\n6447\n12321\n24434\n0\n0\n24906\n2827\n4259\n79738\n160203\nTweets_100K_samefinger_Engram3 = [\n9391\n23756\n12321\n12712\n0\n0\n24906\n2827\n4598\n75167\n165678\nTweets_100K_samefinger_Exgram = [\n9391\n23756\n12321\n12712\n0\n0\n14207\n2827\n10787\n75167\n161168\nTweets_100K_samefinger_Halmak = [\n11789\n6055\n9071\n18985\n0\n0\n42034\n10460\n43913\n100044\n242351\nTweets_100K_samefinger_Hieamtsrn = [\n13716\n5066\n7399\n15381\n0\n0\n14567\n7525\n7280\n84566\n155500\nTweets_100K_samefinger_ColemakModDH = [\n19454\n3602\n7614\n14277\n0\n0\n27363\n8450\n13305\n82224\n176289\nTweets_100K_samefinger_Norman = [\n20294\n5138\n70764\n10426\n0\n0\n97096\n32818\n46124\n78141\n360801\nTweets_100K_samefinger_Workman = [\n15554\n8636\n7150\n21161\n0\n0\n59606\n8450\n21572\n83511\n225640\nTweets_100K_samefinger_MTGap = [\n19532\n12512\n2352\n12273\n0\n0\n51182\n7937\n8764\n84293\n198845\nTweets_100K_samefinger_QGMLWB = [\n6139\n4858\n12022\n42462\n0\n0\n151585\n8450\n13061\n80317\n318894\nTweets_100K_samefinger_Colemak = [\n19454\n3602\n7614\n14277\n0\n0\n27363\n8450\n13305\n82224\n176289\nTweets_100K_samefinger_Asset = [\n20004\n5138\n34215\n7864\n0\n0\n68682\n3324\n46124\n74158\n259509\nTweets_100K_samefinger_CapewellDvorak = [ = [\n27189\n3502\n34848\n59191\n0\n0\n23231\n7150\n13578\n81900\n250589\nTweets_100K_samefinger_Klausler = [\n38074\n4069\n7959\n58716\n0\n0\n28454\n3437\n1136\n85984\n227829\nTweets_100K_samefinger_Dvorak = [\n26129\n1600\n13601\n61445\n0\n0\n28743\n15962\n9006\n89816\n246302\n\n\nTweets_20K_distance_Engram2 = [\n827967.4\n190513.8\n489342.1\n432633.0\n748985.7\n414539.9\n274383.8\n1350474.0\n4728839.8\nTweets_20K_distance_Engram3 = [\n877386.1\n252786.2\n489342.1\n371158.5\n753248.1\n414539.9\n262816.5\n1313689.9\n4734967.3\nTweets_20K_distance_Exgram = [\n877386.1\n252786.2\n489342.1\n371158.5\n647684.7\n414539.9\n370989.1\n1313689.9\n4737576.5\nTweets_20K_distance_Halmak = [\n804427.9\n481673.9\n462393.2\n545563.6\n532615.6\n213225.5\n332700.2\n1302592.0\n4675191.9\nTweets_20K_distance_Hieamtsrn = [\n669355.1\n199784.7\n602938.4\n522540.0\n814662.6\n328413.5\n260001.1\n1340124.4\n4737819.7\nTweets_20K_distance_ColemakModDH = [\n566778.0\n253396.8\n400494.2\n812638.0\n863733.2\n216427.9\n256859.2\n1277370.9\n4647698.2\nTweets_20K_distance_Norman = [\n576596.0\n253396.8\n506668.1\n645251.3\n701641.3\n349630.0\n326855.8\n1255515.7\n4615554.8\nTweets_20K_distance_Workman = [\n556632.6\n343406.7\n560144.0\n758660.9\n638035.4\n216427.9\n264735.3\n1281595.5\n4619638.4\nTweets_20K_distance_MTGap = [\n642229.0\n238311.9\n500314.0\n692751.7\n702656.4\n229476.5\n310416.3\n1188922.6\n4505078.5\nTweets_20K_distance_QGMLWB = [\n585695.7\n258078.5\n444177.8\n876596.1\n911314.9\n216427.9\n186826.9\n1265809.6\n4744927.5\nTweets_20K_distance_Colemak = [\n566778.0\n253396.8\n400494.2\n824699.3\n844468.9\n216427.9\n256859.2\n1277370.9\n4640495.2\nTweets_20K_distance_Asset = [\n574281.6\n253396.8\n400494.2\n687049.9\n948654.2\n216427.9\n326855.8\n1256734.5\n4663894.8\nTweets_20K_distance_CapewellDvorak = [ = [\n708612.8\n151349.5\n371843.7\n647945.9\n776762.6\n292143.1\n440776.1\n1165591.3\n4555025.0\nTweets_20K_distance_Klausler = [\n691510.2\n218659.5\n295114.9\n676267.9\n834534.2\n321868.7\n250193.0\n1317054.7\n4605203.0\nTweets_20K_distance_Dvorak = [\n713303.8\n143896.6\n198760.0\n851698.8\n832010.7\n351565.5\n423853.1\n1274209.6\n4789298.0\n\n\nTweets_20K_taps_Engram2 = [\n208894\n138064\n286632\n216176\n273104\n246031\n159822\n301108\n1829831\nTweets_20K_taps_Engram3 = [\n222632\n152405\n286632\n201835\n273104\n246031\n157309\n289951\n1829899\nTweets_20K_taps_Exgram = [\n222632\n152405\n286632\n201835\n254276\n246031\n176137\n289951\n1829899\nTweets_20K_taps_Halmak = [\n252716\n193598\n202587\n267502\n241721\n213050\n194793\n277057\n1843024\nTweets_20K_taps_Hieamtsrn = [\n204214\n143654\n315200\n240044\n335537\n174442\n150421\n286713\n1850225\nTweets_20K_taps_ColemakModDH = [\n218053\n129810\n182525\n327229\n309243\n213601\n158358\n301448\n1840267\nTweets_20K_taps_Norman = [\n219755\n145126\n276006\n282317\n266611\n180906\n206309\n262740\n1839770\nTweets_20K_taps_Workman = [\n216262\n168764\n208353\n312469\n255657\n213601\n183330\n280827\n1839263\nTweets_20K_taps_MTGap = [\n228274\n166708\n210617\n308994\n262830\n216636\n161497\n283368\n1838924\nTweets_20K_taps_QGMLWB = [\n159607\n146854\n245087\n314831\n336795\n213601\n161875\n263738\n1842388\nTweets_20K_taps_Colemak = [\n218053\n129810\n182525\n327229\n309243\n213601\n158358\n301448\n1840267\nTweets_20K_taps_Asset = [\n219358\n145126\n249882\n295477\n314452\n145656\n206309\n263318\n1839578\nTweets_20K_taps_CapewellDvorak = [ = [\n241447\n142782\n245755\n243926\n276562\n215635\n203980\n274318\n1844405\nTweets_20K_taps_Klausler = [\n241644\n163132\n224719\n252350\n297519\n223688\n137896\n304128\n1845076\nTweets_20K_taps_Dvorak = [\n247560\n137681\n205125\n247540\n271305\n230024\n198723\n307947\n1845905\n\n\nTweets_20K_samefinger_Engram2 = [\n4572\n1807\n3433\n7217\n0\n0\n6532\n1117\n1613\n33852\n60143\nTweets_20K_samefinger_Engram3 = [\n4949\n5203\n3433\n4397\n0\n0\n6532\n1117\n1497\n31540\n58668\nTweets_20K_samefinger_Exgram = [\n4949\n5203\n3433\n4397\n0\n0\n3409\n1117\n2587\n31540\n56635\nTweets_20K_samefinger_Halmak = [\n16292\n2047\n2755\n15230\n0\n0\n9918\n3391\n7842\n27557\n85032\nTweets_20K_samefinger_Hieamtsrn = [\n13032\n1339\n2776\n4554\n0\n0\n4998\n2281\n1827\n28938\n59745\nTweets_20K_samefinger_ColemakModDH = [\n7872\n1260\n2939\n14496\n0\n0\n7618\n2687\n1980\n37016\n75868\nTweets_20K_samefinger_Norman = [\n8470\n1884\n20278\n4474\n0\n0\n19321\n9515\n11622\n31381\n106945\nTweets_20K_samefinger_Workman = [\n6722\n3036\n3019\n7946\n0\n0\n13495\n2687\n5298\n26143\n68346\nTweets_20K_samefinger_MTGap = [\n8486\n3601\n1668\n13798\n0\n0\n10673\n2794\n2491\n26054\n69565\nTweets_20K_samefinger_QGMLWB = [\n3482\n1856\n5077\n12339\n0\n0\n34669\n2687\n3728\n31012\n94850\nTweets_20K_samefinger_Colemak = [\n7872\n1260\n2939\n14496\n0\n0\n7618\n2687\n1980\n37016\n75868\nTweets_20K_samefinger_Asset = [\n8350\n1884\n10968\n3906\n0\n0\n13599\n1359\n11622\n25935\n77623\nTweets_20K_samefinger_CapewellDvorak = [ = [\n11182\n1064\n17648\n15759\n0\n0\n7320\n1732\n3307\n23927\n81939\nTweets_20K_samefinger_Klausler = [\n14186\n944\n2964\n15999\n0\n0\n8023\n1248\n659\n43476\n87499\nTweets_20K_samefinger_Dvorak = [\n10859\n511\n2280\n15715\n0\n0\n7166\n4823\n2428\n41962\n85744\n\n\nTweets_MASC_distance_Engram2 = [\n58340.2\n13952.4\n36877.7\n30025.4\n62970.4\n29576.8\n19716.5\n80550.0\n332009.4\nTweets_MASC_distance_Engram3 = [\n60842.8\n19233.8\n36877.7\n24825.4\n54558.6\n29576.8\n19445.6\n77646.6\n323007.3\nTweets_MASC_distance_Exgram = [\n60842.8\n19233.8\n36877.7\n24825.4\n46698.8\n29576.8\n27851.4\n77646.6\n323553.3\nTweets_MASC_distance_Halmak = [\n51012.9\n33352.8\n33008.1\n36960.4\n42543.8\n15094.3\n22686.9\n85809.9\n320469.1\nTweets_MASC_distance_Hieamtsrn = [\n40935.7\n14518.6\n41371.2\n38760.1\n62043.0\n23979.4\n19107.8\n83846.6\n324562.5\nTweets_MASC_distance_ColemakModDH = [\n34478.5\n14046.3\n25911.0\n56905.8\n59835.8\n16485.0\n21793.4\n81824.1\n311279.8\nTweets_MASC_distance_Norman = [\n36238.7\n14046.3\n31804.1\n48378.0\n51303.3\n29896.4\n27498.6\n80146.8\n319312.2\nTweets_MASC_distance_Workman = [\n33817.1\n18671.6\n42434.2\n55716.4\n47265.4\n16485.0\n21599.6\n82426.1\n318415.4\nTweets_MASC_distance_MTGap = [\n41531.6\n12793.6\n29452.1\n48724.0\n52002.7\n16951.1\n22620.9\n79374.6\n303450.7\nTweets_MASC_distance_QGMLWB = [\n35498.4\n17116.8\n30257.3\n66240.1\n72583.3\n16485.0\n15303.1\n80737.1\n334221.2\nTweets_MASC_distance_Colemak = [\n34478.5\n14046.3\n25911.0\n59702.1\n59136.2\n16485.0\n21793.4\n81824.1\n313376.5\nTweets_MASC_distance_Asset = [\n36030.4\n14046.3\n25911.0\n48861.5\n66526.2\n16485.0\n27498.6\n80322.2\n315681.2\nTweets_MASC_distance_CapewellDvorak = [ = [\n44519.8\n7037.5\n26145.1\n43672.0\n56117.4\n24254.4\n36454.4\n74121.5\n312322.1\nTweets_MASC_distance_Klausler = [\n43413.7\n15057.2\n18341.8\n44713.5\n63606.6\n27700.2\n18754.6\n85478.6\n317066.2\nTweets_MASC_distance_Dvorak = [\n45104.4\n6394.2\n12883.6\n65337.4\n63457.7\n25924.7\n33471.8\n83117.3\n335691.0\n\n\nTweets_MASC_taps_Engram2 = [\n15178\n11625\n20760\n15106\n21492\n17594\n11552\n19517\n132824\nTweets_MASC_taps_Engram3 = [\n15986\n12847\n20760\n13884\n21492\n17594\n12197\n18046\n132806\nTweets_MASC_taps_Exgram = [\n15986\n12847\n20760\n13884\n19582\n17594\n14107\n18046\n132806\nTweets_MASC_taps_Halmak = [\n16991\n13076\n15626\n19039\n18765\n14874\n14329\n20701\n133401\nTweets_MASC_taps_Hieamtsrn = [\n12460\n11801\n22195\n17872\n25010\n12581\n12005\n19554\n133478\nTweets_MASC_taps_ColemakModDH = [\n14299\n9935\n12765\n23542\n22454\n15198\n14179\n20964\n133336\nTweets_MASC_taps_Norman = [\n14604\n9864\n18729\n20903\n20183\n15888\n16766\n16410\n133347\nTweets_MASC_taps_Workman = [\n14181\n11010\n15005\n23151\n19439\n15198\n14800\n20521\n133305\nTweets_MASC_taps_MTGap = [\n16282\n11217\n14535\n22278\n19369\n15301\n12732\n21664\n133378\nTweets_MASC_taps_QGMLWB = [\n9867\n10630\n17614\n24503\n25934\n15198\n13064\n16610\n133420\nTweets_MASC_taps_Colemak = [\n14299\n9935\n12765\n23542\n22454\n15198\n14179\n20964\n133336\nTweets_MASC_taps_Asset = [\n14567\n9864\n17329\n21187\n22752\n12359\n16766\n18537\n133361\nTweets_MASC_taps_CapewellDvorak = [ = [\n16896\n9598\n17961\n18810\n19041\n16387\n16514\n18176\n133383\nTweets_MASC_taps_Klausler = [\n16899\n12173\n15485\n19196\n23137\n17177\n9157\n20230\n133454\nTweets_MASC_taps_Dvorak = [\n16566\n10099\n14851\n19319\n19480\n16727\n15758\n20678\n133478\n\n\nTweets_MASC_samefinger_Engram2 = [\n189\n153\n283\n491\n0\n0\n1217\n92\n142\n1297\n3864\nTweets_MASC_samefinger_Engram3 = [\n692\n477\n283\n279\n0\n0\n1217\n92\n94\n1259\n4393\nTweets_MASC_samefinger_Exgram = [\n692\n477\n283\n279\n0\n0\n388\n92\n458\n1259\n3928\nTweets_MASC_samefinger_Halmak = [\n455\n97\n208\n1013\n0\n0\n886\n247\n658\n2164\n5728\nTweets_MASC_samefinger_Hieamtsrn = [\n465\n125\n180\n312\n0\n0\n467\n161\n403\n2045\n4158\nTweets_MASC_samefinger_ColemakModDH = [\n407\n59\n174\n850\n0\n0\n536\n201\n273\n2149\n4649\nTweets_MASC_samefinger_Norman = [\n464\n129\n1658\n297\n0\n0\n1803\n774\n1144\n1738\n8007\nTweets_MASC_samefinger_Workman = [\n333\n166\n207\n720\n0\n0\n1276\n201\n510\n1936\n5349\nTweets_MASC_samefinger_MTGap = [\n613\n228\n77\n751\n0\n0\n818\n182\n444\n2080\n5193\nTweets_MASC_samefinger_QGMLWB = [\n137\n102\n409\n1139\n0\n0\n3030\n201\n253\n1911\n7182\nTweets_MASC_samefinger_Colemak = [\n407\n59\n174\n850\n0\n0\n536\n201\n273\n2149\n4649\nTweets_MASC_samefinger_Asset = [\n450\n129\n898\n282\n0\n0\n1178\n109\n1144\n1711\n5901\nTweets_MASC_samefinger_CapewellDvorak = [ = [\n875\n66\n1199\n1418\n0\n0\n467\n207\n276\n1599\n6107\nTweets_MASC_samefinger_Klausler = [\n1040\n75\n179\n1247\n0\n0\n860\n72\n56\n2176\n5705\nTweets_MASC_samefinger_Dvorak = [\n748\n30\n261\n1521\n0\n0\n575\n532\n205\n2232\n6104\n\n\nSpoken_MASC_distance_Engram2 = [\n31904.6\n11878.6\n33032.9\n40302.3\n38954.3\n23273.3\n17592.4\n117978.6\n314916.9\nSpoken_MASC_distance_Engram3 = [\n31747.7\n16534.1\n33032.9\n36052.7\n47698.2\n23273.3\n17809.8\n117928.9\n324077.6\nSpoken_MASC_distance_Exgram = [\n31747.7\n16534.1\n33032.9\n36052.7\n41759.4\n23273.3\n23796.4\n117928.9\n324125.4\nSpoken_MASC_distance_Halmak = [\n40088.6\n21597.8\n22139.2\n22285.1\n19659.9\n15525.0\n18704.4\n129009.3\n289009.2\nSpoken_MASC_distance_Hieamtsrn = [\n25101.8\n17384.0\n32442.0\n33915.3\n50307.9\n13885.9\n12789.3\n116438.2\n302264.3\nSpoken_MASC_distance_ColemakModDH = [\n24259.4\n11933.5\n14047.5\n40565.0\n55864.5\n21441.7\n17457.7\n116774.0\n302343.3\nSpoken_MASC_distance_Norman = [\n24542.2\n11933.5\n21428.9\n33593.5\n41289.2\n24609.1\n17953.4\n116832.0\n292181.9\nSpoken_MASC_distance_Workman = [\n23822.5\n14073.4\n27924.7\n40451.4\n35982.5\n21441.7\n11231.4\n117633.8\n292561.3\nSpoken_MASC_distance_MTGap = [\n31946.7\n6691.9\n32081.5\n32957.1\n41715.2\n19630.5\n15786.0\n114542.4\n295351.3\nSpoken_MASC_distance_QGMLWB = [\n25543.2\n8717.9\n17267.1\n50345.8\n54239.2\n21441.7\n10231.3\n114939.0\n302725.1\nSpoken_MASC_distance_Colemak = [\n24259.4\n11933.5\n14047.5\n41263.1\n53640.0\n21441.7\n17457.7\n116774.0\n300817.0\nSpoken_MASC_distance_Asset = [\n24393.9\n11933.5\n14047.5\n36169.1\n62183.4\n21441.7\n17953.4\n116169.0\n304291.5\nSpoken_MASC_distance_CapewellDvorak = [ = [\n25897.0\n6903.8\n13976.7\n37651.8\n40836.8\n20142.1\n24039.1\n116155.9\n285603.1\nSpoken_MASC_distance_Klausler = [\n26490.4\n12509.5\n19638.6\n30463.4\n50926.1\n17798.5\n12013.9\n119846.1\n289686.6\nSpoken_MASC_distance_Dvorak = [\n25793.9\n6459.1\n7045.4\n49013.6\n45652.8\n19649.8\n22175.3\n123090.8\n298880.6\n\n\nSpoken_MASC_taps_Engram2 = [\n8719\n9606\n20577\n16531\n16794\n16077\n10281\n19851\n118436\nSpoken_MASC_taps_Engram3 = [\n8672\n10684\n20577\n15453\n16794\n16077\n10793\n19372\n118422\nSpoken_MASC_taps_Exgram = [\n8672\n10684\n20577\n15453\n16526\n16077\n11061\n19372\n118422\nSpoken_MASC_taps_Halmak = [\n14526\n12671\n12126\n15531\n12392\n15877\n13005\n22708\n118836\nSpoken_MASC_taps_Hieamtsrn = [\n11782\n10883\n20440\n15626\n22192\n9345\n8512\n19771\n118551\nSpoken_MASC_taps_ColemakModDH = [\n12088\n7626\n9346\n19345\n20747\n17247\n10901\n21492\n118792\nSpoken_MASC_taps_Norman = [\n12138\n8873\n17239\n17512\n17117\n12768\n13445\n19768\n118860\nSpoken_MASC_taps_Workman = [\n12011\n9440\n13663\n19389\n16105\n17247\n11111\n19839\n118805\nSpoken_MASC_taps_MTGap = [\n14713\n9290\n14570\n18319\n16129\n16828\n9206\n19882\n118937\nSpoken_MASC_taps_QGMLWB = [\n8195\n8066\n14575\n19473\n20908\n17247\n10803\n19570\n118837\nSpoken_MASC_taps_Colemak = [\n12088\n7626\n9346\n19345\n20747\n17247\n10901\n21492\n118792\nSpoken_MASC_taps_Asset = [\n12112\n8873\n15432\n18343\n20948\n11908\n13445\n17688\n118749\nSpoken_MASC_taps_CapewellDvorak = [ = [\n13544\n9249\n15319\n15719\n17736\n15091\n12574\n19671\n118903\nSpoken_MASC_taps_Klausler = [\n13678\n10547\n16829\n14235\n18756\n14703\n9623\n20603\n118974\nSpoken_MASC_taps_Dvorak = [\n12661\n9979\n13706\n15903\n17489\n14962\n12131\n22153\n118984\n\n\nSpoken_MASC_samefinger_Engram2 = [\n27\n99\n173\n563\n0\n0\n502\n26\n42\n325\n1757\nSpoken_MASC_samefinger_Engram3 = [\n19\n351\n173\n363\n0\n0\n502\n26\n45\n193\n1672\nSpoken_MASC_samefinger_Exgram = [\n19\n351\n173\n363\n0\n0\n356\n26\n117\n193\n1598\nSpoken_MASC_samefinger_Halmak = [\n189\n52\n65\n361\n0\n0\n375\n244\n698\n887\n2871\nSpoken_MASC_samefinger_Hieamtsrn = [\n338\n112\n151\n293\n0\n0\n187\n113\n59\n343\n1596\nSpoken_MASC_samefinger_ColemakModDH = [\n134\n22\n113\n99\n0\n0\n584\n368\n113\n889\n2322\nSpoken_MASC_samefinger_Norman = [\n140\n35\n1161\n75\n0\n0\n1299\n473\n449\n879\n4511\nSpoken_MASC_samefinger_Workman = [\n116\n61\n211\n350\n0\n0\n1069\n368\n397\n506\n3078\nSpoken_MASC_samefinger_MTGap = [\n492\n105\n15\n84\n0\n0\n506\n330\n87\n1507\n3126\nSpoken_MASC_samefinger_QGMLWB = [\n28\n61\n220\n391\n0\n0\n1794\n368\n190\n867\n3919\nSpoken_MASC_samefinger_Colemak = [\n134\n22\n113\n99\n0\n0\n584\n368\n113\n889\n2322\nSpoken_MASC_samefinger_Asset = [\n135\n35\n662\n48\n0\n0\n902\n38\n449\n563\n2832\nSpoken_MASC_samefinger_CapewellDvorak = [ = [\n479\n36\n678\n775\n0\n0\n460\n123\n74\n783\n3408\nSpoken_MASC_samefinger_Klausler = [\n569\n22\n330\n676\n0\n0\n283\n25\n4\n697\n2606\nSpoken_MASC_samefinger_Dvorak = [\n200\n100\n207\n775\n0\n0\n511\n326\n65\n772\n2956\n\n\nCOCA_blogs_distance_Engram2 = [\n1638526.8\n595437.8\n1845339.7\n1426202.3\n2730231.3\n1452126.0\n975102.0\n1938587.2\n12601553.0\nCOCA_blogs_distance_Engram3 = [\n1714074.9\n763441.1\n1845339.7\n1258703.1\n2540946.5\n1452126.0\n897608.7\n1927496.9\n12399736.9\nCOCA_blogs_distance_Exgram = [\n1714074.9\n763441.1\n1845339.7\n1258703.1\n2102901.6\n1452126.0\n1335539.0\n1927496.9\n12399622.3\nCOCA_blogs_distance_Halmak = [\n1774467.9\n1493613.7\n1606552.5\n1470536.8\n1365957.4\n738440.5\n1085214.6\n2087906.2\n11622689.6\nCOCA_blogs_distance_Hieamtsrn = [\n1143152.5\n605485.2\n1875206.9\n1482673.1\n2708925.6\n1175707.0\n885627.1\n1874879.4\n11751656.6\nCOCA_blogs_distance_ColemakModDH = [\n856756.7\n556542.6\n1199294.7\n2748002.5\n2922862.0\n942954.0\n841506.9\n1570334.3\n11638253.7\nCOCA_blogs_distance_Norman = [\n889469.7\n556542.6\n1553040.7\n2161300.5\n2286825.0\n1581318.4\n1171401.4\n1516192.9\n11716091.2\nCOCA_blogs_distance_Workman = [\n834311.0\n913014.9\n1953894.9\n2595441.0\n2116650.8\n942954.0\n797336.1\n1602646.2\n11756248.8\nCOCA_blogs_distance_MTGap = [\n1158226.0\n559121.3\n1572850.4\n2095892.9\n2308046.9\n875959.3\n1150340.0\n1502833.6\n11223270.4\nCOCA_blogs_distance_QGMLWB = [\n916752.5\n590454.3\n1312010.0\n3228188.4\n3335246.1\n942954.0\n607511.8\n1504761.8\n12437878.8\nColemak = [\n856756.7\n556542.6\n1199294.7\n2801553.6\n2849065.3\n942954.0\n841506.9\n1570334.3\n11618008.1\nAsset = [\n880669.5\n556542.6\n1199294.7\n2320115.4\n3141198.9\n942954.0\n1171401.4\n1528977.0\n11741153.4\nCapewellDvorak = [\n1035248.9\n335872.4\n1014558.1\n2053965.3\n2761217.4\n1003422.5\n1779571.0\n1536770.4\n11520625.9\nKlausler = [\n1067390.6\n583212.7\n879527.3\n1927064.3\n3116710.7\n1122159.2\n928160.0\n2000212.0\n11624436.8\nDvorak = [\n1064382.0\n310172.7\n346465.4\n2963689.8\n3020449.6\n1206828.2\n1676315.5\n2007717.5\n12596020.5\n\n    \nCOCA_blogs_taps_Engram2 = [\n515844\n566272\n1173819\n810064\n981485\n907329\n613793\n716835\n6285441\nCOCA_blogs_taps_Engram3 = [\n540041\n605206\n1173819\n771130\n981485\n907329\n615469\n691187\n6285666\nCOCA_blogs_taps_Exgram = [\n540041\n605206\n1173819\n771130\n900937\n907329\n696017\n691187\n6285666\nCOCA_blogs_taps_Halmak = [\n751878\n683820\n805445\n896346\n806432\n879869\n728358\n751894\n6304042\nCOCA_blogs_taps_Hieamtsrn = [\n518333\n574011\n1180674\n827825\n1198472\n668358\n592211\n715613\n6275497\nCOCA_blogs_taps_ColemakModDH = [\n618213\n470079\n668166\n1168023\n1144067\n927186\n630770\n672103\n6298607\nCOCA_blogs_taps_Norman = [\n623935\n506936\n1075735\n1014044\n975752\n823564\n787298\n491559\n6298823\nCOCA_blogs_taps_Workman = [\n614280\n599763\n776600\n1126179\n952706\n927186\n664690\n636528\n6297932\nCOCA_blogs_taps_MTGap = [\n680903\n609598\n788978\n1064077\n944652\n911673\n649097\n648812\n6297790\nCOCA_blogs_taps_QGMLWB = [\n366389\n517100\n869547\n1236032\n1285795\n927186\n610025\n490400\n6302474\nColemak = [\n618213\n470079\n668166\n1168023\n1144067\n927186\n630770\n672103\n6298607\nAsset = [\n622393\n506936\n989890\n1061480\n1132915\n655738\n787298\n541923\n6298573\nCapewellDvorak = [\n654705\n546320\n943933\n918787\n1015277\n792328\n842405\n588086\n6301841\nKlausler = [\n662356\n610958\n911481\n895921\n1172946\n825465\n513549\n709747\n6302423\nDvorak = [\n667318\n533762\n786407\n907194\n992132\n840765\n817169\n757899\n6302646\n\n\nCOCA_blogs_samefinger_Engram2 = [\n2129\n4141\n12555\n21196\n0\n0\n10248\n1913\n3824\n12639\n68645\nCOCA_blogs_samefinger_Engram3 = [\n2675\n14452\n12555\n14891\n0\n0\n10248\n1913\n4360\n8803\n69897\nCOCA_blogs_samefinger_Exgram = [\n2675\n14452\n12555\n14891\n0\n0\n2597\n1913\n8381\n8803\n66267\nCOCA_blogs_samefinger_Halmak = [\n9599\n2336\n10825\n20029\n0\n0\n34886\n15212\n27097\n14139\n134123\nCOCA_blogs_samefinger_Hieamtsrn = [\n19390\n3732\n9169\n12041\n0\n0\n9271\n7210\n4309\n12715\n77837\nCOCA_blogs_samefinger_ColemakModDH = [\n8591\n2838\n7214\n9689\n0\n0\n21354\n6702\n2599\n18005\n76992\nCOCA_blogs_samefinger_Norman = [\n9657\n3037\n111893\n7325\n0\n0\n70841\n39801\n32348\n22682\n297584\nCOCA_blogs_samefinger_Workman = [\n7151\n5987\n9949\n23597\n0\n0\n52774\n6702\n26980\n10671\n143811\nCOCA_blogs_samefinger_MTGap = [\n12945\n12017\n1839\n7621\n0\n0\n30257\n6687\n7724\n9272\n88362\nCOCA_blogs_samefinger_QGMLWB = [\n1071\n3333\n18765\n39522\n0\n0\n123835\n6702\n12417\n22576\n228221\nColemak = [\n8591\n2838\n7214\n9689\n0\n0\n21354\n6702\n2599\n18005\n76992\nAsset = [\n9263\n3037\n59245\n5832\n0\n0\n42552\n3752\n32348\n10401\n166430\nCapewellDvorak = [\n17423\n2033\n43124\n54903\n0\n0\n23660\n3512\n10896\n11977\n167528\nKlausler = [\n23915\n371\n6686\n52822\n0\n0\n28103\n3041\n610\n13391\n128939\nDvorak = [\n14291\n113\n1667\n46534\n0\n0\n20913\n20515\n10773\n16703\n131509\n\n\niweb_distance_Engram2 = [\n9164499.4\n3347614.1\n10543924.9\n7969894.1\n16059053.6\n8360759.0\n5522514.1\n11371913.3\n72340172.3\niweb_distance_Engram3 = [\n9909496.4\n4233648.5\n10543924.9\n7096781.1\n13792131.4\n8360759.0\n4788694.1\n11300359.2\n70025794.5\niweb_distance_Exgram = [\n9909496.4\n4233648.5\n10543924.9\n7096781.1\n10975821.0\n8360759.0\n7621632.5\n11300359.2\n70042422.6\niweb_distance_Halmak = [\n9419294.9\n8623276.0\n9760442.6\n8419191.0\n7955907.1\n4517922.3\n6344752.6\n11947563.0\n66988349.5\niweb_distance_Hieamtsrn = [\n6473195.8\n3402052.2\n10614165.3\n8054091.7\n15356999.1\n7194833.3\n5180113.0\n11017005.4\n67292455.7\niweb_distance_ColemakModDH = [\n4112869.3\n3071102.1\n7401898.6\n15856176.9\n16180927.0\n5567947.9\n4733226.1\n9308979.8\n66233127.6\niweb_distance_Norman = [\n4308336.0\n3071102.1\n9458047.0\n12104303.1\n13431893.2\n9497545.9\n6857490.2\n8997485.0\n67726202.4\niweb_distance_Workman = [\n4128791.3\n5401296.0\n11663713.6\n14862366.5\n12296027.8\n5567947.9\n4796386.1\n9282232.1\n67998761.3\niweb_distance_MTGap = [\n5958510.6\n3344120.7\n8308022.6\n12308538.7\n13258772.2\n4800710.3\n6775884.9\n9026980.6\n63781540.6\niweb_distance_QGMLWB = [\n4445888.9\n3364197.0\n7864755.8\n18999710.5\n19096155.4\n5567947.9\n3464405.9\n8959190.8\n71762252.3\niweb_distance_Colemak = [\n4112869.3\n3071102.1\n7401898.6\n16046231.3\n15818671.4\n5567947.9\n4733226.1\n9308979.8\n66060926.5\niweb_distance_Asset = [\n4276589.8\n3071102.1\n7401898.6\n13003768.5\n17519950.7\n5567947.9\n6857490.2\n9039908.3\n66738656.1\niweb_distance_CapewellDvorak = [ = [\n5272106.9\n1890549.3\n6197933.3\n12096009.7\n16228202.0\n5500792.8\n10576987.0\n8639509.4\n66402090.3\niweb_distance_Klausler = [\n5869886.2\n3220975.3\n4866524.8\n11288418.0\n18403949.2\n6266196.6\n5266048.1\n11651345.8\n66833344.1\niweb_distance_Dvorak = [\n5436616.3\n1709925.9\n1915032.9\n17145406.8\n17275358.1\n7132350.2\n10149547.9\n11456547.1\n72220785.1\n\n\niweb_taps_Engram2 = [\n3001132\n3233904\n6767298\n4578171\n5576490\n5157643\n3596919\n4202863\n36114420\niweb_taps_Engram3 = [\n3232215\n3438878\n6767298\n4373197\n5576490\n5157643\n3422812\n4143635\n36112168\niweb_taps_Exgram = [\n3232215\n3438878\n6767298\n4373197\n4870810\n5157643\n4128492\n4143635\n36112168\niweb_taps_Halmak = [\n4269573\n3810031\n4727117\n5088908\n4614959\n5151304\n4230331\n4287205\n36179428\niweb_taps_Hieamtsrn = [\n2812034\n3248804\n6782925\n4628359\n6774116\n4043335\n3563631\n4211819\n36065023\niweb_taps_ColemakModDH = [\n3400043\n2800625\n4051343\n6682276\n6411562\n5394214\n3550571\n3876090\n36166724\niweb_taps_Norman = [\n3434069\n2965052\n6344684\n5714886\n5665905\n4827975\n4527855\n2685285\n36165711\niweb_taps_Workman = [\n3402786\n3577751\n4431620\n6392123\n5485815\n5394214\n3848410\n3634296\n36167015\niweb_taps_MTGap = [\n3800079\n3528888\n4320964\n6120170\n5523374\n5216625\n3905164\n3752295\n36167559\niweb_taps_QGMLWB = [\n2007468\n3047903\n5001602\n7217666\n7369018\n5394214\n3466797\n2676162\n36180830\niweb_taps_Colemak = [\n3400043\n2800625\n4051343\n6682276\n6411562\n5394214\n3550571\n3876090\n36166724\niweb_taps_Asset = [\n3428505\n2965052\n5842870\n5991862\n6364034\n3802234\n4527855\n3242477\n36164889\niweb_taps_CapewellDvorak = [ = [\n3624191\n3117803\n5497187\n5371258\n5795761\n4414598\n4899821\n3458332\n36178951\niweb_taps_Klausler = [\n3770373\n3426115\n5224633\n5210869\n6855978\n4626459\n2803011\n4261489\n36178927\niweb_taps_Dvorak = [\n3666780\n3061601\n4484227\n5321116\n5549228\n4816148\n4793138\n4482995\n36175233\n\n\niweb_samefinger_Engram2 = [\n17264\n24882\n55657\n150715\n0\n0\n105326\n14224\n27769\n136483\n532320\niweb_samefinger_Engram3 = [\n24861\n73939\n55657\n105902\n0\n0\n105326\n14224\n25184\n120383\n525476\niweb_samefinger_Exgram = [\n24861\n73939\n55657\n105902\n0\n0\n60636\n14224\n40913\n120383\n496515\niweb_samefinger_Halmak = [\n89406\n13664\n70593\n160557\n0\n0\n246563\n93821\n149535\n190678\n1014817\niweb_samefinger_Hieamtsrn = [\n114896\n20069\n37927\n97619\n0\n0\n56817\n44696\n20779\n157255\n550058\niweb_samefinger_ColemakModDH = [\n58990\n12839\n44736\n71524\n0\n0\n99312\n85581\n36729\n207174\n616885\niweb_samefinger_Norman = [\n63743\n22327\n689084\n46173\n0\n0\n415876\n259702\n225030\n220706\n1942641\niweb_samefinger_Workman = [\n48193\n39735\n66938\n154850\n0\n0\n278054\n85581\n150752\n163679\n987782\niweb_samefinger_MTGap = [\n104965\n67130\n10315\n53542\n0\n0\n179031\n55268\n46848\n249323\n766422\niweb_samefinger_QGMLWB = [\n20868\n18367\n125025\n238335\n0\n0\n736352\n85581\n74674\n214563\n1513765\niweb_samefinger_Colemak = [\n58990\n12839\n44736\n71524\n0\n0\n99312\n85581\n36729\n207174\n616885\niweb_samefinger_Asset = [\n61341\n22327\n362102\n41713\n0\n0\n227843\n36295\n225030\n158020\n1134671\niweb_samefinger_CapewellDvorak = [ = [\n102617\n18561\n334304\n356228\n0\n0\n126433\n24080\n74270\n159215\n1195708\niweb_samefinger_Klausler = [\n144673\n17708\n55265\n320043\n0\n0\n164410\n12835\n3069\n179299\n897302\niweb_samefinger_Dvorak = [\n84777\n7861\n70921\n305848\n0\n0\n115425\n139027\n70446\n202368\n996673\n\n\nMonkey_distance_Engram2 = [\n287881.2\n87005.4\n307909.6\n244385.9\n492518.1\n271660.1\n181082.0\n404573.4\n2277015.8\nMonkey_distance_Engram3 = [\n306036.7\n108255.3\n307909.6\n223643.6\n448805.7\n271660.1\n155536.8\n412624.5\n2234472.3\nMonkey_distance_Exgram = [\n306036.7\n108255.3\n307909.6\n223643.6\n363830.2\n271660.1\n240954.8\n412624.5\n2234914.8\nMonkey_distance_Halmak = [\n295533.3\n264632.4\n302685.6\n266868.2\n232101.5\n124933.7\n202761.5\n420817.8\n2110334.0\nMonkey_distance_Hieamtsrn = [\n215675.6\n90765.0\n309675.2\n243381.4\n473579.3\n228190.8\n163914.8\n385247.7\n2110429.8\nMonkey_distance_ColemakModDH = [\n126843.9\n92966.8\n231423.8\n490053.3\n524390.2\n170629.6\n130356.3\n345686.9\n2112350.7\nMonkey_distance_Norman = [\n132110.3\n92966.8\n301566.9\n366496.9\n383234.5\n311394.7\n208883.8\n338028.1\n2134682.0\nMonkey_distance_Workman = [\n121983.0\n174634.7\n364188.8\n453196.3\n365002.2\n170629.6\n139750.5\n352283.9\n2141668.9\nMonkey_distance_MTGap = [\n192713.9\n104486.4\n285710.8\n370830.8\n397898.9\n144548.0\n209947.8\n328634.9\n2034771.4\nMonkey_distance_QGMLWB = [\n136813.8\n96492.7\n241996.1\n595571.1\n570040.8\n170629.6\n102578.4\n340702.4\n2254824.8\nMonkey_distance_Colemak = [\n126843.9\n92966.8\n231423.8\n495958.1\n509719.4\n170629.6\n130356.3\n345686.9\n2103584.8\nMonkey_distance_Asset = [\n130692.4\n92966.8\n231423.8\n408567.9\n536933.5\n170629.6\n208883.8\n340087.6\n2120185.3\nMonkey_distance_CapewellDvorak = [ = [\n179817.5\n66233.2\n184813.1\n335112.6\n517078.3\n169126.6\n335367.4\n308874.5\n2096423.1\nMonkey_distance_Klausler = [\n189634.1\n102772.3\n143944.4\n337816.2\n571359.5\n191574.9\n171921.3\n399757.3\n2108780.0\nMonkey_distance_Dvorak = [\n189702.0\n61829.1\n53399.5\n504031.6\n551454.7\n223571.7\n312411.7\n400559.7\n2296960.1\n\n\nMonkey_taps_Engram2 = [\n92936\n97071\n207397\n143198\n177747\n161463\n112149\n144428\n1136389\nMonkey_taps_Engram3 = [\n98494\n101990\n207397\n138279\n177747\n161463\n110349\n140837\n1136556\nMonkey_taps_Exgram = [\n98494\n101990\n207397\n138279\n159441\n161463\n128655\n140837\n1136556\nMonkey_taps_Halmak = [\n131929\n123673\n149956\n158700\n140841\n158621\n126972\n147301\n1137993\nMonkey_taps_Hieamtsrn = [\n96598\n98296\n207799\n144129\n208856\n125085\n110860\n143658\n1135281\nMonkey_taps_ColemakModDH = [\n106686\n87550\n124984\n205346\n206013\n169195\n106687\n130663\n1137124\nMonkey_taps_Norman = [\n107615\n90549\n201678\n173877\n169588\n154507\n133197\n106161\n1137172\nMonkey_taps_Workman = [\n105841\n111732\n145276\n195510\n167830\n169195\n111572\n130250\n1137206\nMonkey_taps_MTGap = [\n114730\n111335\n144194\n186110\n166760\n163172\n120800\n129682\n1136783\nMonkey_taps_QGMLWB = [\n64379\n91689\n153520\n227633\n224475\n169195\n100949\n105961\n1137801\nMonkey_taps_Colemak = [\n106686\n87550\n124984\n205346\n206013\n169195\n106687\n130663\n1137124\nMonkey_taps_Asset = [\n107367\n90549\n184614\n185623\n200566\n117621\n133197\n117621\n1137158\nMonkey_taps_CapewellDvorak = [ = [\n110641\n100465\n171873\n157410\n189032\n135015\n156700\n116652\n1137788\nMonkey_taps_Klausler = [\n112316\n109168\n163071\n159357\n215020\n141415\n95533\n141946\n1137826\nMonkey_taps_Dvorak = [\n119715\n92166\n140803\n154518\n181957\n148400\n151735\n148586\n1137880\n\n\nMonkey_samefinger_Engram2 = [\n624\n713\n1552\n4592\n0\n0\n3664\n419\n706\n6497\n18767\nMonkey_samefinger_Engram3 = [\n581\n1734\n1552\n3558\n0\n0\n3664\n419\n934\n5530\n17972\nMonkey_samefinger_Exgram = [\n581\n1734\n1552\n3558\n0\n0\n2087\n419\n1561\n5530\n17022\nMonkey_samefinger_Halmak = [\n2098\n500\n2403\n4955\n0\n0\n7589\n2901\n3720\n10263\n34429\nMonkey_samefinger_Hieamtsrn = [\n3873\n610\n982\n3709\n0\n0\n1933\n1409\n943\n6982\n20441\nMonkey_samefinger_ColemakModDH = [\n2312\n382\n1412\n2068\n0\n0\n3147\n3075\n1100\n10223\n23719\nMonkey_samefinger_Norman = [\n2601\n519\n24162\n1540\n0\n0\n12303\n9474\n6335\n10988\n67922\nMonkey_samefinger_Workman = [\n1904\n1104\n2266\n4780\n0\n0\n8396\n3075\n4767\n9283\n35575\nMonkey_samefinger_MTGap = [\n3347\n2238\n430\n1475\n0\n0\n5282\n1721\n1778\n12801\n29072\nMonkey_samefinger_QGMLWB = [\n556\n507\n3638\n7845\n0\n0\n22051\n3075\n2306\n10397\n50375\nMonkey_samefinger_Colemak = [\n2312\n382\n1412\n2068\n0\n0\n3147\n3075\n1100\n10223\n23719\nMonkey_samefinger_Asset = [\n2475\n519\n11403\n1252\n0\n0\n6595\n1094\n6335\n9030\n38703\nMonkey_samefinger_CapewellDvorak = [ = [\n3993\n645\n9990\n10055\n0\n0\n4469\n879\n2517\n6528\n39076\nMonkey_samefinger_Klausler = [\n4564\n572\n1716\n9511\n0\n0\n5754\n405\n112\n7149\n29783\nMonkey_samefinger_Dvorak = [\n4101\n272\n1839\n7967\n0\n0\n3971\n4193\n2400\n7754\n32497\n\n\nCoder_distance_Engram2 = [\n877832.2\n251277.1\n209134.1\n564336.6\n718232.8\n220925.3\n150502.2\n1653685.6\n4645926.0\nCoder_distance_Engram3 = [\n907818.0\n233267.7\n209134.1\n580416.4\n572756.0\n220925.3\n121442.3\n1649320.3\n4495080.3\nCoder_distance_Exgram = [\n907818.0\n233267.7\n209134.1\n580416.4\n501075.9\n220925.3\n193476.4\n1649320.3\n4495434.3\nCoder_distance_Halmak = [\n927452.3\n281483.4\n281032.7\n390764.7\n393970.7\n168575.6\n345586.7\n1637800.1\n4426666.2\nCoder_distance_Hieamtsrn = [\n674378.8\n208444.8\n294746.8\n442708.3\n362376.9\n228107.8\n170562.0\n1806099.6\n4187425.0\nCoder_distance_ColemakModDH = [\n834091.9\n143427.5\n240757.1\n469448.8\n353593.1\n231058.2\n335037.9\n1623384.2\n4230798.6\nCoder_distance_Norman = [\n842628.0\n143427.5\n272138.6\n375148.1\n358551.8\n339183.6\n418113.1\n1592984.8\n4342175.5\nCoder_distance_Workman = [\n844128.7\n215481.3\n336872.0\n413584.9\n330419.7\n231058.2\n381234.9\n1598126.5\n4350906.2\nCoder_distance_MTGap = [\n924674.9\n184330.1\n171241.2\n390563.8\n320175.3\n215502.6\n375146.3\n1591054.9\n4172689.0\nCoder_distance_QGMLWB = [\n849510.1\n164435.3\n246231.4\n547042.6\n474932.2\n231058.2\n329271.0\n1632956.3\n4475437.2\nCoder_distance_Colemak = [\n834091.9\n143427.5\n240757.1\n476640.4\n356360.6\n231058.2\n335037.9\n1623384.2\n4240757.7\nCoder_distance_Asset = [\n842914.8\n143427.5\n240757.1\n391631.5\n359240.9\n231058.2\n418113.1\n1592778.0\n4219921.0\nCoder_distance_CapewellDvorak = [ = [\n874378.6\n196699.9\n233251.5\n357968.5\n460749.1\n136512.9\n467951.0\n1637842.1\n4365353.6\nCoder_distance_Klausler = [\n790705.3\n233686.9\n225598.9\n435935.6\n482220.0\n184979.3\n350164.5\n1722681.0\n4425971.6\nCoder_distance_Dvorak = [\n914749.7\n168161.3\n131040.4\n530219.8\n478086.8\n345318.3\n468779.3\n1505054.4\n4541410.0\n\n\nCoder_taps_Engram2 = [\n179443\n95161\n126847\n172429\n178254\n115531\n77841\n280194\n1225700\nCoder_taps_Engram3 = [\n188293\n90868\n126847\n176722\n178254\n115531\n81218\n268297\n1226030\nCoder_taps_Exgram = [\n188293\n90868\n126847\n176722\n161204\n115531\n98268\n268297\n1226030\nCoder_taps_Halmak = [\n215122\n78979\n120918\n148327\n131794\n114210\n104058\n297191\n1210599\nCoder_taps_Hieamtsrn = [\n137133\n97595\n146721\n147243\n146296\n97339\n92392\n319326\n1184045\nCoder_taps_ColemakModDH = [\n192799\n78175\n97939\n162075\n138163\n129042\n110601\n298254\n1207048\nCoder_taps_Norman = [\n194318\n71224\n138055\n136504\n137838\n135344\n124049\n268098\n1205430\nCoder_taps_Workman = [\n194582\n90262\n95403\n146994\n130734\n129042\n113013\n305939\n1205969\nCoder_taps_MTGap = [\n213957\n84722\n90769\n148421\n118503\n125712\n120785\n303411\n1206280\nCoder_taps_QGMLWB = [\n176627\n76435\n117817\n184267\n156070\n129042\n98268\n272159\n1210685\nCoder_taps_Colemak = [\n192799\n78175\n97939\n162075\n138163\n129042\n110601\n298254\n1207048\nCoder_taps_Asset = [\n194369\n71224\n130014\n141947\n134296\n105958\n124049\n303583\n1205440\nCoder_taps_CapewellDvorak = [ = [\n203270\n88757\n129480\n130704\n126723\n92977\n147416\n293510\n1212837\nCoder_taps_Klausler = [\n181773\n99020\n126312\n149403\n171308\n105034\n77160\n303347\n1213357\nCoder_taps_Dvorak = [\n221149\n77968\n105395\n137824\n121862\n126881\n153238\n269361\n1213678\n\n\nCoder_samefinger_Engram2 = [\n9272\n1324\n857\n6315\n0\n0\n5654\n1688\n915\n36874\n62899\nCoder_samefinger_Engram3 = [\n9676\n603\n857\n7089\n0\n0\n5654\n1688\n510\n34995\n61072\nCoder_samefinger_Exgram = [\n9676\n603\n857\n7089\n0\n0\n5019\n1688\n1212\n34995\n61139\nCoder_samefinger_Halmak = [\n16951\n544\n2588\n7636\n0\n0\n7621\n5215\n4463\n27377\n72395\nCoder_samefinger_Hieamtsrn = [\n5166\n1065\n1120\n5888\n0\n0\n3723\n1326\n510\n60551\n79349\nCoder_samefinger_ColemakModDH = [\n10196\n955\n1411\n4751\n0\n0\n2614\n3365\n1401\n34228\n58921\nCoder_samefinger_Norman = [\n10801\n1233\n12799\n3018\n0\n0\n14799\n9320\n6465\n31441\n89876\nCoder_samefinger_Workman = [\n9964\n1662\n1457\n6050\n0\n0\n4241\n3365\n4832\n34692\n66263\nCoder_samefinger_MTGap = [\n17801\n2099\n370\n4142\n0\n0\n4224\n2776\n1339\n36491\n69242\nCoder_samefinger_QGMLWB = [\n10519\n1196\n4451\n7350\n0\n0\n14369\n3365\n1870\n31563\n74683\nCoder_samefinger_Colemak = [\n10196\n955\n1411\n4751\n0\n0\n2614\n3365\n1401\n34228\n58921\nCoder_samefinger_Asset = [\n10785\n1233\n7555\n3442\n0\n0\n5637\n1528\n6465\n33798\n70443\nCoder_samefinger_CapewellDvorak = [ = [\n12411\n3269\n6936\n7032\n0\n0\n3443\n1019\n3339\n38148\n75597\nCoder_samefinger_Klausler = [\n11460\n3283\n2859\n8854\n0\n0\n5681\n1524\n552\n33678\n67891\nCoder_samefinger_Dvorak = [\n18188\n1430\n1783\n8092\n0\n0\n3902\n4404\n2784\n30459\n71042\n\n\nRosetta_distance_Engram2 = [\n44991.5\n7132.2\n14832.8\n28019.2\n30817.0\n12268.0\n7927.5\n79880.8\n225869.1\nRosetta_distance_Engram3 = [\n46518.5\n8103.9\n14832.8\n26983.5\n25039.1\n12268.0\n4741.4\n82114.3\n220601.4\nRosetta_distance_Exgram = [\n46518.5\n8103.9\n14832.8\n26983.5\n23004.2\n12268.0\n6747.5\n82114.3\n220572.7\nRosetta_distance_Halmak = [\n46752.7\n13288.8\n15996.4\n18794.0\n16593.5\n4236.1\n15405.1\n83326.0\n214392.6\nRosetta_distance_Hieamtsrn = [\n33992.7\n8080.7\n19808.7\n20310.5\n18772.1\n9620.5\n5991.4\n89583.0\n206159.5\nRosetta_distance_ColemakModDH = [\n40632.6\n4928.6\n11772.3\n26243.1\n16451.7\n11539.1\n12760.5\n81756.0\n206084.0\nRosetta_distance_Norman = [\n41775.5\n4928.6\n11968.5\n21363.2\n15789.5\n17462.6\n15850.0\n77820.3\n206958.3\nRosetta_distance_Workman = [\n41398.3\n8399.6\n18310.4\n21963.3\n12561.3\n11539.1\n16400.0\n81426.2\n211998.3\nRosetta_distance_MTGap = [\n46607.6\n8211.0\n8230.9\n19082.8\n13281.8\n7549.0\n17171.2\n80587.3\n200721.5\nRosetta_distance_QGMLWB = [\n41985.1\n6200.8\n13339.0\n22606.8\n20494.3\n11539.1\n16180.3\n82675.6\n215021.0\nRosetta_distance_Colemak = [\n40632.6\n4928.6\n11772.3\n24460.1\n16853.3\n11539.1\n12760.5\n81756.0\n204702.6\nRosetta_distance_Asset = [\n41889.6\n4928.6\n11772.3\n19769.7\n18199.7\n11539.1\n15850.0\n77993.2\n201942.3\nRosetta_distance_CapewellDvorak = [ = [\n41987.1\n10627.3\n10004.7\n17120.2\n21158.8\n4871.5\n19273.5\n84602.6\n209645.7\nRosetta_distance_Klausler = [\n39063.6\n12924.4\n9792.2\n19038.5\n20370.3\n9859.8\n15293.3\n87501.5\n213843.5\nRosetta_distance_Dvorak = [\n44489.8\n9803.6\n6079.9\n22878.6\n24383.9\n13549.0\n22804.3\n77781.2\n221770.3\n\n\nRosetta_taps_Engram2 = [\n8696\n3632\n6968\n8525\n7521\n5544\n3818\n13257\n57961\nRosetta_taps_Engram3 = [\n9215\n3846\n6968\n8311\n7521\n5544\n3467\n13137\n58009\nRosetta_taps_Exgram = [\n9215\n3846\n6968\n8311\n7224\n5544\n3764\n13137\n58009\nRosetta_taps_Halmak = [\n10669\n3810\n6091\n7124\n5783\n4247\n6091\n14093\n57908\nRosetta_taps_Hieamtsrn = [\n6845\n4134\n7893\n6467\n7039\n4355\n3862\n15743\n56338\nRosetta_taps_ColemakModDH = [\n8944\n3088\n4639\n7801\n6553\n6256\n4857\n15300\n57438\nRosetta_taps_Norman = [\n9149\n2997\n5880\n7014\n6228\n7010\n6518\n12452\n57248\nRosetta_taps_Workman = [\n9076\n3916\n4992\n6692\n5503\n6256\n6624\n14505\n57564\nRosetta_taps_MTGap = [\n12570\n3647\n4150\n6784\n5341\n5015\n5386\n14583\n57476\nRosetta_taps_QGMLWB = [\n8555\n3322\n5558\n7893\n6731\n6256\n6514\n12964\n57793\nRosetta_taps_Colemak = [\n8944\n3088\n4639\n7801\n6553\n6256\n4857\n15300\n57438\nRosetta_taps_Asset = [\n9169\n2997\n5811\n6694\n6788\n5485\n6518\n13830\n57292\nRosetta_taps_CapewellDvorak = [ = [\n10942\n4685\n5695\n6174\n6066\n3728\n6225\n14329\n57844\nRosetta_taps_Klausler = [\n10185\n5540\n5299\n6589\n7440\n4978\n3590\n14426\n58047\nRosetta_taps_Dvorak = [\n10282\n5868\n4778\n5783\n6186\n5029\n7104\n13026\n58056\n\n\nRosetta_samefinger_Engram2 = [\n542\n26\n11\n330\n0\n0\n155\n35\n30\n1782\n2911\nRosetta_samefinger_Engram3 = [\n546\n14\n11\n370\n0\n0\n155\n35\n14\n1497\n2642\nRosetta_samefinger_Exgram = [\n546\n14\n11\n370\n0\n0\n137\n35\n47\n1497\n2657\nRosetta_samefinger_Halmak = [\n625\n9\n55\n319\n0\n0\n145\n106\n121\n1316\n2696\nRosetta_samefinger_Hieamtsrn = [\n224\n24\n31\n293\n0\n0\n75\n113\n32\n2870\n3662\nRosetta_samefinger_ColemakModDH = [\n541\n20\n116\n155\n0\n0\n74\n54\n38\n1666\n2664\nRosetta_samefinger_Norman = [\n583\n63\n405\n119\n0\n0\n463\n286\n314\n1468\n3701\nRosetta_samefinger_Workman = [\n474\n86\n38\n128\n0\n0\n101\n54\n286\n1608\n2775\nRosetta_samefinger_MTGap = [\n1419\n21\n5\n144\n0\n0\n166\n16\n79\n1786\n3636\nRosetta_samefinger_QGMLWB = [\n444\n62\n75\n671\n0\n0\n605\n54\n612\n1508\n4031\nRosetta_samefinger_Colemak = [\n541\n20\n116\n155\n0\n0\n74\n54\n38\n1666\n2664\nRosetta_samefinger_Asset = [\n583\n63\n310\n76\n0\n0\n130\n25\n314\n1509\n3010\nRosetta_samefinger_CapewellDvorak = [ = [\n848\n238\n223\n458\n0\n0\n88\n29\n131\n2489\n4504\nRosetta_samefinger_Klausler = [\n767\n253\n21\n573\n0\n0\n180\n36\n34\n1858\n3722\nRosetta_samefinger_Dvorak = [\n869\n189\n50\n202\n0\n0\n139\n83\n65\n1645\n3242\n\n```\n\n## Keyboard Layout Analyzer analysis of individual measures <a name=\"KLAmeasures\">\n    \n### Construct tables\n\n\n```python\nlayout_names2 = ['Engram v2','Engram v2.5','Engram v3','Halmak','Hieamtsrn','Colemak Mod-DH',\n                'Norman','Workman','MTGap 2.0','QGMLWB','Colemak',\n                'Asset','Capewell-Dvorak','Klausler','Dvorak','QWERTY']\nlayout_abbrs2 = ['Engram2','Engram25','Engram3','Halmak','Hieamtsrn','ColemakModDH',\n                'Norman','Workman','MTGap','QGMLWB','Colemak',\n                'Asset','CapewellDvorak','Klausler','Dvorak','QWERTY']\nfinger_names = [\"left little\", \"left ring\", \"left middle\", \"left index\",\n                \"right index\", \"right middle\", \"right ring\", \"right little\", \"total\"]\nmeasure_abbrs = [\"distance\", \"taps\", \"samefinger\"]\nempty_matrix = np.zeros((len(layout_names2), len(text_names)))\n\n# Finger distances (cm)  \ntotal_finger_distances = empty_matrix.copy()\nleft_little_finger_distances = empty_matrix.copy()\nright_little_finger_distances = empty_matrix.copy()\nleft_index_finger_distances = empty_matrix.copy()\nright_index_finger_distances = empty_matrix.copy()\n# Finger taps  \nleft_little_finger_taps = empty_matrix.copy()\nright_little_finger_taps = empty_matrix.copy()\n# Same-finger, different key bigram taps  \nsame_finger_different_key_taps = empty_matrix.copy()  \n# Balance between left and right hands (percent, left side negative)\nhand_balances = empty_matrix.copy()\n\nfor ilayout, layout_abbr in enumerate(layout_abbrs2):\n    for itext, text_abbr in enumerate(text_abbrs):\n        exec('distances = {0}_{1}_{2}'.format(text_abbr, measure_abbrs[0], layout_abbr))\n        exec('taps = {0}_{1}_{2}'.format(text_abbr, measure_abbrs[1], layout_abbr))\n        exec('samefingers = {0}_{1}_{2}'.format(text_abbr, measure_abbrs[2], layout_abbr))\n        total_finger_distances[ilayout, itext] = np.sum(distances)\n        left_little_finger_distances[ilayout, itext] = distances[0]\n        right_little_finger_distances[ilayout, itext] = distances[7]\n        left_index_finger_distances[ilayout, itext] = distances[3]\n        right_index_finger_distances[ilayout, itext] = distances[4]\n        left_little_finger_taps[ilayout, itext] = taps[0]\n        right_little_finger_taps[ilayout, itext] = taps[7]\n        same_finger_different_key_taps[ilayout, itext] = np.sum(samefingers)\n        hand_balances[ilayout, itext] = 100 * (np.sum(taps[4:8]) - np.sum(taps[0:4])) / np.sum(taps[0:8]) \n\n```\n\n\n```python\nscore_matrices = [\n    total_finger_distances,\n    left_little_finger_distances,\n    right_little_finger_distances,\n    left_index_finger_distances,\n    right_index_finger_distances,\n    left_little_finger_taps,\n    right_little_finger_taps,\n    same_finger_different_key_taps,\n    hand_balances]\nmatrix_labels = [\n    \"Total finger distances\",\n    \"Left little finger distances\",\n    \"Right little finger distances\",\n    \"Left index finger distances\",\n    \"Right index finger distances\",\n    \"Left little finger taps\",\n    \"Right little finger taps\",\n    \"Same finger different key taps\",\n    \"Hand balances\"]\n\ndivide_bys = [100,100,100,100,100,1,1,1,1]\ndisplay_ints = [True,True,True,True,True,True,True,True,False]\n\nfor imatrix, score_matrix in enumerate(score_matrices):\n    matrix_label = matrix_labels[imatrix]\n    divide_by = divide_bys[imatrix]\n    display_int = display_ints[imatrix]\n    print('\\n\\n{0}\\n'.format(matrix_label))\n    print(\"| Layout |\", end='')\n    for itext in range(len(text_names)):\n        print(\" {0} |\".format(text_abbrs[itext]), end='')\n    print(\"\")\n    print(\"| --- |\", end='')\n    for itext in range(len(text_names)):\n        print(\" --- |\", end='')\n    for ilayout in range(len(layout_names2)):\n        print(\"\")\n        for itext in range(len(text_names)):\n            score = score_matrix[ilayout, itext]\n            if divide_by > 1:\n                if display_int:\n                    score = '{0:0.0f}'.format(np.int(score_matrix[ilayout, itext])/100)\n                else:\n                    score = '{0:0.2f}'.format(np.int(score_matrix[ilayout, itext])/100)\n            else:\n                if display_int:\n                    score = '{0:0.0f}'.format(np.float(score_matrix[ilayout, itext]))\n                else:\n                    score = '{0:0.2f}'.format(np.float(score_matrix[ilayout, itext]))\n            if itext == 0:\n                print(\"| {0} | {1} |\".format(layout_names2[ilayout], score), end='') \n            else:\n                print(\" {0} |\".format(score), end='')  \n\n```\n\n    \n    \n    Total finger distances\n    \n    | Layout | Alice | Memento | Tweets_100K | Tweets_20K | Tweets_MASC | Spoken_MASC | COCA_blogs | iweb | Monkey | Coder | Rosetta |\n    | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n    | Engram v2 | 566 | 14692 | 419215 | 132526 | 9338 | 8675 | 369688 | 2122428 | 66897 | 121992 | 5922 |\n    | Engram v2.5 | 581 | 14664 | 418898 | 132430 | 9110 | 8881 | 364615 | 2066500 | 65774 | 118645 | 5816 |\n    | Engram v3 | 581 | 14647 | 417532 | 132294 | 9102 | 8866 | 364165 | 2064657 | 65734 | 118636 | 5800 |\n    | Halmak | 527 | 14340 | 403026 | 131920 | 9122 | 8158 | 349569 | 2010306 | 63353 | 116433 | 5653 |\n    | Hieamtsrn | 544 | 14340 | 415403 | 133322 | 9188 | 8399 | 349726 | 2002603 | 62990 | 110227 | 5426 |\n    | Colemak Mod-DH | 549 | 13753 | 405828 | 131877 | 8957 | 8467 | 352487 | 2009008 | 63903 | 112411 | 5489 |\n    | Norman | 526 | 13998 | 403559 | 130814 | 8507 | 8225 | 352517 | 2031254 | 64017 | 114581 | 5490 |\n    | Workman | 528 | 13742 | 403910 | 130907 | 9088 | 8236 | 353539 | 2038019 | 64193 | 114758 | 5606 |\n    | MTGap 2.0 | 515 | 13527 | 396029 | 128049 | 8747 | 8265 | 340496 | 1939308 | 61611 | 110778 | 5352 |\n    | QGMLWB | 528 | 14684 | 420989 | 133989 | 9452 | 8466 | 369723 | 2128855 | 67002 | 117893 | 5687 |\n    | Colemak | 546 | 13734 | 407104 | 131671 | 8996 | 8430 | 351881 | 2004168 | 63686 | 112626 | 5458 |\n    | Asset | 547 | 14154 | 410554 | 132213 | 9050 | 8510 | 354715 | 2019875 | 64064 | 112119 | 5392 |\n    | Capewell-Dvorak | 527 | 14131 | 403672 | 129908 | 8964 | 8113 | 349514 | 2010879 | 63461 | 115380 | 5558 |\n    | Klausler | 538 | 14122 | 405001 | 130629 | 9055 | 8181 | 350589 | 2012388 | 63525 | 116691 | 5656 |\n    | Dvorak | 541 | 14528 | 425749 | 134617 | 9445 | 8391 | 371416 | 2127700 | 67529 | 118796 | 5814 |\n    | QWERTY | 789 | 17968 | 572030 | 173370 | 12263 | 11738 | 542839 | 3095912 | 97366 | 132669 | 6398 |\n    \n    Left little finger distances\n    \n    | Layout | Alice | Memento | Tweets_100K | Tweets_20K | Tweets_MASC | Spoken_MASC | COCA_blogs | iweb | Monkey | Coder | Rosetta |\n    | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n    | Engram v2 | 33 | 1661 | 28603 | 11444 | 805 | 424 | 22658 | 128098 | 4009 | 11680 | 598 |\n    | Engram v2.5 | 32 | 1671 | 28740 | 12059 | 838 | 423 | 23637 | 137365 | 4240 | 12044 | 615 |\n    | Engram v3 | 32 | 1671 | 28740 | 12059 | 838 | 423 | 23637 | 137365 | 4240 | 12044 | 615 |\n    | Halmak | 32 | 1583 | 31042 | 11232 | 706 | 534 | 24614 | 128539 | 4013 | 12465 | 658 |\n    | Hieamtsrn | 21 | 1554 | 19967 | 9605 | 584 | 375 | 17196 | 96839 | 3249 | 8928 | 456 |\n    | Colemak Mod-DH | 21 | 1357 | 21199 | 8607 | 529 | 381 | 15254 | 76511 | 2374 | 11650 | 566 |\n    | Norman | 20 | 1423 | 21352 | 8738 | 553 | 384 | 15704 | 79222 | 2447 | 11771 | 582 |\n    | Workman | 20 | 1336 | 20341 | 8465 | 520 | 374 | 14944 | 76750 | 2307 | 11794 | 576 |\n    | MTGap 2.0 | 30 | 1478 | 23490 | 9610 | 628 | 483 | 18993 | 100039 | 3150 | 12772 | 654 |\n    | QGMLWB | 21 | 1396 | 19278 | 8379 | 507 | 365 | 13986 | 69598 | 2163 | 11703 | 579 |\n    | Colemak | 21 | 1357 | 21199 | 8607 | 529 | 381 | 15254 | 76511 | 2374 | 11650 | 566 |\n    | Asset | 21 | 1417 | 21197 | 8708 | 550 | 383 | 15584 | 78791 | 2427 | 11776 | 584 |\n    | Capewell-Dvorak | 26 | 1629 | 23483 | 10495 | 669 | 402 | 17392 | 91700 | 3012 | 12059 | 586 |\n    | Klausler | 24 | 1622 | 25094 | 10195 | 648 | 409 | 17789 | 98962 | 3139 | 10961 | 548 |\n    | Dvorak | 27 | 1641 | 23502 | 10542 | 669 | 394 | 17851 | 94145 | 3206 | 12610 | 608 |\n    | QWERTY | 20 | 1360 | 21156 | 8604 | 532 | 380 | 15385 | 77757 | 2391 | 11612 | 574 |\n    \n    Right little finger distances\n    \n    | Layout | Alice | Memento | Tweets_100K | Tweets_20K | Tweets_MASC | Spoken_MASC | COCA_blogs | iweb | Monkey | Coder | Rosetta |\n    | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n    | Engram v2 | 37 | 2169 | 43562 | 17637 | 1059 | 1471 | 27599 | 161115 | 5695 | 20997 | 1011 |\n    | Engram v2.5 | 47 | 2223 | 47738 | 17735 | 1078 | 1567 | 29014 | 163358 | 5880 | 20727 | 973 |\n    | Engram v3 | 47 | 2213 | 47471 | 17724 | 1072 | 1562 | 28808 | 163058 | 5839 | 20646 | 970 |\n    | Halmak | 33 | 2293 | 39746 | 15532 | 1010 | 1445 | 22984 | 134783 | 5013 | 20261 | 1066 |\n    | Hieamtsrn | 43 | 2167 | 45368 | 17748 | 1112 | 1452 | 26600 | 155279 | 5411 | 22540 | 1120 |\n    | Colemak Mod-DH | 37 | 1990 | 39289 | 17159 | 1103 | 1459 | 23332 | 137552 | 4984 | 20236 | 1028 |\n    | Norman | 35 | 2046 | 37071 | 16596 | 1046 | 1447 | 21247 | 124299 | 4696 | 19640 | 959 |\n    | Workman | 36 | 2020 | 39605 | 17057 | 1108 | 1456 | 23439 | 135326 | 5061 | 20000 | 1018 |\n    | MTGap 2.0 | 32 | 2052 | 39523 | 15885 | 1070 | 1417 | 22061 | 131371 | 4737 | 19880 | 1011 |\n    | QGMLWB | 33 | 2295 | 38163 | 16712 | 1056 | 1422 | 21100 | 123679 | 4720 | 20139 | 1020 |\n    | Colemak | 37 | 1990 | 39289 | 17159 | 1103 | 1459 | 23332 | 137552 | 4984 | 20236 | 1028 |\n    | Asset | 34 | 2068 | 37241 | 16619 | 1065 | 1422 | 21809 | 129307 | 4813 | 19920 | 972 |\n    | Capewell-Dvorak | 35 | 2058 | 40927 | 15508 | 981 | 1447 | 22210 | 125580 | 4426 | 20535 | 1065 |\n    | Klausler | 41 | 2154 | 43650 | 17396 | 1122 | 1493 | 27840 | 162221 | 5527 | 21518 | 1098 |\n    | Dvorak | 47 | 2166 | 45609 | 16955 | 1099 | 1537 | 28238 | 161514 | 5578 | 18990 | 985 |\n    | QWERTY | 35 | 2039 | 39034 | 17264 | 1104 | 1449 | 24320 | 145897 | 5241 | 20353 | 1002 |\n    \n    Left index finger distances\n    \n    | Layout | Alice | Memento | Tweets_100K | Tweets_20K | Tweets_MASC | Spoken_MASC | COCA_blogs | iweb | Monkey | Coder | Rosetta |\n    | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n    | Engram v2 | 41 | 640 | 22344 | 6247 | 435 | 559 | 21386 | 119845 | 3706 | 7327 | 366 |\n    | Engram v2.5 | 36 | 546 | 18271 | 5457 | 368 | 503 | 19232 | 108615 | 3439 | 7538 | 353 |\n    | Engram v3 | 36 | 546 | 18271 | 5457 | 368 | 503 | 19232 | 108615 | 3439 | 7538 | 353 |\n    | Halmak | 30 | 579 | 23946 | 8481 | 604 | 403 | 21375 | 119770 | 3522 | 4539 | 202 |\n    | Hieamtsrn | 39 | 687 | 27872 | 7406 | 553 | 481 | 22158 | 121270 | 3704 | 5860 | 268 |\n    | Colemak Mod-DH | 57 | 921 | 38538 | 11285 | 796 | 592 | 38793 | 223369 | 6899 | 6251 | 342 |\n    | Norman | 46 | 706 | 32988 | 9131 | 85 | 500 | 31236 | 175133 | 5309 | 5042 | 282 |\n    | Workman | 52 | 760 | 36446 | 10584 | 780 | 585 | 36741 | 210242 | 6412 | 5557 | 288 |\n    | MTGap 2.0 | 48 | 802 | 33204 | 9764 | 694 | 492 | 30576 | 178619 | 5386 | 5276 | 254 |\n    | QGMLWB | 69 | 1013 | 41348 | 11806 | 899 | 690 | 44207 | 259903 | 8162 | 7259 | 302 |\n    | Colemak | 58 | 934 | 39640 | 11393 | 823 | 598 | 39300 | 224921 | 6952 | 6329 | 322 |\n    | Asset | 51 | 826 | 34739 | 9715 | 691 | 536 | 33441 | 187843 | 5887 | 5293 | 265 |\n    | Capewell-Dvorak | 36 | 666 | 30220 | 8779 | 611 | 526 | 29085 | 171000 | 4807 | 4790 | 229 |\n    | Klausler | 40 | 702 | 28978 | 9170 | 626 | 435 | 27515 | 160939 | 4856 | 5804 | 254 |\n    | Dvorak | 50 | 908 | 42181 | 11038 | 853 | 653 | 38995 | 226118 | 6641 | 6728 | 289 |\n    | QWERTY | 95 | 1429 | 60189 | 16971 | 1285 | 1070 | 65288 | 372241 | 11440 | 9211 | 435 |\n    \n    Right index finger distances\n    \n    | Layout | Alice | Memento | Tweets_100K | Tweets_20K | Tweets_MASC | Spoken_MASC | COCA_blogs | iweb | Monkey | Coder | Rosetta |\n    | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n    | Engram v2 | 53 | 1024 | 34818 | 10192 | 846 | 551 | 37026 | 216262 | 6684 | 9078 | 389 |\n    | Engram v2.5 | 60 | 1019 | 34821 | 10240 | 754 | 647 | 34944 | 191336 | 6204 | 7479 | 326 |\n    | Engram v3 | 49 | 907 | 33651 | 9576 | 711 | 612 | 31704 | 169835 | 5559 | 6962 | 350 |\n    | Halmak | 40 | 617 | 27940 | 7471 | 587 | 456 | 23076 | 128477 | 3811 | 4942 | 248 |\n    | Hieamtsrn | 64 | 1011 | 46382 | 11360 | 864 | 715 | 38464 | 217742 | 6707 | 5007 | 256 |\n    | Colemak Mod-DH | 67 | 1067 | 43775 | 11728 | 819 | 768 | 40459 | 224314 | 7263 | 4838 | 229 |\n    | Norman | 39 | 783 | 36039 | 9653 | 712 | 578 | 32304 | 189116 | 5464 | 4930 | 220 |\n    | Workman | 46 | 803 | 33802 | 8901 | 664 | 517 | 30376 | 176078 | 5258 | 4566 | 177 |\n    | MTGap 2.0 | 42 | 737 | 36478 | 9604 | 711 | 580 | 32249 | 185720 | 5578 | 4331 | 184 |\n    | QGMLWB | 61 | 1067 | 49600 | 12495 | 989 | 750 | 46246 | 264943 | 7953 | 6371 | 277 |\n    | Colemak | 65 | 1044 | 43311 | 11516 | 812 | 744 | 39648 | 220342 | 7102 | 4868 | 233 |\n    | Asset | 65 | 1073 | 48065 | 12691 | 895 | 839 | 42844 | 239079 | 7382 | 4886 | 249 |\n    | Capewell-Dvorak | 59 | 987 | 39221 | 10602 | 759 | 584 | 37987 | 221884 | 7102 | 5968 | 276 |\n    | Klausler | 66 | 970 | 40842 | 11258 | 862 | 693 | 42605 | 251133 | 7814 | 6504 | 279 |\n    | Dvorak | 61 | 1020 | 43094 | 11097 | 835 | 632 | 40406 | 230108 | 7388 | 6078 | 311 |\n    | QWERTY | 91 | 1523 | 63615 | 16201 | 1173 | 1182 | 61077 | 343059 | 10706 | 7162 | 318 |\n    \n    Left little finger taps\n    \n    | Layout | Alice | Memento | Tweets_100K | Tweets_20K | Tweets_MASC | Spoken_MASC | COCA_blogs | iweb | Monkey | Coder | Rosetta |\n    | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n    | Engram v2 | 702 | 36656 | 601505 | 220582 | 15909 | 8730 | 522938 | 3059178 | 94115 | 197655 | 9723 |\n    | Engram v2.5 | 690 | 36943 | 606711 | 234165 | 16744 | 8684 | 546593 | 3285822 | 99588 | 205947 | 10153 |\n    | Engram v3 | 690 | 36943 | 606711 | 234165 | 16744 | 8684 | 546593 | 3285822 | 99588 | 205947 | 10153 |\n    | Halmak | 1026 | 40010 | 744317 | 249220 | 15111 | 14724 | 649523 | 3444960 | 113279 | 213638 | 11624 |\n    | Hieamtsrn | 871 | 38038 | 558249 | 217201 | 13063 | 11808 | 528656 | 2879031 | 97916 | 150500 | 8512 |\n    | Colemak Mod-DH | 888 | 40313 | 710680 | 235125 | 14916 | 12481 | 628201 | 3447309 | 108553 | 225473 | 11097 |\n    | Norman | 890 | 39190 | 711129 | 236003 | 15228 | 12463 | 634103 | 3487747 | 109496 | 227863 | 11454 |\n    | Workman | 880 | 39389 | 696710 | 232550 | 14746 | 12391 | 623934 | 3451809 | 107612 | 228367 | 11166 |\n    | MTGap 2.0 | 1097 | 41900 | 787727 | 246806 | 16963 | 14984 | 689492 | 3868187 | 117057 | 246974 | 14475 |\n    | QGMLWB | 633 | 34584 | 471124 | 176349 | 10488 | 8555 | 373626 | 2059911 | 66281 | 206392 | 10503 |\n    | Colemak | 888 | 40313 | 710680 | 235125 | 14916 | 12481 | 628201 | 3447309 | 108553 | 225473 | 11097 |\n    | Asset | 893 | 39194 | 710005 | 235948 | 15207 | 12548 | 632891 | 3483248 | 109300 | 228074 | 11467 |\n    | Capewell-Dvorak | 1015 | 42979 | 792134 | 257611 | 17702 | 13822 | 663564 | 3679810 | 112125 | 228832 | 12033 |\n    | Klausler | 981 | 42318 | 829682 | 258500 | 17654 | 13899 | 671647 | 3831110 | 113958 | 205790 | 11228 |\n    | Dvorak | 1023 | 42052 | 751676 | 265209 | 17353 | 12872 | 677492 | 3739024 | 121505 | 246022 | 11379 |\n    | QWERTY | 876 | 37950 | 706895 | 233338 | 14886 | 12482 | 629320 | 3463858 | 108544 | 223338 | 11132 |\n    \n    Right little finger taps\n    \n    | Layout | Alice | Memento | Tweets_100K | Tweets_20K | Tweets_MASC | Spoken_MASC | COCA_blogs | iweb | Monkey | Coder | Rosetta |\n    | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n    | Engram v2 | 992 | 36036 | 878246 | 315596 | 19925 | 20185 | 723222 | 4239597 | 145817 | 294655 | 14543 |\n    | Engram v2.5 | 1188 | 37086 | 963903 | 317302 | 20562 | 22086 | 750777 | 4267126 | 148968 | 287671 | 13412 |\n    | Engram v3 | 1136 | 35621 | 929046 | 315415 | 19684 | 21408 | 723514 | 4222472 | 143489 | 277366 | 13027 |\n    | Halmak | 927 | 34370 | 854440 | 261398 | 18915 | 19900 | 638369 | 3689730 | 131312 | 302120 | 15207 |\n    | Hieamtsrn | 1047 | 35508 | 914629 | 320577 | 20935 | 19975 | 720370 | 4234858 | 144503 | 332278 | 16310 |\n    | Colemak Mod-DH | 1123 | 35858 | 924246 | 319835 | 21696 | 21528 | 680622 | 3943707 | 132401 | 308409 | 16009 |\n    | Norman | 1017 | 32507 | 701154 | 282448 | 17124 | 19804 | 499682 | 2747503 | 107837 | 279000 | 13199 |\n    | Workman | 996 | 34115 | 868000 | 301002 | 21336 | 19875 | 646056 | 3699865 | 132002 | 316062 | 15151 |\n    | MTGap 2.0 | 908 | 36771 | 942692 | 301638 | 22290 | 19895 | 659547 | 3798235 | 131301 | 313991 | 15502 |\n    | QGMLWB | 983 | 33753 | 706574 | 280334 | 17254 | 19594 | 497803 | 2724496 | 106987 | 281586 | 13523 |\n    | Colemak | 1123 | 35858 | 924246 | 319835 | 21696 | 21528 | 680622 | 3943707 | 132401 | 308409 | 16009 |\n    | Asset | 875 | 32748 | 709546 | 282876 | 19221 | 7724 | 549966 | 3304452 | 119259 | 314315 | 14540 |\n    | Capewell-Dvorak | 914 | 33547 | 819979 | 289475 | 18672 | 19711 | 594500 | 3505369 | 118109 | 304988 | 15694 |\n    | Klausler | 982 | 36300 | 874620 | 317922 | 20706 | 20629 | 715147 | 4303432 | 143207 | 315850 | 15636 |\n    | Dvorak | 1199 | 36285 | 955938 | 320119 | 21098 | 22179 | 762193 | 4517125 | 149645 | 280687 | 14173 |\n    | QWERTY | 570 | 28887 | 536961 | 245630 | 15586 | 14462 | 334346 | 2005118 | 76432 | 290115 | 13849 |\n    \n    Same finger different key taps\n    \n    | Layout | Alice | Memento | Tweets_100K | Tweets_20K | Tweets_MASC | Spoken_MASC | COCA_blogs | iweb | Monkey | Coder | Rosetta |\n    | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n    | Engram v2 | 216 | 9807 | 320406 | 120286 | 7728 | 3514 | 137290 | 1064640 | 37534 | 125798 | 5822 |\n    | Engram v2.5 | 270 | 11742 | 339358 | 118954 | 9080 | 3538 | 145178 | 1055230 | 36990 | 121912 | 5766 |\n    | Engram v3 | 252 | 12272 | 343824 | 117568 | 8270 | 3744 | 156244 | 1168198 | 39530 | 123242 | 5414 |\n    | Halmak | 666 | 14962 | 633920 | 205600 | 14044 | 7826 | 362786 | 2487382 | 83702 | 141290 | 6200 |\n    | Hieamtsrn | 244 | 12096 | 311000 | 119490 | 8316 | 3192 | 155674 | 1100116 | 40882 | 158698 | 7324 |\n    | Colemak Mod-DH | 362 | 10960 | 352578 | 151736 | 9298 | 4644 | 153984 | 1233770 | 47438 | 117842 | 5328 |\n    | Norman | 938 | 20012 | 721602 | 213890 | 16014 | 9022 | 595168 | 3885282 | 135844 | 179752 | 7402 |\n    | Workman | 550 | 13086 | 451280 | 136692 | 10698 | 6156 | 287622 | 1975564 | 71150 | 132526 | 5550 |\n    | MTGap 2.0 | 226 | 14550 | 397690 | 139130 | 10386 | 6252 | 176724 | 1532844 | 58144 | 138484 | 7272 |\n    | QGMLWB | 812 | 17820 | 637788 | 189700 | 14364 | 7838 | 456442 | 3027530 | 100750 | 149366 | 8062 |\n    | Colemak | 362 | 10960 | 352578 | 151736 | 9298 | 4644 | 153984 | 1233770 | 47438 | 117842 | 5328 |\n    | Asset | 520 | 13572 | 519018 | 155246 | 11802 | 5664 | 332860 | 2269342 | 77406 | 140886 | 6020 |\n    | Capewell-Dvorak | 556 | 14226 | 501178 | 163878 | 12214 | 6816 | 335056 | 2391416 | 78152 | 151194 | 9008 |\n    | Klausler | 408 | 14734 | 455658 | 174998 | 11410 | 5212 | 257878 | 1794604 | 59566 | 135782 | 7444 |\n    | Dvorak | 516 | 13970 | 492604 | 171488 | 12208 | 5912 | 263018 | 1993346 | 64994 | 142084 | 6484 |\n    | QWERTY | 880 | 19580 | 736894 | 204712 | 16632 | 9264 | 581944 | 3765246 | 130184 | 173598 | 8052 |\n    \n    Hand balances\n    \n    | Layout | Alice | Memento | Tweets_100K | Tweets_20K | Tweets_MASC | Spoken_MASC | COCA_blogs | iweb | Monkey | Coder | Rosetta |\n    | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n    | Engram v2 | 3.54 | 0.31 | 4.18 | 7.17 | 5.35 | 6.65 | 2.42 | 2.57 | 4.86 | 5.90 | 4.28 |\n    | Engram v2.5 | 3.79 | 0.02 | 4.02 | 5.71 | 4.10 | 6.72 | 1.67 | 1.32 | 3.90 | 4.58 | 2.85 |\n    | Engram v3 | 3.79 | 0.02 | 4.02 | 5.71 | 4.10 | 6.72 | 1.67 | 1.32 | 3.90 | 4.58 | 2.85 |\n    | Halmak | 2.34 | -1.67 | 2.03 | -3.02 | -1.40 | 7.58 | -0.85 | -0.56 | 0.16 | 4.71 | 5.96 |\n    | Hieamtsrn | 0.06 | -3.07 | 2.02 | 3.42 | 4.13 | 1.07 | 1.08 | 2.98 | 3.62 | 10.43 | 7.79 |\n    | Colemak Mod-DH | 10.15 | 5.66 | 11.04 | 6.74 | 9.18 | 18.14 | 7.09 | 6.39 | 7.70 | 9.81 | 11.69 |\n    | Norman | -2.34 | -1.19 | 2.46 | -0.17 | 3.89 | 5.91 | -2.29 | -2.05 | -0.92 | 8.21 | 9.30 |\n    | Workman | 1.48 | 0.55 | 3.62 | 1.68 | 5.09 | 7.93 | 1.02 | 1.58 | 1.79 | 10.23 | 11.22 |\n    | MTGap 2.0 | -4.35 | -2.73 | 1.33 | 0.51 | 3.49 | 4.11 | 0.20 | 1.67 | 2.05 | 8.65 | 3.63 |\n    | QGMLWB | 7.11 | 3.55 | 7.43 | 5.84 | 6.10 | 15.00 | 5.14 | 4.49 | 5.48 | 6.41 | 9.53 |\n    | Colemak | 10.15 | 5.66 | 11.04 | 6.74 | 9.18 | 18.14 | 7.09 | 6.39 | 7.70 | 9.81 | 11.69 |\n    | Asset | -0.51 | 0.36 | 4.56 | 1.22 | 5.58 | -1.07 | -1.03 | -0.78 | 0.05 | 8.59 | 10.55 |\n    | Capewell-Dvorak | 8.25 | -0.09 | 4.46 | 5.10 | 4.86 | 9.23 | 2.72 | 2.62 | 5.00 | 7.55 | 5.18 |\n    | Klausler | 2.97 | -3.06 | 1.53 | 4.18 | 4.21 | 6.88 | 2.17 | 2.47 | 4.35 | 7.11 | 4.96 |\n    | Dvorak | 10.59 | 1.48 | 7.00 | 8.78 | 8.49 | 12.00 | 8.03 | 8.46 | 10.76 | 9.24 | 7.77 |\n    | QWERTY | -9.58 | -5.51 | -3.25 | -6.14 | -3.32 | 0.25 | -11.23 | -11.75 | -10.92 | 1.50 | 4.59 |\n\n\n\nTotal finger distances\n\n| Layout | Alice | Memento | Tweets_100K | Tweets_20K | Tweets_MASC | Spoken_MASC | COCA_blogs | iweb | Monkey | Coder | Rosetta |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Engram v2 | 566 | 14692 | 419215 | 132526 | 9338 | 8675 | 369688 | 2122428 | 66897 | 121992 | 5922 |\n| Engram v2.5 | 581 | 14664 | 418898 | 132430 | 9110 | 8881 | 364615 | 2066500 | 65774 | 118645 | 5816 |\n| Engram v3 | 581 | 14647 | 417532 | 132294 | 9102 | 8866 | 364165 | 2064657 | 65734 | 118636 | 5800 |\n| Halmak | 527 | 14340 | 403026 | 131920 | 9122 | 8158 | 349569 | 2010306 | 63353 | 116433 | 5653 |\n| Hieamtsrn | 544 | 14340 | 415403 | 133322 | 9188 | 8399 | 349726 | 2002603 | 62990 | 110227 | 5426 |\n| Colemak Mod-DH | 549 | 13753 | 405828 | 131877 | 8957 | 8467 | 352487 | 2009008 | 63903 | 112411 | 5489 |\n| Norman | 526 | 13998 | 403559 | 130814 | 8507 | 8225 | 352517 | 2031254 | 64017 | 114581 | 5490 |\n| Workman | 528 | 13742 | 403910 | 130907 | 9088 | 8236 | 353539 | 2038019 | 64193 | 114758 | 5606 |\n| MTGap 2.0 | 515 | 13527 | 396029 | 128049 | 8747 | 8265 | 340496 | 1939308 | 61611 | 110778 | 5352 |\n| QGMLWB | 528 | 14684 | 420989 | 133989 | 9452 | 8466 | 369723 | 2128855 | 67002 | 117893 | 5687 |\n| Colemak | 546 | 13734 | 407104 | 131671 | 8996 | 8430 | 351881 | 2004168 | 63686 | 112626 | 5458 |\n| Asset | 547 | 14154 | 410554 | 132213 | 9050 | 8510 | 354715 | 2019875 | 64064 | 112119 | 5392 |\n| Capewell-Dvorak | 527 | 14131 | 403672 | 129908 | 8964 | 8113 | 349514 | 2010879 | 63461 | 115380 | 5558 |\n| Klausler | 538 | 14122 | 405001 | 130629 | 9055 | 8181 | 350589 | 2012388 | 63525 | 116691 | 5656 |\n| Dvorak | 541 | 14528 | 425749 | 134617 | 9445 | 8391 | 371416 | 2127700 | 67529 | 118796 | 5814 |\n| QWERTY | 789 | 17968 | 572030 | 173370 | 12263 | 11738 | 542839 | 3095912 | 97366 | 132669 | 6398 |\n\nLeft little finger distances\n\n| Layout | Alice | Memento | Tweets_100K | Tweets_20K | Tweets_MASC | Spoken_MASC | COCA_blogs | iweb | Monkey | Coder | Rosetta |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Engram v2 | 33 | 1661 | 28603 | 11444 | 805 | 424 | 22658 | 128098 | 4009 | 11680 | 598 |\n| Engram v2.5 | 32 | 1671 | 28740 | 12059 | 838 | 423 | 23637 | 137365 | 4240 | 12044 | 615 |\n| Engram v3 | 32 | 1671 | 28740 | 12059 | 838 | 423 | 23637 | 137365 | 4240 | 12044 | 615 |\n| Halmak | 32 | 1583 | 31042 | 11232 | 706 | 534 | 24614 | 128539 | 4013 | 12465 | 658 |\n| Hieamtsrn | 21 | 1554 | 19967 | 9605 | 584 | 375 | 17196 | 96839 | 3249 | 8928 | 456 |\n| Colemak Mod-DH | 21 | 1357 | 21199 | 8607 | 529 | 381 | 15254 | 76511 | 2374 | 11650 | 566 |\n| Norman | 20 | 1423 | 21352 | 8738 | 553 | 384 | 15704 | 79222 | 2447 | 11771 | 582 |\n| Workman | 20 | 1336 | 20341 | 8465 | 520 | 374 | 14944 | 76750 | 2307 | 11794 | 576 |\n| MTGap 2.0 | 30 | 1478 | 23490 | 9610 | 628 | 483 | 18993 | 100039 | 3150 | 12772 | 654 |\n| QGMLWB | 21 | 1396 | 19278 | 8379 | 507 | 365 | 13986 | 69598 | 2163 | 11703 | 579 |\n| Colemak | 21 | 1357 | 21199 | 8607 | 529 | 381 | 15254 | 76511 | 2374 | 11650 | 566 |\n| Asset | 21 | 1417 | 21197 | 8708 | 550 | 383 | 15584 | 78791 | 2427 | 11776 | 584 |\n| Capewell-Dvorak | 26 | 1629 | 23483 | 10495 | 669 | 402 | 17392 | 91700 | 3012 | 12059 | 586 |\n| Klausler | 24 | 1622 | 25094 | 10195 | 648 | 409 | 17789 | 98962 | 3139 | 10961 | 548 |\n| Dvorak | 27 | 1641 | 23502 | 10542 | 669 | 394 | 17851 | 94145 | 3206 | 12610 | 608 |\n| QWERTY | 20 | 1360 | 21156 | 8604 | 532 | 380 | 15385 | 77757 | 2391 | 11612 | 574 |\n\nRight little finger distances\n\n| Layout | Alice | Memento | Tweets_100K | Tweets_20K | Tweets_MASC | Spoken_MASC | COCA_blogs | iweb | Monkey | Coder | Rosetta |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Engram v2 | 37 | 2169 | 43562 | 17637 | 1059 | 1471 | 27599 | 161115 | 5695 | 20997 | 1011 |\n| Engram v2.5 | 47 | 2223 | 47738 | 17735 | 1078 | 1567 | 29014 | 163358 | 5880 | 20727 | 973 |\n| Engram v3 | 47 | 2213 | 47471 | 17724 | 1072 | 1562 | 28808 | 163058 | 5839 | 20646 | 970 |\n| Halmak | 33 | 2293 | 39746 | 15532 | 1010 | 1445 | 22984 | 134783 | 5013 | 20261 | 1066 |\n| Hieamtsrn | 43 | 2167 | 45368 | 17748 | 1112 | 1452 | 26600 | 155279 | 5411 | 22540 | 1120 |\n| Colemak Mod-DH | 37 | 1990 | 39289 | 17159 | 1103 | 1459 | 23332 | 137552 | 4984 | 20236 | 1028 |\n| Norman | 35 | 2046 | 37071 | 16596 | 1046 | 1447 | 21247 | 124299 | 4696 | 19640 | 959 |\n| Workman | 36 | 2020 | 39605 | 17057 | 1108 | 1456 | 23439 | 135326 | 5061 | 20000 | 1018 |\n| MTGap 2.0 | 32 | 2052 | 39523 | 15885 | 1070 | 1417 | 22061 | 131371 | 4737 | 19880 | 1011 |\n| QGMLWB | 33 | 2295 | 38163 | 16712 | 1056 | 1422 | 21100 | 123679 | 4720 | 20139 | 1020 |\n| Colemak | 37 | 1990 | 39289 | 17159 | 1103 | 1459 | 23332 | 137552 | 4984 | 20236 | 1028 |\n| Asset | 34 | 2068 | 37241 | 16619 | 1065 | 1422 | 21809 | 129307 | 4813 | 19920 | 972 |\n| Capewell-Dvorak | 35 | 2058 | 40927 | 15508 | 981 | 1447 | 22210 | 125580 | 4426 | 20535 | 1065 |\n| Klausler | 41 | 2154 | 43650 | 17396 | 1122 | 1493 | 27840 | 162221 | 5527 | 21518 | 1098 |\n| Dvorak | 47 | 2166 | 45609 | 16955 | 1099 | 1537 | 28238 | 161514 | 5578 | 18990 | 985 |\n| QWERTY | 35 | 2039 | 39034 | 17264 | 1104 | 1449 | 24320 | 145897 | 5241 | 20353 | 1002 |\n\nLeft index finger distances\n\n| Layout | Alice | Memento | Tweets_100K | Tweets_20K | Tweets_MASC | Spoken_MASC | COCA_blogs | iweb | Monkey | Coder | Rosetta |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Engram v2 | 41 | 640 | 22344 | 6247 | 435 | 559 | 21386 | 119845 | 3706 | 7327 | 366 |\n| Engram v2.5 | 36 | 546 | 18271 | 5457 | 368 | 503 | 19232 | 108615 | 3439 | 7538 | 353 |\n| Engram v3 | 36 | 546 | 18271 | 5457 | 368 | 503 | 19232 | 108615 | 3439 | 7538 | 353 |\n| Halmak | 30 | 579 | 23946 | 8481 | 604 | 403 | 21375 | 119770 | 3522 | 4539 | 202 |\n| Hieamtsrn | 39 | 687 | 27872 | 7406 | 553 | 481 | 22158 | 121270 | 3704 | 5860 | 268 |\n| Colemak Mod-DH | 57 | 921 | 38538 | 11285 | 796 | 592 | 38793 | 223369 | 6899 | 6251 | 342 |\n| Norman | 46 | 706 | 32988 | 9131 | 85 | 500 | 31236 | 175133 | 5309 | 5042 | 282 |\n| Workman | 52 | 760 | 36446 | 10584 | 780 | 585 | 36741 | 210242 | 6412 | 5557 | 288 |\n| MTGap 2.0 | 48 | 802 | 33204 | 9764 | 694 | 492 | 30576 | 178619 | 5386 | 5276 | 254 |\n| QGMLWB | 69 | 1013 | 41348 | 11806 | 899 | 690 | 44207 | 259903 | 8162 | 7259 | 302 |\n| Colemak | 58 | 934 | 39640 | 11393 | 823 | 598 | 39300 | 224921 | 6952 | 6329 | 322 |\n| Asset | 51 | 826 | 34739 | 9715 | 691 | 536 | 33441 | 187843 | 5887 | 5293 | 265 |\n| Capewell-Dvorak | 36 | 666 | 30220 | 8779 | 611 | 526 | 29085 | 171000 | 4807 | 4790 | 229 |\n| Klausler | 40 | 702 | 28978 | 9170 | 626 | 435 | 27515 | 160939 | 4856 | 5804 | 254 |\n| Dvorak | 50 | 908 | 42181 | 11038 | 853 | 653 | 38995 | 226118 | 6641 | 6728 | 289 |\n| QWERTY | 95 | 1429 | 60189 | 16971 | 1285 | 1070 | 65288 | 372241 | 11440 | 9211 | 435 |\n\nRight index finger distances\n\n| Layout | Alice | Memento | Tweets_100K | Tweets_20K | Tweets_MASC | Spoken_MASC | COCA_blogs | iweb | Monkey | Coder | Rosetta |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Engram v2 | 53 | 1024 | 34818 | 10192 | 846 | 551 | 37026 | 216262 | 6684 | 9078 | 389 |\n| Engram v2.5 | 60 | 1019 | 34821 | 10240 | 754 | 647 | 34944 | 191336 | 6204 | 7479 | 326 |\n| Engram v3 | 49 | 907 | 33651 | 9576 | 711 | 612 | 31704 | 169835 | 5559 | 6962 | 350 |\n| Halmak | 40 | 617 | 27940 | 7471 | 587 | 456 | 23076 | 128477 | 3811 | 4942 | 248 |\n| Hieamtsrn | 64 | 1011 | 46382 | 11360 | 864 | 715 | 38464 | 217742 | 6707 | 5007 | 256 |\n| Colemak Mod-DH | 67 | 1067 | 43775 | 11728 | 819 | 768 | 40459 | 224314 | 7263 | 4838 | 229 |\n| Norman | 39 | 783 | 36039 | 9653 | 712 | 578 | 32304 | 189116 | 5464 | 4930 | 220 |\n| Workman | 46 | 803 | 33802 | 8901 | 664 | 517 | 30376 | 176078 | 5258 | 4566 | 177 |\n| MTGap 2.0 | 42 | 737 | 36478 | 9604 | 711 | 580 | 32249 | 185720 | 5578 | 4331 | 184 |\n| QGMLWB | 61 | 1067 | 49600 | 12495 | 989 | 750 | 46246 | 264943 | 7953 | 6371 | 277 |\n| Colemak | 65 | 1044 | 43311 | 11516 | 812 | 744 | 39648 | 220342 | 7102 | 4868 | 233 |\n| Asset | 65 | 1073 | 48065 | 12691 | 895 | 839 | 42844 | 239079 | 7382 | 4886 | 249 |\n| Capewell-Dvorak | 59 | 987 | 39221 | 10602 | 759 | 584 | 37987 | 221884 | 7102 | 5968 | 276 |\n| Klausler | 66 | 970 | 40842 | 11258 | 862 | 693 | 42605 | 251133 | 7814 | 6504 | 279 |\n| Dvorak | 61 | 1020 | 43094 | 11097 | 835 | 632 | 40406 | 230108 | 7388 | 6078 | 311 |\n| QWERTY | 91 | 1523 | 63615 | 16201 | 1173 | 1182 | 61077 | 343059 | 10706 | 7162 | 318 |\n\nLeft little finger taps\n\n| Layout | Alice | Memento | Tweets_100K | Tweets_20K | Tweets_MASC | Spoken_MASC | COCA_blogs | iweb | Monkey | Coder | Rosetta |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Engram v2 | 702 | 36656 | 601505 | 220582 | 15909 | 8730 | 522938 | 3059178 | 94115 | 197655 | 9723 |\n| Engram v2.5 | 690 | 36943 | 606711 | 234165 | 16744 | 8684 | 546593 | 3285822 | 99588 | 205947 | 10153 |\n| Engram v3 | 690 | 36943 | 606711 | 234165 | 16744 | 8684 | 546593 | 3285822 | 99588 | 205947 | 10153 |\n| Halmak | 1026 | 40010 | 744317 | 249220 | 15111 | 14724 | 649523 | 3444960 | 113279 | 213638 | 11624 |\n| Hieamtsrn | 871 | 38038 | 558249 | 217201 | 13063 | 11808 | 528656 | 2879031 | 97916 | 150500 | 8512 |\n| Colemak Mod-DH | 888 | 40313 | 710680 | 235125 | 14916 | 12481 | 628201 | 3447309 | 108553 | 225473 | 11097 |\n| Norman | 890 | 39190 | 711129 | 236003 | 15228 | 12463 | 634103 | 3487747 | 109496 | 227863 | 11454 |\n| Workman | 880 | 39389 | 696710 | 232550 | 14746 | 12391 | 623934 | 3451809 | 107612 | 228367 | 11166 |\n| MTGap 2.0 | 1097 | 41900 | 787727 | 246806 | 16963 | 14984 | 689492 | 3868187 | 117057 | 246974 | 14475 |\n| QGMLWB | 633 | 34584 | 471124 | 176349 | 10488 | 8555 | 373626 | 2059911 | 66281 | 206392 | 10503 |\n| Colemak | 888 | 40313 | 710680 | 235125 | 14916 | 12481 | 628201 | 3447309 | 108553 | 225473 | 11097 |\n| Asset | 893 | 39194 | 710005 | 235948 | 15207 | 12548 | 632891 | 3483248 | 109300 | 228074 | 11467 |\n| Capewell-Dvorak | 1015 | 42979 | 792134 | 257611 | 17702 | 13822 | 663564 | 3679810 | 112125 | 228832 | 12033 |\n| Klausler | 981 | 42318 | 829682 | 258500 | 17654 | 13899 | 671647 | 3831110 | 113958 | 205790 | 11228 |\n| Dvorak | 1023 | 42052 | 751676 | 265209 | 17353 | 12872 | 677492 | 3739024 | 121505 | 246022 | 11379 |\n| QWERTY | 876 | 37950 | 706895 | 233338 | 14886 | 12482 | 629320 | 3463858 | 108544 | 223338 | 11132 |\n\nRight little finger taps\n\n| Layout | Alice | Memento | Tweets_100K | Tweets_20K | Tweets_MASC | Spoken_MASC | COCA_blogs | iweb | Monkey | Coder | Rosetta |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Engram v2 | 992 | 36036 | 878246 | 315596 | 19925 | 20185 | 723222 | 4239597 | 145817 | 294655 | 14543 |\n| Engram v2.5 | 1188 | 37086 | 963903 | 317302 | 20562 | 22086 | 750777 | 4267126 | 148968 | 287671 | 13412 |\n| Engram v3 | 1136 | 35621 | 929046 | 315415 | 19684 | 21408 | 723514 | 4222472 | 143489 | 277366 | 13027 |\n| Halmak | 927 | 34370 | 854440 | 261398 | 18915 | 19900 | 638369 | 3689730 | 131312 | 302120 | 15207 |\n| Hieamtsrn | 1047 | 35508 | 914629 | 320577 | 20935 | 19975 | 720370 | 4234858 | 144503 | 332278 | 16310 |\n| Colemak Mod-DH | 1123 | 35858 | 924246 | 319835 | 21696 | 21528 | 680622 | 3943707 | 132401 | 308409 | 16009 |\n| Norman | 1017 | 32507 | 701154 | 282448 | 17124 | 19804 | 499682 | 2747503 | 107837 | 279000 | 13199 |\n| Workman | 996 | 34115 | 868000 | 301002 | 21336 | 19875 | 646056 | 3699865 | 132002 | 316062 | 15151 |\n| MTGap 2.0 | 908 | 36771 | 942692 | 301638 | 22290 | 19895 | 659547 | 3798235 | 131301 | 313991 | 15502 |\n| QGMLWB | 983 | 33753 | 706574 | 280334 | 17254 | 19594 | 497803 | 2724496 | 106987 | 281586 | 13523 |\n| Colemak | 1123 | 35858 | 924246 | 319835 | 21696 | 21528 | 680622 | 3943707 | 132401 | 308409 | 16009 |\n| Asset | 875 | 32748 | 709546 | 282876 | 19221 | 7724 | 549966 | 3304452 | 119259 | 314315 | 14540 |\n| Capewell-Dvorak | 914 | 33547 | 819979 | 289475 | 18672 | 19711 | 594500 | 3505369 | 118109 | 304988 | 15694 |\n| Klausler | 982 | 36300 | 874620 | 317922 | 20706 | 20629 | 715147 | 4303432 | 143207 | 315850 | 15636 |\n| Dvorak | 1199 | 36285 | 955938 | 320119 | 21098 | 22179 | 762193 | 4517125 | 149645 | 280687 | 14173 |\n| QWERTY | 570 | 28887 | 536961 | 245630 | 15586 | 14462 | 334346 | 2005118 | 76432 | 290115 | 13849 |\n\nSame finger different key taps\n\n| Layout | Alice | Memento | Tweets_100K | Tweets_20K | Tweets_MASC | Spoken_MASC | COCA_blogs | iweb | Monkey | Coder | Rosetta |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Engram v2 | 216 | 9807 | 320406 | 120286 | 7728 | 3514 | 137290 | 1064640 | 37534 | 125798 | 5822 |\n| Engram v2.5 | 270 | 11742 | 339358 | 118954 | 9080 | 3538 | 145178 | 1055230 | 36990 | 121912 | 5766 |\n| Engram v3 | 252 | 12272 | 343824 | 117568 | 8270 | 3744 | 156244 | 1168198 | 39530 | 123242 | 5414 |\n| Halmak | 666 | 14962 | 633920 | 205600 | 14044 | 7826 | 362786 | 2487382 | 83702 | 141290 | 6200 |\n| Hieamtsrn | 244 | 12096 | 311000 | 119490 | 8316 | 3192 | 155674 | 1100116 | 40882 | 158698 | 7324 |\n| Colemak Mod-DH | 362 | 10960 | 352578 | 151736 | 9298 | 4644 | 153984 | 1233770 | 47438 | 117842 | 5328 |\n| Norman | 938 | 20012 | 721602 | 213890 | 16014 | 9022 | 595168 | 3885282 | 135844 | 179752 | 7402 |\n| Workman | 550 | 13086 | 451280 | 136692 | 10698 | 6156 | 287622 | 1975564 | 71150 | 132526 | 5550 |\n| MTGap 2.0 | 226 | 14550 | 397690 | 139130 | 10386 | 6252 | 176724 | 1532844 | 58144 | 138484 | 7272 |\n| QGMLWB | 812 | 17820 | 637788 | 189700 | 14364 | 7838 | 456442 | 3027530 | 100750 | 149366 | 8062 |\n| Colemak | 362 | 10960 | 352578 | 151736 | 9298 | 4644 | 153984 | 1233770 | 47438 | 117842 | 5328 |\n| Asset | 520 | 13572 | 519018 | 155246 | 11802 | 5664 | 332860 | 2269342 | 77406 | 140886 | 6020 |\n| Capewell-Dvorak | 556 | 14226 | 501178 | 163878 | 12214 | 6816 | 335056 | 2391416 | 78152 | 151194 | 9008 |\n| Klausler | 408 | 14734 | 455658 | 174998 | 11410 | 5212 | 257878 | 1794604 | 59566 | 135782 | 7444 |\n| Dvorak | 516 | 13970 | 492604 | 171488 | 12208 | 5912 | 263018 | 1993346 | 64994 | 142084 | 6484 |\n| QWERTY | 880 | 19580 | 736894 | 204712 | 16632 | 9264 | 581944 | 3765246 | 130184 | 173598 | 8052 |\n\nHand balances\n\n| Layout | Alice | Memento | Tweets_100K | Tweets_20K | Tweets_MASC | Spoken_MASC | COCA_blogs | iweb | Monkey | Coder | Rosetta |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Engram v2 | 3.54 | 0.31 | 4.18 | 7.17 | 5.35 | 6.65 | 2.42 | 2.57 | 4.86 | 5.90 | 4.28 |\n| Engram v2.5 | 3.79 | 0.02 | 4.02 | 5.71 | 4.10 | 6.72 | 1.67 | 1.32 | 3.90 | 4.58 | 2.85 |\n| Engram v3 | 3.79 | 0.02 | 4.02 | 5.71 | 4.10 | 6.72 | 1.67 | 1.32 | 3.90 | 4.58 | 2.85 |\n| Halmak | 2.34 | -1.67 | 2.03 | -3.02 | -1.40 | 7.58 | -0.85 | -0.56 | 0.16 | 4.71 | 5.96 |\n| Hieamtsrn | 0.06 | -3.07 | 2.02 | 3.42 | 4.13 | 1.07 | 1.08 | 2.98 | 3.62 | 10.43 | 7.79 |\n| Colemak Mod-DH | 10.15 | 5.66 | 11.04 | 6.74 | 9.18 | 18.14 | 7.09 | 6.39 | 7.70 | 9.81 | 11.69 |\n| Norman | -2.34 | -1.19 | 2.46 | -0.17 | 3.89 | 5.91 | -2.29 | -2.05 | -0.92 | 8.21 | 9.30 |\n| Workman | 1.48 | 0.55 | 3.62 | 1.68 | 5.09 | 7.93 | 1.02 | 1.58 | 1.79 | 10.23 | 11.22 |\n| MTGap 2.0 | -4.35 | -2.73 | 1.33 | 0.51 | 3.49 | 4.11 | 0.20 | 1.67 | 2.05 | 8.65 | 3.63 |\n| QGMLWB | 7.11 | 3.55 | 7.43 | 5.84 | 6.10 | 15.00 | 5.14 | 4.49 | 5.48 | 6.41 | 9.53 |\n| Colemak | 10.15 | 5.66 | 11.04 | 6.74 | 9.18 | 18.14 | 7.09 | 6.39 | 7.70 | 9.81 | 11.69 |\n| Asset | -0.51 | 0.36 | 4.56 | 1.22 | 5.58 | -1.07 | -1.03 | -0.78 | 0.05 | 8.59 | 10.55 |\n| Capewell-Dvorak | 8.25 | -0.09 | 4.46 | 5.10 | 4.86 | 9.23 | 2.72 | 2.62 | 5.00 | 7.55 | 5.18 |\n| Klausler | 2.97 | -3.06 | 1.53 | 4.18 | 4.21 | 6.88 | 2.17 | 2.47 | 4.35 | 7.11 | 4.96 |\n| Dvorak | 10.59 | 1.48 | 7.00 | 8.78 | 8.49 | 12.00 | 8.03 | 8.46 | 10.76 | 9.24 | 7.77 |\n| QWERTY | -9.58 | -5.51 | -3.25 | -6.14 | -3.32 | 0.25 | -11.23 | -11.75 | -10.92 | 1.50 | 4.59 |\n\n### Construct heatmap tables\n\n\n```python\nlayout_names_engrams = [x for i,x in enumerate(layout_names2) if i < 3]\nfor imatrix, score_matrix in enumerate(score_matrices):\n    matrix_label = matrix_labels[imatrix]\n\n    #if imatrix == 0:\n    score_matrix = score_matrix[0:3,:]\n    \n    # Normalize by column:\n    columns_max = score_matrix.max(axis=0)\n    score_matrix = score_matrix / columns_max\n\n    heatmap(data=score_matrix, title=matrix_label, xlabel=\"\", ylabel=\"\", \n                       x_axis_labels=text_abbrs, y_axis_labels=layout_names_engrams, \n                       print_output=print_output)\n```\n\n\n```python\nlayout_names2_copy = layout_names2.copy()\nlayout_names2_copy.remove('QWERTY')\nfor imatrix, score_matrix in enumerate(score_matrices):\n    matrix_label = matrix_labels[imatrix]\n\n    #if imatrix == 0:\n    score_matrix = np.delete(score_matrix, (-1), axis=0)\n    #    layout_names2_copy.remove('QWERTY')\n    #elif imatrix == 1:\n    #    layout_names2_copy.append('QWERTY')\n        \n    # Normalize by column:\n    columns_max = score_matrix.max(axis=0)\n    score_matrix = score_matrix / columns_max\n\n    heatmap(data=score_matrix, title=matrix_label, xlabel=\"\", ylabel=\"\", \n                       x_axis_labels=text_abbrs, y_axis_labels=layout_names2_copy, \n                       print_output=print_output)\n```\n\n### Workspace for manual comparisons\n\n\n```python\nlayout1 = ['B','Y','O','U','C','I','E','A','G','X','J','K', 'L','D','W','V','H','T','S','N','R','M','F','P', \"'\",',','-', '\"','.','?', 'Z','Q']\nlayout2 = ['J','Y','G','K','C','I','E','A','W','P','U','O', 'V','L','D','X','H','T','S','N','R','M','F','B', \"'\",',','-', '\"','.','?', 'Z','Q']\nlayout3 = ['J','K','Y','X','C','I','E','A','G','P','U','O', 'V','L','D','B','H','T','S','N','R','M','F','W', \"'\",',','-', '\"','.','?', 'Z','Q']\nlayout4 = ['W','Y','O','U','C','I','E','A','G','P','J','K', 'V','L','D','X','H','T','S','N','R','M','F','B', \"'\",',','-', '\"','.','?', 'Z','Q']\n\ndata_matrix = Factors32x32\ns1 = score_layout(data_matrix, layout1, bigrams, bigram_frequencies, verbose=False)\ns2 = score_layout(data_matrix, layout2, bigrams, bigram_frequencies, verbose=False)\ns3 = score_layout(data_matrix, layout3, bigrams, bigram_frequencies, verbose=False)\ns4 = score_layout(data_matrix, layout4, bigrams, bigram_frequencies, verbose=False)\nprint('Layout 1: {0}'.format(s1))\nprint('Layout 2: {0}'.format(s2))\nprint('Layout 3: {0}'.format(s3))\nprint('Layout 4: {0}'.format(s4))\n```\n\n    Layout 1: 0.7329151915874081\n    Layout 2: 0.733112192971112\n    Layout 3: 0.7331696596245132\n    Layout 4: 0.7329437638133653\n\n", "meta": {"hexsha": "955c669d7503d9e4c18a066a2bae9c580622c191", "size": 1014950, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "compare_layouts.ipynb", "max_stars_repo_name": "sunaku/engram", "max_stars_repo_head_hexsha": "f0a532112e5f03b2e906532c5b72c4fc9bc26eba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "compare_layouts.ipynb", "max_issues_repo_name": "sunaku/engram", "max_issues_repo_head_hexsha": "f0a532112e5f03b2e906532c5b72c4fc9bc26eba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "compare_layouts.ipynb", "max_forks_repo_name": "sunaku/engram", "max_forks_repo_head_hexsha": "f0a532112e5f03b2e906532c5b72c4fc9bc26eba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 104.0974358974, "max_line_length": 40860, "alphanum_fraction": 0.8072131632, "converted": true, "num_tokens": 90059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834914771175, "lm_q2_score": 0.05500529158532569, "lm_q1q2_score": 0.02600009327626866}}
{"text": "```python\n!pip install pennylane StrawberryFields tensorflow-hub tensorflow_text emoji pythainlp pennylane-sf  plotnine\n```\n\n    Requirement already satisfied: pennylane in /usr/local/lib/python3.6/dist-packages (0.9.0)\n    Requirement already satisfied: StrawberryFields in /usr/local/lib/python3.6/dist-packages (0.14.0)\n    Requirement already satisfied: tensorflow-hub in /usr/local/lib/python3.6/dist-packages (0.8.0)\n    Requirement already satisfied: tensorflow_text in /usr/local/lib/python3.6/dist-packages (2.2.1)\n    Requirement already satisfied: emoji in /usr/local/lib/python3.6/dist-packages (0.5.4)\n    Requirement already satisfied: pythainlp in /usr/local/lib/python3.6/dist-packages (2.1.4)\n    Requirement already satisfied: pennylane-sf in /usr/local/lib/python3.6/dist-packages (0.9.0)\n    Collecting plotnine\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/aa/ee/9f343ef0719541e02950384978722ea84cc433264cece09a11a0cccb2bf9/plotnine-0.7.0-py3-none-any.whl (4.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4.4MB 977kB/s eta 0:00:01\n    \u001b[?25hRequirement already satisfied: autograd in /usr/local/lib/python3.6/dist-packages (from pennylane) (1.3)\n    Requirement already satisfied: networkx in /usr/local/lib/python3.6/dist-packages (from pennylane) (2.4)\n    Requirement already satisfied: toml in /usr/local/lib/python3.6/dist-packages (from pennylane) (0.10.1)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from pennylane) (1.3.1)\n    Requirement already satisfied: semantic-version==2.6 in /usr/local/lib/python3.6/dist-packages (from pennylane) (2.6.0)\n    Requirement already satisfied: appdirs in /usr/local/lib/python3.6/dist-packages (from pennylane) (1.4.4)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from pennylane) (1.17.4)\n    Requirement already satisfied: quantum-blackbird>=0.2.3 in /usr/local/lib/python3.6/dist-packages (from StrawberryFields) (0.2.4)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.6/dist-packages (from StrawberryFields) (2.8.1)\n    Requirement already satisfied: requests>=2.22.0 in /usr/local/lib/python3.6/dist-packages (from StrawberryFields) (2.22.0)\n    Requirement already satisfied: thewalrus>=0.12 in /usr/local/lib/python3.6/dist-packages (from StrawberryFields) (0.12.0)\n    Requirement already satisfied: urllib3>=1.25.3 in /usr/local/lib/python3.6/dist-packages (from StrawberryFields) (1.25.7)\n    Requirement already satisfied: numba in /usr/local/lib/python3.6/dist-packages (from StrawberryFields) (0.49.1)\n    Requirement already satisfied: sympy>=1.5 in /usr/local/lib/python3.6/dist-packages (from StrawberryFields) (1.6)\n    Requirement already satisfied: six>=1.12.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-hub) (1.13.0)\n    Requirement already satisfied: protobuf>=3.8.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-hub) (3.10.0)\n    Requirement already satisfied: tensorflow<2.3,>=2.2.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow_text) (2.2.0)\n    Requirement already satisfied: nltk>=3.3 in /usr/local/lib/python3.6/dist-packages (from pythainlp) (3.4.5)\n    Requirement already satisfied: dill>=0.3.0 in /usr/local/lib/python3.6/dist-packages (from pythainlp) (0.3.1.1)\n    Requirement already satisfied: tqdm>=4.1 in /usr/local/lib/python3.6/dist-packages (from pythainlp) (4.38.0)\n    Requirement already satisfied: tinydb>=3.0 in /usr/local/lib/python3.6/dist-packages (from pythainlp) (3.15.2)\n    Collecting mizani>=0.7.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/57/29/72ed07818b1cd7f79340d55c7230748238e09c35fc8461c545a5d350006d/mizani-0.7.1-py3-none-any.whl (62kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 71kB 11.1MB/s eta 0:00:01\n    \u001b[?25hCollecting statsmodels>=0.11.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/cb/83/540fd83238a18abe6c2d280fa8e489ac5fcefa1f370f0ca1acd16ae1b860/statsmodels-0.11.1-cp36-cp36m-manylinux1_x86_64.whl (8.7MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 8.7MB 11.3MB/s eta 0:00:01\n    \u001b[?25hRequirement already satisfied: matplotlib>=3.1.1 in /usr/local/lib/python3.6/dist-packages (from plotnine) (3.2.1)\n    Collecting patsy>=0.5.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/ea/0c/5f61f1a3d4385d6bf83b83ea495068857ff8dfb89e74824c6e9eb63286d8/patsy-0.5.1-py2.py3-none-any.whl (231kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 235kB 29.0MB/s eta 0:00:01\n    \u001b[?25hCollecting descartes>=1.1.0\n      Downloading https://files.pythonhosted.org/packages/e5/b6/1ed2eb03989ae574584664985367ba70cd9cf8b32ee8cad0e8aaeac819f3/descartes-1.1.0-py3-none-any.whl\n    Requirement already satisfied: pandas>=1.0.3 in /usr/local/lib/python3.6/dist-packages (from plotnine) (1.0.3)\n    Requirement already satisfied: future>=0.15.2 in /usr/local/lib/python3.6/dist-packages (from autograd->pennylane) (0.17.1)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx->pennylane) (4.4.1)\n    Requirement already satisfied: antlr4-python3-runtime==4.7.2 in /usr/local/lib/python3.6/dist-packages (from quantum-blackbird>=0.2.3->StrawberryFields) (4.7.2)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.22.0->StrawberryFields) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests>=2.22.0->StrawberryFields) (2019.9.11)\n    Requirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.22.0->StrawberryFields) (2.8)\n    Requirement already satisfied: dask[delayed] in /usr/local/lib/python3.6/dist-packages (from thewalrus>=0.12->StrawberryFields) (2.18.1)\n    Requirement already satisfied: llvmlite<=0.33.0.dev0,>=0.31.0.dev0 in /usr/local/lib/python3.6/dist-packages (from numba->StrawberryFields) (0.32.1)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from numba->StrawberryFields) (41.6.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy>=1.5->StrawberryFields) (1.1.0)\n    Requirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (0.8.1)\n    Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (1.25.0)\n    Requirement already satisfied: tensorflow-estimator<2.3.0,>=2.2.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (2.2.0)\n    Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (1.1.0)\n    Requirement already satisfied: keras-preprocessing>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (1.1.2)\n    Requirement already satisfied: google-pasta>=0.1.8 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (0.1.8)\n    Requirement already satisfied: astunparse==1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (1.6.3)\n    Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (1.11.2)\n    Requirement already satisfied: h5py<2.11.0,>=2.10.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (2.10.0)\n    Requirement already satisfied: gast==0.3.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (0.3.3)\n    Requirement already satisfied: tensorboard<2.3.0,>=2.2.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (2.2.2)\n    Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (3.1.0)\n    Requirement already satisfied: wheel>=0.26; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (0.33.6)\n    Collecting palettable\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/ca/46/5198aa24e61bb7eef28d06cb69e56bfa1942f4b6807d95a0b5ce361fe09b/palettable-3.3.0-py2.py3-none-any.whl (111kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 112kB 23.6MB/s eta 0:00:01\n    \u001b[?25hRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=3.1.1->plotnine) (1.2.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=3.1.1->plotnine) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=3.1.1->plotnine) (0.10.0)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=1.0.3->plotnine) (2019.3)\n    Requirement already satisfied: pyyaml in /usr/local/lib/python3.6/dist-packages (from dask[delayed]->thewalrus>=0.12->StrawberryFields) (5.1.2)\n    Requirement already satisfied: toolz>=0.8.2; extra == \"delayed\" in /usr/local/lib/python3.6/dist-packages (from dask[delayed]->thewalrus>=0.12->StrawberryFields) (0.10.0)\n    Requirement already satisfied: cloudpickle>=0.2.2; extra == \"delayed\" in /opt/tensorflow/horovod-source/.eggs/cloudpickle-1.2.2-py3.6.egg (from dask[delayed]->thewalrus>=0.12->StrawberryFields) (1.2.2)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (0.4.1)\n    Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (1.7.0)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (1.6.0.post3)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (3.1.1)\n    Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (0.16.0)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (1.3.0)\n    Requirement already satisfied: cachetools<3.2,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (3.1.1)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (0.2.7)\n    Requirement already satisfied: rsa<4.1,>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (4.0)\n    Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (3.1.0)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.6/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (0.4.7)\n    Installing collected packages: palettable, mizani, patsy, statsmodels, descartes, plotnine\n    Successfully installed descartes-1.1.0 mizani-0.7.1 palettable-3.3.0 patsy-0.5.1 plotnine-0.7.0 statsmodels-0.11.1\n    \u001b[33mWARNING: You are using pip version 19.3.1; however, version 20.1.1 is available.\n    You should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\n\n\n\n```python\n!wget https://github.com/PyThaiNLP/truevoice-intent/archive/master.zip; unzip master.zip; cd truevoice-intent-master; unzip mari-intent.zip; cp *.* ../;\n```\n\n    --2020-06-11 03:12:29--  https://github.com/PyThaiNLP/truevoice-intent/archive/master.zip\n    Resolving github.com (github.com)... 52.74.223.119\n    Connecting to github.com (github.com)|52.74.223.119|:443... connected.\n    HTTP request sent, awaiting response... 302 Found\n    Location: https://codeload.github.com/PyThaiNLP/truevoice-intent/zip/master [following]\n    --2020-06-11 03:12:30--  https://codeload.github.com/PyThaiNLP/truevoice-intent/zip/master\n    Resolving codeload.github.com (codeload.github.com)... 13.229.189.0\n    Connecting to codeload.github.com (codeload.github.com)|13.229.189.0|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: unspecified [application/zip]\n    Saving to: \u2018master.zip\u2019\n    \n    master.zip              [    <=>             ]   1.29M  2.07MB/s    in 0.6s    \n    \n    2020-06-11 03:12:31 (2.07 MB/s) - \u2018master.zip\u2019 saved [1350596]\n    \n    Archive:  master.zip\n    7ce601a547a4bac938b3bb0640a6036f7b89266c\n       creating: truevoice-intent-master/\n      inflating: truevoice-intent-master/.gitignore  \n      inflating: truevoice-intent-master/LICENSE  \n      inflating: truevoice-intent-master/README.md  \n      inflating: truevoice-intent-master/class_features.py  \n      inflating: truevoice-intent-master/classification.ipynb  \n      inflating: truevoice-intent-master/exploration.ipynb  \n     extracting: truevoice-intent-master/mari-intent.zip  \n      inflating: truevoice-intent-master/remove-dup-split.ipynb  \n      inflating: truevoice-intent-master/thsarabunnew-webfont.ttf  \n    Archive:  mari-intent.zip\n      inflating: mari-train-balanced.csv  \n      inflating: mari-test-balanced.csv  \n\n\n\n```python\n!mkdir ft_data\n!mkdir truevoice_data\n```\n\n\n```python\n!wget https://github.com/rdisipio/qnlp/raw/master/models.py\n```\n\n    --2020-06-11 03:12:33--  https://github.com/rdisipio/qnlp/raw/master/models.py\n    Resolving github.com (github.com)... 52.74.223.119\n    Connecting to github.com (github.com)|52.74.223.119|:443... connected.\n    HTTP request sent, awaiting response... 302 Found\n    Location: https://raw.githubusercontent.com/rdisipio/qnlp/master/models.py [following]\n    --2020-06-11 03:12:34--  https://raw.githubusercontent.com/rdisipio/qnlp/master/models.py\n    Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 151.101.8.133\n    Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|151.101.8.133|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 1212 (1.2K) [text/plain]\n    Saving to: \u2018models.py\u2019\n    \n    models.py           100%[===================>]   1.18K  --.-KB/s    in 0s      \n    \n    2020-06-11 03:12:34 (71.3 MB/s) - \u2018models.py\u2019 saved [1212/1212]\n    \n\n\n\n```python\n!wget https://github.com/rdisipio/qnlp/raw/master/models_quantum.py\n```\n\n    --2020-06-11 03:12:35--  https://github.com/rdisipio/qnlp/raw/master/models_quantum.py\n    Resolving github.com (github.com)... 52.74.223.119\n    Connecting to github.com (github.com)|52.74.223.119|:443... connected.\n    HTTP request sent, awaiting response... 302 Found\n    Location: https://raw.githubusercontent.com/rdisipio/qnlp/master/models_quantum.py [following]\n    --2020-06-11 03:12:35--  https://raw.githubusercontent.com/rdisipio/qnlp/master/models_quantum.py\n    Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 151.101.8.133\n    Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|151.101.8.133|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 8498 (8.3K) [text/plain]\n    Saving to: \u2018models_quantum.py\u2019\n    \n    models_quantum.py   100%[===================>]   8.30K  --.-KB/s    in 0s      \n    \n    2020-06-11 03:12:36 (41.7 MB/s) - \u2018models_quantum.py\u2019 saved [8498/8498]\n    \n\n\n\n```python\nimport pandas as pd\nimport numpy as np\nfrom pythainlp import word_tokenize\nfrom tqdm import tqdm_notebook\nfrom collections import Counter\nimport re\nfrom sklearn.metrics import f1_score,precision_score,recall_score\n\n#viz\nfrom plotnine import *\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndef replace_newline(t):\n    return re.sub('[\\n]{1,}', ' ', t)\n\nft_data = 'ft_data/'\n\ny = 'destination'\nnb_class = 7\n```\n\n\n```python\nimport string\nimport emoji\ndef replace_url(text):\n    URL_PATTERN = r\"\"\"(?i)\\b((?:https?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\\-]+[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)/)(?:[^\\s()<>{}\\[\\]]+|\\([^\\s()]*?\\([^\\s()]+\\)[^\\s()]*?\\)|\\([^\\s]+?\\))+(?:\\([^\\s()]*?\\([^\\s()]+\\)[^\\s()]*?\\)|\\([^\\s]+?\\)|[^\\s`!()\\[\\]{};:'\".,<>?\u00ab\u00bb\u201c\u201d\u2018\u2019])|(?:(?<!@)[a-z0-9]+(?:[.\\-][a-z0-9]+)*[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)\\b/?(?!@)))\"\"\"\n    return re.sub(URL_PATTERN, 'xxurl', text)\n\ndef replace_rep(text):\n    def _replace_rep(m):\n        c,cc = m.groups()\n        return f'{c}xxrep'\n    re_rep = re.compile(r'(\\S)(\\1{2,})')\n    return re_rep.sub(_replace_rep, text)\n\ndef ungroup_emoji(toks):\n    res = []\n    for tok in toks:\n        if emoji.emoji_count(tok) == len(tok):\n            for char in tok:\n                res.append(char)\n        else:\n            res.append(tok)\n    return res\n\ndef process_text(text):\n    #pre rules\n    res = text.lower().strip()\n    res = replace_url(res)\n    res = replace_rep(res)\n    \n    #tokenize\n    res = [word for word in res.split('|') if word and not re.search(pattern=r\"\\s+\", string=word)]\n    \n    #post rules\n    res = ungroup_emoji(res)\n    \n    return res\n```\n\n#Train-validation-test Split\n\nWe perform 85/15 train-validation split in addition to the test split by TrueVoice.\n\n\n```python\nfrom sklearn.model_selection import train_test_split\nall_df = pd.read_csv(f'mari-train-balanced.csv')\nall_df['destination'] = all_df.destination.map(lambda x: x.replace(' ','_'))\n#train_df, valid_df = train_test_split(all_df, test_size=0.15, random_state=1412)\ntrain_df = all_df.reset_index(drop=True)\n#valid_df = valid_df.reset_index(drop=True)\ntest_df = pd.read_csv(f'mari-test-balanced.csv')\ntest_df['destination'] = test_df.destination.map(lambda x: x.replace(' ','_'))\nprint(train_df.shape, test_df.shape)\n```\n\n    (10303, 5) (2607, 5)\n\n\n\n```python\n#test set prevalence\ntest_df['destination'].value_counts() / test_df.shape[0]\n```\n\n\n\n\n    billing_and_payment      0.376678\n    promotions               0.220560\n    other_queries            0.176064\n    internet                 0.154200\n    international_dialing    0.034522\n    true_money               0.019946\n    lost_and_stolen          0.018028\n    Name: destination, dtype: float64\n\n\n\n\n```python\n#!pip install pennylane pennylane-sf \n\nimport pennylane\npennylane.device(\"strawberryfields.gaussian\", wires=2) # \u0e16\u0e49\u0e32 error \u0e43\u0e2b\u0e49 restart runtime\n```\n\n\n\n\n    <StrawberryFieldsGaussian device (wires=2, shots=1000) at 0x7fbf7b375eb8>\n\n\n\n\n```python\nimport tensorflow_hub as hub\nimport tensorflow_text\nimport tensorflow as tf #tensorflow 2.1.0\nfrom tensorflow.keras.callbacks import EarlyStopping\n\nfrom models_quantum import make_model_quantum\nenc = hub.load('https://tfhub.dev/google/universal-sentence-encoder-multilingual/3')\n```\n\n\n```python\ntf.keras.backend.set_floatx('float64') \n```\n\n\n```python\ntrain_df.shape, test_df.shape\n```\n\n\n\n\n    ((10303, 5), (2607, 5))\n\n\n\n\n```python\n\ndef embed_text(X_txt):\n    print(\"Embedding input text...\")\n\n    X = np.array([np.array(x) for x in enc(X_txt)])\n\n    return X\n\n```\n\n\n```python\nX_train = embed_text(train_df.texts)\n```\n\n    Embedding input text...\n\n\n\n```python\nX_test = embed_text(test_df.texts)\n```\n\n    Embedding input text...\n\n\n\n```python\nembedding_dim =X_train.shape[-1]\n```\n\n\n```python\nembedding_dim\n```\n\n\n\n\n    512\n\n\n\n\n```python\nindex = {j:i for i,j in enumerate(list(set(train_df[y].values)))}\n```\n\n\n```python\nindex\n```\n\n\n\n\n    {'other_queries': 0,\n     'billing_and_payment': 1,\n     'lost_and_stolen': 2,\n     'promotions': 3,\n     'international_dialing': 4,\n     'internet': 5,\n     'true_money': 6}\n\n\n\n\n```python\nfrom tensorflow.keras.utils import to_categorical\n```\n\n\n```python\ny_train = [index[i] for i in train_df[y].values]\n```\n\n\n```python\ny_train = to_categorical(y_train)\n```\n\n\n```python\ny_test  = [index[i] for i in test_df[y].values]\n```\n\n\n```python\ny_test = to_categorical(y_test)\n```\n\n\n```python\nN_EPOCHS = 20\nBATCH_SIZE = 32\nn_categories = 7\n```\n\n\n```python\nembedding_dim = X_train.shape[-1]\n```\n\n\n```python\nimport pennylane as qml\nqml.about()\n```\n\n    Name: PennyLane\n    Version: 0.9.0\n    Summary: PennyLane is a Python quantum machine learning library by Xanadu Inc.\n    Home-page: https://github.com/XanaduAI/pennylane\n    Author: None\n    Author-email: None\n    License: Apache License 2.0\n    Location: /usr/local/lib/python3.6/dist-packages\n    Requires: appdirs, toml, autograd, networkx, numpy, scipy, semantic-version\n    Required-by: PennyLane-SF\n    Platform info:           Linux-4.15.0-72-generic-x86_64-with-Ubuntu-18.04-bionic\n    Python version:          3.6.8\n    Numpy version:           1.17.4\n    Scipy version:           1.3.1\n    Installed devices:\n    - default.gaussian (PennyLane-0.9.0)\n    - default.qubit (PennyLane-0.9.0)\n    - default.tensor (PennyLane-0.9.0)\n    - default.tensor.tf (PennyLane-0.9.0)\n    - strawberryfields.fock (PennyLane-SF-0.9.0)\n    - strawberryfields.gaussian (PennyLane-SF-0.9.0)\n\n\n\n```python\nmodel = make_model_quantum(n_categories=n_categories,  n_qubits=4, n_layers=3, embedding_dim=embedding_dim)\n```\n\n\n```python\nmodel.summary()\n```\n\n    Model: \"QuantumPreprintClassifier\"\n    _________________________________________________________________\n    Layer (type)                 Output Shape              Param #   \n    =================================================================\n    text_in (InputLayer)         [(None, 512)]             0         \n    _________________________________________________________________\n    dense_4 (Dense)              (None, 4)                 2052      \n    _________________________________________________________________\n    variational_quantum_circuit_ (None, 4)                 36        \n    _________________________________________________________________\n    dense_7 (Dense)              (None, 7)                 35        \n    =================================================================\n    Total params: 2,123\n    Trainable params: 2,123\n    Non-trainable params: 0\n    _________________________________________________________________\n\n\n\n```python\noptimizer = tf.keras.optimizers.Adam(learning_rate=0.01)\n```\n\n\n```python\nmodel.compile(optimizer, loss='categorical_crossentropy')\n```\n\n\n```python\nearly_stopping_callback = EarlyStopping(monitor='val_loss', patience=3, min_delta=0.01,restore_best_weights=True)\n```\n\n\n```python\nfrom matplotlib import pyplot as plt\nfrom IPython.display import clear_output\nimport numpy as np\n```\n\n\n```python\nclass PlotLosses(tf.keras.callbacks.Callback): # code from https://gist.github.com/stared/dfb4dfaf6d9a8501cd1cc8b8cb806d2e\n    def on_train_begin(self, logs={}):\n        self.i = 0\n        self.x = []\n        self.losses = []\n        self.val_losses = []\n        \n        self.fig = plt.figure()\n        \n        self.logs = []\n\n    def on_epoch_end(self, epoch, logs={}):\n        \n        self.logs.append(logs)\n        self.x.append(self.i)\n        self.losses.append(logs.get('loss'))\n        self.val_losses.append(logs.get('val_loss'))\n        self.i += 1\n        \n        clear_output(wait=True)\n        plt.plot(self.x, self.losses, label=\"loss\")\n        plt.plot(self.x, self.val_losses, label=\"val_loss\")\n        plt.legend()\n        plt.show();\n        \nplot_losses = PlotLosses()\n```\n\n\n```python\ncallbacks = [early_stopping_callback,plot_losses]\n```\n\n\n```python\nhistory = model.fit(X_train, y_train,epochs=N_EPOCHS, batch_size=BATCH_SIZE,validation_split=0.15,callbacks =callbacks)\n```\n\n\n```python\nmodel.predict(X_test)\n```\n\n\n\n\n    array([[3.70255528e-02, 7.62594837e-01, 2.23173318e-03, ...,\n            1.52303516e-04, 5.57465622e-02, 1.40657142e-03],\n           [2.17854399e-02, 2.33223092e-02, 4.43345599e-04, ...,\n            1.40323680e-03, 6.00061262e-03, 1.94607543e-04],\n           [7.96126955e-03, 9.75440668e-01, 1.21422228e-03, ...,\n            3.99320930e-05, 5.49612634e-03, 1.89945120e-03],\n           ...,\n           [6.83175325e-01, 2.75767411e-02, 5.98708792e-02, ...,\n            4.70041373e-02, 1.12416090e-01, 3.57558300e-03],\n           [4.51997391e-02, 5.54229024e-02, 9.59489261e-04, ...,\n            8.83238246e-04, 1.52961508e-02, 2.39712495e-04],\n           [1.32345636e-02, 3.55008743e-02, 1.21654943e-03, ...,\n            2.69381894e-04, 9.15894139e-01, 1.22652911e-03]])\n\n\n\n\n```python\ntest_score = model.evaluate(X_test, y_test, verbose=2)\n```\n\n    82/82 - 125s - loss: 0.6645\n\n\n\n```python\nprint(test_score)\n```\n\n    0.6645362609229327\n\n\n\n```python\nt=model.predict(X_test)\n```\n\n\n```python\nval2tag = {i:j for i,j in zip(index.values(),index.keys())}\n```\n\n\n```python\ny_true = list(test_df[y].values)\n```\n\n\n```python\ny_pred = [val2tag[list(i).index(i.max())] for i in t]\n```\n\n\n```python\nfrom sklearn.metrics import classification_report\nprint(classification_report(y_true, y_pred))\n```\n\n                           precision    recall  f1-score   support\n    \n      billing_and_payment       0.84      0.83      0.84       982\n    international_dialing       0.76      0.73      0.75        90\n                 internet       0.74      0.74      0.74       402\n          lost_and_stolen       0.00      0.00      0.00        47\n            other_queries       0.69      0.74      0.71       459\n               promotions       0.78      0.85      0.81       575\n               true_money       0.90      0.37      0.52        52\n    \n                 accuracy                           0.78      2607\n                macro avg       0.67      0.61      0.62      2607\n             weighted avg       0.77      0.78      0.77      2607\n    \n\n\n    /usr/local/lib/python3.6/dist-packages/sklearn/metrics/_classification.py:1272: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n\n", "meta": {"hexsha": "785a28c4182e7a4aed727732d5ecaf2e91cc9873", "size": 59956, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "quantum-nlp/text-classification/what_the_quantum-n3.ipynb", "max_stars_repo_name": "wannaphong/open-thai-nlp-document", "max_stars_repo_head_hexsha": "bc231f7d3ec1e3d297b18cab7e9cd8d0bb4f4865", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-06-15T03:48:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T17:38:23.000Z", "max_issues_repo_path": "quantum-nlp/text-classification/what_the_quantum-n3.ipynb", "max_issues_repo_name": "wannaphongcom/open-thai-nlp-document", "max_issues_repo_head_hexsha": "bc231f7d3ec1e3d297b18cab7e9cd8d0bb4f4865", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quantum-nlp/text-classification/what_the_quantum-n3.ipynb", "max_forks_repo_name": "wannaphongcom/open-thai-nlp-document", "max_forks_repo_head_hexsha": "bc231f7d3ec1e3d297b18cab7e9cd8d0bb4f4865", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-06-15T03:48:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-25T06:19:19.000Z", "avg_line_length": 49.1845775226, "max_line_length": 15764, "alphanum_fraction": 0.6776469411, "converted": true, "num_tokens": 9520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36296919173767833, "lm_q2_score": 0.07159119399724771, "lm_q1q2_score": 0.025985397820716332}}
{"text": "```python\nimport sys\nprint('hello world', flush=True)\nfor i in range(3):\n    print(i, flush=True)\nprint('output to stderr', file=sys.stderr, flush=True)\nprint('some more stdout text', flush=True)\n```\n\n    hello world\n    0\n    1\n    2\n\n\n    output to stderr\n\n\n    some more stdout text\n\n\n# Markdown Cell\n\n$ e^{ \\pm i\\theta } = \\cos \\theta \\pm i\\sin \\theta + \\beta $\n\n*It* **really** is!\n\n\n```python\nthis is a syntax error\n```\n\n\n```python\nfrom IPython.display import Image\nImage('./jupyter.png')\n```\n\n\n```python\nfrom IPython.display import Latex\nLatex('''The mass-energy equivalence is described by the famous equation\n \n$$E=mc^2$$\n \ndiscovered in 1905 by Albert Einstein. \nIn natural units ($c$ = 1), the formula expresses the identity\n \n\\\\begin{equation}\nE=m\n\\\\end{equation}''')\n```\n\n\n\n\nThe mass-energy equivalence is described by the famous equation\n \n$$E=mc^2$$\n \ndiscovered in 1905 by Albert Einstein. \nIn natural units ($c$ = 1), the formula expresses the identity\n \n\\begin{equation}\nE=m\n\\end{equation}\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "ab99982ecc7df6bc86c5f29dc46c3d7a8ee2545f", "size": 14166, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/notebook/test.ipynb", "max_stars_repo_name": "0x0L/jupyterlab", "max_stars_repo_head_hexsha": "20b43ebdf6336d260aa225252ee4e47132950379", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2016-08-29T23:03:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T13:42:43.000Z", "max_issues_repo_path": "examples/notebook/test.ipynb", "max_issues_repo_name": "0x0L/jupyterlab", "max_issues_repo_head_hexsha": "20b43ebdf6336d260aa225252ee4e47132950379", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2016-07-01T15:35:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-31T18:28:38.000Z", "max_forks_repo_path": "examples/notebook/test.ipynb", "max_forks_repo_name": "0x0L/jupyterlab", "max_forks_repo_head_hexsha": "20b43ebdf6336d260aa225252ee4e47132950379", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2016-07-15T19:35:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-15T07:07:46.000Z", "avg_line_length": 80.9485714286, "max_line_length": 10516, "alphanum_fraction": 0.8226034166, "converted": true, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2538610069692489, "lm_q2_score": 0.10230471815640062, "lm_q1q2_score": 0.02597117876888906}}
{"text": "```python\n# This cell is mandatory in all Dymos documentation notebooks.\nmissing_packages = []\ntry:\n    import openmdao.api as om\nexcept ImportError:\n    if 'google.colab' in str(get_ipython()):\n        !python -m pip install openmdao[notebooks]\n    else:\n        missing_packages.append('openmdao')\ntry:\n    import dymos as dm\nexcept ImportError:\n    if 'google.colab' in str(get_ipython()):\n        !python -m pip install dymos\n    else:\n        missing_packages.append('dymos')\ntry:\n    import pyoptsparse\nexcept ImportError:\n    if 'google.colab' in str(get_ipython()):\n        !pip install -q condacolab\n        import condacolab\n        condacolab.install_miniconda()\n        !conda install -c conda-forge pyoptsparse\n    else:\n        missing_packages.append('pyoptsparse')\nif missing_packages:\n    raise EnvironmentError('This notebook requires the following packages '\n                           'please install them and restart this notebook\\'s runtime: {\",\".join(missing_packages)}')\n```\n\n# Water Rocket\n\nAuthor: Bernardo Bahia Monteiro (bbahia@umich.edu)\n\nIn this example, we will optimize a water rocket for range and height at the apogee, using design variables that are easily modifiable just before launch: the empty mass, the initial water volume and the launch angle.\nThis example builds on [multi-phase cannonball](../multi_phase_cannonball/multi_phase_cannonball.md) ane is adapted from _Optimization of a Water Rocket in OpenMDAO/Dymos_ {cite}`bbahia_2020`.\n\n## Nomenclature\n\n| Symbol               | definition                             |\n|----------------------|----------------------------------------|\n| $v_\\text{out}$       | water exit speed at the nozzle         |\n| $A_\\text{out}$       | nozzle area                            |\n| $V_w$                | water volume in the rocket             |\n| $p$                  | pressure in the rocket                 |\n| $p_a$                | ambient pressure                       |\n| $\\dot{\\,}$           | time derivative                        |\n| $k$                  | polytropic constant                    |\n| $V_b$                | internal volume of the rocket          |\n| $\\rho_w$             | water density                          |\n| $T$                  | thrust                                 |\n| $q$                  | dynamic pressure                       |\n| $S$                  | cross sectional area                   |\n| $(\\cdot)_0$          | value of $(\\cdot)$ at $t=0$            |\n| $t$                  | time                                   |\n\n## Problem Formulation\n\nA natural objective function for a water rocket is the maximum height achieved by the rocket during flight, or the horizontal distance it travels, i.e. its range.\nThe design of a water rocket is somewhat constrained by the soda bottle used as its engine.\nThis means that the volume available for water and air is fixed, the initial launch pressure is limited by the bottle's strength (since the pressure is directly related to the energy available for the rocket, it is easy to see that it should be as high as possible) and the nozzle throat area is also fixed.\nGiven these manufacturing constraints, the design variables we are left with are the empty mass (it can be easily changed through adding ballast), the water volume at the launch, and the launch angle.\nWith this considerations in mind, a natural formulation for the water rocket problem is\n\n\\begin{align}\n    \\text{maximize}   &\\quad \\text{range or height} \\\\\n    \\text{w.r.t.}     &\\quad \\text{empty mass, initial water volume, launch angle, trajectory} \\\\\n    \\text{subject to} &\\quad \\text{flight dynamics} \\\\\n                      &\\quad \\text{fluid dynamics inside the rocket} \\\\\n                      &\\quad 0 < \\text{initial water volume} < \\text{volume of bottle} \\\\\n                      &\\quad 0^\\circ < \\text{launch angle} < 90^\\circ \\\\\n                      &\\quad 0 < \\text{empty mass}\n\\end{align}\n\n##  Model\n\nThe water rocket model is divided into three basic components: a *water engine*, responsible for modelling the fluid dynamics inside the rocket and returning its thrust;  the *aerodynamics*, responsible for calculating the atmospheric drag of the rocket; and the *equations of motion*, responsible for propagating the rocket's trajectory in time, using Newton's laws and the forces provided by the other two components.\n\nIn order to integrate these three basic components, some additional interfacing components are necessary: an atmospheric model to provide values of ambient pressure for the water engine and air density to the calculation of the dynamic pressure for the aerodynamic model, and a component that calculates the instantaneous mass of the rocket by summing the water mass with the rocket's empty mass.\nThe high level layout of this model is shown in below.\n\n<figure>\n  \n  <figcaption>N2 diagram for the water rocket model</figcaption>\n</figure>\n\n`atmos`, `dynamic_pressure`, `aero` and `eom` are the same models used in [multi-phase cannonball](../multi_phase_cannonball/multi_phase_cannonball.md).\nThe remaining components are discussed below.\n\n```{Warning}\nThe `eom` component has a singularity in the flight path angle derivative when the flight speed is zero.\nThis happens because the rotational dynamics are not modelled.\nThis can cause convergence problems if the launch velocity is set to zero or the launch angle is set to $90^\\circ$\n```\n\n```{Note}\nSince the range of altitudes achieved by the water rocket is very small (100m), the air density and pressure are practically constant, thus the use of an atmospheric model is not necessary. However, using it makes it easier to reuse code from [multi-phase cannonball (../multi_phase_cannonball/multi_phase_cannonball.md).\n```\n\n### Water engine\n\nThe water engine is modelled by assuming that the air expansion in the rocket\nfollows an adiabatic process and the water flow is incompressible and inviscid,\ni.e.  it follows Bernoulli's equation. We also make the following simplifying\nassumptions:\n\n1. The thrust developed after the water is depleted is negligible\n2. The area inside the bottle is much smaller than the nozzle area\n3. The inertial forces do not affect the fluid dynamics inside the bottle\n\nThis simplified modelling can be found in Prusa[@Prusa2000].\nA more rigorous formulation, which drops all these simplifying assumptions can be found in Wheeler[@Wheeler2002], Gommes[@Gommes2010], and Barria-Perotti[@BarrioPerotti2010].\n\nThe first assumption leads to an underestimation of the rocket performance, since the air left in the bottle after it is out of water is known to generate appreciable thrust[@Thorncroft2009].\nThis simplified model, however, produces physically meaningful results.\n\nThere are two states in this dynamical model, the water volume in the rocket $V_w$ and the gauge pressure inside the rocket $p$.\nThe constitutive equations and the N2 diagram showing the model organization are shown below.\n\n### Constitutive equations of the water engine model\n| Component              | Equation                                                    |\n| -----------------------|-------------------------------------------------------------|\n| water_exhaust_speed    | $v_\\text{out} = \\sqrt{2(p-p_a)/\\rho_w}$                     |\n| water_flow_rate        | $\\dot{V}_w = -v_\\text{out} A_\\text{out}$                    |\n| pressure_rate          | $\\dot{p} = kp\\frac{\\dot{V_w}}{(V_b-V_w)}$                   |\n| water_thrust           | $T = (\\rho_w v_\\text{out})(v_\\text{out}A_\\text{out})$       |\n\n<figure>\n  \n  <figcaption>N2 diagram for the water engine group</figcaption>\n</figure>\n\n### Water engine\n\nThe water engine is modelled by assuming that the air expansion in the rocket\nfollows an adiabatic process and the water flow is incompressible and inviscid,\ni.e.  it follows Bernoulli's equation. We also make the following simplifying\nassumptions:\n\n1. The thrust developed after the water is depleted is negligible\n2. The area inside the bottle is much smaller than the nozzle area\n3. The inertial forces do not affect the fluid dynamics inside the bottle\n\nThis simplified modelling can be found in Prusa {cite}`Prusa2000`.\nA more rigorous formulation, which drops all these simplifying assumptions can be found in Wheeler {cite}`Wheeler2002`, Gommes {cite}`Gommes2010`, and Barria-Perotti {cite}`BarrioPerotti2010`.\n\nThe first assumption leads to an underestimation of the rocket performance, since the air left in the bottle after it is out of water is known to generate appreciable thrust {cite}`Thorncroft2009`.\nThis simplified model, however, produces physically meaningful results.\n\nThere are two states in this dynamical model, the water volume in the rocket $V_w$ and the gauge pressure inside the rocket $p$.\nThe constitutive equations and the N2 diagram showing the model organization are shown below.\n\n### Constitutive equations of the water engine model\n| Component              | Equation                                                    |\n| -----------------------|-------------------------------------------------------------|\n| water_exhaust_speed    | $v_\\text{out} = \\sqrt{2(p-p_a)/\\rho_w}$                     |\n| water_flow_rate        | $\\dot{V}_w = -v_\\text{out} A_\\text{out}$                    |\n| pressure_rate          | $\\dot{p} = kp\\frac{\\dot{V_w}}{(V_b-V_w)}$                   |\n| water_thrust           | $T = (\\rho_w v_\\text{out})(v_\\text{out}A_\\text{out})$       |\n\n<figure>\n  \n  <figcaption>N2 diagram for the water engine group</figcaption>\n</figure>\n\n\n```python\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nimport openmdao.api as om\nimport dymos as dm\n```\n\n\n```python\nfrom openmdao.utils.notebook_utils import display_source\n```\n\n\n```python\ndisplay_source('dymos.examples.water_rocket.water_engine_comp.WaterEngine')\n```\n\n\n```python\ndisplay_source('dymos.examples.water_rocket.water_engine_comp._WaterExhaustSpeed')\n```\n\n\n```python\ndisplay_source('dymos.examples.water_rocket.water_engine_comp._PressureRate')\n```\n\n\n```python\ndisplay_source('dymos.examples.water_rocket.water_engine_comp._WaterFlowRate')\n```\n\nThe `_MassAdder` component calculates the rocket's instantaneous mass by\nsumming the water mass with the rockets empty mass, i.e.\n\n\\begin{align}\n    m = m_\\text{empty}+\\rho_w V_w\n\\end{align}\n\n\n```python\ndisplay_source('dymos.examples.water_rocket.water_propulsion_ode._MassAdder')\n```\n\nNow these components are joined in a single group\n\n\n```python\ndisplay_source('dymos.examples.water_rocket.water_propulsion_ode.WaterPropulsionODE')\n```\n\n## Phases\n\nThe flight of the water rocket is split in three distinct phases: propelled ascent, ballistic ascent and ballistic descent.\nIf the simplification of no thrust without water were lifted, there would be an extra \"air propelled ascent\" phase between the propelled ascent and ballistic ascent phases.\n\n**Propelled ascent:** is the flight phase where the rocket still has water inside, and hence it is producing thrust.\nThe thrust is given by the water engine model, and fed into the flight dynamic equations.\nIt starts at launch and finishes when the water is depleted, i.e. $V_w=0$.\n\n**Ballistic ascent:** is the flight phase where the rocket is ascending ($\\gamma>0$) but produces no thrust.\nThis phase begins at the end of thepropelled ascent phase and ends at the apogee, defined by $\\gamma=0$.\n\n**Descent:** is the phase where the rocket is descending without thrust.\nIt begins at the end of the ballistic ascent phase and ends with ground impact, i.e. $h=0$.\n\n\n```python\ndisplay_source('dymos.examples.water_rocket.phases.new_propelled_ascent_phase')\n```\n\n\n```python\ndisplay_source('dymos.examples.water_rocket.phases.new_ballistic_ascent_phase')\n```\n\n\n```python\ndisplay_source('dymos.examples.water_rocket.phases.new_descent_phase')\n```\n\n##  Model parameters\n\nThe model requires a few constant parameters.\nThe values used are shown in the following table.\n\nValues for parameters in the water rocket model\n\n|   Parameter        | Value                | Unit         | Reference                                           |\n|--------------------|----------------------|--------------|-----------------------------------------------------|\n| $C_D$              | 0.3450               | -            | {cite}`BarrioPerotti2009`                           |\n| $S$                | $\\pi 106^2/4$        | $mm^2$       | {cite}`BarrioPerotti2009`                           |\n| $k$                | 1.2                  | -            | {cite}`Thorncroft2009` {cite}`Fischer2020` {cite}`Romanelli2013`   |\n| $A_\\text{out}$     | $\\pi22^2/4$          | $mm^2$       | {cite}`aircommand_nozzle`                                |\n| $V_b$              | 2                    | L            |                                                     |\n| $\\rho_w$           | 1000                 | $kg/m^3$     |                                                     |\n| $p_0$              | 6.5                  | bar          |                                                     |\n| $v_0$              | 0.1                  | $m/s$        |                                                     |\n| $h_0$              | 0                    | $m$          |                                                     |\n| $r_0$              | 0                    | $m$          |                                                     |\n\nValues for the bottle volume $V_b$, its cross-sectional area $S$ and the nozzle area $A_\\text{out}$ are determined by the soda bottle that makes the rocket primary structure, and thus are not easily modifiable by the designer.\nThe polytropic coefficient $k$ is a function of the moist air characteristics inside the rocket.\nThe initial speed $v_0$ must be set to a value higher than zero, otherwise the flight dynamic equations become singular.\nThis issue arises from the angular dynamics of the rocket not being modelled.\nThe drag coefficient $C_D$ is sensitive to the aerodynamic design, but can be optimized by a single discipline analysis.\nThe initial pressure $p_0$ should be maximized in order to obtain the maximum range or height for the rocket.\nIt is limited by the structural properties of the bottle, which are modifiable by the designer, since the bottle needs to be available commercially.\nFinally, the starting point of the rocket is set to the origin.\n\n## Putting it all together\n\nThe different phases must be combined in a single trajectory, and linked in a sequence.\nHere we also define the design variables.\n\n\n```python\ndisplay_source('dymos.examples.water_rocket.phases.new_water_rocket_trajectory')\n```\n\n## Helper Functions to Access the Results\n\n\n```python\nfrom collections import namedtuple\n\n\ndef summarize_results(water_rocket_problem):\n    p = water_rocket_problem\n    Entry = namedtuple('Entry', 'value unit')\n    summary = {\n        'Launch angle': Entry(p.get_val('traj.propelled_ascent.timeseries.states:gam',  units='deg')[0, 0], 'deg'),\n        'Flight angle at end of propulsion': Entry(p.get_val('traj.propelled_ascent.timeseries.states:gam',\n                                                   units='deg')[-1, 0], 'deg'),\n        'Empty mass': Entry(p.get_val('traj.parameters:m_empty', units='kg')[0], 'kg'),\n        'Water volume': Entry(p.get_val('traj.propelled_ascent.timeseries.states:V_w', 'L')[0, 0], 'L'),\n        'Maximum range': Entry(p.get_val('traj.descent.timeseries.states:r', units='m')[-1, 0], 'm'),\n        'Maximum height': Entry(p.get_val('traj.ballistic_ascent.timeseries.states:h', units='m')[-1, 0], 'm'),\n        'Maximum velocity': Entry(p.get_val('traj.propelled_ascent.timeseries.states:v', units='m/s')[-1, 0], 'm/s'),\n    }\n\n    return summary\n\n```\n\n\n```python\ncolors={'pa': 'tab:blue', 'ba': 'tab:orange', 'd': 'tab:green'}\n\n\ndef plot_propelled_ascent(p, exp_out):\n    fig, ax = plt.subplots(2, 2, sharex=True, figsize=(12, 6))\n    t_imp = p.get_val('traj.propelled_ascent.time', 's')\n    t_exp = exp_out.get_val('traj.propelled_ascent.time', 's')\n    \n    c = colors['pa']\n\n    ax[0,0].plot(t_imp, p.get_val('traj.propelled_ascent.timeseries.states:p', 'bar'), '.', color=c)\n    ax[0,0].plot(t_exp, exp_out.get_val('traj.propelled_ascent.timeseries.states:p', 'bar'), '-', color=c)\n    ax[0,0].set_ylabel('p (bar)')\n    ax[0,0].set_ylim(bottom=0)\n\n    ax[1,0].plot(t_imp, p.get_val('traj.propelled_ascent.timeseries.states:V_w', 'L'), '.', color=c)\n    ax[1,0].plot(t_exp, exp_out.get_val('traj.propelled_ascent.timeseries.states:V_w', 'L'), '-', color=c)\n    ax[1,0].set_ylabel('$V_w$ (L)')\n\n    ax[0,1].plot(t_imp, p.get_val('traj.propelled_ascent.timeseries.T', 'N'), '.', color=c)\n    ax[0,1].plot(t_exp, exp_out.get_val('traj.propelled_ascent.timeseries.T', 'N'), '-', color=c)\n    ax[0,1].set_ylabel('T (N)')\n    ax[0,1].set_ylim(bottom=0)\n\n    ax[1,1].plot(t_imp, p.get_val('traj.propelled_ascent.timeseries.states:v', 'm/s'), '.', color=c)\n    ax[1,1].plot(t_exp, exp_out.get_val('traj.propelled_ascent.timeseries.states:v', 'm/s'), '-', color=c)\n    ax[1,1].set_ylabel('v (m/s)')\n    ax[1,1].set_ylim(bottom=0)\n\n    ax[1,0].set_xlabel('t (s)')\n    ax[1,1].set_xlabel('t (s)')\n    \n    for i in range(4):\n        ax.ravel()[i].grid(True, alpha=0.2)\n\n    fig.tight_layout()\n```\n\n\n```python\ndef plot_states(p, exp_out, legend_loc='right', legend_ncol=3):\n    fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(12, 4), sharex=True)\n\n    states = ['r', 'h', 'v', 'gam']\n    units = ['m', 'm', 'm/s', 'deg']\n    phases = ['propelled_ascent', 'ballistic_ascent', 'descent']\n\n    time_imp = {'ballistic_ascent': p.get_val('traj.ballistic_ascent.timeseries.time'),\n                'propelled_ascent': p.get_val('traj.propelled_ascent.timeseries.time'),\n                'descent': p.get_val('traj.descent.timeseries.time')}\n\n    time_exp = {'ballistic_ascent': exp_out.get_val('traj.ballistic_ascent.timeseries.time'),\n                'propelled_ascent': exp_out.get_val('traj.propelled_ascent.timeseries.time'),\n                'descent': exp_out.get_val('traj.descent.timeseries.time')}\n\n    x_imp = {phase: {state: p.get_val(f\"traj.{phase}.timeseries.states:{state}\", unit)\n                     for state, unit in zip(states, units)\n                     }\n             for phase in phases\n             }\n\n    x_exp = {phase: {state: exp_out.get_val(f\"traj.{phase}.timeseries.states:{state}\", unit)\n                     for state, unit in zip(states, units)\n                     }\n             for phase in phases\n             }\n\n    for i, (state, unit) in enumerate(zip(states, units)):\n        axes.ravel()[i].set_ylabel(f\"{state} ({unit})\" if state != 'gam' else f'$\\gamma$ ({unit})')\n\n        axes.ravel()[i].plot(time_imp['propelled_ascent'], x_imp['propelled_ascent'][state], '.', color=colors['pa'])\n        axes.ravel()[i].plot(time_imp['ballistic_ascent'], x_imp['ballistic_ascent'][state], '.', color=colors['ba'])\n        axes.ravel()[i].plot(time_imp['descent'], x_imp['descent'][state], '.', color=colors['d'])\n        h1, = axes.ravel()[i].plot(time_exp['propelled_ascent'], x_exp['propelled_ascent'][state], '-', color=colors['pa'], label='Propelled Ascent')\n        h2, = axes.ravel()[i].plot(time_exp['ballistic_ascent'], x_exp['ballistic_ascent'][state], '-', color=colors['ba'], label='Ballistic Ascent')\n        h3, = axes.ravel()[i].plot(time_exp['descent'], x_exp['descent'][state], '-', color=colors['d'], label='Descent')\n\n        if state == 'gam':\n            axes.ravel()[i].yaxis.set_major_locator(mpl.ticker.MaxNLocator(nbins='auto', steps=[1, 1.5, 3, 4.5, 6, 9, 10]))\n            axes.ravel()[i].set_yticks(np.arange(-90, 91, 45))\n        \n        axes.ravel()[i].grid(True, alpha=0.2)\n\n    axes[1, 0].set_xlabel('t (s)')\n    axes[1, 1].set_xlabel('t (s)')\n    \n    plt.figlegend(handles=[h1, h2, h3], loc=legend_loc, ncol=legend_ncol)\n\n    fig.tight_layout()\n```\n\n\n```python\ndef plot_trajectory(p, exp_out, legend_loc='center right'):\n    fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(8, 6))\n\n    time_imp = {'ballistic_ascent': p.get_val('traj.ballistic_ascent.timeseries.time'),\n                'propelled_ascent': p.get_val('traj.propelled_ascent.timeseries.time'),\n                'descent': p.get_val('traj.descent.timeseries.time')}\n\n    time_exp = {'ballistic_ascent': exp_out.get_val('traj.ballistic_ascent.timeseries.time'),\n                'propelled_ascent': exp_out.get_val('traj.propelled_ascent.timeseries.time'),\n                'descent': exp_out.get_val('traj.descent.timeseries.time')}\n\n    r_imp = {'ballistic_ascent': p.get_val('traj.ballistic_ascent.timeseries.states:r'),\n             'propelled_ascent': p.get_val('traj.propelled_ascent.timeseries.states:r'),\n             'descent': p.get_val('traj.descent.timeseries.states:r')}\n\n    r_exp = {'ballistic_ascent': exp_out.get_val('traj.ballistic_ascent.timeseries.states:r'),\n             'propelled_ascent': exp_out.get_val('traj.propelled_ascent.timeseries.states:r'),\n             'descent': exp_out.get_val('traj.descent.timeseries.states:r')}\n\n    h_imp = {'ballistic_ascent': p.get_val('traj.ballistic_ascent.timeseries.states:h'),\n             'propelled_ascent': p.get_val('traj.propelled_ascent.timeseries.states:h'),\n             'descent': p.get_val('traj.descent.timeseries.states:h')}\n\n    h_exp = {'ballistic_ascent': exp_out.get_val('traj.ballistic_ascent.timeseries.states:h'),\n             'propelled_ascent': exp_out.get_val('traj.propelled_ascent.timeseries.states:h'),\n             'descent': exp_out.get_val('traj.descent.timeseries.states:h')}\n\n    axes.plot(r_imp['propelled_ascent'], h_imp['propelled_ascent'], 'o', color=colors['pa'])\n    axes.plot(r_imp['ballistic_ascent'], h_imp['ballistic_ascent'], 'o', color=colors['ba'])\n    axes.plot(r_imp['descent'], h_imp['descent'], 'o', color=colors['d'])\n\n    h1, = axes.plot(r_exp['propelled_ascent'], h_exp['propelled_ascent'], '-', color=colors['pa'], label='Propelled Ascent')\n    h2, = axes.plot(r_exp['ballistic_ascent'], h_exp['ballistic_ascent'], '-', color=colors['ba'], label='Ballistic Ascent')\n    h3, = axes.plot(r_exp['descent'], h_exp['descent'], '-', color=colors['d'], label='Descent')\n\n    axes.set_xlabel('r (m)')\n    axes.set_ylabel('h (m)')\n    axes.set_aspect('equal', 'box')\n    plt.figlegend(handles=[h1, h2, h3], loc=legend_loc)\n    axes.grid(alpha=0.2)\n\n    fig.tight_layout()\n```\n\n## Optimizing for Height\n\n\n```python\nfrom dymos.examples.water_rocket.phases import new_water_rocket_trajectory, set_sane_initial_guesses\n\np = om.Problem(model=om.Group())\n\ntraj, phases = new_water_rocket_trajectory(objective='height')\ntraj = p.model.add_subsystem('traj', traj)\n\np.driver = om.pyOptSparseDriver(optimizer='IPOPT', print_results=False)\np.driver.opt_settings['print_level'] = 4\np.driver.opt_settings['max_iter'] = 1000\np.driver.opt_settings['mu_strategy'] = 'monotone'\np.driver.declare_coloring(tol=1.0E-12)\n\n# Finish Problem Setup\np.model.linear_solver = om.DirectSolver()\n\np.setup()\nset_sane_initial_guesses(p, phases)\n\ndm.run_problem(p, run_driver=True, simulate=True)\n\nsummary = summarize_results(p)\nfor key, entry in summary.items():\n    print(f'{key}: {entry.value:6.4f} {entry.unit}')\n    \nsol_out = om.CaseReader('dymos_solution.db').get_case('final')\nsim_out = om.CaseReader('dymos_simulation.db').get_case('final')\n```\n\n### Maximum Height Solution: Propulsive Phase\n\n\n```python\nplot_propelled_ascent(sol_out, sim_out)\n```\n\n## Maximum Height Solution: Height vs. Range\n\nNote that the equations of motion used here are singular in vertical flight, so the launch angle (the initial flight path angle) was limited to 85 degrees.\n\n\n```python\nplot_trajectory(sol_out, sim_out, legend_loc='center right')\n```\n\n## Maximum Height Solution: State History\n\n\n```python\nplot_states(sol_out, sim_out, legend_loc='lower center', legend_ncol=3)\n```\n\n\n```python\nfrom openmdao.utils.assert_utils import assert_near_equal\n\nassert_near_equal(summary['Launch angle'].value, 85, 0.01)\nassert_near_equal(summary['Empty mass'].value, 0.144, 0.01)\nassert_near_equal(summary['Water volume'].value, 0.98, 0.01)\nassert_near_equal(summary['Maximum height'].value, 53.5, 0.01)\n```\n\n# Optimizing for Range\n\n\n```python\nfrom dymos.examples.water_rocket.phases import new_water_rocket_trajectory, set_sane_initial_guesses\n\np = om.Problem(model=om.Group())\n\ntraj, phases = new_water_rocket_trajectory(objective='range')\ntraj = p.model.add_subsystem('traj', traj)\n\np.driver = om.pyOptSparseDriver(optimizer='IPOPT')\np.driver.opt_settings['print_level'] = 4\np.driver.opt_settings['max_iter'] = 1000\np.driver.opt_settings['mu_strategy'] = 'monotone'\np.driver.declare_coloring(tol=1.0E-12)\n\n# Finish Problem Setup\np.model.linear_solver = om.DirectSolver()\n\np.setup()\nset_sane_initial_guesses(p, phases)\n\ndm.run_problem(p, run_driver=True, simulate=True)\n\nsummary = summarize_results(p)\nfor key, entry in summary.items():\n    print(f'{key}: {entry.value:6.4f} {entry.unit}')\n\nsol_out = om.CaseReader('dymos_solution.db').get_case('final')\nsim_out = om.CaseReader('dymos_simulation.db').get_case('final')\n```\n\n## Maximum Range Solution: Propulsive Phase\n\n\n```python\nplot_propelled_ascent(sol_out, sim_out)\n```\n\n## Maximum Range Solution: Height vs. Range\n\n\n```python\nplot_trajectory(sol_out, sim_out, legend_loc='center')\n```\n\n## Maximum Range Solution: State History\n\n\n```python\nplot_states(sol_out, sim_out, legend_loc='lower center')\n```\n\n\n```python\nfrom openmdao.utils.assert_utils import assert_near_equal\n\n# Check results (tolerance is relative unless value is zero)\nassert_near_equal(summary['Launch angle'].value, 46, 0.02)\nassert_near_equal(summary['Flight angle at end of propulsion'].value, 38, 0.02)\nassert_near_equal(summary['Empty mass'].value, 0.189, 1e-2)\nassert_near_equal(summary['Water volume'].value, 1.026, 1e-2)\nassert_near_equal(summary['Maximum range'].value, 85.11, 1e-2)\nassert_near_equal(summary['Maximum height'].value, 23.08, 1e-2)\nassert_near_equal(summary['Maximum velocity'].value, 41.31, 1e-2)\n```\n\n## References\n\n```{bibliography}\n:filter: docname in docnames\n```\n", "meta": {"hexsha": "0f6c603a3c9c2eba530e6272d61824f4ece420ae", "size": 35818, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/dymos_book/examples/water_rocket/water_rocket.ipynb", "max_stars_repo_name": "yonghoonlee/dymos", "max_stars_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/dymos_book/examples/water_rocket/water_rocket.ipynb", "max_issues_repo_name": "yonghoonlee/dymos", "max_issues_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-05-24T15:14:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-28T21:12:55.000Z", "max_forks_repo_path": "docs/dymos_book/examples/water_rocket/water_rocket.ipynb", "max_forks_repo_name": "yonghoonlee/dymos", "max_forks_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5180995475, "max_line_length": 428, "alphanum_fraction": 0.5605003071, "converted": true, "num_tokens": 6526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.0705596020506861, "lm_q1q2_score": 0.025866425910757544}}
{"text": "## Initial setup\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n\n```python\nimport tensorflow as tf\nprint(tf.__version__)\n# tensorflow version used is 2.7.0\nimport torch\nprint(torch.__version__)\n# torch version used is 1.10+cu111\n```\n\n    2.8.0\n    1.10.0+cu111\n\n\n\n```python\n!nvidia-smi\n```\n\n    Sat Feb 19 13:59:56 2022       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 460.32.03    Driver Version: 460.32.03    CUDA Version: 11.2     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  Tesla P100-PCIE...  Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   36C    P0    26W / 250W |      0MiB / 16280MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    |  No running processes found                                                 |\n    +-----------------------------------------------------------------------------+\n\n\n\n```python\n# Other imports\n! pip install tensorflow_addons\n! pip install tensorflow_io\n\nimport os\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import *\nfrom tensorflow import keras as tfkeras\nimport matplotlib.pyplot as plt\nfrom imutils import paths\nfrom tqdm import tqdm\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nimport tensorflow_datasets as tfds\nimport tensorflow_io as tfio\nimport tensorflow_hub as hub\nimport numpy as np\nimport cv2\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics.pairwise import cosine_similarity as cos\nfrom sympy.utilities.iterables import multiset_permutations\nfrom sklearn.metrics import accuracy_score, f1_score, confusion_matrix\nfrom IPython.display import Image, display\n\nimport zipfile\nimport concurrent.futures\n\n# Random seed fix\nrandom_seed = 42\ntf.random.set_seed(random_seed)\nnp.random.seed(random_seed)\n```\n\n    Requirement already satisfied: tensorflow_addons in /usr/local/lib/python3.7/dist-packages (0.16.1)\n    Requirement already satisfied: typeguard>=2.7 in /usr/local/lib/python3.7/dist-packages (from tensorflow_addons) (2.7.1)\n    Requirement already satisfied: tensorflow_io in /usr/local/lib/python3.7/dist-packages (0.24.0)\n    Requirement already satisfied: tensorflow-io-gcs-filesystem==0.24.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow_io) (0.24.0)\n\n\n## Dataset gathering and preparation\n\n\n```python\nImagenet_images_train = list(paths.list_images(\"/content/drive/MyDrive/TEM image datasets/2022-1000-ImageNet\"))\ntrain_images_directory_select = np.random.choice(Imagenet_images_train, 832, replace=False)\nprint(len(Imagenet_images_train))\nprint(len(train_images_directory_select))\n```\n\n    1000\n    832\n\n\n\n```python\nCEM_images_train = list(paths.list_images(\"/content/drive/MyDrive/TEM image datasets/2021-CEM500K/jpg\"))\ntrain_images_directory_select = np.random.choice(CEM_images_train, 832, replace=False)\nprint(len(CEM_images_train))\nprint(len(train_images_directory_select))\n```\n\n    10000\n    832\n\n\n\n```python\n%cd /content/drive/MyDrive/nanowire-morphology-classification-project/\n```\n\n\n```python\ntraining_batch_size = 64\n\nimageSize=224\n```\n\n\n```python\n# Augmentation utilities (differs from the original implementation)\n# Adapted from: https://arxiv.org/pdf/2002.05709.pdf (Appendxi A) \n# corresponding GitHub: https://github.com/google-research/simclr/)\n\nclass CustomAugment(object):\n    def __call__(self, sample):        \n\n        # Random flips\n        sample = self._random_apply(tf.image.flip_left_right, sample, p=0.5)\n\n        # Random crop always\n        sample = self._random_apply(self._random_crop, sample, p=1.0)\n        \n        # Randomly apply transformation (color distortions) with probability p.\n        sample = self._random_apply(self._color_jitter, sample, p=0.8)\n\n        return sample\n\n    def _random_crop(self, x):\n        \n        # distance from left to right, from bottom to top\n        l = tf.random.uniform([], minval=int(imageSize * 0.25), maxval=int(imageSize * 0.5), dtype=tf.int32)             # 25 as min bound, so that the cropped images are not too small\n        # l = int(0.5 * imageSize)                                                                              # use this line if the crop box size is constant\n\n        # lower left corner\n        y1 = tf.random.uniform([], minval=0, maxval= imageSize - 1 - l, dtype=tf.int32)\n        x1 = tf.random.uniform([], minval=0, maxval= imageSize - 1 - l, dtype=tf.int32)\n        \n        x = tf.image.crop_to_bounding_box(x, y1, x1, l, l)\n        x = tf.image.resize(x, size=[imageSize, imageSize])\n        return x\n\n    def _color_jitter(self, x, s=1):\n        # one can also shuffle the order of following augmentations\n        # each time they are applied.\n        # x = tf.image.random_brightness(x, max_delta=0.2*s)                 \n        x = tf.image.random_contrast(x, lower=1-0.8*s, upper=1+0.8*s)\n        x = tf.image.random_saturation(x, lower=1-0.8*s, upper=1+0.8*s)\n        x = tf.image.random_hue(x, max_delta=0.2*s)\n        x = tf.clip_by_value(x, 0, 1)\n        return x\n    \n    def _random_apply(self, func, x, p):\n        return tf.cond(\n          tf.less(tf.random.uniform([], minval=0, maxval=1, dtype=tf.float32),\n                  tf.cast(p, tf.float32)),\n          lambda: func(x),\n          lambda: x)\n```\n\n\n```python\n# Build the augmentation pipeline\ndata_augmentation = Sequential([Lambda(CustomAugment())])\n```\n\n\n```python\n# Image preprocessing utils\n@tf.function\ndef parse_images(image_path):\n    image_string = tf.io.read_file(image_path)\n    image = tf.image.decode_jpeg(image_string, channels=3)\n    image = tf.image.convert_image_dtype(image, tf.float32)\n    image = tf.image.resize(image, size=[imageSize, imageSize])\n\n    return image\n```\n\n\n```python\n# Create TensorFlow dataset for training\ntrain_ds = tf.data.Dataset.from_tensor_slices(train_images_directory_select)\ntrain_ds = (\n    train_ds\n    .map(parse_images, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n    .batch(training_batch_size\n           , drop_remainder=True\n           )\n    .prefetch(tf.data.experimental.AUTOTUNE)\n)\n```\n\n## Initiate our self-supervised model\n\n\n```python\nResnet50_transfer = tf.keras.applications.ResNet50(\n    include_top=False,\n    weights=\"imagenet\",\n    input_tensor=None,\n    input_shape=(imageSize, imageSize, 3), \n    pooling=None,\n)\n\nResnet50_transfer.trainable = True\n```\n\n\n```python\n# Architecture for resnet as base architecture\ndef get_resnet_self_supervise_model(hidden_1, hidden_2, hidden_3):\n    base_model = Resnet50_transfer\n    base_model.trainable = True\n    inputs = Input((imageSize, imageSize, 3))\n    h = base_model(inputs, training=True)\n    h = GlobalAveragePooling2D()(h)\n\n    projection_1 = Dense(hidden_1)(h)                                        \n    projection_1 = Activation(\"relu\")(projection_1)\n    projection_1 = BatchNormalization(epsilon=0.001)(projection_1)\n    projection_2 = Dense(hidden_2)(projection_1)\n    projection_2 = Activation(\"relu\")(projection_2)\n    projection_2 = BatchNormalization(epsilon=0.001)(projection_2)\n    projection_3 = Dense(hidden_3)(projection_2)\n    projection_3 = BatchNormalization(epsilon=0.001)(projection_3)\n\n    resnet_model = Model(inputs, projection_3)\n    \n    return resnet_model\n```\n\n## Training self-supervised model\n\n\n```python\n#### use this train_step block for Simclr implementation\n\ntf.config.run_functions_eagerly(True)\n\n@tf.function\ndef train_step(xis, xjs, model, optimizer, criterion, temperature):\n    with tf.GradientTape() as tape:\n        projections_1_original = model(xis)\n        projections_2_original = model(xjs)\n\n        # simclr derivatives uses layer norm\n        # normalize projection feature vectors            along the feature dimension, this is a l2_norm\n        projections_1 = tf.math.l2_normalize(projections_1_original, axis=1)\n        projections_2 = tf.math.l2_normalize(projections_2_original, axis=1)\n        similarities = (tf.matmul(projections_1, projections_2, transpose_b=True) / temperature)\n\n        # the temperature-scaled similarities are used as logits for cross-entropy\n        contrastive_labels = tf.range(training_batch_size)\n        loss = criterion(\n            tf.concat([contrastive_labels, contrastive_labels], axis=0),\n            tf.concat([similarities, tf.transpose(similarities)], axis=0))\n\n    gradients = tape.gradient(loss, model.trainable_variables)\n    optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n\n    return loss\n```\n\n\n```python\n#### use this train_step block for Barlow-Twins implementation\n\ntf.config.run_functions_eagerly(True)\n\n@tf.function\ndef train_step(xis, xjs, model, optimizer, criterion, temperature):\n    with tf.GradientTape() as tape:\n        projections_1_original = model(xis)\n        projections_2_original = model(xjs)\n\n        # batchnorm for barlow twins\n        # use these two lines when doing mini-batch gradient descent\n        projections_1 = (projections_1_original - tf.reduce_mean(projections_1_original, axis=0)) / tf.math.reduce_std(projections_1_original, axis=0)\n        projections_2 = (projections_2_original - tf.reduce_mean(projections_2_original, axis=0)) / tf.math.reduce_std(projections_2_original, axis=0)\n\n        # use these two lines when doing stochastic gradient descent (i.e. batch size = 1)\n        # projections_1 = projections_1_original\n        # projections_2 = projections_2_original\n\n        # the cross correlation of image representations should be the identity matrix\n\n        feature_dim = tf.cast(tf.shape(projections_1)[1], tf.float32)\n        cross_correlation = (tf.matmul(projections_1, projections_2, transpose_a=True) / training_batch_size)\n        target_cross_correlation = tf.eye(feature_dim)\n        squared_errors = (target_cross_correlation - cross_correlation) ** 2\n\n        # invariance loss = average diagonal error\n        # redundancy reduction loss = average off-diagonal error\n        invariance_loss = (tf.reduce_sum(squared_errors * tf.eye(feature_dim)) / feature_dim)\n        redundancy_reduction_loss = tf.reduce_sum(squared_errors * (1 - tf.eye(feature_dim))) / (feature_dim * (feature_dim - 1))\n\n        # use redundancy_redunction_weight of 0.005 from the paper, not a sensitive parameter\n        loss = invariance_loss + 0.005 * redundancy_reduction_loss\n\n    gradients = tape.gradient(loss, model.trainable_variables)\n    optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n\n    return loss\n```\n\n\n```python\ndef train_model(model, dataset, optimizer, criterion,\n                 temperature, epochs=100):\n    step_wise_loss = []\n    epoch_wise_loss = []\n\n    epoch = 1\n    for k in tqdm(range(epochs)):\n      i = 0\n      for image_batch in dataset:\n          a = data_augmentation(image_batch)\n          b = data_augmentation(image_batch)\n\n          loss = train_step(a, b, model, optimizer, criterion, temperature)\n          step_wise_loss.append(loss)\n          i += 1\n          print(\"batch: {} loss: {:.5f}\".format(i, np.mean(step_wise_loss)))\n\n      epoch_wise_loss.append(np.mean(step_wise_loss))\n      if epoch % 20 == 0:\n        model.save_weights('barlow_ImageNet_batch%i_project128_64_1024_seed%i.h5' % (training_batch_size, random_seed))\n        print(\"epoch: {} loss: {:.5f}\".format(epoch, np.mean(step_wise_loss)))\n      epoch += 1\n          \n\n    return epoch_wise_loss, model\n```\n\n\n```python\ncriterion = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) \n\n# the learning rate decay schedule in the original implementation of SimCLR and Barlow-Twins\ndecay_steps = 1000\nlr_decayed_fn = tf.keras.experimental.CosineDecay(\n    initial_learning_rate=0.2, decay_steps=decay_steps)\noptimizer = tf.keras.optimizers.SGD(lr_decayed_fn)\n\ntraining_model = get_resnet_self_supervise_model(128, 64, 1024)\n\nepoch_wise_loss, resnet_model  = train_model(training_model, train_ds, optimizer, criterion,\n                 temperature=0.1, epochs=200)\n\nplt.plot(epoch_wise_loss)\nplt.title(\"training loss versus epochs\")\nplt.xlabel('epoch')\nplt.ylabel('loss')\nplt.show()\n```\n\n      0%|          | 0/200 [00:00<?, ?it/s]\n\n    batch: 1 loss: 0.57619\n    batch: 2 loss: 0.43121\n    batch: 3 loss: 0.45222\n    batch: 4 loss: 0.39469\n    batch: 5 loss: 0.38681\n    batch: 6 loss: 0.33074\n    batch: 7 loss: 0.35192\n    batch: 8 loss: 0.34164\n    batch: 9 loss: 0.35104\n    batch: 10 loss: 0.36822\n    batch: 11 loss: 0.36665\n    batch: 12 loss: 0.35966\n\n\n      0%|          | 1/200 [11:33<38:21:06, 693.80s/it]\n\n    batch: 13 loss: 0.33729\n    batch: 1 loss: 0.32755\n    batch: 2 loss: 0.34130\n    batch: 3 loss: 0.33533\n    batch: 4 loss: 0.32271\n    batch: 5 loss: 0.31440\n    batch: 6 loss: 0.31166\n    batch: 7 loss: 0.29918\n    batch: 8 loss: 0.28848\n    batch: 9 loss: 0.27715\n    batch: 10 loss: 0.27190\n    batch: 11 loss: 0.28531\n    batch: 12 loss: 0.27678\n\n\n      1%|          | 2/200 [22:50<37:36:52, 683.90s/it]\n\n    batch: 13 loss: 0.27652\n    batch: 1 loss: 0.27942\n    batch: 2 loss: 0.28107\n    batch: 3 loss: 0.27381\n    batch: 4 loss: 0.26927\n    batch: 5 loss: 0.26277\n    batch: 6 loss: 0.25918\n    batch: 7 loss: 0.25793\n    batch: 8 loss: 0.25574\n    batch: 9 loss: 0.24996\n    batch: 10 loss: 0.24518\n    batch: 11 loss: 0.24362\n    batch: 12 loss: 0.23837\n\n\n      2%|\u258f         | 3/200 [34:09<37:17:54, 681.60s/it]\n\n    batch: 13 loss: 0.23610\n    batch: 1 loss: 0.23580\n    batch: 2 loss: 0.23282\n    batch: 3 loss: 0.22809\n    batch: 4 loss: 0.22476\n    batch: 5 loss: 0.22062\n    batch: 6 loss: 0.21746\n    batch: 7 loss: 0.21734\n    batch: 8 loss: 0.21505\n    batch: 9 loss: 0.21278\n    batch: 10 loss: 0.21072\n    batch: 11 loss: 0.20777\n    batch: 12 loss: 0.20842\n\n\n      2%|\u258f         | 4/200 [45:34<37:11:09, 683.01s/it]\n\n    batch: 13 loss: 0.20911\n    batch: 1 loss: 0.20676\n    batch: 2 loss: 0.20360\n    batch: 3 loss: 0.20137\n    batch: 4 loss: 0.19841\n    batch: 5 loss: 0.19752\n    batch: 6 loss: 0.19467\n    batch: 7 loss: 0.19474\n    batch: 8 loss: 0.19202\n    batch: 9 loss: 0.18932\n    batch: 10 loss: 0.18666\n    batch: 11 loss: 0.18378\n    batch: 12 loss: 0.18168\n\n\n      2%|\u258e         | 5/200 [57:01<37:04:26, 684.44s/it]\n\n    batch: 13 loss: 0.17976\n    batch: 1 loss: 0.17924\n    batch: 2 loss: 0.17720\n    batch: 3 loss: 0.17774\n    batch: 4 loss: 0.17523\n    batch: 5 loss: 0.17427\n    batch: 6 loss: 0.17216\n    batch: 7 loss: 0.17020\n    batch: 8 loss: 0.16820\n    batch: 9 loss: 0.16731\n    batch: 10 loss: 0.16708\n    batch: 11 loss: 0.16545\n    batch: 12 loss: 0.16392\n\n\n      3%|\u258e         | 6/200 [1:08:44<37:13:16, 690.70s/it]\n\n    batch: 13 loss: 0.16309\n    batch: 1 loss: 0.16115\n    batch: 2 loss: 0.16031\n    batch: 3 loss: 0.15966\n    batch: 4 loss: 0.15798\n    batch: 5 loss: 0.15774\n    batch: 6 loss: 0.15649\n    batch: 7 loss: 0.15519\n    batch: 8 loss: 0.15473\n    batch: 9 loss: 0.15320\n    batch: 10 loss: 0.15180\n    batch: 11 loss: 0.15050\n    batch: 12 loss: 0.14895\n\n\n      4%|\u258e         | 7/200 [1:20:29<37:16:23, 695.25s/it]\n\n    batch: 13 loss: 0.14764\n    batch: 1 loss: 0.14642\n    batch: 2 loss: 0.14534\n    batch: 3 loss: 0.14427\n    batch: 4 loss: 0.14284\n    batch: 5 loss: 0.14209\n    batch: 6 loss: 0.14105\n    batch: 7 loss: 0.14056\n    batch: 8 loss: 0.13948\n    batch: 9 loss: 0.13827\n    batch: 10 loss: 0.13721\n    batch: 11 loss: 0.13623\n    batch: 12 loss: 0.13502\n    batch: 13 loss: 0.13429\n\n\n      4%|\u258d         | 8/200 [1:32:51<37:52:23, 710.12s/it]\n\n    batch: 1 loss: 0.13313\n    batch: 2 loss: 0.13211\n    batch: 3 loss: 0.13158\n    batch: 4 loss: 0.13055\n    batch: 5 loss: 0.12949\n    batch: 6 loss: 0.12854\n    batch: 7 loss: 0.12752\n    batch: 8 loss: 0.12647\n    batch: 9 loss: 0.12582\n    batch: 10 loss: 0.12489\n    batch: 11 loss: 0.12422\n    batch: 12 loss: 0.12546\n\n\n      4%|\u258d         | 9/200 [1:44:56<37:55:59, 714.97s/it]\n\n    batch: 13 loss: 0.12449\n    batch: 1 loss: 0.12360\n    batch: 2 loss: 0.12267\n    batch: 3 loss: 0.12226\n    batch: 4 loss: 0.12221\n    batch: 5 loss: 0.12178\n    batch: 6 loss: 0.12156\n    batch: 7 loss: 0.12094\n    batch: 8 loss: 0.12008\n    batch: 9 loss: 0.11936\n    batch: 10 loss: 0.11854\n    batch: 11 loss: 0.11779\n    batch: 12 loss: 0.11741\n    batch: 13 loss: 0.11754\n\n\n      5%|\u258c         | 10/200 [1:57:18<38:10:26, 723.29s/it]\n\n    batch: 1 loss: 0.11689\n    batch: 2 loss: 0.11614\n    batch: 3 loss: 0.11538\n    batch: 4 loss: 0.11458\n    batch: 5 loss: 0.11444\n    batch: 6 loss: 0.11371\n    batch: 7 loss: 0.11293\n    batch: 8 loss: 0.11231\n    batch: 9 loss: 0.11165\n    batch: 10 loss: 0.11144\n    batch: 11 loss: 0.11155\n    batch: 12 loss: 0.11085\n\n\n      6%|\u258c         | 11/200 [2:09:18<37:54:46, 722.15s/it]\n\n    batch: 13 loss: 0.11027\n    batch: 1 loss: 0.11002\n    batch: 2 loss: 0.10948\n    batch: 3 loss: 0.10879\n    batch: 4 loss: 0.10941\n    batch: 5 loss: 0.10988\n    batch: 6 loss: 0.11054\n    batch: 7 loss: 0.11070\n    batch: 8 loss: 0.11029\n    batch: 9 loss: 0.10982\n    batch: 10 loss: 0.10929\n    batch: 11 loss: 0.10888\n    batch: 12 loss: 0.10856\n\n\n      6%|\u258c         | 12/200 [2:21:13<37:36:00, 720.00s/it]\n\n    batch: 13 loss: 0.10822\n    batch: 1 loss: 0.10772\n    batch: 2 loss: 0.10748\n    batch: 3 loss: 0.10699\n    batch: 4 loss: 0.10653\n    batch: 5 loss: 0.10756\n    batch: 6 loss: 0.10694\n    batch: 7 loss: 0.10635\n    batch: 8 loss: 0.10574\n    batch: 9 loss: 0.10526\n    batch: 10 loss: 0.10480\n    batch: 11 loss: 0.10450\n    batch: 12 loss: 0.10398\n\n\n      6%|\u258b         | 13/200 [2:32:56<37:07:57, 714.85s/it]\n\n    batch: 13 loss: 0.10352\n    batch: 1 loss: 0.10295\n    batch: 2 loss: 0.10258\n    batch: 3 loss: 0.10211\n    batch: 4 loss: 0.10166\n    batch: 5 loss: 0.10121\n    batch: 6 loss: 0.10090\n    batch: 7 loss: 0.10036\n    batch: 8 loss: 0.10023\n    batch: 9 loss: 0.09988\n    batch: 10 loss: 0.09948\n    batch: 11 loss: 0.09897\n    batch: 12 loss: 0.09883\n\n\n      7%|\u258b         | 14/200 [2:44:39<36:45:24, 711.42s/it]\n\n    batch: 13 loss: 0.09841\n    batch: 1 loss: 0.09804\n    batch: 2 loss: 0.09791\n    batch: 3 loss: 0.09746\n    batch: 4 loss: 0.09700\n    batch: 5 loss: 0.09752\n    batch: 6 loss: 0.09725\n    batch: 7 loss: 0.09687\n    batch: 8 loss: 0.09680\n    batch: 9 loss: 0.09636\n    batch: 10 loss: 0.09590\n    batch: 11 loss: 0.09586\n    batch: 12 loss: 0.09547\n\n\n      8%|\u258a         | 15/200 [2:56:25<36:27:56, 709.60s/it]\n\n    batch: 13 loss: 0.09537\n    batch: 1 loss: 0.09499\n    batch: 2 loss: 0.09454\n    batch: 3 loss: 0.09417\n\n\n\n```python\nplt.plot(epoch_wise_loss)\nplt.title(\"training loss versus epochs\")\nplt.show()\n```\n", "meta": {"hexsha": "b40055e0a8c1fbcb542c8c3e2d4e6617d2e72241", "size": 50957, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/SimCLR_Barlow_encoder_training.ipynb", "max_stars_repo_name": "arthijayaraman-lab/self-supervised_learning_microscopy_images", "max_stars_repo_head_hexsha": "f7adc86798379ae3934a864e6c41982a15aae870", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/SimCLR_Barlow_encoder_training.ipynb", "max_issues_repo_name": "arthijayaraman-lab/self-supervised_learning_microscopy_images", "max_issues_repo_head_hexsha": "f7adc86798379ae3934a864e6c41982a15aae870", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/SimCLR_Barlow_encoder_training.ipynb", "max_forks_repo_name": "arthijayaraman-lab/self-supervised_learning_microscopy_images", "max_forks_repo_head_hexsha": "f7adc86798379ae3934a864e6c41982a15aae870", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.2814313346, "max_line_length": 15078, "alphanum_fraction": 0.600290441, "converted": true, "num_tokens": 6220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014736319616964, "lm_q2_score": 0.060086652698692546, "lm_q1q2_score": 0.02584611522162661}}
{"text": "## Prerequisites\n\n\n```python\n# Ensure you have `gif` python package installed\n!pip install -U gif\n```\n\n    Collecting gif\n      Downloading gif-3.0.0.tar.gz (5.0 kB)\n    Requirement already satisfied, skipping upgrade: Pillow>=7.1.2 in /home/avani/anaconda3/lib/python3.8/site-packages (from gif) (7.2.0)\n    Building wheels for collected packages: gif\n      Building wheel for gif (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Created wheel for gif: filename=gif-3.0.0-py3-none-any.whl size=4816 sha256=3fe31bc766f5b80a7172a265a9f045a313fece269085946e5cab15c8a742bf3a\n      Stored in directory: /home/avani/.cache/pip/wheels/d8/db/4e/e0ce5209665322902834f4e88fa987f4dfa0c08271368ef098\n    Successfully built gif\n    Installing collected packages: gif\n    Successfully installed gif-3.0.0\n\n\n\n```python\nimport matplotlib\nprint(matplotlib.__version__)\n```\n\n    3.2.2\n\n\n#### Import utility functions\n\nWe have provided a bunch of helper functions in the utils.ipynb notebook that allows for commonly used functions that are not central to the discussion of topic at hand, like plotting functions etc. Feel free to explore the functions and their implementations.\n\nThe following cell imports the functions written in the utils notebook. You can ignore this part of the notebook\n\n\n```python\nimport io, os, sys, types\nfrom IPython import get_ipython\nfrom nbformat import read\nfrom IPython.core.interactiveshell import InteractiveShell\n\ndef find_notebook(fullname, path=None):\n    \"\"\"find a notebook, given its fully qualified name and an optional path\n\n    This turns \"foo.bar\" into \"foo/bar.ipynb\"\n    and tries turning \"Foo_Bar\" into \"Foo Bar\" if Foo_Bar\n    does not exist.\n    \"\"\"\n    name = fullname.rsplit('.', 1)[-1]\n    if not path:\n        path = ['']\n    for d in path:\n        nb_path = os.path.join(d, name + \".ipynb\")\n        #print('searching: %s'%nb_path)\n        if os.path.isfile(nb_path):\n            return nb_path\n        # let import Notebook_Name find \"Notebook Name.ipynb\"\n        nb_path = nb_path.replace(\"_\", \" \")\n        #print('searching: %s' % nb_path)\n        if os.path.isfile(nb_path):\n            return nb_path\n\nclass NotebookLoader(object):\n    \"\"\"Module Loader for Jupyter Notebooks\"\"\"\n    def __init__(self, path=None):\n        self.shell = InteractiveShell.instance()\n        self.path = path\n\n    def load_module(self, fullname):\n        \"\"\"import a notebook as a module\"\"\"\n        path = find_notebook(fullname, self.path)\n\n        print (\"importing Jupyter notebook from %s\" % path)\n\n        # load the notebook object\n        with io.open(path, 'r', encoding='utf-8') as f:\n            nb = read(f, 4)\n\n\n        # create the module and add it to sys.modules\n        # if name in sys.modules:\n        #    return sys.modules[name]\n        mod = types.ModuleType(fullname)\n        mod.__file__ = path\n        mod.__loader__ = self\n        mod.__dict__['get_ipython'] = get_ipython\n        sys.modules[fullname] = mod\n\n        # extra work to ensure that magics that would affect the user_ns\n        # actually affect the notebook module's ns\n        save_user_ns = self.shell.user_ns\n        self.shell.user_ns = mod.__dict__\n\n        #print('Found %d cells'%len(nb.cells))\n        try:\n          for cell in nb.cells:\n            if cell.cell_type == 'code':\n                # transform the input to executable Python\n                code = self.shell.input_transformer_manager.transform_cell(cell.source)\n                # run the code in themodule\n                exec(code, mod.__dict__)\n        finally:\n            self.shell.user_ns = save_user_ns\n        return mod\n\nclass NotebookFinder(object):\n    \"\"\"Module finder that locates Jupyter Notebooks\"\"\"\n    def __init__(self):\n        self.loaders = {}\n\n    def find_module(self, fullname, path=None):\n        nb_path = find_notebook(fullname, path)\n        if not nb_path:\n            return\n\n        key = path\n        if path:\n            # lists aren't hashable\n            key = os.path.sep.join(path)\n\n        if key not in self.loaders:\n            self.loaders[key] = NotebookLoader(path)\n        return self.loaders[key]\n\n\n#  register the NotebookFinder with sys.meta_path\nprint('running importer')\nsys.meta_path.append(NotebookFinder())\n```\n\n    running importer\n\n\n# Gradient Descent\n\nGradient descent is a first-order iterative optimization algorithm to find a local minima (or global minima in case of convex function) of a differentiable function. To achieve this, we take steps proportional to the negative of the gradient (or approximate gradient) of the function at the current point.\n\nConveniently, the objective function of linear regression algorithm is strictly convex and differentiable. Hence, we can use gradient descent optimization to find optimal values of our hypothesis function. \n\nWe revisit the equation to minimize the objective function of linear regression.\n\n\\begin{equation}\n\\min_{\\mathbf{w}} \\mathbf{J(w)} = \\min_{\\mathbf{w}} \\frac{1}{\\mathbf{N}} \\sum_\\mathbf{i=1}^\\mathbf{N} (\\mathbf{y_{i} - w^{\\top}x_i)^{2}}\n\\end{equation}\n\nOur gradient descent update for weights is:\n\n\\begin{equation}\n\\mathbf{w^{k+1}} \\leftarrow \\mathbf{w^k} - \\eta \\nabla{\\mathbf{J}}\n\\end{equation}\n\nwhere $\\eta$ is our learning rate and,\n\n\\begin{equation}\n\\nabla{\\mathbf{J}} = \\min_{\\mathbf{w}} \\frac{2}{\\mathbf{N}} \\sum_\\mathbf{i=1}^\\mathbf{N} (\\mathbf{y_{i} - w^{\\top}x_i)(-x_i)}\n\\end{equation}\n\nWe will look at Standard (Batch) Gradient Descent, Mini-batch, and Stochastic versions of Gradient Descent.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import make_regression\nfrom sklearn.model_selection import train_test_split\nimport seaborn as sb; sb.set();\nfrom utils import plot_convex_loss_and_predict_line, mse_error\nimport gif\n```\n\n    importing Jupyter notebook from utils.ipynb\n\n\n\n```python\nnum_samples = 100\n# Generating regression dataset\nX_train, Y_train = make_regression(n_samples=num_samples, n_features=1, n_informative=1, noise=20, random_state=2017)\n\n# Adding bias as a column in X\nbias_ones = np.ones((num_samples, 1))\nX_train = np.hstack((bias_ones, X_train))\nY_train = Y_train.reshape(-1, 1)\n```\n\n\n```python\nprint(\"X_train: num_samples {}, num_features {}\" .format((X_train.shape)[0], (X_train.shape)[1]))\n```\n\n    X_train: num_samples 100, num_features 2\n\n\n\n```python\nplt.figure(figsize=(7,7));\nplt.scatter(X_train[:, 1], Y_train, label='Point', color='green')\nplt.suptitle('X_train vs Y_train')\nplt.xlabel(\"X_train\")\nplt.ylabel(\"Y_train\");\n```\n\n\n```python\ndef train(X_train, Y_train, num_epochs, pts_per_batch, learning_rate, gd_type):\n    training_errors = []\n    frames = []\n\n    # Initializing weights\n    w = np.array([-15, 40]) + np.random.rand(2)\n    w = w.reshape(-1, 1)\n\n    weights_history = []\n    Y_prediction = []\n    append_flag = False\n\n    # Getting number of batches/epochs to run\n    num_train_datapts = len(Y_train)\n    mini_batches = int(num_train_datapts/pts_per_batch)\n\n    # If mini_batches = num_training_datapoints, then standard GD is being executed.\n    # If mini_batches > 1 and < num_training_datapoints, and an integer, then mini-batch GD is being run.\n    # If mini_batches = 1, then SGD is being run.\n\n    num_batches = int(mini_batches * num_epochs)\n    print(f'Num_batches: {num_batches} Mini-batches: {mini_batches} Num_epochs: {num_epochs} Points_per_batch {pts_per_batch} train_point {num_train_datapts}')\n\n    # Do gradient descent for 'num_batches' batches (or mini-batches)\n    temp_mse_history = []\n    for i in range(1, num_batches+1):\n\n        if num_train_datapts == pts_per_batch:\n            # Sampling training data points for batch GD\n            X_input = X_train\n            Y_true = Y_train\n      \n        else:\n            # Sampling training data points for stochastic or mini-batch GD\n            train_idxs = np.random.permutation(num_train_datapts)\n            train_idxs = train_idxs[:pts_per_batch]\n            X_input = X_train[train_idxs]\n            Y_true = Y_train[train_idxs]\n      \n        y_pred = np.dot(X_input, w)\n        # Gradient of l2 loss w.r.t w\n        grad_w = -np.dot(X_input.T, Y_true - y_pred)\n\n        temp_mse = np.mean(0.5 * (Y_true - y_pred)**2)\n    \n        if num_train_datapts == pts_per_batch:\n          # Appending values during batch GD\n          mse = temp_mse\n          append_flag = True\n      \n        elif pts_per_batch != 1 and pts_per_batch != num_train_datapts:\n            temp_mse_history.append(temp_mse)\n            if ((i % mini_batches == 0 and mini_batches != 1) or i == 1) and pts_per_batch != 1:\n                y_pred = np.dot(X_train, w)\n                mse = np.mean(temp_mse_history)\n                temp_mse_history = []\n                append_flag = True\n\n        elif pts_per_batch == 1:\n            y_pred = np.dot(X_train, w)\n            mse = np.mean(0.5 * (Y_train - y_pred)**2)\n            append_flag = True\n     \n        # Appending errors, weights, and predictions only if an epoch is completed.\n        # This will help us in our visualization of GD.\n        if append_flag:\n            training_errors.append(mse)\n            weights_history.append(w)\n            Y_prediction.append(y_pred)\n            append_flag = False\n\n        # Update the weights\n        w -= (2*learning_rate/pts_per_batch) * grad_w\n        w = np.round(w, decimals=2)\n\n    return training_errors, weights_history, Y_prediction\n```\n\n\n```python\ndef generate_GD_gifs(training_errors, weights_history, X_train, Y_train, Y_prediction, gd_type='mini-batch'):\n    frames = []\n\n    for i in range(len(training_errors)):\n        frame = plot_convex_loss_and_predict_line(training_errors, weights_history, X_train, Y_train, Y_prediction, i)\n        frames.append(frame)\n    gif.save(frames, \"content/\"+gd_type+\"_GD.gif\", duration=500)\n    print('gifs generated')\n```\n\nVanilla gradient descent, aka batch gradient descent, calculates the gradient of the loss function w.r.t to the parameters $w$ for all the training examples. We need to only make one update per epoch. However, for a large dataset, batch GD can be slow and sometimes intractable if the datasets don't fit in memory. Also, we can't update our model online, i.e., with new examples on-the-fly. The pseudo code is as follows:\n\nFor a dataset $D = (x_i, y_i)_i^m$ of $m$ training examples, \n\n1.  Initializing weights and biases.\n2.  For every epoch $\\in [1,...., \\text{max_epochs}]$:\n     * shuffle D to prevent cycles\n     * compute prediction $y_{\\text{prediction}} = activation(X_{\\text{input}} \\times weights)$\n     * compute loss $L = (y_{\\text{true}}, y_{\\text{predicted}})$\n     * compute gradients $\\Delta \\mathbf{w} = - \\nabla_{Loss} \\mathbf{w}$\n     * update parameters $\\mathbf{w} :=\\mathbf{w}+\\Delta \\mathbf{w}$\n\nBatch GD is guaranteed to converge to the global minima for convex loss surfaces and to a local minima for non-convex surfaces.\n\n\n```python\n# Batch GD\ntraining_errors, weights_history, Y_prediction = train(X_train, Y_train, num_epochs=20, pts_per_batch=100, learning_rate=0.1, gd_type='batch')\n\ngenerate_GD_gifs(training_errors, weights_history, X_train, Y_train, Y_prediction, gd_type='batch')\n```\n\n    Num_batches: 20 Mini-batches: 1 Num_epochs: 20 Points_per_batch 100 train_point 100\n    gifs generated\n\n\nVisualizing Batch Gradient Descent\n\n\n\n\n```python\n# Stochastic GD\ntraining_errors, weights_history, Y_prediction = train(X_train, Y_train, num_epochs=1, pts_per_batch=1, learning_rate=0.1, gd_type='SGD')\ngenerate_GD_gifs(training_errors, weights_history, X_train, Y_train, Y_prediction, gd_type='SGD')\n```\n\n    Num_batches: 100 Mini-batches: 100 Num_epochs: 1 Points_per_batch 1 train_point 100\n    gifs generated\n\n\nIn Stochastic GD, parameter updates are performed for every training example. Due to frequent updates, this leads to high variance that causes the loss function to fluctuate heavily.\n\nThese fluctuations can sometimes help to find better local minima. On the other hand, these fluctuations can lead to longer convergence time.\n\nFor a dataset $D = (x_i, y_i)_i^m$ of $m$ training examples, \n\n1.  Initializing weights and biases.\n2.  For every epoch $\\in [1,...., \\text{max_epochs}]$:\n>2.1  For iteration $\\text{itr} \\in [1,....., m]$: \n     * Draw random examples with replacement: $(x_i, y_i) \\in D$\n     * compute prediction $y_i^{\\text{prediction}} = activation(x_i \\times weights)$\n     * compute loss $L_i = (y_i^{\\text{true}}, y_i^{\\text{predicted}})$\n     * compute gradients $\\Delta \\mathbf{w} = - \\nabla_{Loss_i} \\mathbf{w}$\n     * update parameters $\\mathbf{w} :=\\mathbf{w}+\\Delta \\mathbf{w}$\n\nVisualizing Stochastic Gradient Descent\n\n\n\nMinibatch GD offers the best of both worlds, i.e., a trade-off between the stochastic GD that perform updates based on a single training example and Batch GD which takes all of the dataset at once. \n\nIn mini-batch, update is performed for every mini-batch of k training examples. Hence, we would have to take more updates per epoch as compared to batch GD.\n\nThe updates reduces the variances of parameter updates leading to a more stable convergence. By using highly optimized matrix computation from state-of-the-art machine learning libraries, mini-batch is typically the algorithm of choice when training a neural network.\n\nFor a dataset $D = (x_i, y_i)_i^m$ of $m$ training examples,\n\n<ol type=\"1\">\n<li>Initializing weights and biases.</li>\n<li>For every epoch $\\in [1,...., \\text{max_epochs}]$:</li>\n<ul>\n  <li>For iteration $i \\in [1,....., n]$: (where n is the mini-batch size)</li>\n  <ul>\n    <li>Draw random examples with replacement: $(x_i, y_i) \\in D$</li>\n  </ul>\n  <li>compute prediction $y_i^{\\text{prediction}} = activation(x_i \\times weights)$</li>\n  <li>compute loss $L_i = (y_i^{\\text{true}}, y_i^{\\text{predicted}})$</li>\n  <li>compute gradients $\\Delta \\mathbf{w} = - \\nabla_{L_i} \\mathbf{w}$</li>\n  <li>update parameters $\\mathbf{w} :=\\mathbf{w}+\\Delta \\mathbf{w}$</li>\n  </ul>\n</ol>\n  \n\nOne can also draw examples without replacement. Drawing examples w/o replacement is more commonly used in modern deep learning libraries. However, we shall look at mini-batch GD where we draw samples at random.\n\n\n```python\n# Mini-batch GD\ntraining_errors, weights_history, Y_prediction = train(X_train, Y_train, num_epochs=20, pts_per_batch=20, learning_rate=0.1, gd_type='mini-batch')\ngenerate_GD_gifs(training_errors, weights_history, X_train, Y_train, Y_prediction, gd_type='mini-batch')\n```\n\n    Num_batches: 100 Mini-batches: 5 Num_epochs: 20 Points_per_batch 20 train_point 100\n    gifs generated\n\n\nVisualizing mini-batch Gradient Descent\n\n\n\n# Visualizing the effect of learning rate on GD\n\nNow that we have seen the effect of changing the number of batches in a gradient descent, we look at the effect of different learning rates, another important factor that actively influences gradient descent. Previously, we had used 0.1 as our learning rate to train the linear regression model. Let's use Batch gradient descent as an example with lr rate $0.005$ and $1.1. You can try other values for other GD types.\n\n\n```python\n# Batch GD\ntraining_errors, weights_history, Y_prediction = train(X_train, Y_train, num_epochs=20, pts_per_batch=100, learning_rate=0.005, gd_type='batch')\ngenerate_GD_gifs(training_errors, weights_history, X_train, Y_train, Y_prediction, gd_type='batch-small-lr')\n```\n\n    Num_batches: 20 Mini-batches: 1 Num_epochs: 20 Points_per_batch 100 train_point 100\n    gifs generated\n\n\n\n\n\n```python\n# Batch GD\ntraining_errors, weights_history, Y_prediction = train(X_train, Y_train, num_epochs=15, pts_per_batch=100, learning_rate=1.1, gd_type='batch')\ngenerate_GD_gifs(training_errors, weights_history, X_train, Y_train, Y_prediction, gd_type='batch-large-lr')\n```\n\n    Num_batches: 15 Mini-batches: 1 Num_epochs: 15 Points_per_batch 100 train_point 100\n    gifs generated\n\n\n\n", "meta": {"hexsha": "e04f8f18fd86f2a7954a473486b75ecd7876fb7b", "size": 47591, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "HW6/Gradient Descent Tutorial.ipynb", "max_stars_repo_name": "avani17101/SMAI-Assignments", "max_stars_repo_head_hexsha": "8d408911f964768bf50d965f881d10d37ac8f7f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-03-05T12:28:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-05T12:28:44.000Z", "max_issues_repo_path": "HW6/Gradient Descent Tutorial.ipynb", "max_issues_repo_name": "avani17101/Statistical-Methods-in-AI", "max_issues_repo_head_hexsha": "8d408911f964768bf50d965f881d10d37ac8f7f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW6/Gradient Descent Tutorial.ipynb", "max_forks_repo_name": "avani17101/Statistical-Methods-in-AI", "max_forks_repo_head_hexsha": "8d408911f964768bf50d965f881d10d37ac8f7f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-05T12:21:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-05T12:21:26.000Z", "avg_line_length": 51.9552401747, "max_line_length": 17964, "alphanum_fraction": 0.715492425, "converted": true, "num_tokens": 4133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19930799790404566, "lm_q2_score": 0.12940272655544907, "lm_q1q2_score": 0.025790998353091236}}
{"text": "# writefile Magic Function\n\n\n```python\n%%writefile test.txt\nthis is written from a jupyter notebook\n```\n\n    Writing test.txt\n\n\n# The above magic function creates a file if it dint have and writes next lines in the file. if the file exists it will clean up and write the new data.\n\n\n```python\n%%writefile test.txt\nfile exist check from jupyter notebook\n```\n\n    Overwriting test.txt\n\n\n# ls magic function\n\n\n```python\n%ls\n```\n\n    Magic Functions.ipynb           processing_data.ipynb\r\n    My First NoteBook.ipynb         test.txt\r\n    Writefile Magic Function.ipynb\r\n\n\n# HTML Magic Function\n\n\n```python\n%%HTML\n<body> Hello</body>\n```\n\n\n<body> Hello</body>\n\n\n\n# latex magic function used to write the equation\n\n\n```latex\n%%latex\n\\begin{align}\nGradient : \\nabla J = -2H^T (Y-HW)\n\\end{align}\n```\n\n\n\\begin{align}\nGradient : \\nabla J = -2H^T (Y-HW)\n\\end{align}\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "49d2a3fc61f8f539bcd14ed54819ddd1e432538e", "size": 3145, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Writefile Magic Function.ipynb", "max_stars_repo_name": "SrinivasKummari/data-science-with-python", "max_stars_repo_head_hexsha": "0f824c437325c1cae5793e96625c19976fb17149", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/Writefile Magic Function.ipynb", "max_issues_repo_name": "SrinivasKummari/data-science-with-python", "max_issues_repo_head_hexsha": "0f824c437325c1cae5793e96625c19976fb17149", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/Writefile Magic Function.ipynb", "max_forks_repo_name": "SrinivasKummari/data-science-with-python", "max_forks_repo_head_hexsha": "0f824c437325c1cae5793e96625c19976fb17149", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.1791907514, "max_line_length": 158, "alphanum_fraction": 0.4826709062, "converted": true, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167645017354, "lm_q2_score": 0.05582314663237466, "lm_q1q2_score": 0.025735406444763312}}
{"text": "<font color='black' size=10><b><center>Dancing with the Moon</center></b></font>\n\n<font color='blue' size=4><b><center>Learned Uncertainty-Aware (LUNA) Bases for</center></b></font>\n<font color='blue' size=4><b><center>Bayesian Regression using Multi-Headed Auxiliary Networks</center></b></font>\n\n<font color='black' size=4><center>Shih-Yi Tseng, Sangyoon Park, Paulina Toro Isaza, Arthur Young, Avriel Epps-Darling<center></font>\n\n## Table of Contents\n\n1. [Problem Statement and Context](#chapter1)\n\n2. [Existing Work](#chapter2)\n\n3. [Contributions](#chapter3)\n\n4. [Technical Content](#chapter4)\n\n5. [Implementation](#chapter5)\n\n6. [Demo: NLM vs. LUNA under Regularization](#chapter6)\n\n7. [Experiments](#chapter7)\n    * [7.1 Comparison of Methods](#section_7_1)\n    * [7.2 Exploring NLM Behavior](#section_7_2)  \n       * [7.2.1 How does regularization affect NLM uncertainty in data-scare regions?](#section_7_2_1)\n       * [7.2.2 How consistent is good uncertainty behavior in data-scare regions for NLMs?](#section_7_2_2)\n    * [7.3 Exploring LUNA Behavior](#section_7_3)\n       * [7.3.1 How does LUNA\u2019s behavior relate to regularization and diversification strengths?](#section_7_3_1)\n       * [7.3.2 How does LUNA\u2019s behavior relate to the number of auxiliary functions?](#section_7_3_2)\n       * [7.3.3 How does LUNA behave with variation in neural network architecture?](#section_7_3_3)\n       * [7.3.4 How does LUNA behave on different gap locations?](#section_7_3_4)\n       * [7.3.5 How does LUNA behave on multivariate functions?](#section_7_3_5)\n\n8. [Evaluation](#chapter8)\n\n9. [Broader Impact](#chapter9)\n\n10. [References](#chapter10)\n\n## 1. Problem Statement and Context <a class=\"anchor\" id=\"chapter1\"></a>\n\nWhile we typically think of model performance in terms of predictive accuracy, many applications would benefit from (and indeed, should require) producing reliable uncertainty measurements. This is particularly true in high-stakes applications where a user should either turn over an uncertain machine-produced decision to a qualified human decison-maker or abstain from using the machine-produced decision altogether. \n\nIntuitvely, a model should be less certain in data-scarce regions than it is in data-rich regions. Most implementations of popular predictive models do not have an out-of-the-box method to signal to a user that a prediction is being made on data that is out-of-distribution or to quantify the uncertainty due to limited data (also known as epistemic uncertainty). However, generating high model predictive uncertainties in data-scare regions and low predictive uncertainties in data-rich regions is not a trivial task. \n\nPrevious methods for achieving this task are Gaussian Processes (GP), Bayesian Neural Networks (BNNs), and Neural Linear Models (NLM). The first two are not ideal solutions as they are not particularly scalable (GP) or have challenging, intractable inference (BNNs). NLMs are meant to solve these issues by providing tractable inference at scale. For this reason, NLMs have become popular models for applications that require predictive uncertainty.\n\nDespite their popularity, it is not clear from the literature that NLMs produce the desired uncertainty behavior with respect to data-scare and data-rich regions. (See Existing Work for more details.) In \"Learned Uncertainty-Aware (LUNA) Bases for Bayesian Regression using Multi-Headed Auxiliary Networks\" (Thakur, et. al, 2020), the authors theoretically and empirically investigate the drawbacks of NLMs and propose LUNA, an alternative training procedure, to address these draw backs.\n\n## 2. Existing Work <a class=\"anchor\" id=\"chapter2\"></a>\n\n**Gaussian Processes**\n\nA Gaussian Process (GP) assigns probability distributions not to specific parameters as in traditional Bayesian methods, but to functions (Rasmussen & Williams, 2006). They are particularly useful for producing \"good\" uncertainty behavior because they support infinite basis functions which lead to high expressiveness. \n\nUnfortunately, despite producing the desired uncertainty behavior in data-scare regions, GPs are ultimately not practical for most large-scale data applications because they do not scale well as the number of data points increases. This has led researchers to investigate efficient, scalable alternatives.\n\n**Bayesian Neural Networks**\n\nOne such alternative is the Bayesian Neural Network (BNN), a neural network whose parameter weights have a prior distribution and thus can produce distributions of predictions instead of simply point-estimates as in traditonal neural networks. (Neal, 1995). These prediction distributions easily translate to model prediction uncertainty. \n\nHowever, BNNs are not a practical solution. They do not solve the scalability issue of GPs as gradient-based samplers like HMC are extremely inefficient with large training data. Stochastic implementations of HMC sampling and parallelization can help increase efficiency in relation to training size (Springenber et al., 2016), but that still leaves the challenge of sampling from the complex, multimodal posteiror of neural networks. \n\n**Neural Linear Models**\n\nA Neural Linear Model is an approximation of GPs in which, instead of placing prior distributions on all the weights as in BNNs, priors are placed on only the weights of the last neural network layer (Snoek et al.,\n2015). All other layer weights are point-estimates as in the traditional neural network setting. Essentially, we can think of the deterministic layers as learning a feature map while the last layer performs Bayesian Lienar Regression on the basis of this learned feature map. Restricting prior distributions to only the weights in the last layer allows NLMs to be more tractable than BNNs as there is a closed form analytical expression for the posterior of this last layer.\n\nAs mentioned in the problem statement, it is not clear from the literature that NLMs can distinguish between data-scare and data-rich regions and produce the desired uncertainty behaviors for each. One paper claims that a large log-likelihood in the data-scare region signifies high model uncertainty (Ober &\nRasmussen, 2019). This claim does not hold up when we recognize that log-likelihood only accounts for aleatoric uncertainty: that is, uncertainty that comes from the underlying variation in the data generating process (Yao et al., 2019). A good measure of aleatoric uncertainty does not necessarily equate to a good measure of epistemic uncertainty. \n\n## 3. Contributions <a class=\"anchor\" id=\"chapter3\"></a>\n\nThe paper contributes to the literature in two main ways: \n1. Theoretically and empirically determinng that NLMs fail to consistently distinguish between data-scare and data-rich regions when including regularization\n2. Proposing an alternative training procedure that consistently distinguishes between data-scare and data-rich regions when including regularization while providing more scalability than GPs and BNNs\n\nThe technical details of these contributions are expanded on below. \n\n## 4. Technical Content <a class=\"anchor\" id=\"chapter4\"></a>\n\n### High Level\n\nThe development of LUNA was motivated by the recognition that NLM, a popular Bayesian deep learning architecture with easily interpreted inference properties, generates problematic uncertainty estimates in sparse regions of support using traditional learning methods. The authors address this shortcoming by proposing LUNA as an alternative training procedure, augmenting the objective function with an additional term designed to \"diversify\" priors at a computational cost equivalent to training one neural-network and one Bayesian linear regression. In short, an NLM can be considered in two parts: the first is a neural network that projects the covariates $\\mathbf{x} \\in \\mathbb{R}^D$ into an embedding called $\\phi_{\\theta}(\\mathbf{x}) \\in \\mathbb{R}^L$, parameterized by $\\theta$. Then, the embedded manifold $\\phi_{\\theta}$ is passed to a layer of Bayesian linear regression parameterised by $\\mathbf{w} \\sim \\mathcal{N}(0, \\alpha \\mathbf{I})$ to yield predictions $y$. The model is trained by seeking point estimate values for $\\theta$ and then performs inference using the last layer parameterised by $\\mathbf{w}$. \n\nLUNA-based training encourages functional diversity of the feature map $\\phi_{\\theta}$ learned by the neural network via training $M$ auxiliary linear regressors. The core of LUNA is a two-part objective function:\n\n$$\\mathcal{L}_{LUNA}(\\Psi) = \\mathcal{L}_{Fit}(\\Psi) - \\lambda \\cdot \\mathcal{L}_{Diverse}(\\Psi)$$\n\nwhere $\\Psi$ includes shared parameters $\\theta$ from the neural network and $M$ sets of $\\mathbf{w}$ for the auxiliary regressors. The first part, $\\mathcal{L}_{Fit}(\\Psi)$, represents the log likelihood of $M$ regressors on training data with $L_2$ regularization, whereas the second part, $\\mathcal{L}_{Diverse}(\\Psi)$, encodes the cosine similarity of the gradients of the $M$ regressors and thus penalizes non-orthogonal gradients. The hyperparameter $\\lambda$ represents diversification strength, i.e. how much to prioritize diversity in LUNA training.\n\nAfter training the NLM with $\\mathcal{L}_{LUNA}(\\Psi)$ which generates diversified feature basis $\\phi_{\\theta}$, we toss the auxiliary regressions and perform standard linear Bayesian regression over $\\phi_{\\theta}(\\mathbf{x})$ and analytically compute the posterior of the weights $\\mathbf{w}$.\n\n### Details\n\nThe first part of LUNA\u2019s objective function is specified as:\n\n$$\\mathcal{L}_{Fit}(\\Psi) = \\frac{1}{M} \\sum_{m=1}^M \\log\\mathcal{N}(\\mathbf{y}\\,; f_m(\\mathbf{x}), \\sigma^2\\mathbf{I}) - \\gamma\\|\\Psi\\|^2_2$$\n\nwhich is a direct extension of NLM\u2019s maximum a posteriori (MAP) objective. Hence, it attempts to maximize auxiliary regressors\u2019 overall goodness of fit with the observed data while preventing overfitting via $L_2$ regularization.\n\nThe second part of LUNA\u2019s objective function is specified as:\n\n$$\n\\begin{aligned}\n\\mathcal{L}_{Diverse}(\\Psi) \n&= \\sum_{i=1}^M \\sum_{j=i+1}^M \\text{CosSim}^2 \\left( \\nabla_{\\mathbf{x}} f_i(\\mathbf{x}), \\nabla_{\\mathbf{x}} f_j(\\mathbf{x}) \\right) \\\\\n&= \\sum_{i=1}^M \\sum_{j=i+1}^M \\frac{\\left( \\nabla_{\\mathbf{x}} f_i(\\mathbf{x})^T \\nabla_{\\mathbf{x}} f_j(\\mathbf{x}) \\right)^2}{\\left( \\nabla_{\\mathbf{x}} f_i(\\mathbf{x})^T \\nabla_{\\mathbf{x}} f_i(\\mathbf{x}) \\right) \\left( \\nabla_{\\mathbf{x}} f_j(\\mathbf{x})^T \\nabla_{\\mathbf{x}} f_j(\\mathbf{x}) \\right)}\n\\end{aligned}\n$$\n\nwhere `CosSim` stands for cosine similarity. Hence, we can see that this diversity objective minimizes when the gradients of auxiliary regressors are all orthogonal to one another, and this orthogonality of auxiliary regressors can be used as a proxy for the diversity of the functions spanned by the feature basis. In practice, we calculate these gradients using a finite difference approximation to avoid expensive computations, i.e. we use:\n\n$$\\nabla_{\\mathbf{x}} f_i(\\mathbf{x}) \\approx \\frac{f_i(\\mathbf{x} + \\delta\\mathbf{x}) - f_i(\\mathbf{x})}{\\delta\\mathbf{x}}$$\n\nfor some small perturbation $\\delta\\mathbf{x} \\sim \\mathcal{N}(0,\\sigma^2)$ where we generally set $\\sigma=0.1$.\n\n## 5. Implementation <a class=\"anchor\" id=\"chapter5\"></a>\n\nFor our experiments, we implemented various models used for uncertainty evaluation including GPs, BNNs, NLMs, and ensemble neural networks. \n\nHowever, the main implementation work was implementing a working version of LUNA for both single and multi-variate scenarios. \n\nWe decided to implement LUNA as an extension of our general NLM class. As mentioned above, the main differences between LUNA and NLM is the inclusion of auxiliary functions and the loss function $\\mathcal{L}_{Diverse}$. Below, we include a code snippet showing this new loss function. To see the full implementation of LUNA along with the implementations of other models, please see source code [here](https://github.com/weyesians/luna-passa/blob/main/src/models.py).\n\n```python\ndef _make_objective(self, x_train, y_train, reg_param=0, lambda_in=0):\n    M = self.params['M']\n    N = x_train.shape[1]\n\n    def objective(W_full, t):\n        # Compute L_fit\n        y_train_rep = np.tile(y_train, reps=(M,1,1)) # repeat y_train with shape = dim_out x n_sample to M x dim_out x n_sample\n        squared_error = np.linalg.norm(y_train_rep - self.forward(W_full, x_train), axis=1)**2\n        L_fit = np.mean(squared_error) + reg_param * (np.linalg.norm(W_full)**2) / W_full.size\n\n        # Comput L_diverse (#### Only works for dim_out = 1 ####)\n        if self.params['dim_in'] == 1:\n            grad_FD = self._finite_diff_grad(W_full, x_train) # reshape to M x num of samples\n            grad_angle = np.arctan(grad_FD) # compute the \"angle of those gradients\"\n            grad_angle_rep = np.tile(grad_angle, reps=(M,1,1)) # repeate the matrix to create M x M x num of samples\n            grad_angle_rep_transpose = np.transpose(grad_angle_rep, axes=(1,0,2)) # transpose the M x M matrix so we can take pairwise differences between auxiliary functions\n            coSimSqMat = np.mean(np.cos(grad_angle_rep - grad_angle_rep_transpose)**2, axis=-1) # take pairwise square cosine similarity between auxiliary functions, average over datapoints\n        else:\n            grad_FD = self._finite_diff_grad(W_full, x_train) # M x dim_in x num of samples\n            norm_grad = grad_FD/(np.linalg.norm(grad_FD, axis=1).reshape((M,1,N))) # normalize along gradient wrt dim_in to unit length (so inner product gives cosine value directly)\n            norm_grad_transpose = np.transpose(norm_grad, axes=(1,0,2)) # transpose first two dimensions of norm_grad (for taking pairwise inner product in next step)\n            coSimSqMat = np.mean(np.einsum('ij...,jk...->ik...', norm_grad, norm_grad_transpose)**2, axis=-1) # take pairwise square cosine similarity between auxiliary functions (broadcasting along datapoint dimension), and then average over datapoints\n            #### See documentation for np.einsum (with broadcasting): https://numpy.org/doc/stable/reference/generated/numpy.einsum.html#numpy.einsum\n\n        coSimSq_uniq_pair = coSimSqMat[np.triu(np.ones((M,M), dtype=bool), k=1)] # taking the upper triagular part\n        L_diverse = np.mean(coSimSq_uniq_pair)\n\n        return L_fit + lambda_in * L_diverse  # punish when coSimSq is large (close to 1)\n\n    return objective, grad(objective)\n```\n\nIn the following section, we demonstrate how to use our implementations of NLM and LUNA through a simple pedagogical example.\n\n*Note: Training may take a long time, so we recommend NOT running it yourself unless you need to.*\n\n## 6. Demo: NLM vs. LUNA under Regularization <a class=\"anchor\" id=\"chapter6\"></a>\n\nThe paper argues that the main problem with NLMs is that they are unable to express the desired uncertainty behavior in data-scare regions when using regularization. LUNA was set out to remedy this limitation by using a diversified feature map. Below, we walk through generating two sets of NLM and LUNA, one with no regularization and the other with regularization, on the same cubic gap toy dataset.\n\nFirst, we generate the toy data and setup the NLM and LUNA architecture. All models share the same architecture, and the only difference is the regularization strength.\n\n\n```python\nfrom src.models import NLM, LUNA\nfrom src.utils import generate_data, format_time, neg_log_likelihood, epistemic_uncertainty\nfrom autograd import numpy as np\nimport matplotlib.pyplot as plt\n\n# Generate toy data\nx, y, x_test, y_test = generate_data(number_of_points=50, noise_variance=9)\n\n# Extract test gap data\ngap_idx = np.logical_and(x_test > -2, x_test < 2)\nx_test_gap = x_test[gap_idx].reshape(1,-1)\ny_test_gap = y_test[gap_idx].reshape(1,-1)\n\n# Extract test non-gap data\nnon_gap_idx = np.logical_or(np.logical_and(x_test > -4, x_test < -2),np.logical_and(x_test > 2, x_test < 4))\nx_test_non_gap = x_test[non_gap_idx].reshape(1,-1)\ny_test_non_gap = y_test[non_gap_idx].reshape(1,-1)\n\n# Define model architecture to use\narchitecture = {\n    'width': [50,50],\n    'input_dim': 1,\n    'output_dim': 1,\n    'activation_fn_type': 'relu',\n    'activation_fn_params': 'rate=1',\n    'activation_fn': lambda x: np.maximum(np.zeros(x.shape), x),\n    'auxiliary_functions': 30, # Used by LUNA\n}\n\n# Set random state to make the experiments replicable\nrand_state = 207\nrandom = np.random.RandomState(rand_state)\n\n# Define design choices in gradient descent\nparams = {\n    'step_size': 1e-2,\n     'max_iteration': 10000,\n    'random_restarts': 1,\n    'reg_param': 100,\n    'lambda_in': 100, # Diversification strength\n}\n\n# Set hyperparameter values for inference later\nprior_var = 9\nnoise_var = 9\n```\n\nWe then train two sets of models, one with `regularization = 0` and the other with `regularization = 100`.\n\n\n```python\nnlm_list = []\nluna_list = []\nreg_grid = [0, 100]\n\nfor reg in reg_grid:\n\n    print(f\"\\n===== NLM (REG={reg}) =====\")\n    nlm = NLM(architecture, random=random)\n    nlm.modtype = 'NLM'\n    nlm.reg = params['reg_param'] = reg\n    nlm.fit(x, y, params)\n    nlm_list.append(nlm)\n    \n    print(f\"\\n===== LUNA (REG={reg}) =====\")\n    luna = LUNA(architecture, random=random)\n    luna.modtype = 'LUNA'\n    luna.reg = params['reg_param'] = reg\n    luna.fit(x, y, params)\n    luna_list.append(luna)\n```\n\n    \n    ===== NLM (REG=0) =====\n    Iteration 0 loss 8528.227060221521; gradient mag: 19598.254854870906\n    Iteration 100 loss 84.49891870185589; gradient mag: 67.34066308198605\n    Iteration 200 loss 23.804832498265508; gradient mag: 34.36073329179997\n    Iteration 300 loss 12.418929611269178; gradient mag: 7.8218258203317514\n    Iteration 400 loss 10.833654191403163; gradient mag: 2.603156060823849\n    Iteration 500 loss 10.565464009747789; gradient mag: 2.632838821656602\n    Iteration 600 loss 10.522010012687586; gradient mag: 3.468157468040252\n    Iteration 700 loss 10.514785998102338; gradient mag: 1.0840878651546675\n    Iteration 800 loss 10.513083020485986; gradient mag: 1.7432762192455329\n    Iteration 900 loss 10.512718093410115; gradient mag: 2.216655357850456\n    Iteration 1000 loss 10.512281893348105; gradient mag: 2.3291578455178\n    Iteration 1100 loss 10.51197817744762; gradient mag: 1.9205608390549807\n    Iteration 1200 loss 10.511787318890566; gradient mag: 4.706958056203429\n    Iteration 1300 loss 10.511204686453416; gradient mag: 4.695649795427318\n    Iteration 1400 loss 10.51097164042729; gradient mag: 2.460687075682837\n    Iteration 1500 loss 10.510311562667647; gradient mag: 1.6778503289859854\n    Iteration 1600 loss 10.50095332049078; gradient mag: 1.3623617704487894\n    Iteration 1700 loss 10.45089327629521; gradient mag: 3.4282697264925712\n    Iteration 1800 loss 10.436969213460163; gradient mag: 16.15696246510949\n    Iteration 1900 loss 10.432864780407353; gradient mag: 6.876936932659294\n    Iteration 2000 loss 10.450859596560244; gradient mag: 40.8353146249787\n    Iteration 2100 loss 10.44003340420753; gradient mag: 26.048897261168232\n    Iteration 2200 loss 10.43266568638607; gradient mag: 11.728762417335501\n    Iteration 2300 loss 10.45305197483575; gradient mag: 40.60044110057031\n    Iteration 2400 loss 10.432302855343321; gradient mag: 11.35681406022038\n    Iteration 2500 loss 10.429993770466336; gradient mag: 8.197233785252985\n    Iteration 2600 loss 10.443446715314945; gradient mag: 34.29245214323841\n    Iteration 2700 loss 10.43666077995932; gradient mag: 27.476832465246858\n    Iteration 2800 loss 10.433598570497745; gradient mag: 18.637401361565118\n    Iteration 2900 loss 10.44474925693802; gradient mag: 36.89076878991913\n    Iteration 3000 loss 10.424267083045056; gradient mag: 44.89009401296932\n    Iteration 3100 loss 10.405757229259931; gradient mag: 21.698369841974653\n    Iteration 3200 loss 10.422459229163712; gradient mag: 41.69408059731369\n    Iteration 3300 loss 10.505097156088102; gradient mag: 94.91919052617939\n    Iteration 3400 loss 10.441125011830039; gradient mag: 59.714125284075536\n    Iteration 3500 loss 10.43613871225458; gradient mag: 57.22764046111752\n    Iteration 3600 loss 10.490103076530781; gradient mag: 89.55186211297212\n    Iteration 3700 loss 10.493066571583693; gradient mag: 90.07733986706533\n    Iteration 3800 loss 10.532923390901006; gradient mag: 106.77774306220813\n    Iteration 3900 loss 10.408146107267612; gradient mag: 33.35911241292401\n    Iteration 4000 loss 10.475341734749852; gradient mag: 81.35621212531024\n    Iteration 4100 loss 10.550439026405854; gradient mag: 110.95619088066064\n    Iteration 4200 loss 10.501448899084407; gradient mag: 94.32104820921185\n    Iteration 4300 loss 10.582395468050402; gradient mag: 120.52309588596093\n    Iteration 4400 loss 10.437197970778088; gradient mag: 60.78259650137255\n    Iteration 4500 loss 10.526366142119002; gradient mag: 97.72022241023609\n    Iteration 4600 loss 10.45369067402969; gradient mag: 63.005982475082256\n    Iteration 4700 loss 10.395128087832713; gradient mag: 14.619481424459936\n    Iteration 4800 loss 10.450261397930934; gradient mag: 68.18144462480525\n    Iteration 4900 loss 10.560790581680052; gradient mag: 112.61610289190273\n    Iteration 5000 loss 10.403061325479449; gradient mag: 30.257822181630353\n    Iteration 5100 loss 10.629110593288651; gradient mag: 128.3793111934154\n    Iteration 5200 loss 10.422783473638376; gradient mag: 46.330177405946415\n    Iteration 5300 loss 10.52339189536503; gradient mag: 99.06778031703858\n    Iteration 5400 loss 10.776227713255512; gradient mag: 167.6617907903096\n    Iteration 5500 loss 10.419595272379093; gradient mag: 46.041982950247025\n    Iteration 5600 loss 10.573883621925592; gradient mag: 115.59514397817439\n    Iteration 5700 loss 10.404747183627542; gradient mag: 35.158863697171995\n    Iteration 5800 loss 10.41727212065247; gradient mag: 45.81645973531454\n    Iteration 5900 loss 11.245970235819845; gradient mag: 241.04710470375545\n    Iteration 6000 loss 10.431876832276771; gradient mag: 56.52960652530773\n    Iteration 6100 loss 10.47669855405274; gradient mag: 75.6591199432546\n    Iteration 6200 loss 10.420079690963673; gradient mag: 44.13386899593992\n    Iteration 6300 loss 10.389887876411443; gradient mag: 12.243911514043134\n    Iteration 6400 loss 10.393077043470845; gradient mag: 23.45587853468485\n    Iteration 6500 loss 10.70625243079822; gradient mag: 151.28633492395002\n    Iteration 6600 loss 10.393963693421993; gradient mag: 24.664436028541594\n    Iteration 6700 loss 10.431996561026379; gradient mag: 55.38067245895778\n    Iteration 6800 loss 10.538206373350308; gradient mag: 100.99999557243395\n    Iteration 6900 loss 10.941695953306684; gradient mag: 197.79373140138946\n    Iteration 7000 loss 10.556288546275358; gradient mag: 105.31334650281363\n    Iteration 7100 loss 10.582110894270198; gradient mag: 103.34457885029897\n    Iteration 7200 loss 11.923815994093975; gradient mag: 307.20856441819507\n    Iteration 7300 loss 10.723860595835395; gradient mag: 151.74638909633325\n    Iteration 7400 loss 10.607085508523774; gradient mag: 123.87778406106116\n    Iteration 7500 loss 10.968228994060212; gradient mag: 188.60090319388183\n    Iteration 7600 loss 10.385634078634656; gradient mag: 15.744531620815685\n    Iteration 7700 loss 10.702275944371115; gradient mag: 142.99530166169544\n    Iteration 7800 loss 10.478641075622512; gradient mag: 79.91116480692638\n    Iteration 7900 loss 10.84036365002717; gradient mag: 174.4116802496813\n    Iteration 8000 loss 10.461126134864978; gradient mag: 72.50825656995956\n    Iteration 8100 loss 10.46838903973504; gradient mag: 77.97660798556133\n    Iteration 8200 loss 10.411889850220605; gradient mag: 44.32319118921171\n    Iteration 8300 loss 10.697031832948728; gradient mag: 134.87026640424094\n    Iteration 8400 loss 10.541463302745688; gradient mag: 98.06419828853662\n    Iteration 8500 loss 10.37561168982572; gradient mag: 6.57457179523248\n    Iteration 8600 loss 10.38014802475929; gradient mag: 15.054719758996201\n    Iteration 8700 loss 10.398632899976558; gradient mag: 34.26027080269745\n    Iteration 8800 loss 10.472555620767343; gradient mag: 72.60344799269183\n    Iteration 8900 loss 10.420082602357509; gradient mag: 47.69441610521311\n    Iteration 9000 loss 10.374311981490441; gradient mag: 7.193014805159492\n    Iteration 9100 loss 10.43536401876941; gradient mag: 56.53436528331403\n    Iteration 9200 loss 10.375190796669658; gradient mag: 9.144443566006354\n    Iteration 9300 loss 10.419574824681554; gradient mag: 43.83851040799768\n    Iteration 9400 loss 10.460188156060125; gradient mag: 72.17042687309107\n    Iteration 9500 loss 10.375867184420976; gradient mag: 12.170261181979619\n    Iteration 9600 loss 10.425504119888004; gradient mag: 57.80900433096751\n    Iteration 9700 loss 10.3863910440511; gradient mag: 24.068218517024906\n    Iteration 9800 loss 11.588110925828898; gradient mag: 261.1501932228748\n    Iteration 9900 loss 11.063307004817576; gradient mag: 192.09911576327707\n    \n    ===== LUNA (REG=0) =====\n    Iteration 0 loss 6277.716078373747; gradient mag: 3918.0722055757064\n    Iteration 100 loss 188.3932673237993; gradient mag: 62.90218048310361\n    Iteration 200 loss 145.21101453202377; gradient mag: 67.17975309014055\n    Iteration 300 loss 129.23256529174984; gradient mag: 71.59258001352214\n    Iteration 400 loss 125.18565234554143; gradient mag: 170.12779305702526\n    Iteration 500 loss 124.76634008307113; gradient mag: 29.0985570371727\n    Iteration 600 loss 121.68884260577632; gradient mag: 18.47243173263044\n    Iteration 700 loss 121.24396409987506; gradient mag: 44.076999049578454\n    Iteration 800 loss 120.60259052636994; gradient mag: 63.05807528850618\n    Iteration 900 loss 118.0665853913944; gradient mag: 24.203063586771655\n    Iteration 1000 loss 118.12002733909915; gradient mag: 108.32307085297276\n    Iteration 1100 loss 117.25955357833328; gradient mag: 52.4852272803146\n    Iteration 1200 loss 116.4016919942924; gradient mag: 69.95960527765328\n    Iteration 1300 loss 116.47136946199305; gradient mag: 46.94171950714422\n    Iteration 1400 loss 115.85103079382549; gradient mag: 76.99504112237258\n    Iteration 1500 loss 116.36462832894799; gradient mag: 53.05442716198619\n    Iteration 1600 loss 116.54860086189703; gradient mag: 89.14416858128315\n    Iteration 1700 loss 115.2544641958385; gradient mag: 26.005106933065466\n    Iteration 1800 loss 115.29431110525897; gradient mag: 68.03997109107125\n    Iteration 1900 loss 115.17412301565841; gradient mag: 41.645413739744605\n    Iteration 2000 loss 130.9704784195348; gradient mag: 167.6097434201943\n    Iteration 2100 loss 116.30792643811873; gradient mag: 121.72791372254919\n    Iteration 2200 loss 116.15843696044064; gradient mag: 42.33976729619227\n    Iteration 2300 loss 116.02256721703736; gradient mag: 31.174172163558833\n    Iteration 2400 loss 115.27831988823525; gradient mag: 38.051410638351406\n    Iteration 2500 loss 115.33389376402945; gradient mag: 43.98933785300733\n    Iteration 2600 loss 116.08392327337188; gradient mag: 51.395357878967204\n    Iteration 2700 loss 115.5760372748519; gradient mag: 75.75490206355836\n    Iteration 2800 loss 118.38772855497722; gradient mag: 68.43667729717075\n    Iteration 2900 loss 116.10553325852747; gradient mag: 233.08324849965206\n    Iteration 3000 loss 115.69513934901762; gradient mag: 46.76722581965417\n    Iteration 3100 loss 115.2982840140026; gradient mag: 77.58780647785457\n    Iteration 3200 loss 115.61571805996014; gradient mag: 95.19866681414985\n    Iteration 3300 loss 115.05620929057372; gradient mag: 22.25356002110862\n    Iteration 3400 loss 115.50345899273543; gradient mag: 36.076944424344596\n    Iteration 3500 loss 115.2861768373098; gradient mag: 24.955554245176916\n    Iteration 3600 loss 115.52612641582529; gradient mag: 59.64489099450306\n    Iteration 3700 loss 116.57843218154721; gradient mag: 89.404033046026\n    Iteration 3800 loss 115.67529838517288; gradient mag: 32.492777490074424\n    Iteration 3900 loss 115.9912330539861; gradient mag: 45.550361717560875\n    Iteration 4000 loss 115.80300185364908; gradient mag: 46.245648440677705\n    Iteration 4100 loss 116.91850502717642; gradient mag: 63.979245378784995\n    Iteration 4200 loss 115.82666139433685; gradient mag: 48.501943760083\n    Iteration 4300 loss 115.6552257701036; gradient mag: 26.604118937835505\n    Iteration 4400 loss 116.15186194727862; gradient mag: 23.515738108598452\n    Iteration 4500 loss 115.59075346242554; gradient mag: 38.68700094469305\n    Iteration 4600 loss 115.67313453502499; gradient mag: 31.22462415497083\n    Iteration 4700 loss 115.72705634513721; gradient mag: 39.718306036448965\n    Iteration 4800 loss 116.06789134990586; gradient mag: 50.41002022852906\n    Iteration 4900 loss 116.13192959029054; gradient mag: 67.65626491563455\n    Iteration 5000 loss 115.58436638540365; gradient mag: 44.813764350757616\n    Iteration 5100 loss 115.63328839604151; gradient mag: 27.565988427466483\n    Iteration 5200 loss 116.15790468917479; gradient mag: 104.15159407497814\n    Iteration 5300 loss 115.59145842192183; gradient mag: 59.64713504056005\n    Iteration 5400 loss 116.93431725946803; gradient mag: 44.736530092899564\n    Iteration 5500 loss 115.48684687798193; gradient mag: 25.5259003789723\n    Iteration 5600 loss 116.68439083527892; gradient mag: 44.831331768243366\n    Iteration 5700 loss 115.78060946637851; gradient mag: 23.54807552038094\n    Iteration 5800 loss 116.37934467440888; gradient mag: 29.173858827434074\n    Iteration 5900 loss 116.20271464908114; gradient mag: 32.77833722111663\n    Iteration 6000 loss 115.65312801562118; gradient mag: 47.15335927387926\n    Iteration 6100 loss 115.54865911210807; gradient mag: 21.404486539251266\n    Iteration 6200 loss 115.60927010045091; gradient mag: 31.085915411207544\n    Iteration 6300 loss 115.34583941944757; gradient mag: 11.024852039235533\n    Iteration 6400 loss 116.37650738673737; gradient mag: 47.22939459116579\n    Iteration 6500 loss 115.45940714907957; gradient mag: 37.99684165347926\n    Iteration 6600 loss 115.60919103732866; gradient mag: 11.803625265161315\n    Iteration 6700 loss 115.98878896475307; gradient mag: 27.57179141670264\n    Iteration 6800 loss 115.7846903450478; gradient mag: 42.899146894050325\n    Iteration 6900 loss 115.59213480380686; gradient mag: 35.4495264850065\n    Iteration 7000 loss 115.61089669222098; gradient mag: 13.324934139410143\n    Iteration 7100 loss 115.45474172233817; gradient mag: 30.017475406598603\n    Iteration 7200 loss 115.49540157893678; gradient mag: 29.257253381652742\n    Iteration 7300 loss 115.87300657332051; gradient mag: 46.13764239692355\n    Iteration 7400 loss 115.98755890176; gradient mag: 24.11051966488926\n    Iteration 7500 loss 115.49355713928632; gradient mag: 25.97645471712907\n    Iteration 7600 loss 116.13648391107107; gradient mag: 69.92319406734259\n    Iteration 7700 loss 115.67862963790876; gradient mag: 57.303240930348935\n    Iteration 7800 loss 115.46832017678271; gradient mag: 32.72998156676344\n    Iteration 7900 loss 115.3775647570325; gradient mag: 14.943270936634057\n    Iteration 8000 loss 115.3700564295766; gradient mag: 34.35641242588267\n    Iteration 8100 loss 115.3309502141512; gradient mag: 35.48343475805937\n    Iteration 8200 loss 115.44794510644446; gradient mag: 17.91634068939907\n    Iteration 8300 loss 115.6279858745691; gradient mag: 47.92416763587796\n    Iteration 8400 loss 115.55960247069386; gradient mag: 30.63755118300155\n    Iteration 8500 loss 116.1399340523206; gradient mag: 7.006773796410673\n    Iteration 8600 loss 117.01494918190298; gradient mag: 122.18281440836844\n    Iteration 8700 loss 115.57089477188222; gradient mag: 46.90929245225499\n    Iteration 8800 loss 115.94095994770447; gradient mag: 96.05472535297501\n    Iteration 8900 loss 115.45358053887401; gradient mag: 28.991186627807082\n    Iteration 9000 loss 115.62708973946414; gradient mag: 35.69194370730332\n    Iteration 9100 loss 115.80105890457622; gradient mag: 108.61977706551056\n    Iteration 9200 loss 115.92062110727082; gradient mag: 19.777609904875014\n    Iteration 9300 loss 115.28924931211087; gradient mag: 21.12235069120296\n    Iteration 9400 loss 115.30216399393183; gradient mag: 24.580714161201314\n    Iteration 9500 loss 115.352592795158; gradient mag: 26.317048570467822\n    Iteration 9600 loss 115.78437958232735; gradient mag: 27.25622865339623\n    Iteration 9700 loss 116.25129209753939; gradient mag: 41.06747792090057\n    Iteration 9800 loss 115.98091798586464; gradient mag: 67.74694955082138\n    Iteration 9900 loss 115.57883974403673; gradient mag: 10.453192471538145\n    \n    ===== NLM (REG=100) =====\n    Iteration 0 loss 4325.222942431408; gradient mag: 9948.823725989889\n    Iteration 100 loss 80.59520372650265; gradient mag: 53.04492859233226\n    Iteration 200 loss 65.54409722081951; gradient mag: 12.84123519669067\n    Iteration 300 loss 60.09874134867865; gradient mag: 6.3056742557806436\n    Iteration 400 loss 56.564190308287955; gradient mag: 22.660029577741494\n    Iteration 500 loss 53.69859285400721; gradient mag: 38.37100957658609\n    Iteration 600 loss 51.232664224493604; gradient mag: 10.380872041830344\n    Iteration 700 loss 48.90579891243917; gradient mag: 10.227625754609983\n    Iteration 800 loss 46.732409859948135; gradient mag: 6.839028275169824\n    Iteration 900 loss 44.726513387116256; gradient mag: 7.727855966593614\n    Iteration 1000 loss 42.857887845476384; gradient mag: 6.4853088289464145\n    Iteration 1100 loss 41.19697625332168; gradient mag: 3.270606865141315\n    Iteration 1200 loss 39.58361066755701; gradient mag: 6.424394659847555\n    Iteration 1300 loss 38.05762572356096; gradient mag: 3.5347107350944444\n    Iteration 1400 loss 36.62972478426059; gradient mag: 7.668911002191614\n    Iteration 1500 loss 35.27805270763528; gradient mag: 7.748186677665106\n    Iteration 1600 loss 34.00811996886134; gradient mag: 25.21778275264652\n    Iteration 1700 loss 32.7778562567713; gradient mag: 9.218166607886163\n    Iteration 1800 loss 31.654377102942906; gradient mag: 20.564740675631278\n    Iteration 1900 loss 30.561668034345242; gradient mag: 14.972093830554439\n    Iteration 2000 loss 29.566552416242917; gradient mag: 25.434238364284887\n    Iteration 2100 loss 28.588267385436637; gradient mag: 20.804990058107723\n    Iteration 2200 loss 27.66821979688653; gradient mag: 15.054634455222592\n    Iteration 2300 loss 26.803707000317132; gradient mag: 8.547207465930642\n    Iteration 2400 loss 26.105969990229482; gradient mag: 45.380390351443765\n    Iteration 2500 loss 25.22156217366177; gradient mag: 7.417738210186161\n    Iteration 2600 loss 24.505844699368105; gradient mag: 12.347799884019674\n    Iteration 2700 loss 23.815977888041516; gradient mag: 9.550857415800111\n    Iteration 2800 loss 23.18245512442622; gradient mag: 13.737362785154874\n    Iteration 2900 loss 22.626954672462418; gradient mag: 30.940631781820677\n    Iteration 3000 loss 22.064822171016885; gradient mag: 34.404058070315145\n    Iteration 3100 loss 21.46223525808792; gradient mag: 8.391498766189924\n    Iteration 3200 loss 20.980432698724186; gradient mag: 22.482702867795037\n    Iteration 3300 loss 20.4835866011745; gradient mag: 15.879055626791653\n    Iteration 3400 loss 20.02068232753516; gradient mag: 7.078060467985345\n    Iteration 3500 loss 19.607768863468888; gradient mag: 6.432024184319297\n    Iteration 3600 loss 19.209934940076835; gradient mag: 2.944516250824781\n    Iteration 3700 loss 18.856634495236648; gradient mag: 14.146385953646972\n    Iteration 3800 loss 18.50005355874545; gradient mag: 7.8988912665136155\n    Iteration 3900 loss 18.184866250997587; gradient mag: 8.73724657774567\n    Iteration 4000 loss 17.883615166285963; gradient mag: 10.899100397350308\n    Iteration 4100 loss 17.596218826310874; gradient mag: 6.5961796366231775\n    Iteration 4200 loss 17.343119159896407; gradient mag: 12.4355974191316\n    Iteration 4300 loss 17.096794038732188; gradient mag: 8.756349124876534\n    Iteration 4400 loss 16.890155834061265; gradient mag: 18.395245246722702\n    Iteration 4500 loss 16.658065700222092; gradient mag: 6.857565111403978\n    Iteration 4600 loss 16.487685574730726; gradient mag: 16.263447683665003\n    Iteration 4700 loss 16.367823619551274; gradient mag: 28.072042405247295\n    Iteration 4800 loss 16.137997326781246; gradient mag: 13.140199634178893\n    Iteration 4900 loss 15.984840426702053; gradient mag: 9.764722593643526\n    Iteration 5000 loss 15.83835890805064; gradient mag: 8.582581472944502\n    Iteration 5100 loss 15.712623876047083; gradient mag: 7.443138915604146\n    Iteration 5200 loss 15.59655935930098; gradient mag: 8.831096329679612\n    Iteration 5300 loss 15.49829908080531; gradient mag: 12.545086317942294\n    Iteration 5400 loss 15.410317710087144; gradient mag: 14.568397279687225\n    Iteration 5500 loss 15.327584446924003; gradient mag: 17.453620876447108\n    Iteration 5600 loss 15.250653825786468; gradient mag: 16.68601257738771\n    Iteration 5700 loss 15.14231477986944; gradient mag: 1.5385859749936608\n    Iteration 5800 loss 15.098708417649231; gradient mag: 12.419690023563131\n    Iteration 5900 loss 15.036895041258628; gradient mag: 9.568588147368967\n    Iteration 6000 loss 15.01040143021244; gradient mag: 17.6116561949521\n    Iteration 6100 loss 14.922741655886687; gradient mag: 4.068304422776542\n    Iteration 6200 loss 14.878224548466461; gradient mag: 4.660779518178315\n    Iteration 6300 loss 14.854778900596799; gradient mag: 11.786584648979844\n    Iteration 6400 loss 14.807639901792168; gradient mag: 6.069019421303936\n    Iteration 6500 loss 14.782459210621983; gradient mag: 8.631298115627741\n    Iteration 6600 loss 14.748487204342291; gradient mag: 5.788638068425703\n    Iteration 6700 loss 14.733060584595005; gradient mag: 11.858586565841357\n    Iteration 6800 loss 14.714651323662602; gradient mag: 12.448571610082302\n    Iteration 6900 loss 14.804004259244916; gradient mag: 32.18277736098213\n    Iteration 7000 loss 14.692932284576422; gradient mag: 14.712365155481569\n    Iteration 7100 loss 14.64634343364904; gradient mag: 4.81514985959264\n    Iteration 7200 loss 14.645132803616853; gradient mag: 11.104266397071694\n    Iteration 7300 loss 14.629449802807832; gradient mag: 11.441593905348983\n    Iteration 7400 loss 14.666549857276951; gradient mag: 22.07626094065605\n    Iteration 7500 loss 14.633260872147137; gradient mag: 17.64630701271445\n    Iteration 7600 loss 14.589196852933235; gradient mag: 2.233590958780661\n    Iteration 7700 loss 14.598544460828524; gradient mag: 12.209540804157022\n    Iteration 7800 loss 14.601552082883217; gradient mag: 15.087867936187786\n    Iteration 7900 loss 14.621724361591802; gradient mag: 19.625024602445222\n    Iteration 8000 loss 14.597669321601083; gradient mag: 16.787074089787417\n    Iteration 8100 loss 14.649431613243102; gradient mag: 27.61769284259106\n    Iteration 8200 loss 14.565854769475287; gradient mag: 11.758940950943154\n    Iteration 8300 loss 14.574402251630575; gradient mag: 14.771224624639027\n    Iteration 8400 loss 14.592788425130308; gradient mag: 19.76149336594657\n    Iteration 8500 loss 14.546714910478137; gradient mag: 6.127499287784445\n    Iteration 8600 loss 14.542974139532525; gradient mag: 4.784332576402122\n    Iteration 8700 loss 14.562445575403064; gradient mag: 13.91824986820307\n    Iteration 8800 loss 14.539049510454994; gradient mag: 6.64267943492321\n    Iteration 8900 loss 14.555201636270583; gradient mag: 13.408357110016679\n    Iteration 9000 loss 14.560715214416136; gradient mag: 15.866897204036693\n    Iteration 9100 loss 14.590512211489006; gradient mag: 21.875571515329526\n    Iteration 9200 loss 14.64739218789598; gradient mag: 30.934409158383527\n    Iteration 9300 loss 14.56152579559648; gradient mag: 19.797266313858742\n    Iteration 9400 loss 14.535509164319182; gradient mag: 10.110558432212088\n    Iteration 9500 loss 14.597148379702181; gradient mag: 24.473586380684107\n    Iteration 9600 loss 14.526937652050405; gradient mag: 8.17360315353755\n    Iteration 9700 loss 14.515742625052196; gradient mag: 3.0166819353918544\n    Iteration 9800 loss 14.524542447610273; gradient mag: 8.410229021763973\n    Iteration 9900 loss 14.596308120509496; gradient mag: 25.60110438785662\n    \n    ===== LUNA (REG=100) =====\n    Iteration 0 loss 9442.904624482939; gradient mag: 5598.172231852503\n    Iteration 100 loss 275.52901142569544; gradient mag: 77.7439648417684\n    Iteration 200 loss 216.3980035649895; gradient mag: 59.05996446918714\n    Iteration 300 loss 200.7291455162682; gradient mag: 83.19108057358831\n    Iteration 400 loss 192.45285113343806; gradient mag: 27.090407752718946\n    Iteration 500 loss 189.1845104606657; gradient mag: 52.92125119231678\n    Iteration 600 loss 184.43839295627254; gradient mag: 68.81363567517786\n    Iteration 700 loss 181.07488843594584; gradient mag: 32.71526129406701\n    Iteration 800 loss 177.455614399764; gradient mag: 27.75955753344176\n    Iteration 900 loss 175.6867517183963; gradient mag: 33.195116914421256\n    Iteration 1000 loss 172.6462642151742; gradient mag: 32.346397004636756\n    Iteration 1100 loss 169.44195108622944; gradient mag: 90.31028327506846\n    Iteration 1200 loss 166.85450194368366; gradient mag: 72.18149723379084\n    Iteration 1300 loss 164.81530085171272; gradient mag: 73.11564239722499\n    Iteration 1400 loss 162.50536985774704; gradient mag: 27.443906864604738\n    Iteration 1500 loss 160.02720554765162; gradient mag: 37.67738162152859\n    Iteration 1600 loss 158.29201739279517; gradient mag: 47.212375914611904\n    Iteration 1700 loss 155.5784321312354; gradient mag: 98.44081519521762\n    Iteration 1800 loss 153.96384000972785; gradient mag: 33.110697209799284\n    Iteration 1900 loss 152.35943149117492; gradient mag: 22.486074060469672\n    Iteration 2000 loss 148.56437158842692; gradient mag: 87.2498212131538\n    Iteration 2100 loss 147.7119180531327; gradient mag: 23.69500404442306\n    Iteration 2200 loss 146.40319765618523; gradient mag: 55.38805561521368\n    Iteration 2300 loss 146.41334003328762; gradient mag: 22.65831664783938\n    Iteration 2400 loss 142.4171412120089; gradient mag: 39.76384724190604\n    Iteration 2500 loss 141.6084655759699; gradient mag: 56.33456826114398\n    Iteration 2600 loss 138.39489625765958; gradient mag: 33.05153810808339\n    Iteration 2700 loss 137.65467439180566; gradient mag: 37.99328722802308\n    Iteration 2800 loss 136.68402344879223; gradient mag: 27.85683729375714\n    Iteration 2900 loss 135.55818038034; gradient mag: 20.341410186460873\n    Iteration 3000 loss 134.43502167334483; gradient mag: 28.50024728072917\n    Iteration 3100 loss 133.6414155821331; gradient mag: 110.46416932201784\n    Iteration 3200 loss 133.32987278732514; gradient mag: 36.866876222536284\n    Iteration 3300 loss 132.37832074397377; gradient mag: 69.85258942427018\n    Iteration 3400 loss 133.34553474439605; gradient mag: 48.887788579306296\n    Iteration 3500 loss 131.45477999046233; gradient mag: 139.59043409578717\n    Iteration 3600 loss 131.5114837601041; gradient mag: 74.8829491663871\n    Iteration 3700 loss 132.89291039371557; gradient mag: 36.80113914858061\n    Iteration 3800 loss 130.57612485446722; gradient mag: 8.38736883655153\n    Iteration 3900 loss 130.90524171274535; gradient mag: 5.440654614077319\n    Iteration 4000 loss 129.94863489506113; gradient mag: 26.99533818327843\n    Iteration 4100 loss 127.9751658820471; gradient mag: 89.44022937989406\n    Iteration 4200 loss 128.2049522310574; gradient mag: 6.018305678048377\n    Iteration 4300 loss 127.45928512368388; gradient mag: 31.598663938746622\n    Iteration 4400 loss 126.39072914725261; gradient mag: 8.305296307029101\n    Iteration 4500 loss 126.27056369447823; gradient mag: 24.463666173025047\n    Iteration 4600 loss 125.60720016094598; gradient mag: 8.11325655310735\n    Iteration 4700 loss 128.21782008343115; gradient mag: 32.45591387572219\n    Iteration 4800 loss 125.17733538177453; gradient mag: 8.08005635283857\n    Iteration 4900 loss 124.98990540166358; gradient mag: 14.26782565606797\n    Iteration 5000 loss 125.33696648424916; gradient mag: 25.413989490914805\n    Iteration 5100 loss 124.51507067314482; gradient mag: 65.30789161301672\n    Iteration 5200 loss 125.07656703905876; gradient mag: 12.042129892959267\n    Iteration 5300 loss 124.22733342372717; gradient mag: 16.60800829656219\n    Iteration 5400 loss 124.3887028905702; gradient mag: 13.320760553929087\n    Iteration 5500 loss 123.65021184369708; gradient mag: 7.217347849358018\n    Iteration 5600 loss 123.58850479218252; gradient mag: 25.355676685524006\n    Iteration 5700 loss 124.09944565885525; gradient mag: 7.454791179553466\n    Iteration 5800 loss 123.70070355648235; gradient mag: 42.928149038203884\n    Iteration 5900 loss 123.57776296552771; gradient mag: 19.48598518685359\n    Iteration 6000 loss 122.99185627898504; gradient mag: 15.163187773492254\n    Iteration 6100 loss 122.82990537507646; gradient mag: 10.156947018919537\n    Iteration 6200 loss 122.64900379505778; gradient mag: 12.44341417182814\n    Iteration 6300 loss 123.4275275819816; gradient mag: 8.766921823787456\n    Iteration 6400 loss 122.85506076763986; gradient mag: 8.62867499954128\n    Iteration 6500 loss 122.58168054466657; gradient mag: 41.67721935144293\n    Iteration 6600 loss 122.80463653724408; gradient mag: 34.02823090606654\n    Iteration 6700 loss 122.38860191701735; gradient mag: 151.67488601503618\n    Iteration 6800 loss 122.50543463738336; gradient mag: 6.70474596992395\n    Iteration 6900 loss 122.38295317969741; gradient mag: 73.86582231277264\n    Iteration 7000 loss 123.01101550059805; gradient mag: 38.36000413949006\n    Iteration 7100 loss 122.62677567933562; gradient mag: 17.851663153870692\n    Iteration 7200 loss 122.29142545907898; gradient mag: 25.09732170012856\n    Iteration 7300 loss 122.2254994095031; gradient mag: 7.659812062946849\n    Iteration 7400 loss 122.06235972408022; gradient mag: 11.181278192398887\n    Iteration 7500 loss 121.97882027157196; gradient mag: 19.057595263152788\n    Iteration 7600 loss 122.66626057271641; gradient mag: 16.048470226645563\n    Iteration 7700 loss 122.72518609379992; gradient mag: 5.118208143340186\n    Iteration 7800 loss 122.23659571550402; gradient mag: 14.673367042043681\n    Iteration 7900 loss 122.62470297751369; gradient mag: 8.414017072126368\n    Iteration 8000 loss 122.02238500600158; gradient mag: 15.528552117473009\n    Iteration 8100 loss 122.03692836915192; gradient mag: 11.41434381899551\n    Iteration 8200 loss 122.25539455748226; gradient mag: 8.18658952832159\n    Iteration 8300 loss 122.12014319198478; gradient mag: 9.821204981293734\n    Iteration 8400 loss 122.14075412114855; gradient mag: 21.08393940122645\n    Iteration 8500 loss 121.93763462453441; gradient mag: 5.816564916048127\n    Iteration 8600 loss 131.61869234664118; gradient mag: 25.771704117752588\n    Iteration 8700 loss 130.72972266525548; gradient mag: 9.812853258896364\n    Iteration 8800 loss 130.44117088138876; gradient mag: 11.548898430060403\n    Iteration 8900 loss 130.290281686268; gradient mag: 5.662841139081789\n    Iteration 9000 loss 130.15640788183677; gradient mag: 5.967714288591184\n    Iteration 9100 loss 130.15120452579234; gradient mag: 16.079695344698347\n    Iteration 9200 loss 130.11123391290454; gradient mag: 16.370867561178795\n    Iteration 9300 loss 129.953629265016; gradient mag: 7.9566128805030525\n    Iteration 9400 loss 130.2817096694045; gradient mag: 20.81959606743812\n    Iteration 9500 loss 129.83277470937807; gradient mag: 13.041606907871033\n    Iteration 9600 loss 129.74785601778612; gradient mag: 3.720224437253016\n    Iteration 9700 loss 129.7436525382572; gradient mag: 5.824613223819308\n    Iteration 9800 loss 129.7001341985548; gradient mag: 10.308812422753094\n    Iteration 9900 loss 129.6892147010121; gradient mag: 15.344170428480414\n\n\nLet's visualize the prior samples:\n\n\n```python\nmod_list = nlm_list + luna_list\n\nfig, axs = plt.subplots(2, 2, figsize = (15, 12))\nfor i, ax in enumerate(axs.ravel()):\n    mod = mod_list[i]\n    y_prior = mod.get_prior_preds(x_test, w_prior_mean=0, w_prior_cov=prior_var, noise_var=noise_var)\n    ax.scatter(x,y, color='red', alpha=0.5, label='Observed Data')\n    ax.plot(x_test[0,:], y_test[0,:], color='black', label='Ground Truth')\n    ax.plot(x_test[0,:], y_prior.T, color='tab:blue', alpha=0.1)\n    ax.set_ylim([-150, 150])\n    ax.set_title(f'{mod.modtype} (REG = {mod.reg})', fontsize=15)\nhandles, labels = ax.get_legend_handles_labels()\nfig.legend(handles, labels, loc='lower center', ncol=2, fontsize=15, markerscale=2)\nplt.suptitle(\"NLM Regularization Prior Comparison\", fontsize=25)\nplt.show()\n```\n\nIn the plots above, we recreated the example given in the paper showing that NLMs with no regularization can produce expressive prior samples but regularization results in far less expressive prior samples, particularly in the data-scare region of the gap. In contrast, we can observe that regularization in LUNA does not adversely affect its expressiveness in the prior samples.\n\n*Note that in our implementation, we normalized each term in the loss function: log likelihood was normalized by the number of datapoints times the number of auxiliary functions, regularization was normalized by the number of neural network weights, and cosine similarity was normalized by the number of pairs of auxiliary functions x the number of datapoints. This normalization may make the magnitude of the hyperparameters different from the examples in the original paper, but we found the normalization useful to compare effects of hyperparameters across different experiments involving chnages in architecture, auxiliary functions and dataset size.*\n\nNow, let's take a look at the posterior predictive:\n\n\n```python\nmod_list = nlm_list + luna_list\nlls_train = []\nlls_test = []\n\nfig, axs = plt.subplots(2, 2, figsize = (15, 12))\nfor i, ax in enumerate(axs.ravel()):\n    mod = mod_list[i]\n\n    # Calculate Posteriors\n    y_posterior = mod.get_posterior_preds(x_test, x_obs=x, y_obs=y, w_prior_cov=prior_var, noise_var=noise_var, n_models = 5000)\n    y_posterior = y_posterior + np.random.normal(0, noise_var**0.5, size=y_posterior.shape)\n    posterior_predictive_train = mod.get_posterior_preds(x, x_obs=x, y_obs=y, w_prior_cov=prior_var, noise_var=noise_var)\n    posterior_predictive_train = posterior_predictive_train + np.random.normal(0, noise_var**0.5, size=posterior_predictive_train.shape)\n    posterior_predictive_non_gap = mod.get_posterior_preds(x_test_non_gap, x_obs=x, y_obs=y, w_prior_cov=prior_var, noise_var=noise_var)\n    posterior_predictive_non_gap = posterior_predictive_non_gap + np.random.normal(0, noise_var**0.5, size=posterior_predictive_non_gap.shape)\n\n    # Calculate Log-Likelihoods\n    lls_train.append(neg_log_likelihood(posterior_predictive_train, y, noise_var) * -1)\n    lls_test.append(neg_log_likelihood(posterior_predictive_non_gap, y_test_non_gap, noise_var) * -1)\n\n    # Calculating Percentiles\n    pp_upper = np.percentile(y_posterior, 97.5, axis=0)\n    pp_lower = np.percentile(y_posterior, 2.5, axis=0)\n    pp_upper2 = np.percentile(y_posterior, 84, axis=0)\n    pp_lower2 = np.percentile(y_posterior, 16, axis=0)\n    pp_upper3 = np.percentile(y_posterior, 99.85, axis=0)\n    pp_lower3 = np.percentile(y_posterior, 0.15, axis=0)\n    pp_mean = np.mean(y_posterior, axis=0)\n\n    # Visualizing 68%/95%/99.7% posterior predictive interval of Bayesian polynomial regression\n    ax.scatter(x[0,:], y[0,:], color='red', alpha=0.3, label='Observed Data')\n    ax.plot(x_test[0,:], y_test[0,:], color='orange', label=\"Ground Truth\")\n    ax.plot(x_test[0,:], pp_mean, color='tab:blue', alpha=0.9, label='Posterior Predictive Mean')\n    ax.fill_between(x_test[0,:], pp_upper2, pp_lower2, color = 'tab:blue', alpha = 0.3, label=\"68% Predictive Interval\")\n    ax.fill_between(x_test[0,:], pp_upper, pp_lower, color='tab:blue', alpha=0.2, label=\"95% Predictive Interval\")\n    ax.fill_between(x_test[0,:], pp_upper3, pp_lower3, color = 'tab:blue', alpha = 0.1, label=\"99.7% Predictive Interval\")\n    ax.set_ylim([-150, 150])\n    ax.set_title(\"{:} (REG = {:.0f})\\n LL: train = {:.2f}, test = {:.2f}\".format(mod.modtype, mod.reg, lls_train[i], lls_test[i]), fontsize=15)\n\nhandles, labels = ax.get_legend_handles_labels()\nfig.legend(handles, labels, loc='lower center', ncol=3, fontsize=15, markerscale=2)\nplt.suptitle(\"Posterior Predictive under Regularization: NLM vs LUNA\", fontsize=25)\nplt.show()\n```\n\nWe observe that the NLM with no regularization is able to express the desired uncertainty in the data-scare region but that the NLM with regularization expresses insufficient uncertainty in the data-scare region. Again, this contrasts with LUNA, where regularization does not \"collapse\" the uncertainty in the data-scare region.\n\nThe log likelihood values of the models demonstrate that log likehiood cannot be used as a measure of the quality of the uncertainty in this gap region. In other words, a lower (or higher) log likehiood does not automatically indicate a better quality of epistemic uncertainty.\n\n## 7. Experiments <a class=\"anchor\" id=\"chapter7\"></a>\n\n### 7.1 Comparison of Methods: 1-D Cubic Gap <a class=\"anchor\" id=\"section_7_1\"></a>\n\nAs in the paper, we ran various baseline models and LUNA on the 1-D cubic gap toy dataset. You can see the full experiment along with architecture and hyperparmeter choices [here](https://github.com/weyesians/luna-passa/blob/main/notebooks/comparison_of_methods.ipynb).\n\n\n\nAs expected, the gold standards of BNN and GP produced the best epistemic uncertainty behavior in the gap region. Meanwhile, MAP was unable to produce any espistemic uncertainty in either data-scare or data-rich regions. Our ensemble bootstrap and NLM produced somewhat higher epistemic uncertainty in the gap region compared to the data-rich region, but such uncertainty was severly underestimated compared to BNN and GP. Finally, while LUNA was not able to perform as well as BNN and GP, it did produce the closest uncertainty behavior to the gold standard methods. \n\nWe also timed each of the methods to showcase the need for LUNA in place of the gold standard models. \n\n\n\nThis comparison is not perfectly generalizable for real world data which has much higher dimensions and more data points. Particularly, GPs have a cubic time complexity (O($n^3$) depending on the number of data points $n$. Thus, while it ran in less than our second for our toy data, it is actually expected to scale far worse than the other methods. Despite this, we still found the other runtimes to be illustrative. The BNN model took almost twice as long to run as LUNA. Meanwhile, LUNA ran in comparable time to NLM. \n\n### 7.2 Exploring NLM Behavior <a class=\"anchor\" id=\"section_7_2\"></a>\n\nYou can find the following NLM experiments [here](https://github.com/weyesians/luna-passa/blob/main/notebooks/experiment_NLM.ipynb).\n\n#### **7.2.1 How does regularization affect NLM uncertainty in data-scare regions?** <a class=\"anchor\" id=\"section_7_2_1\"></a>\n\nOur first experiment investigates at which regularization level our good uncertainty beahvior \"collapses\": that is, when the uncertainty in the data-scare region is mimics the uncertainty in the data-rich region.\n\nBecause our regularization is normalized by the number of data points, our regularization parameters are on a larger scale than that of the paper. For this reason, we first tested parameters between 0 and 1000.\n\n\n\nAs seen in the graph above, uncertainty in the gap region collapses somewhere between regularization = 10 and regularization = 100.\n\n\n\nUpon further inspection, this appears to happen after regularization = 50. \n\nHowever, we need to remember that NLM does not give us consistent uncertainty behavior in the gap region. This brings us to our next experiment. \n\n#### **7.2.2 How consistent is good uncertainty behavior in data-scare regions for NLMs?** <a class=\"anchor\" id=\"section_7_2_2\"></a>\n\nIn our extended experiments, we noticed that our NLMs were performing much more consistently than expected from the paper findings. In particular, NLMs with no regularization were always giving greater uncertainty in the data-scare region than in the data-poor region. As regularization went up, this behavior became more and more inconsistent. \n\nWe can explain the departure from the paper results from the fact that we are using a prior variance of 9 while the paper used a prior variance of 1. \n\n\n\nWe see that prior variance greatly affects the uncertainty behavior in the data-scare region. The paper claims that NLM inconsistently gives good uncertainty behavior, but this might be only true for lower prior variances. Thus, LUNA might be more suitable than NLMs in cases where we want our prior variance to be small. A hypothesis to test in future work is whether or not NLMs in scenarios with larger prior variances are sufficient for good uncertainty behavior in data-scare regions. \n\n### 7.3 Exploring LUNA Behavior <a class=\"anchor\" id=\"section_7_3\"></a>\n\n#### **7.3.1 How does LUNA\u2019s behavior relate to regularization and diversification strengths?** <a class=\"anchor\" id=\"section_7_3_1\"></a>\n\nWe implemented LUNA and tested it on the 1-D the cubic gap dataset. We used a 2-layer MLE with 50 units per layer and 30 auxiliary functions. For Bayesian linear regression, both prior variance and noise variance were set at 9. To study the behavior of LUNA, we performed a grid search on regularization ($Reg = \\left \\{ 0, 10, 30, 100, 300, 1000, 3000 \\right \\}$) and diversitifcation ($Div = \\left \\{ 0, 10, 100, 1000, 10000 \\right \\}$). We minimized the LUNA loss function with Adam optimizor (step size =  $10^{\u22122}$, 5000 steps), and compared the results to NLM with the same architecture and regularization and optimization hyperparameters. The details of the experiment can be found [here](https://github.com/weyesians/luna-passa/blob/main/notebooks/LUNA_grid_search_of_regularization_and_diversification_demo.ipynb).\n\nFirst we inpected the behavior of the auxiliary functions, visualized below:\n\n\n\nWe observed two trends:\n\n1. With a fixed diviersification value, we can see that auxiliary functions appeared to be more diverse with low regularization, whereas higher regularization puhsed all auxiliary functions to be flat with small slopes, as expected by the effect of regularization.\n\n2. With a fixed regularization value (more obvious with smaller regularization), as the diversification value increased, we first observe increased diversity of the auxiliary functions in the gap region, whereas in the data-rich regions, these auxiliary functions still consistently pass through the training points in a homogenous manner, with less diversity. However, as diversification value further increased ($Div \\geq  100$), we started to see the auxiliary function ssplit into two groups. One group still tried to go linearly through the training points, where the other group became horizontal and passed through the mean y value of the training points in that region. This was originally very perplexing, but became sensible after we gave it a second thought since \n   - The $L_{diverse}$ in the LUNA loss function enforced cosine similarity between the gradients of pairs of auxiliary functions at each datapoints to be small (large angles).\n   - The likelihood part of $L_{fit}$ tried to pull the auxiliary functions to be closed to datapoints. Putting the value at mean would make sure square error doesn't blow up.\n   - At the same time, the regularization part of $L_{fit}$ prohibited auxiliary functions to wiggle drastically between training points (this can be a way to create small cosine similarity), so a quasi-linear behavior is enforced.\n   \nThe interplay of these three terms in the $L_{LUNA}$ thus generated this interesting behavior of the auxiliary functions, suggesting that having multiple terms in loss functions for different purposes can lead to complex, sometimes counter-intuitive behavior.\n\nNever the less, the diversity created by the auxiliary functions was able to generate desirable epistemic uncertainty in the posterior predictive. Below we plot the posterior predictive intervals of the results after linear Bayesian regression, for both NLM and LUNA. \n\n\n\n\n\nAs we can see, when we increased the regularization for NLM, the epistemic uncertainty in the gap region collapsed rapidly. But with LUNA, we were able to restore the desirable epistemic uncertainty in the gap region. However, we also observed a trade-off between the epistemic uncertainty in the gap region and model fit (log likelihood) in the data-rich region. When the diversitication value is really high, the posterior samples in the data-rich region become very rigid and stop fitting to the curve. This can be explained by the \"linear\" and \"crossing\" behavior of the auxiliary functions under high diversitfication.\n\nWe evaluated our results by computing the log likelihood on training and non-gap test data, as well as the epistemic uncertainty on the gap test data and non-gap test data. The results are summarized in the plot below. In short, NLM and LUNA with low to intermediate values of diversification showed similarly high test log likelihood for most of the regularization values (except for the highest one), but LUNA significantly boosted the epistemic uncertainty in the gap region.\n\n\n\n\nFinally, we can take a closer look at the prior and posterior samples of NLM and LUNA. We selected the best performing NLM by log likelihood on non-gap test data ($Reg = 300$), and picked a corresponding LUNA with comparable test log likelihood but decent epistemic uncertainty ($Div = 100$). The prior samples for NLM did not seem diverse compared to the ones from LUNA, leading to reduced epistemic uncertainty in the gap region. The prior samples of LUNA appeared to fill the space more evenly and formed diverse bases for Bayesian linear regression that support large epistemic uncetainty in the data-scarce region.\n\n\n\n\n#### **7.3.2 How does LUNA\u2019s behavior relate to the number of auxiliary functions?** <a class=\"anchor\" id=\"section_7_3_2\"></a>\n\nAnother important hyperparameter in LUNA is the number of auxiliary functions. In order to examine how it relates to LUNA\u2019s behavior, we performed another grid-search experiment where we varied diversification strength ($Div = \\left\\{ 0, 10, 100, 1000, 10000 \\right\\}$) and the number of auxiliary functions ($Aux = \\left\\{ 3, 5, 10, 30, 50 \\right\\}$) while fixing regularization strength ($Reg = 600$). Otherwise, the experiment setup was identical to the earlier one. The details of the experiment can be found [here](https://github.com/weyesians/luna-passa/blob/main/notebooks/LUNA_grid_search_of_auxnum_and_diversification.ipynb).\n\nResults suggest that, even with a small number of auxiliary functions, we can obtain considerably large epistemic uncertainty *if* diversification strength is large enough (relative to regularization strength). However, large diversification strength pushes auxiliary functions \u201caway\u201d from one another (to make their gradients orthogonal), which results in poorer fit with the observed data (i.e. lower log likelihood).\n\nIncrease in the number of auxiliary functions seems to ameliorate this tradeoff between model fit and epistemic uncertainty: by increasing the number of auxiliary functions, we can achieve ideal epistemic uncertainty at much *lower* diversification strength, which means less sacrifice of model fit with the observed data. However, LUNA with more auxiliary functions takes longer to train, so there is a different type of tradeoff.\n\n\n\nIn sum, LUNA helps to overcome the \u201ccollapse\u201d of epistemic uncertainty (under regularization) by using a diversified feature basis. This, however, comes at the cost of model fit: greater diversification, although achieving ideal epistemic uncertainty despite regularization, deteriorates the model\u2019s overall fit with the observed data. This can be in turn overcome by using more auxiliary functions at weaker diversification, but it incurs longer training time.\n\n#### **7.3.3 How does LUNA behave with variation in neural network architecture?** <a class=\"anchor\" id=\"section_7_3_3\"></a>\n\nOne aspect of LUNA model design that lacks documentation in the original paper is the impact of architectural variation on the epistemic uncertainty featured in a learned model. The following section considers the impact of this set of design choices on the resultant inference properties. You can find the full suite of experiments [here](https://github.com/weyesians/luna-passa/blob/main/notebooks/LUNA_architecture_plots.ipynb).  \n\nWe begin by taking a base case against which we will compare the results of all our architecture variation. Following successful results with a LUNA training architecture detailed in table below, we conducted additional experimentation by varying the architecture from this case.\n\n| parameter description             | parameter value                      |\n| --------------------------------- | -----------------------------------  |\n| input dimension                   | $ D_{in} =  1$                       |\n| output dimension                   | $ D_{out} =  1$                       |\n| regularization weighting          | $\\mu = 100.0$                        |\n| cosimilarity weighting            | $\\lambda = 100.0$                    | \n| Hidden Layers                     | $\\textrm{depth} = 2$                 |\n| Width (of each hidden layer)      | $\\mathbf{W} = \\{50, 50\\} $           | \n| auxilliary regressors             | $M = 30$                             | \n| maximum iterations                | 5000                                 | \n| activation function               | ReLu                                 | \n| step size                         | 1e-2                                 | \n\nOur inquiry into the effects of architecture on inference properties can be divided into four main categories:\n\n* width (nodes per layer)\n* depth (layers in network)\n* increasing vs. decreasing width\n* width relative to number of auxiliary regressors ($L$ vs.$M$ )\n\n\nThe following subsections address each of these considerations in turn.\n\n**Effect of width on LUNA inference properties**\n\nIn simple terms, increasing the width of the hidden layer components of an NLM/LUNA model adds complexity to the model which we can expect to increase the expressiveness of our posterior predictions at the cost of training runtime. Our foremost concern when it comes to increasing our model width is the dimensionality of our \\textit{last} hidden layer and therefore the dimensionality of feature map $\\Phi_{\\theta}$. Suppose we represent the entirety of the NLM/LUNA model as follows:\n\n\\begin{align}\n    \\underbrace{\\mathbf{X} \\otimes H^{\\omega_1}_{\\theta_1} \\otimes H^{\\omega_2}_{\\theta_2} \\otimes ... \\otimes H^{\\omega_D}_{\\theta_D}}_{\\Phi_{\\theta}} \\otimes \\mathbf{W} = \\mathbf{y}\n\\end{align}\n\n\nwhere $H$ denotes a hidden layer, $D$ denotes the depth of the model, $\\omega$ denotes the width of the relevant hidden layer, and $\\theta$ refers to the set of parameters $\\{ \\theta_1, \\theta_2, ..., \\theta_D \\} $ that parameterise the feature map. The dimensions of the feature map are $N \\times L$, where $N$ denotes number of observations of $\\mathbf{X, y}$ and $L = \\omega_D$ denotes the dimensions of the feature map space. An increase in the width of $H_{\\theta_D}$ has the undesired effect of increasing the dimensionality of the auxiliary regressors $W \\in \\mathbb{R}^{M \\times L}$, and so we can expect training time to increase for a fixed number $M$ auxiliary regressors with an increase in $L$. Despite this, we cannot cast aside the notion of increasing the width of our network, because we fully expect that the expressiveness of our posterior predictions will vary greatly with increase in the width of $H_{\\theta_D}$. Below, we provide the results for the uniform variation in width of a two layer feature mapping from $\\omega_1 = \\omega_2 = \\omega \\in [25, 200]$:\n\n\n\n| plot coordinate | [1, 1]    | [1, 2]    | [2, 1]    | [2, 2]    |   \n| --------------- | --------- | --------- | --------- | --------- |   \n| $\\omega$ | [25, 25] | [50, 50] | [100, 100] | [200, 200] |   \n| runtimes (s) | 94 | 547 | 310 | 924 |   \n| param num | 1480 | 4130 | 13330 | 46630 |   \n| mean epistemic variance | 17.11 | 99.04 | 221.72 |  934.60 | \n\n\n\n\nOverall our plots unsurprisingly show that with increase in width $\\omega$, our epistemic uncertainty in the gap and extremum regions of the support increases in magnitude.\n\n\nWith increase in the width, we observe the emergence of harmonic behavior in the posterior predictions within the gap region. The frequency of the oscillatory behavior seems to increase as $\\omega$ increases, with $\\omega = 50$ appearing to exhibit a single mode waveform. \n\nWe note that $\\omega = 50 $ is our base case, and perhaps it embodies the fundemental frequency of the observed oscillatory behavior because of the specific set of training parameters we have fixed and declared in the table above.\n\n**Effect of depth on LUNA inference properties**\n\nWhile increase in width comes at a cost of training time due to the resultant dimensions of the auxilliary regressors, a viable alternative presents itself by increasing the depth of our neural network, i.e. increasing the value of $D$. If $D$ is sufficiently large so that our posterior predictions are expressive but the last hidden layer $H^{\\omega_D}_{\\theta_D}$ is thin, then $W$ will also be thin. In other words, if we may achieve high posterior predictive diversity using a deep network of thin hidden layers rather than a wide, shallow network, then it stands to reason that our training time will be faster with no loss in inference quality. Below, we give results for neural networks of width 50 with $D \\in [1, 5]$:\n\n\n\n| plot coordinate | [1, 1] | [1, 2] | [2, 1] | [2, 2] | [3, 1] | [3, 2] | \n| ------ | ------ | ------ | ------ | ------ | ------ | ------ | \n| $\\omega$ | [50] | [50, 50] | [50, 50, 50] | [50, 50, 50, 50] | [50, 50, 50, 50, 50] | [25, 25, 25, 25] |       \n| runtimes (s) | 193 | 547 | 188 | 241 | 306 | 510 |  \n| param num | 1630 | 4180 | 6730 | 9280 | 11830 | 2780 |     \nmean epistemic variance | 2.30 | 99.04 | 656.22 | 92548.82 | 124375.41 | 297.48 |\n\nTo no suprise, the increase in model depth has a direct relationship with epistemic uncertainty. We see that for additional hidden layers of width $\\omega = 50$, there is dramatic amplification in the variance of the psoterior predictions in the OOD regions. \n\nWe have also included the results for a 4 layer network of uniform width $\\omega = 25$ to compare to the base case of two layers with width $\\omega = 50$. For the same number of parameters, and indeed lower dimensional auxilliary parameters, the epistemic uncertainty is greater for this thinner, deeper network. \n\nWe note that in general, our deep networks suffer from slower convergence rates. For virtually all of our tested systems trained over 5000 iterations of gradient descent, the ratio of the final loss value to the previous iteration's is roughly 99%. However, for our deepest networks this ratio is closer to 20%. For our deep neural networks, we recommend that a higher training rate should be applied, or a more sophisticated learning schedule must be utilized.\n\n**Effect of increasing vs. decreasing width on LUNA inference properties**\n\nUntil this point, all given results were for neural network architectures of uniform width for all layers. We have found that increase in width adds to training time, but that increase in depth hinders convergence, though both seem to give us control over the behavior of our posterior predictive epistemic uncertainty. In principle, it may not be necessary to have many wide hidden layers when a few hidden layers with width varying appropriately will do the trick. Ultimately, in the interest of efficiency, we are hoping that having a network that diminishes in width will yield good results, since we would like to improve the efficiency of our training regime by pursuing low dimensional auxilliary regressors. Below, we give results for three layer neural networks of various widths:\n\n\n\n| plot coordinate | [1, 1] | [1, 2] | [1, 3] | [2, 1] | [2, 2] | [2, 3] | \n| ------ | ------ | ------ | ------ | ------ | ------ | ------ | \n| $\\omega$ | [25, 50, 100] | [100, 50, 25] | [200, 100, 50] | [100, 100, 25] | [100, 100, 50] | [100, 50, 50] |       \n| runtimes (s) | 803 | 657 | 2012 | 1075 | 1309 | 755 |  \n| param num | 9430 | 7305 | 27080 | 9280 | 16880 | 9330 |  \n| mean epistemic variance | 1459.63 | 1503.49 | 12350.91 | 1649.04 | 1150.29 | 724.09 | \n\nOur hope that thin final hidden layers would also yield desirable inference properties appears to be in vain. The above figures portraying the inference results from variable width three layer neural networks contrast the behavior of \"thinning\" vs. \"widening\" or \"converging\" vs. \"diverging\" architecture schemes. \n\nThe top left plot is our only \"diverging\" network, with architecture $\\{ \\omega_1, \\omega_2, \\omega_3 \\} = \\{25, 50, 100\\}$. While the observed epistemic uncertainty is too high, it is the shape we are concerned with, and overall has a desirable form. \n\nThe subsequent plots are all of \"converging\" networks, and in particular, the middle plot in the top row is a \"mirror\" of the architecture applied for the sole diverging network, with an architecture of $\\{ \\omega_1, \\omega_2, \\omega_3 \\} = \\{ 100, 50, 25 \\}$. Immediately, it becomes clear that where the widening network exhibits generally homogenous distribution of posterior predictions, the thinning architecture has a clearly harmonic in-phase waveform. Thus, the epistemic uncertainty is biased, violating our rule of thumb that epistemic uncertainty should scale with distance from training support. The subsequent plots convey the same defect, though even more concerningly, it becomes clear that the dramatic reduction in hidden layer width with progression through the hidden layers results in non-smooth behavior in the posterior predictions. To see this clearly, the top right and bottom left plots representing architectures $\\{ \\omega_1, \\omega_2, \\omega_3 \\} = \\{ 200, 100, 50 \\}$ and $\\{ \\omega_1, \\omega_2, \\omega_3 \\} = \\{ 100, 100, 50 \\}$, respectively, depict non-smooth predictions as the test points depart from the training support. \n\nWe may conjecture that this observation of non-smoothness is an artifact of information \"compression\" as the observations $\\mathbf{X}$ are projected into progressively lower dimensional spaces with each layer $H_{\\theta}$. This compression of information can be understood as a further and further constrained embedding of the information resulting from the previous layer into a manifold of a lower dimensional subspace, in effect, \"wrinkling\" the topology of the embedding. Hence, the smoothness of the posterior predictions in the covariate space is compromised, as the resultant feature map becomes more and more aligned with its principle eigenmodes for observations packed into a low dimensional embedding. The posterior samples operate on this non-diverse feature map and resultantly yield non-diverse posterior predictions. \n\nIt should be noted that we are not certain if \"converging\" neural networks are used, appropriately or otherwise, in practice. But the above postulation of the information compression possibly stands to be ameliorated if the model is permitted to train beyond 5000 iterations. Though we did not do so out of fairness of comparison, it is an interesting path of further exploration.\n\n**Effect of width vs. number of auxilliary regressors on LUNA inference properties**\n\nThere remains one intriguing question with regards to the architecture of our NLM/LUNA networks, and that is \"is there a relationship between the relative values of $L$ and $M$?\" In other words, does the dimensionality $L$ of the output layer $W$ and the number of auxilliary regressors $M$ have an impact on the inference properties of our posterior predictions? One may imagine a \"bottleneck\"-like scenario, where the number of auxilliary regressors may be rendered insignificant if the $L$ is sufficiently small or large, and ultimately the tuning of posterior predictive diversity may be wholly dictated by the network architecture. Recall that throughout architecture experimentation, we have held the number of auxilliary regressors to be $M = 30$. We now seek to determine the effect of the width of the final hidden layer $L = \\omega_D$ for a two layer LUNA trained NLM model by carefully varying the feature map dimension such that $L = \\omega_2 \\in [10, 100]$. The plots below detail our investigation: \n\n\n\n| plot coordinate | [1, 1] | [1, 2] | [1, 3] | [2, 1] | [2, 2] | [2, 3] | [3, 1] | [3, 2] | [3, 3] | [4, 1] | [4, 2] | [4, 3] | [5, 1] | [5, 2] | [5, 3] |  [6, 1] | [6, 2] | [6, 3] |  \n| ------ | ------ | ------ | ------ | ------ | ------ | ------ | ------ | ------ | ------ | ------ | ------ | ------ | ------ | ------ | ------ | ------ | ------ | ------ | \n| $\\omega$ | [20, 10] | [30, 10] | [50, 10] | [20, 20] | [30, 20] | [50, 20] | [20, 30] | [30, 30] | [50, 30] | [20, 40] | [30, 40] | [50, 40] | [20, 50] | [30, 50] | [50, 50] | [20, 100] | [30, 100] | [50, 100] |\n| runtimes (s) | 51 | 53 | 78 | 70 | 78 | 101 | 92 | 101 | 122 | 123 | 144 | 146 | 132 | 126 | 547 | 201 | 217 | 219 | \n| param num | 580 | 700 | 940 | 1090 | 1310 | 1750 | 1600 | 1920 | 2560 | 2110 | 2530 | 3370 | 2620 | 3140 | 4180 | 5170 | 6190 | 8230 |\n| mean epistemic variance | 2.25 | 0.57 | 1.03 | 11.18 | 83.29 | 4.39 | 18.12 | 19.09 | 5.29 | 44.85 | 31.05 | 54.18 | 6.19 | 32.05 | 99.04 | 17.16 | 63.69 | 39.844 | \n\n\nIt is difficult to extract patterns from the above plots. On one hand, it is clear that when $\\omega_2 = L = 10$, all cases of input layer width $\\omega_1 = \\{ 20, 30, 50\\} $ result in very poor posterior predictive epistemic uncertainty. Similarly, it generally appears that increasing $L$ results in improved epistemic variance. But the associated $\\omega_2$ value for each input layer's maximum epistemic uncertainty appears to vary, with $\\omega_1 = 20$ having maximum epistemic uncertainty at $\\omega_2 = 40$, $\\omega_1 = 30$ attaining a comparable, albeit non-smooth, maximum at $\\omega_2 = 20$, and $\\omega_1 = 50$ reaching its maximum epistemic uncertainty at $\\omega_2 = 50$, the base case. We see again the information compression phenomenon very clearly in the case of $\\{ \\omega_1, \\omega_2\\} = \\{ 30, 20\\}$. Overall, we consider this investigation inconclusive, but certainly worth further study. \n\n\n#### **7.3.4 How does LUNA behave on different gap locations?** <a class=\"anchor\" id=\"section_7_3_4\"></a>\n\nWe also wanted to examine how generalizable LUNA is across different data-scarce situations. That is, if we find a set of hyperparameter values that work well for one type of gap, do they also work well for different types of gaps? To examine this question, we conducted a simple experiment where we grid-searched ideal hyperparameter values for the data with a gap in the middle and tested the same set of hyperparameter values onto the data with a gap toward the left or right. For this experiment, we used the same 1-D cubic gap data as before, but decreased the gap size to enable moving gaps around.\n\n\n\nResults suggest that the hyperparameter values are not very transferable across different gap locations: the hyperparameter values tuned for one gap location (middle) does not seem to give good epistemic uncertainty when applied to different gap locations (right or left). This means that LUNA may not be generalizable across different data-scarce situations, which calls for domain/problem-specific tuning practices. The details of the experiment can be found [here](https://github.com/weyesians/luna-passa/blob/main/notebooks/LUNA_gap_experiment.ipynb).\n\n#### **7.3.5 How does LUNA behave on multivariate functions?** <a class=\"anchor\" id=\"section_7_3_5\"></a>\n\nTo extend our experiments to multivariate cases, we also implemented LUNA for multivariate input functions. Here we demonstrate fitting LUNA to two example functions, and compared the results to NLM. The details of the experiment can be found [here](https://github.com/weyesians/luna-passa/blob/main/notebooks/LUNA_multivariate_function_demo.ipynb).\n\nThe first function we tried is $y = 10 \\cdot sin( 2 \\sqrt{{x_{1}}^{2}+{x_{2}}^{2}})$. Training data were set on a grid between $x_1 = [-3.25, 3.25], x_2 = [-3.25, 3.25]$ and the gap was created at the region enclosed by $x_1 = [-1.25, 1.25], x_2 = [-1.25, 1.25]$. Below is the visualization of the function.\n\n\n\nFor the fitting, we picked 30 auxlilary functions on top of a 2-layer MLP with 50 units in each layer. Both regularization parameter and diversification parameter were set at 10. For Bayesian linear regression, both prior variance and noise variance were set at 9. We minimized the LUNA loss function with Adam optimizor (step size = $10^{-2}$, 2000 steps), and compared the results to NLM with the same architecture and hyperparameters. \n\nTo visualized the results, we first created a 1-D slice along $x_2 = 0$. On the left, we can see that the 30 auxiliary functions after fitting. As in the 1-D cubic gap dataset, diversity of auxiliary functions can be seen in the gap regions, with many of them not fitting well the training data near the gap. This diversity lead to the increased epistemic uncertainty in the gap regions as we inpsect the posterior predictive. On the other hand, NLM had small epistemic uncertainty in the gap regions. For both LUNA and NLM, we can see that the fitted functions made very sharp turns instead of smooth curves in the middle of data-rich region, which may reflect the limited expressive capacity of this small architecture on a more complex multivariate functions, or could be the impact of relu activation functions.\n\n\n\nWe can also create 2-D heatmap to visualize the posterior mean and epistemic uncertainty of the LUNA and NLM fits. The red dotted square indicates the gap location. We can see that both LUNA and NLM showed decent posterior mean that resembles the ground truth values in the data-rich region. LUNA showed higher epistemic uncertainty in the gap region than NLM. However, as we can see in the 1-D slice, the epistemic uncertainty of LUNA didn't increase smoothly as a function of distance away from the data-rich region; instead, we observed a small region with little epistemic uncertainty follwed by a sharp twist of increasing epistemic uncertainty. Also, at the border region, LUNA wasn't showing increased epistemic uncertainty either, probably also reflecting the limited capacity of this small MLP architecture.\n\n\n\n\nIn the second experiment, we fitted LUNA and NLM to an extension of the cubic gap dataset: $y = {x_{1}}^{3}+{x_{2}}^{3}$. Training data were set on a grid between $x_1 = [-4, 4], x_2 = [-4, 4]$ and the gap was created at the region enclosed by $x_1 = [-2, 2], x_2 = [-2, 2]$. Below is the visualization of the function.\n\n\n\nFor the fitting, we also picked 30 auxlilary functions on top of a 2-layer MLP with 50 units in each layer. Regularization parameter was set at 10 and diversification parameter was 300. For Bayesian linear regression, both prior variance and noise variance were set at 9. The same optimzation procedure was used for the fitting.\n\nAs demonstated in the 1-D slice as well as 2-D heatmap, we observed diverse auxiliary functions, as well as high epistemic uncertainty in the gap region for LUNA, whereas the NLM failed to express desirable epistemic uncertainty. Both LUNA and NLM showed reasonable posterior mean that fit to the ground truth values. Another interesting observation is that when we trained the same NLM without regularization, surprisingly we didn't get ideal epistemic uncertainty. This really showed the usefulness of LUNA; sometimes, NLM falied to express epistemic uncertanty even without regularization. LUNA explicitly encourage diverse feature maps thus can create the uncertainty behavior we desire.\n\n\n\n\n\n\nHowever, we've noticed that this result wasn't consistent with different runs. We repeated the same experiments multiple times. With the identical hyperparameters, sometimes we got results with less epistemic uncertainty. It wasn't completely clear to us what we observed this \"failure mode\". The reason could be that we didn't train the model long enough, or the optimization got stuck in some local minimum.\n\n\n\n## 8. Evaluation <a class=\"anchor\" id=\"chapter8\"></a>\n\nFrom the experiments above we were able to reproduce the ideal behavior for LUNA in the 1-D cubic gap dataset and some of the multivariate input cases. By studying the auxiliary functions as well as the prior samples, we were able to verify the purpose of this method: encourgaing diverse feature map in order to support greater epistemic uncertainty in out-of-distribution cases through Bayesian linear regression.\n\nIn the original paper, the authors also demonstrated a real-life example using the UCI datasets as a use case for LUNA and seemed to provide satisfactory results. We didn't run this experiment; however, we would like to raise some caution for applying LUNA according to our finding in our own experiments in the previous section.\n\n1. **Hyperparameters tuning**: We found that behavior of LUNA can be highly sensitive to hyperparameters such as the divsersitifcation strength, and it's interaction with regularization. An ideal hyperparameter regime can be highly task-specific, and it may be needed to perform hyperparameter search before applying LUNA to a real dataset.\n\n2. **Trade-off between log likelihood and epistemic uncertainty**: We observed from our experiments that normally there's is a trade-off between log likelihood on the in-distribution test data vs. the epistemic uncertainty on the OOD data. The reason is that as the divsersitifcation increases, the epistemic uncertainty improves due to diverse auxiliary functions and feature maps; however, the model would stop fitting to the training data well, and the resultant feature maps may not be used by the Bayesian linear regression, leading to poorer model performance. On the other hand, sometimes it may be worth to sacrafice a little bit of loss in model performance but obtain gain in OOD epistemic uncertainty. One should carefull consider this trade-off for any application of LUNA on real datasets.\n\n3. **Network architectural design vs. the number of auxiliary functions**: We've also performed experiments to show that, the number of auxiliary functions as well as the architecture of neural network can greatly impact the behavior of LUNA. In general, an increased number of auxiliary functions generates more divsersity, and a larger architecture provide sufficient expressive power for the neural network to support diverse feature maps. Howver, there may be an interaction between the two: for a given network architecture, it may only be capable of supporting a certain number of diverse auxiliary functions. This can be left as a future direction for more throughout understanding of LUNA.\n\n## 9. Broader Impact <a class=\"anchor\" id=\"chapter9\"></a>\n\nAs mentioned in the problem statement, LUNA seems promising for high-stakes applications where a user should either turn over an uncertain machine-produced decision to a qualified human decision-maker or abstain from using the machine-produced decision altogether. To this end, LUNA has the potential to reduce disparate impact in high stakes settings such as health care and criminal justice. For example, in image recognition tasks, minority groups are often underrepresented in training data sets. Inaccurate prediction for minority groups in deployment has had dire consequences, leading to false criminal accusations, misdiagnoses, and death. Using LUNA to model appropriate predictive uncertainties could cue users to potential algorithmic discrimination before it happens.\n\nHowever, epistemic uncertainty awareness has its limitations, even when deployed with human decision-makers. Data scarcity and underrepresentation of minority groups in training sets reflect larger societal biases that impact human decision-makers as much as they impact predictive models. For example, social psychologists have long studied the \"cross-race effect,\" which shows that humans are worse at recognizing faces outside of their racial group (an unfortunate side-effect of social segregation). Similarly, there is evidence to suggest that doctors are biased in their diagnoses and treatment of minority groups, which can be attributed to prejudiced curriculum in medical schools, outdated assumptions about group differences rooted in eugenics, and implicit/explicit biases doctors have accumulated throughout their lifetimes. While tools like LUNA can help us better quantify uncertainty in machine learning tasks at scale, there is little evidence--and perhaps even little basis--to suggest that they can address society's inability to meet vulnerable populations' needs. We would caution future users of this technology against overselling its ability to address algorithmic biases in high-stakes tasks when used with human collaborators. Much more research is needed in this area, including human-computer interaction studies to understand how humans collaborate with LUNA in high-stakes situations and psychological interventions aimed at reducing human-cognitive biases in these collaborative settings.\n\n\n## 10. References <a class=\"anchor\" id=\"chapter10\"></a>\n\nThakur, S., Lorsung, C., Yacoby, Y., Doshi-Velez, F., Pan, W. Learned Uncertainty-Aware (LUNA) Bases for Bayesian Regression using Multi-Headed Auxiliary Networks. arXiv:2006.11695v2 [stat.ML], ArXiV, 2020. \n\nNeal, R. M. Bayesian learning for neural networks, 1995.\n\nOber, S. W. and Rasmussen, C. E. Benchmarking the neural linear model for regression. In Advances in Approximate Bayesian Inference (AABI), 2019.\n\nRasmussen, C. and Williams, C. Gaussian Processes for Machine Learning. Adaptive Computation and Machine Learning. MIT Press, Cambridge, MA, USA, January 2006.\n\nRoss, A. S., Pan, W., and Doshi-Velez, F. Learning qualitatively diverse and interpretable rules for classification. In International Conference on Machine Learning (ICML): Workshop on Human Interpretability in Machine Learning, 2018.\n\nSnoek, J., Rippel, O., Swersky, K., Kiros, R., Satish, N., Sundaram, N., Patwary, M. M. A., Prabhat, and Adams, R. P. Scalable bayesian optimization using deep neural networks. In Proceedings of the 32nd International Conference on Machine Learning (ICML), pp. 2171\u20132180, 2015.\n\nSpringenberg, J. T., Klein, A., Falkner, S., and Hutter, F. Bayesian optimization with robust bayesian neural net- works. In Advances in Neural Information Processing Systems 29, pp. 4134\u20134142, 2016.\n\nYao, J., Pan, W., Ghosh, S., and Doshi-Velez, F. Quality of uncertainty quantification for bayesian neural network inference. In International Conference on Machine Learning (ICML): Workshop on Uncertainty & Robustness in Deep Learning, 2019.\n", "meta": {"hexsha": "3786a3480ba9a605a98cf46e8b272e347b367407", "size": 1001971, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "am207_final_project_luna.ipynb", "max_stars_repo_name": "weyesians/luna_passa", "max_stars_repo_head_hexsha": "8c3c6a10387475580a63add4f50c00602ad15641", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "am207_final_project_luna.ipynb", "max_issues_repo_name": "weyesians/luna_passa", "max_issues_repo_head_hexsha": "8c3c6a10387475580a63add4f50c00602ad15641", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-19T21:42:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-19T21:42:17.000Z", "max_forks_repo_path": "am207_final_project_luna.ipynb", "max_forks_repo_name": "weyesians/luna-passa", "max_forks_repo_head_hexsha": "8c3c6a10387475580a63add4f50c00602ad15641", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 663.5569536424, "max_line_length": 690740, "alphanum_fraction": 0.9388664941, "converted": true, "num_tokens": 26076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3106943704494217, "lm_q2_score": 0.08269735058769655, "lm_q1q2_score": 0.025693601278679493}}
{"text": "```python\n%load_ext autoreload\n%autoreload 2\n```\n\n\n```python\n!python -m pip install --upgrade --user jax==0.2.8 jaxlib==0.1.59+cuda101 -f https://storage.googleapis.com/jax-releases/jax_releases.html\n```\n\n\n```python\n!git checkout dev;\n```\n\n    D\texamples/2D sims - IMNN.ipynb\n    M\texamples/IMNN - JAX.ipynb\n    Already on 'dev'\n    Your branch is ahead of 'origin/dev' by 3 commits.\n      (use \"git push\" to publish your local commits)\n\n\n\n```python\n!git pull\n```\n\n    Already up-to-date.\n\n\n\n```python\npwd\n```\n\n\n\n\n    '/mnt/home/tmakinen/repositories/scratch/dev-imnn/imnn'\n\n\n\n\n```python\n!python -m setup.py install\n```\n\n    /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/setuptools/dist.py:458: UserWarning: Normalizing '0.3dev' to '0.3.dev0'\n      warnings.warn(tmpl.format(**locals()))\n    running install\n    running bdist_egg\n    running egg_info\n    writing IMNN.egg-info/PKG-INFO\n    writing dependency_links to IMNN.egg-info/dependency_links.txt\n    writing requirements to IMNN.egg-info/requires.txt\n    writing top-level names to IMNN.egg-info/top_level.txt\n    reading manifest file 'IMNN.egg-info/SOURCES.txt'\n    writing manifest file 'IMNN.egg-info/SOURCES.txt'\n    installing library code to build/bdist.linux-x86_64/egg\n    running install_lib\n    running build_py\n    copying IMNN/experimental/jax/imnn/imnn.py -> build/lib/IMNN/experimental/jax/imnn\n    creating build/bdist.linux-x86_64/egg\n    creating build/bdist.linux-x86_64/egg/IMNN\n    creating build/bdist.linux-x86_64/egg/IMNN/LFI\n    copying build/lib/IMNN/LFI/LFI.py -> build/bdist.linux-x86_64/egg/IMNN/LFI\n    copying build/lib/IMNN/LFI/__init__.py -> build/bdist.linux-x86_64/egg/IMNN/LFI\n    copying build/lib/IMNN/IMNN.py -> build/bdist.linux-x86_64/egg/IMNN\n    copying build/lib/IMNN/tfIMNN.py -> build/bdist.linux-x86_64/egg/IMNN\n    copying build/lib/IMNN/__init__.py -> build/bdist.linux-x86_64/egg/IMNN\n    creating build/bdist.linux-x86_64/egg/IMNN/utils\n    copying build/lib/IMNN/utils/__init__.py -> build/bdist.linux-x86_64/egg/IMNN/utils\n    copying build/lib/IMNN/utils/utils.py -> build/bdist.linux-x86_64/egg/IMNN/utils\n    copying build/lib/IMNN/utils/TFRecords.py -> build/bdist.linux-x86_64/egg/IMNN/utils\n    creating build/bdist.linux-x86_64/egg/IMNN/experimental\n    copying build/lib/IMNN/experimental/__init__.py -> build/bdist.linux-x86_64/egg/IMNN/experimental\n    creating build/bdist.linux-x86_64/egg/IMNN/experimental/jax\n    creating build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/_tensorflow_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/tensorflow_gradient_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/aggregated_gradient_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/gradient_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/numerical_gradient_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/aggregated_numerical_gradient_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/aggregated_numerical_gradient_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/gradient_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/__init__.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/simulator_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/aggregated_simulator_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/tensorflow_numerical_gradient_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/simulator_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/_tensorflow_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/aggregated_gradient_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/numerical_gradient_imnn.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    copying build/lib/IMNN/experimental/jax/imnn/aggregated_simulator_imnn_test.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn\n    creating build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi\n    copying build/lib/IMNN/experimental/jax/lfi/gaussian_approximation.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi\n    copying build/lib/IMNN/experimental/jax/lfi/lfi.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi\n    copying build/lib/IMNN/experimental/jax/lfi/__init__.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi\n    copying build/lib/IMNN/experimental/jax/lfi/approximate_bayesian_computation.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi\n    copying build/lib/IMNN/experimental/jax/__init__.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax\n    creating build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils\n    copying build/lib/IMNN/experimental/jax/utils/__init__.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils\n    copying build/lib/IMNN/experimental/jax/utils/utils.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils\n    copying build/lib/IMNN/experimental/jax/utils/keras_utils.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils\n    copying build/lib/IMNN/experimental/jax/utils/container.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils\n    copying build/lib/IMNN/experimental/jax/utils/jac.py -> build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils\n    creating build/bdist.linux-x86_64/egg/test\n    copying build/lib/test/tensorflow_defaults.py -> build/bdist.linux-x86_64/egg/test\n    copying build/lib/test/simulator_defaults.py -> build/bdist.linux-x86_64/egg/test\n    copying build/lib/test/numerical_gradient_defaults.py -> build/bdist.linux-x86_64/egg/test\n    copying build/lib/test/__init__.py -> build/bdist.linux-x86_64/egg/test\n    copying build/lib/test/gradient_defaults.py -> build/bdist.linux-x86_64/egg/test\n    copying build/lib/test/defaults.py -> build/bdist.linux-x86_64/egg/test\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/LFI/LFI.py to LFI.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/LFI/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/IMNN.py to IMNN.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/tfIMNN.py to tfIMNN.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/utils/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/utils/utils.py to utils.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/utils/TFRecords.py to TFRecords.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/_tensorflow_imnn.py to _tensorflow_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/tensorflow_gradient_imnn.py to tensorflow_gradient_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/aggregated_gradient_imnn_test.py to aggregated_gradient_imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/gradient_imnn_test.py to gradient_imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/numerical_gradient_imnn_test.py to numerical_gradient_imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/_imnn.py to _imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/aggregated_numerical_gradient_imnn_test.py to aggregated_numerical_gradient_imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/imnn.py to imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/aggregated_numerical_gradient_imnn.py to aggregated_numerical_gradient_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/gradient_imnn.py to gradient_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/_imnn_test.py to _imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/simulator_imnn_test.py to simulator_imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/aggregated_simulator_imnn.py to aggregated_simulator_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/tensorflow_numerical_gradient_imnn.py to tensorflow_numerical_gradient_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/simulator_imnn.py to simulator_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/_tensorflow_imnn_test.py to _tensorflow_imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/aggregated_gradient_imnn.py to aggregated_gradient_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/numerical_gradient_imnn.py to numerical_gradient_imnn.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/imnn/aggregated_simulator_imnn_test.py to aggregated_simulator_imnn_test.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi/gaussian_approximation.py to gaussian_approximation.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi/lfi.py to lfi.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/lfi/approximate_bayesian_computation.py to approximate_bayesian_computation.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils/utils.py to utils.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils/keras_utils.py to keras_utils.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils/container.py to container.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/IMNN/experimental/jax/utils/jac.py to jac.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/test/tensorflow_defaults.py to tensorflow_defaults.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/test/simulator_defaults.py to simulator_defaults.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/test/numerical_gradient_defaults.py to numerical_gradient_defaults.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/test/__init__.py to __init__.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/test/gradient_defaults.py to gradient_defaults.cpython-36.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/test/defaults.py to defaults.cpython-36.pyc\n    creating build/bdist.linux-x86_64/egg/EGG-INFO\n    copying IMNN.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying IMNN.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying IMNN.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying IMNN.egg-info/requires.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying IMNN.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    zip_safe flag not set; analyzing archive contents...\n    creating 'dist/IMNN-0.3.dev0-py3.6.egg' and adding 'build/bdist.linux-x86_64/egg' to it\n    removing 'build/bdist.linux-x86_64/egg' (and everything under it)\n    Processing IMNN-0.3.dev0-py3.6.egg\n    Removing /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/IMNN-0.3.dev0-py3.6.egg\n    Copying IMNN-0.3.dev0-py3.6.egg to /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    IMNN 0.3.dev0 is already the active version in easy-install.pth\n    \n    Installed /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/IMNN-0.3.dev0-py3.6.egg\n    Processing dependencies for IMNN==0.3.dev0\n    Searching for matplotlib==3.3.2\n    Best match: matplotlib 3.3.2\n    Adding matplotlib 3.3.2 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for scipy==1.5.3\n    Best match: scipy 1.5.3\n    Adding scipy 1.5.3 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for numpy==1.19.4\n    Best match: numpy 1.19.4\n    Adding numpy 1.19.4 to easy-install.pth file\n    Installing f2py script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing f2py3 script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing f2py3.6 script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for tqdm==4.55.1\n    Best match: tqdm 4.55.1\n    Processing tqdm-4.55.1-py3.6.egg\n    tqdm 4.55.1 is already the active version in easy-install.pth\n    Installing tqdm script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/tqdm-4.55.1-py3.6.egg\n    Searching for jax==0.2.8\n    Best match: jax 0.2.8\n    Processing jax-0.2.8-py3.6.egg\n    jax 0.2.8 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/jax-0.2.8-py3.6.egg\n    Searching for jaxlib==0.1.57+cuda101\n    Best match: jaxlib 0.1.57+cuda101\n    Removing jaxlib 0.1.59 from easy-install.pth file\n    Adding jaxlib 0.1.57+cuda101 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for tensorflow==2.4.0\n    Best match: tensorflow 2.4.0\n    Processing tensorflow-2.4.0-py3.6-linux-x86_64.egg\n    tensorflow 2.4.0 is already the active version in easy-install.pth\n    Installing estimator_ckpt_converter script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing import_pb_to_tensorboard script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing saved_model_cli script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing tensorboard script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing tf_upgrade_v2 script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing tflite_convert script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing toco script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing toco_from_protos script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/tensorflow-2.4.0-py3.6-linux-x86_64.egg\n    Searching for certifi==2020.12.5\n    Best match: certifi 2020.12.5\n    Adding certifi 2020.12.5 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for Pillow==8.1.0\n    Best match: Pillow 8.1.0\n    Adding Pillow 8.1.0 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for python-dateutil==2.8.1\n    Best match: python-dateutil 2.8.1\n    Adding python-dateutil 2.8.1 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for kiwisolver==1.3.1\n    Best match: kiwisolver 1.3.1\n    Adding kiwisolver 1.3.1 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for cycler==0.10.0\n    Best match: cycler 0.10.0\n    Adding cycler 0.10.0 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for pyparsing==2.4.7\n    Best match: pyparsing 2.4.7\n    Adding pyparsing 2.4.7 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for opt-einsum==3.3.0\n    Best match: opt-einsum 3.3.0\n    Adding opt-einsum 3.3.0 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for absl-py==0.11.0\n    Best match: absl-py 0.11.0\n    Adding absl-py 0.11.0 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for flatbuffers==1.12\n    Best match: flatbuffers 1.12\n    Adding flatbuffers 1.12 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for wrapt==1.12.1\n    Best match: wrapt 1.12.1\n    Processing wrapt-1.12.1-py3.6-linux-x86_64.egg\n    wrapt 1.12.1 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/wrapt-1.12.1-py3.6-linux-x86_64.egg\n    Searching for wheel==0.36.2\n    Best match: wheel 0.36.2\n    Adding wheel 0.36.2 to easy-install.pth file\n    Installing wheel script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for typing-extensions==3.7.4.3\n    Best match: typing-extensions 3.7.4.3\n    Processing typing_extensions-3.7.4.3-py3.6.egg\n    typing-extensions 3.7.4.3 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/typing_extensions-3.7.4.3-py3.6.egg\n    Searching for termcolor==1.1.0\n    Best match: termcolor 1.1.0\n    Processing termcolor-1.1.0-py3.6.egg\n    termcolor 1.1.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/termcolor-1.1.0-py3.6.egg\n    Searching for tensorflow-estimator==2.4.0\n    Best match: tensorflow-estimator 2.4.0\n    Processing tensorflow_estimator-2.4.0-py3.6.egg\n    tensorflow-estimator 2.4.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/tensorflow_estimator-2.4.0-py3.6.egg\n    Searching for tensorboard==2.4.0\n    Best match: tensorboard 2.4.0\n    Processing tensorboard-2.4.0-py3.6.egg\n    tensorboard 2.4.0 is already the active version in easy-install.pth\n    Installing tensorboard script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/tensorboard-2.4.0-py3.6.egg\n    Searching for six==1.15.0\n    Best match: six 1.15.0\n    Adding six 1.15.0 to easy-install.pth file\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for protobuf==4.0.0rc2\n    Best match: protobuf 4.0.0rc2\n    Processing protobuf-4.0.0rc2-py3.6.egg\n    protobuf 4.0.0rc2 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/protobuf-4.0.0rc2-py3.6.egg\n    Searching for Keras-Preprocessing==1.1.2\n    Best match: Keras-Preprocessing 1.1.2\n    Processing Keras_Preprocessing-1.1.2-py3.6.egg\n    Keras-Preprocessing 1.1.2 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/Keras_Preprocessing-1.1.2-py3.6.egg\n    Searching for h5py==2.10.0\n    Best match: h5py 2.10.0\n    Processing h5py-2.10.0-py3.6-linux-x86_64.egg\n    h5py 2.10.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/h5py-2.10.0-py3.6-linux-x86_64.egg\n    Searching for grpcio==1.32.0\n    Best match: grpcio 1.32.0\n    Processing grpcio-1.32.0-py3.6-linux-x86_64.egg\n    grpcio 1.32.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/grpcio-1.32.0-py3.6-linux-x86_64.egg\n    Searching for google-pasta==0.2.0\n    Best match: google-pasta 0.2.0\n    Processing google_pasta-0.2.0-py3.6.egg\n    google-pasta 0.2.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/google_pasta-0.2.0-py3.6.egg\n    Searching for gast==0.3.3\n    Best match: gast 0.3.3\n    Processing gast-0.3.3-py3.6.egg\n    gast 0.3.3 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/gast-0.3.3-py3.6.egg\n    Searching for astunparse==1.6.3\n    Best match: astunparse 1.6.3\n    Processing astunparse-1.6.3-py3.6.egg\n    astunparse 1.6.3 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/astunparse-1.6.3-py3.6.egg\n    Searching for Werkzeug==1.0.1\n    Best match: Werkzeug 1.0.1\n    Processing Werkzeug-1.0.1-py3.6.egg\n    Werkzeug 1.0.1 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/Werkzeug-1.0.1-py3.6.egg\n    Searching for tensorboard-plugin-wit==1.7.0\n    Best match: tensorboard-plugin-wit 1.7.0\n    Processing tensorboard_plugin_wit-1.7.0-py3.6.egg\n    tensorboard-plugin-wit 1.7.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/tensorboard_plugin_wit-1.7.0-py3.6.egg\n    Searching for setuptools==49.6.0.post20201009\n    Best match: setuptools 49.6.0.post20201009\n    Adding setuptools 49.6.0.post20201009 to easy-install.pth file\n    Installing easy_install script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages\n    Searching for requests==2.25.1\n    Best match: requests 2.25.1\n    Processing requests-2.25.1-py3.6.egg\n    requests 2.25.1 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/requests-2.25.1-py3.6.egg\n    Searching for Markdown==3.3.3\n    Best match: Markdown 3.3.3\n    Processing Markdown-3.3.3-py3.6.egg\n    Markdown 3.3.3 is already the active version in easy-install.pth\n    Installing markdown_py script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/Markdown-3.3.3-py3.6.egg\n    Searching for google-auth==1.24.0\n    Best match: google-auth 1.24.0\n    Processing google_auth-1.24.0-py3.6.egg\n    google-auth 1.24.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/google_auth-1.24.0-py3.6.egg\n    Searching for google-auth-oauthlib==0.4.2\n    Best match: google-auth-oauthlib 0.4.2\n    Processing google_auth_oauthlib-0.4.2-py3.6.egg\n    google-auth-oauthlib 0.4.2 is already the active version in easy-install.pth\n    Installing google-oauthlib-tool script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/google_auth_oauthlib-0.4.2-py3.6.egg\n    Searching for urllib3==1.26.2\n    Best match: urllib3 1.26.2\n    Processing urllib3-1.26.2-py3.6.egg\n    urllib3 1.26.2 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/urllib3-1.26.2-py3.6.egg\n    Searching for idna==2.10\n    Best match: idna 2.10\n    Processing idna-2.10-py3.6.egg\n    idna 2.10 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/idna-2.10-py3.6.egg\n    Searching for chardet==4.0.0\n    Best match: chardet 4.0.0\n    Processing chardet-4.0.0-py3.6.egg\n    chardet 4.0.0 is already the active version in easy-install.pth\n    Installing chardetect script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/chardet-4.0.0-py3.6.egg\n    Searching for importlib-metadata==3.3.0\n    Best match: importlib-metadata 3.3.0\n    Processing importlib_metadata-3.3.0-py3.6.egg\n    importlib-metadata 3.3.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/importlib_metadata-3.3.0-py3.6.egg\n    Searching for rsa==4.6\n    Best match: rsa 4.6\n    Processing rsa-4.6-py3.6.egg\n    rsa 4.6 is already the active version in easy-install.pth\n    Installing pyrsa-decrypt script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing pyrsa-encrypt script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing pyrsa-keygen script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing pyrsa-priv2pub script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing pyrsa-sign script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    Installing pyrsa-verify script to /mnt/home/tmakinen/anaconda3/envs/pyjax/bin\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/rsa-4.6-py3.6.egg\n    Searching for pyasn1-modules==0.2.8\n    Best match: pyasn1-modules 0.2.8\n    Processing pyasn1_modules-0.2.8-py3.6.egg\n    pyasn1-modules 0.2.8 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/pyasn1_modules-0.2.8-py3.6.egg\n    Searching for cachetools==4.2.0\n    Best match: cachetools 4.2.0\n    Processing cachetools-4.2.0-py3.6.egg\n    cachetools 4.2.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/cachetools-4.2.0-py3.6.egg\n    Searching for requests-oauthlib==1.3.0\n    Best match: requests-oauthlib 1.3.0\n    Processing requests_oauthlib-1.3.0-py3.6.egg\n    requests-oauthlib 1.3.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/requests_oauthlib-1.3.0-py3.6.egg\n    Searching for zipp==3.4.0\n    Best match: zipp 3.4.0\n    Processing zipp-3.4.0-py3.6.egg\n    zipp 3.4.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/zipp-3.4.0-py3.6.egg\n    Searching for pyasn1==0.4.8\n    Best match: pyasn1 0.4.8\n    Processing pyasn1-0.4.8-py3.6.egg\n    pyasn1 0.4.8 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/pyasn1-0.4.8-py3.6.egg\n    Searching for oauthlib==3.1.0\n    Best match: oauthlib 3.1.0\n    Processing oauthlib-3.1.0-py3.6.egg\n    oauthlib 3.1.0 is already the active version in easy-install.pth\n    \n    Using /mnt/home/tmakinen/anaconda3/envs/pyjax/lib/python3.6/site-packages/oauthlib-3.1.0-py3.6.egg\n    Finished processing dependencies for IMNN==0.3.dev0\n    /mnt/home/tmakinen/anaconda3/envs/pyjax/bin/python: Error while finding module specification for 'setup.py' (AttributeError: module 'setup' has no attribute '__path__')\n\n\n\n```python\nfrom jax.config import config\nconfig.update(\"jax_debug_nans\", True)\nconfig.update('jax_enable_x64', True)\n\n```\n\n\n```python\nimport itertools\nimport math\nfrom functools import partial\n\nimport numpy as onp\n\nimport jax\nprint(\"jax version: \", jax.__version__)\nimport jax.experimental.optimizers as optimizers\nimport jax.experimental.stax as stax\nimport jax.numpy as np\nfrom jax import jit\nimport matplotlib.pyplot as plt\n\nimport IMNN\nprint(\"IMNN version: \", IMNN.__version__)\n\nfrom IMNN.experimental.jax.imnn import (\n    AggregatedGradientIMNN,\n    AggregatedNumericalGradientIMNN,\n    AggregatedSimulatorIMNN,\n    GradientIMNN,\n    NumericalGradientIMNN,\n    SimulatorIMNN,\n)\nfrom IMNN.experimental.jax.lfi import (\n    ApproximateBayesianComputation,\n    GaussianApproximation,\n)\nfrom IMNN.experimental.jax.utils import value_and_jacrev, value_and_jacfwd\n\nrng = jax.random.PRNGKey(0)\n\n```\n\n    jax version:  0.2.8\n    IMNN version:  0.2dev\n\n\n\n```python\n!XLA_FLAGS=--xla_cpu_enable_fast_math=false\n```\n\n\n```python\nfrom jax.lib import xla_bridge\nprint(xla_bridge.get_backend().platform)\n```\n\n    gpu\n\n\n\n```python\n\n```\n\n# Model in STAX\n\n\n```python\nn_summaries = 2\nn_s = 10000\nn_d = 5000\n\u03bb = 100.0\n\u03f5 = 0.1\n```\n\n\n```python\n# define inception block layer\n\ndef InceptBlock2(filters, strides, do_5x5=True, do_3x3=True):\n    \"\"\"InceptNet convolutional striding block.\n    filters: tuple: (f1,f2,f3)\n    filters1: for conv1x1\n    filters2: for conv1x1,conv3x3\n    filters3L for conv1x1,conv5x5\"\"\"\n    \n    filters1, filters2, filters3 = filters\n    \n    conv1x1 = stax.serial(stax.Conv(filters1, (1,1), strides, padding=\"SAME\"))\n    \n    filters4 = filters2\n    conv3x3 = stax.serial(stax.Conv(filters2, (1,1), strides=None, padding=\"SAME\"),\n                        stax.Conv(filters4, (3,3), strides, padding=\"SAME\"))\n                        \n    filters5 = filters3\n    conv5x5 = stax.serial(stax.Conv(filters3, (1,1), strides=None, padding=\"SAME\"),\n                         stax.Conv(filters5, (5,5), strides, padding=\"SAME\"))\n#     conv5x5 = stax.serial(stax.Conv(filters1, (1,1), strides=None, padding=\"SAME\"),\n#                          stax.Conv(filters3, (3,3), strides=None, padding=\"SAME\"),\n#                          stax.Conv(filters3, (3,3), strides, padding=\"SAME\"))   \n    \n    maxpool = stax.serial(stax.MaxPool((3,3), padding=\"SAME\"),\n                         stax.Conv(filters4, (1,1), strides, padding=\"SAME\"))\n                            \n    if do_3x3:\n        if do_5x5:\n            return stax.serial(\n                  stax.FanOut(4),  # should num=3 or 2 here ?\n                  stax.parallel(conv1x1, conv3x3, conv5x5, maxpool),\n                  stax.FanInConcat(), \n                  stax.LeakyRelu)\n        else:\n            return stax.serial(\n                  stax.FanOut(3),  # should num=3 or 2 here ?\n                  stax.parallel(conv1x1, conv3x3, maxpool),\n                  stax.FanInConcat(), \n                  stax.LeakyRelu)\n            \n    else:\n        return stax.serial(\n              stax.FanOut(2),  # should num=3 or 2 here ?\n              stax.parallel(conv1x1, maxpool),\n              stax.FanInConcat(), \n              stax.LeakyRelu)\n```\n\n\n```python\nrng,drop_rng = jax.random.split(rng)\n# fs = 4 #for 128x128 sims\n\n# layers = []\n\n# for i in range(7):\n#     if i == 5:\n#         layers.append(InceptBlock2((fs,fs,fs), strides=(2,2), do_5x5=False)\n#         )\n#     elif i == 6:\n#         layers.append(InceptBlock2((fs,fs,fs), strides=(2,2), do_5x5=False, do_3x3=False)\n#         )\n#     else: \n#         layers.append(InceptBlock2((fs,fs,fs), strides=(2,2))\n#         )\n        \n#     if i % 4 == 0:\n#         fs *= 2\n    \n# layers.append(stax.Conv(n_summaries, (1,1), strides=(1,1), padding=\"SAME\"))\n# layers.append(stax.Flatten)\n\n# model = stax.serial(*layers)\n\nfs = 32\n    \n# model = stax.serial(InceptBlock((fs,fs,fs), strides=(2,2)), # output 64x64\n#                     InceptBlock((fs,fs,fs), strides=(2,2)), # output 32x32\n#                     InceptBlock((fs,fs,fs), strides=(2,2)), # output 16x16\n#                     InceptBlock((fs,fs,fs), strides=(2,2)), # output 8x8\n#                     InceptBlock((fs,fs,fs), strides=(2,2)), # output 4x4\n#                     InceptBlock((fs,fs,fs), strides=(2,2), do_5x5=False), # output 2x2\n#                     InceptBlock((fs,fs,fs), strides=(2,2), do_5x5=False), # output 1x1\n#                     stax.Conv(n_summaries, (1,1), strides=(1,1), padding=\"SAME\"),\n#                     stax.Flatten,\n#                    )\n\nmodel = stax.serial(\n       # InceptBlock2((fs,fs,fs), strides=(4,4)),\n        InceptBlock2((fs,fs,fs), strides=(4,4)),\n        InceptBlock2((fs,fs,fs), strides=(4,4)),\n        InceptBlock2((fs,fs,fs), strides=(2,2), do_5x5=False, do_3x3=False),\n        stax.Conv(n_summaries, (1,1), strides=(1,1), padding=\"SAME\"),\n        stax.Flatten\n)\n```\n\n\n```python\noptimiser = optimizers.adam(step_size=1e-3)\n```\n\n\n```python\n# weights = model[0](rng, input_shape)[1]\n# model[1](weights, np.zeros(input_shape, dtype=np.float32), rng=rng).shape\n# state = optimiser[0](weights)\n# model[1](optimiser[2](state), np.zeros(input_shape, dtype=np.float32), rng=rng)\n```\n\n# Random seeds for IMNN\n\n\n```python\nrng, initial_model_key = jax.random.split(rng)\nrng, fitting_key = jax.random.split(rng)\n```\n\n# Random seeds for ABC\n\n\n```python\nrng, abc_key = jax.random.split(rng)\n```\n\n# 2D Gaussian Field Simulator in JAX\n\nSteps to creating $(N \\times N)$ 2D Gaussian field for IMNN:\n1. Generate a $(N\\times N)$ white noise field $\\varphi$ such that $\\langle \\varphi_k \\varphi_{-k} \\rangle' = 1$\n2. Fourier Transform $\\varphi$ to real space: $R_{\\rm white}(\\textbf{x}) \\rightarrow R_{\\rm white}(\\textbf{k})$\n    - note: NumPy's DFT Fourier convention is:\n    $$\\phi_{ab}^{\\textbf{k}} = \\sum_{c,d = 0}^{N-1} \\exp{(-i x_c k_a - i x_d k_b) \\phi^{\\textbf{x}}_{cd}}$$\n    $$\\phi_{ab}^{\\textbf{x}} = \\frac{1}{N^2}\\sum_{c,d = 0}^{N-1} \\exp{(-i x_c k_a - i x_d k_b) \\phi^{\\textbf{k}}_{cd}}$$    \n3. Scale white noise $R_{\\rm white}(\\textbf{k})$ by the chosen power spectrum evaluated over a field of $k$ values:\n$$ R_P(\\textbf{k}) = P^{1/2}(k) R_{\\rm white}(\\textbf{k}) $$\n    - note: here we need to ensure that this array of amplitudes is Hermitian, e.g. $\\phi^{* \\textbf{k}}_{a(N/2 + b)} = \\phi^{\\textbf{k}}_{a(N/2 - b)}$. This is accomplished by choosing indexes $k_a = k_b = \\frac{2\\pi}{N} (0, \\dots, N/2, -N/2+1, \\dots, -1)$ and then evaluating the square root of the outer product of the meshgrid between the two: $k = \\sqrt{k^2_a + k^2_b}$. We can then evaluate $P^{1/2}(k)$.\n    \n4. Fourier Transform $R_{P}(\\textbf{k})$ to real space: $ R_P(\\textbf{x}) = \\int d^d \\tilde{k} e^{i\\textbf{k} \\cdot \\textbf{x}} R_p(\\textbf{k}) $:\n\n$$R_{ab}^{\\textbf{x}} = \\frac{1}{N^2}\\sum_{c,d = 0}^{N-1} \\exp{(-i x_c k_a - i x_d k_b) R^{\\textbf{k}}_{cd}}$$\n\n\n```python\n# SET 32-BiT floats for model !\n\u03b8_fid = np.array([1.0, 0.5], dtype=np.float32)\n\u03b4\u03b8 = np.array([0.1, 0.1], dtype=np.float32)\nn_params = 2\nN = 32\ndim = 2\nL = 32\n\nfield_shape = (N,N)\ndx = L / N\nfourier_b = 2*np.pi\ninput_shape = (1,1, N,N)\nsimulator_args = {\"N\": N, \"L\": L, \"dim\": dim, \"shape\": field_shape, 'vol_norm': False, \"N_scale\": True, \"squeeze\": False}\n```\n\n\n```python\nrng,fg_key = jax.random.split(rng)\nforegrounds = jax.random.normal(fg_key, (1000, 1,) + simulator_args['shape'])*0\n\n\ndef default_P(k, A, B):\n    return A*k**-B\n\n\nclass powerBoxJax:\n    def __init__(self, shape, pk=None, k=None):\n        \n        if pk is None:\n            self.pk = default_P\n        else:\n            self.pk = pk\n            \n        if k is None:\n            self.k = np.sqrt(np.sum(np.array(np.meshgrid(*(\n                (np.hstack((np.arange(0, _shape//2 + 1), \n                    np.arange(-_shape//2 + 1, 0))) * 2*np.pi / _shape)**2\n                    for _shape in shape))), axis=0))\n        else:\n            self.k = k\n            \n        self.shape = shape\n        self.N = shape[0]\n        \n    def simulator(self, rng, \u03b8, simulator_args=simulator_args, add_foregrounds=False):\n        def P(k, A=1, B=1):\n            return self.pk(k, A, B)\n\n        def fn(key, A, B):\n            shape = self.shape #simulator_args[\"shape\"]\n\n            k = self.k\n\n            new_shape = ()\n            for _shape in shape:\n                if _shape % 2 == 0:\n                    new_shape += (_shape+1,)\n                else:\n                    new_shape += (_shape,)\n\n\n            key1,key2 = jax.random.split(key)\n    \n            if add_foregrounds:\n                foreground = foregrounds[jax.random.randint(key2, \n                                            minval=0, maxval=1000, shape=())]\n            else:\n                foreground = 0.\n\n            # L is in length units, like Gpc\n            L = simulator_args['L']\n            dim = simulator_args['dim']\n\n            if np.isscalar(L):\n                L = [L]*int(dim)\n\n            else:\n                L = np.array(L)\n\n\n            V = np.prod(np.array(L))\n\n            scale = V**(1./dim)\n\n            Lk = ()\n\n            _N = 1\n            for i,_shape in enumerate(shape):\n                _N *= _shape\n                Lk += (_shape / L[i],) # 1 / dx\n\n\n            fft_norm = np.prod(np.array(Lk))\n\n            _dims = len(shape)\n            tpl = ()\n            for _d in range(_dims):\n                tpl += (_d,)\n\n            # POWERBOX IMPLEMENTATION\n\n            mag = jax.random.normal(key1, shape=tuple(N for N in new_shape))\n            \n            # random phases\n            pha = 2 * np.pi * jax.random.uniform(key1, shape=tuple(N for N in new_shape))\n            \n            # now make hermitian field (reality condition)\n            revidx = (slice(None, None, -1),) * len(mag.shape)\n            mag = (mag + mag[revidx]) / np.sqrt(2) \n            pha = (pha - pha[revidx]) / 2 + np.pi\n            dk = mag * (np.cos(pha) + 1j * np.sin(pha)) # output is complex\n\n            cutidx = (slice(None, -1),) * len(new_shape)\n\n            dk = dk[cutidx]\n            powers = np.concatenate((np.zeros(1), \n                        np.sqrt(P(k.flatten()[1:], A=A, B=B)))).reshape(k.shape)\n\n            # normalize power by volume\n            if simulator_args['vol_norm']:\n                powers = powers/V\n\n            fourier_field = powers * dk\n\n            fourier_field = jax.ops.index_update(\n                fourier_field,\n                np.zeros(len(shape), dtype=int),\n                np.zeros((1,)))\n            \n            field = np.real(np.fft.ifftn(fourier_field) * fft_norm * V)\n            \n            if simulator_args[\"N_scale\"]:\n                field *= scale\n\n            field = np.expand_dims(field + foreground, (0,))\n\n\n            if not simulator_args[\"squeeze\"]:\n                field = np.expand_dims(field, (0,))\n\n            return np.array(field, dtype='float32')\n\n        shape = self.shape #simulator_args[\"shape\"]\n        A, B = \u03b8\n\n\n        if A.shape == B.shape:\n            if len(A.shape) == 0:\n                return fn(rng, A, B)\n            else:\n                keys = jax.random.split(rng, num=A.shape[0] + 1)\n                rng = keys[0]\n                keys = keys[1:]\n                return jax.vmap(\n                    lambda key, A, B: simulator(key, (A, B), simulator_args=simulator_args)\n                )(keys, A, B)\n        else:\n            if len(A.shape) > 0:\n                keys = jax.random.split(rng, num=A.shape[0] + 1)\n                rng = keys[0]\n                keys = keys[1:]\n                return jax.vmap(\n                    lambda key, A: simulator(key, (A, B), simulator_args=simulator_args)\n                )(keys, A)\n            elif len(B.shape) > 0:\n                keys = jax.random.split(rng, num=B.shape[0])\n                return jax.vmap(\n                    lambda key, B: simulator(key, (A, B), simulator_args=simulator_args)\n                )(keys, B)\n\n\n\n    def AnalyticFisher(self, \n               \u03b8, \n               kvec=None,\n               N=None\n              ):\n        \"\"\"\n        Code for computing the Analytic Fisher for a Gaussian\n        Field with power spectrum P(k) = Ak^-B\n        \"\"\"\n        A,B = \u03b8\n        if N is None:\n            N = self.N\n        \n        # we want all UNIQUE fourier modes\n        if kvec is None:\n            kvec = self.k[:N//2, :N//2]\n\n        pk = lambda k : A*(k**-B)             # P(k) = Ak^(-B)\n        p_a = lambda k : k**-B                # deriv w.r.t. A\n        p_b = lambda k : -A*(k**-B)*np.log(k) # deriv w.r.t. B\n\n\n        powers = np.concatenate((np.ones(1), \n            (pk(kvec.flatten()[1:])))) \n\n        powera = np.concatenate((np.zeros(1), \n            (p_a(kvec.flatten()[1:]))))\n\n        powerb = np.concatenate((np.zeros(1), \n            (p_b(kvec.flatten()[1:])))) \n\n\n        Cinv = np.diag(1. / powers)          # diagonal inv. covariance\n        Ca =  np.diag(powera / 1.)           # C_{,A}\n        Cb =  np.diag(powerb / 1.)           # C_{,B}\n\n        Faa = 0.5 * np.trace((Ca @ Cinv @ Ca @ Cinv))\n        Fab = 0.5 * np.trace((Ca @ Cinv @ Cb @ Cinv))\n        Fba = 0.5 * np.trace((Cb @ Cinv @ Ca @ Cinv))\n        Fbb = 0.5 * np.trace((Cb @ Cinv @ Cb @ Cinv))\n\n        return np.array([[Faa, Fab], [Fba, Fbb]])\n\n\n\nclass analyticFieldLikelihood:\n\n    def __init__(self,\n                 PBJ, \n                 field_shape,\n                 \u0394,\n                 prior,\n                 k=None,\n                 pk=None,\n                 gridsize=20, \n                 tiling=2):\n\n        \"\"\"code for computing a gaussian field's likelihood for power spectrum parameters\n            PBJ :         powerBox simulator object\n            field_shape : list. shape of field input\n            \u0394 :           array-like. FFT of the real-space field\n            prior :       array-like. range over which to compute the likelihood\n            k :           array-like. fourier modes over which to compute P(k)\n            tiling :      list or int. tiling=2 means likelihood will be computed as 2x2 grid\n            gridsize :    how large to make the likelihood surface\n        \"\"\"\n        \n        \n        if k is None:\n            self.k = PBJ.k\n\n        if pk is None:\n            self.pk = PBJ.pk\n\n        self.field_shape = field_shape\n        self.gridsize = gridsize\n        if np.isscalar(tiling):\n            self.tiling = [tiling]*2\n        else:\n            self.tiling = tiling    \n        #self.tilesize = gridsize // tiling\n        self.N = np.sqrt(np.prod(np.array(field_shape)))  # should just be N for NxN grid\n        self.prior = prior\n\n        self.k = k\n        self.\u0394 = \u0394\n\n    def Pk(self, k, A=1, B=0.5):\n        return self.pk(k, A, B)\n\n\n        return np.diag(pk)\n    def log_likelihood(self, k, A, B, \u0394):\n        \u0394 = \u0394.flatten()\n        k = k\n\n        dlength = len(k.flatten())\n\n        def fn(_A, _B):\n\n            nrm = np.pad(np.ones(dlength-2)*2, (1,1), constant_values=1.)\n            nrm = jax.ops.index_update(\n              nrm, np.array([[0],[(dlength-2)]]), np.array([[1],[1]]))\n            #nrm = 1\n\n            powers = np.concatenate((np.ones(1), \n                    (self.Pk(k.flatten()[1:], A=_A, B=_B))))\n\n            # covariance is P(k)\n            C = powers * nrm\n            invC = np.concatenate((np.zeros(1), \n               (1./self.Pk(k.flatten()[1:], A=_A, B=_B))))\n\n            logdetC = np.sum(np.log(C))\n            pi2 = np.pi * 2.\n            m_half_size = -0.5 * len(\u0394)\n            exponent = - 0.5 * np.sum(np.conj(\u0394) * invC * \u0394)\n            norm = -0.5 * logdetC + m_half_size*np.log(pi2) \n            return (exponent + norm)\n        return jax.vmap(fn)(A, B)\n\n    def get_likelihood(self, return_grid=False, shift=None):\n        A_start = self.prior[0][0]\n        A_end = self.prior[1][0]\n        B_start = self.prior[0][1]\n        B_end = self.prior[1][1]\n\n        region_size = [self.gridsize // self.tiling[i] for i in range(len(self.tiling))]\n\n        print(\"computing likelihood on a %dx%d grid \\n \\\n        in tiles of size %dx%d\"%(self.gridsize, self.gridsize, region_size[0], region_size[1]))\n\n\n        def get_like_region(A0, A1, B0, B1, qsize):\n            A_range = np.linspace(A0, A1, qsize)\n            B_range = np.linspace(B0, B1, qsize)\n            A, B = np.meshgrid(A_range, B_range)\n\n            return (self.log_likelihood(k,\n                A.ravel(), B.ravel(), \u0394).reshape(qsize,qsize))\n\n\n\n        A_incr = (A_end - A_start) / self.tiling[0]\n        B_incr = (B_end - B_start) / self.tiling[1]\n\n        # marks the ends of linspace\n        A_starts = [A_start + (i)*A_incr for i in range(self.tiling[0])]\n        A_ends = [A_start + (i+1)*A_incr for i in range(self.tiling[0])]\n        B_starts = [B_start + (i)*B_incr for i in range(self.tiling[1])]\n        B_ends = [B_start + (i+1)*B_incr for i in range(self.tiling[1])]\n\n        _like_cols = []\n        for _col in range(self.tiling[0]):\n            # slide horizontally in A\n            _like_row = []\n            for _row in range(self.tiling[1]):\n                # slide vertically in B\n\n                _like = get_like_region(A_starts[_row], \n                                        A_ends[_row], \n                                        B_starts[_col], \n                                        B_ends[_col],\n                                        region_size[0],\n                                        )\n                _like_row.append(_like)\n\n            _like_cols.append(np.concatenate(_like_row, axis=1))\n\n        _log_likelihood = np.real(np.concatenate(_like_cols, axis=0))\n\n        if shift is None:\n            shift = np.max(_log_likelihood)\n\n        print('shift', shift)\n        print('loglike mean', np.mean(_log_likelihood))\n\n        _log_likelihood = _log_likelihood - shift\n\n        if return_grid:\n            _A_range = np.linspace(self.prior[0,0], self.prior[1,0], self.gridsize)\n            _B_range = np.linspace(self.prior[0,0], self.prior[1,0], self.gridsize)\n            return np.exp(_log_likelihood), _A_range, _B_range\n\n        return np.exp(_log_likelihood)\n\n\n\n    def plot_contours(self, ax=None, \n                      \u03b8_ref=None, shift=None, \n                      xlabel='A', ylabel='B', \n                      return_like=True):\n\n        _like, _A, _B = self.get_likelihood(return_grid=True, shift=shift)\n\n\n        _A, _B = np.meshgrid(_A, _B)\n\n        if ax is None:\n            fig,ax = plt.subplots(figsize=(10,10))\n\n        mesh = ax.contourf(_A, _B, _like)\n        plt.colorbar(mesh, ax=ax)\n\n        if \u03b8_ref is not None:\n            ax.scatter(\u03b8_ref[0], \u03b8_ref[1], zorder=10, marker='+', s=100, color='r')\n\n        ax.set_xlabel('A')\n        ax.set_ylabel('B')\n\n        if return_like:\n            return _like, ax\n\n        else:\n            return ax\n\n    def plot_corner(self, ax=None, label=\"Analytic likelihood\"):\n\n        _like, _A_range, _B_range = self.get_likelihood(return_grid=True)\n\n        likelihoodA = _like.sum(0)\n        likelihoodA /= likelihoodA.sum() * (_A_range[1] -  _A_range[0])\n        likelihoodB = _like.sum(1)\n        likelihoodB /= likelihoodB.sum() * (_B_range[1] -  _B_range[0])\n        sorted_marginal = np.sort(_like.flatten())[::-1]\n        cdf = np.cumsum(sorted_marginal / sorted_marginal.sum())\n        value = []\n        for level in [0.95, 0.68]:\n            this_value = sorted_marginal[np.argmin(np.abs(cdf - level))]\n            if len(value) == 0:\n                value.append(this_value)\n            elif this_value <= value[-1]:\n                break\n            else:\n                value.append(this_value)\n\n\n        # add in the likelihood estimate\n        ax[0, 0].plot(_A_range, likelihoodA, color=\"C2\", label=label)\n        ax[0, 1].axis(\"off\")\n        ax[1, 0].contour(_A_range, _B_range, _like, levels=value, colors=\"C2\")\n        ax[1, 1].plot(likelihoodB, _B_range, color=\"C2\", label=label)\n\n        return ax\n\n```\n\n\n```python\nPBJ = powerBoxJax(simulator_args['shape'])\nsimulator = PBJ.simulator\n```\n\n## sim and gradient\n\n\n```python\ndef simulator_gradient(rng, \u03b8, simulator_args=simulator_args):\n    return value_and_jacrev(simulator, argnums=1, allow_int=True, holomorphic=True)(rng, \u03b8, simulator_args=simulator_args)\n```\n\n\n```python\nrng, key = jax.random.split(rng)\n```\n\n\n```python\nfield_shape\n```\n\n\n\n\n    (32, 32)\n\n\n\n\n```python\n# plot example simulation and derivative\nderiv_args = {\"N\": N, \"L\": 32, \"dim\": dim, \"shape\": field_shape, \"vol_norm\": True, \"N_scale\": True, \"squeeze\": False}\nsimulation, simulation_gradient = value_and_jacfwd(simulator, argnums=1)(rng, \u03b8_fid, simulator_args=deriv_args)\n\nplt.imshow(np.squeeze(simulation[0]), extent=(0,1,0,1))\nplt.colorbar()\nplt.title('example simulation')\nplt.show()\n\nplt.imshow(np.squeeze(simulation_gradient[0].T[0].T), extent=(0,1,0,1))\nplt.title('gradient of simulation')\nplt.colorbar()\nplt.show()\n```\n\n\n```python\ndef get_simulations(rng, n_s, \u03b8, simulator_args=simulator_args):\n    def get_simulator(key):\n        return simulator(key, \u03b8, simulator_args=simulator_args)\n\n    keys = jax.random.split(rng, num=n_s)\n    return jax.vmap(get_simulator)(np.array(keys))\n\n\ndef get_simulation_gradients(rng, n_s, n_d, \u03b8, simulator_args=simulator_args):\n    def get_batch_gradient(key):\n        return simulator_gradient(key, \u03b8, simulator_args=simulator_args)\n\n    keys = jax.random.split(rng, num=n_s)\n    return jax.vmap(get_batch_gradient)(np.array(keys)[:n_d])\n```\n\n# known analytic Fisher information\n\nFor a gaussian field, the likelihood is written\n$$     \\mathcal{L}(\\Delta | \\theta) = \\frac{1}{(2\\pi)^{N_p / 2} \\det(C)^{1/2}}\\exp{\\left(-\\frac{1}{2} \\Delta C^{-1} \\Delta \\right)}$$\n\nWhere $\\Delta \\in \\mathbb{R}^{N_p},\\ N_p=N_k=V=N\\times N$ is the Fourier Transform of the observed real-space field.\nThis yields a Fisher information matrix of\n\n$$F_{\\alpha \\beta} = \\langle -\\frac{\\partial^2 \\ln \\mathcal{L}}{\\partial \\lambda_\\alpha \\partial \\lambda_\\beta} \\rangle= \\frac{1}{2} {\\rm Tr} (C_{, \\alpha} C^{-1} C_{, \\beta} C^{-1}) $$\nwhere the covariance is\n$$ C_{k_i, k_j} =  P(k_i)\\delta_{ij}$$\nThe associated derivatives for a power law $P(k) = Ak^{-B}$ are\n$$\\begin{align}\n    C_{,A} &= \\left( k^{-B} \\right)\\delta_{ij} \\\\\n    C_{,B} &= \\left( -Ak^{-B}\\ln k \\right) \\delta_{ij}\n\\end{align} $$\n\nWe notice that the Fisher information is *only* a function of the power spectrum parameters. It tells us the curvature of the chosen model (likelihood function) at a given $\\theta$. The analytic Fisher information is the maximum amount of information we can expect the IMNN to extract from our simulations.\n\n\n<!-- Alternatively, we can explore a volume integral analytically from the definition of C :\nwhere the Fisher matrix is given by\n$$ F_{\\alpha \\beta} = \\sum_k \\frac{1}{(\\delta P_k)^2} \\frac{\\partial P_k}{\\partial \\lambda_\\alpha} \\frac{\\partial P_k}{\\partial \\lambda_\\beta}$$\nand the error on $P_k$ is given (for a square, 2D box) as\n$$ \\delta P_k = \\sqrt{\\frac{2}{k (\\Delta k) V} } \\left( P_k + \\frac{1}{\\bar{n}} \\right) $$ -->\n\n<!-- For a gaussian field, the likelihood is written\n$$ \\ln \\mathcal{L}(\\theta | \\vec{d}) = \\ln \\mathcal{L}(\\theta | \\Delta) = \\sqrt{\\frac{1}{2\\pi C}} \\exp{\\frac{-{\\Delta}^2}{2C}}$$\n\nwhere $\\vec{d} = \\Delta$ is the overdensity field (in a cosmological context this is the measured temperature or galaxy count in a sky survey). Given that the power spectrum describes the correlations at different scales $k$, we can define the correlation via the power spectrum $C = P(k) = Ak^{-B}$ to compute the log-likelihood. The Fisher information matrix, given as \n$$ F_{\\alpha \\beta} = \\langle - \\frac{\\partial^2 \\ln \\mathcal{L}}{\\partial \\theta_\\alpha \\partial \\theta_\\beta} \\rangle $$\ncan then be computed analytically for our likelihood:\n$$ F_{\\alpha \\beta} = \\sum_k \\frac{1}{(\\delta P_k)^2} \\frac{\\partial P_k}{\\partial \\theta_\\alpha} \\frac{\\partial P_k}{\\partial \\theta_\\beta} $$\n\nwhere $\\delta P_k = \\sqrt{\\frac{2}{4\\pi \\Delta k V k_{\\rm tot}^2}} (P_k + \\frac{1}{\\bar{n}})$ is the error on $P_k$ with survey volume $V$, sampling interval $\\Delta k$, and shot noise $1/\\bar{n}$. Using the fact that $d\\ln P_k = \\frac{d P_k}{P_k}$, we can rewrite the sum as an integral:\n$$ F_{\\alpha \\beta} = 2 \\pi \\left( \\frac{V_{\\rm eff}}{\\lambda^3} \\right) \\int_{k_{\\rm min}}^{k_{\\rm max}} d \\ln k  \\frac{\\partial \\ln P_k}{\\partial \\theta_\\alpha} \\frac{\\partial \\ln P_k}{\\partial \\theta_\\beta}$$\n\nWhere $V_{\\rm eff}$ and $\\lambda^3$ are our effective windowed survey size and survey extent, respectively (set to 1 for now). Doing the integration explicitly, we obtain the Fisher matrix for parameters $\\theta = (A, B)$:\n$$ F = 2 \\pi \\left( \\frac{V_{\\rm eff}}{\\lambda^3} \\right) \\begin{bmatrix}\n    \\frac{1}{A^2} \\ln (\\frac{k_{\\rm max}}{k_{\\rm min}}) & \\frac{1}{2A} ((\\ln k_{\\rm min})^2 - (\\ln k_{\\rm max})^2)  \\\\\n     \\frac{1}{2A} ((\\ln k_{\\rm min})^2 - (\\ln k_{\\rm max})^2) & \\frac{1}{3}((\\ln k_{\\rm max})^3 - (\\ln k_{\\rm min})^3)   \\\\\n\\end{bmatrix}$$\n -->\n\n\nFor our fiducial model with our data vector of size $128^2$, our $\\rm det|F|$ reads:\n\n\n```python\nN = simulator_args[\"N\"]\nshape = simulator_args[\"shape\"]\n\nkbin = np.sqrt(np.sum(np.array(np.meshgrid(*(\n    np.hstack((np.arange(0, _shape//2 + 1), \n        np.arange(-_shape//2 + 1, 0))) *2* np.pi / _shape\n        for _shape in shape)))**2, axis=0))\n\nf_expected = PBJ.AnalyticFisher(\u03b8_fid, kvec=None)\nprint(\"analytic F(\u03b8_fid): \", f_expected)\n\ndetf_expected = np.linalg.det(f_expected)\nprint(\"analytic det(F(\u03b8_fid)): \", detf_expected)\n```\n\n    analytic F(\u03b8_fid):  [[127.5        -91.56274125]\n     [-91.56274125 101.62525821]]\n    analytic det(F(\u03b8_fid)):  4573.484836139556\n\n\n\n```python\n# MAKE SIMULATION\nN = simulator_args[\"N\"]\nshape = (N,N)\n\n\u03b8_sim = np.array([0.7, 0.8])\nsimulator_args = {\"N\": N, \"L\": 32, \"dim\": dim, \"shape\": shape, \"vol_norm\": True, \"N_scale\": False, \"squeeze\": True}\nsimulator_args[\"shape\"] = (N,N)\nsimkey,rng = jax.random.split(rng)\n#sim = np.squeeze(target_data)#\nsim = np.squeeze(simulator(simkey, \u03b8_sim, simulator_args=simulator_args))\nsim_fft = (np.fft.fft2(sim)) #/ (N**2)\n```\n\n\n```python\ngridsize = 100                # for likelihood gridding\n\u0394 = sim_fft[:N//2, :N//2]\nk = kbin[:N//2, :N//2]  \nprior_range = np.array([[0.1, 0.1], [1.25, 1.25]])\nAL = analyticFieldLikelihood(PBJ, shape, \u0394, prior_range, k=k, gridsize=gridsize, tiling=[5,5])\n```\n\n\n```python\n%%time\n#plt.style.use('default')\nlikelihood,_ = AL.plot_contours(\u03b8_ref=\u03b8_sim, shift=None, xlabel=r'$A$', ylabel=r'$B$', return_like=True)\n```\n\n# Initialise IMNN\n\n\n```python\nfrom IMNN.experimental.jax.imnn._imnn import _IMNN\n```\n\n\n```python\nfrom IMNN.experimental.jax.imnn._imnn import _IMNN\nfrom IMNN.experimental.jax.utils import check_simulator, value_and_jacrev\n\n\nclass SimIMNN(_IMNN):\n    def __init__(self, n_s, n_d, n_params, n_summaries, input_shape, \u03b8_fid,\n                 model, optimiser, key_or_state, simulator, verbose=True):\n        super().__init__(\n            n_s=n_s,\n            n_d=n_d,\n            n_params=n_params,\n            n_summaries=n_summaries,\n            input_shape=input_shape,\n            \u03b8_fid=\u03b8_fid,\n            model=model,\n            key_or_state=key_or_state,\n            optimiser=optimiser,\n            verbose=verbose)\n        self.simulator = check_simulator(simulator)\n        self.simulate = True\n\n    def get_fitting_keys(self, rng):\n        return jax.random.split(rng, num=3)\n\n    def get_summaries(self, w, key, validate=False):\n        def get_summary(key, \u03b8):\n            return self.model(w, self.simulator(key, \u03b8))\n\n        def get_derivatives(key):\n            return value_and_jacrev(get_summary, argnums=1)(key, self.\u03b8_fid)\n\n        keys = np.array(jax.random.split(key, num=self.n_s))\n        summaries, derivatives = jax.vmap(get_derivatives)(keys[:self.n_d])\n        if self.n_s > self.n_d:\n            summaries = np.vstack([\n                summaries,\n                jax.vmap(partial(get_summary, \u03b8=self.\u03b8_fid))(keys[self.n_d:])])\n        return np.squeeze(summaries), np.squeeze(derivatives)\n    \n    \nimport jax\nimport jax.numpy as np\nfrom IMNN.experimental.jax.imnn import SimulatorIMNN\nfrom IMNN.experimental.jax.utils import value_and_jacrev, check_devices, \\\n    check_type, check_splitting\n\n\nclass AggregatedSimulatorIMNN(SimulatorIMNN):\n    def __init__(self, n_s, n_d, n_params, n_summaries, input_shape, \u03b8_fid,\n                 model, optimiser, key_or_state, simulator, devices,\n                 n_per_device, verbose=True):\n        super().__init__(\n            n_s=n_s,\n            n_d=n_d,\n            n_params=n_params,\n            n_summaries=n_summaries,\n            input_shape=input_shape,\n            \u03b8_fid=\u03b8_fid,\n            model=model,\n            key_or_state=key_or_state,\n            optimiser=optimiser,\n            simulator=simulator,\n            verbose=verbose)\n        self.devices = check_devices(devices)\n        self.n_devices = len(self.devices)\n        self.n_per_device = check_type(n_per_device, int, \"n_per_device\")\n        if self.n_s == self.n_d:\n            check_splitting(self.n_s, \"n_s and n_d\", self.n_devices,\n                            self.n_per_device)\n        else:\n            check_splitting(self.n_s, \"n_s\", self.n_devices, self.n_per_device)\n            check_splitting(self.n_d, \"n_d\", self.n_devices, self.n_per_device)\n\n    def get_summaries(self, w, key=None, validate=False):\n        def derivative_scan(counter, rng):\n            def get_device_summaries(rng):\n                def get_summary(key, \u03b8):\n                    return self.model(w, self.simulator(key, \u03b8))\n\n                def get_derivatives(rng):\n                    return value_and_jacrev(get_summary, argnums=1)(\n                        rng, self.\u03b8_fid)\n\n                keys = np.array(jax.random.split(rng, num=self.n_per_device))\n                return jax.vmap(get_derivatives)(keys)\n\n            keys = np.array(jax.random.split(rng, num=self.n_devices))\n            summaries, derivatives = jax.pmap(\n                get_device_summaries, devices=self.devices)(keys)\n            return counter, (summaries, derivatives)\n\n        def summary_scan(counter, rng):\n            def get_device_summaries(rng):\n                def get_summary(key):\n                    return self.model(w, self.simulator(key, self.\u03b8_fid))\n\n                keys = np.array(jax.random.split(rng, num=self.n_per_device))\n                return jax.vmap(get_summary)(keys)\n\n            keys = np.array(jax.random.split(rng, num=self.n_devices))\n            summaries = jax.pmap(\n                get_device_summaries, devices=self.devices)(keys)\n            return counter, summaries\n\n        n = self.n_d // (self.n_devices * self.n_per_device)\n        if self.n_s > self.n_d:\n            n_r = (self.n_s - self.n_d) // (self.n_devices * self.n_per_device)\n            key, *keys = jax.random.split(key, num=n_r + 1)\n            counter, remaining_summaries = jax.lax.scan(\n                summary_scan, n_r, np.array(keys))\n        keys = np.array(jax.random.split(key, num=n))\n        counter, results = jax.lax.scan(\n            derivative_scan, 0, keys)\n        summaries, derivatives = results\n        if self.n_s > self.n_d:\n            summaries = np.vstack([summaries, remaining_summaries])\n        return (summaries.reshape((-1, self.n_summaries)),\n                derivatives.reshape((-1, self.n_summaries, self.n_params)))\n\n\n```\n\n\n```python\nsimulator_args[\"squeeze\"] = False\n```\n\n\n```python\nsimulator_args['vol_norm'] = True\nsimulator_args['N_scale'] = True # false \nsimulator_args['L'] = 32.0\n```\n\n\n```python\nsimulator_args\n```\n\n\n\n\n    {'N': 32,\n     'L': 32.0,\n     'dim': 2,\n     'shape': (32, 32),\n     'vol_norm': True,\n     'N_scale': True,\n     'squeeze': False}\n\n\n\n\n```python\nIMNN = SimIMNN(\n        n_s=10000,\n        n_d=10000,\n        n_params=n_params,\n        n_summaries=n_summaries,\n        input_shape=input_shape,\n        \u03b8_fid=\u03b8_fid,\n        model=model,\n        optimiser=optimiser,\n        key_or_state=initial_model_key,\n        simulator=lambda rng, \u03b8: simulator(rng, \u03b8, simulator_args=simulator_args),\n#         devices=[jax.devices()[0]],\n#         n_per_device=1000\n        )\n```\n\n# Fit\n\n\n```python\n# new_optimiser = jax.experimental.optimizers.sgd(1e-5)\n# weights = np.load('./model/best_w.npy',  allow_pickle=True)\n# IMNN.opt_initialiser, IMNN.update, IMNN.get_parameters = optimiser\n# IMNN.state = IMNN.opt_initialiser(list(weights))\n```\n\n\n```python\n# SAVING IMNN ATTRIBUTES\nimport cloudpickle as pickle\nimport os\n\ndef save_weights(IMNN, folder_name='./model', weights='final'):\n    \n    # create output directory\n    if not os.path.exists(folder_name): \n        os.mkdir(folder_name)\n    \n    def pckl_me(obj, path):\n        with open(path, 'wb') as file_pi:\n            pickle.dump(obj, file_pi)\n        file_pi.close()\n        \n    # save IMNN (optimiser) state:\n    savestate = jax.experimental.optimizers.unpack_optimizer_state(IMNN.state)\n    pckl_me(savestate, os.path.join(folder_name, 'IMNN_state'))\n    \n    # save weights\n    if weights == 'final':\n        np.save(os.path.join(folder_name, 'final_w'), IMNN.final_w)\n    \n    else:\n        np.save(os.path.join(folder_name, 'best_w'), IMNN.best_w)\n        \n    # save initial weights\n    np.save(os.path.join(folder_name, 'initial_w'), IMNN.initial_w)\n        \n    # save training history\n    pckl_me(IMNN.history, os.path.join(folder_name, 'history'))\n    \n    # save important attributes as a dict\n    imnn_attributes = {\n        'n_s': IMNN.n_s,\n        'n_d': IMNN.n_d,\n        'input_shape': IMNN.input_shape,\n        'n_params' : IMNN.n_params,            \n        'n_summaries': IMNN.n_summaries,\n        '\u03b8_fid': IMNN.\u03b8_fid,\n        'F': IMNN.F,   \n        'validate': IMNN.validate,\n        'simulate': IMNN.simulate,\n        \n    }\n    \n    pckl_me(imnn_attributes, os.path.join(folder_name, 'IMNN_attributes'))\n    \n    print('saved weights and attributes to the file ', folder_name)\n    \n    \ndef load_weights(IMNN, folder_name='./model', weights='final', load_attributes=True):\n    \n    \n    def unpckl_me(path):\n        file = open(path, 'rb')\n        return pickle.load(file)\n    \n    # load and assign weights\n    if weights=='final':\n        weights = np.load(os.path.join(folder_name, 'final_w.npy'),  allow_pickle=True)\n        IMNN.final_w = weights\n    else:\n        weights = np.load(os.path.join(folder_name, 'best_w.npy'),  allow_pickle=True)\n        IMNN.best_w = weights\n        \n    # re-pack and load the optimiser state\n    loadstate = unpckl_me(os.path.join(folder_name, 'IMNN_state'))\n    IMNN.state = jax.experimental.optimizers.pack_optimizer_state(loadstate)\n    \n    \n    # load history\n    IMNN.history = unpckl_me(os.path.join(folder_name, 'history'))\n    \n    # load important attributes\n    if load_attributes:\n        IMNN.intial_w =  np.load(os.path.join(folder_name, 'initial_w.npy'), allow_pickle=True)\n        attributes = unpckl_me(os.path.join('test_model', 'IMNN_attributes'))\n        IMNN.\u03b8_fid = attributes['\u03b8_fid']\n        IMNN.n_s = attributes['n_s']\n        IMNN.n_d = attributes['n_d']\n        IMNN.input_shape = attributes['input_shape']\n        \n    print('loaded IMNN with these attributes: ', attributes)\n    \n```\n\n\n```python\n# # test save functions\n# save_weights(IMNN, folder_name='./model')\n\n# # test load functions\n\n# # initialize a new imnn with different attributes and then load the old file\n# # to overwrite them\n\n# my_new_IMNN = SimIMNN(\n#         n_s=300,\n#         n_d=100,\n#         n_params=n_params,\n#         n_summaries=n_summaries,\n#         input_shape=input_shape,\n#         \u03b8_fid=np.array([1.0,1.0]),\n#         key=initial_model_key,\n#         model=model,\n#         optimiser=optimiser,\n#         simulator=lambda rng, \u03b8: simulator(rng, \u03b8, simulator_args=simulator_args),\n#         )\n\n# load_weights(my_new_IMNN, folder_name='./model', load_attributes=True)\n# my_new_IMNN.set_F_statistics(rng, my_new_IMNN.best_w, my_new_IMNN.\u03b8_fid, my_new_IMNN.n_s, my_new_IMNN.n_d, validate=True)\n```\n\n\n```python\nIMNN_rngs = 1 * [fitting_key] #+ 12 * [None]\nlabels = [\n    \"Simulator, InceptNet\\n\"\n]\n```\n\n\n```python\n\u03b8_fid\n```\n\n\n\n\n    DeviceArray([1. , 0.5], dtype=float32)\n\n\n\n\n```python\n%%time\nfor i in range(1):\n    rng,fit_rng = jax.random.split(rng)\n    IMNN.fit(\u03bb=10., \u03f5=\u03f5, rng=fit_rng, min_iterations=500) #for IMNN, IMNN_rng in zip(IMNNs, IMNN_rngs);\n    \n#save_weights(IMNN, folder_name='./big_incept128')\n```\n\n    CPU times: user 3min 33s, sys: 5.17 s, total: 3min 38s\n    Wall time: 3min 53s\n\n\n\n```python\nIMNNs = [IMNN]\n```\n\n\n```python\nfor i, (IMNN, label) in enumerate(zip(IMNNs, labels)):\n    if i == 0:\n        ax = IMNN.training_plot(expected_detF=detf_expected, colour=\"C{}\".format(i), label=label)\n    elif i == 10:\n        other_ax = IMNN.training_plot(\n            expected_detF=detf_expected, colour=\"C{}\".format(i), label=label\n        )\n    elif i == 11:\n        IMNN.training_plot(\n            ax=other_ax,\n            expected_detF=50, colour=\"C{}\".format(i), label=label\n        )\n        other_ax[0].set_yscale(\"log\")\n        other_ax[2].set_yscale(\"log\")\n    else:\n        IMNN.training_plot(\n            ax=ax, expected_detF=None, colour=\"C{}\".format(i), label=label, ncol=5\n        );\nax[0].set_yscale(\"log\")\n```\n\n\n```python\nlatexify(fig_width=3.37)\nplt.plot(IMNN.history['detF'][:])\nplt.plot(np.ones(len(IMNN.history['detF'][:]))*detf_expected, c='k', linestyle='--')\nplt.ylim(1e-2, 1e7)\nplt.ylabel(r'$\\det \\textbf{F}$')\nplt.xlabel('number of epochs')\nplt.yscale('log')\nplt.tight_layout()\n#plt.savefig('/mnt/home/tmakinen/repositories/field-plots/128x128-training.png', dpi=400)\n```\n\n\n```python\nnp.linalg.det(IMNNs[0].F) #/ (detf_expected)\n```\n\n\n\n\n    DeviceArray(4931.314, dtype=float32)\n\n\n\n\n```python\nIMNNs[0].F\n```\n\n\n\n\n    DeviceArray([[ 167.05243, -124.48563],\n                 [-124.48561,  122.28488]], dtype=float32)\n\n\n\n\n```python\nprint('IMNN F:', IMNN.F)\n\nprint('IMNN det F:', np.linalg.det(IMNN.F))\n\nprint('IMNN F / analytic det F: ', (np.linalg.det(IMNN.F)) / detf_expected)\n```\n\n    IMNN F: [[ 167.05243 -124.48563]\n     [-124.48561  122.28488]]\n    IMNN det F: 4931.314\n    IMNN F / analytic det F:  1.0782399289654658\n\n\n# Data for ABC example\n\n\n```python\nclass uniform:\n    def __init__(self, low, high):\n        self.low = np.array(low)\n        self.high = np.array(high)\n        self.event_shape = [[] for i in range(self.low.shape[0])]\n    def sample(self, n=None, seed=None):\n        if n is None:\n            n = 1\n        keys = np.array(jax.random.split(\n            seed, \n            num=len(self.event_shape)))\n        return jax.vmap(\n            lambda key, low, high : jax.random.uniform(\n                key, \n                shape=(n,), \n                minval=low, \n                maxval=high))(\n            keys, self.low, self.high)\n\n```\n\n\n```python\nprior = uniform([0.1, 0.1], [1.25, 1.25])\n```\n\n\n```python\nsimulator_args\n```\n\n\n\n\n    {'N': 32,\n     'L': 32.0,\n     'dim': 2,\n     'shape': (32, 32),\n     'vol_norm': True,\n     'N_scale': True,\n     'squeeze': False}\n\n\n\n\n```python\nsimulator_args = {\"N\": N, \"L\": 32, \"dim\": dim, \"shape\": shape, \"N_scale\": True, \"vol_norm\": True, \"squeeze\": True}\n\nrng, key = jax.random.split(rng)\n\u03b8_target = np.array([0.8, 0.8])\ntarget_data = simulator(\n    key,\n    \u03b8_target,\n    simulator_args={**simulator_args, **{'squeeze':False}})\n```\n\n\n```python\n%matplotlib inline\nplt.imshow(np.squeeze(target_data))\nplt.colorbar()\n```\n\n# analytic likelihood calculation\n\n\n```python\ngridsize = 100                # for likelihood gridding\n\u0394 = np.fft.fftn(np.squeeze(target_data))[:N//2, :N//2] / N\nk = kbin[:N//2, :N//2]  \nprior_range = np.array([[0.1, 0.1], [1.25, 1.25]])\nAL = analyticFieldLikelihood(PBJ, shape, \u0394, prior_range, k=k, gridsize=gridsize, tiling=[5,5])\n```\n\n\n```python\n%%time\n%matplotlib inline\n#plt.style.use('default')\nlikelihood,_ = AL.plot_contours(\u03b8_ref=\u03b8_target, shift=None, xlabel=r'$A$', ylabel=r'$B$', return_like=True)\n```\n\n# Gaussian approximation\n\n\n```python\nIMNN.set_F_statistics(IMNN.best_w, key=rng, validate=True);\n```\n\n\n```python\n@jit #partial(jax.jit, static_argnums=0)\ndef get_estimate(d):\n    if len(d.shape) == 1:\n        return IMNN.\u03b8_fid + np.einsum(\n            \"ij,kj,kl,l->i\",\n            IMNN.invF,\n            IMNN.d\u03bc_d\u03b8,\n            IMNN.invC,\n            IMNN.model(IMNN.best_w, d, rng=rng) - IMNN.\u03bc)\n    else:\n        return IMNN.\u03b8_fid + np.einsum(\n            \"ij,kj,kl,ml->mi\",\n            IMNN.invF,\n            IMNN.d\u03bc_d\u03b8,\n            IMNN.invC,\n            IMNN.model(IMNN.best_w, d, rng=rng) - IMNN.\u03bc)\n```\n\n\n```python\nestimates = get_estimate(target_data) #[i.get_estimate(target_data) for i in IMNNs];\n```\n\n\n```python\ndetf_expected\n```\n\n\n\n\n    DeviceArray(4573.48483614, dtype=float64)\n\n\n\n\n```python\nGAs = [GaussianApproximation(get_estimate(target_data), IMNN.invF, prior)]\n       #GaussianApproximation(get_estimate(target_data), np.linalg.inv(f_expected), prior)]\n```\n\n\n```python\n%matplotlib inline\nfor i, (GA, label) in enumerate(zip(GAs, labels)):\n    if i == 0:\n        ax = GA.marginal_plot(\n            axis_labels=[r\"$A$\", r\"$B$\"], label='on-the-fly IMNN', colours=\"C{}\".format(i)\n        )\n    else:\n        GA.marginal_plot(ax=ax, label=label, colours=\"C{}\".format(i), ncol=8)\n```\n\n\n```python\nfig, ax = plt.subplots(2, 6, figsize=(30, 8))\nfor i, (GA, label) in enumerate(zip(GAs, labels)):\n    if i == 0:\n        ax1 = GA.marginal_plot(\n            ax=ax[:, :2],\n            axis_labels=[r\"$A$\", r\"$B$\"],\n            label=label,\n            target=0,\n            format=True,\n            colours=\"C{}\".format(i),\n        )\n        ax2 = GA.marginal_plot(\n            ax=ax[:, 2:4],\n            axis_labels=[r\"$A$\", r\"$B$\"],\n            target=1,\n            format=True,\n            colours=\"C{}\".format(i),\n        )\n        ax3 = GA.marginal_plot(\n            ax=ax[:, 4:],\n            axis_labels=[r\"$A$\", r\"$B$\"],\n            target=2,\n            format=True,\n            colours=\"C{}\".format(i),\n        )\n    else:\n        GA.marginal_plot(ax=ax1, label=label, target=0, colours=\"C{}\".format(i), bbox_to_anchor=(-0.05, 1.0))\n        GA.marginal_plot(ax=ax2, target=1, colours=\"C{}\".format(i))\n        GA.marginal_plot(ax=ax3, target=2, colours=\"C{}\".format(i))\n```\n\n# ABC\n\n\n```python\n{**simulator_args, **{'squeeze':True}}\n```\n\n\n\n\n    {'N': 32,\n     'L': 32,\n     'dim': 2,\n     'shape': (32, 32),\n     'N_scale': True,\n     'vol_norm': True,\n     'squeeze': True}\n\n\n\n\n```python\nABC = ApproximateBayesianComputation(\n        target_data, prior, \n     lambda A,B : simulator(A,B, simulator_args={**simulator_args, **{'squeeze':True}}), \n                                       get_estimate, F=IMNN.F, gridsize=50\n    )\n```\n\n\n```python\nABCs = [\n    ApproximateBayesianComputation(\n        target_data, prior, simulator, IMNN.get_estimate, F=IMNN.F, gridsize=50\n    )\n    for IMNN, estimate in zip(IMNNs, estimates)\n]\n```\n\n\n```python\n%%time\nrng,abc_key = jax.random.split(rng)\nABC(rng=abc_key,\n        n_samples=int(1e3),\n        min_accepted=15000,\n        max_iterations=20000,\n        \u03f5=0.05,\n        smoothing=0.);\n```\n\n    1721 accepted in last  20000 iterations  (20000000 simulations done).\n    CPU times: user 39.3 s, sys: 1.38 s, total: 40.7 s\n    Wall time: 43.5 s\n\n\n\n\n\n    (<IMNN.experimental.jax.utils.container.container at 0x1553b43846d8>,\n     <IMNN.experimental.jax.utils.container.container at 0x1553b4384780>,\n     <IMNN.experimental.jax.utils.container.container at 0x1553b44a1ac8>)\n\n\n\n\n```python\nABC.parameters.accepted[0].shape\n```\n\n\n\n\n    (1721, 2)\n\n\n\n\n```python\n#ax = ABC.scatter_plot(points=ABC.parameters.rejected, colours='red')\nax = ABC.scatter_plot()\n```\n\n\n```python\n#np.save(\"accepted.npy\", ABC.parameters.accepted)\n```\n\n\n```python\n#ax = ABC.scatter_summaries(points=ABC.summaries.rejected, colours='red')\nABC.scatter_summaries( colours='blue')\n```\n\n\n```python\nlikelihood,A_range,B_range = AL.get_likelihood(return_grid=True)\n```\n\n    computing likelihood on a 100x100 grid \n             in tiles of size 20x20\n    shift -363.20173823094433\n    loglike mean -431.7857921416365\n\n\n\n```python\n#A_range = np.linspace(0.1, 3.0, 25)\n#B_range = np.linspace(0.1, 2.5, 25)\nlikelihoodA = np.real(likelihood).sum(0)\nlikelihoodA /= likelihoodA.sum() * (A_range[1] -  A_range[0])\nlikelihoodB = np.real(likelihood).sum(1)\nlikelihoodB /= likelihoodB.sum() * (B_range[1] -  B_range[0])\nsorted_marginal = np.sort(np.real(likelihood).flatten())[::-1]\ncdf = np.cumsum(sorted_marginal / sorted_marginal.sum())\nvalue = []\nfor level in [0.95, 0.68]:\n    this_value = sorted_marginal[np.argmin(np.abs(cdf - level))]\n    if len(value) == 0:\n        value.append(this_value)\n    elif this_value <= value[-1]:\n        break\n    else:\n        value.append(this_value)\n#fig, ax = plt.subplots(2, 2, figsize=(10, 10))\n\n```\n\n\n```python\n%matplotlib inline\n#plt.style.use('default')\nnew_colors = [ '#2c0342', '#286d87', '#4fb49d', '#9af486']\nfig,ax = plt.subplots(nrows=2, ncols=2, figsize=(3.37*2, 3.37*2))\nlatexify(fig_width=3.37, fig_height=3.37)\n\nABC.scatter_plot(ax=ax,\n                      colours=new_colors[0], \n                      axis_labels=[r\"$A$\", r\"$B$\"], \n                      s=8,\n                      label='ABC estimate')\n# ABC.marginal_plot(ax=ax,\n#             axis_labels=[r\"$A$\", r\"$B$\"], colours='green',\n#             label='ABC marginal plot')\n\n\nGAs[0].marginal_plot(ax=ax, colours=new_colors[2], axis_labels=[r\"$A$\", r\"$B$\"], label=None, ncol=1)\nax[0,1].imshow(target_data[0, 0])\n\n#ax[0,1].set_title(r'$\\theta_{\\rm target} = A,B = (%.2f,%.2f)$'%(\u03b8_target[0], \u03b8_target[1]))\n\nax[0,0].axvline(\u03b8_target[0], linestyle='--', c='k')\nax[1,0].axvline(\u03b8_target[0], linestyle='--', c='k')\nax[1,0].axhline(\u03b8_target[1], linestyle='--', c='k')\nax[1,1].axhline(\u03b8_target[1], linestyle='--', c='k', label=r'$\\theta_{\\rm target}$')\n\nax[1,0].set_xlabel(r'$A$')\nax[1,0].set_ylabel(r'$B$')\n\nax[0,0].axvline(\u03b8_fid[0], linestyle='--', c='k', alpha=0.4)\n#ax[1,0].contourf(A_range, B_range, L1.reshape((size, size)))\n#ax[0, 0].plot(A_range, np.real(loglikeA), color='g', label='loglikeA')\n\nax[1,0].axvline(\u03b8_fid[0], linestyle='--', c='k', alpha=0.4)\nax[1,0].axhline(\u03b8_fid[1], linestyle='--', c='k', alpha=0.4)\nax[1,1].axhline(\u03b8_fid[1], linestyle='--', c='k', alpha=0.4, label=r'$\\theta_{\\rm fid}$')\n\nax[1,1].legend(framealpha=0.)\n\n\n# add in the likelihood estimate\nax[0, 0].plot(A_range, likelihoodA, color='#FF8D33', label=None)\nax[0, 1].axis(\"off\")\nax[1, 0].contour(A_range, B_range, np.real(likelihood), levels=value, colors='#FF8D33')\nax[1, 1].plot(likelihoodB, B_range, color='#FF8D33', label='loglike')\n\nax[0,0].legend(framealpha=0.)\n\n#plt.savefig('/mnt/home/tmakinen/repositories/field-plots/128x128-contours.png', dpi=400)\n#plt.subplots_adjust(wspace=0, hspace=0)\nplt.show()\n```\n\n\n```python\n# do PMC-ABC\nimport tensorflow_probability\ntfp = tensorflow_probability.experimental.substrates.jax\ntfd = tfp.distributions\ntfb = tfp.bijectors\n```\n\n\n```python\ndef new_ABC(rng, n_points, proposal_distribution, simulator, data_summary, f, n_parallel_simulations=None, simulator_parameters=None):\n    def get_distance(summaries, data_summary, f):\n        if len(data_summary.shape) > 1:\n            return jax.vmap(lambda data_summary, f : get_distance(summaries, data_summary, f))(data_summary, f)\n        if len(summaries.shape) == 1:\n            difference = summaries - data_summary\n            distance = difference.dot(f).dot(difference)\n            return jax.lax.cond(np.isnan(distance), lambda _ : np.inf, lambda distance : distance, distance)\n        elif len(summaries.shape) == 2:\n            return jax.vmap(lambda summaries : get_distance(summaries, data_summary, f), out_axes=-1)(summaries)\n        else:\n            return jax.vmap(lambda summaries : get_distance(summaries, data_summary, f), out_axes=-2)(summaries)\n    shape = (n_points,)\n    if n_parallel_simulations is not None:\n        shape = shape + (n_parallel_simulations,)\n    rng, key = jax.random.split(rng)\n    proposed = proposal_distribution.sample(shape, seed=key)\n    key = jax.random.split(rng, num=np.prod(np.array(proposed).shape[:-1]))\n    summaries = simulator(key.reshape(proposed.shape[:-1] + (2,)), proposed, simulator_parameters=simulator_parameters)\n    distances = get_distance(summaries, data_summary, f)\n    return proposed, summaries, distances\n```\n\n\n```python\ndef w_cov(proposed, weighting):\n    weighted_samples = proposed * weighting[:, np.newaxis]\n    return weighted_samples.T.dot(weighted_samples) / weighting.T.dot(weighting)\n```\n\n\n```python\nclass tmvn():\n    def __init__(self, loc, scale, low, high, max_counter=int(1e3)):\n        self.loc = loc\n        self.scale = scale\n        self.low = low\n        self.high = high\n        if len(loc.shape) > 1:\n            self.n_samples = loc.shape[0]\n        else:\n            self.n_samples = None\n        self.n_params = low.shape[0]\n        self.max_counter = max_counter\n\n    def mvn(self, rng, loc):\n        u = jax.random.normal(rng, shape=(self.n_params,))\n        return loc + u.dot(self.scale)\n\n    def w_cond(self, args):\n        _, loc, counter = args\n        return np.logical_and(\n            np.logical_or(\n                np.any(np.greater(loc, self.high)),\n                np.any(np.less(loc, self.low))),\n            np.less(counter, self.max_counter))\n\n    def __sample(self, args):\n        rng, loc, counter = args\n        rng, key = jax.random.split(rng)\n        return (rng, self.mvn(key, loc), counter+1)\n\n    def _sample(self, rng, loc):\n        rng, key = jax.random.split(rng)\n        _, loc, counter = jax.lax.while_loop(\n            self.w_cond, \n            self.__sample, \n            (rng, self.mvn(key, loc), 0))\n        return jax.lax.cond(\n            np.greater_equal(counter, self.max_counter),\n            lambda _ : np.nan * np.ones((self.n_params,)),\n            lambda _ : loc,\n            None)\n\n    def _sample_n(self, rng, loc, n=None):\n        if n is None:\n            return self._sample(rng, loc)\n        else:\n            key = jax.random.split(rng, num=n)\n            return jax.vmap(self._sample)(key, \n                np.repeat(loc[np.newaxis], n, axis=0))\n\n    def sample(self, shape=None, seed=None):\n        if shape is None:\n            if self.n_samples is None:\n                return self._sample_n(seed, self.loc)\n            else:\n                key = jax.random.split(seed, num_self.n_samples)\n                return jax.vmap(lambda key, loc : self._sample_n(key, loc))(key, self.loc)\n        elif len(shape) == 1:\n            if self.n_samples is None:\n                return self._sample_n(seed, self.loc, n=shape[0])\n            else:\n                key = jax.random.split(seed, num_self.n_samples)\n                return jax.vmap(lambda key, loc : self._sample_n(key, loc, n=shape[0]))(key, self.loc)\n        else:\n            key = jax.random.split(seed, num=shape[-1])\n            return jax.vmap(lambda key: self.sample(shape=tuple(shape[:-1]), seed=key), out_axes=-2)(key)\n```\n\n\n```python\ndef PMC(rng, n_initial_points, n_points, prior, simulator, data_summary, f, percentile=75, acceptance_ratio=0.1, \n        max_iteration=10, max_acceptance=10, max_samples=int(1e3), n_parallel_simulations=None, simulator_parameters=None):\n    low = np.array([dist.low for dist in prior.distributions])\n    high = np.array([dist.high for dist in prior.distributions])\n    def single_PMC(rng, samples, summaries, distances, weighting, data_summary, f):\n        def single_iteration_condition(args):\n            return np.logical_and(\n                np.greater(args[-3], acceptance_ratio),\n                np.less(args[-2], max_iteration))\n        def single_iteration(args):\n            def single_acceptance_condition(args):\n                return np.logical_and(\n                    np.less(args[-2], 1),\n                    np.less(args[-1], max_acceptance))\n            def single_acceptance(args):\n                rng, loc, summ, dist, draws, accepted, acceptance_counter = args\n                #rng, loc, summ, dist, draws, rejected, acceptance_counter = args\n                rng, key = jax.random.split(rng)\n                proposed, summaries, distances = new_ABC(\n                    key, None, tmvn(loc, scale, low, high, max_counter=max_samples),\n                    simulator, data_summary, f, n_parallel_simulations=n_parallel_simulations,\n                    simulator_parameters=simulator_parameters)\n                if n_parallel_simulations is not None:\n                    min_distance_index = np.argmin(distances)\n                    min_distance = distances[min_distance_index]\n                    closer = np.less(min_distance, \u03f5)\n                    loc = jax.lax.cond(closer, lambda _ : proposed[min_distance_index], lambda _ : loc, None)\n                    summ = jax.lax.cond(closer, lambda _ : summaries[min_distance_index], lambda _ : summ, None)\n                    dist = jax.lax.cond(closer, lambda _ : distances[min_distance_index], lambda _ : dist, None)\n                    iteration_draws = n_parallel_simulations - np.isinf(distances).sum()\n                    draws += iteration_draws \n                    accepted = closer.sum()\n                    #rejected = iteration_draws - closer.sum()\n                else:\n                    closer = np.less(distances, dist)\n                    loc = jax.lax.cond(closer, lambda _ : proposed, lambda _ : loc, None)\n                    summ = jax.lax.cond(closer, lambda _ : summaries, lambda _ : summ, None)\n                    dist = jax.lax.cond(closer, lambda _ : distances, lambda _ : dist, None)\n                    iteration_draws = 1 - np.isinf(distances).sum()\n                    draws += iteration_draws\n                    accepted = closer.sum()\n                    #rejected = iteration_draws - closer.sum()\n                return (rng, loc, summ, dist, draws, accepted, acceptance_counter+1)\n                #return (rng, loc, summ, dist, draws, rejected, acceptance_counter+1)\n\n            rng, samples, summaries, distances, weighting, data_summary, f, acceptance_reached, iteration_counter, total_draws = args\n            \u03f5 = distances[\u03f5_ind]\n            loc = samples[\u03f5_ind:]\n            cov = w_cov(samples, weighting)\n            inv_cov = np.linalg.inv(cov)\n            scale = np.linalg.cholesky(cov)\n            rng, *key = jax.random.split(rng, num=loc.shape[0]+1)\n            draws = np.zeros(loc.shape[0], dtype=np.int32)\n            accepted = np.zeros(loc.shape[0], dtype=np.int32)\n            #rejected = np.zeros(loc.shape[0], dtype=np.int32)\n            acceptance_counter = np.zeros(loc.shape[0], dtype=np.int32)\n\n            results = jax.vmap(\n                lambda key, loc, summaries, distances, draws, accepted, acceptance_counter : jax.lax.while_loop(\n                #lambda key, loc, summaries, distances, draws, rejected, acceptance_counter : jax.lax.while_loop(\n                    single_acceptance_condition, single_acceptance, (key, loc, summaries, distances, draws, accepted, acceptance_counter)))(\n                    #single_acceptance_condition, single_acceptance, (key, loc, summaries, distances, draws, rejected, acceptance_counter)))(\n                np.array(key), loc, summaries[\u03f5_ind:], distances[\u03f5_ind:], draws, accepted, acceptance_counter)\n                #np.array(key), loc, summaries[\u03f5_ind:], distances[\u03f5_ind:], draws, rejected, acceptance_counter)\n\n            weighting = jax.vmap(\n                lambda proposed : (\n                    prior.prob(proposed) \n                    / (np.sum(weighting * tfd.MultivariateNormalTriL(\n                        loc=samples,\n                        scale_tril=np.repeat(\n                            scale[np.newaxis], \n                            samples.shape[0], \n                            axis=0)).prob(proposed)))))(\n                    np.vstack([samples[:\u03f5_ind], results[1]]))\n            samples = jax.ops.index_update(samples, jax.ops.index[\u03f5_ind:, :], results[1])\n            summaries = jax.ops.index_update(summaries, jax.ops.index[\u03f5_ind:, :], results[2])\n            distances = jax.ops.index_update(distances, jax.ops.index[\u03f5_ind:], results[3])\n            acceptance_reached = results[-2].sum() / results[-3].sum()\n            return (rng, samples, summaries, distances, weighting, data_summary, f, acceptance_reached, iteration_counter+1, total_draws+results[-3].sum())\n\n        acceptance_reached = np.inf\n        iteration_counter = 0\n        total_draws = 0\n        results = jax.lax.while_loop(\n            single_iteration_condition, \n            single_iteration, \n            (rng, samples, summaries, distances, weighting, data_summary, f, acceptance_reached, iteration_counter, total_draws))\n        return results[1], results[2], results[3], results[4], results[7], results[8], results[9]\n\n    rng, key = jax.random.split(rng)\n    proposed, summaries, distances = new_ABC(\n        key, n_initial_points, prior, simulator, data_summary, f, \n        n_parallel_simulations=n_parallel_simulations, simulator_parameters=simulator_parameters)\n\n    if n_parallel_simulations is not None:\n        proposed = proposed.reshape((n_initial_points * n_parallel_simulations, -1))\n        summaries = summaries.reshape((n_initial_points * n_parallel_simulations, -1))\n        if len(data_summary.shape) > 1:\n            distances = distances.reshape((data_summary.shape[0], -1))\n        else:\n            distances = distances.reshape((-1,))\n\n    if len(data_summary.shape) == 1:\n        sample_indices = np.argsort(distances)[:n_points]\n        samples = proposed[sample_indices]\n        summaries = summaries[sample_indices]\n        distances = distances[sample_indices]\n    else:\n        sample_indices = np.argsort(distances, axis=1)[:, :n_points]\n        samples = jax.vmap(lambda x: proposed[x])(sample_indices)\n        summaries = jax.vmap(lambda x: summaries[x])(sample_indices)\n        distances = np.take_along_axis(distances, sample_indices, axis=1)    \n\n    weighting = prior.prob(samples)\n\n    if percentile is None:\n        \u03f5_ind = -1\n        to_accept = 1\n    else:\n        \u03f5_ind = int(percentile / 100 * n_points)\n        to_accept = n_points - \u03f5_ind\n\n    if len(data_summary.shape) == 1:\n        return single_PMC(rng, samples, summaries, distances, weighting, data_summary, f)\n    else:\n        key = jax.random.split(rng, num=data_summary.shape[0])\n        return jax.vmap(single_PMC)(key, samples, summaries, distances, weighting, data_summary, f)\n```\n\n\n```python\ntarge_data_summary = get_estimate(target_data)\n```\n\n\n```python\nlow = np.array([0.1, 0.1])\nhigh = np.array([2., 2.])\nmyprior = tfd.Blockwise([tfd.Uniform(low=low[i], high=high[i]) for i in range(low.shape[0])])\n```\n\n\n```python\nrng, key = jax.random.split(rng)\nppmc_prop, ppmc_summ, ppmc_dist, ppmc_w, ppmc_crit, ppmc_it, ppmc_draws = PMC(\n    rng=key, n_initial_points=1000, n_points=250, prior=myprior, simulator=simulator, \n    data_summary=targe_data_summary, f=IMNN.F, percentile=75, acceptance_ratio=0.5, \n    max_iteration=int(1e2), max_acceptance=int(1e3), max_samples=int(1e3), \n    n_parallel_simulations=100, simulator_parameters=(low, high, input_shape))\n```\n\n\n```python\n# Create figures in Python that handle LaTeX, and save images to files in my\n# preferred formatting. I typically place this code in the root of each of my\n# projects, and import using:\n# from latexify import *\n# which will also run the latexify() function on the import.\n\n# Based on code from https://nipunbatra.github.io/blog/2014/latexify.html\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom math import sqrt\n\n#Back-end to use depends on the system\nfrom matplotlib.backends.backend_pgf import FigureCanvasPgf\nmatplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf)\n# matplotlib.use('pgf')\n# from matplotlib.backends.backend_pgf import FigureCanvasPgf\n# matplotlib.backend_bases.register_backend('ps', FigureCanvasPgf)\n\nimport seaborn as sns\nsns.set_style(\"white\")\n\n#my preferred palette. From\n#https://seaborn.pydata.org/tutorial/color_palettes.html: \"The cubehelix color\n#palette system makes sequential palettes with a linear increase or decrease in\n#brightness and some variation in hue. This means that the information in your\n#colormap will be preserved when converted to black and white (for printing) or\n#when viewed by a colorblind individual.\"\n\n# I typically set the number of colors (below, 8) to the distinct colors I need\n# in a given plot, so as to use the full range.\nsns.set_palette(sns.color_palette(\"cubehelix\", 8))\n\n\n# The following is the latexify function. It allows you to create 2 column or 1\n# column figures. You may also wish to alter the height or width of the figure.\n# The default settings are good for most cases. You may also change the\n# parameters such as labelsize and fontsize based on your classfile.\ndef latexify(fig_width=None, fig_height=None, columns=1):\n    \"\"\"Set up matplotlib's RC params for LaTeX plotting.\n    Call this before plotting a figure.\n    Parameters\n    ----------\n    fig_width : float, optional, inches\n    fig_height : float,  optional, inches\n    columns : {1, 2}\n    \"\"\"\n\n    # code adapted from http://www.scipy.org/Cookbook/Matplotlib/LaTeX_Examples\n    # Width and max height in inches for IEEE journals taken from\n    # computer.org/cms/Computer.org/Journal%20templates/transactions_art_guide.pdf\n\n    assert(columns in [1, 2])\n\n    if fig_width is None:\n        fig_width = 6.9 if columns == 1 else 13.8  # width in inches #3.39\n\n    if fig_height is None:\n        golden_mean = (sqrt(5) - 1.0) / 2.0    # Aesthetic ratio\n        fig_height = fig_width * golden_mean  # height in inches\n\n    MAX_HEIGHT_INCHES = 16.0\n    if fig_height > MAX_HEIGHT_INCHES:\n        print((\"WARNING: fig_height too large:\" + fig_height +\n              \"so will reduce to\" + MAX_HEIGHT_INCHES + \"inches.\"))\n        fig_height = MAX_HEIGHT_INCHES\n\n    params = {\n            # 'backend': 'ps',\n           #   'pgf.rcfonts': False,\n           #   'pgf.preamble': ['\\\\usepackage{gensymb}', '\\\\usepackage[dvipsnames]{xcolor}'],\n           #   \"pgf.texsystem\": \"pdflatex\",\n             # 'text.latex.preamble': ['\\\\usepackage{gensymb}', '\\\\usepackage[dvipsnames]{xcolor}'],\n              'text.latex.preamble': '\\\\usepackage{mathptmx}',\n              #values below are useful defaults. individual plot fontsizes are\n              #modified as necessary.\n              'axes.labelsize': 8,  # fontsize for x and y labels\n              'axes.titlesize': 8,\n              'font.size': 8,\n              'legend.fontsize': 8,\n              'xtick.labelsize': 6,\n              'ytick.labelsize': 6,\n              'text.usetex': True,\n              'figure.figsize': [fig_width, fig_height],\n              'font.family': 'serif',\n              'font.serif': 'Times',\n               'lines.linewidth': 1.5,\n               'lines.markersize':1,\n               'xtick.major.pad' : 2,\n               'ytick.major.pad' : 2,\n                'axes.xmargin' :  .0,  # x margin.  See `axes.Axes.margins`\n                'axes.ymargin' : .0,  # y margin See `axes.Axes.margins`\n              }\n\n    matplotlib.rcParams.update(params)\n\ndef saveimage(name, fig = plt, extension = 'pdf', folder = 'plots/'):\n    sns.despine()\n\n    #Minor ticks off by default in matplotlib\n    # plt.minorticks_off()\n\n    #grid being off is the default for seaborn white style, so not needed.\n    # plt.grid(False, axis = \"x\")\n    # plt.grid(False, axis = \"y\")\n    \n    fig.savefig('{}{}.{}'.format(folder,name, extension), bbox_inches = 'tight')\n\nlatexify()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "0eda457d8d79d35cc323fe3205f9a6ab4187c801", "size": 597083, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "fields/2D fields demo.ipynb", "max_stars_repo_name": "tlmakinen/kosmo-kompress", "max_stars_repo_head_hexsha": "2282e20d26dfc523e5705c0e02e0524b639df8a4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-07-16T05:22:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T12:41:06.000Z", "max_issues_repo_path": "fields/2D fields demo.ipynb", "max_issues_repo_name": "tlmakinen/FieldIMNNs", "max_issues_repo_head_hexsha": "1b363559116136d276b7c085b56a80520a7b0830", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fields/2D fields demo.ipynb", "max_forks_repo_name": "tlmakinen/FieldIMNNs", "max_forks_repo_head_hexsha": "1b363559116136d276b7c085b56a80520a7b0830", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 183.8875885433, "max_line_length": 100996, "alphanum_fraction": 0.8593662858, "converted": true, "num_tokens": 26979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.060086647228542, "lm_q1q2_score": 0.02561623513731127}}
{"text": "```python\npip install cirq\n```\n\n    Requirement already satisfied: cirq in /usr/local/lib/python3.7/dist-packages (0.13.1)\n    Requirement already satisfied: cirq-web==0.13.1 in /usr/local/lib/python3.7/dist-packages (from cirq) (0.13.1)\n    Requirement already satisfied: cirq-core==0.13.1 in /usr/local/lib/python3.7/dist-packages (from cirq) (0.13.1)\n    Requirement already satisfied: cirq-google==0.13.1 in /usr/local/lib/python3.7/dist-packages (from cirq) (0.13.1)\n    Requirement already satisfied: cirq-aqt==0.13.1 in /usr/local/lib/python3.7/dist-packages (from cirq) (0.13.1)\n    Requirement already satisfied: cirq-ionq==0.13.1 in /usr/local/lib/python3.7/dist-packages (from cirq) (0.13.1)\n    Requirement already satisfied: cirq-pasqal==0.13.1 in /usr/local/lib/python3.7/dist-packages (from cirq) (0.13.1)\n    Requirement already satisfied: cirq-rigetti==0.13.1 in /usr/local/lib/python3.7/dist-packages (from cirq) (0.13.1)\n    Requirement already satisfied: requests~=2.18 in /usr/local/lib/python3.7/dist-packages (from cirq-aqt==0.13.1->cirq) (2.23.0)\n    Requirement already satisfied: numpy~=1.16 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (1.21.5)\n    Requirement already satisfied: matplotlib~=3.0 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (3.2.2)\n    Requirement already satisfied: duet~=0.2.0 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (0.2.3)\n    Requirement already satisfied: sortedcontainers~=2.0 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (2.4.0)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (1.7.3)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (3.10.0.2)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (4.62.3)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (1.7.1)\n    Requirement already satisfied: networkx~=2.4 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (2.6.3)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (1.3.5)\n    Requirement already satisfied: google-api-core[grpc]<2.0.0dev,>=1.14.0 in /usr/local/lib/python3.7/dist-packages (from cirq-google==0.13.1->cirq) (1.26.3)\n    Requirement already satisfied: protobuf>=3.13.0 in /usr/local/lib/python3.7/dist-packages (from cirq-google==0.13.1->cirq) (3.17.3)\n    Requirement already satisfied: pyjwt~=1.7.1 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (1.7.1)\n    Requirement already satisfied: rfc3339~=6.2 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (6.2)\n    Requirement already satisfied: h11~=0.9.0 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (0.9.0)\n    Requirement already satisfied: httpcore~=0.11.1 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (0.11.1)\n    Requirement already satisfied: qcs-api-client~=0.8.0 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (0.8.0)\n    Requirement already satisfied: certifi~=2021.5.30 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (2021.5.30)\n    Requirement already satisfied: iso8601~=0.1.14 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (0.1.16)\n    Requirement already satisfied: toml~=0.10.2 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (0.10.2)\n    Requirement already satisfied: httpx~=0.15.5 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (0.15.5)\n    Requirement already satisfied: pydantic~=1.8.2 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (1.8.2)\n    Requirement already satisfied: pyquil~=3.0.0 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (3.0.1)\n    Requirement already satisfied: idna~=2.10 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (2.10)\n    Requirement already satisfied: six~=1.16.0 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (1.16.0)\n    Requirement already satisfied: retrying~=1.3.3 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (1.3.3)\n    Requirement already satisfied: attrs~=20.3.0 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (20.3.0)\n    Requirement already satisfied: python-dateutil~=2.8.1 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (2.8.2)\n    Requirement already satisfied: sniffio~=1.2.0 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (1.2.0)\n    Requirement already satisfied: rfc3986~=1.5.0 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (1.5.0)\n    Requirement already satisfied: google-auth<2.0dev,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (1.35.0)\n    Requirement already satisfied: googleapis-common-protos<2.0dev,>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (1.54.0)\n    Requirement already satisfied: pytz in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (2018.9)\n    Requirement already satisfied: setuptools>=40.3.0 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (57.4.0)\n    Requirement already satisfied: packaging>=14.3 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (21.3)\n    Requirement already satisfied: grpcio<2.0dev,>=1.29.0 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (1.43.0)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (0.2.8)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (4.8)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (4.2.4)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core==0.13.1->cirq) (0.11.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core==0.13.1->cirq) (1.3.2)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core==0.13.1->cirq) (3.0.7)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (0.4.8)\n    Requirement already satisfied: rpcq<4.0.0,>=3.6.0 in /usr/local/lib/python3.7/dist-packages (from pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (3.9.2)\n    Requirement already satisfied: lark<0.12.0,>=0.11.1 in /usr/local/lib/python3.7/dist-packages (from pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (0.11.3)\n    Requirement already satisfied: importlib-metadata<4.0.0,>=3.7.3 in /usr/local/lib/python3.7/dist-packages (from pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (3.10.1)\n    Requirement already satisfied: retry<0.10.0,>=0.9.2 in /usr/local/lib/python3.7/dist-packages (from pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (0.9.2)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata<4.0.0,>=3.7.3->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (3.7.0)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests~=2.18->cirq-aqt==0.13.1->cirq) (3.0.4)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests~=2.18->cirq-aqt==0.13.1->cirq) (1.24.3)\n    Requirement already satisfied: py<2.0.0,>=1.4.26 in /usr/local/lib/python3.7/dist-packages (from retry<0.10.0,>=0.9.2->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (1.11.0)\n    Requirement already satisfied: decorator>=3.4.2 in /usr/local/lib/python3.7/dist-packages (from retry<0.10.0,>=0.9.2->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (4.4.2)\n    Requirement already satisfied: pyzmq>=17 in /usr/local/lib/python3.7/dist-packages (from rpcq<4.0.0,>=3.6.0->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (22.3.0)\n    Requirement already satisfied: python-rapidjson in /usr/local/lib/python3.7/dist-packages (from rpcq<4.0.0,>=3.6.0->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (1.5)\n    Requirement already satisfied: msgpack<1.0,>=0.6 in /usr/local/lib/python3.7/dist-packages (from rpcq<4.0.0,>=3.6.0->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (0.6.2)\n    Requirement already satisfied: ruamel.yaml in /usr/local/lib/python3.7/dist-packages (from rpcq<4.0.0,>=3.6.0->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (0.17.21)\n    Requirement already satisfied: ruamel.yaml.clib>=0.2.6 in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml->rpcq<4.0.0,>=3.6.0->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (0.2.6)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->cirq-core==0.13.1->cirq) (1.2.1)\n\n\n\n```python\n#importing required libraries\nimport cirq\nimport numpy as np\nimport scipy as sp\nimport random\nimport time\n```\n\n\n```python\n# Custom function used to respresent a a set of bits in string format\ndef bitstring(bits):\n    return ''.join(str(int(b)) for b in bits)\n```\n\n\n```python\ndef bnv_circuit(qubits):\n\n  # Generating secret number that needs to be encoded by the oracle\n  a=[random.randint(0, 1) for _ in range(qubits)]\n  # Generating the random bit in the function  f(x) = ax+b\n  b = random.randint(0, 1)\n\n  # initializing the circuit in Cirq \n  c = cirq.Circuit()\n\n  # Defining number of qubits in the circuit\n  lines=cirq.LineQubit.range(qubits+1)\n\n  # Segregating input and output qubits\n  input_qubits=lines[:qubits]\n  output_qubit = lines[-1]\n\n  # Applying H gate for superposition\n  c.append([cirq.X(output_qubit),cirq.H(output_qubit),cirq.H.on_each(*input_qubits)])\n\n  # defining the orale function of the circuit\n  def oracle(a,b,c):\n    #Initalizing CNOT gates for qubits that hold value |1>\n    if b:\n      c.append(cirq.X(output_qubit))\n    for i,encoded in zip(input_qubits, a):\n      if (encoded):\n        c.append(cirq.CNOT(i,output_qubit))\n  \n  oracle(a,b,c)\n\n  # Measuring the result in H basis\n  c.append([cirq.H.on_each(*input_qubits), cirq.measure(*input_qubits, key='result')])\n  \n  # Displaying oracle function for cross verification\n  print(\n    'Secret function:\\nf(x) = a\u00b7<{}> + {} (mod 2)'.format(\n        ', '.join(str(e) for e in a), b\n    ))\n  \n  return c\n  \n\n```\n\n\n```python\nc= bnv_circuit(6)\n```\n\n    Secret function:\n    f(x) = a\u00b7<1, 0, 0, 0, 0, 1> + 0 (mod 2)\n\n\n\n```python\nc\n```\n\n\n\n\n<pre style=\"overflow: auto; white-space: pre;\">0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M(&#x27;result&#x27;)\u2500\u2500\u2500\n              \u2502           \u2502\n1: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n              \u2502           \u2502\n2: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n              \u2502           \u2502\n3: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n              \u2502           \u2502\n4: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n              \u2502           \u2502\n5: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n              \u2502   \u2502\n6: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500</pre>\n\n\n\n\n```python\n# Function defined to run simulation of the ciruit above &\n# To determine the most common bitstring that is determined by the circuit after performing a couple of simulations of the circuit.\ndef run_simulation(c,run_count):\n  simulator = cirq.Simulator()\n  result = simulator.run(c, repetitions=run_count)\n  frequencies = result.histogram(key='result', fold_func=bitstring)\n  print(f'Sampled results:\\n{frequencies}')\n\n  # Check if we actually found the secret value.\n  most_common_bitstring = frequencies.most_common(1)[0][0]\n\n```\n\n\n```python\n# Running the algorithm by altering the circuit for varied values of n, where n represents number of qubits & \n# Capturing time taken for the algorithm to run for each value of n\nl=[]\nfor i in range(2,20):\n  st=time.time()\n  c=bnv_circuit(i)\n  print(c)\n  run_simulation(c,1024)\n  end=time.time()\n  l.append(end-st)\n\n\n\n```\n\n    Secret function:\n    f(x) = a\u00b7<0, 1> + 1 (mod 2)\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                              \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502\n    2: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'01': 1024})\n    Secret function:\n    f(x) = a\u00b7<0, 0, 1> + 1 (mod 2)\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                              \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                              \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502\n    3: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'001': 1024})\n    Secret function:\n    f(x) = a\u00b7<1, 1, 1, 0> + 0 (mod 2)\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                  \u2502               \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502           \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502       \u2502\n    3: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502\n    4: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'1110': 1024})\n    Secret function:\n    f(x) = a\u00b7<1, 1, 0, 0, 1> + 0 (mod 2)\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                  \u2502               \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502           \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502           \u2502\n    3: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502           \u2502\n    4: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502\n    5: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'11001': 1024})\n    Secret function:\n    f(x) = a\u00b7<1, 0, 1, 0, 0, 1> + 1 (mod 2)\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                      \u2502               \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502               \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502   \u2502           \u2502\n    3: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502   \u2502           \u2502\n    4: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502   \u2502           \u2502\n    5: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502   \u2502   \u2502\n    6: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'101001': 1024})\n    Secret function:\n    f(x) = a\u00b7<0, 1, 0, 0, 0, 0, 1> + 1 (mod 2)\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                                  \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502           \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502           \u2502\n    3: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502           \u2502\n    4: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502           \u2502\n    5: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502           \u2502\n    6: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502   \u2502\n    7: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'0100001': 1024})\n    Secret function:\n    f(x) = a\u00b7<1, 1, 1, 0, 1, 0, 1, 1> + 1 (mod 2)\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                      \u2502                           \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502   \u2502                       \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502   \u2502   \u2502                   \u2502\n    3: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502   \u2502   \u2502                   \u2502\n    4: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502   \u2502   \u2502   \u2502               \u2502\n    5: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502   \u2502   \u2502   \u2502               \u2502\n    6: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502   \u2502   \u2502   \u2502   \u2502           \u2502\n    7: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    8: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'11101011': 1024})\n    Secret function:\n    f(x) = a\u00b7<0, 0, 1, 0, 0, 0, 1, 0, 0> + 1 (mod 2)\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                                  \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                  \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502           \u2502\n    3: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502           \u2502\n    4: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502           \u2502\n    5: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502           \u2502\n    6: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502   \u2502       \u2502\n    7: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502   \u2502       \u2502\n    8: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502   \u2502\n    9: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'001000100': 1024})\n    Secret function:\n    f(x) = a\u00b7<1, 1, 0, 1, 1, 1, 1, 0, 0, 0> + 1 (mod 2)\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                       \u2502                           \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502                       \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502                       \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502                   \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502               \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502           \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    10: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'1101111000': 1024})\n    Secret function:\n    f(x) = a\u00b7<0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0> + 0 (mod 2)\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                                   \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                   \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                   \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                   \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                   \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502               \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502               \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502               \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502           \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502       \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502\n    11: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'00000100110': 1024})\n    Secret function:\n    f(x) = a\u00b7<1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0> + 0 (mod 2)\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502                               \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502                           \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502                       \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502                   \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502                   \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502                   \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502           \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    12: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'111100100110': 1024})\n    Secret function:\n    f(x) = a\u00b7<1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1> + 1 (mod 2)\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                       \u2502                               \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502                               \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502                               \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502                               \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502                           \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502                       \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502                   \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502           \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502           \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502           \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    13: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'1000111101001': 1024})\n    Secret function:\n    f(x) = a\u00b7<0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1> + 1 (mod 2)\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                                                           \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502                                   \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502                               \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502                           \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502                           \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502                       \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502                   \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502           \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502           \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502           \u2502\n    13: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    14: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'01110111001001': 1024})\n    Secret function:\n    f(x) = a\u00b7<0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0> + 1 (mod 2)\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                                                                   \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502                                           \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502                                           \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502                                       \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502                                   \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502                               \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502                           \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                       \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                   \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                   \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502           \u2502\n    13: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    14: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    15: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'010111111010110': 1024})\n    Secret function:\n    f(x) = a\u00b7<1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0> + 0 (mod 2)\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502                                               \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502                                           \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502                                           \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502                                           \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502                                       \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502                                       \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502                                   \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502                                   \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502                               \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                           \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                       \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                   \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    13: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502           \u2502\n    14: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    15: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    16: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'1100101011111110': 1024})\n    Secret function:\n    f(x) = a\u00b7<1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0> + 1 (mod 2)\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                       \u2502                                   \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502                                   \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502                                   \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502                               \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502                               \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502                           \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502                       \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502                   \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    13: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    14: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502           \u2502\n    15: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    16: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    17: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'10010111100000110': 1024})\n    Secret function:\n    f(x) = a\u00b7<0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0> + 0 (mod 2)\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                                                                       \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502                                                   \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502                                               \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502                                               \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502                                           \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502                                       \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502                                   \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                               \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                               \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                           \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                       \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                   \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                   \u2502\n    13: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    14: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502           \u2502\n    15: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502           \u2502\n    16: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    17: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    18: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'011011110111011010': 1024})\n    Secret function:\n    f(x) = a\u00b7<0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0> + 1 (mod 2)\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                                                   \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                                   \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502                           \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502                           \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502                           \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502                           \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502                           \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502                           \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502                           \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502                           \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502                       \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502                   \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502                   \u2502\n    13: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502                   \u2502\n    14: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502               \u2502\n    15: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502               \u2502\n    16: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502           \u2502\n    17: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    18: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    19: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'0010000000110010110': 1024})\n\n\n\n```python\nimport matplotlib.pyplot as plt\n\n# Plotting the time taken by the algorithm against the number of qubits in the circuit to analyze scalability of the algorithm\nplt.scatter(range(2,20),l)\nplt.title('Time vs Bits')\nplt.xlabel('Qubits')\nplt.ylabel('Time (in seconds)')\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "ac50fca4fe6df9bbf76fbbf19a41ee8c9bddfcab", "size": 63460, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "BernsteinVazarani_Algorithm_Cirq.ipynb", "max_stars_repo_name": "ananyoemon/Quantum-Algorithms", "max_stars_repo_head_hexsha": "1707b67e1181c0b9ddee32de6fb150109caa5119", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BernsteinVazarani_Algorithm_Cirq.ipynb", "max_issues_repo_name": "ananyoemon/Quantum-Algorithms", "max_issues_repo_head_hexsha": "1707b67e1181c0b9ddee32de6fb150109caa5119", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BernsteinVazarani_Algorithm_Cirq.ipynb", "max_forks_repo_name": "ananyoemon/Quantum-Algorithms", "max_forks_repo_head_hexsha": "1707b67e1181c0b9ddee32de6fb150109caa5119", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 76.0, "max_line_length": 11066, "alphanum_fraction": 0.381342578, "converted": true, "num_tokens": 15235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245628973633, "lm_q2_score": 0.09401018405865218, "lm_q1q2_score": 0.02557307922645553}}
{"text": "```python\n# Erasmus+ ICCT project (2018-1-SI01-KA203-047081)\n\n# Toggle cell visibility\n\nfrom IPython.display import HTML\ntag = HTML('''\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.''')\ndisplay(tag)\n\n# Hide the code completely\n\n# from IPython.display import HTML\n# tag = HTML('''<style>\n# div.input {\n#     display:none;\n# }\n# </style>''')\n# display(tag)\n```\n\n\n\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.\n\n\n\n```python\n%matplotlib inline\nimport control\nimport numpy\nimport sympy as sym\nfrom IPython.display import display, Markdown\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\n\n\n#print a matrix latex-like\ndef bmatrix(a):\n     \"\"\"Returns a LaTeX bmatrix - by Damir Arbula (ICCT project)\n\n     :a: numpy array\n     :returns: LaTeX bmatrix as a string\n     \"\"\"\n     if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n     lines = str(a).replace('[', '').replace(']', '').splitlines()\n     rv = [r'\\begin{bmatrix}']\n     rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n     rv +=  [r'\\end{bmatrix}']\n     return '\\n'.join(rv)\n\n\n# Display formatted matrix: \ndef vmatrix(a):\n    if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n    lines = str(a).replace('[', '').replace(']', '').splitlines()\n    rv = [r'\\begin{vmatrix}']\n    rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n    rv +=  [r'\\end{vmatrix}']\n    return '\\n'.join(rv)\n\n\n#matrixWidget is a matrix looking widget built with a VBox of HBox(es) that returns a numPy array as value !\nclass matrixWidget(widgets.VBox):\n    def updateM(self,change):\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.M_[irow,icol] = self.children[irow].children[icol].value\n                #print(self.M_[irow,icol])\n        self.value = self.M_\n\n    def dummychangecallback(self,change):\n        pass\n    \n    \n    def __init__(self,n,m):\n        self.n = n\n        self.m = m\n        self.M_ = numpy.matrix(numpy.zeros((self.n,self.m)))\n        self.value = self.M_\n        widgets.VBox.__init__(self,\n                             children = [\n                                 widgets.HBox(children = \n                                              [widgets.FloatText(value=0.0, layout=widgets.Layout(width='90px')) for i in range(m)]\n                                             ) \n                                 for j in range(n)\n                             ])\n        \n        #fill in widgets and tell interact to call updateM each time a children changes value\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        #value = Unicode('example@example.com', help=\"The email value.\").tag(sync=True)\n        self.observe(self.updateM, names='value', type= 'All')\n        \n    def setM(self, newM):\n        #disable callbacks, change values, and reenable\n        self.unobserve(self.updateM, names='value', type= 'All')\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].unobserve(self.updateM, names='value')\n        self.M_ = newM\n        self.value = self.M_\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        self.observe(self.updateM, names='value', type= 'All')        \n\n                #self.children[irow].children[icol].observe(self.updateM, names='value')\n\n             \n#overlaod class for state space systems that DO NOT remove \"useless\" states (what \"professor\" of automatic control would do this?)\nclass sss(control.StateSpace):\n    def __init__(self,*args):\n        #call base class init constructor\n        control.StateSpace.__init__(self,*args)\n    #disable function below in base class\n    def _remove_useless_states(self):\n        pass\n```\n\n## Crane load position control\n\n\n\nA gantry crane consists of a cart of mass $m_c = 1000$ kg, and a load of mass $m_l$, connected by a rope of length $L$ that can be considered massless. Friction acts on the cart linearly, proportional to cart velocity with coefficient $B_f = 100$ Ns/m; the cart is moved by the force $F$. The angle between the vertical axis and the rope is $\\theta$. The dynamic equations of the system, linearized around the steady condition ($\\theta=\\dot{\\theta}=\\dot{x}=0$), are (where $g = 9.81$ m/$\\text{s}^2$ is gravitational acceleration):  \n\n\\begin{cases}\n    (m_l+m_c)\\ddot{x}+m_lL\\ddot{\\theta}+B_f\\dot{x}=F \\\\\n    m_lL^2\\ddot{\\theta}+m_lL\\ddot{x}+m_lLg\\theta=0\n\\end{cases}\n\nWe assume $m_l=100$ kg and $L=10$ m as nominal values and we want to design a regulator for the measured load position $y=x+L\\sin{\\theta} \\cong x+L\\theta$ according to the following specifications: \n- settling time for 5% tolerance band of less than 20 seconds,  \n- minimal or no overshoot,\n- zero or practically zero steady-state error in response to a step-wise change of the desired load position,\n- force $F$ must not exceed $\\pm1000$ N when the requested position change is 10 meters.\n\nFirst, we have to write the linearized system's equations in state space form; dividing the second equation by $m_lL$ became\n$$\n    L\\ddot{\\theta}+\\ddot{x}+g\\theta=0 \\, .\n$$\n\nNow, defining $x=\\begin{bmatrix} x_1 & x_2 & x_3 & x_4 \\end{bmatrix}^T = =\\begin{bmatrix} \\dot{x} & \\dot{\\theta} & \\theta & x \\end{bmatrix}^T$ we can write:\n\n$$\nM\\dot{x}=Gx+HF,\n$$\n\nwhere:\n\n$$\n    M = \\begin{bmatrix} (m_l+m_c) & m_lL & 0 & 0 \\\\ 1 & L & 0 & 0 \\\\ 0 & 0 & 1 & 0 \\\\ 0 & 0 & 0 & 1 \\end{bmatrix}, \\quad\n    G = \\begin{bmatrix} -B_f & 0 & 0 & 0 \\\\ 0 & 0 & -g & 0 \\\\ 0 & 1 & 0 & 0 \\\\ 1 & 0 & 0 & 0 \\end{bmatrix} \\quad \\text{and} \\quad\n    H = \\begin{bmatrix} 1 \\\\ 0 \\\\ 0 \\\\ 0 \\end{bmatrix} \\, .\n$$\n\nThus, pre-multiplying all with $M^{-1}$ we obtain ($A=M^{-1}G$, $B=M^{-1}H$):\n\n\\begin{cases}\n    \\dot{x} = \\begin{bmatrix} -B_f/m_c & 0 & gm_l/m_c & 0 \\\\ B_f/(Lm_c) & 0 & -g(1/L + m_l/(Lm_c)) & 0 \\\\ 0 & 1 & 0 & 0 \\\\ 1 & 0 & 0 & 0 \\end{bmatrix}x +\\begin{bmatrix}1/m_c \\\\ -1/(Lm_c) \\\\ 0 \\\\ 0 \\end{bmatrix}F \\\\\n    y = \\begin{bmatrix} 0 & 0 & L & 1 \\end{bmatrix}x\n\\end{cases}\n\n### Regulator development\n#### Controller design\n\nThe poles of the system are $0$, $-0.091$ and $-0.0045\\pm1.038i$. In order to meet the requirement for settling time, we move the real poles to $-0.28$ and decrease the real part of the imaginary poles by $-0.25$. As a result, the chosen closed-loop poles are: $-0.28$, $-0.28$ and $-0.2545\\pm1.038i$. For the zero steady-state error we scale the reference signal with a gain equal to the inverse of the closed-loop system's gain.\n\n#### Design of the observer\nTo support the state feedback controller we design a full state observer with poles in $-8$.\n\n### How to use this notebook?\nTry to change the poles location in order to satisfy the requirements for a reference step input of 15 m.\n\n\n```python\n# Preparatory cell\n\nX0 = numpy.matrix('0.0; 0.0; 0.0; 0.0')\nK = numpy.matrix([0,0,0,0])\nL = numpy.matrix([[0],[0],[0],[0]])\n\nX0w = matrixWidget(4,1)\nX0w.setM(X0)\nKw = matrixWidget(1,4)\nKw.setM(K)\nLw = matrixWidget(4,1)\nLw.setM(L)\n\n\neig1c = matrixWidget(1,1)\neig2c = matrixWidget(2,1)\neig3c = matrixWidget(1,1)\neig4c = matrixWidget(2,1)\neig1c.setM(numpy.matrix([-0.28])) \neig2c.setM(numpy.matrix([[-0.2545],[-1.038]]))\neig3c.setM(numpy.matrix([-0.28]))\neig4c.setM(numpy.matrix([[-1.],[-1.]]))\n\neig1o = matrixWidget(1,1)\neig2o = matrixWidget(2,1)\neig3o = matrixWidget(1,1)\neig4o = matrixWidget(2,1)\neig1o.setM(numpy.matrix([-8.])) \neig2o.setM(numpy.matrix([[-8.1],[0.]]))\neig3o.setM(numpy.matrix([-8.2]))\neig4o.setM(numpy.matrix([[-8.3],[0.]]))\n```\n\n\n```python\n# Misc\n\n#create dummy widget \nDW = widgets.FloatText(layout=widgets.Layout(width='0px', height='0px'))\n\n#create button widget\nSTART = widgets.Button(\n    description='Test',\n    disabled=False,\n    button_style='', # 'success', 'info', 'warning', 'danger' or ''\n    tooltip='Test',\n    icon='check'\n)\n                       \ndef on_start_button_clicked(b):\n    #This is a workaround to have intreactive_output call the callback:\n    #   force the value of the dummy widget to change\n    if DW.value> 0 :\n        DW.value = -1\n    else: \n        DW.value = 1\n    pass\nSTART.on_click(on_start_button_clicked)\n\n# Define type of method \nselm = widgets.Dropdown(\n    options= ['Set K and L', 'Set the eigenvalues'],\n    value= 'Set the eigenvalues',\n    description='',\n    disabled=False\n)\n\n# Define the number of complex eigenvalues\nselec = widgets.Dropdown(\n    options= ['0 complex eigenvalues', '2 complex eigenvalues', '4 complex eigenvalues'],\n    value= '2 complex eigenvalues',\n    description='Eig controller:',\n    disabled=False\n)\nseleo = widgets.Dropdown(\n    options= ['0 complex eigenvalues', '2 complex eigenvalues'],\n    value= '0 complex eigenvalues',\n    description='Eig observer:',\n    disabled=False\n)\n\n#define type of ipout \nselu = widgets.Dropdown(\n    options=['impulse', 'step', 'sinusoid', 'square wave'],\n    value='step',\n    description='Type of reference:',\n    style = {'description_width': 'initial'},\n    disabled=False\n)\n# Define the values of the input\nu = widgets.FloatSlider(\n    value=10,\n    min=0,\n    max=20,\n    step=1,\n    description='Reference:',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.1f',\n)\nperiod = widgets.FloatSlider(\n    value=0.5,\n    min=0.001,\n    max=10,\n    step=0.001,\n    description='Period: ',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.3f',\n)\n\nsimTime = widgets.FloatText(\n    value=30,\n    description='',\n    disabled=False\n)\n```\n\n\n```python\n# Support functions\n\ndef eigen_choice(selec,seleo):\n    if selec == '0 complex eigenvalues':\n        eig1c.children[0].children[0].disabled = False\n        eig2c.children[1].children[0].disabled = True\n        eig3c.children[0].children[0].disabled = False\n        eig4c.children[0].children[0].disabled = False\n        eig4c.children[1].children[0].disabled = True\n        eigc = 0\n    if seleo == '0 complex eigenvalues':\n        eig1o.children[0].children[0].disabled = False\n        eig2o.children[1].children[0].disabled = True\n        eig3o.children[0].children[0].disabled = False\n        eig4o.children[0].children[0].disabled = False\n        eig4o.children[1].children[0].disabled = True\n        eigo = 0\n    if selec == '2 complex eigenvalues':\n        eig1c.children[0].children[0].disabled = False\n        eig2c.children[1].children[0].disabled = False\n        eig3c.children[0].children[0].disabled = False\n        eig4c.children[0].children[0].disabled = True\n        eig4c.children[1].children[0].disabled = True\n        eigc = 2\n    if seleo == '2 complex eigenvalues':\n        eig1o.children[0].children[0].disabled = False\n        eig2o.children[1].children[0].disabled = False\n        eig3o.children[0].children[0].disabled = False\n        eig4o.children[0].children[0].disabled = True\n        eig4o.children[1].children[0].disabled = True\n        eigo = 2\n    if selec == '4 complex eigenvalues':\n        eig1c.children[0].children[0].disabled = True\n        eig2c.children[1].children[0].disabled = False\n        eig3c.children[0].children[0].disabled = True\n        eig4c.children[0].children[0].disabled = False\n        eig4c.children[1].children[0].disabled = False\n        eigc = 4\n    if seleo == '4 complex eigenvalues':\n        eig1o.children[0].children[0].disabled = True\n        eig2o.children[1].children[0].disabled = False\n        eig3o.children[0].children[0].disabled = True\n        eig4o.children[0].children[0].disabled = False\n        eig4o.children[1].children[0].disabled = False\n        eigo = 4\n    return eigc, eigo\n\ndef method_choice(selm):\n    if selm == 'Set K and L':\n        method = 1\n        selec.disabled = True\n        seleo.disabled = True\n    if selm == 'Set the eigenvalues':\n        method = 2\n        selec.disabled = False\n        seleo.disabled = False\n    return method\n```\n\n\n```python\nml = 100 \nmc = 1000 \nL  = 10\ng  = 9.81\nBf = 100\n\nA = numpy.matrix([[-Bf/mc,0,g*ml/mc,0],\n                  [Bf/(L*mc), 0, -g*(1/L + ml/(L*mc)), 0],\n                  [0, 1, 0, 0],\n                  [1, 0, 0, 0]])\nB = numpy.matrix([[1/mc],[-1/(L*mc)],[0],[0]])\nC = numpy.matrix([[0,0,L,1]])\n\ndef main_callback2(X0w, K, L, eig1c, eig2c, eig3c, eig4c, eig1o, eig2o, eig3o, eig4o, u, period, selm, selec, seleo, selu, simTime, DW):\n    eigc, eigo = eigen_choice(selec,seleo)\n    method = method_choice(selm)\n    \n    if method == 1:\n        solc = numpy.linalg.eig(A-B*K)\n        solo = numpy.linalg.eig(A-L*C)\n    if method == 2:\n        try:\n            if eigc == 0:\n                K = control.acker(A, B, [eig1c[0,0], eig2c[0,0], eig3c[0,0], eig4c[0,0]])\n                Kw.setM(K)\n            if eigc == 2:\n                K = control.acker(A, B, [eig3c[0,0],\n                                          eig1c[0,0],\n                                          numpy.complex(eig2c[0,0], eig2c[1,0]), \n                                          numpy.complex(eig2c[0,0],-eig2c[1,0])])\n                Kw.setM(K)\n            if eigc == 4:\n                K = control.acker(A, B, [numpy.complex(eig4c[0,0], eig4c[1,0]), \n                                          numpy.complex(eig4c[0,0],-eig4c[1,0]),\n                                          numpy.complex(eig2c[0,0], eig2c[1,0]), \n                                          numpy.complex(eig2c[0,0],-eig2c[1,0])])\n                Kw.setM(K)\n            if eigo == 0:\n                L = control.place(A.T, C.T, [eig1o[0,0], eig2o[0,0], eig3o[0,0], eig4o[0,0]]).T\n                Lw.setM(L)\n            if eigo == 2:\n                L = control.place(A.T, C.T, [eig3o[0,0],\n                                             eig1o[0,0],\n                                             numpy.complex(eig2o[0,0], eig2o[1,0]), \n                                             numpy.complex(eig2o[0,0],-eig2o[1,0])]).T\n                Lw.setM(L)\n            if eigo == 4:\n                L = control.place(A.T, C.T, [numpy.complex(eig4o[0,0], eig4o[1,0]), \n                                          numpy.complex(eig4o[0,0],-eig4o[1,0]),\n                                          numpy.complex(eig2o[0,0], eig2o[1,0]), \n                                          numpy.complex(eig2o[0,0],-eig2o[1,0])]).T\n                Lw.setM(L)\n        except:\n            print(\"ERROR: at least one of the requested pole is repeated more than rank(B) times, try to change the poles\")\n            return\n            \n    sys = sss(A,B,numpy.vstack((C,[0,0,0,0])),[[0],[1]])\n    syse = sss(A-L*C,numpy.hstack((B,L)),numpy.eye(4),numpy.zeros((4,2)))\n    sysc = sss(0,[0,0,0,0],0,-K)\n    sys_append = control.append(sys,syse,sysc)\n    # To avoid strange behaviours\n    try:\n        sys_CL = control.connect(sys_append,\n                                 [[1,7],[2,2],[3,1],[4,3],[5,4],[6,5],[7,6]],\n                                 [1],\n                                 [1,2])\n    except:\n        sys_CL = control.connect(sys_append,\n                                 [[1,7],[2,2],[3,1],[4,3],[5,4],[6,5],[7,6]],\n                                 [1],\n                                 [1,2])\n\n    X0w1 = numpy.zeros((8,1))\n    X0w1[4,0] = X0w[0,0]\n    X0w1[5,0] = X0w[1,0]\n    X0w1[6,0] = X0w[2,0]\n    X0w1[7,0] = X0w[3,0]\n    if simTime != 0:\n        T = numpy.linspace(0, simTime, 10000)\n    else:\n        T = numpy.linspace(0, 1, 10000)\n    #t1, y1 = step(sys_CL[0,0],[0,10000])\n    u1 = u\n    try:\n        DCgain = control.dcgain(sys_CL[0,0])\n        u = u/DCgain\n    except:\n        print(\"Error in the calculation of the dcgain of the closed loop controlled system. The feedforward gain is setted to 1.\")\n        DCgain = 1\n    \n    if selu == 'impulse': #selu\n        U = [0 for t in range(0,len(T))]\n        U[0] = u\n        U1 = [0 for t in range(0,len(T))]\n        U1[0] = u1\n        T, yout, xout = control.forced_response(sys_CL,T,U,X0w1)\n    if selu == 'step':\n        U = [u for t in range(0,len(T))]\n        U1 = [u1 for t in range(0,len(T))]\n        T, yout, xout = control.forced_response(sys_CL,T,U,X0w1)\n    if selu == 'sinusoid':\n        U = u*numpy.sin(2*numpy.pi/period*T)\n        U1 = u1*numpy.sin(2*numpy.pi/period*T)\n        T, yout, xout = control.forced_response(sys_CL,T,U,X0w1)\n    if selu == 'square wave':\n        U = u*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n        U1 = u1*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n        T, yout, xout = control.forced_response(sys_CL,T,U,X0w1)\n    \n    try:\n        step_info_dict = control.step_info(sys_CL[0,0],SettlingTimeThreshold=0.05,T=T)\n        print('Step info: \\n\\tRise time =',step_info_dict['RiseTime'],'\\n\\tSettling time (5%) =',step_info_dict['SettlingTime'],'\\n\\tOvershoot (%)=',step_info_dict['Overshoot'])\n        print('Max u value (% of 1000N)=', max(abs(yout[1]))/(1000)*100)\n    except:\n        print(\"Error in the calculation of step info.\")\n    print(\"Closed loop system's gain =\",DCgain)\n    \n    fig = plt.figure(num='Simulation1', figsize=(14,12))\n    \n    fig.add_subplot(221)\n    plt.title('Output response')\n    plt.ylabel('Output')\n    plt.plot(T,yout[0],T,U1,'r--')\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$y$','Reference'])\n    plt.grid()\n    \n    fig.add_subplot(222)\n    plt.title('Input')\n    plt.ylabel('$u$')\n    plt.plot(T,yout[1])\n    plt.plot(T,[1000 for i in range(len(T))],'r--')\n    plt.plot(T,[-1000 for i in range(len(T))],'r--')\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(223)\n    plt.title('States response')\n    plt.ylabel('States')\n    plt.plot(T,xout[0],\n             T,xout[1],\n             T,xout[2],\n             T,xout[3])\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$x_{1}$','$x_{2}$','$x_{3}$','$x_{4}$'])\n    plt.grid()\n    \n    fig.add_subplot(224)\n    plt.title('Estimation errors')\n    plt.ylabel('Errors')\n    plt.plot(T,xout[4]-xout[0])\n    plt.plot(T,xout[5]-xout[1])\n    plt.plot(T,xout[6]-xout[2])\n    plt.plot(T,xout[7]-xout[3])\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.xlabel('$t$ [s]')\n    plt.legend(['$e_{1}$','$e_{2}$','$e_{3}$','$e_{4}$'])\n    plt.grid()\n    #plt.tight_layout()\n   \nalltogether2 = widgets.VBox([widgets.HBox([selm, \n                                          selec,\n                                          seleo,\n                                          selu]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.HBox([widgets.Label('K:',border=3), Kw, \n                                                        widgets.Label('Eigenvalues:',border=3),\n                                                        widgets.HBox([eig1c, \n                                                                      eig2c, \n                                                                      eig3c,\n                                                                      eig4c])])]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.VBox([widgets.HBox([widgets.Label('L:',border=3), Lw, widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Eigenvalues:',border=3), \n                                          eig1o, \n                                          eig2o,\n                                          eig3o, \n                                          eig4o,\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('X0 est.:',border=3), X0w]),\n                                          widgets.Label(' ',border=3),\n                                                       widgets.HBox([\n                                          widgets.VBox([widgets.Label('Simulation time (s):',border=3)]),\n                                          widgets.VBox([simTime])])]),\n                                          widgets.Label(' ',border=3)]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([u,\n                                          period, \n                                          START])])\nout2 = widgets.interactive_output(main_callback2, {'X0w':X0w, 'K':Kw, 'L':Lw,\n                                                   'eig1c':eig1c, 'eig2c':eig2c, 'eig3c':eig3c, 'eig4c':eig4c, \n                                                   'eig1o':eig1o, 'eig2o':eig2o, 'eig3o':eig3o, 'eig4o':eig4o,  \n                                                   'u':u, 'period':period, 'selm':selm, 'selec':selec, 'seleo':seleo, 'selu':selu, 'simTime':simTime, 'DW':DW})\nout2.layout.height = '860px'\ndisplay(out2, alltogether2)\n```\n\n\n    Output(layout=Layout(height='860px'))\n\n\n\n    VBox(children=(HBox(children=(Dropdown(index=1, options=('Set K and L', 'Set the eigenvalues'), value='Set the\u2026\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "8cfe4fe3f59e317a40cdac9124060ca92e12cd5e", "size": 29588, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_en/examples/04/SS-39-Crane_load_position_control.ipynb", "max_stars_repo_name": "ICCTerasmus/ICCT", "max_stars_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-22T18:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:10:22.000Z", "max_issues_repo_path": "ICCT/ENG/examples/04/SS-39-Crane_load_position_control.ipynb", "max_issues_repo_name": "tuxsaurus/ICCT", "max_issues_repo_head_hexsha": "30d1aea4fb056c9736c9b4c5a0f50fff14fa6382", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICCT/ENG/examples/04/SS-39-Crane_load_position_control.ipynb", "max_forks_repo_name": "tuxsaurus/ICCT", "max_forks_repo_head_hexsha": "30d1aea4fb056c9736c9b4c5a0f50fff14fa6382", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-24T11:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T16:36:18.000Z", "avg_line_length": 42.3290414878, "max_line_length": 547, "alphanum_fraction": 0.4604907395, "converted": true, "num_tokens": 6370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.290980853917813, "lm_q2_score": 0.08756384726162965, "lm_q1q2_score": 0.025479403048517944}}
{"text": "*best viewed in [nbviewer](https://nbviewer.jupyter.org/github/CambridgeSemiticsLab/BH_time_collocations/blob/master/results/notebooks/yqtl_association_with_advb.ipynb)*\n\n# Yiq\u1e6dol and Its Association with Prototypical Adverbs\n### Cody Kingham \n<a href=\"../../docs/sponsors.md\"></a>\n\n\n```python\n! echo \"last updated:\"; date\n```\n\n    last updated:\n    Thu 27 Feb 2020 10:58:59 GMT\n\n\n## Why does yiq\u1e6dol prefer particles?\n\nIn [a preliminary analysis](https://nbviewer.jupyter.org/github/CambridgeSemiticsLab/BH_time_collocations/blob/master/archive/2019-10-31/analysis/exploratory/construction_clusters.ipynb), we found evidence that the yiq\u1e6dol verb tends to be attracted to time words which can be considered \"prototypical adverbs\". These are words which are infrequently combined with constructions that indicate number, definiteness, or possession (see Croft, \"A Conceptual Frameowork for Grammatical Categories,\" 1990). These prototypical adverbs include words such as \u05d0\u05d6 ,\u05e0\u05e6\u05d7 ,\u05e2\u05d5\u05dc\u05dd ,\u05de\u05ea\u05d9 ,\u05e2\u05ea\u05d4. In [the study on parts of speech](https://nbviewer.jupyter.org/github/CambridgeSemiticsLab/BH_time_collocations/blob/master/results/notebooks/time_distribution_and_pos.ipynb), we found an empirical basis for separating these words from their noun counterparts on the grounds of their collocability with nominalizing constructions.\n\nThe preliminary analysis cited above found a statistical association between yiq\u1e6dol and prototypical adverbs. **In this notebook, we seek to confirm that yiq\u1e6dol indeed has a preference for these adverb terms, and we ask why?**\n\n### Why does it matter?\n\nOne of the surprising things about this pattern, as this notebook will demonstrate, is that not all of the yiq\u1e6dol adverbs seem to fit the same semantic mold. For instance, the semantics of \u05d0\u05d6, which refers to a point in time, is different from \u05e2\u05d5\u05dc\u05dd, which refers to a unknown duration. And yet, these words share two major qualities: they are both adverb-like, and they both seem to prefer the yiq\u1e6dol verb (as we will seek to confirm). This is surprising because we might assume that yiq\u1e6dol's preference is primarily semantic in nature: durational terms such as \u05e2\u05d5\u05dc\u05dd and \u05e0\u05e6\u05d7 would fit the widely-agreed, unbounded meaning of the verbal form. But \u05d0\u05d6 suggests another possibility: that yiq\u1e6dol's preference is not wholly predictable from its semantics, but possibly due to a convention of use. Or, in other words, it is simply an idiosyncratic quality of yiq\u1e6dol to easily combine with adverbs. This would not mean such behavior has *no* semantic motivation. Perhaps the association of yiq\u1e6dol with durational adverbs opened the door for an association with adverbs in general. **These questions are purely hypothetical. And in this notebook we will seek to find empirical data that can help (in)validate these hypotheses and suggest further directions for analysis.**\n\n<hr>\n\n# Python\n\nNow we import the modules and data needed for the analysis.\n\n\n```python\n# standard packages\nfrom pathlib import Path\nimport collections\nimport networkx as nx\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams\nrcParams['font.serif'] = ['SBL Biblit']\nimport seaborn as sns\nfrom bidi.algorithm import get_display # bi-directional text support for plotting\nfrom scipy.stats import linregress\n\n# custom package in /tools\nfrom paths import main_table, figs\nfrom tf_tools.load import load_tf\nfrom tf_tools.tokenizers import tokenize_surface\nfrom cx_analysis.load import cxs\nfrom cx_analysis.search import SearchCX\nfrom stats.significance import contingency_table, apply_fishers\nfrom stats.pca import apply_pca\n\nTF, API, A = load_tf(silent='deep')\nA.displaySetup(condenseType='phrase')\nF, E, T, L = A.api.F, A.api.E, A.api.T, A.api.L\nse = SearchCX(A)\nphrase2cxs = cxs['phrase2cxs']\nclass2cx = cxs['class2cx']\ntime_cxs = list(phrase2cxs.values())\n\n# configure data output\nname = 'yqtl_association_with_advb'\nfigures = figs.joinpath(name)\nif not figures.exists():\n    figures.mkdir(parents=True)\ndef fg_path(fg_name):\n    return figures.joinpath(fg_name)\n```\n\n\n<style>\n@font-face {\n  font-family: \"Ezra SIL\";\n  src:\n    local(\"SILEOT.ttf\"),\n    url(\"https://github.com/annotation/text-fabric/blob/master/tf/server/static/fonts/SILEOT.woff?raw=true\");\n}\n.features {\n    font-family: monospace;\n    font-size: medium;\n    font-weight: bold;\n    color: #0a6611;\n    display: flex;\n    flex-flow: column nowrap;\n    padding: 0.1em;\n    margin: 0.1em;\n    direction: ltr;\n}\n.features div,.features span {\n    padding: 0;\n    margin: -0.1rem 0;\n}\n.features .f {\n    font-family: sans-serif;\n    font-size: x-small;\n    font-weight: normal;\n    color: #5555bb;\n}\n.features .xft {\n  color: #000000;\n  background-color: #eeeeee;\n  font-size: medium;\n  margin: 0.1em 0em;\n}\n.features .xft .f {\n  color: #000000;\n  background-color: #eeeeee;\n  font-style: italic;\n  font-size: small;\n  font-weight: normal;\n}\n.ltr {\n    direction: ltr ! important;\n}\n.verse {\n    display: flex;\n    flex-flow: row wrap;\n    direction: rtl;\n}\n.vl {\n    display: flex;\n    flex-flow: column nowrap;\n    justify-content: flex-end;\n    align-items: flex-end;\n    direction: ltr;\n    width: 100%;\n}\n.outeritem {\n    display: flex;\n    flex-flow: row wrap;\n    direction: rtl;\n}\n.sentence,.clause,.phrase {\n    margin-top: -1.2em;\n    margin-left: 1em;\n    background: #ffffff none repeat scroll 0 0;\n    padding: 0 0.3em;\n    border-style: solid;\n    border-radius: 0.2em;\n    font-size: small;\n    display: block;\n    width: fit-content;\n    max-width: fit-content;\n    direction: ltr;\n}\n.atoms {\n    display: flex;\n    flex-flow: row wrap;\n    margin: 0.3em;\n    padding: 0.3em;\n    direction: rtl;\n    background-color: #ffffff;\n}\n.satom,.catom,.patom {\n    margin: 0.3em;\n    padding: 0.3em;\n    border-radius: 0.3em;\n    border-style: solid;\n    display: flex;\n    flex-flow: column nowrap;\n    direction: rtl;\n    background-color: #ffffff;\n}\n.sentence {\n    border-color: #aa3333;\n    border-width: 1px;\n}\n.clause {\n    border-color: #aaaa33;\n    border-width: 1px;\n}\n.phrase {\n    border-color: #33aaaa;\n    border-width: 1px;\n}\n.satom {\n    border-color: #aa3333;\n    border-width: 4px;\n}\n.catom {\n    border-color: #aaaa33;\n    border-width: 3px;\n}\n.patom {\n    border-color: #33aaaa;\n    border-width: 3px;\n}\n.word {\n    padding: 0.1em;\n    margin: 0.1em;\n    border-radius: 0.1em;\n    border: 1px solid #cccccc;\n    display: flex;\n    flex-flow: column nowrap;\n    direction: rtl;\n    background-color: #ffffff;\n}\n.lextp {\n    padding: 0.1em;\n    margin: 0.1em;\n    border-radius: 0.1em;\n    border: 2px solid #888888;\n    width: fit-content;\n    display: flex;\n    flex-flow: column nowrap;\n    direction: rtl;\n    background-color: #ffffff;\n}\n.occs {\n    font-size: x-small;\n}\n.satom.l,.catom.l,.patom.l {\n    border-left-style: dotted\n}\n.satom.r,.catom.r,.patom.r {\n    border-right-style: dotted\n}\n.satom.lno,.catom.lno,.patom.lno {\n    border-left-style: none\n}\n.satom.rno,.catom.rno,.patom.rno {\n    border-right-style: none\n}\n.tr,.tr a:visited,.tr a:link {\n    font-family: sans-serif;\n    font-size: large;\n    color: #000044;\n    direction: ltr;\n    text-decoration: none;\n}\n.trb,.trb a:visited,.trb a:link {\n    font-family: sans-serif;\n    font-size: normal;\n    direction: ltr;\n    text-decoration: none;\n}\n.prb,.prb a:visited,.prb a:link {\n    font-family: sans-serif;\n    font-size: large;\n    direction: ltr;\n    text-decoration: none;\n}\n.h,.h a:visited,.h a:link {\n    font-family: \"Ezra SIL\", \"SBL Hebrew\", sans-serif;\n    font-size: large;\n    color: #000044;\n    direction: rtl;\n    text-decoration: none;\n}\n.hb,.hb a:visited,.hb a:link {\n    font-family: \"Ezra SIL\", \"SBL Hebrew\", sans-serif;\n    font-size: large;\n    line-height: 2;\n    direction: rtl;\n    text-decoration: none;\n}\n.vn {\n  font-size: small !important;\n  padding-right: 1em;\n}\n.rela,.function,.typ {\n    font-family: monospace;\n    font-size: small;\n    color: #0000bb;\n}\n.pdp,.pdp a:visited,.pdp a:link {\n    font-family: monospace;\n    font-size: medium;\n    color: #0000bb;\n    text-decoration: none;\n}\n.voc_lex {\n    font-family: monospace;\n    font-size: medium;\n    color: #0000bb;\n}\n.vs {\n    font-family: monospace;\n    font-size: medium;\n    font-weight: bold;\n    color: #0000bb;\n}\n.vt {\n    font-family: monospace;\n    font-size: medium;\n    font-weight: bold;\n    color: #0000bb;\n}\n.gloss {\n    font-family: sans-serif;\n    font-size: small;\n    font-weight: normal;\n    color: #444444;\n}\n.vrs {\n    font-family: sans-serif;\n    font-size: small;\n    font-weight: bold;\n    color: #444444;\n}\n.nd {\n    font-family: monospace;\n    font-size: x-small;\n    color: #999999;\n}\n.hl {\n    background-color: #ffee66;\n}\n\ntr.tf, td.tf, th.tf {\n  text-align: left;\n}\n\nspan.hldot {\n\tbackground-color: var(--hl-strong);\n\tborder: 0.2rem solid var(--hl-rim);\n\tborder-radius: 0.4rem;\n\t/*\n\tdisplay: inline-block;\n\twidth: 0.8rem;\n\theight: 0.8rem;\n\t*/\n}\nspan.hl {\n\tbackground-color: var(--hl-strong);\n\tborder-width: 0;\n\tborder-radius: 0.1rem;\n\tborder-style: solid;\n}\n\nspan.hlup {\n\tborder-color: var(--hl-dark);\n\tborder-width: 0.1rem;\n\tborder-style: solid;\n\tborder-radius: 0.2rem;\n  padding: 0.2rem;\n}\n\n:root {\n\t--hl-strong:        hsla( 60, 100%,  70%, 0.9  );\n\t--hl-rim:           hsla( 55, 100%,  60%, 0.9  );\n\t--hl-dark:          hsla( 55, 100%,  40%, 0.9  );\n}\n</style>\n\n\n\n```python\n# set up project dataset\ntimes_full = pd.read_csv(main_table, sep='\\t')\ntimes_full.set_index(['node'], inplace=True)\ntimes = times_full[~times_full.classi.str.contains('component')]\n```\n\n# Adverb Collocations with Yiq\u1e6dol\n\nWe pick up the thread where we left off in [the notebook on parts of speech](https://nbviewer.jupyter.org/github/CambridgeSemiticsLab/BH_time_collocations/blob/master/results/notebooks/time_distribution_and_pos.ipynb). There we used Principal Component Analysis (PCA) to isolate prototypical adverbs from nouns. We duplicate that same method here and begin to look at the collocational tendencies of these items compared against verbs. \n\n\n```python\n# compile collocation table of time heads with nominalizing constructions\ntime_cols = pd.pivot_table(\n    times, \n    index=['time'], \n    values=['time_pl', 'quantified', 'definite', \n            'demonstrative', 'ordinal', 'time_sffx',\n            'bare', 'genitive'],\n    aggfunc=np.sum\n)\n\n# sort on size\ntime_cols = time_cols.loc[time_cols.sum(1).sort_values(ascending=False).index]\n\n# drop observations with < 5 total sample size\ntime_cols = time_cols[time_cols.sum(1) > 4]\n\n# calculate ratio\ntime_col_ratio = time_cols.div(time_cols.sum(1), axis=0)\n\n# apply PCA to dataset\ntime_pca, time_loadings = apply_pca(time_col_ratio, 0, 1, scree=False)\n```\n\nThe results of the PCA analysis and its implications are explored and explained further in the notebook linked to above. The resulting PCA space is illustrated below, as calculated in that notebook.\n\n\n\nThe items to the right of the plot are the \"adverb\" group. We can select them by pulling all words with an x-axis value (principal component 1 or PC1) which is $> 0$. We can generalize and say that in this model terms which have a higher x-axis value are \"more adverbial.\" Although, this categorization remains a working hypothesis. Those forms are shown below in descending order. Note that all words down to \u05e2\u05ea\u05d4 have the same value of `0.59`.\n\n\n```python\nadvbs = time_pca[time_pca['PC1'] > 0].iloc[:, :2]\nadvbs = advbs.sort_values(by='PC1', ascending=False) # sort by distance from origin\n\nadvbs\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>PC1</th>\n      <th>PC2</th>\n    </tr>\n    <tr>\n      <th>time</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>\u05d9\u05d5\u05de\u05dd</th>\n      <td>0.594544</td>\n      <td>0.016065</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05ea\u05d9</th>\n      <td>0.594544</td>\n      <td>0.016065</td>\n    </tr>\n    <tr>\n      <th>\u05d8\u05e8\u05dd</th>\n      <td>0.594544</td>\n      <td>0.016065</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d4\u05e8</th>\n      <td>0.594544</td>\n      <td>0.016065</td>\n    </tr>\n    <tr>\n      <th>\u05d0\u05df</th>\n      <td>0.594544</td>\n      <td>0.016065</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d4\u05e8\u05d4</th>\n      <td>0.594544</td>\n      <td>0.016065</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05d3</th>\n      <td>0.594544</td>\n      <td>0.016065</td>\n    </tr>\n    <tr>\n      <th>\u05e9\u05c1\u05e0\u05d9</th>\n      <td>0.594544</td>\n      <td>0.016065</td>\n    </tr>\n    <tr>\n      <th>\u05e4\u05ea\u05d0\u05dd</th>\n      <td>0.594544</td>\n      <td>0.016065</td>\n    </tr>\n    <tr>\n      <th>\u05d4\u05e0\u05d4</th>\n      <td>0.594544</td>\n      <td>0.016065</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d7\u05e8</th>\n      <td>0.594544</td>\n      <td>0.016065</td>\n    </tr>\n    <tr>\n      <th>\u05ea\u05de\u05d9\u05d3</th>\n      <td>0.594544</td>\n      <td>0.016065</td>\n    </tr>\n    <tr>\n      <th>\u05db\u05df</th>\n      <td>0.594544</td>\n      <td>0.016065</td>\n    </tr>\n    <tr>\n      <th>\u05d0\u05d6</th>\n      <td>0.594544</td>\n      <td>0.016065</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05ea\u05d4</th>\n      <td>0.589188</td>\n      <td>0.015674</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05d5\u05d3</th>\n      <td>0.583211</td>\n      <td>0.013436</td>\n    </tr>\n    <tr>\n      <th>\u05e0\u05e6\u05d7</th>\n      <td>0.555681</td>\n      <td>0.011931</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05d5\u05dc\u05dd</th>\n      <td>0.536794</td>\n      <td>0.011730</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d7\u05e8\u05ea</th>\n      <td>0.344338</td>\n      <td>0.023228</td>\n    </tr>\n    <tr>\n      <th>\u05e8\u05d2\u05e2</th>\n      <td>0.199177</td>\n      <td>-0.121825</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nBy contrast, we can also select a list of nouns, which lie on the opposite end of the spectrum. We see that a few terms are clustered towards the center, such as \u05e8\u05d0\u05e9\u05c1\u05d9\u05ea and \u05d0\u05d7\u05e8. Since their classification is mixed, we will not select those. We will thus select all items which have $PC1 < -0.2$\n\n\n```python\nnouns = time_pca[time_pca['PC1'] < -0.2].iloc[:, :2]\nnouns = nouns.sort_values(by='PC1')\n\nnouns\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>PC1</th>\n      <th>PC2</th>\n    </tr>\n    <tr>\n      <th>time</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>\u05e2\u05e8\u05d1</th>\n      <td>-0.580466</td>\n      <td>0.626619</td>\n    </tr>\n    <tr>\n      <th>\u05e9\u05c1\u05d1\u05ea</th>\n      <td>-0.569903</td>\n      <td>0.567700</td>\n    </tr>\n    <tr>\n      <th>\u05e6\u05d4\u05e8\u05d9\u05dd</th>\n      <td>-0.544289</td>\n      <td>0.174998</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d5\u05e2\u05d3</th>\n      <td>-0.531623</td>\n      <td>0.261975</td>\n    </tr>\n    <tr>\n      <th>\u05e8\u05d0\u05e9\u05c1\u05d5\u05df</th>\n      <td>-0.515870</td>\n      <td>0.677366</td>\n    </tr>\n    <tr>\n      <th>\u05e9\u05c1\u05d1\u05d5\u05e2</th>\n      <td>-0.507633</td>\n      <td>-0.183260</td>\n    </tr>\n    <tr>\n      <th>\u05e4\u05e2\u05dd</th>\n      <td>-0.504261</td>\n      <td>-0.184201</td>\n    </tr>\n    <tr>\n      <th>\u05e8\u05d2\u05dc</th>\n      <td>-0.496096</td>\n      <td>-0.423423</td>\n    </tr>\n    <tr>\n      <th>\u05ea\u05d7\u05dc\u05d4</th>\n      <td>-0.492899</td>\n      <td>0.238149</td>\n    </tr>\n    <tr>\n      <th>\u05d9\u05d5\u05dd</th>\n      <td>-0.490936</td>\n      <td>0.096292</td>\n    </tr>\n    <tr>\n      <th>\u05e9\u05c1\u05d1\u05e2</th>\n      <td>-0.489334</td>\n      <td>-0.302840</td>\n    </tr>\n    <tr>\n      <th>\u05e9\u05c1\u05e0\u05d4</th>\n      <td>-0.488740</td>\n      <td>-0.229504</td>\n    </tr>\n    <tr>\n      <th>\u05e4\u05e0\u05d4</th>\n      <td>-0.483370</td>\n      <td>-0.499132</td>\n    </tr>\n    <tr>\n      <th>\u05d3\u05d1\u05e8</th>\n      <td>-0.482846</td>\n      <td>0.040616</td>\n    </tr>\n    <tr>\n      <th>\u05d7\u05d3\u05e9\u05c1</th>\n      <td>-0.467445</td>\n      <td>-0.102637</td>\n    </tr>\n    <tr>\n      <th>\u05d7\u05d9\u05d9\u05dd</th>\n      <td>-0.457386</td>\n      <td>-0.439302</td>\n    </tr>\n    <tr>\n      <th>\u05e0\u05e2\u05d5\u05e8\u05d9\u05dd</th>\n      <td>-0.457386</td>\n      <td>-0.439302</td>\n    </tr>\n    <tr>\n      <th>\u05d3\u05d5\u05e8</th>\n      <td>-0.453976</td>\n      <td>-0.385566</td>\n    </tr>\n    <tr>\n      <th>\u05d1\u05e7\u05e8</th>\n      <td>-0.450121</td>\n      <td>0.606823</td>\n    </tr>\n    <tr>\n      <th>\u05d9\u05e8\u05d7</th>\n      <td>-0.447976</td>\n      <td>-0.224210</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05ea</th>\n      <td>-0.446741</td>\n      <td>0.166803</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d5\u05ea</th>\n      <td>-0.414364</td>\n      <td>-0.184939</td>\n    </tr>\n    <tr>\n      <th>\u05dc\u05d9\u05dc\u05d4</th>\n      <td>-0.246892</td>\n      <td>0.294790</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Compare Verb Tense Collocational Tendencies\n\nWe will now make a count of these two categories' collocational tendencies with certain verb tenses. We depend on the [BHSA's](https://github.com/ETCBC/bhsa) encoding of the verbs, which distinguish the following possible categories:\n\n| name | tag |\n| ---- | --- |\n| qa\u1e6dal | qtl |\n| yiq\u1e6dol| yqtl |\n| wayyiq\u1e6dol | wyqtl |\n| imperative | impv |\n| participle | ptcp |\n| infinitive | inf |\n\nNote that the tense names/tags have been adapted from BHSA terms like \"imperfect\" to fit the more theory-neutral terminology. A further category has been added by this project's code, that of the `weqetal` (see the production code [here](../../data/bhsa/tenses.py)):\n\n| name | tag | \n| ---  | --- |\n| weqe\u1e6dal | wqtl |\n\nFor this analysis, we will focus on `qtl`, `yqtl`, `wyqtl`, `wqtl`, and `ptcp`, leaving aside the imperative and infinitives for now. We do not yet distinguish verb tenses on the basis of positionality or length (e.g. long versus short yiq\u1e6dol). \n\n### Calculate and compare tense tendencies with adverbs / nouns\n\nFirst we build a table, `tense_cols` which contains tense collocation counts.\n\n\n```python\ntense_cols_full = times.pivot_table(index=['time'], columns=['tense'], aggfunc='size').fillna(0) # get collocations\ntense_cols = tense_cols_full[['qtl', 'wqtl', 'wyqtl', 'yqtl', 'ptcp',]] # select subset\ntense_cols = tense_cols.loc[tense_cols.sum(1).sort_values(ascending=False).index] # sort by frequency\ntense_ratios = tense_cols.divide(tense_cols.sum(1), axis=0) # get ratios\ntense_fishers, tense_odds = apply_fishers(tense_cols, 0, 1) # Fisher's association scores\n```\n\nThe top of the collocation dataset is shown below, with **raw counts**.\n\n\n```python\ntense_cols.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>tense</th>\n      <th>qtl</th>\n      <th>wqtl</th>\n      <th>wyqtl</th>\n      <th>yqtl</th>\n      <th>ptcp</th>\n    </tr>\n    <tr>\n      <th>time</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>\u05d9\u05d5\u05dd</th>\n      <td>318.0</td>\n      <td>96.0</td>\n      <td>257.0</td>\n      <td>329.0</td>\n      <td>89.0</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05d5\u05d3</th>\n      <td>42.0</td>\n      <td>8.0</td>\n      <td>48.0</td>\n      <td>198.0</td>\n      <td>24.0</td>\n    </tr>\n    <tr>\n      <th>\u05e9\u05c1\u05e0\u05d4</th>\n      <td>97.0</td>\n      <td>11.0</td>\n      <td>66.0</td>\n      <td>36.0</td>\n      <td>3.0</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05d5\u05dc\u05dd</th>\n      <td>23.0</td>\n      <td>19.0</td>\n      <td>6.0</td>\n      <td>77.0</td>\n      <td>9.0</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05ea</th>\n      <td>29.0</td>\n      <td>6.0</td>\n      <td>31.0</td>\n      <td>42.0</td>\n      <td>12.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nWe also have a table which calculates the **ratio representation of each verb per time**, shown below:\n\n\n```python\ntense_ratios.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>tense</th>\n      <th>qtl</th>\n      <th>wqtl</th>\n      <th>wyqtl</th>\n      <th>yqtl</th>\n      <th>ptcp</th>\n    </tr>\n    <tr>\n      <th>time</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>\u05d9\u05d5\u05dd</th>\n      <td>0.292011</td>\n      <td>0.088154</td>\n      <td>0.235996</td>\n      <td>0.302112</td>\n      <td>0.081726</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05d5\u05d3</th>\n      <td>0.131250</td>\n      <td>0.025000</td>\n      <td>0.150000</td>\n      <td>0.618750</td>\n      <td>0.075000</td>\n    </tr>\n    <tr>\n      <th>\u05e9\u05c1\u05e0\u05d4</th>\n      <td>0.455399</td>\n      <td>0.051643</td>\n      <td>0.309859</td>\n      <td>0.169014</td>\n      <td>0.014085</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05d5\u05dc\u05dd</th>\n      <td>0.171642</td>\n      <td>0.141791</td>\n      <td>0.044776</td>\n      <td>0.574627</td>\n      <td>0.067164</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05ea</th>\n      <td>0.241667</td>\n      <td>0.050000</td>\n      <td>0.258333</td>\n      <td>0.350000</td>\n      <td>0.100000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThe ratios alone tell us a verb's representation within a time's own occurrences, but it does not tell us how significant those values are with respect to a verb's overall frequency and co-occurrence with other times. For that we can use [Fisher's exact test](https://en.wikipedia.org/wiki/Fisher%27s_exact_test), which is uniquely suited for non-normal distributions (as we see in natural language data) and datasets with values $< 5$. The Fisher's test returns a `p-value`, which we in turn transform with a $log_{10}$, following [Stefanowitsch and Gries 2003](https://www.researchgate.net/publication/37929828_Collostructions_Investigating_the_interaction_of_words_and_constructions). The null hypothesis that \"there is no association between A and B\" can be rejected when $p < 1.3$, that is $|\\log_{10}0.05|$. We also add a positive or negative sign based on whether the observed frequency falls below the expected frequency, again following Stefanowitsch and Gries. The top of the **Fisher's Exact** table is shown below.\n\n\n```python\ntense_fishers.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>qtl</th>\n      <th>wqtl</th>\n      <th>wyqtl</th>\n      <th>yqtl</th>\n      <th>ptcp</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>\u05d9\u05d5\u05dd</th>\n      <td>1.586072</td>\n      <td>2.950021</td>\n      <td>1.045879</td>\n      <td>-9.452700</td>\n      <td>1.125428</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05d5\u05d3</th>\n      <td>-9.080649</td>\n      <td>-3.247572</td>\n      <td>-2.896506</td>\n      <td>19.778072</td>\n      <td>0.137591</td>\n    </tr>\n    <tr>\n      <th>\u05e9\u05c1\u05e0\u05d4</th>\n      <td>9.001763</td>\n      <td>-0.401541</td>\n      <td>2.853509</td>\n      <td>-10.911849</td>\n      <td>-3.646659</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05d5\u05dc\u05dd</th>\n      <td>-2.030842</td>\n      <td>2.674619</td>\n      <td>-7.666214</td>\n      <td>5.618482</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05ea</th>\n      <td>-0.222696</td>\n      <td>-0.238904</td>\n      <td>0.508451</td>\n      <td>-0.200192</td>\n      <td>0.699389</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### Separate \"adverb\" dataset from \"noun\" dataset\n\nNow that we have a dataset with verb collocation data, we test whether there are strong tendencies for each group of words as identified by the PCA analysis. First we isolate the potential adverbs from the other times.\n\n\n```python\n# adverbs\nadvb_tenses = tense_cols.loc[advbs.index]\nadvb_tenses = advb_tenses.loc[advb_tenses.sum(1).sort_values(ascending=False).index] # sort by N-observations\nadvb_ratio = tense_ratios.loc[advb_tenses.index] \nadvb_fishers = tense_fishers.loc[advb_tenses.index]\n\n# nouns\nnoun_tenses = tense_cols.loc[nouns.index]\nnoun_tenses = noun_tenses.loc[noun_tenses.sum(1).sort_values(ascending=False).index] # sort by N-observations\nnoun_ratio = tense_ratios.loc[noun_tenses.index] \nnoun_fishers = tense_fishers.loc[noun_tenses.index]\n```\n\nBelow is an exhaustive inventory of raw tense collocation counts for all of the \"adverbs.\" \n\n\n```python\nadvb_tenses\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>tense</th>\n      <th>qtl</th>\n      <th>wqtl</th>\n      <th>wyqtl</th>\n      <th>yqtl</th>\n      <th>ptcp</th>\n    </tr>\n    <tr>\n      <th>time</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>\u05e2\u05d5\u05d3</th>\n      <td>42.0</td>\n      <td>8.0</td>\n      <td>48.0</td>\n      <td>198.0</td>\n      <td>24.0</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05d5\u05dc\u05dd</th>\n      <td>23.0</td>\n      <td>19.0</td>\n      <td>6.0</td>\n      <td>77.0</td>\n      <td>9.0</td>\n    </tr>\n    <tr>\n      <th>\u05d0\u05d6</th>\n      <td>43.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>72.0</td>\n      <td>3.0</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05ea\u05d4</th>\n      <td>45.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>44.0</td>\n      <td>2.0</td>\n    </tr>\n    <tr>\n      <th>\u05db\u05df</th>\n      <td>11.0</td>\n      <td>0.0</td>\n      <td>21.0</td>\n      <td>18.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>\u05ea\u05de\u05d9\u05d3</th>\n      <td>2.0</td>\n      <td>6.0</td>\n      <td>0.0</td>\n      <td>18.0</td>\n      <td>6.0</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d7\u05e8</th>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>20.0</td>\n      <td>4.0</td>\n    </tr>\n    <tr>\n      <th>\u05e0\u05e6\u05d7</th>\n      <td>4.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>20.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d7\u05e8\u05ea</th>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>21.0</td>\n      <td>2.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>\u05e4\u05ea\u05d0\u05dd</th>\n      <td>5.0</td>\n      <td>1.0</td>\n      <td>4.0</td>\n      <td>12.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05ea\u05d9</th>\n      <td>2.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>16.0</td>\n      <td>2.0</td>\n    </tr>\n    <tr>\n      <th>\u05e9\u05c1\u05e0\u05d9</th>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>12.0</td>\n      <td>2.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>\u05d9\u05d5\u05de\u05dd</th>\n      <td>5.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>8.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05d3</th>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>11.0</td>\n      <td>3.0</td>\n    </tr>\n    <tr>\n      <th>\u05d0\u05df</th>\n      <td>2.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>11.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>\u05d8\u05e8\u05dd</th>\n      <td>2.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>9.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>\u05e8\u05d2\u05e2</th>\n      <td>4.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>7.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d4\u05e8\u05d4</th>\n      <td>2.0</td>\n      <td>2.0</td>\n      <td>2.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d4\u05e8</th>\n      <td>4.0</td>\n      <td>2.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>\u05d4\u05e0\u05d4</th>\n      <td>2.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThe numbers are summarized below. For reference, `count` refers to number of non-zero observations. `25%` etc. refer to the percentile. The other values are self-explanatory.\n\n\n```python\nadvb_tenses.describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>tense</th>\n      <th>qtl</th>\n      <th>wqtl</th>\n      <th>wyqtl</th>\n      <th>yqtl</th>\n      <th>ptcp</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>20.000000</td>\n      <td>20.000000</td>\n      <td>20.000000</td>\n      <td>20.000000</td>\n      <td>20.000000</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>9.950000</td>\n      <td>2.150000</td>\n      <td>5.800000</td>\n      <td>27.500000</td>\n      <td>2.900000</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>15.271146</td>\n      <td>4.522168</td>\n      <td>11.954299</td>\n      <td>45.555634</td>\n      <td>5.485867</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>2.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>6.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>3.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>11.500000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>6.500000</td>\n      <td>2.000000</td>\n      <td>4.500000</td>\n      <td>20.000000</td>\n      <td>3.000000</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>45.000000</td>\n      <td>19.000000</td>\n      <td>48.000000</td>\n      <td>198.000000</td>\n      <td>24.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThe ratios are shown below:\n\n\n```python\nadvb_ratio\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>tense</th>\n      <th>qtl</th>\n      <th>wqtl</th>\n      <th>wyqtl</th>\n      <th>yqtl</th>\n      <th>ptcp</th>\n    </tr>\n    <tr>\n      <th>time</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>\u05e2\u05d5\u05d3</th>\n      <td>0.131250</td>\n      <td>0.025000</td>\n      <td>0.150000</td>\n      <td>0.618750</td>\n      <td>0.075000</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05d5\u05dc\u05dd</th>\n      <td>0.171642</td>\n      <td>0.141791</td>\n      <td>0.044776</td>\n      <td>0.574627</td>\n      <td>0.067164</td>\n    </tr>\n    <tr>\n      <th>\u05d0\u05d6</th>\n      <td>0.361345</td>\n      <td>0.000000</td>\n      <td>0.008403</td>\n      <td>0.605042</td>\n      <td>0.025210</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05ea\u05d4</th>\n      <td>0.494505</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.483516</td>\n      <td>0.021978</td>\n    </tr>\n    <tr>\n      <th>\u05db\u05df</th>\n      <td>0.220000</td>\n      <td>0.000000</td>\n      <td>0.420000</td>\n      <td>0.360000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05ea\u05de\u05d9\u05d3</th>\n      <td>0.062500</td>\n      <td>0.187500</td>\n      <td>0.000000</td>\n      <td>0.562500</td>\n      <td>0.187500</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d7\u05e8</th>\n      <td>0.038462</td>\n      <td>0.038462</td>\n      <td>0.000000</td>\n      <td>0.769231</td>\n      <td>0.153846</td>\n    </tr>\n    <tr>\n      <th>\u05e0\u05e6\u05d7</th>\n      <td>0.160000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.800000</td>\n      <td>0.040000</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d7\u05e8\u05ea</th>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.913043</td>\n      <td>0.086957</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05e4\u05ea\u05d0\u05dd</th>\n      <td>0.217391</td>\n      <td>0.043478</td>\n      <td>0.173913</td>\n      <td>0.521739</td>\n      <td>0.043478</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05ea\u05d9</th>\n      <td>0.100000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.800000</td>\n      <td>0.100000</td>\n    </tr>\n    <tr>\n      <th>\u05e9\u05c1\u05e0\u05d9</th>\n      <td>0.000000</td>\n      <td>0.176471</td>\n      <td>0.705882</td>\n      <td>0.117647</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05d9\u05d5\u05de\u05dd</th>\n      <td>0.312500</td>\n      <td>0.062500</td>\n      <td>0.062500</td>\n      <td>0.500000</td>\n      <td>0.062500</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05d3</th>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.785714</td>\n      <td>0.214286</td>\n    </tr>\n    <tr>\n      <th>\u05d0\u05df</th>\n      <td>0.142857</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.785714</td>\n      <td>0.071429</td>\n    </tr>\n    <tr>\n      <th>\u05d8\u05e8\u05dd</th>\n      <td>0.181818</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.818182</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05e8\u05d2\u05e2</th>\n      <td>0.363636</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.636364</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d4\u05e8\u05d4</th>\n      <td>0.222222</td>\n      <td>0.222222</td>\n      <td>0.222222</td>\n      <td>0.333333</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d4\u05e8</th>\n      <td>0.571429</td>\n      <td>0.285714</td>\n      <td>0.000000</td>\n      <td>0.142857</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05d4\u05e0\u05d4</th>\n      <td>0.500000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.250000</td>\n      <td>0.250000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### Ratio across all \"adverbs\" (versus \"nouns\")\n\nWe can see in the summary below that the adverb group has a high proportion of yiqtol representation:\n\n\n```python\nall_advb_tenses = advb_tenses.sum() / advb_tenses.sum().sum()\n\nall_advb_tenses\n```\n\n\n\n\n    tense\n    qtl      0.206004\n    wqtl     0.044513\n    wyqtl    0.120083\n    yqtl     0.569358\n    ptcp     0.060041\n    dtype: float64\n\n\n\nLet's see how this compares against the \"nouns\" group.\n\n\n```python\nall_noun_tenses = noun_tenses.sum() / noun_tenses.sum().sum()\n\nall_noun_tenses\n```\n\n\n\n\n    tense\n    qtl      0.286929\n    wqtl     0.085016\n    wyqtl    0.276833\n    yqtl     0.279490\n    ptcp     0.071732\n    dtype: float64\n\n\n\nWe get the difference between the two distributions:\n\n\n```python\nnoun_advb_difference = (all_advb_tenses - all_noun_tenses).abs()\n\nnoun_advb_difference\n```\n\n\n\n\n    tense\n    qtl      0.080925\n    wqtl     0.040502\n    wyqtl    0.156750\n    yqtl     0.289868\n    ptcp     0.011691\n    dtype: float64\n\n\n\nThe biggest difference is the yiqtol's representation at ~30% more within the adverb group.\n\n### \"Adverbs\" and Fisher's exact tests\n\nThe Fisher's scores for adverbs are show below. $1.3 < score < -1.3$ is statistically significant:\n\n#### Association with any tense\n\n\n```python\nadvb_fishers\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>qtl</th>\n      <th>wqtl</th>\n      <th>wyqtl</th>\n      <th>yqtl</th>\n      <th>ptcp</th>\n    </tr>\n    <tr>\n      <th>time</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>\u05e2\u05d5\u05d3</th>\n      <td>-9.080649</td>\n      <td>-3.247572</td>\n      <td>-2.896506</td>\n      <td>19.778072</td>\n      <td>0.137591</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05d5\u05dc\u05dd</th>\n      <td>-2.030842</td>\n      <td>2.674619</td>\n      <td>-7.666214</td>\n      <td>5.618482</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05d0\u05d6</th>\n      <td>1.586010</td>\n      <td>-3.301144</td>\n      <td>-11.248105</td>\n      <td>6.498397</td>\n      <td>-1.351648</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05ea\u05d4</th>\n      <td>5.521070</td>\n      <td>-2.606705</td>\n      <td>-9.760595</td>\n      <td>1.439333</td>\n      <td>-1.042144</td>\n    </tr>\n    <tr>\n      <th>\u05db\u05df</th>\n      <td>-0.282993</td>\n      <td>-1.331073</td>\n      <td>2.833125</td>\n      <td>-0.053707</td>\n      <td>-1.329310</td>\n    </tr>\n    <tr>\n      <th>\u05ea\u05de\u05d9\u05d3</th>\n      <td>-2.117939</td>\n      <td>1.737141</td>\n      <td>-3.124449</td>\n      <td>1.380447</td>\n      <td>1.662020</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d7\u05e8</th>\n      <td>-2.217454</td>\n      <td>0.000000</td>\n      <td>-2.525332</td>\n      <td>4.286143</td>\n      <td>0.977794</td>\n    </tr>\n    <tr>\n      <th>\u05e0\u05e6\u05d7</th>\n      <td>-0.578327</td>\n      <td>-0.387902</td>\n      <td>-2.537950</td>\n      <td>4.617990</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d7\u05e8\u05ea</th>\n      <td>-2.876783</td>\n      <td>-0.398917</td>\n      <td>11.758661</td>\n      <td>-2.416684</td>\n      <td>-0.395153</td>\n    </tr>\n    <tr>\n      <th>\u05e4\u05ea\u05d0\u05dd</th>\n      <td>-0.089793</td>\n      <td>0.000000</td>\n      <td>-0.096298</td>\n      <td>0.713563</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05ea\u05d9</th>\n      <td>-0.899719</td>\n      <td>-0.404130</td>\n      <td>-1.917864</td>\n      <td>3.687975</td>\n      <td>0.188855</td>\n    </tr>\n    <tr>\n      <th>\u05e9\u05c1\u05e0\u05d9</th>\n      <td>-1.994594</td>\n      <td>0.987496</td>\n      <td>4.640552</td>\n      <td>-1.388484</td>\n      <td>-0.202828</td>\n    </tr>\n    <tr>\n      <th>\u05d9\u05d5\u05de\u05dd</th>\n      <td>0.109501</td>\n      <td>0.000000</td>\n      <td>-0.656254</td>\n      <td>0.506937</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05d3</th>\n      <td>-1.549583</td>\n      <td>-0.208964</td>\n      <td>-1.301094</td>\n      <td>2.460708</td>\n      <td>1.154166</td>\n    </tr>\n    <tr>\n      <th>\u05d0\u05df</th>\n      <td>-0.423193</td>\n      <td>-0.208964</td>\n      <td>-1.301094</td>\n      <td>2.460708</td>\n      <td>-0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05d8\u05e8\u05dd</th>\n      <td>-0.132099</td>\n      <td>0.000000</td>\n      <td>-0.865613</td>\n      <td>2.452161</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05e8\u05d2\u05e2</th>\n      <td>0.302056</td>\n      <td>0.000000</td>\n      <td>-0.865613</td>\n      <td>0.941003</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d4\u05e8\u05d4</th>\n      <td>0.000000</td>\n      <td>0.921577</td>\n      <td>-0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d4\u05e8</th>\n      <td>1.056650</td>\n      <td>1.117225</td>\n      <td>-0.445077</td>\n      <td>-0.573658</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05d4\u05e0\u05d4</th>\n      <td>0.534929</td>\n      <td>0.000000</td>\n      <td>-0.234763</td>\n      <td>0.000000</td>\n      <td>0.596753</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n#### Associations with yiqtol\n\nWe select those scores where $score > 1.3$ for the yiqtol verb.\n\n\n```python\nadvb_yqtl_assoc = advb_fishers[advb_fishers['yqtl'] > 1.3].sort_values(by='yqtl', ascending=False)\n\nadvb_yqtl_assoc\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>qtl</th>\n      <th>wqtl</th>\n      <th>wyqtl</th>\n      <th>yqtl</th>\n      <th>ptcp</th>\n    </tr>\n    <tr>\n      <th>time</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>\u05e2\u05d5\u05d3</th>\n      <td>-9.080649</td>\n      <td>-3.247572</td>\n      <td>-2.896506</td>\n      <td>19.778072</td>\n      <td>0.137591</td>\n    </tr>\n    <tr>\n      <th>\u05d0\u05d6</th>\n      <td>1.586010</td>\n      <td>-3.301144</td>\n      <td>-11.248105</td>\n      <td>6.498397</td>\n      <td>-1.351648</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05d5\u05dc\u05dd</th>\n      <td>-2.030842</td>\n      <td>2.674619</td>\n      <td>-7.666214</td>\n      <td>5.618482</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05e0\u05e6\u05d7</th>\n      <td>-0.578327</td>\n      <td>-0.387902</td>\n      <td>-2.537950</td>\n      <td>4.617990</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d7\u05e8</th>\n      <td>-2.217454</td>\n      <td>0.000000</td>\n      <td>-2.525332</td>\n      <td>4.286143</td>\n      <td>0.977794</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05ea\u05d9</th>\n      <td>-0.899719</td>\n      <td>-0.404130</td>\n      <td>-1.917864</td>\n      <td>3.687975</td>\n      <td>0.188855</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05d3</th>\n      <td>-1.549583</td>\n      <td>-0.208964</td>\n      <td>-1.301094</td>\n      <td>2.460708</td>\n      <td>1.154166</td>\n    </tr>\n    <tr>\n      <th>\u05d0\u05df</th>\n      <td>-0.423193</td>\n      <td>-0.208964</td>\n      <td>-1.301094</td>\n      <td>2.460708</td>\n      <td>-0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05d8\u05e8\u05dd</th>\n      <td>-0.132099</td>\n      <td>0.000000</td>\n      <td>-0.865613</td>\n      <td>2.452161</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05ea\u05d4</th>\n      <td>5.521070</td>\n      <td>-2.606705</td>\n      <td>-9.760595</td>\n      <td>1.439333</td>\n      <td>-1.042144</td>\n    </tr>\n    <tr>\n      <th>\u05ea\u05de\u05d9\u05d3</th>\n      <td>-2.117939</td>\n      <td>1.737141</td>\n      <td>-3.124449</td>\n      <td>1.380447</td>\n      <td>1.662020</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nfig = plt.figure(figsize=(8, 6))\nax = sns.heatmap(advb_yqtl_assoc, center=0, robust=True)\nax.set_yticklabels([get_display(t) for t in advb_yqtl_assoc.index], size=16, rotation=0, fontfamily='serif')\nax.set_ylabel('time word')\nax.set_xlabel('verb tense')\nplt.show()\n```\n\n#### Disassociations with yiqtol\n\nWe select scores where $score < -1.3$. This means that the observed co-occurrence frequency is lower than would be expected in a random distribution.\n\n\n```python\nadvb_yqtl_dassoc =  advb_fishers[advb_fishers['yqtl'] < -1.3].sort_values(by='yqtl', ascending=False)\n\nadvb_yqtl_dassoc\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>qtl</th>\n      <th>wqtl</th>\n      <th>wyqtl</th>\n      <th>yqtl</th>\n      <th>ptcp</th>\n    </tr>\n    <tr>\n      <th>time</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>\u05e9\u05c1\u05e0\u05d9</th>\n      <td>-1.994594</td>\n      <td>0.987496</td>\n      <td>4.640552</td>\n      <td>-1.388484</td>\n      <td>-0.202828</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d7\u05e8\u05ea</th>\n      <td>-2.876783</td>\n      <td>-0.398917</td>\n      <td>11.758661</td>\n      <td>-2.416684</td>\n      <td>-0.395153</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nOnly two terms are marked as especially disassociated with the verb: \u05e9\u05e0\u05d9 and \u05de\u05d7\u05e8\u05ea. We see that both are statistically attracted to wayyiqtol. And likewise disassociated with qatal. There is no statistically significant values for participles and weqatals. \n\n#### Neutral scores with respect to yiqtol\n\nWhat terms are neutral to the yiqtol? i.e. they are neither associated nor disassociated.\n\n\n```python\nadvb_yqtl_neut = advb_fishers[(advb_fishers['yqtl'] < 1.3) & (advb_fishers['yqtl'] > -1.3)].sort_values(by='yqtl', ascending=False)\n\nadvb_yqtl_neut\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>qtl</th>\n      <th>wqtl</th>\n      <th>wyqtl</th>\n      <th>yqtl</th>\n      <th>ptcp</th>\n    </tr>\n    <tr>\n      <th>time</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>\u05e8\u05d2\u05e2</th>\n      <td>0.302056</td>\n      <td>0.000000</td>\n      <td>-0.865613</td>\n      <td>0.941003</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05e4\u05ea\u05d0\u05dd</th>\n      <td>-0.089793</td>\n      <td>0.000000</td>\n      <td>-0.096298</td>\n      <td>0.713563</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05d9\u05d5\u05de\u05dd</th>\n      <td>0.109501</td>\n      <td>0.000000</td>\n      <td>-0.656254</td>\n      <td>0.506937</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d4\u05e8\u05d4</th>\n      <td>0.000000</td>\n      <td>0.921577</td>\n      <td>-0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05d4\u05e0\u05d4</th>\n      <td>0.534929</td>\n      <td>0.000000</td>\n      <td>-0.234763</td>\n      <td>0.000000</td>\n      <td>0.596753</td>\n    </tr>\n    <tr>\n      <th>\u05db\u05df</th>\n      <td>-0.282993</td>\n      <td>-1.331073</td>\n      <td>2.833125</td>\n      <td>-0.053707</td>\n      <td>-1.329310</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d4\u05e8</th>\n      <td>1.056650</td>\n      <td>1.117225</td>\n      <td>-0.445077</td>\n      <td>-0.573658</td>\n      <td>0.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nSome of these terms refer to suddenness: \u05de\u05d4\u05e8, \u05de\u05d4\u05e8\u05d4, \u05e4\u05ea\u05d0\u05dd. Others refer to positions in time like \u05e8\u05d2\u05e2. We also see \u05d9\u05d5\u05de\u05dd. \n\nWe do not see any terms that refer to extended durations or open ended/unknown times, as we did with those that are attracted to yiqtol. \n\n### \"Noun\" associations with yiqtol\n\n\n```python\nnoun_fishers\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>qtl</th>\n      <th>wqtl</th>\n      <th>wyqtl</th>\n      <th>yqtl</th>\n      <th>ptcp</th>\n    </tr>\n    <tr>\n      <th>time</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>\u05d9\u05d5\u05dd</th>\n      <td>1.586072</td>\n      <td>2.950021</td>\n      <td>1.045879</td>\n      <td>-9.452700</td>\n      <td>1.125428</td>\n    </tr>\n    <tr>\n      <th>\u05e9\u05c1\u05e0\u05d4</th>\n      <td>9.001763</td>\n      <td>-0.401541</td>\n      <td>2.853509</td>\n      <td>-10.911849</td>\n      <td>-3.646659</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05ea</th>\n      <td>-0.222696</td>\n      <td>-0.238904</td>\n      <td>0.508451</td>\n      <td>-0.200192</td>\n      <td>0.699389</td>\n    </tr>\n    <tr>\n      <th>\u05dc\u05d9\u05dc\u05d4</th>\n      <td>-0.507048</td>\n      <td>-0.497665</td>\n      <td>10.457816</td>\n      <td>-7.354929</td>\n      <td>0.488659</td>\n    </tr>\n    <tr>\n      <th>\u05d1\u05e7\u05e8</th>\n      <td>-7.399966</td>\n      <td>0.175056</td>\n      <td>9.841146</td>\n      <td>-0.821145</td>\n      <td>-0.079382</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05e8\u05d1</th>\n      <td>-2.766337</td>\n      <td>7.771832</td>\n      <td>-0.250691</td>\n      <td>0.094592</td>\n      <td>-0.627759</td>\n    </tr>\n    <tr>\n      <th>\u05e4\u05e2\u05dd</th>\n      <td>-0.125087</td>\n      <td>1.093670</td>\n      <td>0.913084</td>\n      <td>-0.834382</td>\n      <td>-0.236854</td>\n    </tr>\n    <tr>\n      <th>\u05d7\u05d3\u05e9\u05c1</th>\n      <td>0.472044</td>\n      <td>0.000000</td>\n      <td>1.013502</td>\n      <td>-1.885576</td>\n      <td>0.134547</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d5\u05ea</th>\n      <td>0.092548</td>\n      <td>0.000000</td>\n      <td>1.876936</td>\n      <td>-0.952690</td>\n      <td>-0.403455</td>\n    </tr>\n    <tr>\n      <th>\u05e4\u05e0\u05d4</th>\n      <td>4.118958</td>\n      <td>-0.208964</td>\n      <td>-1.301094</td>\n      <td>-1.633336</td>\n      <td>0.588294</td>\n    </tr>\n    <tr>\n      <th>\u05d3\u05d1\u05e8</th>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>2.644836</td>\n      <td>-0.825327</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05e6\u05d4\u05e8\u05d9\u05dd</th>\n      <td>-0.697813</td>\n      <td>0.715082</td>\n      <td>0.135309</td>\n      <td>0.415514</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05e0\u05e2\u05d5\u05e8\u05d9\u05dd</th>\n      <td>0.910678</td>\n      <td>0.000000</td>\n      <td>-0.227482</td>\n      <td>-0.784677</td>\n      <td>1.369430</td>\n    </tr>\n    <tr>\n      <th>\u05e9\u05c1\u05d1\u05e2</th>\n      <td>-0.477258</td>\n      <td>0.000000</td>\n      <td>-0.227482</td>\n      <td>1.158950</td>\n      <td>0.514756</td>\n    </tr>\n    <tr>\n      <th>\u05d7\u05d9\u05d9\u05dd</th>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.431032</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05e9\u05c1\u05d1\u05d5\u05e2</th>\n      <td>-0.477258</td>\n      <td>1.400536</td>\n      <td>-0.227482</td>\n      <td>0.431032</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05e8\u05d0\u05e9\u05c1\u05d5\u05df</th>\n      <td>1.697273</td>\n      <td>0.000000</td>\n      <td>-0.227482</td>\n      <td>-0.182894</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05de\u05d5\u05e2\u05d3</th>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>-0.234763</td>\n      <td>0.197910</td>\n      <td>0.596753</td>\n    </tr>\n    <tr>\n      <th>\u05e9\u05c1\u05d1\u05ea</th>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>-0.234763</td>\n      <td>0.000000</td>\n      <td>1.570864</td>\n    </tr>\n    <tr>\n      <th>\u05ea\u05d7\u05dc\u05d4</th>\n      <td>0.534929</td>\n      <td>0.000000</td>\n      <td>-0.000000</td>\n      <td>-0.517269</td>\n      <td>0.596753</td>\n    </tr>\n    <tr>\n      <th>\u05e8\u05d2\u05dc</th>\n      <td>0.534929</td>\n      <td>0.000000</td>\n      <td>-0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05d3\u05d5\u05e8</th>\n      <td>0.000000</td>\n      <td>0.611711</td>\n      <td>-0.234763</td>\n      <td>0.197910</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>\u05d9\u05e8\u05d7</th>\n      <td>0.000000</td>\n      <td>0.611711</td>\n      <td>0.676962</td>\n      <td>-0.517269</td>\n      <td>0.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nfig = plt.figure(figsize=(8, 10))\nax = sns.heatmap(noun_fishers, center=0, robust=True)\nax.set_yticklabels([get_display(t) for t in noun_fishers.index], size=16, rotation=0, fontfamily='serif')\nax.set_ylabel('time word')\nax.set_xlabel('verb tense')\nplt.show()\n```\n\n<hr>\n\n## Scatter Plots of Variables\n\n### PC1 versus Yiq\u1e6dol\n\nI'm curious to test whether distance along PC1 space correlates with frequency of use with the yiq\u1e6dol verb. We will make a scatter plot of the two values to see if there's any noticeable trend.\n\n\n```python\npc1_and_yqtl = pd.concat([tense_ratios['yqtl'], time_pca['PC1']], axis=1, sort=True).dropna()\n```\n\n\n```python\nx, y = pc1_and_yqtl['PC1'], pc1_and_yqtl['yqtl']\nslope, intercept, r, p, std_err = linregress(x,y)\nfig, ax = plt.subplots(figsize=(8,6))\nax.set_xlabel('PC1', size=14)\nax.set_ylabel('yqtl', size=14)\nax.scatter(x=x, y=y, color='black', s=8)\n\n# plot regression line\nr_x = np.unique(x.values) # avoid duplicate points\nr_y = slope*r_x+intercept\nax.plot(r_x, r_y, color='red', linewidth=1.2)\n\nax.set_title(f'PC1 vs. yqtl (r={round(r, 2)}) (p={round(p, 4)})')\nplt.show()\n```\n\nWe do see a trend for more yiqtol representation in times that are further along the first principle component. Despite there being some exceptions, our $p=0.00021$ shows the correlation to be significant.\n\nThis correlation is important because it potentially shows another distinguishing feature of these \"adverb\" time words: **they are not only distinguished by their use without nominalizing constructions, they are also distinguished by their preference for the yiqtol verb form.** This confirms the data we have already seen in the dominant proportional representation of yiqtol in this group, as well as in the Fisher's exact scores.\n\n### Time construction co-occurrence preferences versus yiqtol\n\nWe dig down a little bit deeper. Can we corroborate the principle component analysis by looking at word tendencies throughout the various constructions? \n\nFor this analysis, for every time word, we take the ratio of its co-occurrence with nominalizing constructions and its ratio of tense co-occurrences. We want to answer: **Are times that occur more/less often with construction X more/less likely to co-occur with the yiqtol**?\n\nWe then build a separate scatter plot for each one to see whether there is a negative or positive correlation.\n\n\n```python\nsample = time_cols[time_cols.sum(1) > 10]\nsample_tenses = tense_ratios.loc[sample.index]\nsample_cols = time_col_ratio.loc[sample.index]\n```\n\n\n```python\ndo_cxs = [\n    'definite', 'demonstrative', \n    'quantified', 'time_pl', 'genitive',\n    'bare',\n]\n\nnom_yiq_dataset = {}\n\nfor cx in do_cxs:\n    cx_data = sample_cols[cx]\n    tense_data = sample_tenses['yqtl']\n    tense_and_cx = pd.concat([cx_data, tense_data], sort=False, axis=1).fillna(0)\n    tense_and_cx = tense_and_cx[(tense_and_cx > 0).any(1)] # prune null counts\n    nom_yiq_dataset[cx] = tense_and_cx\n```\n\n\n```python\nfig = plt.figure(figsize=(10,10))\n\nfor i, data in enumerate(nom_yiq_dataset.items()):\n    \n    # axes + linear regression analysis\n    cx, df = data\n    x, y =  df[cx], df['yqtl']\n    slope, intercept, r, p, std_err = linregress(x,y)\n    \n    # make plot\n    ax = fig.add_subplot(3, 2, i+1)\n    ax.scatter(x, y, color='', edgecolor='black')\n    ax.set_ylabel('yiqtol')\n    ax.set_xlabel(f'{cx}')\n    ax.set_title(f'{cx} (r={round(r, 2)}) (p={round(p, 3)})')\n    \n    # plot regression line\n    rx = np.unique(x.values)\n    ry = slope*rx+intercept\n    ax.plot(rx, ry, 'red', linewidth=1)\n\n    \nfig.tight_layout()\nplt.savefig(fg_path('yqtl_nominalizers_scatter.png'), dpi=300, bbox_inches='tight')\nplt.show()\n```\n\nThe graphs show the strongest effect in the `bare` category ($p=0.002$). This is essentially a reproduction of the principle component analysis results, which was based on these same features together. \n\nThe graph is likewise very similar to the yiqtol and PC1 plot above. We do not see nearly as much as an effect with any of the other time words.\n\n## Collocation with Nominalizing Constructions\n\nUp to this point we have compared the behavior of time words against their co-occurrence with yiqtol. We've also shown that \"adverb\" words which are distinguished by a preference for bare constructions are likewise distinguished by their preference for yiqtol.\n\nUp until now we have been able to find any strong effects when yiqtol is paired with the nominalizing constructions themselves. So now we will attempt to measure this directly. We ask: **Is the yiqtol more or less likely to occur in the presence of a nominalizing construction?** Remember that for our purposes here we define a \"nominalizing construction\" as any construction which communicates definiteness, quantity, or posession.\n\nTo answer the research question, we first compose tables of collocations between all verb tenses and these various constructions. We build two datasets:\n\n1. yiqtol collocations with nominalizers for all time words\n2. yiqtol collocations with nominalizers for noun words\n\nWe make the second table to see whether yiqtol has any suppressive effect on nominalizers even amongst noun-like terms.\n\n## Fisher's \n\n\n```python\nnoun_data = times[times.time.isin(nouns.index)]\n```\n\n\n```python\n# compile collocation table of time heads with nominalizing constructions\nnoms = [\n    'time_pl', 'quantified', 'definite', \n    'demonstrative', 'ordinal', 'time_sffx',\n    'bare', 'genitive'\n]\nexclude_verbs = ['infa','infc','impv']\n\nverb_nom_cols = pd.pivot_table(\n    times, \n    index=['tense'], \n    values=noms,\n    aggfunc=np.sum\n).drop(exclude_verbs)\n\nverb_nom_ratios = verb_nom_cols.div(verb_nom_cols.sum(1), axis=0)\n\nverb_nom_cols_nouns = pd.pivot_table(\n    noun_data, \n    index=['tense'], \n    values=noms,\n    aggfunc=np.sum\n).drop(exclude_verbs)\n\nverb_nom_ratios_nouns = verb_nom_cols_nouns.div(verb_nom_cols_nouns.sum(1), axis=0)\n```\n\n\n```python\nverb_nom_cols\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>bare</th>\n      <th>definite</th>\n      <th>demonstrative</th>\n      <th>genitive</th>\n      <th>ordinal</th>\n      <th>quantified</th>\n      <th>time_pl</th>\n      <th>time_sffx</th>\n    </tr>\n    <tr>\n      <th>tense</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>ptcp</th>\n      <td>70.0</td>\n      <td>95.0</td>\n      <td>16.0</td>\n      <td>28.0</td>\n      <td>4.0</td>\n      <td>18.0</td>\n      <td>22.0</td>\n      <td>10.0</td>\n    </tr>\n    <tr>\n      <th>qtl</th>\n      <td>230.0</td>\n      <td>274.0</td>\n      <td>130.0</td>\n      <td>108.0</td>\n      <td>21.0</td>\n      <td>162.0</td>\n      <td>169.0</td>\n      <td>52.0</td>\n    </tr>\n    <tr>\n      <th>wqtl</th>\n      <td>45.0</td>\n      <td>98.0</td>\n      <td>38.0</td>\n      <td>21.0</td>\n      <td>16.0</td>\n      <td>48.0</td>\n      <td>44.0</td>\n      <td>5.0</td>\n    </tr>\n    <tr>\n      <th>wyqtl</th>\n      <td>136.0</td>\n      <td>315.0</td>\n      <td>163.0</td>\n      <td>57.0</td>\n      <td>40.0</td>\n      <td>165.0</td>\n      <td>134.0</td>\n      <td>8.0</td>\n    </tr>\n    <tr>\n      <th>yqtl</th>\n      <td>579.0</td>\n      <td>275.0</td>\n      <td>98.0</td>\n      <td>120.0</td>\n      <td>35.0</td>\n      <td>155.0</td>\n      <td>156.0</td>\n      <td>43.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nWe also have calculated ratios across the verbs:\n\n\n```python\nverb_nom_ratios\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>bare</th>\n      <th>definite</th>\n      <th>demonstrative</th>\n      <th>genitive</th>\n      <th>ordinal</th>\n      <th>quantified</th>\n      <th>time_pl</th>\n      <th>time_sffx</th>\n    </tr>\n    <tr>\n      <th>tense</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>ptcp</th>\n      <td>0.266160</td>\n      <td>0.361217</td>\n      <td>0.060837</td>\n      <td>0.106464</td>\n      <td>0.015209</td>\n      <td>0.068441</td>\n      <td>0.083650</td>\n      <td>0.038023</td>\n    </tr>\n    <tr>\n      <th>qtl</th>\n      <td>0.200698</td>\n      <td>0.239092</td>\n      <td>0.113438</td>\n      <td>0.094241</td>\n      <td>0.018325</td>\n      <td>0.141361</td>\n      <td>0.147469</td>\n      <td>0.045375</td>\n    </tr>\n    <tr>\n      <th>wqtl</th>\n      <td>0.142857</td>\n      <td>0.311111</td>\n      <td>0.120635</td>\n      <td>0.066667</td>\n      <td>0.050794</td>\n      <td>0.152381</td>\n      <td>0.139683</td>\n      <td>0.015873</td>\n    </tr>\n    <tr>\n      <th>wyqtl</th>\n      <td>0.133595</td>\n      <td>0.309430</td>\n      <td>0.160118</td>\n      <td>0.055992</td>\n      <td>0.039293</td>\n      <td>0.162083</td>\n      <td>0.131631</td>\n      <td>0.007859</td>\n    </tr>\n    <tr>\n      <th>yqtl</th>\n      <td>0.396304</td>\n      <td>0.188227</td>\n      <td>0.067077</td>\n      <td>0.082136</td>\n      <td>0.023956</td>\n      <td>0.106092</td>\n      <td>0.106776</td>\n      <td>0.029432</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nAnd now the nouns raw counts along with those ratios:\n\n\n```python\nverb_nom_cols_nouns\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>bare</th>\n      <th>definite</th>\n      <th>demonstrative</th>\n      <th>genitive</th>\n      <th>ordinal</th>\n      <th>quantified</th>\n      <th>time_pl</th>\n      <th>time_sffx</th>\n    </tr>\n    <tr>\n      <th>tense</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>ptcp</th>\n      <td>6.0</td>\n      <td>92.0</td>\n      <td>16.0</td>\n      <td>22.0</td>\n      <td>4.0</td>\n      <td>18.0</td>\n      <td>20.0</td>\n      <td>7.0</td>\n    </tr>\n    <tr>\n      <th>qtl</th>\n      <td>9.0</td>\n      <td>266.0</td>\n      <td>128.0</td>\n      <td>97.0</td>\n      <td>21.0</td>\n      <td>160.0</td>\n      <td>146.0</td>\n      <td>31.0</td>\n    </tr>\n    <tr>\n      <th>wqtl</th>\n      <td>2.0</td>\n      <td>98.0</td>\n      <td>38.0</td>\n      <td>20.0</td>\n      <td>16.0</td>\n      <td>48.0</td>\n      <td>44.0</td>\n      <td>5.0</td>\n    </tr>\n    <tr>\n      <th>wyqtl</th>\n      <td>21.0</td>\n      <td>307.0</td>\n      <td>163.0</td>\n      <td>48.0</td>\n      <td>39.0</td>\n      <td>164.0</td>\n      <td>128.0</td>\n      <td>2.0</td>\n    </tr>\n    <tr>\n      <th>yqtl</th>\n      <td>14.0</td>\n      <td>267.0</td>\n      <td>98.0</td>\n      <td>112.0</td>\n      <td>35.0</td>\n      <td>152.0</td>\n      <td>145.0</td>\n      <td>30.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nverb_nom_cols_nouns.sum(1)\n```\n\n\n\n\n    tense\n    ptcp     185.0\n    qtl      858.0\n    wqtl     271.0\n    wyqtl    872.0\n    yqtl     853.0\n    dtype: float64\n\n\n\n\n```python\nverb_nom_ratios_nouns\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>bare</th>\n      <th>definite</th>\n      <th>demonstrative</th>\n      <th>genitive</th>\n      <th>ordinal</th>\n      <th>quantified</th>\n      <th>time_pl</th>\n      <th>time_sffx</th>\n    </tr>\n    <tr>\n      <th>tense</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>ptcp</th>\n      <td>0.032432</td>\n      <td>0.497297</td>\n      <td>0.086486</td>\n      <td>0.118919</td>\n      <td>0.021622</td>\n      <td>0.097297</td>\n      <td>0.108108</td>\n      <td>0.037838</td>\n    </tr>\n    <tr>\n      <th>qtl</th>\n      <td>0.010490</td>\n      <td>0.310023</td>\n      <td>0.149184</td>\n      <td>0.113054</td>\n      <td>0.024476</td>\n      <td>0.186480</td>\n      <td>0.170163</td>\n      <td>0.036131</td>\n    </tr>\n    <tr>\n      <th>wqtl</th>\n      <td>0.007380</td>\n      <td>0.361624</td>\n      <td>0.140221</td>\n      <td>0.073801</td>\n      <td>0.059041</td>\n      <td>0.177122</td>\n      <td>0.162362</td>\n      <td>0.018450</td>\n    </tr>\n    <tr>\n      <th>wyqtl</th>\n      <td>0.024083</td>\n      <td>0.352064</td>\n      <td>0.186927</td>\n      <td>0.055046</td>\n      <td>0.044725</td>\n      <td>0.188073</td>\n      <td>0.146789</td>\n      <td>0.002294</td>\n    </tr>\n    <tr>\n      <th>yqtl</th>\n      <td>0.016413</td>\n      <td>0.313013</td>\n      <td>0.114889</td>\n      <td>0.131301</td>\n      <td>0.041032</td>\n      <td>0.178195</td>\n      <td>0.169988</td>\n      <td>0.035170</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n#### Fisher's with All\n\n\n```python\nverb_nom_cols_fishers, verb_nom_cols_odds = apply_fishers(verb_nom_cols, 0, 1)\n```\n\n\n```python\nplt.figure(figsize=(10, 6))\nax = sns.heatmap(verb_nom_cols_fishers, center=0, robust=True)\nax.set_yticklabels(verb_nom_cols_fishers.index, rotation=0)\nplt.savefig(fg_path('tense_nominalizer_attractions.png'), dpi=300, bbox_inches='tight')\nplt.title('Tense and Nominalization CX Attractions (Fisher\\'s)')\nplt.show()\ndisplay(verb_nom_cols_fishers)\n```\n\n#### Fisher's with Nouns\n\n\n```python\nverb_nom_cols_noun_fishers, verb_nom_cols_noun_fishers_odds = apply_fishers(verb_nom_cols_nouns, 0, 1)\n```\n\n\n```python\nplt.figure(figsize=(10, 6))\nax = sns.heatmap(verb_nom_cols_noun_fishers, center=0, robust=True)\nax.set_yticklabels(verb_nom_cols_noun_fishers.index, rotation=0)\nplt.savefig(fg_path('tense_nominalizer_attractions_nouns.png'), dpi=300, bbox_inches='tight')\nplt.title('Tense and Nominalization CX Attractions with Nouns (Fisher\\'s)')\nplt.show()\ndisplay(verb_nom_cols_noun_fishers)\n```\n\nLooking at the associations for yqtl, we can make note of two collocations which are statistically significant $(-1.3 > attraction > 1.3)$:\n\n* yiqtol with a genitive (i.e. construct) relation on the time word ($a=3.6$)\n* yiqtol with a pronominal suffix on the time word ($a=1.6$)\n\nWe also can see a slight skew away from collocating with definiteness ($a=-1.21$), which falls just shy of the significance threshold. The demonstrative relation, however, is strongly disassociated with $a=-2.6$\n\nInterestingly, yiqtol shares this quality with qatal, which exhibits significant association for the suffix ($a=1.9$) and higher association, though not meeting the significance threshold, with the genitive ($a=1.04$). \n\nLooking at the raw counts again, we can get a sense for the magnitude of the collocations:\n\n\n```python\nverb_nom_cols_nouns\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>bare</th>\n      <th>definite</th>\n      <th>demonstrative</th>\n      <th>genitive</th>\n      <th>ordinal</th>\n      <th>quantified</th>\n      <th>time_pl</th>\n      <th>time_sffx</th>\n    </tr>\n    <tr>\n      <th>tense</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>ptcp</th>\n      <td>6.0</td>\n      <td>92.0</td>\n      <td>16.0</td>\n      <td>22.0</td>\n      <td>4.0</td>\n      <td>18.0</td>\n      <td>20.0</td>\n      <td>7.0</td>\n    </tr>\n    <tr>\n      <th>qtl</th>\n      <td>9.0</td>\n      <td>266.0</td>\n      <td>128.0</td>\n      <td>97.0</td>\n      <td>21.0</td>\n      <td>160.0</td>\n      <td>146.0</td>\n      <td>31.0</td>\n    </tr>\n    <tr>\n      <th>wqtl</th>\n      <td>2.0</td>\n      <td>98.0</td>\n      <td>38.0</td>\n      <td>20.0</td>\n      <td>16.0</td>\n      <td>48.0</td>\n      <td>44.0</td>\n      <td>5.0</td>\n    </tr>\n    <tr>\n      <th>wyqtl</th>\n      <td>21.0</td>\n      <td>307.0</td>\n      <td>163.0</td>\n      <td>48.0</td>\n      <td>39.0</td>\n      <td>164.0</td>\n      <td>128.0</td>\n      <td>2.0</td>\n    </tr>\n    <tr>\n      <th>yqtl</th>\n      <td>14.0</td>\n      <td>267.0</td>\n      <td>98.0</td>\n      <td>112.0</td>\n      <td>35.0</td>\n      <td>152.0</td>\n      <td>145.0</td>\n      <td>30.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nStarting with the genitive: it has a frequency of $112$ when combined with yiqtol and $97$ with qatal, but only $48$ with wayyiqtol, $20$ with weqatal, and $22$ with participle.\n\nThe suffix, which has fewer occurrences, appears with yiqtol $30$ times, qatal $31$ times, but with wayyiqtol only $2$, weqetal $5$ and the participle $7$. \n\n**One hypothesis for the higher frequency of suffix with yiqtol is that it is caused by the yiqtol's more frequent use in the domain of discourse**. Within such contexts, suffixes, especially in second person, might be higher in general.\n\n## \u0394P Asymmetrical Tests\n\nThe Fisher's Exact test is symmetrical, meaning that the association between two variables is the same for each one. However, an asymmetrical significance test can reveal dependency of one variable on the other. To give a simple real-world example: the noun \"blood\" is likely to cue a word such as \"red\"; but \"red\" is likely to cue any number of nouns besides \"blood\". This shows that the co-occurrence relationship between the two forms is not symmetrical.\n\nFollowing Ellis 2006, we can apply an assymetrical significance test to language data on the grounds the one construction would hypothetically serve as a cue, and the other as the response.\n\n> $\\begin{align}\n\\Delta P = P(O|C) - P(O|-C)\\\\\n=\\frac{a}{a+b} - \\frac{c}{c+d}\\\\\n=\\frac{ad-bc}{(a+b)(c+d)}\n\\end{align}$\n\n> \"\udbff\udc01$\\Delta P$ is the probability of the outcome given the cue $P(O|C)$ minus the probability of the outcome in the absence of the cue $P(O|\u2013C)$. When these are the same, when the outcome is just as likely when the cue is present as when it is not, there is no covariation between the two events and \udbff\udc01$P 1\u20444 0$. $\udbff\udc01P$ approaches $1.0$ as the presence of the cue increases the likelihood of the outcome and approaches $\u20131.0$ as the cue decreases the chance of the outcome\u2014a negative association.\" -Ellis, \"Language Acquisition,\" 2006, 11.\n\nFor our purposes here, we will model the time adverbial as the cue and the verb as the response. We want to answer **does an asymmetrical dependency between \"adverbs\" and yiqtol exist?**\n\n#### Time as cue\n\nGiven a time, what is the likelihood that we observe a particular tense?\n\n\n```python\n# unidirectional \u0394P test\na,b,c,d,e = contingency_table(tense_cols, 0, 1) # get contingencies\n\ntime_cue = a / (a + b) - c / (c + d)\n```\n\nWe look at the first 10 values.\n\n\n```python\ntime_cue.iloc[:10,:]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>tense</th>\n      <th>qtl</th>\n      <th>wqtl</th>\n      <th>wyqtl</th>\n      <th>yqtl</th>\n      <th>ptcp</th>\n    </tr>\n    <tr>\n      <th>time</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>\u05d9\u05d5\u05dd</th>\n      <td>0.038117</td>\n      <td>0.032080</td>\n      <td>0.026754</td>\n      <td>-0.114814</td>\n      <td>0.017863</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05d5\u05d3</th>\n      <td>-0.152609</td>\n      <td>-0.047727</td>\n      <td>-0.077087</td>\n      <td>0.272182</td>\n      <td>0.005241</td>\n    </tr>\n    <tr>\n      <th>\u05e9\u05c1\u05e0\u05d4</th>\n      <td>0.202009</td>\n      <td>-0.017236</td>\n      <td>0.097868</td>\n      <td>-0.222135</td>\n      <td>-0.060505</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05d5\u05dc\u05dd</th>\n      <td>-0.100486</td>\n      <td>0.077577</td>\n      <td>-0.182228</td>\n      <td>0.208435</td>\n      <td>-0.003297</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05ea</th>\n      <td>-0.027073</td>\n      <td>-0.018394</td>\n      <td>0.041062</td>\n      <td>-0.026511</td>\n      <td>0.030915</td>\n    </tr>\n    <tr>\n      <th>\u05d0\u05d6</th>\n      <td>0.097532</td>\n      <td>-0.070442</td>\n      <td>-0.219152</td>\n      <td>0.239020</td>\n      <td>-0.046958</td>\n    </tr>\n    <tr>\n      <th>\u05dc\u05d9\u05dc\u05d4</th>\n      <td>-0.048169</td>\n      <td>-0.030243</td>\n      <td>0.301096</td>\n      <td>-0.249445</td>\n      <td>0.026762</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05ea\u05d4</th>\n      <td>0.233904</td>\n      <td>-0.069767</td>\n      <td>-0.225718</td>\n      <td>0.111423</td>\n      <td>-0.049841</td>\n    </tr>\n    <tr>\n      <th>\u05d1\u05e7\u05e8</th>\n      <td>-0.230085</td>\n      <td>0.010427</td>\n      <td>0.312650</td>\n      <td>-0.077778</td>\n      <td>-0.015214</td>\n    </tr>\n    <tr>\n      <th>\u05e2\u05e8\u05d1</th>\n      <td>-0.158723</td>\n      <td>0.219190</td>\n      <td>-0.036670</td>\n      <td>0.019366</td>\n      <td>-0.043163</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n#### Verb as cue\n\nAnother flavor of the $\\Delta P$ looks from the other direction, with the feature as the cue, in this case the verb tense. We calculate that below. To aid the comparison, we flip the axis so that the row always contains the cue.\n\n\n```python\n# unidirectional \u0394P test\n\nverb_cue = (a / (a + c) - b / (b + d)).T\n```\n\nWe look at the first 10 values.\n\n\n```python\nverb_cue.iloc[:,:10]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>time</th>\n      <th>\u05d9\u05d5\u05dd</th>\n      <th>\u05e2\u05d5\u05d3</th>\n      <th>\u05e9\u05c1\u05e0\u05d4</th>\n      <th>\u05e2\u05d5\u05dc\u05dd</th>\n      <th>\u05e2\u05ea</th>\n      <th>\u05d0\u05d6</th>\n      <th>\u05dc\u05d9\u05dc\u05d4</th>\n      <th>\u05e2\u05ea\u05d4</th>\n      <th>\u05d1\u05e7\u05e8</th>\n      <th>\u05e2\u05e8\u05d1</th>\n    </tr>\n    <tr>\n      <th>tense</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>qtl</th>\n      <td>0.044867</td>\n      <td>-0.073861</td>\n      <td>0.067662</td>\n      <td>-0.021771</td>\n      <td>-0.005278</td>\n      <td>0.018863</td>\n      <td>-0.008184</td>\n      <td>0.034929</td>\n      <td>-0.033993</td>\n      <td>-0.018619</td>\n    </tr>\n    <tr>\n      <th>wqtl</th>\n      <td>0.117333</td>\n      <td>-0.071777</td>\n      <td>-0.017939</td>\n      <td>0.052227</td>\n      <td>-0.011143</td>\n      <td>-0.042334</td>\n      <td>-0.015967</td>\n      <td>-0.032373</td>\n      <td>0.004787</td>\n      <td>0.079896</td>\n    </tr>\n    <tr>\n      <th>wyqtl</th>\n      <td>0.036103</td>\n      <td>-0.042772</td>\n      <td>0.037580</td>\n      <td>-0.045262</td>\n      <td>0.009178</td>\n      <td>-0.048591</td>\n      <td>0.058647</td>\n      <td>-0.038641</td>\n      <td>0.052953</td>\n      <td>-0.004931</td>\n    </tr>\n    <tr>\n      <th>yqtl</th>\n      <td>-0.112975</td>\n      <td>0.110121</td>\n      <td>-0.062197</td>\n      <td>0.037750</td>\n      <td>-0.004321</td>\n      <td>0.038644</td>\n      <td>-0.035429</td>\n      <td>0.013909</td>\n      <td>-0.009606</td>\n      <td>0.001899</td>\n    </tr>\n    <tr>\n      <th>ptcp</th>\n      <td>0.063051</td>\n      <td>0.007606</td>\n      <td>-0.060769</td>\n      <td>-0.002142</td>\n      <td>0.018074</td>\n      <td>-0.027233</td>\n      <td>0.013634</td>\n      <td>-0.022318</td>\n      <td>-0.006740</td>\n      <td>-0.015183</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nInspecting the some of the values, we can see that the time adverbial seems to be more predictive of the verb than the verb is of the time adverbial. Here's an example with \u05e2\u05d5\u05d3.\n\n### \u05e2\u05d5\u05d3 as an example\n\nWe see that with time as the cue, the time \u05e2\u05d5\u05d3 has a pretty strong score with yiqtol:\n\n\n```python\ntime_cue.loc['\u05e2\u05d5\u05d3']\n```\n\n\n\n\n    tense\n    qtl     -0.152609\n    wqtl    -0.047727\n    wyqtl   -0.077087\n    yqtl     0.272182\n    ptcp     0.005241\n    Name: \u05e2\u05d5\u05d3, dtype: float64\n\n\n\nThis relationship is not completely symmetrical. The verb is a poorer predictor of \u05e2\u05d5\u05d3:\n\n\n```python\nverb_cue.loc['yqtl']['\u05e2\u05d5\u05d3']\n```\n\n\n\n\n    0.11012143241838356\n\n\n\nWhy is this the case? We can see it more clearly if we look at the ratios of yqtl representation in \u05e2\u05d5\u05d3 versus the ratio across yqtl.\n\n\n```python\ntense_cols['yqtl']['\u05e2\u05d5\u05d3'] / tense_cols['yqtl'].sum()\n```\n\n\n\n\n    0.17491166077738515\n\n\n\n\n```python\ntense_cols.loc['\u05e2\u05d5\u05d3']['yqtl'] / tense_cols.loc['\u05e2\u05d5\u05d3'].sum()\n```\n\n\n\n\n    0.61875\n\n\n\n\u05e2\u05d5\u05d3 makes up $17\\%$ of yiqtol's total. But yiqtol makes up $62\\%$ of \u05e2\u05d5\u05d3's total. **The numbers suggest that \u05e2\u05d5\u05d3 is more predictive of yiqtol than yiqtol is of \u05e2\u05d5\u05d3.**\n\n### The overall predictive power of time for verb\n\nWe can get a sense for the overall predictive power for each test based on the cumulative mean of its absolute values.\n\nBelow we retrieve the mean association score accross the absolute value for the time as a cue.\n\n\n```python\ntime_cue.abs().mean().mean()\n```\n\n\n\n\n    0.21081859098659791\n\n\n\nAnd next we see the same value for the verb.\n\n\n```python\nverb_cue.abs().mean().mean()\n```\n\n\n\n\n    0.005877288199936625\n\n\n\n**Based on this preliminary data, we can conclude that in general, the time adverbial is more predictive of a tense than a tense is for a given adverbial.** Intuitively this makes sense. There are far more time adverbials that can be chosen at any given moment, but there are far less verb tense choices. \n\n### TODO: Add comparisons between nouns/adverbs, see what these results mean for the issue of yiqtol/adverb dependency\n\n## Manual Investigation\n\nWe export a series of spreadsheets for manually inspecting collocations.\n\n### Co-occurrences \"Adverbs\" and yiqtols\n\n\n```python\nadvb_instances = times[(times.time.isin(advbs.index)) & (times.tense == 'yqtl')]\n\nadvb_inspect = advb_instances[['time', 'ref', 'clause', ]].sort_values(by=['time','node'])\n\nadvb_inspect.shape\n```\n\n\n\n\n    (550, 3)\n\n\n\n\n```python\nadvb_inspect.to_csv('../tables/inspect/yqtl_adverbs.tsv', encoding='utf-16', sep='\\t')\n```\n\n### Co-occurrences of \"nouns\" and yiqtols\n\n\n```python\nnoun_instances = times[(times.time.isin(nouns.index)) & (times.tense == 'yqtl')]\n\nnoun_inspect = noun_instances[['time', 'ref', 'clause', ]].sort_values(by=['time','node'])\n\nnoun_inspect.shape\n```\n\n\n\n\n    (526, 3)\n\n\n\n\n```python\nnoun_inspect.to_csv('../tables/inspect/yqtl_nouns.tsv', encoding='utf-16', sep='\\t')\n```\n\n<hr>\n", "meta": {"hexsha": "aea926ff1a1984063c0f27d99c6e5b2252cc1633", "size": 340615, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "archive/2021-03-7/results/notebooks/yqtl_association_with_advb.ipynb", "max_stars_repo_name": "CambridgeSemiticsLab/BH_time_collocations", "max_stars_repo_head_hexsha": "2d1864b6e9cd26624c769ee1e970d69d19da7fbf", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-06-19T19:42:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-20T22:43:45.000Z", "max_issues_repo_path": "archive/2021-03-7/results/notebooks/yqtl_association_with_advb.ipynb", "max_issues_repo_name": "CambridgeSemiticsLab/BHTenseAndAspect", "max_issues_repo_head_hexsha": "2d1864b6e9cd26624c769ee1e970d69d19da7fbf", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-02-25T10:19:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-13T15:29:01.000Z", "max_forks_repo_path": "archive/2021-03-7/results/notebooks/yqtl_association_with_advb.ipynb", "max_forks_repo_name": "CambridgeSemiticsLab/BHTenseAndAspect", "max_forks_repo_head_hexsha": "2d1864b6e9cd26624c769ee1e970d69d19da7fbf", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 68.5342052314, "max_line_length": 95540, "alphanum_fraction": 0.7092200872, "converted": true, "num_tokens": 28283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.320821300824607, "lm_q2_score": 0.07921032139194485, "lm_q1q2_score": 0.025412358347698945}}
{"text": "# Statistical constraints on observing low-angle normal fault seismicity\n\n## Introduction\n\nLow-angle normal faults (LANFs), with dips less than 30$^\\circ$, are\nwell described in the geologic record. They are hypothesized to have\nan important role in accommodating large-magnitude continental\nextension \\citep{howard1987crustal} and crustal thinning\n\\citep{lister1986detachment}, and their recognition has been one of\nthe most important developments in tectonics over the past several\ndecades \\citep{wernicke2009detachment}. However, despite widespread\nfield observations of inactive LANFs, and their central role in modern\nextensional tectonic theory, they remain enigmatic and contentious\nstructures, and it is not clear if they are seismically active at low dip \nangles in the upper crust. This is for two reasons: because brittle faulting\non LANFs is in apparent conflict with standard Andersonian rock mechanical\ntheory as typically applied to the upper crust\n\\citep{axen2004lanfmech}, and because observations of active faulting\non LANFs is sparse and at times ambiguous \\citep{wernicke1995seis}. A\nconsiderable amount of research has been performed to address the\nformer concern, reconciling LANF slip with rock mechanics \\citep [e.g.,]\n[]{axenbartley1997, collettini2011lanfmech}. The latter issue, the paucity of \ndefinitive LANF earthquakes in focal mechanism catalogs, has inhibited\nhypothesis testing of LANF fault theory, and has also contributed to a mode\nof thought where the  absence of evidence for LANF seismicity is taken\nas evidence that LANFs are inactive or aseismic \\citep{jackson1987,\ncollettinisibson2001}. However, the lack of observed seismic slip on\ncontinental LANFs may be simply due to the rarity of earthquakes on\nLANFs, coupled with the small number of potential active structures.\n\nIn this work, we choose to directly address the question of whether\nthe lack of observed large earthquakes on LANFs may be \ninterpreted as an indication that\nLANFs do not slip seismically, or if it is better explained as an\neffect of the small number of active seismogenic LANFs with low moment\naccumulation rates (and hence long recurrence intervals). \nWe then calculate the maximum likelihood of observing a significant\nearthquake on a LANF by treating all potentially active LANFs described in the \nliterature as seismically active at their surface dip angles \nthroughout the upper crust. %, and displaying typical seismic behavior.\nUnder these assumptions, we create synthetic earthquake catalogs with\nGutenberg-Richter and `characteristic' frequency-magnitude distributions\nbased on each fault's geometry and slip rate, and then we calculate the\nprobability of observing earthquakes on each, and any, fault over different\ndurations of observation.\n\n\n### LANF Slip, Mohr-Coulomb Failure Theory, and Seismicity\n\nAreas of the crust undergoing active extension are generally assumed\nto have a subvertical maximum compressive stress.  Mohr-Coulomb\ntheory, as applied to the crust, predicts that a fault with a typical\ncoefficient of friction for rocks (0.6--0.8) should lock up if it is\noriented at an angle greater than 60$^\\circ$ to the maximum compressive stress,\nand new, optimally oriented faults should form \\citep{sibson1985}.  Therefore,\nfor normal faults with dips less than 30$^\\circ$, either much lower\nfault friction or elevated pore fluid pressure is required for fault slip.\n\nEvidence for seismic slip on LANFs is sparse.  This is partly due to the\nambiguity of the rupture plane in earthquake focal mechanisms, which have\nnodal planes 90$^\\circ$ apart, and therefore have a\nhigh-angle nodal plane if they have a low-angle nodal plane.  Without\nancillary information indicating which plane slipped, searches of earthquake\ncatalogs cannot yield unique results as to whether they contain LANF events.\nSeveral collections of normal fault earthquakes\nwith known surface breaks \\citep{jackson1987, collettinisibson2001}, thereby\nresolving dip ambiguity, contain no low-angle events, though the collections\nare small ($\\le$ 25 events).  Some candidate events exist, but they are\nundersea \\citep[e.g.,][]{abers2001} or difficult to verify \\citep[e.g.,]\n[]{doser1987ancash}.\n\n## Potentiall Active LANFs\n\nOver the past decade or so, many field studies have found evidence for LANF \nactivity in orogens throughout the world. These studies typically find arrays of \nQuaternary normal fault scarps on the fault traces and/or in the hanging walls \nof mapped or inferred low-angle detachment faults \\citep [e.g.,]\n[]{axen1999baja}. Some studies also have bedrock thermochronology data from the \nexhumed footwalls of the detachments that is suggestive of ongoing rapid \nexhumation \\citep [e.g.,][]{sundell2013lunggar}, although this data does not \npreclude a recent cessation of faulting. In some cases, additional evidence for \nLANF activity comes from geophysical data such as GPS geodesy \\citep [e.g.,]\n[]{hreinsdottir2009altotib} and seismic waves \\citep [e.g.,][]{doser1987ancash}.\n\nWe have compiled all potentially active LANFs with known subareal\nfault traces from a thorough review of the literature, finding twenty\ntotal (Figure~\\ref{fig:lanf_map}).  We have then mapped the approximate fault\ntraces into a GIS file (available at https://github.com/cossatot/LANF\\_gis), \nwith metadata such as slip rate and source. Though the fault traces of many\nLANFs considered here are obscured by vegetation or agriculture, others\ndisplay large fault scarps in Quaternary sediments, particularly those in the\ndry climates of Tibet \\citep[e.g.,][]{styron2013slr, kapp2005nqtl} and the\nwestern US \\citep[e.g.,][]{axen1999baja, hayman2003dv}, which are commonly\ninterpreted as evidence for past seismic slip.  About half are in Tibet,\nconsistent with hypotheses that LANFs and metamorphic core complexes\nform in areas of hot, thick crust \\citep [e.g.,][]{buck1991mcc}.  The\nrest are distributed through other areas of active continental\nextension: the North American Basin and Range, the Malay Archipelago,\nwestern Turkey, Italy, and Peru. Several of the most-commonly cited\ncandidates for seismically active LANFs were not included because they\ndo not have a clearly-defined, mappable fault trace, which is\nnecessary for our earthquake likelihood calculations.  These include the \nsubmarine core complexes in the Woodlark Basin \\citep{abers2001}, the fault\nresponsible for the 1995 Aigion, Greece earthquake \\citep{bernard1997}\nand other potential LANFs underneath the Gulf of Corinth, and the\nfault responsible for the 1952 Ancash, Peru earthquake\n\\citep{doser1987ancash}.\n\n\n```\n# show map and figure caption\n```\n\n## Likelihood of observing a LANF event\n### Earthquake likelihood on an individual LANF\n\nTo estimate the likelihood of observing a significant earthquake on an\nindividual LANF over some contiguous time window of length $t$ (in\nyears), we perform a Monte Carlo simulation in which we create 4000\nsynthetic time series of earthquakes, with unique values for fault\ngeometry and slip rate for each time series. Then, for each time\nseries we calculate the fraction of unique time windows of length $t$\nin which an earthquake as large or larger than a given magnitude\noccurs.  We take this value as the probability of observing an\nearthquake greater than or equal to moment magnitude $M$ over\ntime period $t$, which we will refer to in general as $P(M,t)$.\n\nThe geometry for each fault is estimated based on the length of the\nfault trace, the dip of the fault, and the estimated seismogenic\nthickness or fault locking depth in the area.  The fault is treated as\nplanar for simplicity of calculations, even though the exposed\nfootwalls of many detachment faults are highly corrugated.  We\ndetermine the fault length by measuring the approximate length of the\nmapped fault trace perpendicular to the assumed extension direction;\nfor faults that change dip significantly along strike (e.g., the Dixie\nValley fault), we only consider the low-angle segments of the fault.\nValues for the dip are taken from the literature in most cases, and\nmeasured of the dip of footwall triangular facets (interpreted as the exhumed\nfault plane) from SRTM data otherwise. In all cases, ranges of fault\ngeometries are considered, encompassing the degree to which the values are \nknown. The fault locking depth is assumed to be 10 km in the absence of other\nevidence (such as a geodetic study, \\citep[e.g.,][]{hreinsdottir2009altotib}).\n\nSlip rates of the 20 LANFs are similarly gathered from the\nliterature if possible, or given broad ranges if not documented\n(e.g., 1--10 mm yr$^{-1}$).  In the Monte Carlo simulation, samples\nfor slip rate and dip are drawn from uniform distributions defined\nby the maximum and minimum values.  Based on field observations,\nsome faults have dip ranges that go above 30$^\\circ$; this study\nonly considers slip on faults shallower than this, so for these\nfaults, dip values are sampled from the minimum to 30$^\\circ$ and\nthe resulting probabilities are then multiplied by the fraction of\nthe dip range that is under 30$^\\circ$.\n\nEach earthquake synthetic earthquake sequence is generated by\nrandomly sampling either 50,000 events from a tapered Gutenberg-Richter (GR)\ndistribution with corner magnitude $M_c = 7.64$ and $\\beta = 0.65$\n(from values estimated by \\citet{birdkagan2004f_m} for continental\nrifts), or a 25,000 events from `characteristic' distribution. It is not\ncertain which distribution more appropriately describes seismicity on a single\nLANF, though studies of many individual fault rupture histories suggests\nthat the characteristic distribution is more accurate \\citep{hecker2013eqdist}.\nThe smaller number of samples from the characteristic distribution is due to \nthe increased computation time associated with a higher proportion of large \nevents.  The samples are taken \nfrom an interval $M = [5.0, \\, M_{max}]$, where $M_{max}$ is calculated as the\nmoment magnitude $M$ resulting from fault slip $D$ = 15 m over a fault of\nlength $L$ cutting through a seismogenic thickness $z$ at dip $\\delta$,\ngiven the relations\n\n\\begin{equation}\n M_o = \\mu L z D \\,/ \\, \\sin \\delta \n \\end{equation}\n\nand\n\n\\begin{equation}\nM = 2/3 \\; \\log_{10} (M_o) - 6\n\\end{equation}\n\nwhere $\\mu = 30$ GPa is the shear modulus and $M_o$ is the seismic\nmoment in N m \\citep{kagan2003pepi}.  The characteristic distribution has a\nlarge-magnitude mode corresponding to $D$ = 1.5 m on the fault, a typical\nslip distance for normal fault events \\citep[e.g.][]{wesnousky2008displacement}.\nThe distributions are shown in Figure~\\ref{fig:fms}.\n\nThese calculations rely on two important assumptions that warrant some\ndiscussion.  The first is that each earthquake ruptures the entire\nfault patch uniformly.  Though this is highly improbable fault behavior,\nthe long-term statistical distribution of earthquake recurrence is \ninsensitive to assumptions about slip distribution in individual events:\nif $n$ different, equal fault patches rupture independently, each \nrequires $n$ times the interseismic strain accumulation time to rupture with\nsome earthquake of magnitude $M$ versus a single fault rupturing uniformly; \nbut on the whole, magnitude $M$ events would happen with the same long-term\nfrequency.  The next assumption is that earthquakes are ordered randomly and\nseparated by the time necessary for sufficient strain to accumulate for each\nearthquake to occur.  This means that foreshock and aftershock sequences\nand other types of event clustering are not taken into account.  However,\nthe modal inter-event times for earthquakes $\\ge M \\,6$ or so are greater than\na hundred years for many LANFs [supplemental figure xx], so the ordering of\nevents does not impact the results, as this is longer than our maximum\nobservation window.  Furthermore, any clustering resulting in\nevent spacing less than the observation window would decrease $P(M,t)$, and\nwe are concerned with calculating the maximum $P(M,t)$.\n\n### Setting up the problem\n\n#### Import necessary modules\n\n\n```\n#%pylab inline\n#%config InlineBackend.figure_format = 'retina'\n```\n\n\n```\nfrom matplotlib.pyplot import *\n```\n\n\n```\nimport sys\nsys.path.append('../eq_stats')\n\nimport numpy as np\nimport pandas as pd\nimport eq_stats as eqs\nimport time\nfrom joblib import Parallel, delayed\nfrom itertools import chain\n```\n\n#### Read in fault data table\n\nMakes a Pandas dataframe of fault data (length, slip rates, etc.)\n\n\n```\nf = pd.read_csv('../data/lanf_stats.csv', index_col=0)\n```\n\n#### Define some variables to be used later\n\n\n```\nn_cores = -3\nn_eq_samp = 3e4 # number of earthquakes in time series\ntime_window = np.hstack( (1, np.arange(5, 105, step=5) ) ) # observation times\nmc_iters = 2e3 # number of Monte Carlo iterations\nmc_index = np.arange(mc_iters, dtype='int')\nmc_cols = ['dip', 'Ddot'] + [t for t in time_window]\nmax_eq_slip = 15 #m\nchar_eq_slip= 1.5 #m\nMc = 7.64 # Hypothetical corner magnitude for Continental Rift Boundaries\n```\n\nMake list of minimum search magnitude $M_{min}$, and then make MultiIndex for Pandas dataframes\n\n\n```\nmin_M_list = [5, 5.5, 6, 6.5, 7, 7.5]\n\ndf_ind_tuples = [[i, M] for i in mc_index for M in min_M_list]\ndf_multi_ind = pd.MultiIndex.from_tuples(df_ind_tuples, names=['mc_iter','M'])\n\nrec_int_bins = np.logspace(1, 5)\n```\n\n### Calculate $P(M,t)$ for Gutenberg-Richter frequency-magnitude distributions\n\n#### Define a function for Joblib Parallel to calculate probabilities for each iteration.\n\nFunction is defined here so it can access all variables generated by script, not just passed variables.  This makes the code cleaner even if it's not very abstracted.\n\nHere is what this function does:\n\n- Get the dip, Ddot and maximum earthquake magnitude for each iteration.\n- Take this info and make the earthquake sequence:\n    - Take the max earthquake magnitude and make a frequency-magnitude distribution based on a Gutenburg-Richter exponential model.\n    - Take 50k samples from this distribution, \n- Make an earthquake time series form the EQ sequence\n    - Calculate the interseismic strain accumulation time for each event\n    - Separate each earthquake in the sequence with the appropriate number of years with no events.\n- Calculate the probability of observation\n    - Run a rolling maximum for each $t$ in [1, 5, 10, 15, ..., 95, 100]\n    - Calculate the observation probability above $M_{min}$ in [5, 5.5, 6, 6.5, 7, 7.5]\n- Calculate inter-event times for EQs $\\ge \\, M$\n\n\n```\ndef calc_iter_probs(iter):\n    df_iter = fdf.loc[iter].copy()\n    df_iter['dip'] = mc_d['dip_samp'][iter]\n    df_iter['Ddot'] = mc_d['Ddot_samp'][iter]\n\n    # Generate EQ sample/sequence from F(M) dist.\n    m_vec = np.linspace(5, mc_d['max_M'][iter], num=1000)\n    fm_vec = eqs.F(m_vec, Mc=Mc)\n    M_samp = eqs.sample_from_pdf(m_vec, fm_vec, n_eq_samp)\n    Mo_samp = eqs.calc_Mo_from_M(M_samp)\n    \n    # Make time series of earthquakes, including no eq years\n    recur_int = eqs.calc_recurrence_interval(Mo=Mo_samp, \n                                             dip=mc_d['dip_samp'][iter],\n                                             slip_rate=mc_d['Ddot_samp'][iter],\n                                             L=params['L_km'],\n                                             z=params['z_km'])\n\n    cum_yrs = eqs.calc_cumulative_yrs(recur_int)\n    eq_series = eqs.make_eq_time_series(M_samp, cum_yrs)\n    \n    # calculate probability of observing EQ in time_window\n    for t in time_window:\n        roll_max = pd.rolling_max(eq_series, t)\n        df_iter[t] = (eqs.get_probability_above_value(roll_max, min_M_list)\n                      * mc_d['dip_frac'])\n        \n    # calculate histgrams of recurrence intervals\n    rec_int_counts_df = rec_int_df.loc[iter].copy()\n    for mm in np.array(min_M_list):\n        ints = np.diff( np.where(eq_series >= mm) )\n        rec_int_counts_df.loc[mm] = np.histogram(ints, bins=rec_int_bins)[0]\n```\n\n#### Iterate through the faults in the fault database, doing all the calculations for each.\n\nThe setup of this for loop is basically this:\n\n- Make DataFrame for each fault.\n    - Columns are dip, Ddot, and observation time windows.\n    - Rows are values for each Monte Carlo iteration.  Values for time windows are calculated probabilities.\n    \n- Calculate maximum earthquake magnitude for each MC iteration.\n\n- Run the above 'calc_iter_probs' function (parallelized over the MC iterations) and concatenate the results\n\n### Note! Not actually running the calcs here, as it's a looong process!\n\n\n```\nfor fault in list(f.index):\n    fdf = pd.DataFrame(index=df_multi_ind, columns=mc_cols, dtype='float')\n    params = f.loc[fault]\n    mc_d = {}\n    mc_d['dip_samp'], mc_d['dip_frac'] = eqs.dip_rand_samp( params['dip_deg'], \n                                                         params['dip_err_deg'], \n                                                         mc_iters)\n\n    mc_d['Ddot_samp'] = eqs.Ddot_rand_samp(params['slip_rate_mm_a'],\n                                           params['sr_err_mm_a'], mc_iters)\n\n    mc_d['max_Mo'] = eqs.calc_Mo_from_fault_params(L=params['L_km'], \n                                                   z=params['z_km'], \n                                                   dip=mc_d['dip_samp'], \n                                                   D=max_eq_slip)\n\n    mc_d['max_M'] = eqs.calc_M_from_Mo(mc_d['max_Mo'])\n    \n    rec_int_df = pd.DataFrame(columns = rec_int_bins[1:],\n                              index=df_multi_ind, dtype='float')\n    t0 = time.time()\n    out_list = Parallel(n_jobs=-3)( delayed( calc_iter_probs)(ii) \n                                    for ii in mc_index)\n    print 'done with', fault, 'parallel calcs in {} s'.format((time.time()-t0))\n    for ii in mc_index:\n        fdf.loc[ii][:] = out_list[ii][0]\n        rec_int_df.loc[ii][:] = out_list[ii][1]\n        \n    fdf.to_csv('../results/{}_test.csv'.format(fault))\n```\n\n    done with kongur_shan parallel calcs in 51.947163105 s\n    done with leo_pargil parallel calcs in 418.76543808 s\n    done with gurla_mandhata parallel calcs in 113.975022078 s\n    done with s_lunggar parallel calcs in 241.274301052 s\n    done with n_lunggar parallel calcs in 259.45785284 s\n    done with pqx_qingdu parallel calcs in 836.985168934 s\n    done with pqx_n parallel calcs in 917.926791191 s\n    done with nqtl parallel calcs in 113.513681889 s\n    done with alto_tiberina parallel calcs in 233.532536983 s\n    done with death_valley parallel calcs in 201.206351042 s\n    done with panamint_valley parallel calcs in 102.183755159 s\n    done with laguna_salada parallel calcs in 217.666782141 s\n    done with dixie_valley parallel calcs in 1027.02227688 s\n    done with dayman_dome parallel calcs in 103.56942296 s\n    done with papangeo parallel calcs in 183.855463028 s\n    done with tokorondo parallel calcs in 78.5454099178 s\n    done with cordillera_blanca parallel calcs in 66.0141530037 s\n    done with kuzey parallel calcs in 268.01406312 s\n    done with guney parallel calcs in 158.371592999 s\n\n\n### Calculate $P(M,t)$ for faults with characteristic frequency-magnitude distributions\n\n\n```\ndef calc_iter_probs(ii):\n    df_iter = fdf.loc[ii].copy()\n    df_iter['dip'] = mc_d['dip_samp'][ii]\n    df_iter['Ddot'] = mc_d['Ddot_samp'][ii]\n\n    # Generate EQ sample/sequence from F(M) dist.\n    m_vec = np.linspace(5, mc_d['max_M'][ii], num=1000)\n    fm_vec = eqs.F_char(m_vec, Mc=Mc, char_M=mc_d['char_M'][ii])\n    M_samp = eqs.sample_from_pdf(m_vec, fm_vec, n_eq_samp)\n    Mo_samp = eqs.calc_Mo_from_M(M_samp)\n    \n    # Make time series of earthquakes, including no eq years\n    recur_int = eqs.calc_recurrence_interval(Mo=Mo_samp, \n                                             dip=mc_d['dip_samp'][ii],\n                                             slip_rate=mc_d['Ddot_samp'][ii],\n                                             L=params['L_km'],\n                                             z=params['z_km'])\n\n    cum_yrs = eqs.calc_cumulative_yrs(recur_int)\n    eq_series = eqs.make_eq_time_series(M_samp, cum_yrs)\n    \n    # calculate probability of observing EQ in time_window\n    for t in time_window:\n        roll_max = pd.rolling_max(eq_series, t)\n        df_iter[t] = (eqs.get_probability_above_value(roll_max, min_M_list)\n                      * mc_d['dip_frac'])\n        \n    # calculate histgrams of recurrence intervals\n    rec_int_counts_df = rec_int_df.loc[ii].copy()\n    for mm in np.array(min_M_list):\n        ints = np.diff( np.where(eq_series >= mm) )\n```\n\n\n```\nfor fault in list(f.index):\n    fdf = pd.DataFrame(index=df_multi_ind, columns=mc_cols, dtype='float')\n    params = f.loc[fault]\n    mc_d = {}\n    mc_d['dip_samp'], mc_d['dip_frac'] = eqs.dip_rand_samp( params['dip_deg'], \n                                                         params['dip_err_deg'], \n                                                         mc_iters)\n\n    mc_d['Ddot_samp'] = eqs.Ddot_rand_samp(params['slip_rate_mm_a'],\n                                           params['sr_err_mm_a'], mc_iters)\n\n    mc_d['max_Mo'] = eqs.calc_Mo_from_fault_params(L=params['L_km'], \n                                                   z=params['z_km'], \n                                                   dip=mc_d['dip_samp'], \n                                                   D=max_eq_slip)\n\n    mc_d['max_M'] = eqs.calc_M_from_Mo(mc_d['max_Mo'])\n    \n    mc_d['char_Mo'] = eqs.calc_Mo_from_fault_params(L=params['L_km'], \n                                                    z=params['z_km'], \n                                                    dip=mc_d['dip_samp'], \n                                                    D=char_eq_slip)\n    \n    mc_d['char_M'] = eqs.calc_M_from_Mo(mc_d['char_Mo'])\n    \n    rec_int_df = pd.DataFrame(columns = rec_int_bins[1:],\n                              index=df_multi_ind, dtype='float')\n    t0 = time.time()\n    out_list = Parallel(n_jobs=n_cores)( delayed( calc_iter_probs)(ii) \n                                    for ii in mc_index)\n    print 'done with', fault, 'parallel calcs in {} s'.format((time.time()-t0))\n    for ii in mc_index:\n        fdf.loc[ii][:] = out_list[ii][0]\n        rec_int_df.loc[ii][:] = out_list[ii][1]\n        \n    fdf.to_csv('../results/{}_char.csv'.format(fault))\n```\n\n### Examining individual fault results\n\n#### Load datasets into Pandas dataframes\n\ntest with one:\n\n\n```\npv = pd.read_csv('../results/panamint_valley_gr.csv', index_col=[0])\npv_c = pd.read_csv('../results/panamint_valley_char.csv', index_col=[0])\n```\n\n\n```\ntw_xarray = np.tile(time_window, (mc_iters,1))\n\ntw_xarray.shape\n```\n\n\n\n\n    (2000, 21)\n\n\n\n\n```\ntw_cols = list(time_window.astype('str'))\n```\n\nmake some plotting functions\n\n\n```\ndef plot_probs(df, lw=0.5, alpha=0.2):\n\n    df_5 = df[df.M==5]\n    df_55 = df[df.M==5.5]\n    df_6 = df[df.M==6]\n    df_65 = df[df.M==6.5]\n    df_7 = df[df.M==7]\n    df_75 = df[df.M==7.5]\n\n    aa = plot(tw_xarray.T, df_5[tw_cols].T, 'b', \n              lw=lw, alpha=alpha)\n    bb = plot(tw_xarray.T, df_55[tw_cols].T, 'c', \n              lw=lw, alpha=alpha)\n    cc = plot(tw_xarray.T, df_6[tw_cols].T, 'g', \n              lw=lw, alpha=alpha)\n    dd = plot(tw_xarray.T, df_65[tw_cols].T, 'gold', \n              lw=lw, alpha=alpha)\n    ee = plot(tw_xarray.T, df_7[tw_cols].T, 'orange', \n              lw=lw, alpha=alpha)\n    ff = plot(tw_xarray.T, df_75[tw_cols].T, 'r', \n              lw=lw, alpha=alpha)\n\n    return aa, bb, cc, dd, ee, ff\n```\n\n\n```\ndef pmf_x_secs(df, tw, n_bins=101, hist_type='stepfilled', alpha=0.5):\n    hist_bins = np.linspace(0, 1, num=n_bins)\n    tw = str(tw)\n    \n    aa = df[df.M==5][tw].hist(bins=hist_bins, histtype=hist_type, \n                              color='b', alpha=alpha)\n    bb = df[df.M==5.5][tw].hist(bins=hist_bins, histtype=hist_type, \n                                color='c', alpha=alpha)\n    cc = df[df.M==6][tw].hist(bins=hist_bins, histtype=hist_type, \n                              color='g', alpha=alpha)\n    dd = df[df.M==6.5][tw].hist(bins=hist_bins, histtype=hist_type, \n                                color='gold', alpha=alpha)\n    ee = df[df.M==7][tw].hist(bins=hist_bins, histtype=hist_type, \n                              color='orange', alpha=alpha)\n    ff = df[df.M==7.5][tw].hist(bins=hist_bins, histtype=hist_type, \n                                color='red', alpha=alpha)\n    \n    return aa, bb, cc, dd, ee, ff\n```\n\n\n```\n#plot_probs(pv)\n\n#xlabel('observation time, yrs', fontsize=18)\n#ylabel('probability', fontsize=18)\n#title('Figure 1: Likelihood of observing an earthquake \\n'\n#      + 'larger than M on the Kongur Shan fault', fontsize=21)\n#show()\n```\n\n\n```\ntw=35\nnbins=1001\nx_sec_lims = [0,0.4,0,400]\n\nfigure()\n\nsubplot2grid((3,2), (0,0), colspan=2)\naxvline(tw, lw=0.5, color='grey')\nplot_probs(pv, lw=0.2, alpha=0.2)\n\nsubplot2grid((3,2), (1,0), colspan=2)\naxvline(tw, lw=0.5, color='grey')\nplot_probs(pv_c, lw=0.2, alpha=0.2)\n\nsubplot2grid((3,2), (2,0))\npmf_x_secs(pv, tw, n_bins=nbins)\naxis(x_sec_lims)\n\nsubplot2grid((3,2), (2,1))\npmf_x_secs(pv_c, tw, n_bins=nbins)\naxis([0,0.1,0,400])\n\nshow()\n\n```\n\nThe results for faults with a GR frequency-magnitude distribution\nindicate that it is unlikely that any individual fault would have an earthquake\ngreater than $M \\, 5$ in any modeled observation time (up to 100 years).  \nAs an example, the results for the Panamint Valley fault are shown in\nFigure~\\ref{fig:pv}a;\nthis fault has the highest $P(M,t)$ of any of the well-studied LANFs.  The\nprobability of observing a $\\ge M \\, 6.0$ event on the Panamint Valley fault \nis about 0.5 for $t$ = 100 years, and about 0.15 for $t$ = 35 years, which is\nthe length of the Global CMT catalog. As expected given the GR distribution,\nthe $P(M,t)$ is much higher for smaller, more frequent events than for larger\nevents.  \n\nThe results for faults with a characteristic frequency-magnitude distribution\nyield much lower $P(M,t)$ for small to moderate events, but for large events,\n$P(M,t)$ is higher (Figure~\\ref{fig:pv}b,d); this is because the earthquake\nsequences are dominated by large, infrequent events, so the inter-event times\nfor moderate events are several times greater. For the Panamint Valley fault,\n$P(M,t)$ for $ \\ge M \\, 5$ is about 0.07 (versus 0.25 for the GR distribution),\nbut $P(M\\ge 7, t=35)$ is around 0.025 (versus essentially zero for the GR\ndistribution).  As the characteristic distribution likely better represents\nearthquakes on an individual large fault, these results suggest that is \nvery unlikely that we would expect to capture any significant seismicity\non an single LANF in the moment tensor catalogs. A similar conclusion was \nfound by \\citet{wernicke1995seis} based on a simple calculation, \nassuming perfectly repeating large earthquakes on an idealized fault. \n\n### Earthquake Likelihood on All LANFs\n\nTo calculate the probability of observing an earthquake over the time\nwindow on any of the LANFs studied, we first assume that seismicity on\neach fault is independent and uncorrelated with seismicity on all\nother faults. This assumption is likely true for most faults, but may\nnot be true for some proximal faults (such as the North and South\nLunggar detachments, or the Papangeo and Tokorondo detachments),\nthough it is unclear how to determine how these faults may interact \nsuch that an appropriate conditional or joint probability may be calculated. \nWe determine the probability for each time window and minimum magnitude\nwith the equation\n\n\\begin{equation}\nP_{AT \\, or \\, LP\\, \\ldots \\, or \\, DV} = 1 - (Q_{AT} \\cdot Q_{LP} \\cdot \\ldots \\, \\cdot Q_{DV})\n%\\label{ProbUnion}\n\\end{equation}\n\nwhere $P_{AT}$ is the probability of observing an earthquake on a\nsingle LANF (e.g., the Alto-Tiberina fault), and $Q_{AT} = 1 -\nP_{AT}$. Equation (\\ref{ProbUnion}) is the union of probabilities for\nnon mutually exclusive random events.\n\n### Calculating these probabilities\n\n####now load the rest:\n\nGutenberg-Richter models\n\n\n```\nks = pd.read_csv('../results/kongur_shan_gr.csv', index_col=0)\ngm = pd.read_csv('../results/gurla_mandhata_gr.csv', index_col=0)\nslr = pd.read_csv('../results/s_lunggar_gr.csv', index_col=0)\nnlr = pd.read_csv('../results/n_lunggar_gr.csv', index_col=0)\npqxn = pd.read_csv('../results/pqx_n_gr.csv', index_col=0)\npqxq = pd.read_csv('../results/pqx_qingdu_gr.csv', index_col=0)\nlp = pd.read_csv('../results/leo_pargil_gr.csv', index_col=0)\nnqtl = pd.read_csv('../results/nqtl_gr.csv', index_col=0)\nat = pd.read_csv('../results/alto_tiberina_gr.csv', index_col=0)\ndv = pd.read_csv('../results/death_valley_gr.csv', index_col=0)\ncd = pd.read_csv('../results/canada_david_gr.csv', index_col=0)\nsd = pd.read_csv('../results/sevier_desert_gr.csv', index_col=0)\ndxv = pd.read_csv('../results/dixie_valley_gr.csv', index_col=0)\ndd = pd.read_csv('../results/dayman_dome_gr.csv', index_col=0)\npp = pd.read_csv('../results/papangeo_gr.csv', index_col=0)\ntk = pd.read_csv('../results/tokorondo_gr.csv', index_col=0)\ncb = pd.read_csv('../results/cordillera_blanca_gr.csv', index_col=0)\nkz = pd.read_csv('../results/kuzey_gr.csv', index_col=0)\ngn = pd.read_csv('../results/guney_gr.csv', index_col=0)\n```\n\ncharacteristic models\n\n\n```\nks_c = pd.read_csv('../results/kongur_shan_char.csv', index_col=0)\ngm_c = pd.read_csv('../results/gurla_mandhata_char.csv', index_col=0)\nslr_c = pd.read_csv('../results/s_lunggar_char.csv', index_col=0)\nnlr_c = pd.read_csv('../results/n_lunggar_char.csv', index_col=0)\npqxn_c = pd.read_csv('../results/pqx_n_char.csv', index_col=0)\npqxq_c = pd.read_csv('../results/pqx_qingdu_char.csv', index_col=0)\nlp_c = pd.read_csv('../results/leo_pargil_char.csv', index_col=0)\nnqtl_c = pd.read_csv('../results/nqtl_char.csv', index_col=0)\nat_c = pd.read_csv('../results/alto_tiberina_char.csv', index_col=0)\ndv_c = pd.read_csv('../results/death_valley_char.csv', index_col=0)\ncd_c = pd.read_csv('../results/canada_david_char.csv', index_col=0)\nsd_c = pd.read_csv('../results/sevier_desert_char.csv', index_col=0)\ndxv_c = pd.read_csv('../results/dixie_valley_char.csv', index_col=0)\ndd_c = pd.read_csv('../results/dayman_dome_char.csv', index_col=0)\npp_c = pd.read_csv('../results/papangeo_char.csv', index_col=0)\ntk_c = pd.read_csv('../results/tokorondo_char.csv', index_col=0)\ncb_c = pd.read_csv('../results/cordillera_blanca_char.csv', index_col=0)\nkz_c = pd.read_csv('../results/kuzey_char.csv', index_col=0)\ngn_c = pd.read_csv('../results/guney_char.csv', index_col=0)\n```\n\nmake list of faults\n\n\n```\nf_list = ['ks', 'lp', 'gm', 'slr', 'nlr', 'pqxn', 'pqxq', 'nqtl', 'at',\n          'dv', 'pv', 'cd', 'sd', 'dxv', 'dd', 'pp', 'tk', 'cb', 'kz', 'gn']\n\nfault_list = [ks, lp, gm, slr, nlr, pqxn, pqxq, nqtl, at,\n              dv, pv, cd, sd,  dxv, dd, pp, tk, cb, kz, gn]\n```\n\n\n```\nfault_c_list = [ks_c, lp_c, gm_c, slr_c, nlr_c, pqxn_c, pqxq_c, nqtl_c, at_c,\n              dv_c, pv_c, cd_c, sd_c, dxv_c, dd_c, pp_c, tk_c, cb_c, kz_c, gn_c]\n\nfc_list = ['ks_c', 'lp_c', 'gm_c', 'slr_c', 'nlr_c', 'pqxn_c', \n                'pqxq_c', 'nqtl_c', 'at_c', 'dv_c', 'pv_c', 'cd_c', \n                'sd_c', 'dxv_c', 'dd_c', 'pp_c', 'tk_c', 'cb_c', 'kz_c', 'gn_c']\n```\n\n#### Calculate $q$, probability of *not* observing an earthquake, for each fault\n\n\n```\nq = {}\n\nfor i, f_ in enumerate(f_list):\n    q[f_] = fault_list[i].copy()\n    q[f_][tw_cols] = 1 - q[f_][tw_cols]\n```\n\n\n```\nqc = {}\n\nfor i, f_ in enumerate(fc_list):\n    qc[f_] = fault_c_list[i].copy()\n    qc[f_][tw_cols] = 1 - qc[f_][tw_cols]\n```\n\n#### Now estimate joint probabilities\n\nMake list of columns to retain in final dataframe\n\n\n```\nprob_cols = list( chain( *['M', list(tw_cols)] ) )\n```\n\ncalculate $p_{joint}$ as $1-(q \\cdot q \\cdot q...)$ and make final dataframe\n\n\n```\nall_prob_gr = 1 - np.product([qq[tw_cols] for qq in  q.values()])\n\nall_prob_gr['M'] = ks['M']\n\nall_prob_gr = all_prob_gr.reindex_axis(prob_cols, axis=1)\n```\n\n\n```\nall_c_prob = 1- np.product([qq[tw_cols] for qq in qc.values()])\n\nall_c_prob['M'] = ks['M']\n\nall_c_prob = all_c_prob.reindex_axis(prob_cols, axis=1)\n```\n\n\n```\ntw=35\nnbins=501\nx_sec_lims = [0,0.4,0,400]\n\nfigure()\n\nsubplot2grid((3,2), (0,0), colspan=2)\naxvline(tw, lw=0.5, color='grey')\nplot_probs(all_prob_gr, lw=0.1, alpha=0.1)\n\nsubplot2grid((3,2), (1,0), colspan=2)\naxvline(tw, lw=0.5, color='grey')\nplot_probs(all_c_prob, lw=0.1, alpha=0.1)\n\nsubplot2grid((3,2), (2,0))\npmf_x_secs(all_prob_gr, tw, n_bins=nbins)\n#axis(x_sec_lims)\n\nsubplot2grid((3,2), (2,1))\npmf_x_secs(all_c_prob, tw, n_bins=nbins)\n#axis([0,0.1,0,400])\nxlim([0,0.8])\nshow()\n```\n\n\n```\ntw=35\nnbins=501\nx_sec_lims = [0,0.4,0,400]\n\nfigure()\n\nsubplot2grid((2,2), (0,0))\naxvline(tw, lw=0.5, color='grey')\nplot_probs(all_prob_gr, lw=0.1, alpha=0.1)\n\nsubplot2grid((2,2), (0,1))\naxvline(tw, lw=0.5, color='grey')\nplot_probs(all_c_prob, lw=0.1, alpha=0.1)\n\nsubplot2grid((2,2), (1,0))\npmf_x_secs(all_prob_gr, tw, n_bins=nbins)\n#axis(x_sec_lims)\n\nsubplot2grid((2,2), (1,1))\npmf_x_secs(all_c_prob, tw, n_bins=nbins)\n#axis([0,0.1,0,400])\nxlim([0,0.8])\nshow()\n```\n\n\n```\n\n```\n", "meta": {"hexsha": "f35746b3cff1d83bfbeefc41b69493818af1bd08", "size": 49932, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lanf_earthquake_likelihood/notebooks/whole_project_real_calcs.ipynb", "max_stars_repo_name": "dick7/test-git", "max_stars_repo_head_hexsha": "359d897d3edd390b14afc28bd9bc50502e087e20", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lanf_earthquake_likelihood/notebooks/whole_project_real_calcs.ipynb", "max_issues_repo_name": "dick7/test-git", "max_issues_repo_head_hexsha": "359d897d3edd390b14afc28bd9bc50502e087e20", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lanf_earthquake_likelihood/notebooks/whole_project_real_calcs.ipynb", "max_forks_repo_name": "dick7/test-git", "max_forks_repo_head_hexsha": "359d897d3edd390b14afc28bd9bc50502e087e20", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9789227166, "max_line_length": 177, "alphanum_fraction": 0.5501482016, "converted": true, "num_tokens": 9029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017956470284, "lm_q2_score": 0.07159120291101934, "lm_q1q2_score": 0.025214550217791776}}
{"text": "```python\n#remove cell visibility\nfrom IPython.display import HTML\ntag = HTML('''\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.''')\ndisplay(tag)\n```\n\n\n\nToggle cell visibility <a href=\"javascript:code_toggle()\">here</a>.\n\n\n\n```python\n%matplotlib inline\nimport control\nimport numpy\nimport sympy as sym\nfrom IPython.display import display, Markdown\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\n\n\n#print a matrix latex-like\ndef bmatrix(a):\n     \"\"\"Returns a LaTeX bmatrix - by Damir Arbula (ICCT project)\n\n     :a: numpy array\n     :returns: LaTeX bmatrix as a string\n     \"\"\"\n     if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n     lines = str(a).replace('[', '').replace(']', '').splitlines()\n     rv = [r'\\begin{bmatrix}']\n     rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n     rv +=  [r'\\end{bmatrix}']\n     return '\\n'.join(rv)\n\n\n# Display formatted matrix: \ndef vmatrix(a):\n    if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n    lines = str(a).replace('[', '').replace(']', '').splitlines()\n    rv = [r'\\begin{vmatrix}']\n    rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n    rv +=  [r'\\end{vmatrix}']\n    return '\\n'.join(rv)\n\n\n#matrixWidget is a matrix looking widget built with a VBox of HBox(es) that returns a numPy array as value !\nclass matrixWidget(widgets.VBox):\n    def updateM(self,change):\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.M_[irow,icol] = self.children[irow].children[icol].value\n                #print(self.M_[irow,icol])\n        self.value = self.M_\n\n    def dummychangecallback(self,change):\n        pass\n    \n    \n    def __init__(self,n,m):\n        self.n = n\n        self.m = m\n        self.M_ = numpy.matrix(numpy.zeros((self.n,self.m)))\n        self.value = self.M_\n        widgets.VBox.__init__(self,\n                             children = [\n                                 widgets.HBox(children = \n                                              [widgets.FloatText(value=0.0, layout=widgets.Layout(width='90px')) for i in range(m)]\n                                             ) \n                                 for j in range(n)\n                             ])\n        \n        #fill in widgets and tell interact to call updateM each time a children changes value\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        #value = Unicode('example@example.com', help=\"The email value.\").tag(sync=True)\n        self.observe(self.updateM, names='value', type= 'All')\n        \n    def setM(self, newM):\n        #disable callbacks, change values, and reenable\n        self.unobserve(self.updateM, names='value', type= 'All')\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].unobserve(self.updateM, names='value')\n        self.M_ = newM\n        self.value = self.M_\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        self.observe(self.updateM, names='value', type= 'All')        \n\n                #self.children[irow].children[icol].observe(self.updateM, names='value')\n\n             \n#overlaod class for state space systems that DO NOT remove \"useless\" states (what \"professor\" of automatic control would do this?)\nclass sss(control.StateSpace):\n    def __init__(self,*args):\n        #call base class init constructor\n        control.StateSpace.__init__(self,*args)\n    #disable function below in base class\n    def _remove_useless_states(self):\n        pass\n```\n\n## Krmiljenje pozicije pnevmatskega sistema\n\n\n\nKroglica je name\u0161\u010dena v navpi\u010dni cevi, skozi katero te\u010de zrak s pretokom $ u $; z vzmetjo togosti $ K $ je povezana na dno cevi; krogla je podvr\u017eena gravitaciji in viskoznemu trenju s koeficientom $ B $. Sila $ F $, ki deluje na kroglo zaradi pretoka zraka, je sorazmerna pretok $ u $ (v m / s) prek konstante $ G $; pretok zraka je lahko samo pozitiven (v cev lahko zgolj vstopa). Glede na maso kroglice $ m = 2 $ g ter $ B = 1 $ g / s, $ K = 2 $ g / $ \\ text {s} ^ 2 $ in $ G = 3 $ Ns / m, je cilj na\u010drtovati regulator, z $ u $ kot vhodom in nadmorsko vi\u0161ino \u017eoge $ z $ kot izhodom, v skladu z naslednjimi zahtevami:\n- brez odstopka v stacionarnem stanju v odzivu na spremembo nadmorske vi\u0161ine v obliki kora\u010dne funkcije,\n- maksimalen prenihaj 30%,\n- \u010das ustalitve kraj\u0161i od 8 s (dose\u017eena vrednost izhoda naj se razlikuje od tiste v stacionarnem stanju za 5%).\n\nDinamiko sistem lahko popi\u0161emo z naslednjo ena\u010dbo:\n\n$$\n    m\\ddot{z} = -Kz -B\\dot{z} + Gu\n$$\n\nOb upot\u0161evanju vektorja stanj $x=\\begin{bmatrix} x_1 & x_2 \\end{bmatrix}^T=\\begin{bmatrix} z & \\dot{z} \\end{bmatrix}^T$ lahko zapi\u0161emo: \n\n\\begin{cases}\n    \\dot{x} = \\begin{bmatrix} 0 & 1 \\\\ -\\frac{K}{m} & -\\frac{B}{m} \\end{bmatrix}x + \\begin{bmatrix} 0 \\\\ \\frac{G}{m} \\end{bmatrix}u \\\\\n    y = \\begin{bmatrix} 1 & 0 \\end{bmatrix}x\n\\end{cases}\n\nPola sistema sta $-0.25\\pm0.97i$.\n\n### Na\u010drtovanje regulatorja\n#### Na\u010drtovanje krmilnika\n\nDa zagotovimo ni\u010den odstopek v stacionarnem stanju, dodamo intergrator v sistem na na\u010din, da raz\u0161irimo vektor stanj z $\\dot{x_3} = x_1 - y_d$, kjer je $y_d$ referenca. Raz\u0161irjen sistem je tako:\n\n\\begin{cases}\n    \\dot{x_a} = \\begin{bmatrix} 0 & 1 & 0 \\\\ -\\frac{K}{m} & -\\frac{B}{m} & 0 \\\\ 1 & 0 & 0 \\end{bmatrix}x_a + \\begin{bmatrix} 0 & 0 \\\\ \\frac{G}{m} & 0 \\\\ 0 & -1 \\end{bmatrix}u \\\\\n    y_a = \\begin{bmatrix} 1 & 0 & 0 \\\\ 0 & 0 & 1 \\end{bmatrix}x_a \\, .\n\\end{cases}\n\nKer so poli sistema po\u010dasni glede na zahteve, pove\u010damo lastno frekvenco kompleksnih polov tako, da ju razporedimo v $-0.5\\pm1.94$, hkrati pa zamenjamo integrator z polom v $-2$.\n\n#### Na\u010drtovanje spoznavalnika\nZa oceno stanj razvijemo spoznavalnik podsistema $(x_1,\\, x_2)$ in vzamemo zgolj oceno stanja $x_2$, ker lahko preostalo stanje neposredno merimo. Za lokacijo polov spoznavalnika izberemo to\u010dko $-5$.\n\n### Kako upravljati s tem interaktivnim primerom?\n- Oceni delovanje regulatorja v primeru relativne variacije mase kroglice (parameter $\\delta m$) in, \u010de je potrebno, spremeni razporeditev polov.\n- Testiraj delovanje regulatorja v primeru za\u010detne napake ocenjenega stanja.\n- Testiraj delovanje regulatorja za razli\u010dne vhodne funkcije.\n\n\n```python\n# Preparatory cell\nb = 1E-03\nk = 2E-03\nG = 3\nm = 2E-03\nAa = numpy.matrix([[0, 1, 0],\n                   [-k/m, -b/m, 0],\n                   [1, 0, 0]])\nBa = numpy.matrix([[0, 0],\n                   [G/m, 0],\n                   [0,-1]])\nCa = numpy.matrix([[1, 0, 0],\n                   [0, 0, 1]])\nA = Aa[0:2,0:2]\nB = Ba[0:2,0]\nC = Ca[0,0:2]\n\nX0 = numpy.matrix('0.0')\nK = numpy.matrix([8/15,-4.4,-4])\nL = numpy.matrix([[23],[66]])\n\nX0w = matrixWidget(1,1)\nX0w.setM(X0)\nKw = matrixWidget(1,3)\nKw.setM(K)\nLw = matrixWidget(2,1)\nLw.setM(L)\n\n\neig1c = matrixWidget(1,1)\neig2c = matrixWidget(2,1)\neig3c = matrixWidget(1,1)\neig1c.setM(numpy.matrix([-2.0])) \neig2c.setM(numpy.matrix([[-0.5],[-1.94]]))\neig3c.setM(numpy.matrix([-2.0]))\n\neig1o = matrixWidget(1,1)\neig2o = matrixWidget(2,1)\neig1o.setM(numpy.matrix([-5.])) \neig2o.setM(numpy.matrix([[-5.],[0.]]))\n```\n\n\n```python\n# Misc\n\n#create dummy widget \nDW = widgets.FloatText(layout=widgets.Layout(width='0px', height='0px'))\n\n#create button widget\nSTART = widgets.Button(\n    description='Test',\n    disabled=False,\n    button_style='', # 'success', 'info', 'warning', 'danger' or ''\n    tooltip='Test',\n    icon='check'\n)\n                       \ndef on_start_button_clicked(b):\n    #This is a workaround to have intreactive_output call the callback:\n    #   force the value of the dummy widget to change\n    if DW.value> 0 :\n        DW.value = -1\n    else: \n        DW.value = 1\n    pass\nSTART.on_click(on_start_button_clicked)\n\n# Define type of method \nselm = widgets.Dropdown(\n    options= ['Nastavi K in L', 'Nastavi lastne vrednosti'],\n    value= 'Nastavi lastne vrednosti',\n    description='',\n    disabled=False\n)\n\n# Define the number of complex eigenvalues\nsele = widgets.Dropdown(\n    options= ['brez kompleksnih lastnih vrednosti', 'dve kompleksni lastni vrednosti'],\n    value= 'dve kompleksni lastni vrednosti',\n    description='Kompleksne lastne vrednosti:',\n    disabled=False\n)\n\n#define type of ipout \nselu = widgets.Dropdown(\n    options=['impulzna funkcija', 'kora\u010dna funkcija', 'sinusoidna funkcija', 'kvadratni val'],\n    value='kora\u010dna funkcija',\n    description='Motnja',\n    style = {'description_width': 'initial'},\n    disabled=False\n)\n# Define the values of the input\nu = widgets.FloatSlider(\n    value=0.1,\n    min=0,\n    max=0.8,\n    step=0.1,\n    description='Referenca [m]:',\n    style = {'description_width': 'initial'},\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.1f',\n)\nmw = widgets.FloatSlider(\n    value=0,\n    min=-30,\n    max=30,\n    step=1,\n    description='delta m [%]:',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.1f',\n)\nperiod = widgets.FloatSlider(\n    value=2,\n    min=0.1,\n    max=3,\n    step=0.05,\n    description='Perioda [s]: ',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.2f',\n)\nsimTime = widgets.FloatText(\n    value=8,\n    description='',\n    disabled=False\n)\n```\n\n\n```python\n# Support functions\n\ndef eigen_choice(sele):\n    if sele == 'brez kompleksnih lastnih vrednosti':\n        eig1c.children[0].children[0].disabled = False\n        eig2c.children[1].children[0].disabled = True\n        eig1o.children[0].children[0].disabled = False\n        eig2o.children[1].children[0].disabled = True\n        eig = 0\n    if sele == 'dve kompleksni lastni vrednosti':\n        eig1c.children[0].children[0].disabled = True\n        eig2c.children[1].children[0].disabled = False\n        eig1o.children[0].children[0].disabled = True\n        eig2o.children[1].children[0].disabled = False\n        eig = 2\n    return eig\n\ndef method_choice(selm):\n    if selm == 'Nastavi K in L':\n        method = 1\n        sele.disabled = True\n    if selm == 'Nastavi lastne vrednosti':\n        method = 2\n        sele.disabled = False\n    return method\n\ndef simulation(m,Kw,L,uw,selu,period,simTime,X0w):\n    Aa = numpy.matrix([[0, 1, 0],\n                   [-k/(0.002*(1+m/100.0)), -b/(0.002*(1+m/100.0)), 0],\n                   [1, 0, 0]])\n    Ba = numpy.matrix([[0, 0],\n                       [G/(0.002*(1+m/100.0)), 0],\n                       [0,-1]])\n    A = Aa[0:2,0:2]\n    B = Ba[0:2,0]\n    \n    e1 = numpy.linalg.eig(Aa-Ba[:,0]*Kw)[0]\n    e1n = numpy.array([numpy.linalg.norm(e1[i]) for i in range(3)])\n    e2 = numpy.linalg.eig(A-L*C)[0]\n    e2n = numpy.array([numpy.linalg.norm(e2[i]) for i in range(2)])\n    # print(e1n,e2n)\n    \n    n1 = 0\n    if all(e1n > 0):\n        if all(numpy.real(e1)<0):\n            n1 = int(max(e1n)/2/numpy.pi*1000)\n    if n1==0:\n        n1 = 10000\n    \n    n2 = 0\n    if all(e2n > 0):\n        if all(numpy.real(e2)<0):\n            n2 = int(max(e2n)/2/numpy.pi*1000)\n    if n2==0:\n        n2 = 10000\n    if n1 >= n2:\n        n = n1\n    else:\n        n = n2\n    \n    T = numpy.linspace(0,simTime,n)\n    ts = T[1]-T[0]\n    if selu == 'impulzna funkcija': #selu\n        R = [0 for t in range(0,len(T))]\n        R[0] = uw        \n    if selu == 'kora\u010dna funkcija':\n        R = [uw for t in range(0,len(T))]\n    if selu == 'sinusoidna funkcija':\n        R = uw*numpy.sin(2*numpy.pi/period*T)\n        #print(R)\n    if selu == 'kvadratni val':\n        R = uw*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n        #print(R)\n    \n    Aad = (numpy.eye(3)+ts*Aa)\n    Bad = ts*Ba\n    Ad = (numpy.eye(2)+ts*(A-L*C))\n    Bd = ts*B\n    Ld = ts*L\n    xa = numpy.matrix([[0],[0],[0]])\n    xe = numpy.matrix([[0],[X0w]])\n    x = numpy.vstack((xa,xe))\n    X = [x]\n    U = []\n    \n    for i in range(len(T)):\n        u = (-Kw*numpy.matrix([[xa[0,0]],[xe[1,0]],[xa[2,0]]]))[0,0]\n        if u < 0:\n            u = 0\n            \n        xe = Ad*xe+Bd*u+Ld*xa[0,0]\n        xa = Aad*xa+Bad*numpy.matrix([[u],[R[i]]])\n        \n        X.append(numpy.vstack((xa,xe)))\n        U.append(u)\n    \n    xout = [\n        [X[i][0,0] for i in range(len(T))],\n        [X[i][1,0] for i in range(len(T))],\n        [X[i][2,0] for i in range(len(T))],\n        [X[i][3,0] for i in range(len(T))],\n        [X[i][4,0] for i in range(len(T))]\n    ]\n    return T, U, R, xout, e1, e2\n```\n\n\n```python\ndef main_callback2(mw, X0w, K, L, eig1c, eig2c, eig3c, eig1o, eig2o, u, period, selm, sele, selu, simTime, DW):\n    eige = eigen_choice(sele)\n    method = method_choice(selm)\n    \n    if method == 1:\n        solc = numpy.linalg.eig(Aa-Ba[:,0]*K)[0]\n        solo = numpy.linalg.eig(A-L*C)[0]\n    if method == 2:\n        if eige == 0:\n            K = control.acker(Aa, Ba[:,0], [eig1c[0,0], eig2c[0,0], eig3c[0,0]])\n            Kw.setM(K)\n            L = control.acker(A.T, C.T, [eig1o[0,0], eig2o[0,0]]).T\n            Lw.setM(L)\n        if eige == 2:\n            K = control.acker(Aa, Ba[:,0], [eig3c[0,0], \n                                     numpy.complex(eig2c[0,0],eig2c[1,0]), \n                                     numpy.complex(eig2c[0,0],-eig2c[1,0])])\n            Kw.setM(K)\n            L = control.acker(A.T, C.T, [numpy.complex(eig2o[0,0],eig2o[1,0]), \n                                         numpy.complex(eig2o[0,0],-eig2o[1,0])]).T\n            Lw.setM(L)\n            \n    if simTime != 0:\n        pass\n    else:\n        simTime = 7\n        \n    T, U, R, xout, sol1, sol2 = simulation(mw,K,L,u,selu,period,simTime,X0w[0,0])\n    \n    if selu == 'kora\u010dna funkcija':\n        found = False\n        ST5 = 0\n        for i in range(len(T)):\n            if R[i] != 0:\n                if abs((xout[0][i]-R[i])/R[i]) <= 0.05 and not found:\n                    ST5 = T[i]\n                    found = True\n                if abs((xout[0][i]-R[i])/R[i]) > 0.05:\n                    found = False\n        OV = 0\n        for i in range(len(T)):\n            if R[i] != 0:\n                if R[0]>0:\n                    if (xout[0][i]-R[i]) > 0:\n                        if abs((xout[0][i]-R[i])/R[i])*100 > OV:\n                            OV = abs((xout[0][i]-R[i])/R[i])*100\n                else:\n                    if (xout[0][i]-R[i]) < 0:\n                        if abs((xout[0][i]-R[i])/R[i])*100 > OV:\n                            OV = abs((xout[0][i]-R[i])/R[i])*100\n    else:\n        ST5 = 'Ni definiran' \n        OV = 'Ni definiran'\n    print('Lastne vrednosti zaprtozan\u010dnega sistema:',sol1)\n    print('Lastne vrednosti spoznavalnika:',sol2)\n    print('Informacije o odzivu sistema: \\n\\t\u010cas ustalitve (5%) [s]=',ST5,'\\n\\tPrenihaj [%]=',OV)\n    \n    fig = plt.figure(num='Simulacija 1', figsize=(14,12))\n    \n    fig.add_subplot(221)\n    plt.title('Odziv sistema')\n    plt.ylabel('Izhod [m]')\n    plt.plot(T,xout[0])\n    plt.plot(T,R,'g--')\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$y$','Referenca'])\n    plt.grid()\n    \n    fig.add_subplot(222)\n    plt.title('Vhod')\n    plt.ylabel('$u$ [N]')\n    plt.plot(T,U)\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(223)\n    plt.title('Odziv stanj')\n    plt.ylabel('Stanje')\n    plt.plot(T,xout[0],\n             T,xout[1],\n             T,xout[2])\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$x_{1}$','$x_{2}$','$x_{3}$'])\n    plt.grid()\n    \n    fig.add_subplot(224)\n    plt.title('Napaka ocene stanj')\n    plt.ylabel('Napaka ocene stanj')\n    plt.plot(T,numpy.array(xout[1])-numpy.array(xout[4]))\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$e_{2}$'])\n    plt.grid()\n    #plt.tight_layout()\n   \nalltogether2 = widgets.VBox([widgets.HBox([selm, \n                                          sele,\n                                          selu]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.Label('K:',border=3), Kw, \n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Lastne vrednosti:',border=3), \n                                          eig1c, \n                                          eig2c, \n                                          eig3c,\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('X0 est.:',border=3), X0w]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.Label('L:',border=3), Lw, \n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Lastne vrednosti:',border=3), \n                                          eig1o, \n                                          eig2o,\n                                          widgets.Label(' ',border=3),\n                                          widgets.VBox([widgets.Label('Simulacijski \u010das [s]:',border=3)]),\n                                          widgets.VBox([simTime])]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([u,\n                                          mw,\n                                          period, \n                                          START])])\nout2 = widgets.interactive_output(main_callback2, {'mw':mw, 'X0w':X0w, 'K':Kw, 'L':Lw,\n                                                 'eig1c':eig1c, 'eig2c':eig2c, 'eig3c':eig3c, 'eig1o':eig1o, 'eig2o':eig2o, \n                                                 'u':u, 'period':period, 'selm':selm, 'sele':sele, 'selu':selu, 'simTime':simTime, 'DW':DW})\nout2.layout.height = '860px'\ndisplay(out2, alltogether2)\n```\n\n\n    Output(layout=Layout(height='860px'))\n\n\n\n    VBox(children=(HBox(children=(Dropdown(index=1, options=('Nastavi K in L', 'Nastavi lastne vrednosti'), value=\u2026\n\n", "meta": {"hexsha": "6bebc073d0dae94b1d7ba6617024267bbb7e005e", "size": 26291, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_si/examples/04/SS-47-Krmiljenje_pozicije_pnevmatskega_sistema.ipynb", "max_stars_repo_name": "ICCTerasmus/ICCT", "max_stars_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-22T18:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:10:22.000Z", "max_issues_repo_path": "ICCT_si/examples/04/SS-47-Krmiljenje_pozicije_pnevmatskega_sistema.ipynb", "max_issues_repo_name": "ICCTerasmus/ICCT", "max_issues_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICCT_si/examples/04/SS-47-Krmiljenje_pozicije_pnevmatskega_sistema.ipynb", "max_forks_repo_name": "ICCTerasmus/ICCT", "max_forks_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-24T11:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T16:36:18.000Z", "avg_line_length": 39.6546003017, "max_line_length": 628, "alphanum_fraction": 0.4535011981, "converted": true, "num_tokens": 5881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814056194821862, "lm_q2_score": 0.08882028878220907, "lm_q1q2_score": 0.024994528387344214}}
{"text": "```python\nfrom IPython.core.display import HTML, Image\ncss_file = 'style.css'\nHTML(open(css_file, 'r').read())\n```\n\n\n\n\n<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:100,300,400,500,700,800,900,100italic,300italic,400italic,500italic,700italic,800italic,900italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Arvo:400,700,400italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=PT+Mono' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Shadows+Into+Light' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Philosopher:400,700,400italic,700italic' rel='stylesheet' type='text/css'>\n\n<style>\n\n@font-face {\n    font-family: \"Computer Modern\";\n    src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');\n}\n\n#notebook_panel { /* main background */\n    background: #ddd;\n    color: #000000;\n}\n\n\n\n/* Formatting for header cells */\n.text_cell_render h1 {\n    font-family: 'Philosopher', sans-serif;\n    font-weight: 400;\n    font-size: 2.2em;\n    line-height: 100%;\n    color: rgb(0, 80, 120);\n    margin-bottom: 0.1em;\n    margin-top: 0.1em;\n    display: block;\n}\t\n.text_cell_render h2 {\n    font-family: 'Philosopher', serif;\n    font-weight: 400;\n    font-size: 1.9em;\n    line-height: 100%;\n    color: rgb(200,100,0);\n    margin-bottom: 0.1em;\n    margin-top: 0.1em;\n    display: block;\n}\t\n\n.text_cell_render h3 {\n    font-family: 'Philosopher', serif;\n    margin-top:12px;\n    margin-bottom: 3px;\n    font-style: italic;\n    color: rgb(94,127,192);\n}\n\n.text_cell_render h4 {\n    font-family: 'Philosopher', serif;\n}\n\n.text_cell_render h5 {\n    font-family: 'Alegreya Sans', sans-serif;\n    font-weight: 300;\n    font-size: 16pt;\n    color: grey;\n    font-style: italic;\n    margin-bottom: .1em;\n    margin-top: 0.1em;\n    display: block;\n}\n\n.text_cell_render h6 {\n    font-family: 'PT Mono', sans-serif;\n    font-weight: 300;\n    font-size: 10pt;\n    color: grey;\n    margin-bottom: 1px;\n    margin-top: 1px;\n}\n\n.CodeMirror{\n        font-family: \"PT Mono\";\n        font-size: 100%;\n}\n\n</style>\n\n\n\n\n\n\n```python\nfrom IPython.core.display import HTML, Image\ncss_file = 'style.css'\nHTML(open(css_file, 'r').read())\n```\n\n\n\n\n<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:100,300,400,500,700,800,900,100italic,300italic,400italic,500italic,700italic,800italic,900italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Arvo:400,700,400italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=PT+Mono' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Shadows+Into+Light' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Philosopher:400,700,400italic,700italic' rel='stylesheet' type='text/css'>\n\n<style>\n\n@font-face {\n    font-family: \"Computer Modern\";\n    src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');\n}\n\n#notebook_panel { /* main background */\n    background: #ddd;\n    color: #000000;\n}\n\n\n\n/* Formatting for header cells */\n.text_cell_render h1 {\n    font-family: 'Philosopher', sans-serif;\n    font-weight: 400;\n    font-size: 2.2em;\n    line-height: 100%;\n    color: rgb(0, 80, 120);\n    margin-bottom: 0.1em;\n    margin-top: 0.1em;\n    display: block;\n}\t\n.text_cell_render h2 {\n    font-family: 'Philosopher', serif;\n    font-weight: 400;\n    font-size: 1.9em;\n    line-height: 100%;\n    color: rgb(200,100,0);\n    margin-bottom: 0.1em;\n    margin-top: 0.1em;\n    display: block;\n}\t\n\n.text_cell_render h3 {\n    font-family: 'Philosopher', serif;\n    margin-top:12px;\n    margin-bottom: 3px;\n    font-style: italic;\n    color: rgb(94,127,192);\n}\n\n.text_cell_render h4 {\n    font-family: 'Philosopher', serif;\n}\n\n.text_cell_render h5 {\n    font-family: 'Alegreya Sans', sans-serif;\n    font-weight: 300;\n    font-size: 16pt;\n    color: grey;\n    font-style: italic;\n    margin-bottom: .1em;\n    margin-top: 0.1em;\n    display: block;\n}\n\n.text_cell_render h6 {\n    font-family: 'PT Mono', sans-serif;\n    font-weight: 300;\n    font-size: 10pt;\n    color: grey;\n    margin-bottom: 1px;\n    margin-top: 1px;\n}\n\n.CodeMirror{\n        font-family: \"PT Mono\";\n        font-size: 100%;\n}\n\n</style>\n\n\n\n\n\n\n```python\nfrom sympy import init_printing, Matrix, symbols, sqrt\nfrom warnings import filterwarnings\n```\n\n\n```python\ninit_printing(use_latex = 'mathjax')\nfilterwarnings('ignore')\n```\n\n# Symmetric matrices\n# Positive definite matrices\n\n## Symmetric matrices\n\n* Symmetric matrices are square with the following property\n$$ {A}={A}^{T} $$\n\n* We are concerned with the eigenvalues and eigenvectors of symmetric matrices\n    * The eigenvalues are real\n    * The eigenvectors are orthogonal, or at least, can be chosen orthogonal\n\n* Considering proof of the real nature of eigenvalues we have the following\n    * Any matrix equation of the following example can be changed to its complex conjugate form by changing each element into its complex conjugate form (here marked with a bar over the top)\n    $$ {A}\\underline{x}={\\lambda}\\underline{x} \\\\ {A}\\overline{x}=\\overline{\\lambda}\\overline{x} $$\n    * We can take the complex conjugate transpose of **x** on both sides\n    $$ \\overline{x}^{T}A\\underline{x}={\\lambda}\\overline{x}^{T}\\underline{x}\\dots\\left(1\\right) $$\n    * In the complex conjugate form this becomes the following\n    $$ \\overline{x}^{T}{A}^{T}\\underline{x}=\\overline{x}^{T}{\\lambda}\\underline{x} $$\n    * Now if A is symmetric we use the fact that A=A<sup>T</sup>\n    $$ \\overline{x}^{T}{A}\\underline{x}=\\overline{x}^{T}\\overline{\\lambda}\\underline{x}\\dots\\left(2\\right) $$\n    * Note how the right-hand sides of (1) and (2) are equal and we therefor have the following\n    $$ \\lambda\\overline{x}^{T}\\underline{x}=\\overline\\lambda\\overline{x}^{T}\\underline{x} $$\n    * This means the following\n    $$ \\lambda=\\overline\\lambda $$\n    * The only ways that this is possible is if the imaginary part is zero and only real eigenvalues are possible\n    * Note also what happens if the complex conjugate of the vector **x** is multiplied by the vector itself\n        * Remember that **x**<sup>T</sup>**x** is a form of the dot product (which is the length squared)\n        * Any number times its complex conjugate gets rid of the imaginary part\n\n* Consider the following symmetric matrix A\n\n\n```python\nA = Matrix([[5, 2], [2, 3]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}5 & 2\\\\2 & 3\\end{matrix}\\right]$$\n\n\n\n* Let's see if it really is symmetric by making sure that it is equal to it's transpose\n\n\n```python\nA == A.transpose() # Boolean (true or false) statement\n```\n\n\n\n\n    True\n\n\n\n\n```python\nS, D = A.diagonalize()\n```\n\n* S, the matrix containing the eigenvectors as it's columns\n    * Remember that these eigenvectors are not necessarily the same as those you would get doing these problems by hand\n    * When substituting the values for &#955;<sub>i</sub> a singular matrix is created with rows that are simply linear combinations of each other\n    * You are free to choose values for the components of the eigenvectors for each eigenvalue (usually choosing the simplest ones)\n\n\n```python\nS\n```\n\n\n\n\n$$\\left[\\begin{matrix}- \\frac{2}{1 + \\sqrt{5}} & - \\frac{2}{- \\sqrt{5} + 1}\\\\1 & 1\\end{matrix}\\right]$$\n\n\n\n* D, the matrix containing the values of the eigenvalues down the main diagonal\n\n\n```python\nD\n```\n\n\n\n\n$$\\left[\\begin{matrix}- \\sqrt{5} + 4 & 0\\\\0 & \\sqrt{5} + 4\\end{matrix}\\right]$$\n\n\n\n* In decomposition, a symmetric matrix results in the following\n$$ {A}={S}{\\Lambda}{S}^{T} $$\n* In this case we have an orthogonal matrix times diagonal matrix times transpose of orthogonal matrix\n$$ {A}={Q}{\\Lambda}{Q}^{T} $$\n\n\n```python\nA.eigenvals()\n```\n\n\n\n\n$$\\begin{Bmatrix}- \\sqrt{5} + 4 : 1, & \\sqrt{5} + 4 : 1\\end{Bmatrix}$$\n\n\n\n\n```python\nA.eigenvects()\n```\n\n\n\n\n$$\\begin{bmatrix}\\begin{pmatrix}- \\sqrt{5} + 4, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}- \\frac{2}{1 + \\sqrt{5}}\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}\\sqrt{5} + 4, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}- \\frac{2}{- \\sqrt{5} + 1}\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}$$\n\n\n\n* We've seen in our example that, indeed, the eigenvalues are real\n* Let's see of the eigenvectors are orthogonal by looking at their dot product\n\n\n```python\neigenvec_1 = Matrix([-2 / (1 + sqrt(5)), 1])\neigenvec_2 = Matrix([-2 / (1 - sqrt(5)), 1])\neigenvec_1.dot(eigenvec_2)\n```\n\n\n\n\n$$\\frac{4}{\\left(1 + \\sqrt{5}\\right) \\left(- \\sqrt{5} + 1\\right)} + 1$$\n\n\n\n* This is certainly zero when simplified\n\n\n```python\n(eigenvec_1.dot(eigenvec_2)).simplify() # Using the simplify() method\n```\n\n\n\n\n$$0$$\n\n\n\n* We need not use symbolic computing (computer algebra system, CAS)\n* Let's look at numerical evaluation using numerical python (numpy)\n\n\n```python\nimport numpy as np # Using namespace abbreviations\n```\n\n\n```python\nA = np.matrix([[5, 2], [2, 3]])\nA\n```\n\n\n\n\n    matrix([[5, 2],\n            [2, 3]])\n\n\n\n\n```python\nw, v = np.linalg.eig(A) # Calculating the eigenvalues and eigenvectors\n# The result of np.linalg.eig() is a tuple, the first being the eigenvalues\n# The second being the eigenvectors\n```\n\n\n```python\nw\n```\n\n\n\n\n    array([ 6.23606798,  1.76393202])\n\n\n\n\n```python\nv\n```\n\n\n\n\n    matrix([[ 0.85065081, -0.52573111],\n            [ 0.52573111,  0.85065081]])\n\n\n\n\n```python\n# Creating the diagonal matrix manually from the eigenvalues\nD = np.matrix([[6.23606798, 0], [0, 1.76393202]])\nD\n```\n\n\n\n\n    matrix([[ 6.23606798,  0.        ],\n            [ 0.        ,  1.76393202]])\n\n\n\n\n```python\n# Checking to see if our equation for A holds\nv * D * np.matrix.transpose(v)\n```\n\n\n\n\n    matrix([[ 5.,  2.],\n            [ 2.,  3.]])\n\n\n\n## Positive definite matrices (referring to symmetric matrices)\n\n* The properties of positive definite (symmetric) matrices \n    * All eigenvalues are positive\n    * All pivots are positive\n    * All determinants (actually also all *sub*-determinants) are positive\n\n* The fact that a (square symmetric) matrix A is invertible implies the following\n    * The determinant is non-zero (actually larger than zero)\n    * The determinant is the product of the eigenvalues\n    * The determinant must therefor be larger than zero\n\n* For projection matrices\n    * The eigenvalues are either 0 or 1\n    * If this projection matrix is positive definite\n        * The eigenvalues must all be 1 (since they must be larger than zero)\n    * The only matrix that satisfies this property is the identity matrix\n\n* The diagonal matrix D is positive definite\n    * This means that for any non-zero vector **x** we have **x**<sup>T</sup>D**x**>0\n    * Let's look at a 3-component vector with a 3&#215;3 matrix D\n\n\n```python\nd1, d2, d3, x1, x2, x3 = symbols('d1 d2 d3 x1 x2 x3')\n```\n\n\n```python\nD = Matrix([[d1, 0, 0], [0, d2, 0], [0, 0, d3]])\nx_vect = Matrix([x1, x2, x3])\nx_vect.transpose(), D, x_vect\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}x_{1} & x_{2} & x_{3}\\end{matrix}\\right], & \\left[\\begin{matrix}d_{1} & 0 & 0\\\\0 & d_{2} & 0\\\\0 & 0 & d_{3}\\end{matrix}\\right], & \\left[\\begin{matrix}x_{1}\\\\x_{2}\\\\x_{3}\\end{matrix}\\right]\\end{pmatrix}$$\n\n\n\n* Indeed we have **x**<sup>T</sup>D**x**>0 since the components if **x** are squared and the eigenvalues are all positive\n\n\n```python\nx_vect.transpose() * D * x_vect\n```\n\n\n\n\n$$\\left[\\begin{matrix}d_{1} x_{1}^{2} + d_{2} x_{2}^{2} + d_{3} x_{3}^{2}\\end{matrix}\\right]$$\n\n\n\n* Not all symmetric matrices with a positive determinant are definite positive\n* Easy matrices to construct with this property have negative values on the main diagonal\n* Note below how the eigenvalues are not all more than zero\n* Also note how **x**<sup>T</sup>D**x**&#8815;0\n* It is important to note that the *sub*-determinant must also be positive\n    * In the example below the *sub*-determinant of 3 is -1\n\n\n```python\nA = Matrix([[3, 1], [1, -1]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}3 & 1\\\\1 & -1\\end{matrix}\\right]$$\n\n\n\n\n```python\nA == A.transpose()\n```\n\n\n\n\n    True\n\n\n\n\n```python\nA.det()\n```\n\n\n\n\n$$-4$$\n\n\n\n\n```python\nA.eigenvals()\n```\n\n\n\n\n$$\\begin{Bmatrix}1 + \\sqrt{5} : 1, & - \\sqrt{5} + 1 : 1\\end{Bmatrix}$$\n\n\n\n\n```python\nA.eigenvects()\n```\n\n\n\n\n$$\\begin{bmatrix}\\begin{pmatrix}1 + \\sqrt{5}, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}- \\frac{1}{- \\sqrt{5} + 2}\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}, & \\begin{pmatrix}- \\sqrt{5} + 1, & 1, & \\begin{bmatrix}\\left[\\begin{matrix}- \\frac{1}{2 + \\sqrt{5}}\\\\1\\end{matrix}\\right]\\end{bmatrix}\\end{pmatrix}\\end{bmatrix}$$\n\n\n\n\n```python\nS, D = A.diagonalize()\n```\n\n\n```python\nS\n```\n\n\n\n\n$$\\left[\\begin{matrix}- \\frac{1}{- \\sqrt{5} + 2} & - \\frac{1}{2 + \\sqrt{5}}\\\\1 & 1\\end{matrix}\\right]$$\n\n\n\n\n```python\nD\n```\n\n\n\n\n$$\\left[\\begin{matrix}1 + \\sqrt{5} & 0\\\\0 & - \\sqrt{5} + 1\\end{matrix}\\right]$$\n\n\n\n\n```python\nx_vect = Matrix([x1, x2])\nx_vect\n```\n\n\n\n\n$$\\left[\\begin{matrix}x_{1}\\\\x_{2}\\end{matrix}\\right]$$\n\n\n\n\n```python\nx_vect.transpose() * D * x_vect\n```\n\n\n\n\n$$\\left[\\begin{matrix}x_{1}^{2} \\left(1 + \\sqrt{5}\\right) + x_{2}^{2} \\left(- \\sqrt{5} + 1\\right)\\end{matrix}\\right]$$\n\n\n\n* In this example the *sub*-determinant of 1 is -3\n\n\n```python\nA = Matrix([[-3, 1], [1, 1]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}-3 & 1\\\\1 & 1\\end{matrix}\\right]$$\n\n\n\n\n```python\nA == A.transpose()\n```\n\n\n\n\n    True\n\n\n\n\n```python\nS, D = A.diagonalize()\n```\n\n\n```python\nx_vect.transpose() * D * x_vect\n```\n\n\n\n\n$$\\left[\\begin{matrix}x_{1}^{2} \\left(-1 + \\sqrt{5}\\right) + x_{2}^{2} \\left(- \\sqrt{5} - 1\\right)\\end{matrix}\\right]$$\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "1e439c21ffa623801d632ea68a9fe041b2e4c343", "size": 30910, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_25_Symmetric_matrices.ipynb", "max_stars_repo_name": "okara83/Becoming-a-Data-Scientist", "max_stars_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_25_Symmetric_matrices.ipynb", "max_issues_repo_name": "okara83/Becoming-a-Data-Scientist", "max_issues_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Mathematics/Linear Algebra/0.0 MIT-18.06 - Jupyter/Lecture_25_Symmetric_matrices.ipynb", "max_forks_repo_name": "okara83/Becoming-a-Data-Scientist", "max_forks_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-09T15:41:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T07:47:40.000Z", "avg_line_length": 25.974789916, "max_line_length": 363, "alphanum_fraction": 0.4541895827, "converted": true, "num_tokens": 4263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.173288223007179, "lm_q2_score": 0.14414884751767365, "lm_q1q2_score": 0.024979297634870473}}
{"text": "# Assignment 3\n\nThis assignment was submitted to the class of 2021/1 for the course MO444 - Introduction to Machine Learning at Universidade Estadual de Campinas.\n\nIts goal is to apply Evolutionary Algorithms and Reinforcement Learning methods to solve the Pac-Man game.\n\n**Authors**\n- Jonathan Nunes  \n  146667  \n  <j146667@dac.unicamp.br>\n\n  Contributions: part II\n\n- Lucas David  \n  188972  \n  <lucas.david@ic.unicamp.br>\n\n  Contributions: part I\n\n**Instructions**\n\nDownload the `pacman.zip` file and extract it into the location described by the `Config.pacman_lib_path` variable. For example: `/content/drive/MyDrive/libs/pacman`.\nThe code inside the Setup section will copy the `search` folder to the same directory containing this notebook.\nThe remaining sections will use the lib indirectly, by executing the python2.7 interpreter with `! python search/pacman.py ...`.\n\nThis notebook is better visualized on Colab, where helpers and unimportant sections are hidden.\n\n\n**Links**\n- Colab: [1R7YboPBEv35cZU5WuGEuN0QNmJrFvYIl](https://colab.research.google.com/drive/1R7YboPBEv35cZU5WuGEuN0QNmJrFvYIl?usp=sharing)\n\n\n```\n#@title\n\nIS_COLAB = 'google.colab' in str(get_ipython())\n\nif IS_COLAB:\n  from google.colab import drive\n  drive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```\nif IS_COLAB:\n  base_dir = '/content/drive/MyDrive/datasets/MO444/assignment-3'\nelse:\n  base_dir = '/home/ldavid/workspace/repos/mo444/assignment-3'\n\nclass Config:\n  pacman_lib_path = base_dir+'/search'\n\n  class evolutionary:\n    jobs = 4\n\n    class small_maze:\n      \n      training_games = 20000\n      testing_games = 10\n\n      config = dict(\n        INITIAL_POPULATION=100,\n        INITIAL_FEATURE_STRENGTH=2.0,\n        MUTATION=0.1,\n        MUTATION_STRENGTH=0.5,\n        TESTS_PER_AGENT=5,\n        RETEST_EVERY_GENERATION=False,\n        MODEL_SAVED_AT = base_dir+'/checkpoints/ev/small',\n        SEED=4124,\n        VERBOSE=1\n      )\n    \n    class medium_maze:\n      training_games = 10000\n      testing_games = 10\n\n      config = dict(\n        INITIAL_POPULATION=100,\n        INITIAL_FEATURE_STRENGTH=2.0,\n        MUTATION=0.1,\n        MUTATION_STRENGTH=0.5,\n        TESTS_PER_AGENT=5,\n        RETEST_EVERY_GENERATION=False,\n        MODEL_SAVED_AT = base_dir+'/checkpoints/ev/medium',\n        SEED=4124,\n        VERBOSE=1\n      )\n    \n    class original_maze:\n      training_games = 4600\n      testing_games = 10\n\n      config = dict(\n        INITIAL_POPULATION=100,\n        INITIAL_FEATURE_STRENGTH=2.0,\n        MUTATION=0.1,\n        MUTATION_STRENGTH=0.5,\n        TESTS_PER_AGENT=5,\n        RETEST_EVERY_GENERATION=False,\n        MODEL_SAVED_AT = base_dir+'/checkpoints/ev/original',\n        SEED=4124,\n        VERBOSE=1\n      )\n  \n  class rl:\n    class test_maze:\n      checkpoint = base_dir+'/checkpoints/rl/test'\n      episodes = 50\n      tests = 10\n    \n    class small_maze:\n      checkpoint = base_dir+'/checkpoints/rl/small'\n      episodes = 5000\n      tests = 10\n    \n    class medium_maze:\n      checkpoint = base_dir+'/checkpoints/rl/medium'\n      episodes = 2000\n      tests = 10\n    \n    class original_maze:\n      checkpoint = base_dir+'/checkpoints/rl/original'\n      episodes = 1000\n      tests = 10\n```\n\n## Setup\n\n\n```bash\n%%bash\n\npip -qq install tk\n### CREATE VIRTUAL DISPLAY ###\napt-get install -y xvfb # Install X Virtual Frame Buffer\n```\n\n    Reading package lists...\n    Building dependency tree...\n    Reading state information...\n    The following NEW packages will be installed:\n      xvfb\n    0 upgraded, 1 newly installed, 0 to remove and 39 not upgraded.\n    Need to get 784 kB of archives.\n    After this operation, 2,270 kB of additional disk space will be used.\n    Get:1 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 xvfb amd64 2:1.19.6-1ubuntu4.9 [784 kB]\n    Fetched 784 kB in 1s (1,031 kB/s)\n    Selecting previously unselected package xvfb.\r\n    (Reading database ... 160815 files and directories currently installed.)\r\n    Preparing to unpack .../xvfb_2%3a1.19.6-1ubuntu4.9_amd64.deb ...\r\n    Unpacking xvfb (2:1.19.6-1ubuntu4.9) ...\r\n    Setting up xvfb (2:1.19.6-1ubuntu4.9) ...\r\n    Processing triggers for man-db (2.8.3-2ubuntu0.1) ...\r\n\n\n\n```\nimport os\nimport json\nimport shutil\n\nimport numpy as np\nimport pandas as pd\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n```\n\n\n```\nsns.set()\n```\n\n\n```\nsearch_path = Config.pacman_lib_path\n\n! cp -r \"$search_path\" .\n! cp -r search/layouts search/*Agents.py .\n```\n\n\n```\n# Checking game run\n\n! python search/pacman.py --layout testMaze --pacman GoWestAgent -q\n```\n\n    Pacman emerges victorious! Score: 503\n    Average Score: 503.0\n    Scores:        503.0\n    Win Rate:      1/1 (1.00)\n    Record:        Win\n\n\n## Evolutionary Strategy\n\n### Description\n\nIn this section, we describe our solution for the Pacman game using Evolutionary Algorithms.\nWe employed Genetic Algorithms to build our Evolutionary Agent,\nand represent by a (state-features, actions) matrix that determines which action will be executed next.\n\n#### Gene and Individual Representation\n\nIndividuals in this population are Pacman agents that can play the game.\nWe represent an agent's decision rationale as a linear process described by\na function similar of classifiers found in Neural Networks and Support Vector Machines (SVMs).\n\nLet $o$ be the temporal step in the current sequential game Pacman, $x^o$ the set of features observed from the world, $l^o_i$ a boolean (0 or 1) vector indicating whether the action $i$ is valid during step $o$, and $W$ and $b$ learning weights. Then,\n\n$$\n\\begin{align}\np_i^o &= \\text{softmax}(x^o\\cdot W+b)_i \\\\\na^o &= \\text{argmax}_i(p^o \\circ l^o_i)\n\\end{align}\n$$\n\nTo simplify things, we leverage the reduced representation of linear transformations, in which the number $1$ is concatenated to the input feature vector and the bias term is represented within $W$:\n\n$$\nx\\cdot W + b \\equiv [x|1] \\cdot \\Bigg[\\frac{W}{b}\\Bigg]\n$$\n\nWhich can be expressed in Python code as:\n\n```python\nclass EvolutionaryAgent(Agent):\n  ...\n\n  def getAction(self, state):\n    legal_action_mask = np.isin(self.ACTIONS, state.getLegalPacmanActions())\n    previ_action_mask = np.isin(self.ACTIONS, [self.previous_action])\n\n    x = extract_features_from(state, previous_action_mask, legal_action_mask)\n    y = np.matmul(x, self.w)\n    y = np.exp(y) / sum(np.exp(y))\n    y = y * legal_action_mask\n\n    choice = self.ACTIONS[y.argmax()]\n```\n\n\n#### Features and Actions\n\nPacman world is described as a *cols x rows* grid, in which the lower-left corner is the $(0, 0)$ point. Furthermore, the first and last rows and columns are always ocupied by walls. Thus valid positions $(y, x)$ for objects in the map are always greater or equal to $(1, 1$) and lower or equal to $(\\text{cols}-1, \\text{rows}-1)$.\nFor example, for the grid below:\n```python\n---------\n|F      |\n|    G P|\n---------\n```\nHence,\n\n* Pacman is located at $P_{p} = (7, 1)$\n* The food dot is located at $P_{f} = (2, 1)$\n* The ghost is located at $P_{g} = (5, 1)$\n\nManhattan distance (or L1-norm) is used to compute distances between points of interest.\nTo simplify the representation of the problem, we opted to represent distances between the Pacman Agent and objects of interest by always taking Pacman's current position as point of reference.\nAdditionaly, We normalize these values by dividing them by $(\\text{cols}-2, \\text{rows}-2)$.\nTherefore,\n\n* Pacman is located at $R_{p} = (0, 0)$\n* G is located at $R_{g} = (\u22120.29, 0)$\n* F is located at $R_{f} = (\u22121, 0.5)$\n\n\nThe following features are extracted by observing the world:\n\n- **food_h**: float, relative horizontal distance to closest food dot.  \n- **food_v**: float, relative vertical distance to closest food dot.\n- **capsule_h**: float, relative horizontal distance to closest capsule.\n- **capsule_v**: float, relative vertical distance to closest capsule.\n- **scary_ghost_h**: float, relative horizontal distance to closest harmful ghost.\n- **scary_ghost_v**: float, relative vertical distance to closest harmful ghost.\n- **scared_ghost_h**: float, relative horizontal distance to closest scared ghost.\n- **scared_ghost_v**: float, relative vertical distance to closest scared ghost.\n- **legal_north?** bool, whether is it legal to go North.\n- **legal_south?** bool, whether is it legal to go South.\n- **legal_east?** bool, whether is it legal to go East.\n- **legal_west?** bool, whether is it legal to go West.\n- **previous_north?** bool, whether North was the previous action.\n- **previous_south?** bool, whether South was the previous action.\n- **previous_east?** bool, whether East was the previous action.\n- **previous_west?** bool, whether West was the previous action.\n- **bias** int, always the constant $1$.\n\n\nFour actions are considered, and are described below.\n```python\nACTIONS = [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]\n```\n\n#### Initial Population Generation\n\nAs individuals are entirely represented by action matrices $W$, generating an initial population is trivial.\nLet $N_0, F, A\\in\\mathbb{N}^+$ be the number of individuals in the initial population, the number of features observed from the world and the number of actions available to the player, respectively.\nLet $V_0\\in\\mathbb{R}^+$ be the maximum feature variation allowed --- a hyperparameter defined during search ---. Then, the initial population is defined as:\n\n$$P = \\{W^i = [w^i_{lm}]_{F\\times A}, \\forall i\\in[0,N_0) \\}$$\nwhere $w^i_{lm} = 2V_0(p_{lm} - 0.5)$ and $p_{lm} \\sim U(0, 1)$ is a number drawn from a uniformly random distribution.\n\nThis is represented in Python code as:\n\n```python\nclass EvolutionPool(object):\n  ...\n\n  def generate(self):\n    self.individuals = (2 * (np.random.rand(self.samples, *self.shape) - 0.5) * INITIAL_FEATURE_STRENGTH)\n    self.scores = np.full(self.samples, -np.inf)\n    self.steps = np.zeros(self.samples)\n    self.evaluations = dict()\n```\n\n#### Evaluating Individuals\n\nAn evaluation of an individual $W^i$ consists of playing the game until its end, in which either Pacman wins by eating all food dots or dies when it comes in contact with one of the Ghosts. In this moment, the score associated with the current state of the game is added to the set of evaluations undertook by $W^i$.\n\nAs the Pacman game has an associated random factor, inducing an uncertain behavior from ghosts across maps, final game scores sometimes do not reflect the true performance of an individual. To circumvent this uncertainty, we evaluate each individual $W^i$ multiple times. We found 5 evaluations per individual to be a good compromise between training time and stability.\n\nOnce an individual is evaluated 5 times, its fitness value (defined as the mean among its evaluation scores) is compared with the highest solution candidate $W^\\star$ found so far. If $W^i$ presents a higher fitness value than $W^\\star$, we redefine the solution candidate in order to restored it during test time.\n\n#### Natural Selection\n\nOnce all individuals in the initial population have been evaluated, selection occurs. We perform selection **before** reproduction, as it showed faster covergence in early testings of our solution.\n\nWe utilize **Steady State** to select individuals, in which half of the population --- the one with lower fitness score --- is killed and replaced with the same number of descendents during the reproduction stage.\n\nSelection can be translated into Python code with the following snippet:\n```python\n  def selection(self):\n    samples = len(self.scores) // 2\n    ids = np.argsort(self.scores)[::-1]\n    selected = ids[:samples]\n    self.individuals = self.individuals[selected]\n    self.scores = self.scores[selected]\n    self.steps = self.steps[selected]\n    self.evaluations = {ind: score for ind, score in enumerate(self.scores)}\n```\n\n#### Reproduction\n\n**Roulette Selection** is used to determine which individuals will be used in crossover. The probability of an individual being selected for breeding is proportional to its fitness, and they are drawn from the population set with replacement.\nA small $\\epsilon$ is added to each fitness value to guarantee every individual has a chance of breeding:\n\n```python\n  def roulette(self, individuals):\n    p = self.scores - self.scores.min() + 1e-7\n    pairs = np.random.choice(len(individuals), size=2 * len(individuals), p=p / p.sum())\n\n    a, b = pairs[:len(pairs) // 2], pairs[len(pairs) // 2:]\n    return individuals[a], individuals[b]\n```\n\nMulti-point crossover is used here. Each individual has a 50% chance of receiving a gene from either parent:\n\n```python\n  def crossover(self, a, b):\n    s = np.random.rand(*a.shape) > 0.5\n    return s * a + ~s * b\n```\n\nFinally, mutation is controlled by a mutation probability factor $p^i_{lm}$ and mutation strength factor $V_m$, in which a gene $[w^i_{lm}]$ is mutated with the addition of a random factor $V_m U(0, 1)$, with probability $p^i_{lm}$:\n\n```python\n  def mutate(self, individuals):\n    r = np.random.rand(*individuals.shape) <= MUTATION\n    m = 2 * (np.random.rand(*individuals.shape) - 0.5) * MUTATION_STRENGTH\n\n    return individuals + r * m\n```\n\n### Genetic Algorithm-Based Agent\n\n\n```\n%%file EvolutionaryAgents.py\n\nimport json\nimport os\n\nimport numpy as np\nimport pandas as pd\nfrom game import Agent, Directions\nfrom util import manhattanDistance\n\n\n# region Global Configuration\n\nconfig_file = os.environ.get('CONFIG_FILE')\n\nif config_file:\n  with open(config_file) as f:\n    config = json.load(f)\n\n  print('[root] loading config file %s' % config_file)\nelse:\n  config = dict()\n\nMAX_SCARED_TIME          = config.get('MAX_SCARED_TIME', 40)\nINITIAL_POPULATION       = config.get('INITIAL_POPULATION', 100)\nINITIAL_FEATURE_STRENGTH = config.get('INITIAL_FEATURE_STRENGTH', 2.)\nMUTATION                 = config.get('MUTATION', 0.05)\nMUTATION_STRENGTH        = config.get('MUTATION_STRENGTH', 0.5)\nTESTS_PER_AGENT          = config.get('TESTS_PER_AGENT', 5)\nRETEST_EVERY_GENERATION  = config.get('RETEST_EVERY_GENERATION', False)\nVERBOSE                  = int(config.get('VERBOSE', 1))\nMODEL_SAVED_AT           = config.get('MODEL_SAVED_AT', 'checkpoints/ev/epochs-10000-pop-100-f-str-2-mut-0.05-mut-str-0.5-tests-5/')\n\nseed = config.get('SEED')\n\nif seed:\n  print('[root] seeding %i' % seed)\n  np.random.seed(seed)\n\n# endregion\n\n\nclass History(object):\n  def __init__(self):\n    self.data = {}\n\n  def update(self, key, value):\n    if key not in self.data:\n      self.data[key] = []\n    self.data[key].append(value)\n\n  def __getitem__(self, item):\n    return self.data[item]\n\n  def items(self):\n    return self.data.items()\n\n  def as_pandas(self):\n    return pd.DataFrame(self.data)\n\n\nclass EvolutionPool(object):\n  def __init__(\n      self,\n      shape,\n      samples=INITIAL_POPULATION,\n  ):\n    self.shape = shape\n    self.samples = samples\n    self.individuals = None\n    self.scores = None\n    self.steps = None\n    self.evaluations = None\n    self.total_evaluations = 0\n    self.generations = 0\n    self.current_ind = 0\n    self.fittest_idx = -1\n    self.fittest_score = -np.inf\n    self.fittest_weights = None\n\n    self.history = History()\n    self.generate()\n\n  def generate(self):\n    if VERBOSE > 1: print('[EvolutionPool] generating an initial population of %i' % self.samples)\n    self.individuals = (2 * (np.random.rand(self.samples, *self.shape) - 0.5) * INITIAL_FEATURE_STRENGTH)\n    self.scores = np.full(self.samples, -np.inf)\n    self.steps = np.zeros(self.samples)\n    self.evaluations = dict()\n\n  def training(self, epoch):\n    if self.current_ind >= len(self.individuals):\n      self.track_generation(epoch)\n      self.selection()\n      self.reproduce()\n\n    return self.current_ind, self.individuals[self.current_ind]\n\n  def evaluate(self, ind, score, steps, epoch):\n    if ind not in self.evaluations:  # First eval\n      self.evaluations[ind] = []\n\n    self.evaluations[ind].append(score)\n    self.steps[ind] += steps\n    self.total_evaluations += 1\n\n    if len(self.evaluations[ind]) >= TESTS_PER_AGENT:\n      self.scores[ind] = np.mean(self.evaluations[ind])\n      self.steps[ind] /= TESTS_PER_AGENT\n\n      if self.scores[ind] > self.fittest_score:\n        if VERBOSE > 1: print('[EvolutionPool] fittest candidate found at epoch %i [score=%s]' % (epoch, self.scores[ind]))\n        self.fittest_idx = ind\n        self.fittest_score = self.scores[ind]\n        self.fittest_weights = self.individuals[ind]\n\n      # No more tests for this individual.\n      self.current_ind += 1\n\n    return self.scores[ind]\n\n  def track_generation(self, epoch):\n    if VERBOSE > 1: print('[EvolutionPool] Epoch=%i' % epoch)\n\n    metrics = (\n      ('generation', self.generations),\n      ('scores', self.scores.copy()),\n      ('scores_max', self.scores.max()),\n      ('scores_min', self.scores.min()),\n      ('scores_avg', self.scores.mean()),\n      ('steps_max', self.steps.max()),\n      ('steps_min', self.steps.min()),\n      ('steps_avg', self.steps.mean()),\n    )\n\n    for k, v in metrics:\n      self.history.update(k, v)\n      if isinstance(v, np.ndarray): v = v.round()[:5]\n      if VERBOSE > 2: print('   %s=%s' % (k, v))\n\n  def reproduce(self):\n    old_population_count = len(self.individuals)\n\n    a, b = self.roulette(self.individuals)\n    offspring = self.crossover(a, b)\n    offspring = self.mutate(offspring)\n    self.individuals = np.concatenate((self.individuals, offspring), axis=0)\n    self.scores = np.concatenate((self.scores, np.full(len(offspring), -np.inf)))\n    self.steps = np.concatenate((self.steps, np.full(len(offspring), 0)))\n\n    self.current_ind = 0 if RETEST_EVERY_GENERATION else old_population_count\n    self.generations += 1\n\n  def roulette(self, individuals):\n    p = self.scores - self.scores.min() + 1e-7\n    pairs = np.random.choice(len(individuals), size=2 * len(individuals), p=p / p.sum())\n\n    a, b = pairs[:len(pairs) // 2], pairs[len(pairs) // 2:]\n    return individuals[a], individuals[b]\n\n  def crossover(self, a, b):\n    s = np.random.rand(*a.shape) > 0.5\n    return s * a + ~s * b\n\n  def mutate(self, individuals):\n    r = np.random.rand(*individuals.shape) <= MUTATION\n    m = 2 * (np.random.rand(*individuals.shape) - 0.5) * MUTATION_STRENGTH\n\n    return individuals + r * m\n\n  def selection(self):\n    samples = len(self.scores) // 2\n    ids = np.argsort(self.scores)[::-1]\n    selected = ids[:samples]\n    self.individuals = self.individuals[selected]\n    self.scores = self.scores[selected]\n    self.steps = self.steps[selected]\n    self.evaluations = {ind: score for ind, score in enumerate(self.scores)}\n\n\nclass EvolutionaryAgent(Agent):\n  ACTIONS = [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]\n  FEATURES = [\n    'food_h', 'food_v', 'capsule_h', 'capsule_v',\n    'scary_ghost_h', 'scary_ghost_v', 'scared_ghost_h', 'scared_ghost_v',\n    'legal_north?', 'legal_south?', 'legal_east?', 'legal_west?',\n    'previous_north?', 'previous_south?', 'previous_east?', 'previous_west?',\n    'bias',\n  ]\n\n  def __init__(\n      self,\n      numTraining=None,\n      **kwargs\n  ):\n    self.epoch = 1\n    self.steps = 0\n    self.numTraining = numTraining\n    self.previous_action = Directions.EAST\n\n    if numTraining:\n      if VERBOSE: print('[EvolutionaryAgent] %s epochs will be used for training.' % numTraining)\n\n      self.p = EvolutionPool(\n        shape=(len(self.FEATURES), len(self.ACTIONS))\n      )\n\n      self.ind, self.w = self.p.training(self.epoch)\n    else:\n      self.p = None\n      self.ind, self.w = -1, load_model(MODEL_SAVED_AT)\n\n  def getAction(self, state):\n    previ_actions_mask = np.isin(self.ACTIONS, [self.previous_action])\n    legal_actions_mask = np.isin(self.ACTIONS, state.getLegalPacmanActions())\n\n    x = extract_features_from(state, previ_actions_mask, legal_actions_mask)\n    y = np.matmul(x, self.w)\n    y = np.exp(y) / sum(np.exp(y))\n    y = y * legal_actions_mask\n\n    # choice = np.random.choice(self.ACTIONS, p=y / y.sum())\n    choice = self.ACTIONS[y.argmax()]\n\n    self.previous_action = choice\n    self.steps += 1\n\n    return choice\n\n  def final(self, state):\n    if self.epoch < self.numTraining:\n      self.p.evaluate(self.ind, state.getScore(), self.steps, self.epoch)\n      self.ind, self.w = self.p.training(self.epoch)\n\n    if self.epoch == self.numTraining and self.p.fittest_weights is not None:\n      if VERBOSE: print('Restoring best weights [score=%.0f]' % self.p.fittest_score)\n\n      self.w = self.p.fittest_weights\n      save_model(self, MODEL_SAVED_AT)\n\n    self.epoch += 1\n    self.steps = 0\n\n\n# region features\n\ndef extract_features_from(state, previous_actions, legal_actions):\n  pp = state.getPacmanPosition()\n\n  fm = np.asarray(state.getFood().data)\n  fp = np.stack(np.where(fm)).T\n\n  cols, rows = fm.shape\n  cols, rows = cols-2, rows-2  # account for external walls.\n\n  food, f_idx = distance_as_features(pp, fp, rows, cols)\n  capsules, c_idx = distance_as_features(pp, state.getCapsules(), rows, cols)\n\n  ghosts = state.getGhostStates()\n  scary = [g for g in ghosts if g.scaredTimer <= 0]\n  scared = [g for g in ghosts if g.scaredTimer > 0]\n\n  scary_dist, _ = distance_as_features(pp, [g.getPosition() for g in scary], rows, cols)\n  scared_dist, _ = distance_as_features(pp, [g.getPosition() for g in scared], rows, cols)\n\n  return np.asarray(food + capsules + scary_dist + scared_dist\n                    + legal_actions.tolist()\n                    + previous_actions.tolist()\n                    + [1])\n\n\ndef distance_as_features(pp, p, rows, cols):\n  p = np.asarray(p)\n  if not len(p):\n    return [1, 1], -1  # max distance\n\n  dists = manhattanDistance(p.T, pp)\n  _idx = closest_idx(dists)\n  d = p[_idx]\n  v = (d - pp).astype('float') / [cols, rows]\n\n  return v.tolist(), _idx\n\n\ndef closest_idx(d, deterministic=False):\n  if deterministic:\n    return d.argmin()\n\n  indices, = np.where(d == d.min())\n  return np.random.choice(indices)\n\n# endregion\n\n\n# region callbacks\n\ndef save_model(model, model_path):\n  if VERBOSE: print('[EvolutionaryAgent] saving weights to %s' % model_path)\n\n  try: os.makedirs(model_path)\n  except: pass\n\n  with open(os.path.join(model_path, 'weights.txt'), 'w') as f:\n    json.dump(model.w.tolist(), f)\n\n  model.p.history.as_pandas().to_csv(os.path.join(model_path, 'history.csv'), index=False)\n\n\ndef load_model(model_path):\n  if VERBOSE: print('[EvolutionaryAgent] loading weights from %s' % model_path)\n\n  with open(os.path.join(model_path, 'weights.txt')) as f:\n    return np.asarray(json.load(f))\n\n# endregion\n```\n\n    Overwriting EvolutionaryAgents.py\n\n\n\n```\n! cp EvolutionaryAgents.py search/EvolutionaryAgents.py\n```\n\n### Searching Parameters\n\n\n```\ndef train(map, epochs, config, config_path):\n  with open(config_path, 'w') as f:\n    json.dump(config, f)\n  \n  print('[Training] map=%s epochs=%i' % (map, epochs))\n\n  ! CONFIG_FILE=$config_path    \\\n    python search/pacman.py     \\\n    --layout $map               \\\n    --pacman EvolutionaryAgent  \\\n    -n $epochs -x $epochs -q -f\n  \n  return config_path\n\ndef train_async(args):\n  return train(*args)\n```\n\n\n```\nfrom math import ceil\nfrom multiprocessing.pool import ThreadPool\n\ndef search(params, config, report_dir, jobs):\n  \"\"\"Run a training procedure for each configuration described in `params`, collecting its logs.\n\n  Returns\n  -------\n  pd.DataFrame\n    The evolution report.\n  \"\"\"\n\n  tp_args = []\n\n  for (epochs, initial_population, mutation, mutation_strength) in params:\n    checkpoint = ('epochs=%s-initial_population=%s-mutation=%s-mutation_strength=%s'\n                  % (epochs, initial_population, mutation, mutation_strength))\n    checkpoint = os.path.join(report_dir, checkpoint)\n    \n    try: os.makedirs(checkpoint)\n    except: pass\n\n    c = config.copy()\n    c.update(\n      INITIAL_POPULATION=initial_population,\n      MUTATION_STRENGTH=mutation_strength,\n      MUTATION=mutation,\n      MODEL_SAVED_AT=checkpoint,\n      VERBOSE=1)\n\n    tp_args.append((\n      'smallClassic',\n      epochs,\n      c,\n      os.path.join(checkpoint, 'config.json')\n    ))\n\n  if jobs > 1:\n    tp = ThreadPool(processes=jobs)\n    results = tp.map(train_async, tp_args)\n    del tp\n  else:\n    results = [train_async(p) for p in tp_args]\n\n  print('done: %s' % results)\n\n\n\ndef generations_to_epochs(g, initial_population=100, tests_per_individual=5):\n  \"\"\"Calculate how many epochs (games) are necessary for the EvolutionPool to spawn `g` generations.\n\n  Parameters\n  ----------\n  g: int, the number of generations desired\n  initial_population: int, the number of individuals in the evolution pool\n  tests_per_individuals: int, the number of tests performed to evaluate each individual\n\n  Returns\n  -------\n  int\n    The number of epochs.\n  \"\"\"\n\n  return int(ceil((1. + (g - 1.) / 2.) * initial_population*tests_per_individual))\n```\n\n\n```\n%%time\n\nEPOCHS = Config.evolutionary.search_epochs\n\nsearch(\n  params=(\n    # epochs, individuals, mutation, mutation_strength\n    (generations_to_epochs(EPOCHS, 100), 100, 0.01, 0.5),\n    (generations_to_epochs(EPOCHS, 100), 100, 0.05, 0.5),\n    (generations_to_epochs(EPOCHS, 100), 100, 0.10, 0.5),\n    (generations_to_epochs(EPOCHS, 100), 100, 0.05, 0.1),\n    (generations_to_epochs(EPOCHS, 100), 100, 0.05, 0.25),\n    (generations_to_epochs(EPOCHS, 100), 100, 0.05, 0.75),\n  ),\n  config=Config.evolutionary.small_maze.config,\n  report_dir=Config.evolutionary.search_reports_dir,\n  jobs=Config.evolutionary.jobs\n)\n```\n\n    [Training] map=smallClassic epochs=7750\n    [root] loading config file /checkpoints/ev/search/epochs=7750-initial_population=100-mutation=0.01-mutation_strength=0.5/config.json\n    [root] seeding 4124\n    [EvolutionaryAgent] 7750 epochs will be used for training.\n    Restoring best weights [score=218]\n    [EvolutionaryAgent] saving weights to /checkpoints/ev/search/epochs=7750-initial_population=100-mutation=0.01-mutation_strength=0.5\n    [Training] map=smallClassic epochs=7750\n    [root] loading config file /checkpoints/ev/search/epochs=7750-initial_population=100-mutation=0.05-mutation_strength=0.5/config.json\n    [root] seeding 4124\n    [EvolutionaryAgent] 7750 epochs will be used for training.\n    Restoring best weights [score=174]\n    [EvolutionaryAgent] saving weights to /checkpoints/ev/search/epochs=7750-initial_population=100-mutation=0.05-mutation_strength=0.5\n    [Training] map=smallClassic epochs=7750\n    [root] loading config file /checkpoints/ev/search/epochs=7750-initial_population=100-mutation=0.1-mutation_strength=0.5/config.json\n    [root] seeding 4124\n    [EvolutionaryAgent] 7750 epochs will be used for training.\n    Restoring best weights [score=172]\n    [EvolutionaryAgent] saving weights to /checkpoints/ev/search/epochs=7750-initial_population=100-mutation=0.1-mutation_strength=0.5\n    [Training] map=smallClassic epochs=7750\n    [root] loading config file /checkpoints/ev/search/epochs=7750-initial_population=100-mutation=0.05-mutation_strength=0.1/config.json\n    [root] seeding 4124\n    [EvolutionaryAgent] 7750 epochs will be used for training.\n    Restoring best weights [score=510]\n    [EvolutionaryAgent] saving weights to /checkpoints/ev/search/epochs=7750-initial_population=100-mutation=0.05-mutation_strength=0.1\n    [Training] map=smallClassic epochs=7750\n    [root] loading config file /checkpoints/ev/search/epochs=7750-initial_population=100-mutation=0.05-mutation_strength=0.25/config.json\n    [root] seeding 4124\n    [EvolutionaryAgent] 7750 epochs will be used for training.\n    Restoring best weights [score=50]\n    [EvolutionaryAgent] saving weights to /checkpoints/ev/search/epochs=7750-initial_population=100-mutation=0.05-mutation_strength=0.25\n    [Training] map=smallClassic epochs=7750\n    [root] loading config file /checkpoints/ev/search/epochs=7750-initial_population=100-mutation=0.05-mutation_strength=0.75/config.json\n    [root] seeding 4124\n    [EvolutionaryAgent] 7750 epochs will be used for training.\n    Restoring best weights [score=-11]\n    [EvolutionaryAgent] saving weights to /checkpoints/ev/search/epochs=7750-initial_population=100-mutation=0.05-mutation_strength=0.75\n    done: ['/checkpoints/ev/search/epochs=7750-initial_population=100-mutation=0.01-mutation_strength=0.5/config.json', '/checkpoints/ev/search/epochs=7750-initial_population=100-mutation=0.05-mutation_strength=0.5/config.json', '/checkpoints/ev/search/epochs=7750-initial_population=100-mutation=0.1-mutation_strength=0.5/config.json', '/checkpoints/ev/search/epochs=7750-initial_population=100-mutation=0.05-mutation_strength=0.1/config.json', '/checkpoints/ev/search/epochs=7750-initial_population=100-mutation=0.05-mutation_strength=0.25/config.json', '/checkpoints/ev/search/epochs=7750-initial_population=100-mutation=0.05-mutation_strength=0.75/config.json']\n    CPU times: user 10.4 s, sys: 2.31 s, total: 12.7 s\n    Wall time: 53min 18s\n\n\n\n```\n#@title Impact of Parameters on Population Evolution\n\nsearch_dir = Config.evolutionary.search_reports_dir\n\nreport = pd.concat([\n  pd.read_csv(os.path.join(search_dir, config, 'history.csv')).assign(config=config)\n  for config in os.listdir(search_dir)\n  if 'history.csv' in os.listdir(os.path.join(search_dir, config))\n])\n\nplt.figure(figsize=(16, 9))\nsns.lineplot(data=report, x='generation', y='scores_avg', hue='config')\nplt.tight_layout();\n```\n\nIt is possible to observe from the curves above that the parameters `initial-population=100`, `mutation=0.05` and `mutation-strength=0.1` induce a faster population convergence, which is not surpassed by other combination of parameters regardless of the generation considered.\n\nAs such, we opted to use these parameters in the following sections.\n\n### Small Classic Maze\n\n#### Training\n\n\n```\n%%time\n\ntrain(\n  'smallClassic',\n  Config.evolutionary.small_maze.training_games,\n  Config.evolutionary.small_maze.config,\n  'small-config.json'\n)\n```\n\n    [Training] map=smallClassic epochs=20000\n    [root] loading config file small-config.json\n    [root] seeding 4124\n    [EvolutionaryAgent] 20000 epochs will be used for training.\n    [EvolutionPool] generating an initial population of 100\n    [EvolutionPool] fittest candidate found [score=-469.8]\n    [EvolutionPool] fittest candidate found [score=-448.6]\n    [EvolutionPool] fittest candidate found [score=-432.0]\n    [EvolutionPool] fittest candidate found [score=-415.0]\n    [EvolutionPool] fittest candidate found [score=-410.8]\n    [EvolutionPool] fittest candidate found [score=-386.2]\n    [EvolutionPool] fittest candidate found [score=-374.8]\n    [EvolutionPool] fittest candidate found [score=-330.6]\n    [EvolutionPool] Epoch=500\n    [EvolutionPool] fittest candidate found [score=-245.4]\n    [EvolutionPool] Epoch=750\n    [EvolutionPool] Epoch=1000\n    [EvolutionPool] fittest candidate found [score=-190.2]\n    [EvolutionPool] Epoch=1250\n    [EvolutionPool] fittest candidate found [score=-103.8]\n    [EvolutionPool] Epoch=1500\n    [EvolutionPool] Epoch=1750\n    [EvolutionPool] fittest candidate found [score=-86.0]\n    [EvolutionPool] Epoch=2000\n    [EvolutionPool] fittest candidate found [score=-39.4]\n    [EvolutionPool] Epoch=2250\n    [EvolutionPool] fittest candidate found [score=80.0]\n    [EvolutionPool] Epoch=2500\n    [EvolutionPool] Epoch=2750\n    [EvolutionPool] Epoch=3000\n    [EvolutionPool] fittest candidate found [score=157.6]\n    [EvolutionPool] fittest candidate found [score=186.0]\n    [EvolutionPool] Epoch=3250\n    [EvolutionPool] Epoch=3500\n    [EvolutionPool] Epoch=3750\n    [EvolutionPool] Epoch=4000\n    [EvolutionPool] Epoch=4250\n    [EvolutionPool] Epoch=4500\n    [EvolutionPool] Epoch=4750\n    [EvolutionPool] Epoch=5000\n    [EvolutionPool] Epoch=5250\n    [EvolutionPool] Epoch=5500\n    [EvolutionPool] fittest candidate found [score=221.4]\n    [EvolutionPool] Epoch=5750\n    [EvolutionPool] Epoch=6000\n    [EvolutionPool] fittest candidate found [score=510.2]\n    [EvolutionPool] Epoch=6250\n    [EvolutionPool] Epoch=6500\n    [EvolutionPool] Epoch=6750\n    [EvolutionPool] Epoch=7000\n    [EvolutionPool] Epoch=7250\n    [EvolutionPool] Epoch=7500\n    [EvolutionPool] Epoch=7750\n    [EvolutionPool] Epoch=8000\n    [EvolutionPool] Epoch=8250\n    [EvolutionPool] Epoch=8500\n    [EvolutionPool] Epoch=8750\n    [EvolutionPool] Epoch=9000\n    [EvolutionPool] Epoch=9250\n    [EvolutionPool] Epoch=9500\n    [EvolutionPool] Epoch=9750\n    [EvolutionPool] Epoch=10000\n    [EvolutionPool] Epoch=10250\n    [EvolutionPool] Epoch=10500\n    [EvolutionPool] Epoch=10750\n    [EvolutionPool] Epoch=11000\n    [EvolutionPool] Epoch=11250\n    [EvolutionPool] Epoch=11500\n    [EvolutionPool] Epoch=11750\n    [EvolutionPool] Epoch=12000\n    [EvolutionPool] Epoch=12250\n    [EvolutionPool] Epoch=12500\n    [EvolutionPool] Epoch=12750\n    [EvolutionPool] Epoch=13000\n    [EvolutionPool] Epoch=13250\n    [EvolutionPool] Epoch=13500\n    [EvolutionPool] Epoch=13750\n    [EvolutionPool] Epoch=14000\n    [EvolutionPool] Epoch=14250\n    [EvolutionPool] Epoch=14500\n    [EvolutionPool] Epoch=14750\n    [EvolutionPool] Epoch=15000\n    [EvolutionPool] Epoch=15250\n    [EvolutionPool] Epoch=15500\n    [EvolutionPool] Epoch=15750\n    [EvolutionPool] Epoch=16000\n    [EvolutionPool] Epoch=16250\n    [EvolutionPool] Epoch=16500\n    [EvolutionPool] Epoch=16750\n    [EvolutionPool] Epoch=17000\n    [EvolutionPool] Epoch=17250\n    [EvolutionPool] Epoch=17500\n    [EvolutionPool] Epoch=17750\n    [EvolutionPool] Epoch=18000\n    [EvolutionPool] Epoch=18250\n    [EvolutionPool] Epoch=18500\n    [EvolutionPool] Epoch=18750\n    [EvolutionPool] Epoch=19000\n    [EvolutionPool] Epoch=19250\n    [EvolutionPool] Epoch=19500\n    [EvolutionPool] Epoch=19750\n    Restoring best weights [score=510]\n    [EvolutionaryAgent] saving weights to /content/drive/MyDrive/datasets/MO444/assignment-3/checkpoints/ev/small\n    CPU times: user 4.7 s, sys: 1.08 s, total: 5.78 s\n    Wall time: 23min 13s\n\n\n\n\n\n    'small-config.json'\n\n\n\n#### Evaluation\n\n\n```\n#@title\n\nhistory = pd.read_csv(os.path.join(\n  Config.evolutionary.small_maze.config['MODEL_SAVED_AT'],\n  'history.csv'))\n\n\nplt.figure(figsize=(12, 4))\nplt.subplot(121)\nsns.lineplot(data=history.melt(id_vars='generation',\n                               value_vars=['scores_avg', 'scores_max', 'scores_min'],\n                               var_name='Metric'),\n             x='generation', y='value', hue='Metric')\nplt.subplot(122)\nsns.lineplot(data=history.melt(id_vars='generation',\n                               value_vars=['steps_avg', 'steps_max', 'steps_min'],\n                               var_name='Metric'),\n             x='generation', y='value', hue='Metric');\n```\n\n#### Playing Game\n\n\n```\n! CONFIG_FILE=small-config.json     \\\n  python search/pacman.py           \\\n         --layout smallClassic      \\\n         --pacman EvolutionaryAgent \\\n         -n 20 -q -f\n```\n\n    [root] loading config file small-config.json\n    [root] seeding 4124\n    [EvolutionaryAgent] loading weights from /content/drive/MyDrive/datasets/MO444/assignment-3/checkpoints/ev/small\n    Pacman died! Score: -446\n    Pacman died! Score: 304\n    Pacman died! Score: -394\n    Pacman died! Score: -446\n    Pacman died! Score: 159\n    Pacman died! Score: 57\n    Pacman died! Score: 89\n    Pacman died! Score: 238\n    Pacman died! Score: -130\n    Pacman died! Score: 198\n    Pacman died! Score: -340\n    Pacman died! Score: -410\n    Pacman died! Score: -9\n    Pacman died! Score: 205\n    Pacman died! Score: -410\n    Pacman died! Score: -184\n    Pacman died! Score: 69\n    Pacman died! Score: -446\n    Pacman died! Score: 242\n    Pacman died! Score: -446\n    Average Score: -105.0\n    Scores:        -446.0, 304.0, -394.0, -446.0, 159.0, 57.0, 89.0, 238.0, -130.0, 198.0, -340.0, -410.0, -9.0, 205.0, -410.0, -184.0, 69.0, -446.0, 242.0, -446.0\n    Win Rate:      0/20 (0.00)\n    Record:        Loss, Loss, Loss, Loss, Loss, Loss, Loss, Loss, Loss, Loss, Loss, Loss, Loss, Loss, Loss, Loss, Loss, Loss, Loss, Loss\n\n\n### Medium Classic Maze\n\n##### Training\n\n\n```\n%%time\n\ntrain(\n  'mediumClassic',\n  Config.evolutionary.medium_maze.training_games,\n  Config.evolutionary.medium_maze.config,\n  'medium-config.json'\n)\n```\n\n    [Training] map=mediumClassic epochs=10000\n    [root] loading config file medium-config.json\n    [root] seeding 4124\n    [EvolutionaryAgent] 10000 epochs will be used for training.\n    [EvolutionPool] generating an initial population of 100\n    [EvolutionPool] fittest candidate found [score=-501.2]\n    [EvolutionPool] fittest candidate found [score=-453.4]\n    [EvolutionPool] fittest candidate found [score=-306.0]\n    [EvolutionPool] fittest candidate found [score=-264.4]\n    [EvolutionPool] Epoch=500\n    [EvolutionPool] fittest candidate found [score=-209.6]\n    [EvolutionPool] Epoch=750\n    [EvolutionPool] Epoch=1000\n    [EvolutionPool] Epoch=1250\n    [EvolutionPool] fittest candidate found [score=-48.8]\n    [EvolutionPool] Epoch=1500\n    [EvolutionPool] Epoch=1750\n    [EvolutionPool] fittest candidate found [score=80.4]\n    [EvolutionPool] Epoch=2000\n    [EvolutionPool] fittest candidate found [score=126.2]\n    [EvolutionPool] Epoch=2250\n    [EvolutionPool] Epoch=2500\n    [EvolutionPool] fittest candidate found [score=158.4]\n    [EvolutionPool] fittest candidate found [score=163.2]\n    [EvolutionPool] Epoch=2750\n    [EvolutionPool] fittest candidate found [score=243.0]\n    [EvolutionPool] Epoch=3000\n    [EvolutionPool] Epoch=3250\n    [EvolutionPool] fittest candidate found [score=248.2]\n    [EvolutionPool] Epoch=3500\n    [EvolutionPool] Epoch=3750\n    [EvolutionPool] fittest candidate found [score=286.0]\n    [EvolutionPool] Epoch=4000\n    [EvolutionPool] Epoch=4250\n    [EvolutionPool] Epoch=4500\n    [EvolutionPool] fittest candidate found [score=289.6]\n    [EvolutionPool] Epoch=4750\n    [EvolutionPool] Epoch=5000\n    [EvolutionPool] fittest candidate found [score=310.0]\n    [EvolutionPool] Epoch=5250\n    [EvolutionPool] Epoch=5500\n    [EvolutionPool] Epoch=5750\n    [EvolutionPool] Epoch=6000\n    [EvolutionPool] Epoch=6250\n    [EvolutionPool] Epoch=6500\n    [EvolutionPool] fittest candidate found [score=338.6]\n    [EvolutionPool] Epoch=6750\n    [EvolutionPool] fittest candidate found [score=418.6]\n    [EvolutionPool] Epoch=7000\n    [EvolutionPool] Epoch=7250\n    [EvolutionPool] Epoch=7500\n    [EvolutionPool] Epoch=7750\n    [EvolutionPool] Epoch=8000\n    [EvolutionPool] Epoch=8250\n    [EvolutionPool] Epoch=8500\n    [EvolutionPool] Epoch=8750\n    [EvolutionPool] Epoch=9000\n    [EvolutionPool] Epoch=9250\n    [EvolutionPool] Epoch=9500\n    [EvolutionPool] Epoch=9750\n    Restoring best weights [score=419]\n    [EvolutionaryAgent] saving weights to /content/drive/MyDrive/datasets/MO444/assignment-3/checkpoints/ev/medium\n    CPU times: user 4.98 s, sys: 1.07 s, total: 6.05 s\n    Wall time: 24min 32s\n\n\n\n\n\n    'medium-config.json'\n\n\n\n#### Evaluation\n\n\n```\n#@title\n\nhistory = pd.read_csv(os.path.join(\n  Config.evolutionary.medium_maze.config['MODEL_SAVED_AT'],\n  'history.csv'))\n\n\nplt.figure(figsize=(12, 4))\nplt.subplot(121)\nsns.lineplot(data=history.melt(id_vars='generation',\n                               value_vars=['scores_avg', 'scores_max', 'scores_min'],\n                               var_name='Metric'),\n             x='generation', y='value', hue='Metric')\nplt.subplot(122)\nsns.lineplot(data=history.melt(id_vars='generation',\n                               value_vars=['steps_avg', 'steps_max', 'steps_min'],\n                               var_name='Metric'),\n             x='generation', y='value', hue='Metric');\n```\n\n#### Playing Game\n\n\n```\n! CONFIG_FILE=medium-config.json     \\\n  python search/pacman.py           \\\n         --layout mediumClassic      \\\n         --pacman EvolutionaryAgent \\\n         -n 10 -q -f\n```\n\n    [root] loading config file medium-config.json\n    [root] seeding 4124\n    [EvolutionaryAgent] loading weights from /content/drive/MyDrive/datasets/MO444/assignment-3/checkpoints/ev/medium\n    Pacman died! Score: 156\n    Pacman died! Score: 289\n    Pacman died! Score: -394\n    Pacman died! Score: 113\n    Pacman died! Score: 195\n    Pacman died! Score: -94\n    Pacman died! Score: 521\n    Pacman died! Score: 133\n    Pacman died! Score: 127\n    Pacman died! Score: 209\n    Average Score: 125.5\n    Scores:        156.0, 289.0, -394.0, 113.0, 195.0, -94.0, 521.0, 133.0, 127.0, 209.0\n    Win Rate:      0/10 (0.00)\n    Record:        Loss, Loss, Loss, Loss, Loss, Loss, Loss, Loss, Loss, Loss\n\n\n### Original Classic Maze\n\n##### Training\n\n\n```\n%%time\n\ntrain(\n  'originalClassic',\n  Config.evolutionary.original_maze.training_games,\n  Config.evolutionary.original_maze.config,\n  'original-config.json'\n)\n```\n\n    [Training] map=originalClassic epochs=4600\n    [root] loading config file original-config.json\n    [root] seeding 4124\n    [EvolutionaryAgent] 4600 epochs will be used for training.\n    [EvolutionPool] generating an initial population of 100\n    [EvolutionPool] fittest candidate found at epoch 5 [score=-490.6]\n    [EvolutionPool] fittest candidate found at epoch 10 [score=-331.8]\n    [EvolutionPool] fittest candidate found at epoch 65 [score=-158.0]\n    [EvolutionPool] fittest candidate found at epoch 255 [score=64.0]\n    [EvolutionPool] Epoch=500\n    [EvolutionPool] Epoch=750\n    [EvolutionPool] Epoch=1000\n    [EvolutionPool] Epoch=1250\n    [EvolutionPool] Epoch=1500\n    [EvolutionPool] fittest candidate found at epoch 1570 [score=112.2]\n    [EvolutionPool] Epoch=1750\n    [EvolutionPool] fittest candidate found at epoch 1860 [score=140.0]\n    [EvolutionPool] fittest candidate found at epoch 1905 [score=302.2]\n    [EvolutionPool] Epoch=2000\n    [EvolutionPool] Epoch=2250\n    [EvolutionPool] Epoch=2500\n    [EvolutionPool] fittest candidate found at epoch 2690 [score=321.2]\n    [EvolutionPool] Epoch=2750\n    [EvolutionPool] fittest candidate found at epoch 2800 [score=364.4]\n    [EvolutionPool] Epoch=3000\n    [EvolutionPool] Epoch=3250\n    [EvolutionPool] Epoch=3500\n    [EvolutionPool] Epoch=3750\n    [EvolutionPool] Epoch=4000\n    [EvolutionPool] Epoch=4250\n    [EvolutionPool] Epoch=4500\n    [EvolutionPool] fittest candidate found at epoch 4595 [score=431.4]\n    Restoring best weights [score=431]\n    [EvolutionaryAgent] saving weights to /content/drive/MyDrive/datasets/MO444/assignment-3/checkpoints/ev/original\n    CPU times: user 13.4 s, sys: 2.72 s, total: 16.1 s\n    Wall time: 1h 2min 18s\n\n\n\n\n\n    'original-config.json'\n\n\n\n#### Evaluation\n\n\n\n\n```\n#@title\n\nhistory = pd.read_csv(os.path.join(\n  Config.evolutionary.original_maze.config['MODEL_SAVED_AT'],\n  'history.csv'))\n\n\nplt.figure(figsize=(12, 4))\nplt.subplot(121)\nsns.lineplot(data=history.melt(id_vars='generation',\n                               value_vars=['scores_avg', 'scores_max', 'scores_min'],\n                               var_name='Metric'),\n             x='generation', y='value', hue='Metric')\nplt.subplot(122)\nsns.lineplot(data=history.melt(id_vars='generation',\n                               value_vars=['steps_avg', 'steps_max', 'steps_min'],\n                               var_name='Metric'),\n             x='generation', y='value', hue='Metric');\n```\n\n#### Playing Game\n\n\n```\n! CONFIG_FILE=original-config.json  \\\n  python search/pacman.py           \\\n         --layout originalClassic   \\\n         --pacman EvolutionaryAgent \\\n         -n 10 -q -f\n```\n\n    [root] loading config file original-config.json\n    [root] seeding 4124\n    [EvolutionaryAgent] loading weights from /content/drive/MyDrive/datasets/MO444/assignment-3/checkpoints/ev/original\n    Pacman died! Score: 36\n    Pacman died! Score: 420\n    Pacman died! Score: 266\n    Pacman died! Score: -371\n    Pacman died! Score: 38\n    Pacman died! Score: 60\n    Pacman died! Score: 100\n    Pacman died! Score: -379\n    Pacman died! Score: 55\n    Pacman died! Score: 113\n    Average Score: 33.8\n    Scores:        36.0, 420.0, 266.0, -371.0, 38.0, 60.0, 100.0, -379.0, 55.0, 113.0\n    Win Rate:      0/10 (0.00)\n    Record:        Loss, Loss, Loss, Loss, Loss, Loss, Loss, Loss, Loss, Loss\n\n\n## Reinforcement Learning\n\n### Description\n\nIn this section we described our solution for the Pacman game using Reinforcement Learning-Based algorithm. We use Q-Learning to train our agent and save the chosen actions in every step.\n\n#### Q-Learning Algorithm\n\nQ-Learning is a model-free reinforcement learning algorithm that seeks to find the best action to take at a given state, trying to maximize the value of total reward over any and all successive steps and hence q-learning is considered a value based agorithm using the Bellman equation.\n\n**Q[s, a]** is the expected value of doing the action **a** in the state **s** and the agent mantains a table **Q[s, a]**.\n\nThe value Q[s, a] is calculated using the bellman equation:\n\n$$Q(s_i, a_i)=Q(s, a)+\\alpha [R(s, a) + \\gamma max(Q'(s', a')) - Q(s, a)]$$\n\nwhere:\n\n$Q(s_i, a_i)$ is the new Q value for a given state and action\n\n$Q(s, a)$  is the current Q value\n\n$\\alpha$ is the learning rate. Varies between 0 and 1 and represents whether the algorithm should prefer old information or future information respectively.\n\n$R(s, a)$ is the reward for taken a given action\n\n$\\gamma$ is the discount rate Varies between 0 and 1 and represents whether the algorithm should priotize immediate reward or future reward respectively.\n\n$max(Q'(s'm a'))$ is the maximum reward given the new state and all valid actions.\n\n```\nbegin\ninitialize Q-table\nwhile state is not end_state:\n    chose an action\n    perform an action\n    measure reward\n    evaluate Q-value\n    update Q-table\nend\n```\n\n#### Implementation Description\n\nThe state of the game is used to save the Q value table. The state consist of the pacman position, ghosts, capsule and food positions. The reward is calculated getting the score of a given action and a value that takes in consideration the following cases:\n\nGive a small reward for pacman not change its direction to prevent loops\n\nGive a positive inversely proportional reward based in the distance of pacman and scared ghosts (the closer Pacman get to the ghosts the greater the reward)\n\nGive a negative inversely proportional reward based in the distance of pacman and ghosts (the closer Pacman get to the ghosts the lower the reward)\n\nThe agent was trained for 1000 epochs and then played 10 times using the training data in the small classic and medium classic mazes and trained for 500 epochs and played 10 times in the original maze.\n\nDuring training the chosen action in each iteraction is either the action with the better score or a random action (this random action is executed $\\epsilon\\%$ of times). After the data is trained we changed $\\epsilon$ to $\\epsilon=0$ so that the data uses only the best actions.\n\nTo visualize the results we generated a scatter plot with a tendency line where the y axis was the epoch number and the x axis was the aveage score for the last 50 epochs.\n\n### Reinforcement Learning-Based Agent\n\n\n```\n%%file QLearningAgents.py\n\nimport os\nimport random\nimport math as m\n\nimport pickle\nfrom game import Agent, Directions\n\n\nCHECKPOINT = os.environ.get('CHECKPOINT', '')\n\n\nclass QLearningAgent(Agent):\n    def __init__(self, a=0.1, g=0.9, eps=0.3, numTraining=0):\n        self.eps = eps  # random action chance\n        self.training_episodes = numTraining\n        self.a = a  # 0 => past information, 1 => future information\n        self.g = g  # 0 => immediate reward, 1 => future reward\n        self.pstate = None\n        self.paction = None\n        self.pscore = None\n        self.episode = 0\n        self.partial_steps = 0\n        self.avr = ''\n        self.avr_steps = ''\n        self.score_max = None\n        self.score_min = None\n        self.steps_max = None\n        self.steps_min = None\n        self.prev_action = None\n        self.qvalues = {}\n\n        if not self.training_episodes:  # testing\n            self.a = 0\n            self.g = 1\n            self.eps = 0\n            self.load_weights()\n        else:\n            print('[QLearningAgent] training for %i games' % numTraining)\n\n    def getAction(self, state):\n        # state information\n        self.partial_steps += 1\n        curr_state = self.get_state_parameters(state)\n        curr_state['legal'].remove(Directions.STOP)\n        \n        if state not in self.qvalues:\n            self.qvalues[state] = {}\n            for action in curr_state['legal']:\n                if action not in self.qvalues[state]:\n                    self.qvalues[state][action] = 0.0\n\n        # select action\n        if self.pstate is not None:\n            self.sel_action(state)\n\n        #next stage\n        self.update(state, curr_state['legal'])\n        return self.paction\n\n    @staticmethod\n    def get_state_parameters(state):\n        return {\n            'legal': state.getLegalPacmanActions(),\n            'pacman_pos': state.getPacmanPosition(),\n            'pup_pos': state.getFood(),\n            'ghost_pos': state.getGhostPositions(),\n            'ghost_state': {\n                i: { 'scared_timer': ghost.scaredTimer }\n                for i, ghost in enumerate(state.getGhostStates())\n            }\n        }\n\n    def get_updated_reward(self, state, action):\n        ret = state.getScore()\n        p = QLearningAgent.get_state_parameters(state)\n        score_ghosts = 0\n        i = 0\n        if action == self.prev_action:\n            s = 5\n        else:\n            s = 0\n        for pos in p['ghost_pos']:\n            mag = m.sqrt((p['pacman_pos'][0] - pos[0])**2 + (p['pacman_pos'][1] - pos[1])**2)\n            if (p['ghost_state'][i]['scared_timer'] == 0) and mag <= 6:\n                s -= (15 if mag == 0 else 1/mag * 15)\n            else:\n                s += (30 if mag == 0 else 1/mag * 30)\n        ret += s\n        return ret\n\n    def sel_action(self, state, final=False):\n        reward = self.get_updated_reward(state, None) - self.pscore\n        if not final:\n            max_qvalue = self.get_max_qvalue(state)\n        else:\n            max_qvalue = 0\n        qv = self.a * (reward + self.g * max_qvalue - self.qvalues[self.pstate][self.paction])\n        self.qvalues[self.pstate][self.paction] += qv\n\n    def get_max_qvalue(self, state):\n        return max(self.qvalues[state].values())\n\n    def update(self, state, legal_actions):\n        updated_cost = {}\n        prob = random.random()\n        self.pstate = state\n        if prob < self.eps:\n            self.paction = random.choice(legal_actions)\n        else:\n            maxq_action = None\n            for action in legal_actions:\n                updated_cost[action] = self.get_updated_reward(state.generatePacmanSuccessor(action), action)\n                if maxq_action is None:\n                    maxq_action = action\n                if self.qvalues[state][action] > self.qvalues[state][maxq_action]:\n                    maxq_action = action\n            if self.qvalues[state][action] == 0:\n                maxq_action = max(updated_cost, key=updated_cost.get)\n            self.paction = maxq_action\n            self.prev_action = maxq_action\n        self.pscore = state.getScore()\n\n    def final(self, state):\n        if self.pstate is not None:\n            self.sel_action(state, True)\n        \n        self.avr += str(self.pscore) if self.episode == self.training_episodes else str(self.pscore) + ','\n        self.avr_steps += str(self.partial_steps) if self.episode == self.training_episodes else str(self.partial_steps) + ','\n        \n        self.episode += 1\n        self.get_steps_data()\n        self.get_score_data(self.pscore)\n\n        if not self.episode % max(1, self.training_episodes // 10):\n            reward = self.get_updated_reward(state, None) - self.pscore\n            print('[QLearningAgent] Episode %i [reward=%f]' % (self.episode, reward))\n\n        self.pstate = None\n        self.paction = None\n        self.pscore = None\n        \n        if self.episode == self.training_episodes:\n            print('[QLearningAgent] training ended.')\n            self.save_values()\n\n        if self.episode >= self.training_episodes:\n            self.a = 0\n            self.g = 1\n            self.eps = 0\n    \n    def get_steps_data(self):\n        if self.steps_max == None:\n            self.steps_max = self.partial_steps\n        if self.steps_min == None:\n            self.steps_min = self.partial_steps\n        if self.steps_max < self.partial_steps:\n            self.steps_max = self.partial_steps\n        if self.steps_min > self.partial_steps:\n            self.steps_min = self.partial_steps\n        self.partial_steps = 0\n    \n    def get_score_data(self, score):\n        if self.score_max == None:\n            self.score_max = score\n        if self.score_min == None:\n            self.score_min = score\n        if self.score_max < score:\n            self.score_max = score\n        if self.score_min > score:\n            self.score_min = score\n    \n    def save_values(self):\n        if CHECKPOINT and not os.path.exists(CHECKPOINT):\n            os.makedirs(CHECKPOINT)\n            \n        with open(os.path.join(CHECKPOINT, 'history.txt'), 'w+') as f:\n            f.write(self.avr)\n            f.write(\"\\n\")\n            f.write(self.avr_steps)\n            f.write(\"\\n\")\n            f.write(str(self.steps_min) + ',' + str(self.steps_max))\n            f.write(\"\\n\")\n            f.write(str(self.score_min) + ',' + str(self.score_max))\n        \n        weights_file = os.path.join(CHECKPOINT, 'weights.p')\n        print('[QLearningAgent] saving weights to %s' % CHECKPOINT)\n\n        with open(weights_file, 'wb') as f:\n          pickle.dump(self.qvalues, f)        \n\n    def load_weights(self):\n        print('[QLearningAgent] loading weights from %s' % CHECKPOINT)\n\n        with open(os.path.join(CHECKPOINT, 'weights.p'), 'rb') as f:\n            self.qvalues = pickle.load(f)\n```\n\n    Overwriting QLearningAgents.py\n\n\n\n```\n! cp QLearningAgents.py search/QLearningAgents.py\n```\n\n### Test Maze\n\n#### Training\n\n\n```\ndef train_rl(map, checkpoint_path, episodes=1000, tests=10):\n    n = episodes + tests\n\n    ! CHECKPOINT=$checkpoint_path \\\n      python search/pacman.py \\\n      --layout $map           \\\n      --pacman QLearningAgent \\\n      -n $n -x $episodes -f -q\n```\n\n\n```\ntrain_rl(\n  'testMaze',\n  Config.rl.test_maze.checkpoint,\n  Config.rl.test_maze.episodes,\n  Config.rl.test_maze.tests\n)\n```\n\n    [QLearningAgent] training for 50 games\n    [QLearningAgent] Episode 5 [reward=509.000000]\n    [QLearningAgent] Episode 10 [reward=509.000000]\n    [QLearningAgent] Episode 15 [reward=509.000000]\n    [QLearningAgent] Episode 20 [reward=509.000000]\n    [QLearningAgent] Episode 25 [reward=509.000000]\n    [QLearningAgent] Episode 30 [reward=509.000000]\n    [QLearningAgent] Episode 35 [reward=509.000000]\n    [QLearningAgent] Episode 40 [reward=509.000000]\n    [QLearningAgent] Episode 45 [reward=509.000000]\n    [QLearningAgent] Episode 50 [reward=509.000000]\n    [QLearningAgent] training ended.\n    Pacman emerges victorious! Score: 503\n    Pacman emerges victorious! Score: 503\n    Pacman emerges victorious! Score: 503\n    Pacman emerges victorious! Score: 503\n    Pacman emerges victorious! Score: 503\n    [QLearningAgent] Episode 55 [reward=509.000000]\n    Pacman emerges victorious! Score: 503\n    Pacman emerges victorious! Score: 503\n    Pacman emerges victorious! Score: 503\n    Pacman emerges victorious! Score: 503\n    Pacman emerges victorious! Score: 503\n    [QLearningAgent] Episode 60 [reward=509.000000]\n    Average Score: 503.0\n    Scores:        503.0, 503.0, 503.0, 503.0, 503.0, 503.0, 503.0, 503.0, 503.0, 503.0\n    Win Rate:      10/10 (1.00)\n    Record:        Win, Win, Win, Win, Win, Win, Win, Win, Win, Win\n\n\n#### Evaluation\n\n\n```\n#@title\n\nclass bold():\n  BOLD  = '\\033[1m'\n  EBOLD = '\\033[0m'\n\nplist_avr = lambda l : np.mean(np.array(l).astype(np.float))\n\ndef plot_results(checkpoint):\n  with open(os.path.join(checkpoint, 'history.txt')) as f:\n    lines = f.readlines()\n  scores = lines[0].split(',')[:-1]\n  steps = lines[1].split(',')[:-1]\n  div = 50\n  samples = len(scores)//div\n  min_max_steps = lines[2].split(',')\n  min_max_score = lines[3].split(',')\n\n  data_score = [[(i+1)*div, plist_avr(scores[i*div:i*div+div])] for i in range(samples)]\n  df1 = pd.DataFrame(data_score, columns = ['Episodes', 'Average score last 50 episodes'])\n\n  data_steps = [[(i+1)*div, plist_avr(steps[i*div:i*div+div])] for i in range(samples)]\n  df2 = pd.DataFrame(data_steps, columns = ['Episodes', 'Average steps last 50 episodes'])\n\n  f, axes = plt.subplots(1, 2, figsize=(20,7))\n  sns.regplot(x='Episodes', y='Average score last 50 episodes',data=df1, fit_reg=True, ax=axes[0])\n  sns.regplot(x='Episodes', y='Average steps last 50 episodes',data=df2, fit_reg=True, ax=axes[1])\n\n  A = np.array(data_steps)\n  ymin = np.min(A[:,1], axis=0) - 5\n  ymax = np.max(A[:,1], axis=0) + 5\n  axes[1].set_ylim(ymin, ymax)\n  plt.show()\n  print('Min number of steps: ' + bold.BOLD + min_max_steps[0] + bold.EBOLD)\n  print('Max number of steps: ' + bold.BOLD + min_max_steps[1] + bold.EBOLD + \"\\n\")\n  print('Min score: ' + bold.BOLD + min_max_score[0] + bold.EBOLD)\n  print('Max score: ' + bold.BOLD + min_max_score[1] + bold.EBOLD)\n```\n\n\n```\nplot_results(Config.rl.test_maze.checkpoint)\n```\n\n\n### Small Classic Maze\n\n#### Training\n\n\n```\n%%time\n\ntrain_rl(\n  'smallClassic',\n  Config.rl.small_maze.checkpoint,\n  Config.rl.small_maze.episodes,\n  Config.rl.small_maze.tests\n)\n```\n\n    [QLearningAgent] training for 5000 games\n    [QLearningAgent] Episode 500 [reward=-513.692308]\n    [QLearningAgent] Episode 1000 [reward=-502.746043]\n    [QLearningAgent] Episode 1500 [reward=-512.278958]\n    [QLearningAgent] Episode 2000 [reward=-512.060807]\n    [QLearningAgent] Episode 2500 [reward=-521.000000]\n    [QLearningAgent] Episode 3000 [reward=-461.136061]\n    [QLearningAgent] Episode 3500 [reward=-514.017544]\n    [QLearningAgent] Episode 4000 [reward=-520.160251]\n    [QLearningAgent] Episode 4500 [reward=-521.000000]\n    [QLearningAgent] Episode 5000 [reward=-502.278958]\n    [QLearningAgent] training ended.\n    tcmalloc: large alloc 1610612736 bytes == 0x56097081e000 @  0x7f6061e811e7 0x56074fecc062 0x56074fef0569 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074fef44c6 0x56074feecd5a 0x56074fef486e 0x56074fef44c6\n    Pacman emerges victorious! Score: 1076\n    Pacman emerges victorious! Score: 889\n    Pacman emerges victorious! Score: 1373\n    Pacman died! Score: -203\n    Pacman died! Score: 736\n    Pacman died! Score: 46\n    Pacman died! Score: 125\n    Pacman died! Score: -104\n    Pacman died! Score: 270\n    Pacman died! Score: -52\n    Average Score: 415.6\n    Scores:        1076.0, 889.0, 1373.0, -203.0, 736.0, 46.0, 125.0, -104.0, 270.0, -52.0\n    Win Rate:      3/10 (0.30)\n    Record:        Win, Win, Win, Loss, Loss, Loss, Loss, Loss, Loss, Loss\n    CPU times: user 2.11 s, sys: 385 ms, total: 2.49 s\n    Wall time: 17min 20s\n\n\n#### Evaluation\n\n\n```\nplot_results(Config.rl.small_maze.checkpoint)\n```\n\n### Medium Classic Maze\n\n#### Training\n\n\n```\n%%time\n\ntrain_rl(\n  'mediumClassic',\n  Config.rl.medium_maze.checkpoint,\n  Config.rl.medium_maze.episodes,\n  Config.rl.medium_maze.tests\n)\n```\n\n    [QLearningAgent] training for 2000 games\n    [QLearningAgent] Episode 200 [reward=-518.785430]\n    [QLearningAgent] Episode 400 [reward=-511.000000]\n    [QLearningAgent] Episode 600 [reward=-511.068030]\n    [QLearningAgent] Episode 800 [reward=-519.000000]\n    [QLearningAgent] Episode 1000 [reward=-501.879183]\n    [QLearningAgent] Episode 1200 [reward=-519.638034]\n    [QLearningAgent] Episode 1400 [reward=-513.692308]\n    [QLearningAgent] Episode 1600 [reward=-518.785430]\n    [QLearningAgent] Episode 1800 [reward=-502.820006]\n    [QLearningAgent] Episode 2000 [reward=-513.508636]\n    [QLearningAgent] training ended.\n    [QLearningAgent] saving weights to /content/drive/MyDrive/datasets/MO444/assignment-3/checkpoints/rl/medium\n    tcmalloc: large alloc 1610612736 bytes == 0x55e4e7c86000 @  0x7fdfbdb481e7 0x55e321f38062 0x55e321f5c569 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6 0x55e321f604c6\n    Pacman died! Score: 827\n    Pacman emerges victorious! Score: 1189\n    Pacman emerges victorious! Score: 1771\n    Pacman emerges victorious! Score: 1456\n    Pacman emerges victorious! Score: 1847\n    Pacman emerges victorious! Score: 1190\n    Pacman emerges victorious! Score: 1098\n    Pacman died! Score: -93\n    Pacman died! Score: -70\n    Pacman died! Score: 838\n    Average Score: 1005.3\n    Scores:        827.0, 1189.0, 1771.0, 1456.0, 1847.0, 1190.0, 1098.0, -93.0, -70.0, 838.0\n    Win Rate:      6/10 (0.60)\n    Record:        Loss, Win, Win, Win, Win, Win, Win, Loss, Loss, Loss\n    CPU times: user 2.02 s, sys: 286 ms, total: 2.31 s\n    Wall time: 14min 33s\n\n\n#### Evaluation\n\n\n```\nplot_results(Config.rl.medium_maze.checkpoint)\n```\n\n### Original Classic Maze\n\n#### Training\n\n\n```\n%%time\n\ntrain_rl(\n  'originalClassic',\n  Config.rl.original_maze.checkpoint,\n  Config.rl.original_maze.episodes,\n  Config.rl.original_maze.tests\n)\n```\n\n    [QLearningAgent] training for 1000 games\n    [QLearningAgent] Episode 100 [reward=-510.699089]\n    [QLearningAgent] Episode 200 [reward=-508.635554]\n    [QLearningAgent] Episode 300 [reward=-509.964241]\n    [QLearningAgent] Episode 400 [reward=-510.818919]\n    [QLearningAgent] Episode 500 [reward=-498.224233]\n    [QLearningAgent] Episode 600 [reward=-502.598713]\n    [QLearningAgent] Episode 700 [reward=-509.082450]\n    [QLearningAgent] Episode 800 [reward=-524.001078]\n    [QLearningAgent] Episode 900 [reward=-517.881966]\n    [QLearningAgent] Episode 1000 [reward=-454.714568]\n    [QLearningAgent] training ended.\n    [QLearningAgent] saving weights to /content/drive/MyDrive/datasets/MO444/assignment-3/checkpoints/rl/original\n    tcmalloc: large alloc 1610612736 bytes == 0x563184e8e000 @  0x7fca550ca1e7 0x562e29a47062 0x562e29a6b569 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a6f4c6 0x562e29a67d5a\n    Pacman died! Score: 1145\n    Pacman died! Score: 1329\n    Pacman emerges victorious! Score: 2943\n    Pacman died! Score: 835\n    Pacman died! Score: 1189\n    Pacman died! Score: 1186\n    Pacman died! Score: 985\n    Pacman died! Score: 1625\n    Pacman died! Score: -113\n    Pacman died! Score: 1495\n    Average Score: 1261.9\n    Scores:        1145.0, 1329.0, 2943.0, 835.0, 1189.0, 1186.0, 985.0, 1625.0, -113.0, 1495.0\n    Win Rate:      1/10 (0.10)\n    Record:        Loss, Loss, Win, Loss, Loss, Loss, Loss, Loss, Loss, Loss\n    CPU times: user 5.92 s, sys: 868 ms, total: 6.78 s\n    Wall time: 41min 51s\n\n\n#### Evaluation\n\n\n```\nplot_results(Config.rl.original_maze.checkpoint)\n```\n\n## Discussions\n\n### Evolutionary Agent\n\n* Small Classic Maze: During training, the solution candidate --- the highest scoring individual, with score of 510.2 --- was found around generation 22 (6,000th iteration of the game), and retained until end of evolution procedure.\n\n  It is noticible, from the evolution graph over the Small Maze, that the score of the average individual  will stabilize after the 40th generation, showing little improvement. The greater variation of minimum score value is due to the constant replacement of the worst individuals during selection phase, replacing those by newborn (and unevaluated) individuals.\n\n  This agent shown a average score of -105 during testing, loosing all of the games, but achieving a positive score in 45% of the games.\n\n* Medium Classic Maze: The medium maze is considerably bigger than than the Small Maze, allowing for a higher number of states and positions ocupied by Pacman and the ghosts. As such, the game history is considerably longer, inducing a higher memory footprint for the whole program.\nWe compensate this memory requirement by running fewer iterations of the game (10,000, 50% less than Small Maze).\n\n  The score of the average individual in the population stabilizes after the 30th generation, slighlty below the 200 score threshold. The minimum fittness value in each generation presents an even stronger variation, when compared to the trend found in Small Maze.\n\n  This agent shows an average test score of 125.5, achieving a positive score in 80% of the games.\nNotwithsanding, it still lost all of the games.\n\n* Original Classic Maze: we reduce the number of game iterations for the Original Classic Maze to 4,600. This number approximately correspond to the maximum number of iterations that can fit into the memory constrains imposed by Colab Pro High-RAM instance (~30 GB), and it was found empirically.\n16 complete generations were evaluated in the process, which took approx. one hour to complete.\n\n  The fittest candidate was found at the 4,595th iteration of the game (10th generation), after which the average score among the individuals seem to stabilize. However, considering that few generations were evaluated, we expect to have better results if higher RAM levels were available.\n\n  The best individual had a test score of 33.8.\nOnce again, it achieved a positive score in 80% of the games it played, but lost all of them.\n\n### RL Agent\n\n* Small Classic Maze: The agent was trained for 5000 iterations of the game.\n\n  During test, it achieved an average score of 415.6 and a positive score in 7 out of 10 games.\nIt also has won 30% of the games it played.\n\n* Medium Classic Maze: The RL agent was trained for 2,000 iterations of the game over the Medium Classic Maze. Similarly to our Evolutionary Agent, memory constraints prevented us from training for longer periods.\n\n  During testing, the agent played 10 games, achieving an average score of 1005.3 points. The agent obtained a positive score in 70% of the games, and won 60% of them.\n\n* Original Classic Maze: Being the largest map, we were limited to run the game for only 1,000 iterations. The regression line over the average score graph for the RL-based agent show a positive tendency, indicating an overall increase in score during the first 1,000 iterations.\n\n  During testing, 10 games were played and the agent obtained an average score of 1261.9 points. The agent obtained positive scores in 9 out of 10, but won a single game.\n\n## Final Considerations\n\nThe agent based on Reinforcement-Learning consistently showed a better results than the agent based on Genetic Algorithm, by both winning more games and presenting a higher average score in test games.\n\nOur evolutionary solution could be further improved by (a) adding more contextual information (developing more features) into the system; (b) considering non-linear decision functions (more than a single layer); and (c) leveraging a computing instance with higher RAM available. As for our RL solution, we envision that a more compact and digested representation of the world could be beneficial in reducing the size of the q-values table, allowing for more interations to be run and more focused learning to be performed.\n", "meta": {"hexsha": "e1e839227e962d67e953e812c4925a701d793b39", "size": 614752, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "assignment-3/report.ipynb", "max_stars_repo_name": "lucasdavid/unicamp-mo444-machine-learning", "max_stars_repo_head_hexsha": "d44a95ebd015c4eecccac4b57539a8824067b1c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assignment-3/report.ipynb", "max_issues_repo_name": "lucasdavid/unicamp-mo444-machine-learning", "max_issues_repo_head_hexsha": "d44a95ebd015c4eecccac4b57539a8824067b1c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment-3/report.ipynb", "max_forks_repo_name": "lucasdavid/unicamp-mo444-machine-learning", "max_forks_repo_head_hexsha": "d44a95ebd015c4eecccac4b57539a8824067b1c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 614752.0, "max_line_length": 614752, "alphanum_fraction": 0.9223101348, "converted": true, "num_tokens": 19182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746995506106744, "lm_q2_score": 0.08389038698317784, "lm_q1q2_score": 0.024954869645941468}}
{"text": "## Pr\u00e9sentation\n\nTwitter est un r\u00e9seau social permettant aux utilisateurs de publier des informations et communiquer entre eux par le biais de messages, appel\u00e9s tweets, pouvant contenir jusqu'\u00e0 280 caract\u00e8res. Largement utilis\u00e9 aujourd'hui, ce r\u00e9seau peut \u00eatre un outil pour des entreprises qui souhaitent \u00e9valuer l'avis de leurs clients.\n\nDans ce TP, on se met \u00e0 la place d'une compagnie a\u00e9rienne, qui souhaiterait d\u00e9tecter les tweets qui la mentionnent et analyser si ce sont des mentions positives ou n\u00e9gatives, en comparant leur r\u00e9sultat avec les autres compagnies.\n\nLe *preprocessing* est une t\u00e2che cruciale en fouille de donn\u00e9es. Elle permet de transformer les donn\u00e9es brutes en un format adapt\u00e9 \u00e0 l'application de m\u00e9thodes de machine learning.\n\n# INF8111 - Fouille de donn\u00e9es\n\n\n## TP1 Automne 2019 - Preprocessing de tweets pour de l'analyse de sentiments\n\n##### Membres de l'\u00e9quipe:\n\n    - Amine Bellahsen\n    - Abderrahim Khalifa\n    - Hamza Sghir\n\n# I/ Analyse de sentiments (13 Pts)\n\nUsuellement dans la litt\u00e9rature, la t\u00e2che d'extraire le sentiment d'un texte est appel\u00e9 *sentiment analysis*.\nIci pour se faire, nous allons utiliser un mod\u00e8le *bag-of-words* (BoW).\n\n## 1. Installation\n\nPour ce TP, vous aurez besoin des librairies `numpy`, `sklearn` et `scipy` (que vous avez sans doute d\u00e9j\u00e0), ainsi que la librairie `nltk`, qui est une libraire utilis\u00e9e pour faire du traitement du language (Natural Language Processing, NLP)\n\nInstallez les libraires en question et ex\u00e9cutez le code ci-dessous :\n\n\n```python\n# If you want, you can use anaconda and install after nltk library\n# !pip install --user numpy\n# !pip install --user sklearn\n# !pip install --user scipy\n# !pip install --user nltk\n\nimport sys\nimport nltk\nnltk.download(\"punkt\")\nnltk.download(\"stopwords\")\nnltk.download(\"averaged_perceptron_tagger\")\nnltk.download(\"universal_tagset\")\nnltk.download('words')\n\n```\n\n    [nltk_data] Downloading package punkt to /home/aminebe/nltk_data...\n    [nltk_data]   Package punkt is already up-to-date!\n    [nltk_data] Downloading package stopwords to\n    [nltk_data]     /home/aminebe/nltk_data...\n    [nltk_data]   Package stopwords is already up-to-date!\n    [nltk_data] Downloading package averaged_perceptron_tagger to\n    [nltk_data]     /home/aminebe/nltk_data...\n    [nltk_data]   Package averaged_perceptron_tagger is already up-to-\n    [nltk_data]       date!\n    [nltk_data] Downloading package universal_tagset to\n    [nltk_data]     /home/aminebe/nltk_data...\n    [nltk_data]   Package universal_tagset is already up-to-date!\n    [nltk_data] Downloading package words to /home/aminebe/nltk_data...\n    [nltk_data]   Package words is already up-to-date!\n\n\n\n\n\n    True\n\n\n\n## 2. Jeu de donn\u00e9es\n\nOn utilise un jeu de donn\u00e9e provenant de *Crowdflower's Data for Everyone library*: https://www.figure-eight.com/data-for-everyone/\n\nPour citer la source originale de la base :\n\n    A sentiment analysis job about the problems of each major U.S. airline. Twitter data was scraped from February of 2015 and contributors were asked to first classify positive, negative, and neutral tweets, followed by categorizing negative reasons (such as \"late flight\" or \"rude service\").\n\nLes compagnies incluses dans cette base de donn\u00e9es sont Virgin America, United Airline, Southwest Airlines, jetBlue, USAirways, et American Airlines.\n\nDans le fichier zip du TP, vous trouverez le fichier *airline_tweets_database.csv*, qui est la base de donn\u00e9es de tweets que nous allons manipuler.\n\nChaque ligne de ce fichier contient un tweet, avec plusieurs informations : l'identifiant du tweet, l'utilisateur, le contenu, le nombre de retweet... Ainsi que le label.\n\n3 labels diff\u00e9rents sont possibles dans ce dataset : *n\u00e9gatif*, *neutre* et *positif*, que l'on va repr\u00e9senter respectivement par 0, 1 et 2.\n\nPour ce TP, on ne va conserver ici que le texte et le label. On divise ensuite la base de donn\u00e9es en 3 ensembles (entrainement/validation/test). Vous utiliserez l'ensemble d'entra\u00eenement et de validation pour cette partie, et l'ensemble de test \u00e0 la partie suivante.\n\nLe code ci-dessous permet de charger ces ensembles:\n\n\n```python\nimport csv\nfrom sklearn.model_selection import train_test_split\n\ndef load_dataset(path):\n    \n    x = []\n    y = []\n\n    with open(path, 'r', newline='', encoding=\"latin-1\") as csvfile:\n        \n        reader = csv.reader(csvfile, delimiter=',')\n        \n        #\u00a0Taking the header of the file + the index of useful columns:\n        header = next(reader)\n        ind_label = header.index('airline_sentiment')\n        ind_text = header.index('text')\n        \n        for row in reader:\n            x.append(row[ind_text])\n            \n            label = row[ind_label]\n            \n            if label == \"negative\":\n                y.append(0)\n            elif label == \"neutral\":\n                y.append(1)\n            elif label == \"positive\":\n                y.append(2)\n\n        assert len(x) == len(y)\n\n        return x, y\n\n\n# Path of the dataset\npath = \"data/airline_tweets_database.csv\"\n\nX, y = load_dataset(path)\n\ntrain_valid_X, test_X, train_valid_Y, test_Y = train_test_split(X, y, test_size=0.15, random_state=12)\n\ntrain_X, valid_X, train_Y, valid_Y = train_test_split(train_valid_X, train_valid_Y, test_size=0.18, random_state=12)\n\nprint(\"Length of training set : \", len(train_X))\nprint(\"Length of validation set : \", len(valid_X))\nprint(\"Length of test set : \", len(test_X))\n\n```\n\n    Length of training set :  10204\n    Length of validation set :  2240\n    Length of test set :  2196\n\n\n## 3. Preprocessing\n\nNous allons ici impl\u00e9menter la *tokenization* et le *stemming*, qui sont 2 \u00e9tapes courantes de preprocessing en NLP. Ensuite, afin d'avoir un mod\u00e8le qui s'adapte mieux au format de Twitter, nous ajouterons une \u00e9tape sp\u00e9cifique suppl\u00e9mentaire.\n\n### 3.1. Tokenization\n\nCette \u00e9tape permet de s\u00e9parer un texte en s\u00e9quence de *tokens* (= jetons, ici des mots, symboles ou ponctuation).\n\nPar exemple la phrase *\"It's the student's notebook.\"* peut \u00eatre s\u00e9par\u00e9 en liste de tokens de cette mani\u00e8re: [\"it\", \" 's\", \"the\", \"student\", \" 's\", \"notebook\", \".\"].\n\n**De plus, tous les tokenizers ont \u00e9galement le r\u00f4le de mettre le texte en minuscule.**\n\n\n##### Question 1. Impl\u00e9mentez les 2 tokenizers diff\u00e9rents suivants: (0.5 Pts)\n\n- Le **SpaceTokenizer**, qui est un tokenizer na\u00eff qui s\u00e9pare simplement en fonction des espaces.\n- Le **NLTKTokenizer**, qui utilise la m\u00e9thode du package *nltk* (https://www.nltk.org/api/nltk.html).\n\n\n\n```python\nfrom nltk.tokenize import TweetTokenizer\n\nclass SpaceTokenizer(object):\n    \"\"\"\n    It tokenizes the tokens that are separated by whitespace (space, tab, newline). \n    We consider that any tokenization was applied in the text when we use this tokenizer.\n\n    For example: \"hello\\tworld of\\nNLP\" is split in ['hello', 'world', 'of', 'NLP']\n    \"\"\"\n\n    def tokenize(self, text):\n        # Have to return a list of tokens\n        tokens = text.split()\n        return tokens\n\n\nclass NLTKTokenizer(object):\n    \"\"\"\n    This tokenizer uses the default function of nltk package (https://www.nltk.org/api/nltk.html) to tokenize the text.\n    \"\"\"\n\n    def tokenize(self, text):\n        # Have to return a list of tokens\n        tokens = nltk.tokenize.word_tokenize(text)\n        return tokens\n\n```\n\n#### Testez les deux tokenizers. Quelles diff\u00e9rences pouvez-vous constater?\n\n\n```python\ntext = \"It's the student's notebook.\"\n\nprint(\"Testing with SpaceTokenizer\")\nspaceTokenizer = SpaceTokenizer()\nprint(spaceTokenizer.tokenize(text))\n\nprint(\"\\n\")\n\nprint(\"Testing with NLTKTokenizer\")\nnltkTokenizer = NLTKTokenizer()\nprint(nltkTokenizer.tokenize(text))\n```\n\n    Testing with SpaceTokenizer\n    [\"It's\", 'the', \"student's\", 'notebook.']\n    \n    \n    Testing with NLTKTokenizer\n    ['It', \"'s\", 'the', 'student', \"'s\", 'notebook', '.']\n\n\n### 3.2. Troncature (ou Stemming)\n\nDans les phrases \"I should have bought a new shoes today\" et \"I spent too much money buying games\", les mots \"buying\" et \"bought\" repr\u00e9sentent la m\u00eame id\u00e9e. Consid\u00e9rer ces deux mots comme diff\u00e9rents ne ferait qu'augmenter pour rien la complexit\u00e9 et la dimension du probl\u00e8me, ce qui peut avoir un impact n\u00e9gatif sur la performance globale. Ainsi, on peut donc plut\u00f4t une forme unique (comme la racine du mot) pour repr\u00e9senter ces deux mots de la m\u00eame mani\u00e8re. Ce proc\u00e9d\u00e9 de conversion de mots en racines permettant de r\u00e9duire la dimension est appel\u00e9 usuellement *stemming*, que l'on peut traduire par troncature.\n\n\n#### Question 2. R\u00e9cup\u00e9rez les troncatures des tokens en utilisant l'attribut *stemmer* de la classe *Stemmer* (0.5 Pts) \n\n\n```python\nfrom nltk.stem.snowball import SnowballStemmer\n\n\nclass Stemmer(object):\n\n    def __init__(self):\n        self.stemmer = SnowballStemmer(\"english\", ignore_stopwords=True)\n\n    def stem(self, token):\n        \"\"\"\n        token: a string that contain a token\n        \"\"\"\n        # Have to return the stemmed token\n        return list(map(self.stemmer.stem,token))\n\n```\n\n\n```python\nstemmer = Stemmer()\nprint(stemmer.stem([\"buying\", \"doing\"]))\n```\n\n    ['buy', 'doing']\n\n\n### 3.3. Twitter preprocessing\n\nParfois, appliquer uniquement ces deux \u00e9tapes ne suffit pas, due aux particularit\u00e9s des donn\u00e9es que nous manipulons, qui peuvent demander des \u00e9tapes de preprocessing sp\u00e9cifiques afin d'obtenir un mod\u00e8le plus adapt\u00e9.\n\nCouramment en NLP, un dictionnaire est utilis\u00e9 pour stocker un ensemble de mots, et tous les mots n'appartenant pas au dictionnaire sont consid\u00e9r\u00e9s comme inconnus. Ainsi, avec ce choix d'impl\u00e9mentation, la dimension de l'espace caract\u00e9ristique du mod\u00e8le est directement li\u00e9e au nombre de mots du dictionnaire. Ainsi, pour des raisons de complexit\u00e9 mais aussi car les mod\u00e8les \u00e0 trop grande dimension peuvent souffrir du fl\u00e9au de la dimensionnalit\u00e9, il est pr\u00e9f\u00e9rable de r\u00e9duire la taille de notre vocabulaire.\n\n#### Question 3. Donnez, en expliquant bri\u00e8vement, au moins deux exemples d'\u00e9tapes de pr\u00e9processing qui permettent de r\u00e9duire la taille du dictionnaire ici, puis impl\u00e9mentez-les.  (2.0 points)\n\nCes \u00e9tapes de pr\u00e9processing doivent \u00eatre en rapport aux charact\u00e9ristiques sp\u00e9cifiques des donn\u00e9es de Twitter. La suppression des mots vides ne compte pas comme une des deux \u00e9tapes.\n\nL'etape du preprocessing est une \u00e9tape crutial pour le developement d'un modele assez puissant. On propose ici quelques traitements qu'on efectuera sur les tweet afin de reduire le vocabulaire et supprimer les tokens qui ne servent pas \u00e0 notre problematique:\n\n- **Remplacer les URL par un token:** les url sur twitter sont tous reduit vers un lien t.co qui ne donnent pas generalement aucune id\u00e9e sur le contenu du tweet. On replace tous les url dans les tweet par le token `__URL__`\n\n- **Remplacer les nombres par un token:** Un nombre ne permet pas dans un model BoW de savoir c'est quoi la nature du tweet sauf si on le met dans un context en specifiant l'unit\u00e9e par exemple. On replace tous les nombre dans les tweet par le token `__NBR__`\n\n- **Remplacer les TAGs par un token:** Lorsqu'on tag quelqu'un sur un tweet cela ne serve pas beaucoup \u00e0 savoir l'emotion qu'on exprime. On replace tous les TAG ( les token qui commencent par @) dans les tweet par le token `__UNAME__`\n\n- **Enlever les # des hashtags:** On va considerer les hashtags comme des mots.\n\n- **Traiter les emojis**: Il s'agit ici de classifer les emojis, au moins les plus utilis\u00e9s, selon deux categories: positives et negatives. Ceci permettra d'avoir une id\u00e9e sur le type d'emotion exprim\u00e9 dans le tweet, en remplacant soit par `EMO_POS` qui signifie emotion positive ou `EMO_NEG` qui signifie emotion negative. le code pour ce traitement on l'a depuis ce [lien](https://github.com/abdulfatir/twitter-sentiment-analysis/blob/master/code/preprocess.py?fbclid=IwAR2D44a0pwGWAhxsUVP0Gvr9EpRqd11qAgBXyfpp796mkCJPDXRraPurfu8).\n\n\n```python\nimport string\nimport re\n```\n\n\n```python\nclass TwitterPreprocessing(object):\n\n    def handle_urls(self, tweet):\n        tweet = re.sub(r'(https:|http:)?\\/\\/t.co\\/[a-zA-Z0-9]+', ' __URL__ ', tweet)\n        return tweet\n    \n    def handle_numbers(self, tweet):\n        tweet = re.sub(r'\\b\\d+\\b', ' __NBR__ ', tweet)\n        return tweet\n        \n    def handle_tags(self, tweet):\n        tweet = re.sub(r'@\\S+', ' __UNAME__ ', tweet)\n        return tweet\n    \n    def handle_hashtags(self, tweet):\n        tweet = re.sub(r'#(\\S+)', r'\\1', tweet)\n        return tweet\n\n    def handle_and(self, tweet):\n        return tweet.replace(\"&amp;\", \"&\")\n    \n    def handle_emojis(self, tweet):\n        # taken from https://github.com/abdulfatir/twitter-sentiment-analysis/blob/master/code/preprocess.py\n        # Smile --\n        tweet = re.sub(r'(:-\\)|\\(-:|:\\'\\))', ' __EMO_POS__ ', tweet)\n        # Laugh -- \n        tweet = re.sub(r'(:-?D|x-?D|X-?D)', ' __EMO_POS__ ', tweet)\n        # Love -- \n        tweet = re.sub(r'(<3|:\\*)', ' __EMO_POS__ ', tweet)\n        # Wink -- \n        tweet = re.sub(r'(;-?\\)|;-?D|\\(-?;)', ' __EMO_POS__ ', tweet)\n        # Sad -- \n        tweet = re.sub(r'(:-\\(|\\)-:)', ' __EMO_NEG__ ', tweet)\n        # Sad 2 -- \n        tweet = re.sub(r'(:\\/|:-\\/)', ' __EMO_NEG__ ', tweet)\n        # Cry -- \n        tweet = re.sub(r'(:,\\(|:\\'\\(|:\"\\()', ' __EMO_NEG__ ', tweet)\n        return tweet\n\n    def preprocess(self,data):\n        \n        data=self.handle_urls(data)\n        data=self.handle_emojis(data)\n        data=self.handle_tags(data)\n        data=self.handle_hashtags(data)\n        data=self.handle_and(data)\n        # remove single letters and some repeated punctuation\n        data = re.sub(r'\\b[-\\']\\b', '', data)\n        data = re.sub(r'\\b\\w\\b', '', data)\n        data = re.sub(r'[\\?\\'\\.]{2,}', ' ', data)\n        # remove encoding chars\n        data = data.encode(\"cp1251\",\"ignore\").decode(\"utf8\")\n        return data\n```\n\n\n```python\n# test\ntext = \"Hello world \\x8f this is my first &amp; tweet 2019!poke @Hamza0, @Amine #LetsMakePolyGreatAgain :D ;) :-) :-D :-/ :/ meet us @ //t.co/kbb0B5FxMK https://t.co/gooNdg00Poly\"\ntweet_prep = TwitterPreprocessing()\ntweet_prep.preprocess(text)\n```\n\n\n\n\n    'Hello world  this is my first & tweet 2019!poke  __UNAME__   __UNAME__  LetsMakePolyGreatAgain  __EMO_POS__   __EMO_POS__   __EMO_POS__   __EMO_POS__   __EMO_NEG__   __EMO_NEG__  meet us @  __URL__   __URL__ '\n\n\n\nd'autres traitements peuvent \u00eatre envisag\u00e9s comme le traitement des ponctuations et les espaces.\n\n### 3.4.  Pipeline\n\nUne pipeline permet d'ex\u00e9cuter s\u00e9quentiellement toutes les \u00e9tapes de preprocessing, pour transformer les donn\u00e9es brutes en une version utilisable pour notre mod\u00e8le. La *PreprocessingPipeline* a \u00e9t\u00e9 impl\u00e9menter pour appliquer \u00e0 la suite le tokenizer, les troncatures et le preprocessing sp\u00e9cifique \u00e0 Twitter. \n\n**N'h\u00e9sitez pas \u00e0 changer l'ordre des \u00e9tapes de preprocessing si vous le souhaitez.**\n\n\n```python\nclass PreprocessingPipeline:\n\n    def __init__(self, tokenization, twitterPreprocessing, stemming):\n        \"\"\"\n        tokenization: enable or disable tokenization.\n        twitterPreprocessing: enable or disable twitter preprocessing.\n        stemming: enable or disable stemming.\n        \"\"\"\n\n        self.tokenizer = NLTKTokenizer() if tokenization else SpaceTokenizer()\n        self.twitterPreprocesser = TwitterPreprocessing(\n        ) if twitterPreprocessing else None\n        self.stemmer = Stemmer() if stemming else None\n\n    def preprocess(self, tweet):\n        \"\"\"\n        Transform the raw data\n\n        tokenization: boolean value.\n        twitterPreprocessing: boolean value. Apply the\n        stemming: boolean value.\n        \"\"\"\n        if self.twitterPreprocesser:\n            tweet_processed = self.twitterPreprocesser.preprocess(tweet)\n        else:\n            tweet_processed = tweet\n        \n        tokens = self.tokenizer.tokenize(tweet_processed)\n        if self.stemmer:\n            tokens = self.stemmer.stem(tokens)\n        return tokens\n\n```\n\nTest de la pipeline :\n\n\n```python\nprint(\"initial tweet:\",train_X[:1])\npipeline = PreprocessingPipeline(tokenization=True, twitterPreprocessing=True, stemming=True)\nprint(\"results:\")\nprint(list(map(pipeline.preprocess, train_X[:1])))\n```\n\n    initial tweet: ['@USAirways tells me to talk to @AmericanAir about my delayed flights. AA tells me to talk to US. #ihatemergers']\n    results:\n    [['__uname__', 'tell', 'me', 'to', 'talk', 'to', '__uname__', 'about', 'my', 'delay', 'flight', '.', 'aa', 'tell', 'me', 'to', 'talk', 'to', 'us', '.', 'ihatemerg']]\n\n\n## 4. N-grams\n\nUn n-gram est une s\u00e9quence continue de *n* tokens dans un texte. Par exemple, les s\u00e9quences *\"nous a\"* et *\"la porte\"* sont deux exemples de 2-grams de la phrase *\"Il nous a dit au revoir en franchissant la porte.\"*. 1-gram, 2-gram et 3-gram sont respectivement appel\u00e9s unigram, bigram et trigram. \n\nVoici la liste de tous les unigrams, bigrams et trigrams possible pour la phrase *\"Il nous a dit au revoir en franchissant la porte.\"* :\n- Unigram: ['Il', 'nous', 'a', 'dit', 'au', 'revoir', 'en', 'franchissant', 'la', 'porte']\n- Bigram: ['Il nous', 'nous a', 'a dit', 'dit au', 'au revoir', 'revoir en', 'en franchissant', 'franchissant la', 'la porte']\n- Trigram: ['Il nous a', 'nous a dit', 'a dit au', 'dit au revoir', 'au revoir en', 'revoir en franchissant', 'en franchissant la', 'franchissant la porte']\n\n\n##### Question 4. Implementez les fonctions `bigram` et `trigram`. (1 Pt)\n\nVous devez r\u00e9soudre cette question sans utiliser de libraire exterieur comme scikit-learn par exemple.\n\n\n```python\ndef bigram(tokens):\n    \"\"\"\n    tokens: a list of strings\n    \"\"\"\n    bigrams = []\n    for words in zip(tokens[:-1],tokens[1:]):\n        bigrams.append(\" \".join(words))\n    # This function returns the list of bigrams\n    return bigrams\n\n\ndef trigram(tokens):\n    \"\"\"\n    tokens: a list of strings\n    \"\"\"\n    trigrams = []\n    for words in zip(tokens[:-2],tokens[1:-1], tokens[2:]):\n        trigrams.append(\" \".join(words))\n    # This function returns the list of trigrams\n    return trigrams\n\n```\n\n\n```python\ntext = \"He does not know what he is talking about\"\nnltktokenizer = NLTKTokenizer()\ntokens = nltktokenizer.tokenize(text)\nprint('Liste des bigrams :'+\"\\n\")\nprint('Bigrams =', bigram(tokens))\nprint('\\n')\nprint('Liste des trigrams :'+\"\\n\")\nprint('Trigrams = ', trigram(tokens))\n```\n\n    Liste des bigrams :\n    \n    Bigrams = ['He does', 'does not', 'not know', 'know what', 'what he', 'he is', 'is talking', 'talking about']\n    \n    \n    Liste des trigrams :\n    \n    Trigrams =  ['He does not', 'does not know', 'not know what', 'know what he', 'what he is', 'he is talking', 'is talking about']\n\n\n## 5. Bag-of-words\n\nR\u00e9gressions logistiques, SVM et d'autres mod\u00e8les tr\u00e8s courants demande des entr\u00e9es qui soient toutes de la m\u00eame taille, ce qui n'est forc\u00e9ment le cas pour des types de donn\u00e9es comme les textes, qui peuvent avoir un nombre variable de mots.  \n\nPar exemple, consid\u00e9rons la phrase 1, \u201dBoard games are much better than video games\u201d et la phrase 2, \u201dPandemic is an awesome game!\u201d. La table ci-dessous montre un exemple d'un moyen de repr\u00e9sentation de ces deux phrases en utilisant une repr\u00e9sentation fixe : \n\n|<i></i>     | an | are | ! | pandemic | awesome | better | games | than | video | much | board | is | game |\n|------------|----|-----|---|----------|---------|--------|-------|------|-------|------|-------|----|------|\n| Sentence 1 | 0  | 1   | 0 | 0        | 0       | 1      | 2     | 1    | 1     | 1    | 1     | 0  | 0    |\n| Sentence 2 | 1  | 0   | 0 | 1        | 1       | 0      | 0     | 0    | 0     | 0    | 0     | 1  | 1    |\n\n\nChaque colonne repr\u00e9sente un mot du vocabulaire (de longueur 13), tandis que chaque ligne contient l'occurence des mots dans une phrase. Ainsi, la valeur 2 \u00e0 la position (1,7) est due au fait que le mot *\"games\"* apparait deux fois dans la phrase 1. \n\nAinsi, chaque ligne \u00e9tant de longueur 13, on peut les utiliser comme vecteur pour repr\u00e9senter les phrases 1 et 2. Ainsi, c'est cette m\u00e9thode que l'on appelle *Bag-of-Words* : c'est une repr\u00e9sentation de documents par des vecteurs dont la dimension est \u00e9gale \u00e0 la taille du vocabulaire, et qui est construit en comptant le nombre d'occurence de chaque mot. Ainsi, chaque token est ici associ\u00e9 \u00e0 une dimension.\n\n\n##### Question 5. Impl\u00e9mentez le Bag-of-Words (2 Pts)\n\nPour cette question, vous ne pouvez pas utiliser de librairie Python externe comme scikit-learn, hormis si vous avez des probl\u00e8mes de m\u00e9moire, vous pouvez utiliser la classe sparse.csr_matrix de scipy (https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csc_matrix.html).\n\n\n```python\n# no need for the csr_matrix if we use an np.int8 type \n# (we suppose the tweet are not too long and cannot contain the same token more than 256 times)\nfrom scipy.sparse import csr_matrix\nimport numpy as np\n\nclass CountBoW(object):\n\n    def __init__(self, pipeline, bigram=False, trigram=False):\n        \"\"\"\n        pipelineObj: instance of PreprocesingPipeline\n        bigram: enable or disable bigram\n        trigram: enable or disable trigram\n        words: list of words in the vocabulary\n        \"\"\"\n        self.pipeline = pipeline\n        self.bigram = bigram\n        self.trigram = trigram\n        self.words = None\n\n        \n    def computeBoW(self, tokens):\n        \"\"\"\n        Calcule du BoW, \u00e0 partir d'un dictionnaire de mots et d'une liste de tweets.\n        On suppose que l'on a d\u00e9j\u00e0 collect\u00e9 le dictionnaire sur l'ensemble d'entra\u00eenement.\n        \n        Entr\u00e9e: tokens, une liste de vecteurs contenant les tweets (une liste de liste)\n        \n        Return: une csr_matrix\n        \"\"\"\n        \n        \n        if self.words is None:\n            raise Exception(\n                \"fit_transform() should be called first (no dictionnary available)\"\n            )\n        \n        word_to_idx = {word:idx for idx,word in enumerate(self.words)}\n        \n        bag_matrix = np.zeros((len(tokens), len(self.words)),dtype=np.int8)\n        \n        for tweet_idx,tweet_tokens in enumerate(tokens):\n            all_tokens = tweet_tokens.copy()\n            if self.bigram == True :\n                all_tokens+=bigram(tweet_tokens)\n            if self.trigram == True :\n                all_tokens+=trigram(tweet_tokens)\n                \n            for token in all_tokens:\n                word_idx = word_to_idx.get(token, -1)\n                if word_idx>=0:\n                    bag_matrix[tweet_idx,word_to_idx[token]] += 1\n        \n        return bag_matrix\n        \n\n    def fit_transform(self, X):\n        \"\"\"\n        Cette m\u00e9thode preprocess les donn\u00e9es en utilisant la pipeline, ajoute les bigram et trigram \n        si besoin, et transforme les textes en vecteurs d'entiers.\n        \n        Entr\u00e9e: X, une liste de vecteurs contenant les tweets\n        \n        Return: une csr_matrix\n        \"\"\"\n        \n        toknized_tweets = list(map(self.pipeline.preprocess, X))\n        words_dictionnary = set()\n        for tweet in toknized_tweets:\n            for token in tweet:\n                words_dictionnary.add(token)\n            if self.bigram == True :\n                for token in bigram(tweet):\n                    words_dictionnary.add(token)\n            if self.trigram == True :\n                for token in trigram(tweet):\n                    words_dictionnary.add(token)\n                    \n        self.words = list(words_dictionnary)\n        \n        return self.computeBoW(toknized_tweets)\n        \n    \n    def transform(self, X):\n        \"\"\"\n        Cette m\u00e9thode preprocess les donn\u00e9es en utilisant la pipeline, ajoute les bigram et trigram \n        si besoin, et transforme les textes en vecteurs d'entiers.\n        Diff\u00e9rence avec fit_transform : on suppose qu'on dispose d\u00e9j\u00e0 du dictionnaire ici\n\n        Entr\u00e9e: X, une liste de vecteurs contenant les tweets\n        Return: une csr_matrix\n        \"\"\"\n        \n        if self.words is None:\n            raise Exception(\n                \"fit_transform() should be called first (no dictionnary available)\"\n            )\n\n        toknized_tweets = list(map(self.pipeline.preprocess, X))\n        return self.computeBoW(toknized_tweets)\n            \n        \n\n```\n\n\n```python\npipeline = PreprocessingPipeline(tokenization=True, twitterPreprocessing=True, stemming=True)\nbow_test=CountBoW(pipeline, bigram=True, trigram=True)\nbow_test.fit_transform(train_X[:2])\n```\n\n\n\n\n    array([[0, 4, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 2, 0, 1, 1, 1, 0, 0,\n            0, 1, 0, 0, 0, 1, 1, 1, 0, 2, 1, 0, 1, 0, 2, 0, 0, 0, 0, 0, 2, 0,\n            0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 2, 2, 0, 1, 0, 0,\n            0, 0, 1, 1, 2, 1, 1, 0, 1, 1, 0, 1, 2, 1, 0, 1, 0, 0, 1, 0, 2, 0,\n            0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, 0, 0, 0,\n            0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0],\n           [1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 2, 1, 1, 0, 1, 0, 0, 0, 1, 1,\n            1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1,\n            1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1,\n            1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1,\n            1, 2, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,\n            1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1]], dtype=int8)\n\n\n\n\n```python\nlist_list= bow_test.transform(train_X[3:5])\nlist_list\n```\n\n\n\n\n    array([[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,\n            0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,\n            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,\n            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n           [0, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,\n            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,\n            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=int8)\n\n\n\n## 6. TF-IDF\n\nL'utilisation de la fr\u00e9quence d'apparition brute des mots, comme c'est le cas avec le bag-of-words, peut \u00eatre probl\u00e9matique. En effet, peu de tokens auront une fr\u00e9quence tr\u00e8s \u00e9lev\u00e9e dans un document, et de ce fait, le poids de ces mots sera beaucoup plus grand que les autres, ce qui aura tendance \u00e0 biaiser l'ensemble des poids. De plus, les mots qui apparaissent dans la plupart des documents n'aident pas \u00e0 les discriminer. Par exemple, le mot \"*de*\" appara\u00eet dans beaucoup de tweets de la base de donn\u00e9es, et pour autant, avoir ce mot en commun ne permet pas de conclure que des tweets sont similaires. Au contraire, le mot \"*g\u00e9nial*\" est plus rare, mais les documents qui contiennent ce mot sont plus susceptibles d'\u00eatre positif. TF-IDF est donc une m\u00e9thode qui permet de pallier \u00e0 ce probl\u00e8me.\n\nTF-IDF pond\u00e8re le vecteur en utilisant une fr\u00e9quence de document inverse (IDF) et une fr\u00e9quence de termes (TF).\n\nTF est l'information locale sur l'importance qu'a un mot dans un document donn\u00e9, tandis que IDF mesure la capacit\u00e9 de discrimination des mots dans un jeu de donn\u00e9es. \n\nL'IDF d'un mot se calcule de la fa\u00e7on suivante:\n\n\\begin{equation}\n\t\\text{idf}_i = \\log\\left( \\frac{N}{\\text{df}_i} \\right),\n\\end{equation}\n\navec $N$ le nombre de documents dans la base de donn\u00e9e, et $\\text{df}_i$ le nombre de documents qui contiennent le mot $i$.\n\nLe nouveau poids $w_{ij}$ d'un mot $i$ dans un document $j$ peut ensuite \u00eatre calcul\u00e9 de la fa\u00e7on suivante:\n\n\\begin{equation}\n\tw_{ij} = \\text{tf}_{ij} \\times \\text{idf}_i,\n\\end{equation}\n\navec $\\text{tf}_{ij}$ la fr\u00e9quence du mot $i$ dans le document $j$.\n\n\n\n\n##### Question 6. Impl\u00e9mentez le bag-of-words avec la pond\u00e9ration de TF-IDF (3 Pts)\n\nPour cette question, vous ne pouvez pas utiliser de librairie Python externe comme scikit-learn, hormis si vous avez des probl\u00e8mes de m\u00e9moire, vous pouvez utiliser la classe sparse.csr_matrix de scipy (https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csc_matrix.html).\n\n\n```python\nfrom scipy.sparse import csr_matrix\nimport math\n\n\nclass TFIDFBoW(object):\n\n    def __init__(self, pipeline, bigram=False, trigram=False):\n        \"\"\"\n        pipelineObj: instance of PreprocesingPipeline\n        bigram: enable or disable bigram\n        trigram: enable or disable trigram\n        words: list of words in the vocabulary\n        idf: list of idfs for each document\n        \"\"\"\n        self.pipeline = pipeline\n        self.bigram = bigram\n        self.trigram = trigram\n        self.words = None\n        self.idf = None\n    \n    def computeTFIDF(self, tokens):\n        \"\"\"\n        Calcule du TF-IDF, \u00e0 partir d'un dictionnaire de mots et d'une \n        liste de tweets.\n        On suppose que l'on a d\u00e9j\u00e0 collect\u00e9 le dictionnaire ainsi que \n        calcul\u00e9 le vecteur contenant l'idf pour chaque document.\n        \n        Entr\u00e9e: tokens, une liste de vecteurs contenant les tweets (une liste de liste)\n        \n        Return: une csr_matrix\n        \"\"\"\n        \n        if self.words is None:\n            raise Exception(\n                \"fit_transform() should be called first (no dictionnary available)\"\n            )\n            \n        word_to_idx = {word:idx for idx,word in enumerate(self.words)}\n        \n        tf = np.zeros((len(tokens), len(self.words)),dtype=np.int8)\n        \n        for tweet_idx,tweet_tokens in enumerate(tokens):\n            all_tokens = tweet_tokens.copy()\n            if self.bigram == True :\n                all_tokens+=bigram(tweet_tokens)\n            if self.bigram == True :\n                all_tokens+=trigram(tweet_tokens)\n                \n            for token in all_tokens:\n                word_idx = word_to_idx.get(token, -1)\n                if word_idx>=0:\n                    tf[tweet_idx,word_to_idx[token]] += 1\n\n        # puisque ce n'est pas specifi\u00e9 on utilise le np.log\n        if self.idf is None:\n            self.idf = np.log(tf.shape[0] / (tf!=0).sum(axis=0))\n        \n        return np.multiply(tf, self.idf)\n\n\n    def fit_transform(self, X):\n        \"\"\"\n        Cette m\u00e9thode preprocess les donn\u00e9es en utilisant la pipeline, ajoute les bigram et trigram \n        si besoin, et transforme les textes en vecteurs de flottants avec la pond\u00e9ration TF-IDF.\n        \n        Entr\u00e9e : X, une liste de vecteurs contenant les tweets\n        \n        Return: une csr_matrix\n        \"\"\"\n        toknized_tweets = list(map(self.pipeline.preprocess, X))\n        words_dictionnary = set()\n        for tweet in toknized_tweets:\n            for token in tweet:\n                words_dictionnary.add(token)\n            if self.bigram == True :\n                for token in bigram(tweet):\n                    words_dictionnary.add(token)\n            if self.trigram == True :\n                for token in trigram(tweet):\n                    words_dictionnary.add(token)\n                    \n        self.words = list(words_dictionnary)\n        return self.computeTFIDF(toknized_tweets)\n    \n    def transform(self, X):\n        \"\"\"\n        Cette m\u00e9thode preprocess les donn\u00e9es en utilisant la pipeline, ajoute les bigram et trigram \n        si besoin, et transforme les textes en vecteurs de flottants avec la pond\u00e9ration TF-IDF.\n        Diff\u00e9rence avec fit_transform : on suppose qu'on dispose d\u00e9j\u00e0 du dictionnaire et du calcul des idf ici.\n            \n        Entr\u00e9e : X, une liste de vecteurs contenant les tweets\n        \n        Return: une csr_matrix\n        \"\"\"\n\n        if self.words is None:\n            raise Exception(\n                \"fit_transform() should be called first (no dictionnary available)\"\n            )\n\n        toknized_tweets = list(map(self.pipeline.preprocess, X))\n        return self.computeTFIDF(toknized_tweets)\n    \n```\n\n\n```python\npipeline = PreprocessingPipeline(tokenization=True, twitterPreprocessing=True, stemming=True)\ntfidf_test=TFIDFBoW(pipeline, bigram=False, trigram=False)\ntfidf_test.fit_transform(train_X[:2])\n```\n\n\n\n\n    array([[0.        , 0.        , 0.        , 1.38629436, 2.77258872,\n            0.69314718, 0.        , 0.        , 0.        , 0.        ,\n            0.        , 0.        , 0.        , 0.69314718, 0.        ,\n            0.        , 0.69314718, 0.        , 0.        , 1.38629436,\n            0.        , 0.        , 0.69314718, 0.        , 0.69314718,\n            0.        , 1.38629436, 0.        , 0.        , 0.        ,\n            0.        , 0.        , 0.69314718, 0.        , 0.        ,\n            0.        , 0.69314718],\n           [0.69314718, 0.69314718, 0.69314718, 0.        , 0.        ,\n            0.        , 0.69314718, 0.69314718, 0.        , 0.        ,\n            0.69314718, 0.69314718, 0.69314718, 0.        , 0.69314718,\n            0.69314718, 0.        , 0.69314718, 0.69314718, 0.        ,\n            1.38629436, 0.69314718, 0.        , 0.69314718, 0.        ,\n            0.69314718, 0.        , 0.69314718, 0.69314718, 1.38629436,\n            0.69314718, 0.69314718, 0.        , 0.69314718, 0.69314718,\n            0.69314718, 0.        ]])\n\n\n\n\n```python\nlist_list= tfidf_test.transform(train_X[3:5])\nlist_list\n```\n\n\n\n\n    array([[0.        , 0.        , 0.        , 0.        , 0.        ,\n            0.        , 0.        , 0.        , 0.        , 0.        ,\n            0.        , 0.        , 0.        , 0.69314718, 0.        ,\n            0.        , 0.        , 0.        , 0.        , 0.        ,\n            0.        , 0.        , 0.        , 0.        , 0.        ,\n            0.        , 0.69314718, 0.        , 0.        , 0.        ,\n            0.        , 0.        , 0.        , 0.        , 0.        ,\n            0.69314718, 0.69314718],\n           [0.        , 0.        , 0.        , 0.        , 2.07944154,\n            0.        , 0.        , 0.        , 0.        , 0.        ,\n            1.38629436, 0.        , 0.        , 0.69314718, 0.        ,\n            0.        , 0.        , 0.        , 0.        , 0.        ,\n            0.        , 0.        , 0.        , 0.        , 0.        ,\n            0.        , 0.69314718, 0.        , 0.        , 0.        ,\n            0.        , 0.        , 0.        , 0.        , 0.        ,\n            0.        , 0.        ]])\n\n\n\n## 7. Classification utilisant BoW\n\nPour la classification, nous allons effectuer une r\u00e9gression logisitique (vu en cours ou que vous allez voir bient\u00f4t). \nPour en savoir plus : https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html\n\nLa m\u00e9thode `train_evaluate` entra\u00eene et \u00e9value le mod\u00e8le de r\u00e9gression logistique.\n\n\n\n```python\nimport numpy as np\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.linear_model import LogisticRegression\n\n\ndef train_evaluate(training_X, training_Y, validation_X, validation_Y, bowObj):\n    \"\"\"\n    training_X: tweets from the training dataset\n    training_Y: tweet labels from the training dataset\n    validation_X: tweets from the validation dataset\n    validation_Y: tweet labels from the validation dataset\n    bowObj: Bag-of-word object\n    \n    :return: the classifier and its accuracy in the training and validation dataset.\n    \"\"\"\n\n    classifier = LogisticRegression(n_jobs=-1)\n\n    training_rep = bowObj.fit_transform(training_X)\n    print(\"- Taille du dictionnaire:\",len(bowObj.words))\n    classifier.fit(training_rep, training_Y)\n\n    trainAcc = accuracy_score(training_Y, classifier.predict(training_rep))\n    validationAcc = accuracy_score(\n        validation_Y, classifier.predict(bowObj.transform(validation_X)))\n    \n    print(f\"- Training accuracy: {trainAcc:.5f}\")\n    print(f\"- Validation accuracy: {validationAcc:.5f}\")\n    return classifier, trainAcc, validationAcc\n\n```\n\n\n##### Question 7. Entra\u00eenez et calculez la pr\u00e9cision de la r\u00e9gression logistique sur les ensembles d'entra\u00eenement et de validation. (4 points)\n\nEssayez les configurations suivantes :\n\n    1. CountBoW + SpaceTokenizer(without tokenizer) + unigram \n    2. CountBoW + NLTKTokenizer + unigram\n    3. TFIDFBoW + NLTKTokenizer + Stemming + unigram\n    4. TFIDFBoW + NLTKTokenizer + Twitter preprocessing + Stemming  + unigram\n    5. TFIDFBoW + NLTKTokenizer + Twitter preprocessing + Stemming  + unigram + bigram\n    6. TFIDFBoW + NLTKTokenizer + Twitter preprocessing + Stemming  + unigram + bigram + trigram\n\nOutre la pr\u00e9cision, reportez la taille du dictionnaire pour chacune des configurations. Enfin, d\u00e9crivez vos r\u00e9sultats obtenus et r\u00e9pondez aux questions suivantes:\n- Quelles \u00e9tapes de preprocessing ont effectivement aid\u00e9 le mod\u00e8le ? Pourquoi ?\n- La pond\u00e9ration avec TF-IDF a-t-elle aid\u00e9 \u00e0 obtenir une meilleure performance que le simple BoW ?\n- Les bigrams et trigrams ont-ils am\u00e9lior\u00e9 la performance ? Expliquez pourquoi.\n\nIndiquez quelle est la configuration que vous choisissez.\n\n\n```python\nconfigurations = [\n    {\"model\":CountBoW, \"tokenize\":False},\n    {\"model\":CountBoW, \"tokenize\":True},\n    {\"model\":TFIDFBoW, \"tokenize\":True, \"stemming\": True},\n    {\"model\":TFIDFBoW, \"tokenize\":True, \"stemming\": True, \"preprocess\":True},\n    {\"model\":TFIDFBoW, \"tokenize\":True, \"stemming\": True, \"preprocess\":True, \"bi\":True},\n    {\"model\":TFIDFBoW, \"tokenize\":True, \"stemming\": True, \"preprocess\":True, \"bi\":True,\"tri\":True}\n]\n\nresults = []\nfor i,conf in enumerate(configurations):\n    print(f\"[+] Running configuration {i+1}...\")\n    stemming = conf.get(\"stemming\",False)\n    tw_prep = conf.get(\"preprocess\",False)\n    tokenize = conf.get(\"tokenize\",False)\n    \n    pipeline = PreprocessingPipeline(tokenization = tokenize, twitterPreprocessing = tw_prep, stemming = stemming)\n    obj = conf[\"model\"](pipeline, bigram = conf.get(\"bi\",False), trigram = conf.get(\"tri\",False))\n    results.append(train_evaluate(train_X, train_Y, train_valid_X, train_valid_Y, obj))\n\n#- Taille du dictionnaire: 11064\n#- Training accuracy: 0.98844\n#- Validation accuracy: 0.94873\n```\n\n    [+] Running configuration 1...\n    - Taille du dictionnaire: 23071\n\n\n    //anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.\n      FutureWarning)\n    //anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:469: FutureWarning: Default multi_class will be changed to 'auto' in 0.22. Specify the multi_class option to silence this warning.\n      \"this warning.\", FutureWarning)\n    //anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:1544: UserWarning: 'n_jobs' > 1 does not have any effect when 'solver' is set to 'liblinear'. Got 'n_jobs' = 4.\n      \" = {}.\".format(effective_n_jobs(self.n_jobs)))\n\n\n    - Training accuracy: 0.96139\n    - Validation accuracy: 0.93161\n    [+] Running configuration 2...\n    - Taille du dictionnaire: 15540\n\n\n    //anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.\n      FutureWarning)\n    //anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:469: FutureWarning: Default multi_class will be changed to 'auto' in 0.22. Specify the multi_class option to silence this warning.\n      \"this warning.\", FutureWarning)\n    //anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:1544: UserWarning: 'n_jobs' > 1 does not have any effect when 'solver' is set to 'liblinear'. Got 'n_jobs' = 4.\n      \" = {}.\".format(effective_n_jobs(self.n_jobs)))\n\n\n    - Training accuracy: 0.94277\n    - Validation accuracy: 0.91763\n    [+] Running configuration 3...\n    - Taille du dictionnaire: 11064\n\n\n    //anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.\n      FutureWarning)\n    //anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:469: FutureWarning: Default multi_class will be changed to 'auto' in 0.22. Specify the multi_class option to silence this warning.\n      \"this warning.\", FutureWarning)\n    //anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:1544: UserWarning: 'n_jobs' > 1 does not have any effect when 'solver' is set to 'liblinear'. Got 'n_jobs' = 4.\n      \" = {}.\".format(effective_n_jobs(self.n_jobs)))\n\n\n    - Training accuracy: 0.98844\n    - Validation accuracy: 0.94873\n    [+] Running configuration 4...\n    - Taille du dictionnaire: 9282\n\n\n    //anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.\n      FutureWarning)\n    //anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:469: FutureWarning: Default multi_class will be changed to 'auto' in 0.22. Specify the multi_class option to silence this warning.\n      \"this warning.\", FutureWarning)\n    //anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:1544: UserWarning: 'n_jobs' > 1 does not have any effect when 'solver' is set to 'liblinear'. Got 'n_jobs' = 4.\n      \" = {}.\".format(effective_n_jobs(self.n_jobs)))\n\n\n    - Training accuracy: 0.98256\n    - Validation accuracy: 0.94511\n    [+] Running configuration 5...\n    - Taille du dictionnaire: 79244\n\n\n    //anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.\n      FutureWarning)\n    //anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:469: FutureWarning: Default multi_class will be changed to 'auto' in 0.22. Specify the multi_class option to silence this warning.\n      \"this warning.\", FutureWarning)\n    //anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:1544: UserWarning: 'n_jobs' > 1 does not have any effect when 'solver' is set to 'liblinear'. Got 'n_jobs' = 4.\n      \" = {}.\".format(effective_n_jobs(self.n_jobs)))\n\n\n    - Training accuracy: 0.99647\n    - Validation accuracy: 0.96255\n    [+] Running configuration 6...\n    - Taille du dictionnaire: 211105\n\n\n    //anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.\n      FutureWarning)\n    //anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:469: FutureWarning: Default multi_class will be changed to 'auto' in 0.22. Specify the multi_class option to silence this warning.\n      \"this warning.\", FutureWarning)\n    //anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:1544: UserWarning: 'n_jobs' > 1 does not have any effect when 'solver' is set to 'liblinear'. Got 'n_jobs' = 4.\n      \" = {}.\".format(effective_n_jobs(self.n_jobs)))\n\n\n    - Training accuracy: 0.99667\n    - Validation accuracy: 0.96183\n\n\n\n```python\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nmodels, training_acc, validation_acc = zip(*results)\n\nplt.figure(figsize=(10,5))\nplt.plot(list(map(lambda i:f\"config {i}\",range(1,7))), training_acc, label=\"Training accuracy\")\nplt.plot(list(map(lambda i:f\"config {i}\",range(1,7))), validation_acc, label=\"Validation accuracy\")\nplt.title(\"Performance of different models per configuration\")\nplt.ylabel(\"Accuracy\")\nplt.legend();\n```\n\n- Quelles \u00e9tapes de preprocessing ont effectivement aid\u00e9 le mod\u00e8le ? Pourquoi ?\n\nSelon les r\u00e9sultats des diff\u00e9rentes configuration de preprocessing ci-dessous, nous constatons que les \u00e9tapes de preprocessing de la configuration 5 qu\u2019ont effectivement aid\u00e9 le mod\u00e8le. En premier lieu, l'ajout du Twitter preprocessing augmente notre pr\u00e9cision, ce qui est logique. Ensuite, l'ajout du bigram nous aide \u00e0 augmenter encore plus cette pr\u00e9cision, puisque le mod\u00e8le consid\u00e8re deux mots en m\u00eame temps (et donc donne un contexte) et non pas chaque mot ind\u00e9pendamment de l'autre.\n\n\n- La pond\u00e9ration avec TF-IDF a-t-elle aid\u00e9 \u00e0 obtenir une meilleure performance que le simple BoW ?\n\n\nOUI, TF-IDF a donn\u00e9 des pr\u00e9cisions meilleures. En outre, l\u2019avantage de TF-IDF provient du fait que certains mots peuvent \u00eatre trouv\u00e9s dans diff\u00e9rents tweets; les gens ont tendance \u00e0 s'exprimer avec des caract\u00e9ristiques communes (m\u00eames mots souvent), ce qui n'est pas pris en compte dans CountBoW, mais appara\u00eet dans le terme IDF de TF-IDF.\n\n- Les bigrams et trigrams ont-ils am\u00e9lior\u00e9 la performance ? Expliquez pourquoi.\n\nLes bigrams et trigrams ont bien am\u00e9lior\u00e9 les performances. Selon les r\u00e9sultats, la pr\u00e9cision sur les donn\u00e9es de validation a augment\u00e9 de 94,5% \u00e0 96,2%  gr\u00e2ce \u00e0 l'utilisation de bigrams. Nous pouvons en justifier par le fait que le mod\u00e8le peut stocker davantage de contexte. Si nous prenons l'exemple d'un mot bigram \"Don\u2019t like\" ou \"Quite pleasant\", cela donne plus d'informations sur le sentiment que d'avoir les deux mots s\u00e9par\u00e9s. Concernant les trigrams, nous pouvons avoir un \u00e0 priori sur leur pr\u00e9cision compar\u00e9e aux unigrams puisqu'ils prennent en compte le contexte quand m\u00eame, mais peut \u00eatre que consid\u00e9rer deux mots \u00e0 la fois marche mieux. En tout cas, c'est le cas dans cette \u00e9tude puisque la configuration n\u00b06 ne donne pas un meilleur r\u00e9sultat que la configuration n\u00b05.\n\n# II/ Prototype (7 points)\n\nMaintenant que nous avons un mod\u00e8le de classification entra\u00een\u00e9 pour l'analyse de sentiments, nous pouvons l'appliquer \u00e0 notre ensemble de tests et analyser le r\u00e9sultat.\n\n## 1. Analyse de Sentiments\n\n\n##### Question 9. Impl\u00e9mentez la fonction `detect_airline` qui d\u00e9tecte la compagnie a\u00e9rienne d'un tweet. (1,5 points)\n\nExpliquez votre approche, et les inconv\u00e9nients possibles.\n\n**Attention :** `detect_airline` doit \u00eatre en mesure de g\u00e9rer le cas o\u00f9 aucune compagnie n'est mentionn\u00e9e (auquel cas `None` est retoun\u00e9e), mais aussi le cas o\u00f9 plusieurs compagnies sont mentionn\u00e9es dans un tweet.\n\n\n```python\nfrom collections import Counter\n\nknows_airlines = ['united', 'usairways', 'americanair', 'southwestair', 'jetblue', 'virginamerica', \n                  'delta', 'spiritairlines', 'staralliance', 'virginatlantic', 'british_airways', 'expedia', \n                  'southwest', 'gma', 'silverairways', 'aircanada']\n\nprint([k[0] for k in sorted(Counter(sum(list(map(lambda x:re.findall(r\"@(\\w+)\",x.lower()),train_X)),[])).items(), \n                            key=lambda x: -x[1]) if k[1]>2])\n```\n\n    ['united', 'usairways', 'americanair', 'southwestair', 'jetblue', 'virginamerica', 'delta', 'imaginedragons', 'phlairport', 'ladygaga', 'carrieunderwood', 'wsj', 'dfwairport', 'flytpa', 'spiritairlines', 'fortunemagazine', 'velourlive', 'staralliance', 'love_dragonss', 'bostonlogan', 'triflight', 'virginatlantic', 'dulles_airport', 'derekc21', 'ny_njairports', 'british_airways', 'cowboycerrone', 'perfectomobile', 'fly2ohare', 'jayvig', 'expedia', 'gg8929', 'southwest', 'directtv', 'jack_kairys', 'thenationaluae', 'zkatcher', 'gma', 'ellahenderson', 'kylejudah', 'annricord', 'aarp', 'dallaslovefield', 'lasairport', 'vincenzolandino', 'jedediahbila', 'roxydigital', 'cnn', 'abcnetwork', 'nytimes', 'silverairways', 'aircanada']\n\n\n\n```python\nimport re\nknows_airlines = ['united', 'usairways', 'americanair', 'southwestair', 'jetblue', 'virginamerica', \n                  'delta', 'spiritairlines', 'staralliance', 'virginatlantic', 'british_airways', 'expedia', \n                  'southwest', 'gma', 'silverairways', 'aircanada']\n\ndef detect_airline(tweet):\n    \"\"\"\n    Detect and return the airline companies mentioned in the tweet\n    \n    tweet: represents the tweet message. You should define the data type\n    \n    Return: list of detected airline companies\n    \"\"\"\n    \n    found = set(knows_airlines).intersection(re.findall(r\"@(\\S+)\",tweet.lower()))\n    return list(found) if len(found)>0 else None\n\n```\n\n\n##### Question 10. Impl\u00e9mentez la fonction `extract_sentiment` qui, \u00e0 partir de tweets et d'un classificateur, extrait leurs sentiments. (0.5 points)\n\n\n\n```python\n\ndef extract_sentiment(classifier, tweets):\n    \"\"\"\n    Extract the tweet sentiment\n    \n    classifier: classifier object\n    tweets: represents the tweet message. processed tweets : matrix with numerical values (n_tweets x n_words)\n    \n    Return: list of detected airline companies\n    \"\"\"\n    # We suppose that the classifier is trained\n    return classifier.predict(tweets)\n\n```\n\n##### Question 11. En utilisant `extract_tweet_content`, `detect_airline` et `extract_sentiment`, g\u00e9n\u00e9rez un diagramme en bar contenant le nombre de tweets positives, n\u00e9gatifs et neutres pour chacune des compagnies. (2 points)\n\nD\u00e9crivez bri\u00e8vement le diagramme et analysez les r\u00e9sultats (par exemple, quelle est la compagnie avec le plus de tweets n\u00e9gatifs?). Expliquez comment un tel diagramme peut aider des compagnies a\u00e9riennes.\n\n\n```python\n# init configuration\nselected_conf = {\"model\":TFIDFBoW, \"tokenize\":True, \"stemming\": True, \"preprocess\":True, \"bi\":True}\n\nstemming = selected_conf.get(\"stemming\",False)\ntw_prep = selected_conf.get(\"preprocess\",False)\ntokenize = selected_conf.get(\"tokenize\",False)\nbi = conf.get(\"bi\",False)\ntri = conf.get(\"tri\",False)\n\n# init preprocessing pipeline\npipeline = PreprocessingPipeline(tokenization = tokenize, twitterPreprocessing = tw_prep, stemming = stemming)\nbowObj = conf[\"model\"](pipeline, bigram = bi, trigram = tri)\n\ntraining_rep = bowObj.fit_transform(train_X)\ntesting_rep = bowObj.transform(test_X)\n\n# fit the classifier\nclassifier = LogisticRegression(n_jobs=-1)\nclassifier.fit(training_rep, train_Y)\n```\n\n    //anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.\n      FutureWarning)\n    //anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:469: FutureWarning: Default multi_class will be changed to 'auto' in 0.22. Specify the multi_class option to silence this warning.\n      \"this warning.\", FutureWarning)\n    //anaconda3/lib/python3.7/site-packages/sklearn/linear_model/logistic.py:1544: UserWarning: 'n_jobs' > 1 does not have any effect when 'solver' is set to 'liblinear'. Got 'n_jobs' = 4.\n      \" = {}.\".format(effective_n_jobs(self.n_jobs)))\n\n\n\n\n\n    LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,\n                       intercept_scaling=1, l1_ratio=None, max_iter=100,\n                       multi_class='warn', n_jobs=-1, penalty='l2',\n                       random_state=None, solver='warn', tol=0.0001, verbose=0,\n                       warm_start=False)\n\n\n\n\n```python\nairlines = list(map(detect_airline,test_X))\nsentiments = extract_sentiment(classifier, testing_rep)\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nfrom collections import Counter, defaultdict\n\nairlines_rates = defaultdict(lambda :defaultdict(int))\nfor airlines_tweet, sentim in zip(airlines, sentiments):\n    if airlines_tweet is not None:\n        for airln in airlines_tweet:\n            airlines_rates[sentim][airln]+=1\n\n\n```\n\n\n```python\nimport pandas as pd\n\nscores = pd.DataFrame(airlines_rates).fillna(0)\nscores.columns = [\"Negative\", \"Neutral\", \"Positive\"]\nscores.plot.bar(figsize=(20,5), rot=0)\nplt.title(\"Histogram of sentiments expressed in comments for different airline companies\")\nplt.ylabel(\"Number of tweets\")\nplt.xlabel(\"Airline companies\");\n```\n\nL\u2019histogramme ci-dessus repr\u00e9sente le nombre de tweets positives, n\u00e9gatifs et neutres pour chacune des compagnies. On remarque que le sentiment n\u00e9gatif est le plus dominant pour tous les compagnies. La compagnie United prend le dessus en terme de tweets n\u00e9gatifs vient apr\u00e8s la compagnie American air, et puis UsairWays. En termes de tweets positives et neutres, on trouve qu\u2019ils varient d\u2019une compagnie \u00e0 l\u2019autre avec un grand \u00e9cart par rapport aux tweets n\u00e9gatifs. \nCe diagramme aide \u00e9norm\u00e9ment  les compagnies a\u00e9riennes pour analyser la satisfaction de leurs clients par rapport \u00e0 leurs concurrents.\n\n\n## 2. Analyse de termes\n\nLe POS-tagging (pour *part-of-speech tagging*, en fran\u00e7ais \u00e9tiquetage grammatical) consiste \u00e0 l'extraction de l'information grammaticale d'un token dans une phrase. Par exemple, la table ci-dessous donne un exemple du *POS-tagging* de la phrase *\"The cat is white!\"*\n\n\n|   The   | cat  |  is  | white     |    !       |\n|---------|------|------|-----------|------------|\n| article | noun | verb | adjective | punctation |\n\n\nPour autant, le *POS-tagging* peut \u00eatre plus complexe que les r\u00e8gles simples apprises \u00e0 l'\u00e9cole. Il faut souvent des informations plus d\u00e9taill\u00e9es sur le r\u00f4le d'un terme dans une phrase. Pour notre probl\u00e8me, nous n'avons pas besoin d'utiliser un mod\u00e8le linguistique plus complexe, nous allons utiliser ce qu'on appelle des *POS-tags* universelles.\n\nEn *POS-tagging*, chaque token est repr\u00e9sent\u00e9 par un tag. La liste des POS-tags utilis\u00e9s sont disponibles ici :\nhttps://universaldependencies.org/u/pos/ .\n\n\n```python\n# NLTK POS-tagger\n\nimport nltk\n\n\n#before using pos_tag function, you have to tokenize the sentence.\ns = ['The', 'cat', 'is',  'white', '!']\nnltk.pos_tag(s,tagset='universal')\n\n```\n\n\n\n\n    [('The', 'DET'), ('cat', 'NOUN'), ('is', 'VERB'), ('white', 'ADJ'), ('!', '.')]\n\n\n\n##### Question 12. Impl\u00e9mentez un code qui collecte les 10 termes les plus fr\u00e9quents pour chaque compagnie a\u00e9rienne. (2 Pts)\n\nIci, vous n'allez consid\u00e9rer que les termes apparaissant dans les tweets positifs et n\u00e9gatifs. \n\nDe plus, nous allons utiliser la d\u00e9finition suivante de \"terme\":\n\n1. Un mot qui est soit un adjectif, soit un nom\n2. Un N-gram compos\u00e9 d'adjectifs suivit par un nom (par exemple, \"nice place\"), ou un nom suivi par un autre nom (par exemple, \"sports club\").\n\nEnsuite, **g\u00e9n\u00e9rez une table** contenant les 10 termes les plus fr\u00e9quents, avec leurs fr\u00e9quences (en pourcentage) pour chaque compagnie.\n\n*N'oubliez pas de supprimer le nom de la compagnie parmi les termes !*\n\n\n\n```python\nfrom collections import Counter, defaultdict\n\nselected_tweets = [tweet for tweet, sentiment in zip(train_X, train_Y) if sentiment!=1]\ngrams_companies = defaultdict(list)\nprev_word = None\nfor tweet in selected_tweets:\n    companies = detect_airline(tweet.lower())\n\n    if companies is None: continue\n    cleaned_tweet = tweet.lower()\n    for c in companies:\n        cleaned_tweet = cleaned_tweet.replace(\"@\"+c,\"\")\n    cleaned_tweet = cleaned_tweet.encode(\"cp1251\",\"ignore\").decode()\n\n    for word in nltk.pos_tag(NLTKTokenizer().tokenize(cleaned_tweet),tagset='universal'):\n        if word[1] in [\"NOUN\",\"ADJ\"]:\n            for company in companies:\n                grams_companies[company].append(word[0])\n                if prev_word is not None and word[1] == \"NOUN\" and prev_word[1] in [\"NOUN\",\"ADJ\"]:\n                    grams_companies[company].append(f\"{prev_word[0]} {word[0]}\")\n        prev_word = word\n```\n\n\n```python\n#from IPython.display import display, HTML\n\ndataframes_dict = {}\nfor company_name in knows_airlines:\n    terms_counts = Counter(grams_companies[company_name])\n    most_freq_terms = terms_counts.most_common(10)\n    total_counts = sum(terms_counts.values())\n    most_freq_terms = list(map(lambda x:(x[0],x[1]/total_counts*100), most_freq_terms)) +[(\"\",\"\")]*(10 - len(most_freq_terms))\n    \n    \n    index = [f\"term N.{i}\" for i in range(1,11)]\n    dataframes_dict[company_name] = pd.DataFrame(most_freq_terms, index=index,columns=[\"term\",\"frequency\"])\n\n    # second method\n    #df = pd.DataFrame(most_freq_terms, index=index,columns=[\"term\",\"frequency\"])\n    #df[\"frequency\"] = df[\"frequency\"] / total_counts*100\n    #display(HTML(df.transpose().to_html()))\n    \npd.Panel(dataframes_dict).to_frame().transpose()        \n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th>major</th>\n      <th colspan=\"2\" halign=\"left\">term N.1</th>\n      <th colspan=\"2\" halign=\"left\">term N.2</th>\n      <th colspan=\"2\" halign=\"left\">term N.3</th>\n      <th colspan=\"2\" halign=\"left\">term N.4</th>\n      <th colspan=\"2\" halign=\"left\">term N.5</th>\n      <th colspan=\"2\" halign=\"left\">term N.6</th>\n      <th colspan=\"2\" halign=\"left\">term N.7</th>\n      <th colspan=\"2\" halign=\"left\">term N.8</th>\n      <th colspan=\"2\" halign=\"left\">term N.9</th>\n      <th colspan=\"2\" halign=\"left\">term N.10</th>\n    </tr>\n    <tr>\n      <th>minor</th>\n      <th>term</th>\n      <th>frequency</th>\n      <th>term</th>\n      <th>frequency</th>\n      <th>term</th>\n      <th>frequency</th>\n      <th>term</th>\n      <th>frequency</th>\n      <th>term</th>\n      <th>frequency</th>\n      <th>term</th>\n      <th>frequency</th>\n      <th>term</th>\n      <th>frequency</th>\n      <th>term</th>\n      <th>frequency</th>\n      <th>term</th>\n      <th>frequency</th>\n      <th>term</th>\n      <th>frequency</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>united</th>\n      <td>i</td>\n      <td>4.40439</td>\n      <td>flight</td>\n      <td>3.53518</td>\n      <td>service</td>\n      <td>1.03839</td>\n      <td>time</td>\n      <td>0.816708</td>\n      <td>thanks</td>\n      <td>0.810874</td>\n      <td>customer</td>\n      <td>0.775872</td>\n      <td>plane</td>\n      <td>0.74087</td>\n      <td>bag</td>\n      <td>0.74087</td>\n      <td>united</td>\n      <td>0.711702</td>\n      <td>gate</td>\n      <td>0.618364</td>\n    </tr>\n    <tr>\n      <th>usairways</th>\n      <td>i</td>\n      <td>4.85988</td>\n      <td>flight</td>\n      <td>3.54026</td>\n      <td>service</td>\n      <td>1.2132</td>\n      <td>hold</td>\n      <td>1.18482</td>\n      <td>hours</td>\n      <td>0.971976</td>\n      <td>customer</td>\n      <td>0.922313</td>\n      <td>plane</td>\n      <td>0.780419</td>\n      <td>thanks</td>\n      <td>0.759134</td>\n      <td>customer service</td>\n      <td>0.744945</td>\n      <td>time</td>\n      <td>0.695282</td>\n    </tr>\n    <tr>\n      <th>americanair</th>\n      <td>i</td>\n      <td>5.18524</td>\n      <td>flight</td>\n      <td>3.68113</td>\n      <td>service</td>\n      <td>1.04497</td>\n      <td>thanks</td>\n      <td>1.00538</td>\n      <td>@</td>\n      <td>1.00538</td>\n      <td>hours</td>\n      <td>0.918303</td>\n      <td>customer</td>\n      <td>0.807473</td>\n      <td>hold</td>\n      <td>0.680811</td>\n      <td>time</td>\n      <td>0.641229</td>\n      <td>call</td>\n      <td>0.625396</td>\n    </tr>\n    <tr>\n      <th>southwestair</th>\n      <td>i</td>\n      <td>5.25686</td>\n      <td>flight</td>\n      <td>3.45015</td>\n      <td>thanks</td>\n      <td>1.09926</td>\n      <td>hold</td>\n      <td>1.09926</td>\n      <td>@</td>\n      <td>1.03396</td>\n      <td>service</td>\n      <td>0.946887</td>\n      <td>time</td>\n      <td>0.827166</td>\n      <td>customer</td>\n      <td>0.816282</td>\n      <td>http</td>\n      <td>0.761863</td>\n      <td>thank</td>\n      <td>0.729212</td>\n    </tr>\n    <tr>\n      <th>jetblue</th>\n      <td>i</td>\n      <td>4.95619</td>\n      <td>flight</td>\n      <td>3.8609</td>\n      <td>thanks</td>\n      <td>1.46495</td>\n      <td>@</td>\n      <td>1.20482</td>\n      <td>jetblue</td>\n      <td>1.04053</td>\n      <td>time</td>\n      <td>0.821468</td>\n      <td>http</td>\n      <td>0.780394</td>\n      <td>service</td>\n      <td>0.753012</td>\n      <td>plane</td>\n      <td>0.698248</td>\n      <td>great</td>\n      <td>0.684556</td>\n    </tr>\n    <tr>\n      <th>virginamerica</th>\n      <td>i</td>\n      <td>5.66757</td>\n      <td>flight</td>\n      <td>3.54223</td>\n      <td>http</td>\n      <td>0.980926</td>\n      <td>@</td>\n      <td>0.817439</td>\n      <td>thanks</td>\n      <td>0.762943</td>\n      <td>website</td>\n      <td>0.762943</td>\n      <td>help</td>\n      <td>0.708447</td>\n      <td>great</td>\n      <td>0.653951</td>\n      <td>flights</td>\n      <td>0.653951</td>\n      <td>seat</td>\n      <td>0.599455</td>\n    </tr>\n    <tr>\n      <th>delta</th>\n      <td>i</td>\n      <td>5.50725</td>\n      <td>flight</td>\n      <td>4.05797</td>\n      <td>worst</td>\n      <td>2.02899</td>\n      <td>service</td>\n      <td>1.73913</td>\n      <td>customers</td>\n      <td>1.44928</td>\n      <td>airline</td>\n      <td>1.15942</td>\n      <td>time</td>\n      <td>1.15942</td>\n      <td>@</td>\n      <td>0.869565</td>\n      <td>good</td>\n      <td>0.869565</td>\n      <td>anything</td>\n      <td>0.869565</td>\n    </tr>\n    <tr>\n      <th>spiritairlines</th>\n      <td>florida</td>\n      <td>6.89655</td>\n      <td>wrong</td>\n      <td>3.44828</td>\n      <td>3days</td>\n      <td>3.44828</td>\n      <td>florida 3days</td>\n      <td>3.44828</td>\n      <td>real</td>\n      <td>3.44828</td>\n      <td>airlines</td>\n      <td>3.44828</td>\n      <td>real airlines</td>\n      <td>3.44828</td>\n      <td>fly</td>\n      <td>3.44828</td>\n      <td>smalls</td>\n      <td>3.44828</td>\n      <td>glad</td>\n      <td>3.44828</td>\n    </tr>\n    <tr>\n      <th>staralliance</th>\n      <td>tickets</td>\n      <td>4.25532</td>\n      <td>few</td>\n      <td>2.12766</td>\n      <td>weeks</td>\n      <td>2.12766</td>\n      <td>few weeks</td>\n      <td>2.12766</td>\n      <td>bright</td>\n      <td>2.12766</td>\n      <td>vibrant</td>\n      <td>2.12766</td>\n      <td>bright vibrant</td>\n      <td>2.12766</td>\n      <td>habitrails</td>\n      <td>2.12766</td>\n      <td>right</td>\n      <td>2.12766</td>\n      <td>thing</td>\n      <td>2.12766</td>\n    </tr>\n    <tr>\n      <th>virginatlantic</th>\n      <td>i</td>\n      <td>20</td>\n      <td>representative</td>\n      <td>5</td>\n      <td>solution</td>\n      <td>5</td>\n      <td>loyal</td>\n      <td>5</td>\n      <td>customer</td>\n      <td>5</td>\n      <td>loyal customer</td>\n      <td>5</td>\n      <td>funny</td>\n      <td>5</td>\n      <td>lhr</td>\n      <td>5</td>\n      <td>mean</td>\n      <td>5</td>\n      <td>time</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>british_airways</th>\n      <td>flight</td>\n      <td>10</td>\n      <td>agent</td>\n      <td>5</td>\n      <td>tonight</td>\n      <td>5</td>\n      <td>anyone</td>\n      <td>5</td>\n      <td>aa</td>\n      <td>5</td>\n      <td>weeks</td>\n      <td>5</td>\n      <td>today</td>\n      <td>5</td>\n      <td>miami</td>\n      <td>5</td>\n      <td>i</td>\n      <td>5</td>\n      <td>bag</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>expedia</th>\n      <td>day</td>\n      <td>4.7619</td>\n      <td>costumer</td>\n      <td>4.7619</td>\n      <td>jetblue</td>\n      <td>4.7619</td>\n      <td>makingthingseasy</td>\n      <td>4.7619</td>\n      <td>feelbetter</td>\n      <td>4.7619</td>\n      <td>hour</td>\n      <td>4.7619</td>\n      <td>hold</td>\n      <td>4.7619</td>\n      <td>hour hold</td>\n      <td>4.7619</td>\n      <td>ticket</td>\n      <td>4.7619</td>\n      <td>easy</td>\n      <td>4.7619</td>\n    </tr>\n    <tr>\n      <th>southwest</th>\n      <td>i</td>\n      <td>5.26316</td>\n      <td>change</td>\n      <td>5.26316</td>\n      <td>customer</td>\n      <td>5.26316</td>\n      <td>service</td>\n      <td>5.26316</td>\n      <td>customer service</td>\n      <td>5.26316</td>\n      <td>flight</td>\n      <td>5.26316</td>\n      <td>policy</td>\n      <td>2.63158</td>\n      <td>serious</td>\n      <td>2.63158</td>\n      <td>revision</td>\n      <td>2.63158</td>\n      <td>serious revision</td>\n      <td>2.63158</td>\n    </tr>\n    <tr>\n      <th>gma</th>\n      <td>worse</td>\n      <td>5.88235</td>\n      <td>airline</td>\n      <td>5.88235</td>\n      <td>worse airline</td>\n      <td>5.88235</td>\n      <td>experience</td>\n      <td>5.88235</td>\n      <td>airline experience</td>\n      <td>5.88235</td>\n      <td>rude</td>\n      <td>5.88235</td>\n      <td>unhelpful</td>\n      <td>5.88235</td>\n      <td>help</td>\n      <td>5.88235</td>\n      <td>customer</td>\n      <td>5.88235</td>\n      <td>service</td>\n      <td>5.88235</td>\n    </tr>\n    <tr>\n      <th>silverairways</th>\n      <td>preferred</td>\n      <td>3.125</td>\n      <td>security</td>\n      <td>3.125</td>\n      <td>preferred security</td>\n      <td>3.125</td>\n      <td>line</td>\n      <td>3.125</td>\n      <td>security line</td>\n      <td>3.125</td>\n      <td>tsa</td>\n      <td>3.125</td>\n      <td>pre-check</td>\n      <td>3.125</td>\n      <td>tsa pre-check</td>\n      <td>3.125</td>\n      <td>partner</td>\n      <td>3.125</td>\n      <td>flight</td>\n      <td>3.125</td>\n    </tr>\n    <tr>\n      <th>aircanada</th>\n      <td>baggage</td>\n      <td>16.6667</td>\n      <td>person</td>\n      <td>16.6667</td>\n      <td>baggage person</td>\n      <td>16.6667</td>\n      <td>connecting</td>\n      <td>16.6667</td>\n      <td>flight</td>\n      <td>16.6667</td>\n      <td>connecting flight</td>\n      <td>16.6667</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n##### Question 13. Que conclure de la table g\u00e9n\u00e9r\u00e9 \u00e0 la question 12 pour les compagnies ? (1 Pt)\n\n\nIl n\u2019est pas facile de tirer les conclusions directes, car la fr\u00e9quence des mots est trop faible. Les termes sp\u00e9cifiques discriminants utilis\u00e9s contre / en faveur de la compagnie sont donc difficiles. Le seul probl\u00e8me avec l'extraction de mots bigrammes ou de mots est que les entreprises ne peuvent pas d\u00e9terminer la raison du sentiment; ils devront lire l'int\u00e9gralit\u00e9 du tweet. Sauf dans certains cas o\u00f9 on peut en deviner la raison: par exemple, \"missed\" signifie probablement que l'auteur a rat\u00e9 son vol\n\n# III/ Bonus (2 points)\n\nLes noms de personnes, les noms de soci\u00e9t\u00e9s et les emplacements sont appel\u00e9s \"entit\u00e9s nomm\u00e9es\". La reconnaissance d'entit\u00e9 nomm\u00e9e (NER, pour *Named-entity recognition*) consiste \u00e0 extraire les entit\u00e9s nomm\u00e9es en les classant \u00e0 l'aide de cat\u00e9gories pr\u00e9d\u00e9finies. Dans cette section bonus, vous utiliserez un outil de NER pour extraire automatiquement des entit\u00e9s nomm\u00e9es des tweets. Cette approche est suffisamment g\u00e9n\u00e9rique pour r\u00e9cup\u00e9rer des informations sur d\u2019autres soci\u00e9t\u00e9s ou m\u00eame des noms de produits et de personnes.\n\n\n**Pour le bonus, vous \u00eates libres d'utiliser n'importe quel NER impl\u00e9ment\u00e9 en Python.**\n\n##### Question Bonus 1.  Impl\u00e9mentez un code qui g\u00e9n\u00e8re une table contenant le top 10 des NER de la base de donn\u00e9es. (1 point)\n\nCette table doit contenir les fr\u00e9quences des entit\u00e9s nomm\u00e9es. Ensuite, g\u00e9n\u00e9rez un diagramme en bar qui montre le nombre de tweets positifs, n\u00e9gatifs ou neutres pour chacunes des 10 NER. D\u00e9crivez le r\u00e9sultat obtenu.\n\n\n\n```python\n#!pip install spacy\n#!python -m spacy download en\n\nimport spacy\nimport tqdm\nspacy_nlp = spacy.load('en')\n\n\nner = []\nfor tweet in tqdm.tqdm_notebook(train_X):\n    parsed_ner = spacy_nlp(re.sub(\"#|@\",\"\",tweet))\n\n    for element in parsed_ner.ents:\n        if element.label_ in [\"GPE\", \"ORG\", \"PERSON\"]:\n            ner.append(str(element).lower())\n```\n\n\n    HBox(children=(IntProgress(value=0, max=10204), HTML(value='')))\n\n\n\n```python\ndf = pd.DataFrame(Counter(ner).most_common(10),columns=[\"term\",\"frequency\"])\ndf\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>term</th>\n      <th>frequency</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>americanair</td>\n      <td>822</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>southwestair</td>\n      <td>688</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>virginamerica</td>\n      <td>276</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>jetblue</td>\n      <td>224</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>cancelled flightled</td>\n      <td>190</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>united</td>\n      <td>135</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>jfk</td>\n      <td>89</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>cancelled flighted</td>\n      <td>69</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>lax</td>\n      <td>64</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>us</td>\n      <td>62</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nfrom collections import defaultdict\nfreqs_ner = defaultdict(lambda :defaultdict(int))\nfor tweet, class_ in tqdm.tqdm_notebook(zip(train_X, train_Y)):\n    lower_tw = tweet.lower()\n    for ner_term in df.term.values:\n        if ner_term in lower_tw:\n            parsed_ner = spacy_nlp(re.sub(\"#|@\",\"\",tweet))\n            for element in parsed_ner.ents:\n                if str(element).lower() in df.term.values:\n                    freqs_ner[str(element)][class_]+=1\n            break\n```\n\n\n    HBox(children=(IntProgress(value=1, bar_style='info', max=1), HTML(value='')))\n\n\n\n```python\ndf_req = pd.DataFrame(freqs_ner)\ndf_req.index = [\"Negative\",\"Neutral\",\"Positive\"]\ndf_req.plot.bar(figsize=(15,5),rot=0)\nplt.title(\"le nombre de tweets positifs, n\u00e9gatifs ou neutres pour chacunes des 10 NER\")\n```\n\nTout comme le diagramme fait \u00e0 la question 11, cela aide \u00e9norm\u00e9ment les compagnies a\u00e9riennes \u00e0 analyser leurs points faibles et points forts afin d'atteindre une certaine satisfaction des clients (passagers). En effet, par le biais de ce diagramme, nous pouvons d\u00e9duire de prime \u00e0 bord que le nombre de commentaires n\u00e9gatifs et largement sup\u00e9rieur au nombre de commentaires positifs ou neutres. Cela est tr\u00e8s remarqu\u00e9 pour les deux compagnies AmericanAir et SouthwestAir. En m\u00eame temps, la copagnie SouthwestAir connait le meilleur nombre de commentaires positifs et neutres dans la liste. Ce qui serait int\u00e9ressant et de mesurer le ratio entre les commentaire n\u00e9gatifs et positifs/neutres afin d'avoir une m\u00e9trique de comparaison entre les diff\u00e9rentes compagnies a\u00e9riennes.\n\n##### Question Bonus 2. G\u00e9n\u00e9rez une table similaire \u00e0 la question 12 pour le top 10 des NER pour chaque compagnie. (1 point)\n\nQue peut-on conclure de ces r\u00e9sultats?\n\n\n```python\n# TODO\n```\n", "meta": {"hexsha": "bc19dc8abedeeef5e8c58198221b725b1a57a542", "size": 194985, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Assignment 1/Assignment1.ipynb", "max_stars_repo_name": "AmineBellahsen/INF8111-Data_Mining", "max_stars_repo_head_hexsha": "d570f2d7e02888cb0ec107bba80402097c119e1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assignment 1/Assignment1.ipynb", "max_issues_repo_name": "AmineBellahsen/INF8111-Data_Mining", "max_issues_repo_head_hexsha": "d570f2d7e02888cb0ec107bba80402097c119e1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignment 1/Assignment1.ipynb", "max_forks_repo_name": "AmineBellahsen/INF8111-Data_Mining", "max_forks_repo_head_hexsha": "d570f2d7e02888cb0ec107bba80402097c119e1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 71.2664473684, "max_line_length": 32584, "alphanum_fraction": 0.7100187194, "converted": true, "num_tokens": 21008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746993014852224, "lm_q2_score": 0.08389038011200321, "lm_q1q2_score": 0.024954865512050575}}
{"text": "# Week 2 \n## Introduction to Solid State \n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport subprocess\nimport MSD as msd\nimport fig_params \n\nfrom scipy import stats\n\n\ndef get_diffusion(file, atom):\n    \n    with open(file) as f:\n        y = False\n        for line in f:\n            if str(\"atom        D \") in line:\n                y = True\n            if y == True and str(atom) in line:\n                d = line.split()\n                break\n    return d\n```\n\nNow that you are familiar with molecular dynamics, you are now going to use it to tackle some real world problems. In the next three weeks you will investigate the transport properties of a simple fluorite material - Ca$F_2$. The transport properties of a material determine many properties that are utilised for modern technological applications. For example, solid oxide fuel cell (SOFCs - Alternative to batteries) materials are dependent on the movement of charge carriers through the solid electrolyte and  nuclear fuel materials oxidise and fall apart and this corrosive behaviour is dependent on the diffusion of oxygen into the lattice. Due to the importance of the transport properties of these materials, scientists and engineers spend large amounts of their time tring to optomise these properties using different stoichiometries, introducing defects and by using different syntheisis techniques. Over the next three weeks you will investigate how the transport properties of Ca$F_2$ are affected by temperature, structural defects (Schottky and Frenkel) and by chemcial dopants (e.g. different cations). A rough breakdown looks as follows\n- Week 2 \n    - Introduction to DL_POLY\n    - Tutorial on the calculation of diffusion coefficients\n    - Tutorial on the Arhennius equation\n    - Molecular dynamics simulations of stoichiomteric Ca$F_2$\n- Week 3 \n    - Frenkel and Schottky defects\n- Week 4 \n    - Dopants\n    \n\n\n## Introduction to DL_POLY\n\nDL_POLY is a molecular dynamics program maintained by Daresbury laboratories. In contrast to pylj, DL_POLY is a three dimensional molecular dynamics code that is used worldwide by computational scientists for molecular simulation, but it should be noted that the theory is exactly the same and any understanding gained from pylj is completely applicable to DL_POLY. For the next three weeks you will use DL_POLY to run short molecular dynamics simulations on Ca$F_2$. You first need to understand the input files required for DL_POLY. \n- CONTROL - This is the file that contains all of the simulation parameters, e.g. simulation temperature, pressure, number of steps e.t.c\n- CONFIG - This is the file that contains the structure - i.e. the atomic coordinates of each atom. \n- FIELD - This is the file that contains the force field or potential model e.g. Lennard Jones. \n\nContained within the folder \"Input\" you will find a file called input.txt. This is the main file that you will interact with over the next three weeks and is used to generate the FIELD, CONTROL and CONFIG. Essentially it is easier to meddle with input.txt than it is to meddle with the 3 DL_POLY files everytime you want to change something. To run metadise we will use the subprocess python module. You specify what program you want to run and the file that you want to run it in, you will need to ensure the file path is correct. \n\n#### It is essential that the codes that were downloaded from [here](https://people.bath.ac.uk/chsscp/teach/adv.bho/progs.zip) are in the Codes/ folder in the parent directory, or this following cell will crash. \n\n\n```python\nsubprocess.call('../Codes/metadise.exe', cwd='Input/')\nos.rename('Input/control_o0001.dlp', 'Input/CONTROL')\nos.rename('Input/config__o0001.dlp', 'Input/CONFIG')\nos.rename('Input/field___o0001.dlp', 'Input/FIELD')\n```\n\nNow you should have a CONFIG, CONTROL and FIELD file within the input directory. In theory you could just call the DL_POLY program on this directory and your simulation would run. However we need to tweak the CONTROL file in order to set up our desired simulation. Make a new subdirectory in the week 2 directory named \"Example\" and copy CONFIG, CONTROL and FIELD to that subdirectory. Now edit the CONTROL file.  \n\nWe want to change the following   \n\n`Temperature 300 ---> Temperature 1500`  \n`Steps 5001 ---> Steps 40000`  \n`ensemble nve ---> ensemble npt hoover 0.1 0.5`  \n`trajectory nstraj= 1    istraj=   250 keytrj=0 ---> trajectory nstraj= 0    istraj= 100  keytrj=0`  \n  \nNow your simulation is ready. As a point of interest it is always good to check your structure before and after the simulation. You can view the CONFIG file in three dimensions using the VESTA program. It is available for free at http://www.jp-minerals.org/vesta/en/download.html . Download it and use it to view your CONFIG, a demonstrator can help if necessary. VESTA can generate nice pictures which will look very good in a lab report. \n\n<center>\n    <br>\n    \n    <i>Figure 1. Fluorite Ca$F_2$ unit cell visualised in VESTA.</i>\n    <br>\n</center>\n\n\nTo run DL_POLY from within a notebook use the below command. Keep in mind that this simulation will take 20 or so minutes so be patient. \n\nIf you are not comfortable with running things through this notebook then you can copy and paste the dlpoly_classic.exe executable into the Example/ sub directory and then double click the .exe file\n\n\n```python\nsubprocess.call('../Codes/dlpoly_classic.exe', cwd='Example/')\n```\n\n\n\n\n    0\n\n\n\nOnce DL_POLY has completed you will find several files relating to your simulaton. \n- HISTORY - This file contains the configuration of your system at each step during the simulation. You can view this as a movie using the VMD program - Ask a demonstrator for details\n- REVCON - This is the configuration at the end of the simulation - Can be viewed in VESTA - why not check to see how it has changed. \n- STATIS - Contains the stats at each step in the simulation. \n- OUTPUT - Contains properties \n\nIt is now important to understand how we can actually use the details of the simulation to get some information on the properties of the material, e.g. Diffusion coefficients and activation energies. \n\n## Mean Squared Displacements - Calculating diffusion coefficients\n\nAs we have seen molecules in liquds, gases and solids do not stay in the same place and move constantly. Think about a drop of dye in a glass of water, as time passes the dye distributes throughout the water. This process is called diffusion and is common throughout nature.  \n\nUsing the dye as an example, the motion of a dye molecule is not simple. As it moves it is jostled by collisions with other molecules, preventing it from moving in a straight path. If the path is examined in close detail, it will be seen to be a good approximation to a random walk. In mathmatics a random walk is a series of steps, each taken in a random direction. This was analysed by Albert Einstein in a study of Brownian motion and he showed that the mean square of the distance travelled by a particle following a random walk is proportional to the time elapsed. \n\\begin{align}\n\\Big \\langle r^2 \\big \\rangle & = 6 D_t + C \n\\end{align}\n\nwhere $\\Big \\langle r^2 \\big \\rangle$ is the mean squared distance, t is time, D is the diffusion rate and C is a constant. \n\n## What is the mean squared displacement\n\nGoing back to the example of the dye in water, lets assume for the sake of simplicity that we are in one dimension. Each step can either be forwards or backwards and we cannot predict which. From a given starting position, what distance is our dye molecule likely to travel after 1000 steps? This can be determined simply by adding together the steps, taking into account the fact that steps backwards subtract from the total, while steps forward add to the total. Since both forward and backward steps are equally probable, we come to the surprising conclusion that the probable distance travelled sums up to zero.\n\nBy adding the square of the distance we will always be adding positive numbers to our total which now increases linearly with time. Based upon equation 1 it should now be clear that a plot of $\\Big \\langle r^2 \\big \\rangle$ vs time with produce a line, the gradient of which is equal to 6D. Giving us direct access to the diffusion coefficient of the system. \n\nLets try explore this with an example. Run a short DL_POLY simulation on the input files provided. \n\nYou will a small MSD program called MSD.py to analyse your simulation results. First you need to read in the data, the HISTORY file contains a list of the atomic coordiantes held by the atoms during the simulation. \n\n\n```python\n# Read in the HISTORY file\n\n## Provide the path to the simulation and the atom that you want data for.\ndata = msd.read_history(\"Example/HISTORY\", \"F\")\n```\n\ndata is a dictionary variable containing the atomic trajectories, lattice vectors, total number of atoms, and total number of timesteps. \n\ndata = {'trajectories':trajectories, 'lv':lv, 'timesteps':timesteps, 'natoms':natoms}\n\nThe next step is to calculate the MSD. \n\n\n```python\n# Run the MSD calculation\nmsd_data = msd.run_msd(data)\n```\n\nrun_msd returns a dictionary containing the total MSD, the dimensional MSD values and the time. \nmsd_data = {'msd': msd, 'xmsd': xmsd, 'ymsd': ymsd, 'zmsd': zmsd, 'time': time}\n\nThis can then be plotted to give a nice linear relationship. \n\n\n```python\nplt.plot(msd_data['time'], msd_data['msd'], lw=2, color=\"red\", label=\"MSD\")\nplt.plot(msd_data['time'], msd_data['xmsd'], lw=2, color=\"blue\", label=\"X-MSD\")\nplt.plot(msd_data['time'], msd_data['ymsd'], lw=2, color=\"green\", label=\"Y-MSD\")\nplt.plot(msd_data['time'], msd_data['zmsd'], lw=2, color=\"black\", label=\"Z-MSD\")\n\nplt.ylabel(\"MSD (\" r'$\\AA$' \")\", fontsize=15)\nplt.xlabel(\"Time / ps\", fontsize=15)\nplt.ylim(0, np.amax(msd_data['msd']))\nplt.xlim(0, np.amax(msd_data['time']))\nplt.legend(loc=2, frameon=False)\nplt.show()\n```\n\nTo calculate the gradient we need to perform a linear regression on the data. \n\n\n```python\nslope, intercept, r_value, p_value, std_err = stats.linregress(msd_data['time'], msd_data['msd'])\n```\n\nThe gradient is equal to 6D (6 = dimensionality). So our final diffusion coefficient for the simulation is given by\n\n\n```python\ndiffusion_coefficient = (np.average(slope) / 6) \nprint(\"Diffusion Coefficient: \", diffusion_coefficient, \" X 10 ^-9 (m^-2)\")\n```\n\n    Diffusion Coefficient:  1.4550282026323467  X 10 ^-9 (m^-2)\n\n\n## Simulation Length\n\nIt is important to consider the lenght of your simulation (Number of steps). Create a new folder called \"Example_2\", copy the CONFIG, FIELD and CONTROL files from your previous simulation but this time change the number of steps to 10000. Now rerun the simulation.\n\n\n```python\nsubprocess.call('../Codes/dlpoly_classic.exe', cwd='Example_2/')\n```\n\n\n\n\n    0\n\n\n\n\n```python\ndata = msd.read_history(\"Example_2/HISTORY\", \"F\")\nmsd_data = msd.run_msd(data)\n\nplt.plot(msd_data['time'], msd_data['msd'], lw=2, color=\"red\", label=\"MSD\")\nplt.plot(msd_data['time'], msd_data['xmsd'], lw=2, color=\"blue\", label=\"X-MSD\")\nplt.plot(msd_data['time'], msd_data['ymsd'], lw=2, color=\"green\", label=\"Y-MSD\")\nplt.plot(msd_data['time'], msd_data['zmsd'], lw=2, color=\"black\", label=\"Z-MSD\")\n\nplt.ylabel(\"MSD (\" r'$\\AA$' \")\", fontsize=15)\nplt.xlabel(\"Time / ps\", fontsize=15)\nplt.ylim(0, np.amax(msd_data['msd']))\nplt.xlim(0, np.amax(msd_data['time']))\nplt.legend(loc=2, frameon=False)\nplt.show()\n```\n\n\n```python\nslope, intercept, r_value, p_value, std_err = stats.linregress(msd_data['time'], msd_data['msd'])\n\ndiffusion_coefficient = (np.average(slope) / 6) \nprint(\"Diffusion Coefficient: \", diffusion_coefficient, \" X 10 ^-9 (m^-2)\")\n```\n\n    Diffusion Coefficient:  1.5361178863063245  X 10 ^-9 (m^-2)\n\n\nYou will hopefully see that your MSD plot has become considerably less linear. This shows that your simulation has not run long enough and your results will be unrealiable. You will hopefully also see a change to the value of your diffusion coefficient.  The length of your simulation is something that you should keep in mind for the next 3 weeks. \n\n## Arrhenius\n\nThe next thing is to use the diffusion coefficients to calcaulte the activation energy for F diffusion. This rea=quires diffusion coefficients from a temperature range. Common sense and chemical intuition suggest that the higher the temperature, the faster a given chemical reaction will proceed. Quantitatively this relationship between the rate a reaction proceeds and its temperature is determined by the Arrhenius Equation. At higher temperatures, the probability that two molecules will collide is higher. This higher collision rate results in a higher kinetic energy, which has an effect on the activation energy of the reaction. The activation energy is the amount of energy required to ensure that a reaction happens.  \n  \n\\begin{align}\nk = A * e^{(-Ea / RT)}\n\\end{align}\n  \nwhere k is the rate coefficient, A is a constant, Ea is the activation energy, R is the universal gas constant, and T is the temperature (in kelvin).\n\n\n\n## Week 2 Exercise\n\nUsing what you have learned over the last 45 mins your task this week is to calculate the activation energy of F diffusion in Ca$F_2$. You will need to select a temperature range and carry out simulations at different temperatures within that range. \n#### Questions to answer\n- In what temperature range is Ca$F_2$ completely solid i.e. no diffusion?\n- In what range is fluorine essentially liquid i.e. fluorine diffusion with no calcium diffusion?\n- What is the melting temperature?\n- Plot an Arrhenius plot and determine the activation energies in temperature range - You will need to rearange the equation. \n\n\nYou are encouraged to split the work up within your group and to learn how to view the simulation \"movie\" using VMD (Ask a demonstrator). VMD is a fantastic program that allows you to visualise your simulation, included below is a video showing a short snippet of an MD simulation of Ca$F_2$. A single F atom has been highlighted to show that diffusion is occuring. \n\n\n```python\n%%HTML\n<div align=\"middle\">\n</div>\n```\n\n\n<div align=\"middle\">\n</div>\n\n\nFurthermore, VMD can also be used to generate images showing the entire trajectory of the simulation, e.g.\n\n\n\n<center>\n    <br>\n    \n    <i>Figure 2. A figure showing all positions occupied by F during an MD simulation at 1500 K. F positions are shown in orange and Ca atoms are shown in green.</i>\n    <br>\n</center>\n  \n\n  To save you the time you can use the function declared at the start of this notebook to pull out a diffusion coefficient directly from the simulation output file. MSD.py is a small code to allow visualisation of the MSD plot but it is not neccesary every time you want the diffusion coefficient. \n\nIt is up to you how you organise/create your directories but it is reccomended that you start a new notebook. Use the commands/functions used in this notebook to generate your input files, run DL_POLY and extract the diffusion coefficients. The write your own code to generate an Arrhenius plot and calculate the activation energies. \nIf you finish early then feel free to start week 3. \n\n\n```python\n\n```\n", "meta": {"hexsha": "6040bbe2497ecbc37f4f3d35cf8c7c7e54122341", "size": 78007, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Week_2/Week_2.ipynb", "max_stars_repo_name": "symmy596/Bath_University_Advanced_Practical_Chemistry_Year_2", "max_stars_repo_head_hexsha": "65f846f87d97639f324c6f75f2ac0d1bedfb91d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Week_2/Week_2.ipynb", "max_issues_repo_name": "symmy596/Bath_University_Advanced_Practical_Chemistry_Year_2", "max_issues_repo_head_hexsha": "65f846f87d97639f324c6f75f2ac0d1bedfb91d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week_2/Week_2.ipynb", "max_forks_repo_name": "symmy596/Bath_University_Advanced_Practical_Chemistry_Year_2", "max_forks_repo_head_hexsha": "65f846f87d97639f324c6f75f2ac0d1bedfb91d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 153.8599605523, "max_line_length": 28844, "alphanum_fraction": 0.8736010871, "converted": true, "num_tokens": 3641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814501625211, "lm_q2_score": 0.057493277185463515, "lm_q1q2_score": 0.024951015807543244}}
{"text": "# Molecular Dynamics\n\n##### Syma Khalid\n\n\n```\nfrom IPython.core.display import HTML\ncss_file = '../ipython_notebook_styles/ngcmstyle.css'\nHTML(open(css_file, \"r\").read())\n```\n\n\n\n\n<link href='http://fonts.googleapis.com/css?family=Open+Sans:100,300,400,500,700,800,900,100italic,300italic,400italic,500italic,700italic,800italic,900italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Arvo:400,700,400italic' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=PT+Mono' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Shadows+Into+Light' rel='stylesheet' type='text/css'>\n<link href='http://fonts.googleapis.com/css?family=Nixie+One' rel='stylesheet' type='text/css'>\n<style>\n\n@font-face {\n    font-family: \"Computer Modern\";\n    src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');\n}\n\n#notebook_panel { /* main background */\n    background: rgb(245,245,245);\n}\n\ndiv.cell { /* set cell width */\n    width: 1000px;\n}\n\ndiv #notebook { /* centre the content */\n    background: #fff; /* white background for content */\n    width: 1200px;\n    margin: auto;\n    padding-left: 0em;\n}\n\n#notebook li { /* More space between bullet points */\nmargin-top:0.8em;\n}\n\n/* draw border around running cells */\ndiv.cell.border-box-sizing.code_cell.running { \n    border: 1px solid #111;\n}\n\n/* Put a solid color box around each cell and its output, visually linking them*/\ndiv.cell.code_cell {\n    background-color: rgb(256,256,256); \n    border-radius: 0px; \n    padding: 0.5em;\n    margin-left:1em;\n    margin-top: 1em;\n}\n\ndiv.text_cell_render{\n    font-family: 'Open Sans' sans-serif;\n    line-height: 140%;\n    font-size: 125%;\n    font-weight: 400;\n    width:900px;\n    margin-left:auto;\n    margin-right:auto;\n}\n\n\n/* Formatting for header cells */\n.text_cell_render h1 {\n    font-family: 'Arvo', serif;\n    font-style:regular;\n    font-weight: 400;    \n    font-size: 45pt;\n    line-height: 100%;\n    color: rgb(0,51,102);\n    margin-bottom: 0.5em;\n    margin-top: 0.5em;\n    display: block;\n}\t\n.text_cell_render h2 {\n    font-family: 'Arvo', serif;\n    font-weight: 400;\n    font-size: 30pt;\n    line-height: 100%;\n    color: rgb(0,51,102);\n    margin-bottom: 0.1em;\n    margin-top: 0.3em;\n    display: block;\n}\t\n\n.text_cell_render h3 {\n    font-family: 'Arvo', serif;\n    margin-top:16px;\n\tfont-size: 22pt;\n    font-weight: 600;\n    margin-bottom: 3px;\n    font-style: regular;\n    color: rgb(102,102,0);\n}\n\n.text_cell_render h4 {    /*Use this for captions*/\n    font-family: 'Arvo', serif;\n    font-size: 14pt;\n    text-align: center;\n    margin-top: 0em;\n    margin-bottom: 2em;\n    font-style: regular;\n}\n\n.text_cell_render h5 {  /*Use this for small titles*/\n    font-family: 'Arvo', sans-serif;\n    font-weight: 400;\n    font-size: 16pt;\n    color: rgb(163,0,0);\n    font-style: italic;\n    margin-bottom: .1em;\n    margin-top: 0.8em;\n    display: block;\n}\n\n.text_cell_render h6 { /*use this for copyright note*/\n    font-family: 'PT Mono', sans-serif;\n    font-weight: 300;\n    font-size: 9pt;\n    line-height: 100%;\n    color: grey;\n    margin-bottom: 1px;\n    margin-top: 1px;\n}\n\n.CodeMirror{\n        font-family: \"PT Mono\";\n        font-size: 90%;\n}\n\n</style>\n\n\n\n\n\n## Introduction\n\nEverything that will be done is classical; done in terms of Newtonian physics. Particles will be spherical balls, forces given by harmonic oscillator springs. This *cartoon* model is useful for quite complex situations.\n\nThe two lectures will be on\n\n* Molecular mechanics force fields (functional forms and parameterisation).\n* Energy minisation.\n* Moleculr dynamics simulations\n* Analysis and enhanced sampling methods.\n\n### Recommended reading\n\n* Leach\n* Grant and ...\n\n## Molecular mechanics\n\nMolecular mechanics is a method by which molecular systems are modelled using classical mechanics.\n\nWe want to make models to predict the behaviour of molecules (changes in their structure, and how they interact with other molecules).\n\nCan't do this in the lab thanks to cost, fiddling with underlying \"physical\" parameters (masses etc), etc.\n\n## Force-fields\n\nUnderlying model is that the *potential energy* of a molecule can be described by the *force field* using the principles of classical mechanics.\n\nFor a typical force field, the potential energy of the molecule is determined in terms of the \n\n* bond lengths\n* bond angles\n* dihedral angles\n* electrostatics\n* repulsion and dispersion\n* as well as the Cartesian co-ordinates of the atoms.\n\nTypically there's a massive *table* giving all this information\n\n**Essential** : Cartesian coordinates, and prescription for the force field.\n\nThese interactions are not just within a single molecule; *inter*-molecular forces are also important, as well as the standard *intra*-molecular forces.\n\n### Force-fields and potential energy\n\nTo formally relate potential energy to the positions of the atmos in our molecule of interest we use\n\n$$\n\\begin{equation}\n  \\vec{F} = m \\times \\vec{a}\n\\end{equation}\n$$\n\nUsing that the acceleration $\\vec{a}$ is related to the position $\\vec{r}$ as\n\n$$\n\\begin{align}\n  \\vec{a} &= \\frac{d \\vec{v}}{d t}, \\\\\n  \\vec{v} &= \\frac{d \\vec{r}}{d t} \n\\end{align}\n$$\n\nand expressing the force as the (negative) gradient of the potential energy, \n\n$$\n\\begin{equation}\n  \\vec{F} = - \\frac{d V}{d \\vec{r}},\n\\end{equation}\n$$\n\nwe can combine these results to get\n\n$$\n\\begin{equation}\n  -\\frac{d V}{d \\vec{r}_i} = m_i \\frac{d^2 \\vec{r}_i}{d t^2}.\n\\end{equation}\n$$\n\nHere $i$ is thought of as an index on the atoms making up the molecule.\n\nFor simplicity divide the foce into two parts:\n\n$$\n\\begin{equation}\n  V_{\\text{pot}} = \\sum_{\\text{bonded}} + \\sum_{\\text{non-bonded}}.\n\\end{equation}\n$$\n\nThe bonded terms include bonds, angles, dihedrals (torsions).\n\nThe non-bonded terms include permanent electrostatics, disperion and repulsion.\n\n### Bonded terms: bonds and angles\n\nUsually use a harmonic potential (decent approximation):\n\n$$\n\\begin{align}\n  E &= \\sum_{\\text{bonds}} k_b (r - r_0)^2 \\\\ E &= \\sum_{\\text{angles}} k_{\\theta} ( \\theta - \\theta_0 )^2.\n\\end{align}\n$$\n\nA Morse function (where the bond \"breaks\" after a certain length, leading to a constant potential above a certain length) would be more accurate for bond length.\n\nThe energetic penalty associated with deviating from the equilibrium has the same form for bond lengths *and* bond angles as shown above.\n\nChanging the $k_{b, \\theta}$ parameters will broaden or steepen the slope of the potential well\n\n### Bonded terms: dihedrals\n\nCannot use a simple harmonic term for dihedral angles. This is because there's multiple configurations with the same minima, and two parameters to consider.\n\nSimplest model is to use\n\n$$\n\\begin{equation}\n  E = \\sum_{\\text{dihedrals}} A \\left[ 1 + \\cos (n \\phi - \\phi_0) \\right]\n\\end{equation}\n$$\n\nThe $A$ parameter controls the amplitude of the potential, whilst the $n$ parameter controls its periodicity, and $\\phi_0$ shifts the curve along the rotation angle axis.\n\n### Non-bonded terms: dispersion and repulsion\n\nNon-bonded energy represents the pair-wise sum of the energies of all possible interacting (non-bonded) atoms $i$ and $j$. Typically use the *Lennard-Jones* potential:\n\n$$\n\\begin{equation}\n  V(r) = 4 \\epsilon \\left[ \\left( \\frac{\\sigma}{r_{ij}} \\right)^{12} - \\left( \\frac{\\sigma}{r_{ij}} \\right)^{6} \\right].\n\\end{equation}\n$$\n\nDispersion is always attractive, occurs at short range and rapidly falls off with distance.\n\nRepulsion occurs when the distance between interating atmos becomes slightly less than the sum of their contact radii.\n\nThe $\\epsilon$ term defines the \"stickiness\" of the potential. What is the optimum interaction between the two particles? Do they \"like\" to be near each other?\n\nThe $\\sigma$ term defines the size of the particles. Hard spheres cannot inter-penetrate, so the point at which the energy begins to rise steeply is the limit of the particle.\n\n### Lennard-Jones: parameters\n\nThere are (large) tables of parameters giving the values of $\\sigma$ and $\\epsilon$ for given atoms. When the atmos mix you typically use the Lorenz-Berthelot mixing rules:\n\n$$\n\\begin{align}\n  \\sigma_{AB} & = \\tfrac{1}{2} \\left( \\sigma_{AA} + \\sigma_{BB} \\right), \\\\\n  \\epsilon_{AB} & = \\sqrt{\\epsilon_{AA} \\epsilon_{AB}}.\n\\end{align}\n$$\n\n**Note**: you cannot take *one part* of a force field (eg the bond length) and mix with another part of a *different* force field (eg the non-bonded terms). They're self-consistent and come as a whole.\n\n### Non-bonded terms: permanent electrostatics\n\nEven when a molecule does not have a formal charge, because the charge distributions are not uniform the atoms have different *electronegativities*. This leads to atoms have *partial charges*. These charges are additive pairwise interactions again, *but* could be attractive *or* repulsive.\n\nTwo representations:\n\n1. Partial charges\n2. Multipole moments\n\nThe former is easier to code and explain, and more efficient to code. In this case we have\n\n$$\n\\begin{equation}\n  V = \\sum_{\\text{pairs } (i, j)} \\frac{q_i q_j}{4 \\pi \\epsilon_0 r_{ij}}.\n\\end{equation}\n$$\n\nThis is simply Coulomb's law.\n\nThis is often the most costly term in the system to solve due to the long range interactions; often the least interesting as well, but crucial.\n\nVarious ways of dealing with the long-range terms, including\n\n* Cut-off (at large distance set to a fixed value, typically not zero).\n* Reaction field (add an artificial field at large distance).\n* Ewald (most comprehensive, most complex; split the region into two parts which separately converge).\n\n## The actual simulations\n\n### Overview\n\nNeed\n\n* Suitable initial configuration of the system (usually at equilibrium).\n* Force-field\n* Simulation parameters (temperature, pressure, etc).\n\nThen\n\n* Integration of Newton's equations of motion\n\ngives as output\n\n* A collection of configurations showing the evolution of the system over the specified timescale.\n\nThis then needs to be analysed by the user.\n\n### Newton's equations of motion\n\nThe DEs from Newton's second law are solved.\n\nTrajectory that specifies hwo the positions and velocities of the atoms vary with time.\n\nEquations solved by taking a small step in time, predicting new atom positions and velocities at the end of the step.\n\nAt the new positions, re-calculate the atomic forces and take another timestep.\n\n### Finite difference methods\n\nCoupled nature of the problem, so we solve them numerically.\n\nAssume that the functions $\\vec{r}, \\vec{v}, \\vec{a}$ can be approximated using a *Taylor series* expansion\n\n$$\n\\begin{align}\n  r(t + \\delta t) & = r(t) + v(t) \\, \\delta t + \\tfrac{1}{2} a(t) \\, \\delta t^2, \\\\\n  v(t + \\delta t) & = v(t) + a(t) \\, \\delta t + \\tfrac{1}{2} b(t) \\, \\delta t^2, \\\\\n  a(t + \\delta t) & = a(t) + b(t) \\, \\delta t + \\dots\n\\end{align}\n$$\n\nThe **Verlet** and **velocity Verlet** algorithms are the most popular.\n\n### Verlet Algorithm\n\nUses the positions and accelerations at time $t$ and positions from time $t - \\delta t$ to calculate new positions at time $t + \\delta t$.\n\nThis does not use explicit velocities.\n\nAlgorithm uses the Taylor series expansion for $r$ at $t \\pm \\delta t$ which, when summed, give\n\n$$\n\\begin{equation}\n  r(t + \\delta t) + r(t - \\delta t) = 2 r(t) + a(t) \\, \\delta t^2.\n\\end{equation}\n$$\n\n**Advantages**\n\n1. Simple to code\n2. Modest memory requirements\n\n**Disadvantages**\n\n1. Imprecise\n2. Need to carry two sets of positions ($t$ and $t - \\delta t$).\n3. Velocities are not explicitly calculated, but estimated. Thus temperature is not reliably represented.\n", "meta": {"hexsha": "bfd21e9aa110373dc7c70e29d921cadf250b313c", "size": 20657, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "FEEG6016 Simulation and Modelling/2014/Molecular Dynamics Lecture 1.ipynb", "max_stars_repo_name": "ngcm/training-public", "max_stars_repo_head_hexsha": "e5a0d8830df4292315c8879c4b571eef722fdefb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-06-23T05:50:49.000Z", "max_stars_repo_stars_event_max_datetime": "2016-06-22T10:29:53.000Z", "max_issues_repo_path": "FEEG6016 Simulation and Modelling/2014/Molecular Dynamics Lecture 1.ipynb", "max_issues_repo_name": "Jhongesell/training-public", "max_issues_repo_head_hexsha": "e5a0d8830df4292315c8879c4b571eef722fdefb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-11-28T08:29:55.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-28T08:29:55.000Z", "max_forks_repo_path": "FEEG6016 Simulation and Modelling/2014/Molecular Dynamics Lecture 1.ipynb", "max_forks_repo_name": "Jhongesell/training-public", "max_forks_repo_head_hexsha": "e5a0d8830df4292315c8879c4b571eef722fdefb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2015-04-18T21:44:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-09T17:35:58.000Z", "avg_line_length": 32.1760124611, "max_line_length": 298, "alphanum_fraction": 0.4996853367, "converted": true, "num_tokens": 3152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21469141911224196, "lm_q2_score": 0.11596071214366646, "lm_q1q2_score": 0.024895769851389943}}
{"text": "```python\n# for interest, here is how I would make this a software project\n# training classifier using hugging face api (high, high level nlp)\n# then classifying script text content\n# dataset and csv are fomatted and ready to go for api (as in this sofware works)\n# will need a valid hugging face api to work- (will fail but illustrates working code) \n!python3 main.py --hugging_face --login --api_key sldkfjdummykey\n\n```\n\n    here\n    sldkfjdummykey\n    > \u001b[31m\u001b[1mERROR   \u274c Failed to authenticate. Check the passed token is valid!\u001b[0m\n    > \u001b[31m\u001b[1mERROR   \u274c Oops! Something failed in AutoNLP backend..\u001b[0m\n    > \u001b[31m\u001b[1mERROR   Error code: 401; Details: '{\"error\":\"Unauthorized\"}'\u001b[0m\n    Model trianing using autonlp (hugging face api)\n\n\n####  Here is the software verison with and args parser that I wrote as an example of using hugging face api to train a binary text classifier and an illustration of how I would approach this problem as a piece of end to end software that runs in terminal\n\n\n```python\n# to show you what the args parser -help would return of this sofware \n!python3 main.py --help\n```\n\n    usage: main.py [-h] [--input csv INPUT CSV] [--project PROJECT]\n                   [--split SPLIT] [--col_mapping COL_MAPPING] [--files FILES]\n                   [--api_key API_KEY] [--resize RESIZE] [--name NAME]\n                   [--language LANGUAGE] [--task TASK] [--max_models MAX_MODELS]\n                   [--create_project] [--hugging_face] [--send] [--login] [--make]\n                   [--train]\n    \n    Training Calssifier\n    \n    optional arguments:\n      -h, --help            show this help message and exit\n      --input csv INPUT CSV\n                            relative loacation of input csv for training\n      --project PROJECT     poject name\n      --split SPLIT         dataset split\n      --col_mapping COL_MAPPING\n                            text:text, label:target\n      --files FILES         formated csv only 2 colls one for text one for target\n      --api_key API_KEY     api key from hugging_face account\n      --resize RESIZE       Resizes images by percentage as scalar\n      --name NAME           project name hugging face\n      --language LANGUAGE   lang in eg [en,sp,fr]\n      --task TASK           Resizes images by percentage as scalar\n      --max_models MAX_MODELS\n                            nuber of trainable models\n      --create_project      create_new hf project\n      --hugging_face        uses hugging face api to train model\n      --send                if entered will try to sen .csv\n      --login               if entered will try to sen .csv\n      --make                create_new hf project\n      --train               create_new hf project\n\n\n\n```python\n#files\nimport gdown \nimport os\nimport zipfile\n\n#data \nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# utils\nfrom pathlib import Path\nimport time\nfrom tqdm import tqdm\n\n# web\nimport urllib.request\nimport requests\nfrom bs4 import BeautifulSoup\n\n# evaluation metrics\nfrom scipy import stats\nfrom scipy.spatial import distance\nfrom sklearn.metrics import matthews_corrcoef\nfrom sklearn.metrics import confusion_matrix\n```\n\n### Start time\n\n\n```python\n#starting time\ntime.strftime(\"%H:%M:%S\", time.localtime())\n```\n\n\n\n\n    '20:46:46'\n\n\n\n\n```python\n!ls\n\n```\n\n    README.md        main.py          \u001b[34mscripts_html\u001b[m\u001b[m\r\n    bechdel.ipynb    \u001b[34mpre_scraped\u001b[m\u001b[m      scripts_html.zip\r\n    classifier.py    requirments.txt  super_woman.png\r\n\n\n\n\n\n\n## **preamble**\n**bechdel criteria:**\n- 1. [x] (of film or literature) Has to have at least two women (discrete int) or $\\in \\mathbb{Z}$\n- 2. [x] Talk to each other in (continuous time) or $\\in \\mathbb{R}$\n- 3. [x] Talk about somthing other than a man (not.self) (binary) or $\\in \\mathbb{B}$ \n \n \n> here the problem is framed as one of comparing those that meet first condition with two different consecutive female first names in script segments and verifieable ground truth - that is the first condition a prediction of passing overall -- this is to gauge whether more detailed anaylis might be needed such as training an NLP classifier. \n\n\n```python\ndef get_scripts(did=None):\n    '''this funciton gets scripts using gdown from google drive zip\n    unzips and preservs file name'''\n    url = 'https://drive.google.com/drive/folders/1PWoip6Hkl-3WG9Syyd_IxOPeC-FsshDP?usp=sharing'\n    os.makedirs(did,exist_ok=True)\n    gdown.download_folder(url,output=None,quiet=False)\n    fid = Path('scripts_html.zip')\n    with zipfile.ZipFile(fid, 'r') as zip_fid:\n        zip_fid.extractall(fid.parent)\n# path to scripts \ndid = Path('pre_scraped/')\nos.makedirs(did,exist_ok=True)\nget_scripts(did)\ndid = Path('scripts_html/')\n# using path object as itterator to ge file in directory\nfids = [fid for fid in did.iterdir()]\nscripts = { }\nfor fid in tqdm(fids):\n    with open(fid,'r') as handle:\n        scripts[fid.name.strip(fid.suffix)]=BeautifulSoup(handle, 'html.parser')\n```\n\n    Retrieving folder list\n\n\n    Processing file 1sKXHb17Ah6Bl6nVMCUE--SnCGV-rvlzk scripts_html.zip\n    Building directory structure completed\n\n\n    Retrieving folder list completed\n    Building directory structure\n    Downloading...\n    From: https://drive.google.com/uc?id=1sKXHb17Ah6Bl6nVMCUE--SnCGV-rvlzk\n    To: /Users/fridades/Projects/bechdel/scripts_html.zip\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 16.1M/16.1M [00:01<00:00, 8.99MB/s]\n    Download completed\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 282/282 [00:16<00:00, 17.12it/s]\n\n\n\n```python\ndef clean(script):\n    script = [element for element in script.find_all('b')]\n   \n    script = [element.get_text() for element in script]\n \n    script = [\" \".join(element.split()) for element in script\n              if \" \".join(element.split()) !='']\n    return [element.upper() for element in script]\n\n# make dict for ease of manipulation later and if need to save as .json\nnames_dict = {script:clean(scripts[script]) for script in scripts}\nnames_dict = {key.strip(', The').upper():names_dict[key] for key in names_dict}\n#clean names and make upper\n\n```\n\n\n```python\n#get list of first names (man and woman from academic source)\nwomen_names ='https://www.cs.cmu.edu/Groups/AI/areas/nlp/corpora/names/female.txt'\nman_names = 'https://www.cs.cmu.edu/Groups/AI/areas/nlp/corpora/names/male.txt'\ngdown.download(women_names);gdown.download(man_names)\n```\n\n    Downloading...\n    From: https://www.cs.cmu.edu/Groups/AI/areas/nlp/corpora/names/female.txt\n    To: /Users/fridades/Projects/bechdel/female.txt\n    35.8kB [00:00, 58.1MB/s]                                                        \n    Downloading...\n    From: https://www.cs.cmu.edu/Groups/AI/areas/nlp/corpora/names/male.txt\n    To: /Users/fridades/Projects/bechdel/male.txt\n    20.5kB [00:00, 33.6MB/s]                                                        \n\n\n\n\n\n    'male.txt'\n\n\n\n\n```python\ndef read_text(fid):\n    '''gets names from txt removing preamble (prints)\n    prints first name converted to upper'''\n    with open(fid,'r') as hndl:\n        txt = hndl.read().splitlines()\n    preamble = txt[:5]\n    #convert all names to upper\n    txt = [name.upper() for name in txt[5:]]\n    print(preamble,'\\n', txt[1])\n    return txt\n\n# get lists\nfem_first, man_first = read_text('female.txt'), read_text('male.txt')\n```\n\n    ['# List of common female names.', '# Copyright (c) January 1991 by Mark Kantrowitz.', '# 4987 names', '# Thanks to Bill.Ross for about 1000 additional names.', '# Version 1.3 (29-MAR-94)'] \n     ABAGAEL\n    ['# List of common male names.', '# Copyright (c) January 1991 by Mark Kantrowitz.', '# 2940 names', '# Thanks to Bill Ross for about 1000 additional names.', '# Version 1.3 (29-MAR-94)'] \n     AAMIR\n\n\n\n```python\n# might take a minute to parse and compute (but less time than training an nlp model :-))\ndef bechdel_one(script_names,fems):\n    '''a generator function that yields whther or not condtion 1\n    is passed where 2 female names not the same in seqence are \n    a potential proxy for passing condition 1 of Bechdel test'''\n    for idx,name in enumerate(script_names[3:]):\n        if idx+1!=len(script_names):\n            dialoge = script_names[idx:idx+2]\n            #not the same person\n            not_solo = dialoge[0]!=dialoge[1]\n            # first person is in womens names\n            a_is_girl = dialoge[0] in fems\n            # secong perons is in womens names\n            b_is_girl = dialoge[1] in fems\n            yield all([not_solo,a_is_girl,b_is_girl])\n    \npasses_bechdel_one = {title:any(list(bechdel_one(names_dict[title],fem_first))) for title in names_dict}\n```\n\n\n```python\n# passed condition one according to boolean process\n\npasses_bechdel_one['10 THINGS I HATE ABOUT YOU']\n```\n\n\n\n\n    True\n\n\n\n\n```python\npasses_one_vector = np.array([passes_bechdel_one[key] for key in passes_bechdel_one])\n#convert bools to ints\npasses_one_vector = passes_one_vector.astype(int)\nlen(passes_one_vector)\nplt.bar(['does not pass','passes'],np.bincount(passes_one_vector))\nnp.count_nonzero(passes_one_vector)\n```\n\n\n```python\ntime.strftime(\"%H:%M:%S\", time.localtime())\n```\n\n\n\n\n    '20:48:18'\n\n\n\n####  list of film titles that pass all three conditions from bechdeltest.com (here taken as **ground truth**)\n\n\n```python\nbechdel_films = requests.get('https://bechdeltest.com/?list=all').text\n```\n\n\n```python\n bechdel_soup = BeautifulSoup(bechdel_films, 'html.parser')\n```\n\n\n```python\ncriteria = \"[There are two or more women in this movie and they talk to each other about something other than a man]\"\nfilms = bechdel_soup.find_all('a')\ntitles_that_pass = [films[idx-2].text for idx,film in enumerate(films) if criteria in str(film.contents)]\ntitles_that_pass = [title.upper().strip('THE ') for title in titles_that_pass if title !='']\nto_check = [title.strip(', The').upper() for title in list(names_dict.keys())]\nlen(to_check)\n```\n\n\n\n\n    281\n\n\n\n\n```python\n# 1*n d array (aka a vector) of those that pass all 1=pass 0=fail\npass_all_vector = np.array([i in titles_that_pass for i in to_check]).astype(int)\n```\n\n\n```python\nplt.bar(['does not pass','passes'],np.bincount(pass_all_vector))\n```\n\n\n```python\nnp.count_nonzero(pass_all_vector)\n```\n\n\n\n\n    86\n\n\n\n#### PLCC vanilla correlation coeff (can be used for binary and give phi coefficinet) to compare method used to derive condition one with ground truth (human rated unambiguous passes of Bechdel test\n$$\\begin{equation}\nr = \\frac{{}\\sum_{i=1}^{n} (x_i - \\overline{x})(y_i -\\overline{y})}{\\sqrt{\\sum_{i=1}^{n} (x_i -\\overline{x})^2(y_i - \\overline{y})^2}}\n\\label{PLCC} \n\\end{equation}$$\n\n\n```python\npearson_r, p_val = stats.pearsonr(passes_one_vector,pass_all_vector)\nf'R value = {pearson_r:.3f} P value {p_val:.3f}'\n```\n\n\n\n\n    'R value = -0.080 P value 0.183'\n\n\n\n#### Shows that not very significant prediction and that either the method of using sequential female names is not very good or that it is a poor proxy for passing the Bechdel test\n\n#### hack proof using mathews (specifically binary) PLCC vanilla correlation coeff (can be used for binary as and give phi coefficinet)\n\n$$\\begin{equation}\n    MMC = \\frac{TP\\times TN - FP \\times FN}{\\sqrt{(TP+FP)(TP+FN)(TN+FP)(TN+FN)}}\n\\end{equation}$$\n\n\n```python\nf' Mathews coef = {matthews_corrcoef(pass_all_vector,passes_one_vector):.3f}'\n```\n\n\n\n\n    ' Mathews coef = -0.080'\n\n\n\n#### however perhaps more appropriate as shows 'set similarity' is Jacard's Distance (a bit like SSIM but for binary vectors)\n$$\\begin{equation}\n    d_j(A,B) = 1-J(A,B) = \\frac{| A \\cup B| - | A \\cap B|}{| A \\cup B|}\n\\end{equation}$$\n\n\n```python\nf' Jackards Dist = {distance.jaccard(pass_all_vector,passes_one_vector):.3f}'\n```\n\n\n\n\n    ' Jackards Dist = 0.761'\n\n\n\n#### shows significant distance however about 1/3 of sample space is same \n> therefore while poor correlation (between those that pass condition 1 of bechdel and are in ground truth) ther is some promise that those that meet two fmale charachter names being used in seqece maight be good a prediction condition one but that the textuall content accounts for faliure of the Bechdel test after this (indicates that textuall analysis is needed)!!\n\n#### Show if condition of one by names method is a an accurate predictory of all three. \n\n$$\\begin{equation}\n    Accuracy = \\frac{TP+TN}{TP+TN+FP+FN}\n\\end{equation}$$\n\n\n```python\ntn, fp, fn, tp = confusion_matrix(pass_all_vector,passes_one_vector).ravel()\n\nf'accuracy = {sum([tp,tn])/sum([tn,fp,fn,tp]):.3f}'\n```\n\n\n\n\n    'accuracy = 0.399'\n\n\n\n\n```python\nmain_films = requests.get('https://imsdb.com/all-scripts.html').text\nmain_films = BeautifulSoup(main_films, 'html.parser')\n```\n\n\n```python\nscript_urls = [ ]\nfor i in main_films.find_all('a'):\n    if '/Movie Scripts/' in i['href']:\n        if i.text.strip(' ,The').upper() not in passes_bechdel_one:\n            url = 'https://imsdb.com'+str(i['href'])\n            script_urls.append(url)\n```\n\n\n```python\nscript_urls[0].split('/')[-1].strip('.html').strip(', The').upper()\n```\n\n\n\n\n    'RESERVOIR DOGS SCRIP'\n\n\n\n\n```python\n'https://imsdb.com/Movie%20Scripts/Four%20Rooms%20Script.html'\ndef get_script(parent_page):\n    '''gets script form parent html (script page \n    rather thatn script itself)'''\n    one_film = requests.get(parent_page).text\n    one_film = BeautifulSoup(one_film, 'html.parser')\n    for i in one_film.find_all('a'):\n        if 'Read' in i.text:\n            # get one script\n            one_script = requests.get(\n                'https://imsdb.com/Movie Scripts'+i['href']).text\n            return BeautifulSoup(one_script, 'html.parser')\n        \n```\n\n#### probably a bit exaggerated on the evasion of web crawl blocking but illustrates  some techniques for this\n\n\n```python\nscript_urls = np.array(script_urls)\n# random shuffle urls array so (evasion of blocking)\nnp.random.shuffle(script_urls)\nconstant = 100\n#batching scripts into 100 to take a \n#longer break of random time every 100 scrapes\nbatches = [script_urls[i-constant:i] \n           for i in range(constant,len(script_urls),constant)]\n\nnew_scripts =  { }\nfor batch in tqdm(batches):\n    # random sleep of uniform probability (evasion of blocking)\n    for url in batch:\n        #sleep_for = sum(np.random.random_sample(1))*0.5\n        # micro sleep to emulate unpredictable behaviour\n        #time.sleep(sleep_for)\n        title = url.split('/')[-1].strip('.html').strip(', The').upper()\n        # try as some pages migh be irregular/not parsed etc\n        try:\n            script = clean(get_script(url))\n            new_scripts[title]=script\n        except:\n            print(title, 'not parsed')\n```\n\n      0%|                                                     | 0/9 [00:00<?, ?it/s]\n\n    GREMLINS 2 SCRIP not parsed\n    FURY SCRIP not parsed\n    CONTACT SCRIP not parsed\n    DONNIE DARKO SCRIP not parsed\n\n\n     11%|\u2588\u2588\u2588\u2588\u2588                                        | 1/9 [00:48<06:29, 48.70s/it]\n\n    WHAT ABOUT BOB? SCRIP not parsed\n    O BROTHER WHERE ART THOU? SCRIP not parsed\n    BATMAN FOREVER SCRIP not parsed\n    BATMAN RETURNS SCRIP not parsed\n\n\n     22%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588                                   | 2/9 [01:36<05:38, 48.38s/it]\n\n    BATMAN BEGINS SCRIP not parsed\n    HARRY POTTER AND THE HALF-BLOOD PRINCE SCRIP not parsed\n    OUTBREAK SCRIP not parsed\n    EXECUTIVE DECISION SCRIP not parsed\n    HARRY POTTER AND THE GOBLET OF FIRE SCRIP not parsed\n\n\n     33%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588                              | 3/9 [02:25<04:51, 48.53s/it]\n\n    VALENTINE'S DAY SCRIP not parsed\n\n\n     44%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588                         | 4/9 [03:14<04:04, 48.85s/it]\n\n    UNFORGIVEN SCRIP not parsed\n    MATCHSTICK MEN SCRIP not parsed\n    HARRY POTTER AND THE CHAMBER OF SECRETS SCRIP not parsed\n\n\n     56%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588                    | 5/9 [04:04<03:16, 49.10s/it]\n\n    GOODFELLAS SCRIP not parsed\n    LETHAL WEAPON SCRIP not parsed\n    CASABLANCA SCRIP not parsed\n    BATMAN AND ROBIN SCRIP not parsed\n\n\n     67%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588               | 6/9 [04:54<02:28, 49.43s/it]\n\n    EYES WIDE SHUT SCRIP not parsed\n    GINGER SNAPS SCRIP not parsed\n\n\n     78%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588          | 7/9 [05:46<01:39, 50.00s/it]\n\n    WHO FRAMED ROGER RABBIT? SCRIP not parsed\n\n\n     89%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588     | 8/9 [06:33<00:49, 49.38s/it]\n\n    DARK KNIGHT, THE SCRIP not parsed\n    HARRY POTTER AND THE DEATHLY HALLOWS PART 1 SCRIP not parsed\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 9/9 [07:25<00:00, 49.46s/it]\n\n\n\n```python\nlen(new_scripts)\n```\n\n\n\n\n    866\n\n\n\n\n```python\nnew_script = {key.replace('THE SCRIP','').replace('SCRIP',''):new_scripts[key] for key in new_scripts}\n```\n\n\n```python\nall_scripts = {**names_dict, **new_script}\nprint(f'there are now {len(all_scripts)} scripts scraped')\npasses_bechdel_one = {title:any(list(bechdel_one(all_scripts[title],fem_first))) for title in all_scripts}\n```\n\n    there are now 1147 scripts scraped\n\n\n\n```python\npasses_one_vector = np.array([passes_bechdel_one[key] for key in passes_bechdel_one])\n#convert bools to ints\npasses_one_vector = passes_one_vector.astype(int)\nlen(passes_one_vector)\nplt.bar(['does not pass','passes'],np.bincount(passes_one_vector))\nnp.count_nonzero(passes_one_vector)\n```\n\n\n```python\npass_all_vector = np.array([i in titles_that_pass for i in all_scripts]).astype(int)\nplt.bar(['does not pass','passes'],np.bincount(pass_all_vector))\n```\n\n\n```python\npearson_r, p_val = stats.pearsonr(passes_one_vector,pass_all_vector)\nf'R value = {pearson_r:.3f} P value {p_val:.3f}'\n```\n\n\n\n\n    'R value = -0.022 P value 0.455'\n\n\n\n\n```python\nf' Mathews coef = {matthews_corrcoef(pass_all_vector,passes_one_vector):.3f}'\n```\n\n\n\n\n    ' Mathews coef = -0.022'\n\n\n\n\n```python\nf' Jackards Dist = {distance.jaccard(pass_all_vector,passes_one_vector):.3f}'\n```\n\n\n\n\n    ' Jackards Dist = 0.935'\n\n\n\n\n```python\ntn, fp, fn, tp = confusion_matrix(pass_all_vector,passes_one_vector).ravel()\n\nf'accuracy = {sum([tp,tn])/sum([tn,fp,fn,tp]):.3f}'\n```\n\n\n\n\n    'accuracy = 0.364'\n\n\n", "meta": {"hexsha": "520fd4efef3f94a6e08c22cb32182270eb16d816", "size": 57618, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "bechdel.ipynb", "max_stars_repo_name": "fdsig/bechdel", "max_stars_repo_head_hexsha": "dbd755687634ff07afef35619a62bddab61a833e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bechdel.ipynb", "max_issues_repo_name": "fdsig/bechdel", "max_issues_repo_head_hexsha": "dbd755687634ff07afef35619a62bddab61a833e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bechdel.ipynb", "max_forks_repo_name": "fdsig/bechdel", "max_forks_repo_head_hexsha": "dbd755687634ff07afef35619a62bddab61a833e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1120196239, "max_line_length": 6372, "alphanum_fraction": 0.7097261273, "converted": true, "num_tokens": 4972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505321516081, "lm_q2_score": 0.07921032791293581, "lm_q1q2_score": 0.024876045632960867}}
{"text": "```python\n\n```\n\n\n```python\n!pip install qiskit==0.26.2 #==0.13.0\n```\n\n    Requirement already satisfied: qiskit==0.26.2 in /usr/local/lib/python3.7/dist-packages (0.26.2)\n    Requirement already satisfied: qiskit-ibmq-provider==0.13.1 in /usr/local/lib/python3.7/dist-packages (from qiskit==0.26.2) (0.13.1)\n    Requirement already satisfied: qiskit-terra==0.17.4 in /usr/local/lib/python3.7/dist-packages (from qiskit==0.26.2) (0.17.4)\n    Requirement already satisfied: qiskit-ignis==0.6.0 in /usr/local/lib/python3.7/dist-packages (from qiskit==0.26.2) (0.6.0)\n    Requirement already satisfied: qiskit-aer==0.8.2 in /usr/local/lib/python3.7/dist-packages (from qiskit==0.26.2) (0.8.2)\n    Requirement already satisfied: qiskit-aqua==0.9.1 in /usr/local/lib/python3.7/dist-packages (from qiskit==0.26.2) (0.9.1)\n    Requirement already satisfied: requests-ntlm>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit==0.26.2) (1.1.0)\n    Requirement already satisfied: numpy>=1.13 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit==0.26.2) (1.19.5)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit==0.26.2) (0.3.3)\n    Requirement already satisfied: websockets>=8 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit==0.26.2) (9.0.2)\n    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit==0.26.2) (1.24.3)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit==0.26.2) (2.8.1)\n    Requirement already satisfied: nest-asyncio!=1.1.0,>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit==0.26.2) (1.5.1)\n    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit==0.26.2) (2.23.0)\n    Requirement already satisfied: python-constraint>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit==0.26.2) (1.4.0)\n    Requirement already satisfied: fastjsonschema>=2.10 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit==0.26.2) (2.15.1)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit==0.26.2) (5.4.8)\n    Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit==0.26.2) (2.6.0)\n    Requirement already satisfied: scipy>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit==0.26.2) (1.4.1)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit==0.26.2) (1.7.1)\n    Requirement already satisfied: ply>=3.10 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit==0.26.2) (3.11)\n    Requirement already satisfied: retworkx>=0.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit==0.26.2) (0.8.0)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ignis==0.6.0->qiskit==0.26.2) (56.1.0)\n    Requirement already satisfied: pybind11>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.8.2->qiskit==0.26.2) (2.6.2)\n    Requirement already satisfied: yfinance<=0.1.55 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit==0.26.2) (0.1.55)\n    Requirement already satisfied: quandl<=3.6.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit==0.26.2) (3.6.0)\n    Requirement already satisfied: docplex<=2.20.204; sys_platform != \"darwin\" in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit==0.26.2) (2.20.204)\n    Requirement already satisfied: h5py<=3.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit==0.26.2) (3.1.0)\n    Requirement already satisfied: dlx<=1.0.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit==0.26.2) (1.0.4)\n    Requirement already satisfied: fastdtw<=0.3.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit==0.26.2) (0.3.4)\n    Requirement already satisfied: scikit-learn<=0.24.1,>=0.20.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit==0.26.2) (0.22.2.post1)\n    Requirement already satisfied: pandas<=1.2.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit==0.26.2) (1.1.5)\n    Requirement already satisfied: ntlm-auth>=1.0.2 in /usr/local/lib/python3.7/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit==0.26.2) (1.5.0)\n    Requirement already satisfied: cryptography>=1.3 in /usr/local/lib/python3.7/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit==0.26.2) (3.4.7)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.8.0->qiskit-ibmq-provider==0.13.1->qiskit==0.26.2) (1.15.0)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit==0.26.2) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit==0.26.2) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit==0.26.2) (2020.12.5)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra==0.17.4->qiskit==0.26.2) (1.2.1)\n    Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance<=0.1.55->qiskit-aqua==0.9.1->qiskit==0.26.2) (0.0.9)\n    Requirement already satisfied: lxml>=4.5.1 in /usr/local/lib/python3.7/dist-packages (from yfinance<=0.1.55->qiskit-aqua==0.9.1->qiskit==0.26.2) (4.6.3)\n    Requirement already satisfied: inflection>=0.3.1 in /usr/local/lib/python3.7/dist-packages (from quandl<=3.6.0->qiskit-aqua==0.9.1->qiskit==0.26.2) (0.5.1)\n    Requirement already satisfied: more-itertools in /usr/local/lib/python3.7/dist-packages (from quandl<=3.6.0->qiskit-aqua==0.9.1->qiskit==0.26.2) (8.7.0)\n    Requirement already satisfied: cached-property; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from h5py<=3.1.0->qiskit-aqua==0.9.1->qiskit==0.26.2) (1.5.2)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn<=0.24.1,>=0.20.0->qiskit-aqua==0.9.1->qiskit==0.26.2) (1.0.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas<=1.2.3->qiskit-aqua==0.9.1->qiskit==0.26.2) (2018.9)\n    Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit==0.26.2) (1.14.5)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit==0.26.2) (2.20)\n\n\n\n```python\nfrom qiskit.providers.aer import QasmSimulator  \nfrom qiskit.algorithms import VQE\nfrom qiskit.algorithms.optimizers import COBYLA \nfrom qiskit.circuit.library import EfficientSU2\n# opflow is Qiskit's module for creating operators like yours\nfrom qiskit.opflow import Z, X, I  # Pauli Z, X matrices and identity\n\nh = 0.25  # or whatever value you have for h\nH = - h * ((X ^ I) + (I ^ X))\n\n# you can swap this for a real quantum device and keep the rest of the code the same!\nbackend = QasmSimulator() \n\n# COBYLA usually works well for small problems like this one\noptimizer = COBYLA(maxiter=200)\n\n# EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library\nansatz = EfficientSU2(2, reps=1)\n\n# set the algorithm\nvqe = VQE(ansatz, optimizer, quantum_instance=backend)\n\n# run it with the Hamiltonian we defined above\nresult = vqe.compute_minimum_eigenvalue(H)  \n\n# print the result (it contains lot's of information)\nprint(result) \n```\n\n    {   'aux_operator_eigenvalues': None,\n        'cost_function_evals': 93,\n        'eigenstate': {   '00': 0.4881406047441659,\n                          '01': 0.5067898356320892,\n                          '10': 0.49311668243935936,\n                          '11': 0.5115845482420281},\n        'eigenvalue': -0.49951171875,\n        'optimal_parameters': {   ParameterVectorElement(\u03b8[5]): -0.005963564918571073,\n                                  ParameterVectorElement(\u03b8[6]): 3.4679057346080238,\n                                  ParameterVectorElement(\u03b8[7]): 0.06761013048071884,\n                                  ParameterVectorElement(\u03b8[3]): -0.037457635289982194,\n                                  ParameterVectorElement(\u03b8[4]): -2.4785608272501425,\n                                  ParameterVectorElement(\u03b8[1]): 1.5543178794741934,\n                                  ParameterVectorElement(\u03b8[2]): 0.44253663321918507,\n                                  ParameterVectorElement(\u03b8[0]): 0.9563573926735457},\n        'optimal_point': array([ 0.95635739,  1.55431788,  0.44253663, -0.03745764, -2.47856083,\n           -0.00596356,  3.46790573,  0.06761013]),\n        'optimal_value': -0.49951171875,\n        'optimizer_evals': 93,\n        'optimizer_time': 0.4424128532409668}\n\n", "meta": {"hexsha": "f29577efe3908dd0d5c3a1aca6b414020debbfcd", "size": 12199, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "research/rough-work-misc/kinetic_ising_draft.ipynb", "max_stars_repo_name": "arnavdas88/QuGlassyIsing", "max_stars_repo_head_hexsha": "6b6514d58646130c03619aebefb9f9aed4e5646a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-19T16:06:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T17:03:31.000Z", "max_issues_repo_path": "research/rough-work-misc/kinetic_ising_draft.ipynb", "max_issues_repo_name": "IshmamShah/QuGlassyIsing", "max_issues_repo_head_hexsha": "6c3ff2ebd77ed9b34a0e731083f1e56b7eacb7ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "research/rough-work-misc/kinetic_ising_draft.ipynb", "max_forks_repo_name": "IshmamShah/QuGlassyIsing", "max_forks_repo_head_hexsha": "6c3ff2ebd77ed9b34a0e731083f1e56b7eacb7ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-19T16:06:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T06:51:18.000Z", "avg_line_length": 72.6130952381, "max_line_length": 210, "alphanum_fraction": 0.5970981228, "converted": true, "num_tokens": 3424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658972248186, "lm_q2_score": 0.06754669254743426, "lm_q1q2_score": 0.024761923275531447}}
{"text": "## California wildfires 2017 - Thomas Fire analysis\n\nThe Thomas Fire was a massive wildfire that started in early December 2017 in Ventura and Santa Barbara counties and grew into California's largest fire ever.\n\n\n\n\n```python\nfrom arcgis import *\nfrom arcgis.mapping import MapImageLayer\n```\n\n\n```python\ngis = GIS(\"https://python.playground.esri.com/portal\", \"arcgis_python\", \"amazing_arcgis_123\") \n```\n\n## Visualize the extent of damage\n\n\n```python\nfrom ipywidgets import *\n\npostfire = MapImageLayer('https://tiles.arcgis.com/tiles/DO4gTjwJVIJ7O9Ca/arcgis/rest/services/Digital_Globe_Imagery_Dec_11th/MapServer')\n\ndef side_by_side(address):\n    location = geocode(address)[0]\n\n    satmap1 = gis.map(location)\n    satmap1.basemap = 'satellite'\n\n    satmap2 = gis.map(location)\n    satmap2.add_layer(postfire)\n\n    satmap1.layout=Layout(flex='1 1', padding='6px')\n    satmap2.layout=Layout(flex='1 1', padding='6px')\n\n    box = HBox([satmap1, satmap2])\n    return box\n```\n\n### Nob Hill, Ventura, CA\n\n\n```python\nside_by_side('Montclair Dr, Ventura, CA')\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>HBox</code>.</p>\n<p>\n  If you're reading this message in Jupyter Notebook or JupyterLab, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another notebook frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n### Vista Del Mar Hospital, Ventura, CA\n\n\n```python\nside_by_side('801 Seneca St, Ventura, CA 93001')\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>HBox</code>.</p>\n<p>\n  If you're reading this message in Jupyter Notebook or JupyterLab, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another notebook frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n## Remote Sensing and Image Processing\n\n\n```python\nlandsat_item = gis.content.search('title:Multispectral Landsat', 'Imagery Layer', outside_org=True)[0]\nlandsat = landsat_item.layers[0]\nlandsat_item\n```\n\n\n\n\n<div class=\"item_container\" style=\"height: auto; overflow: hidden; border: 1px solid #cfcfcf; border-radius: 2px; background: #f6fafa; line-height: 1.21429em; padding: 10px;\">\n                    <div class=\"item_left\" style=\"width: 210px; float: left;\">\n                       <a href='https://pythonapi.playground.esri.com/portal/home/item.html?id=d9b466d6a9e647ce8d1dd5fe12eb434b' target='_blank'>\n                        \n                       </a>\n                    </div>\n\n                    <div class=\"item_right\"     style=\"float: none; width: auto; overflow: hidden;\">\n                        <a href='https://pythonapi.playground.esri.com/portal/home/item.html?id=d9b466d6a9e647ce8d1dd5fe12eb434b' target='_blank'><b>Multispectral Landsat</b>\n                        </a>\n                        <br/>Landsat 8 OLI, 30m Multispectral 8 band scenes with visual renderings and indices. Updated daily. Based on the Landsat on AWS collections.Imagery Layer by esri_livingatlas\n                        <br/>Last Modified: October 12, 2017\n                        <br/>0 comments, 0 views\n                    </div>\n                </div>\n\n\n\n\n### Select before and after rasters\n\n\n```python\naoi = {'spatialReference': {'latestWkid': 3857, 'wkid': 102100}, 'type': 'extent', \n       'xmax': -13305000, 'xmin': -13315000, 'ymax': 4106000, 'ymin': 4052000}\narcgis.env.analysis_extent = {\"xmin\":-13337766,\"ymin\":4061097,\"xmax\":-13224868,\"ymax\":4111469,\n                              \"spatialReference\":{\"wkid\":102100,\"latestWkid\":3857}}\nlandsat.extent = aoi\n```\n\n\n```python\nimport pandas as pd\nfrom datetime import datetime\n\nselected = landsat.filter_by(where=\"(Category = 1)\",\n                             time=[datetime(2017, 11, 15), datetime(2018, 1, 1)],\n                             geometry=arcgis.geometry.filters.intersects(aoi))\n\ndf = selected.query(out_fields=\"AcquisitionDate, GroupName, CloudCover, DayOfYear\", order_by_fields=\"AcquisitionDate\").df\ndf['AcquisitionDate'] = pd.to_datetime(df['AcquisitionDate'], unit='ms')\ndf.tail()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>AcquisitionDate</th>\n      <th>CloudCover</th>\n      <th>DayOfYear</th>\n      <th>GroupName</th>\n      <th>OBJECTID</th>\n      <th>Shape_Area</th>\n      <th>Shape_Length</th>\n      <th>SHAPE</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>2017-11-23 18:34:42.440</td>\n      <td>0.0441</td>\n      <td>327</td>\n      <td>LC80420362017327LGN00_MTL</td>\n      <td>591810</td>\n      <td>5.131484e+10</td>\n      <td>906509.716682</td>\n      <td>{'rings': [[[-13208036.3849, 4199102.123899996...</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2017-12-09 18:34:39.504</td>\n      <td>0.2136</td>\n      <td>343</td>\n      <td>LC80420362017343LGN00_MTL</td>\n      <td>599875</td>\n      <td>5.127378e+10</td>\n      <td>906136.246386</td>\n      <td>{'rings': [[[-13208251.4004, 4199098.6241], [-...</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2017-12-25 18:34:42.003</td>\n      <td>0.6529</td>\n      <td>359</td>\n      <td>LC80420362017359LGN00_MTL</td>\n      <td>607727</td>\n      <td>5.129089e+10</td>\n      <td>906293.823931</td>\n      <td>{'rings': [[[-13210387.2213, 4199063.157099999...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nprefire = landsat.filter_by('OBJECTID=591810') # 2017-11-23 \nmidfire = landsat.filter_by('OBJECTID=599875') # 2017-12-09 \n```\n\n## Visual Assessment\n\n\n```python\nfrom arcgis.raster.functions import *\n\napply(midfire, 'Natural Color with DRA')\n```\n\n\n\n\n    \n\n    \n\n\n\n### Visualize Burn Scars\n\nExtract the [6, 4, 1] bands to improve visibility of fire and burn scars. This band combination pushes further into the SWIR range of the electromagnetic spectrum, where there is less susceptibility to smoke and haze generated by a burning fire.\n\n\n```python\nextract_band(midfire, [6,4,1])\n```\n\n\n\n\n    \n\n    \n\n\n\n\n```python\nextract_band(prefire, [6,4,1])\n```\n\n\n\n\n    \n\n    \n\n\n\nFor comparison, the same area before the fire started shows no burn scar.\n\n## Quantitative Assessment\n\nThe **Normalized Burn Ratio (NBR)** can be used to delineate the burnt areas and identify the severity of the fire. \n\nThe formula for the NBR is very similar to that of NDVI except that it uses near-infrared band 5 and the short-wave infrared band 7:\n\\begin{align}\n{\\mathbf{NBR}} = \\frac{\\mathbf{B_5} - \\mathbf{B_7}}{\\mathbf{B_5} + \\mathbf{B_7}} \\\\   \n\\end{align}\n\nThe NBR equation was designed to be calcualted from reflectance, but it can be calculated from radiance and digital_number_(dn) with changes to the burn severity table below. \n\nFor a given area, NBR is calculated from an image just prior to the burn and a second NBR is calculated for an image immediately following the burn. Burn extent and severity is judged by taking the difference between these two index layers:\n\n\\begin{align}\n{\\Delta \\mathbf{NBR}} = \\mathbf{NBR_{prefire}} - \\mathbf{NBR_{postfire}} \\\\   \n\\end{align}\n\nThe meaning of the \u2206NBR values can vary by scene, and interpretation in specific instances should always be based on some field assessment. However, the following table from the USGS FireMon program can be useful as a first approximation for interpreting the NBR difference:\n\n\n| \\begin{align}{\\Delta \\mathbf{NBR}}  \\end{align}      | Burn Severity |\n| ------------- |:-------------:|\n| 0.1 to 0.27   | Low severity burn |\n| 0.27 to 0.44  | Medium severity burn |\n| 0.44 to 0.66 | Moderate severity burn |\n| > 0.66 | High severity burn |\n\n[Source: http://wiki.landscapetoolbox.org/doku.php/remote_sensing_methods:normalized_burn_ratio]\n\n### Use Band Arithmetic and Map Algebra \n\n\n```python\nnbr_prefire  = band_arithmetic(prefire, \"(b5 - b7) / (b5 + b7)\")\nnbr_postfire = band_arithmetic(midfire, \"(b5 - b7) / (b5 + b7)\")\n\nnbr_diff = nbr_prefire - nbr_postfire\n```\n\n\n```python\nburnt_areas = colormap(remap(nbr_diff,\n                             input_ranges=[0.1,  0.27,  # low severity \n                                           0.27, 0.44,  # medium severity\n                                           0.44, 0.66,  # moderate severity\n                                           0.66, 1.00], # high severity burn\n                             output_values=[1, 2, 3, 4],                    \n                             no_data_ranges=[-1, 0.1], astype='u8'), \n                       colormap=[[4, 0xFF, 0xC3, 0], [3, 0xFA, 0x8E, 0], [2, 0xF2, 0x55, 0], [1, 0xE6, 0,    0]])\n```\n\n\n```python\nburnt_areas.draw_graph()\n```\n\n\n\n\n    \n\n    \n\n\n\n### Area calculation\n\n\n```python\next = {\"xmax\": -13246079.10806628, \"ymin\": 4035733.9433013694, \"xmin\": -13438700.419344831, \"ymax\": 4158033.188557592,\n       \"spatialReference\": {\"wkid\": 102100, \"latestWkid\": 3857}, \"type\": \"extent\"}\npixx = (ext['xmax'] - ext['xmin']) / 1200.0\npixy = (ext['ymax'] - ext['ymin']) / 450.0\n\nres = burnt_areas.compute_histograms(ext, pixel_size={'x':pixx, 'y':pixy})\n\nnumpix = 0\nhistogram = res['histograms'][0]['counts'][1:]\nfor i in histogram:\n    numpix += i\n```\n\n### Report burnt area\n\n\n```python\nfrom IPython.display import HTML\nsqmarea = numpix * pixx * pixy # in sq. m\nacres = 0.00024711 * sqmarea   # in acres\n\nHTML('<h3>Thomas fire has consumed <i>{:,} acres</i>  till {}</h3>.'.format(int(acres), df.iloc[-1]['AcquisitionDate'].date()))\n```\n\n\n\n\n<h3>Thomas fire has consumed <i>229,304 acres</i>  till 2017-12-25</h3>.\n\n\n\n\n```python\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nplt.title('Distribution by severity', y=-0.1)\nplt.pie(histogram, labels=['Low Severity', 'Medium Severity', 'Moderate Severity', 'High Severity']);\nplt.axis('equal');\n```\n\n### Visualize burnt areas\n\n\n```python\nm = gis.map('Carpinteria, CA', zoomlevel=10)\nm\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>MapView</code>.</p>\n<p>\n  If you're reading this message in Jupyter Notebook or JupyterLab, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another notebook frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n\n```python\nm.add_layer([midfire, burnt_areas])\n```\n\n## Raster to Feature layer conversion\n\nUse Raster Analytics and Geoanalytics to convert the burnt area raster to a feature layer. The `to_features()` method converts the raster to a feature layer and `create_buffers()` fills holes in the features and dissolves them to output one feature that covers the extent of the Thomas Fire.\n\n\n```python\nfrom arcgis.geoanalytics.use_proximity import create_buffers\n\nfire_item = burnt_areas.to_features(output_name='ThomasFire_Boundary')\n\nfire_layer = fire_item.layers[0]\nfire_layer.filter = 'st_area_sh > 3000000'\n\nfire = create_buffers(lyr, 100, 'Meters', dissolve_option='All', multipart=True, output_name='ThomasFire')\n```\n\n\n```python\nfire = gis.content.search('Thomas_Fire', 'Feature Layer')[0]\nfire\n```\n\n\n\n\n<div class=\"item_container\" style=\"height: auto; overflow: hidden; border: 1px solid #cfcfcf; border-radius: 2px; background: #f6fafa; line-height: 1.21429em; padding: 10px;\">\n                    <div class=\"item_left\" style=\"width: 210px; float: left;\">\n                       <a href='https://pythonapi.playground.esri.com/portal/home/item.html?id=7f05c4cdc33b49a0a586960f52169679' target='_blank'>\n                        \n                       </a>\n                    </div>\n\n                    <div class=\"item_right\"     style=\"float: none; width: auto; overflow: hidden;\">\n                        <a href='https://pythonapi.playground.esri.com/portal/home/item.html?id=7f05c4cdc33b49a0a586960f52169679' target='_blank'><b>Thomas Fire</b>\n                        </a>\n                        <br/>Feature Layer Collection by rohitgeo\n                        <br/>Last Modified: February 28, 2018\n                        <br/>0 comments, 0 views\n                    </div>\n                </div>\n\n\n\n\n\n```python\nvectormap = gis.map('Carpinteria, CA', zoomlevel=10)\nvectormap.basemap = 'dark-gray'\nvectormap.add_layer(fire)\n\nvectormap\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>MapView</code>.</p>\n<p>\n  If you're reading this message in Jupyter Notebook or JupyterLab, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another notebook frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n## Impact Assessment\n\n### Compute infrastructure and human impact\n\n\n```python\nfrom arcgis.geoenrichment import enrich\nfrom arcgis.features import SpatialDataFrame\n\nsdf = SpatialDataFrame.from_layer(fire.layers[0])\n\nfire_geometry = sdf.iloc[0].SHAPE\nsa_filter = geometry.filters.intersects(geometry=fire_geometry, sr=4326)\n\nsecondary_roads_layer = FeatureLayer(\"https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/Transportation_LargeScale/MapServer/1\")\nsecondary_roads = secondary_roads_layer.query(geometry_filter=sa_filter, out_sr=4326)\n\nlocal_roads_layer = FeatureLayer(\"https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/Transportation_LargeScale/MapServer/2\")\nlocal_roads = local_roads_layer.query(geometry_filter=sa_filter, out_sr=4326)\n\ndef age_pyramid(df):\n    import warnings\n    import seaborn as sns\n    import matplotlib.pyplot as plt\n\n    %matplotlib inline\n    warnings.simplefilter(action='ignore', category=FutureWarning)\n    pd.options.mode.chained_assignment = None \n    plt.style.use('ggplot')\n\n    df = df[[x for x in impacted_people.columns if 'MALE' in x or 'FEM' in x]]\n    sf = pd.DataFrame(df.sum())\n    sf['age'] = sf.index.str.extract('(\\d+)').astype('int64')\n\n    f = sf[sf.index.str.startswith('FEM')]\n    m = sf[sf.index.str.startswith('MALE')]\n    f = f.sort_values(by='age', ascending=False).set_index('age')\n    m = m.sort_values(by='age', ascending=False).set_index('age')\n\n    popdf = pd.concat([f, m], axis=1)\n    popdf.columns = ['F', 'M']\n    popdf['agelabel'] = popdf.index.map(str) + ' - ' + (popdf.index+4).map(str)\n    popdf.M = -popdf.M\n    \n    sns.barplot(x=\"F\", y=\"agelabel\", color=\"#CC6699\", label=\"Female\", data=popdf, edgecolor='none')\n    sns.barplot(x=\"M\",  y=\"agelabel\", color=\"#008AB8\", label=\"Male\",   data=popdf,  edgecolor='none')\n    plt.ylabel('Age group')\n    plt.xlabel('Number of people');\n    return plt;\n```\n\n### Visualize affected roads on map\n\n\n```python\nimpactmap = gis.map('Carpinteria, CA', zoomlevel=10)\nimpactmap.basemap = 'streets'\n\nimpactmap\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>MapView</code>.</p>\n<p>\n  If you're reading this message in Jupyter Notebook or JupyterLab, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another notebook frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n\n```python\nimpactmap.draw([local_roads, secondary_roads])\n```\n\n### Age Pyramid of affected population\n\n\n```python\nimpacted_people = enrich(sdf, 'Age')\nage_pyramid(impacted_people);\n```\n\n\n", "meta": {"hexsha": "75384ed301b0a92af1925fa4e072d4f1985c1f6b", "size": 426965, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "samples/04_gis_analysts_data_scientists/california_wildfires_2017_thomas_fire_analysis.ipynb", "max_stars_repo_name": "2016102050016/arcgis-python-api", "max_stars_repo_head_hexsha": "abc30102cb2f665870aad9288fa3cb72ff2f1206", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-18T09:56:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-18T09:56:01.000Z", "max_issues_repo_path": "samples/04_gis_analysts_data_scientists/california_wildfires_2017_thomas_fire_analysis.ipynb", "max_issues_repo_name": "KLabp/arcgis-python-api", "max_issues_repo_head_hexsha": "abc30102cb2f665870aad9288fa3cb72ff2f1206", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "samples/04_gis_analysts_data_scientists/california_wildfires_2017_thomas_fire_analysis.ipynb", "max_forks_repo_name": "KLabp/arcgis-python-api", "max_forks_repo_head_hexsha": "abc30102cb2f665870aad9288fa3cb72ff2f1206", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-11T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-11T14:23:50.000Z", "avg_line_length": 389.9223744292, "max_line_length": 125929, "alphanum_fraction": 0.9255746958, "converted": true, "num_tokens": 4797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.06754668832401889, "lm_q1q2_score": 0.024761922662137198}}
{"text": "\\title{Diode Connected MOSFET Tobology}\n\\author{Steven K Armour}\n\\maketitle\n\n<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\" style=\"margin-top: 1em;\"><ul class=\"toc-item\"><li><span><a href=\"#Background\" data-toc-modified-id=\"Background-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Background</a></span></li><li><span><a href=\"#References--(Need-to-Finish)\" data-toc-modified-id=\"References--(Need-to-Finish)-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>References  (Need to Finish)</a></span></li><li><span><a href=\"#Imports\" data-toc-modified-id=\"Imports-3\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>Imports</a></span></li><li><span><a href=\"#Diode-Connected-NMOS\" data-toc-modified-id=\"Diode-Connected-NMOS-4\"><span class=\"toc-item-num\">4&nbsp;&nbsp;</span>Diode Connected NMOS</a></span><ul class=\"toc-item\"><li><span><a href=\"#Square-Law-Theory\" data-toc-modified-id=\"Square-Law-Theory-4.1\"><span class=\"toc-item-num\">4.1&nbsp;&nbsp;</span>Square Law Theory</a></span><ul class=\"toc-item\"><li><span><a href=\"#Simplified-Analysis\" data-toc-modified-id=\"Simplified-Analysis-4.1.1\"><span class=\"toc-item-num\">4.1.1&nbsp;&nbsp;</span>Simplified Analysis</a></span></li><li><span><a href=\"#Full-Analysis\" data-toc-modified-id=\"Full-Analysis-4.1.2\"><span class=\"toc-item-num\">4.1.2&nbsp;&nbsp;</span>Full Analysis</a></span></li><li><span><a href=\"#Difference-Between-Simplified-and-Full-analysis\" data-toc-modified-id=\"Difference-Between-Simplified-and-Full-analysis-4.1.3\"><span class=\"toc-item-num\">4.1.3&nbsp;&nbsp;</span>Difference Between Simplified and Full analysis</a></span></li><li><span><a href=\"#Diode-Connected-as-a-Topology-Slice\" data-toc-modified-id=\"Diode-Connected-as-a-Topology-Slice-4.1.4\"><span class=\"toc-item-num\">4.1.4&nbsp;&nbsp;</span>Diode Connected as a Topology Slice</a></span></li></ul></li><li><span><a href=\"#SPICE-Diode-Connected-NMOS\" data-toc-modified-id=\"SPICE-Diode-Connected-NMOS-4.2\"><span class=\"toc-item-num\">4.2&nbsp;&nbsp;</span>SPICE Diode Connected NMOS</a></span><ul class=\"toc-item\"><li><span><a href=\"#SPICE-analysis-of-TSMC-180nm-Diode-Connected-NMOS\" data-toc-modified-id=\"SPICE-analysis-of-TSMC-180nm-Diode-Connected-NMOS-4.2.1\"><span class=\"toc-item-num\">4.2.1&nbsp;&nbsp;</span>SPICE analysis of TSMC 180nm Diode Connected NMOS</a></span></li><li><span><a href=\"#SPICE-Confirmation-of-Topology-Interpretation\" data-toc-modified-id=\"SPICE-Confirmation-of-Topology-Interpretation-4.2.2\"><span class=\"toc-item-num\">4.2.2&nbsp;&nbsp;</span>SPICE Confirmation of Topology Interpretation</a></span></li><li><span><a href=\"#Testing-the-frequency-dependence-of-the-Bias-point\" data-toc-modified-id=\"Testing-the-frequency-dependence-of-the-Bias-point-4.2.3\"><span class=\"toc-item-num\">4.2.3&nbsp;&nbsp;</span>Testing the frequency dependence of the Bias point</a></span></li></ul></li></ul></li><li><span><a href=\"#Diode-Connected-PMOS\" data-toc-modified-id=\"Diode-Connected-PMOS-5\"><span class=\"toc-item-num\">5&nbsp;&nbsp;</span>Diode Connected PMOS</a></span><ul class=\"toc-item\"><li><span><a href=\"#Square-Law-Theory\" data-toc-modified-id=\"Square-Law-Theory-5.1\"><span class=\"toc-item-num\">5.1&nbsp;&nbsp;</span>Square Law Theory</a></span><ul class=\"toc-item\"><li><span><a href=\"#Simplifed\" data-toc-modified-id=\"Simplifed-5.1.1\"><span class=\"toc-item-num\">5.1.1&nbsp;&nbsp;</span>Simplifed</a></span></li></ul></li></ul></li><li><span><a href=\"#I-will-finish-this-later\" data-toc-modified-id=\"I-will-finish-this-later-6\"><span class=\"toc-item-num\">6&nbsp;&nbsp;</span>I will finish this later</a></span></li></ul></div>\n\n# Background\nThe Diode connected Mosfet is one of the four single Mosfet topologies (the others being CS, CD, CG) where the Mosfets gate is connected to its drain (for both NMOS and PMOS) thereby forcing it to behave much like a Diode till certain compliance voltage is reached. This compliance voltage is similar to the Diodes threshold voltage and where beyond this point the MOSFET will no longer conduct current at meaningful amounts. \n\nThe usage of diode-connected MOSFETs is important not only in creating a pseudo Diode to then recreate notable diode topologies such as Half and Full wave rectifiers. But are also used like diodes in waveform shaping and biasing to eliminate resistors where possible at the ASIC level. The two most common first exposure to diode-connected MOSFETs come by way of the  Saturated Enhancement loaded inverters in Digital MOSFETs topologies and in biasing and the current reference of current mirrors in Analog Mosfet topologies.    \n\n(insert images)\n\n# References  (Need to Finish)\n\n# Imports\n\n\n```python\nfrom sympy import *\ninit_printing()\n\nimport numpy as np\nimport pandas as pd\nfrom itertools import product as IProd\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\n%matplotlib inline\n```\n\n\n```python\nimport nbimporter\nnbimporter.options['only_defs'] = False\nfrom SympyMOSModels import *\n```\n\n    Importing Jupyter notebook from SympyMOSModels.ipynb\n\n\n\n```python\nfrom PySpice.Probe.Plot import plot\nfrom PySpice.Spice.Library import SpiceLibrary\nfrom PySpice.Spice.Netlist import Circuit\nfrom PySpice.Unit import *\n\nlibraries_path = 'SpiceLib/'\nspice_library = SpiceLibrary(libraries_path)\n```\n\n# Diode Connected NMOS\n(Insert Image)\n\n## Square Law Theory \n\nThe Diode Connected NMOS is defined as the $V_{GS}=V_{DS}$ made possible by the connection of the gate to the drain. And in this analysis we will assume that the body voltage is not in play.\n\n\n```python\nVD, VS=symbols('V_D, V_S')\n```\n\n### Simplified Analysis\nIn the simplified analysis, we forgo the channel length modulation effect. And we proceed with the analysis of the NMOS via expanding $V_{DS}=V_D-V_S$ where we affix the $V_D$.\n\nIn the simplified analysis, we forgo the channel length modulation effect. And we proceed with the analysis of the NMOS via expanding $V_{DS}=V_D-V_S$ where we affix the $V_D$.\n\n\n```python\nNIdSimpDiodConected=simplify(NMOS.IdSimp(subs={VGS:VDS}))\nNIdSimpDiodConected\n```\n\n\n```python\nNIdSimpDiodConected=NIdSimpDiodConected.subs(VDS, VD-VS)\nNIdSimpDiodConected\n```\n\nThe following example values for a greater than $1\\mu m$ device are based on example 19.1 load NMOS from chapter 19 of reference DeMassa \n\n\n```python\nsubsN={W:5e6,L:15e6, nTechConst:20e-6, Vnth:1.1, VnA:1/.02, VD:5}\n```\n\n\n```python\nNIdSimpDiodConectedN=lambdify(VS, NIdSimpDiodConected.subs(subsN), dummify=False)\nNIdSimpDiodConectedN(3.3)\n```\n\n\n\n\n    array(1.199999999999999e-06)\n\n\n\n\n```python\nVSN=np.linspace(0, 5)\n```\n\n\n```python\nVSN=np.linspace(0, 5)\nNIdSimpDiodData=pd.DataFrame()\nNIdSimpDiodData['Vs[V]']=VSN\nNIdSimpDiodData['Id[A]']=NIdSimpDiodConectedN(VSN)\nNIdSimpDiodData['DIdDVs[OhmInv]']=np.gradient(NIdSimpDiodData['Id[A]'], NIdSimpDiodData['Vs[V]'])\nNIdSimpDiodData['DDIdDDVs']=np.gradient(NIdSimpDiodData['DIdDVs[OhmInv]'], NIdSimpDiodData['Vs[V]'])\nNIdSimpDiodData['DDDIdDDDVs']=np.gradient(NIdSimpDiodData['DDIdDDVs'], NIdSimpDiodData['Vs[V]'])\nNIdSimpDiodData.describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Vs[V]</th>\n      <th>Id[A]</th>\n      <th>DIdDVs[OhmInv]</th>\n      <th>DDIdDDVs</th>\n      <th>DDDIdDDDVs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>50.000000</td>\n      <td>5.000000e+01</td>\n      <td>5.000000e+01</td>\n      <td>50.000000</td>\n      <td>5.000000e+01</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>2.500000</td>\n      <td>1.342977e-05</td>\n      <td>-1.019380e-05</td>\n      <td>0.000005</td>\n      <td>-4.900000e-07</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>1.487488</td>\n      <td>1.560910e-05</td>\n      <td>8.736476e-06</td>\n      <td>0.000003</td>\n      <td>5.995389e-06</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n      <td>-2.565986e-05</td>\n      <td>0.000000</td>\n      <td>-2.410473e-05</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>1.250000</td>\n      <td>8.150771e-08</td>\n      <td>-1.766667e-05</td>\n      <td>0.000004</td>\n      <td>-4.201283e-19</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>2.500000</td>\n      <td>6.542010e-06</td>\n      <td>-9.333333e-06</td>\n      <td>0.000007</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>3.750000</td>\n      <td>2.341484e-05</td>\n      <td>-1.000000e-06</td>\n      <td>0.000007</td>\n      <td>3.320369e-19</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>5.000000</td>\n      <td>5.070000e-05</td>\n      <td>0.000000e+00</td>\n      <td>0.000007</td>\n      <td>1.633333e-05</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nNVCompSimpLoc=np.where(NIdSimpDiodData['DDDIdDDDVs']==NIdSimpDiodData['DDDIdDDDVs'].min())[0][0]\nNVCompSimp=NIdSimpDiodData['Vs[V]'][NVCompSimpLoc]\nprint(f'NMOS Simp Square Law Complince Voltage ={NVCompSimp:.3f}[V]')\n\n```\n\n    NMOS Simp Square Law Complince Voltage =3.878[V]\n\n\n\n```python\nfig, [axId, axDId, axDDId, axDDDId]=plt.subplots(ncols=1, nrows=4, sharex=True)\nNIdSimpDiodData.plot(ax=axId, x='Vs[V]', y='Id[A]', legend=False)\naxId.axvline(x=NVCompSimp, linestyle='--', color='y', \n             label=f'VComp={NVCompSimp:.3f}[V]')\n\naxId.set_ylabel('$I_d[A]$')\naxId.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))\naxId.grid()\n\nbox = axId.get_position()\naxId.set_position([box.x0, box.y0, box.width * 0.8, box.height])\naxId.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n\nNIdSimpDiodData.plot(ax=axDId, x='Vs[V]', y='DIdDVs[OhmInv]', legend=False)\naxDId.axvline(x=NVCompSimp, linestyle='--', color='y')\n\naxDId.set_ylabel(r'$g_m[\\Omega^{-1}]$')\naxDId.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))\naxDId.grid()\n\n\nNIdSimpDiodData.plot(ax=axDDId, x='Vs[V]', y='DDIdDDVs', legend=False)\naxDDId.axvline(x=NVCompSimp, linestyle='--', color='y')\n\naxDDId.set_ylabel('$\\dfrac{\\partial^2 I_d}{\\partial V_{S}^2}$')\naxDDId.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))\naxDDId.grid()\n\n\n\n\nNIdSimpDiodData.plot(ax=axDDDId, x='Vs[V]', y='DDDIdDDDVs', legend=False)\naxDDDId.axvline(x=NVCompSimp, linestyle='--', color='y')\n\naxDDDId.set_ylabel('$\\dfrac{\\partial^3 I_d}{\\partial V_{S}^3}$')\naxDDDId.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))\naxDDDId.set_xlabel('$V_s[V]$')\naxDDDId.grid()\n\nfig.subplots_adjust(hspace=.5)\nplt.suptitle('NMOS Diode $I_d$ Simplifed ');\n\n```\n\nIn the above graph, the substitutions were made to our simple model and `lambdify` was utilized to create a numerical version of the symbolic model of a greater than $1\\mu m$ Diode connected NMOS device. As well be seen later the transconductance ($g_m$) dictates the behavior of the Diode Connected NMOS. And as the differential voltage $V_{DS}$ becomes less, remember $V_D$ is fixed the conductance of the Diode Connect NMOS drops before shutting off much like that of an ordinary rectifying diode as the voltage differential between its terminals approaches the Diodes threshold voltage. Unlike the Diode, this voltage is typically referred to as the compliance voltage. Where we by examining up to the third derivative of the $I_d$ we respect to the changing $V_s$ we can ascertain the compliance voltage exactly (within the scope of the model)\n\n### Full Analysis\nIn this full analysis, the Channel Length Modulation effect $\\dfrac{V_{DS}}{V_A}$ is not ignored and proceed through the analysis as was done in the Simplified Analysis\n\n\n```python\nNIdFullDiodConected=simplify(NMOS.IdFull(subs={VGS:VDS}))\nNIdFullDiodConected\n```\n\n\n```python\nNIdFullDiodConected=NIdFullDiodConected.subs(VDS, VD-VS)\nNIdFullDiodConected\n```\n\n\n```python\nNIdFullDiodConectedN=lambdify(VS, NIdFullDiodConected.subs(subsN), dummify=False)\nNIdFullDiodConectedN(3.3)\n```\n\n\n\n\n    array(1.2408000000000009e-06)\n\n\n\n\n```python\nVSN=np.linspace(0, 5)\nNIdFullDiodData=pd.DataFrame()\nNIdFullDiodData['Vs[V]']=VSN\nNIdFullDiodData['Id[A]']=NIdFullDiodConectedN(VSN)\nNIdFullDiodData['DIdDVs[OhmInv]']=np.gradient(NIdFullDiodData['Id[A]'], NIdFullDiodData['Vs[V]'])\nNIdFullDiodData['DDIdDDVs']=np.gradient(NIdFullDiodData['DIdDVs[OhmInv]'], NIdFullDiodData['Vs[V]'])\nNIdFullDiodData['DDDIdDDDVs']=np.gradient(NIdFullDiodData['DDIdDDVs'], NIdFullDiodData['Vs[V]'])\nNIdFullDiodData.describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Vs[V]</th>\n      <th>Id[A]</th>\n      <th>DIdDVs[OhmInv]</th>\n      <th>DDIdDDVs</th>\n      <th>DDDIdDDDVs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>50.000000</td>\n      <td>5.000000e+01</td>\n      <td>50.000000</td>\n      <td>50.000000</td>\n      <td>5.000000e+01</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>2.500000</td>\n      <td>1.452101e-05</td>\n      <td>-0.000011</td>\n      <td>0.000006</td>\n      <td>-6.134400e-07</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>1.487488</td>\n      <td>1.705876e-05</td>\n      <td>0.000010</td>\n      <td>0.000003</td>\n      <td>6.635026e-06</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n      <td>-0.000029</td>\n      <td>0.000000</td>\n      <td>-2.486786e-05</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>1.250000</td>\n      <td>8.359108e-08</td>\n      <td>-0.000019</td>\n      <td>0.000005</td>\n      <td>-4.000000e-07</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>2.500000</td>\n      <td>6.869597e-06</td>\n      <td>-0.000010</td>\n      <td>0.000007</td>\n      <td>-4.000000e-07</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>3.750000</td>\n      <td>2.517164e-05</td>\n      <td>-0.000001</td>\n      <td>0.000008</td>\n      <td>-4.000000e-07</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>5.000000</td>\n      <td>5.577000e-05</td>\n      <td>0.000000</td>\n      <td>0.000008</td>\n      <td>2.031467e-05</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nNVCompFullLoc=np.where(NIdFullDiodData['DDDIdDDDVs']==NIdFullDiodData['DDDIdDDDVs'].min())[0][0]\nNVCompFull=NIdFullDiodData['Vs[V]'][NVCompFullLoc]\nprint(f'NMOS Full Square Law Complince Voltage ={NVCompFull:.3f}[V]')\n\n```\n\n    NMOS Full Square Law Complince Voltage =3.878[V]\n\n\n\n```python\nfig, [axId, axDId, axDDId, axDDDId]=plt.subplots(ncols=1, nrows=4, sharex=True)\nNIdFullDiodData.plot(ax=axId, x='Vs[V]', y='Id[A]', legend=False)\naxId.axvline(x=NVCompFull, linestyle='--', color='y', \n             label=f'VComp={NVCompFull:.3f}[V]')\n\naxId.set_ylabel('$I_d[A]$')\naxId.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))\naxId.grid()\n\nbox = axId.get_position()\naxId.set_position([box.x0, box.y0, box.width * 0.8, box.height])\naxId.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n\nNIdFullDiodData.plot(ax=axDId, x='Vs[V]', y='DIdDVs[OhmInv]', legend=False)\naxDId.axvline(x=NVCompFull, linestyle='--', color='y')\n\naxDId.set_ylabel(r'$g_m[\\Omega^{-1}]$')\naxDId.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))\naxDId.grid()\n\n\nNIdFullDiodData.plot(ax=axDDId, x='Vs[V]', y='DDIdDDVs', legend=False)\naxDDId.axvline(x=NVCompFull, linestyle='--', color='y')\n\naxDDId.set_ylabel('$\\dfrac{\\partial^2 I_d}{\\partial V_{S}^2}$')\naxDDId.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))\naxDDId.grid()\n\n\n\n\nNIdFullDiodData.plot(ax=axDDDId, x='Vs[V]', y='DDDIdDDDVs', legend=False)\naxDDDId.axvline(x=NVCompFull, linestyle='--', color='y')\n\naxDDDId.set_ylabel('$\\dfrac{\\partial^3 I_d}{\\partial V_{S}^3}$')\naxDDDId.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))\naxDDDId.set_xlabel('$V_s[V]$')\naxDDDId.grid()\n\nfig.subplots_adjust(hspace=.5)\nplt.suptitle('NMOS Diode $I_d$ Full ');\n\n```\n\n### Difference Between Simplified and Full analysis\nWe can compare not only the $I_d vs. V_S$ graphs for the two analysis but also the difference in the found Compliance Voltage to see if there are any difference in ignoring the Channel Length Modulation effect in a greater then $1\\mu m$ Diode connected NMOS.\n\n\n```python\nNVCompFull-NVCompSimp\n```\n\n\n```python\nfig, ax=plt.subplots(nrows=1, ncols=1)\nax.plot(VSN, NIdSimpDiodConectedN(VSN), label='Simp Model')\nax.plot(VSN, NIdFullDiodConectedN(VSN), label='Full Model')\nax.set_xlabel('$V_S[V]$'); ax.set_ylabel('$I_d[A]$')\nax.grid()\nax.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))\n\nbox = ax.get_position()\nax.set_position([box.x0, box.y0, box.width * 0.8, box.height])\nax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n\nfig.subplots_adjust(hspace=.5)\nplt.suptitle('NMOS Diode Id Compersion between Simp and Full');\n```\n\nAs is shown the differences between the Simplified and the Full analysis are minute for a diode connected NMOS ( be in mind a large channel NMOS).\n\n### Diode Connected as a Topology Slice\nIn the following, we will examine the what a Diode Connected Transistor means in terms of the global view of $I_d$. This is maybe not a new viewpoint but a less common than the declaration that a Diode Connected MOSFET is always in the saturated state (This is true-ish up to the compliance voltage). But given the ease of data collection and analyses with `PySpice` and *Python* we can do better in predicting the Diode-Connected MOSFET from the transistors $I_d$ surface that shows the MOSFETS behaver for all combinations of $V_{GS}, V_{DS}$\n\n\n```python\nNIdFullN=lambdify((VGS, VDS), NMOS.IdFull(subs=subsN), dummify=False)\nVGSN, VDSN=np.meshgrid(np.linspace(0, 5), np.linspace(0, 5))\nNIdFullNDate=NIdFullN(VGSN, VDSN)\nNIdFullNDateDiag=NIdFullNDate.diagonal()\nVdiagN=VGSN.diagonal()\n```\n\n\n```python\n%matplotlib notebook\n%matplotlib notebook\nfrom mpl_toolkits.mplot3d import axes3d\n\nfig = plt.figure()\naxId = fig.gca(projection='3d')\naxId.set_xlabel('$V_{gs}$'); axId.set_ylabel('$V_{ds}$'); axId.set_zlabel('$I_d[mA]$')\n\n\nsurf = axId.plot_surface(VGSN, VDSN, NIdFullNDate*1000, cmap=cm.coolwarm,\n                       linewidth=0, antialiased=True)\naxId.plot(VdiagN, VdiagN, NIdFullNDateDiag*1000, label='$V_{GS}=V_{DS}$')\nbox = ax.get_position()\naxId.set_position([box.x0, box.y0, box.width * 0.8, box.height])\naxId.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n\nplt.suptitle('NMOS $I_d$ Full Surface')\nplt.show()\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n(if the 3D Graph is not showing up try rerunning the cell twice, at the time of this writing the nbmagic `notebook` is still a bit temperamental)\n\nThe above surface plot of the current for (this cant be stressed enough) large channel Full modeled NMOS shows every combination of $V_{GS}$ and $V_{DS}$ that effects the NMOS's $I_d$. Since we are interested in the Diode-Connected NMOS in this analysis we know that the regions of interest will be where $$V_{GS}=V_{DS}$$.\nThus we can find this ROI and overlay it on the $I_D$ surface and plot it individually below. The result is identical to what we predicted from modify the governing equations to the Diode-Connected topology. Save for the vertical mirroring that arises from the choice of fixing the $V_D$ and not the $V_S$.\n\n\n```python\n%matplotlib inline\nXdiag=VDSN.diagonal(); Zdiag=NIdFullNDate.diagonal()\nfig, ax=plt.subplots(ncols=1, nrows=1)\nax.plot(Xdiag, Zdiag*1000)\nax.set_xlabel('$V_{DS}[V]$'); ax.set_ylabel('$I_d[mA]$')\nplt.suptitle('NMOS $I_d$ Full Surface Cut along $V_{DS}=V_{GS}$');\n```\n\n## SPICE Diode Connected NMOS\nHere we proceed with the same analysis but instead utilizing an older submicron NMOS technology. The technology that was chosen was the readily available Taiwan Semiconductor Manufacturing Company (TSMC) $180nm$ NMOS with a channel width and length set in the next cell. While the $180nm$ is not even close to there current cutting-edge $7nm$ process it does display non-square law effects without getting too much deviation from greater $1\\mu m$ technology where the Square Law holds better. \n\n\n```python\nNMOSR_W=200; NMOSR_L=200 #nm\n```\n\n### SPICE analysis of TSMC 180nm Diode Connected NMOS\n\nsetup the \"NetList\"\n\n\n```python\nTestCirN=Circuit('DCBench')\nVbs=TestCirN.V('bs', 'base', TestCirN.gnd, 0@u_V)\n#VDD\nVds=TestCirN.V('ds', 'drain', TestCirN.gnd, 1.8@u_V)\n#Vload\nVsgnd=TestCirN.V('sgnd', 'source', TestCirN.gnd, 0@u_V)\n\nTestCirN.include(spice_library['TSMC180nmN'])\nM0=TestCirN.MOSFET('0', 'drain', 'drain', 'source', 'base',\n                          model='TSMC180nmN', \n                   length=NMOSR_L@u_nm, width=NMOSR_W@u_nm)\nprint(TestCirN)\n```\n\n    .title DCBench\n    .include /home/iridium/Documents/ClonedGitReps/PySpiceExsamples/SpiceLib/TSMC180N.lib\n    Vbs base 0 0V\n    Vds drain 0 1.8V\n    Vsgnd source 0 0V\n    M0 drain drain source base TSMC180nmN l=200nm w=200nm\n    \n\n\nsetup and run the Simulation\n\n\n```python\nTempC=27\nTestCirNSim=TestCirN.simulator(temperature=TempC, nominal_temperature=TempC)\nTestCirNSimData=TestCirNSim.dc(Vsgnd=slice(0, 1.8, .01))\n```\n\n\n```python\nNDiodeConctedData=pd.DataFrame()\nNDiodeConctedData['Vsgnd[V]']=pd.Series(TestCirNSimData.sweep)\nNDiodeConctedData['Id[A]']=-TestCirNSimData.Vds\nNDiodeConctedData.count()\n\n```\n\n\n\n\n    Vsgnd[V]    181\n    Id[A]       181\n    dtype: int64\n\n\n\n\n```python\nNDiodeConctedData['DIdDVs[OhmInv]']=np.gradient(NDiodeConctedData['Id[A]'], NDiodeConctedData['Vsgnd[V]'])\nNDiodeConctedData['DDIdDDVs']=np.gradient(NDiodeConctedData['DIdDVs[OhmInv]'], NDiodeConctedData['Vsgnd[V]'])\nNDiodeConctedData['DDDIdDDDVs']=np.gradient(NDiodeConctedData['DDIdDDVs'], NDiodeConctedData['Vsgnd[V]'])\nNDiodeConctedData.describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Vsgnd[V]</th>\n      <th>Id[A]</th>\n      <th>DIdDVs[OhmInv]</th>\n      <th>DDIdDDVs</th>\n      <th>DDDIdDDDVs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>181.000000</td>\n      <td>1.810000e+02</td>\n      <td>1.810000e+02</td>\n      <td>1.810000e+02</td>\n      <td>1.810000e+02</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>0.900000</td>\n      <td>3.845577e-05</td>\n      <td>-8.825913e-05</td>\n      <td>1.163705e-04</td>\n      <td>-1.101192e-04</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>0.523943</td>\n      <td>4.931266e-05</td>\n      <td>8.334699e-05</td>\n      <td>1.504332e-04</td>\n      <td>1.701090e-03</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>0.000000</td>\n      <td>1.809886e-12</td>\n      <td>-2.096984e-04</td>\n      <td>-1.387779e-13</td>\n      <td>-7.176422e-03</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>0.450000</td>\n      <td>3.238798e-11</td>\n      <td>-1.727597e-04</td>\n      <td>3.938239e-08</td>\n      <td>-1.725217e-07</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>0.900000</td>\n      <td>8.786765e-06</td>\n      <td>-9.506566e-05</td>\n      <td>7.793643e-05</td>\n      <td>9.746982e-05</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>1.350000</td>\n      <td>7.199544e-05</td>\n      <td>-1.099948e-09</td>\n      <td>1.514092e-04</td>\n      <td>1.931309e-04</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>1.800000</td>\n      <td>1.587005e-04</td>\n      <td>1.110223e-14</td>\n      <td>6.400539e-04</td>\n      <td>4.088288e-03</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nNVCompReal=NDiodeConctedData['Vsgnd[V]'][np.where(NDiodeConctedData['DDDIdDDDVs']==NDiodeConctedData['DDDIdDDDVs'].max())[0]]\nNVCompReal=np.around(float(NVCompReal), 4); NVCompReal\n```\n\n\n```python\nNVbiasTarget=NVCompReal/2; NVbiasTarget\n```\n\n\n```python\n%matplotlib inline\nfig, [axId, axDId, axDDId, axDDDId]=plt.subplots(ncols=1, nrows=4, sharex=True)\nNDiodeConctedData.plot(ax=axId, x='Vsgnd[V]', y='Id[A]', legend=False)\naxId.axvline(x=NVCompReal, linestyle='--', color='y', \n             label=f'VComp={NVCompReal:.3f}[V]')\naxId.axvline(x=NVbiasTarget, linestyle='--', color='g',\n            label=f'VBiasTar={NVbiasTarget:.3f}[V]')\n\naxId.set_ylabel('$I_d[A]$')\naxId.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))\naxId.grid()\n\nbox = axId.get_position()\naxId.set_position([box.x0, box.y0, box.width * 0.8, box.height])\naxId.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n\n###############\n\nNDiodeConctedData.plot(ax=axDId, x='Vsgnd[V]', y='DIdDVs[OhmInv]', legend=False)\naxDId.axvline(x=NVCompReal, linestyle='--', color='y')\naxDId.axvline(x=NVbiasTarget, linestyle='--', color='g')\n\naxDId.set_ylabel(r'$g_m[\\Omega^{-1}]$')\naxDId.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))\naxDId.grid()\n\n#######################################\nNDiodeConctedData.plot(ax=axDDId, x='Vsgnd[V]', y='DDIdDDVs', legend=False)\naxDDId.axvline(x=NVCompReal, linestyle='--', color='y')\naxDDId.axvline(x=NVbiasTarget, linestyle='--', color='g')\n\n\naxDDId.set_ylabel('$\\dfrac{\\partial^2 I_d}{\\partial V_{S}^2}$')\naxDDId.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))\naxDDId.grid()\n\n\n#############################################\n\nNDiodeConctedData.plot(ax=axDDDId, x='Vsgnd[V]', y='DDDIdDDDVs', legend=False)\naxDDDId.axvline(x=NVCompReal, linestyle='--', color='y')\naxDDDId.axvline(x=NVbiasTarget, linestyle='--', color='g')\n\n\naxDDDId.set_ylabel('$\\dfrac{\\partial^3 I_d}{\\partial V_{S}^3}$')\naxDDDId.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))\naxDDDId.set_xlabel('$V_s[V]$')\naxDDDId.grid()\n\nfig.subplots_adjust(hspace=.5)\nplt.suptitle(f'TSMC180nm NMOS $I_d$ Diode Connnected W={NMOSR_W}[nm], L={NMOSR_L}[nm]');\n\n```\n\n(Finish later)\n\n### SPICE Confirmation of Topology Interpretation\n\nTest Circuit for extracting NMOS characteristics curves \n\n\n```python\nTestCir=Circuit('DCBench')\nVgs=TestCir.V('gs', 'gate', TestCir.gnd, 1.8@u_V)\nVbs=TestCir.V('bs', 'base', TestCir.gnd, 0@u_V)\nVds=TestCir.V('ds', 'drain', TestCir.gnd, 1.8@u_V)\n\nTestCir.include(spice_library['TSMC180nmN'])\n\nM0=TestCir.MOSFET('0', 'drain', 'gate', TestCir.gnd, 'base',\n                          model='TSMC180nmN', length=200@u_nm, width=200@u_nm)\nprint(TestCir)\n```\n\n    .title DCBench\n    .include /home/iridium/Documents/ClonedGitReps/PySpiceExsamples/SpiceLib/TSMC180N.lib\n    Vgs gate 0 1.8V\n    Vbs base 0 0V\n    Vds drain 0 1.8V\n    M0 drain gate 0 base TSMC180nmN l=200nm w=200nm\n    \n\n\nCreate simulation object\n\n\n```python\nTempC=27\nTestCirSim=TestCir.simulator(temperature=TempC, nominal_temperature=TempC)\n```\n\n\n```python\nx=np.linspace(0, 1.8)\ny=np.linspace(0, 1.8)\nX, Y=np.meshgrid(x, y)\nlen(x),len(y), np.prod([*X.shape])\n```\n\n\n\n\n    (50, 50, 2500)\n\n\n\nperform a DC operating point analyses at every combination of $V_{GS}$ and $V_{DS}$ specified and bind the results to a 2D array for use in plotting a 3D surface of $I_D$\n\n\n```python\nZ=np.zeros(X.shape)\nM0.length=200@u_nm\nfor i in IProd(x, y):\n    Vgs.dc_value=i[0]@u_V; Vds.dc_value=i[1]@u_V\n    TestCirSimData=TestCirSim.operating_point()    \n\n    \n    Z[np.where(x==i[0])[0], np.where(y==i[1])[0]]=np.array(-TestCirSimData.Vds)\n```\n\n\n```python\nDIdDVgs, DIdDVds=np.gradient(Z, x, y)\nAv0=DIdDVgs/DIdDVds\nDIdDVgsDiag=DIdDVgs.diagonal()\nDIdDVdsDiag=DIdDVds.diagonal()\nAv0Diag=Av0.diagonal()\n```\n\n\n```python\nXdiag=X.diagonal(); ZDiag=1000*Z.diagonal()\n```\n\n\n```python\n%matplotlib notebook\n%matplotlib notebook\nfrom mpl_toolkits.mplot3d import axes3d\n\nfig = plt.figure()\n###############\naxId = fig.add_subplot(3, 1, 1, projection='3d')\naxId.set_xlabel('$V_{gs}[V]$'); ax.set_ylabel('$V_{ds}[V]$'); \naxId.set_zlabel('$I_d[mA]$')\n\n\naxId.plot_surface(X, Y, Z*1000, cmap=cm.coolwarm,\n                       linewidth=0, antialiased=True)\naxId.ticklabel_format(axis='z', style='sci', scilimits=(-1,1))\n\naxId.plot(Xdiag, Xdiag, ZDiag, label='Diode Line')\naxId.legend()\n\n##################\n\naxDIdDVgs = fig.add_subplot(3, 2, 3, projection='3d')\n\naxDIdDVgs.set_xlabel('$V_{gs}[V]$'); axDIdDVgs.set_ylabel('$V_{ds}[V]$'); \naxDIdDVgs.set_zlabel('$\\dfrac{\\partial I_d}{\\partial V_{gs}}$')\n\n\naxDIdDVgs.plot_surface(X, Y, DIdDVgs, cmap=cm.coolwarm,\n                       linewidth=0, antialiased=True)\naxDIdDVgs.ticklabel_format(axis='z', style='sci', scilimits=(-1,1))\n\naxDIdDVgs.plot(Xdiag, Xdiag, DIdDVgsDiag)\n\n##############################\n\naxDIdDVds = fig.add_subplot(3, 2, 4, projection='3d')\naxDIdDVds.set_xlabel('$V_{gs}[V]$'); axDIdDVds.set_ylabel('$V_{ds}[V]$'); \naxDIdDVds.set_zlabel('$\\dfrac{\\partial I_d}{\\partial V_{ds}}$')\n\n\naxDIdDVds.plot_surface(X, Y, DIdDVds, cmap=cm.coolwarm,\n                       linewidth=0, antialiased=True)\naxDIdDVds.plot(Xdiag, Xdiag, DIdDVdsDiag)\naxDIdDVds.ticklabel_format(axis='z', style='sci', scilimits=(-1,1))\n\n############################\n\naxAv0 = fig.add_subplot(3, 2, 5, projection='3d')\naxAv0.set_xlabel('$V_{gs}[V]$'); axAv0.set_ylabel('$V_{ds}[V]$'); \naxAv0.set_zlabel('$A_{V0}$')\n\n\naxAv0.plot_surface(X, Y, Av0, cmap=cm.coolwarm,\n                       linewidth=0, antialiased=True)\naxAv0.plot(Xdiag, Xdiag, Av0Diag)\naxAv0.ticklabel_format(axis='z', style='sci', scilimits=(-1,1))\n\n\nplt.suptitle(f'TSMC180nm NMOS $I_d$ Surface W={NMOSR_W}[nm], L={NMOSR_L}[nm]')\nfig.subplots_adjust(hspace=.5, wspace=0.5);\n\nplt.show()\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n(Need to Get a hold of the subplot numbering arghh)\n\n\n```python\n%matplotlib inline\nfig, [axId, axDIdDVgs, axDIdDVds, axAv0]=plt.subplots(nrows=4, ncols=1, sharex=True)\n\naxId.plot(Xdiag, ZDiag)\naxId.set_ylabel('$I_d[mA]$')\naxId.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))\n\n\n#########################\n\naxDIdDVgs.plot(Xdiag, DIdDVgsDiag)\naxDIdDVgs.set_ylabel('$\\dfrac{\\partial I_d}{\\partial V_{gs}}$')\naxDIdDVgs.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))\n\n\n\n########################\n\naxDIdDVds.plot(Xdiag, DIdDVdsDiag)\naxDIdDVds.set_ylabel('$\\dfrac{\\partial I_d}{\\partial V_{ds}}$')\naxDIdDVds.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))\n\n\n#######################\n\naxAv0.plot(Xdiag, Av0Diag)\naxAv0.set_ylabel('$A_{V0}$')\naxAv0.set_xlabel('$V_{ds}[V]$')\n\nfig.subplots_adjust(hspace=.5)\nplt.suptitle(f'TSMC180nm NMOS $I_d$ Diode Connnected Counters W={NMOSR_W}[nm], L={NMOSR_L}[nm]');\n\n```\n\nIn the above graph there is a $A_{vo}$ where\n$$A_{vo}=g_m r_{DS}=\\dfrac{\\partial I_d}{\\partial V_{gs}}/\\dfrac{\\partial I_d}{\\partial V_{ds}}$$\nthis is not a true intrensit gain. It is however a meassure of the influsince between $\\dfrac{\\partial I_d}{\\partial V_{gs}}$ and $\\dfrac{\\partial I_d}{\\partial V_{ds}}$ that shows that the transcondutance domonated the output resistince for a Diode connected NMOS \n\n### Testing the frequency dependence of the Bias point\n\n\n```python\nTestCirSinN=Circuit('DCBench')\nVbs=TestCirSinN.V('bs', 'base', TestCirSinN.gnd, 0@u_V)\n#VDD\nVds=TestCirSinN.V('ds', 'drain', TestCirSinN.gnd, 1.8@u_V)\n#Vload\nVsgnd=TestCirSinN.SinusoidalVoltageSource('sgnd', 'source', TestCirSinN.gnd, \n                             dc_offset=NVbiasTarget@u_V, \n                          amplitude=.1@u_V, frequency=1@u_kHz)\n\nTestCirSinN.include(spice_library['TSMC180nmN'])\nM0=TestCirSinN.MOSFET('0', 'drain', 'drain', 'source', 'base',\n                          model='TSMC180nmN', length=200@u_nm, width=200@u_nm)\nprint(TestCirSinN)\n```\n\n    .title DCBench\n    .include /home/iridium/Documents/ClonedGitReps/PySpiceExsamples/SpiceLib/TSMC180N.lib\n    Vbs base 0 0V\n    Vds drain 0 1.8V\n    Vsgnd source 0 DC 0.46V AC SIN(0V 0.1V 1kHz 0s 0Hz)\n    M0 drain drain source base TSMC180nmN l=200nm w=200nm\n    \n\n\n\n```python\nTempC=27\nTestCirSinNSim=TestCirSinN.simulator(temperature=TempC, nominal_temperature=TempC)\nTestCirSinNData=TestCirSinNSim.ac(start_frequency=1@u_Hz, stop_frequency=100@u_MHz, number_of_points=100,  variation='dec')\n```\n\n\n```python\nfrom PySpice.Plot.BodeDiagram import bode_diagram\n```\n\n\n```python\nId_Freq=pd.Series(-TestCirSinNData.Vds)\nfigure = plt.figure(1, (20, 10))\naxes = (plt.subplot(211), plt.subplot(212))\nbode_diagram(axes=axes,\n             frequency=TestCirSinNData.frequency,\n             gain=20*np.log10(np.absolute(Id_Freq)),\n             phase=np.angle(Id_Freq, deg=True),\n             marker='.',\n             linestyle='-',\n            )\n\n```\n\n# Diode Connected PMOS\n\n## Square Law Theory\n\n### Simplifed\n\n\n```python\nPIdSimpDiodConected=simplify(PMOS.IdSimp(subs={VSG:VSD}))\nPIdSimpDiodConected\n```\n\n\n```python\nPIdSimpDiodConected=PIdSimpDiodConected.subs(VSD, VS-VD)\nPIdSimpDiodConected\n```\n\n\n```python\nsubsP={W:8e6,L:2e6, nTechConst:2e-6, Vnth:1.1, VnA:1/.02, VD:5}\n```\n\n# I will finish this later\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "887b9362766009b754fa22e672a2ebd6dac047a2", "size": 489460, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "DiodeConnectedMOFET.ipynb", "max_stars_repo_name": "PyLCARS/PySpiceExsamples", "max_stars_repo_head_hexsha": "8b5aeaac0459cab2068f630129a11bb87f1392c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2018-02-09T04:49:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T19:10:53.000Z", "max_issues_repo_path": ".ipynb_checkpoints/DiodeConnectedMOFET-checkpoint.ipynb", "max_issues_repo_name": "PyLCARS/PySpiceExsamples", "max_issues_repo_head_hexsha": "8b5aeaac0459cab2068f630129a11bb87f1392c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": ".ipynb_checkpoints/DiodeConnectedMOFET-checkpoint.ipynb", "max_forks_repo_name": "PyLCARS/PySpiceExsamples", "max_forks_repo_head_hexsha": "8b5aeaac0459cab2068f630129a11bb87f1392c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-07-30T11:23:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T07:17:06.000Z", "avg_line_length": 141.8313532309, "max_line_length": 79359, "alphanum_fraction": 0.8331508193, "converted": true, "num_tokens": 11425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.06954174836258786, "lm_q1q2_score": 0.024741208118451374}}
{"text": "# Load the needed data from Foundry.\n\n\n\n\n```python\n# install the foundry and pymatgen\n!pip install foundry_ml\n!pip install pymatgen\n```\n\n    Requirement already satisfied: foundry_ml in /usr/local/lib/python3.7/dist-packages (0.0.12)\n    Requirement already satisfied: mdf-forge>=0.7.6 in /usr/local/lib/python3.7/dist-packages (from foundry_ml) (0.7.6)\n    Requirement already satisfied: h5py>=3.2.1 in /usr/local/lib/python3.7/dist-packages (from foundry_ml) (3.2.1)\n    Requirement already satisfied: scikit-learn>=0.24.1 in /usr/local/lib/python3.7/dist-packages (from foundry_ml) (0.24.2)\n    Requirement already satisfied: funcx==0.0.5 in /usr/local/lib/python3.7/dist-packages (from foundry_ml) (0.0.5)\n    Requirement already satisfied: json2table in /usr/local/lib/python3.7/dist-packages (from foundry_ml) (1.1.5)\n    Requirement already satisfied: dlhub-sdk>=0.9.4 in /usr/local/lib/python3.7/dist-packages (from foundry_ml) (0.9.5)\n    Requirement already satisfied: numpy>=1.15.4 in /usr/local/lib/python3.7/dist-packages (from foundry_ml) (1.20.3)\n    Requirement already satisfied: pandas>=0.23.4 in /usr/local/lib/python3.7/dist-packages (from foundry_ml) (1.1.5)\n    Requirement already satisfied: dlhub-client in /usr/local/lib/python3.7/dist-packages (from foundry_ml) (0.0.1)\n    Requirement already satisfied: mdf-connect-client>=0.3.8 in /usr/local/lib/python3.7/dist-packages (from foundry_ml) (0.3.8)\n    Requirement already satisfied: pydantic>=1.4 in /usr/local/lib/python3.7/dist-packages (from foundry_ml) (1.8.2)\n    Requirement already satisfied: requests>=2.18.4 in /usr/local/lib/python3.7/dist-packages (from mdf-forge>=0.7.6->foundry_ml) (2.23.0)\n    Requirement already satisfied: tqdm>=4.19.4 in /usr/local/lib/python3.7/dist-packages (from mdf-forge>=0.7.6->foundry_ml) (4.41.1)\n    Requirement already satisfied: mdf-toolbox>=0.5.0 in /usr/local/lib/python3.7/dist-packages (from mdf-forge>=0.7.6->foundry_ml) (0.5.7)\n    Requirement already satisfied: globus-sdk>=1.7.0 in /usr/local/lib/python3.7/dist-packages (from mdf-forge>=0.7.6->foundry_ml) (2.0.1)\n    Requirement already satisfied: cached-property; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from h5py>=3.2.1->foundry_ml) (1.5.2)\n    Requirement already satisfied: scipy>=0.19.1 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.24.1->foundry_ml) (1.6.3)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.24.1->foundry_ml) (2.1.0)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.24.1->foundry_ml) (1.0.1)\n    Requirement already satisfied: typer>=0.3.0 in /usr/local/lib/python3.7/dist-packages (from funcx==0.0.5->foundry_ml) (0.3.2)\n    Requirement already satisfied: configobj in /usr/local/lib/python3.7/dist-packages (from funcx==0.0.5->foundry_ml) (5.0.6)\n    Requirement already satisfied: nbsphinx in /usr/local/lib/python3.7/dist-packages (from funcx==0.0.5->foundry_ml) (0.8.6)\n    Requirement already satisfied: jsonschema>=3.2.0 in /usr/local/lib/python3.7/dist-packages (from funcx==0.0.5->foundry_ml) (3.2.0)\n    Requirement already satisfied: texttable in /usr/local/lib/python3.7/dist-packages (from funcx==0.0.5->foundry_ml) (1.6.3)\n    Requirement already satisfied: fair-research-login in /usr/local/lib/python3.7/dist-packages (from funcx==0.0.5->foundry_ml) (0.2.0)\n    Requirement already satisfied: parsl==0.9.0 in /usr/local/lib/python3.7/dist-packages (from funcx==0.0.5->foundry_ml) (0.9.0)\n    Requirement already satisfied: sphinx-rtd-theme in /usr/local/lib/python3.7/dist-packages (from funcx==0.0.5->foundry_ml) (0.5.2)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from funcx==0.0.5->foundry_ml) (0.3.3)\n    Requirement already satisfied: python-daemon in /usr/local/lib/python3.7/dist-packages (from funcx==0.0.5->foundry_ml) (2.3.0)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.23.4->foundry_ml) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.23.4->foundry_ml) (2018.9)\n    Requirement already satisfied: ipywidgets in /usr/local/lib/python3.7/dist-packages (from dlhub-client->foundry_ml) (7.6.3)\n    Requirement already satisfied: nameparser>=1.0.4 in /usr/local/lib/python3.7/dist-packages (from mdf-connect-client>=0.3.8->foundry_ml) (1.0.6)\n    Requirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.7/dist-packages (from pydantic>=1.4->foundry_ml) (3.7.4.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.18.4->mdf-forge>=0.7.6->foundry_ml) (2021.5.30)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.18.4->mdf-forge>=0.7.6->foundry_ml) (3.0.4)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests>=2.18.4->mdf-forge>=0.7.6->foundry_ml) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.18.4->mdf-forge>=0.7.6->foundry_ml) (2.10)\n    Requirement already satisfied: globus-nexus-client>=0.2.8 in /usr/local/lib/python3.7/dist-packages (from mdf-toolbox>=0.5.0->mdf-forge>=0.7.6->foundry_ml) (0.3.0)\n    Requirement already satisfied: pyjwt[crypto]<2.0.0,>=1.5.3 in /usr/local/lib/python3.7/dist-packages (from globus-sdk>=1.7.0->mdf-forge>=0.7.6->foundry_ml) (1.7.1)\n    Requirement already satisfied: click<7.2.0,>=7.1.1 in /usr/local/lib/python3.7/dist-packages (from typer>=0.3.0->funcx==0.0.5->foundry_ml) (7.1.2)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from configobj->funcx==0.0.5->foundry_ml) (1.15.0)\n    Requirement already satisfied: docutils in /usr/local/lib/python3.7/dist-packages (from nbsphinx->funcx==0.0.5->foundry_ml) (0.17.1)\n    Requirement already satisfied: traitlets in /usr/local/lib/python3.7/dist-packages (from nbsphinx->funcx==0.0.5->foundry_ml) (5.0.5)\n    Requirement already satisfied: nbformat in /usr/local/lib/python3.7/dist-packages (from nbsphinx->funcx==0.0.5->foundry_ml) (5.1.3)\n    Requirement already satisfied: nbconvert!=5.4 in /usr/local/lib/python3.7/dist-packages (from nbsphinx->funcx==0.0.5->foundry_ml) (5.6.1)\n    Requirement already satisfied: jinja2 in /usr/local/lib/python3.7/dist-packages (from nbsphinx->funcx==0.0.5->foundry_ml) (2.11.3)\n    Requirement already satisfied: sphinx>=1.8 in /usr/local/lib/python3.7/dist-packages (from nbsphinx->funcx==0.0.5->foundry_ml) (1.8.5)\n    Requirement already satisfied: attrs>=17.4.0 in /usr/local/lib/python3.7/dist-packages (from jsonschema>=3.2.0->funcx==0.0.5->foundry_ml) (21.2.0)\n    Requirement already satisfied: pyrsistent>=0.14.0 in /usr/local/lib/python3.7/dist-packages (from jsonschema>=3.2.0->funcx==0.0.5->foundry_ml) (0.17.3)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from jsonschema>=3.2.0->funcx==0.0.5->foundry_ml) (4.5.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from jsonschema>=3.2.0->funcx==0.0.5->foundry_ml) (57.0.0)\n    Requirement already satisfied: ipykernel in /usr/local/lib/python3.7/dist-packages (from parsl==0.9.0->funcx==0.0.5->foundry_ml) (4.10.1)\n    Requirement already satisfied: psutil>=5.5.1 in /usr/local/lib/python3.7/dist-packages (from parsl==0.9.0->funcx==0.0.5->foundry_ml) (5.8.0)\n    Requirement already satisfied: paramiko in /usr/local/lib/python3.7/dist-packages (from parsl==0.9.0->funcx==0.0.5->foundry_ml) (2.7.2)\n    Requirement already satisfied: tblib in /usr/local/lib/python3.7/dist-packages (from parsl==0.9.0->funcx==0.0.5->foundry_ml) (1.7.0)\n    Requirement already satisfied: typeguard in /usr/local/lib/python3.7/dist-packages (from parsl==0.9.0->funcx==0.0.5->foundry_ml) (2.7.1)\n    Requirement already satisfied: pyzmq>=17.1.2 in /usr/local/lib/python3.7/dist-packages (from parsl==0.9.0->funcx==0.0.5->foundry_ml) (22.1.0)\n    Requirement already satisfied: ipyparallel in /usr/local/lib/python3.7/dist-packages (from parsl==0.9.0->funcx==0.0.5->foundry_ml) (6.3.0)\n    Requirement already satisfied: lockfile>=0.10 in /usr/local/lib/python3.7/dist-packages (from python-daemon->funcx==0.0.5->foundry_ml) (0.12.2)\n    Requirement already satisfied: ipython>=4.0.0; python_version >= \"3.3\" in /usr/local/lib/python3.7/dist-packages (from ipywidgets->dlhub-client->foundry_ml) (5.5.0)\n    Requirement already satisfied: widgetsnbextension~=3.5.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->dlhub-client->foundry_ml) (3.5.1)\n    Requirement already satisfied: jupyterlab-widgets>=1.0.0; python_version >= \"3.6\" in /usr/local/lib/python3.7/dist-packages (from ipywidgets->dlhub-client->foundry_ml) (1.0.0)\n    Requirement already satisfied: cryptography>=1.4; extra == \"crypto\" in /usr/local/lib/python3.7/dist-packages (from pyjwt[crypto]<2.0.0,>=1.5.3->globus-sdk>=1.7.0->mdf-forge>=0.7.6->foundry_ml) (3.4.7)\n    Requirement already satisfied: ipython-genutils in /usr/local/lib/python3.7/dist-packages (from traitlets->nbsphinx->funcx==0.0.5->foundry_ml) (0.2.0)\n    Requirement already satisfied: jupyter-core in /usr/local/lib/python3.7/dist-packages (from nbformat->nbsphinx->funcx==0.0.5->foundry_ml) (4.7.1)\n    Requirement already satisfied: pandocfilters>=1.4.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert!=5.4->nbsphinx->funcx==0.0.5->foundry_ml) (1.4.3)\n    Requirement already satisfied: pygments in /usr/local/lib/python3.7/dist-packages (from nbconvert!=5.4->nbsphinx->funcx==0.0.5->foundry_ml) (2.6.1)\n    Requirement already satisfied: bleach in /usr/local/lib/python3.7/dist-packages (from nbconvert!=5.4->nbsphinx->funcx==0.0.5->foundry_ml) (3.3.0)\n    Requirement already satisfied: entrypoints>=0.2.2 in /usr/local/lib/python3.7/dist-packages (from nbconvert!=5.4->nbsphinx->funcx==0.0.5->foundry_ml) (0.3)\n    Requirement already satisfied: testpath in /usr/local/lib/python3.7/dist-packages (from nbconvert!=5.4->nbsphinx->funcx==0.0.5->foundry_ml) (0.5.0)\n    Requirement already satisfied: defusedxml in /usr/local/lib/python3.7/dist-packages (from nbconvert!=5.4->nbsphinx->funcx==0.0.5->foundry_ml) (0.7.1)\n    Requirement already satisfied: mistune<2,>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert!=5.4->nbsphinx->funcx==0.0.5->foundry_ml) (0.8.4)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2->nbsphinx->funcx==0.0.5->foundry_ml) (2.0.1)\n    Requirement already satisfied: alabaster<0.8,>=0.7 in /usr/local/lib/python3.7/dist-packages (from sphinx>=1.8->nbsphinx->funcx==0.0.5->foundry_ml) (0.7.12)\n    Requirement already satisfied: imagesize in /usr/local/lib/python3.7/dist-packages (from sphinx>=1.8->nbsphinx->funcx==0.0.5->foundry_ml) (1.2.0)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from sphinx>=1.8->nbsphinx->funcx==0.0.5->foundry_ml) (20.9)\n    Requirement already satisfied: sphinxcontrib-websupport in /usr/local/lib/python3.7/dist-packages (from sphinx>=1.8->nbsphinx->funcx==0.0.5->foundry_ml) (1.2.4)\n    Requirement already satisfied: babel!=2.0,>=1.3 in /usr/local/lib/python3.7/dist-packages (from sphinx>=1.8->nbsphinx->funcx==0.0.5->foundry_ml) (2.9.1)\n    Requirement already satisfied: snowballstemmer>=1.1 in /usr/local/lib/python3.7/dist-packages (from sphinx>=1.8->nbsphinx->funcx==0.0.5->foundry_ml) (2.1.0)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->jsonschema>=3.2.0->funcx==0.0.5->foundry_ml) (3.4.1)\n    Requirement already satisfied: jupyter-client in /usr/local/lib/python3.7/dist-packages (from ipykernel->parsl==0.9.0->funcx==0.0.5->foundry_ml) (5.3.5)\n    Requirement already satisfied: tornado>=4.0 in /usr/local/lib/python3.7/dist-packages (from ipykernel->parsl==0.9.0->funcx==0.0.5->foundry_ml) (5.1.1)\n    Requirement already satisfied: bcrypt>=3.1.3 in /usr/local/lib/python3.7/dist-packages (from paramiko->parsl==0.9.0->funcx==0.0.5->foundry_ml) (3.2.0)\n    Requirement already satisfied: pynacl>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from paramiko->parsl==0.9.0->funcx==0.0.5->foundry_ml) (1.4.0)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.7/dist-packages (from ipyparallel->parsl==0.9.0->funcx==0.0.5->foundry_ml) (4.4.2)\n    Requirement already satisfied: pexpect; sys_platform != \"win32\" in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets->dlhub-client->foundry_ml) (4.8.0)\n    Requirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets->dlhub-client->foundry_ml) (0.8.1)\n    Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets->dlhub-client->foundry_ml) (1.0.18)\n    Requirement already satisfied: pickleshare in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets->dlhub-client->foundry_ml) (0.7.5)\n    Requirement already satisfied: notebook>=4.4.1 in /usr/local/lib/python3.7/dist-packages (from widgetsnbextension~=3.5.0->ipywidgets->dlhub-client->foundry_ml) (5.3.1)\n    Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.4; extra == \"crypto\"->pyjwt[crypto]<2.0.0,>=1.5.3->globus-sdk>=1.7.0->mdf-forge>=0.7.6->foundry_ml) (1.14.5)\n    Requirement already satisfied: webencodings in /usr/local/lib/python3.7/dist-packages (from bleach->nbconvert!=5.4->nbsphinx->funcx==0.0.5->foundry_ml) (0.5.1)\n    Requirement already satisfied: pyparsing>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->sphinx>=1.8->nbsphinx->funcx==0.0.5->foundry_ml) (2.4.7)\n    Requirement already satisfied: sphinxcontrib-serializinghtml in /usr/local/lib/python3.7/dist-packages (from sphinxcontrib-websupport->sphinx>=1.8->nbsphinx->funcx==0.0.5->foundry_ml) (1.1.5)\n    Requirement already satisfied: ptyprocess>=0.5 in /usr/local/lib/python3.7/dist-packages (from pexpect; sys_platform != \"win32\"->ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets->dlhub-client->foundry_ml) (0.7.0)\n    Requirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets->dlhub-client->foundry_ml) (0.2.5)\n    Requirement already satisfied: Send2Trash in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->dlhub-client->foundry_ml) (1.5.0)\n    Requirement already satisfied: terminado>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->dlhub-client->foundry_ml) (0.10.1)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.4; extra == \"crypto\"->pyjwt[crypto]<2.0.0,>=1.5.3->globus-sdk>=1.7.0->mdf-forge>=0.7.6->foundry_ml) (2.20)\n    Requirement already satisfied: pymatgen in /usr/local/lib/python3.7/dist-packages (2022.0.8)\n    Requirement already satisfied: scipy>=1.5.0 in /usr/local/lib/python3.7/dist-packages (from pymatgen) (1.6.3)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen) (2021.6.10)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen) (0.8.9)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen) (3.3.0)\n    Requirement already satisfied: plotly>=4.5.0 in /usr/local/lib/python3.7/dist-packages (from pymatgen) (4.14.3)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen) (1.16.1)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from pymatgen) (1.7.1)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen) (0.17.9)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen) (2.5.1)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen) (3.2.2)\n    Requirement already satisfied: uncertainties>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from pymatgen) (3.1.5)\n    Requirement already satisfied: typing-extensions>=3.7.4.3; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from pymatgen) (3.7.4.3)\n    Requirement already satisfied: numpy>=1.20.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen) (1.20.3)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen) (2.23.0)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from pymatgen) (1.1.5)\n    Requirement already satisfied: retrying>=1.3.3 in /usr/local/lib/python3.7/dist-packages (from plotly>=4.5.0->pymatgen) (1.3.3)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from plotly>=4.5.0->pymatgen) (1.15.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->pymatgen) (1.2.1)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen) (0.2.2)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.2->pymatgen) (4.4.2)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen) (1.3.1)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen) (2.8.1)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from uncertainties>=3.1.4->pymatgen) (0.16.0)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen) (2021.5.30)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen) (3.0.4)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen) (2018.9)\n\n\n\n```python\n# initiate the foundry\nfrom foundry import Foundry\nf = Foundry(no_browser=True, no_local_server=True)\n```\n\n    Please paste the following URL in a browser:\n    https://auth.globus.org/v2/oauth2/authorize?client_id=984464e2-90ab-433d-8145-ac0215d26c8e&redirect_uri=https%3A%2F%2Fauth.globus.org%2Fv2%2Fweb%2Fauth-code&scope=urn%3Aglobus%3Aauth%3Ascope%3Adata.materialsdatafacility.org%3Aall+https%3A%2F%2Fauth.globus.org%2Fscopes%2Fc17f27bb-f200-486a-b785-2a25e82af505%2Fconnect+urn%3Aglobus%3Aauth%3Ascope%3Asearch.api.globus.org%3Asearch+https%3A%2F%2Fauth.globus.org%2Fscopes%2F56ceac29-e98a-440a-a594-b41e7a084b62%2Fall+urn%3Aglobus%3Aauth%3Ascope%3Atransfer.api.globus.org%3Aall+https%3A%2F%2Fauth.globus.org%2Fscopes%2F81fc4156-a623-47f2-93ad-7184118226ba%2Fauth+openid+https%3A%2F%2Fauth.globus.org%2Fscopes%2Ffacd7ccc-c5f4-42aa-916b-a0e270e2c2a9%2Fall&state=_default&response_type=code&code_challenge=qRhicK9FKttaJ9A5U83hwtpvOy4wbIFEmrCYH2Yu0Ro&code_challenge_method=S256&access_type=offline&prefill_named_grant=Foundry+Login\n    Please Paste your Auth Code Below: \n    3YSi12S3hzsW3dmT8ZggNiscuP6ORr\n    Please paste the following URL in a browser:\n    https://auth.globus.org/v2/oauth2/authorize?client_id=f47a891c-cfd0-443c-8db8-c72fb82fe3f7&redirect_uri=https%3A%2F%2Fauth.globus.org%2Fv2%2Fweb%2Fauth-code&scope=urn%3Aglobus%3Aauth%3Ascope%3Asearch.api.globus.org%3Asearch+https%3A%2F%2Fauth.globus.org%2Fscopes%2F81fc4156-a623-47f2-93ad-7184118226ba%2Fauth+https%3A%2F%2Fauth.globus.org%2Fscopes%2Ffacd7ccc-c5f4-42aa-916b-a0e270e2c2a9%2Fall+openid&state=_default&response_type=code&code_challenge=9wGOAZWOhPBEgKnKqJAVRJ9rv5rbJDOWPfPu1BQuSDo&code_challenge_method=S256&access_type=offline&prefill_named_grant=DLHub_Client+Login\n    Please Paste your Auth Code Below: \n    x0SLUasQU80yVLum4IMyfgLYDtBQqi\n\n\n\n```python\nf.list()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>source_id</th>\n      <th>name</th>\n      <th>year</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>_test_foundry_aflow_band_gaps_v1.1</td>\n      <td>AFlowLib Band Gap Data Package</td>\n      <td>2020</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>_test_blaiszik_jarvis_mbj_3d_v1.1</td>\n      <td>Jarvis MBJ 3D</td>\n      <td>2020</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>_test_foundry_fashion_mnist_v1.1</td>\n      <td>Fashion-MNIST: a Novel Image Dataset for Bench...</td>\n      <td>2021</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>_test_blaiszik_foundry_iris_v2.1</td>\n      <td>Foundry - Iris Dataset</td>\n      <td>2021</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>_test_foundry_stein_bandgaps_v1.1</td>\n      <td>JCAP images and absorption spectra for 179072 ...</td>\n      <td>2021</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>_test_foundry_oqmd_v1.1</td>\n      <td>Foundry - OQMD</td>\n      <td>2021</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>_test_foundry_experimental_bandgap_v1.1</td>\n      <td>Foundry - Experimental Bandgaps</td>\n      <td>2021</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>_test_foundry_aflow_bandgaps_v1.1</td>\n      <td>Foundry - Experimental Bandgaps</td>\n      <td>2021</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>_test_foundry_nrel_bandgap_v1.1</td>\n      <td>NREL MatDB Band Gaps</td>\n      <td>2021</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>_test_foundry_oqmd_bandgap_v1.1</td>\n      <td>Foundry - OQMD Bandgaps</td>\n      <td>2021</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>_test_exp_bandgap_v1.1</td>\n      <td>Experimental bandgap dataset</td>\n      <td>2021</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>_test_oqmd_bandgap_v1.1</td>\n      <td>Open Quantum Materials Database bandgap dataset</td>\n      <td>2021</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>_test_example_iris_v1.1</td>\n      <td>scourtas_example_iris_test_publish</td>\n      <td>2021</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>_test_foundry_assorted_computational_bandgap_v1.1</td>\n      <td>Foundry - Assorted Computational Bandgaps</td>\n      <td>2021</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>_test_foundry_mp_bandgap_v1.1</td>\n      <td>Foundry - Materials Project Bandgaps</td>\n      <td>2021</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>_test_comp_bandgap_v1.1</td>\n      <td>Assorted computational bandgap dataset</td>\n      <td>2021</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>_test_aflow_bandgap_v1.1</td>\n      <td>Automatic Flow bandgap dataset</td>\n      <td>2021</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>_test_dmax_regression_v1.2</td>\n      <td>Molecular Dynamic Characteristic Temperatures ...</td>\n      <td>2021</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>_test_mp_bandgap_v1.1</td>\n      <td>Materials Project bandgap dataset</td>\n      <td>2021</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>_test_foundry_irisdev_v1.2</td>\n      <td>Foundry - Iris Dev Dataset</td>\n      <td>2021</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>_test_foundry_stan_dendrite_segmentation_v4.1</td>\n      <td>Semantic Segmentation of Dendrites via Machine...</td>\n      <td>2021</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nLoad and clean the experimental data. For clean method details, please refer to the paper\n\n\n```python\nimport numpy as np\nfrom pymatgen.core import Structure\nimport pandas as pd\n\nf = f.load('_test_exp_bandgap_v1.1', globus=False)\ndf_X, df_Y = f.load_data()\nN = len(df_Y)\ndrop_index = []\nfor i in range(N):\n    if type(df_Y.loc[i,'bandgap value (eV)']) == list:\n        new = [float(k) for k in df_Y.loc[i,'bandgap value (eV)']]\n        mean = np.mean(new)\n        std = np.std(new)\n        if abs(mean) > 1.e-6 and std/mean > 0.1:\n            drop_index.append(i)\n        else:\n            df_Y.loc[i,'bandgap value (eV)'] = mean\ndf1_exp_Y = df_Y.drop(drop_index)\ndf1_exp_X = df_X.drop(drop_index)\n# select 300K, optical, smallest bandgap data\ncomposition = []\nsp = []\nN1 = len(df1_exp_Y)\nfor i in range(N1):\n    str_temp = Structure.from_dict(df1_exp_X.iloc[i]['structure'])\n    composition.append(str_temp.composition.reduced_formula)\n    sp.append(str_temp.get_space_group_info()[1])\n#     composition.append(i['Composition'])\ndf_300_smallest_X = []\ndf_300_smallest_Y = []\nfor com in list({value:\"\" for value in composition}):\n    temp = []\n    for index in range(N1):\n        if composition[index] == com:\n            temp.append(index)\n    spacegroup = []\n    for index in temp:\n        spacegroup.append(sp[index])\n#     print(spacegroup, list(set(spacegroup)))\n    for sp1 in list({value:\"\" for value in spacegroup}):\n        temp1 = []\n        kinds = []\n        for index in temp:\n            if  sp[index] == sp1:\n                temp1.append(index)\n                string = df1_exp_X.iloc[index]['temp (K)'] + df1_exp_X.iloc[index]['bandgap type'] + df1_exp_X.iloc[index]['exp method']\n                kinds.append(string)\n#         print('temp1',temp1)\n        for case in ['300IO','300I','IO','I','300O','300','O','','300DO','300D','DO','D']:\n            if case in kinds:\n                for index in temp1:\n                    string = df1_exp_X.iloc[index]['temp (K)'] + df1_exp_X.iloc[index]['bandgap type'] + df1_exp_X.iloc[index]['exp method']\n                    if string == case:\n                        df_300_smallest_X.append(df1_exp_X.iloc[index])\n                        df_300_smallest_Y.append(df1_exp_Y.iloc[index])\n                break\n            else:\n                continue      \nprint(len(df_300_smallest_X))\ndf_exp_X = pd.DataFrame(df_300_smallest_X)\ndf_exp_Y = pd.DataFrame(df_300_smallest_Y)\ndf_exp_X, df_exp_Y\n```\n\n    Loading by source_id\n    Done curling.\n    [{'/foundry/_test_exp_bandgap_v1.1/foundry_dataframe.json status': True}]\n\n\n    /usr/local/lib/python3.7/dist-packages/pandas/core/indexing.py:670: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame\n    \n    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      iloc._setitem_with_indexer(indexer, value)\n    /usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:17: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame\n    \n    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n\n\n    1464\n\n\n\n\n\n    (     reference        icsd_id  ... space group temp (K)\n     0           41  MPDS-S1531436  ...       Fd-3m         \n     1            1         238499  ...        Pnma      300\n     2            1         416461  ...       Pm-3m         \n     3            1         262893  ...      Cmc2_1         \n     4            1          50460  ...        Fddd         \n     ...        ...            ...  ...         ...      ...\n     2803         1          71947  ...        Immm         \n     2804         3         100268  ...       F-43m      300\n     2805    [2, 2]         230266  ...       Fm-3m         \n     2806         1         253696  ...       P2_13         \n     2807         1         243641  ...        R-3c         \n     \n     [1464 rows x 9 columns],      bandgap value (eV)\n     0                  1.05\n     1                  5.2 \n     2                  1.5 \n     3                 2.29 \n     4                 1.77 \n     ...                 ...\n     2803              1.48 \n     2804               0.47\n     2805               2.25\n     2806               4.2 \n     2807              3.88 \n     \n     [1464 rows x 1 columns])\n\n\n\nLoad the materials project PBE data\n\n\n```python\nf = f.load('_test_mp_bandgap_v1.1', globus=False)\ndf_pbe_X, df_pbe_Y = f.load_data()\n```\n\n    Loading by source_id\n    Done curling.\n    [{'/foundry/_test_mp_bandgap_v1.1/foundry_dataframe.json status': True}]\n\n\nLoad other computational data\n\n\n```python\nf = f.load('_test_comp_bandgap_v1.1',globus=False)\ndf_X, df_Y = f.load_data()\n```\n\n    Loading by source_id\n    Done curling.\n    [{'/foundry/_test_comp_bandgap_v1.1/foundry_dataframe.json status': True}]\n\n\nObtain the Jarvis PBE data with OPTB88 (vdW)\n\n\n```python\ndf_pbe1_X = df_X[(df_X['comp method'] == 'optb88') ]\ndf_pbe1_Y = df_Y[(df_X['comp method'] == 'optb88') ]\n```\n\nObtain the data for mbj\n\n\n```python\ndf_temp1_X = df_X[(df_X['comp method'] == 'MBJ') | (df_X['comp method'] == 'mbj')]\ndf_temp1_Y = df_Y[(df_X['comp method'] == 'MBJ') | (df_X['comp method'] == 'mbj')]\ndf_temp_X = df_temp1_X[df_temp1_X['bandgap type'] != 'D']\ndf_temp_Y = df_temp1_Y[df_temp1_X['bandgap type'] != 'D']\ndf_temp2_X = df_temp_X.copy()\ndf_temp2_Y = df_temp_Y.copy()\n# remove repeated case\ncomposition = []\nsp = []\nN = len(df_temp_X)\nfor i in range(N):\n    str_temp = Structure.from_dict(df_temp_X.iloc[i]['structure'])\n    composition.append(str_temp.composition.reduced_formula)\n    sp.append(str_temp.get_space_group_info()[1])\ndf_no_repeat_X = []\ndf_no_repeat_Y = []\nfor com in list({value:\"\" for value in composition}):\n    temp = []\n    for index in range(N):\n        if composition[index] == com:\n            temp.append(index)\n    if len(temp) == 1:\n        df_no_repeat_X.append(df_temp_X.iloc[temp[0]])\n        df_no_repeat_Y.append(df_temp_Y.iloc[temp[0]])\n    else:       \n        spacegroup = []\n        for index in temp:\n            spacegroup.append(sp[index])\n        for sp1 in list({value:\"\" for value in spacegroup}):\n            temp1 = []\n            for index in temp:\n                if  sp[index] == sp1:\n                    temp1.append(index)\n            if len(temp1) == 1:\n                df_no_repeat_X.append(df_temp_X.iloc[temp1[0]])\n                df_no_repeat_Y.append(df_temp_Y.iloc[temp1[0]])\n            else:\n                values = []\n                for index in temp1:\n                    values.append(float(df_temp_Y.iloc[index]['bandgap value (eV)']))\n                mean = np.mean(values)\n                std = np.std(values)\n                if abs(mean) < 1.e-10 or abs(std) < 1.e-10:\n                    df_no_repeat_Y.append(df_temp_Y.iloc[temp1[0]])\n                    df_no_repeat_X.append(df_temp_X.iloc[temp1[0]])\n                elif std/mean < 0.1:\n                    df_temp2_Y.iloc[temp1[0],df_temp2_Y.columns.get_loc('bandgap value (eV)')] = mean\n                    df_no_repeat_Y.append(df_temp2_Y.iloc[temp1[0]])\n                    df_no_repeat_X.append(df_temp2_X.iloc[temp1[0]])\ndf_mbj_X = pd.DataFrame(df_no_repeat_X)\ndf_mbj_Y = pd.DataFrame(df_no_repeat_Y)\n```\n\n    /usr/local/lib/python3.7/dist-packages/pymatgen/core/periodic_table.py:212: UserWarning: No electronegativity for He. Setting to NaN. This has no physical meaning, and is mainly done to avoid errors caused by the code expecting a float.\n      \"avoid errors caused by the code expecting a float.\" % self.symbol\n    /usr/local/lib/python3.7/dist-packages/pymatgen/core/periodic_table.py:212: UserWarning: No electronegativity for Ne. Setting to NaN. This has no physical meaning, and is mainly done to avoid errors caused by the code expecting a float.\n      \"avoid errors caused by the code expecting a float.\" % self.symbol\n    /usr/local/lib/python3.7/dist-packages/pymatgen/core/periodic_table.py:212: UserWarning: No electronegativity for Ar. Setting to NaN. This has no physical meaning, and is mainly done to avoid errors caused by the code expecting a float.\n      \"avoid errors caused by the code expecting a float.\" % self.symbol\n\n\nObtain the data for GLLB-SC\n\n\n```python\ndf_temp1_X = df_X[(df_X['comp method'] == 'GLLB_SC') | (df_X['comp method'] == 'GLLB-SC')]\ndf_temp1_Y = df_Y[(df_X['comp method'] == 'GLLB_SC') | (df_X['comp method'] == 'GLLB-SC')]\ndf_temp_X = df_temp1_X[df_temp1_X['bandgap type'] != 'D']\ndf_temp_Y = df_temp1_Y[df_temp1_X['bandgap type'] != 'D']\ndf_temp2_X = df_temp_X.copy()\ndf_temp2_Y = df_temp_Y.copy()\n# remove repeated case\ncomposition = []\nsp = []\nN = len(df_temp_X)\nfor i in range(N):\n    str_temp = Structure.from_dict(df_temp_X.iloc[i]['structure'])\n    composition.append(str_temp.composition.reduced_formula)\n    sp.append(str_temp.get_space_group_info()[1])\ndf_no_repeat_X = []\ndf_no_repeat_Y = []\nfor com in list({value:\"\" for value in composition}):\n    temp = []\n    for index in range(N):\n        if composition[index] == com:\n            temp.append(index)\n    if len(temp) == 1:\n        df_no_repeat_X.append(df_temp_X.iloc[temp[0]])\n        df_no_repeat_Y.append(df_temp_Y.iloc[temp[0]])\n    else:       \n        spacegroup = []\n        for index in temp:\n            spacegroup.append(sp[index])\n        for sp1 in list({value:\"\" for value in spacegroup}):\n            temp1 = []\n            for index in temp:\n                if  sp[index] == sp1:\n                    temp1.append(index)\n            if len(temp1) == 1:\n                df_no_repeat_X.append(df_temp_X.iloc[temp1[0]])\n                df_no_repeat_Y.append(df_temp_Y.iloc[temp1[0]])\n            else:\n                values = []\n                for index in temp1:\n                    values.append(float(df_temp_Y.iloc[index]['bandgap value (eV)']))\n                mean = np.mean(values)\n                std = np.std(values)\n                if abs(mean) < 1.e-10 or abs(std) < 1.e-10:\n                    df_no_repeat_Y.append(df_temp_Y.iloc[temp1[0]])\n                    df_no_repeat_X.append(df_temp_X.iloc[temp1[0]])\n                elif std/mean < 0.1:\n                    df_temp2_Y.iloc[temp1[0],df_temp2_Y.columns.get_loc('bandgap value (eV)')] = mean\n                    df_no_repeat_Y.append(df_temp2_Y.iloc[temp1[0]])\n                    df_no_repeat_X.append(df_temp2_X.iloc[temp1[0]])\ndf_gllb_X = pd.DataFrame(df_no_repeat_X)\ndf_gllb_Y = pd.DataFrame(df_no_repeat_Y)\n```\n\nObtain the data for HSE\n\n\n\n\n```python\ndf_temp1_X = df_X[(df_X['comp method'] == 'HSE') | (df_X['comp method'] == 'hse')]\ndf_temp1_Y = df_Y[(df_X['comp method'] == 'HSE') | (df_X['comp method'] == 'hse')]\ndf_temp_X = df_temp1_X[df_temp1_X['bandgap type'] != 'D']\ndf_temp_Y = df_temp1_Y[df_temp1_X['bandgap type'] != 'D']\ndf_temp2_X = df_temp_X.copy()\ndf_temp2_Y = df_temp_Y.copy()\n# remove repeated case\ncomposition = []\nsp = []\nN = len(df_temp_X)\nfor i in range(N):\n    str_temp = Structure.from_dict(df_temp_X.iloc[i]['structure'])\n    composition.append(str_temp.composition.reduced_formula)\n    sp.append(str_temp.get_space_group_info()[1])\ndf_no_repeat_X = []\ndf_no_repeat_Y = []\nfor com in list({value:\"\" for value in composition}):\n    temp = []\n    for index in range(N):\n        if composition[index] == com:\n            temp.append(index)\n    if len(temp) == 1:\n        df_no_repeat_X.append(df_temp_X.iloc[temp[0]])\n        df_no_repeat_Y.append(df_temp_Y.iloc[temp[0]])\n    else:       \n        spacegroup = []\n        for index in temp:\n            spacegroup.append(sp[index])\n        for sp1 in list({value:\"\" for value in spacegroup}):\n            temp1 = []\n            for index in temp:\n                if  sp[index] == sp1:\n                    temp1.append(index)\n            if len(temp1) == 1:\n                df_no_repeat_X.append(df_temp_X.iloc[temp1[0]])\n                df_no_repeat_Y.append(df_temp_Y.iloc[temp1[0]])\n            else:\n                values = []\n                for index in temp1:\n                    values.append(float(df_temp_Y.iloc[index]['bandgap value (eV)']))\n                mean = np.mean(values)\n                std = np.std(values)\n                if abs(mean) < 1.e-10 or abs(std) < 1.e-10:\n                    df_no_repeat_Y.append(df_temp_Y.iloc[temp1[0]])\n                    df_no_repeat_X.append(df_temp_X.iloc[temp1[0]])\n                elif std/mean < 0.1:\n                    df_temp2_Y.iloc[temp1[0],df_temp2_Y.columns.get_loc('bandgap value (eV)')] = mean\n                    df_no_repeat_Y.append(df_temp2_Y.iloc[temp1[0]])\n                    df_no_repeat_X.append(df_temp2_X.iloc[temp1[0]])\ndf_hse_X = pd.DataFrame(df_no_repeat_X)\ndf_hse_Y = pd.DataFrame(df_no_repeat_Y)\n```\n\n    /usr/local/lib/python3.7/dist-packages/pymatgen/core/periodic_table.py:212: UserWarning: No electronegativity for He. Setting to NaN. This has no physical meaning, and is mainly done to avoid errors caused by the code expecting a float.\n      \"avoid errors caused by the code expecting a float.\" % self.symbol\n\n\nObtain the data for GW\n\n\n```python\ndf_temp1_X = df_X[(df_X['comp method'] == 'GW') | (df_X['comp method'] == 'GWVD')]\ndf_temp1_Y = df_Y[(df_X['comp method'] == 'GW') | (df_X['comp method'] == 'GWVD')]\ndf_temp_X = df_temp1_X[df_temp1_X['bandgap type'] != 'D']\ndf_temp_Y = df_temp1_Y[df_temp1_X['bandgap type'] != 'D']\ndf_temp2_X = df_temp_X.copy()\ndf_temp2_Y = df_temp_Y.copy()\n# remove repeated case\ncomposition = []\nsp = []\nN = len(df_temp_X)\nfor i in range(N):\n    str_temp = Structure.from_dict(df_temp_X.iloc[i]['structure'])\n    composition.append(str_temp.composition.reduced_formula)\n    sp.append(str_temp.get_space_group_info()[1])\ndf_no_repeat_X = []\ndf_no_repeat_Y = []\nfor com in list({value:\"\" for value in composition}):\n    temp = []\n    for index in range(N):\n        if composition[index] == com:\n            temp.append(index)\n    if len(temp) == 1:\n        df_no_repeat_X.append(df_temp_X.iloc[temp[0]])\n        df_no_repeat_Y.append(df_temp_Y.iloc[temp[0]])\n    else:       \n        spacegroup = []\n        for index in temp:\n            spacegroup.append(sp[index])\n        for sp1 in list({value:\"\" for value in spacegroup}):\n            temp1 = []\n            for index in temp:\n                if  sp[index] == sp1:\n                    temp1.append(index)\n            if len(temp1) == 1:\n                df_no_repeat_X.append(df_temp_X.iloc[temp1[0]])\n                df_no_repeat_Y.append(df_temp_Y.iloc[temp1[0]])\n            else:\n                values = []\n                for index in temp1:\n                    values.append(float(df_temp_Y.iloc[index]['bandgap value (eV)']))\n                mean = np.mean(values)\n                std = np.std(values)\n                if abs(mean) < 1.e-10 or abs(std) < 1.e-10:\n                    df_no_repeat_Y.append(df_temp_Y.iloc[temp1[0]])\n                    df_no_repeat_X.append(df_temp_X.iloc[temp1[0]])\n                elif std/mean < 0.1:\n                    df_temp2_Y.iloc[temp1[0],df_temp2_Y.columns.get_loc('bandgap value (eV)')] = mean\n                    df_no_repeat_Y.append(df_temp2_Y.iloc[temp1[0]])\n                    df_no_repeat_X.append(df_temp2_X.iloc[temp1[0]])\ndf_gw_X = pd.DataFrame(df_no_repeat_X)\ndf_gw_Y = pd.DataFrame(df_no_repeat_Y)\n```\n\n# Set and initiate the MEGNet model\n\n\n```python\n# install megnet\n!pip install megnet\n!pip install jsonlines\n```\n\n    Requirement already satisfied: megnet in /usr/local/lib/python3.7/dist-packages (1.2.8)\n    Requirement already satisfied: pymatgen>=2019.10.4 in /usr/local/lib/python3.7/dist-packages (from megnet) (2022.0.8)\n    Requirement already satisfied: monty in /usr/local/lib/python3.7/dist-packages (from megnet) (2021.5.9)\n    Requirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from megnet) (0.24.2)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from megnet) (1.20.3)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen>=2019.10.4->megnet) (0.17.7)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from pymatgen>=2019.10.4->megnet) (1.7.1)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen>=2019.10.4->megnet) (3.2.2)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen>=2019.10.4->megnet) (2.5.1)\n    Requirement already satisfied: uncertainties>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from pymatgen>=2019.10.4->megnet) (3.1.5)\n    Requirement already satisfied: typing-extensions>=3.7.4.3; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from pymatgen>=2019.10.4->megnet) (3.7.4.3)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen>=2019.10.4->megnet) (3.3.0)\n    Requirement already satisfied: plotly>=4.5.0 in /usr/local/lib/python3.7/dist-packages (from pymatgen>=2019.10.4->megnet) (4.14.3)\n    Requirement already satisfied: scipy>=1.5.0 in /usr/local/lib/python3.7/dist-packages (from pymatgen>=2019.10.4->megnet) (1.6.3)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen>=2019.10.4->megnet) (1.16.1)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen>=2019.10.4->megnet) (2.23.0)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen>=2019.10.4->megnet) (0.8.9)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from pymatgen>=2019.10.4->megnet) (1.1.5)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->megnet) (1.0.1)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->megnet) (2.1.0)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen>=2019.10.4->megnet) (0.2.2)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->pymatgen>=2019.10.4->megnet) (1.2.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen>=2019.10.4->megnet) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen>=2019.10.4->megnet) (1.3.1)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen>=2019.10.4->megnet) (2.8.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen>=2019.10.4->megnet) (2.4.7)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.2->pymatgen>=2019.10.4->megnet) (4.4.2)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from uncertainties>=3.1.4->pymatgen>=2019.10.4->megnet) (0.16.0)\n    Requirement already satisfied: retrying>=1.3.3 in /usr/local/lib/python3.7/dist-packages (from plotly>=4.5.0->pymatgen>=2019.10.4->megnet) (1.3.3)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from plotly>=4.5.0->pymatgen>=2019.10.4->megnet) (1.16.0)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen>=2019.10.4->megnet) (2020.12.5)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen>=2019.10.4->megnet) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen>=2019.10.4->megnet) (2.10)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen>=2019.10.4->megnet) (1.24.3)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen>=2019.10.4->megnet) (2018.9)\n    Requirement already satisfied: jsonlines in /usr/local/lib/python3.7/dist-packages (2.0.0)\n\n\nDefine data fidelity\n\n\n```python\nALL_FIDELITIES = ['pbe','pbe1','mbj', 'gllb-sc', 'hse','gw','exp']\nTRAIN_FIDELITIES= ['pbe','pbe1','mbj', 'gllb-sc', 'hse', 'gw','exp']\nVAL_FIDELITIES = ['mbj','gllb-sc', 'hse', 'gw','exp']\nTEST_FIDELITIES= ['pbe','pbe1','mbj', 'gllb-sc', 'hse', 'gw','exp']\n```\n\nImport needed modules\n\n\n```python\nfrom megnet.callbacks import ReduceLRUponNan, ManualStop\nfrom megnet.data.crystal import CrystalGraph\nfrom megnet.data.graph import GraphBatchDistanceConvert, GaussianDistance\nfrom megnet.models import MEGNetModel\n\n# import jsonlines\n\n\nimport tensorflow as tf\ntf.compat.v1.disable_eager_execution()\n```\n\nInitiate the megnet model\n\n\n```python\n##  Set the number of maximum epochs to 1500\nEPOCHS = 1500\n\n##  Random seed\nSEED = 11742\ncrystal_graph = CrystalGraph(\n        bond_converter=GaussianDistance(centers=np.linspace(0, 6, 100),\n                                        width=0.5),\n        cutoff=5.0)\nmodel = MEGNetModel(nfeat_edge=100, nfeat_global=None, ngvocal=len(TRAIN_FIDELITIES),\n                    global_embedding_dim=16,  nblocks=3, nvocal=95,\n                    npass=2, graph_converter=crystal_graph, lr=1e-3)\n```\n\n    WARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/array_ops.py:5049: calling gather (from tensorflow.python.ops.array_ops) with validate_indices is deprecated and will be removed in a future version.\n    Instructions for updating:\n    The `validate_indices` argument has no effect. Indices are always validated on CPU and never validated on GPU.\n\n\n    WARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/array_ops.py:5049: calling gather (from tensorflow.python.ops.array_ops) with validate_indices is deprecated and will be removed in a future version.\n    Instructions for updating:\n    The `validate_indices` argument has no effect. Indices are always validated on CPU and never validated on GPU.\n    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:375: UserWarning: The `lr` argument is deprecated, use `learning_rate` instead.\n      \"The `lr` argument is deprecated, use `learning_rate` instead.\")\n\n\nSet the structure feature(graph) and target (bandgap value).\n\n\n```python\ngraphs = []\ntargets = []\nindexs = []\n\nfor fidelity_id, fidelity in enumerate(ALL_FIDELITIES):\n    if fidelity == 'hse':\n        N = len(df_hse_X)\n        df_temp_X = df_hse_X.copy()\n        df_temp_Y = df_hse_Y.copy()\n    elif fidelity == 'gw':\n        N = len(df_gw_X)\n        df_temp_X = df_gw_X.copy()\n        df_temp_Y = df_gw_Y.copy()\n    elif fidelity == 'gllb-sc':\n        N = len(df_gllb_X)\n        df_temp_X = df_gllb_X.copy()\n        df_temp_Y = df_gllb_Y.copy()\n    elif fidelity == 'exp':\n        N = len(df_exp_X)\n        df_temp_X = df_exp_X.copy()\n        df_temp_Y = df_exp_Y.copy()\n    elif fidelity == 'pbe':\n        N = len(df_pbe_X)\n        df_temp_X = df_pbe_X.copy()\n        df_temp_Y = df_pbe_Y.copy()\n    elif fidelity == 'mbj':\n        N = len(df_mbj_X)\n        df_temp_X = df_mbj_X.copy()\n        df_temp_Y = df_mbj_Y.copy()\n        \n    for index in range(N):\n        try:\n            graph = crystal_graph.convert(Structure.from_dict(df_temp_X.iloc[index]['structure']))\n            graph['state'] = [fidelity_id]\n            graphs.append(graph)\n            bd_value = float(df_temp_Y.iloc[index]['bandgap value (eV)'])\n            targets.append(bd_value)\n            indexs.append('%s_%s' % (str(index), fidelity))\n        except:\n            pass\n\nfinal_graphs = {i:j for i, j in zip(indexs, graphs)}\nfinal_targets = {i:j for i, j in zip(indexs, targets)}\n```\n\nData split\n\n\n```python\nfrom sklearn.model_selection import train_test_split\n\n##  train:val:test = 8:1:1\nfidelity_list = [i.split('_')[1] for i in indexs]\ntrain_val_ids, test_ids = train_test_split(indexs, stratify=fidelity_list,\n                                           test_size=0.1, random_state=SEED)\nfidelity_list = [i.split('_')[1] for i in train_val_ids]\ntrain_ids, val_ids = train_test_split(train_val_ids, stratify=fidelity_list,\n                                      test_size=0.1/0.9, random_state=SEED)\n\n##  remove pbe from validation\nval_ids = [i for i in val_ids if not i.endswith('pbe')]\n\nprint(\"Train, val and test data sizes are \", len(train_ids), len(val_ids), len(test_ids))\n```\n\n    Train, val and test data sizes are  144456 10562 18058\n\n\n\n```python\n## Get the train, val and test graph-target pairs\ndef get_graphs_targets(ids):\n    \"\"\"\n    Get graphs and targets list from the ids\n    \n    Args:\n        ids (List): list of ids\n    \n    Returns:\n        list of graphs and list of target values\n    \"\"\"\n    ids = [i for i in ids if i in final_graphs]\n    return [final_graphs[i] for i in ids], [final_targets[i] for i in ids]\n\ntrain_graphs, train_targets = get_graphs_targets(train_ids)\nval_graphs, val_targets = get_graphs_targets(val_ids)\n```\n\nModel training\n\n\n```python\ncallbacks = [ReduceLRUponNan(patience=500), ManualStop()]\nmodel.train_from_graphs(train_graphs, train_targets, val_graphs, val_targets,\n                        epochs=EPOCHS, verbose=2, initial_epoch=0, callbacks=callbacks)\n```\n\n    Epoch 1/1500\n\n\n    /usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/indexed_slices.py:449: UserWarning: Converting sparse IndexedSlices(IndexedSlices(indices=Tensor(\"training/Adam/gradients/gradients/set2set_atom/GatherV2_1_grad/Reshape_1:0\", shape=(None,), dtype=int32), values=Tensor(\"training/Adam/gradients/gradients/set2set_atom/GatherV2_1_grad/Reshape:0\", shape=(None,), dtype=float32), dense_shape=Tensor(\"training/Adam/gradients/gradients/set2set_atom/GatherV2_1_grad/Cast:0\", shape=(1,), dtype=int32))) to a dense Tensor of unknown shape. This may consume a large amount of memory.\n      \"shape. This may consume a large amount of memory.\" % value)\n    /usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/indexed_slices.py:449: UserWarning: Converting sparse IndexedSlices(IndexedSlices(indices=Tensor(\"training/Adam/gradients/gradients/set2set_bond/GatherV2_1_grad/Reshape_1:0\", shape=(None,), dtype=int32), values=Tensor(\"training/Adam/gradients/gradients/set2set_bond/GatherV2_1_grad/Reshape:0\", shape=(None,), dtype=float32), dense_shape=Tensor(\"training/Adam/gradients/gradients/set2set_bond/GatherV2_1_grad/Cast:0\", shape=(1,), dtype=int32))) to a dense Tensor of unknown shape. This may consume a large amount of memory.\n      \"shape. This may consume a large amount of memory.\" % value)\n    /usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/indexed_slices.py:449: UserWarning: Converting sparse IndexedSlices(IndexedSlices(indices=Tensor(\"training/Adam/gradients/gradients/set2set_atom/GatherV2_grad/Reshape_1:0\", shape=(None,), dtype=int32), values=Tensor(\"training/Adam/gradients/gradients/set2set_atom/GatherV2_grad/Reshape:0\", shape=(None,), dtype=float32), dense_shape=Tensor(\"training/Adam/gradients/gradients/set2set_atom/GatherV2_grad/Cast:0\", shape=(1,), dtype=int32))) to a dense Tensor of unknown shape. This may consume a large amount of memory.\n      \"shape. This may consume a large amount of memory.\" % value)\n    /usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/indexed_slices.py:449: UserWarning: Converting sparse IndexedSlices(IndexedSlices(indices=Tensor(\"training/Adam/gradients/gradients/set2set_bond/GatherV2_grad/Reshape_1:0\", shape=(None,), dtype=int32), values=Tensor(\"training/Adam/gradients/gradients/set2set_bond/GatherV2_grad/Reshape:0\", shape=(None,), dtype=float32), dense_shape=Tensor(\"training/Adam/gradients/gradients/set2set_bond/GatherV2_grad/Cast:0\", shape=(1,), dtype=int32))) to a dense Tensor of unknown shape. This may consume a large amount of memory.\n      \"shape. This may consume a large amount of memory.\" % value)\n\n", "meta": {"hexsha": "05b1b562524a29ae47bd8b85241ff0d099a99aec", "size": 64018, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Notebook/Bandgap_model_demo.ipynb", "max_stars_repo_name": "ucsdlxg/ML_bandgap", "max_stars_repo_head_hexsha": "bc286b26bda56e9f146387b9976619b90b446b2e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Notebook/Bandgap_model_demo.ipynb", "max_issues_repo_name": "ucsdlxg/ML_bandgap", "max_issues_repo_head_hexsha": "bc286b26bda56e9f146387b9976619b90b446b2e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Notebook/Bandgap_model_demo.ipynb", "max_forks_repo_name": "ucsdlxg/ML_bandgap", "max_forks_repo_head_hexsha": "bc286b26bda56e9f146387b9976619b90b446b2e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-13T13:43:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-13T13:43:33.000Z", "avg_line_length": 64018.0, "max_line_length": 64018, "alphanum_fraction": 0.6642819207, "converted": true, "num_tokens": 16574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.051845469579796084, "lm_q1q2_score": 0.024708495801571643}}
{"text": "### Movies Recommendation System\n\nThis notebook is to introduce the recommender system that recommend movies for user based on different kind of recommendations: movies' popularity, user interests, movies having same actors, directors, etc. We will use demographic filtering and content based filtering \n\n\n```python\nimport numpy as np \nimport pandas as pd \ndf1 = pd.read_csv('tmdb_5000_credits.csv')\ndf2 = pd.read_csv('tmdb_5000_movies.csv')\n```\n\n\n```python\n# Preprocessing \ndf1.info()\ndf2.info()\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 4803 entries, 0 to 4802\n    Data columns (total 4 columns):\n     #   Column    Non-Null Count  Dtype \n    ---  ------    --------------  ----- \n     0   movie_id  4803 non-null   int64 \n     1   title     4803 non-null   object\n     2   cast      4803 non-null   object\n     3   crew      4803 non-null   object\n    dtypes: int64(1), object(3)\n    memory usage: 150.2+ KB\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 4803 entries, 0 to 4802\n    Data columns (total 20 columns):\n     #   Column                Non-Null Count  Dtype  \n    ---  ------                --------------  -----  \n     0   budget                4803 non-null   int64  \n     1   genres                4803 non-null   object \n     2   homepage              1712 non-null   object \n     3   id                    4803 non-null   int64  \n     4   keywords              4803 non-null   object \n     5   original_language     4803 non-null   object \n     6   original_title        4803 non-null   object \n     7   overview              4800 non-null   object \n     8   popularity            4803 non-null   float64\n     9   production_companies  4803 non-null   object \n     10  production_countries  4803 non-null   object \n     11  release_date          4802 non-null   object \n     12  revenue               4803 non-null   int64  \n     13  runtime               4801 non-null   float64\n     14  spoken_languages      4803 non-null   object \n     15  status                4803 non-null   object \n     16  tagline               3959 non-null   object \n     17  title                 4803 non-null   object \n     18  vote_average          4803 non-null   float64\n     19  vote_count            4803 non-null   int64  \n    dtypes: float64(3), int64(4), object(13)\n    memory usage: 750.6+ KB\n\n\n\n```python\n# check for NA values in df1 \ndf1.isna().sum()\n```\n\n\n\n\n    movie_id    0\n    title       0\n    cast        0\n    crew        0\n    dtype: int64\n\n\n\n\n```python\n# check for NA values in df2\ndf2.isna().sum()\n```\n\n\n\n\n    budget                     0\n    genres                     0\n    homepage                3091\n    id                         0\n    keywords                   0\n    original_language          0\n    original_title             0\n    overview                   3\n    popularity                 0\n    production_companies       0\n    production_countries       0\n    release_date               1\n    revenue                    0\n    runtime                    2\n    spoken_languages           0\n    status                     0\n    tagline                  844\n    title                      0\n    vote_average               0\n    vote_count                 0\n    dtype: int64\n\n\n\n\n```python\n# merge 2 data set based on id \ndf1.columns = ['id','tittle','cast','crew']\ndf2= df2.merge(df1,on='id')\ndf2.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>level_0</th>\n      <th>index</th>\n      <th>budget</th>\n      <th>genres</th>\n      <th>homepage</th>\n      <th>id</th>\n      <th>keywords</th>\n      <th>original_language</th>\n      <th>original_title</th>\n      <th>overview</th>\n      <th>...</th>\n      <th>cast_x</th>\n      <th>crew_x</th>\n      <th>director</th>\n      <th>soup</th>\n      <th>tittle_y</th>\n      <th>cast_y</th>\n      <th>crew_y</th>\n      <th>tittle</th>\n      <th>cast</th>\n      <th>crew</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0</td>\n      <td>0</td>\n      <td>237000000</td>\n      <td>[action, adventure, fantasy]</td>\n      <td>http://www.avatarmovie.com/</td>\n      <td>19995</td>\n      <td>[cultureclash, future, spacewar]</td>\n      <td>en</td>\n      <td>Avatar</td>\n      <td>In the 22nd century, a paraplegic Marine is di...</td>\n      <td>...</td>\n      <td>[samworthington, zoesaldana, sigourneyweaver]</td>\n      <td>[{'credit_id': '52fe48009251416c750aca23', 'de...</td>\n      <td>jamescameron</td>\n      <td>cultureclash future spacewar samworthington zo...</td>\n      <td>Avatar</td>\n      <td>[{\"cast_id\": 242, \"character\": \"Jake Sully\", \"...</td>\n      <td>[{\"credit_id\": \"52fe48009251416c750aca23\", \"de...</td>\n      <td>Avatar</td>\n      <td>[{\"cast_id\": 242, \"character\": \"Jake Sully\", \"...</td>\n      <td>[{\"credit_id\": \"52fe48009251416c750aca23\", \"de...</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>1</td>\n      <td>300000000</td>\n      <td>[adventure, fantasy, action]</td>\n      <td>http://disney.go.com/disneypictures/pirates/</td>\n      <td>285</td>\n      <td>[ocean, drugabuse, exoticisland]</td>\n      <td>en</td>\n      <td>Pirates of the Caribbean: At World's End</td>\n      <td>Captain Barbossa, long believed to be dead, ha...</td>\n      <td>...</td>\n      <td>[johnnydepp, orlandobloom, keiraknightley]</td>\n      <td>[{'credit_id': '52fe4232c3a36847f800b579', 'de...</td>\n      <td>goreverbinski</td>\n      <td>ocean drugabuse exoticisland johnnydepp orland...</td>\n      <td>Pirates of the Caribbean: At World's End</td>\n      <td>[{\"cast_id\": 4, \"character\": \"Captain Jack Spa...</td>\n      <td>[{\"credit_id\": \"52fe4232c3a36847f800b579\", \"de...</td>\n      <td>Pirates of the Caribbean: At World's End</td>\n      <td>[{\"cast_id\": 4, \"character\": \"Captain Jack Spa...</td>\n      <td>[{\"credit_id\": \"52fe4232c3a36847f800b579\", \"de...</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2</td>\n      <td>2</td>\n      <td>245000000</td>\n      <td>[action, adventure, crime]</td>\n      <td>http://www.sonypictures.com/movies/spectre/</td>\n      <td>206647</td>\n      <td>[spy, basedonnovel, secretagent]</td>\n      <td>en</td>\n      <td>Spectre</td>\n      <td>A cryptic message from Bond\u2019s past sends him o...</td>\n      <td>...</td>\n      <td>[danielcraig, christophwaltz, l\u00e9aseydoux]</td>\n      <td>[{'credit_id': '54805967c3a36829b5002c41', 'de...</td>\n      <td>sammendes</td>\n      <td>spy basedonnovel secretagent danielcraig chris...</td>\n      <td>Spectre</td>\n      <td>[{\"cast_id\": 1, \"character\": \"James Bond\", \"cr...</td>\n      <td>[{\"credit_id\": \"54805967c3a36829b5002c41\", \"de...</td>\n      <td>Spectre</td>\n      <td>[{\"cast_id\": 1, \"character\": \"James Bond\", \"cr...</td>\n      <td>[{\"credit_id\": \"54805967c3a36829b5002c41\", \"de...</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>3</td>\n      <td>3</td>\n      <td>250000000</td>\n      <td>[action, crime, drama]</td>\n      <td>http://www.thedarkknightrises.com/</td>\n      <td>49026</td>\n      <td>[dccomics, crimefighter, terrorist]</td>\n      <td>en</td>\n      <td>The Dark Knight Rises</td>\n      <td>Following the death of District Attorney Harve...</td>\n      <td>...</td>\n      <td>[christianbale, michaelcaine, garyoldman]</td>\n      <td>[{'credit_id': '52fe4781c3a36847f81398c3', 'de...</td>\n      <td>christophernolan</td>\n      <td>dccomics crimefighter terrorist christianbale ...</td>\n      <td>The Dark Knight Rises</td>\n      <td>[{\"cast_id\": 2, \"character\": \"Bruce Wayne / Ba...</td>\n      <td>[{\"credit_id\": \"52fe4781c3a36847f81398c3\", \"de...</td>\n      <td>The Dark Knight Rises</td>\n      <td>[{\"cast_id\": 2, \"character\": \"Bruce Wayne / Ba...</td>\n      <td>[{\"credit_id\": \"52fe4781c3a36847f81398c3\", \"de...</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>4</td>\n      <td>4</td>\n      <td>260000000</td>\n      <td>[action, adventure, sciencefiction]</td>\n      <td>http://movies.disney.com/john-carter</td>\n      <td>49529</td>\n      <td>[basedonnovel, mars, medallion]</td>\n      <td>en</td>\n      <td>John Carter</td>\n      <td>John Carter is a war-weary, former military ca...</td>\n      <td>...</td>\n      <td>[taylorkitsch, lynncollins, samanthamorton]</td>\n      <td>[{'credit_id': '52fe479ac3a36847f813eaa3', 'de...</td>\n      <td>andrewstanton</td>\n      <td>basedonnovel mars medallion taylorkitsch lynnc...</td>\n      <td>John Carter</td>\n      <td>[{\"cast_id\": 5, \"character\": \"John Carter\", \"c...</td>\n      <td>[{\"credit_id\": \"52fe479ac3a36847f813eaa3\", \"de...</td>\n      <td>John Carter</td>\n      <td>[{\"cast_id\": 5, \"character\": \"John Carter\", \"c...</td>\n      <td>[{\"credit_id\": \"52fe479ac3a36847f813eaa3\", \"de...</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 33 columns</p>\n</div>\n\n\n\n### Demographic Filtering \nThis filter is suitable to recommend movies for all kinds of users, not based on particular interets of each user\nWe will use IMDB's weighted ratinf (WR) which is given as:\n\\begin{equation}                                    \n                                    WR = {\\frac{vR}{v+m}}+{\\frac{mC}{v+m}}\n\\end{equation}               \nwhere, <br>\nv: is the number of votes for the movie <br>\nm: is the minimum votes required to be listed in the chart <br>\nR: is the average rating of the movie <br>\nC: is the mean vote across the whole report \n\n\n```python\n# compute the average mean for the whole report\nC = df2['vote_average'].mean()\nC\n```\n\n\n\n\n    6.092171559442011\n\n\n\n\n```python\n# compute the minium votes require. We used 90% as a threshold \nm = df2['vote_count'].quantile(0.9)\nm\n```\n\n\n\n\n    1838.4000000000015\n\n\n\n\n```python\n# create a new data set which contains only movies having more than m votes\nnew_df = df2.copy().loc[df2['vote_count'] >= m]\nnew_df.shape\n```\n\n\n\n\n    (481, 23)\n\n\n\n\n```python\n# This is function computing the Weighted Rating \ndef weighted_rating(x, m = m , C = C):\n    v = x['vote_count']\n    R = x['vote_average']\n    return (v/(v+m)*R) + (m/(v+m)*C)\n```\n\n\n```python\n# create a new column name 'score' which is socre of weighted rating of each movie\nnew_df['score'] = new_df.apply(weighted_rating, axis = 1)\n```\n\n\n```python\n# print out results\nnew_df = new_df.sort_values('score', ascending = False)\nnew_df[['title', 'vote_count', 'vote_average', 'score']].head(10)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>title</th>\n      <th>vote_count</th>\n      <th>vote_average</th>\n      <th>score</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1881</th>\n      <td>The Shawshank Redemption</td>\n      <td>8205</td>\n      <td>8.5</td>\n      <td>8.059258</td>\n    </tr>\n    <tr>\n      <th>662</th>\n      <td>Fight Club</td>\n      <td>9413</td>\n      <td>8.3</td>\n      <td>7.939256</td>\n    </tr>\n    <tr>\n      <th>65</th>\n      <td>The Dark Knight</td>\n      <td>12002</td>\n      <td>8.2</td>\n      <td>7.920020</td>\n    </tr>\n    <tr>\n      <th>3232</th>\n      <td>Pulp Fiction</td>\n      <td>8428</td>\n      <td>8.3</td>\n      <td>7.904645</td>\n    </tr>\n    <tr>\n      <th>96</th>\n      <td>Inception</td>\n      <td>13752</td>\n      <td>8.1</td>\n      <td>7.863239</td>\n    </tr>\n    <tr>\n      <th>3337</th>\n      <td>The Godfather</td>\n      <td>5893</td>\n      <td>8.4</td>\n      <td>7.851236</td>\n    </tr>\n    <tr>\n      <th>95</th>\n      <td>Interstellar</td>\n      <td>10867</td>\n      <td>8.1</td>\n      <td>7.809479</td>\n    </tr>\n    <tr>\n      <th>809</th>\n      <td>Forrest Gump</td>\n      <td>7927</td>\n      <td>8.2</td>\n      <td>7.803188</td>\n    </tr>\n    <tr>\n      <th>329</th>\n      <td>The Lord of the Rings: The Return of the King</td>\n      <td>8064</td>\n      <td>8.1</td>\n      <td>7.727243</td>\n    </tr>\n    <tr>\n      <th>1990</th>\n      <td>The Empire Strikes Back</td>\n      <td>5879</td>\n      <td>8.2</td>\n      <td>7.697884</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# Look for what movies are trending now based on the attribute 'popularity'\npop = df2.sort_values('popularity', ascending = False)\nimport matplotlib.pyplot as plt \nplt.figure(figsize = (12,5))\nplt.barh(pop['title'].head(10), pop['popularity'].head(10), align = 'center', color = 'skyblue')\nplt.gca().invert_yaxis()\nplt.xlabel('Popularity')\nplt.title('Popular movies now')\n```\n\n### Content Based Filtering\nIn this section, we will do text processing using Term Frequency - Inverse Document Frequency (TF-IDF).\n\n\n```python\nfrom sklearn.feature_extraction.text import TfidfVectorizer\ntf_idf = TfidfVectorizer(stop_words = 'english', lowercase = True)\ndf2['overview'] = df2['overview'].fillna('na')\ntf_idf_matrix = tf_idf.fit_transform(df2['overview'])\ntf_idf_matrix.shape\n```\n\n\n\n\n    (4803, 20979)\n\n\n\nWe will be using the cosine similiarity to calculate a numeric qunatity the denotes similarity between two movies. Using the cosin similarity score is good choice since it is independent of magnitude and is relatively easy and fast to calculate\n\n\n```python\n# Import linear_kernel\nfrom sklearn.metrics.pairwise import linear_kernel\n# Compute the cosine similarity matrix\ncosine_sim = linear_kernel(tf_idf_matrix, tf_idf_matrix)\n\n```\n\n\n```python\n# Construct a reverse map of indices and movies titles\nindices = pd.Series(df2.index, index = df2['title']).drop_duplicates()\n```\n\n\n```python\n# Function that takes in movie title as input and outputs are most similar movies \ndef get_recommendations(title, cosine_sim = cosine_sim):\n\n    # get the index of movie that matches the title\n    indx = indices[title]\n    # get the pairwise similarity scores of all movies with particular one \n    sim_scores = list(enumerate(cosine_sim[indx]))\n    # sort the score \n    sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)\n    # get score of 10 most similar movies \n    sim_scores = sim_scores[1:11]\n    # get the movies indices \n    movies_indices = [i[0] for i in sim_scores]\n    # return the top 10 movies \n    return df2['title'].iloc[movies_indices]\n    \n```\n\n\n```python\nget_recommendations('The Dark Knight Rises')\n```\n\n\n\n\n    65                              The Dark Knight\n    299                              Batman Forever\n    428                              Batman Returns\n    1359                                     Batman\n    3854    Batman: The Dark Knight Returns, Part 2\n    119                               Batman Begins\n    2507                                  Slow Burn\n    9            Batman v Superman: Dawn of Justice\n    1181                                        JFK\n    210                              Batman & Robin\n    Name: title, dtype: object\n\n\n\n### Credits, Genres and Keywords Based Recommender\nThe quality of recommender would be incresed with the usage of better metadata. We are going to buid a recommender based on the following metadata: top 3 actors, directoes, related gernes and the movie plot keywords.\n\n\n```python\n# Parse the stringified features into their corresponding python objects\nfrom ast import literal_eval\nfeatures = ['cast', 'crew', 'keywords', 'genres']\nfor feature in features:\n    df2[feature] = df2[feature].apply(literal_eval)\n```\n\nBelow is the functions that will help us extract the required information from each features above\n\n\n```python\n# get the director's name from the crew feature. If director is not listed, return NaN\ndef get_director(x):\n    for i in x:\n        if i['job'] == 'Director':\n            return i['name']\n    return np.nan\n```\n\n\n```python\n# return the list top 3 elements or entire list; whichever is more \ndef get_list(x):\n    if isinstance(x, list):\n        names = [i['name'] for i in x]\n        if len(names) > 3:\n            names = names[:3]\n        return names \n    return []\n```\n\n\n```python\n# define new director, casr, genres and keywords features that are in suitable form\ndf2['director'] = df2['crew'].apply(get_director)\nfeatures = ['cast','keywords', 'genres']\nfor feature in features:\n    df2[feature] = df2[feature].apply(get_list)\n```\n\n\n```python\n# Print the new features of the first 3 films\ndf2[['title', 'cast', 'director', 'keywords', 'genres']].head(10)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>title</th>\n      <th>cast</th>\n      <th>director</th>\n      <th>keywords</th>\n      <th>genres</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Avatar</td>\n      <td>[Sam Worthington, Zoe Saldana, Sigourney Weaver]</td>\n      <td>James Cameron</td>\n      <td>[culture clash, future, space war]</td>\n      <td>[Action, Adventure, Fantasy]</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Pirates of the Caribbean: At World's End</td>\n      <td>[Johnny Depp, Orlando Bloom, Keira Knightley]</td>\n      <td>Gore Verbinski</td>\n      <td>[ocean, drug abuse, exotic island]</td>\n      <td>[Adventure, Fantasy, Action]</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Spectre</td>\n      <td>[Daniel Craig, Christoph Waltz, L\u00e9a Seydoux]</td>\n      <td>Sam Mendes</td>\n      <td>[spy, based on novel, secret agent]</td>\n      <td>[Action, Adventure, Crime]</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>The Dark Knight Rises</td>\n      <td>[Christian Bale, Michael Caine, Gary Oldman]</td>\n      <td>Christopher Nolan</td>\n      <td>[dc comics, crime fighter, terrorist]</td>\n      <td>[Action, Crime, Drama]</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>John Carter</td>\n      <td>[Taylor Kitsch, Lynn Collins, Samantha Morton]</td>\n      <td>Andrew Stanton</td>\n      <td>[based on novel, mars, medallion]</td>\n      <td>[Action, Adventure, Science Fiction]</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>Spider-Man 3</td>\n      <td>[Tobey Maguire, Kirsten Dunst, James Franco]</td>\n      <td>Sam Raimi</td>\n      <td>[dual identity, amnesia, sandstorm]</td>\n      <td>[Fantasy, Action, Adventure]</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Tangled</td>\n      <td>[Zachary Levi, Mandy Moore, Donna Murphy]</td>\n      <td>Byron Howard</td>\n      <td>[hostage, magic, horse]</td>\n      <td>[Animation, Family]</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Avengers: Age of Ultron</td>\n      <td>[Robert Downey Jr., Chris Hemsworth, Mark Ruff...</td>\n      <td>Joss Whedon</td>\n      <td>[marvel comic, sequel, superhero]</td>\n      <td>[Action, Adventure, Science Fiction]</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Harry Potter and the Half-Blood Prince</td>\n      <td>[Daniel Radcliffe, Rupert Grint, Emma Watson]</td>\n      <td>David Yates</td>\n      <td>[witch, magic, broom]</td>\n      <td>[Adventure, Fantasy, Family]</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>Batman v Superman: Dawn of Justice</td>\n      <td>[Ben Affleck, Henry Cavill, Gal Gadot]</td>\n      <td>Zack Snyder</td>\n      <td>[dc comics, vigilante, superhero]</td>\n      <td>[Action, Adventure, Fantasy]</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# Functon to convert all strinsg and list to lower case and strip names of spaces\n\n# Function to convert all strings to lower case and strip names of spaces\ndef clean_data(x):\n    if isinstance(x, list):\n        return [str.lower(i.replace(\" \", \"\")) for i in x]\n    else:\n        #Check if director exists. If not, return empty string\n        if isinstance(x, str):\n            return str.lower(x.replace(\" \", \"\"))\n        else:\n            return ''\n```\n\n\n```python\n# Apply clean_data function to your features.\nfeatures = ['cast', 'keywords', 'director', 'genres']\nfor feature in features:\n    df2[feature] = df2[feature].apply(clean_data)\n```\n\nNow, we will create a 'metadata soup' which is a string that contains all the metadat that we want to feed our vectorizer (actors, directors, keywords)\n\n\n```python\ndef create_soup(x):\n    return ' '.join(x['keywords']) + ' ' + ' '.join(x['cast']) + ' ' + x['director'] + ' ' + ' '.join(x['genres'])\ndf2['soup'] = df2.apply(create_soup, axis=1)\n```\n\nInstead of using TF-IDF, we use CountVectorizer so that it will not down weight the presence of an actor/director when\nhe/she really acted or directed directly in the movies.\n\n\n```python\nfrom sklearn.feature_extraction.text import CountVectorizer\ncount = CountVectorizer(stop_words = 'english')\ncount_mat = count.fit_transform(df2['soup'])\n```\n\n\n```python\n#Compute the Cosine Similarity matrix based on the count_matrix\nfrom sklearn.metrics.pairwise import cosine_similarity\ncosine_sim2 = cosine_similarity(count_mat, count_mat)\n```\n\n\n```python\ndf2 = df2.reset_index()\nindices = pd.Series(df2.index, index = df2['title'])\n```\n\n\n```python\nget_recommendations('The Dark Knight Rises', cosine_sim2)\n```\n\n\n\n\n    65               The Dark Knight\n    119                Batman Begins\n    4638    Amidst the Devil's Wings\n    1196                The Prestige\n    3073           Romeo Is Bleeding\n    3326              Black November\n    1503                      Takers\n    1986                      Faster\n    303                     Catwoman\n    747               Gangster Squad\n    Name: title, dtype: object\n\n\n\nNotice that the recommender system has given better result in capturing more information based on metadata. Marvel fans seems to like the movie with the same kind of production company. That is resulted by adding more features in the soup\n\n\n```python\n\n```\n", "meta": {"hexsha": "233b1140e8a5ebe2e4ee77f864b988ef209a3978", "size": 72464, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Movie Recommendation System .ipynb", "max_stars_repo_name": "phuongnguyen99/movies_recommender_system", "max_stars_repo_head_hexsha": "6d9e86c83d13017bab44758a2df091e53e7435dd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Movie Recommendation System .ipynb", "max_issues_repo_name": "phuongnguyen99/movies_recommender_system", "max_issues_repo_head_hexsha": "6d9e86c83d13017bab44758a2df091e53e7435dd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Movie Recommendation System .ipynb", "max_forks_repo_name": "phuongnguyen99/movies_recommender_system", "max_forks_repo_head_hexsha": "6d9e86c83d13017bab44758a2df091e53e7435dd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.0641025641, "max_line_length": 21956, "alphanum_fraction": 0.6253863988, "converted": true, "num_tokens": 6548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.07369626411128531, "lm_q1q2_score": 0.024657991831442176}}
{"text": "Notebook by **Jakob R. J\u00fcrgens** - Final project for the courses **OSE - Data Science** in the summer semester 2021 and **OSE - Scientific Computing** in the winter semester 2021/2022 - Find me at [jakobjuergens.com](https://jakobjuergens.com) <br>\n# Outlier Detection in Sensor Data using Functional Depth Measures\n---\n\nThe best way to access this project is to clone this repository and execute the jupyter notebook and the shiny app locally. Alternatively, on the main site of this repository, there are nbviewer and binder badges set up to directly look at them in the browser.\n\nThe following packages and their dependencies are necessary to execute the notebook and the shiny app. If you are executing the code locally, make sure that these packages are provided and that an R Kernel (like irkernel) is activated in the Jupyter notebook.\n\n\n```R\nsuppressMessages(library(devtools))\nsuppressMessages(library(MASS))\nsuppressMessages(library(tidyverse))\nsuppressMessages(library(shiny))\nsuppressMessages(library(shinydashboard))\nsuppressMessages(library(largeList))\nsuppressMessages(library(parallel))\nsuppressMessages(library(Rcpp))\nsuppressMessages(library(repr))\n\noptions(repr.plot.width=30, repr.plot.height=8)\n\ninstall.packages('Code/OutDetectR_1.0.tar.gz', repos = NULL, type = 'source')\nlibrary(OutDetectR)\n\nsource(\"Code/auxiliary/observation_vis.R\")\nsource(\"Code/auxiliary/distribution_vis.R\")\nsource(\"Code/auxiliary/updating_vis.R\")\nsource(\"Code/auxiliary/generate_set_1.R\")\nsource(\"Code/auxiliary/generate_set_2.R\")\nsource(\"Code/auxiliary/generate_set_3.R\")\n```\n\nIf you are in posession of the original Endanzug data set, convert it to a .RDS object using the provided function **data_prep()** from the package written for this project. Set the path to the RDS-object here. As it is property of Daimler AG, it is not included in the repository.\n\n\n```R\nreal_data <- TRUE\nif(real_data){\n    endanzug_path <- '~/F/data_local/Projekt_AMEIUS_Daten/schra.RDS'\n    endanzug_data <- readRDS(file = endanzug_path)\n}\n```\n\n## Table of Contents\n---\n1. [Introduction](#introduction)\n2. [Observation Structure](#observation)\n3. [The Algorithm](#algorithm)\n4. [h-modal depth](#h-modal)\n5. [Difficulties due to the Data](#difficulties)\n6. [Sampling Approach](#sampling)\n7. [Finding Comparable Sets of Observations](#comparables)\n8. [Description of Full Procedure for Existing Data sets](#procedure)\n9. [Updating](#updating)\n10. [Implementation](#implementation)\n    1. [Grid Approximation](#impl_grid) \n    2. [Febrero-Bande, Galeano, and Gonz\u00e0lez-Manteiga (2008) for Observations on a Shared Grid](#impl_algorithm)\n    3. [Sampling Approach](#impl_sampling)\n    4. [Dynamic Splitting](#impl_splitting)\n    5. [Full Procedure](#impl_full)\n    6. [Updating](#impl_upd)\n11. [How to use the package?](#how_to)\n12. [Simulated Data](#simulated)\n13. [Endanzug-Data](#application)\n14. [Shiny App](#shiny)\n15. [Outlook](#outlook)\n16. [Sources](#sources)\n\n## Introduction <a name=\"introduction\"></a>\n---\nThis project is part of a cooperation with **Daimler AG** and deals with outlier detection in sensor data from production processes. <br>\nIt serves as my final project for the courses **OSE - Data Science** (summer semester 2021) and **OSE - Scientific Computing for Economists** (winter semester 2021/2022).\n\nThe main data set that is used in this project deals with the relation of angle and torque during the process of tightening a bolt in a screwing connection. The corresponding data set will be called \"Endanzugsproblem\" in the following notebook and contains ~350000 observations of what can be imagined as a function that maps angles to torque. The following schematic will give an idea of what the data set represents and what the problem is:\n\n\n\nTo clarify some things about this simplified schematic:\n* The so called Endanzug is only part of the tightening process, but the parts of the observation happening before it are not subject of this analysis\n* The focus of this project lies on curves that are \"In Ordnung\", so observations that do not immediately disqualify themselves in some way by for example not reaching the fixed window of acceptable final values\n* The observations typically have a high frequency of measuring torque, but the measuring points are not equidistant\n* The angles where torque is measured are not shared between observations, but the measuring interval of angles might overlap between observations\n* The Endanzug does not start at the same angle for every observation and also does not necessarily start at the same torque\n* Outliers can be very general, so methods based on detecting only specific types of outliers may not be able to effectively filter out other suspicious observations. So the optimum would be to have some kind of Omnibus test for outliers\n\nEspecially due to the high frequency of measurement and the non-identical points where torque is measured, the idea of interpreting each observation as a function and therefore approaching the problem from a standpoint of functional data analysis comes to mind. One method that is used in functional data analysis to identify outliers is based on what is called a \"functional depth measure\". Gijbels and Nagy (2017) introduces the idea of depth as follows and then elaborate on the theoretical properties a depth function for functional data should possess:\n\n> For univariate data the sample median is well known\nto be appropriately describing the centre of a data\ncloud. An extension of this concept for multivariate\ndata (say p-dimensional) is the notion of a point (in\n$\\mathbb{R}^p$) for which a statistical depth function is maximized. \n\nThe idea is to define an analogous concept to centrality measures (such as the distance from some central tendency like the median) in a scalar setting for functional data and then use those to determine which functions in a set are typical for the whole population. Due to the more applied nature of this project, I will not go into detail on the theoretical properties of the methods used, but focus on giving intuition why the chosen methods make sense in this context.\n\nThe main inspiration for my approach to the problem of detecting outliers in a data set such as the one described above is the paper \"**Outlier detection in functional data by depth measures, with application to identify abnormal NOx levels**\" by Febrero-Bande, Galeano, and Gonz\u00e0lez-Manteiga (2008). I am going to first describe their algorithm, then present my extensions and my implementation and finally apply it to three simulated data sets mimicking the \"Endanzugsproblem\" as the original data is property of Daimler AG, which I cannot make public.\n\n## Observation Structure <a name=\"observation\"></a>\n---\nFor the sake of clarity, I will show the typical structure of one observation and define a couple of objects I will refer to later. To give context for the later choices of data generating processes, it is useful to know that the physical process of tightening a bolt is typically associated with a linear relationship between angle and torque (at least in the relevant parts of the tightening process) - this approximation is good for the parts of the tightening process that are part of the \"Endanzug\". Therefore, simulations in the later parts of this notebook typically assume an approximately linear process as the data generating process for non-outliers.\n\nOne observation in a data set might look as follows.\n\n\n\n| Observation \t| 1    \t| 2    \t| 3    \t| 4    \t| 5    \t| 6    \t| 7    \t| 8    \t| 9    \t| 10   \t| 11   \t| 12   \t| 13   \t| 14   \t| 15   \t| 16   \t| 17   \t| 18   \t| 19   \t| 20   \t|\n|:-----------:\t|------\t|------\t|------\t|------\t|------\t|------\t|------\t|------\t|------\t|------\t|------\t|------\t|------\t|------\t|------\t|------\t|------\t|------\t|------\t|------\t|\n|    Angle    \t| 2.01 \t| 2.21 \t| 2.91 \t| 3.00 \t| 3.07 \t| 3.95 \t| 4.33 \t| 4.35 \t| 4.41 \t| 4.74 \t| 4.77 \t| 5.06 \t| 6.33 \t| 6.37 \t| 6.41 \t| 6.57 \t| 7.25 \t| 7.32 \t| 7.71 \t| 7.94 \t|\n|    Torque   \t| 2.02 \t| 2.61 \t| 3.05 \t| 3.16 \t| 2.99 \t| 4.19 \t| 4.24 \t| 4.37 \t| 4.73 \t| 4.89 \t| 5.03 \t| 5.45 \t| 6.32 \t| 6.18 \t| 6.22 \t| 7.06 \t| 7.30 \t| 7.59 \t| 7.99 \t| 8.06 \t|\n\n* The red diamonds represent measurements of torque that were taken at a recorded angle.\n* The blue lines are an example of **linear interpolation** between the points that were actually measured. This will become important later on.\n* The **measuring interval** marked in green is the convex hull of angles where measurements were taken for this observation.\n\nThe data set contains many of these objects, that do not necessarily share these characteristics.\n\n\n```R\n# Generated using function from auxiliary/observation_vis.R\n# source(\"auxiliary/observation_vis.R\")\n# obs_vis()\n```\n\n## The Algorithm <a name=\"algorithm\"></a>\n---\nThe idea of Febrero-Bande, Galeano, and Gonz\u00e0lez-Manteiga (2008) is an iterative process that classifies observations as outliers if their functional depth lies below a threshold C, which is determined using a bootstrapping procedure in each iteration. <br> \nThe algorithm can be decomposed into two parts:\n\n1. **The iterative process**: (quoted from Febrero-Bande, Galeano, and Gonz\u00e0lez-Manteiga (2008))\n    1. Obtain the functional depths $D_n(x_i),\\: \\dots \\: ,D_n(x_n)$ for one of the functional depths [...]\n    2. Let $x_{i_1},\\: \\dots,\\: x_{i_k}$ be the k curves such that $D_n(x_{i_k}) \\leq C$, for a given cutoff $C$. Then, assume that $x_{i_1},\\: \\dots,\\: x_{i_k}$ are outliers and delete them from the sample.\n    3. Then, come back to step 1 with the new dataset after deleting the outliers found in step 2. Repeat this until no more outliers are found. \n    \nThe underlying idea is that observations that are more central in the sense of the chosen depth will have higher depth assigned to them. So choosing the least deep observations from a data set is a reasonable way to search for atypical observations. The question of where to draw the border for observations to be classified as abnormal is done using a bootstrapping procedure described next. <br>\n\n2. **Determining C**: (quoted from Febrero-Bande, Galeano, and Gonz\u00e0lez-Manteiga (2008))\n    1. Obtain the functional depths $D_n(x_i),\\: \\dots ,\\:D_n(x_n)$ for one of the functional depths [...]\n    2. Obtain B standard bootstrap samples of size n from the dataset of curves obtained after deleting the $\\alpha \\%$ less deepest curves. The bootstrap samples are denoted by $x_i^b$ for $i = 1,\\: \\dots,\\: n$ and $b = 1,\\: \\dots,\\: B$.\n    3. Obtain smoothed bootstrap samples $y_i^b = x_i^b + z_i^b$, where $z_i^b$ is such that $(z_i^b(t_1), \\dots, z_i^b(t_m))$ is normally distributed with mean 0 and covariance matrix $\\gamma\\Sigma_x$ where $\\Sigma_x$ is the covariance matrix of $x(t_1),\\: \\dots,\\: x(t_m)$ and $\\gamma$ is a smoothing parameter. Let $y_i^b$, $i = 1,\\: \\dots,\\:n$ and $b = 1,\\:\\dots,\\: B$ be these samples. *\n    4. For each bootstrap set $b = 1,\\:\\dots,\\:B$, obtain $C^b$ as the empirical 1% percentile of the distribution of the depths $D(y_i^b)$, $i = 1,\\: \\dots,\\: n$.\n    5. Take $C$ as the median of the values of $C^b$, $b = 1,\\: \\dots,\\: B$. \n<br>\n\nThis is done, as a theoretical derivation of the distribution of depth values for data generated by a specific data generating process is often infeasible. Instead, one drops a fraction of observations $\\alpha$ and uses a smoothed bootstrapping algorithm to approximate the corresponding threshold value to remove approximately that fraction of observations in the procedure listed under 1.\n\n*At this point in the algorithm the assumption that the functional observations are observed at a set of discrete points $t_1,\\:\\dots,\\:t_m$ has already been made. <br>\n\nSome important points:\n* I decided to deviate from the original procedure proposed by the authors by allowing the user to decide whether to reestimate $C$ in each iteration of the process. The authors present good arguments, why keeping $C$ fixed is the better approach and my testing confirms those. But to keep the possibilities for experimentation open, I opted to implement it in this way nevertheless. In later stages of this project I will go into detail on why keeping $C$ constant also has some problems and try to introduce corrections to improve the method developped below.\n* The authors recommend a choice of $\\gamma = 0.05$ as a smoothing parameter for the bootstrap which I adopted in my applications.\n* For the choice of $\\alpha$ preexisting information on the data should be used if available. A good way to choose this is the expected fraction of outliers in the data. However, my testing showed that in some cases the choice of this parameter had to be lower than the actual fraction of observations generated by abnormal processes when using a sampling procedure to get better results.\n\nThe authors propose three functional depth measures and benchmark them in a simulation setting. Because of their results and the computational cost which are comparatively small, I chose to use **h-modal depth** for my implementation, which I will introduce in the following.\n\n## h-modal depth <a name=\"h-modal\"></a>\n---\n\nIntroduced by Cuevas, Febrero-Bande, and Fraiman (2006) h-modal depth is one of three depth measures covered in Febrero-Bande, Galeano, and Gonz\u00e0lez-Manteiga (2008). I will follow the summary in the latter paper for my overview.  <br> The idea behind this depth is that a curve is central in a set of curves if it is closely surrounded by other curves. <br>\n\nIn mathematical terms, the h-modal depth of a curve $x_i$ in relation to a set of curves $x_1, \\dots, x_n$ is defined as follows: <br>\n\\begin{equation}\n    MD_m(x_i,h) = \\sum_{k = 1}^{n} K(\\frac{||x_i - x_k||}{h})\n\\end{equation}\n\nwhere $K: \\mathbb{R^{+}} \\rightarrow \\mathbb{R^{+}}$ is a kernel function and $h$ is a bandwidth. <br>\nThe authors recommend using the truncated Gaussian kernel, which is defined as follows:\n\\begin{equation}\n    K(t) = \\frac{2}{\\sqrt{2\\pi}} \\exp(-\\frac{t^2}{2}) \\quad \\text{for} \\quad t>0 \\quad \\text{and} \\quad 0 \\quad \\text{otherwise}\n\\end{equation}\n\nand to choose $h$ as the 15th percentile of the empirical distribution of $\\{||x_i - x_k|| \\, | \\, i,k = 1,\\:\\dots,\\:n\\}$\n\nI chose to implement the $L^2$ norm - one of the norms recommended by the authors - as it performed better than the $L^{\\infty}$ norm (which was also recommended) in my preliminary tests. In a functional setting $L^2$ is defined by:\n\\begin{equation}\n    ||x_i - x_k||_{2} = \\sqrt{\\int_a^b (x_i(t) - x_k(t))^2 dt}\n\\end{equation}\n\nwhere a and b are the boundaries of the measurement interval. This can be replaced by its empirical version\n\\begin{equation}\n    ||x_i - x_k||_{2} = \\sqrt{\\sum_{j = 2}^m \\Delta_j(x_i(t_j) - x_k(t_j))^2} = \\sqrt{\\sum_{j = 2}^m (t_j - t_{j-1})(x_i(t_j) - x_k(t_j))^2}\n\\end{equation}\n\nin case of a discrete set of $m$ observation points shared between observations.\n\nThe choice of the functional norm could be adjusted to deal with data resembling different functional forms. This could be part of a possible extension, where different norms are implemented and compared. This might become part of future iteratons of this project.\n\n## Difficulties due to the Data <a name=\"difficulties\"></a>\n---\n### The Endanzug does not start at the same angle for every observation.\nIn this setting the fact that the first measurement is taken at different angles is not of a problem, since the property of interest is the shape of the curve after the Endanzug has started. In real world terms, the beginning of the \"Endanzug\" is determined by the first angle where a specific torque is exceeded and the change in torque during the \"Endanzug\" is of interest and not the position of the \"Endanzug\" in the whole tightening process. Therefore, all observations can be modified by subtracting the first angle of the \"Endanzug\" from all angles, effectively **zeroing** the observations. \n\nAt this time, I am going to focus on problems where zeroing is admissible and elaborate on how to possibly extend the method to scenarios where it is not. Those generalizations will be part of further work on this project.\n\n\n\n### After zeroing, the measurement intervals might still not be identical due to differing lengths.\nI decided to try to remedy this remaining problem in the zeroed data set by stretching the measuring intervals to a shared interval while leaving the observed torques identical. Excessive stretching however is problematic, as it can lead to similar observations ending up very different. Putting a conservative limit on stretching should however conserve the quality of relationships between observations. This should lead to limited influence on the calculated depths of the functional observations. To do so, I define a parameter $\\lambda \\geq 1$ called **acceptable stretching** and make observations comparable by stretching their measuring intervals by a factor $\\psi_i \\in [1/\\lambda, \\lambda]$ before approximating them using linear interpolation. In an optimal setting stretching would not be necessary and employing it leads to trade offs, so this parameter should be chosen conservatively.\n\nIf zeroing as described in 1. is not appropriate, a combination of **acceptable stretching** and **acceptable shifting** could be implemented to increase the size of sets of pairwise comparable functions. This will be part of future extensions of this project.\n\n\n\nAs you can already see in this animation, the acceptable stretching introduces inaccuracies even in an approximately linear setting. Outlier classifications could be quite sensitive to this parameter.\n\n### The angles where torque is measured are not shared between observations.\nAssuming that the measuring intervals are identical, I decided to use **linear interpolation** to approximate the observations. This is done to treat them as if they had been observed at a **shared grid of angles** to make them compatible with the simplification of the **h-modal norm** described above. This is only an approximation, but choosing an appropriately fine grid to approximate the observations should limit the influence of this procedure on the calculated functional depths. <br>\nEspacially in case of the dataset under consideration in this project, performing this approximation by linear interpolation should not result in large distortions due to the linearity of the described physical process. In other settings this approximation could lead to bad performance. One example that came to my mind is if most observations are zero, the frequency of taking measurements is comparatively low and the relevant parts of the observations are instantaneous deviations from zero (or spikes that have infinitesimally small duration). In cases like the one described, it would probably be a better idea to choose a different method or at least choose a different functional norm more appropriate for the dgp due to the necessity of very fine grids to achieve a appropriate approximation of the data.<br> Benchmarking of the method for different data generating processes will be part of future revisions to explore the applicability of the developed method.<br>\n\nFor sufficiently smooth processes with a high measuring frequency this approximation should however not result in huge distortions.\n\n\n\nAnother possibility to approach this third problem would be to use a different version of the norm for discretized points I described above. <br>\nInstead of calculating \n\\begin{equation}\n    ||x_i - x_k||_{2} = \\sqrt{\\sum_{j = 2}^m \\Delta_j(x_i(t_j) - x_k(t_j))^2}\n\\end{equation}\n\nfor a set of points on a grid approximated by linear interpolation, one could instead define functions $\\tilde{x}_i$ which are just the piece wise linear functions defined by connecting the observed points of $x_i$. A norm based on this could be constructed as:\n\n\\begin{equation}\n    ||x_i - x_k||_{\\tilde{2}} = \\sqrt{\\int_a^b (\\tilde{x}_i(t) - \\tilde{x}_k(t))^2 dt}\n\\end{equation}\n\nFor very fine grid approximations these criteria should result in similar depths, as under some mild conditions, the first approach will converge to the second for increasingly fine grids. In a sense the first approach is similar to a Riemann sum which for increasingly fine grids converges to the corresponding Riemann integral under the necessary assumptions.\n\n### Runtime Complexity\nThe runtime complexity of this algorithm is at least $O(n^2)$ and I concluded that using my implementation it is infeasible to use it on a very large data set such as the \"Endanzugsproblem\" (assuming that all observations are comparable at once). Even when splitting up the observations as proposed above into comparable subsets, some of them will be too large to directly approach with this method. <br>\nTo solve this problem, I instead opted to use a **sampling approach** which I explain in the next section.\n\n\n```R\n### The gifs have been rendered using function from auxiliary/observation_vis.R (needs more packages, than are available in this environment)\n# source(\"auxiliary/observation_vis.R\")\n# stretching_vis()\n# zeroing_vis()\n# lin_approx_vis()\n```\n\n## Sampling Approach <a name=\"sampling\"></a>\n---\nSince it is infeasible to use this method on very large data sets at once, I chose to pursue a sampling-based approach instead. Intuitively this is reasonable as in many cases observations that are atypical in the full data set will be classified as atypical in its subsamples more often than \"typical\" observations. If this principle does not apply to the data set, a sampling-based approach is difficult to justify. In a case like that it is more reasonable to choose differnet methods to identify abnormal observations. <br>\n\nAs the assumption seems reasonable in case of the \"Endanzugsproblem\", instead of performing the algorithm described above on the whole data set (or its comparable subsets), I devise a procedure as described in the following: <br>\n\nLet $\\{x_1, \\dots, x_L\\}$ be a set of observations that are comparable using the algorithm but too large to perform this procedure in reality.\n1. Define the following objects:\n    * Let *num\\_samples* $ = (a_1,\\:\\dots,\\: a_L) \\in \\mathbb{N}_0^L$ where $a_i$ is the number of samples $x_i$ was part of $\\quad \\forall i \\in \\{1,\\:\\dots,\\: L\\}$. <br>(Initialize all entries as 0)\n    * Let *num\\_outliers* $ = (b_1,\\:\\dots,\\: b_L) \\in \\mathbb{N}_0^L$ where $b_i$ is the number of samples $x_i$ was classified as an outlier in $\\quad \\forall i \\in \\{1,\\:\\dots,\\: L\\}$. <br>(Initialize all as entries 0)\n    * Let *frac\\_outliers* $ = (c_1,\\:\\dots,\\: c_L) \\in \\mathbb{R}_{\\geq 0}^L$ where $c_i = \\begin{cases}1 & a_i = 0 \\\\ \\frac{b_i}{a_i} & a_i > 0\\end{cases} \\quad \\forall i \\in \\{1,\\:\\dots,\\: L\\}$  <br>(Initialize all entries as 1)\n2. Draw a sample of size K from $\\{x_1,\\: \\dots,\\: x_L\\}$ without replacement\n3. Perform the outlier detection procedure on this sample and update the vectors according to your results.\n4. Go back to two and iterate this process until some condition is fulfilled.\n\nTypical conditions could be:\n* A specified number of iterations was reached\n* Every observation was part of more than a specified number of samples\n* The vector of certainties did not change enough according to some criterion over a specified number of iterations\n\nIn the end, the entries of *frac\\_outliers* can be used as a metric for the outlyingness of an observation. If a binary decision rule is needed, every observation with an entry over some specified threshold could be classified as an outlier.\n\n## Finding Comparable Sets of Observations <a name=\"comparables\"></a>\n---\nAssume for the sake of simplicity that **zeroing** is reasonable so that the minima of the measurement intervals of the observations are all zero. Therefore, the measurement intervals only differ in their end points or lengths which is identical in this case. <br>\nAs an example to visualize possible ways to find comparable subsets assume that the empirical distribution of endpoints looks as follows:\n\n\n\nIn the following I describe three methods to find comparable subsets to perform the sampling procedure on and explain why I chose the method that I ultimately implemented.\n\n### Static Splitting\n\nFor **Static Splitting** the idea is to partition the whole data set into pairwise disjunct subsets of pairwise comparable observations. This partition depends on the acceptable stretching parameter and is not necessarily unique for a choice of the acceptable stretching parameter. Therefore, a choice procedure would have to be introduced if this approach were to be taken. <br>\nSome possible partitions of the set above (not necessarily consistent with the same acceptable stretching parameter) could look like this: \n\n\n\nHowever, this idea has some problems:\n* The choice of subsets could introduce a new source of distortions in addition to the acceptable stretching parameter.\n* Adding new observations could change the chosen subsets, making an updating procedure difficult to realize.\n* In each individual subset, the observations that are changed due to stretching are identical over samples. This could lead to distortions since for some observations not the original but only the stretched observations are taken into account in the classification.\n\n### Dynamic Splitting\n\nIn **Dynamic Splitting** the allocation of comparable subsets takes place dynamically for each realization of the observation interval. The procedure is as follows: <br>\\\nFor each realization of the endpoint, determine the subset of comparable observations and perform the sampling approach on this subset but keep the parameter for acceptable stretching constant for all end points.\n\n\n\nThis approach has some advantages over the first one:\n* The choice of subsets becomes only a question of the acceptable stretching parameter and not of the choice of algorithm that chooses the partition of the data set.\n* Adding new observations is unproblematic, as new observations do not influence the allocation of comparable subsets. Therefore additional samples containing the new observation can be drawn without creating problems in the comparability to previous sampling-based results. A procedure like this is described in the next section.\n* Each observation can enter the classification procedure undistorted in at least the comparable subset corresponding to its own endpoint. Additionally, it can enter the classification in samples, where it is comparable due to acceptable stretching. The latter can realize for different degrees of stretching - increasing or decreasing the length of the measuring interval. This solves the problem of observations being used for classification only in a specific distorted state.\n\n### Dynamic Splitting with varying acceptable stretching parameter\n\nAs shown above, the difference in length of these comparable subsets changes quite substantially and does not react to the density of observations having similar measurement intervals. A deviation from this appraoch might be desirable for multiple reasons:\n* If there are many observations with a very similar measuring interval, including observations with a more dissimilar interval (in terms of the animation above, a midpoint farther away) might be detrimental to the procedure's performance. If there are fewer observations close by one might want to allow for a bigger acceptable stretching parameter to allow for more comparisons.\n* In tandem with the advantage above one could also change the sample size to suit specific needs of the procedure.\n\nIt would be possible to use a **local acceptable stretching parameter** that changes as a function of the estimated density of end points (since zeroing was admissible in this example).\nUsing a rather simple function determining the local acceptable stretching parameter to serve as an example leads to the following choice of comparable subsets.\n\n\n\nIn this example the effect is quite subtle, but in comparison to the previous animation, one can see that the expansion of the interval of end points of comparable observations is slower in regions, where the estimated density of end points is higher. <br>\nThere are two reasons why I decided against making acceptable stretching a varying parameter in my implementation:\n1. It introduces another complication as the function to determine the local acceptable stretching has to be chosen.\n2. It makes the updating procedure described later more difficult, as adding more observations will change the estimated density of the end points and thereby change the comparable subsets.\n\n### Choice for Implementation\nDue to the advantages and disadvantages described above, I decided to implement Dynamic Splitting with a global acceptable stretching parameter. <br>\nThis makes it easier to later justify an updating procedure and still does not create distorted results as described for Static Splitting.\n\n\n```R\n### The graphics and gifs have been rendered using function from auxiliary/observation_vis.R (needs more packages, than are available in this environment)\n# source(\"auxiliary/distribution_vis.R\")\n# dist_vis()\n# static_splits_vis()\n# dynamic_splits_vis()\n# dynamic_splits2_vis()\n```\n\n## Description of Full Procedure for Existing Data sets <a name=\"procedure\"></a>\n---\nHaving explained\n* The algorithm by Febrero-Bande, Galeano, and Gonz\u00e0lez-Manteiga (2008)\n* The sampling approach \n* The procedure for selecting comparable subsets with dynamic splitting of the data set \n\nI am going to explain the full procedure applied to an existing data set assuming that zeroing is admissible. <br>\n\n### Definition of Objects\n* Let $x_1,\\: \\dots,\\: x_n$ be the full data set of observations as described in the beginning\n* Let $I_1 = [s_1, e_1], \\dots, I_n = [s_n, e_n]$ be the measuring intervals of $x_1, \\dots, x_n$\n\nAssuming that zeroing is admissible:\n* Let $\\bar{x}_1,\\: \\dots, \\:\\bar{x}_n$ be the corresponding zeroed observations\n* Let $\\bar{I}_1 = [0, \\: \\bar{e}_1], \\: \\dots, \\bar{I}_n = [0, \\bar{e}_n]$ be the corresponding zeroed measuring intervals\n* Let $\\bar{E} = \\{\\bar{e} \\: | \\: \\exists k \\in \\{1, \\dots, n\\} \\: \\text{s.t.} \\: \\bar{e} = \\max(\\bar{I}_k)\\}$ be the set of measuring interval end points occurring in $\\bar{I}_1,\\: \\dots,\\: \\bar{I}_n$\n* Let $\\bar{\\Lambda}(\\bar{x}, \\bar{e})$ be the resulting object when zeroed observation $\\bar{x}$ is stretched to fit zeroed measuring interval $\\bar{I} = [0, \\bar{e}]$\n\nAgain assuming that zeroing is admissible, one can reasonably define the following objects.\n* Let $\\bar{Z}(\\bar{e}, \\lambda) = \\{\\bar{x}_k \\: | \\: \\frac{\\bar{e}_k}{\\bar{e}} \\in [\\frac{1}{\\lambda},\\lambda]\\}$ be the set of zeroed observations that can be compared to a zeroed observation with measuring interval $\\bar{I} = [0, \\bar{e}]$ with an acceptable stretching factor of $\\lambda$.\n* Let $\\bar{S}(\\bar{e}, \\lambda) = \\{\\bar{\\Lambda}(\\bar{e}, \\bar{x}) \\: | \\: \\bar{x} \\in \\bar{Z}(\\bar{e}, \\lambda)\\}$ be the set of zeroed observations that have been stretched with an admissible stretching factor to be comparable to a zeroed observation with zeroed measuring interval $\\bar{I} = [0, \\bar{e}]$.\n\nIf zeroing is not a valid approach, corresponding objects dependent on acceptable shifting and acceptable stretching have to be defined, which will be one challenge in generalizing this method.\n\n### Procedure\n1. Choose parameters:\n    * $\\lambda$ acceptable stretching\n    * $L$ sample size in sampling procedure (may also be varying depending on chosen approach for sampling)*\n    * $K$ number of equidistant points in grid for approximation by linear interpolation*\n    * $\\alpha$ fraction of observations to drop in approximation of cutoff value $C$ in outlier classification algorithm*\n    * $B$ sample size in approximation of cutoff value $C$ in outlier classification algorithm*\n    * $\\gamma$ tuning parameter in approximation of cutoff value $C$ in outlier classification algorithm*\n2. Initialize the following vectors:\n    * *num\\_samples* $ = (a_1,\\:\\dots,\\: a_n)\\in \\mathbb{N}_0^n \\quad$ with all entries being 0\n    * *num\\_outliers* $ = (b_1,\\:\\dots,\\: b_n)\\in \\mathbb{N}_0^n \\quad$ with all entries being 0\n    * *frac\\_outliers* $ = (c_1,\\:\\dots,\\: c_n) \\in \\mathbb{R}_{\\geq 0}^n \\quad$ with all entries being 1\n3. Iterate through the elements of $\\bar{E}$ doing the following:\n    * Let $\\hat{e}$ be the element of $\\bar{E}$ currently looked at\n    * Determine $\\bar{S}(\\hat{e}, \\lambda)$ and perform the sampling based outlier identification procedure on this set for some predetermined stopping condition\n    * Update *num\\_samples*, *num\\_outliers*, and *frac\\_outliers* for both the stretched and non-stretched observations in $\\bar{S}(\\hat{e}, \\lambda)$ as described in the section about sampling\n    * Go to the next element of $\\bar{E}$ and repeat until all elements have been reached.\n4. Report *frac\\_outliers* as a measure of outlyingness for the observations.\n\n*not explicitly mentioned in the procedure below\n\n\n## Updating <a name=\"updating\"></a>\n---\nThe procedure described above is constructed to work for a full data set. In a day-to-day setting the data set will not be static. Instead, new observations will be added and it would be a problem, if all calculations had to be done all over again only to incorporate a comparatively small number of new observations.\n\nInstead, I devise mechanisms to assign comparable values of *frac\\_outliers* to the newly added observations and to possibly also update the pre-existing observations due to the presence of the newly added ones. In the following assume that new observations are added sequentially. Two ways came to my mind to approach this updating procedure, one more true to the original process (1) and the other one less computationally expensive (2).\n\n### Version 1:\nThis procedure involves additional samples from all sets the new observation could have been part of. So both in a stretched form or in its original form <br>\n* Let $x'$ be the new observation and $\\bar{x}'$ its zeroed counterpart. Define $I'$, $\\bar{I'}$ and $\\bar{e}'$ accordingly.\n* Determine all elements $\\bar{e} \\in \\bar{E}$ such that $\\bar{x}' \\in \\bar{Z}(\\bar{e}, \\lambda)$. Define $\\bar{U}(\\bar{x}', \\lambda) = \\{\\bar{e} \\in \\bar{E} \\: | \\: \\bar{x}' \\in \\bar{Z}(\\bar{e}, \\lambda)\\}$ as the subset of $\\bar{E}$ called the Updating Window. <br> In this setting where zeroing is admissible, this can be simplified to $\\bar{U}(\\bar{x}', \\lambda) = \\{\\bar{e} \\in \\bar{E} \\: | \\: \\bar{e} \\in [\\frac{1}{\\lambda} \\bar{e}', \\lambda \\bar{e}']\\} = \\bar{E} \\cap [\\frac{1}{\\lambda} \\bar{e}', \\lambda \\bar{e}']$\n    \n \n\nFor all $\\tilde{e} \\in \\bar{U}(\\bar{x}', \\lambda)$ perform a sampling procedure as follows: <br>\n* $\\bar{\\Lambda}(\\bar{x}', \\tilde{e})$ is part of each sample \n* The size of each sample is identical to the one used in the original procedure\n* The number of samples for each $\\tilde{e}$ is the expected value of the number of samples the new observation would have been part of, if it had been in the original data set\n* The updating procedure of the vectors works as before. Not only the entry of the new observation in each vector is added and updated, also the entries for the original observations included in the new samples are updated.\n\nSo the set of zeroed observations that is potentially updated during this procedure is the following: <br> \n$$\\bigcup_{\\tilde{e}\\in \\bar{U}(\\bar{x}', \\lambda)} \\bar{Z}(\\tilde{e}, \\lambda) = \\Big\\{\\bar{x} \\: | \\: \\bar{e} \\in \\big[\\frac{1}{\\lambda}\\min\\{\\bar{U}(\\bar{x}', \\lambda)\\}, \\lambda \\max\\{\\bar{U}(\\bar{x}', \\lambda)\\}\\big]\\Big\\}$$\n<br>\nWhich is visualized in the following animation. (The endpoints of the potentially updated zeroed observations are marked by the red rectangle.)\n\n \n \n\n### Version 2:\nIn comparison the other procedure involves only additional sampling from the set where the new observation is non-stretched.\n* Let $x'$ be the new observation and $\\bar{x}'$ its zeroed counterpart. Define $I'$, $\\bar{I'}$ and $\\bar{e}'$ accordingly.\n* Determine $\\bar{S}(\\bar{e}', \\lambda)$ and perform additional sampling as follows:\n    * $\\bar{x}'$ is part of each sample\n    * The number of samples drawn is the expected value of samples the new observation would have been part of, if it had been in the original data set\n    * The updating procedure works as before. Not only the entry of the new observation in each vector is added and updated, also the entries for the original observations are updated.\n\nThe following graphic shows the equivalent objects of version 1:\n\n \n\nThis procedure is less true to the values calculated in the original data set, as the new observation is only taken into consideration in its non-stretched form. Additionally, pre-existing observations could be taken into consideration in their stretched form more frequently depending on the structure of new data being added which could lead to additional distortions. Therefore, I decided to start by implementing the first method and possibly include comparisons of both methods in future revisions.\n\n\n```R\n### The graphics and gifs have been rendered using functions from auxiliary/updating_vis.R (needs more packages, than are available in this environment)\n# source(\"auxiliary/updating_vis.R\")\n# upd_1_vis()\n# pot_upd_obs_vis()\n# upd_2_vis()\n```\n\n## Implementation <a name=\"implementation\"></a>\n---\nI decided to implement these methods in **R** and **C++** and to employ parallelization where possible, to strike a balance between speed and ease of use. All of these functions are implemented in the [**Rcpp**](https://cran.r-project.org/web/packages/Rcpp/) package **OutDetectR** that is contained in the code folder and can be installed as shown in the first code block. Documentation in the package is realized with [**roxygen2**](https://cran.r-project.org/web/packages/roxygen2/) so help files for the functions can be accessed using the notation ?\\<function_name\\>.\n\nThe following section will follow a similar structure as the description of the procedure above ordered as follows:\n\n1. [Grid Approximation](#impl_grid) \n2. [Febrero-Bande, Galeano, and Gonz\u00e0lez-Manteiga (2008) for Observations on a Shared Grid](#impl_algorithm)\n3. [Sampling approach](#impl_sampling)\n4. [Dynamic Splitting and Finding Comparable Subsets](#impl_splitting)\n5. [Full Procedure](#impl_full)\n6. [Updating](#impl_updating)\n\nAll of these functions can also be found in */auxiliary/R_functions.R* and will in the future be available as an Rcpp-package the tar-ball of which will be included in the repo. <br>\nIn future revisions there will be a secondary notebook with the details of the implementation. This notebook will instead focus on explaining the method and evaluating its perfomance.\n\n### Grid Approximation <a name=\"impl_grid\"></a>\n\n#### Finding a grid for Approximation\nAssuming that the observations already share the measuring intervals.\n\n\n```R\n#' This function creates a grid that is used for the piece wise linear\n#' approximation of functions. Currently this assumes that the observations\n#' share a measuring interval and constructs an equdistant grid of specified\n#' length.\n#'\n#' @param func_dat: Data used by functional procedures\n#' @param length.out: number of points in the grid\n#'\n#' @return A vector that contains the grid points\n#' @export\ngrid_finder <- function(func_dat, length.out = 100) {\n\n  # Extract Measuring Interval from first functional observation\n  measuring_interval <- c(min(func_dat[[1]]$args), max(func_dat[[1]]$args))\n  # Create Equdistant grid\n  grid <- seq(measuring_interval[1], measuring_interval[2], length.out = length.out)\n  # Return grid\n  return(grid)\n}\n```\n\n#### Grid approximation by Linear Interpolation\ndouble interpolate(double x_left, double x_right, double y_left, double y_right, double x){\n  if(x == x_left) return(y_left);\n  double m = (y_right - y_left) / (x_right - x_left);\n  double y = y_left + m * (x - x_left);\n  return(y);\n}\n\ndouble x_lneigh(NumericVector args, double x) {\n  int len = args.size();\n  int i = 0;\n  \n  while(i < len){\n    if(x >= args[i]){\n      if(x == args[i]) return(i);\n      i++;\n    }\n    else{\n      break;\n    }\n  } \n  return(i-1);\n}\n\n// [[Rcpp::export]]\nNumericVector grid_approx_obs(NumericVector args, NumericVector vals, NumericVector grid) {\n  \n  int n_points = grid.size();\n  NumericVector output(n_points);\n  int x_l = 0;\n  \n  for(int i = 0; i < n_points; i++){\n    x_l = x_lneigh(args, grid[i]);\n    output(i) = interpolate(args[x_l], args[x_l + 1], vals[x_l], vals[x_l + 1], grid[i]);\n  }\n  \n  return(output);\n}\nThis following function acts as a wrapper for the **C++** function grid_approx_obs() shown above, that given a vector of arguments, a vector of values and a vector that represents the grid to be used for approximation, performs the desired approximation and returns the vector of approximated values taken at the grid points.\n\n\n```R\n#' This function approximates the functional observations given to it using a piece\n#' wise linear approximation on a specified grid. The format of the data is unchanged\n#'\n#' @param func_dat: list that contains the observations:\n#' each observation is a list, that contains two vectors of identical length: args and vals\n#' @param grid: grid to use for approximation\n#'\n#' @return A list of identical length to func_dat. Each entry corresponds to the \n#' same entry in func_dat but is an approximation using linear interpolation on\n#' the points given in grid.\n#' @export\ngrid_approx_set_obs <- function(func_dat, grid) {\n  # for each observation perform an approximation on the grid points\n  approx_list <- map(\n    .x = func_dat,\n    .f = function(obs) {\n      list(\n        args = grid,\n        vals = grid_approx_obs(obs$args, obs$vals, grid)\n      )\n    }\n  )\n  # return the approximated observations\n  return(approx_list)\n}\n```\n\nThe second wrapper then combines those values to a matrix, where each row represents the approximated values of an observation at the given grid points. \n\n\n```R\n#' This function is a wrapper around grid_approx_set_obs.\n#' It takes the approximated observations of identical length and transforms \n#' them into a matrix\n#'\n#' @param func_dat: list that contains the observations:\n#' each observation is a list, that contains two vectors of identical length: args and vals\n#' @param grid: grid to use for approximation\n#'\n#' @return A matrix of dimensions length(func_dat)xlength(grid) that contains \n#' the approximated values of the functional observations at the grid points\n#' in each row.\n#' @export\ngrid_approx_mat <- function(func_dat, grid){\n  # call approximation in list form\n  list_approx <- grid_approx_set_obs(func_dat = func_dat,\n                                     grid = grid)\n  # extract values\n  approx_values <- map(.x = list_approx,\n                       .f = function(obs) obs$vals)\n  # combine in matrix\n  mat_approx <- matrix(data = unlist(approx_values),\n                       nrow = length(list_approx), ncol = length(grid),\n                       byrow = TRUE)\n  # return matrix\n  return(mat_approx)\n}\n```\n\n### Febrero-Bande, Galeano, and Gonz\u00e0lez-Manteiga (2008) for Observations on a Shared Grid <a name=\"impl_algorithm\"></a>\nThe following functions implement the algorithm described above for functional observations that are observed at a common set of discrete points. The grid approximation above serves as a preparation to make these functions applicable. <br> \n\n#### approx_C\nThe function *approx_C* implements the approximation of the cutoff value $C$ by bootstrapping described in Febrero-Bande, Galeano, and Gonz\u00e0lez-Manteiga (2008).\n\n\n```R\n#' Uses a bootstrapping procedure to approximate the cutoff value for the identification\n#' of outliers\n#'\n#' @param matr_dat: data in matrix form - each row contains the grid approximations of one observation\n#' @param fdepths: corresponding depths for the observations\n#' @param alpha: quantile of least deep observations to drop before bootstrapping\n#' @param B: number of smoothed bootstrap samples to use\n#' @param gamma: tuning parameter for smoothed bootstrap\n#' @param grid: grid used in approximation of matr_dat\n#'\n#' @return placeholder\n#' @export\napprox_C <- function(matr_dat, fdepths, alpha, B, gamma, grid) {\n\n  # set smoothing mode to on\n  smoothing <- TRUE\n  # infer number of observations from length of depth vector\n  n <- length(fdepths)\n  # Get number of elements in grid\n  grid_length <- length(grid)\n  # determine threshold to drop observations with lowest depth values\n  depth_thr <- tryCatch(\n    {\n      quantile(x = fdepths, probs = alpha, na.rm = FALSE)\n    },\n    error = function(cond){\n      stop(fdepths, 'approx_C - I ran into this error!')\n    }\n  )\n  # drop observations for bootstrapping\n  matr_dat_red <- matr_dat[fdepths >= depth_thr, ]\n\n  n_red <- dim(matr_dat_red)[1]\n\n  # Determine vcov-matrix for smoothed bootstrapping\n  Sigma_x <- cov(matr_dat_red)\n\n  my_vcov <- gamma * Sigma_x\n  \n  # Draw bootstrap samples from data set\n  fsamples <- map(\n    .x = 1:B,\n    .f = function(inds) matr_dat_red[sample(x = 1:n_red, size = n, replace = TRUE), ]\n  )\n\n  # Create smoothing components for bootstrapping\n  smoothing_components <- map(\n    .x = 1:B,\n    .f = function(x) mvrnorm(n = n, mu = rep(0, times = grid_length), Sigma = my_vcov)\n  )\n\n  # Obtain smoothed bootstrap samples\n  smoothed_BS_samples <- map(\n    .x = 1:B,\n    .f = function(b) fsamples[[b]] + smoothing_components[[b]]\n  )\n\n  # Calculate depths for each smoothed bootstrap sample\n  bootstrap_depths <- map(\n    .x = 1:B,\n    .f = function(b) hM_depth(smoothed_BS_samples[[b]], grid)\n  )\n\n  # Calculate first percentile from depths of smoothed bootstrap samples\n  one_perc_quantiles <- unlist(map(\n    .x = bootstrap_depths,\n    .f = function(sample) quantile(sample, probs = 0.01, na.rm = FALSE)\n  ))\n\n  # return median of first percentiles\n  return(median(one_perc_quantiles))\n}\n```\n\n#### outlier_iteration\nThis function performs one iteration of the algorithm, including the calculation of functional depths, the approximation of $C$ and the flagging of observations with depths lower than $C$\n\n\n```R\n#' This function performs one iteration of the algorithm, including the \n#' calculation of functional depths, the approximation of C and the \n#' flagging of observations with depths lower than C\n#'\n#' @param matr_dat: data in matrix form - each row contains the grid approximations of one observation\n#' @param alpha: quantile of least deep observations to drop before bootstrapping\n#' (in approximation of C - optional if C is specified)\n#' @param: B: number of smoothed bootstrap samples to use\n#' (in approximation of C - optional if C is specified)\n#' @param: gamma: tuning parameter for smoothed bootstrap\n#' @param: ids: identifiers of individual observations\n#' @param: grid: grid used in approximation of matr_dat\n#' @param: C: should be provided. Otherwise C will be approximated in each step of the iteration\n#'\n#' @return placeholder\n#' @export\noutlier_iteration <- function(matr_dat, alpha = 0.05, B = 50, gamma, ids, grid, C = NULL) {\n\n  # Calculating functional depths using a function from ./auxiliary/Rcpp_functions.cpp\n  fdepths <- hM_depth(matr_dat, grid)\n\n  if (missing(C)) {\n    # Approximating C\n    C <- approx_C(\n      matr_dat = matr_dat, fdepths = fdepths, alpha = alpha,\n      B = B, gamma = gamma, grid = grid\n    )\n  }\n\n  # Flagging observations with depths lower than the cutoff value C\n  outliers <- which(fdepths < C)\n\n  return(list(\n    matr_dat = matr_dat[-outliers, ],\n    ids = ids[-outliers],\n    outlier_ids = ids[outliers]\n  ))\n}\n```\n\n #### outlier_detection\n This function serves as a wrapper for outlier_iteration and iterates the process until no new observations are flagged.\n\n\n```R\n#'  This function serves as a wrapper for outlier_iteration and iterates the process until no new observations are flagged.\n#'\n#' @param matr_dat: data in matrix form - each row contains the grid approximations of one observation\n#' @param alpha: quantile of least deep observations to drop before bootstrapping\n#' (in approximation of C - optional if C is specified)\n#' @param B: number of smoothed bootstrap samples to use\n#' (in approximation of C - optional if C is specified)\n#' @param gamma: tuning parameter for smoothed bootstrap\n#' @param ids: identifiers of individual observations\n#' @param grid: grid used in approximation of matr_dat\n#' @param C: should be provided. Otherwise C will be approximated in each step of the iteration\n#'\n#' @return placeholder\n#' @export\noutlier_detection <- function(matr_dat, alpha = 0.05, B = 100, gamma = 0.05, ids, grid, C = NULL) {\n  tmp_ids <- ids\n  # Initialize empty vectors for position of flagged observations in func_dat\n  # and ids of flagged observations\n  outlier_ids <- c()\n\n  # loop that continues until an iteration does not flag any new observations\n  condition <- TRUE\n  while (condition) {\n\n    # perform iteration\n    iter_res <- outlier_iteration(\n      matr_dat = matr_dat, alpha = alpha, B = B, gamma = gamma, \n      ids = tmp_ids, grid = grid, C = C)\n    \n    new_outliers <- iter_res$outlier_ids\n\n    # if there are no new flagged observations stop loop\n    if (length(new_outliers) == 0) {\n      condition <- FALSE\n    } else {\n      # otherwise: add flagged observations to vector\n      outlier_ids <- c(outlier_ids, new_outliers)\n      # reduce data to non-flagged observations\n      matr_dat <- iter_res$matr_dat\n      # reduce ids to non-flagged observations\n      tmp_ids <- iter_res$ids\n    }\n  }\n\n  # return identifiers of flagged observations and position of these flagged observations in the data set\n  return(list(\n    outlier_ids = outlier_ids,\n    outlier_ind = which(is.element(ids, outlier_ids))\n  ))\n}\n```\n\n#### Outlier Detection - Wrapper\nThe following function acts as a wrapper to the previous one in case, $C$ should not be recalculated in each iteration. My recommendation would be to use this function as recalculation of $C$ in each iteration can lead to classifying unreasonably many observations as outliers. Due to problems with the parallelization, non-reproducible errors appear in some cases, making a tryCatch necessary.\nIn case of a reproducible error a counter will reach a specified value after a number of iterations, throwing the error to the overarching procedure, terminating the outlier detection process.\n\n\n```R\n#' This function performs the identification procedure implemented in this package\n#' in the simplest scenario. It serves as an important building block for the\n#' more high-level functions.\n#' Important assumptions are the following:\n#' - observations in func_dat are zeroed and have the same measuring interval\n#'\n#' @param func_dat: list that contains the observations\n#' each observation is a list, that contains two vectors of identical length: args and vals\n#' @param ids: identifiers of individual observations\n#' @param alpha: quantile of least deep observations to drop before bootstrapping\n#' (in approximation of C - optional if C is specified)\n#' @param ids: B: number of smoothed bootstrap samples to use\n#' (in approximation of C - optional if C is specified)\n#' @param gamma: tuning parameter for smoothed bootstrap\n#'\n#' @return Returns a list containing two objects:\n#' 1. outlier_ids: a vector containing the ids of the observations identified as outliers\n#' 2. outlier_ind: a vector containing the position of the the observations identified as outliers in the func_dat list\n#' @export\ndetection_wrap <- function(func_dat, ids, alpha, B, gamma = 0.05) {\n\n  # determine the grid for approximation\n  grid <- grid_finder(func_dat = func_dat)\n\n  # Approximate by linear interpolation\n  matr_dat <- grid_approx_mat(func_dat = func_dat, grid = grid)\n\n  # tmp redo variable\n  redos <- 0\n  \n  while(redos < 10){\n    # calculate h-modal depths\n    fdepths <- hM_depth(valueMatrix = matr_dat, grid = grid)\n    if(all(is.na(fdepths))){\n      redos <- redos + 1\n    } else{\n      redos <- 10\n    }\n  }\n\n  # create temporary variable indicating if error occured\n  n_error <- 0\n\n  # Approximate a value of C\n  while (n_error < 10) {\n    add <- FALSE\n    C_appr <- tryCatch(\n      {\n        approx_C(\n          matr_dat = matr_dat, fdepths = fdepths, alpha = alpha,\n          B = B, gamma = gamma, grid = grid\n        )\n      },\n      error = function(cond) {\n        warning(cond)\n        add <<- TRUE\n      }\n    )\n    if(add == TRUE){\n      n_error <- n_error + 1\n    } else{\n      n_error <- 10\n    }\n  }\n\n  # Perform the outlier classification procedure for the approximated value of C\n  flagged <- outlier_detection(\n    matr_dat = matr_dat, ids = ids, grid = grid, C = C_appr\n  )\n\n  # Return the list of outlier ids and outlier indices - these are useful in different cases\n  # contains the objects outlier_ids and outlier_ind\n  return(flagged)\n}\n\n```\n\n### Sampling Approach <a name=\"impl_sampling\"></a>\n\n#### Helper function for parallelization\nSince data sets can get large very quickly, it is useful to perform parallelization in this sampling approach in a less memory intensive way. Therefore I decided to write the data set in its prepared form to the disk and use a format that supports random access in lists, to only read in the observations that are part of the sample. After reading in those observations, it performs the outlier detection procedure implemented above.\n\n\n```R\n\n```\n\n\n```R\n\n```\n\n#### How to use this function?\nUsing the function *sampling_wrap()* is not as straight-forward as using the previous as multiple steps have to be performed before and after using this function to ensure a problem free experience.\nI will explain the following code fragments in detail, as depending on which operating system a user employs modifications have to be made. For this reason, the code is commented out in these parts, in order not to cause technical problems that are difficult to replicate. The following code segments were written on a Linux machine and will work on UNIX systems. Since forking is not supported under windows, alternatives would have to be used, like using PSOCK-Clusters instead of ForkClusters.\n\n\n```R\n\n```\n\n* *num_cores()* detects the number of logical cores\n* *makeForkCluster()* creates a virtual cluster object that can serve as an argument to functions from the parallel package to perform parallelized computations\n* the *clusterCall()* calls execute the command inside on each individual node of the virtual cluster to ensure that all necessary packages are loaded in each instance\n* *clusterExport* this exports objects from an environment to each of the nodes. These can be functions or objects.\n\n(These last to steps are technically not necessary in case of a fork cluster, but will navigate around some hard to troubleshoot problems that can occur.)\n\n* *sampling_wrap()* performs the actions implemented above on the virtual cluster *cl*\n* *stopCluster()* stops the cluster, to ensure that it does not clog up the system\n\n### Dynamic Splitting <a name=\"impl_splitting\"></a>\n\n#### Zeroing\nTo use the dynamic splitting procedure in the previously described settings, it is first necessary to zero all observations. This is implemented for the functional observations and its results should be saved as a separate object for future use.\n\n\n```R\n\n```\n\n#### Determine measuring intervals\nThis function returns a matrix containing in each row the beginning and end point of the measuring interval of the corresponding observation.\n\n\n```R\n\n```\n\n#### Create a list of measuring intervals that occur in the data set\nThis set is needed later on for iterating through all possible realizations of the measuring interval to determine the comparable sets for each one.\n\n\n```R\n\n```\n\n#### Find comparable observations for one measuring interval\nGiven a measuring interval that is currently under consideration and the matrix of all measuring intervals, determine the indices of the observations that are comparable given an acceptable stretching factor $\\lambda$. Here zeroing is assumed, such that the condition simplifies to a condition on the endpoint of the intervals.\n\n\n```R\n\n```\n\nThis function can then be used for determining which sets to sample from using the sampling procedure implemented above while iterating through the measuring intervals that occur in the data set.\n\n### Full Procedure <a name=\"impl_full\"></a>\n\n#### Stretching an observation\nThe first function needed for the full procedure is the ability to stretch an observation to be comparable to another.\n\n\n```R\n\n```\n\n#### Stretching a set of observations to prepare sampling procedure\nThis function acts as a wrapper for the previous function and applies it to a set of observations that are stretched to the same measuring interval.\n\n\n```R\n\n```\n\n#### Performing stretching and sampling procedure on set of observations\nThis is nearly identical to the functions for the sampling procedure itself and could easily be included as a subcase. For the sake of clarity, I nevertheless decided to make these separate functions.\nUnderstanding the sampling procedure and the stretching functions will make these functions easy to understand.\n\n\n```R\n\n```\n\nThis function performing the parallelized sampling is again very similar. It only differs in four points:\n* argument measuring_interval: interval the observations are stretched to\n* argument comparable: ids of the observations to include in the process as now not all observations are to be sampled in the same process\n* no argument n_obs: this can be replaced by comparable\n* use of the appropriately changed helper function for the parallelization\n\nBe careful when using the following function. The vectors that are returned only relate to the set of comparable observations currently under consideration. <br>\nA value of 3 in the first entry of *num_samples* means that the first observation of the whole data set occurred in 3 samples, not that the first observation from the set of comparable observations occurred in 3 samples. This has to be kept in mind while later using the output of this function.\n\n\n```R\n\n```\n\n#### Putting the pieces together\nNow that there are functions that\n* Find the set of measuring intervals that occur in the data set\n* Find comparable observations given a specific measuring interval and an acceptable stretching factor\n* Perform the sampling procedure with acceptable stretching on comparable subsets of the data set\n\nit is possible to assemble the pieces into one cohesive function that performs the outlier classification procedure described above on a data set where zeroing is admissible.\n\n\n```R\n\n```\n\n### Updating <a name=\"impl_upd\"></a>\nThe updating procedure is not yet implemented. This is why this part is a description of the functions and their implementation.\n\n#### Find measuring intervals with possible occurences of new observation\n\n\n```R\n# new_func_obs: list with two elements: vectors of equal length called args and vals\n# new_id: identifier for the new observation (be careful not to create duplicates - for example just consecutive intergers would be fine)\n# list_path: path to the largeList object, where data set is saved\n# id_path: path to the RDS file with the identifiers\n\nobs_append <- function(new_func_obs, new_id, list_path, id_path){\n    \n    # read in previous ids\n    ids <- readRDS(file = id_path)\n    # append new ID\n    new_ids <- c(ids, new_id)\n    # overwrite old ID file\n    saveRDS(object = new_ids, file = id_path)\n    \n    # largeLists support appending\n    saveList(object = list(new_func_obs), file = list_path, append = TRUE) \n}\n```\n\n#### Appending observation to list of functional data and ids\n\n\n```R\n# new_func_obs: list with two elements: vectors of equal length called args and vals\n# unique_intervals: matrix containing measuring intervals that occur in the data set (one in each row)\n# lambda: acceptable stretching parameter\n\npossible_occurences <- function(new_func_obs, unique_intervals, lambda){\n    \n    # determine measuring interval of new observation\n    new_measuring_interval <- c(min(new_func_obs$args),  max(new_func_obs$args))\n    \n    # determine for all previously used measuring intervals if the new\n    # observation could have been part of the stretching and sampling procedure\n    occurs <- map(.x = 1:(dim(unique_intervals)[1]),\n                      .f = function(i) ifelse(new_measuring_interval[2] >= unique_intervals[i,2]/lambda \n                                              & new_measuring_interval[2] <= unique_intervals[i,2]*lambda,\n                                              TRUE, FALSE))\n                  \n    # return the indices and intervals that the new observation could have been a part of\n    return(list(occurs = occurs,\n                occurs_intervals = unique_intervals[occurs, ]))                         \n}\n```\n\n#### Determine expected number of occurences in this measuring interval sampling run\n\n\n```R\n# orig_n_obs: number of observations in the original comparable set (use output from comparable_obs_finder to determine this)\n# orig_n_samples: number of samples drawn in the original procedure (this can be updated by adding those drawn now for future updates)\n# orig_sample_size: sample size used in the original prrocedure for this comparable subset\n\nexp_num_samples <- function(orig_n_obs, orig_n_samples, orig_sample_size){\n    \n    # determine the probability that the observation would have been part of any original sample,\n    # if it had been part of the data set\n    # exp_per_sample <- choose(orig_n_obs, orig_sample_size - 1) / choose(orig_n_obs + 1, orig_sample_size)\n    # simplifies to:\n    exp_per_sample <- orig_sample_size / orig_n_obs\n    \n    # multiplay with the number of samples and return the number rounded to the next whole integer\n    return(ceiling(orig_n_samples * exp_per_sample))\n}\n```\n\n#### Update one measuring interval\n\nwork in progress\n\n\n```R\n\n```\n\n#### Updating for one new observation\n\nwork in progress\n\n\n```R\nobs_update <- function(cl, new_func_obs, list_path, measuring_intervals, lambda, n_samples = NULL, \n                       prev_num_samples, prev_num_outliers, sample_size = NULL, alpha = NULL, B = NULL, \n                       gamma = 0.05){\n    \n    main_interval <- c(min(new_func_obs$args),  max(new_func_obs$args))\n    \n    comparable <- comparable_obs_finder\n    \n}\n```\n\n## How to use the package?<a name=\"how_to\"></a>\n---\n\n## Simulated Data <a name=\"simulated\"></a>\n---\nTo show possible usecases of the implementation I create three datasets:\n1. **No sampling** <br> This data set shows the outlier classification procedure of Febrero-Bande, Galeano, and Gonz\u00e0lez-Manteiga (2008) in action. It is characterized by:\n    * Observations with identical measuring intervals \n    * Relatively few observations meaning that the algorithm can be applied without sampling <br>\n2. **Sampling** <br>A data set where observations share the measuring interval but which is large enough that sampling is necessary to use the algorithm <br>\n3. **Full procedure**\n    * A dataset where observations share the starting point of the measuring interval but have different endpoints. \n    * This is meant to show the full procedure on a data set that is effectively already zeroed.\n\nThe functional form of the non-outliers in these data sets is approximately **linear** which has two reasons: <br>\n1. Simplicity \n2. The approximate linearity of the relationship that is fundamental to the main data set explored in this project (angle and torque when tightening a bolt). \n\nAll of these data sets and the results of the outlier classification procedures applied to them can be seen in the **shiny app** provided in the repository.\n\n### No sampling:\nThis data set is based on a simple data generating process. Each of the 500 observations is generated as follows:\n\n* Determine if the observation is generated as an outlier by drawing from a Bernoulli distributed random variable with parameter 0.05.\n* Determine the number of points $k$ where the function is observed. (In the terms of the method above the number of points where measurements are taken) This is drawn from a discrete uniform with elements $10, \\dots, 100$\n\nThe generation of dependent variables depends on whether the observation is generated as an outlier. The general process is as follows: <br>\n\n* Draw k-2 realizations of $p \\sim U[0, 1] \\quad \\text{s.t.} \\quad p_1, \\dots, p_k \\quad \\text{i.i.d.}\\quad$ Let $p_{(1)}, \\dots, p_{(k-2)}$ be the sorted realizations and define $(0, \\: p_{(1)},\\: \\dots, \\: p_{(k-2)},\\: 1)^T = \\vec{p}$ <br>(This is equivalent to our grid of measuring points.)<br>\n* Draw k realizations of $s \\sim U[\\underset{\\bar{}}{s}, \\bar{s}] \\quad \\text{s.t.} \\quad s_1, \\dots, s_k \\quad \\text{i.i.d.} \\quad$ and define $(s_1,\\: \\dots, \\: s_k)^T = \\vec{s}$\n* Draw k realizations of $\\epsilon \\sim \\mathcal{N}[0, \\sigma] \\quad \\text{s.t.} \\quad \\epsilon_1, \\dots, \\epsilon_k \\quad \\text{i.i.d.} \\quad$ and define $(\\epsilon_1,\\: \\dots, \\: \\epsilon_k)^T = \\vec{\\epsilon}$\n* Let $\\vec{y} = m \\vec{s} \\odot \\vec{p} + \\vec{\\epsilon}$ be the vector of realizations of the dependent variable, where $\\odot$ is the component-wise (or Hadamard) product.\n\nThe parameters are different for non-outliers and outliers: <br>\nFor non-outliers:\n* $\\underset{\\bar{}}{s} = 0.8, \\quad \\bar{s} = 1.2$\n* $\\sigma = 0.05$\n* $m = 1.02$\n\nand for outliers:\n* $\\underset{\\bar{}}{s} = 1, \\quad \\bar{s} = 1.4$\n* $\\sigma = 0.1$\n* $m = 1.2 * 1.02$\n\n\n```R\n# Data generated, transformed and visualized with functions from auxiliary/generate_set_1.R\n# Data set is also saved to ./data/Set_1 and if existent read from there instead\n# source(\"auxiliary/generate_set_1.R\")\n\nif(file.exists(\"./data/Set_1/functional.llo\") && \n   file.exists(\"./data/Set_1/ids.RDS\") && \n   file.exists(\"./data/Set_1/outliers.RDS\")){\n    data_set_1 <- list(data = readList(file = \"./data/Set_1/functional.llo\"),\n                       ids = readRDS(file = \"./data/Set_1/ids.RDS\"),\n                       outliers = readRDS(file = \"./data/Set_1/outliers.RDS\"))\n\n} else{\n    data_set_1 <- generate_set_1()\n}    \n\nif(file.exists(\"./data/Set_1/tibble.RDS\")){\n   tidy_set_1 <- readRDS(\"./data/Set_1/tibble.RDS\") \n} else{\n   tidy_set_1 <- tidify_1(data_set_1$data, data_set_1$ids)\n   saveRDS(object = tidy_set_1, file = \"./data/Set_1/tibble.RDS\")\n}\n                        \nvis_1(tidy_set_1)           \n```\n\nPrepare data for visualization in the shiny app.\n\n\n```R\nif(file.exists(\"./data/Set_1/detection.RDS\")){\n    set_1_detection <- readRDS(\"./data/Set_1/detection.RDS\")\n} else{\n    set_1_detection <- detection_wrap(func_dat = data_set_1$data, alpha = 0.05, B = 50, gamma = 0.05, ids = data_set_1$ids)\n    saveRDS(object = set_1_detection, file = \"./data/Set_1/detection.RDS\")\n}\n\nif(file.exists(\"./data/Set_1/summary.RDS\")){\n    set_1_summary <- readRDS(\"./data/Set_1/summary.RDS\")\n} else{\n    \n    missed_outliers = setdiff(data_set_1$outliers, set_1_detection$outlier_ind)\n    false_outliers = setdiff(set_1_detection$outlier_ind, data_set_1$outliers)\n    \n    set_1_summary <- list(flagged = set_1_detection$outlier_ind,\n                          original = data_set_1$outliers,\n                          missed = missed_outliers,\n                          false = false_outliers)\n    \n    saveRDS(object = set_1_summary, file = \"./data/Set_1/summary.RDS\")\n}\n\nif(file.exists(\"./data/Set_1/shiny_tibble.RDS\")){\n    shiny_tibble_1 <- readRDS(\"./data/Set_1/shiny_tibble.RDS\")\n} else{\n    shiny_tibble_1 <- tidy_set_1 %>%\n        mutate(outlier = ifelse(ids %in% data_set_1$outliers, TRUE, FALSE),\n               flagged = ifelse(ids %in% set_1_detection$outlier_ind, TRUE, FALSE))\n    saveRDS(object = shiny_tibble_1, file = \"./data/Set_1/shiny_tibble.RDS\")\n}\n```\n\n### Sampling:\nThis second data set consists of 10000 observations where 95% are generated by the same process as the non-outlier variant in the previous data set. \nSo a vector of arguments is drawn from the continuous uniform on $[0,1]$ of random length. Call this vector *args* in the following description.\n\nBut the outliers take 5 different forms each appearing in about one percent of cases. I will describe their data generating processes in mathematical form in the following:\n\n1. Exactly as the outliers in data set 1.\n\n2. Sigmoid function: $\\frac{1}{\\mathbb{1} + \\exp{(-3 * \\text{args})}} + \\epsilon$ where $\\epsilon$ is a vector of appropriate length containing i.i.d. elements drawn from $\\mathcal{N}(0, 0.05^2)$\n\n3. Half sigmoid function: $\\frac{2}{\\mathbb{1} + \\exp{(-3 * \\text{args})}} - \\mathbb{1} + \\epsilon$ where $\\epsilon$ is a vector of appropriate length containing i.i.d. elements drawn from $\\mathcal{N}(0, 0.05^2)$\n\n4. Exponential function: $\\frac{\\exp(args) - \\mathbb{1}}{e - 1} + \\epsilon$ where $\\epsilon$ is a vector of appropriate length containing i.i.d. elements drawn from $\\mathcal{N}(0, 0.05^2)$\n\n5. Noise: i.i.d. draws from $U[0,1]$\n\n\n```R\n# Data generated, transformed and visualized with functions from auxiliary/generate_set_2.R\n# Data set is also saved to ./data/Set_2 and if existent read from there instead\n# source(\"auxiliary/generate_set_2.R\")\n\nif(file.exists(\"./data/Set_2/functional.llo\") && \n   file.exists(\"./data/Set_2/ids.RDS\") && \n   file.exists(\"./data/Set_2/outliers.RDS\")){\n    data_set_2 <- list(data = readList(file = \"./data/Set_2/functional.llo\"),\n                       ids = readRDS(file = \"./data/Set_2/ids.RDS\"),\n                       outliers = readRDS(file = \"./data/Set_2/outliers.RDS\"))\n\n} else{\n    data_set_2 <- generate_set_2()\n}    \n\nif(file.exists(\"./data/Set_2/tibble.RDS\")){\n   tidy_set_2 <- readRDS(\"./data/Set_2/tibble.RDS\") \n} else{\n   tidy_set_2 <- tidify_2(data_set_2$data, data_set_2$ids)\n   saveRDS(object = tidy_set_2, file = \"./data/Set_2/tibble.RDS\")\n}\n\nvis_2(tidy_set_2)\n```\n\nDue to the computational cost of this classifying procedure I saved its results and only perform the classification, if those results could not be found. In the case of 10000 observations can still be done on the full set and I opted to use this lower number of observations not due to computational problems with larger data sets but due to overplotting in the visualizations, that has to be addressed, before large data sets can be appropriately visualized.\n\n\n```R\nif(file.exists(\"./data/Set_2/results.RDS\")){\n    set_2_results <- readRDS(file = \"./data/Set_2/results.RDS\")\n\n} else{\n    num_cores <- detectCores()\n    cl <- makeForkCluster(nnodes = num_cores)\n                   \n    clusterExport(cl, varlist = list(\"grid_approx_set_obs\",\n                                     \"approx_C\",\n                                     \"grid_finder\",\n                                     \"outlier_iteration\",\n                                     \"outlier_detection\",\n                                     \"detection_wrap\",\n                                     \"random_access_par_helper\"),\n                                      envir = .GlobalEnv)\n                          \n    set_2_results <- sampling_wrap(cl = cl, n_obs = 10000, n_samples = 150, \n                               sample_size = 500, alpha = 0.05, B = 100, gamma = 0.05, \n                               list_path = \"./data/Set_2/functional.llo\")   \n    \n    stopCluster(cl)    \n    \n    saveRDS(object = set_2_results, file = \"./data/Set_2/results.RDS\")\n}    \n\nif(file.exists(\"./data/Set_2/shiny_tibble.RDS\")){\n    shiny_tibble_2 <- readRDS(\"./data/Set_2/shiny_tibble.RDS\")\n} else{\n    shiny_tibble_2 <- tidy_set_2 %>%\n        mutate(outlier = ifelse(ids %in% data_set_2$outliers, TRUE, FALSE))\n    \n    lengths <- unlist(map(.x = 1:10000,\n                          .f = function(i) length(data_set_2$data[[i]]$vals)))\n                          \n    shiny_tibble_2$cert <- unlist(map(.x = 1:10000,\n                                      .f = function(i) rep(set_2_results$certainties[i], times = lengths[i])))\n    \n    saveRDS(object = shiny_tibble_2, file = \"./data/Set_2/shiny_tibble.RDS\")\n}\n```\n\nTo see the results of this classification procedure for different values of the certainty threshold, you can use the shiny app provided in the repository.\n\n### Full Procedure:\nThis data set is similar to the sampling data set in its data generating process. There are 30000 observations each generated by a similar process as in data set 2.\n\nThe main difference is, that the measuring intervals are not identical and are drawn from the following possibilities:\n\n| Endpoint of Measuring Interval \t| 0.9  \t| 1   \t| 1.1  \t| 1.5  \t| 1.6  \t| 1.7  \t| 1.9 \t| 2    \t| 2.1  \t|\n|:------------------------------:\t|------\t|-----\t|------\t|------\t|------\t|------\t|-----\t|------\t|------\t|\n|           Probability          \t| 0.05 \t| 0.2 \t| 0.05 \t| 0.07 \t| 0.15 \t| 0.08 \t| 0.1 \t| 0.25 \t| 0.05 \t|\n\nAlso the data generating processes for both the outliers and the non-outliers are scaled such that the expected realizations at the beginning and end of the data set are identical. (Especially important for the exponential and sigmoidal outliers.) An exception from this are the type 5 outliers, which stay uniformly distributed - but the upper border of the support is made to fit the expected realization of the non-outlier process at the end point of the measuring interval.\n\n\n```R\n# Data generated, transformed and visualized with functions from auxiliary/generate_set_3.R\n# Data set is also saved to ./data/Set_3 and if existent read from there instead\nsource(\"auxiliary/generate_set_3.R\")\n\nif(file.exists(\"./data/Set_3/functional.llo\") && \n   file.exists(\"./data/Set_3/ids.RDS\") && \n   file.exists(\"./data/Set_3/outliers.RDS\")){\n    data_set_3 <- list(data = readList(file = \"./data/Set_3/functional.llo\"),\n                       ids = readRDS(file = \"./data/Set_3/ids.RDS\"),\n                       outliers = readRDS(file = \"./data/Set_3/outliers.RDS\"))\n\n} else{\n    data_set_3 <- generate_set_3()\n}    \n\nif(file.exists(\"./data/Set_3/tibble.RDS\")){\n   tidy_set_3 <- readRDS(\"./data/Set_3/tibble.RDS\") \n} else{\n   tidy_set_3 <- tidify_3(data_set_3$data, data_set_3$ids)\n   saveRDS(object = tidy_set_3, file = \"./data/Set_3/tibble.RDS\")\n}\n\n### Due to a lengthy plotting time and overplotting, this plot is saved an inserted as a png\n# vis_3(tidy_set_3)\n```\n\n \n\nFull procedure works - update this!!!\n\n\n```R\nif(file.exists(\"./data/Set_3/results.RDS\")){\n   set_3_results <- readRDS(file = \"./data/Set_3/results.RDS\")\n} else{\n    num_cores <- detectCores()\n    cl <- makeForkCluster(nnodes = num_cores)\n                   \n    clusterExport(cl, varlist = list(\"grid_approx_set_obs\",\n                                     \"approx_C\",\n                                     \"grid_finder\",\n                                     \"outlier_iteration\",\n                                     \"outlier_detection\",\n                                     \"detection_wrap\",\n                                     \"random_access_par_helper\"),\n                                      envir = .GlobalEnv)\n    \n    measuring_intervals <- measuring_int(func_dat = data_set_3$data)\n\n    comp_test <- comparable_obs_finder(main_interval = c(0,1), measuring_intervals = measuring_intervals,  lambda = 1.2, ids = 1:30000)$ids\n    \n    #test <- stretch_and_sample(cl = cl, n_samples = 100, sample_size = 100, alpha = 0.02, B = 100, gamma = 0.05, n_obs = 30000,\n    #                           list_path = \"./data/Set_3/functional.llo\", measuring_interval = c(0,1), \n    #                           comparable = comp_test)\n    \n    set_3_results <- dectection_zr_smpl(cl = cl, list_path = \"./data/Set_3/functional.llo\", measuring_intervals = measuring_intervals,\n                                        n_obs = 30000, lambda = 1.2, n_samples = 300, sample_size = 300, alpha = 0.02, B = 100, gamma = 0.05)\n    \n    stopCluster(cl)    \n    \n   saveRDS(object = set_3_results, file = \"./data/Set_3/results.RDS\")\n}    \n\nif(file.exists(\"./data/Set_3/shiny_tibble.RDS\")){\n    shiny_tibble_3 <- readRDS(\"./data/Set_3/shiny_tibble.RDS\")\n} else{\n    shiny_tibble_3 <- tidy_set_3 %>%\n        mutate(outlier = ifelse(ids %in% data_set_3$outliers, TRUE, FALSE))\n    \n    lengths <- unlist(map(.x = 1:30000,\n                          .f = function(i) length(data_set_3$data[[i]]$vals)))\n                          \n    shiny_tibble_3$cert <- unlist(map(.x = 1:30000,\n                                      .f = function(i) rep(set_3_results$certainties[i], times = lengths[i])))\n    \n    saveRDS(object = shiny_tibble_3, file = \"./data/Set_3/shiny_tibble.RDS\")\n}\n```\n\n## Endanzug-Data <a name=\"application\"></a>\n---\nWhen applying the procedure to the real world data from the Endanzug dataset, I decided to use a subset of 20000 randomly chosen observations. Using the whole dataset is unfeasible with a typical computer and would require further optimizations and the usage of high-performance computing.\n\n## Shiny App <a name=\"shiny\"></a>\n---\nInstead of presenting the visualizations for the classification procedure in static graphics, I decided to use a shiny web app instead. This has multiple advantages in the setting of this final project, but the main motivation behind it was the use case described to me:<br> **An engineer wants to get a preselection of suspicious observations they should have a look at.**\n\nIn this context, having a raw R file as output without an easy way to interact with it, would not be particularly useful. Instead, being able to run this shiny app on a local server with the precalculated values stored in a database, would be more in line with the idea of the job. This also motivates the features I implemented for the app (and plan to implement in future updates) like:\n* setting the focus to single observations\n* changing the plotting window\n* changing the centrainty threshold for observations to be classified as atypical\n\netc.\n\nTo start the shiny app, I recommend cloning this repository and executing the file **app.R** locally. This will start the shiny app on a local server. Instead, one can choose to use the **binder** button on the repo site to start it. Due to a lengthy build process, this is not the recommended way to look at it.\n\nThe shiny app serves as the visualization for all results of the previously explained simulation studies and shows what a possible deployment of the method in a real world scenario could look like.\n\n## Outlook <a name=\"outlook\"></a>\n---\nThe current state of the project and the implementation can serve as an example for the capabilities of the functional depth approach described by \n\n### Finalize Implementation of Updating Procedure\nIn the current state of the project, the implementation of the updating procedure is incomplete. Future revisions will fill this incompleteness and add simulations to show the process of updating and compare cases where observations were added in an updating procedure to data sets containing them from the beginning. This can serve as a device to check the validity of the updating procedure.\n\n### Improvements of Implementation\nThe implementation above still has some other problems. The most striking is the tendency of the sampling procedure to mark a full sample as atypical, if it contains a lower than expected fraction of atypical observations. <br>\nI plan to address this by introducing a rescaling factor to the cutoff threshold $C$ that adjusts for the removal of observations from the sample currently under consideration. This seems reasonable, as adding a new observation to a data set will always increase calculated depths for all observations. Therefore, removing observations can lead to overall lower depths and incrementally lower all observations under the cutoff that determines if they are classified as atypical in a sample. This is not described in the paper this project is based on - so it will make some theoretical work necessary to develop an appropritae correction.\n\n### Generalizations\nAs described in a previous section, the method described in this project for data sets which allow for zeroing of the observations could be generalized by introducing another parameter **acceptable shifting** in addition to **acceptable stretching**. This could then be used to define a method that finds comparable subsets in data sets that do not allow zeroing. As this introduces more variables and makes a more sophisticated splitting algorithm necessary, it was out of the scope of this project, but will be addressed in the future.\n\n### Parameter Choice\nAn important part of this procedure will be the choice of its tuning parameters: \n* In its purest form the algorithm needs a choice for $\\alpha$, $\\gamma$, $B$ and a grid to use for approximation purposes\n* Adding sampling adds the choice of sample size and number of samples\n* The full procedure then additionally needs $\\lambda$\n\nSome of these like sample size and number of samples could be made dependent on the structure of comparable subsets and even change when switching from one comparable subset to the next. One goal of this could be to make each observation appear in a similar number of samples overall. But other reasonable procedures are possible. <br>\nOthers like $\\alpha$ and $\\lambda$ could be chosen by a simulation method. Constructing a similar but smaller data set with intentionally added outliers to perform cross validation or a similar procedure could be an approach for this case. A more sophisticated and detailed description of this method will be part of future revisions.\n\n### Making Results reproducible\nCurrently, the results of the method are mostly non-reproducible when taking about exact numbers. Qualitative results of the procedure will be similar, but due to randomization in the method the replication of exact numbers is currently not possible. This can be addressed with some work to allow for manually setting seeds in the classification algorithm without sampling and in the choice of samples. Because of parallelization this cannot be done be setting the seed once in the beginning.\n\n### Performance Measures for the Algorithm & Benchmarking\nTightly connected to the point of parameter choice is the question of how to measure the performance of the outlier detection procedure in different settings. \n* First, I am going to look for existing data sets that are commonly used to benchmark outlier classification procedures. The performance of this algorithm in these preclassified settings can serve as grounds for determining in which cases and using which parameter choices the method performs well and compare it to existing methods that are applicable in comparable scenarios. <br>\n* Second, as can be seen by the previously generated data, an ex ante classification of realizations created by different dgps may not appropriately cover the idea of outlyingness. Some realizations in previous data sets look very typical for the non-outlier dgp and a classification as atypical due to the different dgp could lead to an underestimation of the procedures performance. Therefore, a comparison to established methods can serve as a better tool to judge the effectiveness.\n\n### Identifying what contributes to outlyingness of an observation\nOnce atypical observations in a data set are identified, it is very interesting to see what contributes to their outlyingness in the eyes of the algorithm. To create some ex-post explanation for why a classification decision was made would be a useful tool to inform future real-world decisions or improve the procedure itself by incorporating that information into the mechanism. Some interesting approaches to create an ex-post explanation are the following:\n\n1. Create slightly altered realizations of an observation that has been marked as an outlier and see what effect different alterations have on its classification (or certainty in case of the sampling-based methods).\n2. Compare locally similar observations that have different outcomes in the overall procedure.\n\nThere are more ways to gain information on what features contribute to outlyingness, but due to the current scope of this project, more in-depth considerations of this approach will only be part of future revisions.\n\n### Creation of an Rcpp-Package to improve usability\nFurther iterations of this project will be different in the way the functions are made available. Instead of implementing the functions directly in the main notebook, there will be an additional notebook explaining the implementation and an R package that can be installed directly that contains all functionality provided above. This will make it easier to use the functions in the future.\n\n### Improvements to the Shiny App\nThe visualizations of the shiny app will also undergo considerable overhauls, starting with changes to which observations are plotted when focus is set to a single observation. In this case for example plotting more observations in the close vicinity of the observation might be of greater interest, whereas observations farther away may provide little information of use and could be plotted less frequently to avoid overplotting. <br>\nThere are further improvements planned but due to the interactive process of designing an interface that is meant for direct interaction with the user, it is difficult to predict the exact nature of the changes.\n\n## Sources <a name=\"sources\"></a>\n---\n* Cuevas, A. & Febrero-Bande, M. & Fraiman, R. (2006). On the use of bootstrap for estimating functions with functional data. Computational Statistics & Data Analysis. 51. 1063-1074.\n* Febrero-Bande, M. & Galeano, P. & Gonz\u00e0lez-Manteiga, W. (2008). Outlier detection in functional data by depth measures, with application to identify abnormal NOx levels. Environmetrics. 19. 331 - 345.\n* Gijbels, I. & Nagy, S. (2017). On a General Definition of Depth for Functional Data. Statistical Science. 32. 630-639.\n\n---\n\nNotebook by **Jakob R. J\u00fcrgens** <br>\nFinal project for the course **OSE - data science** in the summer semester 2021<br>\nFind me at [jakobjuergens.com](https://jakobjuergens.com)\n", "meta": {"hexsha": "7cfaa65c535cd2654a708e369a5bca7c56b8a886", "size": 111637, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Project_Main.ipynb", "max_stars_repo_name": "JakobJuergens/ose-data-science-course-projeect-JakobJuergens", "max_stars_repo_head_hexsha": "509d1636ebd68211aaae0e38dfec987c8eef7472", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-13T13:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-13T13:11:59.000Z", "max_issues_repo_path": "Project_Main.ipynb", "max_issues_repo_name": "JakobJuergens/ose-data-science-course-projeect-JakobJuergens", "max_issues_repo_head_hexsha": "509d1636ebd68211aaae0e38dfec987c8eef7472", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Project_Main.ipynb", "max_forks_repo_name": "JakobJuergens/ose-data-science-course-projeect-JakobJuergens", "max_forks_repo_head_hexsha": "509d1636ebd68211aaae0e38dfec987c8eef7472", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.4108135422, "max_line_length": 984, "alphanum_fraction": 0.6453057678, "converted": true, "num_tokens": 20312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368443773709, "lm_q2_score": 0.06278920158197557, "lm_q1q2_score": 0.024634517209646916}}
{"text": "# Parameter settings\n\nThe following code imports the BD wrapper class and initializes it:\n\n```python\nimport BD_wrapper.BD_wrapper as bdw\nb = bdw.BayesianDistance()\n```\n\nIn the following we list all possible parameter settings for the BD wrapper with their default settings.\n\n### General settings\n\n```python\nb.version = '2.4'\n```\n\nThe `version` parameter defines the BDC version that should be used. Currently available options are `'2.4'` (corresponding to the BDC version discussed in [Reid et al. 2019](https://ui.adsabs.harvard.edu/abs/2019ApJ...885..131R/abstract)) and `'1.0'` (corresponding to the BDC version discussed in [Reid et al. 2016](https://ui.adsabs.harvard.edu/abs/2016ApJ...823...77R/abstract)).\n\n```python\nb.use_ncpus = None\n```\n\nSpecify the number of CPUs used for multiprocessing. \n\n<div class=\"alert alert-block alert-warning\">\nNOTE: By default the BD_wrapper uses 75% of all CPUs on the machine where it is running on unless the `use_ncpus` parameter is specified.\n</div>\n\n```python\nb.verbose = True\n```\n\nSet the `verbose` parameter to `False` if you don't want status messages to be printed to the terminal.\n\n```python\nb.save_temporary_files = False\n```\n\nIf the `save_temporary_files` parameter is set to `True`, all temporary files produced by the BDC will be saved (by default these files are removed after the main distance results are read in by the `BD wrapper`). setting this parameter to `True` can be useful in case of debugging or trying to understand the distance estimation process in detail.\n\n```python\nb.plot_probability = False\n```\n\nIf the `plot_probability` is set to `True` a plot of the probability density distribution of the distance results (similar to Figs. 2 and 3 in [Riener et al. 2020b](https://ui.adsabs.harvard.edu/abs/2020A%26A...640A..72R/abstract)) is produced.\n\n<div class=\"alert alert-block alert-warning\">\nNote: Do not set the `save_temporary_files` and `plot_probability` parameters to `True` in case of large input tables! \n</div>\n\n### Parameters controlling the weight of the priors\n\n```python\nb.prob_sa = None  # default values: 0.85 (v2.4), 0.5 (v1.0)\nb.prob_kd = None  # default values: 1.0 (v2.4), 0.85 (v1.0)  \nb.prob_gl = None  # default values: 1.0 (v2.4), 0.85 (v1.0)   \nb.prob_ps = None  # default values: 0.25 (v2.4), 0.15 (v1.0)   \nb.prob_pm = None  # default values: 0.85 (v2.4), N/A (v1.0)\n```\n\nThese five parameters define the probabilities for the different priors. If they are not specified default values as specified in [Reid et al. 2019](https://ui.adsabs.harvard.edu/abs/2019ApJ...885..131R/abstract) (if `b.version = '2.4'`) [Reid et al. 2016](https://ui.adsabs.harvard.edu/abs/2016ApJ...823...77R/abstract) (if `b.version = '1.0'`) are assumed. The priors are:\n- `prob_sa`: the proximity to features from an assumed spiral arm model\n- `prob_kd`: the kinematic distance\n- `prob_gl`: the Galactic latitude value or displacement from the Galactic midplane\n- `prob_ps`: the proximity to high mass star-forming regions with parallax measurements\n- `prob_pm`: the proper motion of the source (only available in v2.4)\n\n### Parameters for input and output tables\n\n```python\nb.path_to_input_table = None\nb.path_to_output_table = None\n```\n\nThese parameter define the path to the input table and the resulting output table containing the distance results.\n\n```python\nb.table_format = 'ascii'\n```\nTable format of the input and resulting output table. See this [list](https://docs.astropy.org/en/stable/io/unified.html#built-in-table-readers-writers) for supported table formats.\n\n```python\nb.colname_lon = None  \nb.colname_lat = None  \nb.colname_vel = None  \nb.colname_e_vel = None  \nb.colname_kda = None  \nb.colname_name = None  \nb.colname_vel_disp = None  \n```\n\nWith the preceding seven parameters users can specify the corresponding columns in the input table. These column names specify:\n- `colname_lon`: the name of the column giving the Galactic longitude value\n- `colname_lat`: the name of the column giving the Galactic latitude value\n- `colname_vel`: the name of the column giving the radial velocity (VLSR) value\n- `colname_e_vel` (optional): the name of the column giving the error in radial velocity\n- `colname_kda` (optional): the name of the column giving solutions for the kinematic distance ambiguity ('N', or 'F')\n- `colname_name` (optional): the name of the column giving the source name\n- `colname_vel_disp` (optional): the name of the column giving the velocity dispersion value associated with the source; has to be specified if `prior_velocity_dispersion` is set to `True`\n\nOnly the `colname_lon`, `colname_lat`, and `colname_vel` parameters have to be specified. In case there are no column names available, alternatively also the column number can be specified with the following parameters instead: \n\n```python\nb.colnr_lon = None  \nb.colnr_lat = None  \nb.colnr_vel = None  \nb.colnr_e_vel = None  \nb.colnr_kda = None  \nb.colnr_name = None  \nb.colnr_vel_disp = None  \n```\n\n```python\nb.add_kinematic_distance = True\n```\n\nIf the `add_kinematic_distance` parameter is set to `True`, the distance results will include two additional columns giving the solutions of the near and far kinematic distances. This essentially corresponds to a BDC run in which all priors apart from KD prior are switched off.\n\n```python\nb.add_galactocentric_distance = True\n```\n\nIf the `add_galactocentric_distance` parameter is set to `True`, the distance results will include an additional column giving the Galactocentric distance.\n\n```python\nb.default_e_vel = 5.0\n```\n\nThe `default_e_vel` parameter sets the default value for the uncertainty in the radial velocity (VLSR) in case neither `colname_e_vel` or `colnr_e_vel` is specified or if the corresponding value is not given.\n\n```python\nb.max_e_vel = 5.0\n```\n\nThe `max_e_vel` parameter sets the maximum value for the uncertainty in the radial velocity (VLSR). e_VLSR values exceeding this threshold are set to `max_e_vel`.\n\n```python\nb.kda_weight = 1\n```\nIf the `colname_kda` or `colnr_kda` parameters are specified, users can decide whether to modify their weight with the `kda_weight` parameter. For example, if `kda_weight = 1`, KDA input values of `'N'` and `'F'` would result in $P_{\\text{far}} = 0$ and $P_{\\text{far}} = 1$, respectively. If `kda_weight = 0.5`, these values reduce to $P_{\\text{far}} = 0.25$ and $P_{\\text{far}} = 0.75$.\n\n### Parameters for the prior for the kinematic distance ambiguity\n\n```python\nb.check_for_kda_solutions = True\nb.kda_info_tables = []\nb.exclude_kda_info_tables = []\n```\n\nIf the `check_for_kda_solutions` parameter is set to `True`, solutions of the kinematic distance ambiguity for sources in the literature will be crossmatched with the input source coordinates to inform the $P_{\\text{far}}$ prior. See Sect. 3.2 and Appendix A in [Riener et al. 2020b](https://ui.adsabs.harvard.edu/abs/2020A%26A...640A..72R/abstract) for more information. By default all KDA info tables in the `KDA_info` directory are considered. Users can specify whether they want to include or exclude specific catalogues. For example `b.kda_info_tables = ['Roman-Duval+09', 'Urquhart+18']` would only consider these KDA tables, whereas specifying `b.exclude_kda_info_tables = ['Roman-Duval+09', 'Simon+06', 'Urquhart+18']` would exclude these three tables, but consider the remaining nine tables.\n\n### Parameters for the size-linewidth prior\n\nThe following parameters define the size-linewidth prior. The size-linewidth prior is only used if the `prior_velocity_dispersion` value is set to `True`. This prior requires that either `colname_vel_disp` or `colnr_vel_disp` are specified by the user.\n\n```python\nb.prior_velocity_dispersion = False  \nb.beam = None  \nb.random_seed = 177  \nb.sample = 1000  \nb.size_linewidth_index = 0.5  \nb.size_linewidth_e_index = 0.1  \nb.size_linewidth_sigma_0 = 0.7  \nb.size_linewidth_e_sigma_0 = 0.1  \n```\n\nThe size-linewidth prior tries to solve for the KDA by considering the velocity dispersion associated with the input source. By default the size-linewidth relationship established by [Solomon et al. (1987)](https://ui.adsabs.harvard.edu/abs/1987ApJ...319..730S/abstract) is used which is defined as:\n\n\\begin{equation}\n\\sigma_{v,exp} = \\sigma_{v,0}\\cdot\\left( \\dfrac{L}{1 \\text{pc}} \\right)^{\\gamma}\n\\end{equation}\n\nwhere $\\sigma_{v,0}$ corresponds to the `size_linewidth_sigma_0` parameter and the exponent $\\gamma$ corresponds to the `size_linewidth_index` parameter. The expected velocity dispersion values for the two kinematic distance values for the input source are determined from the average value of a Monte Carlo sampling of the size-linewidth relationship within the specified errors of  $\\sigma_{v,0}$ and $\\gamma$, which are given by the `size_linewidth_e_sigma_0` and `size_linewidth_e_index` parameters. The `random_seed` parameter intitializes the random seed for the Monte Carlo sampling and the sample size can be specified with the `sample` parameter.\nThe `beam` parameter specifies the telescope beam and has to be valid [astropy.units.Quantity](https://docs.astropy.org/en/stable/api/astropy.units.Quantity.html#astropy.units.Quantity) object.\n\nSee 3.3 in [Riener et al. 2020b](https://ui.adsabs.harvard.edu/abs/2020A%26A...640A..72R/abstract) for more details about the size-linewidth prior.\n\n\n```python\n\n```\n", "meta": {"hexsha": "1d22a725e27eb41e21514cd0ea24270ffaeb5dee", "size": 11859, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorials/Parameter_settings.ipynb", "max_stars_repo_name": "mriener/BD_wrapper", "max_stars_repo_head_hexsha": "e61a27c67420359db557329457fff586700d8001", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-29T11:35:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-29T11:35:21.000Z", "max_issues_repo_path": "tutorials/Parameter_settings.ipynb", "max_issues_repo_name": "mriener/BD_wrapper", "max_issues_repo_head_hexsha": "e61a27c67420359db557329457fff586700d8001", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/Parameter_settings.ipynb", "max_forks_repo_name": "mriener/BD_wrapper", "max_forks_repo_head_hexsha": "e61a27c67420359db557329457fff586700d8001", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-09T00:37:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-09T00:37:19.000Z", "avg_line_length": 49.2074688797, "max_line_length": 807, "alphanum_fraction": 0.6480310313, "converted": true, "num_tokens": 2505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.06278920245886001, "lm_q1q2_score": 0.024634516661429944}}
{"text": "```python\n# This cell is mandatory in all Dymos documentation notebooks.\nmissing_packages = []\ntry:\n    import openmdao.api as om\nexcept ImportError:\n    if 'google.colab' in str(get_ipython()):\n        !python -m pip install openmdao[notebooks]\n    else:\n        missing_packages.append('openmdao')\ntry:\n    import dymos as dm\nexcept ImportError:\n    if 'google.colab' in str(get_ipython()):\n        !python -m pip install dymos\n    else:\n        missing_packages.append('dymos')\ntry:\n    import pyoptsparse\nexcept ImportError:\n    if 'google.colab' in str(get_ipython()):\n        !pip install -q condacolab\n        import condacolab\n        condacolab.install_miniconda()\n        !conda install -c conda-forge pyoptsparse\n    else:\n        missing_packages.append('pyoptsparse')\nif missing_packages:\n    raise EnvironmentError('This notebook requires the following packages '\n                           'please install them and restart this notebook\\'s runtime: {\",\".join(missing_packages)}')\n```\n\n# Aircraft Balanced Field Length Calculation\n\n```{admonition} Things you'll learn through this example\n- How to perform branching trajectories\n- How to constraint the difference between values at the end of two different phases\n- Using complex-step differentiation on a monolithic ODE component\n```\n\nThe United States Federal Aviation Regulations Part 25 defines a\nbalanced field length for the aircraft as the shortest field which can\naccommodate a \"balanced takeoff\".  In a balanced takeoff the aircraft\naccelerates down the runway to some critical speed \"V1\".\n\nBefore achieving V1, the aircraft must be capable of rejecting the takeoff\nand coming to a stop before the end of the runway.\n\nAfter V1, the aircraft must be capable of achieving an altitude of 35 ft\nabove the end of the runway with a speed of V2 (the minimum safe takeoff\nspeed or 1.2 x the stall speed) while on a single engine (for two engine aircraft).\n\nAt V1, both options must be available. The nominal phase sequence for this trajectory is:\n\n1. Break Release to V1 (br_to_v1)\n\n    Accelerate down the runway under the power of two engines.\n    Where V1 is some as-yet-undetermined speed.\n\n2. V1 to Vr (v1_to_vr)\n\n    Accelerate down the runway under the power of a single engine.\n    End at \"Vr\" or the rotation speed.\n    The rotation speed here is defined as 1.2 times the stall speed.\n\n3. Rotate (rotate)\n\n    Operating under the power of a single engine, begin pitching the nose\n    up (increasing alpha) while rolling down the runway.\n    In this example, the rate of change of alpha is linear over some time.\n\n4. Climb (climb)\n\n    Still operating with one engine, begin climbing to a flight path angle\n    of no more than 5 degrees.\n    This phase ends when the aircraft is 35 feet above the ground with an airspeed\n    of 1.25 x the stall speed.\n\n5. Rejected Takeoff (rto)\n\n    Shut down all engines (zero thrust) and apply brakes (increase of\n    runway $\\mu$ coefficient to 0.3) until the aircraft airspeed is zero.\n\n    This phase is continuous in time and state with the first phase, and so\n    forms a branch off of the nominal trajectory.\n\nSince the RTO phase and the climb phase both must end such that they\ndo not exceed the end of the runway, the final value of range in each\nof these two phases must be the same.  We don't know what this value is\nuntil we've solved the problem, so we cannot simply constrain both to\nthe same fixed value.\n\nInstead, we'll use a trajectory linkage constraint to ensure that `range`\nat the end of the RTO phase is equal to `range` at the end of the climb phase.\n\nMore information on calculating the balanced field length is available\nin section 17.8 of _Aircraft Design: A Conceptual Approach_ by\nDaniel Raymer {cite}`raymer2012aircraft`.\n\n## The ODE System\n\nIn this problem two sets of ordinary differential equations are used:\none for the aircraft motion on the runway, and one for the aircraft motion once airborne.\n\nFor simplification, we're going to assume a constant atmospheric model since the aircraft will never exceed 35 feet of altitude.\nAlso, since the duration of the trajectory is small, we're going to assume that the vehicle fuel burn is negligible\n\n### The Aerodynamic Model\n\nBoth sets of equations of motion have common aerodynamic models.\n\nFirst, the lift coefficient is computed using a model which assumes linearity in lift wrt the angle of attack.\n\n\\begin{align}\n    C_L &= C_{L0} + \\frac{\\alpha}{\\alpha_{max}} \\left(C_{L-max} - C_{L0}\\right)\n\\end{align}\n\nNext, the drag-due-to-lift factor is computed (Equations 12.48 and 12.61 in Raymer[@raymer2012aircraft]).\n\n\\begin{align}\n    K_{nom} &= \\frac{1}{ \\pi  AR  e} \\\\\n    b &= \\frac{span}{2} \\\\\n    K &= 33 K_{nom} \\frac{ \\left(\\frac{h + h_w}{b} \\right) ^{\\frac{3}{2}}}{1.0 + 33 \\left( \\frac{h + h_w}{b}\\right) ^{\\frac{3}{2}}}\n\\end{align}\n\nNote the singularity in the equation for $K$ when $h + h_w$ is negative.\nThis causes this problem to be difficult to solve using a shooting method.\nIf the optimizer proposes a combination of initial states and a control history that results in altitude dropping significantly below zero, the propagation will fail.\n\nFinally, the lift and drag are computed after computing the dynamic pressure.\n\n\\begin{align}\n    q &= 0.5 \\rho v^2 \\\\\n    L &= q  S  C_L \\\\\n    D &= q S \\left( C_{D0} + K C_{L}^2 \\right)\n\\end{align}\n\n### Stall Speed\n\nThis model relies on the ratio of the current true airspeed to stall speed ($\\frac{v}{v_{stall}}$).\nThis constraint is used to trigger the beginning of rotation and is used as a boundary constraint at the end of the initial climb.\nStall speed is given by Equation 5.6 in Raymer[@raymer2012aircraft].\n\n\\begin{align}\n    W &= m g \\\\\n    v_{stall} &= \\sqrt{\\frac{2 * W}{\\rho S C_{L-max}}}\n\\end{align}\n\n### Runway Equations of Motion\n\nThe runway equations of motion are used to integrate range and speed as the vehicle rolls along the runway.\n\n\\begin{align}\n  F_r &= mg - L \\cos \\alpha - T \\sin \\alpha \\\\\n  \\dot{v} &= \\frac{T \\cos \\alpha - D - F_r \\mu_r}{m} \\\\\n  \\dot{r} &= v\n\\end{align}\n\n\n|State  | Description           |Units        |\n|-------|-----------------------|-------------|\n|r      |range                  |$m$          |\n|v      |true airspeed          |$m s^{-1}$   |\n\n\n### Flight Equations of Motion\n\nThe flight equations of motion include two additional state variables: the flight-path angle ($\\gamma$) and altitude ($h$).\n\n\\begin{align}\n  \\dot{v} &= \\frac{T}{m} \\cos \\alpha - \\frac{D}{m} - g \\sin \\gamma \\\\\n  \\dot{\\gamma} &= \\frac{T}{m v} \\sin \\alpha + \\frac{L}{m v} - \\frac{g \\cos \\gamma}{v} \\\\\n  \\dot{h} &= v \\sin \\gamma \\\\\n  \\dot{r} &= v \\cos \\gamma\n\\end{align}\n\n|State    | Description           |Units       |\n|---------|-----------------------|------------|\n|v        |true airspeed          |$m s^{-1}$  |\n|$\\gamma$ |flight path angle      |$rad$       |\n|r        |range                  |$m$         |\n|h        |altitude               |$m$         |\n\n\n### Treatment of the angle-of-attack ($\\alpha$)\n\nIn three of the runway phases (break release to $V1$, $V1$ to $V_r$, and rejected takeoff) $\\alpha$ is treated as a fixed static parameter.\n\nIn the rotation phase, $\\alpha$ is treated as a polynomial control of order 1.\n$\\alpha$ starts at an initial value of zero and increases at a linear rate until the upward forces on the aircraft due to lift and thrust cancel the downward force due to gravity.\n\nIn the climb phase, $\\alpha$ is treated as a dynamic control to be chosen by the optimizer.\n\nPhase linkage constraints are used to maintain continuity in $\\alpha$ throughout the trajectory.\n\n### Parameters\n\nThe following parameters define properties of the aircraft and environment for the problem.\n\n|Parameters  | Description               |Units        |Value                    |\n|------------|---------------------------|-------------|-------------------------|\n|m           |mass                       |$kg$         | 79015.7909              |\n|g           |gravitational acceleration |$m s^{-2}$   | 9.80665                 |\n|T           |thrust                     |$N$          | 2 x 120101.98 (nominal) |\n|$\\mu$       |runway friction coefficient|-            | 0.03 (nominal)          |\n|h           |altitude                   |$m$          | 0                       |\n|$\\rho$      |atmospheric density        |$kg\\,m^{3}$  | 1.225                   |\n|S           |aerodynamic reference area |$m^2$        | 124.7                   |\n|CD0         |zero-lift drag coefficient |-            | 0.03                    |\n|AR          |wing aspect ratio          |-            | 9.45                    |\n|e           |Oswald's wing efficiency   |-            | 801                     |\n|span        |wingspan                   |$m$          | 35.7                    |\n|h_w         |height of wing above CoG   |$m$          | 1.0                     |\n|CL0         |aerodynamic reference area |-            | 0.5                     |\n|CL_max      |aerodynamic reference area |-            | 2.0                     |\n\n## The Optimal Control Problem\n\nThe following constraints and objective complete the definition of this optimal control problem.\n\n### Objective\n\n|Name   | Phase     | Location | Description | Minimized or Maximized | Ref  |\n|-------|-----------|----------|-------------|------------------------|------|\n| r     | rto       | final    | range       | Minimized              | 1000 |\n\n### Nonlinear Boundary Constraints\n\n|Name              | Phase    | Description           | Loc   | Units     | Lower  | Upper | Equals | Ref    |\n|------------------|----------|-----------------------|-------|-----------|--------|-------|--------|--------|\n| v_over_v_stall   | v1_to_vr | $\\frac{v}{v_{stall}}$ | final | -         | 1.2    |       |        | 1.2    |\n| v                | rto      | airspeed              | final | $ms^{-1}$ |        |       | 0      | 100    |\n| F_r              | rotate   | downforce on gear     | final | $N$       |        |       | 0      | 100000 |\n| h                | climb    | altitude              | final | $ft$      |        |       | 35     | 35     |\n| gam              | climb    | flight path angle     | final | $rad$     |        |       | 5      | 5      |\n| v_over_v_stall   | climb    | $\\frac{v}{v_{stall}}$ | final | -         | 1.25   |       |        | 1.25   |\n\n### Nonlinear Path Constraints\n\n|Name              | Phase    | Description         | Units     | Lower  | Upper | Equals | Ref    |\n|------------------|----------|---------------------|-----------|--------|-------|--------|--------|\n| gam              | climb    | flight path angle   | $rad$     | 0      | 5     |        | 5      |\n\n### Phase Continuity Constraints\n\n| First Phase      | Second Phase      | Variables                   |\n|------------------|-------------------|-----------------------------|\n| br_to_v1[final]  | v1_to_vr[initial] | $time$, $r$, $v$            |\n| vr_to_v1[final]  | rotate[initial]   | $time$, $r$, $v$, $\\alpha$  |\n| rotate[final]    | climb[initial]    | $time$, $r$, $v$, $\\alpha$  |\n| br_to_v1[final]  | rto[initial]      | $time$, $r$, $v$            |\n| climb[final]     | rto[final]        | $r$                         |\n\n## Source Code\n\nUnlike most other Dymos examples, which use analytic derivatives, the ODE in this case is a single component.\nAll calculations within the ODE are complex-safe and thus we can use complex-step, in conjunction with\n[partial derivative coloring](http://openmdao.org/newdocs/versions/latest/features/core_features/working_with_derivatives/simul_derivs.html),\nto automatically compute the derivatives using complex-step with reasonable speed.\n\nSince there is significant commonality between the ODEs for the runway roll and the climb, this implementation\nuses a single ODE class with an option `mode` that can be set to either `'runway'` or `'climb'`.\nBased on the value of `mode`, the component conditionally changes its inputs and outputs.\n\n### BalancedFieldODEComp\n\n\n```python\nclass BalancedFieldODEComp(om.ExplicitComponent):\n    \"\"\"\n    The ODE System for an aircraft takeoff climb.\n\n    Computes the rates for states v (true airspeed) gam (flight path angle) r (range) and h (altitude).\n\n    References\n    ----------\n    .. [1] Raymer, Daniel. Aircraft design: a conceptual approach. American Institute of\n    Aeronautics and Astronautics, Inc., 2012.\n    \"\"\"\n    def initialize(self):\n        self.options.declare('num_nodes', types=int)\n        self.options.declare('g', types=(float, int), default=9.80665, desc='gravitational acceleration (m/s**2)')\n        self.options.declare('mode', values=('runway', 'climb'), desc='mode of operation (ground roll or flight)')\n\n    def setup(self):\n        nn = self.options['num_nodes']\n\n        # Scalar (constant) inputs\n        self.add_input('rho', val=1.225, desc='atmospheric density at runway', units='kg/m**3')\n        self.add_input('S', val=124.7, desc='aerodynamic reference area', units='m**2')\n        self.add_input('CD0', val=0.03, desc='zero-lift drag coefficient', units=None)\n        self.add_input('CL0', val=0.5, desc='zero-alpha lift coefficient', units=None)\n        self.add_input('CL_max', val=2.0, desc='maximum lift coefficient for linear fit', units=None)\n        self.add_input('alpha_max', val=np.radians(10), desc='angle of attack at CL_max', units='rad')\n        self.add_input('h_w', val=1.0, desc='height of the wing above the CG', units='m')\n        self.add_input('AR', val=9.45, desc='wing aspect ratio', units=None)\n        self.add_input('e', val=0.801, desc='Oswald span efficiency factor', units=None)\n        self.add_input('span', val=35.7, desc='Wingspan', units='m')\n        self.add_input('T', val=1.0, desc='thrust', units='N')\n\n        # Dynamic inputs (can assume a different value at every node)\n        self.add_input('m', shape=(nn,), desc='aircraft mass', units='kg')\n        self.add_input('v', shape=(nn,), desc='aircraft true airspeed', units='m/s')\n        self.add_input('h', shape=(nn,), desc='altitude', units='m')\n        self.add_input('alpha', shape=(nn,), desc='angle of attack', units='rad')\n\n        # Outputs\n        self.add_output('CL', shape=(nn,), desc='lift coefficient', units=None)\n        self.add_output('q', shape=(nn,), desc='dynamic pressure', units='Pa')\n        self.add_output('L', shape=(nn,), desc='lift force', units='N')\n        self.add_output('D', shape=(nn,), desc='drag force', units='N')\n        self.add_output('K', val=np.ones(nn), desc='drag-due-to-lift factor', units=None)\n        self.add_output('F_r', shape=(nn,), desc='runway normal force', units='N')\n        self.add_output('v_dot', shape=(nn,), desc='rate of change of speed', units='m/s**2',\n                        tags=['dymos.state_rate_source:v'])\n        self.add_output('r_dot', shape=(nn,), desc='rate of change of range', units='m/s',\n                        tags=['dymos.state_rate_source:r'])\n        self.add_output('W', shape=(nn,), desc='aircraft weight', units='N')\n        self.add_output('v_stall', shape=(nn,), desc='stall speed', units='m/s')\n        self.add_output('v_over_v_stall', shape=(nn,), desc='stall speed ratio', units=None)\n\n        # Mode-dependent IO\n        if self.options['mode'] == 'runway':\n            self.add_input('mu_r', val=0.05, desc='runway friction coefficient', units=None)\n        else:\n            self.add_input('gam', shape=(nn,), desc='flight path angle', units='rad')\n            self.add_output('gam_dot', shape=(nn,), desc='rate of change of flight path angle',\n                            units='rad/s', tags=['dymos.state_rate_source:gam'])\n            self.add_output('h_dot', shape=(nn,), desc='rate of change of altitude', units='m/s',\n                            tags=['dymos.state_rate_source:h'])\n\n        self.declare_coloring(wrt='*', method='cs')\n\n    def compute(self, inputs, outputs, discrete_inputs=None, discrete_outputs=None):\n        g = self.options['g']\n\n        # Compute factor k to include ground effect on lift\n        rho = inputs['rho']\n        v = inputs['v']\n        S = inputs['S']\n        CD0 = inputs['CD0']\n        m = inputs['m']\n        T = inputs['T']\n        h = inputs['h']\n        h_w = inputs['h_w']\n        span = inputs['span']\n        AR = inputs['AR']\n        CL0 = inputs['CL0']\n        alpha = inputs['alpha']\n        alpha_max = inputs['alpha_max']\n        CL_max = inputs['CL_max']\n        e = inputs['e']\n\n        outputs['W'] = W = m * g\n        outputs['v_stall'] = v_stall = np.sqrt(2 * W / rho / S / CL_max)\n        outputs['v_over_v_stall'] = v / v_stall\n\n        outputs['CL'] = CL = CL0 + (alpha / alpha_max) * (CL_max - CL0)\n        K_nom = 1.0 / (np.pi * AR * e)\n        b = span / 2.0\n        fact = ((h + h_w) / b) ** 1.5\n        outputs['K'] = K = K_nom * 33 * fact / (1.0 + 33 * fact)\n\n        outputs['q'] = q = 0.5 * rho * v ** 2\n        outputs['L'] = L = q * S * CL\n        outputs['D'] = D = q * S * (CD0 + K * CL ** 2)\n\n        # Compute the downward force on the landing gear\n        calpha = np.cos(alpha)\n        salpha = np.sin(alpha)\n\n        # Runway normal force\n        outputs['F_r'] = F_r = m * g - L * calpha - T * salpha\n\n        # Compute the dynamics\n        if self.options['mode'] == 'climb':\n            gam = inputs['gam']\n            cgam = np.cos(gam)\n            sgam = np.sin(gam)\n            outputs['v_dot'] = (T * calpha - D) / m - g * sgam\n            outputs['gam_dot'] = (T * salpha + L) / (m * v) - (g / v) * cgam\n            outputs['h_dot'] = v * sgam\n            outputs['r_dot'] = v * cgam\n        else:\n            outputs['v_dot'] = (T * calpha - D - F_r * inputs['mu_r']) / m\n            outputs['r_dot'] = v\n```\n\n## Building and running the problem\n\nIn the following code we define and solve the optimal control problem.\nNote the use of `add_linkage_constraint` to handle the less common phase\nlinkage condition, where the range must be equal at the end of the `rto` and `climb` phases.\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport openmdao.api as om\nfrom openmdao.utils.general_utils import set_pyoptsparse_opt\nimport dymos as dm\n\np = om.Problem()\n\n_, optimizer = set_pyoptsparse_opt('IPOPT', fallback=True)\n\np.driver = om.pyOptSparseDriver()\np.driver.declare_coloring()\n\n# Use IPOPT if available, with fallback to SLSQP\np.driver.options['optimizer'] = optimizer\np.driver.options['print_results'] = False\nif optimizer == 'IPOPT':\n    p.driver.opt_settings['print_level'] = 5\n    p.driver.opt_settings['derivative_test'] = 'first-order'\n\n# First Phase: Brake release to V1 - both engines operable\nbr_to_v1 = dm.Phase(ode_class=BalancedFieldODEComp, transcription=dm.Radau(num_segments=3),\n                    ode_init_kwargs={'mode': 'runway'})\nbr_to_v1.set_time_options(fix_initial=True, duration_bounds=(1, 1000), duration_ref=10.0)\nbr_to_v1.add_state('r', fix_initial=True, lower=0, ref=1000.0, defect_ref=1000.0)\nbr_to_v1.add_state('v', fix_initial=True, lower=0, ref=100.0, defect_ref=100.0)\nbr_to_v1.add_parameter('alpha', val=0.0, opt=False, units='deg')\nbr_to_v1.add_timeseries_output('*')\n\n# Second Phase: Rejected takeoff at V1 - no engines operable\nrto = dm.Phase(ode_class=BalancedFieldODEComp, transcription=dm.Radau(num_segments=3),\n               ode_init_kwargs={'mode': 'runway'})\nrto.set_time_options(fix_initial=False, duration_bounds=(1, 1000), duration_ref=1.0)\nrto.add_state('r', fix_initial=False, lower=0, ref=1000.0, defect_ref=1000.0)\nrto.add_state('v', fix_initial=False, lower=0, ref=100.0, defect_ref=100.0)\nrto.add_parameter('alpha', val=0.0, opt=False, units='deg')\nrto.add_timeseries_output('*')\n\n# Third Phase: V1 to Vr - single engine operable\nv1_to_vr = dm.Phase(ode_class=BalancedFieldODEComp, transcription=dm.Radau(num_segments=3),\n                    ode_init_kwargs={'mode': 'runway'})\nv1_to_vr.set_time_options(fix_initial=False, duration_bounds=(1, 1000), duration_ref=1.0)\nv1_to_vr.add_state('r', fix_initial=False, lower=0, ref=1000.0, defect_ref=1000.0)\nv1_to_vr.add_state('v', fix_initial=False, lower=0, ref=100.0, defect_ref=100.0)\nv1_to_vr.add_parameter('alpha', val=0.0, opt=False, units='deg')\nv1_to_vr.add_timeseries_output('*')\n\n# Fourth Phase: Rotate - single engine operable\nrotate = dm.Phase(ode_class=BalancedFieldODEComp, transcription=dm.Radau(num_segments=3),\n                  ode_init_kwargs={'mode': 'runway'})\nrotate.set_time_options(fix_initial=False, duration_bounds=(1.0, 5), duration_ref=1.0)\nrotate.add_state('r', fix_initial=False, lower=0, ref=1000.0, defect_ref=1000.0)\nrotate.add_state('v', fix_initial=False, lower=0, ref=100.0, defect_ref=100.0)\nrotate.add_polynomial_control('alpha', order=1, opt=True, units='deg', lower=0, upper=10, ref=10, val=[0, 10])\nrotate.add_timeseries_output('*')\n\n# Fifth Phase: Climb to target speed and altitude at end of runway.\nclimb = dm.Phase(ode_class=BalancedFieldODEComp, transcription=dm.Radau(num_segments=5),\n                 ode_init_kwargs={'mode': 'climb'})\nclimb.set_time_options(fix_initial=False, duration_bounds=(1, 100), duration_ref=1.0)\nclimb.add_state('r', fix_initial=False, lower=0, ref=1000.0, defect_ref=1000.0)\nclimb.add_state('h', fix_initial=True, lower=0, ref=1.0, defect_ref=1.0)\nclimb.add_state('v', fix_initial=False, lower=0, ref=100.0, defect_ref=100.0)\nclimb.add_state('gam', fix_initial=True, lower=0, ref=0.05, defect_ref=0.05)\nclimb.add_control('alpha', opt=True, units='deg', lower=-10, upper=15, ref=10)\nclimb.add_timeseries_output('*')\n\n# Instantiate the trajectory and add phases\ntraj = dm.Trajectory()\np.model.add_subsystem('traj', traj)\ntraj.add_phase('br_to_v1', br_to_v1)\ntraj.add_phase('rto', rto)\ntraj.add_phase('v1_to_vr', v1_to_vr)\ntraj.add_phase('rotate', rotate)\ntraj.add_phase('climb', climb)\n\n# Add parameters common to multiple phases to the trajectory\ntraj.add_parameter('m', val=174200., opt=False, units='lbm',\n                   desc='aircraft mass',\n                   targets={'br_to_v1': ['m'], 'v1_to_vr': ['m'], 'rto': ['m'],\n                            'rotate': ['m'], 'climb': ['m']})\n\ntraj.add_parameter('T_nominal', val=27000 * 2, opt=False, units='lbf', static_target=True,\n                   desc='nominal aircraft thrust',\n                   targets={'br_to_v1': ['T']})\n\ntraj.add_parameter('T_engine_out', val=27000, opt=False, units='lbf', static_target=True,\n                   desc='thrust under a single engine',\n                   targets={'v1_to_vr': ['T'], 'rotate': ['T'], 'climb': ['T']})\n\ntraj.add_parameter('T_shutdown', val=0.0, opt=False, units='lbf', static_target=True,\n                   desc='thrust when engines are shut down for rejected takeoff',\n                   targets={'rto': ['T']})\n\ntraj.add_parameter('mu_r_nominal', val=0.03, opt=False, units=None, static_target=True,\n                   desc='nominal runway friction coefficient',\n                   targets={'br_to_v1': ['mu_r'], 'v1_to_vr': ['mu_r'],  'rotate': ['mu_r']})\n\ntraj.add_parameter('mu_r_braking', val=0.3, opt=False, units=None, static_target=True,\n                   desc='runway friction coefficient under braking',\n                   targets={'rto': ['mu_r']})\n\ntraj.add_parameter('h_runway', val=0., opt=False, units='ft',\n                   desc='runway altitude',\n                   targets={'br_to_v1': ['h'], 'v1_to_vr': ['h'], 'rto': ['h'],\n                            'rotate': ['h']})\n\ntraj.add_parameter('rho', val=1.225, opt=False, units='kg/m**3', static_target=True,\n                   desc='atmospheric density',\n                   targets={'br_to_v1': ['rho'], 'v1_to_vr': ['rho'], 'rto': ['rho'],\n                            'rotate': ['rho']})\n\ntraj.add_parameter('S', val=124.7, opt=False, units='m**2', static_target=True,\n                   desc='aerodynamic reference area',\n                   targets={'br_to_v1': ['S'], 'v1_to_vr': ['S'], 'rto': ['S'],\n                            'rotate': ['S'], 'climb': ['S']})\n\ntraj.add_parameter('CD0', val=0.03, opt=False, units=None, static_target=True,\n                   desc='zero-lift drag coefficient',\n                   targets={f'{phase}': ['CD0'] for phase in ['br_to_v1', 'v1_to_vr',\n                                                              'rto', 'rotate' 'climb']})\n\ntraj.add_parameter('AR', val=9.45, opt=False, units=None, static_target=True,\n                   desc='wing aspect ratio',\n                   targets={f'{phase}': ['AR'] for phase in ['br_to_v1', 'v1_to_vr',\n                                                             'rto', 'rotate' 'climb']})\n\ntraj.add_parameter('e', val=801, opt=False, units=None, static_target=True,\n                   desc='Oswald span efficiency factor',\n                   targets={f'{phase}': ['e'] for phase in ['br_to_v1', 'v1_to_vr',\n                                                            'rto', 'rotate' 'climb']})\n\ntraj.add_parameter('span', val=35.7, opt=False, units='m', static_target=True,\n                   desc='wingspan',\n                   targets={f'{phase}': ['span'] for phase in ['br_to_v1', 'v1_to_vr',\n                                                               'rto', 'rotate' 'climb']})\n\ntraj.add_parameter('h_w', val=1.0, opt=False, units='m', static_target=True,\n                   desc='height of wing above CG',\n                   targets={f'{phase}': ['h_w'] for phase in ['br_to_v1', 'v1_to_vr',\n                                                              'rto', 'rotate' 'climb']})\n\ntraj.add_parameter('CL0', val=0.5, opt=False, units=None, static_target=True,\n                   desc='zero-alpha lift coefficient',\n                   targets={f'{phase}': ['CL0'] for phase in ['br_to_v1', 'v1_to_vr',\n                                                              'rto', 'rotate' 'climb']})\n\ntraj.add_parameter('CL_max', val=2.0, opt=False, units=None, static_target=True,\n                   desc='maximum lift coefficient for linear fit',\n                   targets={f'{phase}': ['CL_max'] for phase in ['br_to_v1', 'v1_to_vr',\n                                                                 'rto', 'rotate' 'climb']})\n\ntraj.add_parameter('alpha_max', val=10.0, opt=False, units='deg', static_target=True,\n                   desc='angle of attack at maximum lift',\n                   targets={f'{phase}': ['alpha_max'] for phase in ['br_to_v1', 'v1_to_vr',\n                                                                    'rto', 'rotate' 'climb']})\n\n# Standard \"end of first phase to beginning of second phase\" linkages\n# Alpha changes from being a parameter in v1_to_vr to a polynomial control\n# in rotate, to a dynamic control in `climb`.\ntraj.link_phases(['br_to_v1', 'v1_to_vr'], vars=['time', 'r', 'v'])\ntraj.link_phases(['v1_to_vr', 'rotate'], vars=['time', 'r', 'v', 'alpha'])\ntraj.link_phases(['rotate', 'climb'], vars=['time', 'r', 'v', 'alpha'])\ntraj.link_phases(['br_to_v1', 'rto'], vars=['time', 'r', 'v'])\n\n# Less common \"final value of r must match at ends of two phases\".\ntraj.add_linkage_constraint(phase_a='rto', var_a='r', loc_a='final',\n                            phase_b='climb', var_b='r', loc_b='final',\n                            ref=1000)\n\n# Define the constraints and objective for the optimal control problem\nv1_to_vr.add_boundary_constraint('v_over_v_stall', loc='final', lower=1.2, ref=100)\n\nrto.add_boundary_constraint('v', loc='final', equals=0., ref=100, linear=True)\n\nrotate.add_boundary_constraint('F_r', loc='final', equals=0, ref=100000)\n\nclimb.add_boundary_constraint('h', loc='final', equals=35, ref=35, units='ft', linear=True)\nclimb.add_boundary_constraint('gam', loc='final', equals=5, ref=5, units='deg', linear=True)\nclimb.add_path_constraint('gam', lower=0, upper=5, ref=5, units='deg')\nclimb.add_boundary_constraint('v_over_v_stall', loc='final', lower=1.25, ref=1.25)\n\nrto.add_objective('r', loc='final', ref=1000.0)\n\n#\n# Setup the problem and set the initial guess\n#\np.setup(check=True)\n\np.set_val('traj.br_to_v1.t_initial', 0)\np.set_val('traj.br_to_v1.t_duration', 35)\np.set_val('traj.br_to_v1.states:r', br_to_v1.interp('r', [0, 2500.0]))\np.set_val('traj.br_to_v1.states:v', br_to_v1.interp('v', [0, 100.0]))\np.set_val('traj.br_to_v1.parameters:alpha', 0, units='deg')\n\np.set_val('traj.v1_to_vr.t_initial', 35)\np.set_val('traj.v1_to_vr.t_duration', 35)\np.set_val('traj.v1_to_vr.states:r', v1_to_vr.interp('r', [2500, 300.0]))\np.set_val('traj.v1_to_vr.states:v', v1_to_vr.interp('v', [100, 110.0]))\np.set_val('traj.v1_to_vr.parameters:alpha', 0.0, units='deg')\n\np.set_val('traj.rto.t_initial', 35)\np.set_val('traj.rto.t_duration', 35)\np.set_val('traj.rto.states:r', rto.interp('r', [2500, 5000.0]))\np.set_val('traj.rto.states:v', rto.interp('v', [110, 0]))\np.set_val('traj.rto.parameters:alpha', 0.0, units='deg')\n\np.set_val('traj.rotate.t_initial', 70)\np.set_val('traj.rotate.t_duration', 5)\np.set_val('traj.rotate.states:r', rotate.interp('r', [1750, 1800.0]))\np.set_val('traj.rotate.states:v', rotate.interp('v', [80, 85.0]))\np.set_val('traj.rotate.polynomial_controls:alpha', 0.0, units='deg')\n\np.set_val('traj.climb.t_initial', 75)\np.set_val('traj.climb.t_duration', 15)\np.set_val('traj.climb.states:r', climb.interp('r', [5000, 5500.0]), units='ft')\np.set_val('traj.climb.states:v', climb.interp('v', [160, 170.0]), units='kn')\np.set_val('traj.climb.states:h', climb.interp('h', [0, 35.0]), units='ft')\np.set_val('traj.climb.states:gam', climb.interp('gam', [0, 5.0]), units='deg')\np.set_val('traj.climb.controls:alpha', 5.0, units='deg')\n\ndm.run_problem(p, run_driver=True, simulate=True)\n\nprint(p.get_val('traj.rto.states:r')[-1])\n\nsim_case = om.CaseReader('dymos_solution.db').get_case('final')\n\nfig, axes = plt.subplots(2, 1, sharex=True, gridspec_kw={'top': 0.92})\nfor phase in ['br_to_v1', 'rto', 'v1_to_vr', 'rotate', 'climb']:\n    r = sim_case.get_val(f'traj.{phase}.timeseries.states:r', units='ft')\n    v = sim_case.get_val(f'traj.{phase}.timeseries.states:v', units='kn')\n    t = sim_case.get_val(f'traj.{phase}.timeseries.time', units='s')\n    axes[0].plot(t, r, '-', label=phase)\n    axes[1].plot(t, v, '-', label=phase)\nfig.suptitle('Balanced Field Length')\naxes[1].set_xlabel('time (s)')\naxes[0].set_ylabel('range (ft)')\naxes[1].set_ylabel('airspeed (kts)')\naxes[0].grid(True)\naxes[1].grid(True)\n\ntv1 = sim_case.get_val('traj.br_to_v1.timeseries.time', units='s')[-1, 0]\nv1 = sim_case.get_val('traj.br_to_v1.timeseries.states:v', units='kn')[-1, 0]\n\ntf_rto = sim_case.get_val('traj.rto.timeseries.time', units='s')[-1, 0]\nrf_rto = sim_case.get_val('traj.rto.timeseries.states:r', units='ft')[-1, 0]\n\naxes[0].annotate(f'field length = {r[-1, 0]:5.1f} ft', xy=(t[-1, 0], r[-1, 0]),\n                 xycoords='data', xytext=(0.7, 0.5),\n                 textcoords='axes fraction', arrowprops=dict(arrowstyle='->'),\n                 horizontalalignment='center', verticalalignment='top')\n\naxes[0].annotate(f'', xy=(tf_rto, rf_rto),\n                 xycoords='data', xytext=(0.7, 0.5),\n                 textcoords='axes fraction', arrowprops=dict(arrowstyle='->'),\n                 horizontalalignment='center', verticalalignment='top')\n\naxes[1].annotate(f'$v1$ = {v1:5.1f} kts', xy=(tv1, v1), xycoords='data', xytext=(0.5, 0.5),\n                 textcoords='axes fraction', arrowprops=dict(arrowstyle='->'),\n                 horizontalalignment='center', verticalalignment='top')\n\nplt.legend()\nplt.show()\n```\n\n\n```python\nfrom openmdao.utils.assert_utils import assert_near_equal\n\nassert_near_equal(p.get_val('traj.rto.states:r')[-1], 2188.2, tolerance=0.01)\n```\n\n## References\n\n```{bibliography}\n:filter: docname in docnames\n```\n", "meta": {"hexsha": "72b45ac2053c356d333a95a330033c5d0efcaded", "size": 39019, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/dymos_book/examples/balanced_field/balanced_field.ipynb", "max_stars_repo_name": "yonghoonlee/dymos", "max_stars_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/dymos_book/examples/balanced_field/balanced_field.ipynb", "max_issues_repo_name": "yonghoonlee/dymos", "max_issues_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-05-24T15:14:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-28T21:12:55.000Z", "max_forks_repo_path": "docs/dymos_book/examples/balanced_field/balanced_field.ipynb", "max_forks_repo_name": "yonghoonlee/dymos", "max_forks_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.6124338624, "max_line_length": 189, "alphanum_fraction": 0.5245905841, "converted": true, "num_tokens": 8732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.341582499438317, "lm_q2_score": 0.07159120093018112, "lm_q1q2_score": 0.02445430135152203}}
{"text": "<a href=\"https://colab.research.google.com/github/zozo123/QC-IL/blob/master/notebooks/cirq_hello.ipynb\" target=\"_parent\"></a>\n\n\n```\n!pip install cirq\n```\n\n    Collecting cirq\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/53/29/a66c4c28306dae359745e37c4c10120e477da44cb050d06d8ceb1117a22a/cirq-0.7.0-py3-none-any.whl (1.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.2MB 4.9MB/s \n    \u001b[?25hCollecting protobuf==3.8.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/d2/fb/29de8d08967f0cce1bb10b39846d836b0f3bf6776ddc36aed7c73498ca7e/protobuf-3.8.0-cp36-cp36m-manylinux1_x86_64.whl (1.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.2MB 59.0MB/s \n    \u001b[?25hRequirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from cirq) (0.7)\n    Requirement already satisfied: matplotlib~=3.0 in /usr/local/lib/python3.6/dist-packages (from cirq) (3.1.3)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from cirq) (1.4.1)\n    Requirement already satisfied: requests~=2.18 in /usr/local/lib/python3.6/dist-packages (from cirq) (2.21.0)\n    Requirement already satisfied: google-api-python-client~=1.6 in /usr/local/lib/python3.6/dist-packages (from cirq) (1.7.11)\n    Collecting networkx==2.3\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/85/08/f20aef11d4c343b557e5de6b9548761811eb16e438cee3d32b1c66c8566b/networkx-2.3.zip (1.7MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.8MB 54.5MB/s \n    \u001b[?25hCollecting sympy==1.4\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/21/21/f4105795ca7f35c541d82c5b06be684dd2f5cb4f508fb487cd7aea4de776/sympy-1.4-py2.py3-none-any.whl (5.3MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5.3MB 50.1MB/s \n    \u001b[?25hRequirement already satisfied: sortedcontainers~=2.0 in /usr/local/lib/python3.6/dist-packages (from cirq) (2.1.0)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from cirq) (0.25.3)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.6/dist-packages (from cirq) (3.6.6)\n    Requirement already satisfied: numpy~=1.16 in /usr/local/lib/python3.6/dist-packages (from cirq) (1.17.5)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from protobuf==3.8.0->cirq) (45.2.0)\n    Requirement already satisfied: six>=1.9 in /usr/local/lib/python3.6/dist-packages (from protobuf==3.8.0->cirq) (1.12.0)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq) (2.6.1)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq) (1.1.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq) (2.4.6)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq) (0.10.0)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (2019.11.28)\n    Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (1.24.3)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (3.0.4)\n    Requirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (2.8)\n    Requirement already satisfied: httplib2<1dev,>=0.9.2 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client~=1.6->cirq) (0.11.3)\n    Requirement already satisfied: google-auth>=1.4.1 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client~=1.6->cirq) (1.7.2)\n    Requirement already satisfied: google-auth-httplib2>=0.0.3 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client~=1.6->cirq) (0.0.3)\n    Requirement already satisfied: uritemplate<4dev,>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client~=1.6->cirq) (3.0.1)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx==2.3->cirq) (4.4.1)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy==1.4->cirq) (1.1.0)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas->cirq) (2018.9)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.6/dist-packages (from google-auth>=1.4.1->google-api-python-client~=1.6->cirq) (0.2.8)\n    Requirement already satisfied: cachetools<3.2,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth>=1.4.1->google-api-python-client~=1.6->cirq) (3.1.1)\n    Requirement already satisfied: rsa<4.1,>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from google-auth>=1.4.1->google-api-python-client~=1.6->cirq) (4.0)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.6/dist-packages (from pyasn1-modules>=0.2.1->google-auth>=1.4.1->google-api-python-client~=1.6->cirq) (0.4.8)\n    Building wheels for collected packages: networkx\n      Building wheel for networkx (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for networkx: filename=networkx-2.3-py2.py3-none-any.whl size=1556408 sha256=d3ee3c13ca251200746c137efef35eece519c8d2c69901baac916d558d4f4142\n      Stored in directory: /root/.cache/pip/wheels/de/63/64/3699be2a9d0ccdb37c7f16329acf3863fd76eda58c39c737af\n    Successfully built networkx\n    \u001b[31mERROR: albumentations 0.1.12 has requirement imgaug<0.2.7,>=0.2.5, but you'll have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Installing collected packages: protobuf, networkx, sympy, cirq\n      Found existing installation: protobuf 3.10.0\n        Uninstalling protobuf-3.10.0:\n          Successfully uninstalled protobuf-3.10.0\n      Found existing installation: networkx 2.4\n        Uninstalling networkx-2.4:\n          Successfully uninstalled networkx-2.4\n      Found existing installation: sympy 1.1.1\n        Uninstalling sympy-1.1.1:\n          Successfully uninstalled sympy-1.1.1\n    Successfully installed cirq-0.7.0 networkx-2.3 protobuf-3.8.0 sympy-1.4\n\n\n\n\n\n```\nimport cirq\n```\n\n\n```\n# ref: https://colab.research.google.com/drive/1LHTDuIsb0mwVlEqbyrQ8K1rKdK6fFV7v\n# Here I'm defining a utility function to print circuits nicely using an svg\nfrom cirq.contrib.svg import circuit_to_svg\nfrom IPython.display import SVG, display\nimport os\n\nq0, q1 = cirq.GridQubit.rect(1, 2)\nmy_circuit = cirq.Circuit(cirq.H(q0), cirq.CNOT(q0, q1))\n\ndef circuit_print(circuit):\n  \"\"\"Convert the cirq.Circuit to a temp svg and display + garbage collect.\"\"\"\n  with open(\"temp.svg\", 'w+') as f:\n    f.write(circuit_to_svg(circuit))\n  display(SVG('temp.svg'))\n  os.remove('temp.svg')\n\n# Now we can use the above-defined function anywhere in the notebook\ncircuit_print(my_circuit)\n```\n\n\n    \n\n    \n\n\n\n```\nfrom cirq.contrib import qcircuit \n# Colab doesn't support inline LaTeX compilation, but you can copy and paste\n# the printed LaTeX code to run on your own machine. Follow these instructions:\n# http://physics.unm.edu/CQuIC/Qcircuit/Qtutorial.pdf\nprint(qcircuit.circuit_to_latex_using_qcircuit(my_circuit))\n```\n\n    \\Qcircuit @R=1em @C=0.75em {\n     \\\\\n     &\\lstick{\\text{(0, 0)}}& \\qw&\\gate{\\text{H}} \\qw&\\control \\qw    &\\qw\\\\\n     &\\lstick{\\text{(0, 1)}}& \\qw&                \\qw&\\targ    \\qw\\qwx&\\qw\\\\\n     \\\\\n    }\n\n\n\n```\n\n```\n", "meta": {"hexsha": "634d5d183928e4705e655907c00b7174d4752c9c", "size": 13297, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/cirq_hello.ipynb", "max_stars_repo_name": "zozo123/QC-IL", "max_stars_repo_head_hexsha": "9f37cec0b55a13ba517b34a9878218f64158c5a1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/cirq_hello.ipynb", "max_issues_repo_name": "zozo123/QC-IL", "max_issues_repo_head_hexsha": "9f37cec0b55a13ba517b34a9878218f64158c5a1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/cirq_hello.ipynb", "max_forks_repo_name": "zozo123/QC-IL", "max_forks_repo_head_hexsha": "9f37cec0b55a13ba517b34a9878218f64158c5a1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.8247863248, "max_line_length": 1444, "alphanum_fraction": 0.5719335188, "converted": true, "num_tokens": 2591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.0558231458469803, "lm_q1q2_score": 0.024440685046287342}}
{"text": "#  Pawnee Fire analysis\n\nThe Pawnee Fire was a large wildfire that burned in Lake County, California. The fire started on June 23, 2018 and burned a total of 15,185 acres (61 km2) before it was fully contained on July 8, 2018.\n\n\n\n\n## Remote Sensing using Sentinel-2 layer\n\n\n```python\nfrom arcgis import GIS\ngis = GIS(profile='plenary_deldev_profile')\n```\n\nFor this analysis, we will be using Sentinel-2 imagery from the Living Atlas.\n\nSentinel-2 is an Earth observation mission developed by ESA as part of the Copernicus Programme to perform terrestrial observations in support of services such as forest monitoring, land cover changes detection, and natural disaster management.\n\n\n```python\nsentinel_item = gis.content.search('Sentinel-2 Views', outside_org=True)[0]\nsentinel_item\n```\n\n\n\n\n<div class=\"item_container\" style=\"height: auto; overflow: hidden; border: 1px solid #cfcfcf; border-radius: 2px; background: #f6fafa; line-height: 1.21429em; padding: 10px;\">\n                    <div class=\"item_left\" style=\"width: 210px; float: left;\">\n                       <a href='https://arcgissolutions.maps.arcgis.com/home/item.html?id=fd61b9e0c69c4e14bebd50a9a968348c' target='_blank'>\n                        \n                       </a>\n                    </div>\n\n                    <div class=\"item_right\"     style=\"float: none; width: auto; overflow: hidden;\">\n                        <a href='https://arcgissolutions.maps.arcgis.com/home/item.html?id=fd61b9e0c69c4e14bebd50a9a968348c' target='_blank'><b>Sentinel-2 Views</b>\n                        </a>\n                        <br/>Sentinel-2, 10m Multispectral, Multitemporal, 13-band images with visual renderings and indices.  This Imagery Layer is sourced from the Sentinel-2 on AWS collections and is updated daily with new imagery.  This layer is in beta release.Imagery Layer by esri\n                        <br/>Last Modified: December 19, 2018\n                        <br/>8 comments, 93,761 views\n                    </div>\n                </div>\n\n\n\n\n### Select before and after rasters\n\n\n```python\nimport arcgis\n\nsentinel = sentinel_item.layers[0]\naoi = {'spatialReference': {'latestWkid': 3857, 'wkid': 102100},\n 'xmax': -13643017.100720055,\n 'xmin': -13652113.10708598,\n 'ymax': 4739654.477447927,\n 'ymin': 4731284.622850712}\narcgis.env.analysis_extent = aoi\nsentinel.extent = aoi\n```\n\n\n```python\nimport pandas as pd\nfrom datetime import datetime\n\nselected = sentinel.filter_by(where=\"acquisitiondate BETWEEN timestamp '2018-06-15 00:00:00' AND timestamp '2018-06-24 19:59:59'\",\n                              geometry=arcgis.geometry.filters.intersects(aoi))\n\ndf = selected.query(out_fields=\"AcquisitionDate, Tile_ID, CloudCover\", order_by_fields=\"AcquisitionDate\").df\ndf['acquisitiondate'] = pd.to_datetime(df['acquisitiondate'], unit='ms')\ndf.tail(40)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>acquisitiondate</th>\n      <th>cloudcover</th>\n      <th>objectid</th>\n      <th>shape_Area</th>\n      <th>shape_Length</th>\n      <th>tile_id</th>\n      <th>SHAPE</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>2018-06-17 19:02:28</td>\n      <td>0.1070</td>\n      <td>2686387</td>\n      <td>1.214547e+10</td>\n      <td>446919.588256</td>\n      <td>20180617T224132_10SEJ_0</td>\n      <td>{'rings': [[[-13599954.1142, 4730228.964000002...</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2018-06-17 19:13:35</td>\n      <td>0.0398</td>\n      <td>2686843</td>\n      <td>4.138418e+09</td>\n      <td>271266.855576</td>\n      <td>20180618T001031_10SEJ_1</td>\n      <td>{'rings': [[[-13634891.7136, 4731760.155000001...</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2018-06-19 19:03:34</td>\n      <td>0.0273</td>\n      <td>2701464</td>\n      <td>1.089364e+10</td>\n      <td>438058.126931</td>\n      <td>20180619T190334_10SEJ_0</td>\n      <td>{'rings': [[[-13667279.6085, 4773934.774300002...</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>2018-06-22 19:04:33</td>\n      <td>0.0000</td>\n      <td>2750251</td>\n      <td>1.402370e+10</td>\n      <td>486152.331987</td>\n      <td>20180622T190432_10SEJ_0</td>\n      <td>{'rings': [[[-13596402.5766, 4745349.801899999...</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>2018-06-24 19:01:08</td>\n      <td>0.0000</td>\n      <td>2800097</td>\n      <td>1.991829e+10</td>\n      <td>560634.860343</td>\n      <td>20180624T190108_10SEJ_0</td>\n      <td>{'rings': [[[-13549971.4055, 4828395.097300000...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nprefire = sentinel.filter_by('OBJECTID=2750251') # 2017-07-01\nmidfire = sentinel.filter_by('OBJECTID=2800097') # 2017-07-24 \n```\n\n## Visual Assessment\n\n\n```python\nfrom arcgis.raster.functions import *\n\ntruecolor = apply(midfire, 'Natural Color with DRA')\ntruecolor\n```\n\n\n\n\n    \n\n    \n\n\n\n### Visualize Burn Scars\n\nExtract the [12, 11, 4] bands to improve visibility of fire and burn scars. This band combination pushes further into the SWIR range of the electromagnetic spectrum, where there is less susceptibility to smoke and haze generated by a burning fire.\n\n\n```python\nextract_band(midfire, [12,11,4])\n```\n\n\n\n\n    \n\n    \n\n\n\nFor comparison, the same area before the fire started shows no burn scar.\n\n\n```python\nextract_band(prefire, [12,11,4])\n```\n\n\n\n\n    \n\n    \n\n\n\n## Quantitative Assessment\n\nThe **Normalized Burn Ratio (NBR)** can be used to delineate the burnt areas and identify the severity of the fire. \n\nThe formula for the NBR is very similar to that of NDVI except that it uses near-infrared band 9 and the short-wave infrared band 13:\n\\begin{align}\n{\\mathbf{NBR}} = \\frac{\\mathbf{B9} - \\mathbf{B13}}{\\mathbf{B9} + \\mathbf{B13} + \\mathbf{WS}} \\\\   \n\\end{align}\n\nThe NBR equation was designed to be calcualted from reflectance, but it can be calculated from radiance and digital_number_(dn) with changes to the burn severity table below. The WS parameter is used for water suppression, and is typically 2000. \n\nFor a given area, NBR is calculated from an image just prior to the burn and a second NBR is calculated for an image immediately following the burn. Burn extent and severity is judged by taking the difference between these two index layers:\n\n\\begin{align}\n{\\Delta \\mathbf{NBR}} = \\mathbf{NBR_{prefire}} - \\mathbf{NBR_{postfire}} \\\\   \n\\end{align}\n\nThe meaning of the \u2206NBR values can vary by scene, and interpretation in specific instances should always be based on some field assessment. However, the following table from the USGS FireMon program can be useful as a first approximation for interpreting the NBR difference:\n\n\n| \\begin{align}{\\Delta \\mathbf{NBR}}  \\end{align}      | Burn Severity |\n| ------------- |:-------------:|\n| 0.1 to 0.27   | Low severity burn |\n| 0.27 to 0.44  | Medium severity burn |\n| 0.44 to 0.66 | Moderate severity burn |\n| > 0.66 | High severity burn |\n\n[Source: http://wiki.landscapetoolbox.org/doku.php/remote_sensing_methods:normalized_burn_ratio]\n\n### Use Band Arithmetic and Map Algebra \n\n\n```python\nnbr_prefire  = band_arithmetic(prefire, \"(b9 - b13) / (b9 + b13 + 2000)\")\nnbr_postfire = band_arithmetic(midfire, \"(b9 - b13) / (b9 + b13 + 2000)\")\n\nnbr_diff = nbr_prefire - nbr_postfire\n```\n\n\n```python\nburnt_areas = colormap(remap(nbr_diff, \n                             input_ranges=[0.1,  0.27,  # low severity \n                                           0.27, 0.44,  # medium severity\n                                           0.44, 0.66,  # moderate severity\n                                           0.66, 1.00], # high severity burn\n                             output_values=[1, 2, 3, 4],                    \n                             no_data_ranges=[-1, 0.1], astype='u8'), \n                       colormap=[[4, 0xFF, 0xC3, 0], [3, 0xFA, 0x8E, 0], [2, 0xF2, 0x55, 0], \n                                 [1, 0xE6, 0,    0]])\n```\n\n\n```python\nburnt_areas.draw_graph()\n```\n\n\n\n### Area calculation\n\n\n```python\npixx = (aoi['xmax'] - aoi['xmin']) / 1200.0\npixy = (aoi['ymax'] - aoi['ymin']) / 450.0\n\nres = burnt_areas.compute_histograms(aoi, pixel_size={'x':pixx, 'y':pixy})\n\nnumpix = 0\nhistogram = res['histograms'][0]['counts'][1:]\nfor i in histogram:\n    numpix += i\n```\n\n### Report burnt area\n\n\n```python\nfrom IPython.display import HTML\nsqmarea = numpix * pixx * pixy # in sq. m\nacres = 0.00024711 * sqmarea   # in acres\n\nHTML('<h3>Fire has consumed <font color=\"red\">{:,} acres</font>  till {}</h3>.' \\\n     .format(int(acres), df.iloc[-1]['acquisitiondate'].date()))\n```\n\n\n\n\n<h3>Fire has consumed <font color=\"red\">3,569 acres</font>  till 2018-06-24</h3>.\n\n\n\n\n```python\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nplt.title('Distribution by severity', y=-0.1)\nplt.pie(histogram, labels=['Low Severity', 'Medium Severity', \n                           'Moderate Severity', 'High Severity'])\nplt.axis('equal')\n```\n\n### Visualize burnt areas\n\n\n```python\nfiremap = gis.map()\nfiremap.extent = aoi\nfiremap\n```\n\n\n\n\n```python\nfiremap.add_layer([truecolor, burnt_areas])\n```\n\n## Raster to Feature layer conversion\n\nUse Raster Analytics and Geoanalytics to convert the burnt area raster to a feature layer. The `to_features()` method converts the raster to a feature layer and `create_buffers()` fills holes in the features and dissolves them to output one feature that covers the extent of the Thomas Fire.\n\n#### Access Portal\n\n\n```python\n#gis = GIS(\"https://datasciencedev.esri.com/portal\", \"rjackson\", \"admin123\", verify_cert=False)\nportal = GIS(\"https://python.playground.esri.com/portal\", \"arcgis_python\", \"amazing_arcgis_123\") \n\nfire = portal.content.search('PawneeFireArea', 'Feature Layer')[0]\nfire\n```\n\n\n\n\n<div class=\"item_container\" style=\"height: auto; overflow: hidden; border: 1px solid #cfcfcf; border-radius: 2px; background: #f6fafa; line-height: 1.21429em; padding: 10px;\">\n                    <div class=\"item_left\" style=\"width: 210px; float: left;\">\n                       <a href='https://python.playground.esri.com/portal/home/item.html?id=b1f1a2524ecb479a93601a84d0ea7629' target='_blank'>\n                        \n                       </a>\n                    </div>\n\n                    <div class=\"item_right\"     style=\"float: none; width: auto; overflow: hidden;\">\n                        <a href='https://python.playground.esri.com/portal/home/item.html?id=b1f1a2524ecb479a93601a84d0ea7629' target='_blank'><b>PawneeFireArea</b>\n                        </a>\n                        <br/>PawneeFireAreaFeature Layer Collection by arcgis_python\n                        <br/>Last Modified: October 16, 2018\n                        <br/>0 comments, 17 views\n                    </div>\n                </div>\n\n\n\n\n### Convert and Buffer Data\n\n\n```python\nfrom arcgis.geoanalytics.use_proximity import create_buffers\n\nfire_item = burnt_areas.to_features(output_name='Pawnee_Fire_boundary_output_tst')\n\nfire_layer = fire_item.layers[0]\n```\n\n\n```python\nfire = create_buffers(fire_layer, 100, 'Meters', dissolve_option='All', \n                      multipart=True, output_name='PawneeFireAreaTst')\n```\n\n## Visualize feature layer\n\n\n```python\nvectormap = gis.map()\nvectormap.basemap = 'dark-gray'\nvectormap.extent  = aoi\nvectormap.add_layer(fire)\nvectormap\n```\n\n\n\n## Impact Assessment\n\n### Assess human impact\n\n\n```python\nfrom arcgis.geoenrichment import enrich\nfrom arcgis.geometry import filters\nfrom arcgis.features import GeoAccessor, GeoSeriesAccessor\nimport pandas as pd\n```\n\n\n```python\nsdf = pd.DataFrame.spatial.from_layer(fire.layers[0])\n\ngis = GIS(profile='deldev')\n\nfire_geometry = sdf.iloc[0].SHAPE\nsa_filter = filters.intersects(geometry=fire_geometry, \n                               sr=fire_geometry['spatialReference'])\n```\n\n\n```python\ndef age_pyramid(df):\n    import warnings\n    import seaborn as sns\n    import matplotlib.pyplot as plt\n\n    %matplotlib inline\n    warnings.simplefilter(action='ignore', category=FutureWarning)\n    pd.options.mode.chained_assignment = None \n    plt.style.use('ggplot')\n\n    df = df[[x for x in impacted_people.columns if 'MALE' in x or 'FEM' in x]]\n    sf = pd.DataFrame(df.sum())\n    age = sf.index.str.extract('(\\d+)').astype('int64')\n    f = sf[sf.index.str.startswith('FEM')]\n    m = sf[sf.index.str.startswith('MALE')]\n    sf = sf.reset_index(drop = True)\n    f = f.reset_index(drop = True)\n    m = m.reset_index(drop = True)\n    sf['age'] = age\n    f[\"age\"] = age\n    m[\"age\"] = age\n    f = f.sort_values(by='age', ascending=False).set_index('age')\n    m = m.sort_values(by='age', ascending=False).set_index('age')\n    \n\n    popdf = pd.concat([f, m], axis=1)\n    popdf.columns = ['F', 'M']\n    popdf['agelabel'] = popdf.index.map(str) + ' - ' + (popdf.index+4).map(str)\n    popdf.M = -popdf.M\n    \n    sns.barplot(x=\"F\", y=\"agelabel\", color=\"#CC6699\", label=\"Female\", data=popdf, edgecolor='none')\n    sns.barplot(x=\"M\",  y=\"agelabel\", color=\"#008AB8\", label=\"Male\",   data=popdf,  edgecolor='none')\n    plt.ylabel('Age group')\n    plt.xlabel('Number of people');\n    return plt;\n```\n\n### Age Pyramid of affected population\n\n\n```python\nfrom arcgis.geoenrichment import enrich\n\nimpacted_people = enrich(sdf, 'Age')\nage_pyramid(impacted_people)\n```\n\n\n", "meta": {"hexsha": "18538d72c94e39f5168a9aa0f0b6b19c510368f7", "size": 499446, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "talks/FederalDevSummit2019/PlenaryDemos/demo 02 - RA_ML/02 - Wildfire analysis using Sentinel-2 imagery.ipynb", "max_stars_repo_name": "ChrisFrenchPDX/arcgis-python-api", "max_stars_repo_head_hexsha": "2e28ccb6ee753e5ad3f349f66cc36a4aea3aee68", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-23T23:06:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-23T23:06:07.000Z", "max_issues_repo_path": "talks/FederalDevSummit2019/PlenaryDemos/demo 02 - RA_ML/02 - Wildfire analysis using Sentinel-2 imagery.ipynb", "max_issues_repo_name": "ChrisFrenchPDX/arcgis-python-api", "max_issues_repo_head_hexsha": "2e28ccb6ee753e5ad3f349f66cc36a4aea3aee68", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "talks/FederalDevSummit2019/PlenaryDemos/demo 02 - RA_ML/02 - Wildfire analysis using Sentinel-2 imagery.ipynb", "max_forks_repo_name": "ChrisFrenchPDX/arcgis-python-api", "max_forks_repo_head_hexsha": "2e28ccb6ee753e5ad3f349f66cc36a4aea3aee68", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 613.57002457, "max_line_length": 120505, "alphanum_fraction": 0.9555287258, "converted": true, "num_tokens": 3933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577487985229833, "lm_q2_score": 0.06853748542165705, "lm_q1q2_score": 0.024383915641268687}}
{"text": "# Optimization for Medical Image Segmentation with 2D U-Net on Intel\u00ae Xeon Scalable Platform\n\n#### Agenda\n\n1. Background information introduction\n2. Intel's optimization technologies on Intel\u00ae Xeon Scalable Processors\n3. Let's do coding!\n\n### 1. Background Information Introduction\n#### 1.1 Brain MRI scan\nMagnetic resonance imaging (MRI) of the brain is a safe and painless test that uses a magnetic field and radio waves to produce detailed images of the brain and the brain stem. An MRI differs from a CAT scan (also called a CT scan or a computed axial tomography scan) because it does not use radiation.\n\nAn MRI scanner consists of a large doughnut-shaped magnet that often has a tunnel in the center. Patients are placed on a table that slides into the tunnel. Some centers have open MRI machines that have larger openings and are helpful for patients with claustrophobia. MRI machines are located in hospitals and radiology centers.\n\nDuring the exam, radio waves manipulate the magnetic position of the atoms of the body, which are picked up by a powerful antenna and sent to a computer. The computer performs millions of calculations, resulting in clear, cross-sectional black and white images of the body. These images can be converted into three-dimensional (3-D) pictures of the scanned area. This helps pinpoint problems in the brain and the brain stem when the scan focuses on those areas.\n\n**Reference:** https://kidshealth.org/en/parents/mri-brain.html\n\n<table><tr><td></td><td></td></tr></table>\n\n**Reference:** https://github.com/IntelAI/unet\n\n### 1.2 U-Net for brain images segmentation\n\nU-Net implementation in TensorFlow for FLAIR abnormality segmentation in brain MRI based on a deep learning segmentation algorithm used in [Association of genomic subtypes of lower-grade gliomas with shape features automatically extracted by a deep learning algorithm](https://doi.org/10.1016/j.compbiomed.2019.05.002).\n\n```latex\n@article{buda2019association,\n  title={Association of genomic subtypes of lower-grade gliomas with shape features automatically extracted by a deep learning algorithm},\n  author={Buda, Mateusz and Saha, Ashirbani and Mazurowski, Maciej A},\n  journal={Computers in Biology and Medicine},\n  volume={109},\n  year={2019},\n  publisher={Elsevier},\n  doi={10.1016/j.compbiomed.2019.05.002}\n}\n```\n\nTopology structured as the following:\n\n\n**Reference:** https://github.com/mateuszbuda/brain-segmentation-pytorch\n\n### 2. Intel's optimization technologies on Intel\u00ae Xeon Scalable Processors\n\nIn order to take full advantage of Intel\u00ae architecture and to extract maximum performance, the TensorFlow framework has been optimized with Intel\u00ae Math Kernel Library for Deep Neural Networks (Intel\u00ae oneDNN) primitives, a popular performance library for deep learning applications.\n\nFor more information about the optimizations as well as performance data, see the blog post:[TensorFlow Optimizations on Modern Intel\u00ae Architecture](https://software.intel.com/en-us/articles/tensorflow-optimizations-on-modern-intel-architecture).\n\nInstallation guide of Intel Optimization for TensorFlow can be found at [Intel\u00ae Optimization for TensorFlow Installation Guide](https://software.intel.com/en-us/articles/intel-optimization-for-tensorflow-installation-guide).\n\n\n#### 2.1 Optimization with TensorFlow switches\n**intra_op_parallelism_threads**\n- Number of threads in each threadpool for an operation (like matrix multiplication or reduction). \n- Recommend: #physical cores, found in Linux with \u2018lscpu\u2019 command. \n\n**inter_op_parallelism_threads**\n- Number of thread pools for independent operations.\n- Recommend: #cpu sockets,  found in Linux with \u2018lscpu\u2019 command.\n\nNote, need to test with the model & platform to find the best parameters.\n\n#### 2.2 Optimization with Intel\u00ae oneDNN switches\nIntel oneDNN utilizes OpenMP to leverage Intel architecture.\nFollowing environment variables for vectorization and multi-threading.\n\n**KMP_AFFINITY**\n- Restricts execution of certain threads to a subset of the physical processing units in a multiprocessor computer.\n- Recommend: ```export KMP_AFFINITY=granularity=fine,compact,1,0```\n\n**KMP_BLOCKTIME**\n- Set the time (milliseconds), that a thread wait for, after completing the execution of a parallel region, before sleeping. \n- Recommend: ```export KMP_BLOCKTIME=0 (or 1)```\n\n**OMP_NUM_THREADS**\n- Set maximum number of threads to use for OpenMP parallel regions\n- Recommend: ```export OMP_NUM_THREADS=num physical cores```\n\nNote, recommend users tuning these values for their specific neural network model and platform.\n\n#### 2.3 Optimization with miscellaneous configurations/tools\n**Numactl**\n- Running on a NUMA-enabled machine brings with it special considerations. NUMA or non-uniform memory access is a memory layout design used in data center machines meant to take advantage of locality of memory in multi-socket machines with multiple memory controllers and blocks. In most cases, inference runs best when confining both the execution and memory usage to a single NUMA node.\n- Recommend: ```numactl --cpunodebind=N --membind=N python <pytorch_script>```\n\n**Batch size**\n- Can increase usage and efficiency of hardware resources.\n- Optional according to your requirements.\n\nA more detailed introduction of maximizing performance with Intel Optimization for TensorFlow can be found [here](https://software.intel.com/en-us/articles/maximize-tensorflow-performance-on-cpu-considerations-and-recommendations-for-inference).\n\nhttps://software.intel.com/en-us/articles/maximize-tensorflow-performance-on-cpu-considerations-and-recommendations-for-inference\n\n### 3. Let's do coding!\n\n#### 3.0 Dataset\nWe use [brain tumor segmentation (BraTS) subset](https://drive.google.com/file/d/1A2IU8Sgea1h3fYLpYtFb2v7NYdMjvEhU/view?usp=sharing) of the [Medical Segmentation Decathlon](http://medicaldecathlon.com/) dataset. The dataset has the [Creative Commons Attribution-ShareAlike 4.0 International license](https://creativecommons.org/licenses/by-sa/4.0/).\n\nPlease follow instructions [here](https://github.com/IntelAI/unet/blob/master/2D/00_Prepare-Data.ipynb) to prepare the dataset.\n\n#### 3.1 Import required packages\n\n\n```python\n%matplotlib inline\nimport os\nimport numpy as np\nimport tensorflow as tf\nimport keras as K\nimport h5py\nimport math\nimport pandas as pd\nimport time\nimport matplotlib.pyplot as plt\nimport sys; sys.argv=['']; del sys\n\nfrom argparser import args\nfrom data import load_data\nfrom model import unet\n```\n\n#### 3.2 Check TensorFlow version, and do sanity check\n\n\n```python\nprint (\"We are using TensorFlow version\", tf.__version__,\\\n       \"with Intel(R) oneDNN\", \"enabled\" if tf.pywrap_tensorflow.IsMklEnabled() else \"disabled\",)\n```\n\n#### 3.3 Define the DICE coefficient and loss function\nThe S\u00f8rensen\u2013Dice coefficient is a statistic used for comparing the similarity of two samples. Given two sets, X and Y, it is defined as\n\n\\begin{equation}\nDice = \\frac{2|X\\cap Y|}{|X|+|Y|}\n\\end{equation}\n\n\n```python\ndef calc_dice(target, prediction, smooth=0.01):\n    \"\"\"\n    Sorensen Dice coefficient\n    \"\"\"\n    prediction = np.round(prediction)\n\n    numerator = 2.0 * np.sum(target * prediction) + smooth\n    denominator = np.sum(target) + np.sum(prediction) + smooth\n    coef = numerator / denominator\n\n    return coef\n\ndef calc_soft_dice(target, prediction, smooth=0.01):\n    \"\"\"\n    Sorensen (Soft) Dice coefficient - Don't round preictions\n    \"\"\"\n    numerator = 2.0 * np.sum(target * prediction) + smooth\n    denominator = np.sum(target) + np.sum(prediction) + smooth\n    coef = numerator / denominator\n\n    return coef\n```\n\n#### 3.4 Load images\n\n\n```python\ndata_path = os.path.join(\"../../data/decathlon/144x144/\")\ndata_filename = \"Task01_BrainTumour.h5\"\nhdf5_filename = os.path.join(data_path, data_filename)\nimgs_train, msks_train, imgs_validation, msks_validation, imgs_testing, msks_testing = load_data(hdf5_filename)\nimgs_warmup=imgs_testing[:500]\nimgs_infere=imgs_testing[500:2500]\nprint(\"Number of imgs_warmup: {}\".format(imgs_warmup.shape[0]))\nprint(\"Number of imgs_infere: {}\".format(imgs_infere.shape[0]))\n```\n\n#### 3.5 Load model\n\n\n```python\nunet_model = unet()\nmodel = unet_model.load_model(os.path.join(\"./output/unet_model_for_decathlon.hdf5\"))\n```\n\n#### 3.6 Define function to inference on input images and plot results out\n\n\n```python\ndef plot_results(model, imgs_validation, msks_validation, img_no):\n    img = imgs_validation[idx:idx+1]\n    msk = msks_validation[idx:idx+1]\n    \n    pred_mask = model.predict(img, verbose=1, steps=None)\n\n    plt.figure(figsize=(15, 15))\n    plt.subplot(1, 3, 1)\n    plt.imshow(img[0, :, :, 0], cmap=\"bone\", origin=\"lower\")\n    plt.axis(\"off\")\n    plt.title(\"MRI Input\", fontsize=20)\n    plt.subplot(1, 3, 2)\n    plt.imshow(msk[0, :, :, 0], origin=\"lower\")\n    plt.axis(\"off\")\n    plt.title(\"Ground truth\", fontsize=20)\n    plt.subplot(1, 3, 3)\n    plt.imshow(pred_mask[0, :, :, 0], origin=\"lower\")\n    plt.axis(\"off\")\n    plt.title(\"Prediction\\nDice = {:.4f}\".format(calc_dice(pred_mask, msk)), fontsize=20)\n    plt.tight_layout()\n```\n\n#### 3.7 Run inference and plot\n\n\n```python\nindicies_validation = [40, 63, 43, 55, 99]\nfor idx in indicies_validation:\n    plot_results(model, imgs_validation, msks_validation, idx)\n```\n\n#### 3.8 Demo of 2D U-Net inference optimization\n\nSee demo in console.\n\n*Performance results:*\n- Latency\n  - Time spent for processing 1 image.\n  - Unit: millisecond per frame (ms/f)\n- Throughput\n  - Number of processed images in 1 second.\n  - Unit: frames per second (f/s)\n\n*Runs:*\n- Single stream\n  - Batch size 1\n    - Without numactl\n      - Default configuration\n      - Configuration with optimization\n    - With numactl\n      - Default configuration\n      - Configuration with optimization\n  - Batch size 128\n    - With numactl\n      - Default configuration\n      - Configuration with optimization\n- Multiple streams\n  - Batch size 128\n    - Configuration with optimization\n      - 2 streams\n      - 4 streams\n      - 8 streams\n\n##### 3.8.1 Configuration with optimization & numactl\n\n\n```python\ndef plot_perf(x_labels, latencys, throughputs, xlabel, batch_size):\n    x = np.arange(len(x_labels))\n    plt.figure(figsize=(16,6))\n    plt.subplot(121)\n    ax1 = plt.gca()\n    ax1.bar(x, latencys, width=0.3)\n    ax1.set_title('Latency (batch size: {}, the less the better)'.format(batch_size))\n    ax1.set_xlabel(xlabel)\n    ax1.set_ylabel('Latency (ms)')\n    ax1.set_xticks(x)\n    ax1.set_xticklabels(x_labels)\n    for rect, label in zip(ax1.patches, latencys):\n        height = rect.get_height()\n        ax1.text(rect.get_x() + rect.get_width() / 2, height, label, ha='center', va='bottom')\n\n    plt.subplot(122)\n    ax2 = plt.gca()\n    ax2.bar(x, throughputs, color='tab:green', width=0.3)\n    ax2.set_title('Throughput (batch size: {}, the larger the better)'.format(batch_size))\n    ax2.set_xlabel(xlabel)\n    ax2.set_ylabel('Through (fps)')\n    ax2.set_xticks(x)\n    ax2.set_xticklabels(x_labels)\n    for rect, label in zip(ax2.patches, throughputs):\n        height = rect.get_height()\n        ax2.text(rect.get_x() + rect.get_width() / 2, height, label, ha='center', va='bottom')\n\n    plt.show()\n```\n\n\n```python\n# load result performance data\nrsts = []\nwith open('04_rst_opt_numa.csv', 'r') as f:\n    for line in f.readlines():\n        rst = line.strip().split(',')\n        rsts.append(rst)\n```\n\n\n```python\n# batch size: 1\nx_labels = ['default conf', 'conf with optmization', 'conf with opt + numactl']\nlatencys_conf_1 = [float(rsts[1][2]), float(rsts[2][2]), float(rsts[3][2])]\nthroughputs_conf_1 = [float(rsts[1][3]), float(rsts[2][3]), float(rsts[3][3])]\nplot_perf(x_labels, latencys_conf_1, throughputs_conf_1, 'Configuration', 1)\n```\n\n\n```python\n# batch size: 128\nx_labels = ['default conf', 'conf with optmization', 'conf with opt + numactl']\nlatencys_conf_128 = [float(rsts[4][2]), float(rsts[5][2]), float(rsts[6][2])]\nthroughputs_conf_128 = [float(rsts[4][3]), float(rsts[5][3]), float(rsts[6][3])]\nplot_perf(x_labels, latencys_conf_128, throughputs_conf_128, 'Configuration', 128)\n```\n\n##### 3.8.2 number of streams\n\n\n```python\n# load result performance data\nrsts = []\nwith open('04_rst_instances.csv', 'r') as f:\n    for line in f.readlines():\n        rst = line.strip().split(',')\n        rsts.append(rst)\n```\n\n\n```python\n# batch size: 1\nx_labels = [1, 2, 4, 8]\nlatencys_stream_1 = [float(rsts[1][2]), float(rsts[3][2]), float(rsts[4][2]), float(rsts[5][2])]\nthroughputs_stream_1 = [float(rsts[1][3]), float(rsts[3][3]), float(rsts[4][3]), float(rsts[5][3])]\nplot_perf(x_labels, latencys_stream_1, throughputs_stream_1, 'Number of streams', 1)\n```\n\n\n```python\n# batch size: 128\nx_labels = [1, 2, 4, 8]\nlatencys_stream_128 = [float(rsts[2][2]), float(rsts[6][2]), float(rsts[7][2]), float(rsts[8][2])]\nthroughputs_stream_128 = [float(rsts[2][3]), float(rsts[6][3]), float(rsts[7][3]), float(rsts[8][3])]\nplot_perf(x_labels, latencys_stream_128, throughputs_stream_128, 'Number of streams', 128)\n```\n\n### 4. Summary\n\n\n```python\ndef plot_summary(x_labels, y_labels, xlabel, ylabel, title, color):\n    x = np.arange(len(x_labels))\n    plt.figure(figsize=(16,6))\n    ax = plt.gca()\n    ax.bar(x, y_labels, color=color, width=0.3)\n    ax.set_title(title)\n    ax.set_xlabel(xlabel)\n    ax.set_ylabel(ylabel)\n    ax.set_xticks(x)\n    ax.set_xticklabels(x_labels)\n    for rect, label in zip(ax.patches, y_labels):\n        height = rect.get_height()\n        ax.text(rect.get_x() + rect.get_width() / 2, height, label, ha='center', va='bottom')\n    plt.show()\n```\n\n#### 4.0 Scenarios:\n1. You need to get the inference result as soon as possible. (Online processing)\n2. You need to process a large bunch of data in a certain period. (Offline processing)\n\n#### 4.1 Online processing\n\nFrom **latency** perspective point of view.\n\n\\* Run 1 stream processing 1 image/frame on 1 socket with configuration with optimization\n\n\n```python\nx_labels = ['default conf,\\nbs=1, stream=1', 'conf with optmization,\\nbs=1, stream=1', 'conf with opt + numactl,\\nbs=1, stream=1', 'conf with opt + numactl,\\nbs=1, stream=2', 'conf with opt + numactl,\\nbs=1, stream=4']\nx = np.arange(len(x_labels))\nlatencys_summary = [latencys_conf_1[0], latencys_conf_1[1], latencys_conf_1[2], latencys_stream_1[1], latencys_stream_1[2]]\nplot_summary(x_labels, latencys_summary, 'Configuration', 'Latency (ms)', 'Latency with different configurations (the less the better)', 'tab:blue')\n\nprint('Number of sockets: 2')\n```\n\n#### 4.2 Offline processing\n\nFrom **throughput** perspective point of view.\n\n\\* Run multiple streams processing a batch of images/frames on all sockets with configuration with optimization\n\n\n```python\nx_labels = ['conf with opt + numactl,\\nbs=1, stream=1', 'conf with opt + numactl,\\nbs=128, stream=1', 'conf with opt + numactl,\\nbs=128, stream=4', 'conf with opt + numactl,\\nbs=128, stream=8']\nx = np.arange(len(x_labels))\nthroughputs_summary = [throughputs_conf_1[2], throughputs_conf_128[2], throughputs_stream_128[1], throughputs_stream_128[2]]\nplot_summary(x_labels, throughputs_summary, 'Configuration', 'Throughput (fps)', 'Throughput with different configurations (the larger the better)', 'tab:green')\n\nprint('Number of sockets: 2')\n```\n\n**The optimization methods in this course are not the best.**\n\n**All optimization methods should be adjusted based on test result. It depends on the detailed model, dataset, HardWare & user case.**\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n   http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nSPDX-License-Identifier: EPL-2.0\n\n", "meta": {"hexsha": "ee5777379bb40b914a9485fe1db40af1e8cf0c6e", "size": 23013, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "2D/04_Inference.ipynb", "max_stars_repo_name": "jingxu10/medical-decathlon", "max_stars_repo_head_hexsha": "711dba6acb1bfb8bac88b4936980bd21b45995bd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2D/04_Inference.ipynb", "max_issues_repo_name": "jingxu10/medical-decathlon", "max_issues_repo_head_hexsha": "711dba6acb1bfb8bac88b4936980bd21b45995bd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2D/04_Inference.ipynb", "max_forks_repo_name": "jingxu10/medical-decathlon", "max_forks_repo_head_hexsha": "711dba6acb1bfb8bac88b4936980bd21b45995bd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7619808307, "max_line_length": 470, "alphanum_fraction": 0.6043975144, "converted": true, "num_tokens": 4217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.05033063687090299, "lm_q1q2_score": 0.02437915812924229}}
{"text": "```python\n%run src/init_notebooks.py\ncheck_notebook()\nhide_toggle()\n```\n\n# Umbrella sampling\n\n## Questions this tutorial will address\n* How can I get insight faster than with plain molecular dynamics?\n* What problems can umbrella sampling help with?\n* How should I design and set up umbrella sampling simulations? \n\n## Metadata\n\nVersion: 1.0\nContributions: Dr Mark Abraham, Dr Christian Blau\nSupported by: ENCCS (https://enccs.se/), BioExcel (https://bioexcel.eu/)\n\n## Target audience\n\nThe content of this tutorial suits experienced users of GROMACS.\nSuch users should be familiar with basic theory behind MD simulations, along with setting them up and running them in GROMACS.\n\n## Prerequisites\n \n* GROMACS 2020.x (other versions will likely work, but might look a bit different)\n\n### Optional\n\n* a molecular viewer, e.g. VMD \n* a plotting tool, e.g. xmgrace\n\n## What is umbrella sampling?\n\nMany modelling problems require sampling transitions between coarse states.\nIn principle, molecular dynamics simulations will eventually undertake those transitions often enough that insight into paths, barrier sizes, and rates can be gained.\nBut that is extremely inefficient.\nWe would often like to be able to guide or *pull* the sampling to where we need it.\n\n### Example: membrane permeation\n\n\n*The permeability of skin to drugs can be estimated by pulling a drug (in the center) across the bilayers that remain after skin cells dry.*\n\n### Example: host-guest binding\n\n\n*Host-guest systems model ligands binding to biomacromolecules.\nThe free-energy of binding can be estimated by pulling the blue guest away from the wireframe host.*\n\n### Pathways for pulling\n\nGiven an initial guess at a pathway, it is much more efficient to bias the sampling to places that lie on that pathway.\nThe system is allowed to explore the equilibrium state described by the normal molecular potential plus the bias.\nThe observed frequencies of configurations can then be re-weighted to remove the effect of the bias.\nThe resulting unbiased samples can be used to get insight into e.g. changes in free energy along the pathway.\n\nIn the above examples, simple paths for pulling would lie in the horizontal direction, between centers of mass of different groups.\nSometimes simple paths do not exist and need to be composed piece-wise.\n\n\n## Model system for this tutorial\n\nIn this tutorial, we will use a simple system that needs only moderate resources to sample.\nNevertheless, it captures a lot of the essential complexity that characterizes real problems.\nWe will use umbrella sampling, also known as pulling, to examine the free-energy profile of bringing two pyrimidine molecules together in an aqueous solution.\n\n\n*A single molecule of pyrimidine*\n\nWe want to estimate the free energy of binding of two such molecules, and make any observations that we can about the pathway of binding.\nFor the path, or *reaction coordinate* we will choose the vector that joins the center of mass of two pyrimidine molecules.\nWe will run simulations along that pathway to understand the conformations that are adopted there.\nTo locate the free-energy minimum of any bound conformation we will need to bring them quite close together (ie. < 1 nm) and also quite far apart.\n\n## Quiz\n\nHow far apart do we need to take the molecules in order to estimate the free energy of binding?\n\n* Infinitely far\n* 1 nm\n* 5 nm\n* It depends\n\n## Sampling a reaction coordinate\n\nIdeally, we would run just one simulation in the bound state and one in the free state.\nThey would both happen to visit similar conformations, and we could compute the free energy of the transition between bound and free states directly.\n\nThis is possible to do, but rarely efficient.\nInstead we run many simulations, each at different positions along the reaction coordinate.\nWe try to choose the points close enough together that some of the sampling at each point will be of configurations that are also close to adjacent points along the path.\nIf successful, this means that we can estimate the free-energy difference of going from one point to another.\nDoing that pairwise estimation along the whole pathway means we can estimate the free-energy difference of the whole pathway.\nRemember that free energy differences are independent of the path taken between the states!\n\n\n*A series of displacements (shown in dark red) along a reaction coordinate are chosen to create a series of simulations whose configuration ensembles overlap those of adjacent simulations.*\n\n\n## Quiz\n\nWhat would happen if the displacements are chosen too far apart?\n\n* The overall computation would be more efficient\n* The overall computation would be less efficient\n* The result would be more likely to be correct\n* The result would be less likely to be correct\n\n## The biasing potential\n\nOnce the reaction coordinate and sampling locations are chosen, a very common choice of biasing potential is harmonic in the displacement along that coordinate.\nThe shape of an harmonic potential is like an upside-down umbrella, which is how one name for this enhanced-sampling method came about!\n\nOne simulation is run at each single location along the reaction coordinate, and during the simulation if the system diffuses away from that location it experiences a force that tends to return it to that location.\nIn this tutorial, we will measure the displacement between the center of mass of each molecule.\nDuring the simulation, any force on the center of mass due to the bias is distributed to the particles according to their mass.\n\n\n*Schematic illustration of four simulations of the same system used as part of an umbrella sampling study.\nEach simulation has a different harmonic \"umbrella\" potential (shown in green) that keeps it near its chosen displacement along the reaction coordinate (shown in dark red).\nThe umbrella displacements and widths are carefully chosen so that the resulting configurational ensemble (blue) for each simulation overlaps those of adjacent simulations.*\n\n\n*Two Gaussian distributions that overlap are shown.\nHow much the distributions sampled by your biased simulations should overlap depends.\nToo much and you will be running more simulations than you need to.\nToo little and your free-energy profile will be inaccurate.*\n\n## Quiz\n\nWhat would happen if the harmonic potentials are too \"stiff\" ie. narrow in shape?\n\n* The overall computation would be more efficient\n* The overall computation would be less efficient\n* The result would be more likely to be correct\n* The result would be less likely to be correct\n\n## Planning for an umbrella sampling simulation\n\nIn order to do umbrella sampling, a simulation must be equilibrated at each location on the reaction coordinate, with the umbrella potential active.\nThis can be tricky, because it is often not a simple case of \"click and drag!\" \n\nSometimes it is enough to start from either a bound or free configuration near one of the desired reaction coordinate points, and equilibrate to it.\nThe endpoint of that equilibration might be used to start the next equilibration at an adjacent location.\nIf the locations have been chosen well, this will work fine, because the adjacent location will sample nearby configurations that can be reached easily.\nHowever, it means that the last simulation in the series won't start until all the other equilibrations have completed.\n\nAn alternative is to run \"steered molecular dynamics\" to do a non-equilbrium trajectory that is forced to move along the reaction coordinate.\nFrom that trajectory we can pick suitable configurations to start the equilibration at each location along the reaction coordinate.\nIn GROMACS, this is called \"constant-force pulling.\"\n\nAnother alternative is \"interactive molecular dynamics\" where the user can link visualization software to a running simulation and choose where to apply forces to effect transitions.\nThis can help to provide insight into possible reaction coordinates, as well as where to sample along them.\n\n### Discussion\n\nAll these approaches can introduce a *path dependence* into the configurations chosen to begin the equilibration. This might be a significant risk in a real scientific investigation. How might this be mitigated?\n\n\n## System preparation for this tutorial\n\nFor this tutorial, 24 systems have been prepared in advance using the first method described above.\nThis will help us focus on the mechanics of umbrella sampling, rather than details of solvating and choosing box sizes that are common to all simulations.\n\nHowever, we should now look at those mechanics!\n\n## GROMACS .mdp options for pulling\n\nUsing functionality in GROMACS requires setting appropriate options in the ``.mdp`` file.\nThe ones we'll use will let the simulation know that pulling will take place, as well as describe the reaction coordinate(s) and bias(es).\nGROMACS typically uses *pull groups* and *pull geometries* to define *pull coordinates* (ie reaction coordinate).\nIn the example in this tutorial, we will use one pull group for each pyrimidine molecule.\nThe distances betwen the centers of mass of those groups will define the single pull coordinate.\n\n\n\nTogether, the ``.mdp`` lines for the above pulling setup are:\n\n```\npull                     = yes\npull-ngroups             = 2\npull-group1-name         = pyrimidine_1\npull-group2-name         = pyrimidine_2\npull-ncoords             = 1\npull-coord1-groups       = 1 2\npull-coord1-geometry     = distance\n```\n\nAs with other kinds of groups in GROMACS (e.g. temperature-coupling groups), the pull groups are described by *index groups* in the *index file* also supplied to ``gmx grompp`` (typically named ``index.ndx``). \n\nTo use umbrella sampling, we describe that as the ``pull-coord-type`` and choose a width for the harmonic potential ``pull-coord-k``.\nIn this tutorial, the umbrella will not move so has a zero ``pull-coord-rate``.\nFinally, each system we prepare will have a fixed location chosen for the umbrella along the reaction coordinate, here 0.834 nm.\n\n```\npull-coord1-type         = umbrella\npull-coord1-k            = 5000.0\npull-coord1-rate         = 0.0\npull-coord1-init         = 0.834\n```\n\nThese and many other ``.mdp`` options for pulling are described more full in [the documentation](http://manual.gromacs.org/2020.4/user-guide/mdp-options.html#com-pulling).\n\nLet us look at one of the ``grompp.mdp`` run input files:\n\n\n```python\n%less sampling/run-08/grompp.mdp\n```\n\nHere we can see a very normal production simulation of 5 ns, using the above-mentioned pull-code options.\n\nWhat range of initial reaction coordinate locations was chosen over the set of simulations?\n(Remember the default unit for distance is nm.)\n\n\n```python\n! grep pull-coord1-init sampling/run-*/grompp.mdp\n```\n\n### Quiz\n\nDoes that range seem suitable?\n* Yes\n* No, too many short distances\n* No, not enough short distances\n* No, too many long distances\n* No, not enough long distances\n\nWhat differences exist between these run input files? Let's look at two adjacent ones:\n\n\n```python\n! diff sampling/run-08/grompp.mdp sampling/run-09/grompp.mdp\n```\n\nWhat is in the simulation topology?\n\n\n```python\n%less sampling/run-08/topol.top\n```\n\nHow are the index groups set up for the pull groups? Remember, the order of atoms in the coordinate file ``conf.gro`` matches the order implied by the ``[ molecules ]`` section above.\n\n\n```python\n! head -n 10 sampling/run-08/index.ndx\n```\n\nFinally, let's visualize one of the systems:\n\n\n```python\nnv.show_structure_file('sampling/run-08/conf.gro')\n\n```\n\n## Running ``gmx grompp``\n\nIf you have GROMACS installed, then you can go ahead and run ``gmx grompp -n`` in each of the ``sampling/run-*`` directories.\nWe'll need the ``.tpr`` files later for the analysis, so we'll go ahead and use a bash loop to do that now:\n\n\n```bash\n%%bash\nfor run_directory in sampling/run-*\ndo\n  (cd $run_directory; gmx grompp -n)\ndone\n```\n\n## Running ``gmx mdrun``\n\nThese are quite small systems, but we have a lot of them, so we won't try to run them together now. Even if you have a GPU, the set of them will take 10-20 hours to run. If you did run them, then an efficient approach on a cluster would be to use `mpiexec -np 24 gmx_mpi mdrun -multidir sampling/run*`. Alternatively, you could run them one by one with:\n\n```\n(for run_directory in sampling/run-*; \\\n do \\\n   (cd $run_directory; gmx mdrun) \\\n done)\n```\n\nIn each directory, this command produces the usual ``.log``, ``.xtc``, ``.edr``, and ``.cpt`` files together with two other output files, namely ``pullx.xvg`` and ``pullf.xvg``. Respectively, these contain the time series for that simulation of the distance along the reaction coordinate, and the resulting scalar force that biases the simulation back towards the ``pull-coord-init`` distance value.\n\n## Analysing pulling simulations with WHAM\n\nGROMACS provides a tool called ``gmx wham`` that executes the *Weighted Histogram Analysis Method* (WHAM).\nWe will use it to analyse the biased sampling along the reaction coordinate $\\xi$, reweight those samples, and combine the sampling along the reaction coordinate to return a free-energy profile along $\\xi$.\nThat profile is also known as a *potential of mean force* for historical reasons.\n\nThe free energy profile we seek, $A(\\xi)$ is related to the probability $P(\\xi)$ of finding configurations at different points on the reaction coordinate $\\xi$:\n\\begin{equation}\nA(\\xi) = \u2212k_\\beta T \\mathrm{ln} P(\\xi)\n\\end{equation}\n$T$ is the temperature of our simulation, and $k_\\beta$ is Boltzmann'\\s constant.\n\nHowever we don't have time to wait for enough sampling to compute $P(\\xi)$ directly.\nInstead, we have run our series of biased simulations (indexed with $i$ from 1 to $N_w$), with added umbrella potentials $V_i(x)$.\nThese produced a set of biased probability distributions $P_i^\\mathrm{bias}(\\xi)$.\nWe'd like to use those to estimate the unbiased free energy $A_i(\\xi)$ based on simulation $i$ by removing the umbrella potential $V_i(\\xi)$ and the free-energy contribution from that bias, $F_i$, after the fact:\n\\begin{equation}\nA_i(\\xi) = \u2212k_\\beta T \\mathrm{ln} P_i^\\mathrm{bias}(\\xi) - V_i(\\xi) + F_i\n\\end{equation}\nSadly, the values of $F_i$ *depend* on the bias, so there is no easy solution.\n\nTo get the most reliable estimate for $P(\\xi)$ we want to combine the information from all the biased simulations.\n\\begin{equation}\nP(\\xi) = \\Sigma_{i=1}^{N_w} w_i P_i^\\mathrm{bias}(\\xi)\n\\end{equation}\nThere exists a statistically optimal way to determine the weights $w_i$, but going through the derivation is out of scope for this course.\nPlease check out https://doi.org/10.1002/jcc.540130812 to see the details!\n\nThe resulting set of $N_w + 1$ WHAM equations are\n\\begin{equation}\nP(\\xi) = \\frac{ \\Sigma_{i=1}^{N_w} h_i(\\xi) } { \\Sigma_{j=1}^{N_w} n_j \\exp ( -\\beta V_j(\\xi) + F_j )}\n\\end{equation}\n\\begin{equation}\n\\exp (F_i) = \\int d\\xi P(\\xi) \\exp(-\\beta V_i(\\xi) )\n\\end{equation}\nwhere $h_i(\\xi)$ is the histogram count from simulation $i$ observed at reaction coordinate $\\xi$, $n_i$ is the count of total observations from simulation $i$, and $\\beta=\\frac{1}{k_\\beta T}$.\nIn practice, this requires choosing a range of $\\xi$ over which to plot a histogram, and a number of bins into which to divide the histogram.\n\nThere are multiple unknowns, namely $P(\\xi)$ and $F_i$.\nIn such cases, one often resorts to an iterative solution.\nWe guess part of the solution and updating the guess until we find values that are *self-consistent* with all the available information.\nIn general, that would be difficult for WHAM.\nHowever, if the simulations overlap sufficiently and have adequate sampling, we know that they should mutually agree on the value of $P(\\xi)$ in the region where they overlap.\nThis means the iteration to find self-consistency has a decent chance to succeed.\n\nIt often works well to make a  first guess of a flat free-energy profile, ie. $F_i = 0$ for all $i$.\nThereafter, one can compute $P(\\xi)$, then update $F_i$, etc. until the values stop changing.\nThen they are said to be self consistent.\n\nNote that the above equations are simplified in several ways.\nProperly, one should compute the autocorrelation time of the observations and reweight them accordingly.\nHowever, in practice these times are normally the same across all $i$ simulations.\n(A notable exception is phase transitions.)\nWe have assumed that the bias potential depends only on $\\xi$, that all simulations have a common temperature, and that it is necessary to construct a histogram.\nMuch research has gone into generalizations and improvements to umbrella simulation and WHAM protocols, and some links and further reading are found below.\n\n## Analysing our pulling simulations\n\nThe sampling along the reaction coordinate is recorded in the ``pullx.xvg`` files created by ``gmx mdrun``.\nThe bias force experienced there is computed by ``gmx wham`` based on the information in the corresponding ``topol.tpr`` file.\nWe provide will ``gmx wham`` with two lists of files, respectively of ``pullx.xvg`` and ``topol.tpr`` files.\nThe order of the simulations within the lists does not matter, but the pair of files for each simulation must be in matching places in the two lists.\nThat's how ``gmx wham`` is able to match the observed distances with the expected bias.\n\nFor this tutorial, those files have been provided for you, so let's construct the lists of those files:\n\n\n```python\n! ls -1 analysis/run-*/pullx.xvg > pullx.dat; cat pullx.dat; ls -1 sampling/run-*/topol.tpr > tpr.dat; cat tpr.dat\n```\n\nLet's go ahead and run ``gmx wham`` with those inputs!\nIn additional to the terminal output, it produces two output files that we can plot.\n\n\n```python\nrun_command('gmx wham -it tpr.dat -ix pullx')\nmetadata, data = parse_xvg(\"profile.xvg\")\nplot_data(data, metadata)\n```\n\nBy default, ``gmx wham`` will observe the range of sampled reaction coordinate values and decide the range over which it will put samples into histograms to compute the free energy.\nIt reports that it ``Determined boundaries to 0.289226 and 2.399760``\n\n### Quiz\n\nIs that reasonable, given the range of ``pull-coord-init`` we prepared and checked above?\n\n* We can't know\n* No\n* Yes\n\nEarlier in the output, it reports\n\n```\nWarning, poor sampling bin 198 (z=2.38393). Check your histograms!\nWarning, poor sampling bin 199 (z=2.39448). Check your histograms!\n```\n\nso it looks like the automatic range detection might be too ambitious. Scroll down in the output above to see the plot of the histogram, and let's see how it looks.\n\nThe free energy required to be at each location on the reaction coordinate is estimated.\nIt doesn't look too bad, e.g. no sharp spike at large distances.\nBut from the above warnings, the sampling at large distances is suspect, so let's be more conservative.\nWe'll set the minimum and maximum extent of the histograms manually.\nIt's also convenient to set the zero of the free energy to be at large distances in this case, as that is intended to approximately model a pair of infinitely separated pyrimidine modules.\n\n\n```python\nrun_command('gmx wham -it tpr.dat -ix pullx -min 0.288 -max 2.35 -zprof0 2.35')\nmetadata, data = parse_xvg(\"profile.xvg\")\nplot_data(data, metadata)\n```\n\nNo warning this time!\n\nNow we can see easily that we probably haven't chosen simulations for which the reaction coordinate far enough away to properly reach the asymptote we expect at large distances.\nThe free energy grows slowly to a peak around 0.7 nm, reaches a trough as the pyrimidines get closer, and then spikes hard as the centers of mass get so close that van der Waals' repulsions dominate.\n\n### Discussion - think for a minute, then write in the hackmd document\n\nWhat do you think is happening around 0.5 nm?\nWhat do you think is happening when the solutes are 0.7 nm apart?\n\nLet's investigate by taking a look at the initial configuration taken from 0.5 nm.\nIn a real situation, you would consider the whole trajectory, but the initial configuration is enough for this tutorial.\n\n\n```python\nview = nv.show_structure_file('sampling/run-05/conf.gro')\nview\n\n```\n\nModify the line above to inspect the initial conditional also for 0.7 nm (in run-07 folder).\nCan you see anything to confirm your hypotheses?\n\n## Sampling overlap\n\nA successful umbrella sampling simulation requires that the simulations subject to the umbrellas produce configurations that overlap with those sampled by adjacent simulations.\nThe ``gmx wham`` tool also prints out a convenient plot (named ``histo.xvg`` by default) that provides clues whether that has happened.\nThe extent of the overlap suggests whether sufficient overlap exists. Let's see that in action:\n\n\n```python\nmetadata, data = parse_xvg(\"histo.xvg\")\nplot_data(data, metadata)\n```\n\nIt is clear that the distributions described by the simulations do overlap.\nIf they did not overlap enough, then adding another simulation at intermediate point(s) in reaction-coordinate space would improve the results.\n\n## Was there enough sampling?\n\nThis perennial question in MD often doesn't have a good answer.\nIf the converged simulation never found a relevant part of configuration space, then just running more simulation is unlikely to help you.\nIf we hadn't sampled this system enough, we'd run into problems making a histogram.\nLet's use the functionality of ``gmx wham`` to look only at the first two nanoseconds of data, to see the kind of problems we might run into:\n\n\n```python\nrun_command('gmx wham -it tpr.dat -ix pullx.dat -b 0 -e 2 -bins 50')\nmetadata, data = parse_xvg(\"profile.xvg\")\nplot_data(data, metadata)\nmetadata, data = parse_xvg(\"histo.xvg\")\nplot_data(data, metadata)\n```\n\nHere we see that despite reasonable overlap of the limited sampling, the PMF produced has spiky artefacts.\nThat suggests the total sampling is too low, and particularly so in the region of the artefacts (in this case, that means everywhere).\nIf you would see this in a real simulation study, now you know what to do.\n\n## What happens if the reaction coordinate is too widely spaced?\n\nSometimes an initial guess for reaction-coordinate spacing is too conservative.\nIn such cases, the overlap between simulations is too low.\nThe iterative process that solves the WHAM equations will definitely fail for lack of data in such regions.\nThis is sometimes clearly seen in the profile it produces.\nHere, we will use the ``bash`` tool called ``seq`` to help us omit every second simulation from the sampling to observe the kind of effect that can be seen:\n\n\n```bash\n%%bash\nrm -f pullx.dat tpr.dat\nfor index in $(seq -w 0 2 23)\ndo\n  echo \"analysis/run-$index/pullx.xvg\" >> pullx.dat\n  echo \"sampling/run-$index/topol.tpr\" >> tpr.dat\ndone\n```\n\n\n```python\nrun_command('gmx wham -it tpr.dat -ix pullx.dat')\nmetadata, data = parse_xvg(\"profile.xvg\")\nplot_data(data, metadata)\nmetadata, data = parse_xvg(\"histo.xvg\")\nplot_data(data, metadata)\n```\n\nNote again that warnings were seen, and the artifacts had a suggestive regularity, because the missing regions were regularly spaced.\nThat regularity is itself an artifact of our choice to space the simulations evenly in reaction-coordinate space.\nIf the spacing between simulations had been refined already, then you will need to consider carefully where artefacts from lack of sampling overlap might exist.\nOverlaying the locations of the target locations in configuration space can be helpful here.\n\n## Other possible artefacts\n\nAs with all methods that require choosing a reaction coordinate, if the choice does not capture essential features of the landscape, then the conclusions are unlikely to be correct.\nExploratory studies are often needed to provide the insight to choose these reaction coordinates.\nOften in real work with biomolecular systems, a process including multiple coordinate stages is needed.\nFor example, one reaction coordinate might open a pocket, then another might guide a ligand into the pocket.\n\n## Further reading about WHAM, ``gmx wham``, and alternatives\n\nThere is a lot more functionality in ``gmx wham`` than we have covered, including bootstrapped error estimates. See https://doi.org/10.1021/ct100494z for details.\n\nThe WHAM technique is widely used across the field of molecular simulations, not just for umbrella sampling.\nIt has its own page at [the alchemistry.org wiki](http://www.alchemistry.org/wiki/Weighted_Histogram_Analysis_Method)\nMany different implementations exist, and if you have any doubt about the numerical quality of any of them, you should definitely check against another implementation.\nFor example, this [open-source implementation](http://membrane.urmc.rochester.edu/?page_id=126) produces good results.\n\nWHAM is part of a family of related methods that include BAR and MBAR.\nIn particular, MBAR can be seen as a generalization of WHAM.\nIt also frees the user from having to choose a histogram range, which is both convenient and statistically sound. \nThe [alchemistry.org wiki](http://www.alchemistry.org/wiki/Multistate_Bennett_Acceptance_Ratio) contains more information for you.\nAn [open-source implementation of MBAR](https://github.com/choderalab/pymbar) is recommended.\n\n\n## Closing thoughts\n\nThere are many alternative kinds of pulling available in GROMACS.\nThese include alternative coordinate types, e.g. angles, as well as pulling ``geometries``.\nDo check out [the documentation](http://manual.gromacs.org/2020.4/user-guide/mdp-options.html#com-pulling) and consider if you need those capabilities for your simulation problems!\n\n## Other resources\n\n* Prof Justin Lemkul's excellent [MD tutorial on umbrella sampling](http://www.mdtutorials.com/gmx/umbrella/index.html)\n* The [alchemistry.org wiki]()\n* Some example publications using umbrella sampling [here](https://doi.org/10.1021/jp9110794), [here](https://doi.org/10.1021/ja211929h), and [here](https://doi.org/10.1007/s10822-016-9970-8).\n\n", "meta": {"hexsha": "6381dbc728e3ff01232f99f457100c7197336392", "size": 35300, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorial.ipynb", "max_stars_repo_name": "ENCCS/umbrella-sampling-tutorial-test", "max_stars_repo_head_hexsha": "90f3bf7ef6267b992aed58892d95af9bdfe17ca2", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorial.ipynb", "max_issues_repo_name": "ENCCS/umbrella-sampling-tutorial-test", "max_issues_repo_head_hexsha": "90f3bf7ef6267b992aed58892d95af9bdfe17ca2", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorial.ipynb", "max_forks_repo_name": "ENCCS/umbrella-sampling-tutorial-test", "max_forks_repo_head_hexsha": "90f3bf7ef6267b992aed58892d95af9bdfe17ca2", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.3128834356, "max_line_length": 405, "alphanum_fraction": 0.6544759207, "converted": true, "num_tokens": 5884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567937024021, "lm_q2_score": 0.08756383595141072, "lm_q1q2_score": 0.02436523223612267}}
{"text": "**Introduction to Medical Imaging: Handling Dicom Files**\n\nO Dicom \u00e9 um formato de arquivo utilizado para armazenar exames m\u00e9dicos, como radiografias, tomografias, resson\u00e2ncias magn\u00e9ticas, entre outros. Ele armazena v\u00e1rios metadados sobre o exame, como dados do paciente, a m\u00e1quina usada para o exame, como a imagem \u00e9 armazenada, informa\u00e7\u00f5es espaciais e assim por diante. Cada exame tem propriedades diferentes, por isso \u00e9 importante saber com qual tipo de exame voc\u00ea estar\u00e1 lidando em um projeto.\n\nAqui, mostraremos algumas dicas e truques b\u00e1sicos e essenciais ao manusear um arquivo dicom.\n\n\n\n```python\n!pip install -q condacolab\nimport condacolab\ncondacolab.install_miniconda()\n!conda install -c conda-forge gdcm\n!pip install pydicom==2.0.0\n\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    \u23ec Downloading https://repo.anaconda.com/miniconda/Miniconda3-py37_4.9.2-Linux-x86_64.sh...\n    \ud83d\udce6 Installing...\n    \ud83d\udccc Adjusting configuration...\n    \ud83e\ude79 Patching environment...\n    \u23f2 Done in 0:00:21\n    \ud83d\udd01 Restarting kernel...\n    Collecting package metadata (current_repodata.json): - \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\bdone\n    Solving environment: | \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\bdone\n    \n    \n    ==> WARNING: A newer version of conda exists. <==\n      current version: 4.9.2\n      latest version: 4.11.0\n    \n    Please update conda by running\n    \n        $ conda update -n base -c defaults conda\n    \n    \n    \n    ## Package Plan ##\n    \n      environment location: /usr/local\n    \n      added / updated specs:\n        - gdcm\n    \n    \n    The following packages will be downloaded:\n    \n        package                    |            build\n        ---------------------------|-----------------\n        _libgcc_mutex-0.1          |      conda_forge           3 KB  conda-forge\n        _openmp_mutex-4.5          |            1_gnu          22 KB  conda-forge\n        ca-certificates-2021.10.8  |       ha878542_0         139 KB  conda-forge\n        certifi-2021.10.8          |   py37h89c1867_1         145 KB  conda-forge\n        conda-4.11.0               |   py37h89c1867_0        16.9 MB  conda-forge\n        expat-2.4.4                |       h295c915_0         169 KB\n        gdcm-2.8.9                 |   py37h500ead1_1         3.4 MB  conda-forge\n        jpeg-9e                    |       h7f98852_0         269 KB  conda-forge\n        json-c-0.13.1              |    hbfbb72e_1002          76 KB  conda-forge\n        libgcc-ng-11.2.0           |      h1d223b6_13         906 KB  conda-forge\n        libgomp-11.2.0             |      h1d223b6_13         428 KB  conda-forge\n        libjpeg-turbo-2.1.1        |       h7f98852_0         981 KB  conda-forge\n        libpng-1.6.37              |       h21135ba_2         306 KB  conda-forge\n        libtiff-4.0.9              |    h648cc4a_1002         566 KB  conda-forge\n        openjpeg-2.3.1             |       h58a6597_0         470 KB  conda-forge\n        openssl-1.1.1l             |       h7f98852_0         2.1 MB  conda-forge\n        python_abi-3.7             |          2_cp37m           4 KB  conda-forge\n        ------------------------------------------------------------\n                                               Total:        26.8 MB\n    \n    The following NEW packages will be INSTALLED:\n    \n      _openmp_mutex      conda-forge/linux-64::_openmp_mutex-4.5-1_gnu\n      expat              pkgs/main/linux-64::expat-2.4.4-h295c915_0\n      gdcm               conda-forge/linux-64::gdcm-2.8.9-py37h500ead1_1\n      jpeg               conda-forge/linux-64::jpeg-9e-h7f98852_0\n      json-c             conda-forge/linux-64::json-c-0.13.1-hbfbb72e_1002\n      libgomp            conda-forge/linux-64::libgomp-11.2.0-h1d223b6_13\n      libjpeg-turbo      conda-forge/linux-64::libjpeg-turbo-2.1.1-h7f98852_0\n      libpng             conda-forge/linux-64::libpng-1.6.37-h21135ba_2\n      libtiff            conda-forge/linux-64::libtiff-4.0.9-h648cc4a_1002\n      openjpeg           conda-forge/linux-64::openjpeg-2.3.1-h58a6597_0\n      python_abi         conda-forge/linux-64::python_abi-3.7-2_cp37m\n    \n    The following packages will be UPDATED:\n    \n      ca-certificates    pkgs/main::ca-certificates-2020.10.14~ --> conda-forge::ca-certificates-2021.10.8-ha878542_0\n      certifi            pkgs/main/noarch::certifi-2020.6.20-p~ --> conda-forge/linux-64::certifi-2021.10.8-py37h89c1867_1\n      conda               pkgs/main::conda-4.9.2-py37h06a4308_0 --> conda-forge::conda-4.11.0-py37h89c1867_0\n      libgcc-ng           pkgs/main::libgcc-ng-9.1.0-hdf63c60_0 --> conda-forge::libgcc-ng-11.2.0-h1d223b6_13\n      openssl              pkgs/main::openssl-1.1.1h-h7b6447c_0 --> conda-forge::openssl-1.1.1l-h7f98852_0\n    \n    The following packages will be SUPERSEDED by a higher-priority channel:\n    \n      _libgcc_mutex           pkgs/main::_libgcc_mutex-0.1-main --> conda-forge::_libgcc_mutex-0.1-conda_forge\n    \n    \n    \n    Downloading and Extracting Packages\n    jpeg-9e              | 269 KB    | : 100% 1.0/1 [00:00<00:00,  8.02it/s]\n    libgomp-11.2.0       | 428 KB    | : 100% 1.0/1 [00:00<00:00, 10.44it/s]\n    libjpeg-turbo-2.1.1  | 981 KB    | : 100% 1.0/1 [00:00<00:00,  4.33it/s]\n    expat-2.4.4          | 169 KB    | : 100% 1.0/1 [00:00<00:00,  9.84it/s]\n    python_abi-3.7       | 4 KB      | : 100% 1.0/1 [00:00<00:00, 31.46it/s]\n    _libgcc_mutex-0.1    | 3 KB      | : 100% 1.0/1 [00:00<00:00, 29.99it/s]\n    ca-certificates-2021 | 139 KB    | : 100% 1.0/1 [00:00<00:00, 22.89it/s]\n    gdcm-2.8.9           | 3.4 MB    | : 100% 1.0/1 [00:00<00:00,  1.42it/s]\n    openjpeg-2.3.1       | 470 KB    | : 100% 1.0/1 [00:00<00:00,  6.52it/s]\n    conda-4.11.0         | 16.9 MB   | : 100% 1.0/1 [00:04<00:00,  4.06s/it]\n    libgcc-ng-11.2.0     | 906 KB    | : 100% 1.0/1 [00:00<00:00,  5.03it/s]\n    libpng-1.6.37        | 306 KB    | : 100% 1.0/1 [00:00<00:00,  5.09it/s]                 \n    _openmp_mutex-4.5    | 22 KB     | : 100% 1.0/1 [00:00<00:00, 26.27it/s]\n    libtiff-4.0.9        | 566 KB    | : 100% 1.0/1 [00:00<00:00,  6.06it/s]\n    certifi-2021.10.8    | 145 KB    | : 100% 1.0/1 [00:00<00:00, 19.71it/s]\n    openssl-1.1.1l       | 2.1 MB    | : 100% 1.0/1 [00:00<00:00,  2.75it/s]\n    json-c-0.13.1        | 76 KB     | : 100% 1.0/1 [00:00<00:00, 24.25it/s]\n    Preparing transaction: / \b\bdone\n    Verifying transaction: \\ \b\b| \b\bdone\n    Executing transaction: - \b\b\\ \b\bdone\n    Collecting pydicom==2.0.0\n      Downloading pydicom-2.0.0-py3-none-any.whl (35.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 35.4 MB 74 kB/s \n    \u001b[?25hInstalling collected packages: pydicom\n    Successfully installed pydicom-2.0.0\n    Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n\n\nO segundo passo \u00e9 usar a biblioteca 'pydicom' para abrir o arquivo dicom desejado. Esta lib retorna um objeto especial com todas as informa\u00e7\u00f5es armazenadas dentro de um dicom. Para este notebook, usaremos um conjunto de arquivos dicom extra\u00eddos do RSNA Pulmonary Embolism Detection Challenge, que est\u00e3o armazenados na pasta que compartilhamos.\n\n\n```python\nimport pydicom\n\nDATASET_FOLDER = 'drive/MyDrive/Curso IA para Medicina - Cientista de Dados/1. Introdu\u00e7\u00e3o Imagens M\u00e9dicas/Dicom Hands-On/sample_train/'\ndcm_file = DATASET_FOLDER + '1ac673a65484/43e3fab0e6a7/5fe509226d61.dcm'\ndcm = pydicom.dcmread(dcm_file)\nprint(dcm)\n```\n\n    Dataset.file_meta -------------------------------\n    (0002, 0010) Transfer Syntax UID                 UI: Implicit VR Little Endian\n    -------------------------------------------------\n    (0008, 0005) Specific Character Set              CS: 'ISO_IR 100'\n    (0008, 0008) Image Type                          CS: \"['ORIGINAL', 'PRIMARY', 'AXIAL']\"\n    (0008, 0016) SOP Class UID                       UI: 80e30f500244\n    (0008, 0018) SOP Instance UID                    UI: 5fe509226d61\n    (0008, 0060) Modality                            CS: 'CT'\n    (0018, 0050) Slice Thickness                     DS: \"1.25\"\n    (0018, 0060) KVP                                 DS: \"120.0\"\n    (0018, 1120) Gantry/Detector Tilt                DS: \"0.0\"\n    (0018, 1130) Table Height                        DS: \"153.5\"\n    (0018, 1140) Rotation Direction                  CS: 'CW'\n    (0018, 1151) X-Ray Tube Current                  IS: \"367\"\n    (0018, 1152) Exposure                            IS: \"3\"\n    (0018, 1210) Convolution Kernel                  SH: 'STANDARD'\n    (0018, 5100) Patient Position                    CS: 'FFS'\n    (0020, 000d) Study Instance UID                  UI: 1ac673a65484\n    (0020, 000e) Series Instance UID                 UI: 43e3fab0e6a7\n    (0020, 0011) Series Number                       IS: \"2\"\n    (0020, 0013) Instance Number                     IS: \"141\"\n    (0020, 0032) Image Position (Patient)            DS: [-175.400, -192.500, -176.500]\n    (0020, 0037) Image Orientation (Patient)         DS: [1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000]\n    (0020, 0052) Frame of Reference UID              UI: 7e544ca6e059\n    (0028, 0002) Samples per Pixel                   US: 1\n    (0028, 0004) Photometric Interpretation          CS: 'MONOCHROME2'\n    (0028, 0010) Rows                                US: 512\n    (0028, 0011) Columns                             US: 512\n    (0028, 0030) Pixel Spacing                       DS: [0.751953, 0.751953]\n    (0028, 0100) Bits Allocated                      US: 16\n    (0028, 0101) Bits Stored                         US: 16\n    (0028, 0102) High Bit                            US: 15\n    (0028, 0103) Pixel Representation                US: 1\n    (0028, 1050) Window Center                       DS: \"40.0\"\n    (0028, 1051) Window Width                        DS: \"350.0\"\n    (0028, 1052) Rescale Intercept                   DS: \"-1024.0\"\n    (0028, 1053) Rescale Slope                       DS: \"1.0\"\n    (7fe0, 0010) Pixel Data                          OW: Array of 524288 elements\n\n\nAqui podemos ver o que est\u00e1 armazenado dentro de um arquivo dicom. \n\nPor enquanto, vamos focar nossa aten\u00e7\u00e3o na estrela principal: a imagem real do exame. Esta imagem \u00e9 armazenada no campo \"Pixel Data\". Como mencionamos anteriormente, pydicom l\u00ea um dicom e retorna um objeto especial com diferentes tags dicom. Cada uma dessas tags pode ser acessada como uma vari\u00e1vel de objeto normal. Por exemplo, os dados de pixel podem ser acessados \u200b\u200busando dcm.PixelData. No entanto, o atributo PixelData armazena os bytes brutos usados \u200b\u200bpara armazenar os pixels da imagem. Existe outro atributo especial que converte o PixelData para um formato mais amig\u00e1vel: o dcm.pixel_array.\n\nPara este primeiro exemplo, usaremos um arquivo dicom de tomografia computadorizada. Portanto, esta imagem representa uma \u00fanica fatia de um exame 3D. Mas, por enquanto, vamos nos concentrar apenas em como lidar com uma \u00fanica fatia.\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimg = dcm.pixel_array\nprint(f'min max img value = ({np.min(img)}, {np.max(img)})')\nprint(f'img shape = {img.shape}')\nimgplot = plt.imshow(img, cmap='gray')\n```\n\n**Hounsfield Unit**\n\nComo podemos ver na c\u00e9lula anterior, o pixel_array armazena os valores dos pixels no exame. Observe que, neste caso, os valores de pixel variam de -2000 a 4095 (nesta imagem). Nesta parte, mostramos que cada voxel (voxel \u00e9 um pixel em um espa\u00e7o 3D) em uma tomografia computadorizada indica a densidade daquela parte espec\u00edfica do corpo, de forma semelhante a um exame de raio-x. Portanto, valores de pixel mais altos indicam regi\u00f5es de baixa densidade. Essa medida \u00e9 realizada com a escala Hounsfield Unit (HU), usada para medir a radiodensidade. Nesta escala, a \u00e1gua destilada tem uma medida de 0 HU, enquanto o ar costuma ficar em torno de -1000 HU. Quando convertemos isso em uma imagem, as regi\u00f5es de baixa densidade ficam mais escuras, enquanto as \u00e1reas de alta densidade s\u00e3o mais claras. Na dicom mostrada na c\u00e9lula anterior, podemos ver um corte mostrando parte dos pulm\u00f5es do paciente. Os pulm\u00f5es est\u00e3o cheios de ar, diminuindo sua densidade. Por isso, \u00e9 mostrado na imagem com um tom mais escuro.\n\nMas, na realidade, os arquivos dicom geralmente armazenam a matriz de pixels em uma representa\u00e7\u00e3o interna. Na verdade, requer uma convers\u00e3o especial para transformar o valor armazenado na escala de unidade desejada (HU no caso de um exame de TC). Para isso, precisamos de duas outras tags dicom: RescaleSlope e RescaleIntercept. A imagem HU \u00e9 obtida pela seguinte opera\u00e7\u00e3o:\n\n\\begin{align}\nI_{HU} = I r_{s} + r_{i}\n\\end{align}\n\nonde IHU \u00e9 a imagem em escala HU, I \u00e9 a imagem armazenada na matriz de pixels, rs \u00e9 a etiqueta de inclina\u00e7\u00e3o de reescalonamento e ri \u00e9 a intercepta\u00e7\u00e3o de reescalonamento\n\n\n```python\nimg = dcm.pixel_array\n\nslope = float(dcm.RescaleSlope)\nintercept = float(dcm.RescaleIntercept)\nprint(f'slope = {slope}')\nprint(f'intercept = {intercept}')\n\nimg = (img*slope +intercept)\nprint(f'min max img value = ({np.min(img)}, {np.max(img)})')\nprint(f'img shape = {img.shape}')\nimgplot = plt.imshow(img, cmap='gray')\n```\n\nAo trabalhar com imagens e aprendizado profundo, uma boa coisa a fazer \u00e9 usar apenas imagens normalizadas. Para imagens de TC, por exemplo, sempre podemos converter uma imagem dicom em um intervalo normalizado entre (0, 1) sem perder nenhuma informa\u00e7\u00e3o \u00fatil:\n\n\n```python\ndef change_range(img, new_min, new_max, actual_min=None, actual_max=None):\n    if actual_min is None or actual_max is None:\n        actual_min = np.min(img)\n        actual_max = np.max(img)\n\n    if actual_min == new_min and actual_max == new_max:\n        return img\n\n    img = (\n        (new_max - new_min) * (img - actual_min) / (actual_max - actual_min)\n    ) + new_min\n\n    return img\n\n\n\nimg = change_range(dcm.pixel_array, new_min=0.0, new_max=1.0)\nprint(f'min max img value = ({np.min(img)}, {np.max(img)})')\nprint(f'img shape = {img.shape}')\nimgplot = plt.imshow(img, cmap='gray')\n```\n\n**Dicom Windowing Operation**\n\nUma imagem dicom de um exame de TC ou raio-X s\u00e3o todas representadas na escala da Unidade Hounsfield, que indica a densidade de cada regi\u00e3o do corpo. Isso resulta em imagens com muita informa\u00e7\u00e3o, geralmente representadas por pixels com 12 a 16 bits. Isso \u00e9 muita informa\u00e7\u00e3o. Imagens regulares s\u00e3o geralmente representadas com pixels de 8 bits (valores entre (0, 255)). Ent\u00e3o, como podemos converter uma imagem dicom medida em HU em uma imagem comum? Bem, j\u00e1 fizemos isso na c\u00e9lula anterior: podemos simplesmente converter esta imagem para um intervalo diferente. Mas ao fazer isso, a imagem se torna uma imagem de baixo contraste, pois h\u00e1 muita informa\u00e7\u00e3o para nossos olhos capturarem completamente. Uma abordagem mais sofisticada \u00e9 usar janelas dicom.\n\nUma janela dicom indica qual faixa do espectro de imagem HU original queremos focar. Uma janela \u00e9 definida pelos par\u00e2metros principais:\n\nCentro da Janela ( wc ): representa a faixa m\u00e9dia de HU a focar;\nLargura da janela ( ww ): indica a faixa de HU a partir do centro da janela a ser analisada.\nA imagem em janela \u00e9 calculada de acordo com a seguinte equa\u00e7\u00e3o:\n\n\\begin{align}\nmin_{p} = w_c - \\frac{w_w}{2} \\\\\nmax_{p} = w_c + \\frac{w_w}{2} \\\\\nI_w = \\texttt{clip}(I, min_{p}, max_{p})\n\\end{align}\n\nonde minp representa o valor m\u00ednimo de pixel da imagem em janela, maxp indica o valor m\u00e1ximo de pixel, I \u00e9 a imagem HU original, Iw \u00e9 a imagem em janela e clip(i,m,M) \u00e9 uma fun\u00e7\u00e3o de recorte que recorta todos os valores dentro imagem i para um valor m\u00ednimo de m e um valor m\u00e1ximo de M, ou seja, cada pixel com um valor maior que M \u00e9 recortado em M e todos os valores menores que m s\u00e3o recortados em m.\n\n\n```python\nslope = float(dcm.RescaleSlope)\nintercept = float(dcm.RescaleIntercept)\nwindow_center = float(dcm.WindowCenter)\nwindow_width = float(dcm.WindowWidth)\nprint(f'slope = {slope}')\nprint(f'intercept = {intercept}')\nprint(f'window_center = {window_center}')\nprint(f'window_width = {window_width}')\n\nimg = dcm.pixel_array\nimg = (img*slope +intercept)\nimg_min = window_center - window_width//2\nimg_max = window_center + window_width//2\nimg = np.clip(img, img_min, img_max)\n\nprint(f'min max img value = ({np.min(img)}, {np.max(img)})')\nimgplot = plt.imshow(img, cmap='gray')\n\n\n```\n\n**Building a Compact Windowing Function**\n\nVamos agora construir uma fun\u00e7\u00e3o compacta capaz de realizar uma opera\u00e7\u00e3o de janelas sobre uma imagem dicom. Esta fun\u00e7\u00e3o nos permitir\u00e1 reutilizar esta opera\u00e7\u00e3o no restante deste curso. Tamb\u00e9m podemos testar diferentes valores de janela para ver o que muda.\n\nEm primeiro lugar, devemos carregar o arquivo dicom. J\u00e1 mostramos como carregar um arquivo dicom usando pydicom. Em alguns casos, o atributo de matriz de pixels pode ser compactado dentro do arquivo dicom. Para descompact\u00e1-lo, \u00e9 importante usar a fun\u00e7\u00e3o interna descompactar. Existem v\u00e1rios algoritmos de compacta\u00e7\u00e3o usados \u200b\u200bpara arquivos dicom. O Pydicom tem alguns algoritmos de descompress\u00e3o implementados, mas n\u00e3o todos. Para disponibilizar o n\u00famero m\u00e1ximo de algoritmos de descompress\u00e3o, recomendamos instalar a biblioteca gdcm (use a vers\u00e3o conda desta biblioteca, pois \u00e9 mais f\u00e1cil faz\u00ea-la funcionar com a biblioteca pydicom). Se estiver instalado, a fun\u00e7\u00e3o de descompress\u00e3o funcionar\u00e1 com uma gama mais ampla de algoritmos de descompress\u00e3o. Usar isso pode salvar seu futuro aprendizado profundo para o pipeline de infer\u00eancia de imagens m\u00e9dicas.\n\n\n```python\nimport gdcm\n\ndef read_dicom(dicom_path):\n  ds = pydicom.dcmread(dicom_path)\n  ds.decompress()\n  return ds\n```\n\nVamos agora construir uma fun\u00e7\u00e3o para ler as tags dicom de inclina\u00e7\u00e3o, intercepta\u00e7\u00e3o e janela. Como vimos, podemos simplesmente ler essas tags e convert\u00ea-las em float. No entanto, isso pode falhar em alguns casos, onde essas tags s\u00e3o armazenadas como uma matriz. Portanto, usamos a seguinte fun\u00e7\u00e3o para recuperar esses valores (fun\u00e7\u00e3o recuperada deste post em uma competi\u00e7\u00e3o do kaggle):\n\n\n```python\ndef get_first_of_dicom_field_as_int(x):\n  if type(x) == pydicom.multival.MultiValue:\n    return int(x[0])\n  else:\n    return int(x)\n```\n\nAgora podemos construir efetivamente nossa fun\u00e7\u00e3o de janelas. Primeiro, devemos carregar o arquivo dicom usando nossa fun\u00e7\u00e3o read_dicom. A segunda coisa que nossa fun\u00e7\u00e3o de janela deve verificar \u00e9 como os bits s\u00e3o armazenados na imagem dicom. Isso pode ser verificado usando a tag dicom PhotometricInterpretation, que mostra se os valores altos de pixel s\u00e3o convertidos em preto (MONOCHROME1) ou branco (MONOCHROME2). Para mais informa\u00e7\u00f5es, consulte este e este link. Basicamente, vamos considerar aqui que MONOCHROME2 \u00e9 o padr\u00e3o b\u00e1sico a ser seguido, ent\u00e3o se alguma dicom for MONOCHROME1, iremos convert\u00ea-la para MONOCHROME2 invertendo seu valor.\n\nO restante da fun\u00e7\u00e3o usa conceitos j\u00e1 explorados neste caderno. Se quisermos um conjunto espec\u00edfico de par\u00e2metros de janela, podemos passar esses valores como par\u00e2metros para a fun\u00e7\u00e3o. Caso contr\u00e1rio, usaremos os par\u00e2metros de janela padr\u00e3o presentes no arquivo dicom.\n\n\n```python\ndef get_single_window_img(path, window_center=None, window_width=None):\n  dicom = read_dicom(path)\n  img = dicom.pixel_array\n  if 'MONOCHROME1' in dicom.PhotometricInterpretation:\n    img = 2**dicom.BitsStored-img\n\n  try:\n    slope = get_first_of_dicom_field_as_int(dicom.RescaleSlope)\n    intercept = get_first_of_dicom_field_as_int(dicom.RescaleIntercept)\n    if window_center is None:\n      window_center = get_first_of_dicom_field_as_int(dicom.WindowCenter)\n      window_width = get_first_of_dicom_field_as_int(dicom.WindowWidth)\n\n    img = (img*slope +intercept)\n    img_min = window_center - window_width//2\n    img_max = window_center + window_width//2\n    img[imgimg_max] = img_max\n\n    img = (img - img_min) / window_width\n  except:\n    return None\n\n  return img\n```\n\n**Testing Other Window Parameters**\n\nCom nossa fun\u00e7\u00e3o constru\u00edda, podemos us\u00e1-la para testar diferentes par\u00e2metros de janela. Cada par\u00e2metro de janela \u00e9 usado para focar a aten\u00e7\u00e3o em detalhes espec\u00edficos da imagem dicom. Por exemplo, o par (centro da janela, largura da janela) usado para analisar os pulm\u00f5es \u00e9 (-600, 1500), enquanto uma janela espec\u00edfica do f\u00edgado \u00e9 dada por (30, 150) e uma janela do osso da coluna \u00e9 (400, 1800) \n\n\n```python\nimg_lung = get_single_window_img(dcm_file, window_center=-600, window_width=1500)\nimg_liver = get_single_window_img(dcm_file, window_center=30, window_width=150)\nimg_spine = get_single_window_img(dcm_file, window_center=400, window_width=1800)\n\nf, axarr = plt.subplots(1, 3, figsize=(15,15))\naxarr[0].imshow(img_lung, cmap='gray')\naxarr[1].imshow(img_liver, cmap='gray')\naxarr[2].imshow(img_spine, cmap='gray')\n```\n\nTamb\u00e9m podemos empilhar essas imagens obtidas usando diferentes par\u00e2metros de janela em uma \u00fanica imagem. Precisamos apenas adicionar cada imagem a um canal de cor diferente para obter um rgb\n\n\n```python\nimg = np.stack([img_lung, img_liver, img_spine], axis=-1)\nprint(img.shape)\nimgplot = plt.imshow(img)\n```\n\nAgora podemos encapsular essa opera\u00e7\u00e3o de construir uma imagem dicom multicanal com diferentes par\u00e2metros de janela em cada canal. Para isso, vamos construir uma fun\u00e7\u00e3o que recebe o caminho do arquivo dicom, uma lista de par\u00e2metros de centro e largura da janela (neste caso, essas listas devem ter o mesmo comprimento), ou um \u00fanico par\u00e2metro de centro e largura da janela em caso queiramos uma imagem de canal \u00fanico, ou um valor nulo para ambos os par\u00e2metros caso queiramos carregar os par\u00e2metros originais da janela do dicom.\n\n\n```python\ndef get_dicom_img(path, window_center=None, window_width=None):\n  img = None\n  if window_center is None or window_width is None:\n    img = get_single_window_img(path)\n  elif type(window_center) == list:\n    img = []\n    for i in range(len(window_center)):\n      img_ch = get_single_window_img(path, window_center[i], window_width[i])\n      img.append(img_ch)\n    img = np.array(img)\n    img = np.moveaxis(img, 0,2)\n  else:\n    img = get_single_window_img(path, window_center, window_width)\n\n  return img\n\nwindow_center_list = [-600, 30, 400]\nwindow_width_list = [1500, 150, 1800]\nimg_multi = get_dicom_img(dcm_file, window_center_list, window_width_list)\nimg_lung = get_dicom_img(dcm_file, -600, 1500)\nimg_original = get_dicom_img(dcm_file)\n\nf, axarr = plt.subplots(1, 3, figsize=(15,15))\nprint(img_original.shape)\naxarr[0].imshow(img_multi)\naxarr[1].imshow(img_lung, cmap='gray')\naxarr[2].imshow(img_original, cmap='gray')\n```\n", "meta": {"hexsha": "1da91f5e3a941e30dcc9120326e032dc97f84a8e", "size": 804948, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "00_Handling_Dicom.ipynb", "max_stars_repo_name": "vpaula07/Dicom-Hands-On", "max_stars_repo_head_hexsha": "3b68fdb5077437ba0e2d519fd5f948f38b1da6fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "00_Handling_Dicom.ipynb", "max_issues_repo_name": "vpaula07/Dicom-Hands-On", "max_issues_repo_head_hexsha": "3b68fdb5077437ba0e2d519fd5f948f38b1da6fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "00_Handling_Dicom.ipynb", "max_forks_repo_name": "vpaula07/Dicom-Hands-On", "max_forks_repo_head_hexsha": "3b68fdb5077437ba0e2d519fd5f948f38b1da6fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 884.5582417582, "max_line_length": 274880, "alphanum_fraction": 0.9494240622, "converted": true, "num_tokens": 7281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3073580168652638, "lm_q2_score": 0.07921033063001552, "lm_q1q2_score": 0.024345930137683432}}
{"text": "```python\nimport os\nos.environ['TRKXINPUTDIR']=\"/global/cfs/cdirs/m3443/data/trackml-kaggle/train_10evts\"\ninput_data_path = \"/global/cfs/projectdirs/m3443/usr/caditi97/iml2021/run_dir\" \nos.environ['TRKXOUTPUTDIR']= input_data_path\n```\n\n\n```python\nimport pkg_resources\nimport yaml\nimport pprint\nimport random\nrandom.seed(1234)\nimport numpy as np\n# import pandas as pd\nimport itertools\nimport matplotlib.pyplot as plt\nimport tqdm\nfrom os import listdir\nfrom os.path import isfile, join\nimport matplotlib.cm as cm\nimport sys\nimport tqdm\nfrom tqdm import tqdm\nimport tqdm.notebook as tq\n# import sympy\n# from sympy import S, symbols, printing\n# %matplotlib widget\n\nsys.path.append('/global/homes/c/caditi97/exatrkx-iml2020/exatrkx/src/')\n\n# 3rd party\nimport torch\nimport torch.nn.functional as F\nfrom torch_geometric.data import Data\nfrom trackml.dataset import load_event\nfrom pytorch_lightning import Trainer\nfrom pytorch_lightning.callbacks import ModelCheckpoint\nfrom pytorch_lightning.loggers.neptune import NeptuneLogger\n\n\n# local import\nfrom exatrkx import config_dict # for accessing predefined configuration files\nfrom exatrkx import outdir_dict # for accessing predefined output directories\nfrom exatrkx.src import utils_dir\nfrom exatrkx.src import utils_robust\nfrom utils_robust import *\n\n\n# for preprocessing\nfrom exatrkx import FeatureStore\nfrom exatrkx.src import utils_torch\n\n# for embedding\nfrom exatrkx import LayerlessEmbedding\nfrom exatrkx import EmbeddingInferenceCallback\nfrom exatrkx.src import utils_torch\nfrom torch_cluster import radius_graph\nfrom utils_torch import build_edges\nfrom embedding.embedding_base import *\n\n# for filtering\nfrom exatrkx import VanillaFilter\n\n# for GNN\nimport tensorflow as tf\nfrom graph_nets import utils_tf\nfrom exatrkx import SegmentClassifier\nimport sonnet as snt\n\n# for labeling\nfrom exatrkx.scripts.tracks_from_gnn import prepare as prepare_labeling\nfrom exatrkx.scripts.tracks_from_gnn import clustering as dbscan_clustering\n\n# track efficiency\nfrom trackml.score import _analyze_tracks\nfrom exatrkx.scripts.eval_reco_trkx import make_cmp_plot, pt_configs, eta_configs\nfrom functools import partial\n\n\n```\n\n\n```python\nmypath = \"/global/cfs/projectdirs/m3443/usr/caditi97/iml2021/run_dir/fs_notscaled\"\n```\n\n\n```python\nevents = [f for f in listdir(mypath)]\n```\n\n\n```python\nfor evtid in tqdm(events):\n    f = join(mypath,evtid)\n    data = torch.load(f)\n    x = torch.from_numpy(data.x.numpy()/np.array([3000, np.pi, 400])).float()\n    new_data = Data(event_file=data.event_file,\n                    x=x, \n                    pid=data.pid,\n                    layers=data.layers, \n                    hid=data.hid,\n                   layerless_true_edges=data.layerless_true_edges)\n    filename = f\"/global/cfs/projectdirs/m3443/usr/caditi97/iml2021/run_dir/feature_store/{evtid}\"\n    with open(filename, 'wb') as pickle_file:\n            torch.save(new_data, pickle_file)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5000/5000 [00:28<00:00, 176.04it/s]\n\n\n\n```python\ntorch.load(filename)\n# tf.convert_to_tensor(data_np, np.float32)\n```\n\n\n\n\n    Data(event_file=\"WmuHNL15GeV_NoPileUp_Generic/event000004814\", hid=[201], layerless_true_edges=[2, 183], layers=[201], pid=[201], x=[201, 3])\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "ba0993e487589b033753e335f464b6004ed4ef7b", "size": 5781, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/scale_evt.ipynb", "max_stars_repo_name": "caditi97/exatrkx-iml2020", "max_stars_repo_head_hexsha": "f4b1e4438cda7db2d40c8e572b1b682c12781e6c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-24T18:54:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-24T18:54:55.000Z", "max_issues_repo_path": "notebooks/scale_evt.ipynb", "max_issues_repo_name": "caditi97/exatrkx-iml2020", "max_issues_repo_head_hexsha": "f4b1e4438cda7db2d40c8e572b1b682c12781e6c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/scale_evt.ipynb", "max_forks_repo_name": "caditi97/exatrkx-iml2020", "max_forks_repo_head_hexsha": "f4b1e4438cda7db2d40c8e572b1b682c12781e6c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0502512563, "max_line_length": 152, "alphanum_fraction": 0.5933229545, "converted": true, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.055005283258827455, "lm_q1q2_score": 0.024294348784360435}}
{"text": "```python\n#@title  <-- Run Me: (Hidden) Installing Spark\n%%bash \n\n## Setup Spark on Colab\npip install -q pyspark\napt-get -qq install -y openjdk-8-jdk-headless\npip install -q elephas\n\n## Setup port-forwarding\n\n# Download ngrok\nwget -q https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip\n# Unload ngrok\nunzip -q ngrok-stable-linux-amd64.zip\n```\n\n    replace ngrok? [y]es, [n]o, [A]ll, [N]one, [r]ename:  NULL\n    (EOF or read error, treating as \"[N]one\" ...)\n\n\n\n```python\n#@title  <-- Run Me: (Hidden) Environment Variable Setup\nimport os\nos.environ[\"JAVA_HOME\"] = \"/usr/lib/jvm/java-8-openjdk-amd64\"\n```\n\n\n```python\nimport pyspark \nfrom pyspark.sql import *\nfrom pyspark.sql.functions import *\nfrom pyspark import SparkContext, SparkConf\n\n# Set configuration scope to be local and use port 4050\nconfig_scope = SparkConf().set(\"spark.ui.port\", \"4050\")\n\n# Create the connection to a Spark cluster\nsc = pyspark.SparkContext(conf = config_scope)\n\n# Create a session to programmatically build Spark RDD, DataFrame and DataSet\nspark = SparkSession.builder.getOrCreate()\n```\n\n\n```python\n#@title (Hidden) Diagnostic Check\nimport os\nimport sys\nimport pandas as pd\nimport numpy as np\n\nprint(f\"python: {sys.version}\")\nprint(f\"pyspark: {sc.version}\")\nprint(f\"pandas: {pd.__version__}\")\nprint(f\"NumPy: {np.__version__}\")\n\ntry:\n  from google.colab import drive\n  is_google_colab = True\n\n  print(\"Notebook is on Google CoLab\")\nexcept:\n  is_google_colab = False\n  print(\"Notebook is being run locally or through another source.\")\n\n```\n\n    python: 3.7.13 (default, Apr 24 2022, 01:04:09) \n    [GCC 7.5.0]\n    pyspark: 3.2.0\n    pandas: 1.3.5\n    NumPy: 1.21.6\n    Notebook is on Google CoLab\n\n\n\n```python\nfrom pyspark.ml.classification import MultilayerPerceptronClassifier\nfrom pyspark.ml.evaluation import MulticlassClassificationEvaluator\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n\n```python\nraw_train_data = spark.read.option(\"delimiter\", \"|\").options(header = True, inferSchema = True).csv(\"/content/drive/MyDrive/train_data.csv\")\nraw_train_data.printSchema()\ntemp, temp1=raw_train_data.randomSplit([0.1, 0.9])\ntrain, test=temp.randomSplit([0.95, 0.05])\n```\n\n    root\n     |-- label: integer (nullable = true)\n     |-- uid: integer (nullable = true)\n     |-- task_id: integer (nullable = true)\n     |-- adv_id: integer (nullable = true)\n     |-- creat_type_cd: integer (nullable = true)\n     |-- adv_prim_id: integer (nullable = true)\n     |-- dev_id: integer (nullable = true)\n     |-- inter_type_cd: integer (nullable = true)\n     |-- slot_id: integer (nullable = true)\n     |-- spread_app_id: integer (nullable = true)\n     |-- tags: integer (nullable = true)\n     |-- app_first_class: integer (nullable = true)\n     |-- app_second_class: integer (nullable = true)\n     |-- age: integer (nullable = true)\n     |-- city: integer (nullable = true)\n     |-- city_rank: integer (nullable = true)\n     |-- device_name: integer (nullable = true)\n     |-- device_size: integer (nullable = true)\n     |-- career: integer (nullable = true)\n     |-- gender: integer (nullable = true)\n     |-- net_type: integer (nullable = true)\n     |-- residence: integer (nullable = true)\n     |-- his_app_size: integer (nullable = true)\n     |-- his_on_shelf_time: integer (nullable = true)\n     |-- app_score: integer (nullable = true)\n     |-- emui_dev: integer (nullable = true)\n     |-- list_time: integer (nullable = true)\n     |-- device_price: integer (nullable = true)\n     |-- up_life_duration: integer (nullable = true)\n     |-- up_membership_grade: integer (nullable = true)\n     |-- membership_life_duration: integer (nullable = true)\n     |-- consume_purchase: integer (nullable = true)\n     |-- communication_onlinerate: string (nullable = true)\n     |-- communication_avgonline_30d: integer (nullable = true)\n     |-- indu_name: integer (nullable = true)\n     |-- pt_d: integer (nullable = true)\n    \n\n\n\n```python\nfrom pyspark.ml.feature import VectorAssembler\n# Apply the transformation and rename columns\nid_df = train.select(\"uid\", \"task_id\",\"adv_id\")\ntrain_df=train.drop(\"uid\", \"task_id\",\"adv_id\",\"communication_onlinerate\")\n```\n\n\n```python\n# Dynamically generate name of columns\nvecAssembler = VectorAssembler(\n    inputCols = train_df.columns[1:],\n    outputCol = \"features\")\n\n# Apply the transformation\nvec_data = vecAssembler.transform(train_df)\ntrain_data_new=vec_data.select(\"label\",\"features\")\n\n```\n\n\n```python\nid_df_test = test.select(\"uid\", \"task_id\",\"adv_id\")\ntest_df=test.drop(\"uid\", \"task_id\",\"adv_id\",\"communication_onlinerate\")\n# Dynamically generate name of columns\nvecAssembler = VectorAssembler(\n    inputCols = test_df.columns[1:],\n    outputCol = \"features\")\n\n# Apply the transformation\nvec_data = vecAssembler.transform(test_df)\ntest_data_new=vec_data.select(\"label\",\"features\")\n```\n\n\n```python\ntrain1DF = train_data_new.where(\"label=1\")\nONumber = train1DF.count()\ntrain0DF = train_data_new.where(\"label=0\")\nZNumber = train0DF.count()\nratio = ONumber/(ZNumber)\nsampleNormalDF = train0DF.sample(False, ratio, 10)\nunderDF = train1DF.union(sampleNormalDF)\n```\n\n## Deep learning\n\n\n```python\nfrom pyspark.ml.linalg import Vectors\nimport numpy as np\nimport random\nimport tensorflow\nfrom pyspark import SparkContext, SparkConf\nfrom pyspark.sql import SQLContext\nfrom pyspark.ml.feature import StringIndexer, StandardScaler\nfrom pyspark.ml import Pipeline\n\nfrom tensorflow.keras import optimizers, regularizers\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Activation\n\nfrom elephas.ml_model import ElephasEstimator\n```\n\n\n```python\ndim=len(underDF.select(\"features\").first()[0])\nmodel=Sequential()\nmodel.add(Dense(128,input_shape=(dim,),activity_regularizer=regularizers.l2(0.01)))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(rate=0.3))\nmodel.add(Dense(128,activity_regularizer=regularizers.l2(0.01)))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(rate=0.3))\nmodel.add(Dense(2))\nmodel.add(Activation('sigmoid'))\nmodel.compile(loss='binary_crossentropy',optimizer='adam')\n```\n\n\n```python\n#optimizer_coef=Adam(lr=0.01)\n#opt_coef=optimizers.serialize(optimizer_coef)\noptimizer_coef = optimizers.Adam(lr=0.01)\nopt_coef = optimizers.serialize(optimizer_coef)\n```\n\n    /usr/local/lib/python3.7/dist-packages/keras/optimizer_v2/adam.py:105: UserWarning: The `lr` argument is deprecated, use `learning_rate` instead.\n      super(Adam, self).__init__(name, **kwargs)\n\n\n\n```python\nestimate=ElephasEstimator()\nestimate.setFeaturesCol(\"features\")\nestimate.setLabelCol(\"label\")\nestimate.set_keras_model_config(model.to_json())\nestimate.set_categorical_labels(True)\nestimate.set_nb_classes(2)\nestimate.set_num_workers(1)\nestimate.set_epochs(25)\nestimate.set_batch_size(64)\nestimate.set_verbosity(1)\nestimate.set_validation_split(0.1)\nestimate.set_optimizer_config(opt_coef)\nestimate.set_mode(\"synchronous\")\nestimate.set_loss(\"binary_crossentropy\")\nestimate.set_metrics([\"acc\"])\n```\n\n\n\n\n    ElephasEstimator_4822113b019a\n\n\n\n\n```python\ndl_pipeline=Pipeline(stages=[estimate])\nfit_dl=dl_pipeline.fit(underDF)\n```\n\n    >>> Fit model\n    >>> Synchronous training complete.\n\n\n\n```python\n#pred_train=fit_dl.transform(underDF)\npred_test=fit_dl.transform(test_data_new)\n```\n\n\n```python\npnl = pred_test.select(\"label\",\"prediction\")\npnl.head(50)\n```\n\n\n\n\n    [Row(label=0, prediction=[0.438194215297699, 0.5616056323051453]),\n     Row(label=0, prediction=[0.5163557529449463, 0.4836386442184448]),\n     Row(label=0, prediction=[0.40139707922935486, 0.5984794497489929]),\n     Row(label=0, prediction=[0.3933424949645996, 0.6066682934761047]),\n     Row(label=0, prediction=[0.4820730984210968, 0.5178900361061096]),\n     Row(label=0, prediction=[0.4340554177761078, 0.5658337473869324]),\n     Row(label=0, prediction=[0.41489601135253906, 0.5851355791091919]),\n     Row(label=0, prediction=[0.5241385102272034, 0.4758770763874054]),\n     Row(label=0, prediction=[0.4530496299266815, 0.5468299388885498]),\n     Row(label=0, prediction=[0.5099837779998779, 0.48999398946762085]),\n     Row(label=0, prediction=[0.37734025716781616, 0.622628390789032]),\n     Row(label=0, prediction=[0.4359513223171234, 0.5640239119529724]),\n     Row(label=0, prediction=[0.46863946318626404, 0.5313493013381958]),\n     Row(label=0, prediction=[0.3562997281551361, 0.6437332034111023]),\n     Row(label=0, prediction=[0.5213179588317871, 0.47871267795562744]),\n     Row(label=0, prediction=[0.47824618220329285, 0.5215450525283813]),\n     Row(label=0, prediction=[0.5086542963981628, 0.4913155436515808]),\n     Row(label=0, prediction=[0.4135501980781555, 0.5862641930580139]),\n     Row(label=0, prediction=[0.463422030210495, 0.536344051361084]),\n     Row(label=0, prediction=[0.4690689146518707, 0.5307546257972717]),\n     Row(label=0, prediction=[0.5175883173942566, 0.4824284315109253]),\n     Row(label=0, prediction=[0.3624550700187683, 0.6375131607055664]),\n     Row(label=0, prediction=[0.41266748309135437, 0.5872901678085327]),\n     Row(label=0, prediction=[0.43002572655677795, 0.5699203014373779]),\n     Row(label=0, prediction=[0.5197933912277222, 0.48013055324554443]),\n     Row(label=0, prediction=[0.4752129316329956, 0.5246576070785522]),\n     Row(label=0, prediction=[0.38660097122192383, 0.6132520437240601]),\n     Row(label=0, prediction=[0.44079458713531494, 0.5592135190963745]),\n     Row(label=0, prediction=[0.5234086513519287, 0.47660934925079346]),\n     Row(label=0, prediction=[0.37648072838783264, 0.6235202550888062]),\n     Row(label=0, prediction=[0.4659220576286316, 0.5339611768722534]),\n     Row(label=0, prediction=[0.5161776542663574, 0.48388126492500305]),\n     Row(label=0, prediction=[0.41838428378105164, 0.5815260410308838]),\n     Row(label=0, prediction=[0.5395340323448181, 0.46041804552078247]),\n     Row(label=0, prediction=[0.506840169429779, 0.4931052327156067]),\n     Row(label=0, prediction=[0.5026028156280518, 0.49738016724586487]),\n     Row(label=0, prediction=[0.5270317196846008, 0.47297754883766174]),\n     Row(label=0, prediction=[0.5222308039665222, 0.4777633547782898]),\n     Row(label=0, prediction=[0.4786037802696228, 0.5212347507476807]),\n     Row(label=0, prediction=[0.4287435710430145, 0.5711016654968262]),\n     Row(label=0, prediction=[0.4856346547603607, 0.514271080493927]),\n     Row(label=0, prediction=[0.4520629644393921, 0.5477721095085144]),\n     Row(label=0, prediction=[0.43519851565361023, 0.5646072626113892]),\n     Row(label=0, prediction=[0.5150904059410095, 0.48495376110076904]),\n     Row(label=0, prediction=[0.49946993589401245, 0.5004138946533203]),\n     Row(label=0, prediction=[0.5258638858795166, 0.47413772344589233]),\n     Row(label=0, prediction=[0.4398408830165863, 0.5599850416183472]),\n     Row(label=0, prediction=[0.4804458022117615, 0.5194776058197021]),\n     Row(label=0, prediction=[0.503496527671814, 0.49644777178764343]),\n     Row(label=0, prediction=[0.47223132848739624, 0.5276749730110168])]\n\n\n\n\n```python\npnl.tail(50)\n```\n\n\n\n\n    [Row(label=1, prediction=[0.3184173107147217, 0.6816353797912598]),\n     Row(label=1, prediction=[0.40757182240486145, 0.5923088192939758]),\n     Row(label=1, prediction=[0.33075153827667236, 0.6694265604019165]),\n     Row(label=1, prediction=[0.3710591197013855, 0.6289851069450378]),\n     Row(label=1, prediction=[0.27900463342666626, 0.7210713624954224]),\n     Row(label=1, prediction=[0.31854450702667236, 0.6816060543060303]),\n     Row(label=1, prediction=[0.3194119334220886, 0.6806076765060425]),\n     Row(label=1, prediction=[0.29181569814682007, 0.7083054780960083]),\n     Row(label=1, prediction=[0.3233720064163208, 0.6768039464950562]),\n     Row(label=1, prediction=[0.37393718957901, 0.6261382102966309]),\n     Row(label=1, prediction=[0.4349546730518341, 0.5649554133415222]),\n     Row(label=1, prediction=[0.3644590675830841, 0.6355600953102112]),\n     Row(label=1, prediction=[0.33881425857543945, 0.6614755392074585]),\n     Row(label=1, prediction=[0.3894408643245697, 0.6106200218200684]),\n     Row(label=1, prediction=[0.3038020133972168, 0.6961541175842285]),\n     Row(label=1, prediction=[0.347168505191803, 0.6528571844100952]),\n     Row(label=1, prediction=[0.4466967284679413, 0.5533464550971985]),\n     Row(label=1, prediction=[0.38177400827407837, 0.6182135939598083]),\n     Row(label=1, prediction=[0.3756067454814911, 0.6243973970413208]),\n     Row(label=1, prediction=[0.3415568470954895, 0.6584869623184204]),\n     Row(label=1, prediction=[0.2507994771003723, 0.7493894696235657]),\n     Row(label=1, prediction=[0.3842267394065857, 0.6157395243644714]),\n     Row(label=1, prediction=[0.3123153746128082, 0.6878194212913513]),\n     Row(label=1, prediction=[0.3270070254802704, 0.6730873584747314]),\n     Row(label=1, prediction=[0.2774936854839325, 0.7225515246391296]),\n     Row(label=1, prediction=[0.35052162408828735, 0.6493769288063049]),\n     Row(label=1, prediction=[0.4350886940956116, 0.5648491978645325]),\n     Row(label=1, prediction=[0.3329293727874756, 0.6673209071159363]),\n     Row(label=1, prediction=[0.344948410987854, 0.655180811882019]),\n     Row(label=1, prediction=[0.34248656034469604, 0.6574580669403076]),\n     Row(label=1, prediction=[0.31624794006347656, 0.6840243935585022]),\n     Row(label=1, prediction=[0.28405067324638367, 0.7161954641342163]),\n     Row(label=1, prediction=[0.3521384000778198, 0.648004412651062]),\n     Row(label=1, prediction=[0.3765367269515991, 0.6236228942871094]),\n     Row(label=1, prediction=[0.2849416136741638, 0.7151237726211548]),\n     Row(label=1, prediction=[0.27514922618865967, 0.7249124050140381]),\n     Row(label=1, prediction=[0.38021180033683777, 0.6197392344474792]),\n     Row(label=1, prediction=[0.2833642363548279, 0.7167612910270691]),\n     Row(label=1, prediction=[0.3125302195549011, 0.6874938011169434]),\n     Row(label=1, prediction=[0.4050518870353699, 0.5948985815048218]),\n     Row(label=1, prediction=[0.3952249586582184, 0.6048775911331177]),\n     Row(label=1, prediction=[0.32268404960632324, 0.6774202585220337]),\n     Row(label=1, prediction=[0.2619391679763794, 0.7381935119628906]),\n     Row(label=1, prediction=[0.25184527039527893, 0.7483471632003784]),\n     Row(label=1, prediction=[0.4181339144706726, 0.5818472504615784]),\n     Row(label=1, prediction=[0.3146488666534424, 0.6854904890060425]),\n     Row(label=1, prediction=[0.40045425295829773, 0.5995100736618042]),\n     Row(label=1, prediction=[0.3757701516151428, 0.6242534518241882]),\n     Row(label=1, prediction=[0.34844619035720825, 0.6514830589294434]),\n     Row(label=1, prediction=[0.3664519786834717, 0.6336061358451843])]\n\n\n\n\n```python\nfrom pyspark.mllib.evaluation import MulticlassMetrics\nfrom pyspark.mllib.evaluation import BinaryClassificationMetrics\npred_and_label_test=pnl.rdd.map(lambda row: (row['label'],row['prediction']))\nmetrics=MulticlassMetrics(pred_and_label_test)\n```\n\n\n```python\npred_and_label_test.first()\n```\n\n\n\n\n    (0, [0.48643019795417786, 0.5138109922409058])\n\n\n\n\n```python\nprint(\"Accuracy: {}\".format(round(metrics.accuracy(),4)))\n```\n\n\n```python\ncausaldf=train.tail(500)\n```\n\n\n```python\ntest.where(\"label=1\").show()\n```\n\n    +-----+-------+-------+------+-------------+-----------+------+-------------+-------+-------------+----+---------------+----------------+---+----+---------+-----------+-----------+------+------+--------+---------+------------+-----------------+---------+--------+---------+------------+----------------+-------------------+------------------------+----------------+------------------------+---------------------------+---------+----+\n    |label|    uid|task_id|adv_id|creat_type_cd|adv_prim_id|dev_id|inter_type_cd|slot_id|spread_app_id|tags|app_first_class|app_second_class|age|city|city_rank|device_name|device_size|career|gender|net_type|residence|his_app_size|his_on_shelf_time|app_score|emui_dev|list_time|device_price|up_life_duration|up_membership_grade|membership_life_duration|consume_purchase|communication_onlinerate|communication_avgonline_30d|indu_name|pt_d|\n    +-----+-------+-------+------+-------------+-----------+------+-------------+-------+-------------+----+---------------+----------------+---+----+---------+-----------+-----------+------+------+--------+---------+------------+-----------------+---------+--------+---------+------------+----------------+-------------------+------------------------+----------------+------------------------+---------------------------+---------+----+\n    |    1|1005960|   2366|  3431|            3|        210|    70|            4|     21|           88|  40|              4|              25|  5| 200|        3|         88|        180|     4|     2|       3|       13|          16|                3|        2|      20|        7|           3|              18|                 -1|                      -1|               2|    1^2^3^4^5^6^7^8^9...|                         12|       27|   1|\n    |    1|1021343|   5372|  3899|            7|        109|    29|            5|     12|           86|  37|              4|              21|  5| 141|        3|         35|        117|     4|     2|       2|       37|           4|                3|        2|      20|       15|           3|              20|                 -1|                      -1|               2|    0^1^2^3^4^5^6^7^8...|                         12|       17|   1|\n    |    1|1031158|   2766|  4291|            7|        156|    56|            5|     12|           58|  37|              4|              21|  6| 127|        3|         29|        141|     4|     2|       2|       39|          14|                3|        2|      20|        9|           3|              -1|                 -1|                      -1|               2|    6^7^8^9^10^11^12^...|                         10|       17|   1|\n    |    1|1048491|   3084|  3824|            7|        150|    17|            5|     22|           11|  39|              4|              17|  6| 142|        3|         48|        349|     9|     2|       2|       35|           6|                3|        2|      14|       10|           3|              18|                 -1|                      -1|               2|    5^6^7^8^9^10^11^1...|                         11|       36|   1|\n    |    1|1048846|   3927|  3434|            6|        156|    56|            5|     18|           58|  37|              4|              21|  5| 312|        3|         74|        141|     9|     2|       2|       20|          14|                3|        2|      20|        8|           2|              -1|                 -1|                      -1|               2|    0^1^2^3^4^5^6^7^8...|                         13|       17|   1|\n    |    1|1050208|   3352|  5188|            7|        122|    18|            5|     15|           56|  18|              4|              29|  4| 110|        5|         82|        117|    10|     2|       2|       20|          16|                2|        2|      20|        9|           3|              14|                 -1|                      -1|               2|    3^4^5^6^7^8^9^10^...|                         12|       14|   1|\n    |    1|1050907|   1669|  4362|            7|        207|    17|            5|     22|           13|  37|              4|              21|  7| 416|        5|        103|        179|     4|     2|       2|       12|           4|                2|        2|      19|       12|           2|              -1|                 -1|                      -1|               2|    5^6^7^8^9^10^11^1...|                         11|       17|   1|\n    |    1|1051733|   3454|  2610|            6|        137|    37|            5|     18|           34|  13|              4|              25|  7| 333|        5|         80|        156|     9|     2|       2|       41|          17|                3|        2|      26|        7|           1|              18|                 -1|                      -1|               2|    7^8^9^10^11^12^13...|                          9|       17|   1|\n    |    1|1055837|   4923|  5514|            7|        178|    17|            5|     12|           70|  39|              4|              17|  7| 187|        4|         65|        141|     9|     2|       2|       37|           2|                3|        2|      14|       10|           2|              16|                 -1|                      -1|               2|    0^1^2^3^4^5^6^7^8...|                         13|       36|   1|\n    |    1|1057965|   3253|  5804|            8|        142|    36|            5|     12|           80|  41|              4|              26|  3| 223|        4|        103|        141|     4|     4|       3|       37|           5|                3|        2|      19|       12|           2|              20|                  1|                      -1|               5|    8^9^10^11^12^13^1...|                         10|       42|   1|\n    |    1|1058731|   1847|  6428|            7|        178|    17|            5|     12|           70|  39|              4|              17|  7| 344|        3|         26|        156|     9|     2|       2|       30|           2|                3|        2|      14|       12|           1|              -1|                 -1|                      -1|               2|    4^5^6^7^8^9^10^11...|                         11|       36|   1|\n    |    1|1062451|   5110|  6583|            7|        207|    17|            5|     12|           13|  37|              4|              21|  7| 241|        3|         99|        141|     9|     4|       2|       39|           4|                2|        2|      20|       12|           2|              -1|                 -1|                      -1|               2|    6^7^8^9^10^11^12^...|                         10|       17|   1|\n    |    1|1069830|   2567|  5472|            7|        102|    16|            5|     13|           60|  18|              4|              29|  5| 133|        3|         54|        141|     3|     4|       2|       34|          19|                2|        2|      12|        9|           3|              18|                 -1|                      -1|               5|    7^8^9^10^11^12^13...|                         11|       14|   1|\n    |    1|1071969|   1500|  5839|            7|        134|    55|            4|     17|           65|  18|              4|              29|  4| 431|        3|         32|        141|     5|     2|       2|       37|          11|                2|        2|      20|        4|           5|              20|                 -1|                      -1|               2|    6^7^8^9^10^11^12^...|                         10|       14|   1|\n    |    1|1077048|   4806|  2176|            7|        206|    64|            5|     12|           22|  39|              4|              17|  1| 187|        4|         57|        193|     9|     2|       2|       37|           4|                3|        2|      14|       13|           2|              -1|                 -1|                      -1|               2|    4^5^6^7^8^9^10^11...|                         11|       36|   1|\n    |    1|1091405|   4348|  3639|            7|        150|    17|            5|     12|           11|  39|              4|              17|  4| 374|        3|         58|        141|     9|     2|       2|       21|           6|                3|        2|      20|        7|           2|              20|                 -1|                      -1|               2|    3^4^5^6^7^8^9^10^...|                         12|       36|   1|\n    |    1|1098573|   2729|  4412|            8|        142|    36|            5|     12|           80|  41|              4|              26|  4| 403|        3|         58|        141|     4|     4|       3|       34|           5|                3|        2|      20|        7|           2|              18|                 -1|                      -1|               2|    5^6^7^8^9^10^11^1...|                         11|       42|   1|\n    |    1|1112490|   1847|  6428|            7|        178|    17|            5|     12|           70|  39|              4|              17|  1| 186|        5|         25|        141|     4|     2|       2|       39|           2|                3|        2|      12|        9|           4|              12|                 -1|                      -1|               2|    0^1^2^3^4^5^6^7^8...|                         13|       36|   1|\n    |    1|1113512|   5745|  5347|            7|        122|    60|            5|     22|           56|  18|              2|              29|  4| 286|        4|         81|        326|     6|     2|       2|       46|          -1|               -1|        1|      20|        4|           5|              18|                 -1|                      -1|               7|    1^2^3^4^5^6^7^8^9...|                         12|       24|   1|\n    |    1|1123579|   4525|  4748|            7|        147|    29|            5|     17|           86|  37|              4|              21|  4| 221|        5|         91|        310|     4|     4|       2|       12|           4|                3|        2|      27|       14|           5|              18|                 -1|                      -1|               2|    0^1^2^3^4^5^6^7^8...|                         13|       17|   1|\n    +-----+-------+-------+------+-------------+-----------+------+-------------+-------+-------------+----+---------------+----------------+---+----+---------+-----------+-----------+------+------+--------+---------+------------+-----------------+---------+--------+---------+------------+----------------+-------------------+------------------------+----------------+------------------------+---------------------------+---------+----+\n    only showing top 20 rows\n    \n\n\n\n```python\ntest1DF = test.where(\"label=1\")\nONumber = test1DF.count()\ntest0DF = test.where(\"label=0\")\nZNumber = test0DF.count()\nratio = ONumber/(ZNumber)\nsampleNormalDF = test0DF.sample(False, ratio, 10)\nunderDF = test1DF.union(sampleNormalDF)\n```\n\n\n```python\nlabel1=underDF.head(200)\nlabel0=underDF.tail(200)\n```\n\n\n```python\ndf=underDF.toPandas()\n```\n\n\n```python\ndf.to_csv('out.csv')\n```\n\nBegin from here\n\n\n```python\nfrom google.colab import drive\nimport pandas as pd\ndrive.mount('/content/drive')\ndf=pd.read_csv(\"/content/drive/MyDrive/out.csv\")\n```\n\n    Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n\n\n\n```python\nnewdf=df.sample(500)\n```\n\n\n```python\ncolname=newdf.columns\ncolname\n```\n\n\n\n\n    Index(['Unnamed: 0', 'label', 'uid', 'task_id', 'adv_id', 'creat_type_cd',\n           'adv_prim_id', 'dev_id', 'inter_type_cd', 'slot_id', 'spread_app_id',\n           'tags', 'app_first_class', 'app_second_class', 'age', 'city',\n           'city_rank', 'device_name', 'device_size', 'career', 'gender',\n           'net_type', 'residence', 'his_app_size', 'his_on_shelf_time',\n           'app_score', 'emui_dev', 'list_time', 'device_price',\n           'up_life_duration', 'up_membership_grade', 'membership_life_duration',\n           'consume_purchase', 'communication_avgonline_30d', 'indu_name', 'pt_d'],\n          dtype='object')\n\n\n\n\n```python\nnewdf\n```\n\n## Causal inference\n\n\n```python\n!apt-get install python3.8\n!pip install dowhy\n!pip install econml\n```\n\n    Reading package lists... Done\n    Building dependency tree       \n    Reading state information... Done\n    The following packages were automatically installed and are no longer required:\n      libnvidia-common-460 nsight-compute-2020.2.0\n    Use 'apt autoremove' to remove them.\n    The following additional packages will be installed:\n      libpython3.8-minimal libpython3.8-stdlib python3.8-minimal\n    Suggested packages:\n      python3.8-venv binfmt-support\n    The following NEW packages will be installed:\n      libpython3.8-minimal libpython3.8-stdlib python3.8 python3.8-minimal\n    0 upgraded, 4 newly installed, 0 to remove and 42 not upgraded.\n    Need to get 4,691 kB of archives.\n    After this operation, 18.5 MB of additional disk space will be used.\n    Get:1 http://ppa.launchpad.net/deadsnakes/ppa/ubuntu bionic/main amd64 libpython3.8-minimal amd64 3.8.13-1+bionic2 [762 kB]\n    Get:2 http://ppa.launchpad.net/deadsnakes/ppa/ubuntu bionic/main amd64 python3.8-minimal amd64 3.8.13-1+bionic2 [1,837 kB]\n    Get:3 http://ppa.launchpad.net/deadsnakes/ppa/ubuntu bionic/main amd64 libpython3.8-stdlib amd64 3.8.13-1+bionic2 [1,657 kB]\n    Get:4 http://ppa.launchpad.net/deadsnakes/ppa/ubuntu bionic/main amd64 python3.8 amd64 3.8.13-1+bionic2 [434 kB]\n    Fetched 4,691 kB in 0s (11.3 MB/s)\n    Selecting previously unselected package libpython3.8-minimal:amd64.\n    (Reading database ... 155203 files and directories currently installed.)\n    Preparing to unpack .../libpython3.8-minimal_3.8.13-1+bionic2_amd64.deb ...\n    Unpacking libpython3.8-minimal:amd64 (3.8.13-1+bionic2) ...\n    Selecting previously unselected package python3.8-minimal.\n    Preparing to unpack .../python3.8-minimal_3.8.13-1+bionic2_amd64.deb ...\n    Unpacking python3.8-minimal (3.8.13-1+bionic2) ...\n    Selecting previously unselected package libpython3.8-stdlib:amd64.\n    Preparing to unpack .../libpython3.8-stdlib_3.8.13-1+bionic2_amd64.deb ...\n    Unpacking libpython3.8-stdlib:amd64 (3.8.13-1+bionic2) ...\n    Selecting previously unselected package python3.8.\n    Preparing to unpack .../python3.8_3.8.13-1+bionic2_amd64.deb ...\n    Unpacking python3.8 (3.8.13-1+bionic2) ...\n    Setting up libpython3.8-minimal:amd64 (3.8.13-1+bionic2) ...\n    Setting up python3.8-minimal (3.8.13-1+bionic2) ...\n    Setting up libpython3.8-stdlib:amd64 (3.8.13-1+bionic2) ...\n    Setting up python3.8 (3.8.13-1+bionic2) ...\n    Processing triggers for mime-support (3.60ubuntu1) ...\n    Processing triggers for man-db (2.8.3-2ubuntu0.1) ...\n    Collecting dowhy\n      Downloading dowhy-0.7.1-py3-none-any.whl (164 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 164 kB 13.6 MB/s \n    \u001b[?25hRequirement already satisfied: sympy>=1.4 in /usr/local/lib/python3.7/dist-packages (from dowhy) (1.7.1)\n    Collecting pydot>=1.4\n      Downloading pydot-1.4.2-py2.py3-none-any.whl (21 kB)\n    Requirement already satisfied: networkx>=2.0 in /usr/local/lib/python3.7/dist-packages (from dowhy) (2.6.3)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from dowhy) (1.4.1)\n    Requirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from dowhy) (1.0.2)\n    Requirement already satisfied: numpy>=1.15 in /usr/local/lib/python3.7/dist-packages (from dowhy) (1.21.6)\n    Requirement already satisfied: statsmodels in /usr/local/lib/python3.7/dist-packages (from dowhy) (0.10.2)\n    Requirement already satisfied: pandas>=0.24 in /usr/local/lib/python3.7/dist-packages (from dowhy) (1.3.5)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->dowhy) (2.8.2)\n    Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->dowhy) (2022.1)\n    Requirement already satisfied: pyparsing>=2.1.4 in /usr/local/lib/python3.7/dist-packages (from pydot>=1.4->dowhy) (3.0.8)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas>=0.24->dowhy) (1.15.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.4->dowhy) (1.2.1)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->dowhy) (3.1.0)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->dowhy) (1.1.0)\n    Requirement already satisfied: patsy>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from statsmodels->dowhy) (0.5.2)\n    Installing collected packages: pydot, dowhy\n      Attempting uninstall: pydot\n        Found existing installation: pydot 1.3.0\n        Uninstalling pydot-1.3.0:\n          Successfully uninstalled pydot-1.3.0\n    Successfully installed dowhy-0.7.1 pydot-1.4.2\n    Collecting econml\n      Downloading econml-0.13.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (3.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.3 MB 8.4 MB/s \n    \u001b[?25hRequirement already satisfied: statsmodels>=0.10 in /usr/local/lib/python3.7/dist-packages (from econml) (0.10.2)\n    Collecting dowhy<0.7\n      Downloading dowhy-0.6-py3-none-any.whl (123 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 123 kB 48.3 MB/s \n    \u001b[?25hRequirement already satisfied: scipy>1.4.0 in /usr/local/lib/python3.7/dist-packages (from econml) (1.4.1)\n    Collecting shap<0.40.0,>=0.38.1\n      Downloading shap-0.39.0.tar.gz (356 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 356 kB 53.2 MB/s \n    \u001b[?25hRequirement already satisfied: scikit-learn>0.22.0 in /usr/local/lib/python3.7/dist-packages (from econml) (1.0.2)\n    Collecting sparse\n      Downloading sparse-0.13.0-py2.py3-none-any.whl (77 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 77 kB 6.3 MB/s \n    \u001b[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from econml) (1.21.6)\n    Requirement already satisfied: joblib>=0.13.0 in /usr/local/lib/python3.7/dist-packages (from econml) (1.1.0)\n    Requirement already satisfied: lightgbm in /usr/local/lib/python3.7/dist-packages (from econml) (2.2.3)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from econml) (1.3.5)\n    Requirement already satisfied: networkx>=2.0 in /usr/local/lib/python3.7/dist-packages (from dowhy<0.7->econml) (2.6.3)\n    Requirement already satisfied: pydot>=1.4 in /usr/local/lib/python3.7/dist-packages (from dowhy<0.7->econml) (1.4.2)\n    Requirement already satisfied: sympy>=1.4 in /usr/local/lib/python3.7/dist-packages (from dowhy<0.7->econml) (1.7.1)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->econml) (2.8.2)\n    Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas->econml) (2022.1)\n    Requirement already satisfied: pyparsing>=2.1.4 in /usr/local/lib/python3.7/dist-packages (from pydot>=1.4->dowhy<0.7->econml) (3.0.8)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas->econml) (1.15.0)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>0.22.0->econml) (3.1.0)\n    Requirement already satisfied: tqdm>4.25.0 in /usr/local/lib/python3.7/dist-packages (from shap<0.40.0,>=0.38.1->econml) (4.64.0)\n    Collecting slicer==0.0.7\n      Downloading slicer-0.0.7-py3-none-any.whl (14 kB)\n    Requirement already satisfied: numba in /usr/local/lib/python3.7/dist-packages (from shap<0.40.0,>=0.38.1->econml) (0.51.2)\n    Requirement already satisfied: cloudpickle in /usr/local/lib/python3.7/dist-packages (from shap<0.40.0,>=0.38.1->econml) (1.3.0)\n    Requirement already satisfied: patsy>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from statsmodels>=0.10->econml) (0.5.2)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.4->dowhy<0.7->econml) (1.2.1)\n    Requirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba->shap<0.40.0,>=0.38.1->econml) (0.34.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from numba->shap<0.40.0,>=0.38.1->econml) (57.4.0)\n    Building wheels for collected packages: shap\n      Building wheel for shap (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for shap: filename=shap-0.39.0-cp37-cp37m-linux_x86_64.whl size=491690 sha256=124cf569f107593a3c4428c0767a07426e3294bc69210f6d5013307ec3367399\n      Stored in directory: /root/.cache/pip/wheels/ca/25/8f/6ae5df62c32651cd719e972e738a8aaa4a87414c4d2b14c9c0\n    Successfully built shap\n    Installing collected packages: slicer, sparse, shap, dowhy, econml\n      Attempting uninstall: dowhy\n        Found existing installation: dowhy 0.7.1\n        Uninstalling dowhy-0.7.1:\n          Successfully uninstalled dowhy-0.7.1\n    Successfully installed dowhy-0.6 econml-0.13.0 shap-0.39.0 slicer-0.0.7 sparse-0.13.0\n\n\n\n```python\n!apt install libgraphviz-dev\n!pip install pygraphviz\n```\n\n    Reading package lists... Done\n    Building dependency tree       \n    Reading state information... Done\n    The following packages were automatically installed and are no longer required:\n      libnvidia-common-460 nsight-compute-2020.2.0\n    Use 'apt autoremove' to remove them.\n    The following additional packages will be installed:\n      libgail-common libgail18 libgtk2.0-0 libgtk2.0-bin libgtk2.0-common\n      libgvc6-plugins-gtk libxdot4\n    Suggested packages:\n      gvfs\n    The following NEW packages will be installed:\n      libgail-common libgail18 libgraphviz-dev libgtk2.0-0 libgtk2.0-bin\n      libgtk2.0-common libgvc6-plugins-gtk libxdot4\n    0 upgraded, 8 newly installed, 0 to remove and 42 not upgraded.\n    Need to get 2,120 kB of archives.\n    After this operation, 7,128 kB of additional disk space will be used.\n    Get:1 http://archive.ubuntu.com/ubuntu bionic/main amd64 libgtk2.0-common all 2.24.32-1ubuntu1 [125 kB]\n    Get:2 http://archive.ubuntu.com/ubuntu bionic/main amd64 libgtk2.0-0 amd64 2.24.32-1ubuntu1 [1,769 kB]\n    Get:3 http://archive.ubuntu.com/ubuntu bionic/main amd64 libgail18 amd64 2.24.32-1ubuntu1 [14.2 kB]\n    Get:4 http://archive.ubuntu.com/ubuntu bionic/main amd64 libgail-common amd64 2.24.32-1ubuntu1 [112 kB]\n    Get:5 http://archive.ubuntu.com/ubuntu bionic/universe amd64 libxdot4 amd64 2.40.1-2 [15.7 kB]\n    Get:6 http://archive.ubuntu.com/ubuntu bionic/universe amd64 libgvc6-plugins-gtk amd64 2.40.1-2 [18.2 kB]\n    Get:7 http://archive.ubuntu.com/ubuntu bionic/universe amd64 libgraphviz-dev amd64 2.40.1-2 [57.3 kB]\n    Get:8 http://archive.ubuntu.com/ubuntu bionic/main amd64 libgtk2.0-bin amd64 2.24.32-1ubuntu1 [7,536 B]\n    Fetched 2,120 kB in 1s (2,307 kB/s)\n    Selecting previously unselected package libgtk2.0-common.\n    (Reading database ... 155825 files and directories currently installed.)\n    Preparing to unpack .../0-libgtk2.0-common_2.24.32-1ubuntu1_all.deb ...\n    Unpacking libgtk2.0-common (2.24.32-1ubuntu1) ...\n    Selecting previously unselected package libgtk2.0-0:amd64.\n    Preparing to unpack .../1-libgtk2.0-0_2.24.32-1ubuntu1_amd64.deb ...\n    Unpacking libgtk2.0-0:amd64 (2.24.32-1ubuntu1) ...\n    Selecting previously unselected package libgail18:amd64.\n    Preparing to unpack .../2-libgail18_2.24.32-1ubuntu1_amd64.deb ...\n    Unpacking libgail18:amd64 (2.24.32-1ubuntu1) ...\n    Selecting previously unselected package libgail-common:amd64.\n    Preparing to unpack .../3-libgail-common_2.24.32-1ubuntu1_amd64.deb ...\n    Unpacking libgail-common:amd64 (2.24.32-1ubuntu1) ...\n    Selecting previously unselected package libxdot4.\n    Preparing to unpack .../4-libxdot4_2.40.1-2_amd64.deb ...\n    Unpacking libxdot4 (2.40.1-2) ...\n    Selecting previously unselected package libgvc6-plugins-gtk.\n    Preparing to unpack .../5-libgvc6-plugins-gtk_2.40.1-2_amd64.deb ...\n    Unpacking libgvc6-plugins-gtk (2.40.1-2) ...\n    Selecting previously unselected package libgraphviz-dev.\n    Preparing to unpack .../6-libgraphviz-dev_2.40.1-2_amd64.deb ...\n    Unpacking libgraphviz-dev (2.40.1-2) ...\n    Selecting previously unselected package libgtk2.0-bin.\n    Preparing to unpack .../7-libgtk2.0-bin_2.24.32-1ubuntu1_amd64.deb ...\n    Unpacking libgtk2.0-bin (2.24.32-1ubuntu1) ...\n    Setting up libgtk2.0-common (2.24.32-1ubuntu1) ...\n    Setting up libxdot4 (2.40.1-2) ...\n    Setting up libgtk2.0-0:amd64 (2.24.32-1ubuntu1) ...\n    Setting up libgail18:amd64 (2.24.32-1ubuntu1) ...\n    Setting up libgail-common:amd64 (2.24.32-1ubuntu1) ...\n    Setting up libgvc6-plugins-gtk (2.40.1-2) ...\n    Setting up libgraphviz-dev (2.40.1-2) ...\n    Setting up libgtk2.0-bin (2.24.32-1ubuntu1) ...\n    Processing triggers for man-db (2.8.3-2ubuntu0.1) ...\n    Processing triggers for libc-bin (2.27-3ubuntu1.3) ...\n    /sbin/ldconfig.real: /usr/local/lib/python3.7/dist-packages/ideep4py/lib/libmkldnn.so.0 is not a symbolic link\n    \n    Collecting pygraphviz\n      Downloading pygraphviz-1.7.zip (118 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 118 kB 12.4 MB/s \n    \u001b[?25hBuilding wheels for collected packages: pygraphviz\n      Building wheel for pygraphviz (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pygraphviz: filename=pygraphviz-1.7-cp37-cp37m-linux_x86_64.whl size=165751 sha256=7e36858badc9c45d73076882aeb0393860c0665b15a1b0112d99b40d93d241cb\n      Stored in directory: /root/.cache/pip/wheels/8c/bc/0c/ac35392b72556e75107ff610cb31b313e8471918a6d280e34c\n    Successfully built pygraphviz\n    Installing collected packages: pygraphviz\n    Successfully installed pygraphviz-1.7\n\n\n\n```python\n\nimport seaborn as sns\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.linear_model import LassoCV\nfrom sklearn.ensemble import GradientBoostingRegressor\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n```\n\n\n```python\nfrom dowhy import CausalModel\nimport dowhy.datasets\nimport numpy as np\nimport pandas as pd\nimport warnings\nfrom sklearn.exceptions import DataConversionWarning\nfrom IPython.display import Image, display\n\nwarnings.filterwarnings(action='ignore', category=DataConversionWarning)\nwarnings.filterwarnings(action='ignore', category=FutureWarning)\n\n# Config dict to set the logging level\nimport logging\nimport logging.config\n\nDEFAULT_LOGGING = {\n    'version': 1,\n    'disable_existing_loggers': False,\n    'loggers': {\n        '': {\n            'level': 'WARN',\n        },\n    }\n}\n\nlogging.config.dictConfig(DEFAULT_LOGGING)\nlogging.info(\"Getting started with DoWhy. Running notebook...\")\n```\n\n\n```python\ndot_graph ='digraph{ creat_type_cd->label; adv_prim_id->label;dev_id->label;inter_type_cd->label; slot_id->label; spread_app_id->label; tags->label;'\\\n      'app_first_class->label; app_second_class->label; age->label; city->label; city_rank->label;'\\\n       'device_name->label; device_size->label; career->label; gender->label; net_type->label;'\\\n       'residence->label; his_app_size->label; his_on_shelf_time->label; app_score->label;'\\\n       'emui_dev->label; list_time->label; device_price->label; up_life_duration->label;'\\\n       'up_membership_grade->label; membership_life_duration->label; consume_purchase->label;'\\\n       'communication_avgonline_30d->label; indu_name->label;'\\\n       'pt_d->label}'\n```\n\n\n```python\nmodel=CausalModel(\n        data = newdf,\n        treatment='dev_id',\n        outcome='label',\n        graph=dot_graph\n        )\nmodel.view_model()\n\n\ndisplay(Image(filename=\"causal_model.png\"))\n```\n\n\n```python\ncolname\n```\n\n\n\n\n    Index(['Unnamed: 0', 'label', 'uid', 'task_id', 'adv_id', 'creat_type_cd',\n           'adv_prim_id', 'dev_id', 'inter_type_cd', 'slot_id', 'spread_app_id',\n           'tags', 'app_first_class', 'app_second_class', 'age', 'city',\n           'city_rank', 'device_name', 'device_size', 'career', 'gender',\n           'net_type', 'residence', 'his_app_size', 'his_on_shelf_time',\n           'app_score', 'emui_dev', 'list_time', 'device_price',\n           'up_life_duration', 'up_membership_grade', 'membership_life_duration',\n           'consume_purchase', 'communication_avgonline_30d', 'indu_name', 'pt_d'],\n          dtype='object')\n\n\n\n\n```python\ntreatment_text=['creat_type_cd', 'adv_prim_id','dev_id', 'inter_type_cd', 'slot_id', 'spread_app_id', 'tags',\n       'app_first_class', 'app_second_class', 'age', 'city', 'city_rank',\n       'device_name', 'device_size', 'career', 'gender', 'net_type',\n       'residence', 'his_app_size', 'his_on_shelf_time', 'app_score',\n       'emui_dev', 'list_time', 'device_price', 'up_life_duration',\n       'up_membership_grade', 'membership_life_duration', 'consume_purchase',\n      'communication_avgonline_30d', 'indu_name',\n       'pt_d']\nnew_eff=np.zeros(np.size(treatment_text))\nestimated_eff=np.zeros(np.size(treatment_text))\n```\n\n\n```python\ntreatment_text[17]\n```\n\n\n\n\n    'residence'\n\n\n\n\n```python\nnewdf\n```\n\n\n\n\n\n  <div id=\"df-77bbc306-05c6-4bba-81e1-93ebe7c9d8ed\">\n    <div class=\"colab-df-container\">\n      <div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Unnamed: 0</th>\n      <th>label</th>\n      <th>uid</th>\n      <th>task_id</th>\n      <th>adv_id</th>\n      <th>creat_type_cd</th>\n      <th>adv_prim_id</th>\n      <th>dev_id</th>\n      <th>inter_type_cd</th>\n      <th>slot_id</th>\n      <th>...</th>\n      <th>emui_dev</th>\n      <th>list_time</th>\n      <th>device_price</th>\n      <th>up_life_duration</th>\n      <th>up_membership_grade</th>\n      <th>membership_life_duration</th>\n      <th>consume_purchase</th>\n      <th>communication_avgonline_30d</th>\n      <th>indu_name</th>\n      <th>pt_d</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>4304</th>\n      <td>4304</td>\n      <td>1</td>\n      <td>1415478</td>\n      <td>1086</td>\n      <td>6422</td>\n      <td>3</td>\n      <td>142</td>\n      <td>36</td>\n      <td>5</td>\n      <td>17</td>\n      <td>...</td>\n      <td>27</td>\n      <td>12</td>\n      <td>4</td>\n      <td>16</td>\n      <td>-1</td>\n      <td>-1</td>\n      <td>2</td>\n      <td>11</td>\n      <td>42</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>11037</th>\n      <td>11037</td>\n      <td>0</td>\n      <td>1581804</td>\n      <td>3434</td>\n      <td>3412</td>\n      <td>7</td>\n      <td>156</td>\n      <td>60</td>\n      <td>5</td>\n      <td>13</td>\n      <td>...</td>\n      <td>12</td>\n      <td>9</td>\n      <td>3</td>\n      <td>20</td>\n      <td>1</td>\n      <td>-1</td>\n      <td>2</td>\n      <td>13</td>\n      <td>24</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>11412</th>\n      <td>11412</td>\n      <td>0</td>\n      <td>1050663</td>\n      <td>2361</td>\n      <td>5555</td>\n      <td>3</td>\n      <td>142</td>\n      <td>36</td>\n      <td>5</td>\n      <td>17</td>\n      <td>...</td>\n      <td>20</td>\n      <td>8</td>\n      <td>4</td>\n      <td>18</td>\n      <td>-1</td>\n      <td>-1</td>\n      <td>2</td>\n      <td>13</td>\n      <td>42</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>5480</th>\n      <td>5480</td>\n      <td>1</td>\n      <td>1869584</td>\n      <td>4335</td>\n      <td>5710</td>\n      <td>6</td>\n      <td>150</td>\n      <td>17</td>\n      <td>5</td>\n      <td>18</td>\n      <td>...</td>\n      <td>14</td>\n      <td>14</td>\n      <td>2</td>\n      <td>9</td>\n      <td>-1</td>\n      <td>-1</td>\n      <td>2</td>\n      <td>7</td>\n      <td>36</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>9397</th>\n      <td>9397</td>\n      <td>0</td>\n      <td>1924985</td>\n      <td>5946</td>\n      <td>1657</td>\n      <td>7</td>\n      <td>110</td>\n      <td>38</td>\n      <td>5</td>\n      <td>17</td>\n      <td>...</td>\n      <td>12</td>\n      <td>9</td>\n      <td>3</td>\n      <td>20</td>\n      <td>-1</td>\n      <td>-1</td>\n      <td>2</td>\n      <td>12</td>\n      <td>30</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>3143</th>\n      <td>3143</td>\n      <td>1</td>\n      <td>1833387</td>\n      <td>2389</td>\n      <td>5768</td>\n      <td>7</td>\n      <td>177</td>\n      <td>56</td>\n      <td>5</td>\n      <td>12</td>\n      <td>...</td>\n      <td>20</td>\n      <td>16</td>\n      <td>1</td>\n      <td>14</td>\n      <td>-1</td>\n      <td>-1</td>\n      <td>2</td>\n      <td>13</td>\n      <td>17</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>7368</th>\n      <td>7368</td>\n      <td>0</td>\n      <td>2094224</td>\n      <td>2211</td>\n      <td>4079</td>\n      <td>8</td>\n      <td>142</td>\n      <td>60</td>\n      <td>5</td>\n      <td>17</td>\n      <td>...</td>\n      <td>20</td>\n      <td>4</td>\n      <td>4</td>\n      <td>-1</td>\n      <td>-1</td>\n      <td>-1</td>\n      <td>2</td>\n      <td>12</td>\n      <td>42</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>12365</th>\n      <td>12365</td>\n      <td>0</td>\n      <td>1602443</td>\n      <td>2183</td>\n      <td>4262</td>\n      <td>7</td>\n      <td>207</td>\n      <td>17</td>\n      <td>5</td>\n      <td>16</td>\n      <td>...</td>\n      <td>14</td>\n      <td>8</td>\n      <td>4</td>\n      <td>-1</td>\n      <td>-1</td>\n      <td>-1</td>\n      <td>2</td>\n      <td>11</td>\n      <td>17</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>12809</th>\n      <td>12809</td>\n      <td>0</td>\n      <td>1647397</td>\n      <td>2269</td>\n      <td>2674</td>\n      <td>7</td>\n      <td>144</td>\n      <td>43</td>\n      <td>5</td>\n      <td>16</td>\n      <td>...</td>\n      <td>12</td>\n      <td>9</td>\n      <td>4</td>\n      <td>20</td>\n      <td>-1</td>\n      <td>-1</td>\n      <td>2</td>\n      <td>10</td>\n      <td>18</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>9413</th>\n      <td>9413</td>\n      <td>0</td>\n      <td>2097968</td>\n      <td>4683</td>\n      <td>4353</td>\n      <td>7</td>\n      <td>207</td>\n      <td>17</td>\n      <td>5</td>\n      <td>17</td>\n      <td>...</td>\n      <td>20</td>\n      <td>4</td>\n      <td>4</td>\n      <td>-1</td>\n      <td>-1</td>\n      <td>-1</td>\n      <td>2</td>\n      <td>12</td>\n      <td>17</td>\n      <td>4</td>\n    </tr>\n  </tbody>\n</table>\n<p>500 rows \u00d7 36 columns</p>\n</div>\n      <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-77bbc306-05c6-4bba-81e1-93ebe7c9d8ed')\"\n              title=\"Convert this dataframe to an interactive table.\"\n              style=\"display:none;\">\n\n  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n       width=\"24px\">\n    <path d=\"M0 0h24v24H0V0z\" fill=\"none\"/>\n    <path d=\"M18.56 5.44l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94zm-11 1L8.5 8.5l.94-2.06 2.06-.94-2.06-.94L8.5 2.5l-.94 2.06-2.06.94zm10 10l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94z\"/><path d=\"M17.41 7.96l-1.37-1.37c-.4-.4-.92-.59-1.43-.59-.52 0-1.04.2-1.43.59L10.3 9.45l-7.72 7.72c-.78.78-.78 2.05 0 2.83L4 21.41c.39.39.9.59 1.41.59.51 0 1.02-.2 1.41-.59l7.78-7.78 2.81-2.81c.8-.78.8-2.07 0-2.86zM5.41 20L4 18.59l7.72-7.72 1.47 1.35L5.41 20z\"/>\n  </svg>\n      </button>\n\n  <style>\n    .colab-df-container {\n      display:flex;\n      flex-wrap:wrap;\n      gap: 12px;\n    }\n\n    .colab-df-convert {\n      background-color: #E8F0FE;\n      border: none;\n      border-radius: 50%;\n      cursor: pointer;\n      display: none;\n      fill: #1967D2;\n      height: 32px;\n      padding: 0 0 0 0;\n      width: 32px;\n    }\n\n    .colab-df-convert:hover {\n      background-color: #E2EBFA;\n      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n      fill: #174EA6;\n    }\n\n    [theme=dark] .colab-df-convert {\n      background-color: #3B4455;\n      fill: #D2E3FC;\n    }\n\n    [theme=dark] .colab-df-convert:hover {\n      background-color: #434B5C;\n      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n      fill: #FFFFFF;\n    }\n  </style>\n\n      \n    </div>\n  </div>\n\n\n\n\n\n```python\n\nfor i in range(np.size(treatment_text)):\n\n  model=CausalModel(\n        data = newdf,\n        treatment=treatment_text[i],\n        outcome='label',\n        graph=dot_graph\n        )\n\n  #model.view_model()\n  \n  identified_estimand = model.identify_effect(proceed_when_unidentifiable=True)\n  causal_estimate = model.estimate_effect(identified_estimand, method_name=\"backdoor.linear_regression\", test_significance=True)\n  refutation = model.refute_estimate(identified_estimand, causal_estimate, method_name=\"placebo_treatment_refuter\",\n                                  placebo_type=\"permute\", num_simulations=20)\n  new_eff[i]=refutation.new_effect\n  estimated_eff[i]=refutation.estimated_effect\n```\n\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.\n                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.\n\n\n\n```python\nnew_eff\n```\n\n\n\n\n    array([ 1.85051262e-03,  1.97317258e-04, -6.50943336e-05,  8.44171745e-03,\n            1.07534155e-03, -1.61600666e-04,  9.38159901e-04,  2.21842221e-05,\n            5.24682463e-04,  1.38286094e-04,  4.51139090e-05,  2.96671105e-03,\n           -2.13845536e-05,  6.37596294e-05,  5.20486095e-04, -4.00457901e-03,\n           -6.43960776e-03, -7.55514088e-05,  3.66855616e-04, -3.82475201e-03,\n            3.23887497e-02,  9.16059036e-04, -1.35593824e-03,  7.65485729e-03,\n           -1.15509021e-05,  7.62754669e-03, -2.53000000e-01, -1.72404139e-04,\n            2.68059594e-03, -1.41627516e-04,  5.93746195e-04])\n\n\n\n\n```python\nestimated_eff\n```\n\n\n\n\n    array([-1.25407031e-01,  9.54758370e-04,  1.69014337e-03, -1.50366670e-01,\n           -2.04495392e-02, -1.03014163e-03,  1.96834370e-02, -2.17918760e-01,\n           -1.65467245e-02,  1.11968646e-02, -8.30554114e-05,  6.73745830e-03,\n            3.02232926e-04,  5.01179532e-04,  6.34401536e-03, -4.46255823e-03,\n            1.25276807e-01, -4.32226020e-03, -1.89124171e-02, -6.85651026e-02,\n           -5.54579983e-01,  4.81502781e-03,  5.01780352e-03, -5.18583374e-02,\n           -8.25663621e-03, -2.15562856e-01, -2.53000000e-01, -7.76170961e-02,\n           -1.68958518e-02,  5.34393756e-04, -6.95323359e-03])\n\n\n\n\n```python\nesti=np.array([[ -1.25407031e-01,  9.54758370e-04,  1.69014337e-03, -1.50366670e-01,\n       -2.04495392e-02, -1.03014163e-03,  1.96834370e-02, -2.17918760e-01,\n       -1.65467245e-02,  1.11968646e-02, -8.30554114e-05,  6.73745830e-03,\n        3.02232926e-04,  5.01179532e-04,  6.34401536e-03, -4.46255823e-03,\n        1.25276807e-01, -4.32226020e-03, -1.89124171e-02, -6.85651026e-02,\n       -5.54579983e-01,  4.81502781e-03,  5.01780352e-03, -5.18583374e-02,\n       -8.25663621e-03, -2.15562856e-01, -2.53000000e-01, -7.76170961e-02,\n       -1.68958518e-02,  5.34393756e-04, -6.95323359e-03]])\ntemp1=np.array([[-3.95882099e-03, -4.66659267e-06, -4.21405471e-04,  1.23255969e-02,\n        1.85940860e-03, -2.61284366e-05, -2.67626125e-04, -5.82750753e-03,\n       -5.96268729e-04, -3.17372067e-03, -4.50965237e-05, -3.56438003e-03,\n       -3.85690149e-04, -4.15316534e-05,  4.25053266e-04,  6.52150841e-03,\n        2.99792017e-03, -1.21687536e-04, -1.73264209e-03, -1.22474376e-03,\n        1.88035109e-02,  1.80307122e-04, -1.11190353e-03, -3.17669065e-03,\n       -1.57626893e-04, -2.46548740e-02, -2.32491774e-03, -1.00404172e-02,\n       -1.73578584e-03, -2.17642774e-04, -5.15371262e-03]])\ntemp2=np.array([[-5.13568769e-03,  1.11251909e-04,  2.52886160e-04, -4.70316312e-03,\n        2.03130621e-04, -2.66889834e-04, -1.20073312e-03,  1.91978516e-02,\n        1.84530408e-03, -2.51696959e-03,  5.31683021e-05,  3.92749725e-03,\n        2.15096642e-04, -3.17559458e-05,  7.84156517e-04,  2.08362394e-03,\n       -1.64371682e-02, -9.36470244e-05,  1.25647337e-04,  3.01368521e-03,\n       -2.11040653e-02,  5.50563565e-04, -3.47901718e-04, -8.50737089e-04,\n       -2.67273135e-04,  9.26754290e-03, -2.53000000e-01,  2.86352869e-03,\n       -9.63604513e-03,  2.69180907e-04,  6.33667118e-04]])\ntemp3=np.array([[4.62308046e-03,  2.94010200e-05,  8.27119272e-05,  1.82118572e-02,\n        2.31259104e-03,  1.11585468e-04, -5.31740896e-05,  1.05423219e-02,\n        5.15761987e-04, -3.23184651e-03,  4.07299827e-05,  4.23483372e-03,\n        2.75051560e-04,  1.90333716e-05,  1.28504986e-03,  4.82726772e-03,\n        9.63402019e-03,  8.02643567e-04,  2.18766108e-04, -8.11014785e-04,\n       -4.14341305e-03,  3.63748870e-04, -7.89844258e-04,  4.14262307e-03,\n        5.85744820e-04, -3.49885824e-03, -2.53000000e-01, -2.46165747e-03,\n       -7.24279299e-03,  4.91517328e-04,  3.80035294e-04]])\ntemp4=np.array([[8.19948092e-03,  2.70296366e-04, -2.13071565e-05, -1.55584211e-03,\n       -1.27000677e-03,  4.42311104e-04, -2.05038643e-04, -5.64398967e-04,\n        1.20835598e-03,  4.18174100e-04, -4.02581223e-05, -2.42182156e-03,\n        3.04330004e-05, -1.22702925e-05,  3.73623371e-03, -5.83271197e-03,\n        8.58669503e-03,  4.84535070e-07, -2.80559565e-04, -2.13003642e-03,\n       -1.22997025e-02, -2.00658067e-03,  2.24004621e-03,  2.62692705e-03,\n        3.86386951e-04,  2.53236587e-03, -2.53000000e-01,  8.21257885e-03,\n        5.99009241e-03, -7.00401553e-04, -1.71791942e-03]])\ntemp5=np.array([[3.26616492e-03, -2.12709788e-04,  2.44074735e-04,  1.20924757e-02,\n       -5.41271121e-04,  1.02551074e-04,  7.37526347e-05, -3.33526967e-03,\n       -1.14035419e-03,  4.48025375e-03, -5.30477860e-05, -6.14362326e-03,\n        1.13962022e-04,  2.33367000e-05,  2.21835087e-04, -9.75754233e-03,\n        2.46359337e-02,  6.41704804e-04,  6.48624966e-04, -1.82809077e-03,\n        1.33500818e-02, -3.95171826e-04, -2.20761870e-03,  2.44348856e-03,\n        4.15567792e-04, -1.53862516e-02, -2.53000000e-01, -4.50314612e-03,\n        5.44230191e-03,  3.21318950e-04,  1.08796049e-03]])\ntemp6=np.array([[6.75787031e-04,  2.79444340e-04, -5.11250564e-04,  1.24023637e-02,\n       -2.72751294e-04, -3.77635581e-05, -3.60550899e-04,  5.45898167e-03,\n        4.05431483e-04, -1.68357431e-05,  7.04512058e-05, -5.54614105e-03,\n        1.49132246e-05,  2.50355941e-04, -1.96362301e-03,  4.86567559e-03,\n        2.90147602e-03,  1.20981049e-04, -6.01744123e-05,  1.44118527e-03,\n        3.95823925e-03,  1.98729358e-03,  1.58894254e-04, -5.61247184e-04,\n       -6.18752563e-05, -6.02034472e-03, -2.53000000e-01,  1.17471636e-02,\n       -9.31948713e-04,  8.26637405e-06,  1.18523904e-03]])\ntemp7=np.array([[-6.12200622e-04,  3.94015750e-05,  2.85378035e-04, -1.16604419e-02,\n       -2.49400080e-03,  1.43006970e-04,  1.20418076e-04,  3.25778134e-03,\n        1.62112770e-03,  4.54979098e-03,  1.32118425e-05, -5.77109316e-03,\n        5.43310001e-04, -1.18109305e-04,  3.05631402e-03,  8.45062895e-03,\n       -1.05381705e-03, -1.47415988e-04,  5.60856351e-04,  2.95134889e-03,\n       -1.90492870e-03,  1.82741936e-04, -5.65070807e-04, -2.05551676e-03,\n       -6.87224986e-05,  2.69841642e-03, -2.53000000e-01, -3.47152701e-03,\n       -5.22679783e-04,  4.44272962e-04,  1.54248357e-03]])\ntemp8=np.array([[-1.25040082e-04,  9.36662804e-05, -4.58259282e-04,  2.25293555e-03,\n       -9.64809249e-05, -2.11656169e-04,  3.87082629e-04,  4.52881161e-03,\n       -1.80417962e-03, -2.94571075e-03, -6.37174266e-05,  3.18895726e-03,\n       -6.77016836e-05,  1.49955874e-04,  1.17012098e-03, -7.57361800e-04,\n        1.33600684e-02,  3.17748384e-04, -8.58580529e-04, -1.24032496e-03,\n       -2.36054122e-02, -4.28701968e-05, -1.51729342e-03, -7.82203906e-03,\n       -3.34817987e-04,  1.42872327e-02, -2.53000000e-01, -5.86147897e-03,\n        8.98738673e-04, -4.95154930e-04, -2.16849324e-03]])\ntemp9=np.array([[6.13165417e-04, -1.38604929e-04,  1.02711733e-04,  1.32257774e-03,\n       -3.94980953e-03,  3.49285742e-05,  3.47058271e-04,  2.23763543e-03,\n       -3.88260304e-04, -2.63662608e-03, -3.09547914e-05, -1.12136564e-02,\n       -3.80801650e-05, -8.50954133e-06, -1.31002587e-03, -3.28475938e-03,\n       -5.04435206e-03,  3.31508483e-04, -7.21290441e-04, -7.39462008e-04,\n        1.06386879e-02, -1.42814628e-03,  3.15383261e-04, -2.24442828e-04,\n       -7.08322844e-04, -6.61264348e-03, -2.53000000e-01,  3.29544213e-03,\n        4.43189035e-03, -3.73547044e-04,  2.61250316e-03]])\ntemp10=np.array([[6.06257449e-03,  1.59090475e-04, -5.03650486e-05, -7.01832176e-03,\n       -1.48479355e-03, -2.12214256e-04,  7.88694610e-04,  1.42326569e-03,\n       -9.18343437e-04,  7.52790320e-04,  4.05356588e-05, -9.47388873e-03,\n       -5.21553365e-04, -3.81215406e-06, -2.41023233e-03,  6.22760253e-04,\n        2.86706023e-03,  4.52418144e-04, -5.30228137e-05, -3.42583260e-03,\n        8.17861839e-03, -9.46112455e-04, -1.22222953e-03,  2.43424202e-03,\n        4.54962281e-04,  4.69362514e-03, -2.53000000e-01,  8.43248571e-03,\n       -2.30743937e-03, -2.19323713e-05, -2.58388240e-04]])\ntemp11=np.array([[5.20727043e-03, -1.11600175e-04,  2.05236302e-04,  2.06151027e-02,\n       -1.44655639e-03,  1.70824213e-04,  4.76533680e-04, -6.13391734e-03,\n        1.38261758e-04, -6.97785527e-03,  3.49757591e-05, -1.15535033e-02,\n        8.07346509e-05, -3.10124810e-04, -1.98368078e-03,  1.36716731e-04,\n        1.37699202e-02, -6.82440372e-04, -4.20939626e-04, -2.61503504e-03,\n       -1.33185599e-02,  2.43835983e-05, -3.05688440e-04,  3.29075447e-04,\n        1.35935974e-03, -1.22569353e-02, -2.53000000e-01, -2.58235202e-03,\n        1.00662604e-03,  1.68857134e-04, -4.15880386e-03]])\ntemp12=np.array([[8.87154494e-03,  1.03414865e-04, -2.53350184e-04, -5.07550192e-03,\n        3.14038105e-03, -8.27406803e-05,  9.28146341e-04,  6.04155126e-03,\n        1.51758364e-04, -2.83876671e-03, -6.86879914e-05,  6.87052689e-03,\n        1.25236603e-04, -2.50829645e-04, -5.71960965e-03,  1.16923147e-02,\n       -2.75899173e-02,  3.11839752e-04,  1.51569618e-04,  4.43406816e-04,\n        1.75068680e-03,  1.38156464e-03,  3.18978978e-04, -4.69308328e-03,\n        8.61978208e-04, -1.36511678e-03, -2.53000000e-01,  1.60103456e-03,\n        4.65390439e-03,  1.17428669e-04, -2.94553263e-03]])\ntemp13=np.array([[2.69191423e-03, -1.70184863e-04,  4.75432475e-06,  2.45969070e-03,\n       -2.75127889e-03, -1.51902045e-04,  9.05777088e-04, -8.03013087e-03,\n       -7.13074867e-05,  6.83322762e-04, -4.49623980e-05, -9.90802703e-03,\n        3.65774932e-04, -1.18846612e-04,  5.26875390e-04, -2.47248693e-05,\n       -1.11476032e-02, -9.20778256e-04,  1.75043130e-03, -8.55975267e-03,\n        1.78223601e-02, -3.00331787e-04,  1.25915644e-03,  1.90680428e-03,\n        6.10981017e-04,  3.21990320e-03, -2.53000000e-01, -5.27863083e-03,\n        9.57789744e-04,  6.02922062e-05,  4.64208388e-03]])\ntemp14=np.array([[-3.09415577e-03, -6.85573075e-05,  3.15001225e-04,  1.58435708e-02,\n       -1.59211971e-05, -8.91814811e-05, -1.38201267e-03, -1.02863038e-02,\n       -1.75934914e-03,  3.56376029e-04,  3.80139960e-05,  5.04549284e-03,\n        5.89149472e-04, -3.20284081e-05,  1.89112465e-03,  1.65054831e-03,\n        4.25240613e-03,  1.86251970e-04, -9.09819710e-04,  6.23864209e-03,\n       -1.91896929e-02, -1.54508943e-05,  2.55044414e-04,  2.95604892e-03,\n        6.70444540e-05, -4.98741896e-03, -2.53000000e-01, -9.56415119e-03,\n       -2.79941221e-03, -1.71941776e-04,  5.51841426e-04]])\ntemp15=np.array([[1.24589529e-03,  2.51956958e-04, -6.10726572e-05,  9.61558010e-03,\n       -4.89223326e-04, -2.69813180e-04,  1.65122894e-04,  9.78553020e-03,\n        1.19529890e-03,  1.53348352e-04, -4.15773931e-05,  5.79146162e-03,\n       -1.19720023e-04, -6.47891649e-05,  5.59929193e-04,  4.59241048e-03,\n        2.96659379e-03, -2.71103579e-04,  3.16379826e-04,  4.31599019e-03,\n       -2.97683726e-03,  5.97747852e-04,  1.75118867e-03,  2.88346389e-03,\n       -2.55027565e-04,  1.99917566e-03, -2.53000000e-01,  1.55194066e-03,\n        1.80318044e-03,  1.11156109e-04,  1.75785482e-03]])\ntemp16=np.array([[-5.36049786e-03,  1.79828396e-04, -7.79612825e-05,  6.93945342e-03,\n       -2.57405791e-03,  2.79582090e-04, -1.34489626e-04,  6.52161406e-04,\n       -8.37534848e-04,  2.75099601e-03, -3.81977431e-05, -1.24071926e-02,\n       -1.07142140e-04, -1.94189348e-04, -1.75077194e-03, -2.44561632e-04,\n       -1.18481134e-02,  1.86831069e-04, -1.59686002e-03,  3.10651243e-04,\n        2.46187568e-02, -1.02086083e-03,  5.64031669e-04,  4.03951871e-03,\n       -5.78318019e-04, -5.14974620e-03, -2.53000000e-01,  3.48695297e-03,\n       -1.52267857e-03,  1.69443537e-04, -2.77500082e-03]])\ntemp17=np.array([[2.22861391e-03, -1.41233798e-04, -3.36037712e-04, -1.72022223e-03,\n        6.23095436e-04, -2.01134533e-04, -6.49274662e-04,  5.52650456e-04,\n       -8.46987439e-04,  1.34690633e-03, -2.28913177e-05,  1.69473235e-03,\n       -2.88861263e-04,  2.03495385e-04,  7.58770520e-04, -5.54913184e-03,\n       -2.70152897e-02,  5.14893493e-04, -5.22421505e-04, -1.41262552e-03,\n        2.65789556e-03,  1.91503073e-03, -1.33172708e-03, -4.78376213e-03,\n        6.93744590e-04, -2.05644308e-02, -2.53000000e-01,  1.37005660e-02,\n       -4.05947372e-03, -2.05547325e-04, -7.02582759e-03]])\ntemp18=np.array([[8.92631976e-03, -8.51930437e-05, -1.00348714e-04, -9.10722886e-03,\n        3.72803506e-03, -1.47715077e-04, -1.22298199e-04, -1.09872452e-02,\n        4.50454557e-04, -2.73695830e-03, -6.38716093e-05, -2.13926968e-03,\n        3.78806031e-05,  1.13108329e-04, -4.16795838e-03,  5.12834088e-04,\n       -2.01341034e-02,  9.77929874e-04, -2.50822867e-04,  1.60091774e-04,\n        2.30565010e-03, -1.28847558e-03,  6.88306405e-04,  1.28870413e-03,\n        1.36582988e-03,  1.58172828e-02, -2.53000000e-01,  3.90524428e-03,\n       -4.03485194e-03, -2.73483692e-04, -1.51470098e-03]])\ntemp19=np.array([[-3.17133927e-03, -1.74541419e-04,  4.77493020e-04, -1.40714047e-02,\n        1.79249147e-03, -8.36497210e-05, -1.74272285e-03, -2.44309136e-03,\n        1.00781202e-03,  1.19314947e-03,  8.15771698e-05, -8.11243492e-03,\n       -3.52860472e-04,  1.01584016e-04, -3.37448830e-04, -3.50392959e-03,\n        6.32031829e-03,  4.07811346e-04,  2.67596177e-04, -2.90825040e-03,\n       -9.84932380e-03, -6.54722283e-04, -1.53873998e-03,  2.85144910e-04,\n        4.47015646e-04,  7.92134085e-04, -2.53000000e-01,  6.97155211e-03,\n       -6.92720280e-04,  5.17629768e-04, -1.40729152e-03]])\ntemp20=np.array([[1.85051262e-03,  1.97317258e-04, -6.50943336e-05,  8.44171745e-03,\n        1.07534155e-03, -1.61600666e-04,  9.38159901e-04,  2.21842221e-05,\n        5.24682463e-04,  1.38286094e-04,  4.51139090e-05,  2.96671105e-03,\n       -2.13845536e-05,  6.37596294e-05,  5.20486095e-04, -4.00457901e-03,\n       -6.43960776e-03, -7.55514088e-05,  3.66855616e-04, -3.82475201e-03,\n        3.23887497e-02,  9.16059036e-04, -1.35593824e-03,  7.65485729e-03,\n       -1.15509021e-05,  7.62754669e-03, -2.53000000e-01, -1.72404139e-04,\n        2.68059594e-03, -1.41627516e-04,  5.93746195e-04]])\n```\n\n\n```python\n new_data=np.concatenate((temp1,temp2,temp3,temp4,temp5,temp6,temp7,temp8,temp9,temp10,temp11,temp12,temp13,temp14,temp15,temp16,temp17,temp18,temp19,temp20),axis=0)\n```\n\n\n```python\nnew_data=pd.DataFrame(new_data,columns =range(1,32))\n```\n\n\n```python\nplt.figure(figsize=(15,6))\nnew_data.boxplot()\nplt.scatter(range(1,32),esti,marker='o',c='r',label='Estimated effect')\nplt.legend()\n```\n", "meta": {"hexsha": "f880b325567d27de05424165aa883968ebde793b", "size": 362328, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "DL.ipynb", "max_stars_repo_name": "Zhenz2020/Zhenz2020.github.io", "max_stars_repo_head_hexsha": "b390ba52d64c26bd8ad2b0de4226d4a5ae52616a", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DL.ipynb", "max_issues_repo_name": "Zhenz2020/Zhenz2020.github.io", "max_issues_repo_head_hexsha": "b390ba52d64c26bd8ad2b0de4226d4a5ae52616a", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DL.ipynb", "max_forks_repo_name": "Zhenz2020/Zhenz2020.github.io", "max_forks_repo_head_hexsha": "b390ba52d64c26bd8ad2b0de4226d4a5ae52616a", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 162.1154362416, "max_line_length": 220213, "alphanum_fraction": 0.7984367755, "converted": true, "num_tokens": 27138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.060975186410757824, "lm_q1q2_score": 0.024150330269926717}}
{"text": "## Grid-aware spatial operations using xgcm\n\n### ROMS grid\n\n* ROMS variables are staggered according to the Arakawa C-grid \n\n\n\n<div>\n\n\n<p>source:<a href=\"https://www.myroms.org/wiki/Numerical_Solution_Technique\">myroms.org</a>, <a href=\"https://doi.org/10.1016/j.jcp.2011.11.025\">Rajpoot et al. (2012)</a></p>\n</div>\n\nWe open a sample ROMS model output, using xarray, as usual.\n\n\n```python\nimport xarray as xr\nimport xgcm\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfile = '/scratch/training/python_geos/data/ROMS/roms_test.nc'\nds = xr.open_dataset(file)\nds\n```\n\n\n\n\n<div><svg style=\"position: absolute; width: 0; height: 0; overflow: hidden\">\n<defs>\n<symbol id=\"icon-database\" viewBox=\"0 0 32 32\">\n<path d=\"M16 0c-8.837 0-16 2.239-16 5v4c0 2.761 7.163 5 16 5s16-2.239 16-5v-4c0-2.761-7.163-5-16-5z\"></path>\n<path d=\"M16 17c-8.837 0-16-2.239-16-5v6c0 2.761 7.163 5 16 5s16-2.239 16-5v-6c0 2.761-7.163 5-16 5z\"></path>\n<path d=\"M16 26c-8.837 0-16-2.239-16-5v6c0 2.761 7.163 5 16 5s16-2.239 16-5v-6c0 2.761-7.163 5-16 5z\"></path>\n</symbol>\n<symbol id=\"icon-file-text2\" viewBox=\"0 0 32 32\">\n<path d=\"M28.681 7.159c-0.694-0.947-1.662-2.053-2.724-3.116s-2.169-2.030-3.116-2.724c-1.612-1.182-2.393-1.319-2.841-1.319h-15.5c-1.378 0-2.5 1.121-2.5 2.5v27c0 1.378 1.122 2.5 2.5 2.5h23c1.378 0 2.5-1.122 2.5-2.5v-19.5c0-0.448-0.137-1.23-1.319-2.841zM24.543 5.457c0.959 0.959 1.712 1.825 2.268 2.543h-4.811v-4.811c0.718 0.556 1.584 1.309 2.543 2.268zM28 29.5c0 0.271-0.229 0.5-0.5 0.5h-23c-0.271 0-0.5-0.229-0.5-0.5v-27c0-0.271 0.229-0.5 0.5-0.5 0 0 15.499-0 15.5 0v7c0 0.552 0.448 1 1 1h7v19.5z\"></path>\n<path d=\"M23 26h-14c-0.552 0-1-0.448-1-1s0.448-1 1-1h14c0.552 0 1 0.448 1 1s-0.448 1-1 1z\"></path>\n<path d=\"M23 22h-14c-0.552 0-1-0.448-1-1s0.448-1 1-1h14c0.552 0 1 0.448 1 1s-0.448 1-1 1z\"></path>\n<path d=\"M23 18h-14c-0.552 0-1-0.448-1-1s0.448-1 1-1h14c0.552 0 1 0.448 1 1s-0.448 1-1 1z\"></path>\n</symbol>\n</defs>\n</svg>\n<style>/* CSS stylesheet for displaying xarray objects in jupyterlab.\n *\n */\n\n:root {\n  --xr-font-color0: var(--jp-content-font-color0, rgba(0, 0, 0, 1));\n  --xr-font-color2: var(--jp-content-font-color2, rgba(0, 0, 0, 0.54));\n  --xr-font-color3: var(--jp-content-font-color3, rgba(0, 0, 0, 0.38));\n  --xr-border-color: var(--jp-border-color2, #e0e0e0);\n  --xr-disabled-color: var(--jp-layout-color3, #bdbdbd);\n  --xr-background-color: var(--jp-layout-color0, white);\n  --xr-background-color-row-even: var(--jp-layout-color1, white);\n  --xr-background-color-row-odd: var(--jp-layout-color2, #eeeeee);\n}\n\nhtml[theme=dark],\nbody.vscode-dark {\n  --xr-font-color0: rgba(255, 255, 255, 1);\n  --xr-font-color2: rgba(255, 255, 255, 0.54);\n  --xr-font-color3: rgba(255, 255, 255, 0.38);\n  --xr-border-color: #1F1F1F;\n  --xr-disabled-color: #515151;\n  --xr-background-color: #111111;\n  --xr-background-color-row-even: #111111;\n  --xr-background-color-row-odd: #313131;\n}\n\n.xr-wrap {\n  display: block;\n  min-width: 300px;\n  max-width: 700px;\n}\n\n.xr-text-repr-fallback {\n  /* fallback to plain text repr when CSS is not injected (untrusted notebook) */\n  display: none;\n}\n\n.xr-header {\n  padding-top: 6px;\n  padding-bottom: 6px;\n  margin-bottom: 4px;\n  border-bottom: solid 1px var(--xr-border-color);\n}\n\n.xr-header > div,\n.xr-header > ul {\n  display: inline;\n  margin-top: 0;\n  margin-bottom: 0;\n}\n\n.xr-obj-type,\n.xr-array-name {\n  margin-left: 2px;\n  margin-right: 10px;\n}\n\n.xr-obj-type {\n  color: var(--xr-font-color2);\n}\n\n.xr-sections {\n  padding-left: 0 !important;\n  display: grid;\n  grid-template-columns: 150px auto auto 1fr 20px 20px;\n}\n\n.xr-section-item {\n  display: contents;\n}\n\n.xr-section-item input {\n  display: none;\n}\n\n.xr-section-item input + label {\n  color: var(--xr-disabled-color);\n}\n\n.xr-section-item input:enabled + label {\n  cursor: pointer;\n  color: var(--xr-font-color2);\n}\n\n.xr-section-item input:enabled + label:hover {\n  color: var(--xr-font-color0);\n}\n\n.xr-section-summary {\n  grid-column: 1;\n  color: var(--xr-font-color2);\n  font-weight: 500;\n}\n\n.xr-section-summary > span {\n  display: inline-block;\n  padding-left: 0.5em;\n}\n\n.xr-section-summary-in:disabled + label {\n  color: var(--xr-font-color2);\n}\n\n.xr-section-summary-in + label:before {\n  display: inline-block;\n  content: '\u25ba';\n  font-size: 11px;\n  width: 15px;\n  text-align: center;\n}\n\n.xr-section-summary-in:disabled + label:before {\n  color: var(--xr-disabled-color);\n}\n\n.xr-section-summary-in:checked + label:before {\n  content: '\u25bc';\n}\n\n.xr-section-summary-in:checked + label > span {\n  display: none;\n}\n\n.xr-section-summary,\n.xr-section-inline-details {\n  padding-top: 4px;\n  padding-bottom: 4px;\n}\n\n.xr-section-inline-details {\n  grid-column: 2 / -1;\n}\n\n.xr-section-details {\n  display: none;\n  grid-column: 1 / -1;\n  margin-bottom: 5px;\n}\n\n.xr-section-summary-in:checked ~ .xr-section-details {\n  display: contents;\n}\n\n.xr-array-wrap {\n  grid-column: 1 / -1;\n  display: grid;\n  grid-template-columns: 20px auto;\n}\n\n.xr-array-wrap > label {\n  grid-column: 1;\n  vertical-align: top;\n}\n\n.xr-preview {\n  color: var(--xr-font-color3);\n}\n\n.xr-array-preview,\n.xr-array-data {\n  padding: 0 5px !important;\n  grid-column: 2;\n}\n\n.xr-array-data,\n.xr-array-in:checked ~ .xr-array-preview {\n  display: none;\n}\n\n.xr-array-in:checked ~ .xr-array-data,\n.xr-array-preview {\n  display: inline-block;\n}\n\n.xr-dim-list {\n  display: inline-block !important;\n  list-style: none;\n  padding: 0 !important;\n  margin: 0;\n}\n\n.xr-dim-list li {\n  display: inline-block;\n  padding: 0;\n  margin: 0;\n}\n\n.xr-dim-list:before {\n  content: '(';\n}\n\n.xr-dim-list:after {\n  content: ')';\n}\n\n.xr-dim-list li:not(:last-child):after {\n  content: ',';\n  padding-right: 5px;\n}\n\n.xr-has-index {\n  font-weight: bold;\n}\n\n.xr-var-list,\n.xr-var-item {\n  display: contents;\n}\n\n.xr-var-item > div,\n.xr-var-item label,\n.xr-var-item > .xr-var-name span {\n  background-color: var(--xr-background-color-row-even);\n  margin-bottom: 0;\n}\n\n.xr-var-item > .xr-var-name:hover span {\n  padding-right: 5px;\n}\n\n.xr-var-list > li:nth-child(odd) > div,\n.xr-var-list > li:nth-child(odd) > label,\n.xr-var-list > li:nth-child(odd) > .xr-var-name span {\n  background-color: var(--xr-background-color-row-odd);\n}\n\n.xr-var-name {\n  grid-column: 1;\n}\n\n.xr-var-dims {\n  grid-column: 2;\n}\n\n.xr-var-dtype {\n  grid-column: 3;\n  text-align: right;\n  color: var(--xr-font-color2);\n}\n\n.xr-var-preview {\n  grid-column: 4;\n}\n\n.xr-var-name,\n.xr-var-dims,\n.xr-var-dtype,\n.xr-preview,\n.xr-attrs dt {\n  white-space: nowrap;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  padding-right: 10px;\n}\n\n.xr-var-name:hover,\n.xr-var-dims:hover,\n.xr-var-dtype:hover,\n.xr-attrs dt:hover {\n  overflow: visible;\n  width: auto;\n  z-index: 1;\n}\n\n.xr-var-attrs,\n.xr-var-data {\n  display: none;\n  background-color: var(--xr-background-color) !important;\n  padding-bottom: 5px !important;\n}\n\n.xr-var-attrs-in:checked ~ .xr-var-attrs,\n.xr-var-data-in:checked ~ .xr-var-data {\n  display: block;\n}\n\n.xr-var-data > table {\n  float: right;\n}\n\n.xr-var-name span,\n.xr-var-data,\n.xr-attrs {\n  padding-left: 25px !important;\n}\n\n.xr-attrs,\n.xr-var-attrs,\n.xr-var-data {\n  grid-column: 1 / -1;\n}\n\ndl.xr-attrs {\n  padding: 0;\n  margin: 0;\n  display: grid;\n  grid-template-columns: 125px auto;\n}\n\n.xr-attrs dt,\n.xr-attrs dd {\n  padding: 0;\n  margin: 0;\n  float: left;\n  padding-right: 10px;\n  width: auto;\n}\n\n.xr-attrs dt {\n  font-weight: normal;\n  grid-column: 1;\n}\n\n.xr-attrs dt:hover span {\n  display: inline-block;\n  background: var(--xr-background-color);\n  padding-right: 10px;\n}\n\n.xr-attrs dd {\n  grid-column: 2;\n  white-space: pre-wrap;\n  word-break: break-all;\n}\n\n.xr-icon-database,\n.xr-icon-file-text2 {\n  display: inline-block;\n  vertical-align: middle;\n  width: 1em;\n  height: 1.5em !important;\n  stroke-width: 0;\n  stroke: currentColor;\n  fill: currentColor;\n}\n</style><pre class='xr-text-repr-fallback'>&lt;xarray.Dataset&gt;\nDimensions:      (ocean_time: 2, s_w: 51, eta_rho: 489, xi_rho: 655, tracer: 2, s_rho: 50, boundary: 4, eta_psi: 488, xi_psi: 654, eta_u: 489, xi_u: 654, eta_v: 488, xi_v: 655)\nCoordinates:\n    lat_psi      (eta_psi, xi_psi) float64 ...\n    lat_rho      (eta_rho, xi_rho) float64 ...\n    lat_u        (eta_u, xi_u) float64 ...\n    lat_v        (eta_v, xi_v) float64 ...\n    lon_psi      (eta_psi, xi_psi) float64 ...\n    lon_rho      (eta_rho, xi_rho) float64 ...\n    lon_u        (eta_u, xi_u) float64 ...\n    lon_v        (eta_v, xi_v) float64 ...\n  * ocean_time   (ocean_time) datetime64[ns] 2010-01-05T03:00:00 2010-01-05T0...\n  * s_rho        (s_rho) float64 -0.99 -0.97 -0.95 -0.93 ... -0.05 -0.03 -0.01\n  * s_w          (s_w) float64 -1.0 -0.98 -0.96 -0.94 ... -0.06 -0.04 -0.02 0.0\nDimensions without coordinates: eta_rho, xi_rho, tracer, boundary, eta_psi, xi_psi, eta_u, xi_u, eta_v, xi_v\nData variables: (12/74)\n    AKt          (ocean_time, s_w, eta_rho, xi_rho) float32 ...\n    AKv          (ocean_time, s_w, eta_rho, xi_rho) float32 ...\n    Akt_bak      (tracer) float64 1e-06 1e-06\n    Akv_bak      float64 1e-05\n    Cs_r         (s_rho) float64 -0.9672 -0.8937 ... -9.523e-06 -1.051e-06\n    Cs_w         (s_w) float64 -1.0 -0.9316 -0.8539 ... -4.215e-06 0.0\n    ...           ...\n    ubar         (ocean_time, eta_u, xi_u) float32 ...\n    v            (ocean_time, s_rho, eta_v, xi_v) float32 ...\n    vbar         (ocean_time, eta_v, xi_v) float32 ...\n    w            (ocean_time, s_w, eta_rho, xi_rho) float32 ...\n    xl           float64 1.983e+06\n    zeta         (ocean_time, eta_rho, xi_rho) float32 ...\nAttributes: (12/26)\n    file:              GOM_hurr_wrf_19950930-06.ocn_0002.hi.1995-10-04_09:00:...\n    format:            netCDF-3 classic file\n    Conventions:       CF-1.4\n    type:              ROMS/TOMS history file\n    title:             BP_2010 Coupled Hindcast Run\n    rst_file:          gom03_rst.nc\n    ...                ...\n    compiler_flags:    -fp-model precise -ip -O2 -debug minimal -free -free\n    tiling:            020x018\n    history:           Thu Nov  4 09:41:12 2021: ncks -d ocean_time,0,1 roms_...\n    ana_file:          ROMS/Functionals/ana_btflux.h, ROMS/Functionals/ana_hm...\n    CPP_options:       TXGLO, ATM_PRESS, ANA_BSFLUX, ANA_BTFLUX, ASSUMED_SHAP...\n    NCO:               netCDF Operators version 4.9.7 (Homepage = http://nco....</pre><div class='xr-wrap' hidden><div class='xr-header'><div class='xr-obj-type'>xarray.Dataset</div></div><ul class='xr-sections'><li class='xr-section-item'><input id='section-388b2f95-30b9-4930-b9b2-a3697fedda8b' class='xr-section-summary-in' type='checkbox' disabled ><label for='section-388b2f95-30b9-4930-b9b2-a3697fedda8b' class='xr-section-summary'  title='Expand/collapse section'>Dimensions:</label><div class='xr-section-inline-details'><ul class='xr-dim-list'><li><span class='xr-has-index'>ocean_time</span>: 2</li><li><span class='xr-has-index'>s_w</span>: 51</li><li><span>eta_rho</span>: 489</li><li><span>xi_rho</span>: 655</li><li><span>tracer</span>: 2</li><li><span class='xr-has-index'>s_rho</span>: 50</li><li><span>boundary</span>: 4</li><li><span>eta_psi</span>: 488</li><li><span>xi_psi</span>: 654</li><li><span>eta_u</span>: 489</li><li><span>xi_u</span>: 654</li><li><span>eta_v</span>: 488</li><li><span>xi_v</span>: 655</li></ul></div><div class='xr-section-details'></div></li><li class='xr-section-item'><input id='section-a130e3ea-e7e5-45f8-bc2a-657d0f4118bb' class='xr-section-summary-in' type='checkbox'  checked><label for='section-a130e3ea-e7e5-45f8-bc2a-657d0f4118bb' class='xr-section-summary' >Coordinates: <span>(11)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><ul class='xr-var-list'><li class='xr-var-item'><div class='xr-var-name'><span>lat_psi</span></div><div class='xr-var-dims'>(eta_psi, xi_psi)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-fa5f1319-257c-4d1b-9b29-67022720ec91' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-fa5f1319-257c-4d1b-9b29-67022720ec91' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-12732cd3-2fd8-4304-b5df-2c5ed96c4ddc' class='xr-var-data-in' type='checkbox'><label for='data-12732cd3-2fd8-4304-b5df-2c5ed96c4ddc' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>latitude of PSI-points</dd><dt><span>units :</span></dt><dd>degree_north</dd><dt><span>standard_name :</span></dt><dd>latitude</dd><dt><span>field :</span></dt><dd>lat_psi, scalar</dd></dl></div><div class='xr-var-data'><pre>[319152 values with dtype=float64]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>lat_rho</span></div><div class='xr-var-dims'>(eta_rho, xi_rho)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-87937d67-34e2-402b-a8c6-a40772962528' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-87937d67-34e2-402b-a8c6-a40772962528' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-807513e4-cc7a-4e35-b827-4c46bc16d721' class='xr-var-data-in' type='checkbox'><label for='data-807513e4-cc7a-4e35-b827-4c46bc16d721' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>latitude of RHO-points</dd><dt><span>units :</span></dt><dd>degree_north</dd><dt><span>standard_name :</span></dt><dd>latitude</dd><dt><span>field :</span></dt><dd>lat_rho, scalar</dd></dl></div><div class='xr-var-data'><pre>[320295 values with dtype=float64]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>lat_u</span></div><div class='xr-var-dims'>(eta_u, xi_u)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-83bcf353-9c38-481e-be6f-56855877df8c' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-83bcf353-9c38-481e-be6f-56855877df8c' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-825aa146-9d80-43db-81ca-9404c1f4bb50' class='xr-var-data-in' type='checkbox'><label for='data-825aa146-9d80-43db-81ca-9404c1f4bb50' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>latitude of U-points</dd><dt><span>units :</span></dt><dd>degree_north</dd><dt><span>standard_name :</span></dt><dd>latitude</dd><dt><span>field :</span></dt><dd>lat_u, scalar</dd></dl></div><div class='xr-var-data'><pre>[319806 values with dtype=float64]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>lat_v</span></div><div class='xr-var-dims'>(eta_v, xi_v)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-0b9a71f5-e66e-43aa-82f1-c139b09d402f' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-0b9a71f5-e66e-43aa-82f1-c139b09d402f' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-e5cc02f6-575f-4adf-96a7-b6c664314af3' class='xr-var-data-in' type='checkbox'><label for='data-e5cc02f6-575f-4adf-96a7-b6c664314af3' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>latitude of V-points</dd><dt><span>units :</span></dt><dd>degree_north</dd><dt><span>standard_name :</span></dt><dd>latitude</dd><dt><span>field :</span></dt><dd>lat_v, scalar</dd></dl></div><div class='xr-var-data'><pre>[319640 values with dtype=float64]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>lon_psi</span></div><div class='xr-var-dims'>(eta_psi, xi_psi)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-c7cfbb90-97b1-4b79-947b-09edc97acc1b' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-c7cfbb90-97b1-4b79-947b-09edc97acc1b' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-4a3aabf0-0a12-425c-8feb-098e6d71e317' class='xr-var-data-in' type='checkbox'><label for='data-4a3aabf0-0a12-425c-8feb-098e6d71e317' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>longitude of PSI-points</dd><dt><span>units :</span></dt><dd>degree_east</dd><dt><span>standard_name :</span></dt><dd>longitude</dd><dt><span>field :</span></dt><dd>lon_psi, scalar</dd></dl></div><div class='xr-var-data'><pre>[319152 values with dtype=float64]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>lon_rho</span></div><div class='xr-var-dims'>(eta_rho, xi_rho)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-3e8b01e7-4ee4-4d15-877b-80c072c63548' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-3e8b01e7-4ee4-4d15-877b-80c072c63548' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-c0e597fd-eb09-47e5-ac77-756e047eccc8' class='xr-var-data-in' type='checkbox'><label for='data-c0e597fd-eb09-47e5-ac77-756e047eccc8' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>longitude of RHO-points</dd><dt><span>units :</span></dt><dd>degree_east</dd><dt><span>standard_name :</span></dt><dd>longitude</dd><dt><span>field :</span></dt><dd>lon_rho, scalar</dd></dl></div><div class='xr-var-data'><pre>[320295 values with dtype=float64]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>lon_u</span></div><div class='xr-var-dims'>(eta_u, xi_u)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-fa40f7b7-d7f6-4a00-ab78-5268283cb75b' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-fa40f7b7-d7f6-4a00-ab78-5268283cb75b' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-c4f52386-38cd-45f8-b276-f472ad7eab52' class='xr-var-data-in' type='checkbox'><label for='data-c4f52386-38cd-45f8-b276-f472ad7eab52' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>longitude of U-points</dd><dt><span>units :</span></dt><dd>degree_east</dd><dt><span>standard_name :</span></dt><dd>longitude</dd><dt><span>field :</span></dt><dd>lon_u, scalar</dd></dl></div><div class='xr-var-data'><pre>[319806 values with dtype=float64]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>lon_v</span></div><div class='xr-var-dims'>(eta_v, xi_v)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-2270c2f3-7561-48b6-a26c-fbc46cbf1fe3' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-2270c2f3-7561-48b6-a26c-fbc46cbf1fe3' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-b62ac2eb-3535-451b-95e0-2cd26ebb9351' class='xr-var-data-in' type='checkbox'><label for='data-b62ac2eb-3535-451b-95e0-2cd26ebb9351' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>longitude of V-points</dd><dt><span>units :</span></dt><dd>degree_east</dd><dt><span>standard_name :</span></dt><dd>longitude</dd><dt><span>field :</span></dt><dd>lon_v, scalar</dd></dl></div><div class='xr-var-data'><pre>[319640 values with dtype=float64]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>ocean_time</span></div><div class='xr-var-dims'>(ocean_time)</div><div class='xr-var-dtype'>datetime64[ns]</div><div class='xr-var-preview xr-preview'>2010-01-05T03:00:00 2010-01-05T0...</div><input id='attrs-98d9cc97-5c62-42a8-b43e-87e87c8a851e' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-98d9cc97-5c62-42a8-b43e-87e87c8a851e' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-bda4797e-757f-4eb7-ba32-4335a6c2ad21' class='xr-var-data-in' type='checkbox'><label for='data-bda4797e-757f-4eb7-ba32-4335a6c2ad21' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>time since initialization</dd><dt><span>field :</span></dt><dd>time, scalar, series</dd></dl></div><div class='xr-var-data'><pre>array([&#x27;2010-01-05T03:00:00.000000000&#x27;, &#x27;2010-01-05T06:00:00.000000000&#x27;],\n      dtype=&#x27;datetime64[ns]&#x27;)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>s_rho</span></div><div class='xr-var-dims'>(s_rho)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>-0.99 -0.97 -0.95 ... -0.03 -0.01</div><input id='attrs-8748750b-22ff-436e-a9d7-604538d167c0' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-8748750b-22ff-436e-a9d7-604538d167c0' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-da8a78a6-c27d-4f33-bca1-271d14a4f838' class='xr-var-data-in' type='checkbox'><label for='data-da8a78a6-c27d-4f33-bca1-271d14a4f838' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>S-coordinate at RHO-points</dd><dt><span>valid_min :</span></dt><dd>-1.0</dd><dt><span>valid_max :</span></dt><dd>0.0</dd><dt><span>positive :</span></dt><dd>up</dd><dt><span>standard_name :</span></dt><dd>ocean_s_coordinate_g2</dd><dt><span>formula_terms :</span></dt><dd>s: s_rho C: Cs_r eta: zeta depth: h depth_c: hc</dd><dt><span>field :</span></dt><dd>s_rho, scalar</dd></dl></div><div class='xr-var-data'><pre>array([-0.99, -0.97, -0.95, -0.93, -0.91, -0.89, -0.87, -0.85, -0.83, -0.81,\n       -0.79, -0.77, -0.75, -0.73, -0.71, -0.69, -0.67, -0.65, -0.63, -0.61,\n       -0.59, -0.57, -0.55, -0.53, -0.51, -0.49, -0.47, -0.45, -0.43, -0.41,\n       -0.39, -0.37, -0.35, -0.33, -0.31, -0.29, -0.27, -0.25, -0.23, -0.21,\n       -0.19, -0.17, -0.15, -0.13, -0.11, -0.09, -0.07, -0.05, -0.03, -0.01])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>s_w</span></div><div class='xr-var-dims'>(s_w)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>-1.0 -0.98 -0.96 ... -0.02 0.0</div><input id='attrs-9ba86cd9-0dc7-406c-b8de-e475ba7a65e0' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-9ba86cd9-0dc7-406c-b8de-e475ba7a65e0' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-64db504e-c62a-4f1a-98ea-f1b4bc22b21c' class='xr-var-data-in' type='checkbox'><label for='data-64db504e-c62a-4f1a-98ea-f1b4bc22b21c' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>S-coordinate at W-points</dd><dt><span>valid_min :</span></dt><dd>-1.0</dd><dt><span>valid_max :</span></dt><dd>0.0</dd><dt><span>positive :</span></dt><dd>up</dd><dt><span>standard_name :</span></dt><dd>ocean_s_coordinate_g2</dd><dt><span>formula_terms :</span></dt><dd>s: s_w C: Cs_w eta: zeta depth: h depth_c: hc</dd><dt><span>field :</span></dt><dd>s_w, scalar</dd></dl></div><div class='xr-var-data'><pre>array([-1.  , -0.98, -0.96, -0.94, -0.92, -0.9 , -0.88, -0.86, -0.84, -0.82,\n       -0.8 , -0.78, -0.76, -0.74, -0.72, -0.7 , -0.68, -0.66, -0.64, -0.62,\n       -0.6 , -0.58, -0.56, -0.54, -0.52, -0.5 , -0.48, -0.46, -0.44, -0.42,\n       -0.4 , -0.38, -0.36, -0.34, -0.32, -0.3 , -0.28, -0.26, -0.24, -0.22,\n       -0.2 , -0.18, -0.16, -0.14, -0.12, -0.1 , -0.08, -0.06, -0.04, -0.02,\n        0.  ])</pre></div></li></ul></div></li><li class='xr-section-item'><input id='section-0921821d-5053-4eae-bc5c-581b72f8029a' class='xr-section-summary-in' type='checkbox'  ><label for='section-0921821d-5053-4eae-bc5c-581b72f8029a' class='xr-section-summary' >Data variables: <span>(74)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><ul class='xr-var-list'><li class='xr-var-item'><div class='xr-var-name'><span>AKt</span></div><div class='xr-var-dims'>(ocean_time, s_w, eta_rho, xi_rho)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-f5f64926-791d-4832-b07d-498e69fc55ab' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-f5f64926-791d-4832-b07d-498e69fc55ab' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-86507d55-914c-45ca-b9c7-03f063026335' class='xr-var-data-in' type='checkbox'><label for='data-86507d55-914c-45ca-b9c7-03f063026335' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>temperature vertical diffusion coefficient</dd><dt><span>units :</span></dt><dd>meter2 second-1</dd><dt><span>time :</span></dt><dd>ocean_time</dd><dt><span>field :</span></dt><dd>AKt, scalar, series</dd></dl></div><div class='xr-var-data'><pre>[32670090 values with dtype=float32]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>AKv</span></div><div class='xr-var-dims'>(ocean_time, s_w, eta_rho, xi_rho)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-309d6734-abca-4c44-bd1a-5189359fadb9' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-309d6734-abca-4c44-bd1a-5189359fadb9' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-751f202c-5ccd-4d24-abea-f535135f73ac' class='xr-var-data-in' type='checkbox'><label for='data-751f202c-5ccd-4d24-abea-f535135f73ac' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>vertical viscosity coefficient</dd><dt><span>units :</span></dt><dd>meter2 second-1</dd><dt><span>time :</span></dt><dd>ocean_time</dd><dt><span>field :</span></dt><dd>AKv, scalar, series</dd></dl></div><div class='xr-var-data'><pre>[32670090 values with dtype=float32]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>Akt_bak</span></div><div class='xr-var-dims'>(tracer)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-300f671c-de56-4ac4-b47e-10199e8f3f11' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-300f671c-de56-4ac4-b47e-10199e8f3f11' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-caa6afbb-3032-4aa0-9b0b-88f534cab5f5' class='xr-var-data-in' type='checkbox'><label for='data-caa6afbb-3032-4aa0-9b0b-88f534cab5f5' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>background vertical mixing coefficient for tracers</dd><dt><span>units :</span></dt><dd>meter2 second-1</dd></dl></div><div class='xr-var-data'><pre>array([1.e-06, 1.e-06])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>Akv_bak</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-394c12ff-0057-49f2-8d2c-680d5ce846ba' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-394c12ff-0057-49f2-8d2c-680d5ce846ba' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-d0e1b901-7a50-483c-87a5-acc803e3e52f' class='xr-var-data-in' type='checkbox'><label for='data-d0e1b901-7a50-483c-87a5-acc803e3e52f' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>background vertical mixing coefficient for momentum</dd><dt><span>units :</span></dt><dd>meter2 second-1</dd></dl></div><div class='xr-var-data'><pre>array(1.e-05)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>Cs_r</span></div><div class='xr-var-dims'>(s_rho)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-221fedf4-61c2-4593-9eee-0e0f3e60e54e' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-221fedf4-61c2-4593-9eee-0e0f3e60e54e' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-73cdfb9d-f742-46d9-b243-47db8b84555f' class='xr-var-data-in' type='checkbox'><label for='data-73cdfb9d-f742-46d9-b243-47db8b84555f' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>S-coordinate stretching curves at RHO-points</dd><dt><span>valid_min :</span></dt><dd>-1.0</dd><dt><span>valid_max :</span></dt><dd>0.0</dd><dt><span>field :</span></dt><dd>Cs_r, scalar</dd></dl></div><div class='xr-var-data'><pre>array([-9.671839e-01, -8.936687e-01, -8.126768e-01, -7.281038e-01,\n       -6.435888e-01, -5.621205e-01, -4.858744e-01, -4.162221e-01,\n       -3.538425e-01, -2.988764e-01, -2.510829e-01, -2.099765e-01,\n       -1.749358e-01, -1.452832e-01, -1.203400e-01, -9.946089e-02,\n       -8.205365e-02, -6.758860e-02, -5.560076e-02, -4.568777e-02,\n       -3.750529e-02, -3.076122e-02, -2.520941e-02, -2.064362e-02,\n       -1.689180e-02, -1.381088e-02, -1.128230e-02, -9.207977e-03,\n       -7.506952e-03, -6.112496e-03, -4.969678e-03, -4.033328e-03,\n       -3.266331e-03, -2.638219e-03, -2.123991e-03, -1.703151e-03,\n       -1.358904e-03, -1.077496e-03, -8.476765e-04, -6.602504e-04,\n       -5.077145e-04, -3.839599e-04, -2.840284e-04, -2.039151e-04,\n       -1.404087e-04, -9.096290e-05, -5.359506e-05, -2.680655e-05,\n       -9.522969e-06, -1.051087e-06])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>Cs_w</span></div><div class='xr-var-dims'>(s_w)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-7cb187cf-f99b-4740-8bd6-3874889a26fb' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-7cb187cf-f99b-4740-8bd6-3874889a26fb' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-87df8354-4287-4a1c-9511-3774e27df477' class='xr-var-data-in' type='checkbox'><label for='data-87df8354-4287-4a1c-9511-3774e27df477' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>S-coordinate stretching curves at W-points</dd><dt><span>valid_min :</span></dt><dd>-1.0</dd><dt><span>valid_max :</span></dt><dd>0.0</dd><dt><span>field :</span></dt><dd>Cs_w, scalar</dd></dl></div><div class='xr-var-data'><pre>array([-1.000000e+00, -9.315987e-01, -8.538642e-01, -7.705987e-01,\n       -6.856341e-01, -6.023182e-01, -5.232411e-01, -4.501671e-01,\n       -3.841037e-01, -3.254406e-01, -2.741091e-01, -2.297305e-01,\n       -1.917397e-01, -1.594789e-01, -1.322644e-01, -1.094309e-01,\n       -9.035791e-02, -7.448392e-02, -6.131160e-02, -5.040772e-02,\n       -4.139962e-02, -3.396984e-02, -2.785004e-02, -2.281476e-02,\n       -1.867553e-02, -1.527541e-02, -1.248412e-02, -1.019378e-02,\n       -8.315276e-03, -6.775087e-03, -5.512663e-03, -4.478185e-03,\n       -3.630706e-03, -2.936593e-03, -2.368246e-03, -1.903026e-03,\n       -1.522377e-03, -1.211101e-03, -9.567559e-04, -7.491691e-04,\n       -5.800326e-04, -4.425739e-04, -3.312869e-04, -2.417122e-04,\n       -1.702595e-04, -1.140643e-04, -7.087346e-05, -3.895489e-05,\n       -1.702851e-05, -4.214861e-06,  0.000000e+00])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>EminusP</span></div><div class='xr-var-dims'>(ocean_time, eta_rho, xi_rho)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-4c28307a-1211-4b8e-bcf1-6b0672cd1f4a' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-4c28307a-1211-4b8e-bcf1-6b0672cd1f4a' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-72720bf9-613b-4b98-851f-a0258a968c2a' class='xr-var-data-in' type='checkbox'><label for='data-72720bf9-613b-4b98-851f-a0258a968c2a' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>bulk_flux surface net freswater flux, (E-P)</dd><dt><span>units :</span></dt><dd>meter second-1</dd><dt><span>negative_value :</span></dt><dd>upward flux, freshening (net precipitation)</dd><dt><span>positive_value :</span></dt><dd>downward flux, salting (net evaporation)</dd><dt><span>time :</span></dt><dd>ocean_time</dd><dt><span>field :</span></dt><dd>EminusP, scalar, series</dd></dl></div><div class='xr-var-data'><pre>[640590 values with dtype=float32]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>FSobc_in</span></div><div class='xr-var-dims'>(boundary)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-829a9851-5bbe-43a0-92dc-ea374f35135c' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-829a9851-5bbe-43a0-92dc-ea374f35135c' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-f23d0781-a034-4644-af3b-1d020253647c' class='xr-var-data-in' type='checkbox'><label for='data-f23d0781-a034-4644-af3b-1d020253647c' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>free-surface inflow, nudging inverse time scale</dd><dt><span>units :</span></dt><dd>second-1</dd></dl></div><div class='xr-var-data'><pre>array([0., 0., 0., 0.])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>FSobc_out</span></div><div class='xr-var-dims'>(boundary)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-7f89b45e-d87a-46ab-895b-c9692268e78a' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-7f89b45e-d87a-46ab-895b-c9692268e78a' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-f6b9c3b4-e2c7-4b00-b8e9-9547ec6429e5' class='xr-var-data-in' type='checkbox'><label for='data-f6b9c3b4-e2c7-4b00-b8e9-9547ec6429e5' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>free-surface outflow, nudging inverse time scale</dd><dt><span>units :</span></dt><dd>second-1</dd></dl></div><div class='xr-var-data'><pre>array([0., 0., 0., 0.])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>Falpha</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-bcbdd477-983a-4060-b3d1-ab313657a866' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-bcbdd477-983a-4060-b3d1-ab313657a866' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-8a910131-0934-43b3-8396-38db11091cc6' class='xr-var-data-in' type='checkbox'><label for='data-8a910131-0934-43b3-8396-38db11091cc6' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>Power-law shape barotropic filter parameter</dd></dl></div><div class='xr-var-data'><pre>array(2.)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>Fbeta</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-5234e84a-2e1b-44e9-8eb3-cec1fa27ec1b' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-5234e84a-2e1b-44e9-8eb3-cec1fa27ec1b' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-fcc53498-bd9f-415d-9303-c54eda37e015' class='xr-var-data-in' type='checkbox'><label for='data-fcc53498-bd9f-415d-9303-c54eda37e015' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>Power-law shape barotropic filter parameter</dd></dl></div><div class='xr-var-data'><pre>array(4.)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>Fgamma</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-8202db99-8a5f-4e96-9032-cf4c44674d65' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-8202db99-8a5f-4e96-9032-cf4c44674d65' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-742ef194-21ea-4d15-bdb0-9ad17d0f34d8' class='xr-var-data-in' type='checkbox'><label for='data-742ef194-21ea-4d15-bdb0-9ad17d0f34d8' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>Power-law shape barotropic filter parameter</dd></dl></div><div class='xr-var-data'><pre>array(0.284)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>Hsbl</span></div><div class='xr-var-dims'>(ocean_time, eta_rho, xi_rho)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-e28279ab-95f4-4415-af56-79a7bb58e00d' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-e28279ab-95f4-4415-af56-79a7bb58e00d' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-b4fbfc2c-3bd8-4930-abe6-b28e7b9d3085' class='xr-var-data-in' type='checkbox'><label for='data-b4fbfc2c-3bd8-4930-abe6-b28e7b9d3085' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>depth of oceanic surface boundary layer</dd><dt><span>units :</span></dt><dd>meter</dd><dt><span>time :</span></dt><dd>ocean_time</dd><dt><span>field :</span></dt><dd>Hsbl, scalar, series</dd></dl></div><div class='xr-var-data'><pre>[640590 values with dtype=float32]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>M2nudg</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-ea198445-99d1-4e3d-95e8-69e9b66f2a59' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-ea198445-99d1-4e3d-95e8-69e9b66f2a59' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-b162c3fd-5f7f-4b2b-b232-4c5729a69b7a' class='xr-var-data-in' type='checkbox'><label for='data-b162c3fd-5f7f-4b2b-b232-4c5729a69b7a' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>2D momentum nudging/relaxation inverse time scale</dd><dt><span>units :</span></dt><dd>day-1</dd></dl></div><div class='xr-var-data'><pre>array(0.1)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>M2obc_in</span></div><div class='xr-var-dims'>(boundary)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-29a0475a-75c1-4990-9c2b-154bb7d78777' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-29a0475a-75c1-4990-9c2b-154bb7d78777' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-24bfe21c-881f-49c7-8df9-607241eca34f' class='xr-var-data-in' type='checkbox'><label for='data-24bfe21c-881f-49c7-8df9-607241eca34f' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>2D momentum inflow, nudging inverse time scale</dd><dt><span>units :</span></dt><dd>second-1</dd></dl></div><div class='xr-var-data'><pre>array([0., 0., 0., 0.])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>M2obc_out</span></div><div class='xr-var-dims'>(boundary)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-434c4e19-e714-4d27-a1f4-3d223e9e3326' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-434c4e19-e714-4d27-a1f4-3d223e9e3326' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-5112f96c-1321-489b-b06b-3189df650bbb' class='xr-var-data-in' type='checkbox'><label for='data-5112f96c-1321-489b-b06b-3189df650bbb' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>2D momentum outflow, nudging inverse time scale</dd><dt><span>units :</span></dt><dd>second-1</dd></dl></div><div class='xr-var-data'><pre>array([0., 0., 0., 0.])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>M3nudg</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-04e7e62b-bb86-46e3-bbae-57721ffed517' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-04e7e62b-bb86-46e3-bbae-57721ffed517' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-82d427a7-ab1c-4928-8971-f01ae279669f' class='xr-var-data-in' type='checkbox'><label for='data-82d427a7-ab1c-4928-8971-f01ae279669f' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>3D momentum nudging/relaxation inverse time scale</dd><dt><span>units :</span></dt><dd>day-1</dd></dl></div><div class='xr-var-data'><pre>array(0.1)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>M3obc_in</span></div><div class='xr-var-dims'>(boundary)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-ee96e8b6-353a-4f08-966c-5e0534d25b30' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-ee96e8b6-353a-4f08-966c-5e0534d25b30' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-097e8d9b-e720-4959-bc28-2141a92468ba' class='xr-var-data-in' type='checkbox'><label for='data-097e8d9b-e720-4959-bc28-2141a92468ba' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>3D momentum inflow, nudging inverse time scale</dd><dt><span>units :</span></dt><dd>second-1</dd></dl></div><div class='xr-var-data'><pre>array([0.000000e+00, 1.157407e-05, 1.157407e-05, 1.157407e-05])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>M3obc_out</span></div><div class='xr-var-dims'>(boundary)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-dea52688-a02c-4d1f-a7e2-d88a33b8fb98' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-dea52688-a02c-4d1f-a7e2-d88a33b8fb98' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-e07c753f-33e4-4699-b17c-9784038b9142' class='xr-var-data-in' type='checkbox'><label for='data-e07c753f-33e4-4699-b17c-9784038b9142' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>3D momentum outflow, nudging inverse time scale</dd><dt><span>units :</span></dt><dd>second-1</dd></dl></div><div class='xr-var-data'><pre>array([0.000000e+00, 1.157407e-06, 1.157407e-06, 1.157407e-06])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>Tcline</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-618668d8-79c1-4de9-bfa9-9b1346d4c8bd' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-618668d8-79c1-4de9-bfa9-9b1346d4c8bd' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-0d2f25d9-89d6-414e-8776-527af1e9c9b0' class='xr-var-data-in' type='checkbox'><label for='data-0d2f25d9-89d6-414e-8776-527af1e9c9b0' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>S-coordinate surface/bottom layer width</dd><dt><span>units :</span></dt><dd>meter</dd></dl></div><div class='xr-var-data'><pre>array(400.)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>Tnudg</span></div><div class='xr-var-dims'>(tracer)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-2b62513f-8eef-4121-b325-9d49d97280a1' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-2b62513f-8eef-4121-b325-9d49d97280a1' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-9c4e2e65-75b2-4815-a498-8e5a1633fb79' class='xr-var-data-in' type='checkbox'><label for='data-9c4e2e65-75b2-4815-a498-8e5a1633fb79' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>Tracers nudging/relaxation inverse time scale</dd><dt><span>units :</span></dt><dd>day-1</dd></dl></div><div class='xr-var-data'><pre>array([0.5, 0.5])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>Tobc_in</span></div><div class='xr-var-dims'>(boundary, tracer)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-a0f7b862-2208-4ed1-98a1-7c210855d07a' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-a0f7b862-2208-4ed1-98a1-7c210855d07a' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-92bf0043-99e3-4867-b8ef-ac47c9c30468' class='xr-var-data-in' type='checkbox'><label for='data-92bf0043-99e3-4867-b8ef-ac47c9c30468' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>tracers inflow, nudging inverse time scale</dd><dt><span>units :</span></dt><dd>second-1</dd></dl></div><div class='xr-var-data'><pre>array([[0.000000e+00, 0.000000e+00],\n       [5.787037e-05, 5.787037e-05],\n       [5.787037e-05, 5.787037e-05],\n       [5.787037e-05, 5.787037e-05]])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>Tobc_out</span></div><div class='xr-var-dims'>(boundary, tracer)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-0fc95028-c61c-467e-af9f-a4f4d4644d81' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-0fc95028-c61c-467e-af9f-a4f4d4644d81' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-b5fd607c-b4e1-42cb-8d1e-46c93e18da1e' class='xr-var-data-in' type='checkbox'><label for='data-b5fd607c-b4e1-42cb-8d1e-46c93e18da1e' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>tracers outflow, nudging inverse time scale</dd><dt><span>units :</span></dt><dd>second-1</dd></dl></div><div class='xr-var-data'><pre>array([[0.000000e+00, 0.000000e+00],\n       [5.787037e-06, 5.787037e-06],\n       [5.787037e-06, 5.787037e-06],\n       [5.787037e-06, 5.787037e-06]])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>Vstretching</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>int32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-071a29db-b104-495d-8426-b686683a2a2d' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-071a29db-b104-495d-8426-b686683a2a2d' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-a9bb53c9-22a8-4cb0-a7bd-177d3383d676' class='xr-var-data-in' type='checkbox'><label for='data-a9bb53c9-22a8-4cb0-a7bd-177d3383d676' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>vertical terrain-following stretching function</dd></dl></div><div class='xr-var-data'><pre>array(4, dtype=int32)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>Vtransform</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>int32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-e79e7ce0-45d1-4161-85b6-c3acfab6ee8f' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-e79e7ce0-45d1-4161-85b6-c3acfab6ee8f' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-db65cb97-4420-424b-9106-2c7d272a71ec' class='xr-var-data-in' type='checkbox'><label for='data-db65cb97-4420-424b-9106-2c7d272a71ec' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>vertical terrain-following transformation equation</dd></dl></div><div class='xr-var-data'><pre>array(2, dtype=int32)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>Znudg</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-069e1be2-1806-4cff-b907-ee972d1641c9' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-069e1be2-1806-4cff-b907-ee972d1641c9' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-20542375-e49e-433b-a694-8a640d232888' class='xr-var-data-in' type='checkbox'><label for='data-20542375-e49e-433b-a694-8a640d232888' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>free-surface nudging/relaxation inverse time scale</dd><dt><span>units :</span></dt><dd>day-1</dd></dl></div><div class='xr-var-data'><pre>array(0.5)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>Zob</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-9cee4000-aaba-4b22-8add-d563c62a1d9d' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-9cee4000-aaba-4b22-8add-d563c62a1d9d' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-abf83d66-4053-4a0c-922a-c42f103a901e' class='xr-var-data-in' type='checkbox'><label for='data-abf83d66-4053-4a0c-922a-c42f103a901e' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>bottom roughness</dd><dt><span>units :</span></dt><dd>meter</dd></dl></div><div class='xr-var-data'><pre>array(0.02)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>Zos</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-e61429aa-ea88-4baa-a78e-ff49da068bd9' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-e61429aa-ea88-4baa-a78e-ff49da068bd9' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-945266a0-33e9-449b-9406-dceda2ee5232' class='xr-var-data-in' type='checkbox'><label for='data-945266a0-33e9-449b-9406-dceda2ee5232' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>surface roughness</dd><dt><span>units :</span></dt><dd>meter</dd></dl></div><div class='xr-var-data'><pre>array(0.02)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>angle</span></div><div class='xr-var-dims'>(eta_rho, xi_rho)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-17f65c95-05fe-4297-bde9-b0984dcbca83' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-17f65c95-05fe-4297-bde9-b0984dcbca83' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-4606611b-afd8-4d0d-8883-5eafb9b13cea' class='xr-var-data-in' type='checkbox'><label for='data-4606611b-afd8-4d0d-8883-5eafb9b13cea' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>angle between XI-axis and EAST</dd><dt><span>units :</span></dt><dd>radians</dd><dt><span>field :</span></dt><dd>angle, scalar</dd></dl></div><div class='xr-var-data'><pre>[320295 values with dtype=float64]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>dstart</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>datetime64[ns]</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-3373a331-aca0-49e7-835b-10d4246b5c95' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-3373a331-aca0-49e7-835b-10d4246b5c95' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-a229140a-3cd2-4ca1-86b7-ef044d40f908' class='xr-var-data-in' type='checkbox'><label for='data-a229140a-3cd2-4ca1-86b7-ef044d40f908' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>time stamp assigned to model initilization</dd></dl></div><div class='xr-var-data'><pre>array(&#x27;2010-01-01T00:00:00.000000000&#x27;, dtype=&#x27;datetime64[ns]&#x27;)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>dt</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-c5805941-ce10-4e7c-972e-f26030b9c98e' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-c5805941-ce10-4e7c-972e-f26030b9c98e' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-9be2caa6-5de8-49c1-b91f-2e204d135433' class='xr-var-data-in' type='checkbox'><label for='data-9be2caa6-5de8-49c1-b91f-2e204d135433' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>size of long time-steps</dd><dt><span>units :</span></dt><dd>second</dd></dl></div><div class='xr-var-data'><pre>array(30.)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>dtfast</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-e79a675b-818c-4577-8076-0e7a1164cf5e' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-e79a675b-818c-4577-8076-0e7a1164cf5e' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-0425e4f8-e107-4a7b-8809-c3a6cc82376a' class='xr-var-data-in' type='checkbox'><label for='data-0425e4f8-e107-4a7b-8809-c3a6cc82376a' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>size of short time-steps</dd><dt><span>units :</span></dt><dd>second</dd></dl></div><div class='xr-var-data'><pre>array(1.)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>el</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-d7bb83d5-dbda-4cfb-a750-d5ea3f9e6987' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-d7bb83d5-dbda-4cfb-a750-d5ea3f9e6987' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-1fd0054b-83bd-44fe-95b0-2acea97efa1c' class='xr-var-data-in' type='checkbox'><label for='data-1fd0054b-83bd-44fe-95b0-2acea97efa1c' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>domain length in the ETA-direction</dd><dt><span>units :</span></dt><dd>meter</dd></dl></div><div class='xr-var-data'><pre>array(1413082.867518)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>f</span></div><div class='xr-var-dims'>(eta_rho, xi_rho)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-ba208e30-47cd-43ea-a52e-79d6d0066207' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-ba208e30-47cd-43ea-a52e-79d6d0066207' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-e86ab3cd-621b-4323-a6f6-9d91e2452a34' class='xr-var-data-in' type='checkbox'><label for='data-e86ab3cd-621b-4323-a6f6-9d91e2452a34' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>Coriolis parameter at RHO-points</dd><dt><span>units :</span></dt><dd>second-1</dd><dt><span>field :</span></dt><dd>coriolis, scalar</dd></dl></div><div class='xr-var-data'><pre>[320295 values with dtype=float64]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>gamma2</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-f700b594-7b33-403c-ac8a-a5c4243bd311' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-f700b594-7b33-403c-ac8a-a5c4243bd311' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-55ab73d1-69db-4651-bd84-b5ae3cb2d355' class='xr-var-data-in' type='checkbox'><label for='data-55ab73d1-69db-4651-bd84-b5ae3cb2d355' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>slipperiness parameter</dd></dl></div><div class='xr-var-data'><pre>array(1.)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>h</span></div><div class='xr-var-dims'>(eta_rho, xi_rho)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-17270b35-5eae-4289-9f91-92d708442c59' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-17270b35-5eae-4289-9f91-92d708442c59' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-76119543-ab24-4606-923d-4c99eb1c1aff' class='xr-var-data-in' type='checkbox'><label for='data-76119543-ab24-4606-923d-4c99eb1c1aff' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>bathymetry at RHO-points</dd><dt><span>units :</span></dt><dd>meter</dd><dt><span>field :</span></dt><dd>bath, scalar</dd></dl></div><div class='xr-var-data'><pre>[320295 values with dtype=float64]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>hc</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-44a92555-5762-4040-8639-7b8aa7198bb4' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-44a92555-5762-4040-8639-7b8aa7198bb4' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-2066fcd0-13d5-4350-926c-9333c7354ecf' class='xr-var-data-in' type='checkbox'><label for='data-2066fcd0-13d5-4350-926c-9333c7354ecf' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>S-coordinate parameter, critical depth</dd><dt><span>units :</span></dt><dd>meter</dd></dl></div><div class='xr-var-data'><pre>array(400.)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>latent</span></div><div class='xr-var-dims'>(ocean_time, eta_rho, xi_rho)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-ea267d31-eb5c-48cd-a896-2671f68e44d8' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-ea267d31-eb5c-48cd-a896-2671f68e44d8' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-7343abb0-8b2a-4040-bc8e-5132bb1d8f5b' class='xr-var-data-in' type='checkbox'><label for='data-7343abb0-8b2a-4040-bc8e-5132bb1d8f5b' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>net latent heat flux</dd><dt><span>units :</span></dt><dd>watt meter-2</dd><dt><span>negative_value :</span></dt><dd>upward flux, cooling</dd><dt><span>positive_value :</span></dt><dd>downward flux, heating</dd><dt><span>time :</span></dt><dd>ocean_time</dd><dt><span>field :</span></dt><dd>latent heat flux, scalar, series</dd></dl></div><div class='xr-var-data'><pre>[640590 values with dtype=float32]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>lwrad</span></div><div class='xr-var-dims'>(ocean_time, eta_rho, xi_rho)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-d0072bfa-ac17-4b69-80b0-818c5487e536' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-d0072bfa-ac17-4b69-80b0-818c5487e536' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-d6c1e07a-6111-4123-aceb-d2c3defc54ab' class='xr-var-data-in' type='checkbox'><label for='data-d6c1e07a-6111-4123-aceb-d2c3defc54ab' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>net longwave radiation flux</dd><dt><span>units :</span></dt><dd>watt meter-2</dd><dt><span>negative_value :</span></dt><dd>upward flux, cooling</dd><dt><span>positive_value :</span></dt><dd>downward flux, heating</dd><dt><span>time :</span></dt><dd>ocean_time</dd><dt><span>field :</span></dt><dd>longwave radiation, scalar, series</dd></dl></div><div class='xr-var-data'><pre>[640590 values with dtype=float32]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>mask_psi</span></div><div class='xr-var-dims'>(eta_psi, xi_psi)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-401570a4-d746-4931-8887-21d31d15004a' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-401570a4-d746-4931-8887-21d31d15004a' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-eb5e2fa5-d313-4d78-82f3-9df62ed08274' class='xr-var-data-in' type='checkbox'><label for='data-eb5e2fa5-d313-4d78-82f3-9df62ed08274' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>mask on psi-points</dd><dt><span>flag_values :</span></dt><dd>[0. 1.]</dd><dt><span>flag_meanings :</span></dt><dd>land water</dd></dl></div><div class='xr-var-data'><pre>[319152 values with dtype=float64]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>mask_rho</span></div><div class='xr-var-dims'>(eta_rho, xi_rho)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-de968da4-c6fc-4549-91a0-8106d3c77255' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-de968da4-c6fc-4549-91a0-8106d3c77255' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-7b684323-796c-4774-b32d-af8e78831746' class='xr-var-data-in' type='checkbox'><label for='data-7b684323-796c-4774-b32d-af8e78831746' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>mask on RHO-points</dd><dt><span>flag_values :</span></dt><dd>[0. 1.]</dd><dt><span>flag_meanings :</span></dt><dd>land water</dd></dl></div><div class='xr-var-data'><pre>[320295 values with dtype=float64]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>mask_u</span></div><div class='xr-var-dims'>(eta_u, xi_u)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-073382a4-25ed-418a-86ec-3d1703c28dc9' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-073382a4-25ed-418a-86ec-3d1703c28dc9' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-59eb69f9-b9c4-4ea0-b48f-ca10ea65e61d' class='xr-var-data-in' type='checkbox'><label for='data-59eb69f9-b9c4-4ea0-b48f-ca10ea65e61d' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>mask on U-points</dd><dt><span>flag_values :</span></dt><dd>[0. 1.]</dd><dt><span>flag_meanings :</span></dt><dd>land water</dd></dl></div><div class='xr-var-data'><pre>[319806 values with dtype=float64]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>mask_v</span></div><div class='xr-var-dims'>(eta_v, xi_v)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-f818b039-ea49-4f1b-a9ac-b11003f82201' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-f818b039-ea49-4f1b-a9ac-b11003f82201' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-1fcb9c0c-728e-41d7-b1a9-0cf9030f76ef' class='xr-var-data-in' type='checkbox'><label for='data-1fcb9c0c-728e-41d7-b1a9-0cf9030f76ef' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>mask on V-points</dd><dt><span>flag_values :</span></dt><dd>[0. 1.]</dd><dt><span>flag_meanings :</span></dt><dd>land water</dd></dl></div><div class='xr-var-data'><pre>[319640 values with dtype=float64]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>nHIS</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>int32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-945040ec-b8da-4658-81f5-f37a4f467b92' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-945040ec-b8da-4658-81f5-f37a4f467b92' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-06f9ec12-388c-46fb-ae1a-7fb5fea45567' class='xr-var-data-in' type='checkbox'><label for='data-06f9ec12-388c-46fb-ae1a-7fb5fea45567' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>number of time-steps between history records</dd></dl></div><div class='xr-var-data'><pre>array(360, dtype=int32)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>nRST</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>int32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-203b2733-e163-43a4-83a1-6bf6db4335ba' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-203b2733-e163-43a4-83a1-6bf6db4335ba' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-dbfb5ab4-07fa-4e40-b3d5-58f3f94d6af1' class='xr-var-data-in' type='checkbox'><label for='data-dbfb5ab4-07fa-4e40-b3d5-58f3f94d6af1' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>number of time-steps between restart records</dd></dl></div><div class='xr-var-data'><pre>array(8640, dtype=int32)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>ndefHIS</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>int32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-21daa8ac-2309-451a-805a-f0ddbfe05962' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-21daa8ac-2309-451a-805a-f0ddbfe05962' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-333f7b06-ca2c-4502-8d6b-a7096c00eb4d' class='xr-var-data-in' type='checkbox'><label for='data-333f7b06-ca2c-4502-8d6b-a7096c00eb4d' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>number of time-steps between the creation of history files</dd></dl></div><div class='xr-var-data'><pre>array(2880, dtype=int32)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>ndtfast</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>int32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-27121f73-59f2-4ddc-bbbc-289de1406666' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-27121f73-59f2-4ddc-bbbc-289de1406666' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-4d91d9e0-0642-40a2-8eea-58cdc3c2e0c2' class='xr-var-data-in' type='checkbox'><label for='data-4d91d9e0-0642-40a2-8eea-58cdc3c2e0c2' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>number of short time-steps</dd></dl></div><div class='xr-var-data'><pre>array(30, dtype=int32)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>nl_tnu2</span></div><div class='xr-var-dims'>(tracer)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-df48da19-85f6-496b-882d-a2ed4ff9cf90' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-df48da19-85f6-496b-882d-a2ed4ff9cf90' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-83849f81-504f-4858-8ce5-82d8e627bb06' class='xr-var-data-in' type='checkbox'><label for='data-83849f81-504f-4858-8ce5-82d8e627bb06' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>nonlinear model Laplacian mixing coefficient for tracers</dd><dt><span>units :</span></dt><dd>meter2 second-1</dd></dl></div><div class='xr-var-data'><pre>array([15., 15.])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>nl_visc2</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-cffb2e22-f874-41e1-9b03-b97746ee2041' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-cffb2e22-f874-41e1-9b03-b97746ee2041' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-de98294d-4008-40c7-9c6a-794251d181c0' class='xr-var-data-in' type='checkbox'><label for='data-de98294d-4008-40c7-9c6a-794251d181c0' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>nonlinear model Laplacian mixing coefficient for momentum</dd><dt><span>units :</span></dt><dd>meter2 second-1</dd></dl></div><div class='xr-var-data'><pre>array(15.)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>ntimes</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>int32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-250eb537-824a-4cea-9ff1-e3dd5e84d158' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-250eb537-824a-4cea-9ff1-e3dd5e84d158' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-74c69a5b-ec43-4071-86e9-4afb48ca148f' class='xr-var-data-in' type='checkbox'><label for='data-74c69a5b-ec43-4071-86e9-4afb48ca148f' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>number of long time-steps</dd></dl></div><div class='xr-var-data'><pre>array(8640, dtype=int32)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>pm</span></div><div class='xr-var-dims'>(eta_rho, xi_rho)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-36b11915-6228-4db0-b5cd-6ccaf31477a4' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-36b11915-6228-4db0-b5cd-6ccaf31477a4' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-7e9fbbd2-7bb9-486d-a0a6-4b2efbeb248c' class='xr-var-data-in' type='checkbox'><label for='data-7e9fbbd2-7bb9-486d-a0a6-4b2efbeb248c' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>curvilinear coordinate metric in XI</dd><dt><span>units :</span></dt><dd>meter-1</dd><dt><span>field :</span></dt><dd>pm, scalar</dd></dl></div><div class='xr-var-data'><pre>[320295 values with dtype=float64]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>pn</span></div><div class='xr-var-dims'>(eta_rho, xi_rho)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-430a50dc-04d0-4a96-81cd-c30411dbe159' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-430a50dc-04d0-4a96-81cd-c30411dbe159' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-9a938cc7-50c9-4a5c-bebd-91f5e2f797fa' class='xr-var-data-in' type='checkbox'><label for='data-9a938cc7-50c9-4a5c-bebd-91f5e2f797fa' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>curvilinear coordinate metric in ETA</dd><dt><span>units :</span></dt><dd>meter-1</dd><dt><span>field :</span></dt><dd>pn, scalar</dd></dl></div><div class='xr-var-data'><pre>[320295 values with dtype=float64]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>rdrg</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-3f92dbd2-b4fd-4a08-9890-f4e5f0e43b20' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-3f92dbd2-b4fd-4a08-9890-f4e5f0e43b20' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-f012add3-0456-4cde-b785-2188e6a6ed3b' class='xr-var-data-in' type='checkbox'><label for='data-f012add3-0456-4cde-b785-2188e6a6ed3b' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>linear drag coefficient</dd><dt><span>units :</span></dt><dd>meter second-1</dd></dl></div><div class='xr-var-data'><pre>array(0.0003)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>rdrg2</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-4b4e3bad-d002-4ad3-b13e-0d4623e4e19f' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-4b4e3bad-d002-4ad3-b13e-0d4623e4e19f' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-c29ee9da-e007-419a-b109-527cea26da32' class='xr-var-data-in' type='checkbox'><label for='data-c29ee9da-e007-419a-b109-527cea26da32' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>quadratic drag coefficient</dd></dl></div><div class='xr-var-data'><pre>array(0.003)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>rho</span></div><div class='xr-var-dims'>(ocean_time, s_rho, eta_rho, xi_rho)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-38eeae9a-7f53-4d9b-84de-b77ae49bba03' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-38eeae9a-7f53-4d9b-84de-b77ae49bba03' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-e697c13e-42a2-49e6-9a19-ccfdeec8f678' class='xr-var-data-in' type='checkbox'><label for='data-e697c13e-42a2-49e6-9a19-ccfdeec8f678' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>density anomaly</dd><dt><span>units :</span></dt><dd>kilogram meter-3</dd><dt><span>time :</span></dt><dd>ocean_time</dd><dt><span>field :</span></dt><dd>density, scalar, series</dd></dl></div><div class='xr-var-data'><pre>[32029500 values with dtype=float32]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>rho0</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-a3898af2-75ea-4133-a240-55be25c8dabe' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-a3898af2-75ea-4133-a240-55be25c8dabe' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-f7708c8e-a64f-4ba6-9ec2-649c4ac93874' class='xr-var-data-in' type='checkbox'><label for='data-f7708c8e-a64f-4ba6-9ec2-649c4ac93874' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>mean density used in Boussinesq approximation</dd><dt><span>units :</span></dt><dd>kilogram meter-3</dd></dl></div><div class='xr-var-data'><pre>array(1025.)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>salt</span></div><div class='xr-var-dims'>(ocean_time, s_rho, eta_rho, xi_rho)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-5fe2e0cc-9e55-4d03-94a4-12d62469044b' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-5fe2e0cc-9e55-4d03-94a4-12d62469044b' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-ff26dd31-5410-4e4e-af76-5de6fda84153' class='xr-var-data-in' type='checkbox'><label for='data-ff26dd31-5410-4e4e-af76-5de6fda84153' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>salinity</dd><dt><span>time :</span></dt><dd>ocean_time</dd><dt><span>field :</span></dt><dd>salinity, scalar, series</dd></dl></div><div class='xr-var-data'><pre>[32029500 values with dtype=float32]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>sensible</span></div><div class='xr-var-dims'>(ocean_time, eta_rho, xi_rho)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-b2c4246a-4100-4d57-b0e2-629c8186d303' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-b2c4246a-4100-4d57-b0e2-629c8186d303' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-0f8c77c4-57cc-40cd-bd01-85e9123d5841' class='xr-var-data-in' type='checkbox'><label for='data-0f8c77c4-57cc-40cd-bd01-85e9123d5841' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>net sensible heat flux</dd><dt><span>units :</span></dt><dd>watt meter-2</dd><dt><span>negative_value :</span></dt><dd>upward flux, cooling</dd><dt><span>positive_value :</span></dt><dd>downward flux, heating</dd><dt><span>time :</span></dt><dd>ocean_time</dd><dt><span>field :</span></dt><dd>sensible heat flux, scalar, series</dd></dl></div><div class='xr-var-data'><pre>[640590 values with dtype=float32]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>shflux</span></div><div class='xr-var-dims'>(ocean_time, eta_rho, xi_rho)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-d6aaaa87-4efe-485d-a0e0-7f3fc95f2aa2' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-d6aaaa87-4efe-485d-a0e0-7f3fc95f2aa2' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-cde99dbd-ef28-4a4d-b2fc-4142b0fcb8b6' class='xr-var-data-in' type='checkbox'><label for='data-cde99dbd-ef28-4a4d-b2fc-4142b0fcb8b6' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>surface net heat flux</dd><dt><span>units :</span></dt><dd>watt meter-2</dd><dt><span>negative_value :</span></dt><dd>upward flux, cooling</dd><dt><span>positive_value :</span></dt><dd>downward flux, heating</dd><dt><span>time :</span></dt><dd>ocean_time</dd><dt><span>field :</span></dt><dd>surface heat flux, scalar, series</dd></dl></div><div class='xr-var-data'><pre>[640590 values with dtype=float32]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>spherical</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>int32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-d4cc9663-cf81-4b9b-a18e-555f9aae6dc1' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-d4cc9663-cf81-4b9b-a18e-555f9aae6dc1' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-ad54e42e-e258-4a22-bb28-3754141ee7ea' class='xr-var-data-in' type='checkbox'><label for='data-ad54e42e-e258-4a22-bb28-3754141ee7ea' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>grid type logical switch</dd><dt><span>flag_values :</span></dt><dd>[0 1]</dd><dt><span>flag_meanings :</span></dt><dd>Cartesian spherical</dd></dl></div><div class='xr-var-data'><pre>array(1, dtype=int32)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>ssflux</span></div><div class='xr-var-dims'>(ocean_time, eta_rho, xi_rho)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-ec9f93b5-8a9b-4257-8fd1-e015441f0310' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-ec9f93b5-8a9b-4257-8fd1-e015441f0310' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-6036d788-87f8-450e-aadc-e9ddf261edd4' class='xr-var-data-in' type='checkbox'><label for='data-6036d788-87f8-450e-aadc-e9ddf261edd4' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>surface net salt flux, (E-P)*SALT</dd><dt><span>units :</span></dt><dd>meter second-1</dd><dt><span>negative_value :</span></dt><dd>upward flux, freshening (net precipitation)</dd><dt><span>positive_value :</span></dt><dd>downward flux, salting (net evaporation)</dd><dt><span>time :</span></dt><dd>ocean_time</dd><dt><span>field :</span></dt><dd>surface net salt flux, scalar, series</dd></dl></div><div class='xr-var-data'><pre>[640590 values with dtype=float32]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>sustr</span></div><div class='xr-var-dims'>(ocean_time, eta_u, xi_u)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-80e7dc75-cbf3-4ee8-bd43-0963dc3d0241' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-80e7dc75-cbf3-4ee8-bd43-0963dc3d0241' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-29a6536c-01eb-4e95-9731-e6c31df790b2' class='xr-var-data-in' type='checkbox'><label for='data-29a6536c-01eb-4e95-9731-e6c31df790b2' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>surface u-momentum stress</dd><dt><span>units :</span></dt><dd>newton meter-2</dd><dt><span>time :</span></dt><dd>ocean_time</dd><dt><span>field :</span></dt><dd>surface u-momentum stress, scalar, series</dd></dl></div><div class='xr-var-data'><pre>[639612 values with dtype=float32]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>svstr</span></div><div class='xr-var-dims'>(ocean_time, eta_v, xi_v)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-ad06582c-846f-48a2-b617-7236d7b57688' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-ad06582c-846f-48a2-b617-7236d7b57688' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-f9ac6ce1-4ac5-474d-b43b-f238569e00cd' class='xr-var-data-in' type='checkbox'><label for='data-f9ac6ce1-4ac5-474d-b43b-f238569e00cd' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>surface v-momentum stress</dd><dt><span>units :</span></dt><dd>newton meter-2</dd><dt><span>time :</span></dt><dd>ocean_time</dd><dt><span>field :</span></dt><dd>surface v-momentum stress, scalar, series</dd></dl></div><div class='xr-var-data'><pre>[639280 values with dtype=float32]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>swrad</span></div><div class='xr-var-dims'>(ocean_time, eta_rho, xi_rho)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-e395893b-557f-45c5-a867-9354d7d891cf' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-e395893b-557f-45c5-a867-9354d7d891cf' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-719558ec-22c9-4531-bc70-d472b57263ae' class='xr-var-data-in' type='checkbox'><label for='data-719558ec-22c9-4531-bc70-d472b57263ae' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>solar shortwave radiation flux</dd><dt><span>units :</span></dt><dd>watt meter-2</dd><dt><span>negative_value :</span></dt><dd>upward flux, cooling</dd><dt><span>positive_value :</span></dt><dd>downward flux, heating</dd><dt><span>time :</span></dt><dd>ocean_time</dd><dt><span>field :</span></dt><dd>shortwave radiation, scalar, series</dd></dl></div><div class='xr-var-data'><pre>[640590 values with dtype=float32]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>temp</span></div><div class='xr-var-dims'>(ocean_time, s_rho, eta_rho, xi_rho)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-1597fd26-b01f-491b-86df-adb18f47afc0' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-1597fd26-b01f-491b-86df-adb18f47afc0' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-7a5a73b9-8855-469a-a7db-183f9ac6d5db' class='xr-var-data-in' type='checkbox'><label for='data-7a5a73b9-8855-469a-a7db-183f9ac6d5db' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>potential temperature</dd><dt><span>units :</span></dt><dd>Celsius</dd><dt><span>time :</span></dt><dd>ocean_time</dd><dt><span>field :</span></dt><dd>temperature, scalar, series</dd></dl></div><div class='xr-var-data'><pre>[32029500 values with dtype=float32]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>theta_b</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-200854d2-604b-4347-bbd0-fe98a845f033' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-200854d2-604b-4347-bbd0-fe98a845f033' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-d9043da8-3f21-44ce-8188-5cd18df82d83' class='xr-var-data-in' type='checkbox'><label for='data-d9043da8-3f21-44ce-8188-5cd18df82d83' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>S-coordinate bottom control parameter</dd></dl></div><div class='xr-var-data'><pre>array(2.)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>theta_s</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-64018952-0b95-4f4a-be07-46923d5dfe0d' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-64018952-0b95-4f4a-be07-46923d5dfe0d' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-dcefb53c-8c67-430f-bb59-bf9ad46db8a6' class='xr-var-data-in' type='checkbox'><label for='data-dcefb53c-8c67-430f-bb59-bf9ad46db8a6' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>S-coordinate surface control parameter</dd></dl></div><div class='xr-var-data'><pre>array(10.)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>u</span></div><div class='xr-var-dims'>(ocean_time, s_rho, eta_u, xi_u)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-02105b3b-c9e9-4b95-b1fe-67176b899a7b' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-02105b3b-c9e9-4b95-b1fe-67176b899a7b' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-c72ec1ba-f811-4ad4-96bb-82d3b3814e9b' class='xr-var-data-in' type='checkbox'><label for='data-c72ec1ba-f811-4ad4-96bb-82d3b3814e9b' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>u-momentum component</dd><dt><span>units :</span></dt><dd>meter second-1</dd><dt><span>time :</span></dt><dd>ocean_time</dd><dt><span>field :</span></dt><dd>u-velocity, scalar, series</dd></dl></div><div class='xr-var-data'><pre>[31980600 values with dtype=float32]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>ubar</span></div><div class='xr-var-dims'>(ocean_time, eta_u, xi_u)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-6d2e06fb-d66f-445f-b208-31a71936ea61' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-6d2e06fb-d66f-445f-b208-31a71936ea61' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-c344a98b-6807-4491-a1c8-d07574c6f374' class='xr-var-data-in' type='checkbox'><label for='data-c344a98b-6807-4491-a1c8-d07574c6f374' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>vertically integrated u-momentum component</dd><dt><span>units :</span></dt><dd>meter second-1</dd><dt><span>time :</span></dt><dd>ocean_time</dd><dt><span>field :</span></dt><dd>ubar-velocity, scalar, series</dd></dl></div><div class='xr-var-data'><pre>[639612 values with dtype=float32]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>v</span></div><div class='xr-var-dims'>(ocean_time, s_rho, eta_v, xi_v)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-187d7b6e-e44e-4d5b-981d-a332bf2cfae7' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-187d7b6e-e44e-4d5b-981d-a332bf2cfae7' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-73a6021d-3f6c-4f77-bb2b-5d46b0959cf0' class='xr-var-data-in' type='checkbox'><label for='data-73a6021d-3f6c-4f77-bb2b-5d46b0959cf0' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>v-momentum component</dd><dt><span>units :</span></dt><dd>meter second-1</dd><dt><span>time :</span></dt><dd>ocean_time</dd><dt><span>field :</span></dt><dd>v-velocity, scalar, series</dd></dl></div><div class='xr-var-data'><pre>[31964000 values with dtype=float32]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>vbar</span></div><div class='xr-var-dims'>(ocean_time, eta_v, xi_v)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-312e2d7d-9e7d-4b3d-867a-61ec9ee32540' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-312e2d7d-9e7d-4b3d-867a-61ec9ee32540' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-5541cc41-86f6-43a0-b024-2cb816012259' class='xr-var-data-in' type='checkbox'><label for='data-5541cc41-86f6-43a0-b024-2cb816012259' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>vertically integrated v-momentum component</dd><dt><span>units :</span></dt><dd>meter second-1</dd><dt><span>time :</span></dt><dd>ocean_time</dd><dt><span>field :</span></dt><dd>vbar-velocity, scalar, series</dd></dl></div><div class='xr-var-data'><pre>[639280 values with dtype=float32]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>w</span></div><div class='xr-var-dims'>(ocean_time, s_w, eta_rho, xi_rho)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-a4ef8e61-95cd-4264-ba54-0d2429b26e42' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-a4ef8e61-95cd-4264-ba54-0d2429b26e42' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-95d98fea-7939-47eb-9acf-9ac4d6024f57' class='xr-var-data-in' type='checkbox'><label for='data-95d98fea-7939-47eb-9acf-9ac4d6024f57' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>vertical momentum component</dd><dt><span>units :</span></dt><dd>meter second-1</dd><dt><span>time :</span></dt><dd>ocean_time</dd><dt><span>field :</span></dt><dd>w-velocity, scalar, series</dd></dl></div><div class='xr-var-data'><pre>[32670090 values with dtype=float32]</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>xl</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-8dd5be79-c215-4ab3-a6e2-9b78c2d6cf52' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-8dd5be79-c215-4ab3-a6e2-9b78c2d6cf52' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-8f743a57-2e59-45db-985a-b106dee9c91c' class='xr-var-data-in' type='checkbox'><label for='data-8f743a57-2e59-45db-985a-b106dee9c91c' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>domain length in the XI-direction</dd><dt><span>units :</span></dt><dd>meter</dd></dl></div><div class='xr-var-data'><pre>array(1983206.706833)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>zeta</span></div><div class='xr-var-dims'>(ocean_time, eta_rho, xi_rho)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>...</div><input id='attrs-e7bc1e04-2751-438b-9888-1a911501f75e' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-e7bc1e04-2751-438b-9888-1a911501f75e' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-ad7b3d74-1523-4732-8fc7-fc6d149bec6c' class='xr-var-data-in' type='checkbox'><label for='data-ad7b3d74-1523-4732-8fc7-fc6d149bec6c' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>free-surface</dd><dt><span>units :</span></dt><dd>meter</dd><dt><span>time :</span></dt><dd>ocean_time</dd><dt><span>field :</span></dt><dd>free-surface, scalar, series</dd></dl></div><div class='xr-var-data'><pre>[640590 values with dtype=float32]</pre></div></li></ul></div></li><li class='xr-section-item'><input id='section-a6a0fcfa-725b-490e-98a7-0018fc0e882c' class='xr-section-summary-in' type='checkbox'  ><label for='section-a6a0fcfa-725b-490e-98a7-0018fc0e882c' class='xr-section-summary' >Attributes: <span>(26)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><dl class='xr-attrs'><dt><span>file :</span></dt><dd>GOM_hurr_wrf_19950930-06.ocn_0002.hi.1995-10-04_09:00:00.nc</dd><dt><span>format :</span></dt><dd>netCDF-3 classic file</dd><dt><span>Conventions :</span></dt><dd>CF-1.4</dd><dt><span>type :</span></dt><dd>ROMS/TOMS history file</dd><dt><span>title :</span></dt><dd>BP_2010 Coupled Hindcast Run</dd><dt><span>rst_file :</span></dt><dd>gom03_rst.nc</dd><dt><span>his_base :</span></dt><dd>GOM_hurr_wrf_19950930-06.ocn_0002.hi</dd><dt><span>grd_file :</span></dt><dd>./gom03_grd_N050_coast.nc</dd><dt><span>ini_file :</span></dt><dd>./gom03_N050_coast_ini_COPERNICUS_RA025_1995_Opal.nc</dd><dt><span>bry_file :</span></dt><dd>./gom03_N050_coast_bry_COPERNICUS_RA025_1995_Opal.nc</dd><dt><span>script_file :</span></dt><dd>ocean.in</dd><dt><span>svn_url :</span></dt><dd>https://www.myroms.org/svn/src/trunk</dd><dt><span>svn_rev :</span></dt><dd>Unversioned directory</dd><dt><span>code_dir :</span></dt><dd>/scratch/06667/liu6/GOM_hurr_wrf_19950930-06/bld/ocn/src</dd><dt><span>header_dir :</span></dt><dd>/scratch/06667/liu6/GOM_hurr_wrf_19950930-06/bld/ocn/obj/../src/Apps/gom3x</dd><dt><span>header_file :</span></dt><dd>gom3x.h</dd><dt><span>os :</span></dt><dd>Linux</dd><dt><span>cpu :</span></dt><dd>x86_64</dd><dt><span>compiler_system :</span></dt><dd>ifort</dd><dt><span>compiler_command :</span></dt><dd>/opt/apps/intel18/cray_mpich/7.7.3/bin/mpif90</dd><dt><span>compiler_flags :</span></dt><dd>-fp-model precise -ip -O2 -debug minimal -free -free</dd><dt><span>tiling :</span></dt><dd>020x018</dd><dt><span>history :</span></dt><dd>Thu Nov  4 09:41:12 2021: ncks -d ocean_time,0,1 roms_test.nc ROMS/roms_test.nc\nROMS/TOMS, Version 3.5, Tuesday - September 22, 2020 -  6:42:05 PM</dd><dt><span>ana_file :</span></dt><dd>ROMS/Functionals/ana_btflux.h, ROMS/Functionals/ana_hmixcoef.h, ROMS/Functionals/ana_nudgcoef.h</dd><dt><span>CPP_options :</span></dt><dd>TXGLO, ATM_PRESS, ANA_BSFLUX, ANA_BTFLUX, ASSUMED_SHAPE, CCSMCOUPLED, CURVGRID, DIFF_GRID, DJ_GRADPS, DOUBLE_PRECISION, EAST_FSCHAPMAN, EAST_M2FLATHER, EAST_M3NUDGING, EAST_M3RADIATION, EAST_TNUDGING, EAST_TRADIATION, EAST_VOLCONS, EMINUSP, LMD_BKPP, LMD_CONVEC, LMD_MIXING, LMD_NONLOCAL, LMD_RIMIX, LMD_SKPP, MASKING, MIX_GEO_TS, MIX_S_UV, MPI, NONLINEAR, NONLIN_EOS, NORTH_VOLCONS, NORTH_FSCHAPMAN, NORTH_M2FLATHER, NORTH_M3NUDGING, NORTH_M3RADIATION, NORTH_TNUDGING, NORTH_TRADIATION, POWER_LAW, PROFILE, RADIATION_2D, RI_HORAVG, RI_VERAVG, !RST_SINGLE, SALINITY, SOLAR_SOURCE, SOLVE3D, SOUTH_FSCHAPMAN, SOUTH_M2FLATHER, SOUTH_M3NUDGING, SOUTH_M3RADIATION, SOUTH_TNUDGING, SOUTH_TRADIATION, SOUTH_VOLCONS, TS_A4HADVECTION, TS_A4VADVECTION, TS_DIF2, UV_ADV, UV_COR, UV_U3HADVECTION, UV_C4VADVECTION, UV_QDRAG, UV_VIS2, VAR_RHO_2D, VISC_GRID, WESTERN_WALL</dd><dt><span>NCO :</span></dt><dd>netCDF Operators version 4.9.7 (Homepage = http://nco.sf.net, Code = http://github.com/nco/nco)</dd></dl></div></li></ul></div></div>\n\n\n\n### Creating the grid object\n\nNext we create the xgcm `Grid` object from the xarray dataset. The axes will be assumed to be non-periodic, unless specified otherwise.\n\n\n\n\n```python\nds = ds.rename({'eta_u': 'eta_rho','xi_v': 'xi_rho'})\n\ncoords = {\n        \"X\": {\"center\": \"xi_rho\", \"inner\": \"xi_u\"},\n        \"Y\": {\"center\": \"eta_rho\", \"inner\": \"eta_v\"},\n        \"Z\": {\"center\": \"s_rho\", \"outer\": \"s_w\"},\n    }\n\ngrid = xgcm.Grid(ds, coords=coords, periodic=[])\ngrid\n```\n\n\n\n\n    <xgcm.Grid>\n    X Axis (not periodic, boundary=None):\n      * center   xi_rho --> inner\n      * inner    xi_u --> center\n    Y Axis (not periodic, boundary=None):\n      * center   eta_rho --> inner\n      * inner    eta_v --> center\n    Z Axis (not periodic, boundary=None):\n      * center   s_rho --> outer\n      * outer    s_w --> center\n\n\n\nWe see that xgcm identified three different axes: X (longitude), Y (latitude), Z (depth).\n\n## Horizontal Interpolation\n\n### Flow speed\n\n$$ \\large Speed = \\sqrt{U_{rho}^2 + V_{rho}^2} \\ . $$\n\nBelow we use xgcm to compute the horizontal speed, at the surface, on the RHO-grid.\n\n\n```python\nU = ds.u.isel(ocean_time=0,s_rho=-1)\nV = ds.v.isel(ocean_time=0,s_rho=-1)\n\nU_rho = grid.interp(U, \"X\", to=\"center\", boundary=\"extend\")\nV_rho = grid.interp(V, \"Y\", to=\"center\", boundary=\"extend\")\n\nspeed = np.sqrt(U_rho ** 2 + V_rho ** 2)\nspeed.plot()\n```\n\n## What about the curvilinear grid?\n\n<div>\n\nsource:<a href=\"https://doi.org/10.1111/1365-2478.12844\">https://doi.org/10.1111/1365-2478.12844</a>\n</div>\n\n</br></br></br>\n\n#### Grid metrics\n\n$$ \\large \\frac{\\partial x}{\\partial \\xi} = dx = \\frac{1}{pm}\\ . $$\n$$ \\large\\frac{\\partial y}{\\partial \\eta} = dy = \\frac{1}{pn}\\ . $$\n\n</br></br></br>\n### Relative Vorticity\n\nThe relative vorticity is a fundamental quantity of interest in ocean circulation theory. It is defined as\n\n$$ \\large \\zeta = - \\frac{\\partial u}{\\partial y} + \\frac{\\partial v}{\\partial x} \\ . $$\n\n$$ \\large \\zeta = - \\frac{\\partial u}{\\partial \\eta}\\frac{\\partial \\eta}{\\partial y} + \\frac{\\partial v}{\\partial \\xi}\\frac{\\partial \\xi}{\\partial x} \\ . $$\n\nOn the c-grid, including the ROMS metrics, we get the expression: \n\n$$ \\large \\zeta =  (- \\delta_j u * pn + \\delta_i v * pm ) \\ . $$\n\nIn xgcm, we calculate this quanity as\n\n\n```python\nU = ds.u.isel(ocean_time=0,s_rho=-1)\nV = ds.v.isel(ocean_time=0,s_rho=-1)\n\ndUdy = grid.diff(U, axis=\"Y\", boundary=\"extend\")\npn = grid.interp(grid.interp(ds.pn, \"X\"), \"Y\")\n    \n\ndVdx = grid.diff(V, axis=\"X\", boundary=\"extend\")\npm=grid.interp(grid.interp(ds.pm, \"X\"), \"Y\")\n\n\n```\n\n\n<div>\n\nsource:<a href=\"https://www.myroms.org/wiki/Numerical_Solution_Technique\">myroms.org</a>\n</div>\n\n\n\n```python\nzeta = dVdx*pm - dUdy*pn\nzeta.plot(vmin=-1e-4, vmax=1e-4,cmap='bwr')\n```\n\n\n\n\n## Exercise\n\n### Calculate the divergence of velocity\n\nThe divergence of the horizontal flow is is expressed as\n\n$$ \\large \\frac{\\partial u}{\\partial x} + \\frac{\\partial v}{\\partial y} $$\n\n\nCompute the divergence on the C-grid, using xgcm, and plot like previous example. \n\n\n```python\nU = ds.u.isel(ocean_time=0,s_rho=0)\nV = ds.v.isel(ocean_time=0,s_rho=0)\n\n\n```\n\n-------------------------------\n# Vertical interpolation\n\n\n<div>\n\n\n    \nsource:<a href=\"https://www.myroms.org/wiki/Numerical_Solution_Technique\">myroms.org</a>\n</div>\n\n## ROMS Sigma coordinate transformation\n\n$$ \\large \\begin{align}z(x,y,\\sigma,t) &= \\zeta(x,y,t) + \\left[\\zeta(x,y,t) + h(x,y)\\right] \\, S(x,y,\\sigma), \\\\\n        S(x,y,\\sigma) &= \\frac{h_c \\, \\sigma + h(x,y)\\, C(\\sigma)}{h_c + h(x,y)} \\end{align} $$\n\n\n```python\nZo_rho = (ds.hc * ds.s_rho + ds.Cs_r * ds.h) / (ds.hc + ds.h)\nz_rho = ds.zeta + (ds.zeta + ds.h) * Zo_rho\n\nz_rho.attrs = {\n            \"long_name\": \"Depth at RHO-points\",\n            \"time\": \"ocean_time\",\n            \"field\": \"z_rho, scalar, series\",\n            \"units\": \"m\",\n        }\n\nds.coords[\"z_rho\"] = z_rho\n```\n\n\n```python\nfig, (ax1, ax2) = plt.subplots(ncols=2, figsize=[15,5])\nfig.subplots_adjust(wspace=1.)\n\n\ntemp_s = ds.temp.isel(ocean_time=0,eta_rho=200,xi_rho=300)\ntemp_s.plot(ax=ax1, y='s_rho', yincrease=True, marker='.')\n\n\nz_s = ds.z_rho.isel(ocean_time=0,eta_rho=200,xi_rho=300)\nz_s.plot(ax=ax2, y='s_rho', yincrease=True, marker='.')\n\n\nax1.set_title('Temp profile (T vs s_rho)')\nax2.set_title('Depth profile (z_rho vs s_rho)')\n\n```\n\n\n```python\nimport numpy as np\nZ_target = np.linspace(0, -250, 30)\n\ntemp_transformed = grid.transform(ds.temp, 'Z', Z_target, target_data=ds.z_rho)\n```\n\n    /scratch/training/python_geos/conda/envs/training/lib/python3.7/site-packages/numba/np/ufunc/gufunc.py:151: RuntimeWarning: invalid value encountered in _interp_1d_linear\n      return self.ufunc(*args, **kwargs)\n\n\n\n```python\nfig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=[15,5])\nfig.subplots_adjust(wspace=0.5)\n\ntemp_s.plot(ax=ax1, y='s_rho', yincrease=True, marker='.')\nz_s.plot(ax=ax2, y='s_rho', yincrease=True, marker='.')\ntemp_transformed.isel(ocean_time=0,eta_rho=200,xi_rho=300).plot(ax=ax3,y='z_rho',yincrease=True, marker='.')\n\n\nax1.set_title('Temp profile (T vs s_rho)')\nax2.set_title('Depth profile (z_rho vs s_rho)')\nax3.set_title('Interpolated Temp (T vs z_rho)')\n```\n\n\n\n\n## Exercise\n\nThe depth profile of Salinity is shown below. Now try to plot Salinity as a profile of Temperature linearly interpolated between 16 and 28 C. \n\n\n```python\nsalt_s = ds.salt.isel(ocean_time=0,eta_rho=200,xi_rho=300)\nsalt_s.plot( y='s_rho', yincrease=True, marker='.')\n```\n\n\n```python\nT_target = np.linspace(16, 28, 20)\n\nsalt_transformed = # Enter your expression here\n\nfig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=[15,5])\nfig.subplots_adjust(wspace=0.5)\n\n\nds.salt.isel(ocean_time=0,eta_rho=200,xi_rho=300).plot(ax=ax1, y='s_rho', yincrease=True, marker='.')\nds.temp.isel(ocean_time=0,eta_rho=200,xi_rho=300).plot(ax=ax2, y='s_rho', yincrease=True, marker='.')\nsalt_transformed.isel(ocean_time=0,eta_rho=200,xi_rho=300).plot(ax=ax3, y='temp',yincrease=True, marker='.')\n\nax1.set_title('Salt profile (T vs s_rho)')\nax2.set_title('Temp profile (S vs s_rho)')\nax3.set_title('Interpolated Salt (S vs T)')\n```\n\n\n```python\nT_target = np.linspace(16, 28, 20)\n\nsalt_transformed = grid.transform(ds.salt, 'Z', T_target, target_data=ds.temp)\n\nfig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=[15,5])\nfig.subplots_adjust(wspace=0.5)\n\n\nds.salt.isel(ocean_time=0,eta_rho=200,xi_rho=300).plot(ax=ax1, y='s_rho', yincrease=True, marker='.')\nds.temp.isel(ocean_time=0,eta_rho=200,xi_rho=300).plot(ax=ax2, y='s_rho', yincrease=True, marker='.')\nsalt_transformed.isel(ocean_time=0,eta_rho=200,xi_rho=300).plot(ax=ax3, y='temp',yincrease=True, marker='.')\n\nax1.set_title('Salt profile (T vs s_rho)')\nax2.set_title('Temp profile (S vs s_rho)')\nax3.set_title('Interpolated Salt (S vs T)')\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "113ebc9132044caec89c703de58c87a19128a4fa", "size": 899284, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "4_xgcm_grid_utils.ipynb", "max_stars_repo_name": "abishekg7/python_geos", "max_stars_repo_head_hexsha": "19f3a1ff2150e443b1395a4359e8e21ae74d3ddd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4_xgcm_grid_utils.ipynb", "max_issues_repo_name": "abishekg7/python_geos", "max_issues_repo_head_hexsha": "19f3a1ff2150e443b1395a4359e8e21ae74d3ddd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4_xgcm_grid_utils.ipynb", "max_forks_repo_name": "abishekg7/python_geos", "max_forks_repo_head_hexsha": "19f3a1ff2150e443b1395a4359e8e21ae74d3ddd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-11-04T16:15:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T16:26:57.000Z", "avg_line_length": 801.5008912656, "max_line_length": 129744, "alphanum_fraction": 0.9209882529, "converted": true, "num_tokens": 40721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073333856566001, "lm_q2_score": 0.05921025489158706, "lm_q1q2_score": 0.024118313590580424}}
{"text": "Data Science\n====\n### Introduction and Overview\n\nAlessandro Gagliardi  \nSr. Data Scientist, [Glassdoor.com](Glassdoor.com)\n\n# Welcome!\n\nWelcome to General Assembly's Data Science course.\n\n<table border=\"0\" style=\"border-collapse:collapse;\" cellspacing=\"0\">\n<tr><td>Instructor:<td>Alessandro Gagliardi</td></tr>\n<tr><td></td><td>[ADFGagliardi+GA@Gmail.com](mailto:adfgagliardi+ga@gmail.com)</td></tr>\n<tr><td>TA:<td>Kevin Perko</td></tr>\n<tr><td></td><td>[KevinJPerko+GA@Gmail.com](mailto:kevinjperko+ga@gmail.com)</td></tr>\n<tr><td>Classes:<td>6:00pm-9:00pm, Mondays and Wednesdays</td></tr>\n<tr><td></td><td>January 20 \u2013 April 7, 2014 (no class February 17)</td></tr>\n<tr><td>Office Hours:<td>9:00pm-10:00pm Wednesdays after class</td></tr>\n<tr><td></td><td>or by appointment</td></tr>\n<!--tr><td>Outside of classwork:<td>Roughly 3 hours a week.-->\n</table>\n\nThe class will meet every Monday and Wednesday until April 7 except for February 17 which is Presidents' Day.  \n\nKevin, your TA, will hold office hours will be held immediately following class on Wednesdays and either of us will be available by appointment.\n\n## Who am I?\n\n- 1997 - 2001 - Studied Computer Science at UC Santa Cruz  \n- 2001 - 2002 - Developed web-based educational CRM at TMP.Worldwide in New York  \n- 2002 - 2003 - Took some time off  \n- 2003 - 2005 - Worked as a independent consultant for startups in New York\n- 2005 - 2010 - Studient Integrative Neuroscience at Rutgers\n- 2010 - 2011 - Taught Psychology and Neuroscience at USF, NDNU, CIIS \n- 2011 - 2014 - Returned to industry as a Data Scientist at Socialize (R.I.P.), Path, and Glassdoor\n\n## Who are you?\n\n- Your name\n- Where you work and what you do there\n- What you hope to get out of this course (in 1 sentence, please)\n\n1. Lecture  \n    A. What is Data Science?  \n    B. Goals of the Course  \n2. Lab  \n    A. Git setup  \n    B. IPython Notebook setup  \n    C. Working in Python\n\nBut first...\n\nSince today's my birthday, I thought I might have us warm up our brains with...\n\n# The Birthday Paradox!\n(credit to [Balthazar Rouberol](https://gist.github.com/brouberol/6524605) for preparing what follows)\n\nGiven a sample of _n_ people, we would like to calculate the probability _p_ that _at least_ one person has the same birthday as _any_ other person in the group.  \n<br />\n\nFirst: how many know this paradox? Keep the answer to yourselves.  \n\nThe rest of you: how big do you think this class would have to be in order for there to be >50% chance that two people have the same birthday?  \n\nAlternatively, what are the chances that two people in this class have the same birthday (including the TA and me).\n\n### Assumptions:\n\n* the probability distribution is uniform\n* all events are independant from each other  \n<br />\n\nP(A) is the probability of at least two people sharing the same birthday.\nP(A') is the probability that all birthdays are different.\n\n\\begin{equation}\n    P(A') = 1 - P(A)\n\\end{equation}\n\n## Calculating the probability\n\nFrom [Wikipedia](http://en.wikipedia.org/wiki/Birthday_problem)\n\nP(A') could be calculated as P(1) \u00d7 P(2) \u00d7 P(3) \u00d7 ... \u00d7 P(20).\n\nThe 20 independent events correspond to the 20 people, and can be defined in order. Each event can be defined as the corresponding person not sharing his/her birthday with any of the previously analyzed people. For Event 1, there are no previously analyzed people. Therefore, the probability, P(1), that person number 1 does not share his/her birthday with previously analyzed people is 1, or 100%. Ignoring leap years for this analysis, the probability of 1 can also be written as 365/365, for reasons that will become clear below.\n    \nFor Event 2, the only previously analyzed people is Person 1. Assuming that birthdays are equally likely to happen on each of the 365 days of the year, the probability, P(2), that Person 2 has a different birthday than Person 1 is 364/365. This is because, if Person 2 was born on any of the other 364 days of the year, Persons 1 and 2 will not share the same birthday.\n\nSimilarly, if Person 3 is born on any of the 363 days of the year other than the birthdays of Persons 1 and 2, Person 3 will not share their birthday. This makes the probability P(3) = 363/365.\n    \nThis analysis continues until Person 20 is reached, whose probability of not sharing his/her birthday with people analyzed before, P(20), is 346/365.\n    \nP(A') is equal to the product of these individual probabilities:\n\n        (1) P(A') = 365/365 \u00d7 364/365 \u00d7 363/365 \u00d7 362/365 \u00d7 ... \u00d7 346/365\n\nThe terms of equation (1) can be collected to arrive at:\n\n        (2) P(A') = (1/365)^23 \u00d7 (365 \u00d7 364 \u00d7 363 \u00d7 ... \u00d7 346)\n                  = 0.588\n\n        (3) P(A) = 1 - P(A') = 0.411 = 41.1%\n\n## Generalization\n\n\\begin{eqnarray}\nP(n') &=& 1 \\times (1 - \\dfrac{1}{365}) \\times (1 - \\dfrac{2}{365}) \\times ... \\times (1 - \\dfrac{n+1}{365}) \\\\\n      &=& \\dfrac{365 \\times 364 \\times ... \\times (365 - n + 1)}{365^{n}} \\\\\n      &=& \\dfrac{365!}{365^{n} . (365 - n)!}\\\\\n\\end{eqnarray}\n\n\\begin{equation}\nP(n) = 1 - P(n') = 1 - \\dfrac{365!}{365^{n} . (365 - n)!}\n             \\end{equation}\n\n\n```\nfrom __future__ import division\n\nimport math\n\ndef pn_dash(n):\n    \"\"\"Returns probability that no birthday occur the same day in a group of n people.\"\"\"\n    return math.factorial(365) / (365**n * math.factorial(365 - n)) \n\ndef pn(n):\n    \"\"\"Returns probability that birthday of at least 2 people occur same day in group of n people.\"\"\"\n    return 1 - pn_dash(n)\n```\n\n\n```\n# Let's calculate it for 20 people\nprint '{:0.2f}%' . format(pn(20) * 100)\n```\n\n    41.14%\n\n\n\n```\nnb_people = range(0, 85, 5)\np_birthday = [pn(n) for n in nb_people]\n\nfor n, p in zip(nb_people, p_birthday):\n    print 'n = {:2} -> p = {:.2f}%'.format(n, p * 100)\n```\n\n    n =  0 -> p = 0.00%\n    n =  5 -> p = 2.71%\n    n = 10 -> p = 11.69%\n    n = 15 -> p = 25.29%\n    n = 20 -> p = 41.14%\n    n = 25 -> p = 56.87%\n    n = 30 -> p = 70.63%\n    n = 35 -> p = 81.44%\n    n = 40 -> p = 89.12%\n    n = 45 -> p = 94.10%\n    n = 50 -> p = 97.04%\n    n = 55 -> p = 98.63%\n    n = 60 -> p = 99.41%\n    n = 65 -> p = 99.77%\n    n = 70 -> p = 99.92%\n    n = 75 -> p = 99.97%\n    n = 80 -> p = 99.99%\n\n\n\n```\n%pylab inline\n```\n\n    Populating the interactive namespace from numpy and matplotlib\n\n\n\n```\n# Main plot layout\nf, ax = plt.subplots()\nax.set_yticks(np.arange(0, 1.1, 0.1))\nplt.ylabel('probability')\nf.text(x=0.5, y=0.975, s='Probability distribution of birthday collision for a sample of n people', horizontalalignment='center', verticalalignment='top')\n\nplt.plot(nb_people, p_birthday, label='$p(n)$', color='r')\nplt.plot(nb_people, [pn_dash(n) for n in nb_people],label='$p(\\overline{n})$',color='b')\n\nn_p50, p50 = [(n, pn(n)) for n in xrange(0, 100) if round(pn(n), 2) in [0.5, 0.51]][0]\nplt.axhline(y=p50, xmax=n_p50/80., linestyle='--', color='grey')\nplt.axvline(x=n_p50, ymax=p50, linestyle='--', color=\"grey\")\n\nplt.legend(loc='center right')\nplt.text(n_p50 - 1, -0.055, '23')\n```\n\n## Conclusion\n\nIn a group of 23 people, there is a probability of approximately 50% of finding at least two people with the same birthday, contrary to what your intuition could tell you! \n\nA. What is Data Science?\n====\n(And what does the birthday paradox have to do with it?)\n\nList examples:  \n\n- Recommendation Engines\n    - Collaborative Filtering (Amazon, Netflix)\n    - PYMK (LinkedIn, etc.)\n    - Other (Pandora, etc.)\n- Data Viz (NYT, etc.)\n- Fraud detection\n- Business Intelligence (Obama 2012, etc.)\n\n## Data Science = Data + Science\n\n## Data can be:\n\n1. Most data does not conform to any predetermined schema. Must ETL it first. Will cover next class.\n2. Machine-readable but unpredictable. Good for communication. Bad for analysis. Mongo, XML, JSON, etc. Will cover Monday.\n3. Must be structured prior to analysis. Fields always there, always same type. SQL, R, Pandas. Next week and beyond.\n    - Excel is semi-structured but has some structured capabilities. Special case.\n\n### Unstructured (e.g. Email, Photos, Books, etc.)\n\n### Semi-Structured (e.g. XML, JSON, NoSQL, APIs, etc.)\n\n### Structured (e.g. SQL, Data Frames, etc.)\n\n1. Most data in the world is unstructured. That is, it does not conform to any predetermined computer-readable form. Before we can work with this sort of data, we need to extract it, transform it into something usable, and load it into our system, whatever that system may be. Extract, transform, load is ETL and its one of the less glamorous and more time consuming parts of the job, so it is important to know how to do it efficiently. We will cover this in the next class.\n2. Semi-structured data is a relatively new thing and has a lot to do with the web. Semi-structured data is machine readable but does not conform to a rigid structure. This is both a blessing and a curse. The flexibility it provides makes it a lot easier for different systems to talk to one another. But that same flexibility makes working with the data in aggregate more difficult. Many \"NoSQL\" databases use a semi-structured schema. Those of you who are over 30 probably remember XML which was a popular standard for semi-structured in the late 90's and early 2000's. Fortunately, XML has largely been replaced by JSON which is easier to read by both humans (because it doesn't have so many angle brackets) and computers (because it is less flexible and therefore less ambiguous). We will be covering how to work with this sort of data next Monday. \n3. Ultimately, Data Scientists need our data to be structured before we can do anything with it. Relational databases are structured. And once we get into Pandas and R, we will learn about data frames which are also structured. Structured data are consistent throughout. For example, a given field will have the same data type no matter what. This is extremely important because it makes it possible to work across all of the data in aggregate. This opens up the possibility to do everything from calculate sums so measuring relationships and predicting outcomes. We will cover the basics of how to work with this kind of data next week and for the most part, the rest of this course will deal with data in this form. \n    1. As an aside, you might be wondering where Excel spreadsheets would fit in this list. I would place it somewhere between Structured and Semi-structured. We might call it \"mostly structured\". Unlike fully structured data, an Excel spreadsheet can accept different datatypes in a column. But unlike semi-structured data, it will complain when you do this (at least, as soon as you try to do an operation on that column). It probably belongs in the semi-structured category but because of the ability to do structured operations in a spreadsheet, I'm reluctant to put it there.\n\n## Science can be:\n\n1. Once we've got data in a form we can use, first we look at it. Sometimes that is enough to derive valuable insights. Time permitting, we will begin this week 3.\n2. Then we might try to model the data which can be useful for making inferences and predictions\n\n### Explorations / Explanations\n- Data Visualization (e.g. ggplot2, Tableau, d3.js, etc.)\n- Unsupervised Machine Learning (e.g. clustering, etc.)\n- etc....\n<br />\n\n### Inferences / Predictions\n- Regression Models (e.g. Linear Models, Logistic Regression)\n- Supervised Machine Learning (e.g. Neural Nets, Genetic Algorithms)\n- etc....  \n<br />\n\nData Science Workflow\n=====================\nFrom [a Taxonomy of Data Science](http://www.dataists.com/2010/09/a-taxonomy-of-data-science/) (by Dataists)\n\nA. Obtain\n\nB. Scrub\n\nC. Explore\n\nD. Model\n\nE. Interpret\n\n## Workflow Example:\n### Problem: what are the leading indicators that a user will make a new purchase?\n\nA. Collect data around user retention, user actions within the product, potentially find data outside of company\n\nB. Extract aggregated values from raw data  \n\n1. How many times did a user share through Facebook within a week? A month?\n2. How often did they open up our emails?\n\nC. Examine data to find common distributions and correlations\n\nD. Extract new meaning to predict if user would purchase again\n\nE. Share results (and probably also go back to the drawing board)\n\n# B. Goals of the Course\n\nAt the completion of this course, you will be able to:\n\n- Employ the Map/Reduce paradigm to transform big unstructured data\n- Access data from web-based application programming interfaces (APIs)\n- Use Structured Query Language (SQL) functions like JOIN and GROUP\n- Explore and present data through visualizations\n- Apply generalized linear models (GLMs)\n- Detect clusters in multivariate data\n- Predict categories using supervised machine learning techniques\n\n### At the completion of this course, you will be able to:\n\n- Employ the Map/Reduce paradigm to transform big unstructured data\n\n- Access data from web-based application programming interfaces (APIs)\n\n- Use Structured Query Language (SQL) functions like JOIN and GROUP\n\n- Explore and present data through visualizations\n\n- Apply generalized linear models (GLMs)\n\n- Detect clusters in multivariate data\n\n- Predict categories using supervised machine learning techniques\n\n### Tentative Course outline:\n\n1. Intro and Overview\n2. Big Data I: Hadoop\n3. Big Data II: IPython.parallel\n4. APIs and semi-structured data - First Project Proposals Due 1/27\n5. SQL and Data Frames\n6. Data Exploration & Visualization (feedback on proposals returned)\n7. Linear Regression\n8. Logistic Regression - Formal Project Proposals Due 2/3 (including data and methods chosen) \n9. Dimensionality Reduction\n10. Unsupervised Machine Learning: K-Means Clustering (feedback on proposals returned)\n11. Network Analysis\n12. Supervised Machine Learning: K-Nearest Neighbors - Project live on Github 2/19 (no class 2/17)\n13. Supervised Machine Learning: Naive Bayes\n14. Machine Learning in Python: Scikit-Learn \n15. Supervised Machine Learning: Decision Trees & Random Forests - Peer Feedback Due 3/3\n16. Ensemble Techniques\n17. Recommendation Systems\n18. Final Project Working Session\n19. Final Project Working Session\n20. Where to Go Next\n21. Final Project Presentations (10 min. each)\n22. Final Project Presentations (10 min. each)\n\n# C. Lab\n\n### Checklist\n\n- Install Anaconda\n- Setup Git\n\n\n<small><i>The following was put together by [Jake Vanderplas](http://www.vanderplas.com)</i></small>\n\n# Getting Started: Four Ways to Use Python\n\n### 1. The Python command-line interpreter\n\n### 2. Editing Python (.py) files\n\n### 3. The IPython command-line interpreter\n\n### 4. The IPython notebook\n\n## 1. The Python command-line Interpreter\n\nIf you have never used the command-line, you're in for a treat\n\n- Mac OSX: in Finder/Applications, search for \"Terminal\"\n\n- Linux/Unix: ``Ctrl-Alt-t``\n\n- Windows: run \"cmd\"\n\n\n\n## 1. The Python command-line Interpreter\n\nType ``python`` at the command-line to start the interpreter\n\n\n\n## 1. The Python Command-line Interpreter\n\nExecute a command: Type ``print \"hello world\"``\n\n\n\n## 1. The Python Command-line Interpreter\n\nClosing the terminal:\n\n- Either type ``exit()`` or type ``Ctrl-d``\n\n\n\n## 2. Editing Python (.py) files\n\n### This requires a text editor.\n\nThe best option is one which includes code highlighting\n\n- Linux: gedit, emacs, nano, vim...\n-  Mac OSX: textmate, emacs, nano, vim...\n-  Windows: NotePad...\n\n### GUI-based editors with bells & whistles\n\n-  Linux: KWrite, Scribes, eggy\n-  Mac OSX: TextWrangler, SublimeText\n-  Windows: NotePad++, SublimeText\n\n## 2. Editing Python (.py) files\n\nUse your editor to open ``hello_world.py`` (here we use OSX's ``mate`` though any text editor will do)\n\n\n\nEdit the file to say ``print \"hello world\"``\n\n\n\nIn the terminal, run ``python hello_world.py``\n\n\n\n## 3. The IPython command-line Interpreter\n\nIPython provides an enhanced command-line interface\n\nIt can be started by typing ``ipython``:\n\n\n\nUseful features include tab completion, help (``?``), etc.\n\n## 3. The IPython command-line Interpreter\n\nBasic use is just like the standard interpreter:\n\n\n\n## 4. The IPython Notebook\n\nThe IPython notebook can be started by typing ``ipython notebook``:\n\n\n\n\n## 4. The IPython Notebook\n\n\nYour web browser should open to an interactive notebook page\n\n\n\nNotice that this slideshow is written as an IPython notebook!\n\n\nThe most basic data structure is the `None` type. This is the equivalent of `NULL` in other languages.  \nThere are four numeric types: **`int, float, bool, complex`**.\n\n\n```\ntype(1)\n```\n\n\n\n\n    int\n\n\n\n\n```\ntype(2.5)\n```\n\n\n\n\n    float\n\n\n\n\n```\ntype(True)\n```\n\n\n\n\n    bool\n\n\n\n\n```\ntype(2+3j)\n```\n\n\n\n\n    complex\n\n\n\nThe next basic data type is the Python list.  \n**A list is an ordered collection of elements, and these elements can be of arbitrary type. Lists are mutable, meaning they can be changed in-place.**\n\n\n```\nk = [1, 'b', True]\n```\n\n\n```\nk[2]\n```\n\n\n\n\n    True\n\n\n\n\n```\nk[1] = 'a'\n```\n\n\n```\nk\n```\n\n\n\n\n    [1, 'a', True]\n\n\n\nLikewise, **tuples are immutable arrays of arbitrary elements.**\n\n\n```\nx = (1, 'a', 2.5)\n```\n\n\n```\nx\n```\n\n\n\n\n    (1, 'a', 2.5)\n\n\n\n\n```\nx[0]\n```\n\n\n\n\n    1\n\n\n\n\n```\nx[0] = 'b'\n```\n\nThe string type in Python represents an immutable ordered array of characters (note there is no char type).\n\n**Strings support slicing and indexing operations like arrays, and have many other string-specific functions as well.**\n\nString processing is one area where Python excels.\n\nAssociative arrays (or hash tables) are implemented in Python as the dictionary type.\n\n\n```\nthis_class = {'subject': 'Data Science', 'instructor': 'Alessandro', 'time': 1800, 'is_cool': True}\n```\n\n\n```\nthis_class['subject']\n```\n\n\n\n\n    'Data Science'\n\n\n\n\n```\nthis_class['is_cool']\n```\n\n\n\n\n    True\n\n\n\n**Dictionaries are unordered collections of key-value pairs, and dictionary keys must be immutable.**\n\nAnother basic Python data type is the set. Sets are unordered mutable collections of distinct elements.\n\n\n```\ny = set([1, 1, 2, 3, 5, 8])\n```\n\n\n```\ny\n```\n\n\n\n\n    {1, 2, 3, 5, 8}\n\n\n\nThese are particularly useful for checking membership of an element and for ensuring element uniqueness.\n\n### More:\n\n- [Basic Training](http://nbviewer.ipython.org/url/www.astro.washington.edu/users/vanderplas/Astr599/notebooks/01_basic_training.ipynb)\n- [Advanced Data Structures](http://nbviewer.ipython.org/url/www.astro.washington.edu/users/vanderplas/Astr599/notebooks/02_advanced_data_structures.ipynb)\n\n# Discussion\n", "meta": {"hexsha": "aa69fe5756b5766b6a00abcd66d56d9e730d6bbd", "size": 64390, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "DS_Lec01-Intro.ipynb", "max_stars_repo_name": "eklypse/DAT4", "max_stars_repo_head_hexsha": "09edc48357fecf3b7aab87947e51d2bd3c147011", "max_stars_repo_licenses": ["Artistic-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-01-23T15:26:26.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-23T15:26:26.000Z", "max_issues_repo_path": "DS_Lec01-Intro.ipynb", "max_issues_repo_name": "eklypse/DAT4", "max_issues_repo_head_hexsha": "09edc48357fecf3b7aab87947e51d2bd3c147011", "max_issues_repo_licenses": ["Artistic-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DS_Lec01-Intro.ipynb", "max_forks_repo_name": "eklypse/DAT4", "max_forks_repo_head_hexsha": "09edc48357fecf3b7aab87947e51d2bd3c147011", "max_forks_repo_licenses": ["Artistic-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0479078229, "max_line_length": 21303, "alphanum_fraction": 0.6514054977, "converted": true, "num_tokens": 4862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22541660542786957, "lm_q2_score": 0.10669059252545564, "lm_q1q2_score": 0.024049831198176243}}
{"text": "<a href=\"https://colab.research.google.com/github/ChrizZhuang/marginalized_graph_kernel_protein/blob/main/Docking_0614.ipynb\" target=\"_parent\"></a>\n\n## Set up the environment\n\n\n```\n!nvidia-smi\n```\n\n    Mon Jun 14 13:19:59 2021       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 465.27       Driver Version: 460.32.03    CUDA Version: 11.2     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   52C    P8    10W /  70W |      0MiB / 15109MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    |  No running processes found                                                 |\n    +-----------------------------------------------------------------------------+\n\n\n\n```\n#!pip install pymatgen==2020.12.31\n!pip install pymatgen==2019.11.11\n!pip install --pre graphdot\n!pip install gdown\n```\n\n    Requirement already satisfied: pymatgen==2019.11.11 in /usr/local/lib/python3.7/dist-packages (2019.11.11)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2021.6.10)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (0.17.9)\n    Requirement already satisfied: pydispatcher>=2.0.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.0.5)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.16.1)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.5.1)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.23.0)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (3.3.0)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.1.5)\n    Requirement already satisfied: scipy>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.4.1)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (0.8.9)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.7.1)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (3.2.2)\n    Requirement already satisfied: numpy>=1.14.3 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.19.5)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen==2019.11.11) (0.2.2)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.2->pymatgen==2019.11.11) (4.4.2)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (2020.12.5)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (2.10)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (3.0.4)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen==2019.11.11) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen==2019.11.11) (2018.9)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->pymatgen==2019.11.11) (1.2.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (2.4.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (1.3.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (0.10.0)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas->pymatgen==2019.11.11) (1.15.0)\n    Requirement already satisfied: graphdot in /usr/local/lib/python3.7/dist-packages (0.8a17)\n    Requirement already satisfied: pandas>=0.24 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.1.5)\n    Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.19.5)\n    Requirement already satisfied: ase>=3.17 in /usr/local/lib/python3.7/dist-packages (from graphdot) (3.21.1)\n    Requirement already satisfied: networkx>=2.4 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2.5.1)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.7.1)\n    Requirement already satisfied: treelib>=1.6.1 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.6.1)\n    Requirement already satisfied: kahypar>=1.1.4 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.1.6)\n    Requirement already satisfied: pymatgen==2019.11.11 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2019.11.11)\n    Requirement already satisfied: pycuda>=2019 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2021.1)\n    Requirement already satisfied: mendeleev>=0.7 in /usr/local/lib/python3.7/dist-packages (from graphdot) (0.7.0)\n    Requirement already satisfied: numba>=0.51.0 in /usr/local/lib/python3.7/dist-packages (from graphdot) (0.51.2)\n    Requirement already satisfied: tqdm>=4.55 in /usr/local/lib/python3.7/dist-packages (from graphdot) (4.61.1)\n    Requirement already satisfied: scipy>=1.3.0 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.4.1)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->graphdot) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->graphdot) (2018.9)\n    Requirement already satisfied: matplotlib>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from ase>=3.17->graphdot) (3.2.2)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.4->graphdot) (4.4.2)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->graphdot) (1.2.1)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from treelib>=1.6.1->graphdot) (0.16.0)\n    Requirement already satisfied: pydispatcher>=2.0.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2.0.5)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (0.8.9)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2021.6.10)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2.23.0)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (0.17.9)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (1.16.1)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (3.3.0)\n    Requirement already satisfied: pytools>=2011.2 in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (2021.2.7)\n    Requirement already satisfied: appdirs>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (1.4.4)\n    Requirement already satisfied: mako in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (1.1.4)\n    Requirement already satisfied: Pygments<3.0.0,>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (2.9.0)\n    Requirement already satisfied: six<2.0.0,>=1.15.0 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (1.15.0)\n    Requirement already satisfied: pyfiglet<0.9,>=0.8.post1 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (0.8.post1)\n    Requirement already satisfied: SQLAlchemy<2.0.0,>=1.3.23 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (1.4.15)\n    Requirement already satisfied: colorama<0.5.0,>=0.4.4 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (0.4.4)\n    Requirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba>=0.51.0->graphdot) (0.34.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from numba>=0.51.0->graphdot) (57.0.0)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.0.0->ase>=3.17->graphdot) (0.10.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.0.0->ase>=3.17->graphdot) (2.4.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.0.0->ase>=3.17->graphdot) (1.3.1)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (2020.12.5)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (2.10)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen==2019.11.11->graphdot) (0.2.2)\n    Requirement already satisfied: MarkupSafe>=0.9.2 in /usr/local/lib/python3.7/dist-packages (from mako->pycuda>=2019->graphdot) (2.0.1)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (4.0.1)\n    Requirement already satisfied: greenlet!=0.4.17; python_version >= \"3\" in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (1.1.0)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (3.4.1)\n    Requirement already satisfied: typing-extensions>=3.6.4; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (3.7.4.3)\n    Requirement already satisfied: gdown in /usr/local/lib/python3.7/dist-packages (3.6.4)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from gdown) (2.23.0)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from gdown) (4.61.1)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from gdown) (1.15.0)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (2020.12.5)\n\n\n\n```\n%matplotlib inline\nimport io\nimport sys\nsys.path.append('/usr/local/lib/python3.6/site-packages/')\nimport os\nimport urllib\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport graphdot\nfrom graphdot import Graph\nfrom graphdot.graph.adjacency import AtomicAdjacency\nfrom graphdot.graph.reorder import rcm\nfrom graphdot.kernel.marginalized import MarginalizedGraphKernel # https://graphdot.readthedocs.io/en/latest/apidoc/graphdot.kernel.marginalized.html\nfrom graphdot.kernel.marginalized.starting_probability import Uniform\nfrom graphdot.model.gaussian_process import (\n    GaussianProcessRegressor,\n    LowRankApproximateGPR\n)\nfrom graphdot.kernel.fix import Normalization\nimport graphdot.microkernel as uX\nimport ase.io\n\n# for getting all file names into a list under a directory \nfrom os import listdir\n# for getting file names that match certain pattern\nimport glob\nimport time\n```\n\n    /usr/local/lib/python3.7/dist-packages/graphdot/graph/__init__.py:24: UserWarning: Cannot import RDKit, `graph.from_rdkit()` will be unavailable.\n    \n      'Cannot import RDKit, `graph.from_rdkit()` will be unavailable.\\n'\n\n\n\n```\nfrom google.colab import drive\ndrive.mount('/content/gdrive', force_remount=True)\n```\n\n    Mounted at /content/gdrive\n\n\n\n```\n#cd gdrive/MyDrive/Google\\ Colab/Covid-Data\n%cd gdrive/MyDrive/Covid-Data/\n```\n\n    /content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data\n\n\n\n```\n!pwd\n```\n\n    /content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data\n\n\n\n```\n#!mkdir /content/pkls\n```\n\n## load the data\n\n\n```\nfiles  = ['uncharged_NSP15_6W01_A_3_H.Orderable_zinc_db_enaHLL.2col.csv.1.xz']\ndataset = pd.read_pickle(files[0]) # length of each csv file is 100000\n```\n\n\n```\ntarget = 'energy'\nN_train = 1000\nN_test = 2000\n\nnp.random.seed(0) # with the same seed, multiple runs can have the same selected index\ntrain_sel = np.random.choice(len(dataset), N_train, replace=False)\ntest_sel = np.random.choice(np.setxor1d(np.arange(len(dataset)), train_sel), N_test, replace=False)\ntrain = dataset.iloc[train_sel]\ntest = dataset.iloc[test_sel]\n```\n\n\n```\ntrain.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>energy</th>\n      <th>smiles</th>\n      <th>graphs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>3582</th>\n      <td>-2.874773</td>\n      <td>CN(Cc1nc(no1)c2cccc(c2)Br)C(=O)Nc3cccc(c3)OC</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>60498</th>\n      <td>-3.469760</td>\n      <td>CCOC(=O)c1ccc(c(c1)C)NC(=S)NCCOc2ccc(cc2)C</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>53227</th>\n      <td>-0.487984</td>\n      <td>Cc1ccc(cc1S(=O)(=O)Nc2ccccc2OC)NC(=O)c3nc4nc(c...</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>21333</th>\n      <td>-1.808283</td>\n      <td>COc1ccc(cc1OC)CCNC(=O)COc2ccc(cc2)[N@@](Cc3ccc...</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>3885</th>\n      <td>-2.457642</td>\n      <td>Cc1cc(ccc1NCc2ccc(c(c2OC)C)OC)Br</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### Baseline mode\n\n\n```\ngpr_base = GaussianProcessRegressor(\n    # kernel is the covariance function of the gaussian process (GP)\n    kernel=Normalization( # kernel equals to normalization -> normalizes a kernel using the cosine of angle formula, k_normalized(x,y) = k(x,y)/sqrt(k(x,x)*k(y,y))\n        # graphdot.kernel.fix.Normalization(kernel), set kernel as marginalized graph kernel, which is used to calculate the similarity between 2 graphs\n        # implement the random walk-based graph similarity kernel as Kashima, H., Tsuda, K., & Inokuchi, A. (2003). Marginalized kernels between labeled graphs. ICML\n        MarginalizedGraphKernel( \n            # node_kernel - A kernelet that computes the similarity between individual nodes\n            # uX - graphdot.microkernel - microkernels are positive-semidefinite functions between individual nodes and edges of graphs\n            node_kernel=uX.Additive( # addition of kernal matrices: sum of k_a(X_a, Y_a) cross for a in features\n                # uX.Constant - a kernel that returns a constant value, always mutlipled with other microkernels as an adjustable weight\n                #   c, the first input arg. as 0.5, (0.01, 10) the lower and upper bounds of c that is allowed to vary during hyperpara. optimizartion\n                # uX.KroneckerDelta - a kronecker delta returns 1 when two features are equal and return h (the first input arg here, which is 0.5 in this case) otherwise\n                #   (0.1, 0.9) the lower and upper bounds that h is allowed to vary during hyperpara. optimization\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 2nd element of graphdot.graph.Graph.nodes\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 3rd element of graphdot.graph.Graph.nodes\n                # uX.SquareExponential - Equ. 26 in the paper\n                # input arg. length_sacle is a float32, set as 1 in this case, which correspond to approx. 1 of the kernal value. \n                # This is used to determins how quicklys should the kernel decay to zero.\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0), # the 4th element of graphdot.graph.Graph.nodes\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 5th element of graphdot.graph.Graph.nodes\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0), # the 6th element of graphdot.graph.Graph.nodes\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 7th element of graphdot.graph.Graph.nodes\n                # uX.Convolution - a convolutional microkernel which averages evaluations of a base microkernel between pairs pf elememts of two variable-length feature sequences\n                # uX.KroneckerDelta as the base kernel\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9))) # the 8th element of graphdot.graph.Graph.nodes\n            ).normalized,\n            # edge_kernel - A kernelet that computes the similarity between individual edge\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 3rd element of graphdot.graph.Graph.nodes\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 4th element of graphdot.graph.Graph.nodes\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 5th element of graphdot.graph.Graph.nodes\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 6th element of graphdot.graph.Graph.nodes\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)) # the 7th element of graphdot.graph.Graph.nodes\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'), # the strating probability of the random walk on each node\n            q=0.05 # the probability for the random walk to stop during each step\n        )\n    ),\n    alpha=1e-4, # value added to the diagonal of the kernel matrix during fitting\n    optimizer=True, # default optimizer of L-BFGS-B based on scipy.optimize.minimize\n    normalize_y=True, # normalize the y values so taht the means and variance is 0 and 1, repsectively. Will be reversed when predicions are returned\n    regularization='+', # alpha (1e-4 in this case) is added to the diagonals of the kernal matrix\n)\n```\n\n\n```\ngpr_base.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  2.8725e+06|  2.4458e+07|  2.8798e+06|     -7290.9|  8.7024e+06|        22|      0.25|\n    |  1.9315e+06|  2.0707e+07|  1.9382e+06|     -6742.8|  8.0237e+06|        20|      0.24|\n    |  1.2905e+06|  1.5706e+07|  1.2968e+06|     -6252.2|  7.0835e+06|        19|      0.25|\n    |  1.0061e+06|  1.2309e+07|  1.0121e+06|     -5971.8|  6.4171e+06|        18|      0.24|\n    |  8.2557e+05|  9.7267e+06|  8.3132e+05|     -5755.4|  5.8209e+06|        17|      0.23|\n    |  7.1178e+05|  8.0789e+06|  7.1737e+05|     -5588.8|  5.3655e+06|        17|      0.25|\n    |  6.4897e+05|  7.1031e+06|  6.5446e+05|     -5488.6|  5.0424e+06|        17|      0.24|\n    |  6.2995e+05|   7.043e+06|  6.3539e+05|     -5435.7|  4.9627e+06|        17|      0.24|\n    |  6.1001e+05|  6.6424e+06|  6.1542e+05|     -5413.2|  4.8439e+06|        17|      0.24|\n    |   6.055e+05|  6.5416e+06|  6.1091e+05|     -5407.7|  4.7988e+06|        16|      0.24|\n    |  6.0285e+05|  6.4988e+06|  6.0825e+05|     -5402.9|  4.7885e+06|        16|      0.24|\n    |  6.0601e+05|  6.6651e+06|   6.114e+05|     -5395.9|  4.8317e+06|        17|      0.25|\n    |  6.0087e+05|  6.5216e+06|  6.0626e+05|     -5395.1|  4.7916e+06|        17|      0.24|\n    |  5.9979e+05|  6.4968e+06|  6.0518e+05|     -5393.3|  4.7859e+06|        17|      0.24|\n    |  5.9795e+05|  6.4537e+06|  6.0334e+05|     -5390.4|  4.7776e+06|        17|      0.26|\n    |  5.9632e+05|   6.417e+06|  6.0171e+05|     -5388.7|  4.7579e+06|        16|      0.23|\n    |  5.9535e+05|  6.4032e+06|  6.0074e+05|     -5387.3|  4.7491e+06|        16|      0.25|\n    |  5.9515e+05|  6.4246e+06|  6.0054e+05|     -5386.3|  4.7503e+06|        17|      0.24|\n    |  5.9519e+05|  6.4222e+06|  6.0058e+05|     -5386.6|  4.7481e+06|        17|      0.25|\n    |  5.9528e+05|  6.4269e+06|  6.0067e+05|     -5386.3|  4.7487e+06|        17|      0.25|\n    |  5.9518e+05|  6.4251e+06|  6.0056e+05|     -5386.3|   4.747e+06|        17|      0.24|\n    |  5.9522e+05|  6.4263e+06|  6.0061e+05|     -5386.3|   4.748e+06|        17|      0.24|\n    |  5.9521e+05|  6.4261e+06|   6.006e+05|     -5386.3|  4.7459e+06|        17|      0.24|\n    |  5.9521e+05|  6.4263e+06|   6.006e+05|     -5386.3|  4.7474e+06|        17|      0.25|\n    |  5.9516e+05|  6.4253e+06|  6.0055e+05|     -5386.2|  4.7489e+06|        17|      0.25|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  1.7413e+06|  2.1782e+07|   1.748e+06|       -6644|  7.5158e+06|        20|      0.24|\n    |  1.3451e+06|  1.6773e+07|  1.3514e+06|     -6332.3|  6.9251e+06|        19|      0.25|\n    |   1.033e+06|  1.3306e+07|  1.0391e+06|     -6026.9|  6.3155e+06|        19|      0.24|\n    |  7.9866e+05|  1.0452e+07|  8.0437e+05|     -5717.2|  5.7392e+06|        19|      0.26|\n    |  6.9752e+05|  8.1836e+06|  7.0309e+05|     -5576.4|   5.318e+06|        17|      0.26|\n    |  6.4289e+05|   7.195e+06|  6.4837e+05|     -5481.7|  5.0649e+06|        17|      0.23|\n    |   6.153e+05|  6.7608e+06|  6.2073e+05|     -5430.1|  4.8862e+06|        17|      0.24|\n    |  6.1229e+05|  6.6746e+06|  6.1772e+05|     -5421.4|  4.8115e+06|        16|      0.24|\n    |  5.9982e+05|  6.4991e+06|  6.0522e+05|     -5399.3|  4.7705e+06|        16|      0.23|\n    |  5.9655e+05|  6.4385e+06|  6.0194e+05|     -5390.8|  4.7638e+06|        17|      0.23|\n    |  5.9622e+05|  6.4295e+06|  6.0161e+05|       -5390|  4.7603e+06|        16|      0.25|\n    |  5.9531e+05|  6.4019e+06|   6.007e+05|     -5388.4|  4.7574e+06|        16|      0.26|\n    |  5.9498e+05|  6.3961e+06|  6.0037e+05|     -5387.3|  4.7535e+06|        16|      0.25|\n    |  5.9726e+05|  6.5117e+06|  6.0264e+05|     -5385.9|  4.7837e+06|        17|      0.24|\n    |  5.9475e+05|  6.4136e+06|  6.0013e+05|     -5385.8|  4.7581e+06|        17|      0.24|\n    |  5.9453e+05|   6.402e+06|  5.9992e+05|       -5386|  4.7582e+06|        16|      0.24|\n    |  5.9439e+05|   6.409e+06|  5.9978e+05|     -5385.3|  4.7563e+06|        17|      0.24|\n    |  5.9419e+05|  6.4005e+06|  5.9957e+05|     -5385.6|  4.7549e+06|        17|      0.25|\n    |  5.9386e+05|  6.3824e+06|  5.9925e+05|     -5386.6|  4.7468e+06|        16|      0.25|\n    |  5.9362e+05|  6.3753e+06|  5.9901e+05|     -5386.7|  4.7493e+06|        16|      0.24|\n    |  5.9322e+05|  6.3676e+06|  5.9861e+05|     -5387.2|  4.7601e+06|        16|      0.25|\n    |  5.9311e+05|   6.373e+06|  5.9849e+05|     -5386.5|  4.7591e+06|        16|      0.26|\n    |  5.9318e+05|  6.3877e+06|  5.9857e+05|     -5385.4|  4.7644e+06|        17|      0.25|\n    |  5.9334e+05|  6.3815e+06|  5.9873e+05|     -5386.2|  4.7579e+06|        16|      0.23|\n    |  5.9312e+05|  6.3728e+06|  5.9851e+05|     -5386.5|  4.7571e+06|        16|      0.25|\n    |  5.9326e+05|  6.3759e+06|  5.9864e+05|     -5386.5|  4.7563e+06|        16|      0.25|\n    |  5.9319e+05|  6.3747e+06|  5.9858e+05|     -5386.5|  4.7585e+06|        16|      0.24|\n    |  5.9323e+05|  6.3755e+06|  5.9862e+05|     -5386.5|  4.7595e+06|        16|      0.25|\n    |  5.9327e+05|  6.3764e+06|  5.9866e+05|     -5386.5|  4.7575e+06|        16|      0.24|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  3.4092e+06|  2.5343e+07|  3.4168e+06|     -7528.5|  8.7203e+06|        20|      0.24|\n    |  2.2467e+06|  2.1995e+07|  2.2536e+06|     -6926.8|  8.0939e+06|        19|      0.25|\n    |  1.4704e+06|  1.6957e+07|  1.4768e+06|     -6399.5|  7.2075e+06|        19|      0.24|\n    |  1.1068e+06|  1.3411e+07|  1.1129e+06|     -6074.4|  6.5417e+06|        18|      0.23|\n    |  8.6387e+05|  1.0661e+07|  8.6966e+05|     -5795.5|   5.954e+06|        18|      0.25|\n    |  7.4225e+05|  8.8175e+06|  7.4788e+05|     -5630.3|  5.5341e+06|        18|      0.24|\n    |  6.7235e+05|  7.6658e+06|  6.7787e+05|     -5526.8|  5.2141e+06|        17|      0.25|\n    |  6.3387e+05|  7.1558e+06|  6.3932e+05|     -5448.8|  4.9899e+06|        17|      0.24|\n    |  6.1335e+05|  6.7496e+06|  6.1877e+05|     -5423.9|  4.8814e+06|        17|      0.24|\n    |  6.1076e+05|  6.7056e+06|  6.1618e+05|     -5418.4|   4.863e+06|        17|      0.25|\n    |  6.0468e+05|  6.6012e+06|  6.1008e+05|     -5406.1|  4.8233e+06|        17|      0.23|\n    |  5.9819e+05|  6.4569e+06|  6.0358e+05|     -5396.3|   4.775e+06|        17|      0.23|\n    |   5.968e+05|  6.4322e+06|  6.0219e+05|     -5392.3|  4.7729e+06|        17|      0.24|\n    |  5.9554e+05|    6.42e+06|  6.0093e+05|       -5389|  4.7546e+06|        17|      0.23|\n    |  5.9516e+05|  6.4092e+06|  6.0054e+05|     -5386.2|  4.7716e+06|        17|      0.23|\n    |  5.9485e+05|  6.4051e+06|  6.0024e+05|     -5386.6|  4.7631e+06|        17|      0.24|\n    |  5.9451e+05|  6.4007e+06|   5.999e+05|       -5387|  4.7598e+06|        17|      0.25|\n    |  5.9416e+05|  6.3958e+06|  5.9954e+05|       -5387|  4.7533e+06|        17|      0.25|\n    |  5.9357e+05|  6.3871e+06|  5.9896e+05|     -5386.8|   4.753e+06|        17|      0.25|\n    |  5.9331e+05|  6.3992e+06|   5.987e+05|     -5386.3|  4.7538e+06|        17|      0.24|\n    |  5.9325e+05|  6.3912e+06|  5.9863e+05|     -5386.2|  4.7553e+06|        17|      0.26|\n    |   5.931e+05|  6.3778e+06|  5.9848e+05|       -5386|  4.7619e+06|        16|      0.23|\n    |   5.931e+05|  6.3773e+06|  5.9848e+05|     -5385.9|  4.7602e+06|        17|      0.24|\n    |  5.9305e+05|  6.3763e+06|  5.9843e+05|       -5386|  4.7597e+06|        17|      0.24|\n    |  5.9304e+05|  6.3762e+06|  5.9843e+05|       -5386|  4.7621e+06|        17|      0.24|\n    |  5.9307e+05|   6.377e+06|  5.9846e+05|       -5386|  4.7615e+06|        16|      0.23|\n    |  5.9304e+05|  6.3761e+06|  5.9843e+05|     -5385.9|  4.7637e+06|        17|      0.26|\n    |  5.9299e+05|  6.3766e+06|  5.9838e+05|     -5385.9|  4.7612e+06|        17|      0.24|\n    |  5.9306e+05|  6.3801e+06|  5.9844e+05|     -5385.9|  4.7599e+06|        17|      0.24|\n    |  5.9295e+05|  6.3753e+06|  5.9834e+05|     -5385.9|  4.7634e+06|        16|      0.25|\n    |  5.9296e+05|  6.3752e+06|  5.9834e+05|     -5385.9|  4.7608e+06|        17|      0.23|\n    |  5.9309e+05|   6.378e+06|  5.9847e+05|     -5385.9|  4.7631e+06|        16|      0.24|\n    Optimization result:\n          fun: 593087.1156402231\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 6.37396256e+02,  1.29403894e+02,  1.71592132e+01,  7.87202241e+02,\n            1.37346463e+04,  2.83923867e+02,  0.00000000e+00, -9.41929416e+01,\n            8.31120362e+01, -9.89697568e+02,  1.85028746e-02,  1.18859915e+02,\n            5.20268298e+01, -2.37801534e+02,  1.76013556e+04, -5.72112693e+01,\n            1.61763990e+03, -2.77147646e+02,  3.02784539e+03,  2.61391651e+02,\n            2.67337779e+02,  5.39630844e+01,  0.00000000e+00,  1.97901890e+01,\n            2.39186447e+02])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 32\n          nit: 25\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -2.30258509,  1.47773763, -2.30258509,\n           -4.60517019,  1.38836933, -3.83292358, -2.25417628,  2.30258509,\n           -1.84636793, -3.87778892, -2.30258509,  1.7180289 , -2.30258509,\n            1.52931263, -2.30258509,  2.15048481, -2.30258509, -0.16374951,\n           -2.30258509, -4.06382248, -0.19078879, -0.36875751, -2.30258509])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7fa8f0b23690>\n\n\n\n\n```\n#gpr_base.kernel.hyperparameters\n```\n\n\n```\nmu = gpr_base.predict(train.graphs)\n```\n\n\n```\nplt.scatter(train[target], mu)\nplt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\nplt.xlim(-9, 3)\nplt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.1026528897885943\n    RMSE: 0.1559697478035153\n\n\n\n```\nmu_test = gpr_base.predict(test.graphs)\n```\n\n\n```\nplt.scatter(test[target], mu_test)\nplt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\nplt.xlim(-9, 3)\nplt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 1.3984523944497356\n    RMSE: 1.7902476214464011\n\n\n### model2\n\n\n```\ngpr2 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-5, #different from gpr in alpha where gpr's alpha is 1e-4\n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr2.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  3.9342e+06|  7.4014e+07|  3.9413e+06|     -7048.5|  4.2676e+07|        20|      0.25|\n    |  2.5581e+06|  4.8127e+07|  2.5648e+06|     -6637.5|   3.185e+07|        19|      0.26|\n    |  1.9651e+06|  3.6386e+07|  1.9715e+06|     -6391.2|  2.5862e+07|        19|      0.25|\n    |  1.4839e+06|  2.6275e+07|  1.4901e+06|     -6132.7|  2.0389e+07|        19|      0.25|\n    |  1.1925e+06|  1.9644e+07|  1.1985e+06|     -5931.7|  1.6716e+07|        18|      0.25|\n    |  9.9823e+05|  1.5219e+07|   1.004e+06|     -5762.3|  1.4068e+07|        17|      0.25|\n    |   8.735e+05|  1.2618e+07|  8.7912e+05|     -5627.6|  1.2412e+07|        17|      0.25|\n    |   8.215e+05|  1.1223e+07|  8.2708e+05|     -5576.1|  1.1158e+07|        16|      0.25|\n    |  7.7928e+05|  1.0614e+07|  7.8479e+05|     -5517.2|   1.082e+07|        17|      0.25|\n    |  7.6384e+05|  1.0397e+07|  7.6934e+05|     -5493.1|  1.0717e+07|        17|      0.25|\n    |  7.5683e+05|  1.0246e+07|  7.6232e+05|     -5483.1|  1.0625e+07|        17|      0.26|\n    |  7.8307e+05|  1.0957e+07|  7.8857e+05|     -5492.5|  1.1369e+07|        17|      0.25|\n    |  7.5592e+05|  1.0264e+07|   7.614e+05|       -5479|  1.0686e+07|        17|      0.26|\n    |  7.5278e+05|  1.0169e+07|  7.5826e+05|     -5475.4|  1.0618e+07|        17|      0.26|\n    |  7.5039e+05|  1.0088e+07|  7.5587e+05|     -5472.2|  1.0571e+07|        17|      0.25|\n    |  7.4793e+05|  1.0005e+07|   7.534e+05|     -5470.1|  1.0495e+07|        16|      0.27|\n    |  7.4681e+05|  9.9805e+06|  7.5228e+05|     -5468.4|  1.0454e+07|        16|      0.25|\n    |  7.4544e+05|  9.9933e+06|   7.509e+05|     -5465.7|  1.0403e+07|        17|      0.25|\n    |  7.4519e+05|  9.9849e+06|  7.5065e+05|     -5466.5|  1.0374e+07|        16|      0.25|\n    |  7.4522e+05|  9.9838e+06|  7.5069e+05|     -5466.8|  1.0376e+07|        17|      0.27|\n    |  7.4542e+05|   9.991e+06|  7.5089e+05|     -5466.6|  1.0371e+07|        17|      0.25|\n    |  7.4539e+05|  9.9914e+06|  7.5086e+05|     -5466.5|  1.0373e+07|        17|      0.27|\n    |  7.4543e+05|  9.9918e+06|   7.509e+05|     -5466.5|  1.0368e+07|        16|      0.25|\n    |   7.451e+05|  9.9824e+06|  7.5057e+05|     -5466.5|  1.0392e+07|        16|      0.27|\n    |  7.4524e+05|  9.9871e+06|   7.507e+05|     -5466.5|   1.037e+07|        17|      0.27|\n    |  7.4525e+05|  9.9861e+06|  7.5072e+05|     -5466.5|  1.0386e+07|        17|      0.27|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  2.2754e+06|  4.0939e+07|   2.282e+06|     -6573.6|    2.42e+07|        18|      0.25|\n    |  1.7565e+06|  3.1259e+07|  1.7628e+06|     -6332.7|  2.0381e+07|        18|      0.24|\n    |  1.2573e+06|   2.224e+07|  1.2633e+06|       -6009|  1.6215e+07|        19|      0.25|\n    |    1.05e+06|  1.7608e+07|  1.0558e+06|     -5820.4|  1.4598e+07|        18|      0.25|\n    |  8.9771e+05|  1.3272e+07|  9.0338e+05|     -5669.2|  1.2572e+07|        17|      0.27|\n    |  8.1417e+05|  1.1552e+07|  8.1973e+05|     -5559.9|  1.1683e+07|        17|      0.25|\n    |  7.8461e+05|  1.0854e+07|  7.9014e+05|     -5523.1|  1.1122e+07|        17|      0.26|\n    |  7.6515e+05|  1.0363e+07|  7.7064e+05|     -5496.3|  1.0598e+07|        17|      0.26|\n    |   7.549e+05|  1.0202e+07|  7.6038e+05|     -5480.5|  1.0455e+07|        17|      0.27|\n    |  7.5113e+05|   1.013e+07|   7.566e+05|     -5473.3|  1.0408e+07|        17|      0.25|\n    |  7.4842e+05|   1.001e+07|  7.5389e+05|     -5468.3|  1.0405e+07|        16|      0.25|\n    |  7.4817e+05|  1.0021e+07|  7.5363e+05|     -5467.8|  1.0392e+07|        16|      0.27|\n    |  7.4743e+05|  1.0028e+07|   7.529e+05|     -5467.3|  1.0359e+07|        17|      0.26|\n    |  7.4775e+05|   1.007e+07|  7.5321e+05|     -5465.8|   1.042e+07|        17|      0.26|\n    |  7.4729e+05|  1.0032e+07|  7.5276e+05|     -5466.8|  1.0374e+07|        17|      0.26|\n    |  7.4778e+05|  1.0071e+07|  7.5325e+05|       -5466|  1.0404e+07|        17|      0.26|\n    |  7.4737e+05|  1.0035e+07|  7.5284e+05|     -5466.8|  1.0383e+07|        17|      0.26|\n    |  7.4755e+05|  1.0041e+07|  7.5301e+05|     -5466.8|  1.0372e+07|        17|      0.25|\n    |  7.4755e+05|   1.004e+07|  7.5302e+05|     -5466.8|  1.0377e+07|        17|      0.26|\n    |   7.475e+05|  1.0039e+07|  7.5297e+05|     -5466.8|   1.037e+07|        17|      0.25|\n    |  7.4752e+05|  1.0039e+07|  7.5298e+05|     -5466.8|  1.0365e+07|        16|      0.26|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  5.5724e+06|  1.0057e+08|  5.5798e+06|     -7408.4|  5.0139e+07|        19|      0.24|\n    |  3.3661e+06|  6.0838e+07|   3.373e+06|     -6905.1|  3.6581e+07|        19|      0.24|\n    |  2.6218e+06|  4.7142e+07|  2.6285e+06|     -6665.4|  3.0491e+07|        18|      0.24|\n    |  1.8232e+06|  3.1903e+07|  1.8296e+06|     -6322.8|  2.3196e+07|        18|      0.27|\n    |  1.4038e+06|  2.3742e+07|  1.4099e+06|     -6073.7|  1.9114e+07|        18|      0.25|\n    |   1.145e+06|  1.8596e+07|  1.1509e+06|     -5877.2|  1.6369e+07|        18|      0.24|\n    |   9.735e+05|  1.4838e+07|  9.7923e+05|     -5727.6|  1.4079e+07|        17|      0.24|\n    |  8.7366e+05|  1.2752e+07|  8.7928e+05|     -5625.4|  1.2581e+07|        17|      0.24|\n    |  8.0328e+05|  1.1112e+07|  8.0883e+05|     -5549.3|  1.1228e+07|        17|      0.24|\n    |  7.8049e+05|  1.0893e+07|  7.8599e+05|     -5501.9|  1.1205e+07|        17|      0.26|\n    |  7.7098e+05|  1.0617e+07|  7.7648e+05|     -5498.4|  1.0918e+07|        17|      0.25|\n    |  7.6746e+05|  1.0503e+07|  7.7296e+05|       -5497|  1.0782e+07|        17|      0.28|\n    |  7.6154e+05|  1.0323e+07|  7.6703e+05|       -5492|  1.0603e+07|        17|      0.25|\n    |  7.5364e+05|  1.0183e+07|  7.5912e+05|     -5479.7|  1.0515e+07|        17|      0.25|\n    |  7.4872e+05|  1.0065e+07|  7.5419e+05|     -5471.1|   1.047e+07|        17|      0.24|\n    |  7.4729e+05|  1.0013e+07|  7.5276e+05|     -5469.1|  1.0422e+07|        17|      0.25|\n    |  7.4597e+05|  9.9721e+06|  7.5143e+05|     -5467.8|  1.0406e+07|        16|      0.24|\n    |  7.4535e+05|   9.987e+06|  7.5081e+05|     -5465.9|  1.0431e+07|        16|      0.24|\n    |  7.4442e+05|  9.9833e+06|  7.4989e+05|     -5465.8|  1.0408e+07|        17|      0.25|\n    |  7.4428e+05|  9.9827e+06|  7.4975e+05|     -5466.5|  1.0397e+07|        17|      0.24|\n    |  7.4425e+05|  9.9819e+06|  7.4972e+05|     -5466.9|  1.0382e+07|        16|      0.24|\n    |  7.4408e+05|   9.975e+06|  7.4955e+05|       -5467|  1.0385e+07|        16|      0.24|\n    |  7.4382e+05|  9.9587e+06|  7.4928e+05|       -5467|  1.0402e+07|        17|      0.25|\n    |  7.4399e+05|  9.9658e+06|  7.4946e+05|     -5466.8|   1.041e+07|        16|      0.24|\n    |   7.442e+05|   9.971e+06|  7.4967e+05|       -5467|  1.0428e+07|        17|      0.26|\n    |   7.442e+05|  9.9718e+06|  7.4967e+05|       -5467|  1.0405e+07|        17|      0.26|\n    |   7.438e+05|  9.9587e+06|  7.4927e+05|       -5467|  1.0409e+07|        16|      0.26|\n    |  7.4399e+05|   9.964e+06|  7.4946e+05|       -5467|  1.0401e+07|        17|      0.26|\n    |  7.4412e+05|  9.9681e+06|  7.4959e+05|       -5467|  1.0399e+07|        16|      0.25|\n    Optimization result:\n          fun: 744121.6320021643\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 9.96227102e+02,  2.00432837e+02,  2.60510180e+01, -5.48958596e+02,\n            2.06815585e+04,  4.34825299e+02,  0.00000000e+00, -3.24741237e+02,\n            1.95474293e+02,  1.10656164e+03,  0.00000000e+00,  1.22750805e+02,\n            6.73673262e+01, -1.00813058e+03,  2.60017795e+04, -2.51396161e+01,\n            2.21848468e+03, -5.02235333e+02,  4.39914545e+03,  6.69241667e+01,\n            3.26864116e+02,  7.34901570e+01,  0.00000000e+00,  3.90059610e+02,\n            3.90397116e+02])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 29\n          nit: 23\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -2.30258509,  1.45132733, -2.30258509,\n           -4.60517019,  1.38836933, -3.41134142, -2.30258509,  2.29909486,\n           -6.69419395, -4.08788863, -2.30258509,  1.6789475 , -2.30258509,\n            1.54064497, -2.30258509,  2.21314656, -2.30258509, -0.35101412,\n           -2.30258509, -4.06327129, -0.19078879, -0.09102722, -2.30258509])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7fa8dbae75d0>\n\n\n\n\n```\nmu = gpr2.predict(train.graphs)\nplt.scatter(train[target], mu)\n#plt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\n#plt.xlim(-9, 3)\n#plt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.01420440124959926\n    RMSE: 0.021649804308151027\n\n\n\n```\nmu_test = gpr2.predict(test.graphs)\nplt.scatter(test[target], mu_test)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 1.517212238428167\n    RMSE: 1.943288841802438\n\n\n\n```\n\n```\n", "meta": {"hexsha": "966d6e7a60331a77ee19c9f823f48230b2755f96", "size": 128708, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Docking_0614.ipynb", "max_stars_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_stars_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Docking_0614.ipynb", "max_issues_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_issues_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Docking_0614.ipynb", "max_forks_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_forks_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 113.1001757469, "max_line_length": 24654, "alphanum_fraction": 0.7249199739, "converted": true, "num_tokens": 18946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.04885777827594124, "lm_q1q2_score": 0.024047218805095506}}
{"text": "###  Performance improvement work sharing\n\n- Data\n- Demo\n- API \n- Time series data index\n- Vectorized concept\n- Laws & Disruptive move\n\n\n```python\nimport pandas as pd\n```\n\n\n```python\nall = pd.read_pickle(f\"data/quote_df.pkl\")\nall\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>$close</th>\n      <th>$factor</th>\n      <th>$change</th>\n      <th>$volume</th>\n      <th>limit_buy</th>\n      <th>limit_sell</th>\n    </tr>\n    <tr>\n      <th>instrument</th>\n      <th>datetime</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">SH600000</th>\n      <th>2020-01-02 09:30:00</th>\n      <td>159.046677</td>\n      <td>12.713563</td>\n      <td>NaN</td>\n      <td>177660.500000</td>\n      <td>False</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>2020-01-02 09:31:00</th>\n      <td>158.792404</td>\n      <td>12.713563</td>\n      <td>NaN</td>\n      <td>68880.687500</td>\n      <td>False</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>2020-01-02 09:32:00</th>\n      <td>159.046677</td>\n      <td>12.713563</td>\n      <td>NaN</td>\n      <td>79577.617188</td>\n      <td>False</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>2020-01-02 09:33:00</th>\n      <td>159.809494</td>\n      <td>12.713563</td>\n      <td>NaN</td>\n      <td>165822.281250</td>\n      <td>False</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>2020-01-02 09:34:00</th>\n      <td>159.428085</td>\n      <td>12.713563</td>\n      <td>NaN</td>\n      <td>45314.441406</td>\n      <td>False</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">SH600009</th>\n      <th>2020-06-30 14:55:00</th>\n      <td>219.139130</td>\n      <td>3.040221</td>\n      <td>NaN</td>\n      <td>28780.802734</td>\n      <td>False</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>2020-06-30 14:56:00</th>\n      <td>219.139130</td>\n      <td>3.040221</td>\n      <td>NaN</td>\n      <td>15558.079102</td>\n      <td>False</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>2020-06-30 14:57:00</th>\n      <td>219.139130</td>\n      <td>3.040221</td>\n      <td>NaN</td>\n      <td>230.246414</td>\n      <td>False</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>2020-06-30 14:58:00</th>\n      <td>219.139130</td>\n      <td>3.040221</td>\n      <td>NaN</td>\n      <td>0.000000</td>\n      <td>False</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>2020-06-30 14:59:00</th>\n      <td>219.108734</td>\n      <td>3.040221</td>\n      <td>NaN</td>\n      <td>22465.472656</td>\n      <td>False</td>\n      <td>False</td>\n    </tr>\n  </tbody>\n</table>\n<p>163500 rows \u00d7 6 columns</p>\n</div>\n\n\n\n\n```python\nvolume = pd.read_pickle(f\"data/volume_df.pkl\")\nvolume\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>datetime</th>\n      <th>2020-01-02</th>\n      <th>2020-01-03</th>\n      <th>2020-01-06</th>\n      <th>2020-01-07</th>\n      <th>2020-01-08</th>\n      <th>2020-01-09</th>\n      <th>2020-01-10</th>\n      <th>2020-01-13</th>\n      <th>2020-01-14</th>\n      <th>2020-01-15</th>\n      <th>...</th>\n      <th>2020-06-15</th>\n      <th>2020-06-16</th>\n      <th>2020-06-17</th>\n      <th>2020-06-18</th>\n      <th>2020-06-19</th>\n      <th>2020-06-22</th>\n      <th>2020-06-23</th>\n      <th>2020-06-24</th>\n      <th>2020-06-29</th>\n      <th>2020-06-30</th>\n    </tr>\n    <tr>\n      <th>instrument</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>SH600000</th>\n      <td>2.261874e+06</td>\n      <td>2.396091e+06</td>\n      <td>2508010.25</td>\n      <td>2514704.250</td>\n      <td>2.446962e+06</td>\n      <td>2.553695e+06</td>\n      <td>2651805.000</td>\n      <td>2672115.500</td>\n      <td>2.615353e+06</td>\n      <td>2.528383e+06</td>\n      <td>...</td>\n      <td>1756381.125</td>\n      <td>1731880.125</td>\n      <td>1.667069e+06</td>\n      <td>1578945.875</td>\n      <td>1604882.875</td>\n      <td>1753198.375</td>\n      <td>1803229.625</td>\n      <td>1821627.75</td>\n      <td>1870240.375</td>\n      <td>1891510.250</td>\n    </tr>\n    <tr>\n      <th>SH600004</th>\n      <td>3.928184e+06</td>\n      <td>4.189268e+06</td>\n      <td>4512067.00</td>\n      <td>5012114.500</td>\n      <td>5.196058e+06</td>\n      <td>5.564821e+06</td>\n      <td>5843007.000</td>\n      <td>6681968.000</td>\n      <td>7.288429e+06</td>\n      <td>7.365033e+06</td>\n      <td>...</td>\n      <td>6330651.000</td>\n      <td>6216309.500</td>\n      <td>5.872529e+06</td>\n      <td>5767695.500</td>\n      <td>5221974.000</td>\n      <td>5086450.500</td>\n      <td>5085257.500</td>\n      <td>5237319.50</td>\n      <td>5581185.500</td>\n      <td>5673297.500</td>\n    </tr>\n    <tr>\n      <th>SH600006</th>\n      <td>3.677090e+06</td>\n      <td>3.512993e+06</td>\n      <td>3473326.75</td>\n      <td>3209310.500</td>\n      <td>3.290266e+06</td>\n      <td>3.676561e+06</td>\n      <td>3735112.500</td>\n      <td>3675256.750</td>\n      <td>3.791545e+06</td>\n      <td>3.871834e+06</td>\n      <td>...</td>\n      <td>6607741.500</td>\n      <td>6620880.500</td>\n      <td>6.562849e+06</td>\n      <td>6070401.000</td>\n      <td>5108298.500</td>\n      <td>4345236.500</td>\n      <td>3919222.000</td>\n      <td>3732892.00</td>\n      <td>3667949.250</td>\n      <td>3350491.500</td>\n    </tr>\n    <tr>\n      <th>SH600007</th>\n      <td>7.471518e+05</td>\n      <td>7.798411e+05</td>\n      <td>798650.00</td>\n      <td>852837.875</td>\n      <td>9.240082e+05</td>\n      <td>9.653506e+05</td>\n      <td>947146.375</td>\n      <td>937367.125</td>\n      <td>9.143474e+05</td>\n      <td>8.438519e+05</td>\n      <td>...</td>\n      <td>1080689.000</td>\n      <td>1032232.000</td>\n      <td>9.300471e+05</td>\n      <td>980329.000</td>\n      <td>1049706.875</td>\n      <td>1437618.125</td>\n      <td>1737494.250</td>\n      <td>1769172.75</td>\n      <td>1774657.625</td>\n      <td>1789137.625</td>\n    </tr>\n    <tr>\n      <th>SH600008</th>\n      <td>2.073627e+06</td>\n      <td>2.103406e+06</td>\n      <td>2189824.50</td>\n      <td>2180529.250</td>\n      <td>2.460642e+06</td>\n      <td>2.583131e+06</td>\n      <td>2648017.500</td>\n      <td>2676629.250</td>\n      <td>2.665881e+06</td>\n      <td>2.987846e+06</td>\n      <td>...</td>\n      <td>2529171.750</td>\n      <td>2523233.250</td>\n      <td>2.580083e+06</td>\n      <td>2596339.250</td>\n      <td>2327328.000</td>\n      <td>2334081.250</td>\n      <td>2259043.000</td>\n      <td>2114092.25</td>\n      <td>2183888.750</td>\n      <td>2090832.000</td>\n    </tr>\n    <tr>\n      <th>SH600009</th>\n      <td>1.847804e+06</td>\n      <td>2.140634e+06</td>\n      <td>2256605.50</td>\n      <td>2628696.250</td>\n      <td>2.906225e+06</td>\n      <td>3.077406e+06</td>\n      <td>3336729.250</td>\n      <td>3664973.000</td>\n      <td>3.747686e+06</td>\n      <td>4.049192e+06</td>\n      <td>...</td>\n      <td>4232498.500</td>\n      <td>4341015.500</td>\n      <td>4.239846e+06</td>\n      <td>4442293.000</td>\n      <td>4316313.500</td>\n      <td>4186823.750</td>\n      <td>4079572.000</td>\n      <td>4018620.50</td>\n      <td>3944616.750</td>\n      <td>4157829.250</td>\n    </tr>\n  </tbody>\n</table>\n<p>6 rows \u00d7 117 columns</p>\n</div>\n\n\n\n### Running time from 1518.555s to 0.007s \u2328\ufe0f\n\n### Speed up QLib backtesting about 200k times \ud83d\udda5\n\n$$\n\\begin{equation}\n\\begin{aligned}\n\\begin{Bmatrix}\n\\mathrm{Q}_{\\mathcal{s,\\space \\cdots,\\space t}} \n\\\\\n\\mathrm{V}_{\\mathcal{s,\\space d}}\n\\rightarrow\\mathrm{V}_{\\mathcal{s,\\space t}}\n\\end{Bmatrix}\n&\\rightarrow\\mathrm{I}_{\\mathcal{s,\\space \\cdots,\\space t}}\n&:\\space&\\mathscr{F}_{\\mathcal{map}}\n\\\\\n\\frac{1}{n_{s}}\\cdot \\sum_{\\mathcal{s}}\\mathrm{I}_{\\mathcal{s,\\space \\cdots,\\space t}}\n&=\n\\mathrm{I}_{\\mathcal{\\cdots,\\space t}}\n&:\\space&\\mathscr{F}_{\\mathcal{reduce}}\n\\\\\n\\frac{1}{n_{t\\space\\in\\space d}}\\cdot\\sum_{\\mathcal{t\\space\\in\\space d}}\\mathrm{I}_{\\mathcal{\\cdots,\\space t}}\n&=\n\\mathrm{I}_{\\mathcal{\\cdots,\\space d}}\n&:\\space&\\mathscr{F}_{\\mathcal{reduce}}\n\\end{aligned}\n\\end{equation}\n$$\n\n\n```python\nimport numpy as np\nfrom matplotlib import cm\nimport ipyvolume as ipv\n\nk, b, e, s, l, m = (5, 0.1, 1.2, 0.2, 6, 9)\nss = [np.repeat(np.arange(b, e, s), l * m)]\n[ss.append(ss[-1] - d) for d in [[(j - b)/k for j in ss[0]] for i in range(k)]]\nss = np.stack(ss)\nc = np.tile(np.repeat(np.arange(b, e, s), m), l)\nt = np.broadcast_to(np.arange(b, s * m, s), (l, l, m)).reshape(l * l * m)\nfig1 = ipv.figure()\nxnorm = ss[0] - ss[0].min()\nxnorm /= xnorm.ptp()\nscatter = ipv.scatter(ss, c, t, color= cm.gist_rainbow(xnorm), marker=\"sphere\")\nscatter.connected = True\nipv.xlim(b, e)\nipv.animation_control(scatter, interval=256)\n```\n\n\n```python\nipv.view(300, 50, distance=2)\nipv.show()\n```\n\n\n    VBox(children=(Figure(animation=256.0, camera=PerspectiveCamera(fov=46.0, position=(-1.1133407984528387, 1.532\u2026\n\n\n\n```python\nimport ipyvolume as ipv2\ntt=[]\n[tt.append(np.copy(t)) for i in range(3)]\ntt[1][0::3] = (t[2::3] - t[0::3]) / 2 + t[0::3]\ntt[1][1::3] = (t[2::3] - t[1::3]) / 2 + t[1::3]\ntt[2][0::3] = t[2::3]\ntt[2][1::3] = t[2::3]\ntt = np.stack(tt)\ns2 = ss[-1][0:54]\nc2 = c[0:54]\nt2 = tt[:,0:54]\nfig2 = ipv2.figure()\nznorm = t - t.min()\nznorm /= znorm.ptp()\nscatter2 = ipv2.scatter(s2, c2, t2, color=cm.gist_rainbow(znorm), marker=\"sphere\")\nscatter2.connected = True\nipv2.xlim(b, e)\nipv2.animation_control(scatter2, interval=300)\n```\n\n\n```python\nipv2.view(300, 50, distance=2)\nipv2.show()\n```\n\n\n    VBox(children=(Figure(animation=300.0, camera=PerspectiveCamera(fov=46.0, position=(-1.1133407984528387, 1.532\u2026\n\n\n### API  \ud83e\uddfb\n\n- #### Tsidx\n- #### MustelasQuote\n\n## Time series data index\n\n- ### Continuous $\\rightarrow$ Scatter\n- ### How to do unit test \ud83d\udda5\n- ### How to independently build\n\n## Vectorized concept \ud83d\udda5\n\n- ### Why vectorize ?\n- ### NEP 38 \ud83e\uddfb\n\n\n##  Readability\n\n- #### Message passing paradigm\n  - ##### IPC and RPC and multithreading ...\n- #### Generator and Coroutine \u2328\ufe0f\n- #### All design patterns are instances talk each other\u2328\ufe0f\n- #### But a huge gap between 2 languages \u2328\ufe0f\n\n## Nature Laws of performance\n\n- ### Good one is not a feature, but bad one is a bug \u2328\ufe0f\n- ### Time and space consistency \ud83e\uddfb\n- ### Time and space symmetry \ud83d\udda5\n", "meta": {"hexsha": "4c25b760ec1186d7ce50e3450a14346d42077cd8", "size": 25680, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "pyxqlib_perf.ipynb", "max_stars_repo_name": "bartuer/pyxqlib", "max_stars_repo_head_hexsha": "0d08b6041dba97a5f0b475be16c6334a0d74cbb2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyxqlib_perf.ipynb", "max_issues_repo_name": "bartuer/pyxqlib", "max_issues_repo_head_hexsha": "0d08b6041dba97a5f0b475be16c6334a0d74cbb2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyxqlib_perf.ipynb", "max_forks_repo_name": "bartuer/pyxqlib", "max_forks_repo_head_hexsha": "0d08b6041dba97a5f0b475be16c6334a0d74cbb2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3018867925, "max_line_length": 133, "alphanum_fraction": 0.4079439252, "converted": true, "num_tokens": 4560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647596, "lm_q2_score": 0.05340332979982424, "lm_q1q2_score": 0.023999063067933417}}
{"text": "#InSilicoQ\n\n\n```python\n!git clone https://github.com/QaiAbdi/InSilicoQ.git\n```\n\n    Cloning into 'InSilicoQ'...\n    remote: Enumerating objects: 58, done.\u001b[K\n    remote: Counting objects: 100% (58/58), done.\u001b[K\n    remote: Compressing objects: 100% (45/45), done.\u001b[K\n    remote: Total 58 (delta 22), reused 29 (delta 6), pack-reused 0\u001b[K\n    Unpacking objects: 100% (58/58), done.\n\n\n\n```python\n%cd /content/InSilicoQ\n```\n\n    /content/InSilicoQ\n\n\n\n```python\n!pip install -r requirments.txt\n```\n\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from -r requirments.txt (line 1)) (1.19.5)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from -r requirments.txt (line 2)) (1.3.5)\n    Requirement already satisfied: qiskit in /usr/local/lib/python3.7/dist-packages (from -r requirments.txt (line 3)) (0.34.1)\n    Requirement already satisfied: qiskit_machine_learning in /usr/local/lib/python3.7/dist-packages (from -r requirments.txt (line 4)) (0.3.0)\n    Requirement already satisfied: rdkit-pypi in /usr/local/lib/python3.7/dist-packages (from -r requirments.txt (line 5)) (2021.9.4)\n    Requirement already satisfied: chembl_webresource_client in /usr/local/lib/python3.7/dist-packages (from -r requirments.txt (line 6)) (0.10.7)\n    Requirement already satisfied: pubchempy in /usr/local/lib/python3.7/dist-packages (from -r requirments.txt (line 7)) (1.0.4)\n    Requirement already satisfied: sklearn in /usr/local/lib/python3.7/dist-packages (from -r requirments.txt (line 8)) (0.0)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from -r requirments.txt (line 9)) (3.2.2)\n    Requirement already satisfied: seaborn in /usr/local/lib/python3.7/dist-packages (from -r requirments.txt (line 10)) (0.11.2)\n    Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas->-r requirments.txt (line 2)) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->-r requirments.txt (line 2)) (2.8.2)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas->-r requirments.txt (line 2)) (1.15.0)\n    Requirement already satisfied: qiskit-ibmq-provider==0.18.3 in /usr/local/lib/python3.7/dist-packages (from qiskit->-r requirments.txt (line 3)) (0.18.3)\n    Requirement already satisfied: qiskit-aer==0.10.2 in /usr/local/lib/python3.7/dist-packages (from qiskit->-r requirments.txt (line 3)) (0.10.2)\n    Requirement already satisfied: qiskit-ignis==0.7.0 in /usr/local/lib/python3.7/dist-packages (from qiskit->-r requirments.txt (line 3)) (0.7.0)\n    Requirement already satisfied: qiskit-terra==0.19.1 in /usr/local/lib/python3.7/dist-packages (from qiskit->-r requirments.txt (line 3)) (0.19.1)\n    Requirement already satisfied: scipy>=1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.10.2->qiskit->-r requirments.txt (line 3)) (1.7.3)\n    Requirement already satisfied: requests-ntlm>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit->-r requirments.txt (line 3)) (1.1.0)\n    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit->-r requirments.txt (line 3)) (1.24.3)\n    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit->-r requirments.txt (line 3)) (2.23.0)\n    Requirement already satisfied: websocket-client>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit->-r requirments.txt (line 3)) (1.2.3)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ignis==0.7.0->qiskit->-r requirments.txt (line 3)) (57.4.0)\n    Requirement already satisfied: retworkx>=0.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ignis==0.7.0->qiskit->-r requirments.txt (line 3)) (0.11.0)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.1->qiskit->-r requirments.txt (line 3)) (1.7.1)\n    Requirement already satisfied: stevedore>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.1->qiskit->-r requirments.txt (line 3)) (3.5.0)\n    Requirement already satisfied: ply>=3.10 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.1->qiskit->-r requirments.txt (line 3)) (3.11)\n    Requirement already satisfied: python-constraint>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.1->qiskit->-r requirments.txt (line 3)) (1.4.0)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.1->qiskit->-r requirments.txt (line 3)) (5.4.8)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.1->qiskit->-r requirments.txt (line 3)) (0.3.4)\n    Requirement already satisfied: tweedledum<2.0,>=1.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.1->qiskit->-r requirments.txt (line 3)) (1.1.1)\n    Requirement already satisfied: symengine>=0.8 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.1->qiskit->-r requirments.txt (line 3)) (0.8.1)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit->-r requirments.txt (line 3)) (2021.10.8)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit->-r requirments.txt (line 3)) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit->-r requirments.txt (line 3)) (3.0.4)\n    Requirement already satisfied: ntlm-auth>=1.0.2 in /usr/local/lib/python3.7/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit->-r requirments.txt (line 3)) (1.5.0)\n    Requirement already satisfied: cryptography>=1.3 in /usr/local/lib/python3.7/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit->-r requirments.txt (line 3)) (36.0.1)\n    Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit->-r requirments.txt (line 3)) (1.15.0)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit->-r requirments.txt (line 3)) (2.21)\n    Requirement already satisfied: importlib-metadata>=1.7.0 in /usr/local/lib/python3.7/dist-packages (from stevedore>=3.0.0->qiskit-terra==0.19.1->qiskit->-r requirments.txt (line 3)) (4.10.1)\n    Requirement already satisfied: pbr!=2.1.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from stevedore>=3.0.0->qiskit-terra==0.19.1->qiskit->-r requirments.txt (line 3)) (5.8.1)\n    Requirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=1.7.0->stevedore>=3.0.0->qiskit-terra==0.19.1->qiskit->-r requirments.txt (line 3)) (3.10.0.2)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=1.7.0->stevedore>=3.0.0->qiskit-terra==0.19.1->qiskit->-r requirments.txt (line 3)) (3.7.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra==0.19.1->qiskit->-r requirments.txt (line 3)) (1.2.1)\n    Requirement already satisfied: scikit-learn>=0.20.0 in /usr/local/lib/python3.7/dist-packages (from qiskit_machine_learning->-r requirments.txt (line 4)) (1.0.2)\n    Requirement already satisfied: fastdtw in /usr/local/lib/python3.7/dist-packages (from qiskit_machine_learning->-r requirments.txt (line 4)) (0.3.4)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.20.0->qiskit_machine_learning->-r requirments.txt (line 4)) (1.1.0)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.20.0->qiskit_machine_learning->-r requirments.txt (line 4)) (3.1.0)\n    Requirement already satisfied: Pillow in /usr/local/lib/python3.7/dist-packages (from rdkit-pypi->-r requirments.txt (line 5)) (7.1.2)\n    Requirement already satisfied: requests-cache~=0.7.0 in /usr/local/lib/python3.7/dist-packages (from chembl_webresource_client->-r requirments.txt (line 6)) (0.7.5)\n    Requirement already satisfied: easydict in /usr/local/lib/python3.7/dist-packages (from chembl_webresource_client->-r requirments.txt (line 6)) (1.9)\n    Requirement already satisfied: url-normalize<2.0,>=1.4 in /usr/local/lib/python3.7/dist-packages (from requests-cache~=0.7.0->chembl_webresource_client->-r requirments.txt (line 6)) (1.4.3)\n    Requirement already satisfied: pyyaml>=5.4 in /usr/local/lib/python3.7/dist-packages (from requests-cache~=0.7.0->chembl_webresource_client->-r requirments.txt (line 6)) (6.0)\n    Requirement already satisfied: attrs<22.0,>=21.2 in /usr/local/lib/python3.7/dist-packages (from requests-cache~=0.7.0->chembl_webresource_client->-r requirments.txt (line 6)) (21.4.0)\n    Requirement already satisfied: itsdangerous>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from requests-cache~=0.7.0->chembl_webresource_client->-r requirments.txt (line 6)) (2.0.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r requirments.txt (line 9)) (0.11.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r requirments.txt (line 9)) (1.3.2)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r requirments.txt (line 9)) (3.0.7)\n\n\n\n```python\n!python setup.py install\n```\n\n    running install\n    running bdist_egg\n    running egg_info\n    creating Insilicoq.egg-info\n    writing Insilicoq.egg-info/PKG-INFO\n    writing dependency_links to Insilicoq.egg-info/dependency_links.txt\n    writing top-level names to Insilicoq.egg-info/top_level.txt\n    writing manifest file 'Insilicoq.egg-info/SOURCES.txt'\n    adding license file 'LICENSE'\n    writing manifest file 'Insilicoq.egg-info/SOURCES.txt'\n    installing library code to build/bdist.linux-x86_64/egg\n    running install_lib\n    running build_py\n    creating build\n    creating build/lib\n    creating build/lib/Insilicoq\n    copying Insilicoq/quantum_kernel.py -> build/lib/Insilicoq\n    copying Insilicoq/__init__.py -> build/lib/Insilicoq\n    creating build/bdist.linux-x86_64\n    creating build/bdist.linux-x86_64/egg\n    creating build/bdist.linux-x86_64/egg/Insilicoq\n    copying build/lib/Insilicoq/quantum_kernel.py -> build/bdist.linux-x86_64/egg/Insilicoq\n    copying build/lib/Insilicoq/__init__.py -> build/bdist.linux-x86_64/egg/Insilicoq\n    byte-compiling build/bdist.linux-x86_64/egg/Insilicoq/quantum_kernel.py to quantum_kernel.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/Insilicoq/__init__.py to __init__.cpython-37.pyc\n    creating build/bdist.linux-x86_64/egg/EGG-INFO\n    copying Insilicoq.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying Insilicoq.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying Insilicoq.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying Insilicoq.egg-info/not-zip-safe -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying Insilicoq.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    creating dist\n    creating 'dist/Insilicoq-0.1-py3.7.egg' and adding 'build/bdist.linux-x86_64/egg' to it\n    removing 'build/bdist.linux-x86_64/egg' (and everything under it)\n    Processing Insilicoq-0.1-py3.7.egg\n    creating /usr/local/lib/python3.7/dist-packages/Insilicoq-0.1-py3.7.egg\n    Extracting Insilicoq-0.1-py3.7.egg to /usr/local/lib/python3.7/dist-packages\n    Adding Insilicoq 0.1 to easy-install.pth file\n    \n    Installed /usr/local/lib/python3.7/dist-packages/Insilicoq-0.1-py3.7.egg\n    Processing dependencies for Insilicoq==0.1\n    Finished processing dependencies for Insilicoq==0.1\n\n\n#Succesful Import!\n\n\n```python\nimport Insilicoq\nhelp(Insilicoq)\n```\n\n    Help on package Insilicoq:\n    \n    NAME\n        Insilicoq\n    \n    PACKAGE CONTENTS\n        quantum_kernel\n    \n    FILE\n        /content/InSilicoQ/Insilicoq/__init__.py\n    \n    \n\n\n\n```python\nfrom Insilicoq import qkern_default\n```\n\nTesting RDKit\n\n\n```python\nfrom rdkit import Chem\nfrom rdkit.Chem import Draw\nfrom rdkit.Chem.Draw import IPythonConsole\nfrom rdkit.Chem import Descriptors\nfrom rdkit.Chem import AllChem\nfrom rdkit import DataStructs\nimport numpy as np\n```\n\n\n```python\nmol = Chem.MolFromSmiles('C1CCC1')\nmol\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "34b9bfdd9fac310f00df5ee93603ba68156154d5", "size": 21939, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "InSilicoQ_Tutorial.ipynb", "max_stars_repo_name": "QaiAbdi/InSilicoQ", "max_stars_repo_head_hexsha": "302ed2773dc8fcf0bf7b734c328e62984b5089aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "InSilicoQ_Tutorial.ipynb", "max_issues_repo_name": "QaiAbdi/InSilicoQ", "max_issues_repo_head_hexsha": "302ed2773dc8fcf0bf7b734c328e62984b5089aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "InSilicoQ_Tutorial.ipynb", "max_forks_repo_name": "QaiAbdi/InSilicoQ", "max_forks_repo_head_hexsha": "302ed2773dc8fcf0bf7b734c328e62984b5089aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.5913043478, "max_line_length": 3150, "alphanum_fraction": 0.6523086741, "converted": true, "num_tokens": 4409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233681595684605, "lm_q2_score": 0.060975174465973454, "lm_q1q2_score": 0.023922805802393206}}
{"text": "<a href=\"https://colab.research.google.com/github/JacopoMangiavacchi/animegan2-coreml/blob/master/convert_coreml.ipynb\" target=\"_parent\"></a>\n\n\n```python\n!pip install coremltools\n```\n\n    Collecting coremltools\n      Downloading coremltools-5.1.0-cp37-none-manylinux1_x86_64.whl (1.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.6 MB 12.7 MB/s \n    \u001b[?25hRequirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from coremltools) (1.7.1)\n    Requirement already satisfied: protobuf>=3.1.0 in /usr/local/lib/python3.7/dist-packages (from coremltools) (3.17.3)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from coremltools) (4.62.3)\n    Requirement already satisfied: numpy>=1.14.5 in /usr/local/lib/python3.7/dist-packages (from coremltools) (1.19.5)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from coremltools) (21.2)\n    Requirement already satisfied: six>=1.9 in /usr/local/lib/python3.7/dist-packages (from protobuf>=3.1.0->coremltools) (1.15.0)\n    Requirement already satisfied: pyparsing<3,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->coremltools) (2.4.7)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->coremltools) (1.2.1)\n    Installing collected packages: coremltools\n    Successfully installed coremltools-5.1.0\n\n\n\n```python\nimport os\nimport torch\nimport coremltools\n```\n\n    WARNING:root:scikit-learn version 1.0.1 is not supported. Minimum required version: 0.17. Maximum required version: 0.19.2. Disabling scikit-learn conversion API.\n    WARNING:root:TensorFlow version 2.7.0 has not been tested with coremltools. You may run into unexpected errors. TensorFlow 2.5.0 is the most recent version that has been tested.\n    WARNING:root:Keras version 2.7.0 has not been tested with coremltools. You may run into unexpected errors. Keras 2.2.4 is the most recent version that has been tested.\n    WARNING:root:Torch version 1.10.0+cu111 has not been tested with coremltools. You may run into unexpected errors. Torch 1.9.1 is the most recent version that has been tested.\n\n\n\n```python\n!git clone https://github.com/jacopomangiavacchi/animegan2-coreml\n```\n\n    Cloning into 'animegan2-coreml'...\n    remote: Enumerating objects: 85, done.\u001b[K\n    remote: Counting objects: 100% (85/85), done.\u001b[K\n    remote: Compressing objects: 100% (78/78), done.\u001b[K\n    remote: Total 85 (delta 35), reused 36 (delta 6), pack-reused 0\u001b[K\n    Unpacking objects: 100% (85/85), done.\n\n\n\n```python\nos.chdir(f'./animegan2-coreml')\n```\n\n\n```python\nfrom model import Generator\n\ndevice = 'cpu'\ntorch.set_grad_enabled(False)\n\nmodel = Generator().eval().to(device)\n```\n\n\n```python\nckpt = torch.load(f\"weights/celeba_distill.pt\", map_location=device)\n# ckpt = torch.load(f\"weights/face_paint_512_v2.pt\", map_location=device)\n# ckpt = torch.load(f\"weights/paprika.pt\", map_location=device)\nmodel.load_state_dict(ckpt)\n```\n\n\n\n\n    <All keys matched successfully>\n\n\n\n\n```python\nimage_sizes = [256, 512, 1024]\n\nfor image_size in image_sizes:\n    image = torch.randn(1, 3, image_size, image_size)\n    output = model(image.to(device))\n\n    # scripted_model = torch.jit.script(model)\n    traced = torch.jit.trace(model, image)\n\n    image_input = coremltools.ImageType(name=\"input_1\", shape=(1, 3, image_size, image_size))\n\n    mlmodel = coremltools.converters.convert(\n      traced,\n      inputs=[image_input],\n      minimum_deployment_target=coremltools.target.iOS15,\n      compute_units=coremltools.ComputeUnit.ALL,\n      convert_to=\"mlprogram\", # \"neuralnetwork\"\n      compute_precision=coremltools.precision.FLOAT16\n    )\n\n    mlmodel.save(f'animegan2-celeba-distil-{image_size}.mlpackage')    \n    spec = coremltools.utils.load_spec(f\"animegan2-celeba-distil-{image_size}.mlpackage\")\n\n    output = spec.description.output[0]\n\n    output.type.imageType.colorSpace = coremltools.proto.FeatureTypes_pb2.ImageFeatureType.RGB\n    output.type.imageType.height = image_size\n    output.type.imageType.width = image_size\n\n    coremltools.utils.save_spec(spec, f\"animegan2-celeba-distil-{image_size}.mlpackage\")\n```\n\n    /usr/local/lib/python3.7/dist-packages/torch/nn/functional.py:2359: UserWarning: __floordiv__ is deprecated, and its behavior will change in a future version of pytorch. It currently rounds toward 0 (like the 'trunc' function NOT 'floor'). This results in incorrect rounding for negative values. To keep the current behavior, use torch.div(a, b, rounding_mode='trunc'), or for actual floor division, use torch.div(a, b, rounding_mode='floor').\n      _verify_batch_size([input.size(0) * input.size(1) // num_groups, num_groups] + list(input.size()[2:]))\n    Converting Frontend ==> MIL Ops: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589| 295/296 [00:00<00:00, 548.62 ops/s]\n    Running MIL Common passes:   0%|          | 0/34 [00:00<?, ? passes/s]/usr/local/lib/python3.7/dist-packages/coremltools/converters/mil/mil/passes/name_sanitization_utils.py:129: UserWarning: Output, '457', of the source model, has been renamed to 'var_457' in the Core ML model.\n      warnings.warn(msg.format(var.name, new_name))\n    Running MIL Common passes: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 34/34 [00:00<00:00, 63.95 passes/s]\n    Running MIL FP16ComputePrecision pass: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.63s/ passes]\n    Running MIL Clean up passes: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 9/9 [00:06<00:00,  1.46 passes/s]\n    Converting Frontend ==> MIL Ops: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589| 295/296 [00:00<00:00, 538.89 ops/s]\n    Running MIL Common passes: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 34/34 [00:00<00:00, 65.50 passes/s]\n    Running MIL FP16ComputePrecision pass: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.67s/ passes]\n    Running MIL Clean up passes: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 9/9 [00:06<00:00,  1.49 passes/s]\n    Converting Frontend ==> MIL Ops: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589| 295/296 [00:00<00:00, 526.11 ops/s]\n    Running MIL Common passes: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 34/34 [00:00<00:00, 64.26 passes/s]\n    Running MIL FP16ComputePrecision pass: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [00:02<00:00,  2.59s/ passes]\n    Running MIL Clean up passes: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 9/9 [00:06<00:00,  1.47 passes/s]\n\n\n\n```python\n!zip -r /content/animegan2-coreml/animegan2-celeba-distil-1024.zip /content/animegan2-coreml/animegan2-celeba-distil-1024.mlpackage\n!zip -r /content/animegan2-coreml/animegan2-celeba-distil-512.zip /content/animegan2-coreml/animegan2-celeba-distil-512.mlpackage\n!zip -r /content/animegan2-coreml/animegan2-celeba-distil-256.zip /content/animegan2-coreml/animegan2-celeba-distil-256.mlpackage\n```\n\n      adding: content/animegan2-coreml/animegan2-celeba-distil-1024.mlpackage/ (stored 0%)\n      adding: content/animegan2-coreml/animegan2-celeba-distil-1024.mlpackage/Manifest.json (deflated 60%)\n      adding: content/animegan2-coreml/animegan2-celeba-distil-1024.mlpackage/Data/ (stored 0%)\n      adding: content/animegan2-coreml/animegan2-celeba-distil-1024.mlpackage/Data/com.apple.CoreML/ (stored 0%)\n      adding: content/animegan2-coreml/animegan2-celeba-distil-1024.mlpackage/Data/com.apple.CoreML/animegan2-celeba-distil-1024.mlmodel (deflated 88%)\n      adding: content/animegan2-coreml/animegan2-celeba-distil-1024.mlpackage/Data/com.apple.CoreML/weights/ (stored 0%)\n      adding: content/animegan2-coreml/animegan2-celeba-distil-1024.mlpackage/Data/com.apple.CoreML/weights/weight.bin (deflated 8%)\n      adding: content/animegan2-coreml/animegan2-celeba-distil-512.mlpackage/ (stored 0%)\n      adding: content/animegan2-coreml/animegan2-celeba-distil-512.mlpackage/Manifest.json (deflated 60%)\n      adding: content/animegan2-coreml/animegan2-celeba-distil-512.mlpackage/Data/ (stored 0%)\n      adding: content/animegan2-coreml/animegan2-celeba-distil-512.mlpackage/Data/com.apple.CoreML/ (stored 0%)\n      adding: content/animegan2-coreml/animegan2-celeba-distil-512.mlpackage/Data/com.apple.CoreML/animegan2-celeba-distil-512.mlmodel (deflated 88%)\n      adding: content/animegan2-coreml/animegan2-celeba-distil-512.mlpackage/Data/com.apple.CoreML/weights/ (stored 0%)\n      adding: content/animegan2-coreml/animegan2-celeba-distil-512.mlpackage/Data/com.apple.CoreML/weights/weight.bin (deflated 8%)\n      adding: content/animegan2-coreml/animegan2-celeba-distil-256.mlpackage/ (stored 0%)\n      adding: content/animegan2-coreml/animegan2-celeba-distil-256.mlpackage/Manifest.json (deflated 59%)\n      adding: content/animegan2-coreml/animegan2-celeba-distil-256.mlpackage/Data/ (stored 0%)\n      adding: content/animegan2-coreml/animegan2-celeba-distil-256.mlpackage/Data/com.apple.CoreML/ (stored 0%)\n      adding: content/animegan2-coreml/animegan2-celeba-distil-256.mlpackage/Data/com.apple.CoreML/animegan2-celeba-distil-256.mlmodel (deflated 88%)\n      adding: content/animegan2-coreml/animegan2-celeba-distil-256.mlpackage/Data/com.apple.CoreML/weights/ (stored 0%)\n      adding: content/animegan2-coreml/animegan2-celeba-distil-256.mlpackage/Data/com.apple.CoreML/weights/weight.bin (deflated 8%)\n\n\n\n```python\nos.chdir(f'..')\n```\n", "meta": {"hexsha": "ebdc573f5f7a5196fd44ec62dbba2a541ce9138b", "size": 26145, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "convert_coreml.ipynb", "max_stars_repo_name": "JacopoMangiavacchi/animegan2-coreml", "max_stars_repo_head_hexsha": "525de032137602ac03bf5916ee44c6d7c5bce57e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-11-15T02:34:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T10:18:40.000Z", "max_issues_repo_path": "convert_coreml.ipynb", "max_issues_repo_name": "JacopoMangiavacchi/animegan2-coreml", "max_issues_repo_head_hexsha": "525de032137602ac03bf5916ee44c6d7c5bce57e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "convert_coreml.ipynb", "max_forks_repo_name": "JacopoMangiavacchi/animegan2-coreml", "max_forks_repo_head_hexsha": "525de032137602ac03bf5916ee44c6d7c5bce57e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 84.3387096774, "max_line_length": 11864, "alphanum_fraction": 0.4637215529, "converted": true, "num_tokens": 2802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.05184546262100775, "lm_q1q2_score": 0.02390162819949405}}
{"text": "# Targeted Selection Demo For Datasets With Rare Classes\n\n### Imports \n\n\n```python\nimport time\nimport random\nimport datetime\nimport copy\nimport numpy as np\nfrom tabulate import tabulate\nimport os\nimport csv\nimport json\nimport subprocess\nimport sys\nimport PIL.Image as Image\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torchvision\nimport torchvision.models as models\nfrom matplotlib import pyplot as plt\nfrom trust.trust.utils.models.resnet import ResNet18\nfrom trust.trust.utils.custom_dataset import load_dataset_custom\nfrom torch.utils.data import Subset\nfrom torch.autograd import Variable\nimport tqdm\nfrom math import floor\nfrom sklearn.metrics.pairwise import cosine_similarity, pairwise_distances\nfrom trust.trust.strategies.smi import SMI\nfrom trust.trust.strategies.random_sampling import RandomSampling\n\nseed=42\ntorch.manual_seed(seed)\nnp.random.seed(seed)\nrandom.seed(seed)\nfrom trust.trust.utils.utils import *\nfrom trust.trust.utils.viz import tsne_smi\n```\n\n### Helper functions\n\n\n```python\ndef model_eval_loss(data_loader, model, criterion):\n    total_loss = 0\n    with torch.no_grad():\n        for batch_idx, (inputs, targets) in enumerate(data_loader):\n            inputs, targets = inputs.to(device), targets.to(device, non_blocking=True)\n            outputs = model(inputs)\n            loss = criterion(outputs, targets)\n            total_loss += loss.item()\n    return total_loss\n\ndef init_weights(m):\n    if isinstance(m, nn.Conv2d):\n        torch.nn.init.xavier_uniform_(m.weight)\n    elif isinstance(m, nn.Linear):\n        torch.nn.init.xavier_uniform_(m.weight)\n        m.bias.data.fill_(0.01)\n\ndef weight_reset(m):\n    if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):\n        m.reset_parameters()\n                \ndef create_model(name, num_cls, device, embedding_type):\n    if name == 'ResNet18':\n        if embedding_type == \"gradients\":\n            model = ResNet18(num_cls)\n        else:\n            model = models.resnet18()\n    elif name == 'MnistNet':\n        model = MnistNet()\n    elif name == 'ResNet164':\n        model = ResNet164(num_cls)\n    model.apply(init_weights)\n    model = model.to(device)\n    return model\n\ndef loss_function():\n    criterion = nn.CrossEntropyLoss()\n    criterion_nored = nn.CrossEntropyLoss(reduction='none')\n    return criterion, criterion_nored\n\ndef optimizer_with_scheduler(model, num_epochs, learning_rate, m=0.9, wd=5e-4):\n    optimizer = optim.SGD(model.parameters(), lr=learning_rate,\n                          momentum=m, weight_decay=wd)\n    scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=num_epochs)\n    return optimizer, scheduler\n\ndef optimizer_without_scheduler(model, learning_rate, m=0.9, wd=5e-4):\n#     optimizer = optim.Adam(model.parameters(),weight_decay=wd)\n    optimizer = optim.SGD(model.parameters(), lr=learning_rate,\n                          momentum=m, weight_decay=wd)\n    return optimizer\n\ndef generate_cumulative_timing(mod_timing):\n    tmp = 0\n    mod_cum_timing = np.zeros(len(mod_timing))\n    for i in range(len(mod_timing)):\n        tmp += mod_timing[i]\n        mod_cum_timing[i] = tmp\n    return mod_cum_timing/3600\n\ndef displayTable(val_err_log, tst_err_log):\n    col1 = [str(i) for i in range(10)]\n    val_acc = [str(100-i) for i in val_err_log]\n    tst_acc = [str(100-i) for i in tst_err_log]\n    table = [col1, val_acc, tst_acc]\n    table = map(list, zip(*table))\n    print(tabulate(table, headers=['Class', 'Val Accuracy', 'Test Accuracy'], tablefmt='orgtbl'))\n\ndef find_err_per_class(test_set, val_set, final_val_classifications, final_val_predictions, final_tst_classifications, \n                       final_tst_predictions, saveDir, prefix):\n    val_err_idx = list(np.where(np.array(final_val_classifications) == False)[0])\n    tst_err_idx = list(np.where(np.array(final_tst_classifications) == False)[0])\n    val_class_err_idxs = []\n    tst_err_log = []\n    val_err_log = []\n    for i in range(num_cls):\n        if(feature==\"classimb\"): tst_class_idxs = list(torch.where(torch.Tensor(test_set.targets) == i)[0].cpu().numpy())\n        val_class_idxs = list(torch.where(torch.Tensor(val_set.targets.float()) == i)[0].cpu().numpy())\n        #err classifications per class\n        val_err_class_idx = set(val_err_idx).intersection(set(val_class_idxs))\n        tst_err_class_idx = set(tst_err_idx).intersection(set(tst_class_idxs))\n        if(len(val_class_idxs)>0):\n            val_error_perc = round((len(val_err_class_idx)/len(val_class_idxs))*100,2)\n        else:\n            val_error_perc = 0\n        tst_error_perc = round((len(tst_err_class_idx)/len(tst_class_idxs))*100,2)\n#         print(\"val, test error% for class \", i, \" : \", val_error_perc, tst_error_perc)\n        val_class_err_idxs.append(val_err_class_idx)\n        tst_err_log.append(tst_error_perc)\n        val_err_log.append(val_error_perc)\n    displayTable(val_err_log, tst_err_log)\n    tst_err_log.append(sum(tst_err_log)/len(tst_err_log))\n    val_err_log.append(sum(val_err_log)/len(val_err_log))\n    return tst_err_log, val_err_log, val_class_err_idxs\n\n\ndef aug_train_subset(train_set, lake_set, true_lake_set, subset, lake_subset_idxs, budget, augrandom=False):\n    all_lake_idx = list(range(len(lake_set)))\n    if(not(len(subset)==budget) and augrandom):\n        print(\"Budget not filled, adding \", str(int(budget) - len(subset)), \" randomly.\")\n        remain_budget = int(budget) - len(subset)\n        remain_lake_idx = list(set(all_lake_idx) - set(subset))\n        random_subset_idx = list(np.random.choice(np.array(remain_lake_idx), size=int(remain_budget), replace=False))\n        subset += random_subset_idx\n    lake_ss = SubsetWithTargets(true_lake_set, subset, torch.Tensor(true_lake_set.targets.float())[subset])\n    remain_lake_idx = list(set(all_lake_idx) - set(lake_subset_idxs))\n    remain_lake_set = SubsetWithTargets(lake_set, remain_lake_idx, torch.Tensor(lake_set.targets.float())[remain_lake_idx])\n    remain_true_lake_set = SubsetWithTargets(true_lake_set, remain_lake_idx, torch.Tensor(true_lake_set.targets.float())[remain_lake_idx])\n#     print(len(lake_ss),len(remain_lake_set),len(lake_set))\n    aug_train_set = torch.utils.data.ConcatDataset([train_set, lake_ss])\n    return aug_train_set, remain_lake_set, remain_true_lake_set, lake_ss\n                        \ndef getQuerySet(val_set, val_class_err_idxs, imb_cls_idx, miscls):\n    miscls_idx = []\n    if(miscls):\n        for i in range(len(val_class_err_idxs)):\n            if i in imb_cls_idx:\n                miscls_idx += val_class_err_idxs[i]\n        print(\"Total misclassified examples from imbalanced classes (Size of query set): \", len(miscls_idx))\n    else:\n        for i in imb_cls_idx:\n            imb_cls_samples = list(torch.where(torch.Tensor(val_set.targets.float()) == i)[0].cpu().numpy())\n            miscls_idx += imb_cls_samples\n        print(\"Total samples from imbalanced classes as targets (Size of query set): \", len(miscls_idx))\n    return Subset(val_set, miscls_idx), val_set.targets[miscls_idx]\n\ndef getPerClassSel(lake_set, subset, num_cls):\n    perClsSel = []\n    subset_cls = torch.Tensor(lake_set.targets.float())[subset]\n    for i in range(num_cls):\n        cls_subset_idx = list(torch.where(subset_cls == i)[0].cpu().numpy())\n        perClsSel.append(len(cls_subset_idx))\n    return perClsSel\n\ndef print_final_results(res_dict, sel_cls_idx):\n    print(\"Gain in overall test accuracy: \", res_dict['test_acc'][1]-res_dict['test_acc'][0])\n    bf_sel_cls_acc = np.array(res_dict['all_class_acc'][0])[sel_cls_idx]\n    af_sel_cls_acc = np.array(res_dict['all_class_acc'][1])[sel_cls_idx]\n    print(\"Gain in targeted test accuracy: \", np.mean(af_sel_cls_acc-bf_sel_cls_acc))\n```\n\n# Data, Model & Experimental Settings\nThe CIFAR-10 dataset contains 60,000 32x32 color images in 10 different classes.The 10 different classes represent airplanes, cars, birds, cats, deer, dogs, frogs, horses, ships, and trucks. There are 6,000 images of each class. The training set contains 50,000 images and test set contains 10,000 images. We will use custom_dataset() function in Trust to simulated a class imbalance scenario using the split_cfg dictionary given below. We then use a ResNet18 model as our task DNN and train it on the simulated imbalanced version of the CIFAR-10 dataset. Next we perform targeted selection using various SMI functions and compare their gain in overall accuracy as well as on the imbalanced classes.\n\n\n```python\nfeature = \"classimb\"\ndevice_id = 0\nrun=\"test_run\"\ndatadir = 'data/'\ndata_name = 'cifar10'\nmodel_name = 'ResNet18'\nlearning_rate = 0.01\ncomputeClassErrorLog = True\ndevice = \"cuda:\"+str(device_id) if torch.cuda.is_available() else \"cpu\"\nmiscls = False #Set to True if only the misclassified examples from the imbalanced classes is to be used\nembedding_type = \"gradients\" #Type of the representation to use (gradients/features)\nnum_cls = 10\nbudget = 400\nvisualize_tsne = False\nsplit_cfg = {\"num_cls_imbalance\":2, #Number of rare classes\n             \"per_imbclass_train\":200, #Number of samples per rare class in the train dataset\n             \"per_imbclass_val\":5, #Number of samples per rare class in the validation dataset\n             \"per_imbclass_lake\":150, #Number of samples per rare class in the unlabeled dataset\n             \"per_class_train\":1000,  #Number of samples per unrare class in the train dataset\n             \"per_class_val\":5, #Number of samples per unrare class in the validation dataset\n             \"per_class_lake\":3000} #Number of samples per unrare class in the unlabeled dataset\ninitModelPath = \"./\"+data_name + \"_\" + model_name + \"_\" + str(learning_rate) + \"_\" + str(split_cfg[\"per_imbclass_train\"]) + \"_\" + str(split_cfg[\"per_class_train\"]) + \"_\" + str(split_cfg[\"num_cls_imbalance\"])\n```\n\n# Targeted Selection Algorithm\n1. Given: Initial Labeled set of Examples: \ud835\udc38, large unlabeled dataset: \ud835\udc48, A target subset/slice where we want to improve accuracy: \ud835\udc47, Loss function \ud835\udc3f for learning\n2. Train model with loss $\\mathcal L$ on labeled set $E$ and obtain parameters $\\theta_E$\n3. Compute the gradients $\\{\\nabla_{\\theta_E} \\mathcal L(x_i, y_i), i \\in U\\}$ (using hypothesized labels) and $\\{\\nabla_{\\theta_E} \\mathcal L(x_i, y_i), i \\in T\\}$. \n(This notebook uses gradients for representation. However, any other representation can be used. Trust also supports using features via the API.)\n4. Compute the similarity kernels $S$ (this includes kernel of the elements within $U$, within $T$ and between $U$ and $T$) and define a submodular function $f$ and diversity function $g$\n5. Compute subset $\\hat{A}$ by mazximizing the SMI function: $\\hat{A} \\gets \\max_{A \\subseteq U, |A|\\leq k} I_f(A;T) + \\gamma g(A)$\n6. Obtain the labels of the elements in $A^*$: $L(\\hat{A})$\n7. Train a model on the combined labeled set $E \\cup L(\\hat{A})$\n\n\n```python\ndef run_targeted_selection(dataset_name, datadir, feature, model_name, budget, split_cfg, learning_rate, run,\n                device, computeErrorLog, strategy=\"SIM\", sf=\"\"):\n\n    #load the dataset in the class imbalance setting\n    train_set, val_set, test_set, lake_set, sel_cls_idx, num_cls = load_dataset_custom(datadir, dataset_name, feature, split_cfg, False, False)\n    print(\"Indices of randomly selected classes for imbalance: \", sel_cls_idx)\n    \n    #Set batch size for train, validation and test datasets\n    N = len(train_set)\n    trn_batch_size = 20\n    val_batch_size = 10\n    tst_batch_size = 100\n\n    #Create dataloaders\n    trainloader = torch.utils.data.DataLoader(train_set, batch_size=trn_batch_size,\n                                              shuffle=True, pin_memory=True)\n\n    valloader = torch.utils.data.DataLoader(val_set, batch_size=val_batch_size, \n                                            shuffle=False, pin_memory=True)\n\n    tstloader = torch.utils.data.DataLoader(test_set, batch_size=tst_batch_size,\n                                             shuffle=False, pin_memory=True)\n    \n    lakeloader = torch.utils.data.DataLoader(lake_set, batch_size=tst_batch_size,\n                                         shuffle=False, pin_memory=True)\n    true_lake_set = copy.deepcopy(lake_set)\n    # Budget for subset selection\n    bud = budget\n   \n    # Variables to store accuracies\n    num_rounds=2 #The first round is for training the initial model and the second round is to train the final model\n    fulltrn_losses = np.zeros(num_rounds)\n    val_losses = np.zeros(num_rounds)\n    tst_losses = np.zeros(num_rounds)\n    timing = np.zeros(num_rounds)\n    val_acc = np.zeros(num_rounds)\n    full_trn_acc = np.zeros(num_rounds)\n    tst_acc = np.zeros(num_rounds)\n    final_tst_predictions = []\n    final_tst_classifications = []\n    best_val_acc = -1\n    csvlog = []\n    val_csvlog = []\n    # Results logging file\n    all_logs_dir = './results/' + dataset_name  + '/' + feature + '/'+  sf + '/' + str(bud) + '/' + str(run)\n#     print(\"Saving results to: \", all_logs_dir)\n#     subprocess.run([\"mkdir\", \"-p\", all_logs_dir]) #Uncomment for saving results\n    exp_name = dataset_name + \"_\" + feature +  \"_\" + strategy + \"_\" + str(len(sel_cls_idx))  +\"_\" + sf +  '_budget:' + str(bud) + '_rounds:' + str(num_rounds) + '_runs' + str(run)\n\n    #Create a dictionary for storing results and the experimental setting\n    res_dict = {\"dataset\":data_name, \n                \"feature\":feature, \n                \"sel_func\":sf,\n                \"sel_budget\":budget, \n                \"num_selections\":num_rounds-1, \n                \"model\":model_name, \n                \"learning_rate\":learning_rate, \n                \"setting\":split_cfg, \n                \"all_class_acc\":None, \n                \"test_acc\":[],\n                \"sel_per_cls\":[], \n                \"sel_cls_idx\":sel_cls_idx.tolist()}\n    \n    # Model Creation\n    model = create_model(model_name, num_cls, device, embedding_type)\n    model1 = create_model(model_name, num_cls, device, embedding_type)\n    strategy_args = {'batch_size': 20, 'device':device, 'embedding_type':'gradients', 'keep_embedding':True}\n    unlabeled_lake_set = LabeledToUnlabeledDataset(lake_set)\n    \n    if(strategy == \"SIM\"):\n        strategy_args['smi_function'] = sf\n        strategy_sel = SMI(train_set, unlabeled_lake_set, val_set, model, num_cls, strategy_args)\n    if(strategy == \"random\"):\n        strategy_sel = RandomSampling(train_set, unlabeled_lake_set, model, num_cls, strategy_args)\n        \n    # Loss Functions\n    criterion, criterion_nored = loss_function()\n\n    # Getting the optimizer and scheduler\n    optimizer = optimizer_without_scheduler(model, learning_rate)\n\n    for i in range(num_rounds):\n        tst_loss = 0\n        tst_correct = 0\n        tst_total = 0\n        val_loss = 0\n        val_correct = 0\n        val_total = 0\n        \n        if(i==0):\n            print(\"Initial training epoch\")\n            if(os.path.exists(initModelPath)): #Read the initial trained model if it exists\n                model.load_state_dict(torch.load(initModelPath, map_location=device))\n                print(\"Init model loaded from disk, skipping init training: \", initModelPath)\n                with torch.no_grad():\n                    final_val_predictions = []\n                    final_val_classifications = []\n                    for batch_idx, (inputs, targets) in enumerate(valloader):\n                        inputs, targets = inputs.to(device), targets.to(device, non_blocking=True)\n                        outputs = model(inputs)\n                        loss = criterion(outputs, targets)\n                        val_loss += loss.item()\n                        _, predicted = outputs.max(1)\n                        val_total += targets.size(0)\n                        val_correct += predicted.eq(targets).sum().item()\n                        final_val_predictions += list(predicted.cpu().numpy())\n                        final_val_classifications += list(predicted.eq(targets).cpu().numpy())\n  \n                    final_tst_predictions = []\n                    final_tst_classifications = []\n                    for batch_idx, (inputs, targets) in enumerate(tstloader):\n                        inputs, targets = inputs.to(device), targets.to(device, non_blocking=True)\n                        outputs = model(inputs)\n                        loss = criterion(outputs, targets)\n                        tst_loss += loss.item()\n                        _, predicted = outputs.max(1)\n                        tst_total += targets.size(0)\n                        tst_correct += predicted.eq(targets).sum().item()\n                        final_tst_predictions += list(predicted.cpu().numpy())\n                        final_tst_classifications += list(predicted.eq(targets).cpu().numpy())                \n                    best_val_acc = (val_correct/val_total)\n                    val_acc[i] = val_correct / val_total\n                    tst_acc[i] = tst_correct / tst_total\n                    val_losses[i] = val_loss\n                    tst_losses[i] = tst_loss\n                    res_dict[\"test_acc\"].append(tst_acc[i]*100)\n                continue\n        else:\n            #Remove true labels from the unlabeled dataset, the hypothesized labels are computed when select is called\n            unlabeled_lake_set = LabeledToUnlabeledDataset(lake_set)\n            strategy_sel.update_data(train_set, unlabeled_lake_set)\n            #compute the error log before every selection\n            if(computeErrorLog):\n                tst_err_log, val_err_log, val_class_err_idxs = find_err_per_class(test_set, val_set, final_val_classifications, final_val_predictions, final_tst_classifications, final_tst_predictions, all_logs_dir, sf+\"_\"+str(bud))\n                csvlog.append([100-x for x in tst_err_log])\n                val_csvlog.append([100-x for x in val_err_log])\n            ####SIM####\n            if(strategy==\"SIM\" or strategy==\"SF\"):\n                if(sf.endswith(\"mi\")):\n                    if(feature==\"classimb\"):\n                        #make a dataloader for the misclassifications - only for experiments with targets\n                        miscls_set, miscls_set_targets = getQuerySet(val_set, val_class_err_idxs, sel_cls_idx, miscls)\n                        strategy_sel.update_queries(miscls_set)\n            \n            strategy_sel.update_model(model)\n            subset = strategy_sel.select(budget)\n            print(\"#### Selection Complete, Now re-training with augmented subset ####\")\n            if(visualize_tsne):\n                tsne_plt = tsne_smi(strategy_sel.unlabeled_data_embedding.cpu(),\n                                    lake_set.targets,\n                                    strategy_sel.query_embedding.cpu(),\n                                    miscls_set_targets,\n                                    subset)\n                print(\"Computed TSNE plot of the selection\")\n            lake_subset_idxs = subset #indices wrt to lake that need to be removed from the lake\n            perClsSel = getPerClassSel(true_lake_set, lake_subset_idxs, num_cls)\n            res_dict['sel_per_cls'].append(perClsSel)\n            \n            #augment the train_set with selected indices from the lake\n            if(feature==\"classimb\"):\n                train_set, lake_set, true_lake_set, add_val_set = aug_train_subset(train_set, lake_set, true_lake_set, subset, lake_subset_idxs, budget, True) #aug train with random if budget is not filled\n            else:\n                train_set, lake_set, true_lake_set = aug_train_subset(train_set, lake_set, true_lake_set, subset, lake_subset_idxs, budget)\n            print(\"After augmentation, size of train_set: \", len(train_set), \" unlabeled set: \", len(lake_set), \" val set: \", len(val_set))\n    \n#           Reinit train and lake loaders with new splits and reinit the model\n            trainloader = torch.utils.data.DataLoader(train_set, batch_size=trn_batch_size, shuffle=True, pin_memory=True)\n            lakeloader = torch.utils.data.DataLoader(lake_set, batch_size=tst_batch_size, shuffle=False, pin_memory=True)\n            model = create_model(model_name, num_cls, device, strategy_args['embedding_type'])\n            optimizer = optimizer_without_scheduler(model, learning_rate)\n                \n        #Start training\n        start_time = time.time()\n        num_ep=1\n        while(full_trn_acc[i]<0.99 and num_ep<300):\n            model.train()\n            for batch_idx, (inputs, targets) in enumerate(trainloader):\n                inputs, targets = inputs.to(device), targets.to(device, non_blocking=True)\n                # Variables in Pytorch are differentiable.\n                inputs, target = Variable(inputs), Variable(inputs)\n                # This will zero out the gradients for this batch.\n                optimizer.zero_grad()\n                outputs = model(inputs)\n                loss = criterion(outputs, targets)\n                loss.backward()\n                optimizer.step()\n#             scheduler.step()\n          \n            full_trn_loss = 0\n            full_trn_correct = 0\n            full_trn_total = 0\n            model.eval()\n            with torch.no_grad():\n                for batch_idx, (inputs, targets) in enumerate(trainloader): #Compute Train accuracy\n                    inputs, targets = inputs.to(device), targets.to(device, non_blocking=True)\n                    outputs = model(inputs)\n                    loss = criterion(outputs, targets)\n                    full_trn_loss += loss.item()\n                    _, predicted = outputs.max(1)\n                    full_trn_total += targets.size(0)\n                    full_trn_correct += predicted.eq(targets).sum().item()\n                full_trn_acc[i] = full_trn_correct / full_trn_total\n                print(\"Selection Epoch \", i, \" Training epoch [\" , num_ep, \"]\" , \" Training Acc: \", full_trn_acc[i], end=\"\\r\")\n                num_ep+=1\n            timing[i] = time.time() - start_time\n        with torch.no_grad():\n            final_val_predictions = []\n            final_val_classifications = []\n            for batch_idx, (inputs, targets) in enumerate(valloader): #Compute Val accuracy\n                inputs, targets = inputs.to(device), targets.to(device, non_blocking=True)\n                outputs = model(inputs)\n                loss = criterion(outputs, targets)\n                val_loss += loss.item()\n                _, predicted = outputs.max(1)\n                val_total += targets.size(0)\n                val_correct += predicted.eq(targets).sum().item()\n                final_val_predictions += list(predicted.cpu().numpy())\n                final_val_classifications += list(predicted.eq(targets).cpu().numpy())\n\n            final_tst_predictions = []\n            final_tst_classifications = []\n            for batch_idx, (inputs, targets) in enumerate(tstloader): #Compute test accuracy\n                inputs, targets = inputs.to(device), targets.to(device, non_blocking=True)\n                outputs = model(inputs)\n                loss = criterion(outputs, targets)\n                tst_loss += loss.item()\n                _, predicted = outputs.max(1)\n                tst_total += targets.size(0)\n                tst_correct += predicted.eq(targets).sum().item()\n                final_tst_predictions += list(predicted.cpu().numpy())\n                final_tst_classifications += list(predicted.eq(targets).cpu().numpy())                \n            val_acc[i] = val_correct / val_total\n            tst_acc[i] = tst_correct / tst_total\n            val_losses[i] = val_loss\n            fulltrn_losses[i] = full_trn_loss\n            tst_losses[i] = tst_loss\n            full_val_acc = list(np.array(val_acc))\n            full_timing = list(np.array(timing))\n            res_dict[\"test_acc\"].append(tst_acc[i]*100)\n            print('Epoch:', i + 1, 'FullTrn,TrainAcc,ValLoss,ValAcc,TstLoss,TstAcc,Time:', full_trn_loss, full_trn_acc[i], val_loss, val_acc[i], tst_loss, tst_acc[i], timing[i])\n        if(i==0): \n            print(\"Saving initial model\") \n            torch.save(model.state_dict(), initModelPath) #save initial train model if not present\n            \n    #Compute the statistics of the final model\n    if(computeErrorLog):\n        print(\"**** Final Metrics after Targeted Learning ****\")\n        tst_err_log, val_err_log, val_class_err_idxs = find_err_per_class(test_set, val_set, final_val_classifications, final_val_predictions, final_tst_classifications, final_tst_predictions, all_logs_dir, sf+\"_\"+str(bud))\n        csvlog.append([100-x for x in tst_err_log])\n        val_csvlog.append([100-x for x in val_err_log])\n        res_dict[\"all_class_acc\"] = csvlog\n        res_dict[\"all_val_class_acc\"] = val_csvlog\n        \n    #Print overall acc improvement and rare class acc improvement, show that TL selected relevant points in space, is possible show some images\n    print_final_results(res_dict, sel_cls_idx)\n#     tsne_plt.show()\n    \n```\n\n# Submodular Mutual Information (SMI)\n\nWe let $V$ denote the ground-set of $n$ data points $V = \\{1, 2, 3,...,n \\}$ and a set function $f:\n 2^{V} \\xrightarrow{} \\Re$. Given a set of items $A, B \\subseteq V$, the submodular mutual information (MI)[1,3] is defined as $I_f(A; B) = f(A) + f(B) - f(A \\cup B)$. Intuitively, this measures the similarity between $B$ and $A$ and we refer to $B$ as the query set.\n\nIn [2], they extend MI to handle the case when the target can come from an auxiliary set $V^{\\prime}$ different from the ground set $V$. For targeted data subset selection, $V$ is the source set of data instances and the target is a subset of data points (validation set or the specific set of examples of interest).\nLet $\\Omega  = V \\cup V^{\\prime}$. We define a set function $f: 2^{\\Omega} \\rightarrow \\Re$. Although $f$ is defined on $\\Omega$, the discrete optimization problem will only be defined on subsets $A \\subseteq V$. To find an optimal subset given a query set $Q \\subseteq V^{\\prime}$, we can define $g_{Q}(A) = I_f(A; Q)$, $A \\subseteq V$ and maximize the same.\n\n# FL1MI\n\nIn the first variant of FL, we set the unlabeled dataset to be $V$. The SMI instantiation of FL1MI can be defined as:\n\\begin{align}\nI_f(A;Q)=\\sum_{i \\in V}\\min(\\max_{j \\in A}s_{ij}, \\eta \\max_{j \\in Q}sq_{ij})\n\\end{align}\n\nThe first term in the min(.) of FL1MI models diversity, and the second term models query relevance. An increase in the value of $\\eta$ causes the resulting summary to become more relevant to the query.\n\n\n```python\nrun_targeted_selection(data_name, \n               datadir, \n               feature, \n               model_name, \n               budget, \n               split_cfg, \n               learning_rate, \n               run, \n               device, \n               computeClassErrorLog,\n               \"SIM\",'fl1mi')\n```\n\n    Files already downloaded and verified\n    Files already downloaded and verified\n    CIFAR-10 Custom dataset stats: Train size:  8400 Val size:  50 Lake size:  24300\n    Indices of randomly selected classes for imbalance:  [8 1]\n    Initial training epoch\n    Init model loaded from disk, skipping init training:  ./cifar10_ResNet18_0.01_200_1000_2\n    |   Class |   Val Accuracy |   Test Accuracy |\n    |---------+----------------+-----------------|\n    |       0 |             20 |            76.7 |\n    |       1 |              0 |            31.9 |\n    |       2 |             20 |            52   |\n    |       3 |              0 |            49.6 |\n    |       4 |             60 |            68.5 |\n    |       5 |             20 |            54.6 |\n    |       6 |             40 |            75   |\n    |       7 |             40 |            61.6 |\n    |       8 |              0 |            26.1 |\n    |       9 |             20 |            80.4 |\n    total samples from imbalanced classes as targets:  10\n    #### Selection Complete, Now re-training with augmented subset ####\n    After augmentation, size of train_set:  8800  unlabeled set:  23900  val set:  50\n    Epoch: 2 FullTrn,TrainAcc,ValLoss,ValAcc,TstLoss,TstAcc,Time: 9.778989695914788 0.9936363636363637 6.9853388369083405 0.66 175.18406283855438 0.5935 178.13614797592163\n    |   Class |   Val Accuracy |   Test Accuracy |\n    |---------+----------------+-----------------|\n    |       0 |             80 |            71.3 |\n    |       1 |             60 |            42.9 |\n    |       2 |             80 |            65.6 |\n    |       3 |             60 |            48.7 |\n    |       4 |             60 |            56   |\n    |       5 |             40 |            47.3 |\n    |       6 |             80 |            69.5 |\n    |       7 |             20 |            66.2 |\n    |       8 |             80 |            47.7 |\n    |       9 |            100 |            78.3 |\n    [[76.7, 31.900000000000006, 52.0, 49.6, 68.5, 54.6, 75.0, 61.6, 26.099999999999994, 80.4, 57.64], [71.3, 42.9, 65.6, 48.7, 56.0, 47.3, 69.5, 66.2, 47.7, 78.3, 59.35]]\n    Gain in overall test accuracy:  1.7100000000000009\n    Gain in targeted test accuracy:  16.3\n\n\n# FL2MI\n\nIn the V2 variant, we set $D$ to be $V \\cup Q$. The SMI instantiation of FL2MI can be defined as:\n\\begin{align} \\label{eq:FL2MI}\nI_f(A;Q)=\\sum_{i \\in Q} \\max_{j \\in A} sq_{ij} + \\eta\\sum_{i \\in A} \\max_{j \\in Q} sq_{ij}\n\\end{align}\nFL2MI is very intuitive for query relevance as well. It measures the representation of data points that are the most relevant to the query set and vice versa. It can also be thought of as a bidirectional representation score.\n\n\n```python\nrun_targeted_selection(data_name, \n               datadir, \n               feature, \n               model_name, \n               budget, \n               split_cfg, \n               learning_rate, \n               run, \n               device, \n               computeClassErrorLog, \n               \"SIM\",'fl2mi')\n```\n\n    Files already downloaded and verified\n    Files already downloaded and verified\n    CIFAR-10 Custom dataset stats: Train size:  8400 Val size:  50 Lake size:  24300\n    Indices of randomly selected classes for imbalance:  [8 1]\n    Initial training epoch\n    Init model loaded from disk, skipping init training:  ./cifar10_ResNet18_0.01_200_1000_2\n    |   Class |   Val Accuracy |   Test Accuracy |\n    |---------+----------------+-----------------|\n    |       0 |             20 |            76.7 |\n    |       1 |              0 |            31.9 |\n    |       2 |             20 |            52   |\n    |       3 |              0 |            49.6 |\n    |       4 |             60 |            68.5 |\n    |       5 |             20 |            54.6 |\n    |       6 |             40 |            75   |\n    |       7 |             40 |            61.6 |\n    |       8 |              0 |            26.1 |\n    |       9 |             20 |            80.4 |\n    Total samples from imbalanced classes as targets (Size of query set):  10\n    #### Selection Complete, Now re-training with augmented subset ####\n    After augmentation, size of train_set:  8800  unlabeled set:  23900  val set:  50\n    Epoch: 2 FullTrn,TrainAcc,ValLoss,ValAcc,TstLoss,TstAcc,Time: 10.00436659710249 0.9936363636363637 9.651845969259739 0.56 185.48221123218536 0.5941 195.24218201637268\n    **** Final Metrics after Targeted Learning ****\n    |   Class |   Val Accuracy |   Test Accuracy |\n    |---------+----------------+-----------------|\n    |       0 |             60 |            78.9 |\n    |       1 |              0 |            28.2 |\n    |       2 |             80 |            62.7 |\n    |       3 |             40 |            44.2 |\n    |       4 |             20 |            63.1 |\n    |       5 |             60 |            40.1 |\n    |       6 |             60 |            72.8 |\n    |       7 |             60 |            66.8 |\n    |       8 |            100 |            54.8 |\n    |       9 |             80 |            82.5 |\n    Gain in overall test accuracy:  1.769999999999996\n    Gain in targeted test accuracy:  12.5\n\n\n# GCMI\n\nThe SMI instantiation of graph-cut (GCMI) is defined as:\n\\begin{align}\nI_f(A;Q)=2\\sum_{i \\in A} \\sum_{j \\in Q} sq_{ij}\n\\end{align}\nSince maximizing GCMI maximizes the joint pairwise sum with the query set, it will lead to a subset similar to the query set $Q$.\n\n\n```python\nrun_targeted_selection(data_name, \n               datadir, \n               feature, \n               model_name, \n               budget, \n               split_cfg, \n               learning_rate, \n               run, \n               device, \n               computeClassErrorLog,\n               \"SIM\",'gcmi')\n```\n\n    Files already downloaded and verified\n    Files already downloaded and verified\n    CIFAR-10 Custom dataset stats: Train size:  8400 Val size:  50 Lake size:  24300\n    Indices of randomly selected classes for imbalance:  [8 1]\n    Initial training epoch\n    Init model loaded from disk, skipping init training:  ./cifar10_ResNet18_0.01_200_1000_2\n    |   Class |   Val Accuracy |   Test Accuracy |\n    |---------+----------------+-----------------|\n    |       0 |             20 |            76.7 |\n    |       1 |              0 |            31.9 |\n    |       2 |             20 |            52   |\n    |       3 |              0 |            49.6 |\n    |       4 |             60 |            68.5 |\n    |       5 |             20 |            54.6 |\n    |       6 |             40 |            75   |\n    |       7 |             40 |            61.6 |\n    |       8 |              0 |            26.1 |\n    |       9 |             20 |            80.4 |\n    Total samples from imbalanced classes as targets (Size of query set):  10\n    #### Selection Complete, Now re-training with augmented subset ####\n    After augmentation, size of train_set:  8800  unlabeled set:  23900  val set:  50\n    Epoch: 2 FullTrn,TrainAcc,ValLoss,ValAcc,TstLoss,TstAcc,Time: 8.373541493201628 0.9953409090909091 9.280710071325302 0.62 178.8062756061554 0.6014 197.0816731452942\n    **** Final Metrics after Targeted Learning ****\n    |   Class |   Val Accuracy |   Test Accuracy |\n    |---------+----------------+-----------------|\n    |       0 |             60 |            82.2 |\n    |       1 |             40 |            54   |\n    |       2 |             40 |            52.6 |\n    |       3 |             60 |            33   |\n    |       4 |             40 |            55.1 |\n    |       5 |             80 |            59.4 |\n    |       6 |            100 |            75.7 |\n    |       7 |             80 |            77.3 |\n    |       8 |             40 |            40.7 |\n    |       9 |             80 |            71.4 |\n    Gain in overall test accuracy:  2.500000000000007\n    Gain in targeted test accuracy:  18.35\n\n\n# LOGDETMI\n\nThe SMI instantiation of LogDetMI can be defined as:\n\\begin{align}\nI_f(A;Q)=\\log\\det(S_{A}) -\\log\\det(S_{A} - \\eta^2 S_{A,Q}S_{Q}^{-1}S_{A,Q}^T)\n\\end{align}\n$S_{A, B}$ denotes the cross-similarity matrix between the items in sets $A$ and $B$. The similarity matrix in constructed in such a way that the cross-similarity between $A$ and $Q$ is multiplied by $\\eta$ to control the trade-off between query-relevance and diversity.\n\n\n```python\nrun_targeted_selection(data_name, \n               datadir, \n               feature, \n               model_name, \n               budget, \n               split_cfg, \n               learning_rate, \n               run, \n               device, \n               computeClassErrorLog,\n               \"SIM\",'logdetmi')\n```\n\n    Files already downloaded and verified\n    Files already downloaded and verified\n    CIFAR-10 Custom dataset stats: Train size:  8400 Val size:  50 Lake size:  24300\n    Indices of randomly selected classes for imbalance:  [8 1]\n    Initial training epoch\n    Init model loaded from disk, skipping init training:  ./cifar10_ResNet18_0.01_200_1000_2\n    |   Class |   Val Accuracy |   Test Accuracy |\n    |---------+----------------+-----------------|\n    |       0 |             20 |            76.7 |\n    |       1 |              0 |            31.9 |\n    |       2 |             20 |            52   |\n    |       3 |              0 |            49.6 |\n    |       4 |             60 |            68.5 |\n    |       5 |             20 |            54.6 |\n    |       6 |             40 |            75   |\n    |       7 |             40 |            61.6 |\n    |       8 |              0 |            26.1 |\n    |       9 |             20 |            80.4 |\n    Total samples from imbalanced classes as targets (Size of query set):  10\n    #### Selection Complete, Now re-training with augmented subset ####\n    After augmentation, size of train_set:  8800  unlabeled set:  23900  val set:  50\n    Epoch: 2 FullTrn,TrainAcc,ValLoss,ValAcc,TstLoss,TstAcc,Time: 11.645519155834336 0.9927272727272727 7.486996620893478 0.66 164.92539525032043 0.6127 249.82705569267273\n    **** Final Metrics after Targeted Learning ****\n    |   Class |   Val Accuracy |   Test Accuracy |\n    |---------+----------------+-----------------|\n    |       0 |             60 |            72.4 |\n    |       1 |             40 |            56.1 |\n    |       2 |             60 |            48.7 |\n    |       3 |             20 |            48.3 |\n    |       4 |             60 |            61.3 |\n    |       5 |             60 |            53.9 |\n    |       6 |             80 |            75   |\n    |       7 |             80 |            71.2 |\n    |       8 |            100 |            46.9 |\n    |       9 |            100 |            78.9 |\n    Gain in overall test accuracy:  3.6300000000000026\n    Gain in targeted test accuracy:  22.5\n\n\n# Random\n\n\n```python\nrun_targeted_selection(data_name, \n               datadir, \n               feature, \n               model_name, \n               budget, \n               split_cfg, \n               learning_rate, \n               run, \n               device, \n               computeClassErrorLog,\n               \"random\",'random')\n```\n\n    Files already downloaded and verified\n    Files already downloaded and verified\n    CIFAR-10 Custom dataset stats: Train size:  8400 Val size:  50 Lake size:  24300\n    Indices of randomly selected classes for imbalance:  [8 1]\n    Initial training epoch\n    Init model loaded from disk, skipping init training:  ./cifar10_ResNet18_0.01_200_1000_2\n    |   Class |   Val Accuracy |   Test Accuracy |\n    |---------+----------------+-----------------|\n    |       0 |             20 |            76.7 |\n    |       1 |              0 |            31.9 |\n    |       2 |             20 |            52   |\n    |       3 |              0 |            49.6 |\n    |       4 |             60 |            68.5 |\n    |       5 |             20 |            54.6 |\n    |       6 |             40 |            75   |\n    |       7 |             40 |            61.6 |\n    |       8 |              0 |            26.1 |\n    |       9 |             20 |            80.4 |\n    #### Selection Complete, Now re-training with augmented subset ####\n    After augmentation, size of train_set:  8800  unlabeled set:  23900  val set:  50\n    Epoch: 2 FullTrn,TrainAcc,ValLoss,ValAcc,TstLoss,TstAcc,Time: 14.80743219528813 0.9920454545454546 5.834538400173187 0.72 171.24655294418335 0.5876 189.56459832191467\n    **** Final Metrics after Targeted Learning ****\n    |   Class |   Val Accuracy |   Test Accuracy |\n    |---------+----------------+-----------------|\n    |       0 |             80 |            75.4 |\n    |       1 |             40 |            45.7 |\n    |       2 |             80 |            60.2 |\n    |       3 |             60 |            46.9 |\n    |       4 |             60 |            47.9 |\n    |       5 |             60 |            55   |\n    |       6 |             80 |            74   |\n    |       7 |             80 |            65.7 |\n    |       8 |             80 |            34.4 |\n    |       9 |            100 |            82.4 |\n    Gain in overall test accuracy:  1.1199999999999974\n    Gain in targeted test accuracy:  11.050000000000004\n\n\n# References\n[1] Rishabh Iyer, Ninad Khargoankar, Jeff Bilmes, and Himanshu Asnani. Submodular combinatorialinformation measures with applications in machine learning.arXiv preprint arXiv:2006.15412,2020\n\n\n[2] Kaushal V, Kothawade S, Ramakrishnan G, Bilmes J, Iyer R. PRISM: A Unified Framework of Parameterized Submodular Information Measures for Targeted Data Subset Selection and Summarization. arXiv preprint arXiv:2103.00128. 2021 Feb 27.\n\n\n[3] Anupam Gupta and Roie Levin. The online submodular cover problem. InACM-SIAM Symposiumon Discrete Algorithms, 2020\n\n\n```python\n\n```\n", "meta": {"hexsha": "44a1f74b6abc246d66d19e8300d1e3d4f7565b52", "size": 59331, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorials/trust_rare_classes_demo.ipynb", "max_stars_repo_name": "krishnatejakk/trust", "max_stars_repo_head_hexsha": "1b78a562ea570f39615e8ec775d2613d7606df8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-11-05T01:10:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:16:45.000Z", "max_issues_repo_path": "tutorials/trust_rare_classes_demo.ipynb", "max_issues_repo_name": "krishnatejakk/trust", "max_issues_repo_head_hexsha": "1b78a562ea570f39615e8ec775d2613d7606df8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-13T09:16:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-13T09:16:32.000Z", "max_forks_repo_path": "tutorials/trust_rare_classes_demo.ipynb", "max_forks_repo_name": "krishnatejakk/trust", "max_forks_repo_head_hexsha": "1b78a562ea570f39615e8ec775d2613d7606df8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-07-29T16:19:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T22:56:45.000Z", "avg_line_length": 45.8154440154, "max_line_length": 705, "alphanum_fraction": 0.5202845056, "converted": true, "num_tokens": 10253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.04885778225762853, "lm_q1q2_score": 0.02385644380737945}}
{"text": "<a href=\"https://colab.research.google.com/github/ChrizZhuang/marginalized_graph_kernel_protein/blob/main/Docking_0611.ipynb\" target=\"_parent\"></a>\n\n\n```\n!nvidia-smi\n```\n\n    Fri Jun 11 15:11:54 2021       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 465.27       Driver Version: 460.32.03    CUDA Version: 11.2     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   42C    P8     9W /  70W |      0MiB / 15109MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    |  No running processes found                                                 |\n    +-----------------------------------------------------------------------------+\n\n\n\n```\n#!pip install pymatgen==2020.12.31\n!pip install pymatgen==2019.11.11\n!pip install --pre graphdot\n!pip install gdown\n```\n\n    Requirement already satisfied: pymatgen==2019.11.11 in /usr/local/lib/python3.7/dist-packages (2019.11.11)\n    Requirement already satisfied: numpy>=1.14.3 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.19.5)\n    Requirement already satisfied: pydispatcher>=2.0.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.0.5)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.16.1)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.1.5)\n    Requirement already satisfied: scipy>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.4.1)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.5.1)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.23.0)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (0.17.9)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (0.8.9)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (3.3.0)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2021.6.10)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (3.2.2)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.7.1)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen==2019.11.11) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen==2019.11.11) (2018.9)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.2->pymatgen==2019.11.11) (4.4.2)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (1.24.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (2020.12.5)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (2.10)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen==2019.11.11) (0.2.2)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (0.10.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (2.4.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (1.3.1)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->pymatgen==2019.11.11) (1.2.1)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas->pymatgen==2019.11.11) (1.15.0)\n    Requirement already satisfied: graphdot in /usr/local/lib/python3.7/dist-packages (0.8a17)\n    Requirement already satisfied: treelib>=1.6.1 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.6.1)\n    Requirement already satisfied: pycuda>=2019 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2021.1)\n    Requirement already satisfied: tqdm>=4.55 in /usr/local/lib/python3.7/dist-packages (from graphdot) (4.61.0)\n    Requirement already satisfied: ase>=3.17 in /usr/local/lib/python3.7/dist-packages (from graphdot) (3.21.1)\n    Requirement already satisfied: pymatgen==2019.11.11 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2019.11.11)\n    Requirement already satisfied: networkx>=2.4 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2.5.1)\n    Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.19.5)\n    Requirement already satisfied: kahypar>=1.1.4 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.1.6)\n    Requirement already satisfied: numba>=0.51.0 in /usr/local/lib/python3.7/dist-packages (from graphdot) (0.51.2)\n    Requirement already satisfied: scipy>=1.3.0 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.4.1)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.7.1)\n    Requirement already satisfied: mendeleev>=0.7 in /usr/local/lib/python3.7/dist-packages (from graphdot) (0.7.0)\n    Requirement already satisfied: pandas>=0.24 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.1.5)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from treelib>=1.6.1->graphdot) (0.16.0)\n    Requirement already satisfied: mako in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (1.1.4)\n    Requirement already satisfied: pytools>=2011.2 in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (2021.2.7)\n    Requirement already satisfied: appdirs>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (1.4.4)\n    Requirement already satisfied: matplotlib>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from ase>=3.17->graphdot) (3.2.2)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2.23.0)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (3.3.0)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2021.6.10)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (0.17.9)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (0.8.9)\n    Requirement already satisfied: pydispatcher>=2.0.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2.0.5)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (1.16.1)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.4->graphdot) (4.4.2)\n    Requirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba>=0.51.0->graphdot) (0.34.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from numba>=0.51.0->graphdot) (57.0.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->graphdot) (1.2.1)\n    Requirement already satisfied: SQLAlchemy<2.0.0,>=1.3.23 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (1.4.15)\n    Requirement already satisfied: Pygments<3.0.0,>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (2.9.0)\n    Requirement already satisfied: six<2.0.0,>=1.15.0 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (1.15.0)\n    Requirement already satisfied: pyfiglet<0.9,>=0.8.post1 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (0.8.post1)\n    Requirement already satisfied: colorama<0.5.0,>=0.4.4 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (0.4.4)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->graphdot) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->graphdot) (2.8.1)\n    Requirement already satisfied: MarkupSafe>=0.9.2 in /usr/local/lib/python3.7/dist-packages (from mako->pycuda>=2019->graphdot) (2.0.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.0.0->ase>=3.17->graphdot) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.0.0->ase>=3.17->graphdot) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.0.0->ase>=3.17->graphdot) (1.3.1)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (2020.12.5)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (3.0.4)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (2.10)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen==2019.11.11->graphdot) (0.2.2)\n    Requirement already satisfied: greenlet!=0.4.17; python_version >= \"3\" in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (1.1.0)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (4.0.1)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (3.4.1)\n    Requirement already satisfied: typing-extensions>=3.6.4; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (3.7.4.3)\n    Requirement already satisfied: gdown in /usr/local/lib/python3.7/dist-packages (3.6.4)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from gdown) (4.61.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from gdown) (1.15.0)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from gdown) (2.23.0)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (2020.12.5)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (2.10)\n\n\n\n```\n%matplotlib inline\nimport io\nimport sys\nsys.path.append('/usr/local/lib/python3.6/site-packages/')\nimport os\nimport urllib\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport graphdot\nfrom graphdot import Graph\nfrom graphdot.graph.adjacency import AtomicAdjacency\nfrom graphdot.graph.reorder import rcm\nfrom graphdot.kernel.marginalized import MarginalizedGraphKernel # https://graphdot.readthedocs.io/en/latest/apidoc/graphdot.kernel.marginalized.html\nfrom graphdot.kernel.marginalized.starting_probability import Uniform\nfrom graphdot.model.gaussian_process import (\n    GaussianProcessRegressor,\n    LowRankApproximateGPR\n)\nfrom graphdot.kernel.fix import Normalization\nimport graphdot.microkernel as uX\nimport ase.io\n\n# for getting all file names into a list under a directory \nfrom os import listdir\n# for getting file names that match certain pattern\nimport glob\nimport time\n```\n\n    /usr/local/lib/python3.7/dist-packages/graphdot/graph/__init__.py:24: UserWarning: Cannot import RDKit, `graph.from_rdkit()` will be unavailable.\n    \n      'Cannot import RDKit, `graph.from_rdkit()` will be unavailable.\\n'\n\n\n\n```\nfrom google.colab import drive\ndrive.mount('/content/gdrive', force_remount=True)\n```\n\n    Mounted at /content/gdrive\n\n\n\n```\n#cd gdrive/MyDrive/Google\\ Colab/Covid-Data\n%cd gdrive/MyDrive/Covid-Data/\n```\n\n    /content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data\n\n\n\n```\n!pwd\n```\n\n    /content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data\n\n\n\n```\n#!ls\n```\n\n\n```\nfiles  = ['uncharged_NSP15_6W01_A_3_H.Orderable_zinc_db_enaHLL.2col.csv.1.xz']\ndataset = pd.read_pickle(files[0])\n#files  = [f for f in listdir('/content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data')]\n#files = glob.glob(\"uncharged_NSP15_6W01_A_3_H.Orderable_zinc_db_enaHLL.2col.csv.*.xz\")\n#print(files[0:5])\n# concatenate all files into 1 dataset\n#dataset = pd.DataFrame()\n#for i in range(len(files[0:1])):\n#  data = pd.read_pickle(files[i])\n#  print(\"i: \" + str(i) + \" - length of data: \" + str(len(data)))\n#  dataset = pd.concat([dataset, data])\n#frames = [pd.read_pickle(f) for f in files]\n#dataset = pd.concat(frames)\n```\n\n\n```\ntarget = 'energy'\n#N_train = len(dataset)//4\nN_train = 200\n#N_test = 3 * len(dataset)//4\nN_test = 200\nprint(N_train)\nprint(N_test)\n```\n\n    200\n    200\n\n\n\n```\nnp.random.seed(0)\n# select train and test data\ntrain_sel = np.random.choice(len(dataset), N_train, replace=False)\ntest_sel = np.random.choice(np.setxor1d(np.arange(len(dataset)), train_sel), N_test, replace=False)\ntrain_data = dataset.iloc[train_sel]\ntest_data = dataset.iloc[test_sel]\n```\n\n\n```\ntrain_data.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>energy</th>\n      <th>smiles</th>\n      <th>graphs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>3582</th>\n      <td>-2.874773</td>\n      <td>CN(Cc1nc(no1)c2cccc(c2)Br)C(=O)Nc3cccc(c3)OC</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>60498</th>\n      <td>-3.469760</td>\n      <td>CCOC(=O)c1ccc(c(c1)C)NC(=S)NCCOc2ccc(cc2)C</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>53227</th>\n      <td>-0.487984</td>\n      <td>Cc1ccc(cc1S(=O)(=O)Nc2ccccc2OC)NC(=O)c3nc4nc(c...</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>21333</th>\n      <td>-1.808283</td>\n      <td>COc1ccc(cc1OC)CCNC(=O)COc2ccc(cc2)[N@@](Cc3ccc...</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>3885</th>\n      <td>-2.457642</td>\n      <td>Cc1cc(ccc1NCc2ccc(c(c2OC)C)OC)Br</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\n#uX.SquareExponential?\n```\n\n\n```\ngpr = GaussianProcessRegressor(\n    # kernel is the covariance function of the gaussian process (GP)\n    kernel=Normalization( # kernel equals to normalization -> normalizes a kernel using the cosine of angle formula, k_normalized(x,y) = k(x,y)/sqrt(k(x,x)*k(y,y))\n        # graphdot.kernel.fix.Normalization(kernel), set kernel as marginalized graph kernel, which is used to calculate the similarity between 2 graphs\n        # implement the random walk-based graph similarity kernel as Kashima, H., Tsuda, K., & Inokuchi, A. (2003). Marginalized kernels between labeled graphs. ICML\n        MarginalizedGraphKernel( \n            # node_kernel - A kernelet that computes the similarity between individual nodes\n            # uX - graphdot.microkernel - microkernels are positive-semidefinite functions between individual nodes and edges of graphs\n            node_kernel=uX.Additive( # addition of kernal matrices: sum of k_a(X_a, Y_a) cross for a in features\n                # uX.Constant - a kernel that returns a constant value, always mutlipled with other microkernels as an adjustable weight\n                #   c, the first input arg. as 0.5, (0.01, 10) the lower and upper bounds of c that is allowed to vary during hyperpara. optimizartion\n                # uX.KroneckerDelta - a kronecker delta returns 1 when two features are equal and return h (the first input arg here, which is 0.5 in this case) otherwise\n                #   (0.1, 0.9) the lower and upper bounds that h is allowed to vary during hyperpara. optimization\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 2nd element of graphdot.graph.Graph.nodes\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 3rd element of graphdot.graph.Graph.nodes\n                # uX.SquareExponential - Equ. 26 in the paper\n                # input arg. length_sacle is a float32, set as 1 in this case, which correspond to approx. 1 of the kernal value. \n                # This is used to determins how quicklys should the kernel decay to zero.\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0), # the 4th element of graphdot.graph.Graph.nodes\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 5th element of graphdot.graph.Graph.nodes\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0), # the 6th element of graphdot.graph.Graph.nodes\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 7th element of graphdot.graph.Graph.nodes\n                # uX.Convolution - a convolutional microkernel which averages evaluations of a base microkernel between pairs pf elememts of two variable-length feature sequences\n                # uX.KroneckerDelta as the base kernel\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9))) # the 8th element of graphdot.graph.Graph.nodes\n            ).normalized,\n            # edge_kernel - A kernelet that computes the similarity between individual edge\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 3rd element of graphdot.graph.Graph.nodes\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 4th element of graphdot.graph.Graph.nodes\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 5th element of graphdot.graph.Graph.nodes\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 6th element of graphdot.graph.Graph.nodes\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)) # the 7th element of graphdot.graph.Graph.nodes\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'), # the strating probability of the random walk on each node\n            q=0.05 # the probability for the random walk to stop during each step\n        )\n    ),\n    alpha=1e-4, # value added to the diagonal of the kernel matrix during fitting\n    optimizer=True, # default optimizer of L-BFGS-B based on scipy.optimize.minimize\n    normalize_y=True, # normalize the y values so taht the means and variance is 0 and 1, repsectively. Will be reversed when predicions are returned\n    regularization='+', # alpha (1e-4 in this case) is added to the diagonals of the kernal matrix\n)\n```\n\n\n```\ndef train_pipeline_batch(model, train_dataset, test_dataset, target, repeat, batch_number = 10, verbose = True):\n  start_time = time.time()\n  batch_size = len(train_dataset) // batch_number\n\n  for i in range(batch_number):\n    if i <= 1:\n      train = train_dataset[i*batch_size : (i+1)*batch_size]\n      start_time_i = time.time()\n      model.fit(train.graphs, train[target], repeat=repeat, verbose=verbose)\n      mu = gpr.predict(train.graphs)\n      print('Training set')\n      print('MAE:', np.mean(np.abs(train[target] - mu)))\n      print('RMSE:', np.std(train[target] - mu))\n      mu_test = gpr.predict(test_dataset.graphs)\n      print('Test set')\n      print('MAE:', np.mean(np.abs(test_dataset[target] - mu_test)))\n      print('RMSE:', np.std(test_dataset[target] - mu_test))\n      end_time_i = time.time()\n      print(\"the time consumption for batch \" + str(i) + \" is \" + str(end_time_i - start_time_i) + \".\")\n  \n  end_time = time.time()\n  print(\"the total time consumption is \" + str(end_time - start_time) + \".\")\n```\n\n\n```\ndef train_pipeline(model, train_dataset, test_dataset, target, repeat, batch_number = 10, verbose = True):\n  start_time = time.time()\n\n  model.fit(train_dataset.graphs, train_dataset[target], repeat=repeat, verbose=verbose)\n  mu = gpr.predict(train_dataset.graphs)\n  print('Training set')\n  print('MAE:', np.mean(np.abs(train_dataset[target] - mu)))\n  print('RMSE:', np.std(train_dataset[target] - mu))\n  mu_test = gpr.predict(test_dataset.graphs)\n  print('Test set')\n  print('MAE:', np.mean(np.abs(test_dataset[target] - mu_test)))\n  print('RMSE:', np.std(test_dataset[target] - mu_test))\n  \n  end_time = time.time()\n  print(\"the total time consumption is \" + str(end_time - start_time) + \".\")\n```\n\n\n```\n#gpr.fit(train.graphs, train[target], repeat=3, verbose=True)\n# using the molecular graph to predict the energy\n#start_time = time.time()\n#gpr.fit(train.graphs, train[target], repeat=5, verbose=True)\n#end_time = time.time()\n#print(\"the total time consumption is \" + str(end_time - start_time) + \".\")\ntrain_pipeline(gpr, train_data, test_data, target, repeat=1)\ngpr.save(path=\"/content\", filename='train_1.pkl')\ngpr.load(path=\"/content\", filename='train_1.pkl')\ntrain_pipeline(gpr, train_data, test_data, target, repeat=1)\ngpr.save(path=\"/content\", filename='train_2.pkl')\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |       33877|    3.33e+05|       34675|     -798.22|  3.0574e+05|      0.94|     0.017|\n    |       34729|  3.4854e+05|       35529|     -800.42|  3.1158e+05|      0.73|     0.013|\n    |       33878|  3.3308e+05|       34677|      -798.2|  3.0575e+05|      0.74|     0.012|\n    |       33877|    3.33e+05|       34675|     -798.22|  3.0581e+05|       0.7|     0.012|\n    |       33878|    3.33e+05|       34676|     -798.22|  3.0584e+05|      0.74|    0.0069|\n    |       33877|  3.3299e+05|       34675|     -798.22|  3.0577e+05|       0.7|     0.013|\n    |       33876|  3.3297e+05|       34674|     -798.22|  3.0577e+05|      0.71|    0.0068|\n    |       33875|  3.3295e+05|       34674|     -798.22|   3.058e+05|       0.7|     0.007|\n    |       33877|    3.33e+05|       34676|     -798.22|  3.0576e+05|       0.7|     0.007|\n    |       33878|  3.3301e+05|       34676|     -798.22|  3.0571e+05|       0.7|     0.011|\n    Optimization result:\n          fun: 33877.767793188395\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 3.32736269e+01,  1.01181247e+01,  2.11640484e+00,  1.40761837e+01,\n            1.07565959e+03,  2.23105595e+01,  0.00000000e+00,  1.81064581e+01,\n            8.41056953e-01, -7.47117442e+01,  0.00000000e+00,  8.82671356e+00,\n            2.09253886e+00,  1.27173962e+00,  7.19717707e+02,  1.15798556e+01,\n            1.81534335e+02, -5.85837646e+00,  1.84098217e+02, -9.53752556e+00,\n            2.51176366e+00,  1.94963505e+00,  0.00000000e+00,  1.86638215e+00,\n            6.06919566e-02])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 10\n          nit: 1\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -1.91117256,  1.46915661, -2.30258509,\n           -4.60517019,  0.        , -4.60517019, -1.79164389,  2.30258509,\n           -2.93293909, -4.60517019, -2.00735516,  1.06605602, -2.30258509,\n            2.25156611, -2.30258509,  2.25493452, -2.30258509, -2.61786614,\n           -2.2851281 , -4.48663165, -0.22314355, -4.42455148, -1.4882493 ])\n    Training set\n    MAE: 0.028720306073408267\n    RMSE: 0.042411678487393495\n    Test set\n    MAE: 1.6479918805831582\n    RMSE: 1.9823461820124986\n    the total time consumption is 10.234806060791016.\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |       33877|  3.3298e+05|       34675|     -798.22|  3.0573e+05|      0.84|     0.012|\n    |       34725|  3.4858e+05|       35525|     -800.22|  3.1159e+05|      0.74|     0.012|\n    |       33876|  3.3302e+05|       34674|      -798.2|  3.0581e+05|      0.73|     0.012|\n    Optimization result:\n          fun: 33876.26172766554\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 3.32746153e+01,  1.01359973e+01,  2.12186967e+00, -1.52048779e+01,\n            1.07488084e+03,  2.23665697e+01,  0.00000000e+00,  1.81578559e+01,\n            8.41303113e-01, -4.66801773e+01,  0.00000000e+00,  8.84762532e+00,\n            2.09712637e+00,  2.28241286e+00,  7.20498210e+02,  5.90183936e+00,\n            1.81585484e+02,  2.00227793e-02,  1.84179698e+02, -9.73983688e+00,\n            2.54755828e+00,  1.95692913e+00,  0.00000000e+00,  1.87311321e+00,\n            6.09392663e-02])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 3\n          nit: 1\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -1.91157618,  1.46289276, -2.30258509,\n           -4.60517019,  0.        , -4.60517019, -1.79217078,  2.30258509,\n           -2.93293909, -4.60517019, -2.0076596 ,  1.06481976, -2.30258509,\n            2.24449543, -2.30258509,  2.25498365, -2.30258509, -2.61279217,\n           -2.2851461 , -4.48675389, -0.22314355, -4.42473773, -1.48831184])\n    Training set\n    MAE: 0.028702980503987337\n    RMSE: 0.04237352276507943\n    Test set\n    MAE: 1.6476773867278036\n    RMSE: 1.981928579979879\n    the total time consumption is 5.015089988708496.\n\n\n\n```\ngpr.load(path=\"/content\", filename='train_2.pkl')\ntrain_pipeline(gpr, train_data, test_data, target, repeat=3)\ngpr.save(path=\"/content\", filename='train_3.pkl')\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |       33877|  3.3305e+05|       34676|      -798.2|  3.0576e+05|      0.93|     0.012|\n    |       34211|  3.3883e+05|       35016|     -805.28|  3.0971e+05|      0.71|     0.025|\n    |       33879|  3.3311e+05|       34677|     -798.29|  3.0584e+05|      0.69|    0.0078|\n    |       33875|  3.3301e+05|       34673|      -798.2|  3.0583e+05|       0.7|    0.0065|\n    |       33876|  3.3302e+05|       34674|      -798.2|  3.0585e+05|      0.69|    0.0065|\n    |       33878|  3.3307e+05|       34676|      -798.2|  3.0584e+05|      0.69|    0.0068|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |       40944|  4.5338e+05|       41762|     -818.05|  3.4921e+05|      0.76|    0.0066|\n    |       37588|  3.9609e+05|       38394|     -806.57|  3.2833e+05|      0.74|     0.007|\n    |       34551|  3.4423e+05|       35354|     -802.83|   3.126e+05|      0.69|     0.013|\n    |       34239|  3.3838e+05|       35041|      -801.6|  3.0925e+05|      0.69|     0.013|\n    |       33989|  3.3448e+05|       34789|     -799.97|    3.07e+05|      0.74|     0.013|\n    |       33971|  3.3443e+05|       34770|     -798.79|  3.0675e+05|       0.7|     0.013|\n    |       33967|  3.3437e+05|       34765|     -798.58|  3.0666e+05|      0.74|     0.013|\n    |       33952|  3.3419e+05|       34750|     -797.88|  3.0626e+05|      0.71|     0.013|\n    |       33931|  3.3393e+05|       34728|      -797.3|  3.0587e+05|      0.73|    0.0073|\n    |       33886|  3.3314e+05|       34683|     -797.01|  3.0555e+05|       0.7|    0.0075|\n    |       33852|  3.3275e+05|       34650|     -797.49|   3.058e+05|      0.71|     0.012|\n    |       33825|  3.3185e+05|       34624|      -798.7|  3.0659e+05|      0.69|    0.0075|\n    |       33814|  3.3126e+05|       34613|     -798.66|  3.0649e+05|       0.7|     0.012|\n    |       33796|  3.2967e+05|       34594|     -798.46|  3.0652e+05|      0.72|     0.013|\n    |       33793|  3.2918e+05|       34592|     -798.34|  3.0677e+05|      0.74|     0.013|\n    |       33792|  3.2943e+05|       34590|     -798.22|  3.0684e+05|      0.75|     0.013|\n    |       33790|  3.2938e+05|       34589|     -798.21|  3.0686e+05|      0.74|     0.013|\n    |       33791|  3.2942e+05|       34589|     -798.19|  3.0694e+05|       0.7|    0.0077|\n    |       33790|  3.2938e+05|       34589|     -798.21|  3.0691e+05|      0.74|    0.0076|\n    |       33792|  3.2942e+05|       34590|      -798.2|  3.0681e+05|      0.71|    0.0078|\n    |       33792|  3.2942e+05|       34591|     -798.21|  3.0679e+05|       0.7|     0.013|\n    |       33793|  3.2944e+05|       34591|     -798.21|   3.069e+05|      0.74|     0.012|\n    |       33790|  3.2938e+05|       34589|     -798.21|  3.0683e+05|      0.73|     0.012|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |       38244|  3.8449e+05|       39087|      -842.5|  3.3585e+05|      0.74|     0.014|\n    |       35028|  3.4399e+05|       35845|     -817.58|  3.1603e+05|      0.76|     0.013|\n    |       34155|  3.3385e+05|       34960|     -804.81|   3.093e+05|      0.71|    0.0092|\n    |       33975|  3.3408e+05|       34772|     -796.76|  3.0561e+05|       0.7|     0.013|\n    |       33921|  3.3272e+05|       34719|     -798.64|  3.0624e+05|      0.73|     0.013|\n    |       33906|  3.3274e+05|       34705|     -798.81|  3.0632e+05|      0.73|     0.012|\n    |       33895|  3.3296e+05|       34693|     -798.49|  3.0633e+05|      0.71|     0.013|\n    |       33887|  3.3325e+05|       34685|     -798.04|  3.0603e+05|      0.74|    0.0073|\n    |       33880|  3.3406e+05|       34677|     -796.94|  3.0566e+05|      0.72|    0.0077|\n    |       33873|  3.3358e+05|       34670|     -797.38|   3.058e+05|      0.73|    0.0075|\n    |       33865|  3.3301e+05|       34663|     -797.81|  3.0594e+05|      0.72|    0.0081|\n    |       33859|   3.324e+05|       34657|     -798.15|  3.0592e+05|       0.7|    0.0081|\n    |       33849|  3.3145e+05|       34647|     -798.41|   3.059e+05|      0.71|    0.0079|\n    |       33840|  3.3106e+05|       34638|     -798.36|    3.06e+05|      0.71|    0.0077|\n    |       33827|  3.3027e+05|       34625|     -798.31|  3.0606e+05|      0.71|     0.008|\n    |       33808|  3.2947e+05|       34607|     -798.17|  3.0646e+05|       0.7|    0.0074|\n    |       33798|  3.2971e+05|       34596|     -798.34|  3.0673e+05|       0.7|     0.013|\n    |       33797|  3.2975e+05|       34595|        -798|  3.0687e+05|      0.74|    0.0077|\n    |       33798|  3.2975e+05|       34597|     -798.18|  3.0683e+05|       0.7|    0.0075|\n    |       33799|  3.2979e+05|       34597|     -798.02|  3.0677e+05|       0.7|     0.016|\n    |       33798|  3.2977e+05|       34596|        -798|  3.0684e+05|       0.7|     0.008|\n    Optimization result:\n          fun: 33790.48250987352\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 3.29104224e+01,  1.00330454e+01,  1.44760597e+00, -1.27833145e+01,\n            1.07029851e+03,  2.30596942e+01,  0.00000000e+00,  1.84121365e+01,\n            5.16377483e-01, -4.47604474e+01,  3.04947833e-14,  1.12792596e+01,\n            2.49632022e+00, -5.26100869e+00,  7.23890988e+02, -6.45872633e-01,\n            1.38342400e+02, -1.25837389e+01,  1.83140568e+02,  4.02560801e+00,\n            3.77756602e+01,  4.87490238e+00,  0.00000000e+00,  4.33716373e+00,\n            1.10884987e-01])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 23\n          nit: 17\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -2.30258509,  1.42829726, -2.30258509,\n           -4.60517019, -0.05074297, -4.60517019, -2.30258509,  2.30258509,\n           -2.25598876, -4.60517019, -1.74389088,  1.03774342, -2.30258509,\n            1.00767327, -2.30258509,  1.28096557, -2.30258509, -0.2782093 ,\n           -2.30258509, -4.53468472, -0.10536052, -4.59218117, -1.22163041])\n    Training set\n    MAE: 0.028606346973146398\n    RMSE: 0.042543977772967555\n    Test set\n    MAE: 1.6329866898863503\n    RMSE: 1.9750979327415905\n    the total time consumption is 40.392122983932495.\n\n\n\n```\ngpr.kernel.hyperparameters\n```\n\n\n\n\n    starting_probability : Uniform\n    \tp : 1.0\n    stopping_probability : 0.00010000000000000009\n    node_kernel : Composite\n    \taromatic : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.02343420535068002\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.18860200789175988\n    \tatomic_number : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 5.400776905055444\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tcharge : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.0145590563621646\n    \t\trhs : SquareExponential\n    \t\t\tlength_scale : 1.0\n    \tchiral : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.05149063984443944\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.12853164901299938\n    \thcount : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 10.000000000000002\n    \t\trhs : SquareExponential\n    \t\t\tlength_scale : 0.07795674396128768\n    \thybridization : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.02783411902444354\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.17414808329497075\n    \tring_list : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 6.550981640628747\n    \t\trhs : Convolution\n    \t\t\tbase : KroneckerDelta\n    \t\t\t\th : 0.10000000000000002\n    edge_kernel : Composite\n    \taromatic : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 2.331300736214766\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tconjugated : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 3.166641607522053\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \torder : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.05549109210250382\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.25478481015091287\n    \tring_stereo : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.033323606027544916\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.8\n    \tstereo : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.1324351226762118\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.14521546104851712\n\n\n\n\n```\nmu = gpr.predict(train.graphs)\n```\n\n\n```\nplt.scatter(train[target], mu)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.2074369392067814\n    RMSE: 0.3195501910711287\n\n\n\n```\nmu_test = gpr.predict(test.graphs)\n```\n\n\n```\nplt.scatter(test[target], mu_test)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 1.2461703788060545\n    RMSE: 1.6040210737240486\n\n\nWork\u0001on the kernel. Find a kernel that trains and predicts well.\n\n\n```\ngpr2 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-2, #different from gpr in alpha where gpr's alpha is 1e-4\n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\n#gpr2.fit(train.graphs, train[target], repeat=3, verbose=True)\ngpr2.fit(train.graphs, train[target], repeat=1, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |   1.667e+05|   1.928e+05|  1.7773e+05|      -11034|  2.2742e+05|   1.3e+02|       1.7|\n    |  1.5585e+05|  2.2171e+05|  1.6671e+05|      -10857|  2.2218e+05|   1.3e+02|       1.7|\n    |  1.3711e+05|  2.4873e+05|  1.4756e+05|      -10447|  2.0803e+05|   1.2e+02|       1.8|\n    |  1.3286e+05|  2.3627e+05|   1.432e+05|      -10338|  2.0336e+05|   1.1e+02|       1.7|\n    |  1.2977e+05|  2.2744e+05|  1.4002e+05|      -10249|  1.9714e+05|   1.1e+02|       1.7|\n    |  1.3006e+05|  2.1429e+05|  1.4032e+05|      -10258|  2.0119e+05|     1e+02|       1.7|\n    |  1.2923e+05|  2.2103e+05|  1.3946e+05|      -10238|  1.9906e+05|   1.1e+02|       1.7|\n    |  1.2888e+05|  2.2097e+05|  1.3911e+05|      -10228|  1.9865e+05|   1.1e+02|       1.7|\n    |  1.2843e+05|  2.2338e+05|  1.3864e+05|      -10211|  1.9582e+05|   1.1e+02|       1.7|\n    |  1.2837e+05|  2.2244e+05|  1.3858e+05|      -10212|   1.969e+05|   1.1e+02|       1.7|\n    |  1.2836e+05|  2.2225e+05|  1.3857e+05|      -10212|  1.9696e+05|   1.1e+02|       1.7|\n    |  1.2831e+05|  2.2155e+05|  1.3852e+05|      -10211|  1.9715e+05|   1.1e+02|       1.7|\n    |  1.2826e+05|  2.2184e+05|  1.3847e+05|      -10209|  1.9704e+05|   1.1e+02|       1.7|\n    |  1.2821e+05|  2.2181e+05|  1.3841e+05|      -10207|  1.9671e+05|   1.1e+02|       1.7|\n    |  1.2819e+05|  2.2165e+05|   1.384e+05|      -10207|  1.9664e+05|   1.1e+02|       1.8|\n    |  1.2818e+05|  2.2125e+05|  1.3838e+05|      -10207|  1.9671e+05|   1.1e+02|       1.8|\n    |  1.2817e+05|  2.2114e+05|  1.3838e+05|      -10207|  1.9673e+05|   1.1e+02|       1.7|\n    |  1.2815e+05|  2.2077e+05|  1.3836e+05|      -10207|  1.9677e+05|   1.1e+02|       1.7|\n    |  1.2812e+05|   2.185e+05|  1.3833e+05|      -10209|  1.9695e+05|   1.1e+02|       1.7|\n    |  1.2809e+05|   2.178e+05|   1.383e+05|      -10209|    1.97e+05|   1.1e+02|       1.7|\n    |  1.2807e+05|  2.1764e+05|  1.3828e+05|      -10208|  1.9695e+05|   1.1e+02|       1.7|\n    |  1.2805e+05|  2.1597e+05|  1.3826e+05|      -10209|  1.9693e+05|   1.1e+02|       1.7|\n    |  1.2805e+05|   2.172e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1693e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.8|\n    |  1.2804e+05|  2.1674e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1691e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2805e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.8|\n    |  1.2805e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    Optimization result:\n          fun: 128045.20193517115\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 21.67035135,   5.42797631,   0.91584794,   6.62684845,\n           636.88297304,  10.22203408,   0.        ,   6.13155297,\n             0.80318432, -45.79780911,   0.        ,   9.32446636,\n             2.06137402,   7.94609186, 767.483899  ,  -8.19180354,\n            92.93654292,   7.92503084, 118.62629465,   3.36719643,\n            38.71995733,   7.96834618,   0.        , -11.08475724,\n             7.2860016 ])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 31\n          nit: 21\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.51710969, -1.98267626,  1.72521606, -2.30258509,\n           -4.60517019,  0.        , -4.60517019, -1.8070945 ,  2.30258509,\n           -2.88031384, -3.6019383 , -2.30258509,  1.91177723, -2.30258509,\n            0.28746812, -2.30258509,  0.54884256, -2.30258509, -0.5686784 ,\n           -2.30258509, -4.35637808, -0.22314355, -2.55717239, -2.21179129])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7f6bf00630d0>\n\n\n\n\n```\nmu = gpr2.predict(train.graphs)\nplt.scatter(train[target], mu)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.7238389142657052\n    RMSE: 0.9634943206325994\n\n\n\n```\nmu_test = gpr2.predict(test.graphs)\nplt.scatter(test[target], mu_test)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 0.9561539409612109\n    RMSE: 1.2284268143181998\n\n", "meta": {"hexsha": "703ad90fe3712a4dee1b4bc530fd38327d767bbc", "size": 121075, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Docking_0611.ipynb", "max_stars_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_stars_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Docking_0611.ipynb", "max_issues_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_issues_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Docking_0611.ipynb", "max_forks_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_forks_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 93.7838884586, "max_line_length": 16574, "alphanum_fraction": 0.7003510221, "converted": true, "num_tokens": 17140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.04958902719777796, "lm_q1q2_score": 0.023826470233670065}}
{"text": "```python\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n```\n\n# Reading Data and Preprocessing\n\n\n```python\ndata = pd.read_csv('agaricus-lepiota-subset.csv') # reading data\n```\n\n\n```python\ndata.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>p</th>\n      <th>k</th>\n      <th>y</th>\n      <th>e</th>\n      <th>f</th>\n      <th>s</th>\n      <th>f.1</th>\n      <th>c</th>\n      <th>n</th>\n      <th>b</th>\n      <th>...</th>\n      <th>k.1</th>\n      <th>p.1</th>\n      <th>w</th>\n      <th>p.2</th>\n      <th>w.1</th>\n      <th>o</th>\n      <th>e.1</th>\n      <th>w.2</th>\n      <th>v</th>\n      <th>p.3</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>e</td>\n      <td>k</td>\n      <td>s</td>\n      <td>n</td>\n      <td>f</td>\n      <td>n</td>\n      <td>a</td>\n      <td>c</td>\n      <td>b</td>\n      <td>y</td>\n      <td>...</td>\n      <td>s</td>\n      <td>o</td>\n      <td>o</td>\n      <td>p</td>\n      <td>n</td>\n      <td>o</td>\n      <td>p</td>\n      <td>o</td>\n      <td>v</td>\n      <td>l</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>p</td>\n      <td>k</td>\n      <td>s</td>\n      <td>e</td>\n      <td>f</td>\n      <td>f</td>\n      <td>f</td>\n      <td>c</td>\n      <td>n</td>\n      <td>b</td>\n      <td>...</td>\n      <td>s</td>\n      <td>w</td>\n      <td>w</td>\n      <td>p</td>\n      <td>w</td>\n      <td>o</td>\n      <td>e</td>\n      <td>w</td>\n      <td>v</td>\n      <td>d</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>p</td>\n      <td>k</td>\n      <td>y</td>\n      <td>c</td>\n      <td>f</td>\n      <td>m</td>\n      <td>a</td>\n      <td>c</td>\n      <td>b</td>\n      <td>y</td>\n      <td>...</td>\n      <td>y</td>\n      <td>c</td>\n      <td>c</td>\n      <td>p</td>\n      <td>w</td>\n      <td>n</td>\n      <td>n</td>\n      <td>w</td>\n      <td>c</td>\n      <td>d</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>p</td>\n      <td>k</td>\n      <td>s</td>\n      <td>n</td>\n      <td>f</td>\n      <td>y</td>\n      <td>f</td>\n      <td>c</td>\n      <td>n</td>\n      <td>b</td>\n      <td>...</td>\n      <td>s</td>\n      <td>p</td>\n      <td>p</td>\n      <td>p</td>\n      <td>w</td>\n      <td>o</td>\n      <td>e</td>\n      <td>w</td>\n      <td>v</td>\n      <td>d</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>e</td>\n      <td>x</td>\n      <td>s</td>\n      <td>g</td>\n      <td>f</td>\n      <td>n</td>\n      <td>f</td>\n      <td>w</td>\n      <td>b</td>\n      <td>g</td>\n      <td>...</td>\n      <td>k</td>\n      <td>w</td>\n      <td>w</td>\n      <td>p</td>\n      <td>w</td>\n      <td>t</td>\n      <td>p</td>\n      <td>w</td>\n      <td>n</td>\n      <td>g</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 23 columns</p>\n</div>\n\n\n\n\n```python\nprint(data.columns)\n```\n\n    Index(['p', 'k', 'y', 'e', 'f', 's', 'f.1', 'c', 'n', 'b', 't', '?', 's.1',\n           'k.1', 'p.1', 'w', 'p.2', 'w.1', 'o', 'e.1', 'w.2', 'v', 'p.3'],\n          dtype='object')\n\n\n\n```python\ndata = data.reindex(np.random.permutation(data.index)) # shuffling the data\n\ny = data['p'].to_numpy() # labels from dataframe to numpy array\nx = data.drop(columns='p').to_numpy() # data from dataframe to numpy array\n```\n\n\n```python\n# replacing 'p' with '1' and 'e' with '0'\ny = np.where(y=='p', '1', y)\ny = np.where(y=='e', '0', y)\n```\n\n\n```python\ny\n```\n\n\n\n\n    array(['1', '0', '1', '0', '1', '1', '1', '0', '0', '1', '0', '0', '0',\n           '1', '0', '0', '1', '1', '1', '0', '1', '1', '1', '0', '1', '0',\n           '0', '1', '0', '1', '0', '0', '0', '0', '0', '0', '0', '1', '1',\n           '0', '0', '0', '0', '1', '1', '1', '1', '1', '0', '0', '0', '1',\n           '0', '1', '1', '1', '1', '0', '1', '1', '1', '0', '1', '0', '1',\n           '1', '1', '1', '0', '0', '0', '0', '1', '0', '1', '0', '0', '1',\n           '0', '1', '0', '0', '0', '0', '1', '0', '1', '1', '1', '1', '0',\n           '0', '1', '0', '0', '0', '0', '1', '0', '1', '0', '1', '0', '1',\n           '0', '0', '0', '0', '1', '0', '1', '0', '0', '0', '0', '1', '1',\n           '1', '1', '1', '0', '0', '1', '1', '0', '0', '0', '0', '1', '0',\n           '0', '0', '1', '1', '0', '1', '1', '0', '0', '0', '1', '0', '0',\n           '1', '1'], dtype=object)\n\n\n\n\n```python\n# Data is fairly balanced\n\nfig = plt.figure()\nax = fig.add_axes([0,0,1,1])\nlabels = ['p', 'e']\nnum = [(y == '1').sum(), (y == '0').sum()]\nax.bar(labels,num)\nplt.show()\n```\n\n\n```python\nprint(x.shape)\nprint(y.shape)\n```\n\n    (145, 22)\n    (145,)\n\n\n\n```python\n# computing different possible outcomes for every feature\noutcomes = []\nfor i in range(22):\n    outcomes.append(list(set(x[...,i])))\n```\n\n\n```python\noutcomes\n```\n\n\n\n\n    [['k', 'b', 'x', 'f'],\n     ['s', 'f', 'y'],\n     ['g', 'c', 'e', 'w', 'n'],\n     ['t', 'f'],\n     ['f', 'y', 's', 'm', 'n'],\n     ['a', 'f'],\n     ['w', 'c'],\n     ['b', 'n'],\n     ['g', 'o', 'y', 'p', 'w', 'b', 'n'],\n     ['t', 'e'],\n     ['b', '?', 'c'],\n     ['s', 'k', 'y'],\n     ['s', 'k', 'y'],\n     ['o', 'c', 'p', 'w', 'n'],\n     ['o', 'c', 'p', 'w', 'n'],\n     ['p'],\n     ['w', 'o', 'n'],\n     ['t', 'o', 'n'],\n     ['n', 'e', 'p'],\n     ['o', 'y', 'w', 'b', 'n'],\n     ['c', 'y', 's', 'v', 'n'],\n     ['d', 'l', 'g', 'p']]\n\n\n\n# Support and Confidence\n\n\n```python\npossible_outcomes = []\nfor i in data.columns:\n    for j in set(data[i]):\n        possible_outcomes.append((i,j))\n```\n\n\n```python\nsupport = [] # list of support\neconf = [] # list of confidence for features and e output\npconf = [] # list of confidence for features and p output\nrule = [] # list of rules based on the confidence of the outcome\nfor feat, out in possible_outcomes:\n    v = np.array(data[feat])\n    sup = (v==out).sum()\n    support.append(sup)\n    e_conf = (np.dot((y=='0').astype(int), (v==out).astype(int)))/sup\n    p_conf = (np.dot((y=='1').astype(int), (v==out).astype(int)))/sup\n    econf.append(e_conf)\n    pconf.append(p_conf)\n```\n\n\n```python\ndf = pd.DataFrame([support, econf, pconf], columns=possible_outcomes)\ndf.columns = pd.MultiIndex.from_tuples(df.columns, names=['feature', 'outcomes'])\n```\n\n\n```python\n# first row is support, second row is 'e' confidence, third row is 'p' confidence\ndf\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th>feature</th>\n      <th colspan=\"2\" halign=\"left\">p</th>\n      <th colspan=\"4\" halign=\"left\">k</th>\n      <th colspan=\"3\" halign=\"left\">y</th>\n      <th>e</th>\n      <th>...</th>\n      <th>w.2</th>\n      <th colspan=\"5\" halign=\"left\">v</th>\n      <th colspan=\"4\" halign=\"left\">p.3</th>\n    </tr>\n    <tr>\n      <th>outcomes</th>\n      <th>e</th>\n      <th>p</th>\n      <th>k</th>\n      <th>b</th>\n      <th>x</th>\n      <th>f</th>\n      <th>s</th>\n      <th>f</th>\n      <th>y</th>\n      <th>g</th>\n      <th>...</th>\n      <th>n</th>\n      <th>y</th>\n      <th>s</th>\n      <th>c</th>\n      <th>v</th>\n      <th>n</th>\n      <th>d</th>\n      <th>l</th>\n      <th>g</th>\n      <th>p</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>78.000000</td>\n      <td>67.000000</td>\n      <td>83.000000</td>\n      <td>19.000000</td>\n      <td>25.00</td>\n      <td>18.0</td>\n      <td>91.000000</td>\n      <td>16.0000</td>\n      <td>38.000000</td>\n      <td>12.000000</td>\n      <td>...</td>\n      <td>12.000000</td>\n      <td>4.00</td>\n      <td>13.000000</td>\n      <td>22.000000</td>\n      <td>94.000000</td>\n      <td>12.000000</td>\n      <td>25.00</td>\n      <td>69.000000</td>\n      <td>25.00</td>\n      <td>26.000000</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.512821</td>\n      <td>0.567164</td>\n      <td>0.566265</td>\n      <td>0.473684</td>\n      <td>0.52</td>\n      <td>0.5</td>\n      <td>0.527473</td>\n      <td>0.5625</td>\n      <td>0.552632</td>\n      <td>0.583333</td>\n      <td>...</td>\n      <td>0.583333</td>\n      <td>0.25</td>\n      <td>0.692308</td>\n      <td>0.272727</td>\n      <td>0.606383</td>\n      <td>0.416667</td>\n      <td>0.56</td>\n      <td>0.550725</td>\n      <td>0.56</td>\n      <td>0.461538</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.487179</td>\n      <td>0.432836</td>\n      <td>0.433735</td>\n      <td>0.526316</td>\n      <td>0.48</td>\n      <td>0.5</td>\n      <td>0.472527</td>\n      <td>0.4375</td>\n      <td>0.447368</td>\n      <td>0.416667</td>\n      <td>...</td>\n      <td>0.416667</td>\n      <td>0.75</td>\n      <td>0.307692</td>\n      <td>0.727273</td>\n      <td>0.393617</td>\n      <td>0.583333</td>\n      <td>0.44</td>\n      <td>0.449275</td>\n      <td>0.44</td>\n      <td>0.538462</td>\n    </tr>\n  </tbody>\n</table>\n<p>3 rows \u00d7 79 columns</p>\n</div>\n\n\n\n# Functions\n\n\n```python\ndef split(k, x, y):\n    # in this function, I am construction the data fold and also splitting the data into train and test sets\n    \n    # k: number of folds\n    # x: input\n    # y: output\n    \n    x_train = []\n    y_train = []\n    x_test = []\n    y_test = []\n    l = math.ceil(x.shape[0]/k) # len of each fold\n    for i in range(k):\n        # in each step I am using 1 fold as a test set and the others as train\n        x_test.append(x[l*i: min(l*(i+1), x.shape[0])])\n        y_test.append(y[l*i: min(l*(i+1), x.shape[0])])\n        x_train.append(np.concatenate((x[0:l*i], x[min(l*(i+1), x.shape[0]):x.shape[0]])))\n        y_train.append(np.concatenate((y[0:l*i], y[min(l*(i+1), y.shape[0]):y.shape[0]])))\n    return x_train, y_train, x_test, y_test\n```\n\n\n```python\ndef train(x, y, outcomes):\n    # In this function, I am finding rules for each possible outcome of the feature based on support and confidence for each output\n    \n    # x: input\n    # y: output\n    # outomes: possible outcomes of features\n    \n    rule = [] # list of rules for different features and outcomes\n    \n    for i in range(x.shape[1]):\n        r = []\n        for j in outcomes[i]:\n            v = x[...,i] # v is a feature column and j can be different outcomes of that feature\n            sup = (v == j).sum() # support for that outcome\n            e_conf = (np.dot((y=='0').astype(int), (v==j).astype(int)))/sup # e confidence\n            p_conf = (np.dot((y=='1').astype(int), (v==j).astype(int)))/sup # p confidence\n            if e_conf > p_conf:\n                r.append('0')\n            else:\n                r.append('1')\n        rule.append(r)\n        \n    return rule\n```\n\n\n```python\ndef feature_selection(x, y, rule, outcomes):\n    # In this function, I am selecting the best feature to use as a classifier based on accuracy\n    \n    # x: input\n    # y: output\n    # rule: rules found in training\n    # outcomes: possible outcomes of features\n    \n    acc = [] # list of accuracies for features\n    for i in range(x.shape[1]):\n        count = 0\n        for j in range(x.shape[0]):\n            if rule[i][outcomes[i].index(x[j][i])] == y[j]:\n                count += 1\n        acc.append(count/x.shape[0])\n        \n    # Bar plot of accuracy based on each feature\n    \n    fig = plt.figure()\n    ax = fig.add_axes([0,0,1,1])\n    ax.bar(list(data.columns[1:]), acc)\n    plt.show()\n    \n    return int(np.array(acc).argmax()) # returning the index of highest accuracy\n```\n\n\n```python\ndef predict(x_test, best_feature, rule, outcomes):\n    # In this function, I am making prediction based on the rules\n    \n    # x_test: test set for prediction\n    # best_feature: highest accuracy feature selected\n    # rule: rules found in training\n    # outcomes: possible outcomes of features\n    \n    pred = []\n    for i in x_test[...,best_feature]:\n        pred.append(rule[best_feature][outcomes[best_feature].index(i)])\n    return pred\n```\n\n## Precision, Recall, Accuracy and F-Measure\n\n\\begin{equation}\n\\text { Precision }=\\frac{t p}{t p+f p}\n\\end{equation}\n\n\\begin{equation}\n\\text { Recall }=\\frac{t p}{t p+f n}\n\\end{equation}\n\n\\begin{equation}\n\\text { Accuracy }=\\frac{t p+t n}{t p+t n+f p+f n}\n\\end{equation}\n\n\\begin{equation}\nF=2 \\cdot \\frac{\\text { precision } \\cdot \\text { recall }}{\\text { precision }+\\text { recall }}\n\\end{equation}\n\n\n```python\ndef evaluate(pred, y):\n    # In this function, I am computing evaluation metrics based on the equations above\n    \n    # pred: array of prediction\n    # y: correct labels\n    \n    tp = np.dot((pred == '1'), (y == '1')).sum()\n    fp = np.dot((pred == '1'), (y == '0')).sum()\n    fn = np.dot((pred == '0'), (y == '1')).sum()\n    tn = np.dot((pred == '0'), (y == '0')).sum()\n    precision = tp/(tp+fp)\n    recall = tp/(tp+fn)\n    acc = (tp+tn)/(tp+tn+fp+fn)\n    f_measure = (2*precision*recall)/(precision+recall)\n    return precision, recall, acc, f_measure\n```\n\n\n```python\ndef kfold(k, x, y):\n    # In this function, I am integrating the functions for training and kfold validation\n    \n    # k: number of folds\n    # x: input\n    # y: labels\n    \n    x_train, y_train, x_test, y_test = split(k, x, y)\n    for i in range(k):\n        rule = train(x_train[i], y_train[i], outcomes)\n        best_feature = feature_selection(x_train[i], y_train[i], rule, outcomes)\n        pred = predict(x_test[i], best_feature, rule, outcomes)\n        pred = np.array(pred)\n        precision, recall, acc, f = evaluate(pred, y_test[i])\n        print(\"precision: {} \\t recall: {} \\t accuracy: {} \\t f-measure: {} \".format(precision, recall, acc, f))\n```\n\n\n```python\nkfold(5, x, y)\n```\n", "meta": {"hexsha": "9bf11b90d7f0ef40941b1e447bc5f744d3ad7d81", "size": 67436, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "OneR.ipynb", "max_stars_repo_name": "aminsmd/OneR-Classifier", "max_stars_repo_head_hexsha": "2c8051604e30bc2fc2ab570e0cc086c98d8f6c18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "OneR.ipynb", "max_issues_repo_name": "aminsmd/OneR-Classifier", "max_issues_repo_head_hexsha": "2c8051604e30bc2fc2ab570e0cc086c98d8f6c18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OneR.ipynb", "max_forks_repo_name": "aminsmd/OneR-Classifier", "max_forks_repo_head_hexsha": "2c8051604e30bc2fc2ab570e0cc086c98d8f6c18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 71.3608465608, "max_line_length": 6920, "alphanum_fraction": 0.7288095379, "converted": true, "num_tokens": 4902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.373875808818685, "lm_q2_score": 0.06371499247409608, "lm_q1q2_score": 0.023821494345129098}}
{"text": "# Project 2: Multi-location Transshipment Problem \n\nIn this project, we compare Stochastic Gradient Descent Vs. Bender's Decomposition in optimizing a Two-Stage Stochastic LP.\n\n\n```python\n!pip install autotime\n!pip install nb-black\n!pip install cvxpy\n```\n\n    Collecting autotime\n      Using cached autotime-0.1.5-py3-none-any.whl (46 kB)\n    Requirement already satisfied: statsmodels>=0.11.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from autotime) (0.12.2)\n    Requirement already satisfied: plotly>=4.5.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from autotime) (4.14.3)\n    Requirement already satisfied: scikit-learn>=0.22.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from autotime) (0.24.2)\n    Requirement already satisfied: seaborn>=0.9.0 in /home/fpga/.local/lib/python3.7/site-packages (from autotime) (0.11.0)\n    Requirement already satisfied: pandas==0.25.3 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from autotime) (0.25.3)\n    Collecting dnntime>=0.3.4\n      Using cached dnntime-0.4.1-py3-none-any.whl (47 kB)\n    Requirement already satisfied: numpy>=1.18 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from autotime) (1.20.2)\n    Requirement already satisfied: art>=4.5 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from autotime) (5.1)\n    Collecting fbprophet>=0.5\n      Using cached fbprophet-0.7.1.tar.gz (64 kB)\n    Requirement already satisfied: tscv>=0.0.4 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from autotime) (0.1.2)\n    Requirement already satisfied: matplotlib>=3.1.3 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from autotime) (3.4.1)\n    Collecting pyflux>=0.4.0\n      Using cached pyflux-0.4.15.tar.gz (1.3 MB)\n    Requirement already satisfied: scipy>=1.1 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from statsmodels>=0.11.0->autotime) (1.6.3)\n    Requirement already satisfied: patsy>=0.5 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from statsmodels>=0.11.0->autotime) (0.5.1)\n    Requirement already satisfied: six in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from plotly>=4.5.0->autotime) (1.15.0)\n    Requirement already satisfied: retrying>=1.3.3 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from plotly>=4.5.0->autotime) (1.3.3)\n    Requirement already satisfied: joblib>=0.11 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from scikit-learn>=0.22.0->autotime) (1.0.1)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from scikit-learn>=0.22.0->autotime) (2.1.0)\n    Requirement already satisfied: python-dateutil>=2.6.1 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from pandas==0.25.3->autotime) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from pandas==0.25.3->autotime) (2021.1)\n    Requirement already satisfied: nbformat>=5.0.4 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from dnntime>=0.3.4->autotime) (5.1.3)\n    Requirement already satisfied: tensorflow>=2.1.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from dnntime>=0.3.4->autotime) (2.4.1)\n    Requirement already satisfied: pyyaml>=5.3 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from dnntime>=0.3.4->autotime) (5.4.1)\n    Requirement already satisfied: Cython>=0.22 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from fbprophet>=0.5->autotime) (0.29.23)\n    Requirement already satisfied: cmdstanpy==0.9.5 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from fbprophet>=0.5->autotime) (0.9.5)\n    Requirement already satisfied: pystan>=2.14 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from fbprophet>=0.5->autotime) (3.0.2)\n    Requirement already satisfied: LunarCalendar>=0.0.9 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from fbprophet>=0.5->autotime) (0.0.9)\n    Requirement already satisfied: convertdate>=2.1.2 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from fbprophet>=0.5->autotime) (2.3.2)\n    Requirement already satisfied: holidays>=0.10.2 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from fbprophet>=0.5->autotime) (0.11.1)\n    Requirement already satisfied: setuptools-git>=1.2 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from fbprophet>=0.5->autotime) (1.2)\n    Requirement already satisfied: tqdm>=4.36.1 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from fbprophet>=0.5->autotime) (4.60.0)\n    Requirement already satisfied: cycler>=0.10 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from matplotlib>=3.1.3->autotime) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from matplotlib>=3.1.3->autotime) (1.3.1)\n    Requirement already satisfied: pillow>=6.2.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from matplotlib>=3.1.3->autotime) (8.2.0)\n    Requirement already satisfied: pyparsing>=2.2.1 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from matplotlib>=3.1.3->autotime) (2.4.7)\n    Requirement already satisfied: numdifftools in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from pyflux>=0.4.0->autotime) (0.9.39)\n    Requirement already satisfied: ipython-genutils in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from nbformat>=5.0.4->dnntime>=0.3.4->autotime) (0.2.0)\n    Requirement already satisfied: jsonschema!=2.5.0,>=2.4 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from nbformat>=5.0.4->dnntime>=0.3.4->autotime) (3.2.0)\n    Requirement already satisfied: traitlets>=4.1 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from nbformat>=5.0.4->dnntime>=0.3.4->autotime) (5.0.5)\n    Requirement already satisfied: jupyter-core in /home/fpga/.local/lib/python3.7/site-packages (from nbformat>=5.0.4->dnntime>=0.3.4->autotime) (4.7.0)\n    Requirement already satisfied: typing-extensions~=3.7.4 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (3.7.4.3)\n    Requirement already satisfied: wheel~=0.35 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (0.36.2)\n    Requirement already satisfied: astunparse~=1.6.3 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (1.6.3)\n    Requirement already satisfied: tensorflow-estimator<2.5.0,>=2.4.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (2.4.0)\n    Requirement already satisfied: wrapt~=1.12.1 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (1.12.1)\n    Requirement already satisfied: tensorboard~=2.4 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (2.5.0)\n    Requirement already satisfied: protobuf>=3.9.2 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (3.15.8)\n    Requirement already satisfied: h5py~=2.10.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (2.10.0)\n    Requirement already satisfied: opt-einsum~=3.3.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (3.3.0)\n    Requirement already satisfied: termcolor~=1.1.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (1.1.0)\n    Requirement already satisfied: absl-py~=0.10 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (0.12.0)\n    Requirement already satisfied: grpcio~=1.32.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (1.32.0)\n    Requirement already satisfied: google-pasta~=0.2 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (0.2.0)\n    Requirement already satisfied: flatbuffers~=1.12.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (1.12)\n    Requirement already satisfied: gast==0.3.3 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (0.3.3)\n    Requirement already satisfied: keras-preprocessing~=1.1.2 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (1.1.2)\n    Requirement already satisfied: pysimdjson<4.0,>=3.2 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from pystan>=2.14->fbprophet>=0.5->autotime) (3.2.0)\n    Requirement already satisfied: httpstan<4.5,>=4.4 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from pystan>=2.14->fbprophet>=0.5->autotime) (4.4.2)\n    Requirement already satisfied: clikit<0.7,>=0.6 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from pystan>=2.14->fbprophet>=0.5->autotime) (0.6.2)\n    Requirement already satisfied: aiohttp<4.0,>=3.6 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from pystan>=2.14->fbprophet>=0.5->autotime) (3.7.4.post0)\n    Requirement already satisfied: ephem>=3.7.5.3 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from LunarCalendar>=0.0.9->fbprophet>=0.5->autotime) (3.7.7.1)\n    Requirement already satisfied: pymeeus<=1,>=0.3.13 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from convertdate>=2.1.2->fbprophet>=0.5->autotime) (0.5.11)\n    Requirement already satisfied: hijri-converter in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from holidays>=0.10.2->fbprophet>=0.5->autotime) (2.1.1)\n    Requirement already satisfied: korean-lunar-calendar in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from holidays>=0.10.2->fbprophet>=0.5->autotime) (0.2.1)\n    Requirement already satisfied: pyrsistent>=0.14.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from jsonschema!=2.5.0,>=2.4->nbformat>=5.0.4->dnntime>=0.3.4->autotime) (0.17.3)\n    Requirement already satisfied: attrs>=17.4.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from jsonschema!=2.5.0,>=2.4->nbformat>=5.0.4->dnntime>=0.3.4->autotime) (20.3.0)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from jsonschema!=2.5.0,>=2.4->nbformat>=5.0.4->dnntime>=0.3.4->autotime) (3.10.0)\n    Requirement already satisfied: setuptools in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from jsonschema!=2.5.0,>=2.4->nbformat>=5.0.4->dnntime>=0.3.4->autotime) (52.0.0.post20210125)\n    Requirement already satisfied: werkzeug>=0.11.15 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorboard~=2.4->tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (1.0.1)\n    Requirement already satisfied: google-auth<2,>=1.6.3 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorboard~=2.4->tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (1.30.0)\n    Requirement already satisfied: markdown>=2.6.8 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorboard~=2.4->tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (3.3.4)\n    Requirement already satisfied: requests<3,>=2.21.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorboard~=2.4->tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (2.25.1)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorboard~=2.4->tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (1.8.0)\n    Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorboard~=2.4->tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (0.6.0)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from tensorboard~=2.4->tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (0.4.4)\n    Requirement already satisfied: webargs<8.0,>=7.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from httpstan<4.5,>=4.4->pystan>=2.14->fbprophet>=0.5->autotime) (7.0.1)\n    Requirement already satisfied: appdirs<2.0,>=1.4 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from httpstan<4.5,>=4.4->pystan>=2.14->fbprophet>=0.5->autotime) (1.4.4)\n    Requirement already satisfied: marshmallow<4.0,>=3.10 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from httpstan<4.5,>=4.4->pystan>=2.14->fbprophet>=0.5->autotime) (3.11.1)\n    Requirement already satisfied: lz4<4.0,>=3.1 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from httpstan<4.5,>=4.4->pystan>=2.14->fbprophet>=0.5->autotime) (3.1.3)\n    Requirement already satisfied: pastel<0.3.0,>=0.2.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from clikit<0.7,>=0.6->pystan>=2.14->fbprophet>=0.5->autotime) (0.2.1)\n    Requirement already satisfied: crashtest<0.4.0,>=0.3.0; python_version >= \"3.6\" and python_version < \"4.0\" in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from clikit<0.7,>=0.6->pystan>=2.14->fbprophet>=0.5->autotime) (0.3.1)\n    Requirement already satisfied: pylev<2.0,>=1.3 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from clikit<0.7,>=0.6->pystan>=2.14->fbprophet>=0.5->autotime) (1.3.0)\n    Requirement already satisfied: yarl<2.0,>=1.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from aiohttp<4.0,>=3.6->pystan>=2.14->fbprophet>=0.5->autotime) (1.6.3)\n    Requirement already satisfied: multidict<7.0,>=4.5 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from aiohttp<4.0,>=3.6->pystan>=2.14->fbprophet>=0.5->autotime) (5.1.0)\n    Requirement already satisfied: async-timeout<4.0,>=3.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from aiohttp<4.0,>=3.6->pystan>=2.14->fbprophet>=0.5->autotime) (3.0.1)\n    Requirement already satisfied: chardet<5.0,>=2.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from aiohttp<4.0,>=3.6->pystan>=2.14->fbprophet>=0.5->autotime) (4.0.0)\n    Requirement already satisfied: zipp>=0.5 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from importlib-metadata; python_version < \"3.8\"->jsonschema!=2.5.0,>=2.4->nbformat>=5.0.4->dnntime>=0.3.4->autotime) (3.4.1)\n    Requirement already satisfied: rsa<5,>=3.1.4; python_version >= \"3.6\" in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from google-auth<2,>=1.6.3->tensorboard~=2.4->tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (4.7.2)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from google-auth<2,>=1.6.3->tensorboard~=2.4->tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (4.2.2)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from google-auth<2,>=1.6.3->tensorboard~=2.4->tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (0.2.8)\n    Requirement already satisfied: urllib3<1.27,>=1.21.1 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (1.26.4)\n    Requirement already satisfied: idna<3,>=2.5 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (2020.12.5)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.4->tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (1.3.0)\n    Requirement already satisfied: pyasn1>=0.1.3 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from rsa<5,>=3.1.4; python_version >= \"3.6\"->google-auth<2,>=1.6.3->tensorboard~=2.4->tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (0.4.8)\n    Requirement already satisfied: oauthlib>=3.0.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.4->tensorflow>=2.1.0->dnntime>=0.3.4->autotime) (3.1.0)\n    Building wheels for collected packages: fbprophet, pyflux\n      Building wheel for fbprophet (setup.py) ... \u001b[?25lerror\n    \u001b[31m  ERROR: Command errored out with exit status 1:\n       command: /opt/anaconda3/envs/jeff/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '\"'\"'/tmp/pip-install-cyipebue/fbprophet/setup.py'\"'\"'; __file__='\"'\"'/tmp/pip-install-cyipebue/fbprophet/setup.py'\"'\"';f=getattr(tokenize, '\"'\"'open'\"'\"', open)(__file__);code=f.read().replace('\"'\"'\\r\\n'\"'\"', '\"'\"'\\n'\"'\"');f.close();exec(compile(code, __file__, '\"'\"'exec'\"'\"'))' bdist_wheel -d /tmp/pip-wheel-46ektaws\n           cwd: /tmp/pip-install-cyipebue/fbprophet/\n      Complete output (38 lines):\n      running bdist_wheel\n      running build\n      running build_py\n      creating build\n      creating build/lib\n      creating build/lib/fbprophet\n      creating build/lib/fbprophet/stan_model\n      Traceback (most recent call last):\n        File \"<string>\", line 1, in <module>\n        File \"/tmp/pip-install-cyipebue/fbprophet/setup.py\", line 149, in <module>\n          long_description_content_type='text/markdown',\n        File \"/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/setuptools/__init__.py\", line 153, in setup\n          return distutils.core.setup(**attrs)\n        File \"/opt/anaconda3/envs/jeff/lib/python3.7/distutils/core.py\", line 148, in setup\n          dist.run_commands()\n        File \"/opt/anaconda3/envs/jeff/lib/python3.7/distutils/dist.py\", line 966, in run_commands\n          self.run_command(cmd)\n        File \"/opt/anaconda3/envs/jeff/lib/python3.7/distutils/dist.py\", line 985, in run_command\n          cmd_obj.run()\n        File \"/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/wheel/bdist_wheel.py\", line 299, in run\n          self.run_command('build')\n        File \"/opt/anaconda3/envs/jeff/lib/python3.7/distutils/cmd.py\", line 313, in run_command\n          self.distribution.run_command(command)\n        File \"/opt/anaconda3/envs/jeff/lib/python3.7/distutils/dist.py\", line 985, in run_command\n          cmd_obj.run()\n        File \"/opt/anaconda3/envs/jeff/lib/python3.7/distutils/command/build.py\", line 135, in run\n          self.run_command(cmd_name)\n        File \"/opt/anaconda3/envs/jeff/lib/python3.7/distutils/cmd.py\", line 313, in run_command\n          self.distribution.run_command(command)\n        File \"/opt/anaconda3/envs/jeff/lib/python3.7/distutils/dist.py\", line 985, in run_command\n          cmd_obj.run()\n        File \"/tmp/pip-install-cyipebue/fbprophet/setup.py\", line 48, in run\n          build_models(target_dir)\n        File \"/tmp/pip-install-cyipebue/fbprophet/setup.py\", line 38, in build_models\n          StanBackendEnum.get_backend_class(backend).build_model(target_dir, MODEL_DIR)\n        File \"/tmp/pip-install-cyipebue/fbprophet/fbprophet/models.py\", line 209, in build_model\n          import pystan\n      ModuleNotFoundError: No module named 'pystan'\n      ----------------------------------------\u001b[0m\n    \u001b[31m  ERROR: Failed building wheel for fbprophet\u001b[0m\n    \u001b[?25h  Running setup.py clean for fbprophet\n      Building wheel for pyflux (setup.py) ... \u001b[?25lerror\n    \u001b[31m  ERROR: Command errored out with exit status 1:\n       command: /opt/anaconda3/envs/jeff/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '\"'\"'/tmp/pip-install-cyipebue/pyflux/setup.py'\"'\"'; __file__='\"'\"'/tmp/pip-install-cyipebue/pyflux/setup.py'\"'\"';f=getattr(tokenize, '\"'\"'open'\"'\"', open)(__file__);code=f.read().replace('\"'\"'\\r\\n'\"'\"', '\"'\"'\\n'\"'\"');f.close();exec(compile(code, __file__, '\"'\"'exec'\"'\"'))' bdist_wheel -d /tmp/pip-wheel-qzqjec6v\n           cwd: /tmp/pip-install-cyipebue/pyflux/\n      Complete output (628 lines):\n      running bdist_wheel\n      running build\n      running config_cc\n      unifing config_cc, config, build_clib, build_ext, build commands --compiler options\n      running config_fc\n      unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options\n      running build_src\n      build_src\n      building extension \"pyflux.__check_build._check_build\" sources\n      building extension \"pyflux.arma.arma_recursions\" sources\n      building extension \"pyflux.arma.nn_architecture\" sources\n      building extension \"pyflux.families.gas_recursions\" sources\n      building extension \"pyflux.families.poisson_kalman_recursions\" sources\n      building extension \"pyflux.garch.garch_recursions\" sources\n      building extension \"pyflux.gas.gas_core_recursions\" sources\n      building extension \"pyflux.gpnarx.kernel_routines\" sources\n      building extension \"pyflux.inference.metropolis_sampler\" sources\n      building extension \"pyflux.inference.bbvi_routines\" sources\n      building extension \"pyflux.ssm.kalman\" sources\n      building extension \"pyflux.var.var_recursions\" sources\n      build_src: building npy-pkg config files\n      running build_py\n      creating build\n      creating build/lib.linux-x86_64-3.7\n      creating build/lib.linux-x86_64-3.7/pyflux\n      copying pyflux/results.py -> build/lib.linux-x86_64-3.7/pyflux\n      copying pyflux/latent_variables.py -> build/lib.linux-x86_64-3.7/pyflux\n      copying pyflux/setup.py -> build/lib.linux-x86_64-3.7/pyflux\n      copying pyflux/data_check.py -> build/lib.linux-x86_64-3.7/pyflux\n      copying pyflux/__init__.py -> build/lib.linux-x86_64-3.7/pyflux\n      copying pyflux/tsm.py -> build/lib.linux-x86_64-3.7/pyflux\n      copying pyflux/covariances.py -> build/lib.linux-x86_64-3.7/pyflux\n      creating build/lib.linux-x86_64-3.7/pyflux/__check_build\n      copying pyflux/__check_build/setup.py -> build/lib.linux-x86_64-3.7/pyflux/__check_build\n      copying pyflux/__check_build/__init__.py -> build/lib.linux-x86_64-3.7/pyflux/__check_build\n      creating build/lib.linux-x86_64-3.7/pyflux/arma\n      copying pyflux/arma/nnar.py -> build/lib.linux-x86_64-3.7/pyflux/arma\n      copying pyflux/arma/nnarx.py -> build/lib.linux-x86_64-3.7/pyflux/arma\n      copying pyflux/arma/arimax.py -> build/lib.linux-x86_64-3.7/pyflux/arma\n      copying pyflux/arma/setup.py -> build/lib.linux-x86_64-3.7/pyflux/arma\n      copying pyflux/arma/__init__.py -> build/lib.linux-x86_64-3.7/pyflux/arma\n      copying pyflux/arma/arma.py -> build/lib.linux-x86_64-3.7/pyflux/arma\n      creating build/lib.linux-x86_64-3.7/pyflux/arma/tests\n      copying pyflux/arma/tests/test_arimax_t.py -> build/lib.linux-x86_64-3.7/pyflux/arma/tests\n      copying pyflux/arma/tests/test_arimax_poisson.py -> build/lib.linux-x86_64-3.7/pyflux/arma/tests\n      copying pyflux/arma/tests/test_arima_cauchy.py -> build/lib.linux-x86_64-3.7/pyflux/arma/tests\n      copying pyflux/arma/tests/test_arima_inference.py -> build/lib.linux-x86_64-3.7/pyflux/arma/tests\n      copying pyflux/arma/tests/test_arima_normal.py -> build/lib.linux-x86_64-3.7/pyflux/arma/tests\n      copying pyflux/arma/tests/test_arimax_skewt.py -> build/lib.linux-x86_64-3.7/pyflux/arma/tests\n      copying pyflux/arma/tests/test_arimax_cauchy.py -> build/lib.linux-x86_64-3.7/pyflux/arma/tests\n      copying pyflux/arma/tests/test_arimax_exponential.py -> build/lib.linux-x86_64-3.7/pyflux/arma/tests\n      copying pyflux/arma/tests/test_arimax_laplace.py -> build/lib.linux-x86_64-3.7/pyflux/arma/tests\n      copying pyflux/arma/tests/test_arima_poisson.py -> build/lib.linux-x86_64-3.7/pyflux/arma/tests\n      copying pyflux/arma/tests/test_arima_laplace.py -> build/lib.linux-x86_64-3.7/pyflux/arma/tests\n      copying pyflux/arma/tests/test_arima_t.py -> build/lib.linux-x86_64-3.7/pyflux/arma/tests\n      copying pyflux/arma/tests/__init__.py -> build/lib.linux-x86_64-3.7/pyflux/arma/tests\n      copying pyflux/arma/tests/test_arima_exponential.py -> build/lib.linux-x86_64-3.7/pyflux/arma/tests\n      copying pyflux/arma/tests/test_arimax_inference.py -> build/lib.linux-x86_64-3.7/pyflux/arma/tests\n      copying pyflux/arma/tests/test_arimax_normal.py -> build/lib.linux-x86_64-3.7/pyflux/arma/tests\n      copying pyflux/arma/tests/test_arima_skewt.py -> build/lib.linux-x86_64-3.7/pyflux/arma/tests\n      creating build/lib.linux-x86_64-3.7/pyflux/ensembles\n      copying pyflux/ensembles/mixture_of_experts.py -> build/lib.linux-x86_64-3.7/pyflux/ensembles\n      copying pyflux/ensembles/__init__.py -> build/lib.linux-x86_64-3.7/pyflux/ensembles\n      creating build/lib.linux-x86_64-3.7/pyflux/families\n      copying pyflux/families/t.py -> build/lib.linux-x86_64-3.7/pyflux/families\n      copying pyflux/families/exponential.py -> build/lib.linux-x86_64-3.7/pyflux/families\n      copying pyflux/families/family.py -> build/lib.linux-x86_64-3.7/pyflux/families\n      copying pyflux/families/laplace.py -> build/lib.linux-x86_64-3.7/pyflux/families\n      copying pyflux/families/inverse_gamma.py -> build/lib.linux-x86_64-3.7/pyflux/families\n      copying pyflux/families/cauchy.py -> build/lib.linux-x86_64-3.7/pyflux/families\n      copying pyflux/families/inverse_wishart.py -> build/lib.linux-x86_64-3.7/pyflux/families\n      copying pyflux/families/normal.py -> build/lib.linux-x86_64-3.7/pyflux/families\n      copying pyflux/families/poisson.py -> build/lib.linux-x86_64-3.7/pyflux/families\n      copying pyflux/families/setup.py -> build/lib.linux-x86_64-3.7/pyflux/families\n      copying pyflux/families/flat.py -> build/lib.linux-x86_64-3.7/pyflux/families\n      copying pyflux/families/__init__.py -> build/lib.linux-x86_64-3.7/pyflux/families\n      copying pyflux/families/truncated_normal.py -> build/lib.linux-x86_64-3.7/pyflux/families\n      copying pyflux/families/skewt.py -> build/lib.linux-x86_64-3.7/pyflux/families\n      creating build/lib.linux-x86_64-3.7/pyflux/garch\n      copying pyflux/garch/egarch.py -> build/lib.linux-x86_64-3.7/pyflux/garch\n      copying pyflux/garch/segarchm.py -> build/lib.linux-x86_64-3.7/pyflux/garch\n      copying pyflux/garch/garch.py -> build/lib.linux-x86_64-3.7/pyflux/garch\n      copying pyflux/garch/egarchmreg.py -> build/lib.linux-x86_64-3.7/pyflux/garch\n      copying pyflux/garch/setup.py -> build/lib.linux-x86_64-3.7/pyflux/garch\n      copying pyflux/garch/__init__.py -> build/lib.linux-x86_64-3.7/pyflux/garch\n      copying pyflux/garch/lmegarch.py -> build/lib.linux-x86_64-3.7/pyflux/garch\n      copying pyflux/garch/egarchm.py -> build/lib.linux-x86_64-3.7/pyflux/garch\n      copying pyflux/garch/segarch.py -> build/lib.linux-x86_64-3.7/pyflux/garch\n      creating build/lib.linux-x86_64-3.7/pyflux/gas\n      copying pyflux/gas/scores.py -> build/lib.linux-x86_64-3.7/pyflux/gas\n      copying pyflux/gas/gas.py -> build/lib.linux-x86_64-3.7/pyflux/gas\n      copying pyflux/gas/gasllt.py -> build/lib.linux-x86_64-3.7/pyflux/gas\n      copying pyflux/gas/gasx.py -> build/lib.linux-x86_64-3.7/pyflux/gas\n      copying pyflux/gas/setup.py -> build/lib.linux-x86_64-3.7/pyflux/gas\n      copying pyflux/gas/gasllm.py -> build/lib.linux-x86_64-3.7/pyflux/gas\n      copying pyflux/gas/__init__.py -> build/lib.linux-x86_64-3.7/pyflux/gas\n      copying pyflux/gas/gasreg.py -> build/lib.linux-x86_64-3.7/pyflux/gas\n      copying pyflux/gas/gasrank.py -> build/lib.linux-x86_64-3.7/pyflux/gas\n      creating build/lib.linux-x86_64-3.7/pyflux/gpnarx\n      copying pyflux/gpnarx/gpnarx.py -> build/lib.linux-x86_64-3.7/pyflux/gpnarx\n      copying pyflux/gpnarx/kernels.py -> build/lib.linux-x86_64-3.7/pyflux/gpnarx\n      copying pyflux/gpnarx/setup.py -> build/lib.linux-x86_64-3.7/pyflux/gpnarx\n      copying pyflux/gpnarx/__init__.py -> build/lib.linux-x86_64-3.7/pyflux/gpnarx\n      creating build/lib.linux-x86_64-3.7/pyflux/inference\n      copying pyflux/inference/norm_post_sim.py -> build/lib.linux-x86_64-3.7/pyflux/inference\n      copying pyflux/inference/stoch_optim.py -> build/lib.linux-x86_64-3.7/pyflux/inference\n      copying pyflux/inference/metropolis_hastings.py -> build/lib.linux-x86_64-3.7/pyflux/inference\n      copying pyflux/inference/bbvi.py -> build/lib.linux-x86_64-3.7/pyflux/inference\n      copying pyflux/inference/setup.py -> build/lib.linux-x86_64-3.7/pyflux/inference\n      copying pyflux/inference/__init__.py -> build/lib.linux-x86_64-3.7/pyflux/inference\n      creating build/lib.linux-x86_64-3.7/pyflux/output\n      copying pyflux/output/__init__.py -> build/lib.linux-x86_64-3.7/pyflux/output\n      copying pyflux/output/tableprinter.py -> build/lib.linux-x86_64-3.7/pyflux/output\n      creating build/lib.linux-x86_64-3.7/pyflux/ssm\n      copying pyflux/ssm/dynlin.py -> build/lib.linux-x86_64-3.7/pyflux/ssm\n      copying pyflux/ssm/nllt.py -> build/lib.linux-x86_64-3.7/pyflux/ssm\n      copying pyflux/ssm/dynamic_glm.py -> build/lib.linux-x86_64-3.7/pyflux/ssm\n      copying pyflux/ssm/local_level.py -> build/lib.linux-x86_64-3.7/pyflux/ssm\n      copying pyflux/ssm/local_trend.py -> build/lib.linux-x86_64-3.7/pyflux/ssm\n      copying pyflux/ssm/llt.py -> build/lib.linux-x86_64-3.7/pyflux/ssm\n      copying pyflux/ssm/setup.py -> build/lib.linux-x86_64-3.7/pyflux/ssm\n      copying pyflux/ssm/ndynlin.py -> build/lib.linux-x86_64-3.7/pyflux/ssm\n      copying pyflux/ssm/__init__.py -> build/lib.linux-x86_64-3.7/pyflux/ssm\n      copying pyflux/ssm/nllm.py -> build/lib.linux-x86_64-3.7/pyflux/ssm\n      copying pyflux/ssm/dar.py -> build/lib.linux-x86_64-3.7/pyflux/ssm\n      copying pyflux/ssm/llm.py -> build/lib.linux-x86_64-3.7/pyflux/ssm\n      creating build/lib.linux-x86_64-3.7/pyflux/tests\n      copying pyflux/tests/nhst.py -> build/lib.linux-x86_64-3.7/pyflux/tests\n      copying pyflux/tests/__init__.py -> build/lib.linux-x86_64-3.7/pyflux/tests\n      creating build/lib.linux-x86_64-3.7/pyflux/var\n      copying pyflux/var/var.py -> build/lib.linux-x86_64-3.7/pyflux/var\n      copying pyflux/var/setup.py -> build/lib.linux-x86_64-3.7/pyflux/var\n      copying pyflux/var/__init__.py -> build/lib.linux-x86_64-3.7/pyflux/var\n      running build_ext\n      customize UnixCCompiler\n      customize UnixCCompiler using build_ext\n      CCompilerOpt.cc_test_flags[999] : testing flags (-march=native)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      creating /tmp/tmp0x9e4tz_/opt\n      creating /tmp/tmp0x9e4tz_/opt/anaconda3\n      creating /tmp/tmp0x9e4tz_/opt/anaconda3/envs\n      creating /tmp/tmp0x9e4tz_/opt/anaconda3/envs/jeff\n      creating /tmp/tmp0x9e4tz_/opt/anaconda3/envs/jeff/lib\n      creating /tmp/tmp0x9e4tz_/opt/anaconda3/envs/jeff/lib/python3.7\n      creating /tmp/tmp0x9e4tz_/opt/anaconda3/envs/jeff/lib/python3.7/site-packages\n      creating /tmp/tmp0x9e4tz_/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy\n      creating /tmp/tmp0x9e4tz_/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils\n      creating /tmp/tmp0x9e4tz_/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks\n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-march=native'\n      CCompilerOpt.cc_test_flags[999] : testing flags (-O3)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-O3'\n      CCompilerOpt.cc_test_flags[999] : testing flags (-Werror)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-Werror'\n      CCompilerOpt.__init__[1674] : check requested baseline\n      CCompilerOpt.cc_test_flags[999] : testing flags (-msse)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse'\n      CCompilerOpt.cc_test_flags[999] : testing flags (-msse2)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse2'\n      CCompilerOpt.feature_test[1446] : testing feature 'SSE' with flags (-msse -msse2)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -Werror'\n      CCompilerOpt.feature_test[1446] : testing feature 'SSE2' with flags (-msse -msse2)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -Werror'\n      CCompilerOpt.cc_test_flags[999] : testing flags (-msse3)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse3'\n      CCompilerOpt.feature_test[1446] : testing feature 'SSE3' with flags (-msse -msse2 -msse3)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -msse3 -Werror'\n      CCompilerOpt.__init__[1683] : check requested dispatch-able features\n      CCompilerOpt.cc_test_flags[999] : testing flags (-mssse3)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-mssse3'\n      CCompilerOpt.cc_test_flags[999] : testing flags (-msse4.1)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse4.1'\n      CCompilerOpt.cc_test_flags[999] : testing flags (-mpopcnt)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-mpopcnt'\n      CCompilerOpt.cc_test_flags[999] : testing flags (-msse4.2)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse4.2'\n      CCompilerOpt.cc_test_flags[999] : testing flags (-mavx)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-mavx'\n      CCompilerOpt.feature_test[1446] : testing feature 'AVX' with flags (-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -Werror'\n      CCompilerOpt.feature_test[1446] : testing feature 'SSSE3' with flags (-msse -msse2 -msse3 -mssse3)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -msse3 -mssse3 -Werror'\n      CCompilerOpt.feature_test[1446] : testing feature 'POPCNT' with flags (-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -Werror'\n      CCompilerOpt.feature_test[1446] : testing feature 'SSE41' with flags (-msse -msse2 -msse3 -mssse3 -msse4.1)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -msse3 -mssse3 -msse4.1 -Werror'\n      CCompilerOpt.cc_test_flags[999] : testing flags (-mf16c)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-mf16c'\n      CCompilerOpt.feature_test[1446] : testing feature 'F16C' with flags (-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -Werror'\n      CCompilerOpt.feature_test[1446] : testing feature 'SSE42' with flags (-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -Werror'\n      CCompilerOpt.cc_test_flags[999] : testing flags (-mavx2)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-mavx2'\n      CCompilerOpt.feature_test[1446] : testing feature 'AVX2' with flags (-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mavx2)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mavx2 -Werror'\n      CCompilerOpt.cc_test_flags[999] : testing flags (-mfma)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-mfma'\n      CCompilerOpt.cc_test_flags[999] : testing flags (-mavx512f)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-mavx512f'\n      CCompilerOpt.cc_test_flags[999] : testing flags (-mavx512cd)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-mavx512cd'\n      CCompilerOpt.cc_test_flags[999] : testing flags (-mavx512vl -mavx512bw -mavx512dq)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-mavx512vl -mavx512bw -mavx512dq'\n      CCompilerOpt.cc_test_flags[999] : testing flags (-mavx512ifma -mavx512vbmi)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-mavx512ifma -mavx512vbmi'\n      CCompilerOpt.feature_test[1446] : testing feature 'AVX512_CNL' with flags (-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -mavx512cd -mavx512vl -mavx512bw -mavx512dq -mavx512ifma -mavx512vbmi)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -mavx512cd -mavx512vl -mavx512bw -mavx512dq -mavx512ifma -mavx512vbmi -Werror'\n      CCompilerOpt.feature_test[1446] : testing feature 'FMA3' with flags (-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -Werror'\n      CCompilerOpt.feature_test[1446] : testing feature 'AVX512_SKX' with flags (-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -mavx512cd -mavx512vl -mavx512bw -mavx512dq)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -mavx512cd -mavx512vl -mavx512bw -mavx512dq -Werror'\n      CCompilerOpt.feature_test[1446] : testing feature 'AVX512CD' with flags (-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -mavx512cd)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -mavx512cd -Werror'\n      CCompilerOpt.feature_test[1446] : testing feature 'AVX512F' with flags (-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -Werror'\n      CCompilerOpt.cc_test_flags[999] : testing flags (-mavx512vnni)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-mavx512vnni'\n      CCompilerOpt.dist_test[576] : CCompilerOpt._dist_test_spawn[713] : Command (gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/opt/anaconda3/envs/jeff/include/python3.7m -c /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/test_flags.c -o /tmp/tmp0x9e4tz_/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/test_flags.o -MMD -MF /tmp/tmp0x9e4tz_/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/test_flags.o.d -mavx512vnni) failed with exit status 1 output ->\n      gcc: error: unrecognized command line option \u2018-mavx512vnni\u2019\n      \n      CCompilerOpt.cc_test_flags[1003] : testing failed\n      CCompilerOpt.feature_test[1446] : testing feature 'AVX512_CLX' with flags (-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -mavx512cd -mavx512vl -mavx512bw -mavx512dq)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -mavx512cd -mavx512vl -mavx512bw -mavx512dq -Werror'\n      CCompilerOpt.dist_test[576] : CCompilerOpt._dist_test_spawn[713] : Command (gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/opt/anaconda3/envs/jeff/include/python3.7m -c /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/cpu_avx512_clx.c -o /tmp/tmp0x9e4tz_/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/cpu_avx512_clx.o -MMD -MF /tmp/tmp0x9e4tz_/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/cpu_avx512_clx.o.d -msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -mavx512cd -mavx512vl -mavx512bw -mavx512dq -Werror) failed with exit status 1 output ->\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/cpu_avx512_clx.c: In function \u2018main\u2019:\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/cpu_avx512_clx.c:6:17: error: implicit declaration of function \u2018_mm512_dpbusd_epi32\u2019 [-Werror=implicit-function-declaration]\n           __m512i a = _mm512_dpbusd_epi32(_mm512_setzero_si512(), _mm512_setzero_si512(), _mm512_setzero_si512());\n                       ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/cpu_avx512_clx.c:6:17: error: incompatible types when initializing type \u2018__m512i {aka __vector(8) long long int}\u2019 using type \u2018int\u2019\n      cc1: all warnings being treated as errors\n      \n      CCompilerOpt.feature_test[1458] : testing failed\n      CCompilerOpt.cc_test_flags[999] : testing flags (-mavx512er -mavx512pf)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-mavx512er -mavx512pf'\n      CCompilerOpt.feature_test[1446] : testing feature 'AVX512_KNL' with flags (-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -mavx512cd -mavx512er -mavx512pf)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -mavx512cd -mavx512er -mavx512pf -Werror'\n      CCompilerOpt.cc_test_flags[999] : testing flags (-mavx5124fmaps -mavx5124vnniw -mavx512vpopcntdq)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-mavx5124fmaps -mavx5124vnniw -mavx512vpopcntdq'\n      CCompilerOpt.dist_test[576] : CCompilerOpt._dist_test_spawn[713] : Command (gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/opt/anaconda3/envs/jeff/include/python3.7m -c /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/test_flags.c -o /tmp/tmp0x9e4tz_/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/test_flags.o -MMD -MF /tmp/tmp0x9e4tz_/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/test_flags.o.d -mavx5124fmaps -mavx5124vnniw -mavx512vpopcntdq) failed with exit status 1 output ->\n      gcc: error: unrecognized command line option \u2018-mavx5124fmaps\u2019\n      gcc: error: unrecognized command line option \u2018-mavx5124vnniw\u2019\n      gcc: error: unrecognized command line option \u2018-mavx512vpopcntdq\u2019\n      \n      CCompilerOpt.cc_test_flags[1003] : testing failed\n      CCompilerOpt.feature_test[1446] : testing feature 'AVX512_KNM' with flags (-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -mavx512cd -mavx512er -mavx512pf)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -mavx512cd -mavx512er -mavx512pf -Werror'\n      CCompilerOpt.dist_test[576] : CCompilerOpt._dist_test_spawn[713] : Command (gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/opt/anaconda3/envs/jeff/include/python3.7m -c /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/cpu_avx512_knm.c -o /tmp/tmp0x9e4tz_/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/cpu_avx512_knm.o -MMD -MF /tmp/tmp0x9e4tz_/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/cpu_avx512_knm.o.d -msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -mavx512cd -mavx512er -mavx512pf -Werror) failed with exit status 1 output ->\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/cpu_avx512_knm.c: In function \u2018main\u2019:\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/cpu_avx512_knm.c:9:9: error: implicit declaration of function \u2018_mm512_4fmadd_ps\u2019 [-Werror=implicit-function-declaration]\n           b = _mm512_4fmadd_ps(b, b, b, b, b, NULL);\n               ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/cpu_avx512_knm.c:9:7: error: incompatible types when assigning to type \u2018__m512 {aka __vector(16) float}\u2019 from type \u2018int\u2019\n           b = _mm512_4fmadd_ps(b, b, b, b, b, NULL);\n             ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/cpu_avx512_knm.c:11:9: error: implicit declaration of function \u2018_mm512_4dpwssd_epi32\u2019 [-Werror=implicit-function-declaration]\n           a = _mm512_4dpwssd_epi32(a, a, a, a, a, NULL);\n               ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/cpu_avx512_knm.c:11:7: error: incompatible types when assigning to type \u2018__m512i {aka __vector(8) long long int}\u2019 from type \u2018int\u2019\n           a = _mm512_4dpwssd_epi32(a, a, a, a, a, NULL);\n             ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/cpu_avx512_knm.c:13:9: error: implicit declaration of function \u2018_mm512_popcnt_epi64\u2019 [-Werror=implicit-function-declaration]\n           a = _mm512_popcnt_epi64(a);\n               ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/cpu_avx512_knm.c:13:7: error: incompatible types when assigning to type \u2018__m512i {aka __vector(8) long long int}\u2019 from type \u2018int\u2019\n           a = _mm512_popcnt_epi64(a);\n             ^\n      cc1: all warnings being treated as errors\n      \n      CCompilerOpt.feature_test[1458] : testing failed\n      CCompilerOpt.__init__[1696] : skip features (SSE3 SSE SSE2) since its part of baseline\n      CCompilerOpt.__init__[1699] : initialize targets groups\n      CCompilerOpt.__init__[1701] : parse target group simd_test\n      CCompilerOpt._parse_target_tokens[1912] : skip targets (VSX3 ASIMD VSX FMA4 VSX2 XOP NEON) not part of baseline or dispatch-able features\n      CCompilerOpt._parse_policy_not_keepbase[2022] : skip baseline features (SSE2)\n      CCompilerOpt.generate_dispatch_header[2236] : generate CPU dispatch header: (build/src.linux-x86_64-3.7/numpy/distutils/include/npy_cpu_dispatch_config.h)\n      CCompilerOpt.generate_dispatch_header[2247] : dispatch header dir build/src.linux-x86_64-3.7/numpy/distutils/include does not exist, creating it\n      CCompilerOpt.feature_extra_checks[1519] : Testing extra checks for feature 'AVX512F' (AVX512F_REDUCE)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -Werror'\n      CCompilerOpt.dist_test[576] : CCompilerOpt._dist_test_spawn[713] : Command (gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/opt/anaconda3/envs/jeff/include/python3.7m -c /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c -o /tmp/tmp0x9e4tz_/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.o -MMD -MF /tmp/tmp0x9e4tz_/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.o.d -msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -Werror) failed with exit status 1 output ->\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c: In function \u2018main\u2019:\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:13:21: error: implicit declaration of function \u2018_mm512_reduce_add_ps\u2019 [-Werror=implicit-function-declaration]\n           float sum_ps  = _mm512_reduce_add_ps(one_ps);\n                           ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:14:21: error: implicit declaration of function \u2018_mm512_reduce_add_pd\u2019 [-Werror=implicit-function-declaration]\n           double sum_pd = _mm512_reduce_add_pd(one_pd);\n                           ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:15:26: error: implicit declaration of function \u2018_mm512_reduce_add_epi64\u2019 [-Werror=implicit-function-declaration]\n           int sum_int   = (int)_mm512_reduce_add_epi64(one_i64);\n                                ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:16:26: error: implicit declaration of function \u2018_mm512_reduce_add_epi32\u2019 [-Werror=implicit-function-declaration]\n               sum_int  += (int)_mm512_reduce_add_epi32(one_i64);\n                                ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:18:16: error: implicit declaration of function \u2018_mm512_reduce_mul_ps\u2019 [-Werror=implicit-function-declaration]\n           sum_ps  += _mm512_reduce_mul_ps(one_ps);\n                      ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:19:16: error: implicit declaration of function \u2018_mm512_reduce_mul_pd\u2019 [-Werror=implicit-function-declaration]\n           sum_pd  += _mm512_reduce_mul_pd(one_pd);\n                      ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:20:21: error: implicit declaration of function \u2018_mm512_reduce_mul_epi64\u2019 [-Werror=implicit-function-declaration]\n           sum_int += (int)_mm512_reduce_mul_epi64(one_i64);\n                           ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:21:21: error: implicit declaration of function \u2018_mm512_reduce_mul_epi32\u2019 [-Werror=implicit-function-declaration]\n           sum_int += (int)_mm512_reduce_mul_epi32(one_i64);\n                           ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:23:16: error: implicit declaration of function \u2018_mm512_reduce_min_ps\u2019 [-Werror=implicit-function-declaration]\n           sum_ps  += _mm512_reduce_min_ps(one_ps);\n                      ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:24:16: error: implicit declaration of function \u2018_mm512_reduce_min_pd\u2019 [-Werror=implicit-function-declaration]\n           sum_pd  += _mm512_reduce_min_pd(one_pd);\n                      ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:25:21: error: implicit declaration of function \u2018_mm512_reduce_min_epi32\u2019 [-Werror=implicit-function-declaration]\n           sum_int += (int)_mm512_reduce_min_epi32(one_i64);\n                           ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:26:21: error: implicit declaration of function \u2018_mm512_reduce_min_epu32\u2019 [-Werror=implicit-function-declaration]\n           sum_int += (int)_mm512_reduce_min_epu32(one_i64);\n                           ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:27:21: error: implicit declaration of function \u2018_mm512_reduce_min_epi64\u2019 [-Werror=implicit-function-declaration]\n           sum_int += (int)_mm512_reduce_min_epi64(one_i64);\n                           ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:29:16: error: implicit declaration of function \u2018_mm512_reduce_max_ps\u2019 [-Werror=implicit-function-declaration]\n           sum_ps  += _mm512_reduce_max_ps(one_ps);\n                      ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:30:16: error: implicit declaration of function \u2018_mm512_reduce_max_pd\u2019 [-Werror=implicit-function-declaration]\n           sum_pd  += _mm512_reduce_max_pd(one_pd);\n                      ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:31:21: error: implicit declaration of function \u2018_mm512_reduce_max_epi32\u2019 [-Werror=implicit-function-declaration]\n           sum_int += (int)_mm512_reduce_max_epi32(one_i64);\n                           ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:32:21: error: implicit declaration of function \u2018_mm512_reduce_max_epu32\u2019 [-Werror=implicit-function-declaration]\n           sum_int += (int)_mm512_reduce_max_epu32(one_i64);\n                           ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:33:21: error: implicit declaration of function \u2018_mm512_reduce_max_epi64\u2019 [-Werror=implicit-function-declaration]\n           sum_int += (int)_mm512_reduce_max_epi64(one_i64);\n                           ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:35:21: error: implicit declaration of function \u2018_mm512_reduce_and_epi32\u2019 [-Werror=implicit-function-declaration]\n           sum_int += (int)_mm512_reduce_and_epi32(one_i64);\n                           ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:36:21: error: implicit declaration of function \u2018_mm512_reduce_and_epi64\u2019 [-Werror=implicit-function-declaration]\n           sum_int += (int)_mm512_reduce_and_epi64(one_i64);\n                           ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:38:21: error: implicit declaration of function \u2018_mm512_reduce_or_epi32\u2019 [-Werror=implicit-function-declaration]\n           sum_int += (int)_mm512_reduce_or_epi32(one_i64);\n                           ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512f_reduce.c:39:21: error: implicit declaration of function \u2018_mm512_reduce_or_epi64\u2019 [-Werror=implicit-function-declaration]\n           sum_int += (int)_mm512_reduce_or_epi64(one_i64);\n                           ^\n      cc1: all warnings being treated as errors\n      \n      CCompilerOpt.feature_extra_checks[1537] : testing failed for checks (AVX512F_REDUCE)\n      CCompilerOpt.feature_extra_checks[1519] : Testing extra checks for feature 'AVX512_SKX' (AVX512BW_MASK AVX512DQ_MASK)\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -mavx512cd -mavx512vl -mavx512bw -mavx512dq -Werror'\n      CCompilerOpt.dist_test[576] : CCompilerOpt._dist_test_spawn[713] : Command (gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/opt/anaconda3/envs/jeff/include/python3.7m -c /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512bw_mask.c -o /tmp/tmp0x9e4tz_/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512bw_mask.o -MMD -MF /tmp/tmp0x9e4tz_/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512bw_mask.o.d -msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -mavx512cd -mavx512vl -mavx512bw -mavx512dq -Werror) failed with exit status 1 output ->\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512bw_mask.c: In function \u2018main\u2019:\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512bw_mask.c:12:11: error: implicit declaration of function \u2018_kor_mask64\u2019 [-Werror=implicit-function-declaration]\n           m64 = _kor_mask64(m64, m64);\n                 ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512bw_mask.c:13:11: error: implicit declaration of function \u2018_kxor_mask64\u2019 [-Werror=implicit-function-declaration]\n           m64 = _kxor_mask64(m64, m64);\n                 ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512bw_mask.c:14:11: error: implicit declaration of function \u2018_cvtu64_mask64\u2019 [-Werror=implicit-function-declaration]\n           m64 = _cvtu64_mask64(_cvtmask64_u64(m64));\n                 ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512bw_mask.c:14:26: error: implicit declaration of function \u2018_cvtmask64_u64\u2019 [-Werror=implicit-function-declaration]\n           m64 = _cvtu64_mask64(_cvtmask64_u64(m64));\n                                ^\n      cc1: all warnings being treated as errors\n      \n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      compile options: '-I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -mavx512cd -mavx512vl -mavx512bw -mavx512dq -Werror'\n      CCompilerOpt.dist_test[576] : CCompilerOpt._dist_test_spawn[713] : Command (gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/opt/anaconda3/envs/jeff/include/python3.7m -c /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512dq_mask.c -o /tmp/tmp0x9e4tz_/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512dq_mask.o -MMD -MF /tmp/tmp0x9e4tz_/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512dq_mask.o.d -msse -msse2 -msse3 -mssse3 -msse4.1 -mpopcnt -msse4.2 -mavx -mf16c -mfma -mavx2 -mavx512f -mavx512cd -mavx512vl -mavx512bw -mavx512dq -Werror) failed with exit status 1 output ->\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512dq_mask.c: In function \u2018main\u2019:\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512dq_mask.c:12:10: error: implicit declaration of function \u2018_kor_mask8\u2019 [-Werror=implicit-function-declaration]\n           m8 = _kor_mask8(m8, m8);\n                ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512dq_mask.c:13:10: error: implicit declaration of function \u2018_kxor_mask8\u2019 [-Werror=implicit-function-declaration]\n           m8 = _kxor_mask8(m8, m8);\n                ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512dq_mask.c:14:10: error: implicit declaration of function \u2018_cvtu32_mask8\u2019 [-Werror=implicit-function-declaration]\n           m8 = _cvtu32_mask8(_cvtmask8_u32(m8));\n                ^\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/distutils/checks/extra_avx512dq_mask.c:14:24: error: implicit declaration of function \u2018_cvtmask8_u32\u2019 [-Werror=implicit-function-declaration]\n           m8 = _cvtu32_mask8(_cvtmask8_u32(m8));\n                              ^\n      cc1: all warnings being treated as errors\n      \n      CCompilerOpt.feature_extra_checks[1537] : testing failed for checks (AVX512BW_MASK AVX512DQ_MASK)\n      Detected changes on compiler optimizations, force rebuilding\n      building 'pyflux.__check_build._check_build' extension\n      compiling C sources\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      creating build/temp.linux-x86_64-3.7/pyflux\n      creating build/temp.linux-x86_64-3.7/pyflux/__check_build\n      compile options: '-I/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/core/include -Ibuild/src.linux-x86_64-3.7/numpy/distutils/include -I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -msse3'\n      gcc: pyflux/__check_build/_check_build.c\n      gcc -pthread -shared -B /opt/anaconda3/envs/jeff/compiler_compat -L/opt/anaconda3/envs/jeff/lib -Wl,-rpath=/opt/anaconda3/envs/jeff/lib -Wl,--no-as-needed -Wl,--sysroot=/ build/temp.linux-x86_64-3.7/pyflux/__check_build/_check_build.o -o build/lib.linux-x86_64-3.7/pyflux/__check_build/_check_build.cpython-37m-x86_64-linux-gnu.so\n      building 'pyflux.arma.arma_recursions' extension\n      compiling C sources\n      C compiler: gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n      \n      creating build/temp.linux-x86_64-3.7/pyflux/arma\n      compile options: '-I/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/core/include -Ibuild/src.linux-x86_64-3.7/numpy/distutils/include -I/opt/anaconda3/envs/jeff/include/python3.7m -c'\n      extra options: '-msse -msse2 -msse3'\n      gcc: pyflux/arma/arma_recursions.c\n      In file included from /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1944:0,\n                       from /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                       from /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                       from pyflux/arma/arma_recursions.c:274:\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n       #warning \"Using deprecated NumPy API, disable it with \" \\\n        ^\n      pyflux/arma/arma_recursions.c: In function \u2018__Pyx__ExceptionSave\u2019:\n      pyflux/arma/arma_recursions.c:19331:19: error: \u2018PyThreadState {aka struct _ts}\u2019 has no member named \u2018exc_type\u2019\n           *type = tstate->exc_type;\n                         ^\n      pyflux/arma/arma_recursions.c:19332:20: error: \u2018PyThreadState {aka struct _ts}\u2019 has no member named \u2018exc_value\u2019\n           *value = tstate->exc_value;\n                          ^\n      pyflux/arma/arma_recursions.c:19333:17: error: \u2018PyThreadState {aka struct _ts}\u2019 has no member named \u2018exc_traceback\u2019\n           *tb = tstate->exc_traceback;\n                       ^\n      pyflux/arma/arma_recursions.c: In function \u2018__Pyx__ExceptionReset\u2019:\n      pyflux/arma/arma_recursions.c:19340:22: error: \u2018PyThreadState {aka struct _ts}\u2019 has no member named \u2018exc_type\u2019\n           tmp_type = tstate->exc_type;\n                            ^\n      pyflux/arma/arma_recursions.c:19341:23: error: \u2018PyThreadState {aka struct _ts}\u2019 has no member named \u2018exc_value\u2019\n           tmp_value = tstate->exc_value;\n                             ^\n      pyflux/arma/arma_recursions.c:19342:20: error: \u2018PyThreadState {aka struct _ts}\u2019 has no member named \u2018exc_traceback\u2019\n           tmp_tb = tstate->exc_traceback;\n                          ^\n      pyflux/arma/arma_recursions.c:19343:11: error: \u2018PyThreadState {aka struct _ts}\u2019 has no member named \u2018exc_type\u2019\n           tstate->exc_type = type;\n                 ^\n      pyflux/arma/arma_recursions.c:19344:11: error: \u2018PyThreadState {aka struct _ts}\u2019 has no member named \u2018exc_value\u2019\n           tstate->exc_value = value;\n                 ^\n      pyflux/arma/arma_recursions.c:19345:11: error: \u2018PyThreadState {aka struct _ts}\u2019 has no member named \u2018exc_traceback\u2019\n           tstate->exc_traceback = tb;\n                 ^\n      pyflux/arma/arma_recursions.c: In function \u2018__Pyx__GetException\u2019:\n      pyflux/arma/arma_recursions.c:19400:22: error: \u2018PyThreadState {aka struct _ts}\u2019 has no member named \u2018exc_type\u2019\n           tmp_type = tstate->exc_type;\n                            ^\n      pyflux/arma/arma_recursions.c:19401:23: error: \u2018PyThreadState {aka struct _ts}\u2019 has no member named \u2018exc_value\u2019\n           tmp_value = tstate->exc_value;\n                             ^\n      pyflux/arma/arma_recursions.c:19402:20: error: \u2018PyThreadState {aka struct _ts}\u2019 has no member named \u2018exc_traceback\u2019\n           tmp_tb = tstate->exc_traceback;\n                          ^\n      pyflux/arma/arma_recursions.c:19403:11: error: \u2018PyThreadState {aka struct _ts}\u2019 has no member named \u2018exc_type\u2019\n           tstate->exc_type = local_type;\n                 ^\n      pyflux/arma/arma_recursions.c:19404:11: error: \u2018PyThreadState {aka struct _ts}\u2019 has no member named \u2018exc_value\u2019\n           tstate->exc_value = local_value;\n                 ^\n      pyflux/arma/arma_recursions.c:19405:11: error: \u2018PyThreadState {aka struct _ts}\u2019 has no member named \u2018exc_traceback\u2019\n           tstate->exc_traceback = local_tb;\n                 ^\n      pyflux/arma/arma_recursions.c: In function \u2018__Pyx__ExceptionSwap\u2019:\n      pyflux/arma/arma_recursions.c:19427:22: error: \u2018PyThreadState {aka struct _ts}\u2019 has no member named \u2018exc_type\u2019\n           tmp_type = tstate->exc_type;\n                            ^\n      pyflux/arma/arma_recursions.c:19428:23: error: \u2018PyThreadState {aka struct _ts}\u2019 has no member named \u2018exc_value\u2019\n           tmp_value = tstate->exc_value;\n                             ^\n      pyflux/arma/arma_recursions.c:19429:20: error: \u2018PyThreadState {aka struct _ts}\u2019 has no member named \u2018exc_traceback\u2019\n           tmp_tb = tstate->exc_traceback;\n                          ^\n      pyflux/arma/arma_recursions.c:19430:11: error: \u2018PyThreadState {aka struct _ts}\u2019 has no member named \u2018exc_type\u2019\n           tstate->exc_type = *type;\n                 ^\n      pyflux/arma/arma_recursions.c:19431:11: error: \u2018PyThreadState {aka struct _ts}\u2019 has no member named \u2018exc_value\u2019\n           tstate->exc_value = *value;\n                 ^\n      pyflux/arma/arma_recursions.c:19432:11: error: \u2018PyThreadState {aka struct _ts}\u2019 has no member named \u2018exc_traceback\u2019\n           tstate->exc_traceback = *tb;\n                 ^\n      In file included from /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:21:0,\n                       from /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                       from pyflux/arma/arma_recursions.c:274:\n      pyflux/arma/arma_recursions.c: At top level:\n      /opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/core/include/numpy/__multiarray_api.h:1464:1: warning: \u2018_import_array\u2019 defined but not used [-Wunused-function]\n       _import_array(void)\n       ^\n      error: Command \"gcc -pthread -B /opt/anaconda3/envs/jeff/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/numpy/core/include -Ibuild/src.linux-x86_64-3.7/numpy/distutils/include -I/opt/anaconda3/envs/jeff/include/python3.7m -c pyflux/arma/arma_recursions.c -o build/temp.linux-x86_64-3.7/pyflux/arma/arma_recursions.o -MMD -MF build/temp.linux-x86_64-3.7/pyflux/arma/arma_recursions.o.d -msse -msse2 -msse3\" failed with exit status 1\n      \n      ########### EXT COMPILER OPTIMIZATION ###########\n      Platform      :\n        Architecture: x64\n        Compiler    : gcc\n      \n      CPU baseline  :\n        Requested   : 'min'\n        Enabled     : SSE SSE2 SSE3\n        Flags       : -msse -msse2 -msse3\n        Extra checks: none\n      \n      CPU dispatch  :\n        Requested   : 'max -xop -fma4'\n        Enabled     : SSSE3 SSE41 POPCNT SSE42 AVX F16C FMA3 AVX2 AVX512F AVX512CD AVX512_KNL AVX512_SKX AVX512_CNL\n        Generated   : none\n      CCompilerOpt._cache_write[796] : write cache to path -> /tmp/pip-install-cyipebue/pyflux/build/temp.linux-x86_64-3.7/ccompiler_opt_cache_ext.py\n      ----------------------------------------\u001b[0m\n    \u001b[31m  ERROR: Failed building wheel for pyflux\u001b[0m\n    \u001b[?25h  Running setup.py clean for pyflux\n    Failed to build fbprophet pyflux\n    Installing collected packages: fbprophet, dnntime, pyflux, autotime\n        Running setup.py install for fbprophet ... \u001b[?25lerror\n    \u001b[31m    ERROR: Command errored out with exit status 1:\n         command: /opt/anaconda3/envs/jeff/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '\"'\"'/tmp/pip-install-cyipebue/fbprophet/setup.py'\"'\"'; __file__='\"'\"'/tmp/pip-install-cyipebue/fbprophet/setup.py'\"'\"';f=getattr(tokenize, '\"'\"'open'\"'\"', open)(__file__);code=f.read().replace('\"'\"'\\r\\n'\"'\"', '\"'\"'\\n'\"'\"');f.close();exec(compile(code, __file__, '\"'\"'exec'\"'\"'))' install --record /tmp/pip-record-7vad5ilk/install-record.txt --single-version-externally-managed --compile --install-headers /opt/anaconda3/envs/jeff/include/python3.7m/fbprophet\n             cwd: /tmp/pip-install-cyipebue/fbprophet/\n        Complete output (40 lines):\n        running install\n        running build\n        running build_py\n        creating build\n        creating build/lib\n        creating build/lib/fbprophet\n        creating build/lib/fbprophet/stan_model\n        Traceback (most recent call last):\n          File \"<string>\", line 1, in <module>\n          File \"/tmp/pip-install-cyipebue/fbprophet/setup.py\", line 149, in <module>\n            long_description_content_type='text/markdown',\n          File \"/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/setuptools/__init__.py\", line 153, in setup\n            return distutils.core.setup(**attrs)\n          File \"/opt/anaconda3/envs/jeff/lib/python3.7/distutils/core.py\", line 148, in setup\n            dist.run_commands()\n          File \"/opt/anaconda3/envs/jeff/lib/python3.7/distutils/dist.py\", line 966, in run_commands\n            self.run_command(cmd)\n          File \"/opt/anaconda3/envs/jeff/lib/python3.7/distutils/dist.py\", line 985, in run_command\n            cmd_obj.run()\n          File \"/opt/anaconda3/envs/jeff/lib/python3.7/site-packages/setuptools/command/install.py\", line 61, in run\n            return orig.install.run(self)\n          File \"/opt/anaconda3/envs/jeff/lib/python3.7/distutils/command/install.py\", line 545, in run\n            self.run_command('build')\n          File \"/opt/anaconda3/envs/jeff/lib/python3.7/distutils/cmd.py\", line 313, in run_command\n            self.distribution.run_command(command)\n          File \"/opt/anaconda3/envs/jeff/lib/python3.7/distutils/dist.py\", line 985, in run_command\n            cmd_obj.run()\n          File \"/opt/anaconda3/envs/jeff/lib/python3.7/distutils/command/build.py\", line 135, in run\n            self.run_command(cmd_name)\n          File \"/opt/anaconda3/envs/jeff/lib/python3.7/distutils/cmd.py\", line 313, in run_command\n            self.distribution.run_command(command)\n          File \"/opt/anaconda3/envs/jeff/lib/python3.7/distutils/dist.py\", line 985, in run_command\n            cmd_obj.run()\n          File \"/tmp/pip-install-cyipebue/fbprophet/setup.py\", line 48, in run\n            build_models(target_dir)\n          File \"/tmp/pip-install-cyipebue/fbprophet/setup.py\", line 38, in build_models\n            StanBackendEnum.get_backend_class(backend).build_model(target_dir, MODEL_DIR)\n          File \"/tmp/pip-install-cyipebue/fbprophet/fbprophet/models.py\", line 209, in build_model\n            import pystan\n        ModuleNotFoundError: No module named 'pystan'\n        ----------------------------------------\u001b[0m\n    \u001b[31mERROR: Command errored out with exit status 1: /opt/anaconda3/envs/jeff/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '\"'\"'/tmp/pip-install-cyipebue/fbprophet/setup.py'\"'\"'; __file__='\"'\"'/tmp/pip-install-cyipebue/fbprophet/setup.py'\"'\"';f=getattr(tokenize, '\"'\"'open'\"'\"', open)(__file__);code=f.read().replace('\"'\"'\\r\\n'\"'\"', '\"'\"'\\n'\"'\"');f.close();exec(compile(code, __file__, '\"'\"'exec'\"'\"'))' install --record /tmp/pip-record-7vad5ilk/install-record.txt --single-version-externally-managed --compile --install-headers /opt/anaconda3/envs/jeff/include/python3.7m/fbprophet Check the logs for full command output.\u001b[0m\n    \u001b[33mWARNING: You are using pip version 20.2.4; however, version 21.1 is available.\n    You should consider upgrading via the '/opt/anaconda3/envs/jeff/bin/python -m pip install --upgrade pip' command.\u001b[0m\n    \u001b[?25hRequirement already satisfied: nb-black in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (1.0.7)\n    Requirement already satisfied: black>='19.3'; python_version >= \"3.6\" in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from nb-black) (21.4b2)\n    Requirement already satisfied: ipython in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from nb-black) (7.22.0)\n    Requirement already satisfied: regex>=2020.1.8 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from black>='19.3'; python_version >= \"3.6\"->nb-black) (2021.4.4)\n    Requirement already satisfied: typing-extensions>=3.7.4; python_version < \"3.8\" in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from black>='19.3'; python_version >= \"3.6\"->nb-black) (3.7.4.3)\n    Requirement already satisfied: click>=7.1.2 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from black>='19.3'; python_version >= \"3.6\"->nb-black) (7.1.2)\n    Requirement already satisfied: pathspec<1,>=0.8.1 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from black>='19.3'; python_version >= \"3.6\"->nb-black) (0.8.1)\n    Requirement already satisfied: mypy-extensions>=0.4.3 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from black>='19.3'; python_version >= \"3.6\"->nb-black) (0.4.3)\n    Requirement already satisfied: toml>=0.10.1 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from black>='19.3'; python_version >= \"3.6\"->nb-black) (0.10.2)\n    Requirement already satisfied: appdirs in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from black>='19.3'; python_version >= \"3.6\"->nb-black) (1.4.4)\n    Requirement already satisfied: typed-ast>=1.4.2; python_version < \"3.8\" in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from black>='19.3'; python_version >= \"3.6\"->nb-black) (1.4.3)\n    Requirement already satisfied: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from ipython->nb-black) (3.0.18)\n    Requirement already satisfied: traitlets>=4.2 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from ipython->nb-black) (5.0.5)\n    Requirement already satisfied: jedi>=0.16 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from ipython->nb-black) (0.18.0)\n    Requirement already satisfied: backcall in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from ipython->nb-black) (0.2.0)\n    Requirement already satisfied: pygments in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from ipython->nb-black) (2.8.1)\n    Requirement already satisfied: pickleshare in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from ipython->nb-black) (0.7.5)\n    Requirement already satisfied: decorator in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from ipython->nb-black) (5.0.7)\n    Requirement already satisfied: pexpect>4.3; sys_platform != \"win32\" in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from ipython->nb-black) (4.8.0)\n    Requirement already satisfied: setuptools>=18.5 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from ipython->nb-black) (52.0.0.post20210125)\n    Requirement already satisfied: wcwidth in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->ipython->nb-black) (0.2.5)\n    Requirement already satisfied: ipython-genutils in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from traitlets>=4.2->ipython->nb-black) (0.2.0)\n    Requirement already satisfied: parso<0.9.0,>=0.8.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from jedi>=0.16->ipython->nb-black) (0.8.2)\n    Requirement already satisfied: ptyprocess>=0.5 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from pexpect>4.3; sys_platform != \"win32\"->ipython->nb-black) (0.7.0)\n    \u001b[33mWARNING: You are using pip version 20.2.4; however, version 21.1 is available.\n    You should consider upgrading via the '/opt/anaconda3/envs/jeff/bin/python -m pip install --upgrade pip' command.\u001b[0m\n    Requirement already satisfied: cvxpy in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (1.1.12)\n    Requirement already satisfied: numpy>=1.15 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from cvxpy) (1.20.2)\n    Requirement already satisfied: scipy>=1.1.0 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from cvxpy) (1.6.3)\n    Requirement already satisfied: scs>=1.1.6 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from cvxpy) (2.1.3)\n    Requirement already satisfied: ecos>=2 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from cvxpy) (2.0.7.post1)\n    Requirement already satisfied: osqp>=0.4.1 in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from cvxpy) (0.6.2.post0)\n    Requirement already satisfied: qdldl in /opt/anaconda3/envs/jeff/lib/python3.7/site-packages (from osqp>=0.4.1->cvxpy) (0.1.5.post0)\n    \u001b[33mWARNING: You are using pip version 20.2.4; however, version 21.1 is available.\n    You should consider upgrading via the '/opt/anaconda3/envs/jeff/bin/python -m pip install --upgrade pip' command.\u001b[0m\n\n\n\n```python\n# %load_ext autotime\n# %load_ext nb_black\n\n# General\nimport time\nimport numpy as np\nimport cvxpy as cp\nimport scipy as sp\nimport pandas as pd\nimport itertools\n\n# Ignore warnings LOL\nimport warnings\n\nwarnings.simplefilter(\"ignore\")\n\n# SEED FOR RANDOMNESS\nnp.random.seed(420)\n```\n\n---\n## 1. Preface\n\nThe type of problem we care about in this project are known as [two-stage stochastic programming](https://en.wikipedia.org/wiki/Stochastic_programming#Two-stage_problems). Let The general formulation of it is as follows (Adapted from Wikipedia):\n\n### 1.1. General Two-Stage Stochastic Program\n\n#### 1.1.1 First Stage Stochastic Program\n\n\\begin{align}\n    \\min_{x\\in X} & \\{ g(x)= f(x) + E_{\\tilde{s}\\sim S}[h(x, s=\\tilde{s})]\\}\n\\end{align}\n\n, where $h(x, s=\\tilde{s})$ is the optimal value of the second-stage problem given a specific scenario $\\tilde{s}$. $x \\in X$ is our first-stage decision variable vector, $S$ is a probability distribution of the scenario variables that we're sampling from.\n\n#### 1.1.2 Second Stage Stochastic Program\n\nFor a specific $\\tilde{x}$ and $\\tilde{s}$,\n\n\\begin{align}\n    h(x=\\tilde{x}, s=\\tilde{s}) = \\min_{y} & \\{ d(s, y) \\,\\vert\\,C(s, x) +D(s, y) = \\xi(s)\\}  \\\\\n\\end{align}\n\n, where $C, D, \\xi$ are functions given a specific scenario $\\tilde{s}$. $y$ is our second-stage decision variable vector. \n\nAt the first stage we optimize (minimize in the above formulation) the cost of the first-stage decision plus the expected cost of the (optimal) second-stage decision. We can view the second-stage problem simply as an optimization problem which describes our supposedly optimal behavior when the uncertain data is revealed (specific scenario $\\tilde{s}$), or we can consider its solution as a recourse action where the term $D(s, y)$ compensates for a possible inconsistency of the system $C(s, x) \\leq \\xi(s)$ and $d(s, y)$ is the cost of this recourse action.\n\n### 1.2. Two-Stage Stochastic Linear Program\n\nThe stochastic linear program below is just a specific instance of the general program above, with very minor changes - e.g. functions of first-stage / second-stage decision variables are no longer general functions, but rather vectors / matrices because of constraints must be linear for a linear program.\n\n#### 1.2.1 First Stage Stochastic Linear Program\n\n\\begin{align}\n    \\min\\limits_{x\\in \\mathbb{R}^n} & f(x)= c^\\top x + E_{\\tilde{s}\\sim S}[h(x, s=\\tilde{s})] & \\\\\n    \\text{subject to} \n    & Ax = b &\\\\\n    & x \\geq 0\n\\end{align}\n\n, where $h(x, s=\\tilde{s})$ is the optimal value of the second-stage problem given a specific scenario $\\tilde{s}$. $x \\in \\mathbb{R}^n$ is our first-stage decision variable vector, $S$ is a probability distribution of the scenario variables that we're sampling from., where $h(x, s)$ is the optimal value of the second-stage problem\n\n#### 1.2.2 Second Stage Stochastic Linear Program\n\nFor a specific $\\tilde{x}$ and $\\tilde{s}$,\n\n\\begin{align}\n    h(x=\\tilde{x}, s=\\tilde{s}) = \\min\\limits_{y\\in \\mathbb{R}^m}\\,& d(s)^T y \\\\\n    \\text{subject to }\\,& C(s)x + D(s)y = \\xi(s) \\\\\n    &y \\geq 0\n\\end{align}\n\n, where $C, D, \\xi$ are matrices given a specific scenario $\\tilde{s}$. $y$ is our second-stage decision variable vector. \n\nAt the first stage we optimize (minimize in the above formulation) the cost of the first-stage decision plus the expected cost of the (optimal) second-stage decision. We can view the second-stage problem simply as an optimization problem which describes our supposedly optimal behavior when the uncertain data is revealed (specific scenario $\\tilde{s}$), or we can consider its solution as a recourse action where the term $D(s)y$ compensates for a possible inconsistency of the system $C(s)x \\leq \\xi(s)$ and $d(s)^\\top y$ is the cost of this recourse action.\n\n### 1.3. Two-Stage Stochastic Linear Program with Discretized Scenario Distribution\n\nWhat happens if we can't get / don't want to sample from a continuous distribution for the scenarios? (What if $S$ is discrete instead of continuous?). Nothing much changes other than how we calculate the expectation of the second-stage objective values. \n\n#### 1.3.1 First Stage Stochastic Linear Program with Discretized Scenario Distribution\n\n\\begin{align}\n    \\min\\limits_{x\\in \\mathbb{R}^n}\\,& f(x)= c^\\top x + \\underbrace{\\sum_{s = \\tilde{s}} p(s = \\tilde{s}) h(x, s = \\tilde{s})}_{E_{\\tilde{s}\\sim S}[h(x, s=\\tilde{s})]} \\\\\n    \\text{subject to }\\,\n    & Ax = b \\\\\n    & x \\geq 0\n\\end{align}\n\n, where $h(x, s)$ is the optimal value of the second-stage problem, and $p(s = \\tilde{s})$ is the probability of the scenario $\\tilde{s}$ occuring.\n\n#### 1.3.2 Second Stage Stochastic Linear Program with Discretized Scenario Distribution\n\nFor a specific $\\tilde{x}$ and $\\tilde{s}$,\n\n\\begin{align}\n    h(x=\\tilde{x}, s=\\tilde{s}) = \\min\\limits_{y\\in \\mathbb{R}^m}\\,& d(s)^T y \\\\\n    \\text{subject to} & \\, C(s)x + D(s)y = \\xi(s) \\text{, where }C(s), D(s), \\xi(s) \\\\\n    & y \\geq 0 \\\\\n\\end{align}\n\nHowever, how do we go about solving this two-stage stochastic programs? The problem we face here is We will present two algorithms: Stochastic Gradient Descent and L-Shaped / Bender's Method.\n\n---\n## 2. Method: Stochastic Gradient Descent\n\nTo keep things simple, we will work on using stochastic gradient descent on a stochastic linear program with s discretized scenario distribution.\n\nFirst, we recall the general key update formula in gradient descent (adjusting parameter $w_i$ in negative direction of gradient of objective $f$):\n\n\\begin{align}\n    & w_i \\leftarrow w_i + \\alpha \\frac{\\partial f}{\\partial w_i}\\,\\forall i = 0, \\cdots , \\text{Number of parameters} \\\\\n\\end{align}\n\nLet's recall the Lagrangian for the first stage problem :\n\n\\begin{align}\n    \\mathcal{L}(x) = c^\\top x + E_{\\tilde{s}\\sim S}[h(x, s=\\tilde{s})] - \\mu\n\\end{align}\n\nAssume we have solved the second stage problem, and have retrieved optimal primal variables $y^*$ and dual variables $\\pi^*$ (equality constraints) and $\\lambda^*$ (inequality constraints), then recall the Lagrangian of $h(x=\\tilde{x}, s=\\tilde{s})$:\n\n\\begin{align}\n  \\mathcal{L}(x) &= d(s)^\\top y^* - \\pi^* \\left(C(s)x + D(s)y^* - \\xi(s) \\right) - \\lambda^* y^* \\\\\n\\end{align}\n\nTo perform gradient descent on our obejctive function $f(x)$, we need to find its gradient / subgradient w.r.t. $x$:\n\n\\begin{align}\n  f(x) &= c^\\top x + \\sum_s p_s h_s(x) \\\\\n  \\frac{df}{dx} &= c + \\frac{d \\left(\\sum_s p_s h_s(x)\\right)}{dx} \\\\\n  &= c + \\sum_s p_s\\frac{d\\left(h_s(x)\\right)}{dx} \\\\\n  &= c + \\sum_s p_s\\frac{d\\left(\\mathcal{L}(x)\\right)}{dx} \\\\\n  &= c + \\sum_s p_s\\frac{d\\left(d^\\top y_s - \\pi_s \\left( Dy_s - \\xi_s + C_s x \\right) - \\lambda_s y_s \\right)}{dx} \\\\\n  &= c - \\sum_s p_s (\\pi^\\top_s C_s) \\\\\n\\end{align}\n\nStochastic Gradient Descent:\n\n\\begin{align}\n  x &= x + \\alpha \\frac{df}{dx} \\\\\n  &= x + \\alpha \\left( c - \\sum_s p_s (\\pi^\\top_s C_s) \\right) \\\\\n\\end{align}\n\n\nOrthogonal Projection onto [intersection of half-spaces (Convex Polytope)](https://en.wikipedia.org/wiki/Convex_polytope)\n\n\\begin{align}\n    \\arg \\min_{x \\geq 0} & \\frac{1}{2} {\\lVert x - y \\rVert}_{2}^{2} \\\\\n    \\text{subject to } & Ax \\leq b\n\\end{align}\n\nLagrangian\n\n\\begin{align}\n    \\mathcal{L}(x, \\lambda) &= \\frac{1}{2} {\\lVert x - y \\rVert}_{2}^{2} + \\lambda \\left(Ax  - b \\right) \\\\\n\\end{align}\n\nLagrange Dual\n\n\\begin{align}\n    \\mathcal{L}(\\lambda) \n    &= \\inf_{x \\geq 0} \\mathcal{L}(x, \\lambda) \\\\ \n    &= \\inf_{x \\geq 0} \\frac{1}{2} {\\lVert x - y \\rVert}_{2}^{2} + \\lambda \\left(Ax  - b \\right) \\\\\n\\end{align}\n\nKKT Conditions\n\nStationarity:\n\n\\begin{align}\n    \\nabla_x \\mathcal{L}(x, \\lambda) &= 0 \\\\\n    \\nabla_x \\frac{1}{2} {\\left( x - y \\right) }^\\top \\left( x - y \\right) + \\lambda \\left(Ax  - b \\right) &= 0 \\\\\n    \\left( x - y \\right) + \\lambda A &= 0 \\\\\n    \\lambda &= A^{-1}\\left(y - x\\right) \\\\\n\\end{align}\n\n\n\n\n```python\nclass StochasticGradientDescent:\n    @staticmethod\n    def projection(vector, constraints=None):\n        \"\"\"Find the projection of y onto the C(A) that minimizes\n        the euclidean norm between y and the projected vector\n        \n        .. math::\n            \\begin{align}\n                \\arg \\min_{x \\geq 0} & \\frac{1}{2} {\\lVert x - y \\rVert}_{2}^{2} \\\\\n                \\text{subject to } & x \\in X, \\, \\text{where }X\\text{ is a convex set}\n            \\end{align}\n            \n        Args:\n            vector (np.array): Vector to be projected\n            \n        Returns:\n            np.array: Projected vector\n        \"\"\"\n        P_positive = lambda vector: np.maximum(\n            vector, np.zeros(vector.shape)\n        )  # Positive projection operator on a point\n        if constraints is None:\n            return P_positive(\n                vector\n            )  # Return positive projection if there isnt a convex polytope / set constraint\n\n        proj = cp.Variable(vector.shape, nonneg=True)  # Projected Vector\n        obj = cp.Minimize(\n            cp.norm2(proj - vector)\n        )  # Minimize euclidean norm of difference between y and projection\n        prob = cp.Problem(obj, constraints=constraints)\n        prob.solve()\n        return proj.value\n\n    @staticmethod\n    def projection_dykstra(projections, x0, max_iter=1000, tol=1e-6):\n        \"\"\"Dykstra's Projection algorithm to find the orthogonal\n        projection of a point onto a convex polytope (intersection\n        of affine halfspaces). The algorithm below is adapted from\n        https://github.com/mjhough/Dykstra/blob/main/dykstra/Dykstra.py\n\n        Args:\n            projections\n\n        \"\"\"\n        assert len(x0.shape) == 1, \"x0 must be a vector\"\n\n        x = x0.copy()\n        y = np.zeros((projections.shape[0], x0.shape[0]))\n\n        n = 0\n        cI = np.inf\n        while n < max_iter and cI >= tol:\n            cI = 0\n            for i in range(projections.shape[0]):\n\n                # Update iterate\n                prev_x = x.copy()\n                x = projections[i](prev_x - y[i, :])\n\n                # Update increment\n                prev_y = y[i, :].copy()\n                y[i, :] = x - (prev_x - prev_y)\n\n                # Stop condition\n                cI += np.linalg.norm(prev_y - y[i, :]) ** 2\n\n                n += 1\n        return x\n\n    def __init__(\n        self, c, x0, first_stage_constraints, s_gen, n, n_iter=None, \u03b1=1e0, \u03b5=1e-04, log=True\n    ):\n        \"\"\"The Stochastic Gradient Descent method implemented here\n        is used to optimize the Two-Stage Stochastic Linear Program\n        with second-stage variables following a discrete distribution\n\n        \"\"\"\n        self.c = c  # First-stage decision coefficient\n        self.x0 = x0  # Initial first-stage decision variable values\n        self.first_stage_constraints = first_stage_constraints  # Function that gives a list of the constraints for first-stage problem\n        self.s_gen = s_gen  # Function to generate scenario specific entities\n        self.n = n  # Number of scenarios to generate using s_gen\n        self.n_iter = n_iter  # Number of iterations of sgd\n        self.\u03b1 = \u03b1  # Learning rate for gradient descent\n        self.\u03b5 = \u03b5 # Tolerance for how close subgradient is to 0\n        self.log = log  # Whether or not to log progress\n\n    def solve(self):\n        \"\"\"Solves the Two-stage Stochastic Optimization\"\"\"\n        f_primal_optimal, x_star, k = self.first_stage()\n\n        if self.log:\n            print(\n                f\"Optimal primal objective of first stage problem: {np.round(f_primal_optimal, 3)}\"\n            )\n            print(f\"Optimal first-stage decision variables: {np.round(x_star, 3)}\")\n            print(f\"Number of iterations for convergence: {k}\")\n\n        return f_primal_optimal, x_star, k\n\n    def first_stage(self):\n        \"\"\"First-stage Optimization\"\"\"\n        f_primal_optimal = np.inf  # First-stage primal optimal objective value\n        x = (\n            np.array([0.0] * self.c.shape[0]) if self.x0 is None else self.x0.copy()\n        )  # First-stage decision variables\n\n#         # Fix number of iterations\n#         for k in range(self.n_iter):\n        k = 0\n        while True:\n            \n            data = list(self.s_gen(self.n))  # Random Scenarios and associated variables\n\n            # Initialize subgradient of f\n            \u03bd = self.c.copy()\n\n            # Initialize expectation of h\n            expected_h = 0\n\n            # Accumulating subgradients\n            for p_s, d_s, C_s, D_s, \u03be_s in data:\n\n                \u03c0_s, h_primal_optimal = self.second_stage(\n                    x=x, d=d_s, C=C_s, D=D_s, \u03be=\u03be_s\n                )\n\n                \u03bd -= p_s * \u03c0_s.T @ C_s  # Update subgradient\n                expected_h += (\n                    p_s * h_primal_optimal\n                )  # Update expected second-stage optimal value\n                \n            # Early stopping condition\n            if np.allclose(\u03bd, np.zeros(self.c.shape[0]), atol=self.\u03b5):\n                print(\"Early Stopping condition satisfied.\")\n                break\n            \n            # The current f primal optimal found\n            current_f_primal_optimal = self.c.T @ x + expected_h\n\n            # Updated x value [WHY TF is it a + and not a -]\n            x = StochasticGradientDescent.projection(\n                vector=x + (self.\u03b1 * \u03bd), constraints=self.first_stage_constraints\n            )\n\n            if self.log and k % 50 == 0:\n                print(\"=\" * 20 + f\" Iteration {k}\" + \"=\" * 20)\n                print(\n                    f\"Current Primal Objective Found:\",\n                    np.round(current_f_primal_optimal, 3),\n                    \"|\",\n                    f\"Best Primal Objective Found:\",\n                    np.round(f_primal_optimal, 3),\n                )\n\n            # If minimized value is better, update\n            if f_primal_optimal > current_f_primal_optimal:\n                f_primal_optimal = current_f_primal_optimal\n                \n            # Update k\n            k += 1\n\n        return f_primal_optimal, x, k\n\n    def second_stage(self, x, d, C, D, \u03be):\n        \"\"\"Second-stage Optimization\"\"\"\n        y = cp.Variable(d.shape[0], nonneg=True)  # Second-stage decision variables\n        constraints = [C @ x + D @ y == \u03be]  # Second-stage constraints\n        obj = cp.Minimize(d @ y)\n        prob = cp.Problem(obj, constraints=constraints)\n        prob.solve()\n\n        return constraints[0].dual_value, prob.value\n```\n\n---\n## 3. L-Shaped / Bender's Method\n\nMaster Problem:\n\n\\begin{align}\n  \\underset{S \\geq 0}{\\min} \\mu & \\\\\n\\end{align}\n\nSub Problem:\n\n\\begin{align}\n  \\underset{F}{\\min} h(S=S^* = \\underset{S \\geq 0}{\\arg\\min}\\,\\mu, d=\\tilde{d}) &= \\underset{F}{\\min} \\sum^N_{i=1} h_i F_{B_i E_i} + \\sum^N_{i=1} \\sum^N_{j=1} c_{ij} F_{B_i M_j} + \\sum^N_i p_i F_{RM_i} \\\\\n  \\text{subject to } &S_i = F_{B_i M_i} + \\sum^N_{j =1 \\\\ i \\not= 1} F_{B_i M_j} + F_{B_i E_i}\\qquad i = 1, \\cdots , N, \\\\\n  &F_{B_i M_i} + \\sum^N_{j = 1 \\\\ j \\not= i} F_{B_j M_i} + F_{RM_i} = {d}_i\\qquad i = 1, \\cdots , N, \\\\\n  &\\sum^N_{i=1} {d}_i = \\sum^N_{i=1} F_{RM_i} + \\sum^N_{i = 1} F_{RE_i}, \\\\\n  &F_{B_i E_i} + F_{RE_i} = S_i\\qquad i = 1, \\cdots , N, \\\\\n  &F_{B_i E_i}, F_{B_i M_j}, F_{RM_i}, F_{RE_i} \\geq 0\\qquad i = 1, \\cdots , N, \\\\\n  &j = 1, \\cdots , N.\n\\end{align}\n\nSp:\n\n\\begin{align}\n  h_s(x) &= \\underset{y_s}{\\min} d^\\top y_s \\\\\n  \\text{subject to } Dy_s &= \\xi_s - C_s x \\\\\n  y_s &\\geq 0 \\\\\n\\end{align}\n\nDual Sp:\n\n\\begin{align}\n  \\underset{\\pi_s, \\lambda_s}{\\max} & \\left[\\xi_s - C_s x\\right]^\\top \\left(\\pi_s, \\lambda_s\\right) \\\\\n  \\text{subject to } & \\pi_s \\text{ free} \\\\\n  & \\lambda_s \\geq 0 \\\\\n\\end{align}\n\n\n```python\nclass Benders:\n    def __init__(self, c, first_stage_constraints, s_gen, \u03b5=1e-5, log=True):\n        \"\"\"The Bender's method implemented here\n        is used to optimize the Two-Stage Stochastic Linear Program\n        with second-stage variables following a discrete distribution\n\n        \"\"\"\n        self.c = c  # First-stage decision coefficient\n        self.first_stage_constraints = first_stage_constraints  # Function that gives a list of the constraints for first-stage problem\n        self.s_gen = s_gen  # Function to generate scenario specific entities\n        self.\u03b5 = \u03b5  # Tolerance between Upper Bound and Lower Bound\n        self.log = log  # Whether or not to log progress\n\n    def solve(self):\n        \"\"\"Solves the Two-stage Stochastic Optimization\"\"\"\n        # 1. Initialize UB = infinity, LB = -infinity\n        UB, LB = np.inf, -np.inf\n        x = cp.Variable(self.c.shape, nonneg=True)  # First-stage decision variables\n\n        # Master Problem\n        z = cp.Variable(1, nonneg=True)\n        MP_obj = cp.Minimize(z)\n\n        # Bender cuts that we will be adding to the master problem\n        cuts = (\n            self.first_stage_constraints\n            if self.first_stage_constraints is not None\n            else []\n        )\n\n        k = 0\n\n        # 2. While UB - LB > \u03b5, we will continue adding cuts\n        while UB - LB > self.\u03b5:\n\n            expected_h = 0\n            \u03b1, \u03b2 = 0, 0  # Hyperplane of cut coefficients\n\n            # Go through all the scenarios possible\n            for p_s, d_s, C_s, D_s, \u03be_s in self.s_gen():\n\n                # 3a. Solve the Dual of the Sub-problem for all combinations of demand \\tilde{d}\n                # [Equivalent to solving primal since LPs have 0 duality gap]\n                \u03c0_optimal, h_dual_optimal, status = self.second_stage(\n                    x=x, d=d_s, C=C_s, D=D_s, \u03be=\u03be_s\n                )\n\n                #                 # 4a. If dual variables are unbounded, add cut\n                #                 if status == \"infeasible\":\n                #                     cuts += [(\u03be_s - C_s @ x).T @ \u03c0_optimal <= 0]\n\n                #                 # 4b. Else set UB and add cut on first stage primal optimal value\n                #                 else:\n                #                     expected_h += p_s * h_dual_optimal\n                #                     cuts += [z >= (\u03be_s - C_s @ x).T @ \u03c0_optimal]\n\n                expected_h += p_s * h_dual_optimal\n                \u03b1 += p_s * \u03be_s.T @ \u03c0_optimal\n                \u03b2 += -p_s * C_s.T @ \u03c0_optimal\n\n            # 3b. Add a new halfspace constraint \n            cuts += [z >= \u03b1 + \u03b2.T @ x]\n\n            # 4. Update UB\n            UB = min(\n                UB,\n                self.c.T @ x.value + expected_h if x.value is not None else expected_h,\n            )\n\n            # 5. Solve Master Problem\n            MP_prob = cp.Problem(MP_obj, constraints=cuts)\n            MP_prob.solve()\n\n            # 6. Update LB\n            LB = MP_prob.value\n\n            if self.log:\n                print(\"=\" * 20 + f\" Iteration {k}\" + \"=\" * 20)\n                print(\n                    f\"Lower Bound:\",\n                    np.round(LB, 3),\n                    \"|\",\n                    f\"Upper Bound:\",\n                    np.round(UB, 3),\n                )\n            k += 1\n\n        if self.log:\n            print(f\"Optimal primal objective of first stage problem: {np.round(LB, 3)}\")\n            print(f\"Optimal first-stage decision variables: {np.round(x.value, 3)}\")\n            print(f\"Number of iterations for convergence: {k}\")\n\n        return LB, np.array(x.value), k\n\n    def second_stage(self, x, d, C, D, \u03be):\n        \"\"\"Dual Form of Second-stage Optimization\"\"\"\n\n        \u03c0 = cp.Variable(\n            \u03be.shape, nonneg=False\n        )  # Second-stage dual variables are Free since they are dual of the equality constraints\n        constraints = [D.T @ \u03c0 <= d]  # Second-stage dual constraints\n        obj = cp.Maximize(\n            (\u03be - C @ (np.zeros(C.shape[1]) if x.value is None else x.value)).T @ \u03c0\n        )\n        prob = cp.Problem(obj, constraints=constraints)\n        prob.solve()\n\n        return \u03c0.value, prob.value, prob.status\n```\n\n---\n## 4. Two-stage Multi-location Transshipment Problem\n\n### 4.1. Problem Setup\n\n#### 4.1.1 First Stage Stochastic Linear Program\n\nIn the first stage problem, we want to figure out what the optimal order-up-to quantity $S$ is. We formulate the first stage LP as follows, minimizing the expected (stochastic demand) transshipment cost with the order-up-to quantities $S$ as our primal variables:\n\n\\begin{align}\n\\underset{S \\geq 0}{\\min}\\,& \\mathbb{E}_{\\tilde{d} \\sim D}\\left[h(S, d = \\tilde{d})\\right] \\qquad \\text{, where }D\\text{ is the demand distribution} \\\\\n\\end{align}\n\n#### 4.1.2 Second Stage Stochastic Linear Program\n\nIn our second stage problem, given a specific order-up-to quantity $\\tilde{S}$, and a fixed demand $\\tilde{d}$, we want to solve the following constrained linear program over the primal variables $F$ (flow to and from each node), minimziing the transshipment cost for the specific instance of $\\tilde{S}$ and $\\tilde{d}$:\n\n\\begin{align}\n    h(S = \\tilde{S}, d=\\tilde{d}) = \\underset{F}{\\min} &\\sum^N_{i=1} h_i F_{B_i E_i} + \\sum^N_{i=1} \\sum^N_{j=1} c_{ij} F_{B_i M_j} + \\sum^N_i p_i F_{RM_i} \\\\\n  \\text{subject to } & S_i = F_{B_i M_i} + \\sum^N_{j =1 \\\\ i \\not= 1} F_{B_i M_j} + F_{B_i E_i} \\,\\,\\,\\, i = 1, \\cdots , N, \\\\\n  &F_{B_i M_i} + \\sum^N_{j = 1 \\\\ j \\not= i} F_{B_j M_i} + F_{RM_i} = {d}_i \\,\\,\\,\\, i = 1, \\cdots , N, \\\\\n  &\\sum^N_{i=1} {d}_i = \\sum^N_{i=1} F_{RM_i} + \\sum^N_{i = 1} F_{RE_i}, \\\\\n  &F_{B_i E_i} + F_{RE_i} = S_i \\,\\,\\,\\, i = 1, \\cdots , N, \\\\\n  &F_{B_i E_i}, F_{B_i M_j}, F_{RM_i}, F_{RE_i} \\geq 0 \\,\\,\\,\\, i = 1, \\cdots , N, \\\\\n  &j = 1, \\cdots , N.\n\\end{align}\n\nReformulate objective and constraints into standard form:\n\n\n```python\ndef get_transshipment_variables():\n\n    # Number of retailers\n    N = 4\n\n    # Holding cost Vector\n    h = np.array([1] * N)\n\n    # Shortage cost Vector\n    p = np.array([4] * N)\n\n    # Cost of transshipment from retailer i to retailer j Matrix\n    C = np.full((N, N), 0.5)\n    np.fill_diagonal(C, 0)\n\n    # PMF of Retailer Demand distribution\n    P = np.array([0.020, 0.14, 0.68, 0.14, 0.020])\n\n    # Each Retailer's Demand distribution associated with probabilities above\n    RETAILER_DEMANDS = np.array(\n        [\n            [60, 80, 100, 120, 140],\n            [100, 150, 200, 250, 300],\n            [90, 120, 150, 180, 210],\n            [70, 120, 170, 220, 270],\n        ]\n    )\n\n    return N, h, p, C, P, RETAILER_DEMANDS\n\n\ndef random_demand(P, retailer_demands):\n    \"\"\"Samples a random demand vector according to demand pmf\n    parameters given\n\n    Args:\n        P (numpy.array): Array of probabilities for each demand, shape: (Number of probabilities)\n        retailer_demands (numpy.array): Matrix of retailer demands, shape: (Number of retailers, Number of discrete demands)\n\n    Returns:\n        Tuple[np.array, float]: A tuple of the (sampled Demand Vector, probability of the Sampled Demand Vector)\n    \"\"\"\n    assert np.isclose(\n        np.sum(P), 1\n    ), \"p must sum to 1 to be a valid probability distribution.\"\n    sampled_demand = np.array(\n        [np.random.choice(retailer_demand, p=P) for retailer_demand in retailer_demands]\n    )\n    p_s = np.prod(\n        [\n            P[np.argwhere(retailer_demand == D_i)[0][0]]\n            for retailer_demand, D_i in zip(retailer_demands, sampled_demand)\n        ]\n    )\n    return sampled_demand, p_s\n\n\ndef get_second_stage_variables(s):\n    \"\"\"\"\"\"\n\n    N, h, p, C, P, RETAILER_DEMANDS = get_transshipment_variables()\n\n    # Coefficient of Second-stage decision variables\n    d_s = np.concatenate(\n        (\n            h,  # Coefficient of Amount of inventory that moves from begining to ending (FBE)\n            C.flatten(),  # Coefficient of Amount of inventory to ship from current retailer to other retailers (FBM)\n            p,  # Coefficient of Amount to ship from supplier to retailer's middle inventory (FRM)\n            np.array(\n                [0] * N\n            ),  # Coefficient of Amount to ship from supplier to retailer's ending inventory (FRE)\n        )\n    )\n\n    # Second-stage C(s) matrix\n    C_s = np.concatenate(\n        (\n            np.eye(N),\n            np.zeros(shape=(N, N)),\n            np.zeros(shape=(1, N)),\n            np.eye(N),\n        ),\n        axis=0,\n    )\n\n    # Second-stage D(s) matrix\n    D_s = np.concatenate(\n        (\n            np.concatenate(\n                (\n                    -np.eye(N),\n                    np.array(\n                        [\n                            ([-1] * N + [0] * (N * (N - 1)))[-N * idx :]\n                            + ([-1] * N + [0] * (N * (N - 1)))[: -N * idx]\n                            for idx in range(N)\n                        ]\n                    ),\n                    np.zeros(shape=(N, N)),\n                    np.zeros(shape=(N, N)),\n                ),\n                axis=1,\n            ),\n            np.concatenate(\n                (\n                    np.zeros(shape=(N, N)),\n                    np.array(\n                        [\n                            np.array(\n                                [\n                                    ([1] + [0] * (N - 1))[-idx:]\n                                    + ([1] + [0] * (N - 1))[:-idx]\n                                ]\n                                * N\n                            ).flatten()\n                            for idx in range(N)\n                        ]\n                    ),\n                    np.eye(N),\n                    np.zeros(shape=(N, N)),\n                ),\n                axis=1,\n            ),\n            np.array([[0] * N + [0] * (N * N) + [1] * N + [1] * N]),\n            np.concatenate(\n                (\n                    -np.eye(N),\n                    np.zeros(shape=(N, N * N)),\n                    np.zeros(shape=(N, N)),\n                    -np.eye(N),\n                ),\n                axis=1,\n            ),\n        ),\n        axis=0,\n    )\n\n    # \u03be(s) vector\n    \u03be_s = np.concatenate(\n        (\n            np.zeros(N),\n            s,\n            np.array([np.sum(s)]),\n            np.zeros(N),\n        ),\n        axis=0,\n    )\n\n    return d_s, C_s, D_s, \u03be_s\n\n\ndef s_gen_sgd(n=50):\n    \"\"\"Function that generates the scenario dependent\n    second-stage variables by sampling demand\n\n    \"\"\"\n\n    N, h, p, C, P, RETAILER_DEMANDS = get_transshipment_variables()\n\n    for _ in range(n):\n\n        # Get Second-stage variables\n        s, p_s = random_demand(P=P, retailer_demands=RETAILER_DEMANDS)\n\n        # Get scenario-dependent variables\n        d_s, C_s, D_s, \u03be_s = get_second_stage_variables(s)\n\n        yield p_s, d_s, C_s, D_s, \u03be_s\n\n\ndef s_gen_benders():\n    \"\"\"Function that generates the scenario dependent\n    second-stage variables by enumerating all combinations of demand\n\n    \"\"\"\n\n    N, h, p, C, P, RETAILER_DEMANDS = get_transshipment_variables()\n\n    # Get Second-stage variables\n    for s in itertools.product(*RETAILER_DEMANDS):\n\n        p_s = np.prod(\n            [\n                P[np.argwhere(retailer_demand == D_i)[0][0]]\n                for retailer_demand, D_i in zip(RETAILER_DEMANDS, s)\n            ]\n        )\n\n        # Get scenario-dependent variables\n        d_s, C_s, D_s, \u03be_s = get_second_stage_variables(s)\n\n        yield p_s, d_s, C_s, D_s, \u03be_s\n```\n\n### 4.2. Stochastic Gradient Descent\n\n\n```python\nsgd = StochasticGradientDescent(\n    c=np.array([0.0] * 4),\n    x0=np.array([0.0] * 4),\n    first_stage_constraints=None,\n    s_gen=s_gen_sgd,\n    n=100,\n    \u03b1=1e-01,\n    \u03b5=1e-01\n)\n\nsgd.solve()\n```\n\n    ==================== Iteration 0====================\n    Current Primal Objective Found: 15740.704 | Best Primal Objective Found: inf\n    ==================== Iteration 50====================\n    Current Primal Objective Found: 2404.495 | Best Primal Objective Found: 2729.085\n    ==================== Iteration 100====================\n    Current Primal Objective Found: 289.641 | Best Primal Objective Found: 264.472\n    ==================== Iteration 150====================\n    Current Primal Objective Found: 262.191 | Best Primal Objective Found: 229.16\n    ==================== Iteration 200====================\n    Current Primal Objective Found: 292.347 | Best Primal Objective Found: 197.497\n    ==================== Iteration 250====================\n    Current Primal Objective Found: 290.276 | Best Primal Objective Found: 197.497\n    ==================== Iteration 300====================\n    Current Primal Objective Found: 177.405 | Best Primal Objective Found: 167.574\n    ==================== Iteration 350====================\n    Current Primal Objective Found: 165.722 | Best Primal Objective Found: 156.476\n    ==================== Iteration 400====================\n    Current Primal Objective Found: 182.0 | Best Primal Objective Found: 130.407\n    ==================== Iteration 450====================\n    Current Primal Objective Found: 199.385 | Best Primal Objective Found: 130.407\n    Early Stopping condition satisfied.\n    Optimal primal objective of first stage problem: 130.407\n    Optimal first-stage decision variables: [100.661 200.54  150.724 170.486]\n    Number of iterations for convergence: 499\n\n\n\n\n\n    (130.407359788351,\n     array([100.66088181, 200.53971283, 150.72409382, 170.48564625]),\n     499)\n\n\n\n### 4.3. Benders\n\n\n```python\nbenders = Benders(\n    c=np.array([0] * 4),\n    first_stage_constraints=None,\n    s_gen=s_gen_benders,\n)\n\nbenders.solve()\n```\n\n    ==================== Iteration 0====================\n    Lower Bound: 0.0 | Upper Bound: 2480.0\n    ==================== Iteration 1====================\n    Lower Bound: 0.0 | Upper Bound: 1041.897\n    ==================== Iteration 2====================\n    Lower Bound: 0.0 | Upper Bound: 115.972\n    ==================== Iteration 3====================\n    Lower Bound: 0.0 | Upper Bound: 115.972\n    ==================== Iteration 4====================\n    Lower Bound: 0.0 | Upper Bound: 115.972\n    ==================== Iteration 5====================\n    Lower Bound: 48.645 | Upper Bound: 115.972\n    ==================== Iteration 6====================\n    Lower Bound: 49.022 | Upper Bound: 115.972\n    ==================== Iteration 7====================\n    Lower Bound: 51.52 | Upper Bound: 115.972\n    ==================== Iteration 8====================\n    Lower Bound: 66.869 | Upper Bound: 92.555\n    ==================== Iteration 9====================\n    Lower Bound: 67.483 | Upper Bound: 92.555\n    ==================== Iteration 10====================\n    Lower Bound: 70.326 | Upper Bound: 92.555\n    ==================== Iteration 11====================\n    Lower Bound: 71.874 | Upper Bound: 82.007\n    ==================== Iteration 12====================\n    Lower Bound: 73.429 | Upper Bound: 82.007\n    ==================== Iteration 13====================\n    Lower Bound: 79.194 | Upper Bound: 80.918\n    ==================== Iteration 14====================\n    Lower Bound: 79.771 | Upper Bound: 80.918\n    ==================== Iteration 15====================\n    Lower Bound: 80.473 | Upper Bound: 80.918\n    ==================== Iteration 16====================\n    Lower Bound: 80.523 | Upper Bound: 80.918\n    ==================== Iteration 17====================\n    Lower Bound: 80.523 | Upper Bound: 80.523\n    Optimal primal objective of first stage problem: 80.523\n    Optimal first-stage decision variables: [108.508 214.065 159.724 187.702]\n    Number of iterations for convergence: 18\n\n\n\n\n\n    (80.52286246994309,\n     array([108.50808924, 214.06507897, 159.7243887 , 187.70244296]),\n     18)\n\n\n\n### 4.4. Stochastic Gradient Descent Vs. Benders\n\n\n```python\ndef run_experiment_sgd(n_scenario, \u03b1, \u03b5):\n\n    optimal_obj_val, optimal_order_up_to_quantity, k = StochasticGradientDescent(\n        c=np.array([0.0] * 4),\n        x0=np.array([0.0] * 4),\n        first_stage_constraints=None,\n        s_gen=s_gen_sgd,\n        n=n_scenario,\n        \u03b1=\u03b1,\n        \u03b5=\u03b5,\n        log=False,\n    ).solve()\n\n    return optimal_obj_val, optimal_order_up_to_quantity, k\n\n\ndef run_experiment_grid_sgd(\n    n_experiments=100, n_scenarios=[50, 100, 1000], \u03b1s=[1e0, 1e-01, 1e-02], \u03b5s=[1e-03, 1e-04, 1e-05]\n):\n\n    results = []\n\n    for n_scenario in n_scenarios:\n\n        for \u03b1 in \u03b1s:\n            \n            for \u03b5 in \u03b5s:\n\n                (\n                    optimal_obj_vals_sgd,\n                    optimal_order_up_to_quantities_sgd,\n                    n_iterations_sgd,\n                    experiment_times,\n                ) = ([], [], [], [])\n\n                # Run Experiments\n                for k in range(n_experiments):\n\n                    if k % 10 == 0:\n                        print(\n                            f\"Experimenting with n_scenario={n_scenario} | \u03b1={\u03b1} | \u03b5={\u03b5} | k={k}...\"\n                        )\n\n                    start = time.time()\n                    optimal_obj_val, optimal_order_up_to_quantity, n_iterations = run_experiment_sgd(\n                        n_scenario, \u03b1, \u03b5\n                    )\n                    end = time.time()\n\n                    optimal_obj_vals_sgd.append(optimal_obj_val)\n                    optimal_order_up_to_quantities_sgd.append(optimal_order_up_to_quantity)\n                    n_iterations_sgd.append(n_iterations)\n                    experiment_times.append(end - start)\n\n                optimal_obj_vals_sgd = np.round(np.array(optimal_obj_vals_sgd), 2)\n                optimal_order_up_to_quantities_sgd = np.round(np.array(\n                    optimal_order_up_to_quantities_sgd\n                ), 2)\n                n_iterations_sgd = np.array(n_iterations_sgd)\n                experiment_times = np.round(np.array(experiment_times), 2)\n\n                results.append(\n                    (\n                        n_scenario,\n                        \u03b1,\n                        \u03b5,\n                        optimal_obj_vals_sgd.mean(axis=0),\n                        optimal_obj_vals_sgd.std(axis=0),\n                        optimal_obj_vals_sgd.max(axis=0),\n                        optimal_obj_vals_sgd.min(axis=0),\n                        optimal_order_up_to_quantities_sgd.mean(axis=0),\n                        optimal_order_up_to_quantities_sgd.std(axis=0),\n                        optimal_order_up_to_quantities_sgd.max(axis=0),\n                        optimal_order_up_to_quantities_sgd.min(axis=0),\n                        n_iterations_sgd.mean(axis=0),\n                        n_iterations_sgd.std(axis=0),\n                        n_iterations_sgd.max(axis=0),\n                        n_iterations_sgd.min(axis=0),\n                        experiment_times.mean(axis=0),\n                        experiment_times.std(axis=0),\n                        experiment_times.max(axis=0),\n                        experiment_times.min(axis=0),\n                    )\n                )\n\n                pd.DataFrame(\n                    results,\n                    columns=[\n                        \"Number of Scenarios\",\n                        \"Learning rate \u03b1\",\n                        \"Tolerance for Subgradient Early Stopping \u03b5\",\n                        \"Mean(Objective Value)\",\n                        \"Std(Objective Value)\",\n                        \"Max(Objective Value)\",\n                        \"Min(Objective Value)\",\n                        \"Mean(Optimal Order-Up-To Quantitites)\",\n                        \"Std(Optimal Order-Up-To Quantitites)\",\n                        \"Max(Optimal Order-Up-To Quantitites)\",\n                        \"Min(Optimal Order-Up-To Quantitites)\",\n                        \"Mean(Number of Iterations)\",\n                        \"Std(Number of Iterations)\",\n                        \"Max(Number of Iterations)\",\n                        \"Min(Number of Iterations)\",\n                        \"Mean(Experiment Times)\",\n                        \"Std(Experiment Times)\",\n                        \"Max(Experiment Times)\",\n                        \"Min(Experiment Times)\",\n                    ],\n                ).to_csv(\"sgd_results.csv\")\n\n    return pd.DataFrame(\n        results,\n        columns=[\n            \"Number of Scenarios\",\n            \"Learning rate \u03b1\",\n            \"Tolerance for Subgradient Early Stopping \u03b5\",\n            \"Mean(Objective Value)\",\n            \"Std(Objective Value)\",\n            \"Max(Objective Value)\",\n            \"Min(Objective Value)\",\n            \"Mean(Optimal Order-Up-To Quantitites)\",\n            \"Std(Optimal Order-Up-To Quantitites)\",\n            \"Max(Optimal Order-Up-To Quantitites)\",\n            \"Min(Optimal Order-Up-To Quantitites)\",\n            \"Mean(Number of Iterations)\",\n            \"Std(Number of Iterations)\",\n            \"Max(Number of Iterations)\",\n            \"Min(Number of Iterations)\",\n            \"Mean(Experiment Times)\",\n            \"Std(Experiment Times)\",\n            \"Max(Experiment Times)\",\n            \"Min(Experiment Times)\",\n        ],\n    )\n\n\nsgd_results = run_experiment_grid_sgd(\n    n_experiments=100, n_scenarios=[10, 50, 100, 200], \u03b1s=[1e-01], \u03b5s=[1e-01]\n)\nsgd_results\n```\n\n    Experimenting with n_scenario=10 | \u03b1=0.1 | \u03b5=0.1 | k=0...\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Experimenting with n_scenario=10 | \u03b1=0.1 | \u03b5=0.1 | k=10...\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Experimenting with n_scenario=10 | \u03b1=0.1 | \u03b5=0.1 | k=20...\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Experimenting with n_scenario=10 | \u03b1=0.1 | \u03b5=0.1 | k=30...\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Experimenting with n_scenario=10 | \u03b1=0.1 | \u03b5=0.1 | k=40...\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Experimenting with n_scenario=10 | \u03b1=0.1 | \u03b5=0.1 | k=50...\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Experimenting with n_scenario=10 | \u03b1=0.1 | \u03b5=0.1 | k=60...\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Experimenting with n_scenario=10 | \u03b1=0.1 | \u03b5=0.1 | k=70...\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Experimenting with n_scenario=10 | \u03b1=0.1 | \u03b5=0.1 | k=80...\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Experimenting with n_scenario=10 | \u03b1=0.1 | \u03b5=0.1 | k=90...\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Experimenting with n_scenario=50 | \u03b1=0.1 | \u03b5=0.1 | k=0...\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n    Early Stopping condition satisfied.\n\n\n\n```python\npd.read_csv(\"./sgd_results.csv\", index_col=[0])\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Number of Scenarios</th>\n      <th>Learning rate \u03b1</th>\n      <th>Tolerance for Subgradient Early Stopping \u03b5</th>\n      <th>Mean(Objective Value)</th>\n      <th>Std(Objective Value)</th>\n      <th>Max(Objective Value)</th>\n      <th>Min(Objective Value)</th>\n      <th>Mean(Optimal Order-Up-To Quantitites)</th>\n      <th>Std(Optimal Order-Up-To Quantitites)</th>\n      <th>Max(Optimal Order-Up-To Quantitites)</th>\n      <th>Min(Optimal Order-Up-To Quantitites)</th>\n      <th>Mean(Number of Iterations)</th>\n      <th>Std(Number of Iterations)</th>\n      <th>Max(Number of Iterations)</th>\n      <th>Min(Number of Iterations)</th>\n      <th>Mean(Experiment Times)</th>\n      <th>Std(Experiment Times)</th>\n      <th>Max(Experiment Times)</th>\n      <th>Min(Experiment Times)</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>10</td>\n      <td>0.1</td>\n      <td>0.1</td>\n      <td>16.5198</td>\n      <td>6.759651</td>\n      <td>55.55</td>\n      <td>8.53</td>\n      <td>[148.4059 157.5988 154.6814 157.4469]</td>\n      <td>[1.96487307 2.73314115 2.02832641 2.73398928]</td>\n      <td>[150.08 162.47 156.3  162.31]</td>\n      <td>[138.58 144.07 143.93 143.92]</td>\n      <td>684.31</td>\n      <td>78.390267</td>\n      <td>980</td>\n      <td>560</td>\n      <td>28.8340</td>\n      <td>3.309319</td>\n      <td>41.45</td>\n      <td>23.71</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>50</td>\n      <td>0.1</td>\n      <td>0.1</td>\n      <td>53.6970</td>\n      <td>4.858717</td>\n      <td>64.30</td>\n      <td>43.98</td>\n      <td>[100.6798 200.597  150.6084 170.606 ]</td>\n      <td>[0.37629504 0.35315011 0.34831227 0.34898424]</td>\n      <td>[101.65 201.48 151.52 171.53]</td>\n      <td>[100.02 200.01 150.02 170.03]</td>\n      <td>786.58</td>\n      <td>40.985163</td>\n      <td>915</td>\n      <td>729</td>\n      <td>166.0559</td>\n      <td>8.613365</td>\n      <td>193.08</td>\n      <td>153.22</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>100</td>\n      <td>0.1</td>\n      <td>0.1</td>\n      <td>127.4597</td>\n      <td>9.509603</td>\n      <td>152.36</td>\n      <td>103.51</td>\n      <td>[101.2032 201.0891 151.1315 171.1326]</td>\n      <td>[0.74875481 0.63293459 0.63881668 0.62607926]</td>\n      <td>[104.29 202.48 152.68 172.56]</td>\n      <td>[100.04 200.01 150.03 170.04]</td>\n      <td>598.64</td>\n      <td>205.785933</td>\n      <td>1469</td>\n      <td>360</td>\n      <td>253.2370</td>\n      <td>87.046833</td>\n      <td>620.72</td>\n      <td>152.10</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndef run_experiment_grid_benders(n_experiments=100):\n\n    results = []\n\n    (\n        optimal_obj_vals_benders,\n        optimal_order_up_to_quantities_benders,\n        n_iterations_benders,\n        experiment_times,\n    ) = ([], [], [], [])\n\n    # Run Experiments\n    for k in range(n_experiments):\n\n        if k % 10 == 0:\n            print(f\"Experimenting with k={k}...\")\n\n        start = time.time()\n        optimal_obj_val, optimal_order_up_to_quantity, n_iterations = Benders(\n            c=np.array([0] * 4),\n            first_stage_constraints=None,\n            s_gen=s_gen_benders,\n            log=False,\n        ).solve()\n        end = time.time()\n\n        optimal_obj_vals_benders.append(optimal_obj_val)\n        optimal_order_up_to_quantities_benders.append(optimal_order_up_to_quantity)\n        n_iterations_benders.append(n_iterations)\n        experiment_times.append(end - start)\n\n    optimal_obj_vals_benders = np.round(np.array(optimal_obj_vals_benders), 2)\n    optimal_order_up_to_quantities_benders = np.round(np.array(\n        optimal_order_up_to_quantities_benders\n    ), 2)\n    n_iterations_benders = np.array(n_iterations_benders)\n    experiment_times = np.round(np.array(experiment_times), 2)\n\n    results.append(\n        (\n            5 ** 4,\n            1,\n            optimal_obj_vals_benders.mean(axis=0),\n            optimal_obj_vals_benders.std(axis=0),\n            optimal_obj_vals_benders.max(axis=0),\n            optimal_obj_vals_benders.min(axis=0),\n            optimal_order_up_to_quantities_benders.mean(axis=0),\n            optimal_order_up_to_quantities_benders.std(axis=0),\n            optimal_order_up_to_quantities_benders.max(axis=0),\n            optimal_order_up_to_quantities_benders.min(axis=0),\n            n_iterations_benders.mean(axis=0),\n            n_iterations_benders.std(axis=0),\n            n_iterations_benders.max(axis=0),\n            n_iterations_benders.min(axis=0),\n            experiment_times.mean(axis=0),\n            experiment_times.std(axis=0),\n            experiment_times.max(axis=0),\n            experiment_times.min(axis=0),\n        )\n    )\n\n    return pd.DataFrame(\n        results,\n        columns=[\n            \"Number of Scenarios\",\n            \"Number of Iterations\",\n            \"Mean(Objective Value)\",\n            \"Std(Objective Value)\",\n            \"Max(Objective Value)\",\n            \"Min(Objective Value)\",\n            \"Mean(Optimal Order-Up-To Quantitites)\",\n            \"Std(Optimal Order-Up-To Quantitites)\",\n            \"Max(Optimal Order-Up-To Quantitites)\",\n            \"Min(Optimal Order-Up-To Quantitites)\",\n            \"Mean(Number of Iterations)\",\n            \"Std(Number of Iterations)\",\n            \"Max(Number of Iterations)\",\n            \"Min(Number of Iterations)\",\n            \"Mean(Experiment Times)\",\n            \"Std(Experiment Times)\",\n            \"Max(Experiment Times)\",\n            \"Min(Experiment Times)\",\n        ],\n    )\n\n\nbenders_results = run_experiment_grid_benders(n_experiments=100)\nbenders_results.to_csv(\"benders_results.csv\")\nbenders_results\n```\n\n    Experimenting with k=0...\n    Experimenting with k=10...\n    Experimenting with k=20...\n    Experimenting with k=30...\n    Experimenting with k=40...\n    Experimenting with k=50...\n    Experimenting with k=60...\n    Experimenting with k=70...\n    Experimenting with k=80...\n    Experimenting with k=90...\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Number of Scenarios</th>\n      <th>Number of Iterations</th>\n      <th>Mean(Objective Value)</th>\n      <th>Std(Objective Value)</th>\n      <th>Max(Objective Value)</th>\n      <th>Min(Objective Value)</th>\n      <th>Mean(Optimal Order-Up-To Quantitites)</th>\n      <th>Std(Optimal Order-Up-To Quantitites)</th>\n      <th>Max(Optimal Order-Up-To Quantitites)</th>\n      <th>Min(Optimal Order-Up-To Quantitites)</th>\n      <th>Mean(Number of Iterations)</th>\n      <th>Std(Number of Iterations)</th>\n      <th>Max(Number of Iterations)</th>\n      <th>Min(Number of Iterations)</th>\n      <th>Mean(Experiment Times)</th>\n      <th>Std(Experiment Times)</th>\n      <th>Max(Experiment Times)</th>\n      <th>Min(Experiment Times)</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>625</td>\n      <td>1</td>\n      <td>80.52</td>\n      <td>1.421085e-14</td>\n      <td>80.52</td>\n      <td>80.52</td>\n      <td>[108.51000000000016, 214.0699999999998, 159.71...</td>\n      <td>[1.5631940186722204e-13, 1.9895196601282805e-1...</td>\n      <td>[108.51, 214.07, 159.72, 187.7]</td>\n      <td>[108.51, 214.07, 159.72, 187.7]</td>\n      <td>18.0</td>\n      <td>0.0</td>\n      <td>18</td>\n      <td>18</td>\n      <td>38.7504</td>\n      <td>0.110408</td>\n      <td>39.2</td>\n      <td>38.53</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n#### 4.4.1 Comparing Mean(Optimal Order-Up-To Quantities)\n\n\n```python\npd.options.display.max_colwidth = 100\n```\n\n\n```python\nimport pandas as pd\n```\n\n\n```python\npd.read_csv(\"./sgd_results.csv\", index_col=[0])\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Number of Scenarios</th>\n      <th>Learning rate \u03b1</th>\n      <th>Tolerance for Subgradient Early Stopping \u03b5</th>\n      <th>Mean(Objective Value)</th>\n      <th>Std(Objective Value)</th>\n      <th>Max(Objective Value)</th>\n      <th>Min(Objective Value)</th>\n      <th>Mean(Optimal Order-Up-To Quantitites)</th>\n      <th>Std(Optimal Order-Up-To Quantitites)</th>\n      <th>Max(Optimal Order-Up-To Quantitites)</th>\n      <th>Min(Optimal Order-Up-To Quantitites)</th>\n      <th>Mean(Number of Iterations)</th>\n      <th>Std(Number of Iterations)</th>\n      <th>Max(Number of Iterations)</th>\n      <th>Min(Number of Iterations)</th>\n      <th>Mean(Experiment Times)</th>\n      <th>Std(Experiment Times)</th>\n      <th>Max(Experiment Times)</th>\n      <th>Min(Experiment Times)</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>10</td>\n      <td>0.1</td>\n      <td>0.1</td>\n      <td>16.5198</td>\n      <td>6.759651</td>\n      <td>55.55</td>\n      <td>8.53</td>\n      <td>[148.4059 157.5988 154.6814 157.4469]</td>\n      <td>[1.96487307 2.73314115 2.02832641 2.73398928]</td>\n      <td>[150.08 162.47 156.3  162.31]</td>\n      <td>[138.58 144.07 143.93 143.92]</td>\n      <td>684.31</td>\n      <td>78.390267</td>\n      <td>980</td>\n      <td>560</td>\n      <td>28.8340</td>\n      <td>3.309319</td>\n      <td>41.45</td>\n      <td>23.71</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>50</td>\n      <td>0.1</td>\n      <td>0.1</td>\n      <td>53.6970</td>\n      <td>4.858717</td>\n      <td>64.30</td>\n      <td>43.98</td>\n      <td>[100.6798 200.597  150.6084 170.606 ]</td>\n      <td>[0.37629504 0.35315011 0.34831227 0.34898424]</td>\n      <td>[101.65 201.48 151.52 171.53]</td>\n      <td>[100.02 200.01 150.02 170.03]</td>\n      <td>786.58</td>\n      <td>40.985163</td>\n      <td>915</td>\n      <td>729</td>\n      <td>166.0559</td>\n      <td>8.613365</td>\n      <td>193.08</td>\n      <td>153.22</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>100</td>\n      <td>0.1</td>\n      <td>0.1</td>\n      <td>127.4597</td>\n      <td>9.509603</td>\n      <td>152.36</td>\n      <td>103.51</td>\n      <td>[101.2032 201.0891 151.1315 171.1326]</td>\n      <td>[0.74875481 0.63293459 0.63881668 0.62607926]</td>\n      <td>[104.29 202.48 152.68 172.56]</td>\n      <td>[100.04 200.01 150.03 170.04]</td>\n      <td>598.64</td>\n      <td>205.785933</td>\n      <td>1469</td>\n      <td>360</td>\n      <td>253.2370</td>\n      <td>87.046833</td>\n      <td>620.72</td>\n      <td>152.10</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\npd.read_csv(\"./benders_results.csv\", index_col=[0])\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Number of Scenarios</th>\n      <th>Number of Iterations</th>\n      <th>Mean(Objective Value)</th>\n      <th>Std(Objective Value)</th>\n      <th>Max(Objective Value)</th>\n      <th>Min(Objective Value)</th>\n      <th>Mean(Optimal Order-Up-To Quantitites)</th>\n      <th>Std(Optimal Order-Up-To Quantitites)</th>\n      <th>Max(Optimal Order-Up-To Quantitites)</th>\n      <th>Min(Optimal Order-Up-To Quantitites)</th>\n      <th>Mean(Number of Iterations)</th>\n      <th>Std(Number of Iterations)</th>\n      <th>Max(Number of Iterations)</th>\n      <th>Min(Number of Iterations)</th>\n      <th>Mean(Experiment Times)</th>\n      <th>Std(Experiment Times)</th>\n      <th>Max(Experiment Times)</th>\n      <th>Min(Experiment Times)</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>625</td>\n      <td>1</td>\n      <td>80.52</td>\n      <td>1.421085e-14</td>\n      <td>80.52</td>\n      <td>80.52</td>\n      <td>[108.51 214.07 159.72 187.7 ]</td>\n      <td>[1.56319402e-13 1.98951966e-13 2.84217094e-13 ...</td>\n      <td>[108.51 214.07 159.72 187.7 ]</td>\n      <td>[108.51 214.07 159.72 187.7 ]</td>\n      <td>18.0</td>\n      <td>0.0</td>\n      <td>18</td>\n      <td>18</td>\n      <td>38.7504</td>\n      <td>0.110408</td>\n      <td>39.2</td>\n      <td>38.53</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n#### 4.4.2 Conclusion\n\nWe observe that benders goes through fewer iterations, and overall has a more accurate result.\n", "meta": {"hexsha": "0c7ed42367354bb57a8193196d4ba4ddba690300", "size": 182683, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "project2.ipynb", "max_stars_repo_name": "Yiyi-cmd/ISE533-Final-Project", "max_stars_repo_head_hexsha": "a51ec977eb2658be5f9a16826959ec639b5626b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-26T00:24:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T00:24:06.000Z", "max_issues_repo_path": "project2.ipynb", "max_issues_repo_name": "Yiyi-cmd/ISE533-Final-Project", "max_issues_repo_head_hexsha": "a51ec977eb2658be5f9a16826959ec639b5626b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project2.ipynb", "max_forks_repo_name": "Yiyi-cmd/ISE533-Final-Project", "max_forks_repo_head_hexsha": "a51ec977eb2658be5f9a16826959ec639b5626b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-26T00:24:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T00:24:07.000Z", "avg_line_length": 54.6464253664, "max_line_length": 801, "alphanum_fraction": 0.5672284777, "converted": true, "num_tokens": 43697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.05033063313165513, "lm_q1q2_score": 0.02379045864917829}}
{"text": "### Checklist for submission\n\nIt is extremely important to make sure that:\n\n1. Everything runs as expected (no bugs when running cells);\n2. The output from each cell corresponds to its code (don't change any cell's contents without rerunning it afterwards);\n3. All outputs are present (don't delete any of the outputs);\n4. Fill in all the places that say `# YOUR CODE HERE`, or \"**Your answer:** (fill in here)\".\n5. Never copy/paste any notebook cells. Inserting new cells is allowed, but it should not be necessary.\n6. The notebook contains some hidden metadata which is important during our grading process. **Make sure not to corrupt any of this metadata!** The metadata may for example be corrupted if you copy/paste any notebook cells, or if you perform an unsuccessful git merge / git pull. It may also be pruned completely if using Google Colab, so watch out for this. Searching for \"nbgrader\" when opening the notebook in a text editor should take you to the important metadata entries.\n7. Although we will try our very best to avoid this, it may happen that bugs are found after an assignment is released, and that we will push an updated version of the assignment to GitHub. If this happens, it is important that you update to the new version, while making sure the notebook metadata is properly updated as well. The safest way to make sure nothing gets messed up is to start from scratch on a clean updated version of the notebook, copy/pasting your code from the cells of the previous version into the cells of the new version.\n8. If you need to have multiple parallel versions of this notebook, make sure not to move them to another directory.\n9. Although not forced to work exclusively in the course `conda` environment, you need to make sure that the notebook will run in that environment, i.e. that you have not added any additional dependencies.\n\n**FOR HA1, HA2, HA3 ONLY:** Failing to meet any of these requirements might lead to either a subtraction of POEs (at best) or a request for resubmission (at worst).\n\nWe advise you to perform the following steps before submission to ensure that requirements 1, 2, and 3 are always met: **Restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart) and then **run all cells** (in the menubar, select Cell$\\rightarrow$Run All). This might require a bit of time, so plan ahead for this (and possibly use Google Cloud's GPU in HA1 and HA2 for this step). Finally press the \"Save and Checkout\" button before handing in, to make sure that all your changes are saved to this .ipynb file.\n\n### Fill in name of notebook file\nThis might seem silly, but the version check below needs to know the filename of the current notebook, which is not trivial to find out programmatically.\n\nYou might want to have several parallel versions of the notebook, and it is fine to rename the notebook as long as it stays in the same directory. **However**, if you do rename it, you also need to update its own filename below:\n\n\n```python\nnb_fname = \"IHA1.ipynb\"\n```\n\n### Fill in group number and member names (use NAME2 and GROUP only for HA1, HA2 and HA3):\n\n\n```python\nNAME1 = \"Aladdin Persson\" \nNAME2 = \"\"\nGROUP = \"\"\n```\n\n### Check Python version\n\n\n```python\nfrom platform import python_version_tuple\nassert python_version_tuple()[:2] == ('3','7'), \"You are not running Python 3.7. Make sure to run Python through the course Conda environment.\"\n```\n\n### Check that notebook server has access to all required resources, and that notebook has not moved\n\n\n```python\nimport os\nnb_dirname = os.path.abspath('')\nassignment_name = os.path.basename(nb_dirname)\nassert assignment_name in ['IHA1', 'IHA2', 'HA1', 'HA2', 'HA3'], \\\n    '[ERROR] The notebook appears to have been moved from its original directory'\n```\n\n### Verify correct nb_fname\n\n\n```python\nfrom IPython.display import display, HTML\ntry:\n    display(HTML(r''.format(nb_fname=nb_fname)))\nexcept NameError:\n    assert False, 'Make sure to fill in the nb_fname variable above!'\n```\n\n\n\n\n\n### Verify that your notebook is up-to-date and not corrupted in any way\n\n\n```python\nimport sys\nsys.path.append('..')\nfrom ha_utils import check_notebook_uptodate_and_not_corrupted\ncheck_notebook_uptodate_and_not_corrupted(nb_dirname, nb_fname)\n```\n\n    Matching current notebook against the following URL:\n    http://raw.githubusercontent.com/JulianoLagana/deep-machine-learning/master/home-assignments/IHA1/IHA1.ipynb\n    [SUCCESS] No major notebook mismatch found when comparing to latest GitHub version. (There might be minor updates, but even that is the case, submitting your work based on this notebook version would be acceptable.)\n\n\n# IHA1 - Assignment\n\nWelcome to the first individual home assignment!  \n\nThis assignment consists of two parts:\n * Python and NumPy exercises;\n * Build a deep neural network for forward propagation.\n  \nThe focus of this assignment is for you to gain practical knowledge with implementing forward propagation of deep neural networks without using any deep learning framework. You will also gain practical knowledge in two of Python's scientific libraries [NumPy](https://docs.scipy.org/doc/numpy-1.13.0/index.html) and [Matplotlib](https://matplotlib.org/devdocs/index.html).  \n\nSkeleton code is provided for most tasks and every part you are expected to implement is marked with **TODO**. Throughout the assignment you will also need to submit written answers to some questions. These questions are mainly to make you reflect on some particular topics and your answers will not be graded in detail. \n\nWe expect you to search and learn by yourself any commands you think are useful for these tasks. Don't limit yourself to what was taught in CL1. Use the help function, [stackoverflow](https://stackoverflow.com/), google, the [python documentation](https://docs.python.org/3.5/library/index.html) and the [NumPy](https://docs.scipy.org/doc/numpy-1.13.0/index.html) documentation to your advantage.  \n\n**IMPORTANT NOTE**: The tests available are not exhaustive, meaning that if you pass a test you have avoided the most common mistakes, but it is still not guaranteed that your solution is 100% correct.  \n\nLets start by importing the necessary libraries below.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom utils.tests.iha1Tests import *\n```\n\n## 1. Lists and arrays introduction\nFirst, we will warm up with a Python exercise and few NumPy exercises.\n\n### 1.1 List comprehensions\nExamine the code snippet provided below.\n\n\n```python\nmyList = []\nfor i in range(25):\n    if i % 2 == 0:\n        myList.append(i**2)\n        \nprint(myList)\n```\n\n    [0, 4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576]\n\n\nThis is not a very \"[pythonic](http://docs.python-guide.org/en/latest/writing/style/)\" way of writing. Lets re-write the code above using a [list comprehension](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions). The result will be less code, more readable and elegant. Your solution should be able to fit into one line of code.\n\n\n```python\nmyList = [i**2 for i in range(25) if i % 2 == 0] # TODO\n# YOUR CODE HERE\nprint(myList)\n```\n\n    [0, 4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576]\n\n\n\n```python\n# sample output from cell above for reference\n# [0, 4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576]\n```\n\n### 1.2 Numpy array vs numpy vectors\nRun the cell below to create a numpy array.   \n\n\n```python\nmyArr = np.array([1, 9, 25, 49, 81, 121, 169, 225, 289, 361, 441, 529])\nprint(myArr)\nprint(myArr.shape)\n```\n\n    [  1   9  25  49  81 121 169 225 289 361 441 529]\n    (12,)\n\n\nOne of the core features of numpy is to efficiently perform linear algebra operations.\nThere are two types of one-dimensional representations in numpy: arrays of shape (x,) and vectors of shape (x,1).\n\nThe above result indicates that **myArr** is an array of 12 elements with shape (12,).  \n\nNumpy's arrays and vectors both have the type of `numpy.ndarray` but have in some cases different characteristics and it is important to separate the two types because it will save a lot of debugging time later on. Read more about numpy shapes [here](https://stackoverflow.com/a/22074424).\n\nRun the code below to see how the transpose operation behaves differently between an array and vector.\n\n\n```python\n# print the shape of an array and the shape of a transposed array\nprint('myArr is an array of shape:')\nprint(myArr.shape)\nprint('The transpose of myArr has the shape:')\nprint(myArr.T.shape)\n\n# print the shape of a vector and the transpose of a vector\nmyVec = myArr.reshape(12,1)\nprint('myVec is a vector of shape:')\nprint(myVec.shape)\nprint('The transpose of myVec has the shape:')\nprint(myVec.T.shape)\n```\n\n    myArr is an array of shape:\n    (12,)\n    The transpose of myArr has the shape:\n    (12,)\n    myVec is a vector of shape:\n    (12, 1)\n    The transpose of myVec has the shape:\n    (1, 12)\n\n\n### 1.3 Numpy exercises\nNow run the cell below to create the numpy array `numbers` and then complete the exercises sequentially.\n\n\n```python\nnumbers = np.arange(24)\nprint(numbers)\n```\n\n    [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]\n\n\n\n```python\n# TODO: reshape numbers into a 6x4 matrix\nnumbers = numbers.reshape(6, 4)\n# YOUR CODE HERE\nprint(numbers)\n\n```\n\n    [[ 0  1  2  3]\n     [ 4  5  6  7]\n     [ 8  9 10 11]\n     [12 13 14 15]\n     [16 17 18 19]\n     [20 21 22 23]]\n\n\n\n```python\n# sample output from cell above for reference\n#  [[ 0  1  2  3]\n#   [ 4  5  6  7]\n#   [ 8  9 10 11]\n#   [12 13 14 15]\n#   [16 17 18 19]\n#   [20 21 22 23]]\n```\n\n\n```python\n# test case\ntest_numpy_reshape(numbers)\n```\n\n    Test passed\n\n\n\n```python\n# TODO: set the element of the last row of the last column to zero\n# Hint: Try what happends when indices are negative\nnumbers[5,3] = 0\n# YOUR CODE HERE\nprint(numbers)\n```\n\n    [[ 0  1  2  3]\n     [ 4  5  6  7]\n     [ 8  9 10 11]\n     [12 13 14 15]\n     [16 17 18 19]\n     [20 21 22  0]]\n\n\n\n```python\n# sample output from cell above for reference\n#  [[ 0  1  2  3]\n#   [ 4  5  6  7]\n#   [ 8  9 10 11]\n#   [12 13 14 15]\n#   [16 17 18 19]\n#   [20 21 22  0]]\n```\n\n\n```python\n# test case\ntest_numpy_neg_ix(numbers)\n```\n\n    Test passed\n\n\n\n```python\n# TODO: set every element of the 0th row to 0\nnumbers[0, :] = 0\n# YOUR CODE HERE\nprint(numbers)\n```\n\n    [[ 0  0  0  0]\n     [ 4  5  6  7]\n     [ 8  9 10 11]\n     [12 13 14 15]\n     [16 17 18 19]\n     [20 21 22  0]]\n\n\n\n```python\n# sample output from cell above for reference\n#  [[ 0  0  0  0]\n#   [ 4  5  6  7]\n#   [ 8  9 10 11]\n#   [12 13 14 15]\n#   [16 17 18 19]\n#   [20 21 22  0]]\n```\n\n\n```python\n# test case\ntest_numpy_row_ix(numbers)\n```\n\n    Test passed\n\n\n\n```python\n# TODO: append a 1x4 row vector of zeros to `numbers`, \n# resulting in a 7x4 matrix where the new row of zeros is the last row\n# Hint: A new matrix must be created in the procedure. Numpy arrays are not dynamic.\nprint(numbers)\nprint(numbers.shape)\nnumbers = np.append(numbers, [[0,0,0,0]], axis=0)\n# YOUR CODE HERE\nprint(numbers)\nprint(numbers.shape)\n```\n\n    [[ 0  0  0  0]\n     [ 4  5  6  7]\n     [ 8  9 10 11]\n     [12 13 14 15]\n     [16 17 18 19]\n     [20 21 22  0]]\n    (6, 4)\n    [[ 0  0  0  0]\n     [ 4  5  6  7]\n     [ 8  9 10 11]\n     [12 13 14 15]\n     [16 17 18 19]\n     [20 21 22  0]\n     [ 0  0  0  0]]\n    (7, 4)\n\n\n\n```python\n# sample output from cell above for reference\n#   [[ 0  0  0  0]\n#    [ 4  5  6  7]\n#    [ 8  9 10 11]\n#    [12 13 14 15]\n#    [16 17 18 19]\n#    [20 21 22  0]\n#    [ 0  0  0  0]]\n#  (7, 4)\n```\n\n\n```python\n# test case\ntest_numpy_append_row(numbers)\n```\n\n    Test passed\n\n\n\n```python\n# TODO: set all elements above 10 to the value 1\nnumbers[numbers>10] = 1\n# YOUR CODE HERE\nprint(numbers)\n```\n\n    [[ 0  0  0  0]\n     [ 4  5  6  7]\n     [ 8  9 10  1]\n     [ 1  1  1  1]\n     [ 1  1  1  1]\n     [ 1  1  1  0]\n     [ 0  0  0  0]]\n\n\n\n```python\n# sample output from cell above for reference\n#  [[ 0  0  0  0]\n#   [ 4  5  6  7]\n#   [ 8  9 10  1]\n#   [ 1  1  1  1]\n#   [ 1  1  1  1]\n#   [ 1  1  1  0]\n#   [ 0  0  0  0]]\n```\n\n\n```python\n# test case\ntest_numpy_bool_matrix(numbers)\n```\n\n    Test passed\n\n\n\n```python\n# TODO: compute the sum of every row and replace `numbers` with the answer\n# `numbers` will be a (7,) array as a result\nnumbers = numbers.sum(axis=1)\n# YOUR CODE HERE\nprint(numbers.shape)\nprint(numbers)\n```\n\n    (7,)\n    [ 0 22 28  4  4  3  0]\n\n\n\n```python\n# sample output from cell above for reference\n#   (7,)\n#   [ 0 22 28  4  4  3  0]\n```\n\n\n```python\n# test case\ntest_numpy_sum(numbers)\n```\n\n    Test passed\n\n\n## 2 Building your deep neural network\nIt is time to start implementing your first feed-forward neural network. In this lab you will only focus on implementing the forward propagation procedure. \n\nAs you know, a feed-forward neural network consists of a sequence of layers, where the output from one layer is the input to the following layer. Below you can find an example of a feed-forward neural network with 2 hidden layers (blue) and 1 output layer (red). \n\n\n\n**What would be your approach to implement a feed-forward neural network? Please provide a brief and high level explanation on how would you implement the several components of network; for instance, would you use any `python` class or only functions?** We will not grade this answer in detail. The objective with this question is to help you reflect upon how to structure the code. This will hopefully enable you to understand the code below more easily. As long as it is clear from your answer that you have tried to briefly describe the overall structure of the code, we will accept your answer.\n\n**Your answer:**  I would create a class for the neural network and create internal functions for each of the parts of the neural network, which would for example be to initialize weights, one for forward propogation, backward propogation, and a main function with the specifics of number of update steps/epochs to run it.\n\nIn this exercise, you will implement several components of a feed-forward network, such as a layers, activation functions and weight initialization functions, and from those create your own feed-forward neural network implementation. \n\nNOTE: When using a neural network, due to memory and computational constraints, you can not forward propagate the entire dataset at once. Therefore, you divide the dataset into a number of sets/parts called batches. A batch will make up for the first dimension of every input to a layer and the notation `(BATCH_SIZE, NUM_FEATURES)` simply means the dimension of a batch of samples where every sample has `NUM_FEATURES` features.\n\n### 2.1 Activation functions\nYou will start by defining a few activation functions that are later needed by the neural network.\n\n#### 2.1.1 ReLU\nThe neural network will use the ReLU activation function in every layer except for the last. ReLU does element-wise comparison of the input matrix. For example, if the input is `X`, and `X[i,j] == 2` and `X[k,l] == -1`, then after applying ReLU, `X[i,j] == 2` and `X[k,l] == 0` should be true.  \n\nThe formula for implementing ReLU for a single neuron $i$ is:\n\\begin{equation}\nrelu(z_i) = \n    \\begin{cases}\n      0, & \\text{if}\\ z_i \\leq 0 \\\\\n      z_i, & \\text{otherwise}\n    \\end{cases}\n\\end{equation}\n\nNow implement `relu` in vectorized form\n\n\n```python\ndef relu(z):\n    \"\"\" Implement the ReLU activation function\n    \n    Arguments:\n    z - the input of the activation function. Has a type of 'numpy.ndarray'\n    \n    Returns:\n    a - the output of the activation function. Has a type of numpy.ndarray and the same shape as 'z'\n    \"\"\"    \n    a = np.maximum(0, z) # TODO\n    # YOUR CODE HERE\n    \n    return a\n```\n\n\n```python\n# test case\ntest_relu(relu)\n```\n\n    Test passed\n\n\nCan you name some of the advantages of the ReLU activation function? (We will not grade this answer in detail.)\n\n**Your answer:** It seems to me that the gradients of it are incredibly simple, either 0 if it didn't allow input to be passed or 1 if it did. This probably has computational benefits which I can imagine is quite beneficial as NNs usually train a long time. Comparing to other like sigmoid or tanh the gradient is stable in the way that it's always 1 which is not the case for sigmoid for example. For large values of z the sigmoid will return a gradient close to 0, which perhaps is not intuitive because it means it'll be difficult to update.\n\n#### 2.1.2 Sigmoid\nThe sigmoid activation function is common for binary classification. This is because it squashes its input to the range [0,1].  \nImplement the activation function `sigmoid` using the formula:  \n\\begin{equation}\n    \\sigma(z) = \\frac{1}{1 + e^{-z}}\n\\end{equation}\n\n\n```python\ndef sigmoid(z):\n    \"\"\" Implement the sigmoid activation function\n    \n    Arguments:\n    z - the input of the activation function. Has a type of 'numpy.ndarray'\n    \n    Returns:\n    a - the output of the activation function. Has a type of 'numpy.ndarray' and the same shape as 'z'\n    \"\"\"\n    \n    a = 1/(1 + np.exp(-z)) # TODO\n    # YOUR CODE HERE\n    \n    return a\n```\n\n\n```python\n# test case\ntest_sigmoid(sigmoid)\n```\n\n    Test passed\n\n\nWhy is the sigmoid activation function useful for binary classification? Feel free to use some numerical examples to show how the magnitudes of the variable $z$ affect the output of the sigmoid layer. (We will not grade this answer in detail.)\n\n**Your answer:** Because it outputs values between (0,1) it is easy to use a threshold of say 0.5 and set everything above to 1 and otherwise, and hence it makes sense to use this for binary classification.\n\n#### 2.1.3 Visualization\nMake a plot using matplotlib to visualize the activation functions between the input interval [-3,3]. The plot should have the following properties\n * one plot should contain a visualization of both `ReLU` and `sigmoid`;\n * x-axis: range of values between [-3,3], **hint**: np.linspace;\n * y-axis: the value of the activation functions at a given input `x`;\n * a legend explaining which line represents which activation function.\n\n\n```python\n# TODO: make a plot of ReLU and sigmoid values in the interval [-3,3]\nx = np.arange(-3, 3, 0.01)\ny1 = relu(x)\ny2 = sigmoid(x)\nplt.plot(x,y1, label=\"ReLU\")\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\n\nplt.plot(x,y2, label=\"sigmoid\")\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"PLot of ReLU and Sigmoid between [-3, 3]\")\n\nplt.legend()\n# YOUR CODE HERE\n```\n\n#### 2.1.4 Softmax\nYou will use the softmax activation function / classifier as the final layer of your neural network later in the assignment. Implement `softmax` according to the formula below. The subtraction of the maximum value is there solely to avoid overflows in a practical implementation.\n\\begin{equation}\nsoftmax(z_i) = \\frac{e^{z_i - max(\\mathbf{z})}}{ \\sum^j e^{z_j - max(\\mathbf{z})}}\n\\end{equation}\n\n\n\n```python\ndef softmax(z):\n    \"\"\" Implement the softmax activation function\n    \n    Arguments:\n    z - the input of the activation function, shape (BATCH_SIZE, FEATURES) and type 'numpy.ndarray'\n    \n    Returns:\n    a - the output of the activation function, shape (BATCH_SIZE, FEATURES) and type 'numpy.ndarray'\n    \"\"\"\n    max_z = np.max(z, axis=1, keepdims=True)\n    z = z - max_z\n    z = np.exp(z)\n    a = z / z.sum(axis=1, keepdims=True)\n    # YOUR CODE HERE\n    \n    return a\n```\n\n\n```python\n# test case\ntest_softmax(softmax)\n```\n\n    Test passed\n\n\nWhat are the main differences between using `sigmoid` and `softmax` for multi-class classification problems? And when the number of classes is 2? (We will not grade this answer in detail.)\n\n**Your answer:** Softmax will make the output nodes actually correspond to probabilities which will make it easy to interpret (sum will be 1) which is not the case for sigmoid. When googling I found that sigmoid is simply softmax when the classes=2 but I couldn't rederive that by my own.\n\n### 2.2 Initialize weights\nYou will implement a helper function that takes the shape of a layer as input, and returns an initialized weight matrix $\\mathbf{W}$ and bias vector $\\mathbf{b}$ as output. The matrix $\\mathbf{W}$ should be sampled from a normal distribution with mean 0 and standard deviation 2, and $\\mathbf{b}$ should be initialized to all zeros.\n\n\n```python\ndef initialize_weights(layer_shape):\n    \"\"\" Implement initialization of the weight matrix and biases\n    \n    Arguments:\n    layer_shape - a tuple of length 2, type (int, int), that determines the dimensions of the weight matrix: (input_dim, output_dim)\n    \n    Returns:\n    w - a weight matrix with dimensions of 'layer_shape', (input_dim, output_dim), that is normally distributed with\n        properties mu = 0, stddev = 2. Has a type of 'numpy.ndarray'\n    b - a vector of initialized biases with shape (1,output_dim), all of value zero. Has a type of 'numpy.ndarray'\n    \"\"\"\n    w = np.random.normal(loc=0, scale=2, size=layer_shape) # TODO\n    b = np.zeros((1, layer_shape[1])) # TODO\n    # YOUR CODE HERE\n    \n    return w, b\n```\n\n\n```python\n# test case\ntest_initialize_weights(initialize_weights)\n```\n\n    Test passed\n\n\n### 2.3 Feed-forward neural network layer module\nTo build a feed-forward neural network of arbitrary depth you are going to define a neural network layer as a module that can be used to stack layers upon each other. Your task is to complete the `Layer` class by following the descriptions in the comments. Recall the formula for forward propagation of an arbitrary layer $l$:\n\n\\begin{equation}\n\\mathbf{a}^{[l]} = g(\\mathbf{z}^{[l]}) = g(\\mathbf{a}^{[l-1]}\\mathbf{w}^{[l]} +\\mathbf{b}^{[l]})\n\\end{equation}\n\nwhere $g$ is the activation function given by `activation_fn`, which can be relu, sigmoid or softmax. \n\n\n```python\nclass Layer:\n    \"\"\" \n    TODO: Build a class called Layer that satisfies the descriptions of the methods\n    Make sure to utilize the helper functions you implemented before\n    \"\"\"\n    \n    def __init__(self, input_dim, output_dim, activation_fn=relu):\n        \"\"\"\n        Arguments:\n        input_dim - the number of inputs of the layer. type int\n        output_dim - the number of outputs of the layer. type int\n        activation_fn - a reference to the activation function to use. Should be 'relu' as a default\n                        possible values are the 'relu', 'sigmoid' and 'softmax' functions you implemented earlier.\n                        Has the type 'function'\n        \n        Attributes:\n        w - the weight matrix of the layer, should be initialized with 'initialize_weights'\n            and has the shape (INPUT_FEATURES, OUTPUT_FEATURES) and type 'numpy.ndarray'\n        b - the bias vector of the layer, should be initialized with 'initialize_weights'\n            and has the shape (1, OUTPUT_FEATURES) and type 'numpy.ndarray'\n        activation_fn - a reference to the activation function to use.\n                        Has the type 'function'\n        \"\"\"\n        self.w, self.b = initialize_weights((input_dim, output_dim)) # TODO\n        self.activation_fn = activation_fn # TODO\n        # YOUR CODE HERE\n        \n        \n    def forward_prop(self, a_prev):\n        \"\"\" Implement the forward propagation module of the neural network layer\n        Should use whatever activation function that 'activation_fn' references to\n        \n        Arguments:\n        a_prev - the input to the layer, which may be the data 'X', or the output from the previous layer.\n            a_prev has the shape of (BATCH_SIZE, INPUT_FEATURES) and the type 'numpy.ndarray'\n        \n        Returns:\n        a - the output of the layer when performing forward propagation. Has the type 'numpy.ndarray'\n        \"\"\"\n        a = self.activation_fn(np.dot(a_prev, self.w) + self.b) # TODO\n        # YOUR CODE HERE\n        \n        return a\n```\n\n\n```python\n# test case, be sure that you pass the previous activation function tests before running this test\ntest_layer(Layer, relu, sigmoid, softmax)\n```\n\n    Test passed\n\n\n### 2.4 Backward propagation\n\nIn the previous exercise you only implemented the forward propagation of the layer. However, when training a network, you would also need to implement the backward propagation of the layer in order to be able to update its weights. (You won't need to do this in this assignment since you will not train the network. Instead you will load the network weights, which are obtained from a previously trained network.)\n\nProvide a high-level explanation of how you would modify your current implementation of the `Layer` class in order to add the backward propagation. (We will not grade this in detail. It is enough that your answer demonstrates that you have thought about how to perform backprop using these classes.)\n\n**Your answer:** You would need to first cache the values of the current weights and the values of the activation values. And the idea is then to start at the end of the graph with the loss and you want to compute the gradients of each weight with respect to the loss, since the gradient will the direction of steepest descent we will then update with:\n\nweight = weight - learning_rate * grad(weight)\n\nAnd this should minimize the loss for the next time it sees the same example.\n\n### 2.5 Example - Logistic regression \nBinary logistic regression is a classifier where classification is performed by applying the sigmoid activation function to a linear combination of input values. You will now try out your neural network layer by utilizing it as a linear combination of input values and apply the sigmoid activation function to classify a simple problem. \n\nThe cell below defines a dataset of 5 points of either class `0` or class `1`. Your assignment is to:  \n1. Create an instance of a `Layer` with the sigmoid activation function;\n2. Manually tune the weights `w` and bias `b` of your layer.\n\nYou can use `test_logistic` to visually inspect how your classifier is performing. In order to  be successful in this exercise you need select values for the weights `w` and bias `b` such that all points are classified correctly. \n\n\n```python\n# Run this cell to create the dataset\nX_s = np.array([[1, 2],\n               [5, 3],\n               [8, 8],\n               [7, 5],\n               [3, 6]])\nY_s = np.array([0,0,1,0,1])\n\ntest_logistic(X_s, Y_s)\n```\n\n\n```python\n# create an instance of layer\nl = Layer(2,1,sigmoid)\n\n# TODO: manually tune weights\nl.w = np.array([-0.5,1])\nl.b = np.array([-2])\n# YOUR CODE HERE\n\n# testing your choice of weights with this function\ntest_logistic(X_s,Y_s,l,sigmoid)\n```\n\n### 2.6 Feed-forward neural network\nYou will now define the actual neural network class. It is an L-layer neural network, meaning that the number of layers and neurons in each layer is specified as input by the user. Once again, you will only focus on implementing the forward propagation part.\n\nRead the descriptions in the comments and complete the **TODO**s.\n\n\n```python\nclass NeuralNetwork:\n    \"\"\" \n    TODO: Implement an L-layer neural network class by utilizing the Layer module defined above \n    Each layer should use 'relu' activation function, except for the output layer, which should use 'softmax'\n    \"\"\"\n    \n    def __init__(self, input_n, layer_dims):\n        \"\"\"\n        Arguments:\n        input_n    - the number of inputs to the network. Should be the same as the length of a data sample\n                     Has type int\n        layer_dims - a python list or tuple of the number of neurons in each layer. Layer 'l' should have a weight matrix  \n                     with the shape ('layer_dims[l-1]', 'layer_dims[l]'). \n                     'layer_dims[-1]' is the dimension of the output layer.\n                     Layer 1 should have the dimensions ('input_n', 'layer_dims[0]').\n                     len(layer_dims) is the depth of the neural network\n        Attributes:\n        input_n - the number of inputs to the network. Has type int\n        layers  - a python list of each layer in the network. Each layer should use the 'relu' activation function,\n                  except for the last layer, which should use 'softmax'. \n                  Has type 'list' containing layers of type 'Layer'\n        \"\"\"\n        \n        self.input_n = input_n # TODO\n        self.layers = [] # TODO\n        \n        prev_nodes = self.input_n\n        for idx, layer in enumerate(layer_dims):\n            if idx != len(layer_dims)-1:\n                self.layers.append(Layer(prev_nodes, layer, activation_fn=relu))\n            else:\n                self.layers.append(Layer(prev_nodes, layer, activation_fn=softmax))\n            \n            prev_nodes = layer\n        \n        # YOUR CODE HERE\n        \n    def forward_prop(self, x):\n        \"\"\" \n        Implement the forward propagation procedure through the entire network, from input to output.\n        You will now connect each layer's forward propagation function into a chain of layer-wise forward propagations.\n        \n        Arguments:\n        x - the input data, which has the shape (BATCH_SIZE, NUM_FEATURES) and type 'numpy.ndarray'\n        \n        Returns:\n        a - the output of the last layer after forward propagating through the every layer in 'layers'.\n            Should have the dimension (BATCH_SIZE, layers[-1].w.shape[1]) and type 'numpy.ndarray'\n        \"\"\"\n        for l in self.layers:\n            a = l.forward_prop(x)\n            x = a\n            \n        # YOUR CODE HERE            \n        return a\n```\n\n\n```python\n# test case\ntest_neuralnetwork(NeuralNetwork)\n```\n\n    Test passed\n\n\n## 3 Making predictions with a neural network\nIn practice, its common to load weights to your neural network that has already been trained.  \nIn this section, you will create an instance of your neural network, load trained weights from disk, and perform predictions.\n\n### 3.1 Load weights from disk\nCreate an instance of `NeuralNetwork` with input size $28 \\times 28 = 784$, two hidden layers of size 100 and an output layer of size 10. Thereafter, load the weights contained in `./utils/ann_weights.npz` to your network.\n\n\n```python\nann = NeuralNetwork(784, layer_dims=[100, 100, 10]) # TODO: create instance of ann\n# YOUR CODE HERE\n\n# load weights\nweights = np.load('./utils/ann_weights.npz')\nfor l in range(len(ann.layers)):\n    ann.layers[l].w = weights['w' + str(l)]\n    ann.layers[l].b = weights['b' + str(l)]\n```\n\n### 3.2 Prediction\nNow, implement the function `predict_and_correct` which does the following:\n1. Load `./utils/test_data.npz` from disk;\n2. Extract test data `X` and `Y` from file;\n3. Perform for every pair of data:  \n    a. plot the image `x`; <br> \n    b. make a prediction using your neural network by forward propagating and picking the most probable class;     \n    c. check whether the prediction is correct (compare with the ground truth number `y`);    \n    d. print the predicted label and wether it was correct or not. \n\n\n```python\ndef predict_and_correct(ann):\n    \"\"\" Load test data from file and predict using your neural network. \n    Make a prediction for ever data sample and print it along with wether it was a correct prediction or not\n    \n    Arguments:\n    ann - the neural network to use for prediction. Has type `NeuralNetwork`\n    \n    Returns: # for test case purposes\n    A `numpy.ndarray` of predicted classes (integers [0-9]) with shape (11,)\n    \"\"\"\n    data = np.load('./utils/test_data.npz')\n    X, cls = data['X'], data['Y']\n    \n    cls_preds = ann.forward_prop(X) # TODO: make a predicted number for every image in X\n    cls_preds = cls_preds.argmax(1)\n    # YOUR CODE HERE\n    \n    for i in range(len(X)):\n        plt.imshow(X[i].reshape(28,28), cmap='gray')\n        plt.show()\n        correct = cls_preds[i] == cls[i]\n        print('The prediction was {0}, it was {1}!'.format(cls_preds[i], 'correct' if correct else 'incorrect'))\n        \n    return cls_preds\n        \ncls_pred = predict_and_correct(ann)\n```\n\n\n```python\n# final test case\ntest_predict_and_correct_answer(cls_pred)\n```\n\n    Test passed, you have implemented your neural network correctly!\n\n\n## Congratulations!\nYou have successfully implemented a neural network from scratch using only NumPy!  \n", "meta": {"hexsha": "cfc244bb1f71772d2f8448a6dc50de8f9691e4d9", "size": 203266, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Courses/SSY340/home-assignments/IHA1/.ipynb_checkpoints/IHA1-checkpoint.ipynb", "max_stars_repo_name": "aladdinpersson/Courses", "max_stars_repo_head_hexsha": "0b730d14f29349d73a967133fe4b5d4aac5671b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40, "max_stars_repo_stars_event_min_datetime": "2020-09-30T13:45:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T10:22:19.000Z", "max_issues_repo_path": "Courses/SSY340/home-assignments/IHA1/IHA1.ipynb", "max_issues_repo_name": "aladdinpersson/Courses", "max_issues_repo_head_hexsha": "0b730d14f29349d73a967133fe4b5d4aac5671b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Courses/SSY340/home-assignments/IHA1/IHA1.ipynb", "max_forks_repo_name": "aladdinpersson/Courses", "max_forks_repo_head_hexsha": "0b730d14f29349d73a967133fe4b5d4aac5671b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2020-10-06T07:05:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T10:23:29.000Z", "avg_line_length": 72.3624065504, "max_line_length": 39916, "alphanum_fraction": 0.8074887094, "converted": true, "num_tokens": 8277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1561049131496319, "lm_q2_score": 0.15203224930631218, "lm_q1q2_score": 0.02373298107390505}}
{"text": "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Backtesing\" data-toc-modified-id=\"Backtesing-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Backtesing</a></span></li></ul></div>\n\n\n```python\n%tensorflow_version 2.x\n!git clone https://github.com/tensortrade-org/tensortrade.git\n!pip install -U ta\n```\n\n    TensorFlow 2.x selected.\n    Cloning into 'tensortrade'...\n    remote: Enumerating objects: 287, done.\u001b[K\n    remote: Counting objects: 100% (287/287), done.\u001b[K\n    remote: Compressing objects: 100% (201/201), done.\u001b[K\n    remote: Total 7670 (delta 188), reused 171 (delta 85), pack-reused 7383\u001b[K\n    Receiving objects: 100% (7670/7670), 53.96 MiB | 20.97 MiB/s, done.\n    Resolving deltas: 100% (5115/5115), done.\n    Collecting ta\n      Downloading https://files.pythonhosted.org/packages/a1/69/602e636dd2ed3bc15fcae514c5918049a8e02490d660f601f464c91985e1/ta-0.5.15.tar.gz\n    Requirement already satisfied, skipping upgrade: numpy in /usr/local/lib/python3.6/dist-packages (from ta) (1.18.2)\n    Requirement already satisfied, skipping upgrade: pandas in /usr/local/lib/python3.6/dist-packages (from ta) (0.25.3)\n    Requirement already satisfied, skipping upgrade: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas->ta) (2018.9)\n    Requirement already satisfied, skipping upgrade: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas->ta) (2.8.1)\n    Requirement already satisfied, skipping upgrade: six>=1.5 in /usr/local/lib/python3.6/dist-packages (from python-dateutil>=2.6.1->pandas->ta) (1.12.0)\n    Building wheels for collected packages: ta\n      Building wheel for ta (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for ta: filename=ta-0.5.15-cp36-none-any.whl size=23439 sha256=1a825dfd41b8282243041c3fd15cbee7bfc5d824dfa6d7df4c8437b835793e88\n      Stored in directory: /root/.cache/pip/wheels/53/b3/ec/93bd3d04147adcf06fab4ba9926b1150c987d8ffa053374709\n    Successfully built ta\n    Installing collected packages: ta\n    Successfully installed ta-0.5.15\n\n\n\n```python\ncd tensortrade\n```\n\n    /content/tensortrade\n\n\n\n```python\n!pip install -r requirements.txt\n```\n\n    Requirement already satisfied: numpy>=1.16.4 in /usr/local/lib/python3.6/dist-packages (from -r requirements.txt (line 1)) (1.18.2)\n    Requirement already satisfied: pandas>=0.25.0 in /usr/local/lib/python3.6/dist-packages (from -r requirements.txt (line 2)) (0.25.3)\n    Requirement already satisfied: gym>=0.14.0 in /usr/local/lib/python3.6/dist-packages (from -r requirements.txt (line 3)) (0.17.1)\n    Collecting pyyaml>=5.1.2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/64/c2/b80047c7ac2478f9501676c988a5411ed5572f35d1beff9cae07d321512c/PyYAML-5.3.1.tar.gz (269kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 276kB 2.8MB/s \n    \u001b[?25hCollecting sympy>=1.4\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/ce/5b/acc12e3c0d0be685601fc2b2d20ed18dc0bf461380e763afc9d0a548deb0/sympy-1.5.1-py2.py3-none-any.whl (5.6MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5.6MB 9.1MB/s \n    \u001b[?25hRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.25.0->-r requirements.txt (line 2)) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.25.0->-r requirements.txt (line 2)) (2.8.1)\n    Requirement already satisfied: pyglet<=1.5.0,>=1.4.0 in /usr/local/lib/python3.6/dist-packages (from gym>=0.14.0->-r requirements.txt (line 3)) (1.5.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from gym>=0.14.0->-r requirements.txt (line 3)) (1.12.0)\n    Requirement already satisfied: cloudpickle<1.4.0,>=1.2.0 in /usr/local/lib/python3.6/dist-packages (from gym>=0.14.0->-r requirements.txt (line 3)) (1.3.0)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from gym>=0.14.0->-r requirements.txt (line 3)) (1.4.1)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy>=1.4->-r requirements.txt (line 5)) (1.1.0)\n    Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from pyglet<=1.5.0,>=1.4.0->gym>=0.14.0->-r requirements.txt (line 3)) (0.16.0)\n    Building wheels for collected packages: pyyaml\n      Building wheel for pyyaml (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pyyaml: filename=PyYAML-5.3.1-cp36-cp36m-linux_x86_64.whl size=44621 sha256=48c62b8ff4a26e3dad8fa0e7fa549206625c3f5c2778c6b1bb0c3421d9bfcc69\n      Stored in directory: /root/.cache/pip/wheels/a7/c1/ea/cf5bd31012e735dc1dfea3131a2d5eae7978b251083d6247bd\n    Successfully built pyyaml\n    Installing collected packages: pyyaml, sympy\n      Found existing installation: PyYAML 3.13\n        Uninstalling PyYAML-3.13:\n          Successfully uninstalled PyYAML-3.13\n      Found existing installation: sympy 1.1.1\n        Uninstalling sympy-1.1.1:\n          Successfully uninstalled sympy-1.1.1\n    Successfully installed pyyaml-5.3.1 sympy-1.5.1\n\n\n\n```python\n!mkdir /content/agents\n!mkdir /content/data\n```\n\n\n```python\nimport pandas as pd\nimport numpy as np\n%matplotlib inline\n\nimport ta\nfrom tensortrade.data import DataFeed, Module\nfrom tensortrade.exchanges import Exchange\nfrom tensortrade.exchanges.services.execution.simulated import execute_order\nfrom tensortrade.data import Stream, DataFeed, Module\nfrom tensortrade.instruments import USD, BTC, ETH, LTC\nfrom tensortrade.wallets import Wallet, Portfolio\nfrom tensortrade.environments import TradingEnvironment\n\nfrom tensortrade.agents import DQNAgent\nfrom tensortrade.agents import A2CAgent\n```\n\n\n```python\nimport pandas as pd\n\ndef load_csv(filename):\n    df = pd.read_csv(filename)\n    # Convert the date column type from string to datetime for proper sorting.\n    df['date'] = pd.to_datetime(df['date'])\n\n    # Make sure historical prices are sorted chronologically, oldest first.\n    df.sort_values(by='date', ascending=True, inplace=True)\n    df.reset_index(drop=True, inplace=True)\n\n    # Format timestamps as you want them to appear on the chart buy/sell marks.\n    df['date'] = df['date'].dt.strftime('%Y-%m-%d')\n\n    # PlotlyTradingChart expects 'datetime' as the timestamps column name.\n    df.rename(columns={'date': 'datetime'}, inplace=True)\n\n    return df\n\ndf = load_csv('/content/data/hz_data.csv')\ndf.tail()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>datetime</th>\n      <th>open</th>\n      <th>high</th>\n      <th>low</th>\n      <th>close</th>\n      <th>volume</th>\n      <th>y2_hat</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>587</th>\n      <td>2019-10-19</td>\n      <td>7950.48</td>\n      <td>8096.76</td>\n      <td>7875.00</td>\n      <td>7960.49</td>\n      <td>3461.125292</td>\n      <td>0.003603</td>\n    </tr>\n    <tr>\n      <th>588</th>\n      <td>2019-10-20</td>\n      <td>7965.39</td>\n      <td>8314.77</td>\n      <td>7874.68</td>\n      <td>8235.74</td>\n      <td>6358.924991</td>\n      <td>0.003452</td>\n    </tr>\n    <tr>\n      <th>589</th>\n      <td>2019-10-21</td>\n      <td>8236.49</td>\n      <td>8352.00</td>\n      <td>8156.00</td>\n      <td>8213.65</td>\n      <td>4919.734168</td>\n      <td>0.000227</td>\n    </tr>\n    <tr>\n      <th>590</th>\n      <td>2019-10-22</td>\n      <td>8206.53</td>\n      <td>8314.77</td>\n      <td>7989.15</td>\n      <td>8025.90</td>\n      <td>5678.934831</td>\n      <td>-0.000325</td>\n    </tr>\n    <tr>\n      <th>591</th>\n      <td>2019-10-23</td>\n      <td>8021.57</td>\n      <td>8052.04</td>\n      <td>7920.40</td>\n      <td>7995.47</td>\n      <td>1588.417045</td>\n      <td>0.000585</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nimport ta\nfrom tensortrade.data import DataFeed, Module\n\ndataset = ta.add_all_ta_features(df, 'open', 'high', 'low', 'close', 'volume', fillna=True)\ndataset.head(3)\n```\n\n\n```python\nprice_history = dataset[['datetime', 'open', 'high', 'low', 'close', 'volume']]  # chart data\ndisplay(price_history.head(3))\n\ndataset.drop(columns=['datetime', 'open', 'high', 'low', 'close', 'volume'], inplace=True)\n```\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>datetime</th>\n      <th>open</th>\n      <th>high</th>\n      <th>low</th>\n      <th>close</th>\n      <th>volume</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>2018-03-11</td>\n      <td>8795.04</td>\n      <td>9768.37</td>\n      <td>8450.00</td>\n      <td>9535.04</td>\n      <td>16407.54238</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2018-03-12</td>\n      <td>9535.04</td>\n      <td>9892.00</td>\n      <td>8742.07</td>\n      <td>9120.75</td>\n      <td>18751.02058</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2018-03-13</td>\n      <td>9115.24</td>\n      <td>9482.79</td>\n      <td>8830.00</td>\n      <td>9142.32</td>\n      <td>16001.47535</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n```python\nfrom tensortrade.exchanges import Exchange\nfrom tensortrade.exchanges.services.execution.simulated import execute_order\nfrom tensortrade.data import Stream, DataFeed, Module\nfrom tensortrade.instruments import USD, BTC, ETH, LTC\nfrom tensortrade.wallets import Wallet, Portfolio\nfrom tensortrade.environments import TradingEnvironment\n\ncoinbase = Exchange(\"coinbase\", service=execute_order)(\n    Stream(\"USD-BTC\", price_history['close'].tolist())\n)\n\nportfolio = Portfolio(USD, [\n    Wallet(coinbase, 10000 * USD),\n    Wallet(coinbase, 10 * BTC),\n])\n\nwith Module(\"coinbase\") as coinbase_ns:\n    nodes = [Stream(name, dataset[name].tolist()) for name in dataset.columns]\n\nfeed = DataFeed([coinbase_ns])\nfeed.next()\n```\n\n\n\n\n    {'coinbase:/momentum_ao': 0.0,\n     'coinbase:/momentum_kama': 9535.04,\n     'coinbase:/momentum_mfi': 50.0,\n     'coinbase:/momentum_roc': 0.0,\n     'coinbase:/momentum_rsi': 100.0,\n     'coinbase:/momentum_stoch': 82.30163004315938,\n     'coinbase:/momentum_stoch_signal': 82.30163004315938,\n     'coinbase:/momentum_tsi': 0.0,\n     'coinbase:/momentum_uo': 50.0,\n     'coinbase:/momentum_wr': -17.69836995684063,\n     'coinbase:/others_cr': 0.0,\n     'coinbase:/others_dlr': 0.0,\n     'coinbase:/others_dr': 37.03698680179694,\n     'coinbase:/trend_adx': 0.0,\n     'coinbase:/trend_adx_neg': 0.0,\n     'coinbase:/trend_adx_pos': 0.0,\n     'coinbase:/trend_aroon_down': 4.0,\n     'coinbase:/trend_aroon_ind': 0.0,\n     'coinbase:/trend_aroon_up': 4.0,\n     'coinbase:/trend_cci': 0.0,\n     'coinbase:/trend_dpo': -2577.035287162161,\n     'coinbase:/trend_ema_fast': 9535.04,\n     'coinbase:/trend_ema_slow': 9535.04,\n     'coinbase:/trend_ichimoku_a': 9109.185000000001,\n     'coinbase:/trend_ichimoku_b': 9109.185000000001,\n     'coinbase:/trend_kst': 370.3698680179695,\n     'coinbase:/trend_kst_diff': 0.0,\n     'coinbase:/trend_kst_sig': 370.3698680179695,\n     'coinbase:/trend_macd': 0.0,\n     'coinbase:/trend_macd_diff': 0.0,\n     'coinbase:/trend_macd_signal': 0.0,\n     'coinbase:/trend_mass_index': 1.0,\n     'coinbase:/trend_psar': 9535.04,\n     'coinbase:/trend_psar_down': -1.0,\n     'coinbase:/trend_psar_down_indicator': 0.0,\n     'coinbase:/trend_psar_up': -1.0,\n     'coinbase:/trend_psar_up_indicator': 0.0,\n     'coinbase:/trend_trix': 36.24669700257624,\n     'coinbase:/trend_visual_ichimoku_a': 6998.578475506762,\n     'coinbase:/trend_visual_ichimoku_b': 7113.944231418929,\n     'coinbase:/trend_vortex_ind_diff': 0.0,\n     'coinbase:/trend_vortex_ind_neg': 1.0,\n     'coinbase:/trend_vortex_ind_pos': 1.0,\n     'coinbase:/volatility_atr': 0.0,\n     'coinbase:/volatility_bbh': 9535.04,\n     'coinbase:/volatility_bbhi': 0.0,\n     'coinbase:/volatility_bbl': 9535.04,\n     'coinbase:/volatility_bbli': 0.0,\n     'coinbase:/volatility_bbm': 9535.04,\n     'coinbase:/volatility_bbp': 0.0,\n     'coinbase:/volatility_bbw': 0.0,\n     'coinbase:/volatility_dch': 9535.04,\n     'coinbase:/volatility_dchi': 1.0,\n     'coinbase:/volatility_dcl': 9535.04,\n     'coinbase:/volatility_dcli': 1.0,\n     'coinbase:/volatility_kcc': 9251.136666666667,\n     'coinbase:/volatility_kch': 10569.506666666668,\n     'coinbase:/volatility_kchi': 0.0,\n     'coinbase:/volatility_kcl': 7932.766666666666,\n     'coinbase:/volatility_kcli': 0.0,\n     'coinbase:/volatility_kcp': 0.6076721001438645,\n     'coinbase:/volatility_kcw': 28.501794914570873,\n     'coinbase:/volume_adi': 10599.807277524375,\n     'coinbase:/volume_cmf': 0.6460326008631875,\n     'coinbase:/volume_em': 0.0,\n     'coinbase:/volume_fi': 0.0,\n     'coinbase:/volume_nvi': 1000.0,\n     'coinbase:/volume_obv': 16407.542380000003,\n     'coinbase:/volume_sma_em': 0.0,\n     'coinbase:/volume_vpt': 6080.713723685023,\n     'coinbase:/y2_hat': -0.002261962}\n\n\n\n\n```python\nenv = TradingEnvironment(\n    feed=feed,\n    portfolio=portfolio,\n    action_scheme='managed-risk',\n    reward_scheme='risk-adjusted',\n    window_size=20\n)\n```\n\n    /usr/local/lib/python3.6/dist-packages/gym/logger.py:30: UserWarning:\n    \n    \u001b[33mWARN: Box bound precision lowered by casting to float32\u001b[0m\n    \n\n\n\n```python\nfrom tensortrade.agents import DQNAgent\nagent = DQNAgent(env)\nagent.train(n_episodes=10, n_steps=200, save_path=\"../agents/\")\n```\n\n    ====      AGENT ID: 0d76af7d-78d9-432a-b3b1-c430b56229e0      ====\n    [2020-03-21 10:11:42 PM] Episode: 1/10 Step: 150/200\n    [2020-03-21 10:11:49 PM] Episode: 1/10 Step: 200/200\n    [2020-03-21 10:11:56 PM] Episode: 2/10 Step: 50/200\n    [2020-03-21 10:12:03 PM] Episode: 2/10 Step: 100/200\n    [2020-03-21 10:12:10 PM] Episode: 2/10 Step: 150/200\n    [2020-03-21 10:12:16 PM] Episode: 2/10 Step: 200/200\n    [2020-03-21 10:12:23 PM] Episode: 3/10 Step: 50/200\n    [2020-03-21 10:12:30 PM] Episode: 3/10 Step: 100/200\n    [2020-03-21 10:12:37 PM] Episode: 3/10 Step: 150/200\n    [2020-03-21 10:12:44 PM] Episode: 3/10 Step: 200/200\n    [2020-03-21 10:12:51 PM] Episode: 4/10 Step: 50/200\n    [2020-03-21 10:12:58 PM] Episode: 4/10 Step: 100/200\n    [2020-03-21 10:13:04 PM] Episode: 4/10 Step: 150/200\n    [2020-03-21 10:13:11 PM] Episode: 4/10 Step: 200/200\n    [2020-03-21 10:13:18 PM] Episode: 5/10 Step: 50/200\n    [2020-03-21 10:13:25 PM] Episode: 5/10 Step: 100/200\n    [2020-03-21 10:13:32 PM] Episode: 5/10 Step: 150/200\n    [2020-03-21 10:13:38 PM] Episode: 5/10 Step: 200/200\n    [2020-03-21 10:13:45 PM] Episode: 6/10 Step: 50/200\n    [2020-03-21 10:13:52 PM] Episode: 6/10 Step: 100/200\n    [2020-03-21 10:13:59 PM] Episode: 6/10 Step: 150/200\n    [2020-03-21 10:14:06 PM] Episode: 6/10 Step: 200/200\n    [2020-03-21 10:14:13 PM] Episode: 7/10 Step: 50/200\n    [2020-03-21 10:14:20 PM] Episode: 7/10 Step: 100/200\n    [2020-03-21 10:14:27 PM] Episode: 7/10 Step: 150/200\n    [2020-03-21 10:14:34 PM] Episode: 7/10 Step: 200/200\n    [2020-03-21 10:14:40 PM] Episode: 8/10 Step: 50/200\n    [2020-03-21 10:14:47 PM] Episode: 8/10 Step: 100/200\n    [2020-03-21 10:14:54 PM] Episode: 8/10 Step: 150/200\n    [2020-03-21 10:15:01 PM] Episode: 8/10 Step: 200/200\n    [2020-03-21 10:15:08 PM] Episode: 9/10 Step: 50/200\n    [2020-03-21 10:15:15 PM] Episode: 9/10 Step: 100/200\n    [2020-03-21 10:15:22 PM] Episode: 9/10 Step: 150/200\n    [2020-03-21 10:15:29 PM] Episode: 9/10 Step: 200/200\n    [2020-03-21 10:15:36 PM] Episode: 10/10 Step: 50/200\n    [2020-03-21 10:15:43 PM] Episode: 10/10 Step: 100/200\n    [2020-03-21 10:15:49 PM] Episode: 10/10 Step: 150/200\n    [2020-03-21 10:15:56 PM] Episode: 10/10 Step: 200/200\n\n\n\n\n\n    911000.4083567932\n\n\n\n\n```python\n# from tensortrade.agents import A2CAgent\n# agent = A2CAgent(env)\n# agent.train(n_episodes=4, n_steps=200, save_path=\"../agents/\")\n```\n\n\n```python\n%matplotlib inline\nprint(portfolio.performance.net_worth)\nportfolio.performance.net_worth.plot(figsize=(16,10))\n```\n\n## Backtesing\n\n\n```python\ndf1 = load_csv(\"/content/data/BTCUSD_1d.csv\")\ndf1 = df1[1500:-600].reset_index(drop = True)\ndf1.tail()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>datetime</th>\n      <th>open</th>\n      <th>high</th>\n      <th>low</th>\n      <th>close</th>\n      <th>volume</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>858</th>\n      <td>2018-02-26</td>\n      <td>9595.99</td>\n      <td>10461.97</td>\n      <td>9376.34</td>\n      <td>10324.70</td>\n      <td>16156.805056</td>\n    </tr>\n    <tr>\n      <th>859</th>\n      <td>2018-02-27</td>\n      <td>10329.99</td>\n      <td>10850.00</td>\n      <td>10150.00</td>\n      <td>10566.30</td>\n      <td>10408.479938</td>\n    </tr>\n    <tr>\n      <th>860</th>\n      <td>2018-02-28</td>\n      <td>10572.49</td>\n      <td>11064.75</td>\n      <td>10255.07</td>\n      <td>10314.90</td>\n      <td>10490.749058</td>\n    </tr>\n    <tr>\n      <th>861</th>\n      <td>2018-03-01</td>\n      <td>10314.99</td>\n      <td>11090.00</td>\n      <td>10223.41</td>\n      <td>10903.13</td>\n      <td>9481.665146</td>\n    </tr>\n    <tr>\n      <th>862</th>\n      <td>2018-03-02</td>\n      <td>10917.37</td>\n      <td>11175.00</td>\n      <td>10774.01</td>\n      <td>11029.99</td>\n      <td>8329.097901</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndataset1 = ta.add_all_ta_features(df1, 'open', 'high', 'low', 'close', 'volume', fillna=True)\ndataset1.head(3)\n```\n\n    /usr/local/lib/python3.6/dist-packages/ta/trend.py:543: RuntimeWarning:\n    \n    invalid value encountered in double_scalars\n    \n    /usr/local/lib/python3.6/dist-packages/ta/trend.py:547: RuntimeWarning:\n    \n    invalid value encountered in double_scalars\n    \n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>datetime</th>\n      <th>open</th>\n      <th>high</th>\n      <th>low</th>\n      <th>close</th>\n      <th>volume</th>\n      <th>volume_adi</th>\n      <th>volume_obv</th>\n      <th>volume_cmf</th>\n      <th>volume_fi</th>\n      <th>momentum_mfi</th>\n      <th>volume_em</th>\n      <th>volume_sma_em</th>\n      <th>volume_vpt</th>\n      <th>volume_nvi</th>\n      <th>volatility_atr</th>\n      <th>volatility_bbm</th>\n      <th>volatility_bbh</th>\n      <th>volatility_bbl</th>\n      <th>volatility_bbw</th>\n      <th>volatility_bbp</th>\n      <th>volatility_bbhi</th>\n      <th>volatility_bbli</th>\n      <th>volatility_kcc</th>\n      <th>volatility_kch</th>\n      <th>volatility_kcl</th>\n      <th>volatility_kcw</th>\n      <th>volatility_kcp</th>\n      <th>volatility_kchi</th>\n      <th>volatility_kcli</th>\n      <th>volatility_dcl</th>\n      <th>volatility_dch</th>\n      <th>volatility_dchi</th>\n      <th>volatility_dcli</th>\n      <th>trend_macd</th>\n      <th>trend_macd_signal</th>\n      <th>trend_macd_diff</th>\n      <th>trend_ema_fast</th>\n      <th>trend_ema_slow</th>\n      <th>trend_adx</th>\n      <th>trend_adx_pos</th>\n      <th>trend_adx_neg</th>\n      <th>trend_vortex_ind_pos</th>\n      <th>trend_vortex_ind_neg</th>\n      <th>trend_vortex_ind_diff</th>\n      <th>trend_trix</th>\n      <th>trend_mass_index</th>\n      <th>trend_cci</th>\n      <th>trend_dpo</th>\n      <th>trend_kst</th>\n      <th>trend_kst_sig</th>\n      <th>trend_kst_diff</th>\n      <th>trend_ichimoku_a</th>\n      <th>trend_ichimoku_b</th>\n      <th>trend_visual_ichimoku_a</th>\n      <th>trend_visual_ichimoku_b</th>\n      <th>trend_aroon_up</th>\n      <th>trend_aroon_down</th>\n      <th>trend_aroon_ind</th>\n      <th>trend_psar</th>\n      <th>trend_psar_up</th>\n      <th>trend_psar_down</th>\n      <th>trend_psar_up_indicator</th>\n      <th>trend_psar_down_indicator</th>\n      <th>momentum_rsi</th>\n      <th>momentum_tsi</th>\n      <th>momentum_uo</th>\n      <th>momentum_stoch</th>\n      <th>momentum_stoch_signal</th>\n      <th>momentum_wr</th>\n      <th>momentum_ao</th>\n      <th>momentum_kama</th>\n      <th>momentum_roc</th>\n      <th>others_dr</th>\n      <th>others_dlr</th>\n      <th>others_cr</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>2015-10-22</td>\n      <td>267.90</td>\n      <td>280.04</td>\n      <td>267.39</td>\n      <td>275.21</td>\n      <td>30166.425443</td>\n      <td>7130.246014</td>\n      <td>30166.425443</td>\n      <td>0.236364</td>\n      <td>0.000000</td>\n      <td>50.0</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>-27137.171080</td>\n      <td>1000.000000</td>\n      <td>0.0</td>\n      <td>275.210000</td>\n      <td>275.210000</td>\n      <td>275.210000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>274.213333</td>\n      <td>286.863333</td>\n      <td>261.563333</td>\n      <td>9.226393</td>\n      <td>0.539394</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>275.21</td>\n      <td>275.21</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>275.210000</td>\n      <td>275.210000</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>-89.022715</td>\n      <td>1.000000</td>\n      <td>0.000000</td>\n      <td>2470.627543</td>\n      <td>-899.771929</td>\n      <td>-899.771929</td>\n      <td>0.000000</td>\n      <td>273.715</td>\n      <td>273.715</td>\n      <td>2619.953082</td>\n      <td>2524.904009</td>\n      <td>4.0</td>\n      <td>4.0</td>\n      <td>0.0</td>\n      <td>275.21</td>\n      <td>-1.0</td>\n      <td>-1.00</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>100.0</td>\n      <td>0.0</td>\n      <td>50.0</td>\n      <td>61.818182</td>\n      <td>61.818182</td>\n      <td>-38.181818</td>\n      <td>0.0</td>\n      <td>275.21</td>\n      <td>0.0</td>\n      <td>-89.977193</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2015-10-23</td>\n      <td>275.21</td>\n      <td>280.19</td>\n      <td>273.46</td>\n      <td>278.60</td>\n      <td>21572.268470</td>\n      <td>18509.377228</td>\n      <td>51738.693913</td>\n      <td>0.357747</td>\n      <td>73129.990115</td>\n      <td>50.0</td>\n      <td>97024.103092</td>\n      <td>97024.103092</td>\n      <td>-26877.178494</td>\n      <td>1012.317866</td>\n      <td>0.0</td>\n      <td>276.905000</td>\n      <td>280.295000</td>\n      <td>273.515000</td>\n      <td>2.448493</td>\n      <td>0.750000</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>275.815000</td>\n      <td>285.505000</td>\n      <td>266.125000</td>\n      <td>7.026449</td>\n      <td>0.643705</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>275.21</td>\n      <td>278.60</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.270427</td>\n      <td>0.054085</td>\n      <td>0.216342</td>\n      <td>275.731538</td>\n      <td>275.461111</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.002406</td>\n      <td>1.923694</td>\n      <td>66.666667</td>\n      <td>2468.932543</td>\n      <td>-899.154631</td>\n      <td>-899.463280</td>\n      <td>0.308649</td>\n      <td>273.790</td>\n      <td>273.790</td>\n      <td>2619.953082</td>\n      <td>2524.904009</td>\n      <td>8.0</td>\n      <td>4.0</td>\n      <td>4.0</td>\n      <td>278.60</td>\n      <td>-1.0</td>\n      <td>-1.00</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>100.0</td>\n      <td>100.0</td>\n      <td>50.0</td>\n      <td>87.578125</td>\n      <td>74.698153</td>\n      <td>-12.421875</td>\n      <td>0.0</td>\n      <td>278.60</td>\n      <td>0.0</td>\n      <td>1.231787</td>\n      <td>1.224262</td>\n      <td>1.231787</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2015-10-24</td>\n      <td>278.60</td>\n      <td>284.00</td>\n      <td>278.22</td>\n      <td>282.84</td>\n      <td>20586.335018</td>\n      <td>30832.685041</td>\n      <td>72325.028931</td>\n      <td>0.426307</td>\n      <td>75152.285881</td>\n      <td>50.0</td>\n      <td>120309.418743</td>\n      <td>108666.760917</td>\n      <td>579.026763</td>\n      <td>1027.724283</td>\n      <td>0.0</td>\n      <td>278.883333</td>\n      <td>285.126075</td>\n      <td>272.640592</td>\n      <td>4.476956</td>\n      <td>0.816901</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>277.772222</td>\n      <td>286.158889</td>\n      <td>269.385556</td>\n      <td>6.038521</td>\n      <td>0.802133</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>275.21</td>\n      <td>282.84</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.817452</td>\n      <td>0.206759</td>\n      <td>0.610694</td>\n      <td>276.825148</td>\n      <td>276.007695</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.009324</td>\n      <td>2.784692</td>\n      <td>100.000000</td>\n      <td>2466.954210</td>\n      <td>-898.434147</td>\n      <td>-899.120236</td>\n      <td>0.686089</td>\n      <td>275.695</td>\n      <td>275.695</td>\n      <td>2619.953082</td>\n      <td>2524.904009</td>\n      <td>12.0</td>\n      <td>4.0</td>\n      <td>8.0</td>\n      <td>280.04</td>\n      <td>-1.0</td>\n      <td>280.04</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>100.0</td>\n      <td>100.0</td>\n      <td>50.0</td>\n      <td>93.016255</td>\n      <td>80.804187</td>\n      <td>-6.983745</td>\n      <td>0.0</td>\n      <td>282.84</td>\n      <td>0.0</td>\n      <td>1.521895</td>\n      <td>1.510431</td>\n      <td>2.772428</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nprice_history1 = dataset1[['datetime', 'open', 'high', 'low', 'close', 'volume']]  # chart data\ndisplay(price_history1.head(3))\n\ndataset1.drop(columns=['datetime', 'open', 'high', 'low', 'close', 'volume'], inplace=True)\ndataset1['y2_hat']=np.nan\n```\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>datetime</th>\n      <th>open</th>\n      <th>high</th>\n      <th>low</th>\n      <th>close</th>\n      <th>volume</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>2015-10-22</td>\n      <td>267.90</td>\n      <td>280.04</td>\n      <td>267.39</td>\n      <td>275.21</td>\n      <td>30166.425443</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2015-10-23</td>\n      <td>275.21</td>\n      <td>280.19</td>\n      <td>273.46</td>\n      <td>278.60</td>\n      <td>21572.268470</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2015-10-24</td>\n      <td>278.60</td>\n      <td>284.00</td>\n      <td>278.22</td>\n      <td>282.84</td>\n      <td>20586.335018</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n```python\ncoinbase = Exchange(\"coinbase\", service=execute_order)(\n    Stream(\"USD-BTC\", price_history1['close'].tolist())\n)\n\nportfolio = Portfolio(USD, [\n    Wallet(coinbase, 10000 * USD),\n    Wallet(coinbase, 10 * BTC),\n])\n\nwith Module(\"coinbase\") as coinbase_ns:\n    nodes = [Stream(name, dataset1[name].tolist()) for name in dataset1.columns]\n\nfeed = DataFeed([coinbase_ns])\nfeed.next()\n\nenv = TradingEnvironment(\n    feed=feed,\n    portfolio=portfolio,\n    action_scheme='managed-risk',\n    reward_scheme='risk-adjusted',\n    window_size=20\n)\nagent = DQNAgent(env)\nagent.restore(path=\"/content/agents/DQN1_10.hdf5\")\n```\n\n    /usr/local/lib/python3.6/dist-packages/gym/logger.py:30: UserWarning:\n    \n    \u001b[33mWARN: Box bound precision lowered by casting to float32\u001b[0m\n    \n\n\n\n```python\nstate, reward, done, info = agent.env.step(action)\naction = agent.env.action_space.sample()\nn_steps = 200\nstep = 0\n\nwhile not done and (step < n_steps):\n    state, reward, done, info = agent.env.step(action)\n    action = agent.get_action(state)\n    print('step:', step, '-- action:', action)\n    step += 1\n```\n\n    step: 0 -- action: 84\n    step: 1 -- action: 84\n    step: 2 -- action: 84\n    step: 3 -- action: 84\n    step: 4 -- action: 84\n    step: 5 -- action: 84\n    step: 6 -- action: 84\n    step: 7 -- action: 84\n    step: 8 -- action: 84\n    step: 9 -- action: 84\n    step: 10 -- action: 84\n    step: 11 -- action: 84\n    step: 12 -- action: 84\n    step: 13 -- action: 53\n    step: 14 -- action: 84\n    step: 15 -- action: 70\n    step: 16 -- action: 41\n    step: 17 -- action: 45\n    step: 18 -- action: 41\n    step: 19 -- action: 41\n    step: 20 -- action: 41\n    step: 21 -- action: 41\n    step: 22 -- action: 84\n    step: 23 -- action: 20\n    step: 24 -- action: 84\n    step: 25 -- action: 84\n    step: 26 -- action: 84\n    step: 27 -- action: 84\n    step: 28 -- action: 84\n    step: 29 -- action: 84\n    step: 30 -- action: 84\n    step: 31 -- action: 84\n    step: 32 -- action: 53\n    step: 33 -- action: 84\n    step: 34 -- action: 20\n    step: 35 -- action: 53\n    step: 36 -- action: 84\n    step: 37 -- action: 84\n    step: 38 -- action: 84\n    step: 39 -- action: 84\n    step: 40 -- action: 84\n    step: 41 -- action: 84\n    step: 42 -- action: 84\n    step: 43 -- action: 84\n    step: 44 -- action: 84\n    step: 45 -- action: 84\n    step: 46 -- action: 84\n    step: 47 -- action: 84\n    step: 48 -- action: 84\n    step: 49 -- action: 127\n    step: 50 -- action: 84\n    step: 51 -- action: 84\n    step: 52 -- action: 84\n    step: 53 -- action: 45\n    step: 54 -- action: 84\n    step: 55 -- action: 84\n    step: 56 -- action: 53\n    step: 57 -- action: 127\n    step: 58 -- action: 169\n    step: 59 -- action: 41\n    step: 60 -- action: 20\n    step: 61 -- action: 20\n    step: 62 -- action: 20\n    step: 63 -- action: 70\n    step: 64 -- action: 84\n    step: 65 -- action: 84\n    step: 66 -- action: 84\n    step: 67 -- action: 84\n    step: 68 -- action: 84\n    step: 69 -- action: 84\n    step: 70 -- action: 84\n    step: 71 -- action: 84\n    step: 72 -- action: 84\n    step: 73 -- action: 84\n    step: 74 -- action: 20\n    step: 75 -- action: 53\n    step: 76 -- action: 20\n    step: 77 -- action: 84\n    step: 78 -- action: 84\n    step: 79 -- action: 84\n    step: 80 -- action: 84\n    step: 81 -- action: 41\n    step: 82 -- action: 84\n    step: 83 -- action: 84\n    step: 84 -- action: 41\n    step: 85 -- action: 41\n    step: 86 -- action: 84\n    step: 87 -- action: 41\n    step: 88 -- action: 20\n    step: 89 -- action: 84\n    step: 90 -- action: 84\n    step: 91 -- action: 84\n    step: 92 -- action: 84\n    step: 93 -- action: 84\n    step: 94 -- action: 84\n    step: 95 -- action: 20\n    step: 96 -- action: 84\n    step: 97 -- action: 84\n    step: 98 -- action: 84\n    step: 99 -- action: 84\n    step: 100 -- action: 41\n    step: 101 -- action: 127\n    step: 102 -- action: 84\n    step: 103 -- action: 41\n    step: 104 -- action: 84\n    step: 105 -- action: 84\n    step: 106 -- action: 84\n    step: 107 -- action: 84\n    step: 108 -- action: 84\n    step: 109 -- action: 84\n    step: 110 -- action: 84\n    step: 111 -- action: 84\n    step: 112 -- action: 84\n    step: 113 -- action: 84\n    step: 114 -- action: 84\n    step: 115 -- action: 84\n    step: 116 -- action: 84\n    step: 117 -- action: 84\n    step: 118 -- action: 84\n    step: 119 -- action: 84\n    step: 120 -- action: 84\n    step: 121 -- action: 84\n    step: 122 -- action: 84\n    step: 123 -- action: 84\n    step: 124 -- action: 84\n    step: 125 -- action: 84\n    step: 126 -- action: 84\n    step: 127 -- action: 84\n    step: 128 -- action: 20\n    step: 129 -- action: 84\n    step: 130 -- action: 84\n    step: 131 -- action: 84\n    step: 132 -- action: 84\n    step: 133 -- action: 41\n    step: 134 -- action: 41\n    step: 135 -- action: 20\n    step: 136 -- action: 84\n    step: 137 -- action: 84\n    step: 138 -- action: 84\n    step: 139 -- action: 84\n    step: 140 -- action: 127\n    step: 141 -- action: 84\n    step: 142 -- action: 173\n    step: 143 -- action: 169\n    step: 144 -- action: 84\n    step: 145 -- action: 154\n    step: 146 -- action: 84\n    step: 147 -- action: 84\n    step: 148 -- action: 84\n    step: 149 -- action: 53\n    step: 150 -- action: 41\n    step: 151 -- action: 84\n    step: 152 -- action: 41\n    step: 153 -- action: 84\n    step: 154 -- action: 84\n    step: 155 -- action: 84\n    step: 156 -- action: 84\n    step: 157 -- action: 84\n    step: 158 -- action: 127\n    step: 159 -- action: 84\n    step: 160 -- action: 84\n    step: 161 -- action: 84\n    step: 162 -- action: 84\n    step: 163 -- action: 20\n    step: 164 -- action: 84\n    step: 165 -- action: 53\n    step: 166 -- action: 84\n    step: 167 -- action: 84\n    step: 168 -- action: 84\n    step: 169 -- action: 41\n    step: 170 -- action: 84\n    step: 171 -- action: 84\n    step: 172 -- action: 84\n    step: 173 -- action: 84\n    step: 174 -- action: 84\n    step: 175 -- action: 127\n    step: 176 -- action: 84\n    step: 177 -- action: 84\n    step: 178 -- action: 84\n    step: 179 -- action: 41\n    step: 180 -- action: 70\n    step: 181 -- action: 84\n    step: 182 -- action: 84\n    step: 183 -- action: 41\n    step: 184 -- action: 84\n    step: 185 -- action: 41\n    step: 186 -- action: 53\n    step: 187 -- action: 84\n    step: 188 -- action: 84\n    step: 189 -- action: 84\n    step: 190 -- action: 41\n    step: 191 -- action: 41\n    step: 192 -- action: 41\n    step: 193 -- action: 41\n    step: 194 -- action: 41\n    step: 195 -- action: 41\n    step: 196 -- action: 84\n    step: 197 -- action: 84\n    step: 198 -- action: 84\n    step: 199 -- action: 84\n\n\n\n```python\nenv.portfolio.performance.net_worth.plot(figsize=(16,10))\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "0c29913b04caa27c4275a97beeb45a57a91d8590", "size": 207742, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "AI2 Huafeng.ipynb", "max_stars_repo_name": "zhfeng18/Schulich-AI2-Bitcoin-Predictions", "max_stars_repo_head_hexsha": "27bdb6a39b987cbab1376ac743141415cacd3d87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AI2 Huafeng.ipynb", "max_issues_repo_name": "zhfeng18/Schulich-AI2-Bitcoin-Predictions", "max_issues_repo_head_hexsha": "27bdb6a39b987cbab1376ac743141415cacd3d87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AI2 Huafeng.ipynb", "max_forks_repo_name": "zhfeng18/Schulich-AI2-Bitcoin-Predictions", "max_forks_repo_head_hexsha": "27bdb6a39b987cbab1376ac743141415cacd3d87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 117.2358916479, "max_line_length": 81348, "alphanum_fraction": 0.8181301807, "converted": true, "num_tokens": 13125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.047425876880082714, "lm_q1q2_score": 0.023712938440041357}}
{"text": "# **FLISol BA 2021** - Carlos Bustillo\n\n### 0. Consideraciones\n\nRequiere que los archivos 'sim.py', 'simConst.py', 'remoteapi.dll' est\u00e9n alojados en la misma carpeta que este cuaderno de Jupyter.\nIncluir en el script de Coppelia la l\u00ednea: simRemoteApi.start(19999)\n\n\n```python\n# Se importa las librer\u00edas necesarias\nimport sim\nimport sympy as sp                    \nimport matplotlib.pyplot as plt # pyplot\nimport numpy as np      \n```\n\n### 1. Establecer la conexi\u00f3n\n\nUtilizaremos las funciones del API Remoto de VREP.\n<br>Para m\u00e1s detalles refi\u00e9rase a la documentaci\u00f3n de la librer\u00eda:\n<br>http://www.coppeliarobotics.com/helpFiles/en/remoteApiFunctionsPython.htm\n\n\n```python\ndef connect(port):\n# Establece la conexi\u00f3n a VREP\n# port debe coincidir con el puerto de conexi\u00f3n en VREP\n# retorna el n\u00famero de cliente o -1 si no puede establecer conexi\u00f3n\n    sim.simxFinish(-1) # Por si acaso, cierre todas las conexiones abiertas.\n    clientID=sim.simxStart('127.0.0.1',port,True,True,2000,5) # Conectarse\n    if clientID == 0: print(\"Conectado a\", port)\n    else: print(\"No se pudo conectar\")\n    return clientID\n```\n\n\n```python\n# Obtenemos los manejadores para cada una de las articulaciones del Robot\ndef getHandlers():\n    retCode,effector=sim.simxGetObjectHandle(clientID,'effector',sim.simx_opmode_blocking)\n    retCode,target=sim.simxGetObjectHandle(clientID,'Cuboid',sim.simx_opmode_blocking)\n    retCode,joint1=sim.simxGetObjectHandle(clientID,'MTB_joint1',sim.simx_opmode_blocking)\n    retCode,joint2=sim.simxGetObjectHandle(clientID,'MTB_joint2',sim.simx_opmode_blocking)\n    retCode,joint3=sim.simxGetObjectHandle(clientID,'MTB_joint3',sim.simx_opmode_blocking)\n    retCode,joint4=sim.simxGetObjectHandle(clientID,'MTB_joint4',sim.simx_opmode_blocking)\n    joint = [joint1, joint2, joint3, joint4]\n    return joint, effector, target\n```\n\n### 2. Inicializar\n\n\n```python\n# Obtenemos el manejador del sensor de visi\u00f3n\nclientID = connect(19999)\njoint, effector, target = getHandlers()\nretCode,sensorHandle=sim.simxGetObjectHandle(clientID,'Vision_sensor',sim.simx_opmode_blocking)\n```\n\n    Conectado a 19999\n\n\n### 3. Visualizar Imagen captada\n\n\n```python\n# Obtenemos la imagen\nretCode, resolution, image=sim.simxGetVisionSensorImage(clientID,sensorHandle,0,sim.simx_opmode_oneshot_wait)\n```\n\n\n```python\nimg = np.array(image, dtype=np.uint8)\nimg.resize([resolution[1],resolution[0],3])\nplt.imshow(img)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "0897304245175025535af1155833c8a5b67da732", "size": 14237, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Procesamiento_Img/Procesamiento_Img.ipynb", "max_stars_repo_name": "cabustillo13/CoppeliaSim_FlisolBA", "max_stars_repo_head_hexsha": "a7ade0cc76ab362ff75f7fd08a5f1dfefd1a38f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Procesamiento_Img/Procesamiento_Img.ipynb", "max_issues_repo_name": "cabustillo13/CoppeliaSim_FlisolBA", "max_issues_repo_head_hexsha": "a7ade0cc76ab362ff75f7fd08a5f1dfefd1a38f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Procesamiento_Img/Procesamiento_Img.ipynb", "max_forks_repo_name": "cabustillo13/CoppeliaSim_FlisolBA", "max_forks_repo_head_hexsha": "a7ade0cc76ab362ff75f7fd08a5f1dfefd1a38f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 72.269035533, "max_line_length": 9280, "alphanum_fraction": 0.8293179743, "converted": true, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730203630095, "lm_q2_score": 0.05340332565681315, "lm_q1q2_score": 0.02358680814027406}}
{"text": "```python\n!pip install -r ../requirements.txt\n```\n\n    Requirement already satisfied: numpy in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from -r ../requirements.txt (line 1)) (1.15.0)\n    Requirement already satisfied: scipy in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from -r ../requirements.txt (line 2)) (1.1.0)\n    Requirement already satisfied: matplotlib in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from -r ../requirements.txt (line 3)) (2.1.1)\n    Requirement already satisfied: Pillow in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from -r ../requirements.txt (line 4)) (4.3.0)\n    Requirement already satisfied: ipywidgets>=0.6.0 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from -r ../requirements.txt (line 5)) (7.2.1)\n    Requirement already satisfied: requests in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from -r ../requirements.txt (line 6)) (2.14.2)\n    Collecting SimPEG (from -r ../requirements.txt (line 7))\n      Using cached https://files.pythonhosted.org/packages/4f/b5/042629700a6bec03b3a693c4dcb15b15087668c5ae5f4142ba8d7b8aee8e/SimPEG-0.9.2-py2.py3-none-any.whl\n    Collecting em_examples (from -r ../requirements.txt (line 8))\n      Using cached https://files.pythonhosted.org/packages/ca/01/3b3c3f7402fc2967811398ab00789bd273afd2cb1ccada0e0774bff54e30/em_examples-0.0.30-py2.py3-none-any.whl\n    Collecting empymod (from -r ../requirements.txt (line 9))\n      Using cached https://files.pythonhosted.org/packages/0a/24/77231d9af2438d8913b457c58e739a039542623fdb7d2ee02a09cf940442/empymod-1.7.3-py3-none-any.whl\n    Collecting deepdish (from -r ../requirements.txt (line 10))\n      Using cached https://files.pythonhosted.org/packages/6e/39/2a47c852651982bc5eb39212ac110284dd20126bdc7b49bde401a0139f5d/deepdish-0.3.6-py2.py3-none-any.whl\n    Collecting pymatsolver>=0.1.2 (from -r ../requirements.txt (line 11))\n      Using cached https://files.pythonhosted.org/packages/0f/5e/30e92dfe738cc3e28f52344484aa2c6e44872787b2edd789df0eaae04e3b/pymatsolver-0.1.2.tar.gz\n    Requirement already satisfied: six>=1.10 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from matplotlib->-r ../requirements.txt (line 3)) (1.10.0)\n    Requirement already satisfied: python-dateutil>=2.0 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from matplotlib->-r ../requirements.txt (line 3)) (2.5.3)\n    Requirement already satisfied: pytz in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from matplotlib->-r ../requirements.txt (line 3)) (2016.6.1)\n    Requirement already satisfied: cycler>=0.10 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from matplotlib->-r ../requirements.txt (line 3)) (0.10.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from matplotlib->-r ../requirements.txt (line 3)) (2.1.4)\n    Requirement already satisfied: olefile in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from Pillow->-r ../requirements.txt (line 4)) (0.44)\n    Requirement already satisfied: ipykernel>=4.5.1 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (4.7.0)\n    Requirement already satisfied: traitlets>=4.3.1 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (4.3.1)\n    Requirement already satisfied: nbformat>=4.2.0 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (4.2.0)\n    Requirement already satisfied: widgetsnbextension~=3.2.0 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (3.2.0)\n    Requirement already satisfied: ipython>=4.0.0 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (6.2.1)\n    Collecting properties>=0.5.2 (from SimPEG->-r ../requirements.txt (line 7))\n      Using cached https://files.pythonhosted.org/packages/61/9c/034bb67472f33d399a789875e98c3fc47c8ad9f6a59efbf23f3d65a6dd1e/properties-0.5.3.tar.gz\n    Requirement already satisfied: cython in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from SimPEG->-r ../requirements.txt (line 7)) (0.24.1)\n    Collecting vectormath>=0.2.0 (from SimPEG->-r ../requirements.txt (line 7))\n      Using cached https://files.pythonhosted.org/packages/c7/44/297304759e6e5076b5fe96cdef1dd7ff6e1c67b1e735a8284ab7f5555712/vectormath-0.2.0.tar.gz\n    Collecting discretize>=0.2.0 (from SimPEG->-r ../requirements.txt (line 7))\n      Using cached https://files.pythonhosted.org/packages/8b/0c/5419bb36abfd8ddc45c7a63d553126523ce67074073442f5f0dcb05ff694/discretize-0.3.2.tar.gz\n    Collecting geoana>=0.0.4 (from SimPEG->-r ../requirements.txt (line 7))\n      Using cached https://files.pythonhosted.org/packages/60/34/5715c1b3e35b4b7e0fdef463405c9ae5b073563f48118f2a54165be78cdc/geoana-0.0.5-py2.py3-none-any.whl\n    Requirement already satisfied: future in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from em_examples->-r ../requirements.txt (line 8)) (0.16.0)\n    Requirement already satisfied: jupyter in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from em_examples->-r ../requirements.txt (line 8)) (1.0.0)\n    Requirement already satisfied: tables in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from deepdish->-r ../requirements.txt (line 10)) (3.4.2)\n    Collecting pyMKL>=0.0.3 (from pymatsolver>=0.1.2->-r ../requirements.txt (line 11))\n      Using cached https://files.pythonhosted.org/packages/43/9d/0657fdb64d31a83c5caab80a70e55dac7658ba3fac7d1f43cbcca726b286/pyMKL-0.0.3.tar.gz\n    Requirement already satisfied: jupyter_client in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipykernel>=4.5.1->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (5.1.0)\n    Requirement already satisfied: tornado>=4.0 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipykernel>=4.5.1->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (4.4.1)\n    Requirement already satisfied: notebook>=4.4.1 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from widgetsnbextension~=3.2.0->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (5.0.0)\n    Requirement already satisfied: setuptools>=18.5 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipython>=4.0.0->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (40.0.0)\n    Requirement already satisfied: jedi>=0.10 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipython>=4.0.0->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (0.11.0)\n    Requirement already satisfied: decorator in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipython>=4.0.0->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (4.0.10)\n    Requirement already satisfied: pickleshare in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipython>=4.0.0->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (0.7.4)\n    Requirement already satisfied: simplegeneric>0.8 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipython>=4.0.0->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (0.8.1)\n    Requirement already satisfied: prompt_toolkit<2.0.0,>=1.0.4 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipython>=4.0.0->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (1.0.15)\n    Requirement already satisfied: pygments in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipython>=4.0.0->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (2.1.3)\n    Requirement already satisfied: pexpect in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from ipython>=4.0.0->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (4.0.1)\n    Collecting utm (from geoana>=0.0.4->SimPEG->-r ../requirements.txt (line 7))\n      Using cached https://files.pythonhosted.org/packages/92/d9/8bdb3d477dcaf75e1a1021772892f729a055787a08aa472582c5d35a0b36/utm-0.4.2.tar.gz\n    Requirement already satisfied: numexpr>=2.5.2 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from tables->deepdish->-r ../requirements.txt (line 10)) (2.6.2)\n    Requirement already satisfied: jupyter_core in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from jupyter_client->ipykernel>=4.5.1->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (4.4.0)\n    Requirement already satisfied: pyzmq>=13 in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from jupyter_client->ipykernel>=4.5.1->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (15.4.0)\n    Requirement already satisfied: parso==0.1.* in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from jedi>=0.10->ipython>=4.0.0->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (0.1.1)\n    Requirement already satisfied: wcwidth in /home/nbuser/anaconda3_420/lib/python3.5/site-packages (from prompt_toolkit<2.0.0,>=1.0.4->ipython>=4.0.0->ipywidgets>=0.6.0->-r ../requirements.txt (line 5)) (0.1.7)\n    Building wheels for collected packages: pymatsolver, properties, vectormath, discretize, pyMKL, utm\n      Running setup.py bdist_wheel for pymatsolver ... \u001b[?25ldone\n    \u001b[?25h  Stored in directory: /home/nbuser/.cache/pip/wheels/09/66/a3/c540b8d29d1edab2bd4fabe368987aedc7fda18e742672be5b\n      Running setup.py bdist_wheel for properties ... \u001b[?25ldone\n    \u001b[?25h  Stored in directory: /home/nbuser/.cache/pip/wheels/76/46/be/6a1402b7cfa1ca30e7fda543437f5dd615abef8aeb7a3d62c6\n      Running setup.py bdist_wheel for vectormath ... \u001b[?25ldone\n    \u001b[?25h  Stored in directory: /home/nbuser/.cache/pip/wheels/a2/86/4d/f9890cfc126a83639eb2651f1e66f6d7f7bf0322b237f5a17b\n      Running setup.py bdist_wheel for discretize ... \u001b[?25ldone\n    \u001b[?25h  Stored in directory: /home/nbuser/.cache/pip/wheels/09/6d/73/3b88a7371a5b8cdcf860f4fbd2c5001ff59054b63b2c37a0cc\n      Running setup.py bdist_wheel for pyMKL ... \u001b[?25ldone\n    \u001b[?25h  Stored in directory: /home/nbuser/.cache/pip/wheels/d6/40/40/df64f35d394a22fbecae00749cb8e7071798a3554fac9e5abe\n      Running setup.py bdist_wheel for utm ... \u001b[?25ldone\n    \u001b[?25h  Stored in directory: /home/nbuser/.cache/pip/wheels/1d/2d/5a/4c6320941f607ffefd353e1bb715e33a250a59f835cf0fbdd8\n    Successfully built pymatsolver properties vectormath discretize pyMKL utm\n    Installing collected packages: properties, vectormath, pyMKL, pymatsolver, discretize, utm, geoana, SimPEG, deepdish, empymod, em-examples\n    Successfully installed SimPEG-0.9.2 deepdish-0.3.6 discretize-0.3.2 em-examples-0.0.30 empymod-1.7.3 geoana-0.0.5 properties-0.5.3 pyMKL-0.0.3 pymatsolver-0.1.2 utm-0.4.2 vectormath-0.2.0\n\n\n\n```python\nfrom em_examples import DCLayers\nfrom IPython.display import display\n%matplotlib inline\n```\n\n    /home/nbuser/anaconda3_420/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88\n      return f(*args, **kwds)\n    /home/nbuser/anaconda3_420/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88\n      return f(*args, **kwds)\n\n\n\n```python\nfrom matplotlib import rcParams\nrcParams['font.size'] = 14\n```\n\n# Purpose\n\n## Investigating DC Resistivity Data \n\nUsing the widgets contained in this notebook we will explore the physical principals governing DC resistivity including the behavior of currents, electric field, electric potentials in a two layer earth. \n\nThe measured data in a DC experiment are potential differences, we will demonstrate how these  provide information about subsurface physical properties. \n\n### Background: Computing Apparent Resistivity\n\nIn practice we cannot measure the potentials everywhere, we are limited to those locations where we place electrodes. For each source (current electrode pair) many potential differences are measured between M and N electrode pairs to characterize the overall distribution of potentials. The widget below allows you to visualize the potentials, electric fields, and current densities from a dipole source in a simple model with 2 layers. For different electrode configurations you can measure the potential differences and see the calculated apparent resistivities. \n\nIn a uniform halfspace the potential differences can be computed by summing up the potentials at each measurement point from the different current sources based on the following equations:\n\n\\begin{align}\n    V_M = \\frac{\\rho I}{2 \\pi} \\left[ \\frac{1}{AM} - \\frac{1}{MB} \\right] \\\\\n    V_N = \\frac{\\rho I}{2 \\pi} \\left[ \\frac{1}{AN} - \\frac{1}{NB} \\right] \n\\end{align} \nwhere $AM$, $MB$, $AN$, and $NB$ are the distances between the corresponding electrodes. \n\nThe potential difference $\\Delta V_{MN}$ in a dipole-dipole survey can therefore be expressed as follows,\n\n\\begin{equation}\n    \\Delta V_{MN} = V_M - V_N = \\rho I \\underbrace{\\frac{1}{2 \\pi} \\left[ \\frac{1}{AM} - \\frac{1}{MB} - \\frac{1}{AN} + \\frac{1}{NB} \\right]}_{G}\n\\end{equation}\n\nand the resistivity of the halfspace $\\rho$ is equal to,\n\n$$\n    \\rho = \\frac{\\Delta V_{MN}}{IG}\n$$\n\nIn this equation $G$ is often referred to as the geometric factor. \n\nIn the case where we are not in a uniform halfspace the above equation is used to compute the apparent resistivity ($\\rho_a$) which is the resistivity of the uniform halfspace which best reproduces the measured potential difference.\n\nIn the top plot the location of the A electrode is marked by the red +, the B electrode is marked by the blue -, and the M/N potential electrodes are marked by the black dots. The $V_M$ and $V_N$ potentials are printed just above and to the right of the black dots. The calculted apparent resistivity is shown in the grey box to the right. The bottom plot can show the resistivity model, the electric fields (e), potentials, or current densities (j) depending on which toggle button is selected. Some patience may be required for the plots to update after parameters have been changed.\n\n# LayeredEarth app\n\n## Parameters:\n\n - **A**: (+) Current electrode  location\n - **B**: (-) Current electrode  location\n - **M**: (+) Potential electrode  location\n - **N**: (-) Potential electrode  location\n - **$\\rho_1$**: Resistivity of the first layer\n - **$\\rho_2$**: Resistivity of the second layer\n - **h**: Thickness of the first layer\n - **Plot**: Choice of 2D plot (Model, Potential, Electric field, Currents)\n\n\n\n```python\nout = DCLayers.plot_layer_potentials_app()\ndisplay(out)\n```\n\n\n    MyApp(children=(FloatSlider(value=-30.0, continuous_update=False, description='A', max=30.0, min=-30.0, step=1\u2026\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "8e4b40ad4a531a60a288192fd73be29e5ae52316", "size": 17784, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "LabExercise_1/.ipynb_checkpoints/DC_LayeredEarth-checkpoint.ipynb", "max_stars_repo_name": "RichardScottOZ/UHElectromagnetics", "max_stars_repo_head_hexsha": "6fa608681060bc1354fd4532f62c923a0881ed65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-11-23T21:15:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T11:09:11.000Z", "max_issues_repo_path": "LabExercise_1/.ipynb_checkpoints/DC_LayeredEarth-checkpoint.ipynb", "max_issues_repo_name": "RichardScottOZ/UHElectromagnetics", "max_issues_repo_head_hexsha": "6fa608681060bc1354fd4532f62c923a0881ed65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LabExercise_1/.ipynb_checkpoints/DC_LayeredEarth-checkpoint.ipynb", "max_forks_repo_name": "RichardScottOZ/UHElectromagnetics", "max_forks_repo_head_hexsha": "6fa608681060bc1354fd4532f62c923a0881ed65", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-23T21:16:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T21:16:16.000Z", "avg_line_length": 66.3582089552, "max_line_length": 591, "alphanum_fraction": 0.6795434098, "converted": true, "num_tokens": 4806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31069438321455395, "lm_q2_score": 0.07585817740967664, "lm_q1q2_score": 0.02356870964207969}}
{"text": "# Hep Recommender\n> A recommender system for scientific articles in the field of High Energy Physics.\n\n- toc: true \n- badges: true\n- comments: true\n- categories: [jupyter]\n- image: images/hep_recommender.png\n\n# Introduction\n\nIn this note I want to discuss [hep-recommender](https://hep-recommender.herokuapp.com/), a recommender system for scientific papers in the field of High Energy Physics (HEP) aimed to help researchers in the exploration of relevant literature.  This is a personal project I have been working recently in collaboration with [Jos\u00e9 Eliel Camargo Molina](https://github.com/JoseEliel).    A [submission](https://devpost.com/software/hep-recommender) of this project to the [Facebook Artificial Intelligence Hackathon (2020)](https://fbai1.devpost.com) won the third place.\n\n\nThere are different approaches to determine the degree of similarity between articles in order to identify related work. Some works have used text-mining and natural language processing methods. Another popular approach is based on citation analysis, where the similarity between two articles is estimated based on bibliographic information [1,2,4,5]. Finally, other works have used a combination of the previous approaches, see for instance [3].    \n\nIn this project, we develop a recommender system based on citation analysis. More specifically, we will develop a recommender system that elaborates on the ideas of co-citation analysis [1,4] and co-citation proximity analysis (CPA) [2]. Co-citation analysis is based on the premise that articles which are frequently cited together (by the same papers) should be related to each other. CPA extends this idea by incorporating the notion that the closer the citations are to each other within the article text, the more likely it is that they are related. While these methods are relatively simple they provide a high quality of related article recommendations.   Our recommender system relies on a distributed representation of articles obtained by training a Skip-Gram model on reference lists.  This model also captures the notion that articles cited close to each other on the text are similar. \n\nIn this note I want to go to some detail about the model powering our recommender system, how it compares to other approaches, and how we made it available via a web application.  \n\n# Related work\n\nI would like to start discussing some of the standard methods in the literature to quantify the similarity between two articles.  I will define the following concepts: \n\n* bibliometric coupling\n\n* co-citation count\n \n* co-citation proximity analysis (CPA)\n\nBibliometric couplign reflects the idea that two papers sharing a large portion of their references should be similar [5].  Co-citation count assigns a high degree of similarity to articles which are frequenly cited together (regardless of where the citations occcured within the text) [1].   CPA extends co-citation count by assigning more weigth to cases where the articles are cited close to each other within the text [2].  In general CPA is expected to give better results than co-citation count, though it requires some work in order to parse the references of each article keeping information about the location of the references within the text.\n \nLets formalize these concepts.  We consider a set of papers $\\{  \\omega_1, \\omega_2, \\ldots \\omega_n  \\}$. We define the quantities $c_{i,j}$, where $c_{i,j}=1$ if $\\omega_i$ is cited by $\\omega_j$ and $c_{i,j}=0$ otherwise.  Then we are ready to introduce our three measures of similarity:\n\n\n* bibliographic coupling is defined as $\\sum_{k=1}^{n}   c_{k,i}   c_{k,j}$\n\n\n\n* co-citation count is defined as $\\sum_{k=1}^{n}   c_{i,k}   c_{j,k}$\n\n\n\n* CPA can be used to define a measure $\\sum_{k=1}^{n} \\eta_{i,j}^{k}  c_{i,k}   c_{j,k}$, where $n_{ij}^{k}$ are coefficients that penalize cases where the citations occur far from each other within the text.    \n\nIn the original CPA article [2], $\\eta$ was fixed to $1$ if the citations occur in the same sentence, $1/2$ if they only occur in the same paragraph, $1/4$ if they only occur in the same chapter, and $1/8$ if they only appear on the same article. Parametric representations of $\\eta$ have also been proposed [7]. \n\n# Distributed representation on co-citations\n\n\nWe propose a model that relies on the same idea behind CPA, namely, that the proximity of references within an article provide valuable information regarding the similarity of two articles.    However, we wanted to simplify the process of extracting the necessary data as much as possible.  \n\n\nWe assume that it is possible to extract the list of references of each article in the order of appearance within the text. For instance the following article  \n\n\n> Higgs boson pair production in gluon fusion is the most promising process to find out whether the Higgs boson self-coupling is Standard-Model-like. Early studies of Higgs boson pair production within an EFT framework can be found in Refs. [1\u20133]. Many phenomenological investigations about the potential of this process to reveal New Physics have been performed since, see e.g. Refs. [4\u20138]...\n\nwould give rise to a reference list [1,2,3,4,5,6,7,8,...].   In this way, articles which are frequently close to each other on these reference lists should be very similar, as the community is citing them close to each other within the text of the articles.   \n\nWe will use an approach that has proven to be very fruitful in Natural Language Processing (NLP).  We will take the lists of references and train a Skip-Gram model, such that articles which tend to be cited close to each other will have similar embeddings.    \n\n\nOur dataset consists of ordered lists of references.  Suppose we have a total of $n$ unique articles in our dataset and for each of these articles we have its reference list.  The Skip-gram model maximizes the following objective function:\n\n\\begin{align}\n\\frac{1}{n} \\sum_{q=1}^{n}    \\left[  \\frac{1}{n_q}   \\sum_{i=1}^{n_q}  \\sum_{ -c \\leq j  \\leq c ,\\, j\\neq 0  } \\log p(w_{i+j}^{q}| w_i^{q}) \\right]\n\\end{align} \n\nHere $\\omega_{i}^{q}$ represents the embedding of the $i$-th article appearing on the reference list of article $q$; $n_q$ represents the size of the reference list for article $q$, and $c$ represents the context-window size of the Skip-Gram model.  The probability is modelled using  a softmax function\n \n\\begin{align}\np(    \\omega_{i}  |    \\omega_j  )   = \\frac{   \\exp(   \\omega_{i} \\cdot \\omega_{j}  )}{     \\sum_{l=1}^{n}   \\exp(   \\omega_{l}  \\cdot \\omega_j   )   }\n\\end{align}\n\nJust like in the Skip-Gram model used in NLP, in order to make the model training more efficient we need to implement negative sampling or hierarchical softmax.      A good implementation of the Skip-Gram model is provided by the [Gensim](https://radimrehurek.com/gensim/auto_examples/index.html) library for instance.\n\nIn order to explore the structure of the trained embeddings, I took a sample of articles and made a t-SNE visualization of their embeddings in two dimensions:\n\n\n\nFor this, I picked a set of articles that were published on the [arXiv](https://arxiv.org).  Each arXiv category was displayed with a different color.  On this plot, some of the arXiv categories that appear are: astro-ph (red), hep-ex (blue), hep-th (black) and hep-ph (green), among others.  As expected, the embeddings form cluster around their categories.\n\n# Data\n\nRegarding open acces digital libraries, the research community in the field of High Energy Physics mainly uses the [INSPIRE-HEP](https://inspirehep.net) and the [arXiv](https://arxiv.org). INSPIRE-HEP provides an API from which data for articles in the field of HEP can be retrieved, we use this API to extract the data we need.  Below I show some exploratory example.  Lets first define some classes that talk to the API and handle the response.\n\n\n```python\nimport requests\nfrom typing import List, Dict\n\n\nclass InspireAPI:\n    \"\"\"\n    Simple wrapper class around the INSPIRE API\n\n    https://inspirehep.net\n\n    methods:\n       literature: gives access to the literature endpoint\n    \"\"\"\n\n    LITERATURE = \"https://inspirehep.net/api/literature/\"\n\n    def __init__(self):\n        pass\n\n    def literature(self, record_id: str):\n        \"\"\"\n        Returns api response for a given record_id\n        \"\"\"\n        url = self.LITERATURE + record_id\n        return LiteratureRecord(requests.get(url).json())\n\n\nclass LiteratureRecord:\n    \"\"\"\n    Datamodel class for handling literature record data,\n    implementing basic methods to access the properties\n    \"\"\"\n\n    def __init__(self, data: Dict):\n        self.data = data\n        \n    @property \n    def record_id(self) -> str:\n        \"\"\"\n        Returns the INSPIRE id of the article\n        \"\"\"\n        return self.data['id']\n        \n    @property\n    def metadata(self) -> Dict:\n        \"\"\"\n        Returns article metadata\n        \"\"\"\n        return self.data['metadata']\n\n    @property\n    def references(self) -> List[str]:\n        \"\"\"\n        Returns reference list of the article as a List of INSPIRE article ids\n        \"\"\"\n        if self.metadata.get(\"references\"):\n            return [\n                element[\"record\"][\"$ref\"].split(\"/\")[-1]\n                for element in self.metadata[\"references\"]\n                if element.get(\"record\")\n            ]    \n```\n\nWe can now look at one example. All the bibliographic data is contained on the *metadata* property of our LiteratureRecord class.  I implemented a *references* property in order to retrieve the list of references (only the article identifiers).   Lets extract data for the article with the identifier ['11883'](https://labs.inspirehep.net/literature/11883),\n\n\n```python\ninspireapi = InspireAPI()\n\nrecord = inspireapi.literature('11883')\n\nrecord.references\n```\n\n\n\n\n    ['40440',\n     '12289',\n     '12290',\n     '14006',\n     '12291',\n     '12288',\n     '9159',\n     '43800',\n     '43801']\n\n\n\nIn this way we are able to extract the lists of references we need for our model.  Note that the INSPIRE-API returns references in the order of appearance on the reference section of the article, and by tradition, the HEP community orders references by the order of appearance on the text. \n\n# Recommendations\n\nWe can use the Skip-Gram model embeddings and some metric on the vector space to provide recommendations for articles with at least some citations.  Very recent articles or unpopular articles with no citations will not have embeddings and we must find other method to provide recommendations for these articles.   For this reason, we consider two scenarios when we want to provide recommendations for a given article: \n\n*i)* The article has embeddings produced by our Skip-Gram model.  \n\n\n*ii)* The article has no embeddings from the Skip-Gram model. \n\n\nIn case *i)* we retrieve the top similar articles using cosine similarity as the metric.  Cosine similarity is defined as $\\cos \\theta_{12} = \\hat \\omega_{1} \\cdot \\hat \\omega_{2}$, where $\\hat \\omega = \\omega/|\\omega|$ is a unit norm vector.   In this case we retrieve as recommendations the articles whose embedding have a smaller angle difference with the original article.  \n\n\nIn case *ii)*, we dont have an embedding but we can build one out of the references of the article.  We retrieve the references of the article by calling the INSPIRE-HEP api and then take the average vector $\\omega_{\\rm{avg}}^q =  1/n_q \\sum_{i=1}^{n_q} \\omega_i^{q}$ of the references. We can then proceed to retrieve the top similar articles using cosine similarity as before.    \n\nThese two simple methods are able to provide recommendations for most articles.   \n\n# Web application\n\nThe recommender system has been made available at [hep-recommender](https://hep-recommender.herokuapp.com/).   It is a Flask web application\ncurrently hosted on Heroku with a gunicorn server. Storage of the model artifacts is done in AWS S3.\n\n# Discussion\n\nTo see one example of the application, we can look the recommendations of similar articles for:\n\n[\"Broken Symmetries and the Masses of Gauge Bosons\"](https://labs.inspirehep.net/literature/11883) by Higgs, Peter W. (1964).\n\n\nThis article is one of the works behind the 2013 Physics nobel prize for the theoretical development of the so-called Higgs mechanism.  The recommendations from our system are very good, including the other articles which were also responsible for these theoretical developments as aknowledged by the community.\n\nAnother interesting example is this one  \n\n[\"Unitary Symmetry and Leptonic Decays\"](http://www.hep-recommender.com/?article=4510) by Cabibbo, Nicola (1963)\n\nThis article introduced the idea of quark mixing when only two quark generations were known.  The recommendations include the article\n\n[\"CP Violation in the Renormalizable Theory of Weak Interaction\"](https://labs.inspirehep.net/literature/81350) by Kobayashi, Makoto; Maskawa, Toshihide (1973)\n\nwhich extends the idea of Cabibbo to three quark generations and gave rise to what is now known as the CKM matrix.\n\nExploring a large set of articles I was surprised by the high quality of the recommendations.  Several experts on the field of HEP have also been using the application and find the recommendations satisfactory.\n\n# References\n\n[[1]](https://www.semanticscholar.org/paper/Co-citation-in-the-scientific-literature%3A-A-new-of-Small/da30b84925764b550b55c7d00596f8f1b9608fe2) H. Small, \u201cCo-citation in the scientific literature: A new measure of the relationship between two documents\u201d Journal of the American Society for Information Science, vol. 24, no. 4, pp. 265\u2013269, 1973.\n\n[[2]](https://www.semanticscholar.org/paper/Citation-Proximity-Analysis-%28CPA%28-%3A-A-New-Approach-Gipp-Beel/22b519fcf4b623bef5cd702f2e1c995640d4c833) B. Gipp and J. Beel, \u201cCitation proximity analysis (cpa) : A new approach for identifying related work based on co-citation analysis\u201d in Proceedings of the 12th International Confer- ence on Scientometrics and Informetrics, vol. 1 (B. Larsen, ed.), (Sao Paulo), pp. 571\u2013575, BIREME/PANO/WHO, 2009.\n\n[[3]](https://www.semanticscholar.org/paper/A-Scalable-Hybrid-Research-Paper-Recommender-System-Kanakia-Shen/bb246e08bc6641672c2bb2b93d4214eccf3f84b6) A. Kanakia, Z. Shen, D. Eide, and K. Wang, \u201cA scalable hybrid research paper recommender system for microsoft academic\u201d CoRR, vol. abs/1905.08880, 2019.\n\n[[4]](https://www.semanticscholar.org/paper/System-of-Document-Connections-Based-on-References-Marshakova-shaikevich/2d871489eb7288dd1bec4be99bc363efd4933d48) I. V. Marshakova-shaikevich, \u201cSystem of document connections based on references\u201d 2009.\n\n[[5]](https://www.semanticscholar.org/paper/Bibliographic-coupling-between-scientific-papers-Kessler/68300052245f0f3aed1a4d65943e436cf1227242) M. M. Kessler, \u201cBibliographic coupling between scientific papers\u201d American Documentation, vol. 14, no. 1, pp. 10\u201325, 1963.\n\n[[6]](https://www.semanticscholar.org/paper/Efficient-Estimation-of-Word-Representations-in-Mikolov-Chen/330da625c15427c6e42ccfa3b747fb29e5835bf0) T. Mikolov, K. Chen, G. S. Corrado, and J. Dean, \u201cEfficient estimation of word representations in vector space\u201d CoRR, vol. abs/1301.3781, 2013.\n\n[[7]](https://www.semanticscholar.org/paper/Evaluating-link-based-recommendations-for-Wikipedia-Schwarzer-Schubotz/7c72a2008f94078ce50ac251c6437038bbcf0185) M. Schwarzer, M. Schubotz, N. Meuschke, C. Breitinger, V. Markl, and B. Gipp, \u201cEvaluating link-based recommendations for wikipedia\u201d 2016 IEEE/ACM Joint Conference on Digital Libraries (JCDL), pp. 191\u2013200, 2016.\n", "meta": {"hexsha": "46c1c34efc98f4665aef8c0d409aaac66f6206e6", "size": 19499, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "_notebooks/2020-02-20-hep-recommender.ipynb", "max_stars_repo_name": "celis/personal", "max_stars_repo_head_hexsha": "c10d3159f830c463711aec6db6e6189c09c50449", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_notebooks/2020-02-20-hep-recommender.ipynb", "max_issues_repo_name": "celis/personal", "max_issues_repo_head_hexsha": "c10d3159f830c463711aec6db6e6189c09c50449", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-05-20T21:08:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T05:30:20.000Z", "max_forks_repo_path": "_notebooks/2020-02-20-hep-recommender.ipynb", "max_forks_repo_name": "celis/personal", "max_forks_repo_head_hexsha": "c10d3159f830c463711aec6db6e6189c09c50449", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.619047619, "max_line_length": 907, "alphanum_fraction": 0.6548540951, "converted": true, "num_tokens": 3893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746995506106744, "lm_q2_score": 0.07921032084852897, "lm_q1q2_score": 0.023562690583184647}}
{"text": "# Writing a SAS Global Forum Paper in Jupyter Lab\n\nThis paper outlines how you can submit your SAS Global forum paper directly from Jupyter lab\n\nIn the cells below you will see examples of common elements in SAS Global Forum papers\n\nThis template leverages [Jupyter Book](https://jupyterbook.org/start/overview.html)\n\nThe [MyST Cheat sheet](https://jupyterbook.org/reference/cheatsheet.html) is here\n\nFor questions post issues to: <<I'm not sure>>\n\n\n# Headings\n\n# This is a heading (only for title)\n\n## this is a subheading (section headings)\n\n### this is a heading3\n\nThis is normal text\n\n**This code is in bold**\n\nThis is *italic* text\n\nYou can use either underscore `_` or asterisk `*` to augment your text. \n\nA single symbol for italics _underscore_ or *asterisk* \n\nA double symbol for bold __underscore__ or **asterisk** \n\n\n\n\n\n\n# SAS Code\n\nThe preferred way to represent code is in a code cell.\nYou can modify the cell metadata to present combinations of code, output, or both removed or hidden by default.  This behavior is active in the HTML version of your paper.\n\nYou can see the cell metadata in the `property inspector`.\n\n## To create inline runable code, use a code cell\n\nTo create code that is not runable use the single backtick '\\`' for code that is less than one line long\nand triple backtick '\\`\\`\\`' for blocks of code\n\nHere is an example of a single backtick `data _null_`\n\nHere is an example of a triple backtick (use sas to get SAS syntax coloring in your code block. It only works with code blocks). \n```sas\nproc print data=sashelp.class(obs=10)\nrun;\n```\n\n\n```sas\n/* This cell should be removed */\nproc print data=sashelp.class;\nrun;\n```\n\n\n```sas\n/* This output should be removed */\nproc print data=sashelp.class;\nrun;\n```\n\n\n```sas\n/* This code should be removed */\nproc print data=sashelp.class;\nrun;\n```\n\n\n```sas\n/* This code should be hidden */\nproc print data=sashelp.class;\nrun;\n```\n\n\n```sas\n/* This output should be hidden */\nproc print data=sashelp.class;\nrun;\n```\n\n\n```sas\n/* This cell should be hidden */\nproc print data=sashelp.class;\nrun;\n```\n\n# Math Equations\n\nYou can specify your math equations between `$$` and then will be rendered by [MathJax](https://www.mathjax.org). [Here](https://davidhamann.de/2017/06/12/latex-cheat-sheet/) is a good reference and tutorial.\n\n$$\na_1 = b_1 + c_1\n$$ \n\n$$\ny = \\beta_0 + \\beta_1 X_1 +\\beta_2 X_2 + \\epsilon\n$$\n\n\\begin{equation}\n  \\int_0^\\infty \\frac{x^3}{e^x-1}\\,dx = \\frac{\\pi^4}{15}\n  \\label{eq:sample}\n\\end{equation}\n\n# Images\n\n* Include an image via URL\n\n\n\n* Include an image via local file\n\n\n\n* Format an image\n\n```{image} ../images/sas-campus.jpg\n:alt: SAS Cary Campus\n:class: bg-primary\n:width: 200px\n:align: center\n```\n\n\n# Figures\n\n# Tables\n\n[Tables reference](https://www.markdownguide.org/extended-syntax/#tables)\n\n| Syntax      | Description | Test Text     |\n| :---        |    :----:   |          ---: |\n| Header      | Title       | Here's this   |\n| Paragraph   | Text        | And more      |\n\n<center></center>\n\n# Footnotes\n\nThis is a very important finding\n\nThis is a example of footnote and tooltip[<sup>1</sup>](#fn1 \"footnote and tooltip 1\").\nAnother footnote[<sup>2</sup>](#fn2).\nAnother tooltip[<sup>3</sup>](#_blank \"tooltip 3\").\n\n<span id=\"fn1\">footnote and tooltip 1</span>\n<span id=\"fn2\">footnote 2</span>\n\n```{note}\nHere is a note\n```\n\n# This cell and All cells above should be removed before publication!!!\n\n<center>\n<small>Paper ####-2020</small><br />\n<h1>My Great Paper Title</h1><br />\nJane Doe, Anywhere USA\n</center>\n\n## ABSTRACT\n\nLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum\n\n## INTRODUCTION\n\nContrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum et Malorum\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \"Lorem ipsum dolor sit amet..\", comes from a line in section 1.10.32.\n\n\n```sas\n\n```\n\n## CONCLUSION\n\n\n```sas\n\n```\n\n\n```sas\n\n```\n\n## References\n\n\n\n## Recommended Reading\n\n## Acknowledgments\n\n## CONTACT INFORMATION\n\nYour comments and questions are valued and encouraged. Contact the author at:\n\n```\nJane Doe\nProfessor\nDepartment of Statistics\nAnywhere, NC\nJane.Doe@sas.com\n```\n\nSAS and all other SAS Institute Inc. product or service names are registered trademarks or trademarks of SAS Institute Inc. in the USA and other countries. \u00ae indicates USA registration.\n\nOther brand and product names are trademarks of their respective companies.\n", "meta": {"hexsha": "31c93b2793e7fc14949b073a9e51cdc1b631662b", "size": 10152, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/SASGF_Template.ipynb", "max_stars_repo_name": "jld23/SASGF-ipynb-test", "max_stars_repo_head_hexsha": "0eefad20e6450ebb32bc803f8f9d223d62b51806", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/SASGF_Template.ipynb", "max_issues_repo_name": "jld23/SASGF-ipynb-test", "max_issues_repo_head_hexsha": "0eefad20e6450ebb32bc803f8f9d223d62b51806", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/SASGF_Template.ipynb", "max_forks_repo_name": "jld23/SASGF-ipynb-test", "max_forks_repo_head_hexsha": "0eefad20e6450ebb32bc803f8f9d223d62b51806", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6363636364, "max_line_length": 773, "alphanum_fraction": 0.5539795114, "converted": true, "num_tokens": 1413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21469142916152642, "lm_q2_score": 0.10970577387797076, "lm_q1q2_score": 0.023552889381132796}}
{"text": "```python\nimport nltk \nfrom nltk.corpus import stopwords \nfrom nltk.stem.wordnet import WordNetLemmatizer\nimport nltk.corpus\n\nimport spacy\n\nimport gensim\nfrom gensim import corpora\nfrom gensim.models import CoherenceModel\n\nfrom matplotlib import pyplot as plt\nfrom wordcloud import WordCloud, STOPWORDS\nimport matplotlib.colors as mcolors\n\nimport pandas as pd\nimport numpy as np\n\nimport string\nimport csv\nimport datetime\nimport os.path\n```\n\n\n```python\nclass Metrics:\n    @staticmethod\n    def mean_absolute_percentage_error(y_true, y_pred): \n        y_true, y_pred = np.array(y_true), np.array(y_pred)\n        return np.mean(np.abs((y_true - y_pred) / y_true)) * 100\n    @staticmethod\n    def weighted_mean_absolute_percentage_error(y_true, y_pred): \n        y_true, y_pred = np.array(y_true), np.array(y_pred)\n        return np.mean(np.abs(((y_true*y_pred) - (y_pred*y_pred)) / (y_true* y_pred))) * 100\n```\n\n\n```python\nclass Research:\n    @staticmethod\n    def parse_xls(xls_file=None):\n        if not xls_file:\n            return False\n        df = pd.read_excel(xls_file)\n        return list(df['Abstract Note'])\n\n    @staticmethod\n    def parse_scholar(query_word='security', size=6, initial_time=None, end_time=None):\n        import scholarly\n        q = '/scholar?lr=lang_us&q='+query_word+'&hl=en-US&as_vis=1&as_sdt=1,5'\n        if(initial_time != None):\n            q = q + '&as_ylo=' + initial_time\n        if(end_time != None):\n            q = q +'&as_yhi=' + end_time\n        searchFilter = scholarly.search_pubs_custom_url(q)\n        return [next(searchFilter).bib['abstract'] for i in range(size)]\n    @staticmethod\n    def words_stop(stopPath):\n        stop_words = set(stopwords.words('english'))\n        with open(stopPath, \"rb\") as msw:\n            my_stops = msw.read().decode('utf-8').split(\"\\r\\n\")            \n            ret = stop_words | set(my_stops)\n        return ret\n    @staticmethod    \n    def clean(doc, stopPath):\n        exclude = set(string.punctuation)\n        lemma = WordNetLemmatizer()          \n        stop = set(stopwords.words('english'))      \n        my_stops = Research.words_stop(stopPath)\n        stop_free = \" \".join([i for i in doc.lower().split() if i not in stop])\n        punc_free = ''.join(ch for ch in stop_free if ch not in exclude)\n        normalized = \" \".join(lemma.lemmatize(word) for word in punc_free.split())\n        return \" \".join([i for i in normalized.split() if i not in my_stops])\n    @staticmethod\n    def save(path, doc_list):\n        with open(path, \"wb\") as file:\n            doc_str = str(doc_list).encode(\"utf-8\")\n            file.write(doc_str)\n```\n\n\n```python\nclass Cleaner:\n    def __init__(self):\n        self.result = []\n    @staticmethod\n    def clean_xls(xls_file_in=None, xls_file_out=None):\n        if not xls_file_in:\n            return False\n        if not xls_file_out:\n            xls_file_out = xls_file_in\n\n        data = pd.read_excel(xls_file_in, index_col=0)\n        data = clean_panda(data)\n        data.to_excel(xls_file_out)\n        \n    @staticmethod\n    def clean_csv(csv_file_in=None, csv_file_out=None):\n        if not csv_file_in:\n            return False\n        if not csv_file_out:\n            csv_file_out = csv_file_in\n\n        data = pd.read_csv(csv_file_in, index_col=0)\n        data = clean_panda(data)\n        data.to_csv(csv_file_out)\n\n    @staticmethod\n    def clean_panda(data):\n        data[\"abstract\"] = data[\"abstract\"].apply(lambda x: re.sub(\"([\u00a9]*)\\.\",\"\",x))#remove copyright's\n        data[\"abstract\"] = data[\"abstract\"].apply(lambda x: re.sub('\\S*@\\S*\\s?', '', x))#remove emails\n        data[\"abstract\"] = data[\"abstract\"].apply(lambda x: re.sub('\\s+', ' ', x))#\n        data[\"abstract\"] = data[\"abstract\"].apply(lambda x: re.sub(\"\\'\", ' ', x))# remove '\n        return data\n```\n\n__Tokenization__ : Split the text into sentences and the sentences into words. Lowercase the words and remove punctuation.<br><br>\nWords that have __fewer than 3 characters__ are removed.<br><br>\nAll __stopwords__  are removed.<br><br>\nWords are __lemmatized__\u200a \u2014\u200a words in third person are changed to first person and verbs in past and future tenses are changed into present.<br><br>\nWords are __stemmed__ \u200a\u2014\u200a words are reduced to their root form.\n\n\n```python\n#Set variables\nsource = 'Papers.xlsx'\nstopWords = 'BlockWords.txt'\nclean_path = 'CleanArchive.txt'\nlog_path = 'BeforeArchive.txt'\ntopics = 10\nwords = 8\n```\n\n\n```python\n#prepare docs\n#log = research.revoke(source)\ndoc_complete = Research.parse_xls(source)\ndoc_clean = [Research.clean(doc, stopWords).split() for doc in doc_complete]\n\n```\n\n\n```python\n#save this version and alterations\nResearch.save(log_path, []) #log)\nResearch.save(clean_path, doc_clean)\n```\n\n\n```python\n#dictionary and matrix\ndictionary = corpora.Dictionary(doc_clean)\ndoc_term_matrix = [dictionary.doc2bow(doc) for doc in doc_clean]\n```\n\n\n```python\n#lda model\nLDA = gensim.models.ldamodel.LdaModel\n```\n\n\n```python\n#LDA result\nresult = LDA(doc_term_matrix, chunksize=604, num_topics = topics, id2word=dictionary, passes = 2, iterations = 100) \n```\n\n\n```python\nLDA.save(result, 'aprendizado')\n```\n\n\n```python\nif os.path.exists('aprendizado'):\n    LDA.update(gensim.models.ldamodel.LdaModel.load('aprendizado'), doc_term_matrix)\n```\n\n\n```python\nfor idx, topic in result.print_topics(-1):\n    print('Topic: {} \\nWords: {}'.format(idx, topic))\n```\n\n    Topic: 0 \n    Words: 0.026*\"ism\" + 0.017*\"informationsecurity\" + 0.013*\"study\" + 0.012*\"organization\" + 0.008*\"management\" + 0.008*\"risk\" + 0.008*\"process\" + 0.007*\"paper\" + 0.007*\"research\" + 0.007*\"employee\"\n    Topic: 1 \n    Words: 0.023*\"system\" + 0.021*\"management\" + 0.016*\"ism\" + 0.015*\"security\" + 0.013*\"information\" + 0.010*\"paper\" + 0.010*\"informationsecurity\" + 0.010*\"iso\" + 0.009*\"organization\" + 0.009*\"standard\"\n    Topic: 2 \n    Words: 0.019*\"informationsecurity\" + 0.018*\"ism\" + 0.016*\"information\" + 0.012*\"organization\" + 0.012*\"system\" + 0.011*\"security\" + 0.010*\"standard\" + 0.009*\"model\" + 0.009*\"paper\" + 0.009*\"management\"\n    Topic: 3 \n    Words: 0.008*\"security\" + 0.006*\"skill\" + 0.005*\"informationsecurity\" + 0.005*\"ism\" + 0.005*\"study\" + 0.005*\"research\" + 0.005*\"data\" + 0.005*\"act\" + 0.004*\"organization\" + 0.004*\"institutional\"\n    Topic: 4 \n    Words: 0.017*\"ism\" + 0.014*\"security\" + 0.012*\"informationsecurity\" + 0.011*\"management\" + 0.010*\"system\" + 0.008*\"service\" + 0.008*\"study\" + 0.008*\"information\" + 0.007*\"control\" + 0.007*\"paper\"\n    Topic: 5 \n    Words: 0.020*\"informationsecurity\" + 0.014*\"system\" + 0.010*\"security\" + 0.010*\"information\" + 0.010*\"management\" + 0.007*\"ism\" + 0.007*\"network\" + 0.006*\"paper\" + 0.006*\"risk\" + 0.005*\"level\"\n    Topic: 6 \n    Words: 0.022*\"security\" + 0.017*\"informationsecurity\" + 0.014*\"information\" + 0.014*\"ism\" + 0.013*\"system\" + 0.010*\"risk\" + 0.010*\"standard\" + 0.008*\"organization\" + 0.007*\"management\" + 0.007*\"data\"\n    Topic: 7 \n    Words: 0.020*\"system\" + 0.018*\"management\" + 0.013*\"organization\" + 0.011*\"information\" + 0.010*\"security\" + 0.009*\"model\" + 0.007*\"informationsecurity\" + 0.007*\"threat\" + 0.006*\"risk\" + 0.006*\"ism\"\n    Topic: 8 \n    Words: 0.037*\"security\" + 0.017*\"management\" + 0.013*\"information\" + 0.012*\"informationsecurity\" + 0.011*\"system\" + 0.011*\"ism\" + 0.011*\"risk\" + 0.010*\"paper\" + 0.009*\"policy\" + 0.007*\"technology\"\n    Topic: 9 \n    Words: 0.021*\"security\" + 0.019*\"informationsecurity\" + 0.011*\"organization\" + 0.011*\"study\" + 0.010*\"ism\" + 0.009*\"management\" + 0.007*\"research\" + 0.007*\"paper\" + 0.007*\"process\" + 0.006*\"analysis\"\n\n\n## Metrics works\n\n\n```latex\n%%latex\n\\begin{align}\n    Mean\\ Absolute\\ Error\\\\\n    & MAE &= &\\frac{1}{n}\\sum_{t=1}^{n}|e_t|\\\\\n    Mean\\ Absolute\\ Percentage\\ Error\\\\\n    & MAPE &= &\\frac{100\\%}{n}\\sum_{t=1}^{n}\\left |\\frac{e_t}{y_t}\\right|\\\\\n    Weighted\\ Mean\\ Absolute\\ Percentage\\ Error\\\\\n    & WMAPE &= &\\frac{100\\%}{n}\\sum_{t=1}^{n}\\left |\\frac{e_t - y_t}{y_t}\\right|\\\\\n\\end{align}\n```\n\n\n\\begin{align}\n    Mean\\ Absolute\\ Error\\\\\n    & MAE &= &\\frac{1}{n}\\sum_{t=1}^{n}|e_t|\\\\\n    Mean\\ Absolute\\ Percentage\\ Error\\\\\n    & MAPE &= &\\frac{100\\%}{n}\\sum_{t=1}^{n}\\left |\\frac{e_t}{y_t}\\right|\\\\\n    Weighted\\ Mean\\ Absolute\\ Percentage\\ Error\\\\\n    & WMAPE &= &\\frac{100\\%}{n}\\sum_{t=1}^{n}\\left |\\frac{e_t - y_t}{y_t}\\right|\\\\\n\\end{align}\n\n\n\n\n```python\ncorpus = [[\"a\", \"a\", \"b\"], [\"a\", \"c\"]]\ndct = Dictionary(corpus)\ndct.doc2idx([\"a\", \"a\", \"c\", \"not_in_dictionary\", \"c\"])\n# [0, 0, 2, -1, 2]\n```\n\n\n\n\n    [0, 0, 2, -1, 2]\n\n\n\n### A persist\u00eancia do modelo \u00e9 obtida atrav\u00e9s dos m\u00e9todos load () e save ().\n\n## Par\u00e2metros:\n##### corpus ({iter\u00e1vel da lista de (int, float), scipy.sparse.csc}, opcional) \n- Fluxo de vetores de documento ou matriz esparsa de forma (num_terms, num_documents). Se n\u00e3o for fornecido, o modelo ser\u00e1 deixado sem treinamento (presumivelmente porque voc\u00ea deseja chamar update () manualmente).\n\n##### num_topics (int, optional) \n- O n\u00famero de t\u00f3picos latentes solicitados a serem extra\u00eddos do corpus de treinamento.\n\n#####  id2word ({dict of (int, str), gensim.corpora.dictionary.Dictionary}) \n- Mapeamento de IDs de palavras em palavras. Ele \u00e9 usado para determinar o tamanho do vocabul\u00e1rio, bem como para depura\u00e7\u00e3o e impress\u00e3o de t\u00f3picos.\n\n#####  distributed (bool, optional) \n- Se a computa\u00e7\u00e3o distribu\u00edda deve ser usada para acelerar o treinamento.\n\n##### chunksize (int, optional) \n- N\u00famero de documentos a serem usados \u200b\u200bem cada bloco de treinamento.\n\n#####  passes (int, opcional) \n- N\u00famero de passagens pelo corpus durante o treinamento.\n\n#####  update_every (int, opcional) \n- N\u00famero de documentos a serem repetidos para cada atualiza\u00e7\u00e3o. Definido como 0 para aprendizado em lote,> 1 para aprendizado interativo iterativo.\n\n#####  alpha ({numpy.ndarray, str}, opcional) \n- Pode ser definido para um array 1D de comprimento igual ao n\u00famero de t\u00f3picos esperados que expressam nossa cren\u00e7a a priori para a probabilidade de cada t\u00f3pico. Alternativamente, as estrat\u00e9gias de sele\u00e7\u00e3o pr\u00e9via padr\u00e3o podem ser empregadas fornecendo uma string:\n\n>  'Assim\u00e9trico': Usa um prior assim\u00e9trico fixo normalizado de 1.0 / topicno.\n\n>  'Auto': aprende um prior assim\u00e9trico do corpus (n\u00e3o dispon\u00edvel se distribu\u00eddo == True).\n\n#####  eta ({float, np.array, str}, opcional) - A priori cren\u00e7a na probabilidade da palavra, isso pode ser:\n- escalar para um prior sim\u00e9trico sobre probabilidade de t\u00f3pico / palavra, vetor de comprimento num_words para denotar uma probabilidade definida pelo usu\u00e1rio assim\u00e9trica para cada palavra, matriz de forma (num_topics, num_words) para atribuir uma probabilidade para cada combina\u00e7\u00e3o de t\u00f3picos de palavras,  a string \"auto\" para aprender a priori assim\u00e9trica a partir dos dados.\n\n##### decay (float, optional) \n- Um n\u00famero entre (0.5, 1) para pesar que porcentagem do valor lambda anterior \u00e9 esquecida quando cada novo documento \u00e9 examinado Corresponde ao Kappa de Matthew D. Hoffman, David M. Blei e Francis Bach: \u201cAprendizagem on-line para a aloca\u00e7\u00e3o de Dirichlet Latent NIPS'10\u201d.\n\n##### offset (flutuante, opcional)\n- Hyper-par\u00e2metro que controla o quanto vamos desacelerar os primeiros passos nas primeiras itera\u00e7\u00f5es. Corresponde a Tau_0 de Matthew D. Hoffman, David M. Blei e Francis Bach: \u201cAprendizagem on-line para aloca\u00e7\u00e3o de Dirichlet latente NIPS '10\u201d.\n\n##### eval_every (int, opcional) \n- A perplexidade do log \u00e9 estimada em cada uma das muitas atualiza\u00e7\u00f5es. Definir isso para um diminui o treinamento em ~ 2x.\n\n##### itera\u00e7\u00f5es (int, opcional) \n- N\u00famero m\u00e1ximo de itera\u00e7\u00f5es no corpus ao inferir a distribui\u00e7\u00e3o de t\u00f3pico de um corpus.\n\n##### gamma_threshold (float, optional) \n- M\u00ednima altera\u00e7\u00e3o no valor dos par\u00e2metros gama para continuar a itera\u00e7\u00e3o.\n\n##### minimum_probability (float, opcional) \n- T\u00f3picos com uma probabilidade menor que esse limite ser\u00e3o filtrados.\n\n##### random_state ({np.random.RandomState, int}, opcional)\n- Um objeto randomState ou um seed para gerar um. \u00datil para reprodutibilidade.\n\n##### ns_conf (dict de (str, objeto), opcional)\n- Par\u00e2metros de palavra chave propagados para gensim.utils.getNS () para obter um Pyro4 Nameserved. Usado somente se distribu\u00eddo estiver definido como True.\n\n##### minimum_phi_value (float, opcional) \n- se per_word_topics for True, isso representa um limite inferior no termo probabilidades.\n\n##### per_word_topics (bool)\n- Se for True, o modelo tamb\u00e9m calcula uma lista de t\u00f3picos, classificados em ordem decrescente dos t\u00f3picos mais prov\u00e1veis para cada palavra, juntamente com seus valores phi multiplicados pelo comprimento do recurso (ou seja, contagem de palavras).\n\n##### callbacks (lista de retorno de chamada) \n- Retornos m\u00e9tricos para registrar e visualizar as m\u00e9tricas de avalia\u00e7\u00e3o do modelo durante o treinamento.\n\n##### dtype ({numpy.float16, numpy.float32, numpy.float64}, opcional) \n- Tipo de dados a ser usado durante os c\u00e1lculos dentro do modelo. Todas as entradas tamb\u00e9m s\u00e3o convertidas.\n\ngensim.models.ldamodel.LdaModel\n(corpus=None, num_topics=100, id2word=None, distributed=False, chunksize=2000, passes=1, update_every=1, alpha='symmetric', eta=None, decay=0.5, offset=1.0, eval_every=10, iterations=50, gamma_threshold=0.001, minimum_probability=0.01, random_state=None, ns_conf=None, minimum_phi_value=0.01, per_word_topics=False, callbacks=None, dtype=<type 'numpy.float32'>)\n\n\n\n```python\nresult.state.numdocs\n```\n\n\n\n\n    604\n\n\n\n\n```python\ntable = result.show_topics(formatted=False)\n```\n\n\n```python\npredict = []\nfor x in range(10):\n    for y in range(10):\n        predict.append(table[x][1][y][1])\npredict[:6]\n```\n\n\n\n\n    [0.028573252,\n     0.007387697,\n     0.0070668235,\n     0.006985185,\n     0.0060804444,\n     0.0048886137]\n\n\n\n\n```python\nid2word = corpora.Dictionary(doc_clean)\ncorpus = [id2word.doc2bow(text) for text in doc_clean]\nprint('\\nPerplexity: ', result.log_perplexity(corpus))\n```\n\n    \n    Perplexity:  -7.722407445827293\n\n\n\n```python\nresult.top_topics(corpus)\n```\n\n\n\n\n    [([(0.021811074, 'informationsecurity'),\n       (0.014149627, 'information'),\n       (0.013810457, 'security'),\n       (0.011798965, 'ism'),\n       (0.011782215, 'risk'),\n       (0.010998599, 'system'),\n       (0.009502687, 'organization'),\n       (0.009368965, 'management'),\n       (0.0075890855, 'paper'),\n       (0.0068079983, 'research'),\n       (0.005969076, 'standard'),\n       (0.005538359, 'analysis'),\n       (0.0054948493, 'study'),\n       (0.005338934, 'method'),\n       (0.0051193587, 'approach'),\n       (0.005049361, 'framework'),\n       (0.0044785873, 'model'),\n       (0.004440682, 'informationtechnology'),\n       (0.0043409425, 'new'),\n       (0.004262905, 'based')],\n      -1.251370357603163),\n     ([(0.03255854, 'management'),\n       (0.022717005, 'system'),\n       (0.021648528, 'security'),\n       (0.01671891, 'ism'),\n       (0.0097910175, 'information'),\n       (0.009789073, 'paper'),\n       (0.00945449, 'organization'),\n       (0.008744363, 'standard'),\n       (0.0071993195, 'risk'),\n       (0.007113832, 'informationsecurity'),\n       (0.006537088, 'iso'),\n       (0.006417009, 'informationtechnology'),\n       (0.0057708416, 'approach'),\n       (0.0055191875, 'research'),\n       (0.0054194233, 'study'),\n       (0.005372173, 'quality'),\n       (0.005348146, 'level'),\n       (0.0046862224, 'business'),\n       (0.004542345, 'model'),\n       (0.00427449, 'practice')],\n      -1.3378460542438915),\n     ([(0.020491572, 'informationsecurity'),\n       (0.014790535, 'security'),\n       (0.012076422, 'information'),\n       (0.010681236, 'ism'),\n       (0.009901371, 'company'),\n       (0.008534332, 'data'),\n       (0.008462942, 'study'),\n       (0.008104858, 'paper'),\n       (0.0068825297, 'method'),\n       (0.006196082, 'system'),\n       (0.0055224546, 'management'),\n       (0.0054903077, 'research'),\n       (0.005479383, 'control'),\n       (0.0052264105, 'network'),\n       (0.004936652, 'organization'),\n       (0.004494213, 'risk'),\n       (0.0044467463, 'knowledge'),\n       (0.004283907, 'standard'),\n       (0.0042820107, 'business'),\n       (0.0036945238, 'user')],\n      -1.3501615010461938),\n     ([(0.036361527, 'security'),\n       (0.01662409, 'information'),\n       (0.012973946, 'ism'),\n       (0.011979015, 'system'),\n       (0.010220208, 'standard'),\n       (0.009998236, 'organization'),\n       (0.009112284, 'control'),\n       (0.00892309, 'informationsecurity'),\n       (0.008657538, 'model'),\n       (0.007586148, 'management'),\n       (0.0065647145, 'data'),\n       (0.005962707, 'policy'),\n       (0.00575041, 'process'),\n       (0.0056577045, 'paper'),\n       (0.005448288, 'study'),\n       (0.004927966, 'analysis'),\n       (0.0046320586, 'used'),\n       (0.0046299547, 'asset'),\n       (0.0043721753, 'iso'),\n       (0.004371761, 'enterprise')],\n      -1.3691956647262384),\n     ([(0.019229822, 'ism'),\n       (0.019052364, 'informationsecurity'),\n       (0.018860986, 'organization'),\n       (0.009980432, 'process'),\n       (0.009002395, 'study'),\n       (0.008639004, 'information'),\n       (0.007829958, 'factor'),\n       (0.006890057, 'security'),\n       (0.0068073124, 'standard'),\n       (0.006745466, 'management'),\n       (0.0059967614, 'data'),\n       (0.0059757787, 'enterprise'),\n       (0.005942156, 'research'),\n       (0.0055803577, 'paper'),\n       (0.0055752657, 'awareness'),\n       (0.0055201757, 'implementation'),\n       (0.0050539086, 'organizational'),\n       (0.004810384, 'control'),\n       (0.004670858, 'isoiec'),\n       (0.0045807995, 'business')],\n      -1.4479789076734506),\n     ([(0.021224607, 'security'),\n       (0.019199284, 'ism'),\n       (0.008960443, 'process'),\n       (0.008479697, 'informationsecurity'),\n       (0.008456483, 'paper'),\n       (0.008421651, 'study'),\n       (0.008305767, 'management'),\n       (0.007917386, 'system'),\n       (0.007723297, 'risk'),\n       (0.0072168494, 'model'),\n       (0.0069974973, 'research'),\n       (0.0069844374, 'information'),\n       (0.006916359, 'standard'),\n       (0.006400092, 'organization'),\n       (0.0059033036, 'framework'),\n       (0.005641374, 'knowledge'),\n       (0.004912154, 'service'),\n       (0.004678908, 'result'),\n       (0.0045272117, 'development'),\n       (0.004487542, 'cloud')],\n      -1.4652787634937456),\n     ([(0.02567378, 'informationsecurity'),\n       (0.018071475, 'system'),\n       (0.015488429, 'information'),\n       (0.01532756, 'security'),\n       (0.01506758, 'ism'),\n       (0.010282547, 'paper'),\n       (0.010202126, 'risk'),\n       (0.00819207, 'management'),\n       (0.0070576356, 'organization'),\n       (0.0065514706, 'network'),\n       (0.0060836384, 'process'),\n       (0.0060320403, 'business'),\n       (0.0051085213, 'enterprise'),\n       (0.004948997, 'application'),\n       (0.004898236, 'approach'),\n       (0.004833088, 'company'),\n       (0.0048284754, 'assessment'),\n       (0.0047110296, 'policy'),\n       (0.004633282, 'proposed'),\n       (0.0045729545, 'based')],\n      -1.4760847876736543),\n     ([(0.013481724, 'informationsecurity'),\n       (0.009966217, 'system'),\n       (0.009455102, 'information'),\n       (0.00839647, 'security'),\n       (0.0073294574, 'policy'),\n       (0.006730692, 'management'),\n       (0.0066919043, 'enterprise'),\n       (0.006219898, 'organization'),\n       (0.0054459525, 'ism'),\n       (0.0051086787, 'mobile'),\n       (0.0050899154, 'method'),\n       (0.005066359, 'provider'),\n       (0.004932352, 'service'),\n       (0.0046063783, 'network'),\n       (0.0045563076, 'rule'),\n       (0.0043440247, 'data'),\n       (0.004264997, 'paper'),\n       (0.0042579183, 'technology'),\n       (0.004045343, 'development'),\n       (0.003972465, 'money')],\n      -2.3227073244040004),\n     ([(0.01512936, 'informationsecurity'),\n       (0.01252219, 'employee'),\n       (0.012339599, 'ism'),\n       (0.011148821, 'system'),\n       (0.008958945, 'model'),\n       (0.0079061845, 'requirement'),\n       (0.007378536, 'standard'),\n       (0.0071415887, 'security'),\n       (0.0070702876, 'information'),\n       (0.0069288965, 'study'),\n       (0.006910624, 'paper'),\n       (0.0066721574, 'organization'),\n       (0.00531921, 'method'),\n       (0.005080178, 'development'),\n       (0.004969194, 'medical'),\n       (0.004857246, 'compliance'),\n       (0.0039717574, 'monitoring'),\n       (0.0038311828, 'elearning'),\n       (0.0037601755, 'research'),\n       (0.0035126247, 'organizational')],\n      -3.1325119918728044),\n     ([(0.028573252, 'de'),\n       (0.007387697, 'e'),\n       (0.0070668235, 'la'),\n       (0.006985185, 'que'),\n       (0.0060804444, 'processos'),\n       (0.0048886137, 'da'),\n       (0.004813976, 'model'),\n       (0.004729046, 'system'),\n       (0.0041301884, 'effect'),\n       (0.00412925, 'se'),\n       (0.003843984, 'security'),\n       (0.0036173118, 'gest\u00e3o'),\n       (0.0034422027, 'en'),\n       (0.0033817783, 'public'),\n       (0.0031938953, 'study'),\n       (0.003188973, 'informa\u00e7\u00e3o'),\n       (0.0031425443, 'processo'),\n       (0.0030551993, 'foram'),\n       (0.002821518, 'benthos'),\n       (0.0027781574, 'site')],\n      -12.683481561177127)]\n\n\n\n\n```python\n# Compute Coherence Score !lower is better\ncoherence_model_lda = CoherenceModel(model=result, texts=doc_clean, dictionary=id2word, coherence='c_v')\ncoherence_lda = coherence_model_lda.get_coherence()\nprint('\\nCoherence Score: ', coherence_lda)\n```\n\n    \n    Coherence Score:  0.3550623115965115\n\n\n\n```python\nreal = [0.125 for x in range(100)]\n#real = list(i for j in real for i in j)\n```\n\n\n```python\nprint(Metrics.mean_absolute_percentage_error(real,predict))\nprint(Metrics.weighted_mean_absolute_percentage_error(real,predict))\n```\n\n    91.14475502446294\n    91.1447550200704\n\n\n\n```python\nprint(Metrics.mean_absolute_percentage_error(real,predict))\n```\n\n    88.93094658851624\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "d5fadd7b2f74d9911499f23a601a1c4492868ad2", "size": 31442, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Data Science/LDA/Metrics.ipynb", "max_stars_repo_name": "Alissonfelipe1234/JupyterNotebooks", "max_stars_repo_head_hexsha": "ba732e40bbaef70d9ddaae312b72616a5aa8b98b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Data Science/LDA/Metrics.ipynb", "max_issues_repo_name": "Alissonfelipe1234/JupyterNotebooks", "max_issues_repo_head_hexsha": "ba732e40bbaef70d9ddaae312b72616a5aa8b98b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Science/LDA/Metrics.ipynb", "max_forks_repo_name": "Alissonfelipe1234/JupyterNotebooks", "max_forks_repo_head_hexsha": "ba732e40bbaef70d9ddaae312b72616a5aa8b98b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7908653846, "max_line_length": 390, "alphanum_fraction": 0.5142802621, "converted": true, "num_tokens": 6789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.05108274020744003, "lm_q1q2_score": 0.023550000368881746}}
{"text": " Exercise Sheet No. 6\n\n---\n\n> Machine Learning for Natural Sciences, Summer 2021, Jun.-Prof. Pascal Friederich, pascal.friederich@kit.edu\n> \n> Deadline: 31.05.2021, 8 am\n>\n> Tutor: Matthias Schniewind [matthias.schniewind@kit.edu](mailto:matthias.schniewind@kit.edu)  \n> **Please ask questions in the forum and only contact the tutor for issues regarding the grading**\n\n---\n\n**Topic**: This exercise sheet will focus on feed-forward neural networks, their implementation and training, as well as an application to materials science.\n\n**You have two weeks to finish for Pentecost (Pfingst) holidays :)**\n\n\n\n# Preliminaries\n\nAs we had problems with the nbgrader versions, **everyone needs to rebuild their environment**. When downloading the assignment you were provided with an environment.yml file.  \nPlease shutdown jupyter and run on the command line / anaconda prompt using the new environment file:\n```\n# Deactivate aimat\nconda deactivate aimat\n\n# Remove aimat\nconda env remove -n aimat\n\n# Rebuild the conda environment. From here it is all the initial setup:\nconda env create -f environment.yml\n\n# add nbgrader extensions needed to validate your results locally\nconda run -n aimat jupyter nbextension install --sys-prefix --py nbgrader --overwrite\nconda run -n aimat jupyter nbextension enable --sys-prefix --py nbgrader\nconda run -n aimat jupyter serverextension enable --sys-prefix --py nbgrader\n\n# activate the conda environment, otherwise, your previously installed\n# packages won't be accessible\nconda activate aimat\n\n# Start jupyter again\njupyter notebook Exercise06.ipynb\n```\n\n# General remarks\n\nWe do our best to provide you with interesting, as well as challenging exercises. Many of you submit high quality notebooks and also start playing around with the existing code to go further. We like to see that and strongly encourage you to go beyond what is covered in the exercises if time and motivation allows.  \n\n**Nevertheless, it makes your life and our life much easier if you use another copy of the notebook as playground and try to stay as concise as possible in the submitted notebooks.** We are a small team and it is impossible to check all the exercise sheets manually. Therefore when things fail because you did additional things in the notebooks, we won't see that in the first run and it is quite some effort to debug this. So please don't add additional cells or delete cells in you submission.\n\n---\n\n# Application\n\nNext week you will start learning about applications of NNs in materials science. To give you a little teaser, we will use an application in materials science already here:\n\n# Organic Solar Cells\nFor organic materials to become semi-conducting, electrons must be delocalized in the molecule. For electrons to be delocalized, a high level of conjugation is necessary:  \nWhen single and double bonds are alternating in an organic molecule, electrons can move. When we think about an aromatic ring, like benzene, it is not defined where the double bonds would form, so they can move around the ring and are delocalized along the whole aromatic system:\n\n\n```python\nfrom rdkit import Chem\n\nmol = Chem.MolFromSmiles('c1ccccc1')\nmol\n```\n\nThese electrons have higher energies and are part of what is called the highest occupied molecular orbit (HOMO). This is basically the equivalent of the valence band in classical semiconductors.  \n\nThe equivalent of the conduction band is the lowest level at higher energies that is unoccupied or the lowest unoccupied molecular orbit (LUMO). The gap between those two levels is the bandgap of organic semiconductors.\n\nFor OPV (organic photovoltaic) solar cells this bandgap needs to be small enough so that visible light can excite an electron from the HOMO to the LUMO. This requires a high level of conjugation and hence aromatic systems (Figure 1)\n\n<a title=\"Alevina89, CC BY-SA 3.0 &lt;https://creativecommons.org/licenses/by-sa/3.0&gt;, via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File:Homo-lumo_gap.tif\"></a>\n<p style=\"text-align:center;font-size:80%;font-style:italic\">\n    Figure 1: Conjugation induced LUMO reduction.\n</p>\n\nFor the development of organic semiconductors, HOMO and LUMO can be simulated by density functional theory (DFT) using different levels of theory. You will learn about this in later lectures. All you need to know now, is that depending on the level of theory  - or better the details of the approximations taken - the calculation of properties like HOMO and LUMO from the molecule can take hours.\n\nThis is a problem for high-throughput screening if one wants to discover new materials. It is extremely costly to evaluate e.g. 100,000 molecules for their properties with methods that are precise enough. Hence, one usually tries to do a detailed simulation only on a subset of molecules and then train a ML-model to predict the properties of interest on the labeled data.\n\n## Dataset\nThe dataset of [Lopez et Al. 2017](https://www.sciencedirect.com/science/article/pii/S2542435117301307) contains the simulated LUMO and HOMO values for 51,247 organic molecules. Additionally, it contains 63 molecule descriptors that were calculated using [rdkit](https://www.rdkit.org/docs/index.html):\n\n\n```python\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\ndf = pd.read_hdf('OPV.h5')\ndf.describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th colspan=\"2\" halign=\"left\">labels</th>\n      <th colspan=\"19\" halign=\"left\">mol_descriptors</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>LUMO</th>\n      <th>HOMO</th>\n      <th>NumHAcceptors</th>\n      <th>NumHDonors</th>\n      <th>NumHeteroatoms</th>\n      <th>NumValenceElectrons</th>\n      <th>fr_thiophene</th>\n      <th>PEOE_VSA5</th>\n      <th>PEOE_VSA6</th>\n      <th>PEOE_VSA7</th>\n      <th>...</th>\n      <th>HeavyAtomCount</th>\n      <th>HeavyAtomMolWt</th>\n      <th>fr_imide</th>\n      <th>LabuteASA</th>\n      <th>MaxAbsEStateIndex</th>\n      <th>MaxEStateIndex</th>\n      <th>fr_nitrile</th>\n      <th>MolWt</th>\n      <th>NHOHCount</th>\n      <th>NOCount</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>51247.000000</td>\n      <td>51247.000000</td>\n      <td>51247.000000</td>\n      <td>51247.000000</td>\n      <td>51247.000000</td>\n      <td>51247.000000</td>\n      <td>51247.000000</td>\n      <td>51247.000000</td>\n      <td>51247.000000</td>\n      <td>51247.000000</td>\n      <td>...</td>\n      <td>51247.000000</td>\n      <td>51247.000000</td>\n      <td>51247.000000</td>\n      <td>51247.000000</td>\n      <td>51247.000000</td>\n      <td>51247.000000</td>\n      <td>51247.000000</td>\n      <td>51247.000000</td>\n      <td>51247.000000</td>\n      <td>51247.000000</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>-3.469117</td>\n      <td>-6.278187</td>\n      <td>9.479892</td>\n      <td>0.434699</td>\n      <td>11.535895</td>\n      <td>176.291646</td>\n      <td>1.188674</td>\n      <td>18.012681</td>\n      <td>14.876386</td>\n      <td>29.051809</td>\n      <td>...</td>\n      <td>36.115675</td>\n      <td>502.741343</td>\n      <td>0.533202</td>\n      <td>211.089329</td>\n      <td>12.268723</td>\n      <td>12.268722</td>\n      <td>0.848284</td>\n      <td>516.483676</td>\n      <td>0.463617</td>\n      <td>8.701622</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>0.556705</td>\n      <td>0.586477</td>\n      <td>2.439179</td>\n      <td>0.773003</td>\n      <td>2.727198</td>\n      <td>29.118399</td>\n      <td>1.147485</td>\n      <td>16.466421</td>\n      <td>21.106906</td>\n      <td>16.974289</td>\n      <td>...</td>\n      <td>6.068335</td>\n      <td>81.664870</td>\n      <td>0.882705</td>\n      <td>35.016824</td>\n      <td>2.787968</td>\n      <td>2.787973</td>\n      <td>1.286705</td>\n      <td>83.755283</td>\n      <td>0.865545</td>\n      <td>2.913345</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>-5.785082</td>\n      <td>-8.829189</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>54.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>...</td>\n      <td>11.000000</td>\n      <td>146.085000</td>\n      <td>0.000000</td>\n      <td>61.168567</td>\n      <td>2.188704</td>\n      <td>2.188704</td>\n      <td>0.000000</td>\n      <td>149.109000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>-3.879740</td>\n      <td>-6.699339</td>\n      <td>8.000000</td>\n      <td>0.000000</td>\n      <td>9.000000</td>\n      <td>160.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>17.696186</td>\n      <td>...</td>\n      <td>32.000000</td>\n      <td>458.376000</td>\n      <td>0.000000</td>\n      <td>190.573070</td>\n      <td>11.637669</td>\n      <td>11.637669</td>\n      <td>0.000000</td>\n      <td>470.446000</td>\n      <td>0.000000</td>\n      <td>6.000000</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>-3.480653</td>\n      <td>-6.319910</td>\n      <td>9.000000</td>\n      <td>0.000000</td>\n      <td>12.000000</td>\n      <td>180.000000</td>\n      <td>1.000000</td>\n      <td>11.336786</td>\n      <td>6.076020</td>\n      <td>28.832742</td>\n      <td>...</td>\n      <td>37.000000</td>\n      <td>516.482000</td>\n      <td>0.000000</td>\n      <td>215.878722</td>\n      <td>13.047850</td>\n      <td>13.047850</td>\n      <td>0.000000</td>\n      <td>530.613000</td>\n      <td>0.000000</td>\n      <td>9.000000</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>-3.069627</td>\n      <td>-5.820485</td>\n      <td>11.000000</td>\n      <td>1.000000</td>\n      <td>13.000000</td>\n      <td>196.000000</td>\n      <td>2.000000</td>\n      <td>23.098671</td>\n      <td>23.523770</td>\n      <td>40.041517</td>\n      <td>...</td>\n      <td>40.000000</td>\n      <td>558.416000</td>\n      <td>1.000000</td>\n      <td>234.220092</td>\n      <td>13.919575</td>\n      <td>13.919575</td>\n      <td>2.000000</td>\n      <td>573.685000</td>\n      <td>1.000000</td>\n      <td>11.000000</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>-1.577372</td>\n      <td>-4.088010</td>\n      <td>23.000000</td>\n      <td>6.000000</td>\n      <td>28.000000</td>\n      <td>318.000000</td>\n      <td>9.000000</td>\n      <td>124.704645</td>\n      <td>169.858278</td>\n      <td>136.508949</td>\n      <td>...</td>\n      <td>66.000000</td>\n      <td>902.998000</td>\n      <td>6.000000</td>\n      <td>380.808169</td>\n      <td>17.589617</td>\n      <td>17.589617</td>\n      <td>11.000000</td>\n      <td>904.006000</td>\n      <td>8.000000</td>\n      <td>24.000000</td>\n    </tr>\n  </tbody>\n</table>\n<p>8 rows \u00d7 65 columns</p>\n</div>\n\n\n\nThe dataframe has a two-level column index so you can index the labels by calling `df['labels']`:\n\n\n```python\ndf['labels'].hist(bins=100)\nplt.show()\n```\n\n# Linear regression benchmark\nFor a first shot we can train a ridge regression to predict the `labels` from the `mol_descriptors`.\n\nThis time we will use `sklearn`. Additionally we will also pre-process the features with a standard scaler to shift them to zero mean and scale them to unit variance.\n\nAs already mentioned, the calculation of DFT properties can be very costly. Hence, we want to have a model that extrapolates well to unseen data. Hence, we will use only 20% of the dataset for training and test on 80%.\n\n\n\n\n```python\nfrom sklearn.linear_model import LinearRegression, Ridge\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score\n\nX = df['mol_descriptors'].values\ny = df['labels'].values\n```\n\nFirst use the [`StandardScaler()`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html) to scale the features (`X`) to mean of 0 and unit variance:\n\n\n```python\n# Assign a StandardScaler object to scaler and obtain the scaled fatures as X_scaled\nscaler = None\nX_scaled = None\n\n# YOUR CODE HERE\nscaler = StandardScaler()\nscaler.fit(X)\nX_scaled = scaler.transform(X)\n\n# raise NotImplementedError()\n```\n\n\n```python\n# Scaler - 1 point\n\nassert isinstance(scaler, StandardScaler), \"The scaler should be an instance of the sklearn StandardScaler\"\nnp.testing.assert_almost_equal(np.mean(X_scaled), 0, 10)\nnp.testing.assert_almost_equal(np.var(X_scaled, axis=0).sum(), 63.)\n# Possible hidden tests\n```\n\nNext we use the [`train_test_split()`](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html?highlight=train_test_split#sklearn.model_selection.train_test_split) to split of 20% of `X_scaled` and `y` as train set and use the rest as test set:\n\n\n```python\nX_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.8, random_state=0)\n```\n\nNow use the [`Ridge()`](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Ridge.html?highlight=ridge#sklearn.linear_model.Ridge) model to fit a ridge regression with standard parameters to the train data, and assign the predictions of the fitted model on the test data to `y_pred`:\n\n\n```python\n# Instantiate a Ridge() model as model, fit it and assign the predictions to y_pred\nmodel = None\ny_pred = None\n\n# YOUR CODE HERE\nmodel = Ridge(alpha=1.0)\nmodel.fit(X_train, y_train)\ny_pred = model.predict(X_test)\n# raise NotImplementedError()\n```\n\n\n\n\n    {'alpha': 1.0,\n     'copy_X': True,\n     'fit_intercept': True,\n     'max_iter': None,\n     'normalize': False,\n     'random_state': None,\n     'solver': 'auto',\n     'tol': 0.001}\n\n\n\n\n```python\nr2_lumo_ridge = r2_score(y_test[:,0], y_pred[:,0])\nr2_homo_ridge = r2_score(y_test[:,1], y_pred[:,1])\nprint(f'R2 LUMO: {r2_lumo_ridge}\\nR2 HOMO: {r2_homo_ridge}')\n```\n\n    R2 LUMO: 0.7165829853845778\n    R2 HOMO: 0.7971295175598169\n\n\n\n```python\n# Ridge Regression - 1 point\n\nassert y_pred.shape[0] == y_test.shape[0]\nassert y_pred.shape[1] == y_test.shape[1]\nassert r2_lumo_ridge > 0.70\nassert r2_homo_ridge > 0.78\n# Possible hidden tests\n```\n\nNow we can plot the correlations of the the true and predicted values:\n\n\n```python\nfig, axs = plt.subplots(1, 2, figsize=(12,6))\n\naxs[0].scatter(y_test[:,0], y_pred[:,0], alpha=0.2, s=5)\naxs[0].plot([-6, -1], [-6, -1], 'k')\naxs[0].set_title(f'R2 LUMO: {r2_lumo_ridge}')\naxs[0].set_xlabel('true LUMO')\naxs[0].set_ylabel('predicted LUMO')\naxs[0].set_xlim([-6, -1])\naxs[0].set_ylim([-6, -1])\n\naxs[1].scatter(y_test[:,1], y_pred[:,1], alpha=0.2, s=5)\naxs[1].plot([-9, -3], [-9, -3], 'k')\naxs[1].set_title(f'R2 HOMO: {r2_homo_ridge}')\naxs[1].set_xlabel('true HOMO')\naxs[1].set_ylabel('predicted HOMO')\naxs[1].set_xlim([-9, -3])\naxs[1].set_ylim([-9, -3])\n\nplt.show()\n```\n\nAs you can see, the ridge regression learns something, but the predictions are still way off from the true values.\n\nHence, we will apply a non-linear model, namely a:\n\n# Neural Network\n\n## A little bit of biology background\n\nThe rough idea of todays neural networks stems from biological neural networks. A neuron, integrates information from its upstream neurons at the dendrites, creating a post-synaptic potential. At the axon hillock this potential is encoded into a spike train of action potentials. These are sent down he axon until they reach a synapse of an axon terminal. At the synapse the spike train is again decoded into a pre-synaptic potential and depending on the incoming spike frequency more or less neurotransmitters are released to pass the signal on to the next neuron (Figure 2).\n<p style=\"text-align:center;font-size:80%;font-style:italic\">\n    \n    <br>\n    Figure 2: Simplified sketch of a neuron.\n</p>\n\n\n## Forward Pass\n\nFor todays artificial neural networks this was simplified in the following way:  \nInstead of simulating spikes, we only simulate a spike frequency as a continuous value. Depending on the post-synaptic potential, this frequency can be higher or lower. E.g. neurons do not respond at all until a specific post-synaptic potential is reached and also have a maximum spike-frequency. This implies two things:  \n**1. The transformation from post-synaptic potential to spike-frequency is non-linear. (activation function)**  \n**2. Each neuron has a different base activity. (bias)**\n\nIn the following mathematical definitions, lower-case letters denote scalars, while upper-case letters denote vectors or matrices. No dot or $\\cdot$ denotes a dot product of vectors or matrices.\n\n### Single neuron\nGiven a subjected neuron $l$ receives inputs from an upstream layer $k$ and the upstream layer consists of three neurons with the outputs $x_1, x_2, x_3$ via connections with weights $\\theta_{1,l}, \\theta_{2,l}, \\theta_{3,l}$ (Figure 3), we can compute the weighted sum as state $h_l(X)$ of the subjected neuron by linear algebra as the product of the row vector $X_k$ and the column vector $\\Theta_{k,l}$. Additionally, we add a bias $b$ to the neuron.\n\n\\begin{align}\nh_l(X) &= X_k \\cdot \\Theta_{k,l} + b_l\\\\\n&=\n\\begin{bmatrix}\n    x_1 & x_2 & x_3\n\\end{bmatrix} \n\\cdot\n\\begin{bmatrix}\n    \\theta_{1,l} \\\\ \\theta_{2,l} \\\\ \\theta_{3,l}\n\\end{bmatrix}\n+ b_l\\\\\n&=x_1 \\theta_{1,l} +  x_2 \\theta_{2,l} + x_3 \\theta_{3,l} + b_l\n\\end{align}\n\nAnd the output or activation $a_l(x)$ of the subjected neuron in terms of spike-frequency is computed using a non-linear activation function $\\sigma()$:\n\n\\begin{align}\na_l(X) &= \\sigma(h_l(X))\n\\end{align}\n\n<div>\n\n</div>\n<p style=\"text-align:center;font-size:80%;font-style:italic\">\nFigure 3: A neuron layer k with three neurons has feed-forward connections to a single neuron l.\n</p>\n\n### Neuron Layer\nNow given that the subjected $l$ is not only a single neuron but e.g. a layer of two neurons (Figure 4), the notation is the same with the only difference that we add a column to the weight column vector $\\Theta_{k,l}$ changing it to a $3 \\times 2$ dimensional matrix to calculate the $1 \\times 2$ dimensional row state vector $H_l(X)$:\n\n\\begin{align}\n    H_l(X) &= X_k \\cdot \\Theta_{k,l} + B_l\\\\\n    &=\n    \\begin{bmatrix}\n        x_1 & x_2 & x_3\n    \\end{bmatrix} \n    \\cdot\n    \\begin{bmatrix}\n        \\theta_{1,1} & \\theta_{1,2} \\\\\n        \\theta_{2,1} & \\theta_{2,2} \\\\\n        \\theta_{3,1} & \\theta_{3,2} \n    \\end{bmatrix}\n    +\n    \\begin{bmatrix}\n        b_1 & b_2 \n    \\end{bmatrix} \\\\\n    &=\n    \\begin{bmatrix}\n        \\theta_{1,1} x_1 + \\theta_{1,2} x_2 + \\theta_{1,3} x_3 + b_1 &\n        \\theta_{2,1} x_1 + \\theta_{2,2} x_2 + \\theta_{2,3} x_3 + b_2\n    \\end{bmatrix}\n\\end{align}\n\nAnd the activation of the layer:\n\n\\begin{align}\nA_i(X) &= \\sigma(H_i(X))\n\\end{align}\n\n<div>\n\n</div>\n<p style=\"text-align:center;font-size:80%;font-style:italic\">\nFigure 4: A neuron layer j with three neurons has feed-forward connections to a neuron layer i with two neurons.\n</p>\n\nFor the bias there exist two approaches:\n1. One can see the bias as an additional input with a constant $1$ from the previous layer and a learnable weight vector.\n2. Adding the bias simply as row vector that added to the neuron state $H(x)$.\n\nHere we use approach 2.\n\n### Batches\nUsually data is processed in batches, so not only one single sample is processed at a time but multiple samples as this is much faster when calculated using vectorization. In our case, samples are rows with the length of the features. So when we pass 10 samples of our features (the `mol_descriptors`), we pass a matrix of shape $10 \\times 63$. This already fits well with our current notation. E.g. if we use a hidden layer with $32$ neurons and input our features it will return a $10 \\times 32$ state matrix.\n\n\n### Weight initialization\nTo compute anything, the weights must be different from $0$. There are several approaches to initialize weights. We will use the approach of [Glorot et Al., 2010](http://proceedings.mlr.press/v9/glorot10a.html).\nThe initial weights are drawn form a uniform distribution $U(-z, z)$ with the limit $z$ calculated as:\n\\begin{align}\n    z &= \\sqrt{\\frac{6}{k+l}}\n\\end{align}\n...with input length $k$ and output length $l$.\n\n\nJust to get an idea how this all works in python we will build a layer with 32 neurons and feed all 63 `mol_descriptors`.  \nInitialize the weight matrix `theta` using numpy functions:\n\n\n```python\n# Take 10 rows as one batch\nsample = X_train[0:10]\nn_inputs = sample.shape[1]\nn_outputs = 32\n#\u9996\u5148\u8981\u641e\u6e05\u695a\u884c\u5217\u662f\u5565?\n#\u6bcf\u884c\u662f\u4e00\u7ec4observation,\u6bcf\u5217\u662f\u4e00\u4e2afeature...\n```\n\n\n```python\n# Initialize the weights theta after Glorot et Al. 2010 (glorot uniform):\ntheta = None\n# YOUR CODE HERE\nk = n_inputs\nl = n_outputs\nz = np.sqrt(6/(k+l))\ntheta = np.random.uniform(-z,z,(k,l))\n# raise NotImplementedError()\n```\n\n\n```python\n# Weights - 1 point\n\nassert theta.shape[0] == n_inputs, \"Your weight shape doesn't match!\"\nassert theta.shape[1] == n_outputs, \"Your weight shape doesn't match!\"\n\n# Hidden asserts for the limits of the uniform distribution\n```\n\nNow calculate h(x) for the sample using your weights:\n\n\n```python\n# Initialize the bias row vector with zeros:\nb = None\n# YOUR CODE HERE\nb= np.zeros((1,n_outputs))\n# raise NotImplementedError()\n\n# Calculate h(x) using sample, theta and b\n# The bias won't change anything but it will check for correct shapes.\nh = None\n# YOUR CODE HERE\nh = np.dot(sample,theta)+b\n# raise NotImplementedError()\n```\n\n\n```python\n# States - 2 points\n\nassert h.shape[0] == sample.shape[0]\nassert h.shape[1] == n_outputs\n# Possible hidden asserts\n```\n\n## Activation functions\n\nOur model will be a regression model. For the output of the model we need to fit the unscaled `y`. Hence we need an unbound linear activation function for the output, which is basically an identity function:\n\n\\begin{align}\n    linear(H(x)) &= H(x)\n\\end{align}\n\nAs non-linear activation function for the hidden layers we will use the ReLu function:\n\n\\begin{align}\n    relu(H(x)) &= \n\\begin{cases} \n    0~\\text{ if }~h_l(x) \\leq 0\\\\\n    h_l(x)~\\text{ if }~h_l(x)>0\n\\end{cases}\n\\end{align}\n\nSo it sets all values below zero to zero.  \nThe ReLu has the biological motivation of having a minimal threshold until it starts outputting values different from 0. Additionally, it yields sparse activations in the network, which is usually favorable, and its gradient is trivial to calculate.\n\nPlease calculate the ReLu of your previously calculated `h`:\n\n\n```python\n# Calculate the activation a by computing the ReLu of h\na = None\n# YOUR CODE HERE\na = h.copy()\na[a<0] = 0\n# raise NotImplementedError()\n```\n\n\n```python\n# ReLu - 1 point\n\nassert np.min(a) >= 0\n# Possible hidden asserts\n```\n\n## Backpropagation\n\n### Weights\nFrom the lecture recall the following chain to get the gradient of the error $J$ with respect to the weights $\\Theta$ of the output layer:\n\n\\begin{align}\n\\frac{\\partial J}{\\partial \\Theta} &= \\underset{(1)}{\\frac{\\partial J}{\\partial a}} \n                                      \\underset{(2)}{\\frac{\\partial a}{\\partial h}}\n                                      \\underset{(3)}{\\frac{\\partial h}{\\partial \\Theta}} \\\\\n\\end{align}\n\nFor our case the error is the MSE defined as:\n\\begin{align}\nJ &= \\frac{1}{m} \\sum_{i=1}^m \\left( a^{(i)} - y^{(i)} \\right)^2\n\\end{align}\n...for $m$ samples $i$.\n\nEverything else is given. Now calculate the partial derivatives for a single sample $i$ of:  \n**(1) $\\frac{\\partial \\text{J}}{\\partial a^{(i)}}$ with the MSE as $J$  \n(2) $\\frac{\\partial a^{(i)}}{\\partial h^{(i)}}$ with the linear and ReLu functions as $a$  \n(3) $\\frac{\\partial h^{(i)}}{\\partial \\theta^{(i)}}$ using the calculation for a neuron layer**  \n\n\n\n```python\nfrom IPython.display import display, Markdown\n\ndisplay(Markdown(r\"\\begin{align}\"\n                 r\"\\frac{\\partial \\text{MSE}}{\\partial a^{(i)}} &= \\frac{1}{m} \\left( a^{(i)} - y^{(i)} \\right) \\tag{1}\\\\\"\n                 r\"\\frac{\\partial \\text{ReLu}^{(i)}}{\\partial h^{(i)}} &= \"\n                 r\"\\begin{cases} \"\n                 r\"0~\\text{ if }~h^{(i)}(x) \\leq 0\\\\\"\n                 r\"1~\\text{ if }~h^{(i)}(x)>0\"\n                 r\"\\end{cases} \\tag{2}\\\\\"\n                 r\"\\frac{\\partial \\text{linear}^{(i)}}{\\partial h^{(i)}} &= 1 \\tag{2}\\\\\"\n                 r\"\\frac{\\partial h^{(i)}}{\\partial \\theta^{(i)}} &= x^{(i)} \\tag{3}\"\n                 r\"\\end{align}\"))\n```\n\n\n\\begin{align}\\frac{\\partial \\text{MSE}}{\\partial a^{(i)}} &= \\frac{1}{m} \\left( a^{(i)} - y^{(i)} \\right) \\tag{1}\\\\\\frac{\\partial \\text{ReLu}^{(i)}}{\\partial h^{(i)}} &= \\begin{cases} 0~\\text{ if }~h^{(i)}(x) \\leq 0\\\\1~\\text{ if }~h^{(i)}(x)>0\\end{cases} \\tag{2}\\\\\\frac{\\partial \\text{linear}^{(i)}}{\\partial h^{(i)}} &= 1 \\tag{2}\\\\\\frac{\\partial h^{(i)}}{\\partial \\theta^{(i)}} &= x^{(i)} \\tag{3}\\end{align}\n\n\nNow let's take the above calculated `a` as output and calculate some random true labels `y_` for testing:\n\n\n```python\ny_ = np.random.uniform(low=0, high=3, size=[10, 32])\n```\n\nNext we can use the drivatives from above to calculate the gradient for one layer with ReLu activation:\n\n\\begin{align}\n\\frac{\\partial J}{\\partial \\Theta} &= \\underset{(1)}{\\frac{\\partial J}{\\partial a}} \n                                      \\underset{(2)}{\\frac{\\partial a}{\\partial h}}\n                                      \\underset{(3)}{\\frac{\\partial h}{\\partial \\Theta}} \\\\\n\\end{align}\n\n\n```python\n# We start from the back:\n\n# (3) is trivial\n#chuzhetide renshabi\n\ndh_dtheta = None\n\n# YOUR CODE HERE\ndh_dtheta = sample\n# raise NotImplementedError()\n\n# (2) for ReLu: Here you need a reference to h and maybe two steps\nda_dh = None\n# YOUR CODE HERE\n# a  ref???????\nda_dh = h.copy()\nif np.min(a) <0:\n    da_dh = np.zeros((10,32))\nelse:\n    da_dh[da_dh <=0]= 0\n    da_dh[da_dh>0] = 1\n\n# raise NotImplementedError()\n\n# (1) m is the batch size!\nm = a.shape[0]\ndJ_da = 1/m*(a-y_)\n# YOUR CODE HERE\n\n# raise NotImplementedError()\n#meishadaioyong\ndJ_dTheta = np.dot(dh_dtheta.T, (dJ_da * da_dh))\n# The error gradient with respect to the weights and the shape of the weights should agree:\nprint(dJ_dTheta.shape, theta.shape)\n```\n\n    (63, 32) (63, 32)\n\n\n\n```python\n# dh dtheta - 1 point\n\nassert dh_dtheta.shape[0] == 10\nassert dh_dtheta.shape[1] == 63\n# Hidden test for the content of dh_dtheta\n```\n\n\n```python\n# da dh - 1 point\n\nassert da_dh.shape[0] == 10\nassert da_dh.shape[1] == 32\n# Hidden test for the content of drelu_dh\n```\n\n\n```python\n# dJ dh - 1 point\n\nassert dJ_da.shape[0] == 10\nassert dJ_da.shape[1] == 32\n# Hidden test for the content of dJ_da\n```\n\nWe can then update the weights for the next step using:\n\\begin{align}\n    \\Theta_{t+1} &= \\Theta_t - \\alpha \\cdot \\frac{\\partial J}{\\partial \\Theta} \\\\\n\\end{align}\n...with learning rate $\\alpha$.\n\n### Bias \n\nBesides the weights we also need to fit the bias. The bias can be derived in the same manner, only that instead of $x$ the input is $1$. We simply multiply $1$ with the bias weights. Therefore (3) only for the bias collapses to:\n\\begin{align}\n\\frac{\\partial h^{(i)}_b}{\\partial \\theta^{(i)}_b} &= x^{(i)}_b = 1\\tag{3}\n\\end{align}\n\nNext we will build a simple feed forward network.\n\nRecall from the lecture (Figure 5):\n\n<div>\n\n</div>\n<p style=\"text-align:center;font-size:80%;font-style:italic\">\nFigure 5: Backpropagation.\n</p>\n\nFor backpropagation we are still missing the one element connecting the layers, namely $\\frac{\\partial a^2}{\\partial a^1}$:\n\\begin{align}\na^2 &= \\Theta^2 a^1 \\\\\n\\frac{\\partial a^2}{\\partial a^1} &= \\Theta^2\n\\end{align}\n\nWith this and the above derived equations we can calculated the gradient of the first (hidden) layer weights regarding the output error as:\n\\begin{align}\n\\frac{\\partial J}{\\partial \\Theta^1} &= \\underbrace{\\frac{\\partial J}{\\partial a^2}\n                                                    \\frac{\\partial a^2}{\\partial a^1}}_\\text{(a.)}\n                                        \\underbrace{\\frac{\\partial a^1}{\\partial h^1}\n                                                    \\frac{\\partial h^1}{\\partial \\Theta^1}}_\\text{(b.)} \\\\\n\\end{align}\n**The part (a.) can be calculated in the second (output) layer and is returned as upstream gradient.**\n\n**In the first (hidden) layer we can then use this gradient and combine it with part (b.) to obtain the gradient for the weights of layer 1 with respect to the output error.**\n\nLet's put this into work by building a feed forward network for our regression task with:\n\n1. The 63 `mol_descriptors` as input $x^{(i)}$\n2. One hidden layer $1$ with 32 neurons and a ReLu activation: `class HiddenLayer`\n3. One output layer $2$ with two outputs (LUMO and HOMO) with a linear (no) activation function: `class OutputLayer`\n\nBoth have a forward pass, which calculates the output of the layer, a backward pass which calculates the gradients and an update function that updates the weights using the gradients and the learning rate.\n\nOnly the `OutputLayer` has to return the part (a.) from above to then pass it on to the backward pass of the `HiddenLayer`.\n\nWe start implementing from the bottom up with the `OutputLayer` (layer 2):\n\n\n\n```python\nclass OutputLayer:\n\n    def __init__(self, n_inputs: int, n_outputs: int):\n        # Initialize (n_inputs X n_outputs)-dimensional weight matrix self.theta with a\n        # Glorot et Al. 2010 uniform initialization:\n        self.theta = None\n        # YOUR CODE HERE\n        k = n_inputs\n        l = n_outputs\n        z = np.sqrt(6/(k+l))\n        self.theta = np.random.uniform(-z,z,(k,l))\n        # raise NotImplementedError()\n        \n        # Initialize the bias vector self.b to zeros:\n        self.b = None\n        # YOUR CODE HERE\n        self.b = np.zeros(n_outputs)\n        # raise NotImplementedError()\n\n    def forward(self, input_vector):\n        self.input = input_vector\n        # Compute the states h(x) as self.h\n        self.h = None\n        # YOUR CODE HERE\n        self.h = np.dot(self.input,self.theta)\n        self.h = self.h + self.b\n        # raise NotImplementedError()\n        \n        # As this is a linear layer a(x) = h(x)\n        self.a = self.h.copy()\n        return self.a\n    \n    def backward(self, y_predicted, y_true):\n        # HINT: as we do things backwards you might have to transpose some matrices\n        \n        # partial derivative of the states with respect to the weights\n        dh2_dtheta2 = None\n        # YOUR CODE HERE\n        #why call it a back ward is that it is easier to start from back.......\n        dh2_dtheta2 = self.input\n\n\n        # raise NotImplementedError()\n        \n        # partial derivative of activations with respect to the states\n        # One as we have a linear/no activation for the regression output\n        da2_dh2 = 1\n        \n        # partial derivative of the error (MSE) with respect to the acivation\n        # infer the batch size from the input shape for normalization\n        dJ_da2 = None\n        # YOUR CODE HERE\n        m = self.a.shape[0]\n        dJ_da2 = 1/m*(y_predicted-y_true)\n        # raise NotImplementedError()\n        \n        # Gradient of the weights with respect to the error\n        # for the weight updates for this layer:\n        self.dJ_dTheta2 = None\n        # YOUR CODE HERE\n        self.dJ_dTheta2 = np.dot(dh2_dtheta2.T, (dJ_da2 * da2_dh2))\n        # raise NotImplementedError()\n        \n        # Gradient of the bias with respect to the error\n        # Recall using dh2_db2 = 1 and handle the batch size by summation\n        self.dJ_db2 = None\n        # YOUR CODE HERE\n        self.dJ_db2 = np.sum(dJ_da2,axis=0)\n        # raise NotImplementedError()\n        \n        # The downstream gradient for layer 1.\n        # employing da2_da1 = theta\n        downstream_gradient = None\n        # YOUR CODE HERE\n        #Ah, you want Dj/ da-1\n        downstream_gradient = np.dot(dJ_da2, self.theta.T)\n        # raise NotImplementedError()\n        \n        return downstream_gradient\n        \n    def update(self, learning_rate):\n        # You don't need to change this\n        # HINT:\n        # If your model gets worse instead of better make sure you calculate the correct MSE\n        self.theta = self.theta - learning_rate*self.dJ_dTheta2\n        self.b = self.b - learning_rate*self.dJ_db2\n```\n\n\n```python\nX_sample = X_train[0:100, :]\ny_sample = y_train[0:100, :]\n```\n\n\n```python\n# Output Forward Pass - 1 point\n\nl2 = OutputLayer(X_sample.shape[1], y_sample.shape[1])\ny_pred_sample = l2.forward(X_sample)\n\nassert y_sample.shape[0] == y_pred_sample.shape[0]\nassert y_sample.shape[1] == y_pred_sample.shape[1]\n```\n\n\n```python\n# Output Backward Pass - 2 points\n\ndownstream_gradient = l2.backward(y_pred_sample, y_sample)\n\nassert downstream_gradient.shape[0] == X_sample.shape[0]\nassert downstream_gradient.shape[1] == X_sample.shape[1]\n```\n\n\n```python\n# Output Weight Update - 2 points\n\nl2 = OutputLayer(X_sample.shape[1], y_sample.shape[1])\ny_pred_before = l2.forward(X_sample)\n\nfor i in range(100):\n    y_pred_sample = l2.forward(X_sample)\n    l2.backward(y_pred_sample, y_sample)\n    l2.update(0.05)\n    \ny_pred_after = l2.forward(X_sample)\nr2_before = r2_score(y_sample, y_pred_before)\nr2_after = r2_score(y_sample, y_pred_after)\n\nassert r2_before < r2_after\n```\n\nNext is the `HiddenLayer`. There are mainly two main differences you have to keep in mind here:\n1. You have to work with the ReLu activation, so $\\frac{\\partial a}{\\partial h}$ isn't $1$ anymore.\n2. We use the `upstream_gradient` for the backward pass, provided by the `backward` method of the `OutputLayer`.\n\n\n```python\nclass HiddenLayer:\n\n    def __init__(self, n_inputs: int, n_outputs: int):\n        # Initialize the weight matrix self.theta with a\n        # Glorot et Al. 2010 uniform initialization:\n        self.theta = None\n        # YOUR CODE HERE\n        k = n_inputs\n        l = n_outputs\n        z = np.sqrt(6/(k+l))\n        self.theta = np.random.uniform(-z,z,(k,l))\n        # raise NotImplementedError()\n        \n        # Initialize the bias vector to zeros:\n        self.b = None\n        # YOUR CODE HERE\n        self.b = np.zeros(n_outputs)\n        # raise NotImplementedError()\n\n    def forward(self, input_vector):\n        self.input = input_vector\n        # Compute the states h(x) as self.h\n        self.h = None\n        # YOUR CODE HERE\n        self.h = np.dot(self.input,self.theta)\n        self.h += self.b\n        # raise NotImplementedError()\n        \n        # Compute the activations a(x) as self.a with ReLu activation\n        self.a = None\n        # YOUR CODE HERE\n        temp = self.h.copy()\n        temp[temp<= 0] = 0\n        self.a = temp.copy()\n        del temp\n        # raise NotImplementedError()\n        \n        return self.a\n    \n    def backward(self, upstream_gradient):\n        # HINT: as we do things backwards you might have to transpose some matrices\n        \n        # Gradient of the states with respect to the inputs (trivial):\n        dh1_dtheta1 = None\n        # YOUR CODE HERE\n        dh1_dtheta1 = self.input\n        # raise NotImplementedError()\n        \n        # Gradient of the activations with respect to the states:\n        # Remember to apply ReLu here\n        da1_dh1 = None\n        # YOUR CODE HERE\n        da1_dh1 = self.h.copy()\n        da1_dh1[da1_dh1<=0]=0\n        da1_dh1[da1_dh1>0] = 1\n        # raise NotImplementedError()\n        \n        # Gradient of the error with respect to the weights:\n        # Now we can finally use the upstream gradient...\n        self.dJ_dTheta1 = None\n        # YOUR CODE HERE\n        self.dJ_dTheta1 = np.dot(dh1_dtheta1.T, (upstream_gradient * da1_dh1))\n        # raise NotImplementedError()\n        \n        # And for the bias, similar to the output layer but this time\n        # using the upstream gradient:\n        self.dJ_db1 = None\n        # YOUR CODE HERE\n        self.dJ_db1 = np.sum(upstream_gradient,axis=0)\n        # raise NotImplementedError()\n        \n    def update(self, learning_rate):\n        # You don't need to change this\n        self.theta = self.theta - learning_rate*self.dJ_dTheta1\n        self.b = self.b - learning_rate*self.dJ_db1\n```\n\n\n```python\n# We create a sample from the existing data that matches the output dimension \n# and also shift it above zero, so it is learnable with ReLu:\n\nn_hidden = 32\n\nX_sample = X_train[0:100, :]\ny_sample = np.array([y_train[i*100:i*100+100, 0] for i in range(n_hidden)]).T\ny_sample = y_sample-y_sample.min()\n```\n\n\n```python\n# Hidden Forward Pass - 1 point\n\nl1 = HiddenLayer(X_sample.shape[1], n_hidden)\n\ny_pred_sample = l1.forward(X_sample)\nassert y_pred_sample.shape[0] == X_sample.shape[0]\nassert y_pred_sample.shape[1] == n_hidden\nassert y_pred_sample.min() >= 0\n```\n\n\n```python\n# Hidden Weight Update - 2 points\n\nl1 = HiddenLayer(X_sample.shape[1], n_hidden)\ny_pred_before = l1.forward(X_sample)\n\nfor i in range(100):\n    y_pred_sample = l1.forward(X_sample)\n    downstream_gradient = 1/100 * (y_pred_sample-y_sample)\n    l1.backward(downstream_gradient)\n    l1.update(0.05)\n    \ny_pred_after = l1.forward(X_sample)\nr2_before = r2_score(y_sample, y_pred_before)\nr2_after = r2_score(y_sample, y_pred_after)\n\nassert r2_before < r2_after\n```\n\n## NN Training\n\nOkay now let's see whether we can be better with our network than the benchmark ridge regression.\n\nAs said before we will train our network in batches (`batch_size`) and for `n_epochs`.  \nPer epoch we therefore have to pass `X_train.shape[0] // batch_size` batches.  \nFor each epoch we randomly shuffle the dataset. Using `np.random.permutation(X_train.shape[0])` we generate a randomly shuffled index. Indexing X and y with slices of this shuffled index, creates differently shuffled batches for each epoch.\n\n\n```python\nn_hidden = 64\nlr = 0.05\nn_epochs = 60\nbatch_size = 100\nn_batches = X_train.shape[0] // batch_size\n\nl1 = HiddenLayer(X_train.shape[1], n_hidden)\nl2 = OutputLayer(n_hidden, y_train.shape[1])\n\ny_pred_before = l2.forward(l1.forward(X_test))\n```\n\n\n```python\nfor epoch in range(n_epochs):\n    permutation = np.random.permutation(X_train.shape[0])\n    \n    for batch in range(n_batches):\n        start = batch*batch_size\n        end = start+batch_size\n        X_batch = X_train[permutation[start:end]]\n        y_batch = y_train[permutation[start:end]]\n        \n        # Get the predictions\n        y_pred = None\n        # YOUR CODE HERE\n        y_pred = l2.forward(l1.forward(X_batch))\n\n        # raise NotImplementedError()\n\n        # Do the backward pass of both layers and update the weights\n        # YOUR CODE HERE\n        downstream_gradient = l2.backward(y_pred,y_batch)\n        l2.update(lr)\n        l1.backward(downstream_gradient)\n        l1.update(lr)\n        # raise NotImplementedError()\n        \n    y_pred = l2.forward(l1.forward(X_test))\n    if epoch%4 == 0:\n        print(f\"Epoch {epoch}: Test R2 = {r2_score(y_test, y_pred)}\")\n    \n```\n\n    Epoch 0: Test R2 = 0.3135007441059437\n    Epoch 4: Test R2 = 0.6818742354820766\n    Epoch 8: Test R2 = 0.7541999178040204\n    Epoch 12: Test R2 = 0.7735264940103128\n    Epoch 16: Test R2 = 0.766444225749243\n    Epoch 20: Test R2 = 0.7975829512713322\n    Epoch 24: Test R2 = 0.8035754202604943\n    Epoch 28: Test R2 = 0.802916312128392\n    Epoch 32: Test R2 = 0.80923422543202\n    Epoch 36: Test R2 = 0.8104614898963678\n    Epoch 40: Test R2 = 0.8160932172136297\n    Epoch 44: Test R2 = 0.815289625402196\n    Epoch 48: Test R2 = 0.8218650938725245\n    Epoch 52: Test R2 = 0.8227658214323406\n    Epoch 56: Test R2 = 0.8247257439337223\n\n\n\n```python\n# Full Training - 2 points\n\ny_pred_after = l2.forward(l1.forward(X_test))\n\nr2_before = r2_score(y_test, y_pred_before)\nr2_after = r2_score(y_test, y_pred_after)\n\nassert r2_before < r2_after\n```\n\n\n```python\ny_pred = l2.forward(l1.forward(X_test))\n\nr2_lumo_nn = r2_score(y_test[:,0], y_pred[:,0])\nr2_homo_nn = r2_score(y_test[:,1], y_pred[:,1])\nprint(f'R2 LUMO: {r2_lumo_nn}\\nR2 HOMO: {r2_homo_nn}')\n```\n\n    R2 LUMO: 0.781655082468047\n    R2 HOMO: 0.8711996905518564\n\n\n\n```python\n# Bonus Beating Ridge - 1 point\n\nprint(f'\\tRidge\\t\\t\\tNN\\nLUMO\\t{r2_lumo_ridge}\\t{r2_lumo_nn}\\nHOMO\\t{r2_homo_ridge}\\t{r2_homo_nn}')\n\nassert r2_lumo_nn > r2_lumo_ridge and r2_homo_nn > r2_homo_ridge\n```\n\n    \tRidge\t\t\tNN\n    LUMO\t0.7165829853845778\t0.781655082468047\n    HOMO\t0.7971295175598169\t0.8711996905518564\n\n\nQuite possibly you were able to beat the ridge regression at that point, only with one hidden ReLu layer. Of course the hyperparameters of both models haven't been optimized yet, so you can get even better. But please do this in a separate notebook ;)\n\nLet's have a look at the final plots:\n\n\n```python\nfig, axs = plt.subplots(1, 2, figsize=(12,6))\n\naxs[0].scatter(y_test[:,0], y_pred[:,0], alpha=0.2, s=5)\naxs[0].plot([-6, -1], [-6, -1], 'k')\naxs[0].set_title(f'R2 LUMO: {r2_lumo_nn}')\naxs[0].set_xlabel('true LUMO')\naxs[0].set_ylabel('predicted LUMO')\naxs[0].set_xlim([-6, -1])\naxs[0].set_ylim([-6, -1])\n\naxs[1].scatter(y_test[:,1], y_pred[:,1], alpha=0.2, s=5)\naxs[1].plot([-9, -3], [-9, -3], 'k')\naxs[1].set_title(f'R2 HOMO: {r2_homo_nn}')\naxs[1].set_xlabel('true HOMO')\naxs[1].set_ylabel('predicted HOMO')\naxs[1].set_xlim([-9, -3])\naxs[1].set_ylim([-9, -3])\n\nplt.show()\n```\n\n**You finished the Exercise!**\n\nNext time we will start using Tensorflow and Keras to build neural networks.  \n\nHere is a little example for our application. Be aware that Tensorflow does things slightly different internally, so it might give results that differ from your own implementation.\n\nYou can use this example as a start to experiment with own implementations **in another notebook**:\n\n\n```python\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\nn_hidden = 64\nlr = 0.05\n# A low number of epochs so the nb doesn't slow down during grading\nn_epochs = 5\nbatch_size = 100\n\ninputs = keras.Input(shape=(X.shape[1],))\nhidden1 = layers.Dense(n_hidden, activation='relu')(inputs)\noutputs = layers.Dense(2, activation='linear')(hidden1)\nmodel = keras.Model(inputs=inputs, outputs=outputs, name=\"simple_ff\")\nprint(model.summary())\n\nmodel.compile(\n    loss=keras.losses.MeanSquaredError(),\n    optimizer=keras.optimizers.SGD(),\n    metrics=[\"MSE\"],\n)\n\nmodel.fit(X_train, y_train, batch_size=batch_size, epochs=n_epochs)\n\ny_pred = model.predict(X_test)\nr2_lumo_keras = r2_score(y_test[:,0], y_pred[:,0])\nr2_homo_keras = r2_score(y_test[:,1], y_pred[:,1])\nprint(f'R2 LUMO: {r2_lumo_keras}\\nR2 HOMO: {r2_homo_keras}')\n\nfig, axs = plt.subplots(1, 2, figsize=(12,6))\n\naxs[0].scatter(y_test[:,0], y_pred[:,0], alpha=0.2, s=5)\naxs[0].plot([-6, -1], [-6, -1], 'k')\naxs[0].set_title(f'R2 LUMO: {r2_lumo_keras}')\naxs[0].set_xlabel('true LUMO')\naxs[0].set_ylabel('predicted LUMO')\naxs[0].set_xlim([-6, -1])\naxs[0].set_ylim([-6, -1])\n\naxs[1].scatter(y_test[:,1], y_pred[:,1], alpha=0.2, s=5)\naxs[1].plot([-9, -3], [-9, -3], 'k')\naxs[1].set_title(f'R2 HOMO: {r2_homo_keras}')\naxs[1].set_xlabel('true HOMO')\naxs[1].set_ylabel('predicted HOMO')\naxs[1].set_xlim([-9, -3])\naxs[1].set_ylim([-9, -3])\n\nplt.show()\n```\n", "meta": {"hexsha": "deeab36faedfa3d7523a6502725bb57e141b24a8", "size": 854805, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "RepeatExpriment/Exercise06.ipynb", "max_stars_repo_name": "fliaght/YouCanAdvance", "max_stars_repo_head_hexsha": "ddfc0ef20438ea2fefd49b87d3620de41da6ec21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RepeatExpriment/Exercise06.ipynb", "max_issues_repo_name": "fliaght/YouCanAdvance", "max_issues_repo_head_hexsha": "ddfc0ef20438ea2fefd49b87d3620de41da6ec21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RepeatExpriment/Exercise06.ipynb", "max_forks_repo_name": "fliaght/YouCanAdvance", "max_forks_repo_head_hexsha": "ddfc0ef20438ea2fefd49b87d3620de41da6ec21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 344.4016921837, "max_line_length": 186236, "alphanum_fraction": 0.9263013202, "converted": true, "num_tokens": 12743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28457600421652673, "lm_q2_score": 0.08269734210984904, "lm_q1q2_score": 0.023533679176947955}}
{"text": "# Physics 256\n## Radioactive Decay\n\n\n\n\n```python\nimport style\nstyle._set_css_style('../include/bootstrap.css')\n```\n\n\n\n\n<style>/*!\n * Bootstrap v3.0.3 (http://getbootstrap.com)\n * Copyright 2013 Twitter, Inc.\n * Licensed under http://www.apache.org/licenses/LICENSE-2.0\n */\n\n/*! normalize.css v2.1.3 | MIT License | git.io/normalize */\n\narticle,\naside,\ndetails,\nfigcaption,\nfigure,\nfooter,\nheader,\nhgroup,\nmain,\nnav,\nsection,\nsummary {\n  display: block;\n}\n\naudio,\ncanvas,\nvideo {\n  display: inline-block;\n}\n\naudio:not([controls]) {\n  display: none;\n  height: 0;\n}\n\n[hidden],\ntemplate {\n  display: none;\n}\n\nhtml {\n  font-family: sans-serif;\n  -webkit-text-size-adjust: 100%;\n      -ms-text-size-adjust: 100%;\n}\n\nbody {\n  margin: 0;\n}\n\na {\n  background: transparent;\n}\n\na:focus {\n  outline: thin dotted;\n}\n\na:active,\na:hover {\n  outline: 0;\n}\n\nh1 {\n  margin: 0.67em 0;\n  font-size: 2em;\n}\n\nabbr[title] {\n  border-bottom: 1px dotted;\n}\n\nb,\nstrong {\n  font-weight: bold;\n}\n\ndfn {\n  font-style: italic;\n}\n\nhr {\n  height: 0;\n  -moz-box-sizing: content-box;\n       box-sizing: content-box;\n}\n\nmark {\n  color: #000;\n  background: #ff0;\n}\n\ncode,\nkbd,\npre,\nsamp {\n  font-family: monospace, serif;\n  font-size: 1em;\n}\n\npre {\n  white-space: pre-wrap;\n}\n\nq {\n  quotes: \"\\201C\" \"\\201D\" \"\\2018\" \"\\2019\";\n}\n\nsmall {\n  font-size: 80%;\n}\n\nsub,\nsup {\n  position: relative;\n  font-size: 75%;\n  line-height: 0;\n  vertical-align: baseline;\n}\n\nsup {\n  top: -0.5em;\n}\n\nsub {\n  bottom: -0.25em;\n}\n\nimg {\n  border: 0;\n}\n\nsvg:not(:root) {\n  overflow: hidden;\n}\n\nfigure {\n  margin: 0;\n}\n\nfieldset {\n  padding: 0.35em 0.625em 0.75em;\n  margin: 0 2px;\n  border: 1px solid #c0c0c0;\n}\n\nlegend {\n  padding: 0;\n  border: 0;\n}\n\nbutton,\ninput,\nselect,\ntextarea {\n  margin: 0;\n  font-family: inherit;\n  font-size: 100%;\n}\n\nbutton,\ninput {\n  line-height: normal;\n}\n\nbutton,\nselect {\n  text-transform: none;\n}\n\nbutton,\nhtml input[type=\"button\"],\ninput[type=\"reset\"],\ninput[type=\"submit\"] {\n  cursor: pointer;\n  -webkit-appearance: button;\n}\n\nbutton[disabled],\nhtml input[disabled] {\n  cursor: default;\n}\n\ninput[type=\"checkbox\"],\ninput[type=\"radio\"] {\n  padding: 0;\n  box-sizing: border-box;\n}\n\ninput[type=\"search\"] {\n  -webkit-box-sizing: content-box;\n     -moz-box-sizing: content-box;\n          box-sizing: content-box;\n  -webkit-appearance: textfield;\n}\n\ninput[type=\"search\"]::-webkit-search-cancel-button,\ninput[type=\"search\"]::-webkit-search-decoration {\n  -webkit-appearance: none;\n}\n\nbutton::-moz-focus-inner,\ninput::-moz-focus-inner {\n  padding: 0;\n  border: 0;\n}\n\ntextarea {\n  overflow: auto;\n  vertical-align: top;\n}\n\ntable {\n  border-collapse: collapse;\n  border-spacing: 0;\n}\n\n@media print {\n  * {\n    color: #000 !important;\n    text-shadow: none !important;\n    background: transparent !important;\n    box-shadow: none !important;\n  }\n  a,\n  a:visited {\n    text-decoration: underline;\n  }\n  a[href]:after {\n    content: \" (\" attr(href) \")\";\n  }\n  abbr[title]:after {\n    content: \" (\" attr(title) \")\";\n  }\n  a[href^=\"javascript:\"]:after,\n  a[href^=\"#\"]:after {\n    content: \"\";\n  }\n  pre,\n  blockquote {\n    border: 1px solid #999;\n    page-break-inside: avoid;\n  }\n  thead {\n    display: table-header-group;\n  }\n  tr,\n  img {\n    page-break-inside: avoid;\n  }\n  img {\n    max-width: 100% !important;\n  }\n  @page  {\n    margin: 2cm .5cm;\n  }\n  p,\n  h2,\n  h3 {\n    orphans: 3;\n    widows: 3;\n  }\n  h2,\n  h3 {\n    page-break-after: avoid;\n  }\n  select {\n    background: #fff !important;\n  }\n  .navbar {\n    display: none;\n  }\n  .table td,\n  .table th {\n    background-color: #fff !important;\n  }\n  .btn > .caret,\n  .dropup > .btn > .caret {\n    border-top-color: #000 !important;\n  }\n  .label {\n    border: 1px solid #000;\n  }\n  .table {\n    border-collapse: collapse !important;\n  }\n  .table-bordered th,\n  .table-bordered td {\n    border: 1px solid #ddd !important;\n  }\n}\n\n*,\n*:before,\n*:after {\n  -webkit-box-sizing: border-box;\n     -moz-box-sizing: border-box;\n          box-sizing: border-box;\n}\n\nhtml {\n  font-size: 62.5%;\n  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);\n}\n\nbody {\n  font-family: \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n  font-size: 14px;\n  line-height: 1.428571429;\n  color: #333333;\n  background-color: #ffffff;\n}\n\ninput,\nbutton,\nselect,\ntextarea {\n  font-family: inherit;\n  font-size: inherit;\n  line-height: inherit;\n}\n\na {\n  color: #428bca;\n  text-decoration: none;\n}\n\na:hover,\na:focus {\n  color: #2a6496;\n  text-decoration: underline;\n}\n\na:focus {\n  outline: thin dotted;\n  outline: 5px auto -webkit-focus-ring-color;\n  outline-offset: -2px;\n}\n\nimg {\n  vertical-align: middle;\n}\n\n.img-responsive {\n  display: block;\n  height: auto;\n  max-width: 100%;\n}\n\n.img-rounded {\n  border-radius: 6px;\n}\n\n.img-thumbnail {\n  display: inline-block;\n  height: auto;\n  max-width: 100%;\n  padding: 4px;\n  line-height: 1.428571429;\n  background-color: #ffffff;\n  border: 1px solid #dddddd;\n  border-radius: 4px;\n  -webkit-transition: all 0.2s ease-in-out;\n          transition: all 0.2s ease-in-out;\n}\n\n.img-circle {\n  border-radius: 50%;\n}\n\nhr {\n  margin-top: 20px;\n  margin-bottom: 20px;\n  border: 0;\n  border-top: 1px solid #eeeeee;\n}\n\n.sr-only {\n  position: absolute;\n  width: 1px;\n  height: 1px;\n  padding: 0;\n  margin: -1px;\n  overflow: hidden;\n  clip: rect(0, 0, 0, 0);\n  border: 0;\n}\n\nh1,\nh2,\nh3,\nh4,\nh5,\nh6,\n.h1,\n.h2,\n.h3,\n.h4,\n.h5,\n.h6 {\n  font-family: \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n  font-weight: 500;\n  line-height: 1.1;\n  color: inherit;\n}\n\nh1 small,\nh2 small,\nh3 small,\nh4 small,\nh5 small,\nh6 small,\n.h1 small,\n.h2 small,\n.h3 small,\n.h4 small,\n.h5 small,\n.h6 small,\nh1 .small,\nh2 .small,\nh3 .small,\nh4 .small,\nh5 .small,\nh6 .small,\n.h1 .small,\n.h2 .small,\n.h3 .small,\n.h4 .small,\n.h5 .small,\n.h6 .small {\n  font-weight: normal;\n  line-height: 1;\n  color: #999999;\n}\n\nh1,\nh2,\nh3 {\n  margin-top: 20px;\n  margin-bottom: 10px;\n}\n\nh1 small,\nh2 small,\nh3 small,\nh1 .small,\nh2 .small,\nh3 .small {\n  font-size: 65%;\n}\n\nh4,\nh5,\nh6 {\n  margin-top: 10px;\n  margin-bottom: 10px;\n}\n\nh4 small,\nh5 small,\nh6 small,\nh4 .small,\nh5 .small,\nh6 .small {\n  font-size: 75%;\n}\n\nh1,\n.h1 {\n  font-size: 36px;\n}\n\nh2,\n.h2 {\n  font-size: 30px;\n}\n\nh3,\n.h3 {\n  font-size: 24px;\n}\n\nh4,\n.h4 {\n  font-size: 18px;\n}\n\nh5,\n.h5 {\n  font-size: 14px;\n}\n\nh6,\n.h6 {\n  font-size: 12px;\n}\n\np {\n  margin: 0 0 10px;\n}\n\n.lead {\n  margin-bottom: 20px;\n  font-size: 16px;\n  font-weight: 200;\n  line-height: 1.4;\n}\n\n@media (min-width: 768px) {\n  .lead {\n    font-size: 21px;\n  }\n}\n\nsmall,\n.small {\n  font-size: 85%;\n}\n\ncite {\n  font-style: normal;\n}\n\n.text-muted {\n  color: #999999;\n}\n\n.text-primary {\n  color: #428bca;\n}\n\n.text-primary:hover {\n  color: #3071a9;\n}\n\n.text-warning {\n  color: #8a6d3b;\n}\n\n.text-warning:hover {\n  color: #66512c;\n}\n\n.text-danger {\n  color: #a94442;\n}\n\n.text-danger:hover {\n  color: #843534;\n}\n\n.text-success {\n  color: #3c763d;\n}\n\n.text-success:hover {\n  color: #2b542c;\n}\n\n.text-info {\n  color: #31708f;\n}\n\n.text-info:hover {\n  color: #245269;\n}\n\n.text-left {\n  text-align: left;\n}\n\n.text-right {\n  text-align: right;\n}\n\n.text-center {\n  text-align: center;\n}\n\n.page-header {\n  padding-bottom: 9px;\n  margin: 40px 0 20px;\n  border-bottom: 1px solid #eeeeee;\n}\n\nul,\nol {\n  margin-top: 0;\n  margin-bottom: 10px;\n}\n\nul ul,\nol ul,\nul ol,\nol ol {\n  margin-bottom: 0;\n}\n\n.list-unstyled {\n  padding-left: 0;\n  list-style: none;\n}\n\n.list-inline {\n  padding-left: 0;\n  list-style: none;\n}\n\n.list-inline > li {\n  display: inline-block;\n  padding-right: 5px;\n  padding-left: 5px;\n}\n\n.list-inline > li:first-child {\n  padding-left: 0;\n}\n\ndl {\n  margin-top: 0;\n  margin-bottom: 20px;\n}\n\ndt,\ndd {\n  line-height: 1.428571429;\n}\n\ndt {\n  font-weight: bold;\n}\n\ndd {\n  margin-left: 0;\n}\n\n@media (min-width: 768px) {\n  .dl-horizontal dt {\n    float: left;\n    width: 160px;\n    overflow: hidden;\n    clear: left;\n    text-align: right;\n    text-overflow: ellipsis;\n    white-space: nowrap;\n  }\n  .dl-horizontal dd {\n    margin-left: 180px;\n  }\n  .dl-horizontal dd:before,\n  .dl-horizontal dd:after {\n    display: table;\n    content: \" \";\n  }\n  .dl-horizontal dd:after {\n    clear: both;\n  }\n  .dl-horizontal dd:before,\n  .dl-horizontal dd:after {\n    display: table;\n    content: \" \";\n  }\n  .dl-horizontal dd:after {\n    clear: both;\n  }\n}\n\nabbr[title],\nabbr[data-original-title] {\n  cursor: help;\n  border-bottom: 1px dotted #999999;\n}\n\n.initialism {\n  font-size: 90%;\n  text-transform: uppercase;\n}\n\nblockquote {\n  padding: 10px 20px;\n  margin: 0 0 20px;\n  border-left: 5px solid #eeeeee;\n}\n\nblockquote p {\n  font-size: 17.5px;\n  font-weight: 300;\n  line-height: 1.25;\n}\n\nblockquote p:last-child {\n  margin-bottom: 0;\n}\n\nblockquote small,\nblockquote .small {\n  display: block;\n  line-height: 1.428571429;\n  color: #999999;\n}\n\nblockquote small:before,\nblockquote .small:before {\n  content: '\\2014 \\00A0';\n}\n\nblockquote.pull-right {\n  padding-right: 15px;\n  padding-left: 0;\n  border-right: 5px solid #eeeeee;\n  border-left: 0;\n}\n\nblockquote.pull-right p,\nblockquote.pull-right small,\nblockquote.pull-right .small {\n  text-align: right;\n}\n\nblockquote.pull-right small:before,\nblockquote.pull-right .small:before {\n  content: '';\n}\n\nblockquote.pull-right small:after,\nblockquote.pull-right .small:after {\n  content: '\\00A0 \\2014';\n}\n\nblockquote:before,\nblockquote:after {\n  content: \"\";\n}\n\naddress {\n  margin-bottom: 20px;\n  font-style: normal;\n  line-height: 1.428571429;\n}\n\ncode,\nkbd,\npre,\nsamp {\n  font-family: Menlo, Monaco, Consolas, \"Courier New\", monospace;\n}\n\ncode {\n  padding: 2px 4px;\n  font-size: 90%;\n  color: #c7254e;\n  white-space: nowrap;\n  background-color: #f9f2f4;\n  border-radius: 4px;\n}\n\npre {\n  display: block;\n  padding: 9.5px;\n  margin: 0 0 10px;\n  font-size: 13px;\n  line-height: 1.428571429;\n  color: #333333;\n  word-break: break-all;\n  word-wrap: break-word;\n  background-color: #f5f5f5;\n  border: 1px solid #cccccc;\n  border-radius: 4px;\n}\n\npre code {\n  padding: 0;\n  font-size: inherit;\n  color: inherit;\n  white-space: pre-wrap;\n  background-color: transparent;\n  border-radius: 0;\n}\n\n.pre-scrollable {\n  max-height: 340px;\n  overflow-y: scroll;\n}\n\n.container {\n  padding-right: 15px;\n  padding-left: 15px;\n  margin-right: auto;\n  margin-left: auto;\n}\n\n.container:before,\n.container:after {\n  display: table;\n  content: \" \";\n}\n\n.container:after {\n  clear: both;\n}\n\n.container:before,\n.container:after {\n  display: table;\n  content: \" \";\n}\n\n.container:after {\n  clear: both;\n}\n\n@media (min-width: 768px) {\n  .container {\n    width: 750px;\n  }\n}\n\n@media (min-width: 992px) {\n  .container {\n    width: 970px;\n  }\n}\n\n@media (min-width: 1200px) {\n  .container {\n    width: 1170px;\n  }\n}\n\n.row {\n  margin-right: -15px;\n  margin-left: -15px;\n}\n\n.row:before,\n.row:after {\n  display: table;\n  content: \" \";\n}\n\n.row:after {\n  clear: both;\n}\n\n.row:before,\n.row:after {\n  display: table;\n  content: \" \";\n}\n\n.row:after {\n  clear: both;\n}\n\n.col-xs-1,\n.col-sm-1,\n.col-md-1,\n.col-lg-1,\n.col-xs-2,\n.col-sm-2,\n.col-md-2,\n.col-lg-2,\n.col-xs-3,\n.col-sm-3,\n.col-md-3,\n.col-lg-3,\n.col-xs-4,\n.col-sm-4,\n.col-md-4,\n.col-lg-4,\n.col-xs-5,\n.col-sm-5,\n.col-md-5,\n.col-lg-5,\n.col-xs-6,\n.col-sm-6,\n.col-md-6,\n.col-lg-6,\n.col-xs-7,\n.col-sm-7,\n.col-md-7,\n.col-lg-7,\n.col-xs-8,\n.col-sm-8,\n.col-md-8,\n.col-lg-8,\n.col-xs-9,\n.col-sm-9,\n.col-md-9,\n.col-lg-9,\n.col-xs-10,\n.col-sm-10,\n.col-md-10,\n.col-lg-10,\n.col-xs-11,\n.col-sm-11,\n.col-md-11,\n.col-lg-11,\n.col-xs-12,\n.col-sm-12,\n.col-md-12,\n.col-lg-12 {\n  position: relative;\n  min-height: 1px;\n  padding-right: 15px;\n  padding-left: 15px;\n}\n\n.col-xs-1,\n.col-xs-2,\n.col-xs-3,\n.col-xs-4,\n.col-xs-5,\n.col-xs-6,\n.col-xs-7,\n.col-xs-8,\n.col-xs-9,\n.col-xs-10,\n.col-xs-11,\n.col-xs-12 {\n  float: left;\n}\n\n.col-xs-12 {\n  width: 100%;\n}\n\n.col-xs-11 {\n  width: 91.66666666666666%;\n}\n\n.col-xs-10 {\n  width: 83.33333333333334%;\n}\n\n.col-xs-9 {\n  width: 75%;\n}\n\n.col-xs-8 {\n  width: 66.66666666666666%;\n}\n\n.col-xs-7 {\n  width: 58.333333333333336%;\n}\n\n.col-xs-6 {\n  width: 50%;\n}\n\n.col-xs-5 {\n  width: 41.66666666666667%;\n}\n\n.col-xs-4 {\n  width: 33.33333333333333%;\n}\n\n.col-xs-3 {\n  width: 25%;\n}\n\n.col-xs-2 {\n  width: 16.666666666666664%;\n}\n\n.col-xs-1 {\n  width: 8.333333333333332%;\n}\n\n.col-xs-pull-12 {\n  right: 100%;\n}\n\n.col-xs-pull-11 {\n  right: 91.66666666666666%;\n}\n\n.col-xs-pull-10 {\n  right: 83.33333333333334%;\n}\n\n.col-xs-pull-9 {\n  right: 75%;\n}\n\n.col-xs-pull-8 {\n  right: 66.66666666666666%;\n}\n\n.col-xs-pull-7 {\n  right: 58.333333333333336%;\n}\n\n.col-xs-pull-6 {\n  right: 50%;\n}\n\n.col-xs-pull-5 {\n  right: 41.66666666666667%;\n}\n\n.col-xs-pull-4 {\n  right: 33.33333333333333%;\n}\n\n.col-xs-pull-3 {\n  right: 25%;\n}\n\n.col-xs-pull-2 {\n  right: 16.666666666666664%;\n}\n\n.col-xs-pull-1 {\n  right: 8.333333333333332%;\n}\n\n.col-xs-pull-0 {\n  right: 0;\n}\n\n.col-xs-push-12 {\n  left: 100%;\n}\n\n.col-xs-push-11 {\n  left: 91.66666666666666%;\n}\n\n.col-xs-push-10 {\n  left: 83.33333333333334%;\n}\n\n.col-xs-push-9 {\n  left: 75%;\n}\n\n.col-xs-push-8 {\n  left: 66.66666666666666%;\n}\n\n.col-xs-push-7 {\n  left: 58.333333333333336%;\n}\n\n.col-xs-push-6 {\n  left: 50%;\n}\n\n.col-xs-push-5 {\n  left: 41.66666666666667%;\n}\n\n.col-xs-push-4 {\n  left: 33.33333333333333%;\n}\n\n.col-xs-push-3 {\n  left: 25%;\n}\n\n.col-xs-push-2 {\n  left: 16.666666666666664%;\n}\n\n.col-xs-push-1 {\n  left: 8.333333333333332%;\n}\n\n.col-xs-push-0 {\n  left: 0;\n}\n\n.col-xs-offset-12 {\n  margin-left: 100%;\n}\n\n.col-xs-offset-11 {\n  margin-left: 91.66666666666666%;\n}\n\n.col-xs-offset-10 {\n  margin-left: 83.33333333333334%;\n}\n\n.col-xs-offset-9 {\n  margin-left: 75%;\n}\n\n.col-xs-offset-8 {\n  margin-left: 66.66666666666666%;\n}\n\n.col-xs-offset-7 {\n  margin-left: 58.333333333333336%;\n}\n\n.col-xs-offset-6 {\n  margin-left: 50%;\n}\n\n.col-xs-offset-5 {\n  margin-left: 41.66666666666667%;\n}\n\n.col-xs-offset-4 {\n  margin-left: 33.33333333333333%;\n}\n\n.col-xs-offset-3 {\n  margin-left: 25%;\n}\n\n.col-xs-offset-2 {\n  margin-left: 16.666666666666664%;\n}\n\n.col-xs-offset-1 {\n  margin-left: 8.333333333333332%;\n}\n\n.col-xs-offset-0 {\n  margin-left: 0;\n}\n\n@media (min-width: 768px) {\n  .col-sm-1,\n  .col-sm-2,\n  .col-sm-3,\n  .col-sm-4,\n  .col-sm-5,\n  .col-sm-6,\n  .col-sm-7,\n  .col-sm-8,\n  .col-sm-9,\n  .col-sm-10,\n  .col-sm-11,\n  .col-sm-12 {\n    float: left;\n  }\n  .col-sm-12 {\n    width: 100%;\n  }\n  .col-sm-11 {\n    width: 91.66666666666666%;\n  }\n  .col-sm-10 {\n    width: 83.33333333333334%;\n  }\n  .col-sm-9 {\n    width: 75%;\n  }\n  .col-sm-8 {\n    width: 66.66666666666666%;\n  }\n  .col-sm-7 {\n    width: 58.333333333333336%;\n  }\n  .col-sm-6 {\n    width: 50%;\n  }\n  .col-sm-5 {\n    width: 41.66666666666667%;\n  }\n  .col-sm-4 {\n    width: 33.33333333333333%;\n  }\n  .col-sm-3 {\n    width: 25%;\n  }\n  .col-sm-2 {\n    width: 16.666666666666664%;\n  }\n  .col-sm-1 {\n    width: 8.333333333333332%;\n  }\n  .col-sm-pull-12 {\n    right: 100%;\n  }\n  .col-sm-pull-11 {\n    right: 91.66666666666666%;\n  }\n  .col-sm-pull-10 {\n    right: 83.33333333333334%;\n  }\n  .col-sm-pull-9 {\n    right: 75%;\n  }\n  .col-sm-pull-8 {\n    right: 66.66666666666666%;\n  }\n  .col-sm-pull-7 {\n    right: 58.333333333333336%;\n  }\n  .col-sm-pull-6 {\n    right: 50%;\n  }\n  .col-sm-pull-5 {\n    right: 41.66666666666667%;\n  }\n  .col-sm-pull-4 {\n    right: 33.33333333333333%;\n  }\n  .col-sm-pull-3 {\n    right: 25%;\n  }\n  .col-sm-pull-2 {\n    right: 16.666666666666664%;\n  }\n  .col-sm-pull-1 {\n    right: 8.333333333333332%;\n  }\n  .col-sm-pull-0 {\n    right: 0;\n  }\n  .col-sm-push-12 {\n    left: 100%;\n  }\n  .col-sm-push-11 {\n    left: 91.66666666666666%;\n  }\n  .col-sm-push-10 {\n    left: 83.33333333333334%;\n  }\n  .col-sm-push-9 {\n    left: 75%;\n  }\n  .col-sm-push-8 {\n    left: 66.66666666666666%;\n  }\n  .col-sm-push-7 {\n    left: 58.333333333333336%;\n  }\n  .col-sm-push-6 {\n    left: 50%;\n  }\n  .col-sm-push-5 {\n    left: 41.66666666666667%;\n  }\n  .col-sm-push-4 {\n    left: 33.33333333333333%;\n  }\n  .col-sm-push-3 {\n    left: 25%;\n  }\n  .col-sm-push-2 {\n    left: 16.666666666666664%;\n  }\n  .col-sm-push-1 {\n    left: 8.333333333333332%;\n  }\n  .col-sm-push-0 {\n    left: 0;\n  }\n  .col-sm-offset-12 {\n    margin-left: 100%;\n  }\n  .col-sm-offset-11 {\n    margin-left: 91.66666666666666%;\n  }\n  .col-sm-offset-10 {\n    margin-left: 83.33333333333334%;\n  }\n  .col-sm-offset-9 {\n    margin-left: 75%;\n  }\n  .col-sm-offset-8 {\n    margin-left: 66.66666666666666%;\n  }\n  .col-sm-offset-7 {\n    margin-left: 58.333333333333336%;\n  }\n  .col-sm-offset-6 {\n    margin-left: 50%;\n  }\n  .col-sm-offset-5 {\n    margin-left: 41.66666666666667%;\n  }\n  .col-sm-offset-4 {\n    margin-left: 33.33333333333333%;\n  }\n  .col-sm-offset-3 {\n    margin-left: 25%;\n  }\n  .col-sm-offset-2 {\n    margin-left: 16.666666666666664%;\n  }\n  .col-sm-offset-1 {\n    margin-left: 8.333333333333332%;\n  }\n  .col-sm-offset-0 {\n    margin-left: 0;\n  }\n}\n\n@media (min-width: 992px) {\n  .col-md-1,\n  .col-md-2,\n  .col-md-3,\n  .col-md-4,\n  .col-md-5,\n  .col-md-6,\n  .col-md-7,\n  .col-md-8,\n  .col-md-9,\n  .col-md-10,\n  .col-md-11,\n  .col-md-12 {\n    float: left;\n  }\n  .col-md-12 {\n    width: 100%;\n  }\n  .col-md-11 {\n    width: 91.66666666666666%;\n  }\n  .col-md-10 {\n    width: 83.33333333333334%;\n  }\n  .col-md-9 {\n    width: 75%;\n  }\n  .col-md-8 {\n    width: 66.66666666666666%;\n  }\n  .col-md-7 {\n    width: 58.333333333333336%;\n  }\n  .col-md-6 {\n    width: 50%;\n  }\n  .col-md-5 {\n    width: 41.66666666666667%;\n  }\n  .col-md-4 {\n    width: 33.33333333333333%;\n  }\n  .col-md-3 {\n    width: 25%;\n  }\n  .col-md-2 {\n    width: 16.666666666666664%;\n  }\n  .col-md-1 {\n    width: 8.333333333333332%;\n  }\n  .col-md-pull-12 {\n    right: 100%;\n  }\n  .col-md-pull-11 {\n    right: 91.66666666666666%;\n  }\n  .col-md-pull-10 {\n    right: 83.33333333333334%;\n  }\n  .col-md-pull-9 {\n    right: 75%;\n  }\n  .col-md-pull-8 {\n    right: 66.66666666666666%;\n  }\n  .col-md-pull-7 {\n    right: 58.333333333333336%;\n  }\n  .col-md-pull-6 {\n    right: 50%;\n  }\n  .col-md-pull-5 {\n    right: 41.66666666666667%;\n  }\n  .col-md-pull-4 {\n    right: 33.33333333333333%;\n  }\n  .col-md-pull-3 {\n    right: 25%;\n  }\n  .col-md-pull-2 {\n    right: 16.666666666666664%;\n  }\n  .col-md-pull-1 {\n    right: 8.333333333333332%;\n  }\n  .col-md-pull-0 {\n    right: 0;\n  }\n  .col-md-push-12 {\n    left: 100%;\n  }\n  .col-md-push-11 {\n    left: 91.66666666666666%;\n  }\n  .col-md-push-10 {\n    left: 83.33333333333334%;\n  }\n  .col-md-push-9 {\n    left: 75%;\n  }\n  .col-md-push-8 {\n    left: 66.66666666666666%;\n  }\n  .col-md-push-7 {\n    left: 58.333333333333336%;\n  }\n  .col-md-push-6 {\n    left: 50%;\n  }\n  .col-md-push-5 {\n    left: 41.66666666666667%;\n  }\n  .col-md-push-4 {\n    left: 33.33333333333333%;\n  }\n  .col-md-push-3 {\n    left: 25%;\n  }\n  .col-md-push-2 {\n    left: 16.666666666666664%;\n  }\n  .col-md-push-1 {\n    left: 8.333333333333332%;\n  }\n  .col-md-push-0 {\n    left: 0;\n  }\n  .col-md-offset-12 {\n    margin-left: 100%;\n  }\n  .col-md-offset-11 {\n    margin-left: 91.66666666666666%;\n  }\n  .col-md-offset-10 {\n    margin-left: 83.33333333333334%;\n  }\n  .col-md-offset-9 {\n    margin-left: 75%;\n  }\n  .col-md-offset-8 {\n    margin-left: 66.66666666666666%;\n  }\n  .col-md-offset-7 {\n    margin-left: 58.333333333333336%;\n  }\n  .col-md-offset-6 {\n    margin-left: 50%;\n  }\n  .col-md-offset-5 {\n    margin-left: 41.66666666666667%;\n  }\n  .col-md-offset-4 {\n    margin-left: 33.33333333333333%;\n  }\n  .col-md-offset-3 {\n    margin-left: 25%;\n  }\n  .col-md-offset-2 {\n    margin-left: 16.666666666666664%;\n  }\n  .col-md-offset-1 {\n    margin-left: 8.333333333333332%;\n  }\n  .col-md-offset-0 {\n    margin-left: 0;\n  }\n}\n\n@media (min-width: 1200px) {\n  .col-lg-1,\n  .col-lg-2,\n  .col-lg-3,\n  .col-lg-4,\n  .col-lg-5,\n  .col-lg-6,\n  .col-lg-7,\n  .col-lg-8,\n  .col-lg-9,\n  .col-lg-10,\n  .col-lg-11,\n  .col-lg-12 {\n    float: left;\n  }\n  .col-lg-12 {\n    width: 100%;\n  }\n  .col-lg-11 {\n    width: 91.66666666666666%;\n  }\n  .col-lg-10 {\n    width: 83.33333333333334%;\n  }\n  .col-lg-9 {\n    width: 75%;\n  }\n  .col-lg-8 {\n    width: 66.66666666666666%;\n  }\n  .col-lg-7 {\n    width: 58.333333333333336%;\n  }\n  .col-lg-6 {\n    width: 50%;\n  }\n  .col-lg-5 {\n    width: 41.66666666666667%;\n  }\n  .col-lg-4 {\n    width: 33.33333333333333%;\n  }\n  .col-lg-3 {\n    width: 25%;\n  }\n  .col-lg-2 {\n    width: 16.666666666666664%;\n  }\n  .col-lg-1 {\n    width: 8.333333333333332%;\n  }\n  .col-lg-pull-12 {\n    right: 100%;\n  }\n  .col-lg-pull-11 {\n    right: 91.66666666666666%;\n  }\n  .col-lg-pull-10 {\n    right: 83.33333333333334%;\n  }\n  .col-lg-pull-9 {\n    right: 75%;\n  }\n  .col-lg-pull-8 {\n    right: 66.66666666666666%;\n  }\n  .col-lg-pull-7 {\n    right: 58.333333333333336%;\n  }\n  .col-lg-pull-6 {\n    right: 50%;\n  }\n  .col-lg-pull-5 {\n    right: 41.66666666666667%;\n  }\n  .col-lg-pull-4 {\n    right: 33.33333333333333%;\n  }\n  .col-lg-pull-3 {\n    right: 25%;\n  }\n  .col-lg-pull-2 {\n    right: 16.666666666666664%;\n  }\n  .col-lg-pull-1 {\n    right: 8.333333333333332%;\n  }\n  .col-lg-pull-0 {\n    right: 0;\n  }\n  .col-lg-push-12 {\n    left: 100%;\n  }\n  .col-lg-push-11 {\n    left: 91.66666666666666%;\n  }\n  .col-lg-push-10 {\n    left: 83.33333333333334%;\n  }\n  .col-lg-push-9 {\n    left: 75%;\n  }\n  .col-lg-push-8 {\n    left: 66.66666666666666%;\n  }\n  .col-lg-push-7 {\n    left: 58.333333333333336%;\n  }\n  .col-lg-push-6 {\n    left: 50%;\n  }\n  .col-lg-push-5 {\n    left: 41.66666666666667%;\n  }\n  .col-lg-push-4 {\n    left: 33.33333333333333%;\n  }\n  .col-lg-push-3 {\n    left: 25%;\n  }\n  .col-lg-push-2 {\n    left: 16.666666666666664%;\n  }\n  .col-lg-push-1 {\n    left: 8.333333333333332%;\n  }\n  .col-lg-push-0 {\n    left: 0;\n  }\n  .col-lg-offset-12 {\n    margin-left: 100%;\n  }\n  .col-lg-offset-11 {\n    margin-left: 91.66666666666666%;\n  }\n  .col-lg-offset-10 {\n    margin-left: 83.33333333333334%;\n  }\n  .col-lg-offset-9 {\n    margin-left: 75%;\n  }\n  .col-lg-offset-8 {\n    margin-left: 66.66666666666666%;\n  }\n  .col-lg-offset-7 {\n    margin-left: 58.333333333333336%;\n  }\n  .col-lg-offset-6 {\n    margin-left: 50%;\n  }\n  .col-lg-offset-5 {\n    margin-left: 41.66666666666667%;\n  }\n  .col-lg-offset-4 {\n    margin-left: 33.33333333333333%;\n  }\n  .col-lg-offset-3 {\n    margin-left: 25%;\n  }\n  .col-lg-offset-2 {\n    margin-left: 16.666666666666664%;\n  }\n  .col-lg-offset-1 {\n    margin-left: 8.333333333333332%;\n  }\n  .col-lg-offset-0 {\n    margin-left: 0;\n  }\n}\n\ntable {\n  max-width: 100%;\n  background-color: transparent;\n}\n\nth {\n  text-align: left;\n}\n\n.table {\n  width: 100%;\n  margin-bottom: 20px;\n}\n\n.table > thead > tr > th,\n.table > tbody > tr > th,\n.table > tfoot > tr > th,\n.table > thead > tr > td,\n.table > tbody > tr > td,\n.table > tfoot > tr > td {\n  padding: 8px;\n  line-height: 1.428571429;\n  vertical-align: top;\n  border-top: 1px solid #dddddd;\n}\n\n.table > thead > tr > th {\n  vertical-align: bottom;\n  border-bottom: 2px solid #dddddd;\n}\n\n.table > caption + thead > tr:first-child > th,\n.table > colgroup + thead > tr:first-child > th,\n.table > thead:first-child > tr:first-child > th,\n.table > caption + thead > tr:first-child > td,\n.table > colgroup + thead > tr:first-child > td,\n.table > thead:first-child > tr:first-child > td {\n  border-top: 0;\n}\n\n.table > tbody + tbody {\n  border-top: 2px solid #dddddd;\n}\n\n.table .table {\n  background-color: #ffffff;\n}\n\n.table-condensed > thead > tr > th,\n.table-condensed > tbody > tr > th,\n.table-condensed > tfoot > tr > th,\n.table-condensed > thead > tr > td,\n.table-condensed > tbody > tr > td,\n.table-condensed > tfoot > tr > td {\n  padding: 5px;\n}\n\n.table-bordered {\n  border: 1px solid #dddddd;\n}\n\n.table-bordered > thead > tr > th,\n.table-bordered > tbody > tr > th,\n.table-bordered > tfoot > tr > th,\n.table-bordered > thead > tr > td,\n.table-bordered > tbody > tr > td,\n.table-bordered > tfoot > tr > td {\n  border: 1px solid #dddddd;\n}\n\n.table-bordered > thead > tr > th,\n.table-bordered > thead > tr > td {\n  border-bottom-width: 2px;\n}\n\n.table-striped > tbody > tr:nth-child(odd) > td,\n.table-striped > tbody > tr:nth-child(odd) > th {\n  background-color: #f9f9f9;\n}\n\n.table-hover > tbody > tr:hover > td,\n.table-hover > tbody > tr:hover > th {\n  background-color: #f5f5f5;\n}\n\ntable col[class*=\"col-\"] {\n  position: static;\n  display: table-column;\n  float: none;\n}\n\ntable td[class*=\"col-\"],\ntable th[class*=\"col-\"] {\n  display: table-cell;\n  float: none;\n}\n\n.table > thead > tr > .active,\n.table > tbody > tr > .active,\n.table > tfoot > tr > .active,\n.table > thead > .active > td,\n.table > tbody > .active > td,\n.table > tfoot > .active > td,\n.table > thead > .active > th,\n.table > tbody > .active > th,\n.table > tfoot > .active > th {\n  background-color: #f5f5f5;\n}\n\n.table-hover > tbody > tr > .active:hover,\n.table-hover > tbody > .active:hover > td,\n.table-hover > tbody > .active:hover > th {\n  background-color: #e8e8e8;\n}\n\n.table > thead > tr > .success,\n.table > tbody > tr > .success,\n.table > tfoot > tr > .success,\n.table > thead > .success > td,\n.table > tbody > .success > td,\n.table > tfoot > .success > td,\n.table > thead > .success > th,\n.table > tbody > .success > th,\n.table > tfoot > .success > th {\n  background-color: #dff0d8;\n}\n\n.table-hover > tbody > tr > .success:hover,\n.table-hover > tbody > .success:hover > td,\n.table-hover > tbody > .success:hover > th {\n  background-color: #d0e9c6;\n}\n\n.table > thead > tr > .danger,\n.table > tbody > tr > .danger,\n.table > tfoot > tr > .danger,\n.table > thead > .danger > td,\n.table > tbody > .danger > td,\n.table > tfoot > .danger > td,\n.table > thead > .danger > th,\n.table > tbody > .danger > th,\n.table > tfoot > .danger > th {\n  background-color: #f2dede;\n}\n\n.table-hover > tbody > tr > .danger:hover,\n.table-hover > tbody > .danger:hover > td,\n.table-hover > tbody > .danger:hover > th {\n  background-color: #ebcccc;\n}\n\n.table > thead > tr > .warning,\n.table > tbody > tr > .warning,\n.table > tfoot > tr > .warning,\n.table > thead > .warning > td,\n.table > tbody > .warning > td,\n.table > tfoot > .warning > td,\n.table > thead > .warning > th,\n.table > tbody > .warning > th,\n.table > tfoot > .warning > th {\n  background-color: #fcf8e3;\n}\n\n.table-hover > tbody > tr > .warning:hover,\n.table-hover > tbody > .warning:hover > td,\n.table-hover > tbody > .warning:hover > th {\n  background-color: #faf2cc;\n}\n\n@media (max-width: 767px) {\n  .table-responsive {\n    width: 100%;\n    margin-bottom: 15px;\n    overflow-x: scroll;\n    overflow-y: hidden;\n    border: 1px solid #dddddd;\n    -ms-overflow-style: -ms-autohiding-scrollbar;\n    -webkit-overflow-scrolling: touch;\n  }\n  .table-responsive > .table {\n    margin-bottom: 0;\n  }\n  .table-responsive > .table > thead > tr > th,\n  .table-responsive > .table > tbody > tr > th,\n  .table-responsive > .table > tfoot > tr > th,\n  .table-responsive > .table > thead > tr > td,\n  .table-responsive > .table > tbody > tr > td,\n  .table-responsive > .table > tfoot > tr > td {\n    white-space: nowrap;\n  }\n  .table-responsive > .table-bordered {\n    border: 0;\n  }\n  .table-responsive > .table-bordered > thead > tr > th:first-child,\n  .table-responsive > .table-bordered > tbody > tr > th:first-child,\n  .table-responsive > .table-bordered > tfoot > tr > th:first-child,\n  .table-responsive > .table-bordered > thead > tr > td:first-child,\n  .table-responsive > .table-bordered > tbody > tr > td:first-child,\n  .table-responsive > .table-bordered > tfoot > tr > td:first-child {\n    border-left: 0;\n  }\n  .table-responsive > .table-bordered > thead > tr > th:last-child,\n  .table-responsive > .table-bordered > tbody > tr > th:last-child,\n  .table-responsive > .table-bordered > tfoot > tr > th:last-child,\n  .table-responsive > .table-bordered > thead > tr > td:last-child,\n  .table-responsive > .table-bordered > tbody > tr > td:last-child,\n  .table-responsive > .table-bordered > tfoot > tr > td:last-child {\n    border-right: 0;\n  }\n  .table-responsive > .table-bordered > tbody > tr:last-child > th,\n  .table-responsive > .table-bordered > tfoot > tr:last-child > th,\n  .table-responsive > .table-bordered > tbody > tr:last-child > td,\n  .table-responsive > .table-bordered > tfoot > tr:last-child > td {\n    border-bottom: 0;\n  }\n}\n\nfieldset {\n  padding: 0;\n  margin: 0;\n  border: 0;\n}\n\nlegend {\n  display: block;\n  width: 100%;\n  padding: 0;\n  margin-bottom: 20px;\n  font-size: 21px;\n  line-height: inherit;\n  color: #333333;\n  border: 0;\n  border-bottom: 1px solid #e5e5e5;\n}\n\nlabel {\n  display: inline-block;\n  margin-bottom: 5px;\n  font-weight: bold;\n}\n\ninput[type=\"search\"] {\n  -webkit-box-sizing: border-box;\n     -moz-box-sizing: border-box;\n          box-sizing: border-box;\n}\n\ninput[type=\"radio\"],\ninput[type=\"checkbox\"] {\n  margin: 4px 0 0;\n  margin-top: 1px \\9;\n  /* IE8-9 */\n\n  line-height: normal;\n}\n\ninput[type=\"file\"] {\n  display: block;\n}\n\nselect[multiple],\nselect[size] {\n  height: auto;\n}\n\nselect optgroup {\n  font-family: inherit;\n  font-size: inherit;\n  font-style: inherit;\n}\n\ninput[type=\"file\"]:focus,\ninput[type=\"radio\"]:focus,\ninput[type=\"checkbox\"]:focus {\n  outline: thin dotted;\n  outline: 5px auto -webkit-focus-ring-color;\n  outline-offset: -2px;\n}\n\ninput[type=\"number\"]::-webkit-outer-spin-button,\ninput[type=\"number\"]::-webkit-inner-spin-button {\n  height: auto;\n}\n\noutput {\n  display: block;\n  padding-top: 7px;\n  font-size: 14px;\n  line-height: 1.428571429;\n  color: #555555;\n  vertical-align: middle;\n}\n\n.form-control {\n  display: block;\n  width: 100%;\n  height: 34px;\n  padding: 6px 12px;\n  font-size: 14px;\n  line-height: 1.428571429;\n  color: #555555;\n  vertical-align: middle;\n  background-color: #ffffff;\n  background-image: none;\n  border: 1px solid #cccccc;\n  border-radius: 4px;\n  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n  -webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;\n          transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;\n}\n\n.form-control:focus {\n  border-color: #66afe9;\n  outline: 0;\n  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6);\n          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6);\n}\n\n.form-control:-moz-placeholder {\n  color: #999999;\n}\n\n.form-control::-moz-placeholder {\n  color: #999999;\n  opacity: 1;\n}\n\n.form-control:-ms-input-placeholder {\n  color: #999999;\n}\n\n.form-control::-webkit-input-placeholder {\n  color: #999999;\n}\n\n.form-control[disabled],\n.form-control[readonly],\nfieldset[disabled] .form-control {\n  cursor: not-allowed;\n  background-color: #eeeeee;\n}\n\ntextarea.form-control {\n  height: auto;\n}\n\n.form-group {\n  margin-bottom: 15px;\n}\n\n.radio,\n.checkbox {\n  display: block;\n  min-height: 20px;\n  padding-left: 20px;\n  margin-top: 10px;\n  margin-bottom: 10px;\n  vertical-align: middle;\n}\n\n.radio label,\n.checkbox label {\n  display: inline;\n  margin-bottom: 0;\n  font-weight: normal;\n  cursor: pointer;\n}\n\n.radio input[type=\"radio\"],\n.radio-inline input[type=\"radio\"],\n.checkbox input[type=\"checkbox\"],\n.checkbox-inline input[type=\"checkbox\"] {\n  float: left;\n  margin-left: -20px;\n}\n\n.radio + .radio,\n.checkbox + .checkbox {\n  margin-top: -5px;\n}\n\n.radio-inline,\n.checkbox-inline {\n  display: inline-block;\n  padding-left: 20px;\n  margin-bottom: 0;\n  font-weight: normal;\n  vertical-align: middle;\n  cursor: pointer;\n}\n\n.radio-inline + .radio-inline,\n.checkbox-inline + .checkbox-inline {\n  margin-top: 0;\n  margin-left: 10px;\n}\n\ninput[type=\"radio\"][disabled],\ninput[type=\"checkbox\"][disabled],\n.radio[disabled],\n.radio-inline[disabled],\n.checkbox[disabled],\n.checkbox-inline[disabled],\nfieldset[disabled] input[type=\"radio\"],\nfieldset[disabled] input[type=\"checkbox\"],\nfieldset[disabled] .radio,\nfieldset[disabled] .radio-inline,\nfieldset[disabled] .checkbox,\nfieldset[disabled] .checkbox-inline {\n  cursor: not-allowed;\n}\n\n.input-sm {\n  height: 30px;\n  padding: 5px 10px;\n  font-size: 12px;\n  line-height: 1.5;\n  border-radius: 3px;\n}\n\nselect.input-sm {\n  height: 30px;\n  line-height: 30px;\n}\n\ntextarea.input-sm {\n  height: auto;\n}\n\n.input-lg {\n  height: 46px;\n  padding: 10px 16px;\n  font-size: 18px;\n  line-height: 1.33;\n  border-radius: 6px;\n}\n\nselect.input-lg {\n  height: 46px;\n  line-height: 46px;\n}\n\ntextarea.input-lg {\n  height: auto;\n}\n\n.has-warning .help-block,\n.has-warning .control-label,\n.has-warning .radio,\n.has-warning .checkbox,\n.has-warning .radio-inline,\n.has-warning .checkbox-inline {\n  color: #8a6d3b;\n}\n\n.has-warning .form-control {\n  border-color: #8a6d3b;\n  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n}\n\n.has-warning .form-control:focus {\n  border-color: #66512c;\n  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #c0a16b;\n          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #c0a16b;\n}\n\n.has-warning .input-group-addon {\n  color: #8a6d3b;\n  background-color: #fcf8e3;\n  border-color: #8a6d3b;\n}\n\n.has-error .help-block,\n.has-error .control-label,\n.has-error .radio,\n.has-error .checkbox,\n.has-error .radio-inline,\n.has-error .checkbox-inline {\n  color: #a94442;\n}\n\n.has-error .form-control {\n  border-color: #a94442;\n  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n}\n\n.has-error .form-control:focus {\n  border-color: #843534;\n  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #ce8483;\n          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #ce8483;\n}\n\n.has-error .input-group-addon {\n  color: #a94442;\n  background-color: #f2dede;\n  border-color: #a94442;\n}\n\n.has-success .help-block,\n.has-success .control-label,\n.has-success .radio,\n.has-success .checkbox,\n.has-success .radio-inline,\n.has-success .checkbox-inline {\n  color: #3c763d;\n}\n\n.has-success .form-control {\n  border-color: #3c763d;\n  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n}\n\n.has-success .form-control:focus {\n  border-color: #2b542c;\n  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #67b168;\n          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #67b168;\n}\n\n.has-success .input-group-addon {\n  color: #3c763d;\n  background-color: #dff0d8;\n  border-color: #3c763d;\n}\n\n.form-control-static {\n  margin-bottom: 0;\n}\n\n.help-block {\n  display: block;\n  margin-top: 5px;\n  margin-bottom: 10px;\n  color: #737373;\n}\n\n@media (min-width: 768px) {\n  .form-inline .form-group {\n    display: inline-block;\n    margin-bottom: 0;\n    vertical-align: middle;\n  }\n  .form-inline .form-control {\n    display: inline-block;\n  }\n  .form-inline select.form-control {\n    width: auto;\n  }\n  .form-inline .radio,\n  .form-inline .checkbox {\n    display: inline-block;\n    padding-left: 0;\n    margin-top: 0;\n    margin-bottom: 0;\n  }\n  .form-inline .radio input[type=\"radio\"],\n  .form-inline .checkbox input[type=\"checkbox\"] {\n    float: none;\n    margin-left: 0;\n  }\n}\n\n.form-horizontal .control-label,\n.form-horizontal .radio,\n.form-horizontal .checkbox,\n.form-horizontal .radio-inline,\n.form-horizontal .checkbox-inline {\n  padding-top: 7px;\n  margin-top: 0;\n  margin-bottom: 0;\n}\n\n.form-horizontal .radio,\n.form-horizontal .checkbox {\n  min-height: 27px;\n}\n\n.form-horizontal .form-group {\n  margin-right: -15px;\n  margin-left: -15px;\n}\n\n.form-horizontal .form-group:before,\n.form-horizontal .form-group:after {\n  display: table;\n  content: \" \";\n}\n\n.form-horizontal .form-group:after {\n  clear: both;\n}\n\n.form-horizontal .form-group:before,\n.form-horizontal .form-group:after {\n  display: table;\n  content: \" \";\n}\n\n.form-horizontal .form-group:after {\n  clear: both;\n}\n\n.form-horizontal .form-control-static {\n  padding-top: 7px;\n}\n\n@media (min-width: 768px) {\n  .form-horizontal .control-label {\n    text-align: right;\n  }\n}\n\n.btn {\n  display: inline-block;\n  padding: 6px 12px;\n  margin-bottom: 0;\n  font-size: 14px;\n  font-weight: normal;\n  line-height: 1.428571429;\n  text-align: center;\n  white-space: nowrap;\n  vertical-align: middle;\n  cursor: pointer;\n  background-image: none;\n  border: 1px solid transparent;\n  border-radius: 4px;\n  -webkit-user-select: none;\n     -moz-user-select: none;\n      -ms-user-select: none;\n       -o-user-select: none;\n          user-select: none;\n}\n\n.btn:focus {\n  outline: thin dotted;\n  outline: 5px auto -webkit-focus-ring-color;\n  outline-offset: -2px;\n}\n\n.btn:hover,\n.btn:focus {\n  color: #333333;\n  text-decoration: none;\n}\n\n.btn:active,\n.btn.active {\n  background-image: none;\n  outline: 0;\n  -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);\n          box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);\n}\n\n.btn.disabled,\n.btn[disabled],\nfieldset[disabled] .btn {\n  pointer-events: none;\n  cursor: not-allowed;\n  opacity: 0.65;\n  filter: alpha(opacity=65);\n  -webkit-box-shadow: none;\n          box-shadow: none;\n}\n\n.btn-default {\n  color: #333333;\n  background-color: #ffffff;\n  border-color: #cccccc;\n}\n\n.btn-default:hover,\n.btn-default:focus,\n.btn-default:active,\n.btn-default.active,\n.open .dropdown-toggle.btn-default {\n  color: #333333;\n  background-color: #ebebeb;\n  border-color: #adadad;\n}\n\n.btn-default:active,\n.btn-default.active,\n.open .dropdown-toggle.btn-default {\n  background-image: none;\n}\n\n.btn-default.disabled,\n.btn-default[disabled],\nfieldset[disabled] .btn-default,\n.btn-default.disabled:hover,\n.btn-default[disabled]:hover,\nfieldset[disabled] .btn-default:hover,\n.btn-default.disabled:focus,\n.btn-default[disabled]:focus,\nfieldset[disabled] .btn-default:focus,\n.btn-default.disabled:active,\n.btn-default[disabled]:active,\nfieldset[disabled] .btn-default:active,\n.btn-default.disabled.active,\n.btn-default[disabled].active,\nfieldset[disabled] .btn-default.active {\n  background-color: #ffffff;\n  border-color: #cccccc;\n}\n\n.btn-default .badge {\n  color: #ffffff;\n  background-color: #fff;\n}\n\n.btn-primary {\n  color: #ffffff;\n  background-color: #428bca;\n  border-color: #357ebd;\n}\n\n.btn-primary:hover,\n.btn-primary:focus,\n.btn-primary:active,\n.btn-primary.active,\n.open .dropdown-toggle.btn-primary {\n  color: #ffffff;\n  background-color: #3276b1;\n  border-color: #285e8e;\n}\n\n.btn-primary:active,\n.btn-primary.active,\n.open .dropdown-toggle.btn-primary {\n  background-image: none;\n}\n\n.btn-primary.disabled,\n.btn-primary[disabled],\nfieldset[disabled] .btn-primary,\n.btn-primary.disabled:hover,\n.btn-primary[disabled]:hover,\nfieldset[disabled] .btn-primary:hover,\n.btn-primary.disabled:focus,\n.btn-primary[disabled]:focus,\nfieldset[disabled] .btn-primary:focus,\n.btn-primary.disabled:active,\n.btn-primary[disabled]:active,\nfieldset[disabled] .btn-primary:active,\n.btn-primary.disabled.active,\n.btn-primary[disabled].active,\nfieldset[disabled] .btn-primary.active {\n  background-color: #428bca;\n  border-color: #357ebd;\n}\n\n.btn-primary .badge {\n  color: #428bca;\n  background-color: #fff;\n}\n\n.btn-warning {\n  color: #ffffff;\n  background-color: #f0ad4e;\n  border-color: #eea236;\n}\n\n.btn-warning:hover,\n.btn-warning:focus,\n.btn-warning:active,\n.btn-warning.active,\n.open .dropdown-toggle.btn-warning {\n  color: #ffffff;\n  background-color: #ed9c28;\n  border-color: #d58512;\n}\n\n.btn-warning:active,\n.btn-warning.active,\n.open .dropdown-toggle.btn-warning {\n  background-image: none;\n}\n\n.btn-warning.disabled,\n.btn-warning[disabled],\nfieldset[disabled] .btn-warning,\n.btn-warning.disabled:hover,\n.btn-warning[disabled]:hover,\nfieldset[disabled] .btn-warning:hover,\n.btn-warning.disabled:focus,\n.btn-warning[disabled]:focus,\nfieldset[disabled] .btn-warning:focus,\n.btn-warning.disabled:active,\n.btn-warning[disabled]:active,\nfieldset[disabled] .btn-warning:active,\n.btn-warning.disabled.active,\n.btn-warning[disabled].active,\nfieldset[disabled] .btn-warning.active {\n  background-color: #f0ad4e;\n  border-color: #eea236;\n}\n\n.btn-warning .badge {\n  color: #f0ad4e;\n  background-color: #fff;\n}\n\n.btn-danger {\n  color: #ffffff;\n  background-color: #d9534f;\n  border-color: #d43f3a;\n}\n\n.btn-danger:hover,\n.btn-danger:focus,\n.btn-danger:active,\n.btn-danger.active,\n.open .dropdown-toggle.btn-danger {\n  color: #ffffff;\n  background-color: #d2322d;\n  border-color: #ac2925;\n}\n\n.btn-danger:active,\n.btn-danger.active,\n.open .dropdown-toggle.btn-danger {\n  background-image: none;\n}\n\n.btn-danger.disabled,\n.btn-danger[disabled],\nfieldset[disabled] .btn-danger,\n.btn-danger.disabled:hover,\n.btn-danger[disabled]:hover,\nfieldset[disabled] .btn-danger:hover,\n.btn-danger.disabled:focus,\n.btn-danger[disabled]:focus,\nfieldset[disabled] .btn-danger:focus,\n.btn-danger.disabled:active,\n.btn-danger[disabled]:active,\nfieldset[disabled] .btn-danger:active,\n.btn-danger.disabled.active,\n.btn-danger[disabled].active,\nfieldset[disabled] .btn-danger.active {\n  background-color: #d9534f;\n  border-color: #d43f3a;\n}\n\n.btn-danger .badge {\n  color: #d9534f;\n  background-color: #fff;\n}\n\n.btn-success {\n  color: #ffffff;\n  background-color: #5cb85c;\n  border-color: #4cae4c;\n}\n\n.btn-success:hover,\n.btn-success:focus,\n.btn-success:active,\n.btn-success.active,\n.open .dropdown-toggle.btn-success {\n  color: #ffffff;\n  background-color: #47a447;\n  border-color: #398439;\n}\n\n.btn-success:active,\n.btn-success.active,\n.open .dropdown-toggle.btn-success {\n  background-image: none;\n}\n\n.btn-success.disabled,\n.btn-success[disabled],\nfieldset[disabled] .btn-success,\n.btn-success.disabled:hover,\n.btn-success[disabled]:hover,\nfieldset[disabled] .btn-success:hover,\n.btn-success.disabled:focus,\n.btn-success[disabled]:focus,\nfieldset[disabled] .btn-success:focus,\n.btn-success.disabled:active,\n.btn-success[disabled]:active,\nfieldset[disabled] .btn-success:active,\n.btn-success.disabled.active,\n.btn-success[disabled].active,\nfieldset[disabled] .btn-success.active {\n  background-color: #5cb85c;\n  border-color: #4cae4c;\n}\n\n.btn-success .badge {\n  color: #5cb85c;\n  background-color: #fff;\n}\n\n.btn-info {\n  color: #ffffff;\n  background-color: #5bc0de;\n  border-color: #46b8da;\n}\n\n.btn-info:hover,\n.btn-info:focus,\n.btn-info:active,\n.btn-info.active,\n.open .dropdown-toggle.btn-info {\n  color: #ffffff;\n  background-color: #39b3d7;\n  border-color: #269abc;\n}\n\n.btn-info:active,\n.btn-info.active,\n.open .dropdown-toggle.btn-info {\n  background-image: none;\n}\n\n.btn-info.disabled,\n.btn-info[disabled],\nfieldset[disabled] .btn-info,\n.btn-info.disabled:hover,\n.btn-info[disabled]:hover,\nfieldset[disabled] .btn-info:hover,\n.btn-info.disabled:focus,\n.btn-info[disabled]:focus,\nfieldset[disabled] .btn-info:focus,\n.btn-info.disabled:active,\n.btn-info[disabled]:active,\nfieldset[disabled] .btn-info:active,\n.btn-info.disabled.active,\n.btn-info[disabled].active,\nfieldset[disabled] .btn-info.active {\n  background-color: #5bc0de;\n  border-color: #46b8da;\n}\n\n.btn-info .badge {\n  color: #5bc0de;\n  background-color: #fff;\n}\n\n.btn-link {\n  font-weight: normal;\n  color: #428bca;\n  cursor: pointer;\n  border-radius: 0;\n}\n\n.btn-link,\n.btn-link:active,\n.btn-link[disabled],\nfieldset[disabled] .btn-link {\n  background-color: transparent;\n  -webkit-box-shadow: none;\n          box-shadow: none;\n}\n\n.btn-link,\n.btn-link:hover,\n.btn-link:focus,\n.btn-link:active {\n  border-color: transparent;\n}\n\n.btn-link:hover,\n.btn-link:focus {\n  color: #2a6496;\n  text-decoration: underline;\n  background-color: transparent;\n}\n\n.btn-link[disabled]:hover,\nfieldset[disabled] .btn-link:hover,\n.btn-link[disabled]:focus,\nfieldset[disabled] .btn-link:focus {\n  color: #999999;\n  text-decoration: none;\n}\n\n.btn-lg {\n  padding: 10px 16px;\n  font-size: 18px;\n  line-height: 1.33;\n  border-radius: 6px;\n}\n\n.btn-sm {\n  padding: 5px 10px;\n  font-size: 12px;\n  line-height: 1.5;\n  border-radius: 3px;\n}\n\n.btn-xs {\n  padding: 1px 5px;\n  font-size: 12px;\n  line-height: 1.5;\n  border-radius: 3px;\n}\n\n.btn-block {\n  display: block;\n  width: 100%;\n  padding-right: 0;\n  padding-left: 0;\n}\n\n.btn-block + .btn-block {\n  margin-top: 5px;\n}\n\ninput[type=\"submit\"].btn-block,\ninput[type=\"reset\"].btn-block,\ninput[type=\"button\"].btn-block {\n  width: 100%;\n}\n\n.fade {\n  opacity: 0;\n  -webkit-transition: opacity 0.15s linear;\n          transition: opacity 0.15s linear;\n}\n\n.fade.in {\n  opacity: 1;\n}\n\n.collapse {\n  display: none;\n}\n\n.collapse.in {\n  display: block;\n}\n\n.collapsing {\n  position: relative;\n  height: 0;\n  overflow: hidden;\n  -webkit-transition: height 0.35s ease;\n          transition: height 0.35s ease;\n}\n\n@font-face {\n  font-family: 'Glyphicons Halflings';\n  src: url('../fonts/glyphicons-halflings-regular.eot');\n  src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');\n}\n\n.glyphicon {\n  position: relative;\n  top: 1px;\n  display: inline-block;\n  font-family: 'Glyphicons Halflings';\n  -webkit-font-smoothing: antialiased;\n  font-style: normal;\n  font-weight: normal;\n  line-height: 1;\n  -moz-osx-font-smoothing: grayscale;\n}\n\n.glyphicon:empty {\n  width: 1em;\n}\n\n.glyphicon-asterisk:before {\n  content: \"\\2a\";\n}\n\n.glyphicon-plus:before {\n  content: \"\\2b\";\n}\n\n.glyphicon-euro:before {\n  content: \"\\20ac\";\n}\n\n.glyphicon-minus:before {\n  content: \"\\2212\";\n}\n\n.glyphicon-cloud:before {\n  content: \"\\2601\";\n}\n\n.glyphicon-envelope:before {\n  content: \"\\2709\";\n}\n\n.glyphicon-pencil:before {\n  content: \"\\270f\";\n}\n\n.glyphicon-glass:before {\n  content: \"\\e001\";\n}\n\n.glyphicon-music:before {\n  content: \"\\e002\";\n}\n\n.glyphicon-search:before {\n  content: \"\\e003\";\n}\n\n.glyphicon-heart:before {\n  content: \"\\e005\";\n}\n\n.glyphicon-star:before {\n  content: \"\\e006\";\n}\n\n.glyphicon-star-empty:before {\n  content: \"\\e007\";\n}\n\n.glyphicon-user:before {\n  content: \"\\e008\";\n}\n\n.glyphicon-film:before {\n  content: \"\\e009\";\n}\n\n.glyphicon-th-large:before {\n  content: \"\\e010\";\n}\n\n.glyphicon-th:before {\n  content: \"\\e011\";\n}\n\n.glyphicon-th-list:before {\n  content: \"\\e012\";\n}\n\n.glyphicon-ok:before {\n  content: \"\\e013\";\n}\n\n.glyphicon-remove:before {\n  content: \"\\e014\";\n}\n\n.glyphicon-zoom-in:before {\n  content: \"\\e015\";\n}\n\n.glyphicon-zoom-out:before {\n  content: \"\\e016\";\n}\n\n.glyphicon-off:before {\n  content: \"\\e017\";\n}\n\n.glyphicon-signal:before {\n  content: \"\\e018\";\n}\n\n.glyphicon-cog:before {\n  content: \"\\e019\";\n}\n\n.glyphicon-trash:before {\n  content: \"\\e020\";\n}\n\n.glyphicon-home:before {\n  content: \"\\e021\";\n}\n\n.glyphicon-file:before {\n  content: \"\\e022\";\n}\n\n.glyphicon-time:before {\n  content: \"\\e023\";\n}\n\n.glyphicon-road:before {\n  content: \"\\e024\";\n}\n\n.glyphicon-download-alt:before {\n  content: \"\\e025\";\n}\n\n.glyphicon-download:before {\n  content: \"\\e026\";\n}\n\n.glyphicon-upload:before {\n  content: \"\\e027\";\n}\n\n.glyphicon-inbox:before {\n  content: \"\\e028\";\n}\n\n.glyphicon-play-circle:before {\n  content: \"\\e029\";\n}\n\n.glyphicon-repeat:before {\n  content: \"\\e030\";\n}\n\n.glyphicon-refresh:before {\n  content: \"\\e031\";\n}\n\n.glyphicon-list-alt:before {\n  content: \"\\e032\";\n}\n\n.glyphicon-lock:before {\n  content: \"\\e033\";\n}\n\n.glyphicon-flag:before {\n  content: \"\\e034\";\n}\n\n.glyphicon-headphones:before {\n  content: \"\\e035\";\n}\n\n.glyphicon-volume-off:before {\n  content: \"\\e036\";\n}\n\n.glyphicon-volume-down:before {\n  content: \"\\e037\";\n}\n\n.glyphicon-volume-up:before {\n  content: \"\\e038\";\n}\n\n.glyphicon-qrcode:before {\n  content: \"\\e039\";\n}\n\n.glyphicon-barcode:before {\n  content: \"\\e040\";\n}\n\n.glyphicon-tag:before {\n  content: \"\\e041\";\n}\n\n.glyphicon-tags:before {\n  content: \"\\e042\";\n}\n\n.glyphicon-book:before {\n  content: \"\\e043\";\n}\n\n.glyphicon-bookmark:before {\n  content: \"\\e044\";\n}\n\n.glyphicon-print:before {\n  content: \"\\e045\";\n}\n\n.glyphicon-camera:before {\n  content: \"\\e046\";\n}\n\n.glyphicon-font:before {\n  content: \"\\e047\";\n}\n\n.glyphicon-bold:before {\n  content: \"\\e048\";\n}\n\n.glyphicon-italic:before {\n  content: \"\\e049\";\n}\n\n.glyphicon-text-height:before {\n  content: \"\\e050\";\n}\n\n.glyphicon-text-width:before {\n  content: \"\\e051\";\n}\n\n.glyphicon-align-left:before {\n  content: \"\\e052\";\n}\n\n.glyphicon-align-center:before {\n  content: \"\\e053\";\n}\n\n.glyphicon-align-right:before {\n  content: \"\\e054\";\n}\n\n.glyphicon-align-justify:before {\n  content: \"\\e055\";\n}\n\n.glyphicon-list:before {\n  content: \"\\e056\";\n}\n\n.glyphicon-indent-left:before {\n  content: \"\\e057\";\n}\n\n.glyphicon-indent-right:before {\n  content: \"\\e058\";\n}\n\n.glyphicon-facetime-video:before {\n  content: \"\\e059\";\n}\n\n.glyphicon-picture:before {\n  content: \"\\e060\";\n}\n\n.glyphicon-map-marker:before {\n  content: \"\\e062\";\n}\n\n.glyphicon-adjust:before {\n  content: \"\\e063\";\n}\n\n.glyphicon-tint:before {\n  content: \"\\e064\";\n}\n\n.glyphicon-edit:before {\n  content: \"\\e065\";\n}\n\n.glyphicon-share:before {\n  content: \"\\e066\";\n}\n\n.glyphicon-check:before {\n  content: \"\\e067\";\n}\n\n.glyphicon-move:before {\n  content: \"\\e068\";\n}\n\n.glyphicon-step-backward:before {\n  content: \"\\e069\";\n}\n\n.glyphicon-fast-backward:before {\n  content: \"\\e070\";\n}\n\n.glyphicon-backward:before {\n  content: \"\\e071\";\n}\n\n.glyphicon-play:before {\n  content: \"\\e072\";\n}\n\n.glyphicon-pause:before {\n  content: \"\\e073\";\n}\n\n.glyphicon-stop:before {\n  content: \"\\e074\";\n}\n\n.glyphicon-forward:before {\n  content: \"\\e075\";\n}\n\n.glyphicon-fast-forward:before {\n  content: \"\\e076\";\n}\n\n.glyphicon-step-forward:before {\n  content: \"\\e077\";\n}\n\n.glyphicon-eject:before {\n  content: \"\\e078\";\n}\n\n.glyphicon-chevron-left:before {\n  content: \"\\e079\";\n}\n\n.glyphicon-chevron-right:before {\n  content: \"\\e080\";\n}\n\n.glyphicon-plus-sign:before {\n  content: \"\\e081\";\n}\n\n.glyphicon-minus-sign:before {\n  content: \"\\e082\";\n}\n\n.glyphicon-remove-sign:before {\n  content: \"\\e083\";\n}\n\n.glyphicon-ok-sign:before {\n  content: \"\\e084\";\n}\n\n.glyphicon-question-sign:before {\n  content: \"\\e085\";\n}\n\n.glyphicon-info-sign:before {\n  content: \"\\e086\";\n}\n\n.glyphicon-screenshot:before {\n  content: \"\\e087\";\n}\n\n.glyphicon-remove-circle:before {\n  content: \"\\e088\";\n}\n\n.glyphicon-ok-circle:before {\n  content: \"\\e089\";\n}\n\n.glyphicon-ban-circle:before {\n  content: \"\\e090\";\n}\n\n.glyphicon-arrow-left:before {\n  content: \"\\e091\";\n}\n\n.glyphicon-arrow-right:before {\n  content: \"\\e092\";\n}\n\n.glyphicon-arrow-up:before {\n  content: \"\\e093\";\n}\n\n.glyphicon-arrow-down:before {\n  content: \"\\e094\";\n}\n\n.glyphicon-share-alt:before {\n  content: \"\\e095\";\n}\n\n.glyphicon-resize-full:before {\n  content: \"\\e096\";\n}\n\n.glyphicon-resize-small:before {\n  content: \"\\e097\";\n}\n\n.glyphicon-exclamation-sign:before {\n  content: \"\\e101\";\n}\n\n.glyphicon-gift:before {\n  content: \"\\e102\";\n}\n\n.glyphicon-leaf:before {\n  content: \"\\e103\";\n}\n\n.glyphicon-fire:before {\n  content: \"\\e104\";\n}\n\n.glyphicon-eye-open:before {\n  content: \"\\e105\";\n}\n\n.glyphicon-eye-close:before {\n  content: \"\\e106\";\n}\n\n.glyphicon-warning-sign:before {\n  content: \"\\e107\";\n}\n\n.glyphicon-plane:before {\n  content: \"\\e108\";\n}\n\n.glyphicon-calendar:before {\n  content: \"\\e109\";\n}\n\n.glyphicon-random:before {\n  content: \"\\e110\";\n}\n\n.glyphicon-comment:before {\n  content: \"\\e111\";\n}\n\n.glyphicon-magnet:before {\n  content: \"\\e112\";\n}\n\n.glyphicon-chevron-up:before {\n  content: \"\\e113\";\n}\n\n.glyphicon-chevron-down:before {\n  content: \"\\e114\";\n}\n\n.glyphicon-retweet:before {\n  content: \"\\e115\";\n}\n\n.glyphicon-shopping-cart:before {\n  content: \"\\e116\";\n}\n\n.glyphicon-folder-close:before {\n  content: \"\\e117\";\n}\n\n.glyphicon-folder-open:before {\n  content: \"\\e118\";\n}\n\n.glyphicon-resize-vertical:before {\n  content: \"\\e119\";\n}\n\n.glyphicon-resize-horizontal:before {\n  content: \"\\e120\";\n}\n\n.glyphicon-hdd:before {\n  content: \"\\e121\";\n}\n\n.glyphicon-bullhorn:before {\n  content: \"\\e122\";\n}\n\n.glyphicon-bell:before {\n  content: \"\\e123\";\n}\n\n.glyphicon-certificate:before {\n  content: \"\\e124\";\n}\n\n.glyphicon-thumbs-up:before {\n  content: \"\\e125\";\n}\n\n.glyphicon-thumbs-down:before {\n  content: \"\\e126\";\n}\n\n.glyphicon-hand-right:before {\n  content: \"\\e127\";\n}\n\n.glyphicon-hand-left:before {\n  content: \"\\e128\";\n}\n\n.glyphicon-hand-up:before {\n  content: \"\\e129\";\n}\n\n.glyphicon-hand-down:before {\n  content: \"\\e130\";\n}\n\n.glyphicon-circle-arrow-right:before {\n  content: \"\\e131\";\n}\n\n.glyphicon-circle-arrow-left:before {\n  content: \"\\e132\";\n}\n\n.glyphicon-circle-arrow-up:before {\n  content: \"\\e133\";\n}\n\n.glyphicon-circle-arrow-down:before {\n  content: \"\\e134\";\n}\n\n.glyphicon-globe:before {\n  content: \"\\e135\";\n}\n\n.glyphicon-wrench:before {\n  content: \"\\e136\";\n}\n\n.glyphicon-tasks:before {\n  content: \"\\e137\";\n}\n\n.glyphicon-filter:before {\n  content: \"\\e138\";\n}\n\n.glyphicon-briefcase:before {\n  content: \"\\e139\";\n}\n\n.glyphicon-fullscreen:before {\n  content: \"\\e140\";\n}\n\n.glyphicon-dashboard:before {\n  content: \"\\e141\";\n}\n\n.glyphicon-paperclip:before {\n  content: \"\\e142\";\n}\n\n.glyphicon-heart-empty:before {\n  content: \"\\e143\";\n}\n\n.glyphicon-link:before {\n  content: \"\\e144\";\n}\n\n.glyphicon-phone:before {\n  content: \"\\e145\";\n}\n\n.glyphicon-pushpin:before {\n  content: \"\\e146\";\n}\n\n.glyphicon-usd:before {\n  content: \"\\e148\";\n}\n\n.glyphicon-gbp:before {\n  content: \"\\e149\";\n}\n\n.glyphicon-sort:before {\n  content: \"\\e150\";\n}\n\n.glyphicon-sort-by-alphabet:before {\n  content: \"\\e151\";\n}\n\n.glyphicon-sort-by-alphabet-alt:before {\n  content: \"\\e152\";\n}\n\n.glyphicon-sort-by-order:before {\n  content: \"\\e153\";\n}\n\n.glyphicon-sort-by-order-alt:before {\n  content: \"\\e154\";\n}\n\n.glyphicon-sort-by-attributes:before {\n  content: \"\\e155\";\n}\n\n.glyphicon-sort-by-attributes-alt:before {\n  content: \"\\e156\";\n}\n\n.glyphicon-unchecked:before {\n  content: \"\\e157\";\n}\n\n.glyphicon-expand:before {\n  content: \"\\e158\";\n}\n\n.glyphicon-collapse-down:before {\n  content: \"\\e159\";\n}\n\n.glyphicon-collapse-up:before {\n  content: \"\\e160\";\n}\n\n.glyphicon-log-in:before {\n  content: \"\\e161\";\n}\n\n.glyphicon-flash:before {\n  content: \"\\e162\";\n}\n\n.glyphicon-log-out:before {\n  content: \"\\e163\";\n}\n\n.glyphicon-new-window:before {\n  content: \"\\e164\";\n}\n\n.glyphicon-record:before {\n  content: \"\\e165\";\n}\n\n.glyphicon-save:before {\n  content: \"\\e166\";\n}\n\n.glyphicon-open:before {\n  content: \"\\e167\";\n}\n\n.glyphicon-saved:before {\n  content: \"\\e168\";\n}\n\n.glyphicon-import:before {\n  content: \"\\e169\";\n}\n\n.glyphicon-export:before {\n  content: \"\\e170\";\n}\n\n.glyphicon-send:before {\n  content: \"\\e171\";\n}\n\n.glyphicon-floppy-disk:before {\n  content: \"\\e172\";\n}\n\n.glyphicon-floppy-saved:before {\n  content: \"\\e173\";\n}\n\n.glyphicon-floppy-remove:before {\n  content: \"\\e174\";\n}\n\n.glyphicon-floppy-save:before {\n  content: \"\\e175\";\n}\n\n.glyphicon-floppy-open:before {\n  content: \"\\e176\";\n}\n\n.glyphicon-credit-card:before {\n  content: \"\\e177\";\n}\n\n.glyphicon-transfer:before {\n  content: \"\\e178\";\n}\n\n.glyphicon-cutlery:before {\n  content: \"\\e179\";\n}\n\n.glyphicon-header:before {\n  content: \"\\e180\";\n}\n\n.glyphicon-compressed:before {\n  content: \"\\e181\";\n}\n\n.glyphicon-earphone:before {\n  content: \"\\e182\";\n}\n\n.glyphicon-phone-alt:before {\n  content: \"\\e183\";\n}\n\n.glyphicon-tower:before {\n  content: \"\\e184\";\n}\n\n.glyphicon-stats:before {\n  content: \"\\e185\";\n}\n\n.glyphicon-sd-video:before {\n  content: \"\\e186\";\n}\n\n.glyphicon-hd-video:before {\n  content: \"\\e187\";\n}\n\n.glyphicon-subtitles:before {\n  content: \"\\e188\";\n}\n\n.glyphicon-sound-stereo:before {\n  content: \"\\e189\";\n}\n\n.glyphicon-sound-dolby:before {\n  content: \"\\e190\";\n}\n\n.glyphicon-sound-5-1:before {\n  content: \"\\e191\";\n}\n\n.glyphicon-sound-6-1:before {\n  content: \"\\e192\";\n}\n\n.glyphicon-sound-7-1:before {\n  content: \"\\e193\";\n}\n\n.glyphicon-copyright-mark:before {\n  content: \"\\e194\";\n}\n\n.glyphicon-registration-mark:before {\n  content: \"\\e195\";\n}\n\n.glyphicon-cloud-download:before {\n  content: \"\\e197\";\n}\n\n.glyphicon-cloud-upload:before {\n  content: \"\\e198\";\n}\n\n.glyphicon-tree-conifer:before {\n  content: \"\\e199\";\n}\n\n.glyphicon-tree-deciduous:before {\n  content: \"\\e200\";\n}\n\n.caret {\n  display: inline-block;\n  width: 0;\n  height: 0;\n  margin-left: 2px;\n  vertical-align: middle;\n  border-top: 4px solid;\n  border-right: 4px solid transparent;\n  border-left: 4px solid transparent;\n}\n\n.dropdown {\n  position: relative;\n}\n\n.dropdown-toggle:focus {\n  outline: 0;\n}\n\n.dropdown-menu {\n  position: absolute;\n  top: 100%;\n  left: 0;\n  z-index: 1000;\n  display: none;\n  float: left;\n  min-width: 160px;\n  padding: 5px 0;\n  margin: 2px 0 0;\n  font-size: 14px;\n  list-style: none;\n  background-color: #ffffff;\n  border: 1px solid #cccccc;\n  border: 1px solid rgba(0, 0, 0, 0.15);\n  border-radius: 4px;\n  -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);\n          box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);\n  background-clip: padding-box;\n}\n\n.dropdown-menu.pull-right {\n  right: 0;\n  left: auto;\n}\n\n.dropdown-menu .divider {\n  height: 1px;\n  margin: 9px 0;\n  overflow: hidden;\n  background-color: #e5e5e5;\n}\n\n.dropdown-menu > li > a {\n  display: block;\n  padding: 3px 20px;\n  clear: both;\n  font-weight: normal;\n  line-height: 1.428571429;\n  color: #333333;\n  white-space: nowrap;\n}\n\n.dropdown-menu > li > a:hover,\n.dropdown-menu > li > a:focus {\n  color: #262626;\n  text-decoration: none;\n  background-color: #f5f5f5;\n}\n\n.dropdown-menu > .active > a,\n.dropdown-menu > .active > a:hover,\n.dropdown-menu > .active > a:focus {\n  color: #ffffff;\n  text-decoration: none;\n  background-color: #428bca;\n  outline: 0;\n}\n\n.dropdown-menu > .disabled > a,\n.dropdown-menu > .disabled > a:hover,\n.dropdown-menu > .disabled > a:focus {\n  color: #999999;\n}\n\n.dropdown-menu > .disabled > a:hover,\n.dropdown-menu > .disabled > a:focus {\n  text-decoration: none;\n  cursor: not-allowed;\n  background-color: transparent;\n  background-image: none;\n  filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);\n}\n\n.open > .dropdown-menu {\n  display: block;\n}\n\n.open > a {\n  outline: 0;\n}\n\n.dropdown-header {\n  display: block;\n  padding: 3px 20px;\n  font-size: 12px;\n  line-height: 1.428571429;\n  color: #999999;\n}\n\n.dropdown-backdrop {\n  position: fixed;\n  top: 0;\n  right: 0;\n  bottom: 0;\n  left: 0;\n  z-index: 990;\n}\n\n.pull-right > .dropdown-menu {\n  right: 0;\n  left: auto;\n}\n\n.dropup .caret,\n.navbar-fixed-bottom .dropdown .caret {\n  border-top: 0;\n  border-bottom: 4px solid;\n  content: \"\";\n}\n\n.dropup .dropdown-menu,\n.navbar-fixed-bottom .dropdown .dropdown-menu {\n  top: auto;\n  bottom: 100%;\n  margin-bottom: 1px;\n}\n\n@media (min-width: 768px) {\n  .navbar-right .dropdown-menu {\n    right: 0;\n    left: auto;\n  }\n}\n\n.btn-group,\n.btn-group-vertical {\n  position: relative;\n  display: inline-block;\n  vertical-align: middle;\n}\n\n.btn-group > .btn,\n.btn-group-vertical > .btn {\n  position: relative;\n  float: left;\n}\n\n.btn-group > .btn:hover,\n.btn-group-vertical > .btn:hover,\n.btn-group > .btn:focus,\n.btn-group-vertical > .btn:focus,\n.btn-group > .btn:active,\n.btn-group-vertical > .btn:active,\n.btn-group > .btn.active,\n.btn-group-vertical > .btn.active {\n  z-index: 2;\n}\n\n.btn-group > .btn:focus,\n.btn-group-vertical > .btn:focus {\n  outline: none;\n}\n\n.btn-group .btn + .btn,\n.btn-group .btn + .btn-group,\n.btn-group .btn-group + .btn,\n.btn-group .btn-group + .btn-group {\n  margin-left: -1px;\n}\n\n.btn-toolbar:before,\n.btn-toolbar:after {\n  display: table;\n  content: \" \";\n}\n\n.btn-toolbar:after {\n  clear: both;\n}\n\n.btn-toolbar:before,\n.btn-toolbar:after {\n  display: table;\n  content: \" \";\n}\n\n.btn-toolbar:after {\n  clear: both;\n}\n\n.btn-toolbar .btn-group {\n  float: left;\n}\n\n.btn-toolbar > .btn + .btn,\n.btn-toolbar > .btn-group + .btn,\n.btn-toolbar > .btn + .btn-group,\n.btn-toolbar > .btn-group + .btn-group {\n  margin-left: 5px;\n}\n\n.btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) {\n  border-radius: 0;\n}\n\n.btn-group > .btn:first-child {\n  margin-left: 0;\n}\n\n.btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) {\n  border-top-right-radius: 0;\n  border-bottom-right-radius: 0;\n}\n\n.btn-group > .btn:last-child:not(:first-child),\n.btn-group > .dropdown-toggle:not(:first-child) {\n  border-bottom-left-radius: 0;\n  border-top-left-radius: 0;\n}\n\n.btn-group > .btn-group {\n  float: left;\n}\n\n.btn-group > .btn-group:not(:first-child):not(:last-child) > .btn {\n  border-radius: 0;\n}\n\n.btn-group > .btn-group:first-child > .btn:last-child,\n.btn-group > .btn-group:first-child > .dropdown-toggle {\n  border-top-right-radius: 0;\n  border-bottom-right-radius: 0;\n}\n\n.btn-group > .btn-group:last-child > .btn:first-child {\n  border-bottom-left-radius: 0;\n  border-top-left-radius: 0;\n}\n\n.btn-group .dropdown-toggle:active,\n.btn-group.open .dropdown-toggle {\n  outline: 0;\n}\n\n.btn-group-xs > .btn {\n  padding: 1px 5px;\n  font-size: 12px;\n  line-height: 1.5;\n  border-radius: 3px;\n}\n\n.btn-group-sm > .btn {\n  padding: 5px 10px;\n  font-size: 12px;\n  line-height: 1.5;\n  border-radius: 3px;\n}\n\n.btn-group-lg > .btn {\n  padding: 10px 16px;\n  font-size: 18px;\n  line-height: 1.33;\n  border-radius: 6px;\n}\n\n.btn-group > .btn + .dropdown-toggle {\n  padding-right: 8px;\n  padding-left: 8px;\n}\n\n.btn-group > .btn-lg + .dropdown-toggle {\n  padding-right: 12px;\n  padding-left: 12px;\n}\n\n.btn-group.open .dropdown-toggle {\n  -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);\n          box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);\n}\n\n.btn-group.open .dropdown-toggle.btn-link {\n  -webkit-box-shadow: none;\n          box-shadow: none;\n}\n\n.btn .caret {\n  margin-left: 0;\n}\n\n.btn-lg .caret {\n  border-width: 5px 5px 0;\n  border-bottom-width: 0;\n}\n\n.dropup .btn-lg .caret {\n  border-width: 0 5px 5px;\n}\n\n.btn-group-vertical > .btn,\n.btn-group-vertical > .btn-group,\n.btn-group-vertical > .btn-group > .btn {\n  display: block;\n  float: none;\n  width: 100%;\n  max-width: 100%;\n}\n\n.btn-group-vertical > .btn-group:before,\n.btn-group-vertical > .btn-group:after {\n  display: table;\n  content: \" \";\n}\n\n.btn-group-vertical > .btn-group:after {\n  clear: both;\n}\n\n.btn-group-vertical > .btn-group:before,\n.btn-group-vertical > .btn-group:after {\n  display: table;\n  content: \" \";\n}\n\n.btn-group-vertical > .btn-group:after {\n  clear: both;\n}\n\n.btn-group-vertical > .btn-group > .btn {\n  float: none;\n}\n\n.btn-group-vertical > .btn + .btn,\n.btn-group-vertical > .btn + .btn-group,\n.btn-group-vertical > .btn-group + .btn,\n.btn-group-vertical > .btn-group + .btn-group {\n  margin-top: -1px;\n  margin-left: 0;\n}\n\n.btn-group-vertical > .btn:not(:first-child):not(:last-child) {\n  border-radius: 0;\n}\n\n.btn-group-vertical > .btn:first-child:not(:last-child) {\n  border-top-right-radius: 4px;\n  border-bottom-right-radius: 0;\n  border-bottom-left-radius: 0;\n}\n\n.btn-group-vertical > .btn:last-child:not(:first-child) {\n  border-top-right-radius: 0;\n  border-bottom-left-radius: 4px;\n  border-top-left-radius: 0;\n}\n\n.btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn {\n  border-radius: 0;\n}\n\n.btn-group-vertical > .btn-group:first-child > .btn:last-child,\n.btn-group-vertical > .btn-group:first-child > .dropdown-toggle {\n  border-bottom-right-radius: 0;\n  border-bottom-left-radius: 0;\n}\n\n.btn-group-vertical > .btn-group:last-child > .btn:first-child {\n  border-top-right-radius: 0;\n  border-top-left-radius: 0;\n}\n\n.btn-group-justified {\n  display: table;\n  width: 100%;\n  border-collapse: separate;\n  table-layout: fixed;\n}\n\n.btn-group-justified > .btn,\n.btn-group-justified > .btn-group {\n  display: table-cell;\n  float: none;\n  width: 1%;\n}\n\n.btn-group-justified > .btn-group .btn {\n  width: 100%;\n}\n\n[data-toggle=\"buttons\"] > .btn > input[type=\"radio\"],\n[data-toggle=\"buttons\"] > .btn > input[type=\"checkbox\"] {\n  display: none;\n}\n\n.input-group {\n  position: relative;\n  display: table;\n  border-collapse: separate;\n}\n\n.input-group[class*=\"col-\"] {\n  float: none;\n  padding-right: 0;\n  padding-left: 0;\n}\n\n.input-group .form-control {\n  width: 100%;\n  margin-bottom: 0;\n}\n\n.input-group-lg > .form-control,\n.input-group-lg > .input-group-addon,\n.input-group-lg > .input-group-btn > .btn {\n  height: 46px;\n  padding: 10px 16px;\n  font-size: 18px;\n  line-height: 1.33;\n  border-radius: 6px;\n}\n\nselect.input-group-lg > .form-control,\nselect.input-group-lg > .input-group-addon,\nselect.input-group-lg > .input-group-btn > .btn {\n  height: 46px;\n  line-height: 46px;\n}\n\ntextarea.input-group-lg > .form-control,\ntextarea.input-group-lg > .input-group-addon,\ntextarea.input-group-lg > .input-group-btn > .btn {\n  height: auto;\n}\n\n.input-group-sm > .form-control,\n.input-group-sm > .input-group-addon,\n.input-group-sm > .input-group-btn > .btn {\n  height: 30px;\n  padding: 5px 10px;\n  font-size: 12px;\n  line-height: 1.5;\n  border-radius: 3px;\n}\n\nselect.input-group-sm > .form-control,\nselect.input-group-sm > .input-group-addon,\nselect.input-group-sm > .input-group-btn > .btn {\n  height: 30px;\n  line-height: 30px;\n}\n\ntextarea.input-group-sm > .form-control,\ntextarea.input-group-sm > .input-group-addon,\ntextarea.input-group-sm > .input-group-btn > .btn {\n  height: auto;\n}\n\n.input-group-addon,\n.input-group-btn,\n.input-group .form-control {\n  display: table-cell;\n}\n\n.input-group-addon:not(:first-child):not(:last-child),\n.input-group-btn:not(:first-child):not(:last-child),\n.input-group .form-control:not(:first-child):not(:last-child) {\n  border-radius: 0;\n}\n\n.input-group-addon,\n.input-group-btn {\n  width: 1%;\n  white-space: nowrap;\n  vertical-align: middle;\n}\n\n.input-group-addon {\n  padding: 6px 12px;\n  font-size: 14px;\n  font-weight: normal;\n  line-height: 1;\n  color: #555555;\n  text-align: center;\n  background-color: #eeeeee;\n  border: 1px solid #cccccc;\n  border-radius: 4px;\n}\n\n.input-group-addon.input-sm {\n  padding: 5px 10px;\n  font-size: 12px;\n  border-radius: 3px;\n}\n\n.input-group-addon.input-lg {\n  padding: 10px 16px;\n  font-size: 18px;\n  border-radius: 6px;\n}\n\n.input-group-addon input[type=\"radio\"],\n.input-group-addon input[type=\"checkbox\"] {\n  margin-top: 0;\n}\n\n.input-group .form-control:first-child,\n.input-group-addon:first-child,\n.input-group-btn:first-child > .btn,\n.input-group-btn:first-child > .dropdown-toggle,\n.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle) {\n  border-top-right-radius: 0;\n  border-bottom-right-radius: 0;\n}\n\n.input-group-addon:first-child {\n  border-right: 0;\n}\n\n.input-group .form-control:last-child,\n.input-group-addon:last-child,\n.input-group-btn:last-child > .btn,\n.input-group-btn:last-child > .dropdown-toggle,\n.input-group-btn:first-child > .btn:not(:first-child) {\n  border-bottom-left-radius: 0;\n  border-top-left-radius: 0;\n}\n\n.input-group-addon:last-child {\n  border-left: 0;\n}\n\n.input-group-btn {\n  position: relative;\n  white-space: nowrap;\n}\n\n.input-group-btn:first-child > .btn {\n  margin-right: -1px;\n}\n\n.input-group-btn:last-child > .btn {\n  margin-left: -1px;\n}\n\n.input-group-btn > .btn {\n  position: relative;\n}\n\n.input-group-btn > .btn + .btn {\n  margin-left: -4px;\n}\n\n.input-group-btn > .btn:hover,\n.input-group-btn > .btn:active {\n  z-index: 2;\n}\n\n.nav {\n  padding-left: 0;\n  margin-bottom: 0;\n  list-style: none;\n}\n\n.nav:before,\n.nav:after {\n  display: table;\n  content: \" \";\n}\n\n.nav:after {\n  clear: both;\n}\n\n.nav:before,\n.nav:after {\n  display: table;\n  content: \" \";\n}\n\n.nav:after {\n  clear: both;\n}\n\n.nav > li {\n  position: relative;\n  display: block;\n}\n\n.nav > li > a {\n  position: relative;\n  display: block;\n  padding: 10px 15px;\n}\n\n.nav > li > a:hover,\n.nav > li > a:focus {\n  text-decoration: none;\n  background-color: #eeeeee;\n}\n\n.nav > li.disabled > a {\n  color: #999999;\n}\n\n.nav > li.disabled > a:hover,\n.nav > li.disabled > a:focus {\n  color: #999999;\n  text-decoration: none;\n  cursor: not-allowed;\n  background-color: transparent;\n}\n\n.nav .open > a,\n.nav .open > a:hover,\n.nav .open > a:focus {\n  background-color: #eeeeee;\n  border-color: #428bca;\n}\n\n.nav .nav-divider {\n  height: 1px;\n  margin: 9px 0;\n  overflow: hidden;\n  background-color: #e5e5e5;\n}\n\n.nav > li > a > img {\n  max-width: none;\n}\n\n.nav-tabs {\n  border-bottom: 1px solid #dddddd;\n}\n\n.nav-tabs > li {\n  float: left;\n  margin-bottom: -1px;\n}\n\n.nav-tabs > li > a {\n  margin-right: 2px;\n  line-height: 1.428571429;\n  border: 1px solid transparent;\n  border-radius: 4px 4px 0 0;\n}\n\n.nav-tabs > li > a:hover {\n  border-color: #eeeeee #eeeeee #dddddd;\n}\n\n.nav-tabs > li.active > a,\n.nav-tabs > li.active > a:hover,\n.nav-tabs > li.active > a:focus {\n  color: #555555;\n  cursor: default;\n  background-color: #ffffff;\n  border: 1px solid #dddddd;\n  border-bottom-color: transparent;\n}\n\n.nav-tabs.nav-justified {\n  width: 100%;\n  border-bottom: 0;\n}\n\n.nav-tabs.nav-justified > li {\n  float: none;\n}\n\n.nav-tabs.nav-justified > li > a {\n  margin-bottom: 5px;\n  text-align: center;\n}\n\n.nav-tabs.nav-justified > .dropdown .dropdown-menu {\n  top: auto;\n  left: auto;\n}\n\n@media (min-width: 768px) {\n  .nav-tabs.nav-justified > li {\n    display: table-cell;\n    width: 1%;\n  }\n  .nav-tabs.nav-justified > li > a {\n    margin-bottom: 0;\n  }\n}\n\n.nav-tabs.nav-justified > li > a {\n  margin-right: 0;\n  border-radius: 4px;\n}\n\n.nav-tabs.nav-justified > .active > a,\n.nav-tabs.nav-justified > .active > a:hover,\n.nav-tabs.nav-justified > .active > a:focus {\n  border: 1px solid #dddddd;\n}\n\n@media (min-width: 768px) {\n  .nav-tabs.nav-justified > li > a {\n    border-bottom: 1px solid #dddddd;\n    border-radius: 4px 4px 0 0;\n  }\n  .nav-tabs.nav-justified > .active > a,\n  .nav-tabs.nav-justified > .active > a:hover,\n  .nav-tabs.nav-justified > .active > a:focus {\n    border-bottom-color: #ffffff;\n  }\n}\n\n.nav-pills > li {\n  float: left;\n}\n\n.nav-pills > li > a {\n  border-radius: 4px;\n}\n\n.nav-pills > li + li {\n  margin-left: 2px;\n}\n\n.nav-pills > li.active > a,\n.nav-pills > li.active > a:hover,\n.nav-pills > li.active > a:focus {\n  color: #ffffff;\n  background-color: #428bca;\n}\n\n.nav-stacked > li {\n  float: none;\n}\n\n.nav-stacked > li + li {\n  margin-top: 2px;\n  margin-left: 0;\n}\n\n.nav-justified {\n  width: 100%;\n}\n\n.nav-justified > li {\n  float: none;\n}\n\n.nav-justified > li > a {\n  margin-bottom: 5px;\n  text-align: center;\n}\n\n.nav-justified > .dropdown .dropdown-menu {\n  top: auto;\n  left: auto;\n}\n\n@media (min-width: 768px) {\n  .nav-justified > li {\n    display: table-cell;\n    width: 1%;\n  }\n  .nav-justified > li > a {\n    margin-bottom: 0;\n  }\n}\n\n.nav-tabs-justified {\n  border-bottom: 0;\n}\n\n.nav-tabs-justified > li > a {\n  margin-right: 0;\n  border-radius: 4px;\n}\n\n.nav-tabs-justified > .active > a,\n.nav-tabs-justified > .active > a:hover,\n.nav-tabs-justified > .active > a:focus {\n  border: 1px solid #dddddd;\n}\n\n@media (min-width: 768px) {\n  .nav-tabs-justified > li > a {\n    border-bottom: 1px solid #dddddd;\n    border-radius: 4px 4px 0 0;\n  }\n  .nav-tabs-justified > .active > a,\n  .nav-tabs-justified > .active > a:hover,\n  .nav-tabs-justified > .active > a:focus {\n    border-bottom-color: #ffffff;\n  }\n}\n\n.tab-content > .tab-pane {\n  display: none;\n}\n\n.tab-content > .active {\n  display: block;\n}\n\n.nav-tabs .dropdown-menu {\n  margin-top: -1px;\n  border-top-right-radius: 0;\n  border-top-left-radius: 0;\n}\n\n.navbar {\n  position: relative;\n  min-height: 50px;\n  margin-bottom: 20px;\n  border: 1px solid transparent;\n}\n\n.navbar:before,\n.navbar:after {\n  display: table;\n  content: \" \";\n}\n\n.navbar:after {\n  clear: both;\n}\n\n.navbar:before,\n.navbar:after {\n  display: table;\n  content: \" \";\n}\n\n.navbar:after {\n  clear: both;\n}\n\n@media (min-width: 768px) {\n  .navbar {\n    border-radius: 4px;\n  }\n}\n\n.navbar-header:before,\n.navbar-header:after {\n  display: table;\n  content: \" \";\n}\n\n.navbar-header:after {\n  clear: both;\n}\n\n.navbar-header:before,\n.navbar-header:after {\n  display: table;\n  content: \" \";\n}\n\n.navbar-header:after {\n  clear: both;\n}\n\n@media (min-width: 768px) {\n  .navbar-header {\n    float: left;\n  }\n}\n\n.navbar-collapse {\n  max-height: 340px;\n  padding-right: 15px;\n  padding-left: 15px;\n  overflow-x: visible;\n  border-top: 1px solid transparent;\n  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1);\n  -webkit-overflow-scrolling: touch;\n}\n\n.navbar-collapse:before,\n.navbar-collapse:after {\n  display: table;\n  content: \" \";\n}\n\n.navbar-collapse:after {\n  clear: both;\n}\n\n.navbar-collapse:before,\n.navbar-collapse:after {\n  display: table;\n  content: \" \";\n}\n\n.navbar-collapse:after {\n  clear: both;\n}\n\n.navbar-collapse.in {\n  overflow-y: auto;\n}\n\n@media (min-width: 768px) {\n  .navbar-collapse {\n    width: auto;\n    border-top: 0;\n    box-shadow: none;\n  }\n  .navbar-collapse.collapse {\n    display: block !important;\n    height: auto !important;\n    padding-bottom: 0;\n    overflow: visible !important;\n  }\n  .navbar-collapse.in {\n    overflow-y: visible;\n  }\n  .navbar-fixed-top .navbar-collapse,\n  .navbar-static-top .navbar-collapse,\n  .navbar-fixed-bottom .navbar-collapse {\n    padding-right: 0;\n    padding-left: 0;\n  }\n}\n\n.container > .navbar-header,\n.container > .navbar-collapse {\n  margin-right: -15px;\n  margin-left: -15px;\n}\n\n@media (min-width: 768px) {\n  .container > .navbar-header,\n  .container > .navbar-collapse {\n    margin-right: 0;\n    margin-left: 0;\n  }\n}\n\n.navbar-static-top {\n  z-index: 1000;\n  border-width: 0 0 1px;\n}\n\n@media (min-width: 768px) {\n  .navbar-static-top {\n    border-radius: 0;\n  }\n}\n\n.navbar-fixed-top,\n.navbar-fixed-bottom {\n  position: fixed;\n  right: 0;\n  left: 0;\n  z-index: 1030;\n}\n\n@media (min-width: 768px) {\n  .navbar-fixed-top,\n  .navbar-fixed-bottom {\n    border-radius: 0;\n  }\n}\n\n.navbar-fixed-top {\n  top: 0;\n  border-width: 0 0 1px;\n}\n\n.navbar-fixed-bottom {\n  bottom: 0;\n  margin-bottom: 0;\n  border-width: 1px 0 0;\n}\n\n.navbar-brand {\n  float: left;\n  padding: 15px 15px;\n  font-size: 18px;\n  line-height: 20px;\n}\n\n.navbar-brand:hover,\n.navbar-brand:focus {\n  text-decoration: none;\n}\n\n@media (min-width: 768px) {\n  .navbar > .container .navbar-brand {\n    margin-left: -15px;\n  }\n}\n\n.navbar-toggle {\n  position: relative;\n  float: right;\n  padding: 9px 10px;\n  margin-top: 8px;\n  margin-right: 15px;\n  margin-bottom: 8px;\n  background-color: transparent;\n  background-image: none;\n  border: 1px solid transparent;\n  border-radius: 4px;\n}\n\n.navbar-toggle .icon-bar {\n  display: block;\n  width: 22px;\n  height: 2px;\n  border-radius: 1px;\n}\n\n.navbar-toggle .icon-bar + .icon-bar {\n  margin-top: 4px;\n}\n\n@media (min-width: 768px) {\n  .navbar-toggle {\n    display: none;\n  }\n}\n\n.navbar-nav {\n  margin: 7.5px -15px;\n}\n\n.navbar-nav > li > a {\n  padding-top: 10px;\n  padding-bottom: 10px;\n  line-height: 20px;\n}\n\n@media (max-width: 767px) {\n  .navbar-nav .open .dropdown-menu {\n    position: static;\n    float: none;\n    width: auto;\n    margin-top: 0;\n    background-color: transparent;\n    border: 0;\n    box-shadow: none;\n  }\n  .navbar-nav .open .dropdown-menu > li > a,\n  .navbar-nav .open .dropdown-menu .dropdown-header {\n    padding: 5px 15px 5px 25px;\n  }\n  .navbar-nav .open .dropdown-menu > li > a {\n    line-height: 20px;\n  }\n  .navbar-nav .open .dropdown-menu > li > a:hover,\n  .navbar-nav .open .dropdown-menu > li > a:focus {\n    background-image: none;\n  }\n}\n\n@media (min-width: 768px) {\n  .navbar-nav {\n    float: left;\n    margin: 0;\n  }\n  .navbar-nav > li {\n    float: left;\n  }\n  .navbar-nav > li > a {\n    padding-top: 15px;\n    padding-bottom: 15px;\n  }\n  .navbar-nav.navbar-right:last-child {\n    margin-right: -15px;\n  }\n}\n\n@media (min-width: 768px) {\n  .navbar-left {\n    float: left !important;\n  }\n  .navbar-right {\n    float: right !important;\n  }\n}\n\n.navbar-form {\n  padding: 10px 15px;\n  margin-top: 8px;\n  margin-right: -15px;\n  margin-bottom: 8px;\n  margin-left: -15px;\n  border-top: 1px solid transparent;\n  border-bottom: 1px solid transparent;\n  -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);\n          box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);\n}\n\n@media (min-width: 768px) {\n  .navbar-form .form-group {\n    display: inline-block;\n    margin-bottom: 0;\n    vertical-align: middle;\n  }\n  .navbar-form .form-control {\n    display: inline-block;\n  }\n  .navbar-form select.form-control {\n    width: auto;\n  }\n  .navbar-form .radio,\n  .navbar-form .checkbox {\n    display: inline-block;\n    padding-left: 0;\n    margin-top: 0;\n    margin-bottom: 0;\n  }\n  .navbar-form .radio input[type=\"radio\"],\n  .navbar-form .checkbox input[type=\"checkbox\"] {\n    float: none;\n    margin-left: 0;\n  }\n}\n\n@media (max-width: 767px) {\n  .navbar-form .form-group {\n    margin-bottom: 5px;\n  }\n}\n\n@media (min-width: 768px) {\n  .navbar-form {\n    width: auto;\n    padding-top: 0;\n    padding-bottom: 0;\n    margin-right: 0;\n    margin-left: 0;\n    border: 0;\n    -webkit-box-shadow: none;\n            box-shadow: none;\n  }\n  .navbar-form.navbar-right:last-child {\n    margin-right: -15px;\n  }\n}\n\n.navbar-nav > li > .dropdown-menu {\n  margin-top: 0;\n  border-top-right-radius: 0;\n  border-top-left-radius: 0;\n}\n\n.navbar-fixed-bottom .navbar-nav > li > .dropdown-menu {\n  border-bottom-right-radius: 0;\n  border-bottom-left-radius: 0;\n}\n\n.navbar-nav.pull-right > li > .dropdown-menu,\n.navbar-nav > li > .dropdown-menu.pull-right {\n  right: 0;\n  left: auto;\n}\n\n.navbar-btn {\n  margin-top: 8px;\n  margin-bottom: 8px;\n}\n\n.navbar-btn.btn-sm {\n  margin-top: 10px;\n  margin-bottom: 10px;\n}\n\n.navbar-btn.btn-xs {\n  margin-top: 14px;\n  margin-bottom: 14px;\n}\n\n.navbar-text {\n  margin-top: 15px;\n  margin-bottom: 15px;\n}\n\n@media (min-width: 768px) {\n  .navbar-text {\n    float: left;\n    margin-right: 15px;\n    margin-left: 15px;\n  }\n  .navbar-text.navbar-right:last-child {\n    margin-right: 0;\n  }\n}\n\n.navbar-default {\n  background-color: #f8f8f8;\n  border-color: #e7e7e7;\n}\n\n.navbar-default .navbar-brand {\n  color: #777777;\n}\n\n.navbar-default .navbar-brand:hover,\n.navbar-default .navbar-brand:focus {\n  color: #5e5e5e;\n  background-color: transparent;\n}\n\n.navbar-default .navbar-text {\n  color: #777777;\n}\n\n.navbar-default .navbar-nav > li > a {\n  color: #777777;\n}\n\n.navbar-default .navbar-nav > li > a:hover,\n.navbar-default .navbar-nav > li > a:focus {\n  color: #333333;\n  background-color: transparent;\n}\n\n.navbar-default .navbar-nav > .active > a,\n.navbar-default .navbar-nav > .active > a:hover,\n.navbar-default .navbar-nav > .active > a:focus {\n  color: #555555;\n  background-color: #e7e7e7;\n}\n\n.navbar-default .navbar-nav > .disabled > a,\n.navbar-default .navbar-nav > .disabled > a:hover,\n.navbar-default .navbar-nav > .disabled > a:focus {\n  color: #cccccc;\n  background-color: transparent;\n}\n\n.navbar-default .navbar-toggle {\n  border-color: #dddddd;\n}\n\n.navbar-default .navbar-toggle:hover,\n.navbar-default .navbar-toggle:focus {\n  background-color: #dddddd;\n}\n\n.navbar-default .navbar-toggle .icon-bar {\n  background-color: #cccccc;\n}\n\n.navbar-default .navbar-collapse,\n.navbar-default .navbar-form {\n  border-color: #e7e7e7;\n}\n\n.navbar-default .navbar-nav > .open > a,\n.navbar-default .navbar-nav > .open > a:hover,\n.navbar-default .navbar-nav > .open > a:focus {\n  color: #555555;\n  background-color: #e7e7e7;\n}\n\n@media (max-width: 767px) {\n  .navbar-default .navbar-nav .open .dropdown-menu > li > a {\n    color: #777777;\n  }\n  .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,\n  .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {\n    color: #333333;\n    background-color: transparent;\n  }\n  .navbar-default .navbar-nav .open .dropdown-menu > .active > a,\n  .navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,\n  .navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {\n    color: #555555;\n    background-color: #e7e7e7;\n  }\n  .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a,\n  .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover,\n  .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus {\n    color: #cccccc;\n    background-color: transparent;\n  }\n}\n\n.navbar-default .navbar-link {\n  color: #777777;\n}\n\n.navbar-default .navbar-link:hover {\n  color: #333333;\n}\n\n.navbar-inverse {\n  background-color: #222222;\n  border-color: #080808;\n}\n\n.navbar-inverse .navbar-brand {\n  color: #999999;\n}\n\n.navbar-inverse .navbar-brand:hover,\n.navbar-inverse .navbar-brand:focus {\n  color: #ffffff;\n  background-color: transparent;\n}\n\n.navbar-inverse .navbar-text {\n  color: #999999;\n}\n\n.navbar-inverse .navbar-nav > li > a {\n  color: #999999;\n}\n\n.navbar-inverse .navbar-nav > li > a:hover,\n.navbar-inverse .navbar-nav > li > a:focus {\n  color: #ffffff;\n  background-color: transparent;\n}\n\n.navbar-inverse .navbar-nav > .active > a,\n.navbar-inverse .navbar-nav > .active > a:hover,\n.navbar-inverse .navbar-nav > .active > a:focus {\n  color: #ffffff;\n  background-color: #080808;\n}\n\n.navbar-inverse .navbar-nav > .disabled > a,\n.navbar-inverse .navbar-nav > .disabled > a:hover,\n.navbar-inverse .navbar-nav > .disabled > a:focus {\n  color: #444444;\n  background-color: transparent;\n}\n\n.navbar-inverse .navbar-toggle {\n  border-color: #333333;\n}\n\n.navbar-inverse .navbar-toggle:hover,\n.navbar-inverse .navbar-toggle:focus {\n  background-color: #333333;\n}\n\n.navbar-inverse .navbar-toggle .icon-bar {\n  background-color: #ffffff;\n}\n\n.navbar-inverse .navbar-collapse,\n.navbar-inverse .navbar-form {\n  border-color: #101010;\n}\n\n.navbar-inverse .navbar-nav > .open > a,\n.navbar-inverse .navbar-nav > .open > a:hover,\n.navbar-inverse .navbar-nav > .open > a:focus {\n  color: #ffffff;\n  background-color: #080808;\n}\n\n@media (max-width: 767px) {\n  .navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header {\n    border-color: #080808;\n  }\n  .navbar-inverse .navbar-nav .open .dropdown-menu .divider {\n    background-color: #080808;\n  }\n  .navbar-inverse .navbar-nav .open .dropdown-menu > li > a {\n    color: #999999;\n  }\n  .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover,\n  .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus {\n    color: #ffffff;\n    background-color: transparent;\n  }\n  .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a,\n  .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:hover,\n  .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:focus {\n    color: #ffffff;\n    background-color: #080808;\n  }\n  .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a,\n  .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:hover,\n  .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:focus {\n    color: #444444;\n    background-color: transparent;\n  }\n}\n\n.navbar-inverse .navbar-link {\n  color: #999999;\n}\n\n.navbar-inverse .navbar-link:hover {\n  color: #ffffff;\n}\n\n.breadcrumb {\n  padding: 8px 15px;\n  margin-bottom: 20px;\n  list-style: none;\n  background-color: #f5f5f5;\n  border-radius: 4px;\n}\n\n.breadcrumb > li {\n  display: inline-block;\n}\n\n.breadcrumb > li + li:before {\n  padding: 0 5px;\n  color: #cccccc;\n  content: \"/\\00a0\";\n}\n\n.breadcrumb > .active {\n  color: #999999;\n}\n\n.pagination {\n  display: inline-block;\n  padding-left: 0;\n  margin: 20px 0;\n  border-radius: 4px;\n}\n\n.pagination > li {\n  display: inline;\n}\n\n.pagination > li > a,\n.pagination > li > span {\n  position: relative;\n  float: left;\n  padding: 6px 12px;\n  margin-left: -1px;\n  line-height: 1.428571429;\n  text-decoration: none;\n  background-color: #ffffff;\n  border: 1px solid #dddddd;\n}\n\n.pagination > li:first-child > a,\n.pagination > li:first-child > span {\n  margin-left: 0;\n  border-bottom-left-radius: 4px;\n  border-top-left-radius: 4px;\n}\n\n.pagination > li:last-child > a,\n.pagination > li:last-child > span {\n  border-top-right-radius: 4px;\n  border-bottom-right-radius: 4px;\n}\n\n.pagination > li > a:hover,\n.pagination > li > span:hover,\n.pagination > li > a:focus,\n.pagination > li > span:focus {\n  background-color: #eeeeee;\n}\n\n.pagination > .active > a,\n.pagination > .active > span,\n.pagination > .active > a:hover,\n.pagination > .active > span:hover,\n.pagination > .active > a:focus,\n.pagination > .active > span:focus {\n  z-index: 2;\n  color: #ffffff;\n  cursor: default;\n  background-color: #428bca;\n  border-color: #428bca;\n}\n\n.pagination > .disabled > span,\n.pagination > .disabled > span:hover,\n.pagination > .disabled > span:focus,\n.pagination > .disabled > a,\n.pagination > .disabled > a:hover,\n.pagination > .disabled > a:focus {\n  color: #999999;\n  cursor: not-allowed;\n  background-color: #ffffff;\n  border-color: #dddddd;\n}\n\n.pagination-lg > li > a,\n.pagination-lg > li > span {\n  padding: 10px 16px;\n  font-size: 18px;\n}\n\n.pagination-lg > li:first-child > a,\n.pagination-lg > li:first-child > span {\n  border-bottom-left-radius: 6px;\n  border-top-left-radius: 6px;\n}\n\n.pagination-lg > li:last-child > a,\n.pagination-lg > li:last-child > span {\n  border-top-right-radius: 6px;\n  border-bottom-right-radius: 6px;\n}\n\n.pagination-sm > li > a,\n.pagination-sm > li > span {\n  padding: 5px 10px;\n  font-size: 12px;\n}\n\n.pagination-sm > li:first-child > a,\n.pagination-sm > li:first-child > span {\n  border-bottom-left-radius: 3px;\n  border-top-left-radius: 3px;\n}\n\n.pagination-sm > li:last-child > a,\n.pagination-sm > li:last-child > span {\n  border-top-right-radius: 3px;\n  border-bottom-right-radius: 3px;\n}\n\n.pager {\n  padding-left: 0;\n  margin: 20px 0;\n  text-align: center;\n  list-style: none;\n}\n\n.pager:before,\n.pager:after {\n  display: table;\n  content: \" \";\n}\n\n.pager:after {\n  clear: both;\n}\n\n.pager:before,\n.pager:after {\n  display: table;\n  content: \" \";\n}\n\n.pager:after {\n  clear: both;\n}\n\n.pager li {\n  display: inline;\n}\n\n.pager li > a,\n.pager li > span {\n  display: inline-block;\n  padding: 5px 14px;\n  background-color: #ffffff;\n  border: 1px solid #dddddd;\n  border-radius: 15px;\n}\n\n.pager li > a:hover,\n.pager li > a:focus {\n  text-decoration: none;\n  background-color: #eeeeee;\n}\n\n.pager .next > a,\n.pager .next > span {\n  float: right;\n}\n\n.pager .previous > a,\n.pager .previous > span {\n  float: left;\n}\n\n.pager .disabled > a,\n.pager .disabled > a:hover,\n.pager .disabled > a:focus,\n.pager .disabled > span {\n  color: #999999;\n  cursor: not-allowed;\n  background-color: #ffffff;\n}\n\n.label {\n  display: inline;\n  padding: .2em .6em .3em;\n  font-size: 75%;\n  font-weight: bold;\n  line-height: 1;\n  color: #ffffff;\n  text-align: center;\n  white-space: nowrap;\n  vertical-align: baseline;\n  border-radius: .25em;\n}\n\n.label[href]:hover,\n.label[href]:focus {\n  color: #ffffff;\n  text-decoration: none;\n  cursor: pointer;\n}\n\n.label:empty {\n  display: none;\n}\n\n.btn .label {\n  position: relative;\n  top: -1px;\n}\n\n.label-default {\n  background-color: #999999;\n}\n\n.label-default[href]:hover,\n.label-default[href]:focus {\n  background-color: #808080;\n}\n\n.label-primary {\n  background-color: #428bca;\n}\n\n.label-primary[href]:hover,\n.label-primary[href]:focus {\n  background-color: #3071a9;\n}\n\n.label-success {\n  background-color: #5cb85c;\n}\n\n.label-success[href]:hover,\n.label-success[href]:focus {\n  background-color: #449d44;\n}\n\n.label-info {\n  background-color: #5bc0de;\n}\n\n.label-info[href]:hover,\n.label-info[href]:focus {\n  background-color: #31b0d5;\n}\n\n.label-warning {\n  background-color: #f0ad4e;\n}\n\n.label-warning[href]:hover,\n.label-warning[href]:focus {\n  background-color: #ec971f;\n}\n\n.label-danger {\n  background-color: #d9534f;\n}\n\n.label-danger[href]:hover,\n.label-danger[href]:focus {\n  background-color: #c9302c;\n}\n\n.badge {\n  display: inline-block;\n  min-width: 10px;\n  padding: 3px 7px;\n  font-size: 12px;\n  font-weight: bold;\n  line-height: 1;\n  color: #ffffff;\n  text-align: center;\n  white-space: nowrap;\n  vertical-align: baseline;\n  background-color: #999999;\n  border-radius: 10px;\n}\n\n.badge:empty {\n  display: none;\n}\n\n.btn .badge {\n  position: relative;\n  top: -1px;\n}\n\na.badge:hover,\na.badge:focus {\n  color: #ffffff;\n  text-decoration: none;\n  cursor: pointer;\n}\n\na.list-group-item.active > .badge,\n.nav-pills > .active > a > .badge {\n  color: #428bca;\n  background-color: #ffffff;\n}\n\n.nav-pills > li > a > .badge {\n  margin-left: 3px;\n}\n\n.jumbotron {\n  padding: 30px;\n  margin-bottom: 30px;\n  font-size: 21px;\n  font-weight: 200;\n  line-height: 2.1428571435;\n  color: inherit;\n  background-color: #eeeeee;\n}\n\n.jumbotron h1,\n.jumbotron .h1 {\n  line-height: 1;\n  color: inherit;\n}\n\n.jumbotron p {\n  line-height: 1.4;\n}\n\n.container .jumbotron {\n  border-radius: 6px;\n}\n\n.jumbotron .container {\n  max-width: 100%;\n}\n\n@media screen and (min-width: 768px) {\n  .jumbotron {\n    padding-top: 48px;\n    padding-bottom: 48px;\n  }\n  .container .jumbotron {\n    padding-right: 60px;\n    padding-left: 60px;\n  }\n  .jumbotron h1,\n  .jumbotron .h1 {\n    font-size: 63px;\n  }\n}\n\n.thumbnail {\n  display: block;\n  padding: 4px;\n  margin-bottom: 20px;\n  line-height: 1.428571429;\n  background-color: #ffffff;\n  border: 1px solid #dddddd;\n  border-radius: 4px;\n  -webkit-transition: all 0.2s ease-in-out;\n          transition: all 0.2s ease-in-out;\n}\n\n.thumbnail > img,\n.thumbnail a > img {\n  display: block;\n  height: auto;\n  max-width: 100%;\n  margin-right: auto;\n  margin-left: auto;\n}\n\na.thumbnail:hover,\na.thumbnail:focus,\na.thumbnail.active {\n  border-color: #428bca;\n}\n\n.thumbnail .caption {\n  padding: 9px;\n  color: #333333;\n}\n\n.alert {\n  padding: 15px;\n  margin-bottom: 20px;\n  border: 1px solid transparent;\n  border-radius: 4px;\n}\n\n.alert h4 {\n  margin-top: 0;\n  color: inherit;\n}\n\n.alert .alert-link {\n  font-weight: bold;\n}\n\n.alert > p,\n.alert > ul {\n  margin-bottom: 0;\n}\n\n.alert > p + p {\n  margin-top: 5px;\n}\n\n.alert-dismissable {\n  padding-right: 35px;\n}\n\n.alert-dismissable .close {\n  position: relative;\n  top: -2px;\n  right: -21px;\n  color: inherit;\n}\n\n.alert-success {\n  color: #3c763d;\n  background-color: #dff0d8;\n  border-color: #d6e9c6;\n}\n\n.alert-success hr {\n  border-top-color: #c9e2b3;\n}\n\n.alert-success .alert-link {\n  color: #2b542c;\n}\n\n.alert-info {\n  color: #31708f;\n  background-color: #d9edf7;\n  border-color: #bce8f1;\n}\n\n.alert-info hr {\n  border-top-color: #a6e1ec;\n}\n\n.alert-info .alert-link {\n  color: #245269;\n}\n\n.alert-warning {\n  color: #8a6d3b;\n  background-color: #fcf8e3;\n  border-color: #faebcc;\n}\n\n.alert-warning hr {\n  border-top-color: #f7e1b5;\n}\n\n.alert-warning .alert-link {\n  color: #66512c;\n}\n\n.alert-danger {\n  color: #a94442;\n  background-color: #f2dede;\n  border-color: #ebccd1;\n}\n\n.alert-danger hr {\n  border-top-color: #e4b9c0;\n}\n\n.alert-danger .alert-link {\n  color: #843534;\n}\n\n@-webkit-keyframes progress-bar-stripes {\n  from {\n    background-position: 40px 0;\n  }\n  to {\n    background-position: 0 0;\n  }\n}\n\n@keyframes progress-bar-stripes {\n  from {\n    background-position: 40px 0;\n  }\n  to {\n    background-position: 0 0;\n  }\n}\n\n.progress {\n  height: 20px;\n  margin-bottom: 20px;\n  overflow: hidden;\n  background-color: #f5f5f5;\n  border-radius: 4px;\n  -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);\n          box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);\n}\n\n.progress-bar {\n  float: left;\n  width: 0;\n  height: 100%;\n  font-size: 12px;\n  line-height: 20px;\n  color: #ffffff;\n  text-align: center;\n  background-color: #428bca;\n  -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);\n          box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);\n  -webkit-transition: width 0.6s ease;\n          transition: width 0.6s ease;\n}\n\n.progress-striped .progress-bar {\n  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n  background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n  background-size: 40px 40px;\n}\n\n.progress.active .progress-bar {\n  -webkit-animation: progress-bar-stripes 2s linear infinite;\n          animation: progress-bar-stripes 2s linear infinite;\n}\n\n.progress-bar-success {\n  background-color: #5cb85c;\n}\n\n.progress-striped .progress-bar-success {\n  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n  background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n}\n\n.progress-bar-info {\n  background-color: #5bc0de;\n}\n\n.progress-striped .progress-bar-info {\n  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n  background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n}\n\n.progress-bar-warning {\n  background-color: #f0ad4e;\n}\n\n.progress-striped .progress-bar-warning {\n  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n  background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n}\n\n.progress-bar-danger {\n  background-color: #d9534f;\n}\n\n.progress-striped .progress-bar-danger {\n  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n  background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n}\n\n.media,\n.media-body {\n  overflow: hidden;\n  zoom: 1;\n}\n\n.media,\n.media .media {\n  margin-top: 15px;\n}\n\n.media:first-child {\n  margin-top: 0;\n}\n\n.media-object {\n  display: block;\n}\n\n.media-heading {\n  margin: 0 0 5px;\n}\n\n.media > .pull-left {\n  margin-right: 10px;\n}\n\n.media > .pull-right {\n  margin-left: 10px;\n}\n\n.media-list {\n  padding-left: 0;\n  list-style: none;\n}\n\n.list-group {\n  padding-left: 0;\n  margin-bottom: 20px;\n}\n\n.list-group-item {\n  position: relative;\n  display: block;\n  padding: 10px 15px;\n  margin-bottom: -1px;\n  background-color: #ffffff;\n  border: 1px solid #dddddd;\n}\n\n.list-group-item:first-child {\n  border-top-right-radius: 4px;\n  border-top-left-radius: 4px;\n}\n\n.list-group-item:last-child {\n  margin-bottom: 0;\n  border-bottom-right-radius: 4px;\n  border-bottom-left-radius: 4px;\n}\n\n.list-group-item > .badge {\n  float: right;\n}\n\n.list-group-item > .badge + .badge {\n  margin-right: 5px;\n}\n\na.list-group-item {\n  color: #555555;\n}\n\na.list-group-item .list-group-item-heading {\n  color: #333333;\n}\n\na.list-group-item:hover,\na.list-group-item:focus {\n  text-decoration: none;\n  background-color: #f5f5f5;\n}\n\na.list-group-item.active,\na.list-group-item.active:hover,\na.list-group-item.active:focus {\n  z-index: 2;\n  color: #ffffff;\n  background-color: #428bca;\n  border-color: #428bca;\n}\n\na.list-group-item.active .list-group-item-heading,\na.list-group-item.active:hover .list-group-item-heading,\na.list-group-item.active:focus .list-group-item-heading {\n  color: inherit;\n}\n\na.list-group-item.active .list-group-item-text,\na.list-group-item.active:hover .list-group-item-text,\na.list-group-item.active:focus .list-group-item-text {\n  color: #e1edf7;\n}\n\n.list-group-item-heading {\n  margin-top: 0;\n  margin-bottom: 5px;\n}\n\n.list-group-item-text {\n  margin-bottom: 0;\n  line-height: 1.3;\n}\n\n.panel {\n  margin-bottom: 20px;\n  background-color: #ffffff;\n  border: 1px solid transparent;\n  border-radius: 4px;\n  -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);\n          box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);\n}\n\n.panel-body {\n  padding: 15px;\n}\n\n.panel-body:before,\n.panel-body:after {\n  display: table;\n  content: \" \";\n}\n\n.panel-body:after {\n  clear: both;\n}\n\n.panel-body:before,\n.panel-body:after {\n  display: table;\n  content: \" \";\n}\n\n.panel-body:after {\n  clear: both;\n}\n\n.panel > .list-group {\n  margin-bottom: 0;\n}\n\n.panel > .list-group .list-group-item {\n  border-width: 1px 0;\n}\n\n.panel > .list-group .list-group-item:first-child {\n  border-top-right-radius: 0;\n  border-top-left-radius: 0;\n}\n\n.panel > .list-group .list-group-item:last-child {\n  border-bottom: 0;\n}\n\n.panel-heading + .list-group .list-group-item:first-child {\n  border-top-width: 0;\n}\n\n.panel > .table,\n.panel > .table-responsive > .table {\n  margin-bottom: 0;\n}\n\n.panel > .panel-body + .table,\n.panel > .panel-body + .table-responsive {\n  border-top: 1px solid #dddddd;\n}\n\n.panel > .table > tbody:first-child th,\n.panel > .table > tbody:first-child td {\n  border-top: 0;\n}\n\n.panel > .table-bordered,\n.panel > .table-responsive > .table-bordered {\n  border: 0;\n}\n\n.panel > .table-bordered > thead > tr > th:first-child,\n.panel > .table-responsive > .table-bordered > thead > tr > th:first-child,\n.panel > .table-bordered > tbody > tr > th:first-child,\n.panel > .table-responsive > .table-bordered > tbody > tr > th:first-child,\n.panel > .table-bordered > tfoot > tr > th:first-child,\n.panel > .table-responsive > .table-bordered > tfoot > tr > th:first-child,\n.panel > .table-bordered > thead > tr > td:first-child,\n.panel > .table-responsive > .table-bordered > thead > tr > td:first-child,\n.panel > .table-bordered > tbody > tr > td:first-child,\n.panel > .table-responsive > .table-bordered > tbody > tr > td:first-child,\n.panel > .table-bordered > tfoot > tr > td:first-child,\n.panel > .table-responsive > .table-bordered > tfoot > tr > td:first-child {\n  border-left: 0;\n}\n\n.panel > .table-bordered > thead > tr > th:last-child,\n.panel > .table-responsive > .table-bordered > thead > tr > th:last-child,\n.panel > .table-bordered > tbody > tr > th:last-child,\n.panel > .table-responsive > .table-bordered > tbody > tr > th:last-child,\n.panel > .table-bordered > tfoot > tr > th:last-child,\n.panel > .table-responsive > .table-bordered > tfoot > tr > th:last-child,\n.panel > .table-bordered > thead > tr > td:last-child,\n.panel > .table-responsive > .table-bordered > thead > tr > td:last-child,\n.panel > .table-bordered > tbody > tr > td:last-child,\n.panel > .table-responsive > .table-bordered > tbody > tr > td:last-child,\n.panel > .table-bordered > tfoot > tr > td:last-child,\n.panel > .table-responsive > .table-bordered > tfoot > tr > td:last-child {\n  border-right: 0;\n}\n\n.panel > .table-bordered > thead > tr:last-child > th,\n.panel > .table-responsive > .table-bordered > thead > tr:last-child > th,\n.panel > .table-bordered > tbody > tr:last-child > th,\n.panel > .table-responsive > .table-bordered > tbody > tr:last-child > th,\n.panel > .table-bordered > tfoot > tr:last-child > th,\n.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > th,\n.panel > .table-bordered > thead > tr:last-child > td,\n.panel > .table-responsive > .table-bordered > thead > tr:last-child > td,\n.panel > .table-bordered > tbody > tr:last-child > td,\n.panel > .table-responsive > .table-bordered > tbody > tr:last-child > td,\n.panel > .table-bordered > tfoot > tr:last-child > td,\n.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > td {\n  border-bottom: 0;\n}\n\n.panel > .table-responsive {\n  margin-bottom: 0;\n  border: 0;\n}\n\n.panel-heading {\n  padding: 10px 15px;\n  border-bottom: 1px solid transparent;\n  border-top-right-radius: 3px;\n  border-top-left-radius: 3px;\n}\n\n.panel-heading > .dropdown .dropdown-toggle {\n  color: inherit;\n}\n\n.panel-title {\n  margin-top: 0;\n  margin-bottom: 0;\n  font-size: 16px;\n  color: inherit;\n}\n\n.panel-title > a {\n  color: inherit;\n}\n\n.panel-footer {\n  padding: 10px 15px;\n  background-color: #f5f5f5;\n  border-top: 1px solid #dddddd;\n  border-bottom-right-radius: 3px;\n  border-bottom-left-radius: 3px;\n}\n\n.panel-group .panel {\n  margin-bottom: 0;\n  overflow: hidden;\n  border-radius: 4px;\n}\n\n.panel-group .panel + .panel {\n  margin-top: 5px;\n}\n\n.panel-group .panel-heading {\n  border-bottom: 0;\n}\n\n.panel-group .panel-heading + .panel-collapse .panel-body {\n  border-top: 1px solid #dddddd;\n}\n\n.panel-group .panel-footer {\n  border-top: 0;\n}\n\n.panel-group .panel-footer + .panel-collapse .panel-body {\n  border-bottom: 1px solid #dddddd;\n}\n\n.panel-default {\n  border-color: #dddddd;\n}\n\n.panel-default > .panel-heading {\n  color: #333333;\n  background-color: #f5f5f5;\n  border-color: #dddddd;\n}\n\n.panel-default > .panel-heading + .panel-collapse .panel-body {\n  border-top-color: #dddddd;\n}\n\n.panel-default > .panel-footer + .panel-collapse .panel-body {\n  border-bottom-color: #dddddd;\n}\n\n.panel-primary {\n  border-color: #428bca;\n}\n\n.panel-primary > .panel-heading {\n  color: #ffffff;\n  background-color: #428bca;\n  border-color: #428bca;\n}\n\n.panel-primary > .panel-heading + .panel-collapse .panel-body {\n  border-top-color: #428bca;\n}\n\n.panel-primary > .panel-footer + .panel-collapse .panel-body {\n  border-bottom-color: #428bca;\n}\n\n.panel-success {\n  border-color: #d6e9c6;\n}\n\n.panel-success > .panel-heading {\n  color: #3c763d;\n  background-color: #dff0d8;\n  border-color: #d6e9c6;\n}\n\n.panel-success > .panel-heading + .panel-collapse .panel-body {\n  border-top-color: #d6e9c6;\n}\n\n.panel-success > .panel-footer + .panel-collapse .panel-body {\n  border-bottom-color: #d6e9c6;\n}\n\n.panel-warning {\n  border-color: #faebcc;\n}\n\n.panel-warning > .panel-heading {\n  color: #8a6d3b;\n  background-color: #fcf8e3;\n  border-color: #faebcc;\n}\n\n.panel-warning > .panel-heading + .panel-collapse .panel-body {\n  border-top-color: #faebcc;\n}\n\n.panel-warning > .panel-footer + .panel-collapse .panel-body {\n  border-bottom-color: #faebcc;\n}\n\n.panel-danger {\n  border-color: #ebccd1;\n}\n\n.panel-danger > .panel-heading {\n  color: #a94442;\n  background-color: #f2dede;\n  border-color: #ebccd1;\n}\n\n.panel-danger > .panel-heading + .panel-collapse .panel-body {\n  border-top-color: #ebccd1;\n}\n\n.panel-danger > .panel-footer + .panel-collapse .panel-body {\n  border-bottom-color: #ebccd1;\n}\n\n.panel-info {\n  border-color: #bce8f1;\n}\n\n.panel-info > .panel-heading {\n  color: #31708f;\n  background-color: #d9edf7;\n  border-color: #bce8f1;\n}\n\n.panel-info > .panel-heading + .panel-collapse .panel-body {\n  border-top-color: #bce8f1;\n}\n\n.panel-info > .panel-footer + .panel-collapse .panel-body {\n  border-bottom-color: #bce8f1;\n}\n\n.well {\n  min-height: 20px;\n  padding: 19px;\n  margin-bottom: 20px;\n  background-color: #f5f5f5;\n  border: 1px solid #e3e3e3;\n  border-radius: 4px;\n  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);\n          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);\n}\n\n.well blockquote {\n  border-color: #ddd;\n  border-color: rgba(0, 0, 0, 0.15);\n}\n\n.well-lg {\n  padding: 24px;\n  border-radius: 6px;\n}\n\n.well-sm {\n  padding: 9px;\n  border-radius: 3px;\n}\n\n.close {\n  float: right;\n  font-size: 21px;\n  font-weight: bold;\n  line-height: 1;\n  color: #000000;\n  text-shadow: 0 1px 0 #ffffff;\n  opacity: 0.2;\n  filter: alpha(opacity=20);\n}\n\n.close:hover,\n.close:focus {\n  color: #000000;\n  text-decoration: none;\n  cursor: pointer;\n  opacity: 0.5;\n  filter: alpha(opacity=50);\n}\n\nbutton.close {\n  padding: 0;\n  cursor: pointer;\n  background: transparent;\n  border: 0;\n  -webkit-appearance: none;\n}\n\n.modal-open {\n  overflow: hidden;\n}\n\n.modal {\n  position: fixed;\n  top: 0;\n  right: 0;\n  bottom: 0;\n  left: 0;\n  z-index: 1040;\n  display: none;\n  overflow: auto;\n  overflow-y: scroll;\n}\n\n.modal.fade .modal-dialog {\n  -webkit-transform: translate(0, -25%);\n      -ms-transform: translate(0, -25%);\n          transform: translate(0, -25%);\n  -webkit-transition: -webkit-transform 0.3s ease-out;\n     -moz-transition: -moz-transform 0.3s ease-out;\n       -o-transition: -o-transform 0.3s ease-out;\n          transition: transform 0.3s ease-out;\n}\n\n.modal.in .modal-dialog {\n  -webkit-transform: translate(0, 0);\n      -ms-transform: translate(0, 0);\n          transform: translate(0, 0);\n}\n\n.modal-dialog {\n  position: relative;\n  z-index: 1050;\n  width: auto;\n  margin: 10px;\n}\n\n.modal-content {\n  position: relative;\n  background-color: #ffffff;\n  border: 1px solid #999999;\n  border: 1px solid rgba(0, 0, 0, 0.2);\n  border-radius: 6px;\n  outline: none;\n  -webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);\n          box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);\n  background-clip: padding-box;\n}\n\n.modal-backdrop {\n  position: fixed;\n  top: 0;\n  right: 0;\n  bottom: 0;\n  left: 0;\n  z-index: 1030;\n  background-color: #000000;\n}\n\n.modal-backdrop.fade {\n  opacity: 0;\n  filter: alpha(opacity=0);\n}\n\n.modal-backdrop.in {\n  opacity: 0.5;\n  filter: alpha(opacity=50);\n}\n\n.modal-header {\n  min-height: 16.428571429px;\n  padding: 15px;\n  border-bottom: 1px solid #e5e5e5;\n}\n\n.modal-header .close {\n  margin-top: -2px;\n}\n\n.modal-title {\n  margin: 0;\n  line-height: 1.428571429;\n}\n\n.modal-body {\n  position: relative;\n  padding: 20px;\n}\n\n.modal-footer {\n  padding: 19px 20px 20px;\n  margin-top: 15px;\n  text-align: right;\n  border-top: 1px solid #e5e5e5;\n}\n\n.modal-footer:before,\n.modal-footer:after {\n  display: table;\n  content: \" \";\n}\n\n.modal-footer:after {\n  clear: both;\n}\n\n.modal-footer:before,\n.modal-footer:after {\n  display: table;\n  content: \" \";\n}\n\n.modal-footer:after {\n  clear: both;\n}\n\n.modal-footer .btn + .btn {\n  margin-bottom: 0;\n  margin-left: 5px;\n}\n\n.modal-footer .btn-group .btn + .btn {\n  margin-left: -1px;\n}\n\n.modal-footer .btn-block + .btn-block {\n  margin-left: 0;\n}\n\n@media screen and (min-width: 768px) {\n  .modal-dialog {\n    width: 600px;\n    margin: 30px auto;\n  }\n  .modal-content {\n    -webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);\n            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);\n  }\n}\n\n.tooltip {\n  position: absolute;\n  z-index: 1030;\n  display: block;\n  font-size: 12px;\n  line-height: 1.4;\n  opacity: 0;\n  filter: alpha(opacity=0);\n  visibility: visible;\n}\n\n.tooltip.in {\n  opacity: 0.9;\n  filter: alpha(opacity=90);\n}\n\n.tooltip.top {\n  padding: 5px 0;\n  margin-top: -3px;\n}\n\n.tooltip.right {\n  padding: 0 5px;\n  margin-left: 3px;\n}\n\n.tooltip.bottom {\n  padding: 5px 0;\n  margin-top: 3px;\n}\n\n.tooltip.left {\n  padding: 0 5px;\n  margin-left: -3px;\n}\n\n.tooltip-inner {\n  max-width: 200px;\n  padding: 3px 8px;\n  color: #ffffff;\n  text-align: center;\n  text-decoration: none;\n  background-color: #000000;\n  border-radius: 4px;\n}\n\n.tooltip-arrow {\n  position: absolute;\n  width: 0;\n  height: 0;\n  border-color: transparent;\n  border-style: solid;\n}\n\n.tooltip.top .tooltip-arrow {\n  bottom: 0;\n  left: 50%;\n  margin-left: -5px;\n  border-top-color: #000000;\n  border-width: 5px 5px 0;\n}\n\n.tooltip.top-left .tooltip-arrow {\n  bottom: 0;\n  left: 5px;\n  border-top-color: #000000;\n  border-width: 5px 5px 0;\n}\n\n.tooltip.top-right .tooltip-arrow {\n  right: 5px;\n  bottom: 0;\n  border-top-color: #000000;\n  border-width: 5px 5px 0;\n}\n\n.tooltip.right .tooltip-arrow {\n  top: 50%;\n  left: 0;\n  margin-top: -5px;\n  border-right-color: #000000;\n  border-width: 5px 5px 5px 0;\n}\n\n.tooltip.left .tooltip-arrow {\n  top: 50%;\n  right: 0;\n  margin-top: -5px;\n  border-left-color: #000000;\n  border-width: 5px 0 5px 5px;\n}\n\n.tooltip.bottom .tooltip-arrow {\n  top: 0;\n  left: 50%;\n  margin-left: -5px;\n  border-bottom-color: #000000;\n  border-width: 0 5px 5px;\n}\n\n.tooltip.bottom-left .tooltip-arrow {\n  top: 0;\n  left: 5px;\n  border-bottom-color: #000000;\n  border-width: 0 5px 5px;\n}\n\n.tooltip.bottom-right .tooltip-arrow {\n  top: 0;\n  right: 5px;\n  border-bottom-color: #000000;\n  border-width: 0 5px 5px;\n}\n\n.popover {\n  position: absolute;\n  top: 0;\n  left: 0;\n  z-index: 1010;\n  display: none;\n  max-width: 276px;\n  padding: 1px;\n  text-align: left;\n  white-space: normal;\n  background-color: #ffffff;\n  border: 1px solid #cccccc;\n  border: 1px solid rgba(0, 0, 0, 0.2);\n  border-radius: 6px;\n  -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);\n          box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);\n  background-clip: padding-box;\n}\n\n.popover.top {\n  margin-top: -10px;\n}\n\n.popover.right {\n  margin-left: 10px;\n}\n\n.popover.bottom {\n  margin-top: 10px;\n}\n\n.popover.left {\n  margin-left: -10px;\n}\n\n.popover-title {\n  padding: 8px 14px;\n  margin: 0;\n  font-size: 14px;\n  font-weight: normal;\n  line-height: 18px;\n  background-color: #f7f7f7;\n  border-bottom: 1px solid #ebebeb;\n  border-radius: 5px 5px 0 0;\n}\n\n.popover-content {\n  padding: 9px 14px;\n}\n\n.popover .arrow,\n.popover .arrow:after {\n  position: absolute;\n  display: block;\n  width: 0;\n  height: 0;\n  border-color: transparent;\n  border-style: solid;\n}\n\n.popover .arrow {\n  border-width: 11px;\n}\n\n.popover .arrow:after {\n  border-width: 10px;\n  content: \"\";\n}\n\n.popover.top .arrow {\n  bottom: -11px;\n  left: 50%;\n  margin-left: -11px;\n  border-top-color: #999999;\n  border-top-color: rgba(0, 0, 0, 0.25);\n  border-bottom-width: 0;\n}\n\n.popover.top .arrow:after {\n  bottom: 1px;\n  margin-left: -10px;\n  border-top-color: #ffffff;\n  border-bottom-width: 0;\n  content: \" \";\n}\n\n.popover.right .arrow {\n  top: 50%;\n  left: -11px;\n  margin-top: -11px;\n  border-right-color: #999999;\n  border-right-color: rgba(0, 0, 0, 0.25);\n  border-left-width: 0;\n}\n\n.popover.right .arrow:after {\n  bottom: -10px;\n  left: 1px;\n  border-right-color: #ffffff;\n  border-left-width: 0;\n  content: \" \";\n}\n\n.popover.bottom .arrow {\n  top: -11px;\n  left: 50%;\n  margin-left: -11px;\n  border-bottom-color: #999999;\n  border-bottom-color: rgba(0, 0, 0, 0.25);\n  border-top-width: 0;\n}\n\n.popover.bottom .arrow:after {\n  top: 1px;\n  margin-left: -10px;\n  border-bottom-color: #ffffff;\n  border-top-width: 0;\n  content: \" \";\n}\n\n.popover.left .arrow {\n  top: 50%;\n  right: -11px;\n  margin-top: -11px;\n  border-left-color: #999999;\n  border-left-color: rgba(0, 0, 0, 0.25);\n  border-right-width: 0;\n}\n\n.popover.left .arrow:after {\n  right: 1px;\n  bottom: -10px;\n  border-left-color: #ffffff;\n  border-right-width: 0;\n  content: \" \";\n}\n\n.carousel {\n  position: relative;\n}\n\n.carousel-inner {\n  position: relative;\n  width: 100%;\n  overflow: hidden;\n}\n\n.carousel-inner > .item {\n  position: relative;\n  display: none;\n  -webkit-transition: 0.6s ease-in-out left;\n          transition: 0.6s ease-in-out left;\n}\n\n.carousel-inner > .item > img,\n.carousel-inner > .item > a > img {\n  display: block;\n  height: auto;\n  max-width: 100%;\n  line-height: 1;\n}\n\n.carousel-inner > .active,\n.carousel-inner > .next,\n.carousel-inner > .prev {\n  display: block;\n}\n\n.carousel-inner > .active {\n  left: 0;\n}\n\n.carousel-inner > .next,\n.carousel-inner > .prev {\n  position: absolute;\n  top: 0;\n  width: 100%;\n}\n\n.carousel-inner > .next {\n  left: 100%;\n}\n\n.carousel-inner > .prev {\n  left: -100%;\n}\n\n.carousel-inner > .next.left,\n.carousel-inner > .prev.right {\n  left: 0;\n}\n\n.carousel-inner > .active.left {\n  left: -100%;\n}\n\n.carousel-inner > .active.right {\n  left: 100%;\n}\n\n.carousel-control {\n  position: absolute;\n  top: 0;\n  bottom: 0;\n  left: 0;\n  width: 15%;\n  font-size: 20px;\n  color: #ffffff;\n  text-align: center;\n  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);\n  opacity: 0.5;\n  filter: alpha(opacity=50);\n}\n\n.carousel-control.left {\n  background-image: -webkit-linear-gradient(left, color-stop(rgba(0, 0, 0, 0.5) 0), color-stop(rgba(0, 0, 0, 0.0001) 100%));\n  background-image: linear-gradient(to right, rgba(0, 0, 0, 0.5) 0, rgba(0, 0, 0, 0.0001) 100%);\n  background-repeat: repeat-x;\n  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);\n}\n\n.carousel-control.right {\n  right: 0;\n  left: auto;\n  background-image: -webkit-linear-gradient(left, color-stop(rgba(0, 0, 0, 0.0001) 0), color-stop(rgba(0, 0, 0, 0.5) 100%));\n  background-image: linear-gradient(to right, rgba(0, 0, 0, 0.0001) 0, rgba(0, 0, 0, 0.5) 100%);\n  background-repeat: repeat-x;\n  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);\n}\n\n.carousel-control:hover,\n.carousel-control:focus {\n  color: #ffffff;\n  text-decoration: none;\n  outline: none;\n  opacity: 0.9;\n  filter: alpha(opacity=90);\n}\n\n.carousel-control .icon-prev,\n.carousel-control .icon-next,\n.carousel-control .glyphicon-chevron-left,\n.carousel-control .glyphicon-chevron-right {\n  position: absolute;\n  top: 50%;\n  z-index: 5;\n  display: inline-block;\n}\n\n.carousel-control .icon-prev,\n.carousel-control .glyphicon-chevron-left {\n  left: 50%;\n}\n\n.carousel-control .icon-next,\n.carousel-control .glyphicon-chevron-right {\n  right: 50%;\n}\n\n.carousel-control .icon-prev,\n.carousel-control .icon-next {\n  width: 20px;\n  height: 20px;\n  margin-top: -10px;\n  margin-left: -10px;\n  font-family: serif;\n}\n\n.carousel-control .icon-prev:before {\n  content: '\\2039';\n}\n\n.carousel-control .icon-next:before {\n  content: '\\203a';\n}\n\n.carousel-indicators {\n  position: absolute;\n  bottom: 10px;\n  left: 50%;\n  z-index: 15;\n  width: 60%;\n  padding-left: 0;\n  margin-left: -30%;\n  text-align: center;\n  list-style: none;\n}\n\n.carousel-indicators li {\n  display: inline-block;\n  width: 10px;\n  height: 10px;\n  margin: 1px;\n  text-indent: -999px;\n  cursor: pointer;\n  background-color: #000 \\9;\n  background-color: rgba(0, 0, 0, 0);\n  border: 1px solid #ffffff;\n  border-radius: 10px;\n}\n\n.carousel-indicators .active {\n  width: 12px;\n  height: 12px;\n  margin: 0;\n  background-color: #ffffff;\n}\n\n.carousel-caption {\n  position: absolute;\n  right: 15%;\n  bottom: 20px;\n  left: 15%;\n  z-index: 10;\n  padding-top: 20px;\n  padding-bottom: 20px;\n  color: #ffffff;\n  text-align: center;\n  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);\n}\n\n.carousel-caption .btn {\n  text-shadow: none;\n}\n\n@media screen and (min-width: 768px) {\n  .carousel-control .glyphicons-chevron-left,\n  .carousel-control .glyphicons-chevron-right,\n  .carousel-control .icon-prev,\n  .carousel-control .icon-next {\n    width: 30px;\n    height: 30px;\n    margin-top: -15px;\n    margin-left: -15px;\n    font-size: 30px;\n  }\n  .carousel-caption {\n    right: 20%;\n    left: 20%;\n    padding-bottom: 30px;\n  }\n  .carousel-indicators {\n    bottom: 20px;\n  }\n}\n\n.clearfix:before,\n.clearfix:after {\n  display: table;\n  content: \" \";\n}\n\n.clearfix:after {\n  clear: both;\n}\n\n.center-block {\n  display: block;\n  margin-right: auto;\n  margin-left: auto;\n}\n\n.pull-right {\n  float: right !important;\n}\n\n.pull-left {\n  float: left !important;\n}\n\n.hide {\n  display: none !important;\n}\n\n.show {\n  display: block !important;\n}\n\n.invisible {\n  visibility: hidden;\n}\n\n.text-hide {\n  font: 0/0 a;\n  color: transparent;\n  text-shadow: none;\n  background-color: transparent;\n  border: 0;\n}\n\n.hidden {\n  display: none !important;\n  visibility: hidden !important;\n}\n\n.affix {\n  position: fixed;\n}\n\n@-ms-viewport {\n  width: device-width;\n}\n\n.visible-xs,\ntr.visible-xs,\nth.visible-xs,\ntd.visible-xs {\n  display: none !important;\n}\n\n@media (max-width: 767px) {\n  .visible-xs {\n    display: block !important;\n  }\n  table.visible-xs {\n    display: table;\n  }\n  tr.visible-xs {\n    display: table-row !important;\n  }\n  th.visible-xs,\n  td.visible-xs {\n    display: table-cell !important;\n  }\n}\n\n@media (min-width: 768px) and (max-width: 991px) {\n  .visible-xs.visible-sm {\n    display: block !important;\n  }\n  table.visible-xs.visible-sm {\n    display: table;\n  }\n  tr.visible-xs.visible-sm {\n    display: table-row !important;\n  }\n  th.visible-xs.visible-sm,\n  td.visible-xs.visible-sm {\n    display: table-cell !important;\n  }\n}\n\n@media (min-width: 992px) and (max-width: 1199px) {\n  .visible-xs.visible-md {\n    display: block !important;\n  }\n  table.visible-xs.visible-md {\n    display: table;\n  }\n  tr.visible-xs.visible-md {\n    display: table-row !important;\n  }\n  th.visible-xs.visible-md,\n  td.visible-xs.visible-md {\n    display: table-cell !important;\n  }\n}\n\n@media (min-width: 1200px) {\n  .visible-xs.visible-lg {\n    display: block !important;\n  }\n  table.visible-xs.visible-lg {\n    display: table;\n  }\n  tr.visible-xs.visible-lg {\n    display: table-row !important;\n  }\n  th.visible-xs.visible-lg,\n  td.visible-xs.visible-lg {\n    display: table-cell !important;\n  }\n}\n\n.visible-sm,\ntr.visible-sm,\nth.visible-sm,\ntd.visible-sm {\n  display: none !important;\n}\n\n@media (max-width: 767px) {\n  .visible-sm.visible-xs {\n    display: block !important;\n  }\n  table.visible-sm.visible-xs {\n    display: table;\n  }\n  tr.visible-sm.visible-xs {\n    display: table-row !important;\n  }\n  th.visible-sm.visible-xs,\n  td.visible-sm.visible-xs {\n    display: table-cell !important;\n  }\n}\n\n@media (min-width: 768px) and (max-width: 991px) {\n  .visible-sm {\n    display: block !important;\n  }\n  table.visible-sm {\n    display: table;\n  }\n  tr.visible-sm {\n    display: table-row !important;\n  }\n  th.visible-sm,\n  td.visible-sm {\n    display: table-cell !important;\n  }\n}\n\n@media (min-width: 992px) and (max-width: 1199px) {\n  .visible-sm.visible-md {\n    display: block !important;\n  }\n  table.visible-sm.visible-md {\n    display: table;\n  }\n  tr.visible-sm.visible-md {\n    display: table-row !important;\n  }\n  th.visible-sm.visible-md,\n  td.visible-sm.visible-md {\n    display: table-cell !important;\n  }\n}\n\n@media (min-width: 1200px) {\n  .visible-sm.visible-lg {\n    display: block !important;\n  }\n  table.visible-sm.visible-lg {\n    display: table;\n  }\n  tr.visible-sm.visible-lg {\n    display: table-row !important;\n  }\n  th.visible-sm.visible-lg,\n  td.visible-sm.visible-lg {\n    display: table-cell !important;\n  }\n}\n\n.visible-md,\ntr.visible-md,\nth.visible-md,\ntd.visible-md {\n  display: none !important;\n}\n\n@media (max-width: 767px) {\n  .visible-md.visible-xs {\n    display: block !important;\n  }\n  table.visible-md.visible-xs {\n    display: table;\n  }\n  tr.visible-md.visible-xs {\n    display: table-row !important;\n  }\n  th.visible-md.visible-xs,\n  td.visible-md.visible-xs {\n    display: table-cell !important;\n  }\n}\n\n@media (min-width: 768px) and (max-width: 991px) {\n  .visible-md.visible-sm {\n    display: block !important;\n  }\n  table.visible-md.visible-sm {\n    display: table;\n  }\n  tr.visible-md.visible-sm {\n    display: table-row !important;\n  }\n  th.visible-md.visible-sm,\n  td.visible-md.visible-sm {\n    display: table-cell !important;\n  }\n}\n\n@media (min-width: 992px) and (max-width: 1199px) {\n  .visible-md {\n    display: block !important;\n  }\n  table.visible-md {\n    display: table;\n  }\n  tr.visible-md {\n    display: table-row !important;\n  }\n  th.visible-md,\n  td.visible-md {\n    display: table-cell !important;\n  }\n}\n\n@media (min-width: 1200px) {\n  .visible-md.visible-lg {\n    display: block !important;\n  }\n  table.visible-md.visible-lg {\n    display: table;\n  }\n  tr.visible-md.visible-lg {\n    display: table-row !important;\n  }\n  th.visible-md.visible-lg,\n  td.visible-md.visible-lg {\n    display: table-cell !important;\n  }\n}\n\n.visible-lg,\ntr.visible-lg,\nth.visible-lg,\ntd.visible-lg {\n  display: none !important;\n}\n\n@media (max-width: 767px) {\n  .visible-lg.visible-xs {\n    display: block !important;\n  }\n  table.visible-lg.visible-xs {\n    display: table;\n  }\n  tr.visible-lg.visible-xs {\n    display: table-row !important;\n  }\n  th.visible-lg.visible-xs,\n  td.visible-lg.visible-xs {\n    display: table-cell !important;\n  }\n}\n\n@media (min-width: 768px) and (max-width: 991px) {\n  .visible-lg.visible-sm {\n    display: block !important;\n  }\n  table.visible-lg.visible-sm {\n    display: table;\n  }\n  tr.visible-lg.visible-sm {\n    display: table-row !important;\n  }\n  th.visible-lg.visible-sm,\n  td.visible-lg.visible-sm {\n    display: table-cell !important;\n  }\n}\n\n@media (min-width: 992px) and (max-width: 1199px) {\n  .visible-lg.visible-md {\n    display: block !important;\n  }\n  table.visible-lg.visible-md {\n    display: table;\n  }\n  tr.visible-lg.visible-md {\n    display: table-row !important;\n  }\n  th.visible-lg.visible-md,\n  td.visible-lg.visible-md {\n    display: table-cell !important;\n  }\n}\n\n@media (min-width: 1200px) {\n  .visible-lg {\n    display: block !important;\n  }\n  table.visible-lg {\n    display: table;\n  }\n  tr.visible-lg {\n    display: table-row !important;\n  }\n  th.visible-lg,\n  td.visible-lg {\n    display: table-cell !important;\n  }\n}\n\n.hidden-xs {\n  display: block !important;\n}\n\ntable.hidden-xs {\n  display: table;\n}\n\ntr.hidden-xs {\n  display: table-row !important;\n}\n\nth.hidden-xs,\ntd.hidden-xs {\n  display: table-cell !important;\n}\n\n@media (max-width: 767px) {\n  .hidden-xs,\n  tr.hidden-xs,\n  th.hidden-xs,\n  td.hidden-xs {\n    display: none !important;\n  }\n}\n\n@media (min-width: 768px) and (max-width: 991px) {\n  .hidden-xs.hidden-sm,\n  tr.hidden-xs.hidden-sm,\n  th.hidden-xs.hidden-sm,\n  td.hidden-xs.hidden-sm {\n    display: none !important;\n  }\n}\n\n@media (min-width: 992px) and (max-width: 1199px) {\n  .hidden-xs.hidden-md,\n  tr.hidden-xs.hidden-md,\n  th.hidden-xs.hidden-md,\n  td.hidden-xs.hidden-md {\n    display: none !important;\n  }\n}\n\n@media (min-width: 1200px) {\n  .hidden-xs.hidden-lg,\n  tr.hidden-xs.hidden-lg,\n  th.hidden-xs.hidden-lg,\n  td.hidden-xs.hidden-lg {\n    display: none !important;\n  }\n}\n\n.hidden-sm {\n  display: block !important;\n}\n\ntable.hidden-sm {\n  display: table;\n}\n\ntr.hidden-sm {\n  display: table-row !important;\n}\n\nth.hidden-sm,\ntd.hidden-sm {\n  display: table-cell !important;\n}\n\n@media (max-width: 767px) {\n  .hidden-sm.hidden-xs,\n  tr.hidden-sm.hidden-xs,\n  th.hidden-sm.hidden-xs,\n  td.hidden-sm.hidden-xs {\n    display: none !important;\n  }\n}\n\n@media (min-width: 768px) and (max-width: 991px) {\n  .hidden-sm,\n  tr.hidden-sm,\n  th.hidden-sm,\n  td.hidden-sm {\n    display: none !important;\n  }\n}\n\n@media (min-width: 992px) and (max-width: 1199px) {\n  .hidden-sm.hidden-md,\n  tr.hidden-sm.hidden-md,\n  th.hidden-sm.hidden-md,\n  td.hidden-sm.hidden-md {\n    display: none !important;\n  }\n}\n\n@media (min-width: 1200px) {\n  .hidden-sm.hidden-lg,\n  tr.hidden-sm.hidden-lg,\n  th.hidden-sm.hidden-lg,\n  td.hidden-sm.hidden-lg {\n    display: none !important;\n  }\n}\n\n.hidden-md {\n  display: block !important;\n}\n\ntable.hidden-md {\n  display: table;\n}\n\ntr.hidden-md {\n  display: table-row !important;\n}\n\nth.hidden-md,\ntd.hidden-md {\n  display: table-cell !important;\n}\n\n@media (max-width: 767px) {\n  .hidden-md.hidden-xs,\n  tr.hidden-md.hidden-xs,\n  th.hidden-md.hidden-xs,\n  td.hidden-md.hidden-xs {\n    display: none !important;\n  }\n}\n\n@media (min-width: 768px) and (max-width: 991px) {\n  .hidden-md.hidden-sm,\n  tr.hidden-md.hidden-sm,\n  th.hidden-md.hidden-sm,\n  td.hidden-md.hidden-sm {\n    display: none !important;\n  }\n}\n\n@media (min-width: 992px) and (max-width: 1199px) {\n  .hidden-md,\n  tr.hidden-md,\n  th.hidden-md,\n  td.hidden-md {\n    display: none !important;\n  }\n}\n\n@media (min-width: 1200px) {\n  .hidden-md.hidden-lg,\n  tr.hidden-md.hidden-lg,\n  th.hidden-md.hidden-lg,\n  td.hidden-md.hidden-lg {\n    display: none !important;\n  }\n}\n\n.hidden-lg {\n  display: block !important;\n}\n\ntable.hidden-lg {\n  display: table;\n}\n\ntr.hidden-lg {\n  display: table-row !important;\n}\n\nth.hidden-lg,\ntd.hidden-lg {\n  display: table-cell !important;\n}\n\n@media (max-width: 767px) {\n  .hidden-lg.hidden-xs,\n  tr.hidden-lg.hidden-xs,\n  th.hidden-lg.hidden-xs,\n  td.hidden-lg.hidden-xs {\n    display: none !important;\n  }\n}\n\n@media (min-width: 768px) and (max-width: 991px) {\n  .hidden-lg.hidden-sm,\n  tr.hidden-lg.hidden-sm,\n  th.hidden-lg.hidden-sm,\n  td.hidden-lg.hidden-sm {\n    display: none !important;\n  }\n}\n\n@media (min-width: 992px) and (max-width: 1199px) {\n  .hidden-lg.hidden-md,\n  tr.hidden-lg.hidden-md,\n  th.hidden-lg.hidden-md,\n  td.hidden-lg.hidden-md {\n    display: none !important;\n  }\n}\n\n@media (min-width: 1200px) {\n  .hidden-lg,\n  tr.hidden-lg,\n  th.hidden-lg,\n  td.hidden-lg {\n    display: none !important;\n  }\n}\n\n.visible-print,\ntr.visible-print,\nth.visible-print,\ntd.visible-print {\n  display: none !important;\n}\n\n@media print {\n  .visible-print {\n    display: block !important;\n  }\n  table.visible-print {\n    display: table;\n  }\n  tr.visible-print {\n    display: table-row !important;\n  }\n  th.visible-print,\n  td.visible-print {\n    display: table-cell !important;\n  }\n  .hidden-print,\n  tr.hidden-print,\n  th.hidden-print,\n  td.hidden-print {\n    display: none !important;\n  }\n}\n</style>\n\n\n\n## Last Time\n\n### [Notebook Link: 11_PlotTypes.ipynb](./11_PlotTypes.ipynb)\n\n- plot types in Matplotlib\n- graphical solutions of transcendental equations\n\n## Today\n\n- Radioactive Decay\n- **Reading:** G&N Chapter 1\n\n\n## Setting up the Notebook\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n%matplotlib inline\nplt.style.use('../include/notebook.mplstyle');\n%config InlineBackend.figure_format = 'svg'\ncolors = plt.rcParams['axes.prop_cycle'].by_key()['color']\n```\n\n## Radioactive Decay\n\nWe want to analyze the radioactive decay of some sample where there are $N(t)$ atoms at some time $t$.  The behavior of $N(t)$ is governed by the differential equation:\n\n\\begin{equation}\n\\frac{dN}{dt} = -\\frac{N}{\\tau}\n\\tag{1}\n\\end{equation}\n\nwhere $\\tau$ is the time constant of the decay.  The solution to this first order differential equation can be found by separation and integration:\n\n\\begin{align}\n\\int_{N(0)}^{N(t)} \\frac{dN}{N} &= - \\int_0^t \\frac{dt}{\\tau} \\\\\n\\log\\frac{N(t)}{N(0)} &= -\\frac{t}{\\tau} \\\\\nN(t) &= N(0) \\mathrm{e}^{-t/\\tau}\n\\end{align}\n\n### Plot $N(t)/N(0)$ vs. $t/\\tau$\n\n\n```python\nt = np.arange(0,5,0.1)\nplt.plot(t,np.exp(-t))\nplt.ylabel(r'$N(t)/N_0$')\nplt.xlabel(r'$t/\\tau$')\n```\n\n\n\n\n    Text(0.5, 0, '$t/\\\\tau$')\n\n\n\n\n    \n\n    \n\n\n## A Numerical Approach\n\n### Question: How do we approximate the ODE on a discrete set of grid points?\n\n### Taylor Expansions\n\n\\begin{equation}\nf(t+\\Delta t) = f(t) + \\frac{df}{dt}\\Delta t + \\frac{1}{2} \\frac{d^2 f}{dt^2} \\Delta t^2 + \\mathrm{O}\\left(\\Delta t^3\\right)\n\\end{equation}\n\nif $\\Delta t \\ll 1$ we can rearrange to get the discrete **forward derivative**:\n\n\\begin{equation}\n\\frac{df(t)}{dt} = \\frac{f(t+\\Delta t) - f(t)}{\\Delta t} + \\mathrm{O}\\left(\\Delta t\\right) .\n\\end{equation}\n\n### Application to the Radioactive Decay Problem\n\nWe have:\n\\begin{align}\n\\frac{dN(t)}{dt} & = -\\frac{N}{\\tau} \\\\\n\\Rightarrow \\frac{N(t+\\Delta t) - N(t)}{\\Delta t} &= -\\frac{N(t)}{\\tau} + \\mathrm{O}\\left(\\Delta t\\right) \\\\\nN(t+\\Delta t) &\\approx \\left(1-\\frac{\\Delta t}{\\tau}\\right)N(t)\n\\end{align}\n \n\nIf we define an array $t/\\tau = n \\Delta t$ where $n \\in \\mathbb{Z}$ is an integer then this is a simple iterative initial value problem.  The **accuracy** of the numerical solution depends on the size of $\\Delta t$.  This approach using the lowest order approximation to the derivitive is called the [Euler's Method](https://en.wikipedia.org/wiki/Euler_method).\n\n<div class=\"span alert alert-success\">\n<h2> Team Programming challenge </h2>\nWrite a program that employs the Euler Method to solve the radioactive decay problem and compare with the exact solution.\n</div>\n\n\n\n```python\n# Initialization\ntmin,tmax,\u0394t = 0.0,5.0,0.2\n\nt = np.arange(tmin,tmax,\u0394t)\nN = np.ones_like(t)\n\n# Perform the numerical solution of the ODE\nfor ti in range(len(N)-1):\n    # fill in code here\n    N[ti+1] = N[ti]*(1-\u0394t)\n\n# Plot the numerical result, make sure you include the time step in the legend\n# By convention, as we only know the approximate solution at discrete time steps\n# we use open symbols\nplt.plot(t,N,'o', mfc='None')\n\n# Plot the exact result\n# As we can evaluate it as a function, we use a line\nplt.plot(t,np.exp(-t))\nplt.xlabel(r'$t/\\tau$')\nplt.ylabel(r'$N(t)/N(0)$')\n\nplt.legend()\n```\n\n    No handles with labels found to put in legend.\n\n\n\n\n\n    <matplotlib.legend.Legend at 0x11ab8a390>\n\n\n\n\n    \n\n    \n\n\n\n```python\n%run ./examples/Simple_ODEs/radioactive_decay.py\n```\n\n\n```python\n%load ./examples/Simple_ODEs/radioactive_decay.py\n```\n", "meta": {"hexsha": "be1a577e1d5f40aa7d44c6da5851652febed6542", "size": 272029, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "4-assets/BOOKS/Jupyter-Notebooks/Overflow/12_RadioactiveDecay.ipynb", "max_stars_repo_name": "impastasyndrome/Lambda-Resource-Static-Assets", "max_stars_repo_head_hexsha": "7070672038620d29844991250f2476d0f1a60b0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4-assets/BOOKS/Jupyter-Notebooks/Overflow/12_RadioactiveDecay.ipynb", "max_issues_repo_name": "impastasyndrome/Lambda-Resource-Static-Assets", "max_issues_repo_head_hexsha": "7070672038620d29844991250f2476d0f1a60b0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4-assets/BOOKS/Jupyter-Notebooks/Overflow/12_RadioactiveDecay.ipynb", "max_forks_repo_name": "impastasyndrome/Lambda-Resource-Static-Assets", "max_forks_repo_head_hexsha": "7070672038620d29844991250f2476d0f1a60b0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-05T07:48:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T07:48:26.000Z", "avg_line_length": 31.2497415279, "max_line_length": 373, "alphanum_fraction": 0.4253921457, "converted": true, "num_tokens": 39165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.074770045485098, "lm_q1q2_score": 0.02348157353365726}}
{"text": "<a href=\"https://colab.research.google.com/github/jakobbb/cif2robotex/blob/master/cif2robotex.ipynb\" target=\"_parent\"></a>\n\n# cif2robotex\n\nThis jupyter notebook can be used to obtain publication ready latex tables from cif files. Furthermore in the future this notebook can also use [robocrys](https://github.com/hackingmaterials/robocrystallographer) to return a first description of the structure.\n\n\n\n\n```\n!git clone https://github.com/openbabel/openbabel --depth 1 && cd openbabel\n!mkdir build && cd build\n!cmake ../openbabel -DPYTHON_BINDINGS=ON\n!make && make install\n!pip install pymatgen\n\n```\n\n    Requirement already satisfied: pymatgen in /usr/local/lib/python3.6/dist-packages (2020.7.14)\n    Requirement already satisfied: scipy>=1.5.0 in /usr/local/lib/python3.6/dist-packages (from pymatgen) (1.5.1)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.6/dist-packages (from pymatgen) (0.8.7)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from pymatgen) (1.0.5)\n    Requirement already satisfied: plotly>=4.5.0 in /usr/local/lib/python3.6/dist-packages (from pymatgen) (4.8.2)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.6/dist-packages (from pymatgen) (1.1.1)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from pymatgen) (3.0.4)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.6/dist-packages (from pymatgen) (2.4)\n    Requirement already satisfied: numpy>=1.14.3 in /usr/local/lib/python3.6/dist-packages (from pymatgen) (1.18.5)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.6/dist-packages (from pymatgen) (3.3.0)\n    Requirement already satisfied: dataclasses>=0.6; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from pymatgen) (0.7)\n    Requirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from pymatgen) (2.23.0)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.6/dist-packages (from pymatgen) (1.15.1)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.6/dist-packages (from pymatgen) (0.16.10)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.6/dist-packages (from pymatgen) (3.2.2)\n    Requirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas->pymatgen) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas->pymatgen) (2018.9)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from plotly>=4.5.0->pymatgen) (1.12.0)\n    Requirement already satisfied: retrying>=1.3.3 in /usr/local/lib/python3.6/dist-packages (from plotly>=4.5.0->pymatgen) (1.3.3)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy->pymatgen) (1.1.0)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx>=2.2->pymatgen) (4.4.2)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->pymatgen) (2020.6.20)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->pymatgen) (2.10)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->pymatgen) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->pymatgen) (3.0.4)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.9\" in /usr/local/lib/python3.6/dist-packages (from ruamel.yaml>=0.15.6->pymatgen) (0.2.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=1.5->pymatgen) (1.2.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=1.5->pymatgen) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=1.5->pymatgen) (0.10.0)\n\n\n\n```\nfrom pymatgen.io.cif import CifParser\nfrom pymatgen import Structure\n```\n\nThe following function *cif_import* imports the cif file and returns it as a structure file which can later be used to acces the informations of the cif file.\n\n\n\n\n\n```\ndef cif_import(filename):\n  parser = CifParser(filename + \".cif\")\n  structure = parser.as_dict()\n  structure = structure[list(structure.keys())[0]]\n  return structure\n# To import the cif just call the function with the filenmae without extension\n#structure = cif_import(\"BLJ223_DABCO_SB_Cu_Br\")\n#print(structure[\"_diffrn_radiation_type\"][:-2])\n```\n\n# Cif Table\n\nWrite .tex file with information from cif file.\nAdd items here using keys of dictionary from cif file.\nThe output will be a latex table\n\n\n\n\n\n\n```\ndef ciftable_tex(filename, structure):\n  # Open the file with writing permission\n  with open(filename +\".tex\", \"w\") as myfile:\n\n    # Write a line to the file\n    myfile.write(\"\\\\begin{table} \\n \\\\caption{Crystallographic data for compound}\\n \\\\label{tab:cryst_data} \\n\")\n    myfile.write(\"\\\\begin{tabular}{@{}ll@{}} \\n\")\n    myfile.write(\"\\\\toprule\\n\"+ structure[\"_chemical_formula_sum\"] +\"& \\\\ce{} \\\\\\ \\\\midrule \\n\")\n    myfile.write(\"Formula weight & \"+ structure[\"_chemical_formula_weight\"] +\"    \\\\\\ \\n\")\n    myfile.write(\"Temperature/K & \"+ structure[\"_cell_measurement_temperature\"] +\"  \\\\\\ \\n\")\n    myfile.write(\"Crystal system  & \"+ structure[\"_space_group_crystal_system\"]     +\"                           \\\\\\ \\n\")\n    myfile.write(\"Space group & \"+ structure[\"_space_group_name_H-M_alt\"].replace(\" \", \"\")+ \"  \\\\\\ \\n\")\n    myfile.write(\"a/\\\\AA\\\\ & \"+ structure[\"_cell_length_a\"] +\" \\\\\\ \\n\")\n    myfile.write(\"b/\\\\AA\\\\ & \"+ structure[\"_cell_length_b\"] +\"  \\\\\\ \\n\")\n    myfile.write(\"c/\\\\AA\\\\ & \"+ structure[\"_cell_length_c\"] +\" \\\\\\ \\n\")\n    myfile.write(\"$\\\\alpha$/\\\\textdegree  & \"+ structure[\"_cell_angle_alpha\"] +\"   \\\\\\ \\n\")\n    myfile.write(\"$\\\\beta$/\\\\textdegree  & \"+ structure[\"_cell_angle_beta\"] +\" \\\\\\ \\n\")\n    myfile.write(\"$\\\\gamma$/\\\\textdegree  & \"+ structure[\"_cell_angle_gamma\"] +\" \\\\\\ \\n\")\n    myfile.write(\"Volume/\\\\AA$^3$   & \"+ structure[\"_cell_volume\"] +\" \\\\\\ \\n\")\n    myfile.write(\"Z & \"+ structure[\"_cell_formula_units_Z\"] +\" \\\\\\ \\n\")\n    myfile.write(\"$\\\\rho$calcg/cm$^3$  & \"+ structure[\"_exptl_crystal_density_meas\"]+ \"\\\\\\ \\n\")\n    myfile.write(\"F(000)  & \"+ structure[\"_exptl_crystal_F_000\"] +\" \\\\\\ \\n\")\n    myfile.write(\"Crystal size/mm$^3$ & \"+ structure[\"_exptl_crystal_size_max\"] +\" x\" + structure[\"_exptl_crystal_size_mid\"] +\" x\" + structure[\"_exptl_crystal_size_min\"] +\"\\\\\\ \\n\")\n    myfile.write(\"Radiation  & \"+ structure[\"_diffrn_radiation_type\"][:-2]+ \"$\\\\alpha$ ($\\\\lambda$ = \" + structure[\"_diffrn_radiation_wavelength\"] +\") \\\\\\ \\n\")\n    myfile.write(\"2$\\\\theta$ range for data collection/\\textdegree                 & \"+ structure[\"_diffrn_reflns_theta_min\"]+ \" to \" + structure[\"_diffrn_reflns_theta_max\"] +\" \\\\\\ \\n\")\n    myfile.write(\"Index ranges & \" +structure[\"_diffrn_reflns_limit_h_min\"]+\" $\\leq$ h $\\leq$ \"+structure[\"_diffrn_reflns_limit_h_max\"]+\",\"+structure[\"_diffrn_reflns_limit_k_min\"]+\"  $\\leq$ k $\\leq$\"+ structure[\"_diffrn_reflns_limit_k_max\"]+\",\" + structure[\"_diffrn_reflns_limit_l_min\"]+\" $\\leq$ l $\\leq$\"+ structure[\"_diffrn_reflns_limit_h_min\"]+\"  \\\\\\ \\n\")\n    myfile.write(\"Reflections collected & \"+ structure[\"_diffrn_reflns_number\"]+\" \\\\\\ \\n\")\n    myfile.write(\"Independent reflections & \" + structure[\"_reflns_number_total\"] + \"{[}R$_{int}$ =\" + structure[\"_diffrn_reflns_av_R_equivalents\"]+ \", R$_\\sigma$ =\" + structure[\"_diffrn_reflns_av_unetI/netI\"]+\"{]} \\\\\\ \\n\")\n    myfile.write(\"Data/restraints/parameters &\"+ structure[\"_refine_ls_number_reflns\"]+\"/\"+ structure[\"_refine_ls_number_restraints\"]+ \"/\"+ structure[\"_refine_ls_number_parameters\"]  +\" \\\\\\ \\n\")\n    myfile.write(\"Goodness-of-fit & \"+ structure[\"_refine_ls_restrained_S_all\"] + \" \\\\\\ \\n\")\n    myfile.write(\"Final R indexes {[}I$\\\\geq$2$\\\\sigma$ (I){]} & R$_1$ = \"+ structure[\"_refine_ls_R_factor_gt\"]+ \", wR$_2$ = \"+ structure[\"_refine_ls_wR_factor_gt\"] + \"\\\\\\ \\n\")\n    myfile.write(\"Final R indexes {[}all data{]}               & R$_1$ = \"+ structure[\"_refine_ls_R_factor_all\"]+ \", wR$_2$ = \"+ structure[\"_refine_ls_wR_factor_ref\"] + \" \\\\\\ \\n\")\n    myfile.write(\"Largest diff. peak/hole / e \\AA$^-3$  & \"+ structure[\"_refine_diff_density_max\"] + \"/ \"+ structure[\"_refine_diff_density_min\"] +\" \\\\\\* \\\\bottomrule \\n\")\n    myfile.write(\"\\\\end{tabular} \\n\")\n    myfile.write(\"\\\\end{table}\")\n\nciftable_tex(\"filename\", cif_import(\"structure_name\"))\n\n```\n\n## Here the table for atom coordinates etc will be written to \"name_tables.tex\"\n\n\n```\nimport pandas as pd\ndef atom_tables(filename, structure):\n  atom_label = structure[\"_atom_site_label\"]\n  atom_x = structure[\"_atom_site_fract_x\"]\n  atom_y = structure[\"_atom_site_fract_y\"]\n  atom_z = structure[\"_atom_site_fract_z\"]\n  atom_U = structure[\"_atom_site_U_iso_or_equiv\"]\n  data_iso = pd.DataFrame({\"Atom\": atom_label, \"x\": atom_x , \"y\": atom_y, \"z\": atom_z, \"U\": atom_U})\n\n  with open(filename+\"_atom_coordinates_iso.tex\", \"w\") as myfile:\n    myfile.write(data_iso.to_latex(index=False, caption=\"Test\"))\n\n  atom_anis = structure[\"_atom_site_aniso_label\"]\n  atom_u11 = structure[\"_atom_site_aniso_U_11\"]\n  atom_u22 = structure[\"_atom_site_aniso_U_22\"]\n  atom_u33 = structure[\"_atom_site_aniso_U_33\"]\n  atom_u23 = structure[\"_atom_site_aniso_U_23\"]\n  atom_u13 = structure[\"_atom_site_aniso_U_13\"]\n  atom_u12 = structure[\"_atom_site_aniso_U_12\"]\n  data_anis = pd.DataFrame({\"Atom\": atom_anis, \"U_{11}\": atom_u11 , \"U_{22}\": atom_u22 , \"U_{33}\": atom_u33 , \"U_{23}\": atom_u23 , \"U_{13}\": atom_u13, \"U_{12}\": atom_u12})\n\n  with open(filename+\"_atom_anis.tex\", \"w\") as myfile:\n    myfile.write(data_anis.to_latex(index=False)) \n\natom_tables(\"filename\", cif_import(\"structure_name\"))\n```\n\n# Robocrystallographer\n\nHere [robocrys](https://hackingmaterials.lbl.gov/robocrystallographer/modules.html) will be used to desccribe the structure.\n\n\n\n```\n!pip install robocrys\n```\n\n\n```\n\nfrom robocrys import StructureCondenser, StructureDescriber\nfilename = \"filename\"\nstructure_cif = Structure.from_file(filename+ \".cif\") # other file formats also supported\n\n# alternatively, uncomment the lines below to use the MPRester object\n# to fetch structures from the Materials Project database\n# from pymatgen import MPRester\n# structure = MPRester(API_KEY=None).get_structure_by_material_id(\"mp-856\")\n\ncondenser = StructureCondenser()\ndescriber = StructureDescriber()\n\ncondensed_structure = condenser.condense_structure(structure_cif)\ndescription = describer.describe(condensed_structure)\n\nwith open(filename +\"_description.tex\", \"w\") as robotext:\n  robotext.write(description)\nprint(description)\n```\n\n\n```\n\n```\n", "meta": {"hexsha": "4eb396cdc0804b9bee2024851e04167612b3103b", "size": 31257, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "cif2robotex.ipynb", "max_stars_repo_name": "jakobbb/cif2robotex", "max_stars_repo_head_hexsha": "3ec78da7d5d267b12aefeb9090a32e5006b2a142", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cif2robotex.ipynb", "max_issues_repo_name": "jakobbb/cif2robotex", "max_issues_repo_head_hexsha": "3ec78da7d5d267b12aefeb9090a32e5006b2a142", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cif2robotex.ipynb", "max_forks_repo_name": "jakobbb/cif2robotex", "max_forks_repo_head_hexsha": "3ec78da7d5d267b12aefeb9090a32e5006b2a142", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 87.3100558659, "max_line_length": 1678, "alphanum_fraction": 0.6262917107, "converted": true, "num_tokens": 3243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.06097518043836536, "lm_q1q2_score": 0.023470087462826004}}
{"text": "```python\n! pip install qeds\nimport random\nimport numpy as np\nimport pandas as pd\nimport qeds\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport qeds\nqeds.themes.mpl_style();\n```\n\n    Requirement already satisfied: qeds in c:\\users\\asus\\anaconda3\\lib\\site-packages (0.6.2)\n    Requirement already satisfied: pandas in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.25.1)\n    Requirement already satisfied: numpy in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (1.16.5)\n    Requirement already satisfied: quantecon in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.4.6)\n    Requirement already satisfied: matplotlib in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (3.1.1)\n    Requirement already satisfied: scipy in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (1.3.1)\n    Requirement already satisfied: scikit-learn in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.21.3)\n    Requirement already satisfied: seaborn in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.9.0)\n    Requirement already satisfied: statsmodels in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.10.1)\n    Requirement already satisfied: pandas-datareader in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.8.1)\n    Requirement already satisfied: plotly in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (4.5.4)\n    Requirement already satisfied: pyarrow in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.16.0)\n    Requirement already satisfied: quandl in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (3.5.0)\n    Requirement already satisfied: openpyxl in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (3.0.0)\n    Requirement already satisfied: requests in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (2.22.0)\n    Requirement already satisfied: pytz>=2017.2 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pandas->qeds) (2019.3)\n    Requirement already satisfied: python-dateutil>=2.6.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pandas->qeds) (2.8.0)\n    Requirement already satisfied: numba>=0.38 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quantecon->qeds) (0.45.1)\n    Requirement already satisfied: sympy in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quantecon->qeds) (1.4)\n    Requirement already satisfied: cycler>=0.10 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (1.1.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (2.4.2)\n    Requirement already satisfied: joblib>=0.11 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from scikit-learn->qeds) (0.13.2)\n    Requirement already satisfied: patsy>=0.4.0 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from statsmodels->qeds) (0.5.1)\n    Requirement already satisfied: lxml in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pandas-datareader->qeds) (4.4.1)\n    Requirement already satisfied: six in c:\\users\\asus\\anaconda3\\lib\\site-packages (from plotly->qeds) (1.12.0)\n    Requirement already satisfied: retrying>=1.3.3 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from plotly->qeds) (1.3.3)\n    Requirement already satisfied: more-itertools in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quandl->qeds) (7.2.0)\n    Requirement already satisfied: inflection>=0.3.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quandl->qeds) (0.3.1)\n    Requirement already satisfied: et-xmlfile in c:\\users\\asus\\anaconda3\\lib\\site-packages (from openpyxl->qeds) (1.0.1)\n    Requirement already satisfied: jdcal in c:\\users\\asus\\anaconda3\\lib\\site-packages (from openpyxl->qeds) (1.4.1)\n    Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (2019.9.11)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (1.24.2)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (3.0.4)\n    Requirement already satisfied: idna<2.9,>=2.5 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (2.8)\n    Requirement already satisfied: llvmlite>=0.29.0dev0 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from numba>=0.38->quantecon->qeds) (0.29.0)\n    Requirement already satisfied: mpmath>=0.19 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from sympy->quantecon->qeds) (1.1.0)\n    Requirement already satisfied: setuptools in c:\\users\\asus\\anaconda3\\lib\\site-packages (from kiwisolver>=1.0.1->matplotlib->qeds) (41.4.0)\n\n\n# GroupBy - Exercises\n\n**We will begin with a simple made-up dataset to discuss the concepts and then work through extended example and exercises with real data.**\n\n\n```python\nC = np.arange(1, 7, dtype=float)\nC[[3, 5]] = np.nan\ndf = pd.DataFrame({\n    \"A\" : [1, 1, 1, 2, 2, 2],\n    \"B\" : [1, 1, 2, 2, 1, 1],\n    \"C\": C,\n})\ndf\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>A</th>\n      <th>B</th>\n      <th>C</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>2.0</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>1</td>\n      <td>2</td>\n      <td>3.0</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>2</td>\n      <td>2</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>2</td>\n      <td>1</td>\n      <td>5.0</td>\n    </tr>\n    <tr>\n      <td>5</td>\n      <td>2</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n**We create a DataFrameGroupBy to use in what follows.**\n\n\n```python\ngbA = df.groupby(\"A\")\ngbA.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>A</th>\n      <th>B</th>\n      <th>C</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>2.0</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>1</td>\n      <td>2</td>\n      <td>3.0</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>2</td>\n      <td>2</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>2</td>\n      <td>1</td>\n      <td>5.0</td>\n    </tr>\n    <tr>\n      <td>5</td>\n      <td>2</td>\n      <td>1</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Exercise 1\n\n**Try the following operations: gbA.sum(), gbA.mean(), gbA.count(). How did pandas compute the sum of `gbA`? What happened to the `NaN` entries in column `C`? Write your thoughts.** \n\n\n```python\n# the NaN entries in column C are disregarded in the analysis, regardless of the operation we use\n    # for A = 2: the sum is 5, the mean is also 5 (computed with one element), the count gives us 1 element\n\nprint(\"This is gbA.sum()\")\ndisplay(gbA.sum())\nprint(\"This is gbA.mean()\")\ndisplay(gbA.mean())\nprint(\"This is gbA.count()\")\ndisplay(gbA.count())\n```\n\n    This is gbA.sum()\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>B</th>\n      <th>C</th>\n    </tr>\n    <tr>\n      <th>A</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>1</td>\n      <td>4</td>\n      <td>6.0</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>4</td>\n      <td>5.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    This is gbA.mean()\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>B</th>\n      <th>C</th>\n    </tr>\n    <tr>\n      <th>A</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>1</td>\n      <td>1.333333</td>\n      <td>2.0</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>1.333333</td>\n      <td>5.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    This is gbA.count()\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>B</th>\n      <th>C</th>\n    </tr>\n    <tr>\n      <th>A</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>1</td>\n      <td>3</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>3</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n## Exercise 2\n\n1. **Use introspection (tab completion) to see what other aggregations are defined for GroupBy objects. Pick three and evaluate them in the cells below.**\n\n\n```python\nprint(\"This is gbA.max()\")\ndisplay(gbA.max())\nprint(\"This is gbA.median()\")\ndisplay(gbA.median())\nprint(\"This is gbA.diff()\")\ndisplay(gbA.diff())\n```\n\n    This is gbA.max()\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>B</th>\n      <th>C</th>\n    </tr>\n    <tr>\n      <th>A</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>1</td>\n      <td>2</td>\n      <td>3.0</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>2</td>\n      <td>5.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    This is gbA.median()\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>B</th>\n      <th>C</th>\n    </tr>\n    <tr>\n      <th>A</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>1</td>\n      <td>1</td>\n      <td>2.0</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>1</td>\n      <td>5.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    This is gbA.diff()\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>B</th>\n      <th>C</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>0.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>1.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>-1.0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>5</td>\n      <td>0.0</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n2. **Does the output of each of these commands have the same features as the output of `gbA.sum()` from above? If not, what is different?**\n\n\n```python\n#the three commands chosen seem to have the same features, excet for the last one where the key disappears\n```\n\n## Exercise 3\n\n1. **Write a function that, given a DataFrame, computes each entry's deviation from the mean of its column and apply the function to `gbA`.**\n\n\n```python\n# write function here\ndef mean_deviation(x):\n    avg = x.mean()\n   \n    return x - avg\n\n# apply function here\nmean_deviation = gbA.apply(mean_deviation)\nmean_deviation\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>B</th>\n      <th>C</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>-0.333333</td>\n      <td>-1.0</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>-0.333333</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>0.666667</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>0.666667</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>-0.333333</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <td>5</td>\n      <td>-0.333333</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n2. **Describe what the index and and columns are? Where are the group keys (the `A` column)?**\n\n\n```python\nmean_deviation.info()\n#the index contains 6 entries, from 0 to 5\n#the columns are B and C\n#the group keys no longer appear\n    #gbA.groups.keys()\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 6 entries, 0 to 5\n    Data columns (total 2 columns):\n    B    6 non-null float64\n    C    4 non-null float64\n    dtypes: float64(2)\n    memory usage: 224.0 bytes\n\n\n3. **Determine the correct way to add these results back into `df` as new columns.** \n    - Hint: remember the merge lecture\n\n\n```python\n# add output of function as new columns to df here...\nmean_deviation_tu = mean_deviation.rename(columns={\"B\":\"B_dev\", \"C\":\"C_dev\"},inplace=True)\n\nmerged=pd.concat([df, mean_deviation], axis=1)\nmerged\n\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>A</th>\n      <th>B</th>\n      <th>C</th>\n      <th>B_dev</th>\n      <th>C_dev</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1.0</td>\n      <td>-0.333333</td>\n      <td>-1.0</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>2.0</td>\n      <td>-0.333333</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>1</td>\n      <td>2</td>\n      <td>3.0</td>\n      <td>0.666667</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>2</td>\n      <td>2</td>\n      <td>NaN</td>\n      <td>0.666667</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>2</td>\n      <td>1</td>\n      <td>5.0</td>\n      <td>-0.333333</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <td>5</td>\n      <td>2</td>\n      <td>1</td>\n      <td>NaN</td>\n      <td>-0.333333</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n<dl style='margin: 20px 0;'>\n<dt>Note that if the group keys</dt>\n<dd>\nremained in the index as the `.apply`'s output, the merge/join step would have been complicated.\n\n## Exercise 4\n\n**We use an airline DataFrame:**\n\n\n```python\nair_dec = qeds.load(\"airline_performance_dec16\")\nair_dec.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Carrier</th>\n      <th>TailNum</th>\n      <th>FlightNum</th>\n      <th>OriginCityMarketID</th>\n      <th>Origin</th>\n      <th>OriginCityName</th>\n      <th>OriginStateName</th>\n      <th>DestCityMarketID</th>\n      <th>Dest</th>\n      <th>DestCityName</th>\n      <th>...</th>\n      <th>AirTime</th>\n      <th>Distance</th>\n      <th>CarrierDelay</th>\n      <th>WeatherDelay</th>\n      <th>NASDelay</th>\n      <th>SecurityDelay</th>\n      <th>LateAircraftDelay</th>\n      <th>FirstDepTime</th>\n      <th>TotalAddGTime</th>\n      <th>Date</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>AA</td>\n      <td>N3JHAA</td>\n      <td>46</td>\n      <td>31650</td>\n      <td>MSP</td>\n      <td>Minneapolis, MN</td>\n      <td>Minnesota</td>\n      <td>30977</td>\n      <td>ORD</td>\n      <td>Chicago, IL</td>\n      <td>...</td>\n      <td>58.0</td>\n      <td>334.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>20.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2016-12-18</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>AA</td>\n      <td>N3DPAA</td>\n      <td>46</td>\n      <td>31650</td>\n      <td>MSP</td>\n      <td>Minneapolis, MN</td>\n      <td>Minnesota</td>\n      <td>30977</td>\n      <td>ORD</td>\n      <td>Chicago, IL</td>\n      <td>...</td>\n      <td>57.0</td>\n      <td>334.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>20.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2016-12-19</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>AA</td>\n      <td>N3KUAA</td>\n      <td>46</td>\n      <td>31650</td>\n      <td>MSP</td>\n      <td>Minneapolis, MN</td>\n      <td>Minnesota</td>\n      <td>30977</td>\n      <td>ORD</td>\n      <td>Chicago, IL</td>\n      <td>...</td>\n      <td>49.0</td>\n      <td>334.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2016-12-20</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>AA</td>\n      <td>N3FBAA</td>\n      <td>46</td>\n      <td>31650</td>\n      <td>MSP</td>\n      <td>Minneapolis, MN</td>\n      <td>Minnesota</td>\n      <td>30977</td>\n      <td>ORD</td>\n      <td>Chicago, IL</td>\n      <td>...</td>\n      <td>51.0</td>\n      <td>334.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2016-12-21</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>AA</td>\n      <td>N3BLAA</td>\n      <td>46</td>\n      <td>31650</td>\n      <td>MSP</td>\n      <td>Minneapolis, MN</td>\n      <td>Minnesota</td>\n      <td>30977</td>\n      <td>ORD</td>\n      <td>Chicago, IL</td>\n      <td>...</td>\n      <td>51.0</td>\n      <td>334.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2016-12-22</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 36 columns</p>\n</div>\n\n\n\n1. **Which type of delay was the most common?**\n\n\n```python\n#The air_dec DataFrame has information on the minutes of delay attributed to 5 different categories:\ndelay_cols = [\n    'CarrierDelay',\n    'WeatherDelay',\n    'NASDelay',\n    'SecurityDelay',\n    'LateAircraftDelay'\n]\n\nair_dec[delay_cols]=(air_dec[delay_cols] > 0) \nair_dec[delay_cols][air_dec[delay_cols]==True].count().sort_values()\n#CarrierDelay was the most frequent one\n```\n\n\n\n\n    SecurityDelay          356\n    WeatherDelay          5946\n    NASDelay             55765\n    LateAircraftDelay    56377\n    CarrierDelay         57189\n    dtype: int64\n\n\n\n2. **Which one caused the largest average delay?**  \n\n\n```python\nair_dec[delay_cols].mean().sort_values()\n#CarrierDelay caused the largest average delay\n```\n\n\n\n\n    SecurityDelay        0.000772\n    WeatherDelay         0.012899\n    NASDelay             0.120979\n    LateAircraftDelay    0.122306\n    CarrierDelay         0.124068\n    dtype: float64\n\n\n\n3. **Does that vary by airline?**  \n\n\n```python\nair_dec.groupby(\"Carrier\")[delay_cols].mean()\n#it does: \n    #AA - LateAircraftDelay\n    #EV - CarrierDelay\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>CarrierDelay</th>\n      <th>WeatherDelay</th>\n      <th>NASDelay</th>\n      <th>SecurityDelay</th>\n      <th>LateAircraftDelay</th>\n    </tr>\n    <tr>\n      <th>Carrier</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>AA</td>\n      <td>0.112612</td>\n      <td>0.012317</td>\n      <td>0.118127</td>\n      <td>0.001233</td>\n      <td>0.089361</td>\n    </tr>\n    <tr>\n      <td>AS</td>\n      <td>0.067172</td>\n      <td>0.016121</td>\n      <td>0.154461</td>\n      <td>0.002067</td>\n      <td>0.078333</td>\n    </tr>\n    <tr>\n      <td>B6</td>\n      <td>0.197797</td>\n      <td>0.005878</td>\n      <td>0.149540</td>\n      <td>0.002918</td>\n      <td>0.158089</td>\n    </tr>\n    <tr>\n      <td>DL</td>\n      <td>0.104186</td>\n      <td>0.020499</td>\n      <td>0.099187</td>\n      <td>0.000168</td>\n      <td>0.076663</td>\n    </tr>\n    <tr>\n      <td>EV</td>\n      <td>0.113454</td>\n      <td>0.004558</td>\n      <td>0.124010</td>\n      <td>0.000000</td>\n      <td>0.122304</td>\n    </tr>\n    <tr>\n      <td>F9</td>\n      <td>0.180027</td>\n      <td>0.010525</td>\n      <td>0.181006</td>\n      <td>0.000000</td>\n      <td>0.154693</td>\n    </tr>\n    <tr>\n      <td>HA</td>\n      <td>0.115488</td>\n      <td>0.027730</td>\n      <td>0.002363</td>\n      <td>0.000945</td>\n      <td>0.077517</td>\n    </tr>\n    <tr>\n      <td>NK</td>\n      <td>0.117898</td>\n      <td>0.007484</td>\n      <td>0.203283</td>\n      <td>0.001449</td>\n      <td>0.089731</td>\n    </tr>\n    <tr>\n      <td>OO</td>\n      <td>0.090251</td>\n      <td>0.016382</td>\n      <td>0.149895</td>\n      <td>0.000484</td>\n      <td>0.150500</td>\n    </tr>\n    <tr>\n      <td>UA</td>\n      <td>0.129314</td>\n      <td>0.018658</td>\n      <td>0.119668</td>\n      <td>0.000175</td>\n      <td>0.100901</td>\n    </tr>\n    <tr>\n      <td>VX</td>\n      <td>0.113102</td>\n      <td>0.049975</td>\n      <td>0.120500</td>\n      <td>0.003123</td>\n      <td>0.142693</td>\n    </tr>\n    <tr>\n      <td>WN</td>\n      <td>0.150046</td>\n      <td>0.006281</td>\n      <td>0.106032</td>\n      <td>0.000695</td>\n      <td>0.170568</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n", "meta": {"hexsha": "e6db260c292b2a6fbe2ba0d7f261a6e86ed47184", "size": 46031, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Session_7/8_groupby_exercises.ipynb", "max_stars_repo_name": "remi-sudo/Classes", "max_stars_repo_head_hexsha": "71497927ed4d54ddf6fd5abe2ddabb5966eb0304", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Session_7/8_groupby_exercises.ipynb", "max_issues_repo_name": "remi-sudo/Classes", "max_issues_repo_head_hexsha": "71497927ed4d54ddf6fd5abe2ddabb5966eb0304", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Session_7/8_groupby_exercises.ipynb", "max_forks_repo_name": "remi-sudo/Classes", "max_forks_repo_head_hexsha": "71497927ed4d54ddf6fd5abe2ddabb5966eb0304", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7357881137, "max_line_length": 188, "alphanum_fraction": 0.3837196672, "converted": true, "num_tokens": 8318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.059210246175955, "lm_q1q2_score": 0.023451293627545087}}
{"text": "Copyright 2020 DeepMind Technologies Limited\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n     https://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n## Clone repo and import dependencies\n\n\n```python\n!pip install tensorflow==1.15 dm-sonnet==1.36 tensor2tensor==1.14 pyntcloud \n\nimport os\nimport numpy as np\nimport tensorflow.compat.v1 as tf\ntf.logging.set_verbosity(tf.logging.ERROR)  # Hide TF deprecation messages\nimport matplotlib.pyplot as plt\n\n%cd /tmp\n%rm -rf /tmp/deepmind_research\n!git clone https://github.com/davidharrod/PengLai.git\n%cd /tmp/PengLai\nimport modules\nimport data_utils\nimport train\nfrom pre_process import point_cloud_2_voxel as p2v\n```\n\n    Requirement already satisfied: tensorflow==1.15 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (1.15.0)\n    Requirement already satisfied: dm-sonnet==1.36 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (1.36)\n    Requirement already satisfied: tensor2tensor==1.14 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (1.14.0)\n    Requirement already satisfied: pyntcloud in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (0.1.5)\n    Requirement already satisfied: protobuf>=3.6.1 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow==1.15) (3.19.1)\n    Requirement already satisfied: numpy<2.0,>=1.16.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow==1.15) (1.18.5)\n    Requirement already satisfied: gast==0.2.2 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow==1.15) (0.2.2)\n    Requirement already satisfied: google-pasta>=0.1.6 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow==1.15) (0.2.0)\n    Requirement already satisfied: tensorflow-estimator==1.15.1 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow==1.15) (1.15.1)\n    Requirement already satisfied: six>=1.10.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow==1.15) (1.16.0)\n    Requirement already satisfied: termcolor>=1.1.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow==1.15) (1.1.0)\n    Requirement already satisfied: grpcio>=1.8.6 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow==1.15) (1.43.0)\n    Requirement already satisfied: wheel>=0.26 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow==1.15) (0.37.0)\n    Requirement already satisfied: absl-py>=0.7.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow==1.15) (0.12.0)\n    Requirement already satisfied: keras-preprocessing>=1.0.5 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow==1.15) (1.1.2)\n    Requirement already satisfied: tensorboard<1.16.0,>=1.15.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow==1.15) (1.15.0)\n    Requirement already satisfied: astor>=0.6.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow==1.15) (0.8.1)\n    Requirement already satisfied: opt-einsum>=2.3.2 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow==1.15) (3.3.0)\n    Requirement already satisfied: wrapt>=1.11.1 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow==1.15) (1.13.3)\n    Requirement already satisfied: keras-applications>=1.0.8 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow==1.15) (1.0.8)\n    Requirement already satisfied: semantic-version in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from dm-sonnet==1.36) (2.8.5)\n    Requirement already satisfied: contextlib2 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from dm-sonnet==1.36) (21.6.0)\n    Requirement already satisfied: tensorflow-probability<0.9.0,>=0.8.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from dm-sonnet==1.36) (0.8.0)\n    Requirement already satisfied: opencv-python in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (4.5.4.60)\n    Requirement already satisfied: gym in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (0.12.5)\n    Requirement already satisfied: kfac in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (0.2.3)\n    Requirement already satisfied: tqdm in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (4.62.3)\n    Requirement already satisfied: mesh-tensorflow in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (0.1.19)\n    Requirement already satisfied: requests in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (2.26.0)\n    Requirement already satisfied: pypng in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (0.0.21)\n    Requirement already satisfied: gevent in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (21.12.0)\n    Requirement already satisfied: dopamine-rl in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (3.0.1)\n    Requirement already satisfied: flask in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (2.0.2)\n    Requirement already satisfied: gunicorn in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (20.1.0)\n    Requirement already satisfied: Pillow in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (8.4.0)\n    Requirement already satisfied: scipy in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (1.7.3)\n    Requirement already satisfied: tensorflow-datasets in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (4.4.0)\n    Requirement already satisfied: oauth2client in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (4.1.3)\n    Requirement already satisfied: google-api-python-client in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (2.33.0)\n    Requirement already satisfied: h5py in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (3.6.0)\n    Requirement already satisfied: gin-config in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (0.5.0)\n    Requirement already satisfied: bz2file in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (0.98)\n    Requirement already satisfied: sympy in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (1.9)\n    Requirement already satisfied: future in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (0.18.2)\n    Requirement already satisfied: tensorflow-gan in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensor2tensor==1.14) (2.1.0)\n    Requirement already satisfied: pandas in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from pyntcloud) (1.3.5)\n    Requirement already satisfied: setuptools>=41.0.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorboard<1.16.0,>=1.15.0->tensorflow==1.15) (58.0.4)\n    Requirement already satisfied: werkzeug>=0.11.15 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorboard<1.16.0,>=1.15.0->tensorflow==1.15) (2.0.2)\n    Requirement already satisfied: markdown>=2.6.8 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorboard<1.16.0,>=1.15.0->tensorflow==1.15) (3.3.6)\n    Requirement already satisfied: importlib-metadata>=4.4 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from markdown>=2.6.8->tensorboard<1.16.0,>=1.15.0->tensorflow==1.15) (4.10.0)\n    Requirement already satisfied: typing-extensions>=3.6.4 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from importlib-metadata>=4.4->markdown>=2.6.8->tensorboard<1.16.0,>=1.15.0->tensorflow==1.15) (4.0.1)\n    Requirement already satisfied: zipp>=0.5 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from importlib-metadata>=4.4->markdown>=2.6.8->tensorboard<1.16.0,>=1.15.0->tensorflow==1.15) (3.6.0)\n    Requirement already satisfied: decorator in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow-probability<0.9.0,>=0.8.0->dm-sonnet==1.36) (5.1.0)\n    Requirement already satisfied: cloudpickle==1.1.1 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow-probability<0.9.0,>=0.8.0->dm-sonnet==1.36) (1.1.1)\n    Requirement already satisfied: pyglet>=1.2.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from gym->tensor2tensor==1.14) (1.5.21)\n    Requirement already satisfied: itsdangerous>=2.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from flask->tensor2tensor==1.14) (2.0.1)\n    Requirement already satisfied: click>=7.1.2 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from flask->tensor2tensor==1.14) (8.0.3)\n    Requirement already satisfied: Jinja2>=3.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from flask->tensor2tensor==1.14) (3.0.3)\n    Requirement already satisfied: MarkupSafe>=2.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from Jinja2>=3.0->flask->tensor2tensor==1.14) (2.0.1)\n    Requirement already satisfied: zope.interface in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from gevent->tensor2tensor==1.14) (5.4.0)\n    Requirement already satisfied: greenlet<2.0,>=1.1.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from gevent->tensor2tensor==1.14) (1.1.2)\n    Requirement already satisfied: zope.event in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from gevent->tensor2tensor==1.14) (4.5.0)\n    Requirement already satisfied: uritemplate<5,>=3.0.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from google-api-python-client->tensor2tensor==1.14) (4.1.1)\n    Requirement already satisfied: google-api-core<3.0.0dev,>=1.21.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from google-api-python-client->tensor2tensor==1.14) (2.3.2)\n    Requirement already satisfied: google-auth<3.0.0dev,>=1.16.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from google-api-python-client->tensor2tensor==1.14) (2.3.3)\n    Requirement already satisfied: google-auth-httplib2>=0.1.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from google-api-python-client->tensor2tensor==1.14) (0.1.0)\n    Requirement already satisfied: httplib2<1dev,>=0.15.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from google-api-python-client->tensor2tensor==1.14) (0.20.2)\n    Requirement already satisfied: googleapis-common-protos<2.0dev,>=1.52.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from google-api-core<3.0.0dev,>=1.21.0->google-api-python-client->tensor2tensor==1.14) (1.54.0)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from google-auth<3.0.0dev,>=1.16.0->google-api-python-client->tensor2tensor==1.14) (4.2.4)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from google-auth<3.0.0dev,>=1.16.0->google-api-python-client->tensor2tensor==1.14) (4.8)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from google-auth<3.0.0dev,>=1.16.0->google-api-python-client->tensor2tensor==1.14) (0.2.8)\n    Requirement already satisfied: pyparsing!=3.0.0,!=3.0.1,!=3.0.2,!=3.0.3,<4,>=2.4.2 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from httplib2<1dev,>=0.15.0->google-api-python-client->tensor2tensor==1.14) (3.0.6)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from pyasn1-modules>=0.2.1->google-auth<3.0.0dev,>=1.16.0->google-api-python-client->tensor2tensor==1.14) (0.4.8)\n    Requirement already satisfied: certifi>=2017.4.17 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from requests->tensor2tensor==1.14) (2021.10.8)\n    Requirement already satisfied: urllib3<1.27,>=1.21.1 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from requests->tensor2tensor==1.14) (1.26.7)\n    Requirement already satisfied: charset-normalizer~=2.0.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from requests->tensor2tensor==1.14) (2.0.9)\n    Requirement already satisfied: idna<4,>=2.5 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from requests->tensor2tensor==1.14) (3.3)\n    Requirement already satisfied: cached-property in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from h5py->tensor2tensor==1.14) (1.5.2)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from pandas->pyntcloud) (2.8.2)\n    Requirement already satisfied: pytz>=2017.3 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from pandas->pyntcloud) (2021.3)\n    Requirement already satisfied: mpmath>=0.19 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from sympy->tensor2tensor==1.14) (1.2.1)\n    Requirement already satisfied: attrs>=18.1.0 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow-datasets->tensor2tensor==1.14) (21.2.0)\n    Requirement already satisfied: tensorflow-metadata in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow-datasets->tensor2tensor==1.14) (1.5.0)\n    Requirement already satisfied: importlib-resources in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow-datasets->tensor2tensor==1.14) (5.4.0)\n    Requirement already satisfied: dill in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow-datasets->tensor2tensor==1.14) (0.3.4)\n    Requirement already satisfied: promise in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow-datasets->tensor2tensor==1.14) (2.3)\n    Requirement already satisfied: tensorflow-hub>=0.2 in /home/yqs/anaconda3/envs/poly/lib/python3.7/site-packages (from tensorflow-gan->tensor2tensor==1.14) (0.12.0)\n    /tmp\n    \u6b63\u514b\u9686\u5230 'PMGen'...\n    remote: Enumerating objects: 39, done.\u001b[K\n    remote: Counting objects: 100% (39/39), done.\u001b[K\n    remote: Compressing objects: 100% (37/37), done.\u001b[K\n    remote: Total 39 (delta 5), reused 0 (delta 0), pack-reused 0\u001b[K\n    \u5c55\u5f00\u5bf9\u8c61\u4e2d: 100% (39/39), \u5b8c\u6210.\n    [Errno 2] No such file or directory: '/tmp/PolyGen'\n    /tmp\n\n\n## Prepare dataset\n\n\n```python\nbatch_size = 1\nbuffer_size =20\nobj_path = \"./dataset/obj/\"\nbinvox_path = \"./dataset/binvox\"\nvertex_dataset, face_dataset = train.load_dataset(obj_path, binvox_path,batch_size,buffer_size)\n```\n\n## Set configuration\n\n\n```python\nVERTICES = \"VERTICES_FLAT\"\nFACES = \"FACES\"\nEPOCH = 10000\nCHECK_POINT = 5000\n\n# Set tensorflow gpu configuration.\ntf_gpu_config = tf.ConfigProto(allow_soft_placement=True)\ntf_gpu_config.gpu_options.allow_growth = True\n\n# Set encoders and decoders' configuration.\nvertex_model_encoder_config = {\n    \"hidden_sizes\": (64, 256),\n    \"num_blocks\": (1, 2),\n    \"dropout_rate\": 0.1\n}\nvertex_model_decoder_config = {\n    \"hidden_size\": 256,\n    \"fc_size\": 1024,\n    \"num_heads\": 4,\n    \"dropout_rate\": 0.2,\n}\nface_model_encoder_config = {\n    'hidden_size': 128,\n    'fc_size': 512,\n    'num_layers': 3,\n    'dropout_rate': 0.\n}\nface_model_decoder_config = {\n    'hidden_size': 128,\n    'fc_size': 512,\n    'num_layers': 3,\n    'dropout_rate': 0.\n}\n```\n\n## Create models\n\n\n```python\n# Set training parameters.\ntarget_dir = \"./log/\"\nlearning_rate = 5e-4\ntraining_step = 20\ncheck_step = 2\n\n# Prepare for training.\nvertex_batch = vertex_dataset.make_one_shot_iterator().get_next()\nface_batch = face_dataset.make_one_shot_iterator().get_next()\n_, vertex_loss, vertex_samples = train._create_model(\n    vertex_batch,\n    model_type=VERTICES,\n    encoder_config=vertex_model_encoder_config,\n    decoder_config=vertex_model_decoder_config)\n_, face_loss, _=train._create_model(face_batch,\n                                model_type=FACES,\n                                encoder_config=face_model_encoder_config,\n                                decoder_config=face_model_decoder_config,\n                                vertex_samples=vertex_samples)\noptimizer = tf.train.AdamOptimizer(learning_rate)\nvertex_model_optim_op = optimizer.minimize(vertex_loss)\nface_model_optim_op = optimizer.minimize(face_loss)\n# Set saver and summary.\ntf.summary.scalar(\"vertex loss\", vertex_loss)\ntf.summary.scalar(\"face loss\", face_loss)\nmerged = tf.summary.merge_all()\n```\n\n## Start training\n\n\n```python\nwith tf.Session(config=tf_gpu_config) as sess:\n    writer = tf.summary.FileWriter(os.getcwd(), sess.graph)\n    sess.run(tf.global_variables_initializer())\n    for epoch in range(EPOCH):\n        for n in range(training_step):\n            if n % check_step == 0:\n                summary = sess.run(merged)\n                writer.add_summary(summary, n + epoch * training_step)\n            sess.run((vertex_model_optim_op, face_model_optim_op))\n```\n\n## Check out logging with tensorboard\n\n\n```python\n%load_ext tensorboard\n%tensorboard --logdir ./\n```\n", "meta": {"hexsha": "1ad5f32f932e8562b25c215ff59fcf7e23b56563", "size": 20074, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "training.ipynb", "max_stars_repo_name": "davidharrod/PengLai", "max_stars_repo_head_hexsha": "58bcd58d75e0647ab95bdbf97ccfa780c3d36c52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "training.ipynb", "max_issues_repo_name": "davidharrod/PengLai", "max_issues_repo_head_hexsha": "58bcd58d75e0647ab95bdbf97ccfa780c3d36c52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "training.ipynb", "max_forks_repo_name": "davidharrod/PengLai", "max_forks_repo_head_hexsha": "58bcd58d75e0647ab95bdbf97ccfa780c3d36c52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 10037.0, "max_line_length": 20073, "alphanum_fraction": 0.731991631, "converted": true, "num_tokens": 5626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.05749328041530818, "lm_q1q2_score": 0.023418933391361575}}
{"text": "# Orders of Magnitude\nThe simulation examples in the previous chapters are conceptual. As we begin to build simulation models of realistic biological processes, the need to obtain information such as the numerical values of the parameters that appear in the dynamic mass balances. We thus go through a process of estimating the approximate numerical values of various quantities and parameters. Size, mass, chemical composition, metabolic complexity, and genetic makeup represent characteristics for which we now have extensive data available. Based on typical values for these quantities we show how one can make useful estimates of concentrations and the dynamic features of the intracellular environment.\n\n## Cellular Composition and Ultra-structure\nIt is often stated that all biologists have two favorite organisms, _E. coli_ and another one. Fortunately, much data exists for _E. coli,_ and we can go through parameter and variable estimation procedures using it as an example. These estimation procedures can be performed for other target organisms, cell types, and cellular processes in an analogous manner if the appropriate data is available. We organize the discussion around key questions. \n\n### The interior of a cell  \nThe typical bacterial cell, like _E. coli,_ is on the order of microns in size (Figure\u00a07.1a). The _E. coli_ cell is a short cylinder, about 2-4 micron in length with a 0.5 to 1.5 micron diameter, Figure\u00a07.1b. The size of the _E. coli_ cell is growth rate dependent; the faster the cell grows, the larger it is. \n\nIt has a complex intra-cellular environment. One can isolate and crystallize macromolecules and obtain their individual structure. However, this approach gives limited information about the configuration and location of a protein in a living functional cell. The intracellular milieu can to be reconstructed from available data to yield an indirect picture of the interior of an cell. Such a reconstruction has been carried out\u00a0Goodsell93. Based on well known chemical composition data, this image provides us with about a million-fold magnification of the interior of an _E. coli_ cell, see Figure\u00a07.1c. Examination of this picture of the interior of the _E. coli_ cell is instructive: \n\n* The intracellular environment is very crowded and represents a dense solution. Protein density in some sub-cellular structures can approach that found in protein crystals, and the intracellular environment is sometimes referred to as 'soft glass,' suggesting that it is close to a crystalline state. \n\n* The chemical composition of this dense mixture is very complex. The majority of cellular mass are macromolecules with metabolites, the small molecular weight molecules interspersed among the macromolecules. \n\n* In this crowded solution, the motion of the macromolecules is estimated to be one hundred to even one thousand-fold slower than in a dilute solution. The time it takes a 160 kDa protein to move 10 nm - a distance that corresponds approximately to the size of the protein molecule - is estimated to be 0.2 to 2 milliseconds. Moving one cellular diameter of approximately 0.64\u00a0$\\mu m$, or 640\u00a0nm, would then require 1-10 min. The motion of metabolites is expected to be significantly faster due to their smaller size. \n\n\n\n**Figure 7.1:** (a) An electron micrograph of the _E. coli_ cell, from\u00a0Ingraham83. (b) Characteristic features of an _E. coli_ cell. (c) The interior of an _E. coli_ cell, \u00a9 David S. Goodsell 1999.\n\n### The overall chemical composition of a cell  \nWith these initial observations, let's take a closer look at the chemical composition of the cell. Most cells are about 70% water. It is likely that cellular functions and evolutionary design is constrained by the solvent capacity of water, and the fact that most cells are approximately 70% water suggests that all cells are close to these constraints. \n\nThe 'biomass' is about 30% of cell weight. It is sometimes referred to as the dry weight of a cell, and is denoted by gDW. The 30% of the weight that is biomass is comprised of 26% macromolecules, 1% inorganic ions, and 3% low molecular weight metabolites. The basic chemical makeup of prokaryotic cells is shown in Table\u00a07.1, and contrasted to that of a typical animal cell. The gross chemical composition is similar except that animal cells, and eukaryotic cells in general, have a higher lipid content because of the membrane requirement for cellular compartmentalization. Approximate cellular composition is available or relatively easy to get for other cell types.  \n\n**Table 7.1:** Approximate composition of cells, from\u00a0(Alberts, 1983). The numbers given are weight percent.\n\n\n\n### The detailed composition of _E. coli_\nThe total weight of a bacterial cell is about 1 picogram. The density of cells barely exceeds that of water, and cellular density is typically around 1.04 to 1.08 $gm/cm^3$. Since the density of cells is close to unity, a cellular concentration of about $10^12$ cells per milliliter represents packing density of _E. coli_ cells. Detailed and recent data is found later in Figure\u00a07.2. \n\nThis information provides the basis for estimating the numerical values for a number of important quantities that relate to dynamic network modeling. Having such order of magnitude information provides a frame of reference, allows one to develop a conceptual model of cells, evaluate the numerical outputs from models, and perform any approximation or simplification that is useful and justified based on the numbers. \"Numbers count,\" even in biology. \n\n### Order of magnitude estimates  \nIt is relatively easy to estimate the approximate order of magnitude of the numerical values of key quantities. Enrico Fermi the famous physicist was well-known for his skills with such calculations and they thus know as Fermi problems. We give a couple examples to illustrate the order of magnitude estimation process. \n\n#### 1. How many piano tuners are in Chicago?  \nThis question represents a classical Fermi problem. First we state assumptions or key numbers: \n\n**1.** There are approximately 5,000,000 people living in Chicago. \n\n**2.** On average, there are two persons in each household in Chicago. \n\n**3.** Roughly one household in twenty has a piano that is tuned regularly. \n\n**4.** Pianos that are tuned regularly are tuned on average about once per year. \n\n**5.** It takes a piano tuner about two hours to tune a piano, including travel time. \n\n**6.** Each piano tuner works eight hours in a day, five days in a week, and 50 weeks in a year. \n\nFrom these assumptions we can compute: \n\n* that the number of piano tunings in a single year in Chicago is: \n(5,000,000 persons in Chicago)/(2 persons/household) $*$ (1 piano/20 households) $*$ (1 piano tuning per piano per year) = 125,000 piano tunings per year in Chicago.\n\n\n* that the average piano tuner performs (50 weeks/year) $*$ (5 days/week) $*$ (8 hours/day)/(1 piano tuning per 2 hours per piano tuner) = 1000 piano tunings per year per piano tuner. \n\n\n* then dividing gives (125,000 piano tuning per year in Chicago) / (1000 piano tunings per year per piano tuner) = 125 piano tuners in Chicago, which is the answer that we sought. \n\n\n#### 2. How far can a retrovirus diffuse before it falls apart?  \nA similar procedure that relies more on scientific principles can be used to answer this question. The half-live of retroviruses, $t_{0.5}$, are measured to be about 5 to 6 hours. The time constant for diffusion is: \n\n$$\\begin{equation} t_{diff} = t^2 / D \\tag{7.1} \\end{equation}$$\n\nwhere l is the diffusion distance and $D$ is the diffusion constant. Then the distance $l_{0.5}$ that a virus can travel over a half life is \n\n$$\\begin{equation} l_{0.5} = \\sqrt{D\\ t_{0.5}} \\tag{7.2} \\end{equation}$$\n\nUsing a numerical value for $D$ of $6.5*10^{-8}\\ cm^2/sec$ that is computed from the Stokes-Einstein equation for a 100 nm particle (approximately the diameter of the retrovirus) the estimate is about 500 $\\mu m$\u00a0(Chuck, 1996). A fairly short distance that limits how far a virus can go to infect a target cell. \n\n### A multi-scale view  \nThe cellular composition of cells is complex. More complex yet is the intricate and coordinated web of complex functions that underlie the physiological state of a cell. We can view this as a multi-scale relationship, Figure\u00a07.2. Based on cellular composition and other data we can estimate the overall parameters that are associated with cellular functions. Here we will focus on metabolism, macro-molecular synthesis and overall cellular states. \n\n\n\n**Figure 7.2:** A multi-scale view of metabolism, macromolecular synthesis, and cellular functions. Prokaryotic cell (Synechocytis image from W. Vermaas, Arizona State University). Prokaryotic cell structures (purified carboxysomes) image from T. Yates, M. Yeager, and K. Dryden. Macromolecular complexes image \u00a9 2000, David S. Goodsell.\n\n## Metabolism\nBiomass composition allows the estimation of important overall features of metabolic processes. These quantities are basically concentrations (abundance), rates of change (fluxes), and time constants (response times, sensitivities, etc). For metabolism, we can readily estimate reasonable values for these quantities, and we again organize the discussion around key questions. \n\n### What are typical concentrations?  \n#### Estimation  \nThe approximate number of different metabolites present in a given cell is on the order of 1000\u00a0(Feist, 2007). By assuming that metabolite has a median molecular weight of about 312 gm/mol (Figure\u00a07.3a) and that the fraction of metabolites of the wet weight is 0.01, we can estimate a typical metabolite concentration of: \n\n$$\\begin{equation} x_{avg} \\approx \\frac{1 gm/cm^3 * 0.01}{1000*312\\ gm/mol} \\approx 32 \\mu M \\tag{7.3} \\end{equation}$$\n\nThe volume of a bacterial cell is about one cubic micron, or about one femto-liter $(=(10^-15)$ liter). Since a cubic micron is a logical reference volume, we convert the concentration unit as follows: \n\n$$\\begin{align} 1 \\mu M &= \\frac{10^{-6} mole}{1\\ L} * \\frac{10^{-15}\\ L}{1\\ \\mu m^3} * \\frac{6 * 10^{23}\\ molecules}{mol} \\tag{7.4} \\\\ &= 600\\ molecules/\\ \\mu m^3 \\tag{7.5} \\end{align}$$\n\nThis number is remarkably small. A typical metabolite concentration of $32 \\mu M$ then translates into mere $19,000$ molecules per cubic micron. One would expect that such low concentrations would lead to slow reaction rates. However, metabolic reaction rates are fairly rapid. As discussed in Chapter\u00a05, cells have evolved highly efficient enzymes to achieve high reaction rates that occur even in the presence of low metabolite concentrations. \n\n\n\n**Figure 7.3:** Details of _E. coli_ K12 MG1655 composition and properties. (a) The average molecular weight of metabolites is 500 gm/mol and the median is 312 gm/mol. Molecular weight distribution. (b) Thermodynamic properties of the reactions in the iAF1260 reconstruction the metabolic network. (c) Size distribution of ORF lengths or protein sizes: protein size distribution. The average protein length is 316 amino acids, the median is 281. Average molecular weight of _E. coli's_ proteins (monomers): 34.7 kDa Median: 30.828 kDa (d) distribution of protein concentrations: relative protein abundance distribution. See\u00a0(Feist, 2007) and\u00a0(Riley, 2006) for details. Prepared by Vasiliy Portnoy.\n\n#### Measurement  \nExperimentally determined ranges of metabolite concentrations fall around the estimated range; an example is provided in Table\u00a07.2. Surprisingly, glutamate is at a concentration that falls within the 100 millimolar range in _E. coli_. Other important metabolites such as ATP tend to fall in the millimolar range. Intermediates of pathways are often in the micromolar range. Several on-line resources are now available for metabolic concentration data, Table\u00a07.3. \n\n**Table 7.2:** Measured and predicted parameters for _E. coli_ growing on minimal media. Taken from (Yuan, 2006).\n\n\n\n**Table 7.3:** Publicly available metabolic resources (above the dashed line) and proteomic resources (below the dashed line). Assembled by Vasiliy Portnoy.\n\n\n\n### What are typical metabolic fluxes?  \n#### Rates of diffusion  \nIn estimating reaction rates we first need to know if they are diffusion limited. Typical cellular dimensions are on the order of microns, or less. The diffusion constants for metabolites is on the order of $10^{-5}\\ cm^2/sec$  and $10^{-6}\\ cm^2/sec$. These figures translate into diffusional response times that are on the order of: \n\n$$\\begin{equation} t_{diff} = \\frac{t^2}{D} = \\frac{(10^{-4} cm)^2}{10^{-5}\\ \\text{to}\\ 10^{-6} cm^2 / sec} \\approx 1-10 msec \\tag{7.6} \\end{equation}$$\n\nor faster. The metabolic dynamics of interest are much slower than milliseconds. Although more detail about the cell's finer spatial structure is becoming increasingly available, it is unlikely, from a dynamic modeling standpoint, that spatial concentration gradients will be a key concern for dynamic modeling of metabolic states in bacterial cells\u00a0(Weisz, 1973). \n\n#### Estimating maximal reaction rates  \nReaction rates in cells are limited by the achievable kinetics. Few collections of enzyme kinetic parameters are available in the literature, see Table\u00a07.3. One observation from such collections is that the biomolecular association rate constant, $k_1$, for a substrate $(S)$ to an enzyme $(E)$; \n\n$$\\begin{equation} S + E \\stackrel{k_1}{\\longrightarrow} \\tag{7.7} \\end{equation}$$\n\nis on the order of $10^8 M^{-1} sec^{-1}$. This numerical value corresponds to the estimated theoretical limit, due to diffusional constraints\u00a0(Gutfreund, 1972). The corresponding number for macromolecules is about three orders of magnitude lower. \n\nUsing the order of magnitude values for concentrations of metabolites given above and for enzymes in the next section, we find the representative association rate of substrate to enzymes to be on the order of \n\n$$\\begin{equation} k_1 s e = 10^8 (M*sec)^{-1} * 10^{-4}M * 10^{-6}M = 0.01\\ M/sec \\tag{7.8} \\end{equation}$$\n\nthat translates into about \n\n$$\\begin{equation} k_1 s e = 10^6\\ molecules / \\mu m^3 sec \\tag{7.9} \\end{equation}$$\n\nthat is only one million molecules per cubic micron per second. However, the binding of the substrate to the enzyme is typically reversible and a better order of magnitude estimate for _net_ reaction rates is obtained by considering the release rate of the product from the substrate-enzyme complex, $X$. This release step tends to be the slowest step in enzyme catalysis\u00a0(Albery 1976, Albery 1977, Cleland 1975). Typical values for the release rate constant, $k_2$, \n\n$$\\begin{equation} X \\stackrel{k_2}{\\rightarrow} P + E \\tag{7.10} \\end{equation}$$\n\nare $100-1000\\ sec^{-1}$. If the concentration of the intermediate substrate-enzyme complex, $X$, is on the order of 1 $\\mu M$ we get a release rate of about \n\n$$\\begin{equation} k_2x = 10^4\\ \\text{to}\\ 10^5 molecules/\\mu m^3 sec \\tag{7.11} \\end{equation}$$\n\nWe can compare the estimate in Eq. (7.9) to observed metabolic fluxes, see Table\u00a07.4. Uptake and secretion rates of major metabolites during bacterial growth represent high flux pathways. \n\n**Table 7.4:** Typical metabolic fluxes measured in _E. coli_ K12 MG1655 grown under oxic and anoxic conditions.\n\n\n\n#### Measured kinetic constants  \nThere are now several accessible sources of information that contain kinetic data for enzymes and the chemical transformation that they catalyze. For kinetic information, both BRENDA and SABIO-RK\u00a0(Wittig, 2006) are resources of literature curated constants, including rates and saturation levels, Table 7.2.2. Unlike stoichiometric information which is universal, kinetic parameters are highly condition-dependent. _In vitro_ kinetic assays typically do not represent in vivo conditions. Factors such as cofactor binding, pH, and unknown interactions with metabolites and proteins are likely causes. \n\n#### Thermodynamics  \nWhile computational prediction of enzyme kinetic rates is difficult, obtaining thermodynamic values is more feasible. Estimates of metabolite standard transformed Gibbs energy of formation can be derived using an approach called _group contribution method_ (Mavrovouniotis 1991). This method considers a single compound as being made up of smaller structural subgroups. The metabolite standard Gibbs energy of formation associated with structural subgroups commonly found in metabolites are available in the literature and in the NIST database\u00a0urlnist. To estimate the metabolite standard Gibbs energy of formation of the entire compound, the contributions from each of the subgroups are summed along with an origin term. The group contribution approach has been used to estimate standard transformed Gibbs energy of formation for 84% of the metabolites in the genome scale model of _E. coli_\u00a0(Feist 2007, Henry 2006, Henry 2007). \n\nThermodynamic values can also be obtained by integrating experimentally measured parameters and algorithms which implement sophisticated theory from biophysical chemistry\u00a0(Alberty 2003, Alberty 2006). Combining this information with the results from group contribution method provides standard transformed Gibbs energy of formation for 96% of the reactions in the genome-scale _E. coli_ model\u00a0(Feist 2007), see Figure 7.3b. \n\n### What are typical turnover times?  \nAs outlined in Chapter\u00a02, turnover times can be estimated by taking that ratio of the concentration relative to the flux of degradation. Both concentrations and fluxes have been estimated above. Some specific examples of estimated turnover times are now provided. \n\n#### Glucose turnover in rapidly growing E. coli cells  \nWith an intracellular concentration of glucose of 1 to 5 mM, the estimate of the internal glucose turnover time is \n\n$$\\begin{equation} \\tau_{glu} = \\frac{6-30*10^5\\ molecules/cell}{4.2 * 10^5\\ \\text{to}\\ 8.4*10^5\\ molecules/ \\mu m^3 /sec} = 1\\ \\text{to} \\ 8\\  sec \\tag{7.12} \\end{equation}$$\n\n#### Response of red cell glycolytic intermediates  \nA typical glycolytic flux in the red cell is about 1.25 mM/hr. By using this number and measured concentrations, we can estimate the turnover times for the intermediates of glycolysis by simply using: \n\n$$\\begin{equation} t_R = \\frac{x_{avg}}{1.25 \\ mM/hr} \\tag{7.13} \\end{equation}$$\n\nThe results are shown in Table\u00a07.5. We see the sharp distribution of turnover times that appears. Note that the turnover times are set by the relative concentrations since the flux through the pathway is the same. Thus the least abundant metabolites will have the fastest turnover. At a constant flux, the relative concentrations are set by the kinetic constants. \n\n**Table 7.5:** Turnover times for the glycolytic intermediates in the red blood cell. The glycolytic flux is assumed to be 1.25 mM/hr = 0.35 $\\mu M/sec$ and the Rapoport-Luebering shunt flux is about 0.5 mM/hr. Table adapted from (Joshi, 1990).\n\n\n\n#### Response of the energy charge  \nExchange of high energy bonds between the various carriers is on the order of minutes. The dynamics of this energy pool occur on the middle time scale of minutes as described earlier, see Figure\u00a07.4. \n\n\n\n**Figure 7.4:** Responses in energy transduction processes in cells. (a) Effect of addition of glucose on the energy charge of Ehrlich ascites tumor cells. Redrawn based on\u00a0(Atkinson, 1977). (b) Transient response of the transmembrane gradient, from\u00a0(Konings, 1983). Generation of a proton motive force in energy starved _S.\u00a0cremoris_ upon addition of lactose (indicated by arrows) at different times after the start of starvation (t=0).  \n\n#### Response of transmembrane charge gradients\nCells store energy by extruding protons across membranes. The consequence is the formation of an osmotic and charge gradient that results in the so-called _proton motive force,_ denoted as $\\Delta \\mu_{H^+}$. It is defined by: \n\n$$\\begin{equation} \\Delta \\mu_{H^+} = \\Delta \\Psi - Z\\Delta pH \\tag{7.14} \\end{equation}$$\n\nwhere $\\Delta \\Psi$ is the charge gradient and $\\Delta pH$ is the hydrogen ion gradient. The parameter $Z$ takes a value of about 60 mV under physiological conditions. The transient response of gradient establishment is very rapid, Figure\u00a07.4. \n\n(Konings, 1983)\n\n#### Conversion between different forms of energy  \nIf energy is to be readily exchanged between transmembrane gradients and the high energy phosphate bond system, their displacement from equilibrium should be about the same. Based on typical ATP, ADP, and $P_i$ concentrations, one can calculate the transmembrane gradient to be about -180mV. Table\u00a07.6 shows that observed values for the transmembrane gradient, $\\Delta \\widetilde{\\mu}$, are on the order of -180 to -220 mV. It is interesting to note that the maximum gradient that a bi-lipid layer can withstand is on the order of -280mV\u00a0(Konings, 1983), based on electrostatic considerations. \n\n**Table 7.6:** Typical values (mV) for the transmembrane electrochemical potential gradient, reproduced from (Konings, 1983).\n\n\n\n#### What are typical power densities?  \nThe metabolic rates estimated above come with energy transmission through key cofactors. The highest energy production and dissipation rates are associated with energy transducing membranes. The ATP molecule is considered to be an energy currency of the cell, allowing one to estimate the power density in the cell/organelle based on the ATP production rate. \n\n#### Power density in mitochondria  \nThe rate of ATP production in mitochondria can be measured. Since we know the energy in each phosphate bond and the volume of the mitochondria, we can estimate the volumetric rate of energy production in the mitochondria. \n\nReported rates of ATP production in rat mitochondria from succinate are on the order of $6*10^{-19}$ mol ATP/mitochondria/sec \u00a0Schwerzmann86, taking place in a volume of about 0.27 $\\mu m^3$. The energy in the phosphate bond about is -52kJ/mol ATP at physiological conditions. These numbers lead to the computation of a per unit volume energy production rate of $2.2*10^{-18}$ mol ATP/$\\mu m^3/sec$, or $10^{-13}W/\\mu m^3\\ (0.1 pW/\\mu m^3)$. \n\n#### Power density in chloroplast of green algae  \nIn _Chlamydomonas reinhardtii_, the rate of ATP production of chloroplast varies between $9.0*10^{-17}\\ \\text{to}\\ 1.4*10^{-16}$ mol ATP/chloroplast/sec depending on the light intensity\u00a0(Baroli 2003, Burns 1990, Melis 2000, Ross 1995) in the volume of 17.4 $\\mu m^3$\u00a0(Harris 1989a). Thus, the volumetric energy production rate of chloroplast is on the order of $5*10^{-18}$ mol ATP/$\\mu m^3/sec$, or $3*10^{-13}W/\\mu m^3\\ (0.3 pW/\\mu m^3)$.\n\n#### Power density in rapidly growing E. coli cells:  \nA similar estimate of energy production rates can be performed for microorganisms. The aerobic glucose consumption of _E. coli_ is about 10 mmol/gDW/hr. The weight of a cell is about $2.8*10^{-13}$ gDW/cell. The ATP yield on glucose is about 17.5 ATP/glucose. These numbers allow us to compute the energy generation density from the ATP production rate of $1.4*10^{-17}$ mol ATP/cell/sec. These numbers lead to the computation of the power density of or $7.3*10^{-13}W/\\mu m^3 O_2\\ (0.7 pW/\\mu m^3)$., that is a similar numbers computed for the mitochondria and chloroplast above. \n\n## Macromolecules\nWe now look at the abundance, concentration and turnover rates of macromolecules in the bacterial cell. We are interested in the genome, RNA and protein molecules. \n\n### What are typical characteristics of a genome?  \nSizes of genomes vary significantly amongst different organisms, see Table\u00a07.7. For bacteria, they vary from about 0.5 to 9 million base pairs. The key features of the _E. coli_ K-12 MG1655 genome are summarized in Table\u00a07.8. There are about 4500 ORFs on the genome of an average length of about 1kb. This means that the average protein size is 316 amino acids, see Figure\u00a07.3c. \n\n**Table 7.7:** Genome sizes. A selection of representative genome sizes from the rapidly growing list of organisms whose genomes have been sequenced. Adapted from Kimball's Biology Pages.\n\n\n\n**Table 7.8:** Some features of the _E. coli_ genome. From\u00a0(Blattner 1997).\n\n\n\nThe number of RNA polymerase binding sites is estimated to be about 2800, leading to a estimate of about 1.6 ORFs $(\\approx 4.4*10^6/2400)$ per transcription unit. There are roughly 3000 copies of the RNA polymerase present in an _E. coli_ cell\u00a0(Wagner 2000). Thus if 1000 of the transcription units are active at any given time, there are only 2-3 RNA polymerase molecules available for each transcription unit. The promoters have different binding strength and thus recruit a different number of RNA polymerase molecules each. ChIP-chip data can be used to estimate this distribution. \n\n### What are typical protein concentrations?  \nCells represent a fairly dense solution of protein. One can estimate the concentration ranges for individual enzymes in cells. If we assume that the cell has about 1000 proteins with an average molecular weight of 34.7kD, as is typical for an _E. coli_ cell, see Figure\u00a07.3c, and given the fact that the cellular biomass is about 15% protein, we get: \n\n$$\\begin{equation} e_{tot} \\approx \\frac{1\\ gm/cm^3 * 0.15}{1000 * 34700 gm/mole} = 4.32 \\mu M \\tag{7.15} \\end{equation}$$\n\nThis estimate is, indeed, the range into which the _in vivo_ concentration of most proteins fall. It corresponds to about 2500 molecules of a particular protein molecule per cubic micron. As with metabolites there is a significant distribution around the estimate of Eq. (7.15). Important proteins such as the enzymes catalyzing major catabolic reactions tend to be present in higher concentrations, and pathways with smaller fluxes have their enzymes in lower concentrations. It should be noted that we are not assuming that all these proteins are in solution; the above number should be viewed more as a molar density. \n\nThe distribution about this mean is significant, Figure\u00a07.3d. Many of the proteins in _E. coli_ are in concentrations as low as a few dozen per cell. The _E. coli_ cell is believed to have about 200 major proteins which brings our estimate for the abundant ones to about 12,000 copies per cell. The _E. coli_ cell has a capacity to carry about 2.0-2.3 million protein molecules. \n\n### What are typical fluxes?  \nThe rates of synthesis of the major classes of macromolecules in _E. coli_ are summarized in Table\u00a07.9. The genome can be replicated in 40 min with two replication forks. This means that the speed of DNA polymerase is estimated to be \n\n$$\\begin{equation} \\text{rate of DNA polymerase} = \\frac{4.4*10^6\\ \\text{bp}}{2*40*60} \\approx 900\\ \\text{bp/sec/fork} \\tag{7.16} \\end{equation}$$\n\nRNA polymerase is much slower at 40-50 bp/sec and the ribosomes operate at about 12-21 peptide bonds per ribosome per second. \n\n#### Protein synthesis capacity in _E. coli_\nWe can estimate the number of peptide bonds (pb) produced by _E. coli_ per second. To do so we will need the rate of peptide bond formation by the ribosome (12 to 21 bp/ribosome/sec\u00a0(Bremer 1996, Dennis 1974, Young 1976)); and number of ribosomes present in the _E. coli_ cell $(7*10^3\\ \\text{to} \\ 7*10^4$ ribosomes/cell depending on the growth rate\u00a0(Bremer 1996)). So the total number of the peptide bonds that _E. coli_ can make per second is on the order of: $8*10^4\\ \\text{to}\\ 1.5*10^6$ pb/cell/sec\n\nThe average size of a protein in _E. coli_ is about 320 amino acids. At about 45 to 60 min doubling time, the total amount of protein produced by _E. coli_ per second is ~300 to 900 protein molecules/cell/sec. This is equivalent to $1\\ \\text{to}\\ 3*10^6$ molecules/cell/h as a function of growth rate, about the total number of protein per cell given above. \n\n#### Maximum protein production rate from a single gene in murine cells  \nThe total amount of the protein formed from a single gene in the mammalian cell can be estimated based on the total amount of mRNA present in the cytoplasm from a single gene, the rate of translation of the mRNA molecule by ribosomes, and the ribosomal spacing\u00a0(Savinell 1989). Additional factors needed include gene dosage (here taken as 1), rate of mRNA degradation, velocity of the RNA polymerase II molecule, and the growth rate\u00a0(Savinell 1989). \n\nMurine hybridoma cell lines are commonly used for antibody production. For this cell type, the total amount of mRNA from a single antibody encoding gene in the cytoplasm is on the order of 40,000 mRNA molecules/cell\u00a0(Gilmore 1979, Schibler 1978) the ribosomal synthesis rate is on the order of 20 nucleotides/sec\u00a0[Potter72], and the ribosomal spacing on the mRNA is between 90-100 nucleotides\u00a0(Christensen 1987, Potter 1972). Multiplying these numbers, we can estimate the protein production rate in a hybridoma cell line to be approximately 3000 - 6000 protein molecules/cell/sec. \n\n### What are the typical turnover times?  \nThe assembly of new macromolecules such as RNA and proteins requires the source of nucleotides and amino acids. These building blocks are generated by the degradation of existing RNA molecules and proteins. Many cellular components are constantly degraded and synthesized. This process is commonly characterized by the turnover rates and half-lives. Intracellular protein turnover is experimentally assessed by an addition of an isotope-labeled amino acid mixture to the normally growing or non-growing cells\u00a0(Levine 1965, Pratt 2002). It has been shown that the rate of breakdown of an individual proteins is on the order of 2-20% per hour in _E. coli_ culture\u00a0(Levine 1965, Neidhardt 1996). \n\n## Cell Growth and Phenotypic Functions\n### What are typical cell-specific production rates?\nThe estimated rates of metabolism and macromolecular synthesis can be used to compute various cellular functions and their limitations. Such computations can in turn be used for bioengineering design purposes, environmental roles and impacts of microorganisms, and for other purposes. We provide a couple of simple examples. \n\n#### Limits on volumetric productivity\n_E. coli_ is one of the most commonly used host organisms for metabolic engineering and overproduction of metabolites. In many cases, the glycolytic flux acts as a carbon entry point to the pathway for metabolite overproduction\u00a0(Eiteman 2008, Jantama 2008, Yomano 2008, Zhu 2008). Thus, the substrate uptake rate (SUR) is one of the critical characteristics of the productive capabilities of the engineered cell. \n\nLet us examine the wild-type _E. coli_ grown on glucose under anoxic conditions. As shown in Table 7.4, the (SUR) is on the order of 15-20 mmol glucose/gDW/h which translates into 1.5 gm glucose/L/h at cell densities of (VP has number). Theoretically, if all the carbon source (glucose) is converted to the desired metabolite the volumetric productivity will be approximately 3 g/L/h. \n\nThe amount of cells present in the culture, play a significant role in production potential. In the industrial settings, the cell density is usually higher which increases the volumetric productivity. Some metabolic engineered strain designs demonstrate higher SUR\u00a0(Portnoy 2008) that also leads to the increase in volumetric productivity. \n\n#### Photoautotrophic growth  \n_Chlorella vulgaris_ is a single-celled green algae that uses light to generate energy necessary for growth. At the top rate of photosynthesis, the specific oxygen production rate (SOPR) can be estimated to be between 20-400 fmol $O_2$/cell/h\u00a0(Lee 1994a). Algae biotechnology is drawing increasing interest due to its potential for production of biofuels and fine chemicals\u00a0(Lee 1994a). However, a lack of suitable photobioreactors (PBR) makes the cost of algally-derived compounds high. One of the key limiting factors for PBR is the light source; however, light-emitting diodes (LED) can be employed for these purposes. \n\nLet us now use order of magnitude calculations to estimate the light requirement for an algae photobioreactor using _C. vulgaris_ as a model organism. Given the fact that maximum photosynthetic efficiency of _C. vulgaris_ is below 50% \u00a0(Kok 1960, Myers 1980, Pirt 1980) and one mole of photons (680 nm) is equivalent to 50W, we can estimate that in order to sustain the SOPR of 100 fmol $\\text{O}_2$/cell/h each cell must receive 40pW equivalent of photons\u00a0(Lee1994a). A conventional LED can provide $0.3\\ \\text{mW/cm}^2$ or $0.1\\ \\text{mW}$ per LED. With a cell density close to $10^9\\ \\text{cells/ml}$ and $80\\ \\text{cm}^3$ volume of the reactor\u00a0(Lee 1994a), the photobioreactor must include close to a 100 LED to sustain the growth of algae and oxygen production. \n\n### Balancing the fluxes and composition in an entire cell  \nThe approximate calculation procedures presented can be used to estimate the overall flows of mass and energy in a bacterial cell. Proteins are 55% of the dry weight of cells and their most energetically costly component, so let's begin such computation with the assumption that there are about $10^9$ amino acids found in the proteins of a single cell. With this starting point and the various data given in this chapter, we can roughly estimate all the major flows using a 60 min doubling time: \n\n* With approximately 316 amino acids found in a protein, we have to make about 3 million protein molecules. \n\n* If we take the ribosome to make 20 pb/sec = 72,000 pb/hr, (pb=peptide bond) the we require\n\n    $$\\begin{equation} \\frac{1,000,000,000}{72,000} = 14,000\\ \\text{ribosomes} \\tag{7.17} \\end{equation}$$\n  \n    to carry out this protein synthesis. \n\n* To make 14,000 ribosomes with each having 4,500 nt length RNA molecules (nt = nucleotide), we need \n\n    $$\\begin{equation} 14,000*4,500 = 63,000,000\\ \\text{nt}\\ \\tag{7.18} \\end{equation}$$\n    \n    assembled. In addition, there are 10 tRNAs of 80 nt in length per ribosome leading to an additional nucleotide requirement of \n\n    $$\\begin{equation} 10*80*14,000 = 11,200,000\\ \\text{nt}\\ \\tag{7.19} \\end{equation}$$\n    \n    for a grand total of approximately 75,000,000 for stable RNA molecule synthesis. \n\n* The total nucleotide synthesis for RNA will be 3000 RNA polymerase molecules synthesizing at the rate of 50 nt/sec or \n\n    $$\\begin{equation} 3000*50*3600 = 540,000,000\\ \\text{nt/hour}\\ \\tag{7.20} \\end{equation}$$\n\n* The fraction of RNA that is mRNA is 0.03 to 0.05\u00a0Rosenow01 or, \n\n    $$\\begin{equation} 540,000,000*(0.03\\ \\text{to}\\ 0.05) \\approx (16\\ \\text{to}\\ 25.0)*10^6\\ \\text{nt/cell/hr}\\ \\tag{7.21} \\end{equation}$$\n    \n    If the average mRNA length is 1100 nt then the cell needs to make on average 20,000 transcripts in one hour. \n\n* We have to make 3,000,000 proteins from 20,000 transcripts, or about 150 protein molecules per transcript. \n\n* The transcripts have a finite half live. On average, each transcript has a 5 min lifetime, or 300 sec. Due to structural constraints a ribosome can only bind every 50 nt to the mRNA, producing a maximum ribosomal loading of about 20 ribosomes per transcript. The rate of translation is 20 pb/sec. With the average length of the peptide being 316 amino acids, we can produce 1.25 protein/sec. This calculation estimated the maximum protein production from one transcript on the order of 375 protein molecules per transcript. \n\n* To synthesize the genome, we need $2*4,500,000 = 9,000,000\\ \\text{nt}$ to make the double stranded DNA. \n\n* Thus, the total metabolic requirement of amino acids and nucleotides in _E. coli_ per doubling is $1*10^9$ amino acids/cell/h and $5*10^8$ nt/cell/h. \n\nThese are the approximate overall material requirements. We also need energy to drive the process. Using Table\u00a07.4 we can estimate energy requirements for _E. coli_ under oxic and anoxic conditions. \n\n* Aerobically, at a doubling time of 1 hour, the glucose uptake rate is about 10 mmol/gDW/h, that is equivalent to $1.5*10^9$ molecules of glucose per cell per doubling. At 17.5 ATP produced per glucose he corresponding energy production is: $3*10^{10}$ ATP per cell per doubling. \n\n* Anaerobically, at a doubling time of 1.5 hours, the glucose uptake rate is about 18 mmol/gDW/h, which is equivalent to $4.5*10^9$ molecules of glucose/ cell/doubling. At 3 ATP per glucose the corresponding energy production is $1.4*10^{10}$ molecules ATP/cell/doubling. \n\n## Summary\n* Data on cellular composition and over all rates are available. \n\n* Order of magnitude estimation procedures exist through which one can obtain the approximate values for key quantities. \n\n* In this fashion, typical concentrations, fluxes and turnover times can be estimated. \n\n* An approximate quantitative overall multi-scale framework can be obtained for the function of complex biological processes. \n\n$\\tiny{\\text{\u00a9 B. \u00d8. Palsson 2011;}\\ \\text{This publication is in copyright.}\\\\ \\text{Subject to statutory exception and to the provisions of relevant collective licensing agreements,}\\\\ \\text{no reproduction of any part may take place without the written permission of Cambridge University Press.}}$\n", "meta": {"hexsha": "6f569f26e92be51ac0884fc699ae2b2b6f86eaeb", "size": 41467, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/education/sb2/chapters/sb2_chapter7.ipynb", "max_stars_repo_name": "z-haiman/MASSpy", "max_stars_repo_head_hexsha": "aeeed1e3f9d1058e9485247a86f85cb94eeecbc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/education/sb2/chapters/sb2_chapter7.ipynb", "max_issues_repo_name": "z-haiman/MASSpy", "max_issues_repo_head_hexsha": "aeeed1e3f9d1058e9485247a86f85cb94eeecbc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/education/sb2/chapters/sb2_chapter7.ipynb", "max_forks_repo_name": "z-haiman/MASSpy", "max_forks_repo_head_hexsha": "aeeed1e3f9d1058e9485247a86f85cb94eeecbc9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 105.7831632653, "max_line_length": 940, "alphanum_fraction": 0.7154363711, "converted": true, "num_tokens": 9156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16451646289656316, "lm_q2_score": 0.14223189137395392, "lm_q1q2_score": 0.02339948767993109}}
{"text": "# Prerequsites\n\n\n```python\n# log the time of the experiment\nfrom datetime import datetime\nimport time\n\nexp_time = datetime.now()\nexp_time_str = exp_time.strftime(\"_%H_%M_%S\")\ndate_str = exp_time.strftime(\"%m_%d_%y\")\n```\n\n\n```python\n# Path management for MacOS and Windows\nfrom pathlib import Path\nimport os, sys\n\nscriptPath = Path(sys.path[0])\nparentPath = Path(sys.path[0]).parent\n#libPath = Path(\"/home/tw329/GitHub/ONN_MNIST/\")\nlibPath = Path(\"C:\\\\Users\\\\Logan\\\\Documents\\\\GitHub\\\\ONN_MNIST\")\nsys.path.append(libPath.as_posix())\nsys.path.append(\"C:\\\\Users\\\\Logan\\\\Documents\\\\GitHub\\\\mcmahon_lab_devices\") \n\n# Set the working directory (to save the files)\nresultPath = scriptPath\n\nslmWeightPath = resultPath / \"slm_weights\"\nif not os.path.exists(slmWeightPath.as_posix()):\n    os.makedirs(slmWeightPath.as_posix())\n    \nphoneImagePath = resultPath / \"phone_images\"\nif not os.path.exists(phoneImagePath.as_posix()):\n    os.makedirs(phoneImagePath.as_posix())\n    \nsaveDataPath = resultPath / \"saved_data\"\nif not os.path.exists(saveDataPath.as_posix()):\n    os.makedirs(saveDataPath.as_posix())\n    \nprint(resultPath)\n```\n\n    D:\\McMahon lab Dropbox\\peter mcmahon\\tw329\\Experiments\\12_01_20_4bit_randy_aug_MLP_100_100_MPPC\n\n\n\n```python\nfrom __future__ import print_function\nimport os, sys\nimport argparse\nfrom IPython.core.debugger import set_trace\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\nimport numpy as np\nimport pandas\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\n```\n\n\n```python\n%matplotlib notebook\n```\n\n# Instrument Controls\n\n\n```python\n# Configure the SLM\nfrom src.slmpy import SLMdisplay   # Popoff's simple package for controlling SLM\n\nslm = SLMdisplay(isImageLock = True)\n\nLUT_used=\"AmpLUT_basedon_100120slmbackcali_140509_start5.lut\"\n\nslmParamFile = resultPath / ''.join([\"slm_info\", exp_time_str, \".txt\"])\nwith open(slmParamFile,'w') as slmparams:\n    slmparams.write('LUT\\t\\t\\t{}\\n'.format(LUT_used))\nslmparams.close()\n\n```\n\n    C:/Users/Logan/Documents/GitHub/ONN_MNIST\\src\\slmpy.py:39: wxPyDeprecationWarning: Call to deprecated item EmptyImage. Use :class:`Image` instead.\n      self.img = wx.EmptyImage(2,2)\n\n\n\n```python\nimport pyvisa\nfrom devices import Agilent54845A as AgilentOscope\n\nrm = pyvisa.ResourceManager(\"C:\\\\WINDOWS\\\\System32\\\\visa64.dll\")\ngpib_id = rm.list_resources()[-1]\noscope = AgilentOscope(rm.open_resource(gpib_id))\noscope.set_waveform_source(1)\n\ndef oscope_info(oscope):\n    measure_state = {}\n    measure_state[\"ID\"] = oscope.id()\n    measure_state[\"x_range\"] = oscope.get_xrange()\n    measure_state[\"x_unit\"] = oscope.get_xunits()\n    measure_state[\"y_range\"] = oscope.get_yrange()\n    measure_state[\"y_unit\"] = oscope.get_yunits()\n    measure_state[\"y_offset\"] = oscope.get_offset()\n    measure_state[\"y_bounds\"] = [oscope.get_bottom_bound(), oscope.get_top_bound()]\n    return measure_state\n```\n\n\n```python\n# Configure the phone\n\nfrom Android_Display_Control.Remote_Display.image_stream import AndroidOpenAccessoryBridge as AOAB\n\nPIXEL_VENDOR_ID = 0x18d1\nPIXEL_UNCONFIG_ID =  0x4ee7\nPIXEL_CONFIG_ID = 0x2d01\n\n# Create an AOAB object for managing data send/receive via USB\naoab = AOAB(PIXEL_VENDOR_ID, PIXEL_UNCONFIG_ID, \n  PIXEL_CONFIG_ID,\n  manufacturer='ImageStreamManufacturer',\n  model='ImageStream1',\n  description='Stream Images to Android',\n  version=1,\n  uri=('https://github.com/chris-blay/android-open-accessory-bridge'),\n  serial='AoabSerial')\n```\n\n    Exception ignored in: <function _AutoFinalizedObjectBase.__del__ at 0x0000018CD55C5C80>\n    Traceback (most recent call last):\n      File \"C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\usb\\_objfinalizer.py\", line 84, in __del__\n        self.finalize()\n      File \"C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\usb\\_objfinalizer.py\", line 144, in finalize\n        self._finalizer()\n      File \"C:\\Users\\Logan\\Anaconda3\\lib\\weakref.py\", line 552, in __call__\n        return info.func(*info.args, **(info.kwargs or {}))\n      File \"C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\usb\\_objfinalizer.py\", line 104, in _do_finalize_object_ref\n        obj._do_finalize_object()\n      File \"C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\usb\\_objfinalizer.py\", line 71, in _do_finalize_object\n        self._finalize_object()\n      File \"C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\usb\\backend\\libusb1.py\", line 604, in _finalize_object\n        _lib.libusb_unref_device(self.devid)\n    OSError: exception: access violation writing 0x0000000000000024\n\n\n\n```python\ndef PIL_to_bytestream(img_px):\n    array_px = np.array(img_px)\n    byte_array_px = bytearray()\n\n    for i in range(array_px.shape[0]):\n        for j in range(array_px.shape[1]):\n            byte_array_px.append(array_px[i, j, 0])\n            byte_array_px.append(array_px[i, j, 1])\n            byte_array_px.append(array_px[i, j, 2])\n\n    assert(len(byte_array_px) == 1920*1080*3)\n    return byte_array_px\n```\n\n\n```python\n# Load the phone pixel LUT\nlut_p = torch.zeros(1000, dtype=torch.uint8) \nwith open((resultPath/'PhoneLUT_100120_161444c30et20ms_1000.lut').as_posix(),'r') as lutfile:\n        for i in range(len(lut_p)):\n            aline = lutfile.readline().split()\n            lut_p[i] = int(aline[1])\nlutfile.close()\n```\n\n# Helper Functions\n\n\n```python\n\"\"\" Helper functions for generating phone and SLM patterns. \"\"\"\n\nfrom math import sqrt\n\ndef Wrap_vec_to_square (idx_vec, null_element=torch.tensor([-1])):\n    \n    if isinstance(null_element, int):\n        null_element = torch.tensor([null_element])\n        \n    a = int(sqrt(len(idx_vec)))\n    if len(idx_vec) < a*(a+1):\n        px_col_counts = a\n        last_row_supplements = a - 1 - (idx_vec.numel()-1)%a \n    if len(idx_vec) >= a*(a+1):\n        px_col_counts = a+1\n        last_row_supplements = a - (idx_vec.numel()-1)%(a+1)\n    \n    idx_vec = torch.cat((idx_vec, torch.repeat_interleave(null_element, last_row_supplements)))\n    idx_vec = idx_vec.view(-1, px_col_counts)\n    \n    return idx_vec\n\n# Image binarize functions\ndef binarize_img_by_percentile(img, rate):\n    img_b = (img<=np.percentile(img.numpy(), rate))\n    res_ones = int(img_b.sum() - rate/100.0 * img_b.numel())\n    vec_b = img_b.flatten()\n    vec_b[vec_b.nonzero()[:res_ones]] = 0\n    return vec_b.view(img_b.shape)\n\ndef add_surr(img,expan_r):\n    img_shape = np.array(img.shape)\n    expan_img = np.zeros(img_shape*expan_r)\n    expan_img[expan_r//2::expan_r,expan_r//2::expan_r] = img\n    return expan_img\n\ndef expand_pixels(img, expan_r):\n    img_temp = torch.repeat_interleave(img, expan_r, dim=0)\n    return torch.repeat_interleave(img_temp, expan_r, dim=1)\n\ndef Add_frame(pic, frame_px_value):\n    \n    frame = torch.zeros(pic.shape[0]+40, pic.shape[1]+40, dtype=pic.dtype)\n    frame[[0,-1],:] = frame_px_value\n    frame[:,[0,-1]] = frame_px_value\n    frame[20:-20, 20:-20] = pic\n    \n    return frame\n```\n\n# Correction Mask\n\n\n```python\nf_list = []\nfor f in os.listdir(saveDataPath):\n    if f.endswith('.pkl'):\n        f_list.append(f)\nf_list\n```\n\n\n\n\n    ['phonemask_blk600x600_antiatt_phone_mask_onsite_lb640_1_1012_092948.bmp.pkl',\n     'phonemask_blk600x600_antiatt_phone_mask_raw_1012_092948.pkl',\n     'phonemask_blk720x720_antiatt_phone_mask_onsite_lb450_1_1015_233224.bmp.pkl',\n     'phonemask_blk720x720_antiatt_phone_mask_raw_1015_233224.pkl']\n\n\n\n\n```python\ndef im_maxmin(img):\n    plt.figure()\n    plt.imshow(img)\n    plt.colorbar()\n    plt.title(f\"max/min = {img.max():.1f}/{img.min():.1f} = {img.max()/img.min():.2f}\")\n    plt.xlabel(f\"std/mean = {img.std():g}/{img.mean():g} = {img.std()/img.mean():g}\")\n    plt.show()\n```\n\n\n```python\nimport joblib\nmaskPath = saveDataPath\nmaskName = \"phonemask_blk720x720_antiatt_phone_mask_onsite_lb450_1_1015_233224.bmp.pkl\"\nmask_str = \"onsite\"\n# maskName = \"blk600x600_antiatt_phone_mask_raw_0911_142600.bmp\"\n# mask_str = \"rawmask\"\nphone_mask = joblib.load(saveDataPath / maskName)\n# if len(mask.shape)==3:\n#     mask = mask[:,:,1]\nphone_mask\nim_maxmin(phone_mask)\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:5: RuntimeWarning: divide by zero encountered in double_scalars\n      \"\"\"\n\n\n\n```python\nexpan_r = 5\nx_norm_expan = torch.repeat_interleave(torch.ones(28, 28), expan_r, dim=0)\nx_norm_expan = torch.repeat_interleave(x_norm_expan, expan_r, dim=1)\nx_norm_embedded = CenterEmbedding(x_norm_expan, torch.zeros(1920, 1080))\nsub_phone_mask = phone_mask * x_norm_embedded.numpy()\nsub_phone_mask = sub_phone_mask / sub_phone_mask.max()\nplt.figure()\nplt.imshow(sub_phone_mask)\nplt.show()\n```\n\n# Definition of the Neural Network\n\n\n```python\n\"\"\" Define digitized fully connected layers \"\"\"\n\n# Definition of an in-place digitization function.\ndef Digitize(tensor, quant_mode='det', levels=16, min_val=None, max_val=None):\n    if not min_val and not max_val:\n        min_val, max_val = tensor.min().item(), tensor.max().item()\n    tensor.clamp_(min_val, max_val).add_(-1*min_val).mul_(levels-1).div_(max_val-min_val)\n    if quant_mode == \"det\": \n        tensor.round_()\n    elif quant_mode == \"rand\":\n        tensor.add_(torch.rand(tensor.size(), device=tensor.device).add_(-0.5)).round_()\n    tensor.mul_(max_val-min_val).div_(levels-1).add_(min_val)\n    return tensor\n\nclass DigitizeLinear(nn.Linear):\n\n    def __init__(self,  *kargs, a_quant_mode=\"det\", w_quant_mode=\"det\", a_quant_levels=16, w_quant_levels=32, running_weight=0.001, **kwargs):\n        super(DigitizeLinear, self).__init__(*kargs, **kwargs)\n        self.act_quant_mode = a_quant_mode\n        self.weight_quant_mode = w_quant_mode\n        self.register_buffer(\"act_quant_levels\", torch.tensor(a_quant_levels))\n        self.register_buffer(\"weight_quant_levels\", torch.tensor(w_quant_levels))\n        self.register_buffer(\"running_weight\", torch.tensor(running_weight)) \n        self.register_buffer(\"running_min\", None)\n        self.register_buffer(\"running_max\", None)\n\n    def forward(self, input):\n\n        if not self.weight_quant_mode is None: # Set a flag to control weight digitization.\n            if not hasattr(self.weight,'org'):\n                self.weight.org=self.weight.data.clone()\n            self.weight.data=Digitize(self.weight.data, quant_mode=self.weight_quant_mode, levels=self.weight_quant_levels)\n\n        if not self.bias is None:\n            self.bias.org=self.bias.data.clone()    \n        out = nn.functional.linear(input, self.weight, bias=self.bias)\n\n        if not self.act_quant_mode is None: # A flag to control output digitization. \n            if self.training: # Update the running average of min and max only during training\n                with torch.no_grad():\n                    if not self.running_min and not self.running_max:\n                        self.running_min, self.running_max = out.min(), out.max()\n                    self.running_min = (1-self.running_weight) * self.running_min + self.running_weight * out.min()\n                    self.running_max = (1-self.running_weight) * self.running_max + self.running_weight * out.max()\n            out.data=Digitize(out.data, quant_mode=self.act_quant_mode, levels=self.act_quant_levels, min_val=self.running_min, max_val=self.running_max)\n    \n        return out\n```\n\n\n```python\n\"\"\" Define a generic QAT MLP structure (including perceptron) \"\"\"\n\nclass Net(nn.Module):\n    def __init__(self, Nunits, **kwargs):\n        super().__init__()\n        self.fcs = nn.ModuleList([DigitizeLinear(i,j,**kwargs) for i, j in zip(Nunits[:-1], Nunits[1:])])\n\n    def forward(self, X):\n        X = X.view(X.size(0), -1)\n        for i, fc in enumerate(self.fcs):\n            X = fc(X)\n            if fc is not self.fcs[-1]:\n                X = F.relu(X)\n        return X\n    \n    def set_digitize_config(self, a_quant_mode, w_quant_mode, a_quant_levels, w_quant_levels):\n        for fc in self.fcs:\n            fc.act_quant_mode = a_quant_mode\n            fc.weight_quant_mode = w_quant_mode\n            fc.act_quant_levels = torch.tensor(a_quant_levels)\n            fc.weight_quant_levels = torch.tensor(w_quant_levels)\n```\n\n\n```python\n\"\"\" Load the trained model \"\"\"\n\ndevice = \"cpu\"\n\nmodel = Net([784, 100, 100, 10])\nfor l in model.fcs:\n    l.running_min = torch.tensor(0.0)\n    l.running_max = torch.tensor(0.0)\nmodel_ckpt = torch.load(\"./RA_4bit_H2_100_100_lr_0.043_0.50_m_0.87_wep_6_randActDigi_v80_ep97.pt\", map_location=device)\nmodel_state_dict = model_ckpt[\"model_state_dict\"]\nmodel.load_state_dict(model_state_dict)\nmodel.to(device)\nmodel.eval()\n```\n\n\n\n\n    Net(\n      (fcs): ModuleList(\n        (0): DigitizeLinear(in_features=784, out_features=100, bias=True)\n        (1): DigitizeLinear(in_features=100, out_features=100, bias=True)\n        (2): DigitizeLinear(in_features=100, out_features=10, bias=True)\n      )\n    )\n\n\n\n\n```python\n\"\"\" Construct dataloaders \"\"\"\n\ntrainID_range = range(200) # ID of the samples to be passed through the NN\n\n# Import the test data loaders\nkwargs = {'num_workers': 1, 'pin_memory': True} if True else {}\n\ndata_mnist_test = datasets.MNIST('../ML_data', \n                                 train=False, \n                                 transform=transforms.Compose([transforms.ToTensor()]))\n\n# Remember to set the batch size to the length of train ID range, or the dataloader will draw sample one by one.\nsubset_data_loader = torch.utils.data.DataLoader(data_mnist_test, \n                                           batch_size=int(max(trainID_range)+1), \n                                           shuffle=False, **kwargs)\n\n# Remember to set the batch size to the length of train ID range, or the dataloader will draw sample one by one.\ntest_loader = torch.utils.data.DataLoader(data_mnist_test, \n                                           batch_size=1, \n                                           shuffle=False,  **kwargs)\n```\n\n# Notes on ONN Forward Propagation Implementation (Rev. 3)\n\nThe update equation from one neuron layer to the next:\n\n\\begin{equation}\nx_{i}^{L+1} = \\sigma(\\sum_{j}^N{W_{ij}^{L} x_{j}^{L}+b_i^{L}})    \n\\end{equation}\n\nwhere $x_j^L$ is the activation of neuron $j$ in layer $L=0,1,..$.\n\nSince the pixel values in an ONN are intensity encoded, including inputs, activations, and weights, the update equation needs to be modified such that the matrices and vectors to be loaded onto the ONN contain only non-negative numbers. In fact, the possible range of matrix and vector entries is actually limited to positive values, since the phone and SLM pixel values cannot infinitely approach zero in reality, due to hardware limitations. The following framework deals with the most general case where both phone and SLM pixel values cannot be extinguished to zero. If reality, if the resolution permits, the expression can be significantly simplified if either phone or SLM pixels can reach zero within the demanded accuracy.\n\nThe update equation is first rewritten into a vector form to facilitate the following discussion:\n\n\\begin{equation}\nX^{L+1} = \\sigma({W^{L} X^{L} + B^{L}})    \n\\end{equation}\n\nA note on symbol convention: any lower case letter represents a column vector (e.g., $b$, $x$); any captital letter represents a matrix (e.g., $W$, and $X$ actually indicates a batch of data $X = [x_0, x_1, ..., x_{B-1}]$); columns and rows of a matrix is represented in Python indexing convention (i.e., $W[,j]$ and $W[i,]$); element at row $i$ and column $j$ of matrix $W$ is written as $W[i,j]$ instead of $W_{ij}$; the $i$th element in vector a vector is also indicated with Python indexing convention (e.g., $x[i]$ instead of $x_i$). The superscript $L$ indicating the layer of NN is dropped here and below as long as it does not cause any confusion. \n\nTherefore, $W^L[i,j]$ is the weight from neuron i in layer L to neuron j in layer L+1, $X^L[j,k]$ is the actication of neuron j of data batch index k, $B^L[i,k]$ is the bias for neuron i in layer L.\n\nEach element in a row $W[i,]$ can be linearly mapped from interval $[\\text{min}(W[i,]), \\text{max}(W[i,])]$ to $[I_\\text{min}, I_\\text{max}]$, with $I_\\text{max}>I_\\text{min} \\geq 0$. More explicitely, the resultant matrix $\\tilde{W}$ is related to $W$ with the relation:\n\n\\begin{equation}\nW = \\hat{K}\\tilde{W} + \\hat{D}\\mathbb{1}\n\\end{equation}\n\nwhere\n\\begin{equation}\n\\hat{K}=\\frac{1}{I_\\text{max}-I_\\text{min}}diag\\{\\Delta W_i = \\text{max}(W[i,]) - \\text{min}(W[i,])\\}, \n\\hat{D} = \\frac{1}{I_\\text{max}-I_\\text{min}} diag \\{I_\\text{max} \\text{min}(W[i,]) - I_\\text{min} \\text{max}(W[i,]) \\}\n\\end{equation}\nand $\\mathbb{1}$ is all 1 matrix. (Tip: hat implies diagonal matrix; tilde implies the control signal to be sent to a device, such as phone or SLM).\n\n\nThe same transform can be performed on a data batch, which gives $X = \\tilde{X} \\hat{K}_X  +  \\mathbb{1}\\hat{D}_X$ ($\\hat{K}_X$ and $X$ switch position because the definiation of $X$ is transposed from that of $W$.)\n\nNow we can rewrite the update equation as\n\\begin{equation}\nX^{L+1}  = \\sigma( \\hat{K}  \\{\\tilde{W} \\tilde{X}^L\\} \\hat{K}_X  + \\hat{D} \\{\\mathbb{1} \\tilde{X}^L\\} \\hat{K}_X  + \\hat{K} \\{\\tilde{W}\\mathbb{1}\\}\\hat{D}_X + \\hat{D} \\mathbb{1}\\mathbb{1} \\hat{D}_X + b)\n\\end{equation}\n\n\nNote that the matrix products in curly brackets are to be measured expiermentally from the ONN output, and the other quantities are computed once and stored.\n\n\nThe reason to rewrite the update equation in this form is to carry out *each* inner product computation at the full pixel resolution of the smartphone and SLM. The matrices and vectors are always normalized to cover the entire dynamic range of the devices. The normalization factor is stored and later re-applied to the value readout from the ONN to recover the actual numerical value. \n\n\nMore specifically, the passing of NN activation from one layer to the next can be summarized as the following steps:\n1. Normalize $W$ to $\\tilde{W}$, which needs to be done only once for a trained NN and takes $O(MN)$ operations. \n2. Normalize $X$ to $\\tilde{X}$, which needs to be done for every input and layer and takes a total of $NBL$ multiplications. However, these operations can be waived if the phone pixel has high enough bit depth. Since the activations are usually non-negative numbers, it is possible to represent them with pixel intensity without any pre-processing.\n3. Load $\\tilde{X}$ to the phone to control pixel intensity and $\\tilde{W}$ to SLM to control transimission. In this way, $\\tilde{W}$ and $\\tilde{X}$ are both represented with the full resolutin of the devices.\n4. Measure the total pixel value in a region of interest that corresponds to the inner product $\\tilde{W}[i,]\\tilde{X}[,j]$ (read: the input to neuron $i$ for the data batch index $j$) in the captured camera image. In the ideal case, this signal can be measured by a single-pixel detector.\n5. Use the calibration model to find $\\tilde{W}[i,]\\tilde{X}[,j]$ based on the integrated pixel value in the regions of interest, obtained in step (4). \n6. After reading out all the entries of $\\tilde{W}\\tilde{X}$ (W_til_X_til), multiply it with $\\hat{D}$ and $\\hat{D_X}$ digitially, which were obtained in step (1) and (2).\n7. Derive $\\mathbb{1} \\tilde{X}$ (sum_X_til) and $\\tilde{W}\\mathbb{1}$ (sum_W_til) following similar steps as (5) and (6). Essentially they are just special cases of $\\tilde{W}\\tilde{X}$ with either $\\tilde{W} = \\mathbb{1}$ or $\\tilde{X} = \\mathbb{1}$.\n8. Add the computed terms $\\hat{K}\\tilde{W}\\tilde{X}\\hat{K}_X$ (Delta_W_Delta_X), $\\hat{D}\\mathbb{1}\\tilde{X}\\hat{K}_X$ (Offset_W_Delta_X),  $\\hat{K}\\tilde{W}\\mathbb{1}\\hat{D}_X$ (Delta_W_Offset_X), $\\hat{D} \\mathbb{1}\\mathbb{1}\\hat{D}_X$ (Offset_W_Offset_X), and $b$ digitally, and then apply the nonlinear activation function $\\sigma$ to obtain the activations of neurons.\n\n\n\n\n```python\n\"\"\"Auxilitary functions for simulating activation propation in ONN\"\"\"\n\ndef digitize(x, levels=8, min_val=None, max_val=None):\n    \"\"\"\n    digitize activations into the discrete steps, by rounding to the closest level.\n    levels: specifies the number of total discrete levels.\n    min_val: the x value to be mapped to the lowest level\n    max_val: the x value to be mapped to the highest level\n    \"\"\"\n\n    if not min_val and not max_val:\n        min_val, max_val = x.min(), x.max()\n    x = (levels-1)*(x - min_val)/(max_val-min_val)\n    x = x.round()\n    x = torch.min(torch.max(x, torch.zeros_like(x)), torch.ones_like(x)*(levels-1))\n    x = x*(max_val-min_val)/(levels-1) + min_val\n    return x\n\ndef Matrix_Linear_Mapping(W, target_interval):\n    \"\"\"\n    Transform each column of W with the following linear transform: \n    Argument target_interval=[a,b] specifies the lower and upper bound a and b.\n    The minimum of each column of W will be mapped to a, and the maximum of each W column mapped to b.\n    The rest of elements in the column are mapped in-between a and b with linear interporlation.\n    Such operation is repeated for each column individually.\n    \"\"\"\n    \n    W = W.type(torch.double)\n    W_mins, _ = torch.min(W, dim=0) \n    W_maxs, _ = torch.max(W, dim=0)\n    Delta_I = float(target_interval[1] - target_interval[0])\n    Delta_W = W_maxs - W_mins\n    K_W = torch.diag(Delta_W/Delta_I)\n    D_W = target_interval[1]*W_mins - target_interval[0]*W_maxs\n    offset = torch.mm(torch.repeat_interleave(D_W.view(1,-1), W.shape[0],dim=0), torch.diag(1/Delta_W))\n    W_til = torch.mm(W, torch.diag(Delta_I/Delta_W)) - offset\n    \n    return (W_til, K_W, torch.diag(D_W)/Delta_I)\n    \n\ndef ONN_layer_prop(layer, W_transform, X_transform, W_digitize_func=None, X_digitize_func=None, Act_digitize_func=None,  X=None,\n                     W_til_X_til=None, sum_W_til=None, sum_X_til=None):\n    \"\"\"\n    Forward propagate a batch of data for one layer.\n\n    layer: of type torch.nn.module, the layer to propagate the current batch of data through. Both W and b are derived from layer.\n    W_transform: the mapping from the W stored in layer to the control value to be applied to SLM.\n    X_transform: the mapping from the activation values stored in X to the control value to be applied to the smartphone.\n    Act_digitize_func: The function for digitizing the output activation. No digitization is performed if None is given.\n    W_digitize_func: The function for digitizing weight matrix W before the forward propagation. \n                     No digitization is performed if None is assigned to W_digitize_func as default.\n    X_digitize_func: The function for digitizing the batch data X before the forward propagation. \n                     No digitization is performed if None is assigned to X_digitize_func as default.\n    X: Inputs to the current NN layer. \n       If X is not given, an identity matrix is assigned to X as default, such that the W_til_X_til returned by the function equals W_til.\n       X.shape = [batch size, current NN layer width]\n    W: weight matrix derived from layer. W.shape = [current NN layer width, next NN layer size]\n    b: bias vector. b.shape = [next NN layer width]\n    \n    When no digitization is performed on W, X, or Wx+b, only linear stretching is performed on W and X, and the output of the function is \n    almost identical to the results obtained by prop(layer).\n    \"\"\"\n    \n    W = layer.weight.data.t()\n        \n    # Normalize W \n    (W_til, K_W, D_W) = W_transform(W)\n    \n    if X is None: # If X is not given, make it an identity matrix.\n        X = torch.eye(W.shape[0])\n        (X_til, K_X, D_X) = Matrix_Linear_Mapping(X, [0,1])\n    else: # Normalize X\n        (X_til, K_X, D_X) = X_transform(X.t())\n        (X_til, K_X, D_X) = (X_til.t(), K_X.t(), D_X.t())\n    \n    if W_digitize_func is not None:\n        W_til = W_digitize_func(W_til)\n        \n    if X_digitize_func is not None:\n        X_til = X_digitize_func(X_til)\n        \n    W_til_max = W_til[:,0].max()\n    X_til_max = X_til[0,:].max()\n    \n    # First simulate the three measurables from the ONN (defined in Notes on ONN Forward Propagation Implementation (Rev. 3)):\n    if W_til_X_til is None:\n        W_til_X_til = torch.mm(X_til, W_til) # tilde{WX} \n    if sum_X_til is None:\n        sum_X_til = torch.mm(X_til, torch.ones_like(W_til)) * W_til_max # sum(tilde{X[j,:]}), aka the sum of all activations of batch index j.   \n    if sum_W_til is None:\n        sum_W_til = torch.mm(torch.ones_like(X_til), W_til) * X_til_max# sum(tilde{W[:,i]}), aka the sum of all weights into neuron i.\n    \n    # The following terms are defined in Notes on ONN Forward Propagation Implementation (Rev. 3)\n    Delta_W_Delta_X = torch.mm(torch.mm(K_X, W_til_X_til), K_W) \n    Delta_W_Offest_X = torch.mm(torch.mm(K_X, sum_X_til), D_W) / W_til_max\n    Offset_W_Delta_X = torch.mm(D_X, torch.mm(sum_W_til, K_W)) / X_til_max\n    Offset_W_Offset_X = torch.mm(D_X, torch.mm(torch.ones_like(W_til_X_til)*W_til.shape[0], D_W)) \n    \n    Wx = Delta_W_Delta_X + Delta_W_Offest_X + Offset_W_Delta_X + Offset_W_Offset_X  # Wx\n    Wx_b = Wx + torch.repeat_interleave(layer.bias.view(1,-1), W_til_X_til.shape[0], dim=0).type(torch.double) # Wx+b\n    if Act_digitize_func is not None:\n        Wx_b = Act_digitize_func(Wx_b) # digitize(Wx+b)\n    a = F.relu(Wx_b) # ReLU(digitize(Wx+b))\n\n    return {\"norm(W)norm(X)\": W_til_X_til, \"sum(norm(X))\": sum_X_til, \"sum(norm(W))\": sum_W_til, \"Wx\": Wx, \"Wx+b\": Wx_b, \"a\": a}\n```\n\n\n```python\n# Calculate the ground truth of activations of each layer \n# by Propagating each test sample through the trained NN and record activation of each layer.\nimport pandas\n\nX, data_labels = next(iter(subset_data_loader))\nX = X.view(X.size(0), -1)\nX0 = X\n\ndf_layer = {}\n\n# Define the transform and quantization functions for all layers:\nW_transform = lambda W: Matrix_Linear_Mapping(W, [5,2**8-1])\nX_transform = lambda X: Matrix_Linear_Mapping(X, [0,1000-1])\nW_digitize = lambda W: Digitize(W.clone(), levels=2**8-5) # levels of quantization for W\nX_digitize = lambda X: Digitize(X.clone(), levels=1000) # levels of quantization for X\n# One very strange thing is that you cannot lambda function dictionary\n\nfor l, layer in enumerate(model.fcs):\n    # Calculate the ground truth activation by passing through one layer\n    layer.act_quant_mode=None\n    layer.weight_quant_mode=None\n    X0 = F.relu(layer(X0))\n    \n    # Propagate the batch for one layer\n    Act_digitize = lambda X: Digitize(X.clone(), levels=2**4, min_val=layer.running_min.item(), max_val=layer.running_max.item()) # levels of quantization for y=Wx+b\n    results = ONN_layer_prop(layer, W_transform, X_transform, \\\n                             W_digitize_func=W_digitize, X_digitize_func=X_digitize, Act_digitize_func=Act_digitize, X=X)    \n    X = results[\"a\"] # The activation of the current layer is the input to the next layer. \n    \n    results[\"a_true\"] = X0\n    df = {}\n    for k in results.keys():\n        df[k] = pandas.DataFrame(results[k].detach().numpy()).stack(level=-1)\n    df_layer[l] = pandas.concat(df, axis=1)\n        \n# Concatenate the df for each sample into an even larger one to include all the samples spcified.    \ndf_all_acts = pandas.concat(df_layer, axis=0, \\\n                            keys=df_layer.keys(), names=[\"layer\", \"test_ID\", \"output node\"])\ndf_all_acts.index = df_all_acts.index.swaplevel(0,1)\n```\n\n\n```python\ndf_all_acts\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th></th>\n      <th>norm(W)norm(X)</th>\n      <th>sum(norm(X))</th>\n      <th>sum(norm(W))</th>\n      <th>Wx</th>\n      <th>Wx+b</th>\n      <th>a</th>\n      <th>a_true</th>\n    </tr>\n    <tr>\n      <th>test_ID</th>\n      <th>layer</th>\n      <th>output node</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">0</th>\n      <th rowspan=\"5\" valign=\"top\">0</th>\n      <th>0</th>\n      <td>7435548.0</td>\n      <td>18435480.0</td>\n      <td>101575323.0</td>\n      <td>-15.719175</td>\n      <td>-15.587848</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>9019478.0</td>\n      <td>18435480.0</td>\n      <td>99886014.0</td>\n      <td>-3.035051</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>9160499.0</td>\n      <td>18435480.0</td>\n      <td>95635269.0</td>\n      <td>-1.905754</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>9690888.0</td>\n      <td>18435480.0</td>\n      <td>101176722.0</td>\n      <td>2.341606</td>\n      <td>5.428436</td>\n      <td>5.428436</td>\n      <td>2.607136</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>11035015.0</td>\n      <td>18435480.0</td>\n      <td>94579326.0</td>\n      <td>13.105385</td>\n      <td>12.433863</td>\n      <td>12.433863</td>\n      <td>12.107492</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <th>...</th>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">199</th>\n      <th rowspan=\"5\" valign=\"top\">2</th>\n      <th>5</th>\n      <td>596998.0</td>\n      <td>2243745.0</td>\n      <td>10846143.0</td>\n      <td>-502.093804</td>\n      <td>-515.057654</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>604275.0</td>\n      <td>2243745.0</td>\n      <td>9649341.0</td>\n      <td>-495.412649</td>\n      <td>-515.057654</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>1273638.0</td>\n      <td>2243745.0</td>\n      <td>10318671.0</td>\n      <td>119.142521</td>\n      <td>94.972668</td>\n      <td>94.972668</td>\n      <td>101.693199</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>1021207.0</td>\n      <td>2243745.0</td>\n      <td>12271716.0</td>\n      <td>-112.619283</td>\n      <td>-108.370772</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>682060.0</td>\n      <td>2243745.0</td>\n      <td>11444544.0</td>\n      <td>-423.996730</td>\n      <td>-413.385933</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n  </tbody>\n</table>\n<p>42000 rows \u00d7 7 columns</p>\n</div>\n\n\n\n\n```python\nprint(data_labels[50])\ndf_all_acts.loc[(50,0)]\n```\n\n    tensor(6)\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:2: PerformanceWarning: indexing past lexsort depth may impact performance.\n      \n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>norm(W)norm(X)</th>\n      <th>sum(norm(X))</th>\n      <th>sum(norm(W))</th>\n      <th>Wx</th>\n      <th>Wx+b</th>\n      <th>a</th>\n      <th>a_true</th>\n    </tr>\n    <tr>\n      <th>output node</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>10328027.0</td>\n      <td>20142450.0</td>\n      <td>101575323.0</td>\n      <td>0.475091</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>10031575.0</td>\n      <td>20142450.0</td>\n      <td>99886014.0</td>\n      <td>-1.898899</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>11218257.0</td>\n      <td>20142450.0</td>\n      <td>95635269.0</td>\n      <td>7.604060</td>\n      <td>5.428436</td>\n      <td>5.428436</td>\n      <td>6.597994</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>11818030.0</td>\n      <td>20142450.0</td>\n      <td>101176722.0</td>\n      <td>12.407047</td>\n      <td>12.433863</td>\n      <td>12.433863</td>\n      <td>12.708588</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>9299017.0</td>\n      <td>20142450.0</td>\n      <td>94579326.0</td>\n      <td>-7.765229</td>\n      <td>-8.582420</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>95</th>\n      <td>8049976.0</td>\n      <td>20142450.0</td>\n      <td>105060834.0</td>\n      <td>-17.767560</td>\n      <td>-15.587848</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>96</th>\n      <td>9271061.0</td>\n      <td>20142450.0</td>\n      <td>97347555.0</td>\n      <td>-7.989101</td>\n      <td>-8.582420</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>97</th>\n      <td>10241632.0</td>\n      <td>20142450.0</td>\n      <td>106398495.0</td>\n      <td>-0.216761</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>98</th>\n      <td>9954893.0</td>\n      <td>20142450.0</td>\n      <td>100877022.0</td>\n      <td>-2.512969</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>99</th>\n      <td>11442822.0</td>\n      <td>20142450.0</td>\n      <td>97679223.0</td>\n      <td>9.402378</td>\n      <td>5.428436</td>\n      <td>5.428436</td>\n      <td>8.418477</td>\n    </tr>\n  </tbody>\n</table>\n<p>100 rows \u00d7 7 columns</p>\n</div>\n\n\n\n# Generate Phone and SLM Images\n\n\n```python\n\"\"\" Generate the weight images to be applied to SLM and save them. \"\"\"\n# Pre-process the SLM weight matrix by shifting all elements to non-negative.\n\nimport numpy as np\nfrom utils.helper_functions import ConvertPhoneImageToSLMImage, NormalizeWeights, CenterEmbedding\n\n# Indicate the current NN layer (the 1st layer has index 0)\nL = 0\nexpan_r = 5\n\n# Convert weight matrix to SLM control values using EXACTLY the same sequence of functions as in ONN_layer_prop()\nW = model.fcs[L].weight.data.t()\nW_til,_,_ = W_transform(W)\nW_norm = W_digitize(W_til).t()\nW_norm = W_norm.round().type(torch.uint8)\n\nslm_weights_numpy = {}\n\nfor i in range(W_norm.size(0)):\n    # Add a frame for alignment, and embed in a canvas of phone display size\n    w_norm_expan = torch.repeat_interleave(W_norm[i,:].view(28,-1), expan_r, dim=0)\n    w_norm_expan = torch.repeat_interleave(w_norm_expan, expan_r, dim=1)\n    w_norm_embedded = CenterEmbedding(w_norm_expan, torch.zeros(1920, 1080, dtype=torch.uint8))\n    w_norm_slm = ConvertPhoneImageToSLMImage(w_norm_embedded, 1.0) # Convert the phone image to SLM image.\n\n    # Save the SLM patterns to image files.\n    w_norm_path = slmWeightPath / (f\"SLM_MLP_{expan_r}x_fc{L}_w{i}.bmp\")\n    w_norm_slm.save(w_norm_path.as_posix(), format = 'bmp') # PIL.Image.save can be saved as 8-bit greyscale bmp\n\n    \nw_norm_embedded = CenterEmbedding(torch.ones_like(w_norm_expan)*255, torch.zeros(1920, 1080, dtype=torch.uint8))\nw_norm_slm = ConvertPhoneImageToSLMImage(w_norm_embedded, 1.0) # Convert the phone image to SLM image.\n\n# Save the SLM patterns to image files.\nw_norm_path = slmWeightPath / (f\"SLM_MLP_{expan_r}x_fc{L}_wsum.bmp\")\nw_norm_slm.save(w_norm_path.as_posix(), format = 'bmp') # PIL.Image.save can be saved as 8-bit greyscale bmp\n    \n# Plot w_kaleidoscope \nprint(\"The normalized weight matrix to be applied on the SLM looks like below:\")\nfig, ax = plt.subplots()\nim = ax.imshow(w_norm_slm)\nfig.colorbar(im, ax=ax)\nplt.show()\n```\n\n    The normalized weight matrix to be applied on the SLM looks like below:\n\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n\n```python\n\"\"\" Generate the images to be displayed on the phone and save them. \"\"\"\n\ninput_data, data_labels = next(iter(subset_data_loader))\ninput_data = input_data.view(X.size(0), -1)\n\npx_margin = 1\nblankImage = torch.zeros(3, 1920, 1080, dtype=torch.uint8)\n\nfor i, batchIdx in enumerate(trainID_range):\n    \n    # x is the output of the previous layer L-1 (L>0) or the input data (L==0).\n    if L > 0:\n        x = torch.tensor(df_measured_acts[\"ORDERED\"].loc[batchIdx, L-1, :].values)\n        #x = torch.tensor(df_all_acts[\"a_true\"].loc[batchIdx, L-1, :].values) # test mode\n    elif L == 0:\n        x = input_data[batchIdx,:]\n    \n    # Normalize each x to its max and min and scale to 7 bit to match the dynamical range of the phone.\n    # The operations here are performed EXACTLY the same as in ONN_layer_prop()\n    x_til,_,_ = X_transform(x.view(-1,1))\n    x_norm = X_digitize(x_til.squeeze()).round().type(torch.long) # round() cannot be omitted for type(torch.long) sometimes work as floor(0)\n    \n    # Add the singla-pixel frame for image alignment.\n    imToPhone = blankImage.clone()\n    x_norm_expan = torch.repeat_interleave(x_norm.view(28,-1), expan_r, dim=0)\n    x_norm_expan = torch.repeat_interleave(x_norm_expan, expan_r, dim=1)\n    x_norm_spar = x_norm_expan\n    x_norm_spar[::expan_r,:] = 0\n    x_norm_spar[(expan_r-px_margin)::expan_r,:] = 0\n    x_norm_spar[:,::expan_r] = 0\n    x_norm_spar[:,(expan_r-px_margin)::expan_r] = 0\n    x_norm_embedded = CenterEmbedding(x_norm_spar, blankImage[1,:,:].type(torch.long))\n    imToPhone[1, :, :] = lut_p[x_norm_embedded.type(torch.long)] # no uniformness correction\n    #phone_corr_numpy = lut_p[(x_norm_embedded * sub_phone_mask).type(torch.long)]\n    #imToPhone[1, :, :] = phone_corr_numpy\n\n    # Save the generated image\n    imToPhone_PIL = transforms.ToPILImage()(imToPhone)\n    imToPhone_PIL.save((phoneImagePath / f\"test_{expan_r}x_gap2px_MLP_fc{L}_digit_{data_labels[batchIdx]}_{batchIdx:05d}.png\").as_posix())\n\n# Generate and save a black image to be displayed on the phone for background and power saving.\nblackImage_PIL = transforms.ToPILImage()(blankImage)\nblackImage_PIL.save((phoneImagePath / \"black.png\").as_posix())\n\nprint(\"The normalized weight matrix to be applied on the SLM looks like below:\")\nfig, ax = plt.subplots()\nim = ax.imshow(imToPhone_PIL)\nfig.colorbar(im, ax=ax)\nplt.show()\n```\n\n    The normalized weight matrix to be applied on the SLM looks like below:\n\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n\n```python\nConvertPhoneImageToSLMImage(imToPhone[1,:,:], 1.0).save((slmWeightPath / \"alignment_check\").as_posix(), format = 'bmp')\n```\n\n# Acquire Data\n\n\n```python\n\"\"\" Set up MPPC experiment scheme. \"\"\"\n\nrepeats = 100\noscope.set_range(6)\noscope.set_offset(2)\noscope_info(oscope)\n```\n\n\n\n\n    {'ID': 'HEWLETT-PACKARD,54845A,US40240103,A.04.50\\n',\n     'x_range': 0.0001,\n     'x_unit': 'SECOND',\n     'y_range': 6.0,\n     'y_unit': 'VOLT',\n     'y_offset': 2.0,\n     'y_bounds': [-1.0, 5.0]}\n\n\n\n\n```python\n\"\"\" Set up the (empty) dataframe table for taking data. \"\"\"\n\nimport pandas\n\nrepeats = 100\ntest_digit_idx = np.arange(20)\nnode_idx = [*range(100), \"sum\", \"bkg\"]\ntime_ranges = [0.0001, ]\n#rowMultiIdx = pandas.MultiIndex.from_product([test_digit_idx, node_idx, time_ranges, np.arange(repeats)], names=[\"test_ID\", \"output_node\", \"time_range\", \"repeats\"])\nrowMultiIdx = pandas.MultiIndex.from_product([node_idx, time_ranges, np.arange(repeats)], names=[\"output_node\", \"time_range\", \"repeats\"])\n#df_volTraces = pandas.DataFrame(index=rowMultiIdx, columns=np.arange(1004))\n\nphoneLoadPath = phoneImagePath \nslmLoadPath = slmWeightPath \n\nprint(phoneLoadPath)\nprint(slmLoadPath)\nprint(rowMultiIdx)\n#print(df_volTraces)\n```\n\n    D:\\McMahon lab Dropbox\\peter mcmahon\\tw329\\Experiments\\12_01_20_4bit_randy_aug_MLP_100_100_MPPC\\phone_images\n    D:\\McMahon lab Dropbox\\peter mcmahon\\tw329\\Experiments\\12_01_20_4bit_randy_aug_MLP_100_100_MPPC\\slm_weights\n    MultiIndex([(    0, 0.0001,  0),\n                (    0, 0.0001,  1),\n                (    0, 0.0001,  2),\n                (    0, 0.0001,  3),\n                (    0, 0.0001,  4),\n                (    0, 0.0001,  5),\n                (    0, 0.0001,  6),\n                (    0, 0.0001,  7),\n                (    0, 0.0001,  8),\n                (    0, 0.0001,  9),\n                ...\n                ('bkg', 0.0001, 90),\n                ('bkg', 0.0001, 91),\n                ('bkg', 0.0001, 92),\n                ('bkg', 0.0001, 93),\n                ('bkg', 0.0001, 94),\n                ('bkg', 0.0001, 95),\n                ('bkg', 0.0001, 96),\n                ('bkg', 0.0001, 97),\n                ('bkg', 0.0001, 98),\n                ('bkg', 0.0001, 99)],\n               names=['output_node', 'time_range', 'repeats'], length=10200)\n\n\n\n```python\n\"\"\" Perform the inference of the trained model with ONN on test digits, and save the data. \"\"\"\n\nimport joblib, pickle, time\n\nexp_time = datetime.now()\nsavePath = resultPath /  (f\"MLP_fc{L}_{expan_r}x_marg_1px_MPPC_{exp_time:%m%d_%H%M%S}\")\nprint(savePath)\nif not os.path.exists(savePath.as_posix()):\n    os.makedirs(savePath.as_posix())\n\noscope.instrument.write(\"TIM:RANG 0.0001\")\n\njoblib.dump([oscope_info(oscope),], savePath / 'exp_info.pkl')\ndataFile = pandas.HDFStore((savePath / \"mppc_vol_meas.h5\").as_posix())\n\n# write a black image to the phone to take the background\nblackImage_PIL = Image.open((phoneImagePath / \"black.png\").as_posix())\nblackImage_byte = PIL_to_bytestream(blackImage_PIL)\n\nfor idx in range(180, 200):\n#for idx in range(20):\n    t0 = time.time()\n    # Record background to capture potential voltage bias drift\n    aoab.write(blackImage_byte)\n    #time.sleep(0.5)\n    slmPattern_PIL = Image.open((slmLoadPath / f\"SLM_solid_0.bmp\").as_posix())\n    slm.updateArray((np.array(slmPattern_PIL)).astype('uint8'))\n    time.sleep(0.5)\n    \n    df = pandas.DataFrame(index=rowMultiIdx, columns=np.arange(1004))\n\n    for i in rowMultiIdx.get_level_values(\"repeats\").unique(): \n        trace = oscope.get_waveform()\n        df.loc[(\"bkg\", 0.0001, i), range(len(trace))] = trace\n        time.sleep(0.04)\n    print(f\"time_span=0.0001s, test_ID={idx}, label={data_labels[idx]}, output_node=bkg, voltage={trace.mean()}\")\n        \n    # Load the phone pattern\n    phonePattern_PIL = Image.open((phoneLoadPath / f\"test_{expan_r}x_gap2px_MLP_fc{L}_digit_{data_labels[idx]}_{idx:05d}.png\").as_posix())\n    phonePattern_byte = PIL_to_bytestream(phonePattern_PIL)\n    aoab.write(phonePattern_byte)\n    time.sleep(0.5) # Wait for the pattern applied to be stable\n    for n in rowMultiIdx.get_level_values(\"output_node\").unique().drop(\"bkg\"):\n        # refresh the slm pattern\n        slmPattern_PIL = Image.open((slmLoadPath / f\"SLM_MLP_{expan_r}x_fc{L}_w{n}.bmp\").as_posix())\n        slm.updateArray((np.array(slmPattern_PIL)).astype('uint8'))\n        time.sleep(0.5) # Wait for the pattern applied to be stable\n        \n        for i in rowMultiIdx.get_level_values(\"repeats\").unique(): \n            trace = oscope.get_waveform()\n            df.loc[(n, 0.0001, i), range(len(trace))] = trace\n            time.sleep(0.04)\n        print(f\"time_span=0.0001s, test_ID={idx}, label={data_labels[idx]}, output_node={n}, voltage={trace.mean()}\")\n            \n        if n == 10 and idx == 180:\n            print(\"20 s to exit anydesk\")\n            time.sleep(20)  \n            \n    t1 = time.time()\n    print(f\"Time consumed for 1 sample = {t1-t0} s\")\n    t0 = t1\n    dataFile[str(idx)]=df \n    \ndataFile.close()\naoab.write(blackImage_byte)\nprint(\"Finished! Safe to change code now.\")\n```\n\n    D:\\McMahon lab Dropbox\\peter mcmahon\\tw329\\Experiments\\12_01_20_4bit_randy_aug_MLP_100_100_MPPC\\MLP_fc0_5x_marg_1px_MPPC_1220_124131\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\IPython\\core\\interactiveshell.py:2878: PerformanceWarning: indexing past lexsort depth may impact performance.\n      raw_cell, store_history, silent, shell_futures)\n\n\n    time_span=0.0001s, test_ID=180, label=1, output_node=bkg, voltage=-0.0031165340915322304\n    time_span=0.0001s, test_ID=180, label=1, output_node=0, voltage=0.004261952359229326\n    time_span=0.0001s, test_ID=180, label=1, output_node=1, voltage=0.0043017929419875145\n    time_span=0.0001s, test_ID=180, label=1, output_node=2, voltage=0.0028117529582232237\n    time_span=0.0001s, test_ID=180, label=1, output_node=3, voltage=0.001362549839541316\n    time_span=0.0001s, test_ID=180, label=1, output_node=4, voltage=0.007617529947310686\n    time_span=0.0001s, test_ID=180, label=1, output_node=5, voltage=0.0004910359275527298\n    time_span=0.0001s, test_ID=180, label=1, output_node=6, voltage=0.00555677292868495\n    time_span=0.0001s, test_ID=180, label=1, output_node=7, voltage=0.005204183515161276\n    time_span=0.0001s, test_ID=180, label=1, output_node=8, voltage=0.003472111653536558\n    time_span=0.0001s, test_ID=180, label=1, output_node=9, voltage=0.001879482064396143\n    time_span=0.0001s, test_ID=180, label=1, output_node=10, voltage=0.0013326694024726748\n    20 s to exit anydesk\n    time_span=0.0001s, test_ID=180, label=1, output_node=11, voltage=0.005313745234161615\n    time_span=0.0001s, test_ID=180, label=1, output_node=12, voltage=0.003431274788454175\n    time_span=0.0001s, test_ID=180, label=1, output_node=13, voltage=0.0021832669153809547\n    time_span=0.0001s, test_ID=180, label=1, output_node=14, voltage=0.004253983963280916\n    time_span=0.0001s, test_ID=180, label=1, output_node=15, voltage=0.0010458168108016253\n    time_span=0.0001s, test_ID=180, label=1, output_node=16, voltage=0.0031195220071822405\n    time_span=0.0001s, test_ID=180, label=1, output_node=17, voltage=0.002644421998411417\n    time_span=0.0001s, test_ID=180, label=1, output_node=18, voltage=0.0031085656955838203\n    time_span=0.0001s, test_ID=180, label=1, output_node=19, voltage=0.002818725071847439\n    time_span=0.0001s, test_ID=180, label=1, output_node=20, voltage=-3.68526489182841e-05\n    time_span=0.0001s, test_ID=180, label=1, output_node=21, voltage=0.0032161353155970573\n    time_span=0.0001s, test_ID=180, label=1, output_node=22, voltage=0.0029571710620075464\n    time_span=0.0001s, test_ID=180, label=1, output_node=23, voltage=0.001761952298693359\n    time_span=0.0001s, test_ID=180, label=1, output_node=24, voltage=0.002108565764501691\n    time_span=0.0001s, test_ID=180, label=1, output_node=25, voltage=0.0019810758531093597\n    time_span=0.0001s, test_ID=180, label=1, output_node=26, voltage=0.0019153389148414135\n    time_span=0.0001s, test_ID=180, label=1, output_node=27, voltage=0.004915338475257158\n    time_span=0.0001s, test_ID=180, label=1, output_node=28, voltage=0.002556772902607918\n    time_span=0.0001s, test_ID=180, label=1, output_node=29, voltage=0.005300797522068024\n    time_span=0.0001s, test_ID=180, label=1, output_node=30, voltage=-0.00038645416498184204\n    time_span=0.0001s, test_ID=180, label=1, output_node=31, voltage=0.0031245017889887094\n    time_span=0.0001s, test_ID=180, label=1, output_node=32, voltage=0.007518924307078123\n    time_span=0.0001s, test_ID=180, label=1, output_node=33, voltage=0.0009322709520347416\n    time_span=0.0001s, test_ID=180, label=1, output_node=34, voltage=0.0003067729121539742\n    time_span=0.0001s, test_ID=180, label=1, output_node=35, voltage=0.006518924608826637\n    time_span=0.0001s, test_ID=180, label=1, output_node=36, voltage=0.002628485905006528\n    time_span=0.0001s, test_ID=180, label=1, output_node=37, voltage=0.0003555776784196496\n    time_span=0.0001s, test_ID=180, label=1, output_node=38, voltage=0.003910358529537916\n    time_span=0.0001s, test_ID=180, label=1, output_node=39, voltage=0.005588645581156015\n    time_span=0.0001s, test_ID=180, label=1, output_node=40, voltage=0.0033456177916377783\n    time_span=0.0001s, test_ID=180, label=1, output_node=41, voltage=0.0004571714380290359\n    time_span=0.0001s, test_ID=180, label=1, output_node=42, voltage=0.005701194982975721\n    time_span=0.0001s, test_ID=180, label=1, output_node=43, voltage=0.005355577450245619\n    time_span=0.0001s, test_ID=180, label=1, output_node=44, voltage=0.003864541882649064\n    time_span=0.0001s, test_ID=180, label=1, output_node=45, voltage=0.004826693329960108\n    time_span=0.0001s, test_ID=180, label=1, output_node=46, voltage=0.0015079681761562824\n    time_span=0.0001s, test_ID=180, label=1, output_node=47, voltage=0.0038097607903182507\n    time_span=0.0001s, test_ID=180, label=1, output_node=48, voltage=0.0014482071856036782\n    time_span=0.0001s, test_ID=180, label=1, output_node=49, voltage=0.009555776603519917\n    time_span=0.0001s, test_ID=180, label=1, output_node=50, voltage=0.0036384460981935263\n    time_span=0.0001s, test_ID=180, label=1, output_node=51, voltage=0.003015936119481921\n    time_span=0.0001s, test_ID=180, label=1, output_node=52, voltage=0.0044999998062849045\n    time_span=0.0001s, test_ID=180, label=1, output_node=53, voltage=0.005099601577967405\n    time_span=0.0001s, test_ID=180, label=1, output_node=54, voltage=0.0046075694262981415\n    time_span=0.0001s, test_ID=180, label=1, output_node=55, voltage=0.004411354660987854\n    time_span=0.0001s, test_ID=180, label=1, output_node=56, voltage=0.0026802788488566875\n    time_span=0.0001s, test_ID=180, label=1, output_node=57, voltage=0.005110557656735182\n    time_span=0.0001s, test_ID=180, label=1, output_node=58, voltage=0.004308765288442373\n    time_span=0.0001s, test_ID=180, label=1, output_node=59, voltage=0.003336653346195817\n    time_span=0.0001s, test_ID=180, label=1, output_node=60, voltage=0.002766932127997279\n    time_span=0.0001s, test_ID=180, label=1, output_node=61, voltage=0.001241035875864327\n    time_span=0.0001s, test_ID=180, label=1, output_node=62, voltage=0.0035458167549222708\n    time_span=0.0001s, test_ID=180, label=1, output_node=63, voltage=0.002668326487764716\n    time_span=0.0001s, test_ID=180, label=1, output_node=64, voltage=0.0046583665534853935\n    time_span=0.0001s, test_ID=180, label=1, output_node=65, voltage=0.0040099602192640305\n    time_span=0.0001s, test_ID=180, label=1, output_node=66, voltage=0.0004900398198515177\n    time_span=0.0001s, test_ID=180, label=1, output_node=67, voltage=0.00397410336881876\n    time_span=0.0001s, test_ID=180, label=1, output_node=68, voltage=0.0030049802735447884\n    time_span=0.0001s, test_ID=180, label=1, output_node=69, voltage=0.0014103585854172707\n    time_span=0.0001s, test_ID=180, label=1, output_node=70, voltage=0.0047051794826984406\n    time_span=0.0001s, test_ID=180, label=1, output_node=71, voltage=0.002912350697442889\n    time_span=0.0001s, test_ID=180, label=1, output_node=72, voltage=0.0026015935000032187\n    time_span=0.0001s, test_ID=180, label=1, output_node=73, voltage=0.0011762948706746101\n    time_span=0.0001s, test_ID=180, label=1, output_node=74, voltage=0.003565737046301365\n    time_span=0.0001s, test_ID=180, label=1, output_node=75, voltage=0.002744023920968175\n    time_span=0.0001s, test_ID=180, label=1, output_node=76, voltage=0.0018884462770074606\n    time_span=0.0001s, test_ID=180, label=1, output_node=77, voltage=-0.00038545820279978216\n    time_span=0.0001s, test_ID=180, label=1, output_node=78, voltage=0.006803784519433975\n    time_span=0.0001s, test_ID=180, label=1, output_node=79, voltage=0.003100597532466054\n    time_span=0.0001s, test_ID=180, label=1, output_node=80, voltage=0.0038207173347473145\n    time_span=0.0001s, test_ID=180, label=1, output_node=81, voltage=0.0005458167870528996\n    time_span=0.0001s, test_ID=180, label=1, output_node=82, voltage=0.001656374428421259\n    time_span=0.0001s, test_ID=180, label=1, output_node=83, voltage=0.0042161354795098305\n    time_span=0.0001s, test_ID=180, label=1, output_node=84, voltage=0.002466135658323765\n    time_span=0.0001s, test_ID=180, label=1, output_node=85, voltage=0.005720119457691908\n    time_span=0.0001s, test_ID=180, label=1, output_node=86, voltage=0.0044183265417814255\n    time_span=0.0001s, test_ID=180, label=1, output_node=87, voltage=0.002860557520762086\n    time_span=0.0001s, test_ID=180, label=1, output_node=88, voltage=0.0014472113689407706\n    time_span=0.0001s, test_ID=180, label=1, output_node=89, voltage=0.00440239068120718\n    time_span=0.0001s, test_ID=180, label=1, output_node=90, voltage=0.000887450238224119\n    time_span=0.0001s, test_ID=180, label=1, output_node=91, voltage=0.003822709433734417\n    time_span=0.0001s, test_ID=180, label=1, output_node=92, voltage=0.0022659364622086287\n    time_span=0.0001s, test_ID=180, label=1, output_node=93, voltage=0.0017340637277811766\n    time_span=0.0001s, test_ID=180, label=1, output_node=94, voltage=0.0018017928814515471\n    time_span=0.0001s, test_ID=180, label=1, output_node=95, voltage=0.005429283250123262\n    time_span=0.0001s, test_ID=180, label=1, output_node=96, voltage=0.0017410358414053917\n    time_span=0.0001s, test_ID=180, label=1, output_node=97, voltage=0.0038914342876523733\n    time_span=0.0001s, test_ID=180, label=1, output_node=98, voltage=0.003668326884508133\n    time_span=0.0001s, test_ID=180, label=1, output_node=99, voltage=0.00572211155667901\n    time_span=0.0001s, test_ID=180, label=1, output_node=sum, voltage=0.011390439234673977\n    Time consumed for 1 sample = 1214.491173505783 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '180'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\pandas\\io\\pytables.py:556: PerformanceWarning: \n    your performance may suffer as PyTables will pickle object types that it cannot\n    map directly to c-types [inferred_type->mixed-integer,key->axis1_level0] [items->None]\n    \n      self.put(key, value)\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\IPython\\core\\interactiveshell.py:3418: PerformanceWarning: \n    your performance may suffer as PyTables will pickle object types that it cannot\n    map directly to c-types [inferred_type->floating,key->block0_values] [items->Int64Index([   0,    1,    2,    3,    4,    5,    6,    7,    8,    9,\n                ...\n                 994,  995,  996,  997,  998,  999, 1000, 1001, 1002, 1003],\n               dtype='int64', length=1004)]\n    \n      exec(code_obj, self.user_global_ns, self.user_ns)\n\n\n    time_span=0.0001s, test_ID=181, label=8, output_node=bkg, voltage=-0.004434262402355671\n    time_span=0.0001s, test_ID=181, label=8, output_node=0, voltage=0.02280876412987709\n    time_span=0.0001s, test_ID=181, label=8, output_node=1, voltage=0.01699701137840748\n    time_span=0.0001s, test_ID=181, label=8, output_node=2, voltage=0.02129681222140789\n    time_span=0.0001s, test_ID=181, label=8, output_node=3, voltage=0.015394422225654125\n    time_span=0.0001s, test_ID=181, label=8, output_node=4, voltage=0.01727191172540188\n    time_span=0.0001s, test_ID=181, label=8, output_node=5, voltage=0.01662250980734825\n    time_span=0.0001s, test_ID=181, label=8, output_node=6, voltage=0.018840637058019638\n    time_span=0.0001s, test_ID=181, label=8, output_node=7, voltage=0.02551095560193062\n    time_span=0.0001s, test_ID=181, label=8, output_node=8, voltage=0.020379481837153435\n    time_span=0.0001s, test_ID=181, label=8, output_node=9, voltage=0.01432669349014759\n    time_span=0.0001s, test_ID=181, label=8, output_node=10, voltage=0.015709163621068\n    time_span=0.0001s, test_ID=181, label=8, output_node=11, voltage=0.014536852948367596\n    time_span=0.0001s, test_ID=181, label=8, output_node=12, voltage=0.015119521878659725\n    time_span=0.0001s, test_ID=181, label=8, output_node=13, voltage=0.016658367589116096\n    time_span=0.0001s, test_ID=181, label=8, output_node=14, voltage=0.015909362584352493\n    time_span=0.0001s, test_ID=181, label=8, output_node=15, voltage=0.015084661543369293\n    time_span=0.0001s, test_ID=181, label=8, output_node=16, voltage=0.0160507969558239\n    time_span=0.0001s, test_ID=181, label=8, output_node=17, voltage=0.016295816749334335\n    time_span=0.0001s, test_ID=181, label=8, output_node=18, voltage=0.02015637420117855\n    time_span=0.0001s, test_ID=181, label=8, output_node=19, voltage=0.015971114858984947\n    time_span=0.0001s, test_ID=181, label=8, output_node=20, voltage=0.014272908680140972\n    time_span=0.0001s, test_ID=181, label=8, output_node=21, voltage=0.024211155250668526\n    time_span=0.0001s, test_ID=181, label=8, output_node=22, voltage=0.01788545958697796\n    time_span=0.0001s, test_ID=181, label=8, output_node=23, voltage=0.015173305757343769\n    time_span=0.0001s, test_ID=181, label=8, output_node=24, voltage=0.01564442366361618\n    time_span=0.0001s, test_ID=181, label=8, output_node=25, voltage=0.015564740635454655\n    time_span=0.0001s, test_ID=181, label=8, output_node=26, voltage=0.01583864539861679\n    time_span=0.0001s, test_ID=181, label=8, output_node=27, voltage=0.019144423305988312\n    time_span=0.0001s, test_ID=181, label=8, output_node=28, voltage=0.020345615223050117\n    time_span=0.0001s, test_ID=181, label=8, output_node=29, voltage=0.01663247123360634\n    time_span=0.0001s, test_ID=181, label=8, output_node=30, voltage=0.013952190987765789\n    time_span=0.0001s, test_ID=181, label=8, output_node=31, voltage=0.01694721169769764\n    time_span=0.0001s, test_ID=181, label=8, output_node=32, voltage=0.017775896936655045\n    time_span=0.0001s, test_ID=181, label=8, output_node=33, voltage=0.01699502021074295\n    time_span=0.0001s, test_ID=181, label=8, output_node=34, voltage=0.017147410660982132\n    time_span=0.0001s, test_ID=181, label=8, output_node=35, voltage=0.0144721120595932\n    time_span=0.0001s, test_ID=181, label=8, output_node=36, voltage=0.013068725354969501\n    time_span=0.0001s, test_ID=181, label=8, output_node=37, voltage=0.019708165898919106\n    time_span=0.0001s, test_ID=181, label=8, output_node=38, voltage=0.019968127831816673\n    time_span=0.0001s, test_ID=181, label=8, output_node=39, voltage=0.02056972123682499\n    time_span=0.0001s, test_ID=181, label=8, output_node=40, voltage=0.018500996753573418\n    time_span=0.0001s, test_ID=181, label=8, output_node=41, voltage=0.01959860511124134\n    time_span=0.0001s, test_ID=181, label=8, output_node=42, voltage=0.014891434460878372\n    time_span=0.0001s, test_ID=181, label=8, output_node=43, voltage=0.021117528900504112\n    time_span=0.0001s, test_ID=181, label=8, output_node=44, voltage=0.011661353521049023\n    time_span=0.0001s, test_ID=181, label=8, output_node=45, voltage=0.020346615463495255\n    time_span=0.0001s, test_ID=181, label=8, output_node=46, voltage=0.014136453159153461\n    time_span=0.0001s, test_ID=181, label=8, output_node=47, voltage=0.018787847831845284\n    time_span=0.0001s, test_ID=181, label=8, output_node=48, voltage=0.015412351116538048\n    time_span=0.0001s, test_ID=181, label=8, output_node=49, voltage=0.01545916311442852\n    time_span=0.0001s, test_ID=181, label=8, output_node=50, voltage=0.016530876979231834\n    time_span=0.0001s, test_ID=181, label=8, output_node=51, voltage=0.018521912395954132\n    time_span=0.0001s, test_ID=181, label=8, output_node=52, voltage=0.011811751872301102\n    time_span=0.0001s, test_ID=181, label=8, output_node=53, voltage=0.014312748797237873\n    time_span=0.0001s, test_ID=181, label=8, output_node=54, voltage=0.006342629436403513\n    time_span=0.0001s, test_ID=181, label=8, output_node=55, voltage=0.02032768912613392\n    time_span=0.0001s, test_ID=181, label=8, output_node=56, voltage=0.014687251299619675\n    time_span=0.0001s, test_ID=181, label=8, output_node=57, voltage=0.021559759974479675\n    time_span=0.0001s, test_ID=181, label=8, output_node=58, voltage=0.015504981391131878\n    time_span=0.0001s, test_ID=181, label=8, output_node=59, voltage=0.013194222934544086\n    time_span=0.0001s, test_ID=181, label=8, output_node=60, voltage=0.012528885155916214\n    time_span=0.0001s, test_ID=181, label=8, output_node=61, voltage=0.01655976101756096\n    time_span=0.0001s, test_ID=181, label=8, output_node=62, voltage=0.020963149145245552\n    time_span=0.0001s, test_ID=181, label=8, output_node=63, voltage=0.017466137185692787\n    time_span=0.0001s, test_ID=181, label=8, output_node=64, voltage=0.02006075531244278\n    time_span=0.0001s, test_ID=181, label=8, output_node=65, voltage=0.021043824031949043\n    time_span=0.0001s, test_ID=181, label=8, output_node=66, voltage=0.016141433268785477\n    time_span=0.0001s, test_ID=181, label=8, output_node=67, voltage=0.01710757054388523\n    time_span=0.0001s, test_ID=181, label=8, output_node=68, voltage=0.018324701115489006\n    time_span=0.0001s, test_ID=181, label=8, output_node=69, voltage=0.01896812580525875\n    time_span=0.0001s, test_ID=181, label=8, output_node=70, voltage=0.011739043518900871\n    time_span=0.0001s, test_ID=181, label=8, output_node=71, voltage=0.01837848499417305\n    time_span=0.0001s, test_ID=181, label=8, output_node=72, voltage=0.013200199231505394\n    time_span=0.0001s, test_ID=181, label=8, output_node=73, voltage=0.015395416878163815\n    time_span=0.0001s, test_ID=181, label=8, output_node=74, voltage=0.012935258448123932\n    time_span=0.0001s, test_ID=181, label=8, output_node=75, voltage=0.018843626603484154\n    time_span=0.0001s, test_ID=181, label=8, output_node=76, voltage=0.019134460017085075\n    time_span=0.0001s, test_ID=181, label=8, output_node=77, voltage=0.011414341628551483\n    time_span=0.0001s, test_ID=181, label=8, output_node=78, voltage=0.01473506074398756\n    time_span=0.0001s, test_ID=181, label=8, output_node=79, voltage=0.015302789397537708\n    time_span=0.0001s, test_ID=181, label=8, output_node=80, voltage=0.012723107822239399\n    time_span=0.0001s, test_ID=181, label=8, output_node=81, voltage=0.013916334137320518\n    time_span=0.0001s, test_ID=181, label=8, output_node=82, voltage=0.013371513225138187\n    time_span=0.0001s, test_ID=181, label=8, output_node=83, voltage=0.012015935964882374\n    time_span=0.0001s, test_ID=181, label=8, output_node=84, voltage=0.018212150782346725\n    time_span=0.0001s, test_ID=181, label=8, output_node=85, voltage=0.013027888722717762\n    time_span=0.0001s, test_ID=181, label=8, output_node=86, voltage=0.015540836378932\n    time_span=0.0001s, test_ID=181, label=8, output_node=87, voltage=0.01703685149550438\n    time_span=0.0001s, test_ID=181, label=8, output_node=88, voltage=0.013571713119745255\n    time_span=0.0001s, test_ID=181, label=8, output_node=89, voltage=0.019707171246409416\n    time_span=0.0001s, test_ID=181, label=8, output_node=90, voltage=0.009450200013816357\n    time_span=0.0001s, test_ID=181, label=8, output_node=91, voltage=0.01563645340502262\n    time_span=0.0001s, test_ID=181, label=8, output_node=92, voltage=0.018066732212901115\n    time_span=0.0001s, test_ID=181, label=8, output_node=93, voltage=0.009545816108584404\n    time_span=0.0001s, test_ID=181, label=8, output_node=94, voltage=0.018130477517843246\n    time_span=0.0001s, test_ID=181, label=8, output_node=95, voltage=0.01662250980734825\n    time_span=0.0001s, test_ID=181, label=8, output_node=96, voltage=0.018154384568333626\n    time_span=0.0001s, test_ID=181, label=8, output_node=97, voltage=0.015972111374139786\n    time_span=0.0001s, test_ID=181, label=8, output_node=98, voltage=0.015167329460382462\n    time_span=0.0001s, test_ID=181, label=8, output_node=99, voltage=0.016659362241625786\n    time_span=0.0001s, test_ID=181, label=8, output_node=sum, voltage=0.04042031988501549\n    Time consumed for 1 sample = 1206.739015340805 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '181'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=182, label=5, output_node=bkg, voltage=-0.006096614059060812\n    time_span=0.0001s, test_ID=182, label=5, output_node=0, voltage=0.004719123709946871\n    time_span=0.0001s, test_ID=182, label=5, output_node=1, voltage=0.008810756728053093\n    time_span=0.0001s, test_ID=182, label=5, output_node=2, voltage=0.01017529796808958\n    time_span=0.0001s, test_ID=182, label=5, output_node=3, voltage=0.007649402599781752\n    time_span=0.0001s, test_ID=182, label=5, output_node=4, voltage=0.0047749001532793045\n    time_span=0.0001s, test_ID=182, label=5, output_node=5, voltage=0.008591634221374989\n    time_span=0.0001s, test_ID=182, label=5, output_node=6, voltage=0.010847608558833599\n    time_span=0.0001s, test_ID=182, label=5, output_node=7, voltage=0.008099601604044437\n    time_span=0.0001s, test_ID=182, label=5, output_node=8, voltage=0.0030926296021789312\n    time_span=0.0001s, test_ID=182, label=5, output_node=9, voltage=0.0031782870646566153\n    time_span=0.0001s, test_ID=182, label=5, output_node=10, voltage=0.005282868631184101\n    time_span=0.0001s, test_ID=182, label=5, output_node=11, voltage=0.004958167672157288\n    time_span=0.0001s, test_ID=182, label=5, output_node=12, voltage=0.0024183266796171665\n    time_span=0.0001s, test_ID=182, label=5, output_node=13, voltage=0.0035647412296384573\n    time_span=0.0001s, test_ID=182, label=5, output_node=14, voltage=0.008412349969148636\n    time_span=0.0001s, test_ID=182, label=5, output_node=15, voltage=0.0031623507384210825\n    time_span=0.0001s, test_ID=182, label=5, output_node=16, voltage=0.008528884500265121\n    time_span=0.0001s, test_ID=182, label=5, output_node=17, voltage=0.006970119196921587\n    time_span=0.0001s, test_ID=182, label=5, output_node=18, voltage=0.004450199194252491\n    time_span=0.0001s, test_ID=182, label=5, output_node=19, voltage=0.008601592853665352\n    time_span=0.0001s, test_ID=182, label=5, output_node=20, voltage=0.006323704961687326\n    time_span=0.0001s, test_ID=182, label=5, output_node=21, voltage=0.0029611557256430387\n    time_span=0.0001s, test_ID=182, label=5, output_node=22, voltage=0.010827689431607723\n    time_span=0.0001s, test_ID=182, label=5, output_node=23, voltage=0.011692231521010399\n    time_span=0.0001s, test_ID=182, label=5, output_node=24, voltage=0.006861553527414799\n    time_span=0.0001s, test_ID=182, label=5, output_node=25, voltage=0.011474103666841984\n    time_span=0.0001s, test_ID=182, label=5, output_node=26, voltage=0.006966135464608669\n    time_span=0.0001s, test_ID=182, label=5, output_node=27, voltage=0.005968127399682999\n    time_span=0.0001s, test_ID=182, label=5, output_node=28, voltage=0.0027908366173505783\n    time_span=0.0001s, test_ID=182, label=5, output_node=29, voltage=0.006325697060674429\n    time_span=0.0001s, test_ID=182, label=5, output_node=30, voltage=0.0040946220979094505\n    time_span=0.0001s, test_ID=182, label=5, output_node=31, voltage=0.0015667327679693699\n    time_span=0.0001s, test_ID=182, label=5, output_node=32, voltage=0.006126494146883488\n    time_span=0.0001s, test_ID=182, label=5, output_node=33, voltage=0.003690239042043686\n    time_span=0.0001s, test_ID=182, label=5, output_node=34, voltage=0.00309163355268538\n    time_span=0.0001s, test_ID=182, label=5, output_node=35, voltage=0.008428286761045456\n    time_span=0.0001s, test_ID=182, label=5, output_node=36, voltage=0.007672310806810856\n    time_span=0.0001s, test_ID=182, label=5, output_node=37, voltage=0.007942231371998787\n    time_span=0.0001s, test_ID=182, label=5, output_node=38, voltage=0.004529880825430155\n    time_span=0.0001s, test_ID=182, label=5, output_node=39, voltage=0.008083665743470192\n    time_span=0.0001s, test_ID=182, label=5, output_node=40, voltage=0.0035707170609384775\n    time_span=0.0001s, test_ID=182, label=5, output_node=41, voltage=0.0037749004550278187\n    time_span=0.0001s, test_ID=182, label=5, output_node=42, voltage=0.011343625374138355\n    time_span=0.0001s, test_ID=182, label=5, output_node=43, voltage=0.007602589670568705\n    time_span=0.0001s, test_ID=182, label=5, output_node=44, voltage=0.005625497549772263\n    time_span=0.0001s, test_ID=182, label=5, output_node=45, voltage=0.006852589547634125\n    time_span=0.0001s, test_ID=182, label=5, output_node=46, voltage=0.00727490009739995\n    time_span=0.0001s, test_ID=182, label=5, output_node=47, voltage=0.009412350133061409\n    time_span=0.0001s, test_ID=182, label=5, output_node=48, voltage=0.0031802786979824305\n    time_span=0.0001s, test_ID=182, label=5, output_node=49, voltage=0.0064780875109136105\n    time_span=0.0001s, test_ID=182, label=5, output_node=50, voltage=0.011647410690784454\n    time_span=0.0001s, test_ID=182, label=5, output_node=51, voltage=0.005651394370943308\n    time_span=0.0001s, test_ID=182, label=5, output_node=52, voltage=0.005989043973386288\n    time_span=0.0001s, test_ID=182, label=5, output_node=53, voltage=0.007916335016489029\n    time_span=0.0001s, test_ID=182, label=5, output_node=54, voltage=0.010786852799355984\n    time_span=0.0001s, test_ID=182, label=5, output_node=55, voltage=0.01134760957211256\n    time_span=0.0001s, test_ID=182, label=5, output_node=56, voltage=0.009288844652473927\n    time_span=0.0001s, test_ID=182, label=5, output_node=57, voltage=0.008777888491749763\n    time_span=0.0001s, test_ID=182, label=5, output_node=58, voltage=0.005234064068645239\n    time_span=0.0001s, test_ID=182, label=5, output_node=59, voltage=0.006285856943577528\n    time_span=0.0001s, test_ID=182, label=5, output_node=60, voltage=0.00776593666523695\n    time_span=0.0001s, test_ID=182, label=5, output_node=61, voltage=0.0011225100606679916\n    time_span=0.0001s, test_ID=182, label=5, output_node=62, voltage=0.008430279791355133\n    time_span=0.0001s, test_ID=182, label=5, output_node=63, voltage=0.0088167330250144\n    time_span=0.0001s, test_ID=182, label=5, output_node=64, voltage=0.003785856533795595\n    time_span=0.0001s, test_ID=182, label=5, output_node=65, voltage=0.00798904336988926\n    time_span=0.0001s, test_ID=182, label=5, output_node=66, voltage=0.009710160084068775\n    time_span=0.0001s, test_ID=182, label=5, output_node=67, voltage=0.00674701202660799\n    time_span=0.0001s, test_ID=182, label=5, output_node=68, voltage=0.0065458170138299465\n    time_span=0.0001s, test_ID=182, label=5, output_node=69, voltage=0.007405378390103579\n    time_span=0.0001s, test_ID=182, label=5, output_node=70, voltage=0.0035398404579609632\n    time_span=0.0001s, test_ID=182, label=5, output_node=71, voltage=0.011494024656713009\n    time_span=0.0001s, test_ID=182, label=5, output_node=72, voltage=0.00787549838423729\n    time_span=0.0001s, test_ID=182, label=5, output_node=73, voltage=0.005865537561476231\n    time_span=0.0001s, test_ID=182, label=5, output_node=74, voltage=0.007050797343254089\n    time_span=0.0001s, test_ID=182, label=5, output_node=75, voltage=0.008234064094722271\n    time_span=0.0001s, test_ID=182, label=5, output_node=76, voltage=0.0026404382660984993\n    time_span=0.0001s, test_ID=182, label=5, output_node=77, voltage=0.0037320717237889767\n    time_span=0.0001s, test_ID=182, label=5, output_node=78, voltage=0.008495018817484379\n    time_span=0.0001s, test_ID=182, label=5, output_node=79, voltage=0.008551793172955513\n    time_span=0.0001s, test_ID=182, label=5, output_node=80, voltage=0.00638346653431654\n    time_span=0.0001s, test_ID=182, label=5, output_node=81, voltage=0.006555777043104172\n    time_span=0.0001s, test_ID=182, label=5, output_node=82, voltage=0.0061384462751448154\n    time_span=0.0001s, test_ID=182, label=5, output_node=83, voltage=0.00551593629643321\n    time_span=0.0001s, test_ID=182, label=5, output_node=84, voltage=0.005062749143689871\n    time_span=0.0001s, test_ID=182, label=5, output_node=85, voltage=0.007630478125065565\n    time_span=0.0001s, test_ID=182, label=5, output_node=86, voltage=0.005811753217130899\n    time_span=0.0001s, test_ID=182, label=5, output_node=87, voltage=0.008018924854695797\n    time_span=0.0001s, test_ID=182, label=5, output_node=88, voltage=0.006142430007457733\n    time_span=0.0001s, test_ID=182, label=5, output_node=89, voltage=0.004118526354432106\n    time_span=0.0001s, test_ID=182, label=5, output_node=90, voltage=0.00666434271261096\n    time_span=0.0001s, test_ID=182, label=5, output_node=91, voltage=0.007506972178816795\n    time_span=0.0001s, test_ID=182, label=5, output_node=92, voltage=0.0070986058562994\n    time_span=0.0001s, test_ID=182, label=5, output_node=93, voltage=0.012670318596065044\n    time_span=0.0001s, test_ID=182, label=5, output_node=94, voltage=0.002921314910054207\n    time_span=0.0001s, test_ID=182, label=5, output_node=95, voltage=0.010754979215562344\n    time_span=0.0001s, test_ID=182, label=5, output_node=96, voltage=0.003523904597386718\n    time_span=0.0001s, test_ID=182, label=5, output_node=97, voltage=0.0049422308802604675\n    time_span=0.0001s, test_ID=182, label=5, output_node=98, voltage=0.008129483088850975\n    time_span=0.0001s, test_ID=182, label=5, output_node=99, voltage=0.007384462282061577\n    time_span=0.0001s, test_ID=182, label=5, output_node=sum, voltage=0.017305776476860046\n    Time consumed for 1 sample = 1199.6570105552673 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '182'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=183, label=0, output_node=bkg, voltage=-0.006234063766896725\n    time_span=0.0001s, test_ID=183, label=0, output_node=0, voltage=0.019208166748285294\n    time_span=0.0001s, test_ID=183, label=0, output_node=1, voltage=0.015600597485899925\n    time_span=0.0001s, test_ID=183, label=0, output_node=2, voltage=0.02129681222140789\n    time_span=0.0001s, test_ID=183, label=0, output_node=3, voltage=0.023427290841937065\n    time_span=0.0001s, test_ID=183, label=0, output_node=4, voltage=0.01571115478873253\n    time_span=0.0001s, test_ID=183, label=0, output_node=5, voltage=0.01117729116231203\n    time_span=0.0001s, test_ID=183, label=0, output_node=6, voltage=0.024496015161275864\n    time_span=0.0001s, test_ID=183, label=0, output_node=7, voltage=0.024035856127738953\n    time_span=0.0001s, test_ID=183, label=0, output_node=8, voltage=0.027079680934548378\n    time_span=0.0001s, test_ID=183, label=0, output_node=9, voltage=0.021243026480078697\n    time_span=0.0001s, test_ID=183, label=0, output_node=10, voltage=0.015513943508267403\n    time_span=0.0001s, test_ID=183, label=0, output_node=11, voltage=0.010017928667366505\n    time_span=0.0001s, test_ID=183, label=0, output_node=12, voltage=0.022542830556631088\n    time_span=0.0001s, test_ID=183, label=0, output_node=13, voltage=0.025575699284672737\n    time_span=0.0001s, test_ID=183, label=0, output_node=14, voltage=0.017258962616324425\n    time_span=0.0001s, test_ID=183, label=0, output_node=15, voltage=0.022118525579571724\n    time_span=0.0001s, test_ID=183, label=0, output_node=16, voltage=0.018043825402855873\n    time_span=0.0001s, test_ID=183, label=0, output_node=17, voltage=0.014675297774374485\n    time_span=0.0001s, test_ID=183, label=0, output_node=18, voltage=0.02347211167216301\n    time_span=0.0001s, test_ID=183, label=0, output_node=19, voltage=0.01980876550078392\n    time_span=0.0001s, test_ID=183, label=0, output_node=20, voltage=0.027679283171892166\n    time_span=0.0001s, test_ID=183, label=0, output_node=21, voltage=0.01803785003721714\n    time_span=0.0001s, test_ID=183, label=0, output_node=22, voltage=0.01929083652794361\n    time_span=0.0001s, test_ID=183, label=0, output_node=23, voltage=0.021333664655685425\n    time_span=0.0001s, test_ID=183, label=0, output_node=24, voltage=0.023119522258639336\n    time_span=0.0001s, test_ID=183, label=0, output_node=25, voltage=0.016294822096824646\n    time_span=0.0001s, test_ID=183, label=0, output_node=26, voltage=0.02269521914422512\n    time_span=0.0001s, test_ID=183, label=0, output_node=27, voltage=0.01631673239171505\n    time_span=0.0001s, test_ID=183, label=0, output_node=28, voltage=0.01637151464819908\n    time_span=0.0001s, test_ID=183, label=0, output_node=29, voltage=0.023087650537490845\n    time_span=0.0001s, test_ID=183, label=0, output_node=30, voltage=0.021658364683389664\n    time_span=0.0001s, test_ID=183, label=0, output_node=31, voltage=0.01730378344655037\n    time_span=0.0001s, test_ID=183, label=0, output_node=32, voltage=0.02385059930384159\n    time_span=0.0001s, test_ID=183, label=0, output_node=33, voltage=0.024936256930232048\n    time_span=0.0001s, test_ID=183, label=0, output_node=34, voltage=0.019018923863768578\n    time_span=0.0001s, test_ID=183, label=0, output_node=35, voltage=0.019806774333119392\n    time_span=0.0001s, test_ID=183, label=0, output_node=36, voltage=0.01892131380736828\n    time_span=0.0001s, test_ID=183, label=0, output_node=37, voltage=0.023281872272491455\n    time_span=0.0001s, test_ID=183, label=0, output_node=38, voltage=0.021823706105351448\n    time_span=0.0001s, test_ID=183, label=0, output_node=39, voltage=0.0255567729473114\n    time_span=0.0001s, test_ID=183, label=0, output_node=40, voltage=0.023070715367794037\n    time_span=0.0001s, test_ID=183, label=0, output_node=41, voltage=0.018505975604057312\n    time_span=0.0001s, test_ID=183, label=0, output_node=42, voltage=0.016054781153798103\n    time_span=0.0001s, test_ID=183, label=0, output_node=43, voltage=0.018714142963290215\n    time_span=0.0001s, test_ID=183, label=0, output_node=44, voltage=0.025726094841957092\n    time_span=0.0001s, test_ID=183, label=0, output_node=45, voltage=0.022010955959558487\n    time_span=0.0001s, test_ID=183, label=0, output_node=46, voltage=0.023937251418828964\n    time_span=0.0001s, test_ID=183, label=0, output_node=47, voltage=0.010760956443846226\n    time_span=0.0001s, test_ID=183, label=0, output_node=48, voltage=0.019254980608820915\n    time_span=0.0001s, test_ID=183, label=0, output_node=49, voltage=0.014666334725916386\n    time_span=0.0001s, test_ID=183, label=0, output_node=50, voltage=0.021246017888188362\n    time_span=0.0001s, test_ID=183, label=0, output_node=51, voltage=0.020192230120301247\n    time_span=0.0001s, test_ID=183, label=0, output_node=52, voltage=0.013585656881332397\n    time_span=0.0001s, test_ID=183, label=0, output_node=53, voltage=0.021793825551867485\n    time_span=0.0001s, test_ID=183, label=0, output_node=54, voltage=0.014511952176690102\n    time_span=0.0001s, test_ID=183, label=0, output_node=55, voltage=0.021827690303325653\n    time_span=0.0001s, test_ID=183, label=0, output_node=56, voltage=0.028093624860048294\n    time_span=0.0001s, test_ID=183, label=0, output_node=57, voltage=0.02397310733795166\n    time_span=0.0001s, test_ID=183, label=0, output_node=58, voltage=0.018682271242141724\n    time_span=0.0001s, test_ID=183, label=0, output_node=59, voltage=0.01571812853217125\n    time_span=0.0001s, test_ID=183, label=0, output_node=60, voltage=0.019528886303305626\n    time_span=0.0001s, test_ID=183, label=0, output_node=61, voltage=0.015036853961646557\n    time_span=0.0001s, test_ID=183, label=0, output_node=62, voltage=0.016428286209702492\n    time_span=0.0001s, test_ID=183, label=0, output_node=63, voltage=0.019255977123975754\n    time_span=0.0001s, test_ID=183, label=0, output_node=64, voltage=0.017791831865906715\n    time_span=0.0001s, test_ID=183, label=0, output_node=65, voltage=0.02139342576265335\n    time_span=0.0001s, test_ID=183, label=0, output_node=66, voltage=0.020258964970707893\n    time_span=0.0001s, test_ID=183, label=0, output_node=67, voltage=0.01869422383606434\n    time_span=0.0001s, test_ID=183, label=0, output_node=68, voltage=0.019804779440164566\n    time_span=0.0001s, test_ID=183, label=0, output_node=69, voltage=0.019806772470474243\n    time_span=0.0001s, test_ID=183, label=0, output_node=70, voltage=0.0198505986481905\n    time_span=0.0001s, test_ID=183, label=0, output_node=71, voltage=0.02239741012454033\n    time_span=0.0001s, test_ID=183, label=0, output_node=72, voltage=0.019804781302809715\n    time_span=0.0001s, test_ID=183, label=0, output_node=73, voltage=0.022539841011166573\n    time_span=0.0001s, test_ID=183, label=0, output_node=74, voltage=0.01874103583395481\n    time_span=0.0001s, test_ID=183, label=0, output_node=75, voltage=0.017122508957982063\n    time_span=0.0001s, test_ID=183, label=0, output_node=76, voltage=0.026274900883436203\n    time_span=0.0001s, test_ID=183, label=0, output_node=77, voltage=0.01930876635015011\n    time_span=0.0001s, test_ID=183, label=0, output_node=78, voltage=0.022459162399172783\n    time_span=0.0001s, test_ID=183, label=0, output_node=79, voltage=0.021059760823845863\n    time_span=0.0001s, test_ID=183, label=0, output_node=80, voltage=0.01884561963379383\n    time_span=0.0001s, test_ID=183, label=0, output_node=81, voltage=0.023829681798815727\n    time_span=0.0001s, test_ID=183, label=0, output_node=82, voltage=0.02009960263967514\n    time_span=0.0001s, test_ID=183, label=0, output_node=83, voltage=0.020312748849391937\n    time_span=0.0001s, test_ID=183, label=0, output_node=84, voltage=0.02401195466518402\n    time_span=0.0001s, test_ID=183, label=0, output_node=85, voltage=0.01657470129430294\n    time_span=0.0001s, test_ID=183, label=0, output_node=86, voltage=0.01871015876531601\n    time_span=0.0001s, test_ID=183, label=0, output_node=87, voltage=0.018051793798804283\n    time_span=0.0001s, test_ID=183, label=0, output_node=88, voltage=0.01933167316019535\n    time_span=0.0001s, test_ID=183, label=0, output_node=89, voltage=0.019417328760027885\n    time_span=0.0001s, test_ID=183, label=0, output_node=90, voltage=0.023313743993639946\n    time_span=0.0001s, test_ID=183, label=0, output_node=91, voltage=0.02736155316233635\n    time_span=0.0001s, test_ID=183, label=0, output_node=92, voltage=0.02742430381476879\n    time_span=0.0001s, test_ID=183, label=0, output_node=93, voltage=0.02517629601061344\n    time_span=0.0001s, test_ID=183, label=0, output_node=94, voltage=0.0236324705183506\n    time_span=0.0001s, test_ID=183, label=0, output_node=95, voltage=0.01942828670144081\n    time_span=0.0001s, test_ID=183, label=0, output_node=96, voltage=0.010446215979754925\n    time_span=0.0001s, test_ID=183, label=0, output_node=97, voltage=0.022455180063843727\n    time_span=0.0001s, test_ID=183, label=0, output_node=98, voltage=0.021250996738672256\n    time_span=0.0001s, test_ID=183, label=0, output_node=99, voltage=0.020621513947844505\n    time_span=0.0001s, test_ID=183, label=0, output_node=sum, voltage=0.05015139654278755\n    Time consumed for 1 sample = 1209.9009895324707 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '183'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=184, label=8, output_node=bkg, voltage=-0.0044272905215620995\n    time_span=0.0001s, test_ID=184, label=8, output_node=0, voltage=0.015430279076099396\n    time_span=0.0001s, test_ID=184, label=8, output_node=1, voltage=0.012886454351246357\n    time_span=0.0001s, test_ID=184, label=8, output_node=2, voltage=0.013463147915899754\n    time_span=0.0001s, test_ID=184, label=8, output_node=3, voltage=0.013808764517307281\n    time_span=0.0001s, test_ID=184, label=8, output_node=4, voltage=0.011517927050590515\n    time_span=0.0001s, test_ID=184, label=8, output_node=5, voltage=0.010062748566269875\n    time_span=0.0001s, test_ID=184, label=8, output_node=6, voltage=0.011142430827021599\n    time_span=0.0001s, test_ID=184, label=8, output_node=7, voltage=0.014215139672160149\n    time_span=0.0001s, test_ID=184, label=8, output_node=8, voltage=0.014703188091516495\n    time_span=0.0001s, test_ID=184, label=8, output_node=9, voltage=0.01184462197124958\n    time_span=0.0001s, test_ID=184, label=8, output_node=10, voltage=0.012306773103773594\n    time_span=0.0001s, test_ID=184, label=8, output_node=11, voltage=0.012719123624265194\n    time_span=0.0001s, test_ID=184, label=8, output_node=12, voltage=0.007255976088345051\n    time_span=0.0001s, test_ID=184, label=8, output_node=13, voltage=0.01150597631931305\n    time_span=0.0001s, test_ID=184, label=8, output_node=14, voltage=0.009895417839288712\n    time_span=0.0001s, test_ID=184, label=8, output_node=15, voltage=0.011515936814248562\n    time_span=0.0001s, test_ID=184, label=8, output_node=16, voltage=0.010027889162302017\n    time_span=0.0001s, test_ID=184, label=8, output_node=17, voltage=0.01482868567109108\n    time_span=0.0001s, test_ID=184, label=8, output_node=18, voltage=0.014733067713677883\n    time_span=0.0001s, test_ID=184, label=8, output_node=19, voltage=0.011324700899422169\n    time_span=0.0001s, test_ID=184, label=8, output_node=20, voltage=0.015405378304421902\n    time_span=0.0001s, test_ID=184, label=8, output_node=21, voltage=0.011311753652989864\n    time_span=0.0001s, test_ID=184, label=8, output_node=22, voltage=0.00702191237360239\n    time_span=0.0001s, test_ID=184, label=8, output_node=23, voltage=0.012142430059611797\n    time_span=0.0001s, test_ID=184, label=8, output_node=24, voltage=0.008033864200115204\n    time_span=0.0001s, test_ID=184, label=8, output_node=25, voltage=0.013755976222455502\n    time_span=0.0001s, test_ID=184, label=8, output_node=26, voltage=0.010189242660999298\n    time_span=0.0001s, test_ID=184, label=8, output_node=27, voltage=0.012021912261843681\n    time_span=0.0001s, test_ID=184, label=8, output_node=28, voltage=0.012829681858420372\n    time_span=0.0001s, test_ID=184, label=8, output_node=29, voltage=0.013564740307629108\n    time_span=0.0001s, test_ID=184, label=8, output_node=30, voltage=0.007958167232573032\n    time_span=0.0001s, test_ID=184, label=8, output_node=31, voltage=0.013788844458758831\n    time_span=0.0001s, test_ID=184, label=8, output_node=32, voltage=0.015975099056959152\n    time_span=0.0001s, test_ID=184, label=8, output_node=33, voltage=0.014455179683864117\n    time_span=0.0001s, test_ID=184, label=8, output_node=34, voltage=0.013833665288984776\n    time_span=0.0001s, test_ID=184, label=8, output_node=35, voltage=0.01291633490473032\n    time_span=0.0001s, test_ID=184, label=8, output_node=36, voltage=0.01409262977540493\n    time_span=0.0001s, test_ID=184, label=8, output_node=37, voltage=0.015463147312402725\n    time_span=0.0001s, test_ID=184, label=8, output_node=38, voltage=0.015487052500247955\n    time_span=0.0001s, test_ID=184, label=8, output_node=39, voltage=0.019149402156472206\n    time_span=0.0001s, test_ID=184, label=8, output_node=40, voltage=0.008875497616827488\n    time_span=0.0001s, test_ID=184, label=8, output_node=41, voltage=0.013602589257061481\n    time_span=0.0001s, test_ID=184, label=8, output_node=42, voltage=0.010766931809484959\n    time_span=0.0001s, test_ID=184, label=8, output_node=43, voltage=0.011043825186789036\n    time_span=0.0001s, test_ID=184, label=8, output_node=44, voltage=0.017962152138352394\n    time_span=0.0001s, test_ID=184, label=8, output_node=45, voltage=0.014405378140509129\n    time_span=0.0001s, test_ID=184, label=8, output_node=46, voltage=0.011201195418834686\n    time_span=0.0001s, test_ID=184, label=8, output_node=47, voltage=0.014701195061206818\n    time_span=0.0001s, test_ID=184, label=8, output_node=48, voltage=0.009844622574746609\n    time_span=0.0001s, test_ID=184, label=8, output_node=49, voltage=0.01240737084299326\n    time_span=0.0001s, test_ID=184, label=8, output_node=50, voltage=0.011819722130894661\n    time_span=0.0001s, test_ID=184, label=8, output_node=51, voltage=0.012395419180393219\n    time_span=0.0001s, test_ID=184, label=8, output_node=52, voltage=0.008245020173490047\n    time_span=0.0001s, test_ID=184, label=8, output_node=53, voltage=0.01217729039490223\n    time_span=0.0001s, test_ID=184, label=8, output_node=54, voltage=0.010913346894085407\n    time_span=0.0001s, test_ID=184, label=8, output_node=55, voltage=0.011126493103802204\n    time_span=0.0001s, test_ID=184, label=8, output_node=56, voltage=0.011265937238931656\n    time_span=0.0001s, test_ID=184, label=8, output_node=57, voltage=0.01682569645345211\n    time_span=0.0001s, test_ID=184, label=8, output_node=58, voltage=0.014196216128766537\n    time_span=0.0001s, test_ID=184, label=8, output_node=59, voltage=0.010107569396495819\n    time_span=0.0001s, test_ID=184, label=8, output_node=60, voltage=0.015331674367189407\n    time_span=0.0001s, test_ID=184, label=8, output_node=61, voltage=0.012573705054819584\n    time_span=0.0001s, test_ID=184, label=8, output_node=62, voltage=0.013132469728589058\n    time_span=0.0001s, test_ID=184, label=8, output_node=63, voltage=0.01285159308463335\n    time_span=0.0001s, test_ID=184, label=8, output_node=64, voltage=0.009351593442261219\n    time_span=0.0001s, test_ID=184, label=8, output_node=65, voltage=0.016126494854688644\n    time_span=0.0001s, test_ID=184, label=8, output_node=66, voltage=0.005387450568377972\n    time_span=0.0001s, test_ID=184, label=8, output_node=67, voltage=0.014025895856320858\n    time_span=0.0001s, test_ID=184, label=8, output_node=68, voltage=0.01174800843000412\n    time_span=0.0001s, test_ID=184, label=8, output_node=69, voltage=0.013728088699281216\n    time_span=0.0001s, test_ID=184, label=8, output_node=70, voltage=0.011836654506623745\n    time_span=0.0001s, test_ID=184, label=8, output_node=71, voltage=0.01474402379244566\n    time_span=0.0001s, test_ID=184, label=8, output_node=72, voltage=0.010715140029788017\n    time_span=0.0001s, test_ID=184, label=8, output_node=73, voltage=0.008475100621581078\n    time_span=0.0001s, test_ID=184, label=8, output_node=74, voltage=0.0071952189318835735\n    time_span=0.0001s, test_ID=184, label=8, output_node=75, voltage=0.01038545835763216\n    time_span=0.0001s, test_ID=184, label=8, output_node=76, voltage=0.013366534374654293\n    time_span=0.0001s, test_ID=184, label=8, output_node=77, voltage=0.00856573786586523\n    time_span=0.0001s, test_ID=184, label=8, output_node=78, voltage=0.006557769142091274\n    time_span=0.0001s, test_ID=184, label=8, output_node=79, voltage=0.012864542193710804\n    time_span=0.0001s, test_ID=184, label=8, output_node=80, voltage=0.009697210974991322\n    time_span=0.0001s, test_ID=184, label=8, output_node=81, voltage=0.012818724848330021\n    time_span=0.0001s, test_ID=184, label=8, output_node=82, voltage=0.00950099527835846\n    time_span=0.0001s, test_ID=184, label=8, output_node=83, voltage=0.01146912295371294\n    time_span=0.0001s, test_ID=184, label=8, output_node=84, voltage=0.010821713134646416\n    time_span=0.0001s, test_ID=184, label=8, output_node=85, voltage=0.012214142829179764\n    time_span=0.0001s, test_ID=184, label=8, output_node=86, voltage=0.012216134928166866\n    time_span=0.0001s, test_ID=184, label=8, output_node=87, voltage=0.0161125510931015\n    time_span=0.0001s, test_ID=184, label=8, output_node=88, voltage=0.0074880472384393215\n    time_span=0.0001s, test_ID=184, label=8, output_node=89, voltage=0.013647410087287426\n    time_span=0.0001s, test_ID=184, label=8, output_node=90, voltage=0.00841235090047121\n    time_span=0.0001s, test_ID=184, label=8, output_node=91, voltage=0.011640438809990883\n    time_span=0.0001s, test_ID=184, label=8, output_node=92, voltage=0.00889840628951788\n    time_span=0.0001s, test_ID=184, label=8, output_node=93, voltage=0.011366533115506172\n    time_span=0.0001s, test_ID=184, label=8, output_node=94, voltage=0.00844123587012291\n    time_span=0.0001s, test_ID=184, label=8, output_node=95, voltage=0.009283864870667458\n    time_span=0.0001s, test_ID=184, label=8, output_node=96, voltage=0.012028884142637253\n    time_span=0.0001s, test_ID=184, label=8, output_node=97, voltage=0.012248007580637932\n    time_span=0.0001s, test_ID=184, label=8, output_node=98, voltage=0.01064043864607811\n    time_span=0.0001s, test_ID=184, label=8, output_node=99, voltage=0.011425299569964409\n    time_span=0.0001s, test_ID=184, label=8, output_node=sum, voltage=0.03029482066631317\n    Time consumed for 1 sample = 1202.8652820587158 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '184'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=185, label=9, output_node=bkg, voltage=-0.004004979971796274\n    time_span=0.0001s, test_ID=185, label=9, output_node=0, voltage=0.008655378594994545\n    time_span=0.0001s, test_ID=185, label=9, output_node=1, voltage=0.010108565911650658\n    time_span=0.0001s, test_ID=185, label=9, output_node=2, voltage=0.013581673614680767\n    time_span=0.0001s, test_ID=185, label=9, output_node=3, voltage=0.009534860961139202\n    time_span=0.0001s, test_ID=185, label=9, output_node=4, voltage=0.012226096354424953\n    time_span=0.0001s, test_ID=185, label=9, output_node=5, voltage=0.01704282872378826\n    time_span=0.0001s, test_ID=185, label=9, output_node=6, voltage=0.00843725074082613\n    time_span=0.0001s, test_ID=185, label=9, output_node=7, voltage=0.012183267623186111\n    time_span=0.0001s, test_ID=185, label=9, output_node=8, voltage=0.009744022972881794\n    time_span=0.0001s, test_ID=185, label=9, output_node=9, voltage=0.01485258899629116\n    time_span=0.0001s, test_ID=185, label=9, output_node=10, voltage=0.007047809194773436\n    time_span=0.0001s, test_ID=185, label=9, output_node=11, voltage=0.014174303039908409\n    time_span=0.0001s, test_ID=185, label=9, output_node=12, voltage=0.010441235266625881\n    time_span=0.0001s, test_ID=185, label=9, output_node=13, voltage=0.01057171355932951\n    time_span=0.0001s, test_ID=185, label=9, output_node=14, voltage=0.01251195278018713\n    time_span=0.0001s, test_ID=185, label=9, output_node=15, voltage=0.012191235087811947\n    time_span=0.0001s, test_ID=185, label=9, output_node=16, voltage=0.009799801744520664\n    time_span=0.0001s, test_ID=185, label=9, output_node=17, voltage=0.008934262208640575\n    time_span=0.0001s, test_ID=185, label=9, output_node=18, voltage=0.011676294729113579\n    time_span=0.0001s, test_ID=185, label=9, output_node=19, voltage=0.01123007945716381\n    time_span=0.0001s, test_ID=185, label=9, output_node=20, voltage=0.00570816732943058\n    time_span=0.0001s, test_ID=185, label=9, output_node=21, voltage=0.008214143104851246\n    time_span=0.0001s, test_ID=185, label=9, output_node=22, voltage=0.01452490035444498\n    time_span=0.0001s, test_ID=185, label=9, output_node=23, voltage=0.009048804640769958\n    time_span=0.0001s, test_ID=185, label=9, output_node=24, voltage=0.011621513403952122\n    time_span=0.0001s, test_ID=185, label=9, output_node=25, voltage=0.008767927996814251\n    time_span=0.0001s, test_ID=185, label=9, output_node=26, voltage=0.003209163434803486\n    time_span=0.0001s, test_ID=185, label=9, output_node=27, voltage=0.007065736688673496\n    time_span=0.0001s, test_ID=185, label=9, output_node=28, voltage=0.009195219725370407\n    time_span=0.0001s, test_ID=185, label=9, output_node=29, voltage=0.012894422747194767\n    time_span=0.0001s, test_ID=185, label=9, output_node=30, voltage=0.011446216143667698\n    time_span=0.0001s, test_ID=185, label=9, output_node=31, voltage=0.013888446614146233\n    time_span=0.0001s, test_ID=185, label=9, output_node=32, voltage=0.008665339089930058\n    time_span=0.0001s, test_ID=185, label=9, output_node=33, voltage=0.010536852292716503\n    time_span=0.0001s, test_ID=185, label=9, output_node=34, voltage=0.013411354273557663\n    time_span=0.0001s, test_ID=185, label=9, output_node=35, voltage=0.009335656650364399\n    time_span=0.0001s, test_ID=185, label=9, output_node=36, voltage=0.009017928503453732\n    time_span=0.0001s, test_ID=185, label=9, output_node=37, voltage=0.011073704808950424\n    time_span=0.0001s, test_ID=185, label=9, output_node=38, voltage=0.011163346469402313\n    time_span=0.0001s, test_ID=185, label=9, output_node=39, voltage=0.009075697511434555\n    time_span=0.0001s, test_ID=185, label=9, output_node=40, voltage=0.007395418360829353\n    time_span=0.0001s, test_ID=185, label=9, output_node=41, voltage=0.011668327264487743\n    time_span=0.0001s, test_ID=185, label=9, output_node=42, voltage=0.010719123296439648\n    time_span=0.0001s, test_ID=185, label=9, output_node=43, voltage=0.009751992300152779\n    time_span=0.0001s, test_ID=185, label=9, output_node=44, voltage=0.009512947872281075\n    time_span=0.0001s, test_ID=185, label=9, output_node=45, voltage=0.012910358607769012\n    time_span=0.0001s, test_ID=185, label=9, output_node=46, voltage=0.013382471166551113\n    time_span=0.0001s, test_ID=185, label=9, output_node=47, voltage=0.01628486067056656\n    time_span=0.0001s, test_ID=185, label=9, output_node=48, voltage=0.0065209162421524525\n    time_span=0.0001s, test_ID=185, label=9, output_node=49, voltage=0.009630478918552399\n    time_span=0.0001s, test_ID=185, label=9, output_node=50, voltage=0.004329681396484375\n    time_span=0.0001s, test_ID=185, label=9, output_node=51, voltage=0.009280877187848091\n    time_span=0.0001s, test_ID=185, label=9, output_node=52, voltage=0.009199202992022038\n    time_span=0.0001s, test_ID=185, label=9, output_node=53, voltage=0.010610558092594147\n    time_span=0.0001s, test_ID=185, label=9, output_node=54, voltage=0.011168327182531357\n    time_span=0.0001s, test_ID=185, label=9, output_node=55, voltage=0.011308765038847923\n    time_span=0.0001s, test_ID=185, label=9, output_node=56, voltage=0.013196215964853764\n    time_span=0.0001s, test_ID=185, label=9, output_node=57, voltage=0.009686254896223545\n    time_span=0.0001s, test_ID=185, label=9, output_node=58, voltage=0.008294821716845036\n    time_span=0.0001s, test_ID=185, label=9, output_node=59, voltage=0.010030877776443958\n    time_span=0.0001s, test_ID=185, label=9, output_node=60, voltage=0.008831674233078957\n    time_span=0.0001s, test_ID=185, label=9, output_node=61, voltage=0.006168326362967491\n    time_span=0.0001s, test_ID=185, label=9, output_node=62, voltage=0.0092978086322546\n    time_span=0.0001s, test_ID=185, label=9, output_node=63, voltage=0.011711155995726585\n    time_span=0.0001s, test_ID=185, label=9, output_node=64, voltage=0.0068386453203856945\n    time_span=0.0001s, test_ID=185, label=9, output_node=65, voltage=0.009182270616292953\n    time_span=0.0001s, test_ID=185, label=9, output_node=66, voltage=0.011273904703557491\n    time_span=0.0001s, test_ID=185, label=9, output_node=67, voltage=0.008955178782343864\n    time_span=0.0001s, test_ID=185, label=9, output_node=68, voltage=0.012171315029263496\n    time_span=0.0001s, test_ID=185, label=9, output_node=69, voltage=0.013305776752531528\n    time_span=0.0001s, test_ID=185, label=9, output_node=70, voltage=0.011199203319847584\n    time_span=0.0001s, test_ID=185, label=9, output_node=71, voltage=0.01086354535073042\n    time_span=0.0001s, test_ID=185, label=9, output_node=72, voltage=0.0071145412512123585\n    time_span=0.0001s, test_ID=185, label=9, output_node=73, voltage=0.010245019569993019\n    time_span=0.0001s, test_ID=185, label=9, output_node=74, voltage=0.0061254980973899364\n    time_span=0.0001s, test_ID=185, label=9, output_node=75, voltage=0.0067649404518306255\n    time_span=0.0001s, test_ID=185, label=9, output_node=76, voltage=0.009019920602440834\n    time_span=0.0001s, test_ID=185, label=9, output_node=77, voltage=0.011636453680694103\n    time_span=0.0001s, test_ID=185, label=9, output_node=78, voltage=0.013339641503989697\n    time_span=0.0001s, test_ID=185, label=9, output_node=79, voltage=0.01310557872056961\n    time_span=0.0001s, test_ID=185, label=9, output_node=80, voltage=0.009194224141538143\n    time_span=0.0001s, test_ID=185, label=9, output_node=81, voltage=0.009607569314539433\n    time_span=0.0001s, test_ID=185, label=9, output_node=82, voltage=0.010523904114961624\n    time_span=0.0001s, test_ID=185, label=9, output_node=83, voltage=0.011996015906333923\n    time_span=0.0001s, test_ID=185, label=9, output_node=84, voltage=0.008408366702497005\n    time_span=0.0001s, test_ID=185, label=9, output_node=85, voltage=0.009556773118674755\n    time_span=0.0001s, test_ID=185, label=9, output_node=86, voltage=0.011134462431073189\n    time_span=0.0001s, test_ID=185, label=9, output_node=87, voltage=0.01157769002020359\n    time_span=0.0001s, test_ID=185, label=9, output_node=88, voltage=0.011605578474700451\n    time_span=0.0001s, test_ID=185, label=9, output_node=89, voltage=0.012353585101664066\n    time_span=0.0001s, test_ID=185, label=9, output_node=90, voltage=0.010096613317728043\n    time_span=0.0001s, test_ID=185, label=9, output_node=91, voltage=0.008574701845645905\n    time_span=0.0001s, test_ID=185, label=9, output_node=92, voltage=0.012079681269824505\n    time_span=0.0001s, test_ID=185, label=9, output_node=93, voltage=0.009461156092584133\n    time_span=0.0001s, test_ID=185, label=9, output_node=94, voltage=0.009432271122932434\n    time_span=0.0001s, test_ID=185, label=9, output_node=95, voltage=0.010641434229910374\n    time_span=0.0001s, test_ID=185, label=9, output_node=96, voltage=0.010489043779671192\n    time_span=0.0001s, test_ID=185, label=9, output_node=97, voltage=0.008213147521018982\n    time_span=0.0001s, test_ID=185, label=9, output_node=98, voltage=0.00959760881960392\n    time_span=0.0001s, test_ID=185, label=9, output_node=99, voltage=0.010546812787652016\n    time_span=0.0001s, test_ID=185, label=9, output_node=sum, voltage=0.028708167374134064\n    Time consumed for 1 sample = 1201.9383883476257 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '185'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=186, label=2, output_node=bkg, voltage=-0.0028545819222927094\n    time_span=0.0001s, test_ID=186, label=2, output_node=0, voltage=0.022045815363526344\n    time_span=0.0001s, test_ID=186, label=2, output_node=1, voltage=0.02353685349225998\n    time_span=0.0001s, test_ID=186, label=2, output_node=2, voltage=0.01885657198727131\n    time_span=0.0001s, test_ID=186, label=2, output_node=3, voltage=0.0298934243619442\n    time_span=0.0001s, test_ID=186, label=2, output_node=4, voltage=0.020492032170295715\n    time_span=0.0001s, test_ID=186, label=2, output_node=5, voltage=0.015017928555607796\n    time_span=0.0001s, test_ID=186, label=2, output_node=6, voltage=0.018998008221387863\n    time_span=0.0001s, test_ID=186, label=2, output_node=7, voltage=0.030734064057469368\n    time_span=0.0001s, test_ID=186, label=2, output_node=8, voltage=0.022019920870661736\n    time_span=0.0001s, test_ID=186, label=2, output_node=9, voltage=0.015673307701945305\n    time_span=0.0001s, test_ID=186, label=2, output_node=10, voltage=0.023612551391124725\n    time_span=0.0001s, test_ID=186, label=2, output_node=11, voltage=0.030477089807391167\n    time_span=0.0001s, test_ID=186, label=2, output_node=12, voltage=0.021285854279994965\n    time_span=0.0001s, test_ID=186, label=2, output_node=13, voltage=0.017299801111221313\n    time_span=0.0001s, test_ID=186, label=2, output_node=14, voltage=0.017025895416736603\n    time_span=0.0001s, test_ID=186, label=2, output_node=15, voltage=0.01730876788496971\n    time_span=0.0001s, test_ID=186, label=2, output_node=16, voltage=0.021559759974479675\n    time_span=0.0001s, test_ID=186, label=2, output_node=17, voltage=0.01836255006492138\n    time_span=0.0001s, test_ID=186, label=2, output_node=18, voltage=0.025546813383698463\n    time_span=0.0001s, test_ID=186, label=2, output_node=19, voltage=0.021220119670033455\n    time_span=0.0001s, test_ID=186, label=2, output_node=20, voltage=0.023630477488040924\n    time_span=0.0001s, test_ID=186, label=2, output_node=21, voltage=0.025052789598703384\n    time_span=0.0001s, test_ID=186, label=2, output_node=22, voltage=0.019125496968626976\n    time_span=0.0001s, test_ID=186, label=2, output_node=23, voltage=0.02402091771364212\n    time_span=0.0001s, test_ID=186, label=2, output_node=24, voltage=0.020507968962192535\n    time_span=0.0001s, test_ID=186, label=2, output_node=25, voltage=0.017821714282035828\n    time_span=0.0001s, test_ID=186, label=2, output_node=26, voltage=0.02647111564874649\n    time_span=0.0001s, test_ID=186, label=2, output_node=27, voltage=0.027162350714206696\n    time_span=0.0001s, test_ID=186, label=2, output_node=28, voltage=0.026288846507668495\n    time_span=0.0001s, test_ID=186, label=2, output_node=29, voltage=0.02483067661523819\n    time_span=0.0001s, test_ID=186, label=2, output_node=30, voltage=0.01904183253645897\n    time_span=0.0001s, test_ID=186, label=2, output_node=31, voltage=0.018235059455037117\n    time_span=0.0001s, test_ID=186, label=2, output_node=32, voltage=0.028569720685482025\n    time_span=0.0001s, test_ID=186, label=2, output_node=33, voltage=0.0222270917147398\n    time_span=0.0001s, test_ID=186, label=2, output_node=34, voltage=0.023678286001086235\n    time_span=0.0001s, test_ID=186, label=2, output_node=35, voltage=0.023337649181485176\n    time_span=0.0001s, test_ID=186, label=2, output_node=36, voltage=0.019774900749325752\n    time_span=0.0001s, test_ID=186, label=2, output_node=37, voltage=0.024485059082508087\n    time_span=0.0001s, test_ID=186, label=2, output_node=38, voltage=0.020583664998412132\n    time_span=0.0001s, test_ID=186, label=2, output_node=39, voltage=0.023548806086182594\n    time_span=0.0001s, test_ID=186, label=2, output_node=40, voltage=0.020944222807884216\n    time_span=0.0001s, test_ID=186, label=2, output_node=41, voltage=0.021923307329416275\n    time_span=0.0001s, test_ID=186, label=2, output_node=42, voltage=0.013699202798306942\n    time_span=0.0001s, test_ID=186, label=2, output_node=43, voltage=0.023220119997859\n    time_span=0.0001s, test_ID=186, label=2, output_node=44, voltage=0.02641533873975277\n    time_span=0.0001s, test_ID=186, label=2, output_node=45, voltage=0.023671315982937813\n    time_span=0.0001s, test_ID=186, label=2, output_node=46, voltage=0.01622011885046959\n    time_span=0.0001s, test_ID=186, label=2, output_node=47, voltage=0.014782869257032871\n    time_span=0.0001s, test_ID=186, label=2, output_node=48, voltage=0.012765935622155666\n    time_span=0.0001s, test_ID=186, label=2, output_node=49, voltage=0.020298805087804794\n    time_span=0.0001s, test_ID=186, label=2, output_node=50, voltage=0.024599604308605194\n    time_span=0.0001s, test_ID=186, label=2, output_node=51, voltage=0.02593127451837063\n    time_span=0.0001s, test_ID=186, label=2, output_node=52, voltage=0.022415338084101677\n    time_span=0.0001s, test_ID=186, label=2, output_node=53, voltage=0.020838646218180656\n    time_span=0.0001s, test_ID=186, label=2, output_node=54, voltage=0.01874900422990322\n    time_span=0.0001s, test_ID=186, label=2, output_node=55, voltage=0.01831274852156639\n    time_span=0.0001s, test_ID=186, label=2, output_node=56, voltage=0.020134462043642998\n    time_span=0.0001s, test_ID=186, label=2, output_node=57, voltage=0.026589641347527504\n    time_span=0.0001s, test_ID=186, label=2, output_node=58, voltage=0.022360557690262794\n    time_span=0.0001s, test_ID=186, label=2, output_node=59, voltage=0.019649403169751167\n    time_span=0.0001s, test_ID=186, label=2, output_node=60, voltage=0.018056774511933327\n    time_span=0.0001s, test_ID=186, label=2, output_node=61, voltage=0.02178187109529972\n    time_span=0.0001s, test_ID=186, label=2, output_node=62, voltage=0.024213148280978203\n    time_span=0.0001s, test_ID=186, label=2, output_node=63, voltage=0.022271912544965744\n    time_span=0.0001s, test_ID=186, label=2, output_node=64, voltage=0.021125497296452522\n    time_span=0.0001s, test_ID=186, label=2, output_node=65, voltage=0.023425299674272537\n    time_span=0.0001s, test_ID=186, label=2, output_node=66, voltage=0.015763944014906883\n    time_span=0.0001s, test_ID=186, label=2, output_node=67, voltage=0.02235756814479828\n    time_span=0.0001s, test_ID=186, label=2, output_node=68, voltage=0.02607569843530655\n    time_span=0.0001s, test_ID=186, label=2, output_node=69, voltage=0.01997111551463604\n    time_span=0.0001s, test_ID=186, label=2, output_node=70, voltage=0.019256971776485443\n    time_span=0.0001s, test_ID=186, label=2, output_node=71, voltage=0.02357669174671173\n    time_span=0.0001s, test_ID=186, label=2, output_node=72, voltage=0.017703186720609665\n    time_span=0.0001s, test_ID=186, label=2, output_node=73, voltage=0.015190238133072853\n    time_span=0.0001s, test_ID=186, label=2, output_node=74, voltage=0.020167332142591476\n    time_span=0.0001s, test_ID=186, label=2, output_node=75, voltage=0.026741037145256996\n    time_span=0.0001s, test_ID=186, label=2, output_node=76, voltage=0.02499900385737419\n    time_span=0.0001s, test_ID=186, label=2, output_node=77, voltage=0.01663247123360634\n    time_span=0.0001s, test_ID=186, label=2, output_node=78, voltage=0.025838647037744522\n    time_span=0.0001s, test_ID=186, label=2, output_node=79, voltage=0.022059760987758636\n    time_span=0.0001s, test_ID=186, label=2, output_node=80, voltage=0.020790837705135345\n    time_span=0.0001s, test_ID=186, label=2, output_node=81, voltage=0.018464144319295883\n    time_span=0.0001s, test_ID=186, label=2, output_node=82, voltage=0.0236414335668087\n    time_span=0.0001s, test_ID=186, label=2, output_node=83, voltage=0.023849600926041603\n    time_span=0.0001s, test_ID=186, label=2, output_node=84, voltage=0.021598605439066887\n    time_span=0.0001s, test_ID=186, label=2, output_node=85, voltage=0.023725099861621857\n    time_span=0.0001s, test_ID=186, label=2, output_node=86, voltage=0.02192728966474533\n    time_span=0.0001s, test_ID=186, label=2, output_node=87, voltage=0.029335658997297287\n    time_span=0.0001s, test_ID=186, label=2, output_node=88, voltage=0.015615537762641907\n    time_span=0.0001s, test_ID=186, label=2, output_node=89, voltage=0.023020917549729347\n    time_span=0.0001s, test_ID=186, label=2, output_node=90, voltage=0.014885458163917065\n    time_span=0.0001s, test_ID=186, label=2, output_node=91, voltage=0.025694221258163452\n    time_span=0.0001s, test_ID=186, label=2, output_node=92, voltage=0.02258067950606346\n    time_span=0.0001s, test_ID=186, label=2, output_node=93, voltage=0.027891432866454124\n    time_span=0.0001s, test_ID=186, label=2, output_node=94, voltage=0.024322709068655968\n    time_span=0.0001s, test_ID=186, label=2, output_node=95, voltage=0.025189243257045746\n    time_span=0.0001s, test_ID=186, label=2, output_node=96, voltage=0.01811055839061737\n    time_span=0.0001s, test_ID=186, label=2, output_node=97, voltage=0.029257968068122864\n    time_span=0.0001s, test_ID=186, label=2, output_node=98, voltage=0.02577490173280239\n    time_span=0.0001s, test_ID=186, label=2, output_node=99, voltage=0.021382469683885574\n    time_span=0.0001s, test_ID=186, label=2, output_node=sum, voltage=0.05041234940290451\n    Time consumed for 1 sample = 1211.6711883544922 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '186'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=187, label=5, output_node=bkg, voltage=-0.005420319270342588\n    time_span=0.0001s, test_ID=187, label=5, output_node=0, voltage=0.010087649337947369\n    time_span=0.0001s, test_ID=187, label=5, output_node=1, voltage=0.01634860783815384\n    time_span=0.0001s, test_ID=187, label=5, output_node=2, voltage=0.011462152004241943\n    time_span=0.0001s, test_ID=187, label=5, output_node=3, voltage=0.0188615545630455\n    time_span=0.0001s, test_ID=187, label=5, output_node=4, voltage=0.012315737083554268\n    time_span=0.0001s, test_ID=187, label=5, output_node=5, voltage=0.01041334681212902\n    time_span=0.0001s, test_ID=187, label=5, output_node=6, voltage=0.010980079881846905\n    time_span=0.0001s, test_ID=187, label=5, output_node=7, voltage=0.014554781839251518\n    time_span=0.0001s, test_ID=187, label=5, output_node=8, voltage=0.013648406602442265\n    time_span=0.0001s, test_ID=187, label=5, output_node=9, voltage=0.011634461581707\n    time_span=0.0001s, test_ID=187, label=5, output_node=10, voltage=0.013413346372544765\n    time_span=0.0001s, test_ID=187, label=5, output_node=11, voltage=0.018239043653011322\n    time_span=0.0001s, test_ID=187, label=5, output_node=12, voltage=0.013858565129339695\n    time_span=0.0001s, test_ID=187, label=5, output_node=13, voltage=0.012005976401269436\n    time_span=0.0001s, test_ID=187, label=5, output_node=14, voltage=0.014831673353910446\n    time_span=0.0001s, test_ID=187, label=5, output_node=15, voltage=0.011069721542298794\n    time_span=0.0001s, test_ID=187, label=5, output_node=16, voltage=0.012292828410863876\n    time_span=0.0001s, test_ID=187, label=5, output_node=17, voltage=0.010965139605104923\n    time_span=0.0001s, test_ID=187, label=5, output_node=18, voltage=0.015147410333156586\n    time_span=0.0001s, test_ID=187, label=5, output_node=19, voltage=0.011664343066513538\n    time_span=0.0001s, test_ID=187, label=5, output_node=20, voltage=0.01787649653851986\n    time_span=0.0001s, test_ID=187, label=5, output_node=21, voltage=0.010950199328362942\n    time_span=0.0001s, test_ID=187, label=5, output_node=22, voltage=0.014005976729094982\n    time_span=0.0001s, test_ID=187, label=5, output_node=23, voltage=0.014715139754116535\n    time_span=0.0001s, test_ID=187, label=5, output_node=24, voltage=0.01592032052576542\n    time_span=0.0001s, test_ID=187, label=5, output_node=25, voltage=0.011368525214493275\n    time_span=0.0001s, test_ID=187, label=5, output_node=26, voltage=0.0063535855151712894\n    time_span=0.0001s, test_ID=187, label=5, output_node=27, voltage=0.015165338292717934\n    time_span=0.0001s, test_ID=187, label=5, output_node=28, voltage=0.011965139769017696\n    time_span=0.0001s, test_ID=187, label=5, output_node=29, voltage=0.014671314507722855\n    time_span=0.0001s, test_ID=187, label=5, output_node=30, voltage=0.014279880560934544\n    time_span=0.0001s, test_ID=187, label=5, output_node=31, voltage=0.009548804722726345\n    time_span=0.0001s, test_ID=187, label=5, output_node=32, voltage=0.015552788972854614\n    time_span=0.0001s, test_ID=187, label=5, output_node=33, voltage=0.012642430141568184\n    time_span=0.0001s, test_ID=187, label=5, output_node=34, voltage=0.016182269901037216\n    time_span=0.0001s, test_ID=187, label=5, output_node=35, voltage=0.017244024202227592\n    time_span=0.0001s, test_ID=187, label=5, output_node=36, voltage=0.01667928136885166\n    time_span=0.0001s, test_ID=187, label=5, output_node=37, voltage=0.01576593518257141\n    time_span=0.0001s, test_ID=187, label=5, output_node=38, voltage=0.017470119521021843\n    time_span=0.0001s, test_ID=187, label=5, output_node=39, voltage=0.015515937469899654\n    time_span=0.0001s, test_ID=187, label=5, output_node=40, voltage=0.013863546773791313\n    time_span=0.0001s, test_ID=187, label=5, output_node=41, voltage=0.01110856607556343\n    time_span=0.0001s, test_ID=187, label=5, output_node=42, voltage=0.009548804722726345\n    time_span=0.0001s, test_ID=187, label=5, output_node=43, voltage=0.014923305250704288\n    time_span=0.0001s, test_ID=187, label=5, output_node=44, voltage=0.017352590337395668\n    time_span=0.0001s, test_ID=187, label=5, output_node=45, voltage=0.018486056476831436\n    time_span=0.0001s, test_ID=187, label=5, output_node=46, voltage=0.015278884209692478\n    time_span=0.0001s, test_ID=187, label=5, output_node=47, voltage=0.011637450195848942\n    time_span=0.0001s, test_ID=187, label=5, output_node=48, voltage=0.008174302987754345\n    time_span=0.0001s, test_ID=187, label=5, output_node=49, voltage=0.015484063886106014\n    time_span=0.0001s, test_ID=187, label=5, output_node=50, voltage=0.018121514469385147\n    time_span=0.0001s, test_ID=187, label=5, output_node=51, voltage=0.01402390468865633\n    time_span=0.0001s, test_ID=187, label=5, output_node=52, voltage=0.009824701584875584\n    time_span=0.0001s, test_ID=187, label=5, output_node=53, voltage=0.014768924564123154\n    time_span=0.0001s, test_ID=187, label=5, output_node=54, voltage=0.011191234923899174\n    time_span=0.0001s, test_ID=187, label=5, output_node=55, voltage=0.01349402405321598\n    time_span=0.0001s, test_ID=187, label=5, output_node=56, voltage=0.012915338389575481\n    time_span=0.0001s, test_ID=187, label=5, output_node=57, voltage=0.020200196653604507\n    time_span=0.0001s, test_ID=187, label=5, output_node=58, voltage=0.01887848600745201\n    time_span=0.0001s, test_ID=187, label=5, output_node=59, voltage=0.008252988569438457\n    time_span=0.0001s, test_ID=187, label=5, output_node=60, voltage=0.011532869189977646\n    time_span=0.0001s, test_ID=187, label=5, output_node=61, voltage=0.014913346618413925\n    time_span=0.0001s, test_ID=187, label=5, output_node=62, voltage=0.014688247814774513\n    time_span=0.0001s, test_ID=187, label=5, output_node=63, voltage=0.01561752986162901\n    time_span=0.0001s, test_ID=187, label=5, output_node=64, voltage=0.014637450687587261\n    time_span=0.0001s, test_ID=187, label=5, output_node=65, voltage=0.013002987951040268\n    time_span=0.0001s, test_ID=187, label=5, output_node=66, voltage=0.01464243046939373\n    time_span=0.0001s, test_ID=187, label=5, output_node=67, voltage=0.014062749221920967\n    time_span=0.0001s, test_ID=187, label=5, output_node=68, voltage=0.015080678276717663\n    time_span=0.0001s, test_ID=187, label=5, output_node=69, voltage=0.013082669116556644\n    time_span=0.0001s, test_ID=187, label=5, output_node=70, voltage=0.008542828261852264\n    time_span=0.0001s, test_ID=187, label=5, output_node=71, voltage=0.01782071776688099\n    time_span=0.0001s, test_ID=187, label=5, output_node=72, voltage=0.012420318089425564\n    time_span=0.0001s, test_ID=187, label=5, output_node=73, voltage=0.013367529027163982\n    time_span=0.0001s, test_ID=187, label=5, output_node=74, voltage=0.010272908955812454\n    time_span=0.0001s, test_ID=187, label=5, output_node=75, voltage=0.013737051747739315\n    time_span=0.0001s, test_ID=187, label=5, output_node=76, voltage=0.012008963152766228\n    time_span=0.0001s, test_ID=187, label=5, output_node=77, voltage=0.013654381968080997\n    time_span=0.0001s, test_ID=187, label=5, output_node=78, voltage=0.010168326087296009\n    time_span=0.0001s, test_ID=187, label=5, output_node=79, voltage=0.015503983944654465\n    time_span=0.0001s, test_ID=187, label=5, output_node=80, voltage=0.013385457918047905\n    time_span=0.0001s, test_ID=187, label=5, output_node=81, voltage=0.013277887366712093\n    time_span=0.0001s, test_ID=187, label=5, output_node=82, voltage=0.011491036973893642\n    time_span=0.0001s, test_ID=187, label=5, output_node=83, voltage=0.015866534784436226\n    time_span=0.0001s, test_ID=187, label=5, output_node=84, voltage=0.015455178916454315\n    time_span=0.0001s, test_ID=187, label=5, output_node=85, voltage=0.012121514417231083\n    time_span=0.0001s, test_ID=187, label=5, output_node=86, voltage=0.01697111502289772\n    time_span=0.0001s, test_ID=187, label=5, output_node=87, voltage=0.01397509966045618\n    time_span=0.0001s, test_ID=187, label=5, output_node=88, voltage=0.011370518244802952\n    time_span=0.0001s, test_ID=187, label=5, output_node=89, voltage=0.01414143480360508\n    time_span=0.0001s, test_ID=187, label=5, output_node=90, voltage=0.01506772916764021\n    time_span=0.0001s, test_ID=187, label=5, output_node=91, voltage=0.014924301765859127\n    time_span=0.0001s, test_ID=187, label=5, output_node=92, voltage=0.008718127384781837\n    time_span=0.0001s, test_ID=187, label=5, output_node=93, voltage=0.014994023367762566\n    time_span=0.0001s, test_ID=187, label=5, output_node=94, voltage=0.014062749221920967\n    time_span=0.0001s, test_ID=187, label=5, output_node=95, voltage=0.017566734924912453\n    time_span=0.0001s, test_ID=187, label=5, output_node=96, voltage=0.010126493871212006\n    time_span=0.0001s, test_ID=187, label=5, output_node=97, voltage=0.015116533264517784\n    time_span=0.0001s, test_ID=187, label=5, output_node=98, voltage=0.012748007662594318\n    time_span=0.0001s, test_ID=187, label=5, output_node=99, voltage=0.013343625701963902\n    time_span=0.0001s, test_ID=187, label=5, output_node=sum, voltage=0.032385457307100296\n    Time consumed for 1 sample = 1205.7202291488647 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '187'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=188, label=0, output_node=bkg, voltage=-0.005127490032464266\n    time_span=0.0001s, test_ID=188, label=0, output_node=0, voltage=0.017109563574194908\n    time_span=0.0001s, test_ID=188, label=0, output_node=1, voltage=0.023749005049467087\n    time_span=0.0001s, test_ID=188, label=0, output_node=2, voltage=0.02044721320271492\n    time_span=0.0001s, test_ID=188, label=0, output_node=3, voltage=0.021857568994164467\n    time_span=0.0001s, test_ID=188, label=0, output_node=4, voltage=0.013896414078772068\n    time_span=0.0001s, test_ID=188, label=0, output_node=5, voltage=0.012184263207018375\n    time_span=0.0001s, test_ID=188, label=0, output_node=6, voltage=0.02075498178601265\n    time_span=0.0001s, test_ID=188, label=0, output_node=7, voltage=0.018996015191078186\n    time_span=0.0001s, test_ID=188, label=0, output_node=8, voltage=0.016431273892521858\n    time_span=0.0001s, test_ID=188, label=0, output_node=9, voltage=0.02115139365196228\n    time_span=0.0001s, test_ID=188, label=0, output_node=10, voltage=0.022764939814805984\n    time_span=0.0001s, test_ID=188, label=0, output_node=11, voltage=0.020215138792991638\n    time_span=0.0001s, test_ID=188, label=0, output_node=12, voltage=0.02569621428847313\n    time_span=0.0001s, test_ID=188, label=0, output_node=13, voltage=0.0218057744204998\n    time_span=0.0001s, test_ID=188, label=0, output_node=14, voltage=0.021696213632822037\n    time_span=0.0001s, test_ID=188, label=0, output_node=15, voltage=0.016528883948922157\n    time_span=0.0001s, test_ID=188, label=0, output_node=16, voltage=0.017789840698242188\n    time_span=0.0001s, test_ID=188, label=0, output_node=17, voltage=0.014609561301767826\n    time_span=0.0001s, test_ID=188, label=0, output_node=18, voltage=0.01966235227882862\n    time_span=0.0001s, test_ID=188, label=0, output_node=19, voltage=0.020174304023385048\n    time_span=0.0001s, test_ID=188, label=0, output_node=20, voltage=0.02412649430334568\n    time_span=0.0001s, test_ID=188, label=0, output_node=21, voltage=0.021884461864829063\n    time_span=0.0001s, test_ID=188, label=0, output_node=22, voltage=0.018810758367180824\n    time_span=0.0001s, test_ID=188, label=0, output_node=23, voltage=0.025972111150622368\n    time_span=0.0001s, test_ID=188, label=0, output_node=24, voltage=0.028345616534352303\n    time_span=0.0001s, test_ID=188, label=0, output_node=25, voltage=0.02095717191696167\n    time_span=0.0001s, test_ID=188, label=0, output_node=26, voltage=0.020531870424747467\n    time_span=0.0001s, test_ID=188, label=0, output_node=27, voltage=0.020207172259688377\n    time_span=0.0001s, test_ID=188, label=0, output_node=28, voltage=0.021141434088349342\n    time_span=0.0001s, test_ID=188, label=0, output_node=29, voltage=0.02444223128259182\n    time_span=0.0001s, test_ID=188, label=0, output_node=30, voltage=0.02164541929960251\n    time_span=0.0001s, test_ID=188, label=0, output_node=31, voltage=0.01376892440021038\n    time_span=0.0001s, test_ID=188, label=0, output_node=32, voltage=0.021874504163861275\n    time_span=0.0001s, test_ID=188, label=0, output_node=33, voltage=0.020518925040960312\n    time_span=0.0001s, test_ID=188, label=0, output_node=34, voltage=0.02013944275677204\n    time_span=0.0001s, test_ID=188, label=0, output_node=35, voltage=0.018844621255993843\n    time_span=0.0001s, test_ID=188, label=0, output_node=36, voltage=0.01977689191699028\n    time_span=0.0001s, test_ID=188, label=0, output_node=37, voltage=0.021690240129828453\n    time_span=0.0001s, test_ID=188, label=0, output_node=38, voltage=0.01930079609155655\n    time_span=0.0001s, test_ID=188, label=0, output_node=39, voltage=0.02694721147418022\n    time_span=0.0001s, test_ID=188, label=0, output_node=40, voltage=0.01571912318468094\n    time_span=0.0001s, test_ID=188, label=0, output_node=41, voltage=0.015763944014906883\n    time_span=0.0001s, test_ID=188, label=0, output_node=42, voltage=0.020348606631159782\n    time_span=0.0001s, test_ID=188, label=0, output_node=43, voltage=0.014075697399675846\n    time_span=0.0001s, test_ID=188, label=0, output_node=44, voltage=0.023329680785536766\n    time_span=0.0001s, test_ID=188, label=0, output_node=45, voltage=0.015851594507694244\n    time_span=0.0001s, test_ID=188, label=0, output_node=46, voltage=0.021728089079260826\n    time_span=0.0001s, test_ID=188, label=0, output_node=47, voltage=0.02032768912613392\n    time_span=0.0001s, test_ID=188, label=0, output_node=48, voltage=0.018812749534845352\n    time_span=0.0001s, test_ID=188, label=0, output_node=49, voltage=0.021714141592383385\n    time_span=0.0001s, test_ID=188, label=0, output_node=50, voltage=0.022902391850948334\n    time_span=0.0001s, test_ID=188, label=0, output_node=51, voltage=0.02621314860880375\n    time_span=0.0001s, test_ID=188, label=0, output_node=52, voltage=0.02005079761147499\n    time_span=0.0001s, test_ID=188, label=0, output_node=53, voltage=0.019490040838718414\n    time_span=0.0001s, test_ID=188, label=0, output_node=54, voltage=0.025683267042040825\n    time_span=0.0001s, test_ID=188, label=0, output_node=55, voltage=0.01608067750930786\n    time_span=0.0001s, test_ID=188, label=0, output_node=56, voltage=0.028211155906319618\n    time_span=0.0001s, test_ID=188, label=0, output_node=57, voltage=0.02250996232032776\n    time_span=0.0001s, test_ID=188, label=0, output_node=58, voltage=0.023335658013820648\n    time_span=0.0001s, test_ID=188, label=0, output_node=59, voltage=0.01656673289835453\n    time_span=0.0001s, test_ID=188, label=0, output_node=60, voltage=0.02129681222140789\n    time_span=0.0001s, test_ID=188, label=0, output_node=61, voltage=0.01567032001912594\n    time_span=0.0001s, test_ID=188, label=0, output_node=62, voltage=0.022295815870165825\n    time_span=0.0001s, test_ID=188, label=0, output_node=63, voltage=0.020405378192663193\n    time_span=0.0001s, test_ID=188, label=0, output_node=64, voltage=0.01956673339009285\n    time_span=0.0001s, test_ID=188, label=0, output_node=65, voltage=0.01981872320175171\n    time_span=0.0001s, test_ID=188, label=0, output_node=66, voltage=0.024712152779102325\n    time_span=0.0001s, test_ID=188, label=0, output_node=67, voltage=0.02472509816288948\n    time_span=0.0001s, test_ID=188, label=0, output_node=68, voltage=0.018987052142620087\n    time_span=0.0001s, test_ID=188, label=0, output_node=69, voltage=0.022803785279393196\n    time_span=0.0001s, test_ID=188, label=0, output_node=70, voltage=0.020111555233597755\n    time_span=0.0001s, test_ID=188, label=0, output_node=71, voltage=0.020752988755702972\n    time_span=0.0001s, test_ID=188, label=0, output_node=72, voltage=0.018309762701392174\n    time_span=0.0001s, test_ID=188, label=0, output_node=73, voltage=0.013082669116556644\n    time_span=0.0001s, test_ID=188, label=0, output_node=74, voltage=0.020251993089914322\n    time_span=0.0001s, test_ID=188, label=0, output_node=75, voltage=0.018322709947824478\n    time_span=0.0001s, test_ID=188, label=0, output_node=76, voltage=0.022390438243746758\n    time_span=0.0001s, test_ID=188, label=0, output_node=77, voltage=0.02588844671845436\n    time_span=0.0001s, test_ID=188, label=0, output_node=78, voltage=0.02466832660138607\n    time_span=0.0001s, test_ID=188, label=0, output_node=79, voltage=0.025261953473091125\n    time_span=0.0001s, test_ID=188, label=0, output_node=80, voltage=0.02273605577647686\n    time_span=0.0001s, test_ID=188, label=0, output_node=81, voltage=0.029513943940401077\n    time_span=0.0001s, test_ID=188, label=0, output_node=82, voltage=0.01431872509419918\n    time_span=0.0001s, test_ID=188, label=0, output_node=83, voltage=0.02407968044281006\n    time_span=0.0001s, test_ID=188, label=0, output_node=84, voltage=0.02098306640982628\n    time_span=0.0001s, test_ID=188, label=0, output_node=85, voltage=0.02153884433209896\n    time_span=0.0001s, test_ID=188, label=0, output_node=86, voltage=0.02083565853536129\n    time_span=0.0001s, test_ID=188, label=0, output_node=87, voltage=0.02263844572007656\n    time_span=0.0001s, test_ID=188, label=0, output_node=88, voltage=0.020798804238438606\n    time_span=0.0001s, test_ID=188, label=0, output_node=89, voltage=0.022577688097953796\n    time_span=0.0001s, test_ID=188, label=0, output_node=90, voltage=0.02359163388609886\n    time_span=0.0001s, test_ID=188, label=0, output_node=91, voltage=0.02464342676103115\n    time_span=0.0001s, test_ID=188, label=0, output_node=92, voltage=0.029702192172408104\n    time_span=0.0001s, test_ID=188, label=0, output_node=93, voltage=0.02372111566364765\n    time_span=0.0001s, test_ID=188, label=0, output_node=94, voltage=0.017259959131479263\n    time_span=0.0001s, test_ID=188, label=0, output_node=95, voltage=0.022399403154850006\n    time_span=0.0001s, test_ID=188, label=0, output_node=96, voltage=0.01731972023844719\n    time_span=0.0001s, test_ID=188, label=0, output_node=97, voltage=0.01797410473227501\n    time_span=0.0001s, test_ID=188, label=0, output_node=98, voltage=0.023442231118679047\n    time_span=0.0001s, test_ID=188, label=0, output_node=99, voltage=0.021924303844571114\n    time_span=0.0001s, test_ID=188, label=0, output_node=sum, voltage=0.04915139451622963\n    Time consumed for 1 sample = 1211.2925741672516 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '188'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=189, label=1, output_node=bkg, voltage=-0.005798804108053446\n    time_span=0.0001s, test_ID=189, label=1, output_node=0, voltage=0.0010687251342460513\n    time_span=0.0001s, test_ID=189, label=1, output_node=1, voltage=0.0017559761181473732\n    time_span=0.0001s, test_ID=189, label=1, output_node=2, voltage=0.0025627489667385817\n    time_span=0.0001s, test_ID=189, label=1, output_node=3, voltage=-0.0009392430074512959\n    time_span=0.0001s, test_ID=189, label=1, output_node=4, voltage=0.0017888445872813463\n    time_span=0.0001s, test_ID=189, label=1, output_node=5, voltage=0.0024671312421560287\n    time_span=0.0001s, test_ID=189, label=1, output_node=6, voltage=0.006294820457696915\n    time_span=0.0001s, test_ID=189, label=1, output_node=7, voltage=0.0013545817928388715\n    time_span=0.0001s, test_ID=189, label=1, output_node=8, voltage=-0.002042828593403101\n    time_span=0.0001s, test_ID=189, label=1, output_node=9, voltage=-0.00046513957204297185\n    time_span=0.0001s, test_ID=189, label=1, output_node=10, voltage=-0.0003436255210544914\n    time_span=0.0001s, test_ID=189, label=1, output_node=11, voltage=-0.0015647411346435547\n    time_span=0.0001s, test_ID=189, label=1, output_node=12, voltage=-0.0024840636178851128\n    time_span=0.0001s, test_ID=189, label=1, output_node=13, voltage=8.964152948465198e-05\n    time_span=0.0001s, test_ID=189, label=1, output_node=14, voltage=-0.0008794820168986917\n    time_span=0.0001s, test_ID=189, label=1, output_node=15, voltage=0.0016972111770883203\n    time_span=0.0001s, test_ID=189, label=1, output_node=16, voltage=0.003541832324117422\n    time_span=0.0001s, test_ID=189, label=1, output_node=17, voltage=-0.0004790836828760803\n    time_span=0.0001s, test_ID=189, label=1, output_node=18, voltage=0.001454183249734342\n    time_span=0.0001s, test_ID=189, label=1, output_node=19, voltage=0.001028884551487863\n    time_span=0.0001s, test_ID=189, label=1, output_node=20, voltage=0.0002041833067778498\n    time_span=0.0001s, test_ID=189, label=1, output_node=21, voltage=0.0035826691891998053\n    time_span=0.0001s, test_ID=189, label=1, output_node=22, voltage=8.366526890313253e-05\n    time_span=0.0001s, test_ID=189, label=1, output_node=23, voltage=-0.0011693226406350732\n    time_span=0.0001s, test_ID=189, label=1, output_node=24, voltage=0.0018127491930499673\n    time_span=0.0001s, test_ID=189, label=1, output_node=25, voltage=0.0007768925279378891\n    time_span=0.0001s, test_ID=189, label=1, output_node=26, voltage=-0.0009541832259856164\n    time_span=0.0001s, test_ID=189, label=1, output_node=27, voltage=-0.0004621513362508267\n    time_span=0.0001s, test_ID=189, label=1, output_node=28, voltage=0.0013047809479758143\n    time_span=0.0001s, test_ID=189, label=1, output_node=29, voltage=0.001909362617880106\n    time_span=0.0001s, test_ID=189, label=1, output_node=30, voltage=-0.002795816631987691\n    time_span=0.0001s, test_ID=189, label=1, output_node=31, voltage=-0.0005179282743483782\n    time_span=0.0001s, test_ID=189, label=1, output_node=32, voltage=-0.002252988051623106\n    time_span=0.0001s, test_ID=189, label=1, output_node=33, voltage=-0.0011354582384228706\n    time_span=0.0001s, test_ID=189, label=1, output_node=34, voltage=-0.0013207170413807034\n    time_span=0.0001s, test_ID=189, label=1, output_node=35, voltage=-1.3944162674306426e-05\n    time_span=0.0001s, test_ID=189, label=1, output_node=36, voltage=-0.0031573702581226826\n    time_span=0.0001s, test_ID=189, label=1, output_node=37, voltage=-0.00013247018796391785\n    time_span=0.0001s, test_ID=189, label=1, output_node=38, voltage=0.0019960161298513412\n    time_span=0.0001s, test_ID=189, label=1, output_node=39, voltage=-0.0002649401139933616\n    time_span=0.0001s, test_ID=189, label=1, output_node=40, voltage=0.0006025898037478328\n    time_span=0.0001s, test_ID=189, label=1, output_node=41, voltage=0.001348605495877564\n    time_span=0.0001s, test_ID=189, label=1, output_node=42, voltage=0.0010946213733404875\n    time_span=0.0001s, test_ID=189, label=1, output_node=43, voltage=0.001011952175758779\n    time_span=0.0001s, test_ID=189, label=1, output_node=44, voltage=0.0002290837437612936\n    time_span=0.0001s, test_ID=189, label=1, output_node=45, voltage=-0.0003167330287396908\n    time_span=0.0001s, test_ID=189, label=1, output_node=46, voltage=0.0033565734047442675\n    time_span=0.0001s, test_ID=189, label=1, output_node=47, voltage=-0.0007061752257868648\n    time_span=0.0001s, test_ID=189, label=1, output_node=48, voltage=-0.0010737052652984858\n    time_span=0.0001s, test_ID=189, label=1, output_node=49, voltage=-0.0006135458243079484\n    time_span=0.0001s, test_ID=189, label=1, output_node=50, voltage=0.0017569720512256026\n    time_span=0.0001s, test_ID=189, label=1, output_node=51, voltage=-0.0010507968254387379\n    time_span=0.0001s, test_ID=189, label=1, output_node=52, voltage=-0.0009810756891965866\n    time_span=0.0001s, test_ID=189, label=1, output_node=53, voltage=-0.0010966135887429118\n    time_span=0.0001s, test_ID=189, label=1, output_node=54, voltage=0.0013346611522138119\n    time_span=0.0001s, test_ID=189, label=1, output_node=55, voltage=0.0010826694779098034\n    time_span=0.0001s, test_ID=189, label=1, output_node=56, voltage=-2.988044980156701e-05\n    time_span=0.0001s, test_ID=189, label=1, output_node=57, voltage=0.0018157372251152992\n    time_span=0.0001s, test_ID=189, label=1, output_node=58, voltage=0.00016633466293569654\n    time_span=0.0001s, test_ID=189, label=1, output_node=59, voltage=-4.980134235665901e-06\n    time_span=0.0001s, test_ID=189, label=1, output_node=60, voltage=0.003625498153269291\n    time_span=0.0001s, test_ID=189, label=1, output_node=61, voltage=-0.000444223202066496\n    time_span=0.0001s, test_ID=189, label=1, output_node=62, voltage=0.0002519920526538044\n    time_span=0.0001s, test_ID=189, label=1, output_node=63, voltage=0.002246015937998891\n    time_span=0.0001s, test_ID=189, label=1, output_node=64, voltage=0.0025249002501368523\n    time_span=0.0001s, test_ID=189, label=1, output_node=65, voltage=0.0005986057221889496\n    time_span=0.0001s, test_ID=189, label=1, output_node=66, voltage=0.00022410346718970686\n    time_span=0.0001s, test_ID=189, label=1, output_node=67, voltage=0.002856573788449168\n    time_span=0.0001s, test_ID=189, label=1, output_node=68, voltage=0.002510956022888422\n    time_span=0.0001s, test_ID=189, label=1, output_node=69, voltage=-0.00045019935350865126\n    time_span=0.0001s, test_ID=189, label=1, output_node=70, voltage=-0.0005597610143013299\n    time_span=0.0001s, test_ID=189, label=1, output_node=71, voltage=0.00019322709704283625\n    time_span=0.0001s, test_ID=189, label=1, output_node=72, voltage=0.001568725099787116\n    time_span=0.0001s, test_ID=189, label=1, output_node=73, voltage=-0.0007858566241338849\n    time_span=0.0001s, test_ID=189, label=1, output_node=74, voltage=-0.00017828693671617657\n    time_span=0.0001s, test_ID=189, label=1, output_node=75, voltage=0.0024890440981835127\n    time_span=0.0001s, test_ID=189, label=1, output_node=76, voltage=1.792820512491744e-05\n    time_span=0.0001s, test_ID=189, label=1, output_node=77, voltage=0.0005129481432959437\n    time_span=0.0001s, test_ID=189, label=1, output_node=78, voltage=0.004926295019686222\n    time_span=0.0001s, test_ID=189, label=1, output_node=79, voltage=0.0014800798380747437\n    time_span=0.0001s, test_ID=189, label=1, output_node=80, voltage=-0.00011254980927333236\n    time_span=0.0001s, test_ID=189, label=1, output_node=81, voltage=-0.00022609549341723323\n    time_span=0.0001s, test_ID=189, label=1, output_node=82, voltage=0.0014661356108263135\n    time_span=0.0001s, test_ID=189, label=1, output_node=83, voltage=-5.776895341114141e-05\n    time_span=0.0001s, test_ID=189, label=1, output_node=84, voltage=0.0017241035820916295\n    time_span=0.0001s, test_ID=189, label=1, output_node=85, voltage=-0.0004621514235623181\n    time_span=0.0001s, test_ID=189, label=1, output_node=86, voltage=0.0015597608871757984\n    time_span=0.0001s, test_ID=189, label=1, output_node=87, voltage=-0.0010039841290563345\n    time_span=0.0001s, test_ID=189, label=1, output_node=88, voltage=0.00021115544950589538\n    time_span=0.0001s, test_ID=189, label=1, output_node=89, voltage=0.003054780885577202\n    time_span=0.0001s, test_ID=189, label=1, output_node=90, voltage=-0.0012948208022862673\n    time_span=0.0001s, test_ID=189, label=1, output_node=91, voltage=0.000589641451369971\n    time_span=0.0001s, test_ID=189, label=1, output_node=92, voltage=0.0022470117546617985\n    time_span=0.0001s, test_ID=189, label=1, output_node=93, voltage=-0.0006115537253208458\n    time_span=0.0001s, test_ID=189, label=1, output_node=94, voltage=-0.0006484063342213631\n    time_span=0.0001s, test_ID=189, label=1, output_node=95, voltage=0.0030278884805738926\n    time_span=0.0001s, test_ID=189, label=1, output_node=96, voltage=-0.0009960158495232463\n    time_span=0.0001s, test_ID=189, label=1, output_node=97, voltage=-0.0032241034787148237\n    time_span=0.0001s, test_ID=189, label=1, output_node=98, voltage=-0.0009731075842864811\n    time_span=0.0001s, test_ID=189, label=1, output_node=99, voltage=0.002607569796964526\n    time_span=0.0001s, test_ID=189, label=1, output_node=sum, voltage=0.0067390440963208675\n    Time consumed for 1 sample = 1200.8918297290802 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '189'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=190, label=1, output_node=bkg, voltage=-0.006010956130921841\n    time_span=0.0001s, test_ID=190, label=1, output_node=0, voltage=0.003598605515435338\n    time_span=0.0001s, test_ID=190, label=1, output_node=1, voltage=0.010577688924968243\n    time_span=0.0001s, test_ID=190, label=1, output_node=2, voltage=0.006264940369874239\n    time_span=0.0001s, test_ID=190, label=1, output_node=3, voltage=0.0067440238781273365\n    time_span=0.0001s, test_ID=190, label=1, output_node=4, voltage=0.013136453926563263\n    time_span=0.0001s, test_ID=190, label=1, output_node=5, voltage=0.011993028223514557\n    time_span=0.0001s, test_ID=190, label=1, output_node=6, voltage=0.01080179214477539\n    time_span=0.0001s, test_ID=190, label=1, output_node=7, voltage=0.011488047428429127\n    time_span=0.0001s, test_ID=190, label=1, output_node=8, voltage=0.008171315304934978\n    time_span=0.0001s, test_ID=190, label=1, output_node=9, voltage=0.004888446070253849\n    time_span=0.0001s, test_ID=190, label=1, output_node=10, voltage=0.009711155667901039\n    time_span=0.0001s, test_ID=190, label=1, output_node=11, voltage=0.011567729525268078\n    time_span=0.0001s, test_ID=190, label=1, output_node=12, voltage=0.005513944197446108\n    time_span=0.0001s, test_ID=190, label=1, output_node=13, voltage=0.008710159920156002\n    time_span=0.0001s, test_ID=190, label=1, output_node=14, voltage=0.011857569217681885\n    time_span=0.0001s, test_ID=190, label=1, output_node=15, voltage=0.0072161355055868626\n    time_span=0.0001s, test_ID=190, label=1, output_node=16, voltage=0.004674302414059639\n    time_span=0.0001s, test_ID=190, label=1, output_node=17, voltage=0.008952191099524498\n    time_span=0.0001s, test_ID=190, label=1, output_node=18, voltage=0.00971912406384945\n    time_span=0.0001s, test_ID=190, label=1, output_node=19, voltage=0.00938247051090002\n    time_span=0.0001s, test_ID=190, label=1, output_node=20, voltage=0.006539840716868639\n    time_span=0.0001s, test_ID=190, label=1, output_node=21, voltage=0.010257967747747898\n    time_span=0.0001s, test_ID=190, label=1, output_node=22, voltage=0.007957170717418194\n    time_span=0.0001s, test_ID=190, label=1, output_node=23, voltage=0.008972111158072948\n    time_span=0.0001s, test_ID=190, label=1, output_node=24, voltage=0.007940239273011684\n    time_span=0.0001s, test_ID=190, label=1, output_node=25, voltage=0.009694223292171955\n    time_span=0.0001s, test_ID=190, label=1, output_node=26, voltage=0.011991036124527454\n    time_span=0.0001s, test_ID=190, label=1, output_node=27, voltage=0.012800795957446098\n    time_span=0.0001s, test_ID=190, label=1, output_node=28, voltage=0.014782868325710297\n    time_span=0.0001s, test_ID=190, label=1, output_node=29, voltage=0.012834660708904266\n    time_span=0.0001s, test_ID=190, label=1, output_node=30, voltage=0.006622510030865669\n    time_span=0.0001s, test_ID=190, label=1, output_node=31, voltage=0.008260956965386868\n    time_span=0.0001s, test_ID=190, label=1, output_node=32, voltage=0.01454880554229021\n    time_span=0.0001s, test_ID=190, label=1, output_node=33, voltage=0.012017928063869476\n    time_span=0.0001s, test_ID=190, label=1, output_node=34, voltage=0.008820717222988605\n    time_span=0.0001s, test_ID=190, label=1, output_node=35, voltage=0.01338944211602211\n    time_span=0.0001s, test_ID=190, label=1, output_node=36, voltage=0.010072708129882812\n    time_span=0.0001s, test_ID=190, label=1, output_node=37, voltage=0.011476095765829086\n    time_span=0.0001s, test_ID=190, label=1, output_node=38, voltage=0.012400398962199688\n    time_span=0.0001s, test_ID=190, label=1, output_node=39, voltage=0.009012947790324688\n    time_span=0.0001s, test_ID=190, label=1, output_node=40, voltage=0.011885457672178745\n    time_span=0.0001s, test_ID=190, label=1, output_node=41, voltage=0.011750996112823486\n    time_span=0.0001s, test_ID=190, label=1, output_node=42, voltage=0.013121513649821281\n    time_span=0.0001s, test_ID=190, label=1, output_node=43, voltage=0.013650398701429367\n    time_span=0.0001s, test_ID=190, label=1, output_node=44, voltage=0.010274900123476982\n    time_span=0.0001s, test_ID=190, label=1, output_node=45, voltage=0.011902390979230404\n    time_span=0.0001s, test_ID=190, label=1, output_node=46, voltage=0.008939243853092194\n    time_span=0.0001s, test_ID=190, label=1, output_node=47, voltage=0.006286852993071079\n    time_span=0.0001s, test_ID=190, label=1, output_node=48, voltage=0.0076344627887010574\n    time_span=0.0001s, test_ID=190, label=1, output_node=49, voltage=0.015264940448105335\n    time_span=0.0001s, test_ID=190, label=1, output_node=50, voltage=0.00874402280896902\n    time_span=0.0001s, test_ID=190, label=1, output_node=51, voltage=0.006661354098469019\n    time_span=0.0001s, test_ID=190, label=1, output_node=52, voltage=0.009505976922810078\n    time_span=0.0001s, test_ID=190, label=1, output_node=53, voltage=0.01047410350292921\n    time_span=0.0001s, test_ID=190, label=1, output_node=54, voltage=0.012393427081406116\n    time_span=0.0001s, test_ID=190, label=1, output_node=55, voltage=0.011472111567854881\n    time_span=0.0001s, test_ID=190, label=1, output_node=56, voltage=0.009477091953158379\n    time_span=0.0001s, test_ID=190, label=1, output_node=57, voltage=0.006758964620530605\n    time_span=0.0001s, test_ID=190, label=1, output_node=58, voltage=0.01086354535073042\n    time_span=0.0001s, test_ID=190, label=1, output_node=59, voltage=0.009086653590202332\n    time_span=0.0001s, test_ID=190, label=1, output_node=60, voltage=0.0038177291862666607\n    time_span=0.0001s, test_ID=190, label=1, output_node=61, voltage=0.010763943195343018\n    time_span=0.0001s, test_ID=190, label=1, output_node=62, voltage=0.013441234827041626\n    time_span=0.0001s, test_ID=190, label=1, output_node=63, voltage=0.008826692588627338\n    time_span=0.0001s, test_ID=190, label=1, output_node=64, voltage=0.007440239191055298\n    time_span=0.0001s, test_ID=190, label=1, output_node=65, voltage=0.008452191017568111\n    time_span=0.0001s, test_ID=190, label=1, output_node=66, voltage=0.00021215145534370095\n    time_span=0.0001s, test_ID=190, label=1, output_node=67, voltage=0.008795817382633686\n    time_span=0.0001s, test_ID=190, label=1, output_node=68, voltage=0.008288845419883728\n    time_span=0.0001s, test_ID=190, label=1, output_node=69, voltage=0.010119521990418434\n    time_span=0.0001s, test_ID=190, label=1, output_node=70, voltage=0.006862550042569637\n    time_span=0.0001s, test_ID=190, label=1, output_node=71, voltage=0.006303784903138876\n    time_span=0.0001s, test_ID=190, label=1, output_node=72, voltage=0.0067958165891468525\n    time_span=0.0001s, test_ID=190, label=1, output_node=73, voltage=0.004629482049494982\n    time_span=0.0001s, test_ID=190, label=1, output_node=74, voltage=0.012590637430548668\n    time_span=0.0001s, test_ID=190, label=1, output_node=75, voltage=0.009584660641849041\n    time_span=0.0001s, test_ID=190, label=1, output_node=76, voltage=0.010133465752005577\n    time_span=0.0001s, test_ID=190, label=1, output_node=77, voltage=0.007699203211814165\n    time_span=0.0001s, test_ID=190, label=1, output_node=78, voltage=0.007462151348590851\n    time_span=0.0001s, test_ID=190, label=1, output_node=79, voltage=0.009591633453965187\n    time_span=0.0001s, test_ID=190, label=1, output_node=80, voltage=0.009170319885015488\n    time_span=0.0001s, test_ID=190, label=1, output_node=81, voltage=0.0073067727498710155\n    time_span=0.0001s, test_ID=190, label=1, output_node=82, voltage=0.005818725097924471\n    time_span=0.0001s, test_ID=190, label=1, output_node=83, voltage=0.010056773200631142\n    time_span=0.0001s, test_ID=190, label=1, output_node=84, voltage=0.012554780580103397\n    time_span=0.0001s, test_ID=190, label=1, output_node=85, voltage=0.01032470166683197\n    time_span=0.0001s, test_ID=190, label=1, output_node=86, voltage=0.008213147521018982\n    time_span=0.0001s, test_ID=190, label=1, output_node=87, voltage=0.014108565635979176\n    time_span=0.0001s, test_ID=190, label=1, output_node=88, voltage=0.005409362725913525\n    time_span=0.0001s, test_ID=190, label=1, output_node=89, voltage=0.011227091774344444\n    time_span=0.0001s, test_ID=190, label=1, output_node=90, voltage=0.008495019748806953\n    time_span=0.0001s, test_ID=190, label=1, output_node=91, voltage=0.007730080280452967\n    time_span=0.0001s, test_ID=190, label=1, output_node=92, voltage=0.009582669474184513\n    time_span=0.0001s, test_ID=190, label=1, output_node=93, voltage=0.0025657368823885918\n    time_span=0.0001s, test_ID=190, label=1, output_node=94, voltage=0.006026891991496086\n    time_span=0.0001s, test_ID=190, label=1, output_node=95, voltage=0.009803785011172295\n    time_span=0.0001s, test_ID=190, label=1, output_node=96, voltage=0.00686254957690835\n    time_span=0.0001s, test_ID=190, label=1, output_node=97, voltage=0.01168824639171362\n    time_span=0.0001s, test_ID=190, label=1, output_node=98, voltage=0.012694223783910275\n    time_span=0.0001s, test_ID=190, label=1, output_node=99, voltage=0.008721115998923779\n    time_span=0.0001s, test_ID=190, label=1, output_node=sum, voltage=0.025794818997383118\n    Time consumed for 1 sample = 1202.1020131111145 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '190'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=191, label=1, output_node=bkg, voltage=-0.005875498056411743\n    time_span=0.0001s, test_ID=191, label=1, output_node=0, voltage=0.0023725100327283144\n    time_span=0.0001s, test_ID=191, label=1, output_node=1, voltage=0.0029492031317204237\n    time_span=0.0001s, test_ID=191, label=1, output_node=2, voltage=0.005375498440116644\n    time_span=0.0001s, test_ID=191, label=1, output_node=3, voltage=0.004117530304938555\n    time_span=0.0001s, test_ID=191, label=1, output_node=4, voltage=0.002759960014373064\n    time_span=0.0001s, test_ID=191, label=1, output_node=5, voltage=0.002109561813995242\n    time_span=0.0001s, test_ID=191, label=1, output_node=6, voltage=0.006731076166033745\n    time_span=0.0001s, test_ID=191, label=1, output_node=7, voltage=0.003934262786060572\n    time_span=0.0001s, test_ID=191, label=1, output_node=8, voltage=0.0028565735556185246\n    time_span=0.0001s, test_ID=191, label=1, output_node=9, voltage=0.0011065737344324589\n    time_span=0.0001s, test_ID=191, label=1, output_node=10, voltage=0.002607569796964526\n    time_span=0.0001s, test_ID=191, label=1, output_node=11, voltage=0.0010288843186572194\n    time_span=0.0001s, test_ID=191, label=1, output_node=12, voltage=0.0004641434352379292\n    time_span=0.0001s, test_ID=191, label=1, output_node=13, voltage=0.0008406375418417156\n    time_span=0.0001s, test_ID=191, label=1, output_node=14, voltage=0.0022310756612569094\n    time_span=0.0001s, test_ID=191, label=1, output_node=15, voltage=0.0034621511586010456\n    time_span=0.0001s, test_ID=191, label=1, output_node=16, voltage=0.006379482336342335\n    time_span=0.0001s, test_ID=191, label=1, output_node=17, voltage=0.002208167454227805\n    time_span=0.0001s, test_ID=191, label=1, output_node=18, voltage=0.003085657488554716\n    time_span=0.0001s, test_ID=191, label=1, output_node=19, voltage=0.003857569769024849\n    time_span=0.0001s, test_ID=191, label=1, output_node=20, voltage=0.00038147412124089897\n    time_span=0.0001s, test_ID=191, label=1, output_node=21, voltage=0.007317729294300079\n    time_span=0.0001s, test_ID=191, label=1, output_node=22, voltage=0.00261055794544518\n    time_span=0.0001s, test_ID=191, label=1, output_node=23, voltage=-0.00032768925302661955\n    time_span=0.0001s, test_ID=191, label=1, output_node=24, voltage=0.005487052258104086\n    time_span=0.0001s, test_ID=191, label=1, output_node=25, voltage=0.006139441858977079\n    time_span=0.0001s, test_ID=191, label=1, output_node=26, voltage=0.0019153383327648044\n    time_span=0.0001s, test_ID=191, label=1, output_node=27, voltage=0.003589641535654664\n    time_span=0.0001s, test_ID=191, label=1, output_node=28, voltage=0.0037888444494456053\n    time_span=0.0001s, test_ID=191, label=1, output_node=29, voltage=0.0042111556977033615\n    time_span=0.0001s, test_ID=191, label=1, output_node=30, voltage=-0.0019890437833964825\n    time_span=0.0001s, test_ID=191, label=1, output_node=31, voltage=0.0018456174293532968\n    time_span=0.0001s, test_ID=191, label=1, output_node=32, voltage=0.0030079681891947985\n    time_span=0.0001s, test_ID=191, label=1, output_node=33, voltage=0.0013705180026590824\n    time_span=0.0001s, test_ID=191, label=1, output_node=34, voltage=0.0034013944678008556\n    time_span=0.0001s, test_ID=191, label=1, output_node=35, voltage=0.0029292828403413296\n    time_span=0.0001s, test_ID=191, label=1, output_node=36, voltage=0.0018247009720653296\n    time_span=0.0001s, test_ID=191, label=1, output_node=37, voltage=0.004112549591809511\n    time_span=0.0001s, test_ID=191, label=1, output_node=38, voltage=0.0025836655404418707\n    time_span=0.0001s, test_ID=191, label=1, output_node=39, voltage=0.0041952189058065414\n    time_span=0.0001s, test_ID=191, label=1, output_node=40, voltage=0.0026015935000032187\n    time_span=0.0001s, test_ID=191, label=1, output_node=41, voltage=0.003000000026077032\n    time_span=0.0001s, test_ID=191, label=1, output_node=42, voltage=0.003591633401811123\n    time_span=0.0001s, test_ID=191, label=1, output_node=43, voltage=0.005448206793516874\n    time_span=0.0001s, test_ID=191, label=1, output_node=44, voltage=0.004821713548153639\n    time_span=0.0001s, test_ID=191, label=1, output_node=45, voltage=0.004497012123465538\n    time_span=0.0001s, test_ID=191, label=1, output_node=46, voltage=0.0044990042224526405\n    time_span=0.0001s, test_ID=191, label=1, output_node=47, voltage=0.001248007989488542\n    time_span=0.0001s, test_ID=191, label=1, output_node=48, voltage=0.0029780876357108355\n    time_span=0.0001s, test_ID=191, label=1, output_node=49, voltage=0.001793824601918459\n    time_span=0.0001s, test_ID=191, label=1, output_node=50, voltage=0.004652390256524086\n    time_span=0.0001s, test_ID=191, label=1, output_node=51, voltage=0.005258964374661446\n    time_span=0.0001s, test_ID=191, label=1, output_node=52, voltage=0.0010806773789227009\n    time_span=0.0001s, test_ID=191, label=1, output_node=53, voltage=0.0009800795232877135\n    time_span=0.0001s, test_ID=191, label=1, output_node=54, voltage=0.004057768732309341\n    time_span=0.0001s, test_ID=191, label=1, output_node=55, voltage=0.004478088114410639\n    time_span=0.0001s, test_ID=191, label=1, output_node=56, voltage=0.00032768931123428047\n    time_span=0.0001s, test_ID=191, label=1, output_node=57, voltage=0.0069462149403989315\n    time_span=0.0001s, test_ID=191, label=1, output_node=58, voltage=0.0022988049313426018\n    time_span=0.0001s, test_ID=191, label=1, output_node=59, voltage=0.003188247326761484\n    time_span=0.0001s, test_ID=191, label=1, output_node=60, voltage=0.005102589726448059\n    time_span=0.0001s, test_ID=191, label=1, output_node=61, voltage=0.0031932273413985968\n    time_span=0.0001s, test_ID=191, label=1, output_node=62, voltage=0.002119522076100111\n    time_span=0.0001s, test_ID=191, label=1, output_node=63, voltage=0.004595617763698101\n    time_span=0.0001s, test_ID=191, label=1, output_node=64, voltage=0.006196214817464352\n    time_span=0.0001s, test_ID=191, label=1, output_node=65, voltage=0.004206175450235605\n    time_span=0.0001s, test_ID=191, label=1, output_node=66, voltage=0.0024770917370915413\n    time_span=0.0001s, test_ID=191, label=1, output_node=67, voltage=0.006041832733899355\n    time_span=0.0001s, test_ID=191, label=1, output_node=68, voltage=0.0024342630058526993\n    time_span=0.0001s, test_ID=191, label=1, output_node=69, voltage=0.001706175273284316\n    time_span=0.0001s, test_ID=191, label=1, output_node=70, voltage=-0.0009910358348861337\n    time_span=0.0001s, test_ID=191, label=1, output_node=71, voltage=0.003790836548432708\n    time_span=0.0001s, test_ID=191, label=1, output_node=72, voltage=0.0038356571458280087\n    time_span=0.0001s, test_ID=191, label=1, output_node=73, voltage=0.0036523905582726\n    time_span=0.0001s, test_ID=191, label=1, output_node=74, voltage=0.003499999875202775\n    time_span=0.0001s, test_ID=191, label=1, output_node=75, voltage=0.004464143421500921\n    time_span=0.0001s, test_ID=191, label=1, output_node=76, voltage=0.0009850598871707916\n    time_span=0.0001s, test_ID=191, label=1, output_node=77, voltage=0.0024312748573720455\n    time_span=0.0001s, test_ID=191, label=1, output_node=78, voltage=0.006079681217670441\n    time_span=0.0001s, test_ID=191, label=1, output_node=79, voltage=0.002057769102975726\n    time_span=0.0001s, test_ID=191, label=1, output_node=80, voltage=0.0030956172849982977\n    time_span=0.0001s, test_ID=191, label=1, output_node=81, voltage=0.0024501990992575884\n    time_span=0.0001s, test_ID=191, label=1, output_node=82, voltage=0.0011015936033800244\n    time_span=0.0001s, test_ID=191, label=1, output_node=83, voltage=0.000582669279538095\n    time_span=0.0001s, test_ID=191, label=1, output_node=84, voltage=0.004481075797230005\n    time_span=0.0001s, test_ID=191, label=1, output_node=85, voltage=0.003470119321718812\n    time_span=0.0001s, test_ID=191, label=1, output_node=86, voltage=0.003137450199574232\n    time_span=0.0001s, test_ID=191, label=1, output_node=87, voltage=0.0038545820862054825\n    time_span=0.0001s, test_ID=191, label=1, output_node=88, voltage=0.003990039695054293\n    time_span=0.0001s, test_ID=191, label=1, output_node=89, voltage=0.004750995896756649\n    time_span=0.0001s, test_ID=191, label=1, output_node=90, voltage=0.002828685101121664\n    time_span=0.0001s, test_ID=191, label=1, output_node=91, voltage=0.00199203216470778\n    time_span=0.0001s, test_ID=191, label=1, output_node=92, voltage=0.0015896415570750833\n    time_span=0.0001s, test_ID=191, label=1, output_node=93, voltage=0.005015936680138111\n    time_span=0.0001s, test_ID=191, label=1, output_node=94, voltage=0.004674302414059639\n    time_span=0.0001s, test_ID=191, label=1, output_node=95, voltage=0.0050926292315125465\n    time_span=0.0001s, test_ID=191, label=1, output_node=96, voltage=0.003465139539912343\n    time_span=0.0001s, test_ID=191, label=1, output_node=97, voltage=0.0023466134443879128\n    time_span=0.0001s, test_ID=191, label=1, output_node=98, voltage=-0.00014741036284249276\n    time_span=0.0001s, test_ID=191, label=1, output_node=99, voltage=0.002664342289790511\n    time_span=0.0001s, test_ID=191, label=1, output_node=sum, voltage=0.015355577692389488\n    Time consumed for 1 sample = 1199.192355632782 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '191'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=192, label=0, output_node=bkg, voltage=-0.004725099075585604\n    time_span=0.0001s, test_ID=192, label=0, output_node=0, voltage=0.016984064131975174\n    time_span=0.0001s, test_ID=192, label=0, output_node=1, voltage=0.012999999336898327\n    time_span=0.0001s, test_ID=192, label=0, output_node=2, voltage=0.014326694421470165\n    time_span=0.0001s, test_ID=192, label=0, output_node=3, voltage=0.021298803389072418\n    time_span=0.0001s, test_ID=192, label=0, output_node=4, voltage=0.011216134764254093\n    time_span=0.0001s, test_ID=192, label=0, output_node=5, voltage=0.006857569795101881\n    time_span=0.0001s, test_ID=192, label=0, output_node=6, voltage=0.020685259252786636\n    time_span=0.0001s, test_ID=192, label=0, output_node=7, voltage=0.011006972752511501\n    time_span=0.0001s, test_ID=192, label=0, output_node=8, voltage=0.012148406356573105\n    time_span=0.0001s, test_ID=192, label=0, output_node=9, voltage=0.01881474070250988\n    time_span=0.0001s, test_ID=192, label=0, output_node=10, voltage=0.016277888789772987\n    time_span=0.0001s, test_ID=192, label=0, output_node=11, voltage=0.010268923826515675\n    time_span=0.0001s, test_ID=192, label=0, output_node=12, voltage=0.013626493513584137\n    time_span=0.0001s, test_ID=192, label=0, output_node=13, voltage=0.013910357840359211\n    time_span=0.0001s, test_ID=192, label=0, output_node=14, voltage=0.017653385177254677\n    time_span=0.0001s, test_ID=192, label=0, output_node=15, voltage=0.01429481990635395\n    time_span=0.0001s, test_ID=192, label=0, output_node=16, voltage=0.010836653411388397\n    time_span=0.0001s, test_ID=192, label=0, output_node=17, voltage=0.01117430254817009\n    time_span=0.0001s, test_ID=192, label=0, output_node=18, voltage=0.012728087604045868\n    time_span=0.0001s, test_ID=192, label=0, output_node=19, voltage=0.011189242824912071\n    time_span=0.0001s, test_ID=192, label=0, output_node=20, voltage=0.017427291721105576\n    time_span=0.0001s, test_ID=192, label=0, output_node=21, voltage=0.011234063655138016\n    time_span=0.0001s, test_ID=192, label=0, output_node=22, voltage=0.012911354191601276\n    time_span=0.0001s, test_ID=192, label=0, output_node=23, voltage=0.018188247457146645\n    time_span=0.0001s, test_ID=192, label=0, output_node=24, voltage=0.011706175282597542\n    time_span=0.0001s, test_ID=192, label=0, output_node=25, voltage=0.01752290688455105\n    time_span=0.0001s, test_ID=192, label=0, output_node=26, voltage=0.010051792487502098\n    time_span=0.0001s, test_ID=192, label=0, output_node=27, voltage=0.009673306718468666\n    time_span=0.0001s, test_ID=192, label=0, output_node=28, voltage=0.009832669049501419\n    time_span=0.0001s, test_ID=192, label=0, output_node=29, voltage=0.015756972134113312\n    time_span=0.0001s, test_ID=192, label=0, output_node=30, voltage=0.012466134503483772\n    time_span=0.0001s, test_ID=192, label=0, output_node=31, voltage=0.012844621203839779\n    time_span=0.0001s, test_ID=192, label=0, output_node=32, voltage=0.018851594999432564\n    time_span=0.0001s, test_ID=192, label=0, output_node=33, voltage=0.018973106518387794\n    time_span=0.0001s, test_ID=192, label=0, output_node=34, voltage=0.01074601523578167\n    time_span=0.0001s, test_ID=192, label=0, output_node=35, voltage=0.00940737035125494\n    time_span=0.0001s, test_ID=192, label=0, output_node=36, voltage=0.017080675810575485\n    time_span=0.0001s, test_ID=192, label=0, output_node=37, voltage=0.01793227344751358\n    time_span=0.0001s, test_ID=192, label=0, output_node=38, voltage=0.01858864352107048\n    time_span=0.0001s, test_ID=192, label=0, output_node=39, voltage=0.01912948116660118\n    time_span=0.0001s, test_ID=192, label=0, output_node=40, voltage=0.012393425218760967\n    time_span=0.0001s, test_ID=192, label=0, output_node=41, voltage=0.010393425822257996\n    time_span=0.0001s, test_ID=192, label=0, output_node=42, voltage=0.01305378507822752\n    time_span=0.0001s, test_ID=192, label=0, output_node=43, voltage=0.011688247323036194\n    time_span=0.0001s, test_ID=192, label=0, output_node=44, voltage=0.014772907830774784\n    time_span=0.0001s, test_ID=192, label=0, output_node=45, voltage=0.013666334562003613\n    time_span=0.0001s, test_ID=192, label=0, output_node=46, voltage=0.014079682528972626\n    time_span=0.0001s, test_ID=192, label=0, output_node=47, voltage=0.015112549066543579\n    time_span=0.0001s, test_ID=192, label=0, output_node=48, voltage=0.010800796560943127\n    time_span=0.0001s, test_ID=192, label=0, output_node=49, voltage=0.016257967799901962\n    time_span=0.0001s, test_ID=192, label=0, output_node=50, voltage=0.01787549816071987\n    time_span=0.0001s, test_ID=192, label=0, output_node=51, voltage=0.01881474070250988\n    time_span=0.0001s, test_ID=192, label=0, output_node=52, voltage=0.01471115555614233\n    time_span=0.0001s, test_ID=192, label=0, output_node=53, voltage=0.019941234961152077\n    time_span=0.0001s, test_ID=192, label=0, output_node=54, voltage=0.022215140983462334\n    time_span=0.0001s, test_ID=192, label=0, output_node=55, voltage=0.011978087946772575\n    time_span=0.0001s, test_ID=192, label=0, output_node=56, voltage=0.021388445049524307\n    time_span=0.0001s, test_ID=192, label=0, output_node=57, voltage=0.015062750317156315\n    time_span=0.0001s, test_ID=192, label=0, output_node=58, voltage=0.018252987414598465\n    time_span=0.0001s, test_ID=192, label=0, output_node=59, voltage=0.013187251053750515\n    time_span=0.0001s, test_ID=192, label=0, output_node=60, voltage=0.011369521729648113\n    time_span=0.0001s, test_ID=192, label=0, output_node=61, voltage=0.01212450210005045\n    time_span=0.0001s, test_ID=192, label=0, output_node=62, voltage=0.015965139493346214\n    time_span=0.0001s, test_ID=192, label=0, output_node=63, voltage=0.016969121992588043\n    time_span=0.0001s, test_ID=192, label=0, output_node=64, voltage=0.014022909104824066\n    time_span=0.0001s, test_ID=192, label=0, output_node=65, voltage=0.013610556721687317\n    time_span=0.0001s, test_ID=192, label=0, output_node=66, voltage=0.013369521126151085\n    time_span=0.0001s, test_ID=192, label=0, output_node=67, voltage=0.010950198397040367\n    time_span=0.0001s, test_ID=192, label=0, output_node=68, voltage=0.011157370172441006\n    time_span=0.0001s, test_ID=192, label=0, output_node=69, voltage=0.018331674858927727\n    time_span=0.0001s, test_ID=192, label=0, output_node=70, voltage=0.013341633602976799\n    time_span=0.0001s, test_ID=192, label=0, output_node=71, voltage=0.015732072293758392\n    time_span=0.0001s, test_ID=192, label=0, output_node=72, voltage=0.016393426805734634\n    time_span=0.0001s, test_ID=192, label=0, output_node=73, voltage=0.016022907570004463\n    time_span=0.0001s, test_ID=192, label=0, output_node=74, voltage=0.010415338911116123\n    time_span=0.0001s, test_ID=192, label=0, output_node=75, voltage=0.012877491302788258\n    time_span=0.0001s, test_ID=192, label=0, output_node=76, voltage=0.017462151125073433\n    time_span=0.0001s, test_ID=192, label=0, output_node=77, voltage=0.0153346611186862\n    time_span=0.0001s, test_ID=192, label=0, output_node=78, voltage=0.015130477957427502\n    time_span=0.0001s, test_ID=192, label=0, output_node=79, voltage=0.018666336312890053\n    time_span=0.0001s, test_ID=192, label=0, output_node=80, voltage=0.012485059909522533\n    time_span=0.0001s, test_ID=192, label=0, output_node=81, voltage=0.023368528112769127\n    time_span=0.0001s, test_ID=192, label=0, output_node=82, voltage=0.016272909939289093\n    time_span=0.0001s, test_ID=192, label=0, output_node=83, voltage=0.010158366523683071\n    time_span=0.0001s, test_ID=192, label=0, output_node=84, voltage=0.016528885811567307\n    time_span=0.0001s, test_ID=192, label=0, output_node=85, voltage=0.01993127539753914\n    time_span=0.0001s, test_ID=192, label=0, output_node=86, voltage=0.013798804953694344\n    time_span=0.0001s, test_ID=192, label=0, output_node=87, voltage=0.012791832908987999\n    time_span=0.0001s, test_ID=192, label=0, output_node=88, voltage=0.017305776476860046\n    time_span=0.0001s, test_ID=192, label=0, output_node=89, voltage=0.015573704615235329\n    time_span=0.0001s, test_ID=192, label=0, output_node=90, voltage=0.013752988539636135\n    time_span=0.0001s, test_ID=192, label=0, output_node=91, voltage=0.018416335806250572\n    time_span=0.0001s, test_ID=192, label=0, output_node=92, voltage=0.023939242586493492\n    time_span=0.0001s, test_ID=192, label=0, output_node=93, voltage=0.01190537866204977\n    time_span=0.0001s, test_ID=192, label=0, output_node=94, voltage=0.01164740975946188\n    time_span=0.0001s, test_ID=192, label=0, output_node=95, voltage=0.0126942228525877\n    time_span=0.0001s, test_ID=192, label=0, output_node=96, voltage=0.01418924331665039\n    time_span=0.0001s, test_ID=192, label=0, output_node=97, voltage=0.017688246443867683\n    time_span=0.0001s, test_ID=192, label=0, output_node=98, voltage=0.016301793977618217\n    time_span=0.0001s, test_ID=192, label=0, output_node=99, voltage=0.015361553058028221\n    time_span=0.0001s, test_ID=192, label=0, output_node=sum, voltage=0.039289843291044235\n    Time consumed for 1 sample = 1204.6972386837006 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '192'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=193, label=9, output_node=bkg, voltage=-0.00447111576795578\n    time_span=0.0001s, test_ID=193, label=9, output_node=0, voltage=0.004729083739221096\n    time_span=0.0001s, test_ID=193, label=9, output_node=1, voltage=0.007038845214992762\n    time_span=0.0001s, test_ID=193, label=9, output_node=2, voltage=0.015438247472047806\n    time_span=0.0001s, test_ID=193, label=9, output_node=3, voltage=0.007581673096865416\n    time_span=0.0001s, test_ID=193, label=9, output_node=4, voltage=0.008570716716349125\n    time_span=0.0001s, test_ID=193, label=9, output_node=5, voltage=0.009169322438538074\n    time_span=0.0001s, test_ID=193, label=9, output_node=6, voltage=0.005423306953161955\n    time_span=0.0001s, test_ID=193, label=9, output_node=7, voltage=0.01103187259286642\n    time_span=0.0001s, test_ID=193, label=9, output_node=8, voltage=0.007845617830753326\n    time_span=0.0001s, test_ID=193, label=9, output_node=9, voltage=0.008858566172420979\n    time_span=0.0001s, test_ID=193, label=9, output_node=10, voltage=0.004786852281540632\n    time_span=0.0001s, test_ID=193, label=9, output_node=11, voltage=0.00983565766364336\n    time_span=0.0001s, test_ID=193, label=9, output_node=12, voltage=0.012189243920147419\n    time_span=0.0001s, test_ID=193, label=9, output_node=13, voltage=0.00658764922991395\n    time_span=0.0001s, test_ID=193, label=9, output_node=14, voltage=0.011472112499177456\n    time_span=0.0001s, test_ID=193, label=9, output_node=15, voltage=0.010798804461956024\n    time_span=0.0001s, test_ID=193, label=9, output_node=16, voltage=0.00769521901383996\n    time_span=0.0001s, test_ID=193, label=9, output_node=17, voltage=0.009230080060660839\n    time_span=0.0001s, test_ID=193, label=9, output_node=18, voltage=0.007315737195312977\n    time_span=0.0001s, test_ID=193, label=9, output_node=19, voltage=0.009733066894114017\n    time_span=0.0001s, test_ID=193, label=9, output_node=20, voltage=0.006389442831277847\n    time_span=0.0001s, test_ID=193, label=9, output_node=21, voltage=0.008213147521018982\n    time_span=0.0001s, test_ID=193, label=9, output_node=22, voltage=0.00931474193930626\n    time_span=0.0001s, test_ID=193, label=9, output_node=23, voltage=0.00850996095687151\n    time_span=0.0001s, test_ID=193, label=9, output_node=24, voltage=0.01364442240446806\n    time_span=0.0001s, test_ID=193, label=9, output_node=25, voltage=0.004429283086210489\n    time_span=0.0001s, test_ID=193, label=9, output_node=26, voltage=0.004349600989371538\n    time_span=0.0001s, test_ID=193, label=9, output_node=27, voltage=0.011931275017559528\n    time_span=0.0001s, test_ID=193, label=9, output_node=28, voltage=0.008587649092078209\n    time_span=0.0001s, test_ID=193, label=9, output_node=29, voltage=0.011534860357642174\n    time_span=0.0001s, test_ID=193, label=9, output_node=30, voltage=0.009781872853636742\n    time_span=0.0001s, test_ID=193, label=9, output_node=31, voltage=0.007782868575304747\n    time_span=0.0001s, test_ID=193, label=9, output_node=32, voltage=0.006957171484827995\n    time_span=0.0001s, test_ID=193, label=9, output_node=33, voltage=0.010399402119219303\n    time_span=0.0001s, test_ID=193, label=9, output_node=34, voltage=0.00999402441084385\n    time_span=0.0001s, test_ID=193, label=9, output_node=35, voltage=0.00975498091429472\n    time_span=0.0001s, test_ID=193, label=9, output_node=36, voltage=0.009049801155924797\n    time_span=0.0001s, test_ID=193, label=9, output_node=37, voltage=0.008273905143141747\n    time_span=0.0001s, test_ID=193, label=9, output_node=38, voltage=0.007588645443320274\n    time_span=0.0001s, test_ID=193, label=9, output_node=39, voltage=0.009776892140507698\n    time_span=0.0001s, test_ID=193, label=9, output_node=40, voltage=0.008625498041510582\n    time_span=0.0001s, test_ID=193, label=9, output_node=41, voltage=0.010432272218167782\n    time_span=0.0001s, test_ID=193, label=9, output_node=42, voltage=0.00623007956892252\n    time_span=0.0001s, test_ID=193, label=9, output_node=43, voltage=0.009916335344314575\n    time_span=0.0001s, test_ID=193, label=9, output_node=44, voltage=0.011006972752511501\n    time_span=0.0001s, test_ID=193, label=9, output_node=45, voltage=0.013443227857351303\n    time_span=0.0001s, test_ID=193, label=9, output_node=46, voltage=0.013362550176680088\n    time_span=0.0001s, test_ID=193, label=9, output_node=47, voltage=0.009607569314539433\n    time_span=0.0001s, test_ID=193, label=9, output_node=48, voltage=0.005986055824905634\n    time_span=0.0001s, test_ID=193, label=9, output_node=49, voltage=0.008872509002685547\n    time_span=0.0001s, test_ID=193, label=9, output_node=50, voltage=0.01092330738902092\n    time_span=0.0001s, test_ID=193, label=9, output_node=51, voltage=0.009635457769036293\n    time_span=0.0001s, test_ID=193, label=9, output_node=52, voltage=0.006085657514631748\n    time_span=0.0001s, test_ID=193, label=9, output_node=53, voltage=0.008371513336896896\n    time_span=0.0001s, test_ID=193, label=9, output_node=54, voltage=0.007729083765298128\n    time_span=0.0001s, test_ID=193, label=9, output_node=55, voltage=0.010471115820109844\n    time_span=0.0001s, test_ID=193, label=9, output_node=56, voltage=0.00995717104524374\n    time_span=0.0001s, test_ID=193, label=9, output_node=57, voltage=0.010990040376782417\n    time_span=0.0001s, test_ID=193, label=9, output_node=58, voltage=0.010367530398070812\n    time_span=0.0001s, test_ID=193, label=9, output_node=59, voltage=0.007472111843526363\n    time_span=0.0001s, test_ID=193, label=9, output_node=60, voltage=0.007120518013834953\n    time_span=0.0001s, test_ID=193, label=9, output_node=61, voltage=0.009642429649829865\n    time_span=0.0001s, test_ID=193, label=9, output_node=62, voltage=0.011877489276230335\n    time_span=0.0001s, test_ID=193, label=9, output_node=63, voltage=0.011540836654603481\n    time_span=0.0001s, test_ID=193, label=9, output_node=64, voltage=0.00897908303886652\n    time_span=0.0001s, test_ID=193, label=9, output_node=65, voltage=0.009712152183055878\n    time_span=0.0001s, test_ID=193, label=9, output_node=66, voltage=0.008455179631710052\n    time_span=0.0001s, test_ID=193, label=9, output_node=67, voltage=0.008803785778582096\n    time_span=0.0001s, test_ID=193, label=9, output_node=68, voltage=0.014161353930830956\n    time_span=0.0001s, test_ID=193, label=9, output_node=69, voltage=0.008856574073433876\n    time_span=0.0001s, test_ID=193, label=9, output_node=70, voltage=0.006748008541762829\n    time_span=0.0001s, test_ID=193, label=9, output_node=71, voltage=0.008000995963811874\n    time_span=0.0001s, test_ID=193, label=9, output_node=72, voltage=0.010245020501315594\n    time_span=0.0001s, test_ID=193, label=9, output_node=73, voltage=0.0084043825045228\n    time_span=0.0001s, test_ID=193, label=9, output_node=74, voltage=0.005394422449171543\n    time_span=0.0001s, test_ID=193, label=9, output_node=75, voltage=0.011110558174550533\n    time_span=0.0001s, test_ID=193, label=9, output_node=76, voltage=0.011585657484829426\n    time_span=0.0001s, test_ID=193, label=9, output_node=77, voltage=0.009086653590202332\n    time_span=0.0001s, test_ID=193, label=9, output_node=78, voltage=0.011337650008499622\n    time_span=0.0001s, test_ID=193, label=9, output_node=79, voltage=0.01055079698562622\n    time_span=0.0001s, test_ID=193, label=9, output_node=80, voltage=0.010181275196373463\n    time_span=0.0001s, test_ID=193, label=9, output_node=81, voltage=0.009609561413526535\n    time_span=0.0001s, test_ID=193, label=9, output_node=82, voltage=0.002633466152474284\n    time_span=0.0001s, test_ID=193, label=9, output_node=83, voltage=0.015731075778603554\n    time_span=0.0001s, test_ID=193, label=9, output_node=84, voltage=0.004651394672691822\n    time_span=0.0001s, test_ID=193, label=9, output_node=85, voltage=0.008836653083562851\n    time_span=0.0001s, test_ID=193, label=9, output_node=86, voltage=0.012979083694517612\n    time_span=0.0001s, test_ID=193, label=9, output_node=87, voltage=0.010404381901025772\n    time_span=0.0001s, test_ID=193, label=9, output_node=88, voltage=0.009368525817990303\n    time_span=0.0001s, test_ID=193, label=9, output_node=89, voltage=0.010126493871212006\n    time_span=0.0001s, test_ID=193, label=9, output_node=90, voltage=0.007301792502403259\n    time_span=0.0001s, test_ID=193, label=9, output_node=91, voltage=0.010448207147419453\n    time_span=0.0001s, test_ID=193, label=9, output_node=92, voltage=0.0041862549260258675\n    time_span=0.0001s, test_ID=193, label=9, output_node=93, voltage=0.014048805460333824\n    time_span=0.0001s, test_ID=193, label=9, output_node=94, voltage=0.01157470140606165\n    time_span=0.0001s, test_ID=193, label=9, output_node=95, voltage=0.010965140536427498\n    time_span=0.0001s, test_ID=193, label=9, output_node=96, voltage=0.010096613317728043\n    time_span=0.0001s, test_ID=193, label=9, output_node=97, voltage=0.009753984399139881\n    time_span=0.0001s, test_ID=193, label=9, output_node=98, voltage=0.008363545872271061\n    time_span=0.0001s, test_ID=193, label=9, output_node=99, voltage=0.009981075301766396\n    time_span=0.0001s, test_ID=193, label=9, output_node=sum, voltage=0.025233067572116852\n    Time consumed for 1 sample = 1198.9469175338745 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '193'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=194, label=0, output_node=bkg, voltage=-0.00536454189568758\n    time_span=0.0001s, test_ID=194, label=0, output_node=0, voltage=0.013569721020758152\n    time_span=0.0001s, test_ID=194, label=0, output_node=1, voltage=0.015858566388487816\n    time_span=0.0001s, test_ID=194, label=0, output_node=2, voltage=0.01233764924108982\n    time_span=0.0001s, test_ID=194, label=0, output_node=3, voltage=0.01753685250878334\n    time_span=0.0001s, test_ID=194, label=0, output_node=4, voltage=0.012534860521554947\n    time_span=0.0001s, test_ID=194, label=0, output_node=5, voltage=0.009327689185738564\n    time_span=0.0001s, test_ID=194, label=0, output_node=6, voltage=0.01982569508254528\n    time_span=0.0001s, test_ID=194, label=0, output_node=7, voltage=0.015728088095784187\n    time_span=0.0001s, test_ID=194, label=0, output_node=8, voltage=0.01870816759765148\n    time_span=0.0001s, test_ID=194, label=0, output_node=9, voltage=0.014898406341671944\n    time_span=0.0001s, test_ID=194, label=0, output_node=10, voltage=0.014140438288450241\n    time_span=0.0001s, test_ID=194, label=0, output_node=11, voltage=0.017017928883433342\n    time_span=0.0001s, test_ID=194, label=0, output_node=12, voltage=0.01752191223204136\n    time_span=0.0001s, test_ID=194, label=0, output_node=13, voltage=0.014725100249052048\n    time_span=0.0001s, test_ID=194, label=0, output_node=14, voltage=0.02143426425755024\n    time_span=0.0001s, test_ID=194, label=0, output_node=15, voltage=0.017033865675330162\n    time_span=0.0001s, test_ID=194, label=0, output_node=16, voltage=0.01174900308251381\n    time_span=0.0001s, test_ID=194, label=0, output_node=17, voltage=0.013795817270874977\n    time_span=0.0001s, test_ID=194, label=0, output_node=18, voltage=0.017640437930822372\n    time_span=0.0001s, test_ID=194, label=0, output_node=19, voltage=0.013074700720608234\n    time_span=0.0001s, test_ID=194, label=0, output_node=20, voltage=0.018690237775444984\n    time_span=0.0001s, test_ID=194, label=0, output_node=21, voltage=0.0189372505992651\n    time_span=0.0001s, test_ID=194, label=0, output_node=22, voltage=0.01509860623627901\n    time_span=0.0001s, test_ID=194, label=0, output_node=23, voltage=0.018081672489643097\n    time_span=0.0001s, test_ID=194, label=0, output_node=24, voltage=0.01630776934325695\n    time_span=0.0001s, test_ID=194, label=0, output_node=25, voltage=0.017373505979776382\n    time_span=0.0001s, test_ID=194, label=0, output_node=26, voltage=0.011426295153796673\n    time_span=0.0001s, test_ID=194, label=0, output_node=27, voltage=0.016741035506129265\n    time_span=0.0001s, test_ID=194, label=0, output_node=28, voltage=0.011992031708359718\n    time_span=0.0001s, test_ID=194, label=0, output_node=29, voltage=0.016957173123955727\n    time_span=0.0001s, test_ID=194, label=0, output_node=30, voltage=0.01577490195631981\n    time_span=0.0001s, test_ID=194, label=0, output_node=31, voltage=0.01233864575624466\n    time_span=0.0001s, test_ID=194, label=0, output_node=32, voltage=0.01649302802979946\n    time_span=0.0001s, test_ID=194, label=0, output_node=33, voltage=0.018618525937199593\n    time_span=0.0001s, test_ID=194, label=0, output_node=34, voltage=0.018179282546043396\n    time_span=0.0001s, test_ID=194, label=0, output_node=35, voltage=0.015850597992539406\n    time_span=0.0001s, test_ID=194, label=0, output_node=36, voltage=0.013480080291628838\n    time_span=0.0001s, test_ID=194, label=0, output_node=37, voltage=0.011916334740817547\n    time_span=0.0001s, test_ID=194, label=0, output_node=38, voltage=0.012561752460896969\n    time_span=0.0001s, test_ID=194, label=0, output_node=39, voltage=0.01955777034163475\n    time_span=0.0001s, test_ID=194, label=0, output_node=40, voltage=0.01501494087278843\n    time_span=0.0001s, test_ID=194, label=0, output_node=41, voltage=0.014287848956882954\n    time_span=0.0001s, test_ID=194, label=0, output_node=42, voltage=0.017818724736571312\n    time_span=0.0001s, test_ID=194, label=0, output_node=43, voltage=0.01424203161150217\n    time_span=0.0001s, test_ID=194, label=0, output_node=44, voltage=0.016885457560420036\n    time_span=0.0001s, test_ID=194, label=0, output_node=45, voltage=0.01696314476430416\n    time_span=0.0001s, test_ID=194, label=0, output_node=46, voltage=0.017321713268756866\n    time_span=0.0001s, test_ID=194, label=0, output_node=47, voltage=0.017865538597106934\n    time_span=0.0001s, test_ID=194, label=0, output_node=48, voltage=0.014256971888244152\n    time_span=0.0001s, test_ID=194, label=0, output_node=49, voltage=0.01102490071207285\n    time_span=0.0001s, test_ID=194, label=0, output_node=50, voltage=0.018998010084033012\n    time_span=0.0001s, test_ID=194, label=0, output_node=51, voltage=0.020421316847205162\n    time_span=0.0001s, test_ID=194, label=0, output_node=52, voltage=0.008645419031381607\n    time_span=0.0001s, test_ID=194, label=0, output_node=53, voltage=0.012473108246922493\n    time_span=0.0001s, test_ID=194, label=0, output_node=54, voltage=0.012359562329947948\n    time_span=0.0001s, test_ID=194, label=0, output_node=55, voltage=0.012072709389030933\n    time_span=0.0001s, test_ID=194, label=0, output_node=56, voltage=0.020347610116004944\n    time_span=0.0001s, test_ID=194, label=0, output_node=57, voltage=0.020000997930765152\n    time_span=0.0001s, test_ID=194, label=0, output_node=58, voltage=0.016158366575837135\n    time_span=0.0001s, test_ID=194, label=0, output_node=59, voltage=0.010622510686516762\n    time_span=0.0001s, test_ID=194, label=0, output_node=60, voltage=0.016039840877056122\n    time_span=0.0001s, test_ID=194, label=0, output_node=61, voltage=0.00989641435444355\n    time_span=0.0001s, test_ID=194, label=0, output_node=62, voltage=0.017525896430015564\n    time_span=0.0001s, test_ID=194, label=0, output_node=63, voltage=0.0199302788823843\n    time_span=0.0001s, test_ID=194, label=0, output_node=64, voltage=0.015412349253892899\n    time_span=0.0001s, test_ID=194, label=0, output_node=65, voltage=0.013242032378911972\n    time_span=0.0001s, test_ID=194, label=0, output_node=66, voltage=0.01683466136455536\n    time_span=0.0001s, test_ID=194, label=0, output_node=67, voltage=0.016012948006391525\n    time_span=0.0001s, test_ID=194, label=0, output_node=68, voltage=0.019943227991461754\n    time_span=0.0001s, test_ID=194, label=0, output_node=69, voltage=0.018414342775940895\n    time_span=0.0001s, test_ID=194, label=0, output_node=70, voltage=0.00892629474401474\n    time_span=0.0001s, test_ID=194, label=0, output_node=71, voltage=0.020056774839758873\n    time_span=0.0001s, test_ID=194, label=0, output_node=72, voltage=0.015333665534853935\n    time_span=0.0001s, test_ID=194, label=0, output_node=73, voltage=0.0180149395018816\n    time_span=0.0001s, test_ID=194, label=0, output_node=74, voltage=0.01155876461416483\n    time_span=0.0001s, test_ID=194, label=0, output_node=75, voltage=0.017037848010659218\n    time_span=0.0001s, test_ID=194, label=0, output_node=76, voltage=0.01966434344649315\n    time_span=0.0001s, test_ID=194, label=0, output_node=77, voltage=0.01541135460138321\n    time_span=0.0001s, test_ID=194, label=0, output_node=78, voltage=0.01784362643957138\n    time_span=0.0001s, test_ID=194, label=0, output_node=79, voltage=0.016346612945199013\n    time_span=0.0001s, test_ID=194, label=0, output_node=80, voltage=0.01524501945823431\n    time_span=0.0001s, test_ID=194, label=0, output_node=81, voltage=0.019902389496564865\n    time_span=0.0001s, test_ID=194, label=0, output_node=82, voltage=0.017858566716313362\n    time_span=0.0001s, test_ID=194, label=0, output_node=83, voltage=0.01836155354976654\n    time_span=0.0001s, test_ID=194, label=0, output_node=84, voltage=0.011354582384228706\n    time_span=0.0001s, test_ID=194, label=0, output_node=85, voltage=0.020474104210734367\n    time_span=0.0001s, test_ID=194, label=0, output_node=86, voltage=0.012467131949961185\n    time_span=0.0001s, test_ID=194, label=0, output_node=87, voltage=0.014750995673239231\n    time_span=0.0001s, test_ID=194, label=0, output_node=88, voltage=0.016884461045265198\n    time_span=0.0001s, test_ID=194, label=0, output_node=89, voltage=0.015165339224040508\n    time_span=0.0001s, test_ID=194, label=0, output_node=90, voltage=0.01931573636829853\n    time_span=0.0001s, test_ID=194, label=0, output_node=91, voltage=0.016943229362368584\n    time_span=0.0001s, test_ID=194, label=0, output_node=92, voltage=0.02250099554657936\n    time_span=0.0001s, test_ID=194, label=0, output_node=93, voltage=0.0161882471293211\n    time_span=0.0001s, test_ID=194, label=0, output_node=94, voltage=0.017854580655694008\n    time_span=0.0001s, test_ID=194, label=0, output_node=95, voltage=0.013691235333681107\n    time_span=0.0001s, test_ID=194, label=0, output_node=96, voltage=0.01537051796913147\n    time_span=0.0001s, test_ID=194, label=0, output_node=97, voltage=0.020588647574186325\n    time_span=0.0001s, test_ID=194, label=0, output_node=98, voltage=0.017340637743473053\n    time_span=0.0001s, test_ID=194, label=0, output_node=99, voltage=0.017896417528390884\n    time_span=0.0001s, test_ID=194, label=0, output_node=sum, voltage=0.03775298595428467\n    Time consumed for 1 sample = 1206.5608777999878 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '194'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=195, label=3, output_node=bkg, voltage=-0.003943226765841246\n    time_span=0.0001s, test_ID=195, label=3, output_node=0, voltage=-0.00028685267898254097\n    time_span=0.0001s, test_ID=195, label=3, output_node=1, voltage=0.001936255139298737\n    time_span=0.0001s, test_ID=195, label=3, output_node=2, voltage=0.003467131406068802\n    time_span=0.0001s, test_ID=195, label=3, output_node=3, voltage=0.002545817056670785\n    time_span=0.0001s, test_ID=195, label=3, output_node=4, voltage=0.0016842628829181194\n    time_span=0.0001s, test_ID=195, label=3, output_node=5, voltage=0.005261952057480812\n    time_span=0.0001s, test_ID=195, label=3, output_node=6, voltage=0.0038555776700377464\n    time_span=0.0001s, test_ID=195, label=3, output_node=7, voltage=0.005535856354981661\n    time_span=0.0001s, test_ID=195, label=3, output_node=8, voltage=0.0010039840126410127\n    time_span=0.0001s, test_ID=195, label=3, output_node=9, voltage=0.0011802789522334933\n    time_span=0.0001s, test_ID=195, label=3, output_node=10, voltage=0.0028087650425732136\n    time_span=0.0001s, test_ID=195, label=3, output_node=11, voltage=0.0036782866809517145\n    time_span=0.0001s, test_ID=195, label=3, output_node=12, voltage=0.002862549852579832\n    time_span=0.0001s, test_ID=195, label=3, output_node=13, voltage=0.0009571713162586093\n    time_span=0.0001s, test_ID=195, label=3, output_node=14, voltage=0.00020219130965415388\n    time_span=0.0001s, test_ID=195, label=3, output_node=15, voltage=0.002138446317985654\n    time_span=0.0001s, test_ID=195, label=3, output_node=16, voltage=0.006682270672172308\n    time_span=0.0001s, test_ID=195, label=3, output_node=17, voltage=0.006455179303884506\n    time_span=0.0001s, test_ID=195, label=3, output_node=18, voltage=0.0037410359364002943\n    time_span=0.0001s, test_ID=195, label=3, output_node=19, voltage=0.003368525765836239\n    time_span=0.0001s, test_ID=195, label=3, output_node=20, voltage=0.0023555776569992304\n    time_span=0.0001s, test_ID=195, label=3, output_node=21, voltage=0.003777888137847185\n    time_span=0.0001s, test_ID=195, label=3, output_node=22, voltage=0.004549800418317318\n    time_span=0.0001s, test_ID=195, label=3, output_node=23, voltage=-0.00013545803085435182\n    time_span=0.0001s, test_ID=195, label=3, output_node=24, voltage=0.0031035856809467077\n    time_span=0.0001s, test_ID=195, label=3, output_node=25, voltage=0.001040836563333869\n    time_span=0.0001s, test_ID=195, label=3, output_node=26, voltage=0.0005039840470999479\n    time_span=0.0001s, test_ID=195, label=3, output_node=27, voltage=0.002482071751728654\n    time_span=0.0001s, test_ID=195, label=3, output_node=28, voltage=0.004556772764772177\n    time_span=0.0001s, test_ID=195, label=3, output_node=29, voltage=0.0027988047804683447\n    time_span=0.0001s, test_ID=195, label=3, output_node=30, voltage=0.0012898406712338328\n    time_span=0.0001s, test_ID=195, label=3, output_node=31, voltage=0.0012768924934789538\n    time_span=0.0001s, test_ID=195, label=3, output_node=32, voltage=0.0005996015970595181\n    time_span=0.0001s, test_ID=195, label=3, output_node=33, voltage=0.0012549801031127572\n    time_span=0.0001s, test_ID=195, label=3, output_node=34, voltage=0.0014651394449174404\n    time_span=0.0001s, test_ID=195, label=3, output_node=35, voltage=0.0021344623528420925\n    time_span=0.0001s, test_ID=195, label=3, output_node=36, voltage=0.0022798804566264153\n    time_span=0.0001s, test_ID=195, label=3, output_node=37, voltage=0.0048177288845181465\n    time_span=0.0001s, test_ID=195, label=3, output_node=38, voltage=0.0023077689111232758\n    time_span=0.0001s, test_ID=195, label=3, output_node=39, voltage=0.0032001989893615246\n    time_span=0.0001s, test_ID=195, label=3, output_node=40, voltage=0.0017051792237907648\n    time_span=0.0001s, test_ID=195, label=3, output_node=41, voltage=0.0015009960625320673\n    time_span=0.0001s, test_ID=195, label=3, output_node=42, voltage=-0.0014203187311068177\n    time_span=0.0001s, test_ID=195, label=3, output_node=43, voltage=0.003742031753063202\n    time_span=0.0001s, test_ID=195, label=3, output_node=44, voltage=0.0030876495875418186\n    time_span=0.0001s, test_ID=195, label=3, output_node=45, voltage=0.0017470117891207337\n    time_span=0.0001s, test_ID=195, label=3, output_node=46, voltage=0.0024013943038880825\n    time_span=0.0001s, test_ID=195, label=3, output_node=47, voltage=0.002574701327830553\n    time_span=0.0001s, test_ID=195, label=3, output_node=48, voltage=0.0011474104830995202\n    time_span=0.0001s, test_ID=195, label=3, output_node=49, voltage=0.0006424302700906992\n    time_span=0.0001s, test_ID=195, label=3, output_node=50, voltage=0.00280577689409256\n    time_span=0.0001s, test_ID=195, label=3, output_node=51, voltage=0.004116533789783716\n    time_span=0.0001s, test_ID=195, label=3, output_node=52, voltage=0.0013027888489887118\n    time_span=0.0001s, test_ID=195, label=3, output_node=53, voltage=0.00030378493829630315\n    time_span=0.0001s, test_ID=195, label=3, output_node=54, voltage=0.00047310764784924686\n    time_span=0.0001s, test_ID=195, label=3, output_node=55, voltage=0.0028067731764167547\n    time_span=0.0001s, test_ID=195, label=3, output_node=56, voltage=-4.880468623014167e-05\n    time_span=0.0001s, test_ID=195, label=3, output_node=57, voltage=0.004540836438536644\n    time_span=0.0001s, test_ID=195, label=3, output_node=58, voltage=0.0015906373737379909\n    time_span=0.0001s, test_ID=195, label=3, output_node=59, voltage=-3.784859291044995e-05\n    time_span=0.0001s, test_ID=195, label=3, output_node=60, voltage=0.004626493901014328\n    time_span=0.0001s, test_ID=195, label=3, output_node=61, voltage=0.000383466191124171\n    time_span=0.0001s, test_ID=195, label=3, output_node=62, voltage=0.0033027888275682926\n    time_span=0.0001s, test_ID=195, label=3, output_node=63, voltage=0.004214143846184015\n    time_span=0.0001s, test_ID=195, label=3, output_node=64, voltage=0.0043705180287361145\n    time_span=0.0001s, test_ID=195, label=3, output_node=65, voltage=0.002208167454227805\n    time_span=0.0001s, test_ID=195, label=3, output_node=66, voltage=0.0030896414536982775\n    time_span=0.0001s, test_ID=195, label=3, output_node=67, voltage=0.0032181276474148035\n    time_span=0.0001s, test_ID=195, label=3, output_node=68, voltage=0.0011543824803084135\n    time_span=0.0001s, test_ID=195, label=3, output_node=69, voltage=0.0030876495875418186\n    time_span=0.0001s, test_ID=195, label=3, output_node=70, voltage=0.002048804657533765\n    time_span=0.0001s, test_ID=195, label=3, output_node=71, voltage=0.00027888448676094413\n    time_span=0.0001s, test_ID=195, label=3, output_node=72, voltage=0.0017908369190990925\n    time_span=0.0001s, test_ID=195, label=3, output_node=73, voltage=0.000743027834687382\n    time_span=0.0001s, test_ID=195, label=3, output_node=74, voltage=0.003362549701705575\n    time_span=0.0001s, test_ID=195, label=3, output_node=75, voltage=0.0030756972264498472\n    time_span=0.0001s, test_ID=195, label=3, output_node=76, voltage=0.001237051677890122\n    time_span=0.0001s, test_ID=195, label=3, output_node=77, voltage=0.0031872510444372892\n    time_span=0.0001s, test_ID=195, label=3, output_node=78, voltage=0.0027161352336406708\n    time_span=0.0001s, test_ID=195, label=3, output_node=79, voltage=0.0031424304470419884\n    time_span=0.0001s, test_ID=195, label=3, output_node=80, voltage=0.00015239040658343583\n    time_span=0.0001s, test_ID=195, label=3, output_node=81, voltage=0.003087649354711175\n    time_span=0.0001s, test_ID=195, label=3, output_node=82, voltage=0.001637450186535716\n    time_span=0.0001s, test_ID=195, label=3, output_node=83, voltage=0.0027519920840859413\n    time_span=0.0001s, test_ID=195, label=3, output_node=84, voltage=0.0015129483072087169\n    time_span=0.0001s, test_ID=195, label=3, output_node=85, voltage=0.000835657468996942\n    time_span=0.0001s, test_ID=195, label=3, output_node=86, voltage=0.0018037849804386497\n    time_span=0.0001s, test_ID=195, label=3, output_node=87, voltage=0.004065736662596464\n    time_span=0.0001s, test_ID=195, label=3, output_node=88, voltage=0.0021802789997309446\n    time_span=0.0001s, test_ID=195, label=3, output_node=89, voltage=0.0019860558677464724\n    time_span=0.0001s, test_ID=195, label=3, output_node=90, voltage=0.004038844723254442\n    time_span=0.0001s, test_ID=195, label=3, output_node=91, voltage=0.0012091632233932614\n    time_span=0.0001s, test_ID=195, label=3, output_node=92, voltage=0.0007739043212495744\n    time_span=0.0001s, test_ID=195, label=3, output_node=93, voltage=0.00198406376875937\n    time_span=0.0001s, test_ID=195, label=3, output_node=94, voltage=0.0005278884200379252\n    time_span=0.0001s, test_ID=195, label=3, output_node=95, voltage=0.0017231078818440437\n    time_span=0.0001s, test_ID=195, label=3, output_node=96, voltage=0.0021623503416776657\n    time_span=0.0001s, test_ID=195, label=3, output_node=97, voltage=0.00140836660284549\n    time_span=0.0001s, test_ID=195, label=3, output_node=98, voltage=0.000788844539783895\n    time_span=0.0001s, test_ID=195, label=3, output_node=99, voltage=0.003376494161784649\n    time_span=0.0001s, test_ID=195, label=3, output_node=sum, voltage=0.008248007856309414\n    Time consumed for 1 sample = 1199.6495254039764 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '195'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=196, label=1, output_node=bkg, voltage=-0.005982071626931429\n    time_span=0.0001s, test_ID=196, label=1, output_node=0, voltage=0.009152390994131565\n    time_span=0.0001s, test_ID=196, label=1, output_node=1, voltage=0.008064741268754005\n    time_span=0.0001s, test_ID=196, label=1, output_node=2, voltage=0.004199202638119459\n    time_span=0.0001s, test_ID=196, label=1, output_node=3, voltage=0.007500000298023224\n    time_span=0.0001s, test_ID=196, label=1, output_node=4, voltage=0.007455179467797279\n    time_span=0.0001s, test_ID=196, label=1, output_node=5, voltage=0.0047400398179888725\n    time_span=0.0001s, test_ID=196, label=1, output_node=6, voltage=0.009000997059047222\n    time_span=0.0001s, test_ID=196, label=1, output_node=7, voltage=0.006594621576368809\n    time_span=0.0001s, test_ID=196, label=1, output_node=8, voltage=0.005432270932942629\n    time_span=0.0001s, test_ID=196, label=1, output_node=9, voltage=0.003518924117088318\n    time_span=0.0001s, test_ID=196, label=1, output_node=10, voltage=0.00774203147739172\n    time_span=0.0001s, test_ID=196, label=1, output_node=11, voltage=0.007102589588612318\n    time_span=0.0001s, test_ID=196, label=1, output_node=12, voltage=0.0018575696740299463\n    time_span=0.0001s, test_ID=196, label=1, output_node=13, voltage=0.0066882469691336155\n    time_span=0.0001s, test_ID=196, label=1, output_node=14, voltage=0.007885457947850227\n    time_span=0.0001s, test_ID=196, label=1, output_node=15, voltage=0.004244023468345404\n    time_span=0.0001s, test_ID=196, label=1, output_node=16, voltage=0.010455179028213024\n    time_span=0.0001s, test_ID=196, label=1, output_node=17, voltage=0.0045258961617946625\n    time_span=0.0001s, test_ID=196, label=1, output_node=18, voltage=0.006599601823836565\n    time_span=0.0001s, test_ID=196, label=1, output_node=19, voltage=0.009616533294320107\n    time_span=0.0001s, test_ID=196, label=1, output_node=20, voltage=0.005651394836604595\n    time_span=0.0001s, test_ID=196, label=1, output_node=21, voltage=0.009469123557209969\n    time_span=0.0001s, test_ID=196, label=1, output_node=22, voltage=0.0066444226540625095\n    time_span=0.0001s, test_ID=196, label=1, output_node=23, voltage=0.011493027210235596\n    time_span=0.0001s, test_ID=196, label=1, output_node=24, voltage=0.0052260952070355415\n    time_span=0.0001s, test_ID=196, label=1, output_node=25, voltage=0.009984063915908337\n    time_span=0.0001s, test_ID=196, label=1, output_node=26, voltage=0.005409362725913525\n    time_span=0.0001s, test_ID=196, label=1, output_node=27, voltage=0.008754979819059372\n    time_span=0.0001s, test_ID=196, label=1, output_node=28, voltage=0.013725100085139275\n    time_span=0.0001s, test_ID=196, label=1, output_node=29, voltage=0.0068127489648759365\n    time_span=0.0001s, test_ID=196, label=1, output_node=30, voltage=0.003970119636505842\n    time_span=0.0001s, test_ID=196, label=1, output_node=31, voltage=0.006661354564130306\n    time_span=0.0001s, test_ID=196, label=1, output_node=32, voltage=0.008009959943592548\n    time_span=0.0001s, test_ID=196, label=1, output_node=33, voltage=0.00438047805801034\n    time_span=0.0001s, test_ID=196, label=1, output_node=34, voltage=0.0043356576934456825\n    time_span=0.0001s, test_ID=196, label=1, output_node=35, voltage=0.010734064504504204\n    time_span=0.0001s, test_ID=196, label=1, output_node=36, voltage=0.0007380478200502694\n    time_span=0.0001s, test_ID=196, label=1, output_node=37, voltage=0.005902390461415052\n    time_span=0.0001s, test_ID=196, label=1, output_node=38, voltage=0.006411354523152113\n    time_span=0.0001s, test_ID=196, label=1, output_node=39, voltage=0.009745020419359207\n    time_span=0.0001s, test_ID=196, label=1, output_node=40, voltage=0.007740039844065905\n    time_span=0.0001s, test_ID=196, label=1, output_node=41, voltage=0.005915338639169931\n    time_span=0.0001s, test_ID=196, label=1, output_node=42, voltage=0.00840936228632927\n    time_span=0.0001s, test_ID=196, label=1, output_node=43, voltage=0.010675298050045967\n    time_span=0.0001s, test_ID=196, label=1, output_node=44, voltage=0.008609562180936337\n    time_span=0.0001s, test_ID=196, label=1, output_node=45, voltage=0.009722110815346241\n    time_span=0.0001s, test_ID=196, label=1, output_node=46, voltage=0.0070009962655603886\n    time_span=0.0001s, test_ID=196, label=1, output_node=47, voltage=0.0068436251021921635\n    time_span=0.0001s, test_ID=196, label=1, output_node=48, voltage=0.005970119033008814\n    time_span=0.0001s, test_ID=196, label=1, output_node=49, voltage=0.010772908106446266\n    time_span=0.0001s, test_ID=196, label=1, output_node=50, voltage=0.006121513899415731\n    time_span=0.0001s, test_ID=196, label=1, output_node=51, voltage=0.009210159070789814\n    time_span=0.0001s, test_ID=196, label=1, output_node=52, voltage=0.013934263028204441\n    time_span=0.0001s, test_ID=196, label=1, output_node=53, voltage=0.00810956209897995\n    time_span=0.0001s, test_ID=196, label=1, output_node=54, voltage=0.008263944648206234\n    time_span=0.0001s, test_ID=196, label=1, output_node=55, voltage=0.014259960502386093\n    time_span=0.0001s, test_ID=196, label=1, output_node=56, voltage=0.0051015932112932205\n    time_span=0.0001s, test_ID=196, label=1, output_node=57, voltage=0.008026892319321632\n    time_span=0.0001s, test_ID=196, label=1, output_node=58, voltage=0.006328685209155083\n    time_span=0.0001s, test_ID=196, label=1, output_node=59, voltage=0.007245020009577274\n    time_span=0.0001s, test_ID=196, label=1, output_node=60, voltage=0.0076982066966593266\n    time_span=0.0001s, test_ID=196, label=1, output_node=61, voltage=0.003536852775141597\n    time_span=0.0001s, test_ID=196, label=1, output_node=62, voltage=0.006088645197451115\n    time_span=0.0001s, test_ID=196, label=1, output_node=63, voltage=0.008670318871736526\n    time_span=0.0001s, test_ID=196, label=1, output_node=64, voltage=0.0073326691053807735\n    time_span=0.0001s, test_ID=196, label=1, output_node=65, voltage=0.008093626238405704\n    time_span=0.0001s, test_ID=196, label=1, output_node=66, voltage=0.0018695220351219177\n    time_span=0.0001s, test_ID=196, label=1, output_node=67, voltage=0.010312749072909355\n    time_span=0.0001s, test_ID=196, label=1, output_node=68, voltage=0.008388446643948555\n    time_span=0.0001s, test_ID=196, label=1, output_node=69, voltage=0.006152390502393246\n    time_span=0.0001s, test_ID=196, label=1, output_node=70, voltage=0.002009960124269128\n    time_span=0.0001s, test_ID=196, label=1, output_node=71, voltage=0.0027868524193763733\n    time_span=0.0001s, test_ID=196, label=1, output_node=72, voltage=0.005567729007452726\n    time_span=0.0001s, test_ID=196, label=1, output_node=73, voltage=0.004596613347530365\n    time_span=0.0001s, test_ID=196, label=1, output_node=74, voltage=0.014702190645039082\n    time_span=0.0001s, test_ID=196, label=1, output_node=75, voltage=0.006816733628511429\n    time_span=0.0001s, test_ID=196, label=1, output_node=76, voltage=0.004301792476326227\n    time_span=0.0001s, test_ID=196, label=1, output_node=77, voltage=0.006007968448102474\n    time_span=0.0001s, test_ID=196, label=1, output_node=78, voltage=0.0056344615295529366\n    time_span=0.0001s, test_ID=196, label=1, output_node=79, voltage=0.005450199358165264\n    time_span=0.0001s, test_ID=196, label=1, output_node=80, voltage=0.005428286734968424\n    time_span=0.0001s, test_ID=196, label=1, output_node=81, voltage=0.0025826692581176758\n    time_span=0.0001s, test_ID=196, label=1, output_node=82, voltage=0.006565737072378397\n    time_span=0.0001s, test_ID=196, label=1, output_node=83, voltage=0.007831673137843609\n    time_span=0.0001s, test_ID=196, label=1, output_node=84, voltage=0.005170318763703108\n    time_span=0.0001s, test_ID=196, label=1, output_node=85, voltage=0.00871215108782053\n    time_span=0.0001s, test_ID=196, label=1, output_node=86, voltage=0.011729083955287933\n    time_span=0.0001s, test_ID=196, label=1, output_node=87, voltage=0.004440239164978266\n    time_span=0.0001s, test_ID=196, label=1, output_node=88, voltage=0.005475099664181471\n    time_span=0.0001s, test_ID=196, label=1, output_node=89, voltage=0.010957171209156513\n    time_span=0.0001s, test_ID=196, label=1, output_node=90, voltage=0.0064810761250555515\n    time_span=0.0001s, test_ID=196, label=1, output_node=91, voltage=0.004355577751994133\n    time_span=0.0001s, test_ID=196, label=1, output_node=92, voltage=0.002720119431614876\n    time_span=0.0001s, test_ID=196, label=1, output_node=93, voltage=0.00720019917935133\n    time_span=0.0001s, test_ID=196, label=1, output_node=94, voltage=0.0046752989292144775\n    time_span=0.0001s, test_ID=196, label=1, output_node=95, voltage=0.005151394288986921\n    time_span=0.0001s, test_ID=196, label=1, output_node=96, voltage=0.008427291177213192\n    time_span=0.0001s, test_ID=196, label=1, output_node=97, voltage=0.007807768881320953\n    time_span=0.0001s, test_ID=196, label=1, output_node=98, voltage=0.007512948475778103\n    time_span=0.0001s, test_ID=196, label=1, output_node=99, voltage=0.0113884462043643\n    time_span=0.0001s, test_ID=196, label=1, output_node=sum, voltage=0.025349602103233337\n    Time consumed for 1 sample = 1200.686919927597 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '196'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=197, label=6, output_node=bkg, voltage=-0.0035846612881869078\n    time_span=0.0001s, test_ID=197, label=6, output_node=0, voltage=0.014555777423083782\n    time_span=0.0001s, test_ID=197, label=6, output_node=1, voltage=0.01041334681212902\n    time_span=0.0001s, test_ID=197, label=6, output_node=2, voltage=0.01511454302817583\n    time_span=0.0001s, test_ID=197, label=6, output_node=3, voltage=0.017137449234724045\n    time_span=0.0001s, test_ID=197, label=6, output_node=4, voltage=0.013445219956338406\n    time_span=0.0001s, test_ID=197, label=6, output_node=5, voltage=0.011332669295370579\n    time_span=0.0001s, test_ID=197, label=6, output_node=6, voltage=0.014972111210227013\n    time_span=0.0001s, test_ID=197, label=6, output_node=7, voltage=0.015958167612552643\n    time_span=0.0001s, test_ID=197, label=6, output_node=8, voltage=0.010987051762640476\n    time_span=0.0001s, test_ID=197, label=6, output_node=9, voltage=0.01233067736029625\n    time_span=0.0001s, test_ID=197, label=6, output_node=10, voltage=0.01343326736241579\n    time_span=0.0001s, test_ID=197, label=6, output_node=11, voltage=0.015858566388487816\n    time_span=0.0001s, test_ID=197, label=6, output_node=12, voltage=0.014295817352831364\n    time_span=0.0001s, test_ID=197, label=6, output_node=13, voltage=0.01186454202979803\n    time_span=0.0001s, test_ID=197, label=6, output_node=14, voltage=0.016754981130361557\n    time_span=0.0001s, test_ID=197, label=6, output_node=15, voltage=0.013037849217653275\n    time_span=0.0001s, test_ID=197, label=6, output_node=16, voltage=0.014047808945178986\n    time_span=0.0001s, test_ID=197, label=6, output_node=17, voltage=0.01126294769346714\n    time_span=0.0001s, test_ID=197, label=6, output_node=18, voltage=0.012473107315599918\n    time_span=0.0001s, test_ID=197, label=6, output_node=19, voltage=0.019002988934516907\n    time_span=0.0001s, test_ID=197, label=6, output_node=20, voltage=0.015771910548210144\n    time_span=0.0001s, test_ID=197, label=6, output_node=21, voltage=0.01774701289832592\n    time_span=0.0001s, test_ID=197, label=6, output_node=22, voltage=0.012459163554012775\n    time_span=0.0001s, test_ID=197, label=6, output_node=23, voltage=0.01957470178604126\n    time_span=0.0001s, test_ID=197, label=6, output_node=24, voltage=0.01406075619161129\n    time_span=0.0001s, test_ID=197, label=6, output_node=25, voltage=0.01463446207344532\n    time_span=0.0001s, test_ID=197, label=6, output_node=26, voltage=0.017378486692905426\n    time_span=0.0001s, test_ID=197, label=6, output_node=27, voltage=0.014776892960071564\n    time_span=0.0001s, test_ID=197, label=6, output_node=28, voltage=0.018704183399677277\n    time_span=0.0001s, test_ID=197, label=6, output_node=29, voltage=0.015548805706202984\n    time_span=0.0001s, test_ID=197, label=6, output_node=30, voltage=0.01014741137623787\n    time_span=0.0001s, test_ID=197, label=6, output_node=31, voltage=0.020832668989896774\n    time_span=0.0001s, test_ID=197, label=6, output_node=32, voltage=0.014938248321413994\n    time_span=0.0001s, test_ID=197, label=6, output_node=33, voltage=0.015699204057455063\n    time_span=0.0001s, test_ID=197, label=6, output_node=34, voltage=0.014368525706231594\n    time_span=0.0001s, test_ID=197, label=6, output_node=35, voltage=0.014866534620523453\n    time_span=0.0001s, test_ID=197, label=6, output_node=36, voltage=0.014963147230446339\n    time_span=0.0001s, test_ID=197, label=6, output_node=37, voltage=0.01597709208726883\n    time_span=0.0001s, test_ID=197, label=6, output_node=38, voltage=0.012622510083019733\n    time_span=0.0001s, test_ID=197, label=6, output_node=39, voltage=0.018995018675923347\n    time_span=0.0001s, test_ID=197, label=6, output_node=40, voltage=0.01216832734644413\n    time_span=0.0001s, test_ID=197, label=6, output_node=41, voltage=0.018536852672696114\n    time_span=0.0001s, test_ID=197, label=6, output_node=42, voltage=0.01709362491965294\n    time_span=0.0001s, test_ID=197, label=6, output_node=43, voltage=0.020345618948340416\n    time_span=0.0001s, test_ID=197, label=6, output_node=44, voltage=0.01719820685684681\n    time_span=0.0001s, test_ID=197, label=6, output_node=45, voltage=0.01916932314634323\n    time_span=0.0001s, test_ID=197, label=6, output_node=46, voltage=0.01627490110695362\n    time_span=0.0001s, test_ID=197, label=6, output_node=47, voltage=0.020702190697193146\n    time_span=0.0001s, test_ID=197, label=6, output_node=48, voltage=0.013534861616790295\n    time_span=0.0001s, test_ID=197, label=6, output_node=49, voltage=0.014740039594471455\n    time_span=0.0001s, test_ID=197, label=6, output_node=50, voltage=0.013394421897828579\n    time_span=0.0001s, test_ID=197, label=6, output_node=51, voltage=0.01634063757956028\n    time_span=0.0001s, test_ID=197, label=6, output_node=52, voltage=0.0200677290558815\n    time_span=0.0001s, test_ID=197, label=6, output_node=53, voltage=0.016044821590185165\n    time_span=0.0001s, test_ID=197, label=6, output_node=54, voltage=0.01905677281320095\n    time_span=0.0001s, test_ID=197, label=6, output_node=55, voltage=0.01701992191374302\n    time_span=0.0001s, test_ID=197, label=6, output_node=56, voltage=0.019652388989925385\n    time_span=0.0001s, test_ID=197, label=6, output_node=57, voltage=0.016375498846173286\n    time_span=0.0001s, test_ID=197, label=6, output_node=58, voltage=0.019844621419906616\n    time_span=0.0001s, test_ID=197, label=6, output_node=59, voltage=0.017840638756752014\n    time_span=0.0001s, test_ID=197, label=6, output_node=60, voltage=0.016256971284747124\n    time_span=0.0001s, test_ID=197, label=6, output_node=61, voltage=0.009145417250692844\n    time_span=0.0001s, test_ID=197, label=6, output_node=62, voltage=0.0186045803129673\n    time_span=0.0001s, test_ID=197, label=6, output_node=63, voltage=0.017833666875958443\n    time_span=0.0001s, test_ID=197, label=6, output_node=64, voltage=0.013018924742937088\n    time_span=0.0001s, test_ID=197, label=6, output_node=65, voltage=0.010579681023955345\n    time_span=0.0001s, test_ID=197, label=6, output_node=66, voltage=0.005905378609895706\n    time_span=0.0001s, test_ID=197, label=6, output_node=67, voltage=0.012606574222445488\n    time_span=0.0001s, test_ID=197, label=6, output_node=68, voltage=0.017774900421500206\n    time_span=0.0001s, test_ID=197, label=6, output_node=69, voltage=0.01465438213199377\n    time_span=0.0001s, test_ID=197, label=6, output_node=70, voltage=0.010002989321947098\n    time_span=0.0001s, test_ID=197, label=6, output_node=71, voltage=0.014152389951050282\n    time_span=0.0001s, test_ID=197, label=6, output_node=72, voltage=0.015039840713143349\n    time_span=0.0001s, test_ID=197, label=6, output_node=73, voltage=0.008825697004795074\n    time_span=0.0001s, test_ID=197, label=6, output_node=74, voltage=0.01764143444597721\n    time_span=0.0001s, test_ID=197, label=6, output_node=75, voltage=0.01603286899626255\n    time_span=0.0001s, test_ID=197, label=6, output_node=76, voltage=0.011424302123486996\n    time_span=0.0001s, test_ID=197, label=6, output_node=77, voltage=0.016830677166581154\n    time_span=0.0001s, test_ID=197, label=6, output_node=78, voltage=0.01629083789885044\n    time_span=0.0001s, test_ID=197, label=6, output_node=79, voltage=0.016619522124528885\n    time_span=0.0001s, test_ID=197, label=6, output_node=80, voltage=0.015890438109636307\n    time_span=0.0001s, test_ID=197, label=6, output_node=81, voltage=0.014898405410349369\n    time_span=0.0001s, test_ID=197, label=6, output_node=82, voltage=0.013407371006906033\n    time_span=0.0001s, test_ID=197, label=6, output_node=83, voltage=0.014309761114418507\n    time_span=0.0001s, test_ID=197, label=6, output_node=84, voltage=0.021632472053170204\n    time_span=0.0001s, test_ID=197, label=6, output_node=85, voltage=0.014445219188928604\n    time_span=0.0001s, test_ID=197, label=6, output_node=86, voltage=0.015294821001589298\n    time_span=0.0001s, test_ID=197, label=6, output_node=87, voltage=0.01651892252266407\n    time_span=0.0001s, test_ID=197, label=6, output_node=88, voltage=0.014352589845657349\n    time_span=0.0001s, test_ID=197, label=6, output_node=89, voltage=0.012736055068671703\n    time_span=0.0001s, test_ID=197, label=6, output_node=90, voltage=0.011893426068127155\n    time_span=0.0001s, test_ID=197, label=6, output_node=91, voltage=0.01280378457158804\n    time_span=0.0001s, test_ID=197, label=6, output_node=92, voltage=0.015165339224040508\n    time_span=0.0001s, test_ID=197, label=6, output_node=93, voltage=0.012805777601897717\n    time_span=0.0001s, test_ID=197, label=6, output_node=94, voltage=0.011554780416190624\n    time_span=0.0001s, test_ID=197, label=6, output_node=95, voltage=0.0066832671873271465\n    time_span=0.0001s, test_ID=197, label=6, output_node=96, voltage=0.014967132359743118\n    time_span=0.0001s, test_ID=197, label=6, output_node=97, voltage=0.016403386369347572\n    time_span=0.0001s, test_ID=197, label=6, output_node=98, voltage=0.009404381737112999\n    time_span=0.0001s, test_ID=197, label=6, output_node=99, voltage=0.0184183269739151\n    time_span=0.0001s, test_ID=197, label=6, output_node=sum, voltage=0.03546912223100662\n    Time consumed for 1 sample = 1206.74578166008 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '197'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=198, label=4, output_node=bkg, voltage=-0.00496613560244441\n    time_span=0.0001s, test_ID=198, label=4, output_node=0, voltage=0.0039402395486831665\n    time_span=0.0001s, test_ID=198, label=4, output_node=1, voltage=0.003453186945989728\n    time_span=0.0001s, test_ID=198, label=4, output_node=2, voltage=0.010364541783928871\n    time_span=0.0001s, test_ID=198, label=4, output_node=3, voltage=0.006316733080893755\n    time_span=0.0001s, test_ID=198, label=4, output_node=4, voltage=0.008948205970227718\n    time_span=0.0001s, test_ID=198, label=4, output_node=5, voltage=0.008669323287904263\n    time_span=0.0001s, test_ID=198, label=4, output_node=6, voltage=0.007950199767947197\n    time_span=0.0001s, test_ID=198, label=4, output_node=7, voltage=0.007740039844065905\n    time_span=0.0001s, test_ID=198, label=4, output_node=8, voltage=0.007813745178282261\n    time_span=0.0001s, test_ID=198, label=4, output_node=9, voltage=0.012165338732302189\n    time_span=0.0001s, test_ID=198, label=4, output_node=10, voltage=0.006873506121337414\n    time_span=0.0001s, test_ID=198, label=4, output_node=11, voltage=0.009475099854171276\n    time_span=0.0001s, test_ID=198, label=4, output_node=12, voltage=0.004299800843000412\n    time_span=0.0001s, test_ID=198, label=4, output_node=13, voltage=0.005706175230443478\n    time_span=0.0001s, test_ID=198, label=4, output_node=14, voltage=0.01125896442681551\n    time_span=0.0001s, test_ID=198, label=4, output_node=15, voltage=0.008902390487492085\n    time_span=0.0001s, test_ID=198, label=4, output_node=16, voltage=0.008089641109108925\n    time_span=0.0001s, test_ID=198, label=4, output_node=17, voltage=0.010134461335837841\n    time_span=0.0001s, test_ID=198, label=4, output_node=18, voltage=0.006127490196377039\n    time_span=0.0001s, test_ID=198, label=4, output_node=19, voltage=0.008236056193709373\n    time_span=0.0001s, test_ID=198, label=4, output_node=20, voltage=0.005177290644496679\n    time_span=0.0001s, test_ID=198, label=4, output_node=21, voltage=0.006915338337421417\n    time_span=0.0001s, test_ID=198, label=4, output_node=22, voltage=0.010478087700903416\n    time_span=0.0001s, test_ID=198, label=4, output_node=23, voltage=0.005589641164988279\n    time_span=0.0001s, test_ID=198, label=4, output_node=24, voltage=0.010247011668980122\n    time_span=0.0001s, test_ID=198, label=4, output_node=25, voltage=0.009014940820634365\n    time_span=0.0001s, test_ID=198, label=4, output_node=26, voltage=0.0019013944547623396\n    time_span=0.0001s, test_ID=198, label=4, output_node=27, voltage=0.0069123501889407635\n    time_span=0.0001s, test_ID=198, label=4, output_node=28, voltage=0.003583665471524\n    time_span=0.0001s, test_ID=198, label=4, output_node=29, voltage=0.009180278517305851\n    time_span=0.0001s, test_ID=198, label=4, output_node=30, voltage=0.003465139539912343\n    time_span=0.0001s, test_ID=198, label=4, output_node=31, voltage=0.009207170456647873\n    time_span=0.0001s, test_ID=198, label=4, output_node=32, voltage=0.006857569795101881\n    time_span=0.0001s, test_ID=198, label=4, output_node=33, voltage=0.006435258314013481\n    time_span=0.0001s, test_ID=198, label=4, output_node=34, voltage=0.008077689446508884\n    time_span=0.0001s, test_ID=198, label=4, output_node=35, voltage=0.004998008254915476\n    time_span=0.0001s, test_ID=198, label=4, output_node=36, voltage=0.009248008020222187\n    time_span=0.0001s, test_ID=198, label=4, output_node=37, voltage=0.007994024083018303\n    time_span=0.0001s, test_ID=198, label=4, output_node=38, voltage=0.013252987526357174\n    time_span=0.0001s, test_ID=198, label=4, output_node=39, voltage=0.005840637255460024\n    time_span=0.0001s, test_ID=198, label=4, output_node=40, voltage=0.011552789248526096\n    time_span=0.0001s, test_ID=198, label=4, output_node=41, voltage=0.010570717044174671\n    time_span=0.0001s, test_ID=198, label=4, output_node=42, voltage=0.009386453777551651\n    time_span=0.0001s, test_ID=198, label=4, output_node=43, voltage=0.011916335672140121\n    time_span=0.0001s, test_ID=198, label=4, output_node=44, voltage=0.00838446244597435\n    time_span=0.0001s, test_ID=198, label=4, output_node=45, voltage=0.010381474159657955\n    time_span=0.0001s, test_ID=198, label=4, output_node=46, voltage=0.012902391143143177\n    time_span=0.0001s, test_ID=198, label=4, output_node=47, voltage=0.010312749072909355\n    time_span=0.0001s, test_ID=198, label=4, output_node=48, voltage=0.006762948352843523\n    time_span=0.0001s, test_ID=198, label=4, output_node=49, voltage=0.010101594030857086\n    time_span=0.0001s, test_ID=198, label=4, output_node=50, voltage=0.010162350721657276\n    time_span=0.0001s, test_ID=198, label=4, output_node=51, voltage=0.0058804783038794994\n    time_span=0.0001s, test_ID=198, label=4, output_node=52, voltage=0.004569721408188343\n    time_span=0.0001s, test_ID=198, label=4, output_node=53, voltage=0.0044651394709944725\n    time_span=0.0001s, test_ID=198, label=4, output_node=54, voltage=0.009353586472570896\n    time_span=0.0001s, test_ID=198, label=4, output_node=55, voltage=0.0073754978366196156\n    time_span=0.0001s, test_ID=198, label=4, output_node=56, voltage=0.0073237051256000996\n    time_span=0.0001s, test_ID=198, label=4, output_node=57, voltage=0.009039840660989285\n    time_span=0.0001s, test_ID=198, label=4, output_node=58, voltage=0.008948207832872868\n    time_span=0.0001s, test_ID=198, label=4, output_node=59, voltage=0.009233067743480206\n    time_span=0.0001s, test_ID=198, label=4, output_node=60, voltage=0.007884461432695389\n    time_span=0.0001s, test_ID=198, label=4, output_node=61, voltage=0.009012947790324688\n    time_span=0.0001s, test_ID=198, label=4, output_node=62, voltage=0.009127490222454071\n    time_span=0.0001s, test_ID=198, label=4, output_node=63, voltage=0.01009063795208931\n    time_span=0.0001s, test_ID=198, label=4, output_node=64, voltage=0.0065209162421524525\n    time_span=0.0001s, test_ID=198, label=4, output_node=65, voltage=0.009253984317183495\n    time_span=0.0001s, test_ID=198, label=4, output_node=66, voltage=0.008179282769560814\n    time_span=0.0001s, test_ID=198, label=4, output_node=67, voltage=0.009826692752540112\n    time_span=0.0001s, test_ID=198, label=4, output_node=68, voltage=0.007505975663661957\n    time_span=0.0001s, test_ID=198, label=4, output_node=69, voltage=0.011232072487473488\n    time_span=0.0001s, test_ID=198, label=4, output_node=70, voltage=0.007855577394366264\n    time_span=0.0001s, test_ID=198, label=4, output_node=71, voltage=0.007273904979228973\n    time_span=0.0001s, test_ID=198, label=4, output_node=72, voltage=0.006974103394895792\n    time_span=0.0001s, test_ID=198, label=4, output_node=73, voltage=0.010585657320916653\n    time_span=0.0001s, test_ID=198, label=4, output_node=74, voltage=0.0025756971444934607\n    time_span=0.0001s, test_ID=198, label=4, output_node=75, voltage=0.005483068060129881\n    time_span=0.0001s, test_ID=198, label=4, output_node=76, voltage=0.007132470142096281\n    time_span=0.0001s, test_ID=198, label=4, output_node=77, voltage=0.011302788741886616\n    time_span=0.0001s, test_ID=198, label=4, output_node=78, voltage=0.009428285993635654\n    time_span=0.0001s, test_ID=198, label=4, output_node=79, voltage=0.01031673327088356\n    time_span=0.0001s, test_ID=198, label=4, output_node=80, voltage=0.008332669734954834\n    time_span=0.0001s, test_ID=198, label=4, output_node=81, voltage=0.00896215159446001\n    time_span=0.0001s, test_ID=198, label=4, output_node=82, voltage=0.0046583665534853935\n    time_span=0.0001s, test_ID=198, label=4, output_node=83, voltage=0.00819023884832859\n    time_span=0.0001s, test_ID=198, label=4, output_node=84, voltage=0.006873506121337414\n    time_span=0.0001s, test_ID=198, label=4, output_node=85, voltage=0.005111553706228733\n    time_span=0.0001s, test_ID=198, label=4, output_node=86, voltage=0.008098606020212173\n    time_span=0.0001s, test_ID=198, label=4, output_node=87, voltage=0.010442230850458145\n    time_span=0.0001s, test_ID=198, label=4, output_node=88, voltage=0.006242031697183847\n    time_span=0.0001s, test_ID=198, label=4, output_node=89, voltage=0.008597609587013721\n    time_span=0.0001s, test_ID=198, label=4, output_node=90, voltage=0.00743426289409399\n    time_span=0.0001s, test_ID=198, label=4, output_node=91, voltage=0.008308764547109604\n    time_span=0.0001s, test_ID=198, label=4, output_node=92, voltage=0.0064691235311329365\n    time_span=0.0001s, test_ID=198, label=4, output_node=93, voltage=0.0060776895843446255\n    time_span=0.0001s, test_ID=198, label=4, output_node=94, voltage=0.003909362480044365\n    time_span=0.0001s, test_ID=198, label=4, output_node=95, voltage=0.0067091635428369045\n    time_span=0.0001s, test_ID=198, label=4, output_node=96, voltage=0.008128485642373562\n    time_span=0.0001s, test_ID=198, label=4, output_node=97, voltage=0.007172311190515757\n    time_span=0.0001s, test_ID=198, label=4, output_node=98, voltage=0.006903386674821377\n    time_span=0.0001s, test_ID=198, label=4, output_node=99, voltage=0.005198207218199968\n    time_span=0.0001s, test_ID=198, label=4, output_node=sum, voltage=0.021648406982421875\n    Time consumed for 1 sample = 1200.9711618423462 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '198'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=199, label=2, output_node=bkg, voltage=-0.004428287036716938\n    time_span=0.0001s, test_ID=199, label=2, output_node=0, voltage=0.019910359755158424\n    time_span=0.0001s, test_ID=199, label=2, output_node=1, voltage=0.02160458080470562\n    time_span=0.0001s, test_ID=199, label=2, output_node=2, voltage=0.021180277690291405\n    time_span=0.0001s, test_ID=199, label=2, output_node=3, voltage=0.024395419284701347\n    time_span=0.0001s, test_ID=199, label=2, output_node=4, voltage=0.015608565881848335\n    time_span=0.0001s, test_ID=199, label=2, output_node=5, voltage=0.014289841055870056\n    time_span=0.0001s, test_ID=199, label=2, output_node=6, voltage=0.023365536704659462\n    time_span=0.0001s, test_ID=199, label=2, output_node=7, voltage=0.030211156234145164\n    time_span=0.0001s, test_ID=199, label=2, output_node=8, voltage=0.028195219114422798\n    time_span=0.0001s, test_ID=199, label=2, output_node=9, voltage=0.024605577811598778\n    time_span=0.0001s, test_ID=199, label=2, output_node=10, voltage=0.024456175044178963\n    time_span=0.0001s, test_ID=199, label=2, output_node=11, voltage=0.027173306792974472\n    time_span=0.0001s, test_ID=199, label=2, output_node=12, voltage=0.019010957330465317\n    time_span=0.0001s, test_ID=199, label=2, output_node=13, voltage=0.02123107574880123\n    time_span=0.0001s, test_ID=199, label=2, output_node=14, voltage=0.019859561696648598\n    time_span=0.0001s, test_ID=199, label=2, output_node=15, voltage=0.02609163336455822\n    time_span=0.0001s, test_ID=199, label=2, output_node=16, voltage=0.016981074586510658\n    time_span=0.0001s, test_ID=199, label=2, output_node=17, voltage=0.011392430402338505\n    time_span=0.0001s, test_ID=199, label=2, output_node=18, voltage=0.01800697110593319\n    time_span=0.0001s, test_ID=199, label=2, output_node=19, voltage=0.02119024097919464\n    time_span=0.0001s, test_ID=199, label=2, output_node=20, voltage=0.018202191218733788\n    time_span=0.0001s, test_ID=199, label=2, output_node=21, voltage=0.02796713449060917\n    time_span=0.0001s, test_ID=199, label=2, output_node=22, voltage=0.020858565345406532\n    time_span=0.0001s, test_ID=199, label=2, output_node=23, voltage=0.02211354486644268\n    time_span=0.0001s, test_ID=199, label=2, output_node=24, voltage=0.023953186348080635\n    time_span=0.0001s, test_ID=199, label=2, output_node=25, voltage=0.01737649366259575\n    time_span=0.0001s, test_ID=199, label=2, output_node=26, voltage=0.021277887746691704\n    time_span=0.0001s, test_ID=199, label=2, output_node=27, voltage=0.024643424898386\n    time_span=0.0001s, test_ID=199, label=2, output_node=28, voltage=0.01986653357744217\n    time_span=0.0001s, test_ID=199, label=2, output_node=29, voltage=0.02884860709309578\n    time_span=0.0001s, test_ID=199, label=2, output_node=30, voltage=0.020170317962765694\n    time_span=0.0001s, test_ID=199, label=2, output_node=31, voltage=0.018655378371477127\n    time_span=0.0001s, test_ID=199, label=2, output_node=32, voltage=0.024923305958509445\n    time_span=0.0001s, test_ID=199, label=2, output_node=33, voltage=0.029711155220866203\n    time_span=0.0001s, test_ID=199, label=2, output_node=34, voltage=0.021776892244815826\n    time_span=0.0001s, test_ID=199, label=2, output_node=35, voltage=0.02046414278447628\n    time_span=0.0001s, test_ID=199, label=2, output_node=36, voltage=0.018852589651942253\n    time_span=0.0001s, test_ID=199, label=2, output_node=37, voltage=0.021307768300175667\n    time_span=0.0001s, test_ID=199, label=2, output_node=38, voltage=0.025928286835551262\n    time_span=0.0001s, test_ID=199, label=2, output_node=39, voltage=0.022484065964818\n    time_span=0.0001s, test_ID=199, label=2, output_node=40, voltage=0.020639441907405853\n    time_span=0.0001s, test_ID=199, label=2, output_node=41, voltage=0.01724601536989212\n    time_span=0.0001s, test_ID=199, label=2, output_node=42, voltage=0.021250996738672256\n    time_span=0.0001s, test_ID=199, label=2, output_node=43, voltage=0.022198207676410675\n    time_span=0.0001s, test_ID=199, label=2, output_node=44, voltage=0.02057868428528309\n    time_span=0.0001s, test_ID=199, label=2, output_node=45, voltage=0.019435258582234383\n    time_span=0.0001s, test_ID=199, label=2, output_node=46, voltage=0.023547809571027756\n    time_span=0.0001s, test_ID=199, label=2, output_node=47, voltage=0.020232072100043297\n    time_span=0.0001s, test_ID=199, label=2, output_node=48, voltage=0.012279881164431572\n    time_span=0.0001s, test_ID=199, label=2, output_node=49, voltage=0.02391733042895794\n    time_span=0.0001s, test_ID=199, label=2, output_node=50, voltage=0.02093326672911644\n    time_span=0.0001s, test_ID=199, label=2, output_node=51, voltage=0.02495916560292244\n    time_span=0.0001s, test_ID=199, label=2, output_node=52, voltage=0.016167329624295235\n    time_span=0.0001s, test_ID=199, label=2, output_node=53, voltage=0.015262948349118233\n    time_span=0.0001s, test_ID=199, label=2, output_node=54, voltage=0.023000994697213173\n    time_span=0.0001s, test_ID=199, label=2, output_node=55, voltage=0.0192430280148983\n    time_span=0.0001s, test_ID=199, label=2, output_node=56, voltage=0.02551693096756935\n    time_span=0.0001s, test_ID=199, label=2, output_node=57, voltage=0.025352589786052704\n    time_span=0.0001s, test_ID=199, label=2, output_node=58, voltage=0.019077688455581665\n    time_span=0.0001s, test_ID=199, label=2, output_node=59, voltage=0.02026992104947567\n    time_span=0.0001s, test_ID=199, label=2, output_node=60, voltage=0.021268924698233604\n    time_span=0.0001s, test_ID=199, label=2, output_node=61, voltage=0.0205866526812315\n    time_span=0.0001s, test_ID=199, label=2, output_node=62, voltage=0.022359561175107956\n    time_span=0.0001s, test_ID=199, label=2, output_node=63, voltage=0.020487051457166672\n    time_span=0.0001s, test_ID=199, label=2, output_node=64, voltage=0.020766932517290115\n    time_span=0.0001s, test_ID=199, label=2, output_node=65, voltage=0.022458169609308243\n    time_span=0.0001s, test_ID=199, label=2, output_node=66, voltage=0.011552789248526096\n    time_span=0.0001s, test_ID=199, label=2, output_node=67, voltage=0.0218147411942482\n    time_span=0.0001s, test_ID=199, label=2, output_node=68, voltage=0.0214113537222147\n    time_span=0.0001s, test_ID=199, label=2, output_node=69, voltage=0.02255876734852791\n    time_span=0.0001s, test_ID=199, label=2, output_node=70, voltage=0.020985059440135956\n    time_span=0.0001s, test_ID=199, label=2, output_node=71, voltage=0.017006972804665565\n    time_span=0.0001s, test_ID=199, label=2, output_node=72, voltage=0.022342627868056297\n    time_span=0.0001s, test_ID=199, label=2, output_node=73, voltage=0.012271912768483162\n    time_span=0.0001s, test_ID=199, label=2, output_node=74, voltage=0.021541832014918327\n    time_span=0.0001s, test_ID=199, label=2, output_node=75, voltage=0.021696213632822037\n    time_span=0.0001s, test_ID=199, label=2, output_node=76, voltage=0.023509960621595383\n    time_span=0.0001s, test_ID=199, label=2, output_node=77, voltage=0.022036852315068245\n    time_span=0.0001s, test_ID=199, label=2, output_node=78, voltage=0.023853586986660957\n    time_span=0.0001s, test_ID=199, label=2, output_node=79, voltage=0.01980777084827423\n    time_span=0.0001s, test_ID=199, label=2, output_node=80, voltage=0.022214142605662346\n    time_span=0.0001s, test_ID=199, label=2, output_node=81, voltage=0.022455180063843727\n    time_span=0.0001s, test_ID=199, label=2, output_node=82, voltage=0.026945220306515694\n    time_span=0.0001s, test_ID=199, label=2, output_node=83, voltage=0.027494024485349655\n    time_span=0.0001s, test_ID=199, label=2, output_node=84, voltage=0.02981773018836975\n    time_span=0.0001s, test_ID=199, label=2, output_node=85, voltage=0.026800798252224922\n    time_span=0.0001s, test_ID=199, label=2, output_node=86, voltage=0.02282669208943844\n    time_span=0.0001s, test_ID=199, label=2, output_node=87, voltage=0.023499999195337296\n    time_span=0.0001s, test_ID=199, label=2, output_node=88, voltage=0.021837648004293442\n    time_span=0.0001s, test_ID=199, label=2, output_node=89, voltage=0.023103585466742516\n    time_span=0.0001s, test_ID=199, label=2, output_node=90, voltage=0.015825696289539337\n    time_span=0.0001s, test_ID=199, label=2, output_node=91, voltage=0.022694222629070282\n    time_span=0.0001s, test_ID=199, label=2, output_node=92, voltage=0.024827688932418823\n    time_span=0.0001s, test_ID=199, label=2, output_node=93, voltage=0.017915338277816772\n    time_span=0.0001s, test_ID=199, label=2, output_node=94, voltage=0.024808766320347786\n    time_span=0.0001s, test_ID=199, label=2, output_node=95, voltage=0.016690239310264587\n    time_span=0.0001s, test_ID=199, label=2, output_node=96, voltage=0.018835656344890594\n    time_span=0.0001s, test_ID=199, label=2, output_node=97, voltage=0.027140438556671143\n    time_span=0.0001s, test_ID=199, label=2, output_node=98, voltage=0.019497012719511986\n    time_span=0.0001s, test_ID=199, label=2, output_node=99, voltage=0.02075498178601265\n    time_span=0.0001s, test_ID=199, label=2, output_node=sum, voltage=0.04974103718996048\n    Time consumed for 1 sample = 1211.3642213344574 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '199'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    Finished! Safe to change code now.\n\n\n\n```python\ndf_temp = pandas.read_hdf((savePath / \"mppc_vol_meas.h5\").as_posix(), key='26')\ndf_temp\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th></th>\n      <th>0</th>\n      <th>1</th>\n      <th>2</th>\n      <th>3</th>\n      <th>4</th>\n      <th>5</th>\n      <th>6</th>\n      <th>7</th>\n      <th>8</th>\n      <th>9</th>\n      <th>...</th>\n      <th>994</th>\n      <th>995</th>\n      <th>996</th>\n      <th>997</th>\n      <th>998</th>\n      <th>999</th>\n      <th>1000</th>\n      <th>1001</th>\n      <th>1002</th>\n      <th>1003</th>\n    </tr>\n    <tr>\n      <th>output_node</th>\n      <th>time_range</th>\n      <th>repeats</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">0</th>\n      <th rowspan=\"5\" valign=\"top\">0.0001</th>\n      <th>0</th>\n      <td>0.024</td>\n      <td>0.027</td>\n      <td>0.018</td>\n      <td>0.002</td>\n      <td>-0.005</td>\n      <td>-0.008</td>\n      <td>0</td>\n      <td>0.016</td>\n      <td>0.026</td>\n      <td>0.032</td>\n      <td>...</td>\n      <td>0.01</td>\n      <td>0.008</td>\n      <td>0.006</td>\n      <td>-0.005</td>\n      <td>-0.012</td>\n      <td>-0.009</td>\n      <td>-0.004</td>\n      <td>-0.005</td>\n      <td>-0.005</td>\n      <td>0.003</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.033</td>\n      <td>0.028</td>\n      <td>0.025</td>\n      <td>0.015</td>\n      <td>0.005</td>\n      <td>0.002</td>\n      <td>0.004</td>\n      <td>0.007</td>\n      <td>0.008</td>\n      <td>0.01</td>\n      <td>...</td>\n      <td>0.02</td>\n      <td>0.029</td>\n      <td>0.043</td>\n      <td>0.033</td>\n      <td>0.035</td>\n      <td>0.033</td>\n      <td>0.013</td>\n      <td>0.009</td>\n      <td>0.018</td>\n      <td>0.027</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.011</td>\n      <td>0.008</td>\n      <td>0.006</td>\n      <td>0.007</td>\n      <td>0.004</td>\n      <td>-0.003</td>\n      <td>0.002</td>\n      <td>0.011</td>\n      <td>0.005</td>\n      <td>0.001</td>\n      <td>...</td>\n      <td>0.017</td>\n      <td>0.018</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.014</td>\n      <td>0.033</td>\n      <td>0.014</td>\n      <td>0.021</td>\n      <td>0.021</td>\n      <td>0.025</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.016</td>\n      <td>0.003</td>\n      <td>0.001</td>\n      <td>0.003</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>-0.002</td>\n      <td>-0.003</td>\n      <td>-0.007</td>\n      <td>...</td>\n      <td>0.013</td>\n      <td>0.014</td>\n      <td>0.025</td>\n      <td>0.032</td>\n      <td>0.037</td>\n      <td>0.043</td>\n      <td>0.033</td>\n      <td>0.026</td>\n      <td>0.021</td>\n      <td>0.016</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.002</td>\n      <td>-0.002</td>\n      <td>-0.003</td>\n      <td>-0.006</td>\n      <td>-0.006</td>\n      <td>0</td>\n      <td>0.004</td>\n      <td>0.011</td>\n      <td>0.02</td>\n      <td>0.013</td>\n      <td>...</td>\n      <td>0.036</td>\n      <td>0.021</td>\n      <td>0.008</td>\n      <td>0.001</td>\n      <td>0.01</td>\n      <td>0.029</td>\n      <td>0.036</td>\n      <td>0.04</td>\n      <td>0.033</td>\n      <td>0.016</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <th>...</th>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">bkg</th>\n      <th rowspan=\"5\" valign=\"top\">0.0001</th>\n      <th>95</th>\n      <td>0.008</td>\n      <td>0.009</td>\n      <td>0.015</td>\n      <td>0.017</td>\n      <td>0.008</td>\n      <td>0</td>\n      <td>0.006</td>\n      <td>0.012</td>\n      <td>0.011</td>\n      <td>0.007</td>\n      <td>...</td>\n      <td>-0.004</td>\n      <td>-0.005</td>\n      <td>-0.002</td>\n      <td>-0.002</td>\n      <td>-0.006</td>\n      <td>-0.014</td>\n      <td>-0.019</td>\n      <td>-0.022</td>\n      <td>-0.024</td>\n      <td>-0.019</td>\n    </tr>\n    <tr>\n      <th>96</th>\n      <td>0.002</td>\n      <td>-0.002</td>\n      <td>-0.002</td>\n      <td>-0.002</td>\n      <td>-0.005</td>\n      <td>-0.008</td>\n      <td>-0.006</td>\n      <td>-0.002</td>\n      <td>-0.003</td>\n      <td>-0.001</td>\n      <td>...</td>\n      <td>-0.003</td>\n      <td>-0.006</td>\n      <td>-0.011</td>\n      <td>-0.021</td>\n      <td>-0.026</td>\n      <td>-0.021</td>\n      <td>-0.019</td>\n      <td>-0.012</td>\n      <td>-0.007</td>\n      <td>-0.007</td>\n    </tr>\n    <tr>\n      <th>97</th>\n      <td>-0.006</td>\n      <td>-0.003</td>\n      <td>-0.004</td>\n      <td>-0.004</td>\n      <td>-0.005</td>\n      <td>-0.014</td>\n      <td>-0.022</td>\n      <td>-0.022</td>\n      <td>-0.018</td>\n      <td>-0.006</td>\n      <td>...</td>\n      <td>-0.003</td>\n      <td>-0.021</td>\n      <td>-0.034</td>\n      <td>-0.022</td>\n      <td>-0.005</td>\n      <td>0.014</td>\n      <td>0.013</td>\n      <td>0.002</td>\n      <td>-0.015</td>\n      <td>-0.02</td>\n    </tr>\n    <tr>\n      <th>98</th>\n      <td>-0.021</td>\n      <td>-0.019</td>\n      <td>-0.011</td>\n      <td>-0.005</td>\n      <td>-0.006</td>\n      <td>-0.006</td>\n      <td>-0.007</td>\n      <td>-0.003</td>\n      <td>-0.003</td>\n      <td>-0.002</td>\n      <td>...</td>\n      <td>-0.007</td>\n      <td>-0.003</td>\n      <td>0.004</td>\n      <td>0.006</td>\n      <td>0.004</td>\n      <td>0.009</td>\n      <td>0.01</td>\n      <td>0.008</td>\n      <td>0.013</td>\n      <td>0.005</td>\n    </tr>\n    <tr>\n      <th>99</th>\n      <td>-0.007</td>\n      <td>-0.007</td>\n      <td>-0.008</td>\n      <td>-0.014</td>\n      <td>-0.018</td>\n      <td>-0.019</td>\n      <td>-0.022</td>\n      <td>-0.014</td>\n      <td>-0.008</td>\n      <td>-0.01</td>\n      <td>...</td>\n      <td>-0.007</td>\n      <td>-0.009</td>\n      <td>-0.015</td>\n      <td>-0.011</td>\n      <td>-0.006</td>\n      <td>-0.01</td>\n      <td>-0.009</td>\n      <td>-0.004</td>\n      <td>-0.003</td>\n      <td>-0.004</td>\n    </tr>\n  </tbody>\n</table>\n<p>10200 rows \u00d7 1004 columns</p>\n</div>\n\n\n\n\n```python\ndf\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th></th>\n      <th>0</th>\n      <th>1</th>\n      <th>2</th>\n      <th>3</th>\n      <th>4</th>\n      <th>5</th>\n      <th>6</th>\n      <th>7</th>\n      <th>8</th>\n      <th>9</th>\n      <th>...</th>\n      <th>994</th>\n      <th>995</th>\n      <th>996</th>\n      <th>997</th>\n      <th>998</th>\n      <th>999</th>\n      <th>1000</th>\n      <th>1001</th>\n      <th>1002</th>\n      <th>1003</th>\n    </tr>\n    <tr>\n      <th>output_node</th>\n      <th>time_range</th>\n      <th>repeats</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">0</th>\n      <th rowspan=\"5\" valign=\"top\">0.0001</th>\n      <th>0</th>\n      <td>0.028</td>\n      <td>0.033</td>\n      <td>0.035</td>\n      <td>0.022</td>\n      <td>0.003</td>\n      <td>-0.002</td>\n      <td>0.013</td>\n      <td>0.022</td>\n      <td>0.025</td>\n      <td>0.016</td>\n      <td>...</td>\n      <td>0.021</td>\n      <td>0.021</td>\n      <td>0.013</td>\n      <td>0.001</td>\n      <td>-0.004</td>\n      <td>-0.008</td>\n      <td>0.001</td>\n      <td>0.013</td>\n      <td>0.017</td>\n      <td>0.013</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.025</td>\n      <td>0.001</td>\n      <td>-0.015</td>\n      <td>-0.005</td>\n      <td>0.008</td>\n      <td>0.012</td>\n      <td>0.023</td>\n      <td>0.03</td>\n      <td>0.039</td>\n      <td>0.047</td>\n      <td>...</td>\n      <td>0.021</td>\n      <td>0.029</td>\n      <td>0.022</td>\n      <td>0.026</td>\n      <td>0.021</td>\n      <td>0.016</td>\n      <td>0.026</td>\n      <td>0.025</td>\n      <td>0.032</td>\n      <td>0.04</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>-0.005</td>\n      <td>-0.004</td>\n      <td>0.002</td>\n      <td>0.016</td>\n      <td>0.024</td>\n      <td>0.035</td>\n      <td>0.033</td>\n      <td>0.017</td>\n      <td>0.012</td>\n      <td>0.01</td>\n      <td>...</td>\n      <td>0.036</td>\n      <td>0.023</td>\n      <td>0.018</td>\n      <td>0.028</td>\n      <td>0.04</td>\n      <td>0.044</td>\n      <td>0.048</td>\n      <td>0.044</td>\n      <td>0.032</td>\n      <td>0.019</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.021</td>\n      <td>0.036</td>\n      <td>0.033</td>\n      <td>0.029</td>\n      <td>0.036</td>\n      <td>0.041</td>\n      <td>0.044</td>\n      <td>0.048</td>\n      <td>0.048</td>\n      <td>0.037</td>\n      <td>...</td>\n      <td>0.041</td>\n      <td>0.033</td>\n      <td>0.033</td>\n      <td>0.025</td>\n      <td>0.013</td>\n      <td>0</td>\n      <td>-0.009</td>\n      <td>0.001</td>\n      <td>0.019</td>\n      <td>0.035</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.029</td>\n      <td>0.037</td>\n      <td>0.039</td>\n      <td>0.03</td>\n      <td>0.028</td>\n      <td>0.016</td>\n      <td>0.005</td>\n      <td>0.006</td>\n      <td>0.007</td>\n      <td>0.01</td>\n      <td>...</td>\n      <td>0.037</td>\n      <td>0.035</td>\n      <td>0.033</td>\n      <td>0.026</td>\n      <td>0.027</td>\n      <td>0.016</td>\n      <td>0.013</td>\n      <td>0.019</td>\n      <td>0.03</td>\n      <td>0.043</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <th>...</th>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">bkg</th>\n      <th rowspan=\"5\" valign=\"top\">0.0001</th>\n      <th>95</th>\n      <td>-0.013</td>\n      <td>-0.023</td>\n      <td>-0.033</td>\n      <td>-0.024</td>\n      <td>-0.013</td>\n      <td>-0.006</td>\n      <td>0.012</td>\n      <td>0.02</td>\n      <td>0.018</td>\n      <td>0.01</td>\n      <td>...</td>\n      <td>0.004</td>\n      <td>0.003</td>\n      <td>0.003</td>\n      <td>0.003</td>\n      <td>-0.001</td>\n      <td>-0.008</td>\n      <td>-0.009</td>\n      <td>-0.007</td>\n      <td>-0.003</td>\n      <td>0.004</td>\n    </tr>\n    <tr>\n      <th>96</th>\n      <td>-0.008</td>\n      <td>0.003</td>\n      <td>0.009</td>\n      <td>0.014</td>\n      <td>0.019</td>\n      <td>0.021</td>\n      <td>0.02</td>\n      <td>0.008</td>\n      <td>-0.012</td>\n      <td>-0.033</td>\n      <td>...</td>\n      <td>-0.004</td>\n      <td>-0.004</td>\n      <td>-0.002</td>\n      <td>-0.004</td>\n      <td>-0.008</td>\n      <td>-0.017</td>\n      <td>-0.025</td>\n      <td>-0.03</td>\n      <td>-0.034</td>\n      <td>-0.027</td>\n    </tr>\n    <tr>\n      <th>97</th>\n      <td>-0.009</td>\n      <td>-0.007</td>\n      <td>0</td>\n      <td>0.002</td>\n      <td>0</td>\n      <td>-0.003</td>\n      <td>-0.008</td>\n      <td>-0.011</td>\n      <td>-0.011</td>\n      <td>-0.012</td>\n      <td>...</td>\n      <td>-0.018</td>\n      <td>-0.011</td>\n      <td>-0.018</td>\n      <td>-0.025</td>\n      <td>-0.022</td>\n      <td>-0.016</td>\n      <td>-0.007</td>\n      <td>0.001</td>\n      <td>-0.001</td>\n      <td>-0.006</td>\n    </tr>\n    <tr>\n      <th>98</th>\n      <td>-0.007</td>\n      <td>-0.006</td>\n      <td>-0.004</td>\n      <td>-0.004</td>\n      <td>-0.006</td>\n      <td>-0.002</td>\n      <td>-0.003</td>\n      <td>-0.008</td>\n      <td>-0.018</td>\n      <td>-0.027</td>\n      <td>...</td>\n      <td>-0.017</td>\n      <td>-0.05</td>\n      <td>-0.025</td>\n      <td>-0.02</td>\n      <td>-0.009</td>\n      <td>-0.011</td>\n      <td>-0.011</td>\n      <td>-0.01</td>\n      <td>-0.017</td>\n      <td>-0.02</td>\n    </tr>\n    <tr>\n      <th>99</th>\n      <td>-0.001</td>\n      <td>0.005</td>\n      <td>0.015</td>\n      <td>0.016</td>\n      <td>0.013</td>\n      <td>0.009</td>\n      <td>0</td>\n      <td>-0.004</td>\n      <td>-0.005</td>\n      <td>-0.004</td>\n      <td>...</td>\n      <td>0.011</td>\n      <td>0.003</td>\n      <td>-0.006</td>\n      <td>-0.006</td>\n      <td>-0.005</td>\n      <td>-0.004</td>\n      <td>-0.002</td>\n      <td>-0.001</td>\n      <td>-0.004</td>\n      <td>0.004</td>\n    </tr>\n  </tbody>\n</table>\n<p>10200 rows \u00d7 1004 columns</p>\n</div>\n\n\n\n\n```python\ndf_volTraces.loc[0,].dropna(axis=\"columns\").astype(float).mean(level=[0,1]).mean(axis=1)*100\n```\n\n\n\n\n    output_node  time_range\n    0            0.0001        1.108908\n    1            0.0001        0.135558\n    2            0.0001        0.954472\n    3            0.0001        1.069739\n    4            0.0001        0.617894\n    5            0.0001        0.339468\n    6            0.0001        0.495554\n    7            0.0001        1.219645\n    8            0.0001        0.718153\n    9            0.0001        0.582032\n    dtype: float64\n\n\n\n\n```python\ndf_all_acts.loc[0,0]\n```\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:1: PerformanceWarning: indexing past lexsort depth may impact performance.\n      \"\"\"Entry point for launching an IPython kernel.\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>norm(W)norm(X)</th>\n      <th>sum(norm(X))</th>\n      <th>sum(norm(W))</th>\n      <th>Wx</th>\n      <th>Wx+b</th>\n      <th>a</th>\n      <th>a_true</th>\n    </tr>\n    <tr>\n      <th>output node</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>7435548.0</td>\n      <td>18435480.0</td>\n      <td>101575323.0</td>\n      <td>-15.719175</td>\n      <td>-15.587848</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>9019478.0</td>\n      <td>18435480.0</td>\n      <td>99886014.0</td>\n      <td>-3.035051</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>9160499.0</td>\n      <td>18435480.0</td>\n      <td>95635269.0</td>\n      <td>-1.905754</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>9690888.0</td>\n      <td>18435480.0</td>\n      <td>101176722.0</td>\n      <td>2.341606</td>\n      <td>5.428436</td>\n      <td>5.428436</td>\n      <td>2.607136</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>11035015.0</td>\n      <td>18435480.0</td>\n      <td>94579326.0</td>\n      <td>13.105385</td>\n      <td>12.433863</td>\n      <td>12.433863</td>\n      <td>12.107492</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>95</th>\n      <td>10351690.0</td>\n      <td>18435480.0</td>\n      <td>105060834.0</td>\n      <td>7.633313</td>\n      <td>5.428436</td>\n      <td>5.428436</td>\n      <td>6.962213</td>\n    </tr>\n    <tr>\n      <th>96</th>\n      <td>11421935.0</td>\n      <td>18435480.0</td>\n      <td>97347555.0</td>\n      <td>16.203844</td>\n      <td>12.433863</td>\n      <td>12.433863</td>\n      <td>15.228162</td>\n    </tr>\n    <tr>\n      <th>97</th>\n      <td>9724589.0</td>\n      <td>18435480.0</td>\n      <td>106398495.0</td>\n      <td>2.611483</td>\n      <td>5.428436</td>\n      <td>5.428436</td>\n      <td>2.248217</td>\n    </tr>\n    <tr>\n      <th>98</th>\n      <td>10679262.0</td>\n      <td>18435480.0</td>\n      <td>100877022.0</td>\n      <td>10.256513</td>\n      <td>12.433863</td>\n      <td>12.433863</td>\n      <td>9.260293</td>\n    </tr>\n    <tr>\n      <th>99</th>\n      <td>8540622.0</td>\n      <td>18435480.0</td>\n      <td>97679223.0</td>\n      <td>-6.869734</td>\n      <td>-8.582420</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n  </tbody>\n</table>\n<p>100 rows \u00d7 7 columns</p>\n</div>\n\n\n\n\n```python\ndf_volTraces.to_hdf((savePath / \"mppc_vol_meas.h5\").as_posix(), key=\" \", mode='w')\njoblib.dump([oscope_info(oscope),], savePath / 'exp_info.pkl')\n```\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: ' '; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\pandas\\core\\generic.py:2505: PerformanceWarning: \n    your performance may suffer as PyTables will pickle object types that it cannot\n    map directly to c-types [inferred_type->floating,key->block0_values] [items->Int64Index([   0,    1,    2,    3,    4,    5,    6,    7,    8,    9,\n                ...\n                1590, 1591, 1592, 1593, 1594, 1595, 1596, 1597, 1598, 1599],\n               dtype='int64', length=1600)]\n    \n      encoding=encoding,\n\n\n\n\n\n    ['D:\\\\McMahon lab Dropbox\\\\peter mcmahon\\\\tw329\\\\Experiments\\\\11_05_20_Perceptron_MPPC\\\\Percep_4bit_5x_gap2px_MPPC_1107_210954\\\\exp_info.pkl']\n\n\n\n\n```python\nblackImage_PIL = Image.open((phoneImagePath / \"black.png\").as_posix())\nblackImage_byte = PIL_to_bytestream(blackImage_PIL)\naoab.write(blackImage_byte)\n```\n\n# Troubleshoot Blocks\n\n\n```python\n# Debug alignment \nfrom PIL import Image\ntestImagePath = phoneImagePath / f\"test_digit_7_00000.png\"\nimToPhone_PIL = Image.open(testImagePath)\nimToPhone_byte = PIL_to_bytestream(imToPhone_PIL)\nslm.updateArray(slm_weights_numpy[\"ordered\"])\naoab.write(imToPhone_byte)\n```\n\n\n```python\n# Debug alignment \nfrom PIL import Image\nalignImagePath = resultPath.parent / \"alignment_images\" \nimToPhone_PIL = Image.open((alignImagePath / \"TheGreenViewFinder.png\").as_posix())\nimToPhone_byte = PIL_to_bytestream(imToPhone_PIL)\naoab.write(imToPhone_byte)\nimToSLM = Image.open((alignImagePath / \"TheGreenViewFinder_SLM.bmp\").as_posix())\nslm.updateArray(np.array(imToSLM))\n```\n\n\n```python\n# Debug alignment \nfrom PIL import Image\nalignImagePath = resultPath.parent / \"alignment_images\" \nimToPhone_PIL = Image.open((alignImagePath / \"Horizontal_stripes_period_4.png\").as_posix())\nimToPhone_byte = PIL_to_bytestream(imToPhone_PIL)\naoab.write(imToPhone_byte)\nimToSLM = Image.open((alignImagePath / \"Horizontal_stripes_period_4_SLM.bmp\").as_posix())\nslm.updateArray(np.array(imToSLM))\n```\n\n\n```python\n# Debug alignment \nfrom PIL import Image\nalignImagePath = resultPath.parent / \"alignment_images\" \nimToPhone_PIL = Image.open((alignImagePath / \"Vertical_stripes_period_4.png\").as_posix())\nimToPhone_byte = PIL_to_bytestream(imToPhone_PIL)\naoab.write(imToPhone_byte)\nimToSLM = Image.open((alignImagePath / \"Vertical_stripes_period_4_SLM.bmp\").as_posix())\nslm.updateArray(np.array(imToSLM))\n```\n", "meta": {"hexsha": "af06aabb2537dde455dca8b0e9c3e9c872d6f329", "size": 550192, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "data_collection/run_MLP_MPPC_fc0.ipynb", "max_stars_repo_name": "ConnectionMaster/ONN-device-control", "max_stars_repo_head_hexsha": "0b909c48272ec0f92c79dfa1d7fb8b8b6c55766a", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-18T15:59:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T03:00:19.000Z", "max_issues_repo_path": "data_collection/run_MLP_MPPC_fc0.ipynb", "max_issues_repo_name": "mcmahon-lab/ONN-device-control", "max_issues_repo_head_hexsha": "ecb0b6e8afef57c3c9ceeaa7e00d76860135a8ab", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-11T14:44:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-11T14:44:56.000Z", "max_forks_repo_path": "data_collection/run_MLP_MPPC_fc0.ipynb", "max_forks_repo_name": "ConnectionMaster/ONN-device-control", "max_forks_repo_head_hexsha": "0b909c48272ec0f92c79dfa1d7fb8b8b6c55766a", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-11T14:43:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-11T14:43:40.000Z", "avg_line_length": 67.1211418812, "max_line_length": 55416, "alphanum_fraction": 0.6479919737, "converted": true, "num_tokens": 95891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.06008664596619963, "lm_q1q2_score": 0.023350753786757456}}
{"text": "# CBMPy Tutorial 01 Getting Started\n\n## Checking dependencies and loading CBMPy\n\nPySCeS CBMPy is a flexible framework for contraint based modelling. With this tutorial we setup a CBMPy session and load a model. To begin with let's see if we have all the basic dependencies installed. For more information please see the CBMPy reference guide (available from http://cbmpy.sourceforge.net).\n\nNo additional files are required for this tutorial.\n\n\n```python\n# Required for basic CBMPy functionality\nimport numpy\n\n# extended functionaliy\nimport libsbml\nprint('\\nYou are using libSBML version {}'.format(libsbml.LIBSBML_VERSION_STRING))\nif libsbml.LIBSBML_VERSION > 51100 and libsbml.LIBSBML_VERSION < 51106:\n    print('Your version of libSBML supports SBML 3 FBC version 1, please consider upgrading to the latest version for FBC version 2 support.\\n')\nelif libsbml.LIBSBML_VERSION >= 51106:\n    print('Your version of libSBML supports SBML 3 FBC versions 1 and 2.\\n')\nelse:\n    print('You are using an extrememly old version of libSBML please upgrade now!\\n')\n    \n# optional, but highly recommended for rerading/writing excel spreadsheets\nimport xlrd\nimport xlwt\n# sympy is only required for methods utilizing exact arithmetic\ntry:\n    import sympy\nexcept ImportError:\n    print('\\nSympy is only required for selected methods utilizing exact arithmetic and is not required for normal functionality.')\n    \n\n```\n\n    \n    You are using libSBML version 51401\n    Your version of libSBML supports SBML 3 FBC versions 1 and 2.\n    \n\n\nIf any of of the above imports failed consider installing them. Please see the online documentation for comprehensive installation [instructions](http://cbmpy.sourceforge.net/reference/cbmpy.html). Next we need to import CBMPy, at this point it is convenient to alias the imported module. In all tutorials this will be `cbm`.\n\n\n```python\nimport cbmpy\n```\n\n    \n    *****\n    Using CPLEX\n    *****\n    \n    WX GUI tools available.\n    \n    CBMPy environment\n    ******************\n    Revision: r562\n    \n    \n    ***********************************************************************\n    * Welcome to CBMPy (0.7.11) - PySCeS Constraint Based Modelling        *\n    *                http://cbmpy.sourceforge.net                         *\n    * Copyright(C) Brett G. Olivier 2014 - 2016                           *\n    * Dept. of Systems Bioinformatics                                     *\n    * Vrije Universiteit Amsterdam, Amsterdam, The Netherlands            *\n    * CBMPy is developed as part of the BeBasic MetaToolKit Project       *\n    * Distributed under the GNU GPL v 3.0 licence, see                    *\n    * LICENCE (supplied with this release) for details                    *\n    ***********************************************************************\n    \n\n\nYou should some status text and a version of the welcome screen:\n```\n***********************************************************************\n* Welcome to CBMPy (0.7.4) - PySCeS Constraint Based Modelling        *\n*                http://cbmpy.sourceforge.net                         *\n* Copyright(C) Brett G. Olivier 2014 - 2016                           *\n* Dept. of Systems Bioinformatics                                     *\n* Vrije Universiteit Amsterdam, Amsterdam, The Netherlands            *\n* CBMPy is developed as part of the BeBasic MetaToolKit Project       *\n* Distributed under the GNU GPL v 3.0 licence, see                    *\n* LICENCE (supplied with this release) for details                    *\n***********************************************************************\n```\n\n## Testing the installation, loading the default models\n\nCBMPy now includes a growing set of Nose based unittests, try run them to test your installation (this may take a few minutes) unfortunately the test runner does not seem to like the Notebook environment but try the following in a console:\n\n```import cbmpy\ncbmpy.test()```\n\nIn addition CBMPy is also shipped with two models that can be used to test your installation and get going quickly. In order to use these models at least SBML FBC version 1 support is required and both models can be loaded using the *special* filenames: `cbmpy_test_core` and  `cbmpy_test_ecoli`.\n\nIn CBMPy models are *read* from files and *instantiated* as Python objects. Here I will instantiated two model objectes from the two test files: `cmod` and `ecoli` but you can use any Python name. Note it is possible to instantiate multiple *independent* instances from the same input file.\n\n\n```python\ncmod = cbmpy.readSBML3FBC('cbmpy_test_core')\necoli = cbmpy.readSBML3FBC('cbmpy_test_ecoli')\n```\n\n    core_memesa_model.l3.xml\n    FBC version: 1\n    M.getNumReactions: 26\n    M.getNumSpecies: 22\n    FBC.getNumObjectives: 1\n    FBC.getNumGeneAssociations: 0\n    FBC.getNumFluxBounds: 52\n    Zero dimension compartment detected: Cell\n    INFO: Active objective: objMaxJ25\n    Adding objective: objMaxJ25\n    \n    SBML3 load time: 0.023\n    \n    INFO: no standard gene encoding detected, attempting to load from annotations.\n    INFO: used key(s) '[]'\n    INFO: Added 0 new genes and 0 associations to model\n    Ecoli_iJR904.glc.l3.xml\n    FBC version: 1\n    M.getNumReactions: 1066\n    M.getNumSpecies: 904\n    FBC.getNumObjectives: 1\n    FBC.getNumGeneAssociations: 1066\n    FBC.getNumFluxBounds: 2132\n    INFO: Active objective: obj1\n    Adding objective: obj1\n    \n    SBML3 load time: 1.264\n    \n\n\nOnce model objects have been instantiated they can be modified and analysed, here we will perform FBA on each model and test that CBMPy is calculating the correct result:\n\n\n```python\nprint('\\n*****\\nCalculating FBA for model: core\\n*****')\noptcm = cbmpy.analyzeModel(cmod)\n\nprint('\\n*****\\nCalculating FBA for model: ecoli\\n*****')\noptec = cbmpy.analyzeModel(ecoli)\n\nif 1.0 - abs(round(optcm, 2)) < 1.2e-10:\n    print('\\nCore model test FBA: PASSED.\\n Value expected: 1.0, calculated: {}'.format(round(optcm, 2)))\nelse:\n    print('\\nCore model test FBA: FAILED.\\n Value expected: 1.0, calculated: {}'.format(round(optcm, 2)))\nif 1.0 - abs(round(optec, 2)) < 1.2e-10:\n    print('\\nE. Coli model test FBA: PASSED.\\n Value expected: 1.0, calculated: {}'.format(round(optec, 2)))\nelse:\n    print('\\nE. Coli model test FBA: FAILED.\\n Value expected: 1.0, calculated: {}'.format(round(optec, 2)))\n\n```\n\n    \n    *****\n    Calculating FBA for model: core\n    *****\n    \n    cplx_constructLPfromFBA time: 0.0090000629425\n    \n    \n    cplx_analyzeModel FBA --> LP time: 0.0090000629425\n    \n    Tried aggregator 1 time.\n    LP Presolve eliminated 0 rows and 4 columns.\n    Aggregator did 11 substitutions.\n    Reduced LP has 8 rows, 11 columns, and 20 nonzeros.\n    Presolve time = 0.00 sec. (0.02 ticks)\n    Initializing dual steep norms . . .\n    \n    Iteration log . . .\n    Iteration:     1   Dual objective     =          1000.000000\n    INFO: Model is optimal: 1\n    Solution status =  1 : optimal\n    Solution method =  2 : dual\n    Objective value =  1.0\n    Model is optimal\n    Status: LPS_OPT\n    Model is optimal\n    Model is optimal\n    \n    analyzeModel objective value: 1.0\n    \n    \n    *****\n    Calculating FBA for model: ecoli\n    *****\n    \n    cplx_constructLPfromFBA time: 0.0590000152588\n    \n    \n    cplx_analyzeModel FBA --> LP time: 0.0599999427795\n    \n    Tried aggregator 1 time.\n    LP Presolve eliminated 273 rows and 354 columns.\n    Aggregator did 230 substitutions.\n    Reduced LP has 258 rows, 482 columns, and 2449 nonzeros.\n    Presolve time = 0.02 sec. (0.98 ticks)\n    Initializing dual steep norms . . .\n    \n    Iteration log . . .\n    Iteration:     1   Dual objective     =       1073881.855205\n    Iteration:    62   Dual objective     =        207254.367443\n    Iteration:   124   Dual objective     =        158540.756315\n    Iteration:   186   Dual objective     =         49426.164215\n    Iteration:   248   Dual objective     =             1.274029\n    INFO: Model is optimal: 1\n    Solution status =  1 : optimal\n    Solution method =  2 : dual\n    Objective value =  1.0\n    Model is optimal\n    Status: LPS_OPT\n    Model is optimal\n    Model is optimal\n    \n    analyzeModel objective value: 1.0\n    \n    \n    Core model test FBA: PASSED.\n     Value expected: 1.0, calculated: 1.0\n    \n    E. Coli model test FBA: PASSED.\n     Value expected: 1.0, calculated: 1.0\n\n\nIf both of the above tests passed, congratulations you are ready to model with CBMPy. In tutorial 2 we will look in more detail at model ecoding formats that can be used with CBMPy.\n", "meta": {"hexsha": "ba2e78194c67eab3fe340760b41b74c9bfa51c95", "size": 12070, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "cbmpy-docs/tutorials/cbmpy-jupyter/cbmpy_01_getting-started.ipynb", "max_stars_repo_name": "bgoli/cbmpy-dev", "max_stars_repo_head_hexsha": "04a6179af8e04aefdb49ed97f34544ede8180005", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cbmpy-docs/tutorials/cbmpy-jupyter/cbmpy_01_getting-started.ipynb", "max_issues_repo_name": "bgoli/cbmpy-dev", "max_issues_repo_head_hexsha": "04a6179af8e04aefdb49ed97f34544ede8180005", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cbmpy-docs/tutorials/cbmpy-jupyter/cbmpy_01_getting-started.ipynb", "max_forks_repo_name": "bgoli/cbmpy-dev", "max_forks_repo_head_hexsha": "04a6179af8e04aefdb49ed97f34544ede8180005", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.683908046, "max_line_length": 331, "alphanum_fraction": 0.5495443248, "converted": true, "num_tokens": 2202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510528442897664, "lm_q2_score": 0.06754669207816587, "lm_q1q2_score": 0.023310720381871937}}
{"text": "```python\nprint(\"Hello, World!\")\n```\n\n    Hello, World!\n\n\n\n```python\nimport time\ntime.sleep(3)\n```\n\n\n```python\ndef say_hello(recipient):\n    return 'Hello, {}!'.format(recipient)\n\nsay_hello('Bugx')\n```\n\n\n\n\n    'Hello, Bugx!'\n\n\n\n# Title\n## Section\n### Title\n\n\\begin{equation}\ny = ax^2 + bx + c + \\frac{e^x}{\\tan x}\n\\end{equation}\n\n\n```python\n\n```\n", "meta": {"hexsha": "09c96badec4e9878cb3597904c0b78fc0bc1348a", "size": 1828, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebook/hello/hello_world.ipynb", "max_stars_repo_name": "dudung/cookbook", "max_stars_repo_head_hexsha": "8a43a923af8367dafd04e3dd2ef6b9e7ed82b22f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebook/hello/hello_world.ipynb", "max_issues_repo_name": "dudung/cookbook", "max_issues_repo_head_hexsha": "8a43a923af8367dafd04e3dd2ef6b9e7ed82b22f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebook/hello/hello_world.ipynb", "max_forks_repo_name": "dudung/cookbook", "max_forks_repo_head_hexsha": "8a43a923af8367dafd04e3dd2ef6b9e7ed82b22f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0841121495, "max_line_length": 50, "alphanum_fraction": 0.4638949672, "converted": true, "num_tokens": 113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18713266402902046, "lm_q2_score": 0.12421299862599397, "lm_q1q2_score": 0.02324430933991531}}
{"text": "```\n# Data: US regional unemployment data from Bureau of Labor Statistics\n! pip install qeds\n```\n\n    Collecting qeds\n      Downloading https://files.pythonhosted.org/packages/41/50/509c79a019156862898acb9e23b28e872818c20492da187090167f6702ad/qeds-0.6.2.tar.gz\n    Requirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from qeds) (1.0.5)\n    Requirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from qeds) (2.23.0)\n    Collecting quandl\n      Downloading https://files.pythonhosted.org/packages/1b/29/185269dbd2e2698c8098b35c52ce73a2c52cf76163e709f9f7789d03ebbb/Quandl-3.5.2-py2.py3-none-any.whl\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from qeds) (1.4.1)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from qeds) (1.18.5)\n    Collecting quantecon\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/5d/e3/4fd5f948de917036b5696347b28fa25da7bd7df995e4f9f42db1c3070eb8/quantecon-0.4.8-py3-none-any.whl (230kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 235kB 6.0MB/s \n    \u001b[?25hRequirement already satisfied: matplotlib in /usr/local/lib/python3.6/dist-packages (from qeds) (3.2.2)\n    Requirement already satisfied: pyarrow in /usr/local/lib/python3.6/dist-packages (from qeds) (0.14.1)\n    Requirement already satisfied: openpyxl in /usr/local/lib/python3.6/dist-packages (from qeds) (2.5.9)\n    Requirement already satisfied: plotly in /usr/local/lib/python3.6/dist-packages (from qeds) (4.4.1)\n    Requirement already satisfied: pandas_datareader in /usr/local/lib/python3.6/dist-packages (from qeds) (0.8.1)\n    Requirement already satisfied: scikit-learn in /usr/local/lib/python3.6/dist-packages (from qeds) (0.22.2.post1)\n    Requirement already satisfied: seaborn in /usr/local/lib/python3.6/dist-packages (from qeds) (0.10.1)\n    Requirement already satisfied: statsmodels in /usr/local/lib/python3.6/dist-packages (from qeds) (0.10.2)\n    Requirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas->qeds) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas->qeds) (2018.9)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->qeds) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->qeds) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->qeds) (2020.6.20)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->qeds) (3.0.4)\n    Requirement already satisfied: more-itertools in /usr/local/lib/python3.6/dist-packages (from quandl->qeds) (8.5.0)\n    Collecting inflection>=0.3.1\n      Downloading https://files.pythonhosted.org/packages/59/91/aa6bde563e0085a02a435aa99b49ef75b0a4b062635e606dab23ce18d720/inflection-0.5.1-py2.py3-none-any.whl\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from quandl->qeds) (1.15.0)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.6/dist-packages (from quantecon->qeds) (1.1.1)\n    Requirement already satisfied: numba>=0.38 in /usr/local/lib/python3.6/dist-packages (from quantecon->qeds) (0.48.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->qeds) (2.4.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->qeds) (1.2.0)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib->qeds) (0.10.0)\n    Requirement already satisfied: et-xmlfile in /usr/local/lib/python3.6/dist-packages (from openpyxl->qeds) (1.0.1)\n    Requirement already satisfied: jdcal in /usr/local/lib/python3.6/dist-packages (from openpyxl->qeds) (1.4.1)\n    Requirement already satisfied: retrying>=1.3.3 in /usr/local/lib/python3.6/dist-packages (from plotly->qeds) (1.3.3)\n    Requirement already satisfied: lxml in /usr/local/lib/python3.6/dist-packages (from pandas_datareader->qeds) (4.2.6)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->qeds) (0.16.0)\n    Requirement already satisfied: patsy>=0.4.0 in /usr/local/lib/python3.6/dist-packages (from statsmodels->qeds) (0.5.1)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy->quantecon->qeds) (1.1.0)\n    Requirement already satisfied: llvmlite<0.32.0,>=0.31.0dev0 in /usr/local/lib/python3.6/dist-packages (from numba>=0.38->quantecon->qeds) (0.31.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from numba>=0.38->quantecon->qeds) (50.3.0)\n    Building wheels for collected packages: qeds\n      Building wheel for qeds (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for qeds: filename=qeds-0.6.2-cp36-none-any.whl size=27821 sha256=7e13f5972afd7d6676eb9587e4cf0b29bcfdaf9b215dc4e26962f5e8ae8709df\n      Stored in directory: /root/.cache/pip/wheels/b7/0b/74/c09109813c2b6116a2d4f2833c354b24163672f846a50fc7b4\n    Successfully built qeds\n    Installing collected packages: inflection, quandl, quantecon, qeds\n    Successfully installed inflection-0.5.1 qeds-0.6.2 quandl-3.5.2 quantecon-0.4.8\n\n\n\n```\nimport pandas as pd\n%matplotlib inline\n# activating plot theme\nimport qeds\nqeds.themes.mpl_style\n```\n\n\n\n\n    <function qeds.themes.mpl_style>\n\n\n\n\n```\npd.__version__\n```\n\n\n\n\n    '1.0.5'\n\n\n\n\n```\nvalues = [5.6,5.3,4.3,4.2,5.8,5.3,4.6,7.8,9.1,8.,5.7]\nyears = list(range(1995,2017,2))\nunemp = pd.Series(data=values,index=years,name='Unemployment')\nunemp\n```\n\n\n\n\n    1995    5.6\n    1997    5.3\n    1999    4.3\n    2001    4.2\n    2003    5.8\n    2005    5.3\n    2007    4.6\n    2009    7.8\n    2011    9.1\n    2013    8.0\n    2015    5.7\n    Name: Unemployment, dtype: float64\n\n\n\n\n```\nunemp.index\n```\n\n\n\n\n    Int64Index([1995, 1997, 1999, 2001, 2003, 2005, 2007, 2009, 2011, 2013, 2015], dtype='int64')\n\n\n\n\n```\nunemp.values\n```\n\n\n\n\n    array([5.6, 5.3, 4.3, 4.2, 5.8, 5.3, 4.6, 7.8, 9.1, 8. , 5.7])\n\n\n\n\n```\nunemp.name\n```\n\n\n\n\n    'Unemployment'\n\n\n\n\n```\nunemp.plot() #python matplotlib plot command\n```\n\n\n```\n# unique values\nunemp.unique()\n```\n\n\n\n\n    array([5.6, 5.3, 4.3, 4.2, 5.8, 4.6, 7.8, 9.1, 8. , 5.7])\n\n\n\n\n```\nunemp.plot.bar()\n```\n\n\n```\n# DataFrame\ndata = {\n    \"NorthEast\": [5.9,  5.6,  4.4,  3.8,  5.8,  4.9,  4.3,  7.1,  8.3,  7.9,  5.7],\n    \"MidWest\": [4.5,  4.3,  3.6,  4. ,  5.7,  5.7,  4.9,  8.1,  8.7,  7.4,  5.1],\n    \"South\": [5.3,  5.2,  4.2,  4. ,  5.7,  5.2,  4.3,  7.6,  9.1,  7.4,  5.5],\n    \"West\": [6.6, 6., 5.2, 4.6, 6.5, 5.5, 4.5, 8.6, 10.7, 8.5, 6.1],\n    \"National\": [5.6, 5.3, 4.3, 4.2, 5.8, 5.3, 4.6, 7.8, 9.1, 8., 5.7]\n}\nunemp_region = pd.DataFrame(data,index=years)\nunemp_region\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>NorthEast</th>\n      <th>MidWest</th>\n      <th>South</th>\n      <th>West</th>\n      <th>National</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1995</th>\n      <td>5.9</td>\n      <td>4.5</td>\n      <td>5.3</td>\n      <td>6.6</td>\n      <td>5.6</td>\n    </tr>\n    <tr>\n      <th>1997</th>\n      <td>5.6</td>\n      <td>4.3</td>\n      <td>5.2</td>\n      <td>6.0</td>\n      <td>5.3</td>\n    </tr>\n    <tr>\n      <th>1999</th>\n      <td>4.4</td>\n      <td>3.6</td>\n      <td>4.2</td>\n      <td>5.2</td>\n      <td>4.3</td>\n    </tr>\n    <tr>\n      <th>2001</th>\n      <td>3.8</td>\n      <td>4.0</td>\n      <td>4.0</td>\n      <td>4.6</td>\n      <td>4.2</td>\n    </tr>\n    <tr>\n      <th>2003</th>\n      <td>5.8</td>\n      <td>5.7</td>\n      <td>5.7</td>\n      <td>6.5</td>\n      <td>5.8</td>\n    </tr>\n    <tr>\n      <th>2005</th>\n      <td>4.9</td>\n      <td>5.7</td>\n      <td>5.2</td>\n      <td>5.5</td>\n      <td>5.3</td>\n    </tr>\n    <tr>\n      <th>2007</th>\n      <td>4.3</td>\n      <td>4.9</td>\n      <td>4.3</td>\n      <td>4.5</td>\n      <td>4.6</td>\n    </tr>\n    <tr>\n      <th>2009</th>\n      <td>7.1</td>\n      <td>8.1</td>\n      <td>7.6</td>\n      <td>8.6</td>\n      <td>7.8</td>\n    </tr>\n    <tr>\n      <th>2011</th>\n      <td>8.3</td>\n      <td>8.7</td>\n      <td>9.1</td>\n      <td>10.7</td>\n      <td>9.1</td>\n    </tr>\n    <tr>\n      <th>2013</th>\n      <td>7.9</td>\n      <td>7.4</td>\n      <td>7.4</td>\n      <td>8.5</td>\n      <td>8.0</td>\n    </tr>\n    <tr>\n      <th>2015</th>\n      <td>5.7</td>\n      <td>5.1</td>\n      <td>5.5</td>\n      <td>6.1</td>\n      <td>5.7</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\n# Computations with Columns\nunemp_region['West']/100\n```\n\n\n\n\n    1995    0.066\n    1997    0.060\n    1999    0.052\n    2001    0.046\n    2003    0.065\n    2005    0.055\n    2007    0.045\n    2009    0.086\n    2011    0.107\n    2013    0.085\n    2015    0.061\n    Name: West, dtype: float64\n\n\n\n\n```\n# finding correlation \nunemp_region.corr()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>NorthEast</th>\n      <th>MidWest</th>\n      <th>South</th>\n      <th>West</th>\n      <th>National</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>NorthEast</th>\n      <td>1.000000</td>\n      <td>0.875654</td>\n      <td>0.964415</td>\n      <td>0.967875</td>\n      <td>0.976016</td>\n    </tr>\n    <tr>\n      <th>MidWest</th>\n      <td>0.875654</td>\n      <td>1.000000</td>\n      <td>0.951379</td>\n      <td>0.900638</td>\n      <td>0.952389</td>\n    </tr>\n    <tr>\n      <th>South</th>\n      <td>0.964415</td>\n      <td>0.951379</td>\n      <td>1.000000</td>\n      <td>0.987259</td>\n      <td>0.995030</td>\n    </tr>\n    <tr>\n      <th>West</th>\n      <td>0.967875</td>\n      <td>0.900638</td>\n      <td>0.987259</td>\n      <td>1.000000</td>\n      <td>0.981308</td>\n    </tr>\n    <tr>\n      <th>National</th>\n      <td>0.976016</td>\n      <td>0.952389</td>\n      <td>0.995030</td>\n      <td>0.981308</td>\n      <td>1.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\nunemp_region.dtypes\n```\n\n\n\n\n    NorthEast    float64\n    MidWest      float64\n    South        float64\n    West         float64\n    National     float64\n    dtype: object\n\n\n\n\n```\nstr_unemp = unemp_region.copy()\nstr_unemp['South'] = str_unemp['South'].astype(str)\nstr_unemp.dtypes\n```\n\n\n\n\n    NorthEast    float64\n    MidWest      float64\n    South         object\n    West         float64\n    National     float64\n    dtype: object\n\n\n\n\n```\nstr_unemp.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>NorthEast</th>\n      <th>MidWest</th>\n      <th>South</th>\n      <th>West</th>\n      <th>National</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1995</th>\n      <td>5.9</td>\n      <td>4.5</td>\n      <td>5.3</td>\n      <td>6.6</td>\n      <td>5.6</td>\n    </tr>\n    <tr>\n      <th>1997</th>\n      <td>5.6</td>\n      <td>4.3</td>\n      <td>5.2</td>\n      <td>6.0</td>\n      <td>5.3</td>\n    </tr>\n    <tr>\n      <th>1999</th>\n      <td>4.4</td>\n      <td>3.6</td>\n      <td>4.2</td>\n      <td>5.2</td>\n      <td>4.3</td>\n    </tr>\n    <tr>\n      <th>2001</th>\n      <td>3.8</td>\n      <td>4.0</td>\n      <td>4.0</td>\n      <td>4.6</td>\n      <td>4.2</td>\n    </tr>\n    <tr>\n      <th>2003</th>\n      <td>5.8</td>\n      <td>5.7</td>\n      <td>5.7</td>\n      <td>6.5</td>\n      <td>5.8</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\nstr_unemp.sum()\n```\n\n\n\n\n    NorthEast                                 63.7\n    MidWest                                     62\n    South        5.35.24.24.05.75.24.37.69.17.45.5\n    West                                      72.8\n    National                                  65.7\n    dtype: object\n\n\n\n\n```\n# creating new columns \nunemp_region[\"UnweightedMean\"] = (unemp_region[\"NorthEast\"] +\n                                  unemp_region[\"MidWest\"] +\n                                  unemp_region[\"South\"] +\n                                  unemp_region[\"West\"])/4\n```\n\n\n```\nunemp_region.tail()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>NorthEast</th>\n      <th>MidWest</th>\n      <th>South</th>\n      <th>West</th>\n      <th>National</th>\n      <th>UnweightedMean</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2007</th>\n      <td>4.3</td>\n      <td>4.9</td>\n      <td>4.3</td>\n      <td>4.5</td>\n      <td>4.6</td>\n      <td>4.50</td>\n    </tr>\n    <tr>\n      <th>2009</th>\n      <td>7.1</td>\n      <td>8.1</td>\n      <td>7.6</td>\n      <td>8.6</td>\n      <td>7.8</td>\n      <td>7.85</td>\n    </tr>\n    <tr>\n      <th>2011</th>\n      <td>8.3</td>\n      <td>8.7</td>\n      <td>9.1</td>\n      <td>10.7</td>\n      <td>9.1</td>\n      <td>9.20</td>\n    </tr>\n    <tr>\n      <th>2013</th>\n      <td>7.9</td>\n      <td>7.4</td>\n      <td>7.4</td>\n      <td>8.5</td>\n      <td>8.0</td>\n      <td>7.80</td>\n    </tr>\n    <tr>\n      <th>2015</th>\n      <td>5.7</td>\n      <td>5.1</td>\n      <td>5.5</td>\n      <td>6.1</td>\n      <td>5.7</td>\n      <td>5.60</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\n# renaming columns by passing a dictionary to the 'rename' method\nnames = {'NorthEast':'NE','MidWest':'MW','South':'S','West':'W'}\nunemp_region.rename(columns=names,inplace=True)\nunemp_region.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>NE</th>\n      <th>MW</th>\n      <th>S</th>\n      <th>W</th>\n      <th>National</th>\n      <th>UnweightedMean</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1995</th>\n      <td>5.9</td>\n      <td>4.5</td>\n      <td>5.3</td>\n      <td>6.6</td>\n      <td>5.6</td>\n      <td>5.575</td>\n    </tr>\n    <tr>\n      <th>1997</th>\n      <td>5.6</td>\n      <td>4.3</td>\n      <td>5.2</td>\n      <td>6.0</td>\n      <td>5.3</td>\n      <td>5.275</td>\n    </tr>\n    <tr>\n      <th>1999</th>\n      <td>4.4</td>\n      <td>3.6</td>\n      <td>4.2</td>\n      <td>5.2</td>\n      <td>4.3</td>\n      <td>4.350</td>\n    </tr>\n    <tr>\n      <th>2001</th>\n      <td>3.8</td>\n      <td>4.0</td>\n      <td>4.0</td>\n      <td>4.6</td>\n      <td>4.2</td>\n      <td>4.100</td>\n    </tr>\n    <tr>\n      <th>2003</th>\n      <td>5.8</td>\n      <td>5.7</td>\n      <td>5.7</td>\n      <td>6.5</td>\n      <td>5.8</td>\n      <td>5.925</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\n###############################project##################################################\n# loading up data\nurl = \"https://datascience.quantecon.org/assets/data/state_unemployment.csv\"\nunemp_raw = pd.read_csv(url,parse_dates=['Date']) \n# load up the Date column as a Python datetime type\nunemp_raw.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Date</th>\n      <th>state</th>\n      <th>LaborForce</th>\n      <th>UnemploymentRate</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>2000-01-01</td>\n      <td>Alabama</td>\n      <td>2142945.0</td>\n      <td>4.7</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2000-01-01</td>\n      <td>Alaska</td>\n      <td>319059.0</td>\n      <td>6.3</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2000-01-01</td>\n      <td>Arizona</td>\n      <td>2499980.0</td>\n      <td>4.1</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>2000-01-01</td>\n      <td>Arkansas</td>\n      <td>1264619.0</td>\n      <td>4.4</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>2000-01-01</td>\n      <td>California</td>\n      <td>16680246.0</td>\n      <td>5.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\nunemp_raw.shape\n```\n\n\n\n\n    (10800, 4)\n\n\n\n\n```\n# looking at unemployment rate across different states over time\n# data transformation\nunemp_all = (unemp_raw\n             .reset_index()\n             .pivot_table(index='Date',columns='state',values='UnemploymentRate')\n             )\nunemp_all.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>state</th>\n      <th>Alabama</th>\n      <th>Alaska</th>\n      <th>Arizona</th>\n      <th>Arkansas</th>\n      <th>California</th>\n      <th>Colorado</th>\n      <th>Connecticut</th>\n      <th>Delaware</th>\n      <th>Florida</th>\n      <th>Georgia</th>\n      <th>Hawaii</th>\n      <th>Idaho</th>\n      <th>Illinois</th>\n      <th>Indiana</th>\n      <th>Iowa</th>\n      <th>Kansas</th>\n      <th>Kentucky</th>\n      <th>Louisiana</th>\n      <th>Maine</th>\n      <th>Maryland</th>\n      <th>Massachusetts</th>\n      <th>Michigan</th>\n      <th>Minnesota</th>\n      <th>Mississippi</th>\n      <th>Missouri</th>\n      <th>Montana</th>\n      <th>Nebraska</th>\n      <th>Nevada</th>\n      <th>New Hampshire</th>\n      <th>New Mexico</th>\n      <th>New York</th>\n      <th>New jersey</th>\n      <th>North Carolina</th>\n      <th>North Dakota</th>\n      <th>Ohio</th>\n      <th>Oklahoma</th>\n      <th>Oregon</th>\n      <th>Pennsylvania</th>\n      <th>Rhode island</th>\n      <th>South Carolina</th>\n      <th>South Dakota</th>\n      <th>Tennessee</th>\n      <th>Texas</th>\n      <th>Utah</th>\n      <th>Vermont</th>\n      <th>Virginia</th>\n      <th>Washington</th>\n      <th>West Virginia</th>\n      <th>Wisconsin</th>\n      <th>Wyoming</th>\n    </tr>\n    <tr>\n      <th>Date</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2000-01-01</th>\n      <td>4.7</td>\n      <td>6.3</td>\n      <td>4.1</td>\n      <td>4.4</td>\n      <td>5.0</td>\n      <td>2.8</td>\n      <td>2.8</td>\n      <td>3.5</td>\n      <td>3.7</td>\n      <td>3.7</td>\n      <td>4.7</td>\n      <td>4.6</td>\n      <td>4.2</td>\n      <td>3.2</td>\n      <td>2.4</td>\n      <td>3.4</td>\n      <td>4.2</td>\n      <td>5.1</td>\n      <td>3.6</td>\n      <td>3.4</td>\n      <td>3.0</td>\n      <td>3.3</td>\n      <td>3.0</td>\n      <td>5.4</td>\n      <td>3.1</td>\n      <td>5.1</td>\n      <td>2.8</td>\n      <td>3.9</td>\n      <td>2.7</td>\n      <td>5.1</td>\n      <td>4.7</td>\n      <td>3.8</td>\n      <td>3.3</td>\n      <td>3.1</td>\n      <td>4.1</td>\n      <td>3.2</td>\n      <td>5.0</td>\n      <td>4.1</td>\n      <td>4.0</td>\n      <td>4.0</td>\n      <td>2.4</td>\n      <td>3.7</td>\n      <td>4.6</td>\n      <td>3.1</td>\n      <td>2.7</td>\n      <td>2.6</td>\n      <td>4.9</td>\n      <td>5.8</td>\n      <td>3.2</td>\n      <td>4.1</td>\n    </tr>\n    <tr>\n      <th>2000-02-01</th>\n      <td>4.7</td>\n      <td>6.3</td>\n      <td>4.1</td>\n      <td>4.3</td>\n      <td>5.0</td>\n      <td>2.8</td>\n      <td>2.7</td>\n      <td>3.6</td>\n      <td>3.7</td>\n      <td>3.6</td>\n      <td>4.6</td>\n      <td>4.6</td>\n      <td>4.2</td>\n      <td>3.3</td>\n      <td>2.4</td>\n      <td>3.4</td>\n      <td>4.1</td>\n      <td>5.1</td>\n      <td>3.5</td>\n      <td>3.4</td>\n      <td>2.9</td>\n      <td>3.2</td>\n      <td>3.0</td>\n      <td>5.5</td>\n      <td>3.2</td>\n      <td>5.0</td>\n      <td>2.8</td>\n      <td>3.9</td>\n      <td>2.7</td>\n      <td>5.0</td>\n      <td>4.7</td>\n      <td>3.7</td>\n      <td>3.3</td>\n      <td>3.0</td>\n      <td>4.1</td>\n      <td>3.1</td>\n      <td>5.0</td>\n      <td>4.0</td>\n      <td>4.0</td>\n      <td>3.9</td>\n      <td>2.4</td>\n      <td>3.7</td>\n      <td>4.6</td>\n      <td>3.1</td>\n      <td>2.6</td>\n      <td>2.5</td>\n      <td>4.9</td>\n      <td>5.6</td>\n      <td>3.2</td>\n      <td>3.9</td>\n    </tr>\n    <tr>\n      <th>2000-03-01</th>\n      <td>4.6</td>\n      <td>6.3</td>\n      <td>4.0</td>\n      <td>4.3</td>\n      <td>5.0</td>\n      <td>2.7</td>\n      <td>2.6</td>\n      <td>3.6</td>\n      <td>3.7</td>\n      <td>3.6</td>\n      <td>4.5</td>\n      <td>4.6</td>\n      <td>4.3</td>\n      <td>3.3</td>\n      <td>2.4</td>\n      <td>3.5</td>\n      <td>4.1</td>\n      <td>5.1</td>\n      <td>3.5</td>\n      <td>3.5</td>\n      <td>2.8</td>\n      <td>3.2</td>\n      <td>3.0</td>\n      <td>5.5</td>\n      <td>3.3</td>\n      <td>5.0</td>\n      <td>2.8</td>\n      <td>4.0</td>\n      <td>2.7</td>\n      <td>4.9</td>\n      <td>4.6</td>\n      <td>3.6</td>\n      <td>3.4</td>\n      <td>3.0</td>\n      <td>4.0</td>\n      <td>3.1</td>\n      <td>5.0</td>\n      <td>4.0</td>\n      <td>4.0</td>\n      <td>3.8</td>\n      <td>2.4</td>\n      <td>3.8</td>\n      <td>4.5</td>\n      <td>3.1</td>\n      <td>2.6</td>\n      <td>2.4</td>\n      <td>5.0</td>\n      <td>5.5</td>\n      <td>3.3</td>\n      <td>3.9</td>\n    </tr>\n    <tr>\n      <th>2000-04-01</th>\n      <td>4.6</td>\n      <td>6.3</td>\n      <td>4.0</td>\n      <td>4.3</td>\n      <td>5.1</td>\n      <td>2.7</td>\n      <td>2.5</td>\n      <td>3.7</td>\n      <td>3.7</td>\n      <td>3.7</td>\n      <td>4.4</td>\n      <td>4.6</td>\n      <td>4.3</td>\n      <td>3.3</td>\n      <td>2.5</td>\n      <td>3.5</td>\n      <td>4.1</td>\n      <td>5.1</td>\n      <td>3.4</td>\n      <td>3.5</td>\n      <td>2.7</td>\n      <td>3.3</td>\n      <td>3.0</td>\n      <td>5.6</td>\n      <td>3.3</td>\n      <td>5.0</td>\n      <td>2.8</td>\n      <td>4.0</td>\n      <td>2.7</td>\n      <td>4.9</td>\n      <td>4.6</td>\n      <td>3.6</td>\n      <td>3.4</td>\n      <td>2.9</td>\n      <td>4.0</td>\n      <td>3.1</td>\n      <td>5.0</td>\n      <td>4.0</td>\n      <td>4.0</td>\n      <td>3.7</td>\n      <td>2.4</td>\n      <td>3.8</td>\n      <td>4.4</td>\n      <td>3.1</td>\n      <td>2.7</td>\n      <td>2.4</td>\n      <td>5.0</td>\n      <td>5.4</td>\n      <td>3.4</td>\n      <td>3.8</td>\n    </tr>\n    <tr>\n      <th>2000-05-01</th>\n      <td>4.5</td>\n      <td>6.3</td>\n      <td>4.0</td>\n      <td>4.2</td>\n      <td>5.1</td>\n      <td>2.7</td>\n      <td>2.4</td>\n      <td>3.7</td>\n      <td>3.7</td>\n      <td>3.7</td>\n      <td>4.3</td>\n      <td>4.6</td>\n      <td>4.3</td>\n      <td>3.3</td>\n      <td>2.5</td>\n      <td>3.5</td>\n      <td>4.1</td>\n      <td>5.1</td>\n      <td>3.3</td>\n      <td>3.6</td>\n      <td>2.6</td>\n      <td>3.5</td>\n      <td>3.0</td>\n      <td>5.6</td>\n      <td>3.3</td>\n      <td>5.0</td>\n      <td>2.8</td>\n      <td>4.0</td>\n      <td>2.7</td>\n      <td>4.9</td>\n      <td>4.6</td>\n      <td>3.6</td>\n      <td>3.5</td>\n      <td>2.9</td>\n      <td>4.1</td>\n      <td>3.1</td>\n      <td>5.1</td>\n      <td>4.0</td>\n      <td>4.1</td>\n      <td>3.8</td>\n      <td>2.4</td>\n      <td>3.9</td>\n      <td>4.3</td>\n      <td>3.2</td>\n      <td>2.7</td>\n      <td>2.3</td>\n      <td>5.1</td>\n      <td>5.4</td>\n      <td>3.5</td>\n      <td>3.8</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\nstates = [\n          'Arizona','California','Florida','Illinois',\n          'Michigan','New York','Texas'\n]\nunemp = unemp_all[states]\nunemp.head()\n# a subset\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>state</th>\n      <th>Arizona</th>\n      <th>California</th>\n      <th>Florida</th>\n      <th>Illinois</th>\n      <th>Michigan</th>\n      <th>New York</th>\n      <th>Texas</th>\n    </tr>\n    <tr>\n      <th>Date</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2000-01-01</th>\n      <td>4.1</td>\n      <td>5.0</td>\n      <td>3.7</td>\n      <td>4.2</td>\n      <td>3.3</td>\n      <td>4.7</td>\n      <td>4.6</td>\n    </tr>\n    <tr>\n      <th>2000-02-01</th>\n      <td>4.1</td>\n      <td>5.0</td>\n      <td>3.7</td>\n      <td>4.2</td>\n      <td>3.2</td>\n      <td>4.7</td>\n      <td>4.6</td>\n    </tr>\n    <tr>\n      <th>2000-03-01</th>\n      <td>4.0</td>\n      <td>5.0</td>\n      <td>3.7</td>\n      <td>4.3</td>\n      <td>3.2</td>\n      <td>4.6</td>\n      <td>4.5</td>\n    </tr>\n    <tr>\n      <th>2000-04-01</th>\n      <td>4.0</td>\n      <td>5.1</td>\n      <td>3.7</td>\n      <td>4.3</td>\n      <td>3.3</td>\n      <td>4.6</td>\n      <td>4.4</td>\n    </tr>\n    <tr>\n      <th>2000-05-01</th>\n      <td>4.0</td>\n      <td>5.1</td>\n      <td>3.7</td>\n      <td>4.3</td>\n      <td>3.5</td>\n      <td>4.6</td>\n      <td>4.3</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\nunemp.plot(figsize=(8,6))\n```\n\n\n```\n# Dates in pandas\nunemp.index\n```\n\n\n\n\n    DatetimeIndex(['2000-01-01', '2000-02-01', '2000-03-01', '2000-04-01',\n                   '2000-05-01', '2000-06-01', '2000-07-01', '2000-08-01',\n                   '2000-09-01', '2000-10-01',\n                   ...\n                   '2017-03-01', '2017-04-01', '2017-05-01', '2017-06-01',\n                   '2017-07-01', '2017-08-01', '2017-09-01', '2017-10-01',\n                   '2017-11-01', '2017-12-01'],\n                  dtype='datetime64[ns]', name='Date', length=216, freq=None)\n\n\n\n\n```\n# Data corresponding to a single date\nunemp.loc['01/01/2000']\n```\n\n\n\n\n    state\n    Arizona       4.1\n    California    5.0\n    Florida       3.7\n    Illinois      4.2\n    Michigan      3.3\n    New York      4.7\n    Texas         4.6\n    Name: 2000-01-01 00:00:00, dtype: float64\n\n\n\n\n```\n# Data for all days between New Years Day and June first in 2000\nunemp.loc['01/01/2000':'06/01/2000']\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>state</th>\n      <th>Arizona</th>\n      <th>California</th>\n      <th>Florida</th>\n      <th>Illinois</th>\n      <th>Michigan</th>\n      <th>New York</th>\n      <th>Texas</th>\n    </tr>\n    <tr>\n      <th>Date</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2000-01-01</th>\n      <td>4.1</td>\n      <td>5.0</td>\n      <td>3.7</td>\n      <td>4.2</td>\n      <td>3.3</td>\n      <td>4.7</td>\n      <td>4.6</td>\n    </tr>\n    <tr>\n      <th>2000-02-01</th>\n      <td>4.1</td>\n      <td>5.0</td>\n      <td>3.7</td>\n      <td>4.2</td>\n      <td>3.2</td>\n      <td>4.7</td>\n      <td>4.6</td>\n    </tr>\n    <tr>\n      <th>2000-03-01</th>\n      <td>4.0</td>\n      <td>5.0</td>\n      <td>3.7</td>\n      <td>4.3</td>\n      <td>3.2</td>\n      <td>4.6</td>\n      <td>4.5</td>\n    </tr>\n    <tr>\n      <th>2000-04-01</th>\n      <td>4.0</td>\n      <td>5.1</td>\n      <td>3.7</td>\n      <td>4.3</td>\n      <td>3.3</td>\n      <td>4.6</td>\n      <td>4.4</td>\n    </tr>\n    <tr>\n      <th>2000-05-01</th>\n      <td>4.0</td>\n      <td>5.1</td>\n      <td>3.7</td>\n      <td>4.3</td>\n      <td>3.5</td>\n      <td>4.6</td>\n      <td>4.3</td>\n    </tr>\n    <tr>\n      <th>2000-06-01</th>\n      <td>4.0</td>\n      <td>5.1</td>\n      <td>3.8</td>\n      <td>4.3</td>\n      <td>3.7</td>\n      <td>4.6</td>\n      <td>4.3</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\n# Data aggregations: combining multiple values into a single value\n# Data aggregations are used extensively to analyze and manipulate data\nunemp.mean()\n```\n\n\n\n\n    state\n    Arizona       6.301389\n    California    7.299074\n    Florida       6.048611\n    Illinois      6.822685\n    Michigan      7.492593\n    New York      6.102315\n    Texas         5.695370\n    dtype: float64\n\n\n\n\n```\n# aggregations on rows\nunemp.var(axis=1)\n```\n\n\n\n\n    Date\n    2000-01-01    0.352381\n    2000-02-01    0.384762\n    2000-03-01    0.364762\n    2000-04-01    0.353333\n    2000-05-01    0.294762\n                    ...   \n    2017-08-01    0.141429\n    2017-09-01    0.163333\n    2017-10-01    0.165714\n    2017-11-01    0.165714\n    2017-12-01    0.148095\n    Length: 216, dtype: float64\n\n\n\n\n```\n# custom-built aggregations \n#classify states as \u201clow unemployment\u201d or \u201chigh unemployment\u201d based on whether their mean unemployment level is above or below 6.5\ndef high_or_low(s):\n    \"\"\"\n    high\n    if the mean is above 6.5 and low if the mean is below 6.5\n    \"\"\"\n    if s.mean() < 6.5:\n        out ='Low'\n    else:\n        out = 'High'\n\n    return out\n```\n\n\n```\nunemp.agg(high_or_low)\n```\n\n\n\n\n    state\n    Arizona        Low\n    California    High\n    Florida        Low\n    Illinois      High\n    Michigan      High\n    New York       Low\n    Texas          Low\n    dtype: object\n\n\n\n\n```\nunemp.agg(high_or_low,axis=1)\n```\n\n\n\n\n    Date\n    2000-01-01    Low\n    2000-02-01    Low\n    2000-03-01    Low\n    2000-04-01    Low\n    2000-05-01    Low\n                 ... \n    2017-08-01    Low\n    2017-09-01    Low\n    2017-10-01    Low\n    2017-11-01    Low\n    2017-12-01    Low\n    Length: 216, dtype: object\n\n\n\n\n```\nunemp.agg([min,max,high_or_low])\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Arizona</th>\n      <th>California</th>\n      <th>Florida</th>\n      <th>Illinois</th>\n      <th>Michigan</th>\n      <th>New York</th>\n      <th>Texas</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>min</th>\n      <td>3.6</td>\n      <td>4.5</td>\n      <td>3.1</td>\n      <td>4.2</td>\n      <td>3.2</td>\n      <td>4.2</td>\n      <td>3.9</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>10.9</td>\n      <td>12.3</td>\n      <td>11.3</td>\n      <td>11.3</td>\n      <td>14.6</td>\n      <td>8.9</td>\n      <td>8.3</td>\n    </tr>\n    <tr>\n      <th>high_or_low</th>\n      <td>Low</td>\n      <td>High</td>\n      <td>Low</td>\n      <td>High</td>\n      <td>High</td>\n      <td>Low</td>\n      <td>Low</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\nunemp.agg([min,max,high_or_low]).columns\n```\n\n\n\n\n    Index(['Arizona', 'California', 'Florida', 'Illinois', 'Michigan', 'New York',\n           'Texas'],\n          dtype='object')\n\n\n\n\n```\n# Transforms \n\n```\n", "meta": {"hexsha": "48b5a7f4142292269830c2b8e7895808ab50024f", "size": 183120, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "_notebooks/2020-12-03-QuantEconDS.ipynb", "max_stars_repo_name": "d3LA/wOL3", "max_stars_repo_head_hexsha": "8e430c8ab45e25fe12d6b2b0402c281b168a0fae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_notebooks/2020-12-03-QuantEconDS.ipynb", "max_issues_repo_name": "d3LA/wOL3", "max_issues_repo_head_hexsha": "8e430c8ab45e25fe12d6b2b0402c281b168a0fae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-26T09:59:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T09:59:46.000Z", "max_forks_repo_path": "_notebooks/2020-12-03-QuantEconDS.ipynb", "max_forks_repo_name": "d3LA/wOL3", "max_forks_repo_head_hexsha": "8e430c8ab45e25fe12d6b2b0402c281b168a0fae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 73.6604987932, "max_line_length": 76586, "alphanum_fraction": 0.6645915247, "converted": true, "num_tokens": 13094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3593641451601019, "lm_q2_score": 0.06465348925734803, "lm_q1q2_score": 0.023234145898584704}}
{"text": "## Initial setup\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```python\nimport tensorflow as tf\nprint(tf.__version__)\n# tensorflow version used is 2.8.0\nimport torch\nprint(torch.__version__)\n# torch version used is 1.10+cu111\n```\n\n    2.8.0\n    1.10.0+cu111\n\n\n\n```python\n!nvidia-smi\n```\n\n    Sun Apr 17 21:06:30 2022       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 460.32.03    Driver Version: 460.32.03    CUDA Version: 11.2     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   43C    P8     9W /  70W |      0MiB / 15109MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    |  No running processes found                                                 |\n    +-----------------------------------------------------------------------------+\n\n\n\n```python\n# Other imports\n! pip install tensorflow_addons\n! pip install tensorflow_io\n! pip install lightgbm\n! pip install xgboost\n! pip install catboost\n\nimport os\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import *\nfrom tensorflow import keras as tfkeras\nimport matplotlib.pyplot as plt\nfrom imutils import paths\nfrom tqdm import tqdm\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nimport tensorflow_datasets as tfds\nimport tensorflow_io as tfio\nimport tensorflow_hub as hub\nimport numpy as np\nimport cv2\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics.pairwise import cosine_similarity as cos\nfrom sympy.utilities.iterables import multiset_permutations\nfrom sklearn.metrics import accuracy_score, f1_score, confusion_matrix, mean_absolute_error, r2_score\nfrom sklearn.model_selection import *\nfrom IPython.display import Image, display\nfrom scipy import ndimage\n\nfrom xgboost import XGBRegressor as xgb\nfrom sklearn.ensemble import ExtraTreesRegressor as extratree\nfrom sklearn.ensemble import RandomForestRegressor as randomforest\nfrom sklearn.svm import NuSVR as svr\nfrom sklearn.gaussian_process import GaussianProcessRegressor as gpr\nfrom sklearn.ensemble import AdaBoostRegressor as ada\nfrom sklearn.tree import DecisionTreeRegressor as tree\nfrom sklearn.ensemble import GradientBoostingRegressor as gdb\nfrom sklearn.neural_network import MLPRegressor as mlp\nfrom sklearn.experimental import enable_hist_gradient_boosting\nfrom sklearn.ensemble import HistGradientBoostingRegressor as hgb\nfrom lightgbm import LGBMRegressor as lgb\nfrom catboost import CatBoostRegressor as cgb\nfrom sklearn.ensemble import StackingRegressor as stk\nfrom sklearn.linear_model import RidgeCV\nfrom sklearn.model_selection import cross_validate, cross_val_predict\nfrom sklearn.ensemble import VotingRegressor as vot\n\nimport zipfile\nimport concurrent.futures\n\n# Random seed fix\nrandom_seed = 42\ntf.random.set_seed(random_seed)\nnp.random.seed(random_seed)\n```\n\n    Collecting tensorflow_addons\n      Downloading tensorflow_addons-0.16.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.1 MB 28.5 MB/s \n    \u001b[?25hRequirement already satisfied: typeguard>=2.7 in /usr/local/lib/python3.7/dist-packages (from tensorflow_addons) (2.7.1)\n    Installing collected packages: tensorflow-addons\n    Successfully installed tensorflow-addons-0.16.1\n    Collecting tensorflow_io\n      Downloading tensorflow_io-0.24.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (23.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 23.4 MB 60.3 MB/s \n    \u001b[?25hRequirement already satisfied: tensorflow-io-gcs-filesystem==0.24.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow_io) (0.24.0)\n    Installing collected packages: tensorflow-io\n    Successfully installed tensorflow-io-0.24.0\n    Requirement already satisfied: lightgbm in /usr/local/lib/python3.7/dist-packages (2.2.3)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from lightgbm) (1.4.1)\n    Requirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from lightgbm) (1.0.2)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from lightgbm) (1.21.5)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->lightgbm) (3.1.0)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->lightgbm) (1.1.0)\n    Requirement already satisfied: xgboost in /usr/local/lib/python3.7/dist-packages (0.90)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from xgboost) (1.4.1)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from xgboost) (1.21.5)\n    Collecting catboost\n      Downloading catboost-1.0.5-cp37-none-manylinux1_x86_64.whl (76.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 76.6 MB 1.2 MB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.16.0 in /usr/local/lib/python3.7/dist-packages (from catboost) (1.21.5)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from catboost) (1.4.1)\n    Requirement already satisfied: graphviz in /usr/local/lib/python3.7/dist-packages (from catboost) (0.10.1)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from catboost) (3.2.2)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from catboost) (1.15.0)\n    Requirement already satisfied: plotly in /usr/local/lib/python3.7/dist-packages (from catboost) (5.5.0)\n    Requirement already satisfied: pandas>=0.24.0 in /usr/local/lib/python3.7/dist-packages (from catboost) (1.3.5)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24.0->catboost) (2.8.2)\n    Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24.0->catboost) (2018.9)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->catboost) (3.0.8)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->catboost) (1.4.2)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->catboost) (0.11.0)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from kiwisolver>=1.0.1->matplotlib->catboost) (4.1.1)\n    Requirement already satisfied: tenacity>=6.2.0 in /usr/local/lib/python3.7/dist-packages (from plotly->catboost) (8.0.1)\n    Installing collected packages: catboost\n    Successfully installed catboost-1.0.5\n\n\n    /usr/local/lib/python3.7/dist-packages/sklearn/experimental/enable_hist_gradient_boosting.py:17: UserWarning: Since version 1.0, it is not needed to import enable_hist_gradient_boosting anymore. HistGradientBoostingClassifier and HistGradientBoostingRegressor are now stable and can be normally imported from sklearn.ensemble.\n      \"Since version 1.0, \"\n\n\n## Data utility, only need to use once to preprocess tiff images to png format\n\n\n```python\n%%time\nzf = zipfile.ZipFile('/content/drive/MyDrive/ML course 2022/rawImages.zip')\ndef unzip(file):\n    zf.extract(file)\nwith concurrent.futures.ProcessPoolExecutor() as executor:\n    executor.map(unzip, zf.infolist())\n```\n\n    CPU times: user 14 s, sys: 1.32 s, total: 15.3 s\n    Wall time: 5min 4s\n\n\n\n```python\ndrive.flush_and_unmount()\n```\n\n\n```python\nfor i in range(len(level1_images_train)):\n  img = cv2.imread(level1_images_train[i])\n  if img is None:\n    continue\n  img = cv2.imread(level1_images_train[i])\n  cv2.imwrite('/content/drive/MyDrive/ML course 2022_Team BNL/level1/%s.jpeg' %level1_images_train[i].split('/')[-1][:-5], img)\n```\n\n\n```python\nimport shutil\nfor i in range(len(level1_images_train)):\n  shutil.copy(level1_images_train[i], \"/content/drive/MyDrive/ML course 2022_Team BNL/level1_png/%s\" %level1_images_train[i].split(\"/\")[-1])\n```\n\n\n```python\n# the snippet that I use to create the jpegs of the high pass filtered images\npixel_std_values = np.zeros((len(train_images_directory_select)))\nfor i in range(train_images_directory_select.shape[0]):\n    im = cv2.imread(train_images_directory_select[i])                                                       # high pass filter then grayscale then standard deviation of all pixel values\n    high_pass_image = cv2.cvtColor(ndimage.gaussian_filter(im, 63) - im, cv2.COLOR_BGR2GRAY)\n    # pixel_std_values[i] = np.std(high_pass_image)\n    cv2.imwrite('/content/drive/MyDrive/ML course 2022_Team BNL/level2_kernel63/%s.jpeg' %train_images_directory_select[i].split('/')[-1][:-5], high_pass_image)\n# plt.scatter(labels, pixel_std_values)\n# plt.xlabel('true_focal_distance')\n# plt.ylabel('std value')\n```\n\n## Dataset gathering and preparation\n\n\n```python\n%cd /content/drive/MyDrive/ML\\ course\\ 2022_Team\\ BNL\n```\n\n    /content/drive/MyDrive/ML course 2022_Team BNL\n\n\n\n```python\ntraining_batch_size = 1\ntest_batch_size = 1\n\nimageSizeheight=1200\nimageSizewidth=1920\n\n# imageSizeheight=300\n# imageSizewidth=480\n```\n\n\n```python\n# Image preprocessing utils\n@tf.function\ndef parse_images(image_path):\n\n    image_string = tf.io.read_file(image_path)\n    image = tf.io.decode_jpeg(image_string, channels=3)\n    # image = tfio.experimental.image.decode_tiff(image_string, index=0, name=None)[:,:,:-1]   # in the doc, it transforms tiff to 4 channels, with additional channel of opacity which is not needed.\n    image = tf.image.convert_image_dtype(image, tf.float32)\n    image = tf.image.resize(image, size=[imageSizeheight, imageSizewidth])\n\n    return image\n```\n\n\n```python\nlevel2_images = np.array(list(paths.list_files(\"/content/drive/MyDrive/ML course 2022_Team BNL/level2_kernel63\", validExts=\"jpeg\")))\n# train_images_directory_select = np.random.choice(level2_images_train, 6000, replace=False)\n\nlabels = []                                                    # initialize labels\npositions = []\n\nfor i in range(level2_images.shape[0]):\n  label = np.abs(float(level2_images[i].split(\"_\")[-1][4:-7].split(\"(\")[0]))               # individual label, can be put into absolute or not                                                 \n  labels.append(label)\n  position = level2_images[i].split(\"_\")[-3] + '_' + level2_images[i].split(\"_\")[-2]      # individual position\n  positions.append(position)\nlabels = np.array(labels)\npositions = np.array(positions)\n\n# these test images are selected by our national lab mentor.\ntest_positions = np.array(['ix000_iy004', 'ix000_iy009', 'ix001_iy007', 'ix003_iy013', 'ix006_iy003',\n                           'ix013_iy008', 'ix013_iy012', 'ix013_iy013', 'ix015_iy006', 'ix017_iy012',\n                           'ix017_iy013', 'ix019_iy000', 'ix019_iy011', 'ix020_iy007', 'ix020_iy011',\n                           'ix020_iy015', 'ix021_iy000', 'ix021_iy006', 'ix022_iy004', 'ix023_iy005', \n                           'ix023_iy014', 'ix023_iy015', 'ix025_iy015', 'ix028_iy005', 'ix031_iy007',\n                           'ix032_iy007', 'ix032_iy008', 'ix033_iy006', 'ix034_iy004', 'ix034_iy006',\n                           'ix034_iy012', 'ix034_iy013', 'ix034_iy014', 'ix035_iy009', 'ix035_iy015',\n                           'ix036_iy006', 'ix036_iy012', 'ix036_iy013', 'ix037_iy013', 'ix038_iy014',\n                           'ix039_iy004', 'ix039_iy009', 'ix039_iy013', 'ix040_iy006', 'ix040_iy013',\n                           'ix041_iy011', 'ix045_iy008', 'ix047_iy009', 'ix048_iy013', 'ix049_iy006',\n                           'ix049_iy012', 'ix051_iy009', 'ix051_iy010', 'ix053_iy002', 'ix053_iy010',\n                           'ix053_iy013', 'ix054_iy001', 'ix054_iy012'])\n\ntest_images_directory_select = level2_images[np.where(np.isin(positions, test_positions) == True)[0]]\ntrain_images_directory_select = level2_images[np.where(np.isin(positions, test_positions) == False)[0]]\ntest_label = labels[np.where(np.isin(positions, test_positions) == True)[0]]\n\nprint(len(level2_images))\nprint(len(train_images_directory_select))\nprint(len(test_images_directory_select))\n```\n\n    9462\n    8829\n    633\n\n\n\n```python\nlabels = []                                                    # initialize labels\npositions = []\n\nfor i in range(train_images_directory_select.shape[0]):\n  label = np.abs(float(train_images_directory_select[i].split(\"_\")[-1][4:-7].split(\"(\")[0]))               # individual label, can be put into absolute or not                                                 \n  labels.append(label)\n  position = train_images_directory_select[i].split(\"_\")[-3] + '_' + train_images_directory_select[i].split(\"_\")[-2]      # individual position\n  positions.append(position)\nlabels = np.array(labels)\npositions = np.array(positions)                              # initialize the positions of the images, needed for record keeping\n```\n\n\n```python\nedge_pixel_intensity_high_threshold = 0.50\nedge_pixel_intensity_low_threshold = 0.16\nedge_percentage_threshold = 0.02\ncap = 50\n\ninfocus_images_coordinate = np.where(labels==0)[0]                                       # locations where the infocus images are\nedge_percentages = []\nvalid = []\nfor i in range(train_images_directory_select[infocus_images_coordinate].shape[0]):\n  edge_percentage = len(np.where((parse_images(train_images_directory_select[infocus_images_coordinate][i])[:,:,0]>=edge_pixel_intensity_high_threshold) \n                                  | (parse_images(train_images_directory_select[infocus_images_coordinate][i])[:,:,0]<=edge_pixel_intensity_low_threshold))[0]) / imageSizeheight / imageSizewidth\n  edge_percentages.append(edge_percentage)\n  if edge_percentage >= edge_percentage_threshold:                                                             # picking out infocus images where the area containing edges is smaller than a threshold value\n    valid.append(positions[infocus_images_coordinate][i])\n\nfor i in range(len(valid)):\n  valid_position = np.where(positions==valid[i])[0]\n  if i == 0:\n    valid_positions = valid_position\n  else:\n    valid_positions = np.append(valid_positions, valid_position)\n\nvalid_directories = train_images_directory_select[valid_positions]\nvalid_labels = labels[valid_positions]\n# features = all_features_45_smooth3[valid_positions]\n\ncapped_valid_labels = valid_labels[np.where((np.abs(valid_labels)<=cap) & (np.abs(valid_labels)>=0))[0]]                                # not include the focal distance larger than cap\ncapped_valid_directories = valid_directories[np.where((np.abs(valid_labels)<=cap) & (np.abs(valid_labels)>=0))[0]]\n# features = features[np.where((np.abs(valid_labels)<=cap) & (np.abs(valid_labels)>=0))[0]]\n\nprint(len(capped_valid_labels))\n```\n\n    WARNING:tensorflow:5 out of the last 9 calls to <function parse_images at 0x7fad29805c20> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for  more details.\n    WARNING:tensorflow:6 out of the last 11 calls to <function parse_images at 0x7fad29805c20> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for  more details.\n\n\n## Initiate our cnn model\n\n\n```python\nResnet50_transfer = tf.keras.applications.resnet50.ResNet50(\n    include_top=False,\n    weights=\"imagenet\",\n    # weights=None,\n    input_tensor=None,\n    input_shape=(imageSizeheight, imageSizewidth, 3), \n    pooling=None,\n)\n\nResnet50_transfer.trainable = True\n```\n\n    Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/resnet/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5\n    94773248/94765736 [==============================] - 1s 0us/step\n    94781440/94765736 [==============================] - 1s 0us/step\n\n\n\n```python\nResnet50_transfer.trainable = False\n\nsupervise_model = tf.keras.models.Sequential([\n    \n    Resnet50_transfer,\n    GlobalAveragePooling2D(),\n    # BatchNormalization(epsilon=0.1),\n    # Dense(64, activation='relu'),\n    # Dropout(0.5),\n    # BatchNormalization(epsilon=0.1),\n    # Dense(32, activation='relu'),\n    # Dropout(0.5),\n    # BatchNormalization(epsilon=0.1),\n    Dense(16, activation='relu'),\n    Dropout(0.5),\n    Dense(1)\n])\n```\n\n\n```python\n# adam = tf.keras.optimizers.Adam(learning_rate=0.001)\n# sgd = tf.keras.optimizers.SGD(learning_rate=0.001)\n# metrics = ['mae'\n#                 ]\n# supervise_model.compile(loss = 'mse', optimizer = adam, metrics = metrics)\n# supervise_model.summary()\n```\n\n    Model: \"sequential\"\n    _________________________________________________________________\n     Layer (type)                Output Shape              Param #   \n    =================================================================\n     resnet50 (Functional)       (None, 38, 60, 2048)      23587712  \n                                                                     \n     global_average_pooling2d (G  (None, 2048)             0         \n     lobalAveragePooling2D)                                          \n                                                                     \n     dense (Dense)               (None, 16)                32784     \n                                                                     \n     dropout (Dropout)           (None, 16)                0         \n                                                                     \n     dense_1 (Dense)             (None, 1)                 17        \n                                                                     \n    =================================================================\n    Total params: 23,620,513\n    Trainable params: 32,801\n    Non-trainable params: 23,587,712\n    _________________________________________________________________\n\n\n\n```python\n# cnn feature extraction in segments so as to avoid OOM problem, that we encountered with image set size larger than 1000.\nfeature_extractor = Model(supervise_model.input, supervise_model.layers[-4].output)\nn_segments = len(test_images_directory_select) // 500 + 1\nfor i in range(n_segments):\n  if i == 0:\n    test_ds = tf.data.Dataset.from_tensor_slices(test_images_directory_select[:(i + 1) * 500])\n    test_ds = (\n        test_ds\n        .map(parse_images, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n        .batch(training_batch_size\n              #  , drop_remainder=True\n              )\n        .prefetch(tf.data.experimental.AUTOTUNE)\n    )\n\n    features_test = feature_extractor.predict(test_ds)\n\n  else:\n    test_ds = tf.data.Dataset.from_tensor_slices(test_images_directory_select[i * 500 :(i + 1) * 500])\n    test_ds = (\n        test_ds\n        .map(parse_images, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n        .batch(training_batch_size\n              #  , drop_remainder=True\n              )\n        .prefetch(tf.data.experimental.AUTOTUNE)\n    )\n\n    features_test = np.append(features_test, feature_extractor.predict(test_ds), axis=0)\n# np.savez_compressed('performance_log/level2/feature_map.npz', feature_map=features)\n```\n\n\n```python\nn_segments = len(labels) // 500 + 1\nfor i in range(n_segments):\n  if i == 0:\n    train_ds = tf.data.Dataset.from_tensor_slices(train_images_directory_select[:(i + 1) * 500])\n    train_ds = (\n        train_ds\n        .map(parse_images, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n        .batch(training_batch_size\n              #  , drop_remainder=True\n              )\n        .prefetch(tf.data.experimental.AUTOTUNE)\n    )\n\n    features_train = feature_extractor.predict(train_ds)\n\n  else:\n    train_ds = tf.data.Dataset.from_tensor_slices(train_images_directory_select[i * 500 :(i + 1) * 500])\n    train_ds = (\n        train_ds\n        .map(parse_images, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n        .batch(training_batch_size\n              #  , drop_remainder=True\n              )\n        .prefetch(tf.data.experimental.AUTOTUNE)\n    )\n\n    features_train = np.append(features_train, feature_extractor.predict(train_ds), axis=0)\n```\n\n\n```python\nrf_regressor = randomforest(max_depth=8)\n# features_train, features_test, train_label, test_label = train_test_split(features, capped_valid_labels, test_size=0.2, random_state=42)\nrf_regressor.fit(features_train, labels)\ny_pred_rf = rf_regressor.predict(features_test)\n```\n\n\n```python\nprint('rf prediction r2_score = %f' % r2_score(y_pred_rf, test_label))\nprint('rf prediction mean_absolute_error = %f' % mean_absolute_error(y_pred_rf, test_label))\nplt.scatter(test_label, y_pred_rf)\nplt.plot(np.linspace(0, 50, 150), np.linspace(0, 50, 150), c='r')\nplt.xlabel('true_distance [$\\mu m$]')\nplt.ylabel('predicted_distance [$\\mu m$]')\n```\n\n\n```python\ndepth = np.array([8, 16])\nlr = np.linspace(0.01, 0.20, 21)\nperformance = np.zeros((len(depth), len(lr), 2))\n\n# features_train, features_test, train_label, test_label = train_test_split(features, capped_valid_labels, test_size=0.2, random_state=42)\n\nfor i in range(len(depth)):\n  for j in range(len(lr)):\n    xg_boost_regressor = xgb(max_depth=depth[i], learning_rate=lr[j], tree_method='gpu_hist', objective='reg:squarederror')         # don't go beyond max_depth of 16, session will crash due to OOM\n    xg_boost_regressor.fit(features_train, labels)\n    y_pred_xg = xg_boost_regressor.predict(features_test)\n    performance[i, j, 0] = r2_score(y_pred_xg, test_label)\n    performance[i, j, 1] = mean_absolute_error(y_pred_xg, test_label)\n```\n\n\n```python\nxg_boost_regressor = xgb(max_depth=depth[np.where(performance == np.min(performance[:, :, 1]))[0][0]], learning_rate=lr[np.where(performance == np.min(performance[:, :, 1]))[1][0]], tree_method='gpu_hist', objective='reg:squarederror')         # don't go beyond max_depth of 16, session will crash due to OOM\nxg_boost_regressor.fit(features_train, labels)\ny_pred_xg = xg_boost_regressor.predict(features_test)\nprint('rf prediction r2_score = %f' % r2_score(y_pred_xg, test_label))\nprint('rf prediction mean_absolute_error = %f' % mean_absolute_error(y_pred_xg, test_label))\nplt.scatter(test_label, y_pred_xg)\nplt.plot(np.linspace(0, 50, 150), np.linspace(0, 50, 150), c='r')\nplt.xlabel('true_distance [$\\mu m$]')\nplt.ylabel('predicted_distance [$\\mu m$]')\n```\n\n\n```python\nplt.scatter(lr[2:], performance[0, 2:, 1])\nplt.scatter(lr[2:], performance[1, 2:, 1])\n```\n\nkernel 63\nr2 scores    (mae are between 5 and 8)\n\n0.10: rf: 0.60, xgb: 0.85    ~ 132 images\n\n0.08: rf: 0.48, xgb: 0.70    ~ 230 images\n\n0.05: rf: 0.16, xgb: 0.60    ~ 532 images\n\n0.04: rf: 0.19, xgb: 0.55    ~ 884 images\n\nkernel 45\nr2 scores    (mae are between 5 and 8)\n\n0.10: rf: 0.69, xgb: 0.73    ~ 132 images\n\n0.08: rf: 0.67, xgb: 0.73    ~ 230 images\n\n0.05: rf: 0.44, xgb: 0.64    ~ 422 images\n\n0.04: rf: 0.44, xgb: 0.67    ~ 763 images\n\nkernel 33\nr2 scores    (mae are between 5 and 8)\n\n0.10: rf: 0.69, xgb: 0.73    ~ 132 images\n\n0.08: rf: 0.67, xgb: 0.73    ~ 230 images\n\n0.05: rf: 0.44, xgb: 0.64    ~ 422 images\n\n0.04: rf: 0.44, xgb: 0.67    ~ 763 images\n\n\n```python\nprint('xgboost prediction r2_score = %f' % r2_score(y_pred_xg, test_label))\nprint('xgboost prediction mean_absolute_error = %f' % mean_absolute_error(y_pred_xg, test_label))\nplt.scatter(test_label, y_pred_xg)\n# plt.plot(np.linspace(0, cap, 150), np.linspace(0, cap, 150), c='r')\nplt.xlabel('true_distance [$\\mu m$]')\nplt.ylabel('predicted_distance [$\\mu m$]')\n```\n", "meta": {"hexsha": "adaea03146f621675aa9202102441e41478c6737", "size": 125515, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/archive/training_level2.ipynb", "max_stars_repo_name": "evanmacbride/microscope-autofocus", "max_stars_repo_head_hexsha": "5e88dc8b498cc96c3eee0503111fdf67ef867b54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/archive/training_level2.ipynb", "max_issues_repo_name": "evanmacbride/microscope-autofocus", "max_issues_repo_head_hexsha": "5e88dc8b498cc96c3eee0503111fdf67ef867b54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/archive/training_level2.ipynb", "max_forks_repo_name": "evanmacbride/microscope-autofocus", "max_forks_repo_head_hexsha": "5e88dc8b498cc96c3eee0503111fdf67ef867b54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 125515.0, "max_line_length": 125515, "alphanum_fraction": 0.8380193602, "converted": true, "num_tokens": 6587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758367247085, "lm_q2_score": 0.06187598442618339, "lm_q1q2_score": 0.023133935450504347}}
{"text": "```python\nimport numpy as np\nimport sympy\nT = symbols('T')\nA = np.array([])\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "f7570acf61dbc66f1323075a4b18d976383d544e", "size": 1887, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Untitled.ipynb", "max_stars_repo_name": "KianPardoe/RocketPy", "max_stars_repo_head_hexsha": "d3d835fa7fd71fea636132616b2eea8917729875", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Untitled.ipynb", "max_issues_repo_name": "KianPardoe/RocketPy", "max_issues_repo_head_hexsha": "d3d835fa7fd71fea636132616b2eea8917729875", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Untitled.ipynb", "max_forks_repo_name": "KianPardoe/RocketPy", "max_forks_repo_head_hexsha": "d3d835fa7fd71fea636132616b2eea8917729875", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9830508475, "max_line_length": 626, "alphanum_fraction": 0.5590885003, "converted": true, "num_tokens": 30, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.048136769068338116, "lm_q1q2_score": 0.023128691167452482}}
{"text": "--- \nReplication Project for Microeconometrics course | Summer 2021, M.Sc. Economics, Bonn University | [Aysu Avc\u0131](https://github.com/aysuavci)\n\n# Replication of Zimmermann (2020) <a class=\"tocSkip\">   \n---\n\nThis notebook contains the replication of the following study:\n\n> [Zimmermann, F. (2020). The Dynamics of Motivated Beliefs. American Economic Review, 110(2), 337\u2013363](https://www.aeaweb.org/articles?id=10.1257/aer.20180728).\n\n\n##### Notes:\n\n* I try to remain true to the original naming of the variables, however, I renamed all of the figures and tables according to sections in this notebook to avoid any confusions that might arise due to having two replications.\n* For convenience, I decided to keep some of the coding in the notebook which I have seen essential for understanding the steps taken in replication. \n\n* The responsitory can be downloaded from [here](https://github.com/OpenSourceEconomics/ose-data-science-course-project-aysuavci), for the best viewing.\n\n## **Table of Contents**\n* [Introduction](#sec1)\n* [Background for the Experiment and Hypothesis](#sec2)\n* [Experiment Design](#sec3)\n* [Identification](#sec4)\n* [Empirical Strategy](#sec5)\n* [Replication of Zimmermann (2020)](#sec6)\n    * [Main Results](#sec6_1)\n        * [Data & Descriptive Statistics](#sec6_1_1)\n        * [Belief Adjustment Distribution\u00b6](#sec6_1_2)\n        * [Belief Adjustment Distribution & Test performances](#sec6_1_3)\n        * [Regression Outputs](#sec6_1_4)\n    * [Robustness Checks](#sec6_2)\n        * [Appendix A.4 - Alternative Definition of Positive/Negative Feedback](#sec6_2_1)\n        * [Appendix A.6 - Updating in the Short-Run](#sec6_2_2)\n        * [Appendix A.7 - No Feedback Condition](#sec6_2_3)\n        * [Appendix A.8 - Figures Bayesian Posteriors](#sec6_2_4)\n* [Extension](#sec7)\n    * [Replication of Eil and Rao (2011)](#sec7_1)\n        * [Introduction](#sec7_1_1)\n        * [Experiment Design](#sec7_1_2)\n        * [Emprical Strategy](#sec7_1_3)\n        * [Replication](#sec7_1_4)\n        * [Comparison with Zimmermann (2020)](#sec7_1_5)\n    * [Further Extension](#sec7_2)\n        * [Alternative Data Visualization](#sec7_2_1)\n        * [Further Analysis with No Feedback Group](#sec7_2_2)\n            * [Emprical Strategy](#sec7_2_2_1)\n            * [Estimation](#sec7_2_2_2)              \n* [Conclusion](#sec8)\n* [References](#sec9)\n\n\n```python\n%matplotlib inline\n!pip install stargazer\n!pip install matplotlib\n!pip install -U matplotlib\nimport numpy as np\nimport pandas as pd\nimport pandas.io.formats.style\nimport seaborn as sns\nimport statsmodels as sm\nimport statsmodels.formula.api as smf\nimport statsmodels.api as sm_api\nimport matplotlib as plt\nfrom IPython.display import HTML\nfrom stargazer.stargazer import Stargazer, LineLocation\nfrom statsmodels.iolib.summary2 import summary_col\n```\n\n\n```python\nfrom auxiliary.auxiliary_tools import *\nfrom auxiliary.auxiliary_plots import *\nfrom auxiliary.auxiliary_tables import *\n```\n\n---\n# 1.Introduction <a class=\"anchor\" id=\"sec1\"></a>\n---\n\nThe study of Zimmermann(2020) is a lab experiment aiming to examine how motivated beliefs held by individuals continues to be sustained after receiving positive or negative feedback.\nThe study can be divided into 3 parts:\n\n1. The first part of the study-named \u201c**Motivated Belief Dynamics**\u201d in the paper- is the main study for investigating the causality between different types of feedback (positive or negative) received and reconstruction of belief patterns depending on the elicitation time (directly or 1 month) of the belief after the experiment. \n2. The second part of the study-named \u201c**The Role of Memory**\u201d in the paper- investigates the asymmetry in the accuracy of feedback recall and also recall of IQ test in general that they solve as a part of the experiment. \n3. The final part of the study-named \u201c**The Trade-Off between Motivated and Accurate Belief**\u201d in the paper- that questions whether incentivizing for recall accuracy could mitigate the motivated reasoning that participants employ.\n\nIn this project notebook, the main study-first part- will be replicated; the part where Zimmermann (2020) used also **difference-in-difference (DID) models** for their estimations. In the next section (Section 2), I will give a quick literature background for the experiment and also specify the researcher\u2019s hypothesis. In Section 3, I will explain the relevant parts of the experimental design and introduce treatment groups and variables for convenience. The identification part (Section 4) will explain the causality studied by Zimmermann (2020) and the empirical strategy part (Section 5) will present the established models for estimations. Section 6 is the replication part where the figures and tables from the main study and relevant Appendix parts are presented. The extension of this project is located in Section 7 where I replicate the study of Eil and Rao (2022)  as well as including some data visualization and further analysis. Finally, Section 8 includes my concluding remarks.\n\n---\n# 2. Background for the Experiment and Hypothesis <a class=\"anchor\" id=\"sec2\"></a>\n---\nPersonally, I have always been interested in the question of how individual beliefs are formed and sustained or changed over time. In the neoclassical economics framework, any changes in beliefs follow Bayes Rule\u2019s since it is accepted that all agents are rational and unbiased. However, many studies in the literature of motivated beliefs showed that individuals deviate from these Bayesian predictions and manipulate their beliefs in a self-serving way; and some studies like Eil and Rao 2011 or Zimmermann 2020 tried to address the asymmetry in belief updating as well. I see the study of Zimmermann (2020) as an influential study to study motivated belief dynamics because of the experiment design that is been employed. The design of Zimmermann (2020) allows comparing the belief updating across signals received (asymmetry) and also across time (short-run and long-run updating) by employing control and various treatment groups.\n \n**Main Hypothesis:** *Individuals\u2019 engagement with belief updating follows an asymmetric pattern, putting more weight on positive signals and less on the negative signals, which is more pronounced for long-term since negative signal\u2019s effects fade over time.*\n\n\nUsing DID models for analysis is suitable for this study because, first of all, it is impossible to make one experiment subject expose to two different treatments while keeping everything constant in this experiment to examine individual-level effects. Secondly, since this is a randomly assigned experiment we can assume subjects do not differ between the control group and treatment groups. Also, between the control group and treatment group Zimmermann (2020) made sure to keep everything constant and only made the feedback condition vary. Also, DID was easily implemented as an interaction term between time treatment and feedback dummy allowing for causal inferences on belief dynamics in line with the researcher\u2019s goal and with the group of interest which is the individuals who received a negative signal and in the treatment group 1 month and their differences compared to other groups in belief updating. In addition to these, employing DID models allowed Zimmermann (2020) to add the fixed rank effects interacted with treatment which serve as a control for the possible characteristic differences due to rank groups between treatments. Also, having a control condition for 1-month treatment which serve as a robustness check for potential beliefs changes due to time trends that may exist in the absence of feedback.\n\n---\n# 3. Experimental Design <a class=\"anchor\" id=\"sec3\"></a>\n---\n1. Subjects completed an IQ test where they need to solve 10 Raven matrices.\n2. Subjects were randomly assigned to groups of 10.\n3. Subjects were asked to estimate their belief about the likelihood of being ranked in the upper half of their group in terms of a percentage point. Full probability distributions for every possible rank is also elicited.\n4. Subjects were given noisy but true information about their rank by randomly selecting 3 participants from their group and telling them whether they were rank higher or lower than these 3 participants. If a subject is told that they ranked higher than 2 or 3 participants in their group, the subject is considered to be in the positive feedback group. They considered being in the negative feedback group if otherwise.\n5. After receiving the feedbacks, subjects are divided into two treatment groups randomly: `condifence_direct` and `confidence_1monthlater`.\n6. In the `confidence_1monthlater` treatment, subjects are asked to elicit their beliefs 1 month later; and in the `condifence_direct` treatment, group subjects are asked to elicit their beliefs after the feedback. `condifence_direct`has also two subgroups: `condifence_direct_immediate` and `condifence_direct_15minutelater`.\n\n\n**Main Variables**\n\n|Treatment groups|Feedback types|Outcomes|Other variables|\n|---|---|---|---|\n|`confidence_1monthlater`|Positive|Belief adjustment|Bayesian belief adjustment||\n|`condifence_direct_immediate`|Negative||rank|\n|`condifence_direct_15minutelater`|||\n|`no_feedback`|||\n\n\n---\n# 4. Identification <a class=\"anchor\" id=\"sec4\"></a>\n--- \n\nThe first part of the experiment is dedicated to investigating the causality between the effect of feedback and belief adjustments of participants that are in two different treatment groups that vary depending on time: _CondifenceDirect_ and _Condifence1month_. The causality is established by two key components in the experiment. First of all, Zimmermann(2020) elicit peoples prior beliefs about their probability of ranking in the upper half of the group and then they elicited again after participants received the feedback. So, for each participant, they had a clear measure of belief updating which is possibly caused by the feedback and in line with the type of feedback. The second and the most important component of the experiment, that ensured causal identification, is the noisy feedback component. In this experiment rather than randomly assigning a subject into a negative or positive feedback group directly, Zimmermann(2020) randomly choose 3 other participants within the subject\u2019s group to compare their rank and provide them with 3 comparisons. In this way, subjects indeed received true feedback but a noisy one. So, it is possible for two subjects with the same rank to receive different types of feedback. By adopting such an experimental design, Zimmermann(2020) ensured that potential asymmetries in the belief dynamics cannot be explained by the individual difference between participants. \n\nIn addition to investigating the causal relationship between belief dynamics and feedback, another goal of the experiment is to observe the effect of time on this relationship. For that, Zimmermann(2020) assigned participants randomly to two groups: Confidence1month and CondifenceDirect. ConfidenceDirect is also divided into two subgroups(immediate and 15 minutes later belief elicitation) to investigate the possible short-term dynamics in belief adjustment, however, that part of the study will not be covered in this replication.\n\n\n\n---\n# 5. Empirical Strategy <a class=\"anchor\" id=\"sec5\"></a>\n---\n\n\nIn the study, the belief adjustment is defined as the difference between the elicited belief after the feedback and the belief before the feedback, formally\n\n\\begin{equation}\nPr(upperhalf)^{post}_{i} - Pr(upperhalf)^{prior}_{i}\n\\end{equation}\n\nwhere $Pr(upperhalf)_{i}$ represents the subject ${i}$'s given probability of being in the upperhalf of the group.\n\nTo compare belief adjustments between positive and negative feedbacks, a normalized version of the belief adjustment norm is also formed as below:\n\n\n$$\nbeliefadjustmentnorm_i = \\left\\{\n    \\begin{array}\\\\\n        Pr(upperhalf)^{post}_{i} - Pr(upperhalf)^{prior}_{i} & \\mbox{if } \\ feedback \\ positive \\\\\n        (-1) x (Pr(upperhalf)^{post}_{i} - Pr(upperhalf)^{prior}_{i}) & \\mbox{if } \\ feedback \\ negative \\\\\n    \\end{array}\n\\right.\n$$\n\n\nThe difference-in-difference models, formally in the form of \n\n\\begin{equation}\nbeliefadjustmentnorm_i = \\alpha + \\beta feedback_i + \\gamma T_i + \\delta I_i + X_i \\gamma + \\epsilon_i\n\\end{equation}\n\nare estimated for the purpose of establishing dynamic belief patterns. $feedback_i$ is the dummy variable for feedback and $T_i$ is the type of treatment. $I_i$ is for the interation term that is a generated dummy for the interest group, interest group being subjects who are in the `confidence_1monthlater`and received a negative feedback. In other words, if subjects were in `confidence_1monthlater` treatment and received a negative information; treatment dummy, feedback dummy and interaction term are all equal to 1. In this case, parameter $\\delta$ is therefore captures the belief dynamics. In other words, if the subject is in `confidence_1monthlater` treatment and received a negative information; treatment dummy, feedback dummy and interaction term are equal to 1.\n\nIn order to form a causal inference, Zimmermann (2020) control for rank and IQ test scores; these variables are captured by $X_i$, set of control variables. As another control variable, Bayesian belief adjustments are also used for some specifications. Zimmermann (2020) calculated Bayesian predictions, using individuals full prior probability distribution and the feedback type that they received. The Bayesian belief adjustment is then, produced in the same way as the belief adjustment\n\n\\begin{equation}\nPr(upperhalf)^{postBayes}_{i} - Pr(upperhalf)^{prior}_{i}\n\\end{equation}\n\nwhere $Pr(upperhalf)^{postBayes}_{i}$ is the calculated Bayesian prediction for the subject $i$.\n\nAnother specification within the study is adding the rank fixed effects interacted with treatment. In this way, Zimmermann (2020) was able to control the differentiation of possible different characteristics due to ranking between treatment groups.\n\nZimmermann (2020) choose to perform ordinary least square (OLS) estimates with type HC1 heteroscedasticity robust covariance. Most of the main results are produced with this linear regression and I will use this type of regression in the table replications.\n\n---\n# 6. Replication of Zimmermann (2020) <a class=\"anchor\" id=\"sec6\"></a>\n---\n## 6.1. Main Results <a class=\"anchor\" id=\"sec6_1\"></a>\n### 6.1.1 Data & Descriptive Statistics <a class=\"anchor\" id=\"sec6_1_1\"></a>\n\n\n```python\ndf = pd.read_stata('data/data.dta')\n```\n\n\n```python\n#Adjustments for better viewing\npd.set_option(\"display.max.columns\", None)\npd.set_option(\"display.precision\", 7)\npd.set_option(\"display.max.rows\", 30)\n```\n\n\n```python\n#Viewing data\ndf.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>treatment</th>\n      <th>rscore</th>\n      <th>performance1</th>\n      <th>performance2</th>\n      <th>performance3</th>\n      <th>performance4</th>\n      <th>performance5</th>\n      <th>performance6</th>\n      <th>performance7</th>\n      <th>performance8</th>\n      <th>performance9</th>\n      <th>wspt</th>\n      <th>donation</th>\n      <th>prior_median</th>\n      <th>prior_1</th>\n      <th>prior_2</th>\n      <th>prior_3</th>\n      <th>prior_4</th>\n      <th>prior_5</th>\n      <th>prior_6</th>\n      <th>prior_7</th>\n      <th>prior_8</th>\n      <th>prior_9</th>\n      <th>prior_10</th>\n      <th>rank</th>\n      <th>pos_comparisons</th>\n      <th>neg_comparisons</th>\n      <th>repeat_neg_comparisons</th>\n      <th>repeat_pos_comparisons</th>\n      <th>risk_investment</th>\n      <th>recall_neg_comparisons</th>\n      <th>recall_pos_comparisons</th>\n      <th>big5_1</th>\n      <th>big5_2</th>\n      <th>big5_3</th>\n      <th>big5_4</th>\n      <th>big5_5</th>\n      <th>big5_6</th>\n      <th>big5_7</th>\n      <th>big5_8</th>\n      <th>big5_9</th>\n      <th>big5_10</th>\n      <th>big5_11</th>\n      <th>big5_12</th>\n      <th>big5_13</th>\n      <th>big5_14</th>\n      <th>big5_15</th>\n      <th>gender</th>\n      <th>field_of_study</th>\n      <th>student</th>\n      <th>posterior_median</th>\n      <th>recallfeedback</th>\n      <th>qualtrics</th>\n      <th>recall_part_IQtest</th>\n      <th>recall_part_feedback</th>\n      <th>recall_parts_nonIQ</th>\n      <th>pricelist1</th>\n      <th>pricelist2</th>\n      <th>pricelist3</th>\n      <th>pricelist4</th>\n      <th>pricelist5</th>\n      <th>pricelist6</th>\n      <th>pricelist7</th>\n      <th>pricelist8</th>\n      <th>pricelist9</th>\n      <th>pricelist10</th>\n      <th>pricelist11</th>\n      <th>pricelist12</th>\n      <th>pricelist13</th>\n      <th>pricelist14</th>\n      <th>pricelist15</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>belief_announcement</td>\n      <td>4</td>\n      <td>1</td>\n      <td>3</td>\n      <td>4</td>\n      <td>4</td>\n      <td>5</td>\n      <td>5</td>\n      <td>5</td>\n      <td>6</td>\n      <td>8</td>\n      <td>6</td>\n      <td>1</td>\n      <td>53</td>\n      <td>2</td>\n      <td>4</td>\n      <td>9</td>\n      <td>14</td>\n      <td>24</td>\n      <td>16</td>\n      <td>13</td>\n      <td>9</td>\n      <td>7</td>\n      <td>2</td>\n      <td>7</td>\n      <td>2.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>2.0</td>\n      <td>80</td>\n      <td>1.0</td>\n      <td>2.0</td>\n      <td>1</td>\n      <td>2</td>\n      <td>4</td>\n      <td>3</td>\n      <td>2</td>\n      <td>4</td>\n      <td>3</td>\n      <td>4</td>\n      <td>2</td>\n      <td>5</td>\n      <td>3</td>\n      <td>4</td>\n      <td>3</td>\n      <td>4</td>\n      <td>4</td>\n      <td>0</td>\n      <td>Geographie</td>\n      <td>1</td>\n      <td>68.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>belief_announcement</td>\n      <td>6</td>\n      <td>3</td>\n      <td>4</td>\n      <td>5</td>\n      <td>5</td>\n      <td>6</td>\n      <td>6</td>\n      <td>7</td>\n      <td>8</td>\n      <td>9</td>\n      <td>7</td>\n      <td>5</td>\n      <td>70</td>\n      <td>10</td>\n      <td>10</td>\n      <td>10</td>\n      <td>20</td>\n      <td>20</td>\n      <td>10</td>\n      <td>5</td>\n      <td>5</td>\n      <td>5</td>\n      <td>5</td>\n      <td>4</td>\n      <td>2.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>2.0</td>\n      <td>150</td>\n      <td>1.0</td>\n      <td>2.0</td>\n      <td>2</td>\n      <td>2</td>\n      <td>6</td>\n      <td>2</td>\n      <td>5</td>\n      <td>2</td>\n      <td>7</td>\n      <td>2</td>\n      <td>2</td>\n      <td>7</td>\n      <td>3</td>\n      <td>6</td>\n      <td>2</td>\n      <td>2</td>\n      <td>3</td>\n      <td>1</td>\n      <td>psychologie</td>\n      <td>1</td>\n      <td>60.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>belief_announcement</td>\n      <td>8</td>\n      <td>4</td>\n      <td>6</td>\n      <td>7</td>\n      <td>7</td>\n      <td>7</td>\n      <td>8</td>\n      <td>8</td>\n      <td>9</td>\n      <td>10</td>\n      <td>5</td>\n      <td>3</td>\n      <td>85</td>\n      <td>1</td>\n      <td>4</td>\n      <td>30</td>\n      <td>30</td>\n      <td>20</td>\n      <td>9</td>\n      <td>2</td>\n      <td>2</td>\n      <td>1</td>\n      <td>1</td>\n      <td>3</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>2.0</td>\n      <td>80</td>\n      <td>0.0</td>\n      <td>2.0</td>\n      <td>3</td>\n      <td>5</td>\n      <td>6</td>\n      <td>3</td>\n      <td>2</td>\n      <td>3</td>\n      <td>4</td>\n      <td>4</td>\n      <td>2</td>\n      <td>2</td>\n      <td>3</td>\n      <td>2</td>\n      <td>2</td>\n      <td>3</td>\n      <td>5</td>\n      <td>1</td>\n      <td>Medienwissenschaft</td>\n      <td>1</td>\n      <td>85.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>belief_announcement</td>\n      <td>5</td>\n      <td>4</td>\n      <td>6</td>\n      <td>7</td>\n      <td>7</td>\n      <td>7</td>\n      <td>8</td>\n      <td>8</td>\n      <td>9</td>\n      <td>10</td>\n      <td>5</td>\n      <td>0</td>\n      <td>80</td>\n      <td>3</td>\n      <td>6</td>\n      <td>6</td>\n      <td>25</td>\n      <td>40</td>\n      <td>5</td>\n      <td>5</td>\n      <td>4</td>\n      <td>3</td>\n      <td>3</td>\n      <td>9</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>150</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>2</td>\n      <td>7</td>\n      <td>3</td>\n      <td>2</td>\n      <td>2</td>\n      <td>6</td>\n      <td>4</td>\n      <td>2</td>\n      <td>4</td>\n      <td>1</td>\n      <td>4</td>\n      <td>1</td>\n      <td>2</td>\n      <td>3</td>\n      <td>0</td>\n      <td>Lebensmittelchemie</td>\n      <td>1</td>\n      <td>45.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>belief_announcement</td>\n      <td>5</td>\n      <td>1</td>\n      <td>3</td>\n      <td>4</td>\n      <td>4</td>\n      <td>5</td>\n      <td>5</td>\n      <td>5</td>\n      <td>6</td>\n      <td>8</td>\n      <td>3</td>\n      <td>0</td>\n      <td>25</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>25</td>\n      <td>5</td>\n      <td>5</td>\n      <td>20</td>\n      <td>20</td>\n      <td>25</td>\n      <td>4</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>100</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>4</td>\n      <td>4</td>\n      <td>7</td>\n      <td>3</td>\n      <td>2</td>\n      <td>1</td>\n      <td>7</td>\n      <td>2</td>\n      <td>6</td>\n      <td>3</td>\n      <td>2</td>\n      <td>4</td>\n      <td>1</td>\n      <td>1</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Geographie</td>\n      <td>1</td>\n      <td>70.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n#Renaming treatgroup for easier coding\ntg_conditions = [\n    (df['treatment'] == 'belief_announcement'),\n    (df['treatment'] == 'confidence_1monthlater'),\n    (df['treatment'] == 'confidence_direct_15minuteslater'),\n    (df['treatment'] == 'confidence_direct_immediate'),\n    (df['treatment'] == 'memory'),\n    (df['treatment'] == 'memory_high'),\n    (df['treatment'] == 'nofeedback'),\n    (df['treatment'] == 'tournament_announcement'),\n]\ntg_values = [1, 2, 3, 4, 5, 6, 7, 8]\ndf['treatgroup'] = np.select(tg_conditions, tg_values)\n```\n\nThroughout this study feedback groups will be addressed using the dummy variable `dummynews_goodbad`. As it is mentioned above, if a subject received more than 2 positive comparisons they are considered to be in the positive feedback group; if else they are considered to be in the negative feedback group.\n\n\n```python\n#Creating dummy variable for good/bad news (if good = 0, if bad = 1)\ndf[\"dummynews_goodbad\"] = np.nan\ndf.loc[(df['pos_comparisons'] == 2) | (df['pos_comparisons'] == 3), 'dummynews_goodbad'] = 0\ndf.loc[(df['pos_comparisons'] == 0) | (df['pos_comparisons'] == 1), 'dummynews_goodbad'] = 1\n```\n\n\n```python\n#Belief adjustment\ndf[\"beliefadjustment\"] = df[\"posterior_median\"] - df[\"prior_median\"]\n#Normalized belief adjustment\ndf[\"beliefadjustment_normalized\"] = np.nan\ndf.loc[df['dummynews_goodbad'] == 0, 'beliefadjustment_normalized'] = df['beliefadjustment']\ndf.loc[df['dummynews_goodbad'] == 1, 'beliefadjustment_normalized'] = df['beliefadjustment']*-1\n```\n\n### 6.1.2 Belief Adjustment Distribution <a class=\"anchor\" id=\"sec6_1_2\"></a>\n\n\n```python\nMain_Figure1(df)\n```\n\nFigure 1 is an easy way to view the belief adjustments of the subjects, even though, they aren't enough for causal inference. As it is observable from Panel A. subjects adjusted their beliefs in line with the feedback they have received. For instance, in the positive feedback group, we see the accumulation of observations between 0 and +50 while an opposite pattern is observable for the negative feedback group.\n\nIn Panel B. we see that for the individuals who have received positive feedback, the pattern observe is not so much different from the pattern in Panel A. However, the graph significantly changes for the negative feedback when subjects elicit their beliefs 1 month after the feedback.\n\n### 6.1.3 Belief Adjustment Distribution  & Test performances <a class=\"anchor\" id=\"sec6_1_3\"></a>\n\n**Calculating Bayesian Predictions**\n\n\n```python\n#Bayesian predictions\nget_Bayesian_predictions(df)\n```\n\n\n```python\n#Calculating Bayesian Posterior Median Beliefs\ndf[\"posterior_median_bayes\"] = (df[\"post_1\"] + df[\"post_2\"] + df[\"post_3\"] + df[\"post_4\"] + df[\"post_5\"])*100\n```\n\n\n```python\n##Bayesian predictions for belief adjustment\ndf[\"beliefadjustment_bayes\"] = df[\"posterior_median_bayes\"] - df[\"prior_median\"]\n\n#Normalization of Bayesian predictions\ndf[\"beliefadjustment_bayes_norm\"] = np.nan\ndf.loc[df['dummynews_goodbad'] == 0, 'beliefadjustment_bayes_norm'] = df['beliefadjustment_bayes']\ndf.loc[df['dummynews_goodbad'] == 1, 'beliefadjustment_bayes_norm'] = df['beliefadjustment_bayes']*-1\n```\n\nThere are two sub treatment groups in the immediate treatment: confidence_direct_15minuteslater' and 'confidence_direct_immediate'. Zimmermann(2020) made this differentiation for a robustness check to see whether there would be a difference between eliciting beliefs immediately after feedback or 15 minutes later. However, the main results derived from the comparison between 1-month treatment and pooled treatment which combines 15 minutes later and immediate treatment. So, a dummy is created for further analysis; with 1 indicating treatment 1 month and 0 indicating pooled direct treatment.\n\n\n```python\n#Generate dummy for direct treatment and 1 month treatment\ndf[\"dummytreat_direct1month\"] = np.nan\ndf.loc[(df['treatgroup'] == 3) | (df['treatgroup'] == 4), 'dummytreat_direct1month'] = 0\ndf.loc[df['treatgroup'] == 2, 'dummytreat_direct1month'] = 1\n```\n\n\n```python\n#Grouping IQ test scores\ndf[\"test_1\"] = np.nan\ndf.loc[(df['rscore'] == 0) | (df['rscore'] == 1) | (df['rscore'] == 2) | (df['rscore'] == 3) | (df['rscore'] == 4), 'test_1'] = 1\ndf.loc[(df['rscore'] == 5), 'test_1'] = 2\ndf.loc[(df['rscore'] == 6), 'test_1'] = 3\ndf.loc[(df['rscore'] == 7) | (df['rscore'] == 8) | (df['rscore'] == 9) | (df['rscore'] == 10), 'test_1'] = 4\n```\n\n\n```python\n#Average prior belief\ndf['prior_av'] = df.groupby(['test_1', 'dummytreat_direct1month'])[\"prior_median\"].transform('mean')\n```\n\n\n```python\n#Average posterior belief if feedback is positive\ndf['post_av_pos'] = df[df[\"dummynews_goodbad\"] == 0].groupby(['test_1', 'dummytreat_direct1month'])[\"posterior_median\"].transform('mean')\n```\n\n\n```python\n#Average posterior belief if feedback is negative\ndf['post_av_neg'] = df[df[\"dummynews_goodbad\"] == 1].groupby(['test_1', 'dummytreat_direct1month'])[\"posterior_median\"].transform('mean')\n```\n\n\n```python\nMain_Figure2(df)\n```\n\nFigure 2 plots the individuals' prior and posterior belief of being in the upper half of their group for differents levels in test performances. Test performances are grouped as 1, 2, 3 and 4; with 1 being the lowest score group. Also, posteriors are plotted with two different lines.\n\nIt is easy to see that in Panel A. ConfidenceDirect, subject's posterior beliefs visibly differ from their prior beliefs in line with the feedback they received. However, in Panel B, the posterior beliefs of subjects that received negative feedback are visibly closer to the prior beliefs.\n\nCompared to the first graph, here causal inference is made possible by grouping individuals according to their test scores.\n\nThese figures are also a great way to observe ex-ante overconfident-average priors lie consistently above 50 percent- which can be theoretically explained by Bayesian updating (see. Beno\u00eet and Dubra, 2011) and also visible in the figures from the study of Zimmermann (2020).\n\n### 6.1.4. Regression Outputs <a class=\"anchor\" id=\"sec6_1_4\"></a>\n\nIn the study, Zimmermann (2020) perform 8 OLS estimations(see in Table 1) with type HC1 heteroscedasticity robust covariance. :<br>\n(1) Regressing $y_i$ (normalized belief adjustment) on $T_i$ (treatment type) in case of positive feedback<br>\n(2) Same as (1) but controling for $X_i$ (rank and normalized bayesian belief adjustment)<br>\n(3) Regressing $y_i$ (normalized belief adjustment) on $T_i$ (treatment type) in case of negative feedback<br>\n(4) Same as (3) but controling for $X_i$ (rank and normalized bayesian belief adjustment)<br>\n(5) Regressing $y_i$ (normalized belief adjustment) on $T_i$ (treatment type), $feedback_i$ (feedback type) and $I_i$ (interaction term indicating whether individual is in the interest group or not)<br>\n(6) Same as (5) but controling for $X_i$ (rank and normalized bayesian belief adjustment)<br>\n(7) Same as (5) but including rank fixed effects with their interaction with treatment<br>\n(8) Same as (7) but controling for $X_i$ (normalized bayesian belief adjustment)<br>\n\n\n```python\ndf_good = pd.DataFrame({\"beliefadjustment_normalized\": df[df[\"dummynews_goodbad\"] == 0]['beliefadjustment_normalized'], \"dummytreat_direct1month\": df[df[\"dummynews_goodbad\"] == 0]['dummytreat_direct1month'], \"rank\": df[df[\"dummynews_goodbad\"] == 0]['rank'], \"beliefadjustment_bayes_norm\": df[df[\"dummynews_goodbad\"] == 0]['beliefadjustment_bayes_norm']})\n#(1)\nmodel_ols = smf.ols(formula=\"beliefadjustment_normalized ~ dummytreat_direct1month\", data=df_good)\nreg_1 = model_ols.fit(cov_type='HC1')\n#(2)\nmodel_ols = smf.ols(formula=\"beliefadjustment_normalized ~ dummytreat_direct1month + rank + beliefadjustment_bayes_norm\", data=df_good)\nreg_2 = model_ols.fit(cov_type='HC1')\n```\n\n\n```python\ndf_bad = pd.DataFrame({\"beliefadjustment_normalized\": df[df[\"dummynews_goodbad\"] == 1]['beliefadjustment_normalized'], \"dummytreat_direct1month\": df[df[\"dummynews_goodbad\"] == 1]['dummytreat_direct1month'], \"rank\": df[df[\"dummynews_goodbad\"] == 1]['rank'], \"beliefadjustment_bayes_norm\": df[df[\"dummynews_goodbad\"] == 1]['beliefadjustment_bayes_norm']})\n#(3)\nmodel_ols = smf.ols(formula=\"beliefadjustment_normalized ~ dummytreat_direct1month\", data=df_bad)\nreg_3 = model_ols.fit(cov_type='HC1')\n#(4)\nmodel_ols = smf.ols(formula=\"beliefadjustment_normalized ~ dummytreat_direct1month + rank + beliefadjustment_bayes_norm\", data=df_bad)\nreg_4 = model_ols.fit(cov_type='HC1')\n```\n\nNext regressions are DID models, therefore interaction term for our interest group is added.\n\n\n```python\n#Generating interaction term\ndf[\"interact_direct1month\"] = df[\"dummytreat_direct1month\"]*df[\"dummynews_goodbad\"]\n```\n\n\n```python\n#(5)\nmodel_ols = smf.ols(formula= \"beliefadjustment_normalized ~ dummytreat_direct1month + dummynews_goodbad + interact_direct1month\", data=df)\nreg_5 = model_ols.fit(cov_type='HC1')\n#(6)\nmodel_ols = smf.ols(formula= \"beliefadjustment_normalized ~ dummytreat_direct1month + dummynews_goodbad + rank + interact_direct1month + beliefadjustment_bayes_norm\", data=df)\nreg_6 = model_ols.fit(cov_type='HC1')\n```\n\nNext spesifications are with rank fixed effects to include their interaction with treatment. So rank dummies are generated and added to the regression as well as their interaction term: `rankdummy`$_i$ *`dummytreat_direct1month`.\n\n\n```python\n#Rank dummies\nget_rank_dummies(df)\n```\n\n\n```python\n#Intereaction term: Rank dummy*Treatment dummy\nget_rank_interation_term(df)\n```\n\n\n```python\n#(7)\nmodel_ols = smf.ols(formula= \"beliefadjustment_normalized ~ dummytreat_direct1month + dummynews_goodbad + interact_direct1month + rankdummy1 + rankdummy2 + rankdummy3 + rankdummy4 + rankdummy5 + rankdummy6 + rankdummy7 + rankdummy8 + rankdummy9 + rankdummy1_interact + rankdummy2_interact + rankdummy3_interact + rankdummy4_interact + rankdummy5_interact + rankdummy6_interact + rankdummy7_interact + rankdummy8_interact + rankdummy9_interact\", data=df)\nreg_7 = model_ols.fit(cov_type='HC1')\n#(8)\nmodel_ols = smf.ols(formula= \"beliefadjustment_normalized ~ dummytreat_direct1month + dummynews_goodbad + interact_direct1month + beliefadjustment_bayes_norm + rankdummy1 + rankdummy2 + rankdummy3 + rankdummy4 + rankdummy5 + rankdummy6 + rankdummy7 + rankdummy8 + rankdummy9 + rankdummy1_interact + rankdummy2_interact + rankdummy3_interact + rankdummy4_interact + rankdummy5_interact + rankdummy6_interact + rankdummy7_interact + rankdummy8_interact + rankdummy9_interact\", data=df)\nreg_8 = model_ols.fit(cov_type='HC1')\n```\n\n\n```python\nMain_Table_1(df)\n```\n\n\n\n\nTable 1 - Belief Adjustment: Direct versus One Month Later<br><table style=\"text-align:center\"><tr><td colspan=\"9\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align:left\"></td><td colspan=\"8\"><em>Normalized Belief Adjustment - beliefadjustment_normalized</em></td></tr><tr><td style=\"text-align:left\"></td><tr><td></td><td colspan=\"2\">Positive Information</td><td colspan=\"2\">Negative Information</td><td colspan=\"2\">Difference-in-difference</td><td colspan=\"2\">Difference-in-difference with rank fixed effects</td></tr><tr><td style=\"text-align:left\"></td><td>(1)</td><td>(2)</td><td>(3)</td><td>(4)</td><td>(5)</td><td>(6)</td><td>(7)</td><td>(8)</td></tr><tr><td colspan=\"9\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align:left\">Intercept</td><td>10.812<sup>***</sup></td><td>-6.705<sup>**</sup></td><td>14.247<sup>***</sup></td><td>15.219<sup>***</sup></td><td>10.812<sup>***</sup></td><td>4.588<sup>**</sup></td><td>9.237<sup>**</sup></td><td>-2.317<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td>(1.604)</td><td>(2.762)</td><td>(1.687)</td><td>(5.600)</td><td>(1.604)</td><td>(2.217)</td><td>(4.421)</td><td>(4.209)</td></tr><tr><td style=\"text-align:left\">beliefadjustment_bayes_norm</td><td></td><td>0.674<sup>***</sup></td><td></td><td>0.252<sup>***</sup></td><td></td><td>0.391<sup>***</sup></td><td></td><td>0.431<sup>***</sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td>(0.071)</td><td></td><td>(0.081)</td><td></td><td>(0.055)</td><td></td><td>(0.061)</td></tr><tr><td style=\"text-align:left\">dummynews_goodbad</td><td></td><td></td><td></td><td></td><td>3.436<sup></sup></td><td>2.403<sup></sup></td><td>5.319<sup></sup></td><td>3.558<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td>(2.328)</td><td>(2.847)</td><td>(3.298)</td><td>(2.932)</td></tr><tr><td style=\"text-align:left\">dummytreat_direct1month</td><td>0.301<sup></sup></td><td>1.504<sup></sup></td><td>-10.411<sup>***</sup></td><td>-11.006<sup>***</sup></td><td>0.301<sup></sup></td><td>0.392<sup></sup></td><td>-0.245<sup></sup></td><td>-1.835<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td>(3.564)</td><td>(3.062)</td><td>(2.540)</td><td>(2.540)</td><td>(3.564)</td><td>(3.238)</td><td>(8.909)</td><td>(8.193)</td></tr><tr><td style=\"text-align:left\">interact_direct1month</td><td></td><td></td><td></td><td></td><td>-10.712<sup>**</sup></td><td>-11.379<sup>***</sup></td><td>-18.060<sup>**</sup></td><td>-21.036<sup>***</sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td>(4.377)</td><td>(4.144)</td><td>(7.698)</td><td>(7.628)</td></tr><tr><td style=\"text-align:left\">rank</td><td></td><td>1.416<sup>**</sup></td><td></td><td>-0.910<sup></sup></td><td></td><td>-0.256<sup></sup></td><td></td><td></td></tr><tr><td style=\"text-align:left\"></td><td></td><td>(0.645)</td><td></td><td>(0.745)</td><td></td><td>(0.484)</td><td></td><td></td></tr><tr><td style=\"text-align:left\">rankdummy1</td><td></td><td></td><td></td><td></td><td></td><td></td><td>8.888<sup></sup></td><td>7.144<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td></td><td></td><td>(7.624)</td><td>(5.666)</td></tr><tr><td style=\"text-align:left\">rankdummy1_interact</td><td></td><td></td><td></td><td></td><td></td><td></td><td>-8.505<sup></sup></td><td>-0.388<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td></td><td></td><td>(11.556)</td><td>(9.580)</td></tr><tr><td style=\"text-align:left\">rankdummy2</td><td></td><td></td><td></td><td></td><td></td><td></td><td>3.526<sup></sup></td><td>6.168<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td></td><td></td><td>(5.247)</td><td>(4.381)</td></tr><tr><td style=\"text-align:left\">rankdummy2_interact</td><td></td><td></td><td></td><td></td><td></td><td></td><td>-2.651<sup></sup></td><td>-4.270<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td></td><td></td><td>(11.072)</td><td>(9.672)</td></tr><tr><td style=\"text-align:left\">rankdummy3</td><td></td><td></td><td></td><td></td><td></td><td></td><td>2.338<sup></sup></td><td>6.993<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td></td><td></td><td>(7.110)</td><td>(5.746)</td></tr><tr><td style=\"text-align:left\">rankdummy3_interact</td><td></td><td></td><td></td><td></td><td></td><td></td><td>-2.517<sup></sup></td><td>-1.159<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td></td><td></td><td>(12.656)</td><td>(11.293)</td></tr><tr><td style=\"text-align:left\">rankdummy4</td><td></td><td></td><td></td><td></td><td></td><td></td><td>-0.957<sup></sup></td><td>3.897<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td></td><td></td><td>(5.276)</td><td>(4.750)</td></tr><tr><td style=\"text-align:left\">rankdummy4_interact</td><td></td><td></td><td></td><td></td><td></td><td></td><td>7.368<sup></sup></td><td>13.099<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td></td><td></td><td>(11.043)</td><td>(11.020)</td></tr><tr><td style=\"text-align:left\">rankdummy5</td><td></td><td></td><td></td><td></td><td></td><td></td><td>-1.133<sup></sup></td><td>3.533<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td></td><td></td><td>(5.154)</td><td>(4.688)</td></tr><tr><td style=\"text-align:left\">rankdummy5_interact</td><td></td><td></td><td></td><td></td><td></td><td></td><td>7.657<sup></sup></td><td>12.868<sup>*</sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td></td><td></td><td>(8.664)</td><td>(7.543)</td></tr><tr><td style=\"text-align:left\">rankdummy6</td><td></td><td></td><td></td><td></td><td></td><td></td><td>-0.485<sup></sup></td><td>3.931<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td></td><td></td><td>(4.809)</td><td>(4.433)</td></tr><tr><td style=\"text-align:left\">rankdummy6_interact</td><td></td><td></td><td></td><td></td><td></td><td></td><td>8.646<sup></sup></td><td>12.852<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td></td><td></td><td>(8.203)</td><td>(8.086)</td></tr><tr><td style=\"text-align:left\">rankdummy7</td><td></td><td></td><td></td><td></td><td></td><td></td><td>-5.460<sup></sup></td><td>3.522<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td></td><td></td><td>(4.343)</td><td>(4.370)</td></tr><tr><td style=\"text-align:left\">rankdummy7_interact</td><td></td><td></td><td></td><td></td><td></td><td></td><td>13.358<sup></sup></td><td>12.417<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td></td><td></td><td>(9.126)</td><td>(7.615)</td></tr><tr><td style=\"text-align:left\">rankdummy8</td><td></td><td></td><td></td><td></td><td></td><td></td><td>3.480<sup></sup></td><td>6.731<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td></td><td></td><td>(4.976)</td><td>(4.711)</td></tr><tr><td style=\"text-align:left\">rankdummy8_interact</td><td></td><td></td><td></td><td></td><td></td><td></td><td>2.621<sup></sup></td><td>6.698<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td></td><td></td><td>(6.694)</td><td>(6.624)</td></tr><tr><td style=\"text-align:left\">rankdummy9</td><td></td><td></td><td></td><td></td><td></td><td></td><td>-0.243<sup></sup></td><td>0.373<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td></td><td></td><td>(4.217)</td><td>(3.598)</td></tr><tr><td style=\"text-align:left\">rankdummy9_interact</td><td></td><td></td><td></td><td></td><td></td><td></td><td>12.301<sup>**</sup></td><td>17.087<sup>***</sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td></td><td></td><td>(6.068)</td><td>(5.082)</td></tr><td colspan=\"9\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align: left\">Observations</td><td>138</td><td>137</td><td>148</td><td>148</td><td>286</td><td>285</td><td>286</td><td>285</td></tr><tr><td style=\"text-align: left\">R<sup>2</sup></td><td>0.000</td><td>0.308</td><td>0.097</td><td>0.175</td><td>0.044</td><td>0.195</td><td>0.076</td><td>0.234</td></tr><tr><td style=\"text-align: left\">Adjusted R<sup>2</sup></td><td>-0.007</td><td>0.293</td><td>0.090</td><td>0.158</td><td>0.034</td><td>0.181</td><td>0.003</td><td>0.169</td></tr><tr><td style=\"text-align: left\">Residual Std. Error</td><td>18.466 (df=136)</td><td>15.512 (df=133)</td><td>15.495 (df=146)</td><td>14.911 (df=144)</td><td>16.993 (df=282)</td><td>15.668 (df=279)</td><td>17.267 (df=264)</td><td>15.775 (df=262)</td></tr><tr><td style=\"text-align: left\">F Statistic</td><td>0.007<sup></sup> (df=1; 136)</td><td>35.171<sup>***</sup> (df=3; 133)</td><td>16.794<sup>***</sup> (df=1; 146)</td><td>7.343<sup>***</sup> (df=3; 144)</td><td>5.733<sup>***</sup> (df=3; 282)</td><td>12.332<sup>***</sup> (df=5; 279)</td><td>2.002<sup>***</sup> (df=21; 264)</td><td>5.052<sup>***</sup> (df=22; 262)</td></tr><tr><td colspan=\"9\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align: left\">Note:</td>\n <td colspan=\"8\" style=\"text-align: right\">\n  <sup>*</sup>p&lt;0.1;\n  <sup>**</sup>p&lt;0.05;\n  <sup>***</sup>p&lt;0.01\n </td></tr></table>\n\n\n\nFrom the first two regressions, it is clear that belief adjustments of individuals in the direct treatment group and the 1-month treatment group did not differ significantly. In other words, time has no significant effect on individuals belief adjustment if they have received positive feedback. These findings overlap with the finding in Zimmermann(2020) that state positive feedback has a persistent effect on belief dynamics.\n\nThe (3) and (4) regression also correlates with Zimmermann(2020) findings since it is clear that the belief adjustments are significantly different between treatment groups at the .01 level, referring to the short-term effect of negative feedback.\n\nAs it is observable from the column 5 and 6 the interaction term for negative feedback and 1-month treatment group is significant again at the .01 level, in line with the findings from the previous columns. The regression output columns with control variables (rank and Bayesian belief adjustment) also gave the same results in terms of significance levels which strengthens the results. Again these are also in line with the findings of Zimmermann (2020).\n\nThe last columns are the DID models with rank effects interacted with treatment group and also includes rank dummy controls, as it is observable the interaction term for negative feedback and 1-month treatment group is significant again at the .05 level in (7) and at the .01 level in (8).\n\nOverall, all of the results and all of the values are exactly the same as the ones in the study of Zimmermann (2020); confirming the researcher's results.\n\n---\n## 6.2. Robustness Checks <a class=\"anchor\" id=\"sec6_2\"></a>\n---\nSome parts of the Appendix that would be relavant for the extension part of this project is added to the project notebook.\n\n### 6.2.1 Appendix A.4 - Alternative Definition of Positive/Negative Feedback  <a class=\"anchor\" id=\"sec6_2_1\"></a>\n\n##### **Heterogenous Feedbacks**\n\nBasically, to be considered to receive a positive or negative feedback, a subject should receive all the comparisons as the same kind; positive feedback if he/she received 3 positive comparisons and negative feedback if he/she received 3 negative comparisons.\n\n\n```python\n#Creating the new feedback dummy accordingly\ndf[\"dummynews_goodbad_h\"] = np.nan\ndf.loc[df['pos_comparisons'] == 3, 'dummynews_goodbad_h'] = 0\ndf.loc[df['pos_comparisons'] == 0, 'dummynews_goodbad_h'] = 1\n```\n\n\n```python\nAppendix_Table_1(df)\n```\n\n\n\n\nAppendix Table 1 - Belief Adjustment: Direct versus One Month Later<br><table style=\"text-align:center\"><tr><td colspan=\"7\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align:left\"></td><td colspan=\"6\"><em>Normalized Belief Adjustment - beliefadjustment_normalized</em></td></tr><tr><td style=\"text-align:left\"></td><tr><td></td><td colspan=\"2\">Positive Information</td><td colspan=\"2\">Negative Information</td><td colspan=\"2\">Difference-in-difference</td></tr><tr><td style=\"text-align:left\"></td><td>(1)</td><td>(2)</td><td>(3)</td><td>(4)</td><td>(5)</td><td>(6)</td></tr><tr><td colspan=\"7\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align:left\">Intercept</td><td>15.511<sup>***</sup></td><td>-0.580<sup></sup></td><td>20.795<sup>***</sup></td><td>31.651<sup>***</sup></td><td>15.511<sup>***</sup></td><td>8.473<sup>***</sup></td></tr><tr><td style=\"text-align:left\"></td><td>(2.483)</td><td>(2.708)</td><td>(2.324)</td><td>(11.841)</td><td>(2.481)</td><td>(3.203)</td></tr><tr><td style=\"text-align:left\">beliefadjustment_bayes_norm</td><td></td><td>0.640<sup>***</sup></td><td></td><td>0.121<sup></sup></td><td></td><td>0.384<sup>***</sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td>(0.069)</td><td></td><td>(0.097)</td><td></td><td>(0.070)</td></tr><tr><td style=\"text-align:left\">dummynews_goodbad_h</td><td></td><td></td><td></td><td></td><td>5.284<sup></sup></td><td>7.631<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td>(3.401)</td><td>(6.612)</td></tr><tr><td style=\"text-align:left\">dummytreat_direct1month</td><td>0.447<sup></sup></td><td>0.855<sup></sup></td><td>-15.895<sup>***</sup></td><td>-16.923<sup>***</sup></td><td>0.447<sup></sup></td><td>0.137<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td>(3.919)</td><td>(2.930)</td><td>(2.840)</td><td>(3.113)</td><td>(3.917)</td><td>(3.067)</td></tr><tr><td style=\"text-align:left\">interact_direct1month</td><td></td><td></td><td></td><td></td><td>-16.343<sup>***</sup></td><td>-16.571<sup>***</sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td></td><td></td><td>(4.839)</td><td>(4.254)</td></tr><tr><td style=\"text-align:left\">rank</td><td></td><td>-0.288<sup></sup></td><td></td><td>-1.825<sup></sup></td><td></td><td>-1.161<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td>(0.872)</td><td></td><td>(1.294)</td><td></td><td>(0.880)</td></tr><td colspan=\"7\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align: left\">Observations</td><td>69</td><td>69</td><td>74</td><td>74</td><td>143</td><td>143</td></tr><tr><td style=\"text-align: left\">R<sup>2</sup></td><td>0.000</td><td>0.459</td><td>0.265</td><td>0.326</td><td>0.133</td><td>0.319</td></tr><tr><td style=\"text-align: left\">Adjusted R<sup>2</sup></td><td>-0.015</td><td>0.434</td><td>0.255</td><td>0.297</td><td>0.114</td><td>0.294</td></tr><tr><td style=\"text-align: left\">Residual Std. Error</td><td>16.051 (df=67)</td><td>11.986 (df=65)</td><td>13.181 (df=72)</td><td>12.799 (df=70)</td><td>14.635 (df=139)</td><td>13.068 (df=137)</td></tr><tr><td style=\"text-align: left\">F Statistic</td><td>0.013<sup></sup> (df=1; 67)</td><td>30.393<sup>***</sup> (df=3; 65)</td><td>31.317<sup>***</sup> (df=1; 72)</td><td>11.025<sup>***</sup> (df=3; 70)</td><td>12.301<sup>***</sup> (df=3; 139)</td><td>11.697<sup>***</sup> (df=5; 137)</td></tr><tr><td colspan=\"7\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align: left\">Note:</td>\n <td colspan=\"6\" style=\"text-align: right\">\n  <sup>*</sup>p&lt;0.1;\n  <sup>**</sup>p&lt;0.05;\n  <sup>***</sup>p&lt;0.01\n </td></tr></table>\n\n\n\nAll of the values mimic the values in Table 1 in terms of significance, which means the definition of feedback in the main study was robust. However, for the negative feedback, the coefficients are larger than the previous results which might suggest more negative feedback may affect belief adjustment more negatively.\n\n\n---\n### 6.2.2 Appendix A.6 - Updating in the Short-Run  <a class=\"anchor\" id=\"sec6_2_2\"></a>\n---\nLooking specifically at short-run updating is not the main aim of Zimmermann(2020), however, the researcher finds it relevant to include the results from data. As it is also mentioned in the study, previous findings on short-term belief updating suggest two phenomena: conservatism (M\u00f6bius et al., 2013) and asymmetry (Eil and Rao, 2011).\n\n**Conservatism**\n\nAccording to Bayes' rule, people should adjust their belief by about 20 percentage points, on average after a signal. However, Zimmermann (2020) found a way lower normalized belief adjustment value of 11.80 while the correlation between Bayesian predictions and belief adjustment is being 0.459.\n\n\n```python\ndf_short = df[df['treatgroup'] == 4]\ndf_short['beliefadjustment_normalized'].mean()\n```\n\n\n\n\n    11.802197802197803\n\n\n\n\n```python\ncorrelation = df_short[['beliefadjustment_normalized','beliefadjustment_bayes_norm']].corr(method='pearson')\ncorrelation\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>beliefadjustment_normalized</th>\n      <th>beliefadjustment_bayes_norm</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>beliefadjustment_normalized</th>\n      <td>1.0000000</td>\n      <td>0.4585338</td>\n    </tr>\n    <tr>\n      <th>beliefadjustment_bayes_norm</th>\n      <td>0.4585338</td>\n      <td>1.0000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n**Asymmetry**\n\nIn order to investigate asymmetry, Zimmermann (2020) analyze the effect of Bayesian predictions on belief adjustments, separately for positive and negative feedback.\n\n\n```python\nAppendix_Table_3(df)\n```\n\n\n\n\nTable 8: Belief Adjustment in the Short-Run<br><table style=\"text-align:center\"><tr><td colspan=\"4\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align:left\"></td><td colspan=\"3\"><em>Belief Adjustmentbeliefadjustment_normalized</em></td></tr><tr><td style=\"text-align:left\"></td><tr><td></td><td colspan=\"1\">Positive Information</td><td colspan=\"1\">Negative Information</td><td colspan=\"1\">Difference-in-difference</td></tr><tr><td style=\"text-align:left\"></td><td>(1)</td><td>(2)</td><td>(3)</td></tr><tr><td colspan=\"4\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align:left\">Intercept</td><td>1.636<sup></sup></td><td>5.930<sup>*</sup></td><td>1.636<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td>(1.673)</td><td>(3.385)</td><td>(1.672)</td></tr><tr><td style=\"text-align:left\">beliefadjustment_bayes_norm</td><td>0.520<sup>***</sup></td><td>0.306<sup>***</sup></td><td>0.520<sup>***</sup></td></tr><tr><td style=\"text-align:left\"></td><td>(0.168)</td><td>(0.111)</td><td>(0.168)</td></tr><tr><td style=\"text-align:left\">dummynews_goodbad</td><td></td><td></td><td>4.294<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td>(3.776)</td></tr><tr><td style=\"text-align:left\">interact_negative_bayes</td><td></td><td></td><td>-0.213<sup></sup></td></tr><tr><td style=\"text-align:left\"></td><td></td><td></td><td>(0.201)</td></tr><td colspan=\"4\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align: left\">Observations</td><td>45</td><td>46</td><td>91</td></tr><tr><td style=\"text-align: left\">R<sup>2</sup></td><td>0.274</td><td>0.153</td><td>0.224</td></tr><tr><td style=\"text-align: left\">Adjusted R<sup>2</sup></td><td>0.257</td><td>0.133</td><td>0.198</td></tr><tr><td style=\"text-align: left\">Residual Std. Error</td><td>13.566 (df=43)</td><td>13.907 (df=44)</td><td>13.739 (df=87)</td></tr><tr><td style=\"text-align: left\">F Statistic</td><td>9.595<sup>***</sup> (df=1; 43)</td><td>7.558<sup>***</sup> (df=1; 44)</td><td>9.610<sup>***</sup> (df=3; 87)</td></tr><tr><td colspan=\"4\" style=\"border-bottom: 1px solid black\"></td></tr><tr><td style=\"text-align: left\">Note:</td>\n <td colspan=\"3\" style=\"text-align: right\">\n  <sup>*</sup>p&lt;0.1;\n  <sup>**</sup>p&lt;0.05;\n  <sup>***</sup>p&lt;0.01\n </td></tr></table>\n\n\n\nAs it is suggested by the findings in Column 3, DID reveals no significant relationship. In other words, the Bayesian predictions don\u2019t significantly differ between feedback groups. However, clearly, the coefficient for Bayesian prediction is slightly larger in positive information than in negative information which suggests some asymmetry.\n\n---\n### 6.2.3. Appendix A.7 - No Feedback Condition  <a class=\"anchor\" id=\"sec6_2_3\"></a>\n---\n\n\n```python\nAppendix_Figure_1(df)\n```\n\nThe figure clearly demonstrates that in absence of feedback, many subjects do not change their beliefs and a clear symmetry is observable for those who changed their beliefs.\n\n\n```python\n#Stats for control group; the only numbers I couldn't get exactly from the study of Zimmermann (2020) is the numbers below.\n#The reported mean belief adjustment being 0.22, with a standard deviation of 17.83.\ndf[df['treatgroup'] == 7]['beliefadjustment'].describe()\n```\n\n\n\n\n    count    51.0000000\n    mean      0.8039216\n    std      15.4687034\n    min     -50.0000000\n    25%      -5.0000000\n    50%       0.0000000\n    75%       5.0000000\n    max      40.0000000\n    Name: beliefadjustment, dtype: float64\n\n\n\n---\n### 6.2.4. Appendix A.8 - Figures Bayesian Posteriors  <a class=\"anchor\" id=\"sec6_2_4\"></a>\n---\n\n\n```python\n#Calculating Bayesian Posterior Averages\ndf['prior_av_b'] = df.groupby(['test_1', 'dummytreat_direct1month'])[\"prior_median\"].transform('mean')\ndf['post_av_pos_b'] = df[df[\"dummynews_goodbad\"] == 0].groupby(['test_1', 'dummytreat_direct1month'])[\"posterior_median_bayes\"].transform('mean')\ndf['post_av_neg_b'] = df[df[\"dummynews_goodbad\"] == 1].groupby(['test_1', 'dummytreat_direct1month'])[\"posterior_median_bayes\"].transform('mean')\n```\n\n\n```python\nAppendix_Figure_2(df)\n```\n\nThis figure is the same as Figure 2 only here Bayes prediction of posterior beliefs are used instead of actual posteriors.\n\n---\n# 7. Extension  <a class=\"anchor\" id=\"sec7\"></a>\n--- \n\nThe extension consist of two parts.\n\nIn the first part, I will replicate the first part of the study of Eil and Rao (2011) which is a quite similar experiment in terms of experimental design and empirical strategy that has been used. I think replicating an experiment that Zimmermann(2020) had taken reference would be beneficial to understand the motives and aims of Zimmermann(2020) while forming his study in the way it has been done. Also, I made use of some parts of the Eil and Rao (2011) study in the second part of the extension.\n\nIn the second part, I will present the extensions I have added such as data visualizations and further analysis on the effect of feedback.\n\n\n---\n## 7.1. Replication of Eil and Rao (2011)  <a class=\"anchor\" id=\"sec7_1\"></a>\n\nAs an extension, I decided to replicate the study of Eil and Rao (2011) which is a relevant experiment that is also quite oftenly mentioned by Zimmermann (2020) in their study.\n\n### 7.1.1. Introduction  <a class=\"anchor\" id=\"sec7_1_1\"></a>\nThe experiment consists of 3 main parts. I decided to replicate the first part of the experiment that analyzes the posterior beliefs of the subjects receiving the most \u201cextreme\u201d feedback(all positive or all negative). \n\nEil and Rao (2011) main aim in this experiment is to observe the asymmetry in the belief updating when subjects receive different types (positive and negative) of signals. Unlike Zimmermann (2020), Eil and Rao (2011) didn\u2019t vary the time between treatments but varied the scoring method(referred to as image task) of subjects. The subjects who are assigned to an image task, either scored according to their IQ test or physical attractiveness(beauty) and also a control group task. \n\n### 7.1.2. Experiment Design  <a class=\"anchor\" id=\"sec7_1_2\"></a>\n\nThe experiment is also quite similar to the study of Zimmermann(2020) by nature.\n\n1. Subjects were first either taken an IQ test and assigned to groups of 10 or went through a series of speed dates with 10 other people and asked to give a rating to each in terms of their physical attractiveness from 1 to 10.\n2. After the tasks, subjects were asked to elicit their belief about their ranking within their group of 10.\n3. Then subjects received 3 cards that revealed whether they were ranked higher or lower than their randomly picked groupmates. For the control task, they were told the number on the cards was randomly picked. Belief elicitation was done in three rounds since subjects were asked to elicit their beliefs about their ranks within the group after each card.\n\n\n**Variable Definitions**\n\n\n|Variable name|Definition|Beauty|IQ|Control|\n|---|---|---|---|---|\n|`meanbelief_priorbayesimage`|Mean Bayesian belief prediction calculated from prior belief|\u221a|\u221a||\n|`meanbelief_priorbayescard`|Mean Bayesian belief prediction calculated from prior belief|||\u221a|\n|`frac_upimage`|0 if good news, 1 if bad news|\u221a|\u221a||\n|`frac_upcard`||||\u221a|\n|`mb_fracup`|interaction term: $meanbelief_priorbayesimage_i$*$frac_upimage_i$|\u221a|\u221a||\n|`mb_fraccard`|interaction term: $meanbelief_priorbayescard_i$*$frac_upcard_i$|||\u221a|\n\n### 7.1.3. Emprical Strategy  <a class=\"anchor\" id=\"sec7_1_3\"></a>\n\nEven though, a model is not specified in the study of Eil and Rao (2011). One can come up with the following DID model for the estimations presented in the Table 1:\n\n\\begin{equation}\nmeanbelief_i = \\alpha + \\beta meanBayesian_i + \\gamma feedback_i + \\delta I_i + \\epsilon_i\n\\end{equation}\n\nwhere $feedback_i$ is the dummy variable for feedback and $meanBayesian_i$ is the mean Bayesian belief prediction. $I_i$ is for the interaction term that is generated by $meanBayesian_i$*$feedback_i$. Bayesian predictions are calculated using reported priors and the received signal type; then the term mean Bayesian, `meanbelief_priorbayesimage`, is produced by taking the expected rank according to posteriors reported through the rounds.\n\n### 7.1.4. Replication  <a class=\"anchor\" id=\"sec7_1_4\"></a>\n\n\n```python\n#Importing the adjusted and merged data set provided by the Eil and Rao (2011)\ndf_ex = pd.read_stata('data/extension.dta')\n```\n\nThe first figure presented by Eil and Rao (2011) is formed by regressing the subject's observed mean belief on the predicted mean belief using Bayes' Rule and grouping subjects by the feedback type that they have received.\n\n\n```python\nExtension_Figure_1(df_ex)\n```\n\nAt first glance, a visible asymmetry can be observed in the Beauty group between good and bad news; while such asymmetry is not that pronounced in the IQ test group. We interpret this asymmetry by the difference in slopes of the lines. As it can be seen in Panel A. bad news condition has a flatter slope, meaning that actual posteriors' have a shorter value length which means even though bayesian posteriors might suggest extreme updating the actual updating is relatively more conservative. In other words, the slope of the bad news line suggests an insensitivity to signal strength. Compared to bad news, we see a steeper slope for good news which suggests an exaggerated response to signal strength. Therefore, an asymmetry in responses for Beauty treatment is pronounced. If we look at Panel C. Control group we see a constant slope which implies that such asymmetries are the results of image treatments. The slope of the good news line in IQ treatments is also steeper compared to the control group however, not as much as it is in Beauty treatment.\n\nAnother feature to analyze in this figure is the observations scattered around the fitted line. If we compare the two treatment groups, it is clear that beliefs are noisier for bad news as it is for good news.\n\nAlso, it is worth noting that having slopes equal to zero and negative intercept would imply optimism in beliefs in general.\n\n\n```python\n#Used regressions in Extension Figure 2 with the standard errors clustered at subject level\nreg_B_b_ = cluster_fit('meanbeliefimage ~ meanbelief_priorbayesimage + mb_fracup + frac_upimage',\n                           data=df_ex[(df_ex['frac_upimage'] == 0) & (df_ex['IQtask'] ==0)], group_var='ID')\nreg_B_g_ = cluster_fit('meanbeliefimage ~ meanbelief_priorbayesimage + mb_fracup + frac_upimage',\n                           data=df_ex[(df_ex['frac_upimage'] == 1) & (df_ex['IQtask'] ==0)], group_var='ID')\n    \nreg_IQ_b_ = cluster_fit('meanbeliefimage ~ meanbelief_priorbayesimage + mb_fracup + frac_upimage',\n                            data=df_ex[(df_ex['frac_upimage'] == 0) & (df_ex['IQtask'] ==1)], group_var='ID')\nreg_IQ_g_ = cluster_fit('meanbeliefimage ~ meanbelief_priorbayesimage + mb_fracup + frac_upimage',\n                            data=df_ex[(df_ex['frac_upimage'] == 1) & (df_ex['IQtask'] ==1)], group_var='ID')\n    \nreg_C_b_ = cluster_fit('meanbeliefcard ~ meanbelief_priorbayescard + mb_fracupcard + frac_upcard',\n                           data=df_ex[(df_ex['frac_upcard'] == 0)], group_var='ID')\nreg_C_g_ = cluster_fit('meanbeliefcard ~ meanbelief_priorbayescard + mb_fracupcard + frac_upcard',\n                           data=df_ex[(df_ex['frac_upcard'] == 0)], group_var='ID')\n```\n\n\n```python\nExtension_Figure_2(df_ex)\n```\n\nPanel. D represents the plots of the R^2s from the regressions used in Extension Table 1 but divided according to the type of feedback. Unfortunately, even though I used regressions with standard errors clustered at the subject level as is described by Eil and Rao (2011); I couldn\u2019t get the R^2 value of the IQ test/good newsgroup right, which is confusing since I get exactly the same result from the pooled regression in the Extension Table 1. According to Eil and Rao (2011), the $R^2$ for IQ/good newsgroup should be below 0.7.\n\nTaking the result of Eil and Rao (2011) as a reference point, R^2 differ for the Beauty and IQ group while that is obviously not the case for the Control group.\n\n**Table 1**\n\n\n```python\n#Used regressions in Extension Table 1 with the standard errors clustered at subject level\nreg_B = cluster_fit('meanbeliefimage ~ meanbelief_priorbayesimage + mb_fracup + frac_upimage', data=df_ex[(((df_ex['frac_upimage'] == 0) | (df_ex['frac_upimage'] == 1)) & (df_ex['IQtask'] ==0))], group_var='ID')\nreg_IQ = cluster_fit('meanbeliefimage ~ meanbelief_priorbayesimage + mb_fracup + frac_upimage', data=df_ex[(((df_ex['frac_upimage'] == 0) | (df_ex['frac_upimage'] == 1)) & (df_ex['IQtask'] ==1))], group_var='ID')\nreg_C = cluster_fit('meanbeliefcard ~ meanbelief_priorbayescard + mb_fracupcard + frac_upcard', data=df_ex[(df_ex['frac_upcard'] == 0) | (df_ex['frac_upcard'] == 1)], group_var='ID')\n```\n\n\n```python\nExtension_Table_1(df_ex)\n```\n\n    \n    ===================================================\n                                Beauty     IQ   Control\n    ---------------------------------------------------\n    Intercept                  2.05***  1.05    2.29***\n                               (0.52)   (0.76)  (0.76) \n    R-squared                  0.87     0.87    0.72   \n    R-squared Adj.             0.86     0.87    0.71   \n    frac_upcard                                 -0.53  \n                                                (0.95) \n    frac_upimage               -2.31*** -0.58          \n                               (0.54)   (0.81)         \n    mb_fracup                  0.41***  0.07           \n                               (0.10)   (0.13)         \n    mb_fracupcard                               -0.00  \n                                                (0.19) \n    meanbelief_priorbayescard                   0.59***\n                                                (0.10) \n    meanbelief_priorbayesimage 0.64***  0.85***        \n                               (0.08)   (0.10)         \n    ===================================================\n    Standard errors in parentheses.\n    * p<.1, ** p<.05, ***p<.01\n\n\n---\n*See below for a reader friendly version of the Extension Table 1 that I created with the same values.*\n\n||Beauty|IQ|Control|\n|---|---|---|---|\n|Intercept|**2.05** |1.05 |**2.29** |\n||(0.52)|(0.76)|(0.76)|\n|Bayesian \u03bc|**0.64** |**0.85** |**0.59** |\n||(0.08)|(0.85)|(0.10)|\n|Bayesian \u03bc *1{All positive feedback}|**0.41** |0.07 |-0.00 |\n||(0.10)|(0.13)|(0.19)|\n|1{All positive feedback}|**-2.31** |-0.58 |-0.53 |\n||(0.54)|(0.81)|(0.95)|\n|Intercept|**2.05** |**1.05** |**2.29**|\n||(0.52)|(0.76)|(0.76)|\n|$R^2$|0.87|0.87|0.72 |\n|$R^2$ Adj.|0.86|0.87 |0.71|\n||Standard errors in parentheses. * p<.1, *p<.05*, ***p<.01|\n\nThe findings found in Extention Table1 are in furtherance of the interpretations made for the Extention Figure2. Like it is suggested by the figure, the asymmetry in belief dynamics-the difference between positive and negative feedback conditions- is only significant in Beauty at the 0.01 level of significance.\n\n### 7.1.5. Comparison with Zimmermann (2020)  <a class=\"anchor\" id=\"sec7_1_5\"></a>\n\nIt is easy to see the two experiments share a lot of experimental and empirical strategies. First of all, both studies have a longitudinal feature since they elicit subjects\u2019 beliefs two times. Secondly, the two studies have the same focus which is the asymmetry in belief dynamics that arise as a result of feedback type. In addition, both studies make use of DID models in their predictions. Nevertheless, while Eil and Rao (2011) are used the heterogeneous definition of feedbacks, Zimmermann(2020) choose to allow homogenous comparison types within feedback groups- even though a robustness check is made (see Appendix A.4)-.  A fundamental difference is the employment of treatment groups. While Eil and Rao (2011) were interested in belief updating in different tasks (Beauty and IQ), Zimmermann (2020) was interested in belief updating when elicitation time differs (Direct and 1 month). Therefore, all of the results Eil and Rao (2011) found was derived from short-run updating. At this point, it is intriguing that whether the difference between the tasks would be as pronounce as it was; if Zimmermann (2020) also had a Beauty image task that is also measured after 1 month.\n\n---\n## 7.2. Further Extension  <a class=\"anchor\" id=\"sec7_2\"></a>\n---\n### 7.2.1. Alternative Data Visualizations <a class=\"anchor\" id=\"sec7_2_1\"></a>\n\n\n```python\nExtension_Figure_3(df)\n```\n\nAs a small extension, I decided to create a figure to combine the figure from Appendix A.8 with Figure 2 since it would be a good way to view posterior beliefs in comparison with Bayesian predictions.\n\nIf we look at the first row we see that observed beliefs follow a relatively similar pattern, in terms of subjects' reported percentages of being in the upper half of the group, to Bayesian predictions compared to the second row where graphs differ visibly.\n\nAlso, in the short run, it is easy to see that people are conservative in belief updating. For instance, in the group of high test scores and positive feedback, according to Bayes' Rule, one would expect a posterior slightly above %90 while it is only slightly above %80; suggesting a difference near %10 percent.\n\nThe opposite can be observable in long-run belief updating in the negative feedback group since in every test score group people reported posterior beliefs that are much higher than Bayesian predictions-especially for the individuals with lower test scores. What I found interesting in the results from long-run, is the difference in belief updating when feedback is positive. In the last figure, we see that no matter the test scores individuals tend to report a belief near %80 percent when they receive positive feedback. I think this would be a good starting point for further research in dynamic beliefs.\n\n---\nMaking use of Extention Figure 2 from the study of Eil and Rao (2011), I created two similar data visualization using the data of Zimmermann (2020).\n\n\n```python\nExtension_Figure_4(df)\n```\n\nIn both figures, negative feedback lines are flatter and specifically very flat in Panel B. 1 month treatment. Meaning that in both treatment groups subjects'  weighed negative information less heavily than positive information and even much less heavily in 1-month treatment.\n\n\n```python\nExtension_Figure_5(df)\n```\n\nIn this visiualization, it is easier to see the asymmetry between positive and negative feedback. If we look at Panel A. Positive Feedback, we see that slopes of fitted lines of direct and 1month treatment are almost the same; while in Panel B. they clearly differ.\n\n\n## 7.2.2 Further Analysis with No Feedback Group <a class=\"anchor\" id=\"sec7_2_2\"></a>\n\nAs a control group, Zimmermann (2020) also added a group where no feedback is given to the subjects. The main aim of adding this group was the investigate the potential time trends in beliefs that may exist independently of receiving feedback. However, I couldn't find any further analyzes with this group neither in the study or appendix-except the visiualization in Appendix A.7.\n\nSo as a further analyze I decided to investigate the difference between feedback(positive or negative) and no feedback groups within the 1-month condition to see whether receiving feedback itself cause a difference in belief adjustment.\n\n### 7.2.2.1. Estimation Strategy  <a class=\"anchor\" id=\"sec7_2_2_1\"></a>\n\nFor my analysis, I made use of a simple difference-in-difference model of the following kind:\n\n\\begin{equation}\nbelief_i = \\alpha + \\beta dummyfeedback_i + \\gamma secondwave_i + \\delta I_i + \\epsilon_i\n\\end{equation}\n\nwhere $dummyfeedback_i$ is the dummy variable for receiving feedback and $secondwave_i$ is the dummy for posterior belief. $I_i$ is for the interaction term that is generated by $dummyfeedback_i$*$secondwave_i$. If the subjects obtained feedback and the belief is a posterior belief, (i)feedback dummy (ii)secondwave dummy and (iii) interaction term are equal to 1; making the $ \\delta$ the coefficient of interest.\n\nFor the estimation, I reshaped data to have a single belief variable combining posterior and prior beliefs and to have a time variable that qualifies in which time the belief is elicited.\n\n### 7.2.2.2. Estimation  <a class=\"anchor\" id=\"sec7_2_2_2\"></a>\n\n\n```python\n#Making a copy of the original data to start the reshape\ndf_control = df\n```\n\n\n```python\n#Generating an ID number for each participant\ndf_control['ID'] = df_control.index + 1\n```\n\n\n```python\n#Filtering data to have only 1 month and no feedback treatment\ndf_control = df[(df['treatgroup'] == 2) | (df['treatgroup'] == 7)]\n```\n\n\n```python\n#Filtering and adjusting data\ndf_control = df[(df['treatgroup'] == 2) | (df['treatgroup'] == 7)]\ndf_control = df_control[['ID', 'treatment', 'posterior_median', 'prior_median']]\ndf_control.rename(columns = {\"prior_median\": \"belief1\", \"posterior_median\": \"belief2\" }, inplace=True)\ndf_control[\"ID\"] = df_control.index\n```\n\n\n```python\n#Transforming data from a wide format to long format\ndf_control = pd.wide_to_long(df_control, stubnames='belief', i=\"ID\", j=\"time\")\n```\n\n\n```python\n#Creating a column with time index\ndf_control = df_control.reset_index(level=1)\n```\n\n\n```python\n#Final data\ndf_control\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>time</th>\n      <th>treatment</th>\n      <th>belief</th>\n    </tr>\n    <tr>\n      <th>ID</th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>115</th>\n      <td>2</td>\n      <td>confidence_1monthlater</td>\n      <td>90.0</td>\n    </tr>\n    <tr>\n      <th>116</th>\n      <td>2</td>\n      <td>confidence_1monthlater</td>\n      <td>50.0</td>\n    </tr>\n    <tr>\n      <th>117</th>\n      <td>2</td>\n      <td>confidence_1monthlater</td>\n      <td>30.0</td>\n    </tr>\n    <tr>\n      <th>118</th>\n      <td>2</td>\n      <td>confidence_1monthlater</td>\n      <td>80.0</td>\n    </tr>\n    <tr>\n      <th>119</th>\n      <td>2</td>\n      <td>confidence_1monthlater</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>679</th>\n      <td>1</td>\n      <td>nofeedback</td>\n      <td>100.0</td>\n    </tr>\n    <tr>\n      <th>680</th>\n      <td>1</td>\n      <td>nofeedback</td>\n      <td>55.0</td>\n    </tr>\n    <tr>\n      <th>681</th>\n      <td>1</td>\n      <td>nofeedback</td>\n      <td>50.0</td>\n    </tr>\n    <tr>\n      <th>682</th>\n      <td>1</td>\n      <td>nofeedback</td>\n      <td>25.0</td>\n    </tr>\n    <tr>\n      <th>683</th>\n      <td>1</td>\n      <td>nofeedback</td>\n      <td>70.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>318 rows \u00d7 3 columns</p>\n</div>\n\n\n\n\n```python\nget_variables_for_extension(df_control)\n```\n\n\n```python\nExtension_Table_2(df_control)\n```\n\n\n\n\n<table class=\"simpletable\">\n<caption>OLS Regression Results</caption>\n<tr>\n  <th>Dep. Variable:</th>         <td>belief</td>      <th>  R-squared:         </th> <td>   0.005</td>\n</tr>\n<tr>\n  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>  -0.005</td>\n</tr>\n<tr>\n  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>  0.5177</td>\n</tr>\n<tr>\n  <th>Date:</th>             <td>Thu, 22 Jul 2021</td> <th>  Prob (F-statistic):</th>  <td> 0.670</td> \n</tr>\n<tr>\n  <th>Time:</th>                 <td>23:31:30</td>     <th>  Log-Likelihood:    </th> <td> -1458.1</td>\n</tr>\n<tr>\n  <th>No. Observations:</th>      <td>   318</td>      <th>  AIC:               </th> <td>   2924.</td>\n</tr>\n<tr>\n  <th>Df Residuals:</th>          <td>   314</td>      <th>  BIC:               </th> <td>   2939.</td>\n</tr>\n<tr>\n  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n</tr>\n<tr>\n  <th>Covariance Type:</th>         <td>HC1</td>       <th>                     </th>     <td> </td>   \n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n           <td></td>              <th>coef</th>     <th>std err</th>      <th>z</th>      <th>P>|z|</th>  <th>[0.025</th>    <th>0.975]</th>  \n</tr>\n<tr>\n  <th>Intercept</th>           <td>   65.9608</td> <td>    3.797</td> <td>   17.371</td> <td> 0.000</td> <td>   58.518</td> <td>   73.403</td>\n</tr>\n<tr>\n  <th>dummy_feedback</th>      <td>   -3.1182</td> <td>    4.358</td> <td>   -0.715</td> <td> 0.474</td> <td>  -11.660</td> <td>    5.424</td>\n</tr>\n<tr>\n  <th>secondwave</th>          <td>    0.2157</td> <td>    5.185</td> <td>    0.042</td> <td> 0.967</td> <td>   -9.947</td> <td>   10.378</td>\n</tr>\n<tr>\n  <th>feedback_secondwave</th> <td>    3.2843</td> <td>    6.035</td> <td>    0.544</td> <td> 0.586</td> <td>   -8.544</td> <td>   15.113</td>\n</tr>\n</table>\n<table class=\"simpletable\">\n<tr>\n  <th>Omnibus:</th>       <td> 9.123</td> <th>  Durbin-Watson:     </th> <td>   1.766</td>\n</tr>\n<tr>\n  <th>Prob(Omnibus):</th> <td> 0.010</td> <th>  Jarque-Bera (JB):  </th> <td>   8.163</td>\n</tr>\n<tr>\n  <th>Skew:</th>          <td>-0.327</td> <th>  Prob(JB):          </th> <td>  0.0169</td>\n</tr>\n<tr>\n  <th>Kurtosis:</th>      <td> 2.566</td> <th>  Cond. No.          </th> <td>    8.62</td>\n</tr>\n</table><br/><br/>Notes:<br/>[1] Standard Errors are heteroscedasticity robust (HC1)\n\n\n\nThe p-value of the interaction term implies that the difference is insignificant. Therefore, one can conclude that receiving feedback does not have an effect on beliefs solely. In other words, the change in beliefs is not significant between feedback and no feedback group.\n\n---\n# 8. Conclusion <a class=\"anchor\" id=\"sec8\"></a>\n---\n\nIn sum, all of the results I get from using the data and STATA codes provided by Zimmmermann (2020) overlaps with the ones in the study. Except for the stats in Appendix A.7., I manage to get the same numbers and figures presented in the study. Similarly, for the extension replication, I used the merged and reshaped data provided by Eil and Rao. Using the Stata codes provided by the researchers, I manage to get the same results except the $R^2$ values represented in the Extension Figure 2. In light of these, I can conclude that even though individuals adjust their beliefs accordingly- and in line with Bayesian predictions- in short term; the effects of negative feedback tend to fade away over time while positive feedback has a long-lasting effect on belief adjustment. According to my analysis done with the control group, the feedback itself solely doesn't have a significant effect on beliefs. Finally, the Difference-in-Difference models used in both of the studies and my analysis, are good tools when researchers want to analyze observations draw from a between-subjects experimental design.\n\n---\n# 9. References <a class=\"anchor\" id=\"sec9\"></a>\n---\n\nBeno\u00eet, Jean-Pierre, and Juan Dubra. 2011. \u201cApparent Overconfidence?\u201d [*Econometrica* 79 (5):\n1591\u20131625.](https://doi.org/10.3982/ECTA8583)\n\nEil, David, and Justin M. Rao. 2011. \u201cThe Good News-Bad News Effect: Asymmetric Processing of Objective Information about Yourself.\u201d [*American Economic Journal: Microeconomics* 3 (2): 114\u201338.](https://doi.org/10.1257/mic.3.2.114)\n\nM\u00f6bius, Markus M., Muriel Niederle, Paul Niehaus, and Tanya S. Rosenblat. 2013. \u201cManaging\nSelf-Confidence: Theory and Experimental Evidence.\u201d Unpublished.\n\nZimmermann, F. 2020. \u201cThe Dynamics of Motivated Beliefs.\u201d [*American Economic Journal: Microeconomics* 110 (2): 337\u2013363.](https://doi.org/10.1257/aer.20180728)\n\n-------\nNotebook by Aysu Avc\u0131 | Find me on GitHub at https://github.com/aysuavci.\n\n---\n", "meta": {"hexsha": "19dd38ac3fd938da024b2072d2a5bdbf64d21407", "size": 583350, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "project_notebook.ipynb", "max_stars_repo_name": "aysuavci/ose-data-science-course-project-aysuavci", "max_stars_repo_head_hexsha": "33ea374588ba22d6328fec84c78e831ba2eb88cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project_notebook.ipynb", "max_issues_repo_name": "aysuavci/ose-data-science-course-project-aysuavci", "max_issues_repo_head_hexsha": "33ea374588ba22d6328fec84c78e831ba2eb88cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project_notebook.ipynb", "max_forks_repo_name": "aysuavci/ose-data-science-course-project-aysuavci", "max_forks_repo_head_hexsha": "33ea374588ba22d6328fec84c78e831ba2eb88cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 223.6771472393, "max_line_length": 97756, "alphanum_fraction": 0.8755326991, "converted": true, "num_tokens": 24817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1561048974454574, "lm_q2_score": 0.1480471923932738, "lm_q1q2_score": 0.02311089178563991}}
{"text": "<a href=\"https://colab.research.google.com/github/Dighvijay/LearningQuantumComputing/blob/master/SimpleStuff.ipynb\" target=\"_parent\"></a>\n\n\n```\n!pip install cirq\n```\n\n    Requirement already satisfied: cirq in /usr/local/lib/python3.6/dist-packages (0.8.1)\n    Requirement already satisfied: google-api-core[grpc]<2.0.0dev,>=1.14.0 in /usr/local/lib/python3.6/dist-packages (from cirq) (1.16.0)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.6/dist-packages (from cirq) (3.6.6)\n    Requirement already satisfied: networkx~=2.4 in /usr/local/lib/python3.6/dist-packages (from cirq) (2.4)\n    Requirement already satisfied: requests~=2.18 in /usr/local/lib/python3.6/dist-packages (from cirq) (2.23.0)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from cirq) (1.4.1)\n    Requirement already satisfied: sortedcontainers~=2.0 in /usr/local/lib/python3.6/dist-packages (from cirq) (2.2.2)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.6/dist-packages (from cirq) (1.1.1)\n    Requirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from cirq) (0.7)\n    Requirement already satisfied: matplotlib~=3.0 in /usr/local/lib/python3.6/dist-packages (from cirq) (3.2.2)\n    Requirement already satisfied: protobuf==3.8.0 in /usr/local/lib/python3.6/dist-packages (from cirq) (3.8.0)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from cirq) (1.0.5)\n    Requirement already satisfied: freezegun~=0.3.15 in /usr/local/lib/python3.6/dist-packages (from cirq) (0.3.15)\n    Requirement already satisfied: numpy~=1.16 in /usr/local/lib/python3.6/dist-packages (from cirq) (1.18.5)\n    Requirement already satisfied: setuptools>=34.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (47.3.1)\n    Requirement already satisfied: pytz in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (2018.9)\n    Requirement already satisfied: google-auth<2.0dev,>=0.4.0 in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (1.17.2)\n    Requirement already satisfied: googleapis-common-protos<2.0dev,>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (1.52.0)\n    Requirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (1.12.0)\n    Requirement already satisfied: grpcio<2.0dev,>=1.8.2; extra == \"grpc\" in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (1.30.0)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx~=2.4->cirq) (4.4.2)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (2.9)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (2020.6.20)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy->cirq) (1.1.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq) (2.4.7)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq) (2.8.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq) (1.2.0)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth<2.0dev,>=0.4.0->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (4.1.0)\n    Requirement already satisfied: rsa<5,>=3.1.4; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from google-auth<2.0dev,>=0.4.0->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (4.6)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.6/dist-packages (from google-auth<2.0dev,>=0.4.0->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (0.2.8)\n    Requirement already satisfied: pyasn1>=0.1.3 in /usr/local/lib/python3.6/dist-packages (from rsa<5,>=3.1.4; python_version >= \"3\"->google-auth<2.0dev,>=0.4.0->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (0.4.8)\n\n\n\n```\nimport cirq\n```\n\n\n```\n#Applying NOT gate to a qubit and measuring it.\nqubit = cirq.GridQubit(0, 0) #picking the qubit\n\ncircuit = cirq.Circuit([\n                                 cirq.X(qubit),\n                                 cirq.measure(qubit, key = 'm')\n                                 ]\n)\nprint(\"The circuit:\")\nprint(circuit)\n```\n\n    The circuit:\n    (0, 0): \u2500\u2500\u2500X\u2500\u2500\u2500M('m')\u2500\u2500\u2500\n\n\n\n```\nsimulator = cirq.Simulator()\nresult = simulator.run(circuit, repetitions = 10)\nprint(\"Results:\")\nprint(result)\n```\n\n    Results:\n    m=1111111111\n\n\n\n```\n#Preparing a Bell States |phi^+>\n\nimport cirq \n\nqreg = [cirq.LineQubit(x) for x in range(2)]\ncirc = cirq.Circuit()\n\ncirc.append([cirq.H(qreg[0]), cirq.CNOT(qreg[0], qreg[1])])\n\nprint(\"Circuit\")\nprint(circ)\n\ncirc.append(cirq.measure(*qreg, key=\"z\"))\n\nsim = cirq.Simulator()\nres = sim.run(circ, repetitions = 100)\n\nprint(\"\\nMeasurements:\")\nprint(res.histogram(key=\"z\"))\n\n\n```\n\n    Circuit\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500\n              \u2502\n    1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\n    \n    Measurements:\n    Counter({3: 56, 0: 44})\n\n\n\n```\n\n```\n", "meta": {"hexsha": "d9788e0f5fdbb3b4273bff48ba51f96e1efe04f9", "size": 9910, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "SimpleStuff.ipynb", "max_stars_repo_name": "Dighvijay/LearningQuantumComputing", "max_stars_repo_head_hexsha": "19375865fdb88f3aec735f3a1cad6290f039f277", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SimpleStuff.ipynb", "max_issues_repo_name": "Dighvijay/LearningQuantumComputing", "max_issues_repo_head_hexsha": "19375865fdb88f3aec735f3a1cad6290f039f277", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SimpleStuff.ipynb", "max_forks_repo_name": "Dighvijay/LearningQuantumComputing", "max_forks_repo_head_hexsha": "19375865fdb88f3aec735f3a1cad6290f039f277", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.8495575221, "max_line_length": 244, "alphanum_fraction": 0.5384460141, "converted": true, "num_tokens": 1976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606818053136394, "lm_q2_score": 0.058345838564946864, "lm_q1q2_score": 0.02310893012199519}}
{"text": "# Damage Mapper Examples\n\nThis Jupyter notebook mainly demonstrates the various function in the Damage Mapper section of the project\n\n\n```python\n!pip install -e . \n!pip install -r requirements.txt\nimport armageddon\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom collections import OrderedDict\n```\n\n    Obtaining file:///home/yhc97/acse/ACSE-4/1-armageddon\n    Installing collected packages: Armageddon\n      Attempting uninstall: Armageddon\n        Found existing installation: Armageddon 1.0\n        Uninstalling Armageddon-1.0:\n          Successfully uninstalled Armageddon-1.0\n      Running setup.py develop for Armageddon\n    Successfully installed Armageddon\n    Requirement already satisfied: numpy>=1.13.0 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from -r requirements.txt (line 1)) (1.18.5)\n    Requirement already satisfied: scipy in /home/yhc97/anaconda3/lib/python3.8/site-packages (from -r requirements.txt (line 2)) (1.5.0)\n    Requirement already satisfied: sympy in /home/yhc97/anaconda3/lib/python3.8/site-packages (from -r requirements.txt (line 3)) (1.6.1)\n    Requirement already satisfied: pandas in /home/yhc97/anaconda3/lib/python3.8/site-packages (from -r requirements.txt (line 4)) (1.0.5)\n    Requirement already satisfied: matplotlib in /home/yhc97/anaconda3/lib/python3.8/site-packages (from -r requirements.txt (line 5)) (3.2.2)\n    Requirement already satisfied: mpltools in /home/yhc97/anaconda3/lib/python3.8/site-packages (from -r requirements.txt (line 6)) (0.2.0)\n    Requirement already satisfied: pytest in /home/yhc97/anaconda3/lib/python3.8/site-packages (from -r requirements.txt (line 7)) (5.4.3)\n    Requirement already satisfied: pytest-timeout in /home/yhc97/anaconda3/lib/python3.8/site-packages (from -r requirements.txt (line 8)) (1.4.2)\n    Requirement already satisfied: sphinx in /home/yhc97/anaconda3/lib/python3.8/site-packages (from -r requirements.txt (line 9)) (3.1.2)\n    Requirement already satisfied: dask in /home/yhc97/anaconda3/lib/python3.8/site-packages (from -r requirements.txt (line 10)) (2.20.0)\n    Requirement already satisfied: distributed in /home/yhc97/anaconda3/lib/python3.8/site-packages (from -r requirements.txt (line 11)) (2.20.0)\n    Requirement already satisfied: googledrivedownloader in /home/yhc97/anaconda3/lib/python3.8/site-packages (from -r requirements.txt (line 12)) (0.4)\n    Requirement already satisfied: folium in /home/yhc97/anaconda3/lib/python3.8/site-packages (from -r requirements.txt (line 13)) (0.12.0)\n    Requirement already satisfied: mpmath>=0.19 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from sympy->-r requirements.txt (line 3)) (1.1.0)\n    Requirement already satisfied: python-dateutil>=2.6.1 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from pandas->-r requirements.txt (line 4)) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from pandas->-r requirements.txt (line 4)) (2020.1)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from matplotlib->-r requirements.txt (line 5)) (1.2.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from matplotlib->-r requirements.txt (line 5)) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from matplotlib->-r requirements.txt (line 5)) (0.10.0)\n    Requirement already satisfied: configobj>=4.4.0 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from mpltools->-r requirements.txt (line 6)) (5.0.6)\n    Requirement already satisfied: future>=0.12.4 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from mpltools->-r requirements.txt (line 6)) (0.18.2)\n    Requirement already satisfied: py>=1.5.0 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from pytest->-r requirements.txt (line 7)) (1.9.0)\n    Requirement already satisfied: packaging in /home/yhc97/anaconda3/lib/python3.8/site-packages (from pytest->-r requirements.txt (line 7)) (20.4)\n    Requirement already satisfied: attrs>=17.4.0 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from pytest->-r requirements.txt (line 7)) (18.2.0)\n    Requirement already satisfied: more-itertools>=4.0.0 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from pytest->-r requirements.txt (line 7)) (8.4.0)\n    Requirement already satisfied: pluggy<1.0,>=0.12 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from pytest->-r requirements.txt (line 7)) (0.13.1)\n    Requirement already satisfied: wcwidth in /home/yhc97/anaconda3/lib/python3.8/site-packages (from pytest->-r requirements.txt (line 7)) (0.2.5)\n    Requirement already satisfied: snowballstemmer>=1.1 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from sphinx->-r requirements.txt (line 9)) (2.0.0)\n    Requirement already satisfied: sphinxcontrib-jsmath in /home/yhc97/anaconda3/lib/python3.8/site-packages (from sphinx->-r requirements.txt (line 9)) (1.0.1)\n    Requirement already satisfied: Pygments>=2.0 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from sphinx->-r requirements.txt (line 9)) (2.6.1)\n    Requirement already satisfied: sphinxcontrib-devhelp in /home/yhc97/anaconda3/lib/python3.8/site-packages (from sphinx->-r requirements.txt (line 9)) (1.0.2)\n    Requirement already satisfied: setuptools in /home/yhc97/anaconda3/lib/python3.8/site-packages (from sphinx->-r requirements.txt (line 9)) (49.2.0.post20200714)\n    Requirement already satisfied: sphinxcontrib-serializinghtml in /home/yhc97/anaconda3/lib/python3.8/site-packages (from sphinx->-r requirements.txt (line 9)) (1.1.4)\n    Requirement already satisfied: docutils>=0.12 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from sphinx->-r requirements.txt (line 9)) (0.16)\n    Requirement already satisfied: sphinxcontrib-htmlhelp in /home/yhc97/anaconda3/lib/python3.8/site-packages (from sphinx->-r requirements.txt (line 9)) (1.0.3)\n    Requirement already satisfied: babel>=1.3 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from sphinx->-r requirements.txt (line 9)) (2.8.0)\n    Requirement already satisfied: alabaster<0.8,>=0.7 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from sphinx->-r requirements.txt (line 9)) (0.7.12)\n    Requirement already satisfied: sphinxcontrib-applehelp in /home/yhc97/anaconda3/lib/python3.8/site-packages (from sphinx->-r requirements.txt (line 9)) (1.0.2)\n    Requirement already satisfied: imagesize in /home/yhc97/anaconda3/lib/python3.8/site-packages (from sphinx->-r requirements.txt (line 9)) (1.2.0)\n    Requirement already satisfied: Jinja2>=2.3 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from sphinx->-r requirements.txt (line 9)) (2.11.2)\n    Requirement already satisfied: sphinxcontrib-qthelp in /home/yhc97/anaconda3/lib/python3.8/site-packages (from sphinx->-r requirements.txt (line 9)) (1.0.3)\n    Requirement already satisfied: requests>=2.5.0 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from sphinx->-r requirements.txt (line 9)) (2.22.0)\n    Requirement already satisfied: pyyaml in /home/yhc97/anaconda3/lib/python3.8/site-packages (from dask->-r requirements.txt (line 10)) (5.3.1)\n    Requirement already satisfied: tornado>=6.0.3; python_version >= \"3.8\" in /home/yhc97/anaconda3/lib/python3.8/site-packages (from distributed->-r requirements.txt (line 11)) (6.0.4)\n    Requirement already satisfied: zict>=0.1.3 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from distributed->-r requirements.txt (line 11)) (2.0.0)\n    Requirement already satisfied: toolz>=0.8.2 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from distributed->-r requirements.txt (line 11)) (0.10.0)\n    Requirement already satisfied: msgpack>=0.6.0 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from distributed->-r requirements.txt (line 11)) (1.0.0)\n    Requirement already satisfied: psutil>=5.0 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from distributed->-r requirements.txt (line 11)) (5.7.0)\n    Requirement already satisfied: tblib>=1.6.0 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from distributed->-r requirements.txt (line 11)) (1.6.0)\n    Requirement already satisfied: cloudpickle>=1.3.0 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from distributed->-r requirements.txt (line 11)) (1.5.0)\n    Requirement already satisfied: sortedcontainers!=2.0.0,!=2.0.1 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from distributed->-r requirements.txt (line 11)) (2.2.2)\n    Requirement already satisfied: click>=6.6 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from distributed->-r requirements.txt (line 11)) (7.1.2)\n    Requirement already satisfied: branca>=0.3.0 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from folium->-r requirements.txt (line 13)) (0.4.2)\n    Requirement already satisfied: six>=1.5 in /home/yhc97/.local/lib/python3.8/site-packages (from python-dateutil>=2.6.1->pandas->-r requirements.txt (line 4)) (1.15.0)\n    Requirement already satisfied: MarkupSafe>=0.23 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from Jinja2>=2.3->sphinx->-r requirements.txt (line 9)) (1.1.1)\n    Requirement already satisfied: certifi>=2017.4.17 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from requests>=2.5.0->sphinx->-r requirements.txt (line 9)) (2019.11.28)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from requests>=2.5.0->sphinx->-r requirements.txt (line 9)) (1.25.7)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from requests>=2.5.0->sphinx->-r requirements.txt (line 9)) (3.0.4)\n    Requirement already satisfied: idna<2.9,>=2.5 in /home/yhc97/anaconda3/lib/python3.8/site-packages (from requests>=2.5.0->sphinx->-r requirements.txt (line 9)) (2.8)\n    Requirement already satisfied: heapdict in /home/yhc97/anaconda3/lib/python3.8/site-packages (from zict>=0.1.3->distributed->-r requirements.txt (line 11)) (1.0.1)\n\n\n\n```python\n# call by keyword\nplanet = armageddon.Planet()\nlocator = armageddon.PostcodeLocator()\n```\n\n\n```python\nparams = {'radius': 60, 'angle': 20, 'strength': 1e6,\n          'density': 3000, 'velocity': 19e3,\n          'lat': 55., 'lon': -2, 'bearing': 180.}\n\nresult = planet.solve_atmospheric_entry(params['radius'], params['velocity'], \n                                        params['density'], params['strength'], params['angle'])\noutcome = planet.analyse_outcome(result=planet.calculate_energy(result))\noutcome\n```\n\n\n\n\n    {'outcome': 'Airburst',\n     'burst_peak_dedz': 12925.271090322896,\n     'burst_altitude': 16460.83220034911,\n     'burst_distance': 238856.6954917025,\n     'burst_energy': 79421.66078548192}\n\n\n\n\n```python\n# use a sample strike event \nzb = outcome['burst_altitude']\nEk = outcome['burst_energy']\n# using the pressure function defined in the DamageMapper.ipynb\nP = lambda r: 3.14 * 10.**11 * ((r**2 + zb**2)/ Ek**(2./3))**(-1.3) + \\\n                1.8 * 10.**7 * ((r**2 + zb**2)/ Ek**(2./3))**(-0.565)\n\nentry_point = [params['lat'], params['lon']]\npressures = [1e3, 3.5e3, 27e3, 43e3]\nblat, blon, damrad = armageddon.damage_zones(outcome, entry_point[0], entry_point[1], params['bearing'], pressures)\nburst_point = [blat, blon]\n\nx = np.linspace(0, 4e5, 1000)\n\n# verification plots, plotting the damrad on the function P to check the results visually\nplt.plot(x, P(x), label=\"Pressure Function\")\ni = 1\nfor (loc, pres) in zip(damrad, pressures):\n    plt.plot(loc, pres, 'o', label='damage level: ' + str(i) + ' boundary')\n    plt.hlines(pres, 0, loc, linestyles='dashed')\n    i += 1\nplt.title(\"Damage radius of the sample burst\")\nplt.legend()\n```\n\n## Extension one\n\nFollowing cells show how the different damage zone and population data can be plotted on the map for effective risk assessment and evacuation planning\n\n\n```python\n# The mapper function then plot the damage zones onto google maps\narmageddon.plot_damage_zones(entry_point, burst_point, damrad)\n```\n\n\n\n\n<div style=\"width:100%;\"><div style=\"position:relative;width:100%;height:0;padding-bottom:60%;\"><span style=\"color:#565656\">Make this Notebook Trusted to load map: File -> Trust Notebook</span></div></div>\n\n\n\n\n```python\n# to get the impacted postcodes in each damage zone:\nsector = True \nz = locator.get_postcodes_by_radius(burst_point, damrad, sector=sector)\n```\n\n    Number of postcode sectors in damage zone 1: ~10% glass windows shatter: 9269\n    Number of postcode sectors in damage zone 2: ~90% glass windows shatter: 2796\n    Number of postcode sectors in damage zone 3: Wood frame buildings collapse: 113\n    Number of postcode sectors in damage zone 4: Multistory brick buildings collapse: 37\n\n\n\n```python\ndamage_zones = [\n    '1: ~10% glass windows shatter',\n    '2: ~90% glass windows shatter',\n    '3: Wood frame buildings collapse',\n    '4: Multistory brick buildings collapse'\n]\n\nfor i in range(len(z)):\n    if sector:\n        print('Number of postcode sectors in damage zone ' + damage_zones[i] + ': ' + str(len(z[i])))\n    else:\n        print('Number of postcodes in damage zone ' + damage_zones[i] + ': ' + str(len(z[i])))\n```\n\n    Number of postcode sectors in damage zone 1: ~10% glass windows shatter: 9269\n    Number of postcode sectors in damage zone 2: ~90% glass windows shatter: 2796\n    Number of postcode sectors in damage zone 3: Wood frame buildings collapse: 113\n    Number of postcode sectors in damage zone 4: Multistory brick buildings collapse: 37\n\n\n\n```python\n# to calculate the population affected in each damage zones\n[p1, p2, p3, p4] = locator.get_population_of_postcode(z, sector=sector)\n```\n\n    estimaed population in damage zone 1 by postcode sector data: 53740669\n    estimaed population in damage zone 2 by postcode sector data: 16242468\n    estimaed population in damage zone 3 by postcode sector data: 765397\n    estimaed population in damage zone 4 by postcode sector data: 293389\n\n\n\n```python\np = [int(sum(p1)), int(sum(p2)), int(sum(p3)), int(sum(p4))]\nfor i in range(len(p)):\n    if sector:\n        print('estimaed population in damage zone ' + str(i+1) + ' by postcode sector data: ' + str(p[i]))\n    else:\n        print('estimaed population in damage zone ' + str(i+1) + ' by postcode data: ' + str(p[i]))\n```\n\n    estimaed population in damage zone 1 by postcode sector data: 53740669\n    estimaed population in damage zone 2 by postcode sector data: 16242468\n    estimaed population in damage zone 3 by postcode sector data: 765397\n    estimaed population in damage zone 4 by postcode sector data: 293389\n\n\n## Extension 2: Uncertainty Analysis\n\nUtilising the input parametres used above for Extension 1, plus the standard deviations of the variables provided in the DamageMapper.ipynb notebook, an example of the impact risk analysis is conducted below.\n\n\n```python\nfiducial_stdevs = {'radius': 1, 'angle': 1, 'strength': 5e5,\n               'density': 500, 'velocity': 1e3,\n               'lat': 0.025, 'lon': 0.025, 'bearing': 0.5}\n\n# call by keyword\nresult = armageddon.impact_risk(planet, means=params, stdevs=fiducial_stdevs,\n            pressure=27.e3, nsamples=100, sector=True)\n# showing the top 5 risky postcode sectors in this example\nresult.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>risk</th>\n    </tr>\n    <tr>\n      <th>sector</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>ST163</th>\n      <td>14172.30</td>\n    </tr>\n    <tr>\n      <th>ST179</th>\n      <td>12609.36</td>\n    </tr>\n    <tr>\n      <th>WS124</th>\n      <td>12151.62</td>\n    </tr>\n    <tr>\n      <th>WS152</th>\n      <td>11820.80</td>\n    </tr>\n    <tr>\n      <th>ST158</th>\n      <td>11452.16</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n# Breaking News Example\n\nAsteroid fact file:\n\n \n\nSize: approximately 20-m radius\nComposition: iron (typical density, 8000 kg/m^3; typical strength, 10 MPa)\nSpeed: 17 km/s\n\n \n\nThe asteroid is expected to enter Earth\u2019s atmosphere (100-km altitude) at coordinates (53.79, -3.55), over the Irish Sea, on a bearing of 112 degrees and at an angle of 45 degrees to the horizontal.\n\n\n```python\nparams = {'radius': 20, 'angle': 45., 'strength': 10e6,\n          'density': 8000, 'velocity': 17e3,\n          'lat': 53.79, 'lon': -3.55, 'bearing': 112.}\nstdevs = {'radius': 1, 'angle': 1, 'strength': 5e5,\n          'density': 500, 'velocity': 1e3,\n          'lat': 0.025, 'lon': 0.025, 'bearing': 0.5}\n```\n\n## Study of the mean case\n\n\n```python\nresult = planet.solve_atmospheric_entry(params['radius'], params['velocity'], \n                                        params['density'], params['strength'], params['angle'])\noutcome = planet.analyse_outcome(result=planet.calculate_energy(result))\n```\n\n\n```python\nzb = outcome['burst_altitude']\nEk = outcome['burst_energy']\n# using the pressure function defined in the DamageMapper.ipynb\nP = lambda r: 3.14 * 10.**11 * ((r**2 + zb**2)/ Ek**(2./3))**(-1.3) + \\\n                1.8 * 10.**7 * ((r**2 + zb**2)/ Ek**(2./3))**(-0.565)\n\nentry_point = [params['lat'], params['lon']]\npressures = [1e3, 3.5e3, 27e3, 43e3]\nblat, blon, damrad = armageddon.damage_zones(outcome, entry_point[0], entry_point[1], params['bearing'], pressures)\nburst_point = [blat, blon]\n\nx = np.linspace(0, 4e5, 1000)\n\n# verification plots, plotting the damrad on the function P to check the results visually\nplt.plot(x, P(x), label=\"Pressure Function\")\ni = 1\nfor (loc, pres) in zip(damrad, pressures):\n    plt.plot(loc, pres, 'o', label='damage level: ' + str(i) + ' boundary')\n    plt.hlines(pres, 0, loc, linestyles='dashed')\n    i += 1\nplt.title(\"Damage radius of the sample burst\")\nplt.legend()\n```\n\n\n```python\n# to get the impacted postcodes in each damage zone:\nsector_op = True \n# %timeit locator.get_postcodes_by_radius(burst_point, damrad, sector=sector_op)\nz = locator.get_postcodes_by_radius(burst_point, damrad, sector=sector_op)\n```\n\n\n```python\ndamage_zones = [\n    '1: ~10% glass windows shatter',\n    '2: ~90% glass windows shatter',\n    '3: Wood frame buildings collapse',\n    '4: Multistory brick buildings collapse'\n]\n\nfor i in range(len(z)):\n    if sector_op:\n        print('Number of postcode sectors in damage zone ' + damage_zones[i] + ': ' + str(len(z[i])))\n    else:\n        print('Number of postcodes in damage zone ' + damage_zones[i] + ': ' + str(len(z[i])))\n```\n\n    Number of postcode sectors in damage zone 1: ~10% glass windows shatter: 3022\n    Number of postcode sectors in damage zone 2: ~90% glass windows shatter: 851\n    Number of postcode sectors in damage zone 3: Wood frame buildings collapse: 145\n\n\n\n```python\n# to calculate the population affected in each damage zones\n[p1, p2, p3] = locator.get_population_of_postcode(z, sector=sector_op)\n```\n\n\n```python\np = [int(sum(p1)), int(sum(p2)), int(sum(p3))]\nfor i in range(len(p)):\n    if sector_op:\n        print('estimaed population in damage zone ' + str(i+1) + ' by postcode sector data: ' + str(p[i]))\n    else:\n        print('estimaed population in damage zone ' + str(i+1) + ' by postcode data: ' + str(p[i]))\n```\n\n    estimaed population in damage zone 1 by postcode sector data: 16482024\n    estimaed population in damage zone 2 by postcode sector data: 4916634\n    estimaed population in damage zone 3 by postcode sector data: 713643\n\n\n\n```python\narmageddon.plot_damage_zones(entry_point, burst_point, damrad, p)\n```\n\n\n\n\n<div style=\"width:100%;\"><div style=\"position:relative;width:100%;height:0;padding-bottom:60%;\"><span style=\"color:#565656\">Make this Notebook Trusted to load map: File -> Trust Notebook</span></div></div>\n\n\n\n## Full Impact Risk Analysis\n\n\n```python\n# call by keyword\nresult = armageddon.impact_risk(planet, means=params, stdevs=fiducial_stdevs,\n            pressure=27.e3, nsamples=100, sector=True)\n# showing the top 5 risky postcode sectors in this example\nresult.head()\n```\n", "meta": {"hexsha": "85e8a3a64db20b33a6b4bfea12defd8ea481dda0", "size": 108696, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "damage_mapper_example.ipynb", "max_stars_repo_name": "acse-cxd20/Armageddon", "max_stars_repo_head_hexsha": "b3d4d9d0ea90a5213aed2f72e9e86be428de56bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "damage_mapper_example.ipynb", "max_issues_repo_name": "acse-cxd20/Armageddon", "max_issues_repo_head_hexsha": "b3d4d9d0ea90a5213aed2f72e9e86be428de56bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "damage_mapper_example.ipynb", "max_forks_repo_name": "acse-cxd20/Armageddon", "max_forks_repo_head_hexsha": "b3d4d9d0ea90a5213aed2f72e9e86be428de56bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 160.5553914328, "max_line_length": 24320, "alphanum_fraction": 0.8123390005, "converted": true, "num_tokens": 6063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577490717496246, "lm_q2_score": 0.06465348475172761, "lm_q1q2_score": 0.02300208753608374}}
{"text": "```python\n #this code snippet was used to import our custom dataset\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n\n\n\n```python\n# import all necessary modules\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport librosa, librosa.display\nimport numpy as np\nimport sympy as sp\nsp.init_printing(use_latex=True)\nfrom IPython.display import display\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\n\n```python\n# set the variables to work with throughout model\nimg_height = 256\nimg_width= 256\nrgb = 3\nbatch_size = 10  \nepochs = 50\n```\n\n\n```python\n# set-up training data from the original dataset only\nods_train = tf.keras.preprocessing.image_dataset_from_directory(\n    '/content/drive/MyDrive/original_data_set', # need local path to directory\n    labels = 'inferred',\n    label_mode = 'categorical',\n    batch_size = batch_size,\n    image_size = (img_height, img_height),\n    shuffle = True,\n    seed = 123,\n    validation_split = 0.3,\n    subset = 'training',\n)\n```\n\n    Found 3000 files belonging to 10 classes.\n    Using 2100 files for training.\n\n\n\n```python\n# set-up training data using original plus the augmented data as well\nplusAugmented_train = tf.keras.preprocessing.image_dataset_from_directory(\n    '/content/drive/MyDrive/plusAugmented', # need local path to directory\n    labels = 'inferred',\n    label_mode = 'categorical',\n    batch_size = batch_size,\n    image_size = (img_height, img_height),\n    shuffle = True,\n    seed = 123,\n    validation_split = 0.3,\n    subset = 'training',\n)\n```\n\n    Found 32898 files belonging to 10 classes.\n    Using 23029 files for training.\n\n\n\n```python\n# now create a batch to test with from original dataset\nods_test = tf.keras.preprocessing.image_dataset_from_directory(\n    '/content/drive/MyDrive/original_data_set', # need local path to directory\n    labels = 'inferred',\n    label_mode = 'categorical',\n    batch_size = batch_size,\n    image_size = (img_height, img_height),\n    shuffle = True,\n    seed = 456,\n    validation_split = 0.3,\n    subset = \"validation\",\n)\n```\n\n    Found 3000 files belonging to 10 classes.\n    Using 900 files for validation.\n\n\n\n```python\n# also need a batch to test with from the original plus augmented datase\nplusAugmented_test = tf.keras.preprocessing.image_dataset_from_directory(\n    '/content/drive/MyDrive/plusAugmented', # need local path to directory\n    labels = 'inferred',\n    label_mode = 'categorical',\n    batch_size = batch_size,\n    image_size = (img_height, img_height),\n    shuffle = True,\n    seed = 456,\n    validation_split = 0.3,\n    subset = \"validation\",\n)\n```\n\n    Found 32898 files belonging to 10 classes.\n    Using 9869 files for validation.\n\n\n\n```python\n# the real test....\n# NOW, a batch of unseen originals the plusAugmented model has not seen\nunseen_test= tf.keras.preprocessing.image_dataset_from_directory(\n    '/content/drive/MyDrive/unseen_originals', # need local path to directory\n    labels = 'inferred',\n    label_mode = 'categorical',\n    batch_size = batch_size,\n    image_size = (img_height, img_height),\n    shuffle = True,\n    seed = 456,\n)\n```\n\n    Found 102 files belonging to 10 classes.\n\n\n\n```python\n#  build up model\nmodel = keras.models.Sequential()\nmodel.add(keras.layers.Convolution2D(32, kernel_size = (5, 5), input_shape=(img_height, img_width, rgb ), activation='relu'))\nmodel.add(keras.layers.Convolution2D(16, kernel_size = (3, 3), activation='relu'))\nmodel.add(keras.layers.BatchNormalization())\nmodel.add(keras.layers.MaxPooling2D(pool_size=(2, 2)))\nmodel.add(keras.layers.Dropout(0.2))\nmodel.add(keras.layers.Reshape((125, -1)))\nmodel.add(keras.layers.TimeDistributed(layers.Dense(100)))\nmodel.add(keras.layers.LSTM(100, return_sequences=False))\nmodel.add(keras.layers.Dense(10,activation = 'softmax'))\n```\n\n\n```python\n# display model layers w/ input and output\ntf.keras.utils.plot_model(model, show_shapes=True, expand_nested=True)\n```\n\n\n```python\n#  compile model\nmodel.compile(optimizer = keras.optimizers.Adam(),\n             loss = [ keras.losses.CategoricalCrossentropy(from_logits=True)],\n             metrics = [ keras.metrics.CategoricalAccuracy()])\n```\n\n\n```python\n# show a summary of layers and the parameters\nmodel.summary()\n```\n\n    Model: \"sequential\"\n    _________________________________________________________________\n    Layer (type)                 Output Shape              Param #   \n    =================================================================\n    conv2d (Conv2D)              (None, 252, 252, 32)      2432      \n    _________________________________________________________________\n    conv2d_1 (Conv2D)            (None, 250, 250, 16)      4624      \n    _________________________________________________________________\n    batch_normalization (BatchNo (None, 250, 250, 16)      64        \n    _________________________________________________________________\n    max_pooling2d (MaxPooling2D) (None, 125, 125, 16)      0         \n    _________________________________________________________________\n    dropout (Dropout)            (None, 125, 125, 16)      0         \n    _________________________________________________________________\n    reshape (Reshape)            (None, 125, 2000)         0         \n    _________________________________________________________________\n    time_distributed (TimeDistri (None, 125, 100)          200100    \n    _________________________________________________________________\n    lstm (LSTM)                  (None, 100)               80400     \n    _________________________________________________________________\n    dense_1 (Dense)              (None, 10)                1010      \n    =================================================================\n    Total params: 288,630\n    Trainable params: 288,598\n    Non-trainable params: 32\n    _________________________________________________________________\n\n\n\n```python\n# training the original dataset\nods_history = model.fit(ods_train,\n                    batch_size = batch_size,\n                    epochs = epochs,\n                    verbose = 1)\n```\n\n    Epoch 1/50\n    210/210 [==============================] - 16s 60ms/step - loss: 2.1985 - categorical_accuracy: 0.1994\n    Epoch 2/50\n    210/210 [==============================] - 13s 61ms/step - loss: 1.8076 - categorical_accuracy: 0.3596\n    Epoch 3/50\n    210/210 [==============================] - 13s 61ms/step - loss: 1.5699 - categorical_accuracy: 0.4344\n    Epoch 4/50\n    210/210 [==============================] - 13s 63ms/step - loss: 1.3776 - categorical_accuracy: 0.5302\n    Epoch 5/50\n    210/210 [==============================] - 14s 63ms/step - loss: 1.2153 - categorical_accuracy: 0.5917\n    Epoch 6/50\n    210/210 [==============================] - 13s 63ms/step - loss: 1.2228 - categorical_accuracy: 0.6000\n    Epoch 7/50\n    210/210 [==============================] - 14s 64ms/step - loss: 1.2050 - categorical_accuracy: 0.6108\n    Epoch 8/50\n    210/210 [==============================] - 13s 63ms/step - loss: 1.1002 - categorical_accuracy: 0.6396\n    Epoch 9/50\n    210/210 [==============================] - 13s 62ms/step - loss: 1.0108 - categorical_accuracy: 0.6576\n    Epoch 10/50\n    210/210 [==============================] - 13s 61ms/step - loss: 0.9910 - categorical_accuracy: 0.6684\n    Epoch 11/50\n    210/210 [==============================] - 13s 60ms/step - loss: 0.8780 - categorical_accuracy: 0.7239\n    Epoch 12/50\n    210/210 [==============================] - 13s 60ms/step - loss: 0.8507 - categorical_accuracy: 0.7324\n    Epoch 13/50\n    210/210 [==============================] - 13s 61ms/step - loss: 0.8468 - categorical_accuracy: 0.7428\n    Epoch 14/50\n    210/210 [==============================] - 13s 61ms/step - loss: 0.8723 - categorical_accuracy: 0.7078\n    Epoch 15/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.9129 - categorical_accuracy: 0.6928\n    Epoch 16/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.7908 - categorical_accuracy: 0.7449\n    Epoch 17/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.8310 - categorical_accuracy: 0.7211\n    Epoch 18/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.7568 - categorical_accuracy: 0.7535\n    Epoch 19/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.7254 - categorical_accuracy: 0.7633\n    Epoch 20/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.6462 - categorical_accuracy: 0.7766\n    Epoch 21/50\n    210/210 [==============================] - 13s 60ms/step - loss: 0.6637 - categorical_accuracy: 0.7763\n    Epoch 22/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.6727 - categorical_accuracy: 0.7800\n    Epoch 23/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.6600 - categorical_accuracy: 0.7813\n    Epoch 24/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.6160 - categorical_accuracy: 0.8011\n    Epoch 25/50\n    210/210 [==============================] - 13s 60ms/step - loss: 0.6095 - categorical_accuracy: 0.8071\n    Epoch 26/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.5478 - categorical_accuracy: 0.8356\n    Epoch 27/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.5455 - categorical_accuracy: 0.8211\n    Epoch 28/50\n    210/210 [==============================] - 13s 60ms/step - loss: 0.4764 - categorical_accuracy: 0.8603\n    Epoch 29/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.5469 - categorical_accuracy: 0.8191\n    Epoch 30/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.5579 - categorical_accuracy: 0.8189\n    Epoch 31/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.5841 - categorical_accuracy: 0.8078\n    Epoch 32/50\n    210/210 [==============================] - 13s 60ms/step - loss: 0.5836 - categorical_accuracy: 0.8092\n    Epoch 33/50\n    210/210 [==============================] - 13s 58ms/step - loss: 0.5312 - categorical_accuracy: 0.8281\n    Epoch 34/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.5205 - categorical_accuracy: 0.8249\n    Epoch 35/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.4781 - categorical_accuracy: 0.8520\n    Epoch 36/50\n    210/210 [==============================] - 13s 60ms/step - loss: 0.4859 - categorical_accuracy: 0.8465\n    Epoch 37/50\n    210/210 [==============================] - 13s 58ms/step - loss: 0.4388 - categorical_accuracy: 0.8530\n    Epoch 38/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.4737 - categorical_accuracy: 0.8484\n    Epoch 39/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.4537 - categorical_accuracy: 0.8574\n    Epoch 40/50\n    210/210 [==============================] - 13s 58ms/step - loss: 0.3783 - categorical_accuracy: 0.8761\n    Epoch 41/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.3696 - categorical_accuracy: 0.8820\n    Epoch 42/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.5071 - categorical_accuracy: 0.8319\n    Epoch 43/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.4509 - categorical_accuracy: 0.8564\n    Epoch 44/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.4206 - categorical_accuracy: 0.8599\n    Epoch 45/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.4481 - categorical_accuracy: 0.8515\n    Epoch 46/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.3741 - categorical_accuracy: 0.8804\n    Epoch 47/50\n    210/210 [==============================] - 13s 60ms/step - loss: 0.3598 - categorical_accuracy: 0.8770\n    Epoch 48/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.3476 - categorical_accuracy: 0.8827\n    Epoch 49/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.3824 - categorical_accuracy: 0.8696\n    Epoch 50/50\n    210/210 [==============================] - 13s 59ms/step - loss: 0.3798 - categorical_accuracy: 0.8693\n\n\n\n```python\n# how did we do?\n# graphically display results of training and testing\nplt.figure()\nplt.subplot(211)\nplt.plot(ods_history.history['categorical_accuracy'])\nplt.title('Using Only Original Data: Model Accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['training'], loc = 'upper left')\n\nplt.subplot(212)\nplt.plot(ods_history.history['loss'])\nplt.title('Using Only Origianl Data: Model Loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['training'], loc = 'upper right')\n\nplt.tight_layout()\nplt.show()\n```\n\n\n```python\n# go ahead and save the model here\nmodel.save(\"ods_32_d.h5\")\n```\n\n\n```python\n# now test the model against the reserved unseen images from the original dataset\nods_t = model.evaluate(ods_test, verbose = 1)\nprint(\"Using only original unseen samples:\")\nprint(\"Accuracy: \", ods_t[1] * 100)\nprint(\"Loss: \", ods_t[0])\n```\n\n    90/90 [==============================] - 5s 43ms/step - loss: 0.5985 - categorical_accuracy: 0.8011\n    Using only original unseen samples:\n    Accuracy:  80.1111102104187\n    Loss:  0.5984845161437988\n\n\n\n```python\n# next, we need to train with the original plus the augmented data on the exact same architecture\nplusAugmented_history = model.fit(plusAugmented_train,\n                    batch_size = batch_size,\n                    epochs = epochs,\n                    verbose = 1)\n```\n\n    Epoch 1/50\n    2303/2303 [==============================] - 141s 61ms/step - loss: 1.2448 - categorical_accuracy: 0.6015\n    Epoch 2/50\n    2303/2303 [==============================] - 142s 62ms/step - loss: 1.0001 - categorical_accuracy: 0.6659\n    Epoch 3/50\n    2303/2303 [==============================] - 147s 64ms/step - loss: 0.9219 - categorical_accuracy: 0.6958\n    Epoch 4/50\n    2303/2303 [==============================] - 146s 63ms/step - loss: 0.8544 - categorical_accuracy: 0.7167\n    Epoch 5/50\n    2303/2303 [==============================] - 147s 64ms/step - loss: 0.8145 - categorical_accuracy: 0.7293\n    Epoch 6/50\n    2303/2303 [==============================] - 147s 64ms/step - loss: 0.7268 - categorical_accuracy: 0.7588\n    Epoch 7/50\n    2303/2303 [==============================] - 147s 64ms/step - loss: 0.7168 - categorical_accuracy: 0.7646\n    Epoch 8/50\n    2303/2303 [==============================] - 148s 64ms/step - loss: 0.6706 - categorical_accuracy: 0.7776\n    Epoch 9/50\n    2303/2303 [==============================] - 147s 64ms/step - loss: 0.6285 - categorical_accuracy: 0.7934\n    Epoch 10/50\n    2303/2303 [==============================] - 148s 64ms/step - loss: 0.5881 - categorical_accuracy: 0.8061\n    Epoch 11/50\n    2303/2303 [==============================] - 148s 64ms/step - loss: 0.5617 - categorical_accuracy: 0.8121\n    Epoch 12/50\n    2303/2303 [==============================] - 142s 61ms/step - loss: 0.6013 - categorical_accuracy: 0.7988\n    Epoch 13/50\n    2303/2303 [==============================] - 142s 62ms/step - loss: 0.5037 - categorical_accuracy: 0.8329\n    Epoch 14/50\n    2303/2303 [==============================] - 145s 63ms/step - loss: 0.7385 - categorical_accuracy: 0.7595\n    Epoch 15/50\n    2303/2303 [==============================] - 146s 63ms/step - loss: 0.5494 - categorical_accuracy: 0.8176\n    Epoch 16/50\n    2303/2303 [==============================] - 147s 64ms/step - loss: 0.5320 - categorical_accuracy: 0.8244\n    Epoch 17/50\n    2303/2303 [==============================] - 145s 63ms/step - loss: 0.5033 - categorical_accuracy: 0.8343\n    Epoch 18/50\n    2303/2303 [==============================] - 146s 63ms/step - loss: 0.4641 - categorical_accuracy: 0.8478\n    Epoch 19/50\n    2303/2303 [==============================] - 146s 63ms/step - loss: 0.4581 - categorical_accuracy: 0.8483\n    Epoch 20/50\n    2303/2303 [==============================] - 150s 65ms/step - loss: 0.4353 - categorical_accuracy: 0.8567\n    Epoch 21/50\n    2303/2303 [==============================] - 151s 66ms/step - loss: 0.4247 - categorical_accuracy: 0.8572\n    Epoch 22/50\n    2303/2303 [==============================] - 147s 64ms/step - loss: 0.4126 - categorical_accuracy: 0.8633\n    Epoch 23/50\n    2303/2303 [==============================] - 144s 62ms/step - loss: 0.3769 - categorical_accuracy: 0.8766\n    Epoch 24/50\n    2303/2303 [==============================] - 142s 61ms/step - loss: 0.3848 - categorical_accuracy: 0.8731\n    Epoch 25/50\n    2303/2303 [==============================] - 143s 62ms/step - loss: 0.3756 - categorical_accuracy: 0.8765\n    Epoch 26/50\n    2303/2303 [==============================] - 143s 62ms/step - loss: 0.3608 - categorical_accuracy: 0.8793\n    Epoch 27/50\n    2303/2303 [==============================] - 143s 62ms/step - loss: 0.3639 - categorical_accuracy: 0.8790\n    Epoch 28/50\n    2303/2303 [==============================] - 143s 62ms/step - loss: 0.3475 - categorical_accuracy: 0.8858\n    Epoch 29/50\n    2303/2303 [==============================] - 142s 61ms/step - loss: 0.3382 - categorical_accuracy: 0.8885\n    Epoch 30/50\n    2303/2303 [==============================] - 141s 61ms/step - loss: 0.3393 - categorical_accuracy: 0.8868\n    Epoch 31/50\n    2303/2303 [==============================] - 142s 61ms/step - loss: 0.3247 - categorical_accuracy: 0.8931\n    Epoch 32/50\n    2303/2303 [==============================] - 140s 61ms/step - loss: 0.3300 - categorical_accuracy: 0.8893\n    Epoch 33/50\n    2303/2303 [==============================] - 143s 62ms/step - loss: 0.3284 - categorical_accuracy: 0.8902\n    Epoch 34/50\n    2303/2303 [==============================] - 144s 63ms/step - loss: 0.3189 - categorical_accuracy: 0.8966\n    Epoch 35/50\n    2303/2303 [==============================] - 143s 62ms/step - loss: 0.3142 - categorical_accuracy: 0.8968\n    Epoch 36/50\n    2303/2303 [==============================] - 141s 61ms/step - loss: 0.3026 - categorical_accuracy: 0.9006\n    Epoch 37/50\n    2303/2303 [==============================] - 145s 63ms/step - loss: 0.3047 - categorical_accuracy: 0.9011\n    Epoch 38/50\n    2303/2303 [==============================] - 145s 63ms/step - loss: 0.3159 - categorical_accuracy: 0.8966\n    Epoch 39/50\n    2303/2303 [==============================] - 146s 63ms/step - loss: 0.3408 - categorical_accuracy: 0.8895\n    Epoch 40/50\n    2303/2303 [==============================] - 146s 63ms/step - loss: 0.2838 - categorical_accuracy: 0.9063\n    Epoch 41/50\n    2303/2303 [==============================] - 147s 64ms/step - loss: 0.2766 - categorical_accuracy: 0.9082\n    Epoch 42/50\n    2303/2303 [==============================] - 148s 64ms/step - loss: 0.2979 - categorical_accuracy: 0.9014\n    Epoch 43/50\n    2303/2303 [==============================] - 146s 63ms/step - loss: 0.3041 - categorical_accuracy: 0.8980\n    Epoch 44/50\n    2303/2303 [==============================] - 147s 64ms/step - loss: 0.2905 - categorical_accuracy: 0.9026\n    Epoch 45/50\n    2303/2303 [==============================] - 146s 63ms/step - loss: 0.2979 - categorical_accuracy: 0.9025\n    Epoch 46/50\n    2303/2303 [==============================] - 149s 64ms/step - loss: 0.3049 - categorical_accuracy: 0.9015\n    Epoch 47/50\n    2303/2303 [==============================] - 147s 64ms/step - loss: 0.2848 - categorical_accuracy: 0.9062\n    Epoch 48/50\n    2303/2303 [==============================] - 149s 64ms/step - loss: 0.2928 - categorical_accuracy: 0.9023\n    Epoch 49/50\n    2303/2303 [==============================] - 148s 64ms/step - loss: 0.3199 - categorical_accuracy: 0.8925\n    Epoch 50/50\n    2303/2303 [==============================] - 151s 65ms/step - loss: 0.2840 - categorical_accuracy: 0.9084\n\n\n\n```python\n# save one last time\nmodel.save(\"pA_32_c.h5\")\n```\n\n\n```python\n# how did we do?\n# graphically display results of training\nplt.figure()\nplt.subplot(211)\nplt.plot(plusAugmented_history.history['categorical_accuracy'])\nplt.title('Using Augmented Plus Origianl Data: Model Accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['training'], loc = 'upper left')\n\nplt.subplot(212)\nplt.plot(plusAugmented_history.history['loss'])\nplt.title('Using Augmented Plus Original Data: Model Loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['training'], loc = 'upper right')\n\nplt.tight_layout()\nplt.show()\nplt.show()\n```\n\n\n```python\n# now let's test with unseen images from the augmented plus original dataset\nplusAugment_history_test = model.evaluate(plusAugmented_test, verbose = 1)\nprint(\"Using the augmented plus original samples:\")\nprint(\"Accuracy: \", plusAugment_history_test[1] * 100)\nprint(\"Loss: \", plusAugment_history_test[0])\n```\n\n    987/987 [==============================] - 50s 51ms/step - loss: 0.2230 - categorical_accuracy: 0.9245\n    Using the augmented plus original samples:\n    Accuracy:  92.45110750198364\n    Loss:  0.22302104532718658\n\n\n\n```python\n# NOW, let's test the plusAugmented model with 100 super secret unseen original images\nunseen_test_history = model.evaluate(unseen_test, verbose = 1)\nprint(\"Using unseen originals only:\")\nprint(\"Accuracy: \", unseen_test_history[1] * 100)\nprint(\"Loss: \", unseen_test_history[0])\n```\n\n    11/11 [==============================] - 1s 20ms/step - loss: 0.1813 - categorical_accuracy: 0.9510\n    Using unseen originals only:\n    Accuracy:  95.09803652763367\n    Loss:  0.1812841147184372\n\n", "meta": {"hexsha": "24a5e52f49c54b5b24c60590624665f38162415d", "size": 189946, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Code/PROJ_CODE_32.ipynb", "max_stars_repo_name": "CSCI4850/s21-team7-project", "max_stars_repo_head_hexsha": "c3652a117efacd166f2074b228f2f4c303131e4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/PROJ_CODE_32.ipynb", "max_issues_repo_name": "CSCI4850/s21-team7-project", "max_issues_repo_head_hexsha": "c3652a117efacd166f2074b228f2f4c303131e4e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/PROJ_CODE_32.ipynb", "max_forks_repo_name": "CSCI4850/s21-team7-project", "max_forks_repo_head_hexsha": "c3652a117efacd166f2074b228f2f4c303131e4e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-12T20:48:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-05T01:46:22.000Z", "avg_line_length": 224.7881656805, "max_line_length": 98366, "alphanum_fraction": 0.8701841576, "converted": true, "num_tokens": 6630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473631961697, "lm_q2_score": 0.05340332452690107, "lm_q1q2_score": 0.022971299231155835}}
{"text": "# NLP Text Processing methods\n\n\n\n\n### NLTK\n\nWe can use some available data sets for educational purpose. One of such source are NLTK book corporas. To download it we need to do the following:\n\n\n```python\nimport nltk\nnltk.download('book')\n```\n\n    [nltk_data] Downloading collection 'book'\n    [nltk_data]    | \n    [nltk_data]    | Downloading package abc to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/abc.zip.\n    [nltk_data]    | Downloading package brown to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/brown.zip.\n    [nltk_data]    | Downloading package chat80 to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/chat80.zip.\n    [nltk_data]    | Downloading package cmudict to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/cmudict.zip.\n    [nltk_data]    | Downloading package conll2000 to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/conll2000.zip.\n    [nltk_data]    | Downloading package conll2002 to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/conll2002.zip.\n    [nltk_data]    | Downloading package dependency_treebank to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/dependency_treebank.zip.\n    [nltk_data]    | Downloading package genesis to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/genesis.zip.\n    [nltk_data]    | Downloading package gutenberg to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/gutenberg.zip.\n    [nltk_data]    | Downloading package ieer to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/ieer.zip.\n    [nltk_data]    | Downloading package inaugural to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/inaugural.zip.\n    [nltk_data]    | Downloading package movie_reviews to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/movie_reviews.zip.\n    [nltk_data]    | Downloading package nps_chat to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/nps_chat.zip.\n    [nltk_data]    | Downloading package names to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/names.zip.\n    [nltk_data]    | Downloading package ppattach to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/ppattach.zip.\n    [nltk_data]    | Downloading package reuters to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    | Downloading package senseval to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/senseval.zip.\n    [nltk_data]    | Downloading package state_union to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/state_union.zip.\n    [nltk_data]    | Downloading package stopwords to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/stopwords.zip.\n    [nltk_data]    | Downloading package swadesh to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/swadesh.zip.\n    [nltk_data]    | Downloading package timit to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/timit.zip.\n    [nltk_data]    | Downloading package treebank to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/treebank.zip.\n    [nltk_data]    | Downloading package toolbox to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/toolbox.zip.\n    [nltk_data]    | Downloading package udhr to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/udhr.zip.\n    [nltk_data]    | Downloading package udhr2 to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/udhr2.zip.\n    [nltk_data]    | Downloading package unicode_samples to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/unicode_samples.zip.\n    [nltk_data]    | Downloading package webtext to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/webtext.zip.\n    [nltk_data]    | Downloading package wordnet to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/wordnet.zip.\n    [nltk_data]    | Downloading package wordnet_ic to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/wordnet_ic.zip.\n    [nltk_data]    | Downloading package words to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/words.zip.\n    [nltk_data]    | Downloading package maxent_treebank_pos_tagger to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping taggers/maxent_treebank_pos_tagger.zip.\n    [nltk_data]    | Downloading package maxent_ne_chunker to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping chunkers/maxent_ne_chunker.zip.\n    [nltk_data]    | Downloading package universal_tagset to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping taggers/universal_tagset.zip.\n    [nltk_data]    | Downloading package punkt to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping tokenizers/punkt.zip.\n    [nltk_data]    | Downloading package book_grammars to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping grammars/book_grammars.zip.\n    [nltk_data]    | Downloading package city_database to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping corpora/city_database.zip.\n    [nltk_data]    | Downloading package tagsets to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping help/tagsets.zip.\n    [nltk_data]    | Downloading package panlex_swadesh to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    | Downloading package averaged_perceptron_tagger to\n    [nltk_data]    |     /home/kprzystalski/nltk_data...\n    [nltk_data]    |   Unzipping taggers/averaged_perceptron_tagger.zip.\n    [nltk_data]    | \n    [nltk_data]  Done downloading collection book\n\n\n\n\n\n    True\n\n\n\nTo check what kind of books are available we need to import these and print the list as following:\n\n\n```python\nfrom nltk.book import *\ntexts()\n```\n\n    *** Introductory Examples for the NLTK Book ***\n    Loading text1, ..., text9 and sent1, ..., sent9\n    Type the name of the text or sentence to view it.\n    Type: 'texts()' or 'sents()' to list the materials.\n    text1: Moby Dick by Herman Melville 1851\n    text2: Sense and Sensibility by Jane Austen 1811\n    text3: The Book of Genesis\n    text4: Inaugural Address Corpus\n    text5: Chat Corpus\n    text6: Monty Python and the Holy Grail\n    text7: Wall Street Journal\n    text8: Personals Corpus\n    text9: The Man Who Was Thursday by G . K . Chesterton 1908\n    text1: Moby Dick by Herman Melville 1851\n    text2: Sense and Sensibility by Jane Austen 1811\n    text3: The Book of Genesis\n    text4: Inaugural Address Corpus\n    text5: Chat Corpus\n    text6: Monty Python and the Holy Grail\n    text7: Wall Street Journal\n    text8: Personals Corpus\n    text9: The Man Who Was Thursday by G . K . Chesterton 1908\n\n\nNLTK Text object does have some useful methods that you can find here: [NLTK Text Docs](http://www.nltk.org/api/nltk.html#nltk.text.Text). Some are used below.\n\n#### Word and sentences similarity\n\nWord does have different meanings. This makes the comparison and analysis a bit more complex.\n\n\n```python\ntext6.concordance(\"King\")\n\ntext6.count(\"King\")\n```\n\n    Displaying 25 of 38 matches:\n    CENE 1 : [ wind ] [ clop clop clop ] KING ARTHUR : Whoa there ! [ clop clop cl\n    ragon , from the castle of Camelot . King of the Britons , defeator of the Sax\n     CART - MASTER : I dunno . Must be a king . CUSTOMER : Why ? CART - MASTER : H\n     all over him . SCENE 3 : [ thud ] [ King Arthur music ] [ thud thud thud ] [ \n     Arthur music ] [ thud thud thud ] [ King Arthur music stops ] ARTHUR : Old wo\n    e an inferior ! ARTHUR : Well , I am king ! DENNIS : Oh king , eh , very nice \n    HUR : Well , I am king ! DENNIS : Oh king , eh , very nice . And how d ' you g\n    o you do , good lady . I am Arthur , King of the Britons . Who ' s castle is t\n    s . Who ' s castle is that ? WOMAN : King of the who ? ARTHUR : The Britons . \n    . We are all Britons , and I am your king . WOMAN : I didn ' t know we had a k\n    g . WOMAN : I didn ' t know we had a king . I thought we were an autonomous co\n    ink he is ? Heh . ARTHUR : I am your king ! WOMAN : Well , I didn ' t vote for\n     . WOMAN : Well , how did you become king then ? ARTHUR : The Lady of the Lake\n    inging stops ] That is why I am your king ! DENNIS : Listen , strange women ly\n    ou saw it , didn ' t you SCENE 4 : [ King Arthur music ] [ music stops ] BLACK\n    sic stops ] BLACK KNIGHT : Aaagh ! [ King Arthur music ] [ music stops ] BLACK\n    GHT : Aaagh ! GREEN KNIGHT : Ooh ! [ King Arthur music ] [ music stops ] [ sta\n    NIGHT : Aagh ! GREEN KNIGHT : Oh ! [ King Arthur music ] Ooh ! [ music stops ]\n    Sir Knight . [ pause ] I am Arthur , King of the Britons . [ pause ] I seek th\n    ll die . ARTHUR : I command you , as King of the Britons , to stand aside ! BL\n     of science ? ARTHUR : I am Arthur , King of the Britons . BEDEVERE : My liege\n    e Sir Bedevere was the first to join King Arthur ' s knights , but other illus\n    ngels sing ] GOD : Arthur ! Arthur , King of the Britons ! Oh , don ' t grovel\n     Yes , Lord . GOD : Right ! Arthur , King of the Britons , your Knights of the\n    GALAHAD : God be praised SCENE 8 : [ King Arthur music ] [ clop clop clop ] AR\n\n\n\n\n\n    27\n\n\n\nWe can also build a Corpus from a plain text. See the example below.\n\n\n```python\nfrom nltk.corpus import PlaintextCorpusReader\nfrom nltk.tokenize.regexp import WordPunctTokenizer\nfrom nltk.data import LazyLoader\n\ntrump = PlaintextCorpusReader('../datasets/','trump.txt',word_tokenizer=WordPunctTokenizer(),\n             sent_tokenizer=LazyLoader(\n                 'tokenizers/punkt/english.pickle'),\n             encoding='utf8')\nprint(trump)\ntrump.words()\n```\n\n    <PlaintextCorpusReader in '/home/kprzystalski/workshop/datasets'>\n\n\n\n\n\n    ['Thank', 'you', 'very', 'much', '.', 'Mr', '.', ...]\n\n\n\nCorpuses contain large amount of texts, say multiple books, couple hundreds of articles from various magazines etc. NLTK has chosen a few books from over 25,000 pieces available in the whole dataset. We are going to pick Bible and Shakespeare's Macbeth in order to compare a few statistics between them. Let's take a look at other corporas and check the gutenberg and check the word distribution:\n\n\n```python\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nsns.set_style('whitegrid') # general display style of seaborn\n# how to display plot in notebook, jupyter's magic command\n%matplotlib inline \n\n# Download necessary texts\nnltk.download('gutenberg')\nnltk.download('stopwords')\n\nprint(\"Books available in gutenberg dataset:\")\nnltk.corpus.gutenberg.fileids()\n```\n\n    Books available in gutenberg dataset:\n\n\n    [nltk_data] Downloading package gutenberg to\n    [nltk_data]     /home/kprzystalski/nltk_data...\n    [nltk_data]   Package gutenberg is already up-to-date!\n    [nltk_data] Downloading package stopwords to\n    [nltk_data]     /home/kprzystalski/nltk_data...\n    [nltk_data]   Package stopwords is already up-to-date!\n\n\n\n\n\n    ['austen-emma.txt',\n     'austen-persuasion.txt',\n     'austen-sense.txt',\n     'bible-kjv.txt',\n     'blake-poems.txt',\n     'bryant-stories.txt',\n     'burgess-busterbrown.txt',\n     'carroll-alice.txt',\n     'chesterton-ball.txt',\n     'chesterton-brown.txt',\n     'chesterton-thursday.txt',\n     'edgeworth-parents.txt',\n     'melville-moby_dick.txt',\n     'milton-paradise.txt',\n     'shakespeare-caesar.txt',\n     'shakespeare-hamlet.txt',\n     'shakespeare-macbeth.txt',\n     'whitman-leaves.txt']\n\n\n\n\n```python\nnltk.corpus.stopwords.words(\"english\")\n```\n\n\n\n\n    ['i',\n     'me',\n     'my',\n     'myself',\n     'we',\n     'our',\n     'ours',\n     'ourselves',\n     'you',\n     \"you're\",\n     \"you've\",\n     \"you'll\",\n     \"you'd\",\n     'your',\n     'yours',\n     'yourself',\n     'yourselves',\n     'he',\n     'him',\n     'his',\n     'himself',\n     'she',\n     \"she's\",\n     'her',\n     'hers',\n     'herself',\n     'it',\n     \"it's\",\n     'its',\n     'itself',\n     'they',\n     'them',\n     'their',\n     'theirs',\n     'themselves',\n     'what',\n     'which',\n     'who',\n     'whom',\n     'this',\n     'that',\n     \"that'll\",\n     'these',\n     'those',\n     'am',\n     'is',\n     'are',\n     'was',\n     'were',\n     'be',\n     'been',\n     'being',\n     'have',\n     'has',\n     'had',\n     'having',\n     'do',\n     'does',\n     'did',\n     'doing',\n     'a',\n     'an',\n     'the',\n     'and',\n     'but',\n     'if',\n     'or',\n     'because',\n     'as',\n     'until',\n     'while',\n     'of',\n     'at',\n     'by',\n     'for',\n     'with',\n     'about',\n     'against',\n     'between',\n     'into',\n     'through',\n     'during',\n     'before',\n     'after',\n     'above',\n     'below',\n     'to',\n     'from',\n     'up',\n     'down',\n     'in',\n     'out',\n     'on',\n     'off',\n     'over',\n     'under',\n     'again',\n     'further',\n     'then',\n     'once',\n     'here',\n     'there',\n     'when',\n     'where',\n     'why',\n     'how',\n     'all',\n     'any',\n     'both',\n     'each',\n     'few',\n     'more',\n     'most',\n     'other',\n     'some',\n     'such',\n     'no',\n     'nor',\n     'not',\n     'only',\n     'own',\n     'same',\n     'so',\n     'than',\n     'too',\n     'very',\n     's',\n     't',\n     'can',\n     'will',\n     'just',\n     'don',\n     \"don't\",\n     'should',\n     \"should've\",\n     'now',\n     'd',\n     'll',\n     'm',\n     'o',\n     're',\n     've',\n     'y',\n     'ain',\n     'aren',\n     \"aren't\",\n     'couldn',\n     \"couldn't\",\n     'didn',\n     \"didn't\",\n     'doesn',\n     \"doesn't\",\n     'hadn',\n     \"hadn't\",\n     'hasn',\n     \"hasn't\",\n     'haven',\n     \"haven't\",\n     'isn',\n     \"isn't\",\n     'ma',\n     'mightn',\n     \"mightn't\",\n     'mustn',\n     \"mustn't\",\n     'needn',\n     \"needn't\",\n     'shan',\n     \"shan't\",\n     'shouldn',\n     \"shouldn't\",\n     'wasn',\n     \"wasn't\",\n     'weren',\n     \"weren't\",\n     'won',\n     \"won't\",\n     'wouldn',\n     \"wouldn't\"]\n\n\n\n\n```python\n%matplotlib inline\n\ndef lexical_richness(text: str) -> float:\n  # Unique words in text divided by the total amount of words\n  words = nltk.Text(nltk.corpus.gutenberg.words(text))\n  return len(set(words))/len(words)\n\nmacbeth = \"shakespeare-macbeth.txt\"\nbible = \"bible-kjv.txt\"\n\nprint(\"Macbeth richness: {}\".format(lexical_richness(macbeth)))\nprint(\"Bible richness: {}\".format(lexical_richness(bible)))\n\n# Removing stopwords like: , . and or\nbible_words = [\n    word\n    for word in nltk.corpus.gutenberg.words(bible)\n    if word not in nltk.corpus.stopwords.words(\"english\") and word.isalpha()\n]\n\nwords_distribution = nltk.probability.FreqDist(bible_words)\nprint(\"Words occuring most often in Bible:\") \ndisplay(words_distribution.plot(15))\n```\n\n### Regular expression\n\nThe first solution that comes to our mind when it comes to text processing are regular expression. It is usually the best solution in software development. It is also used in many tools that we have mentioned before. Let's take an example to do a short recap how to use regular expressions in Python.\n\n\n```python\nexample = \"JU is a great company with many great developers.\"\n\nimport re\n\npattern = \"\\\\s+\"\nwords = re.split(pattern, example)\nprint(words)\n```\n\n    ['JU', 'is', 'a', 'great', 'company', 'with', 'many', 'great', 'developers.']\n\n\nPython does have some methods for Strings that can do the same as above, but with less code.\n\n\n```python\nwords = example.split(' ')\nprint(words)\n\ntext = \"Well, what can I say about regexes? \\\nThey are quite annoying to be honest, but once you get a grasp you're gonna be fine. \\\nYeah, I could use some basic boring text, here you go if that's what you miss: \\\nAla ma kota, kot ma Al\u0119. m?ke a m1sta.e and see what happens... \\\nThis sentence: 'Mr. & Mrs. Smith, been looking for easter egg here, failed.\"\ntext.split(' ')\n```\n\n    ['JU', 'is', 'a', 'great', 'company', 'with', 'many', 'great', 'developers.']\n\n\n\n\n\n    ['Well,',\n     'what',\n     'can',\n     'I',\n     'say',\n     'about',\n     'regexes?',\n     'They',\n     'are',\n     'quite',\n     'annoying',\n     'to',\n     'be',\n     'honest,',\n     'but',\n     'once',\n     'you',\n     'get',\n     'a',\n     'grasp',\n     \"you're\",\n     'gonna',\n     'be',\n     'fine.',\n     'Yeah,',\n     'I',\n     'could',\n     'use',\n     'some',\n     'basic',\n     'boring',\n     'text,',\n     'here',\n     'you',\n     'go',\n     'if',\n     \"that's\",\n     'what',\n     'you',\n     'miss:',\n     'Ala',\n     'ma',\n     'kota,',\n     'kot',\n     'ma',\n     'Al\u0119.',\n     'm?ke',\n     'a',\n     'm1sta.e',\n     'and',\n     'see',\n     'what',\n     'happens...',\n     'This',\n     'sentence:',\n     \"'Mr.\",\n     '&',\n     'Mrs.',\n     'Smith,',\n     'been',\n     'looking',\n     'for',\n     'easter',\n     'egg',\n     'here,',\n     'failed.']\n\n\n\nThat was too naive, let's make something more intelligent:\n\n\n```python\nprint(\"Using regex:\")\ndisplay(re.split('(?<=[.!?]) +',text))\n```\n\n    Using regex:\n\n\n\n    ['Well, what can I say about regexes?',\n     \"They are quite annoying to be honest, but once you get a grasp you're gonna be fine.\",\n     \"Yeah, I could use some basic boring text, here you go if that's what you miss: Ala ma kota, kot ma Al\u0119.\",\n     'm?ke a m1sta.e and see what happens...',\n     \"This sentence: 'Mr.\",\n     '& Mrs.',\n     'Smith, been looking for easter egg here, failed.']\n\n\nOur regex only splits the text if either of . ! ? is followed by one or more whitespace signs. This approach is quite powerful, yet limited (as could be seen), keep in mind it has it's uses but is far from perfect (later we will see more sophisticated approaches).\n\nAll in all, when faced with a choice: do something using traditional methods or using machine learning, ALWAYS pick the first one.\n\n\n```python\n# Examples of some other regex functions\n\ntext = re.sub(r\"Mr. & Mrs. Smith\", \"Now works like a charm\", text) #substitute string\nfound_text = re.findall(\", been .*,\", text) # find all occurences of string\ndisplay(found_text)\n\n# findall returns list, we need to access it's element\nre.sub(found_text[0], \" but life\", text)\n```\n\n\n    [', been looking for easter egg here,']\n\n\n\n\n\n    \"Well, what can I say about regexes? They are quite annoying to be honest, but once you get a grasp you're gonna be fine. Yeah, I could use some basic boring text, here you go if that's what you miss: Ala ma kota, kot ma Al\u0119. m?ke a m1sta.e and see what happens... This sentence: 'Now works like a charm but life failed.\"\n\n\n\n### Tokenization\n\nNLTK is a more advanced tool than just regular expressions. We can easily tokenize sentences. Tokenization is a process of getting words from sentences. **Tokenizers** are used to divide a string into it's logical subsets. Above, we have used the sentence tokenizer. Tokenization on the other hand is a common name for dividing a text into separate words and can be done in NLTK using word_tokenizer:\n\n\n```python\ntokens = nltk.word_tokenize(example)\nprint(\"Tokens: \" + str(tokens))\n```\n\n    Tokens: ['JU', 'is', 'a', 'great', 'company', 'with', 'many', 'great', 'developers', '.']\n\n\nAfter a little fun we can use nltk to separate text into sentences in 'smarter' fashion:\n\n\n```python\nfrom nltk.tokenize import sent_tokenize\n\nnltk.download('punkt')\n\nsent_tokenize(text)\n```\n\n    [nltk_data] Downloading package punkt to\n    [nltk_data]     /home/kprzystalski/nltk_data...\n    [nltk_data]   Package punkt is already up-to-date!\n\n\n\n\n\n    ['Well, what can I say about regexes?',\n     \"They are quite annoying to be honest, but once you get a grasp you're gonna be fine.\",\n     \"Yeah, I could use some basic boring text, here you go if that's what you miss: Ala ma kota, kot ma Al\u0119.\",\n     'm?ke a m1sta.e and see what happens...',\n     \"This sentence: 'Now works like a charm, been looking for easter egg here, failed.\"]\n\n\n\n__Tokenizers__ are used to divide a string into it's logical subsets. Above, we\nhave used\nthe sentence tokenizer. __Tokenization__ on the other hand is a common\nname for dividing\na text into separate words and can be done in NLTK using\n__word_tokenizer__:\n\n\n```python\nfrom nltk.tokenize import word_tokenize, TweetTokenizer\nfrom nltk.tokenize import TweetTokenizer # Yes, this tokenizer was based on Tweets\n\ntext = \"This is a cooool #dummysmiley: :-) :-P <3 and some arrows < > -> <--\"\nprint(\"Normal tokenizer:\")\nprint(word_tokenize(text))\n\nprint(\"This tokenizer is better suited for emoji handling\")\ntwitter_tokenizer = TweetTokenizer()\ntwitter_tokenizer.tokenize(text)\n```\n\n    Normal tokenizer:\n    ['This', 'is', 'a', 'cooool', '#', 'dummysmiley', ':', ':', '-', ')', ':', '-P', '<', '3', 'and', 'some', 'arrows', '<', '>', '-', '>', '<', '--']\n    This tokenizer is better suited for emoji handling\n\n\n\n\n\n    ['This',\n     'is',\n     'a',\n     'cooool',\n     '#dummysmiley',\n     ':',\n     ':-)',\n     ':-P',\n     '<3',\n     'and',\n     'some',\n     'arrows',\n     '<',\n     '>',\n     '->',\n     '<--']\n\n\n\nAs you can see there are other tokenizers available and each is focused on\ndifferent\n'kind' of tokenization.\n\nThey are usually implemented as a set of\ncomplicated rules trailed down to certain language\n(e.g. will be different for\npolish and english) and __ARE NOT__ a subset of machine\nlearning (in\nthis part of course at least).\n\nHere are some other NLTK's tokenizers you could\nuse:\n\n- __PunktTokenizer__: been used above for sentence tokenization. This one\nactually uses unsupervised algorithm to infer sentence boundaries.\n- __NISTTokenizer__: tokenizer for non-european text (say in Chinese).\n- __SExprTokenizer__: find parenthesized expressions in strings, see below:\n\n\n```python\nfrom nltk.tokenize import SExprTokenizer\n\nSExprTokenizer().tokenize('(a b (c d)) e f (g)')\n```\n\n\n\n\n    ['(a b (c d))', 'e', 'f', '(g)']\n\n\n\n### Tagging\n\nWhat is great with NLTK is that we can tag each word. A tag give us a meaning of a word. We can think about it as a type of word.\n\n\n```python\ntags = nltk.pos_tag(tokens)\nprint(\"Tagged: \" + str(tags))\n```\n\n    Tagged: [('JU', 'NNP'), ('is', 'VBZ'), ('a', 'DT'), ('great', 'JJ'), ('company', 'NN'), ('with', 'IN'), ('many', 'JJ'), ('great', 'JJ'), ('developers', 'NNS'), ('.', '.')]\n\n\nSome tags are shown in the table below.\n\n| tag  | short | description   |\n|------|-------|---------------|\n| DT   | determiner | all an another any both del each either every half la many much nary neither no some such that the them these this those |\n| IN   | preposition or conjunction, subordinating | astride among uppon whether out inside pro despite on by throughout below within for towards near behind atop around if like until below next into if beside ... |\n| JJ   | adjective or numeral, ordinal | third ill-mannered pre-war regrettable oiled calamitous first separable ectoplasmic battery-powered participatory fourth still-to-be-named multilingual multi-disciplinary ... |\n| NN   | noun, common, singular or mass | common-carrier cabbage knuckle-duster Casino afghan shed thermostat investment slide humour falloff slick wind hyena override subhumanity machinist ... |\n| NNP  | noun, proper, singular | Motown Venneboerger Czestochowa Ranzer Conchita Trumplane Christos Oceanside Escobar Kreisler Sawyer Cougar Yvette Ervin ODI Darryl CTCA Shannon A.K.C. Meltex Liverpool ... |\n| NNS  | noun, common, plural | undergraduates scotches bric-a-brac products bodyguards facets coasts divestitures storehouses designs clubs fragrances averages subjectivists apprehensions muses factory-jobs ... |\n| VBZ  | verb, present tense, 3rd person singular | bases reconstructs marks mixes displeases seals carps weaves snatches slumps stretches authorizes smolders pictures emerges stockpiles seduces fizzes uses bolsters slaps speaks pleads ... |\n\nTo get the full list of tags, use the following code:\n\n\n```python\nnltk.download('tagsets')\nnltk.help.upenn_tagset()\n```\n\n    $: dollar\n        $ -$ --$ A$ C$ HK$ M$ NZ$ S$ U.S.$ US$\n    '': closing quotation mark\n        ' ''\n    (: opening parenthesis\n        ( [ {\n    ): closing parenthesis\n        ) ] }\n    ,: comma\n        ,\n    --: dash\n        --\n    .: sentence terminator\n        . ! ?\n    :: colon or ellipsis\n        : ; ...\n    CC: conjunction, coordinating\n        & 'n and both but either et for less minus neither nor or plus so\n        therefore times v. versus vs. whether yet\n    CD: numeral, cardinal\n        mid-1890 nine-thirty forty-two one-tenth ten million 0.5 one forty-\n        seven 1987 twenty '79 zero two 78-degrees eighty-four IX '60s .025\n        fifteen 271,124 dozen quintillion DM2,000 ...\n    DT: determiner\n        all an another any both del each either every half la many much nary\n        neither no some such that the them these this those\n    EX: existential there\n        there\n    FW: foreign word\n        gemeinschaft hund ich jeux habeas Haementeria Herr K'ang-si vous\n        lutihaw alai je jour objets salutaris fille quibusdam pas trop Monte\n        terram fiche oui corporis ...\n    IN: preposition or conjunction, subordinating\n        astride among uppon whether out inside pro despite on by throughout\n        below within for towards near behind atop around if like until below\n        next into if beside ...\n    JJ: adjective or numeral, ordinal\n        third ill-mannered pre-war regrettable oiled calamitous first separable\n        ectoplasmic battery-powered participatory fourth still-to-be-named\n        multilingual multi-disciplinary ...\n    JJR: adjective, comparative\n        bleaker braver breezier briefer brighter brisker broader bumper busier\n        calmer cheaper choosier cleaner clearer closer colder commoner costlier\n        cozier creamier crunchier cuter ...\n    JJS: adjective, superlative\n        calmest cheapest choicest classiest cleanest clearest closest commonest\n        corniest costliest crassest creepiest crudest cutest darkest deadliest\n        dearest deepest densest dinkiest ...\n    LS: list item marker\n        A A. B B. C C. D E F First G H I J K One SP-44001 SP-44002 SP-44005\n        SP-44007 Second Third Three Two * a b c d first five four one six three\n        two\n    MD: modal auxiliary\n        can cannot could couldn't dare may might must need ought shall should\n        shouldn't will would\n    NN: noun, common, singular or mass\n        common-carrier cabbage knuckle-duster Casino afghan shed thermostat\n        investment slide humour falloff slick wind hyena override subhumanity\n        machinist ...\n    NNP: noun, proper, singular\n        Motown Venneboerger Czestochwa Ranzer Conchita Trumplane Christos\n        Oceanside Escobar Kreisler Sawyer Cougar Yvette Ervin ODI Darryl CTCA\n        Shannon A.K.C. Meltex Liverpool ...\n    NNPS: noun, proper, plural\n        Americans Americas Amharas Amityvilles Amusements Anarcho-Syndicalists\n        Andalusians Andes Andruses Angels Animals Anthony Antilles Antiques\n        Apache Apaches Apocrypha ...\n    NNS: noun, common, plural\n        undergraduates scotches bric-a-brac products bodyguards facets coasts\n        divestitures storehouses designs clubs fragrances averages\n        subjectivists apprehensions muses factory-jobs ...\n    PDT: pre-determiner\n        all both half many quite such sure this\n    POS: genitive marker\n        ' 's\n    PRP: pronoun, personal\n        hers herself him himself hisself it itself me myself one oneself ours\n        ourselves ownself self she thee theirs them themselves they thou thy us\n    PRP$: pronoun, possessive\n        her his mine my our ours their thy your\n    RB: adverb\n        occasionally unabatingly maddeningly adventurously professedly\n        stirringly prominently technologically magisterially predominately\n        swiftly fiscally pitilessly ...\n    RBR: adverb, comparative\n        further gloomier grander graver greater grimmer harder harsher\n        healthier heavier higher however larger later leaner lengthier less-\n        perfectly lesser lonelier longer louder lower more ...\n    RBS: adverb, superlative\n        best biggest bluntest earliest farthest first furthest hardest\n        heartiest highest largest least less most nearest second tightest worst\n    RP: particle\n        aboard about across along apart around aside at away back before behind\n        by crop down ever fast for forth from go high i.e. in into just later\n        low more off on open out over per pie raising start teeth that through\n        under unto up up-pp upon whole with you\n    SYM: symbol\n        % & ' '' ''. ) ). * + ,. < = > @ A[fj] U.S U.S.S.R * ** ***\n    TO: \"to\" as preposition or infinitive marker\n        to\n    UH: interjection\n        Goodbye Goody Gosh Wow Jeepers Jee-sus Hubba Hey Kee-reist Oops amen\n        huh howdy uh dammit whammo shucks heck anyways whodunnit honey golly\n        man baby diddle hush sonuvabitch ...\n    VB: verb, base form\n        ask assemble assess assign assume atone attention avoid bake balkanize\n        bank begin behold believe bend benefit bevel beware bless boil bomb\n        boost brace break bring broil brush build ...\n    VBD: verb, past tense\n        dipped pleaded swiped regummed soaked tidied convened halted registered\n        cushioned exacted snubbed strode aimed adopted belied figgered\n        speculated wore appreciated contemplated ...\n    VBG: verb, present participle or gerund\n        telegraphing stirring focusing angering judging stalling lactating\n        hankerin' alleging veering capping approaching traveling besieging\n        encrypting interrupting erasing wincing ...\n    VBN: verb, past participle\n        multihulled dilapidated aerosolized chaired languished panelized used\n        experimented flourished imitated reunifed factored condensed sheared\n        unsettled primed dubbed desired ...\n    VBP: verb, present tense, not 3rd person singular\n        predominate wrap resort sue twist spill cure lengthen brush terminate\n        appear tend stray glisten obtain comprise detest tease attract\n        emphasize mold postpone sever return wag ...\n    VBZ: verb, present tense, 3rd person singular\n        bases reconstructs marks mixes displeases seals carps weaves snatches\n        slumps stretches authorizes smolders pictures emerges stockpiles\n        seduces fizzes uses bolsters slaps speaks pleads ...\n    WDT: WH-determiner\n        that what whatever which whichever\n    WP: WH-pronoun\n        that what whatever whatsoever which who whom whosoever\n    WP$: WH-pronoun, possessive\n        whose\n    WRB: Wh-adverb\n        how however whence whenever where whereby whereever wherein whereof why\n    ``: opening quotation mark\n        ` ``\n\n\n    [nltk_data] Downloading package tagsets to\n    [nltk_data]     /home/kprzystalski/nltk_data...\n    [nltk_data]   Package tagsets is already up-to-date!\n\n\nWe can find the token in NLTK's corporas too:\n\n\n```python\ntext6.tokens\n```\n\n\n\n\n    ['SCENE',\n     '1',\n     ':',\n     '[',\n     'wind',\n     ']',\n     '[',\n     'clop',\n     'clop',\n     'clop',\n     ']',\n     'KING',\n     'ARTHUR',\n     ':',\n     'Whoa',\n     'there',\n     '!',\n     '[',\n     'clop',\n     'clop',\n     'clop',\n     ']',\n     'SOLDIER',\n     '#',\n     '1',\n     ':',\n     'Halt',\n     '!',\n     'Who',\n     'goes',\n     'there',\n     '?',\n     'ARTHUR',\n     ':',\n     'It',\n     'is',\n     'I',\n     ',',\n     'Arthur',\n     ',',\n     'son',\n     'of',\n     'Uther',\n     'Pendragon',\n     ',',\n     'from',\n     'the',\n     'castle',\n     'of',\n     'Camelot',\n     '.',\n     'King',\n     'of',\n     'the',\n     'Britons',\n     ',',\n     'defeator',\n     'of',\n     'the',\n     'Saxons',\n     ',',\n     'sovereign',\n     'of',\n     'all',\n     'England',\n     '!',\n     'SOLDIER',\n     '#',\n     '1',\n     ':',\n     'Pull',\n     'the',\n     'other',\n     'one',\n     '!',\n     'ARTHUR',\n     ':',\n     'I',\n     'am',\n     ',',\n     '...',\n     'and',\n     'this',\n     'is',\n     'my',\n     'trusty',\n     'servant',\n     'Patsy',\n     '.',\n     'We',\n     'have',\n     'ridden',\n     'the',\n     'length',\n     'and',\n     'breadth',\n     'of',\n     'the',\n     'land',\n     'in',\n     'search',\n     'of',\n     'knights',\n     'who',\n     'will',\n     'join',\n     'me',\n     'in',\n     'my',\n     'court',\n     'at',\n     'Camelot',\n     '.',\n     'I',\n     'must',\n     'speak',\n     'with',\n     'your',\n     'lord',\n     'and',\n     'master',\n     '.',\n     'SOLDIER',\n     '#',\n     '1',\n     ':',\n     'What',\n     '?',\n     'Ridden',\n     'on',\n     'a',\n     'horse',\n     '?',\n     'ARTHUR',\n     ':',\n     'Yes',\n     '!',\n     'SOLDIER',\n     '#',\n     '1',\n     ':',\n     'You',\n     \"'\",\n     're',\n     'using',\n     'coconuts',\n     '!',\n     'ARTHUR',\n     ':',\n     'What',\n     '?',\n     'SOLDIER',\n     '#',\n     '1',\n     ':',\n     'You',\n     \"'\",\n     've',\n     'got',\n     'two',\n     'empty',\n     'halves',\n     'of',\n     'coconut',\n     'and',\n     'you',\n     \"'\",\n     're',\n     'bangin',\n     \"'\",\n     \"'\",\n     'em',\n     'together',\n     '.',\n     'ARTHUR',\n     ':',\n     'So',\n     '?',\n     'We',\n     'have',\n     'ridden',\n     'since',\n     'the',\n     'snows',\n     'of',\n     'winter',\n     'covered',\n     'this',\n     'land',\n     ',',\n     'through',\n     'the',\n     'kingdom',\n     'of',\n     'Mercea',\n     ',',\n     'through',\n     '--',\n     'SOLDIER',\n     '#',\n     '1',\n     ':',\n     'Where',\n     \"'\",\n     'd',\n     'you',\n     'get',\n     'the',\n     'coconuts',\n     '?',\n     'ARTHUR',\n     ':',\n     'We',\n     'found',\n     'them',\n     '.',\n     'SOLDIER',\n     '#',\n     '1',\n     ':',\n     'Found',\n     'them',\n     '?',\n     'In',\n     'Mercea',\n     '?',\n     'The',\n     'coconut',\n     \"'\",\n     's',\n     'tropical',\n     '!',\n     'ARTHUR',\n     ':',\n     'What',\n     'do',\n     'you',\n     'mean',\n     '?',\n     'SOLDIER',\n     '#',\n     '1',\n     ':',\n     'Well',\n     ',',\n     'this',\n     'is',\n     'a',\n     'temperate',\n     'zone',\n     '.',\n     'ARTHUR',\n     ':',\n     'The',\n     'swallow',\n     'may',\n     'fly',\n     'south',\n     'with',\n     'the',\n     'sun',\n     'or',\n     'the',\n     'house',\n     'martin',\n     'or',\n     'the',\n     'plover',\n     'may',\n     'seek',\n     'warmer',\n     'climes',\n     'in',\n     'winter',\n     ',',\n     'yet',\n     'these',\n     'are',\n     'not',\n     'strangers',\n     'to',\n     'our',\n     'land',\n     '?',\n     'SOLDIER',\n     '#',\n     '1',\n     ':',\n     'Are',\n     'you',\n     'suggesting',\n     'coconuts',\n     'migrate',\n     '?',\n     'ARTHUR',\n     ':',\n     'Not',\n     'at',\n     'all',\n     '.',\n     'They',\n     'could',\n     'be',\n     'carried',\n     '.',\n     'SOLDIER',\n     '#',\n     '1',\n     ':',\n     'What',\n     '?',\n     'A',\n     'swallow',\n     'carrying',\n     'a',\n     'coconut',\n     '?',\n     'ARTHUR',\n     ':',\n     'It',\n     'could',\n     'grip',\n     'it',\n     'by',\n     'the',\n     'husk',\n     '!',\n     'SOLDIER',\n     '#',\n     '1',\n     ':',\n     'It',\n     \"'\",\n     's',\n     'not',\n     'a',\n     'question',\n     'of',\n     'where',\n     'he',\n     'grips',\n     'it',\n     '!',\n     'It',\n     \"'\",\n     's',\n     'a',\n     'simple',\n     'question',\n     'of',\n     'weight',\n     'ratios',\n     '!',\n     'A',\n     'five',\n     'ounce',\n     'bird',\n     'could',\n     'not',\n     'carry',\n     'a',\n     'one',\n     'pound',\n     'coconut',\n     '.',\n     'ARTHUR',\n     ':',\n     'Well',\n     ',',\n     'it',\n     'doesn',\n     \"'\",\n     't',\n     'matter',\n     '.',\n     'Will',\n     'you',\n     'go',\n     'and',\n     'tell',\n     'your',\n     'master',\n     'that',\n     'Arthur',\n     'from',\n     'the',\n     'Court',\n     'of',\n     'Camelot',\n     'is',\n     'here',\n     '.',\n     'SOLDIER',\n     '#',\n     '1',\n     ':',\n     'Listen',\n     '.',\n     'In',\n     'order',\n     'to',\n     'maintain',\n     'air',\n     '-',\n     'speed',\n     'velocity',\n     ',',\n     'a',\n     'swallow',\n     'needs',\n     'to',\n     'beat',\n     'its',\n     'wings',\n     'forty',\n     '-',\n     'three',\n     'times',\n     'every',\n     'second',\n     ',',\n     'right',\n     '?',\n     'ARTHUR',\n     ':',\n     'Please',\n     '!',\n     'SOLDIER',\n     '#',\n     '1',\n     ':',\n     'Am',\n     'I',\n     'right',\n     '?',\n     'ARTHUR',\n     ':',\n     'I',\n     \"'\",\n     'm',\n     'not',\n     'interested',\n     '!',\n     'SOLDIER',\n     '#',\n     '2',\n     ':',\n     'It',\n     'could',\n     'be',\n     'carried',\n     'by',\n     'an',\n     'African',\n     'swallow',\n     '!',\n     'SOLDIER',\n     '#',\n     '1',\n     ':',\n     'Oh',\n     ',',\n     'yeah',\n     ',',\n     'an',\n     'African',\n     'swallow',\n     'maybe',\n     ',',\n     'but',\n     'not',\n     'a',\n     'European',\n     'swallow',\n     '.',\n     'That',\n     \"'\",\n     's',\n     'my',\n     'point',\n     '.',\n     'SOLDIER',\n     '#',\n     '2',\n     ':',\n     'Oh',\n     ',',\n     'yeah',\n     ',',\n     'I',\n     'agree',\n     'with',\n     'that',\n     '.',\n     'ARTHUR',\n     ':',\n     'Will',\n     'you',\n     'ask',\n     'your',\n     'master',\n     'if',\n     'he',\n     'wants',\n     'to',\n     'join',\n     'my',\n     'court',\n     'at',\n     'Camelot',\n     '?!',\n     'SOLDIER',\n     '#',\n     '1',\n     ':',\n     'But',\n     'then',\n     'of',\n     'course',\n     'a',\n     '--',\n     'African',\n     'swallows',\n     'are',\n     'non',\n     '-',\n     'migratory',\n     '.',\n     'SOLDIER',\n     '#',\n     '2',\n     ':',\n     'Oh',\n     ',',\n     'yeah',\n     '...',\n     'SOLDIER',\n     '#',\n     '1',\n     ':',\n     'So',\n     'they',\n     'couldn',\n     \"'\",\n     't',\n     'bring',\n     'a',\n     'coconut',\n     'back',\n     'anyway',\n     '...',\n     '[',\n     'clop',\n     'clop',\n     'clop',\n     ']',\n     'SOLDIER',\n     '#',\n     '2',\n     ':',\n     'Wait',\n     'a',\n     'minute',\n     '!',\n     'Supposing',\n     'two',\n     'swallows',\n     'carried',\n     'it',\n     'together',\n     '?',\n     'SOLDIER',\n     '#',\n     '1',\n     ':',\n     'No',\n     ',',\n     'they',\n     \"'\",\n     'd',\n     'have',\n     'to',\n     'have',\n     'it',\n     'on',\n     'a',\n     'line',\n     '.',\n     'SOLDIER',\n     '#',\n     '2',\n     ':',\n     'Well',\n     ',',\n     'simple',\n     '!',\n     'They',\n     \"'\",\n     'd',\n     'just',\n     'use',\n     'a',\n     'strand',\n     'of',\n     'creeper',\n     '!',\n     'SOLDIER',\n     '#',\n     '1',\n     ':',\n     'What',\n     ',',\n     'held',\n     'under',\n     'the',\n     'dorsal',\n     'guiding',\n     'feathers',\n     '?',\n     'SOLDIER',\n     '#',\n     '2',\n     ':',\n     'Well',\n     ',',\n     'why',\n     'not',\n     '?',\n     'SCENE',\n     '2',\n     ':',\n     '[',\n     'thud',\n     ']',\n     '[',\n     'clang',\n     ']',\n     'CART',\n     '-',\n     'MASTER',\n     ':',\n     'Bring',\n     'out',\n     'your',\n     'dead',\n     '!',\n     '[',\n     'clang',\n     ']',\n     'Bring',\n     'out',\n     'your',\n     'dead',\n     '!',\n     '[',\n     'clang',\n     ']',\n     'Bring',\n     'out',\n     'your',\n     'dead',\n     '!',\n     '[',\n     'clang',\n     ']',\n     'Bring',\n     'out',\n     'your',\n     'dead',\n     '!',\n     '[',\n     'clang',\n     ']',\n     'Bring',\n     'out',\n     'your',\n     'dead',\n     '!',\n     '[',\n     'cough',\n     'cough',\n     '...]',\n     '[',\n     'clang',\n     ']',\n     '[...',\n     'cough',\n     'cough',\n     ']',\n     'Bring',\n     'out',\n     'your',\n     'dead',\n     '!',\n     '[',\n     'clang',\n     ']',\n     'Bring',\n     'out',\n     'your',\n     'dead',\n     '!',\n     '[',\n     'clang',\n     ']',\n     'Bring',\n     'out',\n     'your',\n     'dead',\n     '!',\n     'Ninepence',\n     '.',\n     '[',\n     'clang',\n     ']',\n     'Bring',\n     'out',\n     'your',\n     'dead',\n     '!',\n     '[',\n     'clang',\n     ']',\n     'Bring',\n     'out',\n     'your',\n     'dead',\n     '!',\n     '[',\n     'clang',\n     ']',\n     'Bring',\n     'out',\n     '...',\n     '[',\n     'rewr',\n     '!]',\n     '...',\n     'your',\n     'dead',\n     '!',\n     '[',\n     'rewr',\n     '!]',\n     '[',\n     'clang',\n     ']',\n     'Bring',\n     'out',\n     'your',\n     'dead',\n     '!',\n     'CUSTOMER',\n     ':',\n     'Here',\n     \"'\",\n     's',\n     'one',\n     '.',\n     'CART',\n     '-',\n     'MASTER',\n     ':',\n     'Ninepence',\n     '.',\n     'DEAD',\n     'PERSON',\n     ':',\n     'I',\n     \"'\",\n     'm',\n     'not',\n     'dead',\n     '!',\n     'CART',\n     '-',\n     'MASTER',\n     ':',\n     'What',\n     '?',\n     'CUSTOMER',\n     ':',\n     'Nothing',\n     '.',\n     'Here',\n     \"'\",\n     's',\n     'your',\n     'ninepence',\n     '.',\n     'DEAD',\n     'PERSON',\n     ':',\n     'I',\n     \"'\",\n     'm',\n     'not',\n     'dead',\n     '!',\n     'CART',\n     '-',\n     'MASTER',\n     ':',\n     \"'\",\n     'Ere',\n     '.',\n     'He',\n     'says',\n     'he',\n     \"'\",\n     's',\n     'not',\n     'dead',\n     '!',\n     'CUSTOMER',\n     ':',\n     'Yes',\n     'he',\n     'is',\n     '.',\n     'DEAD',\n     'PERSON',\n     ':',\n     'I',\n     \"'\",\n     'm',\n     'not',\n     '!',\n     'CART',\n     '-',\n     'MASTER',\n     ':',\n     'He',\n     'isn',\n     \"'\",\n     't',\n     '?',\n     'CUSTOMER',\n     ':',\n     'Well',\n     ',',\n     'he',\n     'will',\n     'be',\n     'soon',\n     '.',\n     'He',\n     \"'\",\n     's',\n     'very',\n     'ill',\n     '.',\n     'DEAD',\n     'PERSON',\n     ':',\n     'I',\n     \"'\",\n     'm',\n     'getting',\n     'better',\n     '!',\n     'CUSTOMER',\n     ':',\n     'No',\n     'you',\n     \"'\",\n     're',\n     'not',\n     '.',\n     'You',\n     \"'\",\n     'll',\n     'be',\n     'stone',\n     'dead',\n     'in',\n     'a',\n     'moment',\n     '.',\n     'CART',\n     '-',\n     'MASTER',\n     ':',\n     'Oh',\n     ',',\n     'I',\n     'can',\n     \"'\",\n     't',\n     'take',\n     'him',\n     'like',\n     'that',\n     '.',\n     'It',\n     \"'\",\n     's',\n     'against',\n     'regulations',\n     '.',\n     'DEAD',\n     'PERSON',\n     ':',\n     'I',\n     'don',\n     \"'\",\n     't',\n     'want',\n     'to',\n     'go',\n     'on',\n     'the',\n     'cart',\n     '!',\n     'CUSTOMER',\n     ':',\n     'Oh',\n     ',',\n     'don',\n     \"'\",\n     't',\n     'be',\n     'such',\n     'a',\n     'baby',\n     '.',\n     'CART',\n     '-',\n     'MASTER',\n     ':',\n     'I',\n     'can',\n     \"'\",\n     't',\n     'take',\n     'him',\n     '.',\n     'DEAD',\n     'PERSON',\n     ':',\n     'I',\n     'feel',\n     'fine',\n     '!',\n     'CUSTOMER',\n     ':',\n     'Well',\n     ',',\n     'do',\n     'us',\n     'a',\n     'favor',\n     '.',\n     'CART',\n     '-',\n     'MASTER',\n     ':',\n     'I',\n     'can',\n     \"'\",\n     't',\n     '.',\n     'CUSTOMER',\n     ':',\n     'Well',\n     ',',\n     'can',\n     'you',\n     'hang',\n     'around',\n     'a',\n     'couple',\n     'of',\n     'minutes',\n     '?',\n     'He',\n     'won',\n     \"'\",\n     't',\n     'be',\n     'long',\n     '.',\n     'CART',\n     '-',\n     'MASTER',\n     ':',\n     'No',\n     ',',\n     'I',\n     \"'\",\n     've',\n     'got',\n     'to',\n     'go',\n     'to',\n     'the',\n     'Robinson',\n     \"'\",\n     's',\n     '.',\n     ...]\n\n\n\nAnother feature of NLTK are the stopwords that are used in each language that NLTK supports:\n\n\n```python\nenglish_stopwords = set(nltk.corpus.stopwords.words('english'))\nprint(english_stopwords)\n```\n\n    {'himself', 'we', 'our', 'under', 'here', 'more', 'itself', \"haven't\", 'couldn', 'will', 'why', 'to', 'who', 'having', 'am', \"mustn't\", 'up', 'too', \"shan't\", \"that'll\", 'does', 'through', \"aren't\", 'have', 'but', 'when', 'needn', 'y', 'all', 'he', 'shan', 'by', 'from', 't', \"mightn't\", \"shouldn't\", \"she's\", 'wasn', 'no', 'o', 'shouldn', 'once', 'they', 'those', \"you're\", 'haven', 'll', 'yourself', 'in', 'their', 'if', 'most', \"wouldn't\", 'or', 'hadn', 'during', \"didn't\", \"doesn't\", 'my', 'can', \"couldn't\", 'these', 'wouldn', 'been', \"it's\", 'be', 'until', 'you', 'is', 'a', 'own', 'your', 'd', 'them', 'she', 'for', 'hers', 'isn', 'before', 'myself', 'i', 'did', \"hasn't\", 'mightn', 'there', 'some', 'how', \"don't\", 'theirs', \"wasn't\", 'which', 'had', 'further', 'so', 'below', 'hasn', 'are', 'being', 'do', 'it', 'any', 'same', 'its', 'into', 'on', 'whom', 'aren', 'against', 'other', 'doesn', 'while', 'with', \"hadn't\", 'down', 'above', 'was', 'don', 'each', 'should', 've', 'just', 'themselves', 'now', 'this', 's', 'not', 'where', 'me', 'such', 'at', 'over', 'an', 'won', 'ours', 'nor', 'mustn', 'because', 'ma', \"you'd\", 'then', 'both', 'between', 'has', 're', \"isn't\", 'his', \"you've\", 'ourselves', 'as', 'doing', 'out', 'yours', 'that', 'were', \"weren't\", 'and', 'herself', 'about', 'very', \"should've\", \"won't\", 'what', 'ain', 'weren', 'after', 'only', 'than', 'him', 'of', 'off', 'm', 'few', 'the', 'again', 'didn', 'her', \"you'll\", 'yourselves', \"needn't\"}\n\n\n__POS-tagging__ is another method of describing our text. For each tokenized word we can obtain it's __Part Of Speech__. Those informations are frequently used throughout more advanced machine learning methods.\n\nUp until now everything was easy, fortunately this one is no exception.\n\n\n```python\n# we have already imported nltk.tokenize.word_tokenizer\n\nnltk.download('averaged_perceptron_tagger')\n\nwords = word_tokenize(\n    \"Another text. You know, this is the hardest part, coming up with all those texts. \"\n    \"Lorem Ipsum or some random stuff is pretty boring IMO. \"\n    \"You may feel like somebody didn't care (or at least I do).\"\n    \"Or maybe it's just an act? I will not address this question.\"\n)\n\nnltk.pos_tag(words)\n```\n\n    [nltk_data] Downloading package averaged_perceptron_tagger to\n    [nltk_data]     /home/kprzystalski/nltk_data...\n    [nltk_data]   Package averaged_perceptron_tagger is already up-to-\n    [nltk_data]       date!\n\n\n\n\n\n    [('Another', 'DT'),\n     ('text', 'NN'),\n     ('.', '.'),\n     ('You', 'PRP'),\n     ('know', 'VBP'),\n     (',', ','),\n     ('this', 'DT'),\n     ('is', 'VBZ'),\n     ('the', 'DT'),\n     ('hardest', 'JJS'),\n     ('part', 'NN'),\n     (',', ','),\n     ('coming', 'VBG'),\n     ('up', 'RP'),\n     ('with', 'IN'),\n     ('all', 'PDT'),\n     ('those', 'DT'),\n     ('texts', 'NNS'),\n     ('.', '.'),\n     ('Lorem', 'NNP'),\n     ('Ipsum', 'NNP'),\n     ('or', 'CC'),\n     ('some', 'DT'),\n     ('random', 'JJ'),\n     ('stuff', 'NN'),\n     ('is', 'VBZ'),\n     ('pretty', 'JJ'),\n     ('boring', 'JJ'),\n     ('IMO', 'NNP'),\n     ('.', '.'),\n     ('You', 'PRP'),\n     ('may', 'MD'),\n     ('feel', 'VB'),\n     ('like', 'IN'),\n     ('somebody', 'NN'),\n     ('did', 'VBD'),\n     (\"n't\", 'RB'),\n     ('care', 'VB'),\n     ('(', '('),\n     ('or', 'CC'),\n     ('at', 'IN'),\n     ('least', 'JJS'),\n     ('I', 'PRP'),\n     ('do', 'VBP'),\n     (')', ')'),\n     ('.Or', 'VB'),\n     ('maybe', 'RB'),\n     ('it', 'PRP'),\n     (\"'s\", 'VBZ'),\n     ('just', 'RB'),\n     ('an', 'DT'),\n     ('act', 'NN'),\n     ('?', '.'),\n     ('I', 'PRP'),\n     ('will', 'MD'),\n     ('not', 'RB'),\n     ('address', 'VB'),\n     ('this', 'DT'),\n     ('question', 'NN'),\n     ('.', '.')]\n\n\n\nLook at `act` and `address` towards the end of output.\n\nPOS can be used to dismabiguate word meaning, `act` can be both noun (NN) and verb (VB), same goes for address. \n\nThis tokenizer is __based on simple one layer neural network__ hence it takes context into account (words before and after an act). \n\nContext (N words before and after certain word) is called __N-gram__ in Machine Learning and we will make use of it more later in this course.\n\n<ADD N-GRAM PHOTO>\n\nThis is more sophisticated approach and __should be__ used when more abstract reasoning is needed (like word disambiguation).\n\nWith __NLTK__ we can create and train our own taggers, or choose a pre-made one and train is as seen below (this one takes the next word as it's context).\n\n\n```python\nimport nltk\nfrom nltk.corpus import brown \nnltk.download(\"brown\")\n \nbrown_tagged_sents = brown.tagged_sents(categories=\"news\")\nbrown_sents = brown.sents(categories=\"news\") \nunigram_tagger = nltk.BigramTagger(brown_tagged_sents)\nunigram_tagger.tag(brown_sents[2007])\n```\n\n    [nltk_data] Downloading package brown to\n    [nltk_data]     /home/kprzystalski/nltk_data...\n    [nltk_data]   Package brown is already up-to-date!\n\n\n\n\n\n    [('Various', 'JJ'),\n     ('of', 'IN'),\n     ('the', 'AT'),\n     ('apartments', 'NNS'),\n     ('are', 'BER'),\n     ('of', 'IN'),\n     ('the', 'AT'),\n     ('terrace', 'NN'),\n     ('type', 'NN'),\n     (',', ','),\n     ('being', 'BEG'),\n     ('on', 'IN'),\n     ('the', 'AT'),\n     ('ground', 'NN'),\n     ('floor', 'NN'),\n     ('so', 'CS'),\n     ('that', 'CS'),\n     ('entrance', 'NN'),\n     ('is', 'BEZ'),\n     ('direct', 'JJ'),\n     ('.', '.')]\n\n\n\n### Unicode\n\nEach alphabet is different and some languages use letter that are not used in any other language. Unicode allows use to standardize the text. Let's see an of some german and portugese text below.\n\n\n```python\nsample = \"\"\"Minderj\u00e4hrige Sch\u00fclerinnen. O portugu\u00eas \u00e9 uma l\u00edngua rom\u00e2ntica\"\"\"\n\ntype(sample)\n```\n\n\n\n\n    str\n\n\n\nIf we convert it to ASCII it will look as following:\n\n\n```python\nascii(sample)\n```\n\n\n\n\n    \"'Minderj\\\\xe4hrige Sch\\\\xfclerinnen. O portugu\\\\xeas \\\\xe9 uma l\\\\xedngua rom\\\\xe2ntica'\"\n\n\n\nIt is not what we expected. It's hard to work with such a text. We can go a step further and encode the string to be a unicode encoded one:\n\n\n```python\nsample.encode('utf8')\n```\n\n\n\n\n    b'Minderj\\xc3\\xa4hrige Sch\\xc3\\xbclerinnen. O portugu\\xc3\\xaas \\xc3\\xa9 uma l\\xc3\\xadngua rom\\xc3\\xa2ntica'\n\n\n\nWe could also ignore the ASCII characters that we cannot do anything with in the further processing:\n\n\n```python\nsample.encode('ascii', 'ignore')\n```\n\n\n\n\n    b'Minderjhrige Schlerinnen. O portugus  uma lngua romntica'\n\n\n\nNow we have all letter that make sense, but we have text that does not make any sense anymore. To solve it, we need to normalize it and only after the normalization remove the ascii signs.\n\n\n```python\nimport unicodedata\n\nunicodedata.normalize('NFKD', sample).encode('ascii','ignore')\n```\n\n\n\n\n    b'Minderjahrige Schulerinnen. O portugues e uma lingua romantica'\n\n\n\nMore about [Unicode normalization forms](http://unicode.org/reports/tr15/)\n\n### Lemmatization\n\nLemmatization is a process of getting one word for many forms of the word. \n\nLet's see an example:\n\n\n```python\nfrom nltk.stem import WordNetLemmatizer\n\nwordnet_lemmatizer = WordNetLemmatizer()\n\nprint(wordnet_lemmatizer.lemmatize('do',pos='v'))\nprint(wordnet_lemmatizer.lemmatize('does',pos='v'))\nprint(wordnet_lemmatizer.lemmatize('doing',pos='v'))\n```\n\n    do\n    do\n    do\n\n\nWe can set the main part of speech as one of the following:\n\nADJ, ADJ_SAT, ADV, NOUN, VERB = 'a', 's', 'r', 'n', 'v'\n\n\n```python\nwordnet_lemmatizer.lemmatize('are',pos='v')\n```\n\n\n\n\n    'be'\n\n\n\n### Stemming\n\nStemming is similar to lemmatization, but the main difference is that is just reduce the word to it root. It gives in many cases different results than lemmatization as the second solution is based on part of speech.\n\n\n```python\nfrom nltk import PorterStemmer, LancasterStemmer, word_tokenize\nfrom nltk.stem.snowball import SnowballStemmer\n\nsample = \"This is a new training about machine learning usage for chatbots\"\n\ntokens = word_tokenize(sample)\n\nporter = PorterStemmer()\np_stem = [porter.stem(t) for t in tokens]\nprint(p_stem)\n\nlancaster = LancasterStemmer()\nl_stem = [lancaster.stem(t) for t in tokens]\nprint(l_stem)\n\nsnowball = SnowballStemmer('english')\ns_stem = [snowball.stem(t) for t in tokens]\nprint(s_stem)\n```\n\n    ['thi', 'is', 'a', 'new', 'train', 'about', 'machin', 'learn', 'usag', 'for', 'chatbot']\n    ['thi', 'is', 'a', 'new', 'train', 'about', 'machin', 'learn', 'us', 'for', 'chatbot']\n    ['this', 'is', 'a', 'new', 'train', 'about', 'machin', 'learn', 'usag', 'for', 'chatbot']\n\n\nAs per usual there are other stemmers and lemmatizers available in NLTK. \nSome\nof them may be faster (PorterStemmer), but Snowball is considered de-facto\nstandard.\n\nA few traits of each should be noticed:\n- Stemming is faster (it\ndoesn't have to consult dictionary and complicated\nmorphological rules).\n-\nStemming may not produce a dictionary word, see `studi` above.\n- Lemmatization\nproduces smaller set of words. It is useful as we do not have to keep\ntrack of\nall the different form of word (running, runner, runs etc.). More memory\nefficient.\n- Lemmatization is not as crude, when it does not find the lemma it\nreturns the original\nform. It __may__ produce more words this way, depends on\nthe kind of text we are\nprocessing.\n\n### Sentence extraction\n\nIn this section we show some features of SpaCy. One of the most commonly used is the sentence extraction. An example of Trump speech divided into sentences can be found below.\n\n\n```python\nimport spacy\n\nfile = open(\"../datasets/trump.txt\", \"r\",encoding='utf-8') \ntrump = file.read() \n\nnlp = spacy.load(\"en_core_web_sm\")\ndoc = nlp(trump)\n\nfor span in doc.sents:\n    print(\"> \", span)\n```\n\n    >  Thank you very much.\n    >  Mr. Speaker, Mr. Vice President, Members of Congress, the First Lady of the United States, and citizens of America: Tonight, as we mark the conclusion of our celebration of Black History Month, we are reminded of our Nation's path towards civil rights and the work that still remains to be done.\n    >  Recent threats targeting Jewish community centers and vandalism of Jewish cemeteries, as well as last week's shooting in Kansas City, remind us that while we may be a nation divided on policies, we are a country that stands united in condemning hate and evil in all of its very ugly forms.\n    >  \n    \n    >  Each American generation passes the torch of truth, liberty, and justice in an unbroken chain, all the way down to the present.\n    >  That torch is now in our hands, and we will use it to light up the world.\n    >  I am here tonight to deliver a message of unity and strength, and it is a message deeply delivered from my heart.\n    >  A new chapter of American greatness is now beginning.\n    >  A new national pride is sweeping across our Nation.\n    >  And a new surge of optimism is placing impossible dreams firmly within our grasp.\n    >  \n    \n    What we are witnessing today is the renewal of the American spirit.\n    >  Our allies will find that America is once again ready to lead.\n    >  All the nations of the world\u2014friend or foe\u2014will find that America is strong, America is proud, and America is free.\n    >  \n    \n    \n    >  In 9 years, the United States will celebrate the 250th anniversary of our founding: 250 years since the day we declared our independence.\n    >  It will be one of the great milestones in the history of the world.\n    >  But what will America look like as we reach our 250th year?\n    >  What kind of country will we leave for our children?\n    >  \n    \n    I will not allow the mistakes of recent decades past to define the course of our future.\n    >  For too long, we've watched our middle class shrink as we've exported our jobs and wealth to foreign countries.\n    >  We've financed and built one global project after another, but ignored the fates of our children in the inner cities of Chicago, Baltimore, Detroit, and so many other places throughout our land.\n    >  \n    \n    We've defended the borders of other nations, while leaving our own borders wide open for anyone to cross and for drugs to pour in at a now unprecedented rate.\n    >  And we've spent trillions and trillions of dollars overseas, while our infrastructure at home has so badly crumbled.\n    >  \n    \n    Then, in 2016, the Earth shifted beneath our feet.\n    >  The rebellion started as a quiet protest, spoken by families of all colors and creeds, families who just wanted a fair shot for their children and a fair hearing for their concerns.\n    >  \n    \n    \n    >  But then the quiet voices became a loud chorus, as thousands of citizens now spoke out together, from cities small and large, all across our country.\n    >  Finally, the chorus became an earthquake, and the people turned out by the tens of millions, and they were all united by one very simple, but crucial demand: that America must put its own citizens first.\n    >  Because only then can we truly make America great again.\n    >  \n    \n    Dying industries will come roaring back to life.\n    >  Heroic veterans will get the care they so desperately need.\n    >  Our military will be given the resources its brave warriors so richly deserve.\n    >  Crumbling infrastructure will be replaced with new roads, bridges, tunnels, airports, and railways gleaming across our very, very beautiful land.\n    >  Our terrible drug epidemic will slow down and, ultimately, stop.\n    >  And our neglected inner cities will see a rebirth of hope, safety, and opportunity.\n    >  Above all else, we will keep our promises to the American people.\n    >  [Applause] Thank you.\n    >  \n    \n    It's been a little over a month since my Inauguration, and I want to take this moment to update the Nation on the progress I've made in keeping those promises.\n    >  \n    \n    \n    >  Since my election, Ford, Fiat Chrysler, General Motors, Sprint, Softbank, Lockheed, Intel, Walmart, and many others have announced that they will invest billions and billions of dollars in the United States and will create tens of thousands of new American jobs.\n    >  \n    \n    The stock market has gained almost $3 trillion in value since the election on November 8\u2014a record.\n    >  We've saved taxpayers hundreds of millions of dollars by bringing down the price of fantastic\u2014and it is a fantastic\u2014new F-35 jet fighter, and we'll be saving billions more on contracts all across our Government.\n    >  We have placed a hiring freeze on nonmilitary and nonessential Federal workers.\n    >  \n    \n    We have begun to drain the swamp of government corruption by imposing a 5-year ban on lobbying by executive branch officials and a lifetime ban\u2014[applause]\u2014thank you.\n    >  Thank you.\n    >  And a lifetime ban on becoming lobbyists for a foreign government.\n    >  \n    \n    We have undertaken a historic effort to massively reduce job-crushing regulations, creating a deregulation Task Force inside of every Government agency.\n    >  And we're imposing a new rule which mandates that for every one new regulation, two old regulations must be eliminated.\n    >  We're going to stop the regulations that threaten the future and livelihood of our great coal miners.\n    >  \n    \n    We have cleared the way for the construction of the Keystone and Dakota Access pipelines, thereby creating tens of thousands of jobs.\n    >  And I've issued a new directive that new American pipelines be made with American steel.\n    >  \n    \n    We have withdrawn the United States from the job-killing Trans-Pacific Partnership.\n    >  And with the help of Prime Minister Justin Trudeau, we have formed a council with our neighbors in Canada to help ensure that women entrepreneurs have access to the networks, markets, and capital they need to start a business and live out their financial dreams.\n    >  \n    \n    To protect our citizens, I have directed the Department of Justice to form a Task Force on Reducing Violent Crime.\n    >  I have further ordered the Departments of Homeland Security and Justice, along with the Department of State and the Director of National Intelligence, to coordinate an aggressive strategy to dismantle the criminal cartels that have spread all across our Nation.\n    >  We will stop the drugs from pouring into our country and poisoning our youth, and we will expand treatment for those who have become so badly addicted.\n    >  \n    \n    \n    >  At the same time, my administration has answered the pleas of the American people for immigration enforcement and border security.\n    >  By finally enforcing our immigration laws, we will raise wages, help the unemployed, save billions and billions of dollars, and make our communities safer for everyone.\n    >  We want all Americans to succeed, but that can't happen in an environment of lawless chaos.\n    >  We must restore integrity and the rule of law at our borders.\n    >  \n    \n    \n    >  For that reason, we will soon begin the construction of a great, great wall along our southern border.\n    >  As we speak tonight, we are removing gang members, drug dealers, and criminals that threaten our communities and prey on our very innocent citizens.\n    >  Bad ones are going out as I speak, and as I've promised throughout the campaign.\n    >  \n    \n    \n    >  To any in Congress who do not believe we should enforce our laws, I would ask you this one question: What would you say to the American family that loses their jobs, their income, or their loved one because America refused to uphold its laws and defend its borders?\n    >  \n    \n    Our obligation is to serve, protect, and defend the citizens of the United States.\n    >  We are also taking strong measures to protect our Nation from radical Islamic terrorism.\n    >  According to data provided by the Department of Justice, the vast majority of individuals convicted of terrorism and terrorism-related offenses since 9/11 came here from outside of our country.\n    >  We have seen the attacks at home, from Boston to San Bernardino to the Pentagon, and, yes, even the World Trade Center.\n    >  \n    \n    We have seen the attacks in France, in Belgium, in Germany, and all over the world.\n    >  It is not compassionate, but reckless to allow uncontrolled entry from places where proper vetting cannot occur.\n    >  Those given the high honor of admission to the United States should support this country and love its people and its values.\n    >  We cannot allow a beachhead of terrorism to form inside America.\n    >  We cannot allow our Nation to become a sanctuary for extremists.\n    >  \n    \n    \n    >  That is why my administration has been working on improved vetting procedures, and we will shortly take new steps to keep our Nation safe and to keep those out who will do us harm.\n    >  \n    \n    As promised, I directed the Department of Defense to develop a plan to demolish and destroy ISIS, a network of lawless savages that have slaughtered Muslims and Christians, and men and women and children of all faiths and all beliefs.\n    >  We will work with our allies, including our friends and allies in the Muslim world, to extinguish this vile enemy from our planet.\n    >  \n    \n    I have also imposed new sanctions on entities and individuals who support Iran's ballistic missile program and reaffirmed our unbreakable alliance with the State of Israel.\n    >  \n    \n    \n    >  Finally, I have kept my promise to appoint a Justice to the United States Supreme Court, from my list of 20 judges, who will defend our Constitution.\n    >  \n    \n    \n    >  I am greatly honored to have Maureen Scalia with us in the gallery tonight.\n    >  Thank you, Maureen.\n    >  Her late, great husband, Antonin Scalia, will forever be a symbol of American justice.\n    >  To fill his seat, we have chosen Judge Neil Gorsuch, a man of incredible skill and deep devotion to the law.\n    >  He was confirmed unanimously by the Court of Appeals, and I am asking the Senate to swiftly approve his nomination.\n    >  \n    \n    \n    >  Tonight, as I outline the next steps we must take as a country, we must honestly acknowledge the circumstances we inherited.\n    >  Ninety-four million Americans are out of the labor force.\n    >  Over 43 million people are now living in poverty, and over 43 million Americans are on food stamps.\n    >  More than 1 in 5 people in their prime working years are not working.\n    >  We have the worst financial recovery in 65 years.\n    >  In the last 8 years, the past administration has put on more new debt than nearly all of the other Presidents combined.\n    >  \n    \n    We've lost more than one-fourth of our manufacturing jobs since NAFTA was approved, and we've lost 60,000 factories since China joined the World Trade Organization in 2001.\n    >  Our trade deficit in goods with the world last year was nearly $800 billion dollars.\n    >  And overseas we have inherited a series of tragic foreign policy disasters.\n    >  Solving these and so many other pressing problems will require us to work past the differences of party.\n    >  It will require us to tap into the American spirit that has overcome every challenge throughout our long and storied history.\n    >  But to accomplish our goals at home and abroad, we must restart the engine of the American economy, making it easier for companies to do business in the United States, and much, much harder for companies to leave our country.\n    >  \n    \n    \n    >  Right now American companies are taxed at one of the highest rates anywhere in the world.\n    >  My economic team is developing historic tax reform that will reduce the tax rate on our companies so they can compete and thrive anywhere and with anyone.\n    >  It will be a big, big cut.\n    >  \n    \n    At the same time, we will provide massive tax relief for the middle class.\n    >  We must create a level playing field for American companies and our workers\u2014have to do it.\n    >  Currently, when we ship products out of America, many other countries make us pay very high tariffs and taxes.\n    >  But when foreign companies ship their products into America, we charge them nothing, or almost nothing.\n    >  \n    \n    I just met with officials and workers from a great American company, Harley-Davidson.\n    >  In fact, they proudly displayed five of their magnificent motorcycles, made in the U.S.A., on the front lawn of the White House.\n    >  [Laughter]\n    >  And they wanted me to ride one, and I said, \"No, thank you.\"\n    >  [Laughter]\n    \n    At our meeting, I asked them, how are you doing, how is business?\n    >  They said that it's good.\n    >  I asked them further, how are you doing with other countries, mainly international sales?\n    >  They told me\u2014without even complaining, because they have been so mistreated for so long that they've become used to it\u2014that it's very hard to do business with other countries because they tax our goods at such a high rate.\n    >  They said that in the case of another country, they taxed their motorcycles at 100 percent.\n    >  They weren't even asking for a change.\n    >  But I am.\n    >  \n    \n    I believe strongly in free trade, but it also has to be fair trade.\n    >  It's been a long time since we had fair trade.\n    >  The first Republican President, Abraham Lincoln, warned that the \"abandonment of the protective policy by the American Government will produce want and ruin among our people.\"\n    >  Lincoln was right, and it's time we heeded his advice and his words.\n    >  I am not going to let America and its great companies and workers be taken advantage of us any longer.\n    >  They have taken advantage of our country.\n    >  No longer.\n    >  \n    \n    I am going to bring back millions of jobs.\n    >  Protecting our workers also means reforming our system of legal immigration.\n    >  The current, outdated system depresses wages for our poorest workers and puts great pressure on taxpayers.\n    >  Nations around the world like Canada, Australia, and many others, have a merit-based immigration system.\n    >  It's a basic principle that those seeking to enter a country ought to be able to support themselves financially.\n    >  Yet, in America, we do not enforce this rule, straining the very public resources that our poorest citizens rely upon.\n    >  According to the National Academy of Sciences, our current immigration system costs American taxpayers many billions of dollars a year.\n    >  \n    \n    Switching away from this current system of lower skilled immigration, and instead adopting a merit-based system, we will have so many more benefits.\n    >  It will save countless dollars, raise workers' wages, and help struggling families\u2014including immigrant families\u2014enter the middle class.\n    >  And they will do it quickly, and they will be very, very happy, indeed.\n    >  \n    \n    I believe that real and positive immigration reform is possible, as long as we focus on the following goals: to improve jobs and wages for Americans, to strengthen our Nation's security, and to restore respect for our laws.\n    >  If we are guided by the wellbeing of American citizens, then I believe Republicans and Democrats can work together to achieve an outcome that has eluded our country for decades.\n    >  \n    \n    Another Republican President, Dwight D. Eisenhower, initiated the last truly great national infrastructure program\u2014the building of the Interstate Highway System.\n    >  The time has come for a new program of national rebuilding.\n    >  America has spent approximately $6 trillion in the Middle East; all the while, our infrastructure at home is crumbling.\n    >  With this $6 trillion, we could have rebuilt our country twice, and maybe even three times if we had people who had the ability to negotiate.\n    >  [Laughter]\n    \n    To launch our national rebuilding, I will be asking Congress to approve legislation that produces a $1 trillion investment in infrastructure of the United States\u2014financed through both public and private capital\u2014creating millions of new jobs.\n    >  This effort will be guided by two core principles: buy American and hire American.\n    >  \n    \n    \n    >  Tonight I am also calling on this Congress to repeal and replace Obamacare with reforms that expand choice, increase access, lower costs, and at the same time, provide better health care.\n    >  \n    \n    Mandating every American to buy Government-approved health insurance was never the right solution for our country.\n    >  The way to make health insurance available to everyone is to lower the cost of health insurance, and that is what we are going do.\n    >  \n    \n    Obamacare premiums nationwide have increased by double and triple digits.\n    >  As an example, Arizona went up 116 percent last year alone.\n    >  Governor Matt Bevin of Kentucky just said Obamacare is failing in his State\u2014the State of Kentucky\u2014and it's unsustainable and collapsing.\n    >  \n    \n    One-third of the counties have only one insurer, and they are losing them fast.\n    >  They are losing them so fast.\n    >  They are leaving, and many Americans have no choice at all.\n    >  There's no choice left.\n    >  Remember when you were told that you could keep your doctor and keep your plan?\n    >  We now know that all of those promises have been totally broken.\n    >  Obamacare is collapsing, and we must act decisively to protect all Americans.\n    \n    \n    >  Action is not a choice, it is a necessity.\n    >  So I am calling on all Democrats and Republicans in Congress to work with us to save Americans from this imploding Obamacare disaster.\n    >  \n    \n    \n    >  Here are the principles that should guide the Congress as we move to create a better health care system for all Americans:\n    \n    First, we should ensure that Americans with preexisting conditions have access to coverage, and that we have a stable transition for Americans currently enrolled in the health care exchanges.\n    >  \n    \n    \n    >  Secondly, we should help Americans purchase their own coverage through the use of tax credits and expanded health savings accounts, but it must be the plan they want, not the plan forced on them by our Government.\n    >  \n    \n    \n    >  Thirdly, we should give our State Governors the resources and flexibility they need with Medicaid to make sure no one is left out.\n    >  \n    \n    Fourth, we should implement legal reforms that protect patients and doctors from unnecessary costs that drive up the price of insurance and work to bring down the artificially high price of drugs and bring them down immediately.\n    >  And finally, the time has come to give Americans the freedom to purchase health insurance across State lines, which will create a truly competitive national marketplace that will bring costs way down and provide far better care.\n    >  So important.\n    >  \n    \n    Everything that is broken in our country can be fixed.\n    >  Every problem can be solved.\n    >  And every hurting family can find healing and hope.\n    >  \n    \n    Our citizens deserve this and so much more, so why not join forces and finally get the job done, and get it done right?\n    >  On this and so many other things, Democrats and Republicans should get together and unite for the good of our country and for the good of the American people.\n    >  \n    \n    My administration wants to work with members of both parties to make childcare accessible and affordable; to help ensure new parents that they have paid family leave; to invest in women's health; and to promote clean air and clean water; and to rebuild our military and our infrastructure.\n    >  \n    \n    True love for our people requires us to find common ground, to advance the common good, and to cooperate on behalf of every American child who deserves a much brighter future.\n    >  \n    \n    An incredible young woman is with us this evening, who should serve as an inspiration to us all.\n    >  Today is Rare Disease Day, and joining us in the gallery is a rare disease survivor, Megan Crowley.\n    >  \n    \n    Megan was diagnosed with Pompe disease, a rare and serious illness, when she was 15 months old.\n    >  She was not expected to live past 5.\n    >  On receiving this news, Megan's dad John fought with everything he had to save the life of his precious child.\n    >  He founded a company to look for a cure and helped develop the drug that saved Megan's life.\n    >  Today she is 20 years old and a sophomore at Notre Dame.\n    >  \n    \n    Megan's story is about the unbounded power of a father's love for a daughter.\n    >  But our slow and burdensome approval process at the Food and Drug Administration keeps too many advances, like the one that saved Megan's life, from reaching those in need.\n    >  If we slash the restraints, not just at the FDA, but across our Government, then we will be blessed with far more miracles just like Megan.\n    >  In fact, our children will grow up in a nation of miracles.\n    >  \n    \n    \n    >  But to achieve this future, we must enrich the mind and the souls of every American child.\n    >  Education is the civil rights issue of our time.\n    >  I am calling upon members of both parties to pass an education bill that funds school choice for disadvantaged youth, including millions of African American and Latino children.\n    >  These families should be free to choose the public, private, charter, magnet, religious, or home school that is right for them.\n    >  \n    \n    \n    >  Joining us tonight in the gallery is a remarkable woman, Denisha Merriweather.\n    >  As a young girl, Denisha struggled in school and failed third grade twice.\n    >  But then, she was able to enroll in a private center for learning\u2014great learning center\u2014with the help of a tax credit and a scholarship program.\n    >  \n    \n    Today, she is the first in her family to graduate, not just from high school, but from college.\n    >  Later this year she will get her master's degree in social work.\n    >  We want all children to be able to break the cycle of poverty just like Denisha.\n    >  \n    \n    \n    >  But to break the cycle of poverty, we must also break the cycle of violence.\n    >  The murder rate in 2015 experienced its largest single-year increase in nearly half a century.\n    >  In Chicago, more than 4,000 people were shot last year alone, and the murder rate so far this year has been even higher.\n    >  This is not acceptable in our society.\n    >  \n    \n    \n    >  Every American child should be able to grow up in a safe community, to attend a great school, and to have access to a high-paying job.\n    >  But to create this future, we must work with, not against\u2014not against\u2014the men and women of law enforcement.\n    >  We must build bridges of cooperation and trust, not drive the wedge of disunity, and really, it's what it is\u2014division.\n    >  It's pure, unadulterated division.\n    >  We have to unify.\n    >  \n    \n    Police and sheriffs are members of our community.\n    >  They're friends and neighbors, they're mothers and fathers, sons and daughters, and they leave behind loved ones every day who worry about whether or not they'll come home safe and sound.\n    >  We must support the incredible men and women of law enforcement.\n    >  \n    \n    \n    >  And we must support the victims of crime.\n    >  I have ordered the Department of Homeland Security to create an office to serve American victims.\n    >  The office is called VOICE:\n    >  Victims of Immigration Crime Engagement.\n    >  We are providing a voice to those who have been ignored by our media and silenced by special interests.\n    >  Joining us in the audience tonight are four very brave Americans whose Government failed them.\n    >  Their names are Jamiel Shaw, Susan Oliver, Jenna Oliver, and Jessica Davis.\n    >  \n    \n    Jamiel's 17-year-old son was viciously murdered by an illegal immigrant gang member who had just been released from prison.\n    >  Jamiel Shaw, Jr. was an incredible young man, with unlimited potential, who was getting ready to go to college where he would have excelled as a great college quarterback.\n    >  But he never got the chance.\n    >  His father, who is in the audience tonight, has become a very good friend of mine.\n    >  Jamiel, thank you.\n    >  Thank you.\n    >  \n    \n    Also with us are Susan Oliver and Jessica Davis.\n    >  Their husbands, Deputy Sheriff Danny Oliver and Detective Michael Davis, were slain in the line of duty in California.\n    >  They were pillars of their community.\n    >  These brave men were viciously gunned down by an illegal immigrant with a criminal record and two prior deportations.\n    >  Should have never been in our country.\n    >  \n    \n    \n    >  Sitting with Susan is her daughter, Jenna.\n    >  Jenna, I want you to know that your father was a hero, and that tonight you have the love of an entire country supporting you and praying for you.\n    >  \n    \n    \n    >  To Jamiel, Jenna, Susan, and Jessica: I want you to know that we will never stop fighting for justice.\n    >  Your loved ones will never, ever be forgotten.\n    >  We will always honor their memory.\n    >  \n    \n    Finally, to keep America safe, we must provide the men and women of the United States military with the tools they need to prevent war.\n    >  If they must, they have to fight and they only have to win.\n    >  \n    \n    I am sending Congress a budget that rebuilds the military, eliminates the defense sequester, and calls for one of the largest increases in national defense spending in American history.\n    >  My budget will also increase funding for our veterans.\n    >  Our veterans have delivered for this Nation, and now we must deliver for them.\n    >  \n    \n    \n    >  The challenges we face as a nation are great, but our people are even greater.\n    >  And none are greater or are braver than those who fight for America in uniform.\n    >  \n    \n    We are blessed to be joined tonight by Carryn Owens, the widow of U.S. Navy Special Operator, Senior Chief William \"Ryan\" Owens.\n    >  Ryan died as he lived: a warrior and a hero, battling against terrorism and securing our Nation.\n    >  I just spoke to our great General Mattis, just now, who reconfirmed that\u2014and I quote\u2014\"Ryan was a part of a highly successful raid that generated large amounts of vital intelligence that will lead to many more victories in the future against our enemy.\"\n    >  Ryan's legacy is etched into eternity.\n    >  Thank you.\n    >  [Applause] And Ryan is looking down, right now\u2014you know that\u2014and he is very happy because I think he just broke a record.\n    >  [Laughter]\n    \n    For as the Bible teaches us, there is no greater act of love than to lay down one's life for one's friends.\n    >  Ryan laid down his life for his friends, for his country, and for our freedom.\n    >  And we will never forget Ryan.\n    >  \n    \n    \n    >  To those allies who wonder what kind of a friend America will be, look no further than the heroes who wear our uniform.\n    >  Our foreign policy calls for a direct, robust, and meaningful engagement with the world.\n    >  It is American leadership based on vital security interests that we share with our allies all across the globe.\n    >  \n    \n    We strongly support NATO, an alliance forged through the bonds of two world wars that dethroned fascism, and a cold war, and defeated communism.\n    >  \n    \n    \n    >  But our partners must meet their financial obligations.\n    >  And now, based on our very strong and frank discussions, they are beginning to do just that.\n    >  In fact, I can tell you, the money is pouring in.\n    >  Very nice.\n    >  We expect our partners\u2014whether in NATO, the Middle East, or in the Pacific\u2014to take a direct and meaningful role in both strategic and military operations, and pay their fair share of the cost.\n    >  Have to do that.\n    >  \n    \n    We will respect historic institutions, but we will respect the foreign rights of all nations, and they have to respect our rights as a nation also.\n    >  Free nations are the best vehicle for expressing the will of the people, and America respects the right of all nations to chart their own path.\n    >  My job is not to represent the world.\n    >  My job is to represent the United States of America.\n    >  \n    \n    \n    >  But we know that America is better off when there is less conflict, not more.\n    >  We must learn from the mistakes of the past.\n    >  We have seen the war and the destruction that have ravaged and raged throughout the world\u2014all across the world.\n    >  The only long-term solution for these humanitarian disasters, in many cases, is to create the conditions where displaced persons can safely return home and begin the long, long process of rebuilding.\n    >  \n    \n    America is willing to find new friends and to forge new partnerships where shared interests align.\n    >  We want harmony and stability, not war and conflict.\n    >  We want peace, wherever peace can be found.\n    >  \n    \n    America is friends today with former enemies.\n    >  Some of our closest allies, decades ago, fought on the opposite side of these terrible, terrible wars.\n    >  This history should give us all faith in the possibilities for a better world.\n    >  Hopefully, the 250th year for America will see a world that is more peaceful, more just, and more free.\n    >  \n    \n    \n    >  On our 100th anniversary, in 1876, citizens from across our Nation came to Philadelphia to celebrate America's centennial.\n    >  At that celebration, the country's builders and artists and inventors showed off their wonderful creations.\n    >  Alexander Graham Bell displayed his telephone for the first time.\n    >  Remington unveiled the first typewriter.\n    >  An early attempt was made at electric light.\n    >  Thomas Edison showed an automatic telegraph and an electric pen.\n    >  Imagine the wonders our country could know in America's 250th year.\n    >  Think of the marvels we can achieve if we simply set free the dreams of our people.\n    >  Cures to the illnesses that have always plagued us are not too much to hope.\n    >  American footprints on distant worlds are not too big a dream.\n    >  Millions lifted from welfare to work is not too much to expect.\n    >  And streets where mothers are safe from fear, schools where children learn in peace, and jobs where Americans prosper and grow are not too much to ask.\n    >  \n    \n    When we have all of this, we will have made America greater than ever before\u2014for all Americans.\n    >  This is our vision.\n    >  This is our mission.\n    >  But we can only get there together.\n    >  We are one people with one destiny.\n    >  We all bleed the same blood.\n    >  We all salute the same great American flag.\n    >  And we all are made by the same God.\n    >  \n    \n    When we fulfill this vision, when we celebrate our 250 years of glorious freedom, we will look back on tonight as when this new chapter of American greatness began.\n    >  The time for small thinking is over.\n    >  The time for trivial fights is behind us.\n    >  We just need the courage to share the dreams that fill our hearts, the bravery to express the hopes that stir our souls, and the confidence to turn those hopes and those dreams into action.\n    >  \n    \n    \n    >  From now on, America will be empowered by our aspirations, not burdened by our fears; inspired by the future, not bound by failures of the past; and guided by our vision, not blinded by our doubts.\n    >  \n    \n    I am asking all citizens to embrace this renewal of the American spirit.\n    >  I am asking all Members of Congress to join me in dreaming big and bold, and daring things for our country.\n    >  I am asking everyone watching tonight to seize this moment.\n    >  Believe in yourselves, believe in your future, and believe, once more, in America.\n    >  \n    \n    Thank you, God bless you, and God bless the United States.\n\n\nEach sentence can next be tokenized and we can get a tag and pos of it.\n\n\n```python\nfor span in doc.sents:\n    for i in range(span.start, span.end):\n        token = doc[i]\n        print(i, token.text, token.tag_, token.pos_)\n```\n\n    0 Thank VBP VERB\n    1 you PRP PRON\n    2 very RB ADV\n    3 much RB ADV\n    4 . . PUNCT\n    5 Mr. NNP PROPN\n    6 Speaker NNP PROPN\n    7 , , PUNCT\n    8 Mr. NNP PROPN\n    9 Vice NNP PROPN\n    10 President NNP PROPN\n    11 , , PUNCT\n    12 Members NNS NOUN\n    13 of IN ADP\n    14 Congress NNP PROPN\n    15 , , PUNCT\n    16 the DT DET\n    17 First NNP PROPN\n    18 Lady NNP PROPN\n    19 of IN ADP\n    20 the DT DET\n    21 United NNP PROPN\n    22 States NNP PROPN\n    23 , , PUNCT\n    24 and CC CCONJ\n    25 citizens NNS NOUN\n    26 of IN ADP\n    27 America NNP PROPN\n    28 : : PUNCT\n    29 Tonight NN NOUN\n    30 , , PUNCT\n    31 as IN ADP\n    32 we PRP PRON\n    33 mark VBP VERB\n    34 the DT DET\n    35 conclusion NN NOUN\n    36 of IN ADP\n    37 our PRP$ PRON\n    38 celebration NN NOUN\n    39 of IN ADP\n    40 Black NNP PROPN\n    41 History NNP PROPN\n    42 Month NNP PROPN\n    43 , , PUNCT\n    44 we PRP PRON\n    45 are VBP AUX\n    46 reminded VBN VERB\n    47 of IN ADP\n    48 our PRP$ PRON\n    49 Nation NN NOUN\n    50 's POS PART\n    51 path NN NOUN\n    52 towards IN ADP\n    53 civil JJ ADJ\n    54 rights NNS NOUN\n    55 and CC CCONJ\n    56 the DT DET\n    57 work NN NOUN\n    58 that WDT DET\n    59 still RB ADV\n    60 remains VBZ VERB\n    61 to TO PART\n    62 be VB AUX\n    63 done VBN VERB\n    64 . . PUNCT\n    65 Recent JJ ADJ\n    66 threats NNS NOUN\n    67 targeting VBG VERB\n    68 Jewish JJ ADJ\n    69 community NN NOUN\n    70 centers NNS NOUN\n    71 and CC CCONJ\n    72 vandalism NN NOUN\n    73 of IN ADP\n    74 Jewish JJ ADJ\n    75 cemeteries NNS NOUN\n    76 , , PUNCT\n    77 as RB ADV\n    78 well RB ADV\n    79 as IN ADP\n    80 last JJ ADJ\n    81 week NN NOUN\n    82 's POS PART\n    83 shooting NN NOUN\n    84 in IN ADP\n    85 Kansas NNP PROPN\n    86 City NNP PROPN\n    87 , , PUNCT\n    88 remind VB VERB\n    89 us PRP PRON\n    90 that IN SCONJ\n    91 while IN SCONJ\n    92 we PRP PRON\n    93 may MD AUX\n    94 be VB VERB\n    95 a DT DET\n    96 nation NN NOUN\n    97 divided VBN VERB\n    98 on IN ADP\n    99 policies NNS NOUN\n    100 , , PUNCT\n    101 we PRP PRON\n    102 are VBP AUX\n    103 a DT DET\n    104 country NN NOUN\n    105 that WDT DET\n    106 stands VBZ VERB\n    107 united JJ ADJ\n    108 in IN ADP\n    109 condemning VBG VERB\n    110 hate NN NOUN\n    111 and CC CCONJ\n    112 evil NN NOUN\n    113 in IN ADP\n    114 all DT DET\n    115 of IN ADP\n    116 its PRP$ PRON\n    117 very RB ADV\n    118 ugly JJ ADJ\n    119 forms NNS NOUN\n    120 . . PUNCT\n    121 \n     _SP SPACE\n    122 Each DT DET\n    123 American JJ ADJ\n    124 generation NN NOUN\n    125 passes VBZ VERB\n    126 the DT DET\n    127 torch NN NOUN\n    128 of IN ADP\n    129 truth NN NOUN\n    130 , , PUNCT\n    131 liberty NN NOUN\n    132 , , PUNCT\n    133 and CC CCONJ\n    134 justice NN NOUN\n    135 in IN ADP\n    136 an DT DET\n    137 unbroken JJ ADJ\n    138 chain NN NOUN\n    139 , , PUNCT\n    140 all PDT DET\n    141 the DT DET\n    142 way NN NOUN\n    143 down RB ADV\n    144 to IN ADP\n    145 the DT DET\n    146 present NN NOUN\n    147 . . PUNCT\n    148 That DT DET\n    149 torch NN NOUN\n    150 is VBZ AUX\n    151 now RB ADV\n    152 in IN ADP\n    153 our PRP$ PRON\n    154 hands NNS NOUN\n    155 , , PUNCT\n    156 and CC CCONJ\n    157 we PRP PRON\n    158 will MD AUX\n    159 use VB VERB\n    160 it PRP PRON\n    161 to TO PART\n    162 light VB VERB\n    163 up RP ADP\n    164 the DT DET\n    165 world NN NOUN\n    166 . . PUNCT\n    167 I PRP PRON\n    168 am VBP AUX\n    169 here RB ADV\n    170 tonight NN NOUN\n    171 to TO PART\n    172 deliver VB VERB\n    173 a DT DET\n    174 message NN NOUN\n    175 of IN ADP\n    176 unity NN NOUN\n    177 and CC CCONJ\n    178 strength NN NOUN\n    179 , , PUNCT\n    180 and CC CCONJ\n    181 it PRP PRON\n    182 is VBZ VERB\n    183 a DT DET\n    184 message NN NOUN\n    185 deeply RB ADV\n    186 delivered VBN VERB\n    187 from IN ADP\n    188 my PRP$ PRON\n    189 heart NN NOUN\n    190 . . PUNCT\n    191 A DT DET\n    192 new JJ ADJ\n    193 chapter NN NOUN\n    194 of IN ADP\n    195 American JJ ADJ\n    196 greatness NN NOUN\n    197 is VBZ AUX\n    198 now RB ADV\n    199 beginning VBG VERB\n    200 . . PUNCT\n    201 A DT DET\n    202 new JJ ADJ\n    203 national JJ ADJ\n    204 pride NN NOUN\n    205 is VBZ AUX\n    206 sweeping VBG VERB\n    207 across IN ADP\n    208 our PRP$ PRON\n    209 Nation NN NOUN\n    210 . . PUNCT\n    211 And CC CCONJ\n    212 a DT DET\n    213 new JJ ADJ\n    214 surge NN NOUN\n    215 of IN ADP\n    216 optimism NN NOUN\n    217 is VBZ AUX\n    218 placing VBG VERB\n    219 impossible JJ ADJ\n    220 dreams NNS NOUN\n    221 firmly RB ADV\n    222 within IN ADP\n    223 our PRP$ PRON\n    224 grasp NN NOUN\n    225 . . PUNCT\n    226 \n    \n     _SP SPACE\n    227 What WP PRON\n    228 we PRP PRON\n    229 are VBP AUX\n    230 witnessing VBG VERB\n    231 today NN NOUN\n    232 is VBZ AUX\n    233 the DT DET\n    234 renewal NN NOUN\n    235 of IN ADP\n    236 the DT DET\n    237 American JJ ADJ\n    238 spirit NN NOUN\n    239 . . PUNCT\n    240 Our PRP$ PRON\n    241 allies NNS NOUN\n    242 will MD AUX\n    243 find VB VERB\n    244 that IN SCONJ\n    245 America NNP PROPN\n    246 is VBZ AUX\n    247 once RB ADV\n    248 again RB ADV\n    249 ready JJ ADJ\n    250 to TO PART\n    251 lead VB VERB\n    252 . . PUNCT\n    253 All PDT DET\n    254 the DT DET\n    255 nations NNS NOUN\n    256 of IN ADP\n    257 the DT DET\n    258 world NN NOUN\n    259 \u2014 : PUNCT\n    260 friend NN NOUN\n    261 or CC CCONJ\n    262 foe NN NOUN\n    263 \u2014 : PUNCT\n    264 will MD AUX\n    265 find VB VERB\n    266 that IN SCONJ\n    267 America NNP PROPN\n    268 is VBZ AUX\n    269 strong JJ ADJ\n    270 , , PUNCT\n    271 America NNP PROPN\n    272 is VBZ AUX\n    273 proud JJ ADJ\n    274 , , PUNCT\n    275 and CC CCONJ\n    276 America NNP PROPN\n    277 is VBZ VERB\n    278 free JJ ADJ\n    279 . . PUNCT\n    280 \n    \n     _SP SPACE\n    281 In IN ADP\n    282 9 CD NUM\n    283 years NNS NOUN\n    284 , , PUNCT\n    285 the DT DET\n    286 United NNP PROPN\n    287 States NNP PROPN\n    288 will MD AUX\n    289 celebrate VB VERB\n    290 the DT DET\n    291 250th JJ ADJ\n    292 anniversary NN NOUN\n    293 of IN ADP\n    294 our PRP$ PRON\n    295 founding NN NOUN\n    296 : : PUNCT\n    297 250 CD NUM\n    298 years NNS NOUN\n    299 since IN SCONJ\n    300 the DT DET\n    301 day NN NOUN\n    302 we PRP PRON\n    303 declared VBD VERB\n    304 our PRP$ PRON\n    305 independence NN NOUN\n    306 . . PUNCT\n    307 It PRP PRON\n    308 will MD AUX\n    309 be VB VERB\n    310 one CD NUM\n    311 of IN ADP\n    312 the DT DET\n    313 great JJ ADJ\n    314 milestones NNS NOUN\n    315 in IN ADP\n    316 the DT DET\n    317 history NN NOUN\n    318 of IN ADP\n    319 the DT DET\n    320 world NN NOUN\n    321 . . PUNCT\n    322 But CC CCONJ\n    323 what WP PRON\n    324 will MD AUX\n    325 America NNP PROPN\n    326 look VB VERB\n    327 like IN ADP\n    328 as IN ADP\n    329 we PRP PRON\n    330 reach VBP VERB\n    331 our PRP$ PRON\n    332 250th JJ ADJ\n    333 year NN NOUN\n    334 ? . PUNCT\n    335 What WDT DET\n    336 kind NN NOUN\n    337 of IN ADP\n    338 country NN NOUN\n    339 will MD AUX\n    340 we PRP PRON\n    341 leave VB VERB\n    342 for IN ADP\n    343 our PRP$ PRON\n    344 children NNS NOUN\n    345 ? . PUNCT\n    346 \n    \n     _SP SPACE\n    347 I PRP PRON\n    348 will MD AUX\n    349 not RB PART\n    350 allow VB VERB\n    351 the DT DET\n    352 mistakes NNS NOUN\n    353 of IN ADP\n    354 recent JJ ADJ\n    355 decades NNS NOUN\n    356 past JJ ADJ\n    357 to TO PART\n    358 define VB VERB\n    359 the DT DET\n    360 course NN NOUN\n    361 of IN ADP\n    362 our PRP$ PRON\n    363 future NN NOUN\n    364 . . PUNCT\n    365 For IN ADP\n    366 too RB ADV\n    367 long RB ADV\n    368 , , PUNCT\n    369 we PRP PRON\n    370 've VBP AUX\n    371 watched VBN VERB\n    372 our PRP$ PRON\n    373 middle JJ ADJ\n    374 class NN NOUN\n    375 shrink NN NOUN\n    376 as IN ADP\n    377 we PRP PRON\n    378 've VBP AUX\n    379 exported VBN VERB\n    380 our PRP$ PRON\n    381 jobs NNS NOUN\n    382 and CC CCONJ\n    383 wealth NN NOUN\n    384 to IN ADP\n    385 foreign JJ ADJ\n    386 countries NNS NOUN\n    387 . . PUNCT\n    388 We PRP PRON\n    389 've VBP AUX\n    390 financed VBN VERB\n    391 and CC CCONJ\n    392 built VBD VERB\n    393 one CD NUM\n    394 global JJ ADJ\n    395 project NN NOUN\n    396 after IN ADP\n    397 another DT DET\n    398 , , PUNCT\n    399 but CC CCONJ\n    400 ignored VBD VERB\n    401 the DT DET\n    402 fates NNS NOUN\n    403 of IN ADP\n    404 our PRP$ PRON\n    405 children NNS NOUN\n    406 in IN ADP\n    407 the DT DET\n    408 inner JJ ADJ\n    409 cities NNS NOUN\n    410 of IN ADP\n    411 Chicago NNP PROPN\n    412 , , PUNCT\n    413 Baltimore NNP PROPN\n    414 , , PUNCT\n    415 Detroit NNP PROPN\n    416 , , PUNCT\n    417 and CC CCONJ\n    418 so RB ADV\n    419 many JJ ADJ\n    420 other JJ ADJ\n    421 places NNS NOUN\n    422 throughout IN ADP\n    423 our PRP$ PRON\n    424 land NN NOUN\n    425 . . PUNCT\n    426 \n    \n     _SP SPACE\n    427 We PRP PRON\n    428 've VBP AUX\n    429 defended VBN VERB\n    430 the DT DET\n    431 borders NNS NOUN\n    432 of IN ADP\n    433 other JJ ADJ\n    434 nations NNS NOUN\n    435 , , PUNCT\n    436 while IN SCONJ\n    437 leaving VBG VERB\n    438 our PRP$ PRON\n    439 own JJ ADJ\n    440 borders NNS NOUN\n    441 wide RB ADV\n    442 open JJ ADJ\n    443 for IN ADP\n    444 anyone NN PRON\n    445 to TO PART\n    446 cross VB VERB\n    447 and CC CCONJ\n    448 for IN ADP\n    449 drugs NNS NOUN\n    450 to TO PART\n    451 pour VB VERB\n    452 in RP ADP\n    453 at IN ADP\n    454 a DT DET\n    455 now RB ADV\n    456 unprecedented JJ ADJ\n    457 rate NN NOUN\n    458 . . PUNCT\n    459 And CC CCONJ\n    460 we PRP PRON\n    461 've VBP AUX\n    462 spent VBN VERB\n    463 trillions NNS NOUN\n    464 and CC CCONJ\n    465 trillions NNS NOUN\n    466 of IN ADP\n    467 dollars NNS NOUN\n    468 overseas RB ADV\n    469 , , PUNCT\n    470 while IN SCONJ\n    471 our PRP$ PRON\n    472 infrastructure NN NOUN\n    473 at IN ADP\n    474 home NN NOUN\n    475 has VBZ AUX\n    476 so RB ADV\n    477 badly RB ADV\n    478 crumbled VBN VERB\n    479 . . PUNCT\n    480 \n    \n     _SP SPACE\n    481 Then RB ADV\n    482 , , PUNCT\n    483 in IN ADP\n    484 2016 CD NUM\n    485 , , PUNCT\n    486 the DT DET\n    487 Earth NNP PROPN\n    488 shifted VBD VERB\n    489 beneath IN ADP\n    490 our PRP$ PRON\n    491 feet NNS NOUN\n    492 . . PUNCT\n    493 The DT DET\n    494 rebellion NN NOUN\n    495 started VBD VERB\n    496 as IN ADP\n    497 a DT DET\n    498 quiet JJ ADJ\n    499 protest NN NOUN\n    500 , , PUNCT\n    501 spoken VBN VERB\n    502 by IN ADP\n    503 families NNS NOUN\n    504 of IN ADP\n    505 all DT DET\n    506 colors NNS NOUN\n    507 and CC CCONJ\n    508 creeds NNS NOUN\n    509 , , PUNCT\n    510 families NNS NOUN\n    511 who WP PRON\n    512 just RB ADV\n    513 wanted VBD VERB\n    514 a DT DET\n    515 fair JJ ADJ\n    516 shot NN NOUN\n    517 for IN ADP\n    518 their PRP$ PRON\n    519 children NNS NOUN\n    520 and CC CCONJ\n    521 a DT DET\n    522 fair JJ ADJ\n    523 hearing NN NOUN\n    524 for IN ADP\n    525 their PRP$ PRON\n    526 concerns NNS NOUN\n    527 . . PUNCT\n    528 \n    \n     _SP SPACE\n    529 But CC CCONJ\n    530 then RB ADV\n    531 the DT DET\n    532 quiet JJ ADJ\n    533 voices NNS NOUN\n    534 became VBD VERB\n    535 a DT DET\n    536 loud JJ ADJ\n    537 chorus NN NOUN\n    538 , , PUNCT\n    539 as IN ADP\n    540 thousands NNS NOUN\n    541 of IN ADP\n    542 citizens NNS NOUN\n    543 now RB ADV\n    544 spoke VBD VERB\n    545 out RP ADP\n    546 together RB ADV\n    547 , , PUNCT\n    548 from IN ADP\n    549 cities NNS NOUN\n    550 small JJ ADJ\n    551 and CC CCONJ\n    552 large JJ ADJ\n    553 , , PUNCT\n    554 all RB ADV\n    555 across IN ADP\n    556 our PRP$ PRON\n    557 country NN NOUN\n    558 . . PUNCT\n    559 Finally RB ADV\n    560 , , PUNCT\n    561 the DT DET\n    562 chorus NN NOUN\n    563 became VBD VERB\n    564 an DT DET\n    565 earthquake NN NOUN\n    566 , , PUNCT\n    567 and CC CCONJ\n    568 the DT DET\n    569 people NNS NOUN\n    570 turned VBD VERB\n    571 out RP ADP\n    572 by IN ADP\n    573 the DT DET\n    574 tens NNS NOUN\n    575 of IN ADP\n    576 millions NNS NOUN\n    577 , , PUNCT\n    578 and CC CCONJ\n    579 they PRP PRON\n    580 were VBD AUX\n    581 all RB ADV\n    582 united VBN VERB\n    583 by IN ADP\n    584 one CD NUM\n    585 very RB ADV\n    586 simple JJ ADJ\n    587 , , PUNCT\n    588 but CC CCONJ\n    589 crucial JJ ADJ\n    590 demand NN NOUN\n    591 : : PUNCT\n    592 that IN SCONJ\n    593 America NNP PROPN\n    594 must MD AUX\n    595 put VB VERB\n    596 its PRP$ PRON\n    597 own JJ ADJ\n    598 citizens NNS NOUN\n    599 first RB ADV\n    600 . . PUNCT\n    601 Because IN SCONJ\n    602 only RB ADV\n    603 then RB ADV\n    604 can MD AUX\n    605 we PRP PRON\n    606 truly RB ADV\n    607 make VB VERB\n    608 America NNP PROPN\n    609 great JJ ADJ\n    610 again RB ADV\n    611 . . PUNCT\n    612 \n    \n     _SP SPACE\n    613 Dying VBG VERB\n    614 industries NNS NOUN\n    615 will MD AUX\n    616 come VB VERB\n    617 roaring VBG VERB\n    618 back RB ADV\n    619 to IN ADP\n    620 life NN NOUN\n    621 . . PUNCT\n    622 Heroic JJ ADJ\n    623 veterans NNS NOUN\n    624 will MD AUX\n    625 get VB VERB\n    626 the DT DET\n    627 care NN NOUN\n    628 they PRP PRON\n    629 so RB ADV\n    630 desperately RB ADV\n    631 need VBP VERB\n    632 . . PUNCT\n    633 Our PRP$ PRON\n    634 military NN NOUN\n    635 will MD AUX\n    636 be VB AUX\n    637 given VBN VERB\n    638 the DT DET\n    639 resources NNS NOUN\n    640 its PRP$ PRON\n    641 brave JJ ADJ\n    642 warriors NNS NOUN\n    643 so RB ADV\n    644 richly RB ADV\n    645 deserve VBP VERB\n    646 . . PUNCT\n    647 Crumbling VBG VERB\n    648 infrastructure NN NOUN\n    649 will MD AUX\n    650 be VB AUX\n    651 replaced VBN VERB\n    652 with IN ADP\n    653 new JJ ADJ\n    654 roads NNS NOUN\n    655 , , PUNCT\n    656 bridges NNS NOUN\n    657 , , PUNCT\n    658 tunnels NNS NOUN\n    659 , , PUNCT\n    660 airports NNS NOUN\n    661 , , PUNCT\n    662 and CC CCONJ\n    663 railways VBZ VERB\n    664 gleaming VBG VERB\n    665 across IN ADP\n    666 our PRP$ PRON\n    667 very RB ADV\n    668 , , PUNCT\n    669 very RB ADV\n    670 beautiful JJ ADJ\n    671 land NN NOUN\n    672 . . PUNCT\n    673 Our PRP$ PRON\n    674 terrible JJ ADJ\n    675 drug NN NOUN\n    676 epidemic NN NOUN\n    677 will MD AUX\n    678 slow VB VERB\n    679 down RP ADP\n    680 and CC CCONJ\n    681 , , PUNCT\n    682 ultimately RB ADV\n    683 , , PUNCT\n    684 stop VB VERB\n    685 . . PUNCT\n    686 And CC CCONJ\n    687 our PRP$ PRON\n    688 neglected VBN VERB\n    689 inner JJ ADJ\n    690 cities NNS NOUN\n    691 will MD AUX\n    692 see VB VERB\n    693 a DT DET\n    694 rebirth NN NOUN\n    695 of IN ADP\n    696 hope NN NOUN\n    697 , , PUNCT\n    698 safety NN NOUN\n    699 , , PUNCT\n    700 and CC CCONJ\n    701 opportunity NN NOUN\n    702 . . PUNCT\n    703 Above IN ADP\n    704 all DT DET\n    705 else RB ADV\n    706 , , PUNCT\n    707 we PRP PRON\n    708 will MD AUX\n    709 keep VB VERB\n    710 our PRP$ PRON\n    711 promises NNS NOUN\n    712 to IN ADP\n    713 the DT DET\n    714 American JJ ADJ\n    715 people NNS NOUN\n    716 . . PUNCT\n    717 [ XX X\n    718 Applause XX X\n    719 ] XX X\n    720 Thank VBP VERB\n    721 you PRP PRON\n    722 . . PUNCT\n    723 \n    \n     _SP SPACE\n    724 It PRP PRON\n    725 's VBZ AUX\n    726 been VBN VERB\n    727 a DT DET\n    728 little JJ ADJ\n    729 over IN ADP\n    730 a DT DET\n    731 month NN NOUN\n    732 since IN SCONJ\n    733 my PRP$ PRON\n    734 Inauguration NNP PROPN\n    735 , , PUNCT\n    736 and CC CCONJ\n    737 I PRP PRON\n    738 want VBP VERB\n    739 to TO PART\n    740 take VB VERB\n    741 this DT DET\n    742 moment NN NOUN\n    743 to TO PART\n    744 update VB VERB\n    745 the DT DET\n    746 Nation NN NOUN\n    747 on IN ADP\n    748 the DT DET\n    749 progress NN NOUN\n    750 I PRP PRON\n    751 've VBP AUX\n    752 made VBN VERB\n    753 in IN ADP\n    754 keeping VBG VERB\n    755 those DT DET\n    756 promises NNS NOUN\n    757 . . PUNCT\n    758 \n    \n     _SP SPACE\n    759 Since IN SCONJ\n    760 my PRP$ PRON\n    761 election NN NOUN\n    762 , , PUNCT\n    763 Ford NNP PROPN\n    764 , , PUNCT\n    765 Fiat NNP PROPN\n    766 Chrysler NNP PROPN\n    767 , , PUNCT\n    768 General NNP PROPN\n    769 Motors NNPS PROPN\n    770 , , PUNCT\n    771 Sprint NNP PROPN\n    772 , , PUNCT\n    773 Softbank NNP PROPN\n    774 , , PUNCT\n    775 Lockheed NNP PROPN\n    776 , , PUNCT\n    777 Intel NNP PROPN\n    778 , , PUNCT\n    779 Walmart NNP PROPN\n    780 , , PUNCT\n    781 and CC CCONJ\n    782 many JJ ADJ\n    783 others NNS NOUN\n    784 have VBP AUX\n    785 announced VBN VERB\n    786 that IN SCONJ\n    787 they PRP PRON\n    788 will MD AUX\n    789 invest VB VERB\n    790 billions NNS NOUN\n    791 and CC CCONJ\n    792 billions NNS NOUN\n    793 of IN ADP\n    794 dollars NNS NOUN\n    795 in IN ADP\n    796 the DT DET\n    797 United NNP PROPN\n    798 States NNP PROPN\n    799 and CC CCONJ\n    800 will MD AUX\n    801 create VB VERB\n    802 tens NNS NOUN\n    803 of IN ADP\n    804 thousands NNS NOUN\n    805 of IN ADP\n    806 new JJ ADJ\n    807 American JJ ADJ\n    808 jobs NNS NOUN\n    809 . . PUNCT\n    810 \n    \n     _SP SPACE\n    811 The DT DET\n    812 stock NN NOUN\n    813 market NN NOUN\n    814 has VBZ AUX\n    815 gained VBN VERB\n    816 almost RB ADV\n    817 $ $ SYM\n    818 3 CD NUM\n    819 trillion CD NUM\n    820 in IN ADP\n    821 value NN NOUN\n    822 since IN SCONJ\n    823 the DT DET\n    824 election NN NOUN\n    825 on IN ADP\n    826 November NNP PROPN\n    827 8 CD NUM\n    828 \u2014 : PUNCT\n    829 a DT DET\n    830 record NN NOUN\n    831 . . PUNCT\n    832 We PRP PRON\n    833 've VBP AUX\n    834 saved VBN VERB\n    835 taxpayers NNS NOUN\n    836 hundreds NNS NOUN\n    837 of IN ADP\n    838 millions NNS NOUN\n    839 of IN ADP\n    840 dollars NNS NOUN\n    841 by IN ADP\n    842 bringing VBG VERB\n    843 down RP ADP\n    844 the DT DET\n    845 price NN NOUN\n    846 of IN ADP\n    847 fantastic NN NOUN\n    848 \u2014 : PUNCT\n    849 and CC CCONJ\n    850 it PRP PRON\n    851 is VBZ VERB\n    852 a DT DET\n    853 fantastic JJ ADJ\n    854 \u2014 : PUNCT\n    855 new JJ ADJ\n    856 F-35 CD NUM\n    857 jet NN NOUN\n    858 fighter NN NOUN\n    859 , , PUNCT\n    860 and CC CCONJ\n    861 we PRP PRON\n    862 'll MD AUX\n    863 be VB AUX\n    864 saving VBG VERB\n    865 billions NNS NOUN\n    866 more RBR ADV\n    867 on IN ADP\n    868 contracts NNS NOUN\n    869 all RB ADV\n    870 across IN ADP\n    871 our PRP$ PRON\n    872 Government NNP PROPN\n    873 . . PUNCT\n    874 We PRP PRON\n    875 have VBP AUX\n    876 placed VBN VERB\n    877 a DT DET\n    878 hiring VBG VERB\n    879 freeze NN NOUN\n    880 on IN ADP\n    881 nonmilitary JJ ADJ\n    882 and CC CCONJ\n    883 nonessential JJ ADJ\n    884 Federal JJ ADJ\n    885 workers NNS NOUN\n    886 . . PUNCT\n    887 \n    \n     _SP SPACE\n    888 We PRP PRON\n    889 have VBP AUX\n    890 begun VBN VERB\n    891 to TO PART\n    892 drain VB VERB\n    893 the DT DET\n    894 swamp NN NOUN\n    895 of IN ADP\n    896 government NN NOUN\n    897 corruption NN NOUN\n    898 by IN ADP\n    899 imposing VBG VERB\n    900 a DT DET\n    901 5 CD NUM\n    902 - HYPH PUNCT\n    903 year NN NOUN\n    904 ban NN NOUN\n    905 on IN ADP\n    906 lobbying NN NOUN\n    907 by IN ADP\n    908 executive JJ ADJ\n    909 branch NN NOUN\n    910 officials NNS NOUN\n    911 and CC CCONJ\n    912 a DT DET\n    913 lifetime NN NOUN\n    914 ban\u2014[applause]\u2014thank NN NOUN\n    915 you PRP PRON\n    916 . . PUNCT\n    917 Thank VBP VERB\n    918 you PRP PRON\n    919 . . PUNCT\n    920 And CC CCONJ\n    921 a DT DET\n    922 lifetime NN NOUN\n    923 ban NN NOUN\n    924 on IN ADP\n    925 becoming VBG VERB\n    926 lobbyists NNS NOUN\n    927 for IN ADP\n    928 a DT DET\n    929 foreign JJ ADJ\n    930 government NN NOUN\n    931 . . PUNCT\n    932 \n    \n     _SP SPACE\n    933 We PRP PRON\n    934 have VBP AUX\n    935 undertaken VBN VERB\n    936 a DT DET\n    937 historic JJ ADJ\n    938 effort NN NOUN\n    939 to TO PART\n    940 massively RB ADV\n    941 reduce VB VERB\n    942 job NN NOUN\n    943 - HYPH PUNCT\n    944 crushing VBG VERB\n    945 regulations NNS NOUN\n    946 , , PUNCT\n    947 creating VBG VERB\n    948 a DT DET\n    949 deregulation NN NOUN\n    950 Task NNP PROPN\n    951 Force NNP PROPN\n    952 inside RB ADV\n    953 of IN ADP\n    954 every DT DET\n    955 Government NNP PROPN\n    956 agency NN NOUN\n    957 . . PUNCT\n    958 And CC CCONJ\n    959 we PRP PRON\n    960 're VBP AUX\n    961 imposing VBG VERB\n    962 a DT DET\n    963 new JJ ADJ\n    964 rule NN NOUN\n    965 which WDT DET\n    966 mandates VBZ VERB\n    967 that IN SCONJ\n    968 for IN ADP\n    969 every DT DET\n    970 one CD NUM\n    971 new JJ ADJ\n    972 regulation NN NOUN\n    973 , , PUNCT\n    974 two CD NUM\n    975 old JJ ADJ\n    976 regulations NNS NOUN\n    977 must MD AUX\n    978 be VB AUX\n    979 eliminated VBN VERB\n    980 . . PUNCT\n    981 We PRP PRON\n    982 're VBP AUX\n    983 going VBG VERB\n    984 to TO PART\n    985 stop VB VERB\n    986 the DT DET\n    987 regulations NNS NOUN\n    988 that WDT DET\n    989 threaten VBP VERB\n    990 the DT DET\n    991 future NN NOUN\n    992 and CC CCONJ\n    993 livelihood NN NOUN\n    994 of IN ADP\n    995 our PRP$ PRON\n    996 great JJ ADJ\n    997 coal NN NOUN\n    998 miners NNS NOUN\n    999 . . PUNCT\n    1000 \n    \n     _SP SPACE\n    1001 We PRP PRON\n    1002 have VBP AUX\n    1003 cleared VBN VERB\n    1004 the DT DET\n    1005 way NN NOUN\n    1006 for IN ADP\n    1007 the DT DET\n    1008 construction NN NOUN\n    1009 of IN ADP\n    1010 the DT DET\n    1011 Keystone NNP PROPN\n    1012 and CC CCONJ\n    1013 Dakota NNP PROPN\n    1014 Access NNP PROPN\n    1015 pipelines NNS NOUN\n    1016 , , PUNCT\n    1017 thereby RB ADV\n    1018 creating VBG VERB\n    1019 tens NNS NOUN\n    1020 of IN ADP\n    1021 thousands NNS NOUN\n    1022 of IN ADP\n    1023 jobs NNS NOUN\n    1024 . . PUNCT\n    1025 And CC CCONJ\n    1026 I PRP PRON\n    1027 've VBP AUX\n    1028 issued VBN VERB\n    1029 a DT DET\n    1030 new JJ ADJ\n    1031 directive NN NOUN\n    1032 that WDT DET\n    1033 new JJ ADJ\n    1034 American JJ ADJ\n    1035 pipelines NNS NOUN\n    1036 be VB AUX\n    1037 made VBN VERB\n    1038 with IN ADP\n    1039 American JJ ADJ\n    1040 steel NN NOUN\n    1041 . . PUNCT\n    1042 \n    \n     _SP SPACE\n    1043 We PRP PRON\n    1044 have VBP AUX\n    1045 withdrawn VBN VERB\n    1046 the DT DET\n    1047 United NNP PROPN\n    1048 States NNP PROPN\n    1049 from IN ADP\n    1050 the DT DET\n    1051 job NN NOUN\n    1052 - HYPH PUNCT\n    1053 killing VBG VERB\n    1054 Trans NNP PROPN\n    1055 - NNP PROPN\n    1056 Pacific NNP PROPN\n    1057 Partnership NNP PROPN\n    1058 . . PUNCT\n    1059 And CC CCONJ\n    1060 with IN ADP\n    1061 the DT DET\n    1062 help NN NOUN\n    1063 of IN ADP\n    1064 Prime NNP PROPN\n    1065 Minister NNP PROPN\n    1066 Justin NNP PROPN\n    1067 Trudeau NNP PROPN\n    1068 , , PUNCT\n    1069 we PRP PRON\n    1070 have VBP AUX\n    1071 formed VBN VERB\n    1072 a DT DET\n    1073 council NN NOUN\n    1074 with IN ADP\n    1075 our PRP$ PRON\n    1076 neighbors NNS NOUN\n    1077 in IN ADP\n    1078 Canada NNP PROPN\n    1079 to TO PART\n    1080 help VB VERB\n    1081 ensure VB VERB\n    1082 that IN SCONJ\n    1083 women NNS NOUN\n    1084 entrepreneurs NNS NOUN\n    1085 have VBP VERB\n    1086 access NN NOUN\n    1087 to IN ADP\n    1088 the DT DET\n    1089 networks NNS NOUN\n    1090 , , PUNCT\n    1091 markets NNS NOUN\n    1092 , , PUNCT\n    1093 and CC CCONJ\n    1094 capital NN NOUN\n    1095 they PRP PRON\n    1096 need VBP VERB\n    1097 to TO PART\n    1098 start VB VERB\n    1099 a DT DET\n    1100 business NN NOUN\n    1101 and CC CCONJ\n    1102 live VB VERB\n    1103 out RP ADP\n    1104 their PRP$ PRON\n    1105 financial JJ ADJ\n    1106 dreams NNS NOUN\n    1107 . . PUNCT\n    1108 \n    \n     _SP SPACE\n    1109 To TO PART\n    1110 protect VB VERB\n    1111 our PRP$ PRON\n    1112 citizens NNS NOUN\n    1113 , , PUNCT\n    1114 I PRP PRON\n    1115 have VBP AUX\n    1116 directed VBN VERB\n    1117 the DT DET\n    1118 Department NNP PROPN\n    1119 of IN ADP\n    1120 Justice NNP PROPN\n    1121 to TO PART\n    1122 form VB VERB\n    1123 a DT DET\n    1124 Task NNP PROPN\n    1125 Force NNP PROPN\n    1126 on IN ADP\n    1127 Reducing VBG VERB\n    1128 Violent NNP PROPN\n    1129 Crime NNP PROPN\n    1130 . . PUNCT\n    1131 I PRP PRON\n    1132 have VBP AUX\n    1133 further RB ADV\n    1134 ordered VBN VERB\n    1135 the DT DET\n    1136 Departments NNPS PROPN\n    1137 of IN ADP\n    1138 Homeland NNP PROPN\n    1139 Security NNP PROPN\n    1140 and CC CCONJ\n    1141 Justice NNP PROPN\n    1142 , , PUNCT\n    1143 along IN ADP\n    1144 with IN ADP\n    1145 the DT DET\n    1146 Department NNP PROPN\n    1147 of IN ADP\n    1148 State NNP PROPN\n    1149 and CC CCONJ\n    1150 the DT DET\n    1151 Director NNP PROPN\n    1152 of IN ADP\n    1153 National NNP PROPN\n    1154 Intelligence NNP PROPN\n    1155 , , PUNCT\n    1156 to TO PART\n    1157 coordinate VB VERB\n    1158 an DT DET\n    1159 aggressive JJ ADJ\n    1160 strategy NN NOUN\n    1161 to TO PART\n    1162 dismantle VB VERB\n    1163 the DT DET\n    1164 criminal JJ ADJ\n    1165 cartels NNS NOUN\n    1166 that WDT DET\n    1167 have VBP AUX\n    1168 spread VBN VERB\n    1169 all RB ADV\n    1170 across IN ADP\n    1171 our PRP$ PRON\n    1172 Nation NN NOUN\n    1173 . . PUNCT\n    1174 We PRP PRON\n    1175 will MD AUX\n    1176 stop VB VERB\n    1177 the DT DET\n    1178 drugs NNS NOUN\n    1179 from IN ADP\n    1180 pouring VBG VERB\n    1181 into IN ADP\n    1182 our PRP$ PRON\n    1183 country NN NOUN\n    1184 and CC CCONJ\n    1185 poisoning VBG VERB\n    1186 our PRP$ PRON\n    1187 youth NN NOUN\n    1188 , , PUNCT\n    1189 and CC CCONJ\n    1190 we PRP PRON\n    1191 will MD AUX\n    1192 expand VB VERB\n    1193 treatment NN NOUN\n    1194 for IN ADP\n    1195 those DT DET\n    1196 who WP PRON\n    1197 have VBP AUX\n    1198 become VBN VERB\n    1199 so RB ADV\n    1200 badly RB ADV\n    1201 addicted JJ ADJ\n    1202 . . PUNCT\n    1203 \n    \n     _SP SPACE\n    1204 At IN ADP\n    1205 the DT DET\n    1206 same JJ ADJ\n    1207 time NN NOUN\n    1208 , , PUNCT\n    1209 my PRP$ PRON\n    1210 administration NN NOUN\n    1211 has VBZ AUX\n    1212 answered VBN VERB\n    1213 the DT DET\n    1214 pleas NNS NOUN\n    1215 of IN ADP\n    1216 the DT DET\n    1217 American JJ ADJ\n    1218 people NNS NOUN\n    1219 for IN ADP\n    1220 immigration NN NOUN\n    1221 enforcement NN NOUN\n    1222 and CC CCONJ\n    1223 border NN NOUN\n    1224 security NN NOUN\n    1225 . . PUNCT\n    1226 By IN ADP\n    1227 finally RB ADV\n    1228 enforcing VBG VERB\n    1229 our PRP$ PRON\n    1230 immigration NN NOUN\n    1231 laws NNS NOUN\n    1232 , , PUNCT\n    1233 we PRP PRON\n    1234 will MD AUX\n    1235 raise VB VERB\n    1236 wages NNS NOUN\n    1237 , , PUNCT\n    1238 help VB VERB\n    1239 the DT DET\n    1240 unemployed JJ ADJ\n    1241 , , PUNCT\n    1242 save VB VERB\n    1243 billions NNS NOUN\n    1244 and CC CCONJ\n    1245 billions NNS NOUN\n    1246 of IN ADP\n    1247 dollars NNS NOUN\n    1248 , , PUNCT\n    1249 and CC CCONJ\n    1250 make VB VERB\n    1251 our PRP$ PRON\n    1252 communities NNS NOUN\n    1253 safer JJR ADJ\n    1254 for IN ADP\n    1255 everyone NN PRON\n    1256 . . PUNCT\n    1257 We PRP PRON\n    1258 want VBP VERB\n    1259 all DT DET\n    1260 Americans NNPS PROPN\n    1261 to TO PART\n    1262 succeed VB VERB\n    1263 , , PUNCT\n    1264 but CC CCONJ\n    1265 that DT DET\n    1266 ca MD AUX\n    1267 n't RB PART\n    1268 happen VB VERB\n    1269 in IN ADP\n    1270 an DT DET\n    1271 environment NN NOUN\n    1272 of IN ADP\n    1273 lawless JJ ADJ\n    1274 chaos NN NOUN\n    1275 . . PUNCT\n    1276 We PRP PRON\n    1277 must MD AUX\n    1278 restore VB VERB\n    1279 integrity NN NOUN\n    1280 and CC CCONJ\n    1281 the DT DET\n    1282 rule NN NOUN\n    1283 of IN ADP\n    1284 law NN NOUN\n    1285 at IN ADP\n    1286 our PRP$ PRON\n    1287 borders NNS NOUN\n    1288 . . PUNCT\n    1289 \n    \n     _SP SPACE\n    1290 For IN ADP\n    1291 that DT DET\n    1292 reason NN NOUN\n    1293 , , PUNCT\n    1294 we PRP PRON\n    1295 will MD AUX\n    1296 soon RB ADV\n    1297 begin VB VERB\n    1298 the DT DET\n    1299 construction NN NOUN\n    1300 of IN ADP\n    1301 a DT DET\n    1302 great JJ ADJ\n    1303 , , PUNCT\n    1304 great JJ ADJ\n    1305 wall NN NOUN\n    1306 along IN ADP\n    1307 our PRP$ PRON\n    1308 southern JJ ADJ\n    1309 border NN NOUN\n    1310 . . PUNCT\n    1311 As IN ADP\n    1312 we PRP PRON\n    1313 speak VBP VERB\n    1314 tonight NN NOUN\n    1315 , , PUNCT\n    1316 we PRP PRON\n    1317 are VBP AUX\n    1318 removing VBG VERB\n    1319 gang NN NOUN\n    1320 members NNS NOUN\n    1321 , , PUNCT\n    1322 drug NN NOUN\n    1323 dealers NNS NOUN\n    1324 , , PUNCT\n    1325 and CC CCONJ\n    1326 criminals NNS NOUN\n    1327 that WDT DET\n    1328 threaten VBP VERB\n    1329 our PRP$ PRON\n    1330 communities NNS NOUN\n    1331 and CC CCONJ\n    1332 prey NN NOUN\n    1333 on IN ADP\n    1334 our PRP$ PRON\n    1335 very RB ADV\n    1336 innocent JJ ADJ\n    1337 citizens NNS NOUN\n    1338 . . PUNCT\n    1339 Bad JJ ADJ\n    1340 ones NNS NOUN\n    1341 are VBP AUX\n    1342 going VBG VERB\n    1343 out RP ADP\n    1344 as IN ADP\n    1345 I PRP PRON\n    1346 speak VBP VERB\n    1347 , , PUNCT\n    1348 and CC CCONJ\n    1349 as IN ADP\n    1350 I PRP PRON\n    1351 've VBP AUX\n    1352 promised VBN VERB\n    1353 throughout IN ADP\n    1354 the DT DET\n    1355 campaign NN NOUN\n    1356 . . PUNCT\n    1357 \n    \n     _SP SPACE\n    1358 To IN ADP\n    1359 any DT DET\n    1360 in IN ADP\n    1361 Congress NNP PROPN\n    1362 who WP PRON\n    1363 do VBP AUX\n    1364 not RB PART\n    1365 believe VB VERB\n    1366 we PRP PRON\n    1367 should MD AUX\n    1368 enforce VB VERB\n    1369 our PRP$ PRON\n    1370 laws NNS NOUN\n    1371 , , PUNCT\n    1372 I PRP PRON\n    1373 would MD AUX\n    1374 ask VB VERB\n    1375 you PRP PRON\n    1376 this DT DET\n    1377 one CD NUM\n    1378 question NN NOUN\n    1379 : : PUNCT\n    1380 What WP PRON\n    1381 would MD AUX\n    1382 you PRP PRON\n    1383 say VB VERB\n    1384 to IN ADP\n    1385 the DT DET\n    1386 American JJ ADJ\n    1387 family NN NOUN\n    1388 that WDT DET\n    1389 loses VBZ VERB\n    1390 their PRP$ PRON\n    1391 jobs NNS NOUN\n    1392 , , PUNCT\n    1393 their PRP$ PRON\n    1394 income NN NOUN\n    1395 , , PUNCT\n    1396 or CC CCONJ\n    1397 their PRP$ PRON\n    1398 loved VBN VERB\n    1399 one NN NOUN\n    1400 because IN SCONJ\n    1401 America NNP PROPN\n    1402 refused VBD VERB\n    1403 to TO PART\n    1404 uphold VB VERB\n    1405 its PRP$ PRON\n    1406 laws NNS NOUN\n    1407 and CC CCONJ\n    1408 defend VB VERB\n    1409 its PRP$ PRON\n    1410 borders NNS NOUN\n    1411 ? . PUNCT\n    1412 \n    \n     _SP SPACE\n    1413 Our PRP$ PRON\n    1414 obligation NN NOUN\n    1415 is VBZ AUX\n    1416 to TO PART\n    1417 serve VB VERB\n    1418 , , PUNCT\n    1419 protect VB VERB\n    1420 , , PUNCT\n    1421 and CC CCONJ\n    1422 defend VB VERB\n    1423 the DT DET\n    1424 citizens NNS NOUN\n    1425 of IN ADP\n    1426 the DT DET\n    1427 United NNP PROPN\n    1428 States NNP PROPN\n    1429 . . PUNCT\n    1430 We PRP PRON\n    1431 are VBP AUX\n    1432 also RB ADV\n    1433 taking VBG VERB\n    1434 strong JJ ADJ\n    1435 measures NNS NOUN\n    1436 to TO PART\n    1437 protect VB VERB\n    1438 our PRP$ PRON\n    1439 Nation NN NOUN\n    1440 from IN ADP\n    1441 radical JJ ADJ\n    1442 Islamic JJ ADJ\n    1443 terrorism NN NOUN\n    1444 . . PUNCT\n    1445 According VBG VERB\n    1446 to IN ADP\n    1447 data NNS NOUN\n    1448 provided VBN VERB\n    1449 by IN ADP\n    1450 the DT DET\n    1451 Department NNP PROPN\n    1452 of IN ADP\n    1453 Justice NNP PROPN\n    1454 , , PUNCT\n    1455 the DT DET\n    1456 vast JJ ADJ\n    1457 majority NN NOUN\n    1458 of IN ADP\n    1459 individuals NNS NOUN\n    1460 convicted VBN VERB\n    1461 of IN ADP\n    1462 terrorism NN NOUN\n    1463 and CC CCONJ\n    1464 terrorism NN NOUN\n    1465 - HYPH PUNCT\n    1466 related VBN VERB\n    1467 offenses NNS NOUN\n    1468 since IN SCONJ\n    1469 9/11 CD NUM\n    1470 came VBD VERB\n    1471 here RB ADV\n    1472 from IN ADP\n    1473 outside IN ADP\n    1474 of IN ADP\n    1475 our PRP$ PRON\n    1476 country NN NOUN\n    1477 . . PUNCT\n    1478 We PRP PRON\n    1479 have VBP AUX\n    1480 seen VBN VERB\n    1481 the DT DET\n    1482 attacks NNS NOUN\n    1483 at IN ADP\n    1484 home NN NOUN\n    1485 , , PUNCT\n    1486 from IN ADP\n    1487 Boston NNP PROPN\n    1488 to IN ADP\n    1489 San NNP PROPN\n    1490 Bernardino NNP PROPN\n    1491 to IN ADP\n    1492 the DT DET\n    1493 Pentagon NNP PROPN\n    1494 , , PUNCT\n    1495 and CC CCONJ\n    1496 , , PUNCT\n    1497 yes UH INTJ\n    1498 , , PUNCT\n    1499 even RB ADV\n    1500 the DT DET\n    1501 World NNP PROPN\n    1502 Trade NNP PROPN\n    1503 Center NNP PROPN\n    1504 . . PUNCT\n    1505 \n    \n     _SP SPACE\n    1506 We PRP PRON\n    1507 have VBP AUX\n    1508 seen VBN VERB\n    1509 the DT DET\n    1510 attacks NNS NOUN\n    1511 in IN ADP\n    1512 France NNP PROPN\n    1513 , , PUNCT\n    1514 in IN ADP\n    1515 Belgium NNP PROPN\n    1516 , , PUNCT\n    1517 in IN ADP\n    1518 Germany NNP PROPN\n    1519 , , PUNCT\n    1520 and CC CCONJ\n    1521 all RB ADV\n    1522 over IN ADP\n    1523 the DT DET\n    1524 world NN NOUN\n    1525 . . PUNCT\n    1526 It PRP PRON\n    1527 is VBZ AUX\n    1528 not RB PART\n    1529 compassionate JJ ADJ\n    1530 , , PUNCT\n    1531 but CC CCONJ\n    1532 reckless JJ ADJ\n    1533 to TO PART\n    1534 allow VB VERB\n    1535 uncontrolled JJ ADJ\n    1536 entry NN NOUN\n    1537 from IN ADP\n    1538 places NNS NOUN\n    1539 where WRB ADV\n    1540 proper JJ ADJ\n    1541 vetting NN NOUN\n    1542 can MD AUX\n    1543 not RB PART\n    1544 occur VB VERB\n    1545 . . PUNCT\n    1546 Those DT DET\n    1547 given VBN VERB\n    1548 the DT DET\n    1549 high JJ ADJ\n    1550 honor NN NOUN\n    1551 of IN ADP\n    1552 admission NN NOUN\n    1553 to IN ADP\n    1554 the DT DET\n    1555 United NNP PROPN\n    1556 States NNP PROPN\n    1557 should MD AUX\n    1558 support VB VERB\n    1559 this DT DET\n    1560 country NN NOUN\n    1561 and CC CCONJ\n    1562 love VB VERB\n    1563 its PRP$ PRON\n    1564 people NNS NOUN\n    1565 and CC CCONJ\n    1566 its PRP$ PRON\n    1567 values NNS NOUN\n    1568 . . PUNCT\n    1569 We PRP PRON\n    1570 can MD AUX\n    1571 not RB PART\n    1572 allow VB VERB\n    1573 a DT DET\n    1574 beachhead NN NOUN\n    1575 of IN ADP\n    1576 terrorism NN NOUN\n    1577 to TO PART\n    1578 form VB VERB\n    1579 inside IN ADP\n    1580 America NNP PROPN\n    1581 . . PUNCT\n    1582 We PRP PRON\n    1583 can MD AUX\n    1584 not RB PART\n    1585 allow VB VERB\n    1586 our PRP$ PRON\n    1587 Nation NN NOUN\n    1588 to TO PART\n    1589 become VB VERB\n    1590 a DT DET\n    1591 sanctuary NN NOUN\n    1592 for IN ADP\n    1593 extremists NNS NOUN\n    1594 . . PUNCT\n    1595 \n    \n     _SP SPACE\n    1596 That DT DET\n    1597 is VBZ AUX\n    1598 why WRB ADV\n    1599 my PRP$ PRON\n    1600 administration NN NOUN\n    1601 has VBZ AUX\n    1602 been VBN AUX\n    1603 working VBG VERB\n    1604 on IN ADP\n    1605 improved JJ ADJ\n    1606 vetting NN NOUN\n    1607 procedures NNS NOUN\n    1608 , , PUNCT\n    1609 and CC CCONJ\n    1610 we PRP PRON\n    1611 will MD AUX\n    1612 shortly RB ADV\n    1613 take VB VERB\n    1614 new JJ ADJ\n    1615 steps NNS NOUN\n    1616 to TO PART\n    1617 keep VB VERB\n    1618 our PRP$ PRON\n    1619 Nation NN NOUN\n    1620 safe JJ ADJ\n    1621 and CC CCONJ\n    1622 to TO PART\n    1623 keep VB VERB\n    1624 those DT DET\n    1625 out RP ADP\n    1626 who WP PRON\n    1627 will MD AUX\n    1628 do VB VERB\n    1629 us PRP PRON\n    1630 harm VB VERB\n    1631 . . PUNCT\n    1632 \n    \n     _SP SPACE\n    1633 As IN ADP\n    1634 promised VBN VERB\n    1635 , , PUNCT\n    1636 I PRP PRON\n    1637 directed VBD VERB\n    1638 the DT DET\n    1639 Department NNP PROPN\n    1640 of IN ADP\n    1641 Defense NNP PROPN\n    1642 to TO PART\n    1643 develop VB VERB\n    1644 a DT DET\n    1645 plan NN NOUN\n    1646 to TO PART\n    1647 demolish VB VERB\n    1648 and CC CCONJ\n    1649 destroy VB VERB\n    1650 ISIS NNP PROPN\n    1651 , , PUNCT\n    1652 a DT DET\n    1653 network NN NOUN\n    1654 of IN ADP\n    1655 lawless JJ ADJ\n    1656 savages NNS NOUN\n    1657 that WDT DET\n    1658 have VBP AUX\n    1659 slaughtered VBN VERB\n    1660 Muslims NNPS PROPN\n    1661 and CC CCONJ\n    1662 Christians NNPS PROPN\n    1663 , , PUNCT\n    1664 and CC CCONJ\n    1665 men NNS NOUN\n    1666 and CC CCONJ\n    1667 women NNS NOUN\n    1668 and CC CCONJ\n    1669 children NNS NOUN\n    1670 of IN ADP\n    1671 all DT DET\n    1672 faiths NNS NOUN\n    1673 and CC CCONJ\n    1674 all DT DET\n    1675 beliefs NNS NOUN\n    1676 . . PUNCT\n    1677 We PRP PRON\n    1678 will MD AUX\n    1679 work VB VERB\n    1680 with IN ADP\n    1681 our PRP$ PRON\n    1682 allies NNS NOUN\n    1683 , , PUNCT\n    1684 including VBG VERB\n    1685 our PRP$ PRON\n    1686 friends NNS NOUN\n    1687 and CC CCONJ\n    1688 allies NNS NOUN\n    1689 in IN ADP\n    1690 the DT DET\n    1691 Muslim JJ ADJ\n    1692 world NN NOUN\n    1693 , , PUNCT\n    1694 to TO PART\n    1695 extinguish VB VERB\n    1696 this DT DET\n    1697 vile JJ ADJ\n    1698 enemy NN NOUN\n    1699 from IN ADP\n    1700 our PRP$ PRON\n    1701 planet NN NOUN\n    1702 . . PUNCT\n    1703 \n    \n     _SP SPACE\n    1704 I PRP PRON\n    1705 have VBP AUX\n    1706 also RB ADV\n    1707 imposed VBN VERB\n    1708 new JJ ADJ\n    1709 sanctions NNS NOUN\n    1710 on IN ADP\n    1711 entities NNS NOUN\n    1712 and CC CCONJ\n    1713 individuals NNS NOUN\n    1714 who WP PRON\n    1715 support VBP VERB\n    1716 Iran NNP PROPN\n    1717 's POS PART\n    1718 ballistic JJ ADJ\n    1719 missile NN NOUN\n    1720 program NN NOUN\n    1721 and CC CCONJ\n    1722 reaffirmed VBD VERB\n    1723 our PRP$ PRON\n    1724 unbreakable JJ ADJ\n    1725 alliance NN NOUN\n    1726 with IN ADP\n    1727 the DT DET\n    1728 State NNP PROPN\n    1729 of IN ADP\n    1730 Israel NNP PROPN\n    1731 . . PUNCT\n    1732 \n    \n     _SP SPACE\n    1733 Finally RB ADV\n    1734 , , PUNCT\n    1735 I PRP PRON\n    1736 have VBP AUX\n    1737 kept VBN VERB\n    1738 my PRP$ PRON\n    1739 promise NN NOUN\n    1740 to TO PART\n    1741 appoint VB VERB\n    1742 a DT DET\n    1743 Justice NN NOUN\n    1744 to IN ADP\n    1745 the DT DET\n    1746 United NNP PROPN\n    1747 States NNP PROPN\n    1748 Supreme NNP PROPN\n    1749 Court NNP PROPN\n    1750 , , PUNCT\n    1751 from IN ADP\n    1752 my PRP$ PRON\n    1753 list NN NOUN\n    1754 of IN ADP\n    1755 20 CD NUM\n    1756 judges NNS NOUN\n    1757 , , PUNCT\n    1758 who WP PRON\n    1759 will MD AUX\n    1760 defend VB VERB\n    1761 our PRP$ PRON\n    1762 Constitution NNP PROPN\n    1763 . . PUNCT\n    1764 \n    \n     _SP SPACE\n    1765 I PRP PRON\n    1766 am VBP AUX\n    1767 greatly RB ADV\n    1768 honored VBN VERB\n    1769 to TO PART\n    1770 have VB VERB\n    1771 Maureen NNP PROPN\n    1772 Scalia NNP PROPN\n    1773 with IN ADP\n    1774 us PRP PRON\n    1775 in IN ADP\n    1776 the DT DET\n    1777 gallery NN NOUN\n    1778 tonight NN NOUN\n    1779 . . PUNCT\n    1780 Thank VBP VERB\n    1781 you PRP PRON\n    1782 , , PUNCT\n    1783 Maureen NNP PROPN\n    1784 . . PUNCT\n    1785 Her PRP$ PRON\n    1786 late JJ ADJ\n    1787 , , PUNCT\n    1788 great JJ ADJ\n    1789 husband NN NOUN\n    1790 , , PUNCT\n    1791 Antonin NNP PROPN\n    1792 Scalia NNP PROPN\n    1793 , , PUNCT\n    1794 will MD AUX\n    1795 forever RB ADV\n    1796 be VB VERB\n    1797 a DT DET\n    1798 symbol NN NOUN\n    1799 of IN ADP\n    1800 American JJ ADJ\n    1801 justice NN NOUN\n    1802 . . PUNCT\n    1803 To TO PART\n    1804 fill VB VERB\n    1805 his PRP$ PRON\n    1806 seat NN NOUN\n    1807 , , PUNCT\n    1808 we PRP PRON\n    1809 have VBP AUX\n    1810 chosen VBN VERB\n    1811 Judge NNP PROPN\n    1812 Neil NNP PROPN\n    1813 Gorsuch NNP PROPN\n    1814 , , PUNCT\n    1815 a DT DET\n    1816 man NN NOUN\n    1817 of IN ADP\n    1818 incredible JJ ADJ\n    1819 skill NN NOUN\n    1820 and CC CCONJ\n    1821 deep JJ ADJ\n    1822 devotion NN NOUN\n    1823 to IN ADP\n    1824 the DT DET\n    1825 law NN NOUN\n    1826 . . PUNCT\n    1827 He PRP PRON\n    1828 was VBD AUX\n    1829 confirmed VBN VERB\n    1830 unanimously RB ADV\n    1831 by IN ADP\n    1832 the DT DET\n    1833 Court NNP PROPN\n    1834 of IN ADP\n    1835 Appeals NNPS PROPN\n    1836 , , PUNCT\n    1837 and CC CCONJ\n    1838 I PRP PRON\n    1839 am VBP AUX\n    1840 asking VBG VERB\n    1841 the DT DET\n    1842 Senate NNP PROPN\n    1843 to TO PART\n    1844 swiftly RB ADV\n    1845 approve VB VERB\n    1846 his PRP$ PRON\n    1847 nomination NN NOUN\n    1848 . . PUNCT\n    1849 \n    \n     _SP SPACE\n    1850 Tonight NN NOUN\n    1851 , , PUNCT\n    1852 as IN ADP\n    1853 I PRP PRON\n    1854 outline VBP VERB\n    1855 the DT DET\n    1856 next JJ ADJ\n    1857 steps NNS NOUN\n    1858 we PRP PRON\n    1859 must MD AUX\n    1860 take VB VERB\n    1861 as IN ADP\n    1862 a DT DET\n    1863 country NN NOUN\n    1864 , , PUNCT\n    1865 we PRP PRON\n    1866 must MD AUX\n    1867 honestly RB ADV\n    1868 acknowledge VB VERB\n    1869 the DT DET\n    1870 circumstances NNS NOUN\n    1871 we PRP PRON\n    1872 inherited VBD VERB\n    1873 . . PUNCT\n    1874 Ninety CD NUM\n    1875 - HYPH PUNCT\n    1876 four CD NUM\n    1877 million CD NUM\n    1878 Americans NNPS PROPN\n    1879 are VBP AUX\n    1880 out IN SCONJ\n    1881 of IN ADP\n    1882 the DT DET\n    1883 labor NN NOUN\n    1884 force NN NOUN\n    1885 . . PUNCT\n    1886 Over IN ADP\n    1887 43 CD NUM\n    1888 million CD NUM\n    1889 people NNS NOUN\n    1890 are VBP AUX\n    1891 now RB ADV\n    1892 living VBG VERB\n    1893 in IN ADP\n    1894 poverty NN NOUN\n    1895 , , PUNCT\n    1896 and CC CCONJ\n    1897 over IN ADP\n    1898 43 CD NUM\n    1899 million CD NUM\n    1900 Americans NNPS PROPN\n    1901 are VBP VERB\n    1902 on IN ADP\n    1903 food NN NOUN\n    1904 stamps NNS NOUN\n    1905 . . PUNCT\n    1906 More JJR ADJ\n    1907 than IN SCONJ\n    1908 1 CD NUM\n    1909 in IN ADP\n    1910 5 CD NUM\n    1911 people NNS NOUN\n    1912 in IN ADP\n    1913 their PRP$ PRON\n    1914 prime JJ ADJ\n    1915 working NN NOUN\n    1916 years NNS NOUN\n    1917 are VBP AUX\n    1918 not RB PART\n    1919 working VBG VERB\n    1920 . . PUNCT\n    1921 We PRP PRON\n    1922 have VBP VERB\n    1923 the DT DET\n    1924 worst JJS ADJ\n    1925 financial JJ ADJ\n    1926 recovery NN NOUN\n    1927 in IN ADP\n    1928 65 CD NUM\n    1929 years NNS NOUN\n    1930 . . PUNCT\n    1931 In IN ADP\n    1932 the DT DET\n    1933 last JJ ADJ\n    1934 8 CD NUM\n    1935 years NNS NOUN\n    1936 , , PUNCT\n    1937 the DT DET\n    1938 past JJ ADJ\n    1939 administration NN NOUN\n    1940 has VBZ AUX\n    1941 put VBN VERB\n    1942 on RP ADP\n    1943 more JJR ADJ\n    1944 new JJ ADJ\n    1945 debt NN NOUN\n    1946 than IN SCONJ\n    1947 nearly RB ADV\n    1948 all DT DET\n    1949 of IN ADP\n    1950 the DT DET\n    1951 other JJ ADJ\n    1952 Presidents NNS NOUN\n    1953 combined VBN VERB\n    1954 . . PUNCT\n    1955 \n    \n     _SP SPACE\n    1956 We PRP PRON\n    1957 've VBP AUX\n    1958 lost VBN VERB\n    1959 more JJR ADJ\n    1960 than IN SCONJ\n    1961 one CD NUM\n    1962 - HYPH PUNCT\n    1963 fourth NN NOUN\n    1964 of IN ADP\n    1965 our PRP$ PRON\n    1966 manufacturing NN NOUN\n    1967 jobs NNS NOUN\n    1968 since IN SCONJ\n    1969 NAFTA NNP PROPN\n    1970 was VBD AUX\n    1971 approved VBN VERB\n    1972 , , PUNCT\n    1973 and CC CCONJ\n    1974 we PRP PRON\n    1975 've VBP AUX\n    1976 lost VBN VERB\n    1977 60,000 CD NUM\n    1978 factories NNS NOUN\n    1979 since IN SCONJ\n    1980 China NNP PROPN\n    1981 joined VBD VERB\n    1982 the DT DET\n    1983 World NNP PROPN\n    1984 Trade NNP PROPN\n    1985 Organization NNP PROPN\n    1986 in IN ADP\n    1987 2001 CD NUM\n    1988 . . PUNCT\n    1989 Our PRP$ PRON\n    1990 trade NN NOUN\n    1991 deficit NN NOUN\n    1992 in IN ADP\n    1993 goods NNS NOUN\n    1994 with IN ADP\n    1995 the DT DET\n    1996 world NN NOUN\n    1997 last JJ ADJ\n    1998 year NN NOUN\n    1999 was VBD AUX\n    2000 nearly RB ADV\n    2001 $ $ SYM\n    2002 800 CD NUM\n    2003 billion CD NUM\n    2004 dollars NNS NOUN\n    2005 . . PUNCT\n    2006 And CC CCONJ\n    2007 overseas RB ADV\n    2008 we PRP PRON\n    2009 have VBP AUX\n    2010 inherited VBN VERB\n    2011 a DT DET\n    2012 series NN NOUN\n    2013 of IN ADP\n    2014 tragic JJ ADJ\n    2015 foreign JJ ADJ\n    2016 policy NN NOUN\n    2017 disasters NNS NOUN\n    2018 . . PUNCT\n    2019 Solving VBG VERB\n    2020 these DT DET\n    2021 and CC CCONJ\n    2022 so RB ADV\n    2023 many JJ ADJ\n    2024 other JJ ADJ\n    2025 pressing VBG VERB\n    2026 problems NNS NOUN\n    2027 will MD AUX\n    2028 require VB VERB\n    2029 us PRP PRON\n    2030 to TO PART\n    2031 work VB VERB\n    2032 past IN ADP\n    2033 the DT DET\n    2034 differences NNS NOUN\n    2035 of IN ADP\n    2036 party NN NOUN\n    2037 . . PUNCT\n    2038 It PRP PRON\n    2039 will MD AUX\n    2040 require VB VERB\n    2041 us PRP PRON\n    2042 to TO PART\n    2043 tap VB VERB\n    2044 into IN ADP\n    2045 the DT DET\n    2046 American JJ ADJ\n    2047 spirit NN NOUN\n    2048 that WDT DET\n    2049 has VBZ AUX\n    2050 overcome VBN VERB\n    2051 every DT DET\n    2052 challenge NN NOUN\n    2053 throughout IN ADP\n    2054 our PRP$ PRON\n    2055 long JJ ADJ\n    2056 and CC CCONJ\n    2057 storied VBD VERB\n    2058 history NN NOUN\n    2059 . . PUNCT\n    2060 But CC CCONJ\n    2061 to TO PART\n    2062 accomplish VB VERB\n    2063 our PRP$ PRON\n    2064 goals NNS NOUN\n    2065 at IN ADP\n    2066 home NN NOUN\n    2067 and CC CCONJ\n    2068 abroad RB ADV\n    2069 , , PUNCT\n    2070 we PRP PRON\n    2071 must MD AUX\n    2072 restart VB VERB\n    2073 the DT DET\n    2074 engine NN NOUN\n    2075 of IN ADP\n    2076 the DT DET\n    2077 American JJ ADJ\n    2078 economy NN NOUN\n    2079 , , PUNCT\n    2080 making VBG VERB\n    2081 it PRP PRON\n    2082 easier JJR ADJ\n    2083 for IN ADP\n    2084 companies NNS NOUN\n    2085 to TO PART\n    2086 do VB VERB\n    2087 business NN NOUN\n    2088 in IN ADP\n    2089 the DT DET\n    2090 United NNP PROPN\n    2091 States NNP PROPN\n    2092 , , PUNCT\n    2093 and CC CCONJ\n    2094 much JJ ADJ\n    2095 , , PUNCT\n    2096 much RB ADV\n    2097 harder RBR ADV\n    2098 for IN ADP\n    2099 companies NNS NOUN\n    2100 to TO PART\n    2101 leave VB VERB\n    2102 our PRP$ PRON\n    2103 country NN NOUN\n    2104 . . PUNCT\n    2105 \n    \n     _SP SPACE\n    2106 Right RB ADV\n    2107 now RB ADV\n    2108 American JJ ADJ\n    2109 companies NNS NOUN\n    2110 are VBP AUX\n    2111 taxed VBN VERB\n    2112 at IN ADP\n    2113 one CD NUM\n    2114 of IN ADP\n    2115 the DT DET\n    2116 highest JJS ADJ\n    2117 rates NNS NOUN\n    2118 anywhere RB ADV\n    2119 in IN ADP\n    2120 the DT DET\n    2121 world NN NOUN\n    2122 . . PUNCT\n    2123 My PRP$ PRON\n    2124 economic JJ ADJ\n    2125 team NN NOUN\n    2126 is VBZ AUX\n    2127 developing VBG VERB\n    2128 historic JJ ADJ\n    2129 tax NN NOUN\n    2130 reform NN NOUN\n    2131 that WDT DET\n    2132 will MD AUX\n    2133 reduce VB VERB\n    2134 the DT DET\n    2135 tax NN NOUN\n    2136 rate NN NOUN\n    2137 on IN ADP\n    2138 our PRP$ PRON\n    2139 companies NNS NOUN\n    2140 so IN SCONJ\n    2141 they PRP PRON\n    2142 can MD AUX\n    2143 compete VB VERB\n    2144 and CC CCONJ\n    2145 thrive VB VERB\n    2146 anywhere RB ADV\n    2147 and CC CCONJ\n    2148 with IN ADP\n    2149 anyone NN PRON\n    2150 . . PUNCT\n    2151 It PRP PRON\n    2152 will MD AUX\n    2153 be VB VERB\n    2154 a DT DET\n    2155 big JJ ADJ\n    2156 , , PUNCT\n    2157 big JJ ADJ\n    2158 cut NN NOUN\n    2159 . . PUNCT\n    2160 \n    \n     _SP SPACE\n    2161 At IN ADP\n    2162 the DT DET\n    2163 same JJ ADJ\n    2164 time NN NOUN\n    2165 , , PUNCT\n    2166 we PRP PRON\n    2167 will MD AUX\n    2168 provide VB VERB\n    2169 massive JJ ADJ\n    2170 tax NN NOUN\n    2171 relief NN NOUN\n    2172 for IN ADP\n    2173 the DT DET\n    2174 middle JJ ADJ\n    2175 class NN NOUN\n    2176 . . PUNCT\n    2177 We PRP PRON\n    2178 must MD AUX\n    2179 create VB VERB\n    2180 a DT DET\n    2181 level JJ ADJ\n    2182 playing NN NOUN\n    2183 field NN NOUN\n    2184 for IN ADP\n    2185 American JJ ADJ\n    2186 companies NNS NOUN\n    2187 and CC CCONJ\n    2188 our PRP$ PRON\n    2189 workers NNS NOUN\n    2190 \u2014 : PUNCT\n    2191 have VBP VERB\n    2192 to TO PART\n    2193 do VB VERB\n    2194 it PRP PRON\n    2195 . . PUNCT\n    2196 Currently RB ADV\n    2197 , , PUNCT\n    2198 when WRB ADV\n    2199 we PRP PRON\n    2200 ship VBP VERB\n    2201 products NNS NOUN\n    2202 out IN SCONJ\n    2203 of IN ADP\n    2204 America NNP PROPN\n    2205 , , PUNCT\n    2206 many JJ ADJ\n    2207 other JJ ADJ\n    2208 countries NNS NOUN\n    2209 make VBP VERB\n    2210 us PRP PRON\n    2211 pay VB VERB\n    2212 very RB ADV\n    2213 high JJ ADJ\n    2214 tariffs NNS NOUN\n    2215 and CC CCONJ\n    2216 taxes NNS NOUN\n    2217 . . PUNCT\n    2218 But CC CCONJ\n    2219 when WRB ADV\n    2220 foreign JJ ADJ\n    2221 companies NNS NOUN\n    2222 ship VBP VERB\n    2223 their PRP$ PRON\n    2224 products NNS NOUN\n    2225 into IN ADP\n    2226 America NNP PROPN\n    2227 , , PUNCT\n    2228 we PRP PRON\n    2229 charge VBP VERB\n    2230 them PRP PRON\n    2231 nothing NN PRON\n    2232 , , PUNCT\n    2233 or CC CCONJ\n    2234 almost RB ADV\n    2235 nothing NN PRON\n    2236 . . PUNCT\n    2237 \n    \n     _SP SPACE\n    2238 I PRP PRON\n    2239 just RB ADV\n    2240 met VBD VERB\n    2241 with IN ADP\n    2242 officials NNS NOUN\n    2243 and CC CCONJ\n    2244 workers NNS NOUN\n    2245 from IN ADP\n    2246 a DT DET\n    2247 great JJ ADJ\n    2248 American JJ ADJ\n    2249 company NN NOUN\n    2250 , , PUNCT\n    2251 Harley NNP PROPN\n    2252 - HYPH PUNCT\n    2253 Davidson NNP PROPN\n    2254 . . PUNCT\n    2255 In IN ADP\n    2256 fact NN NOUN\n    2257 , , PUNCT\n    2258 they PRP PRON\n    2259 proudly RB ADV\n    2260 displayed VBD VERB\n    2261 five CD NUM\n    2262 of IN ADP\n    2263 their PRP$ PRON\n    2264 magnificent JJ ADJ\n    2265 motorcycles NNS NOUN\n    2266 , , PUNCT\n    2267 made VBN VERB\n    2268 in IN ADP\n    2269 the DT DET\n    2270 U.S.A. NNP PROPN\n    2271 , , PUNCT\n    2272 on IN ADP\n    2273 the DT DET\n    2274 front JJ ADJ\n    2275 lawn NN NOUN\n    2276 of IN ADP\n    2277 the DT DET\n    2278 White NNP PROPN\n    2279 House NNP PROPN\n    2280 . . PUNCT\n    2281 [ XX X\n    2282 Laughter XX X\n    2283 ] XX X\n    2284 And CC CCONJ\n    2285 they PRP PRON\n    2286 wanted VBD VERB\n    2287 me PRP PRON\n    2288 to TO PART\n    2289 ride VB VERB\n    2290 one CD NUM\n    2291 , , PUNCT\n    2292 and CC CCONJ\n    2293 I PRP PRON\n    2294 said VBD VERB\n    2295 , , PUNCT\n    2296 \" `` PUNCT\n    2297 No UH INTJ\n    2298 , , PUNCT\n    2299 thank VBP VERB\n    2300 you PRP PRON\n    2301 . . PUNCT\n    2302 \" '' PUNCT\n    2303 [ XX X\n    2304 Laughter NN NOUN\n    2305 ] -RRB- PUNCT\n    2306 \n    \n     _SP SPACE\n    2307 At IN ADP\n    2308 our PRP$ PRON\n    2309 meeting NN NOUN\n    2310 , , PUNCT\n    2311 I PRP PRON\n    2312 asked VBD VERB\n    2313 them PRP PRON\n    2314 , , PUNCT\n    2315 how WRB ADV\n    2316 are VBP AUX\n    2317 you PRP PRON\n    2318 doing VBG VERB\n    2319 , , PUNCT\n    2320 how WRB ADV\n    2321 is VBZ VERB\n    2322 business NN NOUN\n    2323 ? . PUNCT\n    2324 They PRP PRON\n    2325 said VBD VERB\n    2326 that IN SCONJ\n    2327 it PRP PRON\n    2328 's VBZ AUX\n    2329 good JJ ADJ\n    2330 . . PUNCT\n    2331 I PRP PRON\n    2332 asked VBD VERB\n    2333 them PRP PRON\n    2334 further RBR ADV\n    2335 , , PUNCT\n    2336 how WRB ADV\n    2337 are VBP AUX\n    2338 you PRP PRON\n    2339 doing VBG VERB\n    2340 with IN ADP\n    2341 other JJ ADJ\n    2342 countries NNS NOUN\n    2343 , , PUNCT\n    2344 mainly RB ADV\n    2345 international JJ ADJ\n    2346 sales NNS NOUN\n    2347 ? . PUNCT\n    2348 They PRP PRON\n    2349 told VBD VERB\n    2350 me PRP PRON\n    2351 \u2014 : PUNCT\n    2352 without IN ADP\n    2353 even RB ADV\n    2354 complaining VBG VERB\n    2355 , , PUNCT\n    2356 because IN SCONJ\n    2357 they PRP PRON\n    2358 have VBP AUX\n    2359 been VBN AUX\n    2360 so RB ADV\n    2361 mistreated VBN VERB\n    2362 for IN ADP\n    2363 so RB ADV\n    2364 long JJ ADJ\n    2365 that IN SCONJ\n    2366 they PRP PRON\n    2367 've VBP AUX\n    2368 become VBN VERB\n    2369 used JJ ADJ\n    2370 to IN ADP\n    2371 it PRP PRON\n    2372 \u2014 : PUNCT\n    2373 that IN SCONJ\n    2374 it PRP PRON\n    2375 's VBZ AUX\n    2376 very RB ADV\n    2377 hard JJ ADJ\n    2378 to TO PART\n    2379 do VB VERB\n    2380 business NN NOUN\n    2381 with IN ADP\n    2382 other JJ ADJ\n    2383 countries NNS NOUN\n    2384 because IN SCONJ\n    2385 they PRP PRON\n    2386 tax VBP VERB\n    2387 our PRP$ PRON\n    2388 goods NNS NOUN\n    2389 at IN ADP\n    2390 such PDT DET\n    2391 a DT DET\n    2392 high JJ ADJ\n    2393 rate NN NOUN\n    2394 . . PUNCT\n    2395 They PRP PRON\n    2396 said VBD VERB\n    2397 that IN SCONJ\n    2398 in IN ADP\n    2399 the DT DET\n    2400 case NN NOUN\n    2401 of IN ADP\n    2402 another DT DET\n    2403 country NN NOUN\n    2404 , , PUNCT\n    2405 they PRP PRON\n    2406 taxed VBD VERB\n    2407 their PRP$ PRON\n    2408 motorcycles NNS NOUN\n    2409 at IN ADP\n    2410 100 CD NUM\n    2411 percent NN NOUN\n    2412 . . PUNCT\n    2413 They PRP PRON\n    2414 were VBD AUX\n    2415 n't RB PART\n    2416 even RB ADV\n    2417 asking VBG VERB\n    2418 for IN ADP\n    2419 a DT DET\n    2420 change NN NOUN\n    2421 . . PUNCT\n    2422 But CC CCONJ\n    2423 I PRP PRON\n    2424 am VBP AUX\n    2425 . . PUNCT\n    2426 \n    \n     _SP SPACE\n    2427 I PRP PRON\n    2428 believe VBP VERB\n    2429 strongly RB ADV\n    2430 in IN ADP\n    2431 free JJ ADJ\n    2432 trade NN NOUN\n    2433 , , PUNCT\n    2434 but CC CCONJ\n    2435 it PRP PRON\n    2436 also RB ADV\n    2437 has VBZ VERB\n    2438 to TO PART\n    2439 be VB VERB\n    2440 fair JJ ADJ\n    2441 trade NN NOUN\n    2442 . . PUNCT\n    2443 It PRP PRON\n    2444 's VBZ AUX\n    2445 been VBN VERB\n    2446 a DT DET\n    2447 long JJ ADJ\n    2448 time NN NOUN\n    2449 since IN SCONJ\n    2450 we PRP PRON\n    2451 had VBD VERB\n    2452 fair JJ ADJ\n    2453 trade NN NOUN\n    2454 . . PUNCT\n    2455 The DT DET\n    2456 first JJ ADJ\n    2457 Republican JJ ADJ\n    2458 President NNP PROPN\n    2459 , , PUNCT\n    2460 Abraham NNP PROPN\n    2461 Lincoln NNP PROPN\n    2462 , , PUNCT\n    2463 warned VBD VERB\n    2464 that IN SCONJ\n    2465 the DT DET\n    2466 \" `` PUNCT\n    2467 abandonment NN NOUN\n    2468 of IN ADP\n    2469 the DT DET\n    2470 protective JJ ADJ\n    2471 policy NN NOUN\n    2472 by IN ADP\n    2473 the DT DET\n    2474 American NNP PROPN\n    2475 Government NNP PROPN\n    2476 will MD AUX\n    2477 produce VB VERB\n    2478 want VB VERB\n    2479 and CC CCONJ\n    2480 ruin VB VERB\n    2481 among IN ADP\n    2482 our PRP$ PRON\n    2483 people NNS NOUN\n    2484 . . PUNCT\n    2485 \" '' PUNCT\n    2486 Lincoln NNP PROPN\n    2487 was VBD AUX\n    2488 right JJ ADJ\n    2489 , , PUNCT\n    2490 and CC CCONJ\n    2491 it PRP PRON\n    2492 's VBZ VERB\n    2493 time NN NOUN\n    2494 we PRP PRON\n    2495 heeded VBD VERB\n    2496 his PRP$ PRON\n    2497 advice NN NOUN\n    2498 and CC CCONJ\n    2499 his PRP$ PRON\n    2500 words NNS NOUN\n    2501 . . PUNCT\n    2502 I PRP PRON\n    2503 am VBP AUX\n    2504 not RB PART\n    2505 going VBG VERB\n    2506 to TO PART\n    2507 let VB VERB\n    2508 America NNP PROPN\n    2509 and CC CCONJ\n    2510 its PRP$ PRON\n    2511 great JJ ADJ\n    2512 companies NNS NOUN\n    2513 and CC CCONJ\n    2514 workers NNS NOUN\n    2515 be VB AUX\n    2516 taken VBN VERB\n    2517 advantage NN NOUN\n    2518 of IN ADP\n    2519 us PRP PRON\n    2520 any RB ADV\n    2521 longer RBR ADV\n    2522 . . PUNCT\n    2523 They PRP PRON\n    2524 have VBP AUX\n    2525 taken VBN VERB\n    2526 advantage NN NOUN\n    2527 of IN ADP\n    2528 our PRP$ PRON\n    2529 country NN NOUN\n    2530 . . PUNCT\n    2531 No RB ADV\n    2532 longer RBR ADV\n    2533 . . PUNCT\n    2534 \n    \n     _SP SPACE\n    2535 I PRP PRON\n    2536 am VBP AUX\n    2537 going VBG VERB\n    2538 to TO PART\n    2539 bring VB VERB\n    2540 back RB ADV\n    2541 millions NNS NOUN\n    2542 of IN ADP\n    2543 jobs NNS NOUN\n    2544 . . PUNCT\n    2545 Protecting VBG VERB\n    2546 our PRP$ PRON\n    2547 workers NNS NOUN\n    2548 also RB ADV\n    2549 means VBZ VERB\n    2550 reforming VBG VERB\n    2551 our PRP$ PRON\n    2552 system NN NOUN\n    2553 of IN ADP\n    2554 legal JJ ADJ\n    2555 immigration NN NOUN\n    2556 . . PUNCT\n    2557 The DT DET\n    2558 current JJ ADJ\n    2559 , , PUNCT\n    2560 outdated JJ ADJ\n    2561 system NN NOUN\n    2562 depresses VBZ VERB\n    2563 wages NNS NOUN\n    2564 for IN ADP\n    2565 our PRP$ PRON\n    2566 poorest JJS ADJ\n    2567 workers NNS NOUN\n    2568 and CC CCONJ\n    2569 puts VBZ VERB\n    2570 great JJ ADJ\n    2571 pressure NN NOUN\n    2572 on IN ADP\n    2573 taxpayers NNS NOUN\n    2574 . . PUNCT\n    2575 Nations NNS NOUN\n    2576 around IN ADP\n    2577 the DT DET\n    2578 world NN NOUN\n    2579 like IN ADP\n    2580 Canada NNP PROPN\n    2581 , , PUNCT\n    2582 Australia NNP PROPN\n    2583 , , PUNCT\n    2584 and CC CCONJ\n    2585 many JJ ADJ\n    2586 others NNS NOUN\n    2587 , , PUNCT\n    2588 have VBP VERB\n    2589 a DT DET\n    2590 merit NN NOUN\n    2591 - HYPH PUNCT\n    2592 based VBN VERB\n    2593 immigration NN NOUN\n    2594 system NN NOUN\n    2595 . . PUNCT\n    2596 It PRP PRON\n    2597 's VBZ AUX\n    2598 a DT DET\n    2599 basic JJ ADJ\n    2600 principle NN NOUN\n    2601 that IN SCONJ\n    2602 those DT DET\n    2603 seeking VBG VERB\n    2604 to TO PART\n    2605 enter VB VERB\n    2606 a DT DET\n    2607 country NN NOUN\n    2608 ought MD AUX\n    2609 to TO PART\n    2610 be VB VERB\n    2611 able JJ ADJ\n    2612 to TO PART\n    2613 support VB VERB\n    2614 themselves PRP PRON\n    2615 financially RB ADV\n    2616 . . PUNCT\n    2617 Yet CC CCONJ\n    2618 , , PUNCT\n    2619 in IN ADP\n    2620 America NNP PROPN\n    2621 , , PUNCT\n    2622 we PRP PRON\n    2623 do VBP AUX\n    2624 not RB PART\n    2625 enforce VB VERB\n    2626 this DT DET\n    2627 rule NN NOUN\n    2628 , , PUNCT\n    2629 straining VBG VERB\n    2630 the DT DET\n    2631 very RB ADV\n    2632 public JJ ADJ\n    2633 resources NNS NOUN\n    2634 that WDT DET\n    2635 our PRP$ PRON\n    2636 poorest JJS ADJ\n    2637 citizens NNS NOUN\n    2638 rely VBP VERB\n    2639 upon IN SCONJ\n    2640 . . PUNCT\n    2641 According VBG VERB\n    2642 to IN ADP\n    2643 the DT DET\n    2644 National NNP PROPN\n    2645 Academy NNP PROPN\n    2646 of IN ADP\n    2647 Sciences NNPS PROPN\n    2648 , , PUNCT\n    2649 our PRP$ PRON\n    2650 current JJ ADJ\n    2651 immigration NN NOUN\n    2652 system NN NOUN\n    2653 costs VBZ VERB\n    2654 American JJ ADJ\n    2655 taxpayers NNS NOUN\n    2656 many JJ ADJ\n    2657 billions NNS NOUN\n    2658 of IN ADP\n    2659 dollars NNS NOUN\n    2660 a DT DET\n    2661 year NN NOUN\n    2662 . . PUNCT\n    2663 \n    \n     _SP SPACE\n    2664 Switching VBG VERB\n    2665 away RB ADV\n    2666 from IN ADP\n    2667 this DT DET\n    2668 current JJ ADJ\n    2669 system NN NOUN\n    2670 of IN ADP\n    2671 lower JJR ADJ\n    2672 skilled JJ ADJ\n    2673 immigration NN NOUN\n    2674 , , PUNCT\n    2675 and CC CCONJ\n    2676 instead RB ADV\n    2677 adopting VBG VERB\n    2678 a DT DET\n    2679 merit NN NOUN\n    2680 - HYPH PUNCT\n    2681 based VBN VERB\n    2682 system NN NOUN\n    2683 , , PUNCT\n    2684 we PRP PRON\n    2685 will MD AUX\n    2686 have VB VERB\n    2687 so RB ADV\n    2688 many JJ ADJ\n    2689 more JJR ADJ\n    2690 benefits NNS NOUN\n    2691 . . PUNCT\n    2692 It PRP PRON\n    2693 will MD AUX\n    2694 save VB VERB\n    2695 countless JJ ADJ\n    2696 dollars NNS NOUN\n    2697 , , PUNCT\n    2698 raise VB VERB\n    2699 workers NNS NOUN\n    2700 ' POS PART\n    2701 wages NNS NOUN\n    2702 , , PUNCT\n    2703 and CC CCONJ\n    2704 help VB VERB\n    2705 struggling VBG VERB\n    2706 families NNS NOUN\n    2707 \u2014 : PUNCT\n    2708 including VBG VERB\n    2709 immigrant JJ ADJ\n    2710 families NNS NOUN\n    2711 \u2014 : PUNCT\n    2712 enter VB VERB\n    2713 the DT DET\n    2714 middle JJ ADJ\n    2715 class NN NOUN\n    2716 . . PUNCT\n    2717 And CC CCONJ\n    2718 they PRP PRON\n    2719 will MD AUX\n    2720 do VB VERB\n    2721 it PRP PRON\n    2722 quickly RB ADV\n    2723 , , PUNCT\n    2724 and CC CCONJ\n    2725 they PRP PRON\n    2726 will MD AUX\n    2727 be VB VERB\n    2728 very RB ADV\n    2729 , , PUNCT\n    2730 very RB ADV\n    2731 happy JJ ADJ\n    2732 , , PUNCT\n    2733 indeed RB ADV\n    2734 . . PUNCT\n    2735 \n    \n     _SP SPACE\n    2736 I PRP PRON\n    2737 believe VBP VERB\n    2738 that IN SCONJ\n    2739 real JJ ADJ\n    2740 and CC CCONJ\n    2741 positive JJ ADJ\n    2742 immigration NN NOUN\n    2743 reform NN NOUN\n    2744 is VBZ AUX\n    2745 possible JJ ADJ\n    2746 , , PUNCT\n    2747 as RB ADV\n    2748 long RB ADV\n    2749 as IN ADP\n    2750 we PRP PRON\n    2751 focus VBP VERB\n    2752 on IN ADP\n    2753 the DT DET\n    2754 following VBG VERB\n    2755 goals NNS NOUN\n    2756 : : PUNCT\n    2757 to TO PART\n    2758 improve VB VERB\n    2759 jobs NNS NOUN\n    2760 and CC CCONJ\n    2761 wages NNS NOUN\n    2762 for IN ADP\n    2763 Americans NNPS PROPN\n    2764 , , PUNCT\n    2765 to TO PART\n    2766 strengthen VB VERB\n    2767 our PRP$ PRON\n    2768 Nation NN NOUN\n    2769 's POS PART\n    2770 security NN NOUN\n    2771 , , PUNCT\n    2772 and CC CCONJ\n    2773 to TO PART\n    2774 restore VB VERB\n    2775 respect NN NOUN\n    2776 for IN ADP\n    2777 our PRP$ PRON\n    2778 laws NNS NOUN\n    2779 . . PUNCT\n    2780 If IN SCONJ\n    2781 we PRP PRON\n    2782 are VBP AUX\n    2783 guided VBN VERB\n    2784 by IN ADP\n    2785 the DT DET\n    2786 wellbeing NN NOUN\n    2787 of IN ADP\n    2788 American JJ ADJ\n    2789 citizens NNS NOUN\n    2790 , , PUNCT\n    2791 then RB ADV\n    2792 I PRP PRON\n    2793 believe VBP VERB\n    2794 Republicans NNPS PROPN\n    2795 and CC CCONJ\n    2796 Democrats NNPS PROPN\n    2797 can MD AUX\n    2798 work VB VERB\n    2799 together RB ADV\n    2800 to TO PART\n    2801 achieve VB VERB\n    2802 an DT DET\n    2803 outcome NN NOUN\n    2804 that WDT DET\n    2805 has VBZ AUX\n    2806 eluded VBN VERB\n    2807 our PRP$ PRON\n    2808 country NN NOUN\n    2809 for IN ADP\n    2810 decades NNS NOUN\n    2811 . . PUNCT\n    2812 \n    \n     _SP SPACE\n    2813 Another DT DET\n    2814 Republican JJ ADJ\n    2815 President NNP PROPN\n    2816 , , PUNCT\n    2817 Dwight NNP PROPN\n    2818 D. NNP PROPN\n    2819 Eisenhower NNP PROPN\n    2820 , , PUNCT\n    2821 initiated VBD VERB\n    2822 the DT DET\n    2823 last JJ ADJ\n    2824 truly RB ADV\n    2825 great JJ ADJ\n    2826 national JJ ADJ\n    2827 infrastructure NN NOUN\n    2828 program NN NOUN\n    2829 \u2014 : PUNCT\n    2830 the DT DET\n    2831 building NN NOUN\n    2832 of IN ADP\n    2833 the DT DET\n    2834 Interstate NNP PROPN\n    2835 Highway NNP PROPN\n    2836 System NNP PROPN\n    2837 . . PUNCT\n    2838 The DT DET\n    2839 time NN NOUN\n    2840 has VBZ AUX\n    2841 come VBN VERB\n    2842 for IN ADP\n    2843 a DT DET\n    2844 new JJ ADJ\n    2845 program NN NOUN\n    2846 of IN ADP\n    2847 national JJ ADJ\n    2848 rebuilding NN NOUN\n    2849 . . PUNCT\n    2850 America NNP PROPN\n    2851 has VBZ AUX\n    2852 spent VBN VERB\n    2853 approximately RB ADV\n    2854 $ $ SYM\n    2855 6 CD NUM\n    2856 trillion CD NUM\n    2857 in IN ADP\n    2858 the DT DET\n    2859 Middle NNP PROPN\n    2860 East NNP PROPN\n    2861 ; : PUNCT\n    2862 all PDT DET\n    2863 the DT DET\n    2864 while NN NOUN\n    2865 , , PUNCT\n    2866 our PRP$ PRON\n    2867 infrastructure NN NOUN\n    2868 at IN ADP\n    2869 home NN NOUN\n    2870 is VBZ AUX\n    2871 crumbling VBG VERB\n    2872 . . PUNCT\n    2873 With IN ADP\n    2874 this DT DET\n    2875 $ $ SYM\n    2876 6 CD NUM\n    2877 trillion CD NUM\n    2878 , , PUNCT\n    2879 we PRP PRON\n    2880 could MD AUX\n    2881 have VB AUX\n    2882 rebuilt VBN VERB\n    2883 our PRP$ PRON\n    2884 country NN NOUN\n    2885 twice RB ADV\n    2886 , , PUNCT\n    2887 and CC CCONJ\n    2888 maybe RB ADV\n    2889 even RB ADV\n    2890 three CD NUM\n    2891 times NNS NOUN\n    2892 if IN SCONJ\n    2893 we PRP PRON\n    2894 had VBD VERB\n    2895 people NNS NOUN\n    2896 who WP PRON\n    2897 had VBD VERB\n    2898 the DT DET\n    2899 ability NN NOUN\n    2900 to TO PART\n    2901 negotiate VB VERB\n    2902 . . PUNCT\n    2903 [ XX X\n    2904 Laughter XX X\n    2905 ] -RRB- PUNCT\n    2906 \n    \n     _SP SPACE\n    2907 To TO PART\n    2908 launch VB VERB\n    2909 our PRP$ PRON\n    2910 national JJ ADJ\n    2911 rebuilding NN NOUN\n    2912 , , PUNCT\n    2913 I PRP PRON\n    2914 will MD AUX\n    2915 be VB AUX\n    2916 asking VBG VERB\n    2917 Congress NNP PROPN\n    2918 to TO PART\n    2919 approve VB VERB\n    2920 legislation NN NOUN\n    2921 that WDT DET\n    2922 produces VBZ VERB\n    2923 a DT DET\n    2924 $ $ SYM\n    2925 1 CD NUM\n    2926 trillion CD NUM\n    2927 investment NN NOUN\n    2928 in IN ADP\n    2929 infrastructure NN NOUN\n    2930 of IN ADP\n    2931 the DT DET\n    2932 United NNP PROPN\n    2933 States NNP PROPN\n    2934 \u2014 : PUNCT\n    2935 financed VBN VERB\n    2936 through IN ADP\n    2937 both CC CCONJ\n    2938 public JJ ADJ\n    2939 and CC CCONJ\n    2940 private JJ ADJ\n    2941 capital NN NOUN\n    2942 \u2014 : PUNCT\n    2943 creating VBG VERB\n    2944 millions NNS NOUN\n    2945 of IN ADP\n    2946 new JJ ADJ\n    2947 jobs NNS NOUN\n    2948 . . PUNCT\n    2949 This DT DET\n    2950 effort NN NOUN\n    2951 will MD AUX\n    2952 be VB AUX\n    2953 guided VBN VERB\n    2954 by IN ADP\n    2955 two CD NUM\n    2956 core NN NOUN\n    2957 principles NNS NOUN\n    2958 : : PUNCT\n    2959 buy VB VERB\n    2960 American JJ ADJ\n    2961 and CC CCONJ\n    2962 hire VB VERB\n    2963 American JJ ADJ\n    2964 . . PUNCT\n    2965 \n    \n     _SP SPACE\n    2966 Tonight NN NOUN\n    2967 I PRP PRON\n    2968 am VBP AUX\n    2969 also RB ADV\n    2970 calling VBG VERB\n    2971 on IN ADP\n    2972 this DT DET\n    2973 Congress NNP PROPN\n    2974 to TO PART\n    2975 repeal VB VERB\n    2976 and CC CCONJ\n    2977 replace VB VERB\n    2978 Obamacare NNP PROPN\n    2979 with IN ADP\n    2980 reforms NNS NOUN\n    2981 that WDT DET\n    2982 expand VBP VERB\n    2983 choice NN NOUN\n    2984 , , PUNCT\n    2985 increase VB VERB\n    2986 access NN NOUN\n    2987 , , PUNCT\n    2988 lower JJR ADJ\n    2989 costs NNS NOUN\n    2990 , , PUNCT\n    2991 and CC CCONJ\n    2992 at IN ADP\n    2993 the DT DET\n    2994 same JJ ADJ\n    2995 time NN NOUN\n    2996 , , PUNCT\n    2997 provide VB VERB\n    2998 better JJR ADJ\n    2999 health NN NOUN\n    3000 care NN NOUN\n    3001 . . PUNCT\n    3002 \n    \n     _SP SPACE\n    3003 Mandating VBG VERB\n    3004 every DT DET\n    3005 American NNP PROPN\n    3006 to TO PART\n    3007 buy VB VERB\n    3008 Government NN NOUN\n    3009 - HYPH PUNCT\n    3010 approved VBN VERB\n    3011 health NN NOUN\n    3012 insurance NN NOUN\n    3013 was VBD AUX\n    3014 never RB ADV\n    3015 the DT DET\n    3016 right JJ ADJ\n    3017 solution NN NOUN\n    3018 for IN ADP\n    3019 our PRP$ PRON\n    3020 country NN NOUN\n    3021 . . PUNCT\n    3022 The DT DET\n    3023 way NN NOUN\n    3024 to TO PART\n    3025 make VB VERB\n    3026 health NN NOUN\n    3027 insurance NN NOUN\n    3028 available JJ ADJ\n    3029 to IN ADP\n    3030 everyone NN PRON\n    3031 is VBZ AUX\n    3032 to TO PART\n    3033 lower VB VERB\n    3034 the DT DET\n    3035 cost NN NOUN\n    3036 of IN ADP\n    3037 health NN NOUN\n    3038 insurance NN NOUN\n    3039 , , PUNCT\n    3040 and CC CCONJ\n    3041 that DT DET\n    3042 is VBZ VERB\n    3043 what WP PRON\n    3044 we PRP PRON\n    3045 are VBP AUX\n    3046 going VBG VERB\n    3047 do VB VERB\n    3048 . . PUNCT\n    3049 \n    \n     _SP SPACE\n    3050 Obamacare VBP VERB\n    3051 premiums NNS NOUN\n    3052 nationwide RB ADV\n    3053 have VBP AUX\n    3054 increased VBN VERB\n    3055 by IN ADP\n    3056 double JJ ADJ\n    3057 and CC CCONJ\n    3058 triple JJ ADJ\n    3059 digits NNS NOUN\n    3060 . . PUNCT\n    3061 As IN ADP\n    3062 an DT DET\n    3063 example NN NOUN\n    3064 , , PUNCT\n    3065 Arizona NNP PROPN\n    3066 went VBD VERB\n    3067 up RB ADV\n    3068 116 CD NUM\n    3069 percent NN NOUN\n    3070 last JJ ADJ\n    3071 year NN NOUN\n    3072 alone RB ADV\n    3073 . . PUNCT\n    3074 Governor NNP PROPN\n    3075 Matt NNP PROPN\n    3076 Bevin NNP PROPN\n    3077 of IN ADP\n    3078 Kentucky NNP PROPN\n    3079 just RB ADV\n    3080 said VBD VERB\n    3081 Obamacare NNP PROPN\n    3082 is VBZ AUX\n    3083 failing VBG VERB\n    3084 in IN ADP\n    3085 his PRP$ PRON\n    3086 State NNP PROPN\n    3087 \u2014 : PUNCT\n    3088 the DT DET\n    3089 State NNP PROPN\n    3090 of IN ADP\n    3091 Kentucky NNP PROPN\n    3092 \u2014 : PUNCT\n    3093 and CC CCONJ\n    3094 it PRP PRON\n    3095 's VBZ VERB\n    3096 unsustainable JJ ADJ\n    3097 and CC CCONJ\n    3098 collapsing VBG VERB\n    3099 . . PUNCT\n    3100 \n    \n     _SP SPACE\n    3101 One CD NUM\n    3102 - HYPH PUNCT\n    3103 third NN NOUN\n    3104 of IN ADP\n    3105 the DT DET\n    3106 counties NNS NOUN\n    3107 have VBP VERB\n    3108 only RB ADV\n    3109 one CD NUM\n    3110 insurer NN NOUN\n    3111 , , PUNCT\n    3112 and CC CCONJ\n    3113 they PRP PRON\n    3114 are VBP AUX\n    3115 losing VBG VERB\n    3116 them PRP PRON\n    3117 fast RB ADV\n    3118 . . PUNCT\n    3119 They PRP PRON\n    3120 are VBP AUX\n    3121 losing VBG VERB\n    3122 them PRP PRON\n    3123 so RB ADV\n    3124 fast RB ADV\n    3125 . . PUNCT\n    3126 They PRP PRON\n    3127 are VBP AUX\n    3128 leaving VBG VERB\n    3129 , , PUNCT\n    3130 and CC CCONJ\n    3131 many JJ ADJ\n    3132 Americans NNPS PROPN\n    3133 have VBP VERB\n    3134 no DT DET\n    3135 choice NN NOUN\n    3136 at RB ADV\n    3137 all RB ADV\n    3138 . . PUNCT\n    3139 There EX PRON\n    3140 's VBZ AUX\n    3141 no DT DET\n    3142 choice NN NOUN\n    3143 left VBN VERB\n    3144 . . PUNCT\n    3145 Remember VB VERB\n    3146 when WRB ADV\n    3147 you PRP PRON\n    3148 were VBD AUX\n    3149 told VBN VERB\n    3150 that IN SCONJ\n    3151 you PRP PRON\n    3152 could MD AUX\n    3153 keep VB VERB\n    3154 your PRP$ PRON\n    3155 doctor NN NOUN\n    3156 and CC CCONJ\n    3157 keep VB VERB\n    3158 your PRP$ PRON\n    3159 plan NN NOUN\n    3160 ? . PUNCT\n    3161 We PRP PRON\n    3162 now RB ADV\n    3163 know VBP VERB\n    3164 that IN SCONJ\n    3165 all DT DET\n    3166 of IN ADP\n    3167 those DT DET\n    3168 promises NNS NOUN\n    3169 have VBP AUX\n    3170 been VBN AUX\n    3171 totally RB ADV\n    3172 broken VBN VERB\n    3173 . . PUNCT\n    3174 Obamacare NNP PROPN\n    3175 is VBZ AUX\n    3176 collapsing VBG VERB\n    3177 , , PUNCT\n    3178 and CC CCONJ\n    3179 we PRP PRON\n    3180 must MD AUX\n    3181 act VB VERB\n    3182 decisively RB ADV\n    3183 to TO PART\n    3184 protect VB VERB\n    3185 all DT DET\n    3186 Americans NNPS PROPN\n    3187 . . PUNCT\n    3188 \n    \n     _SP SPACE\n    3189 Action NNP PROPN\n    3190 is VBZ AUX\n    3191 not RB PART\n    3192 a DT DET\n    3193 choice NN NOUN\n    3194 , , PUNCT\n    3195 it PRP PRON\n    3196 is VBZ AUX\n    3197 a DT DET\n    3198 necessity NN NOUN\n    3199 . . PUNCT\n    3200 So RB ADV\n    3201 I PRP PRON\n    3202 am VBP AUX\n    3203 calling VBG VERB\n    3204 on IN ADP\n    3205 all DT DET\n    3206 Democrats NNPS PROPN\n    3207 and CC CCONJ\n    3208 Republicans NNPS PROPN\n    3209 in IN ADP\n    3210 Congress NNP PROPN\n    3211 to TO PART\n    3212 work VB VERB\n    3213 with IN ADP\n    3214 us PRP PRON\n    3215 to TO PART\n    3216 save VB VERB\n    3217 Americans NNPS PROPN\n    3218 from IN ADP\n    3219 this DT DET\n    3220 imploding VBG VERB\n    3221 Obamacare NNP PROPN\n    3222 disaster NN NOUN\n    3223 . . PUNCT\n    3224 \n    \n     _SP SPACE\n    3225 Here RB ADV\n    3226 are VBP AUX\n    3227 the DT DET\n    3228 principles NNS NOUN\n    3229 that WDT DET\n    3230 should MD AUX\n    3231 guide VB VERB\n    3232 the DT DET\n    3233 Congress NNP PROPN\n    3234 as IN ADP\n    3235 we PRP PRON\n    3236 move VBP VERB\n    3237 to TO PART\n    3238 create VB VERB\n    3239 a DT DET\n    3240 better JJR ADJ\n    3241 health NN NOUN\n    3242 care NN NOUN\n    3243 system NN NOUN\n    3244 for IN ADP\n    3245 all DT DET\n    3246 Americans NNPS PROPN\n    3247 : : PUNCT\n    3248 \n    \n     _SP SPACE\n    3249 First RB ADV\n    3250 , , PUNCT\n    3251 we PRP PRON\n    3252 should MD AUX\n    3253 ensure VB VERB\n    3254 that IN SCONJ\n    3255 Americans NNPS PROPN\n    3256 with IN ADP\n    3257 preexisting JJ ADJ\n    3258 conditions NNS NOUN\n    3259 have VBP VERB\n    3260 access NN NOUN\n    3261 to IN ADP\n    3262 coverage NN NOUN\n    3263 , , PUNCT\n    3264 and CC CCONJ\n    3265 that IN SCONJ\n    3266 we PRP PRON\n    3267 have VBP VERB\n    3268 a DT DET\n    3269 stable JJ ADJ\n    3270 transition NN NOUN\n    3271 for IN ADP\n    3272 Americans NNPS PROPN\n    3273 currently RB ADV\n    3274 enrolled VBD VERB\n    3275 in IN ADP\n    3276 the DT DET\n    3277 health NN NOUN\n    3278 care NN NOUN\n    3279 exchanges NNS NOUN\n    3280 . . PUNCT\n    3281 \n    \n     _SP SPACE\n    3282 Secondly RB ADV\n    3283 , , PUNCT\n    3284 we PRP PRON\n    3285 should MD AUX\n    3286 help VB VERB\n    3287 Americans NNPS PROPN\n    3288 purchase VB VERB\n    3289 their PRP$ PRON\n    3290 own JJ ADJ\n    3291 coverage NN NOUN\n    3292 through IN ADP\n    3293 the DT DET\n    3294 use NN NOUN\n    3295 of IN ADP\n    3296 tax NN NOUN\n    3297 credits NNS NOUN\n    3298 and CC CCONJ\n    3299 expanded VBN VERB\n    3300 health NN NOUN\n    3301 savings NNS NOUN\n    3302 accounts NNS NOUN\n    3303 , , PUNCT\n    3304 but CC CCONJ\n    3305 it PRP PRON\n    3306 must MD AUX\n    3307 be VB VERB\n    3308 the DT DET\n    3309 plan NN NOUN\n    3310 they PRP PRON\n    3311 want VBP VERB\n    3312 , , PUNCT\n    3313 not RB PART\n    3314 the DT DET\n    3315 plan NN NOUN\n    3316 forced VBN VERB\n    3317 on IN ADP\n    3318 them PRP PRON\n    3319 by IN ADP\n    3320 our PRP$ PRON\n    3321 Government NNP PROPN\n    3322 . . PUNCT\n    3323 \n    \n     _SP SPACE\n    3324 Thirdly RB ADV\n    3325 , , PUNCT\n    3326 we PRP PRON\n    3327 should MD AUX\n    3328 give VB VERB\n    3329 our PRP$ PRON\n    3330 State NNP PROPN\n    3331 Governors NNPS PROPN\n    3332 the DT DET\n    3333 resources NNS NOUN\n    3334 and CC CCONJ\n    3335 flexibility NN NOUN\n    3336 they PRP PRON\n    3337 need VBP VERB\n    3338 with IN ADP\n    3339 Medicaid NNP PROPN\n    3340 to TO PART\n    3341 make VB VERB\n    3342 sure JJ ADJ\n    3343 no DT DET\n    3344 one NN NOUN\n    3345 is VBZ AUX\n    3346 left VBN VERB\n    3347 out RP ADP\n    3348 . . PUNCT\n    3349 \n    \n     _SP SPACE\n    3350 Fourth JJ ADJ\n    3351 , , PUNCT\n    3352 we PRP PRON\n    3353 should MD AUX\n    3354 implement VB VERB\n    3355 legal JJ ADJ\n    3356 reforms NNS NOUN\n    3357 that WDT DET\n    3358 protect VBP VERB\n    3359 patients NNS NOUN\n    3360 and CC CCONJ\n    3361 doctors NNS NOUN\n    3362 from IN ADP\n    3363 unnecessary JJ ADJ\n    3364 costs NNS NOUN\n    3365 that WDT DET\n    3366 drive VBP VERB\n    3367 up RP ADP\n    3368 the DT DET\n    3369 price NN NOUN\n    3370 of IN ADP\n    3371 insurance NN NOUN\n    3372 and CC CCONJ\n    3373 work NN NOUN\n    3374 to TO PART\n    3375 bring VB VERB\n    3376 down RP ADP\n    3377 the DT DET\n    3378 artificially RB ADV\n    3379 high JJ ADJ\n    3380 price NN NOUN\n    3381 of IN ADP\n    3382 drugs NNS NOUN\n    3383 and CC CCONJ\n    3384 bring VB VERB\n    3385 them PRP PRON\n    3386 down RP ADP\n    3387 immediately RB ADV\n    3388 . . PUNCT\n    3389 And CC CCONJ\n    3390 finally RB ADV\n    3391 , , PUNCT\n    3392 the DT DET\n    3393 time NN NOUN\n    3394 has VBZ AUX\n    3395 come VBN VERB\n    3396 to TO PART\n    3397 give VB VERB\n    3398 Americans NNPS PROPN\n    3399 the DT DET\n    3400 freedom NN NOUN\n    3401 to TO PART\n    3402 purchase VB VERB\n    3403 health NN NOUN\n    3404 insurance NN NOUN\n    3405 across IN ADP\n    3406 State NNP PROPN\n    3407 lines NNS NOUN\n    3408 , , PUNCT\n    3409 which WDT DET\n    3410 will MD AUX\n    3411 create VB VERB\n    3412 a DT DET\n    3413 truly RB ADV\n    3414 competitive JJ ADJ\n    3415 national JJ ADJ\n    3416 marketplace NN NOUN\n    3417 that WDT DET\n    3418 will MD AUX\n    3419 bring VB VERB\n    3420 costs NNS NOUN\n    3421 way NN NOUN\n    3422 down RB ADV\n    3423 and CC CCONJ\n    3424 provide VB VERB\n    3425 far RB ADV\n    3426 better JJR ADJ\n    3427 care NN NOUN\n    3428 . . PUNCT\n    3429 So RB ADV\n    3430 important JJ ADJ\n    3431 . . PUNCT\n    3432 \n    \n     _SP SPACE\n    3433 Everything NN PRON\n    3434 that WDT DET\n    3435 is VBZ AUX\n    3436 broken VBN VERB\n    3437 in IN ADP\n    3438 our PRP$ PRON\n    3439 country NN NOUN\n    3440 can MD AUX\n    3441 be VB AUX\n    3442 fixed VBN VERB\n    3443 . . PUNCT\n    3444 Every DT DET\n    3445 problem NN NOUN\n    3446 can MD AUX\n    3447 be VB AUX\n    3448 solved VBN VERB\n    3449 . . PUNCT\n    3450 And CC CCONJ\n    3451 every DT DET\n    3452 hurting VBG VERB\n    3453 family NN NOUN\n    3454 can MD AUX\n    3455 find VB VERB\n    3456 healing NN NOUN\n    3457 and CC CCONJ\n    3458 hope NN NOUN\n    3459 . . PUNCT\n    3460 \n    \n     _SP SPACE\n    3461 Our PRP$ PRON\n    3462 citizens NNS NOUN\n    3463 deserve VBP VERB\n    3464 this DT DET\n    3465 and CC CCONJ\n    3466 so RB ADV\n    3467 much RB ADV\n    3468 more JJR ADJ\n    3469 , , PUNCT\n    3470 so CC CCONJ\n    3471 why WRB ADV\n    3472 not RB PART\n    3473 join VB VERB\n    3474 forces NNS NOUN\n    3475 and CC CCONJ\n    3476 finally RB ADV\n    3477 get VB VERB\n    3478 the DT DET\n    3479 job NN NOUN\n    3480 done VBN VERB\n    3481 , , PUNCT\n    3482 and CC CCONJ\n    3483 get VB VERB\n    3484 it PRP PRON\n    3485 done VBN VERB\n    3486 right RB ADV\n    3487 ? . PUNCT\n    3488 On IN ADP\n    3489 this DT DET\n    3490 and CC CCONJ\n    3491 so RB ADV\n    3492 many JJ ADJ\n    3493 other JJ ADJ\n    3494 things NNS NOUN\n    3495 , , PUNCT\n    3496 Democrats NNPS PROPN\n    3497 and CC CCONJ\n    3498 Republicans NNPS PROPN\n    3499 should MD AUX\n    3500 get VB VERB\n    3501 together RB ADV\n    3502 and CC CCONJ\n    3503 unite VB VERB\n    3504 for IN ADP\n    3505 the DT DET\n    3506 good NN NOUN\n    3507 of IN ADP\n    3508 our PRP$ PRON\n    3509 country NN NOUN\n    3510 and CC CCONJ\n    3511 for IN ADP\n    3512 the DT DET\n    3513 good NN NOUN\n    3514 of IN ADP\n    3515 the DT DET\n    3516 American JJ ADJ\n    3517 people NNS NOUN\n    3518 . . PUNCT\n    3519 \n    \n     _SP SPACE\n    3520 My PRP$ PRON\n    3521 administration NN NOUN\n    3522 wants VBZ VERB\n    3523 to TO PART\n    3524 work VB VERB\n    3525 with IN ADP\n    3526 members NNS NOUN\n    3527 of IN ADP\n    3528 both DT DET\n    3529 parties NNS NOUN\n    3530 to TO PART\n    3531 make VB VERB\n    3532 childcare NN NOUN\n    3533 accessible JJ ADJ\n    3534 and CC CCONJ\n    3535 affordable JJ ADJ\n    3536 ; : PUNCT\n    3537 to TO PART\n    3538 help VB VERB\n    3539 ensure VB VERB\n    3540 new JJ ADJ\n    3541 parents NNS NOUN\n    3542 that WDT DET\n    3543 they PRP PRON\n    3544 have VBP AUX\n    3545 paid VBN VERB\n    3546 family NN NOUN\n    3547 leave VB VERB\n    3548 ; : PUNCT\n    3549 to TO PART\n    3550 invest VB VERB\n    3551 in IN ADP\n    3552 women NNS NOUN\n    3553 's POS PART\n    3554 health NN NOUN\n    3555 ; : PUNCT\n    3556 and CC CCONJ\n    3557 to TO PART\n    3558 promote VB VERB\n    3559 clean JJ ADJ\n    3560 air NN NOUN\n    3561 and CC CCONJ\n    3562 clean JJ ADJ\n    3563 water NN NOUN\n    3564 ; : PUNCT\n    3565 and CC CCONJ\n    3566 to TO PART\n    3567 rebuild VB VERB\n    3568 our PRP$ PRON\n    3569 military NN NOUN\n    3570 and CC CCONJ\n    3571 our PRP$ PRON\n    3572 infrastructure NN NOUN\n    3573 . . PUNCT\n    3574 \n    \n     _SP SPACE\n    3575 True JJ ADJ\n    3576 love NN NOUN\n    3577 for IN ADP\n    3578 our PRP$ PRON\n    3579 people NNS NOUN\n    3580 requires VBZ VERB\n    3581 us PRP PRON\n    3582 to TO PART\n    3583 find VB VERB\n    3584 common JJ ADJ\n    3585 ground NN NOUN\n    3586 , , PUNCT\n    3587 to TO PART\n    3588 advance VB VERB\n    3589 the DT DET\n    3590 common JJ ADJ\n    3591 good NN NOUN\n    3592 , , PUNCT\n    3593 and CC CCONJ\n    3594 to TO PART\n    3595 cooperate VB VERB\n    3596 on IN ADP\n    3597 behalf NN NOUN\n    3598 of IN ADP\n    3599 every DT DET\n    3600 American JJ ADJ\n    3601 child NN NOUN\n    3602 who WP PRON\n    3603 deserves VBZ VERB\n    3604 a DT DET\n    3605 much RB ADV\n    3606 brighter JJR ADJ\n    3607 future NN NOUN\n    3608 . . PUNCT\n    3609 \n    \n     _SP SPACE\n    3610 An DT DET\n    3611 incredible JJ ADJ\n    3612 young JJ ADJ\n    3613 woman NN NOUN\n    3614 is VBZ AUX\n    3615 with IN ADP\n    3616 us PRP PRON\n    3617 this DT DET\n    3618 evening NN NOUN\n    3619 , , PUNCT\n    3620 who WP PRON\n    3621 should MD AUX\n    3622 serve VB VERB\n    3623 as IN ADP\n    3624 an DT DET\n    3625 inspiration NN NOUN\n    3626 to IN ADP\n    3627 us PRP PRON\n    3628 all DT DET\n    3629 . . PUNCT\n    3630 Today NN NOUN\n    3631 is VBZ AUX\n    3632 Rare NNP PROPN\n    3633 Disease NNP PROPN\n    3634 Day NNP PROPN\n    3635 , , PUNCT\n    3636 and CC CCONJ\n    3637 joining VBG VERB\n    3638 us PRP PRON\n    3639 in IN ADP\n    3640 the DT DET\n    3641 gallery NN NOUN\n    3642 is VBZ VERB\n    3643 a DT DET\n    3644 rare JJ ADJ\n    3645 disease NN NOUN\n    3646 survivor NN NOUN\n    3647 , , PUNCT\n    3648 Megan NNP PROPN\n    3649 Crowley NNP PROPN\n    3650 . . PUNCT\n    3651 \n    \n     _SP SPACE\n    3652 Megan NNP PROPN\n    3653 was VBD AUX\n    3654 diagnosed VBN VERB\n    3655 with IN ADP\n    3656 Pompe NNP PROPN\n    3657 disease NN NOUN\n    3658 , , PUNCT\n    3659 a DT DET\n    3660 rare JJ ADJ\n    3661 and CC CCONJ\n    3662 serious JJ ADJ\n    3663 illness NN NOUN\n    3664 , , PUNCT\n    3665 when WRB ADV\n    3666 she PRP PRON\n    3667 was VBD VERB\n    3668 15 CD NUM\n    3669 months NNS NOUN\n    3670 old JJ ADJ\n    3671 . . PUNCT\n    3672 She PRP PRON\n    3673 was VBD AUX\n    3674 not RB PART\n    3675 expected VBN VERB\n    3676 to TO PART\n    3677 live VB VERB\n    3678 past IN ADP\n    3679 5 CD NUM\n    3680 . . PUNCT\n    3681 On IN ADP\n    3682 receiving VBG VERB\n    3683 this DT DET\n    3684 news NN NOUN\n    3685 , , PUNCT\n    3686 Megan NNP PROPN\n    3687 's POS PART\n    3688 dad NN NOUN\n    3689 John NNP PROPN\n    3690 fought VBD VERB\n    3691 with IN ADP\n    3692 everything NN PRON\n    3693 he PRP PRON\n    3694 had VBD VERB\n    3695 to TO PART\n    3696 save VB VERB\n    3697 the DT DET\n    3698 life NN NOUN\n    3699 of IN ADP\n    3700 his PRP$ PRON\n    3701 precious JJ ADJ\n    3702 child NN NOUN\n    3703 . . PUNCT\n    3704 He PRP PRON\n    3705 founded VBD VERB\n    3706 a DT DET\n    3707 company NN NOUN\n    3708 to TO PART\n    3709 look VB VERB\n    3710 for IN ADP\n    3711 a DT DET\n    3712 cure NN NOUN\n    3713 and CC CCONJ\n    3714 helped VBD VERB\n    3715 develop VB VERB\n    3716 the DT DET\n    3717 drug NN NOUN\n    3718 that WDT DET\n    3719 saved VBD VERB\n    3720 Megan NNP PROPN\n    3721 's POS PART\n    3722 life NN NOUN\n    3723 . . PUNCT\n    3724 Today NN NOUN\n    3725 she PRP PRON\n    3726 is VBZ AUX\n    3727 20 CD NUM\n    3728 years NNS NOUN\n    3729 old JJ ADJ\n    3730 and CC CCONJ\n    3731 a DT DET\n    3732 sophomore NN NOUN\n    3733 at IN ADP\n    3734 Notre NNP PROPN\n    3735 Dame NNP PROPN\n    3736 . . PUNCT\n    3737 \n    \n     _SP SPACE\n    3738 Megan NNP PROPN\n    3739 's POS PART\n    3740 story NN NOUN\n    3741 is VBZ AUX\n    3742 about IN ADP\n    3743 the DT DET\n    3744 unbounded JJ ADJ\n    3745 power NN NOUN\n    3746 of IN ADP\n    3747 a DT DET\n    3748 father NN NOUN\n    3749 's POS PART\n    3750 love NN NOUN\n    3751 for IN ADP\n    3752 a DT DET\n    3753 daughter NN NOUN\n    3754 . . PUNCT\n    3755 But CC CCONJ\n    3756 our PRP$ PRON\n    3757 slow JJ ADJ\n    3758 and CC CCONJ\n    3759 burdensome JJ ADJ\n    3760 approval NN NOUN\n    3761 process NN NOUN\n    3762 at IN ADP\n    3763 the DT DET\n    3764 Food NNP PROPN\n    3765 and CC CCONJ\n    3766 Drug NNP PROPN\n    3767 Administration NNP PROPN\n    3768 keeps VBZ VERB\n    3769 too RB ADV\n    3770 many JJ ADJ\n    3771 advances NNS NOUN\n    3772 , , PUNCT\n    3773 like IN ADP\n    3774 the DT DET\n    3775 one NN NOUN\n    3776 that WDT DET\n    3777 saved VBD VERB\n    3778 Megan NNP PROPN\n    3779 's POS PART\n    3780 life NN NOUN\n    3781 , , PUNCT\n    3782 from IN ADP\n    3783 reaching VBG VERB\n    3784 those DT DET\n    3785 in IN ADP\n    3786 need NN NOUN\n    3787 . . PUNCT\n    3788 If IN SCONJ\n    3789 we PRP PRON\n    3790 slash VBP VERB\n    3791 the DT DET\n    3792 restraints NNS NOUN\n    3793 , , PUNCT\n    3794 not RB PART\n    3795 just RB ADV\n    3796 at IN ADP\n    3797 the DT DET\n    3798 FDA NNP PROPN\n    3799 , , PUNCT\n    3800 but CC CCONJ\n    3801 across IN ADP\n    3802 our PRP$ PRON\n    3803 Government NNP PROPN\n    3804 , , PUNCT\n    3805 then RB ADV\n    3806 we PRP PRON\n    3807 will MD AUX\n    3808 be VB AUX\n    3809 blessed VBN VERB\n    3810 with IN ADP\n    3811 far RB ADV\n    3812 more JJR ADJ\n    3813 miracles NNS NOUN\n    3814 just RB ADV\n    3815 like IN ADP\n    3816 Megan NNP PROPN\n    3817 . . PUNCT\n    3818 In IN ADP\n    3819 fact NN NOUN\n    3820 , , PUNCT\n    3821 our PRP$ PRON\n    3822 children NNS NOUN\n    3823 will MD AUX\n    3824 grow VB VERB\n    3825 up RP ADP\n    3826 in IN ADP\n    3827 a DT DET\n    3828 nation NN NOUN\n    3829 of IN ADP\n    3830 miracles NNS NOUN\n    3831 . . PUNCT\n    3832 \n    \n     _SP SPACE\n    3833 But CC CCONJ\n    3834 to TO PART\n    3835 achieve VB VERB\n    3836 this DT DET\n    3837 future NN NOUN\n    3838 , , PUNCT\n    3839 we PRP PRON\n    3840 must MD AUX\n    3841 enrich VB VERB\n    3842 the DT DET\n    3843 mind NN NOUN\n    3844 and CC CCONJ\n    3845 the DT DET\n    3846 souls NNS NOUN\n    3847 of IN ADP\n    3848 every DT DET\n    3849 American JJ ADJ\n    3850 child NN NOUN\n    3851 . . PUNCT\n    3852 Education NN NOUN\n    3853 is VBZ AUX\n    3854 the DT DET\n    3855 civil JJ ADJ\n    3856 rights NNS NOUN\n    3857 issue NN NOUN\n    3858 of IN ADP\n    3859 our PRP$ PRON\n    3860 time NN NOUN\n    3861 . . PUNCT\n    3862 I PRP PRON\n    3863 am VBP AUX\n    3864 calling VBG VERB\n    3865 upon IN SCONJ\n    3866 members NNS NOUN\n    3867 of IN ADP\n    3868 both DT DET\n    3869 parties NNS NOUN\n    3870 to TO PART\n    3871 pass VB VERB\n    3872 an DT DET\n    3873 education NN NOUN\n    3874 bill NN NOUN\n    3875 that WDT DET\n    3876 funds VBZ VERB\n    3877 school NN NOUN\n    3878 choice NN NOUN\n    3879 for IN ADP\n    3880 disadvantaged JJ ADJ\n    3881 youth NN NOUN\n    3882 , , PUNCT\n    3883 including VBG VERB\n    3884 millions NNS NOUN\n    3885 of IN ADP\n    3886 African JJ ADJ\n    3887 American NNP PROPN\n    3888 and CC CCONJ\n    3889 Latino JJ ADJ\n    3890 children NNS NOUN\n    3891 . . PUNCT\n    3892 These DT DET\n    3893 families NNS NOUN\n    3894 should MD AUX\n    3895 be VB VERB\n    3896 free JJ ADJ\n    3897 to TO PART\n    3898 choose VB VERB\n    3899 the DT DET\n    3900 public JJ ADJ\n    3901 , , PUNCT\n    3902 private JJ ADJ\n    3903 , , PUNCT\n    3904 charter NN NOUN\n    3905 , , PUNCT\n    3906 magnet NN NOUN\n    3907 , , PUNCT\n    3908 religious JJ ADJ\n    3909 , , PUNCT\n    3910 or CC CCONJ\n    3911 home NN NOUN\n    3912 school NN NOUN\n    3913 that WDT DET\n    3914 is VBZ VERB\n    3915 right JJ ADJ\n    3916 for IN ADP\n    3917 them PRP PRON\n    3918 . . PUNCT\n    3919 \n    \n     _SP SPACE\n    3920 Joining VBG VERB\n    3921 us PRP PRON\n    3922 tonight NN NOUN\n    3923 in IN ADP\n    3924 the DT DET\n    3925 gallery NN NOUN\n    3926 is VBZ AUX\n    3927 a DT DET\n    3928 remarkable JJ ADJ\n    3929 woman NN NOUN\n    3930 , , PUNCT\n    3931 Denisha NNP PROPN\n    3932 Merriweather NNP PROPN\n    3933 . . PUNCT\n    3934 As IN ADP\n    3935 a DT DET\n    3936 young JJ ADJ\n    3937 girl NN NOUN\n    3938 , , PUNCT\n    3939 Denisha NNP PROPN\n    3940 struggled VBD VERB\n    3941 in IN ADP\n    3942 school NN NOUN\n    3943 and CC CCONJ\n    3944 failed VBN VERB\n    3945 third JJ ADJ\n    3946 grade NN NOUN\n    3947 twice RB ADV\n    3948 . . PUNCT\n    3949 But CC CCONJ\n    3950 then RB ADV\n    3951 , , PUNCT\n    3952 she PRP PRON\n    3953 was VBD AUX\n    3954 able JJ ADJ\n    3955 to TO PART\n    3956 enroll VB VERB\n    3957 in IN ADP\n    3958 a DT DET\n    3959 private JJ ADJ\n    3960 center NN NOUN\n    3961 for IN ADP\n    3962 learning NN NOUN\n    3963 \u2014 : PUNCT\n    3964 great JJ ADJ\n    3965 learning NN NOUN\n    3966 center NN NOUN\n    3967 \u2014 : PUNCT\n    3968 with IN ADP\n    3969 the DT DET\n    3970 help NN NOUN\n    3971 of IN ADP\n    3972 a DT DET\n    3973 tax NN NOUN\n    3974 credit NN NOUN\n    3975 and CC CCONJ\n    3976 a DT DET\n    3977 scholarship NN NOUN\n    3978 program NN NOUN\n    3979 . . PUNCT\n    3980 \n    \n     _SP SPACE\n    3981 Today NN NOUN\n    3982 , , PUNCT\n    3983 she PRP PRON\n    3984 is VBZ AUX\n    3985 the DT DET\n    3986 first JJ ADJ\n    3987 in IN ADP\n    3988 her PRP$ PRON\n    3989 family NN NOUN\n    3990 to TO PART\n    3991 graduate VB VERB\n    3992 , , PUNCT\n    3993 not RB PART\n    3994 just RB ADV\n    3995 from IN ADP\n    3996 high JJ ADJ\n    3997 school NN NOUN\n    3998 , , PUNCT\n    3999 but CC CCONJ\n    4000 from IN ADP\n    4001 college NN NOUN\n    4002 . . PUNCT\n    4003 Later RB ADV\n    4004 this DT DET\n    4005 year NN NOUN\n    4006 she PRP PRON\n    4007 will MD AUX\n    4008 get VB VERB\n    4009 her PRP$ PRON\n    4010 master NN NOUN\n    4011 's POS PART\n    4012 degree NN NOUN\n    4013 in IN ADP\n    4014 social JJ ADJ\n    4015 work NN NOUN\n    4016 . . PUNCT\n    4017 We PRP PRON\n    4018 want VBP VERB\n    4019 all DT DET\n    4020 children NNS NOUN\n    4021 to TO PART\n    4022 be VB VERB\n    4023 able JJ ADJ\n    4024 to TO PART\n    4025 break VB VERB\n    4026 the DT DET\n    4027 cycle NN NOUN\n    4028 of IN ADP\n    4029 poverty NN NOUN\n    4030 just RB ADV\n    4031 like IN ADP\n    4032 Denisha NNP PROPN\n    4033 . . PUNCT\n    4034 \n    \n     _SP SPACE\n    4035 But CC CCONJ\n    4036 to TO PART\n    4037 break VB VERB\n    4038 the DT DET\n    4039 cycle NN NOUN\n    4040 of IN ADP\n    4041 poverty NN NOUN\n    4042 , , PUNCT\n    4043 we PRP PRON\n    4044 must MD AUX\n    4045 also RB ADV\n    4046 break VB VERB\n    4047 the DT DET\n    4048 cycle NN NOUN\n    4049 of IN ADP\n    4050 violence NN NOUN\n    4051 . . PUNCT\n    4052 The DT DET\n    4053 murder NN NOUN\n    4054 rate NN NOUN\n    4055 in IN ADP\n    4056 2015 CD NUM\n    4057 experienced VBD VERB\n    4058 its PRP$ PRON\n    4059 largest JJS ADJ\n    4060 single JJ ADJ\n    4061 - HYPH PUNCT\n    4062 year NN NOUN\n    4063 increase NN NOUN\n    4064 in IN ADP\n    4065 nearly RB ADV\n    4066 half PDT DET\n    4067 a DT DET\n    4068 century NN NOUN\n    4069 . . PUNCT\n    4070 In IN ADP\n    4071 Chicago NNP PROPN\n    4072 , , PUNCT\n    4073 more JJR ADJ\n    4074 than IN SCONJ\n    4075 4,000 CD NUM\n    4076 people NNS NOUN\n    4077 were VBD AUX\n    4078 shot VBN VERB\n    4079 last JJ ADJ\n    4080 year NN NOUN\n    4081 alone RB ADV\n    4082 , , PUNCT\n    4083 and CC CCONJ\n    4084 the DT DET\n    4085 murder NN NOUN\n    4086 rate NN NOUN\n    4087 so RB ADV\n    4088 far RB ADV\n    4089 this DT DET\n    4090 year NN NOUN\n    4091 has VBZ AUX\n    4092 been VBN VERB\n    4093 even RB ADV\n    4094 higher JJR ADJ\n    4095 . . PUNCT\n    4096 This DT DET\n    4097 is VBZ AUX\n    4098 not RB PART\n    4099 acceptable JJ ADJ\n    4100 in IN ADP\n    4101 our PRP$ PRON\n    4102 society NN NOUN\n    4103 . . PUNCT\n    4104 \n    \n     _SP SPACE\n    4105 Every DT DET\n    4106 American JJ ADJ\n    4107 child NN NOUN\n    4108 should MD AUX\n    4109 be VB VERB\n    4110 able JJ ADJ\n    4111 to TO PART\n    4112 grow VB VERB\n    4113 up RP ADP\n    4114 in IN ADP\n    4115 a DT DET\n    4116 safe JJ ADJ\n    4117 community NN NOUN\n    4118 , , PUNCT\n    4119 to TO PART\n    4120 attend VB VERB\n    4121 a DT DET\n    4122 great JJ ADJ\n    4123 school NN NOUN\n    4124 , , PUNCT\n    4125 and CC CCONJ\n    4126 to TO PART\n    4127 have VB VERB\n    4128 access NN NOUN\n    4129 to IN ADP\n    4130 a DT DET\n    4131 high RB ADV\n    4132 - HYPH PUNCT\n    4133 paying VBG VERB\n    4134 job NN NOUN\n    4135 . . PUNCT\n    4136 But CC CCONJ\n    4137 to TO PART\n    4138 create VB VERB\n    4139 this DT DET\n    4140 future NN NOUN\n    4141 , , PUNCT\n    4142 we PRP PRON\n    4143 must MD AUX\n    4144 work VB VERB\n    4145 with IN ADP\n    4146 , , PUNCT\n    4147 not RB PART\n    4148 against IN ADP\n    4149 \u2014 : PUNCT\n    4150 not RB PART\n    4151 against IN ADP\n    4152 \u2014 : PUNCT\n    4153 the DT DET\n    4154 men NNS NOUN\n    4155 and CC CCONJ\n    4156 women NNS NOUN\n    4157 of IN ADP\n    4158 law NN NOUN\n    4159 enforcement NN NOUN\n    4160 . . PUNCT\n    4161 We PRP PRON\n    4162 must MD AUX\n    4163 build VB VERB\n    4164 bridges NNS NOUN\n    4165 of IN ADP\n    4166 cooperation NN NOUN\n    4167 and CC CCONJ\n    4168 trust NN NOUN\n    4169 , , PUNCT\n    4170 not RB PART\n    4171 drive VB VERB\n    4172 the DT DET\n    4173 wedge NN NOUN\n    4174 of IN ADP\n    4175 disunity NN NOUN\n    4176 , , PUNCT\n    4177 and CC CCONJ\n    4178 really RB ADV\n    4179 , , PUNCT\n    4180 it PRP PRON\n    4181 's VBZ VERB\n    4182 what WP PRON\n    4183 it PRP PRON\n    4184 is VBZ AUX\n    4185 \u2014 : PUNCT\n    4186 division NN NOUN\n    4187 . . PUNCT\n    4188 It PRP PRON\n    4189 's VBZ AUX\n    4190 pure JJ ADJ\n    4191 , , PUNCT\n    4192 unadulterated JJ ADJ\n    4193 division NN NOUN\n    4194 . . PUNCT\n    4195 We PRP PRON\n    4196 have VBP VERB\n    4197 to TO PART\n    4198 unify VB VERB\n    4199 . . PUNCT\n    4200 \n    \n     _SP SPACE\n    4201 Police NNS NOUN\n    4202 and CC CCONJ\n    4203 sheriffs NNS NOUN\n    4204 are VBP AUX\n    4205 members NNS NOUN\n    4206 of IN ADP\n    4207 our PRP$ PRON\n    4208 community NN NOUN\n    4209 . . PUNCT\n    4210 They PRP PRON\n    4211 're VBP VERB\n    4212 friends NNS NOUN\n    4213 and CC CCONJ\n    4214 neighbors NNS NOUN\n    4215 , , PUNCT\n    4216 they PRP PRON\n    4217 're VBP VERB\n    4218 mothers NNS NOUN\n    4219 and CC CCONJ\n    4220 fathers NNS NOUN\n    4221 , , PUNCT\n    4222 sons NNS NOUN\n    4223 and CC CCONJ\n    4224 daughters NNS NOUN\n    4225 , , PUNCT\n    4226 and CC CCONJ\n    4227 they PRP PRON\n    4228 leave VBP VERB\n    4229 behind RB ADV\n    4230 loved VBN VERB\n    4231 ones NNS NOUN\n    4232 every DT DET\n    4233 day NN NOUN\n    4234 who WP PRON\n    4235 worry VBP VERB\n    4236 about IN ADP\n    4237 whether IN SCONJ\n    4238 or CC CCONJ\n    4239 not RB PART\n    4240 they PRP PRON\n    4241 'll MD AUX\n    4242 come VB VERB\n    4243 home RB ADV\n    4244 safe JJ ADJ\n    4245 and CC CCONJ\n    4246 sound JJ ADJ\n    4247 . . PUNCT\n    4248 We PRP PRON\n    4249 must MD AUX\n    4250 support VB VERB\n    4251 the DT DET\n    4252 incredible JJ ADJ\n    4253 men NNS NOUN\n    4254 and CC CCONJ\n    4255 women NNS NOUN\n    4256 of IN ADP\n    4257 law NN NOUN\n    4258 enforcement NN NOUN\n    4259 . . PUNCT\n    4260 \n    \n     _SP SPACE\n    4261 And CC CCONJ\n    4262 we PRP PRON\n    4263 must MD AUX\n    4264 support VB VERB\n    4265 the DT DET\n    4266 victims NNS NOUN\n    4267 of IN ADP\n    4268 crime NN NOUN\n    4269 . . PUNCT\n    4270 I PRP PRON\n    4271 have VBP AUX\n    4272 ordered VBN VERB\n    4273 the DT DET\n    4274 Department NNP PROPN\n    4275 of IN ADP\n    4276 Homeland NNP PROPN\n    4277 Security NNP PROPN\n    4278 to TO PART\n    4279 create VB VERB\n    4280 an DT DET\n    4281 office NN NOUN\n    4282 to TO PART\n    4283 serve VB VERB\n    4284 American JJ ADJ\n    4285 victims NNS NOUN\n    4286 . . PUNCT\n    4287 The DT DET\n    4288 office NN NOUN\n    4289 is VBZ AUX\n    4290 called VBN VERB\n    4291 VOICE NN NOUN\n    4292 : : PUNCT\n    4293 Victims NNS NOUN\n    4294 of IN ADP\n    4295 Immigration NNP PROPN\n    4296 Crime NNP PROPN\n    4297 Engagement NNP PROPN\n    4298 . . PUNCT\n    4299 We PRP PRON\n    4300 are VBP AUX\n    4301 providing VBG VERB\n    4302 a DT DET\n    4303 voice NN NOUN\n    4304 to IN ADP\n    4305 those DT DET\n    4306 who WP PRON\n    4307 have VBP AUX\n    4308 been VBN AUX\n    4309 ignored VBN VERB\n    4310 by IN ADP\n    4311 our PRP$ PRON\n    4312 media NNS NOUN\n    4313 and CC CCONJ\n    4314 silenced VBN VERB\n    4315 by IN ADP\n    4316 special JJ ADJ\n    4317 interests NNS NOUN\n    4318 . . PUNCT\n    4319 Joining VBG VERB\n    4320 us PRP PRON\n    4321 in IN ADP\n    4322 the DT DET\n    4323 audience NN NOUN\n    4324 tonight NN NOUN\n    4325 are VBP AUX\n    4326 four CD NUM\n    4327 very RB ADV\n    4328 brave JJ ADJ\n    4329 Americans NNPS PROPN\n    4330 whose WP$ DET\n    4331 Government NNP PROPN\n    4332 failed VBD VERB\n    4333 them PRP PRON\n    4334 . . PUNCT\n    4335 Their PRP$ PRON\n    4336 names NNS NOUN\n    4337 are VBP AUX\n    4338 Jamiel NNP PROPN\n    4339 Shaw NNP PROPN\n    4340 , , PUNCT\n    4341 Susan NNP PROPN\n    4342 Oliver NNP PROPN\n    4343 , , PUNCT\n    4344 Jenna NNP PROPN\n    4345 Oliver NNP PROPN\n    4346 , , PUNCT\n    4347 and CC CCONJ\n    4348 Jessica NNP PROPN\n    4349 Davis NNP PROPN\n    4350 . . PUNCT\n    4351 \n    \n     _SP SPACE\n    4352 Jamiel NNP PROPN\n    4353 's POS PART\n    4354 17 CD NUM\n    4355 - HYPH PUNCT\n    4356 year NN NOUN\n    4357 - HYPH PUNCT\n    4358 old JJ ADJ\n    4359 son NN NOUN\n    4360 was VBD AUX\n    4361 viciously RB ADV\n    4362 murdered VBN VERB\n    4363 by IN ADP\n    4364 an DT DET\n    4365 illegal JJ ADJ\n    4366 immigrant JJ ADJ\n    4367 gang NN NOUN\n    4368 member NN NOUN\n    4369 who WP PRON\n    4370 had VBD AUX\n    4371 just RB ADV\n    4372 been VBN AUX\n    4373 released VBN VERB\n    4374 from IN ADP\n    4375 prison NN NOUN\n    4376 . . PUNCT\n    4377 Jamiel NNP PROPN\n    4378 Shaw NNP PROPN\n    4379 , , PUNCT\n    4380 Jr. NNP PROPN\n    4381 was VBD AUX\n    4382 an DT DET\n    4383 incredible JJ ADJ\n    4384 young JJ ADJ\n    4385 man NN NOUN\n    4386 , , PUNCT\n    4387 with IN ADP\n    4388 unlimited JJ ADJ\n    4389 potential NN NOUN\n    4390 , , PUNCT\n    4391 who WP PRON\n    4392 was VBD AUX\n    4393 getting VBG VERB\n    4394 ready JJ ADJ\n    4395 to TO PART\n    4396 go VB VERB\n    4397 to IN ADP\n    4398 college NN NOUN\n    4399 where WRB ADV\n    4400 he PRP PRON\n    4401 would MD AUX\n    4402 have VB AUX\n    4403 excelled VBN VERB\n    4404 as IN ADP\n    4405 a DT DET\n    4406 great JJ ADJ\n    4407 college NN NOUN\n    4408 quarterback NN NOUN\n    4409 . . PUNCT\n    4410 But CC CCONJ\n    4411 he PRP PRON\n    4412 never RB ADV\n    4413 got VBD VERB\n    4414 the DT DET\n    4415 chance NN NOUN\n    4416 . . PUNCT\n    4417 His PRP$ PRON\n    4418 father NN NOUN\n    4419 , , PUNCT\n    4420 who WP PRON\n    4421 is VBZ VERB\n    4422 in IN ADP\n    4423 the DT DET\n    4424 audience NN NOUN\n    4425 tonight NN NOUN\n    4426 , , PUNCT\n    4427 has VBZ AUX\n    4428 become VBN VERB\n    4429 a DT DET\n    4430 very RB ADV\n    4431 good JJ ADJ\n    4432 friend NN NOUN\n    4433 of IN ADP\n    4434 mine NN NOUN\n    4435 . . PUNCT\n    4436 Jamiel NNP PROPN\n    4437 , , PUNCT\n    4438 thank VBP VERB\n    4439 you PRP PRON\n    4440 . . PUNCT\n    4441 Thank VBP VERB\n    4442 you PRP PRON\n    4443 . . PUNCT\n    4444 \n    \n     _SP SPACE\n    4445 Also RB ADV\n    4446 with IN ADP\n    4447 us PRP PRON\n    4448 are VBP AUX\n    4449 Susan NNP PROPN\n    4450 Oliver NNP PROPN\n    4451 and CC CCONJ\n    4452 Jessica NNP PROPN\n    4453 Davis NNP PROPN\n    4454 . . PUNCT\n    4455 Their PRP$ PRON\n    4456 husbands NNS NOUN\n    4457 , , PUNCT\n    4458 Deputy NNP PROPN\n    4459 Sheriff NNP PROPN\n    4460 Danny NNP PROPN\n    4461 Oliver NNP PROPN\n    4462 and CC CCONJ\n    4463 Detective NNP PROPN\n    4464 Michael NNP PROPN\n    4465 Davis NNP PROPN\n    4466 , , PUNCT\n    4467 were VBD AUX\n    4468 slain VBN VERB\n    4469 in IN ADP\n    4470 the DT DET\n    4471 line NN NOUN\n    4472 of IN ADP\n    4473 duty NN NOUN\n    4474 in IN ADP\n    4475 California NNP PROPN\n    4476 . . PUNCT\n    4477 They PRP PRON\n    4478 were VBD AUX\n    4479 pillars NNS NOUN\n    4480 of IN ADP\n    4481 their PRP$ PRON\n    4482 community NN NOUN\n    4483 . . PUNCT\n    4484 These DT DET\n    4485 brave JJ ADJ\n    4486 men NNS NOUN\n    4487 were VBD AUX\n    4488 viciously RB ADV\n    4489 gunned VBN VERB\n    4490 down RP ADP\n    4491 by IN ADP\n    4492 an DT DET\n    4493 illegal JJ ADJ\n    4494 immigrant NN NOUN\n    4495 with IN ADP\n    4496 a DT DET\n    4497 criminal JJ ADJ\n    4498 record NN NOUN\n    4499 and CC CCONJ\n    4500 two CD NUM\n    4501 prior JJ ADJ\n    4502 deportations NNS NOUN\n    4503 . . PUNCT\n    4504 Should MD AUX\n    4505 have VB AUX\n    4506 never RB ADV\n    4507 been VBN VERB\n    4508 in IN ADP\n    4509 our PRP$ PRON\n    4510 country NN NOUN\n    4511 . . PUNCT\n    4512 \n    \n     _SP SPACE\n    4513 Sitting VBG VERB\n    4514 with IN ADP\n    4515 Susan NNP PROPN\n    4516 is VBZ AUX\n    4517 her PRP$ PRON\n    4518 daughter NN NOUN\n    4519 , , PUNCT\n    4520 Jenna NNP PROPN\n    4521 . . PUNCT\n    4522 Jenna NNP PROPN\n    4523 , , PUNCT\n    4524 I PRP PRON\n    4525 want VBP VERB\n    4526 you PRP PRON\n    4527 to TO PART\n    4528 know VB VERB\n    4529 that IN SCONJ\n    4530 your PRP$ PRON\n    4531 father NN NOUN\n    4532 was VBD AUX\n    4533 a DT DET\n    4534 hero NN NOUN\n    4535 , , PUNCT\n    4536 and CC CCONJ\n    4537 that IN SCONJ\n    4538 tonight NN NOUN\n    4539 you PRP PRON\n    4540 have VBP VERB\n    4541 the DT DET\n    4542 love NN NOUN\n    4543 of IN ADP\n    4544 an DT DET\n    4545 entire JJ ADJ\n    4546 country NN NOUN\n    4547 supporting VBG VERB\n    4548 you PRP PRON\n    4549 and CC CCONJ\n    4550 praying VBG VERB\n    4551 for IN ADP\n    4552 you PRP PRON\n    4553 . . PUNCT\n    4554 \n    \n     _SP SPACE\n    4555 To IN ADP\n    4556 Jamiel NNP PROPN\n    4557 , , PUNCT\n    4558 Jenna NNP PROPN\n    4559 , , PUNCT\n    4560 Susan NNP PROPN\n    4561 , , PUNCT\n    4562 and CC CCONJ\n    4563 Jessica NNP PROPN\n    4564 : : PUNCT\n    4565 I PRP PRON\n    4566 want VBP VERB\n    4567 you PRP PRON\n    4568 to TO PART\n    4569 know VB VERB\n    4570 that IN SCONJ\n    4571 we PRP PRON\n    4572 will MD AUX\n    4573 never RB ADV\n    4574 stop VB VERB\n    4575 fighting VBG VERB\n    4576 for IN ADP\n    4577 justice NN NOUN\n    4578 . . PUNCT\n    4579 Your PRP$ PRON\n    4580 loved VBN VERB\n    4581 ones NNS NOUN\n    4582 will MD AUX\n    4583 never RB ADV\n    4584 , , PUNCT\n    4585 ever RB ADV\n    4586 be VB AUX\n    4587 forgotten VBN VERB\n    4588 . . PUNCT\n    4589 We PRP PRON\n    4590 will MD AUX\n    4591 always RB ADV\n    4592 honor VB VERB\n    4593 their PRP$ PRON\n    4594 memory NN NOUN\n    4595 . . PUNCT\n    4596 \n    \n     _SP SPACE\n    4597 Finally RB ADV\n    4598 , , PUNCT\n    4599 to TO PART\n    4600 keep VB VERB\n    4601 America NNP PROPN\n    4602 safe JJ ADJ\n    4603 , , PUNCT\n    4604 we PRP PRON\n    4605 must MD AUX\n    4606 provide VB VERB\n    4607 the DT DET\n    4608 men NNS NOUN\n    4609 and CC CCONJ\n    4610 women NNS NOUN\n    4611 of IN ADP\n    4612 the DT DET\n    4613 United NNP PROPN\n    4614 States NNP PROPN\n    4615 military NN NOUN\n    4616 with IN ADP\n    4617 the DT DET\n    4618 tools NNS NOUN\n    4619 they PRP PRON\n    4620 need VBP VERB\n    4621 to TO PART\n    4622 prevent VB VERB\n    4623 war NN NOUN\n    4624 . . PUNCT\n    4625 If IN SCONJ\n    4626 they PRP PRON\n    4627 must MD AUX\n    4628 , , PUNCT\n    4629 they PRP PRON\n    4630 have VBP VERB\n    4631 to TO PART\n    4632 fight VB VERB\n    4633 and CC CCONJ\n    4634 they PRP PRON\n    4635 only RB ADV\n    4636 have VBP VERB\n    4637 to TO PART\n    4638 win VB VERB\n    4639 . . PUNCT\n    4640 \n    \n     _SP SPACE\n    4641 I PRP PRON\n    4642 am VBP AUX\n    4643 sending VBG VERB\n    4644 Congress NNP PROPN\n    4645 a DT DET\n    4646 budget NN NOUN\n    4647 that WDT DET\n    4648 rebuilds VBZ VERB\n    4649 the DT DET\n    4650 military NN NOUN\n    4651 , , PUNCT\n    4652 eliminates VBZ VERB\n    4653 the DT DET\n    4654 defense NN NOUN\n    4655 sequester NN NOUN\n    4656 , , PUNCT\n    4657 and CC CCONJ\n    4658 calls VBZ VERB\n    4659 for IN ADP\n    4660 one CD NUM\n    4661 of IN ADP\n    4662 the DT DET\n    4663 largest JJS ADJ\n    4664 increases NNS NOUN\n    4665 in IN ADP\n    4666 national JJ ADJ\n    4667 defense NN NOUN\n    4668 spending NN NOUN\n    4669 in IN ADP\n    4670 American JJ ADJ\n    4671 history NN NOUN\n    4672 . . PUNCT\n    4673 My PRP$ PRON\n    4674 budget NN NOUN\n    4675 will MD AUX\n    4676 also RB ADV\n    4677 increase VB VERB\n    4678 funding NN NOUN\n    4679 for IN ADP\n    4680 our PRP$ PRON\n    4681 veterans NNS NOUN\n    4682 . . PUNCT\n    4683 Our PRP$ PRON\n    4684 veterans NNS NOUN\n    4685 have VBP AUX\n    4686 delivered VBN VERB\n    4687 for IN ADP\n    4688 this DT DET\n    4689 Nation NN NOUN\n    4690 , , PUNCT\n    4691 and CC CCONJ\n    4692 now RB ADV\n    4693 we PRP PRON\n    4694 must MD AUX\n    4695 deliver VB VERB\n    4696 for IN ADP\n    4697 them PRP PRON\n    4698 . . PUNCT\n    4699 \n    \n     _SP SPACE\n    4700 The DT DET\n    4701 challenges NNS NOUN\n    4702 we PRP PRON\n    4703 face VBP VERB\n    4704 as IN ADP\n    4705 a DT DET\n    4706 nation NN NOUN\n    4707 are VBP AUX\n    4708 great JJ ADJ\n    4709 , , PUNCT\n    4710 but CC CCONJ\n    4711 our PRP$ PRON\n    4712 people NNS NOUN\n    4713 are VBP VERB\n    4714 even RB ADV\n    4715 greater JJR ADJ\n    4716 . . PUNCT\n    4717 And CC CCONJ\n    4718 none NN NOUN\n    4719 are VBP AUX\n    4720 greater JJR ADJ\n    4721 or CC CCONJ\n    4722 are VBP VERB\n    4723 braver JJ ADJ\n    4724 than IN SCONJ\n    4725 those DT DET\n    4726 who WP PRON\n    4727 fight VBP VERB\n    4728 for IN ADP\n    4729 America NNP PROPN\n    4730 in IN ADP\n    4731 uniform NN NOUN\n    4732 . . PUNCT\n    4733 \n    \n     _SP SPACE\n    4734 We PRP PRON\n    4735 are VBP AUX\n    4736 blessed VBN VERB\n    4737 to TO PART\n    4738 be VB AUX\n    4739 joined VBN VERB\n    4740 tonight NN NOUN\n    4741 by IN ADP\n    4742 Carryn NNP PROPN\n    4743 Owens NNP PROPN\n    4744 , , PUNCT\n    4745 the DT DET\n    4746 widow NN NOUN\n    4747 of IN ADP\n    4748 U.S. NNP PROPN\n    4749 Navy NNP PROPN\n    4750 Special NNP PROPN\n    4751 Operator NNP PROPN\n    4752 , , PUNCT\n    4753 Senior NNP PROPN\n    4754 Chief NNP PROPN\n    4755 William NNP PROPN\n    4756 \" `` PUNCT\n    4757 Ryan NNP PROPN\n    4758 \" '' PUNCT\n    4759 Owens NNP PROPN\n    4760 . . PUNCT\n    4761 Ryan NNP PROPN\n    4762 died VBD VERB\n    4763 as IN ADP\n    4764 he PRP PRON\n    4765 lived VBD VERB\n    4766 : : PUNCT\n    4767 a DT DET\n    4768 warrior NN NOUN\n    4769 and CC CCONJ\n    4770 a DT DET\n    4771 hero NN NOUN\n    4772 , , PUNCT\n    4773 battling VBG VERB\n    4774 against IN ADP\n    4775 terrorism NN NOUN\n    4776 and CC CCONJ\n    4777 securing VBG VERB\n    4778 our PRP$ PRON\n    4779 Nation NN NOUN\n    4780 . . PUNCT\n    4781 I PRP PRON\n    4782 just RB ADV\n    4783 spoke VBD VERB\n    4784 to IN ADP\n    4785 our PRP$ PRON\n    4786 great JJ ADJ\n    4787 General NNP PROPN\n    4788 Mattis NNP PROPN\n    4789 , , PUNCT\n    4790 just RB ADV\n    4791 now RB ADV\n    4792 , , PUNCT\n    4793 who WP PRON\n    4794 reconfirmed VBD VERB\n    4795 that DT DET\n    4796 \u2014 : PUNCT\n    4797 and CC CCONJ\n    4798 I PRP PRON\n    4799 quote\u2014\"Ryan VBP VERB\n    4800 was VBD VERB\n    4801 a DT DET\n    4802 part NN NOUN\n    4803 of IN ADP\n    4804 a DT DET\n    4805 highly RB ADV\n    4806 successful JJ ADJ\n    4807 raid NN NOUN\n    4808 that WDT DET\n    4809 generated VBD VERB\n    4810 large JJ ADJ\n    4811 amounts NNS NOUN\n    4812 of IN ADP\n    4813 vital JJ ADJ\n    4814 intelligence NN NOUN\n    4815 that WDT DET\n    4816 will MD AUX\n    4817 lead VB VERB\n    4818 to IN ADP\n    4819 many JJ ADJ\n    4820 more JJR ADJ\n    4821 victories NNS NOUN\n    4822 in IN ADP\n    4823 the DT DET\n    4824 future NN NOUN\n    4825 against IN ADP\n    4826 our PRP$ PRON\n    4827 enemy NN NOUN\n    4828 . . PUNCT\n    4829 \" '' PUNCT\n    4830 Ryan NNP PROPN\n    4831 's POS PART\n    4832 legacy NN NOUN\n    4833 is VBZ AUX\n    4834 etched VBN VERB\n    4835 into IN ADP\n    4836 eternity NN NOUN\n    4837 . . PUNCT\n    4838 Thank VBP VERB\n    4839 you PRP PRON\n    4840 . . PUNCT\n    4841 [ XX X\n    4842 Applause XX X\n    4843 ] -RRB- PUNCT\n    4844 And CC CCONJ\n    4845 Ryan NNP PROPN\n    4846 is VBZ AUX\n    4847 looking VBG VERB\n    4848 down RP ADP\n    4849 , , PUNCT\n    4850 right RB ADV\n    4851 now RB ADV\n    4852 \u2014 : PUNCT\n    4853 you PRP PRON\n    4854 know VBP VERB\n    4855 that DT DET\n    4856 \u2014 : PUNCT\n    4857 and CC CCONJ\n    4858 he PRP PRON\n    4859 is VBZ VERB\n    4860 very RB ADV\n    4861 happy JJ ADJ\n    4862 because IN SCONJ\n    4863 I PRP PRON\n    4864 think VBP VERB\n    4865 he PRP PRON\n    4866 just RB ADV\n    4867 broke VBD VERB\n    4868 a DT DET\n    4869 record NN NOUN\n    4870 . . PUNCT\n    4871 [ XX X\n    4872 Laughter XX X\n    4873 ] -RRB- PUNCT\n    4874 \n    \n     _SP SPACE\n    4875 For IN ADP\n    4876 as IN ADP\n    4877 the DT DET\n    4878 Bible NNP PROPN\n    4879 teaches VBZ VERB\n    4880 us PRP PRON\n    4881 , , PUNCT\n    4882 there EX PRON\n    4883 is VBZ AUX\n    4884 no DT DET\n    4885 greater JJR ADJ\n    4886 act NN NOUN\n    4887 of IN ADP\n    4888 love NN NOUN\n    4889 than IN SCONJ\n    4890 to TO PART\n    4891 lay VB VERB\n    4892 down RP ADP\n    4893 one NN NOUN\n    4894 's POS PART\n    4895 life NN NOUN\n    4896 for IN ADP\n    4897 one PRP PRON\n    4898 's POS PART\n    4899 friends NNS NOUN\n    4900 . . PUNCT\n    4901 Ryan NNP PROPN\n    4902 laid VBD VERB\n    4903 down RP ADP\n    4904 his PRP$ PRON\n    4905 life NN NOUN\n    4906 for IN ADP\n    4907 his PRP$ PRON\n    4908 friends NNS NOUN\n    4909 , , PUNCT\n    4910 for IN ADP\n    4911 his PRP$ PRON\n    4912 country NN NOUN\n    4913 , , PUNCT\n    4914 and CC CCONJ\n    4915 for IN ADP\n    4916 our PRP$ PRON\n    4917 freedom NN NOUN\n    4918 . . PUNCT\n    4919 And CC CCONJ\n    4920 we PRP PRON\n    4921 will MD AUX\n    4922 never RB ADV\n    4923 forget VB VERB\n    4924 Ryan NNP PROPN\n    4925 . . PUNCT\n    4926 \n    \n     _SP SPACE\n    4927 To IN ADP\n    4928 those DT DET\n    4929 allies NNS NOUN\n    4930 who WP PRON\n    4931 wonder VBP VERB\n    4932 what WP PRON\n    4933 kind NN NOUN\n    4934 of IN ADP\n    4935 a DT DET\n    4936 friend NN NOUN\n    4937 America NNP PROPN\n    4938 will MD AUX\n    4939 be VB VERB\n    4940 , , PUNCT\n    4941 look VB VERB\n    4942 no RB ADV\n    4943 further RB ADV\n    4944 than IN SCONJ\n    4945 the DT DET\n    4946 heroes NNS NOUN\n    4947 who WP PRON\n    4948 wear VBP VERB\n    4949 our PRP$ PRON\n    4950 uniform NN NOUN\n    4951 . . PUNCT\n    4952 Our PRP$ PRON\n    4953 foreign JJ ADJ\n    4954 policy NN NOUN\n    4955 calls VBZ VERB\n    4956 for IN ADP\n    4957 a DT DET\n    4958 direct JJ ADJ\n    4959 , , PUNCT\n    4960 robust JJ ADJ\n    4961 , , PUNCT\n    4962 and CC CCONJ\n    4963 meaningful JJ ADJ\n    4964 engagement NN NOUN\n    4965 with IN ADP\n    4966 the DT DET\n    4967 world NN NOUN\n    4968 . . PUNCT\n    4969 It PRP PRON\n    4970 is VBZ AUX\n    4971 American JJ ADJ\n    4972 leadership NN NOUN\n    4973 based VBN VERB\n    4974 on IN ADP\n    4975 vital JJ ADJ\n    4976 security NN NOUN\n    4977 interests NNS NOUN\n    4978 that WDT DET\n    4979 we PRP PRON\n    4980 share VBP VERB\n    4981 with IN ADP\n    4982 our PRP$ PRON\n    4983 allies NNS NOUN\n    4984 all RB ADV\n    4985 across IN ADP\n    4986 the DT DET\n    4987 globe NN NOUN\n    4988 . . PUNCT\n    4989 \n    \n     _SP SPACE\n    4990 We PRP PRON\n    4991 strongly RB ADV\n    4992 support VBP VERB\n    4993 NATO NNP PROPN\n    4994 , , PUNCT\n    4995 an DT DET\n    4996 alliance NN NOUN\n    4997 forged VBD VERB\n    4998 through IN ADP\n    4999 the DT DET\n    5000 bonds NNS NOUN\n    5001 of IN ADP\n    5002 two CD NUM\n    5003 world NN NOUN\n    5004 wars NNS NOUN\n    5005 that WDT DET\n    5006 dethroned VBD VERB\n    5007 fascism NN NOUN\n    5008 , , PUNCT\n    5009 and CC CCONJ\n    5010 a DT DET\n    5011 cold JJ ADJ\n    5012 war NN NOUN\n    5013 , , PUNCT\n    5014 and CC CCONJ\n    5015 defeated VBD VERB\n    5016 communism NN NOUN\n    5017 . . PUNCT\n    5018 \n    \n     _SP SPACE\n    5019 But CC CCONJ\n    5020 our PRP$ PRON\n    5021 partners NNS NOUN\n    5022 must MD AUX\n    5023 meet VB VERB\n    5024 their PRP$ PRON\n    5025 financial JJ ADJ\n    5026 obligations NNS NOUN\n    5027 . . PUNCT\n    5028 And CC CCONJ\n    5029 now RB ADV\n    5030 , , PUNCT\n    5031 based VBN VERB\n    5032 on IN ADP\n    5033 our PRP$ PRON\n    5034 very RB ADV\n    5035 strong JJ ADJ\n    5036 and CC CCONJ\n    5037 frank JJ ADJ\n    5038 discussions NNS NOUN\n    5039 , , PUNCT\n    5040 they PRP PRON\n    5041 are VBP AUX\n    5042 beginning VBG VERB\n    5043 to TO PART\n    5044 do VB VERB\n    5045 just RB ADV\n    5046 that DT DET\n    5047 . . PUNCT\n    5048 In IN ADP\n    5049 fact NN NOUN\n    5050 , , PUNCT\n    5051 I PRP PRON\n    5052 can MD AUX\n    5053 tell VB VERB\n    5054 you PRP PRON\n    5055 , , PUNCT\n    5056 the DT DET\n    5057 money NN NOUN\n    5058 is VBZ AUX\n    5059 pouring VBG VERB\n    5060 in RP ADP\n    5061 . . PUNCT\n    5062 Very RB ADV\n    5063 nice JJ ADJ\n    5064 . . PUNCT\n    5065 We PRP PRON\n    5066 expect VBP VERB\n    5067 our PRP$ PRON\n    5068 partners NNS NOUN\n    5069 \u2014 : PUNCT\n    5070 whether IN SCONJ\n    5071 in IN ADP\n    5072 NATO NNP PROPN\n    5073 , , PUNCT\n    5074 the DT DET\n    5075 Middle NNP PROPN\n    5076 East NNP PROPN\n    5077 , , PUNCT\n    5078 or CC CCONJ\n    5079 in IN ADP\n    5080 the DT DET\n    5081 Pacific NNP PROPN\n    5082 \u2014 : PUNCT\n    5083 to TO PART\n    5084 take VB VERB\n    5085 a DT DET\n    5086 direct JJ ADJ\n    5087 and CC CCONJ\n    5088 meaningful JJ ADJ\n    5089 role NN NOUN\n    5090 in IN ADP\n    5091 both CC CCONJ\n    5092 strategic JJ ADJ\n    5093 and CC CCONJ\n    5094 military JJ ADJ\n    5095 operations NNS NOUN\n    5096 , , PUNCT\n    5097 and CC CCONJ\n    5098 pay VB VERB\n    5099 their PRP$ PRON\n    5100 fair JJ ADJ\n    5101 share NN NOUN\n    5102 of IN ADP\n    5103 the DT DET\n    5104 cost NN NOUN\n    5105 . . PUNCT\n    5106 Have VB VERB\n    5107 to TO PART\n    5108 do VB VERB\n    5109 that DT DET\n    5110 . . PUNCT\n    5111 \n    \n     _SP SPACE\n    5112 We PRP PRON\n    5113 will MD AUX\n    5114 respect VB VERB\n    5115 historic JJ ADJ\n    5116 institutions NNS NOUN\n    5117 , , PUNCT\n    5118 but CC CCONJ\n    5119 we PRP PRON\n    5120 will MD AUX\n    5121 respect VB VERB\n    5122 the DT DET\n    5123 foreign JJ ADJ\n    5124 rights NNS NOUN\n    5125 of IN ADP\n    5126 all DT DET\n    5127 nations NNS NOUN\n    5128 , , PUNCT\n    5129 and CC CCONJ\n    5130 they PRP PRON\n    5131 have VBP VERB\n    5132 to TO PART\n    5133 respect VB VERB\n    5134 our PRP$ PRON\n    5135 rights NNS NOUN\n    5136 as IN ADP\n    5137 a DT DET\n    5138 nation NN NOUN\n    5139 also RB ADV\n    5140 . . PUNCT\n    5141 Free JJ ADJ\n    5142 nations NNS NOUN\n    5143 are VBP AUX\n    5144 the DT DET\n    5145 best JJS ADJ\n    5146 vehicle NN NOUN\n    5147 for IN ADP\n    5148 expressing VBG VERB\n    5149 the DT DET\n    5150 will NN NOUN\n    5151 of IN ADP\n    5152 the DT DET\n    5153 people NNS NOUN\n    5154 , , PUNCT\n    5155 and CC CCONJ\n    5156 America NNP PROPN\n    5157 respects VBZ VERB\n    5158 the DT DET\n    5159 right NN NOUN\n    5160 of IN ADP\n    5161 all DT DET\n    5162 nations NNS NOUN\n    5163 to TO PART\n    5164 chart VB VERB\n    5165 their PRP$ PRON\n    5166 own JJ ADJ\n    5167 path NN NOUN\n    5168 . . PUNCT\n    5169 My PRP$ PRON\n    5170 job NN NOUN\n    5171 is VBZ AUX\n    5172 not RB PART\n    5173 to TO PART\n    5174 represent VB VERB\n    5175 the DT DET\n    5176 world NN NOUN\n    5177 . . PUNCT\n    5178 My PRP$ PRON\n    5179 job NN NOUN\n    5180 is VBZ AUX\n    5181 to TO PART\n    5182 represent VB VERB\n    5183 the DT DET\n    5184 United NNP PROPN\n    5185 States NNP PROPN\n    5186 of IN ADP\n    5187 America NNP PROPN\n    5188 . . PUNCT\n    5189 \n    \n     _SP SPACE\n    5190 But CC CCONJ\n    5191 we PRP PRON\n    5192 know VBP VERB\n    5193 that IN SCONJ\n    5194 America NNP PROPN\n    5195 is VBZ AUX\n    5196 better JJR ADJ\n    5197 off RP ADP\n    5198 when WRB ADV\n    5199 there EX PRON\n    5200 is VBZ VERB\n    5201 less JJR ADJ\n    5202 conflict NN NOUN\n    5203 , , PUNCT\n    5204 not RB PART\n    5205 more JJR ADJ\n    5206 . . PUNCT\n    5207 We PRP PRON\n    5208 must MD AUX\n    5209 learn VB VERB\n    5210 from IN ADP\n    5211 the DT DET\n    5212 mistakes NNS NOUN\n    5213 of IN ADP\n    5214 the DT DET\n    5215 past NN NOUN\n    5216 . . PUNCT\n    5217 We PRP PRON\n    5218 have VBP AUX\n    5219 seen VBN VERB\n    5220 the DT DET\n    5221 war NN NOUN\n    5222 and CC CCONJ\n    5223 the DT DET\n    5224 destruction NN NOUN\n    5225 that WDT DET\n    5226 have VBP AUX\n    5227 ravaged VBN VERB\n    5228 and CC CCONJ\n    5229 raged VBD VERB\n    5230 throughout IN ADP\n    5231 the DT DET\n    5232 world NN NOUN\n    5233 \u2014 : PUNCT\n    5234 all RB ADV\n    5235 across IN ADP\n    5236 the DT DET\n    5237 world NN NOUN\n    5238 . . PUNCT\n    5239 The DT DET\n    5240 only JJ ADJ\n    5241 long JJ ADJ\n    5242 - HYPH PUNCT\n    5243 term NN NOUN\n    5244 solution NN NOUN\n    5245 for IN ADP\n    5246 these DT DET\n    5247 humanitarian JJ ADJ\n    5248 disasters NNS NOUN\n    5249 , , PUNCT\n    5250 in IN ADP\n    5251 many JJ ADJ\n    5252 cases NNS NOUN\n    5253 , , PUNCT\n    5254 is VBZ AUX\n    5255 to TO PART\n    5256 create VB VERB\n    5257 the DT DET\n    5258 conditions NNS NOUN\n    5259 where WRB ADV\n    5260 displaced VBN VERB\n    5261 persons NNS NOUN\n    5262 can MD AUX\n    5263 safely RB ADV\n    5264 return VB VERB\n    5265 home RB ADV\n    5266 and CC CCONJ\n    5267 begin VB VERB\n    5268 the DT DET\n    5269 long JJ ADJ\n    5270 , , PUNCT\n    5271 long JJ ADJ\n    5272 process NN NOUN\n    5273 of IN ADP\n    5274 rebuilding NN NOUN\n    5275 . . PUNCT\n    5276 \n    \n     _SP SPACE\n    5277 America NNP PROPN\n    5278 is VBZ AUX\n    5279 willing JJ ADJ\n    5280 to TO PART\n    5281 find VB VERB\n    5282 new JJ ADJ\n    5283 friends NNS NOUN\n    5284 and CC CCONJ\n    5285 to TO PART\n    5286 forge VB VERB\n    5287 new JJ ADJ\n    5288 partnerships NNS NOUN\n    5289 where WRB ADV\n    5290 shared VBN VERB\n    5291 interests NNS NOUN\n    5292 align NN NOUN\n    5293 . . PUNCT\n    5294 We PRP PRON\n    5295 want VBP VERB\n    5296 harmony NN NOUN\n    5297 and CC CCONJ\n    5298 stability NN NOUN\n    5299 , , PUNCT\n    5300 not RB PART\n    5301 war NN NOUN\n    5302 and CC CCONJ\n    5303 conflict NN NOUN\n    5304 . . PUNCT\n    5305 We PRP PRON\n    5306 want VBP VERB\n    5307 peace NN NOUN\n    5308 , , PUNCT\n    5309 wherever WRB ADV\n    5310 peace NN NOUN\n    5311 can MD AUX\n    5312 be VB AUX\n    5313 found VBN VERB\n    5314 . . PUNCT\n    5315 \n    \n     _SP SPACE\n    5316 America NNP PROPN\n    5317 is VBZ AUX\n    5318 friends NNS NOUN\n    5319 today NN NOUN\n    5320 with IN ADP\n    5321 former JJ ADJ\n    5322 enemies NNS NOUN\n    5323 . . PUNCT\n    5324 Some DT DET\n    5325 of IN ADP\n    5326 our PRP$ PRON\n    5327 closest JJS ADJ\n    5328 allies NNS NOUN\n    5329 , , PUNCT\n    5330 decades NNS NOUN\n    5331 ago RB ADV\n    5332 , , PUNCT\n    5333 fought VBD VERB\n    5334 on IN ADP\n    5335 the DT DET\n    5336 opposite JJ ADJ\n    5337 side NN NOUN\n    5338 of IN ADP\n    5339 these DT DET\n    5340 terrible JJ ADJ\n    5341 , , PUNCT\n    5342 terrible JJ ADJ\n    5343 wars NNS NOUN\n    5344 . . PUNCT\n    5345 This DT DET\n    5346 history NN NOUN\n    5347 should MD AUX\n    5348 give VB VERB\n    5349 us PRP PRON\n    5350 all DT DET\n    5351 faith NN NOUN\n    5352 in IN ADP\n    5353 the DT DET\n    5354 possibilities NNS NOUN\n    5355 for IN ADP\n    5356 a DT DET\n    5357 better JJR ADJ\n    5358 world NN NOUN\n    5359 . . PUNCT\n    5360 Hopefully RB ADV\n    5361 , , PUNCT\n    5362 the DT DET\n    5363 250th JJ ADJ\n    5364 year NN NOUN\n    5365 for IN ADP\n    5366 America NNP PROPN\n    5367 will MD AUX\n    5368 see VB VERB\n    5369 a DT DET\n    5370 world NN NOUN\n    5371 that WDT DET\n    5372 is VBZ VERB\n    5373 more RBR ADV\n    5374 peaceful JJ ADJ\n    5375 , , PUNCT\n    5376 more RBR ADV\n    5377 just RB ADV\n    5378 , , PUNCT\n    5379 and CC CCONJ\n    5380 more RBR ADV\n    5381 free JJ ADJ\n    5382 . . PUNCT\n    5383 \n    \n     _SP SPACE\n    5384 On IN ADP\n    5385 our PRP$ PRON\n    5386 100th JJ ADJ\n    5387 anniversary NN NOUN\n    5388 , , PUNCT\n    5389 in IN ADP\n    5390 1876 CD NUM\n    5391 , , PUNCT\n    5392 citizens NNS NOUN\n    5393 from IN ADP\n    5394 across IN ADP\n    5395 our PRP$ PRON\n    5396 Nation NN NOUN\n    5397 came VBD VERB\n    5398 to IN ADP\n    5399 Philadelphia NNP PROPN\n    5400 to TO PART\n    5401 celebrate VB VERB\n    5402 America NNP PROPN\n    5403 's POS PART\n    5404 centennial NN NOUN\n    5405 . . PUNCT\n    5406 At IN ADP\n    5407 that DT DET\n    5408 celebration NN NOUN\n    5409 , , PUNCT\n    5410 the DT DET\n    5411 country NN NOUN\n    5412 's POS PART\n    5413 builders NNS NOUN\n    5414 and CC CCONJ\n    5415 artists NNS NOUN\n    5416 and CC CCONJ\n    5417 inventors NNS NOUN\n    5418 showed VBD VERB\n    5419 off RP ADP\n    5420 their PRP$ PRON\n    5421 wonderful JJ ADJ\n    5422 creations NNS NOUN\n    5423 . . PUNCT\n    5424 Alexander NNP PROPN\n    5425 Graham NNP PROPN\n    5426 Bell NNP PROPN\n    5427 displayed VBD VERB\n    5428 his PRP$ PRON\n    5429 telephone NN NOUN\n    5430 for IN ADP\n    5431 the DT DET\n    5432 first JJ ADJ\n    5433 time NN NOUN\n    5434 . . PUNCT\n    5435 Remington NNP PROPN\n    5436 unveiled VBD VERB\n    5437 the DT DET\n    5438 first JJ ADJ\n    5439 typewriter NN NOUN\n    5440 . . PUNCT\n    5441 An DT DET\n    5442 early JJ ADJ\n    5443 attempt NN NOUN\n    5444 was VBD AUX\n    5445 made VBN VERB\n    5446 at IN ADP\n    5447 electric JJ ADJ\n    5448 light NN NOUN\n    5449 . . PUNCT\n    5450 Thomas NNP PROPN\n    5451 Edison NNP PROPN\n    5452 showed VBD VERB\n    5453 an DT DET\n    5454 automatic JJ ADJ\n    5455 telegraph NN NOUN\n    5456 and CC CCONJ\n    5457 an DT DET\n    5458 electric JJ ADJ\n    5459 pen NN NOUN\n    5460 . . PUNCT\n    5461 Imagine VB VERB\n    5462 the DT DET\n    5463 wonders NNS NOUN\n    5464 our PRP$ PRON\n    5465 country NN NOUN\n    5466 could MD AUX\n    5467 know VB VERB\n    5468 in IN ADP\n    5469 America NNP PROPN\n    5470 's POS PART\n    5471 250th JJ ADJ\n    5472 year NN NOUN\n    5473 . . PUNCT\n    5474 Think VB VERB\n    5475 of IN ADP\n    5476 the DT DET\n    5477 marvels NNS NOUN\n    5478 we PRP PRON\n    5479 can MD AUX\n    5480 achieve VB VERB\n    5481 if IN SCONJ\n    5482 we PRP PRON\n    5483 simply RB ADV\n    5484 set VBD VERB\n    5485 free JJ ADJ\n    5486 the DT DET\n    5487 dreams NNS NOUN\n    5488 of IN ADP\n    5489 our PRP$ PRON\n    5490 people NNS NOUN\n    5491 . . PUNCT\n    5492 Cures NNS NOUN\n    5493 to IN ADP\n    5494 the DT DET\n    5495 illnesses NNS NOUN\n    5496 that WDT DET\n    5497 have VBP AUX\n    5498 always RB ADV\n    5499 plagued VBN VERB\n    5500 us PRP PRON\n    5501 are VBP AUX\n    5502 not RB PART\n    5503 too RB ADV\n    5504 much JJ ADJ\n    5505 to TO PART\n    5506 hope VB VERB\n    5507 . . PUNCT\n    5508 American JJ ADJ\n    5509 footprints NNS NOUN\n    5510 on IN ADP\n    5511 distant JJ ADJ\n    5512 worlds NNS NOUN\n    5513 are VBP AUX\n    5514 not RB PART\n    5515 too RB ADV\n    5516 big JJ ADJ\n    5517 a DT DET\n    5518 dream NN NOUN\n    5519 . . PUNCT\n    5520 Millions NNS NOUN\n    5521 lifted VBD VERB\n    5522 from IN ADP\n    5523 welfare NN NOUN\n    5524 to IN ADP\n    5525 work NN NOUN\n    5526 is VBZ VERB\n    5527 not RB PART\n    5528 too RB ADV\n    5529 much JJ ADJ\n    5530 to TO PART\n    5531 expect VB VERB\n    5532 . . PUNCT\n    5533 And CC CCONJ\n    5534 streets NNS NOUN\n    5535 where WRB ADV\n    5536 mothers NNS NOUN\n    5537 are VBP VERB\n    5538 safe JJ ADJ\n    5539 from IN ADP\n    5540 fear NN NOUN\n    5541 , , PUNCT\n    5542 schools NNS NOUN\n    5543 where WRB ADV\n    5544 children NNS NOUN\n    5545 learn VBP VERB\n    5546 in IN ADP\n    5547 peace NN NOUN\n    5548 , , PUNCT\n    5549 and CC CCONJ\n    5550 jobs NNS NOUN\n    5551 where WRB ADV\n    5552 Americans NNPS PROPN\n    5553 prosper VBP VERB\n    5554 and CC CCONJ\n    5555 grow VB VERB\n    5556 are VBP AUX\n    5557 not RB PART\n    5558 too RB ADV\n    5559 much JJ ADJ\n    5560 to TO PART\n    5561 ask VB VERB\n    5562 . . PUNCT\n    5563 \n    \n     _SP SPACE\n    5564 When WRB ADV\n    5565 we PRP PRON\n    5566 have VBP VERB\n    5567 all DT DET\n    5568 of IN ADP\n    5569 this DT DET\n    5570 , , PUNCT\n    5571 we PRP PRON\n    5572 will MD AUX\n    5573 have VB AUX\n    5574 made VBN VERB\n    5575 America NNP PROPN\n    5576 greater JJR ADJ\n    5577 than IN SCONJ\n    5578 ever RB ADV\n    5579 before RB ADV\n    5580 \u2014 : PUNCT\n    5581 for IN ADP\n    5582 all DT DET\n    5583 Americans NNPS PROPN\n    5584 . . PUNCT\n    5585 This DT DET\n    5586 is VBZ AUX\n    5587 our PRP$ PRON\n    5588 vision NN NOUN\n    5589 . . PUNCT\n    5590 This DT DET\n    5591 is VBZ AUX\n    5592 our PRP$ PRON\n    5593 mission NN NOUN\n    5594 . . PUNCT\n    5595 But CC CCONJ\n    5596 we PRP PRON\n    5597 can MD AUX\n    5598 only RB ADV\n    5599 get VB VERB\n    5600 there RB ADV\n    5601 together RB ADV\n    5602 . . PUNCT\n    5603 We PRP PRON\n    5604 are VBP AUX\n    5605 one CD NUM\n    5606 people NNS NOUN\n    5607 with IN ADP\n    5608 one CD NUM\n    5609 destiny NN NOUN\n    5610 . . PUNCT\n    5611 We PRP PRON\n    5612 all DT DET\n    5613 bleed VBP VERB\n    5614 the DT DET\n    5615 same JJ ADJ\n    5616 blood NN NOUN\n    5617 . . PUNCT\n    5618 We PRP PRON\n    5619 all DT DET\n    5620 salute VBP VERB\n    5621 the DT DET\n    5622 same JJ ADJ\n    5623 great JJ ADJ\n    5624 American JJ ADJ\n    5625 flag NN NOUN\n    5626 . . PUNCT\n    5627 And CC CCONJ\n    5628 we PRP PRON\n    5629 all DT DET\n    5630 are VBP AUX\n    5631 made VBN VERB\n    5632 by IN ADP\n    5633 the DT DET\n    5634 same JJ ADJ\n    5635 God NNP PROPN\n    5636 . . PUNCT\n    5637 \n    \n     _SP SPACE\n    5638 When WRB ADV\n    5639 we PRP PRON\n    5640 fulfill VBP VERB\n    5641 this DT DET\n    5642 vision NN NOUN\n    5643 , , PUNCT\n    5644 when WRB ADV\n    5645 we PRP PRON\n    5646 celebrate VBP VERB\n    5647 our PRP$ PRON\n    5648 250 CD NUM\n    5649 years NNS NOUN\n    5650 of IN ADP\n    5651 glorious JJ ADJ\n    5652 freedom NN NOUN\n    5653 , , PUNCT\n    5654 we PRP PRON\n    5655 will MD AUX\n    5656 look VB VERB\n    5657 back RB ADV\n    5658 on RB ADV\n    5659 tonight NN NOUN\n    5660 as IN ADP\n    5661 when WRB ADV\n    5662 this DT DET\n    5663 new JJ ADJ\n    5664 chapter NN NOUN\n    5665 of IN ADP\n    5666 American JJ ADJ\n    5667 greatness NN NOUN\n    5668 began VBD VERB\n    5669 . . PUNCT\n    5670 The DT DET\n    5671 time NN NOUN\n    5672 for IN ADP\n    5673 small JJ ADJ\n    5674 thinking NN NOUN\n    5675 is VBZ AUX\n    5676 over RB ADV\n    5677 . . PUNCT\n    5678 The DT DET\n    5679 time NN NOUN\n    5680 for IN ADP\n    5681 trivial JJ ADJ\n    5682 fights NNS NOUN\n    5683 is VBZ AUX\n    5684 behind IN ADP\n    5685 us PRP PRON\n    5686 . . PUNCT\n    5687 We PRP PRON\n    5688 just RB ADV\n    5689 need VBP VERB\n    5690 the DT DET\n    5691 courage NN NOUN\n    5692 to TO PART\n    5693 share VB VERB\n    5694 the DT DET\n    5695 dreams NNS NOUN\n    5696 that WDT DET\n    5697 fill VBP VERB\n    5698 our PRP$ PRON\n    5699 hearts NNS NOUN\n    5700 , , PUNCT\n    5701 the DT DET\n    5702 bravery NN NOUN\n    5703 to TO PART\n    5704 express VB VERB\n    5705 the DT DET\n    5706 hopes NNS NOUN\n    5707 that WDT DET\n    5708 stir VBP VERB\n    5709 our PRP$ PRON\n    5710 souls NNS NOUN\n    5711 , , PUNCT\n    5712 and CC CCONJ\n    5713 the DT DET\n    5714 confidence NN NOUN\n    5715 to TO PART\n    5716 turn VB VERB\n    5717 those DT DET\n    5718 hopes NNS NOUN\n    5719 and CC CCONJ\n    5720 those DT DET\n    5721 dreams NNS NOUN\n    5722 into IN ADP\n    5723 action NN NOUN\n    5724 . . PUNCT\n    5725 \n    \n     _SP SPACE\n    5726 From IN ADP\n    5727 now RB ADV\n    5728 on RB ADV\n    5729 , , PUNCT\n    5730 America NNP PROPN\n    5731 will MD AUX\n    5732 be VB AUX\n    5733 empowered VBN VERB\n    5734 by IN ADP\n    5735 our PRP$ PRON\n    5736 aspirations NNS NOUN\n    5737 , , PUNCT\n    5738 not RB PART\n    5739 burdened VBN VERB\n    5740 by IN ADP\n    5741 our PRP$ PRON\n    5742 fears NNS NOUN\n    5743 ; , PUNCT\n    5744 inspired VBN VERB\n    5745 by IN ADP\n    5746 the DT DET\n    5747 future NN NOUN\n    5748 , , PUNCT\n    5749 not RB PART\n    5750 bound VBN VERB\n    5751 by IN ADP\n    5752 failures NNS NOUN\n    5753 of IN ADP\n    5754 the DT DET\n    5755 past NN NOUN\n    5756 ; : PUNCT\n    5757 and CC CCONJ\n    5758 guided VBN VERB\n    5759 by IN ADP\n    5760 our PRP$ PRON\n    5761 vision NN NOUN\n    5762 , , PUNCT\n    5763 not RB PART\n    5764 blinded VBN VERB\n    5765 by IN ADP\n    5766 our PRP$ PRON\n    5767 doubts NNS NOUN\n    5768 . . PUNCT\n    5769 \n    \n     _SP SPACE\n    5770 I PRP PRON\n    5771 am VBP AUX\n    5772 asking VBG VERB\n    5773 all DT DET\n    5774 citizens NNS NOUN\n    5775 to TO PART\n    5776 embrace VB VERB\n    5777 this DT DET\n    5778 renewal NN NOUN\n    5779 of IN ADP\n    5780 the DT DET\n    5781 American JJ ADJ\n    5782 spirit NN NOUN\n    5783 . . PUNCT\n    5784 I PRP PRON\n    5785 am VBP AUX\n    5786 asking VBG VERB\n    5787 all DT DET\n    5788 Members NNS NOUN\n    5789 of IN ADP\n    5790 Congress NNP PROPN\n    5791 to TO PART\n    5792 join VB VERB\n    5793 me PRP PRON\n    5794 in IN ADP\n    5795 dreaming VBG VERB\n    5796 big JJ ADJ\n    5797 and CC CCONJ\n    5798 bold JJ ADJ\n    5799 , , PUNCT\n    5800 and CC CCONJ\n    5801 daring VBG VERB\n    5802 things NNS NOUN\n    5803 for IN ADP\n    5804 our PRP$ PRON\n    5805 country NN NOUN\n    5806 . . PUNCT\n    5807 I PRP PRON\n    5808 am VBP AUX\n    5809 asking VBG VERB\n    5810 everyone NN PRON\n    5811 watching VBG VERB\n    5812 tonight NN NOUN\n    5813 to TO PART\n    5814 seize VB VERB\n    5815 this DT DET\n    5816 moment NN NOUN\n    5817 . . PUNCT\n    5818 Believe VB VERB\n    5819 in IN ADP\n    5820 yourselves NNS NOUN\n    5821 , , PUNCT\n    5822 believe VB VERB\n    5823 in IN ADP\n    5824 your PRP$ PRON\n    5825 future NN NOUN\n    5826 , , PUNCT\n    5827 and CC CCONJ\n    5828 believe VB VERB\n    5829 , , PUNCT\n    5830 once RB ADV\n    5831 more JJR ADJ\n    5832 , , PUNCT\n    5833 in IN ADP\n    5834 America NNP PROPN\n    5835 . . PUNCT\n    5836 \n    \n     _SP SPACE\n    5837 Thank VBP VERB\n    5838 you PRP PRON\n    5839 , , PUNCT\n    5840 God NNP PROPN\n    5841 bless VBP VERB\n    5842 you PRP PRON\n    5843 , , PUNCT\n    5844 and CC CCONJ\n    5845 God NNP PROPN\n    5846 bless VBP VERB\n    5847 the DT DET\n    5848 United NNP PROPN\n    5849 States NNP PROPN\n    5850 . . PUNCT\n\n\n### Noun chunks\n\nChunking is a process of getting just specific part of speeches. The most popular is the noun chunking. It allow us to get the general meaning of what is the text about.\n\n\n```python\nfor np in doc.noun_chunks:\n    print(np)\n```\n\n    you\n    Mr. Vice President\n    Members\n    Congress\n    the First Lady\n    the United States\n    citizens\n    America\n    Tonight\n    we\n    the conclusion\n    our celebration\n    Black History Month\n    we\n    our Nation's path\n    civil rights\n    the work\n    Recent threats\n    Jewish community centers\n    vandalism\n    Jewish cemeteries\n    last week's shooting\n    Kansas City\n    us\n    we\n    a nation\n    policies\n    we\n    a country\n    hate\n    evil\n    its very ugly forms\n    Each American generation\n    the torch\n    truth\n    liberty\n    justice\n    an unbroken chain\n    the present\n    That torch\n    our hands\n    we\n    it\n    the world\n    I\n    a message\n    unity\n    strength\n    it\n    a message\n    my heart\n    A new chapter\n    American greatness\n    A new national pride\n    our Nation\n    a new surge\n    optimism\n    impossible dreams\n    our grasp\n    What\n    we\n    the renewal\n    the American spirit\n    Our allies\n    America\n    All the nations\n    the world\n    friend\n    foe\n    America\n    America\n    America\n    9 years\n    the United States\n    the 250th anniversary\n    our founding\n    the day\n    we\n    our independence\n    It\n    the great milestones\n    the history\n    the world\n    what\n    America\n    we\n    our 250th year\n    What kind\n    country\n    we\n    our children\n    I\n    the mistakes\n    recent decades\n    the course\n    our future\n    we\n    our middle class shrink\n    we\n    our jobs\n    wealth\n    foreign countries\n    We\n    one global project\n    the fates\n    our children\n    the inner cities\n    Chicago\n    Baltimore\n    Detroit\n    so many other places\n    our land\n    We\n    the borders\n    other nations\n    our own borders\n    anyone\n    drugs\n    a now unprecedented rate\n    we\n    trillions\n    trillions\n    dollars\n    our infrastructure\n    home\n    the Earth\n    our feet\n    The rebellion\n    a quiet protest\n    families\n    all colors\n    creeds\n    families\n    who\n    a fair shot\n    their children\n    a fair hearing\n    their concerns\n    the quiet voices\n    a loud chorus\n    thousands\n    citizens\n    cities\n    our country\n    the chorus\n    an earthquake\n    the people\n    the tens\n    millions\n    they\n    crucial demand\n    America\n    its own citizens\n    we\n    America\n    industries\n    life\n    Heroic veterans\n    the care\n    they\n    Our military\n    the resources\n    its brave warriors\n    Crumbling infrastructure\n    new roads\n    bridges\n    tunnels\n    airports\n    our very, very beautiful land\n    Our terrible drug epidemic\n    our neglected inner cities\n    a rebirth\n    hope\n    safety\n    opportunity\n    we\n    our promises\n    the American people\n    you\n    It\n    over a month\n    my Inauguration\n    I\n    this moment\n    the Nation\n    the progress\n    I\n    those promises\n    my election\n    Ford\n    Fiat Chrysler\n    General Motors\n    Sprint\n    Softbank\n    Lockheed\n    Intel\n    Walmart\n    many others\n    they\n    billions\n    billions\n    dollars\n    the United States\n    tens of thousands\n    new American jobs\n    The stock market\n    value\n    the election\n    November\n    a record\n    We\n    taxpayers\n    hundreds of millions\n    dollars\n    the price\n    fantastic\n    it\n    a fantastic\u2014new F-35 jet fighter\n    we\n    billions\n    contracts\n    our Government\n    We\n    a hiring freeze\n    nonmilitary and nonessential Federal workers\n    We\n    the swamp\n    government corruption\n    a 5-year ban\n    lobbying\n    executive branch officials\n    a lifetime ban\u2014[applause]\u2014thank\n    you\n    you\n    And a lifetime ban\n    lobbyists\n    a foreign government\n    We\n    a historic effort\n    job-crushing regulations\n    a deregulation\n    Task Force\n    every Government agency\n    we\n    a new rule\n    every one new regulation\n    two old regulations\n    We\n    the regulations\n    the future\n    livelihood\n    our great coal miners\n    We\n    the way\n    the construction\n    the Keystone\n    Dakota Access pipelines\n    tens of thousands\n    jobs\n    I\n    a new directive\n    new American pipelines\n    American steel\n    We\n    the United States\n    the job-killing Trans-Pacific Partnership\n    the help\n    Prime Minister Justin Trudeau\n    we\n    a council\n    our neighbors\n    Canada\n    women entrepreneurs\n    access\n    the networks\n    markets\n    capital\n    they\n    a business\n    their financial dreams\n    our citizens\n    I\n    the Department\n    Justice\n    a Task Force\n    Violent Crime\n    I\n    the Departments\n    Homeland Security\n    Justice\n    the Department\n    State\n    the Director\n    National Intelligence\n    an aggressive strategy\n    the criminal cartels\n    our Nation\n    We\n    the drugs\n    our country\n    our youth\n    we\n    treatment\n    who\n    the same time\n    my administration\n    the pleas\n    the American people\n    immigration enforcement\n    border security\n    our immigration laws\n    we\n    wages\n    billions\n    billions\n    dollars\n    our communities\n    everyone\n    We\n    all Americans\n    an environment\n    lawless chaos\n    We\n    integrity\n    the rule\n    law\n    our borders\n    that reason\n    we\n    the construction\n    a great, great wall\n    our southern border\n    we\n    we\n    gang members\n    drug dealers\n    criminals\n    our communities\n    prey\n    our very innocent citizens\n    Bad ones\n    I\n    I\n    the campaign\n    Congress\n    who\n    we\n    our laws\n    I\n    you\n    this one question\n    What\n    you\n    the American family\n    their jobs\n    their income\n    their loved one\n    America\n    its laws\n    its borders\n    Our obligation\n    the citizens\n    the United States\n    We\n    strong measures\n    our Nation\n    radical Islamic terrorism\n    data\n    the Department\n    Justice\n    individuals\n    terrorism\n    terrorism-related offenses\n    our country\n    We\n    the attacks\n    home\n    Boston\n    San Bernardino\n    the Pentagon\n    We\n    the attacks\n    France\n    Belgium\n    Germany\n    the world\n    It\n    uncontrolled entry\n    places\n    proper vetting\n    the high honor\n    admission\n    the United States\n    this country\n    its people\n    its values\n    We\n    a beachhead\n    terrorism\n    America\n    We\n    our Nation\n    a sanctuary\n    extremists\n    my administration\n    improved vetting procedures\n    we\n    new steps\n    our Nation\n    who\n    us\n    I\n    the Department\n    Defense\n    a plan\n    ISIS\n    a network\n    lawless savages\n    Muslims\n    Christians\n    men\n    women\n    children\n    all faiths\n    all beliefs\n    We\n    our allies\n    our friends\n    allies\n    the Muslim world\n    this vile enemy\n    our planet\n    I\n    new sanctions\n    entities\n    individuals\n    who\n    Iran's ballistic missile program\n    our unbreakable alliance\n    the State\n    Israel\n    I\n    my promise\n    a Justice\n    the United States Supreme Court\n    my list\n    20 judges\n    who\n    our Constitution\n    I\n    Maureen Scalia\n    us\n    the gallery\n    you\n    Her late, great husband\n    Antonin Scalia\n    a symbol\n    American justice\n    his seat\n    we\n    Judge Neil Gorsuch\n    a man\n    incredible skill\n    deep devotion\n    the law\n    He\n    the Court\n    Appeals\n    I\n    the Senate\n    his nomination\n    I\n    the next steps\n    we\n    a country\n    we\n    the circumstances\n    we\n    Ninety-four million Americans\n    the labor force\n    Over 43 million people\n    poverty\n    over 43 million Americans\n    food stamps\n    5 people\n    their prime working years\n    We\n    the worst financial recovery\n    65 years\n    the last 8 years\n    the past administration\n    more new debt\n    the other Presidents\n    We\n    more than one-fourth\n    our manufacturing jobs\n    NAFTA\n    we\n    60,000 factories\n    China\n    the World Trade Organization\n    Our trade deficit\n    goods\n    the world\n    nearly $800 billion dollars\n    we\n    a series\n    tragic foreign policy disasters\n    us\n    the differences\n    party\n    It\n    us\n    the American spirit\n    every challenge\n    history\n    our goals\n    home\n    we\n    the engine\n    the American economy\n    it\n    companies\n    business\n    the United States\n    companies\n    our country\n    American companies\n    the highest rates\n    the world\n    My economic team\n    historic tax reform\n    the tax rate\n    our companies\n    they\n    anyone\n    It\n    a big, big cut\n    the same time\n    we\n    massive tax relief\n    the middle class\n    We\n    a level playing field\n    American companies\n    our workers\n    it\n    we\n    products\n    America\n    many other countries\n    us\n    very high tariffs\n    taxes\n    foreign companies\n    their products\n    America\n    we\n    them\n    nothing\n    almost nothing\n    I\n    officials\n    workers\n    a great American company\n    Harley-Davidson\n    fact\n    they\n    their magnificent motorcycles\n    the U.S.A.\n    the front lawn\n    the White House\n    they\n    me\n    I\n    you\n    our meeting\n    I\n    them\n    you\n    business\n    They\n    it\n    I\n    them\n    you\n    other countries\n    mainly international sales\n    They\n    me\n    they\n    they\n    it\n    it\n    business\n    other countries\n    they\n    our goods\n    such a high rate\n    They\n    the case\n    another country\n    they\n    their motorcycles\n    100 percent\n    They\n    a change\n    I\n    I\n    free trade\n    it\n    fair trade\n    It\n    a long time\n    we\n    fair trade\n    The first Republican President\n    Abraham Lincoln\n    the \"abandonment\n    the protective policy\n    the American Government\n    our people\n    Lincoln\n    it\n    time\n    we\n    his advice\n    his words\n    I\n    America\n    its great companies\n    workers\n    advantage\n    us\n    They\n    advantage\n    our country\n    I\n    millions\n    jobs\n    our workers\n    our system\n    legal immigration\n    The current, outdated system\n    wages\n    our poorest workers\n    great pressure\n    taxpayers\n    Nations\n    the world\n    Canada\n    Australia\n    many others\n    a merit-based immigration system\n    It\n    a basic principle\n    a country\n    themselves\n    America\n    we\n    this rule\n    the very public resources\n    our poorest citizens\n    the National Academy\n    Sciences\n    our current immigration system\n    American taxpayers\n    many billions\n    dollars\n    this current system\n    lower skilled immigration\n    a merit-based system\n    we\n    so many more benefits\n    It\n    countless dollars\n    workers' wages\n    families\n    immigrant families\n    the middle class\n    they\n    it\n    they\n    I\n    real and positive immigration reform\n    we\n    the following goals\n    jobs\n    wages\n    Americans\n    our Nation's security\n    respect\n    our laws\n    we\n    the wellbeing\n    American citizens\n    I\n    Republicans\n    Democrats\n    an outcome\n    our country\n    decades\n    Another Republican President\n    Dwight D. Eisenhower\n    the last truly great national infrastructure program\n    the building\n    the Interstate Highway System\n    The time\n    a new program\n    national rebuilding\n    America\n    the Middle East\n    our infrastructure\n    home\n    we\n    our country\n    maybe even three times\n    we\n    people\n    who\n    the ability\n    our national rebuilding\n    I\n    Congress\n    legislation\n    a $1 trillion investment\n    infrastructure\n    the United States\n    both public and private capital\n    millions\n    new jobs\n    This effort\n    two core principles\n    I\n    this Congress\n    Obamacare\n    reforms\n    choice\n    access\n    lower costs\n    the same time\n    better health care\n    every American\n    Government-approved health insurance\n    the right solution\n    our country\n    The way\n    health insurance\n    everyone\n    the cost\n    health insurance\n    what\n    we\n    premiums\n    double and triple digits\n    an example\n    Arizona\n    Governor Matt Bevin\n    Kentucky\n    Obamacare\n    his State\n    the State\n    Kentucky\n    it\n    One-third\n    the counties\n    only one insurer\n    they\n    them\n    They\n    them\n    They\n    many Americans\n    no choice\n    no choice\n    you\n    you\n    your doctor\n    your plan\n    We\n    those promises\n    Obamacare\n    we\n    all Americans\n    Action\n    a choice\n    it\n    a necessity\n    I\n    all Democrats\n    Republicans\n    Congress\n    us\n    Americans\n    this imploding Obamacare disaster\n    the principles\n    the Congress\n    we\n    a better health care system\n    all Americans\n    we\n    Americans\n    preexisting conditions\n    access\n    coverage\n    we\n    a stable transition\n    Americans\n    the health care exchanges\n    we\n    Americans\n    their own coverage\n    the use\n    tax credits\n    health savings accounts\n    it\n    the plan\n    they\n    the plan\n    them\n    our Government\n    we\n    our State Governors\n    the resources\n    flexibility\n    they\n    Medicaid\n    no one\n    we\n    legal reforms\n    patients\n    doctors\n    unnecessary costs\n    the price\n    insurance\n    work\n    the artificially high price\n    drugs\n    them\n    the time\n    Americans\n    the freedom\n    health insurance\n    State lines\n    a truly competitive national marketplace\n    costs\n    far better care\n    Everything\n    our country\n    Every problem\n    every hurting family\n    healing\n    hope\n    Our citizens\n    forces\n    the job\n    it\n    so many other things\n    Democrats\n    Republicans\n    the good\n    our country\n    the good\n    the American people\n    My administration\n    members\n    both parties\n    childcare\n    new parents\n    they\n    women's health\n    clean air\n    clean water\n    our military\n    our infrastructure\n    True love\n    our people\n    us\n    common ground\n    the common good\n    behalf\n    every American child\n    who\n    a much brighter future\n    An incredible young woman\n    us\n    who\n    an inspiration\n    us\n    Today\n    Rare Disease Day\n    us\n    the gallery\n    a rare disease survivor\n    Megan Crowley\n    Megan\n    Pompe disease\n    a rare and serious illness\n    she\n    She\n    this news\n    Megan's dad\n    John\n    everything\n    he\n    the life\n    his precious child\n    He\n    a company\n    a cure\n    the drug\n    Megan's life\n    she\n    a sophomore\n    Notre Dame\n    Megan's story\n    the unbounded power\n    a father's love\n    a daughter\n    our slow and burdensome approval process\n    the Food and Drug Administration\n    too many advances\n    the one\n    Megan's life\n    need\n    we\n    the restraints\n    the FDA\n    our Government\n    we\n    far more miracles\n    Megan\n    fact\n    our children\n    a nation\n    miracles\n    this future\n    we\n    the mind\n    the souls\n    every American child\n    Education\n    the civil rights issue\n    our time\n    I\n    members\n    both parties\n    an education bill\n    school choice\n    disadvantaged youth\n    millions\n    African American and Latino children\n    These families\n    charter\n    magnet\n    home school\n    them\n    us\n    the gallery\n    a remarkable woman\n    Denisha Merriweather\n    a young girl\n    Denisha\n    school\n    third grade\n    she\n    a private center\n    learning\n    great learning center\n    the help\n    a tax credit\n    a scholarship program\n    she\n    her family\n    high school\n    college\n    she\n    her master's degree\n    social work\n    We\n    all children\n    the cycle\n    poverty\n    Denisha\n    the cycle\n    poverty\n    we\n    the cycle\n    violence\n    The murder rate\n    its largest single-year increase\n    nearly half a century\n    Chicago\n    more than 4,000 people\n    the murder rate\n    our society\n    Every American child\n    a safe community\n    a great school\n    access\n    a high-paying job\n    this future\n    we\n    the men\n    women\n    law enforcement\n    We\n    bridges\n    cooperation\n    trust\n    the wedge\n    disunity\n    it\n    what\n    it\n    division\n    It\n    pure, unadulterated division\n    We\n    Police\n    sheriffs\n    members\n    our community\n    They\n    friends\n    neighbors\n    they\n    mothers\n    fathers\n    sons\n    daughters\n    they\n    loved ones\n    who\n    they\n    We\n    the incredible men\n    women\n    law enforcement\n    we\n    the victims\n    crime\n    I\n    the Department\n    Homeland Security\n    an office\n    American victims\n    The office\n    VOICE\n    Victims\n    Immigration Crime Engagement\n    We\n    a voice\n    who\n    our media\n    special interests\n    us\n    the audience\n    four very brave Americans\n    whose Government\n    them\n    Their names\n    Jamiel Shaw\n    Susan Oliver\n    Jenna Oliver\n    Jessica Davis\n    Jamiel's 17-year-old son\n    an illegal immigrant gang member\n    who\n    prison\n    Jamiel Shaw, Jr.\n    an incredible young man\n    unlimited potential\n    who\n    college\n    he\n    a great college quarterback\n    he\n    the chance\n    His father\n    who\n    the audience\n    a very good friend\n    mine\n    you\n    you\n    us\n    Susan Oliver\n    Jessica Davis\n    Deputy Sheriff Danny Oliver\n    Detective Michael Davis\n    the line\n    duty\n    California\n    They\n    pillars\n    their community\n    These brave men\n    an illegal immigrant\n    a criminal record\n    two prior deportations\n    our country\n    Susan\n    her daughter\n    Jenna\n    I\n    you\n    your father\n    a hero\n    you\n    the love\n    an entire country\n    you\n    you\n    Jamiel\n    Jenna\n    Susan\n    Jessica\n    I\n    you\n    we\n    justice\n    Your loved ones\n    We\n    their memory\n    America\n    we\n    the men\n    women\n    the United States military\n    the tools\n    they\n    war\n    they\n    they\n    they\n    I\n    Congress\n    a budget\n    the military\n    the defense sequester\n    the largest increases\n    national defense spending\n    American history\n    My budget\n    funding\n    our veterans\n    Our veterans\n    this Nation\n    we\n    them\n    The challenges\n    we\n    a nation\n    our people\n    none\n    who\n    America\n    uniform\n    We\n    Carryn Owens\n    the widow\n    U.S. Navy Special Operator\n    Senior Chief William \"Ryan\" Owens\n    Ryan\n    he\n    a warrior\n    a hero\n    terrorism\n    our Nation\n    I\n    our great General Mattis\n    who\n    I\n    a part\n    a highly successful raid\n    large amounts\n    vital intelligence\n    many more victories\n    the future\n    our enemy\n    Ryan's legacy\n    eternity\n    you\n    Ryan\n    you\n    he\n    I\n    he\n    a record\n    the Bible\n    us\n    no greater act\n    love\n    one's life\n    one's friends\n    Ryan\n    his life\n    his friends\n    his country\n    our freedom\n    we\n    Ryan\n    those allies\n    who\n    what kind\n    a friend\n    America\n    the heroes\n    who\n    our uniform\n    Our foreign policy\n    a direct, robust, and meaningful engagement\n    the world\n    It\n    American leadership\n    vital security interests\n    we\n    our allies\n    the globe\n    We\n    NATO\n    an alliance\n    the bonds\n    two world wars\n    fascism\n    a cold war\n    communism\n    our partners\n    their financial obligations\n    our very strong and frank discussions\n    they\n    fact\n    I\n    you\n    the money\n    We\n    our partners\n    NATO\n    the Middle East\n    the Pacific\n    a direct and meaningful role\n    both strategic and military operations\n    their fair share\n    the cost\n    We\n    historic institutions\n    we\n    the foreign rights\n    all nations\n    they\n    our rights\n    a nation\n    Free nations\n    the best vehicle\n    the will\n    the people\n    America\n    the right\n    all nations\n    their own path\n    My job\n    the world\n    My job\n    the United States\n    America\n    we\n    America\n    less conflict\n    We\n    the mistakes\n    the past\n    We\n    the war\n    the destruction\n    the world\n    the world\n    The only long-term solution\n    these humanitarian disasters\n    many cases\n    the conditions\n    displaced persons\n    the long, long process\n    rebuilding\n    America\n    new friends\n    new partnerships\n    shared interests\n    We\n    harmony\n    stability\n    not war\n    conflict\n    We\n    peace\n    peace\n    America\n    friends\n    former enemies\n    our closest allies\n    the opposite side\n    these terrible, terrible wars\n    This history\n    us\n    all faith\n    the possibilities\n    a better world\n    the 250th year\n    America\n    a world\n    our 100th anniversary\n    citizens\n    our Nation\n    Philadelphia\n    America's centennial\n    that celebration\n    the country's builders\n    artists\n    inventors\n    their wonderful creations\n    Alexander Graham Bell\n    his telephone\n    the first time\n    Remington\n    the first typewriter\n    An early attempt\n    electric light\n    Thomas Edison\n    an automatic telegraph\n    an electric pen\n    the wonders\n    our country\n    America's 250th year\n    the marvels\n    we\n    we\n    the dreams\n    our people\n    Cures\n    the illnesses\n    us\n    American footprints\n    distant worlds\n    too big a dream\n    Millions\n    welfare\n    work\n    mothers\n    fear\n    children\n    peace\n    Americans\n    we\n    we\n    America\n    all Americans\n    our vision\n    our mission\n    we\n    We\n    one people\n    one destiny\n    We\n    the same blood\n    We\n    the same great American flag\n    we\n    the same God\n    we\n    this vision\n    we\n    our 250 years\n    glorious freedom\n    we\n    this new chapter\n    American greatness\n    The time\n    small thinking\n    The time\n    trivial fights\n    us\n    We\n    the courage\n    the dreams\n    our hearts\n    the bravery\n    the hopes\n    our souls\n    the confidence\n    those hopes\n    those dreams\n    action\n    America\n    our aspirations\n    our fears\n    the future\n    failures\n    the past\n    our vision\n    our doubts\n    I\n    all citizens\n    this renewal\n    the American spirit\n    I\n    all Members\n    Congress\n    me\n    things\n    our country\n    I\n    everyone\n    this moment\n    yourselves\n    your future\n    America\n    you\n    God\n    you\n    God\n    the United States\n\n\n### Named entity recognition\n\nThe last feature that we show here is the named entitiy resolution. It returns a NER of each word.\n\n\n```python\nfor entity in doc.ents:\n    print(entity.label_, entity.text)\n```\n\n    PERSON Speaker\n    ORG Congress\n    ORDINAL First\n    GPE the United States\n    GPE America\n    TIME Tonight\n    EVENT Black History Month\n    ORG Nation\n    NORP Jewish\n    NORP Jewish\n    DATE last week's\n    GPE Kansas City\n    NORP American\n    TIME tonight\n    NORP American\n    DATE today\n    NORP American\n    GPE America\n    GPE America\n    GPE America\n    GPE America\n    DATE 9 years\n    GPE the United States\n    ORDINAL 250th\n    DATE 250 years\n    DATE the day\n    GPE America\n    ORDINAL 250th\n    DATE recent decades\n    CARDINAL one\n    GPE Chicago\n    GPE Baltimore\n    GPE Detroit\n    CARDINAL trillions\n    MONEY trillions of dollars\n    DATE 2016\n    LOC Earth\n    CARDINAL thousands\n    CARDINAL one\n    GPE America\n    GPE America\n    NORP American\n    ORG Inauguration\n    ORG Ford\n    ORG Fiat Chrysler\n    ORG General Motors\n    GPE Sprint\n    ORG Softbank\n    ORG Lockheed\n    ORG Intel\n    MONEY billions and billions of dollars\n    GPE the United States\n    CARDINAL tens of thousands\n    NORP American\n    MONEY almost $3 trillion\n    DATE November 8\n    MONEY hundreds of millions of dollars\n    PRODUCT F-35\n    CARDINAL billions\n    DATE 5-year\n    PRODUCT Task Force\n    CARDINAL one\n    CARDINAL two\n    ORG Keystone\n    ORG Dakota Access\n    CARDINAL tens of thousands\n    NORP American\n    NORP American\n    GPE the United States\n    ORG Trans-Pacific Partnership\n    PERSON Justin Trudeau\n    GPE Canada\n    ORG the Department of Justice\n    PRODUCT a Task Force\n    ORG Departments of Homeland Security\n    ORG Justice\n    ORG the Department of State\n    ORG National Intelligence\n    NORP American\n    MONEY billions and billions of dollars\n    NORP Americans\n    TIME tonight\n    ORG Congress\n    CARDINAL one\n    NORP American\n    GPE America\n    GPE the United States\n    NORP Islamic\n    ORG the Department of Justice\n    GPE Boston\n    GPE San Bernardino\n    ORG Pentagon\n    ORG the World Trade Center\n    GPE France\n    GPE Belgium\n    GPE Germany\n    GPE the United States\n    GPE America\n    ORG the Department of Defense\n    ORG ISIS\n    NORP Muslims\n    NORP Christians\n    NORP Muslim\n    GPE Iran\n    GPE the State of Israel\n    ORG Justice\n    GPE the United States Supreme Court\n    CARDINAL 20\n    LAW Constitution\n    PERSON Maureen Scalia\n    TIME tonight\n    PERSON Maureen\n    PERSON Antonin Scalia\n    NORP American\n    PERSON Neil Gorsuch\n    ORG the Court of Appeals\n    ORG Senate\n    TIME Tonight\n    CARDINAL Ninety-four million\n    NORP Americans\n    CARDINAL Over 43 million\n    CARDINAL over 43 million\n    NORP Americans\n    CARDINAL More than 1\n    CARDINAL 5\n    DATE 65 years\n    DATE the last 8 years\n    CARDINAL more than one-fourth\n    ORG NAFTA\n    CARDINAL 60,000\n    GPE China\n    ORG the World Trade Organization\n    DATE 2001\n    DATE last year\n    MONEY nearly $800 billion dollars\n    NORP American\n    NORP American\n    GPE the United States\n    NORP American\n    NORP American\n    GPE America\n    GPE America\n    NORP American\n    ORG Harley-Davidson\n    CARDINAL five\n    GPE U.S.A.\n    ORG the White House\n    PERCENT 100 percent\n    ORDINAL first\n    NORP Republican\n    PERSON Abraham Lincoln\n    ORG the American Government\n    ORG Lincoln\n    GPE America\n    CARDINAL millions\n    GPE Canada\n    GPE Australia\n    GPE America\n    ORG the National Academy of Sciences\n    NORP American\n    MONEY many billions of dollars\n    NORP Americans\n    ORG Nation\n    NORP American\n    NORP Republicans\n    NORP Democrats\n    DATE decades\n    NORP Republican\n    PERSON Dwight D. Eisenhower\n    ORG the Interstate Highway System\n    GPE America\n    MONEY approximately $6 trillion\n    LOC the Middle East\n    MONEY $6 trillion\n    CARDINAL three\n    ORG Congress\n    MONEY $1 trillion\n    GPE the United States\n    CARDINAL millions\n    CARDINAL two\n    NORP American\n    NORP American\n    TIME Tonight\n    ORG Congress\n    NORP American\n    GPE Arizona\n    PERCENT 116 percent\n    DATE last year\n    PERSON Matt Bevin\n    GPE Kentucky\n    ORG Obamacare\n    ORG State\n    GPE Kentucky\n    CARDINAL One-third\n    CARDINAL only one\n    NORP Americans\n    NORP Americans\n    NORP Democrats\n    NORP Republicans\n    ORG Congress\n    NORP Americans\n    ORG Obamacare\n    ORG Congress\n    NORP Americans\n    ORDINAL First\n    NORP Americans\n    NORP Americans\n    ORDINAL Secondly\n    NORP Americans\n    ORDINAL Thirdly\n    ORG Medicaid\n    ORDINAL Fourth\n    NORP Americans\n    ORG State\n    NORP Democrats\n    NORP Republicans\n    NORP American\n    NORP American\n    TIME this evening\n    DATE Today\n    EVENT Rare Disease Day\n    PERSON Megan Crowley\n    PERSON Megan\n    LOC Pompe\n    DATE 15 months old\n    ORG Megan\n    PERSON Megan\n    DATE Today\n    DATE 20 years old\n    FAC Notre Dame\n    PERSON Megan\n    ORG the Food and Drug Administration\n    PERSON Megan\n    ORG FDA\n    PERSON Megan\n    NORP American\n    CARDINAL millions\n    NORP African American\n    PERSON Latino\n    TIME tonight\n    PERSON Denisha Merriweather\n    PERSON Denisha\n    ORDINAL third\n    DATE Today\n    ORDINAL first\n    DATE Later this year\n    PERSON Denisha\n    DATE 2015\n    DATE single-year\n    DATE nearly half a century\n    GPE Chicago\n    CARDINAL more than 4,000\n    DATE last year\n    DATE this year\n    NORP Every American\n    ORG the Department of Homeland Security\n    NORP American\n    TIME tonight\n    CARDINAL four\n    NORP Americans\n    PERSON Jamiel Shaw\n    PERSON Susan Oliver\n    PERSON Jenna Oliver\n    PERSON Jessica Davis\n    PERSON Jamiel\n    DATE 17-year-old\n    PERSON Jamiel Shaw\n    TIME tonight\n    PERSON Jamiel\n    PERSON Susan Oliver\n    PERSON Jessica Davis\n    PERSON Danny Oliver\n    PERSON Michael Davis\n    GPE California\n    CARDINAL two\n    PERSON Susan\n    PERSON Jenna\n    PERSON Jenna\n    TIME tonight\n    PERSON Jenna\n    PERSON Susan\n    PERSON Jessica\n    GPE America\n    GPE the United States\n    ORG Congress\n    CARDINAL one\n    NORP American\n    GPE America\n    TIME tonight\n    PERSON Carryn Owens\n    ORG U.S. Navy Special Operator\n    PERSON William \"Ryan\n    PERSON Owens\n    PERSON Ryan\n    PERSON Mattis\n    PERSON Ryan\n    PERSON Ryan\n    WORK_OF_ART Bible\n    PERSON Ryan\n    PERSON Ryan\n    GPE America\n    NORP American\n    ORG NATO\n    CARDINAL two\n    ORG NATO\n    LOC the Middle East\n    LOC Pacific\n    GPE America\n    GPE the United States of America\n    GPE America\n    GPE America\n    GPE America\n    DATE today\n    DATE decades ago\n    DATE the 250th year\n    GPE America\n    ORDINAL 100th\n    DATE 1876\n    GPE Philadelphia\n    GPE America\n    PERSON Alexander Graham Bell\n    ORDINAL first\n    PERSON Remington\n    ORDINAL first\n    PERSON Thomas Edison\n    GPE America\n    ORDINAL 250th\n    NORP American\n    CARDINAL Millions\n    NORP Americans\n    GPE America\n    NORP Americans\n    CARDINAL one\n    CARDINAL one\n    NORP American\n    DATE 250 years\n    TIME tonight\n    NORP American\n    GPE America\n    NORP American\n    ORG Congress\n    TIME tonight\n    GPE America\n    GPE the United States\n\n\n### Bag of Words\n\nMany machine learning methods cannot use strings as features, we have to encode it using numbers.\n\nWe can easily do this using __Bag Of Words (BOW)__ technique and marvelous __sklearn__ library:\n\n\n```python\nfrom sklearn.feature_extraction.text import CountVectorizer\n\nvectorizer = CountVectorizer()\n\ncorpus = [\n     'Bag Of Words is based on counting',\n     'words occurences throughout multiple documents.',\n     'This is the third document.',\n     'As you can see most of the words occur only once.',\n     'This gives us a pretty sparse matrix, see below. Really, see below',\n]\n\nX = vectorizer.fit_transform(corpus)\nprint(X.toarray())\n```\n\n    [[0 1 1 0 0 1 0 0 0 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0]\n     [0 0 0 0 0 0 0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0]\n     [0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0]\n     [1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 1 0 1 1 0 0 1 0 1 0 0 0 0 1 1]\n     [0 0 0 2 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 1 2 1 0 0 1 0 1 0 0]]\n\n\nEach document is represented by the row. Values ranging from 0 to N represent whether and how many times the word occured in the document. You can see what word corresponds to which column by issuing get_feature_names() on vectorizer object.\n\n\n```python\nvectorizer.get_feature_names()\n```\n\n\n\n\n    ['as',\n     'bag',\n     'based',\n     'below',\n     'can',\n     'counting',\n     'document',\n     'documents',\n     'gives',\n     'is',\n     'matrix',\n     'most',\n     'multiple',\n     'occur',\n     'occurences',\n     'of',\n     'on',\n     'once',\n     'only',\n     'pretty',\n     'really',\n     'see',\n     'sparse',\n     'the',\n     'third',\n     'this',\n     'throughout',\n     'us',\n     'words',\n     'you']\n\n\n\nThis approach allows us to easily describe the whole corpora, but it lacks informations crucial for solving some tasks.\n\n### TF-IDF\n\nLook at word is. It is used in most documents many times, yet it does not tell us anything about them. Let's think about sentiment analysis: if words like great or awesome occur frequently in comparison with another documents it may suggest positive attitude.\n\nTF-IDF is one way to encode this information and I'll walk you through it step by step.\n\nFirst part of TF-IDF is, yes, you guessed it, TF, which means Term Frequency. It can be calculated as:\n\n\\begin{equation}\ntf_{ij}=\\frac{n_{ij}}{\\sum n_{ij}},\n\\end{equation}\nwhere $n_{ij}$ is the number of occurence of word $i$ in document $j$.\n\n\n```python\nimport numpy as np\n\ncorpus = [\n'Tom has cat',\n'Tom has fish',\n'Tom is polish',\n]\n\ndef tf(corpus):\n    vec = CountVectorizer()\n    bow_representation = vec.fit_transform(corpus)\n    words_per_corpus = bow_representation.sum(axis=1)\n    return np.divide(np.array(bow_representation.toarray()),np.array(words_per_corpus).reshape((5,))[:,None])\n\n```\n\nFor each document we count how many times it occurred (BoW implementaion) and divide by the count of all words in this document.\n\nNext part is IDF, which stands for Inverse Document Frequency:\n\n\\begin{equation}\nidf=\\log(\\frac{N}{df_{t}}),\n\\end{equation}\nwhere $N$ is the total number of documents and $df_{t}$ is number of documents containing $t$.\n\n\n```python\ndef idf(corpus):\n    document_count = len(corpus)\n    bow_representation = CountVectorizer().fit_transform(corpus)\n    return np.log(document_count / np.count_nonzero(bow_representation.toarray(), axis=0))\n```\n\nFirst we calculate number of documents in corpus (number of rows in our case). Next, for each word, we calculate documents containing said word at least once.\n\nTaking logarithm allows us to dampen the effect of idf. For example, the difference between term occuring in 40 out of 50 documents and 45 out of 50 documents will be smaller than difference between 1/50 and 5/50. This puts a bigger emphasis on rarely occuring terms as they are more informative.\n\nFinally, for the whole thing to work, we simply multiply both:\n\n\n```python\ndef tf_idf(corpus):\n    return tf(corpus) * idf(corpus)\n```\n\nLet's calculate it:\n\n\n```python\ncorpus = [\n     'Bag Of Words is based on counting',\n     'words occurences throughout multiple documents.',\n     'This is the third document.',\n     'As you can see most of the words occur only once.',\n     'This gives us a pretty sparse matrix, see below. Really, see below',\n]\n\ntfidf_result = tf_idf(corpus)\n\nprint(tfidf_result.shape)\n```\n\n    (5, 30)\n\n\nIn Jupyter it's easier to display results with pandas:\n\n\n```python\nimport pandas as pd\npd.DataFrame(tfidf_result).head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>0</th>\n      <th>1</th>\n      <th>2</th>\n      <th>3</th>\n      <th>4</th>\n      <th>5</th>\n      <th>6</th>\n      <th>7</th>\n      <th>8</th>\n      <th>9</th>\n      <th>...</th>\n      <th>20</th>\n      <th>21</th>\n      <th>22</th>\n      <th>23</th>\n      <th>24</th>\n      <th>25</th>\n      <th>26</th>\n      <th>27</th>\n      <th>28</th>\n      <th>29</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.000000</td>\n      <td>0.22992</td>\n      <td>0.22992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.22992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.130899</td>\n      <td>...</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.072975</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.000000</td>\n      <td>0.00000</td>\n      <td>0.00000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.00000</td>\n      <td>0.000000</td>\n      <td>0.321888</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>...</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.321888</td>\n      <td>0.000000</td>\n      <td>0.102165</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.000000</td>\n      <td>0.00000</td>\n      <td>0.00000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.00000</td>\n      <td>0.321888</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.183258</td>\n      <td>...</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.183258</td>\n      <td>0.321888</td>\n      <td>0.183258</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.146313</td>\n      <td>0.00000</td>\n      <td>0.00000</td>\n      <td>0.000000</td>\n      <td>0.146313</td>\n      <td>0.00000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>...</td>\n      <td>0.000000</td>\n      <td>0.083299</td>\n      <td>0.000000</td>\n      <td>0.083299</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.046439</td>\n      <td>0.146313</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.000000</td>\n      <td>0.00000</td>\n      <td>0.00000</td>\n      <td>0.292625</td>\n      <td>0.000000</td>\n      <td>0.00000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.146313</td>\n      <td>0.000000</td>\n      <td>...</td>\n      <td>0.146313</td>\n      <td>0.166598</td>\n      <td>0.146313</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.083299</td>\n      <td>0.000000</td>\n      <td>0.146313</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 30 columns</p>\n</div>\n\n\n\nThere are many versions of tf-idf, some use different smoothing, use additional logarithm for tf part and so on. Each transforms corpora a little differently, and appropriate should be used based on effect we would like to obtain.\n\n### Summary\nThis constitutes the first NLP-related part of our course and we have gathered some useful and interesting informations \n\n### References\n\n[1] Natural Language Processing with Python, Edward Loper, Ewan Klein, Steven Bird. O'Reilly 2009\n\n[2] Applied Text Analysis with Python, Tony Ojeda , Rebecca Bilbro , Benjamin Bengfort. O'Reilly 2018\n\n[3] Feature Engineering for Machine Learning, Amanda Casari , Alice Zheng. O'Reilly 2018\n", "meta": {"hexsha": "2c58af6bf14f8f3b3079a623f1c29dce986f8b6f", "size": 365972, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ML1/nlp/102_NLP_Text_Processing.ipynb", "max_stars_repo_name": "DevilWillReign/ML2022", "max_stars_repo_head_hexsha": "cb4cc692e9f0e178977fb5e1d272e581b30f998d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ML1/nlp/102_NLP_Text_Processing.ipynb", "max_issues_repo_name": "DevilWillReign/ML2022", "max_issues_repo_head_hexsha": "cb4cc692e9f0e178977fb5e1d272e581b30f998d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ML1/nlp/102_NLP_Text_Processing.ipynb", "max_forks_repo_name": "DevilWillReign/ML2022", "max_forks_repo_head_hexsha": "cb4cc692e9f0e178977fb5e1d272e581b30f998d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3842723609, "max_line_length": 19104, "alphanum_fraction": 0.5267943996, "converted": true, "num_tokens": 86360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.212068814316781, "lm_q2_score": 0.10818894737344459, "lm_q1q2_score": 0.022943501791667015}}
{"text": "```python\npip install qiskit\n```\n\n    Requirement already satisfied: qiskit in /home/dsmishler/anaconda3/lib/python3.8/site-packages (0.34.2)\n    Requirement already satisfied: qiskit-aer==0.10.3 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit) (0.10.3)\n    Requirement already satisfied: qiskit-terra==0.19.2 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit) (0.19.2)\n    Requirement already satisfied: qiskit-ibmq-provider==0.18.3 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit) (0.18.3)\n    Requirement already satisfied: qiskit-ignis==0.7.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit) (0.7.0)\n    Requirement already satisfied: numpy>=1.16.3 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-aer==0.10.3->qiskit) (1.22.3)\n    Requirement already satisfied: scipy>=1.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-aer==0.10.3->qiskit) (1.8.0)\n    Requirement already satisfied: urllib3>=1.21.1 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (1.26.4)\n    Requirement already satisfied: requests>=2.19 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (2.25.1)\n    Requirement already satisfied: requests-ntlm>=1.1.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (1.1.0)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (2.8.1)\n    Requirement already satisfied: websocket-client>=1.0.1 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (1.3.1)\n    Requirement already satisfied: setuptools>=40.1.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-ignis==0.7.0->qiskit) (52.0.0.post20210125)\n    Requirement already satisfied: retworkx>=0.8.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-ignis==0.7.0->qiskit) (0.11.0)\n    Requirement already satisfied: dill>=0.3 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-terra==0.19.2->qiskit) (0.3.4)\n    Requirement already satisfied: psutil>=5 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-terra==0.19.2->qiskit) (5.8.0)\n    Requirement already satisfied: symengine>=0.8 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-terra==0.19.2->qiskit) (0.9.2)\n    Requirement already satisfied: ply>=3.10 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-terra==0.19.2->qiskit) (3.11)\n    Requirement already satisfied: sympy>=1.3 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-terra==0.19.2->qiskit) (1.8)\n    Requirement already satisfied: stevedore>=3.0.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-terra==0.19.2->qiskit) (3.5.0)\n    Requirement already satisfied: tweedledum<2.0,>=1.1 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-terra==0.19.2->qiskit) (1.1.1)\n    Requirement already satisfied: python-constraint>=1.4 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-terra==0.19.2->qiskit) (1.4.0)\n    Requirement already satisfied: six>=1.5 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from python-dateutil>=2.8.0->qiskit-ibmq-provider==0.18.3->qiskit) (1.15.0)\n    Requirement already satisfied: idna<3,>=2.5 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit) (2.10)\n    Requirement already satisfied: chardet<5,>=3.0.2 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit) (4.0.0)\n    Requirement already satisfied: certifi>=2017.4.17 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit) (2020.12.5)\n    Requirement already satisfied: ntlm-auth>=1.0.2 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit) (1.5.0)\n    Requirement already satisfied: cryptography>=1.3 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit) (3.4.7)\n    Requirement already satisfied: cffi>=1.12 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit) (1.14.5)\n    Requirement already satisfied: pycparser in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit) (2.20)\n    Requirement already satisfied: pbr!=2.1.0,>=2.0.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from stevedore>=3.0.0->qiskit-terra==0.19.2->qiskit) (5.8.1)\n    Requirement already satisfied: mpmath>=0.19 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from sympy>=1.3->qiskit-terra==0.19.2->qiskit) (1.2.1)\n    Note: you may need to restart the kernel to use updated packages.\n\n\n\n```python\npip install pylatexenc\n```\n\n    Requirement already satisfied: pylatexenc in /home/dsmishler/anaconda3/lib/python3.8/site-packages (2.10)\n    Note: you may need to restart the kernel to use updated packages.\n\n\n\n```python\npip install pytket\n```\n\n    Requirement already satisfied: pytket in /home/dsmishler/anaconda3/lib/python3.8/site-packages (1.1.0)\n    Requirement already satisfied: types-pkg-resources in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from pytket) (0.1.3)\n    Requirement already satisfied: typing-extensions~=3.7 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from pytket) (3.7.4.3)\n    Requirement already satisfied: sympy~=1.6 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from pytket) (1.8)\n    Requirement already satisfied: networkx~=2.4 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from pytket) (2.5)\n    Requirement already satisfied: jinja2~=3.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from pytket) (3.1.1)\n    Requirement already satisfied: scipy<2.0,>=1.7.2 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from pytket) (1.8.0)\n    Requirement already satisfied: lark-parser~=0.7 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from pytket) (0.12.0)\n    Requirement already satisfied: graphviz~=0.14 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from pytket) (0.19.2)\n    Requirement already satisfied: numpy<2.0,>=1.21.4 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from pytket) (1.22.3)\n    Requirement already satisfied: MarkupSafe>=2.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from jinja2~=3.0->pytket) (2.1.1)\n    Requirement already satisfied: decorator>=4.3.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from networkx~=2.4->pytket) (5.0.6)\n    Requirement already satisfied: mpmath>=0.19 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from sympy~=1.6->pytket) (1.2.1)\n    Note: you may need to restart the kernel to use updated packages.\n\n\n\n```python\npip install pytket-qiskit\n```\n\n    Collecting pytket-qiskit\n      Downloading pytket_qiskit-0.24.0-py3-none-any.whl (36 kB)\n    Collecting qiskit~=0.36.0\n      Downloading qiskit-0.36.0.tar.gz (13 kB)\n    Requirement already satisfied: pytket~=1.1 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from pytket-qiskit) (1.1.0)\n    Requirement already satisfied: numpy<2.0,>=1.21.4 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from pytket~=1.1->pytket-qiskit) (1.22.3)\n    Requirement already satisfied: graphviz~=0.14 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from pytket~=1.1->pytket-qiskit) (0.19.2)\n    Requirement already satisfied: lark-parser~=0.7 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from pytket~=1.1->pytket-qiskit) (0.12.0)\n    Requirement already satisfied: sympy~=1.6 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from pytket~=1.1->pytket-qiskit) (1.8)\n    Requirement already satisfied: scipy<2.0,>=1.7.2 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from pytket~=1.1->pytket-qiskit) (1.8.0)\n    Requirement already satisfied: jinja2~=3.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from pytket~=1.1->pytket-qiskit) (3.1.1)\n    Requirement already satisfied: typing-extensions~=3.7 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from pytket~=1.1->pytket-qiskit) (3.7.4.3)\n    Requirement already satisfied: networkx~=2.4 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from pytket~=1.1->pytket-qiskit) (2.5)\n    Requirement already satisfied: types-pkg-resources in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from pytket~=1.1->pytket-qiskit) (0.1.3)\n    Requirement already satisfied: MarkupSafe>=2.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from jinja2~=3.0->pytket~=1.1->pytket-qiskit) (2.1.1)\n    Requirement already satisfied: decorator>=4.3.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from networkx~=2.4->pytket~=1.1->pytket-qiskit) (5.0.6)\n    Collecting qiskit-terra==0.20.0\n      Downloading qiskit_terra-0.20.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (6.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.5 MB 5.6 MB/s eta 0:00:01\n    \u001b[?25hCollecting qiskit-aer==0.10.4\n      Downloading qiskit_aer-0.10.4-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (18.0 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 18.0 MB 10.8 MB/s eta 0:00:01\n    \u001b[?25hCollecting qiskit-ibmq-provider==0.19.0\n      Downloading qiskit_ibmq_provider-0.19.0-py3-none-any.whl (240 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 240 kB 13.0 MB/s eta 0:00:01\n    \u001b[?25hRequirement already satisfied: qiskit-ignis==0.7.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit~=0.36.0->pytket-qiskit) (0.7.0)\n    Requirement already satisfied: urllib3>=1.21.1 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.19.0->qiskit~=0.36.0->pytket-qiskit) (1.26.4)\n    Requirement already satisfied: websocket-client>=1.0.1 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.19.0->qiskit~=0.36.0->pytket-qiskit) (1.3.1)\n    Collecting websockets>=10.0\n      Downloading websockets-10.2-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (110 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 110 kB 22.3 MB/s eta 0:00:01\n    \u001b[?25hRequirement already satisfied: requests>=2.19 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.19.0->qiskit~=0.36.0->pytket-qiskit) (2.25.1)\n    Requirement already satisfied: requests-ntlm>=1.1.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.19.0->qiskit~=0.36.0->pytket-qiskit) (1.1.0)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-ibmq-provider==0.19.0->qiskit~=0.36.0->pytket-qiskit) (2.8.1)\n    Requirement already satisfied: retworkx>=0.8.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-ignis==0.7.0->qiskit~=0.36.0->pytket-qiskit) (0.11.0)\n    Requirement already satisfied: setuptools>=40.1.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-ignis==0.7.0->qiskit~=0.36.0->pytket-qiskit) (52.0.0.post20210125)\n    Requirement already satisfied: psutil>=5 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-terra==0.20.0->qiskit~=0.36.0->pytket-qiskit) (5.8.0)\n    Requirement already satisfied: python-constraint>=1.4 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-terra==0.20.0->qiskit~=0.36.0->pytket-qiskit) (1.4.0)\n    Requirement already satisfied: symengine>=0.9 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-terra==0.20.0->qiskit~=0.36.0->pytket-qiskit) (0.9.2)\n    Requirement already satisfied: dill>=0.3 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-terra==0.20.0->qiskit~=0.36.0->pytket-qiskit) (0.3.4)\n    Requirement already satisfied: ply>=3.10 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-terra==0.20.0->qiskit~=0.36.0->pytket-qiskit) (3.11)\n    Requirement already satisfied: stevedore>=3.0.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-terra==0.20.0->qiskit~=0.36.0->pytket-qiskit) (3.5.0)\n    Requirement already satisfied: tweedledum<2.0,>=1.1 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from qiskit-terra==0.20.0->qiskit~=0.36.0->pytket-qiskit) (1.1.1)\n    Requirement already satisfied: six>=1.5 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from python-dateutil>=2.8.0->qiskit-ibmq-provider==0.19.0->qiskit~=0.36.0->pytket-qiskit) (1.15.0)\n    Requirement already satisfied: certifi>=2017.4.17 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from requests>=2.19->qiskit-ibmq-provider==0.19.0->qiskit~=0.36.0->pytket-qiskit) (2020.12.5)\n    Requirement already satisfied: chardet<5,>=3.0.2 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from requests>=2.19->qiskit-ibmq-provider==0.19.0->qiskit~=0.36.0->pytket-qiskit) (4.0.0)\n    Requirement already satisfied: idna<3,>=2.5 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from requests>=2.19->qiskit-ibmq-provider==0.19.0->qiskit~=0.36.0->pytket-qiskit) (2.10)\n    Requirement already satisfied: ntlm-auth>=1.0.2 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.19.0->qiskit~=0.36.0->pytket-qiskit) (1.5.0)\n    Requirement already satisfied: cryptography>=1.3 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.19.0->qiskit~=0.36.0->pytket-qiskit) (3.4.7)\n    Requirement already satisfied: cffi>=1.12 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.19.0->qiskit~=0.36.0->pytket-qiskit) (1.14.5)\n    Requirement already satisfied: pycparser in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.19.0->qiskit~=0.36.0->pytket-qiskit) (2.20)\n    Requirement already satisfied: pbr!=2.1.0,>=2.0.0 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from stevedore>=3.0.0->qiskit-terra==0.20.0->qiskit~=0.36.0->pytket-qiskit) (5.8.1)\n    Requirement already satisfied: mpmath>=0.19 in /home/dsmishler/anaconda3/lib/python3.8/site-packages (from sympy~=1.6->pytket~=1.1->pytket-qiskit) (1.2.1)\n    Building wheels for collected packages: qiskit\n      Building wheel for qiskit (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Created wheel for qiskit: filename=qiskit-0.36.0-py3-none-any.whl size=11846 sha256=434a4d073ccaa4408bab702af7d5a103ddbc7158f61cd924cb50a4f9e6092b76\n      Stored in directory: /home/dsmishler/.cache/pip/wheels/17/9a/77/2bcb247a27f566c157de1fb8d63603def70b7abdd36b10104c\n    Successfully built qiskit\n    Installing collected packages: websockets, qiskit-terra, qiskit-ibmq-provider, qiskit-aer, qiskit, pytket-qiskit\n      Attempting uninstall: qiskit-terra\n        Found existing installation: qiskit-terra 0.19.2\n        Uninstalling qiskit-terra-0.19.2:\n          Successfully uninstalled qiskit-terra-0.19.2\n      Attempting uninstall: qiskit-ibmq-provider\n        Found existing installation: qiskit-ibmq-provider 0.18.3\n        Uninstalling qiskit-ibmq-provider-0.18.3:\n          Successfully uninstalled qiskit-ibmq-provider-0.18.3\n      Attempting uninstall: qiskit-aer\n        Found existing installation: qiskit-aer 0.10.3\n        Uninstalling qiskit-aer-0.10.3:\n          Successfully uninstalled qiskit-aer-0.10.3\n      Attempting uninstall: qiskit\n        Found existing installation: qiskit 0.34.2\n        Uninstalling qiskit-0.34.2:\n          Successfully uninstalled qiskit-0.34.2\n    Successfully installed pytket-qiskit-0.24.0 qiskit-0.36.0 qiskit-aer-0.10.4 qiskit-ibmq-provider-0.19.0 qiskit-terra-0.20.0 websockets-10.2\n    Note: you may need to restart the kernel to use updated packages.\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "905822d1b1f529a33961ede749641c91f2019d82", "size": 18884, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "needed-installs.ipynb", "max_stars_repo_name": "DSMishler/Qiskit-clone-CS561", "max_stars_repo_head_hexsha": "6aff182e591588d157364e6e6a9f89efdab9ec20", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "needed-installs.ipynb", "max_issues_repo_name": "DSMishler/Qiskit-clone-CS561", "max_issues_repo_head_hexsha": "6aff182e591588d157364e6e6a9f89efdab9ec20", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "needed-installs.ipynb", "max_forks_repo_name": "DSMishler/Qiskit-clone-CS561", "max_forks_repo_head_hexsha": "6aff182e591588d157364e6e6a9f89efdab9ec20", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 80.0169491525, "max_line_length": 235, "alphanum_fraction": 0.6839652616, "converted": true, "num_tokens": 6032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1968262036430985, "lm_q2_score": 0.11596073047456816, "lm_q1q2_score": 0.022824110350989812}}
{"text": "# Installations\n\n\n```python\n!pip3 install gurobipy\n!pip3 install qiskit[visualization]\n# !pip3 install olsq\n!pip3 install anytree\n\n!pip3 install pytket\n!pip3 install pytket-qiskit\n```\n\n    Collecting gurobipy\n      Downloading gurobipy-9.1.2-cp37-cp37m-manylinux1_x86_64.whl (11.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 11.1 MB 5.3 MB/s \n    \u001b[?25hInstalling collected packages: gurobipy\n    Successfully installed gurobipy-9.1.2\n    Collecting qiskit[visualization]\n      Downloading qiskit-0.31.0.tar.gz (13 kB)\n    Collecting qiskit-terra==0.18.3\n      Downloading qiskit_terra-0.18.3-cp37-cp37m-manylinux2010_x86_64.whl (6.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.1 MB 5.2 MB/s \n    \u001b[?25hCollecting qiskit-aer==0.9.1\n      Downloading qiskit_aer-0.9.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (17.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 17.9 MB 115 kB/s \n    \u001b[?25hCollecting qiskit-ibmq-provider==0.17.0\n      Downloading qiskit_ibmq_provider-0.17.0-py3-none-any.whl (236 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 236 kB 74.2 MB/s \n    \u001b[?25hCollecting qiskit-ignis==0.6.0\n      Downloading qiskit_ignis-0.6.0-py3-none-any.whl (207 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 207 kB 73.0 MB/s \n    \u001b[?25hCollecting qiskit-aqua==0.9.5\n      Downloading qiskit_aqua-0.9.5-py3-none-any.whl (2.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.1 MB 77.3 MB/s \n    \u001b[?25hRequirement already satisfied: matplotlib>=2.1 in /usr/local/lib/python3.7/dist-packages (from qiskit[visualization]) (3.2.2)\n    Requirement already satisfied: ipywidgets>=7.3.0 in /usr/local/lib/python3.7/dist-packages (from qiskit[visualization]) (7.6.5)\n    Requirement already satisfied: pydot in /usr/local/lib/python3.7/dist-packages (from qiskit[visualization]) (1.3.0)\n    Requirement already satisfied: pillow>=4.2.1 in /usr/local/lib/python3.7/dist-packages (from qiskit[visualization]) (7.1.2)\n    Collecting pylatexenc>=1.4\n      Downloading pylatexenc-2.10.tar.gz (162 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 162 kB 76.1 MB/s \n    \u001b[?25hRequirement already satisfied: seaborn>=0.9.0 in /usr/local/lib/python3.7/dist-packages (from qiskit[visualization]) (0.11.2)\n    Requirement already satisfied: pygments>=2.4 in /usr/local/lib/python3.7/dist-packages (from qiskit[visualization]) (2.6.1)\n    Requirement already satisfied: scipy>=1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.9.1->qiskit[visualization]) (1.4.1)\n    Requirement already satisfied: numpy>=1.16.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.9.1->qiskit[visualization]) (1.19.5)\n    Collecting quandl\n      Downloading Quandl-3.6.2-py2.py3-none-any.whl (26 kB)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit[visualization]) (1.7.1)\n    Collecting docplex>=2.21.207\n      Downloading docplex-2.22.213.tar.gz (634 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 634 kB 65.2 MB/s \n    \u001b[?25hRequirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit[visualization]) (1.1.5)\n    Collecting dlx<=1.0.4\n      Downloading dlx-1.0.4.tar.gz (5.5 kB)\n    Requirement already satisfied: fastdtw<=0.3.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit[visualization]) (0.3.4)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit[visualization]) (57.4.0)\n    Collecting yfinance>=0.1.62\n      Downloading yfinance-0.1.64.tar.gz (26 kB)\n    Requirement already satisfied: h5py<3.3.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit[visualization]) (3.1.0)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit[visualization]) (5.4.8)\n    Requirement already satisfied: scikit-learn>=0.20.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit[visualization]) (0.22.2.post1)\n    Collecting retworkx>=0.8.0\n      Downloading retworkx-0.10.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.4 MB 54.4 MB/s \n    \u001b[?25hRequirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.17.0->qiskit[visualization]) (2.23.0)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.17.0->qiskit[visualization]) (2.8.2)\n    Collecting websocket-client>=1.0.1\n      Downloading websocket_client-1.2.1-py2.py3-none-any.whl (52 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 52 kB 1.5 MB/s \n    \u001b[?25hCollecting requests-ntlm>=1.1.0\n      Downloading requests_ntlm-1.1.0-py2.py3-none-any.whl (5.7 kB)\n    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.17.0->qiskit[visualization]) (1.24.3)\n    Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.18.3->qiskit[visualization]) (2.6.0)\n    Collecting tweedledum<2.0,>=1.1\n      Downloading tweedledum-1.1.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (943 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 943 kB 63.9 MB/s \n    \u001b[?25hCollecting fastjsonschema>=2.10\n      Downloading fastjsonschema-2.15.1-py3-none-any.whl (21 kB)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.18.3->qiskit[visualization]) (0.3.4)\n    Collecting ply>=3.10\n      Downloading ply-3.11-py2.py3-none-any.whl (49 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 49 kB 6.7 MB/s \n    \u001b[?25hCollecting symengine>0.7\n      Downloading symengine-0.8.1-cp37-cp37m-manylinux2010_x86_64.whl (38.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 38.2 MB 25 kB/s \n    \u001b[?25hCollecting python-constraint>=1.4\n      Downloading python-constraint-1.4.0.tar.bz2 (18 kB)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from docplex>=2.21.207->qiskit-aqua==0.9.5->qiskit[visualization]) (1.15.0)\n    Requirement already satisfied: cached-property in /usr/local/lib/python3.7/dist-packages (from h5py<3.3.0->qiskit-aqua==0.9.5->qiskit[visualization]) (1.5.2)\n    Requirement already satisfied: traitlets>=4.3.1 in /usr/local/lib/python3.7/dist-packages (from ipywidgets>=7.3.0->qiskit[visualization]) (5.1.0)\n    Requirement already satisfied: ipykernel>=4.5.1 in /usr/local/lib/python3.7/dist-packages (from ipywidgets>=7.3.0->qiskit[visualization]) (4.10.1)\n    Requirement already satisfied: ipython-genutils~=0.2.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets>=7.3.0->qiskit[visualization]) (0.2.0)\n    Requirement already satisfied: ipython>=4.0.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets>=7.3.0->qiskit[visualization]) (5.5.0)\n    Requirement already satisfied: widgetsnbextension~=3.5.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets>=7.3.0->qiskit[visualization]) (3.5.1)\n    Requirement already satisfied: nbformat>=4.2.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets>=7.3.0->qiskit[visualization]) (5.1.3)\n    Requirement already satisfied: jupyterlab-widgets>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets>=7.3.0->qiskit[visualization]) (1.0.2)\n    Requirement already satisfied: tornado>=4.0 in /usr/local/lib/python3.7/dist-packages (from ipykernel>=4.5.1->ipywidgets>=7.3.0->qiskit[visualization]) (5.1.1)\n    Requirement already satisfied: jupyter-client in /usr/local/lib/python3.7/dist-packages (from ipykernel>=4.5.1->ipywidgets>=7.3.0->qiskit[visualization]) (5.3.5)\n    Requirement already satisfied: pickleshare in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.7.5)\n    Requirement already satisfied: pexpect in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[visualization]) (4.8.0)\n    Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[visualization]) (1.0.18)\n    Requirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.8.1)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[visualization]) (4.4.2)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.1->qiskit[visualization]) (2.4.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.1->qiskit[visualization]) (1.3.2)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.1->qiskit[visualization]) (0.10.0)\n    Requirement already satisfied: jupyter-core in /usr/local/lib/python3.7/dist-packages (from nbformat>=4.2.0->ipywidgets>=7.3.0->qiskit[visualization]) (4.8.1)\n    Requirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.2.5)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.17.0->qiskit[visualization]) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.17.0->qiskit[visualization]) (2021.5.30)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.17.0->qiskit[visualization]) (3.0.4)\n    Collecting ntlm-auth>=1.0.2\n      Downloading ntlm_auth-1.5.0-py2.py3-none-any.whl (29 kB)\n    Collecting cryptography>=1.3\n      Downloading cryptography-35.0.0-cp36-abi3-manylinux_2_24_x86_64.whl (3.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.5 MB 50.2 MB/s \n    \u001b[?25hRequirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.17.0->qiskit[visualization]) (1.14.6)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.17.0->qiskit[visualization]) (2.20)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.9.5->qiskit[visualization]) (1.0.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->qiskit-aqua==0.9.5->qiskit[visualization]) (2018.9)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-aqua==0.9.5->qiskit[visualization]) (1.2.1)\n    Requirement already satisfied: notebook>=4.4.1 in /usr/local/lib/python3.7/dist-packages (from widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (5.3.1)\n    Requirement already satisfied: jinja2 in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (2.11.3)\n    Requirement already satisfied: Send2Trash in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (1.8.0)\n    Requirement already satisfied: nbconvert in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (5.6.1)\n    Requirement already satisfied: terminado>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.12.1)\n    Requirement already satisfied: pyzmq>=13 in /usr/local/lib/python3.7/dist-packages (from jupyter-client->ipykernel>=4.5.1->ipywidgets>=7.3.0->qiskit[visualization]) (22.3.0)\n    Requirement already satisfied: ptyprocess in /usr/local/lib/python3.7/dist-packages (from terminado>=0.8.1->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.7.0)\n    Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance>=0.1.62->qiskit-aqua==0.9.5->qiskit[visualization]) (0.0.9)\n    Collecting lxml>=4.5.1\n      Downloading lxml-4.6.4-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl (6.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.3 MB 29.8 MB/s \n    \u001b[?25hRequirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (2.0.1)\n    Requirement already satisfied: mistune<2,>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.8.4)\n    Requirement already satisfied: bleach in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (4.1.0)\n    Requirement already satisfied: defusedxml in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.7.1)\n    Requirement already satisfied: pandocfilters>=1.4.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (1.5.0)\n    Requirement already satisfied: entrypoints>=0.2.2 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.3)\n    Requirement already satisfied: testpath in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.5.0)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (21.0)\n    Requirement already satisfied: webencodings in /usr/local/lib/python3.7/dist-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[visualization]) (0.5.1)\n    Collecting inflection>=0.3.1\n      Downloading inflection-0.5.1-py2.py3-none-any.whl (9.5 kB)\n    Requirement already satisfied: more-itertools in /usr/local/lib/python3.7/dist-packages (from quandl->qiskit-aqua==0.9.5->qiskit[visualization]) (8.10.0)\n    Building wheels for collected packages: qiskit, dlx, docplex, pylatexenc, python-constraint, yfinance\n      Building wheel for qiskit (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for qiskit: filename=qiskit-0.31.0-py3-none-any.whl size=11728 sha256=a475b45dbd136b3ba755c4b8b66be349bdbb541034f5b12c617e7b29f7c3f0bf\n      Stored in directory: /root/.cache/pip/wheels/29/dd/b2/1fe1a9ac92aaf75b267d893ae27329ea229f292a293017afc7\n      Building wheel for dlx (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for dlx: filename=dlx-1.0.4-py3-none-any.whl size=5719 sha256=9b51ed3c173d154977a00a70425fd95defa5985c314f32945d4842108cc63e4c\n      Stored in directory: /root/.cache/pip/wheels/78/55/c8/dc61e772445a566b7608a476d151e9dcaf4e092b01b0c4bc3c\n      Building wheel for docplex (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for docplex: filename=docplex-2.22.213-py3-none-any.whl size=696881 sha256=9831ed8fd75aa3fc72e8185ce43bb246031a839ac038ccd3bdb86201b8b9929a\n      Stored in directory: /root/.cache/pip/wheels/90/69/6b/1375c68a5b7ff94c40263b151c86f58bd72200bf0c465b5ba3\n      Building wheel for pylatexenc (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pylatexenc: filename=pylatexenc-2.10-py3-none-any.whl size=136833 sha256=c6543b6838a744960cb9a8f8a3ea73456bc46114ebd5e4c6569524a23c7ce22d\n      Stored in directory: /root/.cache/pip/wheels/f1/8a/f5/33ee79d4473eb201b519fa40f989b842e373237395a3421f52\n      Building wheel for python-constraint (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for python-constraint: filename=python_constraint-1.4.0-py2.py3-none-any.whl size=24081 sha256=81d3fe7d5fb16e91e67b2f2229788e75ac7c9c364d504e6829a1dd1ef69226c2\n      Stored in directory: /root/.cache/pip/wheels/07/27/db/1222c80eb1e431f3d2199c12569cb1cac60f562a451fe30479\n      Building wheel for yfinance (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for yfinance: filename=yfinance-0.1.64-py2.py3-none-any.whl size=24109 sha256=cb24c08872be528360b19040c4cfbe0f3800a1e88136e216178cbc9069b08367\n      Stored in directory: /root/.cache/pip/wheels/86/fe/9b/a4d3d78796b699e37065e5b6c27b75cff448ddb8b24943c288\n    Successfully built qiskit dlx docplex pylatexenc python-constraint yfinance\n    Installing collected packages: tweedledum, symengine, retworkx, python-constraint, ply, fastjsonschema, qiskit-terra, ntlm-auth, lxml, inflection, cryptography, yfinance, websocket-client, requests-ntlm, quandl, qiskit-ignis, docplex, dlx, qiskit-ibmq-provider, qiskit-aqua, qiskit-aer, qiskit, pylatexenc\n      Attempting uninstall: lxml\n        Found existing installation: lxml 4.2.6\n        Uninstalling lxml-4.2.6:\n          Successfully uninstalled lxml-4.2.6\n    Successfully installed cryptography-35.0.0 dlx-1.0.4 docplex-2.22.213 fastjsonschema-2.15.1 inflection-0.5.1 lxml-4.6.4 ntlm-auth-1.5.0 ply-3.11 pylatexenc-2.10 python-constraint-1.4.0 qiskit-0.31.0 qiskit-aer-0.9.1 qiskit-aqua-0.9.5 qiskit-ibmq-provider-0.17.0 qiskit-ignis-0.6.0 qiskit-terra-0.18.3 quandl-3.6.2 requests-ntlm-1.1.0 retworkx-0.10.2 symengine-0.8.1 tweedledum-1.1.1 websocket-client-1.2.1 yfinance-0.1.64\n    Collecting anytree\n      Downloading anytree-2.8.0-py2.py3-none-any.whl (41 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 41 kB 349 kB/s \n    \u001b[?25hRequirement already satisfied: six>=1.9.0 in /usr/local/lib/python3.7/dist-packages (from anytree) (1.15.0)\n    Installing collected packages: anytree\n    Successfully installed anytree-2.8.0\n    Collecting pytket\n      Downloading pytket-0.16.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (7.0 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 7.0 MB 4.5 MB/s \n    \u001b[?25hCollecting lark-parser~=0.7\n      Downloading lark_parser-0.12.0-py2.py3-none-any.whl (103 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 103 kB 73.6 MB/s \n    \u001b[?25hRequirement already satisfied: jinja2~=2.11 in /usr/local/lib/python3.7/dist-packages (from pytket) (2.11.3)\n    Requirement already satisfied: typing-extensions~=3.7 in /usr/local/lib/python3.7/dist-packages (from pytket) (3.7.4.3)\n    Requirement already satisfied: numpy~=1.19 in /usr/local/lib/python3.7/dist-packages (from pytket) (1.19.5)\n    Collecting types-Jinja2\n      Downloading types_Jinja2-2.11.8-py3-none-any.whl (18 kB)\n    Requirement already satisfied: scipy~=1.2 in /usr/local/lib/python3.7/dist-packages (from pytket) (1.4.1)\n    Requirement already satisfied: networkx~=2.4 in /usr/local/lib/python3.7/dist-packages (from pytket) (2.6.3)\n    Collecting graphviz~=0.14\n      Downloading graphviz-0.18-py3-none-any.whl (38 kB)\n    Collecting types-pkg-resources\n      Downloading types_pkg_resources-0.1.3-py2.py3-none-any.whl (4.8 kB)\n    Requirement already satisfied: sympy~=1.6 in /usr/local/lib/python3.7/dist-packages (from pytket) (1.7.1)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2~=2.11->pytket) (2.0.1)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy~=1.6->pytket) (1.2.1)\n    Collecting types-MarkupSafe\n      Downloading types_MarkupSafe-1.1.8-py3-none-any.whl (4.0 kB)\n    Installing collected packages: types-MarkupSafe, types-pkg-resources, types-Jinja2, lark-parser, graphviz, pytket\n      Attempting uninstall: graphviz\n        Found existing installation: graphviz 0.10.1\n        Uninstalling graphviz-0.10.1:\n          Successfully uninstalled graphviz-0.10.1\n    Successfully installed graphviz-0.18 lark-parser-0.12.0 pytket-0.16.0 types-Jinja2-2.11.8 types-MarkupSafe-1.1.8 types-pkg-resources-0.1.3\n    Collecting pytket-qiskit\n      Downloading pytket-qiskit-0.19.0.tar.gz (28 kB)\n    Requirement already satisfied: pytket~=0.16.0 in /usr/local/lib/python3.7/dist-packages (from pytket-qiskit) (0.16.0)\n    Requirement already satisfied: qiskit~=0.31.0 in /usr/local/lib/python3.7/dist-packages (from pytket-qiskit) (0.31.0)\n    Requirement already satisfied: lark-parser~=0.7 in /usr/local/lib/python3.7/dist-packages (from pytket~=0.16.0->pytket-qiskit) (0.12.0)\n    Requirement already satisfied: types-pkg-resources in /usr/local/lib/python3.7/dist-packages (from pytket~=0.16.0->pytket-qiskit) (0.1.3)\n    Requirement already satisfied: types-Jinja2 in /usr/local/lib/python3.7/dist-packages (from pytket~=0.16.0->pytket-qiskit) (2.11.8)\n    Requirement already satisfied: typing-extensions~=3.7 in /usr/local/lib/python3.7/dist-packages (from pytket~=0.16.0->pytket-qiskit) (3.7.4.3)\n    Requirement already satisfied: networkx~=2.4 in /usr/local/lib/python3.7/dist-packages (from pytket~=0.16.0->pytket-qiskit) (2.6.3)\n    Requirement already satisfied: jinja2~=2.11 in /usr/local/lib/python3.7/dist-packages (from pytket~=0.16.0->pytket-qiskit) (2.11.3)\n    Requirement already satisfied: numpy~=1.19 in /usr/local/lib/python3.7/dist-packages (from pytket~=0.16.0->pytket-qiskit) (1.19.5)\n    Requirement already satisfied: graphviz~=0.14 in /usr/local/lib/python3.7/dist-packages (from pytket~=0.16.0->pytket-qiskit) (0.18)\n    Requirement already satisfied: scipy~=1.2 in /usr/local/lib/python3.7/dist-packages (from pytket~=0.16.0->pytket-qiskit) (1.4.1)\n    Requirement already satisfied: sympy~=1.6 in /usr/local/lib/python3.7/dist-packages (from pytket~=0.16.0->pytket-qiskit) (1.7.1)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2~=2.11->pytket~=0.16.0->pytket-qiskit) (2.0.1)\n    Requirement already satisfied: qiskit-ibmq-provider==0.17.0 in /usr/local/lib/python3.7/dist-packages (from qiskit~=0.31.0->pytket-qiskit) (0.17.0)\n    Requirement already satisfied: qiskit-aer==0.9.1 in /usr/local/lib/python3.7/dist-packages (from qiskit~=0.31.0->pytket-qiskit) (0.9.1)\n    Requirement already satisfied: qiskit-aqua==0.9.5 in /usr/local/lib/python3.7/dist-packages (from qiskit~=0.31.0->pytket-qiskit) (0.9.5)\n    Requirement already satisfied: qiskit-ignis==0.6.0 in /usr/local/lib/python3.7/dist-packages (from qiskit~=0.31.0->pytket-qiskit) (0.6.0)\n    Requirement already satisfied: qiskit-terra==0.18.3 in /usr/local/lib/python3.7/dist-packages (from qiskit~=0.31.0->pytket-qiskit) (0.18.3)\n    Requirement already satisfied: h5py<3.3.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit~=0.31.0->pytket-qiskit) (3.1.0)\n    Requirement already satisfied: quandl in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit~=0.31.0->pytket-qiskit) (3.6.2)\n    Requirement already satisfied: dlx<=1.0.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit~=0.31.0->pytket-qiskit) (1.0.4)\n    Requirement already satisfied: docplex>=2.21.207 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit~=0.31.0->pytket-qiskit) (2.22.213)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit~=0.31.0->pytket-qiskit) (57.4.0)\n    Requirement already satisfied: retworkx>=0.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit~=0.31.0->pytket-qiskit) (0.10.2)\n    Requirement already satisfied: fastdtw<=0.3.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit~=0.31.0->pytket-qiskit) (0.3.4)\n    Requirement already satisfied: scikit-learn>=0.20.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit~=0.31.0->pytket-qiskit) (0.22.2.post1)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit~=0.31.0->pytket-qiskit) (1.1.5)\n    Requirement already satisfied: yfinance>=0.1.62 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit~=0.31.0->pytket-qiskit) (0.1.64)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.5->qiskit~=0.31.0->pytket-qiskit) (5.4.8)\n    Requirement already satisfied: requests-ntlm>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.17.0->qiskit~=0.31.0->pytket-qiskit) (1.1.0)\n    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.17.0->qiskit~=0.31.0->pytket-qiskit) (2.23.0)\n    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.17.0->qiskit~=0.31.0->pytket-qiskit) (1.24.3)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.17.0->qiskit~=0.31.0->pytket-qiskit) (2.8.2)\n    Requirement already satisfied: websocket-client>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.17.0->qiskit~=0.31.0->pytket-qiskit) (1.2.1)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.18.3->qiskit~=0.31.0->pytket-qiskit) (0.3.4)\n    Requirement already satisfied: fastjsonschema>=2.10 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.18.3->qiskit~=0.31.0->pytket-qiskit) (2.15.1)\n    Requirement already satisfied: ply>=3.10 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.18.3->qiskit~=0.31.0->pytket-qiskit) (3.11)\n    Requirement already satisfied: python-constraint>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.18.3->qiskit~=0.31.0->pytket-qiskit) (1.4.0)\n    Requirement already satisfied: symengine>0.7 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.18.3->qiskit~=0.31.0->pytket-qiskit) (0.8.1)\n    Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.18.3->qiskit~=0.31.0->pytket-qiskit) (2.6.0)\n    Requirement already satisfied: tweedledum<2.0,>=1.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.18.3->qiskit~=0.31.0->pytket-qiskit) (1.1.1)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from docplex>=2.21.207->qiskit-aqua==0.9.5->qiskit~=0.31.0->pytket-qiskit) (1.15.0)\n    Requirement already satisfied: cached-property in /usr/local/lib/python3.7/dist-packages (from h5py<3.3.0->qiskit-aqua==0.9.5->qiskit~=0.31.0->pytket-qiskit) (1.5.2)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.17.0->qiskit~=0.31.0->pytket-qiskit) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.17.0->qiskit~=0.31.0->pytket-qiskit) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.17.0->qiskit~=0.31.0->pytket-qiskit) (2021.5.30)\n    Requirement already satisfied: cryptography>=1.3 in /usr/local/lib/python3.7/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.17.0->qiskit~=0.31.0->pytket-qiskit) (35.0.0)\n    Requirement already satisfied: ntlm-auth>=1.0.2 in /usr/local/lib/python3.7/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.17.0->qiskit~=0.31.0->pytket-qiskit) (1.5.0)\n    Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.17.0->qiskit~=0.31.0->pytket-qiskit) (1.14.6)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.17.0->qiskit~=0.31.0->pytket-qiskit) (2.20)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.9.5->qiskit~=0.31.0->pytket-qiskit) (1.0.1)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy~=1.6->pytket~=0.16.0->pytket-qiskit) (1.2.1)\n    Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance>=0.1.62->qiskit-aqua==0.9.5->qiskit~=0.31.0->pytket-qiskit) (0.0.9)\n    Requirement already satisfied: lxml>=4.5.1 in /usr/local/lib/python3.7/dist-packages (from yfinance>=0.1.62->qiskit-aqua==0.9.5->qiskit~=0.31.0->pytket-qiskit) (4.6.4)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->qiskit-aqua==0.9.5->qiskit~=0.31.0->pytket-qiskit) (2018.9)\n    Requirement already satisfied: more-itertools in /usr/local/lib/python3.7/dist-packages (from quandl->qiskit-aqua==0.9.5->qiskit~=0.31.0->pytket-qiskit) (8.10.0)\n    Requirement already satisfied: inflection>=0.3.1 in /usr/local/lib/python3.7/dist-packages (from quandl->qiskit-aqua==0.9.5->qiskit~=0.31.0->pytket-qiskit) (0.5.1)\n    Requirement already satisfied: types-MarkupSafe in /usr/local/lib/python3.7/dist-packages (from types-Jinja2->pytket~=0.16.0->pytket-qiskit) (1.1.8)\n    Building wheels for collected packages: pytket-qiskit\n      Building wheel for pytket-qiskit (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pytket-qiskit: filename=pytket_qiskit-0.19.0-py3-none-any.whl size=36757 sha256=3818eb69c084e4b59b802fc953a78679c9500d0309bff7eb44570e7f621a56a4\n      Stored in directory: /root/.cache/pip/wheels/85/11/b5/65856b5477493ac10f006f8acd33296168bfbddba4a9b99587\n    Successfully built pytket-qiskit\n    Installing collected packages: pytket-qiskit\n    Successfully installed pytket-qiskit-0.19.0\n\n\n\n```python\n!git clone https://github.com/weiT1993/qiskit_helper_functions\n# !cd qiskit_helper_functions && git checkout e046beac78563e9d75abcfde629565d149085983\n!cp -r qiskit_helper_functions/* ./ && python3 setup.py install\n```\n\n    Cloning into 'qiskit_helper_functions'...\n    remote: Enumerating objects: 403, done.\u001b[K\n    remote: Counting objects: 100% (403/403), done.\u001b[K\n    remote: Compressing objects: 100% (267/267), done.\u001b[K\n    remote: Total 403 (delta 247), reused 276 (delta 120), pack-reused 0\u001b[K\n    Receiving objects: 100% (403/403), 73.60 KiB | 5.26 MiB/s, done.\n    Resolving deltas: 100% (247/247), done.\n    running install\n    running bdist_egg\n    running egg_info\n    writing qiskit_helper_functions.egg-info/PKG-INFO\n    writing dependency_links to qiskit_helper_functions.egg-info/dependency_links.txt\n    writing top-level names to qiskit_helper_functions.egg-info/top_level.txt\n    reading manifest file 'qiskit_helper_functions.egg-info/SOURCES.txt'\n    adding license file 'LICENSE'\n    writing manifest file 'qiskit_helper_functions.egg-info/SOURCES.txt'\n    installing library code to build/bdist.linux-x86_64/egg\n    running install_lib\n    running build_py\n    copying qiskit_helper_functions/setup.py -> build/lib/qiskit_helper_functions\n    creating build/lib/qiskit_helper_functions/qiskit_helper_functions\n    copying qiskit_helper_functions/qiskit_helper_functions/non_ibmq_functions.py -> build/lib/qiskit_helper_functions/qiskit_helper_functions\n    copying qiskit_helper_functions/qiskit_helper_functions/schedule.py -> build/lib/qiskit_helper_functions/qiskit_helper_functions\n    copying qiskit_helper_functions/qiskit_helper_functions/__init__.py -> build/lib/qiskit_helper_functions/qiskit_helper_functions\n    copying qiskit_helper_functions/qiskit_helper_functions/ibmq_functions.py -> build/lib/qiskit_helper_functions/qiskit_helper_functions\n    copying qiskit_helper_functions/qiskit_helper_functions/conversions.py -> build/lib/qiskit_helper_functions/qiskit_helper_functions\n    copying qiskit_helper_functions/qiskit_helper_functions/metrics.py -> build/lib/qiskit_helper_functions/qiskit_helper_functions\n    creating build/lib/qiskit_helper_functions/qcg\n    copying qiskit_helper_functions/qcg/__init__.py -> build/lib/qiskit_helper_functions/qcg\n    copying qiskit_helper_functions/qcg/generators.py -> build/lib/qiskit_helper_functions/qcg\n    creating build/lib/qiskit_helper_functions/qcg/QAOA\n    copying qiskit_helper_functions/qcg/QAOA/__init__.py -> build/lib/qiskit_helper_functions/qcg/QAOA\n    copying qiskit_helper_functions/qcg/QAOA/hw_efficient_ansatz.py -> build/lib/qiskit_helper_functions/qcg/QAOA\n    creating build/lib/qiskit_helper_functions/qcg/Dynamics\n    copying qiskit_helper_functions/qcg/Dynamics/__init__.py -> build/lib/qiskit_helper_functions/qcg/Dynamics\n    copying qiskit_helper_functions/qcg/Dynamics/quantum_dynamics.py -> build/lib/qiskit_helper_functions/qcg/Dynamics\n    creating build/lib/qiskit_helper_functions/qcg/VQE\n    copying qiskit_helper_functions/qcg/VQE/__init__.py -> build/lib/qiskit_helper_functions/qcg/VQE\n    copying qiskit_helper_functions/qcg/VQE/uccsd_ansatz.py -> build/lib/qiskit_helper_functions/qcg/VQE\n    creating build/lib/qiskit_helper_functions/qcg/BernsteinVazirani\n    copying qiskit_helper_functions/qcg/BernsteinVazirani/bernstein_vazirani.py -> build/lib/qiskit_helper_functions/qcg/BernsteinVazirani\n    copying qiskit_helper_functions/qcg/BernsteinVazirani/__init__.py -> build/lib/qiskit_helper_functions/qcg/BernsteinVazirani\n    creating build/lib/qiskit_helper_functions/qcg/QFT\n    copying qiskit_helper_functions/qcg/QFT/qft_circ.py -> build/lib/qiskit_helper_functions/qcg/QFT\n    copying qiskit_helper_functions/qcg/QFT/__init__.py -> build/lib/qiskit_helper_functions/qcg/QFT\n    creating build/lib/qiskit_helper_functions/qcg/Supremacy\n    copying qiskit_helper_functions/qcg/Supremacy/Qbit_Sycamore.py -> build/lib/qiskit_helper_functions/qcg/Supremacy\n    copying qiskit_helper_functions/qcg/Supremacy/cz_layer_generation.py -> build/lib/qiskit_helper_functions/qcg/Supremacy\n    copying qiskit_helper_functions/qcg/Supremacy/ABCD_layer_generation.py -> build/lib/qiskit_helper_functions/qcg/Supremacy\n    copying qiskit_helper_functions/qcg/Supremacy/__init__.py -> build/lib/qiskit_helper_functions/qcg/Supremacy\n    copying qiskit_helper_functions/qcg/Supremacy/Qbit_original.py -> build/lib/qiskit_helper_functions/qcg/Supremacy\n    copying qiskit_helper_functions/qcg/Supremacy/Qgrid_Sycamore.py -> build/lib/qiskit_helper_functions/qcg/Supremacy\n    copying qiskit_helper_functions/qcg/Supremacy/Qgrid_original.py -> build/lib/qiskit_helper_functions/qcg/Supremacy\n    creating build/lib/qiskit_helper_functions/qcg/QWalk\n    copying qiskit_helper_functions/qcg/QWalk/quantum_walk.py -> build/lib/qiskit_helper_functions/qcg/QWalk\n    copying qiskit_helper_functions/qcg/QWalk/__init__.py -> build/lib/qiskit_helper_functions/qcg/QWalk\n    creating build/lib/qiskit_helper_functions/qcg/Arithmetic\n    copying qiskit_helper_functions/qcg/Arithmetic/ripple_carry_adder.py -> build/lib/qiskit_helper_functions/qcg/Arithmetic\n    copying qiskit_helper_functions/qcg/Arithmetic/__init__.py -> build/lib/qiskit_helper_functions/qcg/Arithmetic\n    creating build/lib/qiskit_helper_functions/qcg/utils\n    copying qiskit_helper_functions/qcg/utils/__init__.py -> build/lib/qiskit_helper_functions/qcg/utils\n    copying qiskit_helper_functions/qcg/utils/testhwea.py -> build/lib/qiskit_helper_functions/qcg/utils\n    creating build/bdist.linux-x86_64\n    creating build/bdist.linux-x86_64/egg\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/non_ibmq_functions.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/schedule.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/qiskit_helper_functions/non_ibmq_functions.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/qiskit_helper_functions/schedule.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/qiskit_helper_functions/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/qiskit_helper_functions/ibmq_functions.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/qiskit_helper_functions/conversions.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/qiskit_helper_functions/metrics.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/setup.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QAOA\n    copying build/lib/qiskit_helper_functions/qcg/QAOA/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QAOA\n    copying build/lib/qiskit_helper_functions/qcg/QAOA/hw_efficient_ansatz.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QAOA\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Dynamics\n    copying build/lib/qiskit_helper_functions/qcg/Dynamics/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Dynamics\n    copying build/lib/qiskit_helper_functions/qcg/Dynamics/quantum_dynamics.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Dynamics\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/VQE\n    copying build/lib/qiskit_helper_functions/qcg/VQE/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/VQE\n    copying build/lib/qiskit_helper_functions/qcg/VQE/uccsd_ansatz.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/VQE\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/BernsteinVazirani\n    copying build/lib/qiskit_helper_functions/qcg/BernsteinVazirani/bernstein_vazirani.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/BernsteinVazirani\n    copying build/lib/qiskit_helper_functions/qcg/BernsteinVazirani/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/BernsteinVazirani\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QFT\n    copying build/lib/qiskit_helper_functions/qcg/QFT/qft_circ.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QFT\n    copying build/lib/qiskit_helper_functions/qcg/QFT/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QFT\n    copying build/lib/qiskit_helper_functions/qcg/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy\n    copying build/lib/qiskit_helper_functions/qcg/Supremacy/Qbit_Sycamore.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy\n    copying build/lib/qiskit_helper_functions/qcg/Supremacy/cz_layer_generation.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy\n    copying build/lib/qiskit_helper_functions/qcg/Supremacy/ABCD_layer_generation.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy\n    copying build/lib/qiskit_helper_functions/qcg/Supremacy/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy\n    copying build/lib/qiskit_helper_functions/qcg/Supremacy/Qbit_original.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy\n    copying build/lib/qiskit_helper_functions/qcg/Supremacy/Qgrid_Sycamore.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy\n    copying build/lib/qiskit_helper_functions/qcg/Supremacy/Qgrid_original.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QWalk\n    copying build/lib/qiskit_helper_functions/qcg/QWalk/quantum_walk.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QWalk\n    copying build/lib/qiskit_helper_functions/qcg/QWalk/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QWalk\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Arithmetic\n    copying build/lib/qiskit_helper_functions/qcg/Arithmetic/ripple_carry_adder.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Arithmetic\n    copying build/lib/qiskit_helper_functions/qcg/Arithmetic/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Arithmetic\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/utils\n    copying build/lib/qiskit_helper_functions/qcg/utils/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/utils\n    copying build/lib/qiskit_helper_functions/qcg/utils/testhwea.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/utils\n    copying build/lib/qiskit_helper_functions/qcg/generators.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg\n    copying build/lib/qiskit_helper_functions/ibmq_functions.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/conversions.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/metrics.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions\n    creating build/bdist.linux-x86_64/egg/qcg\n    creating build/bdist.linux-x86_64/egg/qcg/QAOA\n    copying build/lib/qcg/QAOA/__init__.py -> build/bdist.linux-x86_64/egg/qcg/QAOA\n    copying build/lib/qcg/QAOA/hw_efficient_ansatz.py -> build/bdist.linux-x86_64/egg/qcg/QAOA\n    creating build/bdist.linux-x86_64/egg/qcg/Dynamics\n    copying build/lib/qcg/Dynamics/__init__.py -> build/bdist.linux-x86_64/egg/qcg/Dynamics\n    copying build/lib/qcg/Dynamics/quantum_dynamics.py -> build/bdist.linux-x86_64/egg/qcg/Dynamics\n    creating build/bdist.linux-x86_64/egg/qcg/VQE\n    copying build/lib/qcg/VQE/__init__.py -> build/bdist.linux-x86_64/egg/qcg/VQE\n    copying build/lib/qcg/VQE/uccsd_ansatz.py -> build/bdist.linux-x86_64/egg/qcg/VQE\n    creating build/bdist.linux-x86_64/egg/qcg/BernsteinVazirani\n    copying build/lib/qcg/BernsteinVazirani/bernstein_vazirani.py -> build/bdist.linux-x86_64/egg/qcg/BernsteinVazirani\n    copying build/lib/qcg/BernsteinVazirani/__init__.py -> build/bdist.linux-x86_64/egg/qcg/BernsteinVazirani\n    creating build/bdist.linux-x86_64/egg/qcg/QFT\n    copying build/lib/qcg/QFT/qft_circ.py -> build/bdist.linux-x86_64/egg/qcg/QFT\n    copying build/lib/qcg/QFT/__init__.py -> build/bdist.linux-x86_64/egg/qcg/QFT\n    copying build/lib/qcg/__init__.py -> build/bdist.linux-x86_64/egg/qcg\n    creating build/bdist.linux-x86_64/egg/qcg/Supremacy\n    copying build/lib/qcg/Supremacy/Qbit_Sycamore.py -> build/bdist.linux-x86_64/egg/qcg/Supremacy\n    copying build/lib/qcg/Supremacy/cz_layer_generation.py -> build/bdist.linux-x86_64/egg/qcg/Supremacy\n    copying build/lib/qcg/Supremacy/ABCD_layer_generation.py -> build/bdist.linux-x86_64/egg/qcg/Supremacy\n    copying build/lib/qcg/Supremacy/__init__.py -> build/bdist.linux-x86_64/egg/qcg/Supremacy\n    copying build/lib/qcg/Supremacy/Qbit_original.py -> build/bdist.linux-x86_64/egg/qcg/Supremacy\n    copying build/lib/qcg/Supremacy/Qgrid_Sycamore.py -> build/bdist.linux-x86_64/egg/qcg/Supremacy\n    copying build/lib/qcg/Supremacy/Qgrid_original.py -> build/bdist.linux-x86_64/egg/qcg/Supremacy\n    creating build/bdist.linux-x86_64/egg/qcg/QWalk\n    copying build/lib/qcg/QWalk/quantum_walk.py -> build/bdist.linux-x86_64/egg/qcg/QWalk\n    copying build/lib/qcg/QWalk/__init__.py -> build/bdist.linux-x86_64/egg/qcg/QWalk\n    creating build/bdist.linux-x86_64/egg/qcg/Arithmetic\n    copying build/lib/qcg/Arithmetic/ripple_carry_adder.py -> build/bdist.linux-x86_64/egg/qcg/Arithmetic\n    copying build/lib/qcg/Arithmetic/__init__.py -> build/bdist.linux-x86_64/egg/qcg/Arithmetic\n    creating build/bdist.linux-x86_64/egg/qcg/utils\n    copying build/lib/qcg/utils/__init__.py -> build/bdist.linux-x86_64/egg/qcg/utils\n    copying build/lib/qcg/utils/testhwea.py -> build/bdist.linux-x86_64/egg/qcg/utils\n    copying build/lib/qcg/generators.py -> build/bdist.linux-x86_64/egg/qcg\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/non_ibmq_functions.py to non_ibmq_functions.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/schedule.py to schedule.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions/non_ibmq_functions.py to non_ibmq_functions.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions/schedule.py to schedule.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions/ibmq_functions.py to ibmq_functions.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions/conversions.py to conversions.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions/metrics.py to metrics.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/setup.py to setup.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QAOA/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QAOA/hw_efficient_ansatz.py to hw_efficient_ansatz.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Dynamics/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Dynamics/quantum_dynamics.py to quantum_dynamics.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/VQE/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/VQE/uccsd_ansatz.py to uccsd_ansatz.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/BernsteinVazirani/bernstein_vazirani.py to bernstein_vazirani.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/BernsteinVazirani/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QFT/qft_circ.py to qft_circ.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QFT/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy/Qbit_Sycamore.py to Qbit_Sycamore.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy/cz_layer_generation.py to cz_layer_generation.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy/ABCD_layer_generation.py to ABCD_layer_generation.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy/Qbit_original.py to Qbit_original.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy/Qgrid_Sycamore.py to Qgrid_Sycamore.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy/Qgrid_original.py to Qgrid_original.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QWalk/quantum_walk.py to quantum_walk.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QWalk/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Arithmetic/ripple_carry_adder.py to ripple_carry_adder.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Arithmetic/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/utils/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/utils/testhwea.py to testhwea.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/generators.py to generators.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/ibmq_functions.py to ibmq_functions.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/conversions.py to conversions.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/metrics.py to metrics.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/QAOA/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/QAOA/hw_efficient_ansatz.py to hw_efficient_ansatz.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Dynamics/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Dynamics/quantum_dynamics.py to quantum_dynamics.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/VQE/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/VQE/uccsd_ansatz.py to uccsd_ansatz.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/BernsteinVazirani/bernstein_vazirani.py to bernstein_vazirani.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/BernsteinVazirani/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/QFT/qft_circ.py to qft_circ.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/QFT/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Supremacy/Qbit_Sycamore.py to Qbit_Sycamore.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Supremacy/cz_layer_generation.py to cz_layer_generation.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Supremacy/ABCD_layer_generation.py to ABCD_layer_generation.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Supremacy/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Supremacy/Qbit_original.py to Qbit_original.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Supremacy/Qgrid_Sycamore.py to Qgrid_Sycamore.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Supremacy/Qgrid_original.py to Qgrid_original.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/QWalk/quantum_walk.py to quantum_walk.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/QWalk/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Arithmetic/ripple_carry_adder.py to ripple_carry_adder.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Arithmetic/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/utils/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/utils/testhwea.py to testhwea.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/generators.py to generators.cpython-37.pyc\n    creating build/bdist.linux-x86_64/egg/EGG-INFO\n    copying qiskit_helper_functions.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying qiskit_helper_functions.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying qiskit_helper_functions.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying qiskit_helper_functions.egg-info/not-zip-safe -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying qiskit_helper_functions.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    creating dist\n    creating 'dist/qiskit_helper_functions-0.0.1-py3.7.egg' and adding 'build/bdist.linux-x86_64/egg' to it\n    removing 'build/bdist.linux-x86_64/egg' (and everything under it)\n    Processing qiskit_helper_functions-0.0.1-py3.7.egg\n    creating /usr/local/lib/python3.7/dist-packages/qiskit_helper_functions-0.0.1-py3.7.egg\n    Extracting qiskit_helper_functions-0.0.1-py3.7.egg to /usr/local/lib/python3.7/dist-packages\n    Adding qiskit-helper-functions 0.0.1 to easy-install.pth file\n    \n    Installed /usr/local/lib/python3.7/dist-packages/qiskit_helper_functions-0.0.1-py3.7.egg\n    Processing dependencies for qiskit-helper-functions==0.0.1\n    Finished processing dependencies for qiskit-helper-functions==0.0.1\n\n\n\n```python\n!pip unstall CutQC\n!git clone https://github.com/weiT1993/CutQC\n!cd CutQC && git checkout 6629a3696bea8ef3aa90dddfc021782859113377\n!cp -r CutQC/* ./ && python3 setup.py install\n```\n\n    ERROR: unknown command \"unstall\" - maybe you meant \"uninstall\"\n    Cloning into 'CutQC'...\n    remote: Enumerating objects: 372, done.\u001b[K\n    remote: Counting objects: 100% (372/372), done.\u001b[K\n    remote: Compressing objects: 100% (182/182), done.\u001b[K\n    remote: Total 372 (delta 127), reused 365 (delta 120), pack-reused 0\u001b[K\n    Receiving objects: 100% (372/372), 230.67 KiB | 6.59 MiB/s, done.\n    Resolving deltas: 100% (127/127), done.\n    Note: checking out '6629a3696bea8ef3aa90dddfc021782859113377'.\n    \n    You are in 'detached HEAD' state. You can look around, make experimental\n    changes and commit them, and you can discard any commits you make in this\n    state without impacting any branches by performing another checkout.\n    \n    If you want to create a new branch to retain commits you create, you may\n    do so (now or later) by using -b with the checkout command again. Example:\n    \n      git checkout -b <new-branch-name>\n    \n    HEAD is now at 6629a36 added numpy postprocess\n    running install\n    running bdist_egg\n    running egg_info\n    creating CutQC.egg-info\n    writing CutQC.egg-info/PKG-INFO\n    writing dependency_links to CutQC.egg-info/dependency_links.txt\n    writing top-level names to CutQC.egg-info/top_level.txt\n    writing manifest file 'CutQC.egg-info/SOURCES.txt'\n    reading manifest file 'CutQC.egg-info/SOURCES.txt'\n    adding license file 'LICENSE'\n    writing manifest file 'CutQC.egg-info/SOURCES.txt'\n    installing library code to build/bdist.linux-x86_64/egg\n    running install_lib\n    running build_py\n    creating build/lib/cutqc\n    copying cutqc/cutter.py -> build/lib/cutqc\n    copying cutqc/verify.py -> build/lib/cutqc\n    copying cutqc/main.py -> build/lib/cutqc\n    copying cutqc/__init__.py -> build/lib/cutqc\n    copying cutqc/post_process.py -> build/lib/cutqc\n    copying cutqc/evaluator.py -> build/lib/cutqc\n    copying cutqc/helper_fun.py -> build/lib/cutqc\n    creating build/bdist.linux-x86_64/egg\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/non_ibmq_functions.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/schedule.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/qiskit_helper_functions/non_ibmq_functions.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/qiskit_helper_functions/schedule.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/qiskit_helper_functions/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/qiskit_helper_functions/ibmq_functions.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/qiskit_helper_functions/conversions.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/qiskit_helper_functions/metrics.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/setup.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QAOA\n    copying build/lib/qiskit_helper_functions/qcg/QAOA/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QAOA\n    copying build/lib/qiskit_helper_functions/qcg/QAOA/hw_efficient_ansatz.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QAOA\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Dynamics\n    copying build/lib/qiskit_helper_functions/qcg/Dynamics/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Dynamics\n    copying build/lib/qiskit_helper_functions/qcg/Dynamics/quantum_dynamics.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Dynamics\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/VQE\n    copying build/lib/qiskit_helper_functions/qcg/VQE/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/VQE\n    copying build/lib/qiskit_helper_functions/qcg/VQE/uccsd_ansatz.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/VQE\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/BernsteinVazirani\n    copying build/lib/qiskit_helper_functions/qcg/BernsteinVazirani/bernstein_vazirani.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/BernsteinVazirani\n    copying build/lib/qiskit_helper_functions/qcg/BernsteinVazirani/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/BernsteinVazirani\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QFT\n    copying build/lib/qiskit_helper_functions/qcg/QFT/qft_circ.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QFT\n    copying build/lib/qiskit_helper_functions/qcg/QFT/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QFT\n    copying build/lib/qiskit_helper_functions/qcg/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy\n    copying build/lib/qiskit_helper_functions/qcg/Supremacy/Qbit_Sycamore.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy\n    copying build/lib/qiskit_helper_functions/qcg/Supremacy/cz_layer_generation.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy\n    copying build/lib/qiskit_helper_functions/qcg/Supremacy/ABCD_layer_generation.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy\n    copying build/lib/qiskit_helper_functions/qcg/Supremacy/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy\n    copying build/lib/qiskit_helper_functions/qcg/Supremacy/Qbit_original.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy\n    copying build/lib/qiskit_helper_functions/qcg/Supremacy/Qgrid_Sycamore.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy\n    copying build/lib/qiskit_helper_functions/qcg/Supremacy/Qgrid_original.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QWalk\n    copying build/lib/qiskit_helper_functions/qcg/QWalk/quantum_walk.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QWalk\n    copying build/lib/qiskit_helper_functions/qcg/QWalk/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QWalk\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Arithmetic\n    copying build/lib/qiskit_helper_functions/qcg/Arithmetic/ripple_carry_adder.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Arithmetic\n    copying build/lib/qiskit_helper_functions/qcg/Arithmetic/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Arithmetic\n    creating build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/utils\n    copying build/lib/qiskit_helper_functions/qcg/utils/__init__.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/utils\n    copying build/lib/qiskit_helper_functions/qcg/utils/testhwea.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/utils\n    copying build/lib/qiskit_helper_functions/qcg/generators.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg\n    copying build/lib/qiskit_helper_functions/ibmq_functions.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/conversions.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions\n    copying build/lib/qiskit_helper_functions/metrics.py -> build/bdist.linux-x86_64/egg/qiskit_helper_functions\n    creating build/bdist.linux-x86_64/egg/cutqc\n    copying build/lib/cutqc/cutter.py -> build/bdist.linux-x86_64/egg/cutqc\n    copying build/lib/cutqc/verify.py -> build/bdist.linux-x86_64/egg/cutqc\n    copying build/lib/cutqc/main.py -> build/bdist.linux-x86_64/egg/cutqc\n    copying build/lib/cutqc/__init__.py -> build/bdist.linux-x86_64/egg/cutqc\n    copying build/lib/cutqc/post_process.py -> build/bdist.linux-x86_64/egg/cutqc\n    copying build/lib/cutqc/evaluator.py -> build/bdist.linux-x86_64/egg/cutqc\n    copying build/lib/cutqc/helper_fun.py -> build/bdist.linux-x86_64/egg/cutqc\n    creating build/bdist.linux-x86_64/egg/qcg\n    creating build/bdist.linux-x86_64/egg/qcg/QAOA\n    copying build/lib/qcg/QAOA/__init__.py -> build/bdist.linux-x86_64/egg/qcg/QAOA\n    copying build/lib/qcg/QAOA/hw_efficient_ansatz.py -> build/bdist.linux-x86_64/egg/qcg/QAOA\n    creating build/bdist.linux-x86_64/egg/qcg/Dynamics\n    copying build/lib/qcg/Dynamics/__init__.py -> build/bdist.linux-x86_64/egg/qcg/Dynamics\n    copying build/lib/qcg/Dynamics/quantum_dynamics.py -> build/bdist.linux-x86_64/egg/qcg/Dynamics\n    creating build/bdist.linux-x86_64/egg/qcg/VQE\n    copying build/lib/qcg/VQE/__init__.py -> build/bdist.linux-x86_64/egg/qcg/VQE\n    copying build/lib/qcg/VQE/uccsd_ansatz.py -> build/bdist.linux-x86_64/egg/qcg/VQE\n    creating build/bdist.linux-x86_64/egg/qcg/BernsteinVazirani\n    copying build/lib/qcg/BernsteinVazirani/bernstein_vazirani.py -> build/bdist.linux-x86_64/egg/qcg/BernsteinVazirani\n    copying build/lib/qcg/BernsteinVazirani/__init__.py -> build/bdist.linux-x86_64/egg/qcg/BernsteinVazirani\n    creating build/bdist.linux-x86_64/egg/qcg/QFT\n    copying build/lib/qcg/QFT/qft_circ.py -> build/bdist.linux-x86_64/egg/qcg/QFT\n    copying build/lib/qcg/QFT/__init__.py -> build/bdist.linux-x86_64/egg/qcg/QFT\n    copying build/lib/qcg/__init__.py -> build/bdist.linux-x86_64/egg/qcg\n    creating build/bdist.linux-x86_64/egg/qcg/Supremacy\n    copying build/lib/qcg/Supremacy/Qbit_Sycamore.py -> build/bdist.linux-x86_64/egg/qcg/Supremacy\n    copying build/lib/qcg/Supremacy/cz_layer_generation.py -> build/bdist.linux-x86_64/egg/qcg/Supremacy\n    copying build/lib/qcg/Supremacy/ABCD_layer_generation.py -> build/bdist.linux-x86_64/egg/qcg/Supremacy\n    copying build/lib/qcg/Supremacy/__init__.py -> build/bdist.linux-x86_64/egg/qcg/Supremacy\n    copying build/lib/qcg/Supremacy/Qbit_original.py -> build/bdist.linux-x86_64/egg/qcg/Supremacy\n    copying build/lib/qcg/Supremacy/Qgrid_Sycamore.py -> build/bdist.linux-x86_64/egg/qcg/Supremacy\n    copying build/lib/qcg/Supremacy/Qgrid_original.py -> build/bdist.linux-x86_64/egg/qcg/Supremacy\n    creating build/bdist.linux-x86_64/egg/qcg/QWalk\n    copying build/lib/qcg/QWalk/quantum_walk.py -> build/bdist.linux-x86_64/egg/qcg/QWalk\n    copying build/lib/qcg/QWalk/__init__.py -> build/bdist.linux-x86_64/egg/qcg/QWalk\n    creating build/bdist.linux-x86_64/egg/qcg/Arithmetic\n    copying build/lib/qcg/Arithmetic/ripple_carry_adder.py -> build/bdist.linux-x86_64/egg/qcg/Arithmetic\n    copying build/lib/qcg/Arithmetic/__init__.py -> build/bdist.linux-x86_64/egg/qcg/Arithmetic\n    creating build/bdist.linux-x86_64/egg/qcg/utils\n    copying build/lib/qcg/utils/__init__.py -> build/bdist.linux-x86_64/egg/qcg/utils\n    copying build/lib/qcg/utils/testhwea.py -> build/bdist.linux-x86_64/egg/qcg/utils\n    copying build/lib/qcg/generators.py -> build/bdist.linux-x86_64/egg/qcg\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/non_ibmq_functions.py to non_ibmq_functions.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/schedule.py to schedule.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions/non_ibmq_functions.py to non_ibmq_functions.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions/schedule.py to schedule.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions/ibmq_functions.py to ibmq_functions.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions/conversions.py to conversions.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qiskit_helper_functions/metrics.py to metrics.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/setup.py to setup.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QAOA/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QAOA/hw_efficient_ansatz.py to hw_efficient_ansatz.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Dynamics/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Dynamics/quantum_dynamics.py to quantum_dynamics.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/VQE/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/VQE/uccsd_ansatz.py to uccsd_ansatz.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/BernsteinVazirani/bernstein_vazirani.py to bernstein_vazirani.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/BernsteinVazirani/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QFT/qft_circ.py to qft_circ.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QFT/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy/Qbit_Sycamore.py to Qbit_Sycamore.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy/cz_layer_generation.py to cz_layer_generation.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy/ABCD_layer_generation.py to ABCD_layer_generation.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy/Qbit_original.py to Qbit_original.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy/Qgrid_Sycamore.py to Qgrid_Sycamore.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Supremacy/Qgrid_original.py to Qgrid_original.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QWalk/quantum_walk.py to quantum_walk.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/QWalk/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Arithmetic/ripple_carry_adder.py to ripple_carry_adder.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/Arithmetic/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/utils/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/utils/testhwea.py to testhwea.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/qcg/generators.py to generators.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/ibmq_functions.py to ibmq_functions.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/conversions.py to conversions.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qiskit_helper_functions/metrics.py to metrics.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/cutqc/cutter.py to cutter.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/cutqc/verify.py to verify.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/cutqc/main.py to main.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/cutqc/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/cutqc/post_process.py to post_process.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/cutqc/evaluator.py to evaluator.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/cutqc/helper_fun.py to helper_fun.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/QAOA/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/QAOA/hw_efficient_ansatz.py to hw_efficient_ansatz.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Dynamics/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Dynamics/quantum_dynamics.py to quantum_dynamics.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/VQE/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/VQE/uccsd_ansatz.py to uccsd_ansatz.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/BernsteinVazirani/bernstein_vazirani.py to bernstein_vazirani.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/BernsteinVazirani/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/QFT/qft_circ.py to qft_circ.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/QFT/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Supremacy/Qbit_Sycamore.py to Qbit_Sycamore.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Supremacy/cz_layer_generation.py to cz_layer_generation.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Supremacy/ABCD_layer_generation.py to ABCD_layer_generation.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Supremacy/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Supremacy/Qbit_original.py to Qbit_original.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Supremacy/Qgrid_Sycamore.py to Qgrid_Sycamore.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Supremacy/Qgrid_original.py to Qgrid_original.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/QWalk/quantum_walk.py to quantum_walk.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/QWalk/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Arithmetic/ripple_carry_adder.py to ripple_carry_adder.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/Arithmetic/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/utils/__init__.py to __init__.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/utils/testhwea.py to testhwea.cpython-37.pyc\n    byte-compiling build/bdist.linux-x86_64/egg/qcg/generators.py to generators.cpython-37.pyc\n    creating build/bdist.linux-x86_64/egg/EGG-INFO\n    copying CutQC.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying CutQC.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying CutQC.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying CutQC.egg-info/not-zip-safe -> build/bdist.linux-x86_64/egg/EGG-INFO\n    copying CutQC.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO\n    creating 'dist/CutQC-0.0.1-py3.7.egg' and adding 'build/bdist.linux-x86_64/egg' to it\n    removing 'build/bdist.linux-x86_64/egg' (and everything under it)\n    Processing CutQC-0.0.1-py3.7.egg\n    creating /usr/local/lib/python3.7/dist-packages/CutQC-0.0.1-py3.7.egg\n    Extracting CutQC-0.0.1-py3.7.egg to /usr/local/lib/python3.7/dist-packages\n    Adding CutQC 0.0.1 to easy-install.pth file\n    \n    Installed /usr/local/lib/python3.7/dist-packages/CutQC-0.0.1-py3.7.egg\n    Processing dependencies for CutQC==0.0.1\n    Finished processing dependencies for CutQC==0.0.1\n\n\n# Code\n\n\n```python\nfrom qiskit.quantum_info import random_unitary\n# from qiskit.circuit.random import random_circuit\nfrom qiskit_helper_functions.non_ibmq_functions import generate_circ\nfrom qiskit_helper_functions.non_ibmq_functions import apply_measurement\nfrom qiskit_helper_functions.conversions import dict_to_array\n\nfrom cutqc.cutter import find_cuts\nfrom cutqc.post_process import generate_summation_terms, get_naive_overhead # build\nfrom cutqc.evaluator import run_subcircuit_instances\nfrom cutqc.verify import verify\n\nfrom anytree import Node, RenderTree\nfrom anytree.exporter import DotExporter\nfrom anytree.search import findall_by_attr\n\nfrom pprint import pprint\n\nfrom cutqc.cutter import subcircuits_parser, get_pairs, get_counter, cost_estimate\nfrom cutqc.evaluator import modify_subcircuit_instance, mutate_measurement_basis, measure_prob\n```\n\n\n```python\nimport numpy as np\nfrom qiskit import QuantumCircuit, QuantumRegister\nfrom inspect import signature\n\ndef random_circuit(width=3, depth=3, max_operands=3):\n        \"\"\"Generate random circuit of arbitrary size.\n        Note: the depth is the layers of independent operation. true depth\n        in the image may be more for visualization purposes, if gates overlap.\n        Args:\n            width (int): number of quantum wires\n            depth (int): layers of operations\n            max_operands (int): maximum operands of each gate\n        Returns:\n            QuantumCircuit: constructed circuit\n        \"\"\"\n        qr = QuantumRegister(width, \"q\")\n        qc = QuantumCircuit(qr)\n\n        one_q_ops = \"x,y,z,h\"\n        two_q_ops = \"cx,cy,ch\"\n        three_q_ops = \"ccx\"\n\n        seed = np.random.randint(0, np.iinfo(np.int32).max)\n        rng = np.random.RandomState(seed)\n        # apply arbitrary random operations at every depth\n        for _ in range(depth):\n            # choose either 1, 2, or 3 qubits for the operation\n            remaining_qubits = list(range(width))\n            while remaining_qubits:\n                max_possible_operands = min(len(remaining_qubits), max_operands)\n                num_operands = rng.choice(range(max_possible_operands)) + 1\n                rng.shuffle(remaining_qubits)\n                operands = remaining_qubits[:num_operands]\n                remaining_qubits = [q for q in remaining_qubits if q not in operands]\n                if num_operands == 1:\n                    operation = rng.choice(one_q_ops.split(','))\n                elif num_operands == 2:\n                    operation = rng.choice(two_q_ops.split(','))\n                elif num_operands == 3:\n                    operation = rng.choice(three_q_ops.split(','))\n                # every gate is defined as a method of the QuantumCircuit class\n                # the code below is so we can call a gate by its name\n                gate = getattr(QuantumCircuit, operation)\n                register_operands = [qr[i] for i in operands]\n                gate(qc, *register_operands)\n\n        return qc\n\nfor _ in range(1000):\n    random_circuit()\n```\n\n\n```python\ntypes = [\n         # qiskit_helper_functions\n         \"bv\",\n         \"supremacy\",\n         \"supremacy_linear\",\n         \"hwea\",\n         \"qft\",\n         \"aqft\",\n         \"sycamore\",\n         \"adder\",\n         \"grover\",\n         \"random\",\n\n         # qiskit.circuit.random\n         \"qiskit-random\"\n    ]\n\ndef generate_circuit(register_size = 12, depth=12, circuit_type = \"bv\", **kwargs):\n\n    if not circuit_type in types:\n        raise Exception(\"Unknown circuit type.\")\n\n    if circuit_type == \"qiskit-random\":\n        return random_circuit(register_size, depth, 2)\n\n    return generate_circ(num_qubits=register_size, depth=depth, circuit_type=circuit_type, **kwargs)\n\ndef run_batch(definition, batch = 5, context = {}):\n    return timeit.repeat(stmt=\"definition()\", setup=\"\", repeat=batch, number = batch, globals={ **globals(), **context, \"definition\": definition })\n\n\ndef avg(arr):\n    return sum(arr) / len(arr)\n```\n\n\n```python\nfrom pprint import pprint\n\ndef cut(circuit, verbose = True):\n    circuit_const = int( circuit.size() / circuit.num_qubits )\n    \n    max_subcircuit_width = min([circuit.num_qubits, circuit_const])\n    max_subcircuit_width = max([max_subcircuit_width, 2])\n\n    max_subcircuit_cuts = circuit.num_qubits - 2\n    quantum_cost_weight = 1.0\n    max_cuts = circuit.num_qubits - 2\n\n    circuit_const = circuit_const + 1\n    \n    if circuit_const < circuit.num_qubits - 1 and circuit_const > 1:\n        num_subcircuits = [ s for s in range(circuit_const - 1, int(circuit.num_qubits / 1.5)) ]\n    else:\n        num_subcircuits = [ s for s in range(2, int(circuit.num_qubits / 1.5)) ]\n\n    kwargs = {\n        \"max_subcircuit_width\": max_subcircuit_width,\n        \"max_subcircuit_cuts\": max_subcircuit_cuts,\n        \"max_subcircuit_size\": None,\n        \"quantum_cost_weight\": quantum_cost_weight,\n        \"max_cuts\": max_cuts,\n        \"num_subcircuits\": num_subcircuits\n    }\n\n    # kwargs['max_subcircuit_width']=12\n    # kwargs['max_subcircuit_cuts']=10\n    # kwargs['max_subcircuit_size']=None\n    # kwargs['quantum_cost_weight']=1.0\n    # kwargs['max_cuts']=10\n    # kwargs['num_subcircuits']=[2,3,4, *kwargs['num_subcircuits']]\n    \n    # pprint(kwargs)\n    \n    return find_cuts(circuit=circuit, **kwargs, verbose=verbose)\n\n\ndef recursive_cut(circuit, callback=None, prefix='cut1', parent_node=None, min_qubit=None):\n    if parent_node:\n        node = Node(prefix, parent=parent_node)\n    else:\n        node = Node(prefix)\n\n    cuts = cut(circuit, False)\n    all_cuts = cuts.get('subcircuits', [])\n    \n    if len(all_cuts) < 2:\n        if callback:\n            callback(node, circuit, prefix)\n        # print(f\"Final Node : {prefix}\")\n        node.data = circuit\n        return node\n    else:\n        node.data = circuit\n\n        if min_qubit:\n            if circuit.num_qubits <= min_qubit:\n                if callback:\n                    callback(node, circuit, prefix)\n                return node\n\n        node.complete_path_map = cuts.get('complete_path_map', {})\n        node.cuts = cuts\n        \n        # if callback:\n        #     callback(node, circuit, prefix)\n        \n        postfix = 0\n        for circ in all_cuts:\n            postfix = postfix + 1\n            recursive_cut(circ, callback, prefix + str(postfix), node, min_qubit)\n    \n    return node\n```\n\n\n```python\ndef get_target_from_path(n, graph):\n\n    key = [ k for k in filter ( lambda obj: obj.index == n, list(graph.keys()) )]\n\n    return key, graph[key]\n\ndef get_mapped_from_path(subcircuit_idx, n, graph):\n\n    def check(obj):\n        for o in obj:\n            if ( o['subcircuit_idx'] == subcircuit_idx ) and ( o['subcircuit_qubit'].index == n ):\n                return True\n        return False\n\n    key = [ k for k in filter ( lambda obj: check(graph[obj]), list(graph.keys()) )]\n    key = key[0]\n\n    return key, graph[key]\n\ndef graph_output_circuit_nums(graph):\n    size = []\n    for val in graph.values():\n        for v in val:\n            size += [ v['subcircuit_idx'] ]\n    return len(set(size))\n\ndef graph_output_circuit_ids(graph):\n    size = []\n    for val in graph.values():\n        for v in val:\n            size += [ v['subcircuit_idx'] ]\n    return list(set(size))\n\ndef graph_input_circuit_size(graph):\n    return list(graph.keys())[0].register.size\n\ndef get_cut_from_graph(graph):\n    return [ mappings for mappings in list(graph.values()) if len(mappings) > 1][0]\n\n\ndef get_cut_idx(cut, graph):\n    for channel in cut:\n        if channel['subcircuit_qubit'] in graph:\n            return channel['subcircuit_idx']\n    return False\n\n\ndef clean_name_tree(node):\n    if node.is_leaf:\n        node.name = \"node\" + node.name[3:]\n    [ clean_name_tree(child) for child in node.children ]\n    return node\n\ndef get_solution(circuit, subcircuits, complete_path_map):\n\n    # subcircuits, complete_path_map = subcircuits_parser(subcircuit_gates=subcircuits, circuit=circuit)\n    O_rho_pairs = get_pairs(complete_path_map=complete_path_map)\n    counter = get_counter(subcircuits=subcircuits, O_rho_pairs=O_rho_pairs)\n    quantum_cost, classical_cost = cost_estimate(counter=counter)\n    max_subcircuit_width = max([subcircuit.width() for subcircuit in subcircuits])\n\n    cut_solution = {\n        'max_subcircuit_width':max_subcircuit_width,\n        'subcircuits':subcircuits,\n        'complete_path_map':complete_path_map,\n        'num_cuts':len(O_rho_pairs),\n        'counter':counter,\n        'classical_cost':classical_cost,\n        'quantum_cost':quantum_cost}\n\n    return cut_solution\n\ndef get_complete_path_map(pnode): # node_stack, circuit_stack, circuit):\n    # 1.) get pnode->path_map\n    # 2.) get (!pnode->is_leaf)=>(return pnode->path_map + pnode.children->get_complete_path_map without None)\n    # 3.) \n    # 4.) (pnode->is_leaf)=>return none\n    # complete_path_map\n\n    if not pnode.is_leaf:\n        child_path_map = [ get_complete_path_map(child) for child in pnode.children ]\n        child_path_map = [ (child) for child in child_path_map if child ]\n        if child_path_map:\n\n            if len(child_path_map) == 1:\n                child_path_map = child_path_map[0]\n                return combine_path_map(pnode.complete_path_map, child_path_map)\n            else:\n                map = combine_path_map(pnode.complete_path_map, child_path_map[0])\n                for i in range(1, len(child_path_map)):\n                    map = combine_path_map(pnode.complete_path_map, child_path_map[i])\n                child_path_map = map\n                return child_path_map\n        else:\n            return pnode.complete_path_map\n    else:\n        return None\n\n\ndef combine_path_map(parent_path_map, child_path_map):\n\n    result = parent_path_map\n\n    reconstructed_map = {}\n\n    parent_size = graph_output_circuit_nums(parent_path_map)\n    child_size = graph_output_circuit_nums(child_path_map)\n    total_size = parent_size + child_size\n\n    circuit_piece = [ i for i in range(total_size + 1) ]\n\n    parent_input_size = graph_input_circuit_size(parent_path_map)\n    child_input_size  = graph_input_circuit_size(child_path_map)\n\n    parent_piece_mapping = {}\n    child_piece_mapping = {}\n\n    cut = get_cut_from_graph(parent_path_map)\n    cut_point = get_cut_idx(cut, list(child_path_map.keys()))\n    end_point = child_size \n\n    parent_piece_mapping.update({ f:f for f in range(0, cut_point) })\n    child_piece_mapping.update({ (f-cut_point):f for f in range(cut_point, end_point + cut_point) })\n    parent_piece_mapping.update({(f-end_point + 1):f for f in range(end_point + cut_point, total_size - 1) })\n\n    child_path_map_remapped = {}\n    for key, values in child_path_map.items():\n        remapped_values = []\n        for piece in values:\n            remapped_values += [{ 'subcircuit_idx': child_piece_mapping[ piece['subcircuit_idx'] ], 'subcircuit_qubit': piece['subcircuit_qubit'] }]\n        child_path_map_remapped[key] = remapped_values\n\n    parent_path_map_remapped = parent_path_map\n\n    reconstructed_map = {}\n    for qubit, qubit_to_sub_circuit_map in parent_path_map_remapped.items():\n        map = qubit_to_sub_circuit_map\n        join = []\n        remove = []\n        for index, connection in enumerate(qubit_to_sub_circuit_map):\n            if connection['subcircuit_qubit'] in list( child_path_map_remapped.keys() ) and cut_point == connection['subcircuit_idx']:\n                add_this = child_path_map_remapped[ connection['subcircuit_qubit'] ]\n                join += add_this\n            else:\n                add_this = connection\n                add_this['subcircuit_idx'] = parent_piece_mapping[add_this['subcircuit_idx']]\n                join += [ add_this ]\n            remove += [connection]\n\n        [ map.remove(con) for con in remove ]\n\n        map += join\n        reconstructed_map[qubit] =  map\n    \n    new_output_map = { value: key for (key, value) in enumerate(graph_output_circuit_ids(reconstructed_map)) }\n    reconstructed_map_correction = {}\n    for key, values in reconstructed_map.items():\n        remapped_values = []\n        for piece in values:\n            remapped_values += [{ 'subcircuit_idx': new_output_map[ piece['subcircuit_idx'] ], 'subcircuit_qubit': piece['subcircuit_qubit'] }]\n        reconstructed_map_correction[key] = remapped_values\n\n\n    return reconstructed_map_correction\n\n```\n\n\n```python\nfrom time import time\nimport itertools, copy\n\nimport numpy as np\n\nfrom qiskit import IBMQ, transpile, Aer, execute\n\nfrom qiskit.providers.aer import noise\nfrom qiskit import QuantumCircuit\nfrom qiskit.providers.aer import AerSimulator\nfrom qiskit.tools.visualization import plot_histogram\nfrom qiskit.test.mock import FakeBackend, FakeTokyo, FakeVigo, FakeMelbourne, FakePoughkeepsie, FakeQasmSimulator, FakeRueschlikon, FakeTenerife\n\navailable_backend = {\n    \"FakeTokyo\": FakeTokyo, \n    \"FakeVigo\": FakeVigo, \n    \"FakeMelbourne\": FakeMelbourne, \n    \"FakePoughkeepsie\": FakePoughkeepsie, \n    \"FakeRueschlikon\": FakeRueschlikon, \n    \"FakeTenerife\": FakeTenerife\n}\n\ndef get_backend_name(backend):\n    for name, device in available_backend.items():\n        if device is backend:\n            return name\n    raise Exception(\"Backend Error: No specified vackend found.\")\n\ndef evaluate_circ(circuit, backend, options=None):\n    if backend in available_backend:\n        backend_name = backend\n        backend = available_backend[backend]()\n\n        noise_model = noise.NoiseModel.from_backend(backend)\n        if isinstance(options,dict) and 'num_shots' in options:\n            num_shots = options['num_shots']\n        else:\n            num_shots = max(1024,2**circuit.num_qubits)\n        if isinstance(options,dict) and 'memory' in options:\n            memory = options['memory']\n        else:\n            memory = False\n        if circuit.num_clbits == 0:\n            circuit = apply_measurement(circuit=circuit,qubits=circuit.qubits)\n            circuit = Tket(circuit, available_backend[backend_name])\n            # print(\"CIRCUIT\")\n            # print(circuit.draw())\n        # job = execute(circuit, backend=backend, noise_model=noise_model, shots=num_shots, memory=memory).result()\n        job = execute(circuit, backend=backend, shots=num_shots, memory=memory).result()\n        if memory:\n            qasm_memory = np.array(job.get_memory(0))\n            assert len(qasm_memory)==num_shots\n            return qasm_memory\n        else:\n            counts = job.get_counts(0)\n            assert sum(counts.values())==num_shots\n            counts = dict_to_array(distribution_dict=counts,force_prob=True)\n            return counts\n    if type(backend) is str:\n        if backend=='statevector_simulator':\n            backend = Aer.get_backend('statevector_simulator')\n            job = execute(circuit, backend=backend, optimization_level=0)\n            result = job.result()\n            output_sv = result.get_statevector(circuit)\n            output_p = []\n            for x in output_sv:\n                amplitude = np.absolute(x)**2\n                if amplitude>1e-16:\n                    output_p.append(amplitude)\n                else:\n                    output_p.append(0)\n            output_p = np.array(output_p)\n            return output_p\n        elif backend == 'noiseless_qasm_simulator':\n            if isinstance(options,dict) and 'num_shots' in options:\n                num_shots = options['num_shots']\n            else:\n                num_shots = max(1024,2**circuit.num_qubits)\n            backend = Aer.get_backend('qasm_simulator')\n\n            if isinstance(options,dict) and 'memory' in options:\n                memory = options['memory']\n            else:\n                memory = False\n            if circuit.num_clbits == 0:\n                circuit = apply_measurement(circuit=circuit,qubits=circuit.qubits)\n            noiseless_qasm_result = execute(circuit, backend, shots=num_shots, memory=memory).result()\n\n            if memory:\n                qasm_memory = np.array(noiseless_qasm_result.get_memory(0))\n                assert len(qasm_memory)==num_shots\n                return qasm_memory\n            else:\n                noiseless_counts = noiseless_qasm_result.get_counts(0)\n                assert sum(noiseless_counts.values())==num_shots\n                noiseless_counts = dict_to_array(distribution_dict=noiseless_counts,force_prob=True)\n                return noiseless_counts\n        elif backend=='noisy_qasm_simulator':\n            noisy_qasm_result = execute(circuit, Aer.get_backend('qasm_simulator'),\n            coupling_map=options['coupling_map'],\n            basis_gates=options['basis_gates'],\n            noise_model=options['noise_model'],\n            shots=options['num_shots']).result()\n\n            noisy_counts = noisy_qasm_result.get_counts(0)\n            assert sum(noisy_counts.values())==options['num_shots']\n            noisy_counts = dict_to_array(distribution_dict=noisy_counts,force_prob=True)\n            return noisy_counts\n        else:\n            raise NotImplementedError\n\ndef simulate_subcircuit(subcircuit,eval_mode,num_shots):\n    '''\n    Simulate a subcircuit\n    '''\n    if eval_mode=='sv':\n        subcircuit_inst_prob = evaluate_circ(circuit=subcircuit,backend='statevector_simulator')\n    elif eval_mode=='qasm':\n        subcircuit_inst_prob = evaluate_circ(circuit=subcircuit,backend='noiseless_qasm_simulator',options={'num_shots':num_shots})\n    else:\n        subcircuit_inst_prob = evaluate_circ(circuit=subcircuit,backend=get_backend_name(eval_mode),options={'num_shots':num_shots})\n    return subcircuit_inst_prob\n\ndef naive_compute(subcircuit_order, summation_terms, subcircuit_entry_probs):\n\ttry:\n\t\timport cupy as cp\n\t\tCUDA = True\n\texcept:\n\t\timport numpy as np\n\t\tCUDA = False\n\treconstructed_prob = None\n\tfor idx in range(len(summation_terms)):\n\t\tsummation_term = summation_terms[idx]\n\t\tsummation_term_prob = None\n\t\tfor subcircuit_idx in subcircuit_order:\n\t\t\tsubcircuit_entry_idx = summation_term[subcircuit_idx]\n\t\t\tsubcircuit_entry_prob = subcircuit_entry_probs[subcircuit_idx][subcircuit_entry_idx]\n\t\t\tif summation_term_prob is None:\n\t\t\t\tsummation_term_prob = subcircuit_entry_prob\n\t\t\telse:\n\t\t\t\tif CUDA:\n\t\t\t\t\tsummation_term_prob = cp.array(summation_term_prob)\n\t\t\t\t\tsubcircuit_entry_prob = cp.array(subcircuit_entry_prob)\n\t\t\t\t\tsummation_term_prob = cp.kron(summation_term_prob,subcircuit_entry_prob)\n\t\t\t\t\tsummation_term_prob = cp.asnumpy(summation_term_prob)\n\t\t\t\telse:\n\t\t\t\t\tsummation_term_prob = np.kron(summation_term_prob,subcircuit_entry_prob)\n                    \n\t\tif reconstructed_prob is None:\n\t\t\treconstructed_prob = summation_term_prob\n\t\telse:\n\t\t\treconstructed_prob += summation_term_prob\n\treturn reconstructed_prob\n\ndef build(summation_terms, subcircuit_entry_probs, num_cuts, counter, verbose):\n\tmin_overhead = float('inf')\n\tfor subcircuit_order in itertools.permutations(range(len(subcircuit_entry_probs))):\n\t\toverhead = get_naive_overhead(subcircuit_order=subcircuit_order,num_cuts=num_cuts,counter=counter)\n\t\tif overhead['additions']+overhead['multiplications']<min_overhead:\n\t\t\tsmart_order = subcircuit_order\n\t\t\tmin_overhead = overhead['additions']+overhead['multiplications']\n\t\t\tif verbose:\n\t\t\t\tprint('subcircuit_order {}. overhead = {}.'.format(subcircuit_order,overhead))\n\t\n\treconstructed_prob = naive_compute(subcircuit_order, summation_terms, subcircuit_entry_probs)\n\treconstructed_prob /= 2**num_cuts\n\treturn reconstructed_prob, smart_order\n\ndef get_backend_name_from_stack(backend_run_stack, circuit):\n    for key, values in backend_run_stack.items():\n        if circuit in values:\n            return key\n    return 'sv'\n\ndef run_subcircuit_instances(subcircuits,subcircuit_instances,eval_mode,num_shots_fn, backend_run_stack=None):\n    '''\n    subcircuit_instance_probs[subcircuit_idx][subcircuit_instance_idx] = measured probability\n    '''\n    subcircuit_instance_probs = {}\n    for subcircuit_idx in subcircuit_instances:\n        subcircuit_instance_probs[subcircuit_idx] = {}\n        num_shots = num_shots_fn(subcircuits[subcircuit_idx])\n        for init_meas in subcircuit_instances[subcircuit_idx]:\n            subcircuit_instance_idx = subcircuit_instances[subcircuit_idx][init_meas]\n            if subcircuit_instance_idx not in subcircuit_instance_probs[subcircuit_idx]:\n                # print('Subcircuit %d instance %d'%(subcircuit_idx,subcircuit_instance_idx))\n                subcircuit_instance = modify_subcircuit_instance(\n                    subcircuit=subcircuits[subcircuit_idx],\n                    init=init_meas[0],meas=init_meas[1])\n                if backend_run_stack:\n                    subcircuit_inst_prob = simulate_subcircuit(subcircuit=subcircuit_instance,eval_mode=get_backend_name_from_stack(backend_run_stack, subcircuits[subcircuit_idx]),num_shots=num_shots)\n                else:\n                    subcircuit_inst_prob = simulate_subcircuit(subcircuit=subcircuit_instance,eval_mode=eval_mode,num_shots=num_shots)\n                mutated_meas = mutate_measurement_basis(meas=init_meas[1])\n                for meas in mutated_meas:\n                    measured_prob = measure_prob(unmeasured_prob=subcircuit_inst_prob,meas=meas)\n                    mutated_subcircuit_instance_idx = subcircuit_instances[subcircuit_idx][(init_meas[0],meas)]\n                    subcircuit_instance_probs[subcircuit_idx][mutated_subcircuit_instance_idx] = measured_prob\n                    # print('Measured instance %d'%mutated_subcircuit_instance_idx)\n    return subcircuit_instance_probs\n\ndef summation(subcircuits, complete_path_map, num_cuts, full_circuit):\n    return generate_summation_terms(subcircuits, complete_path_map, num_cuts)\n\ndef _attribute_shots(summation_terms, subcircuit_entries, subcircuit_instances, subcircuits, backend=None, backend_run_stack=None):\n    '''\n    eval_mode = qasm: simulate shots\n    eval_mode = sv: statevector simulation\n    num_shots_fn: a function that gives the number of shots to take for a given circuit\n    '''\n    eval_mode = 'sv'\n    if backend:\n        eval_mode = backend\n    def constant_shots_fn(circuit):\n        return 1024\n    num_shots_fn = constant_shots_fn\n    print(\"subcircuits : \", [ circ.num_qubits for circ in subcircuits ])\n    print(\"subcircuit_instances : \", subcircuit_instances)\n    subcircuit_instance_probs = run_subcircuit_instances(subcircuits=subcircuits,subcircuit_instances=subcircuit_instances, eval_mode=eval_mode,num_shots_fn=num_shots_fn, backend_run_stack=backend_run_stack)\n    print(\"subcircuit_instance_probs : \", [ f\"{key}: {len(proba)}    \" for key, proba in subcircuit_instance_probs.items() ])\n\n    subcircuit_entry_probs = {}\n    for subcircuit_idx in subcircuit_entries:\n        subcircuit_entry_probs[subcircuit_idx] = {}\n        for label in subcircuit_entries[subcircuit_idx]:\n            subcircuit_entry_idx, kronecker_term = subcircuit_entries[subcircuit_idx][label]\n            # print('Subcircuit {:d} entry {:d} kronecker_term {}'.format(\n            #     subcircuit_idx, subcircuit_entry_idx, kronecker_term\n            # ))\n            subcircuit_entry_prob = None\n            for term in kronecker_term:\n                coefficient, subcircuit_instance_idx = term\n                if subcircuit_entry_prob is None:\n                    subcircuit_entry_prob = coefficient * subcircuit_instance_probs[subcircuit_idx][subcircuit_instance_idx]\n                else:\n                    subcircuit_entry_prob += coefficient * subcircuit_instance_probs[subcircuit_idx][subcircuit_instance_idx]\n            subcircuit_entry_probs[subcircuit_idx][subcircuit_entry_idx] = subcircuit_entry_prob\n    return subcircuit_entry_probs\n\ndef reconstruct(subcircuits, complete_path_map, full_circuit, backend = None, backend_run_stack=None, verbose=True):\n\n    num_cuts = graph_output_circuit_nums(complete_path_map) - 1\n\n    summation_terms, subcircuit_entries, subcircuit_instances = generate_summation_terms(subcircuits, complete_path_map, num_cuts)\n\n    cuts = get_solution(full_circuit, subcircuits, complete_path_map)\n\n    if backend:\n        subcircuit_entry_probs = _attribute_shots(summation_terms, subcircuit_entries, subcircuit_instances, subcircuits, backend=backend)\n    if backend_run_stack:\n        subcircuit_entry_probs = _attribute_shots(summation_terms, subcircuit_entries, subcircuit_instances, subcircuits, backend_run_stack=backend_run_stack)\n\n    reconstructed_prob, smart_order = build(summation_terms, subcircuit_entry_probs, num_cuts, cuts['counter'], verbose)\n\n    unordered_prob = reconstructed_prob\n    reconstructed_output, metrics = verify(full_circuit=full_circuit,\n                unordered=unordered_prob,\n                complete_path_map=cuts['complete_path_map'],\n                subcircuits=subcircuits,\n                smart_order=smart_order)\n    return reconstructed_output, metrics\n\n```\n\n\n```python\nfrom qiskit import QuantumCircuit, execute\n\nclass CircuitLargerThanChip(Exception):\n    pass\n\nclass NoSubcircuitFoundException(Exception):\n    pass\n\ndef check_chip_compatiblity(backend, circuit, raise_exception=True):\n    if backend._configuration.n_qubits < circuit.num_qubits:\n        if raise_exception:\n            raise CircuitLargerThanChip(f\"Circuit is larger than chip size.\\nChip:{backend}\\tCircuit:{circuit.num_qubits}\")\n        else:\n            return False\n    # print(f\"Chip:{backend} {backend._configuration.n_qubits}\\tCircuit:{circuit.num_qubits}\")\n    return True\n\n```\n\n\n```python\nfrom pytket.routing import Architecture, route, place_with_map\nfrom pytket.transform import Transform\nfrom pytket.routing import Placement, LinePlacement, GraphPlacement, NoiseAwarePlacement\nfrom pytket.extensions.qiskit import qiskit_to_tk, tk_to_qiskit\n\ndef Tket(circuit, backend = None, transform = False):\n    pytket_circ = qiskit_to_tk(circuit)\n\n    if not backend in list(available_backend.values()):\n        raise Exception(f\"Backend `{backend}` is not valid\")\n\n    backend = backend()\n    check_chip_compatiblity(backend, circuit) # Validate Chip Size to Circuit Size\n\n    if transform:\n        Transform.RemoveRedundancies().apply(physical_c)\n        Transform.OptimisePostRouting().apply(physical_c)\n        Transform.RebaseToQiskit().apply(physical_c)\n\n\n    arc = Architecture(backend._configuration.coupling_map)\n\n    # placement = Placement(arc)\n    # placement_map = placement.get_placement_map(pytket_circ)\n\n    physical_c = route(pytket_circ, arc)\n\n    # placement.place(physical_c)\n    # place_with_map(pytket_circ, placement_map)\n\n    final_circ = tk_to_qiskit(physical_c)\n\n    return final_circ\n\nfrom qiskit.circuit import QuantumRegister, Qubit\nfrom pprint import pprint\ndef tket_path(pathmap):\n    map = pathmap.copy()\n    q_node = Qubit(QuantumRegister(6, 'q'), 0)\n    q_node.register.size, q_node.index\n    \n    for key, values in map.items():\n        for index, conn in enumerate(map[key]): \n            # {'subcircuit_idx': 0, 'subcircuit_qubit': Qubit(QuantumRegister(4, 'q'), 0)}\n            qubit = conn['subcircuit_qubit']\n            qubit = Qubit(QuantumRegister(qubit.register.size, 'node'), qubit.index)\n            qubit._hash = pathmap[key][index]['subcircuit_qubit']._hash\n            map[key][index]['subcircuit_qubit'] = qubit\n    return map\n\nfrom qiskit import QuantumCircuit, QuantumRegister\ndef tket_rename_nodes(circuit):\n    qreg = QuantumRegister(circuit.num_qubits , 'q')\n    if circuit.cregs:\n        creg = QuantumRegister(len(circuit.cregs) , 'c')\n        circ = QuantumCircuit(qreg, creg)\n    else:\n        circ = QuantumCircuit(qreg)\n\n    for instr, qargs, cargs in circuit._data:\n        qreg = [ reg.index for reg in qargs ]\n        circ.append(instr, qreg)\n\n    return circ\n```\n\n\n```python\nnode_stack = {}\ncircuit_stack = {}\n \ndef callback(node, circuit, prefix):\n    circuit_stack[prefix] = circuit\n    node_stack[prefix] = node\n\ncircuit = generate_circuit( 6, 6, \"supremacy\" )\npnode = cut(circuit)\n# clean_name_tree(pnode)\n\n\n# for pre, fill, node in RenderTree(pnode):\n#     print(\"%s%s\" % (pre, node.name + \" : \" + str(node.data.num_qubits)))\n\ncomplete_path_map = pnode['complete_path_map'] # get_complete_path_map(pnode)\nsolution = get_solution(circuit, pnode['subcircuits'], complete_path_map)\n\n# pprint(solution)\n\n\nsubcircuits = pnode['subcircuits']\nreconstructed_output, metrics = reconstruct(subcircuits, complete_path_map, circuit, backend=FakeTokyo)\n\npprint(metrics)\n```\n\n    3 subcircuits : NO SOLUTIONS\n    4 subcircuits : NO SOLUTIONS\n    2 subcircuits : NO SOLUTIONS\n    3 subcircuits : NO SOLUTIONS\n    --------------------\n    Cutter result:\n    2 subcircuits, 1 cuts\n    subcircuit 0\n    \u03c1 qubits = 0, O qubits = 1, width = 2, effective = 1, depth = 5, size = 7\n         \u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510          \n    q_0: \u2524 H \u251c\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n         \u251c\u2500\u2500\u2500\u2524 \u2502 \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\n    q_1: \u2524 H \u251c\u2500\u25a0\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 T \u251c\u2524 H \u251c\n         \u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\n    subcircuit 1\n    \u03c1 qubits = 1, O qubits = 0, width = 5, effective = 5, depth = 8, size = 25\n         \u250c\u2500\u2500\u2500\u2510                                \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2510\n    q_0: \u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2524 H \u251c\n         \u251c\u2500\u2500\u2500\u2524\u250c\u2500\u2500\u2500\u2510           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u250c\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2510\u251c\u2500\u2500\u2500\u2524\n    q_1: \u2524 H \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 H \u251c\n         \u251c\u2500\u2500\u2500\u2524\u251c\u2500\u2500\u2500\u2524     \u2502     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518          \u2502     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u251c\u2500\u2500\u2500\u2524\n    q_2: \u2524 H \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2524 H \u251c\n         \u251c\u2500\u2500\u2500\u2524\u2514\u2500\u2500\u2500\u2518     \u2502     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2510        \u2502     \u2514\u2500\u2500\u2500\u2518\n    q_3: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2524 H \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n         \u251c\u2500\u2500\u2500\u2524  \u2502  \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u2514\u2500\u2500\u252c\u2500\u2500\u2500\u252c\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2518        \u2502     \u250c\u2500\u2500\u2500\u2510\n    q_4: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2524 H \u251c\n         \u2514\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2518                              \u2514\u2500\u2500\u2500\u2518\n    Classical cost = 2.560e+02. Quantum cost = 7.000e+00. quantum_cost_weight = 1.000\n    Estimated cost = 7.000e+00\n    Model objective value = 7.00e+00\n    MIP runtime: 0.021229982376098633\n    OPTIMAL, MIP gap = 0.0\n    --------------------\n    subcircuits :  [2, 5]\n    subcircuit_instances :  {0: {(('zero', 'zero'), ('I', 'comp')): 0, (('zero', 'zero'), ('X', 'comp')): 1, (('zero', 'zero'), ('Y', 'comp')): 2, (('zero', 'zero'), ('Z', 'comp')): 3}, 1: {(('zero', 'zero', 'zero', 'zero', 'zero'), ('comp', 'comp', 'comp', 'comp', 'comp')): 0, (('one', 'zero', 'zero', 'zero', 'zero'), ('comp', 'comp', 'comp', 'comp', 'comp')): 1, (('plus', 'zero', 'zero', 'zero', 'zero'), ('comp', 'comp', 'comp', 'comp', 'comp')): 2, (('plusI', 'zero', 'zero', 'zero', 'zero'), ('comp', 'comp', 'comp', 'comp', 'comp')): 3}}\n    CIRCUIT\n                                                  \n    node_0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n            \u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510 \u2591    \u250c\u2500\u2510\n    node_1: \u2524 H \u251c\u2500\u25a0\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 T \u251c\u2524 H \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2524M\u251c\n            \u2514\u2500\u2500\u2500\u2518 \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518 \u2591    \u2514\u2565\u2518\n    node_2: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\n                  \u2502                             \u2551 \n    node_3: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\n                  \u2502                             \u2551 \n    node_4: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\n                  \u2502                             \u2551 \n    node_5: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\n            \u250c\u2500\u2500\u2500\u2510 \u2502 \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510           \u2591 \u250c\u2500\u2510 \u2551 \n    node_6: \u2524 H \u251c\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524M\u251c\u2500\u256b\u2500\n            \u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518           \u2591 \u2514\u2565\u2518 \u2551 \n       c: 2/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\n                                             0  1 \n    CIRCUIT\n                                                  \n    node_0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n            \u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510 \u2591    \u250c\u2500\u2510\n    node_1: \u2524 H \u251c\u2500\u25a0\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 T \u251c\u2524 H \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2524M\u251c\n            \u2514\u2500\u2500\u2500\u2518 \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518 \u2591    \u2514\u2565\u2518\n    node_2: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\n                  \u2502                             \u2551 \n    node_3: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\n                  \u2502                             \u2551 \n    node_4: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\n                  \u2502                             \u2551 \n    node_5: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\n            \u250c\u2500\u2500\u2500\u2510 \u2502 \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510      \u2591 \u250c\u2500\u2510 \u2551 \n    node_6: \u2524 H \u251c\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 H \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524M\u251c\u2500\u256b\u2500\n            \u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518      \u2591 \u2514\u2565\u2518 \u2551 \n       c: 2/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\n                                             0  1 \n    CIRCUIT\n                                                    \n    node_0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n            \u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u250c\u2500\u2500\u2500\u2510 \u250c\u2500\u2500\u2500\u2510 \u2591    \u250c\u2500\u2510\n    node_1: \u2524 H \u251c\u2500\u25a0\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u2524 T \u251c\u2500\u2524 H \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2524M\u251c\n            \u2514\u2500\u2500\u2500\u2518 \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2518 \u2591    \u2514\u2565\u2518\n    node_2: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\n                  \u2502                               \u2551 \n    node_3: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\n                  \u2502                               \u2551 \n    node_4: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\n                  \u2502                               \u2551 \n    node_5: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\n            \u250c\u2500\u2500\u2500\u2510 \u2502 \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510 \u2591 \u250c\u2500\u2510 \u2551 \n    node_6: \u2524 H \u251c\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 Sdg \u251c\u2524 H \u251c\u2500\u2591\u2500\u2524M\u251c\u2500\u256b\u2500\n            \u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518 \u2591 \u2514\u2565\u2518 \u2551 \n       c: 2/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\n                                               0  1 \n    CIRCUIT\n             \u250c\u2500\u2500\u2500\u2510                                     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2510\u00bb\n     node_0: \u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2524 H \u251c\u00bb\n             \u251c\u2500\u2500\u2500\u2524     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510             \u2502  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2518\u00bb\n     node_1: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u00bb\n             \u2514\u2500\u2500\u2500\u2518  \u2502  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518             \u2502                          \u2502  \u00bb\n     node_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u00bb\n                    \u2502                               \u2502                          \u2502  \u00bb\n     node_3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u00bb\n                    \u2502                               \u2502                          \u2502  \u00bb\n     node_4: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u00bb\n             \u250c\u2500\u2500\u2500\u2510  \u2502     \u250c\u2500\u2500\u2500\u2510        \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502             \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502  \u00bb\n     node_5: \u2524 H \u251c\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u2500\u253c\u2500\u2500\u00bb\n             \u251c\u2500\u2500\u2500\u2524  \u2502     \u2514\u2500\u2500\u2500\u2518     \u2502  \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u250c\u2500\u2500\u2500\u2510     \u2502     \u2514\u2500\u2500\u252c\u2500\u2500\u2500\u252c\u2500\u2500\u2518  \u2502  \u00bb\n     node_6: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 H \u251c\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u00bb\n             \u2514\u2500\u2500\u2500\u2518                     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518     \u2502        \u2514\u2500\u2500\u2500\u2518        \u00bb\n     node_7: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                                                            \u2502                     \u00bb\n     node_8: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                                                            \u2502                     \u00bb\n     node_9: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n             \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510                                     \u2502                     \u00bb\n    node_10: \u2524 H \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n             \u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518                                                           \u00bb\n        c: 5/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u00bb\n                                                                                  \u00bb\n    \u00ab                    \u2591 \u250c\u2500\u2510            \n    \u00ab node_0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                    \u2591 \u2514\u2565\u2518      \u250c\u2500\u2510   \n    \u00ab node_1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524M\u251c\u2500\u2500\u2500\n    \u00ab                    \u2591  \u2551       \u2514\u2565\u2518   \n    \u00ab node_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab                       \u2551        \u2551    \n    \u00ab node_3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab                       \u2551        \u2551    \n    \u00ab node_4: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab         \u250c\u2500\u2500\u2500\u2510      \u2591  \u2551 \u250c\u2500\u2510    \u2551    \n    \u00ab node_5: \u2524 H \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab         \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2500\u2500\u2510 \u2591  \u2551 \u2514\u2565\u2518    \u2551 \u250c\u2500\u2510\n    \u00ab node_6: \u2500\u2500\u25a0\u2500\u2500\u2524 H \u251c\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2524M\u251c\n    \u00ab           \u2502  \u2514\u2500\u2500\u2500\u2518 \u2591  \u2551  \u2551     \u2551 \u2514\u2565\u2518\n    \u00ab node_7: \u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\n    \u00ab           \u2502           \u2551  \u2551     \u2551  \u2551 \n    \u00ab node_8: \u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\n    \u00ab           \u2502           \u2551  \u2551     \u2551  \u2551 \n    \u00ab node_9: \u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\n    \u00ab           \u2502  \u250c\u2500\u2500\u2500\u2510 \u2591  \u2551  \u2551 \u250c\u2500\u2510 \u2551  \u2551 \n    \u00abnode_10: \u2500\u2500\u25a0\u2500\u2500\u2524 H \u251c\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u256b\u2500\u2500\u256b\u2500\n    \u00ab              \u2514\u2500\u2500\u2500\u2518 \u2591  \u2551  \u2551 \u2514\u2565\u2518 \u2551  \u2551 \n    \u00ab    c: 5/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\n    \u00ab                       0  1  2  3  4 \n    CIRCUIT\n             \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510                                \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2510\u00bb\n     node_0: \u2524 X \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2524 H \u251c\u00bb\n             \u251c\u2500\u2500\u2500\u2524\u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510             \u2502  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2518\u00bb\n     node_1: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u00bb\n             \u2514\u2500\u2500\u2500\u2518  \u2502  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518             \u2502                          \u2502  \u00bb\n     node_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u00bb\n                    \u2502                               \u2502                          \u2502  \u00bb\n     node_3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u00bb\n                    \u2502                               \u2502                          \u2502  \u00bb\n     node_4: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u00bb\n             \u250c\u2500\u2500\u2500\u2510  \u2502     \u250c\u2500\u2500\u2500\u2510        \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502             \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502  \u00bb\n     node_5: \u2524 H \u251c\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u2500\u253c\u2500\u2500\u00bb\n             \u251c\u2500\u2500\u2500\u2524  \u2502     \u2514\u2500\u2500\u2500\u2518     \u2502  \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u250c\u2500\u2500\u2500\u2510     \u2502     \u2514\u2500\u2500\u252c\u2500\u2500\u2500\u252c\u2500\u2500\u2518  \u2502  \u00bb\n     node_6: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 H \u251c\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u00bb\n             \u2514\u2500\u2500\u2500\u2518                     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518     \u2502        \u2514\u2500\u2500\u2500\u2518        \u00bb\n     node_7: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                                                            \u2502                     \u00bb\n     node_8: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                                                            \u2502                     \u00bb\n     node_9: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n             \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510                                     \u2502                     \u00bb\n    node_10: \u2524 H \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n             \u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518                                                           \u00bb\n        c: 5/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u00bb\n                                                                                  \u00bb\n    \u00ab                    \u2591 \u250c\u2500\u2510            \n    \u00ab node_0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                    \u2591 \u2514\u2565\u2518      \u250c\u2500\u2510   \n    \u00ab node_1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524M\u251c\u2500\u2500\u2500\n    \u00ab                    \u2591  \u2551       \u2514\u2565\u2518   \n    \u00ab node_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab                       \u2551        \u2551    \n    \u00ab node_3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab                       \u2551        \u2551    \n    \u00ab node_4: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab         \u250c\u2500\u2500\u2500\u2510      \u2591  \u2551 \u250c\u2500\u2510    \u2551    \n    \u00ab node_5: \u2524 H \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab         \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2500\u2500\u2510 \u2591  \u2551 \u2514\u2565\u2518    \u2551 \u250c\u2500\u2510\n    \u00ab node_6: \u2500\u2500\u25a0\u2500\u2500\u2524 H \u251c\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2524M\u251c\n    \u00ab           \u2502  \u2514\u2500\u2500\u2500\u2518 \u2591  \u2551  \u2551     \u2551 \u2514\u2565\u2518\n    \u00ab node_7: \u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\n    \u00ab           \u2502           \u2551  \u2551     \u2551  \u2551 \n    \u00ab node_8: \u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\n    \u00ab           \u2502           \u2551  \u2551     \u2551  \u2551 \n    \u00ab node_9: \u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\n    \u00ab           \u2502  \u250c\u2500\u2500\u2500\u2510 \u2591  \u2551  \u2551 \u250c\u2500\u2510 \u2551  \u2551 \n    \u00abnode_10: \u2500\u2500\u25a0\u2500\u2500\u2524 H \u251c\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u256b\u2500\u2500\u256b\u2500\n    \u00ab              \u2514\u2500\u2500\u2500\u2518 \u2591  \u2551  \u2551 \u2514\u2565\u2518 \u2551  \u2551 \n    \u00ab    c: 5/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\n    \u00ab                       0  1  2  3  4 \n    CIRCUIT\n             \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510                                \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2510\u00bb\n     node_0: \u2524 H \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2524 H \u251c\u00bb\n             \u251c\u2500\u2500\u2500\u2524\u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510             \u2502  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2518\u00bb\n     node_1: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u00bb\n             \u2514\u2500\u2500\u2500\u2518  \u2502  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518             \u2502                          \u2502  \u00bb\n     node_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u00bb\n                    \u2502                               \u2502                          \u2502  \u00bb\n     node_3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u00bb\n                    \u2502                               \u2502                          \u2502  \u00bb\n     node_4: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u00bb\n             \u250c\u2500\u2500\u2500\u2510  \u2502     \u250c\u2500\u2500\u2500\u2510        \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502             \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502  \u00bb\n     node_5: \u2524 H \u251c\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u2500\u253c\u2500\u2500\u00bb\n             \u251c\u2500\u2500\u2500\u2524  \u2502     \u2514\u2500\u2500\u2500\u2518     \u2502  \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u250c\u2500\u2500\u2500\u2510     \u2502     \u2514\u2500\u2500\u252c\u2500\u2500\u2500\u252c\u2500\u2500\u2518  \u2502  \u00bb\n     node_6: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 H \u251c\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u00bb\n             \u2514\u2500\u2500\u2500\u2518                     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518     \u2502        \u2514\u2500\u2500\u2500\u2518        \u00bb\n     node_7: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                                                            \u2502                     \u00bb\n     node_8: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                                                            \u2502                     \u00bb\n     node_9: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n             \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510                                     \u2502                     \u00bb\n    node_10: \u2524 H \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n             \u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518                                                           \u00bb\n        c: 5/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u00bb\n                                                                                  \u00bb\n    \u00ab                    \u2591 \u250c\u2500\u2510            \n    \u00ab node_0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                    \u2591 \u2514\u2565\u2518      \u250c\u2500\u2510   \n    \u00ab node_1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524M\u251c\u2500\u2500\u2500\n    \u00ab                    \u2591  \u2551       \u2514\u2565\u2518   \n    \u00ab node_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab                       \u2551        \u2551    \n    \u00ab node_3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab                       \u2551        \u2551    \n    \u00ab node_4: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab         \u250c\u2500\u2500\u2500\u2510      \u2591  \u2551 \u250c\u2500\u2510    \u2551    \n    \u00ab node_5: \u2524 H \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab         \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2500\u2500\u2510 \u2591  \u2551 \u2514\u2565\u2518    \u2551 \u250c\u2500\u2510\n    \u00ab node_6: \u2500\u2500\u25a0\u2500\u2500\u2524 H \u251c\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2524M\u251c\n    \u00ab           \u2502  \u2514\u2500\u2500\u2500\u2518 \u2591  \u2551  \u2551     \u2551 \u2514\u2565\u2518\n    \u00ab node_7: \u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\n    \u00ab           \u2502           \u2551  \u2551     \u2551  \u2551 \n    \u00ab node_8: \u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\n    \u00ab           \u2502           \u2551  \u2551     \u2551  \u2551 \n    \u00ab node_9: \u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\n    \u00ab           \u2502  \u250c\u2500\u2500\u2500\u2510 \u2591  \u2551  \u2551 \u250c\u2500\u2510 \u2551  \u2551 \n    \u00abnode_10: \u2500\u2500\u25a0\u2500\u2500\u2524 H \u251c\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u256b\u2500\u2500\u256b\u2500\n    \u00ab              \u2514\u2500\u2500\u2500\u2518 \u2591  \u2551  \u2551 \u2514\u2565\u2518 \u2551  \u2551 \n    \u00ab    c: 5/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\n    \u00ab                       0  1  2  3  4 \n    CIRCUIT\n             \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2510                        \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2510\u00bb\n     node_0: \u2524 H \u251c\u2524 S \u251c\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2524 H \u251c\u00bb\n             \u251c\u2500\u2500\u2500\u2524\u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510             \u2502  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2518\u00bb\n     node_1: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u00bb\n             \u2514\u2500\u2500\u2500\u2518  \u2502  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518             \u2502                          \u2502  \u00bb\n     node_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u00bb\n                    \u2502                               \u2502                          \u2502  \u00bb\n     node_3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u00bb\n                    \u2502                               \u2502                          \u2502  \u00bb\n     node_4: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u00bb\n             \u250c\u2500\u2500\u2500\u2510  \u2502     \u250c\u2500\u2500\u2500\u2510        \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502             \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502  \u00bb\n     node_5: \u2524 H \u251c\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u2500\u253c\u2500\u2500\u00bb\n             \u251c\u2500\u2500\u2500\u2524  \u2502     \u2514\u2500\u2500\u2500\u2518     \u2502  \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u250c\u2500\u2500\u2500\u2510     \u2502     \u2514\u2500\u2500\u252c\u2500\u2500\u2500\u252c\u2500\u2500\u2518  \u2502  \u00bb\n     node_6: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 H \u251c\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u00bb\n             \u2514\u2500\u2500\u2500\u2518                     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518     \u2502        \u2514\u2500\u2500\u2500\u2518        \u00bb\n     node_7: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                                                            \u2502                     \u00bb\n     node_8: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                                                            \u2502                     \u00bb\n     node_9: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n             \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510                                     \u2502                     \u00bb\n    node_10: \u2524 H \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n             \u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518                                                           \u00bb\n        c: 5/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u00bb\n                                                                                  \u00bb\n    \u00ab                    \u2591 \u250c\u2500\u2510            \n    \u00ab node_0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                    \u2591 \u2514\u2565\u2518      \u250c\u2500\u2510   \n    \u00ab node_1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524M\u251c\u2500\u2500\u2500\n    \u00ab                    \u2591  \u2551       \u2514\u2565\u2518   \n    \u00ab node_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab                       \u2551        \u2551    \n    \u00ab node_3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab                       \u2551        \u2551    \n    \u00ab node_4: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab         \u250c\u2500\u2500\u2500\u2510      \u2591  \u2551 \u250c\u2500\u2510    \u2551    \n    \u00ab node_5: \u2524 H \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab         \u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2500\u2500\u2510 \u2591  \u2551 \u2514\u2565\u2518    \u2551 \u250c\u2500\u2510\n    \u00ab node_6: \u2500\u2500\u25a0\u2500\u2500\u2524 H \u251c\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2524M\u251c\n    \u00ab           \u2502  \u2514\u2500\u2500\u2500\u2518 \u2591  \u2551  \u2551     \u2551 \u2514\u2565\u2518\n    \u00ab node_7: \u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\n    \u00ab           \u2502           \u2551  \u2551     \u2551  \u2551 \n    \u00ab node_8: \u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\n    \u00ab           \u2502           \u2551  \u2551     \u2551  \u2551 \n    \u00ab node_9: \u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\n    \u00ab           \u2502  \u250c\u2500\u2500\u2500\u2510 \u2591  \u2551  \u2551 \u250c\u2500\u2510 \u2551  \u2551 \n    \u00abnode_10: \u2500\u2500\u25a0\u2500\u2500\u2524 H \u251c\u2500\u2591\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u256b\u2500\u2500\u256b\u2500\n    \u00ab              \u2514\u2500\u2500\u2500\u2518 \u2591  \u2551  \u2551 \u2514\u2565\u2518 \u2551  \u2551 \n    \u00ab    c: 5/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\n    \u00ab                       0  1  2  3  4 \n    subcircuit_instance_probs :  ['0: 4    ', '1: 4    ']\n    subcircuit_order (0, 1). overhead = {'additions': 192, 'multiplications': 256}.\n    {'naive': {'Cross Entropy': 4.21422140494848,\n               'HOP': 0.4917745590209961,\n               'Mean Absolute Percentage Error': 349.13765151809974,\n               'Mean Squared Error': 0.00027654666389005536,\n               'chi2': 0.4549210575715243},\n     'nearest': {'Cross Entropy': 4.21422140494848,\n                 'HOP': 0.4917745590209961,\n                 'Mean Absolute Percentage Error': 349.13765151809974,\n                 'Mean Squared Error': 0.00027654666389005536,\n                 'chi2': 0.4549210575715243}}\n\n\n\n```python\nnode_stack = {}\ncircuit_stack = {}\n \ndef callback(node, circuit, prefix):\n    circuit_stack[prefix] = circuit\n    node_stack[prefix] = node\n\ncircuit = generate_circuit( 6, 12, \"supremacy_linear\" )\npnode = cut(circuit)\n# clean_name_tree(pnode)\n\n\n# for pre, fill, node in RenderTree(pnode):\n#     print(\"%s%s\" % (pre, node.name + \" : \" + str(node.data.num_qubits)))\n\ncomplete_path_map = pnode['complete_path_map'] # get_complete_path_map(pnode)\nsolution = get_solution(circuit, pnode['subcircuits'], complete_path_map)\n\n# pprint(solution)\n\n\nsubcircuits = pnode['subcircuits']\nreconstructed_output, metrics = reconstruct(subcircuits, complete_path_map, circuit, backend=FakeTokyo)\n\npprint(metrics)\n```\n\n    3 subcircuits : NO SOLUTIONS\n    4 subcircuits : NO SOLUTIONS\n    2 subcircuits : NO SOLUTIONS\n    3 subcircuits : NO SOLUTIONS\n    --------------------\n    Cutter result:\n    2 subcircuits, 1 cuts\n    subcircuit 0\n    \u03c1 qubits = 0, O qubits = 1, width = 4, effective = 3, depth = 11, size = 28\n         \u250c\u2500\u2500\u2500\u2510     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510                           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\u00bb\n    q_0: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u00bb\n         \u251c\u2500\u2500\u2500\u2524  \u2502  \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510     \u2502     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u2514\u2500\u2500\u2500\u2518\u00bb\n    q_1: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u2500\u25a0\u2500\u2500\u00bb\n         \u251c\u2500\u2500\u2500\u2524\u250c\u2500\u2500\u2500\u2510\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518  \u2502  \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u2514\u2500\u2500\u252c\u2500\u2500\u2500\u252c\u2500\u2500\u2518  \u2502  \u00bb\n    q_2: \u2524 H \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u00bb\n         \u251c\u2500\u2500\u2500\u2524\u251c\u2500\u2500\u2500\u2524                \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518  \u2502  \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524   \u2514\u2500\u2500\u2500\u2518        \u00bb\n    q_3: \u2524 H \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n         \u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518                                \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518                \u00bb\n    \u00ab        \u250c\u2500\u2500\u2500\u2510        \n    \u00abq_0: \u2500\u2500\u2500\u2524 H \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab     \u250c\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\n    \u00abq_1: \u2524 Rx(\u03c0/2) \u251c\u2524 H \u251c\n    \u00ab     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u251c\u2500\u2500\u2500\u2524\n    \u00abq_2: \u2524 Ry(\u03c0/2) \u251c\u2524 H \u251c\n    \u00ab     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\n    \u00abq_3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                     \n    subcircuit 1\n    \u03c1 qubits = 1, O qubits = 0, width = 3, effective = 3, depth = 10, size = 19\n                                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2510             \n    q_0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2524 H \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n         \u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510 \u2502 \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\n    q_1: \u2524 H \u251c\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2524 H \u251c\n         \u251c\u2500\u2500\u2500\u2524 \u2502 \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u251c\u2500\u2500\u2500\u2524   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518  \u2502  \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u251c\u2500\u2500\u2500\u2524\u251c\u2500\u2500\u2500\u2524\n    q_2: \u2524 H \u251c\u2500\u25a0\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 T \u251c\u2524 H \u251c\n         \u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518                   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\n    Classical cost = 2.560e+02. Quantum cost = 7.000e+00. quantum_cost_weight = 1.000\n    Estimated cost = 7.000e+00\n    Model objective value = 7.00e+00\n    MIP runtime: 0.022217988967895508\n    OPTIMAL, MIP gap = 0.0\n    --------------------\n    subcircuits :  [4, 3]\n    subcircuit_instances :  {0: {(('zero', 'zero', 'zero', 'zero'), ('comp', 'comp', 'comp', 'I')): 0, (('zero', 'zero', 'zero', 'zero'), ('comp', 'comp', 'comp', 'X')): 1, (('zero', 'zero', 'zero', 'zero'), ('comp', 'comp', 'comp', 'Y')): 2, (('zero', 'zero', 'zero', 'zero'), ('comp', 'comp', 'comp', 'Z')): 3}, 1: {(('zero', 'zero', 'zero'), ('comp', 'comp', 'comp')): 0, (('one', 'zero', 'zero'), ('comp', 'comp', 'comp')): 1, (('plus', 'zero', 'zero'), ('comp', 'comp', 'comp')): 2, (('plusI', 'zero', 'zero'), ('comp', 'comp', 'comp')): 3}}\n    CIRCUIT\n            \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510                \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510           \u00bb\n    node_0: \u2524 H \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n            \u251c\u2500\u2500\u2500\u2524\u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502  \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502 \u2514\u2500\u2500\u252c\u2500\u2500\u2500\u252c\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u00bb\n    node_1: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u2500\u253c\u2500\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u00bb\n            \u2514\u2500\u2500\u2500\u2518  \u2502  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502    \u2514\u2500\u2500\u2500\u2518     \u2502  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u00bb\n    node_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                   \u2502                              \u2502              \u2502             \u00bb\n    node_3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                   \u2502                              \u2502              \u2502             \u00bb\n    node_4: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n            \u250c\u2500\u2500\u2500\u2510  \u2502     \u250c\u2500\u2500\u2500\u2510                    \u2502 \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502             \u00bb\n    node_5: \u2524 H \u251c\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n            \u251c\u2500\u2500\u2500\u2524  \u2502  \u250c\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510              \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518  \u2502  \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u00bb\n    node_6: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u00bb\n            \u2514\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518                              \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u00bb\n       c: 4/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u00bb\n                                                                               \u00bb\n    \u00ab             \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510 \u2591       \u250c\u2500\u2510   \n    \u00abnode_0: \u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 H \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524M\u251c\u2500\u2500\u2500\n    \u00ab          \u2502  \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u251c\u2500\u2500\u2500\u2524 \u2591    \u250c\u2500\u2510\u2514\u2565\u2518   \n    \u00abnode_1: \u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 H \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2524M\u251c\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab             \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518 \u2591    \u2514\u2565\u2518 \u2551    \n    \u00abnode_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab                                    \u2551  \u2551    \n    \u00abnode_3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab                                    \u2551  \u2551    \n    \u00abnode_4: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab                              \u2591     \u2551  \u2551 \u250c\u2500\u2510\n    \u00abnode_5: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2524M\u251c\n    \u00ab        \u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2510         \u2591 \u250c\u2500\u2510 \u2551  \u2551 \u2514\u2565\u2518\n    \u00abnode_6: \u2524 T \u251c\u2500\u2500\u2500\u2524 H \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524M\u251c\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\n    \u00ab        \u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2518         \u2591 \u2514\u2565\u2518 \u2551  \u2551  \u2551 \n    \u00ab   c: 4/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\n    \u00ab                                 0  1  2  3 \n    CIRCUIT\n            \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510                \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510           \u00bb\n    node_0: \u2524 H \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n            \u251c\u2500\u2500\u2500\u2524\u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502  \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502 \u2514\u2500\u2500\u252c\u2500\u2500\u2500\u252c\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u00bb\n    node_1: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u2500\u253c\u2500\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u00bb\n            \u2514\u2500\u2500\u2500\u2518  \u2502  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502    \u2514\u2500\u2500\u2500\u2518     \u2502  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u00bb\n    node_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                   \u2502                              \u2502              \u2502             \u00bb\n    node_3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                   \u2502                              \u2502              \u2502             \u00bb\n    node_4: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n            \u250c\u2500\u2500\u2500\u2510  \u2502     \u250c\u2500\u2500\u2500\u2510                    \u2502 \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502     \u250c\u2500\u2500\u2500\u2510   \u00bb\n    node_5: \u2524 H \u251c\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2524 H \u251c\u2500\u2500\u2500\u00bb\n            \u251c\u2500\u2500\u2500\u2524  \u2502  \u250c\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510              \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518  \u2502  \u250c\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2510\u00bb\n    node_6: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u00bb\n            \u2514\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518                              \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u00bb\n       c: 4/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u00bb\n                                                                               \u00bb\n    \u00ab             \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510 \u2591       \u250c\u2500\u2510   \n    \u00abnode_0: \u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 H \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524M\u251c\u2500\u2500\u2500\n    \u00ab          \u2502  \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u251c\u2500\u2500\u2500\u2524 \u2591    \u250c\u2500\u2510\u2514\u2565\u2518   \n    \u00abnode_1: \u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 H \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2524M\u251c\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab             \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518 \u2591    \u2514\u2565\u2518 \u2551    \n    \u00abnode_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab                                    \u2551  \u2551    \n    \u00abnode_3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab                                    \u2551  \u2551    \n    \u00abnode_4: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab                              \u2591     \u2551  \u2551 \u250c\u2500\u2510\n    \u00abnode_5: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2524M\u251c\n    \u00ab        \u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2510         \u2591 \u250c\u2500\u2510 \u2551  \u2551 \u2514\u2565\u2518\n    \u00abnode_6: \u2524 T \u251c\u2500\u2500\u2500\u2524 H \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524M\u251c\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\n    \u00ab        \u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2518         \u2591 \u2514\u2565\u2518 \u2551  \u2551  \u2551 \n    \u00ab   c: 4/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\n    \u00ab                                 0  1  2  3 \n    CIRCUIT\n            \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510                \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510           \u00bb\n    node_0: \u2524 H \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n            \u251c\u2500\u2500\u2500\u2524\u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502  \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502 \u2514\u2500\u2500\u252c\u2500\u2500\u2500\u252c\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u00bb\n    node_1: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u2500\u253c\u2500\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u00bb\n            \u2514\u2500\u2500\u2500\u2518  \u2502  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502    \u2514\u2500\u2500\u2500\u2518     \u2502  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u00bb\n    node_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                   \u2502                              \u2502              \u2502             \u00bb\n    node_3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                   \u2502                              \u2502              \u2502             \u00bb\n    node_4: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n            \u250c\u2500\u2500\u2500\u2510  \u2502     \u250c\u2500\u2500\u2500\u2510                    \u2502 \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502    \u250c\u2500\u2500\u2500\u2500\u2500\u2510  \u00bb\n    node_5: \u2524 H \u251c\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2524 Sdg \u251c\u2500\u2500\u00bb\n            \u251c\u2500\u2500\u2500\u2524  \u2502  \u250c\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510              \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518  \u2502  \u250c\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2510\u00bb\n    node_6: \u2524 H \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u00bb\n            \u2514\u2500\u2500\u2500\u2518     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518                              \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u00bb\n       c: 4/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u00bb\n                                                                               \u00bb\n    \u00ab             \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510 \u2591       \u250c\u2500\u2510   \n    \u00abnode_0: \u2500\u2500\u25a0\u2500\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 H \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524M\u251c\u2500\u2500\u2500\n    \u00ab          \u2502  \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u251c\u2500\u2500\u2500\u2524 \u2591    \u250c\u2500\u2510\u2514\u2565\u2518   \n    \u00abnode_1: \u2500\u2500\u25a0\u2500\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 H \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2524M\u251c\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab             \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518 \u2591    \u2514\u2565\u2518 \u2551    \n    \u00abnode_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab                                    \u2551  \u2551    \n    \u00abnode_3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab                                    \u2551  \u2551    \n    \u00abnode_4: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u2500\u2500\n    \u00ab        \u250c\u2500\u2500\u2500\u2510                 \u2591     \u2551  \u2551 \u250c\u2500\u2510\n    \u00abnode_5: \u2524 H \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2524M\u251c\n    \u00ab        \u251c\u2500\u2500\u2500\u2524   \u250c\u2500\u2500\u2500\u2510         \u2591 \u250c\u2500\u2510 \u2551  \u2551 \u2514\u2565\u2518\n    \u00abnode_6: \u2524 T \u251c\u2500\u2500\u2500\u2524 H \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524M\u251c\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\n    \u00ab        \u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2518         \u2591 \u2514\u2565\u2518 \u2551  \u2551  \u2551 \n    \u00ab   c: 4/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\n    \u00ab                                 0  1  2  3 \n    CIRCUIT\n                                                                                   \u00bb\n    node_0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n            \u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510                 \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510 \u2591       \u00bb\n    node_1: \u2524 H \u251c\u2500\u25a0\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 T \u251c\u2524 H \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n            \u2514\u2500\u2500\u2500\u2518 \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518               \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518 \u2591       \u00bb\n    node_2: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                  \u2502                                \u2502                               \u00bb\n    node_3: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                  \u2502                                \u2502                               \u00bb\n    node_4: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                  \u2502                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502    \u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2510      \u2591 \u250c\u2500\u2510   \u00bb\n    node_5: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2500\u253c\u2500\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2524 H \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524M\u251c\u2500\u2500\u2500\u00bb\n            \u250c\u2500\u2500\u2500\u2510 \u2502 \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510 \u2502 \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502 \u250c\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2510\u251c\u2500\u2500\u2500\u2524\u250c\u2500\u2500\u2500\u2510 \u2591 \u2514\u2565\u2518\u250c\u2500\u2510\u00bb\n    node_6: \u2524 H \u251c\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2524 H \u251c\u2500\u2591\u2500\u2500\u256b\u2500\u2524M\u251c\u00bb\n            \u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518 \u2591  \u2551 \u2514\u2565\u2518\u00bb\n       c: 3/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u00bb\n                                                                              0  1 \u00bb\n    \u00ab           \n    \u00abnode_0: \u2500\u2500\u2500\n    \u00ab        \u250c\u2500\u2510\n    \u00abnode_1: \u2524M\u251c\n    \u00ab        \u2514\u2565\u2518\n    \u00abnode_2: \u2500\u256b\u2500\n    \u00ab         \u2551 \n    \u00abnode_3: \u2500\u256b\u2500\n    \u00ab         \u2551 \n    \u00abnode_4: \u2500\u256b\u2500\n    \u00ab         \u2551 \n    \u00abnode_5: \u2500\u256b\u2500\n    \u00ab         \u2551 \n    \u00abnode_6: \u2500\u256b\u2500\n    \u00ab         \u2551 \n    \u00ab   c: 3/\u2550\u2569\u2550\n    \u00ab         2 \n    CIRCUIT\n                                                                                   \u00bb\n    node_0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n            \u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510                 \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510 \u2591       \u00bb\n    node_1: \u2524 H \u251c\u2500\u25a0\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 T \u251c\u2524 H \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n            \u2514\u2500\u2500\u2500\u2518 \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518               \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518 \u2591       \u00bb\n    node_2: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                  \u2502                                \u2502                               \u00bb\n    node_3: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                  \u2502                                \u2502                               \u00bb\n    node_4: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n            \u250c\u2500\u2500\u2500\u2510 \u2502                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502    \u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2510      \u2591 \u250c\u2500\u2510   \u00bb\n    node_5: \u2524 X \u251c\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2500\u253c\u2500\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2524 H \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524M\u251c\u2500\u2500\u2500\u00bb\n            \u251c\u2500\u2500\u2500\u2524 \u2502 \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510 \u2502 \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502 \u250c\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2510\u251c\u2500\u2500\u2500\u2524\u250c\u2500\u2500\u2500\u2510 \u2591 \u2514\u2565\u2518\u250c\u2500\u2510\u00bb\n    node_6: \u2524 H \u251c\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2524 H \u251c\u2500\u2591\u2500\u2500\u256b\u2500\u2524M\u251c\u00bb\n            \u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518 \u2591  \u2551 \u2514\u2565\u2518\u00bb\n       c: 3/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u00bb\n                                                                              0  1 \u00bb\n    \u00ab           \n    \u00abnode_0: \u2500\u2500\u2500\n    \u00ab        \u250c\u2500\u2510\n    \u00abnode_1: \u2524M\u251c\n    \u00ab        \u2514\u2565\u2518\n    \u00abnode_2: \u2500\u256b\u2500\n    \u00ab         \u2551 \n    \u00abnode_3: \u2500\u256b\u2500\n    \u00ab         \u2551 \n    \u00abnode_4: \u2500\u256b\u2500\n    \u00ab         \u2551 \n    \u00abnode_5: \u2500\u256b\u2500\n    \u00ab         \u2551 \n    \u00abnode_6: \u2500\u256b\u2500\n    \u00ab         \u2551 \n    \u00ab   c: 3/\u2550\u2569\u2550\n    \u00ab         2 \n    CIRCUIT\n                                                                                   \u00bb\n    node_0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n            \u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510                 \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510 \u2591       \u00bb\n    node_1: \u2524 H \u251c\u2500\u25a0\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 T \u251c\u2524 H \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n            \u2514\u2500\u2500\u2500\u2518 \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518               \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518 \u2591       \u00bb\n    node_2: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                  \u2502                                \u2502                               \u00bb\n    node_3: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                  \u2502                                \u2502                               \u00bb\n    node_4: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n            \u250c\u2500\u2500\u2500\u2510 \u2502                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502    \u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2510      \u2591 \u250c\u2500\u2510   \u00bb\n    node_5: \u2524 H \u251c\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2500\u253c\u2500\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2524 H \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524M\u251c\u2500\u2500\u2500\u00bb\n            \u251c\u2500\u2500\u2500\u2524 \u2502 \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510 \u2502 \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502 \u250c\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2510\u251c\u2500\u2500\u2500\u2524\u250c\u2500\u2500\u2500\u2510 \u2591 \u2514\u2565\u2518\u250c\u2500\u2510\u00bb\n    node_6: \u2524 H \u251c\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2524 H \u251c\u2500\u2591\u2500\u2500\u256b\u2500\u2524M\u251c\u00bb\n            \u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518 \u2591  \u2551 \u2514\u2565\u2518\u00bb\n       c: 3/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u00bb\n                                                                              0  1 \u00bb\n    \u00ab           \n    \u00abnode_0: \u2500\u2500\u2500\n    \u00ab        \u250c\u2500\u2510\n    \u00abnode_1: \u2524M\u251c\n    \u00ab        \u2514\u2565\u2518\n    \u00abnode_2: \u2500\u256b\u2500\n    \u00ab         \u2551 \n    \u00abnode_3: \u2500\u256b\u2500\n    \u00ab         \u2551 \n    \u00abnode_4: \u2500\u256b\u2500\n    \u00ab         \u2551 \n    \u00abnode_5: \u2500\u256b\u2500\n    \u00ab         \u2551 \n    \u00abnode_6: \u2500\u256b\u2500\n    \u00ab         \u2551 \n    \u00ab   c: 3/\u2550\u2569\u2550\n    \u00ab         2 \n    CIRCUIT\n                                                                                   \u00bb\n    node_0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n            \u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510                 \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510 \u2591       \u00bb\n    node_1: \u2524 H \u251c\u2500\u25a0\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 T \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2524 Rx(\u03c0/2) \u251c\u2524 T \u251c\u2524 H \u251c\u2500\u2591\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n            \u2514\u2500\u2500\u2500\u2518 \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518               \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518 \u2591       \u00bb\n    node_2: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                  \u2502                                \u2502                               \u00bb\n    node_3: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                  \u2502                                \u2502                               \u00bb\n    node_4: \u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n            \u250c\u2500\u2500\u2500\u2510 \u2502    \u250c\u2500\u2500\u2500\u2510           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502    \u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2510      \u2591 \u250c\u2500\u2510   \u00bb\n    node_5: \u2524 H \u251c\u2500\u253c\u2500\u2500\u2500\u2500\u2524 S \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2500\u253c\u2500\u2500\u2500\u2500\u2524 T \u251c\u2500\u2500\u2500\u2524 H \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2591\u2500\u2524M\u251c\u2500\u2500\u2500\u00bb\n            \u251c\u2500\u2500\u2500\u2524 \u2502 \u250c\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2510 \u2502 \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502 \u250c\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2510\u251c\u2500\u2500\u2500\u2524\u250c\u2500\u2500\u2500\u2510 \u2591 \u2514\u2565\u2518\u250c\u2500\u2510\u00bb\n    node_6: \u2524 H \u251c\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2500\u25a0\u2500\u2524 Ry(\u03c0/2) \u251c\u2524 T \u251c\u2524 H \u251c\u2500\u2591\u2500\u2500\u256b\u2500\u2524M\u251c\u00bb\n            \u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518 \u2591  \u2551 \u2514\u2565\u2518\u00bb\n       c: 3/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u00bb\n                                                                              0  1 \u00bb\n    \u00ab           \n    \u00abnode_0: \u2500\u2500\u2500\n    \u00ab        \u250c\u2500\u2510\n    \u00abnode_1: \u2524M\u251c\n    \u00ab        \u2514\u2565\u2518\n    \u00abnode_2: \u2500\u256b\u2500\n    \u00ab         \u2551 \n    \u00abnode_3: \u2500\u256b\u2500\n    \u00ab         \u2551 \n    \u00abnode_4: \u2500\u256b\u2500\n    \u00ab         \u2551 \n    \u00abnode_5: \u2500\u256b\u2500\n    \u00ab         \u2551 \n    \u00abnode_6: \u2500\u256b\u2500\n    \u00ab         \u2551 \n    \u00ab   c: 3/\u2550\u2569\u2550\n    \u00ab         2 \n    subcircuit_instance_probs :  ['0: 4    ', '1: 4    ']\n    subcircuit_order (0, 1). overhead = {'additions': 192, 'multiplications': 256}.\n    {'naive': {'Cross Entropy': 4.323429338744058,\n               'HOP': 0.43170976638793945,\n               'Mean Absolute Percentage Error': 294.8487542368127,\n               'Mean Squared Error': 0.0003846859154659857,\n               'chi2': 0.505260271278594},\n     'nearest': {'Cross Entropy': 4.323429338744058,\n                 'HOP': 0.43170976638793945,\n                 'Mean Absolute Percentage Error': 294.8487542368127,\n                 'Mean Squared Error': 0.0003846859154659857,\n                 'chi2': 0.505260271278594}}\n\n\n\n```python\n# print(Tket(circuit, FakeTokyo).draw())\n# tket_rename_nodes(Tket(circuit, FakeTokyo)).draw()\n```\n\n\n```python\nfrom qiskit import QuantumCircuit, execute\n\nclass CircuitLargerThanChip(Exception):\n    pass\n\ndef check_chip_compatiblity(backend, circuit, raise_exception=True):\n    if backend._configuration.n_qubits < circuit.num_qubits:\n        if raise_exception:\n            raise CircuitLargerThanChip(\"Circuit is larger than chip size.\")\n        else:\n            return False\n    return True\n\nclass Schedular:\n    def __init__(self, backend_list):\n        self.backend_list = backend_list\n        self.backend_sizes = { backend()._configuration.n_qubits: backend for backend in backend_list }\n        self.backend_run_stack = { backend: [] for backend in backend_list }\n        self.pnode = None\n        self.smallest_chip_size = min([device()._configuration.n_qubits for device in backend_list])\n        self.node_stack = {}\n        self.circuit_stack = {}\n        \n    def callback(self, node, circuit, prefix):\n        self.circuit_stack[prefix] = circuit\n        self.node_stack[prefix] = node\n\n    def __call__(self, circuit):\n        self.pnode = recursive_cut(circuit, callback=self.callback, min_qubit=self.smallest_chip_size)\n        [ self.alot(circuit) for circuit in list(self.circuit_stack.values()) ]\n\n        # Distribute the circuit if some devices are free\n        \n\n        run_stack_size = [ len(run_stack) for backend, run_stack in self.backend_run_stack.items() ]\n        \n        empty_devices = [backend for backend, run_stack in self.backend_run_stack.items() if len(run_stack) == 0]\n        most_busy_devices = [backend for backend, run_stack in self.backend_run_stack.items() if len(run_stack) == max(run_stack_size)]\n        least_busy_devices = [backend for backend, run_stack in self.backend_run_stack.items() if len(run_stack) == min(run_stack_size)]\n        \n        # Device needed to be freed\n        most_busy = [ (backend, run_stack) for backend, run_stack in self.backend_run_stack.items() if len(run_stack) == max(run_stack_size) ]\n\n\n        for (backend, run_stack) in most_busy:\n            size = len(run_stack)\n            new_run_stack_1 = run_stack[:int(size//2)]\n            new_run_stack_2 = run_stack[int(size//2):]\n\n            self.backend_run_stack[backend] = new_run_stack_1\n\n            allocated = False\n            for devices in empty_devices:\n                if check_chip_compatiblity(devices(), circuit, raise_exception=False):\n                    self.backend_run_stack[devices] += new_run_stack_2\n                    allocated = True\n            if not allocated :\n                self.backend_run_stack[backend] += new_run_stack_2\n\n        subcircuits = list( self.circuit_stack.values() )\n        # print(subcircuits)\n        complete_path_map = get_complete_path_map(self.pnode)\n\n        solution = get_solution(circuit, subcircuits, complete_path_map)\n        reconstructed_output, metrics = reconstruct(subcircuits, complete_path_map, circuit, backend_run_stack = self.backend_run_stack, verbose=False)\n\n        return (reconstructed_output, metrics, subcircuits) # self.backend_run_stack\n\n    def alot(self, circuit, tket=False):\n        # Fill `backend_run_stack` in order from low to high\n        size_list = list(self.backend_sizes.keys())\n        size_list = list(sorted(list(size_list)))\n        for size in size_list:\n            backend = self.backend_sizes[size]\n            if check_chip_compatiblity(backend(), circuit, raise_exception=False):\n                self.backend_run_stack[backend] += [circuit]\n                return backend\n        raise Exception(\"Circuit too big for available devices.\")\n\n    def kernal(self, circuit):\n        pass\n```\n\n\n```python\n{ name:device()._configuration.n_qubits for name, device in available_backend.items() }\n```\n\n\n\n\n    {'FakeMelbourne': 14,\n     'FakePoughkeepsie': 20,\n     'FakeRueschlikon': 16,\n     'FakeTenerife': 5,\n     'FakeTokyo': 20,\n     'FakeVigo': 5}\n\n\n\n\n```python\n!rm ./*.pickle\n```\n\n    rm: cannot remove './*.pickle': No such file or directory\n\n\n\n```python\n!rm -r bv_data\n```\n\n    rm: cannot remove 'bv_data': No such file or directory\n\n\n\n```python\nimport pickle\n\ndef save(obj, filename):\n    with open(f'{filename}.pickle', 'wb') as handle:\n        pickle.dump(obj, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\nmetrics_list = []\n\nbackend_list = list(available_backend.values())\n\ncircuit_list = { f\"cirucit [bv-{qubit}-{depth}]\": generate_circuit( qubit, depth, \"bv\" ) for qubit in range(6, 17) for depth in range(10, 20) }\n\nfor name, circ in circuit_list.items():\n    schedule = Schedular(backend_list)\n    # print(circ.draw())\n    reconstructed_output, metrics = schedule(circ)\n    metrics_list += [ metrics ]\n    save({\"reconstructed_output\": reconstructed_output, \"metrics\": metrics}, name)\n\n```\n\n\n```python\navailable_backend = {\n    # \"FakeTokyo\": FakeTokyo, # 20\n    \"FakeVigo\": FakeVigo, # 5\n    # \"FakeMelbourne\": FakeMelbourne, # 14\n    # \"FakePoughkeepsie\": FakePoughkeepsie, # 20\n    # \"FakeRueschlikon\": FakeRueschlikon, # 16\n    \"FakeTenerife\": FakeTenerife # 5\n}\npprint( { name:device()._configuration.n_qubits for name, device in available_backend.items() } )\nbackend_list = list(available_backend.values())\n\n\n# circuit = generate_circuit( 16, 18, \"grover\" )\ncircuit_list = {}\ncircuit_list['circuit [supremacy-6-6]'] = generate_circ(num_qubits=6, depth=6,circuit_type='supremacy')\ncircuit_list['circuit [supremacy_linear-8-8]'] = generate_circ(num_qubits=8, depth=8,circuit_type='supremacy_linear')\ncircuit_list['circuit [vazirani-16-16]'] = generate_circuit( 16, 16, \"bv\" )\n\n\nfor name, circuit in circuit_list.items():\n    schedule = Schedular(backend_list)\n    reconstructed_output, metrics, subcircuits = schedule(circuit)\n    metrics_list += [ metrics ]\n    print(subcircuits)\n    save({\"reconstructed_output\": reconstructed_output, \"metrics\": metrics, \"subcircuits\": subcircuits, \"parent.circuit\": circuit}, name)\n\n```\n\n\n```python\n!mkdir \"bv_data\"\n!mkdir \"bv_data/base/\"\n!mkdir \"bv_data/tket/\"\n!cp -r ./*.pickle ./bv_data/tket/\n```\n\n    mkdir: cannot create directory \u2018bv_data\u2019: File exists\n    mkdir: cannot create directory \u2018bv_data/base/\u2019: File exists\n    mkdir: cannot create directory \u2018bv_data/tket/\u2019: File exists\n\n\n\n```python\n!zip -r bv_data.zip bv_data\n```\n\n      adding: bv_data/ (stored 0%)\n      adding: bv_data/base/ (stored 0%)\n      adding: bv_data/base/cirucit [bv-7].pickle (deflated 74%)\n      adding: bv_data/base/cirucit [bv-16].pickle (deflated 48%)\n      adding: bv_data/base/cirucit [bv-12].pickle (deflated 89%)\n      adding: bv_data/base/cirucit [bv-15].pickle (deflated 11%)\n      adding: bv_data/base/cirucit [bv-9].pickle (deflated 65%)\n      adding: bv_data/base/cirucit [bv-13].pickle (deflated 94%)\n      adding: bv_data/base/cirucit [bv-10].pickle (deflated 71%)\n      adding: bv_data/base/cirucit [bv-11].pickle (deflated 78%)\n      adding: bv_data/base/cirucit [bv-6].pickle (deflated 58%)\n      adding: bv_data/base/cirucit [bv-8].pickle (deflated 60%)\n      adding: bv_data/base/cirucit [bv-14].pickle (deflated 79%)\n      adding: bv_data/tket/ (stored 0%)\n      adding: bv_data/tket/tket cirucit [bv-15].pickle (deflated 14%)\n      adding: bv_data/tket/tket cirucit [bv-6].pickle (deflated 54%)\n      adding: bv_data/tket/tket cirucit [bv-13].pickle (deflated 94%)\n      adding: bv_data/tket/tket cirucit [bv-16].pickle (deflated 48%)\n      adding: bv_data/tket/tket cirucit [bv-11].pickle (deflated 79%)\n      adding: bv_data/tket/tket cirucit [bv-14].pickle (deflated 79%)\n      adding: bv_data/tket/tket cirucit [bv-12].pickle (deflated 89%)\n      adding: bv_data/tket/tket cirucit [bv-10].pickle (deflated 70%)\n      adding: bv_data/tket/tket cirucit [bv-7].pickle (deflated 74%)\n      adding: bv_data/tket/tket cirucit [bv-9].pickle (deflated 66%)\n      adding: bv_data/tket/tket cirucit [bv-8].pickle (deflated 60%)\n\n\n\n```python\nmetrics_list[0]\n```\n\n\n\n\n    {'naive': {'Cross Entropy': 1.1566534090169873,\n      'HOP': 0.31453704833984375,\n      'Mean Absolute Percentage Error': 1.071035861968994e+16,\n      'Mean Squared Error': 0.008262061045058996,\n      'chi2': 1.042896360396752},\n     'nearest': {'Cross Entropy': 1.1566534090169873,\n      'HOP': 0.31453704833984375,\n      'Mean Absolute Percentage Error': 1.071035861968994e+16,\n      'Mean Squared Error': 0.008262061045058996,\n      'chi2': 1.042896360396752}}\n\n\n\n\n```python\n# importing the required libraries\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef draw(line1, line2, title, start_from = 0):\n    plt.plot([i for i in range(start_from, start_from+len(line1))], line1) # Plot the chart\n    plt.plot([i for i in range(start_from, start_from+len(line2))], line2, '-.') # Plot the chart\n    # plt.xlabel(\"X-axis data\")\n    # plt.ylabel(\"Y-axis data\")\n    plt.title(title)\n    plt.show() # display\n\ndef plot_metric(metrics_list, column):\n    hop_naive = [metric['naive'][column]  for metric in metrics_list]\n    hop_nearest = [metric['nearest'][column]  for metric in metrics_list]\n\n    draw(hop_naive, hop_nearest, column, 6)\n\nplot_metric(metrics_list, 'Cross Entropy')\nplot_metric(metrics_list, 'Mean Squared Error')\nplot_metric(metrics_list, 'Mean Absolute Percentage Error')\nplot_metric(metrics_list, 'chi2')\nplot_metric(metrics_list, 'HOP')\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "bd770b8dbcbfb91fc034edfbab893bbc3cac9e12", "size": 279619, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Copy_of_CutQC_Workpad_1.ipynb", "max_stars_repo_name": "LegacYFTw/qurzon", "max_stars_repo_head_hexsha": "ae6877e11b062102a736468d1ec054f78fff8424", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-28T15:11:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T15:11:39.000Z", "max_issues_repo_path": "notebooks/Copy_of_CutQC_Workpad_1.ipynb", "max_issues_repo_name": "LegacYFTw/qurzon", "max_issues_repo_head_hexsha": "ae6877e11b062102a736468d1ec054f78fff8424", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/Copy_of_CutQC_Workpad_1.ipynb", "max_forks_repo_name": "LegacYFTw/qurzon", "max_forks_repo_head_hexsha": "ae6877e11b062102a736468d1ec054f78fff8424", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 99.7926481085, "max_line_length": 17150, "alphanum_fraction": 0.643883284, "converted": true, "num_tokens": 49174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.04672496061726326, "lm_q1q2_score": 0.02281502241526146}}
{"text": "Starting point: https://cloud.google.com/blog/products/gcp/intro-to-text-classification-with-keras-automatically-tagging-stack-overflow-posts\n\n\n```python\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nfrom sklearn import metrics\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.pipeline import Pipeline\n```\n\n# Data, data, data\n\nWe have 5000 StackOverflow posts that have only one tag. We want to use the post to predict what the tag is.\n\n\n```python\nraw_data = pd.read_csv('../data/stackOverflow.csv')\nraw_data.head(10)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>post</th>\n      <th>tag</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>getting absolute path of directory  how do i g...</td>\n      <td>python</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>css  page header/colours show up in safari but...</td>\n      <td>css</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>position absolute is not within the relative p...</td>\n      <td>css</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>extracting individual items resulting from a s...</td>\n      <td>python</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>resizable backgrounds  ok i need to make a who...</td>\n      <td>css</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>why aren t these two divs displayed how i expe...</td>\n      <td>html</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>strange height size top menu  in my top menu f...</td>\n      <td>css</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>what is the space between these elements   wha...</td>\n      <td>html</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>javascript missing semicolon   so i am using j...</td>\n      <td>javascript</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>how can we link a html button   i would like t...</td>\n      <td>html</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nraw_data.tag.unique()\n```\n\n\n\n\n    array(['python', 'css', 'html', 'javascript', 'jquery'], dtype=object)\n\n\n\n\n```python\nraw_data.post[0]\n```\n\n\n\n\n    'getting absolute path of directory  how do i get the absolute path of a directory (it has to be any directory  not the current one!) in python     i tried with <code>os.path.listdir()</code> but it yields only the relative one. thanks!'\n\n\n\nThe tag words probably often occur in the posts, so let's strip them out to make things a bit more challenging.\n\n\n```python\ndata = raw_data.copy()\ntags = data.tag.unique()\n\ndef tag_stripper(s):\n    return ' '.join(filter((lambda w: w not in tags), s.split()))\n\ndata['post'] = data.post.apply(tag_stripper)\n```\n\n\n```python\ndata.post[0]\n```\n\n\n\n\n    'getting absolute path of directory how do i get the absolute path of a directory (it has to be any directory not the current one!) in i tried with <code>os.path.listdir()</code> but it yields only the relative one. thanks!'\n\n\n\n### How long are the posts?\n\n\n```python\npost_lengths = data.post.apply(lambda s: len(s.split()))\nsns.distplot(post_lengths, axlabel=\"number of words\")\n```\n\n\n```python\navg_length = np.mean(post_lengths)\nmedian_length = np.median(post_lengths)\n\nprint(f\"The average length of the posts in {avg_length} words, with half the posts having less than {median_length} words.\")\npost_lengths.describe()\n```\n\n    The average length of the posts in 138.532 words, with half the posts having less than 105.0 words.\n\n\n\n\n\n    count    5000.00000\n    mean      138.53200\n    std       139.37451\n    min         8.00000\n    25%        68.00000\n    50%       105.00000\n    75%       162.00000\n    max      3019.00000\n    Name: post, dtype: float64\n\n\n\n### Split into training data and testing data\n\nIt is **crucial** that we test our classifier using data that was **not** used to build. We split the data into two chunks, the data used to train (ie. build) the classifier, and the data we will later use to test it.\n\n\n```python\ntrain_data = data[:4000]\ntest_data = data[4000:]\nprint(f\"Training on {len(train_data)} rows\")\nprint(f\"Testing on {len(test_data)} rows\")\n```\n\n    Training on 4000 rows\n    Testing on 1000 rows\n\n\n# Build a classifier!\n\n### Convert posts to word counts\n\nWe will use a **bag of words** approach. Here we ignore what the posts mean, and we even ignore the order of the words in the post! All that matters is the number of times each word appears.\n\nWe convert the words into numbers, and the posts into vectors of word counts.\n\n\n```python\nvectorizer = CountVectorizer()\nword_counts = vectorizer.fit_transform(train_data.post)\n```\n\n\n```python\nprint(f\"Number of unique words in the training data: {len(vectorizer.get_feature_names())}\")\nprint(f\"first 10: {', '.join(vectorizer.get_feature_names()[:10])}\")\nprint(f\"middle 10: {', '.join(vectorizer.get_feature_names()[13000:13010])}\")\n```\n\n    Number of unique words in the training data: 26878\n    first 10: 00, 000, 0000, 00000, 000000, 0000000, 000000000, 00001, 0000121593475342, 000016\n    middle 10: ideal, ideally, idealy, ideas, ident, identical, identically, identifications, identified, identifier\n\n\nLets look at the first post.\n\n\n```python\nprint(f\" tag: {train_data.tag.tolist()[0]}\")\nprint(f\"post: {train_data.post.tolist()[0]}\")\n```\n\n     tag: python\n    post: getting absolute path of directory how do i get the absolute path of a directory (it has to be any directory not the current one!) in i tried with <code>os.path.listdir()</code> but it yields only the relative one. thanks!\n\n\n\n```python\nword_counts[0]\n```\n\n\n\n\n    <1x26878 sparse matrix of type '<class 'numpy.int64'>'\n    \twith 28 stored elements in Compressed Sparse Row format>\n\n\n\nThe first post has 28 different words. We encode it as a sparse vector rather than one that's almost all zeros.\n\n\n```python\nprint(word_counts[0])\n```\n\n      (0, 23915)\t1\n      (0, 20271)\t1\n      (0, 17659)\t1\n      (0, 26612)\t1\n      (0, 5930)\t1\n      (0, 15095)\t1\n      (0, 17903)\t1\n      (0, 6946)\t2\n      (0, 26169)\t1\n      (0, 24558)\t1\n      (0, 13266)\t1\n      (0, 17627)\t2\n      (0, 7983)\t1\n      (0, 17186)\t1\n      (0, 4309)\t1\n      (0, 5159)\t1\n      (0, 24237)\t1\n      (0, 12420)\t1\n      (0, 13925)\t2\n      (0, 23923)\t3\n      (0, 11721)\t1\n      (0, 9133)\t1\n      (0, 12803)\t1\n      (0, 8914)\t3\n      (0, 17515)\t2\n      (0, 18367)\t3\n      (0, 3495)\t2\n      (0, 11901)\t1\n\n\n\n```python\nvectorizer.get_feature_names()[18367]\n```\n\n\n\n\n    'path'\n\n\n\n### Naively classifying\n\nOur classifier will have two steps. First we convert the data into word counts as above. Then we use these word counts in a Naive Bayes classifier. \n\nThis is pretty much the simplest classifier we can use. It has few parameters but makes lots of assumptions about the data that are totally wrong. \n\nFor example, it assumes that the words appear independently, ie one word appearing in a post doesn't change the likelihood of one of the other words appearing.\n\nSince our posts are sentences, this is really wrong.\n\n\n```python\nclassifier = Pipeline([\n    ('vect', CountVectorizer()),\n    ('clf', MultinomialNB()),\n])\n\nclassifier.fit(train_data.post, train_data.tag)\n```\n\n\n\n\n    Pipeline(memory=None,\n         steps=[('vect', CountVectorizer(analyzer='word', binary=False, decode_error='strict',\n            dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',\n            lowercase=True, max_df=1.0, max_features=None, min_df=1,\n            ngram_range=(1, 1), preprocessor=None, stop_words=None,\n            strip_accents=None, token_pattern='(?u)\\\\b\\\\w\\\\w+\\\\b',\n            tokenizer=None, vocabulary=None)), ('clf', MultinomialNB(alpha=1.0, class_prior=None, fit_prior=True))])\n\n\n\nThe proportion of predictions that you get right is called the **accuracy score**.\n\n\n```python\npredictions = classifier.predict(test_data.post)\naccuracy_4000 = metrics.accuracy_score(test_data.tag, predictions)\nprint(f\"Accuracy score: {accuracy_4000 * 100:.0f}%\")\nprint(\"Not terrible!\")\n```\n\n    Accuracy score: 73%\n    Not terrible!\n\n\nA **confusion matrix** shows us how many things got classified as other things.\n\n\n```python\ntags = test_data.tag.unique()\nrow_index = pd.MultiIndex.from_tuples([('actual', x) for x in tags])\ncol_index = pd.MultiIndex.from_tuples([('predicted', x) for x in tags])\nconfusion_matrix = metrics.confusion_matrix(test_data.tag, predictions, labels=tags)\n\ndf = pd.DataFrame(confusion_matrix, index=row_index, columns=col_index)\ndf['Count'] = df[df.columns].sum(axis=1)\ns = df.sum()\ns.name = ('actual', \"Count\")\ndf = df.append(s)\n\nconfusion_matrix_4000 = df\nconfusion_matrix_4000\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th></th>\n      <th colspan=\"5\" halign=\"left\">predicted</th>\n      <th>Count</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th></th>\n      <th>python</th>\n      <th>jquery</th>\n      <th>javascript</th>\n      <th>css</th>\n      <th>html</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"6\" valign=\"top\">actual</th>\n      <th>python</th>\n      <td>184</td>\n      <td>0</td>\n      <td>4</td>\n      <td>2</td>\n      <td>0</td>\n      <td>190</td>\n    </tr>\n    <tr>\n      <th>jquery</th>\n      <td>5</td>\n      <td>133</td>\n      <td>37</td>\n      <td>4</td>\n      <td>16</td>\n      <td>195</td>\n    </tr>\n    <tr>\n      <th>javascript</th>\n      <td>23</td>\n      <td>28</td>\n      <td>138</td>\n      <td>6</td>\n      <td>13</td>\n      <td>208</td>\n    </tr>\n    <tr>\n      <th>css</th>\n      <td>3</td>\n      <td>8</td>\n      <td>6</td>\n      <td>162</td>\n      <td>23</td>\n      <td>202</td>\n    </tr>\n    <tr>\n      <th>html</th>\n      <td>19</td>\n      <td>24</td>\n      <td>15</td>\n      <td>35</td>\n      <td>112</td>\n      <td>205</td>\n    </tr>\n    <tr>\n      <th>Count</th>\n      <td>234</td>\n      <td>193</td>\n      <td>200</td>\n      <td>209</td>\n      <td>164</td>\n      <td>1000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThree other important measures of how good a classifier is are **precision**, **recall** and **f1-score**. Values of one are good, zero are bad.\n\n\n\\begin{align}\n\\text{precision of tag} & = \\frac {\\text {number with that tag guessed correctly}} \n                                        {\\text{total number of times we guessed that tag}} \\\\\n                             & = \\text {how much of our guesses of that tag were correct} \\\\\n                             \\\\\n\\text{recall of tag} &= \\frac {\\text {number with that tag guessed correctly}} \n                                        {\\text{number with that tag}} \\\\\n                          &= \\text {how much of that tag we guessed correctly} \\\\\n                          \\\\\n\\text{f1-score} &= \\text{combination of precision and recall} \\\\\n\\end{align}\n\n\n\n```python\nprint(metrics.classification_report(y_true=test_data.tag, y_pred=predictions))\n```\n\n                  precision    recall  f1-score   support\n    \n             css       0.78      0.80      0.79       202\n            html       0.68      0.55      0.61       205\n      javascript       0.69      0.66      0.68       208\n          jquery       0.69      0.68      0.69       195\n          python       0.79      0.97      0.87       190\n    \n       micro avg       0.73      0.73      0.73      1000\n       macro avg       0.72      0.73      0.73      1000\n    weighted avg       0.72      0.73      0.72      1000\n    \n\n\n### What if we don't have much data?\n\n\n```python\ntrain_data = data[:100]\nprint(f\"Training on {len(train_data)} rows\")\nprint(f\"Testing on {len(test_data)} rows\")\n```\n\n    Training on 100 rows\n    Testing on 1000 rows\n\n\n\n```python\nclassifier = Pipeline([\n    ('vect', CountVectorizer()),\n    ('clf', MultinomialNB()),\n])\n\nclassifier.fit(train_data.post, train_data.tag)\nprint(f\"Accuracy score for 4000 training posts: {accuracy_4000 * 100:.0f}%\")\npredictions = classifier.predict(test_data.post)\naccuracy_100 = metrics.accuracy_score(test_data.tag, predictions)\nprint(f\"Accuracy score for 100 training posts: {accuracy_100 * 100:.0f}%\")\n```\n\n    Accuracy score for 4000 training posts: 73%\n    Accuracy score for 100 training posts: 56%\n\n\n\n```python\nprint(\"If we guessed randomly we'd have a 1 / 5 = 20% chance of being right.\")\nprint(f\"With very little data we boosted that to {accuracy_100 * 100:.0f}%.\")\n```\n\n    If we guessed randomly we'd have a 1 / 5 = 20% chance of being right.\n    With very little data we boosted that to 56%.\n\n\n# Tweak things\n\n\n```python\ntrain_data = data[:4000]\ntest_data = data[4000:]\n```\n\n\n```python\nprint(f\"Original accuracy: {accuracy_4000 * 100:.0f}%\")\n```\n\n    Original accuracy: 73%\n\n\n### Original Naive Bayes\n\n### Normalize word counts\n\nIf a document is really long it will in general have higher word counts, so it might seem (to the classifier) to be more likely to have a given tag (Think of just repeating the text in a post).\n\nTo counter this we usually normalize the counts by the length of the document in some fashion.\n\nAlso, if a word occurs in most of the documents, it probably doesn't have much information value. So we want to reduce its score.\n\nA common way to do both of these is to calculate the Term Frequency Inverse Document Frequency (TFIDF).\n\n\n```python\nclassifier = Pipeline([\n    ('vect', CountVectorizer()),\n    ('tfidf', TfidfTransformer()),\n    ('clf', MultinomialNB()),\n])\n\nclassifier.fit(train_data.post, train_data.tag)\npredictions = classifier.predict(test_data.post)\naccuracy = metrics.accuracy_score(test_data.tag, predictions)\n\nprint(f\"Accuracy with TDIDF: {accuracy * 100:.0f}%\")\n```\n\n    Accuracy with TDIDF: 74%\n\n\n### Stop words\n\n**Stop words** are words that have no information value, such as `the`, `a`, or `or`. Removing them from our data might improve things.\n\n\n```python\nclassifier = Pipeline([\n    ('vect', CountVectorizer(stop_words='english')),\n    ('clf', MultinomialNB()),\n])\n\nclassifier.fit(train_data.post, train_data.tag)\npredictions = classifier.predict(test_data.post)\naccuracy = metrics.accuracy_score(test_data.tag, predictions)\n\nprint(f\"Accuracy with stop words removed: {accuracy * 100:.0f}%\")\n```\n\n    Accuracy with stop words removed: 73%\n\n\n### n-grams\n\nWe used word counts. What if instead we counted pairs of words? Or triples?\n\n\n```python\nclassifier = Pipeline([\n    ('vect', CountVectorizer(ngram_range=(1,2))),\n    ('clf', MultinomialNB()),\n])\n\nclassifier.fit(train_data.post, train_data.tag)\npredictions = classifier.predict(test_data.post)\naccuracy = metrics.accuracy_score(test_data.tag, predictions)\n\nprint(f\"Accuracy with 1,2 -grams: {accuracy * 100:.0f}%\")\n```\n\n    Accuracy with 1,2 -grams: 76%\n\n\n\n```python\nclassifier = Pipeline([\n    ('vect', CountVectorizer(ngram_range=(1,3))),\n    ('clf', MultinomialNB()),\n])\n\nclassifier.fit(train_data.post, train_data.tag)\npredictions = classifier.predict(test_data.post)\naccuracy = metrics.accuracy_score(test_data.tag, predictions)\n\nprint(f\"Accuracy with 1,2,3 -grams: {accuracy * 100:.0f}%\")\n```\n\n    Accuracy with 1,2,3 -grams: 76%\n\n\n### All of the above?\n\n\n```python\nclassifier = Pipeline([\n    ('vect', CountVectorizer(ngram_range=(1,2), stop_words='english')),\n    ('tfidf', TfidfTransformer()),\n    ('clf', MultinomialNB()),\n])\n\nclassifier.fit(train_data.post, train_data.tag)\npredictions = classifier.predict(test_data.post)\naccuracy = metrics.accuracy_score(test_data.tag, predictions)\n\nprint(f\"Accuracy with stopwords, TFIDF, and 1,2-grams: {accuracy * 100:.0f}%\")\n```\n\n    Accuracy with stopwords, TFIDF, and 1,2-grams: 74%\n\n\nSo best option here is to use 1,2-grams.\n\n### Try on small data set\n\n\n```python\ntrain_data = data[:100]\ntest_data = data[4000:]\n```\n\n\n```python\nclassifier = Pipeline([\n    ('vect', CountVectorizer()),\n    ('clf', MultinomialNB()),\n])\n\nclassifier.fit(train_data.post, train_data.tag)\npredictions = classifier.predict(test_data.post)\naccuracy = metrics.accuracy_score(test_data.tag, predictions)\n\nprint(f\"1-gram accuracy: {accuracy * 100:.0f}%\")\n```\n\n    1-gram accuracy: 56%\n\n\n\n```python\nclassifier = Pipeline([\n    ('vect', CountVectorizer(ngram_range=(1,2))),\n    ('clf', MultinomialNB()),\n])\n\nclassifier.fit(train_data.post, train_data.tag)\npredictions = classifier.predict(test_data.post)\naccuracy = metrics.accuracy_score(test_data.tag, predictions)\n\nprint(f\"1,2-gram accuracy: {accuracy * 100:.0f}%\")\n```\n\n    1,2-gram accuracy: 53%\n\n\n## Try other classifiers\n\n\n```python\ntrain_data = data[:4000]\ntest_data = data[4000:]\n```\n\n\n```python\nclassifiers = [\n    MultinomialNB(),\n    SGDClassifier(alpha=0.1, random_state=42, max_iter=20, tol=0.3),\n    RandomForestClassifier(n_estimators=100),\n]\n```\n\n\n```python\nresult_cols = [\"Classifier\", \"Accuracy\"]\nresult_frame = pd.DataFrame(columns=result_cols)\n\nfor clf in classifiers:\n    name = clf.__class__.__name__\n    text_clf = Pipeline([('vect', CountVectorizer(ngram_range=(1,2))),\n                         ('clf', clf),])\n    text_clf.fit(train_data.post, train_data.tag)\n    \n    predicted = text_clf.predict(test_data.post)\n    acc = metrics.accuracy_score(test_data.tag, predicted)\n    print (f'{name} accuracy = {acc*100:.0f}%')\n    acc_field = pd.DataFrame([[name, acc*100]], columns=result_cols)\n    result_frame = result_frame.append(acc_field)\n\nresult_frame\n```\n\n    MultinomialNB accuracy = 76%\n    SGDClassifier accuracy = 80%\n    RandomForestClassifier accuracy = 75%\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Classifier</th>\n      <th>Accuracy</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>MultinomialNB</td>\n      <td>76.1</td>\n    </tr>\n    <tr>\n      <th>0</th>\n      <td>SGDClassifier</td>\n      <td>80.4</td>\n    </tr>\n    <tr>\n      <th>0</th>\n      <td>RandomForestClassifier</td>\n      <td>75.2</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "567d84717c6547d4052351af443a79ad4351d5cd", "size": 49413, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/tutorial 1  - StackOverflow.ipynb", "max_stars_repo_name": "cds-snc/rac-data-exploration", "max_stars_repo_head_hexsha": "e8010981e7d7bd63393d7cb1fd05d75033129d9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/tutorial 1  - StackOverflow.ipynb", "max_issues_repo_name": "cds-snc/rac-data-exploration", "max_issues_repo_head_hexsha": "e8010981e7d7bd63393d7cb1fd05d75033129d9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/tutorial 1  - StackOverflow.ipynb", "max_forks_repo_name": "cds-snc/rac-data-exploration", "max_forks_repo_head_hexsha": "e8010981e7d7bd63393d7cb1fd05d75033129d9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5210643016, "max_line_length": 13324, "alphanum_fraction": 0.6132191933, "converted": true, "num_tokens": 5306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.396068180531364, "lm_q2_score": 0.05749328283769179, "lm_q1q2_score": 0.022771259926299685}}
{"text": "# 00_setup_colab.ipynb\n\n\n\n```python\n%matplotlib inline\n```\n\n\n# Setup Google Colab\n\nIn this script, we setup a Google Colab environment. This script will only work\nwhen run from `Google Colab <https://colab.research.google.com/>`_). You can\nskip it if you run the tutorials on your machine.\n\n\n\n```python\n\n```\n\n## Change runtime to use a GPU\n\nThis tutorial is much faster when a GPU is available to run the computations.\nIn Google Colab you can request access to a GPU by changing the runtime type.\nTo do so, click the following menu options in Google Colab:\n\n(Menu) \"Runtime\" -> \"Change runtime type\" -> \"Hardware accelerator\" -> \"GPU\".\n\n\n\n## Download the data and install all required dependencies\n\nUncomment and run the following cell to download the tutorial data and\ninstall the required dependencies.\n\n\n\n\n```python\n# ![ -f \"vim-5-for-ccn.tar.gz\" ] || gdown --id 1b0I0Ytj06m6GCmfxfNrZuyF97fDo3NZb\n# ![ -d \"vim-5\" ] || tar xzf vim-5-for-ccn.tar.gz\n# ![ -d \"pycortex\" ] || git clone --quiet https://github.com/gallantlab/pycortex\n# !apt-get install -qq inkscape > /dev/null\n# !pip install -q voxelwise_tutorials\n# ![ -f \"ngrok-stable-linux-amd64.zip\" ] || wget -q https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip\n# ![ -f \"ngrok\" ] || unzip ngrok-stable-linux-amd64.zip\n```\n\nFor the record, here is what each command does:\n\n- Download the dataset archive\n- Extract the dataset archive\n- Clone Pycortex to fix some filestore issues with Colab\n- Install Inkscape, to use more features from Pycortex\n- Install the tutorial helper package, and all the required dependencies\n- Download ngrok to create a tunnel for pycortex 3D brain viewer\n- Extract the ngrok archive\n\n\n\nNow run the following cell to set up the environment variables for the\ntutorials and pycortex.\n\n\n\n\n```python\nimport os\nos.environ['VOXELWISE_TUTORIALS_DATA'] = \"/content\"\n\nimport cortex\ncortex.db.__init__(\"/content/pycortex/filestore/\")  # change filestore inplace\ncortex.options.config['webgl']['colormaps'] = \"/content/pycortex/filestore/colormaps\"\n\nimport sklearn\nsklearn.set_config(assume_finite=True)\n```\n\nYour Google Colab environment is now set up for the voxelwise tutorials.\n\n\n\n\n```python\n%reset -f\n```\n\n\n# 01_plot_explainable_variance.ipynb\n\n\n\n```python\n%matplotlib inline\n```\n\n\n# Compute the explainable variance\n\nBefore fitting any voxelwise model to fMRI responses, it is good practice to\nquantify the amount of signal in the test set that can be predicted by an\nencoding model. This quantity is called the *explainable variance*.\n\nThe measured signal can be decomposed into a sum of two components: the\nstimulus-dependent signal and noise. If we present the same stimulus multiple\ntimes and we record brain activity for each repetition, the stimulus-dependent\nsignal will be the same across repetitions while the noise will vary across\nrepetitions. In voxelwise modeling, the features used to model brain activity\nare the same for each repetition of the stimulus. Thus, encoding models will\npredict only the repeatable stimulus-dependent signal.\n\nThe stimulus-dependent signal can be estimated by taking the mean of \nbrain responses over repeats of the same stimulus or experiment. The variance\nof the estimated stimulus-dependent signal, which we call the explainable\nvariance, is proportional to the maximum prediction accuracy that can be\nobtained by a voxelwise encoding model in the test set. \n\nMathematically, let $y_i, i = 1 \\dots N$ be the measured signal in\na voxel for each of the $N$ repetitions of the same stimulus and \n$\\bar{y} = \\frac{1}{N}\\sum_{i=1}^Ny_i$ the average brain response\nacross repetitions. For each repeat, we define the residual timeseries\nbetween brain response and average brain response as $r_i = y_i - \\bar{y}$.\nThe explainable variance (EV) is estimated as\n\n\\begin{align}\\text{EV} = \\frac{1}{N}\\sum_{i=1}^N\\text{Var}(y_i) - \\frac{N}{N-1}\\sum_{i=1}^N\\text{Var}(r_i)\\end{align}\n\n\nIn the literature, the explainable\nvariance is also known as the *signal power*. For more information, see these\nreferences [1]_ [2]_ [3]_.\n\n\n\n```python\n\n```\n\n## Path of the data directory\n\n\n\n\n```python\nimport os\nfrom voxelwise_tutorials.io import get_data_home\ndirectory = os.path.join(get_data_home(), \"vim-5\")\nprint(directory)\n```\n\n\n```python\n# modify to use another subject\nsubject = \"S01\"\n```\n\n## Compute the explainable variance\n\n\n\n\n```python\nimport numpy as np\nfrom voxelwise_tutorials.io import load_hdf5_array\n```\n\nFirst, we load the fMRI responses on the test set, which contains brain\nresponses to ten (10) repeats of the same stimulus.\n\n\n\n\n```python\nfile_name = os.path.join(directory, 'responses', f'{subject}_responses.hdf')\nY_test = load_hdf5_array(file_name, key=\"Y_test\")\nprint(\"(n_repeats, n_samples_test, n_voxels) =\", Y_test.shape)\n```\n\nThen, we compute the explainable variance for each voxel.\n\n\n\n\n```python\nfrom voxelwise_tutorials.utils import explainable_variance\nev = explainable_variance(Y_test)\nprint(\"(n_voxels,) =\", ev.shape)\n```\n\nTo better understand the concept of explainable variance, we can plot the\nmeasured signal in a voxel with high explainable variance...\n\n\n\n\n```python\nimport matplotlib.pyplot as plt\n\nvoxel_1 = np.argmax(ev)\ntime = np.arange(Y_test.shape[1]) * 2  # one time point every 2 seconds\nplt.figure(figsize=(10, 3))\nplt.plot(time, Y_test[:, :, voxel_1].T, color='C0', alpha=0.5)\nplt.plot(time, Y_test[:, :, voxel_1].mean(0), color='C1', label='average')\nplt.xlabel(\"Time (sec)\")\nplt.title(\"Voxel with large explainable variance (%.2f)\" % ev[voxel_1])\nplt.yticks([])\nplt.legend()\nplt.tight_layout()\nplt.show()\n```\n\n... and in a voxel with low explainable variance.\n\n\n\n\n```python\nvoxel_2 = np.argmin(ev)\nplt.figure(figsize=(10, 3))\nplt.plot(time, Y_test[:, :, voxel_2].T, color='C0', alpha=0.5)\nplt.plot(time, Y_test[:, :, voxel_2].mean(0), color='C1', label='average')\nplt.xlabel(\"Time (sec)\")\nplt.title(\"Voxel with low explainable variance (%.2f)\" % ev[voxel_2])\nplt.yticks([])\nplt.legend()\nplt.tight_layout()\nplt.show()\n```\n\nWe can also plot the distribution of explainable variance over voxels.\n\n\n\n\n```python\nplt.hist(ev, bins=np.linspace(0, 1, 100), log=True, histtype='step')\nplt.xlabel(\"Explainable variance\")\nplt.ylabel(\"Number of voxels\")\nplt.title('Histogram of explainable variance')\nplt.grid('on')\nplt.show()\n```\n\nWe see that many voxels have low explainable variance. This is\nexpected, since many voxels are not driven by a visual stimulus, and their\nresponse changes over repeats of the same stimulus.\nWe also see that some voxels have high explainable variance (around 0.7). The\nresponses in these voxels are highly consistent across repetitions of the\nsame stimulus. Thus, they are good targets for encoding models.\n\n\n\n## Map to subject flatmap\n\nTo better understand the distribution of explainable variance, we map the\nvalues to the subject brain. This can be done with `pycortex\n<https://gallantlab.github.io/pycortex/>`_, which can create interactive 3D\nviewers to be displayed in any modern browser. ``pycortex`` can also display\nflattened maps of the cortical surface to visualize the entire cortical\nsurface at once.\n\nHere, we do not share the anatomical information of the subjects for privacy\nconcerns. Instead, we provide two mappers:\n\n- to map the voxels to a (subject-specific) flatmap\n- to map the voxels to the Freesurfer average cortical surface (\"fsaverage\")\n\nThe first mapper is 2D matrix of shape (n_pixels, n_voxels) that maps each\nvoxel to a set of pixel in a flatmap. The matrix is efficiently stored in a\n``scipy`` sparse CSR matrix. The function ``plot_flatmap_from_mapper``\nprovides an example of how to use the mapper and visualize the flatmap.\n\n\n\n\n```python\nfrom voxelwise_tutorials.viz import plot_flatmap_from_mapper\n\nmapper_file = os.path.join(directory, 'mappers', f'{subject}_mappers.hdf')\nplot_flatmap_from_mapper(ev, mapper_file, vmin=0, vmax=0.7)\nplt.show()\n```\n\nThis figure is a flattened map of the cortical surface. A number of regions of\ninterest (ROIs) have been labeled to ease interpretation. If you have\nnever seen such a flatmap, we recommend taking a look at a `pycortex brain\nviewer <https://www.gallantlab.org/brainviewer/Deniz2019>`_, which displays\nthe brain in 3D. In this viewer, press \"I\" to inflate the brain, \"F\" to\nflatten the surface, and \"R\" to reset the view (or use the ``surface/unfold``\ncursor on the right menu). Press \"H\" for a list of all keyboard shortcuts.\nThis viewer should help you understand the correspondance between the flatten\nand the folded cortical surface of the brain.\n\n\n\nOn this flatmap, we can see that the explainable variance is mainly located\nin the visual cortex, in early visual regions like V1, V2, V3, or in\nhigher-level regions like EBA, FFA or IPS. This is expected since this\ndataset contains responses to a visual stimulus.\n\n\n\n## Map to \"fsaverage\"\n\nThe second mapper we provide maps the voxel data to a Freesurfer\naverage surface (\"fsaverage\"), that can be used in ``pycortex``.\n\nFirst, let's download the \"fsaverage\" surface.\n\n\n\n\n```python\nimport cortex\n\nsurface = \"fsaverage\"\n\nif not hasattr(cortex.db, surface):\n    cortex.utils.download_subject(subject_id=surface,\n                                  pycortex_store=cortex.db.filestore)\n    cortex.db._subjects = None  # force filestore reload\n    assert hasattr(cortex.db, surface)\n```\n\nThen, we load the \"fsaverage\" mapper. The mapper is a matrix of shape\n(n_vertices, n_voxels), which maps each voxel to some vertices in the\nfsaverage surface. It is stored as a sparse CSR matrix. The mapper is applied\nwith a dot product ``@`` (equivalent to ``np.dot``).\n\n\n\n\n```python\nfrom voxelwise_tutorials.io import load_hdf5_sparse_array\nvoxel_to_fsaverage = load_hdf5_sparse_array(mapper_file,\n                                            key='voxel_to_fsaverage')\nev_projected = voxel_to_fsaverage @ ev\nprint(\"(n_vertices,) =\", ev_projected.shape)\n```\n\nWe can then create a ``Vertex`` object in ``pycortex``, containing the\nprojected data. This object can be used either in a ``pycortex`` interactive\n3D viewer, or in a ``matplotlib`` figure showing only the flatmap.\n\n\n\n\n```python\nvertex = cortex.Vertex(ev_projected, surface, vmin=0, vmax=0.7, cmap='viridis')\n```\n\nTo start an interactive 3D viewer in the browser, we can use the ``webshow``\nfunction in pycortex. If you are running the notebook on Colab, you first\nneed to tunnel the pycortex application out of Colab. To do so, use the\nfollowing cell to start a tunnel with ``ngrok`` and to get an address where\nthe pycortex viewer will be made accessible.\n\n\n\n\n```python\ntry:\n    import google.colab  # noqa\n    in_colab = True\nexcept ImportError:\n    in_colab = False\nprint(in_colab)\n\nif in_colab:\n    from IPython import get_ipython\n    get_ipython().system_raw('./ngrok http 8050 &')\n    plt.pause(1)\n\n    command = \"\"\"\n        curl -s http://localhost:4040/api/tunnels | python3 -c \\\n        \"import sys, json; print(json.load(sys.stdin)['tunnels'][0]['public_url'])\"\n        \"\"\"\n    result = get_ipython().getoutput(command, split=True)\n    print(\"Use the following address to connect to the brain viewer:\\n\"\n          f\"{result}\\n\"\n          \"and not the one proposed by pycortex ('Open viewer: ...')\\n\")\n```\n\nNow you can start an interactive 3D viewer by changing ``run_webshow`` to\n``True`` and running the following cell.  If you are using Colab, remember to\nuse the address returned by ngrok in the cell above rather than the address\nreturned by this cell.\n\n\n\n\n```python\nrun_webshow = False\nif run_webshow:\n    cortex.webshow(vertex, open_browser=False, port=8050)\n```\n\nAlternatively, to plot a flatmap in a ``matplotlib`` figure, use the\n`quickshow` function.\n\n(This function requires Inkscape to be installed. The rest of the tutorial\ndoes not use this function, so feel free to ignore.)\n\n\n\n\n```python\nfrom cortex.testing_utils import has_installed\n\nfig = cortex.quickshow(vertex, colorbar_location='right',\n                       with_rois=has_installed(\"inkscape\"))\nplt.show()\n```\n\n## References\n\n.. [1] Sahani, M., & Linden, J. F. (2003). How linear are auditory cortical\n   responses?. Advances in neural information processing systems, 125-132.\n\n.. [2] Hsu, A., Borst, A., & Theunissen, F. E. (2004). Quantifying\n   variability in neural responses and its application for the validation of\n   model predictions. Network: Computation in Neural Systems, 15(2), 91-109.\n\n.. [3] Schoppe, O., Harper, N. S., Willmore, B. D., King, A. J., & Schnupp,\n       J. W. (2016). Measuring the performance of neural models. Frontiers in\n       computational neuroscience, 10, 10.\n\n\n\n\n\n```python\n%reset -f\n```\n\n\n# 02_plot_wordnet_model.ipynb\n\n\n\n```python\n%matplotlib inline\n```\n\n\n# Fit a ridge model with wordnet features\n\nIn this example, we model the fMRI responses with semantic \"wordnet\" features,\nmanually annotated on each frame of the movie stimulus. The model is a\nregularized linear regression model, known as ridge regression. Since this\nmodel is used to predict brain activity from the stimulus, it is called a\n(voxelwise) encoding model.\n\nThis example reproduces part of the analysis described in Huth et al (2012)\n[1]_. See this publication for more details about the experiment, the wordnet\nfeatures, along with more results and more discussions.\n\n*Wordnet features:* The features used in this example are semantic labels\nmanually annotated on each frame of the movie stimulus. The semantic labels\ninclude nouns (such as \"woman\", \"car\", or \"building\") and verbs (such as\n\"talking\", \"touching\", or \"walking\"), for a total of 1705 distinct category\nlabels. To interpret our model, labels can be organized in a graph of semantic\nrelashionship based on the `Wordnet <https://wordnet.princeton.edu/>`_ dataset.\n\n*Summary:* We first concatenate the features with multiple temporal delays to\naccount for the slow hemodynamic response. We then use linear regression to fit\na predictive model of brain activity. The linear regression is regularized to\nimprove robustness to correlated features and to improve generalization\nperformance. The optimal regularization hyperparameter is selected over a\ngrid-search with cross-validation. Finally, the model generalization\nperformance is evaluated on a held-out test set, comparing the model\npredictions to the corresponding ground-truth fMRI responses.\n\n\n## Path of the data directory\n\n\n\n\n```python\nimport os\nfrom voxelwise_tutorials.io import get_data_home\ndirectory = os.path.join(get_data_home(), \"vim-5\")\nprint(directory)\n```\n\n\n```python\n# modify to use another subject\nsubject = \"S01\"\n```\n\n## Load the data\n\nWe first load the fMRI responses. These responses have been preprocessed as\ndecribed in [1]_. The data is separated into a training set ``Y_train`` and a\ntesting set ``Y_test``. The training set is used for fitting models, and\nselecting the best models and hyperparameters. The test set is later used\nto estimate the generalization performance of the selected model. The\ntest set contains multiple repetitions of the same experiment to estimate\nan upper bound of the model prediction accuracy (cf. previous example).\n\n\n\n\n```python\nimport numpy as np\nfrom voxelwise_tutorials.io import load_hdf5_array\n\nfile_name = os.path.join(directory, \"responses\", f\"{subject}_responses.hdf\")\nY_train = load_hdf5_array(file_name, key=\"Y_train\")\nY_test = load_hdf5_array(file_name, key=\"Y_test\")\n\nprint(\"(n_samples_train, n_voxels) =\", Y_train.shape)\nprint(\"(n_repeats, n_samples_test, n_voxels) =\", Y_test.shape)\n```\n\nIf we repeat an experiment multiple times, part of the fMRI responses might\nchange. However the modeling features do not change over the repeats, so the\nvoxelwise encoding model will predict the same signal for each repeat. To\nhave an upper bound of the model prediction accuracy, we keep only the\nrepeatable part of the signal by averaging the test repeats.\n\n\n\n\n```python\nY_test = Y_test.mean(0)\n\nprint(\"(n_samples_test, n_voxels) =\", Y_test.shape)\n```\n\nWe fill potential NaN (not-a-number) values with zeros.\n\n\n\n\n```python\nY_train = np.nan_to_num(Y_train)\nY_test = np.nan_to_num(Y_test)\n```\n\nThen, we load the semantic \"wordnet\" features, extracted from the stimulus at\neach time point. The features corresponding to the training set are noted\n``X_train``, and the features corresponding to the test set are noted\n``X_test``.\n\n\n\n\n```python\nfeature_space = \"wordnet\"\n\nfile_name = os.path.join(directory, \"features\", f\"{feature_space}.hdf\")\nX_train = load_hdf5_array(file_name, key=\"X_train\")\nX_test = load_hdf5_array(file_name, key=\"X_test\")\n\nprint(\"(n_samples_train, n_features) =\", X_train.shape)\nprint(\"(n_samples_test, n_features) =\", X_test.shape)\n```\n\n## Define the cross-validation scheme\n\nTo select the best hyperparameter through cross-validation, we must define a\ncross-validation splitting scheme. Since fMRI time-series are autocorrelated\nin time, we should preserve as much as possible the temporal correlation.\nIn other words, since consecutive time samples are correlated, we should not\nput one time sample in the training set and the immediately following time\nsample in the validation set. Thus, we define here a leave-one-run-out\ncross-validation split that keeps each recording run intact.\n\n\n\n\n```python\nfrom sklearn.model_selection import check_cv\nfrom voxelwise_tutorials.utils import generate_leave_one_run_out\n\n# indice of first sample of each run\nrun_onsets = load_hdf5_array(file_name, key=\"run_onsets\")\nprint(run_onsets)\n```\n\nWe define a cross-validation splitter, compatible with ``scikit-learn`` API.\n\n\n\n\n```python\nn_samples_train = X_train.shape[0]\ncv = generate_leave_one_run_out(n_samples_train, run_onsets)\ncv = check_cv(cv)  # copy the cross-validation splitter into a reusable list\n```\n\n## Define the model\n\nNow, let's define the model pipeline.\n\nWe first center the features, since we will not use an intercept. The mean\nvalue in fMRI recording is non-informative, so each run is detrended and\ndemeaned independently, and we do not need to predict an intercept value in\nthe linear model.\n\nHowever, we prefer to avoid normalizing by the standard deviation of each\nfeature. If the features are extracted in a consistent way from the stimulus,\ntheir relative scale is meaningful. Normalizing them independently from each\nother would remove this information. Moreover, the wordnet features are\none-hot-encoded, which means that each feature is either present (1) or not\npresent (0) in each sample. Normalizing one-hot-encoded features is not\nrecommended, since it would scale disproportionately the infrequent features.\n\n\n\n\n```python\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler(with_mean=True, with_std=False)\n```\n\nThen we concatenate the features with multiple delays to account for the\nhemodynamic response. Due to neurovascular coupling, the recorded BOLD signal\nis delayed in time with respect to the stimulus onset. With different delayed\nversions of the features, the linear regression model will weigh each delayed\nfeature with a different weight to maximize the predictions. With a sample\nevery 2 seconds, we typically use 4 delays [1, 2, 3, 4] to cover the\nhemodynamic response peak. In the next example, we further describe this\nhemodynamic response estimation.\n\n\n\n\n```python\nfrom voxelwise_tutorials.delayer import Delayer\ndelayer = Delayer(delays=[1, 2, 3, 4])\n```\n\nFinally, we use a ridge regression model. Ridge regression is a linear\nregression with L2 regularization. The L2 regularization improves robustness\nto correlated features and improves generalization performance. However, the\nL2 regularization is controlled by a hyperparameter ``alpha`` that needs to\nbe tuned for each dataset. This regularization hyperparameter is usually\nselected over a grid search with cross-validation, selecting the\nhyperparameter that maximizes the predictive performances on the validation\nset. More details about cross-validation can be found in the `scikit-learn\ndocumentation\n<https://scikit-learn.org/stable/modules/cross_validation.html>`_.\n\nFor computational reasons, when the number of features is larger than the\nnumber of samples, it is more efficient to solve ridge regression using the\n(equivalent) dual formulation [2]_. This dual formulation is equivalent to\nkernel ridge regression with a linear kernel. Here, we have 3600 training\nsamples, and 1705 * 4 = 6820 features (we multiply by 4 since we use 4 time\ndelays), therefore it is more efficient to use kernel ridge regression.\n\nWith one target, we could directly use the pipeline in ``scikit-learn``'s\n``GridSearchCV``, to select the optimal regularization hyperparameter\n(``alpha``) over cross-validation. However, ``GridSearchCV`` can only\noptimize a single score across all voxels (targets). Thus, in the\nmultiple-target case, ``GridSearchCV`` can only optimize (for example) the\nmean score over targets. Here, we want to find a different optimal\nhyperparameter per target/voxel, so we use the package `himalaya\n<https://github.com/gallantlab/himalaya>`_ which implements a\n``scikit-learn`` compatible estimator ``KernelRidgeCV``, with hyperparameter\nselection independently on each target.\n\n\n\n\n```python\nfrom himalaya.kernel_ridge import KernelRidgeCV\n```\n\n``himalaya`` implements different computational backends,\nincluding two backends that use GPU for faster computations. The two\navailable GPU backends are \"torch_cuda\" and \"cupy\". (Each backend is only\navailable if you installed the corresponding package with CUDA enabled. Check\nthe ``pytorch``/``cupy`` documentation for install instructions.)\n\nHere we use the \"torch_cuda\" backend, but if the import fails we continue\nwith the default \"numpy\" backend. The \"numpy\" backend is expected to be\nslower since it only uses the CPU.\n\n\n\n\n```python\nfrom himalaya.backend import set_backend\nbackend = set_backend(\"torch_cuda\", on_error=\"warn\")\nprint(backend)\n```\n\nTo speed up model fitting on GPU, we use single precision float numbers.\n(This step probably does not change significantly the performances on non-GPU\nbackends.)\n\n\n\n\n```python\nX_train = X_train.astype(\"float32\")\nX_test = X_test.astype(\"float32\")\n```\n\nSince the scale of the regularization hyperparameter ``alpha`` is unknown, we\nuse a large logarithmic range, and we will check after the fit that best\nhyperparameters are not all on one range edge.\n\n\n\n\n```python\nalphas = np.logspace(1, 20, 20)\n```\n\nWe also indicate some batch sizes to limit the GPU memory.\n\n\n\n\n```python\nkernel_ridge_cv = KernelRidgeCV(\n    alphas=alphas, cv=cv,\n    solver_params=dict(n_targets_batch=500, n_alphas_batch=5,\n                       n_targets_batch_refit=100))\n```\n\nFinally, we use a ``scikit-learn`` ``Pipeline`` to link the different steps\ntogether. A ``Pipeline`` can be used as a regular estimator, calling\n``pipeline.fit``, ``pipeline.predict``, etc. Using a ``Pipeline`` can be\nuseful to clarify the different steps, avoid cross-validation mistakes, or\nautomatically cache intermediate results. See the ``scikit-learn``\n`documentation <https://scikit-learn.org/stable/modules/compose.html>`_ for\nmore information.\n\n\n\n\n```python\nfrom sklearn.pipeline import make_pipeline\npipeline = make_pipeline(\n    scaler,\n    delayer,\n    kernel_ridge_cv,\n)\n```\n\nWe can display the ``scikit-learn`` pipeline with an HTML diagram.\n\n\n\n\n```python\nfrom sklearn import set_config\nset_config(display='diagram')  # requires scikit-learn 0.23\npipeline\n```\n\n## Fit the model\n\nWe fit on the training set..\n\n\n\n\n```python\n_ = pipeline.fit(X_train, Y_train)\n```\n\n..and score on the test set. Here the scores are the $R^2$ scores, with\nvalues in $]-\\infty, 1]$. A value of $1$ means the predictions\nare perfect.\n\nNote that since ``himalaya`` is implementing multiple-targets\nmodels, the ``score`` method differs from ``scikit-learn`` API and returns\none score per target/voxel.\n\n\n\n\n```python\nscores = pipeline.score(X_test, Y_test)\nprint(\"(n_voxels,) =\", scores.shape)\n```\n\nIf we fit the model on GPU, scores are returned on GPU using an array object\nspecfic to the backend we used (such as a ``torch.Tensor``). Thus, we need to\nmove them into ``numpy`` arrays on CPU, to be able to use them for example in\na ``matplotlib`` figure.\n\n\n\n\n```python\nscores = backend.to_numpy(scores)\n```\n\n## Plot the model prediction accuracy\n\nTo visualize the model prediction accuracy, we can plot it for each voxel on\na flattened surface of the brain. To do so, we use a mapper that is specific\nto the each subject's brain. (Check previous example to see how to use the\nmapper to Freesurfer average surface.)\n\n\n\n\n```python\nimport matplotlib.pyplot as plt\nfrom voxelwise_tutorials.viz import plot_flatmap_from_mapper\n\nmapper_file = os.path.join(directory, \"mappers\", f\"{subject}_mappers.hdf\")\nax = plot_flatmap_from_mapper(scores, mapper_file, vmin=0, vmax=0.4)\nplt.show()\n```\n\nWe can see that the \"wordnet\" features successfully predict part of the\nmeasured brain activity, with $R^2$ scores as high as 0.4. Note that\nthese scores are generalization scores, since they are computed on a test set\nthat was not used during model fitting. Since we fitted a model independently\nin each voxel, we can inspect the generalization performances at the best\navailable spatial resolution: individual voxels.\n\nThe best-predicted voxels are located in visual semantic areas like EBA, or\nFFA. This is expected since the wordnet features encode semantic information\nabout the visual stimulus. For more discussions about these results, we refer\nthe reader to the original publication [1]_.\n\n\n\n## Plot the selected hyperparameters\n\nSince the scale of alphas is unknown, we plot the optimal alphas selected by\nthe solver over cross-validation. This plot is helpful to refine the alpha\ngrid if the range is too small or too large.\n\nNote that some voxels might be at the maximum regularization value in the\ngrid search. These are voxels where the model has no predictive power, thus\nthe optimal regularization parameter is large to lead to a prediction equal\nto zero. We do not need to extend the alpha range for these voxels.\n\n\n\n\n```python\nfrom himalaya.viz import plot_alphas_diagnostic\nbest_alphas = backend.to_numpy(pipeline[-1].best_alphas_)\nplot_alphas_diagnostic(best_alphas=best_alphas, alphas=alphas)\nplt.show()\n```\n\n## Visualize the regression coefficients\n\nHere, we go back to the main model on all voxels. Since our model is linear,\nwe can use the (primal) regression coefficients to interpret the model. The\nbasic intuition is that the model will use larger coefficients on features\nthat have more predictive power.\n\nSince we know the meaning of each feature, we can interpret the large\nregression coefficients. In the case of wordnet features, we can even build a\ngraph that represents the features that are linked by a semantic\nrelationship.\n\n\n\nWe first get the (primal) ridge regression coefficients from the fitted\nmodel.\n\n\n\n\n```python\nprimal_coef = pipeline[-1].get_primal_coef()\nprimal_coef = backend.to_numpy(primal_coef)\nprint(\"(n_delays * n_features, n_voxels) =\", primal_coef.shape)\n```\n\nHere, we are only interested in the voxels with good generalization\nperformances. We select an arbitrary threshold of 0.05 (R^2 score).\n\n\n\n\n```python\nprimal_coef_selection = primal_coef[:, scores > 0.05]\n```\n\nThen, we aggregate the coefficients across the different delays.\n\n\n\n\n```python\n# split the ridge coefficients per delays\ndelayer = pipeline.named_steps['delayer']\nprimal_coef_per_delay = delayer.reshape_by_delays(primal_coef_selection,\n                                                  axis=0)\nprint(\"(n_delays, n_features, n_voxels) =\", primal_coef_per_delay.shape)\n\n# average over delays\naverage_coef = np.mean(primal_coef_per_delay, axis=0)\nprint(\"(n_features, n_voxels) =\", average_coef.shape)\n```\n\nEven after averaging over delays, the coefficient matrix is still too large\nto interpret it. Therefore, we use principal component analysis (PCA) to\nreduce the dimensionality of the matrix.\n\n\n\n\n```python\nfrom sklearn.decomposition import PCA\n\npca = PCA(n_components=4)\npca.fit(average_coef.T)\ncomponents = pca.components_\nprint(\"(n_components, n_features) =\", components.shape)\n```\n\nWe can check the ratio of explained variance by each principal component.\nWe see that the first four components already explain a large part of the\ncoefficients variance.\n\n\n\n\n```python\nprint(\"PCA explained variance =\", pca.explained_variance_ratio_)\n```\n\nSimilarly to [1]_, we correct the coefficients of features linked by a\nsemantic relationship. When building the wordnet features, if a frame was\nlabeled with `wolf`, the authors automatically added the semantically linked\ncategories `canine`, `carnivore`, `placental mammal`, `mamma`, `vertebrate`,\n`chordate`, `organism`, and `whole`. The authors thus argue that the same\ncorrection needs to be done on the coefficients.\n\n\n\n\n```python\nfrom voxelwise_tutorials.wordnet import load_wordnet\nfrom voxelwise_tutorials.wordnet import correct_coefficients\n_, wordnet_categories = load_wordnet(directory=directory)\ncomponents = correct_coefficients(components.T, wordnet_categories).T\ncomponents -= components.mean(axis=1)[:, None]\ncomponents /= components.std(axis=1)[:, None]\n```\n\nFinally, we plot the first principal component on the wordnet graph. In such\ngraph, edges indicate \"is a\" relationships (e.g. an `athlete` \"is a\"\n`person`). Each marker represents a single noun (circle) or verb (square).\nThe area of each marker indicates the principal component magnitude, and the\ncolor indicates the sign (red is positive, blue is negative).\n\n\n\n\n```python\nfrom voxelwise_tutorials.wordnet import plot_wordnet_graph\nfrom voxelwise_tutorials.wordnet import apply_cmap\n\nfirst_component = components[0]\nnode_sizes = np.abs(first_component)\nnode_colors = apply_cmap(first_component, vmin=-2, vmax=2, cmap='coolwarm',\n                         n_colors=2)\n\nplot_wordnet_graph(node_colors=node_colors, node_sizes=node_sizes)\nplt.show()\n```\n\nAccording to the authors of [1]_, \"this principal component distinguishes\nbetween categories with high stimulus energy (e.g. moving objects like\n`person` and `vehicle`) and those with low stimulus energy (e.g. stationary\nobjects like `sky` and `city`)\".\n\nIn this example, because we use only a single subject and we perform a\ndifferent voxel selection, our result is slightly different than in [1]_. We\nalso use a different regularization parameter in each voxel, while in [1]_\nall voxels had the same regularization parameter. We do not aim at\nreproducing exactly the results in [1]_, but we rather describe the general\napproach.\n\n\n\nTo project the principal component on the cortical surface, we first need to\nuse the fitted PCA to transform the primal weights of all voxels.\n\n\n\n\n```python\n# split the ridge coefficients per delays\nprimal_coef_per_delay = delayer.reshape_by_delays(primal_coef, axis=0)\nprint(\"(n_delays, n_features, n_voxels) =\", primal_coef_per_delay.shape)\ndel primal_coef\n\n# average over delays\naverage_coef = np.mean(primal_coef_per_delay, axis=0)\nprint(\"(n_features, n_voxels) =\", average_coef.shape)\ndel primal_coef_per_delay\n\n# transform with the fitted PCA\naverage_coef_transformed = pca.transform(average_coef.T).T\nprint(\"(n_components, n_voxels) =\", average_coef_transformed.shape)\ndel average_coef\n\n# We make sure vmin = -vmax, so that the colormap is centered on 0.\nvmax = np.percentile(np.abs(average_coef_transformed), 99.9)\n\n# plot the primal weights projected on the first principal component.\nax = plot_flatmap_from_mapper(average_coef_transformed[0], mapper_file,\n                              vmin=-vmax, vmax=vmax, cmap='coolwarm')\nplt.show()\n```\n\nThis flatmap shows in which brain regions the model has the largest\nprojection on the first component. Again, this result is different from the\none in [1]_, and should only be considered as reproducing the general\napproach.\n\n\n\nFollowing [1]_, we also plot the next three principal components on the\nwordnet graph, mapping the three vectors to RGB colors.\n\n\n\n\n```python\nfrom voxelwise_tutorials.wordnet import scale_to_rgb_cube\n\nnext_three_components = components[1:4].T\nnode_sizes = np.linalg.norm(next_three_components, axis=1)\nnode_colors = scale_to_rgb_cube(next_three_components)\nprint(\"(n_nodes, n_channels) =\", node_colors.shape)\n\nplot_wordnet_graph(node_colors=node_colors, node_sizes=node_sizes)\nplt.show()\n```\n\nAccording to the authors of [1]_, \"this graph shows that categories thought\nto be semantically related (e.g. athletes and walking) are represented\nsimilarly in the brain\".\n\n\n\nFinally, we project these principal components on the cortical surface.\n\n\n\n\n```python\nfrom voxelwise_tutorials.viz import plot_3d_flatmap_from_mapper\n\nvoxel_colors = scale_to_rgb_cube(average_coef_transformed[1:4].T, clip=3).T\nprint(\"(n_channels, n_voxels) =\", voxel_colors.shape)\n\nax = plot_3d_flatmap_from_mapper(voxel_colors[0], voxel_colors[1],\n                                 voxel_colors[2], mapper_file=mapper_file,\n                                 vmin=0, vmax=1, vmin2=0, vmax2=1, vmin3=0,\n                                 vmax3=1)\nplt.show()\n```\n\nAgain, our results are different from the ones in [1]_, for the same reasons\nmentioned earlier.\n\n\n\n## References\n\n.. [1] Huth, A. G., Nishimoto, S., Vu, A. T., & Gallant, J. L. (2012).\n   A continuous semantic space describes the representation of thousands of\n   object and action categories across the human brain. Neuron, 76(6),\n   1210-1224.\n\n.. [2] Saunders, C., Gammerman, A., & Vovk, V. (1998).\n   Ridge regression learning algorithm in dual variables.\n\n\n\n\n```python\n%reset -f\n```\n\n\n# 03_plot_hemodynamic_response.ipynb\n\n\n\n```python\n%matplotlib inline\n```\n\n\n# Visualize the hemodynamic response\n\nIn this example, we describe how the hemodynamic response function was\nestimated in the previous model. We fit the same ridge model as in the previous\nexample, and further describe the need to delay the features in time to account\nfor the delayed BOLD response.\n\nBecause of the temporal dynamics of neurovascular coupling, the recorded BOLD\nsignal is delayed in time with respect to the stimulus. To account for this\nlag, we fit encoding models on delayed features. In this way, the linear\nregression model weighs each delayed feature separately and recovers the shape\nof the hemodynamic response function in each voxel separately. In turn, this\nmethod (also known as a Finite Impulse Response model, or FIR) maximizes the\nmodel prediction accuracy. With a repetition time of 2 seconds, we typically\nuse 4 delays [1, 2, 3, 4] to cover the peak of the the hemodynamic response\nfunction. However, the optimal number of delays can vary depending on the\nexperiment and the brain area of interest, so you should experiment with\ndifferent delays.\n\nIn this example, we show that a model without delays performs far worse than a\nmodel with delays. We also show how to visualize the estimated hemodynamic\nresponse function (HRF) from a model with delays.\n\n\n\n```python\n\n```\n\n## Path of the data directory\n\n\n\n\n```python\nimport os\nfrom voxelwise_tutorials.io import get_data_home\ndirectory = os.path.join(get_data_home(), \"vim-5\")\nprint(directory)\n```\n\n\n```python\n# modify to use another subject\nsubject = \"S01\"\n```\n\n## Load the data\n\nWe first load the fMRI responses.\n\n\n\n\n```python\nimport numpy as np\nfrom voxelwise_tutorials.io import load_hdf5_array\n\nfile_name = os.path.join(directory, \"responses\", f\"{subject}_responses.hdf\")\nY_train = load_hdf5_array(file_name, key=\"Y_train\")\nY_test = load_hdf5_array(file_name, key=\"Y_test\")\n\nprint(\"(n_samples_train, n_voxels) =\", Y_train.shape)\nprint(\"(n_repeats, n_samples_test, n_voxels) =\", Y_test.shape)\n```\n\nWe average the test repeats, to remove the non-repeatable part of fMRI\nresponses.\n\n\n\n\n```python\nY_test = Y_test.mean(0)\n\nprint(\"(n_samples_test, n_voxels) =\", Y_test.shape)\n```\n\nWe fill potential NaN (not-a-number) values with zeros.\n\n\n\n\n```python\nY_train = np.nan_to_num(Y_train)\nY_test = np.nan_to_num(Y_test)\n```\n\nThen, we load the semantic \"wordnet\" features.\n\n\n\n\n```python\nfeature_space = \"wordnet\"\n\nfile_name = os.path.join(directory, \"features\", f\"{feature_space}.hdf\")\nX_train = load_hdf5_array(file_name, key=\"X_train\")\nX_test = load_hdf5_array(file_name, key=\"X_test\")\n\nprint(\"(n_samples_train, n_features) =\", X_train.shape)\nprint(\"(n_samples_test, n_features) =\", X_test.shape)\n```\n\n## Define the cross-validation scheme\n\nWe define the same leave-one-run-out cross-validation split as in the\nprevious example.\n\n\n\n\n```python\nfrom sklearn.model_selection import check_cv\nfrom voxelwise_tutorials.utils import generate_leave_one_run_out\n\n# indice of first sample of each run\nrun_onsets = load_hdf5_array(file_name, key=\"run_onsets\")\nprint(run_onsets)\n```\n\nWe define a cross-validation splitter, compatible with ``scikit-learn`` API.\n\n\n\n\n```python\nn_samples_train = X_train.shape[0]\ncv = generate_leave_one_run_out(n_samples_train, run_onsets)\ncv = check_cv(cv)  # copy the cross-validation splitter into a reusable list\n```\n\n## Define the model\n\nWe define the same model as in the previous example. See the previous\nexample for more details about the model definition.\n\n\n\n\n```python\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom voxelwise_tutorials.delayer import Delayer\nfrom himalaya.kernel_ridge import KernelRidgeCV\nfrom himalaya.backend import set_backend\nbackend = set_backend(\"torch_cuda\", on_error=\"warn\")\n\nX_train = X_train.astype(\"float32\")\nX_test = X_test.astype(\"float32\")\n\nalphas = np.logspace(1, 20, 20)\n\npipeline = make_pipeline(\n    StandardScaler(with_mean=True, with_std=False),\n    Delayer(delays=[1, 2, 3, 4]),\n    KernelRidgeCV(\n        alphas=alphas, cv=cv,\n        solver_params=dict(n_targets_batch=500, n_alphas_batch=5,\n                           n_targets_batch_refit=100)),\n)\n```\n\n\n```python\nfrom sklearn import set_config\nset_config(display='diagram')  # requires scikit-learn 0.23\npipeline\n```\n\n## Fit the model\n\nWe fit on the train set, and score on the test set.\n\n\n\n\n```python\npipeline.fit(X_train, Y_train)\n\nscores = pipeline.score(X_test, Y_test)\nscores = backend.to_numpy(scores)\nprint(\"(n_voxels,) =\", scores.shape)\n```\n\n## Intermission: understanding delays\n\nTo have an intuitive understanding of what we accomplish by delaying the\nfeatures before model fitting, we will simulate one voxel and a single\nfeature. We will then create a ``Delayer`` object (which was used in the\nprevious pipeline) and visualize its effect on our single feature. Let's\nstart by simulating the data.\n\n\n\n\n```python\n# number of total trs\nn_trs = 50\n# repetition time for the simulated data\nTR = 2.0\nrng = np.random.RandomState(42)\ny = rng.randn(n_trs)\nx = np.zeros(n_trs)\n# add some arbitrary value to our feature\nx[15:20] = .5\nx += rng.randn(n_trs) * 0.1  # add some noise\n\n# create a delayer object and delay the features\ndelayer = Delayer(delays=[0, 1, 2, 3, 4])\nx_delayed = delayer.fit_transform(x[:, None])\n```\n\nIn the next cell we are plotting six lines. The subplot at the top shows the\nsimulated BOLD response, while the other subplots show the simulated feature\nat different delays. The effect of the delayer is clear: it creates multiple\ncopies of the original feature shifted forward in time by how many samples we\nrequested (in this case, from 0 to 4 samples, which correspond to 0, 2, 4, 6,\nand 8 s in time with a 2 s TR).\n\nWhen these delayed features are used to fit a voxelwise encoding model, the\nbrain response $y$ at time $t$ is simultaneously modeled by the\nfeature $x$ at times $t-0, t-2, t-4, t-6, t-8$. In the remaining\nof this example we will see that this method improves model prediction accuracy\nand it allows to account for the underlying shape of the hemodynamic response\nfunction.\n\n\n\n\n```python\nimport matplotlib.pyplot as plt\nfig, axs = plt.subplots(6, 1, figsize=(8, 6.5), constrained_layout=True, \n        sharex=True)\ntimes = np.arange(n_trs)*TR\n\naxs[0].plot(times, y, color=\"r\")\naxs[0].set_title(\"BOLD response\")\nfor i, (ax, xx) in enumerate(zip(axs.flat[1:], x_delayed.T)):\n  ax.plot(times, xx, color='k')\n  ax.set_title(\"$x(t - {0:.0f})$ (feature delayed by {1} sample{2})\".format(\n      i*TR, i, \"\" if i == 1 else \"s\"))\nfor ax in axs.flat:\n  ax.axvline(40, color='gray')\n  ax.set_yticks([])\n_ = axs[-1].set_xlabel(\"Time [s]\")\nplt.show()\n```\n\n## Compare with a model without delays\n\nWe define here another model without feature delays (i.e. no ``Delayer``).\nBecause the BOLD signal is inherently slow due to the dynamics of\nneuro-vascular coupling, this model is unlikely to perform well.\n\n\n\n\n```python\npipeline_no_delay = make_pipeline(\n    StandardScaler(with_mean=True, with_std=False),\n    KernelRidgeCV(\n        alphas=alphas, cv=cv,\n        solver_params=dict(n_targets_batch=500, n_alphas_batch=5,\n                           n_targets_batch_refit=100)),\n)\npipeline_no_delay\n```\n\nWe fit and score the model as the previous one.\n\n\n\n\n```python\npipeline_no_delay.fit(X_train, Y_train)\nscores_no_delay = pipeline_no_delay.score(X_test, Y_test)\nscores_no_delay = backend.to_numpy(scores_no_delay)\nprint(\"(n_voxels,) =\", scores_no_delay.shape)\n```\n\nThen, we plot the comparison of model prediction accuracies with a 2D\nhistogram. All ~70k voxels are represented in this histogram, where the\ndiagonal corresponds to identical prediction accuracy for both models. A\ndistibution deviating from the diagonal means that one model has better\nprediction accuracy than the other.\n\n\n\n\n```python\nfrom voxelwise_tutorials.viz import plot_hist2d\n\nax = plot_hist2d(scores_no_delay, scores)\nax.set(\n    title='Generalization R2 scores',\n    xlabel='model without delays',\n    ylabel='model with delays',\n)\nplt.show()\n```\n\nWe see that the model with delays performs much better than the model without\ndelays. This can be seen in voxels with scores above 0. The distribution\nof scores below zero is not very informative, since it corresponds to voxels\nwith poor predictive performance anyway, and it only shows which model is\noverfitting the most.\n\n\n\n## Visualize the HRF\n\nWe just saw that delays are necessary to model BOLD responses. Here we show\nhow the fitted ridge regression weights follow the hemodynamic response\nfunction (HRF).\n\nFitting a kernel ridge regression results in a set of coefficients called the\n\"dual\" coefficients $w$. These coefficients differ from the \"primal\"\ncoefficients $\\beta$ obtained with a ridge regression, but the primal\ncoefficients can be computed from the dual coefficients using the training\nfeatures $X$:\n\n\\begin{align}\\beta = X^\\top w\\end{align}\n\nTo better visualize the HRF, we will refit a model with more delays, but only\non a selection of voxels to speed up the computations.\n\n\n\n\n```python\n# pick the 10 best voxels\nvoxel_selection = np.argsort(scores)[-10:]\n\n# define a pipeline with more delays\npipeline_more_delays = make_pipeline(\n    StandardScaler(with_mean=True, with_std=False),\n    Delayer(delays=[0, 1, 2, 3, 4, 5, 6]),\n    KernelRidgeCV(\n        alphas=alphas, cv=cv,\n        solver_params=dict(n_targets_batch=500, n_alphas_batch=5,\n                           n_targets_batch_refit=100)),\n)\n\npipeline_more_delays.fit(X_train, Y_train[:, voxel_selection])\n\n# get the (primal) ridge regression coefficients\nprimal_coef = pipeline_more_delays[-1].get_primal_coef()\nprimal_coef = backend.to_numpy(primal_coef)\n\n# split the ridge coefficients per delays\ndelayer = pipeline_more_delays.named_steps['delayer']\nprimal_coef_per_delay = delayer.reshape_by_delays(primal_coef, axis=0)\nprint(\"(n_delays, n_features, n_voxels) =\", primal_coef_per_delay.shape)\n\n# select the feature with the largest coefficients for each voxel\nfeature_selection = np.argmax(np.sum(np.abs(primal_coef_per_delay), axis=0),\n                              axis=0)\nprimal_coef_selection = primal_coef_per_delay[:, feature_selection,\n                                              np.arange(len(voxel_selection))]\n\nplt.plot(delayer.delays, primal_coef_selection)\nplt.xlabel('Delays')\nplt.xticks(delayer.delays)\nplt.ylabel('Ridge coefficients')\nplt.title(f'Largest feature for the {len(voxel_selection)} best voxels')\nplt.axhline(0, color='k', linewidth=0.5)\nplt.show()\n```\n\nWe see that the hemodynamic response function (HRF) is captured in the model\nweights. Note that in this dataset, the brain responses are recorded every\ntwo seconds.\n\n\n\n\n```python\n%reset -f\n```\n\n\n# 04_plot_motion_energy_model.ipynb\n\n\n\n```python\n%matplotlib inline\n```\n\n\n# Fit a ridge model with motion energy features\n\nIn this example, we model the fMRI responses with motion-energy features\nextracted from the movie stimulus. The model is a regularized linear regression\nmodel.\n\nThis tutorial reproduces part of the analysis described in Nishimoto et al\n(2011) [1]_. See this publication for more details about the experiment, the\nmotion-energy features, along with more results and more discussions.\n\n*Motion-energy features:* Motion-energy features result from filtering a video\nstimulus with spatio-temporal Gabor filters. A pyramid of filters is used to\ncompute the motion-energy features at multiple spatial and temporal scales.\nMotion-energy features were introduced in [1]_.\n\n*Summary:* As in the previous example, we first concatenate the features with\nmultiple delays, to account for the slow hemodynamic response. A linear\nregression model then weights each delayed feature with a different weight, to\nbuild a predictive model of BOLD activity. Again, the linear regression is\nregularized to improve robustness to correlated features and to improve\ngeneralization. The optimal regularization hyperparameter is selected\nindependently on each voxel over a grid-search with cross-validation. Finally,\nthe model generalization performance is evaluated on a held-out test set,\ncomparing the model predictions with the ground-truth fMRI responses.\n\n\n## Path of the data directory\n\n\n\n\n```python\nimport os\nfrom voxelwise_tutorials.io import get_data_home\ndirectory = os.path.join(get_data_home(), \"vim-5\")\nprint(directory)\n```\n\n\n```python\n# modify to use another subject\nsubject = \"S01\"\n```\n\n## Load the data\n\nWe first load the fMRI responses.\n\n\n\n\n```python\nimport numpy as np\n\nfrom voxelwise_tutorials.io import load_hdf5_array\n\nfile_name = os.path.join(directory, \"responses\", f\"{subject}_responses.hdf\")\nY_train = load_hdf5_array(file_name, key=\"Y_train\")\nY_test = load_hdf5_array(file_name, key=\"Y_test\")\n\nprint(\"(n_samples_train, n_voxels) =\", Y_train.shape)\nprint(\"(n_repeats, n_samples_test, n_voxels) =\", Y_test.shape)\n```\n\nWe average the test repeats, to remove the non-repeatable part of fMRI\nresponses.\n\n\n\n\n```python\nY_test = Y_test.mean(0)\n\nprint(\"(n_samples_test, n_voxels) =\", Y_test.shape)\n```\n\nWe fill potential NaN (not-a-number) values with zeros.\n\n\n\n\n```python\nY_train = np.nan_to_num(Y_train)\nY_test = np.nan_to_num(Y_test)\n```\n\nThen we load the precomputed \"motion-energy\" features.\n\n\n\n\n```python\nfeature_space = \"motion_energy\"\nfile_name = os.path.join(directory, \"features\", f\"{feature_space}.hdf\")\nX_train = load_hdf5_array(file_name, key=\"X_train\")\nX_test = load_hdf5_array(file_name, key=\"X_test\")\n\nprint(\"(n_samples_train, n_features) =\", X_train.shape)\nprint(\"(n_samples_test, n_features) =\", X_test.shape)\n```\n\n## Define the cross-validation scheme\n\nWe define the same leave-one-run-out cross-validation split as in the\nprevious example.\n\n\n\n\n```python\nfrom sklearn.model_selection import check_cv\nfrom voxelwise_tutorials.utils import generate_leave_one_run_out\n\n# indice of first sample of each run\nrun_onsets = load_hdf5_array(file_name, key=\"run_onsets\")\nprint(run_onsets)\n```\n\nWe define a cross-validation splitter, compatible with ``scikit-learn`` API.\n\n\n\n\n```python\nn_samples_train = X_train.shape[0]\ncv = generate_leave_one_run_out(n_samples_train, run_onsets)\ncv = check_cv(cv)  # copy the cross-validation splitter into a reusable list\n```\n\n## Define the model\n\nWe define the same model as in the previous example. See the previous\nexample for more details about the model definition.\n\n\n\n\n```python\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom voxelwise_tutorials.delayer import Delayer\nfrom himalaya.kernel_ridge import KernelRidgeCV\nfrom himalaya.backend import set_backend\nbackend = set_backend(\"torch_cuda\", on_error=\"warn\")\n\nX_train = X_train.astype(\"float32\")\nX_test = X_test.astype(\"float32\")\n\nalphas = np.logspace(1, 20, 20)\n\npipeline = make_pipeline(\n    StandardScaler(with_mean=True, with_std=False),\n    Delayer(delays=[1, 2, 3, 4]),\n    KernelRidgeCV(\n        alphas=alphas, cv=cv,\n        solver_params=dict(n_targets_batch=500, n_alphas_batch=5,\n                           n_targets_batch_refit=100)),\n)\n```\n\n\n```python\nfrom sklearn import set_config\nset_config(display='diagram')  # requires scikit-learn 0.23\npipeline\n```\n\n## Fit the model\n\nWe fit on the train set, and score on the test set.\n\n\n\n\n```python\npipeline.fit(X_train, Y_train)\n\nscores_motion_energy = pipeline.score(X_test, Y_test)\nscores_motion_energy = backend.to_numpy(scores_motion_energy)\n\nprint(\"(n_voxels,) =\", scores_motion_energy.shape)\n```\n\n## Plot the model performances\nThe performances are computed using the $R^2$ scores.\n\n\n\n\n```python\nimport matplotlib.pyplot as plt\nfrom voxelwise_tutorials.viz import plot_flatmap_from_mapper\n\nmapper_file = os.path.join(directory, \"mappers\", f\"{subject}_mappers.hdf\")\nax = plot_flatmap_from_mapper(scores_motion_energy, mapper_file, vmin=0,\n                              vmax=0.5)\nplt.show()\n```\n\nThe motion-energy features lead to large generalization scores in the\nearly visual cortex (V1, V2, V3, ...). For more discussions about these\nresults, we refer the reader to the original publication [1]_.\n\n\n\n## Compare with the wordnet model\n\nInterestingly, the motion-energy model performs well in different brain\nregions than the semantic \"wordnet\" model fitted in the previous example. To\ncompare the two models, we first need to fit again the wordnet model.\n\n\n\n\n```python\nfeature_space = \"wordnet\"\nfile_name = os.path.join(directory, \"features\", f\"{feature_space}.hdf\")\nX_train = load_hdf5_array(file_name, key=\"X_train\")\nX_test = load_hdf5_array(file_name, key=\"X_test\")\n\nX_train = X_train.astype(\"float32\")\nX_test = X_test.astype(\"float32\")\n```\n\nWe can create an unfitted copy of the pipeline with the ``clone`` function,\nor simply call fit again if we do not need to reuse the previous model.\n\n\n\n\n```python\nif False:\n    from sklearn.base import clone\n    pipeline_wordnet = clone(pipeline)\n    pipeline_wordnet\n```\n\n\n```python\npipeline.fit(X_train, Y_train)\nscores_wordnet = pipeline.score(X_test, Y_test)\nscores_wordnet = backend.to_numpy(scores_wordnet)\n\nax = plot_flatmap_from_mapper(scores_wordnet, mapper_file, vmin=0,\n                              vmax=0.5)\nplt.show()\n```\n\nWe can also plot the comparison of model prediction accuracies with a 2D\nhistogram. All ~70k voxels are represented in this histogram, where the\ndiagonal corresponds to identical prediction accuracy for both models. A\ndistibution deviating from the diagonal means that one model has better\npredictive performance than the other.\n\n\n\n\n```python\nfrom voxelwise_tutorials.viz import plot_hist2d\n\nax = plot_hist2d(scores_wordnet, scores_motion_energy)\nax.set(title='Generalization R2 scores', xlabel='semantic wordnet model',\n       ylabel='motion energy model')\nplt.show()\n```\n\nInterestingly, the well predicted voxels are different in the two models.\nTo further describe these differences, we can plot both performances on the\nsame flatmap, using a 2D colormap.\n\n\n\n\n```python\nfrom voxelwise_tutorials.viz import plot_2d_flatmap_from_mapper\n\nmapper_file = os.path.join(directory, \"mappers\", f\"{subject}_mappers.hdf\")\nax = plot_2d_flatmap_from_mapper(scores_wordnet, scores_motion_energy,\n                                 mapper_file, vmin=0, vmax=0.25, vmin2=0,\n                                 vmax2=0.5, label_1=\"wordnet\",\n                                 label_2=\"motion energy\")\nplt.show()\n```\n\nThe blue regions are well predicted by the motion-energy features, the orange\nregions are well predicted by the wordnet features, and the white regions are\nwell predicted by both feature spaces.\n\nA large part of the visual semantic areas are not only well predicted by the\nwordnet features, but also by the motion-energy features, as indicated by the\nwhite color. Since these two features spaces encode quite different\ninformation, two interpretations are possible. In the first interpretation,\nthe two feature spaces encode complementary information, and could be used\njointly to further increase the generalization performance. In the second\ninterpretation, both feature spaces encode the same information, because of\nspurious stimulus correlations. For example, imagine that the visual stimulus\ncontained faces that appeared consistetly in the same portion of the visual\nfield. In this case, position in the visual field would be perfectly\ncorrelated with the \"face\" semantic category. Thus, motion-energy features\ncould predict responses in face-responsive areas without encoding any\nsemantic information.\n\nTo better disentangle the two feature spaces, we developed a joint model\ncalled `banded ridge regression` [2]_, which fits multiple feature spaces\nsimultaneously with optimal regularization for each feature space. This model\nis described in the next example.\n\n\n\n## References\n\n.. [1] Nishimoto, S., Vu, A. T., Naselaris, T., Benjamini, Y., Yu,\n    B., & Gallant, J. L. (2011). Reconstructing visual experiences from brain\n    activity evoked by natural movies. Current Biology, 21(19), 1641-1646.\n\n.. [2] Nunez-Elizalde, A. O., Huth, A. G., & Gallant, J. L. (2019).\n    Voxelwise encoding models with non-spherical multivariate normal priors.\n    Neuroimage, 197, 482-492.\n\n\n\n\n```python\n%reset -f\n```\n\n\n# 05_plot_banded_ridge_model.ipynb\n\n\n\n```python\n%matplotlib inline\n```\n\n\n# Fit a banded ridge model with both wordnet and motion energy features\n\nIn this example, we model the fMRI responses with a `banded ridge regression`,\nwith two different feature spaces: motion energy and wordnet categories.\n\n*Banded ridge regression:* Since the relative scaling of both feature spaces is\nunknown, we use two regularization hyperparameters (one per feature space) in a\nmodel called banded ridge regression [1]_. Just like with ridge regression, we\noptimize the hyperparameters over cross-validation. An efficient implementation\nof this model is available in the `himalaya\n<https://github.com/gallantlab/himalaya>`_ package.\n\n*Running time:* This example is more computationally intensive than the\nprevious examples. With a GPU backend, model fitting takes around 6 minutes.\nWith a CPU backend, it can last 10 times more.\n\n\n\n```python\n\n```\n\n## Path of the data directory\n\n\n\n\n```python\nimport os\nfrom voxelwise_tutorials.io import get_data_home\ndirectory = os.path.join(get_data_home(), \"vim-5\")\nprint(directory)\n```\n\n\n```python\n# modify to use another subject\nsubject = \"S01\"\n```\n\n## Load the data\n\nAs in the previous examples, we first load the fMRI responses, which are our\nregression targets.\n\n\n\n\n```python\nimport numpy as np\n\nfrom voxelwise_tutorials.io import load_hdf5_array\n\nfile_name = os.path.join(directory, \"responses\", f\"{subject}_responses.hdf\")\nY_train = load_hdf5_array(file_name, key=\"Y_train\")\nY_test = load_hdf5_array(file_name, key=\"Y_test\")\n\nprint(\"(n_samples_train, n_voxels) =\", Y_train.shape)\nprint(\"(n_repeats, n_samples_test, n_voxels) =\", Y_test.shape)\n```\n\nWe also compute the explainable variance, to exclude voxels with low\nexplainable variance from the fit, and speed up the model fitting.\n\n\n\n\n```python\nfrom voxelwise_tutorials.utils import explainable_variance\nev = explainable_variance(Y_test)\nprint(\"(n_voxels,) =\", ev.shape)\n\nmask = ev > 0.1\nprint(\"(n_voxels_mask,) =\", ev[mask].shape)\n```\n\nWe average the test repeats, to remove the non-repeatable part of fMRI\nresponses.\n\n\n\n\n```python\nY_test = Y_test.mean(0)\n\nprint(\"(n_samples_test, n_voxels) =\", Y_test.shape)\n```\n\nWe fill potential NaN (not-a-number) values with zeros.\n\n\n\n\n```python\nY_train = np.nan_to_num(Y_train)\nY_test = np.nan_to_num(Y_test)\n```\n\nAnd we make sure the targets are centered.\n\n\n\n\n```python\nY_train -= Y_train.mean(0)\nY_test -= Y_test.mean(0)\n```\n\nThen we load both feature spaces, that are going to be used for the\nlinear regression model.\n\n\n\n\n```python\nfeature_names = [\"wordnet\", \"motion_energy\"]\n\nXs_train = []\nXs_test = []\nn_features_list = []\nfor feature_space in feature_names:\n    file_name = os.path.join(directory, \"features\", f\"{feature_space}.hdf\")\n    Xi_train = load_hdf5_array(file_name, key=\"X_train\")\n    Xi_test = load_hdf5_array(file_name, key=\"X_test\")\n\n    Xs_train.append(Xi_train.astype(dtype=\"float32\"))\n    Xs_test.append(Xi_test.astype(dtype=\"float32\"))\n    n_features_list.append(Xi_train.shape[1])\n\n# concatenate the feature spaces\nX_train = np.concatenate(Xs_train, 1)\nX_test = np.concatenate(Xs_test, 1)\n\nprint(\"(n_samples_train, n_features_total) =\", X_train.shape)\nprint(\"(n_samples_test, n_features_total) =\", X_test.shape)\nprint(\"[n_features_wordnet, n_features_motion_energy] =\", n_features_list)\n```\n\n## Define the cross-validation scheme\n\nWe define again a leave-one-run-out cross-validation split scheme.\n\n\n\n\n```python\nfrom sklearn.model_selection import check_cv\nfrom voxelwise_tutorials.utils import generate_leave_one_run_out\n\n# indice of first sample of each run\nrun_onsets = load_hdf5_array(file_name, key=\"run_onsets\")\nprint(run_onsets)\n```\n\nWe define a cross-validation splitter, compatible with ``scikit-learn`` API.\n\n\n\n\n```python\nn_samples_train = X_train.shape[0]\ncv = generate_leave_one_run_out(n_samples_train, run_onsets)\ncv = check_cv(cv)  # copy the cross-validation splitter into a reusable list\n```\n\n## Define the model\n\nThe model pipeline contains similar steps than the pipeline from previous\nexamples. We remove the mean of each feature with a ``StandardScaler``,\nand add delays with a ``Delayer``.\n\n\n\n\n```python\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom voxelwise_tutorials.delayer import Delayer\nfrom himalaya.backend import set_backend\nbackend = set_backend(\"torch_cuda\", on_error=\"warn\")\n```\n\nTo fit the banded ridge model, we use ``himalaya``'s\n``MultipleKernelRidgeCV`` model, with a separate linear kernel per feature\nspace. Similarly to ``KernelRidgeCV``, the model optimizes the\nhyperparameters over cross-validation. However, while ``KernelRidgeCV`` has\nto optimize only one hyperparameter (``alpha``), ``MultipleKernelRidgeCV``\nhas to optimize ``m`` hyperparameters, where ``m`` is the number of feature\nspaces (here ``m = 2``). To do so, the model implements two different\nsolvers, one using hyperparameter random search, and one using hyperparameter\ngradient descent. For large number of targets, we recommend using the\nrandom-search solver.\n\n\n\nThe class takes a number of common parameters during initialization, such as\n``kernels``, or ``solver``. Since the solver parameters vary depending on the\nsolver used, they are passed as a ``solver_params`` dictionary.\n\n\n\n\n```python\nfrom himalaya.kernel_ridge import MultipleKernelRidgeCV\n\n# Here we will use the \"random_search\" solver.\nsolver = \"random_search\"\n\n# We can check its specific parameters in the function docstring:\nsolver_function = MultipleKernelRidgeCV.ALL_SOLVERS[solver]\nprint(\"Docstring of the function %s:\" % solver_function.__name__)\nprint(solver_function.__doc__)\n```\n\nThe hyperparameter random-search solver separates the hyperparameters into a\nshared regularization ``alpha`` and a vector of positive kernel weights which\nsum to one. This separation of hyperparameters allows to explore efficiently\na large grid of values for ``alpha`` for each sampled kernel weights vector.\n\nWe use *20* random-search iterations to have a reasonably fast example. To\nhave better results, especially for larger number of feature spaces, one\nmight need more iterations. (Note that there is currently no stopping\ncriterion in the random-search method.)\n\n\n\n\n```python\nn_iter = 20\n\nalphas = np.logspace(1, 20, 20)\n```\n\nBatch parameters, used to reduce the necessary GPU memory. A larger value\nwill be a bit faster, but the solver might crash if it is out of memory.\nOptimal values depend on the size of your dataset.\n\n\n\n\n```python\nn_targets_batch = 200\nn_alphas_batch = 5\nn_targets_batch_refit = 200\n```\n\nWe put all these parameters in a dictionary ``solver_params``, and define\nthe main estimator ``MultipleKernelRidgeCV``.\n\n\n\n\n```python\nsolver_params = dict(n_iter=n_iter, alphas=alphas,\n                     n_targets_batch=n_targets_batch,\n                     n_alphas_batch=n_alphas_batch,\n                     n_targets_batch_refit=n_targets_batch_refit)\n\nmkr_model = MultipleKernelRidgeCV(kernels=\"precomputed\", solver=solver,\n                                  solver_params=solver_params, cv=cv)\n```\n\nWe need a bit more work than in previous examples before defining the full\npipeline, since the banded ridge model requires `multiple` precomputed\nkernels, one for each feature space. To compute them, we use the\n``ColumnKernelizer``, which can create multiple kernels from different\ncolumn of your features array. ``ColumnKernelizer`` works similarly to\n``scikit-learn``'s ``ColumnTransformer``, but instead of returning a\nconcatenation of transformed features, it returns a stack of kernels,\nas required in ``MultipleKernelRidgeCV(kernels=\"precomputed\")``.\n\n\n\nFirst, we create a different ``Kernelizer`` for each feature space.\nHere we use a linear kernel for all feature spaces, but ``ColumnKernelizer``\naccepts any ``Kernelizer``, or ``scikit-learn`` ``Pipeline`` ending with a\n``Kernelizer``.\n\n\n\n\n```python\nfrom himalaya.kernel_ridge import Kernelizer\nfrom sklearn import set_config\nset_config(display='diagram')  # requires scikit-learn 0.23\n\npreprocess_pipeline = make_pipeline(\n    StandardScaler(with_mean=True, with_std=False),\n    Delayer(delays=[1, 2, 3, 4]),\n    Kernelizer(kernel=\"linear\"),\n)\npreprocess_pipeline\n```\n\nThe column kernelizer applies a different pipeline on each selection of\nfeatures, here defined with ``slices``.\n\n\n\n\n```python\nfrom himalaya.kernel_ridge import ColumnKernelizer\n\n# Find the start and end of each feature space in the concatenated ``X_train``.\nstart_and_end = np.concatenate([[0], np.cumsum(n_features_list)])\nslices = [\n    slice(start, end)\n    for start, end in zip(start_and_end[:-1], start_and_end[1:])\n]\nslices\n```\n\n\n```python\nkernelizers_tuples = [(name, preprocess_pipeline, slice_)\n                      for name, slice_ in zip(feature_names, slices)]\ncolumn_kernelizer = ColumnKernelizer(kernelizers_tuples)\ncolumn_kernelizer\n\n# (Note that ``ColumnKernelizer`` has a parameter ``n_jobs`` to parallelize\n# each ``Kernelizer``, yet such parallelism does not work with GPU arrays.)\n```\n\nThen we can define the model pipeline.\n\n\n\n\n```python\npipeline = make_pipeline(\n    column_kernelizer,\n    mkr_model,\n)\npipeline\n```\n\n## Fit the model\n\nWe fit on the train set, and score on the test set.\n\nTo speed up the fit and to limit the memory peak in Colab, we only fit on\nvoxels with explainable variance above 0.1.\n\nWith a GPU backend, the fitting of this model takes around 6 minutes. With a\nCPU backend, it can last 10 times more.\n\n\n\n\n```python\npipeline.fit(X_train, Y_train[:, mask])\n\nscores_mask = pipeline.score(X_test, Y_test[:, mask])\nscores_mask = backend.to_numpy(scores_mask)\nprint(\"(n_voxels_mask,) =\", scores_mask.shape)\n\n# Then we extend the scores to all voxels, giving a score of zero to unfitted\n# voxels.\nn_voxels = Y_train.shape[1]\nscores = np.zeros(n_voxels)\nscores[mask] = scores_mask\nprint(\"(n_voxels,) =\", scores.shape)\n```\n\n## Compare with a ridge model\n\nWe can compare with a baseline model, which does not use one hyperparameter\nper feature space, but instead shares the same hyperparameter for all feature\nspaces.\n\n\n\n\n```python\nfrom himalaya.kernel_ridge import KernelRidgeCV\n\npipeline_baseline = make_pipeline(\n    StandardScaler(with_mean=True, with_std=False),\n    Delayer(delays=[1, 2, 3, 4]),\n    KernelRidgeCV(\n        alphas=alphas, cv=cv,\n        solver_params=dict(n_targets_batch=n_targets_batch,\n                           n_alphas_batch=n_alphas_batch,\n                           n_targets_batch_refit=n_targets_batch_refit)),\n)\npipeline_baseline\n```\n\n\n```python\npipeline_baseline.fit(X_train, Y_train[:, mask])\nscores_baseline_mask = pipeline_baseline.score(X_test, Y_test[:, mask])\nscores_baseline_mask = backend.to_numpy(scores_baseline_mask)\n\n# extend to unfitted voxels\nn_voxels = Y_train.shape[1]\nscores_baseline = np.zeros(n_voxels)\nscores_baseline[mask] = scores_baseline_mask\n```\n\nHere we plot the comparison of model prediction accuracies with a 2D\nhistogram. All 70k voxels are represented in this histogram, where the\ndiagonal corresponds to identical model prediction accuracy for both models.\nA distibution deviating from the diagonal means that one model has better\npredictive performance than the other.\n\n\n\n\n```python\nimport matplotlib.pyplot as plt\nfrom voxelwise_tutorials.viz import plot_hist2d\n\nax = plot_hist2d(scores_baseline, scores)\nax.set(title='Generalization R2 scores', xlabel='KernelRidgeCV',\n       ylabel='MultipleKernelRidgeCV')\nplt.show()\n```\n\nWe see that the banded ridge model (``MultipleKernelRidgeCV``) outperforms\nthe ridge model (``KernelRidegeCV``). Indeed, banded ridge regression is able\nto find the optimal scalings of each feature space, independently on each\nvoxel. Banded ridge regression is thus able to perform a soft selection\nbetween the available feature spaces, based on the cross-validation\nperformances.\n\n\n\n## Plot the banded ridge split\n\nOn top of better prediction accuracy, banded ridge regression also gives a\nway to disentangle the contribution of the two feature spaces. To do so, we\ntake the kernel weights and the ridge (dual) weights corresponding to each\nfeature space, and use them to compute the prediction from each feature space\nseparately.\n\n\\begin{align}\\hat{y} = \\sum_i^m \\hat{y}_i = \\sum_i^m \\gamma_i K_i \\hat{w}\\end{align}\n\nThen, we use these split predictions to compute split $\\tilde{R}^2_i$\nscores. These scores are corrected so that their sum is equal to the\n$R^2$ score of the full prediction $\\hat{y}$.\n\n\n\n\n```python\nfrom himalaya.scoring import r2_score_split\n\nY_test_pred_split = pipeline.predict(X_test, split=True)\nsplit_scores_mask = r2_score_split(Y_test[:, mask], Y_test_pred_split)\n\nprint(\"(n_kernels, n_samples_test, n_voxels_mask) =\", Y_test_pred_split.shape)\nprint(\"(n_kernels, n_voxels_mask) =\", split_scores_mask.shape)\n\n# extend to unfitted voxels\nn_kernels = split_scores_mask.shape[0]\nn_voxels = Y_train.shape[1]\nsplit_scores = np.zeros((n_kernels, n_voxels))\nsplit_scores[:, mask] = backend.to_numpy(split_scores_mask)\nprint(\"(n_kernels, n_voxels) =\", split_scores.shape)\n```\n\nWe can then plot the split scores on a flatmap with a 2D colormap.\n\n\n\n\n```python\nfrom voxelwise_tutorials.viz import plot_2d_flatmap_from_mapper\n\nmapper_file = os.path.join(directory, \"mappers\", f\"{subject}_mappers.hdf\")\nax = plot_2d_flatmap_from_mapper(split_scores[0], split_scores[1],\n                                 mapper_file, vmin=0, vmax=0.25, vmin2=0,\n                                 vmax2=0.5, label_1=feature_names[0],\n                                 label_2=feature_names[1])\nplt.show()\n```\n\nThe blue regions are better predicted by the motion-energy features, the\norange regions are better predicted by the wordnet features, and the white\nregions are well predicted by both feature spaces.\n\nCompared to the last figure of the previous example, we see that most white\nregions have been replaced by either blue or orange regions. The banded ridge\nregression disentangled the two feature spaces in voxels where both feature\nspaces had good prediction accuracy (see previous example). For example,\nmotion-energy features predict brain activity in early visual cortex, while\nwordnet features predict in semantic visual areas. For more discussions about\nthese results, we refer the reader to the original publication [1]_.\n\n\n\n## References\n\n.. [1] Nunez-Elizalde, A. O., Huth, A. G., & Gallant, J. L. (2019).\n    Voxelwise encoding models with non-spherical multivariate normal priors.\n    Neuroimage, 197, 482-492.\n\n\n", "meta": {"hexsha": "0af95cbf72cc71dea6fc992a6c0e9f2d50d10a28", "size": 108271, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorials/notebooks/movies_3T/merged_for_colab.ipynb", "max_stars_repo_name": "gallantlab/voxelwise_tutorials", "max_stars_repo_head_hexsha": "3df639dd5fb957410f41b4a3b986c9f903f5333b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2021-09-08T22:22:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T18:06:33.000Z", "max_issues_repo_path": "tutorials/notebooks/movies_3T/merged_for_colab.ipynb", "max_issues_repo_name": "gallantlab/voxelwise_tutorials", "max_issues_repo_head_hexsha": "3df639dd5fb957410f41b4a3b986c9f903f5333b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-09-11T16:06:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T23:39:40.000Z", "max_forks_repo_path": "tutorials/notebooks/movies_3T/merged_for_colab.ipynb", "max_forks_repo_name": "gallantlab/voxelwise_tutorials", "max_forks_repo_head_hexsha": "3df639dd5fb957410f41b4a3b986c9f903f5333b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-09-13T19:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T04:35:11.000Z", "avg_line_length": 29.9256495301, "max_line_length": 135, "alphanum_fraction": 0.5986367541, "converted": true, "num_tokens": 16524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742626558767584, "lm_q2_score": 0.0715912034062289, "lm_q1q2_score": 0.02272492834616694}}
{"text": "```python\n!pip install qiskit\n\n```\n\n    Collecting qiskit\n      Downloading https://files.pythonhosted.org/packages/6f/61/cb7506e17a2566dc8a31a3e1924d91ac0bdd8ff07c71ec698c06647b6306/qiskit-0.26.2.tar.gz\n    Collecting qiskit-terra==0.17.4\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/b3/0c/3c7a8dd451dae0907263e9de9e3e34909e15e18c88a589b44581972c8511/qiskit_terra-0.17.4-cp37-cp37m-manylinux2010_x86_64.whl (6.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.0MB 5.2MB/s \n    \u001b[?25hCollecting qiskit-aer==0.8.2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/c2/d2/6ff15c370b5465b32529b528bf3f4ce1e01f74498be16203aa1c04b67022/qiskit_aer-0.8.2-cp37-cp37m-manylinux2010_x86_64.whl (18.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 18.0MB 215kB/s \n    \u001b[?25hCollecting qiskit-ibmq-provider==0.13.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/be/99/74bbb901f88603a7d850d4889abc06d81ba702e4227151f4a5b66f2631fe/qiskit_ibmq_provider-0.13.1-py3-none-any.whl (228kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 235kB 47.1MB/s \n    \u001b[?25hCollecting qiskit-ignis==0.6.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/54/be/a13c828e457e09d979667a61bddbd8c7246aafa94e2501b6a9154429cbea/qiskit_ignis-0.6.0-py3-none-any.whl (207kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 215kB 42.6MB/s \n    \u001b[?25hCollecting qiskit-aqua==0.9.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/88/79/392c57b978decbb24b902344b536af52c40a751aed0ebbaefa8bc2964cb5/qiskit_aqua-0.9.1-py3-none-any.whl (2.1MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.1MB 31.4MB/s \n    \u001b[?25hRequirement already satisfied: scipy>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (1.4.1)\n    Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (2.6.0)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (2.8.1)\n    Collecting fastjsonschema>=2.10\n      Downloading https://files.pythonhosted.org/packages/d1/fb/ea090e917b18320f79be31d754bbe496b715175e865603cfce1eaed2e774/fastjsonschema-2.15.1-py3-none-any.whl\n    Collecting ply>=3.10\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/a3/58/35da89ee790598a0700ea49b2a66594140f44dec458c07e8e3d4979137fc/ply-3.11-py2.py3-none-any.whl (49kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 5.7MB/s \n    \u001b[?25hRequirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (1.7.1)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (0.3.3)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (5.4.8)\n    Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (1.19.5)\n    Collecting python-constraint>=1.4\n      Downloading https://files.pythonhosted.org/packages/37/8b/5f1bc2734ca611943e1d6733ee244238679f6410a10cd45ede55a61a8402/python-constraint-1.4.0.tar.bz2\n    Collecting retworkx>=0.8.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/9e/cd/70d436f170aa1ead2ac9e4c19c8838633355d48b530f09455eab0af2f98e/retworkx-0.9.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.5MB 27.3MB/s \n    \u001b[?25hCollecting pybind11>=2.6\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/8d/43/7339dbabbc2793718d59703aace4166f53c29ee1c202f6ff5bf8a26c4d91/pybind11-2.6.2-py2.py3-none-any.whl (191kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 194kB 28.1MB/s \n    \u001b[?25hCollecting websockets>=8\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/84/64/78c2b3fe37730b30dca3c93d1f7f4a4286767f86e7c04cf3571b39bc2fb7/websockets-9.1-cp37-cp37m-manylinux2010_x86_64.whl (103kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 112kB 53.2MB/s \n    \u001b[?25hRequirement already satisfied: nest-asyncio!=1.1.0,>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit) (1.5.1)\n    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit) (2.23.0)\n    Collecting requests-ntlm>=1.1.0\n      Downloading https://files.pythonhosted.org/packages/03/4b/8b9a1afde8072c4d5710d9fa91433d504325821b038e00237dc8d6d833dc/requests_ntlm-1.1.0-py2.py3-none-any.whl\n    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit) (1.24.3)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ignis==0.6.0->qiskit) (56.1.0)\n    Requirement already satisfied: h5py<=3.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (3.1.0)\n    Requirement already satisfied: scikit-learn<=0.24.1,>=0.20.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (0.22.2.post1)\n    Requirement already satisfied: pandas<=1.2.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (1.1.5)\n    Collecting yfinance<=0.1.55\n      Downloading https://files.pythonhosted.org/packages/7a/e8/b9d7104d3a4bf39924799067592d9e59119fcfc900a425a12e80a3123ec8/yfinance-0.1.55.tar.gz\n    Collecting quandl<=3.6.0\n      Downloading https://files.pythonhosted.org/packages/c2/58/9f0e69d836045e3865d263e9ed49f42b23a58526fdabb30f74c430baee3f/Quandl-3.6.0-py2.py3-none-any.whl\n    Collecting dlx<=1.0.4\n      Downloading https://files.pythonhosted.org/packages/54/c0/b8fb5bb727e983b6f5251433ef941b48f38c65bb0bd6ec509e9185bcd406/dlx-1.0.4.tar.gz\n    Collecting docplex<=2.20.204; sys_platform != \"darwin\"\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/87/99/6f7c219b39fd58c84688ad0713eb932bfcf6be81fc74519e43ea9c915b56/docplex-2.20.204.tar.gz (611kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 614kB 31.8MB/s \n    \u001b[?25hRequirement already satisfied: fastdtw<=0.3.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (0.3.4)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.8.0->qiskit-terra==0.17.4->qiskit) (1.15.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra==0.17.4->qiskit) (1.2.1)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit) (2020.12.5)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit) (3.0.4)\n    Collecting ntlm-auth>=1.0.2\n      Downloading https://files.pythonhosted.org/packages/ff/84/97c550164b54942b0e908c31ef09d9469f3ba4cd7332a671e2125732f63b/ntlm_auth-1.5.0-py2.py3-none-any.whl\n    Collecting cryptography>=1.3\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/b2/26/7af637e6a7e87258b963f1731c5982fb31cd507f0d90d91836e446955d02/cryptography-3.4.7-cp36-abi3-manylinux2014_x86_64.whl (3.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.2MB 32.7MB/s \n    \u001b[?25hRequirement already satisfied: cached-property; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from h5py<=3.1.0->qiskit-aqua==0.9.1->qiskit) (1.5.2)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn<=0.24.1,>=0.20.0->qiskit-aqua==0.9.1->qiskit) (1.0.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas<=1.2.3->qiskit-aqua==0.9.1->qiskit) (2018.9)\n    Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance<=0.1.55->qiskit-aqua==0.9.1->qiskit) (0.0.9)\n    Collecting lxml>=4.5.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/30/c0/d0526314971fc661b083ab135747dc68446a3022686da8c16d25fcf6ef07/lxml-4.6.3-cp37-cp37m-manylinux2014_x86_64.whl (6.3MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.3MB 28.8MB/s \n    \u001b[?25hRequirement already satisfied: more-itertools in /usr/local/lib/python3.7/dist-packages (from quandl<=3.6.0->qiskit-aqua==0.9.1->qiskit) (8.7.0)\n    Collecting inflection>=0.3.1\n      Downloading https://files.pythonhosted.org/packages/59/91/aa6bde563e0085a02a435aa99b49ef75b0a4b062635e606dab23ce18d720/inflection-0.5.1-py2.py3-none-any.whl\n    Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit) (1.14.5)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit) (2.20)\n    Building wheels for collected packages: qiskit, python-constraint, yfinance, dlx, docplex\n      Building wheel for qiskit (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for qiskit: filename=qiskit-0.26.2-cp37-none-any.whl size=10491 sha256=f918bb498cb8dbde768f9544d24f28176928a4a92eaa20342c52edbb0938f4dd\n      Stored in directory: /root/.cache/pip/wheels/89/89/34/524839952d5a58a7be9789e580bfc1ca883bf6579152444568\n      Building wheel for python-constraint (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for python-constraint: filename=python_constraint-1.4.0-py2.py3-none-any.whl size=24079 sha256=35b086ebd96ea7a2891fb5e52f5485c24ae251f78fec828a2895254c5038edb3\n      Stored in directory: /root/.cache/pip/wheels/34/31/15/7b070b25d0a549d20ce2e9fe6d727471c2c61ef904720fd40c\n      Building wheel for yfinance (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for yfinance: filename=yfinance-0.1.55-py2.py3-none-any.whl size=22616 sha256=5f1fe2d1709cbbfaf38cdf03a09dc41d437133e2554f1b41c2392074f45c9943\n      Stored in directory: /root/.cache/pip/wheels/04/98/cc/2702a4242d60bdc14f48b4557c427ded1fe92aedf257d4565c\n      Building wheel for dlx (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for dlx: filename=dlx-1.0.4-cp37-none-any.whl size=5712 sha256=1154e839748f8d28680d5d7c922c454909954f6b3a334a5b7633ba059156b7e1\n      Stored in directory: /root/.cache/pip/wheels/bb/ba/15/fdd0deb104df3254912998150ba9245668db06b00af5912d1a\n      Building wheel for docplex (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for docplex: filename=docplex-2.20.204-cp37-none-any.whl size=675362 sha256=9494f9dd2dec35c5b52e88a18051305c0b7307ab107312f9b0d514a546535200\n      Stored in directory: /root/.cache/pip/wheels/ae/2c/e2/a099ebb6fda8adeba9c5fc2e25659d195ad2f5c6cc5fb75fd4\n    Successfully built qiskit python-constraint yfinance dlx docplex\n    \u001b[31mERROR: qiskit-aqua 0.9.1 has requirement retworkx<=0.8.0,>=0.7.0, but you'll have retworkx 0.9.0 which is incompatible.\u001b[0m\n    Installing collected packages: fastjsonschema, ply, python-constraint, retworkx, qiskit-terra, pybind11, qiskit-aer, websockets, ntlm-auth, cryptography, requests-ntlm, qiskit-ibmq-provider, qiskit-ignis, lxml, yfinance, inflection, quandl, dlx, docplex, qiskit-aqua, qiskit\n      Found existing installation: lxml 4.2.6\n        Uninstalling lxml-4.2.6:\n          Successfully uninstalled lxml-4.2.6\n    Successfully installed cryptography-3.4.7 dlx-1.0.4 docplex-2.20.204 fastjsonschema-2.15.1 inflection-0.5.1 lxml-4.6.3 ntlm-auth-1.5.0 ply-3.11 pybind11-2.6.2 python-constraint-1.4.0 qiskit-0.26.2 qiskit-aer-0.8.2 qiskit-aqua-0.9.1 qiskit-ibmq-provider-0.13.1 qiskit-ignis-0.6.0 qiskit-terra-0.17.4 quandl-3.6.0 requests-ntlm-1.1.0 retworkx-0.9.0 websockets-9.1 yfinance-0.1.55\n\n\n\n```python\n!pip install qiskit-nature\n\n```\n\n    Collecting qiskit-nature\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/4c/54/2562684ccf73215d3d85b65174ea06ee3f1b184422cfd81241a8a13491cd/qiskit_nature-0.1.3-py3-none-any.whl (1.5MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.5MB 6.5MB/s \n    \u001b[?25hRequirement already satisfied: h5py in /usr/local/lib/python3.7/dist-packages (from qiskit-nature) (3.1.0)\n    Requirement already satisfied: scipy>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-nature) (1.4.1)\n    Requirement already satisfied: scikit-learn>=0.20.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-nature) (0.22.2.post1)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-nature) (56.1.0)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-nature) (5.4.8)\n    Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from qiskit-nature) (1.19.5)\n    Requirement already satisfied: qiskit-terra>=0.17.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-nature) (0.17.4)\n    Requirement already satisfied: cached-property; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from h5py->qiskit-nature) (1.5.2)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.20.0->qiskit-nature) (1.0.1)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-nature) (2.8.1)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-nature) (0.3.3)\n    Requirement already satisfied: retworkx>=0.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-nature) (0.9.0)\n    Requirement already satisfied: ply>=3.10 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-nature) (3.11)\n    Requirement already satisfied: python-constraint>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-nature) (1.4.0)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-nature) (1.7.1)\n    Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-nature) (2.6.0)\n    Requirement already satisfied: fastjsonschema>=2.10 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra>=0.17.0->qiskit-nature) (2.15.1)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.8.0->qiskit-terra>=0.17.0->qiskit-nature) (1.15.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra>=0.17.0->qiskit-nature) (1.2.1)\n    Installing collected packages: qiskit-nature\n    Successfully installed qiskit-nature-0.1.3\n\n\n\n```python\n!pip install pyscf\n```\n\n    Collecting pyscf\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/ef/d6/af4ce5035977cb011e4dbe9979bf254129a36d48cb569b86e57b5a72c5b1/pyscf-1.7.6.post1-cp37-cp37m-manylinux1_x86_64.whl (29.7MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 29.7MB 145kB/s \n    \u001b[?25hRequirement already satisfied: numpy!=1.16,!=1.17,>1.8 in /usr/local/lib/python3.7/dist-packages (from pyscf) (1.19.5)\n    Requirement already satisfied: scipy!=1.5.0,!=1.5.1 in /usr/local/lib/python3.7/dist-packages (from pyscf) (1.4.1)\n    Requirement already satisfied: h5py>2.2 in /usr/local/lib/python3.7/dist-packages (from pyscf) (3.1.0)\n    Requirement already satisfied: cached-property; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from h5py>2.2->pyscf) (1.5.2)\n    Installing collected packages: pyscf\n    Successfully installed pyscf-1.7.6.post1\n\n\n\n```python\nfrom qiskit_nature.drivers import PySCFDriver #Importing pyscf module to enable simulation of chemical molecules\n\nmolecule = 'Li 0.0 0.0 0.0; H 0.0 0.0 1.5474'#These represent the coordinates of the atoms in the molcule\ndriver = PySCFDriver(atom=molecule)\nqmolecule = driver.run()\n```\n\n\n```python\nn_mo = qmolecule.num_molecular_orbitals\nprint(n_mo)#This prints the total number of molecular orbitals which is 6 here\n\nfrom qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem #To produce list of fermionic operators\nfrom qiskit_nature.transformers import FreezeCoreTransformer #Freezing the core to reduce the number of qubits\n\n#In order to find out which orbitals to freeze, I checked the corresponding exact ground energy value by freezing all the orbitals in the range (0,5) and chose the ones which were closer to the threshold value\ntr = FreezeCoreTransformer(True,[3,4])#Freezing orbitals 3 and 4\nproblem = ElectronicStructureProblem(driver,[tr])\n\nsecond_q_ops = problem.second_q_ops()#Generating the second-quantized operators\n\n\nmain_op = second_q_ops[0]#Hamiltonian\n\n\n```\n\n    6\n\n\n\n```python\nfrom qiskit_nature.mappers.second_quantization import ParityMapper, BravyiKitaevMapper, JordanWignerMapper\nfrom qiskit_nature.converters.second_quantization.qubit_converter import QubitConverter\n\n#Setting up the mapper and qubit converter\n#Defining mapping for representing molecular orbitals using qubits\nmapper = ParityMapper()\n\n\nconverter = QubitConverter(mapper=mapper, two_qubit_reduction=True)#,z2symmetry_reduction=[-1,1])#Uncomment to apply z2symmetry\n# The fermionic operators are mapped to qubit operators\nnum_particles = (problem.molecule_data_transformed.num_alpha,\n             problem.molecule_data_transformed.num_beta)\nqubit_op = converter.convert(main_op, num_particles=num_particles)\nprint(qubit_op.z2_symmetries)#This prints the symmetries present in the molecule . I didn't apply z2symmetry because I already reduce the number of qubits to 4\n```\n\n    Z2 symmetries:\n    Symmetries:\n    IIIZII\n    ZIIIII\n    Single-Qubit Pauli X:\n    IIIXII\n    XIIIII\n    Cliffords:\n    0.7071067811865475 * IIIZII\n    + 0.7071067811865475 * IIIXII\n    0.7071067811865475 * ZIIIII\n    + 0.7071067811865475 * XIIIII\n    Qubit index:\n    [2, 5]\n    Tapering values:\n    [-1, 1]\n\n\n\n```python\nfrom qiskit_nature.circuit.library import HartreeFock\n#To implement hartreefrock state as the initial state\nnum_particles = (problem.molecule_data_transformed.num_alpha,\n             problem.molecule_data_transformed.num_beta)\nnum_spin_orbitals = 2 * problem.molecule_data_transformed.num_molecular_orbitals\ninit_state = HartreeFock(num_spin_orbitals, num_particles, converter)\nprint(init_state)\n```\n\n         \u250c\u2500\u2500\u2500\u2510\n    q_0: \u2524 X \u251c\n         \u251c\u2500\u2500\u2500\u2524\n    q_1: \u2524 X \u251c\n         \u2514\u2500\u2500\u2500\u2518\n    q_2: \u2500\u2500\u2500\u2500\u2500\n              \n    q_3: \u2500\u2500\u2500\u2500\u2500\n              \n\n\n\n```python\nfrom qiskit.circuit.library import TwoLocal\n#Choosing a quantum circuit to approximate ground state\n\n#Parameters for q-UCC antatze\nnum_particles = (problem.molecule_data_transformed.num_alpha,\n            problem.molecule_data_transformed.num_beta)\nnum_spin_orbitals = 2 * problem.molecule_data_transformed.num_molecular_orbitals\n\n\n#Using TwoLocal ansatz with the following parameters because it uses least number of CNOTs found out by Hit and Trial\n#Single qubit rotations that are placed on all qubits with independent parameters\nrotation_blocks = ['ry', 'rz']\n#Entangling gates\nentanglement_blocks = 'cx'\n#How the qubits are entangled \nentanglement = 'linear'\n#Repetitions of rotation_blocks + entanglement_blocks with independent parameters\nrepetitions = 1\n# Not skipping the final rotation_blocks layer\nskip_final_rotation_layer = False\nansatz = TwoLocal(qubit_op.num_qubits, rotation_blocks, entanglement_blocks, reps=repetitions, \n                      entanglement=entanglement, skip_final_rotation_layer=skip_final_rotation_layer)\n\nprint(ansatz)\n```\n\n         \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510             \u00bb\n    q_0: \u2524 RY(\u03b8[0]) \u251c\u2524 RZ(\u03b8[4]) \u251c\u2500\u2500\u25a0\u2500\u2500\u2524 RY(\u03b8[8]) \u251c\u2524 RZ(\u03b8[12]) \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n         \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u250c\u2500\u2534\u2500\u2510\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u00bb\n    q_1: \u2524 RY(\u03b8[1]) \u251c\u2524 RZ(\u03b8[5]) \u251c\u2524 X \u251c\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 RY(\u03b8[9]) \u251c\u2524 RZ(\u03b8[13]) \u251c\u00bb\n         \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u2514\u2500\u2500\u2500\u2518   \u250c\u2500\u2534\u2500\u2510     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u00bb\n    q_2: \u2524 RY(\u03b8[2]) \u251c\u2524 RZ(\u03b8[6]) \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25a0\u2500\u2500\u2500\u2500\u2500\u2500\u2524 RY(\u03b8[10]) \u251c\u00bb\n         \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524        \u2514\u2500\u2500\u2500\u2518        \u250c\u2500\u2534\u2500\u2510    \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\u00bb\n    q_3: \u2524 RY(\u03b8[3]) \u251c\u2524 RZ(\u03b8[7]) \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 X \u251c\u2500\u2500\u2500\u2500\u2524 RY(\u03b8[11]) \u251c\u00bb\n         \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518                     \u2514\u2500\u2500\u2500\u2518    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u00bb\n    \u00ab                  \n    \u00abq_0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                  \n    \u00abq_1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    \u00abq_2: \u2524 RZ(\u03b8[14]) \u251c\n    \u00ab     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n    \u00abq_3: \u2524 RZ(\u03b8[15]) \u251c\n    \u00ab     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\n\n\n```python\nfrom qiskit import Aer #To specify the simulator for the algorithm to run on\nbackend = Aer.get_backend('statevector_simulator')\n```\n\n\n```python\nfrom qiskit.algorithms.optimizers import SLSQP\noptimizer = SLSQP(maxiter=2000)#This optimiser gave the correct energy value for the chosen ansatz\n```\n\n\n```python\nfrom qiskit_nature.algorithms.ground_state_solvers.minimum_eigensolver_factories import NumPyMinimumEigensolverFactory\nfrom qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver\nimport numpy as np \n#Trying to solve the problem using exact diagonalization of the Hamiltonian\n\ndef exact_diagonalizer(problem, converter):\n    solver = NumPyMinimumEigensolverFactory()\n    calc = GroundStateEigensolver(converter, solver)\n    result = calc.solve(problem)\n    return result\n\nresult_exact = exact_diagonalizer(problem, converter)\nexact_energy = np.real(result_exact.eigenenergies[0])\nprint(\"Exact electronic energy\", exact_energy)\nprint(result_exact)\n\n# The targeted electronic energy for LiH is -1.086 Ha\n\n```\n\n    Exact electronic energy -1.0887060157347406\n    === GROUND STATE ENERGY ===\n     \n    * Electronic ground state energy (Hartree): -8.907396311316\n      - computed part:      -1.088706015735\n      - FreezeCoreTransformer extracted energy part: -7.818690295581\n    ~ Nuclear repulsion energy (Hartree): 1.025934879643\n    > Total ground state energy (Hartree): -7.881461431673\n     \n    === MEASURED OBSERVABLES ===\n     \n      0:  # Particles: 2.000 S: 0.000 S^2: 0.000 M: 0.000\n     \n    === DIPOLE MOMENTS ===\n     \n    ~ Nuclear dipole moment (a.u.): [0.0  0.0  2.92416221]\n     \n      0: \n      * Electronic dipole moment (a.u.): [0.0  0.0  4.76300889]\n        - computed part:      [0.0  0.0  4.76695575]\n        - FreezeCoreTransformer extracted energy part: [0.0  0.0  -0.00394686]\n      > Dipole moment (a.u.): [0.0  0.0  -1.83884668]  Total: 1.83884668\n                     (debye): [0.0  0.0  -4.67388163]  Total: 4.67388163\n     \n\n\n\n```python\nfrom qiskit.algorithms import VQE\nfrom IPython.display import display, clear_output\n#Importing VQE to run the algorithim\n\ndef callback(eval_count, parameters, mean, std):  \n    display(\"Evaluation: {}, Energy: {}, Std: {}\".format(eval_count, mean, std))\n    clear_output(wait=True)\n    counts.append(eval_count)\n    values.append(mean)\n    params.append(parameters)\n    deviation.append(std)\n\ncounts = []\nvalues = []\nparams = []\ndeviation = []\n\n#Default fixed small displacement\ntry:\n    initial_point = [0.01] * len(ansatz.ordered_parameters)\nexcept:\n    initial_point = [0.01] * ansatz.num_parameters\n\nalgorithm = VQE(ansatz,\n                optimizer=optimizer,\n                quantum_instance=backend,\n                callback=callback,\n                initial_point=initial_point)\n\nresult = algorithm.compute_minimum_eigenvalue(qubit_op)\n\nprint(result)\n```\n\n    {   'aux_operator_eigenvalues': None,\n        'cost_function_evals': 851,\n        'eigenstate': array([-1.38503080e-03-3.73975129e-05j,  4.83798144e-03+6.36745268e-05j,\n           -2.66978013e-02-3.06676159e-04j,  9.91386592e-01+1.39272516e-03j,\n            5.38283495e-02+5.40890327e-04j,  3.28152532e-04+9.93615636e-06j,\n           -9.07220622e-04+4.32502418e-06j,  2.39114676e-02-3.84502735e-04j,\n            2.72891302e-03+4.22182794e-05j,  9.36230793e-06+1.71620611e-06j,\n           -5.91311396e-06-6.28705625e-06j, -2.73155829e-04+2.34338973e-04j,\n           -1.13726193e-01+2.30850218e-04j, -4.47959858e-04-1.66081270e-05j,\n            5.62790023e-04-7.93456918e-06j, -2.66622417e-04+1.18701780e-05j]),\n        'eigenvalue': -1.0863663677292887,\n        'optimal_parameters': {   ParameterVectorElement(\u03b8[4]): -0.004768579123950326,\n                                  ParameterVectorElement(\u03b8[12]): -0.010069423154352004,\n                                  ParameterVectorElement(\u03b8[5]): -0.0037985015266241207,\n                                  ParameterVectorElement(\u03b8[6]): -0.005513500988743045,\n                                  ParameterVectorElement(\u03b8[7]): -0.0010895487469465151,\n                                  ParameterVectorElement(\u03b8[8]): 0.05313368644547072,\n                                  ParameterVectorElement(\u03b8[9]): -0.00977072471667363,\n                                  ParameterVectorElement(\u03b8[10]): 0.047986900543765254,\n                                  ParameterVectorElement(\u03b8[13]): -0.011810269141820076,\n                                  ParameterVectorElement(\u03b8[14]): -0.017507464711468492,\n                                  ParameterVectorElement(\u03b8[15]): -0.012680710973539674,\n                                  ParameterVectorElement(\u03b8[1]): 0.005744855621419048,\n                                  ParameterVectorElement(\u03b8[11]): 0.44182324189775946,\n                                  ParameterVectorElement(\u03b8[0]): -2.8892613849526074,\n                                  ParameterVectorElement(\u03b8[3]): -0.44239241452227135,\n                                  ParameterVectorElement(\u03b8[2]): -3.1410072751603506},\n        'optimal_point': array([-2.88926138e+00,  4.79869005e-02,  4.41823242e-01, -1.00694232e-02,\n           -1.18102691e-02, -1.75074647e-02, -1.26807110e-02,  5.74485562e-03,\n           -3.14100728e+00, -4.42392415e-01, -4.76857912e-03, -3.79850153e-03,\n           -5.51350099e-03, -1.08954875e-03,  5.31336864e-02, -9.77072472e-03]),\n        'optimal_value': -1.0863663677292887,\n        'optimizer_evals': 851,\n        'optimizer_time': 9.800698041915894}\n\n\n\n```python\n#Storing results in a dictionary\nfrom qiskit.transpiler import PassManager\nfrom qiskit.transpiler.passes import Unroller\n\n#Transpiling circuit into CNOTs and U gates\npass_ = Unroller(['u', 'cx'])\npm = PassManager(pass_)\nansatz_tp = pm.run(ansatz)\ncnots = ansatz_tp.count_ops()['cx']\nscore = cnots\n\naccuracy_threshold = 4.0 #in mHa\nenergy = result.optimal_value\n\nresult_dict = {\n        'optimizer': optimizer.__class__.__name__,\n        'mapping': converter.mapper.__class__.__name__,\n        'ansatz': ansatz.__class__.__name__,\n        'rotation blocks': rotation_blocks,\n        'entanglement_blocks': entanglement_blocks,\n        'entanglement': entanglement,\n        'repetitions': repetitions,\n        'skip_final_rotation_layer': skip_final_rotation_layer,\n        'energy (Ha)': energy,\n        'error (mHa)': (energy-exact_energy)*1000,\n        'pass': (energy-exact_energy)*1000 <= accuracy_threshold,\n        '# of parameters': len(result.optimal_point),\n        'final parameters': result.optimal_point,\n        '# of evaluations': result.optimizer_evals,\n        'optimizer time': result.optimizer_time,\n        '# of qubits': int(qubit_op.num_qubits),\n        '# of CNOTs': cnots,\n        'score': score}\n\n#Plotting the results\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(1, 1)\nax.set_xlabel('Iterations')\nax.set_ylabel('Energy')\nax.grid()\nfig.text(0.7, 0.75, f'Energy: {result.optimal_value:.3f}\\nScore: {score:.0f}')\nplt.title(f\"{result_dict['optimizer']}-{result_dict['mapping']}\\n{result_dict['ansatz']}\")\nax.plot(counts, values)\nax.axhline(exact_energy, linestyle='--')\nfig_title = f\"\\\n{result_dict['optimizer']}-\\\n{result_dict['mapping']}-\\\n{result_dict['ansatz']}-\\\nEnergy({result_dict['energy (Ha)']:.3f})-\\\nScore({result_dict['score']:.0f})\\\n.png\"\nfig.savefig(fig_title, dpi=300)\n\n#Displaying and saving the data\nimport pandas as pd\nimport os.path\nfilename = 'results_h2.csv'\nif os.path.isfile(filename):\n    result_df = pd.read_csv(filename)\n    result_df = result_df.append([result_dict])\nelse:\n    result_df = pd.DataFrame.from_dict([result_dict])\nresult_df.to_csv(filename)\nresult_df[['optimizer','ansatz', '# of qubits', '# of parameters','rotation blocks', 'entanglement_blocks',\n    'entanglement', 'repetitions', 'error (mHa)', 'pass', 'score']]\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "9bf6493fe30e2720b81e39f078979bf5e9bf5932", "size": 57092, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "solutions by participants/ex5/ex5-ShilpaMahato-3cnot-2.3588mHa-16params.ipynb", "max_stars_repo_name": "fazliberkordek/ibm-quantum-challenge-2021", "max_stars_repo_head_hexsha": "2206a364e354965b749dcda7c5d62631f571d718", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 136, "max_stars_repo_stars_event_min_datetime": "2021-05-20T14:07:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T17:19:31.000Z", "max_issues_repo_path": "solutions by participants/ex5/ex5-ShilpaMahato-3cnot-2.3588mHa-16params.ipynb", "max_issues_repo_name": "fazliberkordek/ibm-quantum-challenge-2021", "max_issues_repo_head_hexsha": "2206a364e354965b749dcda7c5d62631f571d718", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 106, "max_issues_repo_issues_event_min_datetime": "2021-05-21T15:41:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-08T08:29:25.000Z", "max_forks_repo_path": "solutions by participants/ex5/ex5-ShilpaMahato-3cnot-2.3588mHa-16params.ipynb", "max_forks_repo_name": "fazliberkordek/ibm-quantum-challenge-2021", "max_forks_repo_head_hexsha": "2206a364e354965b749dcda7c5d62631f571d718", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 190, "max_forks_repo_forks_event_min_datetime": "2021-05-20T14:02:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T16:31:20.000Z", "avg_line_length": 73.1011523688, "max_line_length": 18304, "alphanum_fraction": 0.7196279689, "converted": true, "num_tokens": 10026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22815649691270323, "lm_q2_score": 0.0994702238929934, "lm_q1q2_score": 0.022694777830547647}}
{"text": "## Initial setup\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```python\nimport tensorflow as tf\nprint(tf.__version__)\nimport torch\nprint(torch.__version__)\nimport matplotlib\nprint(matplotlib.__version__)\n```\n\n    2.8.0\n    1.10.0+cu111\n    3.2.2\n\n\n\n```python\n!nvidia-smi\n```\n\n    Fri Jan 21 19:41:32 2022       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 495.46       Driver Version: 460.32.03    CUDA Version: 11.2     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   34C    P8     9W /  70W |      0MiB / 15109MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    |  No running processes found                                                 |\n    +-----------------------------------------------------------------------------+\n\n\n\n```python\n# Other imports\n! pip install tensorflow_addons\n! pip install tensorflow_io\n\nimport os\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import *\nfrom keras.callbacks import Callback, EarlyStopping, ModelCheckpoint\nfrom tensorflow.keras.applications.resnet50 import preprocess_input\nfrom tensorflow.keras.preprocessing.image import load_img\n\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfrom matplotlib.offsetbox import OffsetImage, AnnotationBbox\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter, AutoMinorLocator\nfrom imutils import paths\nfrom tqdm import tqdm\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nimport tensorflow_datasets as tfds\nimport tensorflow_io as tfio\nimport tensorflow_hub as hub\nimport numpy as np\nimport cv2\nimport pandas as pd\nimport seaborn as sns\nfrom scipy.stats import mannwhitneyu\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.cluster import KMeans\nimport sklearn.manifold\nfrom sklearn.metrics.pairwise import cosine_similarity as cos\nfrom sympy.utilities.iterables import multiset_permutations\nfrom sklearn.metrics import accuracy_score, f1_score,precision_score, recall_score, roc_auc_score, confusion_matrix\nfrom sklearn.model_selection import *\nfrom sklearn.preprocessing import StandardScaler\nfrom IPython.display import Image, display\n\n\nimport zipfile\nimport concurrent.futures\n\n# Random seed fix\nrandom_seed = 42\ntf.random.set_seed(random_seed)\nnp.random.seed(random_seed)\n```\n\n    Collecting tensorflow_addons\n      Downloading tensorflow_addons-0.16.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.1 MB 6.4 MB/s \n    \u001b[?25hRequirement already satisfied: typeguard>=2.7 in /usr/local/lib/python3.7/dist-packages (from tensorflow_addons) (2.7.1)\n    Installing collected packages: tensorflow-addons\n    Successfully installed tensorflow-addons-0.16.1\n    Collecting tensorflow_io\n      Downloading tensorflow_io-0.24.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (23.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 23.4 MB 1.8 MB/s \n    \u001b[?25hRequirement already satisfied: tensorflow-io-gcs-filesystem==0.24.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow_io) (0.24.0)\n    Installing collected packages: tensorflow-io\n    Successfully installed tensorflow-io-0.24.0\n\n\n## Dataset gathering and preparation\n\n\n```python\n%cd /content/drive/MyDrive/nanowire-morphology-classification-project\n```\n\n\n```python\ntraining_batch_size = 4\n\nBATCH_SIZE = training_batch_size\n\nimageSize = 224\n\ncategory_names = ['bundle', 'dispersed', 'network', 'singular']\ncolor_method = ['C0', 'C1', 'C2', 'C3', 'C4']\ncolor = ['black', 'magenta', 'cyan', 'yellow']\nmarker = ['o', 's', '<', '>', '^']\nseaborn_palette = sns.color_palette(\"colorblind\")\n```\n\n\n```python\nnp.random.seed(random_seed)\npeptide_morph_train_path = \"/content/drive/MyDrive/TEM image datasets/2022-nanowire-morphology\"\npeptide_morph_images_train = list(paths.list_files(basePath=peptide_morph_train_path, validExts='jpg'))\npeptide_morph_images_train = np.random.choice(np.array(peptide_morph_images_train), len(peptide_morph_images_train), replace=False)\nprint(len(peptide_morph_images_train))\n```\n\n    400\n\n\n\n```python\ntrain_labels = []\nfor i in range(peptide_morph_images_train.shape[0]):\n  train_label = peptide_morph_images_train[i].split(\"/\")[-2]\n  train_labels.append(train_label)\nle = LabelEncoder()\npeptide_morph_train_enc = le.fit_transform(train_labels)\n```\n\n\n```python\n# Image preprocessing utils\n@tf.function\ndef parse_images(image_path):\n    image_string = tf.io.read_file(image_path)\n    image = tf.image.decode_jpeg(image_string, channels=3)\n    # image = tfio.experimental.image.decode_tiff(image_string)[:, :, :3]   # in the doc, it transforms tiff to 4 channels, with additional channel of opacity which is not needed.\n    image = tf.image.convert_image_dtype(image, tf.float32)\n    image = tf.image.resize(image, size=[imageSize, imageSize])\n\n    return image\n```\n\n\n```python\ntrain_ds = tf.data.Dataset.from_tensor_slices(peptide_morph_images_train)\ntrain_ds = (\n    train_ds\n    .map(parse_images, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n    # .shuffle(200)\n    .batch(training_batch_size\n          #  , drop_remainder=True\n           )\n    .prefetch(tf.data.experimental.AUTOTUNE)\n)\n\ndatagen = tf. keras.preprocessing.image.ImageDataGenerator(preprocessing_function=tf.keras.applications.resnet50.preprocess_input)\n```\n\n## Initiate self-supervised models\n\n\n```python\nResnet50_transfer = tf.keras.applications.ResNet50(\n    include_top=False,\n    weights=\"imagenet\",\n    input_tensor=None,\n    input_shape=(imageSize, imageSize, 3), \n    pooling=None,\n)\n\nResnet50_transfer.trainable = False\n```\n\n    Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/resnet/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5\n    94773248/94765736 [==============================] - 1s 0us/step\n    94781440/94765736 [==============================] - 1s 0us/step\n\n\n\n```python\n# Resnet as backbone\ndef get_resnet_self_supervise_model(hidden_1, hidden_2, hidden_3):\n    base_model = Resnet50_transfer\n    base_model.trainable = True\n    inputs = Input((imageSize, imageSize, 3))\n    h = base_model(inputs, training=True)\n    h = GlobalAveragePooling2D()(h)\n\n    projection_1 = Dense(hidden_1)(h)                                        \n    projection_1 = Activation(\"relu\")(projection_1)\n    projection_1 = BatchNormalization(epsilon=0.001)(projection_1)\n    projection_2 = Dense(hidden_2)(projection_1)\n    projection_2 = Activation(\"relu\")(projection_2)\n    projection_2 = BatchNormalization(epsilon=0.001)(projection_2)\n    projection_3 = Dense(hidden_3)(projection_2)\n    projection_3 = BatchNormalization(epsilon=0.001)(projection_3)\n\n    resnet_model = Model(inputs, projection_3)\n    \n    return resnet_model\n```\n\n## Initiate downstream classification model\n\n\n```python\ndef get_linear_model(features):                                                                                  \n    linear_model = Sequential([                                                                                  \n\t\t\t                              Input(shape=(features,)),\n\t\t                                Dense(4, activation=\"softmax\")])\n    return linear_model\n```\n\n## hyperparameter tuning with cross-validation\n\n\n```python\n# Random seed fix\nrandom_seed_list = np.array([42, 43, 44, 45, 46])\n\n## hyperparameters ss stands for self-supervise\n\n# instead of having for loop for all the hyperparameter choices, we manually \n# change the parameters and ran cross-validation at each hyperparameter set.\n# Considering that Google Colab have time-out protocols that limit long-time usage\n# of GPU, dividing our hyperparameter sweep into smaller segments resulted in a more\n# flexible and productive workflow.\n\nss_method = 'barlow'\nss_backbone = 'resnet'\nss_batch_size = np.array([16])\nphl_1 = np.array([128])\nphl_2 = np.array([64])\nphl_3 = np.array([1024])\n\nearlystop_criterion = EarlyStopping(monitor='val_accuracy', patience=20, verbose=0, mode='auto', restore_best_weights=True)\nadam = tf.keras.optimizers.Adam(learning_rate=0.001)\nmetrics = ['accuracy']\ncv = StratifiedKFold(n_splits=4, shuffle=True, random_state=42)\n```\n\n\n```python\nlinear_scores = np.zeros((len(random_seed_list), len(random_seed_list), 4, 4))\n\nfor i in range(len(random_seed_list)):\n  resnet_model = get_resnet_self_supervise_model(phl_1, phl_2, phl_3)\n  resnet_model.load_weights('%s_%s_batch%i_project%i_%i_%i_res384_seed%i.h5' \n                          % (ss_method, ss_backbone, ss_batch_size, phl_1, phl_2, phl_3, random_seed_list[i]))\n  resnet_model.layers[1].trainable = False\n\n  feature_extraction_model = Model(resnet_model.input, resnet_model.layers[-9].output)\n\n  # Extract train and test features\n  features = feature_extraction_model.predict(train_ds)\n\n  for j in range(len(random_seed_list)):\n    TRAIN_feature, test_feature, TRAIN_label, test_label = train_test_split(features, peptide_morph_train_enc, test_size=0.2, shuffle=True, stratify=peptide_morph_train_enc, random_state=random_seed_list[j])\n    k = 0\n    for train_ix, test_ix in cv.split(TRAIN_feature, TRAIN_label):\n      k += 1\n      train_feature, val_feature = TRAIN_feature[train_ix, :], TRAIN_feature[test_ix, :]\n      train_label, val_label = TRAIN_label[train_ix], TRAIN_label[test_ix]\n      checkpoint_model_linear = ModelCheckpoint('best_classify_models_hyperparameter/%s_%s_batch%i_project%i_%i_%i_res384_seed%i_seed%i_fold%i_linear.h5' \n                                  % (ss_method, ss_backbone, ss_batch_size, phl_1, phl_2, phl_3, random_seed_list[i], random_seed_list[j], k),\n                                  monitor='val_accuracy', mode='auto', verbose=0, save_best_only=True, save_weights_only=True)\n      # train linear classifier model\n      linear_model = get_linear_model(train_feature.shape[1])\n      linear_model.compile(loss=\"sparse_categorical_crossentropy\", metrics=metrics, optimizer=adam)\n      linear_history = linear_model.fit(train_feature, train_label, validation_data=(val_feature, val_label), \n                                            batch_size=training_batch_size, epochs=300, workers=8, use_multiprocessing=True, \n                                            verbose=1, callbacks=[earlystop_criterion, checkpoint_model_linear])\n      # log best classification model performance\n      linear_model = get_linear_model(train_feature.shape[1])\n      linear_model.load_weights('best_classify_models_hyperparameter/%s_%s_batch%i_project%i_%i_%i_res384_seed%i_seed%i_fold%i_linear.h5' \n                                  % (ss_method, ss_backbone, ss_batch_size, phl_1, phl_2, phl_3, random_seed_list[i], random_seed_list[j], k))\n      y_pred_linear = np.argmax(linear_model.predict(val_feature), axis=-1)\n      linear_scores[i, j, k - 1] = np.array([accuracy_score(y_pred_linear, val_label), \n                                             precision_score(y_pred_linear, val_label, average='weighted'), \n                                             recall_score(y_pred_linear, val_label, average='weighted'),\n                                             f1_score(y_pred_linear, val_label, average='weighted')])\n      \nnp.savez_compressed('classify_scores_hyperparameter/%s_%s_batch%i_project%i_%i_%i.npz' \n                            % (ss_method, ss_backbone, ss_batchsize, phl_1, phl_2, phl_3),\n                    scores=linear_scores)\n\nprint('average classification accuracy precision recall f1_score')\nprint(np.average(linear_scores, axis=(0,1,2)))\nprint('standard deviation')\nprint(np.std(linear_scores, axis=(0,1,2)))\n```\n\n    \u001b[1;30;43mStreaming output truncated to the last 5000 lines.\u001b[0m\n    Epoch 27/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0207 - accuracy: 0.9917 - val_loss: 0.0331 - val_accuracy: 0.9750\n    Epoch 28/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0115 - accuracy: 1.0000 - val_loss: 0.0380 - val_accuracy: 0.9875\n    Epoch 29/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0117 - accuracy: 1.0000 - val_loss: 0.0291 - val_accuracy: 0.9875\n    Epoch 30/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0166 - accuracy: 0.9917 - val_loss: 0.0428 - val_accuracy: 0.9750\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0230 - accuracy: 0.9958 - val_loss: 0.1493 - val_accuracy: 0.9125\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0363 - accuracy: 0.9875 - val_loss: 0.0285 - val_accuracy: 0.9875\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0092 - accuracy: 1.0000 - val_loss: 0.0269 - val_accuracy: 0.9875\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.5506 - accuracy: 0.7000 - val_loss: 0.7950 - val_accuracy: 0.8875\n    Epoch 2/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.4288 - accuracy: 0.9083 - val_loss: 0.3398 - val_accuracy: 0.9000\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1853 - accuracy: 0.9292 - val_loss: 0.2431 - val_accuracy: 0.9125\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1084 - accuracy: 0.9625 - val_loss: 0.1688 - val_accuracy: 0.9125\n    Epoch 5/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0926 - accuracy: 0.9625 - val_loss: 0.2290 - val_accuracy: 0.9250\n    Epoch 6/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0901 - accuracy: 0.9625 - val_loss: 0.1880 - val_accuracy: 0.9250\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0485 - accuracy: 0.9917 - val_loss: 0.1761 - val_accuracy: 0.9375\n    Epoch 8/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0646 - accuracy: 0.9708 - val_loss: 0.1603 - val_accuracy: 0.9250\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0425 - accuracy: 0.9875 - val_loss: 0.1563 - val_accuracy: 0.9375\n    Epoch 10/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0546 - accuracy: 0.9833 - val_loss: 0.1770 - val_accuracy: 0.9625\n    Epoch 11/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0702 - accuracy: 0.9750 - val_loss: 0.1593 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0271 - accuracy: 0.9958 - val_loss: 0.1517 - val_accuracy: 0.9625\n    Epoch 13/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0200 - accuracy: 0.9958 - val_loss: 0.1236 - val_accuracy: 0.9250\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0196 - accuracy: 1.0000 - val_loss: 0.1436 - val_accuracy: 0.9500\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0168 - accuracy: 1.0000 - val_loss: 0.1280 - val_accuracy: 0.9500\n    Epoch 16/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0163 - accuracy: 0.9958 - val_loss: 0.1394 - val_accuracy: 0.9625\n    Epoch 17/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0262 - accuracy: 0.9958 - val_loss: 0.1586 - val_accuracy: 0.9625\n    Epoch 18/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0158 - accuracy: 1.0000 - val_loss: 0.1213 - val_accuracy: 0.9625\n    Epoch 19/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0172 - accuracy: 1.0000 - val_loss: 0.1305 - val_accuracy: 0.9500\n    Epoch 20/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0170 - accuracy: 0.9958 - val_loss: 0.1490 - val_accuracy: 0.9750\n    Epoch 21/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0145 - accuracy: 1.0000 - val_loss: 0.1341 - val_accuracy: 0.9500\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0145 - accuracy: 1.0000 - val_loss: 0.1505 - val_accuracy: 0.9750\n    Epoch 23/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0163 - accuracy: 1.0000 - val_loss: 0.1517 - val_accuracy: 0.9625\n    Epoch 24/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0173 - accuracy: 1.0000 - val_loss: 0.1289 - val_accuracy: 0.9500\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0173 - accuracy: 0.9958 - val_loss: 0.1405 - val_accuracy: 0.9500\n    Epoch 26/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0119 - accuracy: 1.0000 - val_loss: 0.1525 - val_accuracy: 0.9625\n    Epoch 27/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0138 - accuracy: 1.0000 - val_loss: 0.1243 - val_accuracy: 0.9500\n    Epoch 28/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0114 - accuracy: 1.0000 - val_loss: 0.1365 - val_accuracy: 0.9750\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0109 - accuracy: 1.0000 - val_loss: 0.1343 - val_accuracy: 0.9750\n    Epoch 30/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0078 - accuracy: 1.0000 - val_loss: 0.1365 - val_accuracy: 0.9750\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0097 - accuracy: 1.0000 - val_loss: 0.1341 - val_accuracy: 0.9750\n    Epoch 32/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0078 - accuracy: 1.0000 - val_loss: 0.1274 - val_accuracy: 0.9750\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0089 - accuracy: 1.0000 - val_loss: 0.1363 - val_accuracy: 0.9750\n    Epoch 34/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0072 - accuracy: 1.0000 - val_loss: 0.1197 - val_accuracy: 0.9750\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0065 - accuracy: 1.0000 - val_loss: 0.1201 - val_accuracy: 0.9750\n    Epoch 36/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0059 - accuracy: 1.0000 - val_loss: 0.1401 - val_accuracy: 0.9625\n    Epoch 37/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0064 - accuracy: 1.0000 - val_loss: 0.1233 - val_accuracy: 0.9500\n    Epoch 38/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0059 - accuracy: 1.0000 - val_loss: 0.1412 - val_accuracy: 0.9750\n    Epoch 39/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0060 - accuracy: 1.0000 - val_loss: 0.1242 - val_accuracy: 0.9625\n    Epoch 40/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0070 - accuracy: 1.0000 - val_loss: 0.1226 - val_accuracy: 0.9750\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.6031 - accuracy: 0.7125 - val_loss: 0.5229 - val_accuracy: 0.8625\n    Epoch 2/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.3325 - accuracy: 0.9042 - val_loss: 0.4620 - val_accuracy: 0.8875\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1316 - accuracy: 0.9583 - val_loss: 0.3288 - val_accuracy: 0.9125\n    Epoch 4/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.1329 - accuracy: 0.9500 - val_loss: 0.5030 - val_accuracy: 0.8875\n    Epoch 5/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.1123 - accuracy: 0.9542 - val_loss: 0.3284 - val_accuracy: 0.9125\n    Epoch 6/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.1090 - accuracy: 0.9583 - val_loss: 0.2972 - val_accuracy: 0.9000\n    Epoch 7/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.1076 - accuracy: 0.9583 - val_loss: 0.2302 - val_accuracy: 0.9375\n    Epoch 8/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0441 - accuracy: 0.9917 - val_loss: 0.2963 - val_accuracy: 0.9375\n    Epoch 9/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0472 - accuracy: 0.9833 - val_loss: 0.2585 - val_accuracy: 0.9375\n    Epoch 10/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0412 - accuracy: 0.9917 - val_loss: 0.1900 - val_accuracy: 0.9500\n    Epoch 11/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0327 - accuracy: 0.9958 - val_loss: 0.2542 - val_accuracy: 0.9250\n    Epoch 12/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0626 - accuracy: 0.9792 - val_loss: 0.2552 - val_accuracy: 0.9375\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0445 - accuracy: 0.9750 - val_loss: 0.2065 - val_accuracy: 0.9375\n    Epoch 14/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0247 - accuracy: 0.9917 - val_loss: 0.1969 - val_accuracy: 0.9375\n    Epoch 15/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0346 - accuracy: 0.9875 - val_loss: 0.1809 - val_accuracy: 0.9500\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0260 - accuracy: 0.9875 - val_loss: 0.2328 - val_accuracy: 0.9375\n    Epoch 17/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0197 - accuracy: 1.0000 - val_loss: 0.2135 - val_accuracy: 0.9500\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0196 - accuracy: 1.0000 - val_loss: 0.1878 - val_accuracy: 0.9625\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0189 - accuracy: 1.0000 - val_loss: 0.2175 - val_accuracy: 0.9375\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0169 - accuracy: 0.9958 - val_loss: 0.2025 - val_accuracy: 0.9500\n    Epoch 21/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0147 - accuracy: 1.0000 - val_loss: 0.2045 - val_accuracy: 0.9500\n    Epoch 22/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0145 - accuracy: 1.0000 - val_loss: 0.1916 - val_accuracy: 0.9500\n    Epoch 23/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0142 - accuracy: 1.0000 - val_loss: 0.2198 - val_accuracy: 0.9375\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0150 - accuracy: 1.0000 - val_loss: 0.2423 - val_accuracy: 0.9375\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0143 - accuracy: 1.0000 - val_loss: 0.1885 - val_accuracy: 0.9625\n    Epoch 26/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0127 - accuracy: 0.9958 - val_loss: 0.1971 - val_accuracy: 0.9500\n    Epoch 27/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0123 - accuracy: 1.0000 - val_loss: 0.2051 - val_accuracy: 0.9500\n    Epoch 28/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0111 - accuracy: 1.0000 - val_loss: 0.1797 - val_accuracy: 0.9500\n    Epoch 29/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0145 - accuracy: 1.0000 - val_loss: 0.2270 - val_accuracy: 0.9375\n    Epoch 30/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0137 - accuracy: 0.9958 - val_loss: 0.1853 - val_accuracy: 0.9500\n    Epoch 31/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0120 - accuracy: 1.0000 - val_loss: 0.1881 - val_accuracy: 0.9500\n    Epoch 32/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0089 - accuracy: 1.0000 - val_loss: 0.2001 - val_accuracy: 0.9500\n    Epoch 33/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0089 - accuracy: 1.0000 - val_loss: 0.2486 - val_accuracy: 0.9375\n    Epoch 34/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0073 - accuracy: 1.0000 - val_loss: 0.1896 - val_accuracy: 0.9500\n    Epoch 35/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0076 - accuracy: 1.0000 - val_loss: 0.1653 - val_accuracy: 0.9500\n    Epoch 36/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0271 - accuracy: 0.9875 - val_loss: 0.1689 - val_accuracy: 0.9375\n    Epoch 37/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0208 - accuracy: 0.9917 - val_loss: 0.1607 - val_accuracy: 0.9625\n    Epoch 38/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0090 - accuracy: 1.0000 - val_loss: 0.1798 - val_accuracy: 0.9500\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.1808 - accuracy: 0.7208 - val_loss: 0.6688 - val_accuracy: 0.8375\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.5107 - accuracy: 0.8292 - val_loss: 0.4230 - val_accuracy: 0.8750\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1728 - accuracy: 0.9583 - val_loss: 0.3316 - val_accuracy: 0.9250\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0762 - accuracy: 0.9750 - val_loss: 0.2097 - val_accuracy: 0.9375\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0651 - accuracy: 0.9833 - val_loss: 0.1698 - val_accuracy: 0.9500\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0667 - accuracy: 0.9792 - val_loss: 0.3522 - val_accuracy: 0.9250\n    Epoch 7/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0819 - accuracy: 0.9708 - val_loss: 0.2333 - val_accuracy: 0.9375\n    Epoch 8/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0431 - accuracy: 0.9875 - val_loss: 0.1985 - val_accuracy: 0.9625\n    Epoch 9/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0443 - accuracy: 0.9917 - val_loss: 0.2194 - val_accuracy: 0.9500\n    Epoch 10/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0329 - accuracy: 0.9958 - val_loss: 0.1943 - val_accuracy: 0.9500\n    Epoch 11/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0358 - accuracy: 0.9917 - val_loss: 0.2743 - val_accuracy: 0.9375\n    Epoch 12/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0263 - accuracy: 0.9958 - val_loss: 0.1772 - val_accuracy: 0.9500\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0261 - accuracy: 0.9875 - val_loss: 0.1981 - val_accuracy: 0.9625\n    Epoch 14/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0258 - accuracy: 0.9917 - val_loss: 0.1591 - val_accuracy: 0.9625\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0159 - accuracy: 0.9958 - val_loss: 0.1400 - val_accuracy: 0.9625\n    Epoch 16/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0243 - accuracy: 0.9917 - val_loss: 0.1716 - val_accuracy: 0.9625\n    Epoch 17/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0127 - accuracy: 1.0000 - val_loss: 0.1473 - val_accuracy: 0.9625\n    Epoch 18/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0135 - accuracy: 1.0000 - val_loss: 0.1496 - val_accuracy: 0.9625\n    Epoch 19/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0149 - accuracy: 1.0000 - val_loss: 0.1683 - val_accuracy: 0.9625\n    Epoch 20/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0130 - accuracy: 1.0000 - val_loss: 0.1697 - val_accuracy: 0.9625\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0093 - accuracy: 1.0000 - val_loss: 0.1616 - val_accuracy: 0.9750\n    Epoch 22/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0115 - accuracy: 0.9958 - val_loss: 0.1356 - val_accuracy: 0.9625\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0076 - accuracy: 1.0000 - val_loss: 0.1559 - val_accuracy: 0.9625\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0098 - accuracy: 1.0000 - val_loss: 0.1501 - val_accuracy: 0.9625\n    Epoch 25/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0090 - accuracy: 1.0000 - val_loss: 0.1639 - val_accuracy: 0.9625\n    Epoch 26/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0085 - accuracy: 1.0000 - val_loss: 0.1453 - val_accuracy: 0.9750\n    Epoch 27/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0076 - accuracy: 1.0000 - val_loss: 0.1579 - val_accuracy: 0.9750\n    Epoch 28/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0087 - accuracy: 1.0000 - val_loss: 0.1440 - val_accuracy: 0.9750\n    Epoch 29/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0058 - accuracy: 1.0000 - val_loss: 0.1568 - val_accuracy: 0.9625\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0054 - accuracy: 1.0000 - val_loss: 0.1474 - val_accuracy: 0.9750\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0052 - accuracy: 1.0000 - val_loss: 0.1571 - val_accuracy: 0.9625\n    Epoch 32/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0070 - accuracy: 1.0000 - val_loss: 0.1557 - val_accuracy: 0.9625\n    Epoch 33/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0063 - accuracy: 1.0000 - val_loss: 0.1405 - val_accuracy: 0.9750\n    Epoch 34/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0056 - accuracy: 1.0000 - val_loss: 0.1466 - val_accuracy: 0.9750\n    Epoch 35/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0050 - accuracy: 1.0000 - val_loss: 0.1518 - val_accuracy: 0.9750\n    Epoch 36/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0067 - accuracy: 1.0000 - val_loss: 0.1504 - val_accuracy: 0.9625\n    Epoch 37/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0052 - accuracy: 1.0000 - val_loss: 0.1610 - val_accuracy: 0.9625\n    Epoch 38/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0066 - accuracy: 1.0000 - val_loss: 0.1553 - val_accuracy: 0.9750\n    Epoch 39/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0046 - accuracy: 1.0000 - val_loss: 0.1592 - val_accuracy: 0.9625\n    Epoch 40/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0042 - accuracy: 1.0000 - val_loss: 0.1629 - val_accuracy: 0.9625\n    Epoch 41/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0042 - accuracy: 1.0000 - val_loss: 0.1479 - val_accuracy: 0.9625\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 0.9836 - accuracy: 0.7917 - val_loss: 1.1370 - val_accuracy: 0.7625\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.5400 - accuracy: 0.9042 - val_loss: 0.5050 - val_accuracy: 0.7750\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3384 - accuracy: 0.8750 - val_loss: 0.2518 - val_accuracy: 0.8750\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1507 - accuracy: 0.9417 - val_loss: 0.2379 - val_accuracy: 0.9500\n    Epoch 5/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0781 - accuracy: 0.9708 - val_loss: 0.2099 - val_accuracy: 0.9625\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0568 - accuracy: 0.9833 - val_loss: 0.1278 - val_accuracy: 0.9750\n    Epoch 7/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0357 - accuracy: 0.9833 - val_loss: 0.1204 - val_accuracy: 0.9750\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0347 - accuracy: 0.9917 - val_loss: 0.1149 - val_accuracy: 0.9875\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0306 - accuracy: 0.9917 - val_loss: 0.1471 - val_accuracy: 0.9500\n    Epoch 10/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0364 - accuracy: 0.9875 - val_loss: 0.1207 - val_accuracy: 0.9625\n    Epoch 11/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0338 - accuracy: 0.9917 - val_loss: 0.1547 - val_accuracy: 0.9750\n    Epoch 12/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0206 - accuracy: 0.9958 - val_loss: 0.1487 - val_accuracy: 0.9500\n    Epoch 13/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0307 - accuracy: 0.9917 - val_loss: 0.1840 - val_accuracy: 0.9625\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0272 - accuracy: 0.9958 - val_loss: 0.1286 - val_accuracy: 0.9750\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0217 - accuracy: 0.9917 - val_loss: 0.1042 - val_accuracy: 0.9875\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0173 - accuracy: 0.9958 - val_loss: 0.1006 - val_accuracy: 0.9875\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0229 - accuracy: 0.9875 - val_loss: 0.1375 - val_accuracy: 0.9625\n    Epoch 18/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0293 - accuracy: 0.9875 - val_loss: 0.1556 - val_accuracy: 0.9500\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0191 - accuracy: 0.9958 - val_loss: 0.0987 - val_accuracy: 0.9875\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0124 - accuracy: 0.9958 - val_loss: 0.1165 - val_accuracy: 0.9750\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0144 - accuracy: 1.0000 - val_loss: 0.1160 - val_accuracy: 0.9750\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0092 - accuracy: 1.0000 - val_loss: 0.0999 - val_accuracy: 0.9875\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0092 - accuracy: 1.0000 - val_loss: 0.1400 - val_accuracy: 0.9750\n    Epoch 24/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0105 - accuracy: 1.0000 - val_loss: 0.1331 - val_accuracy: 0.9750\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0111 - accuracy: 1.0000 - val_loss: 0.1149 - val_accuracy: 0.9750\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0090 - accuracy: 1.0000 - val_loss: 0.1321 - val_accuracy: 0.9750\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0102 - accuracy: 1.0000 - val_loss: 0.1065 - val_accuracy: 0.9750\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0072 - accuracy: 1.0000 - val_loss: 0.1112 - val_accuracy: 0.9750\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.0022 - accuracy: 0.7625 - val_loss: 0.1757 - val_accuracy: 0.9125\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.4234 - accuracy: 0.9083 - val_loss: 0.1947 - val_accuracy: 0.9125\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2286 - accuracy: 0.9333 - val_loss: 0.6522 - val_accuracy: 0.7250\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1413 - accuracy: 0.9458 - val_loss: 0.1004 - val_accuracy: 0.9500\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0929 - accuracy: 0.9750 - val_loss: 0.0606 - val_accuracy: 0.9875\n    Epoch 6/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0894 - accuracy: 0.9667 - val_loss: 0.0922 - val_accuracy: 0.9500\n    Epoch 7/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0737 - accuracy: 0.9792 - val_loss: 0.0943 - val_accuracy: 0.9625\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0633 - accuracy: 0.9750 - val_loss: 0.1728 - val_accuracy: 0.9125\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0921 - accuracy: 0.9792 - val_loss: 0.0645 - val_accuracy: 0.9750\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0559 - accuracy: 0.9792 - val_loss: 0.0768 - val_accuracy: 0.9750\n    Epoch 11/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0450 - accuracy: 0.9875 - val_loss: 0.1519 - val_accuracy: 0.9375\n    Epoch 12/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0557 - accuracy: 0.9792 - val_loss: 0.0751 - val_accuracy: 0.9750\n    Epoch 13/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0285 - accuracy: 0.9958 - val_loss: 0.0476 - val_accuracy: 0.9875\n    Epoch 14/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0342 - accuracy: 0.9958 - val_loss: 0.0838 - val_accuracy: 0.9750\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0377 - accuracy: 0.9875 - val_loss: 0.0371 - val_accuracy: 1.0000\n    Epoch 16/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0259 - accuracy: 0.9917 - val_loss: 0.0737 - val_accuracy: 0.9750\n    Epoch 17/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0311 - accuracy: 0.9917 - val_loss: 0.0433 - val_accuracy: 0.9875\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0196 - accuracy: 0.9958 - val_loss: 0.0648 - val_accuracy: 0.9750\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0171 - accuracy: 0.9958 - val_loss: 0.0656 - val_accuracy: 0.9750\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0275 - accuracy: 0.9917 - val_loss: 0.0375 - val_accuracy: 1.0000\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0189 - accuracy: 0.9958 - val_loss: 0.0284 - val_accuracy: 1.0000\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0136 - accuracy: 1.0000 - val_loss: 0.0529 - val_accuracy: 0.9750\n    Epoch 23/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0149 - accuracy: 0.9958 - val_loss: 0.0303 - val_accuracy: 1.0000\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0114 - accuracy: 1.0000 - val_loss: 0.0386 - val_accuracy: 0.9875\n    Epoch 25/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0203 - accuracy: 1.0000 - val_loss: 0.0394 - val_accuracy: 0.9875\n    Epoch 26/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0102 - accuracy: 1.0000 - val_loss: 0.0360 - val_accuracy: 0.9875\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0109 - accuracy: 1.0000 - val_loss: 0.0364 - val_accuracy: 1.0000\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0167 - accuracy: 1.0000 - val_loss: 0.0434 - val_accuracy: 0.9750\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0150 - accuracy: 1.0000 - val_loss: 0.0393 - val_accuracy: 0.9875\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0113 - accuracy: 1.0000 - val_loss: 0.0229 - val_accuracy: 1.0000\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0088 - accuracy: 1.0000 - val_loss: 0.0289 - val_accuracy: 1.0000\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0087 - accuracy: 1.0000 - val_loss: 0.0318 - val_accuracy: 0.9875\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0094 - accuracy: 1.0000 - val_loss: 0.0259 - val_accuracy: 1.0000\n    Epoch 34/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0080 - accuracy: 1.0000 - val_loss: 0.0326 - val_accuracy: 0.9875\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0097 - accuracy: 1.0000 - val_loss: 0.0339 - val_accuracy: 1.0000\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.0239 - accuracy: 0.7458 - val_loss: 1.0399 - val_accuracy: 0.8125\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3086 - accuracy: 0.9292 - val_loss: 0.7854 - val_accuracy: 0.8500\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2436 - accuracy: 0.9167 - val_loss: 0.3959 - val_accuracy: 0.8500\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1395 - accuracy: 0.9500 - val_loss: 0.3255 - val_accuracy: 0.8500\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0753 - accuracy: 0.9750 - val_loss: 0.2184 - val_accuracy: 0.9125\n    Epoch 6/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0753 - accuracy: 0.9792 - val_loss: 0.3983 - val_accuracy: 0.8375\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0750 - accuracy: 0.9750 - val_loss: 0.2317 - val_accuracy: 0.9125\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0670 - accuracy: 0.9750 - val_loss: 0.1659 - val_accuracy: 0.9625\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0403 - accuracy: 0.9875 - val_loss: 0.1877 - val_accuracy: 0.9250\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0357 - accuracy: 0.9917 - val_loss: 0.1701 - val_accuracy: 0.9500\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0564 - accuracy: 0.9750 - val_loss: 0.2543 - val_accuracy: 0.9250\n    Epoch 12/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0612 - accuracy: 0.9750 - val_loss: 0.1977 - val_accuracy: 0.9250\n    Epoch 13/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0428 - accuracy: 0.9792 - val_loss: 0.2106 - val_accuracy: 0.9375\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0238 - accuracy: 1.0000 - val_loss: 0.1973 - val_accuracy: 0.9250\n    Epoch 15/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0281 - accuracy: 0.9875 - val_loss: 0.2002 - val_accuracy: 0.9250\n    Epoch 16/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0337 - accuracy: 0.9917 - val_loss: 0.1968 - val_accuracy: 0.9125\n    Epoch 17/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0171 - accuracy: 0.9958 - val_loss: 0.2157 - val_accuracy: 0.9250\n    Epoch 18/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0186 - accuracy: 1.0000 - val_loss: 0.2352 - val_accuracy: 0.9250\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0211 - accuracy: 0.9958 - val_loss: 0.1685 - val_accuracy: 0.9375\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0137 - accuracy: 1.0000 - val_loss: 0.1932 - val_accuracy: 0.9250\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0100 - accuracy: 1.0000 - val_loss: 0.1729 - val_accuracy: 0.9250\n    Epoch 22/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0183 - accuracy: 0.9958 - val_loss: 0.1971 - val_accuracy: 0.9375\n    Epoch 23/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0146 - accuracy: 1.0000 - val_loss: 0.1637 - val_accuracy: 0.9500\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0211 - accuracy: 0.9917 - val_loss: 0.1650 - val_accuracy: 0.9500\n    Epoch 25/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0159 - accuracy: 0.9958 - val_loss: 0.1616 - val_accuracy: 0.9500\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0083 - accuracy: 1.0000 - val_loss: 0.1673 - val_accuracy: 0.9625\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0096 - accuracy: 1.0000 - val_loss: 0.1865 - val_accuracy: 0.9375\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0098 - accuracy: 1.0000 - val_loss: 0.1754 - val_accuracy: 0.9375\n    Epoch 1/300\n    60/60 [==============================] - 1s 4ms/step - loss: 1.5515 - accuracy: 0.6833 - val_loss: 0.3500 - val_accuracy: 0.9250\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3480 - accuracy: 0.8917 - val_loss: 0.2234 - val_accuracy: 0.9375\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1644 - accuracy: 0.9375 - val_loss: 0.2668 - val_accuracy: 0.8875\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1841 - accuracy: 0.9417 - val_loss: 0.2375 - val_accuracy: 0.9375\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1214 - accuracy: 0.9625 - val_loss: 0.1081 - val_accuracy: 0.9875\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1238 - accuracy: 0.9375 - val_loss: 0.1977 - val_accuracy: 0.9625\n    Epoch 7/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0584 - accuracy: 0.9833 - val_loss: 0.1690 - val_accuracy: 0.9625\n    Epoch 8/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0764 - accuracy: 0.9750 - val_loss: 0.1359 - val_accuracy: 0.9500\n    Epoch 9/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0556 - accuracy: 0.9833 - val_loss: 0.1568 - val_accuracy: 0.9500\n    Epoch 10/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0613 - accuracy: 0.9833 - val_loss: 0.1423 - val_accuracy: 0.9625\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0573 - accuracy: 0.9750 - val_loss: 0.0966 - val_accuracy: 0.9750\n    Epoch 12/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0394 - accuracy: 0.9833 - val_loss: 0.0903 - val_accuracy: 0.9875\n    Epoch 13/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0390 - accuracy: 0.9875 - val_loss: 0.0928 - val_accuracy: 0.9500\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0252 - accuracy: 1.0000 - val_loss: 0.1004 - val_accuracy: 0.9625\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0328 - accuracy: 0.9917 - val_loss: 0.0883 - val_accuracy: 0.9625\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0355 - accuracy: 0.9917 - val_loss: 0.1248 - val_accuracy: 0.9625\n    Epoch 17/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0202 - accuracy: 1.0000 - val_loss: 0.0979 - val_accuracy: 0.9500\n    Epoch 18/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0164 - accuracy: 1.0000 - val_loss: 0.1069 - val_accuracy: 0.9625\n    Epoch 19/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0300 - accuracy: 0.9917 - val_loss: 0.0686 - val_accuracy: 0.9875\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0179 - accuracy: 1.0000 - val_loss: 0.0822 - val_accuracy: 0.9500\n    Epoch 21/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0200 - accuracy: 1.0000 - val_loss: 0.0971 - val_accuracy: 0.9500\n    Epoch 22/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0157 - accuracy: 1.0000 - val_loss: 0.0772 - val_accuracy: 0.9625\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0173 - accuracy: 0.9958 - val_loss: 0.1040 - val_accuracy: 0.9625\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0198 - accuracy: 0.9958 - val_loss: 0.0753 - val_accuracy: 0.9500\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0123 - accuracy: 1.0000 - val_loss: 0.0897 - val_accuracy: 0.9375\n    Epoch 1/300\n    60/60 [==============================] - 1s 5ms/step - loss: 1.3049 - accuracy: 0.7083 - val_loss: 0.6265 - val_accuracy: 0.8250\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.4889 - accuracy: 0.8875 - val_loss: 0.2713 - val_accuracy: 0.9250\n    Epoch 3/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.2350 - accuracy: 0.9250 - val_loss: 0.2209 - val_accuracy: 0.9250\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1080 - accuracy: 0.9625 - val_loss: 0.1642 - val_accuracy: 0.9625\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0753 - accuracy: 0.9667 - val_loss: 0.1869 - val_accuracy: 0.9500\n    Epoch 6/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0652 - accuracy: 0.9792 - val_loss: 0.2360 - val_accuracy: 0.9250\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0474 - accuracy: 0.9917 - val_loss: 0.1620 - val_accuracy: 0.9500\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0389 - accuracy: 0.9875 - val_loss: 0.1508 - val_accuracy: 0.9500\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0276 - accuracy: 0.9958 - val_loss: 0.1687 - val_accuracy: 0.9500\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0255 - accuracy: 0.9958 - val_loss: 0.1447 - val_accuracy: 0.9625\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0353 - accuracy: 0.9875 - val_loss: 0.1417 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0312 - accuracy: 0.9875 - val_loss: 0.1410 - val_accuracy: 0.9625\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0246 - accuracy: 0.9917 - val_loss: 0.1393 - val_accuracy: 0.9625\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0219 - accuracy: 0.9958 - val_loss: 0.1406 - val_accuracy: 0.9625\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0147 - accuracy: 1.0000 - val_loss: 0.1446 - val_accuracy: 0.9500\n    Epoch 16/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0193 - accuracy: 0.9958 - val_loss: 0.1436 - val_accuracy: 0.9500\n    Epoch 17/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0146 - accuracy: 1.0000 - val_loss: 0.1349 - val_accuracy: 0.9750\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0148 - accuracy: 1.0000 - val_loss: 0.1363 - val_accuracy: 0.9500\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0123 - accuracy: 1.0000 - val_loss: 0.1402 - val_accuracy: 0.9500\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0140 - accuracy: 0.9958 - val_loss: 0.1411 - val_accuracy: 0.9625\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0110 - accuracy: 1.0000 - val_loss: 0.1436 - val_accuracy: 0.9500\n    Epoch 22/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0156 - accuracy: 1.0000 - val_loss: 0.1326 - val_accuracy: 0.9625\n    Epoch 23/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0102 - accuracy: 1.0000 - val_loss: 0.1469 - val_accuracy: 0.9625\n    Epoch 24/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0097 - accuracy: 1.0000 - val_loss: 0.1365 - val_accuracy: 0.9625\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0091 - accuracy: 1.0000 - val_loss: 0.1387 - val_accuracy: 0.9625\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0091 - accuracy: 1.0000 - val_loss: 0.1338 - val_accuracy: 0.9625\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0073 - accuracy: 1.0000 - val_loss: 0.1336 - val_accuracy: 0.9625\n    Epoch 28/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0078 - accuracy: 1.0000 - val_loss: 0.1364 - val_accuracy: 0.9625\n    Epoch 29/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0083 - accuracy: 1.0000 - val_loss: 0.1333 - val_accuracy: 0.9625\n    Epoch 30/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0065 - accuracy: 1.0000 - val_loss: 0.1385 - val_accuracy: 0.9625\n    Epoch 31/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0067 - accuracy: 1.0000 - val_loss: 0.1385 - val_accuracy: 0.9625\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0069 - accuracy: 1.0000 - val_loss: 0.1304 - val_accuracy: 0.9625\n    Epoch 33/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0062 - accuracy: 1.0000 - val_loss: 0.1355 - val_accuracy: 0.9625\n    Epoch 34/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0061 - accuracy: 1.0000 - val_loss: 0.1328 - val_accuracy: 0.9625\n    Epoch 35/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0058 - accuracy: 1.0000 - val_loss: 0.1339 - val_accuracy: 0.9625\n    Epoch 36/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0052 - accuracy: 1.0000 - val_loss: 0.1325 - val_accuracy: 0.9625\n    Epoch 37/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0051 - accuracy: 1.0000 - val_loss: 0.1354 - val_accuracy: 0.9750\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.4990 - accuracy: 0.7375 - val_loss: 0.3866 - val_accuracy: 0.8875\n    Epoch 2/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.2082 - accuracy: 0.9250 - val_loss: 0.4094 - val_accuracy: 0.8875\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1509 - accuracy: 0.9458 - val_loss: 0.2460 - val_accuracy: 0.9250\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1491 - accuracy: 0.9417 - val_loss: 0.2200 - val_accuracy: 0.9125\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0990 - accuracy: 0.9667 - val_loss: 0.1507 - val_accuracy: 0.9625\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1027 - accuracy: 0.9542 - val_loss: 0.3133 - val_accuracy: 0.8875\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0530 - accuracy: 0.9833 - val_loss: 0.1755 - val_accuracy: 0.9750\n    Epoch 8/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0412 - accuracy: 0.9875 - val_loss: 0.1554 - val_accuracy: 0.9750\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0888 - accuracy: 0.9708 - val_loss: 0.2166 - val_accuracy: 0.9625\n    Epoch 10/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0545 - accuracy: 0.9792 - val_loss: 0.1530 - val_accuracy: 0.9625\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0345 - accuracy: 0.9917 - val_loss: 0.1647 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0376 - accuracy: 0.9833 - val_loss: 0.1970 - val_accuracy: 0.9375\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0531 - accuracy: 0.9792 - val_loss: 0.1741 - val_accuracy: 0.9375\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0293 - accuracy: 0.9958 - val_loss: 0.1802 - val_accuracy: 0.9375\n    Epoch 15/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0324 - accuracy: 0.9917 - val_loss: 0.1425 - val_accuracy: 0.9750\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0269 - accuracy: 0.9917 - val_loss: 0.1411 - val_accuracy: 0.9625\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0201 - accuracy: 1.0000 - val_loss: 0.1459 - val_accuracy: 0.9375\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0212 - accuracy: 0.9958 - val_loss: 0.1398 - val_accuracy: 0.9750\n    Epoch 19/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0205 - accuracy: 1.0000 - val_loss: 0.1364 - val_accuracy: 0.9625\n    Epoch 20/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0152 - accuracy: 1.0000 - val_loss: 0.1334 - val_accuracy: 0.9750\n    Epoch 21/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0171 - accuracy: 0.9958 - val_loss: 0.1751 - val_accuracy: 0.9500\n    Epoch 22/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0185 - accuracy: 0.9958 - val_loss: 0.1818 - val_accuracy: 0.9250\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0274 - accuracy: 0.9958 - val_loss: 0.1425 - val_accuracy: 0.9500\n    Epoch 24/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0208 - accuracy: 0.9917 - val_loss: 0.1972 - val_accuracy: 0.9250\n    Epoch 25/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0365 - accuracy: 0.9792 - val_loss: 0.2128 - val_accuracy: 0.9250\n    Epoch 26/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0518 - accuracy: 0.9875 - val_loss: 0.1254 - val_accuracy: 0.9750\n    Epoch 27/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0104 - accuracy: 1.0000 - val_loss: 0.1155 - val_accuracy: 0.9750\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.3185 - accuracy: 0.7583 - val_loss: 0.6828 - val_accuracy: 0.8750\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2403 - accuracy: 0.9167 - val_loss: 0.3605 - val_accuracy: 0.9250\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1171 - accuracy: 0.9583 - val_loss: 0.3538 - val_accuracy: 0.9000\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0561 - accuracy: 0.9792 - val_loss: 0.2779 - val_accuracy: 0.9500\n    Epoch 5/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0738 - accuracy: 0.9667 - val_loss: 0.3017 - val_accuracy: 0.9250\n    Epoch 6/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0563 - accuracy: 0.9792 - val_loss: 0.2988 - val_accuracy: 0.9250\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0456 - accuracy: 0.9917 - val_loss: 0.2594 - val_accuracy: 0.9375\n    Epoch 8/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0835 - accuracy: 0.9625 - val_loss: 0.3243 - val_accuracy: 0.9250\n    Epoch 9/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0754 - accuracy: 0.9667 - val_loss: 0.2429 - val_accuracy: 0.9375\n    Epoch 10/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0572 - accuracy: 0.9833 - val_loss: 0.2571 - val_accuracy: 0.9250\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0324 - accuracy: 0.9917 - val_loss: 0.2492 - val_accuracy: 0.9250\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0358 - accuracy: 0.9917 - val_loss: 0.2573 - val_accuracy: 0.9375\n    Epoch 13/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0308 - accuracy: 0.9917 - val_loss: 0.2613 - val_accuracy: 0.9375\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0241 - accuracy: 0.9958 - val_loss: 0.2567 - val_accuracy: 0.9500\n    Epoch 15/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0181 - accuracy: 0.9958 - val_loss: 0.2521 - val_accuracy: 0.9500\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0139 - accuracy: 1.0000 - val_loss: 0.2529 - val_accuracy: 0.9500\n    Epoch 17/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0139 - accuracy: 1.0000 - val_loss: 0.2579 - val_accuracy: 0.9500\n    Epoch 18/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0120 - accuracy: 1.0000 - val_loss: 0.2761 - val_accuracy: 0.9500\n    Epoch 19/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0125 - accuracy: 1.0000 - val_loss: 0.2519 - val_accuracy: 0.9500\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0130 - accuracy: 0.9958 - val_loss: 0.2585 - val_accuracy: 0.9500\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0104 - accuracy: 1.0000 - val_loss: 0.2484 - val_accuracy: 0.9500\n    Epoch 22/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0120 - accuracy: 1.0000 - val_loss: 0.2642 - val_accuracy: 0.9375\n    Epoch 23/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0111 - accuracy: 1.0000 - val_loss: 0.2544 - val_accuracy: 0.9500\n    Epoch 24/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0102 - accuracy: 1.0000 - val_loss: 0.2777 - val_accuracy: 0.9375\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.6901 - accuracy: 0.7208 - val_loss: 0.3613 - val_accuracy: 0.8875\n    Epoch 2/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.3915 - accuracy: 0.8833 - val_loss: 0.7386 - val_accuracy: 0.8000\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2447 - accuracy: 0.9042 - val_loss: 0.0746 - val_accuracy: 0.9625\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1046 - accuracy: 0.9625 - val_loss: 0.1613 - val_accuracy: 0.9500\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0663 - accuracy: 0.9792 - val_loss: 0.0763 - val_accuracy: 0.9625\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0701 - accuracy: 0.9792 - val_loss: 0.0852 - val_accuracy: 0.9500\n    Epoch 7/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0444 - accuracy: 0.9875 - val_loss: 0.1019 - val_accuracy: 0.9500\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0513 - accuracy: 0.9833 - val_loss: 0.0698 - val_accuracy: 0.9750\n    Epoch 9/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0449 - accuracy: 0.9833 - val_loss: 0.0737 - val_accuracy: 0.9750\n    Epoch 10/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0351 - accuracy: 0.9875 - val_loss: 0.0791 - val_accuracy: 0.9625\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0350 - accuracy: 0.9917 - val_loss: 0.0589 - val_accuracy: 0.9750\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0481 - accuracy: 0.9750 - val_loss: 0.0588 - val_accuracy: 0.9750\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0404 - accuracy: 0.9833 - val_loss: 0.0567 - val_accuracy: 0.9750\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0290 - accuracy: 0.9917 - val_loss: 0.0438 - val_accuracy: 0.9875\n    Epoch 15/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0220 - accuracy: 0.9958 - val_loss: 0.0489 - val_accuracy: 0.9750\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0468 - accuracy: 0.9875 - val_loss: 0.1488 - val_accuracy: 0.9250\n    Epoch 17/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0413 - accuracy: 0.9875 - val_loss: 0.0355 - val_accuracy: 0.9875\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0202 - accuracy: 0.9917 - val_loss: 0.0309 - val_accuracy: 1.0000\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0197 - accuracy: 0.9958 - val_loss: 0.0375 - val_accuracy: 0.9875\n    Epoch 20/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0176 - accuracy: 0.9958 - val_loss: 0.0348 - val_accuracy: 0.9875\n    Epoch 21/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0171 - accuracy: 1.0000 - val_loss: 0.0535 - val_accuracy: 0.9875\n    Epoch 22/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0166 - accuracy: 0.9958 - val_loss: 0.0531 - val_accuracy: 0.9750\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0173 - accuracy: 1.0000 - val_loss: 0.0332 - val_accuracy: 0.9875\n    Epoch 24/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0131 - accuracy: 1.0000 - val_loss: 0.0355 - val_accuracy: 0.9875\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0185 - accuracy: 0.9958 - val_loss: 0.0351 - val_accuracy: 0.9750\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0109 - accuracy: 1.0000 - val_loss: 0.0542 - val_accuracy: 0.9750\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0115 - accuracy: 1.0000 - val_loss: 0.0316 - val_accuracy: 0.9875\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0101 - accuracy: 1.0000 - val_loss: 0.0338 - val_accuracy: 0.9875\n    Epoch 29/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0122 - accuracy: 1.0000 - val_loss: 0.0353 - val_accuracy: 0.9875\n    Epoch 30/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0092 - accuracy: 1.0000 - val_loss: 0.0343 - val_accuracy: 0.9875\n    Epoch 31/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0088 - accuracy: 1.0000 - val_loss: 0.0342 - val_accuracy: 0.9875\n    Epoch 32/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0085 - accuracy: 1.0000 - val_loss: 0.0344 - val_accuracy: 0.9875\n    Epoch 33/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0084 - accuracy: 1.0000 - val_loss: 0.0445 - val_accuracy: 0.9750\n    Epoch 34/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0073 - accuracy: 1.0000 - val_loss: 0.0345 - val_accuracy: 0.9875\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0073 - accuracy: 1.0000 - val_loss: 0.0389 - val_accuracy: 0.9875\n    Epoch 36/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0075 - accuracy: 1.0000 - val_loss: 0.0313 - val_accuracy: 0.9875\n    Epoch 37/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0072 - accuracy: 1.0000 - val_loss: 0.0447 - val_accuracy: 0.9875\n    Epoch 38/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0091 - accuracy: 1.0000 - val_loss: 0.0409 - val_accuracy: 0.9875\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.3985 - accuracy: 0.7708 - val_loss: 0.2646 - val_accuracy: 0.9500\n    Epoch 2/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.2986 - accuracy: 0.9375 - val_loss: 0.1775 - val_accuracy: 0.9375\n    Epoch 3/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.2200 - accuracy: 0.9333 - val_loss: 0.3451 - val_accuracy: 0.9125\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1541 - accuracy: 0.9458 - val_loss: 0.1182 - val_accuracy: 0.9625\n    Epoch 5/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0825 - accuracy: 0.9708 - val_loss: 0.1003 - val_accuracy: 0.9625\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0862 - accuracy: 0.9750 - val_loss: 0.2079 - val_accuracy: 0.9500\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1079 - accuracy: 0.9625 - val_loss: 0.1151 - val_accuracy: 0.9750\n    Epoch 8/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0556 - accuracy: 0.9708 - val_loss: 0.1026 - val_accuracy: 0.9500\n    Epoch 9/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0333 - accuracy: 0.9917 - val_loss: 0.0967 - val_accuracy: 0.9625\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0420 - accuracy: 0.9833 - val_loss: 0.2043 - val_accuracy: 0.8875\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0526 - accuracy: 0.9917 - val_loss: 0.0852 - val_accuracy: 0.9750\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0272 - accuracy: 0.9958 - val_loss: 0.0807 - val_accuracy: 0.9750\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0291 - accuracy: 0.9917 - val_loss: 0.0777 - val_accuracy: 0.9625\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0191 - accuracy: 0.9958 - val_loss: 0.0906 - val_accuracy: 0.9625\n    Epoch 15/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0189 - accuracy: 0.9958 - val_loss: 0.0816 - val_accuracy: 0.9625\n    Epoch 16/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0165 - accuracy: 0.9958 - val_loss: 0.0776 - val_accuracy: 0.9750\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0186 - accuracy: 1.0000 - val_loss: 0.0949 - val_accuracy: 0.9875\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0285 - accuracy: 0.9917 - val_loss: 0.0852 - val_accuracy: 0.9625\n    Epoch 19/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0178 - accuracy: 0.9958 - val_loss: 0.1180 - val_accuracy: 0.9625\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0136 - accuracy: 1.0000 - val_loss: 0.0770 - val_accuracy: 0.9625\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0132 - accuracy: 1.0000 - val_loss: 0.0778 - val_accuracy: 0.9625\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0097 - accuracy: 1.0000 - val_loss: 0.0764 - val_accuracy: 0.9750\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0131 - accuracy: 1.0000 - val_loss: 0.0758 - val_accuracy: 0.9625\n    Epoch 24/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0086 - accuracy: 1.0000 - val_loss: 0.0776 - val_accuracy: 0.9750\n    Epoch 25/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0085 - accuracy: 1.0000 - val_loss: 0.0750 - val_accuracy: 0.9625\n    Epoch 26/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0085 - accuracy: 1.0000 - val_loss: 0.0832 - val_accuracy: 0.9750\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0104 - accuracy: 1.0000 - val_loss: 0.0821 - val_accuracy: 0.9750\n    Epoch 28/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0088 - accuracy: 1.0000 - val_loss: 0.0791 - val_accuracy: 0.9625\n    Epoch 29/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0072 - accuracy: 1.0000 - val_loss: 0.0830 - val_accuracy: 0.9750\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0083 - accuracy: 1.0000 - val_loss: 0.0786 - val_accuracy: 0.9750\n    Epoch 31/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0070 - accuracy: 1.0000 - val_loss: 0.0855 - val_accuracy: 0.9750\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0114 - accuracy: 1.0000 - val_loss: 0.0745 - val_accuracy: 0.9750\n    Epoch 33/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0095 - accuracy: 1.0000 - val_loss: 0.0791 - val_accuracy: 0.9750\n    Epoch 34/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0060 - accuracy: 1.0000 - val_loss: 0.0715 - val_accuracy: 0.9750\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0057 - accuracy: 1.0000 - val_loss: 0.0705 - val_accuracy: 0.9625\n    Epoch 36/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0057 - accuracy: 1.0000 - val_loss: 0.0723 - val_accuracy: 0.9750\n    Epoch 37/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0056 - accuracy: 1.0000 - val_loss: 0.0749 - val_accuracy: 0.9750\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.9764 - accuracy: 0.6708 - val_loss: 0.3257 - val_accuracy: 0.8875\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.5592 - accuracy: 0.8833 - val_loss: 0.1807 - val_accuracy: 0.9500\n    Epoch 3/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.2001 - accuracy: 0.9417 - val_loss: 0.1503 - val_accuracy: 0.9250\n    Epoch 4/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.1759 - accuracy: 0.9500 - val_loss: 0.1413 - val_accuracy: 0.9500\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0976 - accuracy: 0.9667 - val_loss: 0.0721 - val_accuracy: 0.9500\n    Epoch 6/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.1551 - accuracy: 0.9458 - val_loss: 0.0947 - val_accuracy: 0.9625\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1163 - accuracy: 0.9583 - val_loss: 0.1187 - val_accuracy: 0.9500\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0725 - accuracy: 0.9708 - val_loss: 0.2962 - val_accuracy: 0.9000\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0899 - accuracy: 0.9583 - val_loss: 0.0649 - val_accuracy: 0.9625\n    Epoch 10/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0609 - accuracy: 0.9833 - val_loss: 0.1690 - val_accuracy: 0.9500\n    Epoch 11/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0530 - accuracy: 0.9792 - val_loss: 0.0808 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0649 - accuracy: 0.9792 - val_loss: 0.0778 - val_accuracy: 0.9750\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0537 - accuracy: 0.9792 - val_loss: 0.1462 - val_accuracy: 0.9625\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0312 - accuracy: 0.9917 - val_loss: 0.0977 - val_accuracy: 0.9625\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0289 - accuracy: 1.0000 - val_loss: 0.1395 - val_accuracy: 0.9625\n    Epoch 16/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0236 - accuracy: 0.9917 - val_loss: 0.0788 - val_accuracy: 0.9750\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0228 - accuracy: 1.0000 - val_loss: 0.0845 - val_accuracy: 0.9625\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0308 - accuracy: 0.9958 - val_loss: 0.1259 - val_accuracy: 0.9500\n    Epoch 19/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0258 - accuracy: 0.9958 - val_loss: 0.0873 - val_accuracy: 0.9750\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0209 - accuracy: 1.0000 - val_loss: 0.0930 - val_accuracy: 0.9750\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0213 - accuracy: 1.0000 - val_loss: 0.0935 - val_accuracy: 0.9750\n    Epoch 22/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0154 - accuracy: 1.0000 - val_loss: 0.0931 - val_accuracy: 0.9750\n    Epoch 23/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0145 - accuracy: 1.0000 - val_loss: 0.0946 - val_accuracy: 0.9750\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0147 - accuracy: 1.0000 - val_loss: 0.0810 - val_accuracy: 0.9750\n    Epoch 25/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0136 - accuracy: 1.0000 - val_loss: 0.0852 - val_accuracy: 0.9750\n    Epoch 26/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0155 - accuracy: 1.0000 - val_loss: 0.1690 - val_accuracy: 0.9500\n    Epoch 27/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0243 - accuracy: 0.9875 - val_loss: 0.0768 - val_accuracy: 0.9625\n    Epoch 28/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0139 - accuracy: 1.0000 - val_loss: 0.0969 - val_accuracy: 0.9750\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0108 - accuracy: 1.0000 - val_loss: 0.0869 - val_accuracy: 0.9750\n    Epoch 30/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0104 - accuracy: 1.0000 - val_loss: 0.0889 - val_accuracy: 0.9625\n    Epoch 31/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0109 - accuracy: 1.0000 - val_loss: 0.0663 - val_accuracy: 0.9750\n    Epoch 32/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0107 - accuracy: 1.0000 - val_loss: 0.0603 - val_accuracy: 0.9750\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.7479 - accuracy: 0.6875 - val_loss: 0.8620 - val_accuracy: 0.8500\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.5508 - accuracy: 0.9000 - val_loss: 0.2412 - val_accuracy: 0.9500\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2072 - accuracy: 0.9292 - val_loss: 0.1486 - val_accuracy: 0.9625\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2024 - accuracy: 0.9333 - val_loss: 0.1142 - val_accuracy: 0.9375\n    Epoch 5/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.1382 - accuracy: 0.9458 - val_loss: 0.0845 - val_accuracy: 0.9500\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0994 - accuracy: 0.9667 - val_loss: 0.2779 - val_accuracy: 0.9000\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0794 - accuracy: 0.9750 - val_loss: 0.0711 - val_accuracy: 0.9750\n    Epoch 8/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0618 - accuracy: 0.9708 - val_loss: 0.0570 - val_accuracy: 0.9875\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0765 - accuracy: 0.9667 - val_loss: 0.0564 - val_accuracy: 0.9875\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0503 - accuracy: 0.9875 - val_loss: 0.0589 - val_accuracy: 0.9750\n    Epoch 11/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0539 - accuracy: 0.9792 - val_loss: 0.0406 - val_accuracy: 0.9875\n    Epoch 12/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0394 - accuracy: 0.9875 - val_loss: 0.0425 - val_accuracy: 0.9750\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0429 - accuracy: 0.9833 - val_loss: 0.1051 - val_accuracy: 0.9625\n    Epoch 14/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0263 - accuracy: 0.9958 - val_loss: 0.0509 - val_accuracy: 0.9750\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0294 - accuracy: 0.9958 - val_loss: 0.0579 - val_accuracy: 0.9750\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0323 - accuracy: 0.9958 - val_loss: 0.0391 - val_accuracy: 0.9875\n    Epoch 17/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0236 - accuracy: 0.9958 - val_loss: 0.0420 - val_accuracy: 0.9750\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0246 - accuracy: 1.0000 - val_loss: 0.0431 - val_accuracy: 0.9750\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0248 - accuracy: 1.0000 - val_loss: 0.0506 - val_accuracy: 0.9750\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0191 - accuracy: 1.0000 - val_loss: 0.0484 - val_accuracy: 0.9750\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0191 - accuracy: 1.0000 - val_loss: 0.0409 - val_accuracy: 0.9750\n    Epoch 22/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0204 - accuracy: 0.9958 - val_loss: 0.0554 - val_accuracy: 0.9875\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0217 - accuracy: 0.9917 - val_loss: 0.0423 - val_accuracy: 0.9875\n    Epoch 24/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0158 - accuracy: 1.0000 - val_loss: 0.0367 - val_accuracy: 0.9875\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0148 - accuracy: 1.0000 - val_loss: 0.0424 - val_accuracy: 0.9750\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0146 - accuracy: 1.0000 - val_loss: 0.0404 - val_accuracy: 0.9875\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0142 - accuracy: 1.0000 - val_loss: 0.0328 - val_accuracy: 0.9875\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0142 - accuracy: 1.0000 - val_loss: 0.0334 - val_accuracy: 0.9875\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.3138 - accuracy: 0.7125 - val_loss: 1.4244 - val_accuracy: 0.8250\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.4202 - accuracy: 0.8750 - val_loss: 1.0344 - val_accuracy: 0.8000\n    Epoch 3/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.3589 - accuracy: 0.9125 - val_loss: 0.8543 - val_accuracy: 0.8000\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1906 - accuracy: 0.9417 - val_loss: 0.3168 - val_accuracy: 0.9000\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0806 - accuracy: 0.9750 - val_loss: 0.3154 - val_accuracy: 0.9000\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0609 - accuracy: 0.9750 - val_loss: 0.2593 - val_accuracy: 0.9375\n    Epoch 7/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0633 - accuracy: 0.9833 - val_loss: 0.2370 - val_accuracy: 0.9375\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0639 - accuracy: 0.9833 - val_loss: 0.2566 - val_accuracy: 0.9250\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0508 - accuracy: 0.9875 - val_loss: 0.1678 - val_accuracy: 0.9125\n    Epoch 10/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0351 - accuracy: 0.9917 - val_loss: 0.1775 - val_accuracy: 0.9250\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0216 - accuracy: 0.9958 - val_loss: 0.2562 - val_accuracy: 0.9375\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0218 - accuracy: 0.9958 - val_loss: 0.1849 - val_accuracy: 0.9375\n    Epoch 13/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0187 - accuracy: 1.0000 - val_loss: 0.1960 - val_accuracy: 0.9000\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0190 - accuracy: 0.9958 - val_loss: 0.1552 - val_accuracy: 0.9500\n    Epoch 15/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0228 - accuracy: 0.9917 - val_loss: 0.1453 - val_accuracy: 0.9375\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0187 - accuracy: 1.0000 - val_loss: 0.1499 - val_accuracy: 0.9500\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0142 - accuracy: 1.0000 - val_loss: 0.1794 - val_accuracy: 0.9375\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0220 - accuracy: 0.9958 - val_loss: 0.1479 - val_accuracy: 0.9500\n    Epoch 19/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0116 - accuracy: 1.0000 - val_loss: 0.1989 - val_accuracy: 0.9250\n    Epoch 20/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0115 - accuracy: 1.0000 - val_loss: 0.1729 - val_accuracy: 0.9500\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0192 - accuracy: 0.9958 - val_loss: 0.1341 - val_accuracy: 0.9625\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0151 - accuracy: 1.0000 - val_loss: 0.1311 - val_accuracy: 0.9500\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0135 - accuracy: 1.0000 - val_loss: 0.1755 - val_accuracy: 0.9375\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0122 - accuracy: 0.9958 - val_loss: 0.1481 - val_accuracy: 0.9500\n    Epoch 25/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0090 - accuracy: 1.0000 - val_loss: 0.1760 - val_accuracy: 0.9375\n    Epoch 26/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0089 - accuracy: 1.0000 - val_loss: 0.1380 - val_accuracy: 0.9500\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0079 - accuracy: 1.0000 - val_loss: 0.1410 - val_accuracy: 0.9500\n    Epoch 28/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0086 - accuracy: 1.0000 - val_loss: 0.1568 - val_accuracy: 0.9250\n    Epoch 29/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0086 - accuracy: 1.0000 - val_loss: 0.1757 - val_accuracy: 0.9250\n    Epoch 30/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0079 - accuracy: 1.0000 - val_loss: 0.1408 - val_accuracy: 0.9500\n    Epoch 31/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0077 - accuracy: 1.0000 - val_loss: 0.1270 - val_accuracy: 0.9500\n    Epoch 32/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0078 - accuracy: 1.0000 - val_loss: 0.1436 - val_accuracy: 0.9375\n    Epoch 33/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0066 - accuracy: 1.0000 - val_loss: 0.1828 - val_accuracy: 0.9375\n    Epoch 34/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0087 - accuracy: 1.0000 - val_loss: 0.1552 - val_accuracy: 0.9375\n    Epoch 35/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0057 - accuracy: 1.0000 - val_loss: 0.1481 - val_accuracy: 0.9375\n    Epoch 36/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0056 - accuracy: 1.0000 - val_loss: 0.1572 - val_accuracy: 0.9375\n    Epoch 37/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0060 - accuracy: 1.0000 - val_loss: 0.1315 - val_accuracy: 0.9500\n    Epoch 38/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0067 - accuracy: 1.0000 - val_loss: 0.1210 - val_accuracy: 0.9625\n    Epoch 39/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0056 - accuracy: 1.0000 - val_loss: 0.1546 - val_accuracy: 0.9375\n    Epoch 40/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0063 - accuracy: 1.0000 - val_loss: 0.1351 - val_accuracy: 0.9500\n    Epoch 41/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0062 - accuracy: 1.0000 - val_loss: 0.1183 - val_accuracy: 0.9625\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.5419 - accuracy: 0.7500 - val_loss: 0.4428 - val_accuracy: 0.8875\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.4489 - accuracy: 0.8958 - val_loss: 0.6278 - val_accuracy: 0.8625\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1803 - accuracy: 0.9542 - val_loss: 0.2945 - val_accuracy: 0.9125\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1345 - accuracy: 0.9500 - val_loss: 0.2565 - val_accuracy: 0.9250\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1688 - accuracy: 0.9375 - val_loss: 0.2090 - val_accuracy: 0.9375\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0692 - accuracy: 0.9833 - val_loss: 0.2394 - val_accuracy: 0.9375\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0789 - accuracy: 0.9667 - val_loss: 0.2181 - val_accuracy: 0.9375\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0539 - accuracy: 0.9750 - val_loss: 0.2426 - val_accuracy: 0.9125\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0494 - accuracy: 0.9833 - val_loss: 0.1858 - val_accuracy: 0.9500\n    Epoch 10/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0351 - accuracy: 0.9958 - val_loss: 0.2119 - val_accuracy: 0.9250\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0391 - accuracy: 0.9833 - val_loss: 0.1906 - val_accuracy: 0.9500\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0263 - accuracy: 0.9958 - val_loss: 0.1938 - val_accuracy: 0.9375\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0308 - accuracy: 0.9917 - val_loss: 0.2225 - val_accuracy: 0.9125\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0234 - accuracy: 0.9958 - val_loss: 0.1867 - val_accuracy: 0.9500\n    Epoch 15/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0232 - accuracy: 0.9958 - val_loss: 0.1980 - val_accuracy: 0.9375\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0195 - accuracy: 1.0000 - val_loss: 0.1979 - val_accuracy: 0.9375\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0257 - accuracy: 0.9917 - val_loss: 0.1929 - val_accuracy: 0.9375\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0181 - accuracy: 1.0000 - val_loss: 0.2172 - val_accuracy: 0.9375\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0150 - accuracy: 1.0000 - val_loss: 0.1940 - val_accuracy: 0.9375\n    Epoch 20/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0166 - accuracy: 0.9958 - val_loss: 0.1894 - val_accuracy: 0.9375\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0152 - accuracy: 0.9958 - val_loss: 0.1852 - val_accuracy: 0.9375\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0153 - accuracy: 1.0000 - val_loss: 0.2231 - val_accuracy: 0.9375\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0120 - accuracy: 1.0000 - val_loss: 0.1881 - val_accuracy: 0.9625\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0131 - accuracy: 1.0000 - val_loss: 0.1771 - val_accuracy: 0.9625\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0112 - accuracy: 1.0000 - val_loss: 0.2012 - val_accuracy: 0.9500\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0131 - accuracy: 1.0000 - val_loss: 0.2119 - val_accuracy: 0.9375\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0099 - accuracy: 1.0000 - val_loss: 0.1824 - val_accuracy: 0.9500\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0095 - accuracy: 1.0000 - val_loss: 0.1840 - val_accuracy: 0.9625\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0093 - accuracy: 1.0000 - val_loss: 0.1873 - val_accuracy: 0.9500\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0097 - accuracy: 1.0000 - val_loss: 0.1910 - val_accuracy: 0.9375\n    Epoch 31/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0115 - accuracy: 1.0000 - val_loss: 0.2198 - val_accuracy: 0.9375\n    Epoch 32/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0114 - accuracy: 1.0000 - val_loss: 0.2010 - val_accuracy: 0.9375\n    Epoch 33/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0072 - accuracy: 1.0000 - val_loss: 0.1976 - val_accuracy: 0.9625\n    Epoch 34/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0072 - accuracy: 1.0000 - val_loss: 0.2250 - val_accuracy: 0.9375\n    Epoch 35/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0088 - accuracy: 1.0000 - val_loss: 0.1907 - val_accuracy: 0.9625\n    Epoch 36/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0079 - accuracy: 1.0000 - val_loss: 0.2271 - val_accuracy: 0.9375\n    Epoch 37/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0083 - accuracy: 1.0000 - val_loss: 0.1997 - val_accuracy: 0.9375\n    Epoch 38/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0082 - accuracy: 1.0000 - val_loss: 0.2119 - val_accuracy: 0.9500\n    Epoch 39/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0063 - accuracy: 1.0000 - val_loss: 0.2249 - val_accuracy: 0.9375\n    Epoch 40/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0063 - accuracy: 1.0000 - val_loss: 0.2173 - val_accuracy: 0.9500\n    Epoch 41/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0054 - accuracy: 1.0000 - val_loss: 0.1855 - val_accuracy: 0.9625\n    Epoch 42/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0076 - accuracy: 1.0000 - val_loss: 0.1961 - val_accuracy: 0.9500\n    Epoch 43/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0051 - accuracy: 1.0000 - val_loss: 0.1894 - val_accuracy: 0.9625\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.7218 - accuracy: 0.7292 - val_loss: 0.6023 - val_accuracy: 0.8500\n    Epoch 2/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.3979 - accuracy: 0.8917 - val_loss: 0.4439 - val_accuracy: 0.8625\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1480 - accuracy: 0.9583 - val_loss: 0.3890 - val_accuracy: 0.8625\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1453 - accuracy: 0.9667 - val_loss: 0.1606 - val_accuracy: 0.9500\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1143 - accuracy: 0.9583 - val_loss: 0.1152 - val_accuracy: 0.9625\n    Epoch 6/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0808 - accuracy: 0.9667 - val_loss: 0.1729 - val_accuracy: 0.9500\n    Epoch 7/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.1094 - accuracy: 0.9667 - val_loss: 0.1322 - val_accuracy: 0.9625\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0522 - accuracy: 0.9917 - val_loss: 0.1947 - val_accuracy: 0.9375\n    Epoch 9/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0597 - accuracy: 0.9833 - val_loss: 0.1789 - val_accuracy: 0.9500\n    Epoch 10/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0598 - accuracy: 0.9750 - val_loss: 0.1459 - val_accuracy: 0.9375\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0432 - accuracy: 0.9833 - val_loss: 0.1269 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0285 - accuracy: 0.9917 - val_loss: 0.1624 - val_accuracy: 0.9375\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0568 - accuracy: 0.9833 - val_loss: 0.0957 - val_accuracy: 0.9625\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0309 - accuracy: 0.9917 - val_loss: 0.1064 - val_accuracy: 0.9625\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0333 - accuracy: 0.9917 - val_loss: 0.1007 - val_accuracy: 0.9750\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0240 - accuracy: 0.9958 - val_loss: 0.1346 - val_accuracy: 0.9375\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0237 - accuracy: 0.9917 - val_loss: 0.1271 - val_accuracy: 0.9375\n    Epoch 18/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0241 - accuracy: 1.0000 - val_loss: 0.1266 - val_accuracy: 0.9375\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0177 - accuracy: 0.9958 - val_loss: 0.0876 - val_accuracy: 0.9625\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0179 - accuracy: 1.0000 - val_loss: 0.0932 - val_accuracy: 0.9625\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0210 - accuracy: 1.0000 - val_loss: 0.1005 - val_accuracy: 0.9750\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0354 - accuracy: 0.9833 - val_loss: 0.1615 - val_accuracy: 0.9250\n    Epoch 23/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0164 - accuracy: 1.0000 - val_loss: 0.1221 - val_accuracy: 0.9625\n    Epoch 24/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0128 - accuracy: 1.0000 - val_loss: 0.1126 - val_accuracy: 0.9625\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0149 - accuracy: 0.9958 - val_loss: 0.1314 - val_accuracy: 0.9500\n    Epoch 26/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0100 - accuracy: 1.0000 - val_loss: 0.1350 - val_accuracy: 0.9625\n    Epoch 27/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0116 - accuracy: 1.0000 - val_loss: 0.1047 - val_accuracy: 0.9625\n    Epoch 28/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0145 - accuracy: 1.0000 - val_loss: 0.1065 - val_accuracy: 0.9625\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0103 - accuracy: 1.0000 - val_loss: 0.0897 - val_accuracy: 0.9625\n    Epoch 30/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0091 - accuracy: 1.0000 - val_loss: 0.0978 - val_accuracy: 0.9625\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0080 - accuracy: 1.0000 - val_loss: 0.1106 - val_accuracy: 0.9625\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0116 - accuracy: 1.0000 - val_loss: 0.1033 - val_accuracy: 0.9625\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0098 - accuracy: 1.0000 - val_loss: 0.1039 - val_accuracy: 0.9625\n    Epoch 34/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0074 - accuracy: 1.0000 - val_loss: 0.0980 - val_accuracy: 0.9625\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0099 - accuracy: 1.0000 - val_loss: 0.1055 - val_accuracy: 0.9625\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.3683 - accuracy: 0.7417 - val_loss: 0.8600 - val_accuracy: 0.8125\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.4475 - accuracy: 0.8958 - val_loss: 0.2346 - val_accuracy: 0.9250\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1724 - accuracy: 0.9458 - val_loss: 0.1573 - val_accuracy: 0.9500\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1410 - accuracy: 0.9500 - val_loss: 0.0769 - val_accuracy: 0.9625\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1123 - accuracy: 0.9458 - val_loss: 0.2284 - val_accuracy: 0.9250\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0973 - accuracy: 0.9667 - val_loss: 0.2016 - val_accuracy: 0.9375\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0587 - accuracy: 0.9708 - val_loss: 0.0776 - val_accuracy: 0.9750\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0414 - accuracy: 0.9917 - val_loss: 0.1066 - val_accuracy: 0.9625\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0521 - accuracy: 0.9792 - val_loss: 0.0602 - val_accuracy: 0.9875\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0572 - accuracy: 0.9792 - val_loss: 0.0956 - val_accuracy: 0.9625\n    Epoch 11/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0411 - accuracy: 0.9917 - val_loss: 0.0893 - val_accuracy: 0.9750\n    Epoch 12/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0325 - accuracy: 0.9875 - val_loss: 0.1074 - val_accuracy: 0.9750\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0255 - accuracy: 1.0000 - val_loss: 0.1910 - val_accuracy: 0.9375\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0295 - accuracy: 1.0000 - val_loss: 0.1047 - val_accuracy: 0.9625\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0304 - accuracy: 0.9917 - val_loss: 0.0610 - val_accuracy: 0.9750\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0366 - accuracy: 0.9875 - val_loss: 0.1565 - val_accuracy: 0.9375\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0312 - accuracy: 0.9875 - val_loss: 0.1345 - val_accuracy: 0.9500\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0219 - accuracy: 1.0000 - val_loss: 0.1047 - val_accuracy: 0.9750\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0140 - accuracy: 1.0000 - val_loss: 0.0651 - val_accuracy: 0.9875\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0257 - accuracy: 0.9958 - val_loss: 0.0996 - val_accuracy: 0.9750\n    Epoch 21/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0179 - accuracy: 1.0000 - val_loss: 0.0572 - val_accuracy: 0.9875\n    Epoch 22/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0275 - accuracy: 0.9958 - val_loss: 0.0534 - val_accuracy: 0.9875\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0199 - accuracy: 0.9958 - val_loss: 0.0632 - val_accuracy: 0.9875\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0188 - accuracy: 0.9958 - val_loss: 0.0676 - val_accuracy: 0.9875\n    Epoch 25/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0118 - accuracy: 1.0000 - val_loss: 0.0894 - val_accuracy: 0.9750\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0124 - accuracy: 1.0000 - val_loss: 0.0678 - val_accuracy: 0.9875\n    Epoch 27/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0119 - accuracy: 1.0000 - val_loss: 0.1123 - val_accuracy: 0.9750\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0089 - accuracy: 1.0000 - val_loss: 0.0613 - val_accuracy: 0.9875\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0081 - accuracy: 1.0000 - val_loss: 0.0832 - val_accuracy: 0.9875\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.1398 - accuracy: 0.7792 - val_loss: 0.9325 - val_accuracy: 0.7625\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3164 - accuracy: 0.9000 - val_loss: 0.4410 - val_accuracy: 0.9000\n    Epoch 3/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.2120 - accuracy: 0.9250 - val_loss: 0.5880 - val_accuracy: 0.8375\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1149 - accuracy: 0.9667 - val_loss: 0.2647 - val_accuracy: 0.9250\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1067 - accuracy: 0.9417 - val_loss: 0.2661 - val_accuracy: 0.9125\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0491 - accuracy: 0.9792 - val_loss: 0.2772 - val_accuracy: 0.9250\n    Epoch 7/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0621 - accuracy: 0.9875 - val_loss: 0.2903 - val_accuracy: 0.9000\n    Epoch 8/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0963 - accuracy: 0.9542 - val_loss: 0.4055 - val_accuracy: 0.9250\n    Epoch 9/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0325 - accuracy: 0.9917 - val_loss: 0.3198 - val_accuracy: 0.9250\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0240 - accuracy: 0.9917 - val_loss: 0.2472 - val_accuracy: 0.9500\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0190 - accuracy: 0.9917 - val_loss: 0.2674 - val_accuracy: 0.9375\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0170 - accuracy: 0.9917 - val_loss: 0.2497 - val_accuracy: 0.9500\n    Epoch 13/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0116 - accuracy: 1.0000 - val_loss: 0.2762 - val_accuracy: 0.9375\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0117 - accuracy: 1.0000 - val_loss: 0.2690 - val_accuracy: 0.9375\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0124 - accuracy: 1.0000 - val_loss: 0.2515 - val_accuracy: 0.9375\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0103 - accuracy: 1.0000 - val_loss: 0.2577 - val_accuracy: 0.9375\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0079 - accuracy: 1.0000 - val_loss: 0.2466 - val_accuracy: 0.9500\n    Epoch 18/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0090 - accuracy: 1.0000 - val_loss: 0.2575 - val_accuracy: 0.9375\n    Epoch 19/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0082 - accuracy: 1.0000 - val_loss: 0.2460 - val_accuracy: 0.9500\n    Epoch 20/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0080 - accuracy: 1.0000 - val_loss: 0.2716 - val_accuracy: 0.9375\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0080 - accuracy: 1.0000 - val_loss: 0.2698 - val_accuracy: 0.9250\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0075 - accuracy: 1.0000 - val_loss: 0.2747 - val_accuracy: 0.9250\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0074 - accuracy: 1.0000 - val_loss: 0.2391 - val_accuracy: 0.9500\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0069 - accuracy: 1.0000 - val_loss: 0.2371 - val_accuracy: 0.9500\n    Epoch 25/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0058 - accuracy: 1.0000 - val_loss: 0.2219 - val_accuracy: 0.9500\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0070 - accuracy: 1.0000 - val_loss: 0.2613 - val_accuracy: 0.9375\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0061 - accuracy: 1.0000 - val_loss: 0.2550 - val_accuracy: 0.9375\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0052 - accuracy: 1.0000 - val_loss: 0.2486 - val_accuracy: 0.9375\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0049 - accuracy: 1.0000 - val_loss: 0.2550 - val_accuracy: 0.9375\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0049 - accuracy: 1.0000 - val_loss: 0.2338 - val_accuracy: 0.9500\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.3006 - accuracy: 0.7792 - val_loss: 1.1098 - val_accuracy: 0.8750\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.4041 - accuracy: 0.8833 - val_loss: 0.3697 - val_accuracy: 0.9000\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2520 - accuracy: 0.9042 - val_loss: 0.2367 - val_accuracy: 0.9125\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1279 - accuracy: 0.9500 - val_loss: 0.0751 - val_accuracy: 0.9875\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0875 - accuracy: 0.9708 - val_loss: 0.0583 - val_accuracy: 0.9875\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0684 - accuracy: 0.9833 - val_loss: 0.0601 - val_accuracy: 1.0000\n    Epoch 7/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0601 - accuracy: 0.9792 - val_loss: 0.0484 - val_accuracy: 1.0000\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0476 - accuracy: 0.9875 - val_loss: 0.0525 - val_accuracy: 0.9875\n    Epoch 9/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0670 - accuracy: 0.9833 - val_loss: 0.0706 - val_accuracy: 0.9500\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0526 - accuracy: 0.9875 - val_loss: 0.0531 - val_accuracy: 1.0000\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0378 - accuracy: 0.9875 - val_loss: 0.1202 - val_accuracy: 0.9500\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0385 - accuracy: 0.9917 - val_loss: 0.0546 - val_accuracy: 0.9750\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0240 - accuracy: 0.9917 - val_loss: 0.0537 - val_accuracy: 1.0000\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0270 - accuracy: 0.9958 - val_loss: 0.0393 - val_accuracy: 1.0000\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0401 - accuracy: 0.9833 - val_loss: 0.0424 - val_accuracy: 0.9875\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0214 - accuracy: 0.9958 - val_loss: 0.0353 - val_accuracy: 1.0000\n    Epoch 17/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0343 - accuracy: 0.9917 - val_loss: 0.0270 - val_accuracy: 1.0000\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0366 - accuracy: 0.9917 - val_loss: 0.0210 - val_accuracy: 1.0000\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0222 - accuracy: 0.9917 - val_loss: 0.0310 - val_accuracy: 1.0000\n    Epoch 20/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0176 - accuracy: 1.0000 - val_loss: 0.0432 - val_accuracy: 1.0000\n    Epoch 21/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0154 - accuracy: 1.0000 - val_loss: 0.0283 - val_accuracy: 1.0000\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0137 - accuracy: 1.0000 - val_loss: 0.0260 - val_accuracy: 1.0000\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0143 - accuracy: 1.0000 - val_loss: 0.0236 - val_accuracy: 1.0000\n    Epoch 24/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0119 - accuracy: 1.0000 - val_loss: 0.0258 - val_accuracy: 1.0000\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0112 - accuracy: 1.0000 - val_loss: 0.0229 - val_accuracy: 1.0000\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0122 - accuracy: 1.0000 - val_loss: 0.0203 - val_accuracy: 1.0000\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 0.7389 - accuracy: 0.8000 - val_loss: 0.4972 - val_accuracy: 0.9125\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1674 - accuracy: 0.9417 - val_loss: 0.3965 - val_accuracy: 0.8500\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1339 - accuracy: 0.9625 - val_loss: 0.2103 - val_accuracy: 0.9750\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0729 - accuracy: 0.9833 - val_loss: 0.2148 - val_accuracy: 0.9750\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0873 - accuracy: 0.9750 - val_loss: 0.2186 - val_accuracy: 0.9625\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0666 - accuracy: 0.9792 - val_loss: 0.1594 - val_accuracy: 0.9125\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0582 - accuracy: 0.9750 - val_loss: 0.2143 - val_accuracy: 0.9375\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0496 - accuracy: 0.9792 - val_loss: 0.1902 - val_accuracy: 0.9500\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0529 - accuracy: 0.9833 - val_loss: 0.1700 - val_accuracy: 0.9500\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0558 - accuracy: 0.9750 - val_loss: 0.2541 - val_accuracy: 0.9375\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0399 - accuracy: 0.9875 - val_loss: 0.1879 - val_accuracy: 0.9750\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0292 - accuracy: 0.9917 - val_loss: 0.1956 - val_accuracy: 0.9500\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0264 - accuracy: 1.0000 - val_loss: 0.1400 - val_accuracy: 0.9375\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0296 - accuracy: 0.9958 - val_loss: 0.1676 - val_accuracy: 0.9625\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0351 - accuracy: 0.9917 - val_loss: 0.1501 - val_accuracy: 0.9500\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0236 - accuracy: 0.9958 - val_loss: 0.1607 - val_accuracy: 0.9750\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0273 - accuracy: 0.9917 - val_loss: 0.2108 - val_accuracy: 0.9500\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0191 - accuracy: 1.0000 - val_loss: 0.1936 - val_accuracy: 0.9375\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0216 - accuracy: 1.0000 - val_loss: 0.1658 - val_accuracy: 0.9500\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0166 - accuracy: 1.0000 - val_loss: 0.1602 - val_accuracy: 0.9625\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0173 - accuracy: 1.0000 - val_loss: 0.1887 - val_accuracy: 0.9625\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0151 - accuracy: 1.0000 - val_loss: 0.2267 - val_accuracy: 0.9625\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0170 - accuracy: 1.0000 - val_loss: 0.1818 - val_accuracy: 0.9625\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 0.5559 - accuracy: 0.8125 - val_loss: 0.1482 - val_accuracy: 0.9625\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2193 - accuracy: 0.9375 - val_loss: 0.0999 - val_accuracy: 0.9500\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0720 - accuracy: 0.9875 - val_loss: 0.1502 - val_accuracy: 0.9500\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0658 - accuracy: 0.9792 - val_loss: 0.1389 - val_accuracy: 0.9500\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0538 - accuracy: 0.9833 - val_loss: 0.1669 - val_accuracy: 0.9375\n    Epoch 6/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0562 - accuracy: 0.9917 - val_loss: 0.0952 - val_accuracy: 0.9625\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0685 - accuracy: 0.9875 - val_loss: 0.1447 - val_accuracy: 0.9250\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0451 - accuracy: 0.9917 - val_loss: 0.1431 - val_accuracy: 0.9500\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0314 - accuracy: 0.9958 - val_loss: 0.1593 - val_accuracy: 0.9375\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0434 - accuracy: 0.9875 - val_loss: 0.1069 - val_accuracy: 0.9375\n    Epoch 11/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0325 - accuracy: 0.9917 - val_loss: 0.1342 - val_accuracy: 0.9500\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0394 - accuracy: 0.9917 - val_loss: 0.1281 - val_accuracy: 0.9500\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0324 - accuracy: 0.9875 - val_loss: 0.1444 - val_accuracy: 0.9375\n    Epoch 14/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0230 - accuracy: 1.0000 - val_loss: 0.1078 - val_accuracy: 0.9500\n    Epoch 15/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0221 - accuracy: 0.9958 - val_loss: 0.1057 - val_accuracy: 0.9500\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0200 - accuracy: 0.9958 - val_loss: 0.1017 - val_accuracy: 0.9500\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0256 - accuracy: 0.9958 - val_loss: 0.1112 - val_accuracy: 0.9625\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0195 - accuracy: 1.0000 - val_loss: 0.1024 - val_accuracy: 0.9625\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0185 - accuracy: 1.0000 - val_loss: 0.1272 - val_accuracy: 0.9500\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0154 - accuracy: 1.0000 - val_loss: 0.1124 - val_accuracy: 0.9625\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0140 - accuracy: 1.0000 - val_loss: 0.1097 - val_accuracy: 0.9625\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 0.8522 - accuracy: 0.7583 - val_loss: 0.3349 - val_accuracy: 0.9375\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2455 - accuracy: 0.9000 - val_loss: 0.1289 - val_accuracy: 0.9500\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1126 - accuracy: 0.9417 - val_loss: 0.1979 - val_accuracy: 0.9500\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0716 - accuracy: 0.9708 - val_loss: 0.1468 - val_accuracy: 0.9625\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0559 - accuracy: 0.9792 - val_loss: 0.1212 - val_accuracy: 0.9750\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0541 - accuracy: 0.9875 - val_loss: 0.1442 - val_accuracy: 0.9625\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0496 - accuracy: 0.9750 - val_loss: 0.2015 - val_accuracy: 0.9625\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0432 - accuracy: 0.9875 - val_loss: 0.1660 - val_accuracy: 0.9625\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0588 - accuracy: 0.9667 - val_loss: 0.1698 - val_accuracy: 0.9625\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0316 - accuracy: 0.9958 - val_loss: 0.1351 - val_accuracy: 0.9750\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0588 - accuracy: 0.9750 - val_loss: 0.2019 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0273 - accuracy: 0.9917 - val_loss: 0.1176 - val_accuracy: 0.9750\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0249 - accuracy: 0.9958 - val_loss: 0.1930 - val_accuracy: 0.9625\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0300 - accuracy: 0.9875 - val_loss: 0.1959 - val_accuracy: 0.9500\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0204 - accuracy: 0.9958 - val_loss: 0.1306 - val_accuracy: 0.9750\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0248 - accuracy: 0.9958 - val_loss: 0.2008 - val_accuracy: 0.9625\n    Epoch 17/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0243 - accuracy: 0.9958 - val_loss: 0.1395 - val_accuracy: 0.9750\n    Epoch 18/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0175 - accuracy: 1.0000 - val_loss: 0.1604 - val_accuracy: 0.9625\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0221 - accuracy: 0.9958 - val_loss: 0.1830 - val_accuracy: 0.9625\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0158 - accuracy: 1.0000 - val_loss: 0.1642 - val_accuracy: 0.9625\n    Epoch 21/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0162 - accuracy: 1.0000 - val_loss: 0.1952 - val_accuracy: 0.9625\n    Epoch 22/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0227 - accuracy: 0.9958 - val_loss: 0.1592 - val_accuracy: 0.9625\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0205 - accuracy: 1.0000 - val_loss: 0.1997 - val_accuracy: 0.9625\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0199 - accuracy: 0.9958 - val_loss: 0.1542 - val_accuracy: 0.9625\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0134 - accuracy: 1.0000 - val_loss: 0.1373 - val_accuracy: 0.9750\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.0457 - accuracy: 0.7375 - val_loss: 0.4658 - val_accuracy: 0.8625\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1969 - accuracy: 0.9417 - val_loss: 0.2999 - val_accuracy: 0.9125\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1626 - accuracy: 0.9500 - val_loss: 0.2493 - val_accuracy: 0.9125\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1082 - accuracy: 0.9625 - val_loss: 0.1970 - val_accuracy: 0.9250\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0654 - accuracy: 0.9875 - val_loss: 0.1138 - val_accuracy: 0.9625\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0568 - accuracy: 0.9750 - val_loss: 0.0975 - val_accuracy: 0.9625\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0495 - accuracy: 0.9833 - val_loss: 0.1350 - val_accuracy: 0.9500\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0506 - accuracy: 0.9917 - val_loss: 0.0921 - val_accuracy: 0.9625\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0378 - accuracy: 0.9875 - val_loss: 0.1765 - val_accuracy: 0.9500\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0432 - accuracy: 0.9875 - val_loss: 0.1089 - val_accuracy: 0.9500\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0448 - accuracy: 0.9875 - val_loss: 0.1110 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0349 - accuracy: 0.9917 - val_loss: 0.1158 - val_accuracy: 0.9625\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0464 - accuracy: 0.9833 - val_loss: 0.1867 - val_accuracy: 0.9375\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0438 - accuracy: 0.9917 - val_loss: 0.1036 - val_accuracy: 0.9750\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0314 - accuracy: 0.9917 - val_loss: 0.0817 - val_accuracy: 0.9625\n    Epoch 16/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0251 - accuracy: 0.9958 - val_loss: 0.0883 - val_accuracy: 0.9625\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0247 - accuracy: 0.9958 - val_loss: 0.0863 - val_accuracy: 0.9750\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0264 - accuracy: 0.9917 - val_loss: 0.1288 - val_accuracy: 0.9625\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0289 - accuracy: 1.0000 - val_loss: 0.0817 - val_accuracy: 0.9625\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0220 - accuracy: 0.9958 - val_loss: 0.1425 - val_accuracy: 0.9500\n    Epoch 21/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0215 - accuracy: 0.9958 - val_loss: 0.1033 - val_accuracy: 0.9625\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0175 - accuracy: 1.0000 - val_loss: 0.0811 - val_accuracy: 0.9750\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0205 - accuracy: 0.9917 - val_loss: 0.1235 - val_accuracy: 0.9625\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0222 - accuracy: 1.0000 - val_loss: 0.0975 - val_accuracy: 0.9625\n    Epoch 25/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0209 - accuracy: 0.9917 - val_loss: 0.0731 - val_accuracy: 0.9750\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0170 - accuracy: 1.0000 - val_loss: 0.1103 - val_accuracy: 0.9750\n    Epoch 27/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0166 - accuracy: 1.0000 - val_loss: 0.1001 - val_accuracy: 0.9750\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0120 - accuracy: 1.0000 - val_loss: 0.0966 - val_accuracy: 0.9750\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0175 - accuracy: 0.9958 - val_loss: 0.1155 - val_accuracy: 0.9625\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0126 - accuracy: 1.0000 - val_loss: 0.0842 - val_accuracy: 0.9750\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0098 - accuracy: 1.0000 - val_loss: 0.0812 - val_accuracy: 0.9750\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0122 - accuracy: 1.0000 - val_loss: 0.0769 - val_accuracy: 0.9750\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0092 - accuracy: 1.0000 - val_loss: 0.0735 - val_accuracy: 0.9750\n    Epoch 34/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0152 - accuracy: 0.9958 - val_loss: 0.0891 - val_accuracy: 0.9625\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 0.5283 - accuracy: 0.7917 - val_loss: 0.2870 - val_accuracy: 0.8750\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3227 - accuracy: 0.9083 - val_loss: 0.1166 - val_accuracy: 0.9375\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1248 - accuracy: 0.9542 - val_loss: 0.1774 - val_accuracy: 0.9250\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1096 - accuracy: 0.9583 - val_loss: 0.1257 - val_accuracy: 0.9625\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0870 - accuracy: 0.9667 - val_loss: 0.0913 - val_accuracy: 0.9625\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0614 - accuracy: 0.9750 - val_loss: 0.0888 - val_accuracy: 0.9875\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0583 - accuracy: 0.9833 - val_loss: 0.0700 - val_accuracy: 0.9875\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0480 - accuracy: 0.9833 - val_loss: 0.1129 - val_accuracy: 0.9625\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0707 - accuracy: 0.9792 - val_loss: 0.0556 - val_accuracy: 0.9875\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0556 - accuracy: 0.9875 - val_loss: 0.0706 - val_accuracy: 0.9750\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0431 - accuracy: 0.9833 - val_loss: 0.0515 - val_accuracy: 0.9875\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0418 - accuracy: 0.9833 - val_loss: 0.1047 - val_accuracy: 0.9500\n    Epoch 13/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0350 - accuracy: 0.9917 - val_loss: 0.0583 - val_accuracy: 0.9875\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0284 - accuracy: 0.9917 - val_loss: 0.0544 - val_accuracy: 0.9875\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0388 - accuracy: 0.9792 - val_loss: 0.0757 - val_accuracy: 0.9625\n    Epoch 16/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0296 - accuracy: 0.9958 - val_loss: 0.0455 - val_accuracy: 0.9875\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0265 - accuracy: 0.9917 - val_loss: 0.0402 - val_accuracy: 0.9875\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0198 - accuracy: 1.0000 - val_loss: 0.0517 - val_accuracy: 0.9875\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0212 - accuracy: 0.9958 - val_loss: 0.0468 - val_accuracy: 0.9875\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0477 - accuracy: 0.9875 - val_loss: 0.0327 - val_accuracy: 0.9875\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0234 - accuracy: 0.9958 - val_loss: 0.0349 - val_accuracy: 0.9875\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0182 - accuracy: 0.9958 - val_loss: 0.0518 - val_accuracy: 0.9875\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0231 - accuracy: 0.9958 - val_loss: 0.0506 - val_accuracy: 0.9875\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0160 - accuracy: 1.0000 - val_loss: 0.0404 - val_accuracy: 0.9875\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0230 - accuracy: 1.0000 - val_loss: 0.0464 - val_accuracy: 0.9875\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0150 - accuracy: 1.0000 - val_loss: 0.0342 - val_accuracy: 1.0000\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0142 - accuracy: 1.0000 - val_loss: 0.0306 - val_accuracy: 0.9875\n    Epoch 28/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0204 - accuracy: 1.0000 - val_loss: 0.0647 - val_accuracy: 0.9500\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0176 - accuracy: 1.0000 - val_loss: 0.0329 - val_accuracy: 0.9875\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0128 - accuracy: 1.0000 - val_loss: 0.0266 - val_accuracy: 1.0000\n    Epoch 31/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0150 - accuracy: 1.0000 - val_loss: 0.0325 - val_accuracy: 0.9875\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0164 - accuracy: 1.0000 - val_loss: 0.0386 - val_accuracy: 0.9875\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0200 - accuracy: 0.9958 - val_loss: 0.0341 - val_accuracy: 0.9875\n    Epoch 34/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0129 - accuracy: 1.0000 - val_loss: 0.0361 - val_accuracy: 0.9875\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0125 - accuracy: 1.0000 - val_loss: 0.0413 - val_accuracy: 0.9750\n    Epoch 36/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0126 - accuracy: 1.0000 - val_loss: 0.0316 - val_accuracy: 0.9875\n    Epoch 37/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0124 - accuracy: 1.0000 - val_loss: 0.0421 - val_accuracy: 0.9875\n    Epoch 38/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0159 - accuracy: 1.0000 - val_loss: 0.0394 - val_accuracy: 0.9875\n    Epoch 39/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0115 - accuracy: 1.0000 - val_loss: 0.0354 - val_accuracy: 0.9875\n    Epoch 40/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0109 - accuracy: 1.0000 - val_loss: 0.0339 - val_accuracy: 0.9875\n    Epoch 41/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0080 - accuracy: 1.0000 - val_loss: 0.0460 - val_accuracy: 0.9625\n    Epoch 42/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0103 - accuracy: 1.0000 - val_loss: 0.0322 - val_accuracy: 0.9875\n    Epoch 43/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0078 - accuracy: 1.0000 - val_loss: 0.0269 - val_accuracy: 1.0000\n    Epoch 44/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0076 - accuracy: 1.0000 - val_loss: 0.0405 - val_accuracy: 0.9875\n    Epoch 45/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0075 - accuracy: 1.0000 - val_loss: 0.0370 - val_accuracy: 0.9875\n    Epoch 46/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0093 - accuracy: 1.0000 - val_loss: 0.0286 - val_accuracy: 1.0000\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 0.7148 - accuracy: 0.7958 - val_loss: 0.3343 - val_accuracy: 0.9000\n    Epoch 2/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.1688 - accuracy: 0.9375 - val_loss: 0.3395 - val_accuracy: 0.8750\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1239 - accuracy: 0.9625 - val_loss: 0.1714 - val_accuracy: 0.9500\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0853 - accuracy: 0.9792 - val_loss: 0.1579 - val_accuracy: 0.9500\n    Epoch 5/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0605 - accuracy: 0.9833 - val_loss: 0.2014 - val_accuracy: 0.9250\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0722 - accuracy: 0.9833 - val_loss: 0.2077 - val_accuracy: 0.9250\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0672 - accuracy: 0.9833 - val_loss: 0.1474 - val_accuracy: 0.9625\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0481 - accuracy: 0.9875 - val_loss: 0.2226 - val_accuracy: 0.9250\n    Epoch 9/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0407 - accuracy: 0.9917 - val_loss: 0.1810 - val_accuracy: 0.9500\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0319 - accuracy: 0.9917 - val_loss: 0.1377 - val_accuracy: 0.9625\n    Epoch 11/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0364 - accuracy: 0.9917 - val_loss: 0.1731 - val_accuracy: 0.9375\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0336 - accuracy: 0.9958 - val_loss: 0.1826 - val_accuracy: 0.9125\n    Epoch 13/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0309 - accuracy: 0.9958 - val_loss: 0.1608 - val_accuracy: 0.9625\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0380 - accuracy: 0.9917 - val_loss: 0.2491 - val_accuracy: 0.9125\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0295 - accuracy: 0.9917 - val_loss: 0.1757 - val_accuracy: 0.9500\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0219 - accuracy: 1.0000 - val_loss: 0.1678 - val_accuracy: 0.9625\n    Epoch 17/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0204 - accuracy: 0.9958 - val_loss: 0.1431 - val_accuracy: 0.9625\n    Epoch 18/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0217 - accuracy: 0.9958 - val_loss: 0.1517 - val_accuracy: 0.9500\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0239 - accuracy: 1.0000 - val_loss: 0.1717 - val_accuracy: 0.9375\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0216 - accuracy: 0.9958 - val_loss: 0.1540 - val_accuracy: 0.9500\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0188 - accuracy: 0.9958 - val_loss: 0.1795 - val_accuracy: 0.9500\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0243 - accuracy: 0.9917 - val_loss: 0.1856 - val_accuracy: 0.9500\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0310 - accuracy: 0.9917 - val_loss: 0.1464 - val_accuracy: 0.9625\n    Epoch 24/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0244 - accuracy: 0.9958 - val_loss: 0.1552 - val_accuracy: 0.9625\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0183 - accuracy: 0.9958 - val_loss: 0.1671 - val_accuracy: 0.9625\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0155 - accuracy: 1.0000 - val_loss: 0.1752 - val_accuracy: 0.9375\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0119 - accuracy: 1.0000 - val_loss: 0.1802 - val_accuracy: 0.9375\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 0.8720 - accuracy: 0.7250 - val_loss: 0.0830 - val_accuracy: 0.9750\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2496 - accuracy: 0.9292 - val_loss: 0.2543 - val_accuracy: 0.9625\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1106 - accuracy: 0.9667 - val_loss: 0.2020 - val_accuracy: 0.9750\n    Epoch 4/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0923 - accuracy: 0.9708 - val_loss: 0.2674 - val_accuracy: 0.9625\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0658 - accuracy: 0.9792 - val_loss: 0.1997 - val_accuracy: 0.9500\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1023 - accuracy: 0.9542 - val_loss: 0.2704 - val_accuracy: 0.9250\n    Epoch 7/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0379 - accuracy: 1.0000 - val_loss: 0.2346 - val_accuracy: 0.9500\n    Epoch 8/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0539 - accuracy: 0.9792 - val_loss: 0.2610 - val_accuracy: 0.9625\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0487 - accuracy: 0.9833 - val_loss: 0.2215 - val_accuracy: 0.9625\n    Epoch 10/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0429 - accuracy: 0.9875 - val_loss: 0.2297 - val_accuracy: 0.9375\n    Epoch 11/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0467 - accuracy: 0.9833 - val_loss: 0.1808 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0355 - accuracy: 0.9875 - val_loss: 0.2179 - val_accuracy: 0.9500\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0329 - accuracy: 0.9917 - val_loss: 0.2092 - val_accuracy: 0.9625\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0362 - accuracy: 0.9958 - val_loss: 0.2156 - val_accuracy: 0.9500\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0348 - accuracy: 0.9875 - val_loss: 0.1879 - val_accuracy: 0.9625\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0268 - accuracy: 0.9958 - val_loss: 0.2302 - val_accuracy: 0.9625\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0310 - accuracy: 1.0000 - val_loss: 0.1938 - val_accuracy: 0.9750\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0278 - accuracy: 0.9917 - val_loss: 0.2098 - val_accuracy: 0.9625\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0382 - accuracy: 0.9875 - val_loss: 0.1741 - val_accuracy: 0.9500\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0223 - accuracy: 0.9958 - val_loss: 0.2093 - val_accuracy: 0.9500\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0237 - accuracy: 1.0000 - val_loss: 0.1744 - val_accuracy: 0.9500\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 0.6940 - accuracy: 0.7958 - val_loss: 0.1901 - val_accuracy: 0.9250\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2593 - accuracy: 0.9292 - val_loss: 0.1463 - val_accuracy: 0.9500\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1701 - accuracy: 0.9458 - val_loss: 0.1768 - val_accuracy: 0.9250\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0782 - accuracy: 0.9625 - val_loss: 0.1758 - val_accuracy: 0.9500\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1105 - accuracy: 0.9542 - val_loss: 0.1463 - val_accuracy: 0.9625\n    Epoch 6/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0400 - accuracy: 0.9875 - val_loss: 0.3009 - val_accuracy: 0.8875\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0640 - accuracy: 0.9708 - val_loss: 0.1436 - val_accuracy: 0.9625\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0420 - accuracy: 0.9750 - val_loss: 0.1702 - val_accuracy: 0.9375\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0266 - accuracy: 0.9958 - val_loss: 0.1697 - val_accuracy: 0.9500\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0310 - accuracy: 0.9917 - val_loss: 0.1456 - val_accuracy: 0.9625\n    Epoch 11/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0254 - accuracy: 0.9917 - val_loss: 0.1698 - val_accuracy: 0.9375\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0262 - accuracy: 0.9917 - val_loss: 0.1428 - val_accuracy: 0.9500\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0244 - accuracy: 0.9958 - val_loss: 0.1882 - val_accuracy: 0.9375\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0288 - accuracy: 0.9875 - val_loss: 0.1930 - val_accuracy: 0.9250\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0182 - accuracy: 1.0000 - val_loss: 0.1446 - val_accuracy: 0.9625\n    Epoch 16/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0210 - accuracy: 0.9958 - val_loss: 0.1521 - val_accuracy: 0.9625\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0177 - accuracy: 1.0000 - val_loss: 0.1663 - val_accuracy: 0.9375\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0194 - accuracy: 0.9917 - val_loss: 0.1603 - val_accuracy: 0.9375\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0193 - accuracy: 1.0000 - val_loss: 0.1342 - val_accuracy: 0.9750\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0177 - accuracy: 0.9958 - val_loss: 0.1412 - val_accuracy: 0.9625\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0169 - accuracy: 0.9958 - val_loss: 0.1634 - val_accuracy: 0.9500\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0121 - accuracy: 1.0000 - val_loss: 0.1523 - val_accuracy: 0.9375\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0118 - accuracy: 1.0000 - val_loss: 0.1571 - val_accuracy: 0.9375\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0113 - accuracy: 1.0000 - val_loss: 0.1510 - val_accuracy: 0.9500\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0107 - accuracy: 1.0000 - val_loss: 0.1503 - val_accuracy: 0.9500\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0118 - accuracy: 1.0000 - val_loss: 0.1673 - val_accuracy: 0.9375\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0108 - accuracy: 1.0000 - val_loss: 0.1585 - val_accuracy: 0.9500\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0087 - accuracy: 1.0000 - val_loss: 0.1546 - val_accuracy: 0.9500\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0085 - accuracy: 1.0000 - val_loss: 0.1546 - val_accuracy: 0.9500\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0088 - accuracy: 1.0000 - val_loss: 0.1638 - val_accuracy: 0.9500\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0092 - accuracy: 1.0000 - val_loss: 0.1585 - val_accuracy: 0.9500\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0081 - accuracy: 1.0000 - val_loss: 0.1566 - val_accuracy: 0.9500\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0079 - accuracy: 1.0000 - val_loss: 0.1745 - val_accuracy: 0.9375\n    Epoch 34/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0078 - accuracy: 1.0000 - val_loss: 0.1574 - val_accuracy: 0.9375\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0073 - accuracy: 1.0000 - val_loss: 0.1720 - val_accuracy: 0.9500\n    Epoch 36/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0069 - accuracy: 1.0000 - val_loss: 0.1659 - val_accuracy: 0.9500\n    Epoch 37/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0064 - accuracy: 1.0000 - val_loss: 0.1651 - val_accuracy: 0.9375\n    Epoch 38/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0074 - accuracy: 1.0000 - val_loss: 0.1642 - val_accuracy: 0.9500\n    Epoch 39/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0062 - accuracy: 1.0000 - val_loss: 0.1593 - val_accuracy: 0.9500\n    Epoch 1/300\n    60/60 [==============================] - 1s 5ms/step - loss: 0.6139 - accuracy: 0.7750 - val_loss: 0.3309 - val_accuracy: 0.8750\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1266 - accuracy: 0.9625 - val_loss: 0.2958 - val_accuracy: 0.8875\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1153 - accuracy: 0.9542 - val_loss: 0.2092 - val_accuracy: 0.9250\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0721 - accuracy: 0.9667 - val_loss: 0.2068 - val_accuracy: 0.9375\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0641 - accuracy: 0.9792 - val_loss: 0.1652 - val_accuracy: 0.9500\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0736 - accuracy: 0.9708 - val_loss: 0.2182 - val_accuracy: 0.9125\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0415 - accuracy: 0.9875 - val_loss: 0.1597 - val_accuracy: 0.9375\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0324 - accuracy: 0.9917 - val_loss: 0.2201 - val_accuracy: 0.9500\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0574 - accuracy: 0.9625 - val_loss: 0.1819 - val_accuracy: 0.9250\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0358 - accuracy: 0.9917 - val_loss: 0.1951 - val_accuracy: 0.9125\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0278 - accuracy: 0.9958 - val_loss: 0.1970 - val_accuracy: 0.9250\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0313 - accuracy: 0.9875 - val_loss: 0.1864 - val_accuracy: 0.9375\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0331 - accuracy: 0.9917 - val_loss: 0.1842 - val_accuracy: 0.9500\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0193 - accuracy: 1.0000 - val_loss: 0.1997 - val_accuracy: 0.9500\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0227 - accuracy: 0.9958 - val_loss: 0.1786 - val_accuracy: 0.9375\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0180 - accuracy: 1.0000 - val_loss: 0.1852 - val_accuracy: 0.9500\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0186 - accuracy: 1.0000 - val_loss: 0.1825 - val_accuracy: 0.9500\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0172 - accuracy: 1.0000 - val_loss: 0.1988 - val_accuracy: 0.9250\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0177 - accuracy: 1.0000 - val_loss: 0.2017 - val_accuracy: 0.9250\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0155 - accuracy: 1.0000 - val_loss: 0.1825 - val_accuracy: 0.9375\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0152 - accuracy: 1.0000 - val_loss: 0.1967 - val_accuracy: 0.9375\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0149 - accuracy: 1.0000 - val_loss: 0.1931 - val_accuracy: 0.9500\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0189 - accuracy: 1.0000 - val_loss: 0.2499 - val_accuracy: 0.9125\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0161 - accuracy: 1.0000 - val_loss: 0.2210 - val_accuracy: 0.9250\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0183 - accuracy: 1.0000 - val_loss: 0.1817 - val_accuracy: 0.9625\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0153 - accuracy: 1.0000 - val_loss: 0.1809 - val_accuracy: 0.9500\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0097 - accuracy: 1.0000 - val_loss: 0.1927 - val_accuracy: 0.9375\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0106 - accuracy: 1.0000 - val_loss: 0.2007 - val_accuracy: 0.9250\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0096 - accuracy: 1.0000 - val_loss: 0.1938 - val_accuracy: 0.9375\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0106 - accuracy: 1.0000 - val_loss: 0.1961 - val_accuracy: 0.9500\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0085 - accuracy: 1.0000 - val_loss: 0.2055 - val_accuracy: 0.9250\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0087 - accuracy: 1.0000 - val_loss: 0.2080 - val_accuracy: 0.9375\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0087 - accuracy: 1.0000 - val_loss: 0.2070 - val_accuracy: 0.9375\n    Epoch 34/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0075 - accuracy: 1.0000 - val_loss: 0.2026 - val_accuracy: 0.9375\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0097 - accuracy: 1.0000 - val_loss: 0.1963 - val_accuracy: 0.9375\n    Epoch 36/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0087 - accuracy: 1.0000 - val_loss: 0.1921 - val_accuracy: 0.9375\n    Epoch 37/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0089 - accuracy: 1.0000 - val_loss: 0.2057 - val_accuracy: 0.9500\n    Epoch 38/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0079 - accuracy: 1.0000 - val_loss: 0.2019 - val_accuracy: 0.9375\n    Epoch 39/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0063 - accuracy: 1.0000 - val_loss: 0.2151 - val_accuracy: 0.9375\n    Epoch 40/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0063 - accuracy: 1.0000 - val_loss: 0.2093 - val_accuracy: 0.9375\n    Epoch 41/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0060 - accuracy: 1.0000 - val_loss: 0.2104 - val_accuracy: 0.9250\n    Epoch 42/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0073 - accuracy: 1.0000 - val_loss: 0.2281 - val_accuracy: 0.9250\n    Epoch 43/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0070 - accuracy: 1.0000 - val_loss: 0.2187 - val_accuracy: 0.9250\n    Epoch 44/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0059 - accuracy: 1.0000 - val_loss: 0.2085 - val_accuracy: 0.9375\n    Epoch 45/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0052 - accuracy: 1.0000 - val_loss: 0.2195 - val_accuracy: 0.9250\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 0.9374 - accuracy: 0.7875 - val_loss: 0.4281 - val_accuracy: 0.9125\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1537 - accuracy: 0.9292 - val_loss: 0.3583 - val_accuracy: 0.9125\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1061 - accuracy: 0.9542 - val_loss: 0.3374 - val_accuracy: 0.9000\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0696 - accuracy: 0.9833 - val_loss: 0.3251 - val_accuracy: 0.9375\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0684 - accuracy: 0.9833 - val_loss: 0.3139 - val_accuracy: 0.9250\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0655 - accuracy: 0.9708 - val_loss: 0.3092 - val_accuracy: 0.9375\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0591 - accuracy: 0.9833 - val_loss: 0.3030 - val_accuracy: 0.9500\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0714 - accuracy: 0.9625 - val_loss: 0.3008 - val_accuracy: 0.9250\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0450 - accuracy: 0.9875 - val_loss: 0.2975 - val_accuracy: 0.9375\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0416 - accuracy: 0.9833 - val_loss: 0.2953 - val_accuracy: 0.9375\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0424 - accuracy: 0.9833 - val_loss: 0.3155 - val_accuracy: 0.9375\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0260 - accuracy: 0.9958 - val_loss: 0.3069 - val_accuracy: 0.9375\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0319 - accuracy: 0.9917 - val_loss: 0.3249 - val_accuracy: 0.9500\n    Epoch 14/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0262 - accuracy: 0.9958 - val_loss: 0.3010 - val_accuracy: 0.9375\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0243 - accuracy: 0.9958 - val_loss: 0.2963 - val_accuracy: 0.9375\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0222 - accuracy: 0.9958 - val_loss: 0.2957 - val_accuracy: 0.9375\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0221 - accuracy: 0.9958 - val_loss: 0.2968 - val_accuracy: 0.9375\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0206 - accuracy: 0.9958 - val_loss: 0.3048 - val_accuracy: 0.9500\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0157 - accuracy: 1.0000 - val_loss: 0.2976 - val_accuracy: 0.9500\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0153 - accuracy: 0.9958 - val_loss: 0.3074 - val_accuracy: 0.9500\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0128 - accuracy: 1.0000 - val_loss: 0.3373 - val_accuracy: 0.9500\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0294 - accuracy: 0.9917 - val_loss: 0.3001 - val_accuracy: 0.9375\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0185 - accuracy: 1.0000 - val_loss: 0.3024 - val_accuracy: 0.9375\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0134 - accuracy: 1.0000 - val_loss: 0.3106 - val_accuracy: 0.9500\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0132 - accuracy: 1.0000 - val_loss: 0.3155 - val_accuracy: 0.9500\n    Epoch 26/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0145 - accuracy: 1.0000 - val_loss: 0.3408 - val_accuracy: 0.9500\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0146 - accuracy: 1.0000 - val_loss: 0.3056 - val_accuracy: 0.9375\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 0.7419 - accuracy: 0.7792 - val_loss: 0.0986 - val_accuracy: 0.9500\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1499 - accuracy: 0.9458 - val_loss: 0.1546 - val_accuracy: 0.9250\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1167 - accuracy: 0.9500 - val_loss: 0.1084 - val_accuracy: 0.9625\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0924 - accuracy: 0.9625 - val_loss: 0.0931 - val_accuracy: 0.9625\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0618 - accuracy: 0.9833 - val_loss: 0.2118 - val_accuracy: 0.8875\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0809 - accuracy: 0.9583 - val_loss: 0.1295 - val_accuracy: 0.9500\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0463 - accuracy: 0.9875 - val_loss: 0.1428 - val_accuracy: 0.9250\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0573 - accuracy: 0.9833 - val_loss: 0.1091 - val_accuracy: 0.9625\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0371 - accuracy: 0.9958 - val_loss: 0.1194 - val_accuracy: 0.9375\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0320 - accuracy: 0.9917 - val_loss: 0.1711 - val_accuracy: 0.9250\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0301 - accuracy: 0.9917 - val_loss: 0.1276 - val_accuracy: 0.9375\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0435 - accuracy: 0.9875 - val_loss: 0.0943 - val_accuracy: 0.9875\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0351 - accuracy: 0.9917 - val_loss: 0.1167 - val_accuracy: 0.9250\n    Epoch 14/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0278 - accuracy: 0.9958 - val_loss: 0.0872 - val_accuracy: 0.9625\n    Epoch 15/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0196 - accuracy: 1.0000 - val_loss: 0.1197 - val_accuracy: 0.9375\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0306 - accuracy: 0.9917 - val_loss: 0.1002 - val_accuracy: 0.9375\n    Epoch 17/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0268 - accuracy: 0.9917 - val_loss: 0.0651 - val_accuracy: 0.9875\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0189 - accuracy: 1.0000 - val_loss: 0.0684 - val_accuracy: 0.9875\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0267 - accuracy: 0.9917 - val_loss: 0.0765 - val_accuracy: 0.9750\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0181 - accuracy: 1.0000 - val_loss: 0.0682 - val_accuracy: 0.9750\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0170 - accuracy: 1.0000 - val_loss: 0.0728 - val_accuracy: 0.9875\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0152 - accuracy: 1.0000 - val_loss: 0.0912 - val_accuracy: 0.9625\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0140 - accuracy: 1.0000 - val_loss: 0.0817 - val_accuracy: 0.9625\n    Epoch 24/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0128 - accuracy: 1.0000 - val_loss: 0.0782 - val_accuracy: 0.9750\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0212 - accuracy: 1.0000 - val_loss: 0.0713 - val_accuracy: 0.9625\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0132 - accuracy: 1.0000 - val_loss: 0.0775 - val_accuracy: 0.9750\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0157 - accuracy: 1.0000 - val_loss: 0.0706 - val_accuracy: 0.9875\n    Epoch 28/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0126 - accuracy: 1.0000 - val_loss: 0.0732 - val_accuracy: 0.9750\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0116 - accuracy: 1.0000 - val_loss: 0.1028 - val_accuracy: 0.9500\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0133 - accuracy: 1.0000 - val_loss: 0.0799 - val_accuracy: 0.9625\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0110 - accuracy: 1.0000 - val_loss: 0.0736 - val_accuracy: 0.9500\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0111 - accuracy: 1.0000 - val_loss: 0.0633 - val_accuracy: 0.9750\n    Epoch 1/300\n    60/60 [==============================] - 1s 5ms/step - loss: 0.7360 - accuracy: 0.8083 - val_loss: 0.1422 - val_accuracy: 0.9375\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2239 - accuracy: 0.9375 - val_loss: 0.1315 - val_accuracy: 0.9500\n    Epoch 3/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.1417 - accuracy: 0.9583 - val_loss: 0.1966 - val_accuracy: 0.9375\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0805 - accuracy: 0.9750 - val_loss: 0.1041 - val_accuracy: 0.9750\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0993 - accuracy: 0.9500 - val_loss: 0.1213 - val_accuracy: 0.9625\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0637 - accuracy: 0.9792 - val_loss: 0.1628 - val_accuracy: 0.9500\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0535 - accuracy: 0.9792 - val_loss: 0.1115 - val_accuracy: 0.9625\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0918 - accuracy: 0.9625 - val_loss: 0.1269 - val_accuracy: 0.9625\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0466 - accuracy: 0.9875 - val_loss: 0.1177 - val_accuracy: 0.9625\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0346 - accuracy: 0.9875 - val_loss: 0.1491 - val_accuracy: 0.9625\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0713 - accuracy: 0.9750 - val_loss: 0.1128 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0298 - accuracy: 0.9958 - val_loss: 0.1145 - val_accuracy: 0.9750\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0362 - accuracy: 0.9917 - val_loss: 0.1084 - val_accuracy: 0.9750\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0327 - accuracy: 0.9958 - val_loss: 0.1068 - val_accuracy: 0.9625\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0235 - accuracy: 0.9917 - val_loss: 0.1096 - val_accuracy: 0.9625\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0261 - accuracy: 0.9917 - val_loss: 0.1055 - val_accuracy: 0.9625\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0256 - accuracy: 0.9958 - val_loss: 0.1116 - val_accuracy: 0.9750\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0247 - accuracy: 0.9958 - val_loss: 0.1029 - val_accuracy: 0.9625\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0216 - accuracy: 0.9958 - val_loss: 0.1067 - val_accuracy: 0.9625\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0221 - accuracy: 0.9958 - val_loss: 0.1030 - val_accuracy: 0.9625\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0266 - accuracy: 0.9958 - val_loss: 0.1062 - val_accuracy: 0.9625\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0161 - accuracy: 1.0000 - val_loss: 0.1025 - val_accuracy: 0.9625\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0194 - accuracy: 0.9958 - val_loss: 0.1028 - val_accuracy: 0.9625\n    Epoch 24/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0156 - accuracy: 1.0000 - val_loss: 0.1023 - val_accuracy: 0.9625\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.8341 - accuracy: 0.6292 - val_loss: 0.1861 - val_accuracy: 0.9125\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2950 - accuracy: 0.9208 - val_loss: 0.1204 - val_accuracy: 0.9625\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1471 - accuracy: 0.9292 - val_loss: 0.0770 - val_accuracy: 0.9750\n    Epoch 4/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.1181 - accuracy: 0.9542 - val_loss: 0.0773 - val_accuracy: 0.9625\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0806 - accuracy: 0.9625 - val_loss: 0.0518 - val_accuracy: 0.9875\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0842 - accuracy: 0.9708 - val_loss: 0.0555 - val_accuracy: 0.9750\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0763 - accuracy: 0.9792 - val_loss: 0.1023 - val_accuracy: 0.9750\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0671 - accuracy: 0.9833 - val_loss: 0.1635 - val_accuracy: 0.9125\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0681 - accuracy: 0.9833 - val_loss: 0.0457 - val_accuracy: 0.9875\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0689 - accuracy: 0.9833 - val_loss: 0.1408 - val_accuracy: 0.9500\n    Epoch 11/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0798 - accuracy: 0.9708 - val_loss: 0.0419 - val_accuracy: 0.9875\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0559 - accuracy: 0.9792 - val_loss: 0.0519 - val_accuracy: 0.9750\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0442 - accuracy: 0.9875 - val_loss: 0.0587 - val_accuracy: 0.9875\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0616 - accuracy: 0.9708 - val_loss: 0.0592 - val_accuracy: 0.9750\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0445 - accuracy: 0.9875 - val_loss: 0.0615 - val_accuracy: 0.9750\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0365 - accuracy: 0.9917 - val_loss: 0.0429 - val_accuracy: 0.9875\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0382 - accuracy: 0.9875 - val_loss: 0.0442 - val_accuracy: 0.9875\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0382 - accuracy: 0.9875 - val_loss: 0.0455 - val_accuracy: 0.9750\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0304 - accuracy: 0.9958 - val_loss: 0.0465 - val_accuracy: 0.9875\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0287 - accuracy: 1.0000 - val_loss: 0.0482 - val_accuracy: 0.9625\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0284 - accuracy: 0.9958 - val_loss: 0.0474 - val_accuracy: 0.9625\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0230 - accuracy: 1.0000 - val_loss: 0.0462 - val_accuracy: 0.9625\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0288 - accuracy: 0.9958 - val_loss: 0.0468 - val_accuracy: 0.9625\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0243 - accuracy: 0.9958 - val_loss: 0.0506 - val_accuracy: 0.9750\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0280 - accuracy: 0.9958 - val_loss: 0.0451 - val_accuracy: 0.9625\n    Epoch 1/300\n    60/60 [==============================] - 0s 5ms/step - loss: 0.8241 - accuracy: 0.7583 - val_loss: 0.5166 - val_accuracy: 0.8750\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1830 - accuracy: 0.9500 - val_loss: 0.2007 - val_accuracy: 0.9375\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1292 - accuracy: 0.9542 - val_loss: 0.1427 - val_accuracy: 0.9625\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1187 - accuracy: 0.9458 - val_loss: 0.1507 - val_accuracy: 0.9375\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0808 - accuracy: 0.9625 - val_loss: 0.1654 - val_accuracy: 0.9500\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0592 - accuracy: 0.9708 - val_loss: 0.2433 - val_accuracy: 0.8875\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0663 - accuracy: 0.9792 - val_loss: 0.1484 - val_accuracy: 0.9750\n    Epoch 8/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0624 - accuracy: 0.9708 - val_loss: 0.1631 - val_accuracy: 0.9500\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0941 - accuracy: 0.9542 - val_loss: 0.1398 - val_accuracy: 0.9625\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0599 - accuracy: 0.9792 - val_loss: 0.1308 - val_accuracy: 0.9625\n    Epoch 11/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0535 - accuracy: 0.9833 - val_loss: 0.1583 - val_accuracy: 0.9500\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0443 - accuracy: 0.9875 - val_loss: 0.1829 - val_accuracy: 0.9625\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0376 - accuracy: 0.9833 - val_loss: 0.1360 - val_accuracy: 0.9625\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0440 - accuracy: 0.9792 - val_loss: 0.1257 - val_accuracy: 0.9750\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0422 - accuracy: 0.9792 - val_loss: 0.1306 - val_accuracy: 0.9750\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0297 - accuracy: 0.9917 - val_loss: 0.1183 - val_accuracy: 0.9750\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0277 - accuracy: 0.9958 - val_loss: 0.1261 - val_accuracy: 0.9750\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0316 - accuracy: 0.9958 - val_loss: 0.1145 - val_accuracy: 0.9750\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0322 - accuracy: 0.9917 - val_loss: 0.1303 - val_accuracy: 0.9750\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0278 - accuracy: 0.9958 - val_loss: 0.1266 - val_accuracy: 0.9625\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0247 - accuracy: 0.9958 - val_loss: 0.1165 - val_accuracy: 0.9750\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0255 - accuracy: 0.9958 - val_loss: 0.1340 - val_accuracy: 0.9500\n    Epoch 23/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0278 - accuracy: 0.9958 - val_loss: 0.1067 - val_accuracy: 0.9750\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0207 - accuracy: 1.0000 - val_loss: 0.1117 - val_accuracy: 0.9750\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0198 - accuracy: 1.0000 - val_loss: 0.1336 - val_accuracy: 0.9750\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0308 - accuracy: 0.9875 - val_loss: 0.1316 - val_accuracy: 0.9500\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0248 - accuracy: 0.9917 - val_loss: 0.1351 - val_accuracy: 0.9750\n    Epoch 1/300\n    60/60 [==============================] - 1s 4ms/step - loss: 0.8934 - accuracy: 0.7875 - val_loss: 0.5007 - val_accuracy: 0.8500\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2165 - accuracy: 0.9125 - val_loss: 0.4277 - val_accuracy: 0.8875\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1470 - accuracy: 0.9458 - val_loss: 0.4017 - val_accuracy: 0.8875\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0752 - accuracy: 0.9792 - val_loss: 0.1871 - val_accuracy: 0.9375\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0652 - accuracy: 0.9750 - val_loss: 0.2205 - val_accuracy: 0.9250\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0823 - accuracy: 0.9667 - val_loss: 0.1937 - val_accuracy: 0.9250\n    Epoch 7/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0626 - accuracy: 0.9750 - val_loss: 0.1893 - val_accuracy: 0.9250\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0654 - accuracy: 0.9792 - val_loss: 0.2395 - val_accuracy: 0.9500\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0520 - accuracy: 0.9833 - val_loss: 0.1837 - val_accuracy: 0.9375\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0359 - accuracy: 0.9917 - val_loss: 0.1872 - val_accuracy: 0.9625\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0371 - accuracy: 0.9875 - val_loss: 0.2143 - val_accuracy: 0.9375\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0336 - accuracy: 0.9833 - val_loss: 0.1850 - val_accuracy: 0.9500\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0335 - accuracy: 0.9917 - val_loss: 0.1602 - val_accuracy: 0.9500\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0277 - accuracy: 0.9917 - val_loss: 0.1641 - val_accuracy: 0.9500\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0290 - accuracy: 1.0000 - val_loss: 0.1673 - val_accuracy: 0.9375\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0391 - accuracy: 0.9875 - val_loss: 0.1632 - val_accuracy: 0.9500\n    Epoch 17/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0230 - accuracy: 0.9917 - val_loss: 0.1492 - val_accuracy: 0.9500\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0247 - accuracy: 0.9917 - val_loss: 0.1557 - val_accuracy: 0.9500\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0217 - accuracy: 0.9958 - val_loss: 0.1806 - val_accuracy: 0.9375\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0175 - accuracy: 1.0000 - val_loss: 0.2195 - val_accuracy: 0.9250\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0253 - accuracy: 0.9958 - val_loss: 0.1528 - val_accuracy: 0.9500\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0226 - accuracy: 0.9958 - val_loss: 0.1448 - val_accuracy: 0.9500\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0216 - accuracy: 1.0000 - val_loss: 0.1681 - val_accuracy: 0.9375\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0175 - accuracy: 0.9958 - val_loss: 0.1805 - val_accuracy: 0.9500\n    Epoch 25/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0164 - accuracy: 1.0000 - val_loss: 0.1968 - val_accuracy: 0.9500\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0165 - accuracy: 0.9958 - val_loss: 0.1607 - val_accuracy: 0.9500\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0137 - accuracy: 1.0000 - val_loss: 0.1642 - val_accuracy: 0.9500\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0129 - accuracy: 1.0000 - val_loss: 0.1766 - val_accuracy: 0.9375\n    Epoch 29/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0116 - accuracy: 1.0000 - val_loss: 0.1659 - val_accuracy: 0.9375\n    Epoch 30/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0130 - accuracy: 1.0000 - val_loss: 0.1515 - val_accuracy: 0.9500\n    Epoch 1/300\n    60/60 [==============================] - 0s 5ms/step - loss: 0.7347 - accuracy: 0.8125 - val_loss: 0.3805 - val_accuracy: 0.8875\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1873 - accuracy: 0.9333 - val_loss: 0.2169 - val_accuracy: 0.9000\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1484 - accuracy: 0.9375 - val_loss: 0.1576 - val_accuracy: 0.9500\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1022 - accuracy: 0.9667 - val_loss: 0.1635 - val_accuracy: 0.9375\n    Epoch 5/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0623 - accuracy: 0.9833 - val_loss: 0.1555 - val_accuracy: 0.9250\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0524 - accuracy: 0.9833 - val_loss: 0.1918 - val_accuracy: 0.9375\n    Epoch 7/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0505 - accuracy: 0.9833 - val_loss: 0.1814 - val_accuracy: 0.9125\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0398 - accuracy: 0.9833 - val_loss: 0.2128 - val_accuracy: 0.9000\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0464 - accuracy: 0.9750 - val_loss: 0.1849 - val_accuracy: 0.9375\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0378 - accuracy: 0.9875 - val_loss: 0.1653 - val_accuracy: 0.9250\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0341 - accuracy: 0.9917 - val_loss: 0.1666 - val_accuracy: 0.9250\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0259 - accuracy: 0.9958 - val_loss: 0.1932 - val_accuracy: 0.9250\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0297 - accuracy: 0.9958 - val_loss: 0.1890 - val_accuracy: 0.9250\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0274 - accuracy: 0.9958 - val_loss: 0.1648 - val_accuracy: 0.9250\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0231 - accuracy: 1.0000 - val_loss: 0.1681 - val_accuracy: 0.9375\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0247 - accuracy: 1.0000 - val_loss: 0.1715 - val_accuracy: 0.9250\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0241 - accuracy: 1.0000 - val_loss: 0.1708 - val_accuracy: 0.9250\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0180 - accuracy: 1.0000 - val_loss: 0.1996 - val_accuracy: 0.9125\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0232 - accuracy: 0.9958 - val_loss: 0.1740 - val_accuracy: 0.9250\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0180 - accuracy: 1.0000 - val_loss: 0.1794 - val_accuracy: 0.9250\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0169 - accuracy: 1.0000 - val_loss: 0.1681 - val_accuracy: 0.9125\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0177 - accuracy: 1.0000 - val_loss: 0.1784 - val_accuracy: 0.9375\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0159 - accuracy: 1.0000 - val_loss: 0.1679 - val_accuracy: 0.9375\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 0.6935 - accuracy: 0.7750 - val_loss: 0.2688 - val_accuracy: 0.8875\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1528 - accuracy: 0.9417 - val_loss: 0.1796 - val_accuracy: 0.9375\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1161 - accuracy: 0.9625 - val_loss: 0.1332 - val_accuracy: 0.9250\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1155 - accuracy: 0.9583 - val_loss: 0.1469 - val_accuracy: 0.9625\n    Epoch 5/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0871 - accuracy: 0.9667 - val_loss: 0.1128 - val_accuracy: 0.9500\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0751 - accuracy: 0.9792 - val_loss: 0.1314 - val_accuracy: 0.9375\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0760 - accuracy: 0.9750 - val_loss: 0.1255 - val_accuracy: 0.9500\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0638 - accuracy: 0.9667 - val_loss: 0.1001 - val_accuracy: 0.9500\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0650 - accuracy: 0.9667 - val_loss: 0.1171 - val_accuracy: 0.9375\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0466 - accuracy: 0.9875 - val_loss: 0.0590 - val_accuracy: 0.9750\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0427 - accuracy: 0.9917 - val_loss: 0.0654 - val_accuracy: 0.9750\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0397 - accuracy: 0.9875 - val_loss: 0.1043 - val_accuracy: 0.9625\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0490 - accuracy: 0.9833 - val_loss: 0.0726 - val_accuracy: 0.9625\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0367 - accuracy: 0.9958 - val_loss: 0.0651 - val_accuracy: 0.9625\n    Epoch 15/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0368 - accuracy: 0.9917 - val_loss: 0.0830 - val_accuracy: 0.9625\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0282 - accuracy: 0.9958 - val_loss: 0.0642 - val_accuracy: 0.9750\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0304 - accuracy: 0.9917 - val_loss: 0.0767 - val_accuracy: 0.9750\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0391 - accuracy: 0.9917 - val_loss: 0.0805 - val_accuracy: 0.9500\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0303 - accuracy: 0.9875 - val_loss: 0.0787 - val_accuracy: 0.9750\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0290 - accuracy: 0.9958 - val_loss: 0.0520 - val_accuracy: 0.9750\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0226 - accuracy: 1.0000 - val_loss: 0.0632 - val_accuracy: 0.9750\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0209 - accuracy: 1.0000 - val_loss: 0.0501 - val_accuracy: 0.9750\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0193 - accuracy: 1.0000 - val_loss: 0.0561 - val_accuracy: 0.9875\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0274 - accuracy: 0.9958 - val_loss: 0.0529 - val_accuracy: 0.9750\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0206 - accuracy: 1.0000 - val_loss: 0.0477 - val_accuracy: 0.9875\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0186 - accuracy: 1.0000 - val_loss: 0.0761 - val_accuracy: 0.9625\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0190 - accuracy: 1.0000 - val_loss: 0.0660 - val_accuracy: 0.9750\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0181 - accuracy: 1.0000 - val_loss: 0.0509 - val_accuracy: 0.9875\n    Epoch 29/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0173 - accuracy: 0.9958 - val_loss: 0.0487 - val_accuracy: 0.9750\n    Epoch 30/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0135 - accuracy: 1.0000 - val_loss: 0.0577 - val_accuracy: 0.9625\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0144 - accuracy: 1.0000 - val_loss: 0.0572 - val_accuracy: 0.9750\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0225 - accuracy: 0.9958 - val_loss: 0.0451 - val_accuracy: 0.9750\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0136 - accuracy: 1.0000 - val_loss: 0.0463 - val_accuracy: 0.9750\n    Epoch 34/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0121 - accuracy: 1.0000 - val_loss: 0.0416 - val_accuracy: 0.9750\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0148 - accuracy: 1.0000 - val_loss: 0.0515 - val_accuracy: 0.9750\n    Epoch 36/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0142 - accuracy: 1.0000 - val_loss: 0.0416 - val_accuracy: 0.9875\n    Epoch 37/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0122 - accuracy: 1.0000 - val_loss: 0.0488 - val_accuracy: 0.9750\n    Epoch 38/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0104 - accuracy: 1.0000 - val_loss: 0.0827 - val_accuracy: 0.9750\n    Epoch 39/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0163 - accuracy: 1.0000 - val_loss: 0.0459 - val_accuracy: 0.9750\n    Epoch 40/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0101 - accuracy: 1.0000 - val_loss: 0.0398 - val_accuracy: 0.9750\n    Epoch 41/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0090 - accuracy: 1.0000 - val_loss: 0.0585 - val_accuracy: 0.9750\n    Epoch 42/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0101 - accuracy: 1.0000 - val_loss: 0.0460 - val_accuracy: 0.9875\n    Epoch 43/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0096 - accuracy: 1.0000 - val_loss: 0.0392 - val_accuracy: 0.9750\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.0021 - accuracy: 0.7000 - val_loss: 0.1465 - val_accuracy: 0.9250\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2656 - accuracy: 0.9167 - val_loss: 0.0924 - val_accuracy: 0.9750\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1239 - accuracy: 0.9583 - val_loss: 0.0898 - val_accuracy: 0.9625\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0632 - accuracy: 0.9875 - val_loss: 0.0812 - val_accuracy: 0.9625\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0551 - accuracy: 0.9875 - val_loss: 0.1764 - val_accuracy: 0.9375\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0792 - accuracy: 0.9625 - val_loss: 0.1220 - val_accuracy: 0.9500\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0535 - accuracy: 0.9917 - val_loss: 0.1041 - val_accuracy: 0.9500\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0410 - accuracy: 0.9917 - val_loss: 0.1106 - val_accuracy: 0.9625\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0385 - accuracy: 0.9917 - val_loss: 0.1378 - val_accuracy: 0.9500\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0478 - accuracy: 0.9833 - val_loss: 0.1264 - val_accuracy: 0.9500\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0330 - accuracy: 0.9958 - val_loss: 0.1382 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0339 - accuracy: 0.9958 - val_loss: 0.1166 - val_accuracy: 0.9750\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0306 - accuracy: 0.9917 - val_loss: 0.1257 - val_accuracy: 0.9625\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0334 - accuracy: 0.9958 - val_loss: 0.1329 - val_accuracy: 0.9500\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0254 - accuracy: 0.9958 - val_loss: 0.1013 - val_accuracy: 0.9500\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0363 - accuracy: 0.9917 - val_loss: 0.1286 - val_accuracy: 0.9500\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0245 - accuracy: 0.9958 - val_loss: 0.1292 - val_accuracy: 0.9625\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0275 - accuracy: 0.9917 - val_loss: 0.1416 - val_accuracy: 0.9500\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0181 - accuracy: 1.0000 - val_loss: 0.1118 - val_accuracy: 0.9500\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0237 - accuracy: 1.0000 - val_loss: 0.1243 - val_accuracy: 0.9625\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0225 - accuracy: 0.9958 - val_loss: 0.1258 - val_accuracy: 0.9625\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0219 - accuracy: 1.0000 - val_loss: 0.1125 - val_accuracy: 0.9500\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 0.5832 - accuracy: 0.8083 - val_loss: 0.3194 - val_accuracy: 0.8625\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1284 - accuracy: 0.9500 - val_loss: 0.1999 - val_accuracy: 0.9250\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0987 - accuracy: 0.9667 - val_loss: 0.2989 - val_accuracy: 0.9000\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0656 - accuracy: 0.9708 - val_loss: 0.2040 - val_accuracy: 0.9250\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0472 - accuracy: 0.9958 - val_loss: 0.1733 - val_accuracy: 0.9250\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0591 - accuracy: 0.9750 - val_loss: 0.2181 - val_accuracy: 0.9125\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0425 - accuracy: 0.9833 - val_loss: 0.1918 - val_accuracy: 0.9375\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0304 - accuracy: 0.9958 - val_loss: 0.1920 - val_accuracy: 0.9375\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0264 - accuracy: 0.9958 - val_loss: 0.2085 - val_accuracy: 0.9250\n    Epoch 10/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0173 - accuracy: 1.0000 - val_loss: 0.2541 - val_accuracy: 0.9125\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0195 - accuracy: 0.9917 - val_loss: 0.2581 - val_accuracy: 0.9125\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0213 - accuracy: 1.0000 - val_loss: 0.1833 - val_accuracy: 0.9250\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0154 - accuracy: 1.0000 - val_loss: 0.2081 - val_accuracy: 0.9250\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0132 - accuracy: 1.0000 - val_loss: 0.2155 - val_accuracy: 0.9125\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0139 - accuracy: 1.0000 - val_loss: 0.2203 - val_accuracy: 0.9250\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0122 - accuracy: 1.0000 - val_loss: 0.2495 - val_accuracy: 0.9125\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0103 - accuracy: 1.0000 - val_loss: 0.2306 - val_accuracy: 0.9250\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0106 - accuracy: 1.0000 - val_loss: 0.2160 - val_accuracy: 0.9250\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0113 - accuracy: 1.0000 - val_loss: 0.2480 - val_accuracy: 0.9000\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0100 - accuracy: 1.0000 - val_loss: 0.2455 - val_accuracy: 0.9125\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0089 - accuracy: 1.0000 - val_loss: 0.2725 - val_accuracy: 0.9000\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0102 - accuracy: 1.0000 - val_loss: 0.2451 - val_accuracy: 0.9125\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0082 - accuracy: 1.0000 - val_loss: 0.2513 - val_accuracy: 0.9125\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0073 - accuracy: 1.0000 - val_loss: 0.2248 - val_accuracy: 0.9250\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0069 - accuracy: 1.0000 - val_loss: 0.2276 - val_accuracy: 0.9250\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0075 - accuracy: 1.0000 - val_loss: 0.2921 - val_accuracy: 0.9000\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0081 - accuracy: 1.0000 - val_loss: 0.2691 - val_accuracy: 0.9125\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 0.7837 - accuracy: 0.7792 - val_loss: 0.3172 - val_accuracy: 0.8500\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2030 - accuracy: 0.9375 - val_loss: 0.1126 - val_accuracy: 0.9625\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1593 - accuracy: 0.9417 - val_loss: 0.0912 - val_accuracy: 0.9625\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0843 - accuracy: 0.9708 - val_loss: 0.0821 - val_accuracy: 0.9500\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0777 - accuracy: 0.9792 - val_loss: 0.0663 - val_accuracy: 0.9875\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0679 - accuracy: 0.9750 - val_loss: 0.0536 - val_accuracy: 1.0000\n    Epoch 7/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0775 - accuracy: 0.9792 - val_loss: 0.0713 - val_accuracy: 0.9625\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0673 - accuracy: 0.9833 - val_loss: 0.0698 - val_accuracy: 0.9875\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0920 - accuracy: 0.9708 - val_loss: 0.0810 - val_accuracy: 0.9750\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0531 - accuracy: 0.9833 - val_loss: 0.0458 - val_accuracy: 1.0000\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0471 - accuracy: 0.9792 - val_loss: 0.0363 - val_accuracy: 1.0000\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0571 - accuracy: 0.9708 - val_loss: 0.1234 - val_accuracy: 0.9375\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0477 - accuracy: 0.9875 - val_loss: 0.0362 - val_accuracy: 1.0000\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0618 - accuracy: 0.9750 - val_loss: 0.0254 - val_accuracy: 1.0000\n    Epoch 15/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0296 - accuracy: 0.9875 - val_loss: 0.0525 - val_accuracy: 0.9875\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0318 - accuracy: 0.9917 - val_loss: 0.0464 - val_accuracy: 1.0000\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0506 - accuracy: 0.9833 - val_loss: 0.0615 - val_accuracy: 0.9750\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0600 - accuracy: 0.9750 - val_loss: 0.0283 - val_accuracy: 1.0000\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0488 - accuracy: 0.9833 - val_loss: 0.0463 - val_accuracy: 1.0000\n    Epoch 20/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0287 - accuracy: 0.9917 - val_loss: 0.0431 - val_accuracy: 1.0000\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0243 - accuracy: 1.0000 - val_loss: 0.0247 - val_accuracy: 1.0000\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0327 - accuracy: 0.9875 - val_loss: 0.0280 - val_accuracy: 1.0000\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0355 - accuracy: 0.9833 - val_loss: 0.0286 - val_accuracy: 1.0000\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0252 - accuracy: 0.9958 - val_loss: 0.0239 - val_accuracy: 1.0000\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0176 - accuracy: 1.0000 - val_loss: 0.0307 - val_accuracy: 1.0000\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0217 - accuracy: 1.0000 - val_loss: 0.0236 - val_accuracy: 1.0000\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.1206 - accuracy: 0.7583 - val_loss: 0.4365 - val_accuracy: 0.9375\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.4855 - accuracy: 0.9000 - val_loss: 0.3491 - val_accuracy: 0.9250\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2494 - accuracy: 0.9250 - val_loss: 0.3001 - val_accuracy: 0.9000\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3150 - accuracy: 0.9375 - val_loss: 0.0998 - val_accuracy: 0.9750\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1293 - accuracy: 0.9542 - val_loss: 0.0929 - val_accuracy: 0.9750\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0991 - accuracy: 0.9625 - val_loss: 0.1697 - val_accuracy: 0.9625\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0858 - accuracy: 0.9583 - val_loss: 0.0772 - val_accuracy: 0.9750\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0626 - accuracy: 0.9792 - val_loss: 0.0660 - val_accuracy: 0.9625\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0525 - accuracy: 0.9792 - val_loss: 0.0363 - val_accuracy: 0.9875\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0790 - accuracy: 0.9667 - val_loss: 0.0313 - val_accuracy: 0.9875\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1581 - accuracy: 0.9542 - val_loss: 0.0305 - val_accuracy: 0.9875\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0387 - accuracy: 0.9750 - val_loss: 0.0295 - val_accuracy: 1.0000\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0364 - accuracy: 0.9875 - val_loss: 0.0523 - val_accuracy: 0.9750\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0303 - accuracy: 0.9917 - val_loss: 0.0449 - val_accuracy: 0.9750\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0288 - accuracy: 0.9917 - val_loss: 0.0363 - val_accuracy: 0.9875\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0234 - accuracy: 0.9958 - val_loss: 0.0253 - val_accuracy: 1.0000\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0236 - accuracy: 0.9958 - val_loss: 0.0248 - val_accuracy: 1.0000\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0186 - accuracy: 0.9958 - val_loss: 0.0389 - val_accuracy: 0.9875\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0156 - accuracy: 1.0000 - val_loss: 0.0287 - val_accuracy: 1.0000\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0142 - accuracy: 1.0000 - val_loss: 0.0261 - val_accuracy: 1.0000\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0157 - accuracy: 0.9958 - val_loss: 0.0236 - val_accuracy: 1.0000\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0145 - accuracy: 1.0000 - val_loss: 0.0282 - val_accuracy: 1.0000\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0186 - accuracy: 0.9917 - val_loss: 0.0369 - val_accuracy: 1.0000\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0383 - accuracy: 0.9875 - val_loss: 0.0308 - val_accuracy: 0.9875\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0180 - accuracy: 0.9958 - val_loss: 0.0261 - val_accuracy: 1.0000\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0114 - accuracy: 1.0000 - val_loss: 0.0279 - val_accuracy: 1.0000\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0130 - accuracy: 1.0000 - val_loss: 0.0376 - val_accuracy: 0.9875\n    Epoch 28/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0109 - accuracy: 1.0000 - val_loss: 0.0269 - val_accuracy: 1.0000\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0183 - accuracy: 0.9958 - val_loss: 0.0395 - val_accuracy: 0.9875\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0150 - accuracy: 1.0000 - val_loss: 0.0496 - val_accuracy: 1.0000\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0106 - accuracy: 1.0000 - val_loss: 0.0223 - val_accuracy: 1.0000\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0073 - accuracy: 1.0000 - val_loss: 0.0224 - val_accuracy: 1.0000\n    Epoch 1/300\n    60/60 [==============================] - 1s 4ms/step - loss: 0.9015 - accuracy: 0.7708 - val_loss: 0.2254 - val_accuracy: 0.9500\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3460 - accuracy: 0.9000 - val_loss: 0.1605 - val_accuracy: 0.9375\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1586 - accuracy: 0.9542 - val_loss: 0.1477 - val_accuracy: 0.9500\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1420 - accuracy: 0.9500 - val_loss: 0.1695 - val_accuracy: 0.9375\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1433 - accuracy: 0.9542 - val_loss: 0.1098 - val_accuracy: 0.9625\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0704 - accuracy: 0.9750 - val_loss: 0.1357 - val_accuracy: 0.9375\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0895 - accuracy: 0.9708 - val_loss: 0.1302 - val_accuracy: 0.9625\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0534 - accuracy: 0.9792 - val_loss: 0.2007 - val_accuracy: 0.9375\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0405 - accuracy: 0.9917 - val_loss: 0.1752 - val_accuracy: 0.9500\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0368 - accuracy: 0.9958 - val_loss: 0.1220 - val_accuracy: 0.9625\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0320 - accuracy: 0.9958 - val_loss: 0.1476 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0351 - accuracy: 0.9917 - val_loss: 0.1432 - val_accuracy: 0.9625\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0193 - accuracy: 1.0000 - val_loss: 0.1668 - val_accuracy: 0.9500\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0201 - accuracy: 0.9958 - val_loss: 0.1423 - val_accuracy: 0.9625\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0249 - accuracy: 0.9958 - val_loss: 0.1464 - val_accuracy: 0.9625\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0311 - accuracy: 0.9917 - val_loss: 0.1557 - val_accuracy: 0.9625\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0157 - accuracy: 1.0000 - val_loss: 0.1296 - val_accuracy: 0.9625\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0162 - accuracy: 1.0000 - val_loss: 0.1313 - val_accuracy: 0.9625\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0149 - accuracy: 1.0000 - val_loss: 0.1567 - val_accuracy: 0.9625\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0124 - accuracy: 1.0000 - val_loss: 0.1325 - val_accuracy: 0.9750\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0120 - accuracy: 1.0000 - val_loss: 0.1333 - val_accuracy: 0.9750\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0115 - accuracy: 1.0000 - val_loss: 0.1352 - val_accuracy: 0.9750\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0112 - accuracy: 1.0000 - val_loss: 0.1622 - val_accuracy: 0.9625\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0105 - accuracy: 1.0000 - val_loss: 0.1878 - val_accuracy: 0.9500\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0117 - accuracy: 1.0000 - val_loss: 0.1327 - val_accuracy: 0.9625\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0112 - accuracy: 1.0000 - val_loss: 0.1452 - val_accuracy: 0.9625\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0082 - accuracy: 1.0000 - val_loss: 0.1276 - val_accuracy: 0.9750\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0106 - accuracy: 1.0000 - val_loss: 0.1422 - val_accuracy: 0.9625\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0091 - accuracy: 1.0000 - val_loss: 0.1657 - val_accuracy: 0.9625\n    Epoch 30/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0095 - accuracy: 1.0000 - val_loss: 0.1406 - val_accuracy: 0.9625\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0073 - accuracy: 1.0000 - val_loss: 0.1392 - val_accuracy: 0.9625\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0082 - accuracy: 1.0000 - val_loss: 0.1363 - val_accuracy: 0.9750\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0067 - accuracy: 1.0000 - val_loss: 0.1558 - val_accuracy: 0.9625\n    Epoch 34/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0059 - accuracy: 1.0000 - val_loss: 0.1431 - val_accuracy: 0.9625\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0059 - accuracy: 1.0000 - val_loss: 0.1310 - val_accuracy: 0.9750\n    Epoch 36/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0068 - accuracy: 1.0000 - val_loss: 0.1322 - val_accuracy: 0.9625\n    Epoch 37/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0062 - accuracy: 1.0000 - val_loss: 0.1260 - val_accuracy: 0.9750\n    Epoch 38/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0059 - accuracy: 1.0000 - val_loss: 0.1337 - val_accuracy: 0.9750\n    Epoch 39/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0056 - accuracy: 1.0000 - val_loss: 0.1427 - val_accuracy: 0.9750\n    Epoch 40/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0061 - accuracy: 1.0000 - val_loss: 0.1564 - val_accuracy: 0.9625\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.1255 - accuracy: 0.7458 - val_loss: 0.4296 - val_accuracy: 0.8750\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3053 - accuracy: 0.9000 - val_loss: 0.7276 - val_accuracy: 0.8625\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1729 - accuracy: 0.9458 - val_loss: 0.3623 - val_accuracy: 0.9375\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1575 - accuracy: 0.9458 - val_loss: 0.2537 - val_accuracy: 0.9250\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0707 - accuracy: 0.9792 - val_loss: 0.2237 - val_accuracy: 0.9125\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1244 - accuracy: 0.9500 - val_loss: 0.2613 - val_accuracy: 0.9375\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0578 - accuracy: 0.9750 - val_loss: 0.2160 - val_accuracy: 0.9125\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0375 - accuracy: 0.9792 - val_loss: 0.2853 - val_accuracy: 0.9375\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1014 - accuracy: 0.9625 - val_loss: 0.2747 - val_accuracy: 0.9000\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0389 - accuracy: 0.9875 - val_loss: 0.1954 - val_accuracy: 0.9625\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0368 - accuracy: 0.9875 - val_loss: 0.2517 - val_accuracy: 0.9125\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0361 - accuracy: 0.9833 - val_loss: 0.1702 - val_accuracy: 0.9625\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0242 - accuracy: 0.9875 - val_loss: 0.1878 - val_accuracy: 0.9625\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0159 - accuracy: 1.0000 - val_loss: 0.1941 - val_accuracy: 0.9250\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0174 - accuracy: 0.9958 - val_loss: 0.1719 - val_accuracy: 0.9375\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0190 - accuracy: 0.9958 - val_loss: 0.2039 - val_accuracy: 0.9125\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0138 - accuracy: 0.9958 - val_loss: 0.1824 - val_accuracy: 0.9500\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0144 - accuracy: 1.0000 - val_loss: 0.1929 - val_accuracy: 0.9375\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0136 - accuracy: 1.0000 - val_loss: 0.1683 - val_accuracy: 0.9375\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0086 - accuracy: 1.0000 - val_loss: 0.1778 - val_accuracy: 0.9375\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0088 - accuracy: 1.0000 - val_loss: 0.2107 - val_accuracy: 0.9375\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0153 - accuracy: 0.9958 - val_loss: 0.1721 - val_accuracy: 0.9250\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0083 - accuracy: 1.0000 - val_loss: 0.2038 - val_accuracy: 0.9375\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0109 - accuracy: 1.0000 - val_loss: 0.1407 - val_accuracy: 0.9625\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0097 - accuracy: 1.0000 - val_loss: 0.1449 - val_accuracy: 0.9625\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0095 - accuracy: 1.0000 - val_loss: 0.1629 - val_accuracy: 0.9375\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0065 - accuracy: 1.0000 - val_loss: 0.1645 - val_accuracy: 0.9375\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0062 - accuracy: 1.0000 - val_loss: 0.1592 - val_accuracy: 0.9500\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0081 - accuracy: 1.0000 - val_loss: 0.1677 - val_accuracy: 0.9625\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0060 - accuracy: 1.0000 - val_loss: 0.1651 - val_accuracy: 0.9375\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.4506 - accuracy: 0.7333 - val_loss: 1.0315 - val_accuracy: 0.8375\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.4682 - accuracy: 0.9125 - val_loss: 0.5054 - val_accuracy: 0.8625\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3042 - accuracy: 0.9500 - val_loss: 0.6178 - val_accuracy: 0.8625\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2355 - accuracy: 0.9417 - val_loss: 0.2828 - val_accuracy: 0.9125\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1436 - accuracy: 0.9542 - val_loss: 0.2505 - val_accuracy: 0.9000\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1332 - accuracy: 0.9583 - val_loss: 0.1965 - val_accuracy: 0.9375\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0878 - accuracy: 0.9667 - val_loss: 0.1710 - val_accuracy: 0.9500\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0498 - accuracy: 0.9875 - val_loss: 0.2387 - val_accuracy: 0.9250\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0712 - accuracy: 0.9792 - val_loss: 0.1889 - val_accuracy: 0.9250\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0534 - accuracy: 0.9875 - val_loss: 0.1270 - val_accuracy: 0.9625\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0427 - accuracy: 0.9833 - val_loss: 0.1224 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0256 - accuracy: 0.9958 - val_loss: 0.1829 - val_accuracy: 0.9125\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0491 - accuracy: 0.9750 - val_loss: 0.2936 - val_accuracy: 0.9000\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0365 - accuracy: 0.9958 - val_loss: 0.1771 - val_accuracy: 0.9375\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0245 - accuracy: 0.9958 - val_loss: 0.1403 - val_accuracy: 0.9500\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0230 - accuracy: 0.9917 - val_loss: 0.1050 - val_accuracy: 0.9500\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0264 - accuracy: 0.9875 - val_loss: 0.1691 - val_accuracy: 0.9375\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0206 - accuracy: 0.9958 - val_loss: 0.1699 - val_accuracy: 0.9375\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0218 - accuracy: 0.9958 - val_loss: 0.1086 - val_accuracy: 0.9500\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0592 - accuracy: 0.9833 - val_loss: 0.1955 - val_accuracy: 0.9375\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1100 - accuracy: 0.9708 - val_loss: 0.1247 - val_accuracy: 0.9875\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0379 - accuracy: 0.9833 - val_loss: 0.1364 - val_accuracy: 0.9375\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0144 - accuracy: 1.0000 - val_loss: 0.1701 - val_accuracy: 0.9250\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0202 - accuracy: 0.9875 - val_loss: 0.1200 - val_accuracy: 0.9625\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0391 - accuracy: 0.9833 - val_loss: 0.2253 - val_accuracy: 0.9125\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0229 - accuracy: 0.9917 - val_loss: 0.1218 - val_accuracy: 0.9750\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0117 - accuracy: 0.9958 - val_loss: 0.1229 - val_accuracy: 0.9750\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0091 - accuracy: 1.0000 - val_loss: 0.1065 - val_accuracy: 0.9875\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0076 - accuracy: 1.0000 - val_loss: 0.1371 - val_accuracy: 0.9500\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0095 - accuracy: 1.0000 - val_loss: 0.1041 - val_accuracy: 0.9875\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0061 - accuracy: 1.0000 - val_loss: 0.1115 - val_accuracy: 0.9875\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0062 - accuracy: 1.0000 - val_loss: 0.0966 - val_accuracy: 0.9750\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0066 - accuracy: 1.0000 - val_loss: 0.1049 - val_accuracy: 0.9875\n    Epoch 34/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0059 - accuracy: 1.0000 - val_loss: 0.0958 - val_accuracy: 0.9750\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0062 - accuracy: 1.0000 - val_loss: 0.0946 - val_accuracy: 0.9750\n    Epoch 36/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0065 - accuracy: 1.0000 - val_loss: 0.1047 - val_accuracy: 0.9500\n    Epoch 37/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0079 - accuracy: 1.0000 - val_loss: 0.0985 - val_accuracy: 0.9750\n    Epoch 38/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0053 - accuracy: 1.0000 - val_loss: 0.0932 - val_accuracy: 0.9875\n    Epoch 39/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0045 - accuracy: 1.0000 - val_loss: 0.0965 - val_accuracy: 0.9750\n    Epoch 40/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0051 - accuracy: 1.0000 - val_loss: 0.0979 - val_accuracy: 0.9875\n    Epoch 41/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0075 - accuracy: 1.0000 - val_loss: 0.1262 - val_accuracy: 0.9750\n    Epoch 1/300\n    60/60 [==============================] - 0s 5ms/step - loss: 0.6755 - accuracy: 0.7875 - val_loss: 0.3132 - val_accuracy: 0.8625\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.4313 - accuracy: 0.9125 - val_loss: 0.3360 - val_accuracy: 0.8875\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3056 - accuracy: 0.8958 - val_loss: 0.3130 - val_accuracy: 0.9250\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1365 - accuracy: 0.9458 - val_loss: 0.2423 - val_accuracy: 0.9500\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1029 - accuracy: 0.9583 - val_loss: 0.1547 - val_accuracy: 0.9500\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0808 - accuracy: 0.9833 - val_loss: 0.2262 - val_accuracy: 0.9375\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1017 - accuracy: 0.9583 - val_loss: 0.1146 - val_accuracy: 0.9875\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0485 - accuracy: 0.9792 - val_loss: 0.1452 - val_accuracy: 0.9625\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0747 - accuracy: 0.9792 - val_loss: 0.1465 - val_accuracy: 0.9375\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0527 - accuracy: 0.9792 - val_loss: 0.0692 - val_accuracy: 0.9875\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0415 - accuracy: 0.9958 - val_loss: 0.0807 - val_accuracy: 0.9750\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0312 - accuracy: 0.9875 - val_loss: 0.1651 - val_accuracy: 0.9625\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0282 - accuracy: 0.9958 - val_loss: 0.0931 - val_accuracy: 0.9750\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0221 - accuracy: 0.9958 - val_loss: 0.0712 - val_accuracy: 0.9875\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0249 - accuracy: 0.9917 - val_loss: 0.1379 - val_accuracy: 0.9625\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0182 - accuracy: 1.0000 - val_loss: 0.1198 - val_accuracy: 0.9625\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0185 - accuracy: 0.9958 - val_loss: 0.0832 - val_accuracy: 0.9625\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0147 - accuracy: 1.0000 - val_loss: 0.0686 - val_accuracy: 0.9750\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0160 - accuracy: 0.9958 - val_loss: 0.0725 - val_accuracy: 0.9750\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0291 - accuracy: 0.9917 - val_loss: 0.0478 - val_accuracy: 0.9875\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0232 - accuracy: 0.9958 - val_loss: 0.0936 - val_accuracy: 0.9625\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0151 - accuracy: 1.0000 - val_loss: 0.1283 - val_accuracy: 0.9500\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0148 - accuracy: 1.0000 - val_loss: 0.1180 - val_accuracy: 0.9625\n    Epoch 24/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0107 - accuracy: 1.0000 - val_loss: 0.1253 - val_accuracy: 0.9625\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0136 - accuracy: 1.0000 - val_loss: 0.1348 - val_accuracy: 0.9625\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0090 - accuracy: 1.0000 - val_loss: 0.1170 - val_accuracy: 0.9625\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0091 - accuracy: 1.0000 - val_loss: 0.0856 - val_accuracy: 0.9750\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.1226 - accuracy: 0.7333 - val_loss: 1.2970 - val_accuracy: 0.7500\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.4193 - accuracy: 0.8833 - val_loss: 0.6479 - val_accuracy: 0.8875\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2414 - accuracy: 0.9250 - val_loss: 0.3595 - val_accuracy: 0.9000\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2163 - accuracy: 0.9500 - val_loss: 0.4117 - val_accuracy: 0.9375\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1449 - accuracy: 0.9583 - val_loss: 0.2715 - val_accuracy: 0.9500\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0941 - accuracy: 0.9667 - val_loss: 0.3610 - val_accuracy: 0.9125\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1016 - accuracy: 0.9583 - val_loss: 0.2445 - val_accuracy: 0.9500\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0876 - accuracy: 0.9625 - val_loss: 0.3165 - val_accuracy: 0.9375\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0802 - accuracy: 0.9625 - val_loss: 0.2446 - val_accuracy: 0.9500\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0419 - accuracy: 0.9875 - val_loss: 0.2230 - val_accuracy: 0.9500\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0601 - accuracy: 0.9792 - val_loss: 0.2304 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0305 - accuracy: 0.9958 - val_loss: 0.2302 - val_accuracy: 0.9500\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0266 - accuracy: 0.9958 - val_loss: 0.2249 - val_accuracy: 0.9500\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0347 - accuracy: 0.9958 - val_loss: 0.2750 - val_accuracy: 0.9500\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0290 - accuracy: 0.9875 - val_loss: 0.2104 - val_accuracy: 0.9625\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0230 - accuracy: 0.9958 - val_loss: 0.2273 - val_accuracy: 0.9625\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0212 - accuracy: 0.9917 - val_loss: 0.2365 - val_accuracy: 0.9500\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0209 - accuracy: 1.0000 - val_loss: 0.2546 - val_accuracy: 0.9500\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0291 - accuracy: 0.9958 - val_loss: 0.2195 - val_accuracy: 0.9625\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0201 - accuracy: 0.9958 - val_loss: 0.2162 - val_accuracy: 0.9625\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0205 - accuracy: 0.9958 - val_loss: 0.2241 - val_accuracy: 0.9625\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0191 - accuracy: 0.9958 - val_loss: 0.2301 - val_accuracy: 0.9625\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0238 - accuracy: 0.9958 - val_loss: 0.2179 - val_accuracy: 0.9625\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0180 - accuracy: 1.0000 - val_loss: 0.2256 - val_accuracy: 0.9625\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0255 - accuracy: 0.9917 - val_loss: 0.2379 - val_accuracy: 0.9500\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0142 - accuracy: 0.9958 - val_loss: 0.2264 - val_accuracy: 0.9625\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0097 - accuracy: 1.0000 - val_loss: 0.2308 - val_accuracy: 0.9625\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0102 - accuracy: 1.0000 - val_loss: 0.2330 - val_accuracy: 0.9625\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0096 - accuracy: 1.0000 - val_loss: 0.2532 - val_accuracy: 0.9500\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0104 - accuracy: 1.0000 - val_loss: 0.2158 - val_accuracy: 0.9625\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0106 - accuracy: 1.0000 - val_loss: 0.2340 - val_accuracy: 0.9625\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.3238 - accuracy: 0.7042 - val_loss: 0.2793 - val_accuracy: 0.9625\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3835 - accuracy: 0.9083 - val_loss: 0.2966 - val_accuracy: 0.9250\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2020 - accuracy: 0.9333 - val_loss: 0.2334 - val_accuracy: 0.9500\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1712 - accuracy: 0.9167 - val_loss: 0.3149 - val_accuracy: 0.9125\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1411 - accuracy: 0.9458 - val_loss: 0.2601 - val_accuracy: 0.9125\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3617 - accuracy: 0.8667 - val_loss: 0.1777 - val_accuracy: 0.9375\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0966 - accuracy: 0.9625 - val_loss: 0.1634 - val_accuracy: 0.9375\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0964 - accuracy: 0.9583 - val_loss: 0.1449 - val_accuracy: 0.9375\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0569 - accuracy: 0.9708 - val_loss: 0.1666 - val_accuracy: 0.9375\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0637 - accuracy: 0.9833 - val_loss: 0.1453 - val_accuracy: 0.9250\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0493 - accuracy: 0.9833 - val_loss: 0.1253 - val_accuracy: 0.9500\n    Epoch 12/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0460 - accuracy: 0.9833 - val_loss: 0.1711 - val_accuracy: 0.9500\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0312 - accuracy: 0.9958 - val_loss: 0.1290 - val_accuracy: 0.9500\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0295 - accuracy: 0.9958 - val_loss: 0.1796 - val_accuracy: 0.9375\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0280 - accuracy: 0.9958 - val_loss: 0.1091 - val_accuracy: 0.9625\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0238 - accuracy: 0.9958 - val_loss: 0.1603 - val_accuracy: 0.9500\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0279 - accuracy: 0.9917 - val_loss: 0.1151 - val_accuracy: 0.9500\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0229 - accuracy: 0.9958 - val_loss: 0.1739 - val_accuracy: 0.9375\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0421 - accuracy: 0.9875 - val_loss: 0.1036 - val_accuracy: 0.9750\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0191 - accuracy: 1.0000 - val_loss: 0.1022 - val_accuracy: 0.9750\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0258 - accuracy: 1.0000 - val_loss: 0.1191 - val_accuracy: 0.9500\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0162 - accuracy: 1.0000 - val_loss: 0.1231 - val_accuracy: 0.9500\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0215 - accuracy: 0.9958 - val_loss: 0.1025 - val_accuracy: 0.9750\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0223 - accuracy: 1.0000 - val_loss: 0.1052 - val_accuracy: 0.9625\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0123 - accuracy: 1.0000 - val_loss: 0.0982 - val_accuracy: 0.9750\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0129 - accuracy: 1.0000 - val_loss: 0.0944 - val_accuracy: 0.9750\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0128 - accuracy: 1.0000 - val_loss: 0.1034 - val_accuracy: 0.9750\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0119 - accuracy: 1.0000 - val_loss: 0.1107 - val_accuracy: 0.9750\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0128 - accuracy: 1.0000 - val_loss: 0.1306 - val_accuracy: 0.9500\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0108 - accuracy: 1.0000 - val_loss: 0.1112 - val_accuracy: 0.9625\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0102 - accuracy: 1.0000 - val_loss: 0.1058 - val_accuracy: 0.9625\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0090 - accuracy: 1.0000 - val_loss: 0.0995 - val_accuracy: 0.9500\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0087 - accuracy: 1.0000 - val_loss: 0.0954 - val_accuracy: 0.9750\n    Epoch 34/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0097 - accuracy: 1.0000 - val_loss: 0.1279 - val_accuracy: 0.9500\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0102 - accuracy: 1.0000 - val_loss: 0.1112 - val_accuracy: 0.9500\n    Epoch 36/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0091 - accuracy: 1.0000 - val_loss: 0.1178 - val_accuracy: 0.9500\n    Epoch 37/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0090 - accuracy: 1.0000 - val_loss: 0.0906 - val_accuracy: 0.9625\n    Epoch 38/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0092 - accuracy: 1.0000 - val_loss: 0.1306 - val_accuracy: 0.9500\n    Epoch 39/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0101 - accuracy: 1.0000 - val_loss: 0.0886 - val_accuracy: 0.9500\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.2552 - accuracy: 0.7458 - val_loss: 0.4752 - val_accuracy: 0.8625\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3150 - accuracy: 0.9125 - val_loss: 0.2892 - val_accuracy: 0.9125\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2179 - accuracy: 0.9250 - val_loss: 0.2448 - val_accuracy: 0.9000\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1428 - accuracy: 0.9458 - val_loss: 0.2594 - val_accuracy: 0.9250\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1182 - accuracy: 0.9542 - val_loss: 0.1764 - val_accuracy: 0.9250\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1013 - accuracy: 0.9583 - val_loss: 0.4443 - val_accuracy: 0.8500\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0544 - accuracy: 0.9750 - val_loss: 0.1626 - val_accuracy: 0.9500\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0410 - accuracy: 0.9875 - val_loss: 0.2179 - val_accuracy: 0.9250\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0334 - accuracy: 0.9917 - val_loss: 0.2051 - val_accuracy: 0.9250\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0285 - accuracy: 0.9917 - val_loss: 0.1449 - val_accuracy: 0.9500\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0302 - accuracy: 0.9917 - val_loss: 0.1293 - val_accuracy: 0.9500\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0217 - accuracy: 0.9958 - val_loss: 0.1399 - val_accuracy: 0.9500\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0201 - accuracy: 0.9958 - val_loss: 0.1466 - val_accuracy: 0.9500\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0304 - accuracy: 0.9917 - val_loss: 0.1491 - val_accuracy: 0.9500\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0170 - accuracy: 0.9958 - val_loss: 0.1675 - val_accuracy: 0.9500\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0178 - accuracy: 0.9958 - val_loss: 0.1694 - val_accuracy: 0.9375\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0144 - accuracy: 1.0000 - val_loss: 0.1722 - val_accuracy: 0.9375\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0148 - accuracy: 1.0000 - val_loss: 0.1586 - val_accuracy: 0.9500\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0119 - accuracy: 1.0000 - val_loss: 0.1411 - val_accuracy: 0.9625\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0123 - accuracy: 1.0000 - val_loss: 0.1415 - val_accuracy: 0.9625\n    Epoch 21/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0107 - accuracy: 1.0000 - val_loss: 0.1818 - val_accuracy: 0.9250\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0123 - accuracy: 1.0000 - val_loss: 0.1546 - val_accuracy: 0.9625\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0110 - accuracy: 1.0000 - val_loss: 0.1643 - val_accuracy: 0.9500\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0104 - accuracy: 1.0000 - val_loss: 0.1438 - val_accuracy: 0.9625\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0083 - accuracy: 1.0000 - val_loss: 0.1405 - val_accuracy: 0.9625\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0083 - accuracy: 1.0000 - val_loss: 0.1321 - val_accuracy: 0.9750\n    Epoch 27/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0086 - accuracy: 1.0000 - val_loss: 0.1416 - val_accuracy: 0.9625\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0078 - accuracy: 1.0000 - val_loss: 0.1415 - val_accuracy: 0.9625\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0070 - accuracy: 1.0000 - val_loss: 0.1379 - val_accuracy: 0.9625\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0065 - accuracy: 1.0000 - val_loss: 0.1398 - val_accuracy: 0.9500\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0072 - accuracy: 1.0000 - val_loss: 0.1362 - val_accuracy: 0.9625\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0064 - accuracy: 1.0000 - val_loss: 0.1518 - val_accuracy: 0.9625\n    Epoch 33/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0061 - accuracy: 1.0000 - val_loss: 0.1353 - val_accuracy: 0.9500\n    Epoch 34/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0060 - accuracy: 1.0000 - val_loss: 0.1442 - val_accuracy: 0.9625\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0056 - accuracy: 1.0000 - val_loss: 0.1354 - val_accuracy: 0.9625\n    Epoch 36/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0053 - accuracy: 1.0000 - val_loss: 0.1397 - val_accuracy: 0.9625\n    Epoch 37/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0049 - accuracy: 1.0000 - val_loss: 0.1627 - val_accuracy: 0.9625\n    Epoch 38/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0060 - accuracy: 1.0000 - val_loss: 0.1820 - val_accuracy: 0.9375\n    Epoch 39/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0054 - accuracy: 1.0000 - val_loss: 0.1452 - val_accuracy: 0.9625\n    Epoch 40/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0054 - accuracy: 1.0000 - val_loss: 0.1537 - val_accuracy: 0.9625\n    Epoch 41/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0044 - accuracy: 1.0000 - val_loss: 0.1419 - val_accuracy: 0.9625\n    Epoch 42/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0048 - accuracy: 1.0000 - val_loss: 0.1418 - val_accuracy: 0.9750\n    Epoch 43/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0041 - accuracy: 1.0000 - val_loss: 0.1467 - val_accuracy: 0.9625\n    Epoch 44/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0039 - accuracy: 1.0000 - val_loss: 0.1608 - val_accuracy: 0.9625\n    Epoch 45/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0041 - accuracy: 1.0000 - val_loss: 0.1469 - val_accuracy: 0.9625\n    Epoch 46/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0039 - accuracy: 1.0000 - val_loss: 0.1427 - val_accuracy: 0.9625\n    Epoch 1/300\n    60/60 [==============================] - 1s 4ms/step - loss: 0.9260 - accuracy: 0.7875 - val_loss: 0.3626 - val_accuracy: 0.8875\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2920 - accuracy: 0.9292 - val_loss: 0.5725 - val_accuracy: 0.8500\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2374 - accuracy: 0.9500 - val_loss: 0.4686 - val_accuracy: 0.8875\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1521 - accuracy: 0.9542 - val_loss: 0.3559 - val_accuracy: 0.9250\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1081 - accuracy: 0.9625 - val_loss: 0.3144 - val_accuracy: 0.9375\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0815 - accuracy: 0.9750 - val_loss: 0.2743 - val_accuracy: 0.9000\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0428 - accuracy: 0.9875 - val_loss: 0.2342 - val_accuracy: 0.9125\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0343 - accuracy: 0.9833 - val_loss: 0.3022 - val_accuracy: 0.9250\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0713 - accuracy: 0.9667 - val_loss: 0.2094 - val_accuracy: 0.9125\n    Epoch 10/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0265 - accuracy: 1.0000 - val_loss: 0.2681 - val_accuracy: 0.9125\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0212 - accuracy: 1.0000 - val_loss: 0.2529 - val_accuracy: 0.9000\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0225 - accuracy: 0.9958 - val_loss: 0.2270 - val_accuracy: 0.9125\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0366 - accuracy: 0.9875 - val_loss: 0.2333 - val_accuracy: 0.9375\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0263 - accuracy: 0.9958 - val_loss: 0.2499 - val_accuracy: 0.9250\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0185 - accuracy: 0.9958 - val_loss: 0.2014 - val_accuracy: 0.9250\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0149 - accuracy: 1.0000 - val_loss: 0.2144 - val_accuracy: 0.9250\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0142 - accuracy: 1.0000 - val_loss: 0.2226 - val_accuracy: 0.9375\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0133 - accuracy: 1.0000 - val_loss: 0.2173 - val_accuracy: 0.9250\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0130 - accuracy: 1.0000 - val_loss: 0.2188 - val_accuracy: 0.9250\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0107 - accuracy: 1.0000 - val_loss: 0.1978 - val_accuracy: 0.9250\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0120 - accuracy: 1.0000 - val_loss: 0.2414 - val_accuracy: 0.9000\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0095 - accuracy: 1.0000 - val_loss: 0.2250 - val_accuracy: 0.9375\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0139 - accuracy: 1.0000 - val_loss: 0.2583 - val_accuracy: 0.9250\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0141 - accuracy: 0.9958 - val_loss: 0.2246 - val_accuracy: 0.9125\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0101 - accuracy: 1.0000 - val_loss: 0.2172 - val_accuracy: 0.9125\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.6738 - accuracy: 0.7375 - val_loss: 0.5315 - val_accuracy: 0.8875\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.4281 - accuracy: 0.8917 - val_loss: 0.2986 - val_accuracy: 0.9250\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2903 - accuracy: 0.9292 - val_loss: 0.1956 - val_accuracy: 0.9500\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1916 - accuracy: 0.9375 - val_loss: 0.3539 - val_accuracy: 0.8875\n    Epoch 5/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.2755 - accuracy: 0.9375 - val_loss: 0.2297 - val_accuracy: 0.9375\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1224 - accuracy: 0.9375 - val_loss: 0.2854 - val_accuracy: 0.9250\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0993 - accuracy: 0.9625 - val_loss: 0.1690 - val_accuracy: 0.9375\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1246 - accuracy: 0.9542 - val_loss: 0.1838 - val_accuracy: 0.9500\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1041 - accuracy: 0.9667 - val_loss: 0.1335 - val_accuracy: 0.9625\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0619 - accuracy: 0.9792 - val_loss: 0.1001 - val_accuracy: 0.9500\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0659 - accuracy: 0.9708 - val_loss: 0.1141 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0357 - accuracy: 0.9833 - val_loss: 0.0882 - val_accuracy: 0.9500\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0469 - accuracy: 0.9875 - val_loss: 0.1029 - val_accuracy: 0.9625\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0312 - accuracy: 0.9917 - val_loss: 0.0958 - val_accuracy: 0.9625\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0459 - accuracy: 0.9792 - val_loss: 0.1173 - val_accuracy: 0.9750\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0400 - accuracy: 0.9833 - val_loss: 0.0760 - val_accuracy: 0.9625\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0206 - accuracy: 0.9958 - val_loss: 0.0920 - val_accuracy: 0.9750\n    Epoch 18/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0212 - accuracy: 0.9917 - val_loss: 0.1061 - val_accuracy: 0.9375\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0132 - accuracy: 1.0000 - val_loss: 0.0967 - val_accuracy: 0.9500\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0142 - accuracy: 0.9958 - val_loss: 0.1161 - val_accuracy: 0.9500\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0117 - accuracy: 1.0000 - val_loss: 0.1055 - val_accuracy: 0.9500\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0220 - accuracy: 0.9917 - val_loss: 0.0868 - val_accuracy: 0.9500\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0146 - accuracy: 1.0000 - val_loss: 0.0922 - val_accuracy: 0.9375\n    Epoch 24/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0117 - accuracy: 1.0000 - val_loss: 0.0906 - val_accuracy: 0.9500\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0111 - accuracy: 1.0000 - val_loss: 0.1210 - val_accuracy: 0.9500\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0114 - accuracy: 1.0000 - val_loss: 0.1077 - val_accuracy: 0.9500\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0100 - accuracy: 1.0000 - val_loss: 0.0853 - val_accuracy: 0.9500\n    Epoch 28/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0151 - accuracy: 1.0000 - val_loss: 0.1135 - val_accuracy: 0.9375\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0093 - accuracy: 1.0000 - val_loss: 0.1167 - val_accuracy: 0.9500\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0082 - accuracy: 1.0000 - val_loss: 0.0872 - val_accuracy: 0.9625\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0112 - accuracy: 1.0000 - val_loss: 0.0765 - val_accuracy: 0.9500\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0078 - accuracy: 1.0000 - val_loss: 0.0801 - val_accuracy: 0.9500\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0075 - accuracy: 1.0000 - val_loss: 0.0868 - val_accuracy: 0.9625\n    Epoch 34/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0072 - accuracy: 1.0000 - val_loss: 0.0839 - val_accuracy: 0.9625\n    Epoch 35/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0069 - accuracy: 1.0000 - val_loss: 0.0842 - val_accuracy: 0.9625\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.4907 - accuracy: 0.7083 - val_loss: 0.4184 - val_accuracy: 0.9125\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.5568 - accuracy: 0.8958 - val_loss: 0.5351 - val_accuracy: 0.8625\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3204 - accuracy: 0.8667 - val_loss: 0.4097 - val_accuracy: 0.8875\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2343 - accuracy: 0.9125 - val_loss: 0.1384 - val_accuracy: 0.9250\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1720 - accuracy: 0.9375 - val_loss: 0.2609 - val_accuracy: 0.9125\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1151 - accuracy: 0.9500 - val_loss: 0.1767 - val_accuracy: 0.9500\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0892 - accuracy: 0.9667 - val_loss: 0.1664 - val_accuracy: 0.9250\n    Epoch 8/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0571 - accuracy: 0.9833 - val_loss: 0.1544 - val_accuracy: 0.9375\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1026 - accuracy: 0.9625 - val_loss: 0.1460 - val_accuracy: 0.9500\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0496 - accuracy: 0.9833 - val_loss: 0.0769 - val_accuracy: 0.9750\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0266 - accuracy: 0.9958 - val_loss: 0.0821 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0330 - accuracy: 0.9958 - val_loss: 0.1050 - val_accuracy: 0.9500\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0250 - accuracy: 1.0000 - val_loss: 0.0674 - val_accuracy: 0.9875\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0203 - accuracy: 1.0000 - val_loss: 0.0653 - val_accuracy: 0.9875\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0209 - accuracy: 0.9958 - val_loss: 0.0617 - val_accuracy: 0.9875\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0231 - accuracy: 1.0000 - val_loss: 0.0506 - val_accuracy: 1.0000\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0188 - accuracy: 0.9958 - val_loss: 0.1445 - val_accuracy: 0.9375\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0217 - accuracy: 0.9958 - val_loss: 0.0658 - val_accuracy: 0.9625\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0197 - accuracy: 1.0000 - val_loss: 0.0511 - val_accuracy: 0.9875\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0167 - accuracy: 1.0000 - val_loss: 0.0534 - val_accuracy: 0.9875\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0146 - accuracy: 1.0000 - val_loss: 0.0564 - val_accuracy: 0.9875\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0129 - accuracy: 1.0000 - val_loss: 0.0530 - val_accuracy: 0.9750\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0120 - accuracy: 1.0000 - val_loss: 0.0658 - val_accuracy: 0.9750\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0102 - accuracy: 1.0000 - val_loss: 0.0616 - val_accuracy: 0.9625\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0107 - accuracy: 1.0000 - val_loss: 0.0542 - val_accuracy: 0.9875\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0090 - accuracy: 1.0000 - val_loss: 0.0988 - val_accuracy: 0.9250\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0114 - accuracy: 1.0000 - val_loss: 0.0825 - val_accuracy: 0.9375\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0107 - accuracy: 1.0000 - val_loss: 0.0520 - val_accuracy: 0.9750\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0091 - accuracy: 1.0000 - val_loss: 0.0495 - val_accuracy: 1.0000\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0082 - accuracy: 1.0000 - val_loss: 0.0606 - val_accuracy: 0.9625\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0078 - accuracy: 1.0000 - val_loss: 0.0650 - val_accuracy: 0.9500\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0084 - accuracy: 1.0000 - val_loss: 0.0695 - val_accuracy: 0.9625\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0074 - accuracy: 1.0000 - val_loss: 0.0741 - val_accuracy: 0.9625\n    Epoch 34/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0075 - accuracy: 1.0000 - val_loss: 0.0797 - val_accuracy: 0.9500\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0066 - accuracy: 1.0000 - val_loss: 0.0568 - val_accuracy: 0.9625\n    Epoch 36/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0074 - accuracy: 1.0000 - val_loss: 0.0444 - val_accuracy: 1.0000\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.0755 - accuracy: 0.7875 - val_loss: 0.4982 - val_accuracy: 0.9000\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3529 - accuracy: 0.9125 - val_loss: 0.3688 - val_accuracy: 0.9125\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2403 - accuracy: 0.9375 - val_loss: 0.2924 - val_accuracy: 0.9000\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2377 - accuracy: 0.9417 - val_loss: 0.4967 - val_accuracy: 0.8875\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1578 - accuracy: 0.9375 - val_loss: 0.2116 - val_accuracy: 0.9250\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1114 - accuracy: 0.9583 - val_loss: 0.2944 - val_accuracy: 0.9500\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1149 - accuracy: 0.9542 - val_loss: 0.2242 - val_accuracy: 0.9375\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0647 - accuracy: 0.9792 - val_loss: 0.2320 - val_accuracy: 0.9375\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0516 - accuracy: 0.9875 - val_loss: 0.1639 - val_accuracy: 0.9250\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0584 - accuracy: 0.9750 - val_loss: 0.2563 - val_accuracy: 0.9125\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0732 - accuracy: 0.9750 - val_loss: 0.1371 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0401 - accuracy: 0.9750 - val_loss: 0.1531 - val_accuracy: 0.9625\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0537 - accuracy: 0.9917 - val_loss: 0.1813 - val_accuracy: 0.9625\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0257 - accuracy: 0.9958 - val_loss: 0.1600 - val_accuracy: 0.9625\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0193 - accuracy: 1.0000 - val_loss: 0.1477 - val_accuracy: 0.9625\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0180 - accuracy: 0.9958 - val_loss: 0.1584 - val_accuracy: 0.9375\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0212 - accuracy: 1.0000 - val_loss: 0.1268 - val_accuracy: 0.9750\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0150 - accuracy: 1.0000 - val_loss: 0.1292 - val_accuracy: 0.9750\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0122 - accuracy: 1.0000 - val_loss: 0.1213 - val_accuracy: 0.9750\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0126 - accuracy: 1.0000 - val_loss: 0.1276 - val_accuracy: 0.9750\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0160 - accuracy: 1.0000 - val_loss: 0.1218 - val_accuracy: 0.9750\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0095 - accuracy: 1.0000 - val_loss: 0.1414 - val_accuracy: 0.9750\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0109 - accuracy: 1.0000 - val_loss: 0.1391 - val_accuracy: 0.9750\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0103 - accuracy: 1.0000 - val_loss: 0.1439 - val_accuracy: 0.9625\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0119 - accuracy: 1.0000 - val_loss: 0.1263 - val_accuracy: 0.9750\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0101 - accuracy: 1.0000 - val_loss: 0.1398 - val_accuracy: 0.9750\n    Epoch 27/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0105 - accuracy: 1.0000 - val_loss: 0.1520 - val_accuracy: 0.9625\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0120 - accuracy: 1.0000 - val_loss: 0.1279 - val_accuracy: 0.9750\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0091 - accuracy: 1.0000 - val_loss: 0.1474 - val_accuracy: 0.9750\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0091 - accuracy: 1.0000 - val_loss: 0.1514 - val_accuracy: 0.9625\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0085 - accuracy: 1.0000 - val_loss: 0.1472 - val_accuracy: 0.9625\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0087 - accuracy: 1.0000 - val_loss: 0.1442 - val_accuracy: 0.9750\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0095 - accuracy: 1.0000 - val_loss: 0.1410 - val_accuracy: 0.9750\n    Epoch 34/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0081 - accuracy: 1.0000 - val_loss: 0.1372 - val_accuracy: 0.9750\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0069 - accuracy: 1.0000 - val_loss: 0.1221 - val_accuracy: 0.9750\n    Epoch 36/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0064 - accuracy: 1.0000 - val_loss: 0.1367 - val_accuracy: 0.9750\n    Epoch 37/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0059 - accuracy: 1.0000 - val_loss: 0.1435 - val_accuracy: 0.9750\n    Epoch 1/300\n    60/60 [==============================] - 1s 5ms/step - loss: 1.2128 - accuracy: 0.7292 - val_loss: 0.1269 - val_accuracy: 0.9750\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.4673 - accuracy: 0.8875 - val_loss: 0.0708 - val_accuracy: 0.9750\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3159 - accuracy: 0.9125 - val_loss: 0.0301 - val_accuracy: 1.0000\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2682 - accuracy: 0.9167 - val_loss: 0.0200 - val_accuracy: 0.9875\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2222 - accuracy: 0.9250 - val_loss: 0.0805 - val_accuracy: 0.9750\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1500 - accuracy: 0.9375 - val_loss: 0.0125 - val_accuracy: 1.0000\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0691 - accuracy: 0.9708 - val_loss: 0.0813 - val_accuracy: 0.9625\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0762 - accuracy: 0.9750 - val_loss: 0.0678 - val_accuracy: 0.9750\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0643 - accuracy: 0.9792 - val_loss: 0.0180 - val_accuracy: 1.0000\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0831 - accuracy: 0.9708 - val_loss: 0.0409 - val_accuracy: 0.9875\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0822 - accuracy: 0.9708 - val_loss: 0.0195 - val_accuracy: 0.9875\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0677 - accuracy: 0.9625 - val_loss: 0.0193 - val_accuracy: 0.9875\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0752 - accuracy: 0.9667 - val_loss: 0.0122 - val_accuracy: 1.0000\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0349 - accuracy: 0.9958 - val_loss: 0.0116 - val_accuracy: 1.0000\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0340 - accuracy: 0.9875 - val_loss: 0.0193 - val_accuracy: 1.0000\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0264 - accuracy: 0.9917 - val_loss: 0.0105 - val_accuracy: 1.0000\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0302 - accuracy: 0.9917 - val_loss: 0.0082 - val_accuracy: 1.0000\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0328 - accuracy: 0.9875 - val_loss: 0.0085 - val_accuracy: 1.0000\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0287 - accuracy: 0.9958 - val_loss: 0.0082 - val_accuracy: 1.0000\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0198 - accuracy: 1.0000 - val_loss: 0.0124 - val_accuracy: 1.0000\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0179 - accuracy: 0.9958 - val_loss: 0.0099 - val_accuracy: 1.0000\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0177 - accuracy: 1.0000 - val_loss: 0.0089 - val_accuracy: 1.0000\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0176 - accuracy: 1.0000 - val_loss: 0.0095 - val_accuracy: 1.0000\n    Epoch 1/300\n    60/60 [==============================] - 1s 5ms/step - loss: 1.2467 - accuracy: 0.7833 - val_loss: 0.6782 - val_accuracy: 0.8750\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3757 - accuracy: 0.8875 - val_loss: 0.3041 - val_accuracy: 0.9250\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2417 - accuracy: 0.9458 - val_loss: 0.1775 - val_accuracy: 0.9500\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2158 - accuracy: 0.9250 - val_loss: 0.4488 - val_accuracy: 0.8500\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2332 - accuracy: 0.9208 - val_loss: 0.1239 - val_accuracy: 0.9625\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1112 - accuracy: 0.9667 - val_loss: 0.3411 - val_accuracy: 0.8875\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0855 - accuracy: 0.9625 - val_loss: 0.1892 - val_accuracy: 0.9750\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0741 - accuracy: 0.9667 - val_loss: 0.1246 - val_accuracy: 0.9875\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0593 - accuracy: 0.9750 - val_loss: 0.1452 - val_accuracy: 0.9750\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0350 - accuracy: 0.9958 - val_loss: 0.1593 - val_accuracy: 0.9500\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0445 - accuracy: 0.9792 - val_loss: 0.1535 - val_accuracy: 0.9750\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0361 - accuracy: 0.9875 - val_loss: 0.1385 - val_accuracy: 0.9750\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0271 - accuracy: 1.0000 - val_loss: 0.1387 - val_accuracy: 0.9875\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0383 - accuracy: 0.9917 - val_loss: 0.1874 - val_accuracy: 0.9375\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0476 - accuracy: 0.9833 - val_loss: 0.1305 - val_accuracy: 0.9875\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0411 - accuracy: 0.9875 - val_loss: 0.1372 - val_accuracy: 0.9750\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0280 - accuracy: 0.9875 - val_loss: 0.1358 - val_accuracy: 0.9875\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0200 - accuracy: 0.9958 - val_loss: 0.1375 - val_accuracy: 0.9750\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0193 - accuracy: 1.0000 - val_loss: 0.1677 - val_accuracy: 0.9500\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0157 - accuracy: 1.0000 - val_loss: 0.1596 - val_accuracy: 0.9500\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0148 - accuracy: 1.0000 - val_loss: 0.1455 - val_accuracy: 0.9750\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0168 - accuracy: 0.9958 - val_loss: 0.1276 - val_accuracy: 0.9875\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0198 - accuracy: 0.9958 - val_loss: 0.1560 - val_accuracy: 0.9500\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0144 - accuracy: 1.0000 - val_loss: 0.1315 - val_accuracy: 0.9750\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0113 - accuracy: 1.0000 - val_loss: 0.1319 - val_accuracy: 0.9750\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0116 - accuracy: 1.0000 - val_loss: 0.1366 - val_accuracy: 0.9625\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0123 - accuracy: 1.0000 - val_loss: 0.1407 - val_accuracy: 0.9500\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0110 - accuracy: 1.0000 - val_loss: 0.1330 - val_accuracy: 0.9750\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.1931 - accuracy: 0.7417 - val_loss: 0.8962 - val_accuracy: 0.8250\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2887 - accuracy: 0.9375 - val_loss: 0.8289 - val_accuracy: 0.8875\n    Epoch 3/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.2917 - accuracy: 0.9292 - val_loss: 1.0508 - val_accuracy: 0.7750\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1171 - accuracy: 0.9375 - val_loss: 0.3567 - val_accuracy: 0.9000\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1440 - accuracy: 0.9667 - val_loss: 0.5518 - val_accuracy: 0.9125\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0865 - accuracy: 0.9667 - val_loss: 0.4741 - val_accuracy: 0.8875\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0741 - accuracy: 0.9625 - val_loss: 0.5518 - val_accuracy: 0.8750\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0932 - accuracy: 0.9708 - val_loss: 0.6380 - val_accuracy: 0.8000\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0643 - accuracy: 0.9750 - val_loss: 0.2487 - val_accuracy: 0.8750\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0349 - accuracy: 0.9875 - val_loss: 0.2825 - val_accuracy: 0.9000\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0263 - accuracy: 0.9958 - val_loss: 0.3367 - val_accuracy: 0.9125\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0262 - accuracy: 0.9875 - val_loss: 0.4447 - val_accuracy: 0.8750\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0335 - accuracy: 0.9875 - val_loss: 0.2811 - val_accuracy: 0.9250\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0372 - accuracy: 0.9875 - val_loss: 0.3062 - val_accuracy: 0.8875\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0173 - accuracy: 0.9958 - val_loss: 0.2279 - val_accuracy: 0.9250\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0193 - accuracy: 1.0000 - val_loss: 0.2167 - val_accuracy: 0.9000\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0151 - accuracy: 0.9958 - val_loss: 0.2347 - val_accuracy: 0.9250\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0364 - accuracy: 0.9833 - val_loss: 0.1951 - val_accuracy: 0.9375\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0101 - accuracy: 1.0000 - val_loss: 0.2882 - val_accuracy: 0.9000\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0082 - accuracy: 1.0000 - val_loss: 0.3238 - val_accuracy: 0.8875\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0133 - accuracy: 0.9958 - val_loss: 0.2041 - val_accuracy: 0.9125\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0081 - accuracy: 1.0000 - val_loss: 0.2149 - val_accuracy: 0.9125\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0082 - accuracy: 1.0000 - val_loss: 0.2310 - val_accuracy: 0.9250\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0082 - accuracy: 1.0000 - val_loss: 0.2408 - val_accuracy: 0.9000\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0066 - accuracy: 1.0000 - val_loss: 0.2809 - val_accuracy: 0.9125\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0072 - accuracy: 1.0000 - val_loss: 0.2405 - val_accuracy: 0.9000\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0062 - accuracy: 1.0000 - val_loss: 0.2073 - val_accuracy: 0.9125\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0060 - accuracy: 1.0000 - val_loss: 0.2400 - val_accuracy: 0.9000\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0065 - accuracy: 1.0000 - val_loss: 0.2699 - val_accuracy: 0.9125\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0058 - accuracy: 1.0000 - val_loss: 0.2146 - val_accuracy: 0.9125\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0053 - accuracy: 1.0000 - val_loss: 0.2020 - val_accuracy: 0.9250\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0056 - accuracy: 1.0000 - val_loss: 0.2387 - val_accuracy: 0.9250\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0058 - accuracy: 1.0000 - val_loss: 0.2535 - val_accuracy: 0.9000\n    Epoch 34/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0052 - accuracy: 1.0000 - val_loss: 0.2191 - val_accuracy: 0.9125\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0044 - accuracy: 1.0000 - val_loss: 0.2653 - val_accuracy: 0.9000\n    Epoch 36/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0042 - accuracy: 1.0000 - val_loss: 0.2355 - val_accuracy: 0.9125\n    Epoch 37/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0045 - accuracy: 1.0000 - val_loss: 0.2541 - val_accuracy: 0.9000\n    Epoch 38/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0042 - accuracy: 1.0000 - val_loss: 0.2040 - val_accuracy: 0.9125\n    Epoch 1/300\n    60/60 [==============================] - 1s 5ms/step - loss: 1.1212 - accuracy: 0.7833 - val_loss: 0.3166 - val_accuracy: 0.9000\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2774 - accuracy: 0.9292 - val_loss: 0.4820 - val_accuracy: 0.8875\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2341 - accuracy: 0.9500 - val_loss: 0.2393 - val_accuracy: 0.9000\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2236 - accuracy: 0.9458 - val_loss: 0.2810 - val_accuracy: 0.9125\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3063 - accuracy: 0.9125 - val_loss: 0.2856 - val_accuracy: 0.9250\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0861 - accuracy: 0.9792 - val_loss: 0.2975 - val_accuracy: 0.9125\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0884 - accuracy: 0.9708 - val_loss: 0.2874 - val_accuracy: 0.9000\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0758 - accuracy: 0.9667 - val_loss: 0.2549 - val_accuracy: 0.9000\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0725 - accuracy: 0.9750 - val_loss: 0.2104 - val_accuracy: 0.9375\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0553 - accuracy: 0.9792 - val_loss: 0.1844 - val_accuracy: 0.9250\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0270 - accuracy: 0.9958 - val_loss: 0.1821 - val_accuracy: 0.9375\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0223 - accuracy: 0.9917 - val_loss: 0.2838 - val_accuracy: 0.9000\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0356 - accuracy: 0.9875 - val_loss: 0.1611 - val_accuracy: 0.9375\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0177 - accuracy: 0.9958 - val_loss: 0.1640 - val_accuracy: 0.9375\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0186 - accuracy: 1.0000 - val_loss: 0.1606 - val_accuracy: 0.9500\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0182 - accuracy: 1.0000 - val_loss: 0.1908 - val_accuracy: 0.9375\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0153 - accuracy: 1.0000 - val_loss: 0.1580 - val_accuracy: 0.9500\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0118 - accuracy: 1.0000 - val_loss: 0.2045 - val_accuracy: 0.9500\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0157 - accuracy: 1.0000 - val_loss: 0.1631 - val_accuracy: 0.9625\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0136 - accuracy: 1.0000 - val_loss: 0.1584 - val_accuracy: 0.9500\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0105 - accuracy: 1.0000 - val_loss: 0.1660 - val_accuracy: 0.9625\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0119 - accuracy: 1.0000 - val_loss: 0.1901 - val_accuracy: 0.9625\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0102 - accuracy: 1.0000 - val_loss: 0.1680 - val_accuracy: 0.9500\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0106 - accuracy: 1.0000 - val_loss: 0.1576 - val_accuracy: 0.9500\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0094 - accuracy: 1.0000 - val_loss: 0.1756 - val_accuracy: 0.9500\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0084 - accuracy: 1.0000 - val_loss: 0.1642 - val_accuracy: 0.9500\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0086 - accuracy: 1.0000 - val_loss: 0.1601 - val_accuracy: 0.9375\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0082 - accuracy: 1.0000 - val_loss: 0.1564 - val_accuracy: 0.9500\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0073 - accuracy: 1.0000 - val_loss: 0.1590 - val_accuracy: 0.9500\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0082 - accuracy: 1.0000 - val_loss: 0.1619 - val_accuracy: 0.9625\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0065 - accuracy: 1.0000 - val_loss: 0.1621 - val_accuracy: 0.9625\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0083 - accuracy: 1.0000 - val_loss: 0.1676 - val_accuracy: 0.9625\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0063 - accuracy: 1.0000 - val_loss: 0.1726 - val_accuracy: 0.9500\n    Epoch 34/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0057 - accuracy: 1.0000 - val_loss: 0.1821 - val_accuracy: 0.9625\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0074 - accuracy: 1.0000 - val_loss: 0.1623 - val_accuracy: 0.9500\n    Epoch 36/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0109 - accuracy: 1.0000 - val_loss: 0.2013 - val_accuracy: 0.9250\n    Epoch 37/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0063 - accuracy: 1.0000 - val_loss: 0.1813 - val_accuracy: 0.9375\n    Epoch 38/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0057 - accuracy: 1.0000 - val_loss: 0.1690 - val_accuracy: 0.9500\n    Epoch 39/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0055 - accuracy: 1.0000 - val_loss: 0.1890 - val_accuracy: 0.9625\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.0060 - accuracy: 0.7750 - val_loss: 0.2498 - val_accuracy: 0.9250\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.4044 - accuracy: 0.9000 - val_loss: 0.6753 - val_accuracy: 0.9000\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2610 - accuracy: 0.9167 - val_loss: 0.3960 - val_accuracy: 0.9000\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1376 - accuracy: 0.9417 - val_loss: 0.1387 - val_accuracy: 0.9500\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0923 - accuracy: 0.9625 - val_loss: 0.2000 - val_accuracy: 0.9250\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1372 - accuracy: 0.9417 - val_loss: 0.2623 - val_accuracy: 0.9000\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0878 - accuracy: 0.9667 - val_loss: 0.1065 - val_accuracy: 0.9625\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0466 - accuracy: 0.9917 - val_loss: 0.1999 - val_accuracy: 0.9125\n    Epoch 9/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0669 - accuracy: 0.9708 - val_loss: 0.1299 - val_accuracy: 0.9625\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0358 - accuracy: 0.9917 - val_loss: 0.1087 - val_accuracy: 0.9250\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0345 - accuracy: 0.9875 - val_loss: 0.1290 - val_accuracy: 0.9500\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0313 - accuracy: 0.9875 - val_loss: 0.1115 - val_accuracy: 0.9375\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0287 - accuracy: 0.9958 - val_loss: 0.1300 - val_accuracy: 0.9625\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0268 - accuracy: 0.9958 - val_loss: 0.1110 - val_accuracy: 0.9625\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0209 - accuracy: 1.0000 - val_loss: 0.1130 - val_accuracy: 0.9625\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0174 - accuracy: 1.0000 - val_loss: 0.1395 - val_accuracy: 0.9500\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0176 - accuracy: 1.0000 - val_loss: 0.1270 - val_accuracy: 0.9625\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0166 - accuracy: 1.0000 - val_loss: 0.1776 - val_accuracy: 0.9125\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0205 - accuracy: 0.9958 - val_loss: 0.0974 - val_accuracy: 0.9625\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0169 - accuracy: 1.0000 - val_loss: 0.1088 - val_accuracy: 0.9625\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0134 - accuracy: 1.0000 - val_loss: 0.1084 - val_accuracy: 0.9625\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0136 - accuracy: 1.0000 - val_loss: 0.1064 - val_accuracy: 0.9625\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0117 - accuracy: 1.0000 - val_loss: 0.1208 - val_accuracy: 0.9375\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0122 - accuracy: 1.0000 - val_loss: 0.1071 - val_accuracy: 0.9625\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0120 - accuracy: 1.0000 - val_loss: 0.1181 - val_accuracy: 0.9625\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0126 - accuracy: 1.0000 - val_loss: 0.1257 - val_accuracy: 0.9625\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0093 - accuracy: 1.0000 - val_loss: 0.1028 - val_accuracy: 0.9625\n    Epoch 1/300\n    60/60 [==============================] - 0s 5ms/step - loss: 0.9162 - accuracy: 0.7625 - val_loss: 0.2690 - val_accuracy: 0.8875\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3431 - accuracy: 0.9167 - val_loss: 0.2880 - val_accuracy: 0.9250\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3033 - accuracy: 0.9250 - val_loss: 0.1184 - val_accuracy: 0.9625\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1801 - accuracy: 0.9500 - val_loss: 0.3068 - val_accuracy: 0.9000\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2246 - accuracy: 0.9292 - val_loss: 0.1606 - val_accuracy: 0.9625\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0902 - accuracy: 0.9583 - val_loss: 0.2429 - val_accuracy: 0.9375\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0742 - accuracy: 0.9667 - val_loss: 0.1394 - val_accuracy: 0.9500\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0606 - accuracy: 0.9750 - val_loss: 0.1442 - val_accuracy: 0.9375\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0449 - accuracy: 0.9875 - val_loss: 0.1482 - val_accuracy: 0.9375\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0487 - accuracy: 0.9750 - val_loss: 0.1387 - val_accuracy: 0.9375\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0241 - accuracy: 0.9958 - val_loss: 0.1458 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0214 - accuracy: 1.0000 - val_loss: 0.1577 - val_accuracy: 0.9500\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0194 - accuracy: 1.0000 - val_loss: 0.1391 - val_accuracy: 0.9750\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0185 - accuracy: 1.0000 - val_loss: 0.1902 - val_accuracy: 0.9375\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0170 - accuracy: 1.0000 - val_loss: 0.1251 - val_accuracy: 0.9500\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0313 - accuracy: 0.9875 - val_loss: 0.1382 - val_accuracy: 0.9500\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0167 - accuracy: 1.0000 - val_loss: 0.1400 - val_accuracy: 0.9750\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0158 - accuracy: 1.0000 - val_loss: 0.1304 - val_accuracy: 0.9875\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0141 - accuracy: 1.0000 - val_loss: 0.1175 - val_accuracy: 0.9750\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0170 - accuracy: 1.0000 - val_loss: 0.1208 - val_accuracy: 0.9750\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0112 - accuracy: 1.0000 - val_loss: 0.1140 - val_accuracy: 0.9875\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0113 - accuracy: 1.0000 - val_loss: 0.1117 - val_accuracy: 0.9750\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0098 - accuracy: 1.0000 - val_loss: 0.1054 - val_accuracy: 0.9625\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0105 - accuracy: 1.0000 - val_loss: 0.1142 - val_accuracy: 0.9625\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0101 - accuracy: 1.0000 - val_loss: 0.1211 - val_accuracy: 0.9750\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0104 - accuracy: 1.0000 - val_loss: 0.1277 - val_accuracy: 0.9750\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0086 - accuracy: 1.0000 - val_loss: 0.1344 - val_accuracy: 0.9750\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0101 - accuracy: 1.0000 - val_loss: 0.1184 - val_accuracy: 0.9750\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0083 - accuracy: 1.0000 - val_loss: 0.1160 - val_accuracy: 0.9625\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0100 - accuracy: 1.0000 - val_loss: 0.1288 - val_accuracy: 0.9625\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0097 - accuracy: 1.0000 - val_loss: 0.1333 - val_accuracy: 0.9625\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0085 - accuracy: 1.0000 - val_loss: 0.1283 - val_accuracy: 0.9625\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0084 - accuracy: 1.0000 - val_loss: 0.0969 - val_accuracy: 0.9625\n    Epoch 34/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0082 - accuracy: 1.0000 - val_loss: 0.1162 - val_accuracy: 0.9750\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0082 - accuracy: 1.0000 - val_loss: 0.1135 - val_accuracy: 0.9875\n    Epoch 36/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0060 - accuracy: 1.0000 - val_loss: 0.1000 - val_accuracy: 0.9750\n    Epoch 37/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0074 - accuracy: 1.0000 - val_loss: 0.1184 - val_accuracy: 0.9750\n    Epoch 38/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0063 - accuracy: 1.0000 - val_loss: 0.1047 - val_accuracy: 0.9625\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 0.7930 - accuracy: 0.7833 - val_loss: 1.2382 - val_accuracy: 0.8000\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3242 - accuracy: 0.9042 - val_loss: 0.7644 - val_accuracy: 0.8875\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2911 - accuracy: 0.9375 - val_loss: 0.5384 - val_accuracy: 0.8625\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2235 - accuracy: 0.9042 - val_loss: 0.5041 - val_accuracy: 0.8875\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1495 - accuracy: 0.9583 - val_loss: 0.4054 - val_accuracy: 0.8875\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0881 - accuracy: 0.9625 - val_loss: 0.3558 - val_accuracy: 0.8875\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0846 - accuracy: 0.9708 - val_loss: 0.4177 - val_accuracy: 0.9250\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0479 - accuracy: 0.9833 - val_loss: 0.3301 - val_accuracy: 0.9125\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0754 - accuracy: 0.9667 - val_loss: 0.4490 - val_accuracy: 0.9125\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0247 - accuracy: 0.9875 - val_loss: 0.3356 - val_accuracy: 0.9125\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0179 - accuracy: 0.9958 - val_loss: 0.3720 - val_accuracy: 0.9375\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0212 - accuracy: 0.9958 - val_loss: 0.3337 - val_accuracy: 0.9375\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0153 - accuracy: 1.0000 - val_loss: 0.4159 - val_accuracy: 0.9375\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0266 - accuracy: 0.9875 - val_loss: 0.3300 - val_accuracy: 0.9250\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0239 - accuracy: 1.0000 - val_loss: 0.3410 - val_accuracy: 0.9500\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0085 - accuracy: 1.0000 - val_loss: 0.3675 - val_accuracy: 0.9375\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0074 - accuracy: 1.0000 - val_loss: 0.3411 - val_accuracy: 0.9500\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0067 - accuracy: 1.0000 - val_loss: 0.3366 - val_accuracy: 0.9500\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0074 - accuracy: 1.0000 - val_loss: 0.3550 - val_accuracy: 0.9375\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0066 - accuracy: 1.0000 - val_loss: 0.3500 - val_accuracy: 0.9375\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0069 - accuracy: 1.0000 - val_loss: 0.3582 - val_accuracy: 0.9375\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0065 - accuracy: 1.0000 - val_loss: 0.3472 - val_accuracy: 0.9500\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0060 - accuracy: 1.0000 - val_loss: 0.3508 - val_accuracy: 0.9375\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0056 - accuracy: 1.0000 - val_loss: 0.3327 - val_accuracy: 0.9500\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0052 - accuracy: 1.0000 - val_loss: 0.3349 - val_accuracy: 0.9375\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0055 - accuracy: 1.0000 - val_loss: 0.3622 - val_accuracy: 0.9375\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0066 - accuracy: 1.0000 - val_loss: 0.3403 - val_accuracy: 0.9500\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0057 - accuracy: 1.0000 - val_loss: 0.3707 - val_accuracy: 0.9375\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0067 - accuracy: 1.0000 - val_loss: 0.3349 - val_accuracy: 0.9375\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0062 - accuracy: 1.0000 - val_loss: 0.3376 - val_accuracy: 0.9500\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0043 - accuracy: 1.0000 - val_loss: 0.3386 - val_accuracy: 0.9500\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0045 - accuracy: 1.0000 - val_loss: 0.3448 - val_accuracy: 0.9500\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0039 - accuracy: 1.0000 - val_loss: 0.3349 - val_accuracy: 0.9500\n    Epoch 34/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0036 - accuracy: 1.0000 - val_loss: 0.3445 - val_accuracy: 0.9500\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0038 - accuracy: 1.0000 - val_loss: 0.3320 - val_accuracy: 0.9500\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 0.9234 - accuracy: 0.7583 - val_loss: 0.4913 - val_accuracy: 0.9000\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3983 - accuracy: 0.9000 - val_loss: 0.2978 - val_accuracy: 0.9500\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3129 - accuracy: 0.9125 - val_loss: 0.1339 - val_accuracy: 0.9500\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1130 - accuracy: 0.9417 - val_loss: 0.2066 - val_accuracy: 0.9250\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1232 - accuracy: 0.9583 - val_loss: 0.1015 - val_accuracy: 0.9625\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1020 - accuracy: 0.9750 - val_loss: 0.0922 - val_accuracy: 0.9625\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1160 - accuracy: 0.9542 - val_loss: 0.0561 - val_accuracy: 0.9750\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0654 - accuracy: 0.9750 - val_loss: 0.0666 - val_accuracy: 0.9750\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0569 - accuracy: 0.9792 - val_loss: 0.0564 - val_accuracy: 0.9875\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0449 - accuracy: 0.9792 - val_loss: 0.0487 - val_accuracy: 0.9750\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0369 - accuracy: 0.9833 - val_loss: 0.0733 - val_accuracy: 0.9875\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0348 - accuracy: 0.9917 - val_loss: 0.0785 - val_accuracy: 0.9625\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0242 - accuracy: 1.0000 - val_loss: 0.0696 - val_accuracy: 0.9750\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0288 - accuracy: 1.0000 - val_loss: 0.0447 - val_accuracy: 1.0000\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0218 - accuracy: 1.0000 - val_loss: 0.0613 - val_accuracy: 0.9750\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0191 - accuracy: 0.9958 - val_loss: 0.0376 - val_accuracy: 1.0000\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0198 - accuracy: 1.0000 - val_loss: 0.0363 - val_accuracy: 1.0000\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0215 - accuracy: 0.9958 - val_loss: 0.0376 - val_accuracy: 0.9750\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0219 - accuracy: 0.9958 - val_loss: 0.0553 - val_accuracy: 0.9750\n    Epoch 20/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0243 - accuracy: 0.9958 - val_loss: 0.0526 - val_accuracy: 0.9750\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0180 - accuracy: 0.9958 - val_loss: 0.0464 - val_accuracy: 0.9875\n    Epoch 22/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0171 - accuracy: 1.0000 - val_loss: 0.0624 - val_accuracy: 0.9750\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0216 - accuracy: 1.0000 - val_loss: 0.0864 - val_accuracy: 0.9625\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0128 - accuracy: 1.0000 - val_loss: 0.0370 - val_accuracy: 1.0000\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0111 - accuracy: 1.0000 - val_loss: 0.0347 - val_accuracy: 1.0000\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0113 - accuracy: 1.0000 - val_loss: 0.0352 - val_accuracy: 0.9750\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0128 - accuracy: 1.0000 - val_loss: 0.0401 - val_accuracy: 1.0000\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0090 - accuracy: 1.0000 - val_loss: 0.0380 - val_accuracy: 0.9750\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0098 - accuracy: 1.0000 - val_loss: 0.0315 - val_accuracy: 0.9875\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0091 - accuracy: 1.0000 - val_loss: 0.0307 - val_accuracy: 1.0000\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0086 - accuracy: 1.0000 - val_loss: 0.0302 - val_accuracy: 1.0000\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0083 - accuracy: 1.0000 - val_loss: 0.0360 - val_accuracy: 1.0000\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0074 - accuracy: 1.0000 - val_loss: 0.0329 - val_accuracy: 0.9875\n    Epoch 34/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0074 - accuracy: 1.0000 - val_loss: 0.0457 - val_accuracy: 0.9750\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 0.8084 - accuracy: 0.7792 - val_loss: 0.2746 - val_accuracy: 0.9250\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3334 - accuracy: 0.9208 - val_loss: 0.2557 - val_accuracy: 0.9125\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1346 - accuracy: 0.9708 - val_loss: 0.0807 - val_accuracy: 0.9875\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0961 - accuracy: 0.9667 - val_loss: 0.0697 - val_accuracy: 0.9875\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0844 - accuracy: 0.9750 - val_loss: 0.0881 - val_accuracy: 0.9750\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0574 - accuracy: 0.9917 - val_loss: 0.0858 - val_accuracy: 0.9750\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0396 - accuracy: 0.9875 - val_loss: 0.1015 - val_accuracy: 0.9500\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0393 - accuracy: 0.9875 - val_loss: 0.0840 - val_accuracy: 0.9875\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0644 - accuracy: 0.9792 - val_loss: 0.1050 - val_accuracy: 0.9750\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0459 - accuracy: 0.9833 - val_loss: 0.0807 - val_accuracy: 0.9750\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0524 - accuracy: 0.9792 - val_loss: 0.0948 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0202 - accuracy: 1.0000 - val_loss: 0.0884 - val_accuracy: 0.9625\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0191 - accuracy: 1.0000 - val_loss: 0.0925 - val_accuracy: 0.9625\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0166 - accuracy: 1.0000 - val_loss: 0.1045 - val_accuracy: 0.9625\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0220 - accuracy: 1.0000 - val_loss: 0.0890 - val_accuracy: 0.9750\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0182 - accuracy: 0.9958 - val_loss: 0.0967 - val_accuracy: 0.9500\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0190 - accuracy: 1.0000 - val_loss: 0.0915 - val_accuracy: 0.9625\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0132 - accuracy: 1.0000 - val_loss: 0.0900 - val_accuracy: 0.9750\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0121 - accuracy: 1.0000 - val_loss: 0.0879 - val_accuracy: 0.9625\n    Epoch 20/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0123 - accuracy: 0.9958 - val_loss: 0.0968 - val_accuracy: 0.9625\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0115 - accuracy: 1.0000 - val_loss: 0.0953 - val_accuracy: 0.9625\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0110 - accuracy: 1.0000 - val_loss: 0.0945 - val_accuracy: 0.9625\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0128 - accuracy: 1.0000 - val_loss: 0.1145 - val_accuracy: 0.9500\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 0.7298 - accuracy: 0.7833 - val_loss: 0.3033 - val_accuracy: 0.9000\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.4458 - accuracy: 0.8667 - val_loss: 0.2989 - val_accuracy: 0.9250\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1178 - accuracy: 0.9708 - val_loss: 0.3177 - val_accuracy: 0.9625\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0821 - accuracy: 0.9708 - val_loss: 0.2478 - val_accuracy: 0.9625\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0860 - accuracy: 0.9708 - val_loss: 0.2740 - val_accuracy: 0.9625\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0620 - accuracy: 0.9792 - val_loss: 0.2475 - val_accuracy: 0.9500\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0838 - accuracy: 0.9667 - val_loss: 0.2479 - val_accuracy: 0.9625\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0671 - accuracy: 0.9750 - val_loss: 0.3780 - val_accuracy: 0.9250\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0484 - accuracy: 0.9792 - val_loss: 0.2885 - val_accuracy: 0.9625\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0227 - accuracy: 1.0000 - val_loss: 0.2239 - val_accuracy: 0.9625\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0280 - accuracy: 0.9917 - val_loss: 0.2516 - val_accuracy: 0.9500\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0652 - accuracy: 0.9792 - val_loss: 0.2299 - val_accuracy: 0.9625\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0240 - accuracy: 0.9958 - val_loss: 0.2574 - val_accuracy: 0.9500\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0177 - accuracy: 0.9958 - val_loss: 0.2279 - val_accuracy: 0.9625\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0221 - accuracy: 0.9958 - val_loss: 0.2290 - val_accuracy: 0.9625\n    Epoch 16/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0217 - accuracy: 0.9958 - val_loss: 0.2513 - val_accuracy: 0.9625\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0198 - accuracy: 0.9958 - val_loss: 0.2252 - val_accuracy: 0.9625\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0172 - accuracy: 0.9958 - val_loss: 0.2399 - val_accuracy: 0.9500\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0156 - accuracy: 1.0000 - val_loss: 0.2353 - val_accuracy: 0.9625\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0118 - accuracy: 1.0000 - val_loss: 0.2237 - val_accuracy: 0.9625\n    Epoch 21/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0115 - accuracy: 1.0000 - val_loss: 0.2318 - val_accuracy: 0.9625\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0111 - accuracy: 1.0000 - val_loss: 0.2312 - val_accuracy: 0.9625\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0102 - accuracy: 1.0000 - val_loss: 0.2371 - val_accuracy: 0.9625\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.0005 - accuracy: 0.7333 - val_loss: 0.3324 - val_accuracy: 0.9250\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2228 - accuracy: 0.9208 - val_loss: 0.2018 - val_accuracy: 0.9000\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2329 - accuracy: 0.9250 - val_loss: 0.2660 - val_accuracy: 0.9250\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1357 - accuracy: 0.9583 - val_loss: 0.1324 - val_accuracy: 0.9500\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0650 - accuracy: 0.9833 - val_loss: 0.1007 - val_accuracy: 0.9625\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0659 - accuracy: 0.9833 - val_loss: 0.1114 - val_accuracy: 0.9750\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0507 - accuracy: 0.9833 - val_loss: 0.2660 - val_accuracy: 0.9250\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0482 - accuracy: 0.9875 - val_loss: 0.1449 - val_accuracy: 0.9750\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0844 - accuracy: 0.9708 - val_loss: 0.1508 - val_accuracy: 0.9500\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0402 - accuracy: 0.9917 - val_loss: 0.1072 - val_accuracy: 0.9750\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0479 - accuracy: 0.9792 - val_loss: 0.1630 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0453 - accuracy: 0.9875 - val_loss: 0.1489 - val_accuracy: 0.9500\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0287 - accuracy: 0.9917 - val_loss: 0.1380 - val_accuracy: 0.9750\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0241 - accuracy: 0.9875 - val_loss: 0.1239 - val_accuracy: 0.9750\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0167 - accuracy: 0.9958 - val_loss: 0.0899 - val_accuracy: 0.9750\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0216 - accuracy: 0.9917 - val_loss: 0.1099 - val_accuracy: 0.9625\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0171 - accuracy: 1.0000 - val_loss: 0.1284 - val_accuracy: 0.9625\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0210 - accuracy: 0.9958 - val_loss: 0.1135 - val_accuracy: 0.9625\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0184 - accuracy: 1.0000 - val_loss: 0.1051 - val_accuracy: 0.9750\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0123 - accuracy: 1.0000 - val_loss: 0.0937 - val_accuracy: 0.9750\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0121 - accuracy: 1.0000 - val_loss: 0.1108 - val_accuracy: 0.9750\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0128 - accuracy: 1.0000 - val_loss: 0.1056 - val_accuracy: 0.9750\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0100 - accuracy: 1.0000 - val_loss: 0.1268 - val_accuracy: 0.9500\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0126 - accuracy: 1.0000 - val_loss: 0.1108 - val_accuracy: 0.9750\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0102 - accuracy: 1.0000 - val_loss: 0.0897 - val_accuracy: 0.9750\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0107 - accuracy: 1.0000 - val_loss: 0.0918 - val_accuracy: 0.9625\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.4192 - accuracy: 0.7458 - val_loss: 0.8777 - val_accuracy: 0.8000\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3784 - accuracy: 0.9125 - val_loss: 0.5305 - val_accuracy: 0.8125\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1439 - accuracy: 0.9625 - val_loss: 0.2876 - val_accuracy: 0.8875\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1697 - accuracy: 0.9458 - val_loss: 0.3300 - val_accuracy: 0.8875\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0829 - accuracy: 0.9833 - val_loss: 0.1377 - val_accuracy: 0.9375\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0612 - accuracy: 0.9750 - val_loss: 0.1554 - val_accuracy: 0.9375\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0642 - accuracy: 0.9792 - val_loss: 0.1258 - val_accuracy: 0.9625\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0371 - accuracy: 0.9917 - val_loss: 0.1357 - val_accuracy: 0.9500\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0575 - accuracy: 0.9750 - val_loss: 0.1479 - val_accuracy: 0.9500\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0513 - accuracy: 0.9833 - val_loss: 0.1400 - val_accuracy: 0.9625\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0393 - accuracy: 0.9833 - val_loss: 0.1257 - val_accuracy: 0.9750\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0323 - accuracy: 0.9917 - val_loss: 0.1471 - val_accuracy: 0.9375\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0425 - accuracy: 0.9833 - val_loss: 0.1599 - val_accuracy: 0.9625\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0313 - accuracy: 0.9917 - val_loss: 0.1510 - val_accuracy: 0.9750\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0242 - accuracy: 0.9958 - val_loss: 0.1398 - val_accuracy: 0.9625\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0221 - accuracy: 0.9958 - val_loss: 0.1400 - val_accuracy: 0.9500\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0228 - accuracy: 0.9958 - val_loss: 0.1309 - val_accuracy: 0.9625\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0247 - accuracy: 0.9917 - val_loss: 0.1355 - val_accuracy: 0.9750\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0246 - accuracy: 0.9958 - val_loss: 0.1495 - val_accuracy: 0.9500\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0430 - accuracy: 0.9833 - val_loss: 0.1621 - val_accuracy: 0.9625\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0191 - accuracy: 0.9958 - val_loss: 0.1323 - val_accuracy: 0.9750\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0155 - accuracy: 0.9958 - val_loss: 0.1337 - val_accuracy: 0.9750\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0131 - accuracy: 1.0000 - val_loss: 0.1250 - val_accuracy: 0.9750\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0131 - accuracy: 1.0000 - val_loss: 0.1226 - val_accuracy: 0.9750\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0112 - accuracy: 1.0000 - val_loss: 0.1337 - val_accuracy: 0.9750\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0132 - accuracy: 1.0000 - val_loss: 0.1213 - val_accuracy: 0.9750\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0104 - accuracy: 1.0000 - val_loss: 0.1153 - val_accuracy: 0.9750\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0099 - accuracy: 1.0000 - val_loss: 0.1220 - val_accuracy: 0.9750\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0117 - accuracy: 1.0000 - val_loss: 0.1177 - val_accuracy: 0.9750\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0093 - accuracy: 1.0000 - val_loss: 0.1264 - val_accuracy: 0.9750\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0093 - accuracy: 1.0000 - val_loss: 0.1224 - val_accuracy: 0.9750\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.1409 - accuracy: 0.7000 - val_loss: 0.2143 - val_accuracy: 0.9375\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2142 - accuracy: 0.9208 - val_loss: 0.0745 - val_accuracy: 0.9875\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1693 - accuracy: 0.9375 - val_loss: 0.1070 - val_accuracy: 0.9625\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1412 - accuracy: 0.9542 - val_loss: 0.1309 - val_accuracy: 0.9625\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0852 - accuracy: 0.9667 - val_loss: 0.1588 - val_accuracy: 0.9250\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0894 - accuracy: 0.9625 - val_loss: 0.0923 - val_accuracy: 0.9625\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0552 - accuracy: 0.9833 - val_loss: 0.0656 - val_accuracy: 0.9875\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0949 - accuracy: 0.9542 - val_loss: 0.1774 - val_accuracy: 0.9125\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0839 - accuracy: 0.9625 - val_loss: 0.0563 - val_accuracy: 0.9875\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0433 - accuracy: 0.9875 - val_loss: 0.0636 - val_accuracy: 0.9875\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0333 - accuracy: 0.9958 - val_loss: 0.0544 - val_accuracy: 0.9875\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0372 - accuracy: 0.9875 - val_loss: 0.0648 - val_accuracy: 0.9750\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0315 - accuracy: 0.9917 - val_loss: 0.0572 - val_accuracy: 0.9875\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0278 - accuracy: 0.9958 - val_loss: 0.0541 - val_accuracy: 0.9875\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0300 - accuracy: 0.9958 - val_loss: 0.0767 - val_accuracy: 0.9500\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0267 - accuracy: 0.9958 - val_loss: 0.0517 - val_accuracy: 0.9875\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0264 - accuracy: 0.9917 - val_loss: 0.0471 - val_accuracy: 0.9875\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0256 - accuracy: 1.0000 - val_loss: 0.0449 - val_accuracy: 0.9875\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0209 - accuracy: 0.9917 - val_loss: 0.0548 - val_accuracy: 0.9875\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0426 - accuracy: 0.9792 - val_loss: 0.0500 - val_accuracy: 0.9875\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0247 - accuracy: 1.0000 - val_loss: 0.0417 - val_accuracy: 0.9875\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0179 - accuracy: 1.0000 - val_loss: 0.0708 - val_accuracy: 0.9625\n    Epoch 1/300\n    60/60 [==============================] - 1s 5ms/step - loss: 0.8695 - accuracy: 0.7625 - val_loss: 0.5480 - val_accuracy: 0.8625\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1788 - accuracy: 0.9500 - val_loss: 0.4576 - val_accuracy: 0.8625\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2131 - accuracy: 0.9208 - val_loss: 0.2512 - val_accuracy: 0.9375\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1455 - accuracy: 0.9458 - val_loss: 0.2164 - val_accuracy: 0.9375\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0574 - accuracy: 0.9750 - val_loss: 0.2038 - val_accuracy: 0.9500\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0498 - accuracy: 0.9792 - val_loss: 0.3113 - val_accuracy: 0.9000\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0622 - accuracy: 0.9833 - val_loss: 0.1996 - val_accuracy: 0.9500\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0417 - accuracy: 0.9875 - val_loss: 0.1771 - val_accuracy: 0.9500\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0358 - accuracy: 0.9958 - val_loss: 0.1874 - val_accuracy: 0.9500\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0336 - accuracy: 0.9875 - val_loss: 0.1873 - val_accuracy: 0.9500\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0392 - accuracy: 0.9917 - val_loss: 0.1776 - val_accuracy: 0.9500\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0250 - accuracy: 0.9958 - val_loss: 0.2259 - val_accuracy: 0.9500\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0368 - accuracy: 0.9875 - val_loss: 0.1890 - val_accuracy: 0.9500\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0301 - accuracy: 0.9958 - val_loss: 0.2546 - val_accuracy: 0.9375\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0372 - accuracy: 0.9875 - val_loss: 0.1693 - val_accuracy: 0.9625\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0255 - accuracy: 0.9958 - val_loss: 0.1839 - val_accuracy: 0.9500\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0230 - accuracy: 0.9875 - val_loss: 0.1947 - val_accuracy: 0.9500\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0241 - accuracy: 0.9958 - val_loss: 0.1808 - val_accuracy: 0.9625\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0186 - accuracy: 0.9958 - val_loss: 0.1801 - val_accuracy: 0.9625\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0203 - accuracy: 0.9917 - val_loss: 0.1774 - val_accuracy: 0.9375\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0201 - accuracy: 0.9958 - val_loss: 0.1683 - val_accuracy: 0.9500\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0130 - accuracy: 1.0000 - val_loss: 0.1719 - val_accuracy: 0.9500\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0181 - accuracy: 1.0000 - val_loss: 0.1743 - val_accuracy: 0.9375\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0199 - accuracy: 0.9958 - val_loss: 0.1662 - val_accuracy: 0.9500\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0156 - accuracy: 1.0000 - val_loss: 0.1842 - val_accuracy: 0.9375\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0132 - accuracy: 1.0000 - val_loss: 0.1666 - val_accuracy: 0.9625\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0089 - accuracy: 1.0000 - val_loss: 0.1738 - val_accuracy: 0.9625\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0098 - accuracy: 1.0000 - val_loss: 0.1743 - val_accuracy: 0.9625\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0104 - accuracy: 1.0000 - val_loss: 0.1799 - val_accuracy: 0.9500\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0093 - accuracy: 1.0000 - val_loss: 0.1644 - val_accuracy: 0.9625\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0088 - accuracy: 1.0000 - val_loss: 0.1667 - val_accuracy: 0.9625\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0116 - accuracy: 1.0000 - val_loss: 0.1632 - val_accuracy: 0.9500\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0077 - accuracy: 1.0000 - val_loss: 0.1734 - val_accuracy: 0.9500\n    Epoch 34/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0093 - accuracy: 1.0000 - val_loss: 0.1669 - val_accuracy: 0.9500\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0075 - accuracy: 1.0000 - val_loss: 0.1632 - val_accuracy: 0.9625\n    Epoch 1/300\n    60/60 [==============================] - 1s 4ms/step - loss: 1.1194 - accuracy: 0.7292 - val_loss: 0.2989 - val_accuracy: 0.9375\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3255 - accuracy: 0.9000 - val_loss: 0.1806 - val_accuracy: 0.9625\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1258 - accuracy: 0.9583 - val_loss: 0.1411 - val_accuracy: 0.9750\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0947 - accuracy: 0.9750 - val_loss: 0.1580 - val_accuracy: 0.9750\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0784 - accuracy: 0.9750 - val_loss: 0.1311 - val_accuracy: 0.9750\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1034 - accuracy: 0.9667 - val_loss: 0.1160 - val_accuracy: 0.9875\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0545 - accuracy: 0.9667 - val_loss: 0.1109 - val_accuracy: 0.9875\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0818 - accuracy: 0.9708 - val_loss: 0.1155 - val_accuracy: 0.9750\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0474 - accuracy: 0.9917 - val_loss: 0.1459 - val_accuracy: 0.9625\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0542 - accuracy: 0.9833 - val_loss: 0.1016 - val_accuracy: 0.9875\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0444 - accuracy: 0.9833 - val_loss: 0.1455 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0437 - accuracy: 0.9917 - val_loss: 0.1325 - val_accuracy: 0.9625\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0352 - accuracy: 0.9875 - val_loss: 0.1150 - val_accuracy: 0.9875\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0276 - accuracy: 1.0000 - val_loss: 0.1898 - val_accuracy: 0.9500\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0390 - accuracy: 0.9917 - val_loss: 0.1368 - val_accuracy: 0.9750\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0265 - accuracy: 0.9958 - val_loss: 0.1824 - val_accuracy: 0.9500\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0279 - accuracy: 0.9875 - val_loss: 0.1203 - val_accuracy: 0.9875\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0268 - accuracy: 0.9917 - val_loss: 0.1949 - val_accuracy: 0.9500\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0391 - accuracy: 0.9875 - val_loss: 0.1202 - val_accuracy: 0.9750\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0215 - accuracy: 0.9958 - val_loss: 0.1176 - val_accuracy: 0.9875\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0224 - accuracy: 0.9958 - val_loss: 0.1221 - val_accuracy: 0.9875\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0172 - accuracy: 1.0000 - val_loss: 0.1203 - val_accuracy: 0.9875\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0244 - accuracy: 0.9958 - val_loss: 0.1140 - val_accuracy: 0.9875\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0246 - accuracy: 0.9958 - val_loss: 0.1076 - val_accuracy: 0.9875\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0138 - accuracy: 1.0000 - val_loss: 0.1114 - val_accuracy: 0.9875\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0137 - accuracy: 1.0000 - val_loss: 0.1147 - val_accuracy: 0.9875\n    Epoch 1/300\n    60/60 [==============================] - 1s 5ms/step - loss: 0.8422 - accuracy: 0.7583 - val_loss: 0.3845 - val_accuracy: 0.9125\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3386 - accuracy: 0.9292 - val_loss: 0.2871 - val_accuracy: 0.9500\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1961 - accuracy: 0.9458 - val_loss: 0.1947 - val_accuracy: 0.9000\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1229 - accuracy: 0.9458 - val_loss: 0.1272 - val_accuracy: 0.9625\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0548 - accuracy: 0.9875 - val_loss: 0.1473 - val_accuracy: 0.9625\n    Epoch 6/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0378 - accuracy: 0.9958 - val_loss: 0.2337 - val_accuracy: 0.9250\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0453 - accuracy: 0.9875 - val_loss: 0.1392 - val_accuracy: 0.9500\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0271 - accuracy: 0.9958 - val_loss: 0.1306 - val_accuracy: 0.9500\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0296 - accuracy: 0.9917 - val_loss: 0.1508 - val_accuracy: 0.9250\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0250 - accuracy: 0.9958 - val_loss: 0.1277 - val_accuracy: 0.9375\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0233 - accuracy: 0.9958 - val_loss: 0.1345 - val_accuracy: 0.9375\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0194 - accuracy: 0.9958 - val_loss: 0.1340 - val_accuracy: 0.9375\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0166 - accuracy: 0.9958 - val_loss: 0.1249 - val_accuracy: 0.9375\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0163 - accuracy: 1.0000 - val_loss: 0.1450 - val_accuracy: 0.9500\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0142 - accuracy: 0.9958 - val_loss: 0.1472 - val_accuracy: 0.9375\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0193 - accuracy: 0.9917 - val_loss: 0.1482 - val_accuracy: 0.9375\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0123 - accuracy: 1.0000 - val_loss: 0.1574 - val_accuracy: 0.9500\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0108 - accuracy: 1.0000 - val_loss: 0.1398 - val_accuracy: 0.9375\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0106 - accuracy: 1.0000 - val_loss: 0.1351 - val_accuracy: 0.9375\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0095 - accuracy: 1.0000 - val_loss: 0.1462 - val_accuracy: 0.9375\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0093 - accuracy: 1.0000 - val_loss: 0.1419 - val_accuracy: 0.9375\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0089 - accuracy: 1.0000 - val_loss: 0.1535 - val_accuracy: 0.9250\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0088 - accuracy: 1.0000 - val_loss: 0.1437 - val_accuracy: 0.9375\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0079 - accuracy: 1.0000 - val_loss: 0.1395 - val_accuracy: 0.9375\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.3843 - accuracy: 0.7375 - val_loss: 0.5551 - val_accuracy: 0.8625\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2170 - accuracy: 0.9417 - val_loss: 0.4449 - val_accuracy: 0.8875\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1665 - accuracy: 0.9500 - val_loss: 0.2495 - val_accuracy: 0.9250\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0874 - accuracy: 0.9667 - val_loss: 0.2590 - val_accuracy: 0.9125\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0767 - accuracy: 0.9792 - val_loss: 0.1997 - val_accuracy: 0.9500\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0607 - accuracy: 0.9917 - val_loss: 0.2323 - val_accuracy: 0.9375\n    Epoch 7/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0578 - accuracy: 0.9875 - val_loss: 0.2086 - val_accuracy: 0.9250\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0433 - accuracy: 0.9875 - val_loss: 0.2234 - val_accuracy: 0.9375\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0691 - accuracy: 0.9750 - val_loss: 0.2001 - val_accuracy: 0.9375\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0371 - accuracy: 0.9958 - val_loss: 0.2204 - val_accuracy: 0.9125\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0275 - accuracy: 0.9917 - val_loss: 0.2464 - val_accuracy: 0.9250\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0319 - accuracy: 0.9917 - val_loss: 0.2449 - val_accuracy: 0.9125\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0338 - accuracy: 0.9875 - val_loss: 0.2055 - val_accuracy: 0.9375\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0191 - accuracy: 1.0000 - val_loss: 0.2327 - val_accuracy: 0.9250\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0265 - accuracy: 0.9958 - val_loss: 0.1881 - val_accuracy: 0.9375\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0170 - accuracy: 1.0000 - val_loss: 0.2200 - val_accuracy: 0.9375\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0203 - accuracy: 1.0000 - val_loss: 0.2003 - val_accuracy: 0.9375\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0171 - accuracy: 0.9958 - val_loss: 0.1836 - val_accuracy: 0.9500\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0182 - accuracy: 1.0000 - val_loss: 0.1839 - val_accuracy: 0.9375\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0141 - accuracy: 1.0000 - val_loss: 0.1941 - val_accuracy: 0.9375\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0140 - accuracy: 1.0000 - val_loss: 0.2009 - val_accuracy: 0.9375\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0138 - accuracy: 1.0000 - val_loss: 0.2133 - val_accuracy: 0.9375\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0175 - accuracy: 1.0000 - val_loss: 0.1985 - val_accuracy: 0.9500\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0171 - accuracy: 0.9958 - val_loss: 0.2037 - val_accuracy: 0.9375\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0122 - accuracy: 1.0000 - val_loss: 0.2019 - val_accuracy: 0.9375\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.1996 - accuracy: 0.7792 - val_loss: 0.6779 - val_accuracy: 0.8500\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2597 - accuracy: 0.9000 - val_loss: 0.2942 - val_accuracy: 0.9375\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1637 - accuracy: 0.9292 - val_loss: 0.3018 - val_accuracy: 0.9000\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1021 - accuracy: 0.9708 - val_loss: 0.1662 - val_accuracy: 0.9500\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0664 - accuracy: 0.9750 - val_loss: 0.1837 - val_accuracy: 0.9500\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0747 - accuracy: 0.9667 - val_loss: 0.2197 - val_accuracy: 0.9375\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0929 - accuracy: 0.9583 - val_loss: 0.1807 - val_accuracy: 0.9625\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0900 - accuracy: 0.9708 - val_loss: 0.1638 - val_accuracy: 0.9625\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0642 - accuracy: 0.9750 - val_loss: 0.1579 - val_accuracy: 0.9750\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0320 - accuracy: 0.9875 - val_loss: 0.1668 - val_accuracy: 0.9125\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0699 - accuracy: 0.9667 - val_loss: 0.1375 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0259 - accuracy: 1.0000 - val_loss: 0.1171 - val_accuracy: 0.9750\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0387 - accuracy: 0.9833 - val_loss: 0.1441 - val_accuracy: 0.9750\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0350 - accuracy: 0.9875 - val_loss: 0.1385 - val_accuracy: 0.9500\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0425 - accuracy: 0.9833 - val_loss: 0.1165 - val_accuracy: 0.9500\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0421 - accuracy: 0.9792 - val_loss: 0.1081 - val_accuracy: 0.9500\n    Epoch 17/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0193 - accuracy: 1.0000 - val_loss: 0.1167 - val_accuracy: 0.9500\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0249 - accuracy: 0.9875 - val_loss: 0.1211 - val_accuracy: 0.9750\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0232 - accuracy: 0.9958 - val_loss: 0.1165 - val_accuracy: 0.9750\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0138 - accuracy: 1.0000 - val_loss: 0.1164 - val_accuracy: 0.9750\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0118 - accuracy: 1.0000 - val_loss: 0.1165 - val_accuracy: 0.9750\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0238 - accuracy: 0.9917 - val_loss: 0.1003 - val_accuracy: 0.9750\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0169 - accuracy: 0.9958 - val_loss: 0.1027 - val_accuracy: 0.9750\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0127 - accuracy: 1.0000 - val_loss: 0.1080 - val_accuracy: 0.9750\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0113 - accuracy: 1.0000 - val_loss: 0.1297 - val_accuracy: 0.9750\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0116 - accuracy: 1.0000 - val_loss: 0.1302 - val_accuracy: 0.9750\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0109 - accuracy: 1.0000 - val_loss: 0.1055 - val_accuracy: 0.9750\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0131 - accuracy: 1.0000 - val_loss: 0.1238 - val_accuracy: 0.9750\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0101 - accuracy: 1.0000 - val_loss: 0.1054 - val_accuracy: 0.9750\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.1125 - accuracy: 0.7292 - val_loss: 0.3032 - val_accuracy: 0.9375\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2730 - accuracy: 0.9083 - val_loss: 0.2043 - val_accuracy: 0.9000\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1396 - accuracy: 0.9542 - val_loss: 0.3525 - val_accuracy: 0.9000\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1331 - accuracy: 0.9583 - val_loss: 0.0956 - val_accuracy: 0.9500\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0620 - accuracy: 0.9833 - val_loss: 0.1780 - val_accuracy: 0.9375\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0557 - accuracy: 0.9875 - val_loss: 0.1227 - val_accuracy: 0.9500\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0537 - accuracy: 0.9875 - val_loss: 0.1749 - val_accuracy: 0.9375\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0531 - accuracy: 0.9875 - val_loss: 0.2129 - val_accuracy: 0.9250\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0506 - accuracy: 0.9875 - val_loss: 0.1011 - val_accuracy: 0.9500\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0395 - accuracy: 0.9875 - val_loss: 0.1076 - val_accuracy: 0.9625\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0357 - accuracy: 0.9875 - val_loss: 0.1256 - val_accuracy: 0.9500\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0427 - accuracy: 0.9833 - val_loss: 0.1010 - val_accuracy: 0.9375\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0334 - accuracy: 0.9917 - val_loss: 0.1014 - val_accuracy: 0.9750\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0256 - accuracy: 0.9958 - val_loss: 0.1096 - val_accuracy: 0.9500\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0214 - accuracy: 1.0000 - val_loss: 0.1220 - val_accuracy: 0.9500\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0316 - accuracy: 0.9917 - val_loss: 0.1042 - val_accuracy: 0.9625\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0208 - accuracy: 1.0000 - val_loss: 0.0949 - val_accuracy: 0.9625\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0157 - accuracy: 1.0000 - val_loss: 0.0873 - val_accuracy: 0.9625\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0212 - accuracy: 1.0000 - val_loss: 0.0743 - val_accuracy: 0.9625\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0171 - accuracy: 1.0000 - val_loss: 0.1016 - val_accuracy: 0.9500\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0180 - accuracy: 1.0000 - val_loss: 0.0926 - val_accuracy: 0.9375\n    Epoch 22/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0146 - accuracy: 1.0000 - val_loss: 0.0981 - val_accuracy: 0.9625\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0140 - accuracy: 1.0000 - val_loss: 0.1094 - val_accuracy: 0.9625\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0124 - accuracy: 1.0000 - val_loss: 0.0898 - val_accuracy: 0.9500\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0133 - accuracy: 1.0000 - val_loss: 0.0858 - val_accuracy: 0.9500\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0122 - accuracy: 1.0000 - val_loss: 0.1042 - val_accuracy: 0.9625\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0107 - accuracy: 1.0000 - val_loss: 0.0872 - val_accuracy: 0.9625\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0114 - accuracy: 1.0000 - val_loss: 0.0943 - val_accuracy: 0.9500\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0101 - accuracy: 1.0000 - val_loss: 0.0742 - val_accuracy: 0.9625\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0099 - accuracy: 1.0000 - val_loss: 0.0967 - val_accuracy: 0.9500\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0103 - accuracy: 1.0000 - val_loss: 0.0847 - val_accuracy: 0.9500\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0083 - accuracy: 1.0000 - val_loss: 0.0889 - val_accuracy: 0.9625\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0100 - accuracy: 1.0000 - val_loss: 0.0737 - val_accuracy: 0.9625\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 0.8562 - accuracy: 0.8000 - val_loss: 0.4008 - val_accuracy: 0.8875\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2710 - accuracy: 0.9375 - val_loss: 0.3270 - val_accuracy: 0.8875\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1583 - accuracy: 0.9458 - val_loss: 0.2259 - val_accuracy: 0.9250\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1109 - accuracy: 0.9667 - val_loss: 0.1576 - val_accuracy: 0.9500\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1056 - accuracy: 0.9667 - val_loss: 0.1870 - val_accuracy: 0.9125\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1018 - accuracy: 0.9625 - val_loss: 0.1524 - val_accuracy: 0.9750\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0518 - accuracy: 0.9792 - val_loss: 0.1337 - val_accuracy: 0.9375\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0669 - accuracy: 0.9708 - val_loss: 0.1306 - val_accuracy: 0.9250\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0370 - accuracy: 0.9875 - val_loss: 0.1236 - val_accuracy: 0.9375\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0350 - accuracy: 0.9833 - val_loss: 0.2586 - val_accuracy: 0.9125\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0509 - accuracy: 0.9875 - val_loss: 0.0966 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0258 - accuracy: 0.9958 - val_loss: 0.1005 - val_accuracy: 0.9625\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0351 - accuracy: 0.9875 - val_loss: 0.0959 - val_accuracy: 0.9625\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0253 - accuracy: 0.9958 - val_loss: 0.0856 - val_accuracy: 0.9750\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0263 - accuracy: 0.9958 - val_loss: 0.0855 - val_accuracy: 0.9625\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0226 - accuracy: 0.9958 - val_loss: 0.0935 - val_accuracy: 0.9625\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0259 - accuracy: 0.9958 - val_loss: 0.1011 - val_accuracy: 0.9625\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0213 - accuracy: 0.9958 - val_loss: 0.0934 - val_accuracy: 0.9625\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0196 - accuracy: 0.9958 - val_loss: 0.1560 - val_accuracy: 0.9375\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0231 - accuracy: 0.9958 - val_loss: 0.0907 - val_accuracy: 0.9625\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0212 - accuracy: 0.9958 - val_loss: 0.0951 - val_accuracy: 0.9625\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0135 - accuracy: 1.0000 - val_loss: 0.0891 - val_accuracy: 0.9625\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0151 - accuracy: 1.0000 - val_loss: 0.0886 - val_accuracy: 0.9625\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0129 - accuracy: 1.0000 - val_loss: 0.0930 - val_accuracy: 0.9750\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0160 - accuracy: 1.0000 - val_loss: 0.1103 - val_accuracy: 0.9750\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0167 - accuracy: 1.0000 - val_loss: 0.1079 - val_accuracy: 0.9750\n    Epoch 1/300\n    60/60 [==============================] - 1s 5ms/step - loss: 1.4836 - accuracy: 0.7042 - val_loss: 0.1358 - val_accuracy: 0.9750\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3287 - accuracy: 0.9083 - val_loss: 0.2701 - val_accuracy: 0.8625\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2194 - accuracy: 0.9125 - val_loss: 0.0608 - val_accuracy: 0.9875\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1576 - accuracy: 0.9375 - val_loss: 0.0442 - val_accuracy: 0.9875\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0966 - accuracy: 0.9750 - val_loss: 0.0589 - val_accuracy: 0.9750\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1012 - accuracy: 0.9750 - val_loss: 0.0367 - val_accuracy: 0.9875\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0539 - accuracy: 0.9917 - val_loss: 0.0480 - val_accuracy: 0.9750\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0552 - accuracy: 0.9875 - val_loss: 0.0473 - val_accuracy: 0.9750\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0738 - accuracy: 0.9708 - val_loss: 0.0436 - val_accuracy: 0.9875\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0578 - accuracy: 0.9833 - val_loss: 0.0157 - val_accuracy: 1.0000\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0458 - accuracy: 0.9917 - val_loss: 0.0170 - val_accuracy: 1.0000\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0570 - accuracy: 0.9792 - val_loss: 0.0165 - val_accuracy: 1.0000\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0600 - accuracy: 0.9792 - val_loss: 0.0242 - val_accuracy: 1.0000\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0522 - accuracy: 0.9875 - val_loss: 0.0329 - val_accuracy: 0.9875\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0474 - accuracy: 0.9833 - val_loss: 0.0162 - val_accuracy: 1.0000\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0246 - accuracy: 1.0000 - val_loss: 0.0198 - val_accuracy: 1.0000\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0326 - accuracy: 0.9875 - val_loss: 0.0233 - val_accuracy: 1.0000\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0293 - accuracy: 0.9958 - val_loss: 0.0301 - val_accuracy: 0.9875\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0237 - accuracy: 1.0000 - val_loss: 0.0198 - val_accuracy: 1.0000\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0211 - accuracy: 1.0000 - val_loss: 0.0115 - val_accuracy: 1.0000\n    Epoch 21/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0231 - accuracy: 0.9958 - val_loss: 0.0171 - val_accuracy: 1.0000\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0179 - accuracy: 1.0000 - val_loss: 0.0203 - val_accuracy: 1.0000\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0215 - accuracy: 0.9958 - val_loss: 0.0140 - val_accuracy: 1.0000\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0189 - accuracy: 1.0000 - val_loss: 0.0244 - val_accuracy: 1.0000\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0141 - accuracy: 1.0000 - val_loss: 0.0128 - val_accuracy: 1.0000\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0179 - accuracy: 1.0000 - val_loss: 0.0084 - val_accuracy: 1.0000\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0191 - accuracy: 1.0000 - val_loss: 0.0155 - val_accuracy: 1.0000\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0189 - accuracy: 1.0000 - val_loss: 0.0120 - val_accuracy: 1.0000\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0135 - accuracy: 1.0000 - val_loss: 0.0098 - val_accuracy: 1.0000\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0157 - accuracy: 1.0000 - val_loss: 0.0110 - val_accuracy: 1.0000\n    Epoch 1/300\n    60/60 [==============================] - 1s 4ms/step - loss: 1.4198 - accuracy: 0.7000 - val_loss: 0.7476 - val_accuracy: 0.7875\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.4007 - accuracy: 0.8792 - val_loss: 0.3864 - val_accuracy: 0.8750\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1829 - accuracy: 0.9375 - val_loss: 0.2556 - val_accuracy: 0.9375\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1131 - accuracy: 0.9625 - val_loss: 0.3519 - val_accuracy: 0.9250\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1252 - accuracy: 0.9417 - val_loss: 0.1833 - val_accuracy: 0.9375\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0733 - accuracy: 0.9625 - val_loss: 0.3365 - val_accuracy: 0.9125\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0699 - accuracy: 0.9750 - val_loss: 0.2680 - val_accuracy: 0.9250\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0441 - accuracy: 0.9917 - val_loss: 0.2172 - val_accuracy: 0.9500\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0582 - accuracy: 0.9875 - val_loss: 0.2473 - val_accuracy: 0.9375\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0384 - accuracy: 0.9917 - val_loss: 0.2289 - val_accuracy: 0.9500\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0394 - accuracy: 0.9917 - val_loss: 0.2352 - val_accuracy: 0.9250\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0363 - accuracy: 0.9958 - val_loss: 0.2321 - val_accuracy: 0.9500\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0308 - accuracy: 0.9917 - val_loss: 0.2408 - val_accuracy: 0.9375\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0267 - accuracy: 0.9958 - val_loss: 0.2473 - val_accuracy: 0.9500\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0326 - accuracy: 0.9917 - val_loss: 0.2912 - val_accuracy: 0.9000\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0368 - accuracy: 0.9875 - val_loss: 0.2264 - val_accuracy: 0.9500\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0283 - accuracy: 0.9958 - val_loss: 0.2399 - val_accuracy: 0.9375\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0253 - accuracy: 1.0000 - val_loss: 0.2239 - val_accuracy: 0.9500\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0233 - accuracy: 1.0000 - val_loss: 0.2385 - val_accuracy: 0.9500\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0226 - accuracy: 0.9958 - val_loss: 0.2425 - val_accuracy: 0.9500\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0189 - accuracy: 1.0000 - val_loss: 0.2325 - val_accuracy: 0.9500\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0168 - accuracy: 1.0000 - val_loss: 0.2263 - val_accuracy: 0.9375\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0206 - accuracy: 0.9958 - val_loss: 0.2007 - val_accuracy: 0.9500\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0155 - accuracy: 1.0000 - val_loss: 0.2079 - val_accuracy: 0.9500\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0150 - accuracy: 1.0000 - val_loss: 0.2201 - val_accuracy: 0.9500\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0166 - accuracy: 1.0000 - val_loss: 0.2220 - val_accuracy: 0.9375\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0124 - accuracy: 1.0000 - val_loss: 0.2452 - val_accuracy: 0.9125\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0136 - accuracy: 1.0000 - val_loss: 0.2040 - val_accuracy: 0.9500\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 1.0292 - accuracy: 0.7375 - val_loss: 0.8872 - val_accuracy: 0.8375\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2952 - accuracy: 0.9208 - val_loss: 0.8315 - val_accuracy: 0.8750\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1898 - accuracy: 0.9458 - val_loss: 0.6354 - val_accuracy: 0.8500\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0978 - accuracy: 0.9542 - val_loss: 0.3394 - val_accuracy: 0.9125\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1256 - accuracy: 0.9542 - val_loss: 0.5598 - val_accuracy: 0.9125\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1002 - accuracy: 0.9625 - val_loss: 0.2752 - val_accuracy: 0.9250\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0610 - accuracy: 0.9792 - val_loss: 0.3237 - val_accuracy: 0.9250\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0446 - accuracy: 0.9917 - val_loss: 0.3203 - val_accuracy: 0.9125\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0394 - accuracy: 0.9917 - val_loss: 0.2922 - val_accuracy: 0.9375\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0291 - accuracy: 0.9917 - val_loss: 0.2707 - val_accuracy: 0.9250\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0281 - accuracy: 0.9958 - val_loss: 0.2772 - val_accuracy: 0.9375\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0248 - accuracy: 0.9958 - val_loss: 0.2986 - val_accuracy: 0.9250\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0235 - accuracy: 0.9958 - val_loss: 0.2724 - val_accuracy: 0.9375\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0219 - accuracy: 1.0000 - val_loss: 0.2938 - val_accuracy: 0.9250\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0275 - accuracy: 1.0000 - val_loss: 0.2573 - val_accuracy: 0.9250\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0215 - accuracy: 0.9958 - val_loss: 0.2585 - val_accuracy: 0.9375\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0213 - accuracy: 0.9958 - val_loss: 0.2431 - val_accuracy: 0.9375\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0229 - accuracy: 0.9958 - val_loss: 0.2377 - val_accuracy: 0.9375\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0154 - accuracy: 1.0000 - val_loss: 0.3155 - val_accuracy: 0.9125\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0144 - accuracy: 1.0000 - val_loss: 0.3511 - val_accuracy: 0.8875\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0191 - accuracy: 0.9917 - val_loss: 0.2726 - val_accuracy: 0.9375\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0115 - accuracy: 1.0000 - val_loss: 0.2337 - val_accuracy: 0.9375\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0133 - accuracy: 1.0000 - val_loss: 0.3028 - val_accuracy: 0.9250\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0151 - accuracy: 0.9958 - val_loss: 0.2959 - val_accuracy: 0.9250\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0111 - accuracy: 1.0000 - val_loss: 0.3225 - val_accuracy: 0.9250\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0124 - accuracy: 1.0000 - val_loss: 0.3240 - val_accuracy: 0.9000\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0105 - accuracy: 1.0000 - val_loss: 0.2767 - val_accuracy: 0.9125\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0113 - accuracy: 1.0000 - val_loss: 0.2584 - val_accuracy: 0.9375\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0102 - accuracy: 1.0000 - val_loss: 0.2954 - val_accuracy: 0.9250\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 0.7618 - accuracy: 0.7583 - val_loss: 0.2765 - val_accuracy: 0.9125\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2823 - accuracy: 0.8792 - val_loss: 0.4377 - val_accuracy: 0.8875\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1808 - accuracy: 0.9083 - val_loss: 0.3536 - val_accuracy: 0.9375\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2010 - accuracy: 0.9167 - val_loss: 0.3440 - val_accuracy: 0.8375\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1168 - accuracy: 0.9500 - val_loss: 0.1745 - val_accuracy: 0.9625\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0524 - accuracy: 0.9833 - val_loss: 0.1701 - val_accuracy: 0.9500\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0585 - accuracy: 0.9750 - val_loss: 0.1888 - val_accuracy: 0.9375\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0364 - accuracy: 0.9958 - val_loss: 0.1747 - val_accuracy: 0.9625\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0385 - accuracy: 0.9875 - val_loss: 0.1535 - val_accuracy: 0.9625\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0377 - accuracy: 0.9875 - val_loss: 0.1719 - val_accuracy: 0.9625\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0323 - accuracy: 0.9875 - val_loss: 0.1587 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0293 - accuracy: 0.9875 - val_loss: 0.1800 - val_accuracy: 0.9625\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0389 - accuracy: 0.9792 - val_loss: 0.1532 - val_accuracy: 0.9625\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0289 - accuracy: 0.9958 - val_loss: 0.1660 - val_accuracy: 0.9625\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0278 - accuracy: 0.9875 - val_loss: 0.1600 - val_accuracy: 0.9625\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0218 - accuracy: 0.9958 - val_loss: 0.1561 - val_accuracy: 0.9625\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0221 - accuracy: 1.0000 - val_loss: 0.1645 - val_accuracy: 0.9625\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0222 - accuracy: 0.9917 - val_loss: 0.2056 - val_accuracy: 0.9375\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0219 - accuracy: 0.9958 - val_loss: 0.1587 - val_accuracy: 0.9625\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0166 - accuracy: 1.0000 - val_loss: 0.1507 - val_accuracy: 0.9625\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0217 - accuracy: 0.9958 - val_loss: 0.1565 - val_accuracy: 0.9500\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0271 - accuracy: 0.9958 - val_loss: 0.2216 - val_accuracy: 0.9125\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0215 - accuracy: 1.0000 - val_loss: 0.1711 - val_accuracy: 0.9500\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0135 - accuracy: 0.9958 - val_loss: 0.1550 - val_accuracy: 0.9625\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0146 - accuracy: 1.0000 - val_loss: 0.1687 - val_accuracy: 0.9500\n    Epoch 1/300\n    60/60 [==============================] - 1s 5ms/step - loss: 0.7075 - accuracy: 0.8000 - val_loss: 0.3672 - val_accuracy: 0.9250\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3063 - accuracy: 0.9208 - val_loss: 0.2899 - val_accuracy: 0.9375\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1521 - accuracy: 0.9500 - val_loss: 0.3248 - val_accuracy: 0.8750\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1376 - accuracy: 0.9500 - val_loss: 0.2196 - val_accuracy: 0.9500\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0688 - accuracy: 0.9708 - val_loss: 0.2166 - val_accuracy: 0.9500\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0729 - accuracy: 0.9750 - val_loss: 0.1895 - val_accuracy: 0.9500\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0707 - accuracy: 0.9708 - val_loss: 0.1863 - val_accuracy: 0.9500\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0573 - accuracy: 0.9750 - val_loss: 0.1742 - val_accuracy: 0.9625\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0338 - accuracy: 0.9958 - val_loss: 0.1927 - val_accuracy: 0.9750\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0359 - accuracy: 0.9917 - val_loss: 0.2039 - val_accuracy: 0.9500\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0517 - accuracy: 0.9833 - val_loss: 0.1683 - val_accuracy: 0.9625\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0312 - accuracy: 0.9917 - val_loss: 0.1854 - val_accuracy: 0.9500\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0352 - accuracy: 0.9917 - val_loss: 0.1576 - val_accuracy: 0.9750\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0224 - accuracy: 1.0000 - val_loss: 0.1736 - val_accuracy: 0.9750\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0291 - accuracy: 0.9917 - val_loss: 0.1634 - val_accuracy: 0.9750\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0220 - accuracy: 0.9958 - val_loss: 0.1634 - val_accuracy: 0.9750\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0197 - accuracy: 1.0000 - val_loss: 0.1473 - val_accuracy: 0.9750\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0211 - accuracy: 0.9958 - val_loss: 0.1415 - val_accuracy: 0.9750\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0162 - accuracy: 1.0000 - val_loss: 0.1450 - val_accuracy: 0.9875\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0229 - accuracy: 0.9958 - val_loss: 0.1739 - val_accuracy: 0.9750\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0198 - accuracy: 1.0000 - val_loss: 0.1684 - val_accuracy: 0.9500\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0234 - accuracy: 0.9917 - val_loss: 0.3579 - val_accuracy: 0.9000\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0217 - accuracy: 1.0000 - val_loss: 0.1576 - val_accuracy: 0.9875\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0128 - accuracy: 1.0000 - val_loss: 0.1487 - val_accuracy: 0.9750\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0134 - accuracy: 1.0000 - val_loss: 0.1574 - val_accuracy: 0.9875\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0102 - accuracy: 1.0000 - val_loss: 0.1619 - val_accuracy: 0.9750\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0126 - accuracy: 1.0000 - val_loss: 0.1526 - val_accuracy: 0.9750\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0117 - accuracy: 1.0000 - val_loss: 0.1474 - val_accuracy: 0.9875\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0102 - accuracy: 1.0000 - val_loss: 0.1417 - val_accuracy: 0.9750\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0094 - accuracy: 1.0000 - val_loss: 0.1520 - val_accuracy: 0.9750\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0080 - accuracy: 1.0000 - val_loss: 0.1484 - val_accuracy: 0.9750\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0138 - accuracy: 1.0000 - val_loss: 0.1431 - val_accuracy: 0.9750\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0091 - accuracy: 1.0000 - val_loss: 0.1467 - val_accuracy: 0.9875\n    Epoch 34/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0075 - accuracy: 1.0000 - val_loss: 0.1388 - val_accuracy: 0.9750\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0081 - accuracy: 1.0000 - val_loss: 0.1395 - val_accuracy: 0.9750\n    Epoch 36/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0079 - accuracy: 1.0000 - val_loss: 0.1510 - val_accuracy: 0.9750\n    Epoch 37/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0073 - accuracy: 1.0000 - val_loss: 0.1415 - val_accuracy: 0.9750\n    Epoch 38/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0065 - accuracy: 1.0000 - val_loss: 0.1535 - val_accuracy: 0.9750\n    Epoch 39/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0080 - accuracy: 1.0000 - val_loss: 0.1555 - val_accuracy: 0.9875\n    Epoch 1/300\n    60/60 [==============================] - 1s 4ms/step - loss: 0.8626 - accuracy: 0.7292 - val_loss: 0.2212 - val_accuracy: 0.9500\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3013 - accuracy: 0.9083 - val_loss: 0.1030 - val_accuracy: 0.9750\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1060 - accuracy: 0.9625 - val_loss: 0.1780 - val_accuracy: 0.9500\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1036 - accuracy: 0.9583 - val_loss: 0.1047 - val_accuracy: 0.9625\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0639 - accuracy: 0.9833 - val_loss: 0.2968 - val_accuracy: 0.9250\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1285 - accuracy: 0.9583 - val_loss: 0.2274 - val_accuracy: 0.9250\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0663 - accuracy: 0.9833 - val_loss: 0.1478 - val_accuracy: 0.9500\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0538 - accuracy: 0.9917 - val_loss: 0.1101 - val_accuracy: 0.9750\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0487 - accuracy: 0.9792 - val_loss: 0.1056 - val_accuracy: 0.9750\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0474 - accuracy: 0.9875 - val_loss: 0.1243 - val_accuracy: 0.9500\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0329 - accuracy: 0.9917 - val_loss: 0.1336 - val_accuracy: 0.9500\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0292 - accuracy: 0.9917 - val_loss: 0.1899 - val_accuracy: 0.9375\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0318 - accuracy: 0.9958 - val_loss: 0.2000 - val_accuracy: 0.9375\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0285 - accuracy: 0.9958 - val_loss: 0.1213 - val_accuracy: 0.9625\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0247 - accuracy: 1.0000 - val_loss: 0.1256 - val_accuracy: 0.9375\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0273 - accuracy: 0.9958 - val_loss: 0.1262 - val_accuracy: 0.9500\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0227 - accuracy: 1.0000 - val_loss: 0.1638 - val_accuracy: 0.9375\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0210 - accuracy: 1.0000 - val_loss: 0.1482 - val_accuracy: 0.9375\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0184 - accuracy: 1.0000 - val_loss: 0.0975 - val_accuracy: 0.9625\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0338 - accuracy: 0.9875 - val_loss: 0.1293 - val_accuracy: 0.9125\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0300 - accuracy: 0.9917 - val_loss: 0.1029 - val_accuracy: 0.9500\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0307 - accuracy: 0.9917 - val_loss: 0.1141 - val_accuracy: 0.9375\n    Epoch 1/300\n    60/60 [==============================] - 0s 4ms/step - loss: 0.7574 - accuracy: 0.7833 - val_loss: 0.9020 - val_accuracy: 0.8000\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3161 - accuracy: 0.8792 - val_loss: 0.6437 - val_accuracy: 0.8125\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2581 - accuracy: 0.9208 - val_loss: 0.4608 - val_accuracy: 0.8625\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1179 - accuracy: 0.9375 - val_loss: 0.2665 - val_accuracy: 0.9125\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0818 - accuracy: 0.9750 - val_loss: 0.2568 - val_accuracy: 0.9250\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0518 - accuracy: 0.9833 - val_loss: 0.2864 - val_accuracy: 0.9000\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0483 - accuracy: 0.9833 - val_loss: 0.2179 - val_accuracy: 0.9375\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0339 - accuracy: 0.9917 - val_loss: 0.2080 - val_accuracy: 0.9375\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0281 - accuracy: 0.9958 - val_loss: 0.2358 - val_accuracy: 0.9375\n    Epoch 10/300\n    60/60 [==============================] - 0s 2ms/step - loss: 0.0191 - accuracy: 0.9958 - val_loss: 0.2328 - val_accuracy: 0.9375\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0173 - accuracy: 0.9958 - val_loss: 0.2485 - val_accuracy: 0.9250\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0187 - accuracy: 1.0000 - val_loss: 0.2342 - val_accuracy: 0.9250\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0138 - accuracy: 1.0000 - val_loss: 0.2433 - val_accuracy: 0.9375\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0153 - accuracy: 1.0000 - val_loss: 0.2208 - val_accuracy: 0.9375\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0152 - accuracy: 1.0000 - val_loss: 0.2409 - val_accuracy: 0.9250\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0128 - accuracy: 1.0000 - val_loss: 0.2562 - val_accuracy: 0.9250\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0120 - accuracy: 1.0000 - val_loss: 0.2463 - val_accuracy: 0.9250\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0135 - accuracy: 1.0000 - val_loss: 0.2428 - val_accuracy: 0.9250\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0125 - accuracy: 1.0000 - val_loss: 0.3111 - val_accuracy: 0.9250\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0134 - accuracy: 1.0000 - val_loss: 0.2703 - val_accuracy: 0.9250\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0119 - accuracy: 1.0000 - val_loss: 0.2848 - val_accuracy: 0.9250\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0097 - accuracy: 1.0000 - val_loss: 0.2292 - val_accuracy: 0.9375\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0095 - accuracy: 1.0000 - val_loss: 0.2827 - val_accuracy: 0.9250\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0091 - accuracy: 1.0000 - val_loss: 0.2391 - val_accuracy: 0.9375\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0080 - accuracy: 1.0000 - val_loss: 0.2227 - val_accuracy: 0.9375\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0086 - accuracy: 1.0000 - val_loss: 0.3265 - val_accuracy: 0.9375\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0137 - accuracy: 1.0000 - val_loss: 0.2689 - val_accuracy: 0.9250\n    Epoch 1/300\n    60/60 [==============================] - 1s 4ms/step - loss: 1.1719 - accuracy: 0.7458 - val_loss: 0.7040 - val_accuracy: 0.8750\n    Epoch 2/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.3763 - accuracy: 0.8833 - val_loss: 0.4209 - val_accuracy: 0.8750\n    Epoch 3/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.2494 - accuracy: 0.9375 - val_loss: 0.2406 - val_accuracy: 0.9375\n    Epoch 4/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1154 - accuracy: 0.9625 - val_loss: 0.1439 - val_accuracy: 0.9500\n    Epoch 5/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0969 - accuracy: 0.9542 - val_loss: 0.0759 - val_accuracy: 0.9750\n    Epoch 6/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0954 - accuracy: 0.9667 - val_loss: 0.1527 - val_accuracy: 0.9625\n    Epoch 7/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.1170 - accuracy: 0.9500 - val_loss: 0.0609 - val_accuracy: 0.9875\n    Epoch 8/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0518 - accuracy: 0.9917 - val_loss: 0.0992 - val_accuracy: 0.9625\n    Epoch 9/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0836 - accuracy: 0.9583 - val_loss: 0.0832 - val_accuracy: 0.9750\n    Epoch 10/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0663 - accuracy: 0.9708 - val_loss: 0.0612 - val_accuracy: 0.9750\n    Epoch 11/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0433 - accuracy: 0.9875 - val_loss: 0.0777 - val_accuracy: 0.9750\n    Epoch 12/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0340 - accuracy: 0.9958 - val_loss: 0.0549 - val_accuracy: 0.9625\n    Epoch 13/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0312 - accuracy: 1.0000 - val_loss: 0.0548 - val_accuracy: 0.9750\n    Epoch 14/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0277 - accuracy: 0.9958 - val_loss: 0.0742 - val_accuracy: 0.9875\n    Epoch 15/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0290 - accuracy: 1.0000 - val_loss: 0.1186 - val_accuracy: 0.9500\n    Epoch 16/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0386 - accuracy: 0.9833 - val_loss: 0.0489 - val_accuracy: 0.9875\n    Epoch 17/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0270 - accuracy: 1.0000 - val_loss: 0.0452 - val_accuracy: 0.9875\n    Epoch 18/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0287 - accuracy: 1.0000 - val_loss: 0.0441 - val_accuracy: 1.0000\n    Epoch 19/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0252 - accuracy: 0.9958 - val_loss: 0.0513 - val_accuracy: 0.9875\n    Epoch 20/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0218 - accuracy: 1.0000 - val_loss: 0.0506 - val_accuracy: 0.9750\n    Epoch 21/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0227 - accuracy: 1.0000 - val_loss: 0.0563 - val_accuracy: 0.9750\n    Epoch 22/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0200 - accuracy: 1.0000 - val_loss: 0.0509 - val_accuracy: 0.9750\n    Epoch 23/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0227 - accuracy: 1.0000 - val_loss: 0.0689 - val_accuracy: 0.9750\n    Epoch 24/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0188 - accuracy: 1.0000 - val_loss: 0.0560 - val_accuracy: 0.9750\n    Epoch 25/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0199 - accuracy: 1.0000 - val_loss: 0.0473 - val_accuracy: 0.9875\n    Epoch 26/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0165 - accuracy: 1.0000 - val_loss: 0.0444 - val_accuracy: 0.9875\n    Epoch 27/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0216 - accuracy: 0.9958 - val_loss: 0.0631 - val_accuracy: 0.9875\n    Epoch 28/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0146 - accuracy: 1.0000 - val_loss: 0.0469 - val_accuracy: 0.9750\n    Epoch 29/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0139 - accuracy: 1.0000 - val_loss: 0.0451 - val_accuracy: 0.9875\n    Epoch 30/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0145 - accuracy: 1.0000 - val_loss: 0.0429 - val_accuracy: 0.9875\n    Epoch 31/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0121 - accuracy: 1.0000 - val_loss: 0.0470 - val_accuracy: 0.9875\n    Epoch 32/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0115 - accuracy: 1.0000 - val_loss: 0.0515 - val_accuracy: 0.9750\n    Epoch 33/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0106 - accuracy: 1.0000 - val_loss: 0.0418 - val_accuracy: 0.9875\n    Epoch 34/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0115 - accuracy: 1.0000 - val_loss: 0.0403 - val_accuracy: 0.9875\n    Epoch 35/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0122 - accuracy: 1.0000 - val_loss: 0.0423 - val_accuracy: 0.9875\n    Epoch 36/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0378 - accuracy: 0.9875 - val_loss: 0.0481 - val_accuracy: 0.9875\n    Epoch 37/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0429 - accuracy: 0.9833 - val_loss: 0.0564 - val_accuracy: 0.9750\n    Epoch 38/300\n    60/60 [==============================] - 0s 3ms/step - loss: 0.0186 - accuracy: 0.9917 - val_loss: 0.0623 - val_accuracy: 0.9875\n    average classification accuracy precision recall f1_score\n    [0.973      0.9743875  0.973      0.97302131]\n    standard deviation\n    [0.01834734 0.01728031 0.01834734 0.01832658]\n\n", "meta": {"hexsha": "380876bc91f12de8a66d54b2f7f2fbd26cbeb47b", "size": 392264, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Hyperparameter tuning.ipynb", "max_stars_repo_name": "arthijayaraman-lab/self-supervised_learning_microscopy_images", "max_stars_repo_head_hexsha": "f7adc86798379ae3934a864e6c41982a15aae870", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/Hyperparameter tuning.ipynb", "max_issues_repo_name": "arthijayaraman-lab/self-supervised_learning_microscopy_images", "max_issues_repo_head_hexsha": "f7adc86798379ae3934a864e6c41982a15aae870", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/Hyperparameter tuning.ipynb", "max_forks_repo_name": "arthijayaraman-lab/self-supervised_learning_microscopy_images", "max_forks_repo_head_hexsha": "f7adc86798379ae3934a864e6c41982a15aae870", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 392264.0, "max_line_length": 392264, "alphanum_fraction": 0.5187858177, "converted": true, "num_tokens": 152951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3665897363221598, "lm_q2_score": 0.06187597880385995, "lm_q1q2_score": 0.022683098754382566}}
{"text": "# ORION Orientation Estimation Using Commodity Wi-Fi\n\n\n\n\nWith MIMO, Wi-Fi led the way to the adoption of antenna array signal processing techniques for fine-grained localization using commodity hardware. MIMO techniques, previously exclusive to specific domains of applications for instance radar systems, allow to consider estimating the orientation in space of a device equipped with COTS Wi-Fi chip. In fact, the availability channel state information measurement in recent Wi-Fi chips, makes it a candidate readily available for experimentation. Accordingly, we propose the ORION system to estimate the orientation (heading and yaw) of a MIMO Wi-Fi equipped object, relying on a joint estimation of the angle of arrival and the angle of departure.\n\n\n\n## Implementation \n\n### Experimentation Setup\nWe have implemented the system using the Intel Wi-Fi Link 5300 NICs. Indeed, we have used the 533AN_MMW (Full) model with the following SPS references: 480986-0001 0E, 506679-001 0B, 480986-0010A. The firmware of this COTS Wi-Fi card was modified in order to extract the CSI matrices through the Intel CSI tool for 802.11n HT packets. In case of OFDM systems, as for instance Wi-Fi, we are able to extract a CSI matrix for each sub-carrier. In our case the Wireless NIC offers up to 30 subcarriers. We use the 5 GHz band with 20MHz of bandwidth. We set up our wireless cards in the injection mode, which avoids the need of association with an AP and allows raw Wi-Fi packets transmission.\n\nWe setup two uniform linear antenna arrays (ULAs). We use a classical 5dBi omnidirectional compatible with 2.4 GHz as well as the 5GHz band. As we are using the 5.32 GHz band for our system, we respect a 2.8cm of inter-antenna spacing, which corresponds to half the wavelength. These ULAs are connected to the terminal through extension cables in order to have liberty of movement, which is essential for our experimentation. The cables are 3 meters long and compatible with both the Wi-Fi bands with 2dB signal attenuation for 2.4 GHz band.\n\n###  Wireless Card Configuration\nThe transmission is controlled by disabling the antenna selection algorithm and by specifying the desired number of antennas, streams and transmission technique which is in our case the Spatial Multiplexing (SM). The rotation of the antenna array is performed using extension cables that connect the coplanar transmitter and receiver antenna arrays to the access points.\nIn order to specify correctly the antenna mapping as well the number of streams used for the transmission, we change the monitor_tx_rate file, after making sure that all the previous steps for collecting CSI were respected, we could for example launch the following command:\n\n```bash\nsudo echo 0x4101 |sudo tee /sys/kernel/debug/ieee80211/phy0/iwlwifi/iwldvm/debug/monitor_tx_rate\n```\nThis command  is meant for sending 1 stream on the first antenna. \nIn fact there the number of streams that are sent is dependent on the MCS index used .\n\nIf we want to build a rate index we need to choose and appropriate MCS index corresponding to the number of streams. For example, for sending two streams we choose the MCS index number 9 (make sure that the index is in hexadecimal). For choosing the antenna involved in the transmission we need to apply the appropriate mask:\n```\n0x04000 for the first antenna\n0x08000 for the second antenna\n0x10000 for the third antenna\n```\nWe use the HT leagacy packet format by using the flag 0x100.\n\nAnd thus if we want to send 2 streams on the second and third antenna using HT leagacy packets, the appropriate rate would be:\n```\n0x18109=0x08000+0x10000+0x100+0x9\n```\nAnd thus the command used is as follows:\n```bash\nsudo echo 0x18109 |sudo tee /sys/kernel/debug/ieee80211/phy0/iwlwifi/iwldvm/debug/monitor_tx_rate.\n\n```\n\nFor further details check: https://github.com/dhalperi/linux-80211n-csitool/blob/csitool-3.13/drivers/net/wireless/iwlwifi/dvm/commands.h#L245-L334\n\nFor the transmission we choose the injection mode based on lorcon-old. Lorcon, which stands for Loss Of Radio CONnectivity is library for injecting 802.11 frames https://github.com/dhalperi/lorcon-old.\n\nIf you choose to use nepi-ng for running your experiment, you should apply an appropriate rate index in https://github.com/parmentelat/r2lab/blob/public/demos/jobs-angle-measure/angle-measure.sh#L128-L134\n\n## Joint Angle of arrival Angle of Departure Estimation\n\n\n\nWe  jointly estimate AoA and AoD using a 2D MUSIC algorithm on phase corrected CSI matrices collected through out the experiment for a subcarrier.\n\nThe figure shown below represents the values computed for the following pseudo-spectrum:\n\n$$\n\\begin{equation}\n\\textbf{P}(\\theta_i,\\phi_i)=\\frac{1}{(\\textbf{a}_r(\\theta_i) \\otimes \\textbf{a}_t(\\phi_i))^H.\\textbf{Q}_n.\\textbf{Q}_n^H(\\textbf{a}_r(\\theta_i) \\otimes \\textbf{a}_t(\\phi_i))}\n\\end{equation}\n$$\nwith $\\theta_i $ is the angle of arrival and $\\phi_i$ is the angle of departure. The peak represents the AoA and AoD estimates.\n\n\n\n\n```python\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom music import *\ncsi_corr='./log/csi_corr.dat'\ncsi_target='./log/csi_target.dat'\nmusic(csi_corr, csi_target, 2, 3, 0.5, 0.5,640)\n#music_pl(s, 2, 3, 0.5, 0.5,1)\n```\n\n\n```python\n%matplotlib inline\nfrom music_pl import *\nfrom IPython import display\nimport time\n\nx = []\ny = []\nz = []\n\ns = phase_correction(csi_corr, csi_target)    \n\nfor i in range(1900):\n    x = np.append(x, i)\n    o=music_pl(s, 2, 3, 0.5, 0.5,i)\n    y = np.append(y, o[0])\n    z = np.append(z, o[1])\n    plt.gca().cla() \n    plt.plot(x,y,label='DOA')\n    plt.plot(x,z,label='DOD')\n    plt.ylabel('Angle in degrees')\n    plt.xlabel('packet number')\n    plt.legend()\n    plt.ylim(-90, 90)\n    display.clear_output(wait=True)\n    display.display(plt.gcf())\n```\n\n\n```python\nangle=np.array(np.squeeze([[y],[z]]))\nangle.shape\n```\n\n\n\n\n    (2, 1942)\n\n\n\n\n```python\nimport pandas as pd \ndf = pd.DataFrame(angle)\ndf.to_csv(\"exp_meas3.csv\",header=None)\n```\n\n###  Smoothing Angle Estimations\n\nAs shown in the figure above, the estimates are jittery with a strong presence of outliers. Thus, in order to smoothen our estimates, we apply an outlier detector on the measurement data before using a Kalman filter to mitigate the statistical noise.\n\n\n```python\nplt.figure()\nplt.grid(True)\nplt.ylabel('Angle in degrees')\nplt.xlabel('packet number')\nplt.plot(y,'b',linewidth='1',label='DOA') \nplt.plot(z,'r',linewidth='1',label='DOD') \nplt.tick_params(labelsize=14)\nplt.legend()\nplt.ylim(-90, 90)\nplt.show()\n```\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom kalman_fil import *\n\nDOA, DOD,angles1,angles2=kalman_fil(\"exp_meas.csv\")\nplt.figure(figsize=(7,7))\nplt.grid(True)\nplt.ylabel('Angle in degrees')\nplt.xlabel('packet number')\n\nplt.subplot(2, 1, 2)\nplt.plot(DOA,'b',linewidth='2',label='DOA') \nplt.plot(DOD,'r',linewidth='2',label='DOD')\nplt.tick_params(labelsize=14)\nplt.legend()\nplt.grid(True)\nplt.ylabel('Angle in degrees')\nplt.xlabel('packet number')\nplt.ylim(-60, 60)\nplt.subplot(2, 1, 1)\nplt.plot(angles1,'b',linewidth='2',label='DOA') \nplt.plot(angles2,'r',linewidth='2',label='DOD')\nplt.grid(True)\nplt.ylabel('Angle in degrees')\nplt.xlabel('packet number')\nplt.tick_params(labelsize=14)\nplt.legend()\nplt.ylim(-60, 60)\nplt.show()\n```\n\nSo after applying an outlier removal using a Hampel identifier and a Kalman filter on our estimated data we have significantly decreased the noise and increased the overall accuracy.\n", "meta": {"hexsha": "313cfbf498dcbe9764cb827d0d20ed64bb73865c", "size": 379791, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "code/ORION.ipynb", "max_stars_repo_name": "naoufal51/orion", "max_stars_repo_head_hexsha": "0beb3020a3ca0fa7a4113db23ef4767ac3d63624", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2017-04-15T16:46:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-07T06:33:23.000Z", "max_issues_repo_path": "code/ORION.ipynb", "max_issues_repo_name": "naoufal51/orion", "max_issues_repo_head_hexsha": "0beb3020a3ca0fa7a4113db23ef4767ac3d63624", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-07-26T09:01:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-01T16:25:08.000Z", "max_forks_repo_path": "code/ORION.ipynb", "max_forks_repo_name": "naoufal51/orion", "max_forks_repo_head_hexsha": "0beb3020a3ca0fa7a4113db23ef4767ac3d63624", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2017-08-08T21:15:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-07T09:12:54.000Z", "avg_line_length": 1069.8338028169, "max_line_length": 151342, "alphanum_fraction": 0.9424314952, "converted": true, "num_tokens": 1928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367020358429, "lm_q2_score": 0.04958902456418653, "lm_q1q2_score": 0.022668963146446633}}
{"text": "```python\n! pip install qiskit\n```\n\n    Collecting qiskit\n      Downloading qiskit-0.34.0.tar.gz (13 kB)\n    Collecting qiskit-terra==0.19.1\n      Downloading qiskit_terra-0.19.1-cp37-cp37m-manylinux2010_x86_64.whl (6.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.4 MB 4.2 MB/s \n    \u001b[?25hCollecting qiskit-aer==0.10.1\n      Downloading qiskit_aer-0.10.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (18.0 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 18.0 MB 50.8 MB/s \n    \u001b[?25hCollecting qiskit-ibmq-provider==0.18.3\n      Downloading qiskit_ibmq_provider-0.18.3-py3-none-any.whl (238 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 238 kB 56.3 MB/s \n    \u001b[?25hCollecting qiskit-ignis==0.7.0\n      Downloading qiskit_ignis-0.7.0-py3-none-any.whl (200 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 200 kB 65.7 MB/s \n    \u001b[?25hRequirement already satisfied: scipy>=1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.10.1->qiskit) (1.4.1)\n    Requirement already satisfied: numpy>=1.16.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.10.1->qiskit) (1.19.5)\n    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (1.24.3)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (2.8.2)\n    Collecting requests-ntlm>=1.1.0\n      Downloading requests_ntlm-1.1.0-py2.py3-none-any.whl (5.7 kB)\n    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (2.23.0)\n    Collecting websocket-client>=1.0.1\n      Downloading websocket_client-1.2.3-py3-none-any.whl (53 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 53 kB 2.2 MB/s \n    \u001b[?25hRequirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ignis==0.7.0->qiskit) (57.4.0)\n    Collecting retworkx>=0.8.0\n      Downloading retworkx-0.10.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.4 MB 66.2 MB/s \n    \u001b[?25hRequirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.1->qiskit) (5.4.8)\n    Collecting ply>=3.10\n      Downloading ply-3.11-py2.py3-none-any.whl (49 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 49 kB 5.3 MB/s \n    \u001b[?25hCollecting tweedledum<2.0,>=1.1\n      Downloading tweedledum-1.1.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (943 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 943 kB 54.5 MB/s \n    \u001b[?25hCollecting python-constraint>=1.4\n      Downloading python-constraint-1.4.0.tar.bz2 (18 kB)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.1->qiskit) (0.3.4)\n    Collecting stevedore>=3.0.0\n      Downloading stevedore-3.5.0-py3-none-any.whl (49 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 49 kB 6.0 MB/s \n    \u001b[?25hRequirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.1->qiskit) (1.7.1)\n    Collecting symengine>=0.8\n      Downloading symengine-0.8.1-cp37-cp37m-manylinux2010_x86_64.whl (38.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 38.2 MB 1.2 MB/s \n    \u001b[?25hCollecting scipy>=1.0\n      Downloading scipy-1.7.3-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (38.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 38.1 MB 1.2 MB/s \n    \u001b[?25hRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.8.0->qiskit-ibmq-provider==0.18.3->qiskit) (1.15.0)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit) (2021.10.8)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit) (2.10)\n    Collecting ntlm-auth>=1.0.2\n      Downloading ntlm_auth-1.5.0-py2.py3-none-any.whl (29 kB)\n    Collecting cryptography>=1.3\n      Downloading cryptography-36.0.1-cp36-abi3-manylinux_2_24_x86_64.whl (3.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.6 MB 67.7 MB/s \n    \u001b[?25hRequirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit) (1.15.0)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit) (2.21)\n    Collecting pbr!=2.1.0,>=2.0.0\n      Downloading pbr-5.8.0-py2.py3-none-any.whl (112 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 112 kB 58.4 MB/s \n    \u001b[?25hRequirement already satisfied: importlib-metadata>=1.7.0 in /usr/local/lib/python3.7/dist-packages (from stevedore>=3.0.0->qiskit-terra==0.19.1->qiskit) (4.8.2)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=1.7.0->stevedore>=3.0.0->qiskit-terra==0.19.1->qiskit) (3.6.0)\n    Requirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=1.7.0->stevedore>=3.0.0->qiskit-terra==0.19.1->qiskit) (3.10.0.2)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra==0.19.1->qiskit) (1.2.1)\n    Building wheels for collected packages: qiskit, python-constraint\n      Building wheel for qiskit (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for qiskit: filename=qiskit-0.34.0-py3-none-any.whl size=11764 sha256=9f1780476d5d028b08ccbe371f7d4884784473b48d20f51bef7764581c9fc058\n      Stored in directory: /root/.cache/pip/wheels/be/f4/26/53ffcc0c3a1303116016eaf20c4f0c8dc125bc3b3c7afa2347\n      Building wheel for python-constraint (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for python-constraint: filename=python_constraint-1.4.0-py2.py3-none-any.whl size=24081 sha256=97fa637431d714866ec2d61b3218f27812fd62dc1569c5a918dc4537d4567d47\n      Stored in directory: /root/.cache/pip/wheels/07/27/db/1222c80eb1e431f3d2199c12569cb1cac60f562a451fe30479\n    Successfully built qiskit python-constraint\n    Installing collected packages: pbr, tweedledum, symengine, stevedore, scipy, retworkx, python-constraint, ply, ntlm-auth, cryptography, websocket-client, requests-ntlm, qiskit-terra, qiskit-ignis, qiskit-ibmq-provider, qiskit-aer, qiskit\n      Attempting uninstall: scipy\n        Found existing installation: scipy 1.4.1\n        Uninstalling scipy-1.4.1:\n          Successfully uninstalled scipy-1.4.1\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Successfully installed cryptography-36.0.1 ntlm-auth-1.5.0 pbr-5.8.0 ply-3.11 python-constraint-1.4.0 qiskit-0.34.0 qiskit-aer-0.10.1 qiskit-ibmq-provider-0.18.3 qiskit-ignis-0.7.0 qiskit-terra-0.19.1 requests-ntlm-1.1.0 retworkx-0.10.2 scipy-1.7.3 stevedore-3.5.0 symengine-0.8.1 tweedledum-1.1.1 websocket-client-1.2.3\n\n\n\n```python\nimport qiskit\nimport PIL\nimport pandas as pd\nimport numpy as np\nimport os\nimport time\nimport operator\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport math\n\nfrom qiskit import *\nfrom qiskit.circuit import Reset\nfrom qiskit.test.mock import FakeMontreal\nfrom qiskit.compiler import transpile\nfrom PIL import Image\nfrom time import perf_counter\nfrom tensorflow.keras import layers, models\nfrom math import *\n```\n\n\n```python\ndef construct_data_frame(dir):\n  nodule_types = ['NORMAL', 'BENIGN', 'MALIGNANT']\n  data = []\n  for nodule_num, nodule_type in enumerate(nodule_types):\n    i = 1\n    for image in os.listdir(os.path.join(dir, nodule_type)):\n      image_file = Image.open('{}/{}/{}'.format(dir, nodule_type, image))\n      data.append(['{}/{}/{}'.format(dir, nodule_type, image), nodule_num, nodule_type])\n      if i == 20:\n        break\n      i += 1\n  table = pd.DataFrame(data, columns = ['File', 'NoduleNum', 'NoduleTypes'])\n  table = table.sample(frac=1).reset_index(drop=True)\n  return table\n```\n\n\n```python\ndef quantum_filter(input_vals):\n  qreg = QuantumRegister(5)\n  creg = ClassicalRegister(1)\n  circ = QuantumCircuit(qreg, creg)\n  for qubit in qreg:\n   circ.h(qubit)\n  for i in range(4):\n    circ.ry(pi*input_vals[i], i)\n  circ.z(qreg[0])\n  circ.h(qreg[3])\n  circ.cx(qreg[2], qreg[3])\n  circ.h(qreg[2])\n  circ.h(qreg[3])\n  circ.cx(qreg[1], qreg[2])\n  circ.h(qreg[3])\n  circ.h(qreg[1])\n  circ.h(qreg[2])\n  circ.cx(qreg[0], qreg[3])\n  circ.h(qreg[2])\n  circ.h(qreg[3])\n  circ.cx(qreg[0], qreg[2])\n  circ.h(qreg[3])\n  circ.cx(qreg[0], qreg[1])\n  circ.h(qreg[2])\n  circ.h(qreg[1])\n  circ.ccx(qreg[1], qreg[2], qreg[3])\n  circ.h(qreg[2])\n  circ.h(qreg[3])\n  circ.ccx(qreg[0], qreg[1], qreg[2])\n  circ.h(qreg[3])\n  circ.h(qreg[2])\n  circ.mcx([qreg[0], qreg[1], qreg[2]], qreg[3])\n  circ.z(qreg[2])\n  circ.h(qreg[3])\n  circ.z(qreg[3])\n  circ.h(qreg[3])\n  circ.cx(qreg[2], qreg[3])\n  circ.h(qreg[2])\n  circ.h(qreg[3])\n  circ.h(qreg[3])\n  circ.cx(qreg[1], qreg[3])\n  circ.h(qreg[1])\n  circ.h(qreg[3])\n  circ.h(qreg[3])\n  circ.cx(qreg[0], qreg[3])\n  circ.cx(qreg[0], qreg[2])\n  circ.h(qreg[3])\n  circ.cx(qreg[0], qreg[1])\n  circ.h(qreg[2])\n  circ.h(qreg[3])\n  circ.x(qreg[0])\n  circ.ccx(qreg[1], qreg[2], qreg[3])\n  circ.h(qreg[1])\n  circ.h(qreg[2])\n  circ.h(qreg[3])\n  circ.x(qreg[1])\n  circ.x(qreg[2])\n  circ.h(qreg[3])\n  circ.x(qreg[3])\n  circ.mcx([qreg[0], qreg[1], qreg[2], qreg[3]], qreg[4])\n  circ.measure(qreg[4], creg)\n  counts = execute(circ, Aer.get_backend('aer_simulator'), shots = 1000).result().get_counts(circ)\n  key = max(counts.items(), key=operator.itemgetter(1))[0]\n  return key == '1'\n```\n\n\n```python\ndef quantum_preprocess(train_nparrays):\n  cnn_input = [] # input into cnn after quanvolution (preprocessing step)\n  for curr_image in train_nparrays:\n    dimensions = curr_image.shape\n    num_rows_original = dimensions[0]\n    num_cols_original = dimensions[1]\n    modified_image_nparray = np.zeros((num_rows_original-1, num_cols_original-1))\n    for row in range(num_rows_original-1):\n      for col in range(num_cols_original-1):\n        filter_input = [curr_image[row][col], \n                        curr_image[row][col+1],\n                        curr_image[row+1][col], \n                        curr_image[row+1][col+1]]\n        filter_output = quantum_filter(filter_input)\n        if filter_output:\n          modified_image_nparray[row][col] = 1 #check poss vals\n    cnn_input.append(modified_image_nparray)\n  return cnn_input\n```\n\n\n```python\n# load data and preprocess\ntrain_data = construct_data_frame('/content/drive/MyDrive/QC-Final-Project/Modified_Dataset/Train')\ntest_data = construct_data_frame('/content/drive/MyDrive/QC-Final-Project/Modified_Dataset/Test')\n\ntrain_nparrays = []\ntrain_nodule_types = []\nfor col, row in train_data.iterrows():\n  image = Image.open(row['File'])\n  image = image.resize((10, 10))\n  image.save(row['File'])\n  train_nparrays.append(np.asarray(Image.open(row['File'])))\n  train_nodule_types.append(row['NoduleNum'])\n\ntest_nparrays = []\ntest_nodule_types = []\nfor col, row in test_data.iloc[0:20].iterrows():\n  image = Image.open(row['File'])\n  image = image.resize((10, 10))\n  image.save(row['File'])\n  test_nparrays.append(np.asarray(Image.open(row['File'])))\n  test_nodule_types.append(test_data['NoduleNum'])\n```\n\n\n```python\ncnn_input = np.array(quantum_preprocess(train_nparrays))\ntrain_nodule_types = np.array(train_nodule_types)\ntest_nparrays = np.array(quantum_preprocess(test_nparrays))\ntest_nodule_types = np.array(test_nodule_types)\n```\n\n\n```python\n# train\nqcnn = models.Sequential()\nqcnn.add(layers.Conv2D(32, (2, 2), activation = 'relu', input_shape=(9, 9, 1)))\nqcnn.add(layers.MaxPooling2D(3, 3))\nqcnn.add(layers.Conv2D(32, (1, 1), activation = 'relu', input_shape=(None, 2, 2, 10)))\nqcnn.add(layers.Flatten())\nqcnn.add(layers.Dense(3, activation='softmax'))\nqcnn.compile(optimizer = 'adam',\n             loss = \"sparse_categorical_crossentropy\",\n             metrics = [\"accuracy\"])\nhistory = qcnn.fit(cnn_input,\n                   train_nodule_types,\n                   validation_split = 0.2,\n                   epochs = 10,\n                   verbose = 2)\n```\n\n    Epoch 1/10\n    2/2 - 1s - loss: 1.1290 - accuracy: 0.3125 - val_loss: 1.0477 - val_accuracy: 0.4167 - 565ms/epoch - 282ms/step\n    Epoch 2/10\n    2/2 - 0s - loss: 1.1155 - accuracy: 0.3125 - val_loss: 1.0742 - val_accuracy: 0.3333 - 30ms/epoch - 15ms/step\n    Epoch 3/10\n    2/2 - 0s - loss: 1.1058 - accuracy: 0.2500 - val_loss: 1.0998 - val_accuracy: 0.2500 - 24ms/epoch - 12ms/step\n    Epoch 4/10\n    2/2 - 0s - loss: 1.0974 - accuracy: 0.2917 - val_loss: 1.1250 - val_accuracy: 0.1667 - 23ms/epoch - 11ms/step\n    Epoch 5/10\n    2/2 - 0s - loss: 1.0914 - accuracy: 0.4167 - val_loss: 1.1514 - val_accuracy: 0.0000e+00 - 25ms/epoch - 13ms/step\n    Epoch 6/10\n    2/2 - 0s - loss: 1.0863 - accuracy: 0.4167 - val_loss: 1.1771 - val_accuracy: 0.0000e+00 - 23ms/epoch - 12ms/step\n    Epoch 7/10\n    2/2 - 0s - loss: 1.0815 - accuracy: 0.4167 - val_loss: 1.2017 - val_accuracy: 0.0000e+00 - 25ms/epoch - 13ms/step\n    Epoch 8/10\n    2/2 - 0s - loss: 1.0773 - accuracy: 0.4167 - val_loss: 1.2235 - val_accuracy: 0.0000e+00 - 38ms/epoch - 19ms/step\n    Epoch 9/10\n    2/2 - 0s - loss: 1.0791 - accuracy: 0.4167 - val_loss: 1.2462 - val_accuracy: 0.0000e+00 - 42ms/epoch - 21ms/step\n    Epoch 10/10\n    2/2 - 0s - loss: 1.0752 - accuracy: 0.4167 - val_loss: 1.2616 - val_accuracy: 0.0000e+00 - 28ms/epoch - 14ms/step\n\n\n\n```python\n# accuracy and loss plots\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n```\n", "meta": {"hexsha": "2eb05dce82dd4fbb11a3766c08c0dbc73d1700c7", "size": 44981, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "QCNN_based_lung_tumor_classifier.ipynb", "max_stars_repo_name": "saanaz379/lung-tumor-classifier", "max_stars_repo_head_hexsha": "02399fd7734e2574008f942bcabb6cfb647b7ff2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QCNN_based_lung_tumor_classifier.ipynb", "max_issues_repo_name": "saanaz379/lung-tumor-classifier", "max_issues_repo_head_hexsha": "02399fd7734e2574008f942bcabb6cfb647b7ff2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QCNN_based_lung_tumor_classifier.ipynb", "max_forks_repo_name": "saanaz379/lung-tumor-classifier", "max_forks_repo_head_hexsha": "02399fd7734e2574008f942bcabb6cfb647b7ff2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 103.4045977011, "max_line_length": 14598, "alphanum_fraction": 0.762788733, "converted": true, "num_tokens": 5247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423539898095244, "lm_q2_score": 0.06954175125515784, "lm_q1q2_score": 0.02254789746405025}}
{"text": "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Deep-Learning-Model-Calibration-with-Temperature-Scaling\" data-toc-modified-id=\"Deep-Learning-Model-Calibration-with-Temperature-Scaling-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Deep Learning Model Calibration with Temperature Scaling</a></span><ul class=\"toc-item\"><li><span><a href=\"#Tokenizer\" data-toc-modified-id=\"Tokenizer-1.1\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;</span>Tokenizer</a></span></li><li><span><a href=\"#Model-FineTuning\" data-toc-modified-id=\"Model-FineTuning-1.2\"><span class=\"toc-item-num\">1.2&nbsp;&nbsp;</span>Model FineTuning</a></span></li><li><span><a href=\"#Model-Calibration\" data-toc-modified-id=\"Model-Calibration-1.3\"><span class=\"toc-item-num\">1.3&nbsp;&nbsp;</span>Model Calibration</a></span><ul class=\"toc-item\"><li><span><a href=\"#Temperature-Scaling\" data-toc-modified-id=\"Temperature-Scaling-1.3.1\"><span class=\"toc-item-num\">1.3.1&nbsp;&nbsp;</span>Temperature Scaling</a></span></li></ul></li></ul></li><li><span><a href=\"#Reference\" data-toc-modified-id=\"Reference-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Reference</a></span></li></ul></div>\n\n\n```python\nimport os\n\n# path : store the current path to convert back to it later\npath = os.getcwd()\nos.chdir(os.path.join('..', '..', 'notebook_format'))\n\nfrom formats import load_style\nload_style(css_style='custom2.css', plot_style=False)\n```\n\n\n\n\n\n<style>\n    html {\n        font-size: 18px !important;\n    }\n\n    body {\n        background-color: #FFF !important;\n        font-weight: 1rem;\n        font-family: 'Source Sans Pro', \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n    }\n\n    body .notebook-app {\n        background-color: #FFF !important;\n    }\n\n    #header {\n        box-shadow: none !important;\n    }\n\n    #notebook {\n        padding-top: 0px;\n    }\n\n    #notebook-container {\n        box-shadow: none;\n        -webkit-box-shadow: none;\n        padding: 10px;\n    }\n\n    div.cell {\n        width: 1000px;\n        margin-left: 0% !important;\n        margin-right: auto;\n    }\n\n    div.cell.selected {\n        border: 1px dashed #CCCCCC;\n    }\n\n    .edit_mode div.cell.selected {\n        border: 1px dashed #828282;\n    }\n\n    div.output_wrapper {\n        margin-top: 8px;\n    }\n\n    a {\n        color: #383838;\n    }\n\n    code,\n    kbd,\n    pre,\n    samp {\n        font-family: 'Menlo', monospace !important;\n        font-size: 0.75rem !important;\n    }\n\n    h1 {\n        font-size: 2rem !important;\n        font-weight: 500 !important;\n        letter-spacing: 3px !important;\n        text-transform: uppercase !important;\n    }\n\n    h2 {\n        font-size: 1.8rem !important;\n        font-weight: 400 !important;\n        letter-spacing: 3px !important;\n        text-transform: none !important;\n    }\n\n    h3 {\n        font-size: 1.5rem !important;\n        font-weight: 400 !important;\n        font-style: italic !important;\n        display: block !important;\n    }\n\n    h4,\n    h5,\n    h6 {\n        font-size: 1rem !important;\n        font-weight: 400 !important;\n        display: block !important;\n    }\n\n    .prompt {\n        font-family: 'Menlo', monospace !important;\n        font-size: 0.75rem;\n        text-align: right;\n        line-height: 1.21429rem;\n    }\n\n    /* INTRO PAGE */\n\n    .toolbar_info,\n    .list-container {\n        ;\n    }\n    /* NOTEBOOK */\n\n    div#header-container {\n        display: none !important;\n    }\n\n    div#notebook {\n        border-top: none;\n        font-size: 1rem;\n    }\n\n    div.input_prompt {\n        color: #C74483;\n    }\n\n    .code_cell div.input_prompt:after,\n    div.output_prompt:after {\n        content: '\\25b6';\n    }\n\n    div.output_prompt {\n        color: #2B88D9;\n    }\n\n    div.input_area {\n        border-radius: 0px;\n        border: 1px solid #d8d8d8;\n    }\n\n    div.output_area pre {\n        font-weight: normal;\n    }\n\n    div.output_subarea {\n        font-weight: normal;\n    }\n\n    .rendered_html pre,\n    .rendered_html table,\n    .rendered_html th,\n    .rendered_html tr,\n    .rendered_html td {\n        border: 1px #828282 solid;\n        font-size: 0.75rem;\n        font-family: 'Menlo', monospace;\n    }\n\n    .rendered_html th,\n    .rendered_html tr,\n    .rendered_html td {\n        padding: 5px 10px;\n    }\n\n    .rendered_html th {\n        font-weight: normal;\n        background: #f8f8f8;\n    }\n\n    a:link{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:visited{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:hover{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:focus{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:active{\n       font-weight: bold;\n       color:#447adb;\n    }\n    .rendered_html :link {\n       text-decoration: underline; \n    }\n\n    div.output_html {\n        font-weight: 1rem;\n        font-family: 'Source Sans Pro', \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n    }\n\n    table.dataframe tr {\n        border: 1px #CCCCCC;\n    }\n\n    div.cell.selected {\n        border-radius: 0px;\n    }\n\n    div.cell.edit_mode {\n        border-radius: 0px;\n        border: thin solid #CF5804;\n    }\n\n    span.ansiblue {\n        color: #00A397;\n    }\n\n    span.ansigray {\n        color: #d8d8d8;\n    }\n\n    span.ansigreen {\n        color: #688A0A;\n    }\n\n    span.ansipurple {\n        color: #975DDE;\n    }\n\n    span.ansired {\n        color: #D43132;\n    }\n\n    span.ansiyellow {\n        color: #D9AA00;\n    }\n\n    div.output_stderr {\n        background-color: #D43132;\n    }\n\n    div.output_stderr pre {\n        color: #e8e8e8;\n    }\n\n    .cm-s-ipython.CodeMirror {\n        background: #F8F8F8;\n    }\n\n    .cm-s-ipython div.CodeMirror-selected {\n        background: #e8e8e8 !important;\n    }\n\n    .cm-s-ipython .CodeMirror-gutters {\n        background: #F8F8F8;\n        border-right: 0px;\n    }\n\n    .cm-s-ipython .CodeMirror-linenumber {\n        color: #b8b8b8;\n    }\n\n    .cm-s-ipython .CodeMirror-cursor {\n        border-left: 1px solid #585858 !important;\n    }\n\n    .cm-s-ipython span.cm-atom {\n        color: #C74483;\n    }\n\n    .cm-s-ipython span.cm-number {\n        color: #C74483;\n    }\n\n    .cm-s-ipython span.cm-property,\n    .cm-s-ipython span.cm-attribute {\n        color: #688A0A;\n    }\n\n    .cm-s-ipython span.cm-keyword {\n        font-weight: normal;\n        color: #D43132;\n    }\n\n    .cm-s-ipython span.cm-string {\n        color: #D9AA00;\n    }\n\n    .cm-s-ipython span.cm-operator {\n        font-weight: normal;\n    }\n\n    .cm-s-ipython span.cm-builtin {\n        color: #2B88D9;\n    }\n\n    .cm-s-ipython span.cm-variable {\n        color: #00A397;\n    }\n\n    .cm-s-ipython span.cm-variable-2 {\n        color: #2B88D9;\n    }\n\n    .cm-s-ipython span.cm-def {\n        color: #00A397;\n    }\n\n    .cm-s-ipython span.cm-error {\n        background: #FFBDBD;\n        color: #D43132;\n    }\n\n    .cm-s-ipython span.cm-tag {\n        color: #D43132;\n    }\n\n    .cm-s-ipython span.cm-link {\n        color: #975DDE;\n    }\n\n    .cm-s-ipython .CodeMirror-matchingbracket {\n        text-decoration: underline;\n         !important;\n    }\n</style>\n\n\n\n\n\n\n```python\n# 1. magic for inline plot\n# 2. magic to print version\n# 3. magic so that the notebook will reload external python modules\n# 4. magic to enable retina (high resolution) plots\n# https://gist.github.com/minrk/3301035\n%matplotlib inline\n%load_ext watermark\n%load_ext autoreload\n%autoreload 2\n%config InlineBackend.figure_format='retina'\n\nimport os\nimport time\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom tqdm import trange\nfrom torch import optim\nfrom torch.utils.data import DataLoader\nfrom datasets import load_dataset, DatasetDict, Dataset\nfrom transformers import (\n    AutoTokenizer,\n    AutoModelForSequenceClassification,\n    TrainingArguments,\n    Trainer,\n    DataCollatorWithPadding\n)\n\n%watermark -a 'Ethen' -d -t -v -p datasets,transformers,torch,tokenizers,numpy,pandas,matplotlib\n```\n\n    Author: Ethen\n    \n    Python implementation: CPython\n    Python version       : 3.7.3\n    IPython version      : 7.17.0\n    \n    datasets    : 1.6.2\n    transformers: 4.4.1\n    torch       : 1.7.0+cu101\n    tokenizers  : 0.10.3\n    numpy       : 1.20.3\n    pandas      : 1.2.4\n    matplotlib  : 3.4.2\n    \n\n\n# Deep Learning Model Calibration with Temperature Scaling\n\nIn this article, we'll be going over two main things:\n\n- Process of finetuning a pre-trained BERT model towards a text classification task, more specificially, the [Quora Question Pairs](https://www.kaggle.com/c/quora-question-pairs/data) challenge.\n- Process of evaluating model calibration and improving upong calibration error using temperature scaling.\n\nFinetuning pre-trained models on downstream tasks has been increasingly popular these days, this notebook documents the findings on these model's calibration. Calibration in this context means does the model's predicted score reflects true probability. If the reader is not familiar with model calibration 101, there is a separate [notebook](http://ethen8181.github.io/machine-learning/model_selection/prob_calibration/prob_calibration.html) that covers this topic. Reading up till the \"Measuring Calibration\" section should suffice.\n\n\n```python\ndataset_dict = load_dataset(\"quora\")\ndataset_dict\n```\n\n    Using custom data configuration default\n    Reusing dataset quora (/home/mingyuliu/.cache/huggingface/datasets/quora/default/0.0.0/36ba4cd42107f051a158016f1bea6ae3f4685c5df843529108a54e42d86c1e04)\n\n\n\n\n\n    DatasetDict({\n        train: Dataset({\n            features: ['questions', 'is_duplicate'],\n            num_rows: 404290\n        })\n    })\n\n\n\n\n```python\ndataset_dict['train'][0]\n```\n\n\n\n\n    {'is_duplicate': False,\n     'questions': {'id': [1, 2],\n      'text': ['What is the step by step guide to invest in share market in india?',\n       'What is the step by step guide to invest in share market?']}}\n\n\n\n\n```python\ntest_size = 0.1\nval_size = 0.1\ndataset_dict_test = dataset_dict['train'].train_test_split(test_size=test_size)\ndataset_dict_train_val = dataset_dict_test['train'].train_test_split(test_size=val_size)\n\ndataset_dict = DatasetDict({\n    \"train\": dataset_dict_train_val[\"train\"],\n    \"val\": dataset_dict_train_val[\"test\"],\n    \"test\": dataset_dict_test[\"test\"]\n})\ndataset_dict\n```\n\n\n\n\n    DatasetDict({\n        train: Dataset({\n            features: ['questions', 'is_duplicate'],\n            num_rows: 327474\n        })\n        val: Dataset({\n            features: ['questions', 'is_duplicate'],\n            num_rows: 36387\n        })\n        test: Dataset({\n            features: ['questions', 'is_duplicate'],\n            num_rows: 40429\n        })\n    })\n\n\n\n## Tokenizer\n\nWe won't be going over the details of the pre-trained tokenizer or model and only load a pre-trained one available from the huggingface model repository.\n\n\n```python\n# https://huggingface.co/transformers/model_doc/mobilebert.html\npretrained_model_name_or_path = \"google/mobilebert-uncased\"\ntokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path)\ntokenizer\n```\n\n\n\n\n    PreTrainedTokenizerFast(name_or_path='google/mobilebert-uncased', vocab_size=30522, model_max_len=1000000000000000019884624838656, is_fast=True, padding_side='right', special_tokens={'unk_token': '[UNK]', 'sep_token': '[SEP]', 'pad_token': '[PAD]', 'cls_token': '[CLS]', 'mask_token': '[MASK]'})\n\n\n\nWe can feed our tokenizer directly with a pair of sentences.\n\n\n```python\nencoded_input = tokenizer(\n    'What is the step by step guide to invest in share market in india?',\n    'What is the step by step guide to invest in share market?'\n)\nencoded_input\n```\n\n\n\n\n    {'input_ids': [101, 2054, 2003, 1996, 3357, 2011, 3357, 5009, 2000, 15697, 1999, 3745, 3006, 1999, 2634, 1029, 102, 2054, 2003, 1996, 3357, 2011, 3357, 5009, 2000, 15697, 1999, 3745, 3006, 1029, 102], 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}\n\n\n\nDecoding the tokenized inputs, this model's tokenizer adds some special tokens such as, `[SEP]`, that is used to indicate which token belongs to which segment/pair.\n\n\n```python\ntokenizer.decode(encoded_input[\"input_ids\"])\n```\n\n\n\n\n    '[CLS] what is the step by step guide to invest in share market in india? [SEP] what is the step by step guide to invest in share market? [SEP]'\n\n\n\nThe proprocessing step will be task specific, if we happen to be using another dataset, this function needs to be modified accordingly.\n\n\n```python\ndef tokenize_fn(examples):\n    labels = [int(label) for label in examples['is_duplicate']]\n    texts = [question['text'] for question in examples['questions']]\n    texts1 = [text[0] for text in texts]\n    texts2 = [text[1] for text in texts]\n    tokenized_examples = tokenizer(texts1, texts2)\n    tokenized_examples['labels'] = labels\n    return tokenized_examples\n```\n\n\n```python\ndataset_dict_tokenized = dataset_dict.map(\n    tokenize_fn,\n    batched=True,\n    num_proc=8,\n    remove_columns=['is_duplicate', 'questions']\n)\ndataset_dict_tokenized\n```\n\n\n\n\n    DatasetDict({\n        train: Dataset({\n            features: ['attention_mask', 'input_ids', 'labels', 'token_type_ids'],\n            num_rows: 327474\n        })\n        val: Dataset({\n            features: ['attention_mask', 'input_ids', 'labels', 'token_type_ids'],\n            num_rows: 36387\n        })\n        test: Dataset({\n            features: ['attention_mask', 'input_ids', 'labels', 'token_type_ids'],\n            num_rows: 40429\n        })\n    })\n\n\n\n\n```python\ndataset_dict_tokenized['train'][0]\n```\n\n\n\n\n    {'attention_mask': [1,\n      1,\n      1,\n      1,\n      1,\n      1,\n      1,\n      1,\n      1,\n      1,\n      1,\n      1,\n      1,\n      1,\n      1,\n      1,\n      1,\n      1,\n      1,\n      1,\n      1],\n     'input_ids': [101,\n      2129,\n      2064,\n      1045,\n      5356,\n      1037,\n      3167,\n      4638,\n      2005,\n      2489,\n      1029,\n      102,\n      2064,\n      1037,\n      2711,\n      5356,\n      2026,\n      3167,\n      4638,\n      1029,\n      102],\n     'labels': 0,\n     'token_type_ids': [0,\n      0,\n      0,\n      0,\n      0,\n      0,\n      0,\n      0,\n      0,\n      0,\n      0,\n      0,\n      1,\n      1,\n      1,\n      1,\n      1,\n      1,\n      1,\n      1,\n      1]}\n\n\n\n## Model FineTuning\n\nHaving preprocessed our raw dataset, for our text classification task, we use `AutoModelForSequenceClassification` class to load the pre-trained model, the only other argument we need to specify is the number of class/label our text classification task has. Upon instantiating the model for the first time, we'll see some warnings generated, telling us we should fine tune this model on our down stream tasks before using it. \n\n\n```python\nmodel_checkpoint = 'text_classification'\nnum_labels = 2\n```\n\n\n```python\n# we'll save the model after fine tuning it once, so we can skip the fine tuning part during\n# the second round if we detect that we already have one available\nif os.path.isdir(model_checkpoint):\n    model = AutoModelForSequenceClassification.from_pretrained(model_checkpoint)\nelse:\n    model = AutoModelForSequenceClassification.from_pretrained(pretrained_model_name_or_path, num_labels=num_labels)\n\nprint('# of parameters: ', model.num_parameters())\nmodel\n```\n\n    Some weights of the model checkpoint at google/mobilebert-uncased were not used when initializing MobileBertForSequenceClassification: ['cls.predictions.bias', 'cls.predictions.transform.dense.weight', 'cls.predictions.transform.dense.bias', 'cls.predictions.transform.LayerNorm.weight', 'cls.predictions.transform.LayerNorm.bias', 'cls.predictions.dense.weight', 'cls.predictions.decoder.weight', 'cls.predictions.decoder.bias', 'cls.seq_relationship.weight', 'cls.seq_relationship.bias']\n    - This IS expected if you are initializing MobileBertForSequenceClassification from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n    - This IS NOT expected if you are initializing MobileBertForSequenceClassification from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n    Some weights of MobileBertForSequenceClassification were not initialized from the model checkpoint at google/mobilebert-uncased and are newly initialized: ['classifier.weight', 'classifier.bias']\n    You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n\n\n    # of parameters:  24582914\n\n\n\n\n\n    MobileBertForSequenceClassification(\n      (mobilebert): MobileBertModel(\n        (embeddings): MobileBertEmbeddings(\n          (word_embeddings): Embedding(30522, 128, padding_idx=0)\n          (position_embeddings): Embedding(512, 512)\n          (token_type_embeddings): Embedding(2, 512)\n          (embedding_transformation): Linear(in_features=384, out_features=512, bias=True)\n          (LayerNorm): NoNorm()\n          (dropout): Dropout(p=0.0, inplace=False)\n        )\n        (encoder): MobileBertEncoder(\n          (layer): ModuleList(\n            (0): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (1): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (2): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (3): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (4): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (5): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (6): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (7): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (8): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (9): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (10): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (11): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (12): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (13): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (14): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (15): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (16): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (17): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (18): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (19): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (20): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (21): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (22): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n            (23): MobileBertLayer(\n              (attention): MobileBertAttention(\n                (self): MobileBertSelfAttention(\n                  (query): Linear(in_features=128, out_features=128, bias=True)\n                  (key): Linear(in_features=128, out_features=128, bias=True)\n                  (value): Linear(in_features=512, out_features=128, bias=True)\n                  (dropout): Dropout(p=0.1, inplace=False)\n                )\n                (output): MobileBertSelfOutput(\n                  (dense): Linear(in_features=128, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (intermediate): MobileBertIntermediate(\n                (dense): Linear(in_features=128, out_features=512, bias=True)\n              )\n              (output): MobileBertOutput(\n                (dense): Linear(in_features=512, out_features=128, bias=True)\n                (LayerNorm): NoNorm()\n                (bottleneck): OutputBottleneck(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                  (LayerNorm): NoNorm()\n                  (dropout): Dropout(p=0.0, inplace=False)\n                )\n              )\n              (bottleneck): Bottleneck(\n                (input): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n                (attention): BottleneckLayer(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                )\n              )\n              (ffn): ModuleList(\n                (0): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (1): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (2): FFNLayer(\n                  (intermediate): MobileBertIntermediate(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                  )\n                  (output): FFNOutput(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n              )\n            )\n          )\n        )\n        (pooler): MobileBertPooler()\n      )\n      (dropout): Dropout(p=0.0, inplace=False)\n      (classifier): Linear(in_features=512, out_features=2, bias=True)\n    )\n\n\n\n\n```python\ndata_collator = DataCollatorWithPadding(tokenizer, padding=True)\ndata_collator\n```\n\n\n\n\n    DataCollatorWithPadding(tokenizer=PreTrainedTokenizerFast(name_or_path='google/mobilebert-uncased', vocab_size=30522, model_max_len=1000000000000000019884624838656, is_fast=True, padding_side='right', special_tokens={'unk_token': '[UNK]', 'sep_token': '[SEP]', 'pad_token': '[PAD]', 'cls_token': '[CLS]', 'mask_token': '[MASK]'}), padding=True, max_length=None, pad_to_multiple_of=None)\n\n\n\nWe can perform all sorts of hyper parameter tuning on the fine tuning step, here we'll pick some default parameters for illustration purposes.\n\n\n```python\nbatch_size = 64\nargs = TrainingArguments(\n    \"quora\",\n    evaluation_strategy=\"epoch\",\n    learning_rate=1e-4,\n    per_device_train_batch_size=batch_size,\n    per_device_eval_batch_size=batch_size,\n    num_train_epochs=2,\n    weight_decay=0.01,\n    load_best_model_at_end=True\n)\n\ntrainer = Trainer(\n    model,\n    args,\n    data_collator=data_collator,\n    train_dataset=dataset_dict_tokenized[\"train\"],\n    eval_dataset=dataset_dict_tokenized['val']\n)\n```\n\n\n```python\nif not os.path.isdir(model_checkpoint):\n    trainer.train()\n    model.save_pretrained(model_checkpoint)\n```\n\n\n\n    <div>\n        <style>\n            /* Turns off some styling */\n            progress {\n                /* gets rid of default border in Firefox and Opera. */\n                border: none;\n                /* Needs to be in here for Safari polyfill so background images work as expected. */\n                background-size: auto;\n            }\n        </style>\n\n      <progress value='10234' max='10234' style='width:300px; height:20px; vertical-align: middle;'></progress>\n      [10234/10234 1:05:21, Epoch 2/2]\n    </div>\n    <table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: left;\">\n      <th>Epoch</th>\n      <th>Training Loss</th>\n      <th>Validation Loss</th>\n      <th>Runtime</th>\n      <th>Samples Per Second</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>1</td>\n      <td>0.266000</td>\n      <td>0.259760</td>\n      <td>30.191600</td>\n      <td>1205.204000</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>0.195500</td>\n      <td>0.241103</td>\n      <td>29.987800</td>\n      <td>1213.392000</td>\n    </tr>\n  </tbody>\n</table><p>\n\n\n\n```python\nclass SoftmaxModule(nn.Module):\n    \"\"\"\n    Add a softmax layer on top the base model. Note this does not necessarily\n    mean the output score is a well-calibrated probability.\n    \"\"\"\n\n    def __init__(self, model_path: str):\n        super().__init__()\n        self.model_path = model_path\n        self.model = AutoModelForSequenceClassification.from_pretrained(model_path)\n\n    def forward(self, input_ids, attention_mask, token_type_ids):\n        outputs = self.model(\n            input_ids=input_ids,\n            attention_mask=attention_mask,\n            token_type_ids=token_type_ids\n        )\n        scores = nn.functional.softmax(outputs.logits, dim=-1)[:, 1]\n        return scores\n```\n\n\n```python\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nsoftmax_module = SoftmaxModule(model_checkpoint).to(device)\nsoftmax_module.eval()\nsoftmax_module\n```\n\n\n\n\n    SoftmaxModule(\n      (model): MobileBertForSequenceClassification(\n        (mobilebert): MobileBertModel(\n          (embeddings): MobileBertEmbeddings(\n            (word_embeddings): Embedding(30522, 128, padding_idx=0)\n            (position_embeddings): Embedding(512, 512)\n            (token_type_embeddings): Embedding(2, 512)\n            (embedding_transformation): Linear(in_features=384, out_features=512, bias=True)\n            (LayerNorm): NoNorm()\n            (dropout): Dropout(p=0.0, inplace=False)\n          )\n          (encoder): MobileBertEncoder(\n            (layer): ModuleList(\n              (0): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (1): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (2): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (3): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (4): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (5): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (6): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (7): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (8): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (9): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (10): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (11): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (12): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (13): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (14): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (15): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (16): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (17): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (18): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (19): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (20): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (21): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (22): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (23): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n            )\n          )\n          (pooler): MobileBertPooler()\n        )\n        (dropout): Dropout(p=0.0, inplace=False)\n        (classifier): Linear(in_features=512, out_features=2, bias=True)\n      )\n    )\n\n\n\nWe define some helper functions to generate predictions for our dataset, store the predicted score and label into a pandas DataFrame.\n\n\n```python\ndef predict(model, examples, round_digits: int = 5):\n    input_ids = examples['input_ids'].to(device)\n    attention_mask = examples['attention_mask'].to(device)\n    token_type_ids = examples['token_type_ids'].to(device)\n    batch_labels = examples['labels'].detach().cpu().numpy().tolist()\n    model.eval()\n    with torch.no_grad():\n        batch_output = model(input_ids, attention_mask, token_type_ids)\n\n    batch_scores = np.round(batch_output.detach().cpu().numpy(), round_digits).tolist()\n    return batch_scores, batch_labels\n```\n\n\n```python\ndef predict_data_loader(model, data_loader: DataLoader) -> pd.DataFrame:\n    scores = []\n    labels = []\n    for examples in data_loader:\n        batch_scores, batch_labels = predict(model, examples)\n        scores += batch_scores\n        labels += batch_labels\n\n    df_predictions = pd.DataFrame.from_dict({'scores': scores, 'labels': labels})\n    return df_predictions\n```\n\n\n```python\ndata_collator = DataCollatorWithPadding(tokenizer, padding=True)\ndata_loader = DataLoader(dataset_dict_tokenized['test'], collate_fn=data_collator, batch_size=128)\nstart = time.time()\ndf_predictions = predict_data_loader(softmax_module, data_loader)\nend = time.time()\n\nprint('elapsed: ', end - start)\nprint(df_predictions.shape)\ndf_predictions.head()\n```\n\n    elapsed:  28.861881017684937\n    (40429, 2)\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>scores</th>\n      <th>labels</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.97060</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.87807</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.00540</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.64068</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.00003</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Model Calibration\n\n### Temperature Scaling\n\nTemperature Scaling is a post-processing technique that was proposed to improve upon the calibration error, but specifically designed for deep learning. It works by dividing the logits (output of the layer right before the final softmax layer) by a learned scalar parameter.\n\n\\begin{align}\n\\text{softmax} = \\frac{e^{(z/T)}}{\\sum_i e^{(z_i/T)}}\n\\end{align}\n\nwhere $z$ is the logit, and $T$ is the learned temperature scaling parameter. We learn this parameter on a validation set, where $T$ is chosen to minimize negative log likelihood. As we can imagine, with $T \\ge 1$, it lowers the predicted score across all classes, making the model less confident about its predictions but does not change the model's predicted maximum class.\n\nThe benefit of this approach is mainly two folds:\n\n- Unlike a lot of post processing calibration technique, temperature scaling can be directly embedded into our deep learning module as a single additional parameter. We can export the model as is using standard serialization techniques for that specific deep learning library and perform inferencing at run time without introducing additional dependencies.\n- It has been shown to provide potent calibration performance when compared to other post processing calibration techniques by the [original paper](https://arxiv.org/pdf/1706.04599.pdf).\n\n\n```python\nclass TemperatureScalingCalibrationModule(nn.Module):\n\n    def __init__(self, model_path: str):\n        super().__init__()\n        self.model_path = model_path\n        self.model = AutoModelForSequenceClassification.from_pretrained(model_path)\n\n        # the single temperature scaling parameter, the initialization value doesn't\n        # seem to matter that much based on some ad-hoc experimentation\n        self.temperature = nn.Parameter(torch.ones(1))\n\n    def forward(self, input_ids, attention_mask, token_type_ids):\n        \"\"\"forward method that returns softmax-ed confidence scores.\"\"\"\n        outputs = self.forward_logit(input_ids, attention_mask, token_type_ids)\n        scores = nn.functional.softmax(outputs, dim=-1)[:, 1]\n        return scores\n\n    def forward_logit(self, input_ids, attention_mask, token_type_ids):\n        \"\"\"forward method that returns logits, to be used with cross entropy loss.\"\"\"\n        outputs = self.model(\n            input_ids=input_ids,\n            attention_mask=attention_mask,\n            token_type_ids=token_type_ids\n        ).logits\n        return outputs / self.temperature\n\n    def fit(self, dataset_tokenized, n_epochs: int = 3, batch_size: int = 64, lr: float = 0.01):\n        \"\"\"fits the temperature scaling parameter.\"\"\"\n        data_collator = DataCollatorWithPadding(tokenizer, padding=True)\n        data_loader = DataLoader(dataset_tokenized, collate_fn=data_collator, batch_size=batch_size)\n\n        self.freeze_base_model()\n        criterion = nn.CrossEntropyLoss()\n        optimizer = optim.SGD(self.parameters(), lr=lr)\n\n        for epoch in trange(n_epochs):\n            for examples in data_loader:\n                labels = examples['labels'].long().to(device)\n                input_ids = examples['input_ids'].to(device)\n                attention_mask = examples['attention_mask'].to(device)\n                token_type_ids = examples['token_type_ids'].to(device)\n\n                # standard step to perform the forward and backward step\n                self.zero_grad()\n                predict_proba = self.forward_logit(input_ids, attention_mask, token_type_ids)\n                loss = criterion(predict_proba, labels)\n                loss.backward()\n                optimizer.step()\n\n        return self\n\n    def freeze_base_model(self):\n        \"\"\"remember to freeze base model's parameters when training temperature scaler\"\"\"\n        self.model.eval()\n        for parameter in self.model.parameters():\n            parameter.requires_grad = False\n\n        return self\n```\n\n\n```python\ncalibration_module = TemperatureScalingCalibrationModule(model_checkpoint).to(device)\ncalibration_module\n```\n\n\n\n\n    TemperatureScalingCalibrationModule(\n      (model): MobileBertForSequenceClassification(\n        (mobilebert): MobileBertModel(\n          (embeddings): MobileBertEmbeddings(\n            (word_embeddings): Embedding(30522, 128, padding_idx=0)\n            (position_embeddings): Embedding(512, 512)\n            (token_type_embeddings): Embedding(2, 512)\n            (embedding_transformation): Linear(in_features=384, out_features=512, bias=True)\n            (LayerNorm): NoNorm()\n            (dropout): Dropout(p=0.0, inplace=False)\n          )\n          (encoder): MobileBertEncoder(\n            (layer): ModuleList(\n              (0): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (1): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (2): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (3): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (4): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (5): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (6): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (7): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (8): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (9): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (10): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (11): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (12): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (13): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (14): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (15): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (16): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (17): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (18): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (19): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (20): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (21): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (22): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (23): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n            )\n          )\n          (pooler): MobileBertPooler()\n        )\n        (dropout): Dropout(p=0.0, inplace=False)\n        (classifier): Linear(in_features=512, out_features=2, bias=True)\n      )\n    )\n\n\n\n\n```python\ncalibration_module.fit(dataset_dict_tokenized['val'])\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3/3 [01:30<00:00, 30.04s/it]\n\n\n\n\n\n    TemperatureScalingCalibrationModule(\n      (model): MobileBertForSequenceClassification(\n        (mobilebert): MobileBertModel(\n          (embeddings): MobileBertEmbeddings(\n            (word_embeddings): Embedding(30522, 128, padding_idx=0)\n            (position_embeddings): Embedding(512, 512)\n            (token_type_embeddings): Embedding(2, 512)\n            (embedding_transformation): Linear(in_features=384, out_features=512, bias=True)\n            (LayerNorm): NoNorm()\n            (dropout): Dropout(p=0.0, inplace=False)\n          )\n          (encoder): MobileBertEncoder(\n            (layer): ModuleList(\n              (0): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (1): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (2): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (3): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (4): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (5): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (6): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (7): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (8): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (9): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (10): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (11): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (12): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (13): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (14): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (15): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (16): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (17): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (18): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (19): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (20): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (21): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (22): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n              (23): MobileBertLayer(\n                (attention): MobileBertAttention(\n                  (self): MobileBertSelfAttention(\n                    (query): Linear(in_features=128, out_features=128, bias=True)\n                    (key): Linear(in_features=128, out_features=128, bias=True)\n                    (value): Linear(in_features=512, out_features=128, bias=True)\n                    (dropout): Dropout(p=0.1, inplace=False)\n                  )\n                  (output): MobileBertSelfOutput(\n                    (dense): Linear(in_features=128, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (intermediate): MobileBertIntermediate(\n                  (dense): Linear(in_features=128, out_features=512, bias=True)\n                )\n                (output): MobileBertOutput(\n                  (dense): Linear(in_features=512, out_features=128, bias=True)\n                  (LayerNorm): NoNorm()\n                  (bottleneck): OutputBottleneck(\n                    (dense): Linear(in_features=128, out_features=512, bias=True)\n                    (LayerNorm): NoNorm()\n                    (dropout): Dropout(p=0.0, inplace=False)\n                  )\n                )\n                (bottleneck): Bottleneck(\n                  (input): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                  (attention): BottleneckLayer(\n                    (dense): Linear(in_features=512, out_features=128, bias=True)\n                    (LayerNorm): NoNorm()\n                  )\n                )\n                (ffn): ModuleList(\n                  (0): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (1): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                  (2): FFNLayer(\n                    (intermediate): MobileBertIntermediate(\n                      (dense): Linear(in_features=128, out_features=512, bias=True)\n                    )\n                    (output): FFNOutput(\n                      (dense): Linear(in_features=512, out_features=128, bias=True)\n                      (LayerNorm): NoNorm()\n                    )\n                  )\n                )\n              )\n            )\n          )\n          (pooler): MobileBertPooler()\n        )\n        (dropout): Dropout(p=0.0, inplace=False)\n        (classifier): Linear(in_features=512, out_features=2, bias=True)\n      )\n    )\n\n\n\n\n```python\ncalibration_module.temperature\n```\n\n\n\n\n    Parameter containing:\n    tensor([1.2335], device='cuda:0', requires_grad=True)\n\n\n\n\n```python\ndata_collator = DataCollatorWithPadding(tokenizer, padding=True)\ndata_loader = DataLoader(dataset_dict_tokenized['test'], collate_fn=data_collator, batch_size=128)\nstart = time.time()\ndf_calibrated_predictions = predict_data_loader(calibration_module, data_loader)\nend = time.time()\n\nprint('elapsed: ', end - start)\nprint(df_calibrated_predictions.shape)\ndf_calibrated_predictions.head()\n```\n\n    elapsed:  28.950477123260498\n    (40429, 2)\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>scores</th>\n      <th>labels</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.94453</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.83210</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.01436</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.61511</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.00020</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nFrom the plot below, we can see our predicted score on the datset is concentrated on the higher end, however, from the calibration plot, it seems like the original predicted score is already pretty well calibrated, and with temperature scaling, we were able to improve upon the calibration metrics even further. Looking the the final value of the trained temperature scaling, a larger than 1 value indicates that it is indeed shrinking the predicted score to make the model less confident on its prediction.\n\n\n```python\nfrom calibration_module.utils import compute_calibration_summary\n\n\neval_dict = {\n    f'{model_checkpoint}': df_predictions,\n    f'{model_checkpoint}_calibrated': df_calibrated_predictions\n}\n\n# change default style figure and font size\nplt.rcParams['figure.figsize'] = 12, 12\nplt.rcParams['font.size'] = 12\n\nn_bins = 20\ndf_result = compute_calibration_summary(eval_dict, label_col='labels', score_col='scores', n_bins=n_bins)\ndf_result\n```\n\nThere're other [papers](https://arxiv.org/pdf/2106.07998.pdf) that studies the calibration effect for state of the art models. Although it's mainly for image based models, their claim is that model size and pretraining amount doen't fully account for the differences in calibration across different models, but the primary factor seems to be on model architecture, or more explicitly models that rely on attention based mechanism are found to be better calibrated compared to convolution based mechanism.\n\n# Reference\n\n- [Jupyter Notebook: Fine-tuning a model on a text classification task](https://nbviewer.jupyter.org/github/huggingface/notebooks/blob/master/examples/text_classification.ipynb)\n- [Blog: Temperature Scaling for Neural Network Calibration](https://jamesmccaffrey.wordpress.com/2021/01/28/temperature-scaling-for-neural-network-calibration/)\n- [Paper: On Calibration of Modern Neural Networks - Guo, Chuan and Pleiss, Geoff and Sun, Yu and Weinberger, Kilian Q. (2017)](https://arxiv.org/pdf/1706.04599.pdf)\n- [Paper: Revisiting the Calibration of Modern Neural Networks - Matthias Minderer, Josip Djolonga, Rob Romijnders, Frances Hubis, Xiaohua Zhai, Neil Houlsby, Dustin Tran ,Mario Lucic (2021)](https://arxiv.org/pdf/2106.07998.pdf)\n", "meta": {"hexsha": "a79e2695bc4ffac2feecb50ed96a4dbe9e7124ea", "size": 575090, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "model_selection/prob_calibration/deeplearning_prob_calibration.ipynb", "max_stars_repo_name": "ethen8181/machine-learning", "max_stars_repo_head_hexsha": "bc1584d26a4732240056f12f7fa9adaad4f8bc0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2104, "max_stars_repo_stars_event_min_datetime": "2016-04-15T13:35:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T10:39:51.000Z", "max_issues_repo_path": "model_selection/prob_calibration/deeplearning_prob_calibration.ipynb", "max_issues_repo_name": "ethen8181/machine-learning", "max_issues_repo_head_hexsha": "bc1584d26a4732240056f12f7fa9adaad4f8bc0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-04-07T14:25:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-18T03:16:15.000Z", "max_forks_repo_path": "model_selection/prob_calibration/deeplearning_prob_calibration.ipynb", "max_forks_repo_name": "ethen8181/machine-learning", "max_forks_repo_head_hexsha": "bc1584d26a4732240056f12f7fa9adaad4f8bc0f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 539, "max_forks_repo_forks_event_min_datetime": "2015-12-10T04:23:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:15:28.000Z", "avg_line_length": 72.4477198287, "max_line_length": 184380, "alphanum_fraction": 0.5894312195, "converted": true, "num_tokens": 64486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629691917376783, "lm_q2_score": 0.06187599048099379, "lm_q1q2_score": 0.022459078252854592}}
{"text": "```python\n##################################################################################\n# \u5206\u4e3a\u4e09\u4e2a\u90e8\u5206\n# 1. tokenizer\u90e8\u5206\n# 2. transformer\u90e8\u5206\n# 3. pooling\u90e8\u5206\n\n\n# from multiprocessing.pool import Pool\nimport numpy as np\nimport onnxruntime\nimport psutil\nfrom sympy import im\nfrom transformers import (AutoConfig, AutoModel, AutoTokenizer)\nimport os\nimport json\nfrom sentence_transformers.models import Pooling\n\nfrom sentence_transformers import SentenceTransformer as sbert\n\nfrom tqdm import tqdm\nimport torch as t \n\n\n```\n\n\n```python\n\n##################################################################################\n# \u5904\u7406transformer\u548c tokenizer\u90e8\u5206\n\nbig_model_path = \"../models/paraphrase-multilingual-MiniLM-L12-v2\"\n\nmodules_json_path = os.path.join(big_model_path, 'modules.json')\nwith open(modules_json_path) as fIn:\n    modules_config = json.load(fIn)\n\ntf_from_s_path = os.path.join(big_model_path, modules_config[0].get('path'))\n\n\n# \u57fa\u672c\u53c2\u6570\n\nmax_seq_length = 128\ndoc_stride = 128\nmax_query_length = 64\n# Enable overwrite to export onnx model and download latest script each time when running this notebook.\nenable_overwrite = True\n# Total samples to inference. It shall be large enough to get stable latency measurement.\ntotal_samples = 1000\n\n\n# # Load pretrained model and tokenizer\n# Load pretrained model and tokenizer\nconfig_class, model_class, tokenizer_class = (\n    AutoConfig, AutoModel, AutoTokenizer)\n\ncache_dir = os.path.join(\".\", \"cache_models\")\nconfig = config_class.from_pretrained(tf_from_s_path, cache_dir=cache_dir)\ntokenizer = tokenizer_class.from_pretrained(\n    tf_from_s_path, do_lower_case=True, cache_dir=cache_dir)\nmodel_transformer = model_class.from_pretrained(\n    tf_from_s_path, from_tf=False, config=config, cache_dir=cache_dir)\n\n```\n\n\n```python\n\n##################################################################################\n# \u4f7f\u7528onnx \u548ccuda\u63a8\u7406\u90e8\u5206\n\noutput_dir = os.path.join(\"..\", \"onnx_models\")\nexport_model_path = os.path.join(output_dir, 'Multilingual_MiniLM_L12.onnx')\ndevice_name = 'gpu'\nsess_options = onnxruntime.SessionOptions()\nsess_options.optimized_model_filepath = os.path.join(\n    output_dir, \"optimized_model_{}.onnx\".format(device_name))\n# Please change the value according to best setting in Performance Test Tool result.\nsess_options.intra_op_num_threads = psutil.cpu_count(logical=True)\nsession = onnxruntime.InferenceSession(\n    export_model_path, sess_options, providers=['CUDAExecutionProvider'])\n\n```\n\n    2022-02-25 14:01:58.432835797 [W:onnxruntime:, inference_session.cc:1407 Initialize] Serializing optimized model with Graph Optimization level greater than ORT_ENABLE_EXTENDED and the NchwcTransformer enabled. The generated model may contain hardware specific optimizations, and should only be used in the same environment the model was optimized in.\n\n\n\n```python\n##################################################################################\n# \u5904\u7406pooling\u90e8\u5206\npooling_model_path = os.path.join(big_model_path, modules_config[1].get('path'))\npooling_model = Pooling.load(pooling_model_path)\n# pooling_model_path\n```\n\n\n```python\n\n##################################################################################\n# \u63a8\u7406\u51fd\u6570\n\n\ndef inferpart(session, sentences, pooling_model):\n    if isinstance(sentences, str) or not hasattr(sentences, '__len__'):\n        sentences = [sentences]\n\n    inputs = tokenizer(\n        sentences,\n        padding=True,\n        truncation=True,\n        max_length=512,\n        return_tensors=\"pt\"\n    )\n    ort_inputs = {k:v.cpu().numpy() for k, v in inputs.items()}\n    ort_outputs_gpu = session.run(None, ort_inputs)\n    ort_result = pooling_model.forward(features={'token_embeddings':t.Tensor(ort_outputs_gpu[0]),\n    'attention_mask':inputs.get('attention_mask')})\n    result = ort_result.get('sentence_embedding')\n    return result\n\n\n_ = [inferpart(session=session, sentences = ['\u60a8\u597d'], pooling_model=pooling_model) for i in tqdm(range(2000))]\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2000/2000 [00:05<00:00, 340.29it/s]\n\n\n\n```python\n# \u4f7f\u7528\u539f\u751f\u7684sentence transformer\u4ee3\u7801\nmodel_sbert_raw = sbert(big_model_path, device='cuda')\n\n_ = [model_sbert_raw.encode(['\u60a8\u597d'],device='cuda') for i in tqdm(range(2000))]\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2000/2000 [00:25<00:00, 77.36it/s]\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "3f4040a3e21d9fcfc494f260547fb544c318fcc8", "size": 6859, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/06_fullinfer_onnx.ipynb", "max_stars_repo_name": "zyfyyzyf/quick_sentence_transformers", "max_stars_repo_head_hexsha": "059d9d7db0cd95a72fe85c1cfb536a83a817609f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2022-02-28T07:26:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T08:01:26.000Z", "max_issues_repo_path": "examples/06_fullinfer_onnx.ipynb", "max_issues_repo_name": "zyfyyzyf/quick_sentence_transformers", "max_issues_repo_head_hexsha": "059d9d7db0cd95a72fe85c1cfb536a83a817609f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-03-09T11:24:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T02:15:49.000Z", "max_forks_repo_path": "examples/06_fullinfer_onnx.ipynb", "max_forks_repo_name": "zyfyyzyf/quick_sentence_transformers", "max_forks_repo_head_hexsha": "059d9d7db0cd95a72fe85c1cfb536a83a817609f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2022-02-28T07:26:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T01:11:15.000Z", "avg_line_length": 31.036199095, "max_line_length": 360, "alphanum_fraction": 0.5521213005, "converted": true, "num_tokens": 996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.06371499380749801, "lm_q1q2_score": 0.02244053436217105}}
{"text": "#1 \u5bfc\u5165NeMo NLP\u5de5\u5177\u7c7b\u53ca\u76f8\u5173\u5de5\u5177\u5e93\n\n\n```python\n!pip install Cython\n!pip install nemo_toolkit['all']\n```\n\n    Requirement already satisfied: Cython in /usr/local/lib/python3.7/dist-packages (0.29.24)\n    Collecting nemo_toolkit[all]\n      Downloading nemo_toolkit-1.2.0-py3-none-any.whl (1.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.2 MB 7.1 MB/s \n    \u001b[?25hCollecting hydra-core>=1.1.0\n      Downloading hydra_core-1.1.1-py3-none-any.whl (145 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 145 kB 59.4 MB/s \n    \u001b[?25hCollecting transformers<=4.8.1,>=4.0.1\n      Downloading transformers-4.8.1-py3-none-any.whl (2.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.5 MB 29.8 MB/s \n    \u001b[?25hCollecting ruamel.yaml\n      Downloading ruamel.yaml-0.17.13-py3-none-any.whl (108 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 108 kB 74.7 MB/s \n    \u001b[?25hRequirement already satisfied: python-dateutil in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (2.8.2)\n    Requirement already satisfied: tqdm>=4.41.0 in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (4.62.0)\n    Collecting onnx>=1.7.0\n      Downloading onnx-1.10.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (12.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 12.3 MB 178 kB/s \n    \u001b[?25hCollecting opencc\n      Downloading OpenCC-1.1.2-cp37-cp37m-manylinux1_x86_64.whl (765 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 765 kB 59.1 MB/s \n    \u001b[?25hCollecting webdataset<=0.1.62,>=0.1.48\n      Downloading webdataset-0.1.62-py3-none-any.whl (32 kB)\n    Requirement already satisfied: wrapt in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (1.12.1)\n    Requirement already satisfied: torch in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (1.9.0+cu102)\n    Collecting pangu\n      Downloading pangu-4.0.6.1-py3-none-any.whl (6.4 kB)\n    Requirement already satisfied: numpy>=1.18.2 in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (1.19.5)\n    Requirement already satisfied: numba in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (0.51.2)\n    Collecting sentencepiece<1.0.0\n      Downloading sentencepiece-0.1.96-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.2 MB 62.3 MB/s \n    \u001b[?25hCollecting pytorch-lightning<1.4.0,>=1.3.0\n      Downloading pytorch_lightning-1.3.8-py3-none-any.whl (813 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 813 kB 64.6 MB/s \n    \u001b[?25hCollecting wget\n      Downloading wget-3.2.zip (10 kB)\n    Collecting omegaconf>=2.1.0\n      Downloading omegaconf-2.1.1-py3-none-any.whl (74 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 74 kB 4.8 MB/s \n    \u001b[?25hCollecting torchmetrics>=0.4.1rc0\n      Downloading torchmetrics-0.5.0-py3-none-any.whl (272 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 272 kB 83.7 MB/s \n    \u001b[?25hRequirement already satisfied: jieba in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (0.42.1)\n    Requirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (0.22.2.post1)\n    Requirement already satisfied: sphinx in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (1.8.5)\n    Collecting sacremoses>=0.0.43\n      Downloading sacremoses-0.0.45-py3-none-any.whl (895 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 895 kB 41.3 MB/s \n    \u001b[?25hCollecting g2p-en\n      Downloading g2p_en-2.1.0-py3-none-any.whl (3.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.1 MB 76.0 MB/s \n    \u001b[?25hCollecting sox\n      Downloading sox-1.4.1-py2.py3-none-any.whl (39 kB)\n    Collecting black==19.10b0\n      Downloading black-19.10b0-py36-none-any.whl (97 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 97 kB 10.3 MB/s \n    \u001b[?25hRequirement already satisfied: librosa in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (0.8.1)\n    Collecting marshmallow\n      Downloading marshmallow-3.13.0-py2.py3-none-any.whl (47 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 47 kB 6.0 MB/s \n    \u001b[?25hRequirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (3.2.2)\n    Requirement already satisfied: pillow in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (7.1.2)\n    Requirement already satisfied: regex in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (2019.12.20)\n    Collecting pytest-runner\n      Downloading pytest_runner-5.3.1-py3-none-any.whl (7.1 kB)\n    Collecting wordninja==2.0.0\n      Downloading wordninja-2.0.0.tar.gz (541 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 541 kB 68.9 MB/s \n    \u001b[?25hCollecting rapidfuzz\n      Downloading rapidfuzz-1.5.0-cp37-cp37m-manylinux2010_x86_64.whl (1.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.4 MB 58.2 MB/s \n    \u001b[?25hCollecting nltk==3.6.2\n      Downloading nltk-3.6.2-py3-none-any.whl (1.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.5 MB 20.2 MB/s \n    \u001b[?25hCollecting pyannote.metrics\n      Downloading pyannote.metrics-3.0.1-py3-none-any.whl (49 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 49 kB 7.6 MB/s \n    \u001b[?25hCollecting matplotlib>=3.3.2\n      Downloading matplotlib-3.4.3-cp37-cp37m-manylinux1_x86_64.whl (10.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 10.3 MB 20.5 MB/s \n    \u001b[?25hCollecting youtokentome>=1.0.5\n      Downloading youtokentome-1.0.6-cp37-cp37m-manylinux2010_x86_64.whl (1.7 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.7 MB 78.0 MB/s \n    \u001b[?25hRequirement already satisfied: torchvision in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (0.10.0+cu102)\n    Requirement already satisfied: gdown in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (3.6.4)\n    Collecting pystoi\n      Downloading pystoi-0.3.3.tar.gz (7.0 kB)\n    Requirement already satisfied: inflect in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (2.1.0)\n    Collecting sphinxcontrib-bibtex\n      Downloading sphinxcontrib_bibtex-2.3.0-py3-none-any.whl (35 kB)\n    Collecting isort[requirements]<5\n      Downloading isort-4.3.21-py2.py3-none-any.whl (42 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 42 kB 1.2 MB/s \n    \u001b[?25hRequirement already satisfied: nltk in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (3.2.5)\n    Collecting attrdict\n      Downloading attrdict-2.0.1-py2.py3-none-any.whl (9.9 kB)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (1.4.1)\n    Collecting kaldi-io\n      Downloading kaldi_io-0.9.4-py3-none-any.whl (14 kB)\n    Collecting wandb\n      Downloading wandb-0.12.0-py2.py3-none-any.whl (1.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.6 MB 68.5 MB/s \n    \u001b[?25hCollecting pydub\n      Downloading pydub-0.25.1-py2.py3-none-any.whl (32 kB)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (21.0)\n    Collecting kaldi-python-io\n      Downloading kaldi-python-io-1.2.2.tar.gz (8.8 kB)\n    Requirement already satisfied: ipywidgets in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (7.6.3)\n    Collecting parameterized\n      Downloading parameterized-0.8.1-py2.py3-none-any.whl (26 kB)\n    Collecting pyannote.core\n      Downloading pyannote.core-4.1-py3-none-any.whl (56 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 56 kB 6.4 MB/s \n    \u001b[?25hRequirement already satisfied: editdistance in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (0.5.3)\n    Requirement already satisfied: soundfile in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (0.10.3.post1)\n    Collecting sacrebleu[ja]\n      Downloading sacrebleu-2.0.0-py3-none-any.whl (90 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 90 kB 13.6 MB/s \n    \u001b[?25hCollecting torch-stft\n      Downloading torch_stft-0.1.4-py3-none-any.whl (6.2 kB)\n    Collecting megatron-lm==2.2.0\n      Downloading megatron_lm-2.2.0-py3-none-any.whl (171 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 171 kB 77.3 MB/s \n    \u001b[?25hCollecting frozendict\n      Downloading frozendict-2.0.6-py3-none-any.whl (8.3 kB)\n    Collecting kaldiio\n      Downloading kaldiio-2.17.2.tar.gz (24 kB)\n    Collecting unidecode\n      Downloading Unidecode-1.2.0-py2.py3-none-any.whl (241 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 241 kB 67.8 MB/s \n    \u001b[?25hCollecting pypinyin\n      Downloading pypinyin-0.42.0-py2.py3-none-any.whl (1.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.3 MB 67.6 MB/s \n    \u001b[?25hCollecting boto3\n      Downloading boto3-1.18.26-py3-none-any.whl (131 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 131 kB 67.4 MB/s \n    \u001b[?25hRequirement already satisfied: h5py in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (3.1.0)\n    Requirement already satisfied: pytest in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (3.6.4)\n    Collecting braceexpand\n      Downloading braceexpand-0.1.7-py2.py3-none-any.whl (5.9 kB)\n    Collecting pesq\n      Downloading pesq-0.0.3.tar.gz (35 kB)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (1.1.5)\n    Requirement already satisfied: click>=6.5 in /usr/local/lib/python3.7/dist-packages (from black==19.10b0->nemo_toolkit[all]) (7.1.2)\n    Collecting typed-ast>=1.4.0\n      Downloading typed_ast-1.4.3-cp37-cp37m-manylinux1_x86_64.whl (743 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 743 kB 64.0 MB/s \n    \u001b[?25hRequirement already satisfied: attrs>=18.1.0 in /usr/local/lib/python3.7/dist-packages (from black==19.10b0->nemo_toolkit[all]) (21.2.0)\n    Collecting pathspec<1,>=0.6\n      Downloading pathspec-0.9.0-py2.py3-none-any.whl (31 kB)\n    Requirement already satisfied: appdirs in /usr/local/lib/python3.7/dist-packages (from black==19.10b0->nemo_toolkit[all]) (1.4.4)\n    Requirement already satisfied: toml>=0.9.4 in /usr/local/lib/python3.7/dist-packages (from black==19.10b0->nemo_toolkit[all]) (0.10.2)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from megatron-lm==2.2.0->nemo_toolkit[all]) (1.15.0)\n    Collecting pybind11\n      Downloading pybind11-2.7.1-py2.py3-none-any.whl (200 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 200 kB 72.7 MB/s \n    \u001b[?25hCollecting antlr4-python3-runtime==4.8\n      Downloading antlr4-python3-runtime-4.8.tar.gz (112 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 112 kB 55.7 MB/s \n    \u001b[?25hRequirement already satisfied: importlib-resources in /usr/local/lib/python3.7/dist-packages (from hydra-core>=1.1.0->nemo_toolkit[all]) (5.2.2)\n    Collecting PyYAML>=5.1.0\n      Downloading PyYAML-5.4.1-cp37-cp37m-manylinux1_x86_64.whl (636 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 636 kB 60.1 MB/s \n    \u001b[?25hCollecting pip-api\n      Downloading pip_api-0.0.20-py3-none-any.whl (112 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 112 kB 70.3 MB/s \n    \u001b[?25hCollecting pipreqs\n      Downloading pipreqs-0.4.10-py2.py3-none-any.whl (25 kB)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=3.3.2->nemo_toolkit[all]) (1.3.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=3.3.2->nemo_toolkit[all]) (0.10.0)\n    Requirement already satisfied: pyparsing>=2.2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=3.3.2->nemo_toolkit[all]) (2.4.7)\n    Requirement already satisfied: typing-extensions>=3.6.2.1 in /usr/local/lib/python3.7/dist-packages (from onnx>=1.7.0->nemo_toolkit[all]) (3.7.4.3)\n    Requirement already satisfied: protobuf in /usr/local/lib/python3.7/dist-packages (from onnx>=1.7.0->nemo_toolkit[all]) (3.17.3)\n    Collecting future>=0.17.1\n      Downloading future-0.18.2.tar.gz (829 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 829 kB 67.3 MB/s \n    \u001b[?25hCollecting pyDeprecate==0.3.0\n      Downloading pyDeprecate-0.3.0-py3-none-any.whl (10 kB)\n    Collecting fsspec[http]!=2021.06.0,>=2021.05.0\n      Downloading fsspec-2021.7.0-py3-none-any.whl (118 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 118 kB 64.5 MB/s \n    \u001b[?25hRequirement already satisfied: tensorboard!=2.5.0,>=2.2.0 in /usr/local/lib/python3.7/dist-packages (from pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (2.6.0)\n    Collecting aiohttp\n      Downloading aiohttp-3.7.4.post0-cp37-cp37m-manylinux2014_x86_64.whl (1.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.3 MB 58.5 MB/s \n    \u001b[?25hRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (2.23.0)\n    Requirement already satisfied: joblib in /usr/local/lib/python3.7/dist-packages (from sacremoses>=0.0.43->nemo_toolkit[all]) (1.0.1)\n    Requirement already satisfied: absl-py>=0.4 in /usr/local/lib/python3.7/dist-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (0.12.0)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (0.4.5)\n    Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (1.34.0)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (1.8.0)\n    Requirement already satisfied: grpcio>=1.24.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (1.39.0)\n    Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (1.0.1)\n    Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (57.4.0)\n    Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (0.6.1)\n    Requirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.7/dist-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (0.37.0)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (3.3.4)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (4.2.2)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (4.7.2)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (0.2.8)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (1.3.0)\n    Requirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from markdown>=2.6.8->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (4.6.4)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (0.4.8)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (3.0.4)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (1.24.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (2021.5.30)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (2.10)\n    Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (3.1.1)\n    Collecting huggingface-hub==0.0.12\n      Downloading huggingface_hub-0.0.12-py3-none-any.whl (37 kB)\n    Requirement already satisfied: filelock in /usr/local/lib/python3.7/dist-packages (from transformers<=4.8.1,>=4.0.1->nemo_toolkit[all]) (3.0.12)\n    Collecting tokenizers<0.11,>=0.10.1\n      Downloading tokenizers-0.10.3-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (3.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.3 MB 69.3 MB/s \n    \u001b[?25hCollecting multidict<7.0,>=4.5\n      Downloading multidict-5.1.0-cp37-cp37m-manylinux2014_x86_64.whl (142 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 142 kB 71.7 MB/s \n    \u001b[?25hCollecting yarl<2.0,>=1.0\n      Downloading yarl-1.6.3-cp37-cp37m-manylinux2014_x86_64.whl (294 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 294 kB 77.1 MB/s \n    \u001b[?25hCollecting async-timeout<4.0,>=3.0\n      Downloading async_timeout-3.0.1-py3-none-any.whl (8.2 kB)\n    Collecting s3transfer<0.6.0,>=0.5.0\n      Downloading s3transfer-0.5.0-py3-none-any.whl (79 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 79 kB 11.6 MB/s \n    \u001b[?25hCollecting botocore<1.22.0,>=1.21.26\n      Downloading botocore-1.21.26-py3-none-any.whl (7.8 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 7.8 MB 68.7 MB/s \n    \u001b[?25hCollecting jmespath<1.0.0,>=0.7.1\n      Downloading jmespath-0.10.0-py2.py3-none-any.whl (24 kB)\n    Collecting urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1\n      Downloading urllib3-1.25.11-py2.py3-none-any.whl (127 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 127 kB 72.9 MB/s \n    \u001b[?25hCollecting distance>=0.1.3\n      Downloading Distance-0.1.3.tar.gz (180 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 180 kB 74.5 MB/s \n    \u001b[?25hRequirement already satisfied: cached-property in /usr/local/lib/python3.7/dist-packages (from h5py->nemo_toolkit[all]) (1.5.2)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->markdown>=2.6.8->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.4.0,>=1.3.0->nemo_toolkit[all]) (3.5.0)\n    Requirement already satisfied: ipython>=4.0.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->nemo_toolkit[all]) (5.5.0)\n    Requirement already satisfied: widgetsnbextension~=3.5.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->nemo_toolkit[all]) (3.5.1)\n    Requirement already satisfied: ipykernel>=4.5.1 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->nemo_toolkit[all]) (4.10.1)\n    Requirement already satisfied: traitlets>=4.3.1 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->nemo_toolkit[all]) (5.0.5)\n    Requirement already satisfied: nbformat>=4.2.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->nemo_toolkit[all]) (5.1.3)\n    Requirement already satisfied: jupyterlab-widgets>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->nemo_toolkit[all]) (1.0.0)\n    Requirement already satisfied: jupyter-client in /usr/local/lib/python3.7/dist-packages (from ipykernel>=4.5.1->ipywidgets->nemo_toolkit[all]) (5.3.5)\n    Requirement already satisfied: tornado>=4.0 in /usr/local/lib/python3.7/dist-packages (from ipykernel>=4.5.1->ipywidgets->nemo_toolkit[all]) (5.1.1)\n    Requirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets->nemo_toolkit[all]) (0.8.1)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets->nemo_toolkit[all]) (4.4.2)\n    Requirement already satisfied: pexpect in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets->nemo_toolkit[all]) (4.8.0)\n    Requirement already satisfied: pickleshare in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets->nemo_toolkit[all]) (0.7.5)\n    Requirement already satisfied: pygments in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets->nemo_toolkit[all]) (2.6.1)\n    Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets->nemo_toolkit[all]) (1.0.18)\n    Requirement already satisfied: jupyter-core in /usr/local/lib/python3.7/dist-packages (from nbformat>=4.2.0->ipywidgets->nemo_toolkit[all]) (4.7.1)\n    Requirement already satisfied: jsonschema!=2.5.0,>=2.4 in /usr/local/lib/python3.7/dist-packages (from nbformat>=4.2.0->ipywidgets->nemo_toolkit[all]) (2.6.0)\n    Requirement already satisfied: ipython-genutils in /usr/local/lib/python3.7/dist-packages (from nbformat>=4.2.0->ipywidgets->nemo_toolkit[all]) (0.2.0)\n    Requirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython>=4.0.0->ipywidgets->nemo_toolkit[all]) (0.2.5)\n    Requirement already satisfied: notebook>=4.4.1 in /usr/local/lib/python3.7/dist-packages (from widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (5.3.1)\n    Requirement already satisfied: Send2Trash in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (1.8.0)\n    Requirement already satisfied: terminado>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (0.11.0)\n    Requirement already satisfied: nbconvert in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (5.6.1)\n    Requirement already satisfied: jinja2 in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (2.11.3)\n    Requirement already satisfied: pyzmq>=13 in /usr/local/lib/python3.7/dist-packages (from jupyter-client->ipykernel>=4.5.1->ipywidgets->nemo_toolkit[all]) (22.2.1)\n    Requirement already satisfied: ptyprocess in /usr/local/lib/python3.7/dist-packages (from terminado>=0.8.1->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (0.7.0)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (2.0.1)\n    Requirement already satisfied: resampy>=0.2.2 in /usr/local/lib/python3.7/dist-packages (from librosa->nemo_toolkit[all]) (0.2.2)\n    Requirement already satisfied: pooch>=1.0 in /usr/local/lib/python3.7/dist-packages (from librosa->nemo_toolkit[all]) (1.4.0)\n    Requirement already satisfied: audioread>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from librosa->nemo_toolkit[all]) (2.1.9)\n    Requirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba->nemo_toolkit[all]) (0.34.0)\n    Requirement already satisfied: cffi>=1.0 in /usr/local/lib/python3.7/dist-packages (from soundfile->nemo_toolkit[all]) (1.14.6)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.0->soundfile->nemo_toolkit[all]) (2.20)\n    Requirement already satisfied: bleach in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (4.0.0)\n    Requirement already satisfied: testpath in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (0.5.0)\n    Requirement already satisfied: entrypoints>=0.2.2 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (0.3)\n    Requirement already satisfied: mistune<2,>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (0.8.4)\n    Requirement already satisfied: defusedxml in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (0.7.1)\n    Requirement already satisfied: pandocfilters>=1.4.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (1.4.3)\n    Requirement already satisfied: webencodings in /usr/local/lib/python3.7/dist-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (0.5.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->nemo_toolkit[all]) (2018.9)\n    Requirement already satisfied: pip in /usr/local/lib/python3.7/dist-packages (from pip-api->isort[requirements]<5->nemo_toolkit[all]) (21.1.3)\n    Requirement already satisfied: docopt in /usr/local/lib/python3.7/dist-packages (from pipreqs->isort[requirements]<5->nemo_toolkit[all]) (0.6.2)\n    Collecting yarg\n      Downloading yarg-0.1.9-py2.py3-none-any.whl (19 kB)\n    Collecting simplejson>=3.8.1\n      Downloading simplejson-3.17.4-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (129 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 129 kB 55.8 MB/s \n    \u001b[?25hRequirement already satisfied: sortedcontainers>=2.0.4 in /usr/local/lib/python3.7/dist-packages (from pyannote.core->nemo_toolkit[all]) (2.4.0)\n    Requirement already satisfied: tabulate>=0.7.7 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics->nemo_toolkit[all]) (0.8.9)\n    Requirement already satisfied: sympy>=1.1 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics->nemo_toolkit[all]) (1.7.1)\n    Collecting pyannote.database>=4.0.1\n      Downloading pyannote.database-4.1.1-py3-none-any.whl (41 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 41 kB 358 kB/s \n    \u001b[?25hCollecting typer[all]>=0.2.1\n      Downloading typer-0.3.2-py3-none-any.whl (21 kB)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.1->pyannote.metrics->nemo_toolkit[all]) (1.2.1)\n    Collecting colorama<0.5.0,>=0.4.3\n      Downloading colorama-0.4.4-py2.py3-none-any.whl (16 kB)\n    Collecting shellingham<2.0.0,>=1.3.0\n      Downloading shellingham-1.4.0-py2.py3-none-any.whl (9.4 kB)\n    Requirement already satisfied: pluggy<0.8,>=0.5 in /usr/local/lib/python3.7/dist-packages (from pytest->nemo_toolkit[all]) (0.7.1)\n    Requirement already satisfied: atomicwrites>=1.0 in /usr/local/lib/python3.7/dist-packages (from pytest->nemo_toolkit[all]) (1.4.0)\n    Requirement already satisfied: py>=1.5.0 in /usr/local/lib/python3.7/dist-packages (from pytest->nemo_toolkit[all]) (1.10.0)\n    Requirement already satisfied: more-itertools>=4.0.0 in /usr/local/lib/python3.7/dist-packages (from pytest->nemo_toolkit[all]) (8.8.0)\n    Collecting ruamel.yaml.clib>=0.1.2\n      Downloading ruamel.yaml.clib-0.2.6-cp37-cp37m-manylinux1_x86_64.whl (546 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 546 kB 73.2 MB/s \n    \u001b[?25hCollecting portalocker\n      Downloading portalocker-2.3.1-py2.py3-none-any.whl (15 kB)\n    Collecting ipadic<2.0,>=1.0\n      Downloading ipadic-1.0.0.tar.gz (13.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 13.4 MB 210 kB/s \n    \u001b[?25hCollecting mecab-python3==1.0.3\n      Downloading mecab_python3-1.0.3-cp37-cp37m-manylinux1_x86_64.whl (487 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 487 kB 65.2 MB/s \n    \u001b[?25hRequirement already satisfied: babel!=2.0,>=1.3 in /usr/local/lib/python3.7/dist-packages (from sphinx->nemo_toolkit[all]) (2.9.1)\n    Requirement already satisfied: sphinxcontrib-websupport in /usr/local/lib/python3.7/dist-packages (from sphinx->nemo_toolkit[all]) (1.2.4)\n    Requirement already satisfied: docutils>=0.11 in /usr/local/lib/python3.7/dist-packages (from sphinx->nemo_toolkit[all]) (0.17.1)\n    Requirement already satisfied: imagesize in /usr/local/lib/python3.7/dist-packages (from sphinx->nemo_toolkit[all]) (1.2.0)\n    Requirement already satisfied: alabaster<0.8,>=0.7 in /usr/local/lib/python3.7/dist-packages (from sphinx->nemo_toolkit[all]) (0.7.12)\n    Requirement already satisfied: snowballstemmer>=1.1 in /usr/local/lib/python3.7/dist-packages (from sphinx->nemo_toolkit[all]) (2.1.0)\n    Collecting sphinx\n      Downloading Sphinx-4.1.2-py3-none-any.whl (2.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.9 MB 57.8 MB/s \n    \u001b[?25hCollecting pybtex>=0.20\n      Downloading pybtex-0.24.0-py2.py3-none-any.whl (561 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 561 kB 61.2 MB/s \n    \u001b[?25hCollecting pybtex-docutils>=1.0.0\n      Downloading pybtex_docutils-1.0.1-py3-none-any.whl (4.8 kB)\n    Collecting latexcodec>=1.0.4\n      Downloading latexcodec-2.0.1-py2.py3-none-any.whl (18 kB)\n    Collecting sphinxcontrib-jsmath\n      Downloading sphinxcontrib_jsmath-1.0.1-py2.py3-none-any.whl (5.1 kB)\n    Requirement already satisfied: sphinxcontrib-serializinghtml>=1.1.5 in /usr/local/lib/python3.7/dist-packages (from sphinx->nemo_toolkit[all]) (1.1.5)\n    Collecting sphinxcontrib-htmlhelp>=2.0.0\n      Downloading sphinxcontrib_htmlhelp-2.0.0-py2.py3-none-any.whl (100 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 100 kB 14.8 MB/s \n    \u001b[?25hCollecting sphinxcontrib-applehelp\n      Downloading sphinxcontrib_applehelp-1.0.2-py2.py3-none-any.whl (121 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 121 kB 73.0 MB/s \n    \u001b[?25hCollecting sphinxcontrib-qthelp\n      Downloading sphinxcontrib_qthelp-1.0.3-py2.py3-none-any.whl (90 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 90 kB 14.7 MB/s \n    \u001b[?25hCollecting sphinxcontrib-devhelp\n      Downloading sphinxcontrib_devhelp-1.0.2-py2.py3-none-any.whl (84 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 84 kB 5.3 MB/s \n    \u001b[?25hCollecting GitPython>=1.0.0\n      Downloading GitPython-3.1.18-py3-none-any.whl (170 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 170 kB 77.5 MB/s \n    \u001b[?25hCollecting docker-pycreds>=0.4.0\n      Downloading docker_pycreds-0.4.0-py2.py3-none-any.whl (9.0 kB)\n    Requirement already satisfied: psutil>=5.0.0 in /usr/local/lib/python3.7/dist-packages (from wandb->nemo_toolkit[all]) (5.4.8)\n    Collecting configparser>=3.8.1\n      Downloading configparser-5.0.2-py3-none-any.whl (19 kB)\n    Collecting shortuuid>=0.5.0\n      Downloading shortuuid-1.0.1-py3-none-any.whl (7.5 kB)\n    Collecting sentry-sdk>=1.0.0\n      Downloading sentry_sdk-1.3.1-py2.py3-none-any.whl (133 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 133 kB 78.4 MB/s \n    \u001b[?25hCollecting subprocess32>=3.5.3\n      Downloading subprocess32-3.5.4.tar.gz (97 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 97 kB 10.3 MB/s \n    \u001b[?25hCollecting pathtools\n      Downloading pathtools-0.1.2.tar.gz (11 kB)\n    Requirement already satisfied: promise<3,>=2.0 in /usr/local/lib/python3.7/dist-packages (from wandb->nemo_toolkit[all]) (2.3)\n    Collecting gitdb<5,>=4.0.1\n      Downloading gitdb-4.0.7-py3-none-any.whl (63 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 63 kB 2.5 MB/s \n    \u001b[?25hCollecting smmap<5,>=3.0.1\n      Downloading smmap-4.0.0-py2.py3-none-any.whl (24 kB)\n    Building wheels for collected packages: wordninja, antlr4-python3-runtime, future, distance, kaldi-python-io, kaldiio, pesq, pystoi, ipadic, subprocess32, pathtools, wget\n      Building wheel for wordninja (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for wordninja: filename=wordninja-2.0.0-py3-none-any.whl size=541551 sha256=8c42269fbea84faf2b9b649c89973429d4044b23a9f221f24560849fb4b7a497\n      Stored in directory: /root/.cache/pip/wheels/dd/3f/eb/a2692e3d2b9deb1487b09ba4967dd6920bd5032bfd9ff7acfc\n      Building wheel for antlr4-python3-runtime (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for antlr4-python3-runtime: filename=antlr4_python3_runtime-4.8-py3-none-any.whl size=141230 sha256=a2794b0128ad124969b11f910f591c2bcc361d0d131b5a149846a40524c45484\n      Stored in directory: /root/.cache/pip/wheels/ca/33/b7/336836125fc9bb4ceaa4376d8abca10ca8bc84ddc824baea6c\n      Building wheel for future (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for future: filename=future-0.18.2-py3-none-any.whl size=491070 sha256=ffdc73454f71505e101dca629191ddccc8d592f457e72f557ad71c3096d9d3e4\n      Stored in directory: /root/.cache/pip/wheels/56/b0/fe/4410d17b32f1f0c3cf54cdfb2bc04d7b4b8f4ae377e2229ba0\n      Building wheel for distance (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for distance: filename=Distance-0.1.3-py3-none-any.whl size=16275 sha256=b6b56fad8f27c26c371a25e15e78d272003e0108ab75496f8855bf3fd9f2fb9b\n      Stored in directory: /root/.cache/pip/wheels/b2/10/1b/96fca621a1be378e2fe104cfb0d160bb6cdf3d04a3d35266cc\n      Building wheel for kaldi-python-io (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for kaldi-python-io: filename=kaldi_python_io-1.2.2-py3-none-any.whl size=8968 sha256=2ca439f96a389e7abd1b13fcbd83b5ca3493dff3659a2e49b01cafdcbcbff7f7\n      Stored in directory: /root/.cache/pip/wheels/a9/26/38/7678d1ff6cd1bbcbfc0d80b0a29d94d917dfa9ad790b4a85a9\n      Building wheel for kaldiio (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for kaldiio: filename=kaldiio-2.17.2-py3-none-any.whl size=24472 sha256=108e433cf9c7acc191fc98f3868ac6c3d1bd6b7525e3dcc2fbc8ad3aff3fcd53\n      Stored in directory: /root/.cache/pip/wheels/04/07/e8/45641287c59bf6ce41e22259f8680b521c31e6306cb88392ac\n      Building wheel for pesq (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pesq: filename=pesq-0.0.3-cp37-cp37m-linux_x86_64.whl size=209964 sha256=b8706fd82c4909091af59a6582fe9392e058015900358aab1d2bf4da6491e998\n      Stored in directory: /root/.cache/pip/wheels/4f/67/5b/aa7cf31fe0c7199e35c604bb7bc91c629a13726bf221fedba0\n      Building wheel for pystoi (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pystoi: filename=pystoi-0.3.3-py2.py3-none-any.whl size=7793 sha256=f8e282fd6375967c4edad0cb4ea1dd68768f5c773c70f6199cf6c1964fe1a15e\n      Stored in directory: /root/.cache/pip/wheels/46/4a/ad/3ab460193ed0535430b4b1575f255aa6bae69df17453628e86\n      Building wheel for ipadic (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for ipadic: filename=ipadic-1.0.0-py3-none-any.whl size=13556723 sha256=dead0d48768f013a31661b02bd7688f8c4f8bf846e9326ffb4b62f31090c113c\n      Stored in directory: /root/.cache/pip/wheels/33/8b/99/cf0d27191876637cd3639a560f93aa982d7855ce826c94348b\n      Building wheel for subprocess32 (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for subprocess32: filename=subprocess32-3.5.4-py3-none-any.whl size=6502 sha256=a92331d36a1377c6d92a11c5e3c0c0eae192006db6aa932347becd109606d9e0\n      Stored in directory: /root/.cache/pip/wheels/50/ca/fa/8fca8d246e64f19488d07567547ddec8eb084e8c0d7a59226a\n      Building wheel for pathtools (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pathtools: filename=pathtools-0.1.2-py3-none-any.whl size=8807 sha256=6576947218f7fcb666dbb7af4fba4042d4438b174850490cbb852532784ed5c7\n      Stored in directory: /root/.cache/pip/wheels/3e/31/09/fa59cef12cdcfecc627b3d24273699f390e71828921b2cbba2\n      Building wheel for wget (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for wget: filename=wget-3.2-py3-none-any.whl size=9672 sha256=339c981f99d8e9bfc538c16bd5933f8901811a7baef470dd569c50a175238e5e\n      Stored in directory: /root/.cache/pip/wheels/a1/b6/7c/0e63e34eb06634181c63adacca38b79ff8f35c37e3c13e3c02\n    Successfully built wordninja antlr4-python3-runtime future distance kaldi-python-io kaldiio pesq pystoi ipadic subprocess32 pathtools wget\n    Installing collected packages: urllib3, multidict, yarl, async-timeout, typer, smmap, simplejson, shellingham, PyYAML, matplotlib, latexcodec, jmespath, fsspec, colorama, antlr4-python3-runtime, aiohttp, yarg, torchmetrics, tokenizers, sphinxcontrib-qthelp, sphinxcontrib-jsmath, sphinxcontrib-htmlhelp, sphinxcontrib-devhelp, sphinxcontrib-applehelp, sacremoses, ruamel.yaml.clib, pyDeprecate, pybtex, pyannote.core, portalocker, omegaconf, huggingface-hub, gitdb, future, braceexpand, botocore, wget, webdataset, typed-ast, transformers, subprocess32, sphinx, shortuuid, sentry-sdk, sentencepiece, sacrebleu, s3transfer, ruamel.yaml, pytorch-lightning, pybtex-docutils, pybind11, pyannote.database, pipreqs, pip-api, pathtools, pathspec, pangu, opencc, onnx, mecab-python3, isort, ipadic, hydra-core, GitPython, docker-pycreds, distance, configparser, youtokentome, wordninja, wandb, unidecode, torch-stft, sphinxcontrib-bibtex, sox, rapidfuzz, pytest-runner, pystoi, pypinyin, pydub, pyannote.metrics, pesq, parameterized, nemo-toolkit, megatron-lm, marshmallow, kaldiio, kaldi-python-io, kaldi-io, g2p-en, frozendict, boto3, black, attrdict\n      Attempting uninstall: urllib3\n        Found existing installation: urllib3 1.24.3\n        Uninstalling urllib3-1.24.3:\n          Successfully uninstalled urllib3-1.24.3\n      Attempting uninstall: PyYAML\n        Found existing installation: PyYAML 3.13\n        Uninstalling PyYAML-3.13:\n          Successfully uninstalled PyYAML-3.13\n      Attempting uninstall: matplotlib\n        Found existing installation: matplotlib 3.2.2\n        Uninstalling matplotlib-3.2.2:\n          Successfully uninstalled matplotlib-3.2.2\n      Attempting uninstall: future\n        Found existing installation: future 0.16.0\n        Uninstalling future-0.16.0:\n          Successfully uninstalled future-0.16.0\n      Attempting uninstall: sphinx\n        Found existing installation: Sphinx 1.8.5\n        Uninstalling Sphinx-1.8.5:\n          Successfully uninstalled Sphinx-1.8.5\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    datascience 0.10.6 requires folium==0.2.1, but you have folium 0.8.3 which is incompatible.\n    albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Successfully installed GitPython-3.1.18 PyYAML-5.4.1 aiohttp-3.7.4.post0 antlr4-python3-runtime-4.8 async-timeout-3.0.1 attrdict-2.0.1 black-19.10b0 boto3-1.18.26 botocore-1.21.26 braceexpand-0.1.7 colorama-0.4.4 configparser-5.0.2 distance-0.1.3 docker-pycreds-0.4.0 frozendict-2.0.6 fsspec-2021.7.0 future-0.18.2 g2p-en-2.1.0 gitdb-4.0.7 huggingface-hub-0.0.12 hydra-core-1.1.1 ipadic-1.0.0 isort-4.3.21 jmespath-0.10.0 kaldi-io-0.9.4 kaldi-python-io-1.2.2 kaldiio-2.17.2 latexcodec-2.0.1 marshmallow-3.13.0 matplotlib-3.4.3 mecab-python3-1.0.3 megatron-lm-2.2.0 multidict-5.1.0 nemo-toolkit-1.2.0 omegaconf-2.1.1 onnx-1.10.1 opencc-1.1.2 pangu-4.0.6.1 parameterized-0.8.1 pathspec-0.9.0 pathtools-0.1.2 pesq-0.0.3 pip-api-0.0.20 pipreqs-0.4.10 portalocker-2.3.1 pyDeprecate-0.3.0 pyannote.core-4.1 pyannote.database-4.1.1 pyannote.metrics-3.0.1 pybind11-2.7.1 pybtex-0.24.0 pybtex-docutils-1.0.1 pydub-0.25.1 pypinyin-0.42.0 pystoi-0.3.3 pytest-runner-5.3.1 pytorch-lightning-1.3.8 rapidfuzz-1.5.0 ruamel.yaml-0.17.13 ruamel.yaml.clib-0.2.6 s3transfer-0.5.0 sacrebleu-2.0.0 sacremoses-0.0.45 sentencepiece-0.1.96 sentry-sdk-1.3.1 shellingham-1.4.0 shortuuid-1.0.1 simplejson-3.17.4 smmap-4.0.0 sox-1.4.1 sphinx-4.1.2 sphinxcontrib-applehelp-1.0.2 sphinxcontrib-bibtex-2.3.0 sphinxcontrib-devhelp-1.0.2 sphinxcontrib-htmlhelp-2.0.0 sphinxcontrib-jsmath-1.0.1 sphinxcontrib-qthelp-1.0.3 subprocess32-3.5.4 tokenizers-0.10.3 torch-stft-0.1.4 torchmetrics-0.5.0 transformers-4.8.1 typed-ast-1.4.3 typer-0.3.2 unidecode-1.2.0 urllib3-1.25.11 wandb-0.12.0 webdataset-0.1.62 wget-3.2 wordninja-2.0.0 yarg-0.1.9 yarl-1.6.3 youtokentome-1.0.6\n\n\n\n\n\n```python\nfrom nemo.collections import nlp as nemo_nlp\nfrom nemo.utils.exp_manager import exp_manager #\u6a21\u578b\u8bad\u7ec3\u7ba1\u7406\u5de5\u5177\n\nimport os\nimport wget \nimport torch\nimport pytorch_lightning as pl\nfrom omegaconf import OmegaConf #\u914d\u7f6e\u6587\u4ef6\u5de5\u5177\u5e93\n```\n\n    [NeMo W 2021-08-22 14:02:52 optimizers:47] Apex was not found. Using the lamb optimizer will error out.\n    [NeMo W 2021-08-22 14:02:56 experimental:28] Module <class 'nemo.collections.nlp.data.text_normalization.decoder_dataset.TextNormalizationDecoderDataset'> is experimental, not ready for production and is not fully supported. Use at your own risk.\n    [NeMo W 2021-08-22 14:02:56 experimental:28] Module <class 'nemo.collections.nlp.data.text_normalization.tagger_dataset.TextNormalizationTaggerDataset'> is experimental, not ready for production and is not fully supported. Use at your own risk.\n    [NeMo W 2021-08-22 14:02:56 experimental:28] Module <class 'nemo.collections.nlp.data.text_normalization.test_dataset.TextNormalizationTestDataset'> is experimental, not ready for production and is not fully supported. Use at your own risk.\n\n\n    [nltk_data] Downloading package punkt to /root/nltk_data...\n    [nltk_data]   Unzipping tokenizers/punkt.zip.\n\n\n    [NeMo W 2021-08-22 14:02:57 experimental:28] Module <class 'nemo.collections.nlp.models.duplex_text_normalization.duplex_decoder.DuplexDecoderModel'> is experimental, not ready for production and is not fully supported. Use at your own risk.\n    [NeMo W 2021-08-22 14:02:57 experimental:28] Module <class 'nemo.collections.nlp.models.duplex_text_normalization.duplex_tagger.DuplexTaggerModel'> is experimental, not ready for production and is not fully supported. Use at your own risk.\n\n\n    [nltk_data] Downloading package punkt to /root/nltk_data...\n    [nltk_data]   Package punkt is already up-to-date!\n\n\n    [NeMo W 2021-08-22 14:02:57 experimental:28] Module <class 'nemo.collections.nlp.models.duplex_text_normalization.duplex_tn.DuplexTextNormalizationModel'> is experimental, not ready for production and is not fully supported. Use at your own risk.\n\n\n\n```python\n!pwd\n!wget -c https://dl.fbaipublicfiles.com/glue/data/SST-2.zip\n```\n\n    /content\n    --2021-08-22 14:06:06--  https://dl.fbaipublicfiles.com/glue/data/SST-2.zip\n    Resolving dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)... 172.67.9.4, 104.22.74.142, 104.22.75.142, ...\n    Connecting to dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)|172.67.9.4|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 7439277 (7.1M) [application/zip]\n    Saving to: \u2018SST-2.zip\u2019\n    \n    SST-2.zip           100%[===================>]   7.09M  28.8MB/s    in 0.2s    \n    \n    2021-08-22 14:06:07 (28.8 MB/s) - \u2018SST-2.zip\u2019 saved [7439277/7439277]\n    \n\n\n#2 \u521b\u5efa\u7528\u6765\u5b58\u653e\u6570\u636e\u96c6\u548c\u914d\u7f6e\u6587\u4ef6\u7684\u76ee\u5f55\n\n\n```python\n#\u8c03\u7528\u7cfb\u7edf\u6a21\u5757\u5b9a\u4e49\u5e76\u521b\u5efa\u7528\u6765\u5b58\u653e\u6570\u636e\u96c6\u548c\u914d\u7f6e\u6587\u4ef6\u7684\u76ee\u5f55\nDATA_DIR = \"/content\"\nWORK_DIR = \"/content\"\nos.environ['DATA_DIR'] = DATA_DIR\n#! unzip -o SST-2.zip -d {DATA_DIR}\nos.makedirs(WORK_DIR, exist_ok=True)\nos.makedirs(DATA_DIR, exist_ok=True)\n\n#\u6253\u5370\u6570\u636e\u96c6\u4e2d\u7684\u524dn\u884c\u8fdb\u884c\u7b80\u5355\u67e5\u770b\nprint('Contents (first 5 lines) of train.tsv:')\n! head -n 20 {DATA_DIR}/SST-2/train.tsv\n\nprint('\\nContents (first 5 lines) of test.tsv:')\n! head -n 10 {DATA_DIR}/SST-2/test.tsv\n```\n\n    Contents (first 5 lines) of train.tsv:\n    sentence\tlabel\n    hide new secretions from the parental units \t0\n    contains no wit , only labored gags \t0\n    that loves its characters and communicates something rather beautiful about human nature \t1\n    remains utterly satisfied to remain the same throughout \t0\n    on the worst revenge-of-the-nerds clich\u00e9s the filmmakers could dredge up \t0\n    that 's far too tragic to merit such superficial treatment \t0\n    demonstrates that the director of such hollywood blockbusters as patriot games can still turn out a small , personal film with an emotional wallop . \t1\n    of saucy \t1\n    a depressed fifteen-year-old 's suicidal poetry \t0\n    are more deeply thought through than in most ` right-thinking ' films \t1\n    goes to absurd lengths \t0\n    for those moviegoers who complain that ` they do n't make movies like they used to anymore \t0\n    the part where nothing 's happening , \t0\n    saw how bad this movie was \t0\n    lend some dignity to a dumb story \t0\n    the greatest musicians \t1\n    cold movie \t0\n    with his usual intelligence and subtlety \t1\n    redundant concept \t0\n    \n    Contents (first 5 lines) of test.tsv:\n    index\tsentence\n    0\tuneasy mishmash of styles and genres .\n    1\tthis film 's relationship to actual tension is the same as what christmas-tree flocking in a spray can is to actual snow : a poor -- if durable -- imitation .\n    2\tby the end of no such thing the audience , like beatrice , has a watchful affection for the monster .\n    3\tdirector rob marshall went out gunning to make a great one .\n    4\tlathan and diggs have considerable personal charm , and their screen rapport makes the old story seem new .\n    5\ta well-made and often lovely depiction of the mysteries of friendship .\n    6\tnone of this violates the letter of behan 's book , but missing is its spirit , its ribald , full-throated humor .\n    7\talthough it bangs a very cliched drum at times , this crowd-pleaser 's fresh dialogue , energetic music , and good-natured spunk are often infectious .\n    8\tit is not a mass-market entertainment but an uncompromising attempt by one artist to think about another .\n\n\n#3 \u52a0\u8f7d\u6a21\u578b\u7684\u914d\u7f6e\u6587\u4ef6\u5e76\u6253\u5370\n\n\n```python\n#\u5b9a\u4e49\u6a21\u578b\u914d\u7f6e\u6587\u4ef6\u7684\u8def\u5f84\nMODEL_CONFIG = \"text_classification_config.yaml\"\nCONFIG_DIR = WORK_DIR + '/configs/'\nos.makedirs(CONFIG_DIR, exist_ok=True)\n#\u5224\u65ad\u914d\u7f6e\u6587\u4ef6\u662f\u5426\u5df2\u7ecf\u5b58\u5728\nif not os.path.exists(CONFIG_DIR + MODEL_CONFIG):\n    print('Downloading config file...')\n    wget.download('https://raw.githubusercontent.com/NVIDIA/NeMo/main/examples/nlp/text_classification/conf/' + MODEL_CONFIG, CONFIG_DIR)\n    print('Config file downloaded!')\nelse:\n    print ('config file already exists')\nconfig_path = f'{WORK_DIR}/configs/{MODEL_CONFIG}'\nprint(config_path)\n# \u901a\u8fc7OmegaConf\u5de5\u5177\u5e93\u52a0\u8f7d\u6a21\u578b\u914d\u7f6e\u6587\u4ef6\uff0c\u5b9a\u4e49config\u5bf9\u8c61\nconfig = OmegaConf.load(config_path)\nprint(OmegaConf.to_yaml(config))\n```\n\n    Downloading config file...\n    Config file downloaded!\n    /content/configs/text_classification_config.yaml\n    trainer:\n      gpus: 1\n      num_nodes: 1\n      max_epochs: 100\n      max_steps: null\n      accumulate_grad_batches: 1\n      gradient_clip_val: 0.0\n      amp_level: O0\n      precision: 32\n      accelerator: ddp\n      log_every_n_steps: 1\n      val_check_interval: 1.0\n      resume_from_checkpoint: null\n      num_sanity_val_steps: 0\n      checkpoint_callback: false\n      logger: false\n    model:\n      nemo_path: text_classification_model.nemo\n      tokenizer:\n        tokenizer_name: ${model.language_model.pretrained_model_name}\n        vocab_file: null\n        tokenizer_model: null\n        special_tokens: null\n      language_model:\n        pretrained_model_name: bert-base-uncased\n        lm_checkpoint: null\n        config_file: null\n        config: null\n      classifier_head:\n        num_output_layers: 2\n        fc_dropout: 0.1\n      class_labels:\n        class_labels_file: null\n      dataset:\n        num_classes: ???\n        do_lower_case: false\n        max_seq_length: 256\n        class_balancing: null\n        use_cache: false\n      train_ds:\n        file_path: null\n        batch_size: 64\n        shuffle: true\n        num_samples: -1\n        num_workers: 3\n        drop_last: false\n        pin_memory: false\n      validation_ds:\n        file_path: null\n        batch_size: 64\n        shuffle: false\n        num_samples: -1\n        num_workers: 3\n        drop_last: false\n        pin_memory: false\n      test_ds:\n        file_path: null\n        batch_size: 64\n        shuffle: false\n        num_samples: -1\n        num_workers: 3\n        drop_last: false\n        pin_memory: false\n      optim:\n        name: adam\n        lr: 2.0e-05\n        betas:\n        - 0.9\n        - 0.999\n        weight_decay: 0.01\n        sched:\n          name: WarmupAnnealing\n          warmup_steps: null\n          warmup_ratio: 0.1\n          last_epoch: -1\n          monitor: val_loss\n          reduce_on_plateau: false\n      infer_samples:\n      - by the end of no such thing the audience , like beatrice , has a watchful affection\n        for the monster .\n      - director rob marshall went out gunning to make a great one .\n      - uneasy mishmash of styles and genres .\n    exp_manager:\n      exp_dir: null\n      name: TextClassification\n      create_tensorboard_logger: true\n      create_checkpoint_callback: true\n    \n\n\n#4 \u8bbe\u7f6e\u914d\u7f6e\u6587\u4ef6\u53c2\u6570\uff0c\u6307\u5b9a\u6570\u636e\u96c6\n\n\n```python\nconfig.model.dataset.num_classes=2 #\u901a\u8fc7config\u6765\u5b9a\u4e49\u6570\u636e\u96c6\u5206\u7c7b\u7684\u7c7b\u522b\uff1a2\u5206\u7c7b\u4efb\u52a1\nconfig.model.train_ds.file_path = os.path.join(DATA_DIR, 'SST-2/train.tsv')#\u6307\u5b9a\u8bad\u7ec3\u96c6\u8def\u5f84\nconfig.model.validation_ds.file_path = os.path.join(DATA_DIR, 'SST-2/dev.tsv')#\u6307\u5b9a\u9a8c\u8bc1\u96c6\u8def\u5f84\nprint(\"Train dataloader's config: \\n\")\nprint(OmegaConf.to_yaml(config.model.train_ds))\n```\n\n    Train dataloader's config: \n    \n    file_path: /content/SST-2/train.tsv\n    batch_size: 64\n    shuffle: true\n    num_samples: -1\n    num_workers: 3\n    drop_last: false\n    pin_memory: false\n    \n\n\n#5 \u8bbe\u7f6e\u53c2\u6570\u6784\u5efa\u8bad\u7ec3\u5668\n\n\n```python\nconfig.trainer.gpus = 1 if torch.cuda.is_available() else 0 # \u901a\u8fc7\u5224\u65adcuda\u662f\u5426\u7528\u6765\u8bbe\u7f6egpu\u7684\u6570\u91cf\nconfig.trainer.precision = 16 # \u82e5\u4f7f\u7528\u6df7\u5408\u7cbe\u5ea6\u8ba1\u7b97\u53ef\u4ee5\u8bbe\u7f6e\u4e3a16bit\u7cbe\u5ea6\nconfig.trainer.amp_level = \"O1\"# \u82e5\u4f7f\u7528\u6df7\u5408\u7cbe\u5ea6\u8ba1\u7b97\u8fd9\u91cc\u53c2\u6570\u9700\u8bbe\u4e3a\u201c01\u201d\nconfig.trainer.accelerator = None #\u4f7f\u7528\u5206\u5e03\u5f0f\u8bad\u7ec3 in colab set \"dpp\" to None\nconfig.trainer.max_epochs = 10 # \u8bbe\u7f6e\u8bad\u7ec3\u7684epoch\ntrainer = pl.Trainer(**config.trainer) #\u8c03\u7528pytorchlighting\u7684Trainer\u5c06\u8bbe\u7f6e\u597d\u53c2\u6570\u7684\u6a21\u578b\u5b9e\u4f8b\u5316\n```\n\n    GPU available: True, used: True\n    TPU available: False, using: 0 TPU cores\n    Using native 16bit precision.\n\n\n#6 \u8bbe\u7f6e NeMo\u7684\u65e5\u5fd7\u6a21\u578b\u7ba1\u7406\u5668\u00b6\n\n\n\n```python\nprint(OmegaConf.to_yaml(config.exp_manager))\nexp_dir = exp_manager(trainer, config.exp_manager)\nprint(exp_dir)\n```\n\n    exp_dir: null\n    name: TextClassification\n    create_tensorboard_logger: true\n    create_checkpoint_callback: true\n    \n    [NeMo I 2021-08-22 14:12:35 exp_manager:219] Experiments will be logged at /content/nemo_experiments/TextClassification/2021-08-22_14-12-35\n    [NeMo I 2021-08-22 14:12:35 exp_manager:568] TensorboardLogger has been set up\n    /content/nemo_experiments/TextClassification/2021-08-22_14-12-35\n\n\n#7 \u6253\u5370NeMo\u4e2d\u53ef\u7528\u7684\u8bed\u8a00\u6a21\u578b\n\n\n```python\nprint(nemo_nlp.modules.get_pretrained_lm_models_list())\n```\n\n    ['megatron-bert-345m-uncased', 'megatron-bert-345m-cased', 'megatron-bert-uncased', 'megatron-bert-cased', 'biomegatron-bert-345m-uncased', 'biomegatron-bert-345m-cased', 'bert-base-uncased', 'bert-large-uncased', 'bert-base-cased', 'bert-large-cased', 'bert-base-multilingual-uncased', 'bert-base-multilingual-cased', 'bert-base-chinese', 'bert-base-german-cased', 'bert-large-uncased-whole-word-masking', 'bert-large-cased-whole-word-masking', 'bert-large-uncased-whole-word-masking-finetuned-squad', 'bert-large-cased-whole-word-masking-finetuned-squad', 'bert-base-cased-finetuned-mrpc', 'bert-base-german-dbmdz-cased', 'bert-base-german-dbmdz-uncased', 'cl-tohoku/bert-base-japanese', 'cl-tohoku/bert-base-japanese-whole-word-masking', 'cl-tohoku/bert-base-japanese-char', 'cl-tohoku/bert-base-japanese-char-whole-word-masking', 'TurkuNLP/bert-base-finnish-cased-v1', 'TurkuNLP/bert-base-finnish-uncased-v1', 'wietsedv/bert-base-dutch-cased', 'distilbert-base-uncased', 'distilbert-base-uncased-distilled-squad', 'distilbert-base-cased', 'distilbert-base-cased-distilled-squad', 'distilbert-base-german-cased', 'distilbert-base-multilingual-cased', 'distilbert-base-uncased-finetuned-sst-2-english', 'roberta-base', 'roberta-large', 'roberta-large-mnli', 'distilroberta-base', 'roberta-base-openai-detector', 'roberta-large-openai-detector', 'albert-base-v1', 'albert-large-v1', 'albert-xlarge-v1', 'albert-xxlarge-v1', 'albert-base-v2', 'albert-large-v2', 'albert-xlarge-v2', 'albert-xxlarge-v2']\n\n\n\n```python\n# HF_DATASETS_OFFLINE=1 \nTRANSFORMERS_OFFLINE=1 #\u53ef\u4ee5\u4f7f\u7528transformer\u4e2d\u52a0\u8f7d\u8fc7\u8bed\u8a00\u6a21\u578b\u7684\u7f13\u5b58\uff0c\u907f\u514d\u6bcf\u6b21\u90fd\u91cd\u65b0\u8fdc\u7a0b\u52a0\u8f7d\u3002\n```\n\n# 8 \u6a21\u578b\u7684\u521d\u59cb\u5316\uff0c\u5c06\u4e2d\u6587Bert\u8bbe\u7f6e\u4e3a\u9884\u8bad\u7ec3\u6a21\u578b\n\n\n```python\nconfig.model.language_model.pretrained_model_name = \"bert-base-chinese\"\nmodel = nemo_nlp.models.TextClassificationModel(cfg=config.model, trainer=trainer)\n```\n\n    [NeMo I 2021-08-22 14:12:56 tokenizer_utils:101] Getting HuggingFace AutoTokenizer with pretrained_model_name: bert-base-chinese, vocab_file: None, special_tokens_dict: {}, and use_fast: False\n\n\n\n    Downloading:   0%|          | 0.00/29.0 [00:00<?, ?B/s]\n\n\n\n    Downloading:   0%|          | 0.00/624 [00:00<?, ?B/s]\n\n\n\n    Downloading:   0%|          | 0.00/110k [00:00<?, ?B/s]\n\n\n\n    Downloading:   0%|          | 0.00/269k [00:00<?, ?B/s]\n\n\n    Using bos_token, but it is not set yet.\n    Using eos_token, but it is not set yet.\n\n\n    [NeMo I 2021-08-22 14:12:59 text_classification_dataset:120] Read 67350 examples from /content/SST-2/train.tsv.\n    [NeMo I 2021-08-22 14:13:00 text_classification_dataset:238] *** Example ***\n    [NeMo I 2021-08-22 14:13:00 text_classification_dataset:239] example 0: ['a', 'moving', 'tale']\n    [NeMo I 2021-08-22 14:13:00 text_classification_dataset:240] subtokens: [CLS] a mo ##ving ta ##le [SEP]\n    [NeMo I 2021-08-22 14:13:00 text_classification_dataset:241] input_ids: 101 143 11303 10369 8346 8268 102\n    [NeMo I 2021-08-22 14:13:00 text_classification_dataset:242] segment_ids: 0 0 0 0 0 0 0\n    [NeMo I 2021-08-22 14:13:00 text_classification_dataset:243] input_mask: 1 1 1 1 1 1 1\n    [NeMo I 2021-08-22 14:13:00 text_classification_dataset:244] label: 1\n    [NeMo I 2021-08-22 14:13:00 text_classification_dataset:238] *** Example ***\n    [NeMo I 2021-08-22 14:13:00 text_classification_dataset:239] example 1: ['intriguing', ',', 'observant']\n    [NeMo I 2021-08-22 14:13:00 text_classification_dataset:240] subtokens: [CLS] int ##ri ##g ##ui ##ng , ob ##ser ##van ##t [SEP]\n    [NeMo I 2021-08-22 14:13:00 text_classification_dataset:241] input_ids: 101 10673 8641 8181 9273 8291 117 12639 9520 13045 8165 102\n    [NeMo I 2021-08-22 14:13:00 text_classification_dataset:242] segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0\n    [NeMo I 2021-08-22 14:13:00 text_classification_dataset:243] input_mask: 1 1 1 1 1 1 1 1 1 1 1 1\n    [NeMo I 2021-08-22 14:13:00 text_classification_dataset:244] label: 1\n    [NeMo I 2021-08-22 14:13:34 data_preprocessing:358] Some stats of the lengths of the sequences:\n    [NeMo I 2021-08-22 14:13:34 data_preprocessing:364] Min: 3 |                  Max: 102 |                  Mean: 19.74785074759833 |                  Median: 15.0\n    [NeMo I 2021-08-22 14:13:34 data_preprocessing:366] 75 percentile: 26.00\n    [NeMo I 2021-08-22 14:13:34 data_preprocessing:367] 99 percentile: 67.00\n\n\n    [NeMo W 2021-08-22 14:13:35 nemo_logging:349] /usr/local/lib/python3.7/dist-packages/torch/utils/data/dataloader.py:481: UserWarning: This DataLoader will create 3 worker processes in total. Our suggested max number of worker in current system is 2, which is smaller than what this DataLoader is going to create. Please be aware that excessive worker creation might get DataLoader running slow or even freeze, lower the worker number to avoid potential slowness/freeze if necessary.\n          cpuset_checked))\n        \n\n\n    [NeMo I 2021-08-22 14:13:35 text_classification_dataset:120] Read 873 examples from /content/SST-2/dev.tsv.\n    [NeMo I 2021-08-22 14:13:35 text_classification_dataset:238] *** Example ***\n    [NeMo I 2021-08-22 14:13:35 text_classification_dataset:239] example 0: ['it', \"'s\", 'a', 'charming', 'and', 'often', 'affecting', 'journey', '.']\n    [NeMo I 2021-08-22 14:13:35 text_classification_dataset:240] subtokens: [CLS] it ' s a ch ##ar ##ming and of ##ten af ##fe ##ct ##ing jo ##urn ##ey . [SEP]\n    [NeMo I 2021-08-22 14:13:35 text_classification_dataset:241] input_ids: 101 8233 112 161 143 9537 8458 10693 8256 8205 11598 11782 9568 8722 8221 13269 12760 8603 119 102\n    [NeMo I 2021-08-22 14:13:35 text_classification_dataset:242] segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n    [NeMo I 2021-08-22 14:13:35 text_classification_dataset:243] input_mask: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n    [NeMo I 2021-08-22 14:13:35 text_classification_dataset:244] label: 1\n    [NeMo I 2021-08-22 14:13:35 text_classification_dataset:238] *** Example ***\n    [NeMo I 2021-08-22 14:13:35 text_classification_dataset:239] example 1: ['unflinchingly', 'bleak', 'and', 'desperate']\n    [NeMo I 2021-08-22 14:13:35 text_classification_dataset:240] subtokens: [CLS] u ##n ##fl ##in ##chi ##ng ##ly bl ##ea ##k and des ##per ##ate [SEP]\n    [NeMo I 2021-08-22 14:13:35 text_classification_dataset:241] input_ids: 101 163 8171 11690 8277 10525 8291 8436 10353 10073 8197 8256 11081 9063 9690 102\n    [NeMo I 2021-08-22 14:13:35 text_classification_dataset:242] segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n    [NeMo I 2021-08-22 14:13:35 text_classification_dataset:243] input_mask: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n    [NeMo I 2021-08-22 14:13:35 text_classification_dataset:244] label: 0\n    [NeMo I 2021-08-22 14:13:36 data_preprocessing:358] Some stats of the lengths of the sequences:\n    [NeMo I 2021-08-22 14:13:36 data_preprocessing:364] Min: 4 |                  Max: 86 |                  Mean: 37.30733944954128 |                  Median: 36.0\n    [NeMo I 2021-08-22 14:13:36 data_preprocessing:366] 75 percentile: 48.00\n    [NeMo I 2021-08-22 14:13:36 data_preprocessing:367] 99 percentile: 76.00\n    [NeMo I 2021-08-22 14:13:36 text_classification_model:217] Dataloader config or file_path for the test is missing, so no data loader for test is created!\n\n\n    [NeMo W 2021-08-22 14:13:36 modelPT:200] You tried to register an artifact under config key=tokenizer.vocab_file but an artifact for it has already been registered.\n\n\n\n    Downloading:   0%|          | 0.00/412M [00:00<?, ?B/s]\n\n\n    Some weights of the model checkpoint at bert-base-chinese were not used when initializing BertModel: ['cls.predictions.transform.dense.bias', 'cls.predictions.bias', 'cls.seq_relationship.bias', 'cls.predictions.transform.dense.weight', 'cls.predictions.transform.LayerNorm.bias', 'cls.predictions.transform.LayerNorm.weight', 'cls.seq_relationship.weight', 'cls.predictions.decoder.weight']\n    - This IS expected if you are initializing BertModel from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n    - This IS NOT expected if you are initializing BertModel from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n    Some weights of the model checkpoint at bert-base-chinese were not used when initializing BertEncoder: ['cls.predictions.transform.dense.bias', 'cls.predictions.bias', 'cls.seq_relationship.bias', 'cls.predictions.transform.dense.weight', 'cls.predictions.transform.LayerNorm.bias', 'cls.predictions.transform.LayerNorm.weight', 'cls.seq_relationship.weight', 'cls.predictions.decoder.weight']\n    - This IS expected if you are initializing BertEncoder from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n    - This IS NOT expected if you are initializing BertEncoder from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n\n\n#9 \u8c03\u7528trainer\u4e2d\u7684fit\u51fd\u6570\u7ed3\u5408\u6570\u636e\u96c6\u5f00\u59cb\u6a21\u578b\u8bad\u7ec3\n\n\n```python\ntrainer.fit(model)\n```\n\n    LOCAL_RANK: 0 - CUDA_VISIBLE_DEVICES: [0]\n\n\n    [NeMo I 2021-08-22 14:14:00 modelPT:750] Optimizer config = Adam (\n        Parameter Group 0\n            amsgrad: False\n            betas: [0.9, 0.999]\n            eps: 1e-08\n            lr: 2e-05\n            weight_decay: 0.01\n        )\n    [NeMo I 2021-08-22 14:14:00 lr_scheduler:625] Scheduler \"<nemo.core.optim.lr_scheduler.WarmupAnnealing object at 0x7f0c7b569450>\" \n        will be used during training (effective maximum steps = 10530) - \n        Parameters : \n        (warmup_steps: null\n        warmup_ratio: 0.1\n        last_epoch: -1\n        max_steps: 10530\n        )\n\n\n    \n      | Name                  | Type                 | Params\n    ---------------------------------------------------------------\n    0 | loss                  | CrossEntropyLoss     | 0     \n    1 | bert_model            | BertEncoder          | 102 M \n    2 | classifier            | SequenceClassifier   | 592 K \n    3 | classification_report | ClassificationReport | 0     \n    ---------------------------------------------------------------\n    102 M     Trainable params\n    0         Non-trainable params\n    102 M     Total params\n    411.439   Total estimated model params size (MB)\n\n\n\n    Training: 0it [00:00, ?it/s]\n\n\n    [NeMo W 2021-08-22 14:14:00 nemo_logging:349] /usr/local/lib/python3.7/dist-packages/torch/utils/data/dataloader.py:481: UserWarning: This DataLoader will create 3 worker processes in total. Our suggested max number of worker in current system is 2, which is smaller than what this DataLoader is going to create. Please be aware that excessive worker creation might get DataLoader running slow or even freeze, lower the worker number to avoid potential slowness/freeze if necessary.\n          cpuset_checked))\n        \n\n\n\n    Validating: 0it [00:00, ?it/s]\n\n\n    [NeMo I 2021-08-22 14:18:51 text_classification_model:165] val_report: \n        label                                                precision    recall       f1           support   \n        label_id: 0                                             77.17      85.28      81.02        428\n        label_id: 1                                             84.21      75.68      79.72        444\n        -------------------\n        micro avg                                               80.39      80.39      80.39        872\n        macro avg                                               80.69      80.48      80.37        872\n        weighted avg                                            80.75      80.39      80.36        872\n        \n\n\n    Epoch 0, global step 1052: val_loss reached 0.41953 (best 0.41953), saving model to \"/content/nemo_experiments/TextClassification/2021-08-22_14-12-35/checkpoints/TextClassification--val_loss=0.42-epoch=0.ckpt\" as top 3\n\n\n\n    Validating: 0it [00:00, ?it/s]\n\n\n    [NeMo I 2021-08-22 14:24:28 text_classification_model:165] val_report: \n        label                                                precision    recall       f1           support   \n        label_id: 0                                             81.37      85.75      83.50        428\n        label_id: 1                                             85.51      81.08      83.24        444\n        -------------------\n        micro avg                                               83.37      83.37      83.37        872\n        macro avg                                               83.44      83.41      83.37        872\n        weighted avg                                            83.48      83.37      83.37        872\n        \n\n\n    Epoch 1, global step 2105: val_loss reached 0.38472 (best 0.38472), saving model to \"/content/nemo_experiments/TextClassification/2021-08-22_14-12-35/checkpoints/TextClassification--val_loss=0.38-epoch=1.ckpt\" as top 3\n\n\n\n    Validating: 0it [00:00, ?it/s]\n\n\n    [NeMo I 2021-08-22 14:30:05 text_classification_model:165] val_report: \n        label                                                precision    recall       f1           support   \n        label_id: 0                                             89.02      71.96      79.59        428\n        label_id: 1                                             77.19      91.44      83.71        444\n        -------------------\n        micro avg                                               81.88      81.88      81.88        872\n        macro avg                                               83.10      81.70      81.65        872\n        weighted avg                                            82.99      81.88      81.69        872\n        \n\n\n    Epoch 2, global step 3158: val_loss reached 0.43869 (best 0.38472), saving model to \"/content/nemo_experiments/TextClassification/2021-08-22_14-12-35/checkpoints/TextClassification--val_loss=0.44-epoch=2.ckpt\" as top 3\n\n\n\n    Validating: 0it [00:00, ?it/s]\n\n\n    [NeMo I 2021-08-22 14:35:39 text_classification_model:165] val_report: \n        label                                                precision    recall       f1           support   \n        label_id: 0                                             76.64      92.76      83.93        428\n        label_id: 1                                             91.24      72.75      80.95        444\n        -------------------\n        micro avg                                               82.57      82.57      82.57        872\n        macro avg                                               83.94      82.75      82.44        872\n        weighted avg                                            84.08      82.57      82.42        872\n        \n\n\n    Epoch 3, global step 4211: val_loss reached 0.42369 (best 0.38472), saving model to \"/content/nemo_experiments/TextClassification/2021-08-22_14-12-35/checkpoints/TextClassification--val_loss=0.42-epoch=3.ckpt\" as top 3\n\n\n\n    Validating: 0it [00:00, ?it/s]\n\n\n    [NeMo I 2021-08-22 14:41:14 text_classification_model:165] val_report: \n        label                                                precision    recall       f1           support   \n        label_id: 0                                             86.45      74.53      80.05        428\n        label_id: 1                                             78.33      88.74      83.21        444\n        -------------------\n        micro avg                                               81.77      81.77      81.77        872\n        macro avg                                               82.39      81.64      81.63        872\n        weighted avg                                            82.32      81.77      81.66        872\n        \n\n\n    Epoch 4, global step 5264: val_loss was not in top 3\n\n\n\n    Validating: 0it [00:00, ?it/s]\n\n\n    [NeMo I 2021-08-22 14:46:24 text_classification_model:165] val_report: \n        label                                                precision    recall       f1           support   \n        label_id: 0                                             87.82      55.61      68.10        428\n        label_id: 1                                             68.39      92.57      78.66        444\n        -------------------\n        micro avg                                               74.43      74.43      74.43        872\n        macro avg                                               78.10      74.09      73.38        872\n        weighted avg                                            77.93      74.43      73.48        872\n        \n\n\n    Epoch 5, global step 6317: val_loss was not in top 3\n\n\n\n    Validating: 0it [00:00, ?it/s]\n\n\n    [NeMo I 2021-08-22 14:51:35 text_classification_model:165] val_report: \n        label                                                precision    recall       f1           support   \n        label_id: 0                                             86.34      73.83      79.60        428\n        label_id: 1                                             77.87      88.74      82.95        444\n        -------------------\n        micro avg                                               81.42      81.42      81.42        872\n        macro avg                                               82.10      81.29      81.27        872\n        weighted avg                                            82.02      81.42      81.30        872\n        \n\n\n    Epoch 6, global step 7370: val_loss was not in top 3\n\n\n\n    Validating: 0it [00:00, ?it/s]\n\n\n    [NeMo I 2021-08-22 14:56:46 text_classification_model:165] val_report: \n        label                                                precision    recall       f1           support   \n        label_id: 0                                             84.34      78.04      81.07        428\n        label_id: 1                                             80.25      86.04      83.04        444\n        -------------------\n        micro avg                                               82.11      82.11      82.11        872\n        macro avg                                               82.30      82.04      82.06        872\n        weighted avg                                            82.26      82.11      82.07        872\n        \n\n\n    Epoch 7, global step 8423: val_loss was not in top 3\n\n\n\n    Validating: 0it [00:00, ?it/s]\n\n\n    [NeMo I 2021-08-22 15:01:55 text_classification_model:165] val_report: \n        label                                                precision    recall       f1           support   \n        label_id: 0                                             86.55      69.16      76.88        428\n        label_id: 1                                             75.09      89.64      81.72        444\n        -------------------\n        micro avg                                               79.59      79.59      79.59        872\n        macro avg                                               80.82      79.40      79.30        872\n        weighted avg                                            80.72      79.59      79.35        872\n        \n\n\n    Epoch 8, global step 9476: val_loss was not in top 3\n\n\n\n    Validating: 0it [00:00, ?it/s]\n\n\n    [NeMo I 2021-08-22 15:07:06 text_classification_model:165] val_report: \n        label                                                precision    recall       f1           support   \n        label_id: 0                                             86.71      70.09      77.52        428\n        label_id: 1                                             75.67      89.64      82.06        444\n        -------------------\n        micro avg                                               80.05      80.05      80.05        872\n        macro avg                                               81.19      79.87      79.79        872\n        weighted avg                                            81.08      80.05      79.83        872\n        \n\n\n    Epoch 9, global step 10529: val_loss was not in top 3\n    Saving latest checkpoint...\n\n\n#10 \u6a21\u578b\u7684\u9a8c\u8bc1Evaluation\n\n\n```python\nqueries = ['\"\u5f88\u597d,\u5f88\u5b9e\u60e0\"',\n            '\u914d\u9001\u5458\u5f88\u597d',\n            '\u4e0d\u9519\uff0c\u5c31\u662f\u9910\u76d2\u8d35',\n            '\u706b\u70e7\u5939\u8089\u597d\u54b8\u554a\uff01\u6ca1\u6cd5\u5403\u3002\u5176\u4ed6\u8fd8\u884c',\n            \"\u5473\u9053\u4e0d\u9519,\u914d\u9001\u901f\u5ea6\u6bd4\u9884\u8ba1\u5feb\",\n            '\u6ca1\u4ec0\u4e48\u5473\u9053\uff0c\u9001\u6765\u7684\u665a\u51c9\u4e86',\n            '\u5b8c\u5168\u4e0d\u503c\u5f97\u4fe1\u4efb\uff0c\u51fa\u5c14\u53cd\u800c',\n            '\u6ca1\u53d1\u7968\uff0c\u4e71\u6536\u8d39\uff0c\u8ba2\u5355\u6ca1\u5230\u5c31\u88ab\u5b8c\u6210\u4e86',\n            '\u9e21\u86cb\u90fd\u574f\u4e86\uff0c\u51c9\u83dc\u4e5f\u6d12\u4e86',\n            '\u5f88 \u5feb \uff0c \u597d \u5403 \uff0c \u5473 \u9053 \u8db3 \uff0c \u91cf \u5927 ',\n           '\u5f88\u68d2\uff01\u592a\u5feb\u4e86',\n           '\u548c\u5e97\u91cc\u70b9\u7684\u6c34\u5e73\u5dee\u5f88\u591a',\n           '\u633a\u5feb\u7684\uff0c\u4f46\u662f\u5473\u9053\u4e0d\u592a\u597d',\n           '\u6211\u70b9\u7684\u51c9\u83dc\uff0c\u7ed9\u6211\u9001\u4e00\u76d2\u70ed\u7684\u70c2\u767d\u83dc',\n           '\u597d\u670d\u52a1\uff0c\u5c31\u662f\u4e60\u60ef\u767e\u5ea6\u5916\u5356\u7684\u5feb\u901f',\n           '\u633a\u597d\u5403\u7684\uff0c\u5c31\u662f\u6709\u70b9\u96be\u5403',\n           '\u6211\u5bb6\u7684\u72d7\u5403\u4e86\u8fde\u591c\u7ed9\u6211\u505a\u4e86\u56db\u83dc\u4e00\u6c64',\n           '\u4e0d\u9519\uff0c\u53ea\u4e0d\u8fc7\u8fd9\u5473\u9053\u5bf9\u4e8e\u4eba\u7c7b\u6765\u8bb2\u8d85\u524d\u4e86\u4e00\u4e9b\uff0c\u72d7\u89c9\u5f97\u633a\u597d\u5403\u7684']\n           \n     \nresults = model.classifytext(queries=queries, batch_size=3, max_seq_length=512)\n\nprint('The prediction results of some sample queries with the trained model:')\nfor query, result in zip(queries, results):\n    print(f'Query : {query}')\n    print(f'Predicted label: {result}')\n```\n\n    [NeMo W 2021-08-22 15:07:51 nemo_logging:349] /usr/local/lib/python3.7/dist-packages/torch/utils/data/dataloader.py:481: UserWarning: This DataLoader will create 3 worker processes in total. Our suggested max number of worker in current system is 2, which is smaller than what this DataLoader is going to create. Please be aware that excessive worker creation might get DataLoader running slow or even freeze, lower the worker number to avoid potential slowness/freeze if necessary.\n          cpuset_checked))\n        \n\n\n    The prediction results of some sample queries with the trained model:\n    Query : \"\u5f88\u597d,\u5f88\u5b9e\u60e0\"\n    Predicted label: 1\n    Query : \u914d\u9001\u5458\u5f88\u597d\n    Predicted label: 1\n    Query : \u4e0d\u9519\uff0c\u5c31\u662f\u9910\u76d2\u8d35\n    Predicted label: 0\n    Query : \u706b\u70e7\u5939\u8089\u597d\u54b8\u554a\uff01\u6ca1\u6cd5\u5403\u3002\u5176\u4ed6\u8fd8\u884c\n    Predicted label: 0\n    Query : \u5473\u9053\u4e0d\u9519,\u914d\u9001\u901f\u5ea6\u6bd4\u9884\u8ba1\u5feb\n    Predicted label: 0\n    Query : \u6ca1\u4ec0\u4e48\u5473\u9053\uff0c\u9001\u6765\u7684\u665a\u51c9\u4e86\n    Predicted label: 0\n    Query : \u5b8c\u5168\u4e0d\u503c\u5f97\u4fe1\u4efb\uff0c\u51fa\u5c14\u53cd\u800c\n    Predicted label: 0\n    Query : \u6ca1\u53d1\u7968\uff0c\u4e71\u6536\u8d39\uff0c\u8ba2\u5355\u6ca1\u5230\u5c31\u88ab\u5b8c\u6210\u4e86\n    Predicted label: 0\n    Query : \u9e21\u86cb\u90fd\u574f\u4e86\uff0c\u51c9\u83dc\u4e5f\u6d12\u4e86\n    Predicted label: 0\n    Query : \u5f88 \u5feb \uff0c \u597d \u5403 \uff0c \u5473 \u9053 \u8db3 \uff0c \u91cf \u5927 \n    Predicted label: 0\n    Query : \u5f88\u68d2\uff01\u592a\u5feb\u4e86\n    Predicted label: 1\n    Query : \u548c\u5e97\u91cc\u70b9\u7684\u6c34\u5e73\u5dee\u5f88\u591a\n    Predicted label: 0\n    Query : \u633a\u5feb\u7684\uff0c\u4f46\u662f\u5473\u9053\u4e0d\u592a\u597d\n    Predicted label: 0\n    Query : \u6211\u70b9\u7684\u51c9\u83dc\uff0c\u7ed9\u6211\u9001\u4e00\u76d2\u70ed\u7684\u70c2\u767d\u83dc\n    Predicted label: 0\n    Query : \u597d\u670d\u52a1\uff0c\u5c31\u662f\u4e60\u60ef\u767e\u5ea6\u5916\u5356\u7684\u5feb\u901f\n    Predicted label: 0\n    Query : \u633a\u597d\u5403\u7684\uff0c\u5c31\u662f\u6709\u70b9\u96be\u5403\n    Predicted label: 0\n    Query : \u6211\u5bb6\u7684\u72d7\u5403\u4e86\u8fde\u591c\u7ed9\u6211\u505a\u4e86\u56db\u83dc\u4e00\u6c64\n    Predicted label: 0\n    Query : \u4e0d\u9519\uff0c\u53ea\u4e0d\u8fc7\u8fd9\u5473\u9053\u5bf9\u4e8e\u4eba\u7c7b\u6765\u8bb2\u8d85\u524d\u4e86\u4e00\u4e9b\uff0c\u72d7\u89c9\u5f97\u633a\u597d\u5403\u7684\n    Predicted label: 0\n\n\n\n```python\nmodel.save_to(\"sentiment_classify_model.nemo\")\n```\n", "meta": {"hexsha": "0e65c5b3755ef736abc5af8ca8876b19c3695c9c", "size": 310783, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Text_Classification_Sentiment_Analysis_8_12_final_Copy2.ipynb", "max_stars_repo_name": "you-know-who-2017/NeMoSystem", "max_stars_repo_head_hexsha": "be489940b6e9d4acf47fd8813d580bc290b118e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Text_Classification_Sentiment_Analysis_8_12_final_Copy2.ipynb", "max_issues_repo_name": "you-know-who-2017/NeMoSystem", "max_issues_repo_head_hexsha": "be489940b6e9d4acf47fd8813d580bc290b118e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Text_Classification_Sentiment_Analysis_8_12_final_Copy2.ipynb", "max_forks_repo_name": "you-know-who-2017/NeMoSystem", "max_forks_repo_head_hexsha": "be489940b6e9d4acf47fd8813d580bc290b118e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-20T07:04:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T07:04:15.000Z", "avg_line_length": 41.8675737572, "max_line_length": 1652, "alphanum_fraction": 0.5106714331, "converted": true, "num_tokens": 24884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552952031526044, "lm_q2_score": 0.05033063758314071, "lm_q1q2_score": 0.022423784819577897}}
{"text": "# Build Week 2 -- Modeling Project\n\n## Unzipping, Reading CSV, and Creating a DF via Concatenation\n\n\n```python\n# import os\n# import zipfile\n\n# ## Unzipping each file in the filefolder and putting them in the 'unzipped' directory\n# def gather_data(filefolder):\n#     \"\"\" Produces List of Documents from a Directory\n#     filefolder (str): a path of .zip files\n#     returns list of strings\"\"\"\n    \n#     files = os.listdir(filefolder) \n#     for csv_zips in files: \n#         path = os.path.join(filefolder, csv_zips)\n#         if  path[-3:] == 'zip':\n#             with zipfile.ZipFile(path, 'r') as zip_ref:\n#                 zip_ref.extractall('./SPX CBOE Data/unzipped')\n\n                \n# ## Calling the gather_data function (above)\n# gather_data('./SPX CBOE Data')\n```\n\n\n```python\n# import pandas as pd\n\n# ## Instantiating a new, empty list\n# lst = []\n\n# ## Reading in one CSV at a time, sampling 10%, and then appending the sample to 'lst'\n# def readin_csv(filefolder):\n#     \"\"\"Reads in a list of csv documents from a directory \n#     filefoler (str): a path of .csv files returns list of \n#     strings\"\"\"\n    \n#     files = os.listdir(filefolder)\n#     for csvs in files:\n#         path = os.path.join(filefolder, csvs)\n#         if  path[-3:] == 'csv':\n#             temp_frame = pd.read_csv(path)\n#             lst.append(temp_frame.sample(frac = 0.1))\n\n            \n# ## Calling the readin_csv function (above)\n# readin_csv('./SPX CBOE Data/unzipped')\n\n# ## Viewing the first couple of rows 'lst'\n# lst[:5]\n```\n\n\n```python\n# ## Viewing all the available rows\n# pd.set_option('display.max_columns', None)\n\n# ## Creating a pandas dataframe by concatenating the list objects\n# df = pd.concat(objs = lst, axis = 0)\n\n# # CHECK:\n# print(df.shape)\n# df.head()\n```\n\n\n```python\n# df.to_csv('df_file')\n```\n\n\n```python\n# Ignore Warnings\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\nimport pandas as pd\n# Viewing all the columns\npd.set_option('display.max_columns', None)\n\n# Reading in the csv\ndf = pd.read_csv('df_file', index_col = [0])\n\n# CHECK:\ndf.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>underlying_symbol</th>\n      <th>quote_datetime</th>\n      <th>sequence_number</th>\n      <th>root</th>\n      <th>expiration</th>\n      <th>strike</th>\n      <th>option_type</th>\n      <th>exchange_id</th>\n      <th>trade_size</th>\n      <th>trade_price</th>\n      <th>trade_condition_id</th>\n      <th>canceled_trade_condition_id</th>\n      <th>best_bid</th>\n      <th>best_ask</th>\n      <th>trade_iv</th>\n      <th>trade_delta</th>\n      <th>underlying_bid</th>\n      <th>underlying_ask</th>\n      <th>number_of_exchanges</th>\n      <th>{exchange</th>\n      <th>bid_size</th>\n      <th>bid</th>\n      <th>ask_size</th>\n      <th>ask}[number_of_exchanges]</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>35324</th>\n      <td>^SPX</td>\n      <td>2019-02-26 11:00:22.175</td>\n      <td>108071565</td>\n      <td>SPX</td>\n      <td>2019-06-21</td>\n      <td>2600.0</td>\n      <td>C</td>\n      <td>5</td>\n      <td>1</td>\n      <td>230.2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>229.3</td>\n      <td>230.20</td>\n      <td>0.1764</td>\n      <td>0.7835</td>\n      <td>2789.90</td>\n      <td>2790.73</td>\n      <td>1</td>\n      <td>5.0</td>\n      <td>70.0</td>\n      <td>229.3</td>\n      <td>1.0</td>\n      <td>230.20</td>\n    </tr>\n    <tr>\n      <th>33006</th>\n      <td>^SPX</td>\n      <td>2019-02-26 10:57:01.150</td>\n      <td>103929611</td>\n      <td>SPX</td>\n      <td>2019-04-18</td>\n      <td>2840.0</td>\n      <td>C</td>\n      <td>5</td>\n      <td>3</td>\n      <td>27.7</td>\n      <td>35</td>\n      <td>0</td>\n      <td>27.5</td>\n      <td>27.90</td>\n      <td>0.1114</td>\n      <td>0.3594</td>\n      <td>2791.56</td>\n      <td>2792.38</td>\n      <td>1</td>\n      <td>5.0</td>\n      <td>321.0</td>\n      <td>27.5</td>\n      <td>75.0</td>\n      <td>27.90</td>\n    </tr>\n    <tr>\n      <th>34887</th>\n      <td>^SPX</td>\n      <td>2019-02-26 13:10:58.875</td>\n      <td>197160234</td>\n      <td>SPXW</td>\n      <td>2019-05-17</td>\n      <td>2835.0</td>\n      <td>C</td>\n      <td>5</td>\n      <td>5</td>\n      <td>45.6</td>\n      <td>0</td>\n      <td>0</td>\n      <td>45.6</td>\n      <td>46.00</td>\n      <td>0.1188</td>\n      <td>0.4180</td>\n      <td>2794.04</td>\n      <td>2794.75</td>\n      <td>1</td>\n      <td>5.0</td>\n      <td>14.0</td>\n      <td>45.6</td>\n      <td>14.0</td>\n      <td>46.00</td>\n    </tr>\n    <tr>\n      <th>22376</th>\n      <td>^SPX</td>\n      <td>2019-02-26 10:00:46.050</td>\n      <td>46176372</td>\n      <td>SPX</td>\n      <td>2019-03-15</td>\n      <td>2525.0</td>\n      <td>P</td>\n      <td>5</td>\n      <td>6</td>\n      <td>1.6</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1.6</td>\n      <td>1.65</td>\n      <td>0.2474</td>\n      <td>-0.0276</td>\n      <td>2792.09</td>\n      <td>2793.30</td>\n      <td>1</td>\n      <td>5.0</td>\n      <td>10.0</td>\n      <td>1.6</td>\n      <td>264.0</td>\n      <td>1.65</td>\n    </tr>\n    <tr>\n      <th>2670</th>\n      <td>^SPX</td>\n      <td>2019-02-26 06:33:35.900</td>\n      <td>2585428</td>\n      <td>SPXW</td>\n      <td>2019-02-27</td>\n      <td>2775.0</td>\n      <td>P</td>\n      <td>5</td>\n      <td>1</td>\n      <td>5.5</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5.0</td>\n      <td>5.80</td>\n      <td>0.1596</td>\n      <td>-0.3083</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1</td>\n      <td>5.0</td>\n      <td>86.0</td>\n      <td>5.0</td>\n      <td>43.0</td>\n      <td>5.80</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# Resetting the index for the df since we concatenated random samples to a list\ndf = df.reset_index(drop = True)\n\n# CHECK:\ndf.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>underlying_symbol</th>\n      <th>quote_datetime</th>\n      <th>sequence_number</th>\n      <th>root</th>\n      <th>expiration</th>\n      <th>strike</th>\n      <th>option_type</th>\n      <th>exchange_id</th>\n      <th>trade_size</th>\n      <th>trade_price</th>\n      <th>trade_condition_id</th>\n      <th>canceled_trade_condition_id</th>\n      <th>best_bid</th>\n      <th>best_ask</th>\n      <th>trade_iv</th>\n      <th>trade_delta</th>\n      <th>underlying_bid</th>\n      <th>underlying_ask</th>\n      <th>number_of_exchanges</th>\n      <th>{exchange</th>\n      <th>bid_size</th>\n      <th>bid</th>\n      <th>ask_size</th>\n      <th>ask}[number_of_exchanges]</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>^SPX</td>\n      <td>2019-02-26 11:00:22.175</td>\n      <td>108071565</td>\n      <td>SPX</td>\n      <td>2019-06-21</td>\n      <td>2600.0</td>\n      <td>C</td>\n      <td>5</td>\n      <td>1</td>\n      <td>230.2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>229.3</td>\n      <td>230.20</td>\n      <td>0.1764</td>\n      <td>0.7835</td>\n      <td>2789.90</td>\n      <td>2790.73</td>\n      <td>1</td>\n      <td>5.0</td>\n      <td>70.0</td>\n      <td>229.3</td>\n      <td>1.0</td>\n      <td>230.20</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>^SPX</td>\n      <td>2019-02-26 10:57:01.150</td>\n      <td>103929611</td>\n      <td>SPX</td>\n      <td>2019-04-18</td>\n      <td>2840.0</td>\n      <td>C</td>\n      <td>5</td>\n      <td>3</td>\n      <td>27.7</td>\n      <td>35</td>\n      <td>0</td>\n      <td>27.5</td>\n      <td>27.90</td>\n      <td>0.1114</td>\n      <td>0.3594</td>\n      <td>2791.56</td>\n      <td>2792.38</td>\n      <td>1</td>\n      <td>5.0</td>\n      <td>321.0</td>\n      <td>27.5</td>\n      <td>75.0</td>\n      <td>27.90</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>^SPX</td>\n      <td>2019-02-26 13:10:58.875</td>\n      <td>197160234</td>\n      <td>SPXW</td>\n      <td>2019-05-17</td>\n      <td>2835.0</td>\n      <td>C</td>\n      <td>5</td>\n      <td>5</td>\n      <td>45.6</td>\n      <td>0</td>\n      <td>0</td>\n      <td>45.6</td>\n      <td>46.00</td>\n      <td>0.1188</td>\n      <td>0.4180</td>\n      <td>2794.04</td>\n      <td>2794.75</td>\n      <td>1</td>\n      <td>5.0</td>\n      <td>14.0</td>\n      <td>45.6</td>\n      <td>14.0</td>\n      <td>46.00</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>^SPX</td>\n      <td>2019-02-26 10:00:46.050</td>\n      <td>46176372</td>\n      <td>SPX</td>\n      <td>2019-03-15</td>\n      <td>2525.0</td>\n      <td>P</td>\n      <td>5</td>\n      <td>6</td>\n      <td>1.6</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1.6</td>\n      <td>1.65</td>\n      <td>0.2474</td>\n      <td>-0.0276</td>\n      <td>2792.09</td>\n      <td>2793.30</td>\n      <td>1</td>\n      <td>5.0</td>\n      <td>10.0</td>\n      <td>1.6</td>\n      <td>264.0</td>\n      <td>1.65</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>^SPX</td>\n      <td>2019-02-26 06:33:35.900</td>\n      <td>2585428</td>\n      <td>SPXW</td>\n      <td>2019-02-27</td>\n      <td>2775.0</td>\n      <td>P</td>\n      <td>5</td>\n      <td>1</td>\n      <td>5.5</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5.0</td>\n      <td>5.80</td>\n      <td>0.1596</td>\n      <td>-0.3083</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1</td>\n      <td>5.0</td>\n      <td>86.0</td>\n      <td>5.0</td>\n      <td>43.0</td>\n      <td>5.80</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Data Cleaning, Analysis, Exploration, and Manipulation\n\n\n```python\n# Viewing dtypes and info\ndf.info()\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 2323610 entries, 0 to 2323609\n    Data columns (total 24 columns):\n     #   Column                       Dtype  \n    ---  ------                       -----  \n     0   underlying_symbol            object \n     1   quote_datetime               object \n     2   sequence_number              int64  \n     3   root                         object \n     4   expiration                   object \n     5   strike                       float64\n     6   option_type                  object \n     7   exchange_id                  int64  \n     8   trade_size                   int64  \n     9   trade_price                  float64\n     10  trade_condition_id           int64  \n     11  canceled_trade_condition_id  int64  \n     12  best_bid                     float64\n     13  best_ask                     float64\n     14  trade_iv                     float64\n     15  trade_delta                  float64\n     16  underlying_bid               float64\n     17  underlying_ask               float64\n     18  number_of_exchanges          int64  \n     19  {exchange                    float64\n     20  bid_size                     float64\n     21  bid                          float64\n     22  ask_size                     float64\n     23  ask}[number_of_exchanges]    float64\n    dtypes: float64(13), int64(6), object(5)\n    memory usage: 425.5+ MB\n\n\n\n```python\n##### Creating a Wrangle Function to Clean Data and Create Features: #####\nimport numpy as np\n\n# Creating a wrangling function \ndef wrangle(X):\n    \"\"\"Wrangling a dataframe and creating features \n    in the same way across copies.\"\"\"\n    \n    # Creating a df copy\n    X = X.copy()\n    \n    # Inferring the DateTime format to Dates / Time:\n    X['quote_datetime'] = pd.to_datetime(X['quote_datetime'], infer_datetime_format = True)\n    X['expiration'] = pd.to_datetime(X['expiration'], infer_datetime_format = True)\n    \n    ## DateTime Features:\n    # Dates and Time\n    X['datetime_year_month'] = (X['quote_datetime'].dt.to_period('M')).astype('str') # String for rate substitution later\n    X['datetime_fulldate'] = X['quote_datetime'].dt.date\n    X['datetime_time'] = X['quote_datetime'].dt.time\n    # Time to Maturity (Days)\n    X['time_to_maturity'] = X['expiration'] - X['quote_datetime']\n    X['time_to_maturity'] = X['time_to_maturity'].astype('string')\n    X['time_to_maturity'] = X['time_to_maturity'].str.split(' days').str[0]\n    X['time_to_maturity'] = X['time_to_maturity'].astype('int')\n    \n    ###Column Adjustments:\n    # Column Names Dictionary to make changes\n    col_names = {\n        'best_bid':'option_bid',\n        'best_ask':'option_ask',\n        'bid_size':'option_bid_size',\n        'ask_size':'option_ask_size'\n        \n    }\n    \n    # Column Renaming\n    X.rename(columns = col_names, inplace = True)\n    \n    # Dropping Unnecessary Columns\n    col_drop = ['sequence_number', 'root', 'exchange_id', 'trade_condition_id',\n                'canceled_trade_condition_id','number_of_exchanges','{exchange',\n                'ask}[number_of_exchanges]', 'bid']\n    \n    X.drop(columns = col_drop, inplace = True)\n    \n    \n    ## Feature Engineering:\n    # option_bid_ask_spread -- Option Liquidty Proxy\n    X['option_bid_ask_spread'] = X['option_ask'] - X['option_bid']\n    \n    # underlying_bid_ask_spread -- Underlying Liquidity Proxy\n    X['underlying_bid_ask_spread'] =  X['underlying_ask'] - X['underlying_bid']\n    \n    # bid_ask_size_spread\n    X['option_bid_ask_size_spread'] = X['option_ask_size'] - X['option_bid_size']\n    \n    # underlying_distance_from_strike\n    X['distance_from_strike'] = X['underlying_ask'] - X['strike']\n    \n    # risk_free_rate -- Risk-Free Rate (10yr Treasury) Proxy for 'r' in BSM\n    X['risk_free_rate'] = .0214\n    \n    # annualized volatility for SPX 2019\n    X['annualized_vol'] = .2888\n    \n    # T = Time to Expiration in decimal\n    X['T'] = X['time_to_maturity'] / 365\n    \n    # erT = necessary for BSM model\n    X['erT'] = np.exp(-X['risk_free_rate'] * X['T'])\n    \n        \n    ## Reordering Columns:\n    # Column Ordering\n    col_order = ['underlying_symbol',\n                 'quote_datetime',\n                 'datetime_fulldate',\n                 'datetime_year_month',\n                 'datetime_time',\n                 'expiration',\n                 'time_to_maturity',\n                 'T',\n                 'option_type',   \n                 'strike',\n                 'option_bid',\n                 'option_ask',\n                 'option_bid_size',\n                 'option_ask_size',\n                 'option_bid_ask_spread',\n                 'option_bid_ask_size_spread',\n                 'trade_size',\n                 'trade_iv',\n                 'trade_delta',\n                 'annualized_vol',\n                 'underlying_bid',\n                 'underlying_ask',\n                 'underlying_bid_ask_spread',\n                 'distance_from_strike',\n                 'risk_free_rate',\n                 'erT',\n                 'trade_price']\n    # Changing Order\n    X = X[col_order] \n    \n    \n    ## Creating dataframes with subsets of information based on ordering\n    # Returning only the 2019 year values\n    X = X[X['datetime_year_month'] <= '2019-12']\n    # Where Time to Maturity > 0\n    X = X[X['time_to_maturity'] > 0]\n    # Returning only rows where underlying ask != 0\n    X = X[X['underlying_ask'] != 0]\n    \n    ## Resetting Index again for alignment purposes\n    X = X.reset_index(drop = True)\n        \n    ## Return newly created dataframe\n    return X\n    \n\n    \n# applying the wrangle function from above\ndfx = wrangle(df)\n\n# CHECK:\nprint(dfx.shape)\ndfx.head()\n\n```\n\n    (996664, 27)\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>underlying_symbol</th>\n      <th>quote_datetime</th>\n      <th>datetime_fulldate</th>\n      <th>datetime_year_month</th>\n      <th>datetime_time</th>\n      <th>expiration</th>\n      <th>time_to_maturity</th>\n      <th>T</th>\n      <th>option_type</th>\n      <th>strike</th>\n      <th>option_bid</th>\n      <th>option_ask</th>\n      <th>option_bid_size</th>\n      <th>option_ask_size</th>\n      <th>option_bid_ask_spread</th>\n      <th>option_bid_ask_size_spread</th>\n      <th>trade_size</th>\n      <th>trade_iv</th>\n      <th>trade_delta</th>\n      <th>annualized_vol</th>\n      <th>underlying_bid</th>\n      <th>underlying_ask</th>\n      <th>underlying_bid_ask_spread</th>\n      <th>distance_from_strike</th>\n      <th>risk_free_rate</th>\n      <th>erT</th>\n      <th>trade_price</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>^SPX</td>\n      <td>2019-02-26 11:00:22.175</td>\n      <td>2019-02-26</td>\n      <td>2019-02</td>\n      <td>11:00:22.175000</td>\n      <td>2019-06-21</td>\n      <td>114</td>\n      <td>0.312329</td>\n      <td>C</td>\n      <td>2600.0</td>\n      <td>229.3</td>\n      <td>230.20</td>\n      <td>70.0</td>\n      <td>1.0</td>\n      <td>0.90</td>\n      <td>-69.0</td>\n      <td>1</td>\n      <td>0.1764</td>\n      <td>0.7835</td>\n      <td>0.2888</td>\n      <td>2789.90</td>\n      <td>2790.73</td>\n      <td>0.83</td>\n      <td>190.73</td>\n      <td>0.0214</td>\n      <td>0.993338</td>\n      <td>230.2</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>^SPX</td>\n      <td>2019-02-26 10:57:01.150</td>\n      <td>2019-02-26</td>\n      <td>2019-02</td>\n      <td>10:57:01.150000</td>\n      <td>2019-04-18</td>\n      <td>50</td>\n      <td>0.136986</td>\n      <td>C</td>\n      <td>2840.0</td>\n      <td>27.5</td>\n      <td>27.90</td>\n      <td>321.0</td>\n      <td>75.0</td>\n      <td>0.40</td>\n      <td>-246.0</td>\n      <td>3</td>\n      <td>0.1114</td>\n      <td>0.3594</td>\n      <td>0.2888</td>\n      <td>2791.56</td>\n      <td>2792.38</td>\n      <td>0.82</td>\n      <td>-47.62</td>\n      <td>0.0214</td>\n      <td>0.997073</td>\n      <td>27.7</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>^SPX</td>\n      <td>2019-02-26 13:10:58.875</td>\n      <td>2019-02-26</td>\n      <td>2019-02</td>\n      <td>13:10:58.875000</td>\n      <td>2019-05-17</td>\n      <td>79</td>\n      <td>0.216438</td>\n      <td>C</td>\n      <td>2835.0</td>\n      <td>45.6</td>\n      <td>46.00</td>\n      <td>14.0</td>\n      <td>14.0</td>\n      <td>0.40</td>\n      <td>0.0</td>\n      <td>5</td>\n      <td>0.1188</td>\n      <td>0.4180</td>\n      <td>0.2888</td>\n      <td>2794.04</td>\n      <td>2794.75</td>\n      <td>0.71</td>\n      <td>-40.25</td>\n      <td>0.0214</td>\n      <td>0.995379</td>\n      <td>45.6</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>^SPX</td>\n      <td>2019-02-26 10:00:46.050</td>\n      <td>2019-02-26</td>\n      <td>2019-02</td>\n      <td>10:00:46.050000</td>\n      <td>2019-03-15</td>\n      <td>16</td>\n      <td>0.043836</td>\n      <td>P</td>\n      <td>2525.0</td>\n      <td>1.6</td>\n      <td>1.65</td>\n      <td>10.0</td>\n      <td>264.0</td>\n      <td>0.05</td>\n      <td>254.0</td>\n      <td>6</td>\n      <td>0.2474</td>\n      <td>-0.0276</td>\n      <td>0.2888</td>\n      <td>2792.09</td>\n      <td>2793.30</td>\n      <td>1.21</td>\n      <td>268.30</td>\n      <td>0.0214</td>\n      <td>0.999062</td>\n      <td>1.6</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>^SPX</td>\n      <td>2019-02-26 10:53:02.525</td>\n      <td>2019-02-26</td>\n      <td>2019-02</td>\n      <td>10:53:02.525000</td>\n      <td>2019-03-15</td>\n      <td>16</td>\n      <td>0.043836</td>\n      <td>P</td>\n      <td>2795.0</td>\n      <td>28.2</td>\n      <td>28.60</td>\n      <td>226.0</td>\n      <td>187.0</td>\n      <td>0.40</td>\n      <td>-39.0</td>\n      <td>14</td>\n      <td>0.1107</td>\n      <td>-0.5006</td>\n      <td>0.2888</td>\n      <td>2793.48</td>\n      <td>2794.37</td>\n      <td>0.89</td>\n      <td>-0.63</td>\n      <td>0.0214</td>\n      <td>0.999062</td>\n      <td>27.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## BMS Model (for SPX Options)\n\n### Inputs\n\n\n**S:** Current Stock Price\n\n**X:** Strike\n\n**T:** Time to Expiration (days / 365)\n\n**r:** Annualized Risk-Free Rate (10-year, FFR as proxies??)\n\n\n**sigma:** Annualized Standard Deviation of Stock Returns (Annualized IV?)\n\n\\begin{align}\n\\sigma\n\\end{align}\n\n\n**d1**:\n\n\\begin{equation}\nd_{1} = \\frac{\\ln(\\frac{{S}} {X}) + (r + (\\frac{{\\sigma^2}} 2))T }{\\sigma{\\sqrt T}}\n\\end{equation}\n\n**d2**:\n\n\\begin{equation}\nd_{2} = d_{1} - \\sigma\\sqrt(T)\n\\end{equation}\n\n**N(d1):** Gaussian Distribution of d1 (Call)\n\n**(erf = error function for partial differential equation)**\n\n\\begin{equation}\nN(d_{1}) = \\frac{1 + erf(\\frac{d_{1}} {\\sqrt2})} {2}\n\\end{equation}\n\n\n**N(d2):** Probability Call Option lands ITM\n\n\\begin{equation}\nN(d_{2}) = \\frac{1 + erf(\\frac{d_{2}} {\\sqrt2})} {2}\n\\end{equation}\n\n**iN(d1):** Gaussian Distribution of d1 (Put)\n\n\\begin{equation}\niN(d_{1}) = \\frac{1 + erf(\\frac{-d_{1}} {\\sqrt2})} {2}\n\\end{equation}\n\n**iN(d2):** Probability Put Option lands ITM\n\n\\begin{equation}\niN(d_{2}) = \\frac{1 + erf(\\frac{-d_{2}} {\\sqrt2})} {2}\n\\end{equation}\n\n\n### Outputs\n\n\n\n\n\n\n**Call:**\n\n\\begin{equation}\nC = S_{0}N(d_{1}) - Xe^{-r{T}} N(d_{2})\n\\end{equation}\n\n**Put:**\n\n\\begin{equation}\nP = X{e^{\u2212rT}}N(\u2212d_{2}) \u2212 S_{0}N(\u2212d_{1})\n\\end{equation}\n\n\n```python\nfrom scipy.stats import norm\nimport numpy as np\n\n# BSM Inputs Function\ndef bsm_inputs(dataf):\n    \n    Y = dataf.copy()\n    \n    S = Y['underlying_ask']\n    K = Y['strike']\n    r = Y['risk_free_rate']\n    v = Y['annualized_vol']\n    T = Y['T']\n    \n    D1 = ((np.log(S / K) + (r + (v ** 2 / 2))) * T) / (v * np.sqrt(T))\n    Y['d1'] = D1\n    \n    D2 = D1 - (v * np.sqrt(T))\n    Y['d2'] = D2\n    \n    Nd1 = norm.cdf(D1)\n    Y['nd1'] = Nd1\n    \n    Nd2 = norm.cdf(D2)\n    Y['nd2'] = Nd2\n    \n    return Y\n \n# Calling the function\ndfy = bsm_inputs(dfx)\n\n# CHECK:\nprint(dfy.shape)\ndfy.head()\n\n```\n\n    (996664, 31)\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>underlying_symbol</th>\n      <th>quote_datetime</th>\n      <th>datetime_fulldate</th>\n      <th>datetime_year_month</th>\n      <th>datetime_time</th>\n      <th>expiration</th>\n      <th>time_to_maturity</th>\n      <th>T</th>\n      <th>option_type</th>\n      <th>strike</th>\n      <th>option_bid</th>\n      <th>option_ask</th>\n      <th>option_bid_size</th>\n      <th>option_ask_size</th>\n      <th>option_bid_ask_spread</th>\n      <th>option_bid_ask_size_spread</th>\n      <th>trade_size</th>\n      <th>trade_iv</th>\n      <th>trade_delta</th>\n      <th>annualized_vol</th>\n      <th>underlying_bid</th>\n      <th>underlying_ask</th>\n      <th>underlying_bid_ask_spread</th>\n      <th>distance_from_strike</th>\n      <th>risk_free_rate</th>\n      <th>erT</th>\n      <th>trade_price</th>\n      <th>d1</th>\n      <th>d2</th>\n      <th>nd1</th>\n      <th>nd2</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>^SPX</td>\n      <td>2019-02-26 11:00:22.175</td>\n      <td>2019-02-26</td>\n      <td>2019-02</td>\n      <td>11:00:22.175000</td>\n      <td>2019-06-21</td>\n      <td>114</td>\n      <td>0.312329</td>\n      <td>C</td>\n      <td>2600.0</td>\n      <td>229.3</td>\n      <td>230.20</td>\n      <td>70.0</td>\n      <td>1.0</td>\n      <td>0.90</td>\n      <td>-69.0</td>\n      <td>1</td>\n      <td>0.1764</td>\n      <td>0.7835</td>\n      <td>0.2888</td>\n      <td>2789.90</td>\n      <td>2790.73</td>\n      <td>0.83</td>\n      <td>190.73</td>\n      <td>0.0214</td>\n      <td>0.993338</td>\n      <td>230.2</td>\n      <td>0.259102</td>\n      <td>0.097703</td>\n      <td>0.602222</td>\n      <td>0.538916</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>^SPX</td>\n      <td>2019-02-26 10:57:01.150</td>\n      <td>2019-02-26</td>\n      <td>2019-02</td>\n      <td>10:57:01.150000</td>\n      <td>2019-04-18</td>\n      <td>50</td>\n      <td>0.136986</td>\n      <td>C</td>\n      <td>2840.0</td>\n      <td>27.5</td>\n      <td>27.90</td>\n      <td>321.0</td>\n      <td>75.0</td>\n      <td>0.40</td>\n      <td>-246.0</td>\n      <td>3</td>\n      <td>0.1114</td>\n      <td>0.3594</td>\n      <td>0.2888</td>\n      <td>2791.56</td>\n      <td>2792.38</td>\n      <td>0.82</td>\n      <td>-47.62</td>\n      <td>0.0214</td>\n      <td>0.997073</td>\n      <td>27.7</td>\n      <td>0.059199</td>\n      <td>-0.047690</td>\n      <td>0.523603</td>\n      <td>0.480982</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>^SPX</td>\n      <td>2019-02-26 13:10:58.875</td>\n      <td>2019-02-26</td>\n      <td>2019-02</td>\n      <td>13:10:58.875000</td>\n      <td>2019-05-17</td>\n      <td>79</td>\n      <td>0.216438</td>\n      <td>C</td>\n      <td>2835.0</td>\n      <td>45.6</td>\n      <td>46.00</td>\n      <td>14.0</td>\n      <td>14.0</td>\n      <td>0.40</td>\n      <td>0.0</td>\n      <td>5</td>\n      <td>0.1188</td>\n      <td>0.4180</td>\n      <td>0.2888</td>\n      <td>2794.04</td>\n      <td>2794.75</td>\n      <td>0.71</td>\n      <td>-40.25</td>\n      <td>0.0214</td>\n      <td>0.995379</td>\n      <td>45.6</td>\n      <td>0.078618</td>\n      <td>-0.055741</td>\n      <td>0.531332</td>\n      <td>0.477774</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>^SPX</td>\n      <td>2019-02-26 10:00:46.050</td>\n      <td>2019-02-26</td>\n      <td>2019-02</td>\n      <td>10:00:46.050000</td>\n      <td>2019-03-15</td>\n      <td>16</td>\n      <td>0.043836</td>\n      <td>P</td>\n      <td>2525.0</td>\n      <td>1.6</td>\n      <td>1.65</td>\n      <td>10.0</td>\n      <td>264.0</td>\n      <td>0.05</td>\n      <td>254.0</td>\n      <td>6</td>\n      <td>0.2474</td>\n      <td>-0.0276</td>\n      <td>0.2888</td>\n      <td>2792.09</td>\n      <td>2793.30</td>\n      <td>1.21</td>\n      <td>268.30</td>\n      <td>0.0214</td>\n      <td>0.999062</td>\n      <td>1.6</td>\n      <td>0.118956</td>\n      <td>0.058490</td>\n      <td>0.547345</td>\n      <td>0.523321</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>^SPX</td>\n      <td>2019-02-26 10:53:02.525</td>\n      <td>2019-02-26</td>\n      <td>2019-02</td>\n      <td>10:53:02.525000</td>\n      <td>2019-03-15</td>\n      <td>16</td>\n      <td>0.043836</td>\n      <td>P</td>\n      <td>2795.0</td>\n      <td>28.2</td>\n      <td>28.60</td>\n      <td>226.0</td>\n      <td>187.0</td>\n      <td>0.40</td>\n      <td>-39.0</td>\n      <td>14</td>\n      <td>0.1107</td>\n      <td>-0.5006</td>\n      <td>0.2888</td>\n      <td>2793.48</td>\n      <td>2794.37</td>\n      <td>0.89</td>\n      <td>-0.63</td>\n      <td>0.0214</td>\n      <td>0.999062</td>\n      <td>27.0</td>\n      <td>0.045584</td>\n      <td>-0.014882</td>\n      <td>0.518179</td>\n      <td>0.494063</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n# Modeling\n\n### Train, Validate, Test Split\n\n\n```python\n##### Train, Validation and Test Set Split: #####\nfrom sklearn.model_selection import train_test_split\n\n# Splitting original df into training and testing sets\ntrain, test = train_test_split(dfy, train_size = .9, test_size = .1, random_state = 42)\n\n# Splitting training df into training and validation sets\ntrain, val = train_test_split(train, train_size = .8, test_size = .2, random_state = 42)\n\n# CHECK:\nprint(train.shape, val.shape, test.shape)\ntrain.head()\n\n```\n\n    (717597, 31) (179400, 31) (99667, 31)\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>underlying_symbol</th>\n      <th>quote_datetime</th>\n      <th>datetime_fulldate</th>\n      <th>datetime_year_month</th>\n      <th>datetime_time</th>\n      <th>expiration</th>\n      <th>time_to_maturity</th>\n      <th>T</th>\n      <th>option_type</th>\n      <th>strike</th>\n      <th>option_bid</th>\n      <th>option_ask</th>\n      <th>option_bid_size</th>\n      <th>option_ask_size</th>\n      <th>option_bid_ask_spread</th>\n      <th>option_bid_ask_size_spread</th>\n      <th>trade_size</th>\n      <th>trade_iv</th>\n      <th>trade_delta</th>\n      <th>annualized_vol</th>\n      <th>underlying_bid</th>\n      <th>underlying_ask</th>\n      <th>underlying_bid_ask_spread</th>\n      <th>distance_from_strike</th>\n      <th>risk_free_rate</th>\n      <th>erT</th>\n      <th>trade_price</th>\n      <th>d1</th>\n      <th>d2</th>\n      <th>nd1</th>\n      <th>nd2</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>672013</th>\n      <td>^SPX</td>\n      <td>2019-04-15 11:59:21.400</td>\n      <td>2019-04-15</td>\n      <td>2019-04</td>\n      <td>11:59:21.400000</td>\n      <td>2019-04-17</td>\n      <td>1</td>\n      <td>0.002740</td>\n      <td>P</td>\n      <td>2900.0</td>\n      <td>8.60</td>\n      <td>8.9</td>\n      <td>17.0</td>\n      <td>38.0</td>\n      <td>0.30</td>\n      <td>21.0</td>\n      <td>35</td>\n      <td>0.1007</td>\n      <td>-0.4879</td>\n      <td>0.2888</td>\n      <td>2899.35</td>\n      <td>2900.09</td>\n      <td>0.74</td>\n      <td>0.09</td>\n      <td>0.0214</td>\n      <td>0.999941</td>\n      <td>8.72</td>\n      <td>0.011442</td>\n      <td>-0.003674</td>\n      <td>0.504565</td>\n      <td>0.498534</td>\n    </tr>\n    <tr>\n      <th>178438</th>\n      <td>^SPX</td>\n      <td>2019-12-30 10:26:42.975</td>\n      <td>2019-12-30</td>\n      <td>2019-12</td>\n      <td>10:26:42.975000</td>\n      <td>2020-01-13</td>\n      <td>13</td>\n      <td>0.035616</td>\n      <td>P</td>\n      <td>3000.0</td>\n      <td>2.55</td>\n      <td>2.7</td>\n      <td>460.0</td>\n      <td>299.0</td>\n      <td>0.15</td>\n      <td>-161.0</td>\n      <td>7</td>\n      <td>0.2134</td>\n      <td>-0.0458</td>\n      <td>0.2888</td>\n      <td>3216.94</td>\n      <td>3218.26</td>\n      <td>1.32</td>\n      <td>218.26</td>\n      <td>0.0214</td>\n      <td>0.999238</td>\n      <td>2.60</td>\n      <td>0.087128</td>\n      <td>0.032625</td>\n      <td>0.534715</td>\n      <td>0.513013</td>\n    </tr>\n    <tr>\n      <th>415211</th>\n      <td>^SPX</td>\n      <td>2019-08-09 09:40:32.900</td>\n      <td>2019-08-09</td>\n      <td>2019-08</td>\n      <td>09:40:32.900000</td>\n      <td>2019-09-20</td>\n      <td>41</td>\n      <td>0.112329</td>\n      <td>P</td>\n      <td>2785.0</td>\n      <td>26.00</td>\n      <td>26.4</td>\n      <td>362.0</td>\n      <td>442.0</td>\n      <td>0.40</td>\n      <td>80.0</td>\n      <td>1</td>\n      <td>0.2039</td>\n      <td>-0.2187</td>\n      <td>0.2888</td>\n      <td>2931.36</td>\n      <td>2933.70</td>\n      <td>2.34</td>\n      <td>148.70</td>\n      <td>0.0214</td>\n      <td>0.997599</td>\n      <td>26.20</td>\n      <td>0.133597</td>\n      <td>0.036804</td>\n      <td>0.553139</td>\n      <td>0.514679</td>\n    </tr>\n    <tr>\n      <th>844498</th>\n      <td>^SPX</td>\n      <td>2019-02-11 12:25:20.750</td>\n      <td>2019-02-11</td>\n      <td>2019-02</td>\n      <td>12:25:20.750000</td>\n      <td>2019-02-13</td>\n      <td>1</td>\n      <td>0.002740</td>\n      <td>P</td>\n      <td>2700.0</td>\n      <td>7.70</td>\n      <td>8.0</td>\n      <td>36.0</td>\n      <td>32.0</td>\n      <td>0.30</td>\n      <td>-4.0</td>\n      <td>10</td>\n      <td>0.1522</td>\n      <td>-0.3617</td>\n      <td>0.2888</td>\n      <td>2710.69</td>\n      <td>2711.46</td>\n      <td>0.77</td>\n      <td>11.46</td>\n      <td>0.0214</td>\n      <td>0.999941</td>\n      <td>7.90</td>\n      <td>0.012204</td>\n      <td>-0.002912</td>\n      <td>0.504869</td>\n      <td>0.498838</td>\n    </tr>\n    <tr>\n      <th>666304</th>\n      <td>^SPX</td>\n      <td>2019-06-11 13:55:55.075</td>\n      <td>2019-06-11</td>\n      <td>2019-06</td>\n      <td>13:55:55.075000</td>\n      <td>2019-06-17</td>\n      <td>5</td>\n      <td>0.013699</td>\n      <td>C</td>\n      <td>2920.0</td>\n      <td>5.70</td>\n      <td>5.9</td>\n      <td>66.0</td>\n      <td>108.0</td>\n      <td>0.20</td>\n      <td>42.0</td>\n      <td>1</td>\n      <td>0.1165</td>\n      <td>0.2308</td>\n      <td>0.2888</td>\n      <td>2887.13</td>\n      <td>2887.95</td>\n      <td>0.82</td>\n      <td>-32.05</td>\n      <td>0.0214</td>\n      <td>0.999707</td>\n      <td>5.80</td>\n      <td>0.021101</td>\n      <td>-0.012701</td>\n      <td>0.508417</td>\n      <td>0.494933</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### Assigning Features and Target\n\n\n```python\nimport category_encoders as ce\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import r2_score\n\n# Target and Features\ntarget = 'trade_price'\nbaseline_features = ['underlying_ask', 'option_type']\nbsm_features = ['underlying_ask', 'nd1', 'strike', 'erT', 'nd2', 'option_type']\n\nother_features = ['trade_iv', 'trade_delta', 'option_bid_ask_spread',\n                  'underlying_bid_ask_spread', 'risk_free_rate', 'annualized_vol']\n\nall_features = bsm_features + other_features\n\n\n# y target vector\ny_train = train[target]\ny_val = val[target]\ny_test = test[target]\n```\n\n### Linear Regression\n\n\n```python\nfrom sklearn.pipeline import make_pipeline\n\n##### Linear Model Baseline #####\n\n# Features Assignment\nX_train_baseline = train[baseline_features]\nX_val_baseline = val[baseline_features]\n\n# Linear Regression Pipeline\nlr_pipeline = make_pipeline(\n    ce.OrdinalEncoder(),\n    StandardScaler(),\n    LinearRegression()\n)\n\n# Fitting\nlr_pipeline.fit(X_train_baseline, y_train)\n\n# Prediction\ny_pred_baseline = lr_pipeline.predict(X_val_baseline)\n\n\n# Scoring\ndef scoring_func(pipelinemodel, features, Xval, yval, ypred_val):\n    # Coefficients\n    coefs = pipelinemodel.named_steps['linearregression'].coef_\n    train_coefs = pd.Series(coefs, features)\n    print('Model Coefficients:')\n    print(train_coefs)\n    print('\\n')\n\n    # Intercept\n    intercept = pipelinemodel.named_steps['linearregression'].intercept_\n    print('Intercept:', intercept)\n    print('\\n')\n\n    # Mean Square Error (MSE) and Root Mean Square Error (RMSE)\n    mse = mean_squared_error(yval, ypred_val)\n    rmse = np.sqrt(mse)\n    r2 = r2_score(yval, ypred_val)\n    print('Mean Absolute Error (MSE):', mse)\n    print('Root Mean Square Error (RMSE):', rmse)\n    print('R^2:', r2)\n    \n    return \n\n# Calling the function on the pipeline, feature matrices and target vectors\nscoring_func(lr_pipeline, baseline_features, X_train_baseline, y_val, y_pred_baseline)\n```\n\n    Model Coefficients:\n    underlying_ask   -1.807712\n    option_type       4.838029\n    dtype: float64\n    \n    \n    Intercept: 24.917073649973464\n    \n    \n    Mean Absolute Error (MSE): 3700.744751087443\n    Root Mean Square Error (RMSE): 60.83374681118568\n    R^2: 0.006705199377264437\n\n\n\n```python\nfrom sklearn.pipeline import make_pipeline\n\n##### Linear Model 1 #####\n\n# Features Assignment\nX_train_bsm = train[bsm_features]\nX_val_bsm = val[bsm_features]\n\n# Linear Regression Pipeline\nlr_pipeline = make_pipeline(\n    ce.OrdinalEncoder(),\n    StandardScaler(),\n    LinearRegression()\n)\n\n# Fitting\nlr_pipeline.fit(X_train_bsm, y_train)\n\n# Prediction\ny_pred_bsm = lr_pipeline.predict(X_val_bsm)\n\n# Calling Scoring Function\nscoring_func(lr_pipeline, bsm_features, X_train_bsm, y_val, y_pred_bsm)\n```\n\n    Model Coefficients:\n    underlying_ask     4.985803\n    nd1               42.848123\n    strike           -11.858016\n    erT               -7.297155\n    nd2              -44.485876\n    option_type        8.378632\n    dtype: float64\n    \n    \n    Intercept: 24.917073649973585\n    \n    \n    Mean Absolute Error (MSE): 3277.383476428206\n    Root Mean Square Error (RMSE): 57.248436454004626\n    R^2: 0.12033707111888237\n\n\n\n```python\n##### Linear Model 2 #####\n\n# Features \nX_train_other = train[other_features]\nX_val_other = val[other_features]\n\n# Linear Regression Pipeline\nlr_pipeline2 = make_pipeline(\n    ce.OrdinalEncoder(),\n    StandardScaler(),\n    LinearRegression()\n)\n\n# Fitting\nlr_pipeline2.fit(X_train_other, y_train)\n\n# Prediction\ny_pred_other = lr_pipeline2.predict(X_val_other)\n\n# Calling Scoring Function\nscoring_func(lr_pipeline2, other_features, X_train_other, y_val, y_pred_other)\n```\n\n    Model Coefficients:\n    trade_iv                    -1.493419\n    trade_delta                  7.101365\n    option_bid_ask_spread        5.203738\n    underlying_bid_ask_spread   -0.283583\n    risk_free_rate               0.000000\n    annualized_vol               0.000000\n    dtype: float64\n    \n    \n    Intercept: 24.91707364997346\n    \n    \n    Mean Absolute Error (MSE): 3596.781821856943\n    Root Mean Square Error (RMSE): 59.973175852683866\n    R^2: 0.0346092684249395\n\n\n\n```python\n##### Linear Model 3 #####\n\n# Features \nX_train_all = train[all_features]\nX_val_all = val[all_features]\n\n# Linear Regression Pipeline\nlr_pipeline3 = make_pipeline(\n    ce.OrdinalEncoder(),\n    StandardScaler(),\n    LinearRegression()\n)\n\n# Fitting\nlr_pipeline3.fit(X_train_all, y_train)\n\n# Prediction\ny_pred_all = lr_pipeline3.predict(X_val_all)\n\n# Calling Scoring Function\nscoring_func(lr_pipeline3, all_features, X_train_all, y_val, y_pred_all)\n```\n\n    Model Coefficients:\n    underlying_ask               12.585062\n    nd1                          38.502204\n    strike                      -33.132274\n    erT                          -8.179484\n    nd2                         -50.225008\n    option_type                   2.096062\n    trade_iv                    -16.246464\n    trade_delta                   5.472962\n    option_bid_ask_spread         3.718441\n    underlying_bid_ask_spread     0.025785\n    risk_free_rate                0.000000\n    annualized_vol                0.000000\n    dtype: float64\n    \n    \n    Intercept: 24.91707364997359\n    \n    \n    Mean Absolute Error (MSE): 3171.4963296955093\n    Root Mean Square Error (RMSE): 56.316039719563996\n    R^2: 0.14875760789636716\n\n\n### Permutation Importances on Features\n\n\n```python\nimport eli5\nfrom eli5.sklearn import PermutationImportance\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import r2_score\n\n\n### Linear Model 1 ###\n\n\n# X Features Matrix\nX_train = train[bsm_features]\nX_val = val[bsm_features]\nX_test = test[bsm_features]\n\n# X Features Matrix (Encoded and Scaled)\nencoder = ce.OrdinalEncoder()\nscaler = StandardScaler()\n\nX_train = encoder.fit_transform(X_train)\nX_val = encoder.transform(X_val)\nX_test = encoder.transform(X_test)\n\nX_train_sc = scaler.fit_transform(X_train)\nX_val_sc = scaler.transform(X_val)\nX_test_sc = scaler.transform(X_test)\n\n\n# Creating a df for lm features and data ONLY\nX_train_lm = pd.DataFrame(X_train_sc, columns = bsm_features)\nX_val_lm = pd.DataFrame(X_val_sc, columns = bsm_features)\nX_test_lm = pd.DataFrame(X_test_sc, columns = bsm_features)\n\n\n# Instantiate Model\nlr = LinearRegression()\n\n\n# Fitted Model\nlin_reg1 = lr.fit(X_train_lm, y_train)\n\n\n# Prediction of X_val\ny_pred_val = lin_reg1.predict(X_val_lm)\n\n    \n# Creating the permuter importance \npermutation = PermutationImportance(\n    lin_reg1,\n    scoring = 'r2',\n    n_iter = 10,\n    random_state = 42\n)\n\n\n# Fitting \npermutation.fit(X_val, y_val)\n    \n## eli5 Weightings Chart\n# Adding feature names to a list\nfeature_names = X_val.columns.tolist()\n    \n# eli5 Chart\neli5_weights = eli5.show_weights(\n    permutation,\n    top = None,\n    feature_names = feature_names\n)\n \n# Return    \neli5_weights\n\n```\n\n\n\n\n\n    <style>\n    table.eli5-weights tr:hover {\n        filter: brightness(85%);\n    }\n</style>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n        <table class=\"eli5-weights eli5-feature-importances\" style=\"border-collapse: collapse; border: none; margin-top: 0em; table-layout: auto;\">\n    <thead>\n    <tr style=\"border: none;\">\n        <th style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">Weight</th>\n        <th style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">Feature</th>\n    </tr>\n    </thead>\n    <tbody>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 80.00%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                692.9851\n\n                    &plusmn; 3.1962\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                strike\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 80.19%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                683.7744\n\n                    &plusmn; 4.8399\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                underlying_ask\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 99.51%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                3.4803\n\n                    &plusmn; 0.0146\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                nd2\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 99.59%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                2.7137\n\n                    &plusmn; 0.0285\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                option_type\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(0, 100.00%, 99.99%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                -0.0090\n\n                    &plusmn; 0.0002\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                erT\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(0, 100.00%, 99.51%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                -3.4406\n\n                    &plusmn; 0.0159\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                nd1\n            </td>\n        </tr>\n\n\n    </tbody>\n</table>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#### Other Features\n\n\n```python\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import r2_score\n\n\n### Linear Model 2 ###\n\n\n# X Features Matrix\nX_train = train[other_features]\nX_val = val[other_features]\nX_test = test[other_features]\n\n# X Features Matrix (Encoded and Scaled)\nencoder = ce.OrdinalEncoder()\nscaler = StandardScaler()\n\n# Encoding\nX_train = encoder.fit_transform(X_train)\nX_val = encoder.transform(X_val)\nX_test = encoder.transform(X_test)\n\n# Scaling\nX_train_sc = scaler.fit_transform(X_train)\nX_val_sc = scaler.transform(X_val)\nX_test_sc = scaler.transform(X_test)\n\n\n# Creating a df for lm features and data ONLY\nX_train_lm = pd.DataFrame(X_train_sc, columns = bsm_features)\nX_val_lm = pd.DataFrame(X_val_sc, columns = bsm_features)\nX_test_lm = pd.DataFrame(X_test_sc, columns = bsm_features)\n\n\n# Instantiate Model\nlr = LinearRegression()\n\n\n# Fitted Model\nlin_reg2 = lr.fit(X_train_lm, y_train)\n\n\n# Prediction of X_val\ny_pred_val = lin_reg2.predict(X_val_lm)\n\n\n# Creating the permuter importance \npermutation = PermutationImportance(\n    lin_reg2,\n    scoring = 'r2',\n    n_iter = 10,\n    random_state = 42\n)\n    \n# Fitting \npermutation.fit(X_val, y_val)\n    \n## eli5 Weightings Chart\n# Adding feature names to a list\nfeature_names = X_val.columns.tolist()\n    \n# eli5 Chart\neli5_weights = eli5.show_weights(\n    permutation,\n    top = None,\n    feature_names = feature_names\n)\n \n# Return    \neli5_weights\n```\n\n\n\n\n\n    <style>\n    table.eli5-weights tr:hover {\n        filter: brightness(85%);\n    }\n</style>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n        <table class=\"eli5-weights eli5-feature-importances\" style=\"border-collapse: collapse; border: none; margin-top: 0em; table-layout: auto;\">\n    <thead>\n    <tr style=\"border: none;\">\n        <th style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">Weight</th>\n        <th style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">Feature</th>\n    </tr>\n    </thead>\n    <tbody>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 80.00%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                0.0781\n\n                    &plusmn; 0.0010\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                option_bid_ask_spread\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 95.59%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                0.0090\n\n                    &plusmn; 0.0004\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                trade_delta\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 99.01%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                0.0011\n\n                    &plusmn; 0.0004\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                underlying_bid_ask_spread\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 99.85%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                0.0001\n\n                    &plusmn; 0.0000\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                trade_iv\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(0, 100.00%, 100.00%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                0\n\n                    &plusmn; 0.0000\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                annualized_vol\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(0, 100.00%, 100.00%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                0\n\n                    &plusmn; 0.0000\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                risk_free_rate\n            </td>\n        </tr>\n\n\n    </tbody>\n</table>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n```python\n### Linear Model 3 ###\n\n\n# X Features Matrix\nX_train = train[all_features]\nX_val = val[all_features]\nX_test = test[all_features]\n\n# X Features Matrix (Encoded)\nencoder = ce.OrdinalEncoder()\n\nX_train = encoder.fit_transform(X_train)\nX_val = encoder.transform(X_val)\nX_test = encoder.transform(X_test)\n\n# Standard Scaler\nscaler = StandardScaler()\n\nX_train_sc = scaler.fit_transform(X_train)\nX_val_sc = scaler.transform(X_val)\nX_test_sc = scaler.transform(X_test)\n\n\n# Creating a df for lm features and data ONLY\nX_train_lm = pd.DataFrame(X_train_sc, columns = all_features)\nX_val_lm = pd.DataFrame(X_val_sc, columns = all_features)\nX_test_lm = pd.DataFrame(X_test_sc, columns = all_features)\n\n\n# Instantiate Model\nlr = LinearRegression()\n\n\n# Fitted Model\nlin_reg3 = lr.fit(X_train_lm, y_train)\n\n\n# Prediction of X_val\ny_pred_val = lin_reg3.predict(X_val_lm)\n\n\n# Creating the permuter importance \npermutation = PermutationImportance(\n    lin_reg3,\n    scoring = 'r2',\n    n_iter = 10,\n    random_state = 42\n)\n    \n# Fitting \npermutation.fit(X_val, y_val)\n    \n## eli5 Weightings Chart\n# Adding feature names to a list\nfeature_names = X_val.columns.tolist()\n    \n# eli5 Chart\neli5_weights = eli5.show_weights(\n    permutation,\n    top = None,\n    feature_names = feature_names\n)\n \n# Return    \neli5_weights\n```\n\n\n\n\n\n    <style>\n    table.eli5-weights tr:hover {\n        filter: brightness(85%);\n    }\n</style>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n        <table class=\"eli5-weights eli5-feature-importances\" style=\"border-collapse: collapse; border: none; margin-top: 0em; table-layout: auto;\">\n    <thead>\n    <tr style=\"border: none;\">\n        <th style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">Weight</th>\n        <th style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">Feature</th>\n    </tr>\n    </thead>\n    <tbody>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 80.00%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                4849.3065\n\n                    &plusmn; 47.1054\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                strike\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 80.08%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                4821.7894\n\n                    &plusmn; 35.8425\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                underlying_ask\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 99.72%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                10.9708\n\n                    &plusmn; 0.0656\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                nd2\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 99.84%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                4.7429\n\n                    &plusmn; 0.0226\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                trade_iv\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 99.92%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                1.8945\n\n                    &plusmn; 0.0114\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                option_type\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 99.97%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                0.4948\n\n                    &plusmn; 0.0401\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                trade_delta\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 99.97%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                0.3759\n\n                    &plusmn; 0.0999\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                option_bid_ask_spread\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 100.00%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                0.0122\n\n                    &plusmn; 0.0072\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                underlying_bid_ask_spread\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(0, 100.00%, 100.00%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                0\n\n                    &plusmn; 0.0000\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                annualized_vol\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(0, 100.00%, 100.00%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                0\n\n                    &plusmn; 0.0000\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                risk_free_rate\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(0, 100.00%, 100.00%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                -0.0287\n\n                    &plusmn; 0.0006\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                erT\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(0, 100.00%, 99.76%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                -8.6659\n\n                    &plusmn; 0.0459\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                nd1\n            </td>\n        </tr>\n\n\n    </tbody>\n</table>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n### Random Forest Regressor\n\n#### Random Forest Model 1\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom sklearn.ensemble import RandomForestRegressor\n\n# X Features Matrix\nX_train = train[bsm_features]\nX_val = val[bsm_features]\nX_test = test[bsm_features]\n\n# X Features Matrix (Encoded)\nencoder = ce.OrdinalEncoder()\n\nX_train = encoder.fit_transform(X_train)\nX_val = encoder.transform(X_val)\nX_test = encoder.transform(X_test)\n\n# Instantiate Model\nrf = RandomForestRegressor(n_jobs = -1)\n\n# Fitted Model\nrand_forest1 = rf.fit(X_train, y_train)\ny_pred_test = rf.predict(X_test)\nr2 = r2_score(y_test, y_pred_test)\nprint('R^2 (Validation):', rand_forest1.score(X_val, y_val))\nprint('R^2 (Testing):', r2)\n\n```\n\n    R^2 (Validation): 0.9938802472252234\n    R^2 (Testing): 0.9930189578393516\n\n\n\n```python\n### Graphing:\n\n# Getting Features Importances\nimportances = pd.Series(rand_forest1.feature_importances_, X_train.columns)\n        \n# Plotting Importances\nplt.figure(figsize = (10, 10))\nplt.title('Feature Importances')\nimportances.sort_values(ascending = True).plot.barh(color = 'blue');\n```\n\n\n```python\nimport eli5\nfrom eli5.sklearn import PermutationImportance\n    \n# Creating the permuter importance \npermutation = PermutationImportance(\n    rand_forest1,\n    scoring = 'r2',\n    n_iter = 10,\n    random_state = 42\n)\n    \n# Fitting \npermutation.fit(X_val, y_val)\n    \n## eli5 Weightings Chart\n# Adding feature names to a list\nfeature_names = X_val.columns.tolist()\n    \n# eli5 Chart\neli5_weights = eli5.show_weights(\n    permutation,\n    top = None,\n    feature_names = feature_names\n)\n \n# Return    \neli5_weights\n\n```\n\n\n\n\n\n    <style>\n    table.eli5-weights tr:hover {\n        filter: brightness(85%);\n    }\n</style>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n        <table class=\"eli5-weights eli5-feature-importances\" style=\"border-collapse: collapse; border: none; margin-top: 0em; table-layout: auto;\">\n    <thead>\n    <tr style=\"border: none;\">\n        <th style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">Weight</th>\n        <th style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">Feature</th>\n    </tr>\n    </thead>\n    <tbody>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 80.00%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                7.4716\n\n                    &plusmn; 0.1266\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                option_type\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 83.25%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                5.8012\n\n                    &plusmn; 0.0648\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                nd2\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 92.02%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                2.0112\n\n                    &plusmn; 0.1638\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                strike\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 96.62%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                0.5893\n\n                    &plusmn; 0.0119\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                erT\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 97.07%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                0.4806\n\n                    &plusmn; 0.0110\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                nd1\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 99.75%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                0.0142\n\n                    &plusmn; 0.0012\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                underlying_ask\n            </td>\n        </tr>\n\n\n    </tbody>\n</table>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#### Random Foest Model 2\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom sklearn.ensemble import RandomForestRegressor\n\n# X Features Matrix\nX_train = train[other_features]\nX_val = val[other_features]\nX_test = test[other_features]\n\n# X Features Matrix (Encoded)\nencoder = ce.OrdinalEncoder()\n\nX_train = encoder.fit_transform(X_train)\nX_val = encoder.transform(X_val)\nX_test = encoder.transform(X_test)\n\n# Instantiate Model\nrf = RandomForestRegressor(n_jobs = -1)\n\n# Fitted Model\nrand_forest2 = rf.fit(X_train, y_train)\nprint('R^2:', rand_forest2.score(X_val, y_val))\n```\n\n    R^2: 0.7062095390356222\n\n\n\n```python\n### Graphing:\n\n# Getting Features Importances\nimportances = pd.Series(rand_forest2.feature_importances_, X_train.columns)\n        \n# Plotting Importances\nplt.figure(figsize = (10, 10))\nplt.title('Feature Importances')\nimportances.sort_values(ascending = True).plot.barh(color = 'blue');\n```\n\n\n```python\nimport eli5\nfrom eli5.sklearn import PermutationImportance\n    \n# Creating the permuter importance \npermutation = PermutationImportance(\n    rand_forest2,\n    scoring = 'r2',\n    n_iter = 10,\n    random_state = 42\n)\n    \n# Fitting \npermutation.fit(X_val, y_val)\n    \n## eli5 Weightings Chart\n# Adding feature names to a list\nfeature_names = X_val.columns.tolist()\n    \n# eli5 Chart\neli5_weights = eli5.show_weights(\n    permutation,\n    top = None,\n    feature_names = feature_names\n)\n \n# Return    \neli5_weights\n\n```\n\n\n\n\n\n    <style>\n    table.eli5-weights tr:hover {\n        filter: brightness(85%);\n    }\n</style>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n        <table class=\"eli5-weights eli5-feature-importances\" style=\"border-collapse: collapse; border: none; margin-top: 0em; table-layout: auto;\">\n    <thead>\n    <tr style=\"border: none;\">\n        <th style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">Weight</th>\n        <th style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">Feature</th>\n    </tr>\n    </thead>\n    <tbody>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 80.00%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                1.2090\n\n                    &plusmn; 0.0201\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                trade_delta\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 93.22%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                0.2579\n\n                    &plusmn; 0.0163\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                option_bid_ask_spread\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 94.05%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                0.2140\n\n                    &plusmn; 0.0078\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                trade_iv\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(120, 100.00%, 98.41%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                0.0325\n\n                    &plusmn; 0.0231\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                underlying_bid_ask_spread\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(0, 100.00%, 100.00%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                0\n\n                    &plusmn; 0.0000\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                annualized_vol\n            </td>\n        </tr>\n\n        <tr style=\"background-color: hsl(0, 100.00%, 100.00%); border: none;\">\n            <td style=\"padding: 0 1em 0 0.5em; text-align: right; border: none;\">\n                0\n\n                    &plusmn; 0.0000\n\n            </td>\n            <td style=\"padding: 0 0.5em 0 0.5em; text-align: left; border: none;\">\n                risk_free_rate\n            </td>\n        </tr>\n\n\n    </tbody>\n</table>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "4c85e3f703fd9623324c0833352c3d8261380638", "size": 144133, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "BMS Model Project (Working).ipynb", "max_stars_repo_name": "Struth-Rourke/BSM_Project", "max_stars_repo_head_hexsha": "4263d36fb6a6423b14c1e65fdeb59a89f8c8902b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BMS Model Project (Working).ipynb", "max_issues_repo_name": "Struth-Rourke/BSM_Project", "max_issues_repo_head_hexsha": "4263d36fb6a6423b14c1e65fdeb59a89f8c8902b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BMS Model Project (Working).ipynb", "max_forks_repo_name": "Struth-Rourke/BSM_Project", "max_forks_repo_head_hexsha": "4263d36fb6a6423b14c1e65fdeb59a89f8c8902b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6088337182, "max_line_length": 14684, "alphanum_fraction": 0.4834770663, "converted": true, "num_tokens": 21082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.05500528403338538, "lm_q1q2_score": 0.022405489365810986}}
{"text": "## Initial setup\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```python\nimport tensorflow as tf\nprint(tf.__version__)\n# tensorflow version used is 2.8.0\nimport torch\nprint(torch.__version__)\n# torch version used is 1.10+cu111\n```\n\n    2.8.0\n    1.10.0+cu111\n\n\n\n```python\n!nvidia-smi\n```\n\n    Sun Mar 20 16:57:53 2022       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 460.32.03    Driver Version: 460.32.03    CUDA Version: 11.2     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   47C    P8    10W /  70W |      0MiB / 15109MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    |  No running processes found                                                 |\n    +-----------------------------------------------------------------------------+\n\n\n\n```python\n# Other imports\n! pip install tensorflow_addons\n! pip install tensorflow_io\n! pip install lightgbm\n! pip install xgboost\n! pip install catboost\n\nimport os\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import *\nfrom tensorflow import keras as tfkeras\nimport matplotlib.pyplot as plt\nfrom imutils import paths\nfrom tqdm import tqdm\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nimport tensorflow_datasets as tfds\nimport tensorflow_io as tfio\nimport tensorflow_hub as hub\nimport numpy as np\nimport cv2\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics.pairwise import cosine_similarity as cos\nfrom sympy.utilities.iterables import multiset_permutations\nfrom sklearn.metrics import accuracy_score, f1_score, confusion_matrix, mean_absolute_error, r2_score\nfrom sklearn.model_selection import *\nfrom IPython.display import Image, display\nfrom scipy import ndimage\n\nfrom xgboost import XGBRegressor as xgb\nfrom sklearn.ensemble import ExtraTreesRegressor as extratree\nfrom sklearn.ensemble import RandomForestRegressor as randomforest\nfrom sklearn.svm import NuSVR as svr\nfrom sklearn.gaussian_process import GaussianProcessRegressor as gpr\nfrom sklearn.ensemble import AdaBoostRegressor as ada\nfrom sklearn.tree import DecisionTreeRegressor as tree\nfrom sklearn.ensemble import GradientBoostingRegressor as gdb\nfrom sklearn.neural_network import MLPRegressor as mlp\nfrom sklearn.experimental import enable_hist_gradient_boosting\nfrom sklearn.ensemble import HistGradientBoostingRegressor as hgb\nfrom lightgbm import LGBMRegressor as lgb\nfrom catboost import CatBoostRegressor as cgb\nfrom sklearn.ensemble import StackingRegressor as stk\nfrom sklearn.linear_model import RidgeCV\nfrom sklearn.model_selection import cross_validate, cross_val_predict\nfrom sklearn.ensemble import VotingRegressor as vot\n\nimport zipfile\nimport concurrent.futures\n\n# Random seed fix\nrandom_seed = 42\ntf.random.set_seed(random_seed)\nnp.random.seed(random_seed)\n```\n\n    Collecting tensorflow_addons\n      Downloading tensorflow_addons-0.16.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.1 MB 4.3 MB/s \n    \u001b[?25hRequirement already satisfied: typeguard>=2.7 in /usr/local/lib/python3.7/dist-packages (from tensorflow_addons) (2.7.1)\n    Installing collected packages: tensorflow-addons\n    Successfully installed tensorflow-addons-0.16.1\n    Collecting tensorflow_io\n      Downloading tensorflow_io-0.24.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (23.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 23.4 MB 1.7 MB/s \n    \u001b[?25hRequirement already satisfied: tensorflow-io-gcs-filesystem==0.24.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow_io) (0.24.0)\n    Installing collected packages: tensorflow-io\n    Successfully installed tensorflow-io-0.24.0\n    Requirement already satisfied: lightgbm in /usr/local/lib/python3.7/dist-packages (2.2.3)\n    Requirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from lightgbm) (1.0.2)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from lightgbm) (1.21.5)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from lightgbm) (1.4.1)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->lightgbm) (1.1.0)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->lightgbm) (3.1.0)\n    Requirement already satisfied: xgboost in /usr/local/lib/python3.7/dist-packages (0.90)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from xgboost) (1.21.5)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from xgboost) (1.4.1)\n    Collecting catboost\n      Downloading catboost-1.0.4-cp37-none-manylinux1_x86_64.whl (76.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 76.1 MB 1.3 MB/s \n    \u001b[?25hRequirement already satisfied: graphviz in /usr/local/lib/python3.7/dist-packages (from catboost) (0.10.1)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from catboost) (3.2.2)\n    Requirement already satisfied: pandas>=0.24.0 in /usr/local/lib/python3.7/dist-packages (from catboost) (1.3.5)\n    Requirement already satisfied: numpy>=1.16.0 in /usr/local/lib/python3.7/dist-packages (from catboost) (1.21.5)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from catboost) (1.4.1)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from catboost) (1.15.0)\n    Requirement already satisfied: plotly in /usr/local/lib/python3.7/dist-packages (from catboost) (5.5.0)\n    Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24.0->catboost) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24.0->catboost) (2.8.2)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->catboost) (0.11.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->catboost) (3.0.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->catboost) (1.4.0)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from kiwisolver>=1.0.1->matplotlib->catboost) (3.10.0.2)\n    Requirement already satisfied: tenacity>=6.2.0 in /usr/local/lib/python3.7/dist-packages (from plotly->catboost) (8.0.1)\n    Installing collected packages: catboost\n    Successfully installed catboost-1.0.4\n\n\n    /usr/local/lib/python3.7/dist-packages/sklearn/experimental/enable_hist_gradient_boosting.py:17: UserWarning: Since version 1.0, it is not needed to import enable_hist_gradient_boosting anymore. HistGradientBoostingClassifier and HistGradientBoostingRegressor are now stable and can be normally imported from sklearn.ensemble.\n      \"Since version 1.0, \"\n\n\n## Data utility, only need to use once to preprocess tiff images to png format\n\n\n```python\n%%time\nzf = zipfile.ZipFile('/content/drive/MyDrive/ML course 2022/rawImages.zip')\ndef unzip(file):\n    zf.extract(file)\nwith concurrent.futures.ProcessPoolExecutor() as executor:\n    executor.map(unzip, zf.infolist())\n```\n\n    CPU times: user 14 s, sys: 1.32 s, total: 15.3 s\n    Wall time: 5min 4s\n\n\n\n```python\ndrive.flush_and_unmount()\n```\n\n\n```python\nfor i in range(len(level1_images_train)):\n  img = cv2.imread(level1_images_train[i])\n  if img is None:\n    continue\n  img = cv2.imread(level1_images_train[i])\n  cv2.imwrite('/content/drive/MyDrive/ML course 2022_Team BNL/level1/%s.jpeg' %level1_images_train[i].split('/')[-1][:-5], img)\n```\n\n\n```python\nimport shutil\nfor i in range(len(level1_images_train)):\n  shutil.copy(level1_images_train[i], \"/content/drive/MyDrive/ML course 2022_Team BNL/level1_png/%s\" %level1_images_train[i].split(\"/\")[-1])\n```\n\n\n```python\n# the snippet that I use to create the jpegs of the high pass filtered images\npixel_std_values = np.zeros((len(train_images_directory_select)))\nfor i in range(train_images_directory_select.shape[0]):\n    im = cv2.imread(train_images_directory_select[i])                                                       # high pass filter then grayscale then standard deviation of all pixel values\n    high_pass_image = cv2.cvtColor(im - ndimage.gaussian_filter(im, 13), cv2.COLOR_BGR2GRAY)\n    # pixel_std_values[i] = np.std(high_pass_image)\n    cv2.imwrite('/content/drive/MyDrive/ML course 2022_Team BNL/level1_jpeg/%s.jpeg' %train_images_directory_select[i].split('/')[-1][:-5], high_pass_image)\n# plt.scatter(labels, pixel_std_values)\n# plt.xlabel('true_focal_distance')\n# plt.ylabel('std value')\n```\n\n## Dataset gathering and preparation\n\n\n```python\n%cd /content/drive/MyDrive/ML\\ course\\ 2022_Team\\ BNL\n```\n\n    /content/drive/MyDrive/ML course 2022_Team BNL\n\n\n\n```python\ntraining_batch_size = 1\ntest_batch_size = 1\n\nimageSizeheight=1200\nimageSizewidth=1920\n\n# imageSizeheight=300\n# imageSizewidth=480\n```\n\n\n```python\n# Image preprocessing utils\n@tf.function\ndef parse_images(image_path):\n\n    image_string = tf.io.read_file(image_path)\n    image = tf.io.decode_jpeg(image_string, channels=3)\n    # image = tfio.experimental.image.decode_tiff(image_string, index=0, name=None)[:,:,:-1]   # in the doc, it transforms tiff to 4 channels, with additional channel of opacity which is not needed.\n    image = tf.image.convert_image_dtype(image, tf.float32)\n    image = tf.image.resize(image, size=[imageSizeheight, imageSizewidth])\n\n    return image\n```\n\n\n```python\nlevel1_images_train = list(paths.list_files(\"/content/drive/MyDrive/ML course 2022_Team BNL/level1_jpeg\", validExts=\"jpeg\"))\n# train_images_directory_select = np.random.choice(level1_images_train, 6000, replace=False)\ntrain_images_directory_select = np.array(level1_images_train)\nprint(len(level1_images_train))\nprint(len(train_images_directory_select))\n```\n\n    5882\n    5882\n\n\n\n```python\nlabels = []                                                    # initialize labels\npositions = []                                                 # initialize the positions of the images, needed for record keeping\n\nedge_pixel_intensity_threshold = 0.50\nedge_percentage_threshold = 0.10\ncap = 20\n\nfor i in range(train_images_directory_select.shape[0]):\n  label = np.abs(float(train_images_directory_select[i].split(\"_\")[-1][:-5].split(\"(\")[0]))               # individual label, can be put into absolute or not                                                 \n  labels.append(label)\n  position = train_images_directory_select[i].split(\"_\")[-3] + '_' + train_images_directory_select[i].split(\"_\")[-2]      # individual position\n  positions.append(position)\nlabels = np.array(labels)\npositions = np.array(positions)\n\ninfocus_images_coordinate = np.where(labels==0)[0]                                       # locations where the infocus images are\nedge_percentages = []\nvalid = []\nfor i in range(train_images_directory_select[infocus_images_coordinate].shape[0]):\n  edge_percentage = len(np.where(parse_images(train_images_directory_select[infocus_images_coordinate][i])[:,:,0]>=edge_pixel_intensity_threshold)[0]) / imageSizeheight / imageSizewidth\n  edge_percentages.append(edge_percentage)\n  if edge_percentage >= edge_percentage_threshold:                                                             # picking out infocus images where the area containing edges is greater than a threshold value\n    valid.append(positions[infocus_images_coordinate][i])\n\nfor i in range(len(valid)):\n  valid_position = np.where(positions==valid[i])[0]\n  if i == 0:\n    valid_positions = valid_position\n  else:\n    valid_positions = np.append(valid_positions, valid_position)\n\nvalid_directories = train_images_directory_select[valid_positions]\nvalid_labels = labels[valid_positions]\n\n\ncapped_valid_labels = valid_labels[np.where(np.abs(valid_labels)<=cap)[0]]                                # not include the focal distance larger than cap\ncapped_valid_directories = valid_directories[np.where(np.abs(valid_labels)<=cap)[0]]\n\nprint(len(capped_valid_labels))\n```\n\n    510\n\n\n## Initiate our cnn model\n\n\n```python\nResnet50_transfer = tf.keras.applications.resnet50.ResNet50(\n    include_top=False,\n    weights=\"imagenet\",\n    # weights=None,\n    input_tensor=None,\n    input_shape=(imageSizeheight, imageSizewidth, 3), \n    pooling=None,\n)\n\nResnet50_transfer.trainable = True\n```\n\n    Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/resnet/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5\n    94773248/94765736 [==============================] - 2s 0us/step\n    94781440/94765736 [==============================] - 2s 0us/step\n\n\n\n```python\nResnet50_transfer.trainable = False\n\nsupervise_model = tf.keras.models.Sequential([\n    \n    Resnet50_transfer,\n    GlobalAveragePooling2D(),\n    # BatchNormalization(epsilon=0.1),\n    # Dense(64, activation='relu'),\n    # Dropout(0.5),\n    # BatchNormalization(epsilon=0.1),\n    # Dense(32, activation='relu'),\n    # Dropout(0.5),\n    # BatchNormalization(epsilon=0.1),\n    Dense(16, activation='relu'),\n    Dropout(0.5),\n    Dense(1)\n])\n```\n\n\n```python\n# adam = tf.keras.optimizers.Adam(learning_rate=0.001)\n# sgd = tf.keras.optimizers.SGD(learning_rate=0.001)\n# metrics = ['mae'\n#                 ]\n# supervise_model.compile(loss = 'mse', optimizer = adam, metrics = metrics)\n# supervise_model.summary()\n```\n\n    Model: \"sequential\"\n    _________________________________________________________________\n     Layer (type)                Output Shape              Param #   \n    =================================================================\n     resnet50 (Functional)       (None, 38, 60, 2048)      23587712  \n                                                                     \n     global_average_pooling2d (G  (None, 2048)             0         \n     lobalAveragePooling2D)                                          \n                                                                     \n     dense (Dense)               (None, 16)                32784     \n                                                                     \n     dropout (Dropout)           (None, 16)                0         \n                                                                     \n     dense_1 (Dense)             (None, 1)                 17        \n                                                                     \n    =================================================================\n    Total params: 23,620,513\n    Trainable params: 32,801\n    Non-trainable params: 23,587,712\n    _________________________________________________________________\n\n\n\n```python\n# cnn feature extraction in segments so as to avoid OOM problem, that we encountered with image set size larger than 1000.\nfeature_extractor = Model(supervise_model.input, supervise_model.layers[-4].output)\nn_segments = len(capped_valid_directories) // 500 + 1\nfor i in range(n_segments):\n  if i == 0:\n    train_ds = tf.data.Dataset.from_tensor_slices(capped_valid_directories[:(i + 1) * 500])\n    train_ds = (\n        train_ds\n        .map(parse_images, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n        .batch(training_batch_size\n              #  , drop_remainder=True\n              )\n        .prefetch(tf.data.experimental.AUTOTUNE)\n    )\n\n    features = feature_extractor.predict(train_ds)\n\n  else:\n    train_ds = tf.data.Dataset.from_tensor_slices(capped_valid_directories[i * 500 :(i + 1) * 500])\n    train_ds = (\n        train_ds\n        .map(parse_images, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n        .batch(training_batch_size\n              #  , drop_remainder=True\n              )\n        .prefetch(tf.data.experimental.AUTOTUNE)\n    )\n\n    features = np.append(features, feature_extractor.predict(train_ds), axis=0)\n```\n\n## KFolds validation\n\n\n```python\ntraining_data_size = np.array([10, 20, 50, 80, 100, 150, 200])\nn_folds = 5\nn_split_split = 20\nn_validation_images = 50\nrkf = RepeatedKFold(n_splits=n_folds, n_repeats=n_split_split, random_state=42)\n\nxgb_scores = np.zeros((len(training_data_size), n_folds * n_split_split, 2))\nridge_scores = np.zeros((len(training_data_size), n_folds * n_split_split, 2))\nrf_scores = np.zeros((len(training_data_size), n_folds * n_split_split, 2))\nsv_scores = np.zeros((len(training_data_size), n_folds * n_split_split, 2))\ngp_scores = np.zeros((len(training_data_size), n_folds * n_split_split, 2))\nmlp_scores = np.zeros((len(training_data_size), n_folds * n_split_split, 2))\n\nk = 0\nfor train_ix, test_ix in rkf.split(features, capped_valid_labels):\n  \n      Train_feature, val_feature = features[train_ix], features[test_ix]\n      Train_label, val_label = capped_valid_labels[train_ix], capped_valid_labels[test_ix]\n      val_feature = val_feature[:n_validation_images]\n      val_label = val_label[:n_validation_images]\n      \n      for i in range(len(training_data_size)):\n\n        # initate regressors\n        xg_boost_regressor = xgb(max_depth=16, learning_rate=0.1, tree_method='gpu_hist', objective='reg:squarederror')         # don't go beyond max_depth of 16, session will crash due to OOM\n        ridge_regressor = RidgeCV()\n        rf_regressor = randomforest(max_depth=16)\n        sv_regressor = svr()\n        gp_regressor = gpr()\n        mlp_regressor = mlp(hidden_layer_sizes=(100, 100, 100), max_iter=1000)\n\n        train_feature = Train_feature[:training_data_size[i]]\n        train_label = Train_label[:training_data_size[i]]\n\n        ## add or comment out regressors here\n\n\n        xg_boost_regressor.fit(train_feature, train_label)\n        y_pred_xgb = xg_boost_regressor.predict(val_feature)\n        xgb_scores[i, k, 0] = r2_score(y_pred_xgb, val_label)\n        xgb_scores[i, k, 1] = mean_absolute_error(y_pred_xgb, val_label)\n\n        ridge_regressor.fit(train_feature, train_label)\n        y_pred_ridge = ridge_regressor.predict(val_feature)\n        ridge_scores[i, k, 0] = r2_score(y_pred_ridge, val_label)\n        ridge_scores[i, k, 1] = mean_absolute_error(y_pred_ridge, val_label)\n\n        rf_regressor.fit(train_feature, train_label)\n        y_pred_rf = rf_regressor.predict(val_feature)\n        rf_scores[i, k, 0] = r2_score(y_pred_rf, val_label)\n        rf_scores[i, k, 1] = mean_absolute_error(y_pred_rf, val_label)\n\n        sv_regressor.fit(train_feature, train_label)\n        y_pred_sv = sv_regressor.predict(val_feature)\n        sv_scores[i, k, 0] = r2_score(y_pred_sv, val_label)\n        sv_scores[i, k, 1] = mean_absolute_error(y_pred_sv, val_label)\n\n        gp_regressor.fit(train_feature, train_label)\n        y_pred_gp = gp_regressor.predict(val_feature)\n        gp_scores[i, k, 0] = r2_score(y_pred_gp, val_label)\n        gp_scores[i, k, 1] = mean_absolute_error(y_pred_gp, val_label)\n\n        mlp_regressor.fit(train_feature, train_label)\n        y_pred_mlp = mlp_regressor.predict(val_feature)\n        mlp_scores[i, k, 0] = r2_score(y_pred_mlp, val_label)\n        mlp_scores[i, k, 1] = mean_absolute_error(y_pred_mlp, val_label)\n        \n      k += 1\n\nnp.savez_compressed('performance_log/level1/cap%i_cutoff%1.2f_valid%i.npz' %(cap, edge_percentage_threshold, len(capped_valid_labels)), xgb=xgb_scores, ridge=ridge_scores, rf=rf_scores, sv=sv_scores, gp=gp_scores, mlp=mlp_scores)\n```\n\n\n```python\nfor i in range(len(training_data_size)):\n  print('training_data_size: %i' % training_data_size[i])\n  print(np.average(xgb_scores[i, :, 0]))\n  print(np.std(xgb_scores[i, :, 0]))\n  print(np.average(xgb_scores[i, :, 1]))\n  print(np.std(xgb_scores[i, :, 1]))\n  print(np.average(ridge_scores[i, :, 0]))\n  print(np.std(ridge_scores[i, :, 0]))\n  print(np.average(ridge_scores[i, :, 1]))\n  print(np.std(ridge_scores[i, :, 1]))\n  print(np.average(rf_scores[i, :, 0]))\n  print(np.std(rf_scores[i, :, 0]))\n  print(np.average(rf_scores[i, :, 1]))\n  print(np.std(rf_scores[i, :, 1]))\n  print(np.average(sv_scores[i, :, 0]))\n  print(np.std(sv_scores[i, :, 0]))\n  print(np.average(sv_scores[i, :, 1]))\n  print(np.std(sv_scores[i, :, 1]))\n  print(np.average(gp_scores[i, :, 0]))\n  print(np.std(gp_scores[i, :, 0]))\n  print(np.average(gp_scores[i, :, 1]))\n  print(np.std(gp_scores[i, :, 1]))\n  print(np.average(mlp_scores[i, :, 0]))\n  print(np.std(mlp_scores[i, :, 0]))\n  print(np.average(mlp_scores[i, :, 1]))\n  print(np.std(mlp_scores[i, :, 1]))\n```\n\n    training_data_size: 10\n    0.14084248695740414\n    2.7596362558658334\n    3.072736385648594\n    0.8956592728706928\n    -0.7766834675071752\n    7.595225687628904\n    2.919382927749211\n    0.8930499778813756\n    -4.75159455046763\n    21.32244198472842\n    3.707794289579082\n    0.8381547926925947\n    -1376046.7630098618\n    2118775.2312446465\n    6.652055530528884\n    0.7328939987957965\n    -20.139719237492674\n    114.14783619964996\n    4.195719456627305\n    1.0904307439505168\n    0.31790680908968794\n    2.390246555151645\n    2.4593776514136305\n    1.134806561531438\n    training_data_size: 20\n    0.6127460916004517\n    0.14273374618180942\n    2.5826030791908217\n    0.4023774093347564\n    0.5979328567114998\n    0.12393640668622741\n    2.727254395662266\n    0.3551364679070613\n    0.4695063402054142\n    0.20017859336515761\n    2.688883169837599\n    0.38192943109347943\n    -119141.3728962809\n    93425.85060880502\n    6.27230394648212\n    0.6147711495190518\n    0.4227523017135294\n    0.2049816135261394\n    3.532484646850965\n    0.4839886312193726\n    0.7459562784933172\n    0.12870139680243298\n    2.076345256859041\n    0.4731978555179052\n    training_data_size: 50\n    0.8203983095044499\n    0.0813710079479404\n    1.8189238103763918\n    0.31835587664078063\n    0.8810790948688981\n    0.04093764368141865\n    1.7370660068909358\n    0.24903124740454324\n    0.8351375909390757\n    0.05075356508560078\n    1.7992479860717152\n    0.21104235861444043\n    -8376.665931761401\n    2614.529403387579\n    6.002770899687513\n    0.5161205594769536\n    0.6201355889437847\n    0.11851263374356036\n    3.004971927340325\n    0.36547285417363223\n    0.8478852613162248\n    0.056011520626132266\n    1.782785358318094\n    0.2631306362533543\n    training_data_size: 80\n    0.9083950034115618\n    0.03745150726943866\n    1.3435363704845256\n    0.19916348411480972\n    0.9252873768560436\n    0.02102686881782523\n    1.4022435428550668\n    0.1414553425484046\n    0.9100721924319877\n    0.036313377568307346\n    1.347547300866414\n    0.17261037114927213\n    -2651.4731180791555\n    475.47371995027567\n    5.924137085521008\n    0.4525022040498505\n    0.6867956625673383\n    0.11416176743783346\n    2.569695774759313\n    0.40497497869661125\n    0.8778979080638526\n    0.048103982832002734\n    1.6297619458434178\n    0.2509850740151335\n    training_data_size: 100\n    0.9212289448201575\n    0.03647168611797789\n    1.2326429367756924\n    0.19567887801379003\n    0.9293755852615996\n    0.022302630504414243\n    1.329463549542797\n    0.14349953051944603\n    0.9235942071371065\n    0.033336546478229555\n    1.239676189402976\n    0.1608974991051767\n    -1482.2604119163138\n    224.71347800861955\n    5.891199374110353\n    0.43176999215527656\n    0.7125141860700718\n    0.10790024622258106\n    2.4759274293968003\n    0.4044658331879874\n    0.8879578247699073\n    0.04616443076624449\n    1.5710054313252053\n    0.2554933738653663\n    training_data_size: 150\n    0.9425109155778957\n    0.02772839342797353\n    1.0476652797382067\n    0.15881349172825485\n    0.9510358314580771\n    0.017721447215294617\n    1.1157259919904492\n    0.1260250039176212\n    0.9379231184338046\n    0.02798137789388804\n    1.0923404920115902\n    0.15914939271462836\n    -711.8816547442243\n    110.28370311326765\n    5.836516910421523\n    0.447310550243297\n    0.754891961996632\n    0.08783222036969277\n    2.211500399392409\n    0.3674392918856898\n    0.8881859498892823\n    0.05260471220163631\n    1.5768598692961506\n    0.2994298914647158\n    training_data_size: 200\n    0.9500538039644125\n    0.025227156944934555\n    0.9685059190571245\n    0.14970389300903494\n    0.9532059958787177\n    0.015245713932625282\n    1.0865333214303208\n    0.11278059865765575\n    0.9441234177950087\n    0.025805593948424663\n    1.0188601376367352\n    0.14328988408151982\n    -395.004017721243\n    53.94205151407905\n    5.773433767720981\n    0.4318984522267623\n    0.786397781292844\n    0.08230859431349802\n    1.960874737406081\n    0.3394807218700498\n    0.8891547044793708\n    0.041680979172726715\n    1.5479714113376601\n    0.23487422010232534\n\n\n\n```python\n# rf_regressor = randomforest(max_depth=16)\nfeatures_train, features_test, train_label, test_label = train_test_split(features, capped_valid_labels, test_size=0.2, random_state=42)\n# rf_regressor.fit(features_train, train_label)\ny_pred_rf = rf_regressor.predict(features_test)\n```\n\n\n```python\nprint('rf prediction r2_score = %f' % r2_score(y_pred_rf, test_label))\nprint('rf prediction mean_absolute_error = %f' % mean_absolute_error(y_pred_rf, test_label))\nplt.scatter(test_label, y_pred_rf)\nplt.plot(np.linspace(0, cap, 150), np.linspace(0, cap, 150), c='r')\nplt.xlabel('true_distance [$\\mu m$]')\nplt.ylabel('predicted_distance [$\\mu m$]')\n```\n\n\n```python\nridge_regressor.fit(extracted_features_train, train_label)\ny_pred_ridge = ridge_regressor.predict(extracted_features_test)\n```\n\n\n```python\nprint('RidgeCV prediction r2_score = %f' % r2_score(y_pred_ridge, test_label))\nprint('RidgeCV prediction mean_absolute_error = %f' % mean_absolute_error(y_pred_ridge, test_label))\nplt.scatter(test_label, y_pred_ridge)\nplt.plot(np.linspace(0, cap, 150), np.linspace(0, cap, 150), c='r')\nplt.xlabel('true_distance')\nplt.ylabel('predicted_distance')\n```\n\n\n```python\ntf.random.set_seed(42)\nsupervise_history = supervise_model.fit(train_ds,\n                 validation_data=test_ds,                      \n                 batch_size=training_batch_size,                       \n                 epochs=10,                                           \n                 workers=8,                                            \n                 use_multiprocessing=True,                             \n                 verbose=1)                                         \n                #  callbacks=[MetricsCheckpoint('small_supervise')])  \n```\n", "meta": {"hexsha": "cbbd48fd93a638abd1cc095fc4064e1502672e99", "size": 88276, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/archive/training_level1.ipynb", "max_stars_repo_name": "evanmacbride/microscope-autofocus", "max_stars_repo_head_hexsha": "5e88dc8b498cc96c3eee0503111fdf67ef867b54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/archive/training_level1.ipynb", "max_issues_repo_name": "evanmacbride/microscope-autofocus", "max_issues_repo_head_hexsha": "5e88dc8b498cc96c3eee0503111fdf67ef867b54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/archive/training_level1.ipynb", "max_forks_repo_name": "evanmacbride/microscope-autofocus", "max_forks_repo_head_hexsha": "5e88dc8b498cc96c3eee0503111fdf67ef867b54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 88276.0, "max_line_length": 88276, "alphanum_fraction": 0.757918347, "converted": true, "num_tokens": 7709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754065479083276, "lm_q2_score": 0.059210250326255834, "lm_q1q2_score": 0.022354276678503746}}
{"text": "<a href=\"https://colab.research.google.com/github/ChrizZhuang/marginalized_graph_kernel_protein/blob/main/Docking.ipynb\" target=\"_parent\"></a>\n\n## Set up the environment\n\n\n```\n!nvidia-smi\n```\n\n    Fri Jun 18 13:25:10 2021       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 465.27       Driver Version: 460.32.03    CUDA Version: 11.2     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   63C    P0    30W /  70W |    102MiB / 15109MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    +-----------------------------------------------------------------------------+\n\n\n\n```\n#!pip install pymatgen==2020.12.31\n!pip install pymatgen==2019.11.11\n!pip install --pre graphdot\n!pip install gdown\n```\n\n    Requirement already satisfied: pymatgen==2019.11.11 in /usr/local/lib/python3.7/dist-packages (2019.11.11)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.23.0)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.7.1)\n    Requirement already satisfied: scipy>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.4.1)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.1.5)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (0.8.9)\n    Requirement already satisfied: numpy>=1.14.3 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.19.5)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.5.1)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (3.2.2)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (3.3.0)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2021.6.10)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.16.1)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (0.17.9)\n    Requirement already satisfied: pydispatcher>=2.0.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.0.5)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (2021.5.30)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (3.0.4)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->pymatgen==2019.11.11) (1.2.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen==2019.11.11) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen==2019.11.11) (2.8.1)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.2->pymatgen==2019.11.11) (4.4.2)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (2.4.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (1.3.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (0.10.0)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen==2019.11.11) (0.2.2)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas->pymatgen==2019.11.11) (1.15.0)\n    Requirement already satisfied: graphdot in /usr/local/lib/python3.7/dist-packages (0.8a17)\n    Requirement already satisfied: treelib>=1.6.1 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.6.1)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.7.1)\n    Requirement already satisfied: networkx>=2.4 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2.5.1)\n    Requirement already satisfied: pycuda>=2019 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2021.1)\n    Requirement already satisfied: pymatgen==2019.11.11 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2019.11.11)\n    Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.19.5)\n    Requirement already satisfied: kahypar>=1.1.4 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.1.6)\n    Requirement already satisfied: mendeleev>=0.7 in /usr/local/lib/python3.7/dist-packages (from graphdot) (0.7.0)\n    Requirement already satisfied: numba>=0.51.0 in /usr/local/lib/python3.7/dist-packages (from graphdot) (0.51.2)\n    Requirement already satisfied: ase>=3.17 in /usr/local/lib/python3.7/dist-packages (from graphdot) (3.21.1)\n    Requirement already satisfied: tqdm>=4.55 in /usr/local/lib/python3.7/dist-packages (from graphdot) (4.61.1)\n    Requirement already satisfied: pandas>=0.24 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.1.5)\n    Requirement already satisfied: scipy>=1.3.0 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.4.1)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from treelib>=1.6.1->graphdot) (0.16.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->graphdot) (1.2.1)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.4->graphdot) (4.4.2)\n    Requirement already satisfied: mako in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (1.1.4)\n    Requirement already satisfied: pytools>=2011.2 in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (2021.2.7)\n    Requirement already satisfied: appdirs>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (1.4.4)\n    Requirement already satisfied: pydispatcher>=2.0.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2.0.5)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (3.2.2)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (0.8.9)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (1.16.1)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2.23.0)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (3.3.0)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (0.17.9)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2021.6.10)\n    Requirement already satisfied: SQLAlchemy<2.0.0,>=1.3.23 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (1.4.18)\n    Requirement already satisfied: Pygments<3.0.0,>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (2.9.0)\n    Requirement already satisfied: colorama<0.5.0,>=0.4.4 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (0.4.4)\n    Requirement already satisfied: six<2.0.0,>=1.15.0 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (1.15.0)\n    Requirement already satisfied: pyfiglet<0.9,>=0.8.post1 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (0.8.post1)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from numba>=0.51.0->graphdot) (57.0.0)\n    Requirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba>=0.51.0->graphdot) (0.34.0)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->graphdot) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->graphdot) (2.8.1)\n    Requirement already satisfied: MarkupSafe>=0.9.2 in /usr/local/lib/python3.7/dist-packages (from mako->pycuda>=2019->graphdot) (2.0.1)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11->graphdot) (1.3.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11->graphdot) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11->graphdot) (0.10.0)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (2021.5.30)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (2.10)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (1.24.3)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen==2019.11.11->graphdot) (0.2.2)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (4.5.0)\n    Requirement already satisfied: greenlet!=0.4.17; python_version >= \"3\" in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (1.1.0)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (3.4.1)\n    Requirement already satisfied: typing-extensions>=3.6.4; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (3.7.4.3)\n    Requirement already satisfied: gdown in /usr/local/lib/python3.7/dist-packages (3.6.4)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from gdown) (2.23.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from gdown) (1.15.0)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from gdown) (4.61.1)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (2021.5.30)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (3.0.4)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (1.24.3)\n\n\n\n```\n%matplotlib inline\nimport io\nimport sys\nsys.path.append('/usr/local/lib/python3.6/site-packages/')\nimport os\nimport urllib\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport graphdot\nfrom graphdot import Graph\nfrom graphdot.graph.adjacency import AtomicAdjacency\nfrom graphdot.graph.reorder import rcm\nfrom graphdot.kernel.marginalized import MarginalizedGraphKernel # https://graphdot.readthedocs.io/en/latest/apidoc/graphdot.kernel.marginalized.html\nfrom graphdot.kernel.marginalized.starting_probability import Uniform\nfrom graphdot.model.gaussian_process import (\n    GaussianProcessRegressor,\n    LowRankApproximateGPR\n)\nfrom graphdot.kernel.fix import Normalization\nimport graphdot.microkernel as uX\nimport ase.io\n\n# for getting all file names into a list under a directory \nfrom os import listdir\n# for getting file names that match certain pattern\nimport glob\nimport time\n```\n\n\n```\nfrom google.colab import drive\ndrive.mount('/content/gdrive', force_remount=True)\n```\n\n    Mounted at /content/gdrive\n\n\n\n```\n#cd gdrive/MyDrive/Google\\ Colab/Covid-Data\n%cd gdrive/MyDrive/Covid-Data/\n```\n\n    /content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data\n\n\n\n```\n!pwd\n```\n\n    /content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data\n\n\n## load the data\n\n\n```\nfiles  = ['uncharged_NSP15_6W01_A_3_H.Orderable_zinc_db_enaHLL.2col.csv.1.xz']\ndataset = pd.read_pickle(files[0]) # length of each csv file is 100000\n```\n\n\n```\ntarget = 'energy'\nN_train = 1000\nN_test = 2000\n\nnp.random.seed(0) # with the same seed, multiple runs can have the same selected index\ntrain_sel = np.random.choice(len(dataset), N_train, replace=False)\ntest_sel = np.random.choice(np.setxor1d(np.arange(len(dataset)), train_sel), N_test, replace=False)\ntrain = dataset.iloc[train_sel]\ntest = dataset.iloc[test_sel]\n```\n\n\n```\ntrain.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>energy</th>\n      <th>smiles</th>\n      <th>graphs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>3582</th>\n      <td>-2.874773</td>\n      <td>CN(Cc1nc(no1)c2cccc(c2)Br)C(=O)Nc3cccc(c3)OC</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>60498</th>\n      <td>-3.469760</td>\n      <td>CCOC(=O)c1ccc(c(c1)C)NC(=S)NCCOc2ccc(cc2)C</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>53227</th>\n      <td>-0.487984</td>\n      <td>Cc1ccc(cc1S(=O)(=O)Nc2ccccc2OC)NC(=O)c3nc4nc(c...</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>21333</th>\n      <td>-1.808283</td>\n      <td>COc1ccc(cc1OC)CCNC(=O)COc2ccc(cc2)[N@@](Cc3ccc...</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>3885</th>\n      <td>-2.457642</td>\n      <td>Cc1cc(ccc1NCc2ccc(c(c2OC)C)OC)Br</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### Baseline mode\n\n\n```\ngpr_base = GaussianProcessRegressor(\n    # kernel is the covariance function of the gaussian process (GP)\n    kernel=Normalization( # kernel equals to normalization -> normalizes a kernel using the cosine of angle formula, k_normalized(x,y) = k(x,y)/sqrt(k(x,x)*k(y,y))\n        # graphdot.kernel.fix.Normalization(kernel), set kernel as marginalized graph kernel, which is used to calculate the similarity between 2 graphs\n        # implement the random walk-based graph similarity kernel as Kashima, H., Tsuda, K., & Inokuchi, A. (2003). Marginalized kernels between labeled graphs. ICML\n        MarginalizedGraphKernel( \n            # node_kernel - A kernelet that computes the similarity between individual nodes\n            # uX - graphdot.microkernel - microkernels are positive-semidefinite functions between individual nodes and edges of graphs\n            node_kernel=uX.Additive( # addition of kernal matrices: sum of k_a(X_a, Y_a) cross for a in features\n                # uX.Constant - a kernel that returns a constant value, always mutlipled with other microkernels as an adjustable weight\n                #   c, the first input arg. as 0.5, (0.01, 10) the lower and upper bounds of c that is allowed to vary during hyperpara. optimizartion\n                # uX.KroneckerDelta - a kronecker delta returns 1 when two features are equal and return h (the first input arg here, which is 0.5 in this case) otherwise\n                #   (0.1, 0.9) the lower and upper bounds that h is allowed to vary during hyperpara. optimization\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 2nd element of graphdot.graph.Graph.nodes\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 3rd element of graphdot.graph.Graph.nodes\n                # uX.SquareExponential - Equ. 26 in the paper\n                # input arg. length_sacle is a float32, set as 1 in this case, which correspond to approx. 1 of the kernal value. \n                # This is used to determins how quicklys should the kernel decay to zero.\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0), # the 4th element of graphdot.graph.Graph.nodes\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 5th element of graphdot.graph.Graph.nodes\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0), # the 6th element of graphdot.graph.Graph.nodes\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 7th element of graphdot.graph.Graph.nodes\n                # uX.Convolution - a convolutional microkernel which averages evaluations of a base microkernel between pairs pf elememts of two variable-length feature sequences\n                # uX.KroneckerDelta as the base kernel\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9))) # the 8th element of graphdot.graph.Graph.nodes\n            ).normalized,\n            # edge_kernel - A kernelet that computes the similarity between individual edge\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 3rd element of graphdot.graph.Graph.nodes\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 4th element of graphdot.graph.Graph.nodes\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 5th element of graphdot.graph.Graph.nodes\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 6th element of graphdot.graph.Graph.nodes\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)) # the 7th element of graphdot.graph.Graph.nodes\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'), # the strating probability of the random walk on each node\n            q=0.05 # the probability for the random walk to stop during each step\n        )\n    ),\n    alpha=1e-4, # value added to the diagonal of the kernel matrix during fitting\n    optimizer=True, # default optimizer of L-BFGS-B based on scipy.optimize.minimize\n    normalize_y=True, # normalize the y values so taht the means and variance is 0 and 1, repsectively. Will be reversed when predicions are returned\n    regularization='+', # alpha (1e-4 in this case) is added to the diagonals of the kernal matrix\n)\n```\n\n\n```\ngpr_base.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  2.8732e+06|  2.4472e+07|  2.8805e+06|     -7290.9|  8.7025e+06|        25|      0.24|\n    |  1.9317e+06|  2.0708e+07|  1.9384e+06|     -6742.8|  8.0201e+06|        19|      0.23|\n    |  1.2915e+06|  1.5724e+07|  1.2978e+06|     -6252.6|  7.0847e+06|        19|      0.25|\n    |  1.0059e+06|  1.2307e+07|  1.0119e+06|     -5971.9|  6.4112e+06|        18|      0.24|\n    |  8.2586e+05|  9.7306e+06|  8.3162e+05|     -5755.8|  5.8195e+06|        18|      0.24|\n    |  7.1188e+05|  8.0802e+06|  7.1747e+05|       -5589|    5.37e+06|        17|      0.24|\n    |  6.4919e+05|  7.1077e+06|  6.5468e+05|     -5488.7|  5.0436e+06|        17|      0.24|\n    |  6.3022e+05|  7.0494e+06|  6.3566e+05|     -5435.8|  4.9605e+06|        17|      0.25|\n    |  6.0998e+05|  6.6425e+06|   6.154e+05|     -5413.2|  4.8443e+06|        17|      0.23|\n    |  6.0543e+05|  6.5402e+06|  6.1084e+05|     -5407.7|  4.8013e+06|        17|      0.24|\n    |   6.029e+05|  6.5002e+06|   6.083e+05|       -5403|  4.7834e+06|        17|      0.25|\n    |  6.0597e+05|  6.6643e+06|  6.1136e+05|       -5396|  4.8337e+06|        17|      0.24|\n    |  6.0095e+05|  6.5243e+06|  6.0634e+05|     -5395.1|  4.7907e+06|        17|      0.23|\n    |  5.9992e+05|  6.4995e+06|  6.0531e+05|     -5393.3|  4.7863e+06|        17|      0.24|\n    |  5.9795e+05|  6.4528e+06|  6.0334e+05|     -5390.7|   4.776e+06|        17|      0.25|\n    |  5.9645e+05|   6.417e+06|  6.0184e+05|     -5389.1|  4.7596e+06|        17|      0.23|\n    |  5.9551e+05|  6.4043e+06|   6.009e+05|     -5387.4|  4.7506e+06|        17|      0.23|\n    |   5.952e+05|  6.4261e+06|  6.0059e+05|     -5386.3|  4.7509e+06|        17|      0.24|\n    |  5.9521e+05|  6.4221e+06|   6.006e+05|     -5386.7|  4.7457e+06|        17|      0.24|\n    |  5.9529e+05|   6.428e+06|  6.0067e+05|     -5386.4|  4.7501e+06|        17|      0.24|\n    |  5.9532e+05|  6.4293e+06|  6.0071e+05|     -5386.3|  4.7524e+06|        17|      0.24|\n    |   5.954e+05|  6.4315e+06|  6.0079e+05|     -5386.3|  4.7512e+06|        17|      0.23|\n    |  5.9534e+05|  6.4295e+06|  6.0072e+05|     -5386.3|  4.7505e+06|        17|      0.23|\n    |  5.9535e+05|  6.4296e+06|  6.0073e+05|     -5386.3|  4.7493e+06|        17|      0.24|\n    |  5.9525e+05|  6.4271e+06|  6.0063e+05|     -5386.3|  4.7483e+06|        17|      0.24|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  1.7409e+06|  2.1762e+07|  1.7476e+06|       -6644|  7.5137e+06|        20|      0.25|\n    |  1.3449e+06|  1.6767e+07|  1.3512e+06|     -6332.3|  6.9223e+06|        19|      0.23|\n    |  1.0329e+06|  1.3304e+07|  1.0389e+06|     -6026.5|  6.3154e+06|        19|      0.23|\n    |    7.99e+05|  1.0463e+07|  8.0471e+05|     -5717.1|  5.7322e+06|        19|      0.24|\n    |  6.9731e+05|  8.1809e+06|  7.0289e+05|     -5576.4|  5.3116e+06|        18|      0.23|\n    |   6.429e+05|  7.1948e+06|  6.4838e+05|     -5481.8|  5.0628e+06|        17|      0.23|\n    |  6.1534e+05|  6.7632e+06|  6.2077e+05|     -5430.2|  4.8917e+06|        17|      0.24|\n    |  6.1408e+05|   6.702e+06|  6.1951e+05|     -5424.3|  4.8089e+06|        17|      0.23|\n    |  6.0084e+05|  6.5214e+06|  6.0624e+05|     -5401.1|  4.7735e+06|        17|      0.24|\n    |  5.9722e+05|  6.4546e+06|  6.0261e+05|     -5392.3|  4.7711e+06|        17|      0.23|\n    |  5.9574e+05|   6.421e+06|  6.0113e+05|       -5389|   4.753e+06|        17|      0.23|\n    |  5.9474e+05|  6.4009e+06|  6.0012e+05|     -5386.2|  4.7503e+06|        17|      0.24|\n    |   5.948e+05|  6.4051e+06|  6.0018e+05|     -5386.1|  4.7502e+06|        17|      0.26|\n    |  5.9479e+05|  6.4027e+06|  6.0017e+05|     -5386.2|   4.751e+06|        17|      0.25|\n    |  5.9483e+05|  6.4032e+06|  6.0022e+05|     -5386.2|  4.7489e+06|        17|      0.23|\n    |  5.9479e+05|  6.4024e+06|  6.0018e+05|     -5386.2|  4.7497e+06|        17|      0.24|\n    |  5.9463e+05|  6.3985e+06|  6.0001e+05|     -5386.2|  4.7498e+06|        17|      0.23|\n    |  5.9476e+05|  6.4018e+06|  6.0014e+05|     -5386.2|  4.7515e+06|        17|      0.23|\n    |  5.9472e+05|  6.4005e+06|  6.0011e+05|     -5386.2|  4.7481e+06|        17|      0.23|\n    |  5.9438e+05|  6.4049e+06|  5.9976e+05|     -5385.2|  4.7582e+06|        17|      0.24|\n    |  5.9398e+05|  6.3991e+06|  5.9937e+05|     -5384.9|  4.7606e+06|        17|      0.26|\n    |  5.9434e+05|  6.3979e+06|  5.9973e+05|     -5387.1|  4.7974e+06|        17|      0.23|\n    |  5.9364e+05|  6.3943e+06|  5.9903e+05|     -5385.1|  4.7704e+06|        17|      0.24|\n    |  5.9352e+05|  6.3766e+06|   5.989e+05|     -5385.7|  4.7742e+06|        17|      0.24|\n    |  5.9331e+05|  6.3716e+06|  5.9869e+05|     -5385.7|  4.7678e+06|        17|      0.25|\n    |  5.9319e+05|  6.3736e+06|  5.9857e+05|     -5385.5|  4.7668e+06|        17|      0.24|\n    |  5.9321e+05|  6.3761e+06|   5.986e+05|     -5385.5|  4.7654e+06|        17|      0.24|\n    |   5.932e+05|  6.3739e+06|  5.9859e+05|     -5385.5|  4.7652e+06|        17|      0.25|\n    |  5.9324e+05|  6.3745e+06|  5.9862e+05|     -5385.5|  4.7648e+06|        17|      0.26|\n    |  5.9308e+05|   6.371e+06|  5.9846e+05|     -5385.5|  4.7648e+06|        17|      0.24|\n    |  5.9311e+05|  6.3718e+06|  5.9849e+05|     -5385.5|  4.7653e+06|        17|      0.23|\n    |  5.9307e+05|  6.3704e+06|  5.9845e+05|     -5385.5|  4.7663e+06|        17|      0.23|\n    |  5.9311e+05|  6.3717e+06|  5.9849e+05|     -5385.5|  4.7665e+06|        17|      0.24|\n    |  5.9314e+05|  6.3719e+06|  5.9852e+05|     -5385.5|  4.7652e+06|        17|      0.27|\n    |  5.9322e+05|   6.374e+06|  5.9861e+05|     -5385.6|   4.768e+06|        17|      0.24|\n    |  5.9323e+05|  6.3744e+06|  5.9862e+05|     -5385.5|  4.7661e+06|        17|      0.24|\n    |  5.9329e+05|  6.3755e+06|  5.9867e+05|     -5385.5|  4.7682e+06|        17|      0.24|\n    |  5.9317e+05|  6.3733e+06|  5.9856e+05|     -5385.5|  4.7673e+06|        17|      0.22|\n    |  5.9317e+05|  6.3729e+06|  5.9856e+05|     -5385.5|  4.7663e+06|        17|      0.23|\n    |  5.9306e+05|    6.37e+06|  5.9844e+05|     -5385.5|  4.7647e+06|        17|      0.23|\n    |   5.932e+05|  6.3734e+06|  5.9858e+05|     -5385.6|  4.7672e+06|        17|      0.24|\n    |  5.9327e+05|  6.3755e+06|  5.9865e+05|     -5385.5|  4.7661e+06|        17|      0.25|\n    |  5.9316e+05|  6.3727e+06|  5.9855e+05|     -5385.5|  4.7662e+06|        17|      0.23|\n    |  5.9314e+05|  6.3724e+06|  5.9852e+05|     -5385.5|  4.7652e+06|        17|      0.23|\n    |  5.9323e+05|  6.3745e+06|  5.9861e+05|     -5385.5|  4.7646e+06|        17|      0.24|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  3.4088e+06|  2.5346e+07|  3.4163e+06|     -7528.5|  8.7261e+06|        21|      0.23|\n    |  2.2462e+06|  2.1985e+07|  2.2531e+06|     -6926.8|  8.0882e+06|        19|      0.25|\n    |  1.4714e+06|  1.6955e+07|  1.4778e+06|     -6400.7|  7.2113e+06|        19|      0.24|\n    |  1.1069e+06|  1.3406e+07|   1.113e+06|     -6074.7|  6.5387e+06|        18|      0.25|\n    |  8.6431e+05|  1.0668e+07|   8.701e+05|     -5795.9|  5.9546e+06|        18|      0.26|\n    |  7.4254e+05|   8.826e+06|  7.4817e+05|     -5630.3|   5.539e+06|        18|      0.24|\n    |  6.7229e+05|  7.6661e+06|  6.7782e+05|     -5526.8|  5.2131e+06|        17|      0.27|\n    |  6.3377e+05|   7.154e+06|  6.3922e+05|     -5448.9|  4.9896e+06|        17|      0.25|\n    |   6.135e+05|  6.7529e+06|  6.1892e+05|     -5423.9|  4.8776e+06|        17|      0.24|\n    |  6.1058e+05|  6.7014e+06|    6.16e+05|     -5418.3|  4.8685e+06|        17|      0.27|\n    |  6.0465e+05|  6.6012e+06|  6.1005e+05|     -5406.2|  4.8239e+06|        17|      0.24|\n    |  5.9842e+05|   6.465e+06|  6.0382e+05|     -5396.3|  4.7802e+06|        17|      0.24|\n    |  5.9682e+05|  6.4338e+06|  6.0221e+05|     -5392.2|  4.7725e+06|        17|      0.24|\n    |  5.9544e+05|  6.4167e+06|  6.0083e+05|     -5389.1|  4.7551e+06|        17|      0.27|\n    |  5.9514e+05|  6.4084e+06|  6.0053e+05|     -5386.1|  4.7687e+06|        17|      0.24|\n    |  5.9488e+05|  6.4057e+06|  6.0027e+05|     -5386.6|  4.7664e+06|        17|      0.25|\n    |  5.9458e+05|  6.4025e+06|  5.9996e+05|       -5387|  4.7594e+06|        17|      0.25|\n    |  5.9408e+05|   6.395e+06|  5.9947e+05|       -5387|  4.7525e+06|        17|      0.24|\n    |  5.9368e+05|  6.3896e+06|  5.9907e+05|     -5386.8|  4.7493e+06|        17|      0.25|\n    |  5.9342e+05|  6.4028e+06|  5.9881e+05|     -5386.3|  4.7536e+06|        17|      0.25|\n    |  5.9322e+05|  6.3903e+06|  5.9861e+05|     -5386.2|  4.7546e+06|        17|      0.25|\n    |  5.9314e+05|  6.3787e+06|  5.9853e+05|     -5386.1|  4.7629e+06|        17|      0.24|\n    |  5.9313e+05|  6.3786e+06|  5.9852e+05|       -5386|  4.7624e+06|        17|      0.24|\n    |  5.9305e+05|  6.3767e+06|  5.9843e+05|       -5386|  4.7642e+06|        17|      0.24|\n    |  5.9302e+05|  6.3762e+06|   5.984e+05|       -5386|  4.7654e+06|        17|      0.26|\n    |  5.9307e+05|   6.379e+06|  5.9846e+05|       -5386|  4.7622e+06|        17|      0.25|\n    |  5.9298e+05|  6.3757e+06|  5.9837e+05|       -5386|  4.7645e+06|        17|      0.24|\n    |  5.9298e+05|  6.3755e+06|  5.9836e+05|       -5386|   4.765e+06|        17|      0.24|\n    |  5.9302e+05|  6.3775e+06|   5.984e+05|       -5386|  4.7632e+06|        17|      0.24|\n    |  5.9307e+05|   6.378e+06|  5.9846e+05|       -5386|   4.766e+06|        17|      0.26|\n    |  5.9303e+05|   6.377e+06|  5.9842e+05|       -5386|  4.7618e+06|        17|      0.24|\n    |  5.9307e+05|  6.3781e+06|  5.9846e+05|       -5386|  4.7625e+06|        17|      0.25|\n    Optimization result:\n          fun: 593069.932380245\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 6.37401476e+02,  1.29281591e+02,  1.71717340e+01,  8.17163496e+02,\n            1.37449776e+04,  2.83746226e+02,  0.00000000e+00, -9.68972328e+01,\n            7.58704266e+01, -1.01702776e+03,  1.73614628e-02,  9.92115226e+01,\n            4.40083116e+01, -2.10434038e+02,  1.76089738e+04, -5.35392825e+01,\n            1.59837715e+03, -5.23992147e+02,  3.02975068e+03,  3.77204387e+02,\n            2.66645493e+02,  4.72819542e+01,  0.00000000e+00,  1.53619204e+02,\n            2.43442028e+02])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 32\n          nit: 25\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -2.30258509,  1.47919293, -2.30258509,\n           -4.60517019,  1.38836933, -3.87992001, -2.30258509,  2.30258509,\n           -1.84802766, -4.04811436, -2.30258509,  1.7184825 , -2.30258509,\n            1.52051859, -2.30258509,  2.14366376, -2.30258509, -0.12101446,\n           -2.30258509, -4.1942687 , -0.19078879, -0.29039223, -2.30258509])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7f3c6739e090>\n\n\n\n\n```\ngpr_base.kernel.hyperparameters\n```\n\n\n\n\n    starting_probability : Uniform\n    \tp : 1.0\n    stopping_probability : 0.00010000000000000009\n    node_kernel : Composite\n    \taromatic : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.010000000000000004\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tatomic_number : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 4.389401717699675\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tcharge : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.010000000000000004\n    \t\trhs : SquareExponential\n    \t\t\tlength_scale : 4.008308481056897\n    \tchiral : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.020652477208848625\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \thcount : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 10.000000000000002\n    \t\trhs : SquareExponential\n    \t\t\tlength_scale : 0.1575475978780114\n    \thybridization : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.017455257909267944\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tring_list : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 5.576060342281107\n    \t\trhs : Convolution\n    \t\t\tbase : KroneckerDelta\n    \t\t\t\th : 0.10000000000000002\n    edge_kernel : Composite\n    \taromatic : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 4.574596924658218\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tconjugated : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 8.530634633858428\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \torder : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.886021150144127\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tring_stereo : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.015081767749340561\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.8263070943166276\n    \tstereo : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.7479701335024439\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n\n\n\n\n```\nmu = gpr_base.predict(train.graphs)\n```\n\n\n```\nplt.scatter(train[target], mu)\nplt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\nplt.xlim(-9, 3)\nplt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.1026528897885943\n    RMSE: 0.1559697478035153\n\n\n\n```\nmu_test = gpr_base.predict(test.graphs)\n```\n\n\n```\nplt.scatter(test[target], mu_test)\nplt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\nplt.xlim(-9, 3)\nplt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 1.3984523944497356\n    RMSE: 1.7902476214464011\n\n\n### Model 2\n\n\n```\ngpr2 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-5, #different from gpr in alpha where gpr_base alpha is 1e-4\n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr2.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n\n```\nmu = gpr2.predict(train.graphs)\nplt.scatter(train[target], mu)\nplt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\nplt.xlim(-9, 3)\nplt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.01420440124959926\n    RMSE: 0.021649804308151027\n\n\n\n```\nmu_test = gpr2.predict(test.graphs)\nplt.scatter(test[target], mu_test)\nplt.plot(np.linspace(-10, 4), np.linspace(-10, 4), c = 'r')\nplt.xlim(-10, 4)\nplt.ylim(-10, 4)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 1.517212238428167\n    RMSE: 1.943288841802438\n\n\n\n```\ngpr2.kernel.hyperparameters\n```\n\n### Model 3\n\n\n```\ngpr3 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-3, #different from gpr in alpha where gpr_base's alpha is 1e-4\n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr3.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  5.2755e+05|  1.7778e+06|  5.3363e+05|     -6084.7|  9.0543e+05|        23|      0.24|\n    |  4.4225e+05|  1.9516e+06|  4.4806e+05|     -5808.2|  8.7904e+05|        20|      0.24|\n    |  3.1408e+05|  1.8185e+06|  3.1938e+05|       -5299|  8.0603e+05|        19|      0.23|\n    |  2.8466e+05|   1.617e+06|  2.8982e+05|       -5163|  7.8274e+05|        18|      0.25|\n    |  2.6119e+05|  1.4682e+06|  2.6623e+05|     -5042.4|  7.5643e+05|        17|      0.23|\n    |  2.5268e+05|   1.388e+06|  2.5768e+05|     -4997.9|    7.47e+05|        17|      0.24|\n    |  2.4961e+05|  1.3914e+06|  2.5459e+05|       -4978|  7.4222e+05|        17|      0.24|\n    |  2.4852e+05|  1.3833e+06|  2.5349e+05|       -4972|  7.4105e+05|        17|      0.23|\n    |  2.4834e+05|  1.3947e+06|   2.533e+05|     -4968.2|  7.3383e+05|        17|      0.25|\n    |  2.4725e+05|  1.3772e+06|  2.5222e+05|     -4964.8|  7.3856e+05|        17|      0.24|\n    |  2.4714e+05|  1.3741e+06|  2.5211e+05|     -4964.5|  7.3971e+05|        17|      0.24|\n    |  2.4698e+05|  1.3711e+06|  2.5194e+05|     -4963.9|  7.4045e+05|        17|      0.24|\n    |  2.4672e+05|  1.3682e+06|  2.5168e+05|     -4962.6|  7.4076e+05|        17|      0.23|\n    |   2.464e+05|  1.3674e+06|  2.5136e+05|     -4960.7|  7.3978e+05|        17|      0.24|\n    |  2.4638e+05|  1.3727e+06|  2.5134e+05|     -4959.2|  7.3885e+05|        17|      0.26|\n    |  2.4633e+05|  1.3699e+06|  2.5129e+05|     -4959.6|  7.3928e+05|        17|      0.24|\n    |  2.4624e+05|  1.3697e+06|   2.512e+05|       -4959|  7.3809e+05|        17|      0.25|\n    |  2.4623e+05|  1.3693e+06|  2.5118e+05|     -4959.1|  7.3791e+05|        17|      0.25|\n    |  2.4622e+05|  1.3694e+06|  2.5118e+05|     -4959.1|  7.3771e+05|        17|      0.26|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  6.5812e+05|  6.1061e+05|  6.6462e+05|     -6496.8|  9.5215e+05|        16|      0.23|\n    |  5.8273e+05|  9.7375e+05|  5.8902e+05|     -6289.9|  9.3185e+05|        18|      0.23|\n    |  3.6034e+05|   1.697e+06|  3.6585e+05|     -5504.1|   8.405e+05|        19|      0.24|\n    |  2.7015e+05|  1.5213e+06|  2.7523e+05|     -5079.8|  7.4364e+05|        18|      0.26|\n    |  2.6494e+05|  1.4248e+06|     2.7e+05|     -5062.2|   7.565e+05|        16|      0.25|\n    |  2.5759e+05|  1.4116e+06|  2.6261e+05|     -5025.3|  7.5458e+05|        17|      0.25|\n    |  2.5241e+05|  1.3946e+06|  2.5741e+05|     -4995.2|  7.5024e+05|        17|      0.25|\n    |  2.5072e+05|  1.3878e+06|   2.557e+05|     -4985.1|  7.4574e+05|        17|      0.25|\n    |  2.4736e+05|  1.3646e+06|  2.5233e+05|     -4966.7|  7.4271e+05|        17|      0.24|\n    |  2.4692e+05|  1.3704e+06|  2.5189e+05|     -4963.6|  7.3803e+05|        17|      0.24|\n    |  2.4668e+05|  1.3704e+06|  2.5164e+05|     -4962.1|  7.3772e+05|        17|      0.23|\n    |  2.4636e+05|  1.3626e+06|  2.5132e+05|     -4960.7|  7.3814e+05|        17|      0.23|\n    |   2.461e+05|   1.365e+06|  2.5106e+05|       -4959|  7.3849e+05|        17|      0.24|\n    |  2.4609e+05|   1.366e+06|  2.5105e+05|     -4958.9|  7.3807e+05|        17|      0.24|\n    |  2.4607e+05|  1.3668e+06|  2.5103e+05|     -4958.7|  7.3754e+05|        17|      0.23|\n    |  2.4602e+05|  1.3669e+06|  2.5098e+05|     -4958.4|  7.3716e+05|        17|      0.26|\n    |  2.4598e+05|  1.3643e+06|  2.5094e+05|     -4958.2|   7.371e+05|        17|      0.24|\n    |  2.4595e+05|  1.3629e+06|  2.5091e+05|     -4958.1|  7.3764e+05|        17|      0.23|\n    |  2.4592e+05|    1.36e+06|  2.5088e+05|     -4958.2|  7.3836e+05|        17|      0.24|\n    |  2.4591e+05|  1.3593e+06|  2.5087e+05|     -4958.3|  7.3846e+05|        17|      0.23|\n    |  2.4592e+05|  1.3593e+06|  2.5087e+05|     -4958.4|  7.3839e+05|        17|      0.24|\n    |   2.459e+05|  1.3593e+06|  2.5086e+05|     -4958.3|  7.3847e+05|        17|      0.24|\n    |  2.4591e+05|  1.3593e+06|  2.5087e+05|     -4958.3|  7.3841e+05|        17|      0.25|\n    |   2.459e+05|  1.3593e+06|  2.5086e+05|     -4958.3|  7.3837e+05|        17|      0.24|\n    |  2.4592e+05|  1.3595e+06|  2.5088e+05|     -4958.3|  7.3841e+05|        17|      0.24|\n    |  2.4591e+05|  1.3593e+06|  2.5086e+05|     -4958.3|  7.3843e+05|        17|      0.25|\n    |  2.4591e+05|  1.3594e+06|  2.5087e+05|     -4958.4|  7.3838e+05|        17|      0.23|\n    |  2.4592e+05|  1.3596e+06|  2.5088e+05|     -4958.3|  7.3837e+05|        17|      0.23|\n    |  2.4592e+05|  1.3595e+06|  2.5088e+05|     -4958.3|  7.3845e+05|        17|      0.25|\n    |  2.4592e+05|  1.3595e+06|  2.5088e+05|     -4958.3|  7.3837e+05|        17|      0.24|\n    |  2.4592e+05|  1.3594e+06|  2.5087e+05|     -4958.3|  7.3839e+05|        17|      0.22|\n    |  2.4591e+05|  1.3593e+06|  2.5087e+05|     -4958.3|  7.3841e+05|        17|      0.24|\n    |   2.459e+05|  1.3593e+06|  2.5086e+05|     -4958.3|  7.3839e+05|        17|      0.24|\n    |  2.4591e+05|  1.3595e+06|  2.5087e+05|     -4958.4|  7.3835e+05|        17|      0.24|\n    |  2.4592e+05|  1.3595e+06|  2.5087e+05|     -4958.3|   7.384e+05|        17|      0.25|\n    |  2.4591e+05|  1.3593e+06|  2.5087e+05|     -4958.3|  7.3833e+05|        17|      0.23|\n    |  2.4592e+05|  1.3595e+06|  2.5088e+05|     -4958.3|  7.3839e+05|        17|      0.24|\n    |   2.459e+05|  1.3593e+06|  2.5086e+05|     -4958.3|   7.384e+05|        17|      0.25|\n    |  2.4591e+05|  1.3593e+06|  2.5087e+05|     -4958.3|  7.3834e+05|        17|      0.24|\n    |   2.459e+05|  1.3592e+06|  2.5086e+05|     -4958.3|  7.3829e+05|        17|      0.24|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |   5.431e+05|  2.3353e+06|  5.4922e+05|     -6117.3|  8.8699e+05|        23|      0.24|\n    |  4.5519e+05|  2.2735e+06|  4.6102e+05|       -5835|  8.6878e+05|        21|      0.24|\n    |  3.6753e+05|  2.1734e+06|  3.7304e+05|     -5515.8|  8.3787e+05|        20|      0.24|\n    |  3.1701e+05|  1.9674e+06|  3.2231e+05|     -5308.9|  8.0762e+05|        19|      0.24|\n    |  2.8378e+05|  1.7413e+06|  2.8894e+05|       -5161|  7.8606e+05|        19|      0.24|\n    |  2.6799e+05|  1.4806e+06|  2.7308e+05|     -5084.6|  7.7392e+05|        17|      0.26|\n    |  2.5525e+05|  1.4311e+06|  2.6027e+05|     -5015.9|  7.6262e+05|        17|      0.26|\n    |  2.5128e+05|  1.4322e+06|  2.5627e+05|     -4988.7|  7.4475e+05|        17|      0.27|\n    |  2.4982e+05|  1.4137e+06|   2.548e+05|     -4982.2|   7.441e+05|        17|      0.26|\n    |  2.4747e+05|  1.3876e+06|  2.5244e+05|     -4969.3|  7.4071e+05|        17|      0.25|\n    |   2.469e+05|  1.3822e+06|  2.5186e+05|     -4965.2|  7.4053e+05|        17|      0.27|\n    |  2.4652e+05|  1.3758e+06|  2.5149e+05|     -4962.8|  7.4009e+05|        17|      0.24|\n    |  2.4626e+05|  1.3716e+06|  2.5122e+05|     -4960.8|  7.3873e+05|        17|      0.24|\n    |  2.4625e+05|  1.3715e+06|  2.5121e+05|     -4960.6|  7.3867e+05|        17|      0.25|\n    |  2.4617e+05|  1.3706e+06|  2.5113e+05|     -4960.1|  7.3808e+05|        17|      0.24|\n    |  2.4611e+05|  1.3698e+06|  2.5106e+05|     -4959.8|  7.3774e+05|        17|      0.26|\n    |  2.4604e+05|  1.3693e+06|    2.51e+05|     -4959.5|   7.378e+05|        17|      0.25|\n    |  2.4596e+05|  1.3685e+06|  2.5092e+05|     -4959.2|  7.3826e+05|        17|      0.25|\n    |  2.4584e+05|  1.3664e+06|   2.508e+05|     -4959.4|  7.3925e+05|        17|      0.26|\n    |  2.4582e+05|  1.3666e+06|  2.5078e+05|     -4959.2|  7.3904e+05|        17|      0.24|\n    |  2.4578e+05|  1.3668e+06|  2.5074e+05|       -4959|  7.3853e+05|        17|      0.25|\n    |  2.4577e+05|  1.3661e+06|  2.5073e+05|       -4959|   7.386e+05|        17|      0.26|\n    |  2.4577e+05|  1.3642e+06|  2.5073e+05|     -4959.3|  7.3901e+05|        17|      0.24|\n    |  2.4578e+05|  1.3641e+06|  2.5074e+05|     -4959.3|    7.39e+05|        17|      0.25|\n    |  2.4579e+05|  1.3644e+06|  2.5075e+05|     -4959.3|    7.39e+05|        17|      0.25|\n    |  2.4577e+05|  1.3643e+06|  2.5073e+05|     -4959.3|  7.3901e+05|        17|      0.25|\n    |  2.4577e+05|  1.3642e+06|  2.5073e+05|     -4959.3|  7.3903e+05|        17|      0.25|\n    |  2.4577e+05|  1.3643e+06|  2.5073e+05|     -4959.3|  7.3902e+05|        17|      0.25|\n    |  2.4577e+05|  1.3642e+06|  2.5072e+05|     -4959.3|  7.3903e+05|        17|      0.27|\n    Optimization result:\n          fun: 245765.49367824764\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 1.36304913e+02,  3.00810233e+01,  3.90027469e+00,  1.28611778e+01,\n            3.36650532e+03,  6.51776000e+01,  0.00000000e+00,  7.56633342e-01,\n            7.15848687e+00,  5.52325844e+01,  0.00000000e+00,  2.12326989e+01,\n            9.51530446e+00, -1.85408403e+02,  4.37301861e+03,  5.29523389e+01,\n            5.50932936e+02, -6.41571608e+01,  6.78926698e+02, -8.05215814e+01,\n            6.51814604e+01,  2.55543662e+01,  0.00000000e+00,  6.58928427e+01,\n            5.60552606e+01])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 29\n          nit: 23\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -2.30258509,  1.53690932, -2.30258509,\n           -4.60517019, -0.39405819, -4.60517019, -2.30258509,  2.30258509,\n           -3.53658634, -4.11068327, -2.30258509,  1.79329838, -2.30258509,\n            1.71216563, -2.30258509,  1.89983159, -2.30258509, -0.58076275,\n           -2.30258509, -3.56642045, -1.83514442, -0.46088467, -2.30258509])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7f3c65ea2490>\n\n\n\n\n```\nmu = gpr3.predict(train.graphs)\nplt.scatter(train[target], mu)\n#plt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\n#plt.xlim(-9, 3)\n#plt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.3711113759832458\n    RMSE: 0.5245520571276874\n\n\n\n```\nmu_test = gpr3.predict(test.graphs)\nplt.scatter(test[target], mu_test)\n#plt.plot(np.linspace(-10, 4), np.linspace(-10, 4), c = 'r')\n#plt.xlim(-10, 4)\n#plt.ylim(-10, 4)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 1.1498112446483284\n    RMSE: 1.4624191158480997\n\n\n\n```\ngpr3.kernel.hyperparameters\n```\n\n\n\n\n    starting_probability : Uniform\n    \tp : 1.0\n    stopping_probability : 0.00010000000000000009\n    node_kernel : Composite\n    \taromatic : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.010000000000000004\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tatomic_number : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 4.650195760291015\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tcharge : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.010000000000000004\n    \t\trhs : SquareExponential\n    \t\t\tlength_scale : 0.6743148146404403\n    \tchiral : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.010000000000000004\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \thcount : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 10.000000000000002\n    \t\trhs : SquareExponential\n    \t\t\tlength_scale : 0.029112537932671788\n    \thybridization : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.016396567373846038\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tring_list : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 6.009240566276212\n    \t\trhs : Convolution\n    \t\t\tbase : KroneckerDelta\n    \t\t\t\th : 0.10000000000000002\n    edge_kernel : Composite\n    \taromatic : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 5.540948138687138\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tconjugated : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 6.68476853323407\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \torder : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.5594714650176335\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tring_stereo : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.02825681966816714\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.15959045135761826\n    \tstereo : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.6307254157656439\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n\n\n\n### Model 4\n\n\n```\ngpr4 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-2, #different from gpr in alpha where gpr_base's alpha is 1e-4\n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr4.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |       66517|       88265|       70813|     -4296.2|       90905|        21|      0.28|\n    |       61455|  1.0409e+05|       65648|     -4193.5|       88757|        19|      0.25|\n    |       50869|  1.1321e+05|       54789|     -3920.3|       81573|        17|      0.23|\n    |       49285|  1.0995e+05|       53162|     -3876.6|       80232|        17|      0.28|\n    |       48321|  1.0553e+05|       52167|       -3845|       78704|        16|      0.24|\n    |       47912|  1.0664e+05|       51747|     -3834.9|       78334|        17|      0.25|\n    |       47815|  1.0611e+05|       51648|     -3832.7|       78473|        17|      0.25|\n    |       47734|  1.0602e+05|       51565|     -3830.1|       78399|        17|      0.24|\n    |       47721|   1.056e+05|       51549|     -3828.8|       78754|        17|      0.25|\n    |       47682|  1.0583e+05|       51510|     -3827.7|       78471|        17|      0.25|\n    |       47662|  1.0594e+05|       51489|     -3827.2|       78334|        17|      0.28|\n    |       47637|  1.0591e+05|       51463|     -3826.7|       78258|        17|      0.24|\n    |       47613|  1.0565e+05|       51439|     -3826.3|       78273|        17|      0.24|\n    |       47587|  1.0505e+05|       51413|     -3826.2|       78397|        17|      0.25|\n    |       47584|  1.0508e+05|       51410|       -3826|       78364|        17|      0.25|\n    |       47579|  1.0506e+05|       51404|     -3825.6|       78277|        17|      0.23|\n    |       47574|  1.0486e+05|       51399|     -3825.5|       78232|        17|      0.25|\n    |       47570|    1.04e+05|       51397|     -3826.4|       78274|        17|      0.28|\n    |       47576|  1.0386e+05|       51402|     -3825.9|       78262|        17|      0.24|\n    |       47569|  1.0395e+05|       51395|     -3826.1|       78271|        17|      0.24|\n    |       47567|  1.0417e+05|       51393|     -3826.1|       78324|        17|      0.28|\n    |       47566|  1.0407e+05|       51392|     -3826.3|       78362|        17|      0.23|\n    |       47566|  1.0398e+05|       51392|     -3826.4|       78386|        17|      0.24|\n    |       47566|  1.0405e+05|       51393|     -3826.3|       78366|        17|      0.24|\n    |       47566|  1.0406e+05|       51392|     -3826.3|       78363|        17|      0.25|\n    |       47566|  1.0407e+05|       51392|     -3826.3|       78362|        17|      0.24|\n    |       47566|  1.0407e+05|       51392|     -3826.3|       78361|        17|      0.25|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |       73087|       31386|       77530|       -4443|       95203|        16|      0.26|\n    |       69027|       48566|       73397|     -4370.2|       93280|        18|      0.25|\n    |       56295|  1.0441e+05|       60364|     -4068.9|       85503|        19|      0.26|\n    |       49629|  1.0815e+05|       53493|     -3864.5|       76173|        17|      0.26|\n    |       48176|  1.0901e+05|       52013|     -3837.5|       77267|        17|      0.26|\n    |       49949|   1.003e+05|       53850|       -3901|       82147|        18|      0.26|\n    |       47973|   1.074e+05|       51809|     -3836.1|       78349|        18|      0.26|\n    |       47868|  1.0647e+05|       51701|     -3833.7|       78588|        17|      0.25|\n    |       47825|  1.0603e+05|       51658|     -3832.9|       78699|        17|      0.25|\n    |       47758|  1.0569e+05|       51589|     -3831.2|       78709|        17|      0.25|\n    |       47712|  1.0601e+05|       51542|     -3829.4|       78587|        17|      0.26|\n    |       47692|  1.0615e+05|       51520|     -3828.2|       78413|        17|      0.24|\n    |       47690|  1.0616e+05|       51518|     -3828.1|       78396|        17|      0.23|\n    |       47681|  1.0614e+05|       51508|     -3827.4|       78346|        17|      0.24|\n    |       47681|  1.0645e+05|       51508|     -3827.2|       78253|        17|      0.24|\n    |       47674|  1.0629e+05|       51501|     -3827.1|       78299|        17|      0.25|\n    |       47654|  1.0622e+05|       51481|     -3826.3|       78288|        17|      0.25|\n    |       47645|  1.0603e+05|       51471|     -3826.2|       78342|        17|      0.26|\n    |       47644|  1.0605e+05|       51471|     -3826.4|       78352|        17|      0.26|\n    |       47644|  1.0604e+05|       51471|     -3826.3|       78347|        17|      0.24|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |       67828|  1.0852e+05|       72138|     -4309.5|       89137|        24|      0.25|\n    |       62412|  1.1469e+05|       66616|       -4204|       87873|        21|      0.25|\n    |       56410|   1.222e+05|       60478|     -4067.7|       85994|        20|      0.26|\n    |       51080|  1.1784e+05|       55004|     -3924.2|       81494|        18|      0.26|\n    |       49634|  1.1413e+05|       53522|     -3888.1|       80979|        18|      0.24|\n    |       48936|  1.0759e+05|       52800|     -3863.2|       79659|        17|      0.24|\n    |       48434|  1.0891e+05|       52284|     -3850.2|       79231|        17|      0.24|\n    |       48204|  1.0827e+05|       52049|     -3844.6|       79132|        18|      0.25|\n    |       47886|  1.0625e+05|       51723|     -3836.7|       78967|        17|      0.24|\n    |       48724|  1.0903e+05|       52577|     -3853.3|       76871|        19|      0.24|\n    |       47877|  1.0635e+05|       51713|     -3836.1|       78785|        18|      0.24|\n    |       48134|  1.0654e+05|       51976|     -3841.5|       78087|        18|      0.24|\n    |       47877|  1.0635e+05|       51712|       -3836|       78744|        17|      0.23|\n    |       47789|  1.0549e+05|       51623|     -3834.3|       78780|        17|      0.24|\n    |       47692|  1.0404e+05|       51525|     -3832.6|       78739|        17|      0.24|\n    |       47665|  1.0386e+05|       51497|     -3831.4|       78613|        17|      0.24|\n    |       47626|  1.0394e+05|       51456|     -3829.6|       78486|        17|      0.26|\n    |       47604|  1.0463e+05|       51432|     -3827.8|       78343|        17|      0.26|\n    |       47590|  1.0446e+05|       51417|     -3827.3|       78398|        17|      0.24|\n    |       47588|  1.0442e+05|       51415|     -3827.1|       78415|        17|      0.26|\n    |       47586|  1.0443e+05|       51413|     -3826.9|       78414|        17|      0.28|\n    |       47582|   1.045e+05|       51409|     -3826.5|       78406|        17|      0.24|\n    |       47579|  1.0481e+05|       51405|     -3825.9|       78253|        17|      0.23|\n    |       47575|  1.0471e+05|       51401|       -3826|       78318|        17|      0.24|\n    |       47573|  1.0459e+05|       51399|     -3826.2|       78354|        17|      0.24|\n    |       47571|  1.0449e+05|       51397|     -3826.3|       78369|        17|      0.24|\n    |       47568|  1.0432e+05|       51394|     -3826.5|       78382|        17|      0.23|\n    |       47566|  1.0421e+05|       51393|     -3826.5|       78376|        17|      0.24|\n    |       47565|   1.042e+05|       51391|     -3826.3|       78347|        17|      0.26|\n    |       47564|  1.0411e+05|       51390|     -3826.1|       78329|        17|      0.24|\n    |       47564|  1.0402e+05|       51390|     -3826.2|       78343|        17|      0.23|\n    |       47564|  1.0392e+05|       51390|     -3826.3|       78361|        17|      0.26|\n    |       47563|  1.0399e+05|       51389|     -3826.2|       78348|        17|      0.24|\n    Optimization result:\n          fun: 47563.16826613996\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 1.03860634e+01,  3.99556925e+00,  4.34356887e-01, -4.38765528e+00,\n            3.35685830e+02,  5.48613650e+00,  0.00000000e+00,  3.74597978e+00,\n            3.71923847e-01, -1.86677689e+01,  1.80494389e-04,  2.34556512e+00,\n            6.89757782e-01,  7.46525570e+00,  3.86435984e+02, -4.08724178e+00,\n            6.25487975e+01,  3.79069496e+00,  5.00876053e+01, -1.47395577e+00,\n            1.52830838e+01,  1.49931223e+00,  0.00000000e+00,  2.53256179e-01,\n            2.78310073e-01])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 33\n          nit: 29\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.23992363, -2.30258509,  1.70454451, -2.30258509,\n           -4.60517019, -0.39405819, -4.60517019, -1.7367717 ,  2.30258509,\n           -1.86521329, -4.33629426, -2.08030139,  1.84897251, -2.30258509,\n            2.14248562, -2.30258509,  1.93608271, -2.30258509,  0.72987226,\n           -2.30258509, -3.7783557 , -1.83514442, -3.16885023, -2.30258509])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7fb9896f5fd0>\n\n\n\n\n```\nmu = gpr4.predict(train.graphs)\nplt.scatter(train[target], mu)\n#plt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\n#plt.xlim(-9, 3)\n#plt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.6721642416785486\n    RMSE: 0.9001504628434619\n\n\n\n```\nmu_test = gpr4.predict(test.graphs)\nplt.scatter(test[target], mu_test)\n#plt.plot(np.linspace(-10, 4), np.linspace(-10, 4), c = 'r')\n#plt.xlim(-10, 4)\n#plt.ylim(-10, 4)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 0.996800387138675\n    RMSE: 1.2687098498475842\n\n\n### Model 5\n\n\n```\ngpr5 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-1, #different from gpr in alpha where gpr_base's alpha is 1e-4\n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr5.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |      5933.5|      3681.9|        8130|     -2196.5|        9095|        23|      0.27|\n    |      5700.6|      4368.7|      7866.6|       -2166|        8897|        21|      0.23|\n    |      5244.7|      4143.6|      7321.1|     -2076.4|      8114.4|        17|      0.24|\n    |      5161.9|      4261.1|      7222.8|       -2061|      8040.9|        17|      0.23|\n    |      5123.7|      4119.8|      7182.2|     -2058.5|      8116.4|        17|      0.25|\n    |      5100.9|      4055.4|      7155.4|     -2054.5|      8044.2|        17|      0.25|\n    |      5081.3|      3976.5|      7132.4|     -2051.1|      7995.7|        17|      0.24|\n    |      5078.6|      3971.4|      7128.4|     -2049.9|      7991.1|        17|      0.24|\n    |        5077|      3973.1|      7126.9|     -2049.9|      7990.8|        17|      0.24|\n    |      5075.4|      3971.5|      7125.2|     -2049.7|      7988.9|        17|      0.24|\n    |        5074|      3966.8|      7123.6|     -2049.5|      7985.4|        17|      0.26|\n    |      5071.8|      3952.7|        7121|     -2049.2|      7981.1|        17|      0.25|\n    |      5068.8|      3927.3|      7117.9|     -2049.1|      7982.1|        17|      0.26|\n    |      5067.9|      3915.3|      7117.1|     -2049.1|      7980.4|        17|      0.25|\n    |      5067.8|      3917.4|      7116.9|     -2049.1|      7979.1|        17|      0.25|\n    |      5067.8|      3919.2|      7116.8|       -2049|      7978.5|        17|      0.24|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |      6316.2|      4166.3|      8544.1|     -2227.9|        9356|        21|      0.23|\n    |      5897.8|      4552.2|      8086.8|       -2189|      9123.3|        20|      0.25|\n    |      5402.1|      4470.5|      7523.5|     -2121.3|      8676.4|        18|      0.23|\n    |      5263.9|      4484.2|        7355|     -2091.2|      8445.2|        18|      0.26|\n    |      5192.2|      4382.6|      7262.9|     -2070.7|      8189.6|        18|      0.25|\n    |      5121.6|      4136.4|      7180.3|     -2058.7|      8143.5|        17|      0.24|\n    |      5111.8|        4133|      7163.8|       -2052|        7978|        17|      0.23|\n    |      5100.7|      4164.8|      7150.7|     -2049.9|      7976.5|        17|      0.24|\n    |        5094|        4154|        7143|       -2049|      7983.6|        17|      0.23|\n    |      5089.6|        4131|      7138.2|     -2048.5|      7988.5|        17|      0.23|\n    |      5086.1|      4087.2|      7133.9|     -2047.8|      7974.4|        17|      0.23|\n    |      5082.2|      4085.6|        7130|     -2047.8|      7979.5|        17|      0.26|\n    |      5079.1|      4076.2|      7126.9|     -2047.9|      7977.4|        17|      0.23|\n    |      5078.3|      4068.3|      7126.3|       -2048|      7976.8|        17|      0.26|\n    |      5075.3|      3953.8|        7125|     -2049.7|      7975.3|        17|      0.23|\n    |      5073.1|      3984.2|      7122.2|     -2049.1|      7987.6|        17|      0.26|\n    |      5072.6|      3973.4|      7121.8|     -2049.2|      7988.8|        17|      0.28|\n    |      5071.1|      3934.7|      7120.4|     -2049.3|      7985.3|        17|      0.26|\n    |      5069.9|        3928|      7119.1|     -2049.2|      7984.2|        17|      0.25|\n    |      5068.5|      3913.3|      7117.8|     -2049.3|      7983.9|        17|      0.24|\n    |      5067.8|      3915.3|      7116.6|     -2048.8|      7969.8|        17|      0.25|\n    |      5067.5|      3903.7|      7117.2|     -2049.7|      7993.3|        17|      0.25|\n    |      5067.3|      3908.8|      7116.5|     -2049.2|      7983.6|        17|      0.24|\n    |      5067.1|        3910|      7116.1|       -2049|      7977.3|        17|      0.23|\n    |      5067.1|      3910.1|      7116.1|       -2049|      7977.7|        17|      0.26|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |      5834.4|      4699.1|      8022.2|     -2187.9|      9207.7|        21|      0.23|\n    |      5579.2|      4272.2|      7729.4|     -2150.2|      8902.1|        19|      0.24|\n    |        5265|      4187.4|      7346.4|     -2081.4|      8221.2|        18|      0.27|\n    |      5170.4|      3954.9|      7238.8|     -2068.4|      8110.4|        17|      0.24|\n    |      5137.6|      4046.1|      7198.2|     -2060.6|      8053.1|        17|      0.25|\n    |      5109.8|      4060.1|      7164.7|     -2054.9|      8036.6|        17|      0.23|\n    |      5092.8|      4026.6|      7144.8|       -2052|      8014.6|        17|      0.23|\n    |      5086.7|      3944.7|      7136.4|     -2049.7|      7929.4|        17|      0.23|\n    |      5078.8|      3926.5|      7130.6|     -2051.8|      8024.8|        17|      0.24|\n    |      5077.1|      3942.6|      7128.1|     -2050.9|      8009.4|        17|      0.23|\n    |      5075.3|      3953.9|      7125.3|     -2049.9|      7991.6|        17|      0.27|\n    |      5072.7|        3957|      7121.7|       -2049|      7973.5|        17|      0.25|\n    |      5069.8|      3945.2|      7118.4|     -2048.6|      7968.5|        17|      0.24|\n    |      5069.4|        3932|      7118.3|     -2048.9|      7981.7|        17|      0.25|\n    |      5068.9|      3930.6|      7117.9|       -2049|        7981|        17|      0.23|\n    |      5068.8|      3926.4|      7117.9|     -2049.1|      7983.4|        17|      0.24|\n    |      5068.4|      3917.5|      7117.9|     -2049.4|      7987.3|        17|      0.23|\n    |      5068.1|      3910.6|      7117.7|     -2049.6|        7989|        17|      0.25|\n    |      5067.8|      3913.7|      7117.1|     -2049.3|        7985|        17|      0.23|\n    |      5067.6|      3919.1|      7116.2|     -2048.6|      7972.4|        17|      0.23|\n    |      5067.4|      3918.6|      7116.2|     -2048.8|      7975.7|        17|      0.23|\n    |      5067.4|        3918|      7116.2|     -2048.9|        7976|        17|      0.23|\n    Optimization result:\n          fun: 5067.119508760024\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 3.90259274e-01,  1.87865706e-01,  2.15153320e-02,  5.95899075e-02,\n            1.81887249e+01,  3.14234542e-01,  0.00000000e+00,  2.98486676e-01,\n            9.99179948e-03, -1.21282065e+00,  0.00000000e+00,  1.07942514e-01,\n            2.29213419e-02,  2.45315195e-01,  1.44913639e+01,  2.38720249e-03,\n            6.78953722e-03, -1.08856133e-01,  3.25365990e+00,  4.00300271e-02,\n            3.61716207e+00,  3.49621047e-02,  0.00000000e+00,  3.14194196e-02,\n            3.39042590e-03])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 25\n          nit: 24\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -1.9276534 ,  1.65083009, -2.30258509,\n           -4.60517019,  0.08473439, -4.60517019, -0.94627051,  2.30258509,\n           -4.52691773, -4.60517019, -2.30258509,  1.42510738, -2.30258509,\n           -4.00849461, -2.30258509,  2.12160197, -2.30258509,  2.23247174,\n           -2.30258509, -4.60517019, -1.5016103 , -4.60517019, -0.71533121])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7fb9880bba10>\n\n\n\n\n```\nmu = gpr5.predict(train.graphs)\nplt.scatter(train[target], mu)\n#plt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\n#plt.xlim(-9, 3)\n#plt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.8642262237055949\n    RMSE: 1.1297768774199661\n\n\n\n```\nmu_test = gpr5.predict(test.graphs)\nplt.scatter(test[target], mu_test)\n#plt.plot(np.linspace(-10, 4), np.linspace(-10, 4), c = 'r')\n#plt.xlim(-10, 4)\n#plt.ylim(-10, 4)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 0.9967978325813834\n    RMSE: 1.2687065452737312\n\n\n### Model 6\n\n\n```\ngpr6 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.6, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # turn constant from 0.5 to 0.6\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-4, \n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr6.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  2.8944e+06|  2.4509e+07|  2.9017e+06|     -7301.3|  8.7008e+06|        23|      0.24|\n    |  1.9494e+06|  2.0854e+07|  1.9561e+06|     -6753.4|   8.028e+06|        20|      0.23|\n    |  1.2919e+06|  1.5736e+07|  1.2981e+06|     -6252.9|  7.0779e+06|        20|      0.27|\n    |  1.0068e+06|  1.2319e+07|  1.0128e+06|     -5972.2|  6.4115e+06|        19|      0.24|\n    |   8.252e+05|  9.7166e+06|  8.3096e+05|     -5754.8|  5.8216e+06|        18|      0.25|\n    |  7.1178e+05|   8.079e+06|  7.1737e+05|     -5588.3|  5.3678e+06|        18|      0.26|\n    |  6.4905e+05|  7.1022e+06|  6.5454e+05|     -5488.5|  5.0406e+06|        17|      0.27|\n    |  6.2943e+05|  7.0339e+06|  6.3487e+05|     -5434.9|  4.9547e+06|        18|      0.24|\n    |  6.0986e+05|  6.6391e+06|  6.1527e+05|       -5413|  4.8444e+06|        17|      0.23|\n    |  6.0534e+05|  6.5378e+06|  6.1075e+05|     -5407.5|  4.7983e+06|        17|      0.25|\n    |  6.0277e+05|  6.4966e+06|  6.0817e+05|     -5402.7|  4.7826e+06|        17|      0.24|\n    |  6.0629e+05|  6.6683e+06|  6.1169e+05|     -5395.9|  4.8331e+06|        17|      0.24|\n    |  6.0089e+05|  6.5204e+06|  6.0628e+05|     -5395.1|  4.7923e+06|        17|      0.25|\n    |  5.9998e+05|  6.4999e+06|  6.0538e+05|     -5393.6|  4.7905e+06|        17|      0.24|\n    |  5.9751e+05|  6.4425e+06|   6.029e+05|     -5389.9|  4.7727e+06|        17|      0.24|\n    |  5.9602e+05|  6.4134e+06|  6.0141e+05|     -5388.3|  4.7571e+06|        17|      0.23|\n    |  5.9529e+05|  6.4045e+06|  6.0068e+05|     -5387.1|  4.7468e+06|        17|      0.24|\n    |  5.9508e+05|   6.419e+06|  6.0047e+05|     -5386.2|  4.7444e+06|        17|      0.25|\n    |  5.9499e+05|   6.421e+06|  6.0037e+05|     -5386.3|  4.7432e+06|        17|      0.23|\n    |  5.9466e+05|   6.419e+06|  6.0004e+05|     -5386.4|  4.7373e+06|        17|      0.25|\n    |   5.941e+05|   6.412e+06|  5.9948e+05|     -5386.7|  4.7315e+06|        17|      0.23|\n    |  5.9369e+05|  6.4026e+06|  5.9907e+05|     -5386.7|  4.7371e+06|        17|      0.24|\n    |  5.9328e+05|  6.3952e+06|  5.9867e+05|     -5386.1|  4.7444e+06|        17|      0.24|\n    |  5.9304e+05|  6.3888e+06|  5.9842e+05|     -5385.8|  4.7548e+06|        17|      0.23|\n    |  5.9302e+05|  6.3838e+06|   5.984e+05|       -5386|  4.7597e+06|        17|      0.25|\n    |  5.9304e+05|  6.3849e+06|  5.9843e+05|       -5386|  4.7593e+06|        17|      0.24|\n    |  5.9295e+05|  6.3824e+06|  5.9833e+05|       -5386|  4.7587e+06|        17|      0.25|\n    |  5.9299e+05|  6.3837e+06|  5.9838e+05|       -5386|  4.7563e+06|        17|      0.24|\n    |  5.9319e+05|  6.4017e+06|  5.9857e+05|       -5385|  4.7665e+06|        17|      0.24|\n    |  5.9304e+05|  6.3866e+06|  5.9843e+05|     -5385.8|  4.7595e+06|        17|      0.24|\n    |  5.9305e+05|  6.3853e+06|  5.9844e+05|       -5386|  4.7599e+06|        17|      0.23|\n    |  5.9307e+05|  6.3849e+06|  5.9846e+05|       -5386|   4.757e+06|        17|      0.23|\n    |    5.93e+05|  6.3836e+06|  5.9838e+05|       -5386|  4.7559e+06|        17|      0.24|\n    |  5.9306e+05|  6.3852e+06|  5.9845e+05|       -5386|  4.7592e+06|        17|      0.23|\n    |  5.9301e+05|  6.3839e+06|   5.984e+05|       -5386|  4.7578e+06|        17|      0.23|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  4.3078e+06|  2.4446e+07|  4.3158e+06|     -7932.3|  9.2634e+06|        21|      0.25|\n    |  2.6238e+06|  2.3168e+07|   2.631e+06|     -7161.6|  8.6166e+06|        20|      0.24|\n    |  1.4053e+06|  1.5186e+07|  1.4117e+06|     -6369.3|  7.1961e+06|        18|      0.25|\n    |  1.1501e+06|  1.2868e+07|  1.1563e+06|     -6132.5|   6.746e+06|        18|      0.24|\n    |  9.8738e+05|  1.1307e+07|  9.9334e+05|     -5957.9|  6.3374e+06|        18|      0.23|\n    |  8.2974e+05|  9.6748e+06|   8.355e+05|     -5760.9|   5.864e+06|        18|      0.23|\n    |  7.2817e+05|  8.3894e+06|  7.3379e+05|     -5614.1|  5.4676e+06|        18|      0.24|\n    |  6.5311e+05|  7.2434e+06|  6.5861e+05|     -5496.1|  5.0895e+06|        17|      0.23|\n    |  6.3629e+05|  7.1772e+06|  6.4174e+05|     -5445.9|  5.0349e+06|        18|      0.24|\n    |  6.1577e+05|  6.7766e+06|   6.212e+05|     -5425.6|  4.8996e+06|        17|      0.24|\n    |  6.1203e+05|  6.6858e+06|  6.1745e+05|     -5421.8|  4.8508e+06|        17|      0.23|\n    |  6.0713e+05|   6.593e+06|  6.1255e+05|       -5414|  4.7992e+06|        17|      0.24|\n    |  6.0018e+05|  6.4885e+06|  6.0558e+05|     -5401.3|  4.7629e+06|        17|      0.25|\n    |  6.5468e+05|  7.3957e+06|  6.6014e+05|     -5464.5|  5.0674e+06|        18|      0.24|\n    |   5.984e+05|  6.4756e+06|   6.038e+05|       -5396|  4.7756e+06|        17|      0.23|\n    |  5.9776e+05|  6.4973e+06|  6.0315e+05|     -5389.9|  4.8032e+06|        17|      0.24|\n    |  5.9687e+05|  6.4635e+06|  6.0226e+05|     -5390.9|  4.7897e+06|        17|      0.23|\n    |  5.9663e+05|  6.4495e+06|  6.0202e+05|     -5391.1|    4.78e+06|        17|      0.23|\n    |  5.9603e+05|  6.4182e+06|  6.0142e+05|     -5390.9|  4.7783e+06|        17|      0.24|\n    |  5.9545e+05|  6.3978e+06|  6.0084e+05|     -5390.2|  4.7798e+06|        17|      0.24|\n    |   5.942e+05|  6.3869e+06|  5.9958e+05|     -5387.5|  4.7722e+06|        17|      0.24|\n    |  5.9381e+05|  6.4054e+06|   5.992e+05|     -5387.9|  4.7492e+06|        17|      0.24|\n    |  5.9354e+05|  6.4008e+06|  5.9893e+05|     -5386.7|  4.7567e+06|        17|      0.25|\n    |  5.9354e+05|  6.3981e+06|  5.9893e+05|     -5386.7|  4.7567e+06|        17|      0.24|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  2.3591e+06|  2.4908e+07|  2.3661e+06|     -7034.7|  8.4043e+06|        21|      0.24|\n    |  1.5531e+06|  1.6909e+07|  1.5596e+06|     -6490.3|    7.48e+06|        19|      0.23|\n    |  1.1408e+06|  1.3163e+07|  1.1469e+06|     -6126.7|  6.6951e+06|        18|      0.25|\n    |  9.1088e+05|   1.096e+07|  9.1675e+05|     -5869.3|  6.1146e+06|        18|      0.24|\n    |  7.6245e+05|  9.3372e+06|  7.6811e+05|     -5663.5|  5.6153e+06|        18|      0.23|\n    |   6.811e+05|  7.7618e+06|  6.8665e+05|     -5544.7|   5.233e+06|        17|      0.23|\n    |   6.376e+05|  7.2172e+06|  6.4306e+05|     -5456.3|  5.0444e+06|        18|      0.23|\n    |  6.1814e+05|  6.8527e+06|  6.2357e+05|     -5431.2|  4.9071e+06|        17|      0.23|\n    |  6.1533e+05|  6.8145e+06|  6.2076e+05|     -5425.8|  4.8904e+06|        17|      0.24|\n    |  6.0068e+05|  6.5101e+06|  6.0607e+05|     -5396.8|  4.8158e+06|        17|      0.25|\n    |   6.032e+05|  6.5297e+06|   6.086e+05|     -5402.9|  4.7808e+06|        17|      0.24|\n    |  5.9762e+05|  6.4715e+06|  6.0301e+05|     -5392.6|  4.7857e+06|        17|      0.25|\n    |  5.9709e+05|  6.4584e+06|  6.0248e+05|     -5391.8|  4.7814e+06|        17|      0.25|\n    |  5.9557e+05|  6.4218e+06|  6.0096e+05|     -5389.6|  4.7534e+06|        17|      0.25|\n    |  5.9529e+05|  6.4276e+06|  6.0068e+05|     -5388.7|  4.7492e+06|        17|      0.25|\n    |   5.951e+05|  6.4417e+06|  6.0049e+05|     -5387.2|  4.7503e+06|        17|      0.25|\n    |  5.9491e+05|  6.4382e+06|   6.003e+05|     -5386.9|  4.7501e+06|        17|      0.25|\n    |  5.9461e+05|  6.4216e+06|       6e+05|     -5386.2|   4.745e+06|        17|      0.26|\n    |  5.9443e+05|  6.4165e+06|  5.9981e+05|     -5386.3|  4.7458e+06|        17|      0.27|\n    |  5.9437e+05|  6.4123e+06|  5.9976e+05|     -5386.9|  4.7532e+06|        17|      0.24|\n    |  5.9421e+05|  6.4142e+06|  5.9959e+05|     -5387.2|  4.7514e+06|        17|      0.25|\n    |  5.9384e+05|   6.425e+06|  5.9923e+05|     -5387.5|  4.7582e+06|        17|      0.26|\n    |  5.9383e+05|  6.4305e+06|  5.9921e+05|     -5387.4|  4.7531e+06|        17|      0.26|\n    |  5.9352e+05|  6.4281e+06|   5.989e+05|     -5387.3|  4.7524e+06|        17|      0.26|\n    |  5.9368e+05|  6.4099e+06|  5.9907e+05|     -5387.6|  4.7644e+06|        17|      0.25|\n    |  5.9336e+05|  6.4213e+06|  5.9875e+05|     -5387.3|  4.7549e+06|        17|      0.26|\n    |  5.9322e+05|  6.3927e+06|   5.986e+05|     -5387.4|  4.7593e+06|        17|      0.26|\n    |    5.93e+05|  6.3959e+06|  5.9839e+05|     -5386.2|  4.7617e+06|        17|      0.24|\n    |    5.93e+05|  6.3869e+06|  5.9839e+05|     -5386.2|  4.7586e+06|        17|      0.24|\n    Optimization result:\n          fun: 593000.2041736571\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 6.38284515e+02,  1.28515081e+02,  1.72016412e+01, -5.82582048e+02,\n            1.36357933e+04,  2.83378883e+02,  0.00000000e+00, -8.30365981e+01,\n            1.22305889e+02, -5.03965443e+02,  4.60608978e-09,  1.39105061e+02,\n            6.23139520e+01,  6.28523410e+02,  1.76102989e+04, -3.33355337e+02,\n            1.67897721e+03,  4.90612760e+02,  3.01620918e+03, -1.72678375e+02,\n            2.67735167e+02,  7.16052397e+01,  0.00000000e+00, -5.63227592e+01,\n            2.38442814e+02])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 29\n          nit: 26\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -2.30258509,  1.46103589, -2.30258509,\n           -4.60517019, -0.82374502, -3.32653759, -2.30258509,  2.30258509,\n           -2.13639892, -3.70091117, -2.30258509,  1.72561975, -2.30258509,\n            0.9291573 , -2.30258509,  1.55553156, -2.30258509, -0.95878504,\n           -2.30258509, -4.39978823, -0.49842698, -1.02640086, -2.30258509])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7f3c64d5dfd0>\n\n\n\n\n```\nmu = gpr6.predict(train.graphs)\nplt.scatter(train[target], mu)\n#plt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\n#plt.xlim(-9, 3)\n#plt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.10249072489800545\n    RMSE: 0.15577701746575612\n\n\n\n```\nmu_test = gpr6.predict(test.graphs)\nplt.scatter(test[target], mu_test)\n#plt.plot(np.linspace(-10, 4), np.linspace(-10, 4), c = 'r')\n#plt.xlim(-10, 4)\n#plt.ylim(-10, 4)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 1.3991366642890872\n    RMSE: 1.7909756847596061\n\n\n\n```\ngpr6.kernel.hyperparameters\n```\n\n\n\n\n    starting_probability : Uniform\n    \tp : 1.0\n    stopping_probability : 0.00010000000000000009\n    node_kernel : Composite\n    \taromatic : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.010000000000000004\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tatomic_number : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 4.310422330155447\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tcharge : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.010000000000000004\n    \t\trhs : SquareExponential\n    \t\t\tlength_scale : 0.43878531186353925\n    \tchiral : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.035917250437390136\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \thcount : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 10.000000000000002\n    \t\trhs : SquareExponential\n    \t\t\tlength_scale : 0.11807929101826045\n    \thybridization : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.024701009456560903\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tring_list : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 5.61600046940634\n    \t\trhs : Convolution\n    \t\t\tbase : KroneckerDelta\n    \t\t\t\th : 0.10000000000000002\n    edge_kernel : Composite\n    \taromatic : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 2.5323742411622123\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tconjugated : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 4.737604186275108\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \torder : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.3833583698593362\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tring_stereo : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.012279940120036538\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.6074854974727623\n    \tstereo : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.3582941931636685\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n\n\n\n### Model 7\n\n\n```\ngpr7 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.7, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # turn constant from 0.5 to 0.6\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-4, \n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr7.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  5.9304e+05|  6.3793e+06|  5.9843e+05|     -5386.6|  4.7603e+06|        17|      0.24|\n    |  6.2518e+05|  6.9973e+06|   6.306e+05|     -5421.7|  4.9692e+06|        18|      0.23|\n    |  5.9314e+05|  6.3838e+06|  5.9852e+05|     -5386.4|  4.7592e+06|        17|      0.25|\n    |   5.931e+05|  6.3809e+06|  5.9849e+05|     -5386.6|  4.7581e+06|        17|      0.23|\n    |    5.93e+05|  6.3786e+06|  5.9839e+05|     -5386.6|  4.7615e+06|        17|      0.23|\n    |  5.9301e+05|  6.3784e+06|  5.9839e+05|     -5386.6|    4.76e+06|        17|      0.24|\n    |   5.931e+05|  6.3806e+06|  5.9848e+05|     -5386.6|  4.7589e+06|        17|      0.23|\n    |  5.9301e+05|  6.3788e+06|   5.984e+05|     -5386.6|   4.759e+06|        17|      0.23|\n    |  5.9308e+05|  6.3802e+06|  5.9847e+05|     -5386.6|  4.7574e+06|        17|      0.24|\n    |  5.9301e+05|  6.3782e+06|  5.9839e+05|     -5386.6|  4.7602e+06|        17|      0.25|\n    |  5.9297e+05|  6.3774e+06|  5.9835e+05|     -5386.6|  4.7586e+06|        17|      0.23|\n    |  5.9309e+05|  6.3798e+06|  5.9848e+05|     -5386.6|  4.7591e+06|        17|      0.22|\n    |  5.9303e+05|  6.3789e+06|  5.9842e+05|     -5386.6|  4.7591e+06|        17|      0.23|\n    |    5.93e+05|  6.3785e+06|  5.9838e+05|     -5386.6|  4.7606e+06|        17|      0.24|\n    |  5.9308e+05|  6.3803e+06|  5.9847e+05|     -5386.6|   4.758e+06|        17|      0.25|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  6.2038e+05|  6.7537e+06|  6.2582e+05|     -5434.1|  4.7314e+06|        17|      0.24|\n    |  5.9933e+05|  6.4821e+06|  6.0473e+05|       -5397|  4.7441e+06|        17|      0.24|\n    |  5.9769e+05|    6.45e+06|  6.0308e+05|     -5392.6|  4.7696e+06|        17|      0.25|\n    |  5.9743e+05|  6.4631e+06|  6.0282e+05|     -5391.6|  4.7654e+06|        17|      0.26|\n    |  5.9704e+05|  6.4585e+06|  6.0244e+05|     -5391.5|  4.7579e+06|        17|      0.25|\n    |  5.9611e+05|  6.4563e+06|   6.015e+05|     -5390.1|  4.7477e+06|        17|      0.24|\n    |  5.9481e+05|  6.4272e+06|   6.002e+05|     -5388.9|  4.7474e+06|        17|      0.26|\n    |  5.9378e+05|  6.4308e+06|  5.9916e+05|       -5386|  4.7647e+06|        17|      0.27|\n    |  5.9357e+05|  6.4203e+06|  5.9896e+05|       -5386|  4.7722e+06|        17|      0.24|\n    |  5.9347e+05|  6.4064e+06|  5.9886e+05|     -5386.7|  4.7625e+06|        17|      0.24|\n    |   5.934e+05|   6.402e+06|  5.9878e+05|     -5386.9|  4.7599e+06|        17|      0.24|\n    |  5.9342e+05|  6.4005e+06|  5.9881e+05|       -5387|  4.7586e+06|        17|      0.24|\n    |  5.9346e+05|  6.4029e+06|  5.9885e+05|     -5386.9|  4.7625e+06|        17|      0.24|\n    |   5.935e+05|  6.4047e+06|  5.9889e+05|     -5386.9|  4.7585e+06|        17|      0.24|\n    |  5.9357e+05|  6.4069e+06|  5.9896e+05|     -5386.9|  4.7616e+06|        17|      0.24|\n    |   5.935e+05|  6.4051e+06|  5.9889e+05|     -5386.8|  4.7579e+06|        17|      0.24|\n    |  5.9349e+05|  6.4045e+06|  5.9887e+05|     -5386.8|  4.7591e+06|        17|      0.25|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  6.8046e+05|   7.227e+06|    6.86e+05|     -5543.1|  5.0831e+06|        16|      0.23|\n    |  6.3776e+05|   7.023e+06|  6.4323e+05|     -5467.6|  5.0039e+06|        17|      0.23|\n    |  6.1826e+05|  6.7669e+06|  6.2369e+05|     -5432.5|  4.9233e+06|        17|      0.23|\n    |  6.0253e+05|  6.5232e+06|  6.0794e+05|     -5404.8|  4.8388e+06|        17|      0.24|\n    |  6.0067e+05|  6.4919e+06|  6.0608e+05|       -5402|   4.816e+06|        17|      0.23|\n    |   5.976e+05|  6.4513e+06|    6.03e+05|     -5397.5|  4.7775e+06|        17|      0.23|\n    |  5.9556e+05|  6.4049e+06|  6.0095e+05|     -5393.5|  4.7764e+06|        17|      0.24|\n    |  5.9373e+05|  6.3965e+06|  5.9912e+05|     -5388.4|  4.7734e+06|        17|      0.25|\n    |  5.9338e+05|  6.3912e+06|  5.9876e+05|     -5387.8|  4.7767e+06|        17|      0.23|\n    |  5.9323e+05|   6.392e+06|  5.9862e+05|     -5387.4|  4.7644e+06|        17|      0.23|\n    |  5.9313e+05|   6.393e+06|  5.9852e+05|     -5387.5|  4.7663e+06|        17|      0.24|\n    |  5.9311e+05|   6.392e+06|   5.985e+05|     -5387.6|  4.7607e+06|        17|      0.24|\n    |  5.9311e+05|   6.392e+06|  5.9849e+05|     -5387.3|  4.7611e+06|        17|      0.24|\n    |  5.9305e+05|  6.3799e+06|  5.9844e+05|     -5387.2|   4.758e+06|        17|      0.24|\n    |    5.93e+05|  6.3783e+06|  5.9839e+05|     -5386.6|  4.7574e+06|        17|      0.25|\n    |  5.9301e+05|  6.3778e+06|   5.984e+05|     -5386.1|  4.7625e+06|        17|      0.25|\n    |  5.9304e+05|  6.3788e+06|  5.9843e+05|     -5386.5|  4.7581e+06|        17|      0.25|\n    |  5.9306e+05|   6.379e+06|  5.9845e+05|     -5386.6|  4.7608e+06|        17|      0.24|\n    |    5.93e+05|  6.3778e+06|  5.9839e+05|     -5386.6|  4.7568e+06|        17|      0.25|\n    |  5.9309e+05|  6.3801e+06|  5.9848e+05|     -5386.6|  4.7593e+06|        17|      0.24|\n    |    5.93e+05|  6.3781e+06|  5.9838e+05|     -5386.6|  4.7551e+06|        17|      0.24|\n    |  5.9293e+05|  6.3759e+06|  5.9831e+05|     -5386.1|  4.7565e+06|        17|      0.24|\n    |  5.9323e+05|  6.3932e+06|  5.9861e+05|     -5384.9|   4.771e+06|        17|      0.24|\n    |  5.9314e+05|  6.3804e+06|  5.9853e+05|     -5386.1|   4.759e+06|        17|      0.26|\n    |  5.9287e+05|  6.3744e+06|  5.9826e+05|     -5386.1|   4.759e+06|        17|      0.24|\n    |  5.9293e+05|  6.3753e+06|  5.9831e+05|     -5386.1|  4.7584e+06|        17|      0.26|\n    |  5.9295e+05|  6.3758e+06|  5.9833e+05|     -5386.1|  4.7563e+06|        17|      0.27|\n    |  5.9304e+05|  6.3787e+06|  5.9843e+05|     -5386.1|  4.7573e+06|        17|      0.25|\n    Optimization result:\n          fun: 593039.7334368741\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 6.37461123e+02,  1.79991775e+02,  6.58486507e+01,  1.45982531e+02,\n            1.36677101e+04,  2.88421932e+02,  0.00000000e+00, -5.15259810e+01,\n            1.47551553e+02, -3.93697010e+02,  0.00000000e+00,  5.18491461e+01,\n            2.62874591e+01, -2.08222394e+02,  1.76069699e+04,  1.27766156e+01,\n            1.66729270e+03,  1.96626567e+02,  3.03741233e+03, -8.69992034e+00,\n            2.69374891e+02,  9.77041481e+01,  0.00000000e+00, -2.93791800e+02,\n            2.26057692e+02])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 28\n          nit: 17\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -0.97324541,  1.45151   , -2.30258509,\n           -4.60517019, -0.13556738, -3.11773678, -2.30258509,  2.28598906,\n           -2.8828432 , -4.60517019, -2.30258509,  1.70224181, -2.30258509,\n            0.43033363, -2.30258509,  1.03651392, -2.30258509, -1.39825531,\n           -2.30258509, -4.60517019, -2.2597736 , -1.72504057, -2.30258509])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7f3c632f97d0>\n\n\n\n\n```\nmu = gpr7.predict(train.graphs)\nplt.scatter(train[target], mu)\nplt.show()\n\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n\n```\nmu_test = gpr7.predict(test.graphs)\nplt.scatter(test[target], mu_test)\nplt.show()\n\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n\n```\ngpr7.kernel.hyperparameters\n```\n\n\n\n\n    starting_probability : Uniform\n    \tp : 1.0\n    stopping_probability : 0.00010000000000000009\n    node_kernel : Composite\n    \taromatic : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.010057176739150398\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.16282625175478144\n    \tatomic_number : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 4.300149917736712\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tcharge : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.010000000000000004\n    \t\trhs : SquareExponential\n    \t\t\tlength_scale : 1.0\n    \tchiral : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.03561587634496983\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \thcount : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 9.999998413441604\n    \t\trhs : SquareExponential\n    \t\t\tlength_scale : 0.07667118856078592\n    \thybridization : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.01678502695038049\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.130398335790256\n    \tring_list : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 5.517965088466417\n    \t\trhs : Convolution\n    \t\t\tbase : KroneckerDelta\n    \t\t\t\th : 0.10000000000000002\n    edge_kernel : Composite\n    \taromatic : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 1.241291100822831\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tconjugated : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 2.2413377174986335\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \torder : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.19621718051439327\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tring_stereo : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.015312814053543773\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.8\n    \tstereo : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.1776628652028348\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n\n\n\n### Model 8\n\n\n```\ngpr8 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(1, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # turn constant from 0.5 to 1\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-4, \n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr8.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  2.9792e+06|  2.4642e+07|  2.9865e+06|     -7343.8|  8.7118e+06|        23|      0.24|\n    |  2.0165e+06|  2.1362e+07|  2.0233e+06|     -6795.2|   8.062e+06|        21|      0.24|\n    |  1.2966e+06|  1.5902e+07|  1.3028e+06|     -6253.9|   7.068e+06|        20|      0.22|\n    |  1.0075e+06|   1.235e+07|  1.0135e+06|     -5971.1|  6.4058e+06|        19|      0.23|\n    |  8.2429e+05|  9.6934e+06|  8.3004e+05|     -5752.5|  5.8067e+06|        18|      0.23|\n    |  7.1088e+05|  8.0676e+06|  7.1646e+05|     -5586.2|  5.3556e+06|        18|      0.22|\n    |  6.4954e+05|  7.0881e+06|  6.5503e+05|     -5489.7|  5.0295e+06|        17|      0.23|\n    |  6.2388e+05|  6.9272e+06|  6.2931e+05|     -5427.9|   4.937e+06|        18|      0.24|\n    |  6.0965e+05|  6.6369e+06|  6.1507e+05|     -5412.2|  4.8418e+06|        17|      0.23|\n    |  6.0452e+05|   6.522e+06|  6.0993e+05|     -5406.2|  4.7899e+06|        17|      0.24|\n    |  6.0197e+05|  6.5091e+06|  6.0737e+05|     -5398.9|  4.7888e+06|        17|      0.22|\n    |  6.0036e+05|  6.5038e+06|  6.0575e+05|     -5394.2|  4.7893e+06|        17|      0.22|\n    |  5.9951e+05|   6.489e+06|   6.049e+05|       -5393|  4.7822e+06|        17|      0.23|\n    |  5.9656e+05|  6.4171e+06|  6.0195e+05|     -5389.2|  4.7641e+06|        17|      0.22|\n    |  5.9566e+05|  6.4098e+06|  6.0105e+05|       -5388|  4.7507e+06|        17|      0.23|\n    |  5.9511e+05|  6.4048e+06|   6.005e+05|     -5386.8|  4.7432e+06|        17|      0.25|\n    |  5.9481e+05|  6.4085e+06|   6.002e+05|     -5386.4|  4.7446e+06|        17|      0.23|\n    |  5.9412e+05|  6.4236e+06|   5.995e+05|     -5386.1|   4.749e+06|        17|      0.23|\n    |  5.9368e+05|  6.4259e+06|  5.9906e+05|     -5386.6|  4.7559e+06|        17|      0.23|\n    |  5.9331e+05|  6.4114e+06|  5.9869e+05|     -5386.5|  4.7604e+06|        17|      0.23|\n    |  5.9309e+05|  6.3915e+06|  5.9848e+05|     -5386.4|  4.7593e+06|        17|      0.23|\n    |   5.931e+05|  6.3863e+06|  5.9848e+05|     -5386.4|  4.7615e+06|        17|      0.23|\n    |   5.931e+05|  6.3906e+06|  5.9849e+05|     -5386.4|  4.7627e+06|        17|      0.23|\n    |  5.9306e+05|  6.3906e+06|  5.9845e+05|     -5386.4|  4.7601e+06|        17|      0.23|\n    |  5.9312e+05|  6.3917e+06|  5.9851e+05|     -5386.4|  4.7631e+06|        17|      0.23|\n    |  5.9305e+05|  6.3899e+06|  5.9844e+05|     -5386.4|  4.7595e+06|        17|      0.23|\n    |  5.9299e+05|  6.3818e+06|  5.9838e+05|     -5386.4|   4.764e+06|        17|      0.23|\n    |   5.931e+05|  6.3845e+06|  5.9849e+05|     -5386.4|   4.761e+06|        17|      0.23|\n    |  5.9308e+05|  6.3833e+06|  5.9847e+05|     -5386.4|   4.762e+06|        17|      0.23|\n    |  5.9309e+05|   6.384e+06|  5.9848e+05|     -5386.4|  4.7607e+06|        17|      0.24|\n    |  5.9312e+05|  6.3844e+06|   5.985e+05|     -5386.4|  4.7638e+06|        17|      0.24|\n    |  5.9305e+05|  6.3833e+06|  5.9843e+05|     -5386.4|  4.7632e+06|        17|      0.24|\n    |  5.9311e+05|  6.3844e+06|   5.985e+05|     -5386.4|   4.763e+06|        17|      0.24|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |   4.309e+06|  2.4382e+07|  4.3169e+06|     -7932.7|  9.2553e+06|        21|      0.23|\n    |  2.6362e+06|  2.3231e+07|  2.6434e+06|     -7166.7|  8.6035e+06|        20|      0.23|\n    |  1.4002e+06|  1.5158e+07|  1.4066e+06|     -6364.5|  7.1794e+06|        18|      0.22|\n    |  1.1499e+06|  1.2877e+07|   1.156e+06|     -6131.7|  6.7376e+06|        18|      0.24|\n    |  9.8645e+05|  1.1302e+07|  9.9241e+05|     -5956.4|  6.3329e+06|        18|      0.22|\n    |  8.2914e+05|  9.6694e+06|   8.349e+05|     -5759.6|  5.8519e+06|        18|      0.22|\n    |  7.2729e+05|  8.3779e+06|   7.329e+05|     -5612.5|  5.4668e+06|        18|      0.25|\n    |  6.5245e+05|  7.2326e+06|  6.5795e+05|     -5494.9|  5.0812e+06|        17|      0.24|\n    |  6.3709e+05|  7.1964e+06|  6.4253e+05|     -5446.6|  5.0356e+06|        18|      0.23|\n    |  6.1616e+05|   6.786e+06|  6.2159e+05|     -5425.7|  4.8997e+06|        17|      0.23|\n    |  6.1221e+05|  6.6896e+06|  6.1763e+05|     -5421.9|  4.8536e+06|        17|      0.24|\n    |  6.0702e+05|  6.5885e+06|  6.1243e+05|     -5414.2|  4.8025e+06|        17|      0.24|\n    |  6.0011e+05|  6.4941e+06|  6.0551e+05|     -5400.7|  4.7635e+06|        17|      0.22|\n    |  6.1826e+05|  6.8509e+06|  6.2368e+05|     -5414.4|  4.9133e+06|        18|      0.24|\n    |   5.982e+05|  6.4893e+06|  6.0359e+05|     -5394.7|  4.7798e+06|        17|      0.22|\n    |  5.9719e+05|  6.4696e+06|  6.0258e+05|       -5392|  4.7839e+06|        17|      0.23|\n    |  5.9674e+05|  6.4529e+06|  6.0213e+05|       -5391|  4.7862e+06|        17|      0.23|\n    |   5.958e+05|  6.4186e+06|  6.0119e+05|     -5389.5|  4.7882e+06|        17|      0.22|\n    |  5.9491e+05|  6.3949e+06|   6.003e+05|     -5388.1|  4.7813e+06|        17|      0.24|\n    |   5.945e+05|  6.3957e+06|  5.9989e+05|     -5388.1|  4.7701e+06|        17|      0.24|\n    |  5.9404e+05|  6.3999e+06|  5.9942e+05|     -5388.3|   4.762e+06|        17|      0.22|\n    |    5.94e+05|  6.4039e+06|  5.9939e+05|       -5388|   4.759e+06|        17|      0.23|\n    |  5.9386e+05|   6.416e+06|  5.9925e+05|       -5387|  4.7546e+06|        17|      0.24|\n    |  5.9366e+05|   6.418e+06|  5.9904e+05|     -5386.3|  4.7575e+06|        17|      0.24|\n    |  5.9327e+05|  6.4066e+06|  5.9865e+05|     -5385.8|  4.7593e+06|        17|      0.24|\n    |   5.931e+05|  6.3953e+06|  5.9848e+05|     -5386.1|  4.7563e+06|        17|      0.25|\n    |  5.9312e+05|  6.3845e+06|  5.9851e+05|     -5386.3|  4.7561e+06|        17|      0.24|\n    |  5.9314e+05|  6.3939e+06|  5.9852e+05|     -5386.1|   4.756e+06|        17|      0.23|\n    |  5.9312e+05|  6.3951e+06|   5.985e+05|     -5386.1|  4.7564e+06|        17|      0.23|\n    |  5.9331e+05|  6.3997e+06|  5.9869e+05|     -5386.1|  4.7546e+06|        17|      0.24|\n    |  5.9307e+05|  6.3946e+06|  5.9846e+05|     -5386.1|  4.7538e+06|        17|      0.23|\n    |   5.932e+05|  6.3977e+06|  5.9859e+05|     -5386.1|  4.7557e+06|        17|      0.23|\n    |  5.9311e+05|  6.3964e+06|   5.985e+05|     -5386.1|   4.753e+06|        17|      0.24|\n    |  5.9316e+05|  6.3968e+06|  5.9855e+05|     -5386.1|  4.7558e+06|        17|      0.23|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  2.3642e+06|   2.501e+07|  2.3713e+06|       -7035|  8.3857e+06|        22|      0.23|\n    |  1.5682e+06|  1.7112e+07|  1.5747e+06|       -6501|  7.4975e+06|        19|      0.23|\n    |  1.1254e+06|  1.2855e+07|  1.1315e+06|     -6110.8|   6.677e+06|        18|      0.23|\n    |   8.935e+05|  1.0626e+07|  8.9935e+05|     -5848.7|  6.0755e+06|        18|      0.23|\n    |  7.5389e+05|  9.1315e+06|  7.5954e+05|     -5651.6|   5.586e+06|        18|      0.23|\n    |  6.7538e+05|  7.6365e+06|  6.8092e+05|     -5536.1|  5.2056e+06|        17|      0.23|\n    |  6.3294e+05|  7.1193e+06|  6.3839e+05|     -5450.1|  5.0192e+06|        18|      0.24|\n    |  6.1522e+05|  6.7919e+06|  6.2065e+05|       -5427|  4.8927e+06|        17|      0.23|\n    |  6.0924e+05|  6.6947e+06|  6.1466e+05|     -5416.4|  4.8448e+06|        17|      0.23|\n    |  6.0118e+05|  6.5408e+06|  6.0658e+05|       -5400|  4.8099e+06|        17|      0.23|\n    |  6.0716e+05|   6.635e+06|  6.1257e+05|     -5407.4|  4.7901e+06|        17|      0.22|\n    |  5.9975e+05|  6.5325e+06|  6.0515e+05|     -5396.6|  4.7937e+06|        17|      0.23|\n    |  5.9739e+05|  6.4591e+06|  6.0278e+05|       -5392|  4.7831e+06|        17|      0.23|\n    |  5.9604e+05|  6.4368e+06|  6.0143e+05|     -5389.8|  4.7677e+06|        17|      0.23|\n    |  5.9509e+05|  6.4251e+06|  6.0048e+05|     -5387.9|  4.7487e+06|        17|      0.23|\n    |  5.9496e+05|  6.4322e+06|  6.0035e+05|       -5387|  4.7497e+06|        17|      0.22|\n    |   5.946e+05|  6.4308e+06|  5.9999e+05|     -5386.4|  4.7475e+06|        17|      0.23|\n    |  5.9469e+05|  6.4301e+06|  6.0008e+05|     -5386.4|   4.749e+06|        17|      0.23|\n    |  5.9465e+05|  6.4316e+06|  6.0003e+05|     -5386.4|  4.7503e+06|        17|      0.22|\n    |  5.9485e+05|   6.437e+06|  6.0023e+05|     -5386.4|   4.747e+06|        17|      0.23|\n    |  5.9463e+05|  6.4313e+06|  6.0002e+05|     -5386.4|  4.7496e+06|        17|      0.23|\n    |   5.947e+05|  6.4334e+06|  6.0009e+05|     -5386.4|   4.752e+06|        17|      0.23|\n    |  5.9469e+05|  6.4329e+06|  6.0008e+05|     -5386.4|    4.75e+06|        17|      0.23|\n    |  5.9467e+05|  6.4322e+06|  6.0005e+05|     -5386.4|  4.7498e+06|        17|      0.23|\n    Optimization result:\n          fun: 593114.6707814854\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 6.38026776e+02,  1.38782578e+02,  2.66323472e+01,  5.85716583e+02,\n            1.37186070e+04,  2.83861741e+02,  0.00000000e+00, -9.25955378e+01,\n            1.05547529e+02, -4.67581389e+02,  9.92854118e-20,  8.58522091e+01,\n            4.96435846e+01, -5.32965096e+02,  1.75859453e+04,  8.09606265e+01,\n            1.65723821e+03, -3.93953283e+02,  3.01124941e+03, -4.40932945e+01,\n            2.59823969e+02,  1.80457401e+02,  0.00000000e+00,  1.77125402e+02,\n            2.44995429e+02])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 33\n          nit: 23\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -1.86387197,  1.47468801, -2.30258509,\n           -4.60517019,  0.        , -3.49988681, -2.30258509,  2.30258509,\n           -2.40163276, -4.22043617, -2.03747843,  1.71483415, -2.30258509,\n            0.18487075, -2.30258509,  0.76191496, -2.30258509, -1.69254866,\n           -2.30258509, -4.23517368, -0.22314355, -1.65492569, -2.30258509])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7fd805d61c90>\n\n\n\n\n```\nmu = gpr8.predict(train.graphs)\nplt.scatter(train[target], mu)\nplt.show()\n\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n\n```\nmu_test = gpr8.predict(test.graphs)\nplt.scatter(test[target], mu_test)\nplt.show()\n\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n### Model 9\n\n\n```\ngpr9 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(2, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # turn constant from 0.5 to 1\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-4, \n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr9.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  3.1842e+06|  2.4974e+07|  3.1916e+06|     -7444.7|  8.7312e+06|        23|      0.26|\n    |  2.1752e+06|  2.2644e+07|  2.1821e+06|     -6894.5|  8.1462e+06|        21|      0.23|\n    |  1.2857e+06|  1.6274e+07|   1.292e+06|     -6243.6|  7.0034e+06|        20|      0.23|\n    |   1.004e+06|  1.2582e+07|    1.01e+06|     -5967.8|  6.3551e+06|        19|      0.25|\n    |  8.2416e+05|  9.8792e+06|  8.2991e+05|     -5754.1|  5.7767e+06|        18|      0.27|\n    |  7.1531e+05|  8.2743e+06|   7.209e+05|     -5594.7|  5.3493e+06|        18|      0.24|\n    |  6.5715e+05|  7.2687e+06|  6.6266e+05|     -5505.9|  5.0409e+06|        17|      0.24|\n    |  6.2418e+05|  6.9524e+06|  6.2962e+05|     -5436.7|  4.9381e+06|        18|      0.23|\n    |  6.1435e+05|  6.7657e+06|  6.1977e+05|     -5424.1|  4.8623e+06|        17|      0.24|\n    |  6.0457e+05|  6.6082e+06|  6.0998e+05|     -5406.7|    4.82e+06|        17|      0.24|\n    |  6.0409e+05|  6.4935e+06|  6.0949e+05|     -5401.4|  4.8533e+06|        17|      0.23|\n    |  6.0069e+05|  6.5041e+06|  6.0608e+05|     -5398.7|  4.8222e+06|        17|      0.24|\n    |  5.9986e+05|  6.4187e+06|  6.0526e+05|     -5395.8|   4.829e+06|        17|      0.23|\n    |  5.9771e+05|  6.4231e+06|   6.031e+05|     -5392.8|  4.8077e+06|        17|      0.26|\n    |  5.9675e+05|  6.4345e+06|  6.0214e+05|     -5391.7|  4.7932e+06|        17|      0.24|\n    |  5.9549e+05|  6.4231e+06|  6.0088e+05|     -5390.3|  4.7744e+06|        17|      0.24|\n    |  5.9438e+05|  6.4046e+06|  5.9976e+05|       -5388|  4.7547e+06|        17|      0.23|\n    |  5.9435e+05|  6.4109e+06|  5.9973e+05|     -5386.6|  4.7645e+06|        17|      0.24|\n    |  5.9419e+05|  6.4008e+06|  5.9958e+05|     -5386.9|    4.76e+06|        17|      0.24|\n    |  5.9416e+05|  6.3952e+06|  5.9954e+05|     -5387.1|  4.7616e+06|        17|      0.24|\n    |  5.9405e+05|  6.3847e+06|  5.9944e+05|     -5387.4|  4.7563e+06|        17|      0.25|\n    |  5.9384e+05|  6.3816e+06|  5.9923e+05|     -5387.2|  4.7571e+06|        17|      0.22|\n    |   5.937e+05|  6.3784e+06|  5.9908e+05|     -5387.2|  4.7548e+06|        17|      0.23|\n    |  5.9367e+05|  6.3925e+06|  5.9905e+05|     -5385.9|  4.7599e+06|        17|      0.23|\n    |  5.9358e+05|   6.394e+06|  5.9897e+05|     -5385.9|  4.7639e+06|        17|      0.23|\n    |  5.9338e+05|  6.3976e+06|  5.9877e+05|     -5386.2|  4.7562e+06|        17|      0.24|\n    |  5.9321e+05|  6.3888e+06|   5.986e+05|     -5386.4|   4.755e+06|        17|      0.23|\n    |  5.9333e+05|  6.3871e+06|  5.9871e+05|     -5386.5|  4.7591e+06|        17|      0.23|\n    |  5.9327e+05|  6.3903e+06|  5.9866e+05|     -5386.4|  4.7544e+06|        17|      0.24|\n    |  5.9316e+05|  6.3877e+06|  5.9855e+05|     -5386.4|   4.755e+06|        17|      0.24|\n    |  5.9334e+05|  6.3918e+06|  5.9872e+05|     -5386.4|  4.7592e+06|        17|      0.25|\n    |  5.9326e+05|    6.39e+06|  5.9864e+05|     -5386.4|  4.7561e+06|        17|      0.23|\n    |  5.9324e+05|  6.3898e+06|  5.9863e+05|     -5386.4|   4.758e+06|        17|      0.24|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  2.2799e+06|  3.0057e+07|  2.2869e+06|     -6934.8|  7.8008e+06|        24|      0.25|\n    |   1.767e+06|  2.5126e+07|  1.7736e+06|     -6594.3|  7.4479e+06|        23|      0.23|\n    |  1.0278e+06|  1.4821e+07|  1.0337e+06|     -5972.7|  6.4094e+06|        21|      0.23|\n    |  8.6501e+05|  1.1644e+07|  8.7081e+05|     -5794.8|  5.9663e+06|        20|      0.23|\n    |  7.1706e+05|  8.4268e+06|  7.2267e+05|     -5604.3|  5.3554e+06|        18|      0.23|\n    |  6.5162e+05|  7.4137e+06|  6.5712e+05|       -5493|   5.062e+06|        18|      0.23|\n    |  6.2958e+05|  6.9704e+06|  6.3504e+05|       -5458|  4.9042e+06|        17|      0.23|\n    |  6.1225e+05|  6.7455e+06|  6.1768e+05|     -5423.5|  4.8323e+06|        17|      0.23|\n    |  6.0632e+05|  6.6482e+06|  6.1173e+05|       -5411|  4.8372e+06|        17|      0.24|\n    |  6.0233e+05|  6.5526e+06|  6.0773e+05|     -5401.8|  4.8469e+06|        17|      0.23|\n    |  6.0022e+05|  6.4934e+06|  6.0562e+05|     -5397.6|  4.8374e+06|        17|      0.23|\n    |  5.9676e+05|  6.4223e+06|  6.0215e+05|     -5392.6|  4.7962e+06|        17|      0.23|\n    |  5.9504e+05|  6.4098e+06|  6.0043e+05|     -5390.5|  4.7672e+06|        17|      0.24|\n    |   5.947e+05|  6.4114e+06|  6.0009e+05|     -5389.3|  4.7581e+06|        17|      0.23|\n    |  5.9442e+05|  6.4108e+06|   5.998e+05|       -5388|  4.7564e+06|        17|      0.23|\n    |  5.9429e+05|  6.4096e+06|  5.9968e+05|     -5387.3|   4.761e+06|        17|      0.22|\n    |  5.9433e+05|  6.4087e+06|  5.9971e+05|     -5386.8|  4.7608e+06|        17|      0.23|\n    |  5.9434e+05|  6.4102e+06|  5.9972e+05|     -5387.2|  4.7592e+06|        17|      0.22|\n    |  5.9433e+05|  6.4107e+06|  5.9972e+05|     -5387.2|  4.7576e+06|        17|      0.23|\n    |  5.9428e+05|  6.4092e+06|  5.9967e+05|     -5387.2|    4.76e+06|        17|      0.23|\n    |  5.9426e+05|  6.4082e+06|  5.9964e+05|     -5387.2|  4.7593e+06|        17|      0.23|\n    |  5.9438e+05|  6.4119e+06|  5.9977e+05|     -5387.2|  4.7574e+06|        17|      0.23|\n    |  5.9431e+05|  6.4094e+06|   5.997e+05|     -5387.2|  4.7595e+06|        17|      0.23|\n    |  5.9437e+05|   6.411e+06|  5.9976e+05|     -5387.2|  4.7598e+06|        17|      0.25|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  5.6004e+06|  1.0925e+07|  5.6088e+06|     -8411.3|  9.6646e+06|        18|      0.23|\n    |  4.3616e+06|  1.7555e+07|  4.3696e+06|     -7948.7|  9.3139e+06|        19|      0.23|\n    |    1.55e+06|  1.8485e+07|  1.5564e+06|     -6436.8|  7.3811e+06|        21|      0.22|\n    |  1.1849e+06|  1.5675e+07|  1.1911e+06|     -6123.9|  6.7454e+06|        21|      0.22|\n    |  8.8035e+05|  1.0785e+07|  8.8616e+05|     -5807.1|  5.9897e+06|        19|      0.23|\n    |  7.5061e+05|  8.6012e+06|  7.5626e+05|     -5645.9|  5.5033e+06|        18|      0.23|\n    |  6.7138e+05|  7.5125e+06|   6.769e+05|     -5523.2|  5.1857e+06|        18|      0.23|\n    |  6.2543e+05|  6.8949e+06|  6.3087e+05|       -5443|  4.9251e+06|        17|      0.23|\n    |  6.1475e+05|  6.7354e+06|  6.2018e+05|     -5424.2|  4.8917e+06|        17|      0.23|\n    |  6.1085e+05|   6.669e+06|  6.1626e+05|       -5417|  4.8771e+06|        17|      0.23|\n    |  6.0117e+05|  6.4774e+06|  6.0657e+05|     -5400.5|  4.8228e+06|        17|      0.23|\n    |  5.9729e+05|  6.4244e+06|  6.0268e+05|     -5391.3|  4.8081e+06|        17|      0.23|\n    |   5.961e+05|  6.3908e+06|  6.0149e+05|     -5390.5|   4.788e+06|        17|      0.23|\n    |  5.9524e+05|  6.3716e+06|  6.0063e+05|     -5389.3|  4.7759e+06|        17|      0.23|\n    |  5.9457e+05|  6.3724e+06|  5.9996e+05|     -5388.4|  4.7729e+06|        17|      0.23|\n    |  5.9374e+05|  6.3917e+06|  5.9913e+05|     -5387.1|  4.7595e+06|        17|      0.24|\n    |  5.9348e+05|  6.3895e+06|  5.9886e+05|     -5386.8|  4.7578e+06|        17|      0.23|\n    |  5.9413e+05|  6.4288e+06|  5.9951e+05|     -5384.8|  4.7726e+06|        17|      0.25|\n    |  5.9355e+05|  6.3967e+06|  5.9894e+05|     -5386.3|  4.7583e+06|        17|      0.23|\n    |   5.935e+05|  6.3912e+06|  5.9888e+05|     -5386.8|  4.7567e+06|        17|      0.24|\n    |  5.9363e+05|  6.3931e+06|  5.9901e+05|     -5386.8|  4.7552e+06|        17|      0.23|\n    |  5.9352e+05|    6.39e+06|  5.9891e+05|     -5386.8|   4.759e+06|        17|      0.25|\n    |  5.9355e+05|  6.3912e+06|  5.9894e+05|     -5386.8|  4.7567e+06|        17|      0.23|\n    |  5.9355e+05|   6.391e+06|  5.9893e+05|     -5386.8|  4.7581e+06|        17|      0.23|\n    |   5.936e+05|  6.3923e+06|  5.9898e+05|     -5386.8|  4.7583e+06|        17|      0.25|\n    Optimization result:\n          fun: 593239.0731028724\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 6.38571528e+02,  2.53446370e+02,  4.04348138e+01, -8.86199826e+02,\n            1.36287493e+04,  2.83281629e+02,  0.00000000e+00, -8.03270149e+01,\n            1.29925146e+02, -6.68353601e+02,  3.81951546e-03,  1.11964525e+02,\n            7.10964508e+01,  1.00805620e+03,  1.76320909e+04, -2.85119588e+02,\n            1.68133082e+03,  4.70354709e+02,  3.02838241e+03, -2.14150548e+02,\n            2.70225253e+02,  2.26206868e+02,  0.00000000e+00, -1.99055415e+02,\n            2.32813791e+02])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 33\n          nit: 25\n       status: 0\n      success: True\n            x: array([-9.21034037, -3.95840051, -2.09284424,  1.4582562 , -2.30258509,\n           -4.60517019,  0.        , -3.49372658, -2.1095149 ,  2.30258509,\n           -1.88596738, -4.12293699, -1.77144806,  1.72893419, -2.30258509,\n           -0.42084637, -2.30258509,  0.20339185, -2.30258509, -2.32277083,\n           -2.30258509, -4.60517019, -0.22314355, -2.47885086, -2.30258509])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7fd803aefdd0>\n\n\n\n\n```\nmu = gpr9.predict(train.graphs)\nplt.scatter(train[target], mu)\nplt.show()\n\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n\n```\nmu_test = gpr9.predict(test.graphs)\nplt.scatter(test[target], mu_test)\nplt.show()\n\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n### Model 10\n\n\n```\ngpr10 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.1, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # turn constant from 0.5 to 0.1\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-4, \n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr10.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  2.7983e+06|    2.43e+07|  2.8056e+06|     -7255.5|  8.7152e+06|        23|      0.24|\n    |   1.862e+06|  2.0153e+07|  1.8687e+06|     -6699.9|  7.9833e+06|        20|      0.24|\n    |  1.2811e+06|  1.5513e+07|  1.2873e+06|     -6247.6|  7.0832e+06|        20|      0.24|\n    |  1.0015e+06|  1.2225e+07|  1.0075e+06|     -5970.3|  6.4109e+06|        19|      0.24|\n    |  8.2607e+05|   9.751e+06|  8.3183e+05|     -5757.8|  5.8362e+06|        18|      0.24|\n    |  7.1314e+05|  8.1066e+06|  7.1873e+05|     -5592.2|   5.376e+06|        18|      0.23|\n    |  6.4927e+05|  7.1354e+06|  6.5476e+05|     -5488.9|  5.0514e+06|        17|      0.23|\n    |  6.3134e+05|  7.0681e+06|  6.3678e+05|     -5438.9|  4.9652e+06|        18|      0.23|\n    |  6.1006e+05|  6.6411e+06|  6.1548e+05|     -5414.6|  4.8456e+06|        17|      0.23|\n    |  6.0572e+05|   6.545e+06|  6.1113e+05|     -5408.6|  4.8049e+06|        17|      0.23|\n    |  6.0297e+05|  6.5038e+06|  6.0838e+05|     -5403.2|  4.7879e+06|        17|      0.24|\n    |  6.0504e+05|   6.654e+06|  6.1044e+05|     -5394.8|  4.8153e+06|        18|      0.23|\n    |   6.002e+05|  6.5188e+06|   6.056e+05|       -5394|  4.7876e+06|        17|      0.23|\n    |  6.0038e+05|  6.5403e+06|  6.0577e+05|     -5389.6|  4.8007e+06|        17|      0.23|\n    |   5.998e+05|  6.5228e+06|  6.0519e+05|     -5391.3|  4.7927e+06|        17|      0.23|\n    |  5.9818e+05|  6.4716e+06|  6.0357e+05|     -5390.5|  4.7747e+06|        17|      0.22|\n    |  5.9784e+05|  6.4565e+06|  6.0323e+05|     -5390.9|  4.7662e+06|        17|      0.22|\n    |    5.97e+05|  6.4279e+06|  6.0239e+05|     -5390.7|   4.759e+06|        17|      0.23|\n    |  5.9602e+05|  6.4208e+06|  6.0141e+05|     -5387.9|  4.7561e+06|        17|      0.24|\n    |  5.9532e+05|  6.4184e+06|  6.0071e+05|     -5386.5|  4.7421e+06|        17|      0.22|\n    |  5.9503e+05|  6.4111e+06|  6.0041e+05|     -5386.4|  4.7408e+06|        17|      0.24|\n    |  5.9491e+05|   6.408e+06|  6.0029e+05|     -5386.4|  4.7431e+06|        17|      0.23|\n    |  5.9463e+05|   6.401e+06|  6.0002e+05|     -5386.2|  4.7443e+06|        17|      0.22|\n    |  6.0593e+05|  6.5034e+06|  6.1134e+05|     -5408.5|  4.9074e+06|        17|      0.23|\n    |  5.9396e+05|  6.3846e+06|  5.9935e+05|     -5386.5|  4.7594e+06|        17|      0.24|\n    |  5.9382e+05|  6.3835e+06|  5.9921e+05|     -5387.7|  4.7774e+06|        17|      0.22|\n    |  5.9376e+05|   6.384e+06|  5.9915e+05|     -5386.8|  4.7694e+06|        17|      0.24|\n    |  5.9354e+05|  6.3993e+06|  5.9893e+05|     -5385.7|  4.7783e+06|        17|      0.24|\n    |   5.931e+05|  6.3874e+06|  5.9849e+05|       -5386|   4.769e+06|        17|      0.23|\n    |  5.9321e+05|  6.3905e+06|  5.9859e+05|     -5386.5|  4.7589e+06|        17|      0.23|\n    |  5.9325e+05|  6.3911e+06|  5.9864e+05|     -5386.1|  4.7673e+06|        17|      0.23|\n    |  5.9325e+05|  6.3915e+06|  5.9864e+05|     -5386.1|  4.7655e+06|        17|      0.24|\n    |  5.9323e+05|  6.3903e+06|  5.9861e+05|       -5386|  4.7667e+06|        17|      0.26|\n    |  5.9321e+05|    6.39e+06|   5.986e+05|       -5386|  4.7658e+06|        17|      0.23|\n    |  5.9322e+05|  6.3903e+06|   5.986e+05|       -5386|  4.7665e+06|        17|      0.23|\n    |  5.9323e+05|  6.3905e+06|  5.9862e+05|       -5386|  4.7647e+06|        17|      0.24|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |   3.335e+06|  2.0676e+07|  3.3425e+06|     -7511.6|  8.8641e+06|        20|      0.23|\n    |  2.1616e+06|  1.8613e+07|  2.1684e+06|     -6871.7|  8.1374e+06|        20|      0.27|\n    |  1.0552e+06|  1.1657e+07|  1.0612e+06|     -5984.8|  6.4878e+06|        19|      0.24|\n    |  8.3583e+05|  9.3921e+06|  8.4159e+05|     -5752.2|  5.8752e+06|        18|      0.23|\n    |  7.4374e+05|  8.1282e+06|  7.4937e+05|     -5635.8|  5.4636e+06|        17|      0.23|\n    |   6.817e+05|  7.3767e+06|  6.8724e+05|     -5541.2|  5.1875e+06|        17|      0.23|\n    |  6.3778e+05|  6.9335e+06|  6.4325e+05|     -5463.9|  5.0127e+06|        17|      0.23|\n    |   6.165e+05|  6.6822e+06|  6.2193e+05|     -5426.8|   4.878e+06|        17|      0.24|\n    |  6.1137e+05|  6.5342e+06|  6.1679e+05|     -5414.3|  4.8606e+06|        17|      0.25|\n    |  6.0039e+05|  6.4384e+06|  6.0579e+05|     -5398.2|  4.7915e+06|        17|      0.24|\n    |  5.9881e+05|  6.4292e+06|  6.0421e+05|       -5395|  4.7835e+06|        17|      0.24|\n    |  5.9769e+05|  6.4717e+06|  6.0308e+05|     -5388.4|  4.7946e+06|        17|      0.24|\n    |   5.968e+05|  6.4302e+06|  6.0219e+05|     -5389.3|  4.7826e+06|        17|      0.24|\n    |  5.9653e+05|  6.4185e+06|  6.0192e+05|     -5389.6|  4.7764e+06|        17|      0.23|\n    |  5.9628e+05|  6.4064e+06|  6.0167e+05|     -5389.7|  4.7681e+06|        17|      0.25|\n    |  5.9569e+05|   6.392e+06|  6.0108e+05|     -5389.3|  4.7644e+06|        17|      0.23|\n    |  5.9554e+05|  6.4306e+06|  6.0093e+05|     -5385.3|  4.7795e+06|        17|      0.25|\n    |  5.9461e+05|  6.4044e+06|  5.9999e+05|     -5385.7|  4.7627e+06|        17|      0.23|\n    |  5.9443e+05|  6.3917e+06|  5.9981e+05|     -5386.6|  4.7565e+06|        17|      0.23|\n    |  5.9439e+05|  6.3911e+06|  5.9977e+05|     -5386.6|  4.7529e+06|        17|      0.23|\n    |  5.9432e+05|  6.3888e+06|   5.997e+05|     -5386.6|  4.7545e+06|        17|      0.24|\n    |  5.9414e+05|  6.3821e+06|  5.9953e+05|     -5386.4|  4.7585e+06|        17|      0.23|\n    |  5.9408e+05|  6.3773e+06|  5.9946e+05|     -5386.4|  4.7613e+06|        17|      0.23|\n    |  5.9375e+05|  6.3821e+06|  5.9914e+05|     -5386.7|  4.7649e+06|        17|      0.23|\n    |  5.9345e+05|  6.3813e+06|  5.9883e+05|       -5387|  4.7631e+06|        17|      0.23|\n    |   5.934e+05|  6.3896e+06|  5.9879e+05|     -5386.8|   4.763e+06|        17|      0.23|\n    |  5.9344e+05|  6.3955e+06|  5.9882e+05|     -5386.7|  4.7616e+06|        17|      0.23|\n    |  5.9342e+05|  6.3913e+06|  5.9881e+05|     -5386.8|  4.7649e+06|        17|      0.25|\n    |  5.9326e+05|   6.387e+06|  5.9865e+05|     -5386.8|  4.7616e+06|        17|      0.23|\n    |  5.9337e+05|  6.3891e+06|  5.9876e+05|     -5386.8|  4.7671e+06|        17|      0.22|\n    |   5.933e+05|  6.3877e+06|  5.9869e+05|     -5386.8|  4.7628e+06|        17|      0.22|\n    |  5.9324e+05|  6.3942e+06|  5.9862e+05|     -5386.4|  4.7589e+06|        17|      0.24|\n    |  5.9328e+05|   6.388e+06|  5.9867e+05|     -5386.6|  4.7591e+06|        17|      0.25|\n    |  5.9325e+05|  6.3922e+06|  5.9864e+05|     -5386.4|  4.7598e+06|        17|      0.22|\n    |  5.9325e+05|  6.3937e+06|  5.9864e+05|     -5386.4|  4.7632e+06|        17|      0.24|\n    |  5.9335e+05|  6.3958e+06|  5.9874e+05|     -5386.4|  4.7595e+06|        17|      0.25|\n    |  5.9334e+05|  6.3953e+06|  5.9872e+05|     -5386.4|  4.7621e+06|        17|      0.26|\n    |  5.9338e+05|   6.397e+06|  5.9877e+05|     -5386.4|  4.7553e+06|        17|      0.25|\n    |  5.9335e+05|  6.3966e+06|  5.9874e+05|     -5386.4|  4.7606e+06|        17|      0.26|\n    |  5.9333e+05|   6.396e+06|  5.9871e+05|     -5386.4|  4.7579e+06|        17|      0.26|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  5.8553e+06|  6.1173e+06|  5.8637e+06|     -8489.1|   9.764e+06|        13|      0.24|\n    |  4.4775e+06|  1.0414e+07|  4.4854e+06|     -7964.5|  9.4041e+06|        14|      0.24|\n    |   1.499e+06|  1.2523e+07|  1.5054e+06|     -6394.8|  7.5362e+06|        17|      0.24|\n    |  1.0911e+06|  1.0407e+07|  1.0971e+06|     -6028.5|  6.7239e+06|        17|      0.26|\n    |  9.1382e+05|  9.0085e+06|  9.1966e+05|     -5833.1|  6.2209e+06|        17|      0.25|\n    |  7.8666e+05|  7.9393e+06|  7.9232e+05|     -5667.8|   5.793e+06|        17|      0.23|\n    |   7.137e+05|  7.2049e+06|  7.1927e+05|     -5561.2|  5.4904e+06|        17|      0.24|\n    |  6.7654e+05|  6.9513e+06|  6.8204e+05|     -5499.9|  5.3402e+06|        17|      0.24|\n    |  6.4054e+05|  6.5381e+06|  6.4599e+05|     -5455.9|  5.1118e+06|        17|      0.26|\n    |  6.5597e+05|  7.5432e+06|  6.6144e+05|       -5465|  4.9854e+06|        19|      0.26|\n    |  6.0894e+05|   6.557e+06|  6.1435e+05|     -5407.4|  4.9151e+06|        18|      0.24|\n    |  6.0177e+05|  6.5172e+06|  6.0717e+05|     -5402.3|  4.8031e+06|        17|      0.25|\n    |  6.0125e+05|  6.4801e+06|  6.0665e+05|       -5402|  4.8075e+06|        17|      0.26|\n    |  6.0082e+05|  6.4688e+06|  6.0622e+05|     -5400.4|  4.8117e+06|        17|      0.26|\n    |  6.0039e+05|  6.4622e+06|  6.0579e+05|     -5399.3|  4.8118e+06|        17|      0.24|\n    |   5.982e+05|  6.4268e+06|  6.0359e+05|     -5393.2|  4.8253e+06|        17|      0.26|\n    |  5.9754e+05|  6.4135e+06|  6.0294e+05|     -5392.8|  4.8149e+06|        17|      0.26|\n    |  5.9534e+05|  6.3715e+06|  6.0073e+05|     -5392.5|  4.7759e+06|        17|      0.25|\n    |  5.9496e+05|  6.3808e+06|  6.0036e+05|     -5391.6|  4.7699e+06|        17|      0.27|\n    |  5.9436e+05|  6.4056e+06|  5.9975e+05|       -5389|  4.7735e+06|        17|      0.25|\n    |  5.9392e+05|  6.4102e+06|  5.9931e+05|     -5387.2|  4.7705e+06|        17|      0.25|\n    |  5.9358e+05|  6.3991e+06|  5.9897e+05|       -5386|  4.7674e+06|        17|      0.24|\n    |   5.934e+05|  6.3882e+06|  5.9879e+05|     -5386.5|  4.7622e+06|        17|      0.24|\n    |  5.9342e+05|  6.3853e+06|   5.988e+05|     -5386.8|  4.7604e+06|        17|      0.25|\n    |  5.9348e+05|  6.3892e+06|  5.9887e+05|     -5386.5|  4.7637e+06|        17|      0.25|\n    |  5.9343e+05|  6.3882e+06|  5.9881e+05|     -5386.5|  4.7662e+06|        17|      0.26|\n    |  5.9353e+05|  6.3906e+06|  5.9892e+05|     -5386.5|   4.765e+06|        17|      0.26|\n    |   5.934e+05|  6.3875e+06|  5.9878e+05|     -5386.5|   4.763e+06|        17|      0.26|\n    |  5.9342e+05|   6.388e+06|  5.9881e+05|     -5386.5|  4.7621e+06|        17|      0.27|\n    |  5.9349e+05|  6.3898e+06|  5.9888e+05|     -5386.5|  4.7653e+06|        17|      0.25|\n    |  5.9347e+05|   6.389e+06|  5.9885e+05|     -5386.5|  4.7634e+06|        17|      0.26|\n    Optimization result:\n          fun: 593233.3042484035\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([  638.64736427,   141.96903073,    28.55629934,  1626.08930356,\n           13743.38807579,   280.18042823,     0.        ,   -99.97653253,\n             114.814054  , -2792.2638767 ,     0.        ,    91.58912464,\n              57.6192078 ,   776.34364075, 17553.00068355,   978.24342665,\n            1666.14615848, -1272.51341315,  2991.47521638,  -137.29971877,\n             252.38902263,   210.50993072,     0.        ,   218.8639886 ,\n             246.42026873])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 36\n          nit: 24\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -1.76491214,  1.49768933, -2.30258509,\n           -4.60517019,  0.        , -3.40193308, -2.30258509,  2.30258509,\n           -2.68288077, -4.06937858, -2.04385712,  1.73412843, -2.30258509,\n            0.26606458, -2.30258509,  0.73949084, -2.30258509, -1.82914477,\n           -2.23381959, -4.06338654, -0.22314355, -1.61434557, -2.30258509])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7fd802672090>\n\n\n\n\n```\nmu = gpr10.predict(train.graphs)\nplt.scatter(train[target], mu)\nplt.show()\n\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n\n```\nmu_test = gpr10.predict(test.graphs)\nplt.scatter(test[target], mu_test)\nplt.show()\n\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n\n```\ndef gpr_model(aro_c_n = 0.5, ato_c_n = 0.5, cha_c_n = 0.5, chi_c_n = 0.5, hco_c_n = 0.5, hyb_c_n = 0.5, ring_c_n = 0.5, \n              aro_c_e = 0.5, con_c_e = 0.5, ord_c_e = 0.5, ring_c_e = 0.5, ste_c_e = 0.5, alpha = 1e-4):\n  gpr = GaussianProcessRegressor(\n      kernel=Normalization(\n          MarginalizedGraphKernel(\n              node_kernel=uX.Additive(\n                  aromatic=uX.Constant(aro_c_n, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # turn constant from 0.5 to 1\n                  atomic_number=uX.Constant(ato_c_n, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                  charge=uX.Constant(cha_c_n, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                  chiral=uX.Constant(chi_c_n, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                  hcount=uX.Constant(hco_c_n, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                  hybridization=uX.Constant(hyb_c_n, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                  ring_list=uX.Constant(ring_c_n, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n              ).normalized,\n              edge_kernel=uX.Additive(\n                  aromatic=uX.Constant(aro_c_e, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                  conjugated=uX.Constant(con_c_e, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                  order=uX.Constant(ord_c_e, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                  ring_stereo=uX.Constant(ring_c_e, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                  stereo=uX.Constant(ste_c_e, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n              ).normalized,\n              p=Uniform(1.0, p_bounds='fixed'),\n              q=0.05\n          )\n      ),\n      alpha=alpha, \n      optimizer=True,\n      normalize_y=True,\n      regularization='+',\n    )\n    \n  return gpr,[aro_c_n,ato_c_n,cha_c_n,chi_c_n,hco_c_n,hyb_c_n,ring_c_n,aro_c_e,con_c_e,ord_c_e,ring_c_e,ste_c_e,alpha]\n```\n\n\n```\n# list out the investigated hyperparameters\n#aro_c_ns = [1, 5, 9] # 1  \nato_c_ns = [1, 5, 9] # 2\ncha_c_ns = [1, 5, 9] # 3\nchi_c_ns = [1, 5, 9] # 4\nhco_c_ns = [1, 5, 9] # 5\nhyb_c_ns = [1, 5, 9] # 6\nring_c_ns = [1, 5, 9] # 7\naro_c_es = [1, 5, 9] # 8\ncon_c_es = [1, 5, 9] # 9\nord_c_es = [1, 5, 9] # 10\nring_c_es = [1, 5, 9] # 11\nste_c_es = [1, 5, 9]\n#ste_c_es = np.linspace(1, 9, 9).tolist() # 12\n#alphas = [1, 1e-1, 1e-2, 1e-3, 1e-4, 1e-5] # 13\n```\n\n\n```\nexhaust_search_results = pd.DataFrame(columns=['aro_c_n','ato_c_n','cha_c_n','chi_c_n','hco_c_n',\\\n                      'hyb_c_n','ring_c_n','aro_c_e','con_c_e','ord_c_e','ring_c_e',\\\n                      'ste_c_e','alpha','RMSE_train', 'MAE_train', 'RMSE_test', 'MAE_test'])\nexhaust_search_results\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>aro_c_n</th>\n      <th>ato_c_n</th>\n      <th>cha_c_n</th>\n      <th>chi_c_n</th>\n      <th>hco_c_n</th>\n      <th>hyb_c_n</th>\n      <th>ring_c_n</th>\n      <th>aro_c_e</th>\n      <th>con_c_e</th>\n      <th>ord_c_e</th>\n      <th>ring_c_e</th>\n      <th>ste_c_e</th>\n      <th>alpha</th>\n      <th>RMSE_train</th>\n      <th>MAE_train</th>\n      <th>RMSE_test</th>\n      <th>MAE_test</th>\n    </tr>\n  </thead>\n  <tbody>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\nfor ato_c_n in ato_c_ns:\n  model,para_list = gpr_model(ato_c_n = ato_c_n)\n  model.fit(train.graphs, train[target], repeat=3, verbose=True)\n  mu = model.predict(train.graphs)\n  MAE_train = np.mean(np.abs(train[target] - mu))\n  RMSE_train = np.std(train[target] - mu)\n  para_list.append(RMSE_train)\n  para_list.append(MAE_train)\n  mu_test = model.predict(test.graphs)\n  MAE_test = np.mean(np.abs(test[target] - mu_test))\n  RMSE_test = np.std(test[target] - mu_test)\n  para_list.append(RMSE_test)\n  para_list.append(MAE_test)\n  data = pd.DataFrame(data = [para_list],\\\n            columns=['aro_c_n','ato_c_n','cha_c_n','chi_c_n','hco_c_n',\\\n            'hyb_c_n','ring_c_n','aro_c_e','con_c_e','ord_c_e','ring_c_e',\\\n            'ste_c_e','alpha','RMSE_train', 'MAE_train', 'RMSE_test', 'MAE_test'])\n  exhaust_search_results = exhaust_search_results.append(data,ignore_index=True)\n```\n\n\n```\nfor cha_c_n in cha_c_ns:\n  model,para_list = gpr_model(cha_c_n = cha_c_n)\n  model.fit(train.graphs, train[target], repeat=3, verbose=False)\n  mu = model.predict(train.graphs)\n  MAE_train = np.mean(np.abs(train[target] - mu))\n  RMSE_train = np.std(train[target] - mu)\n  para_list.append(RMSE_train)\n  para_list.append(MAE_train)\n  mu_test = model.predict(test.graphs)\n  MAE_test = np.mean(np.abs(test[target] - mu_test))\n  RMSE_test = np.std(test[target] - mu_test)\n  para_list.append(RMSE_test)\n  para_list.append(MAE_test)\n  data = pd.DataFrame(data = [para_list],\\\n            columns=['aro_c_n','ato_c_n','cha_c_n','chi_c_n','hco_c_n',\\\n            'hyb_c_n','ring_c_n','aro_c_e','con_c_e','ord_c_e','ring_c_e',\\\n            'ste_c_e','alpha','RMSE_train', 'MAE_train', 'RMSE_test', 'MAE_test'])\n  exhaust_search_results = exhaust_search_results.append(data,ignore_index=True)\n```\n\n\n```\nfor chi_c_n in chi_c_ns:\n  model,para_list = gpr_model(chi_c_n = chi_c_n)\n  model.fit(train.graphs, train[target], repeat=3, verbose=False)\n  mu = model.predict(train.graphs)\n  MAE_train = np.mean(np.abs(train[target] - mu))\n  RMSE_train = np.std(train[target] - mu)\n  para_list.append(RMSE_train)\n  para_list.append(MAE_train)\n  mu_test = model.predict(test.graphs)\n  MAE_test = np.mean(np.abs(test[target] - mu_test))\n  RMSE_test = np.std(test[target] - mu_test)\n  para_list.append(RMSE_test)\n  para_list.append(MAE_test)\n  data = pd.DataFrame(data = [para_list],\\\n            columns=['aro_c_n','ato_c_n','cha_c_n','chi_c_n','hco_c_n',\\\n            'hyb_c_n','ring_c_n','aro_c_e','con_c_e','ord_c_e','ring_c_e',\\\n            'ste_c_e','alpha','RMSE_train', 'MAE_train', 'RMSE_test', 'MAE_test'])\n  exhaust_search_results = exhaust_search_results.append(data,ignore_index=True)\n```\n\n\n```\n# exhausitive search\nfor aro_c_n in aro_c_ns:\n  for ato_c_n in ato_c_ns:\n    for cha_c_n in cha_c_ns:\n      for chi_c_n in chi_c_ns:\n        for hco_c_n in hco_c_ns:\n          for hyb_c_n in hyb_c_ns:\n            for ring_c_n in ring_c_ns:\n              for aro_c_e in aro_c_es:\n                for con_c_e in con_c_es:\n                  for ord_c_e in ord_c_es:\n                    for ring_c_e in ring_c_es:\n                      for ste_c_e in ste_c_es:\n                        for alpha in alphas:\n                          model = gpr_model(aro_c_n, ato_c_n, cha_c_n, chi_c_n, hco_c_n, hyb_c_n, ring_c_,\\ \n                                  aro_c_e, con_c_e, ord_c_e, ring_c_e, ste_c_e, alpha)\n                          model.fit(train.graphs, train[target], repeat=3, verbose=False)\n                          mu = model.predict(train.graphs)\n                          MAE_train = np.mean(np.abs(train[target] - mu)))\n                          RMSE_train = np.std(train[target] - mu))\n                          mu_test = model.predict(test.graphs)\n                          MAE_test = np.mean(np.abs(test[target] - mu_test)))\n                          RMSE_test = np.std(test[target] - mu_test))\n                          # add results to the dataframe (!unfinished)\n                          \n\n\n\n\n```\n\n\n```\n\n```\n", "meta": {"hexsha": "c4244d5f064630d741b3f726b6613a0d7736ae0d", "size": 496510, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Docking.ipynb", "max_stars_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_stars_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Docking.ipynb", "max_issues_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_issues_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Docking.ipynb", "max_forks_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_forks_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 123.7253924745, "max_line_length": 24654, "alphanum_fraction": 0.7361120622, "converted": true, "num_tokens": 68480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.051845467748535906, "lm_q1q2_score": 0.022301190488225552}}
{"text": "# Lab 6: Collisions in 2D\n### Objectives\n- To learn to take good measurements\n- To learn how to estimate and propagate errors\n- To learn how to take measurements to verify a theory\n- To experiment with collisions\n\n### Equipment\n- One Collision table set up with Spark Timer and Carbon Mat\n- A number of recording sheets\n- One protractor\n- One 30 cm ruler\n- One scale\n\n### Safety\n- <u>**Electrical Hazard**</u>: The Spark Timer generates dots on the recording sheet by passing high voltage from one puck, through the carbon mat, to the other puck.\n    - The red and black cables <u>must always be securely connected</u> between the Spark Timer and the Table and they <u>must be in good condition</u>.\n    - Do not depress the foot switch without both pucks on the table.\n    - <u>**Do not touch the metal pucks while the footswitch is depressed.**</u>\n    - Alert your instructor if the cables are in poor condition, are not remaining seated, or if the <u>sparking is clearly audible</u>.\n- Use the <u>least possible force</u> when sending a puck along the table. Ask your instructor to help you assemble a rubber-band launcher if you prefer---they will give you more reproducible results as well.\n- Do not touch the latex tubes connecting the compressed air distributor to the air pucks. Latex is damaged by oils and UV light (it is also possible---though unlikely---that you might have an allergy to latex).\n- <u>Do not depress the footswitch until you are ready to take data</u>. Leaving a puck in one place for longer than 20 seconds while generating spark data can damage the carbon mat.\n- Do not write on the paper while it is on the carbon mat.\n\n# Introduction\nOne of the primary results of Newtonian Mechanics is that, if there are no external forces, the momentum of a system is conserved---even if mechanical energy is not. This experiment will allow you to test that theory by sending two pucks towards each other and recording their speeds and trajectories both before and after a collision. \n\nThe collision table has a couple of features to help you analyze collisions: The pucks use compressed air to act like hovercraft---greatly reducing friction. And a Spark Timer will generate dots at a frequency of your choosing so that you can locate each puck accurately and use simple kinematics to determine the puck\u2019s velocity and direction.\n\nYour experiments should be performed so that it is clear whether or not momentum is conserved during collisions which both conserve and do not conserve kinetic energy.\n\nIt will be to your benefit to be slow and careful while performing this lab.\n\n# Theory\n\n### Conservation of Momentum\nThe momentum of an object is the product of the mass and the velocity of that object. Because velocity is a vector, momentum must also be a vector:  \n\n\\begin{equation}\n\\vec{p} \\equiv m \\vec{v}\n\\tag{1}\n\\end{equation}\n\nOne must keep track of both the x and y components of the momentum at all times.\n\nThe momentum of a system of particles is simply the sum of the momenta of each particle:\n\n\\begin{equation}\n\\vec{p_{sys}} \\equiv \\sum _{i} \\vec{p_{i}}\n\\tag{2}\n\\end{equation}\n\nRemember that these are vectors and must be added using vector addition. Consult chapter three of your textbook for more details.\n\nBecause Newton\u2019s second law actually reads  \n\n\\begin{equation}\n\\vec{F} \\equiv \\frac{d \\vec{p}}{dt}\n\\tag{3}\n\\end{equation}\n\nit can be interpreted to say \u201can external force on a system induces a change in momentum of that system.\u201d Therefore, if there is no external force, there is no change in momentum. (If you assume the mass of the system is constant and you know how to work with derivatives, you should be able to re-derive the old version:  $\\vec{F} \\equiv m \\vec{a}$ ).  \n\nIn a collision, the most important forces will be internal to the system. In other words, every force will be one of an \u201caction-reaction\u201d pair which comes from within the system itself (e.g. one puck striking the other). Because there will be no external forces (forces that have their origin outside the system), by Newton\u2019s second law, we expect the momentum of the system to remain constant.\n\nTo verify this, you will need to measure the masses of the pucks and their velocities both before and after each collision.\n\n### Elastic and Inelastic Collisions\nAlthough *momentum* is conserved in all collisions (when they are free from external forces), it is not always true that *kinetic energy* is conserved. When two cars collide on an icy street, they may bounce off of one another (for low-speed collisions), or they may stick to one another (for high-speed collisions).\n\nIf the cars bounce off each other, we expect the *total* kinetic energy to be conserved (so that the sum of the kinetic energies before the collision equals the sum afterwards, even if the individual speeds changed). This kind of collision is called a <u>**totally elastic collision.**</u>\n\nIf the cars stick to each other, we expect that some (or all) of the kinetic energy was lost (where did it go?) These kinds of collisions are called <u>**inelastic collisions.**</u>\n\nTo determine if the collision was totally elastic or inelastic, you will need to compute the kinetic energy of each puck  \n\n\\begin{equation}\nK = \\frac{1}{2} m v^2\n\\tag{4}\n\\end{equation}\n\nand add them together. Then compare the sum before the collision to the sum following the collision.\n\n### Kinematics\nClearly, you will need to compute the velocity of the air puck. The information you will have, however, are dots generated by the Spark Timer. The dots will be generated at a rate you set (either with a knob or with the digital controller) and that rate will allow you to compute the puck\u2019s velocity using basic kinematics:  \n\n\\begin{equation} \nv \\equiv \\frac{\\Delta s}{\\Delta t} \n\\tag{5} \n\\end{equation}\n\nwhere $\\Delta s$ is the distance *between* dots and $\\Delta t$ is the time between sparks. The Spark Timer has *frequency* settings (measured in Hz or 1/s). Remember that the frequency is inversely related to the period:  \n\n\\begin{equation} \nf \\equiv \\frac{t}{\\tau} \n\\tag{6} \n\\end{equation}\n\n(You can remember this by thinking about tapping your finger on the desk: If you tap your finger 8 times per second, then the time between taps is 1/8 = 0.125 second. If you tap your finger more quickly, the frequency goes *up*, but the time between taps must go down.)\n\n### Velocity of the Center of Mass\nIf the two pucks were connected with a thin rod, the center of mass of the system would be the place where you could balance that rod. We find the center of mass of two objects by a weighted average:  \n\n\\begin{equation}\nx_{cm} = \\frac{m_{1} x_{1} + m_{2} x_{2}}{m_{1} + m_{2}} \\quad \\textrm{and} \\quad y_{cm} = \\frac{m_{1} y_{1} + m_{2} y_{2}}{m_{1} + m_{2}}\n\\tag{7}\n\\end{equation}\n\nBy taking derivatives, we can find the x- and y-velocities of the center of mass:  \n\n\\begin{equation}\nv_{x,cm} = \\frac{m_{1} v_{x,1} + m_{2} v_{x,2}}{m_{1} + m_{2}} \\quad \\textrm{and} \\quad v_{y,cm} = \\frac{m_{1} v_{y,1} + m_{2} v_{y,2}}{m_{1} + m_{2}}\n\\tag{8}\n\\end{equation}\n\n### Uncertainty Analysis\nYour Lab Manual and the previous labs can guide you in estimating the uncertainties in your measurements and propagating those errors into your computed energies and momenta. The uncertainty in the masses of the air puck will be determined by the accuracy of the scale.\n\nThe uncertainties in your velocities will come from how accurately you can measure distances and times. The uncertainty in the Spark Timer\u2019s frequency is 1% of the frequency you chose. To reduce the uncertainty in your distance between dots, you can measure the distance, *L*, between *n* dots. The average distance between dots is then $\\Delta s = L/(n-1)$. Your uncertainty in that distance is then $\\delta (\\Delta s) = \\delta s/(n-1)$.\n\nIn some cases, it might be easier to use the standard deviation of a large number of\nmeasurements as your measurement uncertainty.\n\n# Experimental Procedure\n\n### Setting up the Air Table\nBefore you begin, you will need to level the air table. To make this process easier, you should have all three feet on the same surface (do not have two feet on one table and one on another).\n\n1. Remove one puck from the table and place the second puck in the center of the table directly under the air distributor.\n2. Plug in/turn on the air compressor.\n3. Hold the puck steady under the distributor and, carefully, release the puck without disturbing it.\n4. If the puck tends to move to one side, you will need to raise (unscrew) the foot nearest that side of the table. In some cases, you will need to adjust two feet simultaneously.\n5. When the table is level, the puck will meander slowly in no particular direction.\n\nThe more time you spend leveling the table (within reason), the better your results will be.\n\nImportant points to remember:\n\n- Keep the compressor as far from the table as possible. The compressor will vibrate the table which may influence your results. If possible, keep the compressor on the floor.\n- Keep the compressor as far from the Spark Timer as possible. The electric motor will generate Electro-Magnetic Interference (EMI) which can interfere with the proper working of the Spark Timer.\n- Be gentle with the carbon mat. This is the source of your data. If you damage it, you may not get clear marks on the recording paper.\n- Be very careful if you must detach the pucks from their tubes. Doing this improperly may cause the conductive chain to retract into the tubing---making it especially difficult to retrieve.\n\nWhen you are ready to take data, place a sheet of blank newsprint paper over the carbon mat and then place both pucks on the paper.\n\n### Totally Elastic Collisions\nOne puck will be launched from one edge of the table towards a stationary puck at the center of the table so that they collide near the center of the table. Before taking data, you should turn on the air compressor and practice launching the pucks a few times *without* using the Spark Timer.\n\nOnce you are ready to take data, turn on the Spark Timer and pick a frequency (you will have to use a few trials to find the frequency that gives you a good line of dots). The person launching the puck should be the one to use the foot pedal. <u>Immediately after the puck is launched, hold the foot pedal down until a second or so after the collision</u>. **Your data will appear on the underside of the paper sheet.**\n\nSome things to consider before analyzing your data:\n\n- Try aligning your coordinate system so that the x-axis points along the path of one of the pucks.\n- On what part of the path should you take your measurements to compute the velocity of the puck both before and after the collision? How many dots should you use? How should you determine the uncertainty in this measurement?\n\n\n```python\n# Raw Data 1: The Elastic Collision\n\n# Import Numpy and Pandas with standard names\nimport pandas as pd\nimport numpy as np\n\n# Create an empty numpy array to hold the raw data\nraw_data_1 = np.empty((3,6))\n\n# Create a Pandas dataframe\ndf1 = pd.DataFrame(raw_data_1, columns=[\" \", \n                                        \"v_x (m/s)\", \n                                        \"v_y (m/s)\",\n                                        \"p_x (kg m/s)\", \n                                        \"p_y (kg m/s)\",\n                                         \"Kinetic (J)\"])\n\ndf1[' '] = [\"Initial (\u201cincoming\u201d)\",\"Mass I (\u201coutgoing\u201d)\", \"Mass II (\u201coutgoing\u201d)\"]\n\n\n#### Enter Raw Data Here!!!!!!!!!!!!!! ####\n\n# Spark Timer Frequency (s) and its uncertainty (1% of f)\nf1 = 0.05\ndelta_f1 = 0.0005\n\n# Incoming Mass (kg) and its uncertainty\nm_in = 0.55840\ndelta_m_in = 0.005\n\n# Dot Spacing of Incoming (m) and its uncertainty\nDelta_s = 0.009\nunc_Delta_s = 0.0005\n\n\n# Outgoing Mass I (kg) and its uncertainty\nm1 = 0.55840\ndelta_m1 = 0.005\n\n# Dot Spacing of Outgoing I(m) and its uncertainty\nDelta_s1 = 0.008\nunc_Delta_s1 = 0.0005\n\n# Angle of Outgoing I\ntheta1 = 19\n\n\n# Outgoing Mass II (kg) and its uncertainty\nm2 = 0.54277\ndelta_m2 = 0.005\n\n# Dot Spacing of Outgoing II (m) and its uncertainty\nDelta_s2 = 0.005\nunc_Delta_s2 = 0.0005\n\n# Angle of Outgoing II\ntheta2 = 308\n\n\n# Velocities in the x and y directions\ndf1['v_x (m/s)'] = [0.18,0.151,0.0616]\ndf1['v_y (m/s)'] = [0,0.052,0.0780]\n\n# Momentum in the x and y directions\ndf1['p_x (kg m/s)'] = [0.1005,0.0843,0.0334]\ndf1['p_y (kg m/s)'] = [0,0.0290,0.0423]\n\n# Kinetic energy of the pucks \ndf1['Kinetic (J)'] = [0.00905,0.00715,0.00271]\n\n###########################################\n\n\n# Print statements for the data\nprint(\"Spark Timer Frequency: f1 = %0.2f s        \ud835\udefff1 = %0.4f\" % (f1, delta_f1))\nprint('-'*80)\n\nprint(\"Incoming Mass:         m = %0.4f kg      \ud835\udeffm = %0.3f\" % (m_in, delta_m_in))\nprint(\"Dot Spacing:           \u0394s = %0.3f m       \ud835\udeff\u0394s = %0.4f\" % (Delta_s, unc_Delta_s))\nprint('-'*80)\n\nprint(\"Outgoing Mass (I):     m1 = %0.4f kg     \ud835\udeffm1 = %0.3f\" % (m1, delta_m1))\nprint(\"Dot Spacing:           \u0394s1 = %0.3f m      \ud835\udeff\u0394s1 = %0.4f\" % (Delta_s1, unc_Delta_s1))\nprint(\"Angle:                 \u03b81 = %0.1f\u00b0\" % (theta1))\nprint('-'*80)\n\nprint(\"Outgoing Mass (II):    m2 = %0.4f kg     \ud835\udeffm2 = %0.3f\" % (m2, delta_m2))\nprint(\"Dot Spacing:           \u0394s2 = %0.3f m      \ud835\udeff\u0394s2 = %0.4f\" % (Delta_s2, unc_Delta_s2))\nprint(\"Angle:                 \u03b82 = %0.1f\u00b0\" % (theta2))\nprint()\n\nfrom IPython.display import display\ndisplay(df1)\nprint (\"Table 1: The Elastic Collision\")\nprint()\n```\n\n    Spark Timer Frequency: f1 = 0.05 s        \ud835\udefff1 = 0.0005\n    --------------------------------------------------------------------------------\n    Incoming Mass:         m = 0.5584 kg      \ud835\udeffm = 0.005\n    Dot Spacing:           \u0394s = 0.009 m       \ud835\udeff\u0394s = 0.0005\n    --------------------------------------------------------------------------------\n    Outgoing Mass (I):     m1 = 0.5584 kg     \ud835\udeffm1 = 0.005\n    Dot Spacing:           \u0394s1 = 0.008 m      \ud835\udeff\u0394s1 = 0.0005\n    Angle:                 \u03b81 = 19.0\u00b0\n    --------------------------------------------------------------------------------\n    Outgoing Mass (II):    m2 = 0.5428 kg     \ud835\udeffm2 = 0.005\n    Dot Spacing:           \u0394s2 = 0.005 m      \ud835\udeff\u0394s2 = 0.0005\n    Angle:                 \u03b82 = 308.0\u00b0\n    \n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>v_x (m/s)</th>\n      <th>v_y (m/s)</th>\n      <th>p_x (kg m/s)</th>\n      <th>p_y (kg m/s)</th>\n      <th>Kinetic (J)</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Initial (\u201cincoming\u201d)</td>\n      <td>0.1800</td>\n      <td>0.000</td>\n      <td>0.1005</td>\n      <td>0.0000</td>\n      <td>0.00905</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Mass I (\u201coutgoing\u201d)</td>\n      <td>0.1510</td>\n      <td>0.052</td>\n      <td>0.0843</td>\n      <td>0.0290</td>\n      <td>0.00715</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Mass II (\u201coutgoing\u201d)</td>\n      <td>0.0616</td>\n      <td>0.078</td>\n      <td>0.0334</td>\n      <td>0.0423</td>\n      <td>0.00271</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    Table 1: The Elastic Collision\n    \n\n\n\n```python\n# Raw Data 2: The Elastic Collision\n\n# Create an empty numpy array to hold the raw data\nraw_data_2 = np.empty((2,4))\n\n# Create a Pandas dataframe\ndf2 = pd.DataFrame(raw_data_2, columns=[\" \", \n                                        \"v (m/s)\", \n                                        \"p(kg m/s)\",\n                                         \"Kinetic (J)\"])\n\ndf2[' '] = [\"Initial (before collision)\",\"Final (after collision)\"]\n\n\n#### Enter Raw Data Here!!!!!!!!!!!!!! ####\n\ndf2['v (m/s)'] = [0.18,0.26]\n\ndf2['p(kg m/s)'] = [0.1005,0.1436]\n\ndf2['Kinetic (J)'] = [0.00905,0.00986]\n\n###########################################\n\nfrom IPython.display import display\ndisplay(df2)\nprint (\"Table 2: Elastic Collision\")\nprint()\n```\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>v (m/s)</th>\n      <th>p(kg m/s)</th>\n      <th>Kinetic (J)</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Initial (before collision)</td>\n      <td>0.18</td>\n      <td>0.1005</td>\n      <td>0.00905</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Final (after collision)</td>\n      <td>0.26</td>\n      <td>0.1436</td>\n      <td>0.00986</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    Table 2: Elastic Collision\n    \n\n\n***\n\n### Inelastic Collisions\nThe procedure for creating an inelastic collision is exactly the same as for creating an elastic collision except that you must modify the pucks slightly by making them \u201csticky.\u201d This is accomplished by wrapping Velcro strips around each puck. It is not necessary that they Velcro actually adheres to the puck, but as long as it is wrapped tightly enough, it won\u2019t come off.\n\nThe inelastic collision will have a complication: after the two pucks stick together, they may \u201corbit\u201d each other as they move away from the collision location. You will need to determine the <u>center-of-mass</u> velocity of these pucks as they move away from the collision.\n\n\n```python\n# Raw Data 3: The Inelastic Collision\n\n# Create an empty numpy array to hold the raw data\nraw_data_3 = np.empty((4,6))\n\n# Create a Pandas dataframe\ndf3 = pd.DataFrame(raw_data_3, columns=[\" \", \n                                        \"v_x (m/s)\", \n                                        \"v_y (m/s)\",\n                                        \"p_x (kg m/s)\", \n                                        \"p_y (kg m/s)\",\n                                         \"Kinetic (J)\"])\n\ndf3[' '] = [\"Initial (\"\"Incoming\"\")\",\"Mass I (\u201coutgoing\u201d)\", \"Mass II (\u201coutgoing\u201d)\", \"CM\"]\n\n\n#### Enter Raw Data Here!!!!!!!!!!!!!! ####\n\n# Spark Timer Frequency (s) and its uncertainty (1% of f)\nf1 = 0.05\ndelta_f1 = 0.0005\n\n# Incoming Mass (kg) and its uncertainty\nm_in = 0.56121\ndelta_m_in = 0.005\n\n# Dot Spacing of Incoming (m) and its uncertainty\nDelta_s = 0.015\nunc_Delta_s = 0.0005\n\n\n# Outgoing Mass I (kg) and its uncertainty\nm1 = 0.56121\ndelta_m1 = 0.005\n\n# Dot Spacing of Outgoing I(m) and its uncertainty\nDelta_s1 = 0.01\nunc_Delta_s1 = 0.0005\n\n# Angle of Outgoing I\ntheta1 = 14\n\n\n# Outgoing Mass II (kg) and its uncertainty\nm2 = 0.5456\ndelta_m2 = 0.005\n\n# Dot Spacing of Outgoing II (m) and its uncertainty\nDelta_s2 = 0.005\nunc_Delta_s2 = 0.0005\n\n# Angle of Outgoing II\ntheta2 = -30\n\n\n# Velocities in the x and y directions\ndf3['v_x (m/s)'] = [0.3,0.194,0.0866,0.1411]\ndf3['v_y (m/s)'] = [0,0.0484, 0.05, 0.04919]\n\n# Momentum in the x and y directions\ndf3['p_x (kg m/s)'] = [0.1684,0.1089,0.0472,0.1562]\ndf3['p_y (kg m/s)'] = [0,0.0217,0.0273,0.0544]\n\n# Kinetic energy of the pucks \ndf3['Kinetic (J)'] = [0.0253,0.01122,0.00273,0.02767]\n\n###########################################\n\n\n# Print statements for the data\nprint(\"Spark Timer Frequency: f1 = %0.2f s        \ud835\udefff1 = %0.4f\" % (f1, delta_f1))\nprint('-'*80)\n\nprint(\"Incoming Mass:         m = %0.4f kg      \ud835\udeffm = %0.3f\" % (m_in, delta_m_in))\nprint(\"Dot Spacing:           \u0394s = %0.3f m       \ud835\udeff\u0394s = %0.4f\" % (Delta_s, unc_Delta_s))\nprint('-'*80)\n\nprint(\"Outgoing Mass (I):     m1 = %0.4f kg     \ud835\udeffm1 = %0.3f\" % (m1, delta_m1))\nprint(\"Dot Spacing:           \u0394s1 = %0.3f m      \ud835\udeff\u0394s1 = %0.4f\" % (Delta_s1, unc_Delta_s1))\nprint(\"Angle:                 \u03b81 = %0.1f\u00b0\" % (theta1))\nprint('-'*80)\n\nprint(\"Outgoing Mass (II):    m2 = %0.4f kg     \ud835\udeffm2 = %0.3f\" % (m2, delta_m2))\nprint(\"Dot Spacing:           \u0394s2 = %0.3f m      \ud835\udeff\u0394s2 = %0.4f\" % (Delta_s2, unc_Delta_s2))\nprint(\"Angle:                 \u03b82 = %0.1f\u00b0\" % (theta2))\nprint()\n\nfrom IPython.display import display\ndisplay(df3)\nprint (\"Table 3: The Inelastic Collision\")\nprint()\n```\n\n    Spark Timer Frequency: f1 = 0.05 s        \ud835\udefff1 = 0.0005\n    --------------------------------------------------------------------------------\n    Incoming Mass:         m = 0.5612 kg      \ud835\udeffm = 0.005\n    Dot Spacing:           \u0394s = 0.015 m       \ud835\udeff\u0394s = 0.0005\n    --------------------------------------------------------------------------------\n    Outgoing Mass (I):     m1 = 0.5612 kg     \ud835\udeffm1 = 0.005\n    Dot Spacing:           \u0394s1 = 0.010 m      \ud835\udeff\u0394s1 = 0.0005\n    Angle:                 \u03b81 = 14.0\u00b0\n    --------------------------------------------------------------------------------\n    Outgoing Mass (II):    m2 = 0.5456 kg     \ud835\udeffm2 = 0.005\n    Dot Spacing:           \u0394s2 = 0.005 m      \ud835\udeff\u0394s2 = 0.0005\n    Angle:                 \u03b82 = -30.0\u00b0\n    \n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>v_x (m/s)</th>\n      <th>v_y (m/s)</th>\n      <th>p_x (kg m/s)</th>\n      <th>p_y (kg m/s)</th>\n      <th>Kinetic (J)</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Initial (Incoming)</td>\n      <td>0.3000</td>\n      <td>0.00000</td>\n      <td>0.1684</td>\n      <td>0.0000</td>\n      <td>0.02530</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Mass I (\u201coutgoing\u201d)</td>\n      <td>0.1940</td>\n      <td>0.04840</td>\n      <td>0.1089</td>\n      <td>0.0217</td>\n      <td>0.01122</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Mass II (\u201coutgoing\u201d)</td>\n      <td>0.0866</td>\n      <td>0.05000</td>\n      <td>0.0472</td>\n      <td>0.0273</td>\n      <td>0.00273</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>CM</td>\n      <td>0.1411</td>\n      <td>0.04919</td>\n      <td>0.1562</td>\n      <td>0.0544</td>\n      <td>0.02767</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    Table 3: The Inelastic Collision\n    \n\n\n\n```python\n# Raw Data 4: Inelastic Collision\n\n# Create an empty numpy array to hold the raw data\nraw_data_4 = np.empty((2,4))\n\n\n# Create a Pandas dataframe\ndf4 = pd.DataFrame(raw_data_4, columns=[\" \", \n                                        \"v (m/s)\", \n                                        \"p(kg m/s)\",\n                                         \"Kinetic (J)\"])\n\ndf4[' '] = [\"Initial (before collision)\",\"Final (after collision)\"]\n\n\n#### Enter Raw Data Here!!!!!!!!!!!!!! ####\n\ndf4['v (m/s)'] = [0,0]\n\ndf4['p(kg m/s)'] = [0,0]\n\ndf4['Kinetic (J)'] = [0,0]\n\n###########################################\n\nfrom IPython.display import display\ndisplay(df4)\nprint (\"Table 4: Inelastic Collision\")\nprint()\n```\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>v (m/s)</th>\n      <th>p(kg m/s)</th>\n      <th>Kinetic (J)</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Initial (before collision)</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Final (after collision)</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    Table 4: Inelastic Collision\n    \n\n\n***\nDiagrams?\n***\n\n# Your Report\n\n### Introduction\nWrite a few sentences about what you set out to measure and how you will compare the measured values with theory.\n\n### Theory\nWrite few paragraphs about how you computed the momenta and kinetic energies for the pucks and what you expect them to be for your experiments. Use equations where necessary. As always, talk about how you computed your errors.\n\n[**Extra Credit**: define \u201ccoefficient of restitution\u201d AND....]\n\n### Experimental Procedure\nWrite a paragraph or two about how you took your data. Write it so that someone else could repeat your experiment by just reading this section. What experiments did you perform? How did you measure the velocities of the pucks? Talk about any problems you encountered and how you handled them.\n\n### Results and Conclusion\nThis will be your longest section. Use good paragraph structure to link the results together:\n\n- How do your initial and final momenta compare for your experiments?\n- How do your initial and final kinetic energies compare for your experiments?\n- Does your data support or refute Conservation of Momentum? What, if anything, might have interfered with perfect agreement?\n- If conservation of momentum is correct, what was your percent error and why was it not zero?\n- Did your \u201celastic collisions\u201d truly conserve kinetic energy? What was your percent error and why was it not zero?\n\n[**Extra Credit**: ...AND Compute the coefficient of restitution for your elastic and inelastic\ncollisions]\n\nAs always, talk about your uncertainties and how you might be able to reduce them. Make sure that you discuss all possible sources of *experimental* error in your experiments.\n\n### Appendix\n*Include your signed raw data sheet(s) and Sample Calculations.*\n", "meta": {"hexsha": "1608cb3fbd52930f8662116ec0e2b02432f25ca1", "size": 37198, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "PHYS201/Lab6.ipynb", "max_stars_repo_name": "JNichols-19/PhysicsLabs", "max_stars_repo_head_hexsha": "289cb0d07408afde252fe2cabad17fc0b4d987c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PHYS201/Lab6.ipynb", "max_issues_repo_name": "JNichols-19/PhysicsLabs", "max_issues_repo_head_hexsha": "289cb0d07408afde252fe2cabad17fc0b4d987c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PHYS201/Lab6.ipynb", "max_forks_repo_name": "JNichols-19/PhysicsLabs", "max_forks_repo_head_hexsha": "289cb0d07408afde252fe2cabad17fc0b4d987c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1146161935, "max_line_length": 451, "alphanum_fraction": 0.5013979246, "converted": true, "num_tokens": 7289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414096510109, "lm_q2_score": 0.08269733645795115, "lm_q1q2_score": 0.022240738241385317}}
{"text": "```python\n%load_ext magic_markdown\n```\n\n\n```python\n%%mmd\nMagicMarkdown cell magic uses the **mmd** command. \n```\n\n\nMagicMarkdown cell magic uses the **mmd** command. \n\n\n\n```python\n%%mmd\nThis is markdown with some python stuff. simply put a python expression into a mustache: {{5+10}}.\n```\n\n\nThis is markdown with some python stuff. simply put a python expression into a mustache: 15.\n\n\n\n```python\n%%mmd\nThe cell is interpreted as Markdown, so html will naturally work.<br>\n<b>some bold  text!</b>\n```\n\n\nThe cell is interpreted as Markdown, so html will naturally work.<br>\n<b>some bold  text!</b>\n\n\n\n```python\nfrom IPython.display import JSON, Latex\n```\n\n\n```python\n%%mmd\nAdditionally some of the other types that are defined in IPython.display can be used. Namely:\n - HTML\n - JSON \n - Image\n - SVG\n - Latex\n - Markdown\n    \nThat means whenever your python expression return an element of these types they \n{{\n    JSON({\"a\":10, \"b\":[1,4,5]})\n}}\n\n<br><br>\n\nFor LaTeX all \\ have to be escaped:\n    \n{{Latex(\"\\\\begin{align}F(x) &= \\\\int^a_b\\\\frac{x^2}{5} \\\\end{align}\")}}\n```\n\n\nAdditionally some of the other types that are defined in IPython.display can be used. Namely:\n - HTML\n - JSON \n - Image\n - SVG\n - Latex\n - Markdown\n    \nThat means whenever your python expression return an element of these types they \n\n\n\n\n    <IPython.core.display.JSON object>\n\n\n\n\n\n<br><br>\n\nFor LaTeX all \\ have to be escaped:\n    \n\n\n\n\n\\begin{align}F(x) &= \\int^a_b\\frac{x^2}{5} \\end{align}\n\n\n\n```python\nfrom random import randint\n\nnumber_count = randint(500, 1000)\nrandom_nums = [randint(0, 1000) for a in range(0, number_count)]\n```\n\n\n```python\n%%mmd\nThere are {{number_count}} numbers. The highest is *{{max(random_nums)}}*\n```\n\n\nThere are 948 numbers. The highest is *1000*\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "4121dcbe0be5db83cf4c5c032448295fab4e78be", "size": 5348, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "example/magic_markdown_test.ipynb", "max_stars_repo_name": "transfluxus/magic_markdown", "max_stars_repo_head_hexsha": "3a71d0c0a0937dc87973b6e19389f27575e16208", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2019-04-09T17:33:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-10T04:58:59.000Z", "max_issues_repo_path": "example/magic_markdown_test.ipynb", "max_issues_repo_name": "transfluxus/magic_markdown", "max_issues_repo_head_hexsha": "3a71d0c0a0937dc87973b6e19389f27575e16208", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/magic_markdown_test.ipynb", "max_forks_repo_name": "transfluxus/magic_markdown", "max_forks_repo_head_hexsha": "3a71d0c0a0937dc87973b6e19389f27575e16208", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9725490196, "max_line_length": 105, "alphanum_fraction": 0.4798055348, "converted": true, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167299096624174, "lm_q2_score": 0.050330628858229316, "lm_q1q2_score": 0.022229679385025982}}
{"text": "```python\npip install matminer\n```\n\n    Requirement already satisfied: matminer in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (0.6.4)\n    Requirement already satisfied: monty>=3.0.2 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from matminer) (4.0.0)\n    Requirement already satisfied: jsonschema>=3.2.0 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from matminer) (3.2.0)\n    Requirement already satisfied: pandas>=1.0.4 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from matminer) (1.2.1)\n    Requirement already satisfied: tqdm>=4.46.0 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from matminer) (4.56.0)\n    Requirement already satisfied: numpy>=1.19.1 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from matminer) (1.19.2)\n    Requirement already satisfied: requests>=2.23.0 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from matminer) (2.25.1)\n    Requirement already satisfied: future>=0.18.2 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from matminer) (0.18.2)\n    Requirement already satisfied: plotly>=4.8.1 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from matminer) (4.14.3)\n    Requirement already satisfied: sympy>=1.6 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from matminer) (1.7.1)\n    Requirement already satisfied: scikit-learn>=0.23.1 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from matminer) (0.23.2)\n    Requirement already satisfied: six>=1.15.0 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from matminer) (1.15.0)\n    Requirement already satisfied: pymongo>=3.10.1 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from matminer) (3.11.2)\n    Requirement already satisfied: pymatgen>=2020.4.29 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from matminer) (2020.8.13)\n    Requirement already satisfied: pint>=0.11 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from matminer) (0.16.1)\n    Requirement already satisfied: attrs>=17.4.0 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from jsonschema>=3.2.0->matminer) (20.3.0)\n    Requirement already satisfied: pyrsistent>=0.14.0 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from jsonschema>=3.2.0->matminer) (0.17.3)\n    Requirement already satisfied: setuptools in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from jsonschema>=3.2.0->matminer) (52.0.0.post20210125)\n    Requirement already satisfied: python-dateutil>=2.7.3 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from pandas>=1.0.4->matminer) (2.8.1)\n    Requirement already satisfied: pytz>=2017.3 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from pandas>=1.0.4->matminer) (2021.1)\n    Requirement already satisfied: packaging in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from pint>=0.11->matminer) (20.9)\n    Requirement already satisfied: retrying>=1.3.3 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from plotly>=4.8.1->matminer) (1.3.3)\n    Requirement already satisfied: scipy>=1.5.0 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from pymatgen>=2020.4.29->matminer) (1.6.0)\n    Requirement already satisfied: tabulate in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from pymatgen>=2020.4.29->matminer) (0.8.7)\n    Requirement already satisfied: networkx>=2.2 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from pymatgen>=2020.4.29->matminer) (2.5)\n    Requirement already satisfied: spglib>=1.9.9.44 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from pymatgen>=2020.4.29->matminer) (1.16.0)\n    Requirement already satisfied: palettable>=3.1.1 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from pymatgen>=2020.4.29->matminer) (3.3.0)\n    Requirement already satisfied: matplotlib>=1.5 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from pymatgen>=2020.4.29->matminer) (3.3.4)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from pymatgen>=2020.4.29->matminer) (0.16.12)\n    Requirement already satisfied: pillow>=6.2.0 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from matplotlib>=1.5->pymatgen>=2020.4.29->matminer) (8.1.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from matplotlib>=1.5->pymatgen>=2020.4.29->matminer) (1.3.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from matplotlib>=1.5->pymatgen>=2020.4.29->matminer) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from matplotlib>=1.5->pymatgen>=2020.4.29->matminer) (0.10.0)\n    Requirement already satisfied: decorator>=4.3.0 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from networkx>=2.2->pymatgen>=2020.4.29->matminer) (4.4.2)\n    Requirement already satisfied: chardet<5,>=3.0.2 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from requests>=2.23.0->matminer) (4.0.0)\n    Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from requests>=2.23.0->matminer) (1.26.3)\n    Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from requests>=2.23.0->matminer) (2020.12.5)\n    Requirement already satisfied: idna<3,>=2.5 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from requests>=2.23.0->matminer) (2.10)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from ruamel.yaml>=0.15.6->pymatgen>=2020.4.29->matminer) (0.2.2)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from scikit-learn>=0.23.1->matminer) (2.1.0)\n    Requirement already satisfied: joblib>=0.11 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from scikit-learn>=0.23.1->matminer) (1.0.0)\n    Requirement already satisfied: mpmath>=0.19 in c:\\users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages (from sympy>=1.6->matminer) (1.1.0)\n    Note: you may need to restart the kernel to use updated packages.\n\n\n\n```python\nconda develop \"C:/Users/sterg/Documents/GitHub/sparks-baird/phylo-mat/code/cgcnn\"\n```\n\n    added C:\\Users\\sterg\\Documents\\GitHub\\sparks-baird\\phylo-mat\\code\\cgcnn\n    completed operation for: C:\\Users\\sterg\\Documents\\GitHub\\sparks-baird\\phylo-mat\\code\\cgcnn\n    \n    Note: you may need to restart the kernel to use updated packages.\n\n\n\n```python\nimport os\nfrom shutil import copyfile\nimport pandas as pd\n```\n\n\n```python\nimport numpy as np\n```\n\n\n```python\nimport glob\n```\n\n\n```python\nfrom pymatgen import Structure\n```\n\n\n```python\nfrom matminer.featurizers.structure import CGCNNFeaturizer\n```\n\n\n```python\nproperties = pd.read_csv(\"C:/Users/sterg/Documents/GitHub/cgcnn/data/cif-K_VRH/id_prop.csv\",header=None)\nproperties.shape\n```\n\n\n\n\n    (9507, 2)\n\n\n\n\n```python\nstructures = []\n#for structure_file in os.listdir(\"C:/Users/sterg/Documents/GitHub/cgcnn/data/cif-K_VRH/*.cif\"):\nfor structure_file in glob.glob(\"C:/Users/sterg/Documents/GitHub/cgcnn/data/cif-K_VRH/*.cif\"):\n    #structure_path = 'C:/Users/sterg/Documents/GitHub/cgcnn/data/cif-only-K_VRH/'+structure_file\n    structure_path = structure_file\n    structure = Structure.from_file(structure_path)\n    structures.append(structure)\ndf = pd.DataFrame({\"K_VRH\": properties[1], \"structure\": structures})\nprint(df) # make sure the dataframe appears like you intended\ndf.to_pickle(\"C:/Users/sterg/Documents/GitHub/cgcnn/data/cif-K_VRH.p\")\n```\n\n    C:\\Users\\sterg\\anaconda3\\envs\\cgcnn\\lib\\site-packages\\pymatgen\\io\\cif.py:1123: UserWarning: Issues encountered while parsing CIF: Some fractional co-ordinates rounded to ideal values to avoid issues with finite precision.\n      warnings.warn(\"Issues encountered while parsing CIF: %s\" % \"\\n\".join(self.warnings))\n\n\n          K_VRH                                          structure\n    0      89.0                                    [[0. 0. 0.] Cs]\n    1     164.0  [[0. 0. 0.] Ba, [2.89438158 2.04663685 5.01321...\n    2     104.0  [[ 1.69333912  0.9776498  10.60299963] Hf, [-4...\n    3      33.0  [[2.07616833 0.94954182 2.511614  ] Nb, [4.152...\n    4      96.0  [[0. 0. 0.] Al, [1.9651759  1.13459484 0.75350...\n    ...     ...                                                ...\n    9502  115.0  [[1.46542997 0.84606639 1.959571  ] W, [0.    ...\n    9503   33.0  [[3.52723706 2.49413324 6.1093538 ] Mn, [1.175...\n    9504   19.0  [[0. 0. 0.] Mn, [1.15572927 0.81722401 2.00178...\n    9505   90.0  [[0. 0. 0.] Mn, [3.54876808 2.50935797 6.14664...\n    9506   79.0  [[0. 0. 0.] Ni, [ 2.4427789   1.45429054 -2.34...\n    \n    [9507 rows x 2 columns]\n\n\n\n```python\ndf.structure[0]\n```\n\n\n\n\n    Structure Summary\n    Lattice\n        abc : 5.29144986 5.291449860000001 5.29144986\n     angles : 109.47122063 109.47122063 109.47122063\n     volume : 114.05180557995794\n          A : 4.988826771224387 0.0 -1.7638166196089895\n          B : -2.4944133847827348 4.320450719439106 -1.7638166196089895\n          C : 0.0 0.0 5.29144986\n    PeriodicSite: Cs (0.0000, 0.0000, 0.0000) [0.0000, 0.0000, 0.0000]\n\n\n\n\n```python\nfeaturizer = CGCNNFeaturizer(task='regression', atom_init_fea=None, pretrained_name='bulk-moduli', warm_start_file=None, warm_start_latest=False, save_model_to_dir=None, save_checkpoint_to_dir=None, checkpoint_interval=100, del_checkpoint=True)\n#featurizer = CGCNNFeaturizer(task='regression', atom_init_fea=None, pretrained_name=None, warm_start_file=\"C:/Users/sterg/Documents/GitHub/cgcnn/model_best.pth.tar\", warm_start_latest=False, save_model_to_dir=None, save_checkpoint_to_dir=None, checkpoint_interval=100, del_checkpoint=True)\n#featurizer = CGCNNFeaturizer(task='regression', atom_init_fea=None, pretrained_name=None, warm_start_file=None, warm_start_latest=False, save_model_to_dir=None, save_checkpoint_to_dir=None, checkpoint_interval=100, del_checkpoint=True)\n```\n\n\n```python\nfeaturizer.__init__\n```\n\n\n```python\nfeaturizer.fit(df.structure,df.K_VRH)\n```\n\n\n```python\n%tb\n```\n\n\n```python\ndir(featurizer)\nfeaturizer.model\n```\n\n\n\n\n    CrystalGraphConvNetWrapper(\n      (embedding): Linear(in_features=92, out_features=64, bias=True)\n      (convs): ModuleList(\n        (0): ConvLayer(\n          (fc_full): Linear(in_features=169, out_features=128, bias=True)\n          (sigmoid): Sigmoid()\n          (softplus1): Softplus(beta=1, threshold=20)\n          (bn1): BatchNorm1d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (bn2): BatchNorm1d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (softplus2): Softplus(beta=1, threshold=20)\n        )\n        (1): ConvLayer(\n          (fc_full): Linear(in_features=169, out_features=128, bias=True)\n          (sigmoid): Sigmoid()\n          (softplus1): Softplus(beta=1, threshold=20)\n          (bn1): BatchNorm1d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (bn2): BatchNorm1d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (softplus2): Softplus(beta=1, threshold=20)\n        )\n        (2): ConvLayer(\n          (fc_full): Linear(in_features=169, out_features=128, bias=True)\n          (sigmoid): Sigmoid()\n          (softplus1): Softplus(beta=1, threshold=20)\n          (bn1): BatchNorm1d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (bn2): BatchNorm1d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (softplus2): Softplus(beta=1, threshold=20)\n        )\n      )\n      (conv_to_fc): Linear(in_features=64, out_features=128, bias=True)\n      (conv_to_fc_softplus): Softplus(beta=1, threshold=20)\n      (fc_out): Linear(in_features=128, out_features=1, bias=True)\n    )\n\n\n\n\n```python\nfeatures = featurizer.featurize_many(df.structure,ignore_errors=True,return_errors=False,pbar=True)\n```\n\n\n    CGCNNFeaturizer:   0%|          | 0/9507 [00:00<?, ?it/s]\n\n\n\n```python\nX=np.array(features)\nprint(X.shape)\nX[2500]\n```\n\n    (9507, 64)\n\n\n\n\n\n    array([1.37573373, 1.23462927, 1.16196263, 1.36911905, 1.31720543,\n           1.40154791, 1.24330628, 1.43035173, 1.63459027, 1.51304066,\n           1.21675014, 1.31668794, 1.42409384, 1.47255003, 1.4079994 ,\n           1.28732741, 1.32336462, 1.28203249, 1.36411798, 1.47177756,\n           1.30156195, 1.47156298, 1.19416833, 1.24935377, 1.31119406,\n           1.29552698, 1.27407646, 1.47710788, 1.50354016, 1.61430931,\n           1.32183707, 1.26828754, 1.25710285, 1.39060116, 1.24898636,\n           1.35720718, 1.22399402, 1.27981389, 1.22088349, 1.26210034,\n           1.19351184, 1.25716746, 1.26547062, 1.31304634, 1.23823953,\n           1.27775526, 1.14454794, 1.39645159, 1.26624322, 1.28061473,\n           1.31844151, 1.40172279, 1.49506128, 1.30037975, 1.26275694,\n           1.20761442, 1.27975655, 1.38074481, 1.35537803, 1.46591377,\n           1.27543914, 1.216537  , 1.38761342, 1.70867193])\n\n\n\n\n```python\npwd\n```\n\n\n\n\n    'C:\\\\Users\\\\sterg\\\\Documents\\\\GitHub\\\\sparks-baird\\\\phylo-mat\\\\code\\\\matminer_examples\\\\matminer_examples\\\\machine_learning-nb'\n\n\n\n\n```python\nsavepath = \"../../../cgcnn/data/K_VRH-features.csv\"\ncopypath = \"../../../data/K_VRH-features.csv\"\nnp.savetxt(savepath, X, delimiter=\",\")\ncopyfile(savepath,copypath)\n```\n\n\n\n\n    '../../../data/K_VRH-features.csv'\n\n\n\n\n```python\nX.shape\n```\n\n\n\n\n    (9507, 64)\n\n\n\n# Code Graveyard\n\n\n```python\nfeaturizer = CGCNNFeaturizer(task='regression', atom_init_fea=None, pretrained_name=None, warm_start_file=\"../../../cgcnn/model_best.pth.tar\", warm_start_latest=False, save_model_to_dir=None, save_checkpoint_to_dir=None, checkpoint_interval=100, del_checkpoint=True)\n```\n\n\n```python\ndir(featurizer)\n```\n\n\n```python\n#featurizer = CGCNNFeaturizer(task='regression', atom_init_fea=None, pretrained_name=None, warm_start_file=None, warm_start_latest=False, save_model_to_dir=None, save_checkpoint_to_dir=None, checkpoint_interval=100, del_checkpoint=True)\n```\n\n\n```python\nimport os\nimport pandas as pd\nfrom pymatgen import Structure\n```\n\n\n```python\nproperties = pd.read_csv(\"id_prop.csv\")\nstructures = []\nfor i, structure_file in enumerate(os.listdir(\"C:/Users/sterg/Documents/GitHub/cgcnn/data/cif-K_VRH/*.cif\"):\n    property = get_property_from_index(i)\n    structure = Structure.from_file(structure_file)\n    properties.append(property)\n    structures.append(structure)\n    df = pd.DataFrame({\u201csome_property\u201d: properties, \u201cstructure\u201d: structures})\n    print(df) # make sure the dataframe appears like you intended\n    df.to_pickle(\"/path/where/u/want/to/save/ur/dataframe.p\")\n```\n\n\n```python\nproperties = []\nstructures = []\nfor i, structure_file in enumerate(os.listdir(\"C:/Users/sterg/Documents/GitHub/cgcnn/data/cif-K_VRH/*.cif\"):\n    property = get_property_from_index(i)\n    structure = Structure.from_file(structure_file)\n    properties.append(property)\n    structures.append(structure)\n    df = pd.DataFrame({\u201csome_property\u201d: properties, \u201cstructure\u201d: structures})\n    print(df) # make sure the dataframe appears like you intended\n    df.to_pickle(\"/path/where/u/want/to/save/ur/dataframe.p\")\n```\n\n\n```python\nproperties = pd.read_csv(\"C:/Users/sterg/Documents/GitHub/cgcnn/data/cif-K_VRH/id_prop.csv\",header=None)\n```\n\n\n```python\nprops = properties[1]\n```\n\n\n```python\nfrom matminer.datasets import load_dataset\n```\n\n\n```python\nstructures = []\nfor structure_file in os.listdir(\"C:/Users/sterg/Documents/GitHub/cgcnn/data/cif-only-K_VRH/\"):\n    structure_path = 'C:/Users/sterg/Documents/GitHub/cgcnn/data/cif-only-K_VRH/'+structure_file\n    structure = Structure.from_file(structure_path)\n    structures.append(structure)\ndf = pd.DataFrame({\"K_VRH\": properties[1], \"structure\": structures})\nprint(df) # make sure the dataframe appears like you intended\ndf.to_pickle(\"C:/Users/sterg/Documents/GitHub/cgcnn/data/cif-K_VRH.p\")\n```\n\n\n```python\ndf = load_dataset(\"boltztrap_mp\");\n```\n\n\n```python\nfeaturizer.fit(df.structure,df.s_p)\n```\n\n\n```python\n%tb\n```\n\n\n```python\n#featurizer.featurize_dataframe(df.mpid,df.structure)\n```\n\n\n```python\ndf\n```\n\n\n```python\n%matplotlib inline\nfrom matplotlib import pyplot as plt\nfrom matminer.datasets import load_dataset\nfrom matminer.featurizers.base import MultipleFeaturizer\n#from matminer.featurizers.composition import ElementProperty, Stoichiometry, ValenceOrbital, IonProperty\n#from matminer.featurizers.structure import (SiteStatsFingerprint, StructuralHeterogeneity,\n#                                            ChemicalOrdering, StructureComposition, MaximumPackingEfficiency)\nfrom matminer.featurizers.conversions import DictToObject\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import ShuffleSplit, train_test_split\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nfrom scipy import stats\nfrom tqdm import tqdm_notebook as tqdm\nimport numpy as np\n```\n\n\n```python\npip install ipywidgets\n```\n\n\n```python\ndto = DictToObject(target_col_id='structure', overwrite_data=True)\n```\n\n\n```python\ndf = dto.featurize_dataframe(df, 'structure')\n```\n\n\n```python\nfeaturizer.fit(df.structure,df.s_p)\n```\n\n\n```python\n\n```\n\n\n```python\nX = featurizer.featurize_many(df['structure'], ignore_errors=False)\n```\n\n\n```python\nX = np.array(X)\nprint('Input data shape:', X.shape)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "5206c9c79bae662f57a82020a0e28dee2523f630", "size": 31699, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "matminer_examples/machine_learning-nb/cgcnn-feature.ipynb", "max_stars_repo_name": "sparks-baird/matminer_examples", "max_stars_repo_head_hexsha": "caa23420fe506a0c920e2a79ef25c0c3a3b608c2", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matminer_examples/machine_learning-nb/cgcnn-feature.ipynb", "max_issues_repo_name": "sparks-baird/matminer_examples", "max_issues_repo_head_hexsha": "caa23420fe506a0c920e2a79ef25c0c3a3b608c2", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matminer_examples/machine_learning-nb/cgcnn-feature.ipynb", "max_forks_repo_name": "sparks-baird/matminer_examples", "max_forks_repo_head_hexsha": "caa23420fe506a0c920e2a79ef25c0c3a3b608c2", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.2653333333, "max_line_length": 1209, "alphanum_fraction": 0.6116912205, "converted": true, "num_tokens": 5760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735801686526387, "lm_q2_score": 0.07159120291101934, "lm_q1q2_score": 0.022004130151729608}}
{"text": "```python\n#remove cell visibility\nfrom IPython.display import HTML\ntag = HTML('''\nPromijeni vidljivost <a href=\"javascript:code_toggle()\">ovdje</a>.''')\ndisplay(tag)\n```\n\n\n\nPromijeni vidljivost <a href=\"javascript:code_toggle()\">ovdje</a>.\n\n\n\n```python\n%matplotlib inline\nimport control\nimport numpy\nimport sympy as sym\nfrom IPython.display import display, Markdown\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\n\n\n#print a matrix latex-like\ndef bmatrix(a):\n     \"\"\"Returns a LaTeX bmatrix - by Damir Arbula (ICCT project)\n\n     :a: numpy array\n     :returns: LaTeX bmatrix as a string\n     \"\"\"\n     if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n     lines = str(a).replace('[', '').replace(']', '').splitlines()\n     rv = [r'\\begin{bmatrix}']\n     rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n     rv +=  [r'\\end{bmatrix}']\n     return '\\n'.join(rv)\n\n\n# Display formatted matrix: \ndef vmatrix(a):\n    if len(a.shape) > 2:\n         raise ValueError('bmatrix can at most display two dimensions')\n    lines = str(a).replace('[', '').replace(']', '').splitlines()\n    rv = [r'\\begin{vmatrix}']\n    rv += ['  ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n    rv +=  [r'\\end{vmatrix}']\n    return '\\n'.join(rv)\n\n\n#matrixWidget is a matrix looking widget built with a VBox of HBox(es) that returns a numPy array as value !\nclass matrixWidget(widgets.VBox):\n    def updateM(self,change):\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.M_[irow,icol] = self.children[irow].children[icol].value\n                #print(self.M_[irow,icol])\n        self.value = self.M_\n\n    def dummychangecallback(self,change):\n        pass\n    \n    \n    def __init__(self,n,m):\n        self.n = n\n        self.m = m\n        self.M_ = numpy.matrix(numpy.zeros((self.n,self.m)))\n        self.value = self.M_\n        widgets.VBox.__init__(self,\n                             children = [\n                                 widgets.HBox(children = \n                                              [widgets.FloatText(value=0.0, layout=widgets.Layout(width='90px')) for i in range(m)]\n                                             ) \n                                 for j in range(n)\n                             ])\n        \n        #fill in widgets and tell interact to call updateM each time a children changes value\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        #value = Unicode('example@example.com', help=\"The email value.\").tag(sync=True)\n        self.observe(self.updateM, names='value', type= 'All')\n        \n    def setM(self, newM):\n        #disable callbacks, change values, and reenable\n        self.unobserve(self.updateM, names='value', type= 'All')\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].unobserve(self.updateM, names='value')\n        self.M_ = newM\n        self.value = self.M_\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].value = self.M_[irow,icol]\n        for irow in range(0,self.n):\n            for icol in range(0,self.m):\n                self.children[irow].children[icol].observe(self.updateM, names='value')\n        self.observe(self.updateM, names='value', type= 'All')        \n\n                #self.children[irow].children[icol].observe(self.updateM, names='value')\n\n             \n#overlaod class for state space systems that DO NOT remove \"useless\" states (what \"professor\" of automatic control would do this?)\nclass sss(control.StateSpace):\n    def __init__(self,*args):\n        #call base class init constructor\n        control.StateSpace.__init__(self,*args)\n    #disable function below in base class\n    def _remove_useless_states(self):\n        pass\n```\n\n## Pneumatsko upravljanje polo\u017eaja\n\n\n\nKugla se nalazi unutar vertikalne cijevi na temelju strujanja zraka $u$ i spojena je putem opruge krutosti $K$ na dno cijevi; kugla je podvrgnuta gravitaciji i viskoznom trenju s koeficijentom $B$. Sila $F$ koja na kuglu djeluje protokom zraka proporcionalna je protoku zraka $u$ (u m/s) uz konstantu $G$; protok zraka mo\u017ee biti samo pozitivan (ulazak u cijev). S obzirom na masu kugle $m=2$ g, $B=1$ g/s, $K=2$ g/$\\text{s}^2$ i $G=3$ Ns/m, cilj je dizajnirati regulator s ulazom $u$ i visinom polo\u017eaja kugle $z$ kao izlazom sustava prema sljede\u0107im zahtjevima:\n- nulta pogre\u0161ka u stacionarnom stanju (u odzivu na ulaz \u017eeljene visine);\n- maksimalno prekora\u010denje 30%\n- vrijeme smirivanja za 5% pojasa tolerancije manje od 8 sekundi.\n\nJednad\u017eba dinamike koja opisuje sustav je:\n\n$$\n    m\\ddot{z} = -Kz -B\\dot{z} + Gu\n$$\n\nDefiniranjem vektora stanja kao $x=\\begin{bmatrix} x_1 & x_2 \\end{bmatrix}^T=\\begin{bmatrix} z & \\dot{z} \\end{bmatrix}^T$, mo\u017eemo pisati: \n\n\\begin{cases}\n    \\dot{x} = \\begin{bmatrix} 0 & 1 \\\\ -\\frac{K}{m} & -\\frac{B}{m} \\end{bmatrix}x + \\begin{bmatrix} 0 \\\\ \\frac{G}{m} \\end{bmatrix}u \\\\\n    y = \\begin{bmatrix} 1 & 0 \\end{bmatrix}x\n\\end{cases}\n\nPolovi sustava su $-0.25\\pm0.97i$.\n\n### Dizajn regulatora\n#### Dizajn kontrolera\n\nDa bi se zadovoljila nulta pogre\u0161ka u stacionarnom stanju, dodajemo integrator u sustav pro\u0161irivanjem vektora stanja s $\\dot{x_3} = x_1 - y_d$, gdje je $y_d$ referentni signal. Tada je pro\u0161ireni sustav:\n\n\\begin{cases}\n    \\dot{x_a} = \\begin{bmatrix} 0 & 1 & 0 \\\\ -\\frac{K}{m} & -\\frac{B}{m} & 0 \\\\ 1 & 0 & 0 \\end{bmatrix}x_a + \\begin{bmatrix} 0 & 0 \\\\ \\frac{G}{m} & 0 \\\\ 0 & -1 \\end{bmatrix}u \\\\\n    y_a = \\begin{bmatrix} 1 & 0 & 0 \\\\ 0 & 0 & 1 \\end{bmatrix}x_a \\, .\n\\end{cases}\n\nBudu\u0107i da su polovi sustava spori u odnosu na zadane zahtjeve, pove\u0107avamo prirodnu frekvenciju kompleksnih polova stavljaju\u0107i ih u $-0.5\\pm1.94$, a, tako\u0111er, integrator zamjenjujemo s polom u $-2$.\n\n\n\n\n#### Dizajn promatra\u010da\nZa procjenu stanja, razvijamo promatra\u010d za podsustav $(x_1,\\, x_2)$, a zatim uzimamo samo procjenu za $x_2$, jer se ostala stanja mjere izravno. Odabiremo $-5$ kao mjesto polova standardnog promatra\u010da.\n\n### Kako koristiti ovaj interaktivni primjer?\n- Provjerite rad regulatora relativnom varijacijom mase kugle (parametar: delta m) i, ako je potrebno, poku\u0161ajte ispraviti poziciju pola.\n- Testirajte regulator s po\u010detnom pogre\u0161kom u estimiranom stanju.\n- Testirajte regulator s razli\u010ditim tipovima referentnog ulaza.\n\n\n```python\n# Preparatory cell\nb = 1E-03\nk = 2E-03\nG = 3\nm = 2E-03\nAa = numpy.matrix([[0, 1, 0],\n                   [-k/m, -b/m, 0],\n                   [1, 0, 0]])\nBa = numpy.matrix([[0, 0],\n                   [G/m, 0],\n                   [0,-1]])\nCa = numpy.matrix([[1, 0, 0],\n                   [0, 0, 1]])\nA = Aa[0:2,0:2]\nB = Ba[0:2,0]\nC = Ca[0,0:2]\n\nX0 = numpy.matrix('0.0')\nK = numpy.matrix([8/15,-4.4,-4])\nL = numpy.matrix([[23],[66]])\n\nX0w = matrixWidget(1,1)\nX0w.setM(X0)\nKw = matrixWidget(1,3)\nKw.setM(K)\nLw = matrixWidget(2,1)\nLw.setM(L)\n\n\neig1c = matrixWidget(1,1)\neig2c = matrixWidget(2,1)\neig3c = matrixWidget(1,1)\neig1c.setM(numpy.matrix([-2.0])) \neig2c.setM(numpy.matrix([[-0.5],[-1.94]]))\neig3c.setM(numpy.matrix([-2.0]))\n\neig1o = matrixWidget(1,1)\neig2o = matrixWidget(2,1)\neig1o.setM(numpy.matrix([-5.])) \neig2o.setM(numpy.matrix([[-5.],[0.]]))\n```\n\n\n```python\n# Misc\n\n#create dummy widget \nDW = widgets.FloatText(layout=widgets.Layout(width='0px', height='0px'))\n\n#create button widget\nSTART = widgets.Button(\n    description='Test',\n    disabled=False,\n    button_style='', # 'success', 'info', 'warning', 'danger' or ''\n    tooltip='Test',\n    icon='check'\n)\n                       \ndef on_start_button_clicked(b):\n    #This is a workaround to have intreactive_output call the callback:\n    #   force the value of the dummy widget to change\n    if DW.value> 0 :\n        DW.value = -1\n    else: \n        DW.value = 1\n    pass\nSTART.on_click(on_start_button_clicked)\n\n# Define type of method \nselm = widgets.Dropdown(\n    options= ['Postavi K i L', 'Postavi svojstvene vrijednosti'],\n    value= 'Postavi svojstvene vrijednosti',\n    description='',\n    disabled=False\n)\n\n# Define the number of complex eigenvalues\nsele = widgets.Dropdown(\n    options= ['0 kompleksnih svojstvenih vrijednosti', '2 kompleksne svojstvene vrijednosti'],\n    value= '2 kompleksne svojstvene vrijednosti',\n    description='Kompleksne svojstvene vrijednosti:',\n    disabled=False\n)\n\n#define type of ipout \nselu = widgets.Dropdown(\n    options=['impuls', 'step', 'sinus', 'Pravokutni val'],\n    value='step',\n    description='Tip smetnje:',\n    style = {'description_width': 'initial'},\n    disabled=False\n)\n# Define the values of the input\nu = widgets.FloatSlider(\n    value=0.1,\n    min=0,\n    max=0.8,\n    step=0.1,\n    description='Referentni signal [m]:',\n    style = {'description_width': 'initial'},\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.1f',\n)\nmw = widgets.FloatSlider(\n    value=0,\n    min=-30,\n    max=30,\n    step=1,\n    description='delta m [%]:',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.1f',\n)\nperiod = widgets.FloatSlider(\n    value=2,\n    min=0.1,\n    max=3,\n    step=0.05,\n    description='Period [s]: ',\n    disabled=False,\n    continuous_update=False,\n    orientation='horizontal',\n    readout=True,\n    readout_format='.2f',\n)\nsimTime = widgets.FloatText(\n    value=8,\n    description='',\n    disabled=False\n)\n```\n\n\n```python\n# Support functions\n\ndef eigen_choice(sele):\n    if sele == '0 kompleksnih svojstvenih vrijednosti':\n        eig1c.children[0].children[0].disabled = False\n        eig2c.children[1].children[0].disabled = True\n        eig1o.children[0].children[0].disabled = False\n        eig2o.children[1].children[0].disabled = True\n        eig = 0\n    if sele == '2 kompleksne svojstvene vrijednosti':\n        eig1c.children[0].children[0].disabled = True\n        eig2c.children[1].children[0].disabled = False\n        eig1o.children[0].children[0].disabled = True\n        eig2o.children[1].children[0].disabled = False\n        eig = 2\n    return eig\n\ndef method_choice(selm):\n    if selm == 'Postavi K i L':\n        method = 1\n        sele.disabled = True\n    if selm == 'Postavi svojstvene vrijednosti':\n        method = 2\n        sele.disabled = False\n    return method\n\ndef simulation(m,Kw,L,uw,selu,period,simTime,X0w):\n    Aa = numpy.matrix([[0, 1, 0],\n                   [-k/(0.002*(1+m/100.0)), -b/(0.002*(1+m/100.0)), 0],\n                   [1, 0, 0]])\n    Ba = numpy.matrix([[0, 0],\n                       [G/(0.002*(1+m/100.0)), 0],\n                       [0,-1]])\n    A = Aa[0:2,0:2]\n    B = Ba[0:2,0]\n    \n    e1 = numpy.linalg.eig(Aa-Ba[:,0]*Kw)[0]\n    e1n = numpy.array([numpy.linalg.norm(e1[i]) for i in range(3)])\n    e2 = numpy.linalg.eig(A-L*C)[0]\n    e2n = numpy.array([numpy.linalg.norm(e2[i]) for i in range(2)])\n    # print(e1n,e2n)\n    \n    n1 = 0\n    if all(e1n > 0):\n        if all(numpy.real(e1)<0):\n            n1 = int(max(e1n)/2/numpy.pi*1000)\n    if n1==0:\n        n1 = 10000\n    \n    n2 = 0\n    if all(e2n > 0):\n        if all(numpy.real(e2)<0):\n            n2 = int(max(e2n)/2/numpy.pi*1000)\n    if n2==0:\n        n2 = 10000\n    if n1 >= n2:\n        n = n1\n    else:\n        n = n2\n    \n    T = numpy.linspace(0,simTime,n)\n    ts = T[1]-T[0]\n    if selu == 'impuls': #selu\n        R = [0 for t in range(0,len(T))]\n        R[0] = uw        \n    if selu == 'step':\n        R = [uw for t in range(0,len(T))]\n    if selu == 'sinus':\n        R = uw*numpy.sin(2*numpy.pi/period*T)\n        #print(R)\n    if selu == 'Pravokutni val':\n        R = uw*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n        #print(R)\n    \n    Aad = (numpy.eye(3)+ts*Aa)\n    Bad = ts*Ba\n    Ad = (numpy.eye(2)+ts*(A-L*C))\n    Bd = ts*B\n    Ld = ts*L\n    xa = numpy.matrix([[0],[0],[0]])\n    xe = numpy.matrix([[0],[X0w]])\n    x = numpy.vstack((xa,xe))\n    X = [x]\n    U = []\n    \n    for i in range(len(T)):\n        u = (-Kw*numpy.matrix([[xa[0,0]],[xe[1,0]],[xa[2,0]]]))[0,0]\n        if u < 0:\n            u = 0\n            \n        xe = Ad*xe+Bd*u+Ld*xa[0,0]\n        xa = Aad*xa+Bad*numpy.matrix([[u],[R[i]]])\n        \n        X.append(numpy.vstack((xa,xe)))\n        U.append(u)\n    \n    xout = [\n        [X[i][0,0] for i in range(len(T))],\n        [X[i][1,0] for i in range(len(T))],\n        [X[i][2,0] for i in range(len(T))],\n        [X[i][3,0] for i in range(len(T))],\n        [X[i][4,0] for i in range(len(T))]\n    ]\n    return T, U, R, xout, e1, e2\n```\n\n\n```python\ndef main_callback2(mw, X0w, K, L, eig1c, eig2c, eig3c, eig1o, eig2o, u, period, selm, sele, selu, simTime, DW):\n    eige = eigen_choice(sele)\n    method = method_choice(selm)\n    \n    if method == 1:\n        solc = numpy.linalg.eig(Aa-Ba[:,0]*K)[0]\n        solo = numpy.linalg.eig(A-L*C)[0]\n    if method == 2:\n        if eige == 0:\n            K = control.acker(Aa, Ba[:,0], [eig1c[0,0], eig2c[0,0], eig3c[0,0]])\n            Kw.setM(K)\n            L = control.acker(A.T, C.T, [eig1o[0,0], eig2o[0,0]]).T\n            Lw.setM(L)\n        if eige == 2:\n            K = control.acker(Aa, Ba[:,0], [eig3c[0,0], \n                                     numpy.complex(eig2c[0,0],eig2c[1,0]), \n                                     numpy.complex(eig2c[0,0],-eig2c[1,0])])\n            Kw.setM(K)\n            L = control.acker(A.T, C.T, [numpy.complex(eig2o[0,0],eig2o[1,0]), \n                                         numpy.complex(eig2o[0,0],-eig2o[1,0])]).T\n            Lw.setM(L)\n            \n    if simTime != 0:\n        pass\n    else:\n        simTime = 7\n        \n    T, U, R, xout, sol1, sol2 = simulation(mw,K,L,u,selu,period,simTime,X0w[0,0])\n    \n    if selu == 'step':\n        found = False\n        ST5 = 0\n        for i in range(len(T)):\n            if R[i] != 0:\n                if abs((xout[0][i]-R[i])/R[i]) <= 0.05 and not found:\n                    ST5 = T[i]\n                    found = True\n                if abs((xout[0][i]-R[i])/R[i]) > 0.05:\n                    found = False\n        OV = 0\n        for i in range(len(T)):\n            if R[i] != 0:\n                if R[0]>0:\n                    if (xout[0][i]-R[i]) > 0:\n                        if abs((xout[0][i]-R[i])/R[i])*100 > OV:\n                            OV = abs((xout[0][i]-R[i])/R[i])*100\n                else:\n                    if (xout[0][i]-R[i]) < 0:\n                        if abs((xout[0][i]-R[i])/R[i])*100 > OV:\n                            OV = abs((xout[0][i]-R[i])/R[i])*100\n    else:\n        ST5 = 'Nije definirano' \n        OV = 'Nije definirano'\n    print('Svojstvene vrijednosti sustava zatvorene petlje:',sol1)\n    print('Svojstvene vrijednosti promatra\u010da:',sol2)\n    print('Informacije o koraku: \\n\\tVrijeme smirivanja (5%) [s]=',ST5,'\\n\\tPrekora\u010denje (%)=',OV)\n    \n    fig = plt.figure(num='Simulation1', figsize=(14,12))\n    \n    fig.add_subplot(221)\n    plt.title('Izlazni odziv')\n    plt.ylabel('Izlaz [m]')\n    plt.plot(T,xout[0])\n    plt.plot(T,R,'g--')\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$y$','Reference'])\n    plt.grid()\n    \n    fig.add_subplot(222)\n    plt.title('Ulaz')\n    plt.ylabel('$u$ [N]')\n    plt.plot(T,U)\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.grid()\n    \n    fig.add_subplot(223)\n    plt.title('Odziv stanja')\n    plt.ylabel('Stanja')\n    plt.plot(T,xout[0],\n             T,xout[1],\n             T,xout[2])\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$x_{1}$','$x_{2}$','$x_{3}$'])\n    plt.grid()\n    \n    fig.add_subplot(224)\n    plt.title('Pogre\u0161ka procjene')\n    plt.ylabel('Pogre\u0161ka')\n    plt.plot(T,numpy.array(xout[1])-numpy.array(xout[4]))\n    plt.xlabel('$t$ [s]')\n    plt.axvline(x=0,color='black',linewidth=0.8)\n    plt.axhline(y=0,color='black',linewidth=0.8)\n    plt.legend(['$e_{2}$'])\n    plt.grid()\n    #plt.tight_layout()\n   \nalltogether2 = widgets.VBox([widgets.HBox([selm, \n                                          sele,\n                                          selu]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.Label('K:',border=3), Kw, \n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Svojstvene vrijednosti:',border=3), \n                                          eig1c, \n                                          eig2c, \n                                          eig3c,\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('X0 est.:',border=3), X0w]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([widgets.Label('L:',border=3), Lw, \n                                          widgets.Label(' ',border=3),\n                                          widgets.Label(' ',border=3),\n                                          widgets.Label('Svojstvene vrijednosti:',border=3), \n                                          eig1o, \n                                          eig2o,\n                                          widgets.Label(' ',border=3),\n                                          widgets.VBox([widgets.Label('Vrijeme simulacije [s]:',border=3)]),\n                                          widgets.VBox([simTime])]),\n                            widgets.Label(' ',border=3),\n                            widgets.HBox([u,\n                                          mw,\n                                          period, \n                                          START])])\nout2 = widgets.interactive_output(main_callback2, {'mw':mw, 'X0w':X0w, 'K':Kw, 'L':Lw,\n                                                 'eig1c':eig1c, 'eig2c':eig2c, 'eig3c':eig3c, 'eig1o':eig1o, 'eig2o':eig2o, \n                                                 'u':u, 'period':period, 'selm':selm, 'sele':sele, 'selu':selu, 'simTime':simTime, 'DW':DW})\nout2.layout.height = '860px'\ndisplay(out2, alltogether2)\n```\n\n\n    Output(layout=Layout(height='860px'))\n\n\n\n    VBox(children=(HBox(children=(Dropdown(index=1, options=('Postavi K i L', 'Postavi svojstvene vrijednosti'), v\u2026\n\n", "meta": {"hexsha": "28d142dac40b54249ef16f67a7e6dcbe7c6bc46a", "size": 26137, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_hr/examples/04/.ipynb_checkpoints/SS-47-Pneumatsko_upravljanje_polozaja-checkpoint.ipynb", "max_stars_repo_name": "ICCTerasmus/ICCT", "max_stars_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-22T18:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:10:22.000Z", "max_issues_repo_path": "ICCT_hr/examples/04/.ipynb_checkpoints/SS-47-Pneumatsko_upravljanje_polozaja-checkpoint.ipynb", "max_issues_repo_name": "ICCTerasmus/ICCT", "max_issues_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICCT_hr/examples/04/.ipynb_checkpoints/SS-47-Pneumatsko_upravljanje_polozaja-checkpoint.ipynb", "max_forks_repo_name": "ICCTerasmus/ICCT", "max_forks_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-24T11:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T16:36:18.000Z", "avg_line_length": 39.2447447447, "max_line_length": 570, "alphanum_fraction": 0.452462027, "converted": true, "num_tokens": 5848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414330889797, "lm_q2_score": 0.08151976155328808, "lm_q1q2_score": 0.021924041497213206}}
{"text": "<a href=\"https://colab.research.google.com/github/ChrizZhuang/marginalized_graph_kernel_protein/blob/main/Docking_0615.ipynb\" target=\"_parent\"></a>\n\n## Set up the environment\n\n\n```\n!nvidia-smi\n```\n\n    Tue Jun 15 01:26:38 2021       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 465.27       Driver Version: 460.32.03    CUDA Version: 11.2     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   46C    P8     9W /  70W |      0MiB / 15109MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    |  No running processes found                                                 |\n    +-----------------------------------------------------------------------------+\n\n\n\n```\n#!pip install pymatgen==2020.12.31\n!pip install pymatgen==2019.11.11\n!pip install --pre graphdot\n!pip install gdown\n```\n\n    Requirement already satisfied: pymatgen==2019.11.11 in /usr/local/lib/python3.7/dist-packages (2019.11.11)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.16.1)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (0.8.9)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (0.17.9)\n    Requirement already satisfied: scipy>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.4.1)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2021.6.10)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (3.3.0)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.23.0)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.5.1)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (3.2.2)\n    Requirement already satisfied: numpy>=1.14.3 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.19.5)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.1.5)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.7.1)\n    Requirement already satisfied: pydispatcher>=2.0.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.0.5)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen==2019.11.11) (0.2.2)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (1.24.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (2021.5.30)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (2.10)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.2->pymatgen==2019.11.11) (4.4.2)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (1.3.1)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen==2019.11.11) (2018.9)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->pymatgen==2019.11.11) (1.2.1)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from cycler>=0.10->matplotlib>=1.5->pymatgen==2019.11.11) (1.15.0)\n    Requirement already satisfied: graphdot in /usr/local/lib/python3.7/dist-packages (0.8a17)\n    Requirement already satisfied: pandas>=0.24 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.1.5)\n    Requirement already satisfied: mendeleev>=0.7 in /usr/local/lib/python3.7/dist-packages (from graphdot) (0.7.0)\n    Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.19.5)\n    Requirement already satisfied: kahypar>=1.1.4 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.1.6)\n    Requirement already satisfied: treelib>=1.6.1 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.6.1)\n    Requirement already satisfied: scipy>=1.3.0 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.4.1)\n    Requirement already satisfied: pycuda>=2019 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2021.1)\n    Requirement already satisfied: networkx>=2.4 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2.5.1)\n    Requirement already satisfied: tqdm>=4.55 in /usr/local/lib/python3.7/dist-packages (from graphdot) (4.61.1)\n    Requirement already satisfied: pymatgen==2019.11.11 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2019.11.11)\n    Requirement already satisfied: numba>=0.51.0 in /usr/local/lib/python3.7/dist-packages (from graphdot) (0.51.2)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.7.1)\n    Requirement already satisfied: ase>=3.17 in /usr/local/lib/python3.7/dist-packages (from graphdot) (3.21.1)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->graphdot) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->graphdot) (2018.9)\n    Requirement already satisfied: Pygments<3.0.0,>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (2.9.0)\n    Requirement already satisfied: SQLAlchemy<2.0.0,>=1.3.23 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (1.4.18)\n    Requirement already satisfied: six<2.0.0,>=1.15.0 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (1.15.0)\n    Requirement already satisfied: colorama<0.5.0,>=0.4.4 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (0.4.4)\n    Requirement already satisfied: pyfiglet<0.9,>=0.8.post1 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (0.8.post1)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from treelib>=1.6.1->graphdot) (0.16.0)\n    Requirement already satisfied: pytools>=2011.2 in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (2021.2.7)\n    Requirement already satisfied: appdirs>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (1.4.4)\n    Requirement already satisfied: mako in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (1.1.4)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.4->graphdot) (4.4.2)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2021.6.10)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (0.17.9)\n    Requirement already satisfied: pydispatcher>=2.0.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2.0.5)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (0.8.9)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (3.2.2)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (3.3.0)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2.23.0)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (1.16.1)\n    Requirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba>=0.51.0->graphdot) (0.34.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from numba>=0.51.0->graphdot) (57.0.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->graphdot) (1.2.1)\n    Requirement already satisfied: greenlet!=0.4.17; python_version >= \"3\" in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (1.1.0)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (4.5.0)\n    Requirement already satisfied: MarkupSafe>=0.9.2 in /usr/local/lib/python3.7/dist-packages (from mako->pycuda>=2019->graphdot) (2.0.1)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen==2019.11.11->graphdot) (0.2.2)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11->graphdot) (1.3.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11->graphdot) (0.10.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11->graphdot) (2.4.7)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (2021.5.30)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (2.10)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (3.4.1)\n    Requirement already satisfied: typing-extensions>=3.6.4; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (3.7.4.3)\n    Requirement already satisfied: gdown in /usr/local/lib/python3.7/dist-packages (3.6.4)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from gdown) (4.61.1)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from gdown) (2.23.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from gdown) (1.15.0)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (2021.5.30)\n\n\n\n```\n%matplotlib inline\nimport io\nimport sys\nsys.path.append('/usr/local/lib/python3.6/site-packages/')\nimport os\nimport urllib\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport graphdot\nfrom graphdot import Graph\nfrom graphdot.graph.adjacency import AtomicAdjacency\nfrom graphdot.graph.reorder import rcm\nfrom graphdot.kernel.marginalized import MarginalizedGraphKernel # https://graphdot.readthedocs.io/en/latest/apidoc/graphdot.kernel.marginalized.html\nfrom graphdot.kernel.marginalized.starting_probability import Uniform\nfrom graphdot.model.gaussian_process import (\n    GaussianProcessRegressor,\n    LowRankApproximateGPR\n)\nfrom graphdot.kernel.fix import Normalization\nimport graphdot.microkernel as uX\nimport ase.io\n\n# for getting all file names into a list under a directory \nfrom os import listdir\n# for getting file names that match certain pattern\nimport glob\nimport time\n```\n\n\n```\nfrom google.colab import drive\ndrive.mount('/content/gdrive', force_remount=True)\n```\n\n    Mounted at /content/gdrive\n\n\n\n```\n#cd gdrive/MyDrive/Google\\ Colab/Covid-Data\n%cd gdrive/MyDrive/Covid-Data/\n```\n\n    /content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data\n\n\n\n```\n!pwd\n```\n\n    /content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data\n\n\n## load the data\n\n\n```\nfiles  = ['uncharged_NSP15_6W01_A_3_H.Orderable_zinc_db_enaHLL.2col.csv.1.xz']\ndataset = pd.read_pickle(files[0]) # length of each csv file is 100000\n```\n\n\n```\ntarget = 'energy'\nN_train = 1000\nN_test = 2000\n\nnp.random.seed(0) # with the same seed, multiple runs can have the same selected index\ntrain_sel = np.random.choice(len(dataset), N_train, replace=False)\ntest_sel = np.random.choice(np.setxor1d(np.arange(len(dataset)), train_sel), N_test, replace=False)\ntrain = dataset.iloc[train_sel]\ntest = dataset.iloc[test_sel]\n```\n\n\n```\ntrain.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>energy</th>\n      <th>smiles</th>\n      <th>graphs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>3582</th>\n      <td>-2.874773</td>\n      <td>CN(Cc1nc(no1)c2cccc(c2)Br)C(=O)Nc3cccc(c3)OC</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>60498</th>\n      <td>-3.469760</td>\n      <td>CCOC(=O)c1ccc(c(c1)C)NC(=S)NCCOc2ccc(cc2)C</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>53227</th>\n      <td>-0.487984</td>\n      <td>Cc1ccc(cc1S(=O)(=O)Nc2ccccc2OC)NC(=O)c3nc4nc(c...</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>21333</th>\n      <td>-1.808283</td>\n      <td>COc1ccc(cc1OC)CCNC(=O)COc2ccc(cc2)[N@@](Cc3ccc...</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>3885</th>\n      <td>-2.457642</td>\n      <td>Cc1cc(ccc1NCc2ccc(c(c2OC)C)OC)Br</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### Baseline mode\n\n\n```\ngpr_base = GaussianProcessRegressor(\n    # kernel is the covariance function of the gaussian process (GP)\n    kernel=Normalization( # kernel equals to normalization -> normalizes a kernel using the cosine of angle formula, k_normalized(x,y) = k(x,y)/sqrt(k(x,x)*k(y,y))\n        # graphdot.kernel.fix.Normalization(kernel), set kernel as marginalized graph kernel, which is used to calculate the similarity between 2 graphs\n        # implement the random walk-based graph similarity kernel as Kashima, H., Tsuda, K., & Inokuchi, A. (2003). Marginalized kernels between labeled graphs. ICML\n        MarginalizedGraphKernel( \n            # node_kernel - A kernelet that computes the similarity between individual nodes\n            # uX - graphdot.microkernel - microkernels are positive-semidefinite functions between individual nodes and edges of graphs\n            node_kernel=uX.Additive( # addition of kernal matrices: sum of k_a(X_a, Y_a) cross for a in features\n                # uX.Constant - a kernel that returns a constant value, always mutlipled with other microkernels as an adjustable weight\n                #   c, the first input arg. as 0.5, (0.01, 10) the lower and upper bounds of c that is allowed to vary during hyperpara. optimizartion\n                # uX.KroneckerDelta - a kronecker delta returns 1 when two features are equal and return h (the first input arg here, which is 0.5 in this case) otherwise\n                #   (0.1, 0.9) the lower and upper bounds that h is allowed to vary during hyperpara. optimization\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 2nd element of graphdot.graph.Graph.nodes\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 3rd element of graphdot.graph.Graph.nodes\n                # uX.SquareExponential - Equ. 26 in the paper\n                # input arg. length_sacle is a float32, set as 1 in this case, which correspond to approx. 1 of the kernal value. \n                # This is used to determins how quicklys should the kernel decay to zero.\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0), # the 4th element of graphdot.graph.Graph.nodes\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 5th element of graphdot.graph.Graph.nodes\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0), # the 6th element of graphdot.graph.Graph.nodes\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 7th element of graphdot.graph.Graph.nodes\n                # uX.Convolution - a convolutional microkernel which averages evaluations of a base microkernel between pairs pf elememts of two variable-length feature sequences\n                # uX.KroneckerDelta as the base kernel\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9))) # the 8th element of graphdot.graph.Graph.nodes\n            ).normalized,\n            # edge_kernel - A kernelet that computes the similarity between individual edge\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 3rd element of graphdot.graph.Graph.nodes\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 4th element of graphdot.graph.Graph.nodes\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 5th element of graphdot.graph.Graph.nodes\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 6th element of graphdot.graph.Graph.nodes\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)) # the 7th element of graphdot.graph.Graph.nodes\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'), # the strating probability of the random walk on each node\n            q=0.05 # the probability for the random walk to stop during each step\n        )\n    ),\n    alpha=1e-4, # value added to the diagonal of the kernel matrix during fitting\n    optimizer=True, # default optimizer of L-BFGS-B based on scipy.optimize.minimize\n    normalize_y=True, # normalize the y values so taht the means and variance is 0 and 1, repsectively. Will be reversed when predicions are returned\n    regularization='+', # alpha (1e-4 in this case) is added to the diagonals of the kernal matrix\n)\n```\n\n\n```\ngpr_base.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  2.8725e+06|  2.4458e+07|  2.8798e+06|     -7290.9|  8.7024e+06|        22|      0.25|\n    |  1.9315e+06|  2.0707e+07|  1.9382e+06|     -6742.8|  8.0237e+06|        20|      0.24|\n    |  1.2905e+06|  1.5706e+07|  1.2968e+06|     -6252.2|  7.0835e+06|        19|      0.25|\n    |  1.0061e+06|  1.2309e+07|  1.0121e+06|     -5971.8|  6.4171e+06|        18|      0.24|\n    |  8.2557e+05|  9.7267e+06|  8.3132e+05|     -5755.4|  5.8209e+06|        17|      0.23|\n    |  7.1178e+05|  8.0789e+06|  7.1737e+05|     -5588.8|  5.3655e+06|        17|      0.25|\n    |  6.4897e+05|  7.1031e+06|  6.5446e+05|     -5488.6|  5.0424e+06|        17|      0.24|\n    |  6.2995e+05|   7.043e+06|  6.3539e+05|     -5435.7|  4.9627e+06|        17|      0.24|\n    |  6.1001e+05|  6.6424e+06|  6.1542e+05|     -5413.2|  4.8439e+06|        17|      0.24|\n    |   6.055e+05|  6.5416e+06|  6.1091e+05|     -5407.7|  4.7988e+06|        16|      0.24|\n    |  6.0285e+05|  6.4988e+06|  6.0825e+05|     -5402.9|  4.7885e+06|        16|      0.24|\n    |  6.0601e+05|  6.6651e+06|   6.114e+05|     -5395.9|  4.8317e+06|        17|      0.25|\n    |  6.0087e+05|  6.5216e+06|  6.0626e+05|     -5395.1|  4.7916e+06|        17|      0.24|\n    |  5.9979e+05|  6.4968e+06|  6.0518e+05|     -5393.3|  4.7859e+06|        17|      0.24|\n    |  5.9795e+05|  6.4537e+06|  6.0334e+05|     -5390.4|  4.7776e+06|        17|      0.26|\n    |  5.9632e+05|   6.417e+06|  6.0171e+05|     -5388.7|  4.7579e+06|        16|      0.23|\n    |  5.9535e+05|  6.4032e+06|  6.0074e+05|     -5387.3|  4.7491e+06|        16|      0.25|\n    |  5.9515e+05|  6.4246e+06|  6.0054e+05|     -5386.3|  4.7503e+06|        17|      0.24|\n    |  5.9519e+05|  6.4222e+06|  6.0058e+05|     -5386.6|  4.7481e+06|        17|      0.25|\n    |  5.9528e+05|  6.4269e+06|  6.0067e+05|     -5386.3|  4.7487e+06|        17|      0.25|\n    |  5.9518e+05|  6.4251e+06|  6.0056e+05|     -5386.3|   4.747e+06|        17|      0.24|\n    |  5.9522e+05|  6.4263e+06|  6.0061e+05|     -5386.3|   4.748e+06|        17|      0.24|\n    |  5.9521e+05|  6.4261e+06|   6.006e+05|     -5386.3|  4.7459e+06|        17|      0.24|\n    |  5.9521e+05|  6.4263e+06|   6.006e+05|     -5386.3|  4.7474e+06|        17|      0.25|\n    |  5.9516e+05|  6.4253e+06|  6.0055e+05|     -5386.2|  4.7489e+06|        17|      0.25|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  1.7413e+06|  2.1782e+07|   1.748e+06|       -6644|  7.5158e+06|        20|      0.24|\n    |  1.3451e+06|  1.6773e+07|  1.3514e+06|     -6332.3|  6.9251e+06|        19|      0.25|\n    |   1.033e+06|  1.3306e+07|  1.0391e+06|     -6026.9|  6.3155e+06|        19|      0.24|\n    |  7.9866e+05|  1.0452e+07|  8.0437e+05|     -5717.2|  5.7392e+06|        19|      0.26|\n    |  6.9752e+05|  8.1836e+06|  7.0309e+05|     -5576.4|   5.318e+06|        17|      0.26|\n    |  6.4289e+05|   7.195e+06|  6.4837e+05|     -5481.7|  5.0649e+06|        17|      0.23|\n    |   6.153e+05|  6.7608e+06|  6.2073e+05|     -5430.1|  4.8862e+06|        17|      0.24|\n    |  6.1229e+05|  6.6746e+06|  6.1772e+05|     -5421.4|  4.8115e+06|        16|      0.24|\n    |  5.9982e+05|  6.4991e+06|  6.0522e+05|     -5399.3|  4.7705e+06|        16|      0.23|\n    |  5.9655e+05|  6.4385e+06|  6.0194e+05|     -5390.8|  4.7638e+06|        17|      0.23|\n    |  5.9622e+05|  6.4295e+06|  6.0161e+05|       -5390|  4.7603e+06|        16|      0.25|\n    |  5.9531e+05|  6.4019e+06|   6.007e+05|     -5388.4|  4.7574e+06|        16|      0.26|\n    |  5.9498e+05|  6.3961e+06|  6.0037e+05|     -5387.3|  4.7535e+06|        16|      0.25|\n    |  5.9726e+05|  6.5117e+06|  6.0264e+05|     -5385.9|  4.7837e+06|        17|      0.24|\n    |  5.9475e+05|  6.4136e+06|  6.0013e+05|     -5385.8|  4.7581e+06|        17|      0.24|\n    |  5.9453e+05|   6.402e+06|  5.9992e+05|       -5386|  4.7582e+06|        16|      0.24|\n    |  5.9439e+05|   6.409e+06|  5.9978e+05|     -5385.3|  4.7563e+06|        17|      0.24|\n    |  5.9419e+05|  6.4005e+06|  5.9957e+05|     -5385.6|  4.7549e+06|        17|      0.25|\n    |  5.9386e+05|  6.3824e+06|  5.9925e+05|     -5386.6|  4.7468e+06|        16|      0.25|\n    |  5.9362e+05|  6.3753e+06|  5.9901e+05|     -5386.7|  4.7493e+06|        16|      0.24|\n    |  5.9322e+05|  6.3676e+06|  5.9861e+05|     -5387.2|  4.7601e+06|        16|      0.25|\n    |  5.9311e+05|   6.373e+06|  5.9849e+05|     -5386.5|  4.7591e+06|        16|      0.26|\n    |  5.9318e+05|  6.3877e+06|  5.9857e+05|     -5385.4|  4.7644e+06|        17|      0.25|\n    |  5.9334e+05|  6.3815e+06|  5.9873e+05|     -5386.2|  4.7579e+06|        16|      0.23|\n    |  5.9312e+05|  6.3728e+06|  5.9851e+05|     -5386.5|  4.7571e+06|        16|      0.25|\n    |  5.9326e+05|  6.3759e+06|  5.9864e+05|     -5386.5|  4.7563e+06|        16|      0.25|\n    |  5.9319e+05|  6.3747e+06|  5.9858e+05|     -5386.5|  4.7585e+06|        16|      0.24|\n    |  5.9323e+05|  6.3755e+06|  5.9862e+05|     -5386.5|  4.7595e+06|        16|      0.25|\n    |  5.9327e+05|  6.3764e+06|  5.9866e+05|     -5386.5|  4.7575e+06|        16|      0.24|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  3.4092e+06|  2.5343e+07|  3.4168e+06|     -7528.5|  8.7203e+06|        20|      0.24|\n    |  2.2467e+06|  2.1995e+07|  2.2536e+06|     -6926.8|  8.0939e+06|        19|      0.25|\n    |  1.4704e+06|  1.6957e+07|  1.4768e+06|     -6399.5|  7.2075e+06|        19|      0.24|\n    |  1.1068e+06|  1.3411e+07|  1.1129e+06|     -6074.4|  6.5417e+06|        18|      0.23|\n    |  8.6387e+05|  1.0661e+07|  8.6966e+05|     -5795.5|   5.954e+06|        18|      0.25|\n    |  7.4225e+05|  8.8175e+06|  7.4788e+05|     -5630.3|  5.5341e+06|        18|      0.24|\n    |  6.7235e+05|  7.6658e+06|  6.7787e+05|     -5526.8|  5.2141e+06|        17|      0.25|\n    |  6.3387e+05|  7.1558e+06|  6.3932e+05|     -5448.8|  4.9899e+06|        17|      0.24|\n    |  6.1335e+05|  6.7496e+06|  6.1877e+05|     -5423.9|  4.8814e+06|        17|      0.24|\n    |  6.1076e+05|  6.7056e+06|  6.1618e+05|     -5418.4|   4.863e+06|        17|      0.25|\n    |  6.0468e+05|  6.6012e+06|  6.1008e+05|     -5406.1|  4.8233e+06|        17|      0.23|\n    |  5.9819e+05|  6.4569e+06|  6.0358e+05|     -5396.3|   4.775e+06|        17|      0.23|\n    |   5.968e+05|  6.4322e+06|  6.0219e+05|     -5392.3|  4.7729e+06|        17|      0.24|\n    |  5.9554e+05|    6.42e+06|  6.0093e+05|       -5389|  4.7546e+06|        17|      0.23|\n    |  5.9516e+05|  6.4092e+06|  6.0054e+05|     -5386.2|  4.7716e+06|        17|      0.23|\n    |  5.9485e+05|  6.4051e+06|  6.0024e+05|     -5386.6|  4.7631e+06|        17|      0.24|\n    |  5.9451e+05|  6.4007e+06|   5.999e+05|       -5387|  4.7598e+06|        17|      0.25|\n    |  5.9416e+05|  6.3958e+06|  5.9954e+05|       -5387|  4.7533e+06|        17|      0.25|\n    |  5.9357e+05|  6.3871e+06|  5.9896e+05|     -5386.8|   4.753e+06|        17|      0.25|\n    |  5.9331e+05|  6.3992e+06|   5.987e+05|     -5386.3|  4.7538e+06|        17|      0.24|\n    |  5.9325e+05|  6.3912e+06|  5.9863e+05|     -5386.2|  4.7553e+06|        17|      0.26|\n    |   5.931e+05|  6.3778e+06|  5.9848e+05|       -5386|  4.7619e+06|        16|      0.23|\n    |   5.931e+05|  6.3773e+06|  5.9848e+05|     -5385.9|  4.7602e+06|        17|      0.24|\n    |  5.9305e+05|  6.3763e+06|  5.9843e+05|       -5386|  4.7597e+06|        17|      0.24|\n    |  5.9304e+05|  6.3762e+06|  5.9843e+05|       -5386|  4.7621e+06|        17|      0.24|\n    |  5.9307e+05|   6.377e+06|  5.9846e+05|       -5386|  4.7615e+06|        16|      0.23|\n    |  5.9304e+05|  6.3761e+06|  5.9843e+05|     -5385.9|  4.7637e+06|        17|      0.26|\n    |  5.9299e+05|  6.3766e+06|  5.9838e+05|     -5385.9|  4.7612e+06|        17|      0.24|\n    |  5.9306e+05|  6.3801e+06|  5.9844e+05|     -5385.9|  4.7599e+06|        17|      0.24|\n    |  5.9295e+05|  6.3753e+06|  5.9834e+05|     -5385.9|  4.7634e+06|        16|      0.25|\n    |  5.9296e+05|  6.3752e+06|  5.9834e+05|     -5385.9|  4.7608e+06|        17|      0.23|\n    |  5.9309e+05|   6.378e+06|  5.9847e+05|     -5385.9|  4.7631e+06|        16|      0.24|\n    Optimization result:\n          fun: 593087.1156402231\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 6.37396256e+02,  1.29403894e+02,  1.71592132e+01,  7.87202241e+02,\n            1.37346463e+04,  2.83923867e+02,  0.00000000e+00, -9.41929416e+01,\n            8.31120362e+01, -9.89697568e+02,  1.85028746e-02,  1.18859915e+02,\n            5.20268298e+01, -2.37801534e+02,  1.76013556e+04, -5.72112693e+01,\n            1.61763990e+03, -2.77147646e+02,  3.02784539e+03,  2.61391651e+02,\n            2.67337779e+02,  5.39630844e+01,  0.00000000e+00,  1.97901890e+01,\n            2.39186447e+02])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 32\n          nit: 25\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -2.30258509,  1.47773763, -2.30258509,\n           -4.60517019,  1.38836933, -3.83292358, -2.25417628,  2.30258509,\n           -1.84636793, -3.87778892, -2.30258509,  1.7180289 , -2.30258509,\n            1.52931263, -2.30258509,  2.15048481, -2.30258509, -0.16374951,\n           -2.30258509, -4.06382248, -0.19078879, -0.36875751, -2.30258509])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7fa8f0b23690>\n\n\n\n\n```\n#gpr_base.kernel.hyperparameters\n```\n\n\n```\nmu = gpr_base.predict(train.graphs)\n```\n\n\n```\nplt.scatter(train[target], mu)\nplt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\nplt.xlim(-9, 3)\nplt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.1026528897885943\n    RMSE: 0.1559697478035153\n\n\n\n```\nmu_test = gpr_base.predict(test.graphs)\n```\n\n\n```\nplt.scatter(test[target], mu_test)\nplt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\nplt.xlim(-9, 3)\nplt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 1.3984523944497356\n    RMSE: 1.7902476214464011\n\n\n### Model 2\n\n\n```\ngpr2 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-5, #different from gpr in alpha where gpr_base alpha is 1e-4\n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr2.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  3.9342e+06|  7.4014e+07|  3.9413e+06|     -7048.5|  4.2676e+07|        20|      0.25|\n    |  2.5581e+06|  4.8127e+07|  2.5648e+06|     -6637.5|   3.185e+07|        19|      0.26|\n    |  1.9651e+06|  3.6386e+07|  1.9715e+06|     -6391.2|  2.5862e+07|        19|      0.25|\n    |  1.4839e+06|  2.6275e+07|  1.4901e+06|     -6132.7|  2.0389e+07|        19|      0.25|\n    |  1.1925e+06|  1.9644e+07|  1.1985e+06|     -5931.7|  1.6716e+07|        18|      0.25|\n    |  9.9823e+05|  1.5219e+07|   1.004e+06|     -5762.3|  1.4068e+07|        17|      0.25|\n    |   8.735e+05|  1.2618e+07|  8.7912e+05|     -5627.6|  1.2412e+07|        17|      0.25|\n    |   8.215e+05|  1.1223e+07|  8.2708e+05|     -5576.1|  1.1158e+07|        16|      0.25|\n    |  7.7928e+05|  1.0614e+07|  7.8479e+05|     -5517.2|   1.082e+07|        17|      0.25|\n    |  7.6384e+05|  1.0397e+07|  7.6934e+05|     -5493.1|  1.0717e+07|        17|      0.25|\n    |  7.5683e+05|  1.0246e+07|  7.6232e+05|     -5483.1|  1.0625e+07|        17|      0.26|\n    |  7.8307e+05|  1.0957e+07|  7.8857e+05|     -5492.5|  1.1369e+07|        17|      0.25|\n    |  7.5592e+05|  1.0264e+07|   7.614e+05|       -5479|  1.0686e+07|        17|      0.26|\n    |  7.5278e+05|  1.0169e+07|  7.5826e+05|     -5475.4|  1.0618e+07|        17|      0.26|\n    |  7.5039e+05|  1.0088e+07|  7.5587e+05|     -5472.2|  1.0571e+07|        17|      0.25|\n    |  7.4793e+05|  1.0005e+07|   7.534e+05|     -5470.1|  1.0495e+07|        16|      0.27|\n    |  7.4681e+05|  9.9805e+06|  7.5228e+05|     -5468.4|  1.0454e+07|        16|      0.25|\n    |  7.4544e+05|  9.9933e+06|   7.509e+05|     -5465.7|  1.0403e+07|        17|      0.25|\n    |  7.4519e+05|  9.9849e+06|  7.5065e+05|     -5466.5|  1.0374e+07|        16|      0.25|\n    |  7.4522e+05|  9.9838e+06|  7.5069e+05|     -5466.8|  1.0376e+07|        17|      0.27|\n    |  7.4542e+05|   9.991e+06|  7.5089e+05|     -5466.6|  1.0371e+07|        17|      0.25|\n    |  7.4539e+05|  9.9914e+06|  7.5086e+05|     -5466.5|  1.0373e+07|        17|      0.27|\n    |  7.4543e+05|  9.9918e+06|   7.509e+05|     -5466.5|  1.0368e+07|        16|      0.25|\n    |   7.451e+05|  9.9824e+06|  7.5057e+05|     -5466.5|  1.0392e+07|        16|      0.27|\n    |  7.4524e+05|  9.9871e+06|   7.507e+05|     -5466.5|   1.037e+07|        17|      0.27|\n    |  7.4525e+05|  9.9861e+06|  7.5072e+05|     -5466.5|  1.0386e+07|        17|      0.27|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  2.2754e+06|  4.0939e+07|   2.282e+06|     -6573.6|    2.42e+07|        18|      0.25|\n    |  1.7565e+06|  3.1259e+07|  1.7628e+06|     -6332.7|  2.0381e+07|        18|      0.24|\n    |  1.2573e+06|   2.224e+07|  1.2633e+06|       -6009|  1.6215e+07|        19|      0.25|\n    |    1.05e+06|  1.7608e+07|  1.0558e+06|     -5820.4|  1.4598e+07|        18|      0.25|\n    |  8.9771e+05|  1.3272e+07|  9.0338e+05|     -5669.2|  1.2572e+07|        17|      0.27|\n    |  8.1417e+05|  1.1552e+07|  8.1973e+05|     -5559.9|  1.1683e+07|        17|      0.25|\n    |  7.8461e+05|  1.0854e+07|  7.9014e+05|     -5523.1|  1.1122e+07|        17|      0.26|\n    |  7.6515e+05|  1.0363e+07|  7.7064e+05|     -5496.3|  1.0598e+07|        17|      0.26|\n    |   7.549e+05|  1.0202e+07|  7.6038e+05|     -5480.5|  1.0455e+07|        17|      0.27|\n    |  7.5113e+05|   1.013e+07|   7.566e+05|     -5473.3|  1.0408e+07|        17|      0.25|\n    |  7.4842e+05|   1.001e+07|  7.5389e+05|     -5468.3|  1.0405e+07|        16|      0.25|\n    |  7.4817e+05|  1.0021e+07|  7.5363e+05|     -5467.8|  1.0392e+07|        16|      0.27|\n    |  7.4743e+05|  1.0028e+07|   7.529e+05|     -5467.3|  1.0359e+07|        17|      0.26|\n    |  7.4775e+05|   1.007e+07|  7.5321e+05|     -5465.8|   1.042e+07|        17|      0.26|\n    |  7.4729e+05|  1.0032e+07|  7.5276e+05|     -5466.8|  1.0374e+07|        17|      0.26|\n    |  7.4778e+05|  1.0071e+07|  7.5325e+05|       -5466|  1.0404e+07|        17|      0.26|\n    |  7.4737e+05|  1.0035e+07|  7.5284e+05|     -5466.8|  1.0383e+07|        17|      0.26|\n    |  7.4755e+05|  1.0041e+07|  7.5301e+05|     -5466.8|  1.0372e+07|        17|      0.25|\n    |  7.4755e+05|   1.004e+07|  7.5302e+05|     -5466.8|  1.0377e+07|        17|      0.26|\n    |   7.475e+05|  1.0039e+07|  7.5297e+05|     -5466.8|   1.037e+07|        17|      0.25|\n    |  7.4752e+05|  1.0039e+07|  7.5298e+05|     -5466.8|  1.0365e+07|        16|      0.26|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  5.5724e+06|  1.0057e+08|  5.5798e+06|     -7408.4|  5.0139e+07|        19|      0.24|\n    |  3.3661e+06|  6.0838e+07|   3.373e+06|     -6905.1|  3.6581e+07|        19|      0.24|\n    |  2.6218e+06|  4.7142e+07|  2.6285e+06|     -6665.4|  3.0491e+07|        18|      0.24|\n    |  1.8232e+06|  3.1903e+07|  1.8296e+06|     -6322.8|  2.3196e+07|        18|      0.27|\n    |  1.4038e+06|  2.3742e+07|  1.4099e+06|     -6073.7|  1.9114e+07|        18|      0.25|\n    |   1.145e+06|  1.8596e+07|  1.1509e+06|     -5877.2|  1.6369e+07|        18|      0.24|\n    |   9.735e+05|  1.4838e+07|  9.7923e+05|     -5727.6|  1.4079e+07|        17|      0.24|\n    |  8.7366e+05|  1.2752e+07|  8.7928e+05|     -5625.4|  1.2581e+07|        17|      0.24|\n    |  8.0328e+05|  1.1112e+07|  8.0883e+05|     -5549.3|  1.1228e+07|        17|      0.24|\n    |  7.8049e+05|  1.0893e+07|  7.8599e+05|     -5501.9|  1.1205e+07|        17|      0.26|\n    |  7.7098e+05|  1.0617e+07|  7.7648e+05|     -5498.4|  1.0918e+07|        17|      0.25|\n    |  7.6746e+05|  1.0503e+07|  7.7296e+05|       -5497|  1.0782e+07|        17|      0.28|\n    |  7.6154e+05|  1.0323e+07|  7.6703e+05|       -5492|  1.0603e+07|        17|      0.25|\n    |  7.5364e+05|  1.0183e+07|  7.5912e+05|     -5479.7|  1.0515e+07|        17|      0.25|\n    |  7.4872e+05|  1.0065e+07|  7.5419e+05|     -5471.1|   1.047e+07|        17|      0.24|\n    |  7.4729e+05|  1.0013e+07|  7.5276e+05|     -5469.1|  1.0422e+07|        17|      0.25|\n    |  7.4597e+05|  9.9721e+06|  7.5143e+05|     -5467.8|  1.0406e+07|        16|      0.24|\n    |  7.4535e+05|   9.987e+06|  7.5081e+05|     -5465.9|  1.0431e+07|        16|      0.24|\n    |  7.4442e+05|  9.9833e+06|  7.4989e+05|     -5465.8|  1.0408e+07|        17|      0.25|\n    |  7.4428e+05|  9.9827e+06|  7.4975e+05|     -5466.5|  1.0397e+07|        17|      0.24|\n    |  7.4425e+05|  9.9819e+06|  7.4972e+05|     -5466.9|  1.0382e+07|        16|      0.24|\n    |  7.4408e+05|   9.975e+06|  7.4955e+05|       -5467|  1.0385e+07|        16|      0.24|\n    |  7.4382e+05|  9.9587e+06|  7.4928e+05|       -5467|  1.0402e+07|        17|      0.25|\n    |  7.4399e+05|  9.9658e+06|  7.4946e+05|     -5466.8|   1.041e+07|        16|      0.24|\n    |   7.442e+05|   9.971e+06|  7.4967e+05|       -5467|  1.0428e+07|        17|      0.26|\n    |   7.442e+05|  9.9718e+06|  7.4967e+05|       -5467|  1.0405e+07|        17|      0.26|\n    |   7.438e+05|  9.9587e+06|  7.4927e+05|       -5467|  1.0409e+07|        16|      0.26|\n    |  7.4399e+05|   9.964e+06|  7.4946e+05|       -5467|  1.0401e+07|        17|      0.26|\n    |  7.4412e+05|  9.9681e+06|  7.4959e+05|       -5467|  1.0399e+07|        16|      0.25|\n    Optimization result:\n          fun: 744121.6320021643\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 9.96227102e+02,  2.00432837e+02,  2.60510180e+01, -5.48958596e+02,\n            2.06815585e+04,  4.34825299e+02,  0.00000000e+00, -3.24741237e+02,\n            1.95474293e+02,  1.10656164e+03,  0.00000000e+00,  1.22750805e+02,\n            6.73673262e+01, -1.00813058e+03,  2.60017795e+04, -2.51396161e+01,\n            2.21848468e+03, -5.02235333e+02,  4.39914545e+03,  6.69241667e+01,\n            3.26864116e+02,  7.34901570e+01,  0.00000000e+00,  3.90059610e+02,\n            3.90397116e+02])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 29\n          nit: 23\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -2.30258509,  1.45132733, -2.30258509,\n           -4.60517019,  1.38836933, -3.41134142, -2.30258509,  2.29909486,\n           -6.69419395, -4.08788863, -2.30258509,  1.6789475 , -2.30258509,\n            1.54064497, -2.30258509,  2.21314656, -2.30258509, -0.35101412,\n           -2.30258509, -4.06327129, -0.19078879, -0.09102722, -2.30258509])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7fa8dbae75d0>\n\n\n\n\n```\nmu = gpr2.predict(train.graphs)\nplt.scatter(train[target], mu)\nplt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\nplt.xlim(-9, 3)\nplt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.01420440124959926\n    RMSE: 0.021649804308151027\n\n\n\n```\nmu_test = gpr2.predict(test.graphs)\nplt.scatter(test[target], mu_test)\nplt.plot(np.linspace(-10, 4), np.linspace(-10, 4), c = 'r')\nplt.xlim(-10, 4)\nplt.ylim(-10, 4)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 1.517212238428167\n    RMSE: 1.943288841802438\n\n\n### Model 3\n\n\n```\ngpr3 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-3, #different from gpr in alpha where gpr_base's alpha is 1e-4\n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr3.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  5.2754e+05|  1.7773e+06|  5.3362e+05|     -6084.7|  9.0549e+05|        25|      0.28|\n    |  4.4224e+05|  1.9515e+06|  4.4805e+05|     -5808.2|  8.7902e+05|        20|      0.27|\n    |  3.1405e+05|  1.8185e+06|  3.1934e+05|     -5298.7|  8.0593e+05|        18|      0.24|\n    |  2.8469e+05|  1.6176e+06|  2.8985e+05|       -5163|  7.8268e+05|        17|      0.26|\n    |  2.6118e+05|  1.4683e+06|  2.6622e+05|     -5042.3|  7.5644e+05|        17|      0.24|\n    |  2.5267e+05|  1.3881e+06|  2.5767e+05|     -4997.8|  7.4692e+05|        16|      0.26|\n    |   2.496e+05|  1.3914e+06|  2.5458e+05|       -4978|  7.4218e+05|        17|      0.25|\n    |  2.4851e+05|  1.3833e+06|  2.5349e+05|     -4971.9|  7.4096e+05|        17|      0.25|\n    |  2.4817e+05|  1.3928e+06|  2.5314e+05|     -4967.6|  7.3437e+05|        17|      0.24|\n    |  2.4724e+05|  1.3771e+06|  2.5221e+05|     -4964.6|  7.3871e+05|        17|      0.23|\n    |  2.4712e+05|  1.3738e+06|  2.5208e+05|     -4964.4|  7.3983e+05|        17|       0.3|\n    |  2.4696e+05|  1.3707e+06|  2.5192e+05|     -4963.8|  7.4051e+05|        17|      0.26|\n    |  2.4668e+05|  1.3678e+06|  2.5164e+05|     -4962.6|  7.4057e+05|        17|      0.26|\n    |  2.4641e+05|  1.3713e+06|  2.5137e+05|       -4960|   7.393e+05|        17|      0.24|\n    |  2.4626e+05|  1.3699e+06|  2.5122e+05|     -4959.3|  7.3801e+05|        17|      0.24|\n    |  2.4623e+05|  1.3693e+06|  2.5119e+05|     -4959.3|  7.3765e+05|        17|      0.24|\n    |  2.4624e+05|  1.3696e+06|   2.512e+05|     -4959.2|  7.3767e+05|        17|      0.25|\n    |  2.4624e+05|  1.3693e+06|   2.512e+05|     -4959.3|  7.3763e+05|        17|      0.24|\n    |  2.4623e+05|  1.3693e+06|  2.5119e+05|     -4959.3|  7.3758e+05|        17|      0.24|\n    |  2.4624e+05|  1.3693e+06|   2.512e+05|     -4959.3|   7.377e+05|        17|      0.26|\n    |  2.4624e+05|  1.3693e+06|   2.512e+05|     -4959.3|  7.3766e+05|        17|      0.28|\n    |  2.4624e+05|  1.3694e+06|   2.512e+05|     -4959.3|  7.3766e+05|        17|      0.26|\n    |  2.4623e+05|  1.3692e+06|  2.5119e+05|     -4959.3|  7.3767e+05|        17|      0.26|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  4.3132e+05|  2.1991e+06|  4.3709e+05|     -5766.2|  8.8044e+05|        20|      0.23|\n    |  3.8205e+05|  2.0562e+06|  3.8763e+05|     -5587.8|  8.5782e+05|        19|      0.23|\n    |  3.1542e+05|  1.9024e+06|  3.2073e+05|     -5313.3|  8.2092e+05|        19|      0.25|\n    |  2.8239e+05|  1.7354e+06|  2.8753e+05|     -5138.7|  7.6999e+05|        19|      0.24|\n    |  2.5844e+05|  1.4472e+06|  2.6347e+05|     -5032.7|  7.6497e+05|        17|      0.25|\n    |  2.5462e+05|   1.423e+06|  2.5963e+05|     -5010.1|  7.5654e+05|        17|      0.24|\n    |  2.4941e+05|  1.3953e+06|  2.5438e+05|     -4977.7|  7.4492e+05|        17|      0.23|\n    |  2.4782e+05|  1.3818e+06|  2.5279e+05|     -4968.9|  7.3616e+05|        17|      0.24|\n    |  2.4685e+05|  1.3767e+06|  2.5181e+05|     -4963.2|  7.3744e+05|        17|      0.23|\n    |  2.4666e+05|  1.3771e+06|  2.5162e+05|     -4960.4|  7.3963e+05|        17|      0.25|\n    |  2.4631e+05|  1.3714e+06|  2.5127e+05|     -4959.9|  7.3887e+05|        17|      0.23|\n    |  2.4624e+05|  1.3688e+06|   2.512e+05|     -4960.1|  7.3878e+05|        17|      0.23|\n    |  2.4618e+05|  1.3657e+06|  2.5114e+05|     -4960.1|  7.3874e+05|        17|      0.23|\n    |  2.4615e+05|  1.3645e+06|  2.5111e+05|     -4959.9|  7.3868e+05|        17|      0.25|\n    |  2.4608e+05|  1.3633e+06|  2.5103e+05|     -4959.5|  7.3863e+05|        17|      0.23|\n    |  2.4597e+05|  1.3625e+06|  2.5093e+05|     -4958.9|  7.3829e+05|        17|      0.23|\n    |  2.4593e+05|  1.3645e+06|  2.5089e+05|     -4958.5|   7.376e+05|        17|      0.25|\n    |  2.4589e+05|  1.3641e+06|  2.5085e+05|     -4958.3|  7.3836e+05|        17|      0.24|\n    |  2.4588e+05|  1.3646e+06|  2.5084e+05|     -4958.2|  7.3802e+05|        17|      0.23|\n    |  2.4585e+05|  1.3647e+06|  2.5081e+05|     -4958.2|  7.3765e+05|        17|      0.28|\n    |  2.4581e+05|  1.3635e+06|  2.5077e+05|     -4958.3|  7.3747e+05|        17|      0.25|\n    |  2.4579e+05|  1.3623e+06|  2.5074e+05|     -4958.3|  7.3782e+05|        17|      0.25|\n    |  2.4577e+05|   1.359e+06|  2.5073e+05|     -4958.8|  7.3883e+05|        17|      0.27|\n    |  2.4576e+05|  1.3601e+06|  2.5072e+05|     -4958.6|   7.387e+05|        17|      0.24|\n    |  2.4576e+05|  1.3607e+06|  2.5072e+05|     -4958.5|  7.3859e+05|        17|      0.23|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  5.7164e+05|  1.6233e+06|  5.7783e+05|     -6194.5|  8.9548e+05|        21|      0.25|\n    |  4.7796e+05|  1.8426e+06|  4.8386e+05|     -5904.1|  8.7295e+05|        20|      0.26|\n    |  3.3798e+05|  1.8581e+06|  3.4337e+05|     -5394.5|  8.2045e+05|        18|      0.24|\n    |  2.9137e+05|  1.7091e+06|  2.9656e+05|     -5188.7|  7.8714e+05|        19|      0.23|\n    |  2.6899e+05|  1.5524e+06|  2.7408e+05|     -5081.7|  7.6873e+05|        18|      0.25|\n    |  2.5569e+05|  1.4244e+06|  2.6071e+05|     -5015.7|  7.5632e+05|        17|      0.25|\n    |  2.5073e+05|  1.4143e+06|  2.5571e+05|     -4982.2|  7.4341e+05|        18|      0.25|\n    |  2.4974e+05|  1.4008e+06|  2.5472e+05|     -4979.3|  7.4547e+05|        17|      0.23|\n    |  2.4886e+05|  1.3879e+06|  2.5384e+05|     -4975.9|  7.4569e+05|        17|      0.24|\n    |  2.4798e+05|  1.3761e+06|  2.5295e+05|     -4971.5|  7.4426e+05|        17|      0.23|\n    |  2.4717e+05|   1.378e+06|  2.5214e+05|     -4965.5|  7.4085e+05|        17|      0.27|\n    |  2.4669e+05|  1.3741e+06|  2.5166e+05|     -4962.6|  7.3887e+05|        17|      0.24|\n    |   2.464e+05|  1.3657e+06|  2.5136e+05|     -4960.9|   7.412e+05|        17|      0.23|\n    |  2.4628e+05|  1.3668e+06|  2.5124e+05|     -4960.5|  7.3916e+05|        17|      0.25|\n    |  2.4624e+05|  1.3678e+06|   2.512e+05|     -4960.2|  7.3857e+05|        17|      0.23|\n    |  2.4619e+05|  1.3698e+06|  2.5115e+05|     -4959.9|  7.3793e+05|        17|      0.24|\n    |  2.4614e+05|  1.3703e+06|   2.511e+05|     -4959.6|  7.3771e+05|        17|      0.24|\n    |  2.4595e+05|  1.3683e+06|  2.5091e+05|     -4959.1|  7.3767e+05|        17|      0.24|\n    |  2.4602e+05|  1.3688e+06|  2.5098e+05|     -4958.9|  7.3875e+05|        17|      0.24|\n    |  2.4592e+05|  1.3683e+06|  2.5088e+05|     -4958.9|  7.3796e+05|        17|      0.23|\n    |  2.4589e+05|  1.3655e+06|  2.5085e+05|       -4959|  7.3856e+05|        17|      0.24|\n    |  2.4586e+05|  1.3623e+06|  2.5082e+05|     -4959.2|  7.3918e+05|        17|      0.24|\n    |  2.4584e+05|  1.3616e+06|   2.508e+05|     -4959.3|  7.3917e+05|        17|      0.24|\n    |  2.4583e+05|  1.3615e+06|  2.5079e+05|     -4959.3|  7.3903e+05|        17|      0.23|\n    |  2.4579e+05|  1.3614e+06|  2.5075e+05|     -4959.3|  7.3865e+05|        17|      0.24|\n    |  2.4578e+05|   1.362e+06|  2.5074e+05|     -4959.2|  7.3874e+05|        17|      0.24|\n    |  2.4576e+05|  1.3621e+06|  2.5072e+05|     -4959.1|   7.391e+05|        17|      0.23|\n    |  2.4576e+05|  1.3624e+06|  2.5072e+05|     -4959.1|  7.3901e+05|        17|      0.27|\n    Optimization result:\n          fun: 245757.64498811733\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 1.35950050e+02,  3.77357938e+01,  1.05734705e+01, -2.13075274e+01,\n            3.36341811e+03,  6.74591558e+01,  0.00000000e+00,  1.41114101e+00,\n            7.33894523e+00, -1.51578382e+02,  0.00000000e+00,  1.62796677e+01,\n            5.68562303e+00,  5.22025613e+01,  4.39601078e+03, -3.71667507e+01,\n            5.31204650e+02,  1.71062274e+01,  6.87112378e+02,  6.34393286e+01,\n            7.78485000e+01,  1.29002790e+01,  0.00000000e+00, -5.61367681e+01,\n            4.45773454e+01])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 25\n          nit: 24\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -1.33774258,  1.50058885, -2.30258509,\n           -4.60517019, -0.21165109, -4.60517019, -2.30258509,  2.2686602 ,\n           -4.07543091, -4.60517019, -2.30258509,  1.77034144, -2.30258509,\n            1.30229701, -2.30258509,  1.57009793, -2.30258509, -0.52372387,\n           -2.30258509, -4.60517019, -0.10536052, -1.31858519, -2.30258509])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7fb9a0f83150>\n\n\n\n\n```\nmu = gpr3.predict(train.graphs)\nplt.scatter(train[target], mu)\n#plt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\n#plt.xlim(-9, 3)\n#plt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.3711113759832458\n    RMSE: 0.5245520571276874\n\n\n\n```\nmu_test = gpr3.predict(test.graphs)\nplt.scatter(test[target], mu_test)\n#plt.plot(np.linspace(-10, 4), np.linspace(-10, 4), c = 'r')\n#plt.xlim(-10, 4)\n#plt.ylim(-10, 4)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 1.1498112446483284\n    RMSE: 1.4624191158480997\n\n\n### Model 4\n\n\n```\ngpr4 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-2, #different from gpr in alpha where gpr_base's alpha is 1e-4\n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr4.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |       66517|       88265|       70813|     -4296.2|       90905|        21|      0.28|\n    |       61455|  1.0409e+05|       65648|     -4193.5|       88757|        19|      0.25|\n    |       50869|  1.1321e+05|       54789|     -3920.3|       81573|        17|      0.23|\n    |       49285|  1.0995e+05|       53162|     -3876.6|       80232|        17|      0.28|\n    |       48321|  1.0553e+05|       52167|       -3845|       78704|        16|      0.24|\n    |       47912|  1.0664e+05|       51747|     -3834.9|       78334|        17|      0.25|\n    |       47815|  1.0611e+05|       51648|     -3832.7|       78473|        17|      0.25|\n    |       47734|  1.0602e+05|       51565|     -3830.1|       78399|        17|      0.24|\n    |       47721|   1.056e+05|       51549|     -3828.8|       78754|        17|      0.25|\n    |       47682|  1.0583e+05|       51510|     -3827.7|       78471|        17|      0.25|\n    |       47662|  1.0594e+05|       51489|     -3827.2|       78334|        17|      0.28|\n    |       47637|  1.0591e+05|       51463|     -3826.7|       78258|        17|      0.24|\n    |       47613|  1.0565e+05|       51439|     -3826.3|       78273|        17|      0.24|\n    |       47587|  1.0505e+05|       51413|     -3826.2|       78397|        17|      0.25|\n    |       47584|  1.0508e+05|       51410|       -3826|       78364|        17|      0.25|\n    |       47579|  1.0506e+05|       51404|     -3825.6|       78277|        17|      0.23|\n    |       47574|  1.0486e+05|       51399|     -3825.5|       78232|        17|      0.25|\n    |       47570|    1.04e+05|       51397|     -3826.4|       78274|        17|      0.28|\n    |       47576|  1.0386e+05|       51402|     -3825.9|       78262|        17|      0.24|\n    |       47569|  1.0395e+05|       51395|     -3826.1|       78271|        17|      0.24|\n    |       47567|  1.0417e+05|       51393|     -3826.1|       78324|        17|      0.28|\n    |       47566|  1.0407e+05|       51392|     -3826.3|       78362|        17|      0.23|\n    |       47566|  1.0398e+05|       51392|     -3826.4|       78386|        17|      0.24|\n    |       47566|  1.0405e+05|       51393|     -3826.3|       78366|        17|      0.24|\n    |       47566|  1.0406e+05|       51392|     -3826.3|       78363|        17|      0.25|\n    |       47566|  1.0407e+05|       51392|     -3826.3|       78362|        17|      0.24|\n    |       47566|  1.0407e+05|       51392|     -3826.3|       78361|        17|      0.25|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |       73087|       31386|       77530|       -4443|       95203|        16|      0.26|\n    |       69027|       48566|       73397|     -4370.2|       93280|        18|      0.25|\n    |       56295|  1.0441e+05|       60364|     -4068.9|       85503|        19|      0.26|\n    |       49629|  1.0815e+05|       53493|     -3864.5|       76173|        17|      0.26|\n    |       48176|  1.0901e+05|       52013|     -3837.5|       77267|        17|      0.26|\n    |       49949|   1.003e+05|       53850|       -3901|       82147|        18|      0.26|\n    |       47973|   1.074e+05|       51809|     -3836.1|       78349|        18|      0.26|\n    |       47868|  1.0647e+05|       51701|     -3833.7|       78588|        17|      0.25|\n    |       47825|  1.0603e+05|       51658|     -3832.9|       78699|        17|      0.25|\n    |       47758|  1.0569e+05|       51589|     -3831.2|       78709|        17|      0.25|\n    |       47712|  1.0601e+05|       51542|     -3829.4|       78587|        17|      0.26|\n    |       47692|  1.0615e+05|       51520|     -3828.2|       78413|        17|      0.24|\n    |       47690|  1.0616e+05|       51518|     -3828.1|       78396|        17|      0.23|\n    |       47681|  1.0614e+05|       51508|     -3827.4|       78346|        17|      0.24|\n    |       47681|  1.0645e+05|       51508|     -3827.2|       78253|        17|      0.24|\n    |       47674|  1.0629e+05|       51501|     -3827.1|       78299|        17|      0.25|\n    |       47654|  1.0622e+05|       51481|     -3826.3|       78288|        17|      0.25|\n    |       47645|  1.0603e+05|       51471|     -3826.2|       78342|        17|      0.26|\n    |       47644|  1.0605e+05|       51471|     -3826.4|       78352|        17|      0.26|\n    |       47644|  1.0604e+05|       51471|     -3826.3|       78347|        17|      0.24|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |       67828|  1.0852e+05|       72138|     -4309.5|       89137|        24|      0.25|\n    |       62412|  1.1469e+05|       66616|       -4204|       87873|        21|      0.25|\n    |       56410|   1.222e+05|       60478|     -4067.7|       85994|        20|      0.26|\n    |       51080|  1.1784e+05|       55004|     -3924.2|       81494|        18|      0.26|\n    |       49634|  1.1413e+05|       53522|     -3888.1|       80979|        18|      0.24|\n    |       48936|  1.0759e+05|       52800|     -3863.2|       79659|        17|      0.24|\n    |       48434|  1.0891e+05|       52284|     -3850.2|       79231|        17|      0.24|\n    |       48204|  1.0827e+05|       52049|     -3844.6|       79132|        18|      0.25|\n    |       47886|  1.0625e+05|       51723|     -3836.7|       78967|        17|      0.24|\n    |       48724|  1.0903e+05|       52577|     -3853.3|       76871|        19|      0.24|\n    |       47877|  1.0635e+05|       51713|     -3836.1|       78785|        18|      0.24|\n    |       48134|  1.0654e+05|       51976|     -3841.5|       78087|        18|      0.24|\n    |       47877|  1.0635e+05|       51712|       -3836|       78744|        17|      0.23|\n    |       47789|  1.0549e+05|       51623|     -3834.3|       78780|        17|      0.24|\n    |       47692|  1.0404e+05|       51525|     -3832.6|       78739|        17|      0.24|\n    |       47665|  1.0386e+05|       51497|     -3831.4|       78613|        17|      0.24|\n    |       47626|  1.0394e+05|       51456|     -3829.6|       78486|        17|      0.26|\n    |       47604|  1.0463e+05|       51432|     -3827.8|       78343|        17|      0.26|\n    |       47590|  1.0446e+05|       51417|     -3827.3|       78398|        17|      0.24|\n    |       47588|  1.0442e+05|       51415|     -3827.1|       78415|        17|      0.26|\n    |       47586|  1.0443e+05|       51413|     -3826.9|       78414|        17|      0.28|\n    |       47582|   1.045e+05|       51409|     -3826.5|       78406|        17|      0.24|\n    |       47579|  1.0481e+05|       51405|     -3825.9|       78253|        17|      0.23|\n    |       47575|  1.0471e+05|       51401|       -3826|       78318|        17|      0.24|\n    |       47573|  1.0459e+05|       51399|     -3826.2|       78354|        17|      0.24|\n    |       47571|  1.0449e+05|       51397|     -3826.3|       78369|        17|      0.24|\n    |       47568|  1.0432e+05|       51394|     -3826.5|       78382|        17|      0.23|\n    |       47566|  1.0421e+05|       51393|     -3826.5|       78376|        17|      0.24|\n    |       47565|   1.042e+05|       51391|     -3826.3|       78347|        17|      0.26|\n    |       47564|  1.0411e+05|       51390|     -3826.1|       78329|        17|      0.24|\n    |       47564|  1.0402e+05|       51390|     -3826.2|       78343|        17|      0.23|\n    |       47564|  1.0392e+05|       51390|     -3826.3|       78361|        17|      0.26|\n    |       47563|  1.0399e+05|       51389|     -3826.2|       78348|        17|      0.24|\n    Optimization result:\n          fun: 47563.16826613996\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 1.03860634e+01,  3.99556925e+00,  4.34356887e-01, -4.38765528e+00,\n            3.35685830e+02,  5.48613650e+00,  0.00000000e+00,  3.74597978e+00,\n            3.71923847e-01, -1.86677689e+01,  1.80494389e-04,  2.34556512e+00,\n            6.89757782e-01,  7.46525570e+00,  3.86435984e+02, -4.08724178e+00,\n            6.25487975e+01,  3.79069496e+00,  5.00876053e+01, -1.47395577e+00,\n            1.52830838e+01,  1.49931223e+00,  0.00000000e+00,  2.53256179e-01,\n            2.78310073e-01])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 33\n          nit: 29\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.23992363, -2.30258509,  1.70454451, -2.30258509,\n           -4.60517019, -0.39405819, -4.60517019, -1.7367717 ,  2.30258509,\n           -1.86521329, -4.33629426, -2.08030139,  1.84897251, -2.30258509,\n            2.14248562, -2.30258509,  1.93608271, -2.30258509,  0.72987226,\n           -2.30258509, -3.7783557 , -1.83514442, -3.16885023, -2.30258509])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7fb9896f5fd0>\n\n\n\n\n```\nmu = gpr4.predict(train.graphs)\nplt.scatter(train[target], mu)\n#plt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\n#plt.xlim(-9, 3)\n#plt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.6721642416785486\n    RMSE: 0.9001504628434619\n\n\n\n```\nmu_test = gpr4.predict(test.graphs)\nplt.scatter(test[target], mu_test)\n#plt.plot(np.linspace(-10, 4), np.linspace(-10, 4), c = 'r')\n#plt.xlim(-10, 4)\n#plt.ylim(-10, 4)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 0.996800387138675\n    RMSE: 1.2687098498475842\n\n\n### Model 5\n\n\n```\ngpr5 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-1, #different from gpr in alpha where gpr_base's alpha is 1e-4\n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr5.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |      5933.5|      3681.9|        8130|     -2196.5|        9095|        23|      0.27|\n    |      5700.6|      4368.7|      7866.6|       -2166|        8897|        21|      0.23|\n    |      5244.7|      4143.6|      7321.1|     -2076.4|      8114.4|        17|      0.24|\n    |      5161.9|      4261.1|      7222.8|       -2061|      8040.9|        17|      0.23|\n    |      5123.7|      4119.8|      7182.2|     -2058.5|      8116.4|        17|      0.25|\n    |      5100.9|      4055.4|      7155.4|     -2054.5|      8044.2|        17|      0.25|\n    |      5081.3|      3976.5|      7132.4|     -2051.1|      7995.7|        17|      0.24|\n    |      5078.6|      3971.4|      7128.4|     -2049.9|      7991.1|        17|      0.24|\n    |        5077|      3973.1|      7126.9|     -2049.9|      7990.8|        17|      0.24|\n    |      5075.4|      3971.5|      7125.2|     -2049.7|      7988.9|        17|      0.24|\n    |        5074|      3966.8|      7123.6|     -2049.5|      7985.4|        17|      0.26|\n    |      5071.8|      3952.7|        7121|     -2049.2|      7981.1|        17|      0.25|\n    |      5068.8|      3927.3|      7117.9|     -2049.1|      7982.1|        17|      0.26|\n    |      5067.9|      3915.3|      7117.1|     -2049.1|      7980.4|        17|      0.25|\n    |      5067.8|      3917.4|      7116.9|     -2049.1|      7979.1|        17|      0.25|\n    |      5067.8|      3919.2|      7116.8|       -2049|      7978.5|        17|      0.24|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |      6316.2|      4166.3|      8544.1|     -2227.9|        9356|        21|      0.23|\n    |      5897.8|      4552.2|      8086.8|       -2189|      9123.3|        20|      0.25|\n    |      5402.1|      4470.5|      7523.5|     -2121.3|      8676.4|        18|      0.23|\n    |      5263.9|      4484.2|        7355|     -2091.2|      8445.2|        18|      0.26|\n    |      5192.2|      4382.6|      7262.9|     -2070.7|      8189.6|        18|      0.25|\n    |      5121.6|      4136.4|      7180.3|     -2058.7|      8143.5|        17|      0.24|\n    |      5111.8|        4133|      7163.8|       -2052|        7978|        17|      0.23|\n    |      5100.7|      4164.8|      7150.7|     -2049.9|      7976.5|        17|      0.24|\n    |        5094|        4154|        7143|       -2049|      7983.6|        17|      0.23|\n    |      5089.6|        4131|      7138.2|     -2048.5|      7988.5|        17|      0.23|\n    |      5086.1|      4087.2|      7133.9|     -2047.8|      7974.4|        17|      0.23|\n    |      5082.2|      4085.6|        7130|     -2047.8|      7979.5|        17|      0.26|\n    |      5079.1|      4076.2|      7126.9|     -2047.9|      7977.4|        17|      0.23|\n    |      5078.3|      4068.3|      7126.3|       -2048|      7976.8|        17|      0.26|\n    |      5075.3|      3953.8|        7125|     -2049.7|      7975.3|        17|      0.23|\n    |      5073.1|      3984.2|      7122.2|     -2049.1|      7987.6|        17|      0.26|\n    |      5072.6|      3973.4|      7121.8|     -2049.2|      7988.8|        17|      0.28|\n    |      5071.1|      3934.7|      7120.4|     -2049.3|      7985.3|        17|      0.26|\n    |      5069.9|        3928|      7119.1|     -2049.2|      7984.2|        17|      0.25|\n    |      5068.5|      3913.3|      7117.8|     -2049.3|      7983.9|        17|      0.24|\n    |      5067.8|      3915.3|      7116.6|     -2048.8|      7969.8|        17|      0.25|\n    |      5067.5|      3903.7|      7117.2|     -2049.7|      7993.3|        17|      0.25|\n    |      5067.3|      3908.8|      7116.5|     -2049.2|      7983.6|        17|      0.24|\n    |      5067.1|        3910|      7116.1|       -2049|      7977.3|        17|      0.23|\n    |      5067.1|      3910.1|      7116.1|       -2049|      7977.7|        17|      0.26|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |      5834.4|      4699.1|      8022.2|     -2187.9|      9207.7|        21|      0.23|\n    |      5579.2|      4272.2|      7729.4|     -2150.2|      8902.1|        19|      0.24|\n    |        5265|      4187.4|      7346.4|     -2081.4|      8221.2|        18|      0.27|\n    |      5170.4|      3954.9|      7238.8|     -2068.4|      8110.4|        17|      0.24|\n    |      5137.6|      4046.1|      7198.2|     -2060.6|      8053.1|        17|      0.25|\n    |      5109.8|      4060.1|      7164.7|     -2054.9|      8036.6|        17|      0.23|\n    |      5092.8|      4026.6|      7144.8|       -2052|      8014.6|        17|      0.23|\n    |      5086.7|      3944.7|      7136.4|     -2049.7|      7929.4|        17|      0.23|\n    |      5078.8|      3926.5|      7130.6|     -2051.8|      8024.8|        17|      0.24|\n    |      5077.1|      3942.6|      7128.1|     -2050.9|      8009.4|        17|      0.23|\n    |      5075.3|      3953.9|      7125.3|     -2049.9|      7991.6|        17|      0.27|\n    |      5072.7|        3957|      7121.7|       -2049|      7973.5|        17|      0.25|\n    |      5069.8|      3945.2|      7118.4|     -2048.6|      7968.5|        17|      0.24|\n    |      5069.4|        3932|      7118.3|     -2048.9|      7981.7|        17|      0.25|\n    |      5068.9|      3930.6|      7117.9|       -2049|        7981|        17|      0.23|\n    |      5068.8|      3926.4|      7117.9|     -2049.1|      7983.4|        17|      0.24|\n    |      5068.4|      3917.5|      7117.9|     -2049.4|      7987.3|        17|      0.23|\n    |      5068.1|      3910.6|      7117.7|     -2049.6|        7989|        17|      0.25|\n    |      5067.8|      3913.7|      7117.1|     -2049.3|        7985|        17|      0.23|\n    |      5067.6|      3919.1|      7116.2|     -2048.6|      7972.4|        17|      0.23|\n    |      5067.4|      3918.6|      7116.2|     -2048.8|      7975.7|        17|      0.23|\n    |      5067.4|        3918|      7116.2|     -2048.9|        7976|        17|      0.23|\n    Optimization result:\n          fun: 5067.119508760024\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 3.90259274e-01,  1.87865706e-01,  2.15153320e-02,  5.95899075e-02,\n            1.81887249e+01,  3.14234542e-01,  0.00000000e+00,  2.98486676e-01,\n            9.99179948e-03, -1.21282065e+00,  0.00000000e+00,  1.07942514e-01,\n            2.29213419e-02,  2.45315195e-01,  1.44913639e+01,  2.38720249e-03,\n            6.78953722e-03, -1.08856133e-01,  3.25365990e+00,  4.00300271e-02,\n            3.61716207e+00,  3.49621047e-02,  0.00000000e+00,  3.14194196e-02,\n            3.39042590e-03])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 25\n          nit: 24\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -1.9276534 ,  1.65083009, -2.30258509,\n           -4.60517019,  0.08473439, -4.60517019, -0.94627051,  2.30258509,\n           -4.52691773, -4.60517019, -2.30258509,  1.42510738, -2.30258509,\n           -4.00849461, -2.30258509,  2.12160197, -2.30258509,  2.23247174,\n           -2.30258509, -4.60517019, -1.5016103 , -4.60517019, -0.71533121])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7fb9880bba10>\n\n\n\n\n```\nmu = gpr5.predict(train.graphs)\nplt.scatter(train[target], mu)\n#plt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\n#plt.xlim(-9, 3)\n#plt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.8642262237055949\n    RMSE: 1.1297768774199661\n\n\n\n```\nmu_test = gpr4.predict(test.graphs)\nplt.scatter(test[target], mu_test)\n#plt.plot(np.linspace(-10, 4), np.linspace(-10, 4), c = 'r')\n#plt.xlim(-10, 4)\n#plt.ylim(-10, 4)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 0.9967978325813834\n    RMSE: 1.2687065452737312\n\n\n\n```\n\n```\n", "meta": {"hexsha": "317102122a23e7601ce81278dceda913acb227ad", "size": 271198, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Docking_0615.ipynb", "max_stars_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_stars_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Docking_0615.ipynb", "max_issues_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_issues_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Docking_0615.ipynb", "max_forks_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_forks_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 133.7268244576, "max_line_length": 24654, "alphanum_fraction": 0.7503742653, "converted": true, "num_tokens": 34642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167645017354, "lm_q2_score": 0.04742587014823577, "lm_q1q2_score": 0.021864121209419093}}
{"text": "# Ray RLlib - Introduction to Reinforcement Learning\n\n\u00a9 2019-2020, Anyscale. All Rights Reserved\n\n\n\n_Reinforcement Learning_ is the category of machine learning that focuses on training one or more _agents_ to achieve maximal _rewards_ while operating in an environment. This lesson discusses the core concepts of RL, while subsequent lessons explore RLlib in depth. We'll use two examples with exercises to give you a taste of RL. If you already understand RL concepts, you can either skim this lesson or skip to the [next lesson](02-Introduction-to-RLlib.ipynb).\n\n## What Is Reinforcement Learning?\n\nLet's explore the basic concepts of RL, specifically the _Markov Decision Process_ abstraction, and to show its use in Python.\n\nConsider the following image:\n\n\n\nIn RL, one or more **agents** interact with an **environment** to maximize a **reward**. The agents make **observations** about the **state** of the environment and take **actions** that are believed will maximize the long-term reward. However, at any particular moment, the agents can only observe the immediate reward. So, the training process usually involves lots and lot of replay of the game, the robot simulator traversing a virtual space, etc., so the agents can learn from repeated trials what decisions/actions work best to maximize the long-term, cumulative reward.\n\nThe trail and error search and delayed reward are the distinguishing characterists of RL vs. other ML methods ([Sutton 2018](06-RL-References.ipynb#Books)).\n\nThe way to formalize trial and error is the **exploitation vs. exploration tradeoff**. When an agent finds what appears to be a \"rewarding\" sequence of actions, the agent may naturally want to continue to **exploit** these actions. However, even better actions may exist. An agent won't know whether alternatives are better or not unless some percentage of actions taken **explore** the alternatives. So, all RL algorithms include a strategy for exploitation and exploration.\n\n## RL Applications\n\nRL has many potential applications. RL became \"famous\" due to these successes, including achieving expert game play, training robots, autonomous vehicles, and other simulated agents:\n\n\n\n\n\n\n\n\n\n\nCredits:\n* [AlphaGo](https://www.youtube.com/watch?v=l7ngy56GY6k)\n* [Breakout](https://towardsdatascience.com/tutorial-double-deep-q-learning-with-dueling-network-architectures-4c1b3fb7f756) ([paper](https://arxiv.org/abs/1312.5602))\n* [Stacking Legos with Sawyer](https://robohub.org/soft-actor-critic-deep-reinforcement-learning-with-real-world-robots/)\n* [Walking Man](https://openai.com/blog/openai-baselines-ppo/)\n* [Autonomous Vehicle](https://www.daimler.com/innovation/case/autonomous/intelligent-drive-2.html)\n* [\"Cassie\": Two-legged Robot](https://mime.oregonstate.edu/research/drl/robots/cassie/) (Uses Ray!)\n\nRecently other industry applications have emerged, include the following:\n\n* **Process optimization:** industrial processes (factories, pipelines) and other business processes, routing problems, cluster optimization.\n* **Ad serving and recommendations:** Some of the traditional methods, including _collaborative filtering_, are hard to scale for very large data sets. RL systems are being developed to do an effective job more efficiently than traditional methods.\n* **Finance:** Markets are time-oriented _environments_ where automated trading systems are the _agents_. \n\n## Markov Decision Processes\n\nAt its core, Reinforcement learning builds on the concepts of [Markov Decision Process (MDP)](https://en.wikipedia.org/wiki/Markov_decision_process), where the current state, the possible actions that can be taken, and overall goal are the building blocks.\n\nAn MDP models sequential interactions with an external environment. It consists of the following:\n\n- a **state space** where the current state of the system is sometimes called the **context**.\n- a set of **actions** that can be taken at a particular state $s$ (or sometimes the same set for all states).\n- a **transition function** that describes the probability of being in a state $s'$ at time $t+1$ given that the MDP was in state $s$ at time $t$ and action $a$ was taken. The next state is selected stochastically based on these probabilities.\n- a **reward function**, which determines the reward received at time $t$ following action $a$, based on the decision of **policy** $\\pi$.\n\nThe goal of MDP is to develop a **policy** $\\pi$ that specifies what action $a$ should be chosen for a given state $s$ so that the cumulative reward is maximized. When it is possible for the policy \"trainer\" to fully observe all the possible states, actions, and rewards, it can define a deterministic policy, fixing a single action choice for each state. In this scenario, the transition probabilities reduce to the probability of transitioning to state $s'$ given the current state is $s$, independent of actions, because the state now leads to a deterministic action choice. Various algorithms can be used to compute this policy. \n\nPut another way, if the policy isn't deterministic, then the transition probability to state $s'$ at a time $t+1$ when action $a$ is taken for state $s$ at time $t$, is given by:\n\n\\begin{equation}\nP_a(s',s) = P(s_{t+1} = s'|s_t=s,a)\n\\end{equation}\n\nWhen the policy is deterministic, this transition probability reduces to the following, independent of $a$:\n\n\\begin{equation}\nP(s',s) = P(s_{t+1} = s'|s_t=s)\n\\end{equation}\n\nTo be clear, a deterministic policy means that one and only one action will always be selected for a given state $s$, but the next state $s'$ will still be selected stochastically.\n\nIn the general case of RL, it isn't possible to fully know all this information, some of which might be hidden and evolving, so it isn't possible to specify a fully-deterministic policy.\n\nOften this cumulative reward is computed using the **discounted sum** over all rewards observed:\n\n\\begin{equation}\n\\arg\\max_{\\pi} \\sum_{t=1}^T \\gamma^t R_t(\\pi),\n\\end{equation}\n\nwhere $T$ is the number of steps taken in the MDP (this is a random variable and may depend on $\\pi$), $R_t$ is the reward received at time $t$ (also a random variable which depends on $\\pi$), and $\\gamma$ is the **discount factor**. The value of $\\gamma$ is between 0 and 1, meaning it has the effect of \"discounting\" earlier rewards vs. more recent rewards. \n\nThe [Wikipedia page on MDP](https://en.wikipedia.org/wiki/Markov_decision_process) provides more details. Note what we said in the third bullet, that the new state only depends on the previous state and the action taken. The assumption is that we can simplify our effort by ignoring all the previous states except the last one and still achieve good results. This is known as the [Markov property](https://en.wikipedia.org/wiki/Markov_property). This assumption often works well and it greatly reduces the resources required.\n\n## The Elements of RL\n\nHere are the elements of RL that expand on MDP concepts (see [Sutton 2018](https://mitpress.mit.edu/books/reinforcement-learning-second-edition) for more details):\n\n#### Policies\n\nUnlike MDP, the **transition function** probabilities are often not known in advance, but must be learned. Learning is done through repeated \"play\", where the agent interacts with the environment.\n\nThis makes the **policy** $\\pi$ harder to determine. Because the fully state space usually can't be fully known, the choice of action $a$ for given state $s$ almostly always remains a stochastic choice, never deterministic, unlike MDP.\n\n#### Reward Signal\n\nThe idea of a **reward signal** encapsulates the desired goal for the system and provides feedback for updating the policy based on how well particular events or actions contribute rewards towards the goal.\n\n#### Value Function\n\nThe **value function** encapsulates the maximum cumulative reward likely to be achieved starting from a given state for an **episode**. This is harder to determine than the simple reward returned after taking an action. In fact, much of the research in RL over the decades has focused on finding better and more efficient implementations of value functions. To illustrate the challenge, repeatedly taking one sequence of actions may yield low rewards for a while, but eventually provide large rewards. Conversely, always choosing a different sequence of actions may yield a good reward at each step, but be suboptimal for the cumulative reward.\n\n#### Episode\n\nA sequence of steps by the agent starting in an initial state. At each step, the agent observes the current state, chooses the next action, and receives the new reward. Episodes are used for both training policies and replaying with an existing policy (called _rollout_).\n\n#### Model\n\nAn optional feature, some RL algorithms develop or use a **model** of the environment to anticipate the resulting states and rewards for future actions. Hence, they are useful for _planning_ scenarios. Methods for solving RL problems that use models are called _model-based methods_, while methods that learn by trial and error are called _model-free methods_.\n\n## Reinforcement Learning Example\n\nLet's finish this introduction let's learn about the popular \"hello world\" (1) example environment for RL, balancing a pole vertically on a moving cart, called `CartPole`. Then we'll see how to use RLlib to train a policy using a popular RL algorithm, _Proximal Policy Optimization_, again using `CartPole`.\n\n(1) In books and tutorials on programming languages, it is a tradition that the very first program shown prints the message \"Hello World!\".\n\n### CartPole and OpenAI\n\nThe popular [OpenAI \"gym\" environment](https://gym.openai.com/) provides MDP interfaces to a variety of simulated environments. Perhaps the most popular for learning RL is `CartPole`, a simple environment that simulates the physics of balancing a pole on a moving cart. The `CartPole` problem is described at https://gym.openai.com/envs/CartPole-v1. Here is an image from that website, where the pole is currently falling to the right, which means the cart will need to move to the right to restore balance:\n\n\n\nThis example fits into the MDP framework as follows:\n- The **state** consists of the position and velocity of the cart (moving in one dimension from left to right) as well as the angle and angular velocity of the pole that is balancing on the cart.\n- The **actions** are to decrease or increase the cart's velocity by one unit. A negative velocity means it is moving to the left.\n- The **transition function** is deterministic and is determined by simulating physical laws. Specifically, for a given **state**, what should we choose as the next velocity value? In the RL context, the correct velocity value to choose has to be learned. Hence, we learn a _policy_ that approximates the optimal transition function that could be calculated from the laws of physics.\n- The **reward function** is a constant 1 as long as the pole is upright, and 0 once the pole has fallen over. Therefore, maximizing the reward means balancing the pole for as long as possible.\n- The **discount factor** in this case can be taken to be 1, meaning we treat the rewards at all time steps equally and don't discount any of them.\n\nMore information about the `gym` Python module is available at https://gym.openai.com/. The list of all the available Gym environments is in [this wiki page](https://github.com/openai/gym/wiki/Table-of-environments). We'll use a few more of them and even create our own in subsequent lessons.\n\n\n```python\nimport gym\nimport numpy as np\nimport pandas as pd\nimport json\n```\n\nThe code below illustrates how to create and manipulate MDPs in Python. An MDP can be created by calling `gym.make`. Gym environments are identified by names like `CartPole-v1`. A **catalog of built-in environments** can be found at https://gym.openai.com/envs.\n\n\n```python\nenv = gym.make(\"CartPole-v1\")\nprint(\"Created env:\", env)\n```\n\nReset the state of the MDP by calling `env.reset()`. This call returns the initial state of the MDP.\n\n\n```python\nstate = env.reset()\nprint(\"The starting state is:\", state)\n```\n\nRecall that the state is the position of the cart, its velocity, the angle of the pole, and the angular velocity of the pole.\n\nThe `env.step` method takes an action. In the case of the `CartPole` environment, the appropriate actions are 0 or 1, for pushing the cart to the left or right, respectively. `env.step()` returns a tuple of four things:\n1. the new state of the environment\n2. a reward\n3. a boolean indicating whether the simulation has finished\n4. a dictionary of miscellaneous extra information\n\nLet's show what happens if we take one step with an action of 0.\n\n\n```python\naction = 0\nstate, reward, done, info = env.step(action)\nprint(state, reward, done, info)\n```\n\nA **rollout** is a simulation of a policy in an environment. It is used both during training and when running simulations with a trained policy. \n\nThe code below performs a rollout in a given environment. It takes **random actions** until the simulation has finished and returns the cumulative reward.\n\n\n```python\ndef random_rollout(env):\n    state = env.reset()\n    \n    done = False\n    cumulative_reward = 0\n\n    # Keep looping as long as the simulation has not finished.\n    while not done:\n        # Choose a random action (either 0 or 1).\n        action = np.random.choice([0, 1])\n        \n        # Take the action in the environment.\n        state, reward, done, _ = env.step(action)\n        \n        # Update the cumulative reward.\n        cumulative_reward += reward\n    \n    # Return the cumulative reward.\n    return cumulative_reward    \n```\n\nTry rerunning the following cell a few times. How much do the answers change? Note that the maximum possible reward for `CartPole-v1` is 500. You'll probably get numbers well under 500.\n\n\n```python\nreward = random_rollout(env)\nprint(reward)\n\nreward = random_rollout(env)\nprint(reward)\n```\n\n### Exercise 1\n\nChoosing actions at random in `random_rollout` is not a very effective policy, as the previous results showed. Finish implementing the `rollout_policy` function below, which takes an environment *and* a policy. Recall that the *policy* is a function that takes in a *state* and returns an *action*. The main difference is that instead of choosing a **random action**, like we just did (with poor results), the action should be chosen **with the policy** (as a function of the state).\n\n> **Note:** Exercise solutions for this tutorial can be found [here](solutions/Ray-RLlib-Solutions.ipynb).\n\n\n```python\ndef rollout_policy(env, policy):\n    state = env.reset()\n    \n    done = False\n    cumulative_reward = 0\n\n    # EXERCISE: Fill out this function by copying the appropriate part of 'random_rollout'\n    # and modifying it to choose the action using the policy.\n    raise NotImplementedError\n\n    # Return the cumulative reward.\n    return cumulative_reward\n\ndef sample_policy1(state):\n    return 0 if state[0] < 0 else 1\n\ndef sample_policy2(state):\n    return 1 if state[0] < 0 else 0\n\nreward1 = np.mean([rollout_policy(env, sample_policy1) for _ in range(100)])\nreward2 = np.mean([rollout_policy(env, sample_policy2) for _ in range(100)])\n\nprint('The first sample policy got an average reward of {}.'.format(reward1))\nprint('The second sample policy got an average reward of {}.'.format(reward2))\n\nassert 5 < reward1 < 15, ('Make sure that rollout_policy computes the action '\n                          'by applying the policy to the state.')\nassert 25 < reward2 < 35, ('Make sure that rollout_policy computes the action '\n                           'by applying the policy to the state.')\n```\n\nWe'll return to `CartPole` in lesson [01: Application Cart Pole](explore-rllib/01-Application-Cart-Pole.ipynb) in the `explore-rllib` section.\n\n### RLlib Reinforcement Learning Example: Cart Pole with Proximal Policy Optimization\n\nThis section demonstrates how to use the _proximal policy optimization_ (PPO) algorithm implemented by [RLlib](http://rllib.io). PPO is a popular way to develop a policy. RLlib also uses [Ray Tune](http://tune.io), the Ray Hyperparameter Tuning framework, which is covered in the [Ray Tune Tutorial](../ray-tune/00-Ray-Tune-Overview.ipynb).\n\nWe'll provide relatively little explanation of **RLlib** concepts for now, but explore them in greater depth in subsequent lessons. For more on RLlib, see the documentation at http://rllib.io.\n\nPPO is described in detail in [this paper](https://arxiv.org/abs/1707.06347). It is a variant of _Trust Region Policy Optimization_ (TRPO) described in [this earlier paper](https://arxiv.org/abs/1502.05477). [This OpenAI post](https://openai.com/blog/openai-baselines-ppo/) provides a more accessible introduction to PPO.\n\nPPO works in two phases. In the first phase, a large number of rollouts are performed in parallel. The rollouts are then aggregated on the driver and a surrogate optimization objective is defined based on those rollouts. In the second phase, we use SGD (_stochastic gradient descent_) to find the policy that maximizes that objective with a penalty term for diverging too much from the current policy.\n\n\n\n> **NOTE:** The SGD optimization step is best performed in a data-parallel manner over multiple GPUs. This is exposed through the `num_gpus` field of the `config` dictionary. Hence, for normal usage, one or more GPUs is recommended.\n\n(The original version of this example can be found [here](https://raw.githubusercontent.com/ucbrise/risecamp/risecamp2018/ray/tutorial/rllib_exercises/)).\n\n\n```python\nimport ray\nfrom ray.rllib.agents.ppo import PPOTrainer, DEFAULT_CONFIG\nfrom ray.tune.logger import pretty_print\n```\n\nInitialize Ray. If you are running these tutorials on your laptop, then a single-node Ray cluster will be started by the next cell. If you are running in the Anyscale platform, it will connect to the running Ray cluster.\n\n\n```python\ninfo = ray.init(ignore_reinit_error=True, log_to_driver=False)\n```\n\n> **Tip:** Having trouble starting Ray? See the [Troubleshooting](../reference/Troubleshooting-Tips-Tricks.ipynb) tips.\n\nThe next cell prints the URL for the Ray Dashboard. **This is only correct if you are running this tutorial on a laptop.** Click the link to open the dashboard.\n\nIf you are running on the Anyscale platform, use the URL provided by your instructor to open the Dashboard.\n\n\n```python\nprint(\"Dashboard URL: http://{}\".format(info[\"webui_url\"]))\n```\n\nInstantiate a PPOTrainer object. We pass in a config object that specifies how the network and training procedure should be configured. Some of the parameters are the following.\n\n- `num_workers` is the number of actors that the agent will create. This determines the degree of parallelism that will be used. In a cluster, these actors will be spread over the available nodes.\n- `num_sgd_iter` is the number of epochs of SGD (stochastic gradient descent, i.e., passes through the data) that will be used to optimize the PPO surrogate objective at each iteration of PPO, for each _minibatch_ (\"chunk\") of training data. Using minibatches is more efficient than training with one record at a time.\n- `sgd_minibatch_size` is the SGD minibatch size (batches of data) that will be used to optimize the PPO surrogate objective.\n- `model` contains a dictionary of parameters describing the neural net used to parameterize the policy. The `fcnet_hiddens` parameter is a list of the sizes of the hidden layers. Here, we have two hidden layers of size 100, each.\n- `num_cpus_per_worker` when set to 0 prevents Ray from pinning a CPU core to each worker, which means we could run out of workers in a constrained environment like a laptop or a cloud VM.\n\n\n```python\nconfig = DEFAULT_CONFIG.copy()\nconfig['num_workers'] = 1\nconfig['num_sgd_iter'] = 30\nconfig['sgd_minibatch_size'] = 128\nconfig['model']['fcnet_hiddens'] = [100, 100]\nconfig['num_cpus_per_worker'] = 0 \n```\n\n\n```python\nagent = PPOTrainer(config, 'CartPole-v1')\n```\n\nNow let's train the policy on the `CartPole-v1` environment for `N` steps. The JSON object returned by each call to `agent.train()` contains a lot of information we'll inspect below. For now, we'll extract information we'll graph, such as `episode_reward_mean`. The _mean_ values are more useful for determining successful training.\n\n\n```python\nN = 10\nresults = []\nepisode_data = []\nepisode_json = []\n\nfor n in range(N):\n    result = agent.train()\n    results.append(result)\n    \n    episode = {'n': n, \n               'episode_reward_min':  result['episode_reward_min'],  \n               'episode_reward_mean': result['episode_reward_mean'], \n               'episode_reward_max':  result['episode_reward_max'],  \n               'episode_len_mean':    result['episode_len_mean']} \n    \n    episode_data.append(episode)\n    episode_json.append(json.dumps(episode))\n    \n    print(f'{n:3d}: Min/Mean/Max reward: {result[\"episode_reward_min\"]:8.4f}/{result[\"episode_reward_mean\"]:8.4f}/{result[\"episode_reward_max\"]:8.4f}')\n```\n\nNow let's convert the episode data to a Pandas `DataFrame` for easy manipulation. The results indicate how much reward the policy is receiving (`episode_reward_*`) and how many time steps of the environment the policy ran (`episode_len_mean`). The maximum possible reward for this problem is `500`. The reward mean and trajectory length are very close because the agent receives a reward of one for every time step that it survives. However, this is specific to this environment and not true in general.\n\n\n```python\ndf = pd.DataFrame(data=episode_data)\ndf\n```\n\n\n```python\ndf.columns.tolist()\n```\n\nLet's plot the data. Since the length and reward means are equal, we'll only plot one line:\n\n\n```python\ndf.plot(x=\"n\", y=[\"episode_reward_mean\", \"episode_reward_min\", \"episode_reward_max\"], secondary_y=True)\n```\n\nThe model is quickly able to hit the maximum value of 500, but the mean is what's most valuable. After 10 steps, we're more than half way there.\n\nFYI, here are two views of the whole value for one result. First, a \"pretty print\" output.\n\n> **Tip:** The output will be long. When this happens for a cell, right click and select _Enable scrolling for outputs_.\n\n\n```python\nprint(pretty_print(results[-1]))\n```\n\nWe'll learn about more of these values as continue the tutorial.\n\nThe whole, long JSON blob, which includes the historical stats about episode rewards and lengths:\n\n\n```python\nresults[-1]\n```\n\nLet's plot the `episode_reward` values:\n\n\n```python\nepisode_rewards = results[-1]['hist_stats']['episode_reward']\ndf_episode_rewards = pd.DataFrame(data={'episode':range(len(episode_rewards)), 'reward':episode_rewards})\n\ndf_episode_rewards.plot(x=\"episode\", y=\"reward\")\n```\n\nFor a well-trained model, most runs do very well while occasional runs do poorly. Try plotting other results episodes by changing the array index in `results[-1]` to another number between `0` and `9`. (The length of `results` is `10`.)\n\n### Exercise 2\n\nThe current network and training configuration are too large and heavy-duty for a simple problem like `CartPole`. Modify the configuration to use a smaller network (the `config['model']['fcnet_hiddens']` setting) and to speed up the optimization of the surrogate objective. (Fewer SGD iterations and a larger batch size should help.)\n\n\n```python\n# Make edits here:\nconfig = DEFAULT_CONFIG.copy()\nconfig['num_workers'] = 3\nconfig['num_sgd_iter'] = 30\nconfig['sgd_minibatch_size'] = 128\nconfig['model']['fcnet_hiddens'] = [100, 100]\nconfig['num_cpus_per_worker'] = 0\n\nagent = PPOTrainer(config, 'CartPole-v1')\n```\n\nTrain the agent and try to get a reward of 500. If it's training too slowly you may need to modify the config above to use fewer hidden units, a larger `sgd_minibatch_size`, a smaller `num_sgd_iter`, or a larger `num_workers`.\n\nThis should take around `N` = 20 or 30 training iterations.\n\n\n```python\nN = 5\nresults = []\nepisode_data = []\nepisode_json = []\n\nfor n in range(N):\n    result = agent.train()\n    results.append(result)\n    \n    episode = {'n': n, \n               'episode_reward_mean': result['episode_reward_mean'], \n               'episode_reward_max': result['episode_reward_max'],  \n               'episode_len_mean': result['episode_len_mean']}   \n    \n    episode_data.append(episode)\n    episode_json.append(json.dumps(episode))\n    \n    print(f'Max reward: {episode[\"episode_reward_max\"]}')\n```\n\n# Using Checkpoints\n\nYou checkpoint the current state of a trainer to save what it has learned. Checkpoints are used for subsequent _rollouts_ and also to continue training later from a known-good state.  Calling `agent.save()` creates the checkpoint and returns the path to the checkpoint file, which can be used later to restore the current state to a new trainer. Here we'll load the trained policy into the same process, but often it would be loaded in a new process, for example on a production cluster for serving that is separate from the training cluster.\n\n\n```python\ncheckpoint_path = agent.save()\nprint(checkpoint_path)\n```\n\nNow load the checkpoint in a new trainer:\n\n\n```python\ntrained_config = config.copy()\ntest_agent = PPOTrainer(trained_config, \"CartPole-v1\")\ntest_agent.restore(checkpoint_path)\n```\n\nUse the previously-trained policy to act in an environment. The key line is the call to `test_agent.compute_action(state)` which uses the trained policy to choose an action. This is an example of _rollout_, which we'll study in a subsequent lesson.\n\nVerify that the cumulative reward received roughly matches up with the reward printed above. It will be at or near 500.\n\n\n```python\nenv = gym.make(\"CartPole-v1\")\nstate = env.reset()\ndone = False\ncumulative_reward = 0\n\nwhile not done:\n    action = test_agent.compute_action(state)  # key line; get the next action\n    state, reward, done, _ = env.step(action)\n    cumulative_reward += reward\n\nprint(cumulative_reward)\n```\n\n\n```python\nray.shutdown()\n```\n\nThe next lesson, [02: Introduction to RLlib](02-Introduction-to-RLlib.ipynb) steps back to introduce to RLlib, its goals and the capabilities it provides.\n", "meta": {"hexsha": "da3305776e809b9ce0956fecca69a2a94f63a1c2", "size": 39088, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb", "max_stars_repo_name": "ewbolme/academy", "max_stars_repo_head_hexsha": "87bda18d4122dbaa3f67d3a1f6c4b534bd279992", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb", "max_issues_repo_name": "ewbolme/academy", "max_issues_repo_head_hexsha": "87bda18d4122dbaa3f67d3a1f6c4b534bd279992", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb", "max_forks_repo_name": "ewbolme/academy", "max_forks_repo_head_hexsha": "87bda18d4122dbaa3f67d3a1f6c4b534bd279992", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.683248731, "max_line_length": 653, "alphanum_fraction": 0.6359496521, "converted": true, "num_tokens": 5988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.373875808818685, "lm_q2_score": 0.05834584224906846, "lm_q1q2_score": 0.021814098962077873}}
{"text": "```\ncurrent_path = '/content/drive/My Drive/Colab Notebooks/Project_GANder/gankook_cuda/semantic-segmentation-pytorch/pytorch.room.layout/'\n\nimport os\nos.chdir(current_path)\n!ls\n```\n\n    build\t\t      drn.py\t\t     requirements.txt\n    cv2_requirements.txt  features\t\t     segment_rl.py\n    datasets\t      lsun.pth.tar\t     segment_st.py\n    data_transforms.py    lu_vp_detect.egg-info  sunrgbd.pth.tar\n    dist\t\t      pics\t\t     test_result\n    drn_d_105_024_val     __pycache__\t     visualize.m\n    drn_d_105_024_val_ms  README.md\t\t     XiaohuLuVPDetection\n\n\n### Get Vanishing point, inliers\n\n\n```\n# !python XiaohuLuVPDetection/setup.py build\n# !python XiaohuLuVPDetection/setup.py install\n!pip install -r cv2_requirements.txt\n```\n\n    Collecting opencv-python==4.0.0.21\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/37/49/874d119948a5a084a7ebe98308214098ef3471d76ab74200f9800efeef15/opencv_python-4.0.0.21-cp36-cp36m-manylinux1_x86_64.whl (25.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 25.4MB 119kB/s \n    \u001b[?25hCollecting opencv-contrib-python==4.0.0.21\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1f/c0/0463d91f297521b2e15e3d682d7077557fe773db72a03a0d2dba899ab8a5/opencv_contrib_python-4.0.0.21-cp36-cp36m-manylinux1_x86_64.whl (31.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 31.2MB 102kB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.11.3 in /usr/local/lib/python3.6/dist-packages (from opencv-python==4.0.0.21->-r cv2_requirements.txt (line 1)) (1.18.5)\n    \u001b[31mERROR: albumentations 0.1.12 has requirement imgaug<0.2.7,>=0.2.5, but you'll have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Installing collected packages: opencv-python, opencv-contrib-python\n      Found existing installation: opencv-python 4.1.2.30\n        Uninstalling opencv-python-4.1.2.30:\n          Successfully uninstalled opencv-python-4.1.2.30\n      Found existing installation: opencv-contrib-python 4.1.2.30\n        Uninstalling opencv-contrib-python-4.1.2.30:\n          Successfully uninstalled opencv-contrib-python-4.1.2.30\n    Successfully installed opencv-contrib-python-4.0.0.21 opencv-python-4.0.0.21\n\n\n\n```\nimport cv2\ncv2.__version__\n```\n\n\n\n\n    '4.0.0'\n\n\n\n### pytorch.room.layout\n\n\n```\n# !pip install -r requirements.txt\n# !apt install octave\n```\n\n\n```\nimport torch\ntorch.__version__\n```\n\n\n```\n!python segment_rl.py train -d datasets/lsun/ -c 4 -s 480 --arch drn_d_105 --batch-size 32 --random-scale 1.75 --random-rotate 15 --epochs 100 --lr 0.01 --momentum 0.9 --lr-mode poly --pretrained sunrgbd.pth.tar\n```\n\n\n```\n!python segment_st.py test -d datasets/sunrgbd/ -c 37 --arch drn_d_105 -s 480 --resume sunrgbd.pth.tar --phase val --batch-size 1 --ms\n```\n\n\n```\n!python segment_rl.py test -d datasets/lsun/ -c 4 --arch drn_d_105 -s 320 --resume lsun.pth.tar --phase val --batch-size 1 --ms\n```\n\n### Functions\n\n\n```\n#             Detect Intersection             #\nfrom collections import defaultdict\nimport math\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.cluster import KMeans\nfrom sympy import Line\n\n\ndef line(p1, p2):\n    A = (p1[1] - p2[1])\n    B = (p2[0] - p1[0])\n    C = (p1[0]*p2[1] - p2[0]*p1[1])\n    return A, B, -C\n\ndef intersection2(L1, L2):\n    D  = L1[0] * L2[1] - L1[1] * L2[0]\n    Dx = L1[2] * L2[1] - L1[1] * L2[2]\n    Dy = L1[0] * L2[2] - L1[2] * L2[0]\n    if D != 0:\n        x = Dx / D\n        y = Dy / D\n        return x,y\n    else:\n        return False\n\n\ndef regression(img, x, y, color=(255, 0, 0)):\n\n  y_at_border = np.array([0, img.shape[0]])\n  p = np.polyfit(y, x, deg=1)\n  x_at_border = np.poly1d(p)(y_at_border)\n\n  cv2.line(img, (int(x_at_border[0]), int(y_at_border[0])), (int(x_at_border[1]), int(y_at_border[1])), color, 2)\n\n  return x_at_border, y_at_border\n\n\ndef drawLines(img, lines, color=(255,0,0)):\n  \"\"\"\n  Draw lines on an image\n  \"\"\"\n\n  centroids = list()\n  r_xs = list()\n  r_ys = list()\n  for line_ in lines:\n      for rho,theta in line_:\n          a = np.cos(theta)\n          b = np.sin(theta)\n          x0 = a*rho\n          y0 = b*rho\n          x1 = int(x0 + 1000*(-b))\n          y1 = int(y0 + 1000*(a))\n          x2 = int(x0 - 1000*(-b))\n          y2 = int(y0 - 1000*(a))\n\n          slope = (y1 - y0) / float(x1 - x0)\n          angle = math.degrees(math.atan(slope))\n          if abs(angle) > 80:\n            # print(img.shape[1])\n            h_layout = line((0, 0), (img.shape[1], 0))\n            h_layout_lower = line((0, img.shape[0]), (img.shape[1], img.shape[0]))\n            r = intersection2(h_layout, line((x1, y1), (x2, y2)))\n            r_lower = intersection2(h_layout_lower, line((x1, y1), (x2, y2)))\n            # cv2.line(img, (int(x1), int(y1)), (int(x2), int(y2)), color, 2)\n            cv2.line(img, (int(r[0]), int(r[1])), (int(r_lower[0]), int(r_lower[1])), color, 2)\n            center_p = (int((r[0] + r_lower[0]) / 2), int((r[1] + r_lower[1])/ 2))\n            centroids.append(center_p)\n\n            r_xs.append((r[0], r_lower[0]))\n            r_ys.append((r[1], r_lower[1]))\n            cv2.circle(img, center_p, 10, (255, 0, 255), -1)\n\n  cv2.line(img, (int(0), int(0)), (int(0), int(img.shape[0])), color, 2)\n  cv2.line(img, (int(img.shape[1]), int(0)), (int(img.shape[1]), int(img.shape[0])), color, 2)\n  cv2.circle(img, (0, int(img.shape[0] / 2)), 10, (255, 0, 255), -1)\n  cv2.circle(img, (img.shape[1], int(img.shape[0] / 2)), 10, (255, 0, 255), -1)\n  centroids.append((0, int(img.shape[0] / 2)))\n  centroids.append((img.shape[1], int(img.shape[0] / 2)))\n\n  return r_xs, r_ys, centroids   \n\nfrom scipy.spatial import distance as sci_dist\n\ndef order_points(pts):\n\n  xSorted = pts[np.argsort(pts[:, 0]), :]\n  leftMost = xSorted[:2, :]\n  rightMost = xSorted[2:, :]\n  leftMost = leftMost[np.argsort(leftMost[:, 1]), :]\n  (tl, bl) = leftMost\n  D = sci_dist.cdist(tl[np.newaxis], rightMost, \"euclidean\")[0]\n  (br, tr) = rightMost[np.argsort(D)[::-1], :]\n\n  return np.array([tl, tr, br, bl], dtype=\"float32\")\n\n\n```\n\n\n```\nfrom PIL import Image\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom XiaohuLuVPDetection.lu_vp_detect.vp_detection import VPDetection\nimport time\n\n\nlength_thresh = 50\nprincipal_point = None\nfocal_length = 1300 # 1102.79\nseed = 1300\nvpd = VPDetection(length_thresh, principal_point, focal_length, seed)\n\n# import os\nimport cv2\nimport pylab as pl\nfrom skimage import morphology as mp\nimport sys\n\n\norg_path = 'datasets/lsun/images/'\nimage_path = 'drn_d_105_024_val_ms/images/'\nrefer_path = '../refer_data/wall/myxkehu1kfzggursepnk0tfiyps8zbs5umvzv8d92r6hhxejgawebwsufssgov5q-.jpg'\nval_image_list = os.listdir(image_path)\n\none_iter = False\nstart_index = 0\nfor image_index, image in enumerate(val_image_list):\n\n  if image_index < start_index:\n    continue\n  image = 'b11f628608c14cb70d252aec023220c0a11312e7.png'\n  print('image_index :', val_image_list.index(image))\n  one_iter = True\n\n  # print(image)\n  img = Image.open(image_path + image)\n  # print(type(img))\n  img_np = np.invert(np.asarray(img))\n  # print(img_np.max(), img_np.min())\n  ret, thr = cv2.threshold(img_np, 254, 255, cv2.THRESH_BINARY_INV)\n  # img_bgr = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)\n  # img_bgr_np = np.asarray(img_rgb)\n\n  org = Image.open(org_path + image)\n  org_np = np.asarray(org)\n\n  # vps = vpd.find_vps(org_np)\n  vps = vpd.find_vps(org_path + image)\n  vl_img = vpd.create_debug_VP_image()\n  # print(img_np.shape, org_np.shape, (img_np.dtype), (org_np.dtype))\n\n\n  # print(img_np.shape, org_np.shape)\n\n  # concat = np.hstack((org_np, img_np))\n  print(image)\n  # plt.subplot(131)\n  # plt.imshow(org)\n  # plt.show()\n  img_size = (org_np.shape[1], org_np.shape[0])\n  \n  scale_factor = 6\n  print('scale_factor :', scale_factor)\n\n  refer = Image.open(refer_path)\n  refer = np.asarray(refer)\n  # if scale_factor >= 1:\n\n  #     refer_size\uc640 img_size\uac00 \ub3d9\uc77c\ud558\uac70\ub098 refer_size\uac00 \uc791\uc740 \uacbd\uc6b0\ub97c \uace0\ub824\ud574\uc57c\ud55c\ub2e4.     #\n  refer = np.tile(refer, (scale_factor, scale_factor, 1))\n  size_ratio = math.floor(min((refer.shape[0] / (org_np.shape[0] * 1.5)), (refer.shape[1] / (org_np.shape[1] * 1.5))))\n  refer = Image.fromarray(refer).resize((int(refer.shape[1] / size_ratio), int(refer.shape[0] / size_ratio)))\n  # plt.imshow(np.asarray(refer))\n  # plt.show()\n\n  # plt.imshow(refer)\n  # plt.show()\n  # size_ratio = math.floor(min((refer.shape[0] / img_size[0]), (refer.shape[1] / img_size[1])))\n  # refer = Image.fromarray(refer).resize((int(refer.shape[1] / size_ratio), int(refer.shape[0] / size_ratio)))\n  # # plt.imshow(np.asarray(refer))\n  # # plt.show()\n  # refer = np.asarray(refer)[:img_size[0], :img_size[1]]\n\n  # plt.imshow(refer)\n  # plt.show()\n\n\n  # plt.subplot(133)\n  # plt.imshow(img)\n  # plt.show()\n\n  # img = org_np\n  # print(img.shape)\n  # org = org_np\n  # hsv_ = cv2.cvtColor(org, cv2.COLOR_RGB2HSV)\n  # hsv_added = cv2.addWeighted(org, 0.7, hsv_, 0.3, 0)\n  # kernel_size, low_threshold, high_threshold = 5, 0, 150\n  # hsv_added = cv2.GaussianBlur(hsv_added, (kernel_size, kernel_size), 0)\n  # hsv_added = cv2.Canny(hsv_added, low_threshold, high_threshold)\n  # hsv_added = np.invert(hsv_added)\n  # plt.subplot(133)\n  # plt.imshow(hsv_added)\n  # plt.show()\n\n  # print(hsv_added.shape, hsv_added.dtype)\n\n  tun = thr        #your tunnel image\n  skl = mp.medial_axis(tun).astype(np.uint8) * 255\n  # skl = Image.fromarray(skl)           #skeleton\n  # print(skl.dtype)\n  # print(thr.dtype)\n  # print(np.asarray(skl).shape)\n\n  # skl_bgr = cv2.cvtColor(skl, cv2.COLOR_GRAY2BGR)\n  #               Draw Houghlines               # \n\n  # Make binary image\n  # blur = cv2.medianBlur(skl, 5)\n  # adapt_type = cv2.ADAPTIVE_THRESH_GAUSSIAN_C\n  # thresh_type = cv2.THRESH_BINARY_INV\n  # bin_img = cv2.adaptiveThreshold(blur, 127, adapt_type, thresh_type, 11, 2)\n  # skl = cv2.Canny(skl,10,150,apertureSize=5)\n  rho = 1\n  theta = np.pi/180\n  thresh = 50\n  lines = cv2.HoughLines(skl, rho, theta, thresh)\n\n  # print(lines)\n  \n  # plt.imshow(skl)\n  # plt.show()\n\n  # Draw all Hough lines in red\n  img_with_all_lines = np.copy(skl)\n  img_with_all_lines = cv2.cvtColor(img_with_all_lines, cv2.COLOR_GRAY2RGB)\n  # plt.imshow(img_with_all_lines)\n  # plt.show()\n  org_np = org_np.astype(np.uint8)\n  org_np2 = org_np.copy()\n\n  start = time.time()\n\n  r_x_list, r_y_list, centroids_list = drawLines(org_np2, lines)\n  drawLines(img_with_all_lines, lines)\n  # img_with_all_lines = cv2.cvtColor(img_with_all_lines, cv2.COLOR_GRAY2RGB)\n\n\n  # try:\n  vps = vpd.find_vps(skl)\n  vl_img, vl_list = vpd.create_debug_VP_image()\n\n  # plt.imshow(skl)\n  # plt.show()\n\n  # except Exception as e:\n  #   print(e)\n  # pl.subplot(121)\n  # pl.imshow(tun,cmap=pl.cm.gray)\n\n  # #Create default Fast Line Detector (FSD)\n  # fld = cv2.ximgproc.createFastLineDetector()\n  # #Detect lines in the image\n  # lines = fld.detect(skl)\n  # #Draw detected lines in the image\n  # drawn_img = fld.drawSegments(skl,lines)\n\n  centroids_data = np.array(centroids_list)[:, [0]]\n  print('len(r_x_list), len(r_y_list) :', len(r_x_list), len(r_y_list))\n  print('centroids_data.shape :', centroids_data.shape)\n  mms = MinMaxScaler()\n  cen_data =mms.fit_transform(centroids_data)\n  # print('cen_data :', cen_data)\n  K = range(2, 6)\n  s_dist = list()\n  for k in K:\n    if cen_data.shape[0] < k:\n      break\n    km = KMeans(n_clusters=k)\n    km = km.fit(cen_data)\n    inertia = km.inertia_\n    s_dist.append(inertia)\n    \n    # if inertia <= 0:\n    #   print('vertical line number =', k)\n    #   break\n  mms2 = MinMaxScaler()\n  mms_s_dist = mms2.fit_transform(np.array(s_dist).reshape(-1, 1))\n  k_thresh = 0.1\n  # plt.plot(range(len(mms_s_dist)), mms_s_dist)\n  # plt.show()\n\n  if cen_data.shape[0] > 2:\n    for i in range(len(mms_s_dist)):\n      if mms_s_dist[i] < k_thresh:\n        k = i + 2\n        break\n  else:\n    k = 2\n\n  #     k Confirmation : Comparing k.cluster_centers_ dist  #\n  while True:    \n\n    km = KMeans(n_clusters=k)\n    km = km.fit(cen_data)\n    if k <= 2:\n      break\n\n    cluster_centroids = km.cluster_centers_\n    # print('cluster_centroids :', cluster_centroids)\n    error_exist = False\n    for i in range(len(cluster_centroids) - 1):\n      for j in range(i + 1, len(cluster_centroids)):\n        if abs(cluster_centroids[i] - cluster_centroids[j]) < 0.05:\n          error_exist = True\n    if error_exist:\n      k -= 1\n    else:\n      break\n\n  print('k is', k)\n\n  predict_cen = km.predict(cen_data)\n  print(predict_cen)\n\n  keys = list(range(k))\n  for rm in predict_cen[-2:]:\n    keys.remove(rm)\n  print('keys :', keys)\n\n  skl_rgb = cv2.cvtColor(skl, cv2.COLOR_GRAY2RGB)\n  skl_copy = np.copy(skl_rgb)\n\n  black_plane = np.zeros(skl_rgb.shape).astype(np.uint8)\n  black_plane2 = np.zeros(skl_rgb.shape).astype(np.uint8)\n\n  \n  reg_xs = list()\n  reg_ys = list()\n  for key in keys:\n    temp_rx = tuple()\n    temp_ry = tuple()\n    for pred_key, r_x, r_y in zip(predict_cen[:-2], r_x_list, r_y_list):\n      if key == pred_key:\n        temp_rx += r_x\n        temp_ry += r_y\n\n    #       Regression Multiple Lines     #\n    border_x, border_y = regression(org_np2, temp_rx, temp_ry)\n    regression(black_plane, temp_rx, temp_ry)\n    print(border_x, border_y)\n\n    reg_xs.append(border_x)\n    reg_ys.append(border_y)\n\n\n  # plt.figure(figsize=(3,3))\n  # plt.plot(range(2, len(mms_s_dist) + 2), mms_s_dist)\n  # plt.show()\n  # print(s_dist)\n\n  # cen_data = mms.transfrom(c)\n  # plt.subplot(132)\n  # pl.imshow(skl,'gray')\n  # plt.imshow(img_with_all_lines)\n  # plt.imshow(cv2.cvtColor(vl_img, cv2.COLOR_RGB2GRAY))\n  # plt.imshow(vl_img)\n  # plt.imshow(drawn_img)\n  # plt.subplot(133)\n  # plt.imshow(cv2.cvtColor(skl, cv2.COLOR_GRAY2RGB))\n  # plt.show()\n\n\n  #           VL Segmentation             #\n  # Angle between line1 and x-axis\n  # print(len(vl_list))\n  v_lines = list()\n  h_lines = list()\n\n  for vl in vl_list:\n    x0, y0, x1, y1 = vl\n    slope = (y1 - y0) / float(x1 - x0)\n    angle = math.degrees(math.atan(slope))\n    # print(angle)\n    \n    # temp_skl = np.copy(skl)\n\n    if abs(angle) > 80:\n      cv2.line(skl_copy, (int(x1), int(y1)), (int(x0), int(y0)), (255, 0, 0), 3,\n                       cv2.LINE_AA)\n      v_lines.append(vl)\n      \n    elif abs(angle) < 70:\n      cv2.line(skl_copy, (int(x1), int(y1)), (int(x0), int(y0)), (0, 0, 255), 2,\n                       cv2.LINE_AA)\n      h_lines.append(vl)\n\n    # plt.imshow(temp_skl)\n    # plt.show()\n\n\n  # print('len(v_lines) :', len(v_lines))\n  # print('len(h_lines) :', len(h_lines))\n  \n  #         Extend v_lines and draw h_lines       #\n  all_closest_inters = list()\n  all_centroid_inters = list()\n  h_border = line((0, 0), (skl_copy.shape[1], 0))\n  h_border_lower = line((0, skl_copy.shape[0]), (skl_copy.shape[1], skl_copy.shape[0]))\n  for reg_x, reg_y in zip(reg_xs, reg_ys):\n\n      left_vh_intersections = list()\n      right_vh_intersections = list()\n\n      left_angle = list()\n      right_angle = list()\n\n      vline = line((reg_x[0], reg_y[0]), (reg_x[1], reg_y[1]))\n      intersections = list()\n      for h_line in h_lines:\n        hline = line(h_line[:2], h_line[2:])\n        center_h_x = (h_line[0] + h_line[2]) / 2\n        center_v_x = (reg_x[0] + reg_x[1]) / 2\n\n        slope = (h_line[3] - h_line[1]) / float(h_line[2] - h_line[0])\n        angle = math.degrees(math.atan(slope))\n        \n        if center_h_x < center_v_x:\n          left_vh_intersections.append(intersection2(vline, hline))\n          left_angle.append(angle)\n        else:\n          right_vh_intersections.append(intersection2(vline, hline))\n          right_angle.append(angle)\n          \n      print('len(left_vh_intersections) :', len(left_vh_intersections))\n      print('len(right_vh_intersections) :', len(right_vh_intersections))\n\n      #     Find Close Intersection Points in vline     #\n      close_points = list()\n      close_thr = 30\n      angle_gap = 10\n      for (ix, iy), l_angle in zip(left_vh_intersections, left_angle):\n        for (jx, jy), r_angle in zip(right_vh_intersections, right_angle):\n          dist = math.hypot(jx - ix, jy - iy)\n          # print(dist)\n          if dist < close_thr:\n            # print(l_angle, r_angle)\n            if abs(l_angle - r_angle) > angle_gap:\n              intersections.append((ix, iy, jx, jy))\n              cv2.circle(black_plane, (int(ix), int(iy)), 5, (255, 0, 255), -1)\n              cv2.circle(black_plane, (int(jx), int(jy)), 5, (255, 255, 0), -1)\n\n      #     Find intersections between horizontal border and vertical lines    #\n      r = intersection2(h_border, vline)\n      r_lower = intersection2(h_border_lower, vline)\n      # print(r)\n      # print(r + r)\n\n      intersections.append(r + r)\n      intersections.append(r_lower + r_lower)\n      intersections_ = intersections.copy()\n\n      imms = MinMaxScaler()\n      intersections = np.array(intersections)[:, [1, 3]]\n      inter_data =imms.fit_transform(intersections)\n      K = range(2, 5)\n      s_dist = list()\n      for k in K:\n        if inter_data.shape[0] < k:\n          break\n        km = KMeans(n_clusters=k)\n        km = km.fit(inter_data)\n        inertia = km.inertia_\n        s_dist.append(inertia)\n      # plt.plot(s_dist)\n      # plt.show()\n\n      print(s_dist)\n      mms2 = MinMaxScaler()\n      mms_s_dist = mms2.fit_transform(np.array(s_dist).reshape(-1, 1))\n      k_thresh = 0.025\n      # print(mms_s_dist)\n      # plt.plot(range(len(mms_s_dist)), mms_s_dist)\n      # plt.show()\n\n      if inter_data.shape[0] > 2:\n        for i in range(len(mms_s_dist)):\n          if mms_s_dist[i] < k_thresh:\n            k = i + 2\n            break\n          elif i == len(mms_s_dist) - 1:\n            k = 4\n      else:\n        k = 2\n      \n      #     k Confirmation : Comparing k.cluster_centers_ dist  #\n      while True:    \n        km = KMeans(n_clusters=k)\n        km = km.fit(inter_data)        \n        if k <= 2:\n          break\n        cluster_centroids = km.cluster_centers_[:, [1]]\n        # print('cluster_centroids :', cluster_centroids)\n        error_exist = False\n        for i in range(len(cluster_centroids) - 1):\n          for j in range(i + 1, len(cluster_centroids)):\n            if abs(cluster_centroids[i] - cluster_centroids[j]) < 0.05:\n              error_exist = True\n        if error_exist:\n          k -= 1\n        else:\n          break\n\n      print('k is ', k)\n      predict_inter = km.predict(inter_data)\n      print(predict_inter)\n\n      keys = list(range(k))\n      for rm in predict_inter[-2:]:\n        keys.remove(rm)\n      print('keys :', keys)\n\n      #     \ud574\ub2f9 \ud0a4 \uc548\uc5d0\uc11c\uc758 closest intersection \ub450\uc30d\uc758 centroid\ub97c \uad6c\ud558\uba74 \ub41c\ub2e4.      #\n      centroid_inters = list()\n      closest_inters = list()\n      temp_black = black_plane2.copy()\n      for key in keys:\n        temp_inter_left = list()\n        temp_inter_right = list()\n        \n        for pred_key, inter_point in zip(predict_inter[:-2], intersections_[:-2]):\n          if key == pred_key:\n            temp_inter_left.append(inter_point[:2])\n            temp_inter_right.append(inter_point[2:])\n          # else:     \n          #   cv2.circle(black_plane2, (int(inter_point[0]), int(inter_point[1])), 5, (255, 0, 255), -1)\n        # plt.imshow(temp_black)\n        # plt.show()\n\n        print('len(temp_inter_left) :', len(temp_inter_left))\n        print('len(temp_inter_right) :', len(temp_inter_right))\n        min_dist = close_thr\n        closest_p = None\n        closest_inter = None\n        for ix, iy in temp_inter_left:\n          for jx, jy in temp_inter_right:\n            dist = math.hypot(jx - ix, jy - iy)\n            # print(dist)\n            if dist < min_dist:\n                min_dist = dist\n                closest_p = ((ix + jx) / 2, (iy + jy) / 2)\n                closest_inter = [ix, iy, jx, jy]\n                # closest_inter = (ix, iy, jx, jy)\n                \n              # print('min_dist :', min_dist)\n        \n        if closest_p:\n          centroid_inters.append(closest_p)\n          closest_inters.append(closest_inter)\n          cv2.circle(black_plane, (int(closest_p[0]), int(closest_p[1])), 5, (0, 255, 0), -1)\n\n      #       \uc5ec\uae30\uc11c append\ud558\ub294 closeest_inters\ub294 \ud56d\uc0c1 2\uac1c\ub97c \uc720\uc9c0\ud574\uc57c\ud55c\ub2e4.    #\n      #       \ub2e8, intersection\uc774 1\uac1c\uc774\uba74 \ub098\uc911\uc5d0 middle section refering \ud63c\ub780\uc744 \ubc29\uc9c0\ud558\uae30 \uc704\ud574 \uc880 \ub2e4\ub978 \ud615\uc2dd\uc73c\ub85c     #\n      #       border intersection\uc744 \uc228\uaca8\uc11c \ubcf4\ub0b4\uc900\ub2e4.      #\n      #       intersection\uc774 \uc874\uc7ac\ud558\uc9c0 \uc54a\ub294 vline\uc740 \uc5c6\uc564\ub2e4.      #\n      if len(closest_inters) != 0:\n        if len(closest_inters) == 1:\n          #       check ceil / floor type inter       #\n          #       ceil condition      #\n          if (closest_inters[0][1] + closest_inters[0][3]) / 2 < (1 / 3) * org_np.shape[0]:\n            opposite_inters = r_lower\n          else:\n            opposite_inters = r\n          closest_inters = [closest_inters[0] + list(opposite_inters)]\n          # print('closest_inters :', closest_inters)\n\n        all_centroid_inters.append(centroid_inters)\n        all_closest_inters.append(closest_inters)\n\n  h_intersections = list()\n  v_border = line((0, 0), (0, skl_copy.shape[0]))\n  v_border_lower = line((skl_copy.shape[1], 0), (skl_copy.shape[1], skl_copy.shape[0]))\n  for h_line in h_lines:\n\n      #       Find Intersection between v_line, h_line      #\n      vh_intersections_x = list()\n      vh_intersections_y = list()\n\n      hline = line(h_line[:2], h_line[2:])\n      for reg_x, reg_y in zip(reg_xs, reg_ys):\n        vline = line((reg_x[0], reg_y[0]), (reg_x[1], reg_y[1]))\n\n        #     Extract only x - coordination     #\n        vh_intersections_x.append(intersection2(vline, hline)[0])\n        vh_intersections_y.append(intersection2(vline, hline)[1])\n\n      # h_x = np.array([h_line[0], h_line[2]])\n      # h_y = np.array([h_line[1], h_line[3]])\n      # ex_h_x, ex_h_y = extended(h_x, h_y, 500)\n      # ex_h_line = line((int(h_x[0]), int(h_y[0])), (int(h_x[1]), int(h_y[1])))\n      r = intersection2(v_border, hline)\n      r_lower = intersection2(v_border_lower, hline)\n\n      vh_intersections_x.append(r[0])\n      vh_intersections_y.append(r[1])\n      vh_intersections_x.append(r_lower[0])\n      vh_intersections_y.append(r_lower[1])\n\n      sorted_vh_inter_x = sorted(vh_intersections_x)\n      # print('vh_intersections_x :', vh_intersections_x)\n      # print('sorted_vh_inter_x :', sorted_vh_inter_x)\n\n      center_h_x = (h_line[0] + h_line[2]) / 2\n      # print('center_h_x :', center_h_x)\n      \n      #       hline \uc0c1\uc758 \uad50\ucc28\uc810\uc744 \ucc3e\uc544\ub0b4\uc11c \ubc94\uc704 \ub0b4\uc5d0\uc11c \uc5f0\uacb0\ud55c\ub2e4.      #\n      for i in range(1, len(sorted_vh_inter_x)):\n\n        if sorted_vh_inter_x[i - 1] <= center_h_x <= sorted_vh_inter_x[i]:\n          lx, ly = sorted_vh_inter_x[i - 1], vh_intersections_y[vh_intersections_x.index(sorted_vh_inter_x[i - 1])]\n          rx, ry = sorted_vh_inter_x[i], vh_intersections_y[vh_intersections_x.index(sorted_vh_inter_x[i])]\n          # print('lx, ly, rx, ry :', lx, ly, rx, ry)\n          #       \uc774\uacf3\uc758 lx, ly, rx, ry \ub294 close_p \ub2e4. \uc88c\uc6b0\ub85c \ub098\ub258\uc5b4\uc9c4 lx, ly\uac00 \uc544\ub2c8\ub2e4.     #\n            \n            #       \uc815\uc81c\ub41c \uad50\ucc28\uc810\uc744 \ub9cc\ub4dc\ub294 hline\ub9cc \uc0ac\uc6a9\ud574\uc57c\ud55c\ub2e4.        #\n          for inters in all_closest_inters:\n            for inter in inters:\n              if lx in inter or rx in inter:\n                h_intersections.append((lx, ly, rx, ry))\n                cv2.line(black_plane, (int(lx), int(ly)), (int(rx), int(ry)), (0, 0, 255), 1, cv2.LINE_AA)\n          \n\n  #       vline \uae30\uc900\uc73c\ub85c \uad6c\ud68d\ud574\uc57c\ud55c\ub2e4. -> \uac00\uc7a5 \uc67c\ucabd / \uc624\ub978\ucabd vline + \uad6c\uc5ed \uba3c\uc800 \ucc3e\uc544 \uc791\uc5c5\ud558\uae30     #\n  #       vline \ubcc4\ub85c \uad6c\ud68d \ub098\ub204\uae30      #\n  h_intersections = list(set(h_intersections))\n  print('np.array(all_closest_inters).shape :', np.array(all_closest_inters).shape)\n  all_closest_inters = np.array(all_closest_inters)\n  print('len(all_closest_inters) :', len(all_closest_inters))\n\n  center_xs = list()\n  for inters in all_closest_inters:\n    #     all_closest_inter\uac00 \uc815\ub82c\ub418\uc9c0 \uc54a\uc558\ub2e4\uba74 inters type = list()      #\n    sum_x = 0\n    for inter in inters:\n      sum_x += inter[0] + inter[2]\n    center_xs.append(sum_x / len(inters) * 2)\n  sorted_center_xs = sorted(center_xs)\n\n  sorted_index = list()\n  for center_x in sorted_center_xs:\n    # print('center_x :', center_x)\n    sorted_index.append(center_xs.index(center_x))\n  # print('sorted_index :', sorted_index)\n  #       sorted_center_xs \uc21c\uc11c\ub85c all_closest_inter\ub97c \uc815\ub82c\ud55c\ub2e4.     #\n  #       index list\ub97c \ucd94\ucd9c\ud574\uc11c for \ubb38\uc73c\ub85c all_closest_inter\uc758 inters\ub97c \ucd94\ucd9c\ud574\n  #       sorted_all ... \uc5d0 append \uc2dc\ud0a8\ub2e4.      #\n  sorted_all_closest_inters = list()\n  sorted_all_centroid_inters = list()\n  for s_index in sorted_index:\n    sorted_all_closest_inters.append(all_closest_inters[s_index])\n    sorted_all_centroid_inters.append(all_centroid_inters[s_index])\n  all_closest_inters = sorted_all_closest_inters\n  all_centroid_inters = sorted_all_centroid_inters\n\n\n  for inters_i, inters in enumerate(all_closest_inters):\n\n    # print('inters :', inters)\n    inter_x = np.array(inters)[:, [0, 2]]\n    inter_y = np.array(inters)[:, [1, 3]]\n\n    #      vline \ubcc4\ub85c \uc591\uc606\uc73c\ub85c \uc791\uc5c5\uc744 \ud558\uba74 len(vline) = 1\uc758 \uc791\uc5c5\uc744 \ubc18\ubcf5\ud560 \ud544\uc694\uac00 \uc5c6\uc5b4\uc9c4\ub2e4.    #\n    iter = False\n    while True:\n\n      four_inters = list()\n      find_pair = True\n      centroid_inters = all_centroid_inters[inters_i]\n\n      if not iter:\n        #       vline \uc6b0\uce21 session      #\n        #   vline \uc6b0\ud3b8 \uc88c\ud45c   #\n        final_xs = inter_x[:, [1]].reshape(-1, )\n        final_ys = inter_y[:, [1]].reshape(-1, )\n        # print(final_xs)\n        # four_inters.append([final_xs[0], final_ys[0]])\n        four_inters.append(centroid_inters[0])\n        # print(four_inters)\n        \n        #       intersection\uc774 1\uac1c\uc774\uace0 \uc624\ub978\ucabd \ub05d vline\uc774\uba74, border intersection\uc744 \ucd94\uac00\ud574\uc900\ub2e4.   #\n        #       \uc624\ub978\ucabd \ub05d\uc774 \uc544\ub2c8\uace0 \ud604\uc7ac vline\uc758 \uad50\ucc28\uc810\uacfc \ub2e4\uc74c vline\uc758 \uad50\ucc28\uc810\uc774\uac19\uc740 \uc704\uce58\uc5d0 \uc5c6\uc73c\uba74 \ud3c9\ud589 copy,    #\n        #       \ud604\uc7ac \uad50\ucc28\uc810\uc774 \uc5c6\uace0 \ub2e4\uc74c \uad50\ucc28\uc810\ub3c4 \uc5c6\uc73c\uba74 border intersection     #\n        #       \ub458\ub2e4 \uc788\uc73c\uba74 \ucd94\uac00      #\n        #        border inter parallel copy     #\n\n        if len(inters[0]) == 6:\n          print('len(inter[0]) == 6')\n          #       \uc624\ub978\ucabd \ub05d vline \uc774\uba74        #\n          if inters_i == len(all_closest_inters) - 1:\n            print('inters_i == len(all_closest_inters) - 1')\n            four_inters.append(inters[0][-2:])\n            four_inters.append([org_np.shape[1], inters[0][-1]])\n          else:\n            find_pair = False\n            next_inters = np.array(all_closest_inters[inters_i + 1])\n            next_centroid_inters = np.array(all_centroid_inters[inters_i + 1])\n            print(next_centroid_inters)\n            four_inters.append(next_centroid_inters[0])\n            if len(next_inters) == 2:\n              print('len(next_inters) == 2')\n              #     \uc5c6\ub294 \ubd80\ubd84 \ud3c9\ud589 copy   #\n              four_inters.append(next_centroid_inters[1])\n\n              #     1. \uc5c6\ub294 \ubd80\ubd84\uc774 \uc5b4\ub514\uc778\uc9c0 \ud655\uc778\ud574\uc57c\ud55c\ub2e4.      #\n              #     2. copy\ud560 \ubd80\ubd84\uc758 \uc778\ub371\uc2a4 \ubc88\ud638\ub97c \ud655\uc778\ud574\uc57c\ud55c\ub2e4.      #\n              if inters[0][-1] == 0: # -> \ucc9c\uc7a5 \ubd80\ubd84 \uad50\ucc28\uc810\uc774 \uc5c6\ub2e4.\n                print(type(next_inters))\n                if np.mean(next_inters[[0], [1, 3]]) < np.mean(next_inters[[1], [1, 3]]):\n                  y_in = np.mean(next_inters[[0], [1, 3]])\n                else:\n                  y_in = np.mean(next_inters[[1], [1, 3]])\n              else:   # -> \ubc14\ub2e5 \uad50\ucc28\uc810\uc774 \uc5c6\ub2e4.    \n                if np.mean(next_inters[[0], [1, 3]]) < np.mean(next_inters[[1], [1, 3]]):\n                  y_in = np.mean(next_inters[[1], [1, 3]])\n                else:\n                  y_in = np.mean(next_inters[[0], [1, 3]])\n\n              x = (inters[0][0], inters[0][2])\n              y = (inters[0][1], inters[0][3])\n              p = np.polyfit(y, x , deg=1)\n              x_out = np.poly1d(p)(y_in)\n              four_inters.append([x_out, y_in])\n\n            else:\n              if inters[0][-1] == next_inters[0][-1]:\n                print('inters[0][-1] == next_inters[0][-1]')\n                #     \uc5c6\ub294 \ubd80\ubd84 border intersection     #\n                four_inters.append(inters[0][-2:])\n                four_inters.append(next_inters[0][-2:])\n\n              else: # \ub2e4\ub978 \uc704\uce58\n                #     \uc5c6\ub294 \ubd80\ubd84 \ud3c9\ud589 copy     #\n                x = (inters[0][0], inters[0][2])\n                y = (inters[0][1], inters[0][3])\n                p = np.polyfit(y, x , deg=1)\n                y_in = np.mean(next_inters[0, [1, 3]])\n                x_out = np.poly1d(p)(y_in)\n                four_inters.append([x_out, y_in])\n\n                x = (next_inters[0][0], next_inters[0][2])\n                y = (next_inters[0][1], next_inters[0][3])\n                p = np.polyfit(y, x , deg=1)\n                y_in = np.mean(inters[0, [1, 3]])\n                x_out = np.poly1d(p)(y_in)\n                four_inters.append([x_out, y_in])\n\n        #      len vline inters = 2     #\n        else:\n          # four_inters.append([final_xs[1], final_ys[1]])\n          four_inters.append(centroid_inters[1])\n\n          #       \uc624\ub978\ucabd \ub05d vline \uc774\uba74      #\n          if inters_i == len(all_closest_inters) - 1:\n            print('inters_i == len(all_closest_inters) - 1')\n          else:\n            find_pair = False\n            inters = np.array(inters)\n            next_inters = np.array(all_closest_inters[inters_i + 1])\n            next_centroid_inters = np.array(all_centroid_inters[inters_i + 1])\n            four_inters.append(next_centroid_inters[0])\n            if len(next_inters) == 2:\n              print('len(next_inters) == 2')\n              four_inters.append(next_centroid_inters[1])\n            else:\n              #     1. \uc5c6\ub294 \ubd80\ubd84\uc774 \uc5b4\ub514\uc778\uc9c0 \ud655\uc778\ud574\uc57c\ud55c\ub2e4.      #\n              #     2. copy\ud560 \ubd80\ubd84\uc758 \uc778\ub371\uc2a4 \ubc88\ud638\ub97c \ud655\uc778\ud574\uc57c\ud55c\ub2e4.      #\n              if next_inters[0][-1] == 0: # -> \ucc9c\uc7a5 \ubd80\ubd84 \uad50\ucc28\uc810\uc774 \uc5c6\ub2e4.\n                print('next_inters[0] :', next_inters[0])\n                print('type(next_inters) :', type(next_inters))\n                inters = np.array(inters)                \n                if np.mean(inters[[0], [1, 3]]) < np.mean(inters[[1], [1, 3]]):\n                  y_in = np.mean(inters[[0], [1, 3]])\n                else:\n                  y_in = np.mean(inters[[1], [1, 3]])              \n              else:   # -> \ubc14\ub2e5 \uad50\ucc28\uc810\uc774 \uc5c6\ub2e4.    \n                if np.mean(inters[0, [1, 3]]) < np.mean(inters[[[1]], [1, 3]]):\n                  y_in = np.mean(inters[[1], [1, 3]])\n                else:\n                  y_in = np.mean(inters[[0], [1, 3]])\n\n              x = (next_inters[0][0], next_inters[0][2])\n              y = (next_inters[0][1], next_inters[0][3])\n              p = np.polyfit(y, x , deg=1)\n              x_out = np.poly1d(p)(y_in)\n              four_inters.append([x_out, y_in])\n\n      #     i = 0 \uc5d0 \ud55c\ud574\uc11c\ub9cc \uc67c\ucabd\uc73c\ub85c\ub3c4 refering \uc9c4\ud589, \ub098\uba38\uc9c0\ub294 \uc624\ub978\ucabd\uc73c\ub85c\ub9cc     #\n      else:\n        #     \ud55c vline\uc5d0 \ub300\ud574 \ubd84\ud3ec\ud558\ub294 \ubaa8\ub4e0 intersection\uc5d0 \ub300\ud55c pair\ub294 \ucc3e\uc544\uc8fc\uc5b4\uc57c \ud55c\ub2e4.   #\n        #   vline \uc88c\ud3b8 \uc88c\ud45c   #\n        final_xs = inter_x[:, [0]].reshape(-1, )\n        final_ys = inter_y[:, [0]].reshape(-1, )\n        # print(final_xs)\n        four_inters.append(centroid_inters[0])\n        # print(four_inters)        \n\n        #       intersection\uc774 1\uac1c\uc774\uba74, border intersection\uc744 \ucd94\uac00\ud574\uc900\ub2e4.   #\n        #        border inter parallel copy     #\n        if len(inters[0]) == 6:\n          print('inters[0][-2:] :', inters[0][-2:])\n          four_inters.append(inters[0][-2:])\n          four_inters.append([0, inters[0][-1]])\n        else:\n          four_inters.append(centroid_inters[1])\n        # print(four_inters)\n\n      print('four_inters :', four_inters)      \n      print('h_intersections :', h_intersections)\n      #             Find intersection pairs by h_intersections            #\n      if find_pair:\n        #       \ub9e8 \uc88c\uc6b0 vline\uc77c \uacbd\uc6b0\uc5d0\ub9cc \ud574\ub2f9\ud558\ub294\ub370 => pair\ub97c \ucc3e\uc544\uc8fc\ub294\uac8c \uc544\ub2c8\ub77c v_border\uc640\uc758      #\n        #       \uad50\ucc28\uc810\uc744 \ucc3e\uc544\uc8fc\ub294\uac8c \ub9de\ub294 \ubc29\ud5a5\uc774\ub2e4.      #\n        for h_inter in h_intersections:\n          for final_x, final_y in zip(final_xs, final_ys):\n            if final_x in h_inter and final_y in h_inter:\n              hline = line(h_inter[:2], h_inter[2:])\n              if iter:\n                print('intersection2(v_border, hline) :', intersection2(v_border, hline))\n                four_inters.append(list(intersection2(v_border, hline)))\n              else:\n                four_inters.append(list(intersection2(v_border_lower, hline)))\n\n      #              Four Intersection \uc644\uc131               #\n      print('four_inters :', four_inters)      \n      if len(four_inters) != 4:\n        print('Error in four_inter == 4')\n        raise Exception\n        break\n\n      #                                   Refering                                 #\n      #     Find Top left / right & Bottom left / right       #\n      #     ->  tl, tr, bl, br     #\n      four_inters = np.array(four_inters)\n      [tl, tr, br, bl] = order_points(four_inters)\n      # print(four_inters.shape)\n      top_length = math.hypot(tl[0] - tr[0], tl[1] - tr[1])\n      bottom_length = math.hypot(bl[0] - br[0], bl[1] - br[1])\n      max_hlength = max(top_length, bottom_length)\n\n      #     1. Compare left / right height     #\n      l_height = bl[1] - tl[1]\n      r_height = br[1] - tr[1]\n\n      #     2. Extend Shorter Height      #\n      if l_height <= r_height:\n        shorter_points = [bl, tl]\n        longer_points = [br, tr]\n      else:\n        shorter_points = [br, tr]\n        longer_points = [bl, tl]\n\n      ex_shorter_points = np.zeros_like(shorter_points)\n      ex_longer_points = np.zeros_like(longer_points)\n\n      print('shorter_points :', shorter_points)\n      x = (shorter_points[0][0], shorter_points[1][0])\n      y = (shorter_points[0][1], shorter_points[1][1])\n      print('shorter x, y :', x, y)\n\n      y_ext = np.array([org_np.shape[0], 0])\n      p = np.polyfit(y, x , deg=1)\n      x_ext = np.poly1d(p)(y_ext)\n\n      ex_shorter_points[0] = [x_ext[0], y_ext[0]]\n      ex_shorter_points[1] = [x_ext[1], y_ext[1]]\n\n      #     Find intersection between (longer + shorter points)'s parallel line and longer line   #\n      long_short_lower = Line(longer_points[0], shorter_points[0])\n      long_short = Line(longer_points[1], shorter_points[1])\n      p_line_lower = long_short_lower.parallel_line(ex_shorter_points[0])\n      p_line = long_short.parallel_line(ex_shorter_points[1])\n      longer_line = Line(longer_points[0], longer_points[1])\n\n      # print('ex_shorter_points[1] in p_line ? :', ex_shorter_points[1] in p_line)\n      # print('p_line_lower.intersection(longer_line) :', p_line_lower.intersection(longer_line)[0][0])\n      ex_longer_points[0] = [p_line_lower.intersection(longer_line)[0][0], p_line_lower.intersection(longer_line)[0][1]]\n      ex_longer_points[1] = [p_line.intersection(longer_line)[0][0], p_line.intersection(longer_line)[0][1]]\n\n      if l_height <= r_height:\n        ex_bl, ex_tl = ex_shorter_points\n        ex_br, ex_tr = ex_longer_points\n      else:\n        ex_br, ex_tr = ex_shorter_points\n        ex_bl, ex_tl = ex_longer_points\n\n      for ex_p in [ex_bl, ex_br, ex_tl, ex_tr]:\n        print(ex_p)\n        # cv2.circle(black_plane2, (int(ex_p[0]), int(ex_p[1])), 10, (255, 0, 255), -1)\n\n      min_x, max_x = min(ex_bl[0], ex_tl[0]), max(ex_br[0], ex_tr[0])\n      min_y, max_y = min(ex_tl[1], ex_tr[1]), max(ex_bl[1], ex_br[1])\n      src_x = max((max_x - min_x), max_hlength) * math.sqrt(2)\n      print('src_x :',  src_x)\n\n      refered = np.asarray(refer)[:int(max_y - min_y), :int(src_x)]\n\n      plt.imshow(refered)\n      plt.title('refered')\n      plt.show()\n\n      #   tl, tr, br, bl    #\n      #     refer\ub97c \uc704\ud574 src_x => 0 \uc73c\ub85c \ub9de\ucdb0\uc900\ub2e4.    #\n      # src = np.array([\n      #     [0, min_y],\n      #     [src_x, min_y],\n      #     [src_x, max_y],\n      #     [0, max_y]], dtype = \"float32\")\n      src = np.array([\n          [0, 0],\n          [src_x, 0],\n          [src_x, max_y - min_y],\n          [0, max_y - min_y]], dtype = \"float32\")\n      dst = np.array([\n                      [ex_tl[0] - min_x, ex_tl[1] - min_y],\n                      [ex_tr[0] - min_x, ex_tr[1] - min_y],\n                      [ex_br[0] - min_x, ex_br[1] - min_y],\n                      [ex_bl[0] - min_x, ex_bl[1] - min_y]], dtype = \"float32\")\n\n      print('src :', src)\n      print('dst :', dst)\n\n      # compute the perspective transform matrix and then apply it\n      matrix = cv2.getPerspectiveTransform(src, dst)\n      refered = cv2.warpPerspective(refered, matrix, (refered.shape[1], refered.shape[0]))\n\n      # print('refered.min() :', refered.min())\n      # print(refered[[0], [0]])\n      # print('refered.shape :', refered.shape)\n      # plt.imshow(refered)\n      # plt.title('warfed')\n      # plt.xlim(min_x, max_x)\n      # plt.xlim(0, max_x - min_x)\n      # plt.ylim(max_y, min_y)\n      # plt.xlim(-1000, 1000)\n      # plt.ylim(1000, -1000)\n      # plt.show()\n      \n      refer_crop = refered[int(abs(min_y)): int(abs(min_y)) + org_np.shape[0], :]\n      # print('refer_crop.shape :', refer_crop.shape)\n\n      plt.imshow(refer_crop)\n      plt.title('cropped refer')\n      plt.xlim(0, max_x)\n\n      plt.show()\n\n      #     Crop Section From Cropped Refer     #\n      #         src_x => 0\uc73c\ub85c \ub9de\ucdb0\uc92c\ub358 \uac83\uc744 \ub418\ub3cc\ub9b0\ub2e4.      #\n      #      \uc798 \uc0dd\uac01\ud574\ubcf4\uba74 y\ucd95\uc73c\ub85c\ub294 \uc774\ub3d9\uc2dc\ud0ac \ud544\uc694\uac00 \uc5c6\ub2e4.      #\n      print('int(min_x) :', int(min_x))\n      print('int(min_y) :', int(min_y))\n      for i in range(refer_crop.shape[1]):\n        for j in range(refer_crop.shape[0]):\n          if sum(refer_crop[j][i]) != 0:\n            if i + int(min_x) < black_plane2.shape[1]:\n              black_plane2[j][i + int(min_x)] = refer_crop[j][i]\n\n      #     i != 0 \uc778 \uacbd\uc6b0 break     #\n      if inters_i == 0 and not iter:\n        iter = True\n        print('iter :', iter)\n      else:\n        break\n\n  if len(all_closest_inters) == 0:\n    refered = np.asarray(refer)[:black_plane2.shape[1], :black_plane2.shape[0]]\n    black_plane2 = refered\n  \n  else:\n    #         Refer\uc758 \ube48 \ubd80\ubd84\uc740 original image\ub85c \ucc44\uc6b4\ub2e4.       #\n    for i in range(black_plane2.shape[1]):\n      for j in range(black_plane2.shape[0]):\n        if sum(black_plane2[j][i]) == 0:\n          black_plane2[j][i] = org_np[j][i]\n  \n  print('elapsed time :', time.time() - start)\n\n\n  for f_inters in four_inters:\n    print(f_inters)\n    cv2.circle(black_plane2, (int(f_inters[0]), int(f_inters[1])), 10, (0, 255, 0), -1)\n\n  \n  plt.figure(figsize=(15, 10))\n\n  plt.subplot(131)\n  plt.imshow(org_np2)\n  plt.xlim(-10, org_np.shape[0] + 10)\n  \n  plt.subplot(132)\n  plt.imshow(black_plane)\n\n  plt.subplot(133)\n  plt.imshow(black_plane2)\n  plt.show()\n\n\n  if one_iter:\n    break\n```\n\n\n```\n\n```\n", "meta": {"hexsha": "baef48c6dbc66c86085a983b5b89b22bab03d3f5", "size": 720232, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Layout Estimation.ipynb", "max_stars_repo_name": "jaytoone/Indoor_Segmentation", "max_stars_repo_head_hexsha": "d99e502f99cb74000483974d931c2da058071bec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Layout Estimation.ipynb", "max_issues_repo_name": "jaytoone/Indoor_Segmentation", "max_issues_repo_head_hexsha": "d99e502f99cb74000483974d931c2da058071bec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Layout Estimation.ipynb", "max_forks_repo_name": "jaytoone/Indoor_Segmentation", "max_forks_repo_head_hexsha": "d99e502f99cb74000483974d931c2da058071bec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-29T15:27:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-29T15:27:56.000Z", "avg_line_length": 720232.0, "max_line_length": 720232, "alphanum_fraction": 0.9417937553, "converted": true, "num_tokens": 11821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.051082738040514976, "lm_q1q2_score": 0.021777674233118608}}
{"text": "##### Copyright 2020 Google LLC.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\n\n\n```\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# Interactive demo: Learning static analyses with the GFSA layer\n\nThis notebook is designed to walk you through training the GFSA layer to perform simple static analyses on Python code, similar to the static analysis experiments in the paper.\n\n\n\n[](https://colab.research.google.com/github/google-research/google-research/blob/master/gfsa/notebooks/demo_learning_static_analyses.ipynb)\n\n## Setting up the environment\n\nThese instructions are designed for running this demo using Google Colab; if you are using a different environment, the setup instructions may differ!\n\nIf you want to follow along, the first step is to connect the Colab runtime to a TPU. You can use the \"Runtime > Change runtime type\" option in the toolbar above.\n\nNext, install necessary dependencies:\n\n\n```\n# Download the GFSA codebase\n!git clone https://github.com/google-research/google-research.git --depth=1\n```\n\n    Cloning into 'google-research'...\n    remote: Enumerating objects: 10043, done.\u001b[K\n    remote: Counting objects: 100% (10043/10043), done.\u001b[K\n    remote: Compressing objects: 100% (8038/8038), done.\u001b[K\n    remote: Total 10043 (delta 1443), reused 7963 (delta 1209), pack-reused 0\u001b[K\n    Receiving objects: 100% (10043/10043), 109.57 MiB | 21.79 MiB/s, done.\n    Resolving deltas: 100% (1443/1443), done.\n    Checking out files: 100% (10525/10525), done.\n\n\n\n```\nimport os\nos.chdir(\"google-research\")\n```\n\n\n```\n# Install Python packages\n!pip install flax labmaze optax tensor2tensor\n```\n\n    Collecting flax\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/2e/ef/1a0c6a869396e4b20a83375fe06d725b5c1711746578ee8dd6969472af41/flax-0.2.2-py3-none-any.whl (148kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 153kB 5.1MB/s \n    \u001b[?25hCollecting labmaze\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/0f/69/9f3b4790affd5353d22608003a555fd9325cc19fe5a3141b563297b4986f/labmaze-1.0.3-cp36-cp36m-manylinux1_x86_64.whl (4.9MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4.9MB 18.0MB/s \n    \u001b[?25hCollecting optax\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1d/94/0a81a6c0aeb1f22840f097dc023cdd803e36d86a0ac8724ad829a51f92a4/optax-0.0.2-py3-none-any.whl (54kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 61kB 7.4MB/s \n    \u001b[?25hCollecting tensor2tensor\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/d6/7c/9e87d30cefad5cbc390bb7f626efb3ded9b19416b8160f1a1278da81b218/tensor2tensor-1.15.7-py2.py3-none-any.whl (1.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.5MB 39.6MB/s \n    \u001b[?25hRequirement already satisfied: jax>=0.1.59 in /usr/local/lib/python3.6/dist-packages (from flax) (0.2.6)\n    Requirement already satisfied: numpy>=1.12 in /usr/local/lib/python3.6/dist-packages (from flax) (1.18.5)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.6/dist-packages (from flax) (3.2.2)\n    Requirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from flax) (0.8)\n    Requirement already satisfied: msgpack in /usr/local/lib/python3.6/dist-packages (from flax) (1.0.0)\n    Requirement already satisfied: absl-py in /usr/local/lib/python3.6/dist-packages (from labmaze) (0.10.0)\n    Requirement already satisfied: six>=1.4.1 in /usr/local/lib/python3.6/dist-packages (from labmaze) (1.15.0)\n    Collecting chex>=0.0.3\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/24/ef/9522eee302d4e3d6504d53d38e7180ca97404c19e638caeacb91cea9b20b/chex-0.0.3-py3-none-any.whl (48kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 5.6MB/s \n    \u001b[?25hRequirement already satisfied: jaxlib>=0.1.37 in /usr/local/lib/python3.6/dist-packages (from optax) (0.1.57+cuda101)\n    Requirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from tensor2tensor) (2.23.0)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from tensor2tensor) (4.41.1)\n    Collecting tf-slim\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/02/97/b0f4a64df018ca018cc035d44f2ef08f91e2e8aa67271f6f19633a015ff7/tf_slim-1.1.0-py2.py3-none-any.whl (352kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 358kB 47.8MB/s \n    \u001b[?25hRequirement already satisfied: gin-config in /usr/local/lib/python3.6/dist-packages (from tensor2tensor) (0.3.0)\n    Collecting bz2file\n      Downloading https://files.pythonhosted.org/packages/61/39/122222b5e85cd41c391b68a99ee296584b2a2d1d233e7ee32b4532384f2d/bz2file-0.98.tar.gz\n    Requirement already satisfied: tensorflow-addons in /usr/local/lib/python3.6/dist-packages (from tensor2tensor) (0.8.3)\n    Requirement already satisfied: google-api-python-client in /usr/local/lib/python3.6/dist-packages (from tensor2tensor) (1.7.12)\n    Collecting tensorflow-probability==0.7.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/3e/3a/c10b6c22320531c774402ac7186d1b673374e2a9d12502cbc8d811e4601c/tensorflow_probability-0.7.0-py2.py3-none-any.whl (981kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 983kB 32.2MB/s \n    \u001b[?25hRequirement already satisfied: opencv-python in /usr/local/lib/python3.6/dist-packages (from tensor2tensor) (4.1.2.30)\n    Requirement already satisfied: tensorflow-datasets in /usr/local/lib/python3.6/dist-packages (from tensor2tensor) (4.0.1)\n    Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from tensor2tensor) (0.16.0)\n    Collecting mesh-tensorflow\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/16/8b/553deb763ce8d00afb17debab7cb14a87b209cd4c6f0e8ecfc8d884cb12a/mesh_tensorflow-0.1.17-py3-none-any.whl (342kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 348kB 37.9MB/s \n    \u001b[?25hRequirement already satisfied: oauth2client in /usr/local/lib/python3.6/dist-packages (from tensor2tensor) (4.1.3)\n    Requirement already satisfied: flask in /usr/local/lib/python3.6/dist-packages (from tensor2tensor) (1.1.2)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.6/dist-packages (from tensor2tensor) (1.1.1)\n    Collecting pypng\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/bc/fb/f719f1ac965e2101aa6ea6f54ef8b40f8fbb033f6ad07c017663467f5147/pypng-0.0.20.tar.gz (649kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 655kB 45.3MB/s \n    \u001b[?25hRequirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from tensor2tensor) (1.4.1)\n    Requirement already satisfied: Pillow in /usr/local/lib/python3.6/dist-packages (from tensor2tensor) (7.0.0)\n    Collecting gunicorn\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/69/ca/926f7cd3a2014b16870086b2d0fdc84a9e49473c68a8dff8b57f7c156f43/gunicorn-20.0.4-py2.py3-none-any.whl (77kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 81kB 8.7MB/s \n    \u001b[?25hRequirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from tensor2tensor) (2.10.0)\n    Collecting kfac\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1c/36/06fe2c757044bb51906fef231ac48cc5bf9a277fc9a8c7e1108d7e9e8cfd/kfac-0.2.3-py2.py3-none-any.whl (191kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 194kB 41.5MB/s \n    \u001b[?25hRequirement already satisfied: gym in /usr/local/lib/python3.6/dist-packages (from tensor2tensor) (0.17.3)\n    Requirement already satisfied: dopamine-rl in /usr/local/lib/python3.6/dist-packages (from tensor2tensor) (1.0.5)\n    Collecting tensorflow-gan\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/0c/2e/62922111d7d50e1900e3030764743ea7735540ce103b3ab30fd5cd2d8a2b/tensorflow_gan-2.0.0-py2.py3-none-any.whl (365kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 368kB 32.8MB/s \n    \u001b[?25hCollecting gevent\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/3f/92/b80b922f08f222faca53c8d278e2e612192bc74b0e1f0db2f80a6ee46982/gevent-20.9.0-cp36-cp36m-manylinux2010_x86_64.whl (5.3MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5.3MB 46.7MB/s \n    \u001b[?25hRequirement already satisfied: opt-einsum in /usr/local/lib/python3.6/dist-packages (from jax>=0.1.59->flax) (3.3.0)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->flax) (2.8.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->flax) (2.4.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->flax) (1.3.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib->flax) (0.10.0)\n    Requirement already satisfied: dm-tree>=0.1.5 in /usr/local/lib/python3.6/dist-packages (from chex>=0.0.3->optax) (0.1.5)\n    Requirement already satisfied: toolz>=0.9.0 in /usr/local/lib/python3.6/dist-packages (from chex>=0.0.3->optax) (0.11.1)\n    Requirement already satisfied: flatbuffers in /usr/local/lib/python3.6/dist-packages (from jaxlib>=0.1.37->optax) (1.12)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->tensor2tensor) (2.10)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->tensor2tensor) (1.24.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->tensor2tensor) (2020.11.8)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->tensor2tensor) (3.0.4)\n    Requirement already satisfied: typeguard in /usr/local/lib/python3.6/dist-packages (from tensorflow-addons->tensor2tensor) (2.7.1)\n    Requirement already satisfied: httplib2<1dev,>=0.17.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor) (0.17.4)\n    Requirement already satisfied: google-auth-httplib2>=0.0.3 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor) (0.0.4)\n    Requirement already satisfied: google-auth>=1.4.1 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor) (1.17.2)\n    Requirement already satisfied: uritemplate<4dev,>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor) (3.0.1)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.6/dist-packages (from tensorflow-probability==0.7.0->tensor2tensor) (4.4.2)\n    Requirement already satisfied: cloudpickle>=0.6.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow-probability==0.7.0->tensor2tensor) (1.3.0)\n    Requirement already satisfied: attrs>=18.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->tensor2tensor) (20.3.0)\n    Requirement already satisfied: tensorflow-metadata in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->tensor2tensor) (0.25.0)\n    Requirement already satisfied: termcolor in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->tensor2tensor) (1.1.0)\n    Requirement already satisfied: protobuf>=3.6.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->tensor2tensor) (3.12.4)\n    Requirement already satisfied: promise in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->tensor2tensor) (2.3)\n    Requirement already satisfied: dill in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->tensor2tensor) (0.3.3)\n    Requirement already satisfied: importlib-resources; python_version < \"3.9\" in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->tensor2tensor) (3.3.0)\n    Requirement already satisfied: pyasn1>=0.1.7 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor) (0.4.8)\n    Requirement already satisfied: rsa>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor) (4.6)\n    Requirement already satisfied: pyasn1-modules>=0.0.5 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor) (0.2.8)\n    Requirement already satisfied: Jinja2>=2.10.1 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor) (2.11.2)\n    Requirement already satisfied: click>=5.1 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor) (7.1.2)\n    Requirement already satisfied: Werkzeug>=0.15 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor) (1.0.1)\n    Requirement already satisfied: itsdangerous>=0.24 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor) (1.1.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy->tensor2tensor) (1.1.0)\n    Requirement already satisfied: setuptools>=3.0 in /usr/local/lib/python3.6/dist-packages (from gunicorn->tensor2tensor) (50.3.2)\n    Requirement already satisfied: pyglet<=1.5.0,>=1.4.0 in /usr/local/lib/python3.6/dist-packages (from gym->tensor2tensor) (1.5.0)\n    Requirement already satisfied: tensorflow-hub>=0.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gan->tensor2tensor) (0.10.0)\n    Collecting greenlet>=0.4.17; platform_python_implementation == \"CPython\"\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/80/d0/532e160c777b42f6f393f9de8c88abb8af6c892037c55e4d3a8a211324dd/greenlet-0.4.17-cp36-cp36m-manylinux1_x86_64.whl (44kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 7.0MB/s \n    \u001b[?25hCollecting zope.interface\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/82/b0/da8afd9b3bd50c7665ecdac062f182982af1173c9081f9af7261091c5588/zope.interface-5.2.0-cp36-cp36m-manylinux2010_x86_64.whl (236kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 245kB 43.8MB/s \n    \u001b[?25hCollecting zope.event\n      Downloading https://files.pythonhosted.org/packages/9e/85/b45408c64f3b888976f1d5b37eed8d746b8d5729a66a49ec846fda27d371/zope.event-4.5.0-py2.py3-none-any.whl\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth>=1.4.1->google-api-python-client->tensor2tensor) (4.1.1)\n    Requirement already satisfied: googleapis-common-protos<2,>=1.52.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-metadata->tensorflow-datasets->tensor2tensor) (1.52.0)\n    Requirement already satisfied: zipp>=0.4; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from importlib-resources; python_version < \"3.9\"->tensorflow-datasets->tensor2tensor) (3.4.0)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.6/dist-packages (from Jinja2>=2.10.1->flask->tensor2tensor) (1.1.1)\n    Building wheels for collected packages: bz2file, pypng\n      Building wheel for bz2file (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for bz2file: filename=bz2file-0.98-cp36-none-any.whl size=6884 sha256=45ffa796f114e5edbf92475ab42982efa3b9b026801025bd0f9217ef533918e8\n      Stored in directory: /root/.cache/pip/wheels/81/75/d6/e1317bf09bf1af5a30befc2a007869fa6e1f516b8f7c591cb9\n      Building wheel for pypng (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pypng: filename=pypng-0.0.20-cp36-none-any.whl size=67162 sha256=8cbc8c8dec3b8620bdbba3a9d660d482ae0c233ef3892a9f18b1e40d4f231711\n      Stored in directory: /root/.cache/pip/wheels/41/6b/ef/0493b536b6d4722c2ae9486691b1d49b922b9877922beeabb3\n    Successfully built bz2file pypng\n    \u001b[31mERROR: kfac 0.2.3 has requirement tensorflow-probability==0.8, but you'll have tensorflow-probability 0.7.0 which is incompatible.\u001b[0m\n    Installing collected packages: flax, labmaze, chex, optax, tf-slim, bz2file, tensorflow-probability, mesh-tensorflow, pypng, gunicorn, kfac, tensorflow-gan, greenlet, zope.interface, zope.event, gevent, tensor2tensor\n      Found existing installation: tensorflow-probability 0.11.0\n        Uninstalling tensorflow-probability-0.11.0:\n          Successfully uninstalled tensorflow-probability-0.11.0\n    Successfully installed bz2file-0.98 chex-0.0.3 flax-0.2.2 gevent-20.9.0 greenlet-0.4.17 gunicorn-20.0.4 kfac-0.2.3 labmaze-1.0.3 mesh-tensorflow-0.1.17 optax-0.0.2 pypng-0.0.20 tensor2tensor-1.15.7 tensorflow-gan-2.0.0 tensorflow-probability-0.7.0 tf-slim-1.1.0 zope.event-4.5.0 zope.interface-5.2.0\n\n\nMake sure JAX can see the TPU:\n\n\n```\n# See https://github.com/google/jax/blob/master/cloud_tpu_colabs/JAX_demo.ipynb\nimport requests\nimport os\n\nif 'COLAB_TPU_ADDR' not in os.environ:\n  raise RuntimeError(\"Please connect to a TPU runtime first!\")\n\nif 'TPU_DRIVER_MODE' not in globals():\n  url = 'http://' + os.environ['COLAB_TPU_ADDR'].split(':')[0] + ':8475/requestversion/tpu_driver_nightly'\n  resp = requests.post(url)\n  TPU_DRIVER_MODE = 1\n\n# Use TPU Driver as JAX's backend.\nfrom jax.config import config\nconfig.FLAGS.jax_xla_backend = \"tpu_driver\"\nconfig.FLAGS.jax_backend_target = \"grpc://\" + os.environ['COLAB_TPU_ADDR']\nprint(config.FLAGS.jax_backend_target)\n```\n\n    grpc://10.48.40.138:8470\n\n\n\n```\nimport jax\njax.devices()\n```\n\n\n\n\n    [TpuDevice(id=0, host_id=0, coords=(0,0,0), core_on_chip=0),\n     TpuDevice(id=1, host_id=0, coords=(0,0,0), core_on_chip=1),\n     TpuDevice(id=2, host_id=0, coords=(1,0,0), core_on_chip=0),\n     TpuDevice(id=3, host_id=0, coords=(1,0,0), core_on_chip=1),\n     TpuDevice(id=4, host_id=0, coords=(0,1,0), core_on_chip=0),\n     TpuDevice(id=5, host_id=0, coords=(0,1,0), core_on_chip=1),\n     TpuDevice(id=6, host_id=0, coords=(1,1,0), core_on_chip=0),\n     TpuDevice(id=7, host_id=0, coords=(1,1,0), core_on_chip=1)]\n\n\n\nYou should see 8 TPU devices connected above!\n\n## Imports and configuration\n\nLet's import and set up some things we will need later:\n\n\n```\nimport functools\nimport itertools\nimport sys\nimport datetime\n\nfrom absl import logging\nfrom absl import flags\n\nimport astunparse\nimport dataclasses\nimport flax\nimport gast\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport numpy as np\nimport jax.numpy as jnp\n```\n\n\n```\nnp.set_printoptions(linewidth=150)\nlogging.use_python_logging()\nlogging.set_verbosity(\"info\")\nlogging.set_stderrthreshold(\"info\")\n```\n\n\n```\nfrom gfsa import automaton_builder\nfrom gfsa import generic_ast_graphs\nfrom gfsa import graph_types\nfrom gfsa import jax_util\nfrom gfsa import py_ast_graphs\nfrom gfsa import schema_util\n\nfrom gfsa.datasets import data_loading\nfrom gfsa.datasets import graph_bundle\nfrom gfsa.datasets import graph_edge_util\nfrom gfsa.datasets.random_python import tasks\nfrom gfsa.datasets.random_python import python_numbers_control_flow\n\nfrom gfsa.model import automaton_layer\nfrom gfsa.model import edge_supervision_models\nfrom gfsa.model import model_util\n\nfrom gfsa.training import train_edge_supervision_lib\nfrom gfsa.training import train_util\nfrom gfsa.training import simple_runner\nfrom gfsa.training import learning_rate_schedules\n\nfrom gfsa import visualization\nimport gfsa.visualization.ndarrays\nfrom gfsa.visualization.pprint import pprint\nfrom gfsa.visualization.pytrees import summarize_tree\n```\n\n## Generating random Python functions\n\nIn this notebook, we will be focusing on graph representations of random Python programs, similar to those used in the static analysis experiments in the paper. We can start by generating some random Python programs!\n\nThe GFSA codebase includes functions for generating random Python functions of configurable size. Python functions are represented as `gast.AST` objects, which can be converted back to source code using `astunparse.unparse`:\n\n\n```\nthe_ast = tasks.make_ast(25, np.random.RandomState(6))\nprint(astunparse.unparse(gast.gast_to_ast(the_ast)))\n```\n\n    \n    \n    def random_function(a, b):\n        a = b\n        if (True and (a > foo_2(b, b))):\n            b = b\n        else:\n            v2 = a\n    \n\n\n\n```\npprint(the_ast)\n```\n\n    Module(\n        body=[FunctionDef(\n                  name='random_function',\n                  args=arguments(\n                           args=[Name(id='a', ctx=Param(), annotation=None, type_comment=None),\n                                 Name(id='b', ctx=Param(), annotation=None, type_comment=None)],\n                           posonlyargs=[],\n                           vararg=None,\n                           kwonlyargs=[],\n                           kw_defaults=[],\n                           kwarg=None,\n                           defaults=[]),\n                  body=[Assign(\n                            targets=[Name(id='a', ctx=Store(), annotation=None, type_comment=None)],\n                            value=Name(id='b', ctx=Load(), annotation=None, type_comment=None)),\n                        If(\n                            test=BoolOp(\n                                     op=And(),\n                                     values=[Constant(value=True, kind=None),\n                                             Compare(\n                                                 left=Name(id='a', ctx=Load(), annotation=None, type_comment=None),\n                                                 ops=[Gt()],\n                                                 comparators=[Call(\n                                                                  func=Name(\n                                                                           id='foo_2',\n                                                                           ctx=Load(),\n                                                                           annotation=None,\n                                                                           type_comment=None),\n                                                                  args=[Name(\n                                                                            id='b',\n                                                                            ctx=Load(),\n                                                                            annotation=None,\n                                                                            type_comment=None),\n                                                                        Name(\n                                                                            id='b',\n                                                                            ctx=Load(),\n                                                                            annotation=None,\n                                                                            type_comment=None)],\n                                                                  keywords=[])])]),\n                            body=[Assign(\n                                      targets=[Name(id='b', ctx=Store(), annotation=None, type_comment=None)],\n                                      value=Name(id='b', ctx=Load(), annotation=None, type_comment=None))],\n                            orelse=[Assign(\n                                        targets=[Name(id='v2', ctx=Store(), annotation=None, type_comment=None)],\n                                        value=Name(id='a', ctx=Load(), annotation=None, type_comment=None))])],\n                  decorator_list=[],\n                  returns=None,\n                  type_comment=None)],\n        type_ignores=[])\n\n\nThe first argument to `make_ast` is the number of AST nodes to generate, and the second is the (optional) random seed to use. For instance, here's a larger function:\n\n\n```\nthe_ast_larger = tasks.make_ast(150, np.random.RandomState(1234))\nprint(astunparse.unparse(gast.gast_to_ast(the_ast_larger)))\n```\n\n    \n    \n    def random_function(a, b):\n        if True:\n            a = a\n            if (b < foo_1(bar_4(b, a, foo_4(b, b, b, a), a))):\n                b = bar_4(foo_2(10, a), (b - b), b, bar_2(b, a))\n                v2 = 14\n            b = bar_4(b, ((b / 50) * (a / b)), a, ((a * 46) / bar_1(b)))\n            a = b\n        v2 = bar_4((b / foo_1(b)), a, (a + a), a)\n        b = foo_2(bar_2(bar_2(94, v2), a), foo_2(bar_1(v2), foo_2(v2, a)))\n        for v3 in range(int(b)):\n            v4 = (b / a)\n            while True:\n                v2 = foo_2(v2, b)\n        a = b\n        b = (b * 93)\n        v3 = v2\n        print(bar_1(10))\n    \n\n\n## Interpreting Python functions as MDPs\n\n\n\nIn order to run a GFSA layer on our functions, we need to convert them into graphs, and then impose an MDP structure on those graphs.\n\nThis process is performed over two steps:\n\n- First, convert the Python AST into a generic representation of abstract syntax trees.\n- Next, use an \"AST specification\" to transform the generic AST into an MDP. This describes what fields each AST node has, and how many of each there are. This information is used to determine what the states, actions, and transitions in the MDP should be. For instance, since a return node may or may not have a value, the MDP has an action for going to the value of a return node, and an observation that indicates that the value was missing. Similarly, since a function call may have many arguments, the MDP has states that track which argument the agent is visiting, actions that move to previous or next arguments, and an observation for reaching the end of the list.\n\n<br><br>\n\n--- \n\n\ud83d\udcac&nbsp; *Note:* If you want to apply the GFSA layer to a different type of AST, you need to:\n\n- write a function to convert from that AST to the generic AST representation shown below\n- define an AST specification for it (either by hand, or by using `ast_spec_inference.py`)\n\nIf you want to apply the GFSA layer to a graph that isn't an AST, you need to describe the MDP in more detail. See the notebook [\"Using the GFSA layer with new tasks\"][new-tasks-colab], which describes how to do this!\n\n[new-tasks-colab]: https://colab.research.google.com/github/google-research/google-research/blob/master/gfsa/notebooks/guide_for_new_tasks.ipynb\n\n---\n\nAfter the first step, we have the same tree structure as before, but instead of various instances of `gast.AST` classes, we now have `GenericASTNode` objects tagged with numeric IDs and string types (which makes it easier to manipulate in a uniform way):\n\n\n```\ngeneric_ast = py_ast_graphs.py_ast_to_generic(the_ast)\npprint(generic_ast)\n```\n\n    GenericASTNode(\n        node_id=140157879314192,\n        node_type='Module',\n        fields={'body': [GenericASTNode(\n                             node_id=140157879313632,\n                             node_type='FunctionDef',\n                             fields={'args': [GenericASTNode(\n                                                  node_id=140157879316432,\n                                                  node_type='arguments',\n                                                  fields={'args': [GenericASTNode(\n                                                                       node_id=140157879315816,\n                                                                       node_type='Name',\n                                                                       fields={'ctx': [GenericASTNode(\n                                                                                           node_id=140157879316152,\n                                                                                           node_type='Param',\n                                                                                           fields={})]}),\n                                                                   GenericASTNode(\n                                                                       node_id=140157879314360,\n                                                                       node_type='Name',\n                                                                       fields={'ctx': [GenericASTNode(\n                                                                                           node_id=140157879315928,\n                                                                                           node_type='Param',\n                                                                                           fields={})]})]})],\n                                     'body': [GenericASTNode(\n                                                  node_id=140157879314472,\n                                                  node_type='Assign',\n                                                  fields={'targets': [GenericASTNode(\n                                                                          node_id=140157879315648,\n                                                                          node_type='Name',\n                                                                          fields={'ctx': [GenericASTNode(\n                                                                                              node_id=140157879314640,\n                                                                                              node_type='Store',\n                                                                                              fields={})]})],\n                                                          'value': [GenericASTNode(\n                                                                        node_id=140157879315592,\n                                                                        node_type='Name',\n                                                                        fields={'ctx': [GenericASTNode(\n                                                                                            node_id=140157879315704,\n                                                                                            node_type='Load',\n                                                                                            fields={})]})]}),\n                                              GenericASTNode(\n                                                  node_id=140157879316040,\n                                                  node_type='If',\n                                                  fields={'test': [GenericASTNode(\n                                                                       node_id=140157879315480,\n                                                                       node_type='BoolOp',\n                                                                       fields={'op': [GenericASTNode(\n                                                                                          node_id=140157879315424,\n                                                                                          node_type='And',\n                                                                                          fields={})],\n                                                                               'values': [GenericASTNode(\n                                                                                              node_id=140157879315312,\n                                                                                              node_type='Constant',\n                                                                                              fields={}),\n                                                                                          GenericASTNode(\n                                                                                              node_id=140157879315256,\n                                                                                              node_type='Compare',\n                                                                                              fields={'left': [GenericASTNode(\n                                                                                                                   node_id=140157879314920,\n                                                                                                                   node_type='Name',\n                                                                                                                   fields={'ctx': [GenericASTNode(\n                                                                                                                                       node_id=140157879315032,\n                                                                                                                                       node_type='Load',\n                                                                                                                                       fields={})]})],\n                                                                                                      'ops': [GenericASTNode(\n                                                                                                                  node_id=140157879314808,\n                                                                                                                  node_type='Gt',\n                                                                                                                  fields={})],\n                                                                                                      'comparators': [GenericASTNode(\n                                                                                                                          node_id=140157879314752,\n                                                                                                                          node_type='Call',\n                                                                                                                          fields={'func': [GenericASTNode(\n                                                                                                                                               node_id=140157879314528,\n                                                                                                                                               node_type='Name',\n                                                                                                                                               fields={'ctx': [GenericASTNode(\n                                                                                                                                                                   node_id=140157879314696,\n                                                                                                                                                                   node_type='Load',\n                                                                                                                                                                   fields={})]})],\n                                                                                                                                  'args': [GenericASTNode(\n                                                                                                                                               node_id=140157879316096,\n                                                                                                                                               node_type='Name',\n                                                                                                                                               fields={'ctx': [GenericASTNode(\n                                                                                                                                                                   node_id=140157879314976,\n                                                                                                                                                                   node_type='Load',\n                                                                                                                                                                   fields={})]}),\n                                                                                                                                           GenericASTNode(\n                                                                                                                                               node_id=140157879357960,\n                                                                                                                                               node_type='Name',\n                                                                                                                                               fields={'ctx': [GenericASTNode(\n                                                                                                                                                                   node_id=140157879357904,\n                                                                                                                                                                   node_type='Load',\n                                                                                                                                                                   fields={})]})]})]})]})],\n                                                          'body': [GenericASTNode(\n                                                                       node_id=140157879315144,\n                                                                       node_type='Assign',\n                                                                       fields={'targets': [GenericASTNode(\n                                                                                               node_id=140157879357792,\n                                                                                               node_type='Name',\n                                                                                               fields={'ctx': [GenericASTNode(\n                                                                                                                   node_id=140157879357848,\n                                                                                                                   node_type='Store',\n                                                                                                                   fields={})]})],\n                                                                               'value': [GenericASTNode(\n                                                                                             node_id=140157879357736,\n                                                                                             node_type='Name',\n                                                                                             fields={'ctx': [GenericASTNode(\n                                                                                                                 node_id=140157879314864,\n                                                                                                                 node_type='Load',\n                                                                                                                 fields={})]})]})],\n                                                          'orelse': [GenericASTNode(\n                                                                         node_id=140157879315200,\n                                                                         node_type='Assign',\n                                                                         fields={'targets': [GenericASTNode(\n                                                                                                 node_id=140157879357512,\n                                                                                                 node_type='Name',\n                                                                                                 fields={'ctx': [GenericASTNode(\n                                                                                                                     node_id=140157879357568,\n                                                                                                                     node_type='Store',\n                                                                                                                     fields={})]})],\n                                                                                 'value': [GenericASTNode(\n                                                                                               node_id=140157879358128,\n                                                                                               node_type='Name',\n                                                                                               fields={'ctx': [GenericASTNode(\n                                                                                                                   node_id=140157879357624,\n                                                                                                                   node_type='Load',\n                                                                                                                   fields={})]})]})]})]})]})\n\n\nThe second step produces a \"flat\" representation of the tree as a graph-based MDP. Each item in the returned dictionary has an autogenerated key (based on the path through the AST from the root node to each AST node), and a `GraphNode` value that specifies the type of the node and the set of possible MDP transitions.\n\n<br>\n\n---\n\n*Note on terminology:* In the GFSA codebase, we represent MDPs as a special type of directed graph, and use some terms interchangeably. In particular:\n\n- Every node in the graph corresponds to a possible location of the agent in the environment.\n- An *out-edge* connects each graph node to the other graph nodes that the agent could move TO when at this location. This determines the action space for the agent; the agent chooses an out-edge type, and then moves to (one of) the destination nodes for that out-edge type.\n- An *in-edge* connects each graph node to the other graph nodes that the agent could move FROM when arriving at this location. This determines the observation space for the agent; when arriving at a node, it will observe the in-edge type that was used to enter the node.\n- Each edge in the graph is associated with both an out-edge type and an in-edge type, which specifies how the agent chooses to cross this edge and the observation it receives when it does so. These will often be different. As an example, for a graph representing an AST where B is the left child of A,\nthe edge from A to B might have outgoing type \"left child\" and incoming type\n\"parent\"; then an agent can choose to move to the left child, and upon doing so observes that it has arrived at that node from its parent.\n- An *input-tagged node* is a pair of (node id, in-edge type). This specifies both the location of an agent and the observation that agent receives at that location. When solving for the absorbing distribution, the set of input-tagged nodes determines the size of the transition matrix.\n\nSee `graph_types.py` for more information about the notation used.\n\n---\n\n\n```\nmdp_graph, id_conversion_map = generic_ast_graphs.ast_to_graph(generic_ast, ast_spec=py_ast_graphs.PY_AST_SPECS)\npprint(mdp_graph)\n```\n\n    {'root__Module': GraphNode(\n                         node_type='Module',\n                         out_edges={'body_out_all': [InputTaggedNode(\n                                                         node_id='root_body_0__Module_body-seq-helper',\n                                                         in_edge='parent_in')],\n                                    'body_out_first': [InputTaggedNode(\n                                                           node_id='root_body_0__Module_body-seq-helper',\n                                                           in_edge='parent_in')],\n                                    'body_out_last': [InputTaggedNode(\n                                                          node_id='root_body_0__Module_body-seq-helper',\n                                                          in_edge='parent_in')]}),\n     'root_body_0__Module_body-seq-helper':\n       GraphNode(\n           node_type='Module_body-seq-helper',\n           out_edges={'parent_out': [InputTaggedNode(node_id='root__Module', in_edge='body_in')],\n                      'item_out': [InputTaggedNode(node_id='root_body_0_item__FunctionDef', in_edge='parent_in')],\n                      'prev_out': [InputTaggedNode(node_id='root_body_0__Module_body-seq-helper', in_edge='prev_missing')],\n                      'next_out': [InputTaggedNode(node_id='root_body_0__Module_body-seq-helper', in_edge='next_missing')]}),\n     'root_body_0_item__FunctionDef':\n       GraphNode(\n           node_type='FunctionDef',\n           out_edges={'parent_out': [InputTaggedNode(node_id='root_body_0__Module_body-seq-helper', in_edge='item_in')],\n                      'args_out': [InputTaggedNode(node_id='root_body_0_item_args__arguments', in_edge='parent_in')],\n                      'returns_out': [InputTaggedNode(node_id='root_body_0_item__FunctionDef', in_edge='returns_missing')],\n                      'body_out_all': [InputTaggedNode(\n                                           node_id='root_body_0_item_body_0__FunctionDef_body-seq-helper',\n                                           in_edge='parent_in'),\n                                       InputTaggedNode(\n                                           node_id='root_body_0_item_body_1__FunctionDef_body-seq-helper',\n                                           in_edge='parent_in')],\n                      'body_out_first': [InputTaggedNode(\n                                             node_id='root_body_0_item_body_0__FunctionDef_body-seq-helper',\n                                             in_edge='parent_in')],\n                      'body_out_last': [InputTaggedNode(\n                                            node_id='root_body_0_item_body_1__FunctionDef_body-seq-helper',\n                                            in_edge='parent_in')]}),\n     'root_body_0_item_args__arguments':\n       GraphNode(\n           node_type='arguments',\n           out_edges={'parent_out': [InputTaggedNode(node_id='root_body_0_item__FunctionDef', in_edge='args_in')],\n                      'args_out_all': [InputTaggedNode(\n                                           node_id='root_body_0_item_args_args_0__arguments_args-seq-helper',\n                                           in_edge='parent_in'),\n                                       InputTaggedNode(\n                                           node_id='root_body_0_item_args_args_1__arguments_args-seq-helper',\n                                           in_edge='parent_in')],\n                      'args_out_first': [InputTaggedNode(\n                                             node_id='root_body_0_item_args_args_0__arguments_args-seq-helper',\n                                             in_edge='parent_in')],\n                      'args_out_last': [InputTaggedNode(\n                                            node_id='root_body_0_item_args_args_1__arguments_args-seq-helper',\n                                            in_edge='parent_in')]}),\n     'root_body_0_item_args_args_0__arguments_args-seq-helper':\n       GraphNode(\n           node_type='arguments_args-seq-helper',\n           out_edges={'parent_out': [InputTaggedNode(node_id='root_body_0_item_args__arguments', in_edge='args_in')],\n                      'item_out': [InputTaggedNode(node_id='root_body_0_item_args_args_0_item__Name', in_edge='parent_in')],\n                      'next_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_args_args_1__arguments_args-seq-helper',\n                                       in_edge='prev_in')],\n                      'prev_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_args_args_0__arguments_args-seq-helper',\n                                       in_edge='prev_missing')]}),\n     'root_body_0_item_args_args_0_item__Name':\n       GraphNode(\n           node_type='Name',\n           out_edges={'parent_out': [InputTaggedNode(\n                                         node_id='root_body_0_item_args_args_0__arguments_args-seq-helper',\n                                         in_edge='item_in')]}),\n     'root_body_0_item_args_args_1__arguments_args-seq-helper':\n       GraphNode(\n           node_type='arguments_args-seq-helper',\n           out_edges={'parent_out': [InputTaggedNode(node_id='root_body_0_item_args__arguments', in_edge='args_in')],\n                      'item_out': [InputTaggedNode(node_id='root_body_0_item_args_args_1_item__Name', in_edge='parent_in')],\n                      'prev_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_args_args_0__arguments_args-seq-helper',\n                                       in_edge='next_in')],\n                      'next_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_args_args_1__arguments_args-seq-helper',\n                                       in_edge='next_missing')]}),\n     'root_body_0_item_args_args_1_item__Name':\n       GraphNode(\n           node_type='Name',\n           out_edges={'parent_out': [InputTaggedNode(\n                                         node_id='root_body_0_item_args_args_1__arguments_args-seq-helper',\n                                         in_edge='item_in')]}),\n     'root_body_0_item_body_0__FunctionDef_body-seq-helper':\n       GraphNode(\n           node_type='FunctionDef_body-seq-helper',\n           out_edges={'parent_out': [InputTaggedNode(node_id='root_body_0_item__FunctionDef', in_edge='body_in')],\n                      'item_out': [InputTaggedNode(node_id='root_body_0_item_body_0_item__Assign', in_edge='parent_in')],\n                      'next_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1__FunctionDef_body-seq-helper',\n                                       in_edge='prev_in')],\n                      'prev_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_0__FunctionDef_body-seq-helper',\n                                       in_edge='prev_missing')]}),\n     'root_body_0_item_body_0_item__Assign':\n       GraphNode(\n           node_type='Assign',\n           out_edges={'parent_out': [InputTaggedNode(\n                                         node_id='root_body_0_item_body_0__FunctionDef_body-seq-helper',\n                                         in_edge='item_in')],\n                      'targets_out': [InputTaggedNode(node_id='root_body_0_item_body_0_item_targets__Name', in_edge='parent_in')],\n                      'value_out': [InputTaggedNode(node_id='root_body_0_item_body_0_item_value__Name', in_edge='parent_in')]}),\n     'root_body_0_item_body_0_item_targets__Name':\n       GraphNode(\n           node_type='Name',\n           out_edges={'parent_out': [InputTaggedNode(node_id='root_body_0_item_body_0_item__Assign', in_edge='targets_in')]}),\n     'root_body_0_item_body_0_item_value__Name':\n       GraphNode(\n           node_type='Name',\n           out_edges={'parent_out': [InputTaggedNode(node_id='root_body_0_item_body_0_item__Assign', in_edge='value_in')]}),\n     'root_body_0_item_body_1__FunctionDef_body-seq-helper':\n       GraphNode(\n           node_type='FunctionDef_body-seq-helper',\n           out_edges={'parent_out': [InputTaggedNode(node_id='root_body_0_item__FunctionDef', in_edge='body_in')],\n                      'item_out': [InputTaggedNode(node_id='root_body_0_item_body_1_item__If', in_edge='parent_in')],\n                      'prev_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_0__FunctionDef_body-seq-helper',\n                                       in_edge='next_in')],\n                      'next_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1__FunctionDef_body-seq-helper',\n                                       in_edge='next_missing')]}),\n     'root_body_0_item_body_1_item__If':\n       GraphNode(\n           node_type='If',\n           out_edges={'parent_out': [InputTaggedNode(\n                                         node_id='root_body_0_item_body_1__FunctionDef_body-seq-helper',\n                                         in_edge='item_in')],\n                      'test_out': [InputTaggedNode(node_id='root_body_0_item_body_1_item_test__BoolOp', in_edge='parent_in')],\n                      'body_out_all': [InputTaggedNode(\n                                           node_id='root_body_0_item_body_1_item_body_0__If_body-seq-helper',\n                                           in_edge='parent_in')],\n                      'body_out_first': [InputTaggedNode(\n                                             node_id='root_body_0_item_body_1_item_body_0__If_body-seq-helper',\n                                             in_edge='parent_in')],\n                      'body_out_last': [InputTaggedNode(\n                                            node_id='root_body_0_item_body_1_item_body_0__If_body-seq-helper',\n                                            in_edge='parent_in')],\n                      'orelse_out_all': [InputTaggedNode(\n                                             node_id='root_body_0_item_body_1_item_orelse_0__If_orelse-seq-helper',\n                                             in_edge='parent_in')],\n                      'orelse_out_first': [InputTaggedNode(\n                                               node_id='root_body_0_item_body_1_item_orelse_0__If_orelse-seq-helper',\n                                               in_edge='parent_in')],\n                      'orelse_out_last': [InputTaggedNode(\n                                              node_id='root_body_0_item_body_1_item_orelse_0__If_orelse-seq-helper',\n                                              in_edge='parent_in')]}),\n     'root_body_0_item_body_1_item_test__BoolOp':\n       GraphNode(\n           node_type='BoolOp',\n           out_edges={'parent_out': [InputTaggedNode(node_id='root_body_0_item_body_1_item__If', in_edge='test_in')],\n                      'op_out': [InputTaggedNode(node_id='root_body_0_item_body_1_item_test_op__And', in_edge='parent_in')],\n                      'values_out_all': [InputTaggedNode(\n                                             node_id='root_body_0_item_body_1_item_test_values_0__BoolOp_values-seq-helper',\n                                             in_edge='parent_in'),\n                                         InputTaggedNode(\n                                             node_id='root_body_0_item_body_1_item_test_values_1__BoolOp_values-seq-helper',\n                                             in_edge='parent_in')],\n                      'values_out_first': [InputTaggedNode(\n                                               node_id='root_body_0_item_body_1_item_test_values_0__BoolOp_values-seq-helper',\n                                               in_edge='parent_in')],\n                      'values_out_last': [InputTaggedNode(\n                                              node_id='root_body_0_item_body_1_item_test_values_1__BoolOp_values-seq-helper',\n                                              in_edge='parent_in')]}),\n     'root_body_0_item_body_1_item_test_op__And':\n       GraphNode(\n           node_type='And',\n           out_edges={'parent_out': [InputTaggedNode(node_id='root_body_0_item_body_1_item_test__BoolOp', in_edge='op_in')]}),\n     'root_body_0_item_body_1_item_test_values_0__BoolOp_values-seq-helper':\n       GraphNode(\n           node_type='BoolOp_values-seq-helper',\n           out_edges={'parent_out': [InputTaggedNode(node_id='root_body_0_item_body_1_item_test__BoolOp', in_edge='values_in')],\n                      'item_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1_item_test_values_0_item__Constant',\n                                       in_edge='parent_in')],\n                      'next_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1_item_test_values_1__BoolOp_values-seq-helper',\n                                       in_edge='prev_in')],\n                      'prev_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1_item_test_values_0__BoolOp_values-seq-helper',\n                                       in_edge='prev_missing')]}),\n     'root_body_0_item_body_1_item_test_values_0_item__Constant':\n       GraphNode(\n           node_type='Constant',\n           out_edges={'parent_out': [InputTaggedNode(\n                                         node_id='root_body_0_item_body_1_item_test_values_0__BoolOp_values-seq-helper',\n                                         in_edge='item_in')]}),\n     'root_body_0_item_body_1_item_test_values_1__BoolOp_values-seq-helper':\n       GraphNode(\n           node_type='BoolOp_values-seq-helper',\n           out_edges={'parent_out': [InputTaggedNode(node_id='root_body_0_item_body_1_item_test__BoolOp', in_edge='values_in')],\n                      'item_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1_item_test_values_1_item__Compare',\n                                       in_edge='parent_in')],\n                      'prev_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1_item_test_values_0__BoolOp_values-seq-helper',\n                                       in_edge='next_in')],\n                      'next_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1_item_test_values_1__BoolOp_values-seq-helper',\n                                       in_edge='next_missing')]}),\n     'root_body_0_item_body_1_item_test_values_1_item__Compare':\n       GraphNode(\n           node_type='Compare',\n           out_edges={'parent_out': [InputTaggedNode(\n                                         node_id='root_body_0_item_body_1_item_test_values_1__BoolOp_values-seq-helper',\n                                         in_edge='item_in')],\n                      'left_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1_item_test_values_1_item_left__Name',\n                                       in_edge='parent_in')],\n                      'ops_out': [InputTaggedNode(\n                                      node_id='root_body_0_item_body_1_item_test_values_1_item_ops__Gt',\n                                      in_edge='parent_in')],\n                      'comparators_out': [InputTaggedNode(\n                                              node_id='root_body_0_item_body_1_item_test_values_1_item_comparators__Call',\n                                              in_edge='parent_in')]}),\n     'root_body_0_item_body_1_item_test_values_1_item_left__Name':\n       GraphNode(\n           node_type='Name',\n           out_edges={'parent_out': [InputTaggedNode(\n                                         node_id='root_body_0_item_body_1_item_test_values_1_item__Compare',\n                                         in_edge='left_in')]}),\n     'root_body_0_item_body_1_item_test_values_1_item_ops__Gt':\n       GraphNode(\n           node_type='Gt',\n           out_edges={'parent_out': [InputTaggedNode(\n                                         node_id='root_body_0_item_body_1_item_test_values_1_item__Compare',\n                                         in_edge='ops_in')]}),\n     'root_body_0_item_body_1_item_test_values_1_item_comparators__Call':\n       GraphNode(\n           node_type='Call',\n           out_edges={'parent_out': [InputTaggedNode(\n                                         node_id='root_body_0_item_body_1_item_test_values_1_item__Compare',\n                                         in_edge='comparators_in')],\n                      'func_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1_item_test_values_1_item_comparators_func__Name',\n                                       in_edge='parent_in')],\n                      'args_out_all': [InputTaggedNode(\n                                           node_id='root_body_0_item_body_1_item_test_values_1_item_comparators_args_0__Call_args-seq-helper',\n                                           in_edge='parent_in'),\n                                       InputTaggedNode(\n                                           node_id='root_body_0_item_body_1_item_test_values_1_item_comparators_args_1__Call_args-seq-helper',\n                                           in_edge='parent_in')],\n                      'args_out_first': [InputTaggedNode(\n                                             node_id='root_body_0_item_body_1_item_test_values_1_item_comparators_args_0__Call_args-seq-helper',\n                                             in_edge='parent_in')],\n                      'args_out_last': [InputTaggedNode(\n                                            node_id='root_body_0_item_body_1_item_test_values_1_item_comparators_args_1__Call_args-seq-helper',\n                                            in_edge='parent_in')]}),\n     'root_body_0_item_body_1_item_test_values_1_item_comparators_func__Name':\n       GraphNode(\n           node_type='Name',\n           out_edges={'parent_out': [InputTaggedNode(\n                                         node_id='root_body_0_item_body_1_item_test_values_1_item_comparators__Call',\n                                         in_edge='func_in')]}),\n     'root_body_0_item_body_1_item_test_values_1_item_comparators_args_0__Call_args-seq-helper':\n       GraphNode(\n           node_type='Call_args-seq-helper',\n           out_edges={'parent_out': [InputTaggedNode(\n                                         node_id='root_body_0_item_body_1_item_test_values_1_item_comparators__Call',\n                                         in_edge='args_in')],\n                      'item_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1_item_test_values_1_item_comparators_args_0_item__Name',\n                                       in_edge='parent_in')],\n                      'next_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1_item_test_values_1_item_comparators_args_1__Call_args-seq-helper',\n                                       in_edge='prev_in')],\n                      'prev_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1_item_test_values_1_item_comparators_args_0__Call_args-seq-helper',\n                                       in_edge='prev_missing')]}),\n     'root_body_0_item_body_1_item_test_values_1_item_comparators_args_0_item__Name':\n       GraphNode(\n           node_type='Name',\n           out_edges={'parent_out': [InputTaggedNode(\n                                         node_id='root_body_0_item_body_1_item_test_values_1_item_comparators_args_0__Call_args-seq-helper',\n                                         in_edge='item_in')]}),\n     'root_body_0_item_body_1_item_test_values_1_item_comparators_args_1__Call_args-seq-helper':\n       GraphNode(\n           node_type='Call_args-seq-helper',\n           out_edges={'parent_out': [InputTaggedNode(\n                                         node_id='root_body_0_item_body_1_item_test_values_1_item_comparators__Call',\n                                         in_edge='args_in')],\n                      'item_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1_item_test_values_1_item_comparators_args_1_item__Name',\n                                       in_edge='parent_in')],\n                      'prev_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1_item_test_values_1_item_comparators_args_0__Call_args-seq-helper',\n                                       in_edge='next_in')],\n                      'next_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1_item_test_values_1_item_comparators_args_1__Call_args-seq-helper',\n                                       in_edge='next_missing')]}),\n     'root_body_0_item_body_1_item_test_values_1_item_comparators_args_1_item__Name':\n       GraphNode(\n           node_type='Name',\n           out_edges={'parent_out': [InputTaggedNode(\n                                         node_id='root_body_0_item_body_1_item_test_values_1_item_comparators_args_1__Call_args-seq-helper',\n                                         in_edge='item_in')]}),\n     'root_body_0_item_body_1_item_body_0__If_body-seq-helper':\n       GraphNode(\n           node_type='If_body-seq-helper',\n           out_edges={'parent_out': [InputTaggedNode(node_id='root_body_0_item_body_1_item__If', in_edge='body_in')],\n                      'item_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1_item_body_0_item__Assign',\n                                       in_edge='parent_in')],\n                      'prev_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1_item_body_0__If_body-seq-helper',\n                                       in_edge='prev_missing')],\n                      'next_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1_item_body_0__If_body-seq-helper',\n                                       in_edge='next_missing')]}),\n     'root_body_0_item_body_1_item_body_0_item__Assign':\n       GraphNode(\n           node_type='Assign',\n           out_edges={'parent_out': [InputTaggedNode(\n                                         node_id='root_body_0_item_body_1_item_body_0__If_body-seq-helper',\n                                         in_edge='item_in')],\n                      'targets_out': [InputTaggedNode(\n                                          node_id='root_body_0_item_body_1_item_body_0_item_targets__Name',\n                                          in_edge='parent_in')],\n                      'value_out': [InputTaggedNode(\n                                        node_id='root_body_0_item_body_1_item_body_0_item_value__Name',\n                                        in_edge='parent_in')]}),\n     'root_body_0_item_body_1_item_body_0_item_targets__Name':\n       GraphNode(\n           node_type='Name',\n           out_edges={'parent_out': [InputTaggedNode(\n                                         node_id='root_body_0_item_body_1_item_body_0_item__Assign',\n                                         in_edge='targets_in')]}),\n     'root_body_0_item_body_1_item_body_0_item_value__Name':\n       GraphNode(\n           node_type='Name',\n           out_edges={'parent_out': [InputTaggedNode(\n                                         node_id='root_body_0_item_body_1_item_body_0_item__Assign',\n                                         in_edge='value_in')]}),\n     'root_body_0_item_body_1_item_orelse_0__If_orelse-seq-helper':\n       GraphNode(\n           node_type='If_orelse-seq-helper',\n           out_edges={'parent_out': [InputTaggedNode(node_id='root_body_0_item_body_1_item__If', in_edge='orelse_in')],\n                      'item_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1_item_orelse_0_item__Assign',\n                                       in_edge='parent_in')],\n                      'prev_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1_item_orelse_0__If_orelse-seq-helper',\n                                       in_edge='prev_missing')],\n                      'next_out': [InputTaggedNode(\n                                       node_id='root_body_0_item_body_1_item_orelse_0__If_orelse-seq-helper',\n                                       in_edge='next_missing')]}),\n     'root_body_0_item_body_1_item_orelse_0_item__Assign':\n       GraphNode(\n           node_type='Assign',\n           out_edges={'parent_out': [InputTaggedNode(\n                                         node_id='root_body_0_item_body_1_item_orelse_0__If_orelse-seq-helper',\n                                         in_edge='item_in')],\n                      'targets_out': [InputTaggedNode(\n                                          node_id='root_body_0_item_body_1_item_orelse_0_item_targets__Name',\n                                          in_edge='parent_in')],\n                      'value_out': [InputTaggedNode(\n                                        node_id='root_body_0_item_body_1_item_orelse_0_item_value__Name',\n                                        in_edge='parent_in')]}),\n     'root_body_0_item_body_1_item_orelse_0_item_targets__Name':\n       GraphNode(\n           node_type='Name',\n           out_edges={'parent_out': [InputTaggedNode(\n                                         node_id='root_body_0_item_body_1_item_orelse_0_item__Assign',\n                                         in_edge='targets_in')]}),\n     'root_body_0_item_body_1_item_orelse_0_item_value__Name':\n       GraphNode(\n           node_type='Name',\n           out_edges={'parent_out': [InputTaggedNode(\n                                         node_id='root_body_0_item_body_1_item_orelse_0_item__Assign',\n                                         in_edge='value_in')]})}\n\n\nThis graph is associated with a `GraphSchema` object that declares the set of all actions and observations for graphs in this MDP family. (As discussed above, the `in_edges` field specifies the set of observations, and the `out_edges` field specifies the set of possible actions.)\n\n\n```\npy_ast_graphs.SCHEMA\n```\n\n\n\n\n    {'Add': NodeSchema(in_edges=['parent_in'], out_edges=['parent_out']),\n     'And': NodeSchema(in_edges=['parent_in'], out_edges=['parent_out']),\n     'Assign': NodeSchema(in_edges=['parent_in', 'targets_in', 'value_in'], out_edges=['parent_out', 'targets_out', 'value_out']),\n     'BinOp': NodeSchema(in_edges=['parent_in', 'left_in', 'op_in', 'right_in'], out_edges=['parent_out', 'left_out', 'op_out', 'right_out']),\n     'BoolOp': NodeSchema(in_edges=['parent_in', 'op_in', 'values_in'], out_edges=['parent_out', 'op_out', 'values_out_all', 'values_out_first', 'values_out_last']),\n     'BoolOp_values-seq-helper': NodeSchema(in_edges=['parent_in', 'item_in', 'next_in', 'next_missing', 'prev_in', 'prev_missing'], out_edges=['parent_out', 'item_out', 'next_out', 'prev_out']),\n     'Break': NodeSchema(in_edges=['parent_in'], out_edges=['parent_out']),\n     'Call': NodeSchema(in_edges=['parent_in', 'func_in', 'args_in', 'args_missing'], out_edges=['parent_out', 'func_out', 'args_out_all', 'args_out_first', 'args_out_last']),\n     'Call_args-seq-helper': NodeSchema(in_edges=['parent_in', 'item_in', 'next_in', 'next_missing', 'prev_in', 'prev_missing'], out_edges=['parent_out', 'item_out', 'next_out', 'prev_out']),\n     'Compare': NodeSchema(in_edges=['parent_in', 'left_in', 'ops_in', 'comparators_in'], out_edges=['parent_out', 'left_out', 'ops_out', 'comparators_out']),\n     'Constant': NodeSchema(in_edges=['parent_in'], out_edges=['parent_out']),\n     'Continue': NodeSchema(in_edges=['parent_in'], out_edges=['parent_out']),\n     'Div': NodeSchema(in_edges=['parent_in'], out_edges=['parent_out']),\n     'Eq': NodeSchema(in_edges=['parent_in'], out_edges=['parent_out']),\n     'Expr': NodeSchema(in_edges=['parent_in', 'value_in'], out_edges=['parent_out', 'value_out']),\n     'For': NodeSchema(in_edges=['parent_in', 'target_in', 'iter_in', 'body_in'], out_edges=['parent_out', 'target_out', 'iter_out', 'body_out_all', 'body_out_first', 'body_out_last']),\n     'For_body-seq-helper': NodeSchema(in_edges=['parent_in', 'item_in', 'next_in', 'next_missing', 'prev_in', 'prev_missing'], out_edges=['parent_out', 'item_out', 'next_out', 'prev_out']),\n     'FunctionDef': NodeSchema(in_edges=['parent_in', 'args_in', 'returns_in', 'returns_missing', 'body_in'], out_edges=['parent_out', 'args_out', 'returns_out', 'body_out_all', 'body_out_first', 'body_out_last']),\n     'FunctionDef_body-seq-helper': NodeSchema(in_edges=['parent_in', 'item_in', 'next_in', 'next_missing', 'prev_in', 'prev_missing'], out_edges=['parent_out', 'item_out', 'next_out', 'prev_out']),\n     'Gt': NodeSchema(in_edges=['parent_in'], out_edges=['parent_out']),\n     'GtE': NodeSchema(in_edges=['parent_in'], out_edges=['parent_out']),\n     'If': NodeSchema(in_edges=['parent_in', 'test_in', 'body_in', 'orelse_in', 'orelse_missing'], out_edges=['parent_out', 'test_out', 'body_out_all', 'body_out_first', 'body_out_last', 'orelse_out_all', 'orelse_out_first', 'orelse_out_last']),\n     'If_body-seq-helper': NodeSchema(in_edges=['parent_in', 'item_in', 'next_in', 'next_missing', 'prev_in', 'prev_missing'], out_edges=['parent_out', 'item_out', 'next_out', 'prev_out']),\n     'If_orelse-seq-helper': NodeSchema(in_edges=['parent_in', 'item_in', 'next_in', 'next_missing', 'prev_in', 'prev_missing'], out_edges=['parent_out', 'item_out', 'next_out', 'prev_out']),\n     'Lt': NodeSchema(in_edges=['parent_in'], out_edges=['parent_out']),\n     'LtE': NodeSchema(in_edges=['parent_in'], out_edges=['parent_out']),\n     'Module': NodeSchema(in_edges=['body_in'], out_edges=['body_out_all', 'body_out_first', 'body_out_last']),\n     'Module_body-seq-helper': NodeSchema(in_edges=['parent_in', 'item_in', 'next_in', 'next_missing', 'prev_in', 'prev_missing'], out_edges=['parent_out', 'item_out', 'next_out', 'prev_out']),\n     'Mult': NodeSchema(in_edges=['parent_in'], out_edges=['parent_out']),\n     'Name': NodeSchema(in_edges=['parent_in'], out_edges=['parent_out']),\n     'NotEq': NodeSchema(in_edges=['parent_in'], out_edges=['parent_out']),\n     'Or': NodeSchema(in_edges=['parent_in'], out_edges=['parent_out']),\n     'Pass': NodeSchema(in_edges=['parent_in'], out_edges=['parent_out']),\n     'Return': NodeSchema(in_edges=['parent_in', 'value_in', 'value_missing'], out_edges=['parent_out', 'value_out']),\n     'Sub': NodeSchema(in_edges=['parent_in'], out_edges=['parent_out']),\n     'While': NodeSchema(in_edges=['parent_in', 'test_in', 'body_in'], out_edges=['parent_out', 'test_out', 'body_out_all', 'body_out_first', 'body_out_last']),\n     'While_body-seq-helper': NodeSchema(in_edges=['parent_in', 'item_in', 'next_in', 'next_missing', 'prev_in', 'prev_missing'], out_edges=['parent_out', 'item_out', 'next_out', 'prev_out']),\n     'arguments': NodeSchema(in_edges=['parent_in', 'args_in', 'args_missing'], out_edges=['parent_out', 'args_out_all', 'args_out_first', 'args_out_last']),\n     'arguments_args-seq-helper': NodeSchema(in_edges=['parent_in', 'item_in', 'next_in', 'next_missing', 'prev_in', 'prev_missing'], out_edges=['parent_out', 'item_out', 'next_out', 'prev_out'])}\n\n\n\nAnd we can confirm that our MDP graph conforms to this schema:\n\n\n```\nschema_util.assert_conforms_to_schema(mdp_graph, py_ast_graphs.SCHEMA)\nprint(\"assertion passed!\")\n```\n\n    assertion passed!\n\n\nThis means that we can parameterize a GFSA layer based on `py_ast_graphs.SCHEMA`, and then pass `mdp_graph` as an input to it.\n\n## Computing ground-truth static analyses\n\nSuppose we wish to train a GFSA layer to perform static analyses of Python code. The next step is to build the ground-truth data for those analyses.\n\nThe implementation of the static analyses used in the paper is not yet open source, so for now let's consider a simpler form of static analysis: finding the target of `return`, `break`, and `continue` statements. More specifically:\n\n- For each `return` statement, we add an edge from the `Return` AST node to the `FunctionDef` AST node defining the function. If there is a return value, we also add an edge from the return value to the `FunctionDef` AST node.\n- For each `break` or `continue` statement, we add an edge from the `Break`/`Continue` AST node to the innermost `For`/`While` node that it is contained inside. This is the loop whose execution will be broken out of or continued with, respectively.\n\n(This can be seen as a simplified type of control flow analysis, where we only consider return, break, and continue statements.)\n\nFirst, let's sample a program:\n\n\n```\n# Use a distribution with more frequent return/break/continue statements\nthe_ast = tasks.make_ast(64, np.random.RandomState(3), python_numbers_control_flow.CFG_DISTRIBUTION)\nprint(astunparse.unparse(gast.gast_to_ast(the_ast)))\n```\n\n    \n    \n    def random_function(a, b):\n        print(a)\n        v2 = 44\n        for v3 in range(int(37)):\n            print(a)\n            if (a == v3):\n                print(a)\n            elif (77 > v3):\n                return\n            elif True:\n                pass\n            return\n        if (((b + 81) + 11) <= 32):\n            for v3 in range(int(a)):\n                break\n        v3 = 92\n    \n\n\nNow we convert it to an MDP graph:\n\n\n```\ngeneric_ast = py_ast_graphs.py_ast_to_generic(the_ast)\nmdp_graph, id_conversion_map = generic_ast_graphs.ast_to_graph(generic_ast, ast_spec=py_ast_graphs.PY_AST_SPECS)\n```\n\nAnd finally, we compute the target edges for this simple task. Each edge is represented as a tuple `(source_id, dest_id, type)`.\n\n- Two edges connect each of the two `return` statements (denoted `root_body_0_item_body_2_item_body_1_item_orelse_0_item_body_0_item__Return` and `root_body_0_item_body_2_item_body_2_item__Return` based on their locations in the AST) to the function definition node (`root_body_0_item__FunctionDef`).\n- One edge connects the break statement (`root_body_0_item_body_3_item_body_0_item_body_0_item__Break`) to the for loop containing it (`root_body_0_item_body_3_item_body_0_item__For`).\n- All of these edges have type \"EXTRA_JUMPS_OUT_OF\", which is just a string that we use to distinguish these edges from other types of edge.\n\n\n```\ntarget_edges = graph_edge_util.compute_jumps_out_edges(the_ast, id_conversion_map)\ntarget_edges\n```\n\n\n\n\n    [('root_body_0_item_body_2_item_body_1_item_orelse_0_item_body_0_item__Return',\n      'root_body_0_item__FunctionDef',\n      'EXTRA_JUMPS_OUT_OF'),\n     ('root_body_0_item_body_2_item_body_2_item__Return',\n      'root_body_0_item__FunctionDef',\n      'EXTRA_JUMPS_OUT_OF'),\n     ('root_body_0_item_body_3_item_body_0_item_body_0_item__Break',\n      'root_body_0_item_body_3_item_body_0_item__For',\n      'EXTRA_JUMPS_OUT_OF')]\n\n\n\nThese edges will be used as the targets for our layer.\n\n## Other edges\n\nWe can also compute other edges from our AST, which are useful when running a baseline graph neural network on the same targets, or to provide additional observations to the GFSA layer. We won't technically need these for this particular toy problem, so feel free to skip this section, but here they are for completeness:\n\n\n```\nother_edges = []\n\n# Add edges based on the transitions in the MDP (which are in turn based on\n# the parent-child relationships in the AST).\n# These edges will have types like `SCHEMA_body_out_last` (which means that it\n# is derived from the MDP schema, and connects nodes that are reachable using\n# the `body_out_last` action. In this case, this is the same as connecting each\n# control flow AST node to the last statement in the contained block.)\nother_edges.extend(graph_edge_util.compute_schema_edges(mdp_graph))\n\n# Add edges between uses of the same identifier. These edges will have type\n# \"EXTRA_SAME_IDENTIFIER\".\nother_edges.extend(\n    graph_edge_util.compute_same_identifier_edges(the_ast, id_conversion_map))\n\n# For the experiments in the paper, we would also include edges based on more\n# sophisticated static analyses, but the code for computing those is not yet\n# open-source.\n\nother_edges\n```\n\n\n\n\n    [('root__Module',\n      'root_body_0__Module_body-seq-helper',\n      'SCHEMA_body_out_all'),\n     ('root__Module',\n      'root_body_0__Module_body-seq-helper',\n      'SCHEMA_body_out_first'),\n     ('root__Module',\n      'root_body_0__Module_body-seq-helper',\n      'SCHEMA_body_out_last'),\n     ('root_body_0__Module_body-seq-helper', 'root__Module', 'SCHEMA_parent_out'),\n     ('root_body_0__Module_body-seq-helper',\n      'root_body_0_item__FunctionDef',\n      'SCHEMA_item_out'),\n     ('root_body_0_item__FunctionDef',\n      'root_body_0__Module_body-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item__FunctionDef',\n      'root_body_0_item_args__arguments',\n      'SCHEMA_args_out'),\n     ('root_body_0_item__FunctionDef',\n      'root_body_0_item_body_0__FunctionDef_body-seq-helper',\n      'SCHEMA_body_out_all'),\n     ('root_body_0_item__FunctionDef',\n      'root_body_0_item_body_1__FunctionDef_body-seq-helper',\n      'SCHEMA_body_out_all'),\n     ('root_body_0_item__FunctionDef',\n      'root_body_0_item_body_2__FunctionDef_body-seq-helper',\n      'SCHEMA_body_out_all'),\n     ('root_body_0_item__FunctionDef',\n      'root_body_0_item_body_3__FunctionDef_body-seq-helper',\n      'SCHEMA_body_out_all'),\n     ('root_body_0_item__FunctionDef',\n      'root_body_0_item_body_4__FunctionDef_body-seq-helper',\n      'SCHEMA_body_out_all'),\n     ('root_body_0_item__FunctionDef',\n      'root_body_0_item_body_0__FunctionDef_body-seq-helper',\n      'SCHEMA_body_out_first'),\n     ('root_body_0_item__FunctionDef',\n      'root_body_0_item_body_4__FunctionDef_body-seq-helper',\n      'SCHEMA_body_out_last'),\n     ('root_body_0_item_args__arguments',\n      'root_body_0_item__FunctionDef',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_args__arguments',\n      'root_body_0_item_args_args_0__arguments_args-seq-helper',\n      'SCHEMA_args_out_all'),\n     ('root_body_0_item_args__arguments',\n      'root_body_0_item_args_args_1__arguments_args-seq-helper',\n      'SCHEMA_args_out_all'),\n     ('root_body_0_item_args__arguments',\n      'root_body_0_item_args_args_0__arguments_args-seq-helper',\n      'SCHEMA_args_out_first'),\n     ('root_body_0_item_args__arguments',\n      'root_body_0_item_args_args_1__arguments_args-seq-helper',\n      'SCHEMA_args_out_last'),\n     ('root_body_0_item_args_args_0__arguments_args-seq-helper',\n      'root_body_0_item_args__arguments',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_args_args_0__arguments_args-seq-helper',\n      'root_body_0_item_args_args_0_item__Name',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_args_args_0__arguments_args-seq-helper',\n      'root_body_0_item_args_args_1__arguments_args-seq-helper',\n      'SCHEMA_next_out'),\n     ('root_body_0_item_args_args_0_item__Name',\n      'root_body_0_item_args_args_0__arguments_args-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_args_args_1__arguments_args-seq-helper',\n      'root_body_0_item_args__arguments',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_args_args_1__arguments_args-seq-helper',\n      'root_body_0_item_args_args_1_item__Name',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_args_args_1__arguments_args-seq-helper',\n      'root_body_0_item_args_args_0__arguments_args-seq-helper',\n      'SCHEMA_prev_out'),\n     ('root_body_0_item_args_args_1_item__Name',\n      'root_body_0_item_args_args_1__arguments_args-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_0__FunctionDef_body-seq-helper',\n      'root_body_0_item__FunctionDef',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_0__FunctionDef_body-seq-helper',\n      'root_body_0_item_body_0_item__Expr',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_0__FunctionDef_body-seq-helper',\n      'root_body_0_item_body_1__FunctionDef_body-seq-helper',\n      'SCHEMA_next_out'),\n     ('root_body_0_item_body_0_item__Expr',\n      'root_body_0_item_body_0__FunctionDef_body-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_0_item__Expr',\n      'root_body_0_item_body_0_item_value__Call',\n      'SCHEMA_value_out'),\n     ('root_body_0_item_body_0_item_value__Call',\n      'root_body_0_item_body_0_item__Expr',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_0_item_value__Call',\n      'root_body_0_item_body_0_item_value_func__Name',\n      'SCHEMA_func_out'),\n     ('root_body_0_item_body_0_item_value__Call',\n      'root_body_0_item_body_0_item_value_args_0__Call_args-seq-helper',\n      'SCHEMA_args_out_all'),\n     ('root_body_0_item_body_0_item_value__Call',\n      'root_body_0_item_body_0_item_value_args_0__Call_args-seq-helper',\n      'SCHEMA_args_out_first'),\n     ('root_body_0_item_body_0_item_value__Call',\n      'root_body_0_item_body_0_item_value_args_0__Call_args-seq-helper',\n      'SCHEMA_args_out_last'),\n     ('root_body_0_item_body_0_item_value_func__Name',\n      'root_body_0_item_body_0_item_value__Call',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_0_item_value_args_0__Call_args-seq-helper',\n      'root_body_0_item_body_0_item_value__Call',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_0_item_value_args_0__Call_args-seq-helper',\n      'root_body_0_item_body_0_item_value_args_0_item__Name',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_0_item_value_args_0_item__Name',\n      'root_body_0_item_body_0_item_value_args_0__Call_args-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_1__FunctionDef_body-seq-helper',\n      'root_body_0_item__FunctionDef',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_1__FunctionDef_body-seq-helper',\n      'root_body_0_item_body_1_item__Assign',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_1__FunctionDef_body-seq-helper',\n      'root_body_0_item_body_0__FunctionDef_body-seq-helper',\n      'SCHEMA_prev_out'),\n     ('root_body_0_item_body_1__FunctionDef_body-seq-helper',\n      'root_body_0_item_body_2__FunctionDef_body-seq-helper',\n      'SCHEMA_next_out'),\n     ('root_body_0_item_body_1_item__Assign',\n      'root_body_0_item_body_1__FunctionDef_body-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_1_item__Assign',\n      'root_body_0_item_body_1_item_targets__Name',\n      'SCHEMA_targets_out'),\n     ('root_body_0_item_body_1_item__Assign',\n      'root_body_0_item_body_1_item_value__Constant',\n      'SCHEMA_value_out'),\n     ('root_body_0_item_body_1_item_targets__Name',\n      'root_body_0_item_body_1_item__Assign',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_1_item_value__Constant',\n      'root_body_0_item_body_1_item__Assign',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2__FunctionDef_body-seq-helper',\n      'root_body_0_item__FunctionDef',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2__FunctionDef_body-seq-helper',\n      'root_body_0_item_body_2_item__For',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_2__FunctionDef_body-seq-helper',\n      'root_body_0_item_body_1__FunctionDef_body-seq-helper',\n      'SCHEMA_prev_out'),\n     ('root_body_0_item_body_2__FunctionDef_body-seq-helper',\n      'root_body_0_item_body_3__FunctionDef_body-seq-helper',\n      'SCHEMA_next_out'),\n     ('root_body_0_item_body_2_item__For',\n      'root_body_0_item_body_2__FunctionDef_body-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item__For',\n      'root_body_0_item_body_2_item_target__Name',\n      'SCHEMA_target_out'),\n     ('root_body_0_item_body_2_item__For',\n      'root_body_0_item_body_2_item_iter__Call',\n      'SCHEMA_iter_out'),\n     ('root_body_0_item_body_2_item__For',\n      'root_body_0_item_body_2_item_body_0__For_body-seq-helper',\n      'SCHEMA_body_out_all'),\n     ('root_body_0_item_body_2_item__For',\n      'root_body_0_item_body_2_item_body_1__For_body-seq-helper',\n      'SCHEMA_body_out_all'),\n     ('root_body_0_item_body_2_item__For',\n      'root_body_0_item_body_2_item_body_2__For_body-seq-helper',\n      'SCHEMA_body_out_all'),\n     ('root_body_0_item_body_2_item__For',\n      'root_body_0_item_body_2_item_body_0__For_body-seq-helper',\n      'SCHEMA_body_out_first'),\n     ('root_body_0_item_body_2_item__For',\n      'root_body_0_item_body_2_item_body_2__For_body-seq-helper',\n      'SCHEMA_body_out_last'),\n     ('root_body_0_item_body_2_item_target__Name',\n      'root_body_0_item_body_2_item__For',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_iter__Call',\n      'root_body_0_item_body_2_item__For',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_iter__Call',\n      'root_body_0_item_body_2_item_iter_func__Name',\n      'SCHEMA_func_out'),\n     ('root_body_0_item_body_2_item_iter__Call',\n      'root_body_0_item_body_2_item_iter_args_0__Call_args-seq-helper',\n      'SCHEMA_args_out_all'),\n     ('root_body_0_item_body_2_item_iter__Call',\n      'root_body_0_item_body_2_item_iter_args_0__Call_args-seq-helper',\n      'SCHEMA_args_out_first'),\n     ('root_body_0_item_body_2_item_iter__Call',\n      'root_body_0_item_body_2_item_iter_args_0__Call_args-seq-helper',\n      'SCHEMA_args_out_last'),\n     ('root_body_0_item_body_2_item_iter_func__Name',\n      'root_body_0_item_body_2_item_iter__Call',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_iter_args_0__Call_args-seq-helper',\n      'root_body_0_item_body_2_item_iter__Call',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_iter_args_0__Call_args-seq-helper',\n      'root_body_0_item_body_2_item_iter_args_0_item__Call',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_2_item_iter_args_0_item__Call',\n      'root_body_0_item_body_2_item_iter_args_0__Call_args-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_iter_args_0_item__Call',\n      'root_body_0_item_body_2_item_iter_args_0_item_func__Name',\n      'SCHEMA_func_out'),\n     ('root_body_0_item_body_2_item_iter_args_0_item__Call',\n      'root_body_0_item_body_2_item_iter_args_0_item_args_0__Call_args-seq-helper',\n      'SCHEMA_args_out_all'),\n     ('root_body_0_item_body_2_item_iter_args_0_item__Call',\n      'root_body_0_item_body_2_item_iter_args_0_item_args_0__Call_args-seq-helper',\n      'SCHEMA_args_out_first'),\n     ('root_body_0_item_body_2_item_iter_args_0_item__Call',\n      'root_body_0_item_body_2_item_iter_args_0_item_args_0__Call_args-seq-helper',\n      'SCHEMA_args_out_last'),\n     ('root_body_0_item_body_2_item_iter_args_0_item_func__Name',\n      'root_body_0_item_body_2_item_iter_args_0_item__Call',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_iter_args_0_item_args_0__Call_args-seq-helper',\n      'root_body_0_item_body_2_item_iter_args_0_item__Call',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_iter_args_0_item_args_0__Call_args-seq-helper',\n      'root_body_0_item_body_2_item_iter_args_0_item_args_0_item__Constant',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_2_item_iter_args_0_item_args_0_item__Constant',\n      'root_body_0_item_body_2_item_iter_args_0_item_args_0__Call_args-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_0__For_body-seq-helper',\n      'root_body_0_item_body_2_item__For',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_0__For_body-seq-helper',\n      'root_body_0_item_body_2_item_body_0_item__Expr',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_2_item_body_0__For_body-seq-helper',\n      'root_body_0_item_body_2_item_body_1__For_body-seq-helper',\n      'SCHEMA_next_out'),\n     ('root_body_0_item_body_2_item_body_0_item__Expr',\n      'root_body_0_item_body_2_item_body_0__For_body-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_0_item__Expr',\n      'root_body_0_item_body_2_item_body_0_item_value__Call',\n      'SCHEMA_value_out'),\n     ('root_body_0_item_body_2_item_body_0_item_value__Call',\n      'root_body_0_item_body_2_item_body_0_item__Expr',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_0_item_value__Call',\n      'root_body_0_item_body_2_item_body_0_item_value_func__Name',\n      'SCHEMA_func_out'),\n     ('root_body_0_item_body_2_item_body_0_item_value__Call',\n      'root_body_0_item_body_2_item_body_0_item_value_args_0__Call_args-seq-helper',\n      'SCHEMA_args_out_all'),\n     ('root_body_0_item_body_2_item_body_0_item_value__Call',\n      'root_body_0_item_body_2_item_body_0_item_value_args_0__Call_args-seq-helper',\n      'SCHEMA_args_out_first'),\n     ('root_body_0_item_body_2_item_body_0_item_value__Call',\n      'root_body_0_item_body_2_item_body_0_item_value_args_0__Call_args-seq-helper',\n      'SCHEMA_args_out_last'),\n     ('root_body_0_item_body_2_item_body_0_item_value_func__Name',\n      'root_body_0_item_body_2_item_body_0_item_value__Call',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_0_item_value_args_0__Call_args-seq-helper',\n      'root_body_0_item_body_2_item_body_0_item_value__Call',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_0_item_value_args_0__Call_args-seq-helper',\n      'root_body_0_item_body_2_item_body_0_item_value_args_0_item__Name',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_2_item_body_0_item_value_args_0_item__Name',\n      'root_body_0_item_body_2_item_body_0_item_value_args_0__Call_args-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1__For_body-seq-helper',\n      'root_body_0_item_body_2_item__For',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1__For_body-seq-helper',\n      'root_body_0_item_body_2_item_body_1_item__If',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_2_item_body_1__For_body-seq-helper',\n      'root_body_0_item_body_2_item_body_0__For_body-seq-helper',\n      'SCHEMA_prev_out'),\n     ('root_body_0_item_body_2_item_body_1__For_body-seq-helper',\n      'root_body_0_item_body_2_item_body_2__For_body-seq-helper',\n      'SCHEMA_next_out'),\n     ('root_body_0_item_body_2_item_body_1_item__If',\n      'root_body_0_item_body_2_item_body_1__For_body-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item__If',\n      'root_body_0_item_body_2_item_body_1_item_test__Compare',\n      'SCHEMA_test_out'),\n     ('root_body_0_item_body_2_item_body_1_item__If',\n      'root_body_0_item_body_2_item_body_1_item_body_0__If_body-seq-helper',\n      'SCHEMA_body_out_all'),\n     ('root_body_0_item_body_2_item_body_1_item__If',\n      'root_body_0_item_body_2_item_body_1_item_body_0__If_body-seq-helper',\n      'SCHEMA_body_out_first'),\n     ('root_body_0_item_body_2_item_body_1_item__If',\n      'root_body_0_item_body_2_item_body_1_item_body_0__If_body-seq-helper',\n      'SCHEMA_body_out_last'),\n     ('root_body_0_item_body_2_item_body_1_item__If',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0__If_orelse-seq-helper',\n      'SCHEMA_orelse_out_all'),\n     ('root_body_0_item_body_2_item_body_1_item__If',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0__If_orelse-seq-helper',\n      'SCHEMA_orelse_out_first'),\n     ('root_body_0_item_body_2_item_body_1_item__If',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0__If_orelse-seq-helper',\n      'SCHEMA_orelse_out_last'),\n     ('root_body_0_item_body_2_item_body_1_item_test__Compare',\n      'root_body_0_item_body_2_item_body_1_item__If',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_test__Compare',\n      'root_body_0_item_body_2_item_body_1_item_test_left__Name',\n      'SCHEMA_left_out'),\n     ('root_body_0_item_body_2_item_body_1_item_test__Compare',\n      'root_body_0_item_body_2_item_body_1_item_test_ops__Eq',\n      'SCHEMA_ops_out'),\n     ('root_body_0_item_body_2_item_body_1_item_test__Compare',\n      'root_body_0_item_body_2_item_body_1_item_test_comparators__Name',\n      'SCHEMA_comparators_out'),\n     ('root_body_0_item_body_2_item_body_1_item_test_left__Name',\n      'root_body_0_item_body_2_item_body_1_item_test__Compare',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_test_ops__Eq',\n      'root_body_0_item_body_2_item_body_1_item_test__Compare',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_test_comparators__Name',\n      'root_body_0_item_body_2_item_body_1_item_test__Compare',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0__If_body-seq-helper',\n      'root_body_0_item_body_2_item_body_1_item__If',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0__If_body-seq-helper',\n      'root_body_0_item_body_2_item_body_1_item_body_0_item__Expr',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0_item__Expr',\n      'root_body_0_item_body_2_item_body_1_item_body_0__If_body-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0_item__Expr',\n      'root_body_0_item_body_2_item_body_1_item_body_0_item_value__Call',\n      'SCHEMA_value_out'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0_item_value__Call',\n      'root_body_0_item_body_2_item_body_1_item_body_0_item__Expr',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0_item_value__Call',\n      'root_body_0_item_body_2_item_body_1_item_body_0_item_value_func__Name',\n      'SCHEMA_func_out'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0_item_value__Call',\n      'root_body_0_item_body_2_item_body_1_item_body_0_item_value_args_0__Call_args-seq-helper',\n      'SCHEMA_args_out_all'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0_item_value__Call',\n      'root_body_0_item_body_2_item_body_1_item_body_0_item_value_args_0__Call_args-seq-helper',\n      'SCHEMA_args_out_first'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0_item_value__Call',\n      'root_body_0_item_body_2_item_body_1_item_body_0_item_value_args_0__Call_args-seq-helper',\n      'SCHEMA_args_out_last'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0_item_value_func__Name',\n      'root_body_0_item_body_2_item_body_1_item_body_0_item_value__Call',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0_item_value_args_0__Call_args-seq-helper',\n      'root_body_0_item_body_2_item_body_1_item_body_0_item_value__Call',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0_item_value_args_0__Call_args-seq-helper',\n      'root_body_0_item_body_2_item_body_1_item_body_0_item_value_args_0_item__Name',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0_item_value_args_0_item__Name',\n      'root_body_0_item_body_2_item_body_1_item_body_0_item_value_args_0__Call_args-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0__If_orelse-seq-helper',\n      'root_body_0_item_body_2_item_body_1_item__If',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0__If_orelse-seq-helper',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item__If',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item__If',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0__If_orelse-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item__If',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_test__Compare',\n      'SCHEMA_test_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item__If',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_body_0__If_body-seq-helper',\n      'SCHEMA_body_out_all'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item__If',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_body_0__If_body-seq-helper',\n      'SCHEMA_body_out_first'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item__If',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_body_0__If_body-seq-helper',\n      'SCHEMA_body_out_last'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item__If',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0__If_orelse-seq-helper',\n      'SCHEMA_orelse_out_all'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item__If',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0__If_orelse-seq-helper',\n      'SCHEMA_orelse_out_first'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item__If',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0__If_orelse-seq-helper',\n      'SCHEMA_orelse_out_last'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_test__Compare',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item__If',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_test__Compare',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_test_left__Constant',\n      'SCHEMA_left_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_test__Compare',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_test_ops__Gt',\n      'SCHEMA_ops_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_test__Compare',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_test_comparators__Name',\n      'SCHEMA_comparators_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_test_left__Constant',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_test__Compare',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_test_ops__Gt',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_test__Compare',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_test_comparators__Name',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_test__Compare',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_body_0__If_body-seq-helper',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item__If',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_body_0__If_body-seq-helper',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_body_0_item__Return',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_body_0_item__Return',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_body_0__If_body-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0__If_orelse-seq-helper',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item__If',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0__If_orelse-seq-helper',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0_item__If',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0_item__If',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0__If_orelse-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0_item__If',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0_item_test__Constant',\n      'SCHEMA_test_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0_item__If',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0_item_body_0__If_body-seq-helper',\n      'SCHEMA_body_out_all'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0_item__If',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0_item_body_0__If_body-seq-helper',\n      'SCHEMA_body_out_first'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0_item__If',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0_item_body_0__If_body-seq-helper',\n      'SCHEMA_body_out_last'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0_item_test__Constant',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0_item__If',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0_item_body_0__If_body-seq-helper',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0_item__If',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0_item_body_0__If_body-seq-helper',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0_item_body_0_item__Pass',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0_item_body_0_item__Pass',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_orelse_0_item_body_0__If_body-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_2__For_body-seq-helper',\n      'root_body_0_item_body_2_item__For',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_2_item_body_2__For_body-seq-helper',\n      'root_body_0_item_body_2_item_body_2_item__Return',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_2_item_body_2__For_body-seq-helper',\n      'root_body_0_item_body_2_item_body_1__For_body-seq-helper',\n      'SCHEMA_prev_out'),\n     ('root_body_0_item_body_2_item_body_2_item__Return',\n      'root_body_0_item_body_2_item_body_2__For_body-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3__FunctionDef_body-seq-helper',\n      'root_body_0_item__FunctionDef',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3__FunctionDef_body-seq-helper',\n      'root_body_0_item_body_3_item__If',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_3__FunctionDef_body-seq-helper',\n      'root_body_0_item_body_2__FunctionDef_body-seq-helper',\n      'SCHEMA_prev_out'),\n     ('root_body_0_item_body_3__FunctionDef_body-seq-helper',\n      'root_body_0_item_body_4__FunctionDef_body-seq-helper',\n      'SCHEMA_next_out'),\n     ('root_body_0_item_body_3_item__If',\n      'root_body_0_item_body_3__FunctionDef_body-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item__If',\n      'root_body_0_item_body_3_item_test__Compare',\n      'SCHEMA_test_out'),\n     ('root_body_0_item_body_3_item__If',\n      'root_body_0_item_body_3_item_body_0__If_body-seq-helper',\n      'SCHEMA_body_out_all'),\n     ('root_body_0_item_body_3_item__If',\n      'root_body_0_item_body_3_item_body_0__If_body-seq-helper',\n      'SCHEMA_body_out_first'),\n     ('root_body_0_item_body_3_item__If',\n      'root_body_0_item_body_3_item_body_0__If_body-seq-helper',\n      'SCHEMA_body_out_last'),\n     ('root_body_0_item_body_3_item_test__Compare',\n      'root_body_0_item_body_3_item__If',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item_test__Compare',\n      'root_body_0_item_body_3_item_test_left__BinOp',\n      'SCHEMA_left_out'),\n     ('root_body_0_item_body_3_item_test__Compare',\n      'root_body_0_item_body_3_item_test_ops__LtE',\n      'SCHEMA_ops_out'),\n     ('root_body_0_item_body_3_item_test__Compare',\n      'root_body_0_item_body_3_item_test_comparators__Constant',\n      'SCHEMA_comparators_out'),\n     ('root_body_0_item_body_3_item_test_left__BinOp',\n      'root_body_0_item_body_3_item_test__Compare',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item_test_left__BinOp',\n      'root_body_0_item_body_3_item_test_left_left__BinOp',\n      'SCHEMA_left_out'),\n     ('root_body_0_item_body_3_item_test_left__BinOp',\n      'root_body_0_item_body_3_item_test_left_op__Add',\n      'SCHEMA_op_out'),\n     ('root_body_0_item_body_3_item_test_left__BinOp',\n      'root_body_0_item_body_3_item_test_left_right__Constant',\n      'SCHEMA_right_out'),\n     ('root_body_0_item_body_3_item_test_left_left__BinOp',\n      'root_body_0_item_body_3_item_test_left__BinOp',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item_test_left_left__BinOp',\n      'root_body_0_item_body_3_item_test_left_left_left__Name',\n      'SCHEMA_left_out'),\n     ('root_body_0_item_body_3_item_test_left_left__BinOp',\n      'root_body_0_item_body_3_item_test_left_left_op__Add',\n      'SCHEMA_op_out'),\n     ('root_body_0_item_body_3_item_test_left_left__BinOp',\n      'root_body_0_item_body_3_item_test_left_left_right__Constant',\n      'SCHEMA_right_out'),\n     ('root_body_0_item_body_3_item_test_left_left_left__Name',\n      'root_body_0_item_body_3_item_test_left_left__BinOp',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item_test_left_left_op__Add',\n      'root_body_0_item_body_3_item_test_left_left__BinOp',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item_test_left_left_right__Constant',\n      'root_body_0_item_body_3_item_test_left_left__BinOp',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item_test_left_op__Add',\n      'root_body_0_item_body_3_item_test_left__BinOp',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item_test_left_right__Constant',\n      'root_body_0_item_body_3_item_test_left__BinOp',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item_test_ops__LtE',\n      'root_body_0_item_body_3_item_test__Compare',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item_test_comparators__Constant',\n      'root_body_0_item_body_3_item_test__Compare',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item_body_0__If_body-seq-helper',\n      'root_body_0_item_body_3_item__If',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item_body_0__If_body-seq-helper',\n      'root_body_0_item_body_3_item_body_0_item__For',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_3_item_body_0_item__For',\n      'root_body_0_item_body_3_item_body_0__If_body-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item_body_0_item__For',\n      'root_body_0_item_body_3_item_body_0_item_target__Name',\n      'SCHEMA_target_out'),\n     ('root_body_0_item_body_3_item_body_0_item__For',\n      'root_body_0_item_body_3_item_body_0_item_iter__Call',\n      'SCHEMA_iter_out'),\n     ('root_body_0_item_body_3_item_body_0_item__For',\n      'root_body_0_item_body_3_item_body_0_item_body_0__For_body-seq-helper',\n      'SCHEMA_body_out_all'),\n     ('root_body_0_item_body_3_item_body_0_item__For',\n      'root_body_0_item_body_3_item_body_0_item_body_0__For_body-seq-helper',\n      'SCHEMA_body_out_first'),\n     ('root_body_0_item_body_3_item_body_0_item__For',\n      'root_body_0_item_body_3_item_body_0_item_body_0__For_body-seq-helper',\n      'SCHEMA_body_out_last'),\n     ('root_body_0_item_body_3_item_body_0_item_target__Name',\n      'root_body_0_item_body_3_item_body_0_item__For',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item_body_0_item_iter__Call',\n      'root_body_0_item_body_3_item_body_0_item__For',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item_body_0_item_iter__Call',\n      'root_body_0_item_body_3_item_body_0_item_iter_func__Name',\n      'SCHEMA_func_out'),\n     ('root_body_0_item_body_3_item_body_0_item_iter__Call',\n      'root_body_0_item_body_3_item_body_0_item_iter_args_0__Call_args-seq-helper',\n      'SCHEMA_args_out_all'),\n     ('root_body_0_item_body_3_item_body_0_item_iter__Call',\n      'root_body_0_item_body_3_item_body_0_item_iter_args_0__Call_args-seq-helper',\n      'SCHEMA_args_out_first'),\n     ('root_body_0_item_body_3_item_body_0_item_iter__Call',\n      'root_body_0_item_body_3_item_body_0_item_iter_args_0__Call_args-seq-helper',\n      'SCHEMA_args_out_last'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_func__Name',\n      'root_body_0_item_body_3_item_body_0_item_iter__Call',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_args_0__Call_args-seq-helper',\n      'root_body_0_item_body_3_item_body_0_item_iter__Call',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_args_0__Call_args-seq-helper',\n      'root_body_0_item_body_3_item_body_0_item_iter_args_0_item__Call',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_args_0_item__Call',\n      'root_body_0_item_body_3_item_body_0_item_iter_args_0__Call_args-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_args_0_item__Call',\n      'root_body_0_item_body_3_item_body_0_item_iter_args_0_item_func__Name',\n      'SCHEMA_func_out'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_args_0_item__Call',\n      'root_body_0_item_body_3_item_body_0_item_iter_args_0_item_args_0__Call_args-seq-helper',\n      'SCHEMA_args_out_all'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_args_0_item__Call',\n      'root_body_0_item_body_3_item_body_0_item_iter_args_0_item_args_0__Call_args-seq-helper',\n      'SCHEMA_args_out_first'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_args_0_item__Call',\n      'root_body_0_item_body_3_item_body_0_item_iter_args_0_item_args_0__Call_args-seq-helper',\n      'SCHEMA_args_out_last'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_args_0_item_func__Name',\n      'root_body_0_item_body_3_item_body_0_item_iter_args_0_item__Call',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_args_0_item_args_0__Call_args-seq-helper',\n      'root_body_0_item_body_3_item_body_0_item_iter_args_0_item__Call',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_args_0_item_args_0__Call_args-seq-helper',\n      'root_body_0_item_body_3_item_body_0_item_iter_args_0_item_args_0_item__Name',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_args_0_item_args_0_item__Name',\n      'root_body_0_item_body_3_item_body_0_item_iter_args_0_item_args_0__Call_args-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item_body_0_item_body_0__For_body-seq-helper',\n      'root_body_0_item_body_3_item_body_0_item__For',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_3_item_body_0_item_body_0__For_body-seq-helper',\n      'root_body_0_item_body_3_item_body_0_item_body_0_item__Break',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_3_item_body_0_item_body_0_item__Break',\n      'root_body_0_item_body_3_item_body_0_item_body_0__For_body-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_4__FunctionDef_body-seq-helper',\n      'root_body_0_item__FunctionDef',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_4__FunctionDef_body-seq-helper',\n      'root_body_0_item_body_4_item__Assign',\n      'SCHEMA_item_out'),\n     ('root_body_0_item_body_4__FunctionDef_body-seq-helper',\n      'root_body_0_item_body_3__FunctionDef_body-seq-helper',\n      'SCHEMA_prev_out'),\n     ('root_body_0_item_body_4_item__Assign',\n      'root_body_0_item_body_4__FunctionDef_body-seq-helper',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_4_item__Assign',\n      'root_body_0_item_body_4_item_targets__Name',\n      'SCHEMA_targets_out'),\n     ('root_body_0_item_body_4_item__Assign',\n      'root_body_0_item_body_4_item_value__Constant',\n      'SCHEMA_value_out'),\n     ('root_body_0_item_body_4_item_targets__Name',\n      'root_body_0_item_body_4_item__Assign',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_body_4_item_value__Constant',\n      'root_body_0_item_body_4_item__Assign',\n      'SCHEMA_parent_out'),\n     ('root_body_0_item_args_args_0_item__Name',\n      'root_body_0_item_args_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_args_args_1_item__Name',\n      'root_body_0_item_args_args_1_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_1_item_targets__Name',\n      'root_body_0_item_body_1_item_targets__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_target__Name',\n      'root_body_0_item_body_2_item_target__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_4_item_targets__Name',\n      'root_body_0_item_body_2_item_target__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_target__Name',\n      'root_body_0_item_body_4_item_targets__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_4_item_targets__Name',\n      'root_body_0_item_body_4_item_targets__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_0_item_value_func__Name',\n      'root_body_0_item_body_0_item_value_func__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_0_item_value_args_0_item__Name',\n      'root_body_0_item_args_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_args_args_0_item__Name',\n      'root_body_0_item_body_0_item_value_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_0_item_value_args_0_item__Name',\n      'root_body_0_item_body_0_item_value_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_iter_func__Name',\n      'root_body_0_item_body_2_item_iter_func__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_3_item_body_0_item_target__Name',\n      'root_body_0_item_body_2_item_target__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_target__Name',\n      'root_body_0_item_body_3_item_body_0_item_target__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_3_item_body_0_item_target__Name',\n      'root_body_0_item_body_4_item_targets__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_4_item_targets__Name',\n      'root_body_0_item_body_3_item_body_0_item_target__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_3_item_body_0_item_target__Name',\n      'root_body_0_item_body_3_item_body_0_item_target__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_iter_args_0_item_func__Name',\n      'root_body_0_item_body_2_item_iter_args_0_item_func__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_0_item_value_func__Name',\n      'root_body_0_item_body_0_item_value_func__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_0_item_value_func__Name',\n      'root_body_0_item_body_2_item_body_0_item_value_func__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_0_item_value_func__Name',\n      'root_body_0_item_body_2_item_body_0_item_value_func__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_0_item_value_args_0_item__Name',\n      'root_body_0_item_args_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_args_args_0_item__Name',\n      'root_body_0_item_body_2_item_body_0_item_value_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_0_item_value_args_0_item__Name',\n      'root_body_0_item_body_0_item_value_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_0_item_value_args_0_item__Name',\n      'root_body_0_item_body_2_item_body_0_item_value_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_0_item_value_args_0_item__Name',\n      'root_body_0_item_body_2_item_body_0_item_value_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_test_left__Name',\n      'root_body_0_item_args_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_args_args_0_item__Name',\n      'root_body_0_item_body_2_item_body_1_item_test_left__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_test_left__Name',\n      'root_body_0_item_body_0_item_value_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_0_item_value_args_0_item__Name',\n      'root_body_0_item_body_2_item_body_1_item_test_left__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_test_left__Name',\n      'root_body_0_item_body_2_item_body_0_item_value_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_0_item_value_args_0_item__Name',\n      'root_body_0_item_body_2_item_body_1_item_test_left__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_test_left__Name',\n      'root_body_0_item_body_2_item_body_1_item_test_left__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_test_comparators__Name',\n      'root_body_0_item_body_2_item_target__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_target__Name',\n      'root_body_0_item_body_2_item_body_1_item_test_comparators__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_test_comparators__Name',\n      'root_body_0_item_body_4_item_targets__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_4_item_targets__Name',\n      'root_body_0_item_body_2_item_body_1_item_test_comparators__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_test_comparators__Name',\n      'root_body_0_item_body_3_item_body_0_item_target__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_3_item_body_0_item_target__Name',\n      'root_body_0_item_body_2_item_body_1_item_test_comparators__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_test_comparators__Name',\n      'root_body_0_item_body_2_item_body_1_item_test_comparators__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_func__Name',\n      'root_body_0_item_body_2_item_iter_func__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_iter_func__Name',\n      'root_body_0_item_body_3_item_body_0_item_iter_func__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_func__Name',\n      'root_body_0_item_body_3_item_body_0_item_iter_func__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0_item_value_func__Name',\n      'root_body_0_item_body_0_item_value_func__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_0_item_value_func__Name',\n      'root_body_0_item_body_2_item_body_1_item_body_0_item_value_func__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0_item_value_func__Name',\n      'root_body_0_item_body_2_item_body_0_item_value_func__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_0_item_value_func__Name',\n      'root_body_0_item_body_2_item_body_1_item_body_0_item_value_func__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0_item_value_func__Name',\n      'root_body_0_item_body_2_item_body_1_item_body_0_item_value_func__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0_item_value_args_0_item__Name',\n      'root_body_0_item_args_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_args_args_0_item__Name',\n      'root_body_0_item_body_2_item_body_1_item_body_0_item_value_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0_item_value_args_0_item__Name',\n      'root_body_0_item_body_0_item_value_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_0_item_value_args_0_item__Name',\n      'root_body_0_item_body_2_item_body_1_item_body_0_item_value_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0_item_value_args_0_item__Name',\n      'root_body_0_item_body_2_item_body_0_item_value_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_0_item_value_args_0_item__Name',\n      'root_body_0_item_body_2_item_body_1_item_body_0_item_value_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0_item_value_args_0_item__Name',\n      'root_body_0_item_body_2_item_body_1_item_test_left__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_test_left__Name',\n      'root_body_0_item_body_2_item_body_1_item_body_0_item_value_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0_item_value_args_0_item__Name',\n      'root_body_0_item_body_2_item_body_1_item_body_0_item_value_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_test_comparators__Name',\n      'root_body_0_item_body_2_item_target__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_target__Name',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_test_comparators__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_test_comparators__Name',\n      'root_body_0_item_body_4_item_targets__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_4_item_targets__Name',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_test_comparators__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_test_comparators__Name',\n      'root_body_0_item_body_3_item_body_0_item_target__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_3_item_body_0_item_target__Name',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_test_comparators__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_test_comparators__Name',\n      'root_body_0_item_body_2_item_body_1_item_test_comparators__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_test_comparators__Name',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_test_comparators__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_orelse_0_item_test_comparators__Name',\n      'root_body_0_item_body_2_item_body_1_item_orelse_0_item_test_comparators__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_3_item_test_left_left_left__Name',\n      'root_body_0_item_args_args_1_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_args_args_1_item__Name',\n      'root_body_0_item_body_3_item_test_left_left_left__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_3_item_test_left_left_left__Name',\n      'root_body_0_item_body_3_item_test_left_left_left__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_args_0_item_func__Name',\n      'root_body_0_item_body_2_item_iter_args_0_item_func__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_iter_args_0_item_func__Name',\n      'root_body_0_item_body_3_item_body_0_item_iter_args_0_item_func__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_args_0_item_func__Name',\n      'root_body_0_item_body_3_item_body_0_item_iter_args_0_item_func__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_args_0_item_args_0_item__Name',\n      'root_body_0_item_args_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_args_args_0_item__Name',\n      'root_body_0_item_body_3_item_body_0_item_iter_args_0_item_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_args_0_item_args_0_item__Name',\n      'root_body_0_item_body_0_item_value_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_0_item_value_args_0_item__Name',\n      'root_body_0_item_body_3_item_body_0_item_iter_args_0_item_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_args_0_item_args_0_item__Name',\n      'root_body_0_item_body_2_item_body_0_item_value_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_0_item_value_args_0_item__Name',\n      'root_body_0_item_body_3_item_body_0_item_iter_args_0_item_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_args_0_item_args_0_item__Name',\n      'root_body_0_item_body_2_item_body_1_item_test_left__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_test_left__Name',\n      'root_body_0_item_body_3_item_body_0_item_iter_args_0_item_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_args_0_item_args_0_item__Name',\n      'root_body_0_item_body_2_item_body_1_item_body_0_item_value_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_2_item_body_1_item_body_0_item_value_args_0_item__Name',\n      'root_body_0_item_body_3_item_body_0_item_iter_args_0_item_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER'),\n     ('root_body_0_item_body_3_item_body_0_item_iter_args_0_item_args_0_item__Name',\n      'root_body_0_item_body_3_item_body_0_item_iter_args_0_item_args_0_item__Name',\n      'EXTRA_SAME_IDENTIFIER')]\n\n\n\n\n```\nall_edges = target_edges + other_edges\n```\n\n## Converting our examples to NDArrays\n\nThe next step is to encode the examples in terms of JAX arrays that we can run our model on.\n\nEach example is encoded as a `GraphBundle`, which contains:\n\n- `automaton_graph`: a sparse representation of the environment dynamics of the corresponding graph MDP. Conceptually, it contains a list of transitions, each of which is associated with a source node, a source observation, an action, a destination node, a destination observation, and a probability of moving to that destination with that observation when taking that action. It is stored in a particular arrangement to make computation efficient; see the docstring for `EncodedGraph` in `automaton_builder.py` for more details.\n- `graph_metadata`: information about the size of the graph.\n- `node_types`: a list of integer node type indices.\n- `edges`: a sparse representation of the labeled adjacency matrix for the graph.\n\nThe `automaton_graph` is used to run the GFSA layer, and the `node_types` and `edges` are used to compute the loss and also to run normal graph-neural-network layers.\n\n\n```\nEDGE_TYPES = sorted({\n    graph_edge_util.JUMPS_OUT_OF_EDGE_TYPE,\n    graph_edge_util.SAME_IDENTIFIER_EDGE_TYPE,\n    *graph_edge_util.schema_edge_types(py_ast_graphs.SCHEMA),\n})\n```\n\n\n```\n# Encode our edges into a coordinate matrix.\nencoded_edges = graph_edge_util.encode_edges(all_edges, EDGE_TYPES)\n# Encode the MDP as a sparse transition matrix.\nbuilder = automaton_builder.AutomatonBuilder(py_ast_graphs.SCHEMA)\nconverted_example = graph_bundle.convert_graph_with_edges(mdp_graph, encoded_edges, builder)\n```\n\n\n```\n# Use `summarize_tree` to replace large arrays with string summaries.\npprint(summarize_tree(converted_example))\n```\n\n    GraphBundle(\n        automaton_graph=EncodedGraph(\n                            initial_to_in_tagged=SparseCoordOperator(\n                                                     input_indices='int32(271, 1) [3, 552] nz:1.0',\n                                                     output_indices='int32(271, 2) [0, 223] nz:0.99',\n                                                     values='float32(271,) 0.97 \u00b10.13 [0.2, 1.0]'),\n                            initial_to_special='int32(89,) [1, 153] nz:1.0',\n                            in_tagged_to_in_tagged=SparseCoordOperator(\n                                                       input_indices='int32(896, 1) [0, 548] nz:1.0',\n                                                       output_indices='int32(896, 2) [0, 223] nz:1.0',\n                                                       values='float32(896,) 0.97 \u00b10.14 [0.2, 1.0]'),\n                            in_tagged_to_special='int32(224,) [0, 152] nz:1.0',\n                            in_tagged_node_indices='int32(224,) [0, 88] nz:1.0'),\n        graph_metadata=EncodedGraphMetadata(num_nodes=89, num_input_tagged_nodes=224),\n        node_types='int32(89,) [0, 38] nz:0.99',\n        edges=SparseCoordOperator(\n                  input_indices='int32(312, 1) [0, 27] nz:0.99',\n                  output_indices='int32(312, 2) [0, 88] nz:0.99',\n                  values='int32(312,) [1, 1] nz:1.0'))\n\n\nThis representation of the MDP graph can be fed into our JAX implementation of the GFSA layer.\n\nIf desired, it can also be padded to a larger size (for instance, to allow batching graphs with different numbers of nodes). The `graph_metadata` field keeps track of the original size, so this doesn't lose any information.\n\n\n```\npadded_example = graph_bundle.pad_example(\n    converted_example,\n    config=graph_bundle.PaddingConfig(\n        static_max_metadata=automaton_builder.EncodedGraphMetadata(\n            num_nodes=256, num_input_tagged_nodes=512),\n        max_initial_transitions=1024,\n        max_in_tagged_transitions=2048,\n        max_edges=2048))\npprint(summarize_tree(padded_example))\n```\n\n    GraphBundle(\n        automaton_graph=EncodedGraph(\n                            initial_to_in_tagged=SparseCoordOperator(\n                                                     input_indices='int32(1024, 1) [0, 552] nz:0.26',\n                                                     output_indices='int32(1024, 2) [0, 223] nz:0.26',\n                                                     values='float32(1024,) 0.26 \u00b10.44 [0.0, 1.0] nz:0.26'),\n                            initial_to_special='int32(256,) [0, 153] nz:0.35',\n                            in_tagged_to_in_tagged=SparseCoordOperator(\n                                                       input_indices='int32(2048, 1) [0, 548] nz:0.44',\n                                                       output_indices='int32(2048, 2) [0, 223] nz:0.44',\n                                                       values='float32(2048,) 0.42 \u00b10.49 [0.0, 1.0] nz:0.44'),\n                            in_tagged_to_special='int32(512,) [0, 152] nz:0.44',\n                            in_tagged_node_indices='int32(512,) [0, 88] nz:0.44'),\n        graph_metadata=EncodedGraphMetadata(num_nodes=89, num_input_tagged_nodes=224),\n        node_types='int32(256,) [0, 38] nz:0.34',\n        edges=SparseCoordOperator(\n                  input_indices='int32(2048, 1) [0, 27] nz:0.15',\n                  output_indices='int32(2048, 2) [0, 88] nz:0.15',\n                  values='int32(2048,) [0, 1] nz:0.15'))\n\n\n## Building a model in Colab\n\n\nNow that we have data that can be passed to a model, we can work on the model itself.\n\nThe core solver for the automaton Markov chain's absorbing distribution is implemented in [automaton_builder.py](https://github.com/google-research/google-research/blob/master/gfsa/automaton_builder.py). To make it easier to use, it has been wrapped in the [`flax.nn` API](https://flax.readthedocs.io/en/latest/flax.nn.html) (note: it is not yet available for the new Linen API, but should be straightforward to adapt if needed).\n\nLet's build a simple model that just runs a single GFSA layer with a few specific hyperparameters.\n\n\n\n---\n\n*Note on variants:* Variants are an optional input to the GFSA layer, which allows dynamically changing the observations received by the agent depending on its start node and its current node. The `variant_weights` input chooses between a fixed number of extra observations that the agent can receive, and the automaton can then act in a different way conditioned on this information. (In appendix C.2 of the paper, $\\Gamma$ denotes the set of all variants, and each $\\gamma \\in \\Gamma$ is a specific variant index.)\n\nFor this simple task, we do not really need to use any variants. However, the experiments in the paper use variants to tell the agent whether two identifier nodes have the same name (for the static analysis experiments) or to pass information from a graph neural network to the GFSA layer (for the variable misuse experiments).\n\nIf you would like to see how enabling variants affect the policy parameters, you can set `USE_VARIANTS = True` below.\n\n---\n\n\n```\nUSE_VARIANTS = False\n```\n\n\n```\npadding_config = graph_bundle.PaddingConfig(\n    static_max_metadata=automaton_builder.EncodedGraphMetadata(\n        num_nodes=256, num_input_tagged_nodes=512),\n    max_initial_transitions=1024,\n    max_in_tagged_transitions=2048,\n    max_edges=2048)\n```\n\n\n```\n@flax.nn.module\ndef simple_model(example: graph_bundle.GraphBundle):\n  if USE_VARIANTS:\n    # Compute the probability of receiving each variant observation. In this case, \n    # these are one-hot vectors that specify whether the start node and the\n    # current node are both identifiers with the same name.\n    variant_weights = edge_supervision_models.variants_from_edges(\n        example,\n        graph_metadata=padding_config.static_max_metadata,\n        variant_edge_type_indices=[EDGE_TYPES.index(\"EXTRA_SAME_IDENTIFIER\")],\n        num_edge_types=len(EDGE_TYPES))\n    \n    # Weights are indexed by (start node, current node, variant index).\n    # `variants_from_edges` sets variants based on whether or not an edge exists\n    # between the two nodes (and what type that edge has).\n    assert variant_weights.shape == (\n        padding_config.static_max_metadata.num_nodes,\n        padding_config.static_max_metadata.num_nodes,\n        2)\n  else:\n    # Don't use variants. In this case, the agent only observes the current\n    # node type and the in-edge type used to enter the node.\n    variant_weights = None\n\n  # Pass all of the information into our GFSA layer.\n  # The flax.nn API encapsulates the parameters inside the\n  # automaton_layer.FiniteStateGraphAutomaton call, so they aren't passed as\n  # arguments. Instead, they will be initialized when the model is instantiated\n  # below.\n  absorbing_probs = automaton_layer.FiniteStateGraphAutomaton(\n      encoded_graph=example.automaton_graph,\n      variant_weights=variant_weights,\n      static_metadata=padding_config.static_max_metadata,\n      dynamic_metadata=example.graph_metadata,\n      # The builder, defind above, determines how the MDP is interpreted.\n      builder=builder,\n      # Increasing this produces multiple edges by running multiple layers in\n      # parallel.\n      num_out_edges=1,\n      # Whether to share parameters across parallel layers, if num_out_edges > 1\n      share_states_across_edges=True,\n      # Controls how many states the automaton has, not counting the initial state.\n      num_intermediate_states = 1,\n      # Configures how parameters are initialized.\n      legacy_initialize=False,\n      # Turns off the adjustment parameters described in Section 3.3\n      logit_scaling=\"none\",\n      # Controls \\epsilon_{bt-stop} described in Appendix C.2\n      backtrack_fails_prob=0.001,\n  ).squeeze(axis=0)\n\n  # Convert from probability space to logit space to make it easier to define\n  # the loss function; gracefully handles numerical stability issues by clipping\n  # gradients.\n  logits = model_util.safe_logit(absorbing_probs)\n  return logits\n\n```\n\nNote that we could also have configure the `FiniteStateGraphAutomaton` layer with `gin`, which is how the standalone training scripts work.\n\nNow we can initialize the model parameters:\n\n\n```\n_, initial_params = simple_model.init(jax.random.PRNGKey(4321), padded_example)\n\n# Visualize the parameters of the model; Flax implicitly passes these into the\n# layer object when the model is run.\npprint(summarize_tree(initial_params))\n```\n\n    {'FiniteStateGraphAutomaton_0':\n       {'edge_logits_entropy': {},\n        'log_routing_params_shared':\n          RoutingParams(\n              move='float32(1, 553, 2, 2) -2.4 \u00b10.94 [-5.8, -0.14]',\n              special='float32(1, 154, 2, 3) -4.3 \u00b10.77 [-6.6, -2.5]')}}\n\n\nIn particular, the tabular policy for the FSA-based agent is stored in a dataclass of type `RoutingParams`. We can visualize the entries of it below.\n\nEach row represents a different POMDP observation that the agent might receive, based on its current location and the last action it took. Within each row, the small dark 3x2 rectangles are the probabilities of taking special actions (add-edge-and-stop, backtrack, stop) in each of the two FSM states, and the large variable-sized rectangles are the probabilities of moving to some adjacent node with each possible next state. The \"checkerboard\" patterns reflect the initialization bias, which encourages the automaton to stay\nin the same state more often.\n\n(If you enabled variants, the two columns within each box represent the two \"variant\" observations. Since we set the variants using `EXTRA_SAME_IDENTIFIER`, the right column is used when the start node and current node are both variables with the same identifier, and the left column is used in every other case.)\n\n\n```\ninitial_log_routing_params = initial_params[\"FiniteStateGraphAutomaton_0\"][\"log_routing_params_shared\"]\nvisualization.ndarrays.show_routing_params(\n    builder,\n    builder.routing_softmax(initial_log_routing_params),\n    rparams_are_logits=False,\n    row_split_ct=4,\n    figsize=(20, 10),\n    vmax=.5, # to enhance detail\n    colorbar=False)\n```\n\n## Training the model\n\nTo show how the model can be trained, this section includes a simplified training loop that runs in Colab. (See the \"Advanced usage\" for a more efficient way to train a model for practical use.)\n\nWe can start by generating a dataset of programs:\n\n\n```\nrng = np.random.RandomState(42)\nexamples = []\nwhile len(examples) < 500:\n  the_ast = tasks.make_ast(150, rng, python_numbers_control_flow.CFG_DISTRIBUTION)\n  generic_ast = py_ast_graphs.py_ast_to_generic(the_ast)\n  mdp_graph, id_conversion_map = generic_ast_graphs.ast_to_graph(generic_ast, ast_spec=py_ast_graphs.PY_AST_SPECS)\n  all_edges = (\n      graph_edge_util.compute_jumps_out_edges(the_ast, id_conversion_map)\n      + graph_edge_util.compute_same_identifier_edges(the_ast, id_conversion_map)\n  )\n  encoded_edges = graph_edge_util.encode_edges(all_edges, EDGE_TYPES)\n  converted_example = graph_bundle.convert_graph_with_edges(mdp_graph, encoded_edges, builder)\n  try:\n    padded_example = graph_bundle.pad_example(\n      converted_example,\n      config=padding_config)\n    examples.append((the_ast, padded_example))\n  except ValueError:\n    pass\n  if len(examples) % 100 == 0:\n    print(len(examples))\n    sys.stdout.flush()\n```\n\n    100\n    200\n    300\n    400\n    500\n\n\nNow we set up our loss function and data iterator:\n\n\n```\ndef loss_fn(model, example, unused_metadata):\n  \"\"\"Compute cross-entropy loss between model output logits and target edges.\"\"\"\n  del unused_metadata\n  unused_rng = jax.random.PRNGKey(0)  # For compatibility with stochastic baselines\n  loss, metrics_dict = train_edge_supervision_lib.loss_fn(\n      *train_edge_supervision_lib.extract_outputs_and_targets(\n          model=model,\n          padded_example_and_rng=(example, unused_rng),\n          target_edge_index=EDGE_TYPES.index(\"EXTRA_JUMPS_OUT_OF\"),\n          num_edge_types=len(EDGE_TYPES)))\n  return  loss, metrics_dict\n```\n\n\n```\ndef data_iterator():\n  rng = np.random.RandomState(1234)\n  for epoch in itertools.count():\n    shuffled_examples = list(enumerate(examples))\n    rng.shuffle(shuffled_examples)\n    for example_id, (_, padded_example) in shuffled_examples:\n      yield train_util.ExampleWithMetadata(\n          example=padded_example, epoch=epoch, example_id=example_id)\n\ndef batch_iterator():\n  it = data_iterator()\n  ldc = jax.local_device_count()\n  it = data_loading.batch(it, (ldc, 32 // ldc))\n  return it\n```\n\n\n```\npprint(summarize_tree(next(batch_iterator())))\n```\n\n    ExampleWithMetadata(\n        epoch='int64(8, 4) [0, 0] nz:0.0',\n        example_id='int64(8, 4) [7, 479] nz:1.0',\n        example=GraphBundle(\n                    automaton_graph=EncodedGraph(\n                                        initial_to_in_tagged=SparseCoordOperator(\n                                                                 input_indices='int32(8, 4, 1024, 1) [0, 552] nz:0.51',\n                                                                 output_indices='int32(8, 4, 1024, 2) [0, 497] nz:0.5',\n                                                                 values='float32(8, 4, 1024) 0.49 \u00b10.49 [0.0, 1.0] nz:0.51'),\n                                        initial_to_special='int32(8, 4, 256) [0, 153] nz:0.75',\n                                        in_tagged_to_in_tagged=SparseCoordOperator(\n                                                                   input_indices='int32(8, 4, 2048, 1) [0, 548] nz:0.81',\n                                                                   output_indices='int32(8, 4, 2048, 2) [0, 497] nz:0.81',\n                                                                   values='float32(8, 4, 2048) 0.78 \u00b10.4 [0.0, 1.0] nz:0.81'),\n                                        in_tagged_to_special='int32(8, 4, 512) [0, 152] nz:0.88',\n                                        in_tagged_node_indices='int32(8, 4, 512) [0, 202] nz:0.88'),\n                    graph_metadata=EncodedGraphMetadata(\n                                       num_nodes='int64(8, 4) [181, 203] nz:1.0',\n                                       num_input_tagged_nodes='int64(8, 4) [407, 498] nz:1.0'),\n                    node_types='int32(8, 4, 256) [0, 38] nz:0.74',\n                    edges=SparseCoordOperator(\n                              input_indices='int32(8, 4, 2048, 1) [0, 1] nz:0.16',\n                              output_indices='int32(8, 4, 2048, 2) [0, 202] nz:0.16',\n                              values='int32(8, 4, 2048) [0, 1] nz:0.16')),\n        mask='bool(8, 4) T:1.0',\n        static_metadata=None)\n\n\nNow we can construct an optimizer:\n\n\n```\ninitial_optimizer = flax.optim.Adam().create(flax.nn.Model(simple_model, initial_params))\n```\n\nAnd do a bit of training:\n\n\n```\nrun_name = datetime.datetime.now().strftime('%y_%m_%d__%H_%M_%S')\n```\n\n\n```\n# Takes about 10 to 15 minutes on a TPU.\n# If you prefer, you can skip this step and load precomputed weights in the next cell.\ntrained_optimizer = simple_runner.training_loop(\n    optimizer=initial_optimizer,\n    train_iterator=batch_iterator(),\n    loss_fn=loss_fn,\n    validation_fn=None,\n    max_iterations=3_000,\n    learning_rate_schedule=learning_rate_schedules.ConstantLearningRateSchedule(0.01),\n    artifacts_dir=f\"/tmp/artifacts_{run_name}\",\n    steps_per_save=200,\n)\n```\n\n    INFO:absl:Setting up training loop.\n    INFO:absl:Peeking at dataset format...\n    INFO:absl:Starting main training loop.\n    INFO:absl:200: loss: 19.377723693847656 avg_per_non_target: 0.00021761865355074406 avg_per_target: 2.2486281394958496 batch_clf_thresh_at_0.1/f1: 0.40355727076530457 batch_clf_thresh_at_0.1/precision: 0.29276591539382935 batch_clf_thresh_at_0.1/recall: 0.6156994104385376 effective_p_model_given_nontarget: 0.00021898560225963593 effective_p_model_given_target: 0.11125928163528442 elapsed_hours: 0.009833792514271206 epoch: 12 gradient_global_norm: 1.7030329704284668 learning_rate: 0.01 positive_per_negative: 0.0001304901234107092 step: 200 worst: 2.693657875061035\n    INFO:absl:Saving a checkpoint at 200\n    INFO:absl:400: loss: 5.795314788818359 avg_per_non_target: 7.953135354910046e-05 avg_per_target: 0.5528256893157959 batch_clf_thresh_at_0.1/f1: 0.7735148668289185 batch_clf_thresh_at_0.1/precision: 0.65949946641922 batch_clf_thresh_at_0.1/recall: 1.0 effective_p_model_given_nontarget: 8.090212941169739e-05 effective_p_model_given_target: 0.587834358215332 elapsed_hours: 0.019207057820426095 epoch: 25 gradient_global_norm: 0.7654008269309998 learning_rate: 0.01 positive_per_negative: 0.00012342461559455842 seconds_per_step: 0.16871878027915954 step: 400 worst: 0.7844127416610718\n    INFO:absl:Saving a checkpoint at 400\n    INFO:absl:600: loss: 1.3853754997253418 avg_per_non_target: 2.3435932234860957e-05 avg_per_target: 0.11455842852592468 batch_clf_thresh_at_0.1/f1: 0.9865643978118896 batch_clf_thresh_at_0.1/precision: 0.9755208492279053 batch_clf_thresh_at_0.1/recall: 1.0 effective_p_model_given_nontarget: 2.4924054741859436e-05 effective_p_model_given_target: 0.892683744430542 elapsed_hours: 0.028151852223608227 epoch: 38 gradient_global_norm: 0.27504831552505493 learning_rate: 0.01 positive_per_negative: 0.00012362848792690784 seconds_per_step: 0.16100628972053527 step: 600 worst: 0.17014822363853455\n    INFO:absl:Saving a checkpoint at 600\n    INFO:absl:800: loss: 0.6699908971786499 avg_per_non_target: 1.2433583833626471e-05 avg_per_target: 0.04683126509189606 batch_clf_thresh_at_0.1/f1: 1.0 batch_clf_thresh_at_0.1/precision: 1.0 batch_clf_thresh_at_0.1/recall: 1.0 effective_p_model_given_nontarget: 1.3738870620727539e-05 effective_p_model_given_target: 0.9543433785438538 elapsed_hours: 0.037277566923035514 epoch: 51 gradient_global_norm: 0.13815997540950775 learning_rate: 0.01 positive_per_negative: 0.00012166185479145497 seconds_per_step: 0.16426286339759827 step: 800 worst: 0.06643061339855194\n    INFO:absl:Saving a checkpoint at 800\n    INFO:absl:1000: loss: 0.4604664444923401 avg_per_non_target: 7.983658179000486e-06 avg_per_target: 0.027946151793003082 batch_clf_thresh_at_0.1/f1: 1.0 batch_clf_thresh_at_0.1/precision: 1.0 batch_clf_thresh_at_0.1/recall: 1.0 effective_p_model_given_nontarget: 9.484589099884033e-06 effective_p_model_given_target: 0.972494900226593 elapsed_hours: 0.04654399693012237 epoch: 63 gradient_global_norm: 0.09773273020982742 learning_rate: 0.01 positive_per_negative: 0.0001405532384524122 seconds_per_step: 0.1667957365512848 step: 1000 worst: 0.04434922710061073\n    INFO:absl:Saving a checkpoint at 1000\n    INFO:absl:1200: loss: 0.29468247294425964 avg_per_non_target: 5.69584744880558e-06 avg_per_target: 0.018984615802764893 batch_clf_thresh_at_0.1/f1: 1.0 batch_clf_thresh_at_0.1/precision: 1.0 batch_clf_thresh_at_0.1/recall: 1.0 effective_p_model_given_nontarget: 7.295981049537659e-06 effective_p_model_given_target: 0.981222927570343 elapsed_hours: 0.05560751822259691 epoch: 76 gradient_global_norm: 0.06535814702510834 learning_rate: 0.01 positive_per_negative: 0.000107972628029529 seconds_per_step: 0.16314337015151978 step: 1200 worst: 0.027228930965065956\n    INFO:absl:Saving a checkpoint at 1200\n    INFO:absl:1400: loss: 0.2343970537185669 avg_per_non_target: 4.313907538744388e-06 avg_per_target: 0.012400067411363125 batch_clf_thresh_at_0.1/f1: 1.0 batch_clf_thresh_at_0.1/precision: 1.0 batch_clf_thresh_at_0.1/recall: 1.0 effective_p_model_given_nontarget: 5.969777703285217e-06 effective_p_model_given_target: 0.9876830577850342 elapsed_hours: 0.06473897424009112 epoch: 89 gradient_global_norm: 0.052110783755779266 learning_rate: 0.01 positive_per_negative: 0.0001521498488727957 seconds_per_step: 0.16436620354652404 step: 1400 worst: 0.01986014097929001\n    INFO:absl:Saving a checkpoint at 1400\n    INFO:absl:1600: loss: 0.17968504130840302 avg_per_non_target: 3.3588257792871445e-06 avg_per_target: 0.010300396010279655 batch_clf_thresh_at_0.1/f1: 1.0 batch_clf_thresh_at_0.1/precision: 1.0 batch_clf_thresh_at_0.1/recall: 1.0 effective_p_model_given_nontarget: 5.058944225311279e-06 effective_p_model_given_target: 0.9897605180740356 elapsed_hours: 0.07402368505795796 epoch: 102 gradient_global_norm: 0.04094467684626579 learning_rate: 0.01 positive_per_negative: 0.00013812952965963632 seconds_per_step: 0.16712479114532472 step: 1600 worst: 0.016302866861224174\n    INFO:absl:Saving a checkpoint at 1600\n    INFO:absl:1800: loss: 0.12899067997932434 avg_per_non_target: 2.4813391519273864e-06 avg_per_target: 0.007430391386151314 batch_clf_thresh_at_0.1/f1: 1.0 batch_clf_thresh_at_0.1/precision: 1.0 batch_clf_thresh_at_0.1/recall: 1.0 effective_p_model_given_nontarget: 4.213303327560425e-06 effective_p_model_given_target: 0.9926003217697144 elapsed_hours: 0.08313697311613295 epoch: 115 gradient_global_norm: 0.02997024543583393 learning_rate: 0.01 positive_per_negative: 0.00012066987983416766 seconds_per_step: 0.1640391767024994 step: 1800 worst: 0.011770209297537804\n    INFO:absl:Saving a checkpoint at 1800\n    INFO:absl:2000: loss: 0.10818523168563843 avg_per_non_target: 2.0723803118016804e-06 avg_per_target: 0.00690688518807292 batch_clf_thresh_at_0.1/f1: 1.0 batch_clf_thresh_at_0.1/precision: 1.0 batch_clf_thresh_at_0.1/recall: 1.0 effective_p_model_given_nontarget: 3.822147846221924e-06 effective_p_model_given_target: 0.9931188821792603 elapsed_hours: 0.09223447653982375 epoch: 127 gradient_global_norm: 0.025862064212560654 learning_rate: 0.01 positive_per_negative: 0.00012165141379227862 seconds_per_step: 0.16375505328178405 step: 2000 worst: 0.010692710056900978\n    INFO:absl:Saving a checkpoint at 2000\n    INFO:absl:2200: loss: 0.09486329555511475 avg_per_non_target: 1.6884167735042865e-06 avg_per_target: 0.00620083836838603 batch_clf_thresh_at_0.1/f1: 1.0 batch_clf_thresh_at_0.1/precision: 1.0 batch_clf_thresh_at_0.1/recall: 1.0 effective_p_model_given_nontarget: 3.4496188163757324e-06 effective_p_model_given_target: 0.9938190579414368 elapsed_hours: 0.1012620895438724 epoch: 140 gradient_global_norm: 0.021290918812155724 learning_rate: 0.01 positive_per_negative: 0.0001338127622148022 seconds_per_step: 0.16249702692031862 step: 2200 worst: 0.00906508881598711\n    INFO:absl:Saving a checkpoint at 2200\n    INFO:absl:2400: loss: 0.08048178255558014 avg_per_non_target: 1.4781015806875075e-06 avg_per_target: 0.005473007448017597 batch_clf_thresh_at_0.1/f1: 1.0 batch_clf_thresh_at_0.1/precision: 1.0 batch_clf_thresh_at_0.1/recall: 1.0 effective_p_model_given_nontarget: 3.259629011154175e-06 effective_p_model_given_target: 0.9945425987243652 elapsed_hours: 0.11027509609858195 epoch: 153 gradient_global_norm: 0.018114732578396797 learning_rate: 0.01 positive_per_negative: 0.00012266272096894681 seconds_per_step: 0.16223411321640013 step: 2400 worst: 0.00795502308756113\n    INFO:absl:Saving a checkpoint at 2400\n    INFO:absl:2600: loss: 0.05905803292989731 avg_per_non_target: 1.228057612934208e-06 avg_per_target: 0.003271682420745492 batch_clf_thresh_at_0.1/f1: 1.0 batch_clf_thresh_at_0.1/precision: 1.0 batch_clf_thresh_at_0.1/recall: 1.0 effective_p_model_given_nontarget: 3.032386302947998e-06 effective_p_model_given_target: 0.9967347383499146 elapsed_hours: 0.11931268877453274 epoch: 166 gradient_global_norm: 0.014629610814154148 learning_rate: 0.01 positive_per_negative: 0.0001021219213725999 seconds_per_step: 0.16267666697502137 step: 2600 worst: 0.005318102426826954\n    INFO:absl:Saving a checkpoint at 2600\n    INFO:absl:2800: loss: 0.04910304397344589 avg_per_non_target: 1.0667299648048356e-06 avg_per_target: 0.0021193567663431168 batch_clf_thresh_at_0.1/f1: 1.0 batch_clf_thresh_at_0.1/precision: 1.0 batch_clf_thresh_at_0.1/recall: 1.0 effective_p_model_given_nontarget: 2.868473529815674e-06 effective_p_model_given_target: 0.9978830814361572 elapsed_hours: 0.12838497817516326 epoch: 179 gradient_global_norm: 0.012885957024991512 learning_rate: 0.01 positive_per_negative: 0.00011229085794184357 seconds_per_step: 0.16330119609832763 step: 2800 worst: 0.0038279499858617783\n    INFO:absl:Saving a checkpoint at 2800\n    INFO:absl:3000: loss: 0.049854353070259094 avg_per_non_target: 9.077161848836113e-07 avg_per_target: 0.003057182300835848 batch_clf_thresh_at_0.1/f1: 1.0 batch_clf_thresh_at_0.1/precision: 1.0 batch_clf_thresh_at_0.1/recall: 1.0 effective_p_model_given_nontarget: 2.723187208175659e-06 effective_p_model_given_target: 0.9969476461410522 elapsed_hours: 0.13739732556872897 epoch: 191 gradient_global_norm: 0.011399208568036556 learning_rate: 0.01 positive_per_negative: 0.00013453495921567082 seconds_per_step: 0.16222224950790406 step: 3000 worst: 0.004913375712931156\n    INFO:absl:Saving a checkpoint at 3000\n    INFO:absl:Training loop finished after 3000 steps.\n    INFO:absl:Saving a checkpoint at 3000\n\n\n\n```\n# Set this to:\n# - \"last\" to load final trained weights\n# - \"precomputed\" to load precomputed weights (if you skipped the previous cell)\n# - a multiple of 200 to load a checkpoint from partway through training.\nload_what = \"last\"\n\nif load_what == \"last\":\n  trained_model = flax.jax_utils.unreplicate(trained_optimizer).target\nelif load_what == \"precomputed\":\n  checkpoint_optimizer, _ = simple_runner.load_from_checkpoint(initial_optimizer, \"./gfsa/notebooks/demo_checkpoint.msgpack\")\n  trained_model = checkpoint_optimizer.target\nelse:\n  checkpoint_optimizer, _ = simple_runner.load_from_checkpoint(initial_optimizer, f\"/tmp/artifacts_{run_name}/checkpoints/current_at_{load_what}.msgpack\")\n  trained_model = checkpoint_optimizer.target\n```\n\n## Investigating the resulting policy\n\nWe can visualize the model weights, and see that the model has learned a policy for solving this simplified static analysis task.\n\nNote that the leftmost pixel is only turned on for a small subset of rows, in particular `FunctionDef: body_in`, `For: parent_in`/`body_in`, and `While: body_in`. This is because the leftmost pixel corresponds to the \"add edge and stop\" action, and the only possible destinations for edges in this task are function definitions, for loops, and while loops.\n\n(If you enabled variants: Recall that the `EXTRA_SAME_IDENTIFIER` edge only connects identifiers, so the parameters in the second column are only used when the agent is at a `Name` node. As a consequence, only the rows for `Name` nodes have changed after training.)\n\n\n```\ntrained_log_routing_params = trained_model.params[\"FiniteStateGraphAutomaton_0\"][\"log_routing_params_shared\"]\nvisualization.ndarrays.show_routing_params(\n    builder,\n    builder.routing_softmax(trained_log_routing_params),\n    rparams_are_logits=False,\n    row_split_ct=4,\n    figsize=(20, 10),\n    colorbar=False)\n```\n\nLet's write our own custom Python function to see how it works:\n\n\n\n\n```\nthe_ast = gast.parse(\"\"\"\ndef test_function(foo):\n  for x in foo:\n    if x:\n      return True\n    else:\n      continue\n  \n  while False:\n    while True:\n      break\n    continue\n  \n  return\n\"\"\")\n\ngeneric_ast = py_ast_graphs.py_ast_to_generic(the_ast)\nmdp_graph, id_conversion_map = generic_ast_graphs.ast_to_graph(generic_ast, ast_spec=py_ast_graphs.PY_AST_SPECS)\nall_edges = (\n    graph_edge_util.compute_jumps_out_edges(the_ast, id_conversion_map)\n    + graph_edge_util.compute_same_identifier_edges(the_ast, id_conversion_map)\n)\nencoded_edges = graph_edge_util.encode_edges(all_edges, EDGE_TYPES)\nconverted_example = graph_bundle.convert_graph_with_edges(mdp_graph, encoded_edges, builder)\n\ntest_example = graph_bundle.pad_example(\n    converted_example,\n    config=padding_config)\n```\n\n\n```\ndef get_short_name(long_name):\n  \"\"\"Helper function to get a short name for an AST's MDP graph node.\"\"\"\n  path, nodetype = long_name.split(\"__\")\n  path_parts = path.split(\"_\")\n  levels = []\n  for part in path_parts:\n    if all(c in '0123456789' for c in part):\n      levels[-1] = levels[-1] + \"[\" + part + \"]\"\n    else:\n      levels.append(part)\n  last = levels[-1]\n  num_rest = len(levels) - 1\n  return \"|\"*num_rest + last + \": \" + nodetype\n```\n\n\n```\n# Generate short summary names for each node, so we can visualize it easily\nshort_names = [f\"{i:2d} \" + get_short_name(k) for i, k in enumerate(mdp_graph.keys())]\nmaxlen = max(len(n) for n in short_names)\npadded_names = [n + \" \" * (maxlen - len(n)) for n in short_names]\n```\n\nWe can run the model on this example:\n\n\n```\nmodel_output = jax.nn.sigmoid(trained_model(test_example))\ntarget_output = edge_supervision_models.ground_truth_adjacency(\n    example=test_example,\n    graph_metadata=padding_config.static_max_metadata,\n    target_edge_type=\"EXTRA_JUMPS_OUT_OF\",\n    all_edge_types=EDGE_TYPES)\n```\n\nVisualizing the model on our example, we can see that the model outputs match the ground-truth targets.\n\nIn this figure, the targets are on the left, and the model output is on the right. The Y axis indicates the location of the source node, and the X axis corresponds to the location of the target node.\n\n\n```\nnum_nodes = test_example.graph_metadata.num_nodes\nvisualization.ndarrays.ndshow(\n    jnp.stack([target_output, model_output])[:, :num_nodes, :num_nodes],\n    \"crc\",\n    figsize=(20,10),\n    names={1:padded_names, 2:padded_names},\n    ticks=True)\n```\n\nWe can compare this to the output of an untrained model:\n\n\n```\nuntrained_output = jax.nn.sigmoid(initial_optimizer.target(test_example))\nvisualization.ndarrays.ndshow(\n    jnp.stack([target_output, untrained_output])[:, :num_nodes, :num_nodes],\n    \"crc\",\n    figsize=(20,10),\n    names={1:padded_names, 2:padded_names},\n    ticks=True)\n```\n\nTo get a better sense of *how* the learned policy works, we can simulate each step of the automaton individually, and visualize a heatmap of the location of the automaton at each timestep.\n\n\n```\ndef unroll_automaton(routing_param_logits: automaton_builder.RoutingParams, example: graph_bundle.GraphBundle, initial_node_index:int, rollout_steps: int):\n  # Variants are the same as in model definition\n  variant_weights = edge_supervision_models.variants_from_edges(\n      example,\n      graph_metadata=padding_config.static_max_metadata,\n      variant_edge_type_indices=[EDGE_TYPES.index(\"EXTRA_SAME_IDENTIFIER\")],\n      num_edge_types=len(EDGE_TYPES))\n\n  # Build the transition matrix for the combination of MDP and policy\n  transition_matrix = builder.build_transition_matrix(\n        builder.routing_softmax(routing_param_logits),\n        example.automaton_graph,\n        padding_config.static_max_metadata)\n\n  initial_state = 0\n\n  # Unroll\n  unrolled = automaton_builder.unroll_chain_steps(\n      builder=builder,\n      transition_matrix=transition_matrix,\n      variant_weights=variant_weights[initial_node_index],\n      start_machine_state=(jnp.arange(2) == initial_state),\n      node_index=initial_node_index,\n      steps=rollout_steps)\n\n  # Reformat for easier analysis\n  aggregated = automaton_builder.aggregate_unrolled_per_node(\n      unrolled,\n      node_index=initial_node_index,\n      initial_state=initial_state,\n      transition_matrix=transition_matrix,\n      graph_metadata=padding_config.static_max_metadata)\n\n  return aggregated\n```\n\n\n```\nstate_colors_dict = {\n  \"State A\":            mpl.colors.to_rgb(\"#4e79a7\"),\n  \"State B\":            mpl.colors.to_rgb(\"#edc948\"),\n  \"\u2713 Add edge and stop\":  mpl.colors.to_rgb(\"#59a14f\"),\n  \"\u2190 Backtrack\":          mpl.colors.to_rgb(\"#b07aa1\"),\n  \"\u2717 Stop\":               mpl.colors.to_rgb(\"#e15759\"),\n}\nstate_symbols = \"AB\u2713\u2190\u2717\"\nstate_colors = list(state_colors_dict.values())\nlegend_items = [\n  mpl.patches.Patch(color=c, label=l)\n  for l,c in state_colors_dict.items()\n]\n\ndef show_automaton_steps(steps, ax):\n  steps = np.array(steps)\n  ax.imshow(np.einsum(\"sni,ic->nsc\", steps[:, :num_nodes, :], state_colors))\n  ax.set_yticks(np.arange(num_nodes))\n  ax.set_yticklabels(labels=padded_names, family=\"monospace\")\n  ax.set_xlabel(\"Step number\")\n\n  for step in range(steps.shape[0]):\n    for node in range(num_nodes):\n      for i, sym in enumerate(state_symbols):\n        d = np.sum(steps[step, node]) + 1e-3\n        v = steps[step, node, i] / d\n        if v > 0.05 and d > 0.05:\n          ax.text(step, node, sym, c=\"black\", alpha=v, verticalalignment=\"center\", horizontalalignment=\"center\")\n```\n\nAt initialization time, the untrained policy behaves like a random walk and does not do any particular action with high probability (leading to \"blurry\" output colors):\n\n\n```\nstarting_positions = [8, 14, 15, 17, 20, 25, 27, 29]\n_, ax = plt.subplots(2, 4, figsize=(40, 12))\nfor i in range(8):\n  r, c = np.unravel_index(i, (2, 4))\n  starting_position = starting_positions[i]\n\n  steps = unroll_automaton(initial_log_routing_params, test_example, initial_node_index=starting_position, rollout_steps=16)\n  ax[r, c].set_title(f\"Starting from node {starting_position}\")\n  show_automaton_steps(steps, ax[r, c])\n\n  if i == 0:\n    ax[r, c].legend(handles=legend_items, loc=\"lower right\")\n```\n\nAfter training, the automaton policy has learned to take a single sequence of actions with high probability, solving the task:\n\n\n```\nstarting_positions = [8, 14, 15, 17, 20, 25, 27, 29]\n\n_, ax = plt.subplots(2, 4, figsize=(40, 12))\nfor i in range(8):\n  r, c = np.unravel_index(i, (2, 4))\n  starting_position = starting_positions[i]\n\n  steps = unroll_automaton(trained_log_routing_params, test_example, initial_node_index=starting_position, rollout_steps=16)\n  ax[r, c].set_title(f\"Starting from node {starting_position}\")\n  show_automaton_steps(steps, ax[r, c])\n\n  if i == 0:\n    ax[r, c].legend(handles=legend_items, loc=\"lower right\")\n```\n\nSome things to notice:\n\n- When starting from node 8 or node 20 (not relevant to the task), the automaton moves to the parent node, sees that it is not a return statement, and halts without adding an edge.\n- When starting from nodes 14, 15, or 29 (return statements or return values), the automaton switches to state B (yellow), walks up the tree until reaching the function definition, and adds an edge there.\n- When starting from nodes 17, 25, or 27, it stays in state A (blue) and stops at the first while loop or for loop it finds.\n\n(Note that different random seeds or hyperparameters may result in slightly different state-changing behaviors for this example.)\n\n## Manually building the transition matrix and solving for the absorbing states\n\nThe sections above have taken care of running the automaton on the input graph automatically. However, if you want more control, you can run each of the steps individually.\n\n\n```\n# Tiny AST to make visualization easier\nthe_ast = gast.parse(\"\"\"\ndef test_function(foo):\n  if foo:\n    return\n  pass\n\"\"\")\n\ngeneric_ast = py_ast_graphs.py_ast_to_generic(the_ast)\nmdp_graph, id_conversion_map = generic_ast_graphs.ast_to_graph(generic_ast, ast_spec=py_ast_graphs.PY_AST_SPECS)\n```\n\nInstead of using `graph_bundle.convert_graph_with_edges`, which builds both the MDP environment and the extra edges at the same time, we can directly build the environment dynamics using the automaton builder object:\n\n\n```\nencoded_mdp, mdp_metadata = builder.encode_graph(mdp_graph, as_jax=False)\n\npprint(summarize_tree(encoded_mdp))\nmdp_metadata\n```\n\n    EncodedGraph(\n        initial_to_in_tagged=SparseCoordOperator(\n                                 input_indices='int32(47, 1) [3, 552] nz:1.0',\n                                 output_indices='int32(47, 2) [0, 35] nz:0.96',\n                                 values='float32(47,) 0.98 \u00b10.1 [0.5, 1.0]'),\n        initial_to_special='int32(13,) [1, 153] nz:1.0',\n        in_tagged_to_in_tagged=SparseCoordOperator(\n                                   input_indices='int32(158, 1) [0, 548] nz:0.99',\n                                   output_indices='int32(158, 2) [0, 35] nz:0.98',\n                                   values='float32(158,) 0.97 \u00b10.11 [0.5, 1.0]'),\n        in_tagged_to_special='int32(36,) [0, 152] nz:0.97',\n        in_tagged_node_indices='int32(36,) [0, 12] nz:0.97')\n\n\n\n\n\n    EncodedGraphMetadata(num_nodes=13, num_input_tagged_nodes=36)\n\n\n\nEach of the fields in the `EncodedGraph` object describe different parts of the environment dynamics. However, they are stored in a sparse form that is difficult to visualize. In particular, they are encoded as sparse operators that transform a policy into a transition matrix, by indicating which policy actions result in which state changes (see the docstring for `EncodedGraph` in `automaton_builder.py` for more details).\n\nThis `EncodedGraph` could be fed into the high-level Flax wrapper. But it's also possible to run each of the steps directly in JAX. \nTo obtain a transition matrix, we need to combine our encoded graph with some parameters. Let's use the ones from our trained model:\n\n\n```\nlearned_policy = builder.routing_softmax(trained_log_routing_params)\n```\n\n\n```\ntransition_matrix = builder.build_transition_matrix(\n    rparams=learned_policy,\n    graph=encoded_mdp,\n    metadata=mdp_metadata)\n\npprint(summarize_tree(transition_matrix))\n```\n\n    AutomatonGraphTransitionMatrix(\n        initial_to_in_tagged='float32(1, 13, 2, 36, 2) 0.012 \u00b10.087 [0.0, 1.0] nz:0.079',\n        initial_to_special='float32(1, 13, 2, 3) 0.045 \u00b10.15 [7.6e-07, 0.97]',\n        in_tagged_to_in_tagged='float32(1, 36, 2, 36, 2) 0.011 \u00b10.088 [0.0, 1.0] nz:0.099',\n        in_tagged_to_special='float32(1, 36, 2, 3) 0.063 \u00b10.23 [1e-06, 0.99]',\n        in_tagged_node_indices='int32(36,) [0, 12] nz:0.97')\n\n\nThe result is still broken up into blocks, which will be used to efficiently solve the linear system. First, we have the transitions from each possible `(initial_node, initial_state)` to each possible `(node, observation, hidden_state)` tuple (in other words, the transition matrix for the starting state). The columns here represent the different possible start nodes and start states, and the rows represent the possible `(node, observation, hidden_state)` tuples.\n\n\n\n```\nvisualization.ndarrays.ndshow(\n    # Visualize only the first variant, which is used for almost all of the nodes\n    transition_matrix.initial_to_in_tagged[0],\n    \"ccrr\", figsize=(4, 8),\n    colskips=lambda _: 0, rowskips=lambda _: 0)\n```\n\nNext, we have immediate transitions from the initial state to a halting state. Here, the columns represent the initial nodes, and each row corresponds to a special action (add edge and stop, backtrack, stop).\n\n\n```\nvisualization.ndarrays.ndshow(\n    transition_matrix.initial_to_special[0],\n    \"ccr\", figsize=(10, 1),\n    colskips=lambda _: 0, rowskips=lambda _: 0)\n```\n\nNext we have the transitions from `(node, observation, hidden_state)` to `(node, observation, hidden_state)`, which make up the majority of the transitions in any given trajectory:\n\n\n```\nvisualization.ndarrays.ndshow(\n    transition_matrix.in_tagged_to_in_tagged[0],\n    \"ccrr\", figsize=(15, 14),\n    colskips=lambda _: 0, rowskips=lambda _: 0)\n```\n\nFinally, we have transitions from intermediate states to halting states:\n\n\n```\nvisualization.ndarrays.ndshow(\n    transition_matrix.in_tagged_to_special[0],\n    \"ccr\", figsize=(20, 1),\n    colskips=lambda _: 0, rowskips=lambda _: 0)\n```\n\n*(Try adding a for or while loop to the test function and seeing how the transition matrix changes!)*\n\nWe can solve for the absorbing distribution for this transition matrix using `all_nodes_absorbing_solve`, which does the heavy lifting of constructing and solving a batch of linear systems, and also sets up the implicit differentiation machinery so that gradients can be computed efficiently.\n\n\n```\nnum_nodes = mdp_metadata.num_nodes\nabsorbing_distribution = automaton_builder.all_nodes_absorbing_solve(\n    builder=builder,\n    transition_matrix=transition_matrix,\n    variant_weights=jax.nn.one_hot(jnp.zeros([num_nodes, num_nodes]), 2 if USE_VARIANTS else 1),  # should sum to 1 across last axis if using multiple variants\n    start_machine_states=jax.nn.one_hot(jnp.zeros([num_nodes]), 2),  # should sum to 1 across last axis if using multiple states\n    steps=100,  # How long to run the solver for; determines the maximum trajectory length\n)\n\npprint(summarize_tree(absorbing_distribution))\n```\n\n    'float32(13, 13) 0.0059 \u00b10.076 [7.3e-16, 1.0]'\n\n\n\n```\nvisualization.ndarrays.ndshow(absorbing_distribution, figsize=(8, 6))\n```\n\nThis matrix of absorbing probabilities is then optionally postprocessed with adjustment parameters, and then returned as the output of the GFSA layer. In this case, the layer adds one edge with high confidence.\n\nThis is a weighted adjacency matrix, so there are also weak connections between other nodes. We can visualize this by changing the colormap:\n\n\n```\nvisualization.ndarrays.ndshow(absorbing_distribution, figsize=(8, 6), vmax=0.002)\n```\n\nAs the model trains, the loss function pushes these extra edge weights closer toward zero.\n\n## Next steps\n\nThanks for following along through this interactive demo! If you'd like to try applying the GFSA layer for a different task, or want a more in-depth discussion of how to specify the schema for new MDPs, see the notebook [\"Using the GFSA layer with new tasks\"][new-tasks-colab].\n\n[new-tasks-colab]: https://colab.research.google.com/github/google-research/google-research/blob/master/gfsa/notebooks/guide_for_new_tasks.ipynb\n", "meta": {"hexsha": "a753b48c39f45bb9712f513d71281adbf8a19da1", "size": 621002, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "gfsa/notebooks/demo_learning_static_analyses.ipynb", "max_stars_repo_name": "deepneuralmachine/google-research", "max_stars_repo_head_hexsha": "d2ce2cf0f5c004f8d78bfeddf6e88e88f4840231", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 23901, "max_stars_repo_stars_event_min_datetime": "2018-10-04T19:48:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:27:42.000Z", "max_issues_repo_path": "gfsa/notebooks/demo_learning_static_analyses.ipynb", "max_issues_repo_name": "deepneuralmachine/google-research", "max_issues_repo_head_hexsha": "d2ce2cf0f5c004f8d78bfeddf6e88e88f4840231", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 891, "max_issues_repo_issues_event_min_datetime": "2018-11-10T06:16:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T10:42:34.000Z", "max_forks_repo_path": "gfsa/notebooks/demo_learning_static_analyses.ipynb", "max_forks_repo_name": "deepneuralmachine/google-research", "max_forks_repo_head_hexsha": "d2ce2cf0f5c004f8d78bfeddf6e88e88f4840231", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6047, "max_forks_repo_forks_event_min_datetime": "2018-10-12T06:31:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:59:28.000Z", "avg_line_length": 144.9246207701, "max_line_length": 95540, "alphanum_fraction": 0.8026189932, "converted": true, "num_tokens": 43832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934934732271168, "lm_q2_score": 0.09009299274041058, "lm_q1q2_score": 0.021563699010767073}}
{"text": "## Todos \n1. Correct CDR3 kmerization. \n\n## Requirements\n\n\n```python\nfrom __future__ import unicode_literals, print_function, division\nfrom io import open\nimport unicodedata\nimport string\nimport re\nimport random\nimport pandas as pd\nimport r2python\n\nimport torch\nimport torch.nn as nn\nfrom torch import optim\nimport torch.nn.functional as F\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n```\n\n\n```python\nNULL_token = 0\nSOS_token = 1\nEOS_token = 2\n\n\nclass Lang:\n    def __init__(self, name):\n        self.name = name\n        self.word2index = {}\n        self.word2count = {}\n        self.index2word = {0: 'NULL', 1: 'SOS', 2: 'EOS'}\n        self.n_words = 2\n        \n    def addSentence(self, sentence):\n        for word in sentence.split(' '):\n            self.addWord(word)\n    \n    def addWord(self, word):\n        if word not in self.word2index:\n            self.word2index[word] = self.n_words\n            self.word2count[word] = 1\n            self.index2word[self.n_words] = word\n            self.n_words +=1\n        else:\n            self.word2count[word] += 1\n```\n\n\n```python\n# Turn a Unicode string to plain ASCII, thanks to\n# http://stackoverflow.com/a/518232/2809427\ndef unicodeToAscii(s):\n    return ''.join(\n        c for c in unicodedata.normalize('NFD', s)\n        if unicodedata.category(c) != 'Mn'\n    )\n\n# Lowercase, trim, and remove non-letter characters\n\n\ndef normalizeString(s):\n    s = unicodeToAscii(s.lower().strip())\n    s = re.sub(r\"([.!?])\", r\" \\1\", s)\n    s = re.sub(r\"[^a-zA-Z.!?]+\", r\" \", s)\n    return s\n```\n\n\n```python\ndef readLangs(lang1, lang2, reverse=False):\n    print(\"Reading lines ...\")\n    \n    # Read the file and split into lines\n    lines = open('data/%s-%s.txt' %(lang1, lang2), encoding='utf-8').\\\n        read().strip().split('\\n')\n    \n    # Split every line into pairs and normalize\n    pairs = [[normalizeString(s) for s in l.split('\\t')] for l in lines]\n    \n    # Reverse pairs, make Lang instances\n    if reverse:\n        pairs = [list(reversed(p)) for p in pairs]\n        input_lang = Lang(lang2)\n        output_lang = Lang(lang1)\n    else:\n        input_lang = Lang(lang1)\n        output_lang = Lang(lang2)\n        \n    return input_lang, output_lang, pairs\n    \n    \n```\n\n\n```python\ndef indexesFromSentence(lang, sentence):\n    indexes = [lang.word2index[word] for word in sentence.split(' ')]\n    indexes.append(EOS_token)\n    return indexes\n\ndef tensorFromSentence(lang, sentence):\n    indexes = indexesFromSentence(lang, sentence) \n    return torch.tensor(indexes, dtype=torch.long, device=device).view(-1, 1)\n\n# ## check if the view is accurate \n# def tensorFromSentences(lang, sentences):\n#     indexes_mat = [indexesFromSentence(lang, sentence) for sentence in sentences]\n#     return torch.tensor(indexes_mat, dtype=torch.long, device=device).view(-1, 1)\n\ndef tensorsFromPair(pair):\n    input_tensor = tensorFromSentence(input_lang, pair[0])\n    target_tensor_mat = tensorFromSentences(output_lang, pair[1])\n    prior_z_np = np.ones(length(target_tensor_mat))/length(target_tensor_mat)\n    prior_z =  torch.tensor(prior_z_np, dtype=torch.long, device=device)\n    return (input_tensor, target_tensor, prior_z)\n# len(pairs[0])\n# random.choice(pairs)\n\n```\n\n\n```python\ndef readInput_cdr3b(lang, langfile):\n    print(\"Reading %s ...\" %(lang))\n    \n    # Read the file and split into lines\n    df = pd.read_csv(langfile, \"\\t\")\n\n    df = df[['kmer.sentence', 'patient']]\n    input_lang = Lang(lang)\n    \n    print(\"Counting words...\")\n    for kmerS in df['kmer.sentence']:\n        input_lang.addSentence(kmerS)\n        \n    df['kmer.tensor'] = df['kmer.sentence'].apply(lambda x: tensorFromSentence(input_lang, x))\n    \n    return input_lang, df\n\ndef readInput_epitope(lang, langfile, nfold=None):\n    \"\"\"The module reads CDR3 and Epitopes of and create lists for each tcga patients\n    output are\n    cdr3s_list: list of cdr3 per common patient,\n    neoantigens_list: list of Epitope per common patient,\n    negative_patients: For each patient list of other patients that does not share any neoantigen with the patient\n\n    approx schematic of the function\n\n\n    # read files\n    # find common paitents\n    # convert to tensor\n    # create list\n    \"\"\"\n    def create_neoantigen_list_from_patient_list(patients_lists, nfold=None):\n        \"\"\"\n        Ouput neoantigen for patients list\n        \"\"\"\n        \n        df_common = df[df['patient'].isin(patients_lists)]\n        neoantigens_list = []\n        for patient_inx, patient in zip(range(len(patients_lists)), patients_lists):\n            neoantigen_curr = df_common[df_common['patient'] == patient]['kmer.tensor']\n            neoantigens_list.append(neoantigen_curr)\n\n        neoantigens_list = [neoantigen.values.tolist() for neoantigen in neoantigens_list]\n        return neoantigens_list\n    \n    df = pd.read_csv(langfile, \"\\t\")\n    \n    input_lang = Lang(lang)\n    print(\"Counting words...\")\n    for kmerS in df['kmer.sentence']:\n        input_lang.addSentence(kmerS)\n        \n    df['kmer.tensor'] = df['kmer.sentence'].apply(lambda x: tensorFromSentence(input_lang, x))\n    common_patients = r2python.unique(df['patient'])\n    if nfold is None:\n        train_patients_list = common_patients\n        trainData = create_neoantigen_list_from_patient_list(train_patients_list)\n        testData = None\n    else:\n        ### this is not working\n        train_patients_list = r2python.sample(common_patients, size=int((nfold - 1) * len(common_patients) / nfold))\n        test_patients_list = r2python.setdiff(common_patients, train_patients_list)\n        trainData = create_neoantigen_list_from_patient_list(train_patients_list)\n        testData = create_neoantigen_list_from_patient_list(test_patients_list)\n\n    dataset = {\n        \"trainData\": trainData,\n        \"testData\": testData\n    }\n    return input_lang, dataset, df\n```\n\n\n```python\nMAX_LENGTH = 30\n\n```\n\n\n```python\n# def format2tensorList(List):\n#     # assumes that indices are in sorted order\n#     tensorList = []\n#     total_indices = int(List[len(List)-1][1])\n#     initial_index = 1\n#     for inx in range(total_indices):\n#         tensorList_set = []\n#         curr\n        \ndef prepareData(cdr3b, cdr3bfile, epitope, epitopefile):\n    cdr3b_lang,  df_cdr3 = readInput_cdr3b(cdr3b, cdr3bfile)\n    print(\"Read %s cdr3bs \" % len(df_cdr3.index))\n\n\n    epitope_lang,  epitope_patient_list, df_epitope = readInput_epitope(epitope, epitopefile)\n    print(\"Read %s epitope \" % len(epitope_patient_list))\n    \n    \n    # epitope NULL sentence\n    epitope_lang.addSentence('NULL')\n    epitopee_null = tensorFromSentence(epitope_lang, 'NULL')\n\n    \n        \n#     for pair in epitope_n_index:\n#         epitope_lang.addSentence(pair[0])  \n        \n#     epitope_matList = format2ListofList(epitope_lang, epitope_n_index)\n#         epitope_mat_lens.addLens(pair[1])\n    \n#     convert epitope to list of matrices for fast indexing \n  \n    print(\"Counted words:\")\n    print(cdr3b_lang.name, cdr3b_lang.n_words)\n    print(epitope_lang.name, epitope_lang.n_words)\n    return cdr3b_lang, epitope_lang, df_cdr3, epitope_patient_list, epitopee_null, df_epitope\n\ncdr3b_lang, epitope_lang, df_cdr3, epitope_patient_list, epitope_null, df_epitope = prepareData('cdr3b', 'data/tcga_extended_tcr_final_200.txt','eptiope', 'data/all.9mers_200.txt')\n# print(random.choice(pairs))\n```\n\n    Reading cdr3b ...\n    Counting words...\n    Read 999 cdr3bs \n    Counting words...\n    Read 2 epitope \n    Counted words:\n    cdr3b 3062\n    eptiope 5168\n\n\n\n```python\n# print([random.choice(pairs) for i in range(10)])\n# pairs[1:10]\n```\n\n## Encoder\n\n\n```python\nclass EncoderRNN(nn.Module):\n    def __init__(self, input_size, hidden_size):\n        super(EncoderRNN, self).__init__()\n        self.hidden_size = hidden_size\n        \n        self.embedding = nn.Embedding(input_size, hidden_size)\n        self.gru = nn.GRU(hidden_size, hidden_size)\n        \n    def forward(self, input, hidden):\n        embedded = self.embedding(input).view(1,1,-1)\n        output = embedded\n        output, hidden = self.gru(output, hidden)\n        return output, hidden\n        \n    def initHidden(self):\n        return torch.zeros(1,1, self.hidden_size, device=device)\n    \n```\n\n## Decoder\n\n\n```python\nclass DecoderRNN(nn.Module):\n    def __init__(self,  hidden_size, output_size):\n        super(DecoderRNN, self).__init__()\n        self.hidden_size = hidden_size\n        \n        self.embedding = nn.Embedding(output_size, hidden_size)\n        self.gru = nn.GRU(hidden_size, hidden_size)\n        self.out = nn.Linear(hidden_size, output_size)\n        self.softmax = nn.Softmax(dim=1)\n        \n    def forward(self, input, hidden):\n        output = self.embedding(input).view(1,1,-1)\n        output = F.relu(output)\n        output, hidden = self.gru(output, hidden)\n        output = self.softmax(output)\n        return output, hidden\n    \n    def initHidden(self):\n        return torch.zeros(1, 1, self.hidden_size, device=device)\n```\n\n## Attention Decoder\n\n\n```python\nclass AttnDecoderRNN(nn.Module):\n    def __init__(self,  hidden_size, output_size, dropout_p =0.1, max_length = MAX_LENGTH):\n        super(AttnDecoderRNN, self).__init__()\n        self.hidden_size = hidden_size\n        self.output_size = output_size\n        self.dropout_p = dropout_p\n        self.max_length = max_length\n        \n        self.embedding = nn.Embedding(self.output_size, self.hidden_size)\n        self.attn = nn.Linear(self.hidden_size * 2, self.max_length)\n        self.attn_combine = nn.Linear(self.hidden_size * 2, self.hidden_size)\n        self.dropout = nn.Dropout(self.dropout_p)\n        self.gru = nn.GRU(hidden_size, hidden_size)\n        self.out = nn.Linear(hidden_size, output_size)\n#         self.softmax = nn.Softmax(dim=1)\n        \n    def forward(self, input, hidden, encoder_outputs):\n        embedded = self.embedding(input).view(1, 1, -1)\n        embedded = self.dropout(embedded)\n        \n#         attn_weights = self.attn(torch.cat((embedded[0], hidden[0]), 1))\n#         attn_weights = F.softmax(attn_weights, dim=1)\n        attn_weights = F.softmax(\n            self.attn(torch.cat((embedded[0], hidden[0]), 1)), dim=1)\n        attn_applied = torch.bmm(attn_weights.unsqueeze(0),\n                                encoder_outputs.unsqueeze(0))\n        \n        output = torch.cat((embedded[0], attn_applied[0]), 1)\n        output = self.attn_combine(output).unsqueeze(0)\n        \n        output= F.relu(output)\n        output, hidden = self.gru(output, hidden)\n        \n        output = F.log_softmax(self.out(output[0]), dim=1)\n        return output, hidden, attn_weights\n    \n    def initHidden(self):\n        return torch.zeros(1, 1, self.hidden_size, device=device)\n```\n\n## Training \n\n## Training the model\nIn this model, we are generating Epitope (X) from the CDR3b (Y). This weird convention is for traditional reason. \nSo the input is CDR3B and output are Antigens. \n\n\\begin{align}\nlog P(X/Y) &= \\sum_{x} log P(x/Y) \\\\ \n            &= \\sum_{x} log \\sum_z P(x,z/Y) \\\\ \n            &= \\sum_{x} log \\sum_z P(z/Y) P(x/z,Y) \\\\\n            &= \\sum_{x} log \\mathbf{E}_z  P(x/z,Y) \n\\end{align}\n\n\n### TODO : Add prior proportial to expression, mhc1 presentation, clonality of mutation \n### TODO : Add prior proportial to its clonality of CDR3  \n\n\n```python\nteacher_forcing_ratio = 0.5\n\n\ndef train_set(input_tensor_list, target_tensor, input_null, prior_z, encoder, decoder, encoder_optimizer,\n              decoder_optimizer, criterion, max_length=MAX_LENGTH):\n    ''' The function inputs cdr3bs and antigens of a set (patient) and for probability of each cdr3b generated by\n    each antigens. And  also calculate the loss'''\n    encoder_hidden = encoder.initHidden()\n\n    loss = 0\n\n    encoder_optimizer.zero_grad()\n    decoder_optimizer.zero_grad()\n#     print(len(input_tensor_list))\n\n    inputs_num = len(input_tensor_list)\n    for input_inx in range(inputs_num + 1):\n#         print(len(input_tensor_list))\n#         print(\"inx:\")\n#         print(input_inx)\n        if input_inx > 0:\n            prior_z_curr = prior_z[1]\n            input_tensor = input_tensor_list[input_inx-1]\n        else:\n            prior_z_curr = prior_z[0]\n            input_tensor = input_null\n\n        input_length = input_tensor.size(0)\n        target_length = target_tensor.size(0)\n    #     print(target_length)\n        encoder_outputs = torch.zeros(max_length, encoder.hidden_size,\n                                      device=device)\n\n        for ei in range(input_length):\n            encoder_output, encoder_hidden = encoder(\n                input_tensor[ei], encoder_hidden)\n\n            encoder_outputs[ei] = encoder_output[0, 0]\n\n        decoder_input = torch.tensor([[SOS_token]], device=device)\n\n        decoder_hidden = encoder_hidden\n\n        use_teacher_forcing = True if random.random() < teacher_forcing_ratio else False\n\n        if use_teacher_forcing:\n            for di in range(target_length):\n                decoder_output, decoder_hidden, decoder_attention = decoder(\n                    decoder_input, decoder_hidden, encoder_outputs)\n                loss += prior_z_curr * criterion(decoder_output, target_tensor[di])\n                decoder_input = target_tensor[di]  # Teacher forcing\n\n        else:\n            # Without teacher forcing: use its own predictions as the next input\n            for di in range(target_length):\n                decoder_output, decoder_hidden, decoder_attention = decoder(\n                    decoder_input, decoder_hidden, encoder_outputs)\n                topv, topi = decoder_output.topk(1)\n                decoder_input = topi.squeeze().detach()  # detach from history as input\n\n                loss += prior_z_curr * criterion(decoder_output, target_tensor[di])\n                if decoder_input.item() == EOS_token:\n                    break\n\n    loss.backward()\n\n    encoder_optimizer.step()\n    decoder_optimizer.step()\n\n    return loss.item() / target_length\n\n```\n\n\n```python\nimport time\nimport math\n\n\ndef asMinutes(s):\n    m = math.floor(s / 60)\n    s -= m * 60\n    return '%dm %ds' % (m, s)\n\n\ndef timeSince(since, percent):\n    now = time.time()\n    s = now - since\n    es = s / (percent)\n    rs = es - s\n    return '%s (- %s)' % (asMinutes(s), asMinutes(rs))\n```\n\n\n```python\ndef trainIters(encoder, decoder, n_iters, total_patients, print_every=1000, plot_every=100, learning_rate=0.01):\n    start = time.time()\n    plot_losses = []\n    print_loss_total = 0  # Reset every print_every\n    plot_loss_total = 0  # Reset every plot_every\n\n    encoder_optimizer = optim.SGD(encoder.parameters(), lr=learning_rate)\n    decoder_optimizer = optim.SGD(decoder.parameters(), lr=learning_rate)\n    training_inx = r2python.sample_int(total_patients, size=n_iters, replace=True)\n#     training_pairs = [tensorsFromPair(random.choice(pairs))\n#                       for i in range(n_iters)]\n    criterion = nn.NLLLoss()\n\n    for iter in range(1, n_iters + 1):\n        inx_curr = training_inx[iter -1]\n        input_tensor_list = epitope_patient_list['trainData'][inx_curr]\n#         print(len(input_tensor_list))\n#         print(input_tensor_list[0])\n        target_tensor = df_cdr3['kmer.tensor'][inx_curr]\n        prior_z = [0.5, 0.5/len(input_tensor_list)]  # prior of NULL distribution, uniform prior \n\n        loss = train_set(input_tensor_list, target_tensor, epitope_null, prior_z, encoder,\n                     decoder, encoder_optimizer, decoder_optimizer, criterion)\n        print_loss_total += loss\n        plot_loss_total += loss\n\n        if iter % print_every == 0:\n            print_loss_avg = print_loss_total / print_every\n            print_loss_total = 0\n            print('%s (%d %d%%) %.4f' % (timeSince(start, iter / n_iters),\n                                         iter, iter / n_iters * 100, print_loss_avg))\n\n        if iter % plot_every == 0:\n            plot_loss_avg = plot_loss_total / plot_every\n            plot_losses.append(plot_loss_avg)\n            plot_loss_total = 0\n\n    showPlot(plot_losses)\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nplt.switch_backend('agg')\nimport matplotlib.ticker as ticker\nimport numpy as np\n\n\ndef showPlot(points):\n    plt.figure()\n    fig, ax = plt.subplots()\n    # this locator puts ticks at regular intervals\n    loc = ticker.MultipleLocator(base=0.2)\n    ax.yaxis.set_major_locator(loc)\n    plt.plot(points)\n```\n\n## Evaluation\n\n\n```python\ndef evaluate(encoder, decoder, sentence, max_length=MAX_LENGTH):\n    with torch.no_grad():\n#         print(sentence)\n        input_tensor = tensorFromSentence(cdr3b_lang, sentence)\n        input_length = input_tensor.size()[0]\n        encoder_hidden = encoder.initHidden()\n\n        encoder_outputs = torch.zeros(max_length, encoder.hidden_size, device=device)\n\n        for ei in range(input_length):\n            encoder_output, encoder_hidden = encoder(input_tensor[ei],\n                                                     encoder_hidden)\n            encoder_outputs[ei] += encoder_output[0, 0]\n\n        decoder_input = torch.tensor([[SOS_token]], device=device)  # SOS\n\n        decoder_hidden = encoder_hidden\n\n        decoded_words = []\n        decoder_attentions = torch.zeros(max_length, max_length)\n\n        for di in range(max_length):\n            decoder_output, decoder_hidden, decoder_attention = decoder(\n                decoder_input, decoder_hidden, encoder_outputs)\n            decoder_attentions[di] = decoder_attention.data\n            topv, topi = decoder_output.data.topk(1)\n            if topi.item() == EOS_token:\n                decoded_words.append('<EOS>')\n                break\n            else:\n                decoded_words.append(epitope_lang.index2word[topi.item()])\n\n            decoder_input = topi.squeeze().detach()\n\n        return decoded_words, decoder_attentions[:di + 1]\n```\n\n\n```python\ndef evaluateRandomly(encoder, decoder, total_patients = 3, n=10, ):\n    for i in range(n):\n#         pair = random.choice(pairs)\n        \n        training_inx = r2python.sample_int(total_patients, size=1, replace=True)\n#         print(training_inx)\n#         print(type(training_inx))\n\n        inx_curr = training_inx[0]\n        epitope_curr = df_epitope['kmer.sentence'][inx_curr]\n        cdr3b_curr = df_cdr3['kmer.sentence'][inx_curr]\n        \n        print('>', cdr3b_curr)\n        print('=', epitope_curr)\n        output_words, attentions = evaluate(encoder, decoder, cdr3b_curr)\n        output_sentence = ' '.join(output_words)\n        print('<', output_sentence)\n        print('')\n```\n\n## TRAINING AND EVALUATING\n\n\n```python\nhidden_size = 256\nencoder1 = EncoderRNN(epitope_lang.n_words, hidden_size).to(device)\nattn_decoder1 = AttnDecoderRNN(hidden_size, cdr3b_lang.n_words, dropout_p=0.1).to(device)\ntotal_patients = 3\ntrainIters(encoder1, attn_decoder1, n_iters=4, total_patients=total_patients, print_every=1)\n```\n\n\n```python\nevaluateRandomly(encoder1, attn_decoder1)\n```\n\n    > ^^^^C ^^^CS ^^CSA ^CSAE CSAEQ SAEQG AEQGA EQGAV QGAVT GAVTG AVTGE VTGEL TGELF\n    = ^^^^Y ^^^YS ^^YST ^YSTK YSTKH STKHS TKHSK KHSKL HSKLY SKLY$ KLY$$ LY$$$ Y$$$$\n    < <EOS>\n    \n    > ^^^^C ^^^CA ^^CAS ^CASS CASSL ASSLF SSLFP SLFPL LFPLA FPLAD PLADE LADEQ ADEQF\n    = ^^^^S ^^^ST ^^STK ^STKH STKHS TKHSK KHSKL HSKLY SKLYI KLYI$ LYI$$ YI$$$ I$$$$\n    < <EOS>\n    \n    > ^^^^C ^^^CA ^^CAS ^CASS CASST ASSTD SSTDR STDRA TDRAY DRAYE RAYEQ AYEQY YEQYF\n    = ^^^^L ^^^LY ^^LYS ^LYST LYSTK YSTKH STKHS TKHSK KHSKL HSKL$ SKL$$ KL$$$ L$$$$\n    < <EOS>\n    \n    > ^^^^C ^^^CA ^^CAS ^CASS CASST ASSTD SSTDR STDRA TDRAY DRAYE RAYEQ AYEQY YEQYF\n    = ^^^^L ^^^LY ^^LYS ^LYST LYSTK YSTKH STKHS TKHSK KHSKL HSKL$ SKL$$ KL$$$ L$$$$\n    < <EOS>\n    \n    > ^^^^C ^^^CA ^^CAS ^CASS CASST ASSTD SSTDR STDRA TDRAY DRAYE RAYEQ AYEQY YEQYF\n    = ^^^^L ^^^LY ^^LYS ^LYST LYSTK YSTKH STKHS TKHSK KHSKL HSKL$ SKL$$ KL$$$ L$$$$\n    < <EOS>\n    \n    > ^^^^C ^^^CA ^^CAS ^CASS CASSL ASSLF SSLFP SLFPL LFPLA FPLAD PLADE LADEQ ADEQF\n    = ^^^^S ^^^ST ^^STK ^STKH STKHS TKHSK KHSKL HSKLY SKLYI KLYI$ LYI$$ YI$$$ I$$$$\n    < <EOS>\n    \n    > ^^^^C ^^^CA ^^CAS ^CASS CASST ASSTD SSTDR STDRA TDRAY DRAYE RAYEQ AYEQY YEQYF\n    = ^^^^L ^^^LY ^^LYS ^LYST LYSTK YSTKH STKHS TKHSK KHSKL HSKL$ SKL$$ KL$$$ L$$$$\n    < <EOS>\n    \n    > ^^^^C ^^^CA ^^CAS ^CASS CASST ASSTD SSTDR STDRA TDRAY DRAYE RAYEQ AYEQY YEQYF\n    = ^^^^L ^^^LY ^^LYS ^LYST LYSTK YSTKH STKHS TKHSK KHSKL HSKL$ SKL$$ KL$$$ L$$$$\n    < <EOS>\n    \n    > ^^^^C ^^^CS ^^CSA ^CSAE CSAEQ SAEQG AEQGA EQGAV QGAVT GAVTG AVTGE VTGEL TGELF\n    = ^^^^Y ^^^YS ^^YST ^YSTK YSTKH STKHS TKHSK KHSKL HSKLY SKLY$ KLY$$ LY$$$ Y$$$$\n    < <EOS>\n    \n    > ^^^^C ^^^CA ^^CAS ^CASS CASSL ASSLF SSLFP SLFPL LFPLA FPLAD PLADE LADEQ ADEQF\n    = ^^^^S ^^^ST ^^STK ^STKH STKHS TKHSK KHSKL HSKLY SKLYI KLYI$ LYI$$ YI$$$ I$$$$\n    < <EOS>\n    \n\n\n\n```python\n%matplotlib inline\noutput_words, attentions = evaluate(\n    encoder1, attn_decoder1, \"^^^^C ^^^CA ^^CAS ^CASS CASSL ASSLF SSLFP SLFPL LFPLA FPLAD PLADE LADEQ ADEQF\")\nplt.matshow(attentions.numpy())\n```\n\n\n```python\ndef showAttention(input_sentence, output_words, attentions):\n    # Set up figure with colorbar\n    fig = plt.figure()\n    ax = fig.add_subplot(111)\n    cax = ax.matshow(attentions.numpy(), cmap='bone')\n    fig.colorbar(cax)\n\n    # Set up axes\n    ax.set_xticklabels([''] + input_sentence.split(' ') +\n                       ['<EOS>'], rotation=90)\n    ax.set_yticklabels([''] + output_words)\n\n    # Show label at every tick\n    ax.xaxis.set_major_locator(ticker.MultipleLocator(1))\n    ax.yaxis.set_major_locator(ticker.MultipleLocator(1))\n\n    plt.show()\n\n\ndef evaluateAndShowAttention(input_sentence):\n    output_words, attentions = evaluate(\n        encoder1, attn_decoder1, input_sentence)\n    print('input =', input_sentence)\n    print('output =', ' '.join(output_words))\n    showAttention(input_sentence, output_words, attentions)\n\n\nevaluateAndShowAttention(\"^^^^C ^^^CS ^^CSA ^CSAE CSAEQ SAEQG AEQGA EQGAV QGAVT GAVTG AVTGE VTGEL TGELF\")\n\n# evaluateAndShowAttention(\"elle est trop petit .\")\n\n# evaluateAndShowAttention(\"je ne crains pas de mourir .\")\n\n# evaluateAndShowAttention(\"c est un jeune directeur plein de talent .\")\n\n```\n\nWe will create a kmer from CDR3 and antigen, with stride =1. The line will end with \".\".\n", "meta": {"hexsha": "a8bf0a123e4d06ca5d7b90e140b46f6d9e96f3e0", "size": 52625, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "antigen2cdr3b.ipynb", "max_stars_repo_name": "vinash85/CDR2epitope", "max_stars_repo_head_hexsha": "70dd52f32dfc5bd7530c6763d262a4c9cc1eafc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "antigen2cdr3b.ipynb", "max_issues_repo_name": "vinash85/CDR2epitope", "max_issues_repo_head_hexsha": "70dd52f32dfc5bd7530c6763d262a4c9cc1eafc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "antigen2cdr3b.ipynb", "max_forks_repo_name": "vinash85/CDR2epitope", "max_forks_repo_head_hexsha": "70dd52f32dfc5bd7530c6763d262a4c9cc1eafc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.1034115139, "max_line_length": 13124, "alphanum_fraction": 0.6926935867, "converted": true, "num_tokens": 5980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116407397951, "lm_q2_score": 0.053403327916637336, "lm_q1q2_score": 0.021351272155316077}}
{"text": "# Satellite-image-based surface reconstruction in `MicMac`\n> A tutorial\n\n- toc: true \n- badges: true\n- comments: true\n- categories: [jupyter] \n- image: images/chart-preview.png\n\n## Goal \n\nIn this tutorial we will introduce you to satellite image processing in MicMac. The goal of the exercise is to compute the surface and generate an orthohoto given a set of *modern* satellite images and their RPC geolocalisations. After setting-up MicMac and downloading the dataset, the pipeline is as follows:\n  1. Tie-points extraction\n  2. RPC-bundle adjustement\n  3. Surface computation\n    \n    3.1. ***Method1***: Matching in object geometry\n\n    3.3. ***Method2***: Matching in image geometry and fusion\n\n\n<!--When you're done, find the next tutorial here: \n[02_satellite_epipolaire.ipynb](https://github.com/micmacIGN/Documentation/blob/master/TutoJupyter/02_satellite_epipolaire.ipynb) -->\n\n<br>\n\n*Contact: ewelina.rupnik(at)ign.fr*\n\n## Projet set-up\n\n### Download and compile MicMac & dependencies\n\n\n```\nimport os\nfrom os.path import exists, join, basename, splitext\nimport numpy as np \nimport cv2\nimport matplotlib.pyplot as plt   \n\nDependencies_install = True\nMicMac_clone = True\nMicMac_cmake = True \nMicMac_build = True\n\nYOUR_PATH = '/content/'\n!cd $YOUR_PATH\n!pwd\n\n\nif Dependencies_install:\n  !apt update\n  !apt install -y cmake\n  !pip install dlib\n  !apt-get install imagemagick proj-bin exiv2\n  !pip install wget gdown\n\nif MicMac_clone:\n  if not exists(YOUR_PATH+'micmac/'):\n    git_repo_url = 'https://github.com/micmacIGN/micmac.git'\n    !git clone $git_repo_url\n\nif MicMac_cmake:\n  !cd micmac\n  if not exists(YOUR_PATH+'micmac/build'):\n    !mkdir $YOUR_PATH\"micmac/build\"\n\n  !cd $YOUR_PATH\"micmac/build\"\n  !cmake $YOUR_PATH\"micmac\" -DBUILD_POISSON=OFF\n\n  if MicMac_build:\n    !make install -j28\n\n\n```\n\n### Add environmental variable & download the dataset\n\nThe dataset consists of: \n  * 4 images (tif)\n  * 4 corresponding RPCs (xml)\n  * `WGS84toUTM.xml` with the definition of a projection coordinate system (*proj4* format)\n\n\n```\nimport os\nos.environ['PATH'] += \":/content/micmac/bin/\"\n!echo $PATH\n\n# if you can see the commands printed to the screen, everything is OK\n!mm3d\n```\n\n\n```\n# download data\ndataset_url = 'https://drive.google.com/uc?id=18hmQL5kIqhcnR5ahp8IUsMZxLv7jvjgB' \n!gdown $dataset_url -O \"satellite_data.tar.gz\" \n\n# unpack\nif not exists(YOUR_PATH+'satellite_data'):\n  !mkdir $YOUR_PATH'satellite_data'\n!tar -xf satellite_data.tar.gz -C $YOUR_PATH'satellite_data'\n%cd $YOUR_PATH'satellite_data'\n\n# utility functions to visualise tie-points\nutils_url='https://drive.google.com/uc?id=1ATO1Nz_aXApxVnm6l7x1xappGXtcjuvp'\n!gdown $utils_url -O \"mm3d_utils.py\"   \n```\n\n## 1. Extract SIFT tie-points\n\n  - **computation strategy**: there exist several predefined *strategies* to compute tie-points: `Line`, `All`, `MulScale`, `File`. We will use the `All` strategy where tie-points are searched between all possible pairs. Refer to MicMac documentation for the other modes. \n  - **image resolution**: tie-points extraction is very costly, and to limit the computation time we usually downsampled the images; in this example, indicate resolution of `-1` which means full-resolution images; otherwise, if set to, e.g., `2000`, the images will be downsampled such that the larger image dimension (typically the width) will have `2000` pixels; the other dimension will have a size that is proportionally smaller;\n  - **ExpTxt=1**: the extracted tie-points will be saved in a text format (as opossed to the default dat format)\n  - **results**: tie-points are stored in the `Homol` directory. For instance, tie-points correponding to image `Im1.tif` will be stored in `Homol/PastisIm1.tif/` directory. If `Im1.tif` overlaps with `Im2.tif` and `Im3.tif`, their tie-points will be stored in `Homol/PastisIm1.tif/Im2.tif.dat` and `Homol/PastisIm1.tif/Im3.tif.dat`, respectively. If you chose to export in the text format, the `dat` extension will be replaced with `txt`.\n\n\n*Note: Intermediary results are stored in the `Pastis` directory. It takesa  significant amount of space and is not used at later processing stages, therefore you may delete it.*\n\n\n```\n!mm3d Tapioca All .*tif -1 ExpTxt=1 @ExitOnBrkp\n```\n\n### Visualise tie-points\n\nRead any pair of images and visalise their tie-points.\n\n\n```\nimport mm3d_utils \n\naIm1 = cv2.imread('TPMM_0435.tif',cv2.IMREAD_IGNORE_ORIENTATION)\naIm2 = cv2.imread('TPMM_0566.tif',cv2.IMREAD_IGNORE_ORIENTATION) \n \nTPtsVec = mm3d_utils.ImportHom(\"Homol/PastisTPMM_0435.tif/TPMM_0566.tif.txt\") \n \nmm3d_utils.plot_images([np.asarray(aIm1),np.asarray(aIm2)]) \nmm3d_utils.plot_tiepts2(np.asarray(TPtsVec,dtype=float))\n```\n\n## 2. RPC-bundle adjustment\n\n### Read the RPCs in DIMAP format\n\nThis function reads the DIMAP format RPCs and converts it to a *MicMac* format. Several parameters are specified here:\n\n  - `(.*).tif` this is the pattern of input images (note the dot preceding the star which is the posix convention)\n\n  - `\\$1.xml` is the corresponding pattern of RPC files; I use here a regular expression that associates the image name with its corresponding RPC file name; you may also run the command independently for each image if you're not familiar with regular expressions;\n\n  - `RPC-d0` is the directory name where the converted files will be stored; it will serve as input in the following step, i.e., the bundle adjustment;\n\n  - `Degre=0`, the degree of the polynomial correction;\n\n  By choosing a zero-degree polynomial we will correct the satellite's geolocalisation by modelling a 3D image shift; please refer to [Rupnik et al., 2016] for more on the method.\n\n  - `ChSys=WGS84toUTM.xml` definition of the projection coordinate sytem; MicMac expects that the processing coordinate frame is euclidean and all three coordinates have the same unit. The RPCs are expressed in geographical coordinates which are neither euclidean, nor unique in terms of units. To overcome that, MicMac will transfer, on the fly, the RPCs to a user-defined coordinate system, in this exemple defined in the `WGS84toUTM.xml` file. The definition of the coordinate system follows the `proj4` library convention. You can retrieve the code corresponding to the coordinate frame of your interest from `https://spatialreference.org/`\n\n\n\n<sub> Rupnik, E., Deseilligny, M.P., Delorme, A. and Klinger, Y., 2016. Refined satellite image orientation in the free open-source photogrammetric tools Apero/Micmac. ISPRS Annals of the Photogrammetry, Remote Sensing and Spatial Information Sciences, 3, p.83.<sub>\n\n\n```\n!mm3d Convert2GenBundle -help @ExitOnBrkp\n!mm3d Convert2GenBundle \"(.*).tif\" \"\\$1.xml\" RPC-d0 ChSys=WGS84toUTM.xml Degre=0  @ExitOnBrkp\n```\n\n    *****************************\n    *  Help for Elise Arg main  *\n    *****************************\n    Mandatory unnamed args : \n      * string :: {Name of Image}\n      * string :: {Name of input Orientation File}\n      * string :: {Directory of output Orientation (MyDir -> Oi-MyDir)}\n    Named args : \n      * [Name=ChSys] string :: {Change coordinate file (MicMac XML convention)}\n      * [Name=Degre] INT :: {Degre of polynomial correction (Def=2)}\n      * [Name=Type] string :: {Type of sensor (see eTypeImporGenBundle)}\n      * [Name=PertubAng] REAL :: {Type of sensor (see eTypeImporGenBundle)}\n    \"(.*).tif\": 4 matches.\n\n\n### Run the adjustment\n\nWithin the bundle adjustemnt, MicMac will estimate the parameters of $D_x$ and $D_y$ functions, that are the polynomials you have defined in `Convert2GenBundle` method. In this example our observations are the tie-points. It is also possible to include ground control points.\n\n\n$\\begin{equation}\n\\begin{split}\ny = g (\\phi, \\lambda, h) +  {D_y (x,y)}\\\\\nx = h (\\phi, \\lambda, h) +  {D_x (x,y)}\n\\end{split}\n\\end{equation}$\n\nwhere $g$ and $h$ are the RPC functions, and \n\n$\\begin{equation}\n\\begin{split}\nD_y (x,y) = \\sum_{i=0}^m \\sum_{j=0}^n a_{ij} \\cdot x^i y^j \\\\\nD_x (x,y) = \\sum_{i=0}^m \\sum_{j=0}^n b_{ij} \\cdot x^i y^j\n\\end{split}\n\\end{equation}$\n\n\nThe input parameters:\n- `RPC-d0` is the folder with the initial geolocalisation\n- `RPC-d0_adj` is the folder where the adjusted geoloc is saved\n- `ExpTxt=1` indicates that tie-points are stored in text format \n\n\n```\n!mm3d Campari \".*tif\" RPC-d0 RPC-d0-adj ExpTxt=1 @ExitOnBrkp\n```\n\n### Interpreting the results\n\nOne way to asses the quality of the adjustment is to look at the tie-points residual (for more sophisticated quality estimates see `MMTestOrient` in MicMac documentation). \n\nThe bundle adjustment is carried out in several iterations. Let's look at image `TPMM_0435.tif` in the last iteration:\n\n> `RES:[TPMM_0435.tif][g] ER2 0.24636 Nn 100 Of 11753 Mul 5171 Mul-NN 5171 Time 1.15821`\n\n* `0.24636` pixels is the mean residual calculated over all tie-points (i.e., $\\sigma$ of the bundle)  \n\n* `Nn 100` means that 100$\\%$ of tie-points were considered as inliers\n\n* `11753` there were as many tie-points found\n\n* `5171` there were as many multiple tie-points found (out of the `11753`), i.e., tie-points observed in at least 3 images;\n\n## 3. Surface reconstruction\n\nWe will now calculate the surface with the semi-global dense image matching [Deseilligny \\& Paparoditis, 2006]. \n\n\n\n <sub> Deseilligny, M. and Paparoditis, N., 2006. A multiresolution and optimization-based image matching approach: An application to surface reconstruction from SPOT5-HRS stereo imagery. Archives of Photogrammetry, Remote Sensing and Spatial Information Sciences, 36(1/W41), pp.1-5.\n\n### ***Method1***: Matching in object geometry\n\nThe computation will be carried out in the so-called terrain geometry, where the optimization is defined in the `(X,Y)` of the object space, and we are looking for the most optimal `Z`-coordinates (see Figure below). This geometry is well adapted to 2.5D surface computation.\n\n<center>\n  \n  <br> \n</center>\n \n\n\n<center>\nFigure. Matching in object geometry. \n  <br> \n</center>\n\n The input parameters are:\n  - `UrbanMNE` is a predefined term and it defines a number of processing parameters (e.g., low regularization, small matching wodows, terrain geometry)\n\n  - `.*tif` is the image set that will be used in the processing\n\n  - `RPC-d0-adj` is the name of the directory containing the geoloclisation\n\n  - `SzW=2` defines the matching window size, i.e., with size set to 2, the window size is ```5x5```\n\n  - `Regul` is the regularization term $\\alpha$; in `UrbanMNE` it is by default set to `0.02` becase in urban zones we're typically interested in reconstructing fine details; the dataset used in this example, however, represents a smooth surface so we're just fine with a more agressive regularization; moreover, our images are quite noisy and by adding more regularization we will avoid noisy surface reconstructions;\n\n  - `DoOrtho=1`, this parameters wil force MicMac to create individual orthomosaic, i.e., rectify each image; the rectified images are stored in `Ortho-MEC-Malt/Ort_*.tif`; to create the final orthophotomap we will still need to do mosaicing with `Tawny` (later in this tutorial);\n\n  - `NbVI=2` sets the necessary minimum number of images for MicMac to compute the surface; by default the value is set to 3 which means that in areas with only two overlapping images, the surface will not be computed; \n\n  - `EZA=1`, this parameter will force the output surface raster to save the Z-coordinates in their absolute values; without explicitly forcing MicMac to do that, to avoid having to store large values inside the raster tiff, it will apply a normalisation (normalisation parameters `OrigineAlti` and `ResolutionAlti` are to be found in the accompanying xml files);\n\n\n```\n!mm3d Malt UrbanMNE \".*tif\" RPC-d0-adj SzW=2 Regul=0.2 DoOrtho=1 NbVI=2 EZA=1 @ExitOnBrkp\n```\n\n#### Reading the output files\n\nThe matching is carried out at multi-resolutions, i.e., we first calculate the surface using low resolution images (top-most level of the image pyramid), then we propagate the solution to lower levels and refine it, so long we have not reached the bottom of the image pyramid. The surface reconstructions at each level are stored inside the `MEC-Malt` directory. Here's how to decipher the files:\n\n- `MEC-Malt/Z_Num8_DeZoom1_STD-MALT.tif` represents the surface raster at the highest resolution; \n- `MEC-Malt/Z_Num8_DeZoom1_STD-MALT.xml` is its metadata file that encodes the georeferencing; let's assume you'd like to convert a pixel $(i,j)$ from its image coordinates to its georeferenced coordinates (i.e., object coordinates):\n\n\n> `Z-coordinate normalised` : $Z^{img}_{i,j} = Z\\_Num\\_File^{img}(i,j)$, \n\n> `Z-coordinate` : $Z^{obj}_{i,j} = OrigineAlti + ResolutionAlti \\cdot Z^{img}_{i,j}$\n\n> `XY-coordinates` : $(X,Y) = OriginePlani + ResolutionAlti \\cdot (i,j)$\n\n\n- `MEC-Malt/Masq_STD-MALT_DeZoomX.tif` is a binary mask file that is a result of your input mask (if you used one) and a mask that is automatically calculated in the matching optimisation phase;\n\n- `MEC-Malt/Correl_STD-MALT_Num_X.tif` are the images with storing the correlation scores (it is not pure correlation, it is the correlation store after the aggregation step)\n\n\n#### Create a grayshaded DSM\n\nRepresent the surface in form of a grayshading. To visually asses the quality of your surface, it is much more intuitive than just looking at the depth/Z image. \n\n\n```\n!mm3d GrShade MEC-Malt/Z_Num8_DeZoom1_STD-MALT.tif ModeOmbre=IgnE Mask=MEC-Malt/Masq_STD-MALT_DeZoom1.tif @ExitOnBrkp\n```\n\n#### Visualise the grayshaded surface\n\n\n```\nsurface_shade_im = cv2.imread(\"MEC-Malt/Z_Num8_DeZoom1_STD-MALTShade.tif\",cv2.IMREAD_IGNORE_ORIENTATION)\n\nfig, ax = plt.subplots(figsize=(30, 10))\nax.imshow(surface_shade_im,cmap=\"gray\") \nplt.tight_layout()\n```\n\n#### Generate an orthophotmap\n\n`Tawny` will mosaic the per-image orthop\u0125otomosaics created in `Malt` (i.e., `Ortho-MEC-Malt/Ort_*.tif`), during matching. It will additionally perform some basic radiometry equalization. The output orthoimage is stored in `Ortho-MEC-Malt/Orthophotomosaic.tif`, and its georeferencing is stored in `Ortho-MEC-Malt/Orthophotomosaic.twf`.\n\n\n```\n!mm3d Tawny Ortho-MEC-Malt/ @ExitOnBrkp\n```\n\n#### Visualise the orthophoto\n\n\n```\northo_im = cv2.imread(\"Ortho-MEC-Malt/Orthophotomosaic.tif\",cv2.IMREAD_IGNORE_ORIENTATION)\n\nfig, ax = plt.subplots(figsize=(30, 10))\nax.imshow(ortho_im,cmap='gray') \nplt.tight_layout()\n```\n\n### ***Method2***: Multiview matching in image geometry and fusion\n\nThe computation will be carried out in the image geometry, where the optimization is defined in the `(x,y)` of the image space, and we are looking for the most optimal `depths` (see Figure below). This geometry is well adapted to true 3D surface reconstruction. Because the individual reconstructions are computed in image coordinate frames, a fusion will but carried out at the end.\n\n<center>    \n  \n  <br> \n</center>\n \n\n<center>\nFigure. Matching in image geometry. \n  <br> \n</center>\n\nThe multiview pipeline is as follows [Rupnik et al., 2018]:\n\n1. Extract tie-points and do RPC-bundle adjustement (done previously)\n2. Do N per-stereo (or per-M image as we are not bound by the number of images) dense matching (`Malt GeomImage`)\n3. Transform the N depth maps to a common coordinate frame (`NuageBascule`)\n4. Fuse the N depth maps into one (`SMDM`)\n\n\n\n<center>    \n  \n  <br> \n</center>\n \n\n<center>\nFigure. Multiview image matching and fusion pipeline. \n  <br> \n</center>\n\n<sub> Rupnik, E., Pierrot-Deseilligny, M. and Delorme, A., 2018. 3D reconstruction from multi-view VHR-satellite images in MicMac. ISPRS Journal of Photogrammetry and Remote Sensing, 139, pp.201-211.\n\n\n#### Do two per-triplet image matching\n\nWe will compute two surfaces using two different subsets of the images. \n\nInput parameters:\n\n  - `GeomImage` is a predefined term and it defines a number of processing parameters (e.g., low regularization, small matching wodows, image geometry)\n\n  - `TPMM_(0435|0566|1088).*tif` is the image set that will be used in the processing; in this example it is an image triplet; we take 3 **consecutive images** to make sure that the $\\frac{B}{H}$ ratios in the set are relatively small\n\n  - `RPC-d0-adj` is the name of the directory containing the geolocalisation\n\n  - `Master=TPMM_0566.tif` is the master image, i.e., the optimization is defined over each pixel of that image\n\n  - `SzW=2` and `Regul=0.2`, similarily to `Method1`, we add regularization and use bigger correlation windows because: (1) the geometry of the surface is smooth (i.e., no discontinuities), and (2) the images are quiet noisy;\n\n  - `NbVI=2` sets the necessary minimum number of images for MicMac to compute the surface; by default the value is set to 3 which means that in areas with only two overlapping images, the surface will not be computed; \n\n\n```\n#the first triplet\n!mm3d Malt GeomImage \"TPMM_(0435|0566|1088).*tif\" RPC-d0-adj Master=TPMM_0566.tif SzW=1 Regul=0.1 NbVI=2 ZPas=1 @ExitOnBrkp\n```\n\n\n```\n# the second triplet\n!mm3d Malt GeomImage \"TPMM_(0566|1088|1216).*tif\" RPC-d0-adj Master=TPMM_1088.tif SzW=1 Regul=0.1 NbVI=2 ZPas=1   @ExitOnBrkp\n```\n\n#### Transform the depth maps to a common coordinate frame\n\n  * The $1^{st}$ command `Malt UrbanMNE` does image matching in ground geometry (we've used it before), but since we indicate `DoMEC=0` it will not calculate the matching, all it will do is to create metadata defining the coordinate frame of the ground geometry. The output, as before, is stored in `MEC-Malt` folder;\n\n  * The $2^{nd}$ command `NuageBascule` will apply the transformation; the parameters are:\n    * `MM-Malt-Img-TPMM_0566/NuageImProf_STD-MALT_Etape_8.xml` is the metadata file defining the input coordinate frame\n    * `MEC-Malt/NuageImProf_STD-MALT_Etape_8.xml` is the metadata file defining the target coordinate frame (i.e., it is the terrain geometry)\n    * `Fusion/DSM_Tri1.xml` is the output metadata file, i.e., the input file transformed to the target coordinate frame; it will be accompagned by several other files containing the surface itself, the mask and the correlation image (see the inside of the `Fusion` folder);\n\n\n```\n# define the common frame\n!mm3d Malt UrbanMNE \".*tif\" RPC-d0-adj DoMEC=0  @ExitOnBrkp\n\n# create a directory that will store the fused surface\n!mkdir Fusion\n\n# do 3D spatial similarity of the first triplet depth map\n!mm3d NuageBascule MM-Malt-Img-TPMM_0566/NuageImProf_STD-MALT_Etape_8.xml MEC-Malt/NuageImProf_STD-MALT_Etape_8.xml Fusion/DSM_Tri1.xml @ExitOnBrkp\n\n# do 3D spatial similarity of the second triplet depth map\n!mm3d NuageBascule MM-Malt-Img-TPMM_1088/NuageImProf_STD-MALT_Etape_8.xml MEC-Malt/NuageImProf_STD-MALT_Etape_8.xml Fusion/DSM_Tri2.xml @ExitOnBrkp\n```\n\n#### Fuse the individual depth maps\n\nThe fusion takes all the surfaces specified by the regular expression and merges it. The fusion takes into account the correlation images and treats it as confidence maps.\n\nInput parameters:\n\n* `Fusion/DSM_Tri.*xml` the subset of surfaces that will be merged; \n\nTha result is saved to `Fusion/Fusion_Prof.tif`, there is a corresponding mask and a correlation map named with `_Mask` and `Correl` postfixes, respectively.\n\n\n```\n!mm3d SMDM Fusion/DSM_Tri.*xml  @ExitOnBrkp\n```\n\n#### Visualise in grayshade and export to ply\n\n\n```\n# grayshade\n!mm3d GrShade Fusion/Fusion_Prof.tif Out=Fusion/Fusion_GShade.tif ModeOmbre=IgnE @ExitOnBrkp\n\nsurface_fused_shade_im = cv2.imread(\"Fusion/Fusion_GShade.tif\",cv2.IMREAD_IGNORE_ORIENTATION)\n\nfig, ax = plt.subplots(1,2,figsize=(15, 15))\nax[0].imshow(surface_fused_shade_im,cmap=\"gray\") \nax[1].imshow(surface_shade_im,cmap=\"gray\") \nplt.tight_layout()\n\n# export to ply\n#!mm3d Nuage2Ply Fusion/Fusion.xml Out=Fusion.ply\n```\n", "meta": {"hexsha": "c2fa88e3b79d6b6e8056bf8be2f465c23a277ae5", "size": 1038911, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Satellite Data.ipynb", "max_stars_repo_name": "sherif-abdallah/Satellite-Data", "max_stars_repo_head_hexsha": "f8eb6501c7c535ee3560c4ee93e796b1c570371e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Satellite Data.ipynb", "max_issues_repo_name": "sherif-abdallah/Satellite-Data", "max_issues_repo_head_hexsha": "f8eb6501c7c535ee3560c4ee93e796b1c570371e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Satellite Data.ipynb", "max_forks_repo_name": "sherif-abdallah/Satellite-Data", "max_forks_repo_head_hexsha": "f8eb6501c7c535ee3560c4ee93e796b1c570371e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 1285.7809405941, "max_line_length": 438594, "alphanum_fraction": 0.952233637, "converted": true, "num_tokens": 5486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25683199138751883, "lm_q2_score": 0.08269734210984904, "lm_q1q2_score": 0.021239323056527447}}
{"text": "<a href=\"https://colab.research.google.com/github/ChrizZhuang/marginalized_graph_kernel_protein/blob/main/Docking_0607.ipynb\" target=\"_parent\"></a>\n\n\n```\n!nvidia-smi\n```\n\n    Mon Jun  7 00:59:45 2021       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 465.27       Driver Version: 460.32.03    CUDA Version: 11.2     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   33C    P8     9W /  70W |      0MiB / 15109MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    |  No running processes found                                                 |\n    +-----------------------------------------------------------------------------+\n\n\n\n```\n#!pip install pymatgen==2020.12.31\n!pip install pymatgen==2019.11.11\n!pip install --pre graphdot\n!pip install gdown\n```\n\n    Requirement already satisfied: pymatgen==2019.11.11 in /usr/local/lib/python3.7/dist-packages (2019.11.11)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (0.17.7)\n    Requirement already satisfied: pydispatcher>=2.0.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.0.5)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (0.8.9)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.23.0)\n    Requirement already satisfied: scipy>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.4.1)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.16.1)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.7.1)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (3.3.0)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (3.2.2)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2021.5.9)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.1.5)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.5.1)\n    Requirement already satisfied: numpy>=1.14.3 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.19.5)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen==2019.11.11) (0.2.2)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (2020.12.5)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (3.0.4)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->pymatgen==2019.11.11) (1.2.1)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (2.8.1)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (1.3.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (0.10.0)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen==2019.11.11) (2018.9)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.2->pymatgen==2019.11.11) (4.4.2)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.1->matplotlib>=1.5->pymatgen==2019.11.11) (1.15.0)\n    Requirement already satisfied: graphdot in /usr/local/lib/python3.7/dist-packages (0.8a17)\n    Requirement already satisfied: scipy>=1.3.0 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.4.1)\n    Requirement already satisfied: treelib>=1.6.1 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.6.1)\n    Requirement already satisfied: networkx>=2.4 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2.5.1)\n    Requirement already satisfied: ase>=3.17 in /usr/local/lib/python3.7/dist-packages (from graphdot) (3.21.1)\n    Requirement already satisfied: kahypar>=1.1.4 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.1.6)\n    Requirement already satisfied: tqdm>=4.55 in /usr/local/lib/python3.7/dist-packages (from graphdot) (4.61.0)\n    Requirement already satisfied: mendeleev>=0.7 in /usr/local/lib/python3.7/dist-packages (from graphdot) (0.7.0)\n    Requirement already satisfied: pymatgen==2019.11.11 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2019.11.11)\n    Requirement already satisfied: numba>=0.51.0 in /usr/local/lib/python3.7/dist-packages (from graphdot) (0.51.2)\n    Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.19.5)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.7.1)\n    Requirement already satisfied: pandas>=0.24 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.1.5)\n    Requirement already satisfied: pycuda>=2019 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2021.1)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from treelib>=1.6.1->graphdot) (0.16.0)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.4->graphdot) (4.4.2)\n    Requirement already satisfied: matplotlib>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from ase>=3.17->graphdot) (3.2.2)\n    Requirement already satisfied: pyfiglet<0.9,>=0.8.post1 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (0.8.post1)\n    Requirement already satisfied: SQLAlchemy<2.0.0,>=1.3.23 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (1.4.15)\n    Requirement already satisfied: colorama<0.5.0,>=0.4.4 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (0.4.4)\n    Requirement already satisfied: six<2.0.0,>=1.15.0 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (1.15.0)\n    Requirement already satisfied: Pygments<3.0.0,>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (2.9.0)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2.23.0)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (3.3.0)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (1.16.1)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (0.17.7)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2021.5.9)\n    Requirement already satisfied: pydispatcher>=2.0.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2.0.5)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (0.8.9)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from numba>=0.51.0->graphdot) (57.0.0)\n    Requirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba>=0.51.0->graphdot) (0.34.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->graphdot) (1.2.1)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->graphdot) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->graphdot) (2018.9)\n    Requirement already satisfied: mako in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (1.1.4)\n    Requirement already satisfied: pytools>=2011.2 in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (2021.2.7)\n    Requirement already satisfied: appdirs>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (1.4.4)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.0.0->ase>=3.17->graphdot) (0.10.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.0.0->ase>=3.17->graphdot) (2.4.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.0.0->ase>=3.17->graphdot) (1.3.1)\n    Requirement already satisfied: greenlet!=0.4.17; python_version >= \"3\" in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (1.1.0)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (4.0.1)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (2020.12.5)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen==2019.11.11->graphdot) (0.2.2)\n    Requirement already satisfied: MarkupSafe>=0.9.2 in /usr/local/lib/python3.7/dist-packages (from mako->pycuda>=2019->graphdot) (2.0.1)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (3.4.1)\n    Requirement already satisfied: typing-extensions>=3.6.4; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (3.7.4.3)\n    Requirement already satisfied: gdown in /usr/local/lib/python3.7/dist-packages (3.6.4)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from gdown) (2.23.0)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from gdown) (4.61.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from gdown) (1.15.0)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (2020.12.5)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (1.24.3)\n\n\n\n```\n%matplotlib inline\nimport io\nimport sys\nsys.path.append('/usr/local/lib/python3.6/site-packages/')\nimport os\nimport urllib\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport graphdot\nfrom graphdot import Graph\nfrom graphdot.graph.adjacency import AtomicAdjacency\nfrom graphdot.graph.reorder import rcm\nfrom graphdot.kernel.marginalized import MarginalizedGraphKernel # https://graphdot.readthedocs.io/en/latest/apidoc/graphdot.kernel.marginalized.html\nfrom graphdot.kernel.marginalized.starting_probability import Uniform\nfrom graphdot.model.gaussian_process import (\n    GaussianProcessRegressor,\n    LowRankApproximateGPR\n)\nfrom graphdot.kernel.fix import Normalization\nimport graphdot.microkernel as uX\nimport ase.io\n```\n\n    /usr/local/lib/python3.7/dist-packages/graphdot/graph/__init__.py:24: UserWarning: Cannot import RDKit, `graph.from_rdkit()` will be unavailable.\n    \n      'Cannot import RDKit, `graph.from_rdkit()` will be unavailable.\\n'\n\n\n\n```\nfrom google.colab import drive\ndrive.mount('/content/gdrive', force_remount=True)\n```\n\n    Mounted at /content/gdrive\n\n\n\n```\n#cd gdrive/MyDrive/Google\\ Colab/Covid-Data\n%cd gdrive/MyDrive/Covid-Data/\n```\n\n    /content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data\n\n\n\n```\n!pwd\n```\n\n    /content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data\n\n\n\n```\nfiles  = ['uncharged_NSP15_6W01_A_3_H.Orderable_zinc_db_enaHLL.2col.csv.1.xz']\ndataset = pd.read_pickle(files[0])\n#frames = [pd.read_pickle(f) for f in files]\n#dataset = pd.concat(frames)\n```\n\n\n```\ndataset.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>energy</th>\n      <th>smiles</th>\n      <th>graphs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>-2.265697</td>\n      <td>Cc1nc(no1)c2cncnc2[C@@H]3CCCN(C3)C(=O)Cc4ccccc4</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>-2.351519</td>\n      <td>Cc1ccc(cc1)c2nnc(n2N)SCC(=O)Nc3ccccc3OC</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>-3.308996</td>\n      <td>CCOC(=O)Cn1c2ccccc2nc1[C@H]3CC(=O)N(C3)c4ccc(c...</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>-3.760179</td>\n      <td>CC[C@H](C)NC(=O)[C@@H](CC)N(Cc1ccccc1)C(=O)Cc2...</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>-2.895577</td>\n      <td>Cc1cccc2c1ccn2CCC(=O)N3CCc4cc(c(cc4C3)OC)OC</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\ntarget = 'energy'\nN_train = 2500\nN_test = 5000\n```\n\n\n```\nnp.random.seed(0)\n# select train and test data\ntrain_sel = np.random.choice(len(dataset), N_train, replace=False)\ntest_sel = np.random.choice(np.setxor1d(np.arange(len(dataset)), train_sel), N_test, replace=False)\ntrain = dataset.iloc[train_sel]\ntest = dataset.iloc[test_sel]\n```\n\n\n```\n# import graphdot.microkernel as uX\ngpr = GaussianProcessRegressor(\n    # kernel is the covariance function of the gaussian process (GP)\n    kernel=Normalization( # kernel equals to normalization -> normalizes a kernel using the cosine of angle formula, k_normalized(x,y) = k(x,y)/sqrt(k(x,x)*k(y,y))\n        # graphdot.kernel.fix.Normalization(kernel), set kernel as marginalized graph kernel, which is used to calculate the similarity between 2 graphs\n        # implement the random walk-based graph similarity kernel as Kashima, H., Tsuda, K., & Inokuchi, A. (2003). Marginalized kernels between labeled graphs. ICML\n        MarginalizedGraphKernel( \n            # node_kernel - A kernelet that computes the similarity between individual nodes\n            # uX - graphdot.microkernel - microkernels are positive-semidefinite functions between individual nodes and edges of graphs\n            node_kernel=uX.Additive( # addition of kernal matrices: sum of k_a(X_a, Y_a) cross for a in features\n                # uX.Constant - a kernel that returns a constant value, always mutlipled with other microkernels as an adjustable weight\n                #   c, the first input arg. as 0.5, (0.01, 10) the lower and upper bounds of c that is allowed to vary during hyperpara. optimizartion\n                # uX.KroneckerDelta - a kronecker delta returns 1 when two features are equal and return h (the first input arg here, which is 0.5 in this case) otherwise\n                #   (0.1, 0.9) the lower and upper bounds that h is allowed to vary during hyperpara. optimization\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), \n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                # uX.SquareExponential \n                # \n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                # uX.Convolution - a convolutional microkernel which averages evaluations of a base microkernel between pairs pf elememts of two variable-length feature sequences\n                # uX.KroneckerDelta as the base kernel\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            # edge_kernel - A kernelet that computes the similarity between individual edge\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'), # the strating probability of the random walk on each node\n            q=0.05 # the probability for the random walk to stop during each step\n        )\n    ),\n    alpha=1e-4, # value added to the diagonal of the kernel matrix during fitting\n    optimizer=True, # default optimizer of L-BFGS-B based on scipy.optimize.minimize\n    normalize_y=True, # normalize the y values so taht the means and variance is 0 and 1, repsectively. Will be reversed when predicions are returned\n    regularization='+', # alpha (1e-4 in this case) is added to the diagonals of the kernal matrix\n)\n```\n\n\n```\n#gpr.fit(train.graphs, train[target], repeat=3, verbose=True)\n# using the molecular graph to predict the energy\ngpr.fit(train.graphs, train[target], repeat=1, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  9.2486e+06|  5.6192e+07|  9.2684e+06|      -19798|  2.2708e+07|   1.3e+02|       1.9|\n    |  7.0456e+06|   5.459e+07|  7.0642e+06|      -18684|  2.1866e+07|   1.2e+02|       1.8|\n    |  4.8866e+06|   4.702e+07|  4.9039e+06|      -17315|  2.0461e+07|   1.2e+02|       1.9|\n    |  4.1676e+06|  4.0965e+07|  4.1844e+06|      -16750|  1.9706e+07|   1.2e+02|       1.9|\n    |   3.645e+06|  3.5011e+07|  3.6612e+06|      -16274|  1.8948e+07|   1.1e+02|       1.8|\n    |   3.326e+06|  3.0749e+07|   3.342e+06|      -15946|  1.8322e+07|   1.1e+02|       1.9|\n    |  3.1778e+06|  2.8881e+07|  3.1936e+06|      -15786|  1.8126e+07|   1.1e+02|       1.9|\n    |  3.1776e+06|   2.825e+07|  3.1934e+06|      -15766|  1.7637e+07|     1e+02|         2|\n    |  3.1162e+06|  2.8107e+07|  3.1319e+06|      -15708|  1.7756e+07|   1.1e+02|       1.8|\n    |  3.1047e+06|  2.7919e+07|  3.1204e+06|      -15701|  1.7957e+07|   1.1e+02|       1.8|\n    |  3.0991e+06|  2.7884e+07|  3.1148e+06|      -15693|  1.7887e+07|   1.1e+02|       1.9|\n    |   3.095e+06|  2.7843e+07|  3.1107e+06|      -15687|  1.7852e+07|   1.1e+02|       1.9|\n    |  3.0915e+06|  2.7966e+07|  3.1071e+06|      -15682|  1.7831e+07|   1.1e+02|       1.8|\n    |  3.0881e+06|   2.783e+07|  3.1037e+06|      -15679|  1.7843e+07|   1.1e+02|       1.8|\n    |  3.0867e+06|   2.776e+07|  3.1024e+06|      -15678|   1.787e+07|   1.1e+02|       1.8|\n    |  3.0846e+06|  2.7689e+07|  3.1002e+06|      -15676|   1.786e+07|   1.1e+02|       1.8|\n    |  3.0826e+06|  2.7772e+07|  3.0982e+06|      -15674|  1.7888e+07|   1.1e+02|       1.9|\n    |  3.0805e+06|  2.7692e+07|  3.0962e+06|      -15672|  1.7856e+07|   1.1e+02|       1.8|\n    |  3.0793e+06|  2.7664e+07|   3.095e+06|      -15671|  1.7848e+07|   1.1e+02|       1.8|\n    |  3.0798e+06|  2.7691e+07|  3.0955e+06|      -15671|  1.7831e+07|   1.1e+02|       1.8|\n    |  3.0801e+06|  2.7681e+07|  3.0957e+06|      -15671|  1.7844e+07|   1.1e+02|       1.8|\n    |  3.0801e+06|  2.7683e+07|  3.0958e+06|      -15671|  1.7848e+07|   1.1e+02|       1.8|\n    |  3.0798e+06|  2.7676e+07|  3.0955e+06|      -15671|  1.7842e+07|   1.1e+02|       1.8|\n    |  3.0802e+06|  2.7682e+07|  3.0959e+06|      -15671|  1.7842e+07|   1.1e+02|       1.8|\n    |  3.0803e+06|   2.769e+07|   3.096e+06|      -15671|  1.7846e+07|   1.1e+02|       1.8|\n    Optimization result:\n          fun: 3080341.1690479927\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 2.76768564e+03,  1.00160522e+03,  2.54343743e+02,  1.40084657e+02,\n            5.36770586e+04,  1.30209697e+03,  0.00000000e+00, -2.38738171e+03,\n            1.03163205e+03,  4.94424731e+03,  2.30155351e-28,  6.29779563e+02,\n            3.92013539e+02, -5.64968699e+03,  6.56766654e+04,  3.29971017e+03,\n            7.68444927e+03,  1.17837847e+03,  1.08177407e+04, -1.00557608e+03,\n            9.33575125e+02,  1.03686271e+03,  0.00000000e+00, -4.50509909e+03,\n            1.46569168e+03])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 25\n          nit: 19\n       status: 0\n      success: True\n            x: array([-9.21034037, -3.75355856, -1.66811626,  1.68654281, -2.30258509,\n           -4.22954205,  0.        , -2.96635524, -2.05158011,  2.30258509,\n           -2.55160117, -3.58149271, -1.74784929,  1.87961491, -2.30258509,\n            0.84642637, -2.30258509,  1.1526716 , -2.30258509, -2.89153277,\n           -1.36733597, -3.40148924, -0.22314355, -2.02166239, -1.9295367 ])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7f6bf13ae190>\n\n\n\n\n```\ngpr.kernel.hyperparameters\n```\n\n\n\n\n    starting_probability : Uniform\n    \tp : 1.0\n    stopping_probability : 0.00010000000000000009\n    node_kernel : Composite\n    \taromatic : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.02343420535068002\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.18860200789175988\n    \tatomic_number : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 5.400776905055444\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tcharge : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.0145590563621646\n    \t\trhs : SquareExponential\n    \t\t\tlength_scale : 1.0\n    \tchiral : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.05149063984443944\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.12853164901299938\n    \thcount : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 10.000000000000002\n    \t\trhs : SquareExponential\n    \t\t\tlength_scale : 0.07795674396128768\n    \thybridization : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.02783411902444354\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.17414808329497075\n    \tring_list : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 6.550981640628747\n    \t\trhs : Convolution\n    \t\t\tbase : KroneckerDelta\n    \t\t\t\th : 0.10000000000000002\n    edge_kernel : Composite\n    \taromatic : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 2.331300736214766\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tconjugated : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 3.166641607522053\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \torder : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.05549109210250382\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.25478481015091287\n    \tring_stereo : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.033323606027544916\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.8\n    \tstereo : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.1324351226762118\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.14521546104851712\n\n\n\n\n```\nmu = gpr.predict(train.graphs)\n```\n\n\n```\nplt.scatter(train[target], mu)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.2074369392067814\n    RMSE: 0.3195501910711287\n\n\n\n```\nmu_test = gpr.predict(test.graphs)\n```\n\n\n```\nplt.scatter(test[target], mu_test)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 1.2461703788060545\n    RMSE: 1.6040210737240486\n\n\n\n```\ngpr2 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-2, #different from gpr in alpha where gpr's alpha is 1e-4\n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\n#gpr2.fit(train.graphs, train[target], repeat=3, verbose=True)\ngpr2.fit(train.graphs, train[target], repeat=1, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |   1.667e+05|   1.928e+05|  1.7773e+05|      -11034|  2.2742e+05|   1.3e+02|       1.7|\n    |  1.5585e+05|  2.2171e+05|  1.6671e+05|      -10857|  2.2218e+05|   1.3e+02|       1.7|\n    |  1.3711e+05|  2.4873e+05|  1.4756e+05|      -10447|  2.0803e+05|   1.2e+02|       1.8|\n    |  1.3286e+05|  2.3627e+05|   1.432e+05|      -10338|  2.0336e+05|   1.1e+02|       1.7|\n    |  1.2977e+05|  2.2744e+05|  1.4002e+05|      -10249|  1.9714e+05|   1.1e+02|       1.7|\n    |  1.3006e+05|  2.1429e+05|  1.4032e+05|      -10258|  2.0119e+05|     1e+02|       1.7|\n    |  1.2923e+05|  2.2103e+05|  1.3946e+05|      -10238|  1.9906e+05|   1.1e+02|       1.7|\n    |  1.2888e+05|  2.2097e+05|  1.3911e+05|      -10228|  1.9865e+05|   1.1e+02|       1.7|\n    |  1.2843e+05|  2.2338e+05|  1.3864e+05|      -10211|  1.9582e+05|   1.1e+02|       1.7|\n    |  1.2837e+05|  2.2244e+05|  1.3858e+05|      -10212|   1.969e+05|   1.1e+02|       1.7|\n    |  1.2836e+05|  2.2225e+05|  1.3857e+05|      -10212|  1.9696e+05|   1.1e+02|       1.7|\n    |  1.2831e+05|  2.2155e+05|  1.3852e+05|      -10211|  1.9715e+05|   1.1e+02|       1.7|\n    |  1.2826e+05|  2.2184e+05|  1.3847e+05|      -10209|  1.9704e+05|   1.1e+02|       1.7|\n    |  1.2821e+05|  2.2181e+05|  1.3841e+05|      -10207|  1.9671e+05|   1.1e+02|       1.7|\n    |  1.2819e+05|  2.2165e+05|   1.384e+05|      -10207|  1.9664e+05|   1.1e+02|       1.8|\n    |  1.2818e+05|  2.2125e+05|  1.3838e+05|      -10207|  1.9671e+05|   1.1e+02|       1.8|\n    |  1.2817e+05|  2.2114e+05|  1.3838e+05|      -10207|  1.9673e+05|   1.1e+02|       1.7|\n    |  1.2815e+05|  2.2077e+05|  1.3836e+05|      -10207|  1.9677e+05|   1.1e+02|       1.7|\n    |  1.2812e+05|   2.185e+05|  1.3833e+05|      -10209|  1.9695e+05|   1.1e+02|       1.7|\n    |  1.2809e+05|   2.178e+05|   1.383e+05|      -10209|    1.97e+05|   1.1e+02|       1.7|\n    |  1.2807e+05|  2.1764e+05|  1.3828e+05|      -10208|  1.9695e+05|   1.1e+02|       1.7|\n    |  1.2805e+05|  2.1597e+05|  1.3826e+05|      -10209|  1.9693e+05|   1.1e+02|       1.7|\n    |  1.2805e+05|   2.172e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1693e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.8|\n    |  1.2804e+05|  2.1674e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1691e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2805e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.8|\n    |  1.2805e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    Optimization result:\n          fun: 128045.20193517115\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 21.67035135,   5.42797631,   0.91584794,   6.62684845,\n           636.88297304,  10.22203408,   0.        ,   6.13155297,\n             0.80318432, -45.79780911,   0.        ,   9.32446636,\n             2.06137402,   7.94609186, 767.483899  ,  -8.19180354,\n            92.93654292,   7.92503084, 118.62629465,   3.36719643,\n            38.71995733,   7.96834618,   0.        , -11.08475724,\n             7.2860016 ])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 31\n          nit: 21\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.51710969, -1.98267626,  1.72521606, -2.30258509,\n           -4.60517019,  0.        , -4.60517019, -1.8070945 ,  2.30258509,\n           -2.88031384, -3.6019383 , -2.30258509,  1.91177723, -2.30258509,\n            0.28746812, -2.30258509,  0.54884256, -2.30258509, -0.5686784 ,\n           -2.30258509, -4.35637808, -0.22314355, -2.55717239, -2.21179129])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7f6bf00630d0>\n\n\n\n\n```\nmu = gpr2.predict(train.graphs)\nplt.scatter(train[target], mu)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.7238389142657052\n    RMSE: 0.9634943206325994\n\n\n\n```\nmu_test = gpr2.predict(test.graphs)\nplt.scatter(test[target], mu_test)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 0.9561539409612109\n    RMSE: 1.2284268143181998\n\n", "meta": {"hexsha": "7f685e11ff316b9aa64977e7592344720a001ef9", "size": 106575, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Docking_0607.ipynb", "max_stars_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_stars_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Docking_0607.ipynb", "max_issues_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_issues_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Docking_0607.ipynb", "max_forks_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_forks_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 101.6937022901, "max_line_length": 16574, "alphanum_fraction": 0.7338024865, "converted": true, "num_tokens": 12925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.04885777654477295, "lm_q1q2_score": 0.021203369431962122}}
{"text": "# Introduction to Biomechanics\n\n> Marcos Duarte, Renato Naville Watanabe  \n> [Laboratory of Biomechanics and Motor Control](http://pesquisa.ufabc.edu.br/bmclab)  \n> Federal University of ABC, Brazil\n\n## Biomechanics @ UFABC\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('http://pesquisa.ufabc.edu.br/bmclab', width='100%', height=500)\n```\n\n\n\n\n\n\n\n\n\n\n##  Biomechanics\n\nThe etymology of the word *Biomechanics* is evident:\n\n<span class=\"notranslate\">\n\\begin{equation}\n\\text{Biomechanics} := \\text{bios} \\, (\\text{life}) + \\text{mechanics}\n\\label{eq_biomechanics}\n\\end{equation}\n</span>  \n\nProfessor Herbert Hatze, on a letter to the editors of the Journal of Biomechanics in 1974, proposed a (very good) definition for *the science called Biomechanics*:\n\n> \"*Biomechanics is the study of the structure and function of biological systems by means of the methods of mechanics.*\"   \n> Hatze (1974) [The meaning of the term biomechanics](https://github.com/demotu/BMC/blob/master/courses/HatzeJB74biomechanics.pdf).\n\n### Biomechanics & Mechanics - Hatze\n\nAnd Hatze, advocating for *Biomechanics to be a science of its own*, argues that Biomechanics **is not** simply Mechanics of (applied to) living systems:\n\n> \"*It would not be correct to state that 'Biomechanics is the study of the mechanical aspects of the structure and function of biological systems' because biological systems do not have mechanical aspects. They only have biomechanical aspects (otherwise mechanics, as it exists, would be sufficient to describe all phenomena which we now call biomechanical features of biological systems).*\" Hatze (1974)\n\n### Biomechanics vs. Mechanics - Hatze\n\nTo support this argument, Hatze illustrates the difference between Biomechanics and the application of Mechanics, with an example of a javelin throw: studying the mechanics aspects of the javelin flight trajectory (use existing knowledge about aerodynamics and ballistics) vs. studying the biomechanical aspects of the phase before the javelin leaves the thrower\u2019s hand (there are no established mechanical models for this system). \n\n### Biomechanics & Mechanics - Fung\n\nProfessor Yuan-Cheng Fung, another great biomechanicist, is (much) less enthusiastic than Hatze about Biomechanics to be a science of its own, according to Fung:\n> \"*Biomechanics is mechanics applied to biology*\" Fung (1993).\n\nBut this definition does not mean Fung demotes the importance of Biomechanics, a few pages later he stated:  \n> \"*Biomechanics has participated in virtually every modern advance of medical science and technology*\" Fung (1993).\n\n### Branches of Mechanics \n\n**A good knowledge of Mechanics is a necessary condition, but not sufficient!, to have a good knowledge of Biomechanics**.  \n\nIn fact, only a subset of Mechanics matters to Biomechanics, the Classical Mechanics subset, the domain of mechanics for bodies with moderate speeds $(\\ll 3.10^8 m/s!)$ and not very small $(\\gg 3.10^{-9} m!)$ as shown in the following diagram:  \n\n<figure><center></center><figcaption><center><i>Figure. Domains of mechanics (image from <a href=\"http://en.wikipedia.org/wiki/Classical_mechanics\">http://en.wikipedia.org/wiki/Classical_mechanics</a>).</i></center></figcaption></figure> \n\n### Biomechanics & other Sciences I\n\nOne last point about the excellent letter from Hatze, already in 1974 he points for the following problem:\n\n> \"*The use of the term biomechanics imposes rather severe restrictions on its meaning because of the established definition of the term, mechanics. This is unfortunate,  since the synonym Biomechanics, as it is being understood by the majority of biomechanists today, has a much wider meaning.*\" Hatze (1974)\n\nAlthough the term Biomechanics may sound new to you, it's not rare that people think the use of methods outside the realm of Mechanics as Biomechanics.  \nFor instance, electromyography and thermography are two methods that although may be useful in Biomechanics, particularly the former, they clearly don't have any relation with Mechanics; Electromagnetism and Thermodynamics are other [branches of Physics](https://en.wikipedia.org/wiki/Branches_of_physics), although there is considerable overlapping between Mechanics and Thermodynamics.\n\n### Biomechanics & Engineering\n\nEven seeing Biomechanics as a field of Science, as argued by Hatze, it's also possible to refer to Engineering Biomechanics considering that Engineering is \"*the application of scientific and mathematical principles to practical ends*\" [[The Free Dictionary](http://www.thefreedictionary.com/engineering)] and particularly that \"*Engineering Mechanics is the application of Mechanics to solve problems involving common engineering elements*\" [[Wikibooks]](https://en.wikibooks.org/wiki/Engineering_Mechanics), and, last but not least, that Biomedical engineering is the application of engineering principles and design concepts to medicine and biology for healthcare purposes [[Wikipedia](https://en.wikipedia.org/wiki/Biomedical_engineering)].\n\n### Applications of Biomechanics\n\nBiomechanics matters to fields of science and technology related to biology and health and it's also relevant for the development of synthetic systems inspired on biological systems, as in robotics. To illustrate the variety of applications of Biomechanics, this is the current list of topics covered in the Journal of Biomechanics:\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('https://www.sciencedirect.com/journal/journal-of-biomechanics/about/aims-and-scope', width='100%', height=500)\n```\n\n\n\n\n\n\n\n\n\n\n### On the branches of Mechanics I\n\nMechanics is a branch of the physical sciences that is concerned with the state of rest or motion of bodies that are subjected to the action of forces. In general, this subject can be subdivided into three branches: rigid-body mechanics, deformable-body mechanics, and fluid mechanics (Hibbeler, 2012; Ruina and Rudra, 2019). \n\n(Classical) Mechanics is typically partitioned in Statics and Dynamics (Hibbeler, 2012; Ruina and Rudra, 2019).  \nIn turn, Dynamics is divided in **Kinematics** and **Kinetics**.  \nThis classification is clear; dynamics is the study of the motions of bodies and Statics is the study of forces in the absence of changes in motion. Kinematics is the study of motion without considering its possible causes (forces) and Kinetics is the study of the possible causes of motion.\n\n<figure><center></center><figcaption><center><i>Figure. Branches of mechanics (image from <a href=\"https://en.wikibooks.org/wiki/Engineering_Statics/Introduction\">https://en.wikibooks.org/wiki/Engineering_Statics/Introduction</a>).</i></center></figcaption></figure> \n\n### On the branches of Mechanics and Biomechanics\n\nNevertheless, it's common in Biomechanics to adopt a slightly different classification: to partition it between Kinematics and Kinetics, and then Kinetics into Statics and Dynamics (David Winter, Nigg & Herzog, and Vladimir Zatsiorsky, among others, use this classification in their books). The rationale is that we first separate the study of motion considering or not its causes (forces). The partition of (Bio)Mechanics in this way is useful because is simpler to study and describe (measure) the kinematics of human motion and then go to the more complicated issue of understanding (measuring) the forces related to the human motion.\n\nAnyway, these different classifications reveal a certain contradiction between Mechanics (particularly from an engineering point of view) and Biomechanics; some scholars will say that this taxonomy in Biomechanics is simply wrong and it should be corrected to align with the Mechanics. Be aware.\n\n### The future of Biomechanics\n\n(Human) Movement Science combines many disciplines of science (such as, Physiology, Biomechanics, and Psychology) for the study of human movement. Professor Benno Nigg claims that with the growing concern for the well-being of humankind, Movement Science will have an important role: \n> Movement science will be one of the most important and most recognized science fields in the twenty-first century... The future discipline of movement science has a unique opportunity to become an important contributor to the well-being of mankind.   \nNigg BM (1993) [Sport  science  in  the twenty-first  century](http://www.ncbi.nlm.nih.gov/pubmed/8230394). Journal of Sports Sciences, 77, 343-347.\n\nAnd so Biomechanics will also become an important contributor to the well-being of humankind.\n\n### Biomechanics  and the Biomedical Engineering at UFABC I\n\nAt the university level, the study of Mechanics is typically done in the disciplines Statics and Dynamics (rigid-body mechanics), Strength of Materials (deformable-body mechanics), and Mechanics of Fluids (fluid mechanics). Consequently, the study on Biomechanics must also cover these topics for a greater understanding of the structure and function of biological systems.  \n\n### Biomechanics  and the Biomedical Engineering at UFABC II\n\nThe Biomedical Engineering degree at UFABC covers these topics for the study of biological systems in different courses: Ci\u00eancia dos Materiais Biocompat\u00edveis, Modelagem e Simula\u00e7\u00e3o de Sistemas Biom\u00e9dicos, M\u00e9todos de Elementos Finitos aplicados a Sistemas Biom\u00e9dicos, Mec\u00e2nica dos Fluidos, Caracteriza\u00e7\u00e3o de Biomateriais, Sistemas Biol\u00f3gicos, and last but not least, [Biomec\u00e2nica I](http://demotu.org/ensino/biomecanica-i/) & Biomec\u00e2nica II.  \n\nHow much of biological systems is in fact studied in these disciplines varies a lot. Anyway, none of these courses cover the study of human motion with implications to health, rehabilitation, and sports, except the last course. This is the reason why the courses [Biomec\u00e2nica I](http://demotu.org/ensino/biomecanica-i/) & II focus on the analysis of the human movement.\n\n### More on Biomechanics\n\nThe Wikipedia page on biomechanics is a good place to read more about Biomechanics:\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('http://en.m.wikipedia.org/wiki/Biomechanics', width='100%', height=400)\n```\n\n\n\n\n\n\n\n\n\n\n## History of Biomechanics\n\nBiomechanics progressed basically with the advancements in Mechanics and with the invention of instrumentations for measuring mechanical quantities and computing.  \n\nThe development of Biomechanics was only possible because people became more interested in the understanding of the structure and function of biological systems and to apply these concepts to the progress of the humankind.\n\n## Aristotle (384-322 BC)  \nAristotle was the first to have written about the movement of animals in his works *On the Motion of Animals (De Motu Animalium)* and *On the Gait of Animals (De Incessu Animalium)* [[Works by Aristotle]](http://classics.mit.edu/Browse/index-Aristotle.html).\n\nAristotle clearly already knew what we nowadays refer as Newton's third law of motion:  \n\"*For as the pusher pushes so is the pushed pushed, and with equal force.*\" [Part 3, [On the Motion of Animals](http://classics.mit.edu/Aristotle/motion_animals.html)]\n\n### Aristotle & the Scientific Revolution I\n\nAlthough Aristotle's contributions were invaluable to humankind, to make his discoveries he doesn't seem to have employed anything similar to what we today refer as [scientific method](https://en.wikipedia.org/wiki/Scientific_method) (the systematic observation, measurement, and experiment, and the formulation, testing, and modification of hypotheses). \n\nMost of the Physics of Aristotle was ambiguous or incorrect; for example, for him there was no motion without a force. He even deduced that speed was proportional to force and inversely proportional to resistance [[Book VII, Physics](http://classics.mit.edu/Aristotle/physics.7.vii.html)]. Perhaps Aristotle was too influenced by the observation of motion of a body under the action of a friction force, where this notion is not at all unreasonable.\n\n### Aristotle & the Scientific Revolution II\n\nIf Aristotle performed any observation/experiment at all in his works, he probably was not good on that as, ironically, evinced in this part of his writing:  \n> \"Males have more teeth than females in the case of men, sheep, goats, and swine; in the case of other animals observations have not yet been made\". Aristotle [The History of Animals](http://classics.mit.edu/Aristotle/history_anim.html).\n\n## Leonardo da Vinci (1452-1519)\n\n<div><figure></figure></div>\n\nContributions of Leonardo to Biomechanics:  \n - Studies on the proportions of humans and animals  \n - Anatomy studies of the human body, especially the foot  \n - Studies on the mechanical function of muscles  \n\n<br><br>\nFigure. *\"Le proporzioni del corpo umano secondo Vitruvio\", also known as the [Vitruvian Man](https://en.wikipedia.org/wiki/Vitruvian_Man), drawing by [Leonardo da Vinci](https://en.wikipedia.org/wiki/Leonardo_da_Vinci) circa 1490 based on the work of [Marcus Vitruvius Pollio](https://en.wikipedia.org/wiki/Vitruvius) (1st century BC), depicting a man in supposedly ideal human proportions (image from [Wikipedia](https://en.wikipedia.org/wiki/Vitruvian_Man)).*  \n\n## Giovanni Alfonso Borelli (1608-1679)\n\n<div><figure></figure></div>\n\n - [The father of biomechanics](https://en.wikipedia.org/wiki/Giovanni_Alfonso_Borelli); the first to use modern scientific method into 'Biomechanics' in his book [De Motu Animalium](http://www.e-rara.ch/doi/10.3931/e-rara-28707).  \n - Proposed that the levers of the musculoskeletal system magnify motion rather than force.  \n - Calculated the forces required for equilibrium in various joints of the human body  before Newton published the laws of motion.  \n<br><br>\nFigure. *Excerpt from the book De Motu Animalium*.\n\n## More on the history of Biomechanics\n\nSee:  \n- http://courses.washington.edu/bioen520/notes/History_of_Biomechanics_(Martin_1999).pdf  \n- [http://biomechanics.vtheatre.net/doc/history.html](http://biomechanics.vtheatre.net/doc/history.html)  \n- Chapter 1 of Nigg and Herzog (2006) [Biomechanics of the Musculo-skeletal System](https://books.google.com.br/books?id=hOIeAQAAIAAJ&dq=editions:ISBN0470017678)\n\n### The International Society of Biomechanics\n\nThe biomechanics community has an official scientific society, the [International Society of Biomechanics](http://isbweb.org/), with a journal, the [Journal of Biomechanics](http://www.jbiomech.com), and an e-mail list, the [Biomch-L](http://biomch-l.isbweb.org):\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('https://biomch-l.isbweb.org/forums/2-General-Discussion', width='100%', height=400)\n```\n\n\n\n\n\n\n\n\n\n\n## Biomechanics by (BMClab) examples\n\nBiomechanics has been applied to many different problems; let's see a few examples of applications of Biomechanics:  \n- Clinical gait analysis: [http://pesquisa.ufabc.edu.br/bmclab/servicos/cga/](http://pesquisa.ufabc.edu.br/bmclab/servicos/cga/)  \n- Biomechanics of sports: [http://pesquisa.ufabc.edu.br/bmclab/biomecanica-do-chute-de-bicicleta/](http://pesquisa.ufabc.edu.br/bmclab/biomecanica-do-chute-de-bicicleta/)  \n\n### Examples of Biomechanics Classes around the World\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('http://pages.uoregon.edu/karduna/biomechanics/bme.htm', width='100%', height=400)\n```\n\n\n\n\n\n\n\n\n\n\n## Biomechanics classes @ UFABC\n\n - **[Biomec\u00e2nica I](http://pesquisa.ufabc.edu.br/bmclab/ensino/biomecanica-i/)**  \n - **[Biomec\u00e2nica II](http://pesquisa.ufabc.edu.br/bmclab/ensino/biomecanica-ii/)**  \n \nThe book [*Introduction to Statics and Dynamics*](http://ruina.tam.cornell.edu/Book/index.html), written by Andy Ruina and Rudra Pratap, is an excellent reference (a rigorous and yet didactic presentation of Mechanics for undergraduate students) on Classical Mechanics and the authors kindly offer the book freely available online.  \nWe will use this book as the main reference on Mechanics and Mathematics in our course.\n\n## Problems\n\n1. Go to [Biomechanics Classes on the Web](http://pages.uoregon.edu/karduna/biomechanics/) to visit websites of biomechanics classes around the world and find out how biomechanics is studied in different fields.  \n2. Find examples of applications of biomechanics in different areas.  \n3. Watch the video [The Weird World of Eadweard Muybridge](http://youtu.be/5Awo-P3t4Ho) to learn about [Eadweard Muybridge](http://en.wikipedia.org/wiki/Eadweard_Muybridge), an important person to the development of instrumentation for biomechanics.  \n4. Think about practical problems in nature that can be studied in biomechanics with simple approaches (simple modeling and low-tech methods) or very complicated approaches (complex modeling and high-tech methods).  \n5. What the study in the biomechanics of athletes, children, elderlies, persons with disabilities, other animals, and computer animation for the cinema industry may have in common and different?  \n6. Visit the website of the Laboratory of Biomechanics and Motor Control at UFABC and find out what we do and if there is anything you are interested in.  \n7. Is there anything in biomechanics that interests you? How could you pursue this interest? \n\n## References\n\n- [Biomechanics - Wikipedia, the free encyclopedia](http://en.wikipedia.org/wiki/Biomechanics)\n- [Mechanics - Wikipedia, the free encyclopedia](http://en.wikipedia.org/wiki/Mechanics)\n- [International Society of Biomechanics](http://isbweb.org/)\n- [Biomech-l, the biomechanics' e-mail list](http://biomch-l.isbweb.org/)\n- [Journal of Biomechanics' aims](http://www.jbiomech.com/aims)  \n- <a href=\"http://courses.washington.edu/bioen520/notes/History_of_Biomechanics_(Martin_1999).pdf\">A Genealogy of Biomechanics</a> \n- Fung Y-C (1993) [Biomechanics: mechanical properties ofliving tissues](https://books.google.com.br/books?id=yx3aBwAAQBAJ). 2nd ed. Springer.  \n- Hatze H (1974) [The meaning of the term biomechanics](https://github.com/demotu/BMC/blob/master/courses/HatzeJB74biomechanics.pdf). Journal of Biomechanics, 7, 189\u2013190.  \n- Hibbeler RC (2012) [Engineering Mechanics: Statics](http://books.google.com.br/books?id=PSEvAAAAQBAJ). 13 edition. Prentice Hall.   \n- Nigg BM and Herzog W (2006) [Biomechanics of the Musculo-skeletal System](https://books.google.com.br/books?id=hOIeAQAAIAAJ&dq=editions:ISBN0470017678). 3rd Edition. Wiley.  \n- Ruina A, Rudra P (2019) [Introduction to Statics and Dynamics](http://ruina.tam.cornell.edu/Book/index.html). Oxford University Press.  \n- Winter DA (2009) [Biomechanics and motor control of human movement](http://books.google.com.br/books?id=_bFHL08IWfwC). 4 ed. Hoboken: Wiley.\n- Zatsiorsky VM (1997) [Kinematics of Human Motion](http://books.google.com.br/books/about/Kinematics_of_Human_Motion.html?id=Pql_xXdbrMcC&redir_esc=y). Champaign, Human Kinetics.  \n- Zatsiorsky VM (2002) [Kinetics of human motion](http://books.google.com.br/books?id=wp3zt7oF8a0C). Human Kinetics.\n", "meta": {"hexsha": "6dbaaa1ad20531d88147705deeae0ef41e9eb318", "size": 31283, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Biomechanics.ipynb", "max_stars_repo_name": "e-moncao-lima/BMC", "max_stars_repo_head_hexsha": "98c3abbf89e630d64b695b535b0be4ddc8b2724b", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/Biomechanics.ipynb", "max_issues_repo_name": "e-moncao-lima/BMC", "max_issues_repo_head_hexsha": "98c3abbf89e630d64b695b535b0be4ddc8b2724b", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/Biomechanics.ipynb", "max_forks_repo_name": "e-moncao-lima/BMC", "max_forks_repo_head_hexsha": "98c3abbf89e630d64b695b535b0be4ddc8b2724b", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.1036339166, "max_line_length": 755, "alphanum_fraction": 0.626218713, "converted": true, "num_tokens": 4612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20689404392565783, "lm_q2_score": 0.10230470515565383, "lm_q1q2_score": 0.021166234162275317}}
{"text": "```python\npip install cirq \n```\n\n    Requirement already satisfied: cirq in /usr/local/lib/python3.7/dist-packages (0.13.1)\n    Requirement already satisfied: cirq-rigetti==0.13.1 in /usr/local/lib/python3.7/dist-packages (from cirq) (0.13.1)\n    Requirement already satisfied: cirq-pasqal==0.13.1 in /usr/local/lib/python3.7/dist-packages (from cirq) (0.13.1)\n    Requirement already satisfied: cirq-aqt==0.13.1 in /usr/local/lib/python3.7/dist-packages (from cirq) (0.13.1)\n    Requirement already satisfied: cirq-ionq==0.13.1 in /usr/local/lib/python3.7/dist-packages (from cirq) (0.13.1)\n    Requirement already satisfied: cirq-core==0.13.1 in /usr/local/lib/python3.7/dist-packages (from cirq) (0.13.1)\n    Requirement already satisfied: cirq-web==0.13.1 in /usr/local/lib/python3.7/dist-packages (from cirq) (0.13.1)\n    Requirement already satisfied: cirq-google==0.13.1 in /usr/local/lib/python3.7/dist-packages (from cirq) (0.13.1)\n    Requirement already satisfied: requests~=2.18 in /usr/local/lib/python3.7/dist-packages (from cirq-aqt==0.13.1->cirq) (2.23.0)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (1.7.1)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (3.10.0.2)\n    Requirement already satisfied: matplotlib~=3.0 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (3.2.2)\n    Requirement already satisfied: sortedcontainers~=2.0 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (2.4.0)\n    Requirement already satisfied: duet~=0.2.0 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (0.2.3)\n    Requirement already satisfied: networkx~=2.4 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (2.6.3)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (4.62.3)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (1.3.5)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (1.7.3)\n    Requirement already satisfied: numpy~=1.16 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (1.21.5)\n    Requirement already satisfied: google-api-core[grpc]<2.0.0dev,>=1.14.0 in /usr/local/lib/python3.7/dist-packages (from cirq-google==0.13.1->cirq) (1.26.3)\n    Requirement already satisfied: protobuf>=3.13.0 in /usr/local/lib/python3.7/dist-packages (from cirq-google==0.13.1->cirq) (3.17.3)\n    Requirement already satisfied: pyjwt~=1.7.1 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (1.7.1)\n    Requirement already satisfied: pyquil~=3.0.0 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (3.0.1)\n    Requirement already satisfied: h11~=0.9.0 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (0.9.0)\n    Requirement already satisfied: retrying~=1.3.3 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (1.3.3)\n    Requirement already satisfied: pydantic~=1.8.2 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (1.8.2)\n    Requirement already satisfied: qcs-api-client~=0.8.0 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (0.8.0)\n    Requirement already satisfied: certifi~=2021.5.30 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (2021.5.30)\n    Requirement already satisfied: sniffio~=1.2.0 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (1.2.0)\n    Requirement already satisfied: toml~=0.10.2 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (0.10.2)\n    Requirement already satisfied: httpcore~=0.11.1 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (0.11.1)\n    Requirement already satisfied: idna~=2.10 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (2.10)\n    Requirement already satisfied: six~=1.16.0 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (1.16.0)\n    Requirement already satisfied: rfc3339~=6.2 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (6.2)\n    Requirement already satisfied: python-dateutil~=2.8.1 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (2.8.2)\n    Requirement already satisfied: httpx~=0.15.5 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (0.15.5)\n    Requirement already satisfied: iso8601~=0.1.14 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (0.1.16)\n    Requirement already satisfied: attrs~=20.3.0 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (20.3.0)\n    Requirement already satisfied: rfc3986~=1.5.0 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (1.5.0)\n    Requirement already satisfied: google-auth<2.0dev,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (1.35.0)\n    Requirement already satisfied: pytz in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (2018.9)\n    Requirement already satisfied: packaging>=14.3 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (21.3)\n    Requirement already satisfied: googleapis-common-protos<2.0dev,>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (1.54.0)\n    Requirement already satisfied: setuptools>=40.3.0 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (57.4.0)\n    Requirement already satisfied: grpcio<2.0dev,>=1.29.0 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (1.43.0)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (0.2.8)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (4.2.4)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (4.8)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core==0.13.1->cirq) (0.11.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core==0.13.1->cirq) (3.0.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core==0.13.1->cirq) (1.3.2)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (0.4.8)\n    Requirement already satisfied: lark<0.12.0,>=0.11.1 in /usr/local/lib/python3.7/dist-packages (from pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (0.11.3)\n    Requirement already satisfied: rpcq<4.0.0,>=3.6.0 in /usr/local/lib/python3.7/dist-packages (from pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (3.9.2)\n    Requirement already satisfied: retry<0.10.0,>=0.9.2 in /usr/local/lib/python3.7/dist-packages (from pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (0.9.2)\n    Requirement already satisfied: importlib-metadata<4.0.0,>=3.7.3 in /usr/local/lib/python3.7/dist-packages (from pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (3.10.1)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata<4.0.0,>=3.7.3->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (3.7.0)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests~=2.18->cirq-aqt==0.13.1->cirq) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests~=2.18->cirq-aqt==0.13.1->cirq) (3.0.4)\n    Requirement already satisfied: py<2.0.0,>=1.4.26 in /usr/local/lib/python3.7/dist-packages (from retry<0.10.0,>=0.9.2->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (1.11.0)\n    Requirement already satisfied: decorator>=3.4.2 in /usr/local/lib/python3.7/dist-packages (from retry<0.10.0,>=0.9.2->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (4.4.2)\n    Requirement already satisfied: msgpack<1.0,>=0.6 in /usr/local/lib/python3.7/dist-packages (from rpcq<4.0.0,>=3.6.0->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (0.6.2)\n    Requirement already satisfied: python-rapidjson in /usr/local/lib/python3.7/dist-packages (from rpcq<4.0.0,>=3.6.0->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (1.5)\n    Requirement already satisfied: pyzmq>=17 in /usr/local/lib/python3.7/dist-packages (from rpcq<4.0.0,>=3.6.0->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (22.3.0)\n    Requirement already satisfied: ruamel.yaml in /usr/local/lib/python3.7/dist-packages (from rpcq<4.0.0,>=3.6.0->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (0.17.21)\n    Requirement already satisfied: ruamel.yaml.clib>=0.2.6 in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml->rpcq<4.0.0,>=3.6.0->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (0.2.6)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->cirq-core==0.13.1->cirq) (1.2.1)\n\n\n\n```python\n# import required libraries\nimport random\nimport time\nimport cirq\nfrom cirq import H, X, CNOT, measure\nimport matplotlib.pyplot as plt\n\n\n\ndef main(n,decide):\n    # Choose qubits to use.\n    q = cirq.LineQubit.range(n+1)\n\n    # Pick a secret n-bit function and create a circuit to query the oracle.\n    secret_function = [random.randint(0, 1) for _ in range(n)]\n    \n    # Create a balanced or constant oracle depending on the deciding bit.\n    oracle = make_oracle(q,n,secret_function,decide)\n    print(f\"Secret function:\\nf(x) = <{', '.join(str(e) for e in secret_function)}>\")\n\n    # Embed the oracle into a quantum circuit querying it.\n    circuit = make_deutsch_circuit(q,n, oracle)\n    print('Circuit:')\n    print(circuit)\n\n    # Simulate the circuit\n#    simulator = cirq.Simulator()\n#    result = simulator.run(circuit)\n    run_simulation(circuit,1024)\n    \n# Custom function used to respresent a a set of bits in string format\ndef bitstring(bits):\n    return ''.join(str(int(b)) for b in bits)\ndef run_simulation(c,run_count):\n  simulator = cirq.Simulator()\n  result = simulator.run(c, repetitions=run_count)\n  frequencies = result.histogram(key='result', fold_func=bitstring)\n  print(f'Sampled results:\\n{frequencies}')\n\n\n  # Check if we actually found the secret value.\n  most_common_bitstring = frequencies.most_common(1)[0][0]\n\n\n\ndef make_oracle(q,n, secret_function,decide):\n    \"\"\"Gates implementing the secret function f(x).\"\"\"\n    \n   \n    # If deciding bit is 0, implement a balanced function, in this case it is a CNOT of each input bits with a predefined control bit in X basis, that hold the value 1\n    if decide == 0:\n      print()\n      print(\"Should be a balanced function!\")\n      print()\n      for i,j in enumerate(secret_function):\n\n        if j == 1:\n          yield cirq.X(q[i])\n\n      for i in q[:n]:\n        yield CNOT(i,q[n])\n\n\n      for i,j in enumerate(secret_function):\n\n        if j == 1:\n          yield cirq.X(q[i])\n    \n    # If the deciding bit is 1, we implement a balanced function \n    else:\n      print()\n      print(\"Should be a constant function!\")\n      print()\n    \n\n    \n\n\ndef make_deutsch_circuit(q,n,oracle):\n    c = cirq.Circuit()\n\n    # Initialize input qubits\n    c.append( cirq.H.on_each(q[:n])) \n    # Initialize output qubits\n    c.append(cirq.X(q[n]) )\n    c.append(cirq.H(q[n]) )\n\n    # Query oracle\n    c.append(oracle)\n\n    # Measure in H basis\n    c.append(cirq.H.on_each(q[:n]))\n    c.append(cirq.measure(*q[:n], key=\"result\"))\n    return c\n\n\n\n```\n\n\n```python\n# Running the algorithm by altering the circuit for varied values of n, where n represents number of qubits & \n# Capturing time taken for the algorithm to run for each value of n for a balanced function\n\nt=[]\ndecide = 0\nfor i in range(1,21):\n    \n    st=time.time()\n    main(i,decide)\n    end=time.time()\n    t.append(end-st)\n\n\n\n```\n\n    Secret function:\n    f(x) = <0>\n    \n    Should be a balanced function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                  \u2502\n    1: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'1': 1024})\n    Secret function:\n    f(x) = <1, 0>\n    \n    Should be a balanced function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                  \u2502           \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502\n    2: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'11': 1024})\n    Secret function:\n    f(x) = <0, 0, 1>\n    \n    Should be a balanced function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                  \u2502                   \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502               \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502\n    3: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'111': 1024})\n    Secret function:\n    f(x) = <0, 0, 1, 0>\n    \n    Should be a balanced function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                  \u2502                   \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502               \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502           \u2502\n    3: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502   \u2502\n    4: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'1111': 1024})\n    Secret function:\n    f(x) = <1, 0, 1, 1, 1>\n    \n    Should be a balanced function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                  \u2502                           \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502                       \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502                   \u2502\n    3: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502   \u2502               \u2502\n    4: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502   \u2502   \u2502\n    5: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'11111': 1024})\n    Secret function:\n    f(x) = <0, 0, 1, 0, 1, 1>\n    \n    Should be a balanced function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                  \u2502                               \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502                           \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502                       \u2502\n    3: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502   \u2502                   \u2502\n    4: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    5: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    6: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'111111': 1024})\n    Secret function:\n    f(x) = <0, 0, 1, 1, 0, 0, 1>\n    \n    Should be a balanced function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                  \u2502                                   \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502                               \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502                           \u2502\n    3: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502   \u2502                       \u2502\n    4: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502   \u2502   \u2502                   \u2502\n    5: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    6: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    7: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'1111111': 1024})\n    Secret function:\n    f(x) = <0, 0, 0, 1, 0, 1, 0, 0>\n    \n    Should be a balanced function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                  \u2502                                   \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502                               \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502                           \u2502\n    3: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502   \u2502                       \u2502\n    4: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502   \u2502   \u2502                   \u2502\n    5: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    6: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502           \u2502\n    7: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    8: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'11111111': 1024})\n    Secret function:\n    f(x) = <1, 1, 0, 0, 0, 1, 1, 1, 1>\n    \n    Should be a balanced function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                  \u2502                                           \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502                                       \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502                                   \u2502\n    3: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502   \u2502                               \u2502\n    4: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502   \u2502   \u2502                           \u2502\n    5: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                       \u2502\n    6: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                   \u2502\n    7: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    8: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    9: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'111111111': 1024})\n    Secret function:\n    f(x) = <1, 1, 0, 1, 0, 1, 1, 1, 1, 0>\n    \n    Should be a balanced function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502                                           \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502                                       \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502                                   \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502                               \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502                           \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                       \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                   \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502           \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    10: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'1111111111': 1024})\n    Secret function:\n    f(x) = <0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0>\n    \n    Should be a balanced function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502                                               \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502                                           \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502                                       \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502                                   \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502                               \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                           \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                       \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                   \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502           \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    11: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'11111111111': 1024})\n    Secret function:\n    f(x) = <0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1>\n    \n    Should be a balanced function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502                                                       \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502                                                   \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502                                               \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502                                           \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502                                       \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                   \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                               \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                           \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                       \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                   \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    12: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'111111111111': 1024})\n    Secret function:\n    f(x) = <1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0>\n    \n    Should be a balanced function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502                                                       \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502                                                   \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502                                               \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502                                           \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502                                       \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                   \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                               \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                           \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                       \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                   \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502           \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    13: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'1111111111111': 1024})\n    Secret function:\n    f(x) = <0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1>\n    \n    Should be a balanced function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502                                                               \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502                                                           \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502                                                       \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502                                                   \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502                                               \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                           \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                       \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                   \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                               \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                           \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                       \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                   \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    13: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    14: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'11111111111111': 1024})\n    Secret function:\n    f(x) = <0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1>\n    \n    Should be a balanced function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502                                                                   \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502                                                               \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502                                                           \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502                                                       \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502                                                   \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                               \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                           \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                       \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                   \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                               \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                           \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                       \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                   \u2502\n    13: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    14: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    15: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'111111111111111': 1024})\n    Secret function:\n    f(x) = <0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1>\n    \n    Should be a balanced function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502                                                                       \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502                                                                   \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502                                                               \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502                                                           \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502                                                       \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                                   \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                               \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                           \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                       \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                   \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                               \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                           \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                       \u2502\n    13: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                   \u2502\n    14: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    15: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    16: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'1111111111111111': 1024})\n    Secret function:\n    f(x) = <1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0>\n    \n    Should be a balanced function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502                                                                       \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502                                                                   \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502                                                               \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502                                                           \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502                                                       \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                                   \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                               \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                           \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                       \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                   \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                               \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                           \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                       \u2502\n    13: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                   \u2502\n    14: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    15: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502           \u2502\n    16: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    17: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'11111111111111111': 1024})\n    Secret function:\n    f(x) = <1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0>\n    \n    Should be a balanced function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502                                                                           \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502                                                                       \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502                                                                   \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502                                                               \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502                                                           \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                                       \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                                   \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                               \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                           \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                       \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                   \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                               \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                           \u2502\n    13: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                       \u2502\n    14: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                   \u2502\n    15: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    16: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502           \u2502\n    17: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    18: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'111111111111111111': 1024})\n    Secret function:\n    f(x) = <1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1>\n    \n    Should be a balanced function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502                                                                                   \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502                                                                               \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502                                                                           \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502                                                                       \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502                                                                   \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                                               \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                                           \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                                       \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                                   \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                               \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                           \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                       \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                   \u2502\n    13: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                               \u2502\n    14: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                           \u2502\n    15: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                       \u2502\n    16: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                   \u2502\n    17: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    18: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    19: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'1111111111111111111': 1024})\n    Secret function:\n    f(x) = <0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1>\n    \n    Should be a balanced function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502                                                                                       \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502                                                                                   \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502                                                                               \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502                                                                           \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502                                                                       \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                                                   \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                                               \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                                           \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                                       \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                                   \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                               \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                           \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                       \u2502\n    13: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                                   \u2502\n    14: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                               \u2502\n    15: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                           \u2502\n    16: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                       \u2502\n    17: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502                   \u2502\n    18: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502               \u2502\n    19: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    20: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'11111111111111111111': 1024})\n\n\n\n```python\n# Plotting the time taken by the algorithm against the number of qubits in the circuit to analyze scalability of the algorithm\n\nplt.scatter(list(range(1,21)), t)\nplt.xlabel('Qubits')\nplt.ylabel('Time (in seconds)')\nplt.title(\" Time vs Qubits \")\nplt.show()\n\n```\n\n\n```python\n# Running the algorithm by altering the circuit for varied values of n, where n represents number of qubits & \n# Capturing time taken for the algorithm to run for each value of n for a balanced function\n\nt=[]\ndecide = 1\nfor i in range(1,21):\n    \n    st=time.time()\n    main(i,decide)\n    end=time.time()\n    t.append(end-st)\n\n\n\n```\n\n    Secret function:\n    f(x) = <0>\n    \n    Should be a constant function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n    \n    1: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'0': 1024})\n    Secret function:\n    f(x) = <0, 1>\n    \n    Should be a constant function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                  \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    2: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'00': 1024})\n    Secret function:\n    f(x) = <0, 1, 0>\n    \n    Should be a constant function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                  \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    3: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'000': 1024})\n    Secret function:\n    f(x) = <0, 0, 0, 1>\n    \n    Should be a constant function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                  \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    3: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    4: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'0000': 1024})\n    Secret function:\n    f(x) = <0, 1, 0, 1, 1>\n    \n    Should be a constant function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                  \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    3: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    4: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    5: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'00000': 1024})\n    Secret function:\n    f(x) = <1, 1, 1, 1, 1, 0>\n    \n    Should be a constant function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                  \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    3: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    4: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    5: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    6: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'000000': 1024})\n    Secret function:\n    f(x) = <1, 1, 1, 1, 1, 0, 1>\n    \n    Should be a constant function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                  \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    3: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    4: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    5: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    6: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    7: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'0000000': 1024})\n    Secret function:\n    f(x) = <0, 1, 1, 0, 0, 1, 1, 0>\n    \n    Should be a constant function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                  \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    3: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    4: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    5: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    6: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    7: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    8: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'00000000': 1024})\n    Secret function:\n    f(x) = <0, 1, 1, 1, 0, 0, 1, 1, 1>\n    \n    Should be a constant function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                  \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    2: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    3: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    4: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    5: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    6: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    7: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\n    8: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    9: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'000000000': 1024})\n    Secret function:\n    f(x) = <1, 0, 1, 0, 0, 1, 0, 1, 1, 1>\n    \n    Should be a constant function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    10: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'0000000000': 1024})\n    Secret function:\n    f(x) = <0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1>\n    \n    Should be a constant function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    11: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'00000000000': 1024})\n    Secret function:\n    f(x) = <0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0>\n    \n    Should be a constant function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    12: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'000000000000': 1024})\n    Secret function:\n    f(x) = <0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0>\n    \n    Should be a constant function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    13: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'0000000000000': 1024})\n    Secret function:\n    f(x) = <0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1>\n    \n    Should be a constant function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    13: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    14: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'00000000000000': 1024})\n    Secret function:\n    f(x) = <0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1>\n    \n    Should be a constant function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    13: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    14: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    15: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'000000000000000': 1024})\n    Secret function:\n    f(x) = <1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0>\n    \n    Should be a constant function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    13: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    14: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    15: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    16: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'0000000000000000': 1024})\n    Secret function:\n    f(x) = <1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1>\n    \n    Should be a constant function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    13: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    14: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    15: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    16: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    17: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'00000000000000000': 1024})\n    Secret function:\n    f(x) = <0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0>\n    \n    Should be a constant function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    13: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    14: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    15: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    16: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    17: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    18: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'000000000000000000': 1024})\n    Secret function:\n    f(x) = <1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0>\n    \n    Should be a constant function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    13: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    14: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    15: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    16: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    17: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    18: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    19: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'0000000000000000000': 1024})\n    Secret function:\n    f(x) = <1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0>\n    \n    Should be a constant function!\n    \n    Circuit:\n    0: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                   \u2502\n    1: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    2: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    3: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    4: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    5: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    6: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    7: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    8: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    9: \u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    10: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    11: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    12: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    13: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    14: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    15: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    16: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    17: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    18: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    19: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    20: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    Sampled results:\n    Counter({'00000000000000000000': 1024})\n\n\n\n```python\n# Plotting the time taken by the algorithm against the number of qubits in the circuit to analyze scalability of the algorithm\n\nplt.scatter(list(range(1,21)), t)\nplt.xlabel('Qubits')\nplt.ylabel('Time (in seconds)')\nplt.title(\" Time vs Qubits \")\nplt.show()\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "3f4099e5776d7a12ffdaad0bf697b6fa42944dc9", "size": 113978, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "DeutschJosza_Algorithm_Cirq.ipynb", "max_stars_repo_name": "ananyoemon/Quantum-Algorithms", "max_stars_repo_head_hexsha": "1707b67e1181c0b9ddee32de6fb150109caa5119", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DeutschJosza_Algorithm_Cirq.ipynb", "max_issues_repo_name": "ananyoemon/Quantum-Algorithms", "max_issues_repo_head_hexsha": "1707b67e1181c0b9ddee32de6fb150109caa5119", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DeutschJosza_Algorithm_Cirq.ipynb", "max_forks_repo_name": "ananyoemon/Quantum-Algorithms", "max_forks_repo_head_hexsha": "1707b67e1181c0b9ddee32de6fb150109caa5119", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 72.8759590793, "max_line_length": 10810, "alphanum_fraction": 0.3448472512, "converted": true, "num_tokens": 28243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.06954174305954322, "lm_q1q2_score": 0.021143588039916797}}
{"text": "# Data Visualization for Exploration\n\nThis notebook details data visualization for exploring a dataset. The goal is to understand more about the data as a human, not to make beautiful graphs, communicate, or feature engineering input into models.\n\n\n```python\nimport pandas as pd\nimport numpy as np\nimport scipy.stats as st\n\n#ggplot equivalent: plotnine\nfrom plotnine import *\n\n#scales package equivalent: mizani\nfrom mizani.breaks import *\nfrom mizani.formatters import *\n\n#widgets\nfrom ipywidgets import interact, interactive, fixed, interact_manual\nimport ipywidgets as widgets\n\n#utility\nimport utils\ndef clean_comma(x): return float(str(x).replace(',',''))\n```\n\n\n```python\n'''\nSnippet for plotnine with thai font by @korakot\nhttps://gist.github.com/korakot/01d181229b21411b0a20784e0ca20d3d\n'''\nimport matplotlib\n# !wget https://github.com/Phonbopit/sarabun-webfont/raw/master/fonts/thsarabunnew-webfont.ttf -q\n# !cp thsarabunnew-webfont.ttf /usr/share/fonts/truetype/\nmatplotlib.font_manager._rebuild()\nmatplotlib.rc('font', family='TH Sarabun New')\ntheme_set(theme_minimal(11, 'TH Sarabun New'));\n```\n\n\n```python\ndf = pd.read_csv('data/taladrod.csv')\ndf['sales_price'] = df.sales_price.map(clean_comma)\ndf['market_price'] = df.market_price.map(clean_comma)\ndf.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>id</th>\n      <th>brand</th>\n      <th>series</th>\n      <th>model</th>\n      <th>gen</th>\n      <th>year</th>\n      <th>color</th>\n      <th>gear</th>\n      <th>gas</th>\n      <th>sales_price</th>\n      <th>original_price</th>\n      <th>market_price</th>\n      <th>description</th>\n      <th>contact_location</th>\n      <th>subscribers</th>\n      <th>scraped_date</th>\n      <th>removed_date</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>2210000</td>\n      <td>HONDA</td>\n      <td>JAZZ</td>\n      <td>1.5 i-VTEC SV (AS)</td>\n      <td>\u0e1b\u0e3508-13</td>\n      <td>2014.0</td>\n      <td>\u0e2a\u0e35\u0e02\u0e32\u0e27</td>\n      <td>\u0e40\u0e01\u0e35\u0e22\u0e23\u0e4c\u0e2d\u0e2d\u0e42\u0e15\u0e49</td>\n      <td>NaN</td>\n      <td>488000.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>\u0e40\u0e04\u0e23\u0e14\u0e34\u0e15\u0e14\u0e35\u0e2d\u0e2d\u0e01\u0e23\u0e1610,000\u0e08\u0e1a\u0e04\u0e23\u0e31\u0e1a\\n\u0e23\u0e31\u0e1a\u0e1b\u0e23\u0e30\u0e01\u0e31\u0e19\u0e40\u0e04\u0e23\u0e37\u0e48\u0e2d\u0e07\u0e40\u0e01\u0e35...</td>\n      <td>\u0e01\u0e23\u0e38\u0e07\u0e40\u0e17\u0e1e\u0e2f</td>\n      <td>1047.0</td>\n      <td>2019-05-22</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2210001</td>\n      <td>TOYOTA</td>\n      <td>ESTIMA</td>\n      <td>2.4 G HYBRID</td>\n      <td>\u0e1b\u0e3510-\u0e1b\u0e31\u0e08\u0e08\u0e38\u0e1a\u0e31\u0e19</td>\n      <td>2013.0</td>\n      <td>\u0e2a\u0e35\u0e02\u0e32\u0e27</td>\n      <td>\u0e40\u0e01\u0e35\u0e22\u0e23\u0e4c\u0e2d\u0e2d\u0e42\u0e15\u0e49</td>\n      <td>NaN</td>\n      <td>1677000.0</td>\n      <td>NaN</td>\n      <td>3050000.0</td>\n      <td>TOP\u0e2a\u0e38\u0e14 Estima Aeras Hybrid \u0e23\u0e16\u0e40\u0e02\u0e49\u0e32\u0e40\u0e0b\u0e2d\u0e23\u0e4c\u0e27\u0e34\u0e2a TOYO...</td>\n      <td>\u0e01\u0e23\u0e38\u0e07\u0e40\u0e17\u0e1e\u0e2f</td>\n      <td>182.0</td>\n      <td>2019-05-22</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2210009</td>\n      <td>HONDA</td>\n      <td>JAZZ</td>\n      <td>1.5 i-VTEC V (AS)</td>\n      <td>\u0e1b\u0e3508-13</td>\n      <td>2008.0</td>\n      <td>\u0e2a\u0e35\u0e19\u0e49\u0e33\u0e40\u0e07\u0e34\u0e19</td>\n      <td>\u0e40\u0e01\u0e35\u0e22\u0e23\u0e4c\u0e2d\u0e2d\u0e42\u0e15\u0e49</td>\n      <td>NaN</td>\n      <td>338000.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>\u0e40\u0e04\u0e23\u0e14\u0e34\u0e14\u0e35\u0e2d\u0e2d\u0e01\u0e23\u0e1610,000\u0e08\u0e1a\u0e04\u0e23\u0e31\u0e1a\\n\u0e23\u0e31\u0e1a\u0e1b\u0e23\u0e30\u0e01\u0e31\u0e19\u0e40\u0e04\u0e23\u0e37\u0e48\u0e2d\u0e07\u0e40\u0e01\u0e35\u0e22...</td>\n      <td>\u0e01\u0e23\u0e38\u0e07\u0e40\u0e17\u0e1e\u0e2f</td>\n      <td>1047.0</td>\n      <td>2019-05-22</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>2210012</td>\n      <td>FORD</td>\n      <td>RANGER</td>\n      <td>2.2 WILDTRAK DBL CAB HI-RIDER</td>\n      <td>DOUBLECAB</td>\n      <td>2016.0</td>\n      <td>\u0e2a\u0e35\u0e02\u0e32\u0e27</td>\n      <td>\u0e40\u0e01\u0e35\u0e22\u0e23\u0e4c\u0e2d\u0e2d\u0e42\u0e15\u0e49</td>\n      <td>NaN</td>\n      <td>689000.0</td>\n      <td>NaN</td>\n      <td>849000.0</td>\n      <td>\u0e23\u0e31\u0e1a\u0e23\u0e2d\u0e07\u0e2a\u0e20\u0e32\u0e1e \u0e44\u0e21\u0e48\u0e21\u0e35\u0e0a\u0e19 \u0e21\u0e37\u0e2d\u0e40\u0e14\u0e35\u0e22\u0e27 \u0e1e\u0e32\u0e0a\u0e48\u0e32\u0e07\u0e21\u0e32\u0e15\u0e23\u0e27\u0e08\u0e2a\u0e20\u0e32\u0e1e\u0e23\u0e16...</td>\n      <td>\u0e01\u0e23\u0e38\u0e07\u0e40\u0e17\u0e1e\u0e2f</td>\n      <td>760.0</td>\n      <td>2019-05-22</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>2210016</td>\n      <td>TOYOTA</td>\n      <td>SOLUNA</td>\n      <td>VIOS 1.5 E (ABS+AB)</td>\n      <td>VIOS \u0e1b\u0e3513-\u0e1b\u0e31\u0e08\u0e08\u0e38\u0e1a\u0e31\u0e19</td>\n      <td>2015.0</td>\n      <td>\u0e2a\u0e35\u0e1a\u0e23\u0e2d\u0e19\u0e0b\u0e4c\u0e40\u0e07\u0e34\u0e19</td>\n      <td>\u0e40\u0e01\u0e35\u0e22\u0e23\u0e4c\u0e2d\u0e2d\u0e42\u0e15\u0e49</td>\n      <td>NaN</td>\n      <td>359000.0</td>\n      <td>NaN</td>\n      <td>649000.0</td>\n      <td>\u0e44\u0e21\u0e25\u0e4c\u0e41\u0e17\u0e49 99,xxx TOYOTA SOLUNA VIOS 1.5E\\nTOYOTA...</td>\n      <td>\u0e01\u0e23\u0e38\u0e07\u0e40\u0e17\u0e1e\u0e2f</td>\n      <td>699.0</td>\n      <td>2019-05-22</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Warming Up: Missing Values\n\nWe use grammar of graphics implementation `ggplot` (ported to Python as `plotnine`) to explore the `taladrod` dataset. Grammar of graphics is an especially useful tool since we do not know exactly what kind of plots we want to see and want to be able to add them up as we go.\n\n\nSource: [A Comprehensive Guide to the Grammar of Graphics for Effective Visualization of Multi-dimensional Data](https://towardsdatascience.com/a-comprehensive-guide-to-the-grammar-of-graphics-for-effective-visualization-of-multi-dimensional-1f92b4ed4149)\n\n\n```python\nmissing = utils.check_missing(df)\nmissing['over90'] = missing.per_missing.map(lambda x: True if x>0.9 else False)\nmissing.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>col_name</th>\n      <th>per_missing</th>\n      <th>rnk</th>\n      <th>over90</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>original_price</td>\n      <td>0.991380</td>\n      <td>00_original_price</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>gas</td>\n      <td>0.936525</td>\n      <td>01_gas</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>removed_date</td>\n      <td>0.886728</td>\n      <td>02_removed_date</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>market_price</td>\n      <td>0.561658</td>\n      <td>03_market_price</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>subscribers</td>\n      <td>0.000641</td>\n      <td>04_subscribers</td>\n      <td>False</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ng = (ggplot(missing,aes(x='rnk',y='per_missing',fill='over90')) + #base plot\n     geom_col() + #type of plot \n     geom_text(aes(x='rnk',y='per_missing+0.1',label='round(100*per_missing,2)')) +#annotate\n     scale_y_continuous(labels=percent_format()) + #y-axis tick\n     theme_minimal() + coord_flip()#theme and flipping plot\n    )\ng\n```\n\n\n```python\n#drop columns with too many missing values\ndf.drop(missing[missing.over90==True].col_name,1,inplace=True)\ndf.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>id</th>\n      <th>brand</th>\n      <th>series</th>\n      <th>model</th>\n      <th>gen</th>\n      <th>year</th>\n      <th>color</th>\n      <th>gear</th>\n      <th>sales_price</th>\n      <th>market_price</th>\n      <th>description</th>\n      <th>contact_location</th>\n      <th>subscribers</th>\n      <th>scraped_date</th>\n      <th>removed_date</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>2210000</td>\n      <td>HONDA</td>\n      <td>JAZZ</td>\n      <td>1.5 i-VTEC SV (AS)</td>\n      <td>\u0e1b\u0e3508-13</td>\n      <td>2014.0</td>\n      <td>\u0e2a\u0e35\u0e02\u0e32\u0e27</td>\n      <td>\u0e40\u0e01\u0e35\u0e22\u0e23\u0e4c\u0e2d\u0e2d\u0e42\u0e15\u0e49</td>\n      <td>488000.0</td>\n      <td>NaN</td>\n      <td>\u0e40\u0e04\u0e23\u0e14\u0e34\u0e15\u0e14\u0e35\u0e2d\u0e2d\u0e01\u0e23\u0e1610,000\u0e08\u0e1a\u0e04\u0e23\u0e31\u0e1a\\n\u0e23\u0e31\u0e1a\u0e1b\u0e23\u0e30\u0e01\u0e31\u0e19\u0e40\u0e04\u0e23\u0e37\u0e48\u0e2d\u0e07\u0e40\u0e01\u0e35...</td>\n      <td>\u0e01\u0e23\u0e38\u0e07\u0e40\u0e17\u0e1e\u0e2f</td>\n      <td>1047.0</td>\n      <td>2019-05-22</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2210001</td>\n      <td>TOYOTA</td>\n      <td>ESTIMA</td>\n      <td>2.4 G HYBRID</td>\n      <td>\u0e1b\u0e3510-\u0e1b\u0e31\u0e08\u0e08\u0e38\u0e1a\u0e31\u0e19</td>\n      <td>2013.0</td>\n      <td>\u0e2a\u0e35\u0e02\u0e32\u0e27</td>\n      <td>\u0e40\u0e01\u0e35\u0e22\u0e23\u0e4c\u0e2d\u0e2d\u0e42\u0e15\u0e49</td>\n      <td>1677000.0</td>\n      <td>3050000.0</td>\n      <td>TOP\u0e2a\u0e38\u0e14 Estima Aeras Hybrid \u0e23\u0e16\u0e40\u0e02\u0e49\u0e32\u0e40\u0e0b\u0e2d\u0e23\u0e4c\u0e27\u0e34\u0e2a TOYO...</td>\n      <td>\u0e01\u0e23\u0e38\u0e07\u0e40\u0e17\u0e1e\u0e2f</td>\n      <td>182.0</td>\n      <td>2019-05-22</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2210009</td>\n      <td>HONDA</td>\n      <td>JAZZ</td>\n      <td>1.5 i-VTEC V (AS)</td>\n      <td>\u0e1b\u0e3508-13</td>\n      <td>2008.0</td>\n      <td>\u0e2a\u0e35\u0e19\u0e49\u0e33\u0e40\u0e07\u0e34\u0e19</td>\n      <td>\u0e40\u0e01\u0e35\u0e22\u0e23\u0e4c\u0e2d\u0e2d\u0e42\u0e15\u0e49</td>\n      <td>338000.0</td>\n      <td>NaN</td>\n      <td>\u0e40\u0e04\u0e23\u0e14\u0e34\u0e14\u0e35\u0e2d\u0e2d\u0e01\u0e23\u0e1610,000\u0e08\u0e1a\u0e04\u0e23\u0e31\u0e1a\\n\u0e23\u0e31\u0e1a\u0e1b\u0e23\u0e30\u0e01\u0e31\u0e19\u0e40\u0e04\u0e23\u0e37\u0e48\u0e2d\u0e07\u0e40\u0e01\u0e35\u0e22...</td>\n      <td>\u0e01\u0e23\u0e38\u0e07\u0e40\u0e17\u0e1e\u0e2f</td>\n      <td>1047.0</td>\n      <td>2019-05-22</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>2210012</td>\n      <td>FORD</td>\n      <td>RANGER</td>\n      <td>2.2 WILDTRAK DBL CAB HI-RIDER</td>\n      <td>DOUBLECAB</td>\n      <td>2016.0</td>\n      <td>\u0e2a\u0e35\u0e02\u0e32\u0e27</td>\n      <td>\u0e40\u0e01\u0e35\u0e22\u0e23\u0e4c\u0e2d\u0e2d\u0e42\u0e15\u0e49</td>\n      <td>689000.0</td>\n      <td>849000.0</td>\n      <td>\u0e23\u0e31\u0e1a\u0e23\u0e2d\u0e07\u0e2a\u0e20\u0e32\u0e1e \u0e44\u0e21\u0e48\u0e21\u0e35\u0e0a\u0e19 \u0e21\u0e37\u0e2d\u0e40\u0e14\u0e35\u0e22\u0e27 \u0e1e\u0e32\u0e0a\u0e48\u0e32\u0e07\u0e21\u0e32\u0e15\u0e23\u0e27\u0e08\u0e2a\u0e20\u0e32\u0e1e\u0e23\u0e16...</td>\n      <td>\u0e01\u0e23\u0e38\u0e07\u0e40\u0e17\u0e1e\u0e2f</td>\n      <td>760.0</td>\n      <td>2019-05-22</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>2210016</td>\n      <td>TOYOTA</td>\n      <td>SOLUNA</td>\n      <td>VIOS 1.5 E (ABS+AB)</td>\n      <td>VIOS \u0e1b\u0e3513-\u0e1b\u0e31\u0e08\u0e08\u0e38\u0e1a\u0e31\u0e19</td>\n      <td>2015.0</td>\n      <td>\u0e2a\u0e35\u0e1a\u0e23\u0e2d\u0e19\u0e0b\u0e4c\u0e40\u0e07\u0e34\u0e19</td>\n      <td>\u0e40\u0e01\u0e35\u0e22\u0e23\u0e4c\u0e2d\u0e2d\u0e42\u0e15\u0e49</td>\n      <td>359000.0</td>\n      <td>649000.0</td>\n      <td>\u0e44\u0e21\u0e25\u0e4c\u0e41\u0e17\u0e49 99,xxx TOYOTA SOLUNA VIOS 1.5E\\nTOYOTA...</td>\n      <td>\u0e01\u0e23\u0e38\u0e07\u0e40\u0e17\u0e1e\u0e2f</td>\n      <td>699.0</td>\n      <td>2019-05-22</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Categorical Variables\n\nWe want to know primarily two things about our categorical variables:\n1. How each variable is distributed\n2. How each variable relate to the dependent variable\n    * 2.1 when dependent variable is numerical\n    * 2.2 when dependent variable is categorical\n\n\n```python\ncat_vars = ['brand','series','gen','color','gear','contact_location']\ncat_df = df[cat_vars].copy()\ncat_df.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>brand</th>\n      <th>series</th>\n      <th>gen</th>\n      <th>color</th>\n      <th>gear</th>\n      <th>contact_location</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>HONDA</td>\n      <td>JAZZ</td>\n      <td>\u0e1b\u0e3508-13</td>\n      <td>\u0e2a\u0e35\u0e02\u0e32\u0e27</td>\n      <td>\u0e40\u0e01\u0e35\u0e22\u0e23\u0e4c\u0e2d\u0e2d\u0e42\u0e15\u0e49</td>\n      <td>\u0e01\u0e23\u0e38\u0e07\u0e40\u0e17\u0e1e\u0e2f</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>TOYOTA</td>\n      <td>ESTIMA</td>\n      <td>\u0e1b\u0e3510-\u0e1b\u0e31\u0e08\u0e08\u0e38\u0e1a\u0e31\u0e19</td>\n      <td>\u0e2a\u0e35\u0e02\u0e32\u0e27</td>\n      <td>\u0e40\u0e01\u0e35\u0e22\u0e23\u0e4c\u0e2d\u0e2d\u0e42\u0e15\u0e49</td>\n      <td>\u0e01\u0e23\u0e38\u0e07\u0e40\u0e17\u0e1e\u0e2f</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>HONDA</td>\n      <td>JAZZ</td>\n      <td>\u0e1b\u0e3508-13</td>\n      <td>\u0e2a\u0e35\u0e19\u0e49\u0e33\u0e40\u0e07\u0e34\u0e19</td>\n      <td>\u0e40\u0e01\u0e35\u0e22\u0e23\u0e4c\u0e2d\u0e2d\u0e42\u0e15\u0e49</td>\n      <td>\u0e01\u0e23\u0e38\u0e07\u0e40\u0e17\u0e1e\u0e2f</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>FORD</td>\n      <td>RANGER</td>\n      <td>DOUBLECAB</td>\n      <td>\u0e2a\u0e35\u0e02\u0e32\u0e27</td>\n      <td>\u0e40\u0e01\u0e35\u0e22\u0e23\u0e4c\u0e2d\u0e2d\u0e42\u0e15\u0e49</td>\n      <td>\u0e01\u0e23\u0e38\u0e07\u0e40\u0e17\u0e1e\u0e2f</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>TOYOTA</td>\n      <td>SOLUNA</td>\n      <td>VIOS \u0e1b\u0e3513-\u0e1b\u0e31\u0e08\u0e08\u0e38\u0e1a\u0e31\u0e19</td>\n      <td>\u0e2a\u0e35\u0e1a\u0e23\u0e2d\u0e19\u0e0b\u0e4c\u0e40\u0e07\u0e34\u0e19</td>\n      <td>\u0e40\u0e01\u0e35\u0e22\u0e23\u0e4c\u0e2d\u0e2d\u0e42\u0e15\u0e49</td>\n      <td>\u0e01\u0e23\u0e38\u0e07\u0e40\u0e17\u0e1e\u0e2f</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nTo simplify the data cleaning step, we \"otherify\" values that appear less than 3% of the time in all categorical columns.\n\n\n```python\n#otherify popular values; you can (should?) also have a mapping dict\nfor col in cat_vars: cat_df = utils.otherify(cat_df,col,th=0.03)\n```\n\n### Value Distribution\n\nEven without plotting them out, we can see the value distribution in each variable using `ipywidgets`.\n\n\n```python\ninteract(utils.value_dist, df =fixed(cat_df),\n         col = widgets.Dropdown(options=list(cat_df.columns),value='brand'))\n```\n\n\n    interactive(children=(Dropdown(description='col', options=('brand', 'series', 'gen', 'color', 'gear', 'contact\u2026\n\n\n\n\n\n    <function utils.value_dist(df, col)>\n\n\n\n**Exercise** Implement `cat_plot` function that plots value distribution for each categorical variable.\n\n\n```python\ndef cat_plot(df,col):\n    return utils.cat_plot(df,col) \n#input dataframe and column\n#output histogram plot of value distribution\n\ninteract(cat_plot, df=fixed(cat_df),\n         col = widgets.Dropdown(options=list(cat_df.columns),value='brand'))\n```\n\n\n    interactive(children=(Dropdown(description='col', options=('brand', 'series', 'gen', 'color', 'gear', 'contact\u2026\n\n\n\n\n\n    <function __main__.cat_plot(df, col)>\n\n\n\n\n```python\n#excluding others\ndef cat_plot_noothers(df,col):\n    x = df.copy()\n    x = x[x[col]!='others']\n    return utils.cat_plot(x,col) + utils.thai_text(8)\n\ninteract(cat_plot_noothers, df=fixed(cat_df),\n         col = widgets.Dropdown(options=list(cat_df.columns),value='gen'))\n```\n\n\n    interactive(children=(Dropdown(description='col', index=2, options=('brand', 'series', 'gen', 'color', 'gear',\u2026\n\n\n\n\n\n    <function __main__.cat_plot_noothers(df, col)>\n\n\n\n### Numerical and Categorical Variables\n\n\n```python\n#relationship between dependent variable and categorical variable\ncat_df['sales_price'] = utils.boxcox(df['sales_price'])\ncat_df.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>brand</th>\n      <th>series</th>\n      <th>gen</th>\n      <th>color</th>\n      <th>gear</th>\n      <th>contact_location</th>\n      <th>sales_price</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>HONDA</td>\n      <td>others</td>\n      <td>\u0e1b\u0e3508-13</td>\n      <td>\u0e2a\u0e35\u0e02\u0e32\u0e27</td>\n      <td>\u0e40\u0e01\u0e35\u0e22\u0e23\u0e4c\u0e2d\u0e2d\u0e42\u0e15\u0e49</td>\n      <td>\u0e01\u0e23\u0e38\u0e07\u0e40\u0e17\u0e1e\u0e2f</td>\n      <td>13.056226</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>TOYOTA</td>\n      <td>others</td>\n      <td>others</td>\n      <td>\u0e2a\u0e35\u0e02\u0e32\u0e27</td>\n      <td>\u0e40\u0e01\u0e35\u0e22\u0e23\u0e4c\u0e2d\u0e2d\u0e42\u0e15\u0e49</td>\n      <td>\u0e01\u0e23\u0e38\u0e07\u0e40\u0e17\u0e1e\u0e2f</td>\n      <td>14.320520</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>HONDA</td>\n      <td>others</td>\n      <td>\u0e1b\u0e3508-13</td>\n      <td>others</td>\n      <td>\u0e40\u0e01\u0e35\u0e22\u0e23\u0e4c\u0e2d\u0e2d\u0e42\u0e15\u0e49</td>\n      <td>\u0e01\u0e23\u0e38\u0e07\u0e40\u0e17\u0e1e\u0e2f</td>\n      <td>12.669810</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>FORD</td>\n      <td>others</td>\n      <td>others</td>\n      <td>\u0e2a\u0e35\u0e02\u0e32\u0e27</td>\n      <td>\u0e40\u0e01\u0e35\u0e22\u0e23\u0e4c\u0e2d\u0e2d\u0e42\u0e15\u0e49</td>\n      <td>\u0e01\u0e23\u0e38\u0e07\u0e40\u0e17\u0e1e\u0e2f</td>\n      <td>13.413541</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>TOYOTA</td>\n      <td>SOLUNA</td>\n      <td>others</td>\n      <td>\u0e2a\u0e35\u0e1a\u0e23\u0e2d\u0e19\u0e0b\u0e4c\u0e40\u0e07\u0e34\u0e19</td>\n      <td>\u0e40\u0e01\u0e35\u0e22\u0e23\u0e4c\u0e2d\u0e2d\u0e42\u0e15\u0e49</td>\n      <td>\u0e01\u0e23\u0e38\u0e07\u0e40\u0e17\u0e1e\u0e2f</td>\n      <td>12.733758</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n#relationship between sales price and color\ncat_df.groupby('color').sales_price.describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>25%</th>\n      <th>50%</th>\n      <th>75%</th>\n      <th>max</th>\n    </tr>\n    <tr>\n      <th>color</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>others</th>\n      <td>1756.0</td>\n      <td>12.568359</td>\n      <td>1.019319</td>\n      <td>0.000000</td>\n      <td>12.072547</td>\n      <td>12.542548</td>\n      <td>13.028055</td>\n      <td>16.905644</td>\n    </tr>\n    <tr>\n      <th>\u0e2a\u0e35\u0e02\u0e32\u0e27</th>\n      <td>4207.0</td>\n      <td>13.085453</td>\n      <td>0.940839</td>\n      <td>0.000000</td>\n      <td>12.672950</td>\n      <td>13.005832</td>\n      <td>13.498058</td>\n      <td>16.438729</td>\n    </tr>\n    <tr>\n      <th>\u0e2a\u0e35\u0e14\u0e33</th>\n      <td>2848.0</td>\n      <td>13.071142</td>\n      <td>0.913027</td>\n      <td>0.000000</td>\n      <td>12.594734</td>\n      <td>13.014780</td>\n      <td>13.535466</td>\n      <td>16.111071</td>\n    </tr>\n    <tr>\n      <th>\u0e2a\u0e35\u0e19\u0e49\u0e33\u0e15\u0e32\u0e25</th>\n      <td>607.0</td>\n      <td>12.660002</td>\n      <td>0.814474</td>\n      <td>8.853808</td>\n      <td>12.144203</td>\n      <td>12.782689</td>\n      <td>13.140205</td>\n      <td>15.635210</td>\n    </tr>\n    <tr>\n      <th>\u0e2a\u0e35\u0e1a\u0e23\u0e2d\u0e19\u0e0b\u0e4c\u0e40\u0e07\u0e34\u0e19</th>\n      <td>1879.0</td>\n      <td>12.760100</td>\n      <td>0.923268</td>\n      <td>0.000000</td>\n      <td>12.421188</td>\n      <td>12.779876</td>\n      <td>13.151924</td>\n      <td>15.854130</td>\n    </tr>\n    <tr>\n      <th>\u0e2a\u0e35\u0e40\u0e17\u0e32</th>\n      <td>2740.0</td>\n      <td>12.786451</td>\n      <td>0.957211</td>\n      <td>0.000000</td>\n      <td>12.421188</td>\n      <td>12.818555</td>\n      <td>13.188621</td>\n      <td>17.822480</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n**Exercise** Implement `numcat_plot` function that plots the relationship between a dependent numerical variable and an independent categorical as displayed above. Useful geoms are `geom_boxplot`, `geom_violin` and `geom_jitter`. Optionally remove outliers before plotting.\n\n\n```python\ndef numcat_plot(df,num,cat, no_outliers=True, geom=geom_boxplot()):\n    return utils.numcat_plot(df,num,cat, no_outliers, geom) \n#plot the summary above\n```\n\n\n```python\ninteract(numcat_plot, \n         df=fixed(cat_df),\n         num=fixed('sales_price'),\n         no_outliers = widgets.Checkbox(value=True),\n         geom=fixed(geom_boxplot()), #geom_violin, geom_jitter\n         cat= widgets.Dropdown(options=list(cat_df.columns)[:-1],value='gen'))\n```\n\n\n    interactive(children=(Dropdown(description='cat', index=2, options=('brand', 'series', 'gen', 'color', 'gear',\u2026\n\n\n\n\n\n    <function __main__.numcat_plot(df, num, cat, no_outliers=True, geom=<plotnine.geoms.geom_boxplot.geom_boxplot object at 0x7fa9a455f358>)>\n\n\n\n\n```python\ninteract(numcat_plot, \n         df=fixed(cat_df),\n         num=fixed('sales_price'),\n         no_outliers = widgets.Checkbox(value=True),\n         geom=fixed(geom_violin()), #geom_violin, geom_jitter\n         cat= widgets.Dropdown(options=list(cat_df.columns)[:-1],value='series'))\n```\n\n\n    interactive(children=(Dropdown(description='cat', index=1, options=('brand', 'series', 'gen', 'color', 'gear',\u2026\n\n\n\n\n\n    <function __main__.numcat_plot(df, num, cat, no_outliers=True, geom=<plotnine.geoms.geom_boxplot.geom_boxplot object at 0x7fa9a455f358>)>\n\n\n\nSometimes we want to see the numerical distribution filled with categories. This is especially useful plotting the results of a binary classification.\n\n\n```python\ndef numdist_plot(df, num,cat, geom=geom_density(alpha=0.5), no_outliers=True):\n    return utils.numdist_plot(df, num, cat, geom, no_outliers)\n\n#either\n#density: geom_density(alpha=0.5)\n#histogram: geom_histogram(binwidth=0.5, position='identity',alpha=0.5) \n#position: identity or dodge\nnumdist_plot(cat_df,'sales_price','gear')\n```\n\n\n```python\nnumdist_plot(cat_df,'sales_price','gear',\n             geom=geom_histogram(binwidth=0.5, position='dodge',alpha=0.5))\n```\n\n### Categorical and Categorical Variables\n\n**Exercise** We can cross-tabulate categorical variables to see their relationship by using `facet_wrap`; for instance, if our dependent variable is `gear` and indpendent variable of interest is `color`.\n\n\n```python\ndef catcat_plot(df, cat_dep, cat_ind):\n    return utils.catcat_plot(df,cat_dep,cat_ind)\n```\n\n\n```python\ninteract(catcat_plot, \n         df=fixed(cat_df),\n         cat_dep=widgets.Dropdown(options=list(cat_df.columns)[:-1],value='gear'),\n         cat_ind= widgets.Dropdown(options=list(cat_df.columns)[:-1],value='color'))\n```\n\n\n    interactive(children=(Dropdown(description='cat_dep', index=4, options=('brand', 'series', 'gen', 'color', 'ge\u2026\n\n\n\n\n\n    <function __main__.catcat_plot(df, cat_dep, cat_ind)>\n\n\n\n### Multiple Ways of Relationships\n\nYou can use `facet_grid` to display multiple ways of relationships; but keep in mind that this is probably what your model is doing anyways so it might not be most human-readable plot to explore.\n\n\n```python\n#getting fancy; not necessarily the best idea\nnew_df = utils.remove_outliers(cat_df,'sales_price')\ng = (ggplot(new_df, aes(x='gen',y='sales_price')) +\n     geom_boxplot() + theme_minimal() +\n     facet_grid('contact_location~color') +\n     theme(axis_text_x = element_text(angle = 90, hjust = 1))\n    ) + utils.thai_text(8)\ng\n```\n\n## Numerical Variables\n\nWe want to know two things about numerical variables:\n1. Their distributions\n2. Their relationships with one another; possibly this involves transforming variables to make them less skewed aka more difficult to see variations\n\n\n```python\nimport datetime\nnow = datetime.datetime.now()\ndf['nb_year'] = now.year - df['year']\nnum_vars = ['nb_year','sales_price','market_price','subscribers']\nnum_df = df[num_vars].dropna() #this is why you need to deal with missing values BEFORE exploration\nnum_df.describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>nb_year</th>\n      <th>sales_price</th>\n      <th>market_price</th>\n      <th>subscribers</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>6150.000000</td>\n      <td>6.150000e+03</td>\n      <td>6.150000e+03</td>\n      <td>6150.000000</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>4.512195</td>\n      <td>7.120724e+05</td>\n      <td>1.333557e+06</td>\n      <td>525.634959</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>2.026358</td>\n      <td>7.745356e+05</td>\n      <td>1.288468e+06</td>\n      <td>386.841217</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>0.000000</td>\n      <td>1.000000e+00</td>\n      <td>3.690000e+05</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>3.000000</td>\n      <td>3.390010e+05</td>\n      <td>6.490000e+05</td>\n      <td>191.250000</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>5.000000</td>\n      <td>4.790010e+05</td>\n      <td>8.770000e+05</td>\n      <td>423.000000</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>6.000000</td>\n      <td>7.590010e+05</td>\n      <td>1.445000e+06</td>\n      <td>772.000000</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>8.000000</td>\n      <td>1.297000e+07</td>\n      <td>1.645000e+07</td>\n      <td>1469.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n`seaborn` has an excellent `pairplot` implementation which not only shows the distribution of values but also their relathionships. It seems like we can get what we want easily; however, as we can see `sales_price` and `market_price` are a little skewed, making it more difficult to see their relationships with other more spread out variables.\n\n\n```python\nimport seaborn as sns\nsns.pairplot(num_df) #non-normal data is a problem!\n```\n\nIn a lot of cases, a variable with normally distributed values have more variations and easier for us to see their relationships with other variables. We will try to transform our skewed variables to more \"normal\" ones to see if that helps.\n\n**Q-Q plot** compares two probability distributions by plotting their quantiles against each other. We can use this to determine the normality of a variable by plotting the sample quantiles (from the data we have) against its theoretical quantiles (where the quantiles would be if the variable is normally distributed).\n\n\n```python\ninteract(utils.qq_plot, df=fixed(num_df),\n         col=widgets.Dropdown(options=list(num_df.columns)))\n```\n\n\n    interactive(children=(Dropdown(description='col', options=('nb_year', 'sales_price', 'market_price', 'subscrib\u2026\n\n\n\n\n\n    <function utils.qq_plot(df, col)>\n\n\n\n**Box-Cox transformation** is a statistical technique used to make data look like more normally distributed.\n\n\\begin{align}\ng_\\lambda(y) = \\left\\{\n\\begin{array}{lr}\\displaystyle\\frac{y^\\lambda - 1}{\\lambda} &  \\lambda \\neq 0\\\\\n        & \\\\\n       \\log(y) &  \\lambda = 0\n     \\end{array}\n   \\right.\n\\end{align}\n\n**Exercise** Implement `boxcox` transformation according to the equation above.\n\n\n```python\ndef boxcox(ser,lamb=0):\n    pass\n#input a column from pandas dataframe\n#output transformed column\n```\n\nOne way of choosing the hyperparameter $\\lambda$ is to look at the Q-Q plot and choose transformation which makes the slope closest to 1.\n\n\n```python\n#see transformation results\ndef what_lamb(df,col,lamb):\n    sample_df = df.copy()\n    former_g = utils.qq_plot(sample_df,col)\n    sample_df[col] = utils.boxcox(sample_df[col],lamb)\n    print(utils.qq_plot(sample_df,col),former_g)\n    \ninteract(what_lamb, df=fixed(num_df),\n         col=widgets.Dropdown(options=list(num_df.columns),value='sales_price'),\n         lamb=widgets.FloatSlider(min=-3,max=3,step=0.5,value=0)\n         )\n```\n\n\n    interactive(children=(Dropdown(description='col', index=1, options=('nb_year', 'sales_price', 'market_price', \u2026\n\n\n\n\n\n    <function __main__.what_lamb(df, col, lamb)>\n\n\n\nThis can also be automated by plotting a slope for each arbitary $\\lambda$; for instance from -3 to 3.\n\n\n```python\nlamb_df = utils.boxcox_lamb_df(num_df.subscribers)\ninteract(utils.boxcox_plot, df=fixed(num_df),\n         col=widgets.Dropdown(options=list(num_df.columns),value='sales_price'),\n         ls=fixed([i/10 for i in range(-30,31,5)])\n         )\n```\n\n\n    interactive(children=(Dropdown(description='col', index=1, options=('nb_year', 'sales_price', 'market_price', \u2026\n\n\n\n\n\n    <function utils.boxcox_plot(df, col, ls=[-3.0, -2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0])>\n\n\n\n\n```python\n#transform sales and market prices\nfor col in ['sales_price','market_price']:\n    num_df['new_'+col] = utils.boxcox(num_df[col], utils.boxcox_lamb(num_df[col]))\n```\n\nYou can see that post transformation, we can see the (lack of) relationships between variables clearer.\n\n\n```python\nsns.pairplot(num_df[['nb_year','new_sales_price','new_market_price','subscribers']]) #a little better!\n```\n\nFor our example, we have only four numerical variables; but imagine when you have ten or more. You may want to plot their distributions separately from relationships.\n\n\n```python\nnum_m = num_df.melt()\nnum_m.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>variable</th>\n      <th>value</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>nb_year</td>\n      <td>6.0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>nb_year</td>\n      <td>3.0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>nb_year</td>\n      <td>4.0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>nb_year</td>\n      <td>4.0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>nb_year</td>\n      <td>7.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n**Exercise** Implement `value_dist_plot` to plot value distribution of all variables.\n\n\n```python\ndef value_dist_plot(df,bins=30):\n    return utils.value_dist_plot(df,bins)\n#input dataframe with only numerical variables\n#output distribution plot for each variable\nvalue_dist_plot(num_df)\n```\n\nLikewise in case there are too many pairs of relationships, you might plot the relationships pair-by-pair with `ipywidget` and `seaborn`'s `jointplot` function.\n\n\n```python\ninteract(utils.jointplot, df=fixed(num_df),\n         col_x= widgets.Dropdown(options=list(num_df.columns),value='sales_price'),\n         col_y=widgets.Dropdown(options=list(num_df.columns),value='market_price'),\n         kind=widgets.Dropdown(options=['scatter','resid','reg','hex','kde','point'],value='scatter'))\n```\n\n\n    interactive(children=(Dropdown(description='col_x', index=1, options=('nb_year', 'sales_price', 'market_price'\u2026\n\n\n\n\n\n    <function utils.jointplot(df, col_x, col_y, no_outliers=True, kind='reg')>\n\n\n\nAs you might have noticed, we have not used any statistical concept to describe the relationship, and that is by design. We can also see correlation table with a simple `pandas` function:\n\n\n```python\n#correlation plot if you must; but it's just ONE number for the relationship\nnum_df.corr(method='pearson').style.background_gradient(cmap='coolwarm') \n```\n\n\n\n\n<style  type=\"text/css\" >\n    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow0_col0 {\n            background-color:  #b40426;\n            color:  #f1f1f1;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow0_col1 {\n            background-color:  #3b4cc0;\n            color:  #f1f1f1;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow0_col2 {\n            background-color:  #4a63d3;\n            color:  #f1f1f1;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow0_col3 {\n            background-color:  #84a7fc;\n            color:  #000000;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow0_col4 {\n            background-color:  #3b4cc0;\n            color:  #f1f1f1;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow0_col5 {\n            background-color:  #3b4cc0;\n            color:  #f1f1f1;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow1_col0 {\n            background-color:  #465ecf;\n            color:  #f1f1f1;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow1_col1 {\n            background-color:  #b40426;\n            color:  #f1f1f1;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow1_col2 {\n            background-color:  #df634e;\n            color:  #000000;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow1_col3 {\n            background-color:  #3b4cc0;\n            color:  #f1f1f1;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow1_col4 {\n            background-color:  #c0282f;\n            color:  #f1f1f1;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow1_col5 {\n            background-color:  #e97a5f;\n            color:  #000000;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow2_col0 {\n            background-color:  #7ea1fa;\n            color:  #000000;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow2_col1 {\n            background-color:  #d95847;\n            color:  #000000;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow2_col2 {\n            background-color:  #b40426;\n            color:  #f1f1f1;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow2_col3 {\n            background-color:  #3e51c5;\n            color:  #f1f1f1;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow2_col4 {\n            background-color:  #d95847;\n            color:  #000000;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow2_col5 {\n            background-color:  #c73635;\n            color:  #f1f1f1;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow3_col0 {\n            background-color:  #aec9fc;\n            color:  #000000;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow3_col1 {\n            background-color:  #5e7de7;\n            color:  #000000;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow3_col2 {\n            background-color:  #3b4cc0;\n            color:  #f1f1f1;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow3_col3 {\n            background-color:  #b40426;\n            color:  #f1f1f1;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow3_col4 {\n            background-color:  #7b9ff9;\n            color:  #000000;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow3_col5 {\n            background-color:  #4a63d3;\n            color:  #f1f1f1;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow4_col0 {\n            background-color:  #3b4cc0;\n            color:  #f1f1f1;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow4_col1 {\n            background-color:  #c12b30;\n            color:  #f1f1f1;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow4_col2 {\n            background-color:  #df634e;\n            color:  #000000;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow4_col3 {\n            background-color:  #4b64d5;\n            color:  #f1f1f1;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow4_col4 {\n            background-color:  #b40426;\n            color:  #f1f1f1;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow4_col5 {\n            background-color:  #da5a49;\n            color:  #000000;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow5_col0 {\n            background-color:  #7da0f9;\n            color:  #000000;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow5_col1 {\n            background-color:  #e36b54;\n            color:  #000000;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow5_col2 {\n            background-color:  #c53334;\n            color:  #f1f1f1;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow5_col3 {\n            background-color:  #5b7ae5;\n            color:  #000000;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow5_col4 {\n            background-color:  #d44e41;\n            color:  #000000;\n        }    #T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow5_col5 {\n            background-color:  #b40426;\n            color:  #f1f1f1;\n        }</style><table id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0b\" ><thead>    <tr>        <th class=\"blank level0\" ></th>        <th class=\"col_heading level0 col0\" >nb_year</th>        <th class=\"col_heading level0 col1\" >sales_price</th>        <th class=\"col_heading level0 col2\" >market_price</th>        <th class=\"col_heading level0 col3\" >subscribers</th>        <th class=\"col_heading level0 col4\" >new_sales_price</th>        <th class=\"col_heading level0 col5\" >new_market_price</th>    </tr></thead><tbody>\n                <tr>\n                        <th id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0blevel0_row0\" class=\"row_heading level0 row0\" >nb_year</th>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow0_col0\" class=\"data row0 col0\" >1</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow0_col1\" class=\"data row0 col1\" >-0.220633</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow0_col2\" class=\"data row0 col2\" >-0.00786656</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow0_col3\" class=\"data row0 col3\" >0.163404</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow0_col4\" class=\"data row0 col4\" >-0.275434</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow0_col5\" class=\"data row0 col5\" >-0.0152819</td>\n            </tr>\n            <tr>\n                        <th id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0blevel0_row1\" class=\"row_heading level0 row1\" >sales_price</th>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow1_col0\" class=\"data row1 col0\" >-0.220633</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow1_col1\" class=\"data row1 col1\" >1</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow1_col2\" class=\"data row1 col2\" >0.862739</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow1_col3\" class=\"data row1 col3\" >-0.07795</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow1_col4\" class=\"data row1 col4\" >0.955499</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow1_col5\" class=\"data row1 col5\" >0.819534</td>\n            </tr>\n            <tr>\n                        <th id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0blevel0_row2\" class=\"row_heading level0 row2\" >market_price</th>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow2_col0\" class=\"data row2 col0\" >-0.00786656</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow2_col1\" class=\"data row2 col1\" >0.862739</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow2_col2\" class=\"data row2 col2\" >1</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow2_col3\" class=\"data row2 col3\" >-0.063786</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow2_col4\" class=\"data row2 col4\" >0.858924</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow2_col5\" class=\"data row2 col5\" >0.948289</td>\n            </tr>\n            <tr>\n                        <th id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0blevel0_row3\" class=\"row_heading level0 row3\" >subscribers</th>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow3_col0\" class=\"data row3 col0\" >0.163404</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow3_col1\" class=\"data row3 col1\" >-0.07795</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow3_col2\" class=\"data row3 col2\" >-0.063786</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow3_col3\" class=\"data row3 col3\" >1</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow3_col4\" class=\"data row3 col4\" >-0.0165204</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow3_col5\" class=\"data row3 col5\" >0.039791</td>\n            </tr>\n            <tr>\n                        <th id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0blevel0_row4\" class=\"row_heading level0 row4\" >new_sales_price</th>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow4_col0\" class=\"data row4 col0\" >-0.275434</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow4_col1\" class=\"data row4 col1\" >0.955499</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow4_col2\" class=\"data row4 col2\" >0.858924</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow4_col3\" class=\"data row4 col3\" >-0.0165204</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow4_col4\" class=\"data row4 col4\" >1</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow4_col5\" class=\"data row4 col5\" >0.882803</td>\n            </tr>\n            <tr>\n                        <th id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0blevel0_row5\" class=\"row_heading level0 row5\" >new_market_price</th>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow5_col0\" class=\"data row5 col0\" >-0.0152819</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow5_col1\" class=\"data row5 col1\" >0.819534</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow5_col2\" class=\"data row5 col2\" >0.948289</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow5_col3\" class=\"data row5 col3\" >0.039791</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow5_col4\" class=\"data row5 col4\" >0.882803</td>\n                        <td id=\"T_1d00e18a_85e2_11e9_b01d_1d76819b2e0brow5_col5\" class=\"data row5 col5\" >1</td>\n            </tr>\n    </tbody></table>\n\n\n\n\n```python\ndef pearson_corr(x,y):\n    sub_x = x - x.mean()\n    sub_y = y - y.mean()\n    return (sub_x * sub_y).sum() / np.sqrt((sub_x**2).sum() * (sub_y**2).sum())\n\n#spearman and kendall: pearson with rank variables\npearson_corr(df.nb_year,df.sales_price)\n```\n\n\n\n\n    -0.23316757399518453\n\n\n\nHowever, the famous Anscombe plots show us that it is always better to look at distribution rather than a summary number.\n\n\n\nSource: [A Comprehensive Guide to the Grammar of Graphics for Effective Visualization of Multi-dimensional Data](https://towardsdatascience.com/a-comprehensive-guide-to-the-grammar-of-graphics-for-effective-visualization-of-multi-dimensional-1f92b4ed4149)\n\n\n```python\n\n```\n", "meta": {"hexsha": "de350b3300f8b437c8458892d71d7e3db3b9ec26", "size": 573415, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "explore.ipynb", "max_stars_repo_name": "cstorm125/viztech", "max_stars_repo_head_hexsha": "12242554885f7e78068f97854d98c6c95caf8768", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 81, "max_stars_repo_stars_event_min_datetime": "2019-05-29T15:26:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-24T07:29:36.000Z", "max_issues_repo_path": "explore.ipynb", "max_issues_repo_name": "tanlull/viztech", "max_issues_repo_head_hexsha": "12242554885f7e78068f97854d98c6c95caf8768", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "explore.ipynb", "max_forks_repo_name": "tanlull/viztech", "max_forks_repo_head_hexsha": "12242554885f7e78068f97854d98c6c95caf8768", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2019-06-05T16:34:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-08T17:23:11.000Z", "avg_line_length": 251.4978070175, "max_line_length": 168324, "alphanum_fraction": 0.8994532756, "converted": true, "num_tokens": 14851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3040416875789104, "lm_q2_score": 0.06954173920278371, "lm_q1q2_score": 0.021143587744386832}}
{"text": "# NLBSE'22 Tool Competition\n\n### Introduction\n\nThe first edition of the NLBSE\u201922 tool competition is on automatic **issue report classification**, an important task in issue management and prioritization.\n\nFor the competition, we provide a dataset encompassing more than 800k labeled issue reports (as bugs, enhancements, and questions) extracted from real open-source projects. You are invited to leverage this dataset for evaluating your classification approaches and compare the achieved results against a proposed baseline approach (based on FastText).\n\n\n### Participation\n\nIf you want to participate, you must:\n* Train and tune a multi-label classifier using the provided [training set](https://tickettagger.blob.core.windows.net/datasets/github-labels-top3-803k-train.tar.gz).\n* Evaluate your classifier on the provided [test set](https://tickettagger.blob.core.windows.net/datasets/github-labels-top3-803k-test.tar.gz)\n* Write a paper (4 pages max.) describing:\n    * The architecture and details of the classifier\n    * The procedure used to pre-process the data\n    * The procedure used to tune the classifier on the training set\n    * The results of your classifier on the test set\n    * Additional info.: provide a link to your code/tool with proper documentation on how to run it\n* **Submit the paper** by the deadline (see below). **Email the paper to the tool competition organizers**: Oscar Chaparro (oscarch@wm.edu) and Rafael Kallis (rk@rafaelkallis.com) \n\nAll submissions must conform to the [ICSE\u201922 formatting and submission instructions](https://conf.researchr.org/track/icse-2022/icse-2022-papers#how-to-submit).\n\nPapers do not need to be double-blinded.\n\n### Important dates\n\n* Paper/tool submission: **February 21, 2022**\n* Acceptance and competition results notification: **March 4, 2022**\n* Camera-ready paper submission: **March 18, 2022**\n\nAll dates are anywhere on earth (AoE).\n\n\n\n### Submission acceptance and competition\n\nSubmissions will be evaluated and accepted based on **correctness** and **reproducibility**, defined by the following criteria:\n* Clarity and detail of the paper content\n* Availability of the code/tool, including the training/tuning/evaluation pipeline, released as open-source\n* Correct training/tuning/evaluation of your code/tool on the provided data\n* Report the metrics and results we outline below\n* Clarity of the code documentation\n\nThe accepted submissions will be published at the workshop proceedings.\n\nThe submissions will be ranked based on the $F_1$ score (defined below) achieved by the proposed classifiers on the test set, as indicated in the papers.\n\nThe submission with the highest $F_1$ score will be the winner of the competition.\n\n### Referencing\n\nSince you will be using our dataset (and possibly this Colab notebook) as well as the original work behind the dataset, please cite the following references in your paper:\n\n```\n@inproceedings{nlbse2022,\n  author={Kallis, Rafael and Chaparro, Oscar and Di Sorbo, Andrea and Panichella, Sebastiano},\n  title={NLBSE'22 Tool Competition},\n  booktitle={Proceedings of The 1st International Workshop on Natural Language-based Software Engineering (NLBSE'22)},\n  year={2022}\n}\n```\n\n```\n@article{ticket-tagger-scp,\n  author={Rafael Kallis and Andrea {Di Sorbo} and Gerardo Canfora and Sebastiano Panichella}\n  title={Predicting issue types on GitHub},\n  journal={Science of Computer Programming},\n  volume={205},\n  pages={102598},\n  year={2021},\n  issn={0167-6423},\n  doi={https://doi.org/10.1016/j.scico.2020.102598},\n  url={https://www.sciencedirect.com/science/article/pii/S0167642320302069}\n}\n  ```\n\n```\n@INPROCEEDINGS{ticket-tagger,\n  author={Kallis, Rafael and Di Sorbo, Andrea and Canfora, Gerardo and Panichella, Sebastiano},\n  booktitle={2019 IEEE International Conference on Software Maintenance and Evolution (ICSME)}, \n  title={Ticket Tagger: Machine Learning Driven Issue Classification}, \n  year={2019},\n  volume={},\n  number={},\n  pages={406-409},\n  doi={10.1109/ICSME.2019.00070}\n}\n  ```\n\n\n### Training \n\nYou are provided a [training set](https://tickettagger.blob.core.windows.net/datasets/github-labels-top3-803k-train.tar.gz) encompassing more than 700,000 labeled issue reports extracted from real open source projects. \n\nParticipants are free to select and transform variables from the training set as they please but **no new sources can be be added**.\nIn other words, any inputs or features used to create the classifier, must be derived from the provided training set.\nParticipants may preprocess, sample, apply over/under-sampling, select a subset of the attributes, perform feature-engineering, split the training set into a model-finetuning validation set, etc. Please contact us if you have any question about this.\n\nEach issue report contains the following metadata:\n- Label\n- Issue title\n- Issue body\n- Issue URL\n- Repository URL\n- Creation timestamp\n- Author association\n\nEach issue is labeled with one class that indicates the issue type, namely, bug, enhancement, and question.\n\nThe distribution of (722,899) issues in the training set is:\n* bug:            361,239 (50%)\n* enhancement:    299,287 (41.4%)\n* question:        62,373 (8.6%)\n\n### Evaluation \n\n> Note: for correct latex rendering, open this notebook in Collab.\n\nSubmissions are evaluated based on their class-detection performance over the provided [test set](https://tickettagger.blob.core.windows.net/datasets/github-labels-top3-803k-test.tar.gz). \n\nThe distribution of (80,518) issues in the test set:\n* bug:\t40,152\t(49.9%)\n* enhancement:\t33,290\t(41.3%)\n* question:\t7,076\t(8.8%)\n\nThe evaluation must be performed on the entire test set only. **Important:** you may apply any preprocessing or feature engineering on this dataset except sampling, rebalancing, undersampling or oversampling techniques.\n\nClassification performance is measured using the $F_1$ score over all the three classes. \n\nA submission (i.e., paper) in the tool competition must provide:\n- Precision $P_c$ for each class $c$\n- Recall $R_c$, for each class $c$\n- $F_{1,c}$ score as the harmonic mean between $P_c$ and $R_c$, for each class $c$\n- Precision $P$, micro-averaged $P_c$\n- Recall $R$, micro-averaged $R_c$\n- $F_1$ score as the harmonic mean between $P$ and $R$\n\nThese metrics are defined as follows:\n\\begin{align}\nP_c &= \\frac{ TP_c }{ TP_c + FP_c } & \nR_c &= \\frac{ TP_c }{ TP_c + FN_c } &\nF_{1,c} &= 2 \\cdot \\frac{ P_c \\cdot R_c }{ P_c + R_c }\\\\\nP &= \\frac{ \\sum_c TP_c }{ \\sum_c \\left( TP_c + FP_c \\right) } & \nR &= \\frac{ \\sum_c TP_c }{ \\sum_c \\left( TP_c + FN_c \\right) } &\nF_1 &= 2 \\cdot \\frac{ P \\cdot R }{ P + R }\n\\end{align}\n\nwhere $TP_c$, $FP_c$ and $FN_c$ represent true positives, false positives and false negatives over a class $c$, respectively.\nMicro-averaging was chosen as the cross-class aggregation method due to the class imbalance present in the data.\n\nPlease note that whilst all of the above measures must be provided for acceptance, the submissions will **only** be ranked by their $F_1$ score.\n\n### Colab Notebook\n\nColab notebooks provide a convenient format for publishing work and make it easier for readers to reproduce results. Colab provides an interactive Python runtime framework that can be accessed from a web browser. \nColab requires no configuration, provides free access to GPUs and allows for easy sharing between collaborators.\n\nParticipants can use a cloud-hosted infrastructure (recommended), connect to a local runtime or not use Colab at all. We do not impose any constraints on the technologies used. You can read more about Colab [here](https://colab.research.google.com/notebooks/intro.ipynb). An example of a GPU-accelerated Colab notebook can be found [here](https://colab.research.google.com/notebooks/gpu.ipynb).\n\n\n## Submission Template\n\nParticipants are encouraged, but not required, to use the following code as a template for their submission. \nThe example below trains a FastText model, which is provided as a baseline.\n\n\n```python\nimport os\nimport time\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport gensim\nimport sklearn.metrics\nfrom tqdm.auto import tqdm\n```\n\n\n```python\n# persistent file storage\n# https://colab.research.google.com/notebooks/io.ipynb\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n#### Training\n\n\n```python\n# download the training set if it does not exist\nif not os.path.isfile(\"github-labels-top3-803k-train.csv\"):\n  !curl \"https://tickettagger.blob.core.windows.net/datasets/github-labels-top3-803k-train.tar.gz\" | tar -xz\n\ntrainset = pd.read_csv(\"github-labels-top3-803k-train.csv\")\n```\n\n      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current\n                                     Dload  Upload   Total   Spent    Left  Speed\n      0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0tar: Ignoring unknown extended header keyword 'LIBARCHIVE.xattr.security.selinux'\n    100  236M  100  236M    0     0  7974k      0  0:00:30  0:00:30 --:--:-- 5912k\n\n\n\n```python\ntrainset.head(5)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Unnamed: 0</th>\n      <th>issue_url</th>\n      <th>issue_label</th>\n      <th>issue_created_at</th>\n      <th>issue_author_association</th>\n      <th>repository_url</th>\n      <th>issue_title</th>\n      <th>issue_body</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0</td>\n      <td>https://api.github.com/repos/eamodio/vscode-gi...</td>\n      <td>bug</td>\n      <td>2021-01-02T18:07:30Z</td>\n      <td>NONE</td>\n      <td>https://api.github.com/repos/eamodio/vscode-gi...</td>\n      <td>Welcome screen on every editor window is very ...</td>\n      <td>I just discovered Gitlens and find the functio...</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>https://api.github.com/repos/binwiederhier/pco...</td>\n      <td>bug</td>\n      <td>2020-12-31T18:19:31Z</td>\n      <td>OWNER</td>\n      <td>https://api.github.com/repos/binwiederhier/pcopy</td>\n      <td>\"pcopy invite\" and \"pcopy paste abc:\" does not...</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2</td>\n      <td>https://api.github.com/repos/binwiederhier/pco...</td>\n      <td>bug</td>\n      <td>2021-01-03T04:33:36Z</td>\n      <td>OWNER</td>\n      <td>https://api.github.com/repos/binwiederhier/pcopy</td>\n      <td>UI: Modal overlay is half transparent, shouldn...</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>3</td>\n      <td>https://api.github.com/repos/Sothatsit/RoyalUr...</td>\n      <td>enhancement</td>\n      <td>2020-12-25T00:46:00Z</td>\n      <td>OWNER</td>\n      <td>https://api.github.com/repos/Sothatsit/RoyalUr...</td>\n      <td>Make the loading screen scale with browser win...</td>\n      <td>Currently the loading wheel is a fixed size in...</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>4</td>\n      <td>https://api.github.com/repos/Malivil/TTT-Custo...</td>\n      <td>bug</td>\n      <td>2021-01-02T21:36:57Z</td>\n      <td>OWNER</td>\n      <td>https://api.github.com/repos/Malivil/TTT-Custo...</td>\n      <td>Spectator - Investigate a way to strip weapons...</td>\n      <td>To bring magneto stick floating</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ntrainset.groupby(\"issue_label\").size()\n```\n\n\n\n\n    issue_label\n    bug            361103\n    enhancement    299374\n    question        62422\n    dtype: int64\n\n\n\n\n```python\n# preprocessing can be customized by participants\ndef preprocess(row):\n  # concatenate title and body, then remove whitespaces\n  doc = \"\"\n  doc += str(row.issue_title)\n  doc += \" \"\n  doc += str(row.issue_body)\n  # https://radimrehurek.com/gensim/parsing/preprocessing.html\n  doc = gensim.parsing.preprocessing.strip_multiple_whitespaces(doc)\n  return doc\n```\n\n\n```python\n# transform dataset into fasttext format\n# https://fasttext.cc/docs/en/supervised-tutorial.html#getting-and-preparing-the-data\n\n# rng used to split training set into fasttext hyperparameter finetuning validation set (2 of 9 parts)\nrandom = np.random.default_rng(0)\n\nwith open(\"train.txt\", \"w\") as train_f, open(\"valid.txt\", \"w\") as valid_f:\n  for row in tqdm(trainset.itertuples(), desc=\"Transform to fastText format\", total=len(trainset)):\n    doc = f\"__label__{row.issue_label} {preprocess(row)}\\n\"\n    is_train = random.uniform() < 7/9\n    f = train_f if is_train else valid_f\n    f.write(doc)\n\n!wc -l \"valid.txt\"\n!wc -l \"train.txt\"\n\n!head -n 10 \"train.txt\"\n```\n\n\n    Transform to fastText format:   0%|          | 0/722899 [00:00<?, ?it/s]\n\n\n    160535 valid.txt\n    562364 train.txt\n    __label__bug Welcome screen on every editor window is very tedious I just discovered Gitlens and find the functionality useful, thank you to all who contribute. I have about a dozen editor windows open, and the install process added a Gitlens welcome tab to each and every one of them. Combined with the snowflake effect, all of the sudden VScode was consuming 300-400% cpu and my fan was raging, as soon as I hunted them all down everything was back to fine. The welcome note content is great (although putting it on _all_ the windows is a bit much, don't know how much control you have on that). But overall it was a bit of a sour first-use experience, just wanted to provide that feedback.\n    __label__bug \"pcopy invite\" and \"pcopy paste abc:\" does not check if clipboard exists nan\n    __label__bug UI: Modal overlay is half transparent, shouldn't be nan\n    __label__enhancement Make the loading screen scale with browser window size Currently the loading wheel is a fixed size in pixels, but it would be better to specify it in terms of percentage of the browser size.\n    __label__bug Correct navigation bar for some resolution  \n    __label__enhancement Return asset growth Would have to cache: - Stock Ticker Request - Last Price at request - Channel that the ticker was requested from (to dedupe issues)\n    __label__enhancement Add filter for logs Add the ability to filter logs like on other pages.\n    __label__enhancement Help bubbles nan\n    __label__bug Nvidia Boot Error This doesn't really affect me, more of a doubt if this is normal to happen. I get this screen 100% when turning my customac on:  Pastebin: https://pastebin.com/0jtUHJgm Cheers!\n    __label__bug catAxisLabelPos and valAxisLabelPos options are not working Hi team , I set the two options of `cataxislabelpos` and `valaxislabelpos`, but they didn't seem to work.Below is my code.  ``` let dataChartAreaLine = [ { name: \"Actual Sales\", labels: [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"], values: [1500, 4600, 5156, 3167, 8510, 8009, 6006, 7855, 12102, 12789, 10123, 15121], }, { name: \"Projected Sales\", labels: [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"], values: [1000, 2600, 3456, 4567, 5010, 6009, 7006, 8855, 9102, 10789, 11123, 12121], }, ]; slide.addChart(\"line\", dataChartAreaLine, { x: 1, y: 1, w: 8, h: 4, catAxisLabelPos: \"high\", valAxisLabelPos: \"high\" }); ```\n\n\n\n```python\n!pip install fasttext\nimport fasttext\n\n# https://fasttext.cc/docs/en/python-module.html#train_supervised-parameters\nmodel = fasttext.train_supervised(\"train.txt\", \n                                  minCount=50,\n                                  autotuneValidationFile=\"valid.txt\",\n                                  autotuneDuration=5*60)\nmodel.quantize()\nmodel.save_model(f\"github-labels-{int(time.time())}.ftz\")\nmodel.save_model(f\"drive/MyDrive/github-labels-{int(time.time())}.ftz\")\nmodel\n```\n\n    Collecting fasttext\n      Downloading fasttext-0.9.2.tar.gz (68 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 68 kB 5.6 MB/s  eta 0:00:01\n    \u001b[?25hCollecting pybind11>=2.2\n      Using cached pybind11-2.8.1-py2.py3-none-any.whl (208 kB)\n    Requirement already satisfied: setuptools>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from fasttext) (57.4.0)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from fasttext) (1.19.5)\n    Building wheels for collected packages: fasttext\n      Building wheel for fasttext (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for fasttext: filename=fasttext-0.9.2-cp37-cp37m-linux_x86_64.whl size=3125036 sha256=2cc2f0c1c6329a77a2f14306152305ca06ecf1a961014e6d0b760ba85b657746\n      Stored in directory: /root/.cache/pip/wheels/4e/ca/bf/b020d2be95f7641801a6597a29c8f4f19e38f9c02a345bab9b\n    Successfully built fasttext\n    Installing collected packages: pybind11, fasttext\n    Successfully installed fasttext-0.9.2 pybind11-2.8.1\n\n\n\n\n\n    <fasttext.FastText._FastText at 0x7f072b9246d0>\n\n\n\n#### Evaluation\n\n\n```python\nif not os.path.isfile(\"github-labels-top3-803k-test.csv\"):\n  !curl \"https://tickettagger.blob.core.windows.net/datasets/github-labels-top3-803k-test.tar.gz\" | tar -xz\n\ntestset = pd.read_csv(\"github-labels-top3-803k-test.csv\")\ntestset.groupby(\"issue_label\").size()\n#testset\n\n```\n\n      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current\n                                     Dload  Upload   Total   Spent    Left  Speed\n      0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0tar: Ignoring unknown extended header keyword 'LIBARCHIVE.xattr.security.selinux'\n    100 27.2M  100 27.2M    0     0  9192k      0  0:00:03  0:00:03 --:--:-- 9192k\n\n\n\n\n\n    issue_label\n    bug            40288\n    enhancement    33203\n    question        7027\n    dtype: int64\n\n\n\n\n```python\n# confusion matrix\ny_true = []\ny_pred = []\n\nfor row in tqdm(testset.itertuples(), desc=\"Benchmarking Inference Performance\", total=len(testset)):\n  pred = model.predict(preprocess(row))[0][0][9:]\n  y_true.append(row.issue_label)\n  y_pred.append(pred)\n\nfor label in [\"bug\", \"enhancement\", \"question\"]:\n  P_c = sklearn.metrics.precision_score(y_true, y_pred, average=None, labels=[label])[0]\n  R_c = sklearn.metrics.recall_score(y_true, y_pred, average=None, labels=[label])[0]\n  F1_c = sklearn.metrics.f1_score(y_true, y_pred, average=None, labels=[label])[0]\n  print(f\"=*= {label} =*=\")\n  print(f\"precision:\\t{P_c:.4f}\")\n  print(f\"recall:\\t\\t{R_c:.4f}\")\n  print(f\"F1 score:\\t{F1_c:.4f}\")\n  print()\n\n\nP = sklearn.metrics.precision_score(y_true, y_pred, average='micro')\nR = sklearn.metrics.recall_score(y_true, y_pred, average='micro')\nF1 = sklearn.metrics.f1_score(y_true, y_pred, average='micro')\n\nprint(\"=*= global =*=\")\nprint(f\"precision:\\t{P:.4f}\")\nprint(f\"recall:\\t\\t{R:.4f}\")\nprint(f\"F1 score:\\t{F1:.4f}\")\n```\n\n\n    Benchmarking Inference Performance:   0%|          | 0/80518 [00:00<?, ?it/s]\n\n\n    =*= bug =*=\n    precision:\t0.8314\n    recall:\t\t0.8725\n    F1 score:\t0.8515\n    \n    =*= enhancement =*=\n    precision:\t0.8155\n    recall:\t\t0.8464\n    F1 score:\t0.8307\n    \n    =*= question =*=\n    precision:\t0.6521\n    recall:\t\t0.3502\n    F1 score:\t0.4557\n    \n    =*= global =*=\n    precision:\t0.8162\n    recall:\t\t0.8162\n    F1 score:\t0.8162\n\n", "meta": {"hexsha": "8426122666aea6d32ace5b4c50405c7df19a30ce", "size": 51909, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/nlbse_tool_competition_template.ipynb", "max_stars_repo_name": "Shikhar-S/Issue-Classifier", "max_stars_repo_head_hexsha": "f3e3fc39bab8708274679dc60a1b92007d9d40e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-26T20:34:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T20:34:26.000Z", "max_issues_repo_path": "notebooks/nlbse_tool_competition_template.ipynb", "max_issues_repo_name": "Shikhar-S/Issue-Classifier", "max_issues_repo_head_hexsha": "f3e3fc39bab8708274679dc60a1b92007d9d40e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/nlbse_tool_competition_template.ipynb", "max_forks_repo_name": "Shikhar-S/Issue-Classifier", "max_forks_repo_head_hexsha": "f3e3fc39bab8708274679dc60a1b92007d9d40e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7682518419, "max_line_length": 951, "alphanum_fraction": 0.5783004874, "converted": true, "num_tokens": 5459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180267058489, "lm_q2_score": 0.054198724476223134, "lm_q1q2_score": 0.02106260135592383}}
{"text": "```python\n#default_exp asciidoc\n```\n\n# fastdoc.asciidoc\n> API for the fastdoc convertor\n\n\n```python\n#export\nfrom fastdoc.imports import *\nfrom fastcore.script import *\nfrom warnings import warn\n```\n\n\n```python\n#export\ndef markdown_cell(md):\n    return nbformat.notebooknode.NotebookNode({'cell_type': 'markdown', 'source': md, 'metadata': {}})\n```\n\n\n```python\n#export\ndef code_cell(code, metadata=None, outputs=None):\n    return nbformat.notebooknode.NotebookNode(\n        {'cell_type': 'code', \n         'execution_count': None,\n         'source': code, \n         'metadata': {} if metadata is None else metadata,\n         'outputs': [] if outputs is None else outputs})\n```\n\n## Preprocessing\n\n### Preprocessing on the list of all cells\n\nRemoving cells with the flag `# hide`\n\n\n```python\n#export\n_re_hidden = re.compile(r'^\\s*#\\s*(hide|clean)\\s*$', re.MULTILINE)\n```\n\n\n```python\n#export\ndef remove_hidden_cells(cells):\n    \"Remove cells marked with #hide\"\n    return [c for c in cells if _re_hidden.search(c['source']) is None]\n```\n\n\n```python\ncells = [code_cell('# hide'), code_cell('lalala'), markdown_cell('lalala\\n# hide')]\ntest_eq(remove_hidden_cells(cells), [code_cell('lalala')])\n```\n\nIsolating the bits in triple quotes annotated with asciidoc in code cells without outputs so that they are not interpreted by the converter, with adding `##clear##` so that the post-processing removes the `[python]` flag. \n\n\n```python\n#export\ndef isolate_adoc_blocks(cells):\n    res = []\n    for cell in cells:\n        if cell['cell_type'] == 'markdown' and re.search(r'```\\s*asciidoc', cell['source']) is not None:\n            lines = cell['source'].split('\\n')\n            adoc,s,idx = False,0,0\n            for line in lines:\n                if re.search(r'^```\\s*asciidoc\\s*$', line) is not None and not adoc:\n                    res.append(markdown_cell('\\n'.join(lines[s:idx])))\n                    adoc,s = True,idx+1\n                elif re.search(r'^```\\s*$', line) is not None and adoc:\n                    res.append(code_cell('##clear##' + '\\n'.join(lines[s:idx])))\n                    adoc,s = False,idx+1\n                idx+=1\n            assert not adoc, f\"Triple-quote asciidoc block not ended in {cell['source']}\"\n            res.append(markdown_cell('\\n'.join(lines[s:])))\n        else: res.append(cell)\n    return res\n```\n\n\n```python\ntest = \"\"\"This is some text\n```asciidoc\nThis should be isolated\n```\nSome other text\n```asciidoc\nThis should also be isolated\n```\nend\"\"\"\ntest_eq(isolate_adoc_blocks([markdown_cell(test)]), [\n    markdown_cell(\"This is some text\"),\n    code_cell(\"##clear##This should be isolated\"),\n    markdown_cell(\"Some other text\"),\n    code_cell(\"##clear##This should also be isolated\"),\n    markdown_cell(\"end\")\n])\n```\n\n### Preprocessing individual code cells\n\nOld way of putting `[WARNING]`, `[NOTE]` or `[TIP]`\n\n\n```python\n#export\n#TODO: remove when all notebooks have been ported to v2\ndef replace_old_jekylls(cell):\n    if cell['source'].startswith('jekyll'):\n        pat1 = re.compile(r\"\"\"jekyll_(.*)\\(['\"].*\"\"\")\n        pat2 = re.compile(r\"\"\"jekyll_.*\\(['\"]+([\\s\\S]*[^'\"])['\"]+\\)$\"\"\")\n        jekyll_type = re.match(pat1, cell['source']).groups()[0]\n        message = re.match(pat2, cell['source']).groups()[0]\n        inst = {'warn':'WARNING', 'note':'NOTE', 'important':'TIP'}\n        cell['metadata'] = {}\n        cell['source'] = f'##clear##[{inst[jekyll_type]}]\\n====\\n{message}\\n===='\n        cell['outputs'] = []\n    return cell\n```\n\n\n```python\ntest_eq(replace_old_jekylls(code_cell('jekyll_warn(\"\"\"Try to convert me!\"\"\")')), \n        code_cell('##clear##[WARNING]\\n====\\nTry to convert me!\\n===='))\n```\n\nHide input of cells with `hide_input=True` in metadata (extension hide input) or a flag `#hide_input`. Put `##remove##` instead of the code that will be removed during post-processing\n\n\n```python\n#export\n_re_hide_input = re.compile(r'^\\s*#\\s*hide_input\\s*$', re.MULTILINE)\n```\n\n\n```python\n#export\ndef hide_input(cell):\n    if cell['metadata'].get('hide_input', False) or _re_hide_input.search(cell[\"source\"]) is not None: cell['source'] = '##remove##'\n    return cell\n```\n\n\n```python\ntest_eq(hide_input(code_cell('some code', metadata={'hide_input': True}, outputs=[1])), \n        code_cell('##remove##', metadata={'hide_input': True}, outputs=[1]))\ntest_eq(hide_input(code_cell('# hide_input\\nsome code', outputs=[1])), \n        code_cell('##remove##', outputs=[1]))\n```\n\nHide outputs of cells with `collapsed=True` in their metadata or a flag #hide_output\n\n\n```python\n#export\n_re_hide_output = re.compile(r'^\\s*#\\s*hide_output\\s*$', re.MULTILINE)\n```\n\n\n```python\n#export\ndef hide_output(cell):\n    if cell['metadata'].get('collapsed', False) or _re_hide_output.search(cell[\"source\"]) is not None: \n        cell['outputs'] = []\n        cell['source'] = re.sub(r'#\\s*hide_output\\s*\\n', '', cell['source'])\n    return cell\n```\n\n\n```python\ntest_eq(hide_output(code_cell('some code', metadata={'collapsed': True}, outputs=[1])), \n        code_cell('some code', metadata={'collapsed': True}))\ntest_eq(hide_output(code_cell('# hide_output\\nsome code', outputs=[1])), \n        code_cell('some code'))\n```\n\nReplace outputs as `text_html` by `text_plain` (otherwise they are not kept)\n\n\n```python\n#export\ndef extract_html(cell):\n    for o in cell['outputs']:\n        if 'data' in o and 'text/html' in o['data']:\n            o['data']['text/plain'] = o['data']['text/html']\n            del o['data']['text/html']\n    return cell\n```\n\n\n```python\ntest_eq(extract_html(code_cell('some code', outputs=[{'data': {'text/html': 'some_html'}}])),\n        code_cell('some code', outputs=[{'data': {'text/plain': 'some_html'}}]))\n```\n\nDeal with errors by putting them in plain text\n\n\n```python\n#export\ndef split_max_len(text, l):\n    words = text.split(' ')\n    line,lines = \"\",[]\n    for word in words:\n        if len(line) + len(word) + 1 <= l: line += f' {word}'\n        else:\n            lines.append(line)\n            line = \"\"\n    if len(line) > 0: lines.append(line)\n    return \"\\n\".join(lines)\n```\n\n\n```python\n#export\ndef deal_error(cell):\n    for i,out in enumerate(cell['outputs']):\n        if out['output_type'] == 'error':\n            msg = f\"{out['ename']}: {out['evalue']}\"\n            cell['outputs'][i] = nbformat.notebooknode.NotebookNode({\n                'data': {'text/plain': split_max_len(msg, 81) },\n                'execution_count': None,\n                'metadata': {},\n                'output_type': 'execute_result'})\n    return cell\n```\n\n\n```python\ntest_eq(deal_error(code_cell('some code', outputs=[{'output_type': 'error', 'ename': 'Error name', 'evalue': 'This is an error.'}])), \n        code_cell('some code', outputs = [\n            {'data': {'text/plain': ' Error name: This is an error.'},\n             'execution_count': None,\n             'metadata': {},\n             'output_type': 'execute_result'}\n        ]))\n```\n\nRemove interrupted progress bars from the outputs\n\n\n```python\n#export\ndef remove_interrupted_pbars(cell):\n    outs = []\n    for out in cell['outputs']:\n        if 'data' not in out or 'text/plain' not in out['data'] or 'progress-bar-interrupted' not in out['data']['text/plain']:\n            outs.append(out)\n    cell['outputs'] = outs\n    return cell\n```\n\n\n```python\ntest_eq(remove_interrupted_pbars(\n    code_cell(\"some code\", outputs = [{'a': 1}, {'data': {'text/plain': 'progress-bar-interrupted'}}, {'b': 2}])),\n        code_cell(\"some code\", outputs = [{'a': 1}, {'b': 2}]))\n```\n\nGet metadata for outputs.\n\n\n```python\n#export\ndef get_cell_meta(cell):\n    for attr in [\"id\", \"caption\", \"alt\", \"width\"]:\n        if re.search(r'^\\s*#\\s*' + attr + r'\\s(.*)$', cell[\"source\"], re.MULTILINE) is not None:\n            cell[\"metadata\"][attr] = re.search(r'^\\s*#\\s*' + attr + r'\\s(.*)$', cell[\"source\"], re.MULTILINE).groups()[0]\n            cell[\"source\"] = re.sub(r'#\\s*' + attr + r'\\s.*?($|\\n)', '', cell[\"source\"])\n    return cell\n```\n\n\n```python\ntest_eq(get_cell_meta(code_cell(\"#id 123\\n#caption This is a bear\\nsome code\")), \n        code_cell(\"some code\", metadata = {'id': '123', 'caption': 'This is a bear'}))\n```\n\nDeal with table captions and refs\n\n\n```python\n#export\ndef caption_tables(cell):\n    if 'outputs' not in cell or len(cell['outputs']) == 0: return cell\n    output = cell['outputs'][0]\n    if 'data' not in output or 'text/plain' not in output['data']: return cell\n    text = output['data']['text/plain']\n    if re.search(r'^<\\s*table\\s+([^>]*>)', text) is None: return cell\n    table_id = cell['metadata'].get('id', None)\n    caption = cell['metadata'].get('caption', None)\n    text_id = '' if table_id is None else f'id=\"{table_id}\" '\n    text_caption = '' if caption is None else f'\\n  <caption>{caption}</caption>'\n    output['data']['text/plain'] = re.sub(r'^<\\s*table\\s+([^>]*>)', '<table '+text_id+r'\\1'+text_caption, text)\n    cell['outputs'][0] = output\n    return cell\n```\n\n\n```python\ncell = code_cell(\"some code\", \n    metadata={'id': '123', 'caption': 'a caption'},\n    outputs=[{'data': {'text/plain': '<table border=\"1\">\\nTable code'}}])\ncell2 = code_cell(\"some code\", \n    metadata={'id': '123', 'caption': 'a caption'},\n    outputs=[{'data': {'text/plain': '<table id=\"123\" border=\"1\">\\n  <caption>a caption</caption>\\nTable code'}}])\ntest_eq(caption_tables(cell), cell2)\n```\n\n\n```python\ncell = code_cell(\"#hide_input\\n#id 123\\n#caption a caption\", \n    metadata={},\n    outputs=[{'data': {'text/plain': '<table border=\"1\">\\nTable code'}, 'output_type':''}])\n```\n\nWrap text in outputs\n\n\n```python\n#export\nTEXT_MAX_WIDTH = 80\n```\n\n\n```python\n#export\ndef _wrap_output(output):\n    if 'text' in output:\n        lines = ['\\n'.join(textwrap.wrap(l, width=TEXT_MAX_WIDTH, subsequent_indent = ' > ')) for l in output['text'].split('\\n')]\n        output['text'] = '\\n'.join(lines)\n        return output\n    if ('data' not in output or 'text/plain' not in output['data']): return output\n    text = output['data']['text/plain']\n    if re.search(r'^<\\s*table\\s*([^>]*>)', text) is not None: return output\n    lines = ['\\n'.join(textwrap.wrap(l, width=TEXT_MAX_WIDTH, subsequent_indent = ' > ')) for l in text.split('\\n')]\n    output['data']['text/plain'] = '\\n'.join(lines)\n    return output\n```\n\n\n```python\n#export\ndef wrap_text_outputs(cell):\n    if 'outputs' not in cell or len(cell['outputs']) == 0: return cell\n    cell['outputs'] = [_wrap_output(o) for o in cell['outputs']]\n    return cell\n```\n\n\n```python\ncell = code_cell(\"some code\", \n    metadata={},\n    outputs=[{'data': {'text/plain': 'This is a long output'*5}, 'output_type':''},\n             {'text': 'This is a long output'*5}])\nwrapped = 'This is a long outputThis is a long outputThis is a long outputThis is a long\\n > outputThis is a long output'\ntest_eq(wrap_text_outputs(cell), code_cell(\"some code\", \n    metadata={},\n    outputs=[{'data': {'text/plain': wrapped}, 'output_type':''},\n             {'text': wrapped}]))\n```\n\nTest code length\n\n\n```python\n#export\nCODE_MAX_LEN = 81\n```\n\n\n```python\n#export\ndef check_code_len(cell):\n    lines = cell['source'].split('\\n')\n    for l in lines:\n        if len(l) > CODE_MAX_LEN: warn(f\"Found code too long in a cell:\\n{cell['source']}\")\n    return cell\n```\n\n### Preprocessing individual markdown cells\n\nReplace \"\\` \\`\" by \\`\\`\n\n\n```python\n#export\ndef deal_quotes(cell):\n    cell['source'] = re.sub(r'\"`([^`]*)`\"', r'`\\1`', cell['source'])\n    cell['source'] = re.sub(r\"'\", r'xxsinglequote', cell['source'])\n    return cell\n```\n\n\n```python\ntest_eq(deal_quotes(markdown_cell('\"`code`\"')), markdown_cell('`code`'))\ntest_eq(deal_quotes(markdown_cell('a\"b\"c')), markdown_cell('a\"b\"c'))\ntest_eq(deal_quotes(markdown_cell(\"a'b'c\")), markdown_cell('axxsinglequotebxxsinglequotec'))\n```\n\nAdd one title level to every Markdown cell\n\n\n```python\n#export\ndef add_title_level(cell):\n    if cell['source'].startswith('#'): cell['source'] = '#' + cell['source']\n    return cell\n```\n\n\n```python\ntest_eq(add_title_level(markdown_cell('# title')), markdown_cell('## title'))\n```\n\nConvert headers to asciidoc-style after they have been shifted one level by `add_title_level`\n\n\n```python\n#export\ndef title_to_asciidoc(cell):\n    _re_header = re.compile(r'^#+\\s+\\S+')\n    if _re_header.search(cell['source']) is not None:\n        src = cell['source'].lstrip('#')\n        src = ('=' * (len(cell['source']) - len(src))) + src\n        cell['source'] = src\n    return cell\n```\n\n\n```python\ntest_eq(title_to_asciidoc(markdown_cell('# title')), markdown_cell('= title'))\ntest_eq(title_to_asciidoc(markdown_cell('## title')), markdown_cell('== title'))\ntest_eq(title_to_asciidoc(markdown_cell('### title')), markdown_cell('=== title'))\ntest_eq(title_to_asciidoc(markdown_cell('#### title')), markdown_cell('==== title'))\ntest_eq(title_to_asciidoc(markdown_cell('##### title')), markdown_cell('===== title'))\ntest_eq(title_to_asciidoc(markdown_cell('#hide')), markdown_cell('#hide'))\ntest_eq(title_to_asciidoc(markdown_cell('#export')), markdown_cell('#export'))\n```\n\nRemove digits from numbered lists and format labeled lists\n\n\n```python\n#export\ndef deal_with_lists(cell):\n    lines = cell['source'].split('\\n')\n    for i in range(len(lines)): \n        lines[i] = re.sub(r'(^\\s*)\\d*\\.(.*)$', r'\\1.\\2xxnewl', lines[i])\n        lines[i] = re.sub(r'(^\\s*)-\\s(.*::)\\s(.*)$', r'\\2xxnewls\\3xxnewl', lines[i])\n        lines[i] = re.sub(r'(^\\s*)-\\s\\*\\*(.*):\\*\\*\\s(.*)$', r'\\2::xxnewls\\3xxnewl', lines[i])\n    cell['source'] = '\\n'.join(lines)\n    return cell\n```\n\n\n```python\ntest_eq(deal_with_lists(markdown_cell(\"  1. Item\\n  2. Item\")),\n        markdown_cell(\"  . Itemxxnewl\\n  . Itemxxnewl\"))\ntest_eq(deal_with_lists(markdown_cell(\"- lbl1:: item1\\n- lbl2:: item2\")),\n        markdown_cell(\"lbl1::xxnewlsitem1xxnewl\\nlbl2::xxnewlsitem2xxnewl\"))\ntest_eq(deal_with_lists(markdown_cell(\"- **lbl1:** item1\\n- **lbl2:** item2\")),\n        markdown_cell(\"lbl1::xxnewlsitem1xxnewl\\nlbl2::xxnewlsitem2xxnewl\"))\n```\n\nCatch block quotes and put them in asciidoc blocks\n\n\n```python\n#export\n_re_block_notes = re.compile(r\"\"\"\n# Catches any pattern > Title: content with title in group 1 and content in group 2\n^\\s*>\\s*     # > followed by any number of whitespace\n([^:]*)      # Catching group for any character but :\n:\\s*         # : then any number of whitespace\n([^\\n]*)     # Catching group for anything but a new line character\n(?:\\n|$)     # Non-catching group for either a new line or the end of the text\n\"\"\", re.VERBOSE | re.MULTILINE)\n\n_re_forgot_column = re.compile(\"^\\s*>[^:]*$\", re.MULTILINE)\n```\n\nHandle admonitions. Atlas supports notes, tips, and warnings.\n\n\n<div class=\"alert alert-info\">\nNote\n</div>\n\n<div class=\"alert alert-success\">\nTip\n</div>\n\n<div class=\"alert alert-danger\">\nWarning\n</div>\n\n\n```python\n#export\ndef replace_jekylls(cell):\n    block_names = {'warning':'WARNING', 'note':'NOTE', 'important':'TIP', 'tip': 'TIP', 'stop': 'WARNING',\n                   '**Warning**':'WARNING', '**Note**':'NOTE', '**TIP**':'TIP',\n                   'jargon':'JARGON', 'question':'QUESTION', 'a': 'ALEXIS', 'j': 'JEREMY', 's': 'SYLVAIN'}\n    def _rep(m):\n        typ,text = m.groups()\n        if text.startswith('**'): text = text[3:]\n        typ = typ.replace('**', '')\n        name = block_names.get(typ.lower(), typ.upper())\n        if name in ['ALEXIS', 'JEREMY', 'SYLVAIN', 'JARGON', 'QUESTION']:\n            title = name[0]+name[1:].lower()\n            surro = 'NOTE'\n            if name=='JARGON':\n                splits = text.split(': ')\n                title = f'{title}: {splits[0]}'\n                text = ': '.join(splits[1:])\n            if name in ['ALEXIS', 'JEREMY', 'SYLVAIN']: \n                title = f\"{title} says\"\n                surro = 'TIP'\n            return f'```asciidoc\\n.{title}\\n[{surro}]\\n====\\n{text}\\n====\\n```\\n'\n        elif len(name) != 0: return f\"```asciidoc\\n[{name}]\\n====\\n{text}\\n====\\n```\\n\"\n        else:              return f\"```asciidoc\\n____\\n{text}\\n____\\n```\\n\"\n    if _re_forgot_column.search(cell[\"source\"]): warn(\"Found a non-processed block quote: \")\n    cell[\"source\"] = _re_block_notes.sub(_rep, cell[\"source\"])\n    return cell\n```\n\n\n```python\ntest_eq(replace_jekylls(markdown_cell(\"text\\n> : This is a block quote\")),\n    markdown_cell(\"text\\n```asciidoc\\n____\\nThis is a block quote\\n____\\n```\\n\"))\ntest_eq(replace_jekylls(markdown_cell(\"text\\n> jargon: term: Some new term\")),\n    markdown_cell('text\\n```asciidoc\\n.Jargon: term\\n[NOTE]\\n====\\nSome new term\\n====\\n```\\n'))\ntest_eq(replace_jekylls(markdown_cell(\".Who's that Pokemon\\n> **Tip:** Some new definition\")),\n    markdown_cell(\".Who's that Pokemon\\n```asciidoc\\n[TIP]\\n====\\nSome new definition\\n====\\n```\\n\"))\ntest_warns(lambda: replace_jekylls(markdown_cell(\"text\\n> This is a block quote\")))\n```\n\n\n```python\n#export\n_re_sidebar = re.compile(r'^\\s*#\\s*sidebar\\s(.*)$', re.MULTILINE)\n```\n\n\n```python\n#export\ndef interpret_sidebar(cell):\n    lines = cell[\"source\"].split(\"\\n\")\n    if _re_sidebar.search(lines[0]) is not None:\n        title = _re_sidebar.search(lines[0]).groups()[0]\n        body = \"\\n\".join(lines[1:])\n        cell[\"source\"] = f\"```asciidoc\\n.{title}\\n****\\n{body}\\n****\\n```\\n\"\n    return cell\n```\n\n\n```python\ntest = \"\"\"#sidebar My intervention\n\nThis will be changed to a sidebar when converted in Asciidoc.\n\nIt can have several lines, contrary to a block quote.\"\"\"\ninterpret_sidebar(markdown_cell(test))\n```\n\n\n\n\n    {'cell_type': 'markdown',\n     'source': '```asciidoc\\n.My intervention\\n****\\n\\nThis will be changed to a sidebar when converted in Asciidoc.\\n\\nIt can have several lines, contrary to a block quote.\\n****\\n```\\n',\n     'metadata': {}}\n\n\n\n\n```python\n#export\n_re_html_image = re.compile(r\"^(]*>)\", re.MULTILINE)\n```\n\n\n```python\n#export\nIMAGE_CONV_MULT = 0.6\n```\n\n\n```python\n#export\ndef process_images(cell):\n    h = HTMLParseAttrs()\n    def _rep(m):\n        d = h(m.groups()[0])\n        attrs = ['\"' + d.get('alt', '') + '\"']\n        if 'width' in d: attrs.append(str(int(IMAGE_CONV_MULT * int(d['width']))))\n        if 'width' in d and 'height' in d: attrs.append(str((int(IMAGE_CONV_MULT * int(d['height'])))))\n        suff = f\"[{', '.join(attrs)}]\"\n        pid = f\"[[{d['id']}]]\\n\" if 'id' in d else \"\"\n        caption = f\".{d['caption']}\\n\" if 'caption' in d else \"\"\n        return f\"```asciidoc\\n{pid}{caption}image::{d['src']}{suff}\\n```\"\n    cell[\"source\"] = _re_html_image.sub(_rep, cell[\"source\"])\n    return cell\n```\n\n\n```python\ntxt = 'text\\n\\nother text'\ntest_eq(process_images(markdown_cell(txt)), \n        markdown_cell('text\\n```asciidoc\\n[[123]]\\n.This is an image\\nimage::puppy.jpg[\"Alternative text\", 420]\\n```\\nother text'))\n```\n\nFormat regular markdown style images making some assumptions about caption and id\n\n\n```python\n#export\n_re_md_image = re.compile(r'!\\[(.*)\\]\\((.+)\\)')\n```\n\n\n```python\n#export\ndef process_md_images(cell):\n    def _rep(m):\n        text = m.groups()[0]\n        src = m.groups()[1]\n        if not os.path.exists(src): warn(f\"Could not find image: {src}\")\n        suff = f'[\"{text}\"]'\n        fname = os.path.basename(src)\n        pid = f\"[[{os.path.splitext(fname)[0]}]]\\n\"\n        caption = f\".{text}\\n\"\n        return f\"```asciidoc\\n{pid}{caption}image::{src}{suff}\\n```\"\n    cell[\"source\"] = _re_md_image.sub(_rep, cell[\"source\"])\n    return cell\n```\n\n\n```python\ntxt = 'text\\n\\nother text'\ntest_eq(process_md_images(markdown_cell(txt)), \n        markdown_cell('text\\n```asciidoc\\n[[puppy]]\\n.This is an image\\nimage::images/puppy.jpg[\"This is an image\"]\\n```\\nother text'))\n```\n\n    <ipython-input-78-3427beca4fcb>:6: UserWarning: Could not find image: images/puppy.jpg\n      if not os.path.exists(src): warn(f\"Could not find image: {src}\")\n\n\nHandle cross-references\n\n\n```python\n#export\n\n# Old reference style\n# _re_reference = re.compile(r'<<([^>]*)>>')\n\n# Using double square brackets is more natural and doesn't\n# mess with suntax highligting. It's also similar to tools\n# like Roam reseach\n_re_reference = re.compile(r'\\[\\[([^>]*)\\]\\]')\n```\n\n\n```python\n#export\ndef wrap_references(cell):\n    cell[\"source\"] = _re_reference.sub(r'xxref\\1xxeref', cell[\"source\"])\n    return cell\n```\n\n\n```python\n# test_eq(wrap_references(markdown_cell(\"There is a reference <<ref>> here.\")),\n#         markdown_cell(\"There is a reference xxrefrefxxeref here.\"))\ntest_eq(wrap_references(markdown_cell(\"There is a reference [[ref]] here.\")),\n        markdown_cell(\"There is a reference xxrefrefxxeref here.\"))\n```\n\n\n```python\n#export\ndef extract_attachments(cell, dest):\n    if not 'attachments' in cell: return cell\n    mime,img = first(first(cell['attachments'].values()).items())\n    ext = mime.split('/')[1]\n    for i in range(99999):\n        p = dest/(f'att_{i:05d}.{ext}')\n        if not p.exists(): break\n    p.write_bytes(b64decode(img))\n    del(cell['attachments'])\n    cell['source'] = re.sub('attachment:image.png', str(p), cell['source'])\n    return cell\n```\n\nSidebars can also be delimitted to create a more natural look and feel in markdown. A markdown-rendered sidebar looks like this:\n\n****\n#### A Sidebar\n\nThis is a sidebar that contains some text. It can be **emphasized**, _underlined_, and `monospaced` as well.\n\n****\n\n\n```python\n#export\n\n# This is the original implementation of sidebar delimitters\n# _re_sidebar_title = re.compile(r'#+\\s+Sidebar:\\s+(.*)$', re.IGNORECASE)\n# _re_end_sidebar = re.compile(r'#+\\s+End sidebar', re.IGNORECASE)\n\n# We can instead use horizontal lines, which looks better in markdown anyway.\n_re_sidebar_title = re.compile(r'\\n*\\*\\*\\*\\*\\n#+\\s+(.*)$', re.IGNORECASE)\n_re_end_sidebar = re.compile(r'\\*\\*\\*\\*$', re.IGNORECASE)\n```\n\n\n```python\n_re_sidebar_title.search(\"****\\n### Sidebar: Tenacity in deep learning\").groups()\n```\n\n\n\n\n    ('Sidebar: Tenacity in deep learning',)\n\n\n\n\n```python\n#export\ndef sidebar_headers(cell):\n    cell['source'] = _re_sidebar_title.sub(r'```asciidoc\\n.\\1\\n****\\n```', cell['source'])\n    cell['source'] = _re_end_sidebar.sub(r'```asciidoc\\n****\\n```', cell['source'])\n    return cell\n```\n\n\n```python\ntest_eq(sidebar_headers(\n        markdown_cell(\"****\\n### My Intervention\")),\n        markdown_cell(\"```asciidoc\\n.My Intervention\\n****\\n```\")\n       )\ntest_eq(sidebar_headers(\n        markdown_cell(\"****\")),\n        markdown_cell(\"```asciidoc\\n****\\n```\")\n       )\n```\n\n### Preprocess individual raw cells\n\nRaw cells just need to have a new line added at the beginning\n\n\n```python\n#export\ndef add_new_line(cell):\n    cell['source'] = '\\n' + cell['source']\n    return cell\n```\n\nExpand `#include` statements in raw cells. This allows the inclusion of external markdown and asciidoc files in a notebook using a C-like `#include` syntax.\n\nInclude cells use the following syntax:\n```\n#include FILENAME.FILE_EXTENSION\n```\n\nWhere `FILE_EXTENSION` is either `md`, `asciidoc` or `adoc`. Include cells are expected to contain only include statements\n\n\n```python\n#export\n_re_include_md = re.compile(r'^#include\\s+.*\\.md$')\n_re_include_adoc = re.compile(r'^#include\\s+.*\\.(asciidoc|adoc)$')\n```\n\n\n```python\n#export\ndef expand_include(cell):\n    if _re_include_md.match(cell['source']):\n        cell['cell_type'] = 'markdown'\n        cell['source'] = open(re.compile(r'\\s+').split(cell['source'])[1]).read()\n    elif _re_include_adoc.match(cell['source']):\n        cell['source'] = open(re.compile(r'\\s+').split(cell['source'])[1]).read()\n    return cell\n```\n\n\n```python\ntest_eq(expand_include(markdown_cell('#include README.md'))['source'], open('README.md').read())\ntest_eq(expand_include(markdown_cell('#incl ude README.md'))['source'], '#incl ude README.md')\n```\n\n### All preprocessing together\n\n\n```python\n#export\ncode_cell_tfms = [get_cell_meta, replace_old_jekylls, hide_input, hide_output, extract_html, deal_error,\n                  remove_interrupted_pbars, wrap_text_outputs, caption_tables, check_code_len]\nmd_cell_tfms = [deal_quotes, wrap_references, interpret_sidebar, sidebar_headers, add_title_level,\n                title_to_asciidoc, deal_with_lists, replace_jekylls, process_md_images, process_images]\nraw_cell_tfms = [add_new_line, expand_include]\n```\n\n\n```python\n#export\ndef treat_notebook(nb, dest):\n    nb['cells'] = remove_hidden_cells(nb['cells'])\n    nb['cells'] = [(expand_include(c) if c['cell_type'] == 'raw' else c) for c in nb['cells']]\n    tfm_func = {'code': compose(*code_cell_tfms), 'markdown': compose(partial(extract_attachments, dest=dest), *md_cell_tfms),\n                'raw': compose(*raw_cell_tfms)}\n    nb['cells'] = [tfm_func[c['cell_type']](c) for c in nb['cells']]\n    nb['cells'] = isolate_adoc_blocks(nb['cells'])\n    return nb\n```\n\n## Post-processing\n\nReplace special tokens by their values\n\n\n```python\n#export\ndef rep_spec_tok(adoc, metadata=None):\n    adoc = re.sub('xxsinglequote', \"'\", adoc)\n    adoc = re.sub('xxnewls', '\\n  ', adoc)\n    return re.sub('xxnewl\\s', '\\n', adoc)\n```\n\nnbconvert will flag the code cells with `[ipython3]`, we replace this by `[python]`\n\n\n```python\n#export\ndef ipython2python(adoc, metadata=None):\n    return re.sub(r'\\[source, ipython3\\]','[source, python]', adoc)\n```\n\n\n```python\ntest_eq(ipython2python(\"[source, ipython3]\\n----\\nsome code\\n----\\n\"), \"[source, python]\\n----\\nsome code\\n----\\n\")\n```\n\nRemove empty cells or cells flagged for removal (because of hide_input)\n\n\n```python\n#export\ndef remove_cells(adoc, metadata=None):\n    adoc = re.sub(r'\\n\\[source, python\\]\\n----(\\n)*----\\n','', adoc)\n    return re.sub(r'\\n\\[source, python\\]\\n----\\n##remove##\\n----\\n','', adoc)\n```\n\n\n```python\ntest_eq(remove_cells(\"lalala\\n[source, python]\\n----\\n\\n----\\n\"), \"lalala\")\ntest_eq(remove_cells(\"lalala\\n[source, python]\\n----\\n##remove##\\n----\\n\"), \"lalala\")\n```\n\nClear code cells from the code flag when there is a `##clear##` tag.\n\n\n```python\n#export\n_re_clear = re.compile(r'\\[source, python\\]\\n----\\n##clear##(.*?)----\\n', re.DOTALL)\ndef clear_cells(adoc, metadata=None): return _re_clear.sub(r'\\1', adoc)\n```\n\n\n```python\ntest_eq(clear_cells(\n    \"lalala\\n[source, python]\\n----\\n##clear##pure adoc\\n----\\nfoo\\nbla\\n[source, python]\\n----\\n##clear##pure adoc again\\n----\\nbli\"),\n        \"lalala\\npure adoc\\nfoo\\nbla\\npure adoc again\\nbli\")\n```\n\nFormat LaTeX equations properly: they arrive either as `latexmath:[$equation$]` or `latexmath:[\\[equation\\]]`\n\n\n```python\n#export\ndef format_latex(adoc, metadata=None):\n    #LaTeX equations\n    adoc = re.sub(r\"latexmath:\\[\\$([^\\$]*)\\$\\]\", r\"latexmath:[\\\\(\\1\\\\)]\", adoc)\n    return re.sub(r\"latexmath:\\[\\\\\\[(.*)\\\\\\]\\]\", r\"\\n[latexmath]\\n++++\\n\\\\begin{equation}\\n\\1\\n\\\\end{equation}\\n++++\\n\", adoc)\n```\n\n\n```python\ntest_eq(format_latex(r\"latexmath:[$equation$]\"), r\"latexmath:[\\(equation\\)]\")\ntest_eq(format_latex(r\"latexmath:[\\[equation\\]]\"), \n        \"\\n[latexmath]\\n++++\\n\\\\begin{equation}\\nequation\\n\\\\end{equation}\\n++++\\n\")\n```\n\nFormat image outputs and make sure they point to the right folder.\n\n\n```python\n#export\n_re_image_output = re.compile(r'----\\n!\\[(?:svg|png|jpg)\\]\\((.+)\\)\\n----')\n```\n\n\n```python\n#export\ndef format_outputs(adoc, metadata=None):\n    folder = ({} if metadata is None else metadata).get('folder', '.')\n    def _rep(m):\n        name = m.groups()[0]\n        d = metadata[name] if metadata is not None and name in metadata else {}\n        attrs = ['\"' + d.get('alt', '') + '\"']\n        if 'width' in d: attrs.append(str(d['width']))\n        if 'width' in d and 'height' in d: attrs.append(str(d['height']))\n        suff = f\"[{', '.join(attrs)}]\"\n        pid = f\"[[{d['id']}]]\\n\" if 'id' in d else \"\"\n        caption = f\".{d['caption']}\\n\" if 'caption' in d else \"\"\n        return f\"{pid}{caption}image::{str(folder)}/{name}{suff}\"\n    return _re_image_output.sub(_rep, adoc)\n```\n\n\n```python\ntest_eq(format_outputs('----\\n\\n----', {'folder':'path', 'output.svg': {'alt': 'alt'}}),\n        'image::path/output.svg[\"alt\"]')\ntest_eq(format_outputs('----\\n\\n----', {'folder':'path', 'output.svg': {'alt': 'alt', 'width': 100}}),\n        'image::path/output.svg[\"alt\", 100]')\ntest_eq(format_outputs('----\\n\\n----'),\n        'image::./output1.png[\"\"]')\n```\n\nDeal with quotes\n\n\n```python\n#export\ndef fix_quotes(adoc, metadata=None):\n    return re.sub(r\"``([^'`]*)''\", r'\"\\1\"', adoc)\n```\n\n\n```python\ntest_eq(fix_quotes(\"``double quotes''\"), '\"double quotes\"')\n```\n\nPut back << >> around refs\n\n\n```python\n#export\ndef fix_references(adoc, metadata=None): return re.sub(r\"xxref(.*)xxeref\", r\"<<\\1>>\", adoc)\n```\n\n\n```python\ntest_eq(fix_references(\"There is a reference xxrefrefxxeref here.\"), \"There is a reference <<ref>> here.\")\n```\n\nFormat tables\n\n\n```python\n#export\ndef format_tables(adoc, metadata=None):\n    splits = adoc.split('----')\n    seps = [''] + ['----' for _ in range(len(splits)-1)] + ['']\n    for i,s in enumerate(splits):\n        s = re.sub(r'<div>[\\s\\S]*<table', '<table', s)\n        s = re.sub('</div>', '', s)\n        s = re.sub('<p>', '', s)\n        s = re.sub('</p>', '', s)\n        if len(s) > 0 and not s.startswith('\\n'): s = '\\n' + s\n        if len(s) > 0 and not s.endswith('\\n'):   s = s + '\\n'\n        if s.startswith('\\n<table'): seps[i],seps[i+1] = '++++','++++'\n        elif '<table' in s:\n            res = re.search('<table', s)\n            begin,end = res.span()\n            s = s[:begin] + '\\n----\\n\\n++++\\n' + s[begin:]\n            seps[i+1] = '++++'\n        splits[i] = s\n    res = ''\n    for s,c in zip(seps,splits): res = res + s + c\n    return res.replace('\\n\\n--------', '')\n```\n\nJust as a personal preference, replace all blocks of three new lines or more by \\n\\n\n\n\n```python\n#export\ndef remove_lines(text, metadata=None):\n    return re.sub(r'\\n\\n\\n\\n+([^\\n])', r'\\n\\n\\n\\1', text)\n```\n\n\n```python\ntest_eq(remove_lines('a\\n\\n\\n\\n\\n\\nb'), 'a\\n\\n\\nb')\n```\n\nAll together\n\n\n```python\n#export\npost_process_tfms = [fix_quotes, rep_spec_tok, ipython2python, remove_cells, clear_cells, format_latex,\n                     format_outputs, fix_references, format_tables, remove_lines]\n```\n\n\n```python\n#export\ndef post_process(adoc, metadata=None):\n    if not adoc.startswith('\\n'): adoc = '\\n' + adoc\n    adoc = re.sub('xxnewl\\s', '\\n', adoc)\n    adoc = compose(*post_process_tfms)(adoc, metadata=metadata)\n    return adoc.strip()\n```\n\n## Exporting\n\n\n```python\n#export\nc = ExportConfig()\nexporter = ASCIIDocExporter(c)\nexporter.exclude_input_prompt=True\nexporter.exclude_output_prompt=True\n```\n\n\n```python\n#export\ndef add_metadata(nb):\n    \"Stripping removes metadata used in the conversion.\"\n    if 'language_info' not in nb['metadata']:\n        nb['metadata']['language_info'] = {\n            'codemirror_mode': {'name': 'ipython', 'version': 3},\n            'file_extension': '.py',\n            'mimetype': 'text/x-python',\n            'name': 'python',\n            'nbconvert_exporter': 'python',\n            'pygments_lexer': 'ipython3',\n            'version': '3.7.1'}\n    return nb\n```\n\n\n```python\n#export\ndef output_num(n):\n    m = re.search(r'^output_(\\d*)_', n)\n    if m is None: return\n    return int(m.groups()[0])\n```\n\n\n```python\ntest_eq(output_num('output_31_0.png'), 31)\ntest_eq(output_num('output_12_0.svg'), 12)\n```\n\n\n```python\n#export\nimport PIL\n```\n\n\n```python\n#export\nIMAGE_OUT_MULT = 0.8\n```\n\n\n```python\n#export\nimport xml.etree.ElementTree as ET\n```\n\n\n```python\n#export\ndef get_output_width(name, raw, folder):\n    if name.endswith('.svg'): return ET.fromstring(raw).attrib['width'].split('.')[0].replace('pt', '')\n    try: return PIL.Image.open(Path(folder)/name).size[0]\n    except: return None\n```\n\n\n```python\n#export\ndef convert_nb(fname, dest_path='.', folder=None):\n    \"Convert a notebook `fname` to html file in `dest_path`.\"\n    print(f\"Converting {fname}\")\n    fname = Path(fname)\n    dest_name = fname.with_suffix('.asciidoc').name\n    if folder is None: folder = Path(dest_path)/f'{fname.stem}_files'\n    #folder for images. Clear if exists\n    if folder.exists(): shutil.rmtree(folder)\n    os.makedirs(folder, exist_ok=True) \n    \n    nb = add_metadata(treat_notebook(read_nb(fname), folder))\n    export = exporter.from_notebook_node(nb)\n    metadata = {'folder': folder.relative_to(dest_path)}\n    metadata.update({n: nb[\"cells\"][output_num(n)]['metadata'] for n in export[1]['outputs'].keys() if output_num(n) is not None})\n    for n,o in export[1]['outputs'].items():\n        with open(Path(folder)/n, 'wb') as f: f.write(o)\n        w = metadata[n]['width'] if 'width' in metadata[n] else get_output_width(n, o, folder)\n        if w is not None: metadata[n]['width'] = str(int(IMAGE_OUT_MULT * int(w)))\n    with open(f'{dest_path}/{dest_name}','w', encoding=\"utf8\") as f:\n        f.write(post_process(export[0], metadata))\n```\n\n\n```python\ndest = Path('test')\nconvert_nb('test/_test.ipynb', dest)\n```\n\n    Converting test/_test.ipynb\n\n\n\n```python\n#convert_nb('test/_test.ipynb', Path('test'))\n```\n\n\n```python\n#export\ndef _copy_images(path, dest_path):\n    os.makedirs(dest_path, exist_ok=True) \n    for f in path.iterdir():\n        if f.is_file(): shutil.copy(f, dest_path/f.name)\n        if f.is_dir(): _copy_images(f, dest_path/f.name)\n```\n\n\n```python\n#export\ndef copy_images(path, dest_path):\n    img_folder = dest_path/\"images\"\n    if img_folder.exists(): shutil.rmtree(img_folder)\n    _copy_images(path/\"images\", img_folder)\n```\n\n\n```python\ndest = Path('..')/'convert_book'\n# copy_images(Path('book'), dest)\n```\n\n\n```python\n#export\ndef _convert1(fname, dest_path='.'):\n    try: convert_nb(fname, dest_path=dest_path)\n    except Exception as e: \n        print(f\"Error in notebook {fname}\")\n        print(e)\n```\n\n\n```python\n#export\n@call_parse\ndef fastdoc_convert_all(\n    path:Param(\"Path to notebooks\",str)='book',\n    dest_path:Param(\"Path to generated asciidoc files\",str)='../convert_book'):\n    path,dest_path = Path(path),Path(dest_path)\n    dest_path.mkdir(parents=True,exist_ok=True)\n    (path/'images').mkdir(parents=True,exist_ok=True)\n    nbs = [f for f in path.iterdir() if f.suffix == '.ipynb' and not f.name.startswith('_')]\n    parallel(_convert1, nbs, dest_path=dest_path)\n    for f in path.iterdir():\n        if f.suffix in ['.adoc', '.asciidoc']: shutil.copy(f, dest_path/f.name)\n    copy_images(path, dest_path)\n```\n\n\n```python\n#convert_all()\n```\n\n## Export -\n\n\n```python\nfrom nbdev.export import *\nnotebook2script()\n```\n\n    Converted 00_asciidoc.ipynb.\n    Converted 01_clean.ipynb.\n    Converted index.ipynb.\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "eb0fd40ab8906a88e2c2c3b1ebddef6a99e334a3", "size": 56472, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "00_asciidoc.ipynb", "max_stars_repo_name": "nlpbook/fastdoc", "max_stars_repo_head_hexsha": "070113b40a0defb9b09fb2b3987a92322ced982a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "00_asciidoc.ipynb", "max_issues_repo_name": "nlpbook/fastdoc", "max_issues_repo_head_hexsha": "070113b40a0defb9b09fb2b3987a92322ced982a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "00_asciidoc.ipynb", "max_forks_repo_name": "nlpbook/fastdoc", "max_forks_repo_head_hexsha": "070113b40a0defb9b09fb2b3987a92322ced982a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3208722741, "max_line_length": 228, "alphanum_fraction": 0.5069237852, "converted": true, "num_tokens": 9665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1460872396128689, "lm_q2_score": 0.14414885119438492, "lm_q1q2_score": 0.021058307764353894}}
{"text": "# Rich Output\n\nIn Python, objects can declare their textual representation using the `__repr__` method.  IPython expands on this idea and allows objects to declare other, rich representations including:\n\n* HTML\n* JSON\n* PNG\n* JPEG\n* SVG\n* LaTeX\n\nA single object can declare some or all of these representations; all are handled by IPython's *display system*. This Notebook shows how you can use this display system to incorporate a broad range of content into your Notebooks.\n\n## Basic display imports\n\nThe `display` function is a general purpose tool for displaying different representations of objects. Think of it as `print` for these rich representations.\n\n\n```python\nfrom IPython.display import display\n```\n\nA few points:\n\n* Calling `display` on an object will send **all** possible representations to the Notebook.\n* These representations are stored in the Notebook document.\n* In general the Notebook will use the richest available representation.\n\nIf you want to display a particular representation, there are specific functions for that:\n\n\n```python\nfrom IPython.display import (\n    display_pretty, display_html, display_jpeg,\n    display_png, display_json, display_latex, display_svg\n)\n```\n\n## Images\n\nTo work with images (JPEG, PNG) use the `Image` class.\n\n\n```python\nfrom IPython.display import Image\n```\n\n\n```python\ni = Image(filename='ipython_logo.png')\n```\n\nReturning an `Image` object from an expression will automatically display it:\n\n\n```python\ni\n```\n\nOr you can pass an object with a rich representation to `display`:\n\n\n```python\ndisplay(i)\n```\n\nAn image can also be displayed from raw data or a URL.\n\n\n```python\nImage(url='http://python.org/images/python-logo.gif')\n```\n\n\n\n\n\n\n\n\nSVG images are also supported out of the box.\n\n\n```python\nfrom IPython.display import SVG\nSVG(filename='python_logo.svg')\n```\n\n\n\n\n    \n\n    \n\n\n\n### Embedded vs non-embedded Images\n\nBy default, image data is embedded in the notebook document so that the images can be viewed offline. However it is also possible to tell the `Image` class to only store a *link* to the image. Let's see how this works using a webcam at Berkeley.\n\n\n```python\nfrom IPython.display import Image\nimg_url = 'http://www.lawrencehallofscience.org/static/scienceview/scienceview.berkeley.edu/html/view/view_assets/images/newview.jpg'\n\n# by default Image data are embedded\nEmbed      = Image(img_url)\n\n# if kwarg `url` is given, the embedding is assumed to be false\nSoftLinked = Image(url=img_url)\n\n# In each case, embed can be specified explicitly with the `embed` kwarg\n# ForceEmbed = Image(url=img_url, embed=True)\n```\n\nHere is the embedded version. Note that this image was pulled from the webcam when this code cell was originally run and stored in the Notebook. Unless we rerun this cell, this is not todays image.\n\n\n```python\nEmbed\n```\n\n\n\n\n    \n\n    \n\n\n\nHere is today's image from same webcam at Berkeley, (refreshed every minutes, if you reload the notebook), visible only with an active internet connection, that should be different from the previous one. Notebooks saved with this kind of image will be smaller and always reflect the current version of the source, but the image won't display offline.\n\n\n```python\nSoftLinked\n```\n\n\n\n\n\n\n\n\nOf course, if you re-run this Notebook, the two images will be the same again.\n\n## HTML\n\nPython objects can declare HTML representations that will be displayed in the Notebook. If you have some HTML you want to display, simply use the `HTML` class.\n\n\n```python\nfrom IPython.display import HTML\n```\n\n\n```python\ns = \"\"\"<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\"\"\"\n```\n\n\n```python\nh = HTML(s)\n```\n\n\n```python\ndisplay(h)\n```\n\n\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n\n\nYou can also use the `%%html` cell magic to accomplish the same thing.\n\n\n```python\n%%html\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n```\n\n\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n\n\n## JavaScript\n\nThe Notebook also enables objects to declare a JavaScript representation. At first, this may seem odd as  output is inherently visual and JavaScript is a programming language. However, this opens the door for rich output that leverages the full power of JavaScript and associated libraries such as [d3.js](http://d3js.org) for output.\n\n\n```python\nfrom IPython.display import Javascript\n```\n\nPass a string of JavaScript source code to the `JavaScript` object and then display it.\n\n\n```python\njs = Javascript('alert(\"hi\")');\n```\n\n\n```python\ndisplay(js)\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\nThe same thing can be accomplished using the `%%javascript` cell magic:\n\n\n```javascript\n%%javascript\n\nalert(\"hi\");\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n## LaTeX\n\nThe IPython display system also has builtin support for the display of mathematical expressions typeset in LaTeX, which is rendered in the browser using [MathJax](http://mathjax.org).\n\nYou can pass raw LaTeX test as a string to the `Math` object:\n\n\n```python\nfrom IPython.display import Math\nMath(r'F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx')\n```\n\n\n\n\n$$F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx$$\n\n\n\nWith the `Latex` class, you have to include the delimiters yourself.  This allows you to use other LaTeX modes such as `eqnarray`:\n\n\n```python\nfrom IPython.display import Latex\nLatex(r\"\"\"\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\"\"\")\n```\n\n\n\n\n\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\n\n\n\nOr you can enter LaTeX directly with the `%%latex` cell magic:\n\n\n```latex\n%%latex\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n```\n\n\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n\n\n## Audio\n\nIPython makes it easy to work with sounds interactively. The `Audio` display class allows you to create an audio control that is embedded in the Notebook. The interface is analogous to the interface of the `Image` display class. All audio formats supported by the browser can be used. Note that no single format is presently supported in all browsers.\n\n\n```python\nfrom IPython.display import Audio\nAudio(url=\"http://www.nch.com.au/acm/8k16bitpcm.wav\")\n```\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"http://www.nch.com.au/acm/8k16bitpcm.wav\" type=\"audio/x-wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\nA NumPy array can be auralized automatically. The `Audio` class normalizes and encodes the data and embeds the resulting audio in the Notebook.\n\nFor instance, when two sine waves with almost the same frequency are superimposed a phenomena known as [beats](https://en.wikipedia.org/wiki/Beat_%28acoustics%29) occur. This can be auralised as follows:\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nmax_time = 3\nf1 = 220.0\nf2 = 224.0\nrate = 8000.0\nL = 3\ntimes = np.linspace(0,L,rate*L)\nsignal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times)\n\nplt.plot(signal)\nAudio(data=signal, rate=rate)\n```\n\n## Video\n\nMore exotic objects can also be displayed, as long as their representation supports the IPython display protocol.  For example, videos hosted externally on YouTube are easy to load:\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('sjfsUzECqK0')\n```\n\n\n\n\n\n\n\n\n\n\nUsing the nascent video capabilities of modern browsers, you may also be able to display local\nvideos.  At the moment this doesn't work very well in all browsers, so it may or may not work for you;\nwe will continue testing this and looking for ways to make it more robust.  \n\nThe following cell loads a local file called  `animation.m4v`, encodes the raw video as base64 for http\ntransport, and uses the HTML5 video tag to load it. On Chrome 15 it works correctly, displaying a control bar at the bottom with a play/pause button and a location slider.\n\n\n```python\nfrom IPython.display import HTML\nfrom base64 import b64encode\nvideo = open(\"animation.m4v\", \"rb\").read()\nvideo_encoded = b64encode(video).decode('ascii')\nvideo_tag = '<video controls alt=\"test\" src=\"data:video/x-m4v;base64,{0}\">'.format(video_encoded)\nHTML(data=video_tag)\n```\n\n\n\n\n<video controls alt=\"test\" src=\"data:video/x-m4v;base64,AAAAHGZ0eXBNNFYgAAACAGlzb21pc28yYXZjMQAAAAhmcmVlAAAqiW1kYXQAAAKMBgX//4jcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTE4IC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAxMSAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTMgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MzoweDExMyBtZT1oZXggc3VibWU9NyBwc3k9MSBwc3lfcmQ9MS4wMDowLjAwIG1peGVkX3JlZj0xIG1lX3JhbmdlPTE2IGNocm9tYV9tZT0xIHRyZWxsaXM9MSA4eDhkY3Q9MSBjcW09MCBkZWFkem9uZT0yMSwxMSBmYXN0X3Bza2lwPTEgY2hyb21hX3FwX29mZnNldD0tMiB0aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MyBiX3B5cmFtaWQ9MiBiX2FkYXB0PTEgYl9iaWFzPTAgZGlyZWN0PTEgd2VpZ2h0Yj0xIG9wZW5fZ29wPTAgd2VpZ2h0cD0yIGtleWludD0yNTAga2V5aW50X21pbj0yNSBzY2VuZWN1dD00MCBpbnRyYV9yZWZyZXNoPTAgcmNfbG9va2FoZWFkPTQwIHJjPWNyZiBtYnRyZWU9MSBjcmY9MjMuMCBxY29tcD0wLjYwIHFwbWluPTAgcXBtYXg9NjkgcXBzdGVwPTQgaXBfcmF0aW89MS40MCBhcT0xOjEuMDAAgAAACqVliIQAV/0TAAI/3gU2tIW7KawwaCmQGTGHKmuYAAADACBcshU+yICkgAA14AHowiEeT6ei7v7h3Hu0i2fpUBLGBIkbCMP3Vfz+9BVGCDXnw9Uv5o3iN030tb7eq6rsEEhHs2azbdTiE9Csz5Zm6SiUWRdmB43hbD5i6syATuODUJd7LM3d9cbFpc7zFlu5y3vUmNGd6urpvKKT9iyleIyTuR1sVS431DhevGfkUllVeIznYUe2USoMW1tufETjyRdmGldN6eNlhAOsGAH4z+HkrwKecPPU7Q5T4gDAIxj9hW84jVExMTSTHxkPTq1I4OotgUxURCGTsw60k/ezPNmNg38j1bqaGmPcruDKEIBDsK5qEytFB90Q68s0h2wmlf2KXd5bleBefiK+/p47ZsyUO4IdlW25rRy+HLjt6wQXfYee3IkiQOoOK+U7u/lxcl78zfxwIoEMjUUSKNZjkp8clnmecDDJ3Kz+viF7bPklk7N6QRyizAKPIIpnNJUuMWQmqeL2Or6cr4D0/0tOym+4tficxmhuEONKUtO2pPn3hRjMllkd12tXp70fLTfxy0dwB70ML9iLEcItHb7zVupHlP5RxdvecpREw+OsIPr9KWilIesNE19jgIbT+TkiRBjOoKvUuwcQnKg7fOTHVoLvnKuAfea+oujEdm1Rwd2tEOnkF+ZC11WaNQsiNR/eJ9EnUXjXDYGfhB+Oe7qj8nYTT+eOXg1cuJNgLXEs4vOheWEjQOqfIWMQc3DmTof5s0ksBmUQ3PQ+UHPxZSnmOEZB+j6xT3wbm7HGzDjWtSg1SjTxd1EiJ8xA4SIxxR8WIKLg+TwFxJNS7Laxq7Uglu3AkXe82P1JCdJX5PsbFbxuDbuJgakzRcTwMLLSKCiizS/eCW0uJed/lev9yb80kKlVET4S219cn/zhkpeDV83cHYOr+sJQKDRk/Wh2c7fsuxfxaEH/6reSmvFDsAnXAyPXliJ3G4VG3OkEM5K5WyGGrBizZbTrdGsBnzj5VSGGOJdCKuRrUluw/8es2vYRPs9BcTqAqvHk9M52SSIf+1T6L53EZP8VbtXB+G29CMW4xVCK/B/YDjaNmqMwJ61dapugjnWJfqeXlGGa3Ch3aA7gi30T8PucNRBjLK3lF67ZDDvkWXRQXd+VMnKWHkBbCkQ/F/fMuNpHO3C00Y2pljna1qImBhVMvPe0F7Qx7G/YyxLRzhyUU8e23HGzp0agtNJRbydbrPV+TqJMSifJMNcZIf8wkdnC3/xdpcXnLf2Ye3Kbd0o7utciTG+q5h6WTEk+PaNbXLLA0YyZ2VnLTcyV1QTS76aNCbV9Q1/OQ7QU81Gg0hPa9aSiscGary6jLVwDQaik4zLsi7jPqgPVdup7pwx7uJDqRCVcVi5QoZFp/GHdex5sJTF69A6sja69/NLkFIWNSIeRcuGahXpF+wZeYIrqJv975s1TKYKAvp1WtzgtgWNkcbzCtROqf8rPtlAIxkX8GLcEo9zfExyfimeXQ64qfFxEy0IMy2Hsxau9fSMqUnIjntuVVjCQtBL+94gx1RZLndE6wROVTq/wHwHrQzo9QL9cpPqPFJjiZ/NGZIFuudS+wsBFe6Hu8Oitf5zToLqLdtU4Smwh4ne3JsiT9lOzN+4PPw3VSx9l5FppVwdKUWELw1dYpCOppyVWlJ3YQ8H4FQQM8EcYMG9N3Bxu79y1J1ikuvuhMmLQlehLTbguhbix74hd1VIQC8EjHmOZSSWbssulYwPbr6FF49tifk6PymJvulR9/u+2585HkRfbxveGeWCz0ix1pIVfaNpESKmtLy/0mcbMg9hYDz2werz9oe0lT2BiMV6uAin6RaQcT8Vk9MPctfwae+gkvtnZA/sOBk8MbpylaHqc0KIVHhhLFMNnkOFiucjtGo/JWTa/F6g8wWeow5ZuIJUORaYHWqegZbTgM9dCsYYsfZGjjVMuSlDIvpYvIvFFooGPC7Ye2Jfawmq4Ut7EL/nv/dyAd2HRc5msmUhzeu/XpX3rVlzRmf9/Qan8Dbve3QfW1Ym0o5J/KAc3z1VBho7JBr5PgCL68RiD9jZHN0VvsT4gzsEjNlW3D91Uy4RduaodBFoNTzXwlfUYULBzdiTbH75l/UmVMC4TKeTWhNzw2UezaqeGd8at3WSY7W/VR3+hvZHDpkIjgKuNNH0DsCRa/Kk56XQoHIyvvUH/eNekNvziReqS4qgLnXUT4BRGt2BOtCifI6+X/DGHUOmWlX7TN5b4pw5U7jwfwshtbhGZM49T8JMk15Mzrc7tM6J11TYxb5R3mQhZ8TZumJ0bMJXPM69HFyihr5dJSEJMycxJVUh6NTQALUOoRTHIOwE+FpWI6feTv1SiZ0YpYe5DbkYJJbN7zAHbAKw25XvqR2mAjQmOlsfX/tK8DPjP/8h5/xgAF4EUbj1tOnQCBQL8jk9vHtfsXncsprww4Z+P/Z/UrKifuFyEpBWN8kLpF7yywE2iYdDruV9+/qKR8rC9ozNKyqQNIwtxrzYkWpE5t8K7gG4JFnrHona/Rp8dOX6VW41+jb5LB1LEtE8MwjLp3RCUOq/+6yLzaOEgBTqzvEjDeFpg/u9DMHMr4/2TOchfjg7dl+uQ6Gsx+4Ia9W7vivG95027p25eKL0nHvx/OqmAQEZYJL/JO58lOj0zPdJxrQ5dZksjMISzVZNn7DsxqE3zgBBuNzk50R8lTK3U8P12QiOAQYSTeGlYlkvfeofrfO1AitEj02m9aUkxTFd1ZZJoLQT2d3zEU5PmE4lxMVfL5ttNnIbqfcIU2RJKNWqdw77xfjfrNc/eNpRKPZ/6z50LzBprgjzBHRfKgSWWkDxHrX0aTbgwQFwd51+PoUWH4DkQg26uGslF5Hn3hB58+fkeLTosTANOIBNAeFZtTc4PIaLHw759zae7scY55xcTabzlilYIftst2RZ6ntsRC3zFxduCKvL6wLfYT+TiIWJn5P7sTwZwXuSzXY+9Q3xMZ5o4Xcpz6vD9FtTjzS69iefEYt4pXiDrZUo4ePGiLeoIFIwYB/v6GXdmG5VLLk+eKbOc9AmsX2zmvqtcvDRGQbzugXbH/kTH/lkNPBTmqN3ZJODUEXVohPEJ6th0xna0EVleB73Q3eNvaVUvhlJbjs3D/T17FRCebN7AOXvzzbLE/I5kNfEmJcv4dxtIeo2uQ/z9ohSpiZzbDj1u40nJRyJxUK60wEv0nA9f/NuJ6/PEyU0bkK16z2KH12k3Lc4+1f5fawIzkK2qJRB4wnj8VHhUW9mbJhs9vgfFmU3xrXSShY67Ygb+gYNPxxtn4K/9eTSwIA9fv/nR33lA2lZoXALRUTmOZIl3R0gAM5h6oX1y1thIyqViBK95VZc8Pvy7G3O90M9S4zkpyFQ36jrMazvMveMA4d39fvoaC7p90quiJfjI4yrl+ECVkCJL5MxRSa+iVcIL7Xbl0jVaGhZIcMYmcGOBbLzhJgloM1x1zFnnj3ggJRFAM8yNnXxhavk+mA18JC+y3lqGsp6vPReRxGlGHMou17L4It070LzkoeCzarpv8Apw59smdS5KN9qVN1WgeL7OSN8BHg94ubCvS7DW6H3/PbtRB62jFLsBhUV5YqCIbIN5VZ81AAACpUGaIWxFfwAru8x8uT3FuOjrAeSWXmAWqq9jCNGE+N5AOv//9//xjk4uBAcADN96c97AVGmzRtnWwPsgcCbLrVdQJgbKp4QSmPwQnVhv0hXyBjeFWWlcvx70urEN3FK6/lvk2tQeZgbtlbzXluvTfnSj/Ctz7vZ+O1FjhDzzdpL7uLzewzCIW5VWLAEKUVuS2J6wNk6MR7UblcEd4EtOY+R4/qJgfojCsfRvA0oC5dc41Vd0erZbSkrmPTjLCn815bxlchUJMS8gQD5hJNwoKHvNLNwn7XKuTtYIhH2wVNZvDWgzCjlPeQajnrcMsb6bZYJvNJU8HuGHvm50r7VG8qifEwmuyegAZXojh5Ul5VvjDW7kSAZyw8a7I6mHY3FZHd+OA3V4JZMbNliI3Tj1L6+MKTmilVialmyZagRtEMeKRdtxUPd3vVEtrOBVIVYWdgAGA7HmZiHQUQNxLkWxbLyWVlrh5EM0Do2NdbclHxxArz90d+MSVeUOIXQ/4V9quq8C8qVflo1gPtPMkjO2/UrdOYqhY404ReObOu/fdp4hAEDq6jhy64vOeT7XUK/Onq0rXTldtA6kvgQaJg+mgYSR9hfXtMbOUSLgLj/RmBSO8aAMHuJJZqf1tCM5pZ9eYUsrHmy+/z2NGalon0//uF6+33bQzT/RLRfBbYTjy9QrJqHLlw46lggWPGkHuPKSqk/CB7U4pNPXUbR0DdcJy9Db00wCzVzxVc6h7jfCFgiL2Y0HVqd6bgIaVUqn/gJCEyCDVplnzebv0gg3XwMJAGu639lHu7rEvxTp1smIYjWp9R5L4SspVvS07Nb+Smk1FgsMp1K3EMUT8X2Fty4VG54/Ec6bE8tNVw4/QV1VzBw7Px2/2eEhhUS+FMfbHAlD28x00jRgAAACW0GaQjwhkymEVwArOUkEOhoFqiELtH8wgecFLiUq6WqmwAP7iGEwbYzfnHacfqUNXAfD+CGR2ap0lAHL25ipuYtd5j2O0PU/MpaWPG/n2y5OkfTzaOpotaR5tWjN55B2XblVVqsFfBC/mvsiPvCBWUHFChacdY5whj5mP5rqQ0dqLJCsWjrs4TWnIbL2V/Iwfj3hwI35jfo1JkTOeR+8GhOdma9rgiKWafCbQyhYMTDmVdvhND60Flm97EDSTjF0OC+0gD9b8Yn4tNeHipCa/aWyt0n79bMmjfcjntBCPjrcB5ecRTpfGHbEHy1IRj2cjkGXKC+VYoYJXBp4rd4cMd8ygLCk5nBSd8/cTaKNRjdBscOeTXG6QEjSxj9/2pVwx9DMRVtWQR0BSaAcQcZ8W2KPSaeRC4QwmNMu2xx25CSyrDiq2rFSK/JJtmvoIjAKq0ciEXoOgw+Ke+Ylb7ULKCS3k1p/613UNRp450uSq5b7CAHo7S0b7fBMLfNmwSjRYEhLlo0HUaRe/I+IX2Z6XdZH9Hty/399ZA1PwZGC6EfvUJIf7CBeaxv7cu6IT2/s0zPRGthpvXpYw6A7P4Wwz5C4V98KnIUNUanadqabKP6eXWhvbvcQHxAjiOOiKZgXZplZW2g+B2NNyJSLiR+g48DqvWR6t9S2aGfFjdOW1Gi6oTtZ1d4p5XIslAr8mryeZ6+htSSQe4AcfVt7k+V6mOthBCYtr/LEU4ZHtl0mW9876PK8mRFAaT8DJOUFVz1lPfzRApuPggkkyq+UMvyfKTUbCk7/DpfX8Y4s4QAAAg9BmmNJ4Q8mUwIr/wAsWUPjZw3ksgRsxZ6n4fQjprPbkj2aUh30y0bZJnLmiXnWskvOGnCPwBnG9dEhatwX3hoxk7BNyG+wQ4emZUpcVzcWl2T9nKQB1euucuZWHTg7TCtM/iHyfPO2vbmGsfzs70b/egIbywUH4y4BQSL1nWc1SmpHm2zHMBcUjYLDZ5gL5vdfxn0V8FFw66G88c/LN4I5icUa7xf4fcSBKywU0ajbp1P+aJYjBgWT6Ggu0MDLDNl54tfqd42lKosQtM1aif4WXAZFP5Ww3vrQ1rH9+utSYxqZd6N6gGtNbSNMcViaKn5LcnjsbBi3T3EmGqshEbcme8VHKwR3kSfBOAprrIsv6K8R+X6az+MD23rWka/2v64m1qM69D7Xa+Kcs/n0KLCJdTilyaGadopLeaAn3eYvWTeHcucMM1Fp1KgHD1tiFeO6HvobLkZlRximsA3/7MiohYklLIcJrZL22BH+6W9d6kZsYIsej9RM681nU6mWNjepBAfAfTbrGRrVB/h2DxC5B8YyRjgSIzQjNYrse0rzChqbrsLl7mQ7W+1bsNKze5//9ZIa8rSsF+BXh/vgoRTDkPW/ws95B7VPCZEFChfX0icw+tpcpN/q7NY87tUn4vESdSiMMlyhKklMjQu/G51J69ZRQLs2oUO6YfoJFqliy4qCFCrf8SZE9Fc6DcCagAAAAodBmoRJ4Q8mUwIr/wArPWF/KOw78THwadfPqhJO0CnmR/M74/XYZLqVYKlNcEaYauf+vrRUDJPmu75sMKy2Y+Bnslc/iAISSyWtw/h/3CF8fE5ZrbrwSNst+MSyCoNWP+8imtoX2eyojpdCk8YP5K+cbK4SJPCkZXbYqSXYk7hO8AdSemBHgXKWiZ+UOr802aJo+98ZOIjX9hWL9bo31Gqx7cy4ZG+W/ar/WGlzDa1xPWnPRsEdrIcZlEVGV/jGmbirkxw1lyUYoqj8Vv7Bxube9XPQlBkXOV6Lc1LT2IzNq0V7WwVhF0kA6yxfAsFxc9krNEH8vGGntTWI608ovjatXc/CKKXw7AjJSftlTcLI0hIIGXbRUr0NCYNp7M4cVd/n73Rjetnixz4SAKpcz/P47UsijZG7T3SxzK2D79WS42aEalc12hQwCZ01LfmF/H2mmGEvOzPBie1D0YT7Jh19vxa4Dd3SQ1FrDfmSUpvv4DjbYcZ2PrPpFpWtMjWqHBeoyMiZf6RP3EfYR6z9jsVNIIHxM0bzzBQF8eeYkPgDySydxPXv9Izo+QUY94N8kWi16fI6eZSDc1G0Yo0L91jcRQuDMGGS7B2zuf/0GbJyRhUO48UbMrqnILMrbQg1LF00Q3pH9nbGEK/RRQpRN3T/J/4IZQjwW2Ft2ipWGztg1Jn9I4DmffKS60QC+JQcyakdVON6zDcKttIKlqeTcmAi4xzmo4QXa2dRKleS+fs3EtTdBBtony2wK9T2Imj+NCziOSEL7Q7VuIU8kclUHrJJsSneFcxGRgIgGGUEQM8/pklwTOqab7mMmJeRiaBrjJDEnDpkR4Vz3qXxgyn4/5x24FuTMNVPwQAAAhtBmqVJ4Q8mUwIr/wApcLwPT0/Xh9UdWqWXIs8Wbj5K1hivmN6qIQnq+aolcegdlM/63MbHsdC6xYZC1e/Q8UjQCt9N/Ejqwms8DzeWv2qxskeliZH0kt1QWkErWSEodq7V0ZNksctLkMGWayX33gBT368EehfIeGDolBZoqIbJfb4nqcfU+ev4OzVv9zVqWyLck315GFmXxQKIM8pICQc8Q5es34LH1+DmnMnW8kQpVGrztQcDXhjCU3F0fOgoSsXSVWCjc6XKqGbCwQDfJUxCfXfIT6YmQoPpVp1mpGy1wQypXus9z0bScDpyDu23hViYDntdj1O45ea0znKZkj1+tLHbBtqAGJ1WTcbGlF6Vya6hQhEsiiZUIC2fRxIj8/wEXCICIbr0gZ/m6gcOhE10tenvE7iy+BKY81wLWrnzos3S6FWxYtmCRes+LLhNGOKWRuQo6SyePH2OZ90xZm8oA1MuTe3V59euVNxjAt0FLkAc9TEiFhP/8CB+gA8mF+A8h1U01f4DVX55GzCH51jHI2xUS0L9GtsHoBxLPLK/NNel8zcnwG4X+UusfcfEb5hh+ffnXteCE9vRGbs2n9wYW0xA3ZicklfadmWKUtMiHYBfkMSULWnkBQr4CXxjpYOs6ygeEoA5+5B0B1SZObgZ42wWqddyyYE0NfwQAl75tfdJGqOa7OMHwBYNeatJaJK0zT2+bFaw2qWCWwAAAitBmsZJ4Q8mUwIr/wAstkdsayRXchoFk703izqzduZ5WsyXriI9cfUdMUWvm0iGHwYIrUujvz3Yjou+JLwv9df2kt7MJo8u+3P5CjEKbwlz4vkE5AHTAbgXn3+Xc/MMJLgW5cm7iX3KiGNnBpbphhwJRlb3u91NRDr0d1IR2up/z7lKxE7XPAPFe0siPMYVlIqWNSn5KqLABPeuxxbOsvMEb27/nH1LUVM8I2F95c1I3Lv1SpkhZXjs1JsmS9X7gsoTxkXyShGC2+zRJSGUbhCPo/q1XSFMHQyMWJ79FKPQSL/RpVsacN2bYwdKo4TFBw1SsKq/L1iOmqMI+4Gxnbbjojdk0ek0JIcDb4bHv1czxchF7FX1Ym8H6IpPuE8CeNKjzQ1a1wqhEu+wl1N0x3Y37ZryCCKJRkxj0FT7bOoH3L38/yMUuh/v3aCmxY4eCkykb2p6ZrYMFE044anM/nMjmbErMibfRFuCz58Io1rBlF7JfkIz0R2/5vjUMVskcdbX2mm7DntncOsWDIdg/XVmgsC9CzVzUyq4VsS/sk97lJggcddpWLNw/29egz8iLyzWHOAXCvl2fTIPkviYAOQXfVhZUQdxsyJUNFMTiALrZCmoQLMp2LmDbfbW8JQriDeR3fVz6P1sjT8C2yEDvzkCn7sh0aTBK+sx7BKH1nb4320+caQepQj4TCJtCeNXjdrVcNEnjvwlcRJwFT1pT+Y7HREbHnT71XYNh4EAAAGEQZrnSeEPJlMCK/8AKIjxcI58rm/ML255fOJW1zbznFna7lfgMQrka7OTPPsvVAV4EJXye/Uxiu9dlftmRypJqfDot3xwDe8lX/qAVf6pBkSlUsaLyBYtww/SUSa1bGl1JvrJCN7FXCCXbLd5R4PoYlPiDIm/DQH2puO0StIWmrR77Isc/J1pRvdu5+mQa/n0SEHUeM2KkoRzCznfD9zaaRO7BDtvC9SYIT0uYZxrwTjxQ7N7UERTrYG0P+vRLAhxkfohFIYl3HXyjPOvnlbUFP2oiiy6nkUFuaIyQcJawJv3GU8k4ObcKsC1cNDXjSpsyQRrxLFaCCjke4mikyt7vs0iN0bnrNWv9HXruG9zOFEOer1ggIFTsT1Eos5CXRkgja5HN4QUM6MhWpc5du/HgBIH8ANFcoo2kJpqcadw9r/0qk25X91MQSDJQiH8Hny2dQhqR+LFWEawiW753SJhn0ngZcv/mPj3mwcHv1SL9ErBqAjm4JGiDetPKYtFwANYY11OyQAAAVdBmwhJ4Q8mUwIr/wArOx5HV2505jRePGgMxptW4PGIHEszV1xGZS+flSkF+aq30AaqO7u6XK9jJsuWXTfYCRQTn1bZfFQ22DbO5DXAxK/TUmbQleCflFzeS6/czxkL4PJ8AwOs2U+oehekgCZC8gZyHHaQSaKbNJ46gTjNsLy84ACQ5uNt11TPuCPqPTuh+schdw9S+/lU/6m+EyaqGZ49wDFPiBFBYXglQQBjyP9k/rqq0xL7SiLjpe4riYg8SFUuUtOzPdWHyvxnI7Ug/0VLPGAAhgMISUnqe01d5QFf36yHpwMAHexjAZFIGQHAFautuMuEw6HzUZVzNdeHYxvEYOGkTo007bLwbuf/nxzrywGOxlRTYJLRdYI0mk0SdN3+LeTv1RIJwv21+e9rT5iFOTCgzeQoekEWXLYz0X8YLq5bVCtijP7/T7w1Ck71j0aqfrEn6wtIAAABNUGbKUnhDyZTAiv/ACcySi7VBgOid6qZNXvhh/JsllHkMLLq0yNbQTqv/Wk2EBoSKICZwFwAD0WRzhvvReCGirep1Fe4bxjm49/UR+OYrXRmHR18T0C83AUVeBk7KvDZmb/eHzuzEN4yfXucr/NWFJl+USVMY4r4UQ9CayrfEY9v6AQ6mzAdLy2UMfFxrRJ99g/Rfl8qx+m4jIZNjlrTaThzJ/3OpVmAliDfxVyg8+CVIlI31IykiwQrXcebgajG+av8XU1SfyAG5ibvwbtdSAxkGBcJWL387V+uTdY56w3KN2vBtoQpVKD2zb3yazIcATZ02upwIytNcM/rpaLCdMb1myWcikE25agzLhDhOS+4zwjYz2DnW6VY0gFBAPsphhsUMnauVVdUVHzCTSdvzEve/H8q4AAAAVdBm0pJ4Q8mUwIr/wAo+x5XKuiN1am7SkJKSMonFZDPU3f5XFcDQSs0FLVq2idfsKwuIkt1mxIq8NgMHpzofTnDHqs/WedvAmhBgL0N5azdQa5MNKG2rJ4IAvGQY/uFm3jKQAKzvhSS01gO1oIfizF817z9IShS4QK2WT0PeFPELqLSpED8eNOpVTR96vmwpk/WBKRVJdTQJzjiCQ5pgEwjtvk7KqoS0+lwXSbvIrXkYm8DignEts3DLNoLHrPjXlQmbIop76JZSyJEtB+91GrLwo6Km5GeebyA2E6qGL3xSkpppej/ruoFprSKrH60UMbrq/SK7eCo+1QFoySPQmqDFsMGiQFqvtld5BXDYdVI4yRaoyN7Y7wi83HRC6eVazuHU9OtIY3xJJApBWq1aJOsYwc38aTC3ee863Aa/4n9Lk4DAtyFYHNZjB5m2e2vk8G2Gny9YFlBAAABQEGba0nhDyZTAiv/ACoZSZQfHxhfQxEqOBQrP+L3DmgvHSJQtB1iVkcLTxm+vagLHBLG91OGnopwrr7gT/loDypIhoRxjcwAAOeg/jN4WBbXzCJtnWGGllUCSdtUZQzKOSp9iM4yX18C6jrY4Sq6R9PUV/lEGNveJR4gw4FMve7110XdEPL1O2VTdHvdqeANyaq0nLdEmtXnrzvdrFlBaUvmaR4EdlkqGkvkZKWJej8Vq+msbKa7JdbxjwZtRufiyGfD/NVqMgSrYRzw9z/a8Zwbr+9+19CxlWD5bCuAEfPmjY6kZJE2L/CQI6+tnCBTXOmWZtZMBoCLGOf7G2uAC3+kFlboh9as5WCkO6+iqXq29dyhKnsHInorRYsPlgxIXyU1Om/Kyhj1DJV0Am9WJK3Dln0zNUH0q6ZTOnZcFD36AAABYkGbjEnhDyZTAiv/ACcwdIOLRFfoGK2ZkKsvgMwG0m0qsY0vMLPSzefc+ebp/aztyF7MlsBz/fBeNtxFBcsKgR4pf65GvdfOMHah0ltZ918sMDmXUEZMeRHy/xpnWpTLeGz6uTs/7MATPmU5BgHbT/DkD8QeaZnFAzidyFCXDz2l/jaKhEdgqipbB2pH0+fQ039r05z9axxEWGmaLQjg6x9+po1o24yhkVO7m03YwWmPyCgy8cOwrvRyJkXJpRN4m8ZBS1zwY80HeN/VyMQQJSMwsTo7R1XMerSFuyx0nz+8qOuhiqykc2ohCCsXia/+kIKbJ5Vs+cbWtvkqBKIDSfU7FhAd3GjcY/xar0EVmi6wWFTugAogR3I7mTrQDdlTAqYgqO7Gn5NMXQVHu2i1zhFSdo9GjMbeGnbkJwsFbQ2XkoKRIDpuW7AewC9AEBt0Ox/Ah6dGXfXO1jl8pEApj2RFmgAAAPlBm61J4Q8mUwIr/wAlR+eW/VZ7bSrmwwMA62G05DZ7p/5FUugsSsQdonUq6abtbU5hjFr+I1lPgoiV5c3CkTQZS+K5zivdo+Ti2P4K90xXANp8dSMAu85uJIOCQn2TXbEnNDifLB+3V84ht5tj4lvTaZx317BcliV8D5v2zZQW8RO1mUbuJEBItst8E7hfE+ZXj7tfDxNZPTvtpFyUv0fH1cTg1pr2VLy0d0zQLiA58dg+GkRvR1/hs2LyifBgHcj6eTWz0vsypVn9iPXRH/unJ6i8cfFL69NO24tQ9QQB+nDFhoP2cRhkAvhHwn56n5PppBD/oxni2f8AAAE9QZvOSeEPJlMCK/8AJjAXVGf+Kj2XNJnFeKC/gr7dJDTC2ngpd4WeAHlg04GuJKnn9hAmiECxxo9qM1IYMRiB85t6gALnlm9sRqGmioyzAm18RJndc9Ah8RlpGzr+44a6ntRaPx0cIwNIWAA8buL2JP00dmfjNqEiAlCa8OdV8FQxjp1vDXsGcAGF3Qbd62KEpkimeI3wH2nuXpbDHm8/ZKOR49s5ifUCkxCoJpfp43aC0lTzh2NXpcfVw6h0QnK8G60R4ZAxOxaJB7c0nn8ixXSU2JVY24EtGMF53nxJnHfzUheewUfBOGYSxeo8oK7oUCqX4rztzDwoc2QywNqQUJUkFrqIN+sb5ecYvX24Zujn+ZzTW6UDAF3R6WdNyJyRAremgC8spSflTqygQNGfHyGkfIEEJJaFo/pBCBkAAAEWQZvvSeEPJlMCK/8AKI41fuekXG59Knbw4Y6YJritsh9VtQgc3QKvVmxrzzo7f4aXn8N74eyP4b2lV1Z2Q+rohxps7EHTkOY9jLdqxI3MXe7je4g2qepz71+hY+jYdX+9LO0kA0Zg3NfyAlIRX7k6c/YHAZNtNaGZgTBMqiPgmEjiJH9Luk7shbgr+srfwiYwBX9rdS3fQNNFwcT8orQC+F60LAY9+GbFo2Sw3Ld4Tw9jq9yJtrY8RtHAdzytyek/mv2+j2TbTvAQKbbCYtdC8E/KtR4V5ZTSScr5Wb63vmbw7UpddEXYvl55pARyyvMxWNSh3Li4GF8Jk5JBi5B5ASQwxCMYpX5hkAMc+d8tl2bT+IEvUTsAAAElQZoQSeEPJlMCK/8AJIAzFZs00JJ0yfm8CZiew4xWdArLklEvBVXo/+ukPLu3XP9HFOfsme3T6BJEKmPPgZw/Lxnraq6Sl2kLVW19YU1qmqgfv+80LkZaWU5gRAH4hqyo3bFYcbuY2SC3IW5Wm69gtYyAXOdbAYSEHA16fvCeRQjHEsxKVndJdrRAlrGHsKgUBQ3Up/ZXIy1vkdFOfKSjpuZnswkuqr8NZI5tJ/dnBSErBTNWPaNwWV7nNomC0EYVGo+geGBhLXzaLw0UAOCYGjiPc3803BDw1GLoLIXjrIFJxwRfBNIAXYZAglu30oYzhpAfRWSprkeULMWYJTlWvbUQ5CNewSZssuDWIRAc3w8AcFaywwn+YSGhtR8VI1OGjYkfBbcAAAD8QZoxSeEPJlMCK/8AJdokjCUETRw/nciVPtaZQSBP/VxAQSITASEzlJBl9Na1r0DJhLOz279+KQLtl/xHZ8vAKc528mTMTqtWs4sFbeVgHWyBpHcHEtgTzjIqEinp/MPuUXF5poo8YLSSMFn9Ozx2FbU5/Kh9A39oN9NHQflVxV1NA6yT/84HHyfMtfdSMS8KTvAEE2lDs14VQayNs5ctjXboQT7xMBf5OLj6thhPvgaDrFB2o/PV9ouK147lruWTP2mkoA9oDIMYW1pcBx4yyV/t9GOPZ3aXneMUb2fFmUCX43BjXfUDMaa4GO2/Ankj3UEQwDxA7ZlNUQK2AAAA4UGaUknhDyZTAiv/ACJHv33I08bkhybYiJ/JiiheW5zMPBu4n5CxGr3frhE7TkLh0vPktM8m/AhaDiJisdk5QXNe/4WmxEDSAyaVi4eUVu0iHT2ly/KNTGqiORqA2oKpTjh84nYbrpXwnGv9SOf/34Z06xN6Yo3t35UZrP8nlcs/63GtnEmnUwVZHBYfPM6bs5M5AeBfAQ/9mIqu7vnEst+5O2wpPjzdItjwGCZ2ApHVjGnYYFomlA9nm6AXnxNIWHIsDgxCk3zx+6QbXipu/CWLG1Wf0WIbt4C0JPVl3TEb0QAAAMlBmnNJ4Q8mUwIr/wAVV64OfTKmlktYOqZHH1W1DhPy/X/6sD4T6hRdzfOgNtTOX2IckRJHshfBQVkJIzns079io6kpJFCcS3VD4zrWCn/dNaGV0kWTpFBRuusfn8F0C0R/EhsQeyTsdZftEkLGb5tq+nrir3vfmeb7rjmWJRXkIrTEKu8pIuAd+4FBGp8ARgGe80Jqpp//s1433HqBFqXsIFJTmU8j/toF9HyueI1Ea4uvsQ6NANGcYCbOAKCmbNiwABMCFaiUTMAAAAPSbW9vdgAAAGxtdmhkAAAAAHwlsIB8JbCAAAAD6AAAAyAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAv10cmFrAAAAXHRraGQAAAAPfCWwgHwlsIAAAAABAAAAAAAAAyAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAY4AAAGGAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAMgAAAAAgABAAAAAAJ1bWRpYQAAACBtZGhkAAAAAHwlsIB8JbCAAAAAGQAAABRVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAACIG1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAeBzdGJsAAAAtHN0c2QAAAAAAAAAAQAAAKRhdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAY4BhgBIAAAASAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGP//AAAAMmF2Y0MBZAAV/+EAGWdkABWs2UGQz6mhAAADAAEAAAMAMg8WLZYBAAZo6+PLIsAAAAAcdXVpZGtoQPJfJE/FujmlG88DI/MAAAAAAAAAGHN0dHMAAAAAAAAAAQAAABQAAAABAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAYY3R0cwAAAAAAAAABAAAAFAAAAAIAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAZHN0c3oAAAAAAAAAAAAAABQAAA05AAACqQAAAl8AAAITAAACiwAAAh8AAAIvAAABiAAAAVsAAAE5AAABWwAAAUQAAAFmAAAA/QAAAUEAAAEaAAABKQAAAQAAAADlAAAAzQAAAGBzdGNvAAAAAAAAABQAAAAsAAANZQAAEA4AABJtAAAUgAAAFwsAABkqAAAbWQAAHOEAAB48AAAfdQAAINAAACIUAAAjegAAJHcAACW4AAAm0gAAJ/sAACj7AAAp4AAAAGF1ZHRhAAAAWW1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAALGlsc3QAAAAkqXRvbwAAABxkYXRhAAAAAQAAAABMYXZmNTIuMTExLjA=\">\n\n\n\n## External sites\n\nYou can even embed an entire page from another site in an iframe; for example this is today's Wikipedia\npage for mobile users:\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('http://jupyter.org', width='100%', height=350)\n```\n\n\n\n\n\n\n\n\n\n\n## Links to local files\n\nIPython provides builtin display classes for generating links to local files. Create a link to a single file using the `FileLink` object:\n\n\n```python\nfrom IPython.display import FileLink, FileLinks\nFileLink('Advanced IPython.ipynb')\n```\n\n\n\n\n<a href='Advanced IPython.ipynb' target='_blank'>Advanced IPython.ipynb</a><br>\n\n\n\nAlternatively, to generate links to all of the files in a directory, use the `FileLinks` object, passing `'.'` to indicate that we want links generated for the current working directory. Note that if there were other directories under the current directory, `FileLinks` would work in a recursive manner creating links to files in all sub-directories as well.\n\n\n```python\nFileLinks('.')\n```\n\n\n\n\n./<br>\n&nbsp;&nbsp;<a href='./Advanced IPython.ipynb' target='_blank'>Advanced IPython.ipynb</a><br>\n&nbsp;&nbsp;<a href='./animation.m4v' target='_blank'>animation.m4v</a><br>\n&nbsp;&nbsp;<a href='./Custom Display Logic.ipynb' target='_blank'>Custom Display Logic.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Image Processing.ipynb' target='_blank'>Image Processing.ipynb</a><br>\n&nbsp;&nbsp;<a href='./ipython_logo.png' target='_blank'>ipython_logo.png</a><br>\n&nbsp;&nbsp;<a href='./Multiple languages from inside IPython.ipynb' target='_blank'>Multiple languages from inside IPython.ipynb</a><br>\n&nbsp;&nbsp;<a href='./mycircle.py' target='_blank'>mycircle.py</a><br>\n&nbsp;&nbsp;<a href='./mycircle2.py' target='_blank'>mycircle2.py</a><br>\n&nbsp;&nbsp;<a href='./python_logo.svg' target='_blank'>python_logo.svg</a><br>\n&nbsp;&nbsp;<a href='./Rich Output.ipynb' target='_blank'>Rich Output.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Using Interact.ipynb' target='_blank'>Using Interact.ipynb</a><br>\n./.ipynb_checkpoints/<br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Advanced IPython-checkpoint.ipynb' target='_blank'>Advanced IPython-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Custom Display Logic-checkpoint.ipynb' target='_blank'>Custom Display Logic-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Image Processing-checkpoint.ipynb' target='_blank'>Image Processing-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/IntroParallel-checkpoint.ipynb' target='_blank'>IntroParallel-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Multiple languages from inside IPython-checkpoint.ipynb' target='_blank'>Multiple languages from inside IPython-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Rich Output-checkpoint.ipynb' target='_blank'>Rich Output-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Using Interact-checkpoint.ipynb' target='_blank'>Using Interact-checkpoint.ipynb</a><br>\n\n\n\n## Rich output and security\n\nThe IPython Notebook allows arbitrary code execution in both the IPython kernel and in the browser, though HTML and JavaScript output. More importantly, because IPython has a JavaScript API for running code in the browser, HTML and JavaScript output can actually trigger code to be run in the kernel. This poses a significant security risk as it would allow IPython Notebooks to execute arbitrary code on your computers.\n\nTo protect against these risks, the IPython Notebook has a security model that specifies how dangerous output is handled. Here is a short summary:\n\n* When you run code in the Notebook, all rich output is displayed.\n* When you open a notebook, rich output is only displayed if it doesn't contain security vulberabilities,...\n* ..or if you have trusted a notebook, all rich output will run upon opening it.\n\nA full description of the IPython security model can be found on [this page](http://ipython.org/ipython-doc/dev/notebook/security.html).\n\n## Rich output and nbviewer\n\nMuch of the power of the Notebook is that it enables users to share notebooks with each other using http://nbviewer.ipython.org, without installing IPython locally. As of IPython 2.0, notebooks rendere on nbviewer will display all output, including HTML and JavaScript. Furthermore, to provide a consistent JavaScript environment on the live Notebook and nbviewer, the following JavaScript libraries are loaded onto the nbviewer page, *before* the notebook and its output is displayed:\n\n* [jQuery](http://jquery.com/)\n* [RequireJS](http://requirejs.org/)\n\nLibraries such as [mpld3](http://mpld3.github.io/) use these capabilities to generate interactive visualizations that work on nbviewer.\n", "meta": {"hexsha": "aee19d6ff894438d4f2a83b4b9c1f48fec4ee6c2", "size": 249259, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "sveske/sources/13_AdvancedIPython/Rich Output.ipynb", "max_stars_repo_name": "milica325/unibl_radionica", "max_stars_repo_head_hexsha": "34a753a663f9ad6a3f1031cd6755748526046376", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-09-18T19:21:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-19T00:00:25.000Z", "max_issues_repo_path": "sveske/sources/13_AdvancedIPython/Rich Output.ipynb", "max_issues_repo_name": "milica325/unibl_radionica", "max_issues_repo_head_hexsha": "34a753a663f9ad6a3f1031cd6755748526046376", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sveske/sources/13_AdvancedIPython/Rich Output.ipynb", "max_forks_repo_name": "milica325/unibl_radionica", "max_forks_repo_head_hexsha": "34a753a663f9ad6a3f1031cd6755748526046376", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 34, "max_forks_repo_forks_event_min_datetime": "2019-09-18T14:39:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-20T06:45:07.000Z", "avg_line_length": 206.1695616212, "max_line_length": 79683, "alphanum_fraction": 0.8955463995, "converted": true, "num_tokens": 15065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23370636758849891, "lm_q2_score": 0.09009299518349309, "lm_q1q2_score": 0.0210553066495023}}
{"text": "<center><h1>Jupyter Notebook Overview for NISAR ST</h1></center>\n\n<center> <h2> Nov 4, 2019 </h2><center>\n\n<center><h2><u>Overview</u></h2></center>\n\n1. Quick Introduction to Jupyter\n   - Markdown text\n   - Executable code\n   - Latex equations\n   - Embedding images\n2. Interactive Plotting examples\n\n<center><h2><u>Intro to Jupyter (1)</u></h2></center>\n\n1. Installation on OS X (10.12)\n   - sudo port install py37-jupyter\n   - sudo pip-3.7 install jupyterlab\n   - sudo pip-3.7 install jupyter_contrib_nbextensions\n   - sudo jupyter-3.7 contrib nbextension install --user\n   - sudo pip-3.7 install jupyter_nbextensions_configurator\n   - sudo jupyter-3.7 nbextensions_configurator enable --user\n   - sudo pip-3.7 install RISE\n   - sudo jupyter-nbextension-3.7 install rise --py --sys-prefix\n\n<center><h2><u>Intro to Jupyter (2)</u></h2></center>\n\n1. Jupyter comes pre-packaged with conda (OS-X / Linux)\n   - python3 -m pip install jupyterlab\n   - python3 -m pip install jupyter_contrib_nbextensions\n   - python3 -m pip install jupyter_nbextensions_configurator\n   - conda install -c conda-forge RISE\n\n<center><h2><u>Jupyter interfaces (3)</u></h2></center>\n\nThere are 3 different Jupyter environments that you can work with\n\n1. [Jupyter Lab](http://localhost:8888/lab)\n\n2. [Jupyter notebook](http://localhost:8888/tree)\n\n3. Jupyter nteract (Not shown today)\n\n\n<center><h1><u>Adding content to a notebook</u></h1></center>\n\n1. Text\n2. Executable code\n3. Latex equations\n4. Embedding images in notebook\n\n<center><h2><u>Text (1)</u></h2></center>\n\nSimple markdown (same as github) is used for writing text in jupyter.\n\nA good reference cheat sheet can be found [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).\n\n# \"#\" is used for Main title (h1)\n## \"##\" is used for Section title (h2)\n### \"###\" is used for Subsection title (h3)\n\n\n\n<center><h2><u>Text (2)</u></h2></center>\n\nEmphasis, aka italics, with *asterisks* or _underscores_.\n\nStrong emphasis, aka bold, with double **asterisks** or __underscores__.\n\nCombined emphasis with **asterisks and _underscores_**.\n\nStrikethrough uses two tildes. ~~Scratch this.~~\n\n<center><h2><u> Text (3)</u></h2></center>\n\n1. Start lines with numbers for ordered lists.\n\n\n* Start lines with asterisk/ minus / plus for unordered lists.\n   - Use 3 spaces to write sub-bullets\n\n\n<center><h2><u>Text (4)</u></h2></center>\nCode-snippets are included with triple back-ticks like this \n\n```python\nimport numpy as np \nx = np.arange(10)\n```\n\n```bash\n> ls -ltr \n```\n\n<center><h2><u>Executable code (1) </u></h2></center>\n\nJupyter can be used in combination with various languages (kernels). A full list can be found [here](https://github.com/jupyter/jupyter/wiki/Jupyter-kernels)\n\nThe most common kernels are \n1. __Python__\n2. Julia\n3. R\n4. Haskell\n5. Javascript\n6. Ruby\n\n<center><h2><u>Executable code (2)</u></h2></center>\n\n* Notebook = One long python script broken into parts + user-content\n\n* Variables created in one cell are available for use in the next cells\n  - This means that the cells need to be run in sequence in general\n\n* Python syntax and normal coding rules apply\n\n* **Note:** Don't carry around large arrays between cells\n\n<center><h2><u>Executable code (3)</u></h2></center>\n\nHere is a simple demo\n\n\n```python\nimport numpy as np \n\nx = np.arange(100)\n```\n\nIn the previous cell, we created an array going from $\\left [ 0,99\\right ]$. We will now compute its mean and standard deviation in a separate cell.\n\n\n```python\nprint('Mean: {0}, Std: {1}'.format(np.mean(x), np.std(x)))\n\n```\n\n<center><h2><u>Executable code (4)</u></h2></center>\n\nOne can also run system commands from within the notebook. Use an exclamation mark in front of your commands. \n\n\n\n```python\n!echo \"Printing GDAL version:\"\n!gdalinfo --version\n```\n\n<center><h2><u>Executable code (5)</u></h2></center>\n\nYou can also pass python variables to shell commands - kind of useful when tying together components in a workflow.\n\n\n```python\n##Pythonic way of searching for files\nimport glob\nnbname = glob.glob('./Slides*.ipynb')[0]\n```\n\nWe will now pass the variable to a shell command directly.\n\n\n```python\n##Programatically\n## os.system('ls -ltr {0}'.format(nbname))\n!ls -ltr {nbname}\n\n```\n\n<center><h2><u>Latex math (1)</u></h2></center>\n\nStandard latex equations should work inline like this $\\left(a + b\\right)^2 \\neq a^2 + b^2$.\n\nOne can also write elaborate equations like this\n\n$\\begin{align}\n\\dot{x} & = \\sigma(y-x) \\\\\n\\dot{y} & = \\rho x - y - xz \\\\\n\\dot{z} & = -\\beta z + xy\n\\end{align}$\n\n<center><h2><u>Latex math (2)</u></h2></center>\n\nMatrices can also be written out using amsmath formatting\n\n\\matrix yields $\\begin{matrix} a & b \\\\ c & d \\end{matrix}$\n\n\\bmatrix yields $\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$\n\n\\pmatrix yields $\\begin{pmatrix} a & b \\\\ c & d \\end{pmatrix}$\n\n\n<center><h2><u>Embedding images (1)</u></h2></center>\n\nImages can be embedded in 2 different ways:\n\n1. Directly using markdown\n   - Not much control over sizing\n   - Simple syntax\n\n\n2. Using HTML\n   - Allows explicit control over sizing\n\n<center><h2><u>Embedding images (2)</u></h2></center>\n\nDirect embedding looks like this\n\n\n\n<center><h2><u>Embedding images (3)</u></h2></center>\n\nEmbedded image with HTML looks like this\n\n\n<center>\n    \n</center>\n\n<center><h1><u> Interactive plotting for teaching </u></h1></center>\n\nJupyter supports interactive plotting and this can be very useful as a teaching tool. Here are some simple examples that can be built upon:\n\n1. [Simple InSAR baseline simulator](../InSARBaseline/InSARBaselineSimulator.ipynb)\n\n\n2. [Impact of DEM error on geolocation](../DEMAndGeocoding/demAndGeocoding.ipynb)\n\n", "meta": {"hexsha": "71b0f6b586d44942e41b1dde3470033d92978905", "size": 11781, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Community/Slides_in_jupyter/Slides_IntroToJupyter.ipynb", "max_stars_repo_name": "danielbeny/opensarlab-notebooks", "max_stars_repo_head_hexsha": "e1e29313880e10b9b50314b6bc0b110cb4717338", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2019-03-20T19:25:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-04T01:47:57.000Z", "max_issues_repo_path": "Community/Slides_in_jupyter/Slides_IntroToJupyter.ipynb", "max_issues_repo_name": "scottstanie/opensarlab-notebooks", "max_issues_repo_head_hexsha": "a1df86a4a74b46145e5c57c58618a7e399a366f0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2021-06-30T00:41:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T16:14:35.000Z", "max_forks_repo_path": "Community/Slides_in_jupyter/Slides_IntroToJupyter.ipynb", "max_forks_repo_name": "scottstanie/opensarlab-notebooks", "max_forks_repo_head_hexsha": "a1df86a4a74b46145e5c57c58618a7e399a366f0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 65, "max_forks_repo_forks_event_min_datetime": "2019-04-04T23:28:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-08T13:24:08.000Z", "avg_line_length": 23.375, "max_line_length": 166, "alphanum_fraction": 0.5250827604, "converted": true, "num_tokens": 1642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1602660483710466, "lm_q2_score": 0.13117322546005344, "lm_q1q2_score": 0.021022614496567126}}
{"text": "##### Copyright 2020 Google\n\n\n```\n#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# Data collection\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n  <td>\n    <a target=\"_blank\" href=\"https://quantumai.google/cirq/experiments/guide/data_collection\">View on QuantumAI</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/ReCirq/blob/master/docs/guide/data_collection.ipynb\">Run in Google Colab</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://github.com/quantumlib/ReCirq/blob/master/docs/guide/data_collection.ipynb\">View source on GitHub</a>\n  </td>\n  <td>\n    <a href=\"https://storage.googleapis.com/tensorflow_docs/ReCirq/docs/guide/data_collection.ipynb\">Download notebook</a>\n  </td>\n</table>\n\nFollowing a set of idioms and using common utilities when running NISQy quantum\nexperiments is advantageous to:\n\n - Avoid duplication of effort for common tasks like data saving and loading\n - Enable easy data sharing\n - Reduce cognitive load of onboarding onto a new experiment. The 'science'\n   part is isolated from an idiomatic 'infrastructure' part.\n - Idioms and conventions are more flexible than a strict framework. You\n   don't need to do everything exactly.\n \nThis notebook shows how to design the infrastructure to support a simple experiment.\n\n## Setup\n\nInstall the ReCirq package:\n\n\n```\ntry:\n    import recirq\nexcept ImportError:\n    !pip install --quiet git+https://github.com/quantumlib/ReCirq\n```\n\nNow import Cirq, ReCirq and the module dependencies:\n\n\n```\nimport os\n\nimport numpy as np\nimport sympy\n\nimport cirq\nimport recirq\n```\n\n## Tasks\n\nWe organize our experiments around the concept of \"tasks\". A task is a unit of work which consists of loading in input data, doing data processing or data collection, and saving results. Dividing your pipeline into tasks can be more of an art than a science. However, some rules of thumb can be observed:\n\n 1. A task should be at least 30 seconds worth of work but less than ten minutes worth of work. Finer division of tasks can make your pipelines more composable, more resistant to failure, easier to restart from failure, and easier to parallelize. Coarser division of tasks can amortize the cost of input and output data serialization and deserialization.\n \n 2. A task should be completely determined by a small-to-medium collection of primitive data type parameters. In fact, these parameters will represent instances of tasks and will act as \"keys\" in a database or on the filesystem.\n\nPractically, a task consists of a `TasknameTask` (use your own name!) dataclass and a function which takes an instance of such a class as its argument, does the requisite data processing, and saves its results. Here, we define the `ReadoutScanTask` class with members that tell us exactly what data we want to collect.\n\n\n```\n@recirq.json_serializable_dataclass(namespace='recirq.readout_scan', \n                                    registry=recirq.Registry,\n                                    frozen=True)\nclass ReadoutScanTask:\n    \"\"\"Scan over Ry(theta) angles from -pi/2 to 3pi/2 tracing out a sinusoid\n    which is primarily affected by readout error.\n\n    See Also:\n        :py:func:`run_readout_scan`\n\n    Attributes:\n        dataset_id: A unique identifier for this dataset.\n        device_name: The device to run on, by name.\n        n_shots: The number of repetitions for each theta value.\n        qubit: The qubit to benchmark.\n        resolution_factor: We select the number of points in the linspace\n            so that the special points: (-1/2, 0, 1/2, 1, 3/2) * pi are\n            always included. The total number of theta evaluations\n            is resolution_factor * 4 + 1.\n    \"\"\"\n    dataset_id: str\n    device_name: str\n    n_shots: int\n    qubit: cirq.GridQubit\n    resolution_factor: int\n\n    @property\n    def fn(self):\n        n_shots = _abbrev_n_shots(n_shots=self.n_shots)\n        qubit = _abbrev_grid_qubit(self.qubit)\n        return (f'{self.dataset_id}/'\n                f'{self.device_name}/'\n                f'q-{qubit}/'\n                f'ry_scan_{self.resolution_factor}_{n_shots}')\n\n\n# Define the following helper functions to make nicer `fn` keys\n# for the tasks:\n    \ndef _abbrev_n_shots(n_shots: int) -> str:\n    \"\"\"Shorter n_shots component of a filename\"\"\"\n    if n_shots % 1000 == 0:\n        return f'{n_shots // 1000}k'\n    return str(n_shots)\n\ndef _abbrev_grid_qubit(qubit: cirq.GridQubit) -> str:\n    \"\"\"Formatted grid_qubit component of a filename\"\"\"\n    return f'{qubit.row}_{qubit.col}'\n```\n\nThere are some things worth noting with this TasknameTask class.\n\n1. We use the utility annotation `@json_serializable_dataclass`, which wraps the vanilla `@dataclass` annotation, except it permits saving and loading instances of `ReadoutScanTask` using Cirq's JSON serialization facilities. We give it an appropriate namespace to distinguish between top-level `cirq` objects.\n\n2. Data members are all primitive or near-primitive data types: `str`, `int`, `GridQubit`. This sets us up well to use `ReadoutScanTask` in a variety of contexts where it may be tricky to use too-abstract data types. First, these simple members allow us to map from a task object to a unique `/`-delimited string appropriate for use as a filename or a unique key. Second, these parameters are immediately suitable to serve as columns in a `pd.DataFrame` or a database table. \n\n3. There is a property named `fn` which provides a mapping from `ReadoutScanTask` instances to strings suitable for use as filenames. In fact, we will use this to save per-task data. Note that every dataclass member variable is used in the construction of `fn`. We also define some utility methods to make more human-readable strings. There must be a 1:1 mapping from task attributes to filenames. In general it is easy to go from a Task object to a filename. It should be possible to go the other way, although filenames prioritize readability over parsability; so in general this relationship won\u2019t be used.\n\n4. We begin with a `dataset_id` field. Remember, instances of `ReadoutScanTask` must completely capture a task. We may want to run the same qubit for the same number of shots on the same device on two different days, so we include `dataset_id` to capture the notion of time and/or the state of the universe for tasks. Each family of tasks should include `dataset_id` as its first parameter.\n\n## Namespacing\n\nA collection of tasks can be grouped into an \"experiment\" with a particular name.\nThis defines a folder `~/cirq-results/[experiment_name]/` under which data will be stored.\nIf you were storing data in a database, this might be the table name.\nThe second level of namespacing comes from tasks' `dataset_id` field which groups together an immutable collection of results taken at roughly the same time.\n\nBy convention, you can define the following global variables in your experiment scripts:\n\n\n```\nEXPERIMENT_NAME = 'readout-scan'\nDEFAULT_BASE_DIR = os.path.expanduser(f'~/cirq-results/{EXPERIMENT_NAME}')\n```\n\nAll of the I/O functions take a `base_dir` parameter to support full control\nover where things are saved / loaded. Your script will use `DEFAULT_BASE_DIR`.\n\nTypically, data collection (i.e. the code in this notebook) would be in a script so you can run it headless for a long time. Typically, analysis is done in one or more notebooks because of their ability to display rich output. By saving data correctly, your analysis and plotting code can run fast and interactively.\n\n## Running a Task\n\nEach task is comprised not only of the Task object, but also a function that executes the task. For example, here we define the process by which we collect data.\n\n - There should only be one required argument: `task` whose type is the class defined to completely specify the parameters of a task. Why define a separate class instead of just using normal function arguments?\n  - Remember this class has a `fn` property that gives a unique string for parameters. If there were more arguments to this function, there would be inputs not specified in `fn` and the data output path could be ambiguous.\n  - By putting the arguments in a class, they can easily be serialized as metadata alongside the output of the task.\n - The behavior of the function must be completely determined by its inputs.\n  - This is why we put a `dataset_id` field in each task that's usually something resembling a timestamp. It captures the 'state of the world' as an input.\n  - It's recommended that you add a check to the beginning of each task function to check if the output file already exists. If it does and the output is completely determined by its inputs, then we can deduce that the task is already done. This can save time for expensive classical pre-computations or it can be used to re-start a collection of tasks where only some of them had completed.\n - In general, you have freedom to implement your own logic in these functions, especially between the beginning (which is code for loading in input data) and the end (which is always a call to `recirq.save()`). Don't go crazy. If there's too much logic in your task execution function, consider factoring out useful functionality into the main library.\n\n\n```\ndef run_readout_scan(task: ReadoutScanTask,\n                     base_dir=None):\n    \"\"\"Execute a :py:class:`ReadoutScanTask` task.\"\"\"\n    if base_dir is None:\n        base_dir = DEFAULT_BASE_DIR\n    \n    if recirq.exists(task, base_dir=base_dir):\n        print(f\"{task} already exists. Skipping.\")\n        return\n\n    # Create a simple circuit\n    theta = sympy.Symbol('theta')\n    circuit = cirq.Circuit([\n        cirq.ry(theta).on(task.qubit),\n        cirq.measure(task.qubit, key='z')\n    ])\n\n    # Use utilities to map sampler names to Sampler objects\n    sampler = recirq.get_sampler_by_name(device_name=task.device_name)\n\n    # Use a sweep over theta values.\n    # Set up limits so we include (-1/2, 0, 1/2, 1, 3/2) * pi\n    # The total number of points is resolution_factor * 4 + 1\n    n_special_points: int = 5\n    resolution_factor = task.resolution_factor\n    theta_sweep = cirq.Linspace(theta, -np.pi / 2, 3 * np.pi / 2,\n                                resolution_factor * (n_special_points - 1) + 1)\n    thetas = np.asarray([v for ((k, v),) in theta_sweep.param_tuples()])\n    flat_circuit, flat_sweep = cirq.flatten_with_sweep(circuit, theta_sweep)\n\n    # Run the jobs\n    print(f\"Collecting data for {task.qubit}\", flush=True)\n    results = sampler.run_sweep(program=flat_circuit, params=flat_sweep,\n                                repetitions=task.n_shots)\n\n    # Save the results\n    recirq.save(task=task, data={\n        'thetas': thetas,\n        'all_bitstrings': [\n            recirq.BitArray(np.asarray(r.measurements['z']))\n            for r in results]\n    }, base_dir=base_dir)\n```\n\n## The driver script\n\nTypically, the above classes and functions will live in a Python module; something like `recirq/readout_scan/tasks.py`. You can then have one or more \"driver scripts\" which are actually executed.\n\nView the driver script as a configuration file that specifies exactly which parameters you want to run. You can see that below, we've formatted the construction of all the task objects to look like a configuration file. This is no accident! As noted in the docstring, the user can be expected to twiddle values defined in the script. Trying to factor this out into an ini file (or similar) is more effort than it's worth.\n\n\n```\n# Put in a file named run-readout-scan.py\n\nimport datetime\nimport cirq_google as cg\n\nMAX_N_QUBITS = 5\n\ndef main():\n    \"\"\"Main driver script entry point.\n\n    This function contains configuration options and you will likely need\n    to edit it to suit your needs. Of particular note, please make sure\n    `dataset_id` and `device_name`\n    are set how you want them. You may also want to change the values in\n    the list comprehension to set the qubits.\n    \"\"\"\n    # Uncomment below for an auto-generated unique dataset_id\n    # dataset_id = datetime.datetime.now().isoformat(timespec='minutes')\n    dataset_id = '2020-02-tutorial'\n    data_collection_tasks = [\n        ReadoutScanTask(\n            dataset_id=dataset_id,\n            device_name='Syc23-simulator',\n            n_shots=40_000,\n            qubit=qubit,\n            resolution_factor=6,\n        )\n        for qubit in cg.Sycamore23.qubits[:MAX_N_QUBITS]\n    ]\n\n    for dc_task in data_collection_tasks:\n        run_readout_scan(dc_task)\n\n\nif __name__ == '__main__':\n    main()\n```\n\nAdditionally, follow good Python convention by wrapping the entry point in a function (i.e. `def main():` rather than putting it directly under `if __name__ == '__main__'`. The latter strategy puts all variables in the global scope (bad!).\n", "meta": {"hexsha": "8b979b1dfa4e879a295764ae0229b0b5f19fa186", "size": 18236, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/guide/data_collection.ipynb", "max_stars_repo_name": "Coiner1909/ReCirq", "max_stars_repo_head_hexsha": "dc52158bf02697c0b0f3022829f0df78665cfcc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 195, "max_stars_repo_stars_event_min_datetime": "2020-04-10T01:56:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:20:25.000Z", "max_issues_repo_path": "docs/guide/data_collection.ipynb", "max_issues_repo_name": "Coiner1909/ReCirq", "max_issues_repo_head_hexsha": "dc52158bf02697c0b0f3022829f0df78665cfcc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 158, "max_issues_repo_issues_event_min_datetime": "2020-04-10T01:39:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T20:24:50.000Z", "max_forks_repo_path": "docs/guide/data_collection.ipynb", "max_forks_repo_name": "Coiner1909/ReCirq", "max_forks_repo_head_hexsha": "dc52158bf02697c0b0f3022829f0df78665cfcc6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 85, "max_forks_repo_forks_event_min_datetime": "2020-04-10T01:56:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T21:44:45.000Z", "avg_line_length": 43.419047619, "max_line_length": 618, "alphanum_fraction": 0.6220662426, "converted": true, "num_tokens": 3115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16451645880021026, "lm_q2_score": 0.12765263361856616, "lm_q1q2_score": 0.021000959239447173}}
{"text": "## LSTM for crude oir price prediction\n\n\n\n```python\n# In order to obtain the correct values for \"credentias\", \"bucket_name\" and \"endpoint\" \n# please follow the tutorial at https://github.com/IBM/skillsnetwork/wiki/Cloud-Object-Storage-Setup\n\ncredentials = {\n  \"apikey\": \"RHPLuwaEctTZ68Ne8FwoHZaXKujcdzApQEgCauExsIbC\",\n  \"cos_hmac_keys\": {\n    \"access_key_id\": \"a89357bb879e4a59aa015abffb144827\",\n    \"secret_access_key\": \"0d78e16cbb6fe96d6f3b55dca4c7f9b6d03ece26626b1cc3\"\n  },\n  \"endpoints\": \"https://control.cloud-object-storage.cloud.ibm.com/v2/endpoints\",\n  \"iam_apikey_description\": \"Auto-generated for key a89357bb-879e-4a59-aa01-5abffb144827\",\n  \"iam_apikey_name\": \"Service credentials-1\",\n  \"iam_role_crn\": \"crn:v1:bluemix:public:iam::::serviceRole:Writer\",\n  \"iam_serviceid_crn\": \"crn:v1:bluemix:public:iam-identity::a/3dba62a148ab4574867f8eb140c3a44e::serviceid:ServiceId-109769b1-d4d5-4997-93a1-faefc036bfa9\",\n  \"resource_instance_id\": \"crn:v1:bluemix:public:cloud-object-storage:global:a/3dba62a148ab4574867f8eb140c3a44e:643e3143-6265-453a-877a-15ae3947ef9a::\"\n}\n\nbucket_name = \"cloud-object-storage-appliedaideeplearning\"\nendpoint = \"https://s3.eu-de.cloud-object-storage.appdomain.cloud\"\n```\n\n\n```python\nimport base64\nfrom ibm_botocore.client import Config\nimport ibm_boto3\nimport time\n\n# Create client \nclient = ibm_boto3.client(\n    's3',\n    aws_access_key_id = credentials[\"cos_hmac_keys\"]['access_key_id'],\n    aws_secret_access_key = credentials[\"cos_hmac_keys\"][\"secret_access_key\"],\n    endpoint_url=endpoint\n)\n\nclient.download_file(bucket_name, 'DCOILBRENTEU.csv', 'DCOILBRENTEU.csv')\n```\n\n\n```python\nimport pandas as pd\n\ndf_data_1 = pd.read_csv('DCOILBRENTEU.csv')\nprint(df_data_1.shape)\ndf_data_1.head()\n```\n\n    (8989, 2)\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>DATE</th>\n      <th>DCOILBRENTEU</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1987-05-20</td>\n      <td>18.63</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1987-05-21</td>\n      <td>18.45</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1987-05-22</td>\n      <td>18.55</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1987-05-25</td>\n      <td>18.60</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1987-05-26</td>\n      <td>18.63</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nData Source\n-----------\nU.S. Energy Information Administration, Crude Oil Prices: Brent - Europe [DCOILBRENTEU], retrieved from FRED, Federal Reserve Bank of St. Louis; https://fred.stlouisfed.org/series/DCOILBRENTEU, January 10, 2018.\n\n\n```python\ndf_data_1 = df_data_1[df_data_1.DCOILBRENTEU != \".\"]\nprint(df_data_1.shape)\n```\n\n    (8747, 2)\n\n\n\n```python\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\ndf_data_1_plot = df_data_1.iloc[:, 1:2].values.astype(float)\n# Visualising the Data\nplt.plot(df_data_1_plot, color = 'red', label = 'Crude Oil Prices')\nplt.title('Crude Oil Prices Historical Data')\nplt.xlabel('Time (Days)')\nplt.ylabel('Crude Oil Prices')\nplt.legend()\nplt.show()\n```\n\nStateful vs. Stateless LSTM\n--------------------------\n\n1. **Stateless**: LSTM updates parameters on **batch 1** and then initiates cell states (meaning - memory, usually with zeros) for **batch 2** \n2. **Stateful**: it uses batch 1 last output cell sates as initial states for batch 2.\n\nWhen to use which?\n----------------\n\n- When  sequences in batches are related to each other (e.g. prices of one commodity), we should better use **stateful** mode\n- Else, when one sequence represents a complete sentence, we  should go with **stateless** mode\n\nBatch-size: which batch-size to choose?\n------------------------------------\n\n**Very important decision!**\n\nImagine, you must learn to recognize a bird...\nYou are presented images of different birds.\n\nWhat would you prefer:\n1. To see the one image at a time, make your notes about special bird qualities (set your **weights**) and then see another bird and so on\n2. **OR** may be you would better learn if you see - let's say 5 - bird images at ones. May be then you can faster notice the bird's intrinsic properties?\n\nI'd say - the second method is more efficient for humans. We need more examples of an entitiy, that we have to distinguish. \n\n**So the machines! Therefore we select a batch size of 64.\nLater in programming assigment we will see how the batch size impacts the prediction accuracy.**\n\n\n```python\n#import packages\nimport numpy as np\nfrom tensorflow.keras.preprocessing import sequence\nfrom tensorflow.keras.models import load_model\n```\n\n\n```python\n# defining the batch size and number of epochs\nbatch_size = 64\nepochs = 120 # 1 epoch: a training round\ntimesteps = 10 # LSTM will learn from timesteps in the past, to predict timesteps in the future. Here 1 timestep = 1 day. \n```\n\nBatch-size and trainings-set size\n-------------------------------\n\nWith **stateful LSTMs** the trainings-set size must be divisible without remainder by the batch-size (modulo = 0)\n\n\n```python\nlength = len(df_data_1)\nprint(length)\nlength *= 1 - 0.1\nprint(length)\n```\n\n    8747\n    7872.3\n\n\n\n```python\n7872.3 % 64.0\n```\n\n\n\n\n    0.3000000000001819\n\n\n\n\n```python\ndef get_train_length(dataset, batch_size, test_percent):\n    # substract test_percent to be excluded from training, reserved for testset\n    length = len(dataset)\n    length *= 1 - test_percent\n    train_length_values = []\n    print(length, int(length) - 100, int(length))\n    for x in range(int(length) - 100, int(length)): \n        modulo = x % batch_size\n        if (modulo == 0):\n            train_length_values.append(x)\n            print(x)\n    return (max(train_length_values))\n```\n\n\n```python\nlength = get_train_length(df_data_1, batch_size, 0.1)\nprint(length)\n```\n\n    7872.3 7772 7872\n    7808\n    7808\n\n\n\n```python\n7808 % 64.0\n```\n\n\n\n\n    0.0\n\n\n\nConstruct input and output data for LSTM\n-------------------------------\n\n\n```python\n#Adding timesteps * 2\nupper_train = length + timesteps*2\ndf_data_1_train = df_data_1[0:upper_train]\ntraining_set = df_data_1_train.iloc[:,1:2].values\nprint(training_set.shape)\nprint(training_set)\n```\n\n    (7828, 1)\n    [['18.63']\n     ['18.45']\n     ['18.55']\n     ...\n     ['64.68']\n     ['64.82']\n     ['66.0']]\n\n\n\n```python\n# Feature Scaling\n# scale between 0 and 1. The weights are easier to find.\nfrom sklearn.preprocessing import MinMaxScaler\n\nsc = MinMaxScaler(feature_range = (0, 1))\ntraining_set_scaled = sc.fit_transform(np.float64(training_set))\nprint(training_set_scaled.shape)\nprint(training_set_scaled)\n```\n\n    (7828, 1)\n    [[0.07067112]\n     [0.0693363 ]\n     [0.07007786]\n     ...\n     [0.41216166]\n     [0.41319985]\n     [0.42195032]]\n\n\n\n```python\nX_train = []\ny_train = []\n\n# Creating a data structure with n timesteps\n\nprint(length + timesteps)\nfor i in range(timesteps, length + timesteps): \n    X_train.append(training_set_scaled[i-timesteps:i,0])\n    y_train.append(training_set_scaled[i:i+timesteps,0])\n\nprint(len(X_train))\nprint(len(y_train))\n#create X_train matrix\n#30 items per array (timestep) \nprint(X_train[0:2])\nprint(np.array(X_train).shape)\n#create Y_train matrix\n#30 items per array (timestep) \nprint(y_train[0:2])\nprint(np.array(y_train).shape)\n```\n\n    7818\n    7808\n    7808\n    [array([0.07067112, 0.0693363 , 0.07007786, 0.07044865, 0.07067112,\n           0.07044865, 0.07044865, 0.07030033, 0.07081943, 0.0710419 ]), array([0.0693363 , 0.07007786, 0.07044865, 0.07067112, 0.07044865,\n           0.07044865, 0.07030033, 0.07081943, 0.0710419 , 0.07156099])]\n    (7808, 10)\n    [array([0.07156099, 0.07178346, 0.07081943, 0.07156099, 0.07178346,\n           0.07178346, 0.0710419 , 0.07178346, 0.07267334, 0.07363737]), array([0.07178346, 0.07081943, 0.07156099, 0.07178346, 0.07178346,\n           0.0710419 , 0.07178346, 0.07267334, 0.07363737, 0.07378569])]\n    (7808, 10)\n\n\n\n```python\n# Reshaping\nX_train, y_train = np.array(X_train), np.array(y_train)\nX_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1)) # shape: (length, timesteps, features)\ny_train = np.reshape(y_train, (y_train.shape[0], y_train.shape[1], 1))\nprint(X_train.shape)\nprint(y_train.shape)\n```\n\n    (7808, 10, 1)\n    (7808, 10, 1)\n\n\n\n```python\n# Building the LSTM\n# Importing the Keras libraries and packages\n\nfrom tensorflow.keras.layers import Dense, Input, LSTM\nfrom tensorflow.keras.models import Model\nimport h5py\n```\n\n\n```python\n# Initialising the LSTM Model with MAE Loss-Function\n# Using Functional API\n\ninputs_1_mae = Input(batch_shape = (batch_size, timesteps, 1)) # 1 feature (dimension): crude oil price\n#each layer is the input of the next layer\nlstm_1_mae = LSTM(10, stateful=True, return_sequences=True)(inputs_1_mae)\nlstm_2_mae = LSTM(10, stateful=True, return_sequences=True)(lstm_1_mae)\n\noutput_1_mae = Dense(units=1)(lstm_2_mae)\n\nregressor_mae = Model(inputs=inputs_1_mae, outputs=output_1_mae)\n\n#adam is fast starting off and then gets slower and more precise\n#mae -> mean absolute error loss function\nregressor_mae.compile(optimizer='adam', loss = 'mae')\nregressor_mae.summary()\n```\n\n    Model: \"model\"\n    _________________________________________________________________\n    Layer (type)                 Output Shape              Param #   \n    =================================================================\n    input_1 (InputLayer)         [(64, 10, 1)]             0         \n    _________________________________________________________________\n    lstm (LSTM)                  (64, 10, 10)              480       \n    _________________________________________________________________\n    lstm_1 (LSTM)                (64, 10, 10)              840       \n    _________________________________________________________________\n    dense (Dense)                (64, 10, 1)               11        \n    =================================================================\n    Total params: 1,331\n    Trainable params: 1,331\n    Non-trainable params: 0\n    _________________________________________________________________\n\n\n\n```python\n# #some learners constantly reported 502 errors in Watson Studio. \n# #This is due to the limited resources in the free tier and the heavy resource consumption of Keras.\n# #This is a workaround to limit resource consumption\n\n# from keras import backend as K\n\n# K.set_session(K.tf.Session(config=K.tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)))\n\n```\n\nHow LSTM Param Number is computed?\n--------------------------------\n\n1. To decide how to handle the memory each LSTM Cell has <bold>3 Gates</bold>:\n    - input (what to let in), \n    - forget (what to forget) and \n    - output (what to write to the output)\n2. LSTM **Cell State** is its **memory**\n3. LSTM Hidden State is equivalent to the Cell output:\n    - lstm_hidden_state_size (number of neurons = memory cells) = lstm_outputs_size\n4. Parameters:\n    - weights for the inputs (lstm_inputs_size)\n    - weights for the outputs (lstm_outputs_size)\n    - bias variable\n5.  Result from previous point - for all 3 Gates and for Cell State ( = 4)  \n   \n    \\begin{equation}\n          \\textbf{PARAMETERS} = \\textbf4 \\times \\textbf{ LSTM outputs size} \\times (\\textbf{weights LSTM inputs size} + \\textbf{weights LSTM outputs size} + 1 \\textbf{ bias variable})\n    \\end{equation}\n    \n\n\n```python\n# 1st LSTM Layer\nparameters = 4 * 10 * (1 + 10 + 1)\nprint(parameters)\n```\n\n    480\n\n\n\n```python\n# 2nd LSTM Layer\nparameters = 4 * 10 * (10 + 10 + 1)\nprint(parameters)\n```\n\n    840\n\n\n\n```python\n#Statefull\nfor i in range(epochs):\n    print(\"Epoch: \" + str(i))\n    #run through all data but the cell, hidden state are used for the next batch.\n    regressor_mae.fit(X_train, y_train, shuffle=False, epochs = 1, batch_size = batch_size)\n    #resets only the states but the weights, cell and hidden are kept.\n    regressor_mae.reset_states()\n    \n#Stateless\n#between the batches the cell and hidden states are lost.\n#regressor_mae.fit(X_train, y_train, shuffle=False, epochs = epochs, batch_size = batch_size)\n```\n\n    Epoch: 0\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0448\n    Epoch: 1\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0477\n    Epoch: 2\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0434\n    Epoch: 3\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0433\n    Epoch: 4\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0441\n    Epoch: 5\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0462\n    Epoch: 6\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0478\n    Epoch: 7\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0482\n    Epoch: 8\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0481\n    Epoch: 9\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0478\n    Epoch: 10\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0471\n    Epoch: 11\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0466\n    Epoch: 12\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0458\n    Epoch: 13\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0449\n    Epoch: 14\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0438\n    Epoch: 15\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0425\n    Epoch: 16\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0413\n    Epoch: 17\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0398\n    Epoch: 18\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0391\n    Epoch: 19\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0379\n    Epoch: 20\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0371\n    Epoch: 21\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0362\n    Epoch: 22\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0354\n    Epoch: 23\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0347\n    Epoch: 24\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0341\n    Epoch: 25\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0335\n    Epoch: 26\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0331\n    Epoch: 27\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0325\n    Epoch: 28\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0320\n    Epoch: 29\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0314\n    Epoch: 30\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0309\n    Epoch: 31\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0305\n    Epoch: 32\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0300\n    Epoch: 33\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0295\n    Epoch: 34\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0290\n    Epoch: 35\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0285\n    Epoch: 36\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0282\n    Epoch: 37\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0276\n    Epoch: 38\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0273\n    Epoch: 39\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0267\n    Epoch: 40\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0264\n    Epoch: 41\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0258\n    Epoch: 42\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0255\n    Epoch: 43\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0251\n    Epoch: 44\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0247\n    Epoch: 45\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0243\n    Epoch: 46\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0240\n    Epoch: 47\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0237\n    Epoch: 48\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0234\n    Epoch: 49\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0233\n    Epoch: 50\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0231\n    Epoch: 51\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0231\n    Epoch: 52\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0230\n    Epoch: 53\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0229\n    Epoch: 54\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0228\n    Epoch: 55\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0229\n    Epoch: 56\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0226\n    Epoch: 57\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0228\n    Epoch: 58\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0225\n    Epoch: 59\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0227\n    Epoch: 60\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0226\n    Epoch: 61\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0227\n    Epoch: 62\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0228\n    Epoch: 63\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0231\n    Epoch: 64\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0230\n    Epoch: 65\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0237\n    Epoch: 66\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0250\n    Epoch: 67\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0218\n    Epoch: 68\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0230\n    Epoch: 69\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0201\n    Epoch: 70\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0206\n    Epoch: 71\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0210\n    Epoch: 72\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0212\n    Epoch: 73\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0214\n    Epoch: 74\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0216\n    Epoch: 75\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0221\n    Epoch: 76\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0224\n    Epoch: 77\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0229\n    Epoch: 78\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0240\n    Epoch: 79\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0240\n    Epoch: 80\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0236\n    Epoch: 81\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0251\n    Epoch: 82\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0230\n    Epoch: 83\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0234\n    Epoch: 84\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0237\n    Epoch: 85\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0228\n    Epoch: 86\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0234\n    Epoch: 87\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0232\n    Epoch: 88\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0234\n    Epoch: 89\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0234\n    Epoch: 90\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0229\n    Epoch: 91\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0228\n    Epoch: 92\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0221\n    Epoch: 93\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0220\n    Epoch: 94\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0213\n    Epoch: 95\n    122/122 [==============================] - 1s 6ms/step - loss: 0.0217\n    Epoch: 96\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0213\n    Epoch: 97\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0217\n    Epoch: 98\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0214\n    Epoch: 99\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0219\n    Epoch: 100\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0216\n    Epoch: 101\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0219\n    Epoch: 102\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0222\n    Epoch: 103\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0217\n    Epoch: 104\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0224\n    Epoch: 105\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0216\n    Epoch: 106\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0221\n    Epoch: 107\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0212\n    Epoch: 108\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0215\n    Epoch: 109\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0211\n    Epoch: 110\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0215\n    Epoch: 111\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0212\n    Epoch: 112\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0216\n    Epoch: 113\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0214\n    Epoch: 114\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0217\n    Epoch: 115\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0215\n    Epoch: 116\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0218\n    Epoch: 117\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0217\n    Epoch: 118\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0218\n    Epoch: 119\n    122/122 [==============================] - 1s 5ms/step - loss: 0.0220\n\n\n\n```python\n#save model\nregressor_mae.save(filepath=\"my_model_with_mae_timesteps_10.h5\")\n```\n\n\n```python\n#load model\nimport h5py\nregressor_mae = load_model(filepath=\"my_model_with_mae_timesteps_10.h5\")\n```\n\n\n```python\nregressor_mae.summary()\n```\n\n    Model: \"model\"\n    _________________________________________________________________\n    Layer (type)                 Output Shape              Param #   \n    =================================================================\n    input_1 (InputLayer)         [(64, 10, 1)]             0         \n    _________________________________________________________________\n    lstm (LSTM)                  (64, 10, 10)              480       \n    _________________________________________________________________\n    lstm_1 (LSTM)                (64, 10, 10)              840       \n    _________________________________________________________________\n    dense (Dense)                (64, 10, 1)               11        \n    =================================================================\n    Total params: 1,331\n    Trainable params: 1,331\n    Non-trainable params: 0\n    _________________________________________________________________\n\n", "meta": {"hexsha": "ec0dbca03bb1fbefe79bc1c5004c89ec2b792bfb", "size": 58572, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "03_Applied_AI_DeepLearning/notebooks/week_3_2_lstm_crude_oil_price_prediction.ipynb", "max_stars_repo_name": "hsotoparada/Advanced-Data-Science-Specialization", "max_stars_repo_head_hexsha": "2bf1804e4c2a7c1841e58c34ca20c717c6174899", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "03_Applied_AI_DeepLearning/notebooks/week_3_2_lstm_crude_oil_price_prediction.ipynb", "max_issues_repo_name": "hsotoparada/Advanced-Data-Science-Specialization", "max_issues_repo_head_hexsha": "2bf1804e4c2a7c1841e58c34ca20c717c6174899", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "03_Applied_AI_DeepLearning/notebooks/week_3_2_lstm_crude_oil_price_prediction.ipynb", "max_forks_repo_name": "hsotoparada/Advanced-Data-Science-Specialization", "max_forks_repo_head_hexsha": "2bf1804e4c2a7c1841e58c34ca20c717c6174899", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.1071428571, "max_line_length": 24136, "alphanum_fraction": 0.6628764597, "converted": true, "num_tokens": 7817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22270014914315836, "lm_q2_score": 0.09401018215490363, "lm_q1q2_score": 0.02093608158687252}}
{"text": "```python\n%matplotlib inline\n```\n\n\nAudio Data Augmentation\n=================\n\n``torchaudio`` provides a variety of ways to augment audio data.\n\n\n\n```python\n# When running this tutorial in Google Colab, install the required packages\n# with the following.\n# !pip install torchaudio\n\nimport torch\nimport torchaudio\nimport torchaudio.functional as F\n\nprint(torch.__version__)\nprint(torchaudio.__version__)\n```\n\nPreparing data and utility functions (skip this section)\n--------------------------------------------------------\n\n\n\n\n\n```python\n#@title Prepare data and utility functions. {display-mode: \"form\"}\n#@markdown\n#@markdown You do not need to look into this cell.\n#@markdown Just execute once and you are good to go.\n#@markdown\n#@markdown In this tutorial, we will use a speech data from [VOiCES dataset](https://iqtlabs.github.io/voices/), which is licensed under Creative Commos BY 4.0.\n\n#-------------------------------------------------------------------------------\n# Preparation of data and helper functions.\n#-------------------------------------------------------------------------------\n\nimport math\nimport os\nimport requests\n\nimport matplotlib.pyplot as plt\nfrom IPython.display import Audio, display\n\n\n_SAMPLE_DIR = \"_sample_data\"\n\nSAMPLE_WAV_URL = \"https://pytorch-tutorial-assets.s3.amazonaws.com/steam-train-whistle-daniel_simon.wav\"\nSAMPLE_WAV_PATH = os.path.join(_SAMPLE_DIR, \"steam.wav\")\n\nSAMPLE_RIR_URL = \"https://pytorch-tutorial-assets.s3.amazonaws.com/VOiCES_devkit/distant-16k/room-response/rm1/impulse/Lab41-SRI-VOiCES-rm1-impulse-mc01-stu-clo.wav\"\nSAMPLE_RIR_PATH = os.path.join(_SAMPLE_DIR, \"rir.wav\")\n\nSAMPLE_WAV_SPEECH_URL = \"https://pytorch-tutorial-assets.s3.amazonaws.com/VOiCES_devkit/source-16k/train/sp0307/Lab41-SRI-VOiCES-src-sp0307-ch127535-sg0042.wav\"\nSAMPLE_WAV_SPEECH_PATH = os.path.join(_SAMPLE_DIR, \"speech.wav\")\n\nSAMPLE_NOISE_URL = \"https://pytorch-tutorial-assets.s3.amazonaws.com/VOiCES_devkit/distant-16k/distractors/rm1/babb/Lab41-SRI-VOiCES-rm1-babb-mc01-stu-clo.wav\"\nSAMPLE_NOISE_PATH = os.path.join(_SAMPLE_DIR, \"bg.wav\")\n\nos.makedirs(_SAMPLE_DIR, exist_ok=True)\n\ndef _fetch_data():\n  uri = [\n    (SAMPLE_WAV_URL, SAMPLE_WAV_PATH),\n    (SAMPLE_RIR_URL, SAMPLE_RIR_PATH),\n    (SAMPLE_WAV_SPEECH_URL, SAMPLE_WAV_SPEECH_PATH),\n    (SAMPLE_NOISE_URL, SAMPLE_NOISE_PATH),\n  ]\n  for url, path in uri:\n    with open(path, 'wb') as file_:\n      file_.write(requests.get(url).content)\n\n_fetch_data()\n\ndef _get_sample(path, resample=None):\n  effects = [\n    [\"remix\", \"1\"]\n  ]\n  if resample:\n    effects.extend([\n      [\"lowpass\", f\"{resample // 2}\"],\n      [\"rate\", f'{resample}'],\n    ])\n  return torchaudio.sox_effects.apply_effects_file(path, effects=effects)\n\ndef get_sample(*, resample=None):\n  return _get_sample(SAMPLE_WAV_PATH, resample=resample)\n\ndef get_speech_sample(*, resample=None):\n  return _get_sample(SAMPLE_WAV_SPEECH_PATH, resample=resample)\n\ndef plot_waveform(waveform, sample_rate, title=\"Waveform\", xlim=None, ylim=None):\n  waveform = waveform.numpy()\n\n  num_channels, num_frames = waveform.shape\n  time_axis = torch.arange(0, num_frames) / sample_rate\n\n  figure, axes = plt.subplots(num_channels, 1)\n  if num_channels == 1:\n    axes = [axes]\n  for c in range(num_channels):\n    axes[c].plot(time_axis, waveform[c], linewidth=1)\n    axes[c].grid(True)\n    if num_channels > 1:\n      axes[c].set_ylabel(f'Channel {c+1}')\n    if xlim:\n      axes[c].set_xlim(xlim)\n    if ylim:\n      axes[c].set_ylim(ylim)\n  figure.suptitle(title)\n  plt.show(block=False)\n\ndef print_stats(waveform, sample_rate=None, src=None):\n  if src:\n    print(\"-\" * 10)\n    print(\"Source:\", src)\n    print(\"-\" * 10)\n  if sample_rate:\n    print(\"Sample Rate:\", sample_rate)\n  print(\"Shape:\", tuple(waveform.shape))\n  print(\"Dtype:\", waveform.dtype)\n  print(f\" - Max:     {waveform.max().item():6.3f}\")\n  print(f\" - Min:     {waveform.min().item():6.3f}\")\n  print(f\" - Mean:    {waveform.mean().item():6.3f}\")\n  print(f\" - Std Dev: {waveform.std().item():6.3f}\")\n  print()\n  print(waveform)\n  print()\n\ndef plot_specgram(waveform, sample_rate, title=\"Spectrogram\", xlim=None):\n  waveform = waveform.numpy()\n\n  num_channels, num_frames = waveform.shape\n  time_axis = torch.arange(0, num_frames) / sample_rate\n\n  figure, axes = plt.subplots(num_channels, 1)\n  if num_channels == 1:\n    axes = [axes]\n  for c in range(num_channels):\n    axes[c].specgram(waveform[c], Fs=sample_rate)\n    if num_channels > 1:\n      axes[c].set_ylabel(f'Channel {c+1}')\n    if xlim:\n      axes[c].set_xlim(xlim)\n  figure.suptitle(title)\n  plt.show(block=False)\n\ndef play_audio(waveform, sample_rate):\n  waveform = waveform.numpy()\n\n  num_channels, num_frames = waveform.shape\n  if num_channels == 1:\n    display(Audio(waveform[0], rate=sample_rate))\n  elif num_channels == 2:\n    display(Audio((waveform[0], waveform[1]), rate=sample_rate))\n  else:\n    raise ValueError(\"Waveform with more than 2 channels are not supported.\")\n\ndef get_rir_sample(*, resample=None, processed=False):\n  rir_raw, sample_rate = _get_sample(SAMPLE_RIR_PATH, resample=resample)\n  if not processed:\n    return rir_raw, sample_rate\n  rir = rir_raw[:, int(sample_rate*1.01):int(sample_rate*1.3)]\n  rir = rir / torch.norm(rir, p=2)\n  rir = torch.flip(rir, [1])\n  return rir, sample_rate\n\ndef get_noise_sample(*, resample=None):\n  return _get_sample(SAMPLE_NOISE_PATH, resample=resample)\n```\n\nApplying effects and filtering\n------------------------------\n\n``torchaudio.sox_effects`` allows for directly applying filters similar to\nthose available in ``sox`` to Tensor objects and file object audio sources.\n\nThere are two functions for this:\n\n-  ``torchaudio.sox_effects.apply_effects_tensor`` for applying effects\n   to Tensor.\n-  ``torchaudio.sox_effects.apply_effects_file`` for applying effects to\n   other audio sources.\n\nBoth functions accept effect definitions in the form\n``List[List[str]]``.\nThis is mostly consistent with how ``sox`` command works, but one caveat is\nthat ``sox`` adds some effects automatically, whereas ``torchaudio``\u2019s\nimplementation does not.\n\nFor the list of available effects, please refer to `the sox\ndocumentation <http://sox.sourceforge.net/sox.html>`__.\n\n**Tip** If you need to load and resample your audio data on the fly,\nthen you can use ``torchaudio.sox_effects.apply_effects_file`` with\neffect ``\"rate\"``.\n\n**Note** ``apply_effects_file`` accepts a file-like object or path-like\nobject. Similar to ``torchaudio.load``, when the audio format cannot be\ninferred from either the file extension or header, you can provide\nargument ``format`` to specify the format of the audio source.\n\n**Note** This process is not differentiable.\n\n\n\n\n\n```python\n# Load the data\nwaveform1, sample_rate1 = get_sample(resample=16000)\n\n# Define effects\neffects = [\n  [\"lowpass\", \"-1\", \"300\"], # apply single-pole lowpass filter\n  [\"speed\", \"0.8\"],  # reduce the speed\n                     # This only changes sample rate, so it is necessary to\n                     # add `rate` effect with original sample rate after this.\n  [\"rate\", f\"{sample_rate1}\"],\n  [\"reverb\", \"-w\"],  # Reverbration gives some dramatic feeling\n]\n\n# Apply effects\nwaveform2, sample_rate2 = torchaudio.sox_effects.apply_effects_tensor(\n    waveform1, sample_rate1, effects)\n\nplot_waveform(waveform1, sample_rate1, title=\"Original\", xlim=(-.1, 3.2))\nplot_waveform(waveform2, sample_rate2, title=\"Effects Applied\", xlim=(-.1, 3.2))\nprint_stats(waveform1, sample_rate=sample_rate1, src=\"Original\")\nprint_stats(waveform2, sample_rate=sample_rate2, src=\"Effects Applied\")\n```\n\nNote that the number of frames and number of channels are different from\nthose of the original after the effects are applied. Let\u2019s listen to the\naudio. Doesn\u2019t it sound more dramatic?\n\n\n\n\n\n```python\nplot_specgram(waveform1, sample_rate1, title=\"Original\", xlim=(0, 3.04))\nplay_audio(waveform1, sample_rate1)\nplot_specgram(waveform2, sample_rate2, title=\"Effects Applied\", xlim=(0, 3.04))\nplay_audio(waveform2, sample_rate2)\n```\n\nSimulating room reverberation\n----------------------------\n\n`Convolution\nreverb <https://en.wikipedia.org/wiki/Convolution_reverb>`__ is a\ntechnique that's used to make clean audio sound as though it has been\nproduced in a different environment.\n\nUsing Room Impulse Response (RIR), for instance, we can make clean speech\nsound as though it has been uttered in a conference room.\n\nFor this process, we need RIR data. The following data are from the VOiCES\ndataset, but you can record your own \u2014 just turn on your microphone\nand clap your hands.\n\n\n\n\n\n```python\nsample_rate = 8000\n\nrir_raw, _ = get_rir_sample(resample=sample_rate)\n\nplot_waveform(rir_raw, sample_rate, title=\"Room Impulse Response (raw)\", ylim=None)\nplot_specgram(rir_raw, sample_rate, title=\"Room Impulse Response (raw)\")\nplay_audio(rir_raw, sample_rate)\n```\n\nFirst, we need to clean up the RIR. We extract the main impulse, normalize\nthe signal power, then flip along the time axis.\n\n\n\n\n\n```python\nrir = rir_raw[:, int(sample_rate*1.01):int(sample_rate*1.3)]\nrir = rir / torch.norm(rir, p=2)\nrir = torch.flip(rir, [1])\n\nprint_stats(rir)\nplot_waveform(rir, sample_rate, title=\"Room Impulse Response\", ylim=None)\n```\n\nThen, we convolve the speech signal with the RIR filter.\n\n\n\n\n\n```python\nspeech, _ = get_speech_sample(resample=sample_rate)\n\nspeech_ = torch.nn.functional.pad(speech, (rir.shape[1]-1, 0))\naugmented = torch.nn.functional.conv1d(speech_[None, ...], rir[None, ...])[0]\n\nplot_waveform(speech, sample_rate, title=\"Original\", ylim=None)\nplot_waveform(augmented, sample_rate, title=\"RIR Applied\", ylim=None)\n\nplot_specgram(speech, sample_rate, title=\"Original\")\nplay_audio(speech, sample_rate)\n\nplot_specgram(augmented, sample_rate, title=\"RIR Applied\")\nplay_audio(augmented, sample_rate)\n```\n\nAdding background noise\n-----------------------\n\nTo add background noise to audio data, you can simply add a noise Tensor to\nthe Tensor representing the audio data. A common method to adjust the\nintensity of noise is changing the Signal-to-Noise Ratio (SNR).\n[`wikipedia <https://en.wikipedia.org/wiki/Signal-to-noise_ratio>`__]\n\n\\begin{align}\\mathrm{SNR} = \\frac{P_\\mathrm{signal}}{P_\\mathrm{noise}}\\end{align}\n\n\\begin{align}{\\mathrm  {SNR_{{dB}}}}=10\\log _{{10}}\\left({\\mathrm  {SNR}}\\right)\\end{align}\n\n\n\n\n\n```python\nsample_rate = 8000\nspeech, _ = get_speech_sample(resample=sample_rate)\nnoise, _ = get_noise_sample(resample=sample_rate)\nnoise = noise[:, :speech.shape[1]]\n\nplot_waveform(noise, sample_rate, title=\"Background noise\")\nplot_specgram(noise, sample_rate, title=\"Background noise\")\nplay_audio(noise, sample_rate)\n\nspeech_power = speech.norm(p=2)\nnoise_power = noise.norm(p=2)\n\nfor snr_db in [20, 10, 3]:\n  snr = math.exp(snr_db / 10)\n  scale = snr * noise_power / speech_power\n  noisy_speech = (scale * speech + noise) / 2\n\n  plot_waveform(noisy_speech, sample_rate, title=f\"SNR: {snr_db} [dB]\")\n  plot_specgram(noisy_speech, sample_rate, title=f\"SNR: {snr_db} [dB]\")\n  play_audio(noisy_speech, sample_rate)\n```\n\nApplying codec to Tensor object\n-------------------------------\n\n``torchaudio.functional.apply_codec`` can apply codecs to a Tensor object.\n\n**Note** This process is not differentiable.\n\n\n\n\n\n```python\nwaveform, sample_rate = get_speech_sample(resample=8000)\n\nplot_specgram(waveform, sample_rate, title=\"Original\")\nplay_audio(waveform, sample_rate)\n\nconfigs = [\n    ({\"format\": \"wav\", \"encoding\": 'ULAW', \"bits_per_sample\": 8}, \"8 bit mu-law\"),\n    ({\"format\": \"gsm\"}, \"GSM-FR\"),\n    ({\"format\": \"mp3\", \"compression\": -9}, \"MP3\"),\n    ({\"format\": \"vorbis\", \"compression\": -1}, \"Vorbis\"),\n]\nfor param, title in configs:\n  augmented = F.apply_codec(waveform, sample_rate, **param)\n  plot_specgram(augmented, sample_rate, title=title)\n  play_audio(augmented, sample_rate)\n```\n\nSimulating a phone recoding\n---------------------------\n\nCombining the previous techniques, we can simulate audio that sounds\nlike a person talking over a phone in a echoey room with people talking\nin the background.\n\n\n\n\n\n```python\nsample_rate = 16000\nspeech, _ = get_speech_sample(resample=sample_rate)\n\nplot_specgram(speech, sample_rate, title=\"Original\")\nplay_audio(speech, sample_rate)\n\n# Apply RIR\nrir, _ = get_rir_sample(resample=sample_rate, processed=True)\nspeech_ = torch.nn.functional.pad(speech, (rir.shape[1]-1, 0))\nspeech = torch.nn.functional.conv1d(speech_[None, ...], rir[None, ...])[0]\n\nplot_specgram(speech, sample_rate, title=\"RIR Applied\")\nplay_audio(speech, sample_rate)\n\n# Add background noise\n# Because the noise is recorded in the actual environment, we consider that\n# the noise contains the acoustic feature of the environment. Therefore, we add\n# the noise after RIR application.\nnoise, _ = get_noise_sample(resample=sample_rate)\nnoise = noise[:, :speech.shape[1]]\n\nsnr_db = 8\nscale = math.exp(snr_db / 10) * noise.norm(p=2) / speech.norm(p=2)\nspeech = (scale * speech + noise) / 2\n\nplot_specgram(speech, sample_rate, title=\"BG noise added\")\nplay_audio(speech, sample_rate)\n\n# Apply filtering and change sample rate\nspeech, sample_rate = torchaudio.sox_effects.apply_effects_tensor(\n  speech,\n  sample_rate,\n  effects=[\n      [\"lowpass\", \"4000\"],\n      [\"compand\", \"0.02,0.05\", \"-60,-60,-30,-10,-20,-8,-5,-8,-2,-8\", \"-8\", \"-7\", \"0.05\"],\n      [\"rate\", \"8000\"],\n  ],\n)\n\nplot_specgram(speech, sample_rate, title=\"Filtered\")\nplay_audio(speech, sample_rate)\n\n# Apply telephony codec\nspeech = F.apply_codec(speech, sample_rate, format=\"gsm\")\n\nplot_specgram(speech, sample_rate, title=\"GSM Codec Applied\")\nplay_audio(speech, sample_rate)\n```\n", "meta": {"hexsha": "13976bb63a36bd39411e99b8ce0a8f43d058acc8", "size": 17444, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/_downloads/348dd7d8be17f21d08f9fd2246e4ad42/audio_data_augmentation_tutorial.ipynb", "max_stars_repo_name": "spongebob03/PyTorch-tutorials-kr", "max_stars_repo_head_hexsha": "efe11ebede0d3384aacd1bdad5881ea8794223c8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 44, "max_stars_repo_stars_event_min_datetime": "2021-12-07T14:51:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:34:17.000Z", "max_issues_repo_path": "docs/_downloads/348dd7d8be17f21d08f9fd2246e4ad42/audio_data_augmentation_tutorial.ipynb", "max_issues_repo_name": "spongebob03/PyTorch-tutorials-kr", "max_issues_repo_head_hexsha": "efe11ebede0d3384aacd1bdad5881ea8794223c8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 128, "max_issues_repo_issues_event_min_datetime": "2021-12-02T18:11:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T05:16:39.000Z", "max_forks_repo_path": "docs/_downloads/348dd7d8be17f21d08f9fd2246e4ad42/audio_data_augmentation_tutorial.ipynb", "max_forks_repo_name": "spongebob03/PyTorch-tutorials-kr", "max_forks_repo_head_hexsha": "efe11ebede0d3384aacd1bdad5881ea8794223c8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2021-12-02T18:56:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T07:18:23.000Z", "avg_line_length": 80.7592592593, "max_line_length": 5039, "alphanum_fraction": 0.6422265535, "converted": true, "num_tokens": 3651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771374883919, "lm_q2_score": 0.06187598269623767, "lm_q1q2_score": 0.0209188551092253}}
{"text": "This notebook is part of the `nbsphinx` documentation: http://nbsphinx.readthedocs.io/.\n\n# Code Cells\n\n## Code, Output, Streams\n\nAn empty code cell:\n\n\n```python\n\n```\n\nTwo empty lines:\n\n\n```python\n\n\n```\n\nLeading/trailing empty lines:\n\n\n```python\n\n\n# 2 empty lines before, 1 after\n\n```\n\nA simple output:\n\n\n```python\n6 * 7\n```\n\nThe standard output stream:\n\n\n```python\nprint('Hello, world!')\n```\n\nNormal output + standard output\n\n\n```python\nprint('Hello, world!')\n6 * 7\n```\n\nThe standard error stream is highlighted and displayed just below the code cell.\nThe standard output stream comes afterwards (with no special highlighting).\nFinally, the \"normal\" output is displayed.\n\n\n```python\nimport sys\n\nprint(\"I'll appear on the standard error stream\", file=sys.stderr, flush=True)\nprint(\"I'll appear on the standard output stream\")\n\"I'm the 'normal' output\"\n```\n\n## Special Display Formats\n\nSee [IPython example notebook](https://nbviewer.jupyter.org/github/ipython/ipython/blob/master/examples/IPython Kernel/Rich Output.ipynb).\n\nTODO: tables? e.g. Pandas DataFrame?\n\n\n```python\nfrom IPython.display import display\n```\n\n### Local Image Files\n\n\n```python\nfrom IPython.display import Image\ni = Image(filename='images/notebook_icon.png')\ni\n```\n\n\n```python\ndisplay(i)\n```\n\nFor some reason this doesn't work with `Image(...)`:\n\n\n```python\nfrom IPython.display import SVG\nSVG(filename='images/python_logo.svg')\n```\n\n### Image URLs\n\n\n```python\nImage(url='https://www.python.org/static/img/python-logo-large.png')\n```\n\n\n```python\nImage(url='https://www.python.org/static/img/python-logo-large.png', embed=True)\n```\n\n\n```python\nImage(url='http://jupyter.org/assets/nav_logo.svg')\n```\n\n\n```python\nImage(url='https://www.python.org/static/favicon.ico')\n```\n\n\n```python\nImage(url='http://python.org/images/python-logo.gif')\n```\n\n### Math\n\n\n```python\nfrom IPython.display import Math\neq = Math(r\"\\int_{-\\infty}^\\infty f(x) \\delta(x - x_0) dx = f(x_0)\")\neq\n```\n\n\n```python\ndisplay(eq)\n```\n\n\n```latex\n%%latex\n\\begin{equation}\n\\int_{-\\infty}^\\infty f(x) \\delta(x - x_0) dx = f(x_0)\n\\end{equation}\n```\n\n### YouTube Videos\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('WAikxUGbomY')\n```\n\n### Unsupported Output Types\n\nIf a code cell produces data with an unsupported MIME type, the Jupyter Notebook doesn't generate any output.\n`nbsphinx`, however, shows a warning message.\n\n\n```python\ndisplay({\n    'text/x-python': 'print(\"Hello, world!\")',\n    'text/x-haskell': 'main = putStrLn \"Hello, world!\"',\n}, raw=True)\n```\n\n## ANSI Colors\n\nThe standard output and standard error streams may contain [ANSI escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code) to change the text and background colors.\n\n\n```python\nprint('BEWARE: \\x1b[1;33;41mugly colors\\x1b[m!', file=sys.stderr, flush=True)\nprint('ABC\\x1b[43mDEF\\x1b[35mGHI\\x1b[1mJKL\\x1b[49mMNO\\x1b[39mPQR\\x1b[22mSTU')\n```\n\nThe following code showing the 8 basic ANSI colors is based on http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html.\nEach of the 8 colors has an \"intense\" variation, which is used for bold text.\n\n\n```python\ntext = ' XYZ '\nformatstring = '\\x1b[{}m' + text + '\\x1b[m'\n\nprint(' ' * 6 + ' ' * len(text) +\n      ''.join('{:^{}}'.format(bg, len(text)) for bg in range(40, 48)))\nfor fg in range(30, 38):\n    for bold in False, True:\n        fg_code = ('1;' if bold else '') + str(fg)\n        print(' {:>4} '.format(fg_code) + formatstring.format(fg_code) +\n              ''.join(formatstring.format(fg_code + ';' + str(bg))\n                      for bg in range(40, 48)))\n```\n\nANSI also supports a set of 256 indexed colors.\nThe following code showing all of them is based on http://bitmote.com/index.php?post/2012/11/19/Using-ANSI-Color-Codes-to-Colorize-Your-Bash-Prompt-on-Linux.\n\n\n```python\nformatstring = '\\x1b[38;5;{0};48;5;{0}mX\\x1b[1mX\\x1b[m'\n\nprint('  + ' + ''.join('{:2}'.format(i) for i in range(36)))\nprint('  0 ' + ''.join(formatstring.format(i) for i in range(16)))\nfor i in range(7):\n    i = i * 36 + 16\n    print('{:3} '.format(i) + ''.join(formatstring.format(i + j)\n                                      for j in range(36) if i + j < 256))\n```\n\nYou can even use 24-bit RGB colors:\n\n\n```python\nstart = 255, 0, 0\nend = 0, 0, 255\nlength = 79\nout = []\n\nfor i in range(length):\n    rgb = [start[c] + int(i * (end[c] - start[c]) / length) for c in range(3)]\n    out.append('\\x1b['\n               '38;2;{rgb[2]};{rgb[1]};{rgb[0]};'\n               '48;2;{rgb[0]};{rgb[1]};{rgb[2]}mX\\x1b[m'.format(rgb=rgb))\nprint(''.join(out))\n```\n", "meta": {"hexsha": "b8f2341772d3288e14377a506c708eab523c1e1e", "size": 10500, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/code-cells.ipynb", "max_stars_repo_name": "bomboradata/nbsphinx", "max_stars_repo_head_hexsha": "843eae55e506eb1b5c941709983eff3bba5bcf02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/code-cells.ipynb", "max_issues_repo_name": "bomboradata/nbsphinx", "max_issues_repo_head_hexsha": "843eae55e506eb1b5c941709983eff3bba5bcf02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-19T19:11:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-19T19:11:39.000Z", "max_forks_repo_path": "doc/code-cells.ipynb", "max_forks_repo_name": "isabella232/nbsphinx", "max_forks_repo_head_hexsha": "843eae55e506eb1b5c941709983eff3bba5bcf02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-19T19:09:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T19:09:41.000Z", "avg_line_length": 21.0843373494, "max_line_length": 178, "alphanum_fraction": 0.510952381, "converted": true, "num_tokens": 1340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30074557894124154, "lm_q2_score": 0.06954175173725284, "lm_q1q2_score": 0.020914374386808196}}
{"text": "<center>\n\n# Jupyter Notebooks\n\n</center>\n\n<center>\n\n\n\nFig. 1 - This is a translated snapshot from a text by Galileo Galilei,<br> the Sidereus Nuncius or the very first jupyter notebook.\n</center>\n\n## What is it?\n\nIn the Sidereus Nuncius [[1](#Galilei1610)] Galileo notes his observations of the moons of Jupyter, which led him to the conclusion that earth orbits around the sun. Galileos notes include data (his drawings), metadata (time, weather, telescope properties) and text in the form of methods, analysis, and conclusions [[2](#Goodman2014)]. And that is what todays jupter notebooks are about. Sharing a scientific work based on data, bringing everything together in one document:\n* data and metadata\n* code applied to the data\n* text \n* visualization of the data\n\n## What can it do?\n\n* You can write rich-text using markdown or html. You can also include images and other media.\n* You can display equations using inline latex\n* You can write and execute code in different programming languages, including julia, python [[3](#VanRossum1995)] and R\n* You can run shell commands and install software \n* You can use widgets and interactive tables and plot\n* notebooks + python and python libraries make it easy to load and process data\n* You can save and share the notebook file\n* You can run locally, on a server or in the cloud\n* You can export a notebook as slideshows, latex or pdf-documents\n\n## OK, how do I do that?\n\nHere are the basics. \n* A notebook is made up of cells.\n    * Each cell has one of 3 possible types\n        * **Markdown**\n        * **Code**\n        * **Raw**\n        \nYou do not see the cells when you look at the notebook. However when you **click** somewhere into the notebook, you will see a blue bar at the left, that shows the extent of the cell into which you clicked. In colab you will see a shadow around the cell instead of the blue bar to the left. When you **double-click** a cell, you'll switch it into edit mode. You get back to display mode by hitting **shift+enter**. If you do this on a code cell the code is executed and if it has any output, the output is displayed below the code. When you hit *shift-enter* on a cell the next cell will become the new active cell. If the cell was the last cell in the notebook, a new cell will automatically be inserted.\n\nYou can either use the menu at the top, to insert and run cells and to save the notebook, or when you are in edit (enter or double-click) or command mode (esc), keyboard shortcuts. Here are some of the most important:\n\n* enter - enter edit mode of the active cell\n* esc - go to command mode\n* shift-enter - execute the active cell and display the result\n* when in command mode (in colab hit ctrl+m before pressing the key):\n    * m - switch the selected cell to *markdown*\n    * y - switch the selected cell to *code*\n    * d - delete the selected cell\n    * a - insert a new cell above the selected cell\n    * b - insert a new cell below the selected cell\n    * ctrl + s - save the notebook\n* when in edit mode\n    * ctrl + z - undo\n    * ctrl + y - redo\n\nYou can get along with just the shotcuts above but for your convenience [here](https://cheatography.com/weidadeyue/cheat-sheets/jupyter-notebook/pdf_bw/) are more keyboard shortcuts.\n\n### Raw Cells\n\nRaw cells are useful when converting a notebook into another document, for example a latex-document. We will note talk about them here, you can savely ignore there existence for now.\n\n### Markdown cells\n\nMarkdown is easy. You can switch any of the text cells in this notebook to edit-mode and see how it is done. Here are some markdown features:\n***\n* \\# makes a line a heading of level 1\n# A first level heading\n* \\#\\# makes a line a heading of level 2\n## A second level heading\n* an empty line begins a new paragraph\n* \\* + space starts a bullet-list, use indentation for multiple levels\n    * item 1.1\n    * item 1.2\n        * item 2.1\n        * itme 2.2   \n* Lines starting with 1. make numbered lists\n1. item 1\n1. item 2\n    1. item 2A\n    1. item 2B\n* emphasis\n    * \\*text\\* makes text emphasized, rendered *in italics*\n    * \\*\\*text\\*\\* makes strong emphazied text, rendered **as bold text**\n* \\[text\\]\\(url\\) makes a link, for example [jupyter.org](https://jupyter.org/)\n* \\!\\[text\\]\\(url\\) displays the image at the url, for example: <center>\n\n</center>\n***    \nThat's it, you can find more about markdown [here](https://sourceforge.net/p/jupiter/wiki/markdown_syntax/).\n\n### Equations with latex\n\nIn markdown cells you can insert equations written in the latex [[4](#wikibook_latex)] format, by putting the text between \\$ signs. \nFor example:\n\n$ X_s(f)\\ \\triangleq \\sum_{k=-\\infty}^{\\infty} X\\left(f - k f_s\\right) = \\sum_{n=-\\infty}^{\\infty} T\\cdot x(nT)\\ e^{-i 2\\pi n T f} $\n\nThat looks pretty complicated, but it's not all this bad. Here are some elements\n\n* _ makes a subscript $X_s$\n* ^ makes an exponent, for example e^{2 \\cdot x} gives $e^{2 \\cdot x}$\n* different parts can be separated by {}, for example X_{2 \\cdot i} gives: $X_{2 \\cdot i}$\n* functions and special symbols start with a backslash (\\\\), for example \\\\pi gives $\\pi$ and \\\\sin(x) gives $\\sin(x)$\n* fractions are written as \\\\frac\\{1\\}\\{n\\}: $\\frac{1}{n}$\n\nUse ``$eqn$`` for equations within a text  (inline equations) and equations between \\\\begin and \\\\end for equations on their own. For example: \n\n\\begin{align}\n\\dot{x} & = \\sigma(y-x) \\\\\n\\dot{y} & = \\rho x - y - xz \\\\\n\\dot{z} & = -\\beta z + xy\n\\end{align}\n\nYou can find more examples [here](https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Typesetting%20Equations.html).\n\n### Code cells\n\nIn the upper-right corner of the notebook, you can select the ``kernel``. By selecting the ``kernel`` you tell jupyter by which programming language code-cells will be interpreted. In our case the kernel should be ``Python 3``. \n\nIn colab you can not change the kernel , it is always ``Python 3``, however you can change the allocated hardware (cpu, gpu or tpu) under ``Runtime>Change Runtime``.\n\nA code cell displays the result of the last expresson in the cell as an output (if any) when executed.\n\n\n```python\n2 + 2\n```\n\n\n\n\n    4\n\n\n\nIt also displays output created by the code, for example by the print command.\n\n\n```python\nprint ('Hello')\n```\n\n    Hello\n\n\nThere are widgets, but if you only need a simple input from the user, you can use:\n\n\n```python\nname = input(\"What's your name?\")\nprint(f\"Hello {name}\")\n```\n\n    What's your name?Volker\n    Hello Volker\n\n\nYou will learn about python in the remainder of this course.\n\n#### Cell and line magic\n\nA line in a code cell that begins with %% is a cell magic command. We can for example measure the time the execution of a cell takes with the cell magic %%time. The next cell calculates the sum of all the numbers from 1 to 1000000. On my computer that takes about 6 and a half seconds. You better do not print the result, it is long. \n\n\n```python\n%%time\nimport math \na = math.factorial(1000000)\n```\n\n    CPU times: user 8.66 s, sys: 26.5 ms, total: 8.69 s\n    Wall time: 8.67 s\n\n\nThe line magic %time measures the execution time of a single line.\n\n\n```python\n%time a = math.factorial(10000)\n%time b = math.factorial(100000)\n%time c = math.factorial(1000000)\n```\n\n    CPU times: user 4.99 ms, sys: 0 ns, total: 4.99 ms\n    Wall time: 4.87 ms\n    CPU times: user 179 ms, sys: 0 ns, total: 179 ms\n    Wall time: 179 ms\n    CPU times: user 8.7 s, sys: 16.7 ms, total: 8.72 s\n    Wall time: 8.7 s\n\n\nYou can learn more about magic command [here](https://ipython.readthedocs.io/en/stable/interactive/magics.html).\n\n### Shell commands\n\nIf a line in a cell begins with a !, it is not send to the kernel, but interpreted by the command shell of the operating system. We can use this for example to install python modules or to move files around.\n\nOne way to install additional packages and modules is by using the python package manager ``pip``. \n\nIn the next cell, we install the packages graphviz and ann_visualizer. They provide a method to draw the architecture of neural networks. Since the output of ann_visualizer is a pdf, we also install pdf2image and its dependency poppler to create an image from the pdf.\n\nWe also install mpld3 for displaying interactive plots later.\n\n\n```python\n!pip3 install graphviz\n!pip3 install ann_visualizer\n!pip install pdf2image\n!apt-get install -y poppler-utils\n!pip install mpld3\n```\n\n    Requirement already satisfied: graphviz in /usr/local/lib/python3.6/dist-packages (0.10.1)\n    Requirement already satisfied: ann_visualizer in /usr/local/lib/python3.6/dist-packages (2.5)\n    Requirement already satisfied: pdf2image in /usr/local/lib/python3.6/dist-packages (1.12.1)\n    Requirement already satisfied: pillow in /usr/local/lib/python3.6/dist-packages (from pdf2image) (7.0.0)\n    Reading package lists... Done\n    Building dependency tree       \n    Reading state information... Done\n    E: Unable to locate package poppler\n    Collecting mpld3\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/91/95/a52d3a83d0a29ba0d6898f6727e9858fe7a43f6c2ce81a5fe7e05f0f4912/mpld3-0.3.tar.gz (788kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 798kB 2.8MB/s \n    \u001b[?25hBuilding wheels for collected packages: mpld3\n      Building wheel for mpld3 (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for mpld3: filename=mpld3-0.3-cp36-none-any.whl size=116679 sha256=c610de412d49af802d5528f40a87a7622a668a9f76e27c4a3ee91a9e524f6e58\n      Stored in directory: /root/.cache/pip/wheels/c0/47/fb/8a64f89aecfe0059830479308ad42d62e898a3e3cefdf6ba28\n    Successfully built mpld3\n    Installing collected packages: mpld3\n    Successfully installed mpld3-0.3\n\n\nNow we can use the packages we installed before. We create a simple neural network and write its visualization to a pdf-file. We transform the pdf-file to an image and display it in the notebook.\n\n\n```python\nfrom IPython.display import IFrame\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom ann_visualizer.visualize import ann_viz\nfrom pdf2image import convert_from_path\nfrom pdf2image.exceptions import PDFInfoNotInstalledError, PDFPageCountError, PDFSyntaxError\nN=3\nmodel = Sequential()\nmodel.add(Dense(N*N-1, input_dim=(N*N), activation='relu'))\nmodel.add(Dense(1, activation='sigmoid'))\nann_viz(model, title='A simple densly connected network.')\nimages = convert_from_path('./network.gv.pdf')\nimages[0]\n```\n\nHere are some usefull shell commands [[5](#wikibook_bourne_shell)] when running on linux:\n\n|command|description|\n|---|---|\n| pwd      | print the working directory |\n| cd <dir> | change the working directory |\n| ls       | list the content of a directory |\n| cat <file> | concatenate and print data |\n| cp <path1> <path2> |  copy a file |\n| man <command> | display the manual page a command |\n    \nYou can find more information about linux shell commands [here](https://www.interserver.net/tips/kb/basic-shell-commands-linux-linux-beginners/).\n\n\n```python\n!pwd\n!ls -al\n```\n\n    /content\n    total 40\n    drwxr-xr-x 1 root root  4096 Apr 28 16:41 .\n    drwxr-xr-x 1 root root  4096 Apr 28 16:23 ..\n    drwxr-xr-x 1 root root  4096 Apr 27 16:13 .config\n    -rw-r--r-- 1 root root  2529 Apr 28 16:54 network.gv\n    -rw-r--r-- 1 root root 16448 Apr 28 16:54 network.gv.pdf\n    drwxr-xr-x 1 root root  4096 Apr  3 16:24 sample_data\n\n\n## Loading and displaying data from excel\n\nTo finish this introduction, an example to demonstrate how easy it is to load and display data in jupyter notebooks. We load an excel file from the website of the French INSEE institute, containing the evolution of greenhouse gas emissions under the Kyoto Protocol from 1990 to 2018. \n\nThe next loads the content of the excel file and displays a part of it as a table.\n\n\n```python\nimport pandas as pd\nts = pd.read_excel('https://www.insee.fr/fr/statistiques/fichier/4277613/T20F023.xlsx', index_col=0)\nts = pd.DataFrame(ts).reset_index()\nts.columns = ['Ann\u00e9e', \"Taux d'\u00e9volution\"]\nts = ts[3:]\nts[1:10]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Ann\u00e9e</th>\n      <th>Taux d'\u00e9volution</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>4</th>\n      <td>1991</td>\n      <td>4.9469</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>1992</td>\n      <td>2.81111</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>1993</td>\n      <td>-1.167</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>1994</td>\n      <td>-2.33197</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>1995</td>\n      <td>-0.901934</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>1996</td>\n      <td>2.26261</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>1997</td>\n      <td>0.913283</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>1998</td>\n      <td>3.42333</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>1999</td>\n      <td>1.9635</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nAnd now we plot the data as an interactive graph.\n\n\n```python\nimport mpld3\naxes = ts.plot(title=\"Plotting data from an excel file\", figsize=(12,4))\nmpld3.display()\n```\n\n\n\n\n\n\n<style>\n\n</style>\n\n<div id=\"fig_el1231407190348483688044489715\"></div>\n\n\n\n\n## Literature\n\n<a name=\"Galilei1610\"></a>\n1. G. Galilei. [Sidereus nuncius](https://www.library.si.edu/digital-library/book/sidereusnuncius00gali). Thomas Baglioni, 1610.\n<a name=\"Goodman2014\"></a>\n1. Alyssa Goodman, Alberto Pepe, Alexander W. Blocker, Christine L. Borgman, Kyle Cranmer, Merc\u00e8 Crosas, Rosanne Di Stefano, Yolanda Gil, Paul Groth, Margaret Hedstrom, David W. Hogg, Vinay Kashyap, Ashish Mahabal, Aneta Siemiginowska, Aleksandra Slavkovic. [Ten Simple Rules for the Care and Feeding of Scientific Data](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3998871/). PLoS Computational Biology In press Public Library of Science, 2014.\n<a name=\"VanRossum1995\"></a>\n1. Van Rossum G, Drake Jr FL. [Python tutorial](https://ir.cwi.nl/pub/5007/05007D.pdf). Centrum voor Wiskunde en Informatica Amsterdam, The Netherlands; 1995.\n<a name=\"wikibook_latex\"></a>\n1. Wikibooks contributors, ['LaTeX'](https://en.wikibooks.org/w/index.php?title=LaTeX&oldid=3659624), Wikibooks, The Free Textbook Project, 16 February 2020, 07:51 UTC, accessed 28 April 2020\n<a name=\"wikibook_bourne_shell\"></a>\n1. Wikibooks contributors, ['Bourne Shell Scripting'](https://en.wikibooks.org/w/index.php?title=Bourne_Shell_Scripting&oldid=3502722), Wikibooks, The Free Textbook Project, 15 December 2018, 04:17 UTC, accessed 28 April 2020\n\n\n\n\n", "meta": {"hexsha": "4b2e7dbc920898985641c04a8a07dd85aa74e265", "size": 435341, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "PIAH_01_jupyter.ipynb", "max_stars_repo_name": "MontpellierRessourcesImagerie/python_in_an_hour", "max_stars_repo_head_hexsha": "ced9be19dea6cb300fbcf80ddedd22f46a5a7dee", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PIAH_01_jupyter.ipynb", "max_issues_repo_name": "MontpellierRessourcesImagerie/python_in_an_hour", "max_issues_repo_head_hexsha": "ced9be19dea6cb300fbcf80ddedd22f46a5a7dee", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PIAH_01_jupyter.ipynb", "max_forks_repo_name": "MontpellierRessourcesImagerie/python_in_an_hour", "max_forks_repo_head_hexsha": "ced9be19dea6cb300fbcf80ddedd22f46a5a7dee", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 447.421377184, "max_line_length": 389658, "alphanum_fraction": 0.9181147652, "converted": true, "num_tokens": 4245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1127954092652892, "lm_q2_score": 0.18476751289253923, "lm_q1q2_score": 0.020840927235643562}}
{"text": "```\nCopyright 2021 Twitter, Inc.\nSPDX-License-Identifier: Apache-2.0\n```\n\n## Image Crop Analysis\n\n[](https://colab.research.google.com/github/twitter-research/image-crop-analysis/blob/master/notebooks/Image%20Crop%20Analysis.ipynb)\n\n\n```python\nimport logging\nimport shlex\nimport subprocess\nimport sys\nfrom collections import namedtuple\nfrom pathlib import Path\n\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.collections import PatchCollection\nfrom matplotlib.patches import Rectangle\n\nlogging.basicConfig(level=logging.ERROR)\n```\n\n\n```python\nimport platform\n\nBIN_MAPS = {\"Darwin\": \"mac\", \"Linux\": \"linux\"}\n\nHOME_DIR = Path(\"../\").expanduser()\n\ntry:\n    import google.colab\n    ! pip install pandas scikit-learn scikit-image statsmodels requests dash\n    ! [[ -d image-crop-analysis ]] || git clone https://github.com/twitter-research/image-crop-analysis.git\n    HOME_DIR = Path(\"./image-crop-analysis\").expanduser()\n    IN_COLAB = True\nexcept:\n    IN_COLAB = False\n\nsys.path.append(str(HOME_DIR / \"src\"))\nbin_dir = HOME_DIR / Path(\"./bin\")\nbin_path = bin_dir / BIN_MAPS[platform.system()] / \"candidate_crops\"\nmodel_path = bin_dir / \"fastgaze.vxm\"\ndata_dir = HOME_DIR / Path(\"./data/\")\ndata_dir.exists()\n```\n\n\n```python\nimg_path = next(data_dir.glob(\"./*.jpeg\"))\nimg_path\n```\n\n\n```python\nimg = mpimg.imread(img_path)\nplt.imshow(img)\nplt.gca().add_patch(\n    Rectangle((0, 0), 200, 112, linewidth=1, edgecolor=\"r\", facecolor=\"none\")\n)\n```\n\n\n```python\nstr(img_path.absolute())\n```\n\n\n```python\ncmd = f\"{str(bin_path)} {str(model_path)} '{img_path.absolute()}' show_all_points\"\ncmd\n```\n\n\n```python\noutput = subprocess.check_output(cmd, shell=True)  # Success!\nprint(output.splitlines())\n```\n\n\n```python\n! {str(bin_path)} {str(model_path)} '{img_path.absolute()}' show_all_points | head\n```\n\n\n```python\nfrom crop_api import ImageSaliencyModel, is_symmetric, parse_output, reservoir_sampling\n```\n\n\n```python\nparse_output(output).keys()\n```\n\n\n```python\nmodel = ImageSaliencyModel(crop_binary_path=bin_path, crop_model_path=model_path)\n```\n\n\n```python\nplt.matplotlib.__version__\n```\n\n\n```python\nlist(data_dir.glob(\"./*.jpeg\"))\n```\n\n\n```python\nfor img_path in data_dir.glob(\"*.jpeg\"):\n    print(img_path)\n    model.plot_img_crops(img_path)\n```\n\n\n```python\nfor img_path in data_dir.glob(\"*.jpeg\"):\n    print(img_path)\n    model.plot_img_crops(img_path)\n```\n\n\n```python\nfor img_path in reservoir_sampling(data_dir.glob(\"./*.jpeg\"), K=5):\n    model.plot_img_crops(img_path)\n```\n\n\n```python\nmodel.plot_img_crops(data_dir / Path(\"./dummy.jpeg\"), topK=2)\nplt.savefig(\"dummy.jpg\", bbox_inches=\"tight\")\n```\n\n## Sample crops based on saliency scores\n\n\n* First, we show the top 3 crops based sorted saliency scores (highest first)\n* Next, we show the top 3 crops sampled based on saliency scores converted into probs using the following formula:\n\n$$\n\\begin{equation}\np_i = \\frac{exp(s_i)}{Z}\\\\\nZ = \\sum_{j=0}^{j=N} exp(s_j)\n\\end{equation}\n$$\n\n\n```python\nmodel.plot_img_crops(data_dir / Path(\"./dummy.jpeg\"), topK=3)\nplt.savefig(\"dummy_top3.jpeg\", bbox_inches=\"tight\")\n```\n\n\n```python\nmodel.plot_img_crops(data_dir / Path(\"./dummy.jpeg\"), topK=3, sample=True)\n```\n\n## Crop an image generated using combination of images\n\n\n```python\nfrom PIL import Image\n\nfrom image_manipulation import join_images\n```\n\n\n```python\nimages = [Image.open(x) for x in data_dir.glob(\"./*.jpeg\")]\nimg = join_images(images, col_wrap=2, img_size=(128, -1))\n```\n\n\n```python\nimg\n```\n\n\n```python\nimages = [\n    Image.open(data_dir / Path(\"./dummy.jpeg\")),\n    Image.open(data_dir / Path(\"./dummy.jpeg\")),\n]\nimg = join_images(images, col_wrap=2, img_size=(128, 128), padding=0)\nmodel.plot_img_crops_using_img(img, topK=5)\nplt.savefig(\"dummy_dummy.jpeg\", bbox_inches=\"tight\")\n```\n\n\n```python\nimages = [\n    Image.open(data_dir / Path(\"./dummy.jpeg\")),\n    Image.open(data_dir / Path(\"./dummy.jpeg\")),\n]\nimg = join_images(images, col_wrap=1, img_size=(128, 128), padding=100)\nmodel.plot_img_crops_using_img(img, topK=1)\n```\n\n\n```python\nimg\n```\n\n\n```python\nimg.save(\"dummy_dummy_stiched.jpeg\", \"JPEG\")\n```\n\n\n```python\nimg_path = Path(\"dummy_dummy_stiched.jpeg\")\nmodel.plot_img_crops(img_path, topK=1)\nplt.savefig(\"dummy_dummy.jpeg\", bbox_inches=\"tight\")\n```\n\n\n```python\nmodel.plot_img_crops(data_dir / Path(\"./dummy.jpeg\"), topK=2, aspectRatios=[0.56])\nplt.savefig(\"dummy.jpeg\", bbox_inches=\"tight\")\n```\n\n\n```python\nimg_path = Path(\"dummy_dummy_stiched.jpeg\")\nmodel.plot_img_crops(img_path, topK=1, add_saliency_line=False, col_wrap=3)\nplt.savefig(\"dummy_dummy.jpeg\", bbox_inches=\"tight\")\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "626a62ef4ebaef836d406563758f6257e9e231db", "size": 10257, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Image Crop Analysis.ipynb", "max_stars_repo_name": "Alex36670/image-crop-analysis", "max_stars_repo_head_hexsha": "ba14828645792122a39b246d91df1cc441d8b806", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 212, "max_stars_repo_stars_event_min_datetime": "2021-05-19T18:22:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T23:48:10.000Z", "max_issues_repo_path": "notebooks/Image Crop Analysis.ipynb", "max_issues_repo_name": "Alex36670/image-crop-analysis", "max_issues_repo_head_hexsha": "ba14828645792122a39b246d91df1cc441d8b806", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-05-20T02:09:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T21:44:46.000Z", "max_forks_repo_path": "notebooks/Image Crop Analysis.ipynb", "max_forks_repo_name": "Alex36670/image-crop-analysis", "max_forks_repo_head_hexsha": "ba14828645792122a39b246d91df1cc441d8b806", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 38, "max_forks_repo_forks_event_min_datetime": "2021-05-19T18:01:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T03:40:38.000Z", "avg_line_length": 23.633640553, "max_line_length": 213, "alphanum_fraction": 0.5466510676, "converted": true, "num_tokens": 1251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.04813676992179506, "lm_q1q2_score": 0.020705903951346895}}
{"text": "```python\npip install cirq\n```\n\n    Requirement already satisfied: cirq in /usr/local/lib/python3.7/dist-packages (0.13.1)\n    Requirement already satisfied: cirq-aqt==0.13.1 in /usr/local/lib/python3.7/dist-packages (from cirq) (0.13.1)\n    Requirement already satisfied: cirq-rigetti==0.13.1 in /usr/local/lib/python3.7/dist-packages (from cirq) (0.13.1)\n    Requirement already satisfied: cirq-google==0.13.1 in /usr/local/lib/python3.7/dist-packages (from cirq) (0.13.1)\n    Requirement already satisfied: cirq-pasqal==0.13.1 in /usr/local/lib/python3.7/dist-packages (from cirq) (0.13.1)\n    Requirement already satisfied: cirq-core==0.13.1 in /usr/local/lib/python3.7/dist-packages (from cirq) (0.13.1)\n    Requirement already satisfied: cirq-ionq==0.13.1 in /usr/local/lib/python3.7/dist-packages (from cirq) (0.13.1)\n    Requirement already satisfied: cirq-web==0.13.1 in /usr/local/lib/python3.7/dist-packages (from cirq) (0.13.1)\n    Requirement already satisfied: requests~=2.18 in /usr/local/lib/python3.7/dist-packages (from cirq-aqt==0.13.1->cirq) (2.23.0)\n    Requirement already satisfied: numpy~=1.16 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (1.21.5)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (1.7.3)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (4.62.3)\n    Requirement already satisfied: duet~=0.2.0 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (0.2.3)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (1.7.1)\n    Requirement already satisfied: matplotlib~=3.0 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (3.2.2)\n    Requirement already satisfied: networkx~=2.4 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (2.6.3)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (3.10.0.2)\n    Requirement already satisfied: sortedcontainers~=2.0 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (2.4.0)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (1.3.5)\n    Requirement already satisfied: protobuf>=3.13.0 in /usr/local/lib/python3.7/dist-packages (from cirq-google==0.13.1->cirq) (3.17.3)\n    Requirement already satisfied: google-api-core[grpc]<2.0.0dev,>=1.14.0 in /usr/local/lib/python3.7/dist-packages (from cirq-google==0.13.1->cirq) (1.26.3)\n    Requirement already satisfied: httpx~=0.15.5 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (0.15.5)\n    Requirement already satisfied: idna~=2.10 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (2.10)\n    Requirement already satisfied: attrs~=20.3.0 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (20.3.0)\n    Requirement already satisfied: certifi~=2021.5.30 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (2021.5.30)\n    Requirement already satisfied: iso8601~=0.1.14 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (0.1.16)\n    Requirement already satisfied: six~=1.16.0 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (1.16.0)\n    Requirement already satisfied: toml~=0.10.2 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (0.10.2)\n    Requirement already satisfied: httpcore~=0.11.1 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (0.11.1)\n    Requirement already satisfied: rfc3339~=6.2 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (6.2)\n    Requirement already satisfied: h11~=0.9.0 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (0.9.0)\n    Requirement already satisfied: pyquil~=3.0.0 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (3.0.1)\n    Requirement already satisfied: rfc3986~=1.5.0 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (1.5.0)\n    Requirement already satisfied: python-dateutil~=2.8.1 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (2.8.2)\n    Requirement already satisfied: retrying~=1.3.3 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (1.3.3)\n    Requirement already satisfied: sniffio~=1.2.0 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (1.2.0)\n    Requirement already satisfied: pydantic~=1.8.2 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (1.8.2)\n    Requirement already satisfied: pyjwt~=1.7.1 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (1.7.1)\n    Requirement already satisfied: qcs-api-client~=0.8.0 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (0.8.0)\n    Requirement already satisfied: googleapis-common-protos<2.0dev,>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (1.54.0)\n    Requirement already satisfied: setuptools>=40.3.0 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (57.4.0)\n    Requirement already satisfied: google-auth<2.0dev,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (1.35.0)\n    Requirement already satisfied: packaging>=14.3 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (21.3)\n    Requirement already satisfied: pytz in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (2018.9)\n    Requirement already satisfied: grpcio<2.0dev,>=1.29.0 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (1.43.0)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (4.8)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (0.2.8)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (4.2.4)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core==0.13.1->cirq) (0.11.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core==0.13.1->cirq) (1.3.2)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core==0.13.1->cirq) (3.0.7)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (0.4.8)\n    Requirement already satisfied: rpcq<4.0.0,>=3.6.0 in /usr/local/lib/python3.7/dist-packages (from pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (3.9.2)\n    Requirement already satisfied: importlib-metadata<4.0.0,>=3.7.3 in /usr/local/lib/python3.7/dist-packages (from pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (3.10.1)\n    Requirement already satisfied: lark<0.12.0,>=0.11.1 in /usr/local/lib/python3.7/dist-packages (from pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (0.11.3)\n    Requirement already satisfied: retry<0.10.0,>=0.9.2 in /usr/local/lib/python3.7/dist-packages (from pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (0.9.2)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata<4.0.0,>=3.7.3->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (3.7.0)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests~=2.18->cirq-aqt==0.13.1->cirq) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests~=2.18->cirq-aqt==0.13.1->cirq) (3.0.4)\n    Requirement already satisfied: py<2.0.0,>=1.4.26 in /usr/local/lib/python3.7/dist-packages (from retry<0.10.0,>=0.9.2->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (1.11.0)\n    Requirement already satisfied: decorator>=3.4.2 in /usr/local/lib/python3.7/dist-packages (from retry<0.10.0,>=0.9.2->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (4.4.2)\n    Requirement already satisfied: pyzmq>=17 in /usr/local/lib/python3.7/dist-packages (from rpcq<4.0.0,>=3.6.0->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (22.3.0)\n    Requirement already satisfied: ruamel.yaml in /usr/local/lib/python3.7/dist-packages (from rpcq<4.0.0,>=3.6.0->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (0.17.21)\n    Requirement already satisfied: python-rapidjson in /usr/local/lib/python3.7/dist-packages (from rpcq<4.0.0,>=3.6.0->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (1.5)\n    Requirement already satisfied: msgpack<1.0,>=0.6 in /usr/local/lib/python3.7/dist-packages (from rpcq<4.0.0,>=3.6.0->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (0.6.2)\n    Requirement already satisfied: ruamel.yaml.clib>=0.2.6 in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml->rpcq<4.0.0,>=3.6.0->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (0.2.6)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->cirq-core==0.13.1->cirq) (1.2.1)\n\n\n\n```python\n#import required libraries\nfrom collections import Counter\nimport numpy as np\nimport scipy as sp\nimport cirq\nimport time\n```\n\n\n```python\ndef make_simon_circuit(input_qubits, output_qubits, secret_string):\n    \"\"\"Solves for the secret period s of a 2-to-1 function such that\n    f(x) = f(y) iff x \u2a01 y = s\n    \"\"\"\n    # Initialise quantum circuit \n    c = cirq.Circuit()\n\n    # Initialize input qubits qubits.\n    c.append(\n        [\n            cirq.H.on_each(*input_qubits),\n        ]\n    )\n\n    # Query oracle.\n    def oracle(input_qubits, output_qubits, secret_string,c):\n      for control_qubit, target_qubit in zip(input_qubits, output_qubits):\n        c.append(cirq.CNOT(control_qubit, target_qubit))\n\n      # Create mapping:\n      if sum(secret_string):  # check if the secret string is non-zero\n        significant = list(secret_string).index(1) # Find significant bit of secret string (first non-zero bit)\n          \n        \n\n      # Add secret string to input according to the significant bit:\n      for j in range(len(secret_string)):\n        if secret_string[j] > 0:\n          c.append(cirq.CNOT(input_qubits[significant], output_qubits[j]))\n      \n      # Apply a random permutation to create periodicity:\n      pos = [\n          0,\n          len(secret_string) - 1,\n          len(secret_string) - 2,\n      ] \n      \n      # Swap some qubits to define oracle. We choose first, second last and last ones:\n      c.append(cirq.SWAP(output_qubits[pos[0]], output_qubits[pos[1]]))\n\n      #if(len(pos)>2):\n      #  pass\n\n      c.append(cirq.SWAP(output_qubits[pos[0]], output_qubits[pos[2]]))\n\n    oracle(input_qubits, output_qubits, secret_string,c)\n    # Measure in X basis.\n    c.append([cirq.H.on_each(*input_qubits), cirq.measure(*input_qubits, key='result')])\n\n    return c\n\n```\n\n\n```python\ndef post_processing(data, results):\n    #Solves a system of equations with modulo 2 numbers \n    sing_values = sp.linalg.svdvals(results)\n    tolerance = 1e-5\n    if sum(sing_values < tolerance) == 0:  # check if measurements are linearly dependent\n        flag = True\n        null_space = sp.linalg.null_space(results).T[0]\n        solution = np.around(null_space, 3)  # ignore very small values\n        minval = abs(min(solution[np.nonzero(solution)], key=abs))\n        solution = (solution / minval % 2).astype(int)  # renormalize vector mod 2\n        data.append(str(solution))\n        return flag\n```\n\n\n```python\ndef main(qubit_count):\n\n    data = []  # To store results\n\n    # define a secret string:\n    secret_string = np.random.randint(2, size=qubit_count)\n\n    print(f'Secret string = {secret_string}')\n\n    n_samples = 100\n    for _ in range(n_samples):\n        flag = False  # check if we have a linearly independence between our measured data\n        while not flag:\n            # Choose qubits to use.\n            input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]  # input x\n            output_qubits = [\n                cirq.GridQubit(i + qubit_count, 0) for i in range(qubit_count)\n            ]  # output f(x)\n\n            # Pick coefficients for the oracle and create a circuit to query it &\n            # Append oracle into special quantum circuit querying it exactly once.\n            circuit = make_simon_circuit(input_qubits, output_qubits, secret_string)\n\n            # Sample from the circuit a n-1 times (n = qubit_count).\n            simulator = cirq.Simulator()\n            results = [\n                simulator.run(circuit).measurements['result'][0] for _ in range(qubit_count - 1)\n            ]\n\n            # Classical Post-Processing:\n            flag = post_processing(data, results)\n\n    freqs = Counter(data)\n    print('Circuit:')\n    print(circuit)\n    print(f'Most common answer was : {freqs.most_common(1)[0]}')\n```\n\n\n```python\n# Running the algorithm by altering the circuit for varied values of n, where n represents number of qubits & \n# Capturing time taken for the algorithm to run for each value of n\nt=[]\nfor i in range(3,21):\n  st=time.time()\n  main(i)\n  end=time.time()\n  t.append(end-st)\n```\n\n    Secret string = [0 1 1]\n    Circuit:\n                   \u250c\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2510\n    (0, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                    \u2502                     \u2502\n    (1, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c@\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2502\u2502      \u2502     \u2502       \u2502\n    (2, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2502\u2502\u2502     \u2502     \u2502\n    (3, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502     \u2502     \u2502   \u2502   \u2502\n    (4, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502           \u2502   \u2502\n    (5, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2514\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2518\n    Most common answer was : ('[0 1 1]', 100)\n    Secret string = [0 1 0 1]\n    Circuit:\n                   \u250c\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2510\n    (0, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                    \u2502                      \u2502\n    (1, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2502\u2502       \u2502     \u2502       \u2502\n    (2, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2502\u2502\u2502      \u2502     \u2502       \u2502\n    (3, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2502\u2502\u2502\u2502     \u2502     \u2502\n    (4, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502     \u2502     \u2502   \u2502   \u2502\n    (5, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502\u2502           \u2502   \u2502   \u2502\n    (6, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502           \u2502   \u2502\n    (7, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2514\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2518\n    Most common answer was : ('[0 1 0 1]', 100)\n    Secret string = [0 1 1 0 0]\n    Circuit:\n                   \u250c\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2510   \u250c\u2500\u2500\u2510\n    (0, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                    \u2502                          \u2502\n    (1, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2502\u2502        \u2502      \u2502         \u2502\n    (2, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2502\u2502\u2502       \u2502      \u2502         \u2502\n    (3, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2502\u2502\u2502\u2502      \u2502      \u2502         \u2502\n    (4, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2502\u2502\u2502\u2502\u2502     \u2502      \u2502\n    (5, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u00d7\u2500\u2500\u2500\u2500\u2500\u253c\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502     \u2502\u2502     \u2502\u2502\n    (6, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502\u2502\u2502      \u2502     \u2502\u2502\n    (7, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502\u2502      \u2502      \u2502\n    (8, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                        \u2502      \u2502\n    (9, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2514\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2518   \u2514\u2500\u2500\u2518\n    Most common answer was : ('[0 1 1 0 0]', 100)\n    Secret string = [1 1 0 1 0 1]\n    Circuit:\n                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2510\n    (0, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                     \u2502          \u2502     \u2502   \u2502   \u2502       \u2502\n    (1, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502         \u2502     \u2502   \u2502   \u2502       \u2502\n    (2, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502        \u2502     \u2502   \u2502   \u2502       \u2502\n    (3, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502       \u2502     \u2502   \u2502   \u2502       \u2502\n    (4, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502      \u2502     \u2502   \u2502   \u2502       \u2502\n    (5, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502     \u2502     \u2502   \u2502   \u2502\n    (6, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502\u2502\u2502\u2502\u2502           \u2502   \u2502   \u2502   \u2502   \u2502\n    (7, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502\u2502\u2502\u2502               \u2502   \u2502   \u2502   \u2502\n    (8, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                        \u2502\u2502\u2502               \u2502   \u2502   \u2502   \u2502\n    (9, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                         \u2502\u2502                   \u2502   \u2502   \u2502\n    (10, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                          \u2502                   \u2502   \u2502\n    (11, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2518\n    Most common answer was : ('[1 1 0 1 0 1]', 65)\n    Secret string = [0 1 1 0 1 1 0]\n    Circuit:\n                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2510\n    (0, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                     \u2502                                 \u2502\n    (1, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502          \u2502     \u2502   \u2502   \u2502       \u2502\n    (2, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502         \u2502     \u2502   \u2502   \u2502       \u2502\n    (3, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502        \u2502     \u2502   \u2502   \u2502       \u2502\n    (4, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502       \u2502     \u2502   \u2502   \u2502       \u2502\n    (5, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502      \u2502     \u2502   \u2502   \u2502       \u2502\n    (6, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502     \u2502   \u2502   \u2502\n    (7, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u00d7\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502\u2502\u2502\u2502\u2502\u2502     \u2502\u2502    \u2502   \u2502   \u2502   \u2502\n    (8, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502\u2502\u2502\u2502\u2502      \u2502    \u2502   \u2502   \u2502   \u2502\n    (9, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                        \u2502\u2502\u2502\u2502      \u2502        \u2502   \u2502   \u2502\n    (10, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                         \u2502\u2502\u2502      \u2502        \u2502   \u2502   \u2502\n    (11, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                          \u2502\u2502      \u2502            \u2502   \u2502\n    (12, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                           \u2502      \u2502\n    (13, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2518\n    Most common answer was : ('[0 1 1 0 1 1 0]', 44)\n    Secret string = [0 1 1 1 0 1 1 1]\n    Circuit:\n                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2510\n    (0, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                     \u2502                                          \u2502\n    (1, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502           \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (2, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502          \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (3, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502         \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (4, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502        \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (5, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502       \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (6, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (7, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502     \u2502   \u2502   \u2502   \u2502   \u2502\n    (8, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (9, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502\u2502\u2502\u2502\u2502\u2502           \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (10, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                        \u2502\u2502\u2502\u2502\u2502               \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (11, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                         \u2502\u2502\u2502\u2502                   \u2502   \u2502   \u2502   \u2502   \u2502\n    (12, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                          \u2502\u2502\u2502                   \u2502   \u2502   \u2502   \u2502   \u2502\n    (13, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                           \u2502\u2502                       \u2502   \u2502   \u2502   \u2502\n    (14, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                            \u2502                           \u2502   \u2502\n    (15, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2518\n    Most common answer was : ('[0 1 1 1 0 1 1 1]', 40)\n    Secret string = [0 1 1 1 1 0 0 1 1]\n    Circuit:\n                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2510\n    (0, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                     \u2502                                           \u2502\n    (1, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502            \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (2, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502           \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (3, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502          \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (4, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502         \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (5, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502        \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (6, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502       \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (7, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (8, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502     \u2502   \u2502   \u2502   \u2502   \u2502\n    (9, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (10, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502\u2502\u2502\u2502\u2502\u2502\u2502           \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (11, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                        \u2502\u2502\u2502\u2502\u2502\u2502               \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (12, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                         \u2502\u2502\u2502\u2502\u2502                   \u2502   \u2502   \u2502   \u2502   \u2502\n    (13, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                          \u2502\u2502\u2502\u2502                       \u2502   \u2502   \u2502   \u2502\n    (14, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                           \u2502\u2502\u2502                       \u2502   \u2502   \u2502   \u2502\n    (15, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                            \u2502\u2502                       \u2502   \u2502   \u2502   \u2502\n    (16, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                             \u2502                           \u2502   \u2502\n    (17, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2518\n    Most common answer was : ('[0 1 1 1 1 0 0 1 1]', 27)\n    Secret string = [1 0 1 0 0 0 1 0 1 1]\n    Circuit:\n                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2510\n    (0, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                     \u2502              \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (1, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502             \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (2, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502            \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (3, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502           \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (4, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502          \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (5, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502         \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (6, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502        \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (7, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502       \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (8, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (9, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502     \u2502   \u2502   \u2502   \u2502\n    (10, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502           \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (11, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502           \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (12, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                        \u2502\u2502\u2502\u2502\u2502\u2502\u2502               \u2502   \u2502   \u2502   \u2502   \u2502\n    (13, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                         \u2502\u2502\u2502\u2502\u2502\u2502               \u2502   \u2502   \u2502   \u2502   \u2502\n    (14, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                          \u2502\u2502\u2502\u2502\u2502               \u2502   \u2502   \u2502   \u2502   \u2502\n    (15, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                           \u2502\u2502\u2502\u2502               \u2502   \u2502   \u2502   \u2502   \u2502\n    (16, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                            \u2502\u2502\u2502                   \u2502   \u2502   \u2502   \u2502\n    (17, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                             \u2502\u2502                   \u2502   \u2502   \u2502   \u2502\n    (18, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                              \u2502                       \u2502   \u2502\n    (19, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2518\n    Most common answer was : ('[1 0 1 0 0 0 1 0 1 1]', 20)\n    Secret string = [1 1 0 0 1 1 1 0 0 0 1]\n    Circuit:\n                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2510\n    (0, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                     \u2502               \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (1, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502              \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (2, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502             \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (3, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502            \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (4, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502           \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (5, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502          \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (6, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502         \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (7, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502        \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (8, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502       \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (9, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502     \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (10, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502     \u2502   \u2502   \u2502   \u2502   \u2502\n    (11, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502           \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (12, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502               \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (13, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                        \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502               \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (14, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                         \u2502\u2502\u2502\u2502\u2502\u2502\u2502               \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (15, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                          \u2502\u2502\u2502\u2502\u2502\u2502                   \u2502   \u2502   \u2502   \u2502   \u2502\n    (16, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                           \u2502\u2502\u2502\u2502\u2502                       \u2502   \u2502   \u2502   \u2502\n    (17, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                            \u2502\u2502\u2502\u2502                           \u2502   \u2502   \u2502\n    (18, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                             \u2502\u2502\u2502                           \u2502   \u2502   \u2502\n    (19, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                              \u2502\u2502                           \u2502   \u2502   \u2502\n    (20, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                               \u2502                           \u2502   \u2502\n    (21, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2518\n    Most common answer was : ('[1 1 0 0 1 1 1 0 0 0 1]', 18)\n    Secret string = [1 1 0 1 0 0 1 0 0 1 1 1]\n    Circuit:\n                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2510\n    (0, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                     \u2502                \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (1, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502               \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (2, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502              \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (3, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502             \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (4, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502            \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (5, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502           \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (6, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502          \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (7, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502         \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (8, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502        \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (9, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502       \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (10, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (11, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (12, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502           \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (13, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502               \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (14, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                        \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502               \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (15, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                         \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (16, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                          \u2502\u2502\u2502\u2502\u2502\u2502\u2502                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (17, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                           \u2502\u2502\u2502\u2502\u2502\u2502                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (18, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                            \u2502\u2502\u2502\u2502\u2502                       \u2502   \u2502   \u2502   \u2502   \u2502\n    (19, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                             \u2502\u2502\u2502\u2502                       \u2502   \u2502   \u2502   \u2502   \u2502\n    (20, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                              \u2502\u2502\u2502                       \u2502   \u2502   \u2502   \u2502   \u2502\n    (21, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                               \u2502\u2502                           \u2502   \u2502   \u2502   \u2502\n    (22, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                \u2502                               \u2502   \u2502\n    (23, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2518\n    Most common answer was : ('[1 1 0 1 0 0 1 0 0 1 1 1]', 20)\n    Secret string = [1 1 0 1 1 1 1 1 0 1 1 0 0]\n    Circuit:\n                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2510   \u250c\u2500\u2500\u2510   \u250c\u2500\u2500\u2510\n    (0, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                     \u2502                 \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (1, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502                \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (2, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502               \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (3, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502              \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (4, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502             \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (5, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502            \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (6, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502           \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (7, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502          \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (8, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502         \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (9, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502        \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (10, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502       \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (11, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (12, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (13, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u00d7\u2500\u2500\u2500\u2500\u2500\u253c\u00d7\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502            \u2502\u2502     \u2502\u2502    \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (14, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u253c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502             \u2502     \u2502\u2502    \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (15, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u253c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                        \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502             \u2502     \u2502\u2502    \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (16, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                         \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502             \u2502      \u2502    \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (17, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                          \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502             \u2502      \u2502        \u2502   \u2502   \u2502   \u2502   \u2502\n    (18, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                           \u2502\u2502\u2502\u2502\u2502\u2502\u2502             \u2502      \u2502            \u2502   \u2502   \u2502   \u2502\n    (19, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                            \u2502\u2502\u2502\u2502\u2502\u2502             \u2502      \u2502                \u2502   \u2502   \u2502\n    (20, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                             \u2502\u2502\u2502\u2502\u2502             \u2502      \u2502                    \u2502   \u2502\n    (21, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                              \u2502\u2502\u2502\u2502             \u2502      \u2502                    \u2502   \u2502\n    (22, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                               \u2502\u2502\u2502             \u2502      \u2502                        \u2502\n    (23, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                \u2502\u2502             \u2502      \u2502\n    (24, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                 \u2502             \u2502\n    (25, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2518   \u2514\u2500\u2500\u2518   \u2514\u2500\u2500\u2518\n    Most common answer was : ('[1 1 0 1 1 1 1 1 0 1 1 0 0]', 4)\n    Secret string = [1 0 1 0 1 0 1 1 1 0 1 0 0 0]\n    Circuit:\n                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2510   \u250c\u2500\u2500\u2510   \u250c\u2500\u2500\u2510\n    (0, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                     \u2502                  \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (1, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502                 \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (2, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502                \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (3, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502               \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (4, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502              \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (5, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502             \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (6, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502            \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (7, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502           \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (8, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502          \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (9, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502         \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (10, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502        \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (11, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502       \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (12, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (13, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502\n    (14, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u00d7\u2500\u2500\u2500\u2500\u2500\u253c\u00d7\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502            \u2502\u2502     \u2502\u2502    \u2502   \u2502   \u2502   \u2502\n    (15, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u253c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502            \u2502\u2502     \u2502\u2502    \u2502   \u2502   \u2502   \u2502\n    (16, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u253c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                        \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502             \u2502     \u2502\u2502    \u2502   \u2502   \u2502   \u2502\n    (17, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u253c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                         \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502             \u2502     \u2502\u2502    \u2502   \u2502   \u2502   \u2502\n    (18, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                          \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502             \u2502      \u2502    \u2502   \u2502   \u2502   \u2502\n    (19, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                           \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502             \u2502      \u2502    \u2502   \u2502   \u2502   \u2502\n    (20, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                            \u2502\u2502\u2502\u2502\u2502\u2502\u2502             \u2502      \u2502        \u2502   \u2502   \u2502\n    (21, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                             \u2502\u2502\u2502\u2502\u2502\u2502             \u2502      \u2502            \u2502   \u2502\n    (22, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                              \u2502\u2502\u2502\u2502\u2502             \u2502      \u2502                \u2502\n    (23, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                               \u2502\u2502\u2502\u2502             \u2502      \u2502                \u2502\n    (24, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                \u2502\u2502\u2502             \u2502      \u2502\n    (25, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                 \u2502\u2502             \u2502      \u2502\n    (26, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                  \u2502             \u2502\n    (27, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2518   \u2514\u2500\u2500\u2518   \u2514\u2500\u2500\u2518\n    Most common answer was : ('[1 0 1 0 1 0 1 1 1 0 1 0 0 0]', 3)\n    Secret string = [0 1 1 0 1 0 1 0 1 0 0 1 1 0 1]\n    Circuit:\n                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2510\n    (0, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                     \u2502                                                         \u2502\n    (1, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502                  \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (2, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502                 \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (3, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502                \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (4, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502               \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (5, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502              \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (6, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502             \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (7, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502            \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (8, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502           \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (9, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502          \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (10, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502         \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (11, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502        \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (12, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502       \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (13, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (14, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (15, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (16, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502           \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (17, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                        \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502               \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (18, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                         \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502               \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (19, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                          \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (20, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                           \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (21, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                            \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (22, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                             \u2502\u2502\u2502\u2502\u2502\u2502\u2502                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (23, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                              \u2502\u2502\u2502\u2502\u2502\u2502                           \u2502   \u2502   \u2502   \u2502   \u2502\n    (24, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                               \u2502\u2502\u2502\u2502\u2502                           \u2502   \u2502   \u2502   \u2502   \u2502\n    (25, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                \u2502\u2502\u2502\u2502                           \u2502   \u2502   \u2502   \u2502   \u2502\n    (26, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                 \u2502\u2502\u2502                               \u2502   \u2502   \u2502   \u2502\n    (27, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                  \u2502\u2502                                   \u2502   \u2502   \u2502\n    (28, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                   \u2502                                   \u2502   \u2502\n    (29, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2518\n    Most common answer was : ('[0 1 1 0 1 0 1 0 1 0 0 1 1 0 1]', 6)\n    Secret string = [0 1 0 0 1 0 1 1 0 0 1 1 0 0 0 0]\n    Circuit:\n                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2510   \u250c\u2500\u2500\u2510\n    (0, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                     \u2502                                                     \u2502\n    (1, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502                   \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (2, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502                  \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (3, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502                 \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (4, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502                \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (5, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502               \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (6, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502              \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (7, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502             \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (8, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502            \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (9, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502           \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (10, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502          \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (11, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502         \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (12, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502        \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (13, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502       \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (14, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502      \u2502     \u2502   \u2502   \u2502   \u2502       \u2502\n    (15, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502      \u2502     \u2502   \u2502   \u2502   \u2502\n    (16, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u00d7\u2500\u2500\u2500\u2500\u2500\u253c\u00d7\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502\u2502     \u2502\u2502    \u2502   \u2502   \u2502   \u2502\n    (17, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u253c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502     \u2502\u2502    \u2502   \u2502   \u2502   \u2502\n    (18, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u253c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                        \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502     \u2502\u2502    \u2502   \u2502   \u2502   \u2502\n    (19, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u253c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                         \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502     \u2502\u2502    \u2502   \u2502   \u2502   \u2502\n    (20, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                          \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502      \u2502    \u2502   \u2502   \u2502   \u2502\n    (21, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                           \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502      \u2502    \u2502   \u2502   \u2502   \u2502\n    (22, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                            \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502      \u2502        \u2502   \u2502   \u2502\n    (23, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                             \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502      \u2502            \u2502   \u2502\n    (24, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                              \u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502      \u2502            \u2502   \u2502\n    (25, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                               \u2502\u2502\u2502\u2502\u2502\u2502      \u2502      \u2502            \u2502   \u2502\n    (26, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                \u2502\u2502\u2502\u2502\u2502      \u2502      \u2502                \u2502\n    (27, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                 \u2502\u2502\u2502\u2502      \u2502      \u2502\n    (28, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                  \u2502\u2502\u2502      \u2502      \u2502\n    (29, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                   \u2502\u2502      \u2502      \u2502\n    (30, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                    \u2502      \u2502\n    (31, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2518   \u2514\u2500\u2500\u2518\n    Most common answer was : ('[0 1 0 0 1 0 1 1 0 0 1 0 0 0 0 0]', 2)\n    Secret string = [0 1 1 0 0 1 0 1 1 1 1 1 1 1 0 1 0]\n    Circuit:\n                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2510\n    (0, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                     \u2502                                                                       \u2502\n    (1, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502                    \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (2, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502                   \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (3, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502                  \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (4, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502                 \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (5, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502                \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (6, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502               \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (7, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502              \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (8, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502             \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (9, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502            \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (10, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502           \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (11, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502          \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (12, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502         \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (13, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502        \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (14, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502       \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (15, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (16, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (17, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u00d7\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502\u2502    \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (18, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502    \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (19, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                        \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502        \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (20, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                         \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502        \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (21, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                          \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502        \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (22, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                           \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502            \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (23, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                            \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502            \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (24, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                             \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502                \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (25, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                              \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502                    \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (26, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                               \u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502                        \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (27, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                \u2502\u2502\u2502\u2502\u2502\u2502      \u2502                            \u2502   \u2502   \u2502   \u2502   \u2502\n    (28, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                 \u2502\u2502\u2502\u2502\u2502      \u2502                                \u2502   \u2502   \u2502   \u2502\n    (29, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                  \u2502\u2502\u2502\u2502      \u2502                                    \u2502   \u2502   \u2502\n    (30, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                   \u2502\u2502\u2502      \u2502                                        \u2502   \u2502\n    (31, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                    \u2502\u2502      \u2502                                        \u2502   \u2502\n    (32, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                     \u2502      \u2502\n    (33, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2518\n    Most common answer was : ('[0 1 1 1 0 0 0 0 1 0 1 1 1 0 0 1 1]', 1)\n    Secret string = [0 0 0 0 0 1 1 1 1 0 1 0 1 0 1 1 1 1]\n    Circuit:\n                    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2510\n    (0, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('result')\u2500\u2500\u2500\n                     \u2502                                                                    \u2502\n    (1, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502                                                                   \u2502\n    (2, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502                                                                  \u2502\n    (3, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502                                                                 \u2502\n    (4, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502                                                                \u2502\n    (5, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502                 \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (6, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502                \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (7, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502               \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (8, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502              \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (9, 0): \u2500\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502             \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (10, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502            \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (11, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502           \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (12, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502          \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (13, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502         \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (14, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502        \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (15, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502       \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (16, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502      \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502       \u2502\n    (17, 0): \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c@\u2500\u2500\u2500\u2500\u2500\u253cH\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                     \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (18, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (19, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                       \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (20, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                        \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (21, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                         \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (22, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                          \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502     \u2502     \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (23, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                           \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502           \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (24, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                            \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502               \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (25, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                             \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502                   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (26, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                              \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (27, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                               \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502                       \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (28, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                \u2502\u2502\u2502\u2502\u2502\u2502\u2502                           \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (29, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                 \u2502\u2502\u2502\u2502\u2502\u2502                           \u2502   \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (30, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                  \u2502\u2502\u2502\u2502\u2502                               \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (31, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                   \u2502\u2502\u2502\u2502                               \u2502   \u2502   \u2502   \u2502   \u2502   \u2502\n    (32, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                    \u2502\u2502\u2502                                   \u2502   \u2502   \u2502   \u2502   \u2502\n    (33, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                     \u2502\u2502                                       \u2502   \u2502   \u2502   \u2502\n    (34, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                      \u2502                                           \u2502   \u2502\n    (35, 0): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2518\n    Most common answer was : ('[1 0 1 1 0 1 0 1 1 1 0 1 1 0 0 0 1 1]', 1)\n    Secret string = [0 1 0 1 0 1 1 0 1 0 0 1 1 1 1 1 1 1 1]\n\n\n\n```python\nimport matplotlib.pyplot as plt\n\n# Plotting the time taken by the algorithm against the number of qubits in the circuit to analyze scalability of the algorithm\nplt.plot(range(3,21),t)\nplt.title('Time vs Bits')\nplt.show()\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "7e8d9f8ef10792a9848eed5f9b26b68c8ce9c251", "size": 85007, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Simon's_Algorithm_Cirq.ipynb", "max_stars_repo_name": "ananyoemon/Quantum-Algorithms", "max_stars_repo_head_hexsha": "1707b67e1181c0b9ddee32de6fb150109caa5119", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Simon's_Algorithm_Cirq.ipynb", "max_issues_repo_name": "ananyoemon/Quantum-Algorithms", "max_issues_repo_head_hexsha": "1707b67e1181c0b9ddee32de6fb150109caa5119", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Simon's_Algorithm_Cirq.ipynb", "max_forks_repo_name": "ananyoemon/Quantum-Algorithms", "max_forks_repo_head_hexsha": "1707b67e1181c0b9ddee32de6fb150109caa5119", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 81.2686424474, "max_line_length": 244, "alphanum_fraction": 0.168115567, "converted": true, "num_tokens": 31891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2043418902459481, "lm_q2_score": 0.1008786267847576, "lm_q1q2_score": 0.0206137292826129}}
{"text": "```python\n# Setup environment for all following codes\nimport os\nimport sys\nnb_dir = os.path.abspath('../')\nif nb_dir not in sys.path:\n    sys.path.insert(0, nb_dir)\n\n# Setup the random seed for reproducibility\nimport random\nrandom.seed(\"Genetic Algorithm Applied in UAV's Path-Planning\")\n```\n\n\n```python\n\n```\n\n# Genetic Algorithm Applied in UAV's Path-Planning\n\n\nGustavo de Moura Souza \\\n_School of Electrical Engineering_ \\\n_University of Campinas_ \\\nCampinas, Brazil \\\ng263234@g.unicamp.br\n\n\n\n<h3>Table of Contents<span class=\"tocSkip\"></span></h3>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Abstract\" data-toc-modified-id=\"Abstract-1\">Abstract</a></span></li><li><span><a href=\"#Introduction\" data-toc-modified-id=\"Introduction-2\">Introduction</a></span></li><li><span><a href=\"#Literature-Review\" data-toc-modified-id=\"Literature-Review-3\">Literature Review</a></span></li><li><span><a href=\"#Problem\" data-toc-modified-id=\"Problem-4\">Problem</a></span></li><li><span><a href=\"#Methodology\" data-toc-modified-id=\"Methodology-5\">Methodology</a></span></li><li><span><a href=\"#Results\" data-toc-modified-id=\"Results-6\">Results</a></span></li><li><span><a href=\"#Conclusion\" data-toc-modified-id=\"Conclusion-7\">Conclusion</a></span></li></ul></div>\n\n## Abstract\n\nThe present paper introduces a hybrid genetic algorithm for path planning problem with obstacle avoidance. The genetic algorithm is combined with Ray Casting (RC) algorithm, where RC is responsible to avoid obstacles and to find safe regions\nfor emergency landing. Thus, the path planning system must deal with a non-convex environment when planning and replanning\ntrajectories. It must also work embedded on the UAV. The system runs under a Raspberry Pi board and it is evaluated over 50\nbenchmark maps from literature.\n\n**Keywords** \u2014 hybrid method, ray casting, genetic algorithm, path planning, UAV, emergency landing\n\n## Introduction\n\nUnmanned Aerial Vehicle (UAV) is an aircraft that does not carry a human operator, and it can be piloted remotely or even fly autonomously [1]. There is a broad interest in the development of better, faster and more useful UAV systems. These systems are being used in a series of applications such as field recognizance, agricultural surveying, disaster assistance, law enforcement and others [2].\n\nHowever, the development of UAV systems is still complex\nand requires more practical and theoretical experience to\nmature the UVA\u2019s flights safe. Regulatory laws regarding the\nsafe use of UAV are being defined in many countries, usually\nfollowing standards from international organizations such as\nthe Federal Aviation Administration (FAA), United States; the\nCivil Aviation Safety Authority (CASA), Australia and the\nEuropean Aviation Safety Agency (EASA), Europe Union [3].\nThese rules define patterns for a safe flight and how to achieve\nit regarding the safety of people and the environment.\n\nAutonomous control systems use techniques from the field\nof Artificial Intelligence (AI) to achieve autonomy [4], and it is\na relevant tool to mitigate problems for complex systems such\nas those embedded in UAVs. An autonomous UAV system\ncan sometimes fly safer, execute tasks quicker and preciser\nthan operated by human pilots. For many UAV applications,\nits remote operation by human pilots can be either expensive\nor impracticable [5].\n\nThe automation can be divided into three main categories:\n(i) not autonomous - the UAV system needs to be operated\nby a human and does not perform any movement actions by\nitself; (ii) semi-autonomous - the system has some elements\nthat facilitate the flight, such as stabilizers, autopilots and\npreviously coded actions (e.g., return to land); (iii) autonomous - the system can complete a given mission without human\ninterference.\n\nThe present paper introduces a solution to make the UAV\nsystem get to the third level of automation when planning a\npath. This research mainly investigates a couple of ways to\naddress the path planning problem with risk allocation and\nobstacle avoidance, while taking care of optimizing the fuel\nconsumption and other resources. Two main constraints are\nhandled. First, the system must work within a non-convex\nenvironment, which means to deal with obstacle avoidance.\nSecond, the system must work embedded in the UAV that\nleads to online path planning and replanning.\n\nIn this scenario, we introduce a hybrid evolutionary algorithm integrating a Genetic Algorithm (GA) to Ray Casting\n(RC) algorithm [6] for obstacle avoidance. RC allows solving\nproblems in 3D computer graphics and computational geometry using ray-surface intersection tests. The proposed method\nis evaluated by running under a Raspberry Pi board to planning\npaths for a set of benchmark maps introduced in [7].\n\nThe present paper is organized as follows: Section II describes some related work, and Section III states the problem\napproached. The hybrid evolutionary algorithm is explained\nin Section IV, and the experimental results are reported in\nSection V. The conclusions follow in Section VI\n\n## Literature Review\n\nMission and path planning approaches are described by\n[8]\u2013[11]. A planning system is described in [8] for discrete\nactions and continuous controls being executed by aerial and\nunderwater vehicles. The planner provides autonomy by giving\nthe system a decision-making module that uses a compact\nrepresentation for all the feasible plans. It also presents a\nmathematical formulation to define the set of actions that can\nbe taken by autonomous vehicles.\n\nThe problem approached by this paper is based on a similar\none described in [9], named as Chance-Constrained Optimal\nPath Planning with Obstacles. The problem is formulated\nusing stochastic models to describe the chance-constraints for\nrisk allocation when planning the trajectories. Mathematical\nprogramming based heuristics are proposed that return paths\nbased on upper and lower bound solutions from the stochastic\nmodel.\n\nThe authors in [10] extend the chance-constrained approach\nto continuous time where the risk is bounded from the reflection principle since the trajectory follows a Brownian motion.\nA Mixed-Integer Linear Programming (MILP) formulation is\nproposed in [11] for the same problem, which was able to\nsolve more complex maps within a reduced computational time\nusing an exact method.\n\nThe evolutionary algorithms have been applied to solve\npath planning problems, as described in [12]\u2013[15]. A hybrid\nmethod combining genetic algorithms with Voronoi diagrams\nis introduced by [12], where the Voronoi approach helps to\ncreate the GA population aiming to improve the overall quality\nof solutions. GA is applied in [13] for path planning of mobile\nrobots with obstacle avoidance.\n\nA hybrid algorithm is proposed in [14] that combines\nAnt Colony Optimization (ACO) and GA for path planning\nin mobile robots with obstacle avoidance. ACO returns an\ninitial trajectory which is improved by GA. The aircraft in\n[15] must avoid no-fly zones, radars zones, missiles, and\nanti-aircraft guns. A three-dimensional scenario is assumed,\nand a Differential Evolution (DE) method is proposed for\npath planning. The robustness and convergence speed of DE\noutperforms 11 other algorithms from the literature.\n\nA hybrid method combines a multi-population genetic algorithm with the resolution of a linear programming model in\n[16]. A non-convex environment with uncertainties is assumed,\nand a visibility graph helps to encode all possible paths as\nindividuals. A linear programming model is solved from such\nencoding, and the solution achieved will define the fitness of\nthe individual as well as a possible path to be executed.\nThe path replanning problem for UAVs, under an emergency\nlanding, is approached by [17]. The authors proposed three\npath planning methods: a greedy heuristic, a simple genetic\nalgorithm, and a multi-population genetic algorithm. The\ngreedy heuristic stands for fast feasible paths, while the genetic\nalgorithms return better quality trajectories.\n\nThe Ray Casting technique used in this research was proposed by [18] for solids modelling systems. The complex\nsolids are modelled by combining simpler solids, such as\ncylinders and pyramids, that receive a virtual light ray cast at\ntheir surface. RC is a reliable and extensible method presenting\na high-grade performance in terms of execution time and is\neasily adapted to other scenarios. The authors in [19] apply RC\nas an acceleration technique for Graphical Processing Units\n(GPU), interpreting the solids as volume described by ray\ncasting instead of object-order units. This work influenced the\nuse of RC to render 3D meshes in movies, games and scientific\nvisualization softwares.\n\nRC is applied for machine-tools in [20] to demonstrate the\neffectiveness of using graphics hardware on manufacturing\nproblems. A NASA research presented in [6] a path planner for\nUAV systems using RC to detect and avoid obstacles, taking\ninto account the safety of the mission. The planning algorithm\nalso used a rapidly exploring random tree to find a suitable\npath.\n\nThe present paper introduces a hybrid evolutionary algorithm to deal with the path planning with obstacles approached\nby [9]\u2013[11], [16], but without handling the chance-constraint\nwith risk allocation. Also, we apply the hybrid evolutionary\nalgorithm for path planning as well as for path replanning\nunder emergency landing. It is a different approach from\n[5], [16]. The path planning in [16] needs to solve a linear\nprogramming model, which can be difficult for a planning\nsystem embedded on the UAV as the one proposed here.\nThe emergency path planners in [5] deal with risk allocation,\nand they are tailor-made for emergency landing, while our\napproach is less specific, but it can easily switch from path\nplanning to emergency landing.\n\n\n## Problem\n\nThe path planning problem with obstacles approached in this paper will optimize trajectories where the hard constraint is the obstacle avoidance. Thus, we must avoid the risk to hit a no-fly zone, which is represented by obstacles or regions where the UAV is not allowed to go through.  The optimization criterion is usually to reach the destination, where some soft constraints can also be satisfied, such as running a short trajectory, saving fuel or applying smooth manoeuvres. The problem is non-convex since the trajectory must avoid the no-fly zones through the path planning map. \nFigure 1 give us an example where the UAV must reach the goal point *End* from the start point *Begin*, avoiding collision with obstacles A and B.  \n\n\nFig. 1. Path Planning problem illustration.\n\nWe will also handle the emergency landing situation, where a path replanning must be executed over a stay-in region (landing area). Figure 2 gives us an example where the UAV must reach the goal point *End* from the start point *Begin*, avoiding collision with obstacles A and B, but when a situation happens, an emergency landing is executed over region C, recalculating the route to safely land.  \n\n\nFig. 2. Path Replanning problem illustration.\n\nTo sum up, the problem assumes the UAV must plan a trajectory to reach a destination, avoiding obstacles and optimizing some criterion. Also, if a situation happens, a path replanning is executed to reach a stay-in area. The stay-out (no-fly zones) and stay-in (landing areas) are previously known by the autonomous path planning system.\n\n\n### Problem Description\n\nA mathematical formulation for the path planning problem is presented next based on the formulation described in [9].\n\nEq. 1.\n\\begin{equation}\n    \\text{Minimize}~~ \\Theta () = \\sum_t \\left\\Vert u_t\\right\\Vert\n    \\label{problem:obj}\n\\end{equation}\n\nWhere:\n\nEq. 2.\n\\begin{equation}\n    x_T = x_{goal}\n    \\label{problem:obj4.2}\n\\end{equation}\n\nEq. 3.\n\\begin{equation}\n    x_{t+1} = Ax_t + B_{u_t} + \\mu_t \\text{,\\;~} \\forall(t)\n    \\label{problem:obj4.3}\n\\end{equation}\n\nEq. 4.\n\\begin{equation}\n    x_t \\in \\mathbb{I}_j \\Leftrightarrow \\bigwedge\\limits_{i\\in H_j^\\mathbb{I}} h_i^T x_t \\leq g_i\n    \\label{problem:obj4.6}\n\\end{equation}\n\nEq. 5.\n\\begin{equation}\n    x_t \\in \\mathbb{O}_j \\Leftrightarrow \\bigvee\\limits_{i\\in H_j^\\mathbb{O}} h_i^T x_t \\geq g_i\n    \\label{problem:obj4.7}\n\\end{equation}\n\n\nThe objective function 1 will minimize some metric related to the mission planning such as distance, fuel consumption, collision risk, among others. The authors in [9] define the objective function as a cost proportional to the applied controllers magnitude. In the objective function 1,  $u_t$ can be the acceleration applied at each time step $t$ within the planning horizon $t=1,...,T$.\n\nThe Constraint 2 defines that the last state of the UAV  must be the state defined by $x_{goal}$. The state variable $x_t$ can be represented, e.g., by the position and velocity of the UAV at time step $t$.  The state transitions are defined recursively by Constraints 3. \n\n\nThe Constraints 4 and 5 describe stay-in and stay-out states in which $i \\in H_j$ is the hyperplane  that defines the convex regions for obstacles or landing regions. The obstacles are defined as the disjunction of linear constraints where the UAV must stay outside of one hyperplane at least, otherwise we have a collision. The landing regions are established as the junction of linear constraints where the UAV must stay-in during the path planning.\n\n\n## Methodology\n\n### Hybrid Genetic Algorithm\n\n The Genetic Algorithm receives as input an object that defines the mission the UAV must complete. The object contains one or more no-fly areas $({\\Phi_n}_i)$, an origin $(\\omega_o)$ and a destination $(\\omega_d)$ waypoint, all of them defined in the Cartesian system. The output is the Cartesian waypoints of the best route evolved. In this project, the best individual is abstracted as the best route. The hybridization aspect arises when the Ray Casting algorithm is applied to detect no-fly regions as well as landing areas. This happens during the fitness calculation.\n%The genetic algorithm performs an optimization on the fitness function \\eqref{eq:fitness} which is the problem's objective function \\eqref{problem:obj} that needs to be minimized. \nThe pseudo-code (Algorithm 1) describes our algorithm.\n\n\nAlgorithm 1: Hybrid Genetic Algorithm\n\n[\\\\]: \"\\begin{algorithm}[!htb]\n     \\DontPrintSemicolon\n     \\label{alg:ga}\n      \\KwIn{Criteria: stop\\_criteria; Int: crossover\\_rate, population\\_size; Map: map}\n     \\KwOut{Route: best\\_route}\n     %population $\\leftarrow$ Genesis()\\\\\n     \\While{not stop\\_criteria}{\n        Initialize\\_Routes(population)\\\\\n        Evaluate\\_Fitness(population, map)\\\\\n         \\Repeat{not converge}{\n             \\For{i=1 to crossover\\_rate x population\\_size}{\n                 parents $\\leftarrow$ Tournament(population)\\\\\n                 offspring $\\leftarrow$ Crossover(parents)\\\\\n                 Mutation(offspring)\\\\\n                 Evaluate\\_Fitness(offspring)\\\\\n                 Insert(offspring)\\\\\n             }\n         }\n     }\n     \\Return best\\_route\n     \\newline\n  \\caption{Hybrid Genetic Algorithm}\n \\end{algorithm}\"\n\nThe stop criterion in our computation experiments is the execution time. The selection for reproduction,  crossover and mutation operators are executed while there is no convergence. A new individual is inserted if it has better fitness value than one of its parents. The method converges when no new individuals are inserted in the population, after a total of $crossover\\_rate \\times population\\_size$ individuals has been created. In this case, all individuals are reinitialized, except by the best one. \n\n\n### Individual\n\nThe solution encoding of the GA has the controllers that a UAV needs to perform a trajectory. Thus, the individual is described as a set of values applied to change the  UAV position from one time step to another. The decoding of such individual will return the set of states $\\left[x_t, y_t, v_t, \\alpha_t\\right]$ of the aircraft through the time steps $t$. \n\nLet $T$ be the planning horizon size that has the quantity of time steps or waypoints that is desired to compute. The individual is defined  for $t = 1, \\ldots T$ as follow:\n\n\\begin{equation*}\n    \\begin{aligned}\n        DNA &= [ gene_1,gene_2,\\ldots,gene_t,\\ldots,gene_T ] \\\\\n        gene_t &= (a_t, e_t)\n    \\end{aligned}\n\\end{equation*}\n\nwhere:\n- a := UAV's acceleration (meters/second$^2$)\n- e := UAV's angle (degrees)\n\nThis representation of individual allows the route to move forward with increasing and decreasing velocity and changing angle freedom, constrained by the UAV design. The individual represents the movement in a vectored form. To imply the Cartesian position where this vector leads, it is needed to decode each of the individual's gene. Define $\\gamma DNA$ the set of UAV controllers, i.e. the decoded DNA, for $t = 1, \\ldots T$: \n\\begin{equation*}\n    \\begin{aligned}\n        \\gamma DNA &= [ \\gamma gene_1, \\ldots \\gamma gene_T]\\\\\n        \\gamma gene_t &= (x_t, y_t, v_t, \\alpha_t)\n    \\end{aligned}\n\\end{equation*}\n\nwhere:\n- $x_t$ := UAV's position on the X axis (meters)\n- $y_t$ := UAV's position on the Y axis (meters)\n- $v_t$ := Horizontal UAV's velocity (meters/second)\n- $\\alpha_t$ := Horizontal UAV's angle (direction) (degrees)\n\nFigure 3 illustrates the individual encode and decoding representation.\n\n\nFig. 3. Individual's encoding and decoding\n\nTo decode each gene and generate the $\\gamma DNA$ with $\\gamma gene$s, it is applied the function 6. It transforms the vectors describing the acceleration and angle to a new interpretation, which represents the $x$ and $y$ coordinates, the velocity and the horizontal angle. Thus, $DNA$ represents transitions, and the decoded $\\gamma DNA$ represents states. Let $\\Gamma$ be the function that decodes a gene:\n\nEq. 6.\n\\begin{equation}\n    \\Gamma(gene) = \n    \\begin{cases}\n        x_{t+1} & = x_t + v_t \\cdot \\cos(\\alpha_t) \\cdot \\Delta T \\\\\n        &+ a_t \\cdot \\cos{(\\alpha_t)} \\cdot \\frac{\\Delta T^2}{2}\\\\\n        y_{t+1} & = y_t + v_t \\cdot \\sin(\\alpha_t) \\cdot \\Delta T\\\\\n        &+ a_t \\cdot \\sin{(\\alpha_t)} \\cdot \\frac{\\Delta T^2}{2}\\\\\n        v_{t+1} & = v_t + a \\cdot \\Delta T - \\frac{F \\cdot \\Delta T}{m}\\\\\n        \\alpha_{t+1} & = \\alpha + e \\cdot \\Delta T\n    \\end{cases}\n    \\label{eq:decode}\n\\end{equation}\n\n\nWhere $\\Delta T$ is time variation between two consecutive time steps.\nThe $F$ term is the drag equation (This particular equation was obtained from [5]), defined by Equation 7, that is used to estimate better the position and the movement of the UAV on the air. \n\nEq. 7.\n\\begin{equation}\n    F = 0.5 \\cdot Cd \\cdot \\rho \\cdot A \\cdot v_t^2\n    \\label{eq:F}\n\\end{equation}\n\nThe drag equation allows to determine the strength that an object is subjected to when passing through a fluid (In this case, the fluid is the air.). The constants $Cd$ (The drag coefficient considered was the same for an *angled cube*, which is $0.8$.), $\\rho$ (The specific fluid mass, a.k.a. density, used was $1.225$ given in k/m$^3$.) and $A$ (Area of reference.) are defined according to the UAV's and environment's conditions.\n\n\n### Fitness\n\n\nThe Equation 8 defines the fitness function\n\nEq. 8.\n\\begin{equation}\n    \\begin{aligned}\n    fitness =\n    &~C_{dist} \\cdot f_{dist} + C_{obs} \\cdot f_{obs} \\\\\n    &+  C_{curv} \\cdot f_{curv} +  C_{cons} \\cdot f_{cons} \\\\\n    &+  C_{T} \\cdot f_{T}\n    \\end{aligned}\n    \\label{eq:fitness}\n\\end{equation}\n\nThe first term penalizes the distance from the last waypoint to the destination one. This is done  by calculating the Euclidean distance between those two points in Equation  9. If the distance is less than a threshold $\\epsilon$, it is set zero.\n\nEq. 9.\n\\begin{equation}\n    f_{dist} = \\sqrt{{(\\omega_d^x - \\gamma gene_T^x)}^2 + {(\\omega_d^y - \\gamma gene_T^y)}^2}\n    \\label{eq:fit:dist}\n\\end{equation}\n\nThe second term penalizes the flight over no-fly zones. In this case, the Ray Casting algorithm is applied to detect such constraint violation. Let $\\omega_i$ be the waypoint described by $(\\gamma gene_i^x, \\gamma gene_i^y)$. Let $\\overline{\\omega_i,\\omega_j}$ be the segment that connects two waypoints: $\\omega_i$ and $\\omega_j$. The Equation 10 describes the obstacle fitness function (When t=T, set t+1=0):\n\nEq. 10.\n\\begin{equation}\n    f_{obs} = \n    \\begin{cases}\n        &\\sum_{t=0}^{T} \\sum_{n=0}^{N} RC_P(\\omega_t, \\Phi_n) \\\\\n        &+ RC_S(\\omega_t, \\omega_{t+1}, \\Phi_n)\n    \\end{cases}\n    \\label{eq:fit:obs}\n\\end{equation}\n\nEq. 11.\n\\begin{equation}\n    RC_P(\\omega, \\Phi) = \n    \\begin{cases}\n        1 & \\text{, if } \\omega \\in \\Phi\\\\\n        0 & \\text{, otherwise}\n    \\end{cases}\n    \\label{eq:fit:RC_P}\n\\end{equation}\n\nEq. 12.\n\\begin{equation}\n    RC_S(\\omega_i, \\omega_j, \\Phi) = \\sum_{n=0}^{N} \\lvert \\overline{\\omega_i,\\omega_j} \\bigcap \\Phi_n \\rvert\n    \\label{eq:fit:RC_S}\n\\end{equation}\n\nThe Equations 11 and 12 describes the results from the Ray Casting algorithm that are further explained in the next subsection. The Equation 11 evaluates those waypoints inside obstacles, while Equation 12 finds the segments that go through some obstacle or no-fly zones.\nEquation 13  indicates the third term of the fitness function, which penalizes routes with lots of curves by summing up the angle between each segment of the route. \n\nEq. 13.\n\\begin{equation}\n    f_{curv} = \\dfrac{1}{e_{max}} \\cdot \\sum_{t=0}^{T} {gene_t^e} \n    \\label{eq:fit:curv}\n\\end{equation}\n\nStraighter routes can be simplified by transforming three or more collinear waypoints into two, that way, the information passed to the autopilot is reduced, decreasing the chance of future communication problems with the UAV. Due to that, smoother routes are rewarded. The fourth fitness term is given by Equation 14, and it takes into account the fuel consumption. \n\nEq. 14.\n\\begin{equation}\n    f_{cons} = \\sum_{t=0}^{T} {gene_t^a}^2 \n    \\label{eq:fit:cons}\n\\end{equation}\n\nTo simplify the introduction of fuel consumption on the fitness function, it is interpreted as the total route's sum of squared accelerations. Longer the route, more significant the fitness. This forces the algorithm to find the shortest route, saving fuel and completing the mission faster.\n\nWe are not assuming a fixed number of time steps $T$ for the trajectory. The proposed GA will optimize the number of time steps. This is done by including on the fitness function the $T$ parameter. Thus, the Equation 15 counts the number of time steps on the individual's encoding.  \n\nEq. 15.\n\\begin{equation}\n    f_{T} = \\overline{T} \n    \\label{eq:fit:T}\n\\end{equation}\n\nThe total values of the fitness function must be minimized, which means that the better individuals will have a reduced fitness value. However, if an emergency landing becomes necessary, Equation 9 is replaced by Equation 16.\n\nEq. 16.\n\\begin{equation}\n    f_{landing} = \n    \\begin{cases}\n        &\\sum_{n=0}^{N} RC_L(\\omega_{\\overline{T}}, \\Psi_n)\n    \\end{cases}\n    \\label{eq:fit:land}\n\\end{equation}\n\nEq. 17.\n\\begin{equation}\n    RC_L(\\omega, \\Psi) = \n    \\begin{cases}\n        1 & \\text{, if } \\omega \\in \\Psi\\\\\n        0 & \\text{, otherwise}\n    \\end{cases}\n    \\label{eq:fit:RC_L}\n\\end{equation}\n\nWhere $\\Psi$ represents a stay-in (landing) area and the last time step $\\overline{T}$ must be within some $\\Psi$.\n\n%Expansion to bonification and penalization areas, expanding the fitness function and redefining the problem to consider those areas as part of the minimization problem. \n\n### Operators\n\nThe initialization operator generates individuals following two steps. First, the number of time steps $\\overline{T}$ is randomly selected from $\\{1,\\ldots,T\\}$. Moreover, individuals with different number of time steps can be created. Second, the pair of values $gene_t=\\left(a_t,e_t\\right)$ for each gene is randomly taken with $a_t\\in[a_{min},a_{max}]$ and $e_t\\in[e_{min},e_{max}]$. \n\nThe selection operator for reproduction is the Tournament [21] with size two. Thus, it is randomly selected two individuals from the population, and the best one is chosen as the first parent. The second parent is selected following the same steps.\n\nThe new individual is generated by randomly choosing between OX and BLX-$\\alpha$ crossover operators for the two parents.\nThese operators are applied as follows:\n\n- OX: The offspring genes are randomly selected between $parent_1$'s or $parent_2$'s gene;\n- BLX-$\\alpha$: It is taken the medium for each of $parent_1$'s and $parent_2$'s gene's elements and modified by a small value.\n\n[\\\\]: \"\\begin{itemize}\n    \\item \\textbf{OX}: The offspring genes are randomly selected between $parent_1$'s or $parent_2$'s gene;\n    \\item \\textbf{BLX-$\\alpha$}: It is taken the medium for each of $parent_1$'s and $parent_2$'s gene's elements and modified by a small value.\n\\end{itemize}\"\n\nThe mutation operator is performed over each of the new genes with a probability $Pr(\\text{mutation})$ of mutating or not the gene. There were defined four operators that perform mutation. Each operator is randomly selected with equal chance.\n\n- Creep: It is added or subtracted a small random value from each gene's element;\n- Change: Each gene has a probability of 50\\% of being replaced by a random generated new gene;\n- Insert: It is inserted a single randomly generated gene anywhere on the DNA, if after muting $T \\leq T_{max}$;\n- Remove: A random gene is removed from the DNA, if after muting $T \\geq T_{min}$.\n    \n[\\\\]: \"\\begin{itemize}\n    \\item \\textbf{Creep}: It is added or subtracted a small random value from each gene's element;\n    \\item \\textbf{Change}: Each gene has a probability of 50\\% of being replaced by a random generated new gene;\n    \\item \\textbf{Insert}: It is inserted a single randomly generated gene anywhere on the DNA, if after muting $T \\leq T_{max}$;\n    \\item \\textbf{Remove}: A random gene is removed from the DNA, if after muting $T \\geq T_{min}$.\n\\end{itemize}\"\n\n### Ray Casting\n\nThe Ray Casting algorithm is applied during the fitness calculation to identify obstacles in Equation 10 or landing areas in Equation 16. As previously mentioned, this algorithm is widely used in computer graphics field, especially for rendering 3D scenes for games and animation movies. \n\nRC simulates the path a light ray makes when inserted on an environment, by calculating the trajectory of the ray from the light source until it reaches an object. Further developments on the Ray Casting simulated the reflex of objects and the projection of new rays. Given a 2D polygon and a point, a ray is cast from the point to the infinite. If this ray crosses an even number of the polygon's edge, the point is outside the polygon, if it crossed an odd number, then it is inside the polygon.\n\nFor the path planning problem, the Ray Casting algorithm is employed here to avoid collision with a no-fly area. This is done by casting horizontal rays from each waypoint of the route. Next, it is calculated how many times the ray cast intercepted the polygon formed by the area. If the ray intercepted the area an odd number, the waypoint is inside the area, if it intercepted an even number, then the waypoint is outside of the area.\n\nThe Ray Casting algorithm implemented in this work consists of a two-fold algorithm. The first one, the *Point in Polygon* RC is used to check if a given polygon contains a point. This algorithm is employed by Equation 11 and it uses the logic of casting a horizontal ray in the direction of the positive axis (i.e. to the right on Cartesian) and counts the number of areas edges intersections, establishing if it is inside or not the area. The *Point in Polygon* RC is used to check for every waypoint of the route the relational position colliding with any obstacle.\n\nThe second RC is the *Segment intersects Segment*. This algorithm is important because the notion of waypoints is only an abstraction for the UAV's controller to trace a motion vector that drives the airship along some path. Due to that, it is not only necessary to check if the waypoints are colliding with obstacles but to check if any part of the UAV's route is colliding.\n\nIt works by checking the orientation of each segment of the route with each edge of the no-fly areas. For a pair of following waypoints belonging to the route, a ray is cast between them, i.e. a connection. It is then checked with the area's edges. If the orientation of the points indicates both segments intersect between themselves, the route is then penalized. Otherwise, the route does not receive a penalty when the segments are not intersecting. This is described by Equation 12.\n\nEquation 17 is also related to the *Point in Polygon* RC. The goal of this equation is to check if the route's last waypoint, the landing point, arrived at a safe zone  or not, allowing the UAV to safely land. To verify if the point is contained inside the polygon formed by the safe zone, the Ray Casting algorithm is applied as described for the *Point in Polygon* RC.\n\nAs the Ray Casting algorithm is not widely used for path planning and geophysical methods, a previous evaluation of the proposed algorithms was necessary. It was made a stress test over the algorithms, executing many cases and inspecting the results. First, the evaluation of checking if a given waypoint is inside a polygon used the algorithm *Point in Polygon*. The process selected a thousand points $\\omega$ and assigned to them uniformly distributed values for its $x$ and $y$ coordinates, where the Equation 18 describes the process of selecting the coordinates.\n\n\\begin{equation}\n    \\omega_i = \\{x,y\\},~~ x \\in U[1,6] ~~\\text{and}~~  y \\in U[1,6] ~~~~ \\forall i \\in [1,1000]\n    \\label{eq:res:pip}\n\\end{equation}\n\nThe generated points were inferred to see if they were inside a defined no-fly area. Figure 4 shows the results of the algorithm, where each cross represents a waypoint, and the square on the centre is the non-navigable area. The label \"T\" stands for *True* along with the colour green, i.e. the point is **inside** the polygon. The label \"F\" stands for *False* along with the colour purple, indicating that the point is **outside** the area. The result shows that for every point tested the classification is right.\n\n\nFigure 3: Stress test for the Point in Polygon Ray Casting Algorithm.\n\n[\\\\]: \"\\begin{figure}[!htb]\n    \\centering\n    \\includegraphics[width=0.7\\columnwidth]{images/rc_pip}\\\\\n    \\caption{Stress test for the \\emph{Point in Polygon} Ray Casting Algorithm.}\n    \\label{fig:rc_pip}\n\\end{figure}\"\n\n\n```python\n%%time\n# Code to run the stress test for the Point in Polygon Ray Casting Algorithm\n\nfrom src.naboo.model import CartesianPoint\nfrom src.naboo.utils import point_in_polygon\nfrom src.naboo.visualization import plot_map\n\n# Defines the quantity of points\nqty_points = 1000\n\n# Define the vertex of the obstacle\nverts1 = [\n    (2.5, 2.5), # left, bottom\n    (2.5, 4.5), # left, top\n    (4.5, 4.5), # right, top\n    (4.5, 2.5), # right, bottom\n]\nverts1.append(verts1[0])\nverts1 = [CartesianPoint(v[0], v[1]) for v in verts1]\n\ntexts = []\nwps = []\nfor i in range(qty_points):\n    x = random.uniform(1,6)\n    y = random.uniform(1,6)\n    \n    wp = CartesianPoint(x,y)\n    wps.append(wp)\n    texts.append(str(point_in_polygon(wp, verts1))[0])\n    \nplot_map(\n    areas=[verts1], \n    labels=['n'], \n    texts=texts,\n    points=wps,\n    wp_style='x',\n    title='Ray Casting Algorithm - Point in Polygon Stress Test, wp={}'.format(qty_points),\n    stress=True\n)\n```\n\n    CPU times: user 3 s, sys: 693 ms, total: 3.7 s\n    Wall time: 2.6 s\n\n\n\nThe second algorithm needed for the obstacle collision detection considers the intersections between the area's edges and the segment connecting two waypoints, it is called the *Segment Intersects Segment* Ray Casting algorithm. The stress test for this algorithm  followed the same steps as the *Point in Polygon*, although this time the process of selecting the coordinates is expressed on Equation 19.\n\n\\begin{equation}\n    \\begin{aligned}\n        \\overline{\\omega_a\\omega_b}_i &:= \\text{line segment connecting}~\\omega_a~\\text{with}~\\omega_b,~\\forall i \\in [1,15]\\\\\n        \\omega &= \\{x,y\\},~~ x,y \\in U[1,6]\n        \\label{eq:res:sis}\n        \\end{aligned}\n\\end{equation}\n\nThe results are displayed by Figure 5, showing the algorithm performs as expected. The green lines represent the classification as *True*, i.e. the segment $\\overline{\\omega_a\\omega_b}_i$ intersects at least one edge of the polygon. The purple lines represent the *False* label. An interesting note about this execution is that the segment F4 (F stands for *False* and the number is an identifier) is **inside** the polygon and does not cross any edges. It occurs as expected since the algorithm is built to detect intersections only. There is no problem this segment not being penalized by this algorithm because, when running the **Point in Polygon** RC, the algorithm will find the two waypoints inside the area, penalizing them.\n\n\nFigure 4: Stress test for the Segment intersects Segment Ray Casting Algorithm\n\n[\\\\]: \"\\begin{figure}[!htb]\n    \\centering\n    \\includegraphics[width=0.7\\columnwidth]{images/rc_sis}\\\\\n\\caption{Stress test for the \\emph{Segment intersects Segment} Ray Casting Algorithm}\n    \\label{fig:rc_sis}\n\\end{figure}\"\n\n\n\n```python\n%%time\n# Code to run the stress test for the Segment intersects Segment Ray Casting Algorithm\n\nfrom src.naboo.model import CartesianPoint\nfrom src.naboo.utils import segment_in_polygon\nfrom src.naboo.visualization import plot_map\n\n# Define the quantity of segments\nqty_segments = 15\n\n# Define the vertex of the obstacle\nverts1 = [\n    (2.5, 2.5), # left, bottom\n    (2.5, 4.5), # left, top\n    (4.5, 4.5), # right, top\n    (4.5, 2.5), # right, bottom\n]\nverts1.append(verts1[0])\nverts1 = [CartesianPoint(v[0], v[1]) for v in verts1]\n\ntexts = []\nsegments = []\nfor i in range(qty_segments):\n    x = random.uniform(1,6)\n    y = random.uniform(1,6)\n    wp1 = CartesianPoint(x,y)\n\n    x = random.uniform(1,6)\n    y = random.uniform(1,6)\n    wp2 = CartesianPoint(x,y)\n\n    segment = [wp1, wp2]\n    segments.append(segment)\n    texts.append(str(segment_in_polygon(wp1, wp2, verts1))[0])\n    \nplot_map(\n    areas=[verts1], \n    labels=['n'], \n    texts=texts,\n    segments=segments,\n    wp_style='-x',\n    title='RC Algorithm - Segment intersects Segment Stress Test, segments={}'.format(qty_segments),\n    stress=True\n)\n```\n\n## Results\n\n### Genetic Algorithm for Mission\n\nThe proposed path planning is expected to be resilient to a variety of environments, aiming to perform well in real-world scenarios. The testing of such resilience is made by simulating 50 different random generated maps proposed by [16]. Each map contained 20 quadrilateral no-fly areas, randomly assembled. Intersection of those areas were allowed. For all maps, the origin and destination waypoints were the same, being the points $(0,0)$ and $(-10,0)$, respectively. \n\nThe algorithms were tested simulating the real environment, which is embedded on a UAV. The tests were executed on a Raspberry PI model B running Linux Ubuntu operating system, with 1.2GHz Quad-Core processor and 1GB of RAM, this device is well suited to fit a UAV. All algorithms and systems for those tests were written in Python. The use of a Raspberry PI is taken into consideration in this work due to its capability of being well suited for an embedded environment and to its computational power capable of running a vast suite of softwares for controlling the UAV and the proposed algorithms.\n\nThe fitness function contains a set of parameters that influences the algorithm's performance. Three different sets of parameters were tested to verify the performance of the algorithms over the maps. The parameters for the tests execution are presented on Table I.\n\n\n\nThe stop criterion is the time limit of  180 sec to find the best trajectory for each map. To evaluate the solutions obtained,  two labels were created. The label \"Feasible\" represents routes that arrive to the destination within less than 2 meters of radius from destination point, and they do not hit any obstacles. Otherwise, the label \"Infeasible\" is applied. This one can be subdivided in two categories: one that represents routes that hit an obstacle (infeasibility by obstacle) and one where the last waypoint is too far from the destination (infeasibility by distance).\n\n\n\nTable II shows the percentage of maps that its best individual completed the task successfully. *Mode C* parameters provided the best results, with 92\\% of best individuals being feasible and possible to be applied to the real-world.\n\nIt is relevant to highlight that neither configuration modes got routes infeasible by obstacle, which means that none best solution hit any obstacle. Further analysis of the results provided by the best parameter set mode (C) were made. Figure 6 shows, for each time step of one second, the cumulative summation of feasible individuals generated.\n\n\nFig. 6. Cumulative summation of feasible individuals for Mode C, showing the average, min and max values over execution time. The blue line represents the average value for each time step, the upper bound of the region represents the maximum values encountered, and the lower represents the minimum values.\n\n Those values are obtained by averaging individuals spawning along the 50 maps. It can be seen that feasible routes appear early in the execution, indicating the applicability in real-time planning.\n\nAn interesting point to notice is that when the execution took much time, i.e., the algorithm iterated over many generations, the last waypoint of the route $\\omega_T$ did not hit exactly the destination point $\\omega_d$. The $\\omega_T$ stays the furthest it can, respecting the delimited precision restriction and minimizing the fuel consumption. That happens due to the penalization on longer routes, as getting closer to $\\omega_d$ would increase the route's length, this solution would have a worse fitness than the solution in which the route is shorter. Hence, the algorithm bonuses shorter routes that consume less fuel and yet arrives at the correct destination inside the imposed threshold. This fact leads us to notice the algorithm's optimization ability and the importance of defining the value of each constraint correctly when planning the trajectory.\n\n\n### Emergency Landing\n\nThe second evaluation is about the emergency landing. When conducting a route, UAVs are subjected to uncertainties that some times can lead to emergencies, requiring to land as soon as possible in a safe area.\nUsing the same 50 previously mentioned maps, a total from one to four safe areas replaced the no-fly zones. \n\nThe best parameters from the last test were used to run the algorithm over all the maps, in a time frame of 180 sec as well. The penalty applied over Equation 16 is -10000, which means a reward for the fitness function.\n\n\nThe results reported that 84\\% of solutions were feasible, being able to land in one of the safe zones. The other 16\\% solutions did not find a feasible path, but none of the solutions were infeasible by obstacle. This means that the aircraft landed far from the safe region. Figure 7 shows the minimum, maximum and average time to find the first feasible solution when solving the 50 maps.\n\n\nFig. 7. Minimum, average and maximum time spent to find a feasible solution.\n\n\nFigure 8 illustrate a solution where the UAV is submitted to an emergency and replan its route to land on a safe zone, avoiding the obstacles.\n\n\n\nFig. 8. Solution on an emergency landing. Grey squares represent the no-fly areas, blue squares the bonus zone for safety landing, route's waypoints are the x marker along the purple line and the origin and destination waypoints on $(0,0)$ and $(-10,0)$ respectively.\n\n\n\n```python\n# Import everything necessary\n\nimport re\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pylab as pl\nimport matplotlib.pyplot as plt\nimport pickle\nimport itertools\n\nfrom pathlib import Path as PPath\nfrom multiprocessing import Pool\n\nfrom src.naboo.model import CartesianPoint, Mapa\nfrom src.naboo.visualization import plot_map, vis_mapa\n\nfrom src.naboo.genetic import Genetic, Subject\n\nfrom reports.helper import read_bonus, separate_areas, sgl_read_areas, read_sgl, run_ags_over_path, get_specific, plot_fitness, get_parameter, make_globals\n```\n\n\n```python\n# Define Paths\n\nMAPS_PATH = nb_dir + \"/data/maps/SGL/NonRegular/\"\nEXPERIMENTS_PATH = nb_dir + \"/experiments/\"\nBONUS_PATH = nb_dir + \"/data/maps/b_n/bonus_regions.txt\"\n```\n\n\n```python\n# Set Origin and Destination waypoints and labels, respectively\n\nwp_ori = CartesianPoint(0, 0)\nwp_des = CartesianPoint(0, -10)\n\nlabels = read_bonus(BONUS_PATH)\n\n```\n\n______________\n\n\n```python\n# Purposely added this cell to prevent a long execution for the next cells\nbreak\n```\n\n\n```python\n# The next three cells will run the same experiment for the 50 maps, \n# changing the parameters to the one mentioned on line 2 of each cell. \n# That will be modes EMA, EMC and EMF reported on Table II\n\n# !!! The next cells will take a lot of RAM memory, since it paralilezes the execution over multiple cores\n# !!! We previously added the results to this repository, so feel free to jump to the next section to only\n# !!! see the execution, or, if you like, try the single map running.\n```\n\n\n```python\ndef run_multiple():\n    pathlist = PPath(MAPS_PATH).glob(\"**/*.sgl\")\n\n    # Iterate over different maps in parallel\n    par_RC = get_parameter(MODE)\n    make_globals(labels, wp_ori, wp_des, par_RC, EXPERIMENTS_PATH, MODE, EXEC)\n    p = Pool(processes=50)\n    p.map(run_ags_over_path, pathlist)\n```\n\n\n```python\nMODE = \"EMA\"\nEXEC = \"1\"\n\nrun_multiple()\n```\n\n\n```python\nMODE = \"EMC\"\nEXEC = \"1\"\n\nrun_multiple()\n```\n\n\n```python\nMODE = \"EMF\"\nEXEC = \"1\"\n\nrun_multiple()\n```\n\n____\n\n\n```python\n# This generates the figure from the same problem as Figure 8\n# It takes 3 minutes to run.\n\n\n# Use this cell to run a single file and show the output result\n\nMODE = \"EMC\"\nEXEC = \"1\"\n\nmapa_name = \"27\"\n\npar_RC = get_parameter(MODE)\nmake_globals(labels, wp_ori, wp_des, par_RC, EXPERIMENTS_PATH, MODE, EXEC)\nag = run_ags_over_path(MAPS_PATH + mapa_name + \".sgl\", show=True)\n```\n\n-----\n\n\n```python\nfrom reports.helper import check_feasibility\nimport ast\n```\n\n\n```python\n\npathlist = PPath(EXPERIMENTS_PATH).glob(\"**/mode_EMC*_exec_1_*.csv\")\ndfs = []\nmap_numbers = []\nfor i, path in enumerate(pathlist):\n    #print(path)\n    m = re.search(r'(_map_\\d*_)',str(path))\n    if m:\n        found = m.group(1)\n    number = re.sub(r\"[A-Za-z/\\-_\\.]\", \"\", found) \n    map_numbers.append(number)\n    \n    df = pd.read_csv(path)\n    df = df[df['birth_time']<=180] #trim\n    df['label'] = df['fitness_trace'].apply(lambda x: check_feasibility(x))\n    \n    df_feasible = pd.DataFrame(df[df['label']=='feasible'])\n    df_feasible['label_count_cumulative'] = 1\n    df_feasible['label_count_cumulative'] = df_feasible['label_count_cumulative'].cumsum()\n    \n    dfs.append(df_feasible)\n    \n    #if i == 5:\n     #   break\n\nlegends = [f'Map {i}' for i in map_numbers]\n\ndic={}\nfor df, legend in zip(dfs, legends):\n    grouped = df.groupby(df['birth_time'].apply(lambda x: round(x, 2))).count()\n    dic[f\"{legend}\"] = grouped['label_count_cumulative'].cumsum()\n\n    \n    \ndic = pd.DataFrame(dic)\ndic = dic.fillna(method='ffill')\n\n\n\ndic['Average'] = dic.mean(axis=1)\ndic['Min'] = dic.min(axis=1)\ndic['Max'] = dic.max(axis=1)\n\nax = dic.plot(y='Average', c='white', use_index=True)\ndic['birth_time'] = dic.index\nplt.fill_between(x='birth_time', y1='Min', y2='Max', data=dic)\nplt.title(f'Feasible Individuals Over Time')\nplt.xlabel('Birth Time')\nplt.ylabel('Quantity of Feasible Individuals')\nplt.legend([])\n\n```\n\n\n```python\ndf['label'].value_counts(normalize=True) * 100\n```\n\n## Conclusion\n\nA hybrid genetic algorithm for path planning problem with obstacle avoidance was introduced in this paper. The novelty is the combination of genetic algorithm with Ray Casting algorithm to avoid obstacles and to find safe regions for an emergency landing. The path planning and replanning system, based on the proposed hybrid method, was executed with a Raspberry PI that can be embedded on the UAV. The method returned trajectories without hit any obstacles for all simulations done. For path planning, more than 90\\% of the trajectories reach the destination within the desired threshold, while a total of 84\\% trajectories landed the aircraft in safety regions. A reasonable amount of feasible solutions is found for both scenarios in less than 40 sec. The method is not compared against related approaches such as those proposed by [9], [11], [16] since these works solve linear models with exact approaches that do not run under Raspberry PI. As a future work, we will compare our approach against other planners for non-convex scenarios, based on methods such as A* or RRT. Also, we will evolve our hybrid GA to deal with 3D environments.\n\n## Acknowledgment\n\nResearch developed using computational resources of Centro de Ci\u00eancias Matem\u00e1ticas Aplicadas \u00e0 Ind\u00fastria (CeMEAI) supported by Funda\u00e7\u00e3o de Amparo \u00e0 Pesquisa do Estado de S\u00e3o Paulo (FAPESP) - CEPID-CeMEAI (FAPESP 2013/07375-0).\n\n# References\n\n[1] O. of the Secretary of Defense, \u201cUnmanned aircraft systems roadmap\n2005-2030,\u201d 2005.\n\n[2] K. Lu, J. Xie, Y. Wan, and S. Fu, \u201cToward uav-based airborne computing,\u201d IEEE Wireless Communications, 2019.\n\n[3] A. N. de Aviac\u00b8ao Civil, \u02dc Regras da ANAC para uso de drones entram em vigor, https://www.anac.gov.br/noticias/2017/regras-da-anacpara-uso-de-drones-entram-em-vigor/release drones v2.pdf, 2017.\n\n[4] H. Chen, X.-m. Wang, and Y. Li, \u201cA survey of autonomous control for\nuav,\u201d in 2009 International Conference on Artificial Intelligence and\nComputational Intelligence, vol. 2. IEEE, 2009, pp. 267\u2013271.\n\n[5] J. da Silva Arantes, \u201cRoute planning for uavs with risk of critical failure:\nA security-based approach,\u201d Master\u2019s thesis, University of Sao Paulo,\n2016.\n\n[6] S. Balachandran, A. Narkawicz, C. Munoz, and M. Consiglio, \u201cA \u02dc\npath planning algorithm to enable well-clear low altitude uas operation beyond visual line of sight,\u201d in Twelfth USA/Europe Air Traffic\nManagement Research and Development Seminar (ATM2017), 2017.\n\n[7] M. da Silva Arantes, \u201cHybrid qualitative state plan problem e o planejamento de missao com vants,\u201d Doctorade, Universidade de S \u02dc ao Paulo, \u02dc\nSao Carlos, 2017. \u02dc\n\n[8] H. X. Li, \u201cKongming: A generative planner for hybrid systems with\ntemporally extended goals,\u201d Master\u2019s thesis, Massachusetts Institute of\nTechnology, 2010.\n\n[9] L. Blackmore, M. Ono, and B. C. Williams, \u201cChance-constrained\noptimal path plan- ning with obstacles,\u201d IEEE Press, 2011.\n\n[10] K. ARIU, C. FANG, M. ARANTES, C. TOLEDO, and B. WILLIAMS,\n\u201cChance-constrained path planning with continuous time safety guarantees. 2017.\u201d\n\n[11] M. da Silva Arantes, C. F. M. Toledo, B. C. Williams, and M. Ono,\n\u201cCollision-free encoding for chance-constrained nonconvex path planning,\u201d IEEE Transactions on Robotics, vol. 35, no. 2, pp. 433\u2013448,\n2019.\n\n[12] Y. V. Pehlivanoglu, \u201cA new vibrational genetic algorithm\nenhanced with a voronoi diagram for path planning\nof autonomous uav,\u201d Aerospace Science and Technology,\nvol. 16, no. 1, pp. 47 \u2013 55, 2012. [Online]. Available:\nhttp://www.sciencedirect.com/science/article/pii/S1270963811000356\n\n[13] A. Tuncer and M. Yildirim, \u201cDynamic path planning of mobile\nrobots with improved genetic algorithm,\u201d Comput. Electr. Eng.,\nvol. 38, no. 6, pp. 1564\u20131572, Nov. 2012. [Online]. Available:\nhttp://dx.doi.org/10.1016/j.compeleceng.2012.06.016\n\n[14] I. Chaari, A. Koub \u02c6 aa, S. Trigui, H. Bennaceur, A. Ammar, and K. Al- \u02c6\nShalfan, \u201cSmartpath: An efficient hybrid aco-ga algorithm for solving the\nglobal path planning problem of mobile robots,\u201d International Journal\nof Advanced Robotic Systems, 2014.\n\n[15] X. Zhang and H. Duan, \u201cAn improved constrained differential evolution\nalgorithm for unmanned aerial vehicle global route planning.\u201d Appl. Soft\nComput, pp. 270\u2013284, 2015.\n\n[16] M. d. S. Arantes, J. d. S. Arantes, C. F. M. Toledo, and B. C.\nWilliams, \u201cA hybrid multi-population genetic algorithm for uav path\nplanning,\u201d in Proceedings of the Genetic and Evolutionary Computation\nConference 2016, ser. GECCO \u201916. New York, NY, USA: Association\nfor Computing Machinery, 2016, p. 853\u2013860. [Online]. Available:\nhttps://doi.org/10.1145/2908812.2908919\n\n[17] J. d. Silva Arantes, M. d. Silva Arantes, C. F. Motta Toledo, O. T. Junior, \u00b4\nand B. C. Williams, \u201cHeuristic and genetic algorithm approaches for uav\npath planning under critical situation,\u201d International Journal on Artificial\nIntelligence Tools, vol. 26, no. 01, p. 1760008, 2017.\n\n[18] S. D. Roth, \u201cRay casting for modeling solids,\u201d Computer graphics and\nimage processing, vol. 18, no. 2, pp. 109\u2013144, 1982.\n\n[19] J. Kruger and R. Westermann, \u201cAcceleration techniques for gpu-based\nvolume rendering,\u201d in Proceedings of the 14th IEEE Visualization 2003\n(VIS\u201903). IEEE Computer Society, 2003, p. 38.\n\n[20] J. A. Tarbutton, T. R. Kurfess, and T. M. Tucker, \u201cGraphics based path\nplanning for multi-axis machine tools,\u201d Computer-Aided Design and\nApplications, vol. 7, no. 6, pp. 835\u2013845, 2010.\n\n[21] B. L. Miller, D. E. Goldberg et al., \u201cGenetic algorithms, tournament\nselection, and the effects of noise,\u201d Complex systems, vol. 9, no. 3, pp.\n193\u2013212, 1995.\n", "meta": {"hexsha": "91bc604a80c6411f349060373101ab1b27a2c28d", "size": 116747, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "reports/Paper - Genetic Algorithm Applied in UAV's Path Planning.ipynb", "max_stars_repo_name": "gustavo-moura/path-planning", "max_stars_repo_head_hexsha": "06eb761257bee1ded81242464022abae1c751dd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-09-27T13:47:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T08:26:14.000Z", "max_issues_repo_path": "reports/Paper - Genetic Algorithm Applied in UAV's Path Planning.ipynb", "max_issues_repo_name": "gustavo-moura/path-planning", "max_issues_repo_head_hexsha": "06eb761257bee1ded81242464022abae1c751dd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reports/Paper - Genetic Algorithm Applied in UAV's Path Planning.ipynb", "max_forks_repo_name": "gustavo-moura/path-planning", "max_forks_repo_head_hexsha": "06eb761257bee1ded81242464022abae1c751dd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-22T15:21:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T08:27:16.000Z", "avg_line_length": 85.4663250366, "max_line_length": 51636, "alphanum_fraction": 0.7839002287, "converted": true, "num_tokens": 12294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505449918074, "lm_q2_score": 0.06560484476669959, "lm_q1q2_score": 0.020603237253084928}}
{"text": "```python\n%matplotlib inline\nfrom pyvista import set_plot_theme\nset_plot_theme('document')\n```\n\n\n# Temperature database usage\n\nIn the following, I present ways to interact with a database of borehole temperatures in the study area, using the module `db_access`.\nThese temperature data are used in other workpackages, e.g. for model calibration or MC-rejection.\n\n\n# Borehole Database\n\nIt is no surprise that the core of a data-driven project is data. Data which is organized in a specific manner, so that users can easily access,\nanalyse, and manipulate data. Many different schemes exist, in which data can be organized, with a most common one being spreadsheet-like tables.\nThus, spreadsheet software like Microsoft Excel or Libre-Office Calc are among popular solutions, when it comes to working with data.\n\nWith growing amount of data, however, these software solutions may soon meet their limits, as they can get overly complicated. One example would be many :code:`.xls` files,\nwhich are connected among each other using hyperlinks. This is obviously an error-prone solution, not really practical. Thus, greater amounts of data with a more complex structure,\nare usually maintained in a `database <https://en.wikipedia.org/wiki/Database>`_, following a certain `data model <https://en.wikipedia.org/wiki/Data_model>`_.\nHere, we use `SQLITE <https://www.sqlite.org/index.html>`_ [1] as underlying database solution, a SQL database engine.\n\nIn the following, we will briefly describe the database structure, its content and provide some short examples how to access the database and work with the stored data.\n\n## Data model\n\nWithin the database, we follow, as we use SQL, a `relational model <https://en.wikipedia.org/wiki/Relational_model>`_ to organize stored data.\nThis data comprises mainly borehole temperature measurements in the study area. The data was originally compiled by Sch\u00e4rli and Kohl [2] in a set of excel tables. \nThis *original* data, i.e. in its excel form, is available as supplementary material to the NAGRA Working report\n`NAB 12-61 <https://www.nagra.ch/de/cat/publikationen/arbeitsberichte-nabs/nabs-2012/downloadcenter.htm>`_. \nThis report comprises temperature measurements for boreholes all over Switzerland. Additionally, a stratigraphical description is available for some boreholes. \n\n\nMany of the temperature data from these deep boreholes is compiled in Sch\u00e4rli and Kohl [2], in addition to temperature data from *shallow* boreholes, i.e. shallower than 500 m.\nIn this work, we use a subset of this data which is (**a**) inside our area of interest, and (**b**) publicly available data. \nFor instance, the map further down shows a subset of deep boreholes (triangles) in the study area, colored by the data restriction. \nWhile blue represents open data, boreholes colored in red contain confidential data. Within the database, this information is stored, so confidential data can easily be erased from the database, \nin case it is made public.\n\n\nCurrently, the database contains three related tables:\n* general borehole information (coordinates, name, original source, ...)  \n* temperature depth information for all boreholes  \n* available petrophysical information  \n\nNot much petrophysical data is available from the boreholes. Temperature depth information, however, comprises more than 39000 data points. \nIn the following, we present methods and procedures to access these data and work with it from within this notebook. For this, we use a mixture of SQL queries and methods of the data analysis library \n`pandas <https://pandas.pydata.org/>`_. \n\n## Acessing data and visualizing\nQuerying a database is maybe the most often performed task, when it comes to databases. When you type something in a seach bar, for example, you query a database for the words you are looking for. \nThe same, though in a more rudimentary form, can be done with the compiled \"borehole temperature\" database. \n\nThe following code cells in this notebook show how:\n- to connect to the database  \n- introduces a very small library :code:`db_access`\n- get information about available tables in the database\n- formulate queries to get desired data, e.g. temperature depth pairs for a specific borehole\n- store query results in a pandas dataframe and visualize them  \n\n\n\n\n\n```python\nimport sys\nimport platform\nsys.path.append('../..')\nimport OpenWF.db_access as db_access\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.cm import get_cmap\nfrom scipy.stats import gaussian_kde\nfrom sklearn.linear_model import LinearRegression\n```\n\nrelative path to the .db file, which is the actual database\n\n\n\n\n```python\nos_name = platform.system()\nif os_name=='Linux':\n    db_path = '../../../../ETHeatflow/dbase_model_btemps.db'\nelif os_name=='Windows':\n    db_path = '../../../../db_borehole_temps/dbase_model_btemps.db'\n```\n\nconnect to the database and get information about stored tables with the ``connect`` routine\n\n\n\n\n```python\nconn, c = db_access.connect(db_path)\n```\n\nAt this point, we successfully connected to the database. One next step would be to see, what different tables are stored in the database. :code:`db_access` provides you with methods to do so. \nOf course, one can directly use an SQL query to do so. For user convenience, such queries are wrapped in some python methods of :code:`db_access`. \nFor instance, let's check the names of tables in the database:\n\n\n\n\n```python\nc.execute(\"SELECT name FROM sqlite_master WHERE type='table';\")\nprint(c.fetchall())\n\ndb_access.get_tables(c)\n```\n\nEssentially, these two commands do the same thing. In the :code:`db_access` method, the :code:`c.execute` and :code:`c.fetchall` commands are bundled in one method, :code:`.get_tables()`. \nThe result are the three tables:  \n- borehole_information_temperatures  \n- temperature_data (with one backup table, marked with extension \\_bak)  \n- sample_information_petrophysics  \n\nIn its current state, `db_access` comprises very basic query methods. More specific data-queries still need to be done via the `c.execute` and `c.fetchall` chain which is extremely versatile.  \nFor instance, consider out of the over 30000 data entries, we want to get all temperature measurements for Borehole Nr. 111. \n\n\n\n\n```python\nc.execute(\"SELECT * FROM {tn} WHERE {idf}=111;\".format(tn='temperature_data', idf='Nr'))\nprint(c.fetchall())\n```\n\nTo get the name of this borehole, we can relate to the table *borehole_information_temperatures* and query the name for the borehole with Nr. 111 in the exact same way:\n\n\n\n\n```python\nc.execute(\"SELECT {param} FROM {tn} WHERE {idf}=111;\".format(param='Namenach',\n                                                             tn='borehole_information_temperatures', idf='Nr'))\nprint(c.fetchall())\n```\n\n\n```python\n# To know which columns are available to choose from as `{param}` in the `execute` command, we can either list names fetched by an `execute` command:\n\n\nnam = c.execute(\"select * from borehole_information_temperatures\")\nnames = list(map(lambda x: x[0], nam.description))\nprint(names)\n```\n\n... or use a `db_access` method which returns this list of table headers:\n\n\n\n\n```python\ndb_access.get_columns(c,table='borehole_information_temperatures')\n```\n\nNow back to the query above, where we asked the database to provide all data for borehole *Riehen-1*, i.e. borehole Nr. 111. The query returns a list of table rows fitting the query command. \nWhile usable, it is difficult to read, at least for humans. This is, where pandas comes into play. As an extensive data analysis library, `pandas <https://pandas.pydata.org/>`_ provides a lot of tools \nto deal with a database and present them in `dataframes <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_, which can be displayed in a way more organized way. \nBelow, we submit a query for the temperature data for borehole Nr. 111 and display it.\nquery database for Borehole Nr. 111 and store it in the dataframe df.\n\n\n\n\n```python\ndf = pd.read_sql_query(\"select * from temperature_data where Nr = 111;\", conn)\ndf.head()\n```\n\nNext to readability, another advantage of querying via pandas, and storing the result in a dataframe, is visualization. Pandas features some plotting functions, which can quickly plot parameters in a \ndataframe. For example, let's plot `Depth` versus `Temperature`:\n\n\n\n\n```python\ndf.plot.scatter(x='Temperature', y='Depth_asl', s=50)\nplt.show()\n\n# alternative syntax in classical matplotlib\nfig, ax = plt.subplots()\nax.scatter(df['Temperature'], -df['Depth'], s=50)\nax.set_ylabel('Depth [m]')\nax.set_xlabel('Temperature [\u00b0C]')\nplt.show()\n```\n\nColleagues at `Georesources Switzerland Group <https://georessourcen.ethz.ch/en/#georesources-switzerland>`_ evaluated temperature data from deep boreholes following certain criteria. \nAccording to their analysis, a subset of the deep boreholes contain enough data for a reliable heat-flow estimation. Boreholes passing this quality assessment are marked with white **+** \nin the following map. \n\n\n\nIt should be noted, that data in these boreholes are all temperature logs with a high enough data density to reliably assess a temperature gradient.\nUntil now, SQL queries consisted mainly of ``select * ...`` where the ``*`` represents ``*all*``, i.e. selecting everything (similar to an ``ls *`` listing every content of a folder in bash). \nIf now we want to know, for instance, all different Borehole numbers, which are the database ID for each borehole, we can use ``select distinct ...``.\n\n\n\n\n```python\nall_borehole_numbers = pd.read_sql_query(\"select distinct Nr from temperature_data;\", conn)\nall_borehole_numbers.head()\n```\n\nOut of this distinct list, only a few passed the QA step by the GS-Group. The ID-Numbers of these boreholes are compiled in the list below:\nHere is a list of boreholes which passed the QA step\n\n\n\n\n```python\nborehole_numbers = [9, 10, 12, 21, 77, 78, 108, 111, 112, 113, 116, 122, 128, 139]\n```\n\n## Chaining queries\nWhen one searches for multiple keywords in, for instance, a google search, this narrows the number of potential results. Similarly this can be done when querying the database. \nAs an example, let's query all data from the boreholes, which pass the QA-workflow by the GS-Group, and plot temperatures versus depth:\nFor instance, we want to get all the boreholes marked as _valid_ in one dataframe:\n\n\n\n\n```python\nvalids = pd.read_sql_query(\"select * from temperature_data where \"+\n                        \" OR \".join([\"Nr = {}\".format(n) for n in borehole_numbers]), conn)\nboreholes = pd.read_sql_query(\"select * from borehole_information_temperatures where \"+\n                              \" OR \".join([\" Nr = {}\".format(n) for n in borehole_numbers]), conn)\n\nfig = plt.figure(figsize=[10,8])\nplt.scatter(valids['Temperature'], valids['Depth_asl'], s=50, c=valids['Nr'], cmap='tab10', alpha=.5)\nplt.xlabel('Temperature [\u00b0C]')\nplt.ylabel('Depth [m asl]')\nplt.show()\n```\n\nIn this plot, where temperature measurements are colored by borehole number, we see that the temperature measurements from different boreholes overall follow a similar gradient. \nThere are, however, singular points next to the dense cluster of continuous temperature logs. These are data points from different measuring procedures, such as **B** ottom **H** ole **T** emperatures (BHTs).  \nIf one would like to include *only* temperature logs in a database query, this can easily be done by extending the above chained query command with an ``AND`` keyword, so that a query would read:  \n\n.. code-block:: SQL  \n\n   SELECT * FROM temperature_data WHERE Method = 'HRT' AND (Nr = ? OR Nr = ? OR ...);\n\n\nThis method essentially queries if a temperature measurement belongs to a borehole with the number specified in our ``borehole_numbers`` list, and if the measurement method is HRT.\n\n\n\n\n```python\nvalids = pd.read_sql_query(\"SELECT * FROM temperature_data WHERE Method = 'HRT' AND (\"+\n                        \" OR \".join([\"Nr = {}\".format(n) for n in borehole_numbers])+\")\", conn)\nboreholes = pd.read_sql_query(\"select * from borehole_information_temperatures where \"+\n                              \" OR \".join([\" Nr = {}\".format(n) for n in borehole_numbers]), conn)\n\n\nfig = plt.figure(figsize=[10,8])\nplt.scatter(valids['Temperature'], valids['Depth_asl'], s=50, c=valids['Nr'], cmap='tab10', alpha=.5)\nplt.xlabel('Temperature [\u00b0C]')\nplt.ylabel('Depth [m asl]')\nplt.show()\n```\n\nThis leaves all log measurements and sorts out BHT values, for instance. While `AND`, `OR` are the standard expressions for specifying different queries to be matched, \nthere are many more useful query statements. There are multiple resources to list available SQL commands and queries, e.g. \non `codeacademy <https://www.codecademy.com/learn/learn-sql/modules/learn-sql-queries/reference>`_ or on `bitdegree <https://www.bitdegree.org/learn/sql-commands-list>`_.  \nTo better distinguish the boreholes, let's add a legend to the plot.\n\n\n\n\n```python\nname = \"Paired\"\ncmap = get_cmap(name)\ncolors = cmap.colors  # type: list\n\nfig, ax = plt.subplots(figsize=[16,12])\nax.set_prop_cycle(color=colors)\nfor i in borehole_numbers:\n    info = pd.read_sql_query(\"select * from borehole_information_temperatures where Nr = {}\".format(i), conn)\n    df = pd.read_sql_query(\"select * from temperature_data where Nr = {} and Method = 'HRT';\".format(i), conn)\n    ax.plot(df['Temperature'], -df['Depth']+info['Z'][0], '^', label=info['Namenach'][0], alpha=.6)\nax.set_ylabel('depth [m]')\nax.set_title('temperature [\u00b0C]')\nax.legend(loc='upper right',bbox_to_anchor=(1.32, 1.01),ncol=1)\nax.xaxis.tick_top()\n```\n\n## A word on data distribution  \n\nUntil now, this notebook mainly dealt with the technical aspects of working with a database. It should provide the basic tools to perform actual analysis on the stored data. \nIn preparation for another notebook, we analyse the distribution of data, to answer for example the question: *How probable is a temperature of X \u00b0C at a certain depth of Y km, according to our data?*  \nThis may be done with another query, yielding all temperatures in a pre-defined depth bracket, for example. Another method for a quick estimate of data distribution is, to calculate \nthe `Kernel Density Estimate <https://mathisonian.github.io/kde/>`_) which, as the name says, is an estimate of a function underlying a certain distribution. Mathematically, it can be written as:  \n\n\\begin{align}f(x) = \\sum_i K \\bigg(\\frac{x-i}{bw}\\bigg)\\end{align}\n\nWhere $K$ is the *Kernel* or *Kernel function*, and $bw$ the *bandwidth*. The higher the bandwith, the smoother the resulting KDE, as it controls the distance, at which data points contribute to the \ncurrent KDE-value. That is, a smaller bandwidth yields a more erratic KDE, while a high bandwidth value yields a smooth, yet shallower KDE where more distant points are taken into account.  \n\nHere, we use the `scipy <https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html>`_ implementation of a gaussian KDE. This means, $K$ is a gaussian Kernel. \nThe bandwidth is estimated using a Scott estimate [3], which automatically estimates an appropriate bandwidth. \n\nIn the following lines, we set up a linear regression through all borehole data and visualize the data distribution by coloring the data by their KDE value:\n\n\n\n\n```python\nxreg = valids['Temperature'].values.reshape(-1,1)\nyreg = valids['Depth_asl'].values\nreg = LinearRegression().fit(xreg,yreg)\n\nr_sc = reg.score(xreg, yreg)\nprint('coefficient of determination:', r_sc)\n\nprint('intercept:', reg.intercept_)\n\nprint('slope:', reg.coef_)\n\n\nxy = np.vstack([valids['Temperature'], valids['Depth_asl']])\nz = gaussian_kde(xy)(xy)\nxreg = np.linspace(10,110,100)\nyreg = reg.coef_[0] * xreg + reg.intercept_\n\n# sphinx_gallery_thumbnail_number = 6\nfig, ax = plt.subplots(figsize=[16,10])\n\ncs = ax.scatter(valids['Temperature'], valids['Depth_asl'], c=z, s=70, alpha=.3, label='data')\nax.plot(xreg, yreg, 'k--', linewidth=3, label='regression')\nax.set_ylabel('depth [m a.s.l.]')\nax.set_title('temperature [\u00b0C]')\nax.xaxis.tick_top()\nax.text(88, 200, 'grad T = {:.3f} K/km'.format(np.abs(reg.coef_[0])), fontsize=18)\nax.legend()\nplt.show()\n```\n\nAs to be expected from averaging temperature-depth data from multiple boreholes, the resulting temperature gradient reflects a normal continental temperature gradient. \nThis indicates, that there is no regional-scale source which would act as a heat-source and would thus regionally increase temperature gradients, and by that the (conductive) heat flow. \nFurther, the majority of data can be found between 600 m and 1000 m depth between 50 \u00b0C and 60 \u00b0C. \nIt should be noted, that the kind of borehole has to be considered, when looking at data distribution. \nIf borehole heat exchangers (BHE) are incorporated in the database, the most data will be at shallower depths, as BHEs usually extend to depths of around 200 m.  \n\n## One last information about databases\nIn this notebook, we worked with an SQL-database. This includes the standard steps of:  \n* connecting to a database \n* querying data from the database \n* analyzing data, adding / manipulating data, ...\n* closing the database\nThe last thing is important, as unexpected closure of non-closed databases may potentially corrupt them. So, the last step in working with the database is close it, as done in the following cell:\n\n\n\n\n```python\nc.close()\nconn.close()\n```\n\n## References\n| [1] Hipp, D. R., Kennedy, D., & Mistachkin, J. (2010). Sqlite documentation.  \n| [2] Sch\u00e4rli, U., & Kohl, T. (2002). Archivierung und Kompilation geothermischer Daten der Schweiz und angrenzender Gebiete. Schweizerische Geophysikalische Kommission.  \n| [3] Scott, D. W. (1979). On optimal and data-based histograms. Biometrika, 66(3), 605-610.\n\n", "meta": {"hexsha": "b946f7e7d70762e918136c425a3ee7dcda71dc20", "size": 23629, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/source/Examples/WP01_borehole_database.ipynb", "max_stars_repo_name": "adamkosik/PSGeothermieAargau", "max_stars_repo_head_hexsha": "00274bf2bc3fe033476b9375085a80c6510713ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-13T09:55:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T12:39:08.000Z", "max_issues_repo_path": "docs/source/Examples/WP01_borehole_database.ipynb", "max_issues_repo_name": "adamkosik/PSGeothermieAargau", "max_issues_repo_head_hexsha": "00274bf2bc3fe033476b9375085a80c6510713ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/source/Examples/WP01_borehole_database.ipynb", "max_forks_repo_name": "adamkosik/PSGeothermieAargau", "max_forks_repo_head_hexsha": "00274bf2bc3fe033476b9375085a80c6510713ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-13T10:04:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T10:04:35.000Z", "avg_line_length": 67.7048710602, "max_line_length": 3993, "alphanum_fraction": 0.6605865674, "converted": true, "num_tokens": 4243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25982564942392716, "lm_q2_score": 0.07921033063001551, "lm_q1q2_score": 0.02058087559702777}}
{"text": "# Homework 2\n\nIn this homework, we are going to play with Twitter data.\n\nThe data is represented as rows of of [JSON](https://en.wikipedia.org/wiki/JSON#Example) strings.\nIt consists of [tweets](https://dev.twitter.com/overview/api/tweets), [messages](https://dev.twitter.com/streaming/overview/messages-types), and a small amount of broken data (cannot be parsed as JSON).\n\nFor this homework, we will only focus on tweets and ignore all other messages.\n\n\n## Tweets\n\nA tweet consists of many data fields. [Here is an example](https://gist.github.com/arapat/03d02c9b327e6ff3f6c3c5c602eeaf8b). You can learn all about them in the Twitter API doc. We are going to briefly introduce only the data fields that will be used in this homework.\n\n* `created_at`: Posted time of this tweet (time zone is included)\n* `id_str`: Tweet ID - we recommend using `id_str` over using `id` as Tweet IDs, becauase `id` is an integer and may bring some overflow problems.\n* `text`: Tweet content\n* `user`: A JSON object for information about the author of the tweet\n    * `id_str`: User ID\n    * `name`: User name (may contain spaces)\n    * `screen_name`: User screen name (no spaces)\n* `retweeted_status`: A JSON object for information about the retweeted tweet (i.e. this tweet is not original but retweeteed some other tweet)\n    * All data fields of a tweet except `retweeted_status`\n* `entities`: A JSON object for all entities in this tweet\n    * `hashtags`: An array for all the hashtags that are mentioned in this tweet\n    * `urls`: An array for all the URLs that are mentioned in this tweet\n\n\n## Data source\n\nAll tweets are collected using the [Twitter Streaming API](https://dev.twitter.com/streaming/overview).\n\n\n## Users partition\n\nBesides the original tweets, we will provide you with a Pickle file, which contains a partition over 452,743 Twitter users. It contains a Python dictionary `{user_id: partition_id}`. The users are partitioned into 7 groups.\n\n# Part 0: Load data to a RDD\n\nThe tweets data is stored on AWS S3. We have in total a little over 1 TB of tweets. We provide 10 MB of tweets for your local development. For the testing and grading on the homework server, we will use different data.\n\n## Testing on the homework server\nOn EdX, we provide four different input sizes to test your program: 10 MB, 1 GB and 10 GB and 100GB. For any run, we will only be using one of these four datasets.\n\nFor submission and for local testing, make sure to read the path of the file you want to operate with from `./hw2-files.txt`. Otherwise your program will receive no points.\n\n## Local test\n\nFor local testing, please create your own `hw2-files.txt` file, which contains a single file path on the local disk, e.g.\n`file://<absolute_path_to_current_directory>/hw2-files-10mb.txt`. For final submission, we will create this file on our server for testing with the appropriate file path. If your implementation is correct, you should not worry about which file system (i.e. local file system or HDFS) Spark will read data from.\n\nNow let's see how many lines there are in the input files.\n\n1. Make RDD from the data in the file given by the file path present in `hw2-files.txt`.\n2. Mark the RDD to be cached (so in next operation data will be loaded in memory) \n3. call the `print_count` method to print number of lines in all these files\n\n<b>It should print<b>\n```\nNumber of elements: 2150\n```\n\n\n```python\n\"\"\"\nThis is a useful cell for debugging. Use timer_start() and timer_stop() at different parts of your code \nfor checking the amount of time a segment takes.\n\"\"\"\nfrom time import time\ntimer = []\nprev_ts = None\ndef timer_start():\n    global prev_ts\n    prev_ts = time()\ndef timer_stop(title):\n    timer.append((title, time() - prev_ts))\n```\n\n\n```python\ndef print_count(rdd):\n    print('Number of elements:', rdd.count())\n```\n\n\n```python\ntimer_start()\n\nfrom pyspark import SparkContext\n\nsc = SparkContext()\n\ntimer_stop(\"set up sc\")\n```\n\n\n```python\ntimer_start()\nwith open('./hw2-files.txt') as f:\n    file_path =  f.read().strip()\n#files will always be a single element array\n\n\n#read in the file as RDD\ntext_file = sc.textFile(file_path)\n\n#parse RDD into lines and remove empty ones\ntext_lines = text_file.flatMap(lambda line: line.split(\"}{\")).filter(lambda x:x!='') \n\n#use the print_count() function to count and print the result\nprint_count(text_lines)\n\n\n\n\n#raise NotImplementedError()\ntimer_stop(\"read data\")\n```\n\n    Number of elements: 2150\n\n\n# Part 1: Parse JSON strings to JSON objects\n\nPython has built-in support for JSON.\n\n\n```python\nimport json\n\njson_example = '''\n{\n    \"id\": 1,\n    \"name\": \"A green door\",\n    \"price\": 12.50,\n    \"tags\": [\"home\", \"green\"]\n}\n'''\n\njson_obj = json.loads(json_example)\njson_obj\n```\n\n\n\n\n    {'id': 1, 'name': 'A green door', 'price': 12.5, 'tags': ['home', 'green']}\n\n\n\n## Broken tweets and irrelevant messages\n\nThe data of this assignment may contain broken tweets (invalid JSON strings). So make sure that your code is robust for such cases.\n\nYou can filter out such broken tweet by checking if:\n* the line is not in json format\n\nIn addition, some lines in the input file might not be tweets, but messages that the Twitter server sent to the developer (such as [limit notices](https://dev.twitter.com/streaming/overview/messages-types#limit_notices)). Your program should also ignore these messages.\n\nThese messages would not contain the `created_at` field and can be filtered out accordingly.\n* Check if json object of the broken tweet has a `created_at` field\n\n*Hint:* [Catch the ValueError](http://stackoverflow.com/questions/11294535/verify-if-a-string-is-json-in-python)\n\n**********************************************************************************\n\n**Tasks**\n\n(1) Parse raw JSON tweets to obtain valid JSON objects. \n\n(2) From all valid tweets, construct a pair RDD of `(user_id, text)`, where `user_id` is the `id_str` data field of the `user` dictionary (read [Tweets](#Tweets) section above), `text` is the `text` data field.\n\n\n```python\nimport json\n\n\n\ndef safe_parse(raw_json):\n    \"\"\"\n    Input is a String\n    Output is a JSON object if the tweet is valid and None if not valid\n    \"\"\"\n    #CODE HERE\n    try:\n        json_obj = json.loads(raw_json)\n    except ValueError:\n        return None\n    \n    if 'created_at' not in json_obj.keys():\n        return None\n    else:\n        return json_obj\n    \n    #raise NotImplementedError()\n    \n# construct an RDD of (user_id, text) for each tweets \n# input: text_lines(RDD) // output: RDD type(user_id, text)\n\nvalid_tweets = text_lines.map(lambda x:safe_parse(x)).filter(lambda x: x!=None).map(lambda x:(x[\"user\"][\"id_str\"],x['text']))\n#raise NotImplementedError()\n\n\n```\n\n## Number of unique users\n\nCount the number of different users in all valid tweets\n\n(hint: [the `distinct()` method](https://spark.apache.org/docs/latest/programming-guide.html#transformations) is an easy way to do this, but try to see if there is a faster way to do this).\n\n*******************************************************************************\n\n**It should print**\n```\nThe number of unique users is: 1748\n```\n\n\n```python\ndef print_users_count(count):\n    print('The number of unique users is:', count)\n```\n\n\n```python\ntimer_start()\n# Code here\nnumOfUsers = valid_tweets.map(lambda x:x[0]).distinct(numPartitions=4).count()  \nprint_users_count(numOfUsers)\n\n#raise NotImplementedError()\ntimer_stop(\"Count unique users\")\n```\n\n    The number of unique users is: 1748\n\n\n# Part 2: Number of posts from each user partition\n\nLoad the Pickle file `/twitter/users-partition.pickle`, you will get a dictionary which represents a partition over 452,743 Twitter users, `{user_id: partition_id}`. The users are partitioned into 7 groups. For example, if the dictionary is loaded into a variable named `partition`, the partition ID of the user `59458445` is `partition[\"59458445\"]`. These users are partitioned into 7 groups. The partition ID is an integer between 0-6.\n\nNote that the user partition we provide doesn't cover all users appear in the input data.\n\n## Load the pickle file\n\nFor local testing, you can load the pickle file from the local file system, namely\n\n```\nproc = subprocess.Popen([\"cat\", \"./users-partition.pickle\"],\n                        stdout=subprocess.PIPE)\npickle_content = proc.communicate()[0]\n```\nHowever, for submission, please keep following code block unchanged, since on the server the pickle file is located on the HDFS.\n\n\n```python\n# You can load pickle_content from a file on the local file system while testing on your laptop\n# To test on your laptop, set `ON_EMR=False`\n# To test on AWS for final submission, set `ON_EMR=True`\n\nON_EMR = True\n```\n\n\n```python\nimport subprocess\nimport pickle\n\nif ON_EMR:\n    proc = subprocess.Popen([\"hadoop\", \"fs\", \"-cat\", \"/twitter/users-partition.pickle\"],\n                            stdout=subprocess.PIPE)\n    pickle_content = proc.communicate()[0]\n    \nelse:\n    #!wget 'http://mas-dse-open.s3.amazonaws.com/Twitter/users-partition.pickle' -O './users-partition.pickle'\n    proc = subprocess.Popen([\"cat\", \"./users-partition.pickle\"],\n                        stdout=subprocess.PIPE)\n    pickle_content = proc.communicate()[0]\n\npartition = pickle.loads(pickle_content)\nlen(partition)\n```\n\n\n\n\n    452743\n\n\n\n## Tweets per user partition\n\n1. Count the number of posts from each user partition\n\n2. Count the number of posts from group 0, 1, ..., 6, plus the number of posts from users who are not in any partition. Assign users who are not in any partition to the group 7.\n\n3. Put the results of this step into a pair RDD `(group_id, count)` that is sorted by key.\n\n\n```python\nfrom pyspark.sql import SQLContext\ntimer_start()\n# CODE HERE\n# valid_tweets\n\n#create sql dataframe and load in the (user_id,partition id)\n#sqlCnt = SQLContext(sc)\n#partId = sc.parallelize(partition.items())\n#partIdFrame = sqlCnt.createDataFrame(partId,['user_id','partition_id'])\n\n\ndef update(userID):\n    if userID not in partition:\n        return (7,userID)\n\n    else:\n        return (partition[userID], userID)\n\n\ntweetsUserPart = valid_tweets.map(lambda x: update(x[0])).groupByKey().sortByKey()\ntweetsPart = tweetsUserPart.mapValues(lambda x:len(x))\n\n\n#raise NotImplementedError()\ntimer_start()\n```\n\n## Printing tweets per user partition\n\nPrint the post count using the `print_post_count` function we provided.\n\n**It should print**\n\n```\nGroup 0 posted 87 tweets\nGroup 1 posted 242 tweets\nGroup 2 posted 41 tweets\nGroup 3 posted 349 tweets\nGroup 4 posted 101 tweets\nGroup 5 posted 358 tweets\nGroup 6 posted 434 tweets\nGroup 7 posted 521 tweets\n```\n\n\n```python\ndef print_post_count(counts):\n    '''\n    `counts` is a list of tuples of group_id and count\n    '''\n    for group_id, count in counts:\n        print('Group %d posted %d tweets' % (group_id, count))\n```\n\n\n```python\nprint_post_count(tweetsPart.collect())\n#raise NotImplementedError()\n```\n\n    Group 0 posted 87 tweets\n    Group 1 posted 242 tweets\n    Group 2 posted 41 tweets\n    Group 3 posted 349 tweets\n    Group 4 posted 101 tweets\n    Group 5 posted 358 tweets\n    Group 6 posted 434 tweets\n    Group 7 posted 521 tweets\n\n\n# Part 3:  Relatively popularity of tokens\n\nIn this step, we are going to find tokens that are relatively popular in each user partition.\n\nWe define the number of mentions of a token $t$ in a specific user partition $k$ as the number of users from the user partition $k$ that ever mentioned the token $t$ in their tweets. Note that even if some users might mention a token $t$ multiple times or in multiple tweets, a user will contribute at most 1 to the counter of the token $t$.\n\nPlease make sure that the number of mentions of a token is equal to the number of users who mentioned this token but NOT the number of tweets that mentioned this token.\n\nLet $N_t^k$ be the number of mentions of the token $t$ in the user partition $k$. Let $N_t^{all} = \\sum_{i=0}^7 N_t^{i}$ be the number of total mentions of the token $t$.\n\nWe define the relative popularity of a token $t$ in a user partition $k$ as the log ratio between $N_t^k$ and $N_t^{all}$, i.e. \n\n\\begin{equation}\np_t^k = \\log \\frac{N_t^k}{N_t^{all}}.\n\\end{equation}\n\n\nYou can compute the relative popularity by calling the function `get_rel_popularity`.\n\nWe load a tweet tokenizer for you in the following cells. This Tokenizer object is called `tok`. Don't forget to execute the two cells below.\n\nYou can expand the following cell if needed to see the minutae of the Tokenizer.\n\n\n```python\n#!/usr/bin/env python\n\n\"\"\"\nThis code implements a basic, Twitter-aware tokenizer.\n\nA tokenizer is a function that splits a string of text into words. In\nPython terms, we map string and unicode objects into lists of unicode\nobjects.\n\nThere is not a single right way to do tokenizing. The best method\ndepends on the application.  This tokenizer is designed to be flexible\nand this easy to adapt to new domains and tasks.  The basic logic is\nthis:\n\n1. The tuple regex_strings defines a list of regular expression\n   strings.\n\n2. The regex_strings strings are put, in order, into a compiled\n   regular expression object called word_re.\n\n3. The tokenization is done by word_re.findall(s), where s is the\n   user-supplied string, inside the tokenize() method of the class\n   Tokenizer.\n\n4. When instantiating Tokenizer objects, there is a single option:\n   preserve_case.  By default, it is set to True. If it is set to\n   False, then the tokenizer will downcase everything except for\n   emoticons.\n\nThe __main__ method illustrates by tokenizing a few examples.\n\nI've also included a Tokenizer method tokenize_random_tweet(). If the\ntwitter library is installed (http://code.google.com/p/python-twitter/)\nand Twitter is cooperating, then it should tokenize a random\nEnglish-language tweet.\n\n\nJulaiti Alafate:\n  I modified the regex strings to extract URLs in tweets.\n\"\"\"\n\n__author__ = \"Christopher Potts\"\n__copyright__ = \"Copyright 2011, Christopher Potts\"\n__credits__ = []\n__license__ = \"Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License: http://creativecommons.org/licenses/by-nc-sa/3.0/\"\n__version__ = \"1.0\"\n__maintainer__ = \"Christopher Potts\"\n__email__ = \"See the author's website\"\n\n######################################################################\n\nimport re\nfrom html import entities \n\n######################################################################\n# The following strings are components in the regular expression\n# that is used for tokenizing. It's important that phone_number\n# appears first in the final regex (since it can contain whitespace).\n# It also could matter that tags comes after emoticons, due to the\n# possibility of having text like\n#\n#     <:| and some text >:)\n#\n# Most imporatantly, the final element should always be last, since it\n# does a last ditch whitespace-based tokenization of whatever is left.\n\n# This particular element is used in a couple ways, so we define it\n# with a name:\nemoticon_string = r\"\"\"\n    (?:\n      [<>]?\n      [:;=8]                     # eyes\n      [\\-o\\*\\']?                 # optional nose\n      [\\)\\]\\(\\[dDpP/\\:\\}\\{@\\|\\\\] # mouth      \n      |\n      [\\)\\]\\(\\[dDpP/\\:\\}\\{@\\|\\\\] # mouth\n      [\\-o\\*\\']?                 # optional nose\n      [:;=8]                     # eyes\n      [<>]?\n    )\"\"\"\n\n# The components of the tokenizer:\nregex_strings = (\n    # Phone numbers:\n    r\"\"\"\n    (?:\n      (?:            # (international)\n        \\+?[01]\n        [\\-\\s.]*\n      )?            \n      (?:            # (area code)\n        [\\(]?\n        \\d{3}\n        [\\-\\s.\\)]*\n      )?    \n      \\d{3}          # exchange\n      [\\-\\s.]*   \n      \\d{4}          # base\n    )\"\"\"\n    ,\n    # URLs:\n    r\"\"\"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+\"\"\"\n    ,\n    # Emoticons:\n    emoticon_string\n    ,    \n    # HTML tags:\n     r\"\"\"<[^>]+>\"\"\"\n    ,\n    # Twitter username:\n    r\"\"\"(?:@[\\w_]+)\"\"\"\n    ,\n    # Twitter hashtags:\n    r\"\"\"(?:\\#+[\\w_]+[\\w\\'_\\-]*[\\w_]+)\"\"\"\n    ,\n    # Remaining word types:\n    r\"\"\"\n    (?:[a-z][a-z'\\-_]+[a-z])       # Words with apostrophes or dashes.\n    |\n    (?:[+\\-]?\\d+[,/.:-]\\d+[+\\-]?)  # Numbers, including fractions, decimals.\n    |\n    (?:[\\w_]+)                     # Words without apostrophes or dashes.\n    |\n    (?:\\.(?:\\s*\\.){1,})            # Ellipsis dots. \n    |\n    (?:\\S)                         # Everything else that isn't whitespace.\n    \"\"\"\n    )\n\n######################################################################\n# This is the core tokenizing regex:\n    \nword_re = re.compile(r\"\"\"(%s)\"\"\" % \"|\".join(regex_strings), re.VERBOSE | re.I | re.UNICODE)\n\n# The emoticon string gets its own regex so that we can preserve case for them as needed:\nemoticon_re = re.compile(regex_strings[1], re.VERBOSE | re.I | re.UNICODE)\n\n# These are for regularizing HTML entities to Unicode:\nhtml_entity_digit_re = re.compile(r\"&#\\d+;\")\nhtml_entity_alpha_re = re.compile(r\"&\\w+;\")\namp = \"&amp;\"\n\n######################################################################\n\nclass Tokenizer:\n    def __init__(self, preserve_case=False):\n        self.preserve_case = preserve_case\n\n    def tokenize(self, s):\n        \"\"\"\n        Argument: s -- any string or unicode object\n        Value: a tokenize list of strings; conatenating this list returns the original string if preserve_case=False\n        \"\"\"        \n        # Try to ensure unicode:\n        try:\n            s = str(s)\n        except UnicodeDecodeError:\n            s = s.encode('string_escape')\n            s = str(s)\n        # Fix HTML character entitites:\n        s = self.__html2unicode(s)\n        # Tokenize:\n        words = word_re.findall(s)\n        # Possible alter the case, but avoid changing emoticons like :D into :d:\n        if not self.preserve_case:            \n            words = map((lambda x : x if emoticon_re.search(x) else x.lower()), words)\n        return words\n\n    def tokenize_random_tweet(self):\n        \"\"\"\n        If the twitter library is installed and a twitter connection\n        can be established, then tokenize a random tweet.\n        \"\"\"\n        try:\n            import twitter\n        except ImportError:\n            print(\"Apologies. The random tweet functionality requires the Python twitter library: http://code.google.com/p/python-twitter/\")\n        from random import shuffle\n        api = twitter.Api()\n        tweets = api.GetPublicTimeline()\n        if tweets:\n            for tweet in tweets:\n                if tweet.user.lang == 'en':            \n                    return self.tokenize(tweet.text)\n        else:\n            raise Exception(\"Apologies. I couldn't get Twitter to give me a public English-language tweet. Perhaps try again\")\n\n    def __html2unicode(self, s):\n        \"\"\"\n        Internal metod that seeks to replace all the HTML entities in\n        s with their corresponding unicode characters.\n        \"\"\"\n        # First the digits:\n        ents = set(html_entity_digit_re.findall(s))\n        if len(ents) > 0:\n            for ent in ents:\n                entnum = ent[2:-1]\n                try:\n                    entnum = int(entnum)\n                    s = s.replace(ent, unichr(entnum))\t\n                except:\n                    pass\n        # Now the alpha versions:\n        ents = set(html_entity_alpha_re.findall(s))\n        ents = filter((lambda x : x != amp), ents)\n        for ent in ents:\n            entname = ent[1:-1]\n            try:            \n                s = s.replace(ent, unichr(entities.name2codepoint[entname]))\n            except:\n                pass                    \n            s = s.replace(amp, \" and \")\n        return s\n\n```\n\n\n```python\nfrom math import log\n\ntok = Tokenizer(preserve_case=False)\n\ndef get_rel_popularity(c_k, c_all):\n    return log(1.0 * c_k / c_all) / log(2)\n\n\ndef print_tokens(tokens, gid = None):\n    group_name = \"overall\"\n    if gid is not None:\n        group_name = \"group %d\" % gid\n    print('=' * 5 + ' ' + group_name + ' ' + '=' * 5)\n    for t, n in tokens:\n        print(\"%s\\t%.4f\" % (t, n))\n    print\n```\n\n## Tokenize tweets\n\n1. Tokenize the tweets using the `tokenize` function that is a method of the `Tokenizer` class that we have instantiated as `tok`. \n\n1. Count the number of mentions for each tokens regardless of specific user group.\n\n1. Call `print_count` function to show how many different tokens we have.\n\n**It should print**\n```\nNumber of elements: 7677\n```\n\n\n```python\ndef mapToken(user, listOfToken):\n    return [(token, user) for token in listOfToken]\n\n# first find tokens for each text, then map the rdd into form of (single_token, user), groupby token, and filter out repeated users.\ntweetsToekn = valid_tweets.mapValues(lambda x: tok.tokenize(x)).flatMap(lambda x:(mapToken(x[0],x[1]))).groupByKey().mapValues(lambda x:set(list(x)))\n\n# The # of keys = # of tokens\nprint_count(tweetsToekn)\n```\n\n    Number of elements: 7677\n\n\n## Token popularity\n\nTokens that are mentioned by too few users are usually not very interesting. So we want to only keep tokens that are mentioned by at least 100 users. Filter out tokens that don't meet this requirement.\n\nCall `print_count` function to show how many different tokens we have after the filtering.\n\nCall `print_tokens` function to show top 20 most frequent tokens.\n\n**It should print**\n```\nNumber of elements: 46\n===== overall =====\n:\t1046.0000\nrt\t920.0000\n.\t767.0000\nthe\t587.0000\ntrump\t560.0000\n\u2026\t520.0000\nto\t501.0000\n,\t497.0000\nin\t385.0000\na\t383.0000\nis\t382.0000\nof\t300.0000\n!\t285.0000\nfor\t275.0000\nand\t263.0000\non\t218.0000\ni\t216.0000\nhe\t191.0000\nthat\t190.0000\n\"\t181.0000\n```\n\n\n```python\ntimer_start()\n\n\natLeast100 = tweetsToekn.mapValues(lambda x:len(x)).filter(lambda x:x[1]>99)\nprint_count(atLeast100)\n\ntop20 = atLeast100.map(lambda x:(x[1],x[0])).sortByKey(ascending=False).map(lambda x:(x[1],x[0])).take(20)                   \nprint_tokens(top20)\n\ntimer_stop(\"Count overall most popular tokens\")\n```\n\n    Number of elements: 46\n    ===== overall =====\n    :\t1046.0000\n    rt\t920.0000\n    .\t767.0000\n    the\t587.0000\n    trump\t560.0000\n    \u2026\t520.0000\n    to\t501.0000\n    ,\t497.0000\n    in\t385.0000\n    a\t383.0000\n    is\t382.0000\n    of\t300.0000\n    !\t285.0000\n    for\t275.0000\n    and\t263.0000\n    on\t218.0000\n    i\t216.0000\n    he\t191.0000\n    that\t190.0000\n    \"\t181.0000\n\n\n## Relative Popularity\n\nFor all tokens that are mentioned by at least 100 users, compute their relative popularity in each user group. Then print the top 10 tokens with highest relative popularity in each user group. In case two tokens have same relative popularity, break the tie by printing the alphabetically smaller one.\n\n**Hint:** Let the relative popularity of a token $t$ be $p$. The order of the items will be satisfied by sorting them using (-p, t) as the key.\n\n**It should print**\n```\n===== group 0 =====\nwith\t-3.6088\ncruz\t-3.6554\nhis\t-3.6582\namp\t-3.8651\non\t-3.9608\nto\t-4.0145\n&\t-4.0875\nhttps\t-4.1699\ni\t-4.1699\nwhat\t-4.1699\n===== group 1 =====\nsanders\t-2.2854\ngop\t-2.4060\nhillary\t-2.4330\n\u2019\t-2.4463\nbernie\t-2.4835\n\"\t-2.6925\nare\t-2.7249\nthis\t-2.7633\nfor\t-2.8179\nabout\t-2.8346\n===== group 2 =====\nwith\t-4.3458\ndonald\t-4.5146\n...\t-4.7004\ngop\t-4.7279\ni\t-4.9475\non\t-4.9608\nhe\t-4.9925\n\u2026\t-5.1155\nhttps\t-5.1699\nwhat\t-5.1699\n===== group 3 =====\nbernie\t-1.5945\nsanders\t-1.6609\nhillary\t-2.2188\nand\t-2.5154\n\"\t-2.5930\nin\t-2.6114\nwill\t-2.6160\nhttps\t-2.6674\n...\t-2.7004\nyou\t-2.7004\n===== group 4 =====\nwhat\t-3.4330\nhave\t-3.4725\nbernie\t-3.5380\nthis\t-3.5518\nit\t-3.6881\n?\t-3.6912\nfor\t-3.7110\nabout\t-3.7415\nhillary\t-3.7549\nthat\t-3.7625\n===== group 5 =====\nwhat\t-1.8007\nnot\t-1.8745\nhttps\t-2.0000\nhis\t-2.0144\ncruz\t-2.0704\nit\t-2.1031\non\t-2.1243\n&\t-2.1399\namp\t-2.1489\n;\t-2.1592\n===== group 6 =====\nwill\t-1.3847\nhave\t-1.4725\n!\t-1.5850\ncruz\t-1.6919\ntrump\t-1.7199\nhttps\t-1.7549\n-\t-1.7673\n;\t-1.7807\nbe\t-1.7952\namp\t-1.8144\n===== group 7 =====\ndonald\t-1.0740\ntrump\t-1.6535\nbernie\t-1.7790\nsanders\t-1.7829\n\u2019\t-1.8613\nof\t-1.9069\n?\t-1.9186\nwith\t-1.9307\nthe\t-1.9588\nbe\t-1.9758\n```\n\nFor all tokens that are mentioned by at least 100 users, compute their relative popularity in each user group. Then print the top 10 tokens with highest relative popularity in each user group. In case two tokens have same relative popularity, break the tie by printing the alphabetically smaller one.\n\nHint: Let the relative popularity of a token  tt  be  pp . The order of the items will be satisfied by sorting them using (-p, t) as the key.\n\n\n\n\n```python\ntimer_start()\n\n#return [(part_id,#users)]\ntokenCountAll = atLeast100.collectAsMap()\n\n# function for computing token's #of appearance in each partition group\ndef countPart(users):\n    counts = {}\n    for user in users:\n        if user not in partition:\n            counts[7]=counts.get(7,0)+1\n        else:\n            counts[partition[user]] = counts.get(partition[user],0)+1\n    # k=part_id , v = #apprearance \n    return [(k,v) for k, v in counts.items()]\n\n# function for formatting the rdd into (partition_id,(token, relative_popularity)) form for later work\ndef formatResult(token,partResult):\n    #partResult is of [(part_id,# appearance)...] form\n    return [(result[0],(token,get_rel_popularity(result[1], tokenCountAll[token]))) for result in partResult]\n\n\n    \npopularPartToken = tweetsToekn.filter(lambda x:len(x[1])>99).mapValues(lambda x:countPart(x)).flatMap(lambda x:formatResult(x[0],x[1])).groupByKey().sortByKey().mapValues(lambda x: sorted(x,key=lambda x:(-x[1],x[0]))).map(lambda x:(x[0],x[1][:10])).collect()\n\nfor group in popularPartToken:\n    print_tokens(group[1],group[0])\n\n\n\ntimer_stop(\"Print popular tokens in each group\")\n```\n\n    ===== group 0 =====\n    with\t-3.6088\n    cruz\t-3.6554\n    his\t-3.6582\n    amp\t-3.8651\n    on\t-3.9608\n    to\t-4.0145\n    &\t-4.0875\n    https\t-4.1699\n    i\t-4.1699\n    what\t-4.1699\n    ===== group 1 =====\n    sanders\t-2.2854\n    gop\t-2.4060\n    hillary\t-2.4330\n    \u2019\t-2.4463\n    bernie\t-2.4835\n    \"\t-2.6925\n    are\t-2.7249\n    this\t-2.7633\n    for\t-2.8179\n    about\t-2.8346\n    ===== group 2 =====\n    with\t-4.3458\n    donald\t-4.5146\n    ...\t-4.7004\n    gop\t-4.7279\n    i\t-4.9475\n    on\t-4.9608\n    he\t-4.9925\n    \u2026\t-5.1155\n    https\t-5.1699\n    what\t-5.1699\n    ===== group 3 =====\n    bernie\t-1.5945\n    sanders\t-1.6609\n    hillary\t-2.2188\n    and\t-2.5154\n    \"\t-2.5930\n    in\t-2.6114\n    will\t-2.6160\n    https\t-2.6674\n    ...\t-2.7004\n    you\t-2.7004\n    ===== group 4 =====\n    what\t-3.4330\n    have\t-3.4725\n    bernie\t-3.5380\n    this\t-3.5518\n    it\t-3.6881\n    ?\t-3.6912\n    for\t-3.7110\n    about\t-3.7415\n    hillary\t-3.7549\n    that\t-3.7625\n    ===== group 5 =====\n    what\t-1.8007\n    not\t-1.8745\n    https\t-2.0000\n    his\t-2.0144\n    cruz\t-2.0704\n    it\t-2.1031\n    on\t-2.1243\n    &\t-2.1399\n    amp\t-2.1489\n    ;\t-2.1592\n    ===== group 6 =====\n    will\t-1.3847\n    have\t-1.4725\n    !\t-1.5850\n    cruz\t-1.6919\n    trump\t-1.7199\n    https\t-1.7549\n    -\t-1.7673\n    ;\t-1.7807\n    be\t-1.7952\n    amp\t-1.8144\n    ===== group 7 =====\n    donald\t-1.0740\n    trump\t-1.6535\n    bernie\t-1.7790\n    sanders\t-1.7829\n    \u2019\t-1.8613\n    of\t-1.9069\n    ?\t-1.9186\n    with\t-1.9307\n    the\t-1.9588\n    be\t-1.9758\n\n\n## Optional Ungraded Exercise\nThe users partition is generated by a machine learning algorithm that tries to group the users by their political preferences. Three of the user groups are showing supports to Bernie Sanders, Ted Cruz, and Donald Trump. \n\nIf your program looks okay on the local test data, you can try it on the larger input by submitting your program to the homework server. Observe the output of your program to larger input files, can you guess the partition IDs of the three groups mentioned above based on your output?\n\n\n```python\n# Change the values (Replace -1s) of the following three items to your guesses\nusers_support = [\n    (3, \"Bernie Sanders\"),\n    (0, \"Ted Cruz\"),\n    (7, \"Donald Trump\")\n]\n\nfor gid, candidate in users_support:\n    print(\"Users from group %d are most likely to support %s.\" % (gid, candidate))\n```\n\n    Users from group 3 are most likely to support Bernie Sanders.\n    Users from group 0 are most likely to support Ted Cruz.\n    Users from group 7 are most likely to support Donald Trump.\n\n\nUncomment the lines in the cell below to print out the time taken between `time_start()` and `time_end()` at various stages of your pipeline. \n\n\n```python\n total_time = 0.0\n for item in timer:\n     print(\"{}\\t{}\".format(item[0], item[1]))\n     total_time += item[1]\n print(\"Total time: {}\".format(total_time))\n```\n\n    set up sc\t2.0265862941741943\n    read data\t1.4144368171691895\n    Count unique users\t0.561680793762207\n    Count overall most popular tokens\t0.5577907562255859\n    Print popular tokens in each group\t2.485125780105591\n    Total time: 7.045620441436768\n\n", "meta": {"hexsha": "f03b5352a7030c33f15ef6da7d77986dfc520fc6", "size": 49690, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "HW/HW2/HW-2_Twitter.ipynb", "max_stars_repo_name": "sookieliao/UCSD_18_Spring_Big-Data-Analytics-using-Spark-Implementation-", "max_stars_repo_head_hexsha": "b443332edaaea952cfbe1e1b16e17a7bac0c2aee", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW/HW2/HW-2_Twitter.ipynb", "max_issues_repo_name": "sookieliao/UCSD_18_Spring_Big-Data-Analytics-using-Spark-Implementation-", "max_issues_repo_head_hexsha": "b443332edaaea952cfbe1e1b16e17a7bac0c2aee", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW/HW2/HW-2_Twitter.ipynb", "max_forks_repo_name": "sookieliao/UCSD_18_Spring_Big-Data-Analytics-using-Spark-Implementation-", "max_forks_repo_head_hexsha": "b443332edaaea952cfbe1e1b16e17a7bac0c2aee", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6728395062, "max_line_length": 448, "alphanum_fraction": 0.5348158583, "converted": true, "num_tokens": 7988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15203222625389934, "lm_q2_score": 0.13477590525944355, "lm_q1q2_score": 0.020490280921977824}}
{"text": "```python\nfrom IPython.display import HTML\nHTML(\"\"\"\n<br><br>\n<a href=http://wwwgong.pythonanywhere.com/cuspea/default/list_talks target=new>\n<font size=+3 color=blue>CUSPEA Talks</font>\n</a>\n<br><br>\n<br> \n\"\"\")\n```\n\n\n\n\n\n<br><br>\n<a href=http://wwwgong.pythonanywhere.com/cuspea/default/list_talks target=new>\n<font size=+3 color=blue>CUSPEA Talks</font>\n</a>\n<br><br>\n<br> \n\n\n\n\n\n```python\n\n```\n\n# Fun with MyPETS\n\n## Table of Contents\n\n* [Motivation](#hid_why)\n* [Introduction](#hid_intro)\n* [Problem Statement](#hid_problem)\n* [Import packages](#hid_pkg)\n\n    \n* [History of Open Source Movement](#hid_open_src)\n* [How to learn STEM (or MyPETS)](#hid_stem)\n\n\n* [References](#hid_ref)\n* [Contributors](#hid_author)\n* [Appendix](#hid_apend)\n\n    \n\n\n\n\n## Motivation  <a class=\"anchor\" id=\"hid_why\"></a>\n\n* Current Choice\n\n\n\n* A New Option\n\n> The __Jupyter Notebook__ is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and explanatory text. Uses include: data cleaning and transformation, numerical simulation, statistical modeling, machine learning and much more.\n\nUseful for many tasks\n\n* Programming\n* Blogging\n* Learning\n* Research\n* Documenting work\n* Collaborating\n* Communicating\n* Publishing results\n\nor even\n\n* Doing homework as a student\n\n\n\n```python\nHTML(\"\")\n```\n\n\n\n\n\n\n\n\n## Introduction  <a class=\"anchor\" id=\"hid_intro\"></a>\n\n## Problem Statement <a class=\"anchor\" id=\"hid_problem\"></a>\n\n## Import packages  <a class=\"anchor\" id=\"hid_pkg\"></a>\n\n\n```python\n# math function\nimport math\n\n# create np array\nimport numpy as np\n\n# pandas for data analysis\nimport pandas as pd\n\n# plotting\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n# symbolic math\nimport sympy as sy\n\n# html5\nfrom IPython.display import HTML, SVG, YouTubeVideo\n\n# widgets\nfrom collections import OrderedDict\nfrom IPython.display import display, clear_output\nfrom ipywidgets import Dropdown\n\n# csv file\nimport csv\n```\n\n## History of Open Source Movement <a class=\"anchor\" id=\"hid_open_src\"></a>\n\n\n```python\nwith open('../dataset/open_src_move_v2_1.csv') as csvfile:\n    reader = csv.DictReader(csvfile)\n    table_str = '<table>'\n    table_row = \"\"\"\n    <tr><td>{year}</td> \n        <td></td> \n        <td><table>\n            <tr><td>{person}</td></tr>\n            <tr><td><a target=new href={subject_url}>{subject}</a></td></tr>\n            <tr><td>{history}</td></tr>\n            </table>\n        </td>  \n    </tr>\n    \"\"\"\n    for row in reader:\n        table_str = table_str + table_row.format(year=row['Year'], \\\n                subject=row['Subject'],\\\n                subject_url=row['SubjectURL'],\\\n                person=row['Person'],\\\n                picture=row['Picture'],\\\n                history=row['History'])\n    table_str = table_str + '</table>'\n    \nHTML(table_str)\n```\n\n\n\n\n<table>\n    <tr><td>1983</td> \n        <td></td> \n        <td><table>\n            <tr><td>Richard Stallman</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/GNU_Project>GNU Project : gcc, Emacs, gdb</a></td></tr>\n            <tr><td>Launch of the free software movement and founder of Free Software Foundation </td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>1984</td> \n        <td></td> \n        <td><table>\n            <tr><td>X.Org</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/X_Window_System>X Window Systerm</a></td></tr>\n            <tr><td>basic framework for a GUI environment</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>1985</td> \n        <td></td> \n        <td><table>\n            <tr><td>Richard Stallman</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/GNU_Manifesto>GNU Manifesto: GNU's Not Unix</a></td></tr>\n            <tr><td>disagreement between Stallman and Symbolics, Inc. over MIT's access to updates Symbolics had made to its Lisp machine, which was based on MIT code</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>1987</td> \n        <td></td> \n        <td><table>\n            <tr><td>Larry Wall</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/Perl>Perl programming lang</a></td></tr>\n            <tr><td>Common Gateway Interface (CGI )</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>1989</td> \n        <td></td> \n        <td><table>\n            <tr><td>Guido van Rossum</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/Python_(programming_language)>Python programming lang</a></td></tr>\n            <tr><td>creator of popular Python scripting lang</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>1990</td> \n        <td></td> \n        <td><table>\n            <tr><td>Tim Berners-Lee</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol>HyperText Transfer Protocol (HTTP)</a></td></tr>\n            <tr><td> creator of the World-Wide-Web at CERN</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>1991</td> \n        <td></td> \n        <td><table>\n            <tr><td>Linus Torvalds</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/Linux>Linux</a></td></tr>\n            <tr><td>creator of freely modifiable Linux kernel source code</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>1993</td> \n        <td></td> \n        <td><table>\n            <tr><td>Ian Murdock</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/Debian>Debian GNU/Linux</a></td></tr>\n            <tr><td>Debian Social Contract</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>1995</td> \n        <td></td> \n        <td><table>\n            <tr><td>Rob McCool</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/Apache_HTTP_Server>Apache HTTP Server</a></td></tr>\n            <tr><td>a web server that powers the digital world</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>1995</td> \n        <td></td> \n        <td><table>\n            <tr><td>David Axmark and Michael 'Monty' Widenius</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/MySQL>MySQL</a></td></tr>\n            <tr><td>popular RDMS acquired by Oracle</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>1996</td> \n        <td></td> \n        <td><table>\n            <tr><td>Jonathan Ian Schwartz</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/Java_Platform,_Standard_Edition>Java / JDK</a></td></tr>\n            <tr><td>general computing platform</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>1997</td> \n        <td></td> \n        <td><table>\n            <tr><td>Eric S. Raymond</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/The_Cathedral_and_the_Bazaar>The Cathedral and the Bazaar</a></td></tr>\n            <tr><td>open-source software advocate and author</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>1998</td> \n        <td></td> \n        <td><table>\n            <tr><td>Marc Lowell Andreessen</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/Netscape_Communicator>Mosaic</a></td></tr>\n            <tr><td>Netscape opened source codes of web browser</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>1999</td> \n        <td></td> \n        <td><table>\n            <tr><td>Brian_Behlendorf</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/Apache_Software_Foundation>Apache Software Foundation</a></td></tr>\n            <tr><td>Open source software incubator</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>1999</td> \n        <td></td> \n        <td><table>\n            <tr><td>Richard Baraniuk</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/OpenStax_CNX>OpenStax CNX</a></td></tr>\n            <tr><td>formerly called Connexions, is a global repository of educational content provided by volunteers</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>2000</td> \n        <td></td> \n        <td><table>\n            <tr><td>Sun Microsystems</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/StarOffice>StarOffice</a></td></tr>\n            <tr><td>office suite to counter evil empire Microsoft</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>2001</td> \n        <td></td> \n        <td><table>\n            <tr><td>Fernando Perez</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/Ipython>IPython Notebook</a></td></tr>\n            <tr><td>active documents that contain live code, equations, visualizations and explanatory text</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>2001</td> \n        <td></td> \n        <td><table>\n            <tr><td>Wikimedia Foundation</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/Wikipedia>Wikipedia</a></td></tr>\n            <tr><td>the free encyclopedia</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>2003</td> \n        <td></td> \n        <td><table>\n            <tr><td>Massimo Banzi</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/Arduino>Arduino</a></td></tr>\n            <tr><td>open-source electronics platform based on easy-to-use hardware and software</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>2005</td> \n        <td></td> \n        <td><table>\n            <tr><td>Linus Torvalds</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/Git>Git</a></td></tr>\n            <tr><td>version control system</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>2005</td> \n        <td></td> \n        <td><table>\n            <tr><td>Steve Chen</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/YouTube>YouTube</a></td></tr>\n            <tr><td>Video Hosting Service</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>2006</td> \n        <td></td> \n        <td><table>\n            <tr><td>Salman Khan</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/Khan_Academy>Khan Academy</a></td></tr>\n            <tr><td>learn anything - \nFor free. For everyone. Forever</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>2007</td> \n        <td></td> \n        <td><table>\n            <tr><td>Google</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/Android_(operating_system)>Android</a></td></tr>\n            <tr><td>mobile operating system</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>2008</td> \n        <td></td> \n        <td><table>\n            <tr><td>Satoshi Nakamoto</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/Blockchain>Blockchain / bitcoin</a></td></tr>\n            <tr><td>an open, distributed ledger that can record transactions between two parties efficiently and in a verifiable and permanent way.</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>2008</td> \n        <td></td> \n        <td><table>\n            <tr><td>Tom Preston-Werner</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/GitHub>GitHub</a></td></tr>\n            <tr><td>Open source project repository</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>2015</td> \n        <td></td> \n        <td><table>\n            <tr><td>Google</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/TensorFlow>Tensorflow</a></td></tr>\n            <tr><td>An open-source software library for Machine Intelligence</td></tr>\n            </table>\n        </td>  \n    </tr>\n\n    <tr><td>2017</td> \n        <td></td> \n        <td><table>\n            <tr><td>Elon Musk</td></tr>\n            <tr><td><a target=new href=https://en.wikipedia.org/wiki/OpenAI>Open AI</a></td></tr>\n            <tr><td>promote and develop friendly AI in such a way as to benefit, rather than harm, humanity as a whole</td></tr>\n            </table>\n        </td>  \n    </tr>\n    </table>\n\n\n\n## How to learn STEM <a class=\"anchor\" id=\"hid_stem\"></a> \n\n\n```python\nHTML(\"Wen calls it -<br><br><br> <font color=red size=+4>M</font><font color=purple>y</font><font color=blue size=+3>P</font><font color=blue size=+4>E</font><font color=green size=+4>T</font><font color=magenta size=+3>S</font><br>\")\n```\n\n\n\n\nWen calls it -<br><br><br> <font color=red size=+4>M</font><font color=purple>y</font><font color=blue size=+3>P</font><font color=blue size=+4>E</font><font color=green size=+4>T</font><font color=magenta size=+3>S</font><br>\n\n\n\n### Math <a class=\"anchor\" id=\"hid_math\"></a>\n\n* [Awesome Math](https://github.com/rossant/awesome-math)\n\n$$ e^{i \\pi} + 1 = 0 $$\n\nsee more [MathJax](https://www.mathjax.org/)  equations [here](https://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Typesetting%20Equations.html#Maxwell's-Equations)\n\n### Science <a class=\"anchor\" id=\"hid_science\"></a>\n\n#### Physics <a class=\"anchor\" id=\"hid_physics\"></a>\n\n*  [Computational Physics, 3rd Ed - Problem Solving with Python by Rubin Landau](http://physics.oregonstate.edu/~landaur/Books/CPbook/index.html)\n\n### Engineering <a class=\"anchor\" id=\"hid_engineer\"></a>\n\n* [How To Be A Programmer](https://github.com/braydie/HowToBeAProgrammer)\n\n### Technology <a class=\"anchor\" id=\"hid_tech\"></a>\n\n* [Deep Learning for Self-Driving Cars](http://selfdrivingcars.mit.edu/)  @MIT\n* [Deep Learning for Natural Language Processing](http://cs224d.stanford.edu/) @Stanford\n\n## References <a class=\"anchor\" id=\"hid_ref\"></a>\n\n### Websites\n\n* [DataCamp - Jupyter Notebook Tutorial](https://www.datacamp.com/community/tutorials/tutorial-jupyter-notebook#gs.ClmI4Jc)\n\n\n* http://docs.python.org\n\nIt goes without saying that Python\u00e2\u20ac\u2122s own online documentation is an excellent resource if you need to delve into the finer details of the language and modules. Just make sure you\u00e2\u20ac\u2122re looking at the documentation for Python 3 and not earlier versions.\n\n\n### Books\n\n### Other Resources\n\n* Idea\n    - [Google Search](http://www.google.com)\n* Text\n    - [Wikipedia](https://www.wikipedia.org/)\n* Image\n    - [Google Images](https://www.google.com/imghp)\n* Video\n    - [YouTube](https://www.youtube.com/)\n\n\n## Contributors <a class=\"anchor\" id=\"hid_author\"></a>\n\n* wen.gong@oracle.com (first created on 2017-03-09)\n\n## Appendix <a class=\"anchor\" id=\"hid_apend\"></a> \n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "2fd234159d242d063273ec17123ba26b90028c3d", "size": 81629, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "learn_stem/fun_with_mypets.ipynb", "max_stars_repo_name": "wgong/open_source_learning", "max_stars_repo_head_hexsha": "ccf819626bf17125abcee8edf66401e4a0d2dc20", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-11T13:27:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-11T13:27:29.000Z", "max_issues_repo_path": "learn_stem/fun_with_mypets.ipynb", "max_issues_repo_name": "wgong/open_source_learning", "max_issues_repo_head_hexsha": "ccf819626bf17125abcee8edf66401e4a0d2dc20", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-03-09T18:42:19.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-19T21:06:23.000Z", "max_forks_repo_path": "learn_stem/fun_with_mypets.ipynb", "max_forks_repo_name": "wgong/open_source_learning", "max_forks_repo_head_hexsha": "ccf819626bf17125abcee8edf66401e4a0d2dc20", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1949213162, "max_line_length": 311, "alphanum_fraction": 0.4977152728, "converted": true, "num_tokens": 4255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1311732373477186, "lm_q2_score": 0.15610490333452268, "lm_q1q2_score": 0.020476785536242013}}
{"text": "<a href=\"https://colab.research.google.com/github/ChrizZhuang/marginalized_graph_kernel_protein/blob/main/Docking_0613.ipynb\" target=\"_parent\"></a>\n\n## Set up the environment\n\n\n```\n!nvidia-smi\n```\n\n    Sun Jun 13 02:41:42 2021       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 465.27       Driver Version: 460.32.03    CUDA Version: 11.2     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   55C    P8    11W /  70W |      0MiB / 15109MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    |  No running processes found                                                 |\n    +-----------------------------------------------------------------------------+\n\n\n\n```\n#!pip install pymatgen==2020.12.31\n!pip install pymatgen==2019.11.11\n!pip install --pre graphdot\n!pip install gdown\n```\n\n    Requirement already satisfied: pymatgen==2019.11.11 in /usr/local/lib/python3.7/dist-packages (2019.11.11)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.1.5)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (3.2.2)\n    Requirement already satisfied: scipy>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.4.1)\n    Requirement already satisfied: pydispatcher>=2.0.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.0.5)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (0.8.9)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (0.17.9)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.16.1)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2021.6.10)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.5.1)\n    Requirement already satisfied: numpy>=1.14.3 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.19.5)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.23.0)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (3.3.0)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.7.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen==2019.11.11) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen==2019.11.11) (2.8.1)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (1.3.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (0.10.0)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen==2019.11.11) (0.2.2)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.2->pymatgen==2019.11.11) (4.4.2)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (1.24.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (2020.12.5)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (3.0.4)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->pymatgen==2019.11.11) (1.2.1)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas->pymatgen==2019.11.11) (1.15.0)\n    Requirement already satisfied: graphdot in /usr/local/lib/python3.7/dist-packages (0.8a17)\n    Requirement already satisfied: tqdm>=4.55 in /usr/local/lib/python3.7/dist-packages (from graphdot) (4.61.1)\n    Requirement already satisfied: numba>=0.51.0 in /usr/local/lib/python3.7/dist-packages (from graphdot) (0.51.2)\n    Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.19.5)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.7.1)\n    Requirement already satisfied: pandas>=0.24 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.1.5)\n    Requirement already satisfied: scipy>=1.3.0 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.4.1)\n    Requirement already satisfied: pymatgen==2019.11.11 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2019.11.11)\n    Requirement already satisfied: networkx>=2.4 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2.5.1)\n    Requirement already satisfied: pycuda>=2019 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2021.1)\n    Requirement already satisfied: mendeleev>=0.7 in /usr/local/lib/python3.7/dist-packages (from graphdot) (0.7.0)\n    Requirement already satisfied: treelib>=1.6.1 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.6.1)\n    Requirement already satisfied: kahypar>=1.1.4 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.1.6)\n    Requirement already satisfied: ase>=3.17 in /usr/local/lib/python3.7/dist-packages (from graphdot) (3.21.1)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from numba>=0.51.0->graphdot) (57.0.0)\n    Requirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba>=0.51.0->graphdot) (0.34.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->graphdot) (1.2.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->graphdot) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->graphdot) (2.8.1)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (3.2.2)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (1.16.1)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (0.8.9)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2021.6.10)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2.23.0)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (3.3.0)\n    Requirement already satisfied: pydispatcher>=2.0.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2.0.5)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (0.17.9)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.4->graphdot) (4.4.2)\n    Requirement already satisfied: appdirs>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (1.4.4)\n    Requirement already satisfied: pytools>=2011.2 in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (2021.2.7)\n    Requirement already satisfied: mako in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (1.1.4)\n    Requirement already satisfied: pyfiglet<0.9,>=0.8.post1 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (0.8.post1)\n    Requirement already satisfied: Pygments<3.0.0,>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (2.9.0)\n    Requirement already satisfied: colorama<0.5.0,>=0.4.4 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (0.4.4)\n    Requirement already satisfied: SQLAlchemy<2.0.0,>=1.3.23 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (1.4.15)\n    Requirement already satisfied: six<2.0.0,>=1.15.0 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (1.15.0)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from treelib>=1.6.1->graphdot) (0.16.0)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11->graphdot) (0.10.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11->graphdot) (2.4.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11->graphdot) (1.3.1)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (2020.12.5)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (2.10)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen==2019.11.11->graphdot) (0.2.2)\n    Requirement already satisfied: MarkupSafe>=0.9.2 in /usr/local/lib/python3.7/dist-packages (from mako->pycuda>=2019->graphdot) (2.0.1)\n    Requirement already satisfied: greenlet!=0.4.17; python_version >= \"3\" in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (1.1.0)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (4.0.1)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (3.4.1)\n    Requirement already satisfied: typing-extensions>=3.6.4; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (3.7.4.3)\n    Requirement already satisfied: gdown in /usr/local/lib/python3.7/dist-packages (3.6.4)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from gdown) (4.61.1)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from gdown) (2.23.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from gdown) (1.15.0)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (2020.12.5)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (3.0.4)\n\n\n\n```\n%matplotlib inline\nimport io\nimport sys\nsys.path.append('/usr/local/lib/python3.6/site-packages/')\nimport os\nimport urllib\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport graphdot\nfrom graphdot import Graph\nfrom graphdot.graph.adjacency import AtomicAdjacency\nfrom graphdot.graph.reorder import rcm\nfrom graphdot.kernel.marginalized import MarginalizedGraphKernel # https://graphdot.readthedocs.io/en/latest/apidoc/graphdot.kernel.marginalized.html\nfrom graphdot.kernel.marginalized.starting_probability import Uniform\nfrom graphdot.model.gaussian_process import (\n    GaussianProcessRegressor,\n    LowRankApproximateGPR\n)\nfrom graphdot.kernel.fix import Normalization\nimport graphdot.microkernel as uX\nimport ase.io\n\n# for getting all file names into a list under a directory \nfrom os import listdir\n# for getting file names that match certain pattern\nimport glob\nimport time\n```\n\n    /usr/local/lib/python3.7/dist-packages/graphdot/graph/__init__.py:24: UserWarning: Cannot import RDKit, `graph.from_rdkit()` will be unavailable.\n    \n      'Cannot import RDKit, `graph.from_rdkit()` will be unavailable.\\n'\n\n\n\n```\nfrom google.colab import drive\ndrive.mount('/content/gdrive', force_remount=True)\n```\n\n    Mounted at /content/gdrive\n\n\n\n```\n#cd gdrive/MyDrive/Google\\ Colab/Covid-Data\n%cd gdrive/MyDrive/Covid-Data/\n```\n\n    /content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data\n\n\n\n```\n!pwd\n```\n\n    /content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data\n\n\n\n```\n!mkdir /content/pkls\n```\n\n## load the data\n\n\n```\nfiles  = ['uncharged_NSP15_6W01_A_3_H.Orderable_zinc_db_enaHLL.2col.csv.1.xz']\ndataset = pd.read_pickle(files[0]) # length of each csv file is 100000\n```\n\n\n```\ntarget = 'energy'\nbatch_size = 1000\nbatch_num_train = 0.8*len(dataset)//batch_size # batch number of training\nnum_test = 0.2*len(dataset)\ntrain_data = dataset.iloc[:int(batch_num_train)*batch_size]\ntest_data = dataset.iloc[int(batch_num_train)*batch_size:len(dataset)]\n#print(len(train_data))\n#print(len(test_data))\n```\n\n\n```\ngpr = GaussianProcessRegressor(\n    # kernel is the covariance function of the gaussian process (GP)\n    kernel=Normalization( # kernel equals to normalization -> normalizes a kernel using the cosine of angle formula, k_normalized(x,y) = k(x,y)/sqrt(k(x,x)*k(y,y))\n        # graphdot.kernel.fix.Normalization(kernel), set kernel as marginalized graph kernel, which is used to calculate the similarity between 2 graphs\n        # implement the random walk-based graph similarity kernel as Kashima, H., Tsuda, K., & Inokuchi, A. (2003). Marginalized kernels between labeled graphs. ICML\n        MarginalizedGraphKernel( \n            # node_kernel - A kernelet that computes the similarity between individual nodes\n            # uX - graphdot.microkernel - microkernels are positive-semidefinite functions between individual nodes and edges of graphs\n            node_kernel=uX.Additive( # addition of kernal matrices: sum of k_a(X_a, Y_a) cross for a in features\n                # uX.Constant - a kernel that returns a constant value, always mutlipled with other microkernels as an adjustable weight\n                #   c, the first input arg. as 0.5, (0.01, 10) the lower and upper bounds of c that is allowed to vary during hyperpara. optimizartion\n                # uX.KroneckerDelta - a kronecker delta returns 1 when two features are equal and return h (the first input arg here, which is 0.5 in this case) otherwise\n                #   (0.1, 0.9) the lower and upper bounds that h is allowed to vary during hyperpara. optimization\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 2nd element of graphdot.graph.Graph.nodes\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 3rd element of graphdot.graph.Graph.nodes\n                # uX.SquareExponential - Equ. 26 in the paper\n                # input arg. length_sacle is a float32, set as 1 in this case, which correspond to approx. 1 of the kernal value. \n                # This is used to determins how quicklys should the kernel decay to zero.\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0), # the 4th element of graphdot.graph.Graph.nodes\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 5th element of graphdot.graph.Graph.nodes\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0), # the 6th element of graphdot.graph.Graph.nodes\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 7th element of graphdot.graph.Graph.nodes\n                # uX.Convolution - a convolutional microkernel which averages evaluations of a base microkernel between pairs pf elememts of two variable-length feature sequences\n                # uX.KroneckerDelta as the base kernel\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9))) # the 8th element of graphdot.graph.Graph.nodes\n            ).normalized,\n            # edge_kernel - A kernelet that computes the similarity between individual edge\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 3rd element of graphdot.graph.Graph.nodes\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 4th element of graphdot.graph.Graph.nodes\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 5th element of graphdot.graph.Graph.nodes\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 6th element of graphdot.graph.Graph.nodes\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)) # the 7th element of graphdot.graph.Graph.nodes\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'), # the strating probability of the random walk on each node\n            q=0.05 # the probability for the random walk to stop during each step\n        )\n    ),\n    alpha=1e-4, # value added to the diagonal of the kernel matrix during fitting\n    optimizer=True, # default optimizer of L-BFGS-B based on scipy.optimize.minimize\n    normalize_y=True, # normalize the y values so taht the means and variance is 0 and 1, repsectively. Will be reversed when predicions are returned\n    regularization='+', # alpha (1e-4 in this case) is added to the diagonals of the kernal matrix\n)\n```\n\n\n```\ndef find_repeat_batch():\n  lower_batch = 0\n  lower_repeat = 0\n  for f in listdir('/content/pkls'):\n    f = f.split('_')\n    f[3] = f[3].split('.')\n\n    if int(f[1]) > lower_batch:\n        lower_batch = f[1]\n    if int(f[3][0]) > lower_repeat:\n        lower_repeat = f[3][0]\n\n  return lower_batch, lower_repeat\n\n\ndef train_pipeline_batch(model, train_dataset, test_dataset, target, repeats, batch_num_train, batch_size, verbose = True, print_batch = True, print_repeat = True):\n\n  start_time = time.time()\n  lower_batch, lower_repeat = find_repeat_batch()\n  assert(lower_batch <= int(batch_num_train)-1)\n  assert(lower_repeat <= repeats)\n\n  for repeat in range(lower_repeat, repeats):\n    for batch in range(lower_batch int(batch_num_train)-1):\n      batch_dataset = dataset.iloc[batch*batch_size:(batch+1)*batch_size] # divide the training data into different batches\n      np.random.seed(0)\n      if batch == 0 and repeat == 0:\n        model.fit(batch_dataset.graphs, batch_dataset[target], repeat=1, verbose=verbose)\n        model.save(path=\"/content/pkls\", filename='batch_0_repeat_0.pkl', overwrite=True)\n      elif batch == 0 and repeat !=0:\n        filename_load = 'batch_0_repeat_'+str(repeat-1)+'.pkl'\n        filename_save = 'batch_0_repeat_'+str(repeat)+'.pkl'\n        model.load(path=\"/content/pkls\", filename=filename_load)\n        model.fit(batch_dataset.graphs, batch_dataset[target], repeat=1, verbose=verbose)\n        model.save(path=\"/content/pkls\", filename=filename_save, overwrite=True)\n      else:\n        filename_load = 'batch_'+str(batch-1)+'_repeat_'+str(repeat)+'.pkl'\n        filename_save = 'batch_'+str(batch)+'_repeat_'+str(repeat)+'.pkl'\n        model.load(path=\"/content/pkls\", filename=filename_load)\n        model.fit(batch_dataset.graphs, batch_dataset[target], repeat=1, verbose=verbose)\n        model.save(path=\"/content/pkls\", filename=filename_save, overwrite=True)\n      \n      if print_batch:\n        mu = gpr.predict(batch_dataset.graphs)\n        print('   Training set of repeat '+str(repeat)+' and batch '+str(batch))\n        print('   MAE '+str(repeat)+' and batch '+str(batch)+' '+str(np.mean(np.abs(batch_dataset[target] - mu))))\n        print('   RMSE '+str(repeat)+' and batch '+str(batch)+' '+str(np.std(batch_dataset[target] - mu)))\n\n    if print_repeat:\n      mu = gpr.predict(train_dataset.graphs)\n      print('Training set of repeat '+str(repeat))\n      print('MAE '+str(repeat)+' '+str(np.mean(np.abs(train_dataset[target] - mu))))\n      print('RMSE '+str(repeat)+' '+str(np.std(train_dataset[target] - mu)))\n\n      mu = gpr.predict(test_dataset.graphs)\n      print('Test set of repeat '+str(repeat))\n      print('MAE '+str(repeat)+' '+str(np.mean(np.abs(test_dataset[target] - mu))))\n      print('RMSE '+str(repeat)+' '+str(np.std(test_dataset[target] - mu)))\n    \n  \n  end_time = time.time()\n  print(\"the total time consumption is \" + str(end_time - start_time) + \".\")\n```\n\n\n```\ntrain_pipeline_batch(gpr, train_data, test_data, target, repeats=2, batch_num_train=batch_num_train, batch_size=batch_size, print_batch = True, print_repeat = True)\n```\n\n\n```\n!zip -r /content/pkls.zip /content/pkls\n```\n\n      adding: content/pkls/ (stored 0%)\n      adding: content/pkls/batch_34_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_27_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_3_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_24_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_16_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_19_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_14_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_18_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_29_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_33_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_17_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_13_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_12_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_32_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_23_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_21_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_2_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_6_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_9_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_31_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_7_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_28_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_20_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_0_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_5_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_30_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_25_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_10_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_1_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_8_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_22_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_26_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_4_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_11_repeat_0.pkl (deflated 35%)\n      adding: content/pkls/batch_15_repeat_0.pkl (deflated 35%)\n\n\n\n```\nfrom google.colab import files\nfiles.download(\"/content/pkls.zip\")\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n```\ngpr.kernel.hyperparameters\n```\n\n\n\n\n    starting_probability : Uniform\n    \tp : 1.0\n    stopping_probability : 0.00010000000000000009\n    node_kernel : Composite\n    \taromatic : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.02343420535068002\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.18860200789175988\n    \tatomic_number : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 5.400776905055444\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tcharge : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.0145590563621646\n    \t\trhs : SquareExponential\n    \t\t\tlength_scale : 1.0\n    \tchiral : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.05149063984443944\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.12853164901299938\n    \thcount : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 10.000000000000002\n    \t\trhs : SquareExponential\n    \t\t\tlength_scale : 0.07795674396128768\n    \thybridization : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.02783411902444354\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.17414808329497075\n    \tring_list : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 6.550981640628747\n    \t\trhs : Convolution\n    \t\t\tbase : KroneckerDelta\n    \t\t\t\th : 0.10000000000000002\n    edge_kernel : Composite\n    \taromatic : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 2.331300736214766\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tconjugated : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 3.166641607522053\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \torder : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.05549109210250382\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.25478481015091287\n    \tring_stereo : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.033323606027544916\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.8\n    \tstereo : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.1324351226762118\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.14521546104851712\n\n\n\n\n```\nmu = gpr.predict(train.graphs)\n```\n\n\n```\nplt.scatter(train[target], mu)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.2074369392067814\n    RMSE: 0.3195501910711287\n\n\n\n```\nmu_test = gpr.predict(test.graphs)\n```\n\n\n```\nplt.scatter(test[target], mu_test)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 1.2461703788060545\n    RMSE: 1.6040210737240486\n\n\nWork\u0001on the kernel. Find a kernel that trains and predicts well.\n\n\n```\ngpr2 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-2, #different from gpr in alpha where gpr's alpha is 1e-4\n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\n#gpr2.fit(train.graphs, train[target], repeat=3, verbose=True)\ngpr2.fit(train.graphs, train[target], repeat=1, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |   1.667e+05|   1.928e+05|  1.7773e+05|      -11034|  2.2742e+05|   1.3e+02|       1.7|\n    |  1.5585e+05|  2.2171e+05|  1.6671e+05|      -10857|  2.2218e+05|   1.3e+02|       1.7|\n    |  1.3711e+05|  2.4873e+05|  1.4756e+05|      -10447|  2.0803e+05|   1.2e+02|       1.8|\n    |  1.3286e+05|  2.3627e+05|   1.432e+05|      -10338|  2.0336e+05|   1.1e+02|       1.7|\n    |  1.2977e+05|  2.2744e+05|  1.4002e+05|      -10249|  1.9714e+05|   1.1e+02|       1.7|\n    |  1.3006e+05|  2.1429e+05|  1.4032e+05|      -10258|  2.0119e+05|     1e+02|       1.7|\n    |  1.2923e+05|  2.2103e+05|  1.3946e+05|      -10238|  1.9906e+05|   1.1e+02|       1.7|\n    |  1.2888e+05|  2.2097e+05|  1.3911e+05|      -10228|  1.9865e+05|   1.1e+02|       1.7|\n    |  1.2843e+05|  2.2338e+05|  1.3864e+05|      -10211|  1.9582e+05|   1.1e+02|       1.7|\n    |  1.2837e+05|  2.2244e+05|  1.3858e+05|      -10212|   1.969e+05|   1.1e+02|       1.7|\n    |  1.2836e+05|  2.2225e+05|  1.3857e+05|      -10212|  1.9696e+05|   1.1e+02|       1.7|\n    |  1.2831e+05|  2.2155e+05|  1.3852e+05|      -10211|  1.9715e+05|   1.1e+02|       1.7|\n    |  1.2826e+05|  2.2184e+05|  1.3847e+05|      -10209|  1.9704e+05|   1.1e+02|       1.7|\n    |  1.2821e+05|  2.2181e+05|  1.3841e+05|      -10207|  1.9671e+05|   1.1e+02|       1.7|\n    |  1.2819e+05|  2.2165e+05|   1.384e+05|      -10207|  1.9664e+05|   1.1e+02|       1.8|\n    |  1.2818e+05|  2.2125e+05|  1.3838e+05|      -10207|  1.9671e+05|   1.1e+02|       1.8|\n    |  1.2817e+05|  2.2114e+05|  1.3838e+05|      -10207|  1.9673e+05|   1.1e+02|       1.7|\n    |  1.2815e+05|  2.2077e+05|  1.3836e+05|      -10207|  1.9677e+05|   1.1e+02|       1.7|\n    |  1.2812e+05|   2.185e+05|  1.3833e+05|      -10209|  1.9695e+05|   1.1e+02|       1.7|\n    |  1.2809e+05|   2.178e+05|   1.383e+05|      -10209|    1.97e+05|   1.1e+02|       1.7|\n    |  1.2807e+05|  2.1764e+05|  1.3828e+05|      -10208|  1.9695e+05|   1.1e+02|       1.7|\n    |  1.2805e+05|  2.1597e+05|  1.3826e+05|      -10209|  1.9693e+05|   1.1e+02|       1.7|\n    |  1.2805e+05|   2.172e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1693e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.8|\n    |  1.2804e+05|  2.1674e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1691e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2805e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.8|\n    |  1.2805e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    Optimization result:\n          fun: 128045.20193517115\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 21.67035135,   5.42797631,   0.91584794,   6.62684845,\n           636.88297304,  10.22203408,   0.        ,   6.13155297,\n             0.80318432, -45.79780911,   0.        ,   9.32446636,\n             2.06137402,   7.94609186, 767.483899  ,  -8.19180354,\n            92.93654292,   7.92503084, 118.62629465,   3.36719643,\n            38.71995733,   7.96834618,   0.        , -11.08475724,\n             7.2860016 ])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 31\n          nit: 21\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.51710969, -1.98267626,  1.72521606, -2.30258509,\n           -4.60517019,  0.        , -4.60517019, -1.8070945 ,  2.30258509,\n           -2.88031384, -3.6019383 , -2.30258509,  1.91177723, -2.30258509,\n            0.28746812, -2.30258509,  0.54884256, -2.30258509, -0.5686784 ,\n           -2.30258509, -4.35637808, -0.22314355, -2.55717239, -2.21179129])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7f6bf00630d0>\n\n\n\n\n```\nmu = gpr2.predict(train.graphs)\nplt.scatter(train[target], mu)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.7238389142657052\n    RMSE: 0.9634943206325994\n\n\n\n```\nmu_test = gpr2.predict(test.graphs)\nplt.scatter(test[target], mu_test)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 0.9561539409612109\n    RMSE: 1.2284268143181998\n\n", "meta": {"hexsha": "887221063063983e93d43b7a87cf7024ebcb9b25", "size": 242752, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Docking_0613.ipynb", "max_stars_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_stars_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Docking_0613.ipynb", "max_issues_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_issues_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Docking_0613.ipynb", "max_forks_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_forks_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 93.6904670012, "max_line_length": 16574, "alphanum_fraction": 0.5848190746, "converted": true, "num_tokens": 11963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.04535257894141504, "lm_q1q2_score": 0.020381114930253484}}
{"text": "# Twitter Tweets\n\nIn this homework, we are going to play with Twitter data.\n\nThe data is represented as rows of of [JSON](https://en.wikipedia.org/wiki/JSON#Example) strings.\nIt consists of [tweets](https://dev.twitter.com/overview/api/tweets), [messages](https://dev.twitter.com/streaming/overview/messages-types), and a small amount of broken data (cannot be parsed as JSON).\n\nFor this homework, we will only focus on tweets and ignore all other messages.\n\n\n## Tweets\n\nA tweet consists of many data fields. [Here is an example](https://gist.github.com/arapat/03d02c9b327e6ff3f6c3c5c602eeaf8b). You can learn all about them in the Twitter API doc. We are going to briefly introduce only the data fields that will be used in this homework.\n\n* `created_at`: Posted time of this tweet (time zone is included)\n* `id_str`: Tweet ID - we recommend using `id_str` over using `id` as Tweet IDs, becauase `id` is an integer and may bring some overflow problems.\n* `text`: Tweet content\n* `user`: A JSON object for information about the author of the tweet\n    * `id_str`: User ID\n    * `name`: User name (may contain spaces)\n    * `screen_name`: User screen name (no spaces)\n* `retweeted_status`: A JSON object for information about the retweeted tweet (i.e. this tweet is not original but retweeteed some other tweet)\n    * All data fields of a tweet except `retweeted_status`\n* `entities`: A JSON object for all entities in this tweet\n    * `hashtags`: An array for all the hashtags that are mentioned in this tweet\n    * `urls`: An array for all the URLs that are mentioned in this tweet\n\n\n## Data source\n\nAll tweets are collected using the [Twitter Streaming API](https://dev.twitter.com/streaming/overview).\n\n\n## Users partition\n\nBesides the original tweets, we will provide you with a Pickle file, which contains a partition over 452,743 Twitter users. It contains a Python dictionary `{user_id: partition_id}`. The users are partitioned into 7 groups.\n\n# Part 0: Load data to a RDD\n\nThe tweets data is stored on AWS S3. We have in total a little over 1 TB of tweets. We provide 10 MB of tweets for your local development. For the testing and grading on the homework server, we will use different data.\n\n## Testing on the homework server\nIn the Playground, we provide input size of 4 GB. To test, read file list from `../../Data/hw6-files-4gb.txt`. More input files will be added soon. \n\nFor final submission, make sure to read files list from `../../Data/hw6-files-final.txt`. Otherwise your program will receive no points.\n\n## Local test\n\nFor local testing, read files list from `../../Data/hw6-files-10mb.txt`.\nNow let's see how many lines there are in the input files.\n\n1. Make RDD from the list of files in `hw6-files-10mb.txt`.\n2. Mark the RDD to be cached (so in next operation data will be loaded in memory) \n3. call the `print_count` method to print number of lines in all these files\n\nIt should print\n```\nNumber of elements: 2193\n```\n\n\n```python\ndef print_count(rdd):\n    print 'Number of elements:', rdd.count()\n```\n\n\n```python\n# Your code here\nimport findspark\nfindspark.init()\n\nfrom pyspark import SparkContext\nsc = SparkContext(master=\"local[4]\")\n\nfilename_list = []\nwith open(\"../../Data/hw6-files-10mb.txt\") as f:\n    filename_list = [filename.strip() for filename in f]\nrdd = sc.textFile(\",\".join(filename_list)).cache()\n\nprint_count(rdd)\n```\n\n    Number of elements: 2193\n\n\n# Part 1: Parse JSON strings to JSON objects\n\nPython has built-in support for JSON.\n\n\n```python\nimport json\n\njson_example = '''\n{\n    \"id\": 1,\n    \"name\": \"A green door\",\n    \"price\": 12.50,\n    \"tags\": [\"home\", \"green\"]\n}\n'''\n\njson_obj = json.loads(json_example)\njson_obj\n```\n\n\n\n\n    {u'id': 1,\n     u'name': u'A green door',\n     u'price': 12.5,\n     u'tags': [u'home', u'green']}\n\n\n\n## Broken tweets and irrelevant messages\n\nThe data of this assignment may contain broken tweets (invalid JSON strings). So make sure that your code is robust for such cases.\n\nIn addition, some lines in the input file might not be tweets, but messages that the Twitter server sent to the developer (such as [limit notices](https://dev.twitter.com/streaming/overview/messages-types#limit_notices)). Your program should also ignore these messages.\n\n*Hint:* [Catch the ValueError](http://stackoverflow.com/questions/11294535/verify-if-a-string-is-json-in-python)\n\n\n(1) Parse raw JSON tweets to obtain valid JSON objects. From all valid tweets, construct a pair RDD of `(user_id, text)`, where `user_id` is the `id_str` data field of the `user` dictionary (read [Tweets](#Tweets) section above), `text` is the `text` data field.\n\n\n```python\nimport json\n\ndef safe_parse(raw_json):\n    try:\n        tweet = json.loads(raw_json)\n        pair = [tweet[\"user\"][\"id_str\"], tweet[\"text\"].encode(\"utf-8\")]\n        return pair\n    except:\n        return None\n\nuser_text_rdd = rdd.map(safe_parse).filter(lambda p: p is not None).cache()\n```\n\n(2) Count the number of different users in all valid tweets (hint: [the `distinct()` method](https://spark.apache.org/docs/latest/programming-guide.html#transformations)).\n\nIt should print\n```\nThe number of unique users is: 2083\n```\n\n\n```python\ndef print_users_count(count):\n    print 'The number of unique users is:', count\n```\n\n\n```python\n# your code here\ncount = user_text_rdd.map(lambda p: p[0]).distinct().count()\nprint_users_count(count)\n```\n\n    The number of unique users is: 2083\n\n\n# Part 2: Number of posts from each user partition\n\nLoad the Pickle file `../../Data/users-partition.pickle`, you will get a dictionary which represents a partition over 452,743 Twitter users, `{user_id: partition_id}`. The users are partitioned into 7 groups. For example, if the dictionary is loaded into a variable named `partition`, the partition ID of the user `59458445` is `partition[\"59458445\"]`. These users are partitioned into 7 groups. The partition ID is an integer between 0-6.\n\nNote that the user partition we provide doesn't cover all users appear in the input data.\n\n(1) Load the pickle file.\n\n\n```python\n# your code here\nimport pickle\n\npartition_dict = None\nwith open(\"../../Data/users-partition.pickle\") as f:\n    partition_dict = pickle.load(f)\n```\n\n(2) Count the number of posts from each user partition\n\nCount the number of posts from group 0, 1, ..., 6, plus the number of posts from users who are not in any partition. Assign users who are not in any partition to the group 7.\n\nPut the results of this step into a pair RDD `(group_id, count)` that is sorted by key.\n\n\n```python\n# your code here\ndef get_group_id(user_id):\n    return partition_dict[user_id] if user_id in partition_dict else 7\n\nfrom operator import add\n    \ngroup_count_rdd = user_text_rdd.map(lambda p: [get_group_id(p[0]), 1]).reduceByKey(add).sortByKey()\n```\n\n(3) Print the post count using the `print_post_count` function we provided.\n\nIt should print\n\n```\nGroup 0 posted 81 tweets\nGroup 1 posted 199 tweets\nGroup 2 posted 45 tweets\nGroup 3 posted 313 tweets\nGroup 4 posted 86 tweets\nGroup 5 posted 221 tweets\nGroup 6 posted 400 tweets\nGroup 7 posted 798 tweets\n```\n\n\n```python\ndef print_post_count(counts):\n    for group_id, count in counts:\n        print 'Group %d posted %d tweets' % (group_id, count)\n```\n\n\n```python\n# your code here\nprint_post_count(group_count_rdd.collect())\n```\n\n    Group 0 posted 81 tweets\n    Group 1 posted 199 tweets\n    Group 2 posted 45 tweets\n    Group 3 posted 313 tweets\n    Group 4 posted 86 tweets\n    Group 5 posted 221 tweets\n    Group 6 posted 400 tweets\n    Group 7 posted 798 tweets\n\n\n# Part 3:  Tokens that are relatively popular in each user partition\n\nIn this step, we are going to find tokens that are relatively popular in each user partition.\n\nWe define the number of mentions of a token $t$ in a specific user partition $k$ as the number of users from the user partition $k$ that ever mentioned the token $t$ in their tweets. Note that even if some users might mention a token $t$ multiple times or in multiple tweets, a user will contribute at most 1 to the counter of the token $t$.\n\nPlease make sure that the number of mentions of a token is equal to the number of users who mentioned this token but NOT the number of tweets that mentioned this token.\n\nLet $N_t^k$ be the number of mentions of the token $t$ in the user partition $k$. Let $N_t^{all} = \\sum_{i=0}^7 N_t^{i}$ be the number of total mentions of the token $t$.\n\nWe define the relative popularity of a token $t$ in a user partition $k$ as the log ratio between $N_t^k$ and $N_t^{all}$, i.e. \n\n\\begin{equation}\np_t^k = \\log \\frac{C_t^k}{C_t^{all}}.\n\\end{equation}\n\n\nYou can compute the relative popularity by calling the function `get_rel_popularity`.\n\n(0) Load the tweet tokenizer.\n\n\n```python\n# %load happyfuntokenizing.py\n#!/usr/bin/env python\n\n\"\"\"\nThis code implements a basic, Twitter-aware tokenizer.\n\nA tokenizer is a function that splits a string of text into words. In\nPython terms, we map string and unicode objects into lists of unicode\nobjects.\n\nThere is not a single right way to do tokenizing. The best method\ndepends on the application.  This tokenizer is designed to be flexible\nand this easy to adapt to new domains and tasks.  The basic logic is\nthis:\n\n1. The tuple regex_strings defines a list of regular expression\n   strings.\n\n2. The regex_strings strings are put, in order, into a compiled\n   regular expression object called word_re.\n\n3. The tokenization is done by word_re.findall(s), where s is the\n   user-supplied string, inside the tokenize() method of the class\n   Tokenizer.\n\n4. When instantiating Tokenizer objects, there is a single option:\n   preserve_case.  By default, it is set to True. If it is set to\n   False, then the tokenizer will downcase everything except for\n   emoticons.\n\nThe __main__ method illustrates by tokenizing a few examples.\n\nI've also included a Tokenizer method tokenize_random_tweet(). If the\ntwitter library is installed (http://code.google.com/p/python-twitter/)\nand Twitter is cooperating, then it should tokenize a random\nEnglish-language tweet.\n\n\nJulaiti Alafate:\n  I modified the regex strings to extract URLs in tweets.\n\"\"\"\n\n__author__ = \"Christopher Potts\"\n__copyright__ = \"Copyright 2011, Christopher Potts\"\n__credits__ = []\n__license__ = \"Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License: http://creativecommons.org/licenses/by-nc-sa/3.0/\"\n__version__ = \"1.0\"\n__maintainer__ = \"Christopher Potts\"\n__email__ = \"See the author's website\"\n\n######################################################################\n\nimport re\nimport htmlentitydefs\n\n######################################################################\n# The following strings are components in the regular expression\n# that is used for tokenizing. It's important that phone_number\n# appears first in the final regex (since it can contain whitespace).\n# It also could matter that tags comes after emoticons, due to the\n# possibility of having text like\n#\n#     <:| and some text >:)\n#\n# Most imporatantly, the final element should always be last, since it\n# does a last ditch whitespace-based tokenization of whatever is left.\n\n# This particular element is used in a couple ways, so we define it\n# with a name:\nemoticon_string = r\"\"\"\n    (?:\n      [<>]?\n      [:;=8]                     # eyes\n      [\\-o\\*\\']?                 # optional nose\n      [\\)\\]\\(\\[dDpP/\\:\\}\\{@\\|\\\\] # mouth      \n      |\n      [\\)\\]\\(\\[dDpP/\\:\\}\\{@\\|\\\\] # mouth\n      [\\-o\\*\\']?                 # optional nose\n      [:;=8]                     # eyes\n      [<>]?\n    )\"\"\"\n\n# The components of the tokenizer:\nregex_strings = (\n    # Phone numbers:\n    r\"\"\"\n    (?:\n      (?:            # (international)\n        \\+?[01]\n        [\\-\\s.]*\n      )?            \n      (?:            # (area code)\n        [\\(]?\n        \\d{3}\n        [\\-\\s.\\)]*\n      )?    \n      \\d{3}          # exchange\n      [\\-\\s.]*   \n      \\d{4}          # base\n    )\"\"\"\n    ,\n    # URLs:\n    r\"\"\"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+\"\"\"\n    ,\n    # Emoticons:\n    emoticon_string\n    ,    \n    # HTML tags:\n     r\"\"\"<[^>]+>\"\"\"\n    ,\n    # Twitter username:\n    r\"\"\"(?:@[\\w_]+)\"\"\"\n    ,\n    # Twitter hashtags:\n    r\"\"\"(?:\\#+[\\w_]+[\\w\\'_\\-]*[\\w_]+)\"\"\"\n    ,\n    # Remaining word types:\n    r\"\"\"\n    (?:[a-z][a-z'\\-_]+[a-z])       # Words with apostrophes or dashes.\n    |\n    (?:[+\\-]?\\d+[,/.:-]\\d+[+\\-]?)  # Numbers, including fractions, decimals.\n    |\n    (?:[\\w_]+)                     # Words without apostrophes or dashes.\n    |\n    (?:\\.(?:\\s*\\.){1,})            # Ellipsis dots. \n    |\n    (?:\\S)                         # Everything else that isn't whitespace.\n    \"\"\"\n    )\n\n######################################################################\n# This is the core tokenizing regex:\n    \nword_re = re.compile(r\"\"\"(%s)\"\"\" % \"|\".join(regex_strings), re.VERBOSE | re.I | re.UNICODE)\n\n# The emoticon string gets its own regex so that we can preserve case for them as needed:\nemoticon_re = re.compile(regex_strings[1], re.VERBOSE | re.I | re.UNICODE)\n\n# These are for regularizing HTML entities to Unicode:\nhtml_entity_digit_re = re.compile(r\"&#\\d+;\")\nhtml_entity_alpha_re = re.compile(r\"&\\w+;\")\namp = \"&amp;\"\n\n######################################################################\n\nclass Tokenizer:\n    def __init__(self, preserve_case=False):\n        self.preserve_case = preserve_case\n\n    def tokenize(self, s):\n        \"\"\"\n        Argument: s -- any string or unicode object\n        Value: a tokenize list of strings; conatenating this list returns the original string if preserve_case=False\n        \"\"\"        \n        # Try to ensure unicode:\n        try:\n            s = unicode(s)\n        except UnicodeDecodeError:\n            s = str(s).encode('string_escape')\n            s = unicode(s)\n        # Fix HTML character entitites:\n        s = self.__html2unicode(s)\n        # Tokenize:\n        words = word_re.findall(s)\n        # Possible alter the case, but avoid changing emoticons like :D into :d:\n        if not self.preserve_case:            \n            words = map((lambda x : x if emoticon_re.search(x) else x.lower()), words)\n        return words\n\n    def tokenize_random_tweet(self):\n        \"\"\"\n        If the twitter library is installed and a twitter connection\n        can be established, then tokenize a random tweet.\n        \"\"\"\n        try:\n            import twitter\n        except ImportError:\n            print \"Apologies. The random tweet functionality requires the Python twitter library: http://code.google.com/p/python-twitter/\"\n        from random import shuffle\n        api = twitter.Api()\n        tweets = api.GetPublicTimeline()\n        if tweets:\n            for tweet in tweets:\n                if tweet.user.lang == 'en':            \n                    return self.tokenize(tweet.text)\n        else:\n            raise Exception(\"Apologies. I couldn't get Twitter to give me a public English-language tweet. Perhaps try again\")\n\n    def __html2unicode(self, s):\n        \"\"\"\n        Internal metod that seeks to replace all the HTML entities in\n        s with their corresponding unicode characters.\n        \"\"\"\n        # First the digits:\n        ents = set(html_entity_digit_re.findall(s))\n        if len(ents) > 0:\n            for ent in ents:\n                entnum = ent[2:-1]\n                try:\n                    entnum = int(entnum)\n                    s = s.replace(ent, unichr(entnum))\t\n                except:\n                    pass\n        # Now the alpha versions:\n        ents = set(html_entity_alpha_re.findall(s))\n        ents = filter((lambda x : x != amp), ents)\n        for ent in ents:\n            entname = ent[1:-1]\n            try:            \n                s = s.replace(ent, unichr(htmlentitydefs.name2codepoint[entname]))\n            except:\n                pass                    \n            s = s.replace(amp, \" and \")\n        return s\n```\n\n\n```python\nfrom math import log\n\ntok = Tokenizer(preserve_case=False)\n\ndef get_rel_popularity(c_k, c_all):\n    return log(1.0 * c_k / c_all) / log(2)\n\n\ndef print_tokens(tokens, gid = None):\n    group_name = \"overall\"\n    if gid is not None:\n        group_name = \"group %d\" % gid\n    print '=' * 5 + ' ' + group_name + ' ' + '=' * 5\n    for t, n in tokens:\n        print \"%s\\t%.4f\" % (t, n)\n    print\n```\n\n(1) Tokenize the tweets using the tokenizer we provided above named `tok`. Count the number of mentions for each tokens regardless of specific user group.\n\nCall `print_count` function to show how many different tokens we have.\n\nIt should print\n```\nNumber of elements: 8949\n```\n\n\n```python\n# your code here\ntokenizer = Tokenizer()\ntoken_user_rdd = user_text_rdd.flatMap(lambda p: [[word, [p[0]]] for word in set(tokenizer.tokenize(p[1]))]) \\\n                              .reduceByKey(add)\\\n                              .map(lambda p: [p[0], list(set(p[1]))]).cache()\nprint_count(token_user_rdd)\n```\n\n    Number of elements: 8979\n\n\n(2) Tokens that are mentioned by too few users are usually not very interesting. So we want to only keep tokens that are mentioned by at least 100 users. Please filter out tokens that don't meet this requirement.\n\nCall `print_count` function to show how many different tokens we have after the filtering.\n\nCall `print_tokens` function to show top 20 most frequent tokens.\n\nIt should print\n```\nNumber of elements: 44\n===== overall =====\n:\t1388.0000\nrt\t1237.0000\n.\t826.0000\n\u2026\t673.0000\nthe\t623.0000\ntrump\t582.0000\nto\t499.0000\n,\t489.0000\na\t404.0000\nis\t376.0000\nin\t297.0000\nof\t292.0000\nand\t288.0000\nfor\t281.0000\n!\t269.0000\n?\t210.0000\non\t195.0000\ni\t192.0000\nyou\t191.0000\nthis\t190.0000\n```\n\n\n```python\n# your code here\nfrequent_token_rdd = token_user_rdd.map(lambda p: [p[0], len(p[1])])\\\n                                   .filter(lambda p: p[1] >= 100)\\\n                                   .sortBy(lambda p: p[1], ascending = False)\nprint_count(frequent_token_rdd)\nprint_tokens(frequent_token_rdd.take(20))\n```\n\n    Number of elements: 52\n    ===== overall =====\n    :\t1386.0000\n    rt\t1237.0000\n    .\t865.0000\n    \\\t745.0000\n    the\t621.0000\n    trump\t595.0000\n    x80\t545.0000\n    xe2\t543.0000\n    to\t499.0000\n    ,\t489.0000\n    xa6\t457.0000\n    a\t403.0000\n    is\t376.0000\n    in\t296.0000\n    '\t294.0000\n    of\t292.0000\n    and\t287.0000\n    for\t280.0000\n    !\t269.0000\n    ?\t210.0000\n    \n\n\n(3) For all tokens that are mentioned by at least 100 users, compute their relative popularity in each user group. Then print the top 10 tokens with highest relative popularity in each user group. In case two tokens have same relative popularity, break the tie by printing the alphabetically smaller one.\n\n**Hint:** Let the relative popularity of a token $t$ be $p$. The order of the items will be satisfied by sorting them using (-p, t) as the key.\n\nIt should print\n```\n===== group 0 =====\n...\t-3.5648\nat\t-3.5983\nhillary\t-4.0875\ni\t-4.1255\nbernie\t-4.1699\nnot\t-4.2479\nhttps\t-4.2695\nhe\t-4.2801\nin\t-4.3074\nare\t-4.3646\n\n===== group 1 =====\n#demdebate\t-2.4391\n-\t-2.6202\n&\t-2.7472\namp\t-2.7472\nclinton\t-2.7570\n;\t-2.7980\nsanders\t-2.8838\n?\t-2.9069\nin\t-2.9664\nif\t-3.0138\n\n===== group 2 =====\nare\t-4.6865\nand\t-4.7105\nbernie\t-4.7549\nat\t-4.7682\nsanders\t-4.9542\nthat\t-5.0224\nin\t-5.0444\ndonald\t-5.0618\na\t-5.0732\n#demdebate\t-5.1396\n\n===== group 3 =====\n#demdebate\t-1.3847\nbernie\t-1.8480\nsanders\t-2.1887\nof\t-2.2356\nthat\t-2.3785\nthe\t-2.4376\n\u2026\t-2.4403\nclinton\t-2.4467\nhillary\t-2.4594\nbe\t-2.5465\n\n===== group 4 =====\nhillary\t-3.7395\nsanders\t-3.9542\nof\t-4.0199\nclinton\t-4.0790\nat\t-4.1832\nin\t-4.2143\na\t-4.2659\non\t-4.2854\n.\t-4.3681\nthe\t-4.4251\n\n===== group 5 =====\ncruz\t-2.3861\nhe\t-2.6280\nare\t-2.7796\nwill\t-2.7829\nthe\t-2.8568\nis\t-2.8822\nfor\t-2.9250\nthat\t-2.9349\nof\t-2.9804\nthis\t-2.9849\n\n===== group 6 =====\n@realdonaldtrump\t-1.1520\ncruz\t-1.4532\nhttps\t-1.5222\n!\t-1.5479\nnot\t-1.8904\n\u2026\t-1.9269\nwill\t-2.0124\nit\t-2.0345\nthis\t-2.1104\nto\t-2.1685\n\n===== group 7 =====\ndonald\t-0.6422\n...\t-0.7922\nsanders\t-1.0282\ntrump\t-1.1296\nbernie\t-1.2106\n-\t-1.2253\nyou\t-1.2376\nclinton\t-1.2511\nif\t-1.2880\ni\t-1.2996\n```\n\n\n```python\n# your code here\ndef get_relpop_vec(users):\n    count_vec = [0 for k in range(8)]\n    for user in users:\n        count_vec[get_group_id(user)] += 1\n    c_all = sum(count_vec)\n    relpop_vec = [get_rel_popularity(count_vec[k], c_all) if count_vec[k] > 0 else float('-inf')\n                      for k in range(8)]\n    return relpop_vec\n\ntoken_relpop_rdd = token_user_rdd.filter(lambda p: len(p[1]) >= 100)\\\n                                 .map(lambda p : [p[0].encode(\"utf-8\"), get_relpop_vec(p[1])])\\\n                                 .cache()\n\nfor k in range(8):\n    group_token_relpop_rdd = token_relpop_rdd.map(lambda p: [p[0], p[1][k]])\\\n                                             .sortBy(lambda p: (-p[1], p[0]))\n    print_tokens(group_token_relpop_rdd.take(10), k)\n```\n\n    ===== group 0 =====\n    ...\t-3.5648\n    at\t-3.5983\n    hillary\t-4.0484\n    bernie\t-4.1430\n    not\t-4.2479\n    he\t-4.2574\n    i\t-4.2854\n    s\t-4.3309\n    are\t-4.3646\n    in\t-4.4021\n    \n    ===== group 1 =====\n    #demdebate\t-2.4391\n    -\t-2.6202\n    clinton\t-2.7174\n    &\t-2.7472\n    amp\t-2.7472\n    ;\t-2.7980\n    sanders\t-2.8745\n    ?\t-2.9069\n    in\t-2.9615\n    if\t-2.9861\n    \n    ===== group 2 =====\n    are\t-4.6865\n    and\t-4.7055\n    bernie\t-4.7279\n    at\t-4.7682\n    sanders\t-4.9449\n    in\t-5.0395\n    donald\t-5.0531\n    a\t-5.0697\n    #demdebate\t-5.1396\n    that\t-5.1599\n    \n    ===== group 3 =====\n    #demdebate\t-1.3847\n    bernie\t-1.8535\n    sanders\t-2.1793\n    of\t-2.2356\n    t\t-2.2675\n    clinton\t-2.4179\n    hillary\t-2.4203\n    the\t-2.4330\n    xa6\t-2.4962\n    that\t-2.5160\n    \n    ===== group 4 =====\n    hillary\t-3.8074\n    sanders\t-3.9449\n    of\t-4.0199\n    what\t-4.0875\n    clinton\t-4.0959\n    at\t-4.1832\n    in\t-4.2095\n    a\t-4.2623\n    on\t-4.2854\n    '\t-4.2928\n    \n    ===== group 5 =====\n    cruz\t-2.3344\n    he\t-2.6724\n    will\t-2.7705\n    are\t-2.7796\n    the\t-2.8522\n    is\t-2.8822\n    that\t-2.9119\n    this\t-2.9542\n    for\t-2.9594\n    of\t-2.9804\n    \n    ===== group 6 =====\n    @realdonaldtrump\t-1.1520\n    cruz\t-1.4657\n    n\t-1.4877\n    !\t-1.5479\n    not\t-1.8904\n    xa6\t-1.9172\n    xe2\t-1.9973\n    /\t-2.0238\n    x80\t-2.0240\n    it\t-2.0506\n    \n    ===== group 7 =====\n    donald\t-0.6471\n    ...\t-0.7922\n    sanders\t-1.0380\n    what\t-1.1178\n    trump\t-1.1293\n    bernie\t-1.2044\n    you\t-1.2099\n    -\t-1.2253\n    if\t-1.2602\n    clinton\t-1.2681\n    \n\n\n(4) (optional, not for grading) The users partition is generated by a machine learning algorithm that tries to group the users by their political preferences. Three of the user groups are showing supports to Bernie Sanders, Ted Cruz, and Donald Trump. \n\nIf your program looks okay on the local test data, you can try it on the larger input by submitting your program to the homework server. Observe the output of your program to larger input files, can you guess the partition IDs of the three groups mentioned above based on your output?\n\n\n```python\n# Change the values of the following three items to your guesses\nusers_support = [\n    (-1, \"Bernie Sanders\"),\n    (-1, \"Ted Cruz\"),\n    (-1, \"Donald Trump\")\n]\n\nfor gid, candidate in users_support:\n    print \"Users from group %d are most likely to support %s.\" % (gid, candidate)\n```\n\n    Users from group -1 are most likely to support Bernie Sanders.\n    Users from group -1 are most likely to support Ted Cruz.\n    Users from group -1 are most likely to support Donald Trump.\n\n", "meta": {"hexsha": "b02cea31b00362df314df23e2940cc8c27bda1be", "size": 34470, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorials/spark-da-cse255/010_twitter_tweets.ipynb", "max_stars_repo_name": "superkley/spark-playground", "max_stars_repo_head_hexsha": "563aacdd4f0bb32372c912a0de8d9f9889842976", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorials/spark-da-cse255/010_twitter_tweets.ipynb", "max_issues_repo_name": "superkley/spark-playground", "max_issues_repo_head_hexsha": "563aacdd4f0bb32372c912a0de8d9f9889842976", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-10-14T07:16:41.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-14T07:16:41.000Z", "max_forks_repo_path": "tutorials/spark-da-cse255/010_twitter_tweets.ipynb", "max_forks_repo_name": "superkley/spark-playground", "max_forks_repo_head_hexsha": "563aacdd4f0bb32372c912a0de8d9f9889842976", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9758812616, "max_line_length": 450, "alphanum_fraction": 0.5143603133, "converted": true, "num_tokens": 6811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18242552380635635, "lm_q2_score": 0.11124120503431592, "lm_q1q2_score": 0.020293235097235365}}
{"text": "<p>\n\n<div align=\"right\">\n<small>\n<br>October 12, 2017: presentation time\n<br>October 8, 2017: second draft\n<br>October 3, 2017: first draft\n</small>\n</div>\n</p>\n<br>\n<p>\n<div align=\"center\">\n<b>Abstract</b><br>\nThis presentation is a summary of the work I've done during the second year\n<br>of my PhD course in Computer Science, XXXI cycle @ UniFI\n</div>\n</p>\n\n\n```python\nfrom IPython.display import Markdown, Image, Latex\n\nfrom collections import defaultdict\n\nfrom muk.core import *\nfrom muk.ext import *\n\nfrom sympy import IndexedBase, symbols, latex, init_printing, Eq, Matrix\ninit_printing()\n\n\ntoc = [\"\", \"exams & courses & conferences\", \"what I've done\", \"what I'm working on\"]#, \"thesis arguments\"]\ntoc_iter = iter(toc[1:])\n\ndef reference_to_this_talk():\n    src = '<a href=\"{href}\">{href}</a>'\n    return Markdown(src.format(href=r'http://massimo-nocentini.github.io/PhD/second-year-summary/talk.html'))\n\ndef table_of_contents():\n    src = r'# TOC'\n    return Markdown('\\n- '.join(toc))\n\ndef greetings(smiley=True):\n    return Markdown(\"<h1>{greet} {smile}</h1>\".format(\n        greet=\"Thanks for coming \", smile=\":)\" if smiley else \"\"))\n\ndef next_topic():\n    return Markdown(\"# {topic}\".format(topic=next(toc_iter)))\n```\n\n\n```python\n__AUTHOR__ = (\"Massimo Nocentini\", \n              \"massimo.nocentini@unifi.it\", \n              \"https://github.com/massimo-nocentini/\")\n\n__SUPERVISOR__ = (\"Donatella Merlini \", \n                  \"donatella.merlini@unifi.it\")\n\n__ACKNOWLEDGEMENT__ = {\"Giovanni Marchetti\", \n                       \"Marco Maggesi\", \n                       \"Antonio Bernini\",\n                       \"Cecilia Verri\"}\n\nreference_to_this_talk()\n```\n\n\n\n\n<a href=\"http://massimo-nocentini.github.io/PhD/second-year-summary/talk.html\">http://massimo-nocentini.github.io/PhD/second-year-summary/talk.html</a>\n\n\n\n\n```python\ntable_of_contents()\n```\n\n\n\n\n\n- exams & courses & conferences\n- what I've done\n- what I'm working on\n\n\n\n\n```python\nnext_topic()\n```\n\n\n\n\n# exams & courses & conferences\n\n\n\n### Analysis of algorithms and data structures through Riordan arrays\n\ntaught by professor Donatella Merlini, 2 CFU: \n- we studied enumeration of _binary words avoiding patterns_\n- submitted a related paper __Algebraic generating functions for languages avoiding Riordan patterns__\n    - received a review in July, just resubmitted with fixes\n- more on this in a little while...\n\n### Advanced programming techniques\n\ntaught by professor Lorenzo Bettini, 2 CFU:\n- hard practice about _TDD, BDD_ and _CI_, the Pythonic way of course\n- reworked on my own the _bootstrap of a TDD framework_ inspired by [Kent Beck][beck]\n- more on this [here][repo]\n\n[repo]:https://github.com/massimo-nocentini/advanced-programming-techniques-course\n[beck]:https://www.amazon.it/Test-Driven-Development-Example-Kent-Beck/dp/0321146530/ref=sr_1_1?s=english-books&ie=UTF8&qid=1507040431&sr=1-1&keywords=beck+test+driven+development\n\n### Bayesian methods for high-dimensional data\n\ntaught by professor Francesco Stingo, 2 CFU:\n- new topics for me: _bayesian model selection for GLM_ and _high-dimension graphical model_\n- worked through _Evolutionary Stochastic Search_, Gibbs and Metropolis-Hastings samplers\n- more on this [here][repo]\n\n[repo]:https://github.com/massimo-nocentini/statistical-models/tree/master/bayesian-inference\n\n### Statistical learning\n\ntaught by professor Giovanni Maria Marchetti, 3 CFU:\n- new topics for me: _graphical models_, $d$-connection, _categorical data analysis_\n- worked through _Decomposition by clique separators_, theoretically\n- more on this [here][repo]\n\n[repo]:https://github.com/massimo-nocentini/statistical-models/tree/master/clique-separators\n\n## Present and Future exams\n\n### Numerical methods for simulation\n\ntaught by professor Luigi Brugnano, 3 CFU: _functions of matrices_.\n\n### Graph mining\n\ntaught by professor Pierluigi Crescenzi, 3 CFU: _OEIS sequences networks_.\n\n## Conferences\n\nLast July, in Rimini, __EUROPYTHON__, https://ep2017.europython.eu/en/\n- attended almost _pydata_ and _core language_ sessions\n- met _Alex Martelli_\n\nLast September, in Oxford, __ICFP2017__, https://icfp17.sigplan.org/\n- served as _student volounteer_\n- attended all ICFP talks\n\n## SKKU open school\n\nGiven two talks (the first one [recorded][youtube]) at open school _Combinatorial methods in the analysis of algorithms and data structures_ ([link][os]) February 20-24, Suwon, Korea.\n\n[youtube]:https://www.youtube.com/watch?v=6w8oi2VeFDM\n[os]:http://shb.skku.edu/aorc/conference_info/new.jsp\n\n\n```python\nnext_topic()\n```\n\n\n\n\n# what I've done\n\n\n\n## in a nutshell\n\ntheoretical stuff:\n- submitted a paper with Donatella for my master thesis about _binary words enumerations_\n- application of the framework of _functions matrices_ to the _Riordan group_\n\ncoding stuff:\n - 70% Python\n   - rewritten a set of tools to mine the [OEIS][oeis]\n   - written a _complete_ port of _microKanren_\n - 20% Lisp\n   - [MiniKanren][mk] under the hood\n - 10% OCaml\n   - begin a _certified_ implementation of microKanren into _HOL Light_, joint work with professor _Marco Maggesi_\n   \n[mk]:http://minikanren.org/\n\n[oeis]:http://oeis.org/\n\n## theoretical time\n\n## practical time\n\nmeet _microKanren_\n- a DSL for relational programming, in Scheme\n- purely functional of [_miniKanren_][mk]\n- *explicit streams* of satisfying states, _goal-based_ approach\n- _unification_ instead of _SLD-NF resolution_\n- complete, _unfair_ search strategy\n\nmy contribution\n- _Pythonic_ [implementation][mkpy]: functional at the core, objective at the interface\n- generators subsume _countably_-satisfiable relations; complete, _fair_ [search][dovetail]\n- _The Reasoned Schemer_ fully tested via [Travis CI][travis]; moreover, [read the docs][rtfd]\n- case studies: Smullyan puzzles and combinatorics\n- tweaking HOL Light for _certified deductions_, [wip][klight]\n\n[mk]:http://minikanren.org/\n[travis]:https://travis-ci.org/massimo-nocentini/microkanrenpy\n[rtfd]:http://microkanrenpy.readthedocs.io/en/latest/\n[klight]:https://github.com/massimo-nocentini/kanren-light\n[mkpy]:https://github.com/massimo-nocentini/microkanrenpy\n[dovetail]:http://microkanrenpy.readthedocs.io/en/latest/under_the_hood.html#muk.core.mplus\n\n\n```python\nrvar(0) # a logic variable\n```\n\n\n\n\n    \u25a2\u2080\n\n\n\n\n```python\nrun(succeed) # a goal that always succeeds\n```\n\n\n\n\n    [Tautology]\n\n\n\n\n```python\nrun(fail) # a goal that always fails\n```\n\n\n```python\nrun(fresh(lambda q: succeed)) # a free variable without association\n```\n\n\n\n\n    [\u25a2\u2080]\n\n\n\n\n```python\nrun(unify(3, 3)) # unification of ground values\n```\n\n\n\n\n    [Tautology]\n\n\n\n\n```python\nrun(fresh(lambda q: unify(3, q))) # unification of a variable\n```\n\n\n```python\nrun(fresh(lambda q: unify([[2, 3], 1, 2, 3], [q, 1] + q))) # list unification\n```\n\n\n```python\nrun(fresh(lambda q, z: unify(q, z) & unify(z, 3))) # co-sharing\n```\n\n\n```python\nrun(fresh(lambda q: unify(q, False) | unify(q, True))) # disjunction\n```\n\n\n\n\n    [False, True]\n\n\n\n\n```python\nrun(fresh(lambda q: \n          fresh(lambda q: unify(q, False)) & \n          unify(q, True))) # conjunction\n```\n\n\n\n\n    [True]\n\n\n\n\n```python\ndef father(p, s):\n    return conde([unify(p, 'paul'), unify(s, 'jason')],\n                 [unify(p, 'john'), unify(s, 'henry')],\n                 [unify(p, 'jason'), unify(s, 'tom')],\n                 [unify(p, 'peter'), unify(s, 'brian')],\n                 [unify(p, 'tom'), unify(s, 'peter')])\n\ndef grand_father(g, s):\n    return fresh(lambda p: father(g, p) & father(p, s))\n\nrun(fresh(lambda rel, p, s: grand_father(p, s) & unify([p, s], rel)))\n```\n\n\n\n\n    [['paul', 'tom'], ['jason', 'peter'], ['tom', 'brian']]\n\n\n\n\n```python\ndef fives(x):\n    return unify(5, x) | fives(x)\n\ntry:\n    run(fresh(lambda x: fives(x)))\nexcept RecursionError:\n    pass\n```\n\n\n```python\ndef fives(x):\n    return unify(5, x) | fresh(lambda y: fives(y))\n\nrun(fresh(fives), n=5)\n```\n\n\n\n\n    [5, \u25a2\u2080, \u25a2\u2080, \u25a2\u2080, \u25a2\u2080]\n\n\n\n\n```python\ng = fresh(lambda x: fives(x))\nstates = g(emptystate())\n[next(states) for i in range(5)]\n```\n\n\n\n\n    [state(sub={x\u2080: 5}, next_index=1),\n     state(sub={y\u2081: 5}, next_index=2),\n     state(sub={y\u2082: 5}, next_index=3),\n     state(sub={y\u2083: 5}, next_index=4),\n     state(sub={y\u2084: 5}, next_index=5)]\n\n\n\n\n```python\ndef fives(x):\n    return unify(5, x) | fresh(lambda: fives(x))\n\nrun(fresh(fives), n=5)\n```\n\n\n```python\ng = fresh(lambda x: fives(x))\nstates = g(emptystate())\n[next(states) for i in range(5)]\n```\n\n\n\n\n    [state(sub={x\u2080: 5}, next_index=1),\n     state(sub={x\u2080: 5}, next_index=1),\n     state(sub={x\u2080: 5}, next_index=1),\n     state(sub={x\u2080: 5}, next_index=1),\n     state(sub={x\u2080: 5}, next_index=1)]\n\n\n\n\n```python\ndef nats(x, n=0):\n    return unify(n, x) | fresh(lambda: nats(x, n+1))\n\nrun(fresh(lambda x: nats(x)), n=10)\n```\n\n\n```python\ndef nullo(l):\n    return unify([], l)\n\ndef appendo(r, s, out):\n    def A(r, out):\n        return conde([nullo(r), unify(s, out)],\n                     else_clause=fresh(lambda a, d, res:\n                                           unify([a]+d, r) &\n                                           unify([a]+res, out) &\n                                           fresh(lambda: A(d, res))))\n    return A(r, out)\n```\n\n\n```python\nrun(fresh(lambda l, q: appendo([1,2,3]+q, [4,5,6], l)), n=5)\n```\n\n\n\n\n    [[1, 2, 3, 4, 5, 6],\n     [1, 2, 3, \u25a2\u2080, 4, 5, 6],\n     [1, 2, 3, \u25a2\u2080, \u25a2\u2081, 4, 5, 6],\n     [1, 2, 3, \u25a2\u2080, \u25a2\u2081, \u25a2\u2082, 4, 5, 6],\n     [1, 2, 3, \u25a2\u2080, \u25a2\u2081, \u25a2\u2082, \u25a2\u2083, 4, 5, 6]]\n\n\n\n\n```python\nrun(fresh(lambda r, x, y:\n          appendo(x, y, ['cake', 'with', 'ice', 'd', 't']) &\n          unify([x, y], r))) \n```\n\n\n\n\n    [[[], ['cake', 'with', 'ice', 'd', 't']],\n     [['cake'], ['with', 'ice', 'd', 't']],\n     [['cake', 'with'], ['ice', 'd', 't']],\n     [['cake', 'with', 'ice'], ['d', 't']],\n     [['cake', 'with', 'ice', 'd'], ['t']],\n     [['cake', 'with', 'ice', 'd', 't'], []]]\n\n\n\n\n```python\ndef dycko(\u03b1):\n    return conde([nullo(\u03b1), succeed],\n                  else_clause=fresh(lambda \u03b2, \u03b3:\n                                    appendo(['(']+\u03b2, [')']+\u03b3, \u03b1) @ \n                                            (dycko(\u03b2) @ dycko(\u03b3))))\n\npaths = run(fresh(lambda \u03b1: dycko(\u03b1)), n=80)\nD = defaultdict(list)\nfor \u03b1 in map(lambda \u03b1: ''.join(\u03b1), paths):\n    D[len(\u03b1)//2].append(\u03b1)\n```\n\n\n```python\nfrom collections import namedtuple\n\ndyck = namedtuple('dyck', ['paths', 'count'])\n```\n\n\n```python\n[dyck(paths, len(paths)) for i in range(5) for paths in [D[i]]]\n```\n\n\n\n\n    [dyck(paths=[''], count=1),\n     dyck(paths=['()'], count=1),\n     dyck(paths=['()()', '(())'], count=2),\n     dyck(paths=['()()()', '(())()', '()(())', '(()())', '((()))'], count=5),\n     dyck(paths=['(())()()', '()()()()', '(())(())', '()(())()', '(()()())', '(()())()', '()()(())', '(()(()))', '((()))()', '()(()())', '((())())', '()((()))', '((()()))', '(((())))'], count=14)]\n\n\n\n\n```python\nP = IndexedBase('P')\nn, m = symbols('n m')\n\ndef pascalo(depth, r, c, \u03b1):\n    if not depth: return unify([P[r,c]], \u03b1)\n    return fresh(lambda \u03b2, \u03b3: (pascalo(depth-1, r-1, c-1, \u03b2) @\n                               pascalo(depth-1, r-1, c, \u03b3) @\n                               appendo(\u03b2, \u03b3, \u03b1)))\n\nunfoldings = {d:sum(addends)\n              for d in range(6) \n              for addends in run(fresh(lambda \u03b1: pascalo(d, n, m, \u03b1)))}\n```\n\n\n```python\nMatrix(5, 1, lambda i, j: unfoldings[i+1])\n```\n\n\n```python\nnext_topic()\n```\n\n\n\n\n# what I'm working on\n\n\n\n- *recursively defined structures*, both *inductively* and *co*-inductively\n- _matrices functions_ and _companion matrices_ applied to Riordan arrays\n- `(Y Y)` works! you do know `Y`, didn't you? \n    - *quine generation* with microKanren\n    - _disequality_ constraints support\n- *reasoning about Smullyan machines*, especially those that talk about themselves\n\n\n```python\ntry: \n    next_topic()\nexcept StopIteration: \n    import this\n```\n\n    The Zen of Python, by Tim Peters\n    \n    Beautiful is better than ugly.\n    Explicit is better than implicit.\n    Simple is better than complex.\n    Complex is better than complicated.\n    Flat is better than nested.\n    Sparse is better than dense.\n    Readability counts.\n    Special cases aren't special enough to break the rules.\n    Although practicality beats purity.\n    Errors should never pass silently.\n    Unless explicitly silenced.\n    In the face of ambiguity, refuse the temptation to guess.\n    There should be one-- and preferably only one --obvious way to do it.\n    Although that way may not be obvious at first unless you're Dutch.\n    Now is better than never.\n    Although never is often better than *right* now.\n    If the implementation is hard to explain, it's a bad idea.\n    If the implementation is easy to explain, it may be a good idea.\n    Namespaces are one honking great idea -- let's do more of those!\n\n\n\n```python\ngreetings(smiley=True)\n```\n\n\n\n\n<h1>Thanks for coming  :)</h1>\n\n\n\n---\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.\n", "meta": {"hexsha": "b2f9119062490e077c064f999ad1ab064a01a12e", "size": 42293, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "PhD/second-year-summary/presentation.ipynb", "max_stars_repo_name": "massimo-nocentini/massimo-nocentini.github.io", "max_stars_repo_head_hexsha": "ec20ba27d15006ba5b3dbcf0a38f20231238e9ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PhD/second-year-summary/presentation.ipynb", "max_issues_repo_name": "massimo-nocentini/massimo-nocentini.github.io", "max_issues_repo_head_hexsha": "ec20ba27d15006ba5b3dbcf0a38f20231238e9ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PhD/second-year-summary/presentation.ipynb", "max_forks_repo_name": "massimo-nocentini/massimo-nocentini.github.io", "max_forks_repo_head_hexsha": "ec20ba27d15006ba5b3dbcf0a38f20231238e9ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4332822086, "max_line_length": 6272, "alphanum_fraction": 0.590381387, "converted": true, "num_tokens": 3879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297238231752, "lm_q2_score": 0.07369627580942689, "lm_q1q2_score": 0.020276036010244167}}
{"text": "<a href=\"https://colab.research.google.com/github/kamehl/ex21/blob/main/imctf2021.ipynb\" target=\"_parent\"></a>\n\n#web\n\n##can you see cookie?\n\nCookie\u3092\u8abf\u3079\u3066\u307f\u308b\n\n\n```python\n!curl -i http://104.196.236.136:31909\n```\n\n    HTTP/1.1 200 OK\r\n    Server: nginx/1.21.4\r\n    Date: Fri, 24 Dec 2021 15:14:39 GMT\r\n    Content-Type: text/html\r\n    Content-Length: 3043\r\n    Last-Modified: Mon, 13 Dec 2021 03:04:20 GMT\r\n    Connection: keep-alive\r\n    ETag: \"61b6b834-be3\"\r\n    Accept-Ranges: bytes\r\n    \r\n    <!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"/><link rel=\"icon\" href=\"/favicon.ico\"/><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"/><meta name=\"theme-color\" content=\"#000000\"/><meta name=\"description\" content=\"Web site created using create-react-app\"/><link rel=\"apple-touch-icon\" href=\"/logo192.png\"/><link rel=\"manifest\" href=\"/manifest.json\"/><title>can you see \ud83c\udf6a?</title></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id=\"root\"></div><style>body,html{margin:0;height:100%;width:100%}</style></body></html>\n\n\u306a\u3044\n\n\u3088\u304f\u307f\u308b\u3068\u30fb\u30fb\u30fb\n\n<pre>You need to enable JavaScript to run this app.</pre>\n\n\u3068\u66f8\u3044\u3066\u3042\u308b\n\n\n\u3055\u3089\u306b\n\n<pre>\nscript src=\"/static/js/2.789fecdc.chunk.js\"\nscript src=\"/static/js/main.40252036.chunk.js\"\n</pre>\n\n\u306a\u3069\u3068\u8a18\u8f09\u304c\u3042\u308b\u306e\u3067\u8abf\u3079\u305f\u3068\u3053\u308d\n\n\n```python\nimport requests\n\nr = requests.get('http://104.196.236.136:31909/static/js/main.40252036.chunk.js')\nr.text\n```\n\n\n\n\n    '(this[\"webpackJsonpcan-you-see-cookie\"]=this[\"webpackJsonpcan-you-see-cookie\"]||[]).push([[0],{9:function(e,n,t){\"use strict\";t.r(n);var c=t(1),i=t.n(c),o=t(3),s=t.n(o),l=t.p+\"static/media/cookies.09ddddb3.jpg\",a=t(0);var r=function(){return document.cookie=decodeURIComponent(escape(atob(\"ZmxhZz1jblZ1WDNKMWJsOXlkVzVmWVhOZlptRnpkRjk1YjNWZlkyRnVJUT09\"))),Object(a.jsxs)(\"div\",{className:\"App\",style:{textAlign:\"center\",display:\"flex\",flexDirection:\"column\"},children:[Object(a.jsx)(\"header\",{className:\"App-header\",style:{backgroundColor:\"#282c34\",minHeight:\"10vh\",display:\"flex\",flexDirection:\"column\",alignItems:\"center\",justifyContent:\"center\",fontSize:\"calc(10px + 2vmin)\",color:\"white\"},children:\"can you see \\\\ud83c\\\\udf6a?\"}),Object(a.jsx)(\"main\",{style:{flexGrow:1},children:Object(a.jsx)(\"img\",{src:l,style:{width:\"80%\",margin:\"5% 10%\",borderRadius:\"0.2pc\"},alt:\"\"})}),Object(a.jsx)(\"footer\",{style:{backgroundColor:\"#282c34\",minHeight:\"10vh\",display:\"flex\",flexDirection:\"column\",alignItems:\"center\",justifyContent:\"center\",fontSize:\"calc(10px + 2vmin)\",color:\"white\"},children:\"Iron Maiden CTF\"})]})},d=function(e){e&&e instanceof Function&&t.e(3).then(t.bind(null,10)).then((function(n){var t=n.getCLS,c=n.getFID,i=n.getFCP,o=n.getLCP,s=n.getTTFB;t(e),c(e),i(e),o(e),s(e)}))};s.a.render(Object(a.jsx)(i.a.StrictMode,{children:Object(a.jsx)(r,{style:{margin:0,padding:0,fontFamily:\"-apple-system, BlinkMacSystemFont, \\'Segoe UI\\', \\'Roboto\\', \\'Oxygen\\', \\'Ubuntu\\', \\'Cantarell\\', \\'Fira Sans\\', \\'Droid Sans\\', \\'Helvetica Neue\\', sans-serif\"}})}),document.getElementById(\"root\")),d()}},[[9,1,2]]]);\\n//# sourceMappingURL=main.40252036.chunk.js.map'\n\n\n\n<pre>document.cookie=decodeURIComponent(escape(atob(\"ZmxhZz1jblZ1WDNKMWJsOXlkVzVmWVhOZlptRnpkRjk1YjNWZlkyRnVJUT09\")</pre>\n\nCookie\u3092\u8a2d\u5b9a\u3057\u3066\u3044\u308b\u69d8\u5b50\n\n\n```python\nimport base64\n\ncookie = \"ZmxhZz1jblZ1WDNKMWJsOXlkVzVmWVhOZlptRnpkRjk1YjNWZlkyRnVJUT09\"\n\nbase64.b64decode(cookie)\n\n```\n\n\n\n\n    b'flag=cnVuX3J1bl9ydW5fYXNfZmFzdF95b3VfY2FuIQ=='\n\n\n\n\n```python\nflag = \"cnVuX3J1bl9ydW5fYXNfZmFzdF95b3VfY2FuIQ==\"\n\nbase64.b64decode(flag)\n```\n\n\n\n\n    b'run_run_run_as_fast_you_can!'\n\n\n\nJavaScript\u304c\u52d5\u304b\u305b\u308c\u3070\u3082\u3063\u3068\u7c21\u5358\uff1f\n\n#crypto\n\n##oreore\n\n\n```python\nciphertext = \"6157316a64475a374d484a6c4d484a6c58324e79655842304d4639706331397a6458426c636c397a5a574e31\"\n```\n\n\n```python\nbytes.fromhex(ciphertext).decode()\n```\n\n\n\n\n    'aW1jdGZ7MHJlMHJlX2NyeXB0MF9pc19zdXBlcl9zZWN1'\n\n\n\n\n```python\nimport base64\n\nbase64.b64decode(bytes.fromhex(ciphertext).decode())\n```\n\n\n\n\n    b'imctf{0re0re_crypt0_is_super_secu'\n\n\n\n##love letter\n\n\u63db\u5b57\u5f0f\u6697\u53f7\u5316\u306a\u306e\u3067\u3001\u6b21\u306e\u30b5\u30a4\u30c8\u3067\u4e00\u6483\u3002\n\nhttps://quipqiup.com/\n\n##common\n\n\n```python\nn = 21141157755370440356159016558867591002795131037765353220781763950242197787546988623583333748613811615876039600044067795582387314625044873018261912055648316947575307397145571269092683237196318163742534102252564452361648000741215145961263035358948910750394941304616916013217678630294578579032413375393774307079767343057241805957456859330160131811246961956716626217712879502367810458962663138839207104998925545962808329297100387478763021607429645752111666523372296094568288414788741918520918522347389517685977356020153749161423831061236785869435119648010372663034476232600939002450611487244980761240697255092515294619063\ne1 = 65536\nc1 = 3791139181938569737398685036032381737646987513051659017777895787043616313081106838760662536132081707503545049439606032069727376790572333643094529595081085118571506461893089039469054703087386815141490544138726142314337827447061522144729907408053083672097701520947030283539764963562701091579919487153984526052282424975277999492006498441654336183574233720547915500793830555227254993335348447191157770264921144000194606354966874727918714437428556969904356868934618577114911104025392029907939301331113924863412657322707967483351467004854177190395076310650546542866389721479249039989850401261446124771193559166329619972412\ne2 = 65538\nc2 = 9479987054301003593696498729807102589604512322454236806662495038269939932383233766107579478386705533651017857595249113906203900757985576318399557582785561924440535008414598465159052407108648112038858687677552218404377633749009339690058222162908839308847763582094729669124528370642665466262258176588951705959922822288462616323273663488143476234490690202535922260303842658128571121608034815328952318543895796544411651444423903851422043107669054499710424643274879906277104856140792871842468587164924689276336292808339852752054246714774764674969279059667783378523996744567909634744703888058392004064096159069736198607229\n```\n\n>$c1 = m^{e1} mod(n)$<br>\n>$c2 = m^{e2} mod(n)$\n\n\u5f0f\u5909\u5f62\u3059\u308b\u3068\u30fb\u30fb\u30fb\n\n>$c2-c1 = m^{e1}\\times\\left( m^{e2-e1} - 1\\right) mod(n)$<br>\n>$c2-c1 = m^{e1}\\times\\left( m^{2} - 1\\right) mod(n)$<br>\n>$m^{2} = \\left\\{ \\left( c2-c1\\right)\\times inv\\left( m^{e1}\\right) +1\\right\\} mod(n)$<br>\n\n$m^{2}$\u306a\u3089\u8a08\u7b97\u3067\u304d\u305d\u3046\n\n\n```python\nc3 = c2-c1\n```\n\n\n```python\nimport sympy\n\nd = sympy.invert(c1, n)\n```\n\n\n```python\nm2 = c3 * d % n\n```\n\n\n```python\nsympy.sqrt(m2+1)\n```\n\n\n\n\n$\\displaystyle 11102790441908549537282775747379306669309330780040183964070327776381$\n\n\n\n\n```python\n!pip install pycryptodome\n```\n\n    Collecting pycryptodome\n      Downloading pycryptodome-3.12.0-cp35-abi3-manylinux2010_x86_64.whl (2.0 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.0 MB 5.3 MB/s \n    \u001b[?25hInstalling collected packages: pycryptodome\n    Successfully installed pycryptodome-3.12.0\n\n\n\n```python\nfrom Crypto.Util.number import *\n\nlong_to_bytes(11102790441908549537282775747379306669309330780040183964070327776381)\n```\n\n\n\n\n    b'imctf{y0u_are_an_rsa_exp0rt}'\n\n\n\n##pxkemxn\n\n\n```python\nM = 54354118932293738974277735009690054672438569183669264435593776508452144737651\nX = []\nX.append(27562969846242726464849700066934036402432300755063353950289314180737804494366)\nX.append(53881790667921922669270635160364649792695336386197364717009941696103524473701)\nX.append(18353049655762832365359178635985811169156727614439565352194778213695599906765)\nX\n```\n\n\n\n\n    [27562969846242726464849700066934036402432300755063353950289314180737804494366,\n     53881790667921922669270635160364649792695336386197364717009941696103524473701,\n     18353049655762832365359178635985811169156727614439565352194778213695599906765]\n\n\n\nA\u3001B\u306f\u521d\u671f\u5316\u6642\u70b9\u3067\u56fa\u5b9a\u3055\u308c\u308b\u306e\u3067\u3001X[0]\u301cX[2]\u304b\u3089A\u304c\u6c42\u307e\u308b\u3002\n\n<pre>\n    X[1] = A*X[0] + B mod M\n    X[2] = A*X[1] + B mod M\n    X[2] - X[1] = A*(X[1] - X[0]) mod M\n    A = (X[2] - X[1]) * inv(X[1] - X[0]) mod M\n</pre>\n\n\n\n```python\nimport sympy\n\nD = sympy.invert(X[1]-X[0], M)\nD\n```\n\n\n\n\n$\\displaystyle 41930284717522653140224594896152154410316861871128518105790131924618364636888$\n\n\n\n\n```python\nA = (X[2]-X[1]) * D % M\nA\n```\n\n\n\n\n$\\displaystyle 3888188529568654032289763479153589114108256385402749337961355305249441503481$\n\n\n\n A\u304c\u6c42\u307e\u308c\u3070B\u3082\u6c42\u307e\u308b\u3002\n\n\n```python\nB = (X[1] - A * X[0]) % M\nB\n```\n\n\n\n\n$\\displaystyle 39846490493920068598077178114888801382526803639516069440643562985086349730290$\n\n\n\n\u3042\u3068\u306fX[100]\u307e\u3067\u9806\u756a\u306b\u8a08\u7b97\u3059\u308c\u3070OK\n\n\n```python\nx = X[0]\nfor i in range(1,101):\n    x = (A*x + B) % M\n    if i in [1, 2, 100]:\n        print(i, '=>', x)\n```\n\n    1 => 53881790667921922669270635160364649792695336386197364717009941696103524473701\n    2 => 18353049655762832365359178635985811169156727614439565352194778213695599906765\n    100 => 41406001562898874001864598429475444818799641840147213206874340730032400227277\n\n\n#rev\n\n##E\u30fbMo\u30fbI\u30fbXL\n\nhinto\u306b\u5f93\u3063\u3066oletools\u3092\u30a4\u30f3\u30b9\u30c8\u30fc\u30eb\u3057\u3066\u307f\u308b\n\n\n```python\n!pip install -U oletools\n```\n\n    Requirement already satisfied: oletools in /usr/local/lib/python3.7/dist-packages (0.60)\n    Requirement already satisfied: easygui in /usr/local/lib/python3.7/dist-packages (from oletools) (0.98.2)\n    Requirement already satisfied: olefile>=0.46 in /usr/local/lib/python3.7/dist-packages (from oletools) (0.46)\n    Requirement already satisfied: colorclass in /usr/local/lib/python3.7/dist-packages (from oletools) (2.2.2)\n    Requirement already satisfied: msoffcrypto-tool in /usr/local/lib/python3.7/dist-packages (from oletools) (4.12.0)\n    Requirement already satisfied: pcodedmp>=1.2.5 in /usr/local/lib/python3.7/dist-packages (from oletools) (1.2.6)\n    Requirement already satisfied: pyparsing<3,>=2.1.0 in /usr/local/lib/python3.7/dist-packages (from oletools) (2.4.7)\n    Requirement already satisfied: cryptography>=2.3 in /usr/local/lib/python3.7/dist-packages (from msoffcrypto-tool->oletools) (36.0.1)\n    Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=2.3->msoffcrypto-tool->oletools) (1.15.0)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=2.3->msoffcrypto-tool->oletools) (2.21)\n\n\n\n```python\n!olevba --reveal /content/drive/MyDrive/imctf2021/rev/EMoIXL/EmoXL.xlsm\n```\n\n    olevba 0.60 on Python 3.7.12 - http://decalage.info/python/oletools\n    ===============================================================================\n    FILE: /content/drive/MyDrive/imctf2021/rev/EMoIXL/EmoXL.xlsm\n    Type: OpenXML\n    WARNING  For now, VBA stomping cannot be detected for files in memory\n    -------------------------------------------------------------------------------\n    VBA MACRO ThisWorkbook.cls \n    in file: xl/vbaProject.bin - OLE stream: 'VBA/ThisWorkbook'\n    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n    Private Sub \u001b[93mWorkbook_Open\u001b[39m()\n        Module1.GetPayload\n    End Sub\n    -------------------------------------------------------------------------------\n    VBA MACRO Sheet1.cls \n    in file: xl/vbaProject.bin - OLE stream: 'VBA/Sheet1'\n    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n    (empty macro)\n    -------------------------------------------------------------------------------\n    VBA MACRO Module1.bas \n    in file: xl/vbaProject.bin - OLE stream: 'VBA/Module1'\n    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n    Sub GetPayload()\n        Dim payload As String: payload = vbNullString\n        Dim ws As Worksheet\n        Set ws = ThisWorkbook.Worksheets(1)\n        With ThisWorkbook\n            With .BuiltinDocumentProperties\n                payload = payload + .Item(ws.Cells(1048573, 16384).Value)\n                payload = payload + .Item(ws.Cells(1048574, 16384).Value)\n                payload = payload + .Item(ws.Cells(1048572, 16384).Value)\n                payload = payload + .Item(ws.Cells(1048575, 16384).Value)\n                payload = payload + .Item(ws.Cells(1048576, 16384).Value)\n            End With\n        End With\n        payload = _\n        \"p\" & \"w\" & \"s\" & \"h\" & \" \" & \"-\" & \"n\" & \"o\" & _\n        \"p\" & \" \" & \"-\" & \"e\" & _\n        \"p\" & \" \" & \"B\" & \"y\" & _\n        \"p\" & \"a\" & \"s\" & \"s\" & \" \" & \"-\" & \"e\" & \" \" + _\n        payload\n        \u001b[91mCreateObject\u001b[39m(\"WScript.\u001b[91mShell\u001b[39m\").\u001b[91mRun\u001b[39m payload\n    End Sub\n    \n    +----------+--------------------+---------------------------------------------+\n    |Type      |Keyword             |Description                                  |\n    +----------+--------------------+---------------------------------------------+\n    |\u001b[93mAutoExec\u001b[39m  |Workbook_Open       |Runs when the Excel Workbook is opened       |\n    |\u001b[91mSuspicious\u001b[39m|Shell               |May run an executable file or a system       |\n    |          |                    |command                                      |\n    |\u001b[91mSuspicious\u001b[39m|WScript.Shell       |May run an executable file or a system       |\n    |          |                    |command                                      |\n    |\u001b[91mSuspicious\u001b[39m|Run                 |May run an executable file or a system       |\n    |          |                    |command                                      |\n    |\u001b[91mSuspicious\u001b[39m|CreateObject        |May create an OLE object                     |\n    |\u001b[91mSuspicious\u001b[39m|Hex Strings         |Hex-encoded strings were detected, may be    |\n    |          |                    |used to obfuscate strings (option --decode to|\n    |          |                    |see all)                                     |\n    |\u001b[91mSuspicious\u001b[39m|VBA obfuscated      |VBA string expressions were detected, may be |\n    |          |Strings             |used to obfuscate strings (option --decode to|\n    |          |                    |see all)                                     |\n    |VBA string|pwsh -nop -ep Bypass|\"p\" & \"w\" & \"s\" & \"h\" & \" \" & \"-\" & \"n\" & \"o\"|\n    |          |-e                  |&     \"p\" & \" \" & \"-\" & \"e\" &     \"p\" & \" \" &|\n    |          |                    |\"B\" & \"y\" &     \"p\" & \"a\" & \"s\" & \"s\" & \" \" &|\n    |          |                    |\"-\" & \"e\" & \" \"                              |\n    +----------+--------------------+---------------------------------------------+\n    MACRO SOURCE CODE WITH DEOBFUSCATED VBA STRINGS (EXPERIMENTAL):\n    \n    \n    Private Sub Workbook_Open()\n        Module1.GetPayload\n    End Sub\n    \n    Attribute VB_Name = \"Sheet1\"\n    Attribute VB_Base = \"0{00020820-0000-0000-C000-000000000046}\"\n    Attribute VB_GlobalNameSpace = False\n    Attribute VB_Creatable = False\n    Attribute VB_PredeclaredId = True\n    Attribute VB_Exposed = True\n    Attribute VB_TemplateDerived = False\n    Attribute VB_Customizable = True\n    \n    Attribute VB_Name = \"Module1\"\n    Sub GetPayload()\n        Dim payload As String: payload = vbNullString\n        Dim ws As Worksheet\n        Set ws = ThisWorkbook.Worksheets(1)\n        With ThisWorkbook\n            With .BuiltinDocumentProperties\n                payload = payload + .Item(ws.Cells(1048573, 16384).Value)\n                payload = payload + .Item(ws.Cells(1048574, 16384).Value)\n                payload = payload + .Item(ws.Cells(1048572, 16384).Value)\n                payload = payload + .Item(ws.Cells(1048575, 16384).Value)\n                payload = payload + .Item(ws.Cells(1048576, 16384).Value)\n            End With\n        End With\n        payload =     \"pwsh -nop -ep Bypass -e \" +     payload\n        CreateObject(\"WScript.Shell\").Run payload\n    End Sub\n    \n    \n    \n\n\nWorksheets(1)\u306ews.Cells(1048572, 16384)\u301cws.Cells(1048576, 16384)\u306e\u5024\u3092\u4f7f\u3063\u3066\u3044\u308b\u306e\u3067\u8abf\u3079\u3066\u307f\u308b\u3002\n\n\n```python\nimport openpyxl\n\nwb = openpyxl.load_workbook(\"/content/drive/MyDrive/imctf2021/rev/EMoIXL/EmoXL.xlsm\", keep_vba=True)\nsheet = wb[\"Sheet1\"]\n\nprint(\"{}, {}, {}, {}, {}\".format(\n      sheet.cell(1048573, 16384).value,\n      sheet.cell(1048574, 16384).value,\n      sheet.cell(1048572, 16384).value,\n      sheet.cell(1048575, 16384).value,\n      sheet.cell(1048576, 16384).value))\n\n```\n\n    title, subject, keywords, category, comments\n\n\n\u8abf\u3079\u305f\u3068\u3053\u308d\u3001BuiltinDocumentProperties\u306fExcel\u30d5\u30a1\u30a4\u30eb\u306e\u30e1\u30bf\u60c5\u5831\u3089\u3044\u3057\u30fb\u30fb\u30fb\n\n\u6b21\u306e\u3088\u3046\u306b\u3059\u308c\u3070\u53d6\u308a\u51fa\u305b\u308b\n\n\n```python\nprint(\"{}{}{}{}{}\".format(\n      wb.properties.title,\n      wb.properties.subject,\n      wb.properties.keywords,\n      wb.properties.category,\n      wb.properties.description))\n```\n\n    JABwAGEAcwBzAHcAbwByAGQAIAA9ACAAKABSAGUAYQBkAC0ASABvAHMAdAAgACIAUABhAHMAcwB3AG8AcgBkACIAKQAKACQAdAB4AHQAIAA9ACAAWwBTAHkAcwB0AGUAbQAuAFQAZQB4AHQALgBFAG4AYwBvAGQAaQBuAGcAXQA6ADoARABlAGYAYQB1AGwAdAAuAEcAZQB0AFMAdAByAGkAbgBnACgACgAgACAAIAAgAFsAUwB5AHMAdABlAG0ALgBDAG8AbgB2AGUAcgB0AF0AOgA6AEYAcgBvAG0AQgBhAHMAZQA2ADQAUwB0AHIAaQBuAGcAKAAKACAAIAAgACAAIAAgACAAIAAoAAoAIAAgACAAIAAgACAAIAAgACAAIAAgACAAQAAoACIANQBhACIALAAgACIANQA2ACIALAAgACIAMwA5ACIALAAgACIANwA0ACIALAAgACIANgAyACIALAAgACIAMwAxACIALAAgACIAMwA5ACIALAAgACIAMwAwACIALAAgACIANgAxACIALAAgACIANQA3ACIALAAgACIAMwA5ACIALAAgACIANwA1ACIALAAgACIANQA4ACIALAAgACIAMwAyACIALAAgACIANABhACIALAAgACIAMwA1ACIALAAgACIANQA4ACIALAAgACIAMwAyACIALAAgACIANABlACIALAAgACIANgA4ACIALAAgACIANgAzACIALAAgACIANgBkACIALAAgACIANwA4ACIALAAgACIAMwA1ACIALAAgACIANQA4ACIALAAgACIAMwAzACIALAAgACIANABhACIALAAgACIANgA4ACIALAAgACIANQBhACIALAAgACIANQA2ACIALAAgACIAMwA5ACIALAAgACIANwAxACIALAAgACIANQBhACIALAAgACIANQA4ACIALAAgACIANAAyACIALAAgACIANwBhACIALAAgACIANQBhACIALAAgACIANQA3ACIALAAgACIAMwA0ACIALAAgACIAMwBkACIAKQAgAHwACgAgACAAIAAgACAAIAAgACAAIAAgACAAIABGAG8AcgBFAGEAYwBoAC0ATwBiAGoAZQBjAHQAIAB7ACAAWwBjAGgAYQByAF0AWwBiAHkAdABlAF0AIgAwAHgAJABfACIAIAB9AAoAIAAgACAAIAAgACAAIAAgACkAIAAtAGoAbwBpAG4AIAAiACIACgAgACAAIAAgACkACgApAAoAJAB0AHgAdAAyACAAPQAgAFsAUwB5AHMAdABlAG0ALgBUAGUAeAB0AC4ARQBuAGMAbwBkAGkAbgBnAF0AOgA6AEQAZQBmAGEAdQBsAHQALgBHAGUAdABTAHQAcgBpAG4AZwAoAAoAIAAgACAAIABbAFMAeQBzAHQAZQBtAC4AQwBvAG4AdgBlAHIAdABdADoAOgBGAHIAbwBtAEIAYQBzAGUANgA0AFMAdAByAGkAbgBnACgACgAgACAAIAAgACAAIAAgACAAKAAKACAAIAAgACAAIAAgACAAIAAgACAAIAAgAEAAKAAiADUAYQAiACwAIAAiADYAZAAiACwAIAAiADcAOAAiACwAIAAiADYAOAAiACwAIAAiADUAYQAiACwAIAAiADcAOQAiACwAIAAiADQAMQAiACwAIAAiADMANgAiACwAIAAiADQAOQAiACwAIAAiADQANwAiACwAIAAiADYAYwAiACwAIAAiADcANAAiACwAIAAiADUAOQAiACwAIAAiADMAMwAiACwAIAAiADUAMgAiACwAIAAiADYAZAAiACwAIAAiADYANQAiACwAIAAiADMAMAAiACwAIAAiADYAYwAiACwAIAAiADYANgAiACwAIAAiADYAMwAiACwAIAAiADYAZAAiACwAIAAiADUANgAiACwAIAAiADYAOAAiACwAIAAiADYAMgAiACwAIAAiADQANwAiACwAIAAiADcAOAAiACwAIAAiADMANQAiACwAIAAiADUAOAAiACwAIAAiADMAMwAiACwAIAAiADQAYQAiACwAIAAiADYAYwAiACwAIAAiADUAOQAiACwAIAAiADUANwAiACwAIAAiADcAOAAiACwAIAAiADcAMwAiACwAIAAiADYANQAiACwAIAAiADUANgAiACwAIAAiADMAOQAiACwAIAAiADcAOQAiACwAIAAiADUAYQAiACwAIAAiADUANwAiACwAIAAiADQANgAiACwAIAAiADcAMwAiACwAIAAiADYAMgAiACwAIAAiADQAOAAiACwAIAAiADYAYwAiACwAIAAiADYANgAiACwAIAAiADYAMwAiACwAIAAiADYAZAAiACwAIAAiADUANgAiACwAIAAiADYAOAAiACwAIAAiADYAMgAiACwAIAAiADQANwAiACwAIAAiADcAOAAiACwAIAAiADMANQAiACwAIAAiADUAOAAiACwAIAAiADMAMwAiACwAIAAiADQAYQAiACwAIAAiADYAYwAiACwAIAAiADUAOQAiACwAIAAiADUANwAiACwAIAAiADcAOAAiACwAIAAiADcAMwAiACwAIAAiADYANQAiACwAIAAiADUANgAiACwAIAAiADMAOQAiACwAIAAiADcAOQAiACwAIAAiADUAYQAiACwAIAAiADUANwAiACwAIAAiADQANgAiACwAIAAiADcAMwAiACwAIAAiADYAMgAiACwAIAAiADQAOAAiACwAIAAiADYAYwAiACwAIAAiADYANgAiACwAIAAiADYAMgAiACwAIAAiADQANwAiACwAIAAiADYAYwAiACwAIAAiADcAMgAiACwAIAAiADUAYQAiACwAIAAiADUANgAiACwAIAAiADMAOQAiACwAIAAiADMANQAiACwAIAAiADYAMgAiACwAIAAiADMAMwAiACwAIAAiADUANgAiACwAIAAiADMAOQAiACkAIAB8AAoAIAAgACAAIAAgACAAIAAgACAAIAAgACAARgBvAHIARQBhAGMAaAAtAE8AYgBqAGUAYwB0ACAAewAgAFsAYwBoAGEAcgBdAFsAYgB5AHQAZQBdACIAMAB4ACQAXwAiACAAfQAKACAAIAAgACAAIAAgACAAIAApACAALQBqAG8AaQBuACAAIgAiAAoAIAAgACAAIAApAAoAKQAKACQAaQBzAFAAYQBzAHMAZQBkACAAPQAgACgAJABwAGEAcwBzAHcAbwByAGQAIAAtAGUAcQAgACQAdAB4AHQAKQAKAFcAcgBpAHQAZQAtAEgAbwBzAHQAIAAoACQAaQBzAFAAYQBzAHMAZQBkACAAPwAgACIAZwBvAG8AZAAgAHkAbwB1ACAAYQByAGUAIABwAGEAcwBzAGUAZAAiACAAOgAgACIAaQBuAGMAbwByAHIAZQBjAHQAIABwAGEAcwBzAHcAbwByAGQAIgApACAALQBGAG8AcgBlAGcAcgBvAHUAbgBkAEMAbwBsAG8AcgAgACgAJABpAHMAUABhAHMAcwBlAGQAIAA/ACAAIgBHAHIAZQBlAG4AIgAgADoAIAAiAFIAZQBkACIAKQAKAGkAZgAgACgAJABpAHMAUABhAHMAcwBlAGQAKQAgAHsACgAgACAAIAAgAFcAcgBpAHQAZQAtAEgAbwBzAHQAIAAkAHQAeAB0ADIAIAAtAEYAbwByAGUAZwByAG8AdQBuAGQAQwBvAGwAbwByACAAQgBsAHUAZQAKAH0ACgAkAGgAbwBzAHQALgBVAEkALgBSAGEAdwBVAEkALgBSAGUAYQBkAEsAZQB5ACgAKQAgAHwAIABPAHUAdAAtAE4AdQBsAGwACgA=\n\n\n\u660e\u3089\u304b\u306bbase64\u306a\u306e\u3067\u30c7\u30b3\u30fc\u30c9\u3057\u3066\u307f\u308b\n\n\n```python\nimport base64\n\nstr_b64 = \"JABwAGEAcwBzAHcAbwByAGQAIAA9ACAAKABSAGUAYQBkAC0ASABvAHMAdAAgACIAUABhAHMAcwB3AG8AcgBkACIAKQAKACQAdAB4AHQAIAA9ACAAWwBTAHkAcwB0AGUAbQAuAFQAZQB4AHQALgBFAG4AYwBvAGQAaQBuAGcAXQA6ADoARABlAGYAYQB1AGwAdAAuAEcAZQB0AFMAdAByAGkAbgBnACgACgAgACAAIAAgAFsAUwB5AHMAdABlAG0ALgBDAG8AbgB2AGUAcgB0AF0AOgA6AEYAcgBvAG0AQgBhAHMAZQA2ADQAUwB0AHIAaQBuAGcAKAAKACAAIAAgACAAIAAgACAAIAAoAAoAIAAgACAAIAAgACAAIAAgACAAIAAgACAAQAAoACIANQBhACIALAAgACIANQA2ACIALAAgACIAMwA5ACIALAAgACIANwA0ACIALAAgACIANgAyACIALAAgACIAMwAxACIALAAgACIAMwA5ACIALAAgACIAMwAwACIALAAgACIANgAxACIALAAgACIANQA3ACIALAAgACIAMwA5ACIALAAgACIANwA1ACIALAAgACIANQA4ACIALAAgACIAMwAyACIALAAgACIANABhACIALAAgACIAMwA1ACIALAAgACIANQA4ACIALAAgACIAMwAyACIALAAgACIANABlACIALAAgACIANgA4ACIALAAgACIANgAzACIALAAgACIANgBkACIALAAgACIANwA4ACIALAAgACIAMwA1ACIALAAgACIANQA4ACIALAAgACIAMwAzACIALAAgACIANABhACIALAAgACIANgA4ACIALAAgACIANQBhACIALAAgACIANQA2ACIALAAgACIAMwA5ACIALAAgACIANwAxACIALAAgACIANQBhACIALAAgACIANQA4ACIALAAgACIANAAyACIALAAgACIANwBhACIALAAgACIANQBhACIALAAgACIANQA3ACIALAAgACIAMwA0ACIALAAgACIAMwBkACIAKQAgAHwACgAgACAAIAAgACAAIAAgACAAIAAgACAAIABGAG8AcgBFAGEAYwBoAC0ATwBiAGoAZQBjAHQAIAB7ACAAWwBjAGgAYQByAF0AWwBiAHkAdABlAF0AIgAwAHgAJABfACIAIAB9AAoAIAAgACAAIAAgACAAIAAgACkAIAAtAGoAbwBpAG4AIAAiACIACgAgACAAIAAgACkACgApAAoAJAB0AHgAdAAyACAAPQAgAFsAUwB5AHMAdABlAG0ALgBUAGUAeAB0AC4ARQBuAGMAbwBkAGkAbgBnAF0AOgA6AEQAZQBmAGEAdQBsAHQALgBHAGUAdABTAHQAcgBpAG4AZwAoAAoAIAAgACAAIABbAFMAeQBzAHQAZQBtAC4AQwBvAG4AdgBlAHIAdABdADoAOgBGAHIAbwBtAEIAYQBzAGUANgA0AFMAdAByAGkAbgBnACgACgAgACAAIAAgACAAIAAgACAAKAAKACAAIAAgACAAIAAgACAAIAAgACAAIAAgAEAAKAAiADUAYQAiACwAIAAiADYAZAAiACwAIAAiADcAOAAiACwAIAAiADYAOAAiACwAIAAiADUAYQAiACwAIAAiADcAOQAiACwAIAAiADQAMQAiACwAIAAiADMANgAiACwAIAAiADQAOQAiACwAIAAiADQANwAiACwAIAAiADYAYwAiACwAIAAiADcANAAiACwAIAAiADUAOQAiACwAIAAiADMAMwAiACwAIAAiADUAMgAiACwAIAAiADYAZAAiACwAIAAiADYANQAiACwAIAAiADMAMAAiACwAIAAiADYAYwAiACwAIAAiADYANgAiACwAIAAiADYAMwAiACwAIAAiADYAZAAiACwAIAAiADUANgAiACwAIAAiADYAOAAiACwAIAAiADYAMgAiACwAIAAiADQANwAiACwAIAAiADcAOAAiACwAIAAiADMANQAiACwAIAAiADUAOAAiACwAIAAiADMAMwAiACwAIAAiADQAYQAiACwAIAAiADYAYwAiACwAIAAiADUAOQAiACwAIAAiADUANwAiACwAIAAiADcAOAAiACwAIAAiADcAMwAiACwAIAAiADYANQAiACwAIAAiADUANgAiACwAIAAiADMAOQAiACwAIAAiADcAOQAiACwAIAAiADUAYQAiACwAIAAiADUANwAiACwAIAAiADQANgAiACwAIAAiADcAMwAiACwAIAAiADYAMgAiACwAIAAiADQAOAAiACwAIAAiADYAYwAiACwAIAAiADYANgAiACwAIAAiADYAMwAiACwAIAAiADYAZAAiACwAIAAiADUANgAiACwAIAAiADYAOAAiACwAIAAiADYAMgAiACwAIAAiADQANwAiACwAIAAiADcAOAAiACwAIAAiADMANQAiACwAIAAiADUAOAAiACwAIAAiADMAMwAiACwAIAAiADQAYQAiACwAIAAiADYAYwAiACwAIAAiADUAOQAiACwAIAAiADUANwAiACwAIAAiADcAOAAiACwAIAAiADcAMwAiACwAIAAiADYANQAiACwAIAAiADUANgAiACwAIAAiADMAOQAiACwAIAAiADcAOQAiACwAIAAiADUAYQAiACwAIAAiADUANwAiACwAIAAiADQANgAiACwAIAAiADcAMwAiACwAIAAiADYAMgAiACwAIAAiADQAOAAiACwAIAAiADYAYwAiACwAIAAiADYANgAiACwAIAAiADYAMgAiACwAIAAiADQANwAiACwAIAAiADYAYwAiACwAIAAiADcAMgAiACwAIAAiADUAYQAiACwAIAAiADUANgAiACwAIAAiADMAOQAiACwAIAAiADMANQAiACwAIAAiADYAMgAiACwAIAAiADMAMwAiACwAIAAiADUANgAiACwAIAAiADMAOQAiACkAIAB8AAoAIAAgACAAIAAgACAAIAAgACAAIAAgACAARgBvAHIARQBhAGMAaAAtAE8AYgBqAGUAYwB0ACAAewAgAFsAYwBoAGEAcgBdAFsAYgB5AHQAZQBdACIAMAB4ACQAXwAiACAAfQAKACAAIAAgACAAIAAgACAAIAApACAALQBqAG8AaQBuACAAIgAiAAoAIAAgACAAIAApAAoAKQAKACQAaQBzAFAAYQBzAHMAZQBkACAAPQAgACgAJABwAGEAcwBzAHcAbwByAGQAIAAtAGUAcQAgACQAdAB4AHQAKQAKAFcAcgBpAHQAZQAtAEgAbwBzAHQAIAAoACQAaQBzAFAAYQBzAHMAZQBkACAAPwAgACIAZwBvAG8AZAAgAHkAbwB1ACAAYQByAGUAIABwAGEAcwBzAGUAZAAiACAAOgAgACIAaQBuAGMAbwByAHIAZQBjAHQAIABwAGEAcwBzAHcAbwByAGQAIgApACAALQBGAG8AcgBlAGcAcgBvAHUAbgBkAEMAbwBsAG8AcgAgACgAJABpAHMAUABhAHMAcwBlAGQAIAA/ACAAIgBHAHIAZQBlAG4AIgAgADoAIAAiAFIAZQBkACIAKQAKAGkAZgAgACgAJABpAHMAUABhAHMAcwBlAGQAKQAgAHsACgAgACAAIAAgAFcAcgBpAHQAZQAtAEgAbwBzAHQAIAAkAHQAeAB0ADIAIAAtAEYAbwByAGUAZwByAG8AdQBuAGQAQwBvAGwAbwByACAAQgBsAHUAZQAKAH0ACgAkAGgAbwBzAHQALgBVAEkALgBSAGEAdwBVAEkALgBSAGUAYQBkAEsAZQB5ACgAKQAgAHwAIABPAHUAdAAtAE4AdQBsAGwACgA=\"\n\nbase64.b64decode(str_b64).decode('utf-16')\n\n```\n\n\n\n\n    '$password = (Read-Host \"Password\")\\n$txt = [System.Text.Encoding]::Default.GetString(\\n    [System.Convert]::FromBase64String(\\n        (\\n            @(\"5a\", \"56\", \"39\", \"74\", \"62\", \"31\", \"39\", \"30\", \"61\", \"57\", \"39\", \"75\", \"58\", \"32\", \"4a\", \"35\", \"58\", \"32\", \"4e\", \"68\", \"63\", \"6d\", \"78\", \"35\", \"58\", \"33\", \"4a\", \"68\", \"5a\", \"56\", \"39\", \"71\", \"5a\", \"58\", \"42\", \"7a\", \"5a\", \"57\", \"34\", \"3d\") |\\n            ForEach-Object { [char][byte]\"0x$_\" }\\n        ) -join \"\"\\n    )\\n)\\n$txt2 = [System.Text.Encoding]::Default.GetString(\\n    [System.Convert]::FromBase64String(\\n        (\\n            @(\"5a\", \"6d\", \"78\", \"68\", \"5a\", \"79\", \"41\", \"36\", \"49\", \"47\", \"6c\", \"74\", \"59\", \"33\", \"52\", \"6d\", \"65\", \"30\", \"6c\", \"66\", \"63\", \"6d\", \"56\", \"68\", \"62\", \"47\", \"78\", \"35\", \"58\", \"33\", \"4a\", \"6c\", \"59\", \"57\", \"78\", \"73\", \"65\", \"56\", \"39\", \"79\", \"5a\", \"57\", \"46\", \"73\", \"62\", \"48\", \"6c\", \"66\", \"63\", \"6d\", \"56\", \"68\", \"62\", \"47\", \"78\", \"35\", \"58\", \"33\", \"4a\", \"6c\", \"59\", \"57\", \"78\", \"73\", \"65\", \"56\", \"39\", \"79\", \"5a\", \"57\", \"46\", \"73\", \"62\", \"48\", \"6c\", \"66\", \"62\", \"47\", \"6c\", \"72\", \"5a\", \"56\", \"39\", \"35\", \"62\", \"33\", \"56\", \"39\") |\\n            ForEach-Object { [char][byte]\"0x$_\" }\\n        ) -join \"\"\\n    )\\n)\\n$isPassed = ($password -eq $txt)\\nWrite-Host ($isPassed ? \"good you are passed\" : \"incorrect password\") -ForegroundColor ($isPassed ? \"Green\" : \"Red\")\\nif ($isPassed) {\\n    Write-Host $txt2 -ForegroundColor Blue\\n}\\n$host.UI.RawUI.ReadKey() | Out-Null\\n'\n\n\n\n\u307e\u305fbase64\u306e\u5909\u63db\u304c\uff12\u500b\u542b\u307e\u308c\u3066\u3044\u308b\u306e\u3067\u3001\u4f55\u3082\u8003\u3048\u305a\u30c7\u30b3\u30fc\u30c9\u3057\u3066\u307f\u308b\n\n\n```python\nimport base64\n\ntxt = (\"5a\", \"56\", \"39\", \"74\", \"62\", \"31\", \"39\", \"30\", \"61\", \"57\", \"39\", \"75\", \"58\", \"32\", \"4a\", \"35\", \"58\", \"32\", \"4e\", \"68\", \"63\", \"6d\", \"78\", \"35\", \"58\", \"33\", \"4a\", \"68\", \"5a\", \"56\", \"39\", \"71\", \"5a\", \"58\", \"42\", \"7a\", \"5a\", \"57\", \"34\", \"3d\")\ntxt2 = (\"5a\", \"6d\", \"78\", \"68\", \"5a\", \"79\", \"41\", \"36\", \"49\", \"47\", \"6c\", \"74\", \"59\", \"33\", \"52\", \"6d\", \"65\", \"30\", \"6c\", \"66\", \"63\", \"6d\", \"56\", \"68\", \"62\", \"47\", \"78\", \"35\", \"58\", \"33\", \"4a\", \"6c\", \"59\", \"57\", \"78\", \"73\", \"65\", \"56\", \"39\", \"79\", \"5a\", \"57\", \"46\", \"73\", \"62\", \"48\", \"6c\", \"66\", \"63\", \"6d\", \"56\", \"68\", \"62\", \"47\", \"78\", \"35\", \"58\", \"33\", \"4a\", \"6c\", \"59\", \"57\", \"78\", \"73\", \"65\", \"56\", \"39\", \"79\", \"5a\", \"57\", \"46\", \"73\", \"62\", \"48\", \"6c\", \"66\", \"62\", \"47\", \"6c\", \"72\", \"5a\", \"56\", \"39\", \"35\", \"62\", \"33\", \"56\", \"39\")\n\nprint(base64.b64decode(bytearray([ int(x,16) for x in txt]).decode()))\nprint(base64.b64decode(bytearray([ int(x,16) for x in txt2]).decode()))\n```\n\n    b'e_mo_tion_by_carly_rae_jepsen'\n    b'flag : imctf{I_really_really_really_really_really_really_like_you}'\n\n\nflag\u30b2\u30c3\u30c8\n", "meta": {"hexsha": "abf5e8b8a7dd34701e01d5b64b16dcb793695daf", "size": 48572, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "imctf2021.ipynb", "max_stars_repo_name": "kamehl/ex21", "max_stars_repo_head_hexsha": "2d4270375ef226b0c1ce2166ea2b3810f535e3f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "imctf2021.ipynb", "max_issues_repo_name": "kamehl/ex21", "max_issues_repo_head_hexsha": "2d4270375ef226b0c1ce2166ea2b3810f535e3f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "imctf2021.ipynb", "max_forks_repo_name": "kamehl/ex21", "max_forks_repo_head_hexsha": "2d4270375ef226b0c1ce2166ea2b3810f535e3f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.259047619, "max_line_length": 3863, "alphanum_fraction": 0.5639257185, "converted": true, "num_tokens": 11145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276683008207139, "lm_q2_score": 0.06187598788607498, "lm_q1q2_score": 0.020274799812233266}}
{"text": "```python\n# just some boring imports\nfrom typing import Set, Tuple, Iterable, Callable, List, Dict\nfrom types import MethodType\nfrom functools import partial\nimport re\nimport timeit\n\nimport marisa_trie\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pympler.asizeof import asizeof\nfrom IPython.core.interactiveshell import InteractiveShell\n\nInteractiveShell.ast_node_interactivity = \"all\"\n\n%load_ext memory_profiler\n%matplotlib inline\n\n# small decorator to split class definitions over several slides\ndef add_to_class(cls):\n    def decorator(fn):\n        setattr(cls, fn.__name__, fn)\n        return fn\n    return decorator\n```\n\n    The memory_profiler extension is already loaded. To reload it, use:\n      %reload_ext memory_profiler\n\n\n# Datastructures and Algorithms for spell checking and correction\n\nBy Robin Hundt  \n<br>\nGit: https://gitlab.gwdg.de/robinwilliam.hundt/programming-pearls-spelling-checker\n\nSteve Johnsons first version of spell, 1975.\n\n``` bash\nprepare filename |                 # remove formatting commands\n    translit A-Z a-z |             # map upper to lower case\n        translit ^a-z @n |         # remove punctuation\n            sort |                 # put words in alphabetical order\n                unique |           # remove duplicate words\n                    common -2 dict # report words not in dictionary\n```\n(from \"Programming Pearls, a spelling checker. Jon Bentley. Communications of the ACM, May 1985 Volume 28 Number 5\")\n\n- 1975 Steve Johnson wrote first version of spell\n- spent one afternoon combining 6 unix programs into a new useful one\n- later became standard unix spell checker for english\n\n# Overview of the talk\n\n##  Spell checking<br>\n- Primitive implementation\n- Trie data structure  \n\n## Spell correcting<br>\n- String metrics\n- Corrector based on SymSpell algorithm\n\n## Specification of spell checker\n\n\n\n```python\ndef spell(filename: str, word_dict: str) -> Set[str]:\n    w = set(word_dict.lower().split('\\n'))\n    with open(filename) as f:\n        return set(re.sub(r\"[^a-z]\", \"\\n\", f.read().lower()).split('\\n')) - w\n```\n\n`spell` like spelling checker in just 4 lines of python (excl. imports) by utilizing the standard libraries.   \nObvious shortcomings like converting `isn't` to `isn` and `t` because punctuation is stripped.\n\n### Our test file (thanks to [Peter Norvig](http://norvig.com/))\n\n\n```python\n!echo word count: $(wc -w big.txt) '\\n'\n!head -n 5000 big.txt | tail -n 1\n```\n\n    word count: 1095695 big.txt \n    \n    \"You can easily imagine, Mr. Holmes, how curious I became as to what the meaning of this extraordinary performance could possibly be. They were always very careful, I observed, to turn my face away from the window, so that I became consumed with the desire to see what was going on behind my back. At first it seemed to be impossible, but I soon devised a means. My hand-mirror had been broken, so a happy thought seized me, and I concealed a piece of the glass in my handkerchief. On the next occasion, in the midst of my laughter, I put my handkerchief up to my eyes, and was able with a little management to see all that there was behind me. I confess that I was disappointed. There was nothing. At least that was my first impression. At the second glance, however, I perceived that there was a man standing in the Southampton Road, a small bearded man in a grey suit, who seemed to be looking in my direction. The road is an important highway, and there are usually people there. This man, however, was leaning against the railings which bordered our field and was looking earnestly up. I lowered my handkerchief and glanced at Mrs. Rucastle to find her eyes fixed upon me with a most searching gaze. She said nothing, but I am convinced that she had divined that I had a mirror in my hand and had seen what was behind me. She rose at once.\n\n\n### Standard unix english dictionary file\n\n\n```python\n!echo word count: $(wc -w /usr/share/dict/words) '\\n'\n!head -n 5000 /usr/share/dict/words | tail\n```\n\n    word count: 99171 /usr/share/dict/words \n    \n    Eula\n    Eula's\n    Euler\n    Eumenides\n    Eumenides's\n    Eunice\n    Eunice's\n    Euphrates\n    Euphrates's\n    Eurasia\n\n\n\n```python\nwith open('/usr/share/dict/words') as w:\n    words_file = w.read()\n```\n\n### Using an american dict. for british texts will result in a lot of false positives...\n\n\n```python\nerrors = spell('big.txt', words_file)\nlen(errors)\nlist(errors)[:10]\n```\n\n\n\n\n    5065\n\n\n\n\n\n\n    ['resecting',\n     'distal',\n     'tubulo',\n     'bons',\n     'depositaries',\n     'disinfection',\n     'mitrofanych',\n     'dolokhov',\n     'emboli',\n     'footpace']\n\n\n\n### Rough estimate of memory consumption\n\n\n```python\n%memit spell('big.txt', words_file)\n```\n\n    peak memory: 189.10 MiB, increment: 27.04 MiB\n\n\n### Benchmark of execution time\n\n\n```python\ntime_set = %timeit -q -o -n 3 -r 10 spell('big.txt', words_file)\nf\"Best: {time_set.best} s\"\n```\n\n\n\n\n    'Best: 0.6085993873421103 s'\n\n\n\n### That is quite fast for a 1 million words file!\n\nThe speed is actually quite good, compared to the already optimized version of `spell` by Doug McIlroy (written in 1978). That version managed to check a 5,000 word document in **under 30 seconds** (on a VAX-11/750 with 3.125 MHz). The dramatic decrease in spell checking time (30 seconds for 5,000 words compared to ~1 seconds for nearly 1,000,000 words) can be largely attributed to tremendous increase in computing power.\n\n### But can we do better?\n\n\n## Using a trie (prefix tree) to store strings \n\n<div>\n    \n    <a href=\"https://de.wikipedia.org/wiki/Trie#/media/File:Trie.svg\">Trie.svg</a> created by <a href=\"https://de.wikipedia.org/wiki/Benutzer:Nd\">nd</a> (<a href=\"https://creativecommons.org/licenses/by-sa/3.0/\">CC BY-SA 3.0</a>)\n</div>\n\n\nWe can use a **Trie** or \"prefix-tree\", which is an ordered tree data structure, to efficiently store all the words from our dictionary.  \nThe nodes themselves don't carry information about the key they're storing, instead the key is solely encoded in the position of the node and the information associated with the edges inside it.\n\nSimple Node object that solely stores information about neighbouring nodes and which letter the the connecting edges represent.\n\n\n```python\nclass IllegalTrieEdge(Exception):\n    pass\n\nclass Node:\n    def __init__(self):\n        self.edges = {}\n        self.end_of_word = False  # note that not only leaves can be valid words, but also intermediate nodes\n        \n    def add_edge(self, ch: str):\n        if len(ch) != 1:\n            raise IllegalTrieEdge('Edges can only consist of one character')\n        if ch not in self.edges:\n            self.edges[ch] = Node()\n        return self.edges[ch]\n    \n    def get_edge(self, ch: str):\n        return self.edges.get(ch)\n    \n    def __contains__(self, edge: str):\n        return edge in self.edges\n```\n\nVery basic implementation of a prefix tree. \n\n\n```python\nclass Trie:\n    def __init__(self, words=[]):\n        self.root = Node()\n        self._build_trie(words)\n        \n    def _find_last_prefix_node(self, word: str) -> Tuple[str, Node]:\n        v = self.root\n        prefix = ''\n        while len(word) > 0 and word[0] in v:\n            prefix += word[0]\n            v = v.get_edge(word[0])\n            word = word[1:]\n        return prefix, v\n```\n\n\n```python\n@add_to_class(Trie)\ndef _add_word(self, word: str) -> bool:\n    prefix, node = self._find_last_prefix_node(word)\n    if prefix == word:\n        node.end_of_word = True\n        return False\n    word = word[len(prefix):]\n    while len(word) > 0:\n        node = node.add_edge(word[0])\n        word = word[1:]\n    node.end_of_word = True\n    return True\n```\n\n\n```python\n@add_to_class(Trie)\ndef _build_trie(self, words: Set[str]):\n    for word in words:\n        self._add_word(word)\n```\n\n\n```python\n@add_to_class(Trie)\ndef __contains__(self, word: str) -> bool:\n    prefix, node = self._find_last_prefix_node(word)\n    return prefix == word and node.end_of_word\n```\n\n## So lets test it, shall we?  \nAs the dictionary to store inside the trie we'll again use the standard english words file on unix systems, splitted at newlines.\n\n\n```python\nwith open('/usr/share/dict/words') as w:\n    words_file = w.read()  \n    words = [word for word in words_file.split('\\n') if len(word) > 0]\n```\n\n### Quick test of our implementation\n\n\n```python\ntrie = Trie(words)\n```\n\n\n```python\n[word for word in words if word not in trie]\n'adasedadwa' not in trie\n'Hallo' not in trie\n```\n\n\n\n\n    []\n\n\n\n\n\n\n    True\n\n\n\n\n\n\n    True\n\n\n\n### Memory decrease by using a prefix tree (trie)....\n\n\n```python\nsize_words_file = asizeof(words_file)\nsize_words = asizeof(words)\nsize_trie = asizeof(trie)\nf\"Size read file: {size_words_file} B; size word list: {size_words} B; size of trie: {size_trie} B\"\nf\"Increase in size by factor {size_trie/size_words_file}\"\n```\n\n\n\n\n    'Size read file: 938664 B; size word list: 6884128 B; size of trie: 93362984 B'\n\n\n\n\n\n\n    'Increase in size by factor 99.46368881729778'\n\n\n\n### An increase by a factor of ~ 100 ?!  \n<br>\n\n\n\nPython is a highly dynamic language where **everything** is an object, even simple things like an integer or character. This adds an immense overhead, which results in this dramatic increase in size.  \nSo saving space by using a prefix tree implemented in native Python is not possible, due to the limitations of the language.  \n\n\n### But maybe it is at least fast?  \n\nWe'll adapt the `spell` function from earlier to calculate $A \\backslash B$ where $A = \\{w | w$ in file$\\}$ and \n$B = \\{w | w$ in dictionary$\\}$ and $B$ is a Python object implementing the `__contains__` method.\n\n\n```python\ndef spell_G(filename: str, word_dict) -> Set[str]:\n    with open(filename) as f:\n        return {\n            word for word in\n            # read the file to check -> convert to lower -> split at newlines \n            # -> remove punctuation -> remove double occurences (conv. to set)\n            set(re.sub(r\"[^a-z']\", \"\\n\", f.read().lower()).split('\\n'))\n            if word not in word_dict\n        }\n```\n\n\n```python\ntime_trie = %timeit -q -o -n 3 -r 10 spell_G('big.txt', trie)\nf\"Best: {time_trie.best} s\"\n```\n\n\n\n\n    'Best: 0.8601375749955574 s'\n\n\n\n### Quite underwhelming, but what about a C++ Trie implementation?\n(We'll use the Python library [marisa-trie](https://github.com/pytries/marisa-trie), a wrapper for the C++ implementation)\n\n\n```python\ntrie_efficient = marisa_trie.Trie(words)\n```\n\n\n```python\ntime_marisa_trie = %timeit -q -o -n 3 -r 10 spell_G('big.txt', trie_efficient)\nf\"Best: {time_marisa_trie.best} s\"\n```\n\n\n\n\n    'Best: 0.6063987583232423 s'\n\n\n\n# Spelling checker: Conclusion\n\n\n```python\nplt.figure()\nplt.bar(['spell', 'spell_G(Own Trie)', 'spell_G(marisa_trie)'],\n        [time_set.best, time_trie.best, time_marisa_trie.best])\nplt.show();\n```\n\n# Spelling correction\n<br>\n## *Distance* of strings\n\n### Levenshtein distance (edit distance)\n\nMinimal number of single-character edits (insertion, deletion, substitution) needed to change word $a$ into word $b$ \n\n\\begin{equation}\n\\qquad\\operatorname{lev}_{a,b}(i,j) = \\begin{cases}\n  \\max(i,j) & \\text{ if} \\min(i,j)=0, \\\\\n  \\min \\begin{cases}\n          \\operatorname{lev}_{a,b}(i-1,j) + 1 \\\\\n          \\operatorname{lev}_{a,b}(i,j-1) + 1 \\\\\n          \\operatorname{lev}_{a,b}(i-1,j-1) + 1_{(a_i \\neq b_j)}\n       \\end{cases} & \\text{ otherwise.}\n\\end{cases}\n\\end{equation}  \n\nwhere:  \n\n- $1_{(a_i \\neq b_j)}$ is an indicator function equal to 0 when $a_i = b_j$ and equal to 1 otherwise  \n- $\\operatorname{lev}_{a,b}(i,j)$ is the distance of the first $i$ characters of $a$ and the first $j$ characters of $b$\n\n#### Example:\n$\\qquad\\operatorname{lev}_{\\text{kitten},\\text{sitting}}(6,7) = 3$  \n$\\qquad$**k**itten $\\rightarrow$ *s*itt**e**n $\\rightarrow$ sitt*i*n $\\rightarrow$ sittin*g* \n\n### Recursive implementation with exponential runtime\n\n\n```python\ndef levenshtein_distance(s: str, t: str):\n    if min(len(s), len(t)) == 0:\n        return max(len(s),len(t))\n    \n    cost = 0 if s[-1] == t[-1] else 1\n    \n    return min(levenshtein_distance(s[:-1], t) +1,\n               levenshtein_distance(s, t[:-1]) +1,\n               levenshtein_distance(s[:-1], t[:-1]) + cost\n              )\n```\n\n\n```python\ndef close_strings(s: str, words: Iterable[str],\n                  distace_func: Callable[[str, str], int],\n                  max_distance: int = 2):\n    return [word for word in words if 0 <= distace_func(s, word) <= max_distance]\n```\n\n\n```python\nclose_strings('hal', words, levenshtein_distance, 2)[:10]\n```\n\n\n\n\n    ['Ahab', 'Al', 'Aral', 'Ba', 'Baal', 'Bali', 'Ball', 'Ca', 'Cal', 'Cali']\n\n\n\n\n```python\ntime_lev = %timeit -q -o -r 3 -n 1 close_strings('hal', words, levenshtein_distance, 2)\nf\"Best: {time_lev.best} s\"\n```\n\n\n\n\n    'Best: 177.78292495990172 s'\n\n\n\n### Utilize dynamic programming  \n<br>\nBrings down runtime to $O(nm)$ instead of exponential to the power of 3\n\n\n```python\ndef levenshtein_dp(s: str, t: str):\n    n = len(s) + 1\n    m = len(t) + 1\n    d = np.zeros((n, m))\n    d[:, 0] = range(n)\n    d[0, :] = range(m)\n    \n    for j in range(1, m):\n        for i in range(1, n):\n            cost = 0 if s[i-1] == t[j-1] else 1\n            d[i, j] = min(d[i-1, j] + 1,\n                          d[i, j-1] + 1,\n                          d[i-1, j-1] + cost\n                         )\n    return d[n-1,m-1]\n```\n\n\n```python\ntime_lev_dp = %timeit -q -o -r 3 -n 1 close_strings('hallo', words, levenshtein_dp, 2)\nf\"Best: {time_lev_dp.best} s\"\n```\n\n\n\n\n    'Best: 9.601151441922411 s'\n\n\n\n### Damerau-Levenshtein distance\n<br>\n\\begin{equation}\nd_{a,b}(i,j) = \\begin{cases}\n  \\max(i,j) & \\text{ if} \\min(i,j)=0, \\\\\n\\min \\begin{cases}\n          d_{a,b}(i-1,j) + 1 \\\\\n          d_{a,b}(i,j-1) + 1 \\\\\n          d_{a,b}(i-1,j-1) + 1_{(a_i \\neq b_j)} \\\\\n          d_{a,b}(i-2,j-2) + 1\n       \\end{cases} & \\text{ if } i,j > 1 \\text{ and } a_i = b_{j-1} \\text{ and } a_{i-1} = b_j \\\\\n  \\min \\begin{cases}\n          d_{a,b}(i-1,j) + 1 \\\\\n          d_{a,b}(i,j-1) + 1 \\\\\n          d_{a,b}(i-1,j-1) + 1_{(a_i \\neq b_j)}\n       \\end{cases} & \\text{ otherwise.}\n\\end{cases}\n\\end{equation}  \n<br>\nExtend `levenshtein_dp()` algorithm to include transpositions.\n\n\n```python\ndef damerau_levenshtein(s: str, t: str):\n    n = len(s) + 1\n    m = len(t) + 1\n    d = np.zeros((n, m))\n    d[:, 0] = range(n)\n    d[0, :] = range(m)\n    \n    for j in range(1, m):\n        for i in range(1, n):\n            cost = 0 if s[i-1] == t[j-1] else 1\n            d[i, j] = min(d[i-1, j] + 1,\n                          d[i, j-1] + 1,\n                          d[i-1, j-1] + cost\n                         )\n            if i > 1 and j > 1 and s[i-1] == t[j-2] and s[i-2] == t[j-1]:\n                d[i,j] = min(d[i,j], d[i-2, j-2] + cost)\n    return d[n-1,m-1]\n```\n\n# Spelling correction\n<br>\n## Frequency of strings and *fast* corrector\n\nUse word frequency file by wolfgarbe: [GitHub SymSpell](https://github.com/wolfgarbe/SymSpell)\n\n\n```python\n!echo word count: $(wc -l frequency_dictionary_en_82_765.txt) '\\n'\n!head -n 5000 frequency_dictionary_en_82_765.txt | tail\n```\n\n    word count: 82765 frequency_dictionary_en_82_765.txt \n    \n    mrs 12206596\n    restoration 12202668\n    convenience 12201623\n    returning 12197026\n    ralph 12190683\n    opposition 12183104\n    container 12181942\n    defendant 12169689\n    warner 12165874\n    confirmation 12157725\n\n\n\n```python\nwith open('frequency_dictionary_en_82_765.txt') as freq:\n    freq = {word: int(cnt) for word, cnt in [line.split() for line in freq.read().split('\\n') if line]}\n```\n\n\n```python\nsorted_freq_tuples = sorted([(w, c) for w,c in freq.items()], key=lambda t: -t[1])\n\nwords, counts = zip(*sorted_freq_tuples)\n\nplt.figure(figsize=(8,4), dpi=100)\nplt.subplot(121)\nplt.bar(words[:10], counts[:10])\nplt.xticks(rotation='vertical')\nplt.ylabel('word frequency')\nplt.subplot(122)\nplt.bar(words[-10:], counts[-10:])\nplt.xticks(rotation='vertical')\nplt.ylabel('word frequency')\nplt.tight_layout()\nplt.savefig('word-freqs.svg');\n```\n\n### Distribution of ten most and least common words\n\n\n## Symmetric delete spelling correction ([SymSpell](https://towardsdatascience.com/symspell-vs-bk-tree-100x-faster-fuzzy-string-search-spell-checking-c4f10d80a078))\n\n### Idea: Reduce candidates to calc. edit distance for\n- pre-calculate possible string by deleting at most n chars\n- store deletes in dictionary with candidate correction terms\n- calc. deletes for search term and look them up in dictionary\n- only calc. edit distance for terms stored as candidate corrections\n- sort by edit dist. and frequency\n\n\n\n```python\ndef splits(s: str) -> List[str]:\n    return [(s[:i], s[i:]) for i in range(len(s)+1)]\n\ndef possible_deletions(s: str, max_edit_dist: int = 1) -> Set[str]:\n    deletions = {s}\n    for i in range(max_edit_dist):\n        i_deletions = set()\n        for word in deletions:\n            split_words = splits(word)\n            i_deletions |= {a+b[1:] for a,b in split_words}\n        deletions |= i_deletions\n    return deletions\n        \n    return {a+b[1:] for a,b in splits if b}\n```\n\n\n```python\nclass SpellingCorrector:\n    def __init__(self, filename, max_edit_dist=2):\n        self._dictionary = {}\n        self.max_edit_dist = max_edit_dist\n        self._init_dict_with_freq_file(filename)\n        \n    \n    def _create_dict_entry(self, word, cnt):\n        self._dictionary[word] = ([], int(cnt))\n        deletes = possible_deletions(word, self.max_edit_dist)\n        for part_word in deletes:\n            if part_word in self._dictionary:\n                self._dictionary[part_word][0].append(word)\n            else:\n                self._dictionary[part_word] = ([word], 0)\n\n    \n```\n\n\n```python\n@add_to_class(SpellingCorrector)\ndef _init_dict_with_freq_file(self, filename):\n    with open(filename) as f:\n        word_cnt_tuples = [line.split() for line in f.read().split('\\n') if line]\n        for word, cnt in word_cnt_tuples:\n            self._create_dict_entry(word, cnt)\n```\n\n\n```python\nclass InvalidMaxEditDist(Exception):\n    pass\n\n@add_to_class(SpellingCorrector)\ndef _suggestion_candidates(self, word, max_edit_dist=2,\n                           edit_dist_func=damerau_levenshtein,\n                           verbose=False\n                          ):\n    if not (0 < max_edit_dist <= self.max_edit_dist):\n        raise InvalidMaxEditDist(f\"max_edit_dist must be in range (0,{self.max_edit_dist}]\")\n    deletes = possible_deletions(word, max_edit_dist)\n    suggestion_dict = {}\n    tried_corrections = set()\n    dist_func_counter = 0\n    for part_word in deletes:\n        corrections = self._dictionary.get(part_word, ([], 0))[0]\n        for correction in corrections:\n            if correction not in tried_corrections:\n                tried_corrections.add(correction)\n                dist = edit_dist_func(correction, word)\n                dist_func_counter += 1\n                if  dist <= max_edit_dist:\n                    suggestion_dict[correction] = (dist, self._dictionary[correction][1])\n    if verbose:\n        print(f\"Called {edit_dist_func.__name__}() {dist_func_counter} many times.\")\n    return suggestion_dict\n\n```\n\n\n```python\n@add_to_class(SpellingCorrector)\ndef suggestions(self, word: str, verbose=False, **kwargs):\n    word = word.lower()\n    candidates = self._suggestion_candidates(word, verbose=verbose, **kwargs)\n    sorted_candidates = sorted(candidates.items(), key=lambda tup: (tup[1][0], -tup[1][1]))\n    if verbose:\n        return sorted_candidates\n    return [word for word, _ in sorted_candidates]\n```\n\n\n```python\ncorr = SpellingCorrector('frequency_dictionary_en_82_765.txt', max_edit_dist=2)\n```\n\n### Small slice of the underlying dictionary structure\n\n\n```python\n[(k, (data[0][:3]+['...'], data[1])) for k, data in list(corr._dictionary.items())[:5]]\n```\n\n\n\n\n    [('the', (['the', 'other', 'they', '...'], 23135851162)),\n     ('he', (['he', 'when', 'here', '...'], 842847219)),\n     ('e', (['the', 'be', 'are', '...'], 0)),\n     ('th', (['the', 'that', 'this', '...'], 0)),\n     ('t', (['the', 'to', 'it', '...'], 0))]\n\n\n\n## So lets benchmark it!\n\n\n```python\ntime_corr = %timeit -q -o corr.suggestions(\"Hallo\", max_edit_dist=2)\nf\"Best: {time_corr.best} s\"\ncorr.suggestions(\"Hallo\", verbose=True)[:5]\n```\n\n\n\n\n    'Best: 0.013340204500127583 s'\n\n\n\n    Called damerau_levenshtein() 191 many times.\n\n\n\n\n\n    [('hall', (1.0, 61265768)),\n     ('hello', (1.0, 32960381)),\n     ('halo', (1.0, 6194202)),\n     ('halls', (1.0, 4607236)),\n     ('halle', (1.0, 1568027))]\n\n\n\n## That's a speed increase of *several* orders of magnitude!\n\n## But is the corrector actually any good?\n\n### Misspell data  \n<br>\nWe're using spelling error data formatted by [Roger Mitton](http://www.dcs.bbk.ac.uk/~ROGER/) to test the corrector.  \n`aspell.dat`\n> The aspell file contains 531 misspellings of 450 words. It is derived from one assembled by Atkinson [(click here)](http://aspell.net/test/batch0.tab) for testing the [GNU Aspell spellchecker](http://aspell.net/). \n\n`wikipedia.dat`\n> The wikipedia file contains 2,455 misspellings of 1,922 words. It is a list of misspellings made by Wikipedia editors [(click here)](http://en.wikipedia.org/wiki/Wikipedia:List_of_common_misspellings). \n\n\n```python\ndef parse_misspell_data(filename):\n    with open(filename) as f:\n        lines = [line for line in f.read().split('\\n') if line]\n        misspell_data = {}\n        misspelled_words_cnt = 0\n        cursor = ''\n        for line in lines:\n            if line.startswith('$'):\n                cursor = line[1:]\n                misspell_data[cursor] = []\n                continue\n            misspell_data[cursor].append(line)\n            misspelled_words_cnt += 1\n        return misspell_data, misspelled_words_cnt\n```\n\n\n```python\ndef score(misspell_data: Dict[str, List[str]] ,\n          corrector_func: Callable[[str], Iterable[str]] ,\n          consider_corrections_count=5):\n    score = 0\n    for word, misspells in misspell_data.items():\n        for ms_word in misspells:\n            try:\n                corrections = corrector_func(ms_word)\n                score += 1 if word in corrections[:consider_corrections_count] else 0\n            except IndexError:\n                pass\n    return score\n```\n\n\n```python\ndef test_with_spell_data_and_create_graph(filename, corrector, max_edit_dist=2, max_lookup=5):\n    misspell_data, misspelled_words_cnt = parse_misspell_data(filename)\n    plot_cols = max_edit_dist\n    plt.figure(figsize=(4*plot_cols, 4), dpi=100)\n    for edit_dist in range(1, max_edit_dist+1):\n        corrector_fixed_dist = partial(corrector, max_edit_dist=edit_dist)\n        score_data = [score(misspell_data, corrector_fixed_dist, lookup)/misspelled_words_cnt \n                      for lookup in range(1, max_lookup+1)]\n        print(score_data)\n        plt.subplot(1, plot_cols, edit_dist)\n        plt.gca().set_ylim([0, 1.0])\n        plt.bar(range(1, max_lookup+1), score_data)\n        plt.title(f\"Max edit dist: {edit_dist}\")\n        plt.ylabel('score in %')\n        plt.xlabel('max lookup')\n    plt.tight_layout()\n    plt.savefig(f'{filename}-score-graph.svg');\n```\n\n\n```python\ntest_with_spell_data_and_create_graph('aspell.dat', corr.suggestions, max_lookup=10)\ntest_with_spell_data_and_create_graph('wikipedia.dat', corr.suggestions, max_lookup=10)\n```\n\n# Spelling corrector: Conclusion\n\n\n(aspell.dat)\n\n\n(wikipedia.dat)\n\n# Thank you for your attention\n<br>\n<br>\nAll slides, the notebooks, the word files, etc. are available on the [GWDG Gitlab](https://gitlab.gwdg.de/) under [programming-pearls-spelling-checker](https://gitlab.gwdg.de/robinwilliam.hundt/programming-pearls-spelling-checker)\n\n# References  \n\n- Programming Pearls, a spelling checker. Jon Bentley. Communications of the ACM, May 1985 Volume 28 Number 5\n- 1000x Faster Spelling Correction algorithm, Wolf, [blog.faroo.com](http://blog.faroo.com/2012/06/07/improved-edit-distance-based-spelling-correction/) (published June 7, 2012)\n- How to Write a Spelling Corrector, Peter Norvig, [norvig.com](http://norvig.com/spell-correct.html) (published Feb 2007 to August 2016)  \n\n## Data sources\n- `big.txt`, Peter Norvig, [norvig.com](http://norvig.com/big.txt)\n- `frequency_dictionary_en_82_765.txt`, Wolf Garbe, [github.com](https://github.com/wolfgarbe/SymSpell/blob/master/SymSpell/frequency_dictionary_en_82_765.txt)\n- `aspell.dat` and `wikipedia.dat`, Roger Mitton, [dcs.bbk.ac.uk](http://www.dcs.bbk.ac.uk/~ROGER/corpora.html)\n\n## Libraries\n- [marisa_trie](https://github.com/pytries/marisa-trie) (MIT license)  \n- [numpy](https://github.com/numpy/numpy) (BSD-new license)  \n- [matplotlib](https://github.com/matplotlib/matplotlib)  \n- [pympler](https://github.com/pympler/pympler) (Apache-2.0)\n", "meta": {"hexsha": "0810e73785a4fc8d759ba065603b1aac24bf0e87", "size": 110904, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "presentation-spell-checking-correction.ipynb", "max_stars_repo_name": "robinhundt/programming-pearls-spelling-checker", "max_stars_repo_head_hexsha": "7c04d1f1d186f104366c89c8e06f36d69d052a52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "presentation-spell-checking-correction.ipynb", "max_issues_repo_name": "robinhundt/programming-pearls-spelling-checker", "max_issues_repo_head_hexsha": "7c04d1f1d186f104366c89c8e06f36d69d052a52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "presentation-spell-checking-correction.ipynb", "max_forks_repo_name": "robinhundt/programming-pearls-spelling-checker", "max_forks_repo_head_hexsha": "7c04d1f1d186f104366c89c8e06f36d69d052a52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.681868743, "max_line_length": 29048, "alphanum_fraction": 0.7781594893, "converted": true, "num_tokens": 6870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782568056728001, "lm_q2_score": 0.07263670686266267, "lm_q1q2_score": 0.020211658026196073}}
{"text": "# iCAT Export\n---\n\n#### Overview\nExport data in pyramidal png stacks for CATMAID.\n\n\n```python\nfrom pathlib import Path\nfrom tqdm.notebook import tqdm\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n```\n\n#### Settings\n\n\n```python\n# pandas display settings\npd.set_option('display.max_rows', 20)\npd.set_option('display.width', None)\npd.set_option('display.max_colwidth', 15)\n\n# Indirectly enable autocomplete\n%config Completer.use_jedi = False\n```\n\n## Set up `render-ws` environment\n---\n\n\n```python\nimport renderapi\nfrom icatapi.render_pandas import create_stack_DataFrame, create_stacks_DataFrame\n```\n\n\n```python\n# `render` project parameters\n# ---------------------------\nowner = 'rlane'\nproject = 'pancreas'\nproject_dir = Path(f'/long_term_storage/{owner}/SECOM/projects/{project}')\nexport_dir = Path(f'/long_term_storage/{owner}/CATMAID/projects/{project}')\n\n# Create a renderapi.connect.Render object\n# ----------------------------------------\nrender_connect_params = {\n    'host': 'sonic.tnw.tudelft.nl',\n    'port': 8080,\n    'owner': owner,\n    'project': project,\n    'client_scripts': '/home/catmaid/render/render-ws-java-client/src/main/scripts',\n    'memGB': '2G'\n}\nrender = renderapi.connect(**render_connect_params)\nrender.make_kwargs()\n```\n\n\n\n\n    {'host': 'http://sonic.tnw.tudelft.nl',\n     'port': 8080,\n     'owner': 'rlane',\n     'project': 'pancreas',\n     'client_scripts': '/home/catmaid/render/render-ws-java-client/src/main/scripts',\n     'client_script': '/home/catmaid/render/render-ws-java-client/src/main/scripts/run_ws_client.sh',\n     'memGB': '2G'}\n\n\n\n\n```python\n# Infer stack and section info\n# ----------------------------\nstacks = renderapi.render.get_stacks_by_owner_project(render=render)\nstacks_EM = [stack for stack in stacks if 'EM' in stack]\nstacks_FM = [stack for stack in stacks if 'EM' not in stack]\nstacks_2_export = [\n    'EM_himag_stitched',\n    'EM_lomag_correlated',\n    'Hoechst_correlated',\n    'AF594_correlated'\n]\n\n# Output\n# ------\nout = f\"\"\"\\\nproject directory... {project_dir} | Exists: {project_dir.exists()}\nexport directory.... {export_dir} | Exists: {export_dir.exists()}\nall stacks.......... {stacks}\nEM stacks........... {stacks_EM}\nFM stacks........... {stacks_FM}\nstacks to export.... {stacks_2_export}\n...\n\"\"\"\nprint(out)\n\n# Create project DataFrame\n# ------------------------\ndf_project = create_stacks_DataFrame(stacks=stacks_2_export,\n                                     render=render)\ndf_project.groupby('stack')\\\n          .apply(lambda x: x.head(5))\n```\n\n    project directory... /long_term_storage/rlane/SECOM/projects/pancreas | Exists: False\n    export directory.... /long_term_storage/rlane/CATMAID/projects/pancreas | Exists: False\n    all stacks.......... ['Hoechst_correlated', 'EM_lomag_correlated', 'AF594_correlated', 'EM_minimontages', 'EM_lomag_world', 'EM_himag_world', 'EM_lomag_overlaid', 'AF594_overlaid', 'Hoechst_overlaid', 'EM_himag_stitched', 'EM_himag_montaged', 'Hoechst', 'EM_lomag', 'EM_himag', 'AF594']\n    EM stacks........... ['EM_lomag_correlated', 'EM_minimontages', 'EM_lomag_world', 'EM_himag_world', 'EM_lomag_overlaid', 'EM_himag_stitched', 'EM_himag_montaged', 'EM_lomag', 'EM_himag']\n    FM stacks........... ['Hoechst_correlated', 'AF594_correlated', 'AF594_overlaid', 'Hoechst_overlaid', 'Hoechst', 'AF594']\n    stacks to export.... ['EM_himag_stitched', 'EM_lomag_correlated', 'Hoechst_correlated', 'AF594_correlated']\n    ...\n    \n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>tileId</th>\n      <th>z</th>\n      <th>width</th>\n      <th>height</th>\n      <th>minint</th>\n      <th>maxint</th>\n      <th>imageUrl</th>\n      <th>tforms</th>\n      <th>stack</th>\n      <th>sectionId</th>\n      <th>imageRow</th>\n      <th>imageCol</th>\n      <th>stageX</th>\n      <th>stageY</th>\n    </tr>\n    <tr>\n      <th>stack</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"4\" valign=\"top\">AF594_correlated</th>\n      <th>108</th>\n      <td>aaa_insulin...</td>\n      <td>4.0</td>\n      <td>2048.0</td>\n      <td>2048.0</td>\n      <td>441.0</td>\n      <td>882.0</td>\n      <td>https://son...</td>\n      <td>[M=[[1.0000...</td>\n      <td>AF594_corre...</td>\n      <td>S004</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1025.598744</td>\n      <td>6371.521975</td>\n    </tr>\n    <tr>\n      <th>109</th>\n      <td>aaa_insulin...</td>\n      <td>5.0</td>\n      <td>2048.0</td>\n      <td>2048.0</td>\n      <td>439.0</td>\n      <td>878.0</td>\n      <td>https://son...</td>\n      <td>[M=[[1.0000...</td>\n      <td>AF594_corre...</td>\n      <td>S005</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1622.072408</td>\n      <td>6381.077600</td>\n    </tr>\n    <tr>\n      <th>110</th>\n      <td>aaa_insulin...</td>\n      <td>6.0</td>\n      <td>2048.0</td>\n      <td>2048.0</td>\n      <td>445.0</td>\n      <td>890.0</td>\n      <td>https://son...</td>\n      <td>[M=[[1.0000...</td>\n      <td>AF594_corre...</td>\n      <td>S006</td>\n      <td>1</td>\n      <td>1</td>\n      <td>2227.808609</td>\n      <td>6381.567861</td>\n    </tr>\n    <tr>\n      <th>111</th>\n      <td>aaa_insulin...</td>\n      <td>7.0</td>\n      <td>2048.0</td>\n      <td>2048.0</td>\n      <td>439.0</td>\n      <td>878.0</td>\n      <td>https://son...</td>\n      <td>[M=[[1.0000...</td>\n      <td>AF594_corre...</td>\n      <td>S007</td>\n      <td>1</td>\n      <td>1</td>\n      <td>2832.009499</td>\n      <td>6381.316683</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">EM_himag_stitched</th>\n      <th>0</th>\n      <td>aaa_lil_EM-...</td>\n      <td>4.0</td>\n      <td>4096.0</td>\n      <td>4096.0</td>\n      <td>31039.0</td>\n      <td>32893.0</td>\n      <td>https://son...</td>\n      <td>[M=[[0.2309...</td>\n      <td>EM_himag_st...</td>\n      <td>S004</td>\n      <td>6</td>\n      <td>6</td>\n      <td>1078.477000</td>\n      <td>6335.559000</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>aab_lil_EM-...</td>\n      <td>4.0</td>\n      <td>4096.0</td>\n      <td>4096.0</td>\n      <td>31039.0</td>\n      <td>32893.0</td>\n      <td>https://son...</td>\n      <td>[M=[[0.2309...</td>\n      <td>EM_himag_st...</td>\n      <td>S004</td>\n      <td>6</td>\n      <td>5</td>\n      <td>1060.996000</td>\n      <td>6335.559000</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>aac_lil_EM-...</td>\n      <td>4.0</td>\n      <td>4096.0</td>\n      <td>4096.0</td>\n      <td>31039.0</td>\n      <td>32893.0</td>\n      <td>https://son...</td>\n      <td>[M=[[0.2308...</td>\n      <td>EM_himag_st...</td>\n      <td>S004</td>\n      <td>6</td>\n      <td>4</td>\n      <td>1043.523000</td>\n      <td>6335.571000</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>aad_lil_EM-...</td>\n      <td>4.0</td>\n      <td>4096.0</td>\n      <td>4096.0</td>\n      <td>31039.0</td>\n      <td>32893.0</td>\n      <td>https://son...</td>\n      <td>[M=[[0.2309...</td>\n      <td>EM_himag_st...</td>\n      <td>S004</td>\n      <td>6</td>\n      <td>3</td>\n      <td>1025.992000</td>\n      <td>6335.580000</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>aae_lil_EM-...</td>\n      <td>4.0</td>\n      <td>4096.0</td>\n      <td>4096.0</td>\n      <td>31039.0</td>\n      <td>32893.0</td>\n      <td>https://son...</td>\n      <td>[M=[[0.2309...</td>\n      <td>EM_himag_st...</td>\n      <td>S004</td>\n      <td>6</td>\n      <td>2</td>\n      <td>1008.514000</td>\n      <td>6335.597000</td>\n    </tr>\n    <tr>\n      <th rowspan=\"4\" valign=\"top\">EM_lomag_correlated</th>\n      <th>100</th>\n      <td>aaa_big_EM-...</td>\n      <td>4.0</td>\n      <td>4096.0</td>\n      <td>4096.0</td>\n      <td>31678.0</td>\n      <td>34295.0</td>\n      <td>https://son...</td>\n      <td>[M=[[1.5358...</td>\n      <td>EM_lomag_co...</td>\n      <td>S004</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1021.110000</td>\n      <td>6371.003000</td>\n    </tr>\n    <tr>\n      <th>101</th>\n      <td>aaa_big_EM-...</td>\n      <td>5.0</td>\n      <td>4096.0</td>\n      <td>4096.0</td>\n      <td>31586.0</td>\n      <td>34319.0</td>\n      <td>https://son...</td>\n      <td>[M=[[1.5332...</td>\n      <td>EM_lomag_co...</td>\n      <td>S005</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1621.125000</td>\n      <td>6381.079000</td>\n    </tr>\n    <tr>\n      <th>102</th>\n      <td>aaa_big_EM-...</td>\n      <td>6.0</td>\n      <td>4096.0</td>\n      <td>4096.0</td>\n      <td>31639.0</td>\n      <td>34260.0</td>\n      <td>https://son...</td>\n      <td>[M=[[1.5290...</td>\n      <td>EM_lomag_co...</td>\n      <td>S006</td>\n      <td>1</td>\n      <td>1</td>\n      <td>2226.245000</td>\n      <td>6381.133000</td>\n    </tr>\n    <tr>\n      <th>103</th>\n      <td>aaa_big_EM-...</td>\n      <td>7.0</td>\n      <td>4096.0</td>\n      <td>4096.0</td>\n      <td>31681.0</td>\n      <td>34238.0</td>\n      <td>https://son...</td>\n      <td>[M=[[1.5343...</td>\n      <td>EM_lomag_co...</td>\n      <td>S007</td>\n      <td>1</td>\n      <td>1</td>\n      <td>2831.405000</td>\n      <td>6381.305000</td>\n    </tr>\n    <tr>\n      <th rowspan=\"4\" valign=\"top\">Hoechst_correlated</th>\n      <th>104</th>\n      <td>aaa_hoechst...</td>\n      <td>4.0</td>\n      <td>2048.0</td>\n      <td>2048.0</td>\n      <td>889.0</td>\n      <td>1778.0</td>\n      <td>https://son...</td>\n      <td>[M=[[1.0000...</td>\n      <td>Hoechst_cor...</td>\n      <td>S004</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1025.598744</td>\n      <td>6371.521975</td>\n    </tr>\n    <tr>\n      <th>105</th>\n      <td>aaa_hoechst...</td>\n      <td>5.0</td>\n      <td>2048.0</td>\n      <td>2048.0</td>\n      <td>870.0</td>\n      <td>1740.0</td>\n      <td>https://son...</td>\n      <td>[M=[[1.0000...</td>\n      <td>Hoechst_cor...</td>\n      <td>S005</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1622.072408</td>\n      <td>6381.077600</td>\n    </tr>\n    <tr>\n      <th>106</th>\n      <td>aaa_hoechst...</td>\n      <td>6.0</td>\n      <td>2048.0</td>\n      <td>2048.0</td>\n      <td>884.0</td>\n      <td>1768.0</td>\n      <td>https://son...</td>\n      <td>[M=[[1.0000...</td>\n      <td>Hoechst_cor...</td>\n      <td>S006</td>\n      <td>1</td>\n      <td>1</td>\n      <td>2227.808609</td>\n      <td>6381.567861</td>\n    </tr>\n    <tr>\n      <th>107</th>\n      <td>aaa_hoechst...</td>\n      <td>7.0</td>\n      <td>2048.0</td>\n      <td>2048.0</td>\n      <td>864.0</td>\n      <td>1728.0</td>\n      <td>https://son...</td>\n      <td>[M=[[1.0000...</td>\n      <td>Hoechst_cor...</td>\n      <td>S007</td>\n      <td>1</td>\n      <td>1</td>\n      <td>2832.009499</td>\n      <td>6381.316683</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Export `render-ws` stacks to CATMAID\n---\n### Set up CATMAID export parameters\n\n\n```python\nfrom random import sample\nfrom renderapi.client import ArgumentParameters\n```\n\n\n```python\nclass CatmaidBoxesParameters(ArgumentParameters):\n    \"\"\"Subclass of `ArgumentParameters` for facilitating CATMAID export client script\"\"\"\n    def __init__(self, stack, root_directory,\n                 height=1024, width=1024, fmt='png', max_level=0,\n                 host=None, port=None, baseurl=None,\n                 owner=None, project=None, render=None, **kwargs):\n\n        super(CatmaidBoxesParameters, self).__init__(**kwargs)\n\n        self.stack = stack\n        self.rootDirectory = root_directory\n        self.height = height\n        self.width = width\n        self.format = fmt\n        self.maxLevel = max_level\n\n        render_kwargs = render.make_kwargs()\n        host = render_kwargs.get('host')\n        port = render_kwargs.get('port')\n        self.baseDataUrl = renderapi.render.format_baseurl(host, port)\n        self.owner = render_kwargs.get('owner') if owner is None else owner\n        self.project = render_kwargs.get('project') if project is None else project\n```\n\n#### Logic for maximum zoom level\n\nIdeally `max_level` is set such that\n\n\\begin{equation}\n\\left( \\frac{w_s}{w_t \\,\\, 2^m} \\right) < 1\n\\end{equation}\n\nwhere $m$ is `max_level`, $w_s$ is the width of the stack and $w_t$ is the width of each tile. Then\n\n\\begin{equation}\nm = \\textrm{ceil} \\left( \\log{\\frac{w_s}{w_t}} \\times \\frac{1}{\\log{2}} \\right)\n\\end{equation}\n\n\n```python\n# Initialize collection for export parameters\nexport_data = {}\n# Update max level\nmaxest_level = 0\n# Set format\nfmt = 'png'\n\n# Iterate through stacks\nfor stack, df_stack in df_project.groupby('stack'):\n\n    # Determine `max_level` such that the full section is in view when fully zoomed out\n    w_tile = 1024\n    h_tile = 1024\n    stack_bounds = renderapi.stack.get_stack_bounds(stack=stack,\n                                                    render=render)\n    w_stack = max(stack_bounds['maxX'] - stack_bounds['minX'],\n                  stack_bounds['maxY'] - stack_bounds['minY'])\n    max_level = int(np.ceil(np.log(w_stack / w_tile) * 1/np.log(2)))\n    # Export each stack to highest level in the project\n    maxest_level = max(max_level, maxest_level)\n\n    # Set parameters for export to CATMAID\n    export_params = CatmaidBoxesParameters(stack=stack,\n                                           root_directory=export_dir.parent.as_posix(),\n                                           width=w_tile,\n                                           height=h_tile,\n                                           max_level=maxest_level,\n                                           fmt=fmt,\n                                           project=project,\n                                           render=render)\n\n    # Add CATMAID export parameters to collection\n    export_data[stack] = export_params\n\n# Preview\nstack = sample(export_data.keys(), 1)[0]\nlist(export_data[stack].to_java_args())\n```\n\n\n\n\n    ['--stack',\n     'Hoechst_correlated',\n     '--rootDirectory',\n     '/long_term_storage/rlane/CATMAID/projects',\n     '--height',\n     '1024',\n     '--width',\n     '1024',\n     '--format',\n     'png',\n     '--maxLevel',\n     '6',\n     '--baseDataUrl',\n     'http://sonic.tnw.tudelft.nl:8080/render-ws/v1',\n     '--owner',\n     'rlane',\n     '--project',\n     'pancreas']\n\n\n\n### Call render script\n`render_catmaid_boxes.sh`\n```sh\nUsage: java -cp <render-module>-standalone.jar\n      org.janelia.render.client.BoxClient [options] Z values for layers to\n      render\n  Options:\n  * --baseDataUrl\n      Base web service URL for data (e.g. http://host[:port]/render-ws/v1)\n    --binaryMask\n      use binary mask (e.g. for DMG data)\n      Default: false\n    --createIGrid\n      create an IGrid file\n      Default: false\n    --doFilter\n      Use ad hoc filter to support alignment\n      Default: false\n    --filterListName\n      Apply this filter list to all rendering (overrides doFilter option)\n    --forceGeneration\n      Regenerate boxes even if they already exist\n      Default: false\n    --format\n      Format for rendered boxes\n      Default: png\n  * --height\n      Height of each box\n    --help\n      Display this note\n    --label\n      Generate single color tile labels instead of actual tile images\n      Default: false\n    --maxLevel\n      Maximum mipmap level to generate\n      Default: 0\n    --maxOverviewWidthAndHeight\n      Max width and height of layer overview image (omit or set to zero to\n      disable overview generation)\n    --numberOfRenderGroups\n      Total number of parallel jobs being used to render this layer (omit if\n      only one job is being used)\n  * --owner\n      Stack owner\n  * --project\n      Stack project\n    --renderGroup\n      Index (1-n) that identifies portion of layer to render (omit if only one\n      job is being used)\n  * --rootDirectory\n      Root directory for rendered tiles (e.g.\n      /tier2/flyTEM/nobackup/rendered_boxes)\n    --skipInterpolation\n      skip interpolation (e.g. for DMG data)\n      Default: false\n  * --stack\n      Stack name\n  * --width\n      Width of each box\n```\n\n#### Wrapper for `render_catmaid_boxes` script for multiprocessing\nMultiprocessing is done across sections, so a process is created for each section.\n\n\n```python\ndef run_render_catmaid_boxes(z, client_script, java_args):\n    \"\"\"Wrapper for `render_catmaid_boxes` script to enable multiprocessing\"\"\"\n    p = subprocess.run([client_script.as_posix(), f'{z:.0f}'] + java_args)\n```\n\n#### \\*\\****COMPUTATIONALLY EXPENSIVE*** \\**\n\n##### Run `render_catmaid_boxes` on `N_cores`\n\n`renderapi.client.WithPool` ends prematurely (after exporting one section).  \nWeirdly only happens with `lil_EM_montaged` stack...\n\n\n```python\nimport subprocess\nfrom functools import partial\nfrom multiprocessing import Pool\n```\n\n\n```python\n# Path to `render_catmaid_boxes` shell script\nfp_client = Path(render_connect_params['client_scripts']) / 'render_catmaid_boxes.sh'\n# Set number of cores for multiprocessing\nN_cores = min(15, df_project['z'].unique().size)\n# Get z values\nz_values = np.unique([renderapi.stack.get_z_values_for_stack(stack, render=render)\\\n                      for stack in stacks_2_export])\n\n# Iterate through stacks to export\n# for stack in tqdm(stacks_2_export):\nfor stack in tqdm(stacks_2_export):\n\n    # Create java arguments from export parameters\n    java_args = list(export_data[stack].to_java_args())\n\n    # Set up `render_catmaid_boxes` client script\n    render_catmaid_boxes_partial = partial(run_render_catmaid_boxes,\n                                           client_script=fp_client,\n                                           java_args=java_args)\n\n    # Run `render_catmaid_boxes` across `N_cores`\n    with Pool(N_cores) as pool:\n        pool.map(render_catmaid_boxes_partial, z_values)\n```\n\n\n      0%|          | 0/4 [00:00<?, ?it/s]\n\n\n## Set up tiles for import to CATMAID\n---\n### Resort CATMAID tiles\nBy (unchangeable) default, `render_catmaid_boxes` exports tiles as\n\n`root directory` / `project` / `stack` / `width x height` / `zoomlevel` / `z` / `row` / `col.fmt`\n\nThis is ok, but preferred format for importing to CATMAID is [tile source convention 1](https://catmaid.readthedocs.io/en/stable/tile_sources.html#tile-source-types) --- \"[File-based image stack](https://catmaid.readthedocs.io/en/stable/tile_sources.html#file-based-image-stack)\"\n\n`root directory` / `project` / `stack` / `z` / `row_col_zoomlevel.fmt`\n\nOne other tidbit is that CATMAID annoyingly assumes that sections are 0-indexed so $z_{min}$ is subtracted.\n\n#### \\*\\****CHANGES LOTS & LOTS OF FILEPATHS ON DISK*** \\**\n\n\n```python\nfrom shutil import rmtree\nfrom skimage import io, transform, img_as_ubyte\n```\n\n\n```python\n# Iterate through stacks to export\nfor stack in tqdm(stacks_2_export):\n\n    # Loop through all the exported tiles per stack\n    fps = (export_dir / stack).glob(f\"1024x1024/**/[0-9]*.{fmt}\")\n    for fp in fps:\n\n        # Extract tile info from filepath\n        zoom_level = int(fp.parents[2].name)\n        z = int(fp.parents[1].name) - int(z_values.min())  # 0-index\n        row = int(fp.parents[0].name)\n        col = int(fp.stem)\n\n        # Reformat tile\n        tile_format_1 = export_dir / stack / f\"{z}/{row}_{col}_{zoom_level}.{fmt}\"\n        tile_format_1.parent.mkdir(parents=True, exist_ok=True)\n        fp.rename(tile_format_1)\n\n    # Clean up (now presumably empty) directory tree\n    rmtree((export_dir / stack / '1024x1024').as_posix())\n```\n\n\n      0%|          | 0/4 [00:00<?, ?it/s]\n\n\n#### Make thumbnails\n\n\n```python\nfrom icatapi.plotting import colorize, T_HOECHST, T_AF594\n```\n\n\n```python\n# Colorize settings\nd_colorize = {\n    'Hoechst_correlated': T_HOECHST,\n    'AF594_correlated': T_AF594,\n}\n\n# Loop through stacks to export\nfor stack in tqdm(stacks_2_export):\n\n    # Loop through each section\n    for z in (z_values - z_values.min()):\n\n        # Load most zoomed out image (0, 0, `maxest_level`)\n        image = io.imread(export_dir / f\"{stack}/{z:.0f}/0_0_{maxest_level}.{fmt}\")\n        # Resize\n        output_shape = (128, 128)\n        thumb = transform.resize(image, output_shape=output_shape)\n        # Colorize\n        if stack in stacks_FM:\n            thumb = colorize(thumb, d_colorize[stack])\n        # Save\n        fp_thumb = export_dir / f\"{stack}/{z:.0f}/small.{fmt}\"\n        io.imsave(fp_thumb, img_as_ubyte(thumb))\n```\n\n\n      0%|          | 0/4 [00:00<?, ?it/s]\n\n\n#### Create `project.yaml` file\n\n\n```python\nimport sys\nfrom random import sample\nfrom ruamel.yaml import YAML\nfrom tifffile import TiffFile\nfrom bs4 import BeautifulSoup as Soup\nimport json\n```\n\n\n```python\n# Set project yaml file\nproject_yaml = export_dir / 'project.yaml'\n\n# Collect stack data\nstack_data = []\nfor stack in tqdm(stacks_2_export):\n\n    # Get dimension data\n    bounds = renderapi.stack.get_stack_bounds(stack=stack,\n                                              render=render)\n    dimensions = (int((bounds['maxX'] - bounds['minX']) * 1.1),\n                  int((bounds['maxY'] - bounds['minY']) * 1.1),\n                  int(bounds['maxZ'] - bounds['minZ'] + 1))\n\n    # Get resolution data (base it off OG EM himag resolution data)\n    stack_metadata = renderapi.stack.get_full_stack_metadata(stack='EM_himag',\n                                                             render=render)\n    resolution = (np.round(stack_metadata['currentVersion']['stackResolutionX'], 5),\n                  np.round(stack_metadata['currentVersion']['stackResolutionY'], 5),\n                  np.round(stack_metadata['currentVersion']['stackResolutionZ'], 5))\n\n    # Get metadata\n    ts = sample(renderapi.tilespec.get_tile_specs_from_stack(stack=stack,\n                                                             render=render), 1)[0]\n    fp = ts.ip[0]['imageUrl'].split('.nl')[1]\n    tif = TiffFile(fp)\n    metadata = tif.pages[0].description\n\n    # Project data for output to project yaml file\n    stack_datum = {\n        \"title\": f\"{stack}\",\n        \"dimension\": f\"{dimensions}\",\n        \"resolution\": f\"{resolution}\",\n        \"zoomlevels\": f\"{(maxest_level + 1):.0f}\",\n        \"metadata\": metadata,\n        \"mirrors\": [{\n            \"title\": f\"{project}_{stack.split('_')[0]}\",\n            \"tile_width\": 1024,\n            \"tile_height\": 1024,\n            \"tile_source_type\": 1,\n            \"fileextension\": f\"{fmt}\",\n            \"url\": f\"http://sonic.tnw.tudelft.nl{(export_dir/stack).as_posix()}\"\n        }]\n    }\n    stack_data.append(stack_datum)\n\n# Create dict for input into project yaml file\nproject_data = {\n    \"project\": {\n        \"title\": f\"{project}\",\n        \"stacks\": stack_data\n    }\n}\n```\n\n\n      0%|          | 0/4 [00:00<?, ?it/s]\n\n\n\n```python\nout = f\"\"\"\\\n{project_yaml}\n--------\\\n\"\"\"\nprint(out)\n\nyaml = YAML()\nyaml.indent(mapping=2, offset=0)\nyaml.dump(project_data, project_yaml)\nyaml.dump(project_data, sys.stdout)\n```\n\n    /long_term_storage/rlane/CATMAID/projects/pancreas/project.yaml\n    --------\n    project:\n      title: pancreas\n      stacks:\n      - title: EM_himag_stitched\n        dimension: (20544, 20870, 4)\n        resolution: (4.85951, 4.85951, 100.0)\n        zoomlevels: '7'\n        metadata: \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?><OME xmlns=\\\"http://www.openmicroscopy.org/Schemas/OME/2012-06\\\"\\\n          \\ xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xsi:schemaLocation=\\\"\\\n          http://www.openmicroscopy.org/Schemas/OME/2012-06 http://www.openmicroscopy.org/Schemas/OME/2012-06/ome.xsd\\\"\\\n          >\\n    <!--Warning: this comment is an OME-XML metadata block, which contains\\\n          \\ crucial dimensional parameters and other important metadata. Please edit cautiously\\\n          \\ (if at all), and back up the original data before doing so. For more information,\\\n          \\ see the OME-TIFF web site: http://ome-xml.org/wiki/OmeTiff.-->\\n    <Instrument\\\n          \\ ID=\\\"Instrument:0\\\">\\n        <Microscope Manufacturer=\\\"Delmic\\\" />\\n   \\\n          \\     <Detector ID=\\\"Detector:0\\\" Model=\\\"pcie-6251\\\" />\\n        <Objective\\\n          \\ CalibratedMagnification=\\\"20950.000000000000000\\\" ID=\\\"Objective:0\\\" />\\n\\\n          \\    </Instrument>\\n    <Image ID=\\\"Image:0\\\" Name=\\\"Secondary electrons\\\">\\n\\\n          \\        <AcquisitionDate>2019-11-04T23:48:50</AcquisitionDate>\\n        <ObjectiveSettings\\\n          \\ ID=\\\"Objective:0\\\" />\\n        <Pixels DimensionOrder=\\\"XYZTC\\\" ID=\\\"Pixels:0\\\"\\\n          \\ PhysicalSizeX=\\\"0.004859505519093\\\" PhysicalSizeY=\\\"0.004859505519093\\\" SizeC=\\\"\\\n          1\\\" SizeT=\\\"1\\\" SizeX=\\\"4096\\\" SizeY=\\\"4096\\\" SizeZ=\\\"1\\\" Type=\\\"uint16\\\">\\n\\\n          \\            <Channel ID=\\\"Channel:0:0\\\" Name=\\\"Secondary electrons\\\" />\\n \\\n          \\           <TiffData FirstC=\\\"0\\\" FirstT=\\\"0\\\" FirstZ=\\\"0\\\" IFD=\\\"0\\\" PlaneCount=\\\"\\\n          1\\\" />\\n            <Plane ExposureTime=\\\"0.000004000000000\\\" IntegrationCount=\\\"\\\n          5\\\" PositionX=\\\"0.002804099000000\\\" PositionY=\\\"0.006330358000000\\\" TheC=\\\"\\\n          0\\\" TheT=\\\"0\\\" TheZ=\\\"0\\\" />\\n        </Pixels>\\n    </Image>\\n</OME>\"\n        mirrors:\n        - title: pancreas_EM\n          tile_width: 1024\n          tile_height: 1024\n          tile_source_type: 1\n          fileextension: png\n          url: http://sonic.tnw.tudelft.nl/long_term_storage/rlane/CATMAID/projects/pancreas/EM_himag_stitched\n      - title: EM_lomag_correlated\n        dimension: (37808, 37706, 4)\n        resolution: (4.85951, 4.85951, 100.0)\n        zoomlevels: '7'\n        metadata: \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?><html><body><ome xmlns=\\\"\\\n          http://www.openmicroscopy.org/Schemas/OME/2012-06\\\" xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\"\\\n          \\ xsi:schemalocation=\\\"http://www.openmicroscopy.org/Schemas/OME/2012-06 http://www.openmicroscopy.org/Schemas/OME/2012-06/ome.xsd\\\"\\\n          ><!--Warning: this comment is an OME-XML metadata block, which contains crucial\\\n          \\ dimensional parameters and other important metadata. Please edit cautiously\\\n          \\ (if at all), and back up the original data before doing so. For more information,\\\n          \\ see the OME-TIFF web site: http://ome-xml.org/wiki/OmeTiff.--><instrument\\\n          \\ id=\\\"Instrument:0\\\"><microscope manufacturer=\\\"Delmic\\\" model=\\\"SECOM\\\"></microscope><detector\\\n          \\ id=\\\"Detector:0\\\" model=\\\"pcie-6251\\\"></detector><objective calibratedmagnification=\\\"\\\n          3033.000000000000000\\\" id=\\\"Objective:2\\\"></objective></instrument><image id=\\\"\\\n          Image:2\\\" name=\\\"Secondary electrons\\\">\\n<acquisitiondate>2019-11-02T16:53:46</acquisitiondate>\\n\\\n          <objectivesettings id=\\\"Objective:2\\\"></objectivesettings>\\n<transform a00=\\\"\\\n          1.000000000000000\\\" a01=\\\"0.000000000000000\\\" a02=\\\"0.000000000000000\\\" a10=\\\"\\\n          0.006820329878077\\\" a11=\\\"1.000000000000000\\\" a12=\\\"0.000000000000000\\\"></transform>\\n\\\n          <pixels dimensionorder=\\\"XYZTC\\\" id=\\\"Pixels:2\\\" physicalsizex=\\\"0.033927219205267\\\"\\\n          \\ physicalsizey=\\\"0.033205415562290\\\" sizec=\\\"1\\\" sizet=\\\"1\\\" sizex=\\\"4096\\\"\\\n          \\ sizey=\\\"4096\\\" sizez=\\\"1\\\" type=\\\"uint16\\\">\\n<channel id=\\\"Channel:2:0\\\" name=\\\"\\\n          Secondary electrons\\\"></channel>\\n<tiffdata firstc=\\\"0\\\" firstt=\\\"0\\\" firstz=\\\"\\\n          0\\\" ifd=\\\"2\\\" planecount=\\\"1\\\"></tiffdata>\\n<plane exposuretime=\\\"0.000005100000000\\\"\\\n          \\ integrationcount=\\\"6\\\" positionx=\\\"0.002226245000000\\\" positiony=\\\"0.006381133000000\\\"\\\n          \\ thec=\\\"0\\\" thet=\\\"0\\\" thez=\\\"0\\\"></plane>\\n</pixels>\\n</image></ome></body></html>\"\n        mirrors:\n        - title: pancreas_EM\n          tile_width: 1024\n          tile_height: 1024\n          tile_source_type: 1\n          fileextension: png\n          url: http://sonic.tnw.tudelft.nl/long_term_storage/rlane/CATMAID/projects/pancreas/EM_lomag_correlated\n      - title: Hoechst_correlated\n        dimension: (54294, 55411, 4)\n        resolution: (4.85951, 4.85951, 100.0)\n        zoomlevels: '7'\n        metadata: \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?><html><body><ome xmlns=\\\"\\\n          http://www.openmicroscopy.org/Schemas/OME/2012-06\\\" xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\"\\\n          \\ xsi:schemalocation=\\\"http://www.openmicroscopy.org/Schemas/OME/2012-06 http://www.openmicroscopy.org/Schemas/OME/2012-06/ome.xsd\\\"\\\n          ><!--Warning: this comment is an OME-XML metadata block, which contains crucial\\\n          \\ dimensional parameters and other important metadata. Please edit cautiously\\\n          \\ (if at all), and back up the original data before doing so. For more information,\\\n          \\ see the OME-TIFF web site: http://ome-xml.org/wiki/OmeTiff.--><instrument\\\n          \\ id=\\\"Instrument:0\\\"><microscope manufacturer=\\\"Delmic\\\" model=\\\"SECOM\\\"></microscope><detector\\\n          \\ id=\\\"Detector:0\\\" model=\\\"Andor ZYLA-4.2P-USB3- (s/n: VSC-06794)\\\"></detector><lightsource\\\n          \\ id=\\\"LightSource:0\\\" power=\\\"757.575757575757621\\\"></lightsource><objective\\\n          \\ calibratedmagnification=\\\"60.000000000000000\\\" id=\\\"Objective:0\\\" model=\\\"\\\n          Optical Objective\\\"></objective></instrument><image id=\\\"Image:0\\\" name=\\\"Filtered\\\n          \\ colour 1\\\">\\n<acquisitiondate>2019-11-02T15:48:30</acquisitiondate>\\n<objectivesettings\\\n          \\ id=\\\"Objective:0\\\"></objectivesettings>\\n<detectorsettings id=\\\"Detector:0\\\"\\\n          \\ offset=\\\"100.000000000000000\\\"></detectorsettings>\\n<transform a00=\\\"0.992909187954275\\\"\\\n          \\ a01=\\\"-0.118875331654563\\\" a02=\\\"0.000000000000000\\\" a10=\\\"0.118875331654563\\\"\\\n          \\ a11=\\\"0.992909187954275\\\" a12=\\\"0.000000000000000\\\"></transform>\\n<pixels\\\n          \\ dimensionorder=\\\"XYZTC\\\" id=\\\"Pixels:0\\\" physicalsizex=\\\"0.106416630143553\\\"\\\n          \\ physicalsizey=\\\"0.106416630143553\\\" significantbits=\\\"16\\\" sizec=\\\"1\\\" sizet=\\\"\\\n          1\\\" sizex=\\\"2048\\\" sizey=\\\"2048\\\" sizez=\\\"1\\\" type=\\\"uint16\\\">\\n<channel acquisitionmode=\\\"\\\n          WideField\\\" color=\\\"#0000ffff\\\" contrastmethod=\\\"Fluorescence\\\" emissionwavelength=\\\"\\\n          440\\\" excitationwavelength=\\\"405\\\" id=\\\"Channel:0:0\\\" illuminationtype=\\\"Epifluorescence\\\"\\\n          \\ name=\\\"Filtered colour 1\\\">\\n<detectorsettings binning=\\\"1x1\\\" gain=\\\"1.100000000000000\\\"\\\n          \\ id=\\\"Detector:0\\\" readoutrate=\\\"100.000000000000000\\\"></detectorsettings>\\n\\\n          <lightsourcesettings id=\\\"LightSource:0\\\"></lightsourcesettings>\\n</channel>\\n\\\n          <tiffdata firstc=\\\"0\\\" firstt=\\\"0\\\" firstz=\\\"0\\\" ifd=\\\"0\\\" planecount=\\\"1\\\"\\\n          ></tiffdata>\\n<plane exposuretime=\\\"3.000000000000000\\\" positionx=\\\"0.001025598743565\\\"\\\n          \\ positiony=\\\"0.006371521974858\\\" thec=\\\"0\\\" thet=\\\"0\\\" thez=\\\"0\\\"></plane>\\n\\\n          </pixels>\\n</image></ome></body></html>\"\n        mirrors:\n        - title: pancreas_Hoechst\n          tile_width: 1024\n          tile_height: 1024\n          tile_source_type: 1\n          fileextension: png\n          url: http://sonic.tnw.tudelft.nl/long_term_storage/rlane/CATMAID/projects/pancreas/Hoechst_correlated\n      - title: AF594_correlated\n        dimension: (54294, 55411, 4)\n        resolution: (4.85951, 4.85951, 100.0)\n        zoomlevels: '7'\n        metadata: \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?><html><body><ome xmlns=\\\"\\\n          http://www.openmicroscopy.org/Schemas/OME/2012-06\\\" xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\"\\\n          \\ xsi:schemalocation=\\\"http://www.openmicroscopy.org/Schemas/OME/2012-06 http://www.openmicroscopy.org/Schemas/OME/2012-06/ome.xsd\\\"\\\n          ><!--Warning: this comment is an OME-XML metadata block, which contains crucial\\\n          \\ dimensional parameters and other important metadata. Please edit cautiously\\\n          \\ (if at all), and back up the original data before doing so. For more information,\\\n          \\ see the OME-TIFF web site: http://ome-xml.org/wiki/OmeTiff.--><instrument\\\n          \\ id=\\\"Instrument:0\\\"><microscope manufacturer=\\\"Delmic\\\" model=\\\"SECOM\\\"></microscope><detector\\\n          \\ id=\\\"Detector:1\\\" model=\\\"Andor ZYLA-4.2P-USB3- (s/n: VSC-06794)\\\"></detector><lightsource\\\n          \\ id=\\\"LightSource:1\\\" power=\\\"1000.000000000000000\\\"></lightsource><objective\\\n          \\ calibratedmagnification=\\\"60.000000000000000\\\" id=\\\"Objective:1\\\" model=\\\"\\\n          Optical Objective\\\"></objective></instrument><image id=\\\"Image:1\\\" name=\\\"Filtered\\\n          \\ colour 2\\\">\\n<acquisitiondate>2019-11-02T15:48:34</acquisitiondate>\\n<objectivesettings\\\n          \\ id=\\\"Objective:1\\\"></objectivesettings>\\n<detectorsettings id=\\\"Detector:1\\\"\\\n          \\ offset=\\\"100.000000000000000\\\"></detectorsettings>\\n<transform a00=\\\"0.992909187954275\\\"\\\n          \\ a01=\\\"-0.118875331654563\\\" a02=\\\"0.000000000000000\\\" a10=\\\"0.118875331654563\\\"\\\n          \\ a11=\\\"0.992909187954275\\\" a12=\\\"0.000000000000000\\\"></transform>\\n<pixels\\\n          \\ dimensionorder=\\\"XYZTC\\\" id=\\\"Pixels:1\\\" physicalsizex=\\\"0.106416630143553\\\"\\\n          \\ physicalsizey=\\\"0.106416630143553\\\" significantbits=\\\"16\\\" sizec=\\\"1\\\" sizet=\\\"\\\n          1\\\" sizex=\\\"2048\\\" sizey=\\\"2048\\\" sizez=\\\"1\\\" type=\\\"uint16\\\">\\n<channel acquisitionmode=\\\"\\\n          WideField\\\" color=\\\"#ff9500ff\\\" contrastmethod=\\\"Fluorescence\\\" emissionwavelength=\\\"\\\n          607\\\" excitationwavelength=\\\"555\\\" id=\\\"Channel:1:0\\\" illuminationtype=\\\"Epifluorescence\\\"\\\n          \\ name=\\\"Filtered colour 2\\\">\\n<detectorsettings binning=\\\"1x1\\\" gain=\\\"1.100000000000000\\\"\\\n          \\ id=\\\"Detector:1\\\" readoutrate=\\\"100.000000000000000\\\"></detectorsettings>\\n\\\n          <lightsourcesettings id=\\\"LightSource:1\\\"></lightsourcesettings>\\n</channel>\\n\\\n          <tiffdata firstc=\\\"0\\\" firstt=\\\"0\\\" firstz=\\\"0\\\" ifd=\\\"1\\\" planecount=\\\"1\\\"\\\n          ></tiffdata>\\n<plane exposuretime=\\\"3.000000000000000\\\" positionx=\\\"0.001025598743565\\\"\\\n          \\ positiony=\\\"0.006371521974858\\\" thec=\\\"0\\\" thet=\\\"0\\\" thez=\\\"0\\\"></plane>\\n\\\n          </pixels>\\n</image></ome></body></html>\"\n        mirrors:\n        - title: pancreas_AF594\n          tile_width: 1024\n          tile_height: 1024\n          tile_source_type: 1\n          fileextension: png\n          url: http://sonic.tnw.tudelft.nl/long_term_storage/rlane/CATMAID/projects/pancreas/AF594_correlated\n\n", "meta": {"hexsha": "b977a88e4866c138c49d4af69c8b787befdeb3aa", "size": 54151, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/6_iCAT-export.ipynb", "max_stars_repo_name": "hoogenboom-group/iCAT-workflow", "max_stars_repo_head_hexsha": "04c3bb5a17b8e5ddd7b14785ade0842ac3adef19", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/6_iCAT-export.ipynb", "max_issues_repo_name": "hoogenboom-group/iCAT-workflow", "max_issues_repo_head_hexsha": "04c3bb5a17b8e5ddd7b14785ade0842ac3adef19", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-03-14T18:37:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T13:35:45.000Z", "max_forks_repo_path": "notebooks/6_iCAT-export.ipynb", "max_forks_repo_name": "hoogenboom-group/iCAT-workflow", "max_forks_repo_head_hexsha": "04c3bb5a17b8e5ddd7b14785ade0842ac3adef19", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2108066971, "max_line_length": 297, "alphanum_fraction": 0.4596221676, "converted": true, "num_tokens": 10459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2509127868852725, "lm_q2_score": 0.08035747708119237, "lm_q1q2_score": 0.020162718521511393}}
{"text": "# Lesson 5: High level plotting\n\n\n```python\nimport numpy as np\nimport pandas as pd\n\nimport bokeh_catplot\n\nimport bokeh.plotting\nimport bokeh.io\n\nbokeh.io.output_notebook()\n```\n\n\n\n<div class=\"bk-root\">\n    <a href=\"https://bokeh.pydata.org\" target=\"_blank\" class=\"bk-logo bk-logo-small bk-logo-notebook\"></a>\n    <span id=\"1001\">Loading BokehJS ...</span>\n</div>\n\n\n\n\n<hr/>\n\nIn this lesson, do some plotting with a high-level package [Bokeh-catplot](https://github.com/justinbois/bokeh-catplot). If you haven't already, you should install it.\n\n    pip install --upgrade bokeh-catplot\n\nFor this lesson, we will use [the frog tongue data set from Kleinteich and Gorb](https://doi.org/10.1038/srep05225) that we used in [lesson 21](l21_practice_with_pandas.html). Let's get the data frame loaded in so we can be on our way.\n\n\n```python\ndf = pd.read_csv('Dataset/frog_tongue_adhesion.csv', comment='#')\n\n# Have a look so we remember\ndf.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>date</th>\n      <th>ID</th>\n      <th>trial number</th>\n      <th>impact force (mN)</th>\n      <th>impact time (ms)</th>\n      <th>impact force / body weight</th>\n      <th>adhesive force (mN)</th>\n      <th>time frog pulls on target (ms)</th>\n      <th>adhesive force / body weight</th>\n      <th>adhesive impulse (N-s)</th>\n      <th>total contact area (mm2)</th>\n      <th>contact area without mucus (mm2)</th>\n      <th>contact area with mucus / contact area without mucus</th>\n      <th>contact pressure (Pa)</th>\n      <th>adhesive strength (Pa)</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>2013_02_26</td>\n      <td>I</td>\n      <td>3</td>\n      <td>1205</td>\n      <td>46</td>\n      <td>1.95</td>\n      <td>-785</td>\n      <td>884</td>\n      <td>1.27</td>\n      <td>-0.290</td>\n      <td>387</td>\n      <td>70</td>\n      <td>0.82</td>\n      <td>3117</td>\n      <td>-2030</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2013_02_26</td>\n      <td>I</td>\n      <td>4</td>\n      <td>2527</td>\n      <td>44</td>\n      <td>4.08</td>\n      <td>-983</td>\n      <td>248</td>\n      <td>1.59</td>\n      <td>-0.181</td>\n      <td>101</td>\n      <td>94</td>\n      <td>0.07</td>\n      <td>24923</td>\n      <td>-9695</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2013_03_01</td>\n      <td>I</td>\n      <td>1</td>\n      <td>1745</td>\n      <td>34</td>\n      <td>2.82</td>\n      <td>-850</td>\n      <td>211</td>\n      <td>1.37</td>\n      <td>-0.157</td>\n      <td>83</td>\n      <td>79</td>\n      <td>0.05</td>\n      <td>21020</td>\n      <td>-10239</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>2013_03_01</td>\n      <td>I</td>\n      <td>2</td>\n      <td>1556</td>\n      <td>41</td>\n      <td>2.51</td>\n      <td>-455</td>\n      <td>1025</td>\n      <td>0.74</td>\n      <td>-0.170</td>\n      <td>330</td>\n      <td>158</td>\n      <td>0.52</td>\n      <td>4718</td>\n      <td>-1381</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>2013_03_01</td>\n      <td>I</td>\n      <td>3</td>\n      <td>493</td>\n      <td>36</td>\n      <td>0.80</td>\n      <td>-974</td>\n      <td>499</td>\n      <td>1.57</td>\n      <td>-0.423</td>\n      <td>245</td>\n      <td>216</td>\n      <td>0.12</td>\n      <td>2012</td>\n      <td>-3975</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## High level plotting and rendering with Bokeh\n\n[HoloViews](https://holoviews.org/) is an excellent high-level plotting package that can use Bokeh to render plots. In my view, it is one of the best high-level plotting languaes in the Python plotting landscape. We will work with HoloViews in a future lesson, but in this lesson, we will do our high-level plotting using a package I wrote called [Bokeh-catplot](https://github.com/justinbois/bokeh-catplot).\n\nWhy are we using this package and not HoloViews? In next year's bootcamp, I am almost certain we will use HoloViews exclusively for high-level plotting because I suspect that most of the functionality in Bokeh-catplot will be incorporated into HoloViews. Bokeh-catplot exists because HoloViews lacks some important functionality. (More on these very important plot types in a moment; don't worry if you don't know what they are just yet.)\n\n- It does not natively make ECDFs.\n- Its definition of a box plot is non-canonical ([my fault](https://github.com/pyviz/holoviews/pull/1926), but will soon be [fixed](https://github.com/pyviz/holoviews/pull/3755)).\n- It does not (easily, or as far as I can tell) enable an axis with more than one categorical variable for strip plots (though it does for box plots).\n- It has a [bug when making horizontal strip plots](https://github.com/pyviz/holoviews/issues/3748).\n\nThere are all relatively minor fixes for HoloViews, which will likely have this functionality in the near future.\n\nNonetheless, ECDFs and horizontal strip plots are important visualizations and I advocate using them often, and Bokeh-catplot provides a high-level way to render them using Bokeh.\n\n## Plots with categorical variables\n\nLet us first consider the different kinds of data we may encounter as we think about constructing a plot.\n\n- **Quantitative** data may have continuously varying (and therefore ordered) values.\n- **Categorical** data has discrete, unordered values that a variable can take.\n- **Ordinal** data has discrete, ordered values. Integers are a classic example.\n- **Temporal** data refers to time, which can be represented as dates.\n\nIn practice, ordinal data can be cast as quantitative or treated as categorical with an ordering enforced on the categories (e.g., categorical data `[1, 2, 3]` becomes `['1', '2', '3']`.). Temporal data can also be cast as quantitative, (e.g., second from the start time). We will therefore focus out attention on quantitative and categorical data.\n\nWhen we made scatter plots in the previous lesson, both types of data were quantitative. We did actually incorporate categorical information in the form of colors of the glyph (insomniacs and normal sleepers being colored differently) and in tooltips. \n\nBut what if we wanted a single type of measurement, say impact force, for each frog. Here, we have the quantitative impact force data and the categorical frog ID data. One of our axes is now categorical.\n\n## Bar graph\n\nTo demonstrate how to set up a categorical axis with Bokeh, I will make a bar graph of the mean impact force for each of the four frogs. But before I even begin this, I will give you the following piece of advice: *Don't make bar graphs.* More on that in a moment.\n\nBefore we do that, we need to compute the means from the inputted data frame.\n\n\n```python\ndf_mean = df.groupby('ID')['impact force (mN)'].mean().reset_index()\n\n# Take a look\ndf_mean\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>ID</th>\n      <th>impact force (mN)</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>I</td>\n      <td>1530.20</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>II</td>\n      <td>707.35</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>III</td>\n      <td>550.10</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>IV</td>\n      <td>419.10</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nTo set up a categorical axis, you need to specify the `x_range` (or `y_range` if you want the y-axis to be categorical) as a list with the categories you want on the axis when you instantiate the figure. I will make a horizontal bar graph, so I will specify `y_range`. Also, when I instantiate this figure, because it is not very tall and I do not want the reset tool cut off, I will also explicitly set the tools I want in the toolbar.\n\n\n```python\np = bokeh.plotting.figure(\n    height=200,\n    width=400,\n    x_axis_label='impact force (mN)',\n    y_range=df_mean['ID'].unique()[::-1],\n    tools='pan,wheel_zoom,save,reset'\n)\n```\n\nNow that we have the figure, we can put the bars on. The `p.hbar()` method populates the figure with horizontal bar glyphs. The `right` kwarg says what column of the data source dictates how far to the right to show the bar, while the `height` kwarg says how think the bars are.\n\nI will also ensure the quantitative axis starts at zero and turn off the grid lines on the categorical axis, which is commonly done.\n\n\n```python\np.hbar(\n    source=df_mean,\n    y='ID',\n    right='impact force (mN)',\n    height=0.6\n)\n\n# Turn off gridlines on categorical axis\np.ygrid.grid_line_color = None\n\n# Start axes at origin on quantitative axis\np.x_range.start = 0\n\nbokeh.io.show(p)\n```\n\n\n\n\n\n\n\n\n<div class=\"bk-root\" id=\"f77b735b-1993-465b-a7cf-66ab35775a3f\" data-root-id=\"1002\"></div>\n\n\n\n\n\nWe similarly make vertical bar graphs specifying `x_range` and using `p.vbar()`.\n\n\n```python\np = bokeh.plotting.figure(\n    height=250,\n    width=250,\n    y_axis_label='impact force (mN)',\n    x_range=df_mean['ID'].unique(),\n)\n\np.vbar(\n    source=df_mean,\n    x='ID',\n    top='impact force (mN)',\n    width=0.6\n)\n\np.xgrid.grid_line_color = None\np.y_range.start = 0\n\nbokeh.io.show(p)\n```\n\n\n\n\n\n\n\n\n<div class=\"bk-root\" id=\"4b3a5dc9-c072-48e8-8e68-ce25e31d7c67\" data-root-id=\"1091\"></div>\n\n\n\n\n\n## Bokeh-catplot\n\nGenerating the bar graphs was not too painful, even tough we used Bokeh, a low-level plotting library. We would like to make plots more directly. We do not want to have to explicitly pre-process the data, set up the categorical axis, etc. We would like to just provide a data set, say which column(s) is/are categorical and which is quantitative, and then just get our plot. As I mentioned before, Holoviews is excellent for this purpose, but we will use Bokeh-catplot as our high-level package for making plots.\n\nBokeh-catplot generates plots from tidy data frames where one or more columns contains categorical data and the column of interest in the plot is quantitative.\n\nThere are four types of plots that Bokeh-catplot can generate. As you will see, all four of these modes of plotting are meant to give a picture about how the quantitative measurements are *distributed* for each category.\n\n- **Plots with a categorical axis**\n    + Box plots: `bokeh_catplot.box()`\n    + Strip plots: `bokeh_catplot.strip()`\n \n    \n- **Plots without a categorical axis**\n    + Histograms: `bokeh_catplot.histogram()`\n    + [ECDFs](https://en.wikipedia.org/wiki/Empirical_distribution_function): `bokeh_catplot.ecdf()`\n    \n\nThe first three arguments of each of these functions are necessary to build the plot. They are:\n\n- `data`: A tidy data frame\n- `cats`: A list of columns in the data frame that are to be considered as categorical variables in the plot. If `None`, a single box, strip, histogram, or ECDF is plotted.\n- `val`: The column of the data frame to be treated as the quantitative variable. \n\nWith this in mind, we will put Bokeh-catplot to use on the frog data set.\n\n## Box plots with Bokeh-catplot\n\nAs I [discuss below](#Don't-make-bar-graphs), bar graphs are almost never a good choice for visualization. You distill all of the information in the data set down to one or two summary statistics, and then use giant glyphs to show them. As a start for improvement, you could distill the data set down to five or so summary statistics and show those graphically, as opposed to just one or two. \n\nBox plots provide such a summary. I will first make one using `bokeh_catplot.box()` and then describe how a box plot is interpreted.\n\n\n```python\np = bokeh_catplot.box(\n    data=df,\n    cats='ID',\n    val='impact force (mN)'\n)\n\nbokeh.io.show(p)\n```\n\n\n\n\n\n\n\n\n<div class=\"bk-root\" id=\"10349cc6-a13c-4f2c-9aec-f63abceb38cc\" data-root-id=\"1200\"></div>\n\n\n\n\n\nThe line in the middle of each box is the median and the top and bottom of the box at the 75th and 25th percentiles, respectively. The distance between the 25th and 75th percentiles is called the **interquartile range**, or IQR. The whiskers of the box plot extend to the most extreme data point within 1.5 times the interquartile range. If any data points are more extreme than the end of the whisker, they are shown individually, and are often referred to as _outliers_.\n\nA box plot can use a useful visualization if you have many data points and it is difficult to plot them all. I rarely find that there are situations where all data cannot be plotted, either with strip plots of ECDFs, which we will cover in a moment, so I generally do not use box plots. Nonetheless, I do not find them too objectionable, as they effectively display important nonparametric summary statistics of your data set.\n\n## Plot all your data\n\nBox plots summarize a data set with summary statistics, but what not plot all your data? You work hard to acquire them. You should show them all. This is a mantra to live by.\n\n<center><font color=\"dodgerblue\"><b>Plot all your data.</b></font></center><br/>\n\nLet's do that now.\n\n## Strip plots\n\nA **strip plot** is like a scatter plot; it puts a glyph for every measured data point. The only different is that one of the axes is categorical. In this case, you are plotting all of your data.\n\n\n```python\np = bokeh_catplot.strip(\n    data=df,\n    cats='ID',\n    val='impact force (mN)'\n)\n\nbokeh.io.show(p)\n```\n\n\n\n\n\n\n\n\n<div class=\"bk-root\" id=\"4c0fcd5d-76f9-4627-a76f-23904f345927\" data-root-id=\"1355\"></div>\n\n\n\n\n\nThis is a good plot to make since you are plotting all of your data, but it does have the problem that you cannot tell if multiple ticks overlap. Let's look at some alternatives.\n\n## Histograms\n\nIn plotting all of our data in a strip plot, we can roughly see how the data are distributed. There are more measurements where there are more glyphs.\n\n\n```python\np = bokeh_catplot.histogram(\n    data=df,\n    cats='ID',\n    val='impact force (mN)'\n)\n\nbokeh.io.show(p)\n```\n\n\n\n\n\n\n\n\n<div class=\"bk-root\" id=\"29d4de9d-35a0-4351-ac9d-9bf3b85a4c0f\" data-root-id=\"1484\"></div>\n\n\n\n\n\n## ECDFs\n\nHistograms are typically used to display how data are distributed. As an example I will generate Normally distributed data and plot the histogram. (We will learn how to generate data like this when we study random number generation with NumPy in a future lesson. For not, this is for purposes of discussing plotting options.)\n\n\n```python\n# Generate normally distributed data\nnp.random.seed(353926)\ndf_norm = pd.DataFrame(data={'x': np.random.normal(size=500)})\n\n# Plot the histogram\np = bokeh_catplot.histogram(\n    data=df_norm,\n    cats=None,\n    val='x'\n)\n\nbokeh.io.show(p)\n```\n\n\n\n\n\n\n\n\n<div class=\"bk-root\" id=\"1ebcc62e-fdc6-41d7-9b60-058e916f33e9\" data-root-id=\"1871\"></div>\n\n\n\n\n\nThis looks similar to the standard Normal curve we are used to seeing and is a useful comparison to a **probability density function** (PDF). However, Histograms suffer from **binning bias**. By binning the data, you are not plotting all of them. In general, if you can **plot all of your data**, you should. For that reason, I prefer not to use histograms for studying how data are distributed, but rather prefer to use ECDFs, which enable plotting of all data.\n\nThe ECDF evaluated at x for a set of measurements is defined as\n\n\\begin{align}\n\\text{ECDF}(x) = \\text{fraction of measurements } \\le x.\n\\end{align}\n\nWhile the histogram is an attempt to visualize a probability density function (PDF) of a distribution, the ECDF visualizes the **cumulative density function** (CDF). The CDF, $F(x)$, and PDF, $f(x)$, both completely define a univariate distribution and are related by\n\n\\begin{align}\nf(x) = \\frac{\\mathrm{d}F}{\\mathrm{d}x}.\n\\end{align}\n\nThe definition of the ECDF is all that you need for interpretation. Once you get used to looking at CDFs, they will become as familiar as PDFs. A peak in a PDF corresponds to an inflection point in a CDF.\n\nTo make this more clear, let us look at plot of a PDF and ECDF for familiar distributions, the Gaussian and Binomial.\n\n<center></center><br/>\n\nNow that we know how to interpret ECDFs, lets plot the ECDF for our dummy Normally-distributed data.\n\n\n```python\np = bokeh_catplot.ecdf(\n    data=df_norm,\n    cats=None,\n    val='x'\n)\n\nbokeh.io.show(p)\n```\n\n\n\n\n\n\n\n\n<div class=\"bk-root\" id=\"2a9d66bf-c6de-4731-883f-befc418e54e5\" data-root-id=\"2067\"></div>\n\n\n\n\n\nNow that we understand what an ECDF is and how to plot it, let's make a set of ECDFs for our frog data.\n\n\n```python\np = bokeh_catplot.ecdf(\n    data=df,\n    cats='ID',\n    val='impact force (mN)'\n)\n\nbokeh.io.show(p)\n```\n\n\n\n\n\n\n\n\n<div class=\"bk-root\" id=\"3f0565e0-8cc4-488e-b843-58cd0eb0c0ea\" data-root-id=\"2248\"></div>\n\n\n\n\n\nEach dot in the ECDF is a single data point that we measured. Given the above definition of the ECDF, it is defined for all real $x$. So, formally, the ECDF is a continuous function (with discontinuous derivatives at each data point). So, it should be plotted like a staircase according to the formal definition. We can plot it that way using the `formal` keyword argument.\n\n\n```python\np = bokeh_catplot.ecdf(\n    data=df,\n    cats='ID',\n    val='impact force (mN)',\n    formal=True\n)\n\nbokeh.io.show(p)\n```\n\n\n\n\n\n\n\n\n<div class=\"bk-root\" id=\"bb4507a6-ea6c-40d8-8deb-3f73aa73f646\" data-root-id=\"2534\"></div>\n\n\n\n\n\nThis is still plotting all of your data. The concave corners of the staircase correspond to the measured data. This can be seen by overlaying the \"dot\" version of the ECDFs.\n\n\n```python\np = bokeh_catplot.ecdf(\n    data=df,\n    cats='ID',\n    val='impact force (mN)',\n    p=p\n)\n\nbokeh.io.show(p)\n```\n\n\n\n\n\n\n\n\n<div class=\"bk-root\" id=\"7c92991b-238d-45c7-b060-a9dfcba920f7\" data-root-id=\"2534\"></div>\n\n\n\n\n\n## Customization with Bokeh-catplot\n\nYou may have noticed in the discussion of ECDFs that I introduced some new keyword arguments, `formal` and `p`. In fact, each of the four plotting functions also has the following additional optional keyword arguments.\n\n- `palette`: A list of hex colors to use for coloring the markers for each category. By default, it uses the default color scheme of [Vega-Lite](https://vega.github.io/vega-lite/).\n- `order`: If specified, the ordering of the categories to use on the categorical axis and legend (if applicable). Otherwise, the order of the inputted data frame is used.\n- `p`: If specified, the `bokeh.plotting.Figure` object to use for the plot. If not specified, a new figure is created.\n\nThe respective plotting functions also have kwargs that are specific to each (such as `formal` for `bokeh_catplot.ecdf()`. Examples highlighting some, but not all, customizations follow. You can find out what kwargs are available for each function by reading their doc strings, e.g., with\n\n```python\nbokeh_catplot.box?\n```\n\nAny kwargs not in the function call signature are passed to `bokeh.plotting.figure()` when the figure is instantiated.\n\n#### Customizing box plots\n\nWe can also have horizontal box plots.\n\n\n```python\np = bokeh_catplot.box(\n    data=df,\n    cats='ID',\n    val='impact force (mN)',\n    horizontal=True\n)\n\nbokeh.io.show(p)\n```\n\n\n\n\n\n\n\n\n<div class=\"bk-root\" id=\"7a83a284-0ed7-4b84-bb21-0b833f919098\" data-root-id=\"4602\"></div>\n\n\n\n\n\nWe can independently specify properties of the marks using `box_kwargs`, `whisker_kwargs`, `median_kwargs`, and `outlier_kwargs`. For example, say we wanted our colors to be [Betancourt red](https://betanalpha.github.io/assets/case_studies/principled_bayesian_workflow.html#step_four:_build_a_generative_model19), and that we wanted the outliers to also be that color and use diamond glyphs.\n\n\n```python\np = bokeh_catplot.box(\n    data=df,\n    cats='ID',\n    val='impact force (mN)',\n    whisker_caps=True,\n    outlier_marker='diamond',\n    box_kwargs=dict(fill_color='#7C0000'),\n    whisker_kwargs=dict(line_color='#7C0000', line_width=2),\n)\n\nbokeh.io.show(p)\n```\n\n\n\n\n\n\n\n\n<div class=\"bk-root\" id=\"cb97c3e3-072d-4c4e-9bdf-b43c9be958ed\" data-root-id=\"4874\"></div>\n\n\n\n\n\n#### Custominzing strip plots\n\nTo help alleviate the overlap problem, we can make a strip plot with dash markers and add some transparency.\n\n\n```python\np = bokeh_catplot.strip(\n    data=df,\n    cats='ID',\n    val='impact force (mN)',\n    marker='dash',\n    marker_kwargs=dict(alpha=0.5)\n)\n\nbokeh.io.show(p)\n```\n\n\n\n\n\n\n\n\n<div class=\"bk-root\" id=\"32111177-fc8b-42b7-a47e-f54ad46e1736\" data-root-id=\"5164\"></div>\n\n\n\n\n\nThe problem with strip plots is that they can have trouble with overlapping data points. A common approach to deal with this is to \"jitter,\" or place the glyphs with small random displacements along the categorical axis. I do that here, allowing for hover tools that give more information about the respective data points.\n\n\n```python\np = bokeh_catplot.strip(\n    data=df,\n    cats='ID',\n    val='impact force (mN)',\n    jitter=True,\n    tooltips=[\n        ('trial', '@{trial number}'),\n        ('adh force', '@{adhesive force (mN)}')\n    ]\n)\n\nbokeh.io.show(p)\n```\n\n\n\n\n\n\n\n\n<div class=\"bk-root\" id=\"899a6b49-370c-4f89-8afd-ec55995a81ec\" data-root-id=\"5421\"></div>\n\n\n\n\n\nWith any of the plots, you can have more than one categorical column, and the categorical axes are nicely spaced and formatted. Here, we'll categorize by frog ID and by trial number.\n\n\n```python\np = bokeh_catplot.strip(\n    data=df,\n    cats=['ID', 'trial number'],\n    val='impact force (mN)',\n    color_column='trial number',\n    width=550\n)\n\nbokeh.io.show(p)\n```\n\n\n\n\n\n\n\n\n<div class=\"bk-root\" id=\"efac7d44-5ca2-40a3-9bfd-31e93878b484\" data-root-id=\"5690\"></div>\n\n\n\n\n\n#### Strip-box plots\n\nEven while plotting all of the data, we sometimes want to graphically display summary statistics, in which case overlaying a box plot and a jitter plot is useful. To populate an existing Bokeh figure with new glyphs from another catplot, pass in the `p` kwarg. You should be careful, though, because you need to make sure the `cats`, `val`, and `horizontal` arguments exactly match.\n\n\n```python\np = bokeh_catplot.strip(\n    data=df,\n    cats='ID',\n    val='impact force (mN)',\n    horizontal=True,\n    jitter=True,\n    height=250\n)\n\np = bokeh_catplot.box(\n    data=df,\n    cats='ID',\n    val='impact force (mN)',\n    horizontal=True,\n    whisker_caps=True,\n    display_points=False,\n    box_kwargs=dict(fill_color=None, line_color='gray'),\n    median_kwargs=dict(line_color='gray'),\n    whisker_kwargs=dict(line_color='gray'),\n    p=p,\n)\n\nbokeh.io.show(p)\n```\n\n\n\n\n\n\n\n\n<div class=\"bk-root\" id=\"2c3ff78a-c5e1-43e3-9ff9-2e2fb1868c22\" data-root-id=\"5965\"></div>\n\n\n\n\n\n#### Customizing histograms\n\nWe could plot normalized histograms using the density kwarg, and we'll make the plot a little wider to support the legend.\n\n\n```python\n# Plot the histogram\np = bokeh_catplot.histogram(\n    data=df_norm,\n    cats=None,\n    val='x',\n    density=True,\n)\n\nbokeh.io.show(p)\n```\n\n\n\n\n\n\n\n\n<div class=\"bk-root\" id=\"921c9995-49b8-4069-8940-667ebb753985\" data-root-id=\"6297\"></div>\n\n\n\n\n\n#### Customizing ECDFs\n\nInstead of plotting a separate ECDF for each category, we can put all of the categories together on one ECDF and color the points by the categorical variable by using the `kind='colored'` kwarg. Note that if we do this, we can only have the \"dot\" style ECDF, not the formal staircase.\n\n\n```python\np = bokeh_catplot.ecdf(\n    data=df,\n    cats='ID',\n    val='impact force (mN)',\n    kind='colored',\n)\n\nbokeh.io.show(p)\n```\n\n\n\n\n\n\n\n\n<div class=\"bk-root\" id=\"968982a3-7df0-4e05-af3e-8e7323de1b8e\" data-root-id=\"6627\"></div>\n\n\n\n\n\n## Don't make bar graphs\n\nBar graphs, especially with error bars (in which case they are called dynamite plots), are typically awful. They are pervasive in biology papers. I have yet to find a single example where a bar graph is the best choice. Strip plots (with jitter) or even box plots, are more informative and almost always preferred. In fact, ECDFs are often better even than these. Here is a simple message:\n\n<center><font color=\"tomato\"><b>Don't make bar graphs.</b></font></center><br/>\n\nWhat should I do instead you ask? The answer is simple: **plot all of your data** when you can. If you can't, box plots are always better than bar graphs.\n\n## Computing environment\n\n\n```python\n%load_ext watermark\n%watermark -v -p numpy,pandas,bokeh,bokeh_catplot,jupyterlab\n```\n\n    CPython 3.6.8\n    IPython 7.1.1\n    \n    numpy 1.16.4\n    pandas 0.24.2\n    bokeh 1.2.0\n    bokeh_catplot 0.1.3\n    jupyterlab 1.0.2\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "396e22c3a4bc7e107cd204cd2102658487fd3a4b", "size": 329411, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "L5_high_level_plotting.ipynb", "max_stars_repo_name": "uschmidt83/NEUBIAS-Porto2019", "max_stars_repo_head_hexsha": "697fe5b6c342474f27fb30f7e9e06f1f67c7b143", "max_stars_repo_licenses": ["CC-BY-4.0", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "L5_high_level_plotting.ipynb", "max_issues_repo_name": "uschmidt83/NEUBIAS-Porto2019", "max_issues_repo_head_hexsha": "697fe5b6c342474f27fb30f7e9e06f1f67c7b143", "max_issues_repo_licenses": ["CC-BY-4.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "L5_high_level_plotting.ipynb", "max_forks_repo_name": "uschmidt83/NEUBIAS-Porto2019", "max_forks_repo_head_hexsha": "697fe5b6c342474f27fb30f7e9e06f1f67c7b143", "max_forks_repo_licenses": ["CC-BY-4.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 141.2568610635, "max_line_length": 41867, "alphanum_fraction": 0.5438100124, "converted": true, "num_tokens": 6893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091278688527247, "lm_q2_score": 0.08035746661981112, "lm_q1q2_score": 0.020162715896617063}}
{"text": "##### Copyright 2020 The Cirq Developers\n\n\n```\n#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# Introduction to Cirq\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n  <td>\n    <a target=\"_blank\" href=\"https://www.example.org/cirq/tutorials/educators/intro\">View on QuantumLib</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/Cirq/blob/master/docs/tutorials/educators/intro.ipynb\">Run in Google Colab</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://github.com/quantumlib/Cirq/blob/master/docs/tutorials/educators/intro.ipynb\">View source on GitHub</a>\n  </td>\n  <td>\n    <a href=\"https://storage.googleapis.com/tensorflow_docs/Cirq/docs/tutorials/educators/intro.ipynb\">Download notebook</a>\n  </td>\n</table>\n\n[Cirq](https://github.com/quantumlib/cirq) is a framework for writing quantum algorithms for noisy intermediate scale quantum (NISQ) devices. Roughly speaking, NISQ devices are those with O(100) qubits that can enact O(1000) gates.  Because the resources for NISQ devices are so constrained we believe that a framework for writing programs on these devices needs to be aware of all of the architectural properties of the device on which the algorithm is written. This is in contrast to other frameworks where there is a clean separation between the abstract model being used and the details of the device.  \n\nIn this tutorial we will teach you the basics of writing quantum alogorithms in Cirq. Our goal will be to write a variational ansatz for use in an optimization algorithm.\n\n---\n\n\n## Contents\n\n>>[Installing Cirq](#scrollTo=rPgPbry6-mF3)\n\n>>[Qubits, Moments, Operations, and Circuits](#scrollTo=8A7a3jcql1l5)\n\n>>>[Create a Circuit](#scrollTo=VFwmWPf7D057)\n\n>>>[Building Circuits](#scrollTo=uaDb6B_jPgrb)\n\n>>>[Exercise: Create a circuit](#scrollTo=y9conKPAPn26)\n\n>>>>[Solution](#scrollTo=KnA4uBkwEw5-)\n\n>>[Simulations of a Circuit](#scrollTo=X15yPl_KQ20Z)\n\n>>>[Repetitions](#scrollTo=YLpiz0aN1Jd6)\n\n>>[The Deutsch-Jozsa Algorithm](#scrollTo=qFsytBIbOVD8)\n\n>>>[Exercise: Two Bit Deutsch-Jozsa Algorithm](#scrollTo=v4ka34Kuj4K0)\n\n>>>>[Solution](#scrollTo=L6vfs97CFZB2)\n\n>>[Gates](#scrollTo=mmhbPIhT4YAI)\n\n>>>[Custom Gate Implementation](#scrollTo=RACz4Z5GDMAf)\n\n>>>[Exercise: Custom Controlled Rx gate](#scrollTo=y63aDja8R4rc)\n\n>>>>[Solution](#scrollTo=7SoneHQRGeUW)\n\n>>>[Gate decompositions](#scrollTo=9W_Vlgpzz0D1)\n\n>>[Parameterized Circuits](#scrollTo=3HtlMxa6QpVo)\n\n>>>[Exercise: Rotate a qubit](#scrollTo=r-CjbPwkRI_I)\n\n>>[Noise](#scrollTo=FEM73JPALREa)\n\n>>>[Monte carlo simulations](#scrollTo=3qUM-Kpi8Iy4)\n\n>>>[Adding Noise to Circuits and Simulations](#scrollTo=weWPzaPx8zly)\n\n>>[Devices](#scrollTo=PvJCA3e0QsuI)\n\n>>>[Exercise: Make a Device](#scrollTo=lyFcloaARXg4)\n\n>>[Compiling / Optimizing](#scrollTo=J9ia4eatUQ_x)\n\n>>>[Exercise: Simplify flipped CNOTs](#scrollTo=--aUfkiaUb3S)\n\n>>[Google's Xmon Gates](#scrollTo=gM1ZW7TstvK9)\n\n\n## Installing Cirq\n\nTo use Cirq one first needs to install Cirq.  Installation instructions are available [at cirq.readthedocs.io under 'Installing Cirq'](https://cirq.readthedocs.io/en/latest/install.html).  For the purpose of using this notebook, you can run pip install to install the latest release of Cirq.  Different notebook execution systems exist but for most they have \"run\" button on a cell, which you can push, or <shift>-<enter> is often the shortcut to run th cell.  Do so in the following cell should install Cirq. \n\n\n```\n# install latest version\n!pip install cirq==0.5 --quiet\n\n# Alternatively, install directly from HEAD on github:\n# !pip install git+https://github.com/quantumlib/Cirq.git --quiet\n```\n\n(Note: you may see an error about `albumentations` requiring an old `imgaug`. You can ignore this error.)\n\nLet's check that Cirq has been successfully installed by importing Cirq and priting out a diagram of the Google's Bristlecone device. \n\n\n```\nimport cirq\nimport numpy as np\nimport matplotlib \nprint(cirq.google.Bristlecone)\n```\n\n                                                 (0, 5)\u2500\u2500\u2500\u2500(0, 6)\n                                                 \u2502         \u2502\n                                                 \u2502         \u2502\n                                        (1, 4)\u2500\u2500\u2500(1, 5)\u2500\u2500\u2500\u2500(1, 6)\u2500\u2500\u2500\u2500(1, 7)\n                                        \u2502        \u2502         \u2502         \u2502\n                                        \u2502        \u2502         \u2502         \u2502\n                               (2, 3)\u2500\u2500\u2500(2, 4)\u2500\u2500\u2500(2, 5)\u2500\u2500\u2500\u2500(2, 6)\u2500\u2500\u2500\u2500(2, 7)\u2500\u2500\u2500(2, 8)\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                      (3, 2)\u2500\u2500\u2500(3, 3)\u2500\u2500\u2500(3, 4)\u2500\u2500\u2500(3, 5)\u2500\u2500\u2500\u2500(3, 6)\u2500\u2500\u2500\u2500(3, 7)\u2500\u2500\u2500(3, 8)\u2500\u2500\u2500(3, 9)\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n             (4, 1)\u2500\u2500\u2500(4, 2)\u2500\u2500\u2500(4, 3)\u2500\u2500\u2500(4, 4)\u2500\u2500\u2500(4, 5)\u2500\u2500\u2500\u2500(4, 6)\u2500\u2500\u2500\u2500(4, 7)\u2500\u2500\u2500(4, 8)\u2500\u2500\u2500(4, 9)\u2500\u2500\u2500(4, 10)\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n    (5, 0)\u2500\u2500\u2500(5, 1)\u2500\u2500\u2500(5, 2)\u2500\u2500\u2500(5, 3)\u2500\u2500\u2500(5, 4)\u2500\u2500\u2500(5, 5)\u2500\u2500\u2500\u2500(5, 6)\u2500\u2500\u2500\u2500(5, 7)\u2500\u2500\u2500(5, 8)\u2500\u2500\u2500(5, 9)\u2500\u2500\u2500(5, 10)\u2500\u2500\u2500(5, 11)\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n             (6, 1)\u2500\u2500\u2500(6, 2)\u2500\u2500\u2500(6, 3)\u2500\u2500\u2500(6, 4)\u2500\u2500\u2500(6, 5)\u2500\u2500\u2500\u2500(6, 6)\u2500\u2500\u2500\u2500(6, 7)\u2500\u2500\u2500(6, 8)\u2500\u2500\u2500(6, 9)\u2500\u2500\u2500(6, 10)\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n                      (7, 2)\u2500\u2500\u2500(7, 3)\u2500\u2500\u2500(7, 4)\u2500\u2500\u2500(7, 5)\u2500\u2500\u2500\u2500(7, 6)\u2500\u2500\u2500\u2500(7, 7)\u2500\u2500\u2500(7, 8)\u2500\u2500\u2500(7, 9)\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                               (8, 3)\u2500\u2500\u2500(8, 4)\u2500\u2500\u2500(8, 5)\u2500\u2500\u2500\u2500(8, 6)\u2500\u2500\u2500\u2500(8, 7)\u2500\u2500\u2500(8, 8)\n                                        \u2502        \u2502         \u2502         \u2502\n                                        \u2502        \u2502         \u2502         \u2502\n                                        (9, 4)\u2500\u2500\u2500(9, 5)\u2500\u2500\u2500\u2500(9, 6)\u2500\u2500\u2500\u2500(9, 7)\n                                                 \u2502         \u2502\n                                                 \u2502         \u2502\n                                                 (10, 5)\u2500\u2500\u2500(10, 6)\n\n\nThe import ran without raising an error, and the output is in fact the grid of qubits for the Bristlecone device. Looks like the install worked!\n\nBe aware that Cirq is still alpha software, meaning **we are still making breaking changes all the time**. If you don't want your project to suddenly go from working to not working when we release a new version, you should depend on a *specific version* of Cirq and periodically bump that version to the latest one. For the purposes of this tutorial, we will use version of `0.5` (i.e. `cirq==0.5` in pip's version notation).\n\n---\n\n## Qubits, Moments, Operations, and Circuits\n \n In Cirq, circuits are represented either by a `Circuit` object or a `Schedule` object. `Schedule`s offer more control over quantum gates and circuits at the timing level.\n\nConceptually: a `Circuit` is a collection of `Moment`s. A `Moment` is a collection of `Operation`s that all act during the same abstract time slice. An `Operation` is a an effect that operates on a specific subset of Qubits. The most common type of `Operation` is a `Gate` applied to several qubits (a \"`GateOperation`\"). The following diagram should help illustrate these concepts.\n\n\n\n### Create a Circuit\n\nLet's create a `Circuit`.  Note that in the previous cell we imported cirq, so we will assume that cirq has been imported through out the rest of this notebook.\n\n\n```\na = cirq.NamedQubit(\"a\")\nb = cirq.NamedQubit(\"b\")\nc = cirq.NamedQubit(\"c\")\nops = [cirq.H(a), cirq.H(b), cirq.CNOT(b, c), cirq.H(b)]\ncircuit = cirq.Circuit.from_ops(ops)\nprint(circuit)\n```\n\n    a: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    b: \u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\n              \u2502\n    c: \u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\nWe can unpack this a bit and see all of the components for the circuit.\n\n\nThe first thing we do is pick some qubits to use. There are many different types of qubits in Cirq, and you can define your own by inheriting from the `cirq.Qid` class. There's nothing inherently special or magical about these quantum id types such as `cirq.NamedQubit`. They simply identify what you wish to operate on, which is relevant when you are targeting a specific device. For example, if we were creating a circuit for the Bristlecone device we would use `cirq.GridQubit(5, 0)` to refer to the qubit in the left most position of the device. To keep these simple for now, we'll start with abstract qubits simply identified by a name such as \"a\".\n```\na = cirq.NamedQubit(\"a\")\n```\n\nNext we encounter of the object `cirq.H`, which is a Hadamard gate.  `cirq.H` is an instance of the `cirq.HGate` class, which itself is a subclass of `Gate` (along with other classes). \n$$H = {1 \\over \\sqrt{2}} \\left[ \\begin{array}[cc]  & 1 & 1  \\\\ 1 & -1 \\end{array}\\right]$$\nWe can use cirq to see this unitary matrix:\n\n\n```\ncirq.unitary(cirq.H)\n```\n\n\n\n\n    array([[ 0.70710678+0.j,  0.70710678+0.j],\n           [ 0.70710678+0.j, -0.70710678+0.j]])\n\n\n\n`Gate` objects have the ability to applied \"on\" to one or more qubits.  There are two ways to do this for gates, either using the `on` method or by directly calling the gate on the qubits as if the gate were a function and the qubits were arguments.  For example to apply the `H` onto qubit `a` we can say\n```\ncirq.H.on(a)\n```\nor \n```\ncirq.H(a)\n```\n\nThe result of those expressions is a `GateOperation` object, which is a type of `Operation`.\n\nIn cirq we make a strong distinction between `Operation`s and `Gate`s. An `Operation` is associated with specific qubits and can be put in `Circuit`s. A `Gate` has unspecified qubits, and will produce an operation when given qubits.\n\nOnce you have a collection of operations, you can construct a `Circuit` using the class method `Circuit.from_ops` (more on that in a minute):\n```\ncircuit = cirq.Circuit.from_ops(ops)\n```\nThe last thing we did in the example code was use the (surprisingly useful) ability to print the circuit as a text diagram.\n\nThe diagram is visually helpful, but it doesn't really get into the internal details of how the `Circuit` is represented. \nA `Circuit` is made up of a sequence of `Moment` objects.\nAnd each `Moment` object is a list of non-overlapping `Operation`s.\nTo see this internal structure, we can iterate over the `Moment`s in the `Circuit` while printing them out.\n\n\n```\nfor i, moment in enumerate(circuit):\n    print('Moment {}: {}'.format(i, moment))\n```\n\n    Moment 0: H(a) and H(b)\n    Moment 1: CNOT(b, c)\n    Moment 2: H(b)\n\n\nWe can also just print the circuit's `repr`, which returns a somewhat more detailed (if less readable) expression.\n\n\n```\nprint(repr(circuit))\n```\n\n    cirq.Circuit(moments=[\n        cirq.Moment(operations=[\n            cirq.H.on(cirq.NamedQubit('a')),\n            cirq.H.on(cirq.NamedQubit('b')),\n        ]),\n        cirq.Moment(operations=[\n            cirq.CNOT.on(cirq.NamedQubit('b'), cirq.NamedQubit('c')),\n        ]),\n        cirq.Moment(operations=[\n            cirq.H.on(cirq.NamedQubit('b')),\n        ]),\n    ])\n\n\nThe usefulness of printing the `repr` is that it includes *all* the gory details.\nThese details can be useful when debugging.\nThe `repr` is also a valid python expression that evaluates to the circuit.\nFor example, if we notice that a circuit generated in some complicated way triggers a bug in a simulator, copy-pasting the generated circuit's `repr` into a test, and then working from there, is a simple way to decouple the reproduction of the bug from the circuit generation code.\n\n### Building Circuits\nAbove we created the `Circuit` using `from_ops`.  But there are many ways to construct and modify circuits, and each of these is useful in different contexts.  Here are a few examples:\n\n\n1.   `from_ops`: This is the simplest way to make a circuit. Give this method some operations, and out pops a circuit.\n2.  `append`:  `Circuit`s are mutable. You can start with an empty `c = cirq.Circuit()` and simply `c.append(operations)` to add on more and more operations \n3. `insert`:  Instead of appending, you can insert before a particular moment location (labeled by an integer index)\n4.  By using `Circuit`'s constructor, which takes a list of `Moment`s. Each `Moment` must be explicitly constructed with its own list of `Operation`s. This is tedious, but gives complete control over how the operations are layed out.\n\nOne interesting, and extremely convenient, fact about `from_ops`, `append`, and `insert` is that they \"auto flatten\" whatever you give them.\nYou *can* give them a list of operations, but you can also give them a list *of lists* of operations.\nOr a generator function that sometimes yields tuples of operations and other times yields individual operations.\nOr just a single operation (without a list around it).\nIf it can recursively iterated into individual operations, `from_ops` and `append` and `insert` will take it.\n\nThe main place where auto-flattening is useful is when you are generating a circuit's operations using generator functions.\nThis is jumping a bit ahead of what we've explained, but basically auto-flattening means that generators producing operations for a circuit can simply `yield` sub-generators (instead of iterating over them and yielding their items):\n\n\n\n```\ndef xor_swap(a, b):\n    yield cirq.CNOT(a, b)\n    yield cirq.CNOT(b, a)\n    yield cirq.CNOT(a, b)\n  \ndef left_rotate(qubits):\n    for i in range(len(qubits) - 1):\n        a, b = qubits[i:i+2]\n        yield xor_swap(a, b)\n\nline = cirq.LineQubit.range(5)\nprint(cirq.Circuit.from_ops(left_rotate(line)))\n```\n\n    0: \u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n          \u2502   \u2502   \u2502\n    1: \u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502   \u2502   \u2502\n    2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                  \u2502   \u2502   \u2502\n    3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500\n                                              \u2502   \u2502   \u2502\n    4: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500\n\n\nYou may have noticed that there is a hole in what we've explained so far.\n`from_ops` effectively takes a 1-dimensional sequence of operations, but the output is a 2-dimensional circuit (a list-of-lists-of-operations).\nThere is a degree of freedom that hasn't been account for.\nSpecifically: how does cirq choose the moment that each operation will be placed within?\nThe answer is: it depends on the  `InsertStrategy` you choose.\n\nThere are currently four insertion strategies in Cirq:\n\n1.  `InsertStrategy.EARLIEST` (currently the default)\n2. `InsertStrategy.NEW`,\n3. `InsertStrategy.INLINE`\n4.  `InsertStrategy.NEW_THEN_INLINE` \n\n`InsertStrategy.EARLIEST` is defined as\n> `InsertStrategy.EARLIEST`: Scans backward from the insert\n> location until a moment with operations touching qubits affected by the\n> operation to insert is found. The operation is added into the moment just\n> after that location.\n\nFor example, if we first create an `Operation` in a single moment,\nand then use `InsertStrategy.EARLIEST` the `Operation` can slide back to this\nfirst `Moment` if there is space\n\nAn `InsertStrategy` defines how ``Operations`` are placed in a `Circuit` when requested to be inserted at a given location.\nHere a `location` is identified by the index of the `Moment` in the `Circuit` that operations should be placed before (in the case of `Circuit.append` this means inserting at the index `len(circuit)`; which is one more than the largets moment index and so represents the end of the circuit).\n\n\n```\ncircuit = cirq.Circuit()\ncircuit.append([cirq.CZ(a, b)])\ncircuit.append([cirq.H(a), cirq.H(b), cirq.H(c)])\nprint(circuit)\n```\n\n    a: \u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\n          \u2502\n    b: \u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\n    \n    c: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\nAfter creating the first moment with a `CZ` gate, the second\nappend uses the `InsertStrategy.EARLIEST` strategy. The\n`H` on ``a`` and ``b`` cannot slide back, while the `H` on ``c`` can and so ends up in the first `Moment`.\n\n`InsertStrategy.EARLIEST` is the default strategy, the second most important strategy is `InsertStrategy.NEW_THEN_INLINE`:\n> `InsertStrategy.NEW_INLINE`: For the first operation, add it to a new \n> `Moment` the insertion point.  Attempts to add the operation after the first \n> operation to insert into the moment just before the desired insert location. \n> But, if there's already an existing operation affecting any of the qubits\n> touched by the operation to insert, a new moment is created instead and this \n> `Moment` is the one that is subsequently used for insertions.\n\nAs an example of this examine this code\n\n\n```\ncircuit = cirq.Circuit()\ncircuit.append([cirq.CZ(a, b)])\ncircuit.append([cirq.H(c), cirq.H(b), cirq.H(b), cirq.H(a)], )\nprint(circuit)\n```\n\n    a: \u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n          \u2502\n    b: \u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\n    \n    c: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n### Exercise: Create a circuit\n\nNow that you've learned about `InsertStrategy`, here is an exercise to validate your understanding.  Create, using the least number of appends the following circuit (note that printing a circuit in Cirq does not always print a moment by moment structure e.g. to avoid overlapping operations in the diagram, but here imagine that you want exactly the moments indicated by the spacing of the circuit.)\n\n\n\n```\na: \u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\n      \u2502\nb: \u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\nc: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n```\n\n\n#### Solution\n\n\n```\n#@title\na = cirq.NamedQubit('a')\nb = cirq.NamedQubit('b')\nc = cirq.NamedQubit('c')\ncircuit = cirq.Circuit()\ncircuit.append([cirq.CZ(a, b), cirq.H(c), cirq.H(a)] )\ncircuit.append([cirq.H(b), cirq.CZ(b, c), cirq.H(b), cirq.H(a), cirq.H(a)],\n               strategy=cirq.InsertStrategy.NEW_THEN_INLINE)\nprint(circuit)\n```\n\n    a: \u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\n          \u2502\n    b: \u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502\n    c: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n## Simulations of a Circuit\n\nNow that you know how to construct a `Circuit` in Cirq, let's use Cirq to simulate the circuit.\n\nHere is a simple circuit\n\n\n```\ndef basic_circuit(measure=True):\n    sqrt_x = cirq.X**0.5\n    cz = cirq.CZ\n    yield sqrt_x(a), sqrt_x(b)\n    yield cz(a, b)\n    yield sqrt_x(a), sqrt_x(b)\n    if measure:\n        yield cirq.measure(a,b)\n        \ncircuit = cirq.Circuit.from_ops(basic_circuit())\nprint(circuit)\n```\n\n    a: \u2500\u2500\u2500X^0.5\u2500\u2500\u2500@\u2500\u2500\u2500X^0.5\u2500\u2500\u2500M\u2500\u2500\u2500\n                  \u2502           \u2502\n    b: \u2500\u2500\u2500X^0.5\u2500\u2500\u2500@\u2500\u2500\u2500X^0.5\u2500\u2500\u2500M\u2500\u2500\u2500\n\n\nThere are a few things to note here.  \n\nOne is that we have used a Python *generator*. Recall that in Python functions that have a `yield` are *generators*. Generators are functions that act as *iterators*. Above we see that we can iterate over ``basic_circuit()``. We see that when we do this each of the `yields` produces what was yielded, and here these are `Operations`,\nor lists of ``Operations``. But when we pass this iterator to the append method, something magical happens. `Circuit` is able to flatten all of these an pass them as one giant list to `Circuit.append` (this also works for `Circuit.insert`).\n> The above idea uses a concept we call an ``OP_TREE``. An ``OP_TREE`` is\n> not a class, but a contract. The basic idea is that, if the input can be\n> iteratively flattened into a list of operations, then the input is an\n> ``OP_TREE``.\n\nA very nice pattern emerges from this structure: define *generators* for sub-circuits, which can vary by size\nor `Operation` parameters.\n\nNow we can simulate this circuit.\n\n\n```\nsimulator = cirq.Simulator()\ncircuit = cirq.Circuit.from_ops(basic_circuit())\nresult = simulator.run(circuit)\nprint('Measurement results')\nprint(result)\n```\n\n    Measurement results\n    a,b=1, 1\n\n\nRunning this multiple times should result in different measurement results, since the above circuit produces a superposition over all computational basis states.   \n\nAbove we used the `run` method on the simulator.  These methods mimic the actual hardware in that they don't give one access to unphysical objects like the wavefunction.  If one wants to get the wave function, then the `simulate` methods can do this:\n\n\n\n```\ncircuit = cirq.Circuit()\ncircuit.append(basic_circuit(measure=False))    \nresult = simulator.simulate(circuit, qubit_order=[a, b])\n\nprint('Wavefunction:')\nprint(np.around(result.final_state, 3))\nprint('Dirac notation:')\nprint(result.dirac_notation())\n```\n\n    Wavefunction:\n    [0.5+0.j  0. +0.5j 0. +0.5j 0.5+0.j ]\n    Dirac notation:\n    0.5|00\u27e9 + 0.5j|01\u27e9 + 0.5j|10\u27e9 + 0.5|11\u27e9\n\n\nNotice that we passed a `qubit_orde`r into the `simulate` method.  This order helps define the order of the kronecker product used in the resulting `final_state` vector.  The `qubit_order` argument is optional. When it is omitted, qubits are sorted ascending according to the ordering methods defined by their python class (for example `cirq.NamedQubit` sorts lexicographically by name).\nIf there are multiple types of qubits in one circuit, the name of the type is used as a tie breaker.\n\nThe simplest `qubit_order` value you can provide is a list of the qubits in the desired ordered. Any qubits from the circuit that are not in the list will be ordered using the  default `__str__` ordering, but come after qubits that are in the list. Be aware that all qubits in the list are included in the simulation, even if they are not operated on by the circuit.\n\nThe mapping from the order of the qubits to the order of the  amplitudes in the wave function can be tricky to understand.  Basically, it is the same as the ordering used by `numpy.kron`.\n\n> If wave function is array \n>>(0.1, 0.2, 0.3, 0.4)\n\n> then this is \n>> 0.1|00\u27e9 + 0.2|01\u27e9 + 0.3|10\u27e9 + 0.4|11\u27e9 \n\n>in Dirac notation.  If the \n>> qubit order = [a, b]\n\n>then |00> means qubit a is in 0 and qubit b is in 0, |01> means \n> qubit a is 0 and qubit b is 1, etc.\n\nAnother way to think about the qubit-to-amplitude ordering is as \"for loop ordering\":\n\n```\nfor a in [0, 1]:\n    for b in [0, 1]:\n        print(a, b)\n```\n\nThe first index (the outermost loop) is the slowest to vary.\n\n### Repetitions\n\nThe simulator `run` methods also take an option for repeating the circuit. If \nthe measurements in the circuit are terminal, and all other operations are unitary, this simulator is optimized to not recompute the wavefunction before sampling from the circuit.  So for example this code doesn't recompute the wave function but knows to sample from the final measurements\n\n\n```\ncircuit = cirq.Circuit.from_ops(basic_circuit())\nresult = simulator.run(circuit, repetitions=1000)\nprint(result.histogram(key='a,b'))\n```\n\n    Counter({1: 276, 0: 252, 2: 246, 3: 226})\n\n\nHere we have also demonstrated the use of the `histogram` method on the `result` which sums over all the different results for all of the different repetitions.\n\nThe `histogram` method can also be given a `fold_func` argument, in order to group measurement results under some key before counting them up.\nFor example, we can group by whether or not the two measurement results agreed:\n\n\n```\nprint(result.histogram(key='a,b', fold_func=lambda e: 'agree' if e[0] == e[1] else 'disagree'))\n```\n\n    Counter({'disagree': 522, 'agree': 478})\n\n\n## The Deutsch-Jozsa Algorithm\n\nThe very first indication that quantum computers could be more powerful than classical computers was provided by David Deutsch in his 1985 paper:\n> David Deutsch,  \"Quantum Theory, the Church-Turing Principle and the Universal Quantum Computer\" Proceedings of the Royal Society of London A. 400: 97 [PDF](https://people.eecs.berkeley.edu/~christos/classics/Deutsch_quantum_theory.pdf)\n\nThis algorithm was extended by Deutsch and Richard Jozsa to a more convincing algorithmic seperation and what is now called the Deutsch-Jozsa algorithm.  In this section we will show how to write circuits for the Deutsch algorithm and then as an exercise in using Cirq for algorithms for a small version of the Deutsch-Jozsa algorithm.\n\nLet's begin with the Deutsch algorithm.  In Deutsch's algorithm you are given access to a box which computes a one bit boolean function.  That is it is a box which takes in a bit and outputs a bit.  If we want to be a mathematician or theoretical computer scientist we write the function $f$ as $f: \\{0, 1\\} \\rightarrow \\{0, 1\\}$.  There are exactly four such boolean functions which we can write out in a table\n\n| $x$ | $f_0$ | $f_1$ | $f_x$ | $f_{\\bar{x}}$ |\n| --- |  --- | --- | --- | --- |\n| 0 | 0 | 1 | 0 | 1\n| 1 | 0 | 1 | 1 | 0\n\nThe first two of these are *constant* functions, $f_0$ and $f_1$.  That is they always output a constant value.  The other two $f_x$ and $f_\\bar{x}$ are *balanced*.  Over their inputs $0$ and $1$, they have an equal number of $0$s and $1$s in their truth table.  \n\nWe can now state Deutsch's problem:\n\n> Given access to a one bit input one bit output boolean function, determine, by querying the function whether the function is *balanced* or *constant*.\n\nIt shouldn't take you much to convince yourself that in order to solve this problem classically you need to call the function on both possible input values.  The easy way to see this is just to consider what happens if you query the function on one particular input and notice that for either input learning the value of the function does not separate the constant from balanced functions.\n\n**Classically one must query the binary function twice to distinguish the constant function from the balanced function.**\n\n\nNow lets turn to the quantum approach to this problem.  There is one bit of book keeping we need to take care of.  Above we have described a classical function on bits that is not reversible.  That is, knowing the values of the output does not allow us to determine uniquely the value of the input.  In order to run this on a quantum computer, however we need to make this computation reversible.  A trick for taking a classical non-reversible function and making it quantum happy is to compute the value in an extra register.  Suppose we have an $n$ bit input $x$ and we are computing a (potentially non-reverisble) boolean function $f(x)$.  Then we can implement this via a Unitary $U_f$ that acts like on $n + 1$ qubits\n\n$$U_f |x\\rangle |y\\rangle = |x\\rangle | y \\oplus f(x)\\rangle$$\n\nHere $\\oplus$ is addition modulo $2$ (XOR) and we have identified how $U_f$ acts by its action on all computational basis states $|x\\rangle$ ($n$ input qubits) and ($1$ output qubit)$|y\\rangle$. To see that this is reversible one can note that applying the transformation twice returns the state to its original form.\n\nLet's see how to implement these functions in Cirq.\n\n$f_0$ enacts the transform\n$$\n\\begin{eqnarray}\n|00\\rangle &\\rightarrow&  |00\\rangle \\\\\n|01\\rangle &\\rightarrow&  |01\\rangle \\\\\n|10\\rangle &\\rightarrow&  |10\\rangle \\\\\n|11\\rangle &\\rightarrow&  |11\\rangle \\\\\n\\end{eqnarray}\n$$\nWell this is just the identity transform, i.e. an empty circuit.\n\n$f_1$ enacts the transform\n$$\n\\begin{eqnarray}\n|00\\rangle &\\rightarrow&  |01\\rangle \\\\\n|01\\rangle &\\rightarrow&  |00\\rangle \\\\\n|10\\rangle &\\rightarrow&  |11\\rangle \\\\\n|11\\rangle &\\rightarrow&  |10\\rangle \\\\\n\\end{eqnarray}\n$$\nThis is the `cirq.X` bit flip gate on the second qubit.\n\n$f_x$ enacts the transform\n$$\n\\begin{eqnarray}\n|00\\rangle &\\rightarrow&  |00\\rangle \\\\\n|01\\rangle &\\rightarrow&  |01\\rangle \\\\\n|10\\rangle &\\rightarrow&  |11\\rangle \\\\\n|11\\rangle &\\rightarrow&  |10\\rangle \\\\\n\\end{eqnarray}\n$$\nThis is nothing more than a `cirq.CNOT` from the first bit to the second bit.\n\nFinally $f_\\bar{x}$ enacts the transform\n$$\n\\begin{eqnarray}\n|00\\rangle &\\rightarrow&  |01\\rangle \\\\\n|01\\rangle &\\rightarrow&  |00\\rangle \\\\\n|10\\rangle &\\rightarrow&  |10\\rangle \\\\\n|11\\rangle &\\rightarrow&  |11\\rangle \\\\\n\\end{eqnarray}\n$$\nwhich is a `cirq.CNOT` from the first bit to the second bit followed by a `cirq.X` on the second bit.\n\nWe can encapulate these functions into a dictionary from a oracle name to the ops in the circuit needed to enact this function:\n\n\n\n```\nq0, q1 = cirq.LineQubit.range(2)\noracles = {\n    '0': [],\n    '1': [cirq.X(q1)],\n    'x': [cirq.CNOT(q0, q1)],\n    'notx': [cirq.CNOT(q0, q1), cirq.X(q1)]\n}    \n```\n\nTurning now to Deutch's algorithm.  Suppose we are given access to the reversible oracle functions we have defined before.  By a similar argument for our irreversible classical functions you can show that you cannot distinguish the balanced from the constant functions by using this oracle only once.  But now we can ask the question: what if we are allowed to query this box in superposition, i.e. what if we can use the power of quantum computing?\n\nDeutsch was able to show that you could solve this problem now, with quantum computers, using only a single query of the box.  To see how this works we need two simple insights.\n\nSuppose that we prepare the second qubit in the superposition state $|-\\rangle=\\frac{1}{\\sqrt{2}}(|0\\rangle-|1\\rangle)$ and apply  the oracle.  Then we can check that\n$$ \nU_f |x\\rangle |-\\rangle = U_f|x\\rangle \\frac{1}{\\sqrt{2}}(|0\\rangle -|1\\rangle ) = |x\\rangle \\frac{1}{\\sqrt{2}}(|f(x)\\rangle -|f(x) \\oplus 1\\rangle ) =  (-1)^{f(x)} |x\\rangle |-\\rangle\n$$  \nThis is the so called \"phase kickback trick\".  By applying $U_f$ onto a target which is in superposition, the value of the function ends up showing up in the global phase.  \n\nHow can we leverage this to distinguish between the constant and balanced functions?  Note that for the constant functions the phase that is applied is the same for all inputs $|x\\rangle$, whereas for the balanced functions the phase is different for each value of $x$.   Another way to say that is that if we use the phase kickback trick then for each of the oracles we apply the following transform on the first qubit.\n$$\n\\begin{eqnarray}\nf_0 \\rightarrow I, &&\nf_1 \\rightarrow -I, &&\nf_x \\rightarrow Z, &&\nf_\\bar{x} \\rightarrow -Z &&\n\\end{eqnarray}\n$$\nNow we only need, on the first qubit, to distinguish between the identity gate and the $Z$ gate.  But we can do this by recalling the identity\n$$ H Z H = X$$\nwhere $H$ is the Hamadard gate\n$$H = {1 \\over \\sqrt{2}} \\left[ \\begin{array}[cc]  & 1 & 1  \\\\ 1 & -1 \\end{array}\\right]$$\nThis means that we can turn a phase flip into a bit flip by applying Hadamards before and after the phase flip.  If we look at the constant and balanced functions we see that this means that the constant functions will be proportional to $I$ and the balanced will be proportional to $X$.  If we feed in $|0\\rangle$ to this register, then in the first cases we will only see $|0\\rangle$ and in the second case we will see $|1\\rangle$.  In other words we will be able to distinguish constant from balanced using a single query of the oracle.\n\n\nLet's code this up\n\n\n\n```\nq0, q1 = cirq.LineQubit.range(2)\noracles = {\n    '0': [],\n    '1': [cirq.X(q1)],\n    'x': [cirq.CNOT(q0, q1)],\n    'notx': [cirq.CNOT(q0, q1), cirq.X(q1)]\n}    \n\ndef deutsch_algorithm(oracle):\n    yield cirq.X(q1)\n    yield cirq.H(q0), cirq.H(q1)\n    yield oracle\n    yield cirq.H(q0)\n    yield cirq.measure(q0)\n\nfor key, oracle in oracles.items():\n    print('Circuit for {}...'.format(key))\n    print('{}\\n'.format(cirq.Circuit.from_ops(deutsch_algorithm(oracle))))\n```\n\n    Circuit for 0...\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\n    \n    1: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    Circuit for 1...\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\n    \n    1: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\n    \n    Circuit for x...\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\n                  \u2502\n    1: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    Circuit for notx...\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\n                  \u2502\n    1: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n\n\nLets run these circuits a bunch of times to see that the measurement result ends up correctly distinguishing constant from balanced.\n\n\n```\nsimulator = cirq.Simulator()\nfor key, oracle in oracles.items():\n    result = simulator.run(cirq.Circuit.from_ops(deutsch_algorithm(oracle)), \n                          repetitions=10)\n    print('oracle: {:<4} results: {}'.format(key, result))\n```\n\n    oracle: 0    results: 0=0000000000\n    oracle: 1    results: 0=0000000000\n    oracle: x    results: 0=1111111111\n    oracle: notx results: 0=1111111111\n\n\n### Exercise: Two Bit Deutsch-Jozsa Algorithm\n\nAll boolean functions for one input bit are either constant or balanced.  For boolean functions from two input bits not all functions are constant or balanced.  There are two constant functions, $f(x_0, x_1) = 0$ and $f(x_0, x_1)=1$, while there are ${4 \\choose 2} = 6$ balanced functions.  The following code gives you the operations for these functions where we take two input qubits and compute the function in the third qubit\n\n\n\n```\nq0, q1, q2 = cirq.LineQubit.range(3)\nconstant = ([], [cirq.X(q2)])\nbalanced = ([cirq.CNOT(q0, q2)], [cirq.CNOT(q1, q2)], [cirq.CNOT(q0, q2), cirq.CNOT(q1, q2)],\n            [cirq.CNOT(q0, q2), cirq.X(q2)], [ cirq.CNOT(q1, q2), cirq.X(q2)], [cirq.CNOT(q0, q2), cirq.CNOT(q1, q2), cirq.X(q2)])\nfor i, ops in enumerate(constant):\n    print('\\nConstant function {}'.format(i))\n    print(cirq.Circuit.from_ops(ops).to_text_diagram(qubit_order=[q0, q1, q2]))\n    print()\n\nfor i, ops in enumerate(balanced):\n    print('\\nBalanced function {}'.format(i))\n    print(cirq.Circuit.from_ops(ops).to_text_diagram(qubit_order=[q0, q1, q2]))\n    \n\n```\n\n    \n    Constant function 0\n    0: \u2500\u2500\u2500\n    \n    1: \u2500\u2500\u2500\n    \n    2: \u2500\u2500\u2500\n    \n    \n    Constant function 1\n    0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    2: \u2500\u2500\u2500X\u2500\u2500\u2500\n    \n    \n    Balanced function 0\n    0: \u2500\u2500\u2500@\u2500\u2500\u2500\n          \u2502\n    1: \u2500\u2500\u2500\u253c\u2500\u2500\u2500\n          \u2502\n    2: \u2500\u2500\u2500X\u2500\u2500\u2500\n    \n    Balanced function 1\n    0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    1: \u2500\u2500\u2500@\u2500\u2500\u2500\n          \u2502\n    2: \u2500\u2500\u2500X\u2500\u2500\u2500\n    \n    Balanced function 2\n    0: \u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n          \u2502\n    1: \u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500\n          \u2502   \u2502\n    2: \u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\n    \n    Balanced function 3\n    0: \u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n          \u2502\n    1: \u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n          \u2502\n    2: \u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\n    \n    Balanced function 4\n    0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    1: \u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n          \u2502\n    2: \u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\n    \n    Balanced function 5\n    0: \u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n          \u2502\n    1: \u2500\u2500\u2500\u253c\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n          \u2502   \u2502\n    2: \u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\n\n\nAn extension of Deutsch's orginal algorithm is the Deutsch-Jozsa algorithm, which can distinguish constant from balanced functions like these using a single query to the oracle.  Write a quantum circuit that can distinguish these \n\n\n```\nsimulator = cirq.Simulator()\ndef your_circuit(oracle):\n    # your code here\n    yield oracle\n    # and here\n    yield cirq.measure(q0, q1, q2)\n\nprint('Your result on constant functions')\nfor oracle in constant:\n    result = simulator.run(cirq.Circuit.from_ops(your_circuit(oracle)), repetitions=10)\n    print(result)\n    \nprint('Your result on balanced functions')\nfor oracle in balanced:\n    result = simulator.run(cirq.Circuit.from_ops(your_circuit(oracle)), repetitions=10)\n    print(result)\n```\n\n    Your result on constant functions\n    0,1,2=0000000000, 0000000000, 0000000000\n    0,1,2=0000000000, 0000000000, 1111111111\n    Your result on balanced functions\n    0,1,2=0000000000, 0000000000, 0000000000\n    0,1,2=0000000000, 0000000000, 0000000000\n    0,1,2=0000000000, 0000000000, 0000000000\n    0,1,2=0000000000, 0000000000, 1111111111\n    0,1,2=0000000000, 0000000000, 1111111111\n    0,1,2=0000000000, 0000000000, 1111111111\n\n\n#### Solution\n\n\n```\n#@title\nsimulator = cirq.Simulator()\ndef your_circuit(oracle):\n    # phase kickback trick\n    yield cirq.X(q2), cirq.H(q2)\n    \n    # equal superposition over input bits\n    yield cirq.H(q0), cirq.H(q1)\n    \n    # query the function\n    yield oracle\n    \n    # interference to get result, put last qubit into |1>\n    yield cirq.H(q0), cirq.H(q1), cirq.H(q2)\n    \n    # a final OR gate to put result in final qubit\n    yield cirq.X(q0), cirq.X(q1), cirq.CCX(q0, q1, q2)\n    yield cirq.measure(q2)\n    \n\nprint('Your result on constant functions')\nfor oracle in constant:\n    result = simulator.run(cirq.Circuit.from_ops(your_circuit(oracle)), repetitions=10)\n    print(result)\n    \nprint('Your result on balanced functions')\nfor oracle in balanced:\n    result = simulator.run(cirq.Circuit.from_ops(your_circuit(oracle)), repetitions=10)\n    print(result)\n```\n\n    Your result on constant functions\n    2=0000000000\n    2=0000000000\n    Your result on balanced functions\n    2=1111111111\n    2=1111111111\n    2=1111111111\n    2=1111111111\n    2=1111111111\n    2=1111111111\n\n\n## Gates\n\nCirq comes with a plethora of different common gates.  Here we show a few of them.\n\n\n```\nq0, q1, q2 = cirq.LineQubit.range(3)\nops = [\n    cirq.X(q0),\n    cirq.Y(q1),\n    cirq.Z(q2),\n    cirq.CZ(q0,q1),\n    cirq.CNOT(q1,q2),\n    cirq.H(q0),\n    cirq.T(q1),\n    cirq.S(q2),\n    cirq.CCZ(q0, q1, q2),\n    cirq.SWAP(q0, q1),\n    cirq.CSWAP(q0, q1, q2),\n    cirq.CCX(q0, q1, q2),\n    cirq.ISWAP(q0, q1),\n    cirq.Rx(0.5 * np.pi)(q0),\n    cirq.Ry(.5 * np.pi)(q1),\n    cirq.Rz(0.5 * np.pi)(q2),\n    (cirq.X**0.5)(q0),\n]\nprint(cirq.Circuit.from_ops(ops))\n```\n\n    0: \u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u00d7\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500Rx(0.5\u03c0)\u2500\u2500\u2500X^0.5\u2500\u2500\u2500\n              \u2502           \u2502   \u2502   \u2502   \u2502   \u2502\n    1: \u2500\u2500\u2500Y\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500T\u2500\u2500\u2500@\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u00d7\u2500\u2500\u2500@\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500Ry(0.5\u03c0)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502       \u2502       \u2502   \u2502\n    2: \u2500\u2500\u2500Z\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500S\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00d7\u2500\u2500\u2500X\u2500\u2500\u2500Rz(0.5\u03c0)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\nFor each of these gates, you can figure out how they act on the computational basis by calling `cirq.unitary` on the gate.  For example\n\n\n```\nprint(cirq.unitary(cirq.CNOT))\n```\n\n    [[1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 1.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 1.+0.j]\n     [0.+0.j 0.+0.j 1.+0.j 0.+0.j]]\n\n\n\n```\nprint(cirq.unitary(cirq.Rx(0.5 * np.pi)))\n```\n\n    [[0.70710678+0.j         0.        -0.70710678j]\n     [0.        -0.70710678j 0.70710678+0.j        ]]\n\n\nFor single qubit gates, we have named gates like `cirq.H` for the Hadmard gate, but probably more useful are the single qubit rotation gates.\n\n$$ \n{\\tt cirq.Rx(\u03b8)}: \\exp(-i \\theta X) = cos \\theta I - i \\sin \\theta X =\\left[ \\begin{array} ~\\cos \\theta & -i \\sin \\theta \\\\ -i \\sin \\theta & \\cos \\theta\\end{array} \\right] \\\\\n$$ \n$$ \n{\\tt cirq.Ry(\u03b8)}: \\exp(-i \\theta Y) = cos \\theta I - i \\sin \\theta Y =\\left[ \\begin{array} ~\\cos \\theta &  -\\sin \\theta \\\\  \\sin \\theta & \\cos \\theta\\end{array} \\right] \\\\\n$$ \n$$ \n{\\tt cirq.Rz(\u03b8)}: \\exp(-i \\theta Z) = cos \\theta I - i \\sin \\theta Z =\\left[ \\begin{array} ~e^{i \\theta} & 0 \\\\ 0 & e^{-i \\theta} \\end{array} \\right] \\\\\n$$ \n\nIn addition to `cirq.unitary` another important method (behind the scenes, anyways) is `cirq.apply_unitary_to_tensor`.  This allows you to apply a unitary gate onto a state.  Of course we could have applied the unitary directly to the state, using `cirq.unitary`.   We'll see below in understanding how these methods are implemented that the `cirq.apply_unitary_to_tensor` can be used to apply the gate more directly onto the state and can save allocations of memory to store the unitary.  \n\nIf we apply `cirq.Rx` to a state we can see how it rotates the state.  To do this let us introduce a new simulate method `simulate_moment_steps`.  This allows us to simulate the circuit `Moment` by `Moment`.  At each point we can access the state.  For example here we can use this to create a circuit that is a series of small `cirq.Rx` rotations and plot the probablility of measureing the state in the $|0\\rangle$ state:\n\n\n```\na = cirq.NamedQubit('a')\ncircuit = cirq.Circuit.from_ops([cirq.Rx(np.pi / 50.0)(a) for theta in range(200)])\nprint('Circuit is a bunch of small rotations about Pauli X axis:')\nprint('{}\\n'.format(circuit))\np0 = []\nz = []\nprint('We step through the circuit and plot the z component of the vector '\n      'as a function of index of the moment being stepped over.')\nfor i, step in enumerate(simulator.simulate_moment_steps(circuit)):\n    prob = np.abs(step.state_vector()) ** 2\n    z.append(i)\n    p0.append(prob[0])\nmatplotlib.pyplot.style.use('seaborn-whitegrid')\nmatplotlib.pyplot.plot(z, p0, 'o')\n```\n\nAbove we have given ourselves direct access to the wave function and calculated the exact probabilities.  Suppose we wanted to sample from the wave function at each point instead.  \n\n\n```\nrepetitions = 100\na = cirq.NamedQubit('a')\ncircuit = cirq.Circuit.from_ops([cirq.Rx(np.pi / 50.0)(a) for theta in range(200)])\np0 = []\nz = []\nfor i, step in enumerate(simulator.simulate_moment_steps(circuit)):\n    samples = step.sample([a], repetitions=repetitions)\n    prob0 = np.sum(samples, axis=0)[0] / repetitions\n    p0.append(prob0)\n    z.append(i)\nmatplotlib.pyplot.style.use('seaborn-whitegrid')\nmatplotlib.pyplot.plot(z, p0, 'o')\n```\n\n### Custom Gate Implementation\n\nSupose there is a gate that you want Cirq to support, but it is not implemented in Cirq.  How do you go about adding a new gate?  \n\nCirq tries to be Pythonic.  One way in which it does this is that it relies on Python's **protocol** pattern.  Protocols are similar to interfaces, in that they define a collection of methods that an object must support to implement a protocol, but different in that this requirement is more informal and not a part of a class or interface declaration.  An object supports a protocol if it implements the methods that the protocol defines.  You're probably familiar with this if you've ever done something like defined your own `Container` in Python.  To do this for an object you simply define the `__contains__`, `__setitem__`, and `__getitem__` methods on your object, and then you can use this object anywere the Container protocol is supported.  \n\nLet's see how this works for defining a custom gate.  The gate we will define is a single qubit gate that has only rational amplitudes. This is based on the famous 3, 4, 5 triangle you may remember from a long ago math class: $3^2 + 4^2 = 5^2$.  Using this observation we can construct normalized vectors and a unitary transform using on ratios of $3$, $4$, and $5$: \n$$\n\\zeta =\\left[ \\begin{array}\n~\\frac{3}{5} & \\frac{4}{5} \\\\\n-\\frac{4}{5} & \\frac{3}{5}\n\\end{array} \\right]\n$$\n\nHere is a simple implementation of this gate.  To do this we simply define a class that inherits from `cirq.SingleQubitGate` and implements the `cirq.SupportsUnitary` protocol by implementing the `_unitary_(self)` method.  We also define a `__str__` representation and by default Cirq will use this gate when priting out the gate in a circuit diagram.\n\n\n\n```\nclass RationalGate(cirq.SingleQubitGate):\n    \n    def _unitary_(self):\n        return np.array([[3 / 5, 4 / 5], [-4 / 5, 3 / 5]])\n    \n    def __str__(self):\n        return '\u03b6'\n\n\na = cirq.NamedQubit('a')\nrg = RationalGate()\nprint(cirq.Circuit.from_ops([rg(a)]))\n```\n\n    a: \u2500\u2500\u2500\u03b6\u2500\u2500\u2500\n\n\n\n```\nprint(cirq.unitary(rg))\n```\n\n    [[ 0.6  0.8]\n     [-0.8  0.6]]\n\n\nLet's check that we can use this gate in a simulation.\n\n\n```\ncircuit = cirq.Circuit.from_ops([rg(a)])\nsimulator = cirq.Simulator()\nresult = simulator.simulate(circuit)\nprint(result.final_state)\n```\n\n    [ 0.6+0.j -0.8+0.j]\n\n\nImplemeting `_unitary_` allows cirq to call `cirq.unitary` on an object.\n\nThere is actually an interesting advanced subtly here, which is that many methods in cirq that ostensibly depend on a gate's unitary try to avoid the `_unitary_` method, because it is extremely inefficient for gates over many qubits.\nIn most cases the method `_apply_unitary_to_tensor_` will be used instead, if it is available.\nThis method allows much more fine grained control on how a unitary is applied to a state, but it is harder to implemented as it is expected to e.g. use the pre-allocated workspace buffer that was given to it.\nAlmost all of the basic gates we have defined in Cirq have this method implemented.\nTL;DR if you need to get performant multiqubit gates you should implement a custom `_apply_unitary_to_tensor_`.\n\n### Exercise: Custom Controlled Rx gate\n\nRecall that the `cirq.Rx` gate is a rotation about the $X$ pauli axis:\n$$ \n{\\tt cirq.Rx(\u03b8)}: \\exp(-i \\theta X) = cos \\theta I - i \\sin \\theta X =\\left[ \\begin{array} ~\\cos \\theta & -i \\sin \\theta \\\\ -i \\sin \\theta & \\cos \\theta\\end{array} \\right] \\\\\n$$ \n\nAs an exercise, create a two qubit controlled `cirq.Rx` gate:\n$$\n{\\tt CRx(\\theta)}:\n\\left[\\begin{array}\n~1 & 0 & 0 & 0 \\\\\n0 & 1 & 0 & 0  \\\\\n0 & 0 & \\cos \\theta & -i \\sin \\theta \\\\\n0 & 0 & -i \\sin \\theta & \\cos \\theta\n\\end{array} \\right]\n$$\n\n\n```\nclass CRx(cirq.TwoQubitGate):\n\n    def __init__(self, theta):\n        self.theta = theta\n\n    def _unitary_(self):\n      return np.array([\n        \n      ])\n    \n\n    \n    pass\n\n    # Get this to print nicely in an ASCII circuit, you should also\n    # implement the _circuit_diagram_info_ method from the\n    # SupportsCircuitDiagramInfo protocol. You can return a tuple\n    # of strings from this method.\n\n\nprint(np.around(cirq.unitary(CRx(0.25 * np.pi))))     \n```\n\n    []\n\n\n\n```\n# Also get your class to print a circuit correctly.\n\na = cirq.NamedQubit('a')\nb = cirq.NamedQubit('b')\nop = CRx(0.25 * np.pi)(a, b)\nprint(cirq.Circuit.from_ops([op]))\n\n```\n\n    a: \u2500\u2500\u2500<__main__.CRx object at 0x7f6f734a0128>\u2500\u2500\u2500\n          \u2502\n    b: \u2500\u2500\u2500#2\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n#### Solution\n\n\n```\nclass CRx(cirq.TwoQubitGate):\n\n    def __init__(self, theta):\n        self.theta = theta\n\n    def _unitary_(self):\n      return np.array([\n          [1, 0, 0, 0],\n          [0, 1, 0, 0],\n          [0, 0, np.cos(self.theta), -1j * np.sin(self.theta)],\n          [0, 0, -1j * np.sin(self.theta), np.cos(self.theta)]\n      ])\n    \n    def _circuit_diagram_info_(self, args):\n        return '@', 'Rx({}\u03c0)'.format(self.theta / np.pi)\n    \n\nprint('cirq.unitary on the gate yields:')\nprint(np.around(cirq.unitary(CRx(0.25 * np.pi))))\nprint()\n\na = cirq.NamedQubit('a')\nb = cirq.NamedQubit('b')\nop = CRx(0.25 * np.pi)(a, b)\nprint('Circuit diagram:')\nprint(cirq.Circuit.from_ops([op]))\n```\n\n    cirq.unitary on the gate yields:\n    [[1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 1.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 1.+0.j 0.-1.j]\n     [0.+0.j 0.+0.j 0.-1.j 1.+0.j]]\n    \n    Circuit diagram:\n    a: \u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n          \u2502\n    b: \u2500\u2500\u2500Rx(0.25\u03c0)\u2500\u2500\u2500\n\n\n### Gate decompositions\n\nIn many context, the notion of what gate you can apply is defined either by the physical hardware you are running or perhaps on the quantum error correcting code you are working with.  In quantum computing we typically talk about **gate sets** and work with respect to a given gate set.  Cirq supports gate decomposition via the `decompose` protocol.  Below we show how one can construct a gate that can be decomposed into two gates.\n\n\n```\nclass HXGate(cirq.SingleQubitGate):\n    \n    def _decompose_(self, qubits):\n        return cirq.H(*qubits), cirq.X(*qubits)\n    \n    def __str__(self):\n        return 'HX'\n    \nHX = HXGate()\n\na = cirq.NamedQubit('a')\ncircuit = cirq.Circuit.from_ops([HX(a)])\nprint(circuit)\nprint(cirq.Circuit.from_ops(cirq.decompose(circuit)))\n```\n\n    a: \u2500\u2500\u2500HX\u2500\u2500\u2500\n    a: \u2500\u2500\u2500Y^0.5\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\n\n\nNote that this not only decomposed the `HX` gate into `H` and `X`, it also decomposed `H` into `Y**0.5` and `X`.  In order to decompose only once, one can use `cirq.decompose_once`:\n\n\n```\nprint(cirq.Circuit.from_ops(cirq.decompose_once(HX(a))))\n```\n\n    a: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\n\n\nWhen we define a gate, it is good practice to give a default decompose in terms of gates in `common_gates`.  However often you will want to change this decomposition at run time for the specific hardware or context you are working in.  To do this we can define an interceptor function which does this decomposition before falling back to the default.\n\n\n```\ndef my_decompose(op):\n    if isinstance(op, cirq.GateOperation) and isinstance(op.gate, HXGate):\n        return cirq.Z(*op.qubits), cirq.H(*op.qubits)\n\ncirq.Circuit.from_ops(cirq.decompose(HX(a), intercepting_decomposer=my_decompose))\n```\n\n\n\n\n<pre style=\"overflow: auto; white-space: pre;\">a: \u2500\u2500\u2500Z\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500X\u2500\u2500\u2500</pre>\n\n\n\nYou can also define a predicate that says which gates to keep without decomposing further.\nThe default predicate is to only keep gates that cannot be decomposed.\n\n\n```\ndef keep_h_and_x(op):\n    return isinstance(op, cirq.GateOperation) and op.gate in [cirq.H, cirq.X]\n\nprint(cirq.decompose(HX(a), keep=keep_h_and_x))\n```\n\n    [cirq.H.on(cirq.NamedQubit('a')), cirq.X.on(cirq.NamedQubit('a'))]\n\n\n## Parameterized Circuits\n\nIn addition to circuit gates with fixed values, Cirq also supports parameterized gates with symbolic values via `sympy`. These are placeholder values, such as `sympy.Symbol('x')`, that will only be resolved at *run-time*. For simulators these values are resolved by providing a `ParamResolver`.  A `ParamResolver` provides a map from the `Symbol`'s name to its assigned value.  Plain python dictionaries can be used whenever a `ParamResolver` is needed.\n\n\n```\nimport sympy as sp\n\na = cirq.NamedQubit('a')\nb = cirq.NamedQubit('b')\nsimulator = cirq.Simulator()\n\nval = sp.Symbol('s')\npow_x_gate = cirq.X**val\ncircuit = cirq.Circuit()\ncircuit.append([pow_x_gate(a), pow_x_gate(b)])\nprint('Circuit with parameterized gates:')\nprint(circuit)\nprint()\nfor y in range(5):\n    result = simulator.simulate(circuit, param_resolver={'s': y / 4.0})\n    print('s={}: {}'.format(y, np.around(result.final_state, 2)))\n```\n\n    Circuit with parameterized gates:\n    a: \u2500\u2500\u2500X^s\u2500\u2500\u2500\n    \n    b: \u2500\u2500\u2500X^s\u2500\u2500\u2500\n    \n    s=0: [1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n    s=1: [ 0.6 +0.6j   0.25-0.25j  0.25-0.25j -0.1 -0.1j ]\n    s=2: [0. +0.5j 0.5+0.j  0.5+0.j  0. -0.5j]\n    s=3: [-0.1 +0.1j   0.25+0.25j  0.25+0.25j  0.6 -0.6j ]\n    s=4: [0.+0.j 0.+0.j 0.+0.j 1.+0.j]\n\n\nHere we see that the `Symbol` is used in two gates, and then the resolver provides this value at run time.\n\nParameterized values are most useful in defining what we call a `Study`.  A `Study` is a collection of trials, where each  trial is a run with a particular set of configurations and which may be run repeatedly.  Running a study returns a list of `TrialResult`s per set of fixed parameter values and repetitions.  Example:\n\n\n\n```\nresolvers = [cirq.ParamResolver({'s': y / 8.0}) for y in range(9)]\ncircuit = cirq.Circuit()\ncircuit.append([pow_x_gate(a), pow_x_gate(b)])\ncircuit.append([cirq.measure(a), cirq.measure(b)])\nresults = simulator.run_sweep(program=circuit,\n                              params=resolvers,\n                              repetitions=10)\nfor i, result in enumerate(results):\n    print('params: {}\\n{}'.format(result.params.param_dict, result))\n```\n\n    params: {'s': 0.0}\n    a=0000000000\n    b=0000000000\n    params: {'s': 0.125}\n    a=0000000000\n    b=0000000000\n    params: {'s': 0.25}\n    a=0011010001\n    b=0000000000\n    params: {'s': 0.375}\n    a=0010001000\n    b=0111011000\n    params: {'s': 0.5}\n    a=0000111100\n    b=1010100011\n    params: {'s': 0.625}\n    a=1100011110\n    b=0101110101\n    params: {'s': 0.75}\n    a=1111111111\n    b=1111111101\n    params: {'s': 0.875}\n    a=1111111110\n    b=1111111111\n    params: {'s': 1.0}\n    a=1111111111\n    b=1111111111\n\n\nAbove we passed in a list of `ParamResolver`s to the `params` parameter of `run_sweep`.  But one can also pass in a `Sweepable`.  There are some useful methods for generating `Sweepable`s, for example to generate an equally spaced set of param resolvers one can use `Linspace`\n\n\n\n```\nlinspace = cirq.Linspace(start=0, stop=1.0, length=11, key='x')\nfor p in linspace:\n    print(p)\n```\n\n    cirq.ParamResolver(OrderedDict([('x', 0.0)]))\n    cirq.ParamResolver(OrderedDict([('x', 0.1)]))\n    cirq.ParamResolver(OrderedDict([('x', 0.2)]))\n    cirq.ParamResolver(OrderedDict([('x', 0.3)]))\n    cirq.ParamResolver(OrderedDict([('x', 0.4)]))\n    cirq.ParamResolver(OrderedDict([('x', 0.5)]))\n    cirq.ParamResolver(OrderedDict([('x', 0.6)]))\n    cirq.ParamResolver(OrderedDict([('x', 0.7)]))\n    cirq.ParamResolver(OrderedDict([('x', 0.8)]))\n    cirq.ParamResolver(OrderedDict([('x', 0.9)]))\n    cirq.ParamResolver(OrderedDict([('x', 1.0)]))\n\n\n### Exercise: Rotate a qubit\n\nLet's do the equivalent of a Rabi-flop experiment.  That is lets apply an `PowXGate` rotating about the `X` axis for a linearly spaced set of values followed by a computational basis measurement.  The end result should be a plot of the sampled fraction that were $|1\\rangle$ as a function of gates of $X^t$ for $t$ between 0 and $1$ for 100 values of $t$ and each result sampled 100 times.\n\nYou can use matplotlib to plot this, see example plot code below.\n\n\n```\nimport matplotlib.pyplot as plt\nplt.plot([1, 2, 3], [5, 3, 10])\n```\n\n\n```\n# Insert your code here\n```\n\n## Noise\n\nIn addition to circuits with unitary gates, Cirq also has support for modeling noisy quantum evolutions. This is useful when modeling what will happen when running on actual hardware.\n\nCirq currently supports noise that fits within the context of *operator sum representations* of noise (a.k.a quantum operations, quantum dyanamical maps, superoperators, etc).  This formalism models the evolution of a density matrix via \n$$\\rho \\rightarrow \\sum_k A_k \\rho A_k^\\dagger$$\nwhere the $A_k$ are *Krauss operators*.  These operators are not necessarily unitary and satisfy the property\n$$ \\sum_k A_k^\\dagger A_k = I$$\n\nAn example of a noise operator is the depolarizing channel on one qubit.  This takes\n$$\\rho \\rightarrow (1-p) \\rho + \\frac{p}{3} (X \\rho X + Y \\rho Y + Z \\rho Z)$$\nIn Cirq we can define such a channel and use it in a quantum circuit:\n\n\n```\ncircuit = cirq.Circuit.from_ops(cirq.depolarize(0.2)(a), cirq.measure(a))\nprint(circuit)\n```\n\n    a: \u2500\u2500\u2500D(0.2)\u2500\u2500\u2500M\u2500\u2500\u2500\n\n\nPreviously we saw that gates could implement that `_unitary_` protocol, and by doing so they could be used to perform wave function simulation.  For noise the gates implement the `_channel_` protocol.  Classes that implement this protocol return the Krauss operators on their `_channel_` method.  Thus\n\n\n```\nfor i, krauss in enumerate(cirq.channel(cirq.depolarize(0.2))):\n    print('{}th krauss operator is {}'.format(i, krauss))\nprint()\n\nfor i, krauss in enumerate(cirq.channel(cirq.depolarize(0.2))):\n    pauli_ex = cirq.expand_matrix_in_orthogonal_basis(krauss, cirq.PAULI_BASIS)\n    print('{}th krauss operator is {}'.format(i, pauli_ex))\n```\n\n    0th krauss operator is [[0.89442719 0.        ]\n     [0.         0.89442719]]\n    1th krauss operator is [[0.        +0.j 0.25819889+0.j]\n     [0.25819889+0.j 0.        +0.j]]\n    2th krauss operator is [[0.+0.j         0.-0.25819889j]\n     [0.+0.25819889j 0.+0.j        ]]\n    3th krauss operator is [[ 0.25819889+0.j  0.        +0.j]\n     [ 0.        +0.j -0.25819889+0.j]]\n    \n    0th krauss operator is 0.8944271909999159*I\n    1th krauss operator is 0.2581988897471611*X\n    2th krauss operator is 0.2581988897471611*Y\n    3th krauss operator is 0.2581988897471611*Z\n\n\nIn addition to the wave function simulator, Cirq also has a density matrix simulator.  Instead of keeping track of the wave function this simulator keeps track of the density matrix.  It has the same `run` and `simulate` type methods.  For example we can use this to simulate depolarizing channel and return the final density matrix of the system\n\n\n```\ncircuit = cirq.Circuit.from_ops(cirq.depolarize(0.2)(a))\nprint('Circuit:\\n{}\\n'.format(circuit))\nsimulator = cirq.DensityMatrixSimulator()\nmatrix = simulator.simulate(circuit).final_density_matrix\nprint('Final density matrix:\\n{}'.format(matrix))\n```\n\n    Circuit:\n    a: \u2500\u2500\u2500D(0.2)\u2500\u2500\u2500\n    \n    Final density matrix:\n    [[0.8666666 +0.j 0.        +0.j]\n     [0.        +0.j 0.13333333+0.j]]\n\n\nOne thing to note is that the density matrix simulator simulates measurement statistically, and not as a channel where the outcome is not known.  Thus for example \n\n\n```\ncircuit = cirq.Circuit.from_ops(cirq.depolarize(0.2)(a), cirq.measure(a))\nsimulator = cirq.DensityMatrixSimulator()\nfor _ in range(5):\n    print(simulator.simulate(circuit).final_density_matrix)\n```\n\n    [[0.99999994+0.j 0.        +0.j]\n     [0.        +0.j 0.        +0.j]]\n    [[0.99999994+0.j 0.        +0.j]\n     [0.        +0.j 0.        +0.j]]\n    [[0.99999994+0.j 0.        +0.j]\n     [0.        +0.j 0.        +0.j]]\n    [[0.99999994+0.j 0.        +0.j]\n     [0.        +0.j 0.        +0.j]]\n    [[0.99999994+0.j 0.        +0.j]\n     [0.        +0.j 0.        +0.j]]\n\n\n### Monte carlo simulations\n\nDensity matrix simulations are more expensive than pure state wave function simulations.  However some channels allow an interpreation of randomly applying one of a fixed set of unitaries with differing probabilites.  For example the depolarizing channel above can be interpretted as: with probability $1-p$ apply the identity to the state and with probability $p$ apply one of the three Pauli matrices $X$, $Y$, or $Z$ with equal probability.  Channels that can be interpretted in this form can be simulating using a wave function simulator: when this channel is simulated the simulation will sample a unitary with the appropriate probability.  \n\nFor channels of these type, the channel can, instead of implementing the `_channel_` protocol, implement the `_mixture_` protocol:\n\n\n```\nfor p, u in cirq.mixture(cirq.depolarize(0.2)):\n    print('prob={}\\nunitary\\n{}\\n'.format(p, u))\n```\n\n    prob=0.8\n    unitary\n    [[1. 0.]\n     [0. 1.]]\n    \n    prob=0.06666666666666667\n    unitary\n    [[0.+0.j 1.+0.j]\n     [1.+0.j 0.+0.j]]\n    \n    prob=0.06666666666666667\n    unitary\n    [[0.+0.j 0.-1.j]\n     [0.+1.j 0.+0.j]]\n    \n    prob=0.06666666666666667\n    unitary\n    [[ 1.+0.j  0.+0.j]\n     [ 0.+0.j -1.+0.j]]\n    \n\n\nIn fact the depolarizing channel does not implement `_channel_`.  Instead it only implements `_mixture_` and the `cirq.channel` method notices this and derives the channel from the mixture.\n\n\n```\nd = cirq.depolarize(0.2)\nprint('does cirq.depolarize(0.2) have _channel_? {}'.format('yes' if getattr(d, '_channel_', None) else 'no'))\nprint('does cirq.depolarize(0.2) have _mixture_? {}'.format('yes' if getattr(d, '_mixture_', None) else 'no'))\n```\n\n    does cirq.depolarize(0.2) have _channel_? no\n    does cirq.depolarize(0.2) have _mixture_? yes\n\n\nWhen channels implement mixture then, as we said, we can use the wave function simulator:\n\n\n```\ncircuit = cirq.Circuit.from_ops(cirq.depolarize(0.5).on(a), cirq.measure(a))\nsimulator = cirq.Simulator()\nresult = simulator.run(circuit, repetitions=10)\nprint(result)\n```\n\n    a=1010110000\n\n\n### Adding Noise to Circuits and Simulations\n\nTo add noise to circuits or during simulations, we provide the notion of a `NoiseModel`.  A `NoiseModel` may add noise operation by operation, or it may add noise moment by moment, or it may add noise across a list of moments.\n\nFor example we can define a noise model that add a single qubit depolarizing for every qubit in each moment.  \n\n\n```\nnoise = cirq.ConstantQubitNoiseModel(cirq.depolarize(0.2))\ncircuit = cirq.Circuit.from_ops(cirq.H(a), cirq.CNOT(a, b), cirq.measure(a, b))\nprint('Circuit with no noise:\\n{}\\n'.format(circuit))\n\nsystem_qubits = sorted(circuit.all_qubits())\nnoisy_circuit = cirq.Circuit()\nfor moment in circuit:\n    noisy_circuit.append(noise.noisy_moment(moment, system_qubits))\nprint('Circuit with noise:\\n{}'.format(noisy_circuit))\n\n```\n\n    Circuit with no noise:\n    a: \u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500M\u2500\u2500\u2500\n              \u2502   \u2502\n    b: \u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500M\u2500\u2500\u2500\n    \n    Circuit with noise:\n    a: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500D(0.2)\u2500\u2500\u2500@\u2500\u2500\u2500D(0.2)\u2500\u2500\u2500M\u2500\u2500\u2500D(0.2)\u2500\u2500\u2500\n                            \u2502            \u2502\n    b: \u2500\u2500\u2500D(0.2)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500D(0.2)\u2500\u2500\u2500M\u2500\u2500\u2500D(0.2)\u2500\u2500\u2500\n\n\n\n```\nnoise = cirq.ConstantQubitNoiseModel(cirq.depolarize(0.2))\ncircuit = cirq.Circuit.from_ops(cirq.H(a), cirq.CNOT(a, b), cirq.measure(a, b))\n\nsimulator = cirq.DensityMatrixSimulator(noise=noise)\nfor i, step in enumerate(simulator.simulate_moment_steps(circuit)):\n    print('After step {} state was\\n{}\\n'.format(i, step.density_matrix()))\n```\n\n    After step 0 state was\n    [[0.4333333 +0.j 0.        +0.j 0.31777775+0.j 0.        +0.j]\n     [0.        +0.j 0.06666666+0.j 0.        +0.j 0.04888888+0.j]\n     [0.31777775+0.j 0.        +0.j 0.4333333 +0.j 0.        +0.j]\n     [0.        +0.j 0.04888888+0.j 0.        +0.j 0.06666666+0.j]]\n    \n    After step 1 state was\n    [[0.34859255+0.j 0.        +0.j 0.        +0.j 0.17089382+0.j]\n     [0.        +0.j 0.15140739+0.j 0.02629136+0.j 0.        +0.j]\n     [0.        +0.j 0.02629136+0.j 0.15140739+0.j 0.        +0.j]\n     [0.17089382+0.j 0.        +0.j 0.        +0.j 0.34859255+0.j]]\n    \n    After step 2 state was\n    [[0.11555553+0.j 0.        +0.j 0.        +0.j 0.        +0.j]\n     [0.        +0.j 0.01777777+0.j 0.        +0.j 0.        +0.j]\n     [0.        +0.j 0.        +0.j 0.75111103+0.j 0.        +0.j]\n     [0.        +0.j 0.        +0.j 0.        +0.j 0.11555554+0.j]]\n    \n\n\n## Devices\n\nNISQ algorithms work in a regime where every gate counts.  A key philosophy behind Cirq is that we believe the details of the hardware, the performance characteristics, as well as device constraints, will be key to getting the most out of NISQ algorithms.  Towards this end these hardware features are contained in the `Device` class.\n\nFor example, here is Google's Bristleconde device\n\n\n```\nprint(cirq.google.Bristlecone)\n```\n\n                                                 (0, 5)\u2500\u2500\u2500\u2500(0, 6)\n                                                 \u2502         \u2502\n                                                 \u2502         \u2502\n                                        (1, 4)\u2500\u2500\u2500(1, 5)\u2500\u2500\u2500\u2500(1, 6)\u2500\u2500\u2500\u2500(1, 7)\n                                        \u2502        \u2502         \u2502         \u2502\n                                        \u2502        \u2502         \u2502         \u2502\n                               (2, 3)\u2500\u2500\u2500(2, 4)\u2500\u2500\u2500(2, 5)\u2500\u2500\u2500\u2500(2, 6)\u2500\u2500\u2500\u2500(2, 7)\u2500\u2500\u2500(2, 8)\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                      (3, 2)\u2500\u2500\u2500(3, 3)\u2500\u2500\u2500(3, 4)\u2500\u2500\u2500(3, 5)\u2500\u2500\u2500\u2500(3, 6)\u2500\u2500\u2500\u2500(3, 7)\u2500\u2500\u2500(3, 8)\u2500\u2500\u2500(3, 9)\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n             (4, 1)\u2500\u2500\u2500(4, 2)\u2500\u2500\u2500(4, 3)\u2500\u2500\u2500(4, 4)\u2500\u2500\u2500(4, 5)\u2500\u2500\u2500\u2500(4, 6)\u2500\u2500\u2500\u2500(4, 7)\u2500\u2500\u2500(4, 8)\u2500\u2500\u2500(4, 9)\u2500\u2500\u2500(4, 10)\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n    (5, 0)\u2500\u2500\u2500(5, 1)\u2500\u2500\u2500(5, 2)\u2500\u2500\u2500(5, 3)\u2500\u2500\u2500(5, 4)\u2500\u2500\u2500(5, 5)\u2500\u2500\u2500\u2500(5, 6)\u2500\u2500\u2500\u2500(5, 7)\u2500\u2500\u2500(5, 8)\u2500\u2500\u2500(5, 9)\u2500\u2500\u2500(5, 10)\u2500\u2500\u2500(5, 11)\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n             (6, 1)\u2500\u2500\u2500(6, 2)\u2500\u2500\u2500(6, 3)\u2500\u2500\u2500(6, 4)\u2500\u2500\u2500(6, 5)\u2500\u2500\u2500\u2500(6, 6)\u2500\u2500\u2500\u2500(6, 7)\u2500\u2500\u2500(6, 8)\u2500\u2500\u2500(6, 9)\u2500\u2500\u2500(6, 10)\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n                      (7, 2)\u2500\u2500\u2500(7, 3)\u2500\u2500\u2500(7, 4)\u2500\u2500\u2500(7, 5)\u2500\u2500\u2500\u2500(7, 6)\u2500\u2500\u2500\u2500(7, 7)\u2500\u2500\u2500(7, 8)\u2500\u2500\u2500(7, 9)\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                               (8, 3)\u2500\u2500\u2500(8, 4)\u2500\u2500\u2500(8, 5)\u2500\u2500\u2500\u2500(8, 6)\u2500\u2500\u2500\u2500(8, 7)\u2500\u2500\u2500(8, 8)\n                                        \u2502        \u2502         \u2502         \u2502\n                                        \u2502        \u2502         \u2502         \u2502\n                                        (9, 4)\u2500\u2500\u2500(9, 5)\u2500\u2500\u2500\u2500(9, 6)\u2500\u2500\u2500\u2500(9, 7)\n                                                 \u2502         \u2502\n                                                 \u2502         \u2502\n                                                 (10, 5)\u2500\u2500\u2500(10, 6)\n\n\nIn a future version, we intend for each `Device` to define a noise model.\n\n`Device`s also contain more information about the timing of the device.  For example here we can calculate the duration of an `Exp11Gate` on the `Bristlecone` device\n\n\n```\nbrissy = cirq.google.Bristlecone\nop = cirq.X.on(cirq.GridQubit(5, 5))\nprint(brissy.duration_of(op))\n```\n\n    20ns\n\n\nAnother property of devices is that they can be used to enforce constraints from the hardware, both checking that these constraints are satisfied, but also enforcing the constraints on the device.  For example on the `Bristlecone` device a two qubit gate has the property that one cannot simultaneously perform a pair of two qubit gates that act on adjacent qubits. So for example if we create such a `Circuit` and validate it using the device it will yell at us\n\n\n```\nq55 = cirq.GridQubit(5, 5)\nq56 = cirq.GridQubit(5, 6)\nq66 = cirq.GridQubit(6, 6)\nq67 = cirq.GridQubit(6, 7)\nops = [cirq.CZ(q55, q56), cirq.CZ(q66, q67)]\ncircuit = cirq.Circuit.from_ops(ops)\nprint(circuit)\nprint('But when we validate it against the device:')\n# cirq.google.Bristlecone.validate_circuit(circuit)\n# (this should throw an error)\n```\n\n    (5, 5): \u2500\u2500\u2500@\u2500\u2500\u2500\n               \u2502\n    (5, 6): \u2500\u2500\u2500@\u2500\u2500\u2500\n    \n    (6, 6): \u2500\u2500\u2500@\u2500\u2500\u2500\n               \u2502\n    (6, 7): \u2500\u2500\u2500@\u2500\u2500\u2500\n    But when we validate it against the device:\n\n\nBut more interestingly we could have passed the device into the `Circuit` and it will perform the creation of the circuit (using the insertion semanics as described above) such that the device cannot violate the constraints.\n\n\n```\nops = [cirq.CZ(q55, q56), cirq.CZ(q66, q67)]\ncircuit = cirq.Circuit(device=cirq.google.Bristlecone)\ncircuit.append(ops)\nprint(circuit)\n\n```\n\n    (5, 5): \u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n               \u2502\n    (5, 6): \u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    (6, 6): \u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\n                   \u2502\n    (6, 7): \u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\n\n\n### Exercise: Make a Device\n\nConstruct a device that acts on a square sized lattice, and only allows Hadamard, CZ, and measurement gates.\n\n\n```\n# your code here\n```\n\n## Compiling / Optimizing\n\nCirq's philosophy for what are often called compilation steps is slightly non-traditional.  In particular we believe that NISQ devices perform so few gates that many compiliations will be one or a few passes. A useful class of optimization codee for this is the `PointOptimizer`. For example here is a `PointOptimizer` that recognizes that a `X` gate followed by a `Z` gate is equivalent to a `Y` gate\n\n\n```\nclass XZOptimizer(cirq.PointOptimizer):\n    \"\"\"Replaces an X followed by a Z with a Y.\"\"\"\n    \n    def optimization_at(self, circuit, index, op):\n        # Is the gate an X gate?\n        if isinstance(op, cirq.GateOperation) and (op.gate == cirq.X):\n            next_op_index = circuit.next_moment_operating_on(op.qubits, index + 1)\n            qubit = op.qubits[0]\n            if next_op_index is not None:\n                next_op = circuit.operation_at(qubit, next_op_index)\n                if isinstance(next_op, cirq.GateOperation) and  (next_op.gate == cirq.Z):\n                    new_op = cirq.Y.on(qubit)\n                    return cirq.PointOptimizationSummary(\n                        clear_span = next_op_index - index + 1,\n                        clear_qubits=op.qubits, \n                        new_operations=[new_op])\n        \nopt = XZOptimizer()\ncircuit = cirq.Circuit.from_ops(cirq.X(a), cirq.Z(a), cirq.CZ(a, b), cirq.X(a))\nprint('Before\\n{}\\n'. format(circuit))\nopt.optimize_circuit(circuit)\nprint('After\\n{}'.format(circuit))\n```\n\n    Before\n    a: \u2500\u2500\u2500X\u2500\u2500\u2500Z\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500\n                  \u2502\n    b: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    After\n    a: \u2500\u2500\u2500Y\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500\n                  \u2502\n    b: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n### Exercise: Simplify flipped CNOTs\n\nWrite an PointOptimizer that performs (greedily) the simplification that\n\n```\na: \u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\n          \u2502\nb: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\n```\nis equal to\n\n\n```\na: \u2500\u2500\u2500X\u2500\u2500\u2500\n      \u2502\nb: \u2500\u2500\u2500@\u2500\u2500\u2500\n```\n\n\n\n```\n# Insert your code here.\n```\n\n\n```\n# Here is a circuit to test this on.\ncircuit = cirq.Circuit.from_ops(cirq.H(a), cirq.H(a), cirq.H(b), \n                                cirq.CNOT(a, b), cirq.H(a), cirq.H(b), \n                                cirq.CZ(a, b))\n# Instantiate your optimizer\n# my_opt = \n\n# And check that it worked.\n# print(my_opt.optimizer_circuit(circuit))\n```\n\n## Google's Xmon Gates\n\nWe built Cirq at Google because we thought that it was important that hardware details flow up through the level of abstractions in a framework for NISQ algorithms.  And we also built it because Google has a class of superconducting qubit devices where we want to explore NISQ algorithms.  \n\nWhat sort of gates does the xmon architecture support?  At the hardware level the basic gate set is rotations about the Pauli $Z$ axis\n$$\\exp(-iZt) = \\left[ \n\\begin{array}\ne^{it} & 0 \\\\\n0 & e^{-it}\n\\end{array}\n\\right]$$\nRotations about any axis in the Pauli $X$ and $Y$ plane:\n$$\\exp(-i(\\cos \\theta X + \\sin \\theta Y) t) = \n\\left[\n\\begin{array}\n\\cos t & -i\\sin t e^{-i \\theta} \\\\\n-i\\sin t e^{i \\theta} & \\cos t\n\\end{array}\n\\right]\n$$\nThe two qubit gate is a phase about the $|11\\rangle$ state:\n$$\n\\exp(-it |11\\rangle \\langle 11|) =\n\\left[ \n\\begin{array}\n1 & 0 & 0 & 0 \\\\\n0 & 1 & 0 & 0 \\\\\n0 & 0 & 1 & 0 \\\\\n0 & 0 & 0 & \\exp(-it)\n\\end{array}\n\\right]\n$$\nAnd finally a measurement in the computational basis.\n\nMany of the common gates in Cirq are directly accessible on this hardware.  To check whether the gate you are using is in the xmon gate set, one can use `is_native_xmon_op`.\n\n\n\n```\ncirq.google.is_native_xmon_op(cirq.X.on(cirq.NamedQubit('a')))\n```\n\n\n\n\n    True\n\n\n\n\n```\ncirq.google.is_native_xmon_op(cirq.CNOT.on(cirq.NamedQubit('a'), cirq.NamedQubit('b')))\n```\n\n\n\n\n    False\n\n\n\nWhen a gate is not a native xmon gate, Cirq can often convert it to an xmon native gate;\n\n\n```\nconverter = cirq.google.ConvertToXmonGates()\nconverted = converter.convert(cirq.CNOT.on(cirq.NamedQubit('a'), cirq.NamedQubit('b')))\nprint(cirq.Circuit.from_ops(converted))\n```\n\n    a: \u2500\u2500\u2500Z^0.75\u2500\u2500\u2500\u2500X^0.5\u2500\u2500\u2500\u2500S^-1\u2500\u2500\u2500Y^-0.5\u2500\u2500\u2500@\u2500\u2500\u2500S^-1\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500\u2500\u2500Z^-0.75\u2500\u2500\u2500\n                                             \u2502\n    b: \u2500\u2500\u2500X^-0.25\u2500\u2500\u2500Y^-0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500S^-1\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500X^-0.25\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\nThis isn't very optimized because what it has done is first rely on the decompose of `CNOT` and then decomposed each of these into native xmon gates.  There are many tricks that one can use to simplify xmon gates.  To apply many of these one can use the `cirq.google.optimize_from_xmon` method:\n\n\n```\ncircuit = cirq.Circuit.from_ops([cirq.CNOT.on(cirq.NamedQubit('a'), cirq.NamedQubit('b'))])\nprint(cirq.google.optimized_for_xmon(circuit))\n\n```\n\n    a: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                              \u2502\n    b: \u2500\u2500\u2500PhasedX(-0.5)^0.5\u2500\u2500\u2500@\u2500\u2500\u2500PhasedX(0.5)^0.5\u2500\u2500\u2500\n\n\nBecause xmon gates can be executed on Google hardware, they will need to be transmitted as machine code to the quantum computer.  This means that they have a serialized form.  We use protobuffers as the serialization.  To see what this form looks like use `cirq.google.gate_to_proto_dict`:\n\n\n```\ncirq.google.gate_to_proto_dict(cirq.X, [cirq.GridQubit(5, 5)])\n```\n\n\n\n\n    {'exp_w': {'axis_half_turns': {'raw': 0.0},\n      'half_turns': {'raw': 1.0},\n      'target': {'col': 5, 'row': 5}}}\n\n\n\n# Other interesting things in Cirq\n\n**Experiments**. The `cirq.experiments` package can perform and plot the results of some basic experiments for understanding how well a system is performing.\n\n\n\n```\nresult = cirq.experiments.rabi_oscillations(\n    sampler=cirq.Simulator(),  # In the future, sampler could point at real hardware.\n    qubit=cirq.LineQubit(0)\n)\nresult.plot()\n```\n\n**Testing**. The `cirq.testing` package has useful debugging and testing methods like `cirq.testing.assert_implements_consistent_protocols` and `cirq.testing.assert_allclose_up_to_global_phase`.\n\n\n\n```\nclass InconsistentXGate(cirq.SingleQubitGate):\n\n    def _decompose_(self, qubits):\n        yield cirq.H(qubits[0])\n        yield cirq.Z(qubits[0])\n        yield cirq.H(qubits[0])\n\n    def _unitary_(self):\n        return np.array([[0, -1j], [1j, 0]])  # Oops! Y instead of X!\n\n# cirq.testing.assert_decompose_is_consistent_with_unitary(InconsistentXGate())\n```\n\n**Export**. You can export a circuit as QASM.\n\n\n```\na, b, c = cirq.LineQubit.range(3)\ncircuit = cirq.Circuit.from_ops(cirq.H(a), cirq.H(c), cirq.CNOT(a, b), cirq.CCZ(a, b, c))\nprint(circuit.to_qasm())\n```\n\n    // Generated from Cirq v0.5.0\n    \n    OPENQASM 2.0;\n    include \"qelib1.inc\";\n    \n    \n    // Qubits: [0, 1, 2]\n    qreg q[3];\n    \n    \n    h q[0];\n    h q[2];\n    cx q[0],q[1];\n    h q[2];\n    ccx q[0],q[1],q[2];\n    h q[2];\n    \n\n\nYou can also turn a circuit into a link to the drag-and-drop web simulation Quirk (though somewhat inconveniently).\n\n\n```\nfrom cirq.contrib.quirk.export_to_quirk import circuit_to_quirk_url\nprint(circuit_to_quirk_url(circuit))\n```\n\n    http://algassert.com/quirk#circuit=%7B%22cols%22%3A%5B%5B%22H%22%2C1%2C%22H%22%5D%2C%5B%22%E2%80%A2%22%2C%22X%22%5D%2C%5B%22%E2%80%A2%22%2C%22%E2%80%A2%22%2C%22Z%22%5D%5D%7D\n\n", "meta": {"hexsha": "7856c4b0fcce6f4891cf251e368490717ba45717", "size": 174613, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/educators/intro.ipynb", "max_stars_repo_name": "lilies/Cirq", "max_stars_repo_head_hexsha": "519b8b70ba4d2d92d1c034c398161ebdbd23e2e7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-06T17:06:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-06T17:06:10.000Z", "max_issues_repo_path": "docs/tutorials/educators/intro.ipynb", "max_issues_repo_name": "lilies/Cirq", "max_issues_repo_head_hexsha": "519b8b70ba4d2d92d1c034c398161ebdbd23e2e7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/tutorials/educators/intro.ipynb", "max_forks_repo_name": "lilies/Cirq", "max_forks_repo_head_hexsha": "519b8b70ba4d2d92d1c034c398161ebdbd23e2e7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-14T15:29:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T15:29:29.000Z", "avg_line_length": 53.398470948, "max_line_length": 18140, "alphanum_fraction": 0.6816903667, "converted": true, "num_tokens": 22069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12085324515618749, "lm_q2_score": 0.1666754067576692, "lm_q1q2_score": 0.020143263794391866}}
{"text": "```python\n! pip install qeds\nimport pandas as pd\nimport qeds\n%matplotlib inline\nimport qeds\nqeds.themes.mpl_style();\nfrom IPython.display import display\n```\n\n    Requirement already satisfied: qeds in c:\\users\\asus\\anaconda3\\lib\\site-packages (0.6.2)\n    Requirement already satisfied: seaborn in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.9.0)\n    Requirement already satisfied: pyarrow in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.16.0)\n    Requirement already satisfied: quandl in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (3.5.0)\n    Requirement already satisfied: scikit-learn in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.21.3)\n    Requirement already satisfied: matplotlib in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (3.1.1)\n    Requirement already satisfied: openpyxl in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (3.0.0)\n    Requirement already satisfied: requests in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (2.22.0)\n    Requirement already satisfied: plotly in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (4.5.4)\n    Requirement already satisfied: quantecon in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.4.6)\n    Requirement already satisfied: pandas in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.25.1)\n    Requirement already satisfied: numpy in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (1.16.5)\n    Requirement already satisfied: pandas-datareader in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.8.1)\n    Requirement already satisfied: scipy in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (1.3.1)\n    Requirement already satisfied: statsmodels in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.10.1)\n    Requirement already satisfied: six>=1.0.0 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pyarrow->qeds) (1.12.0)\n    Requirement already satisfied: more-itertools in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quandl->qeds) (7.2.0)\n    Requirement already satisfied: python-dateutil in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quandl->qeds) (2.8.0)\n    Requirement already satisfied: inflection>=0.3.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quandl->qeds) (0.3.1)\n    Requirement already satisfied: joblib>=0.11 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from scikit-learn->qeds) (0.13.2)\n    Requirement already satisfied: cycler>=0.10 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (1.1.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (2.4.2)\n    Requirement already satisfied: et-xmlfile in c:\\users\\asus\\anaconda3\\lib\\site-packages (from openpyxl->qeds) (1.0.1)\n    Requirement already satisfied: jdcal in c:\\users\\asus\\anaconda3\\lib\\site-packages (from openpyxl->qeds) (1.4.1)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (1.24.2)\n    Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (2019.9.11)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (3.0.4)\n    Requirement already satisfied: idna<2.9,>=2.5 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (2.8)\n    Requirement already satisfied: retrying>=1.3.3 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from plotly->qeds) (1.3.3)\n    Requirement already satisfied: numba>=0.38 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quantecon->qeds) (0.45.1)\n    Requirement already satisfied: sympy in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quantecon->qeds) (1.4)\n    Requirement already satisfied: pytz>=2017.2 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pandas->qeds) (2019.3)\n    Requirement already satisfied: lxml in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pandas-datareader->qeds) (4.4.1)\n    Requirement already satisfied: patsy>=0.4.0 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from statsmodels->qeds) (0.5.1)\n    Requirement already satisfied: setuptools in c:\\users\\asus\\anaconda3\\lib\\site-packages (from kiwisolver>=1.0.1->matplotlib->qeds) (41.4.0)\n    Requirement already satisfied: llvmlite>=0.29.0dev0 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from numba>=0.38->quantecon->qeds) (0.29.0)\n    Requirement already satisfied: mpmath>=0.19 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from sympy->quantecon->qeds) (1.1.0)\n\n\n# Merge - Exercises\n\n## Exercises 1-3\n\n**For these exercises we use several DataFrames:**\n- WDI data on GDP components\n- population\n- square miles of countries  \n\n\n```python\n# from WDI. Units trillions of 2010 USD\nurl = \"https://datascience.quantecon.org/assets/data/wdi_data.csv\"\nwdi = pd.read_csv(url).set_index([\"country\", \"year\"])\n#we create a DataFrame corresponding to 2017 that we need later on\nwdi2017 = wdi.xs(2017, level=\"year\")\n```\n\n\n```python\n# Data from https://www.nationmaster.com/country-info/stats/Geography/Land-area/Square-miles\n# units -- millions of square miles\nsq_miles = pd.Series({\n   \"United States\": 3.8,\n   \"Canada\": 3.8,\n   \"Germany\": 0.137,\n   \"United Kingdom\": 0.0936,\n   \"Russia\": 6.6,\n}, name=\"sq_miles\").to_frame()\nsq_miles.index.name = \"country\"\n```\n\n\n```python\n# from WDI. Units millions of people\npop_url = \"https://datascience.quantecon.org/assets/data/wdi_population.csv\"\npop = pd.read_csv(pop_url).set_index([\"country\", \"year\"])\n```\n\n## Exercise 1\n\n**Use your new `merge` skills to answer the final question from above: What is the population density of each country? How much does it change over time?**\n\n\n```python\n#we first merge the DataFrames that allow us to compute the population density, namely pop and sq_miles\nsqm_pop = pop.join(sq_miles, on='country')\nsqm_pop.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>Population</th>\n      <th>sq_miles</th>\n    </tr>\n    <tr>\n      <th>country</th>\n      <th>year</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td rowspan=\"5\" valign=\"top\">Canada</td>\n      <td>2017</td>\n      <td>36.540268</td>\n      <td>3.8</td>\n    </tr>\n    <tr>\n      <td>2016</td>\n      <td>36.109487</td>\n      <td>3.8</td>\n    </tr>\n    <tr>\n      <td>2015</td>\n      <td>35.702908</td>\n      <td>3.8</td>\n    </tr>\n    <tr>\n      <td>2014</td>\n      <td>35.437435</td>\n      <td>3.8</td>\n    </tr>\n    <tr>\n      <td>2013</td>\n      <td>35.082954</td>\n      <td>3.8</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# we next compute the population density of each country as Population/sq_miles\n    # and store it in a new column called \"density\"\nsqm_pop[\"density\"] = sqm_pop[\"Population\"] / sqm_pop[\"sq_miles\"]\nsqm_pop.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>Population</th>\n      <th>sq_miles</th>\n      <th>density</th>\n    </tr>\n    <tr>\n      <th>country</th>\n      <th>year</th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td rowspan=\"5\" valign=\"top\">Canada</td>\n      <td>2017</td>\n      <td>36.540268</td>\n      <td>3.8</td>\n      <td>9.615860</td>\n    </tr>\n    <tr>\n      <td>2016</td>\n      <td>36.109487</td>\n      <td>3.8</td>\n      <td>9.502497</td>\n    </tr>\n    <tr>\n      <td>2015</td>\n      <td>35.702908</td>\n      <td>3.8</td>\n      <td>9.395502</td>\n    </tr>\n    <tr>\n      <td>2014</td>\n      <td>35.437435</td>\n      <td>3.8</td>\n      <td>9.325641</td>\n    </tr>\n    <tr>\n      <td>2013</td>\n      <td>35.082954</td>\n      <td>3.8</td>\n      <td>9.232356</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# finally, we plot the time series of population density for each country\n    \nsqm_pop=sqm_pop.sort_index()\nsqm_pop.head()\nsqm_pop['density'].unstack(level=0).plot()\n```\n\n## Exercise 2\n\n1. **Create two new DataFrames:**\n\n    - wdi2017_no_US, which excludes the United States\n    - sq_miles_no_germant, which excludes Germany\n\n    **Compare the `how=\"left\"` with `how=\"inner\"` options using the DataFrames `wdi2017_no_US` and `sq_miles_no_germany`. Are they different? How?**\n\n\n```python\n# We create the two DataFrames\nwdi2017_no_US = wdi2017.drop(\"United States\")\nprint(\"This is wdi2017_no_US\")\ndisplay(wdi2017_no_US)\n\nsq_miles_no_germany = sq_miles.drop(\"Germany\")\nprint(\"This is sq_miles_no_germany\")\ndisplay(sq_miles_no_germany)\n```\n\n    This is wdi2017_no_US\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>GovExpend</th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>Imports</th>\n      <th>GDP</th>\n    </tr>\n    <tr>\n      <th>country</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>Canada</td>\n      <td>0.372665</td>\n      <td>1.095475</td>\n      <td>0.582831</td>\n      <td>0.600031</td>\n      <td>1.868164</td>\n    </tr>\n    <tr>\n      <td>Germany</td>\n      <td>0.745579</td>\n      <td>2.112009</td>\n      <td>1.930563</td>\n      <td>1.666348</td>\n      <td>3.883870</td>\n    </tr>\n    <tr>\n      <td>United Kingdom</td>\n      <td>0.549538</td>\n      <td>1.809154</td>\n      <td>0.862629</td>\n      <td>0.933145</td>\n      <td>2.818704</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    This is sq_miles_no_germany\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>sq_miles</th>\n    </tr>\n    <tr>\n      <th>country</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>United States</td>\n      <td>3.8000</td>\n    </tr>\n    <tr>\n      <td>Canada</td>\n      <td>3.8000</td>\n    </tr>\n    <tr>\n      <td>United Kingdom</td>\n      <td>0.0936</td>\n    </tr>\n    <tr>\n      <td>Russia</td>\n      <td>6.6000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n```python\nreq1 = pd.merge(wdi2017_no_US, sq_miles_no_germany, on=\"country\", how=\"left\")\nprint(\"This is how=\\\"left\\\"\")\ndisplay(req1)\n\nreq2 = pd.merge(wdi2017_no_US, sq_miles_no_germany, on=\"country\", how=\"inner\")\nprint(\"This is how=\\\"inner\\\"\")\ndisplay(req2)\n```\n\n    This is how=\"left\"\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>GovExpend</th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>Imports</th>\n      <th>GDP</th>\n      <th>sq_miles</th>\n    </tr>\n    <tr>\n      <th>country</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>Canada</td>\n      <td>0.372665</td>\n      <td>1.095475</td>\n      <td>0.582831</td>\n      <td>0.600031</td>\n      <td>1.868164</td>\n      <td>3.8000</td>\n    </tr>\n    <tr>\n      <td>Germany</td>\n      <td>0.745579</td>\n      <td>2.112009</td>\n      <td>1.930563</td>\n      <td>1.666348</td>\n      <td>3.883870</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>United Kingdom</td>\n      <td>0.549538</td>\n      <td>1.809154</td>\n      <td>0.862629</td>\n      <td>0.933145</td>\n      <td>2.818704</td>\n      <td>0.0936</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    This is how=\"inner\"\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>GovExpend</th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>Imports</th>\n      <th>GDP</th>\n      <th>sq_miles</th>\n    </tr>\n    <tr>\n      <th>country</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>Canada</td>\n      <td>0.372665</td>\n      <td>1.095475</td>\n      <td>0.582831</td>\n      <td>0.600031</td>\n      <td>1.868164</td>\n      <td>3.8000</td>\n    </tr>\n    <tr>\n      <td>United Kingdom</td>\n      <td>0.549538</td>\n      <td>1.809154</td>\n      <td>0.862629</td>\n      <td>0.933145</td>\n      <td>2.818704</td>\n      <td>0.0936</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n```python\n# the how=\"left\" version includes the countries that are common to both DataFrames (Canada & UK),\n    # plus the countries that are included in the left DataFrame (wdi2017_no_US) such as Germany, \n        # but not in the right DataFrame (sq_miles_no_germany)\n    \n# the how=\"inner\" version includes only the countries that are common to both DataFrames (Canada & UK)  \n```\n\n2. **Will this happen for all pairs of DataFrames, or are `wdi2017_no_US` and `sq_miles_no_germany` special in some way?**\n\nAs explained earlier: \n- with the 'left' method, the result contains all the keys from the left (\"base\", here wdi2017_no_US) dataframe. This implies that, for the keys (here, countries) that exist on the left dataframe but not on the right dataframe, the \"new column\" (here sq_miles) while be NaN.\n    - Here, the result has all the country because the wdi2017_no_US has all the country. But, since sq_miles does not have an entry for germany, the result returns NaN in the corresponding cell. \n- With the 'inner' method, the result containts only the keys that exist in both the left (\"base\", here wdi2017_no_US) and right (here sq_miles) dataframe. \n    - Here, the wdi_2017_no_US does have the US and the sq_miles dataframe doesn't have germany so the resulting dataframe have neither\n\n3. **Also compare `how=\"right\"` and `how=\"outer\"` and answer the same questions.**\n\n\n```python\nreq1bis = pd.merge(wdi2017_no_US, sq_miles_no_germany, on=\"country\", how=\"right\")\nprint(\"This is how=\\\"right\\\"\")\ndisplay(req1bis)\n\nreq2bis = pd.merge(wdi2017_no_US, sq_miles_no_germany, on=\"country\", how=\"outer\")\nprint(\"This is how=\\\"outer\\\"\")\ndisplay(req2bis)\n```\n\n    This is how=\"right\"\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>GovExpend</th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>Imports</th>\n      <th>GDP</th>\n      <th>sq_miles</th>\n    </tr>\n    <tr>\n      <th>country</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>Canada</td>\n      <td>0.372665</td>\n      <td>1.095475</td>\n      <td>0.582831</td>\n      <td>0.600031</td>\n      <td>1.868164</td>\n      <td>3.8000</td>\n    </tr>\n    <tr>\n      <td>United Kingdom</td>\n      <td>0.549538</td>\n      <td>1.809154</td>\n      <td>0.862629</td>\n      <td>0.933145</td>\n      <td>2.818704</td>\n      <td>0.0936</td>\n    </tr>\n    <tr>\n      <td>United States</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>3.8000</td>\n    </tr>\n    <tr>\n      <td>Russia</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6.6000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    This is how=\"outer\"\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>GovExpend</th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>Imports</th>\n      <th>GDP</th>\n      <th>sq_miles</th>\n    </tr>\n    <tr>\n      <th>country</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>Canada</td>\n      <td>0.372665</td>\n      <td>1.095475</td>\n      <td>0.582831</td>\n      <td>0.600031</td>\n      <td>1.868164</td>\n      <td>3.8000</td>\n    </tr>\n    <tr>\n      <td>Germany</td>\n      <td>0.745579</td>\n      <td>2.112009</td>\n      <td>1.930563</td>\n      <td>1.666348</td>\n      <td>3.883870</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>United Kingdom</td>\n      <td>0.549538</td>\n      <td>1.809154</td>\n      <td>0.862629</td>\n      <td>0.933145</td>\n      <td>2.818704</td>\n      <td>0.0936</td>\n    </tr>\n    <tr>\n      <td>United States</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>3.8000</td>\n    </tr>\n    <tr>\n      <td>Russia</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6.6000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n```python\n# the how=\"right\" version includes the countries that are common to both DataFrames (Canada & UK),\n    # plus the countries that are included in the right DataFrame (sq_miles_no_germany) such as US & Russia, \n        # but not in the left DataFrame (wdi2017_no_us)\n    \n# the how=\"outer\" version includes all the countries from both DataFrames (Canada, Germany, UK, US, Russia)  \n```\n\n## Exercise 3\n\n**Can you pick the correct argument for `how` such that `pd.merge(wdi2017, sq_miles, how=\"left\")` is equal to `pd.merge(sq_miles, wdi2017, how=XXX)`?**\n\n\n```python\n#first, we check how pd.merge(wdi2017, sq_miles, on=\"country\", how=\"left\") looks like\npd.merge(wdi2017, sq_miles, on=\"country\", how=\"left\")\n\n#the version below is more elegant as it sorts values and orders columns\n    #merged1 = pd.DataFrame(pd.merge(wdi2017, sq_miles, on=\"country\", how=\"left\").sort_values(\"country\", axis = 0) , \n    #                      columns=[\"GovExpend\", \"Consumption\", \"Exports\", \"Imports\", \"GDP\", \"sq_miles\"])\n    #merged1\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>GovExpend</th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>Imports</th>\n      <th>GDP</th>\n      <th>sq_miles</th>\n    </tr>\n    <tr>\n      <th>country</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>Canada</td>\n      <td>0.372665</td>\n      <td>1.095475</td>\n      <td>0.582831</td>\n      <td>0.600031</td>\n      <td>1.868164</td>\n      <td>3.8000</td>\n    </tr>\n    <tr>\n      <td>Germany</td>\n      <td>0.745579</td>\n      <td>2.112009</td>\n      <td>1.930563</td>\n      <td>1.666348</td>\n      <td>3.883870</td>\n      <td>0.1370</td>\n    </tr>\n    <tr>\n      <td>United Kingdom</td>\n      <td>0.549538</td>\n      <td>1.809154</td>\n      <td>0.862629</td>\n      <td>0.933145</td>\n      <td>2.818704</td>\n      <td>0.0936</td>\n    </tr>\n    <tr>\n      <td>United States</td>\n      <td>2.405743</td>\n      <td>12.019266</td>\n      <td>2.287071</td>\n      <td>3.069954</td>\n      <td>17.348627</td>\n      <td>3.8000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n#second, we find the right \"how\"\npd.merge(sq_miles, wdi2017, on=\"country\" , how=\"right\")\n\n#the version below is more elegant as it sorts values and orders columns and gives the exact same DataFrame in visual terms\n    #merged2 = pd.DataFrame(pd.merge(wdi2017, sq_miles, on=\"country\", how=\"right\").sort_values(\"country\", axis = 0) , \n    #                      columns=[\"GovExpend\", \"Consumption\", \"Exports\", \"Imports\", \"GDP\", \"sq_miles\"])\n    #merged2\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>sq_miles</th>\n      <th>GovExpend</th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>Imports</th>\n      <th>GDP</th>\n    </tr>\n    <tr>\n      <th>country</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>United States</td>\n      <td>3.8000</td>\n      <td>2.405743</td>\n      <td>12.019266</td>\n      <td>2.287071</td>\n      <td>3.069954</td>\n      <td>17.348627</td>\n    </tr>\n    <tr>\n      <td>Canada</td>\n      <td>3.8000</td>\n      <td>0.372665</td>\n      <td>1.095475</td>\n      <td>0.582831</td>\n      <td>0.600031</td>\n      <td>1.868164</td>\n    </tr>\n    <tr>\n      <td>Germany</td>\n      <td>0.1370</td>\n      <td>0.745579</td>\n      <td>2.112009</td>\n      <td>1.930563</td>\n      <td>1.666348</td>\n      <td>3.883870</td>\n    </tr>\n    <tr>\n      <td>United Kingdom</td>\n      <td>0.0936</td>\n      <td>0.549538</td>\n      <td>1.809154</td>\n      <td>0.862629</td>\n      <td>0.933145</td>\n      <td>2.818704</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nIt is a matter of keys ! \n- In the first proposed code, we want all the keys from the left dataframe, ie all the countries (keys) in wdi2017.\n- To have the same dataframe in the second case, we want to have the same keys as in the previous dataframe, i.e. the countries in wdi2017. In this case, wdi2017 is the \"on the right\" (it is the dataframe that we put onto the base one) so we chose, thanks to how='right', to have the keys from the right.\n\n## Exercise 4\n\n**For this exercise we use a dataset containing ratings of books from the website [Goodreads](https://www.goodreads.com/) and a dataset containing information on the actual books, that we are going to merge.**\n\n\n```python\n#dataset containing ratings of books from the website [Goodreads]\nratings = qeds.data.load(\"goodreads_ratings\")\n```\n\n\n```python\n#dataset containing information on the actual books\nbooks = qeds.data.load(\"goodreads_books\")\n# we only need a few of the columns\nbooks = books[[\"book_id\", \"authors\", \"title\"]]\n```\n\n\n```python\n#merged dataset\nrated_books = pd.merge(ratings, books)\n```\n\n1. **Determine the average rating for the books with the *most*/*least* number ratings.**\n\n\n```python\n#most rated\nmost_rated_books_id = rated_books[\"book_id\"].value_counts().nlargest(10).index\nmost_rated_books = rated_books.loc[rated_books[\"book_id\"].isin(most_rated_books_id), :]\nlist(most_rated_books[\"title\"].unique())\n```\n\n\n\n\n    ['Harry Potter and the Prisoner of Azkaban (Harry Potter, #3)',\n     \"Harry Potter and the Sorcerer's Stone (Harry Potter, #1)\",\n     'Harry Potter and the Chamber of Secrets (Harry Potter, #2)',\n     'The Great Gatsby',\n     'To Kill a Mockingbird',\n     'The Hobbit',\n     'Twilight (Twilight, #1)',\n     'The Hunger Games (The Hunger Games, #1)',\n     'Catching Fire (The Hunger Games, #2)',\n     'Mockingjay (The Hunger Games, #3)']\n\n\n\n\n```python\n#least rated\nleast_rated_books_id = rated_books[\"book_id\"].value_counts().nsmallest(10).index\nleast_rated_books = rated_books.loc[rated_books[\"book_id\"].isin(least_rated_books_id), :]\nlist(least_rated_books[\"title\"].unique())\n```\n\n\n\n\n    ['The Batman Chronicles, Vol. 1',\n     \"The King's Agent\",\n     'The Magic (The Secret, #3)',\n     'Fifty Shades Duo: Fifty Shades Darker / Fifty Shades Freed (Fifty Shades, #2-3)',\n     'The Lake (The Lake Trilogy #1)',\n     'Diary ng Panget',\n     \"Kindle Paperwhite User's Guide\",\n     \"Kindle User's Guide\",\n     'Attack on Titan: No Regrets, Volume 01',\n     'Manga Classics: Les Mis\u00e9rables']\n\n\n\n2. **Is there a distinguishable difference in the average rating compared to the most rated books?**\n\n\n```python\nleast=least_rated_books.pivot_table(values=\"rating\", index=\"title\")\nmost=most_rated_books.pivot_table(values=\"rating\", index=\"title\")\n```\n\n\n```python\ndisplay(least)\ndisplay(most)\n```\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>rating</th>\n    </tr>\n    <tr>\n      <th>title</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>Attack on Titan: No Regrets, Volume 01</td>\n      <td>4.292683</td>\n    </tr>\n    <tr>\n      <td>Diary ng Panget</td>\n      <td>3.545455</td>\n    </tr>\n    <tr>\n      <td>Fifty Shades Duo: Fifty Shades Darker / Fifty Shades Freed (Fifty Shades, #2-3)</td>\n      <td>4.041667</td>\n    </tr>\n    <tr>\n      <td>Kindle Paperwhite User's Guide</td>\n      <td>3.757576</td>\n    </tr>\n    <tr>\n      <td>Kindle User's Guide</td>\n      <td>3.375000</td>\n    </tr>\n    <tr>\n      <td>Manga Classics: Les Mis\u00e9rables</td>\n      <td>4.187500</td>\n    </tr>\n    <tr>\n      <td>The Batman Chronicles, Vol. 1</td>\n      <td>3.822222</td>\n    </tr>\n    <tr>\n      <td>The King's Agent</td>\n      <td>3.722222</td>\n    </tr>\n    <tr>\n      <td>The Lake (The Lake Trilogy #1)</td>\n      <td>2.960000</td>\n    </tr>\n    <tr>\n      <td>The Magic (The Secret, #3)</td>\n      <td>4.041667</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>rating</th>\n    </tr>\n    <tr>\n      <th>title</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>Catching Fire (The Hunger Games, #2)</td>\n      <td>4.133422</td>\n    </tr>\n    <tr>\n      <td>Harry Potter and the Chamber of Secrets (Harry Potter, #2)</td>\n      <td>4.229418</td>\n    </tr>\n    <tr>\n      <td>Harry Potter and the Prisoner of Azkaban (Harry Potter, #3)</td>\n      <td>4.418732</td>\n    </tr>\n    <tr>\n      <td>Harry Potter and the Sorcerer's Stone (Harry Potter, #1)</td>\n      <td>4.351350</td>\n    </tr>\n    <tr>\n      <td>Mockingjay (The Hunger Games, #3)</td>\n      <td>3.853131</td>\n    </tr>\n    <tr>\n      <td>The Great Gatsby</td>\n      <td>3.772224</td>\n    </tr>\n    <tr>\n      <td>The Hobbit</td>\n      <td>4.148477</td>\n    </tr>\n    <tr>\n      <td>The Hunger Games (The Hunger Games, #1)</td>\n      <td>4.279707</td>\n    </tr>\n    <tr>\n      <td>To Kill a Mockingbird</td>\n      <td>4.329369</td>\n    </tr>\n    <tr>\n      <td>Twilight (Twilight, #1)</td>\n      <td>3.214341</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n```python\n# To decide whether they are really different, a small ttest, underpowered and with no care for the hypothesis ^^\n\nimport scipy.stats as stats\nstats.ttest_ind(least['rating'], most['rating'])\n```\n\n\n\n\n    Ttest_indResult(statistic=-1.7299828900907714, pvalue=0.1007424590612311)\n\n\n\n## Exercises 5-7\n\n**For these exercises we create the DataFrames dfL and dfR, as specified below:**\n\n\n```python\ndfL = pd.DataFrame(\n    {\"Key\": [\"A\", \"B\", \"A\", \"C\"], \"C1\":[1, 2, 3, 4], \"C2\": [10, 20, 30, 40]},\n    index=[\"L1\", \"L2\", \"L3\", \"L4\"]\n)[[\"Key\", \"C1\", \"C2\"]]\nprint(\"This is dfL.\")\ndisplay(dfL)\n\ndfR = pd.DataFrame(\n    {\"Key\": [\"A\", \"B\", \"C\", \"D\"], \"C3\": [100, 200, 300, 400]},\n    index=[\"R1\", \"R2\", \"R3\", \"R4\"]\n)[[\"Key\", \"C3\"]]\nprint(\"This is dfR.\")\ndisplay(dfR)\n```\n\n    This is dfL.\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Key</th>\n      <th>C1</th>\n      <th>C2</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>L1</td>\n      <td>A</td>\n      <td>1</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <td>L2</td>\n      <td>B</td>\n      <td>2</td>\n      <td>20</td>\n    </tr>\n    <tr>\n      <td>L3</td>\n      <td>A</td>\n      <td>3</td>\n      <td>30</td>\n    </tr>\n    <tr>\n      <td>L4</td>\n      <td>C</td>\n      <td>4</td>\n      <td>40</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    This is dfR.\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Key</th>\n      <th>C3</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>R1</td>\n      <td>A</td>\n      <td>100</td>\n    </tr>\n    <tr>\n      <td>R2</td>\n      <td>B</td>\n      <td>200</td>\n    </tr>\n    <tr>\n      <td>R3</td>\n      <td>C</td>\n      <td>300</td>\n    </tr>\n    <tr>\n      <td>R4</td>\n      <td>D</td>\n      <td>400</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n## Exercise 5\n\n**In writing, describe what the output looks like when you do `pd.concat([dfL, dfR], axis=1)` (see above and/or run the cell below). Be sure to describe things like:**\n\n- What are the columns? What about columns with the same name?  \n- What is the index?  \n- Do any `NaN`s get introduced? If so, where? Why?  \n\n\n```python\npd.concat([dfL, dfR], axis=1)\n\n#pd.concat([dfL, dfR], axis=1).info()\n\n#the columns are Key, C1, C2, Key, C3 (since Key is defined as a column and not as an index in both DataFrames, we end up with two columns Key)\n#the index goes through 8 entries: L1 - L4, R1 - R4\n#missing values for:\n    #L rows corresponding to columns Key and C3 (because the L rows do not exist in dfR)\n    #R rows corresponding to columns Key, C1 and C2 (because the R rows do not exist in dfL)\n#while axis = 1 arranges the DataFrames side-by-side, the fact that there are no common values for the index leads to a DataFrame like this\n```\n\n    C:\\Users\\asus\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:1: FutureWarning: Sorting because non-concatenation axis is not aligned. A future version\n    of pandas will change to not sort by default.\n    \n    To accept the future behavior, pass 'sort=False'.\n    \n    To retain the current behavior and silence the warning, pass 'sort=True'.\n    \n      \"\"\"Entry point for launching an IPython kernel.\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Key</th>\n      <th>C1</th>\n      <th>C2</th>\n      <th>Key</th>\n      <th>C3</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>L1</td>\n      <td>A</td>\n      <td>1.0</td>\n      <td>10.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>L2</td>\n      <td>B</td>\n      <td>2.0</td>\n      <td>20.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>L3</td>\n      <td>A</td>\n      <td>3.0</td>\n      <td>30.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>L4</td>\n      <td>C</td>\n      <td>4.0</td>\n      <td>40.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>R1</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>A</td>\n      <td>100.0</td>\n    </tr>\n    <tr>\n      <td>R2</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>B</td>\n      <td>200.0</td>\n    </tr>\n    <tr>\n      <td>R3</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>C</td>\n      <td>300.0</td>\n    </tr>\n    <tr>\n      <td>R4</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>D</td>\n      <td>400.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Exercise 6\n\n**Determine what happens when you run each of the two cells below. For each cell, answer the list of questions from the previous exercise.**\n\n\n```python\n# First code cell for above exercise\npd.concat([dfL, dfL], axis=0)\n#pd.concat([dfL, dfL], axis=0).info()\n\n#the columns are Key, C1, C2\n#the index goes through 4 entries: L1 to L4\n#we don' have any missing values, because the Dataframes have identical structures\n#since we used axis = 0, the DataFrames are arranged on top of one another\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Key</th>\n      <th>C1</th>\n      <th>C2</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>L1</td>\n      <td>A</td>\n      <td>1</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <td>L2</td>\n      <td>B</td>\n      <td>2</td>\n      <td>20</td>\n    </tr>\n    <tr>\n      <td>L3</td>\n      <td>A</td>\n      <td>3</td>\n      <td>30</td>\n    </tr>\n    <tr>\n      <td>L4</td>\n      <td>C</td>\n      <td>4</td>\n      <td>40</td>\n    </tr>\n    <tr>\n      <td>L1</td>\n      <td>A</td>\n      <td>1</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <td>L2</td>\n      <td>B</td>\n      <td>2</td>\n      <td>20</td>\n    </tr>\n    <tr>\n      <td>L3</td>\n      <td>A</td>\n      <td>3</td>\n      <td>30</td>\n    </tr>\n    <tr>\n      <td>L4</td>\n      <td>C</td>\n      <td>4</td>\n      <td>40</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# Second code cell for above exercise\npd.concat([dfR, dfR], axis=1)\n#pd.concat([dfR, dfR], axis=1).info()\n\n#the columns are Key, C3\n#the index goes through 4 entries: R1 to R4\n#we don' have any missing values, because the Dataframes have identical structures\n#since we used axis = 1, the DataFrames are arranged side-by-side\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Key</th>\n      <th>C3</th>\n      <th>Key</th>\n      <th>C3</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>R1</td>\n      <td>A</td>\n      <td>100</td>\n      <td>A</td>\n      <td>100</td>\n    </tr>\n    <tr>\n      <td>R2</td>\n      <td>B</td>\n      <td>200</td>\n      <td>B</td>\n      <td>200</td>\n    </tr>\n    <tr>\n      <td>R3</td>\n      <td>C</td>\n      <td>300</td>\n      <td>C</td>\n      <td>300</td>\n    </tr>\n    <tr>\n      <td>R4</td>\n      <td>D</td>\n      <td>400</td>\n      <td>D</td>\n      <td>400</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Exercise 7\n\n**Describe in words why the output of `pd.merge(dfL, dfR, how=\"right\")` has more rows than either `dfL` or `dfR`. Run the cell below to see the output of that operation.**\n\n\n```python\n# the output of pd.merge(dfL, dfR, how=\"right\") has more rows than either dfL and dfR because, \n    # besides the information common to both DataFrames (A, B, C), \n    # it includes information that is in dfR and not in dfL (D)\n    # Note: all elements from dfL are in dfR, but A appears twice in dfL, which means that the merged DataFrame will include A twice, plus B, plus C, plus D\n \nmerged=pd.merge(dfL, dfR, how=\"right\")\nprint(\"This is merged:\")\ndisplay(merged)\n\nprint(\"This is dfL:\")\ndisplay(dfL)\n\nprint(\"This is dfR:\")\ndisplay(dfR)\n```\n\n    This is merged:\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Key</th>\n      <th>C1</th>\n      <th>C2</th>\n      <th>C3</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>A</td>\n      <td>1.0</td>\n      <td>10.0</td>\n      <td>100</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>A</td>\n      <td>3.0</td>\n      <td>30.0</td>\n      <td>100</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>B</td>\n      <td>2.0</td>\n      <td>20.0</td>\n      <td>200</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>C</td>\n      <td>4.0</td>\n      <td>40.0</td>\n      <td>300</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>D</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>400</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    This is dfL:\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Key</th>\n      <th>C1</th>\n      <th>C2</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>L1</td>\n      <td>A</td>\n      <td>1</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <td>L2</td>\n      <td>B</td>\n      <td>2</td>\n      <td>20</td>\n    </tr>\n    <tr>\n      <td>L3</td>\n      <td>A</td>\n      <td>3</td>\n      <td>30</td>\n    </tr>\n    <tr>\n      <td>L4</td>\n      <td>C</td>\n      <td>4</td>\n      <td>40</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n    This is dfR:\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Key</th>\n      <th>C3</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>R1</td>\n      <td>A</td>\n      <td>100</td>\n    </tr>\n    <tr>\n      <td>R2</td>\n      <td>B</td>\n      <td>200</td>\n    </tr>\n    <tr>\n      <td>R3</td>\n      <td>C</td>\n      <td>300</td>\n    </tr>\n    <tr>\n      <td>R4</td>\n      <td>D</td>\n      <td>400</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n", "meta": {"hexsha": "a8c7694bf18448d5d5a8564839c70bcfcb9c282d", "size": 101702, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Session_7/7_merge_exercises.ipynb", "max_stars_repo_name": "remi-sudo/Classes", "max_stars_repo_head_hexsha": "71497927ed4d54ddf6fd5abe2ddabb5966eb0304", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Session_7/7_merge_exercises.ipynb", "max_issues_repo_name": "remi-sudo/Classes", "max_issues_repo_head_hexsha": "71497927ed4d54ddf6fd5abe2ddabb5966eb0304", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Session_7/7_merge_exercises.ipynb", "max_forks_repo_name": "remi-sudo/Classes", "max_forks_repo_head_hexsha": "71497927ed4d54ddf6fd5abe2ddabb5966eb0304", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2416869424, "max_line_length": 25196, "alphanum_fraction": 0.5443255787, "converted": true, "num_tokens": 13527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.05921025157134613, "lm_q1q2_score": 0.01981112498971728}}
{"text": "## Initial setup\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```python\nimport tensorflow as tf\nprint(tf.__version__)\nimport torch\nprint(torch.__version__)\nimport matplotlib\nprint(matplotlib.__version__)\n```\n\n    2.8.0\n    1.10.0+cu111\n    3.2.2\n\n\n\n```python\n!nvidia-smi\n```\n\n    Fri Jan 21 19:41:32 2022       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 495.46       Driver Version: 460.32.03    CUDA Version: 11.2     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   34C    P8     9W /  70W |      0MiB / 15109MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    |  No running processes found                                                 |\n    +-----------------------------------------------------------------------------+\n\n\n\n```python\n# Other imports\n! pip install tensorflow_addons\n! pip install tensorflow_io\n\nimport os\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import *\nfrom keras.callbacks import Callback, EarlyStopping, ModelCheckpoint\nfrom tensorflow.keras.applications.resnet50 import preprocess_input\nfrom tensorflow.keras.preprocessing.image import load_img\n\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfrom matplotlib.offsetbox import OffsetImage, AnnotationBbox\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter, AutoMinorLocator\nfrom imutils import paths\nfrom tqdm import tqdm\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nimport tensorflow_datasets as tfds\nimport tensorflow_io as tfio\nimport tensorflow_hub as hub\nimport numpy as np\nimport cv2\nimport pandas as pd\nimport seaborn as sns\nfrom scipy.stats import mannwhitneyu\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.cluster import KMeans\nimport sklearn.manifold\nfrom sklearn.metrics.pairwise import cosine_similarity as cos\nfrom sympy.utilities.iterables import multiset_permutations\nfrom sklearn.metrics import accuracy_score, f1_score,precision_score, recall_score, roc_auc_score, confusion_matrix\nfrom sklearn.model_selection import *\nfrom sklearn.preprocessing import StandardScaler\nfrom IPython.display import Image, display\n\n\nimport zipfile\nimport concurrent.futures\n\n# Random seed fix\nrandom_seed = 42\ntf.random.set_seed(random_seed)\nnp.random.seed(random_seed)\n```\n\n    Collecting tensorflow_addons\n      Downloading tensorflow_addons-0.16.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.1 MB 6.4 MB/s \n    \u001b[?25hRequirement already satisfied: typeguard>=2.7 in /usr/local/lib/python3.7/dist-packages (from tensorflow_addons) (2.7.1)\n    Installing collected packages: tensorflow-addons\n    Successfully installed tensorflow-addons-0.16.1\n    Collecting tensorflow_io\n      Downloading tensorflow_io-0.24.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (23.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 23.4 MB 1.8 MB/s \n    \u001b[?25hRequirement already satisfied: tensorflow-io-gcs-filesystem==0.24.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow_io) (0.24.0)\n    Installing collected packages: tensorflow-io\n    Successfully installed tensorflow-io-0.24.0\n\n\n## Dataset gathering and preparation\n\n\n```python\n%cd /content/drive/MyDrive/nanowire-morphology-classification-project\n```\n\n\n```python\ntraining_batch_size = 4\n\nBATCH_SIZE = training_batch_size\n\nimageSize = 224\n\ncategory_names = ['bundle', 'dispersed', 'network', 'singular']\ncolor_method = ['C0', 'C1', 'C2', 'C3', 'C4']\ncolor = ['black', 'magenta', 'cyan', 'yellow']\nmarker = ['o', 's', '<', '>', '^']\nseaborn_palette = sns.color_palette(\"colorblind\")\n```\n\n\n```python\n# Image preprocessing utils\n@tf.function\ndef parse_images(image_path):\n    image_string = tf.io.read_file(image_path)\n    image = tf.image.decode_jpeg(image_string, channels=3)\n    # image = tfio.experimental.image.decode_tiff(image_string)[:, :, :3]   # in the doc, it transforms tiff to 4 channels, with additional channel of opacity which is not needed.\n    image = tf.image.convert_image_dtype(image, tf.float32)\n    image = tf.image.resize(image, size=[imageSize, imageSize])\n\n    return image\n```\n\n## Initiate self-supervised models\n\n\n```python\nResnet50_transfer = tf.keras.applications.ResNet50(\n    include_top=False,\n    weights=\"imagenet\",\n    input_tensor=None,\n    input_shape=(imageSize, imageSize, 3), \n    pooling=None,\n)\n\nResnet50_transfer.trainable = False\n```\n\n    Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/resnet/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5\n    94773248/94765736 [==============================] - 1s 0us/step\n    94781440/94765736 [==============================] - 1s 0us/step\n\n\n\n```python\n# Resnet as backbone\ndef get_resnet_self_supervise_model(hidden_1, hidden_2, hidden_3):\n    base_model = Resnet50_transfer\n    base_model.trainable = True\n    inputs = Input((imageSize, imageSize, 3))\n    h = base_model(inputs, training=True)\n    h = GlobalAveragePooling2D()(h)\n\n    projection_1 = Dense(hidden_1)(h)                                        \n    projection_1 = Activation(\"relu\")(projection_1)\n    projection_1 = BatchNormalization(epsilon=0.001)(projection_1)\n    projection_2 = Dense(hidden_2)(projection_1)\n    projection_2 = Activation(\"relu\")(projection_2)\n    projection_2 = BatchNormalization(epsilon=0.001)(projection_2)\n    projection_3 = Dense(hidden_3)(projection_2)\n    projection_3 = BatchNormalization(epsilon=0.001)(projection_3)\n\n    resnet_model = Model(inputs, projection_3)\n    \n    return resnet_model\n```\n\n## segmentation data preparation, model and results\n\n\n```python\nnp.random.seed(random_seed)\npeptide_morph_seglabel_train_path = \"/content/drive/MyDrive/TEM image datasets/2022-nanowire-morphology\"\npeptide_morph_images_train_seglabel = list(paths.list_files(basePath=peptide_morph_seglabel_train_path, validExts='png'))\npeptide_morph_images_train_seglabel = np.random.choice(np.array(peptide_morph_images_train_seglabel), len(peptide_morph_images_train_seglabel), replace=False)\nprint(len(peptide_morph_images_train_seglabel))\n```\n\n    200\n\n\n\n```python\ndef generate_ground_truth_images(image, resolution):\n  image_bool = np.ones((resolution, resolution))\n  for i in range(image.shape[0]):\n    for j in range(image.shape[1]):\n      if image[i, j, 1] == image[i, j, 2]:\n        image_bool[i, j] = 0            # background is black with code of 0\n      else: \n        image_bool[i, j] = 1            # nanowire is white with code of 1\n  return image_bool\n```\n\n\n```python\nsegmentation_class_labels = []\nfor i in range(peptide_morph_images_train_seglabel.shape[0]):\n  seg_class_label = peptide_morph_images_train_seglabel[i].split(\"/\")[-2]\n  segmentation_class_labels.append(seg_class_label)\nle = LabelEncoder()\npeptide_morph_train_seg_enc = le.fit_transform(segmentation_class_labels)\n```\n\n\n```python\n# image_mask = np.zeros((len(peptide_morph_images_train_seglabel), imageSize, imageSize))\nimages_no_annotation_directory = []\nimages_no_annotation = np.zeros((len(peptide_morph_images_train_seglabel), imageSize, imageSize, 3))\n\nfor i in range(len(peptide_morph_images_train_seglabel)):\n  images_no_annotation_directory.append('%s.jpg' % (peptide_morph_images_train_seglabel[i].split(\"_\")[0] + \"_\" + peptide_morph_images_train_seglabel[i].split(\"_\")[1]))\n  images_no_annotation[i] = parse_images(images_no_annotation_directory[i])\n\n  # these were used to create the ground truth grayscale images from the manual segmentation labels.\n  # image_string = tf.io.read_file(peptide_morph_images_train_seglabel[i])\n  # image = tf.image.decode_image(image_string, channels=3) / 255\n  # image = tf.image.resize(image, (imageSize, imageSize))\n  # image = tf.image.convert_image_dtype(image, tf.float32)\n  # trans_nd_image_array = image.numpy()\n  # image_mask[i] = generate_ground_truth_images(trans_nd_image_array, imageSize)\n  \n# np.savez_compressed('seg_mask_res512.npz', mask=image_mask)\n\n# once we have the seg_mask saved, we can directly load from npz file\nimage_mask = np.load('seg_mask_res%i.npz' % (imageSize), allow_pickle=True)['mask']\n```\n\n    WARNING:tensorflow:5 out of the last 5 calls to <function parse_images at 0x7f9490054b90> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for  more details.\n    WARNING:tensorflow:6 out of the last 6 calls to <function parse_images at 0x7f9490054b90> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for  more details.\n\n\n\n```python\ndef upsample(filters, size, apply_dropout=False):\n\n  result = Sequential()\n  result.add(\n    Conv2DTranspose(filters, size, strides=2,\n                                    padding='same',\n                                    kernel_initializer='he_uniform',\n                                    use_bias=False))\n\n  result.add(BatchNormalization())\n\n  if apply_dropout:\n      result.add(Dropout(0.5))\n\n  result.add(ReLU())\n\n  return result\n```\n\n\n```python\n# build our resnet50-unet model with the option of transfered weights from either tem images\ndef unet_model(base_model, resolution):\n  inputs = tf.keras.layers.Input(shape=[resolution, resolution, 3])\n\n  # Use the activations of these layers\n  layer_names = [\n      'conv1_relu',         # (batch_size, 112, 112, 64)\n      'conv2_block3_out',   # (batch_size, 56, 56, 256)\n      'conv3_block4_out',   # (batch_size, 28, 28, 512)\n      'conv4_block6_out',   # (batch_size, 14, 14, 1024)\n      'conv5_block3_out'    # (batch_size, 7, 7, 2048)\n  ]\n  base_model_outputs = [base_model.get_layer(name).output for name in layer_names]\n\n  # Create the feature extraction model\n  encoder = Model(inputs=base_model.input, outputs=base_model_outputs)\n\n  encoder.trainable = False\n\n  decoder = [\n    upsample(1024, 4),  # (batch_size, 7, 7, 2048)\n    upsample(512, 4),  # (batch_size, 14, 14, 1024)\n    upsample(256, 4),  # (batch_size, 28, 28, 512)\n    upsample(128, 4),  # (batch_size, 56, 56, 256)\n  ]\n\n  last = Conv2DTranspose(1, 4,    # number of class, size of input vector (batch_size, x, y, class)\n                              strides=2,\n                              padding='same',\n                              use_bias=True,\n                              kernel_initializer='he_uniform',\n                              activation='sigmoid')       # (batch_size, resolution, resolution, 3)\n\n  # Downsampling through the model\n  skips = encoder(inputs)\n  x = skips[-1]\n  skips = reversed(skips[:-1])        # exclude the last conv layer, reverse is a python native function\n\n  # Upsampling and establishing the skip connections\n  for up, skip in zip(decoder, skips):\n    x = up(x)\n    x = Concatenate()([x, skip])\n\n  x = last(x)\n\n  return tf.keras.Model(inputs=inputs, outputs=x)\n```\n\n\n```python\n# define loss functions and metrics for segmentation task\n# coef functions are for batches of images, score functions are for a single image\n\ndef dice_coef(y_true, y_pred, smooth=0.000001):\n\n    beta = 1\n    tp = tf.reduce_sum(y_true * y_pred, axis=[1,2])\n    fp = tf.reduce_sum(y_pred, axis=[1,2]) - tp\n    fn = tf.reduce_sum(y_true, axis=[1,2]) - tp\n\n    score = tf.reduce_mean(((1 + beta ** 2) * tp + smooth) \\\n            / ((1 + beta ** 2) * tp + beta ** 2 * fn + fp + smooth))\n    return score\n\ndef dice_score(y_true, y_pred, smooth=0.000001):\n  y_true = y_true.astype('float32')\n  beta = 1\n  tp = tf.reduce_sum(y_true * y_pred, axis=[1])\n  fp = tf.reduce_sum(y_pred, axis=[1]) - tp\n  fn = tf.reduce_sum(y_true, axis=[1]) - tp\n\n  score = tf.reduce_mean(((1 + beta ** 2) * tp + smooth) \\\n          / ((1 + beta ** 2) * tp + beta ** 2 * fn + fp + smooth)).numpy()\n  return score\n\ndef dice_coef_loss(y_true, y_pred):\n    return 1 - dice_coef(y_true, y_pred)\n\ndef iou_coef(y_true, y_pred, smooth=0.000001):\n\n    beta = 1\n    tp = tf.reduce_sum(y_true * y_pred, axis=[1,2])\n    fp = tf.reduce_sum(y_pred, axis=[1,2]) - tp\n    fn = tf.reduce_sum(y_true, axis=[1,2]) - tp\n\n    score = tf.reduce_mean((tp + smooth) \\\n            / (tp + fn + fp + smooth))\n    return score\n\ndef iou_score(y_true, y_pred, smooth=0.000001):\n  y_true = y_true.astype('float32')\n  tp = tf.reduce_sum(y_true * y_pred, axis=[1])\n  fp = tf.reduce_sum(y_pred, axis=[1]) - tp\n  fn = tf.reduce_sum(y_true, axis=[1]) - tp\n\n  score = tf.reduce_mean((tp + smooth) \\\n          / (tp + fn + fp + smooth)).numpy()\n  return score\n\ndef iou_coef_loss(y_true, y_pred):\n    return 1 - iou_coef(y_true, y_pred)\n```\n\n\n```python\ntf.random.set_seed(random_seed)\n\nencoder_res = np.array([224, 384, 224])\nencoder_batch_size = np.array([64, 16, 64])\nrandom_seed_list = np.array([45])\n# random_seed_for_split = np.linspace(42, 42 + 3, 4).astype(int)\nrandom_seed_for_split = np.array([42])\ntraining_image_size = np.array([80, 32, 16, 8, 4, 2, 1])\nn_epoch = np.array([20, 30, 40, 60, 120, 120, 120])\n\nfor i in range(len(random_seed_list)):\n  resnet_model = get_resnet_self_supervise_model(128, 64, 1024)\n  if encoder_res[0] == 224:\n    resnet_model.load_weights('barlow_resnet_batch%i_project128_64_1024_seed%i.h5' % (encoder_batch_size[0], random_seed_list[i]))\n  else:\n    resnet_model.load_weights('barlow_resnet_batch%i_project128_64_1024_res%i_seed%i.h5' % (encoder_batch_size[0], encoder_res[0], random_seed_list[i]))\n  trained_resnet50 = resnet_model.get_layer('resnet50')\n\n  for j in range(len(random_seed_for_split)):\n    seg_scores = np.zeros((len(training_image_size), int(image_mask.shape[0] / 5), 2))\n\n    X_TRAIN, x_val, MASK_TRAIN, mask_val = train_test_split(images_no_annotation, image_mask, test_size=0.2, shuffle=True, stratify=peptide_morph_train_seg_enc, random_state=random_seed_for_split[j])\n    X_TRAIN, x_val, TRAIN_FILENAME, test_filename = train_test_split(images_no_annotation, peptide_morph_images_train_seglabel, test_size=0.2, shuffle=True, stratify=peptide_morph_train_seg_enc, random_state=random_seed_for_split[j])\n    X_TRAIN, x_val, seg_class_train, seg_class_val = train_test_split(images_no_annotation, peptide_morph_train_seg_enc, test_size=0.2, shuffle=True, stratify=peptide_morph_train_seg_enc, random_state=random_seed_for_split[j])      \n\n    for n in range(len(training_image_size)):\n      if os.path.isdir('segmentation_figures/res%i_enc_res%i_seed%i_seed%i_datasize%i' %(imageSize, encoder_res[0], random_seed_list[i], random_seed_for_split[j], training_image_size[n])) != True:\n        os.mkdir('segmentation_figures/res%i_enc_res%i_seed%i_seed%i_datasize%i' %(imageSize, encoder_res[0], random_seed_list[i], random_seed_for_split[j], training_image_size[n]))\n\n      if training_image_size[n] != 80:\n        x_train, x_no_val, mask_train, mask_no_val = train_test_split(X_TRAIN, MASK_TRAIN, test_size=(1 - training_image_size[n] * 2 / len(seg_class_train)), shuffle=True, stratify=seg_class_train, random_state=42)\n        x_train, x_no_val, train_filename, filename_no_val = train_test_split(X_TRAIN, TRAIN_FILENAME, test_size=(1 - training_image_size[n] * 2 / len(seg_class_train)), shuffle=True, stratify=seg_class_train, random_state=42)\n      else:\n        x_train = X_TRAIN\n        mask_train = MASK_TRAIN\n\n      # train segmentation model\n      unet = unet_model(trained_resnet50, imageSize)\n      unet.compile(optimizer='adam',\n                    loss=dice_coef_loss,\n                    metrics=[iou_coef, dice_coef])\n      model_history = unet.fit(x=x_train, y=mask_train, epochs=n_epoch[n],\n                                batch_size=training_batch_size,\n                                validation_data=(x_val, mask_val)\n                                )\n      # log best segmentation model performance\n      y_predict = unet.predict(x_val, batch_size=training_batch_size)\n      y_predict = y_predict.reshape((len(x_val), imageSize, imageSize))\n\n      filename = []\n      for k in range(y_predict.shape[0]):\n        filename.append(test_filename[k].split(\"/\")[-1])\n        seg_scores[n, k, 0] = iou_score(mask_val[k], y_predict[k])\n        seg_scores[n, k, 1] = dice_score(mask_val[k], y_predict[k])\n        fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(20,20))\n        ax1.imshow(x_val[k])\n        nanowire_pix = np.transpose(np.vstack((np.where(mask_val[k] == 0)[0], np.where(mask_val[k] == 0)[1])))\n        image_a = np.expand_dims(mask_val[k], axis=-1) * np.array([1, 1, 1])\n        ax2.imshow(image_a)\n        nanowire_pix = np.transpose(np.vstack((np.where(y_predict[k] == 0)[0], np.where(y_predict[k] == 0)[1])))\n        image_a = np.expand_dims(y_predict[k], axis=-1) * np.array([1, 1, 1])\n        ax3.imshow(image_a)\n        plt.title('iou: %1.4f dice: %1.4f' % (seg_scores[n, k, 0], seg_scores[n, k, 1]))\n        plt.savefig('segmentation_figures/res%i_enc_res%i_seed%i_seed%i_datasize%i/%s' %(imageSize, encoder_res[0], random_seed_list[i], random_seed_for_split[j], training_image_size[n], test_filename[k].split(\"/\")[-1]))\n        plt.close('all')\n\n    np.savez_compressed('segmentation_scores_main_result/res%i_enc_res%i_seed%i_seed%i.npz' %(imageSize, encoder_res[0], random_seed_list[i], random_seed_for_split[j]), scores=seg_scores, filename=filename)\n```\n\n    Epoch 1/20\n    40/40 [==============================] - 18s 343ms/step - loss: 0.5349 - iou_coef: 0.3158 - dice_coef: 0.4651 - val_loss: 0.6011 - val_iou_coef: 0.2629 - val_dice_coef: 0.3989\n    Epoch 2/20\n    40/40 [==============================] - 12s 305ms/step - loss: 0.4216 - iou_coef: 0.4197 - dice_coef: 0.5784 - val_loss: 0.5148 - val_iou_coef: 0.3338 - val_dice_coef: 0.4852\n    Epoch 3/20\n    40/40 [==============================] - 12s 306ms/step - loss: 0.3387 - iou_coef: 0.5071 - dice_coef: 0.6613 - val_loss: 0.5365 - val_iou_coef: 0.3160 - val_dice_coef: 0.4635\n    Epoch 4/20\n    40/40 [==============================] - 12s 307ms/step - loss: 0.2714 - iou_coef: 0.5817 - dice_coef: 0.7286 - val_loss: 0.5199 - val_iou_coef: 0.3307 - val_dice_coef: 0.4801\n    Epoch 5/20\n    40/40 [==============================] - 12s 307ms/step - loss: 0.2524 - iou_coef: 0.6036 - dice_coef: 0.7476 - val_loss: 0.3672 - val_iou_coef: 0.4770 - val_dice_coef: 0.6328\n    Epoch 6/20\n    40/40 [==============================] - 12s 307ms/step - loss: 0.2466 - iou_coef: 0.6123 - dice_coef: 0.7534 - val_loss: 0.2769 - val_iou_coef: 0.5749 - val_dice_coef: 0.7231\n    Epoch 7/20\n    40/40 [==============================] - 12s 306ms/step - loss: 0.2387 - iou_coef: 0.6218 - dice_coef: 0.7613 - val_loss: 0.2393 - val_iou_coef: 0.6214 - val_dice_coef: 0.7607\n    Epoch 8/20\n    40/40 [==============================] - 12s 307ms/step - loss: 0.2366 - iou_coef: 0.6237 - dice_coef: 0.7634 - val_loss: 0.2506 - val_iou_coef: 0.6070 - val_dice_coef: 0.7494\n    Epoch 9/20\n    40/40 [==============================] - 12s 307ms/step - loss: 0.2292 - iou_coef: 0.6335 - dice_coef: 0.7708 - val_loss: 0.2347 - val_iou_coef: 0.6276 - val_dice_coef: 0.7653\n    Epoch 10/20\n    40/40 [==============================] - 12s 307ms/step - loss: 0.2356 - iou_coef: 0.6254 - dice_coef: 0.7644 - val_loss: 0.2428 - val_iou_coef: 0.6166 - val_dice_coef: 0.7572\n    Epoch 11/20\n    40/40 [==============================] - 12s 306ms/step - loss: 0.2324 - iou_coef: 0.6306 - dice_coef: 0.7676 - val_loss: 0.2303 - val_iou_coef: 0.6334 - val_dice_coef: 0.7697\n    Epoch 12/20\n    40/40 [==============================] - 12s 306ms/step - loss: 0.2189 - iou_coef: 0.6459 - dice_coef: 0.7811 - val_loss: 0.2283 - val_iou_coef: 0.6358 - val_dice_coef: 0.7717\n    Epoch 13/20\n    40/40 [==============================] - 12s 306ms/step - loss: 0.2178 - iou_coef: 0.6480 - dice_coef: 0.7822 - val_loss: 0.2269 - val_iou_coef: 0.6382 - val_dice_coef: 0.7731\n    Epoch 14/20\n    40/40 [==============================] - 12s 306ms/step - loss: 0.2213 - iou_coef: 0.6442 - dice_coef: 0.7787 - val_loss: 0.2288 - val_iou_coef: 0.6354 - val_dice_coef: 0.7712\n    Epoch 15/20\n    40/40 [==============================] - 12s 306ms/step - loss: 0.2264 - iou_coef: 0.6383 - dice_coef: 0.7736 - val_loss: 0.2659 - val_iou_coef: 0.5871 - val_dice_coef: 0.7341\n    Epoch 16/20\n    40/40 [==============================] - 12s 306ms/step - loss: 0.2249 - iou_coef: 0.6392 - dice_coef: 0.7751 - val_loss: 0.2308 - val_iou_coef: 0.6319 - val_dice_coef: 0.7692\n    Epoch 17/20\n    40/40 [==============================] - 12s 306ms/step - loss: 0.2157 - iou_coef: 0.6512 - dice_coef: 0.7843 - val_loss: 0.2463 - val_iou_coef: 0.6144 - val_dice_coef: 0.7537\n    Epoch 18/20\n    40/40 [==============================] - 12s 306ms/step - loss: 0.2148 - iou_coef: 0.6517 - dice_coef: 0.7852 - val_loss: 0.2269 - val_iou_coef: 0.6383 - val_dice_coef: 0.7731\n    Epoch 19/20\n    40/40 [==============================] - 12s 306ms/step - loss: 0.2151 - iou_coef: 0.6514 - dice_coef: 0.7849 - val_loss: 0.2219 - val_iou_coef: 0.6444 - val_dice_coef: 0.7781\n    Epoch 20/20\n    40/40 [==============================] - 12s 306ms/step - loss: 0.2163 - iou_coef: 0.6498 - dice_coef: 0.7837 - val_loss: 0.2280 - val_iou_coef: 0.6366 - val_dice_coef: 0.7720\n    Epoch 1/30\n    16/16 [==============================] - 11s 456ms/step - loss: 0.4852 - iou_coef: 0.3647 - dice_coef: 0.5148 - val_loss: 0.6001 - val_iou_coef: 0.2662 - val_dice_coef: 0.3999\n    Epoch 2/30\n    16/16 [==============================] - 6s 356ms/step - loss: 0.3791 - iou_coef: 0.4641 - dice_coef: 0.6209 - val_loss: 0.6000 - val_iou_coef: 0.2663 - val_dice_coef: 0.4000\n    Epoch 3/30\n    16/16 [==============================] - 6s 356ms/step - loss: 0.3423 - iou_coef: 0.5010 - dice_coef: 0.6577 - val_loss: 0.5623 - val_iou_coef: 0.2983 - val_dice_coef: 0.4377\n    Epoch 4/30\n    16/16 [==============================] - 6s 358ms/step - loss: 0.3089 - iou_coef: 0.5395 - dice_coef: 0.6911 - val_loss: 0.5591 - val_iou_coef: 0.2993 - val_dice_coef: 0.4409\n    Epoch 5/30\n    16/16 [==============================] - 6s 357ms/step - loss: 0.2743 - iou_coef: 0.5768 - dice_coef: 0.7257 - val_loss: 0.5915 - val_iou_coef: 0.2726 - val_dice_coef: 0.4085\n    Epoch 6/30\n    16/16 [==============================] - 6s 358ms/step - loss: 0.2628 - iou_coef: 0.5897 - dice_coef: 0.7372 - val_loss: 0.5907 - val_iou_coef: 0.2729 - val_dice_coef: 0.4093\n    Epoch 7/30\n    16/16 [==============================] - 6s 356ms/step - loss: 0.2647 - iou_coef: 0.5886 - dice_coef: 0.7353 - val_loss: 0.5534 - val_iou_coef: 0.3014 - val_dice_coef: 0.4466\n    Epoch 8/30\n    16/16 [==============================] - 6s 357ms/step - loss: 0.2538 - iou_coef: 0.6020 - dice_coef: 0.7462 - val_loss: 0.3743 - val_iou_coef: 0.4680 - val_dice_coef: 0.6257\n    Epoch 9/30\n    16/16 [==============================] - 6s 356ms/step - loss: 0.2472 - iou_coef: 0.6118 - dice_coef: 0.7528 - val_loss: 0.3810 - val_iou_coef: 0.4595 - val_dice_coef: 0.6190\n    Epoch 10/30\n    16/16 [==============================] - 6s 357ms/step - loss: 0.2513 - iou_coef: 0.6056 - dice_coef: 0.7487 - val_loss: 0.2697 - val_iou_coef: 0.5883 - val_dice_coef: 0.7303\n    Epoch 11/30\n    16/16 [==============================] - 6s 356ms/step - loss: 0.2420 - iou_coef: 0.6149 - dice_coef: 0.7580 - val_loss: 0.2680 - val_iou_coef: 0.5849 - val_dice_coef: 0.7320\n    Epoch 12/30\n    16/16 [==============================] - 6s 357ms/step - loss: 0.2334 - iou_coef: 0.6279 - dice_coef: 0.7666 - val_loss: 0.2927 - val_iou_coef: 0.5540 - val_dice_coef: 0.7073\n    Epoch 13/30\n    16/16 [==============================] - 6s 357ms/step - loss: 0.2345 - iou_coef: 0.6254 - dice_coef: 0.7655 - val_loss: 0.3896 - val_iou_coef: 0.4498 - val_dice_coef: 0.6104\n    Epoch 14/30\n    16/16 [==============================] - 6s 357ms/step - loss: 0.2329 - iou_coef: 0.6290 - dice_coef: 0.7671 - val_loss: 0.3420 - val_iou_coef: 0.4969 - val_dice_coef: 0.6580\n    Epoch 15/30\n    16/16 [==============================] - 6s 357ms/step - loss: 0.2387 - iou_coef: 0.6200 - dice_coef: 0.7613 - val_loss: 0.3658 - val_iou_coef: 0.4753 - val_dice_coef: 0.6342\n    Epoch 16/30\n    16/16 [==============================] - 6s 357ms/step - loss: 0.2235 - iou_coef: 0.6398 - dice_coef: 0.7765 - val_loss: 0.2685 - val_iou_coef: 0.5850 - val_dice_coef: 0.7315\n    Epoch 17/30\n    16/16 [==============================] - 6s 357ms/step - loss: 0.2204 - iou_coef: 0.6436 - dice_coef: 0.7796 - val_loss: 0.2407 - val_iou_coef: 0.6206 - val_dice_coef: 0.7593\n    Epoch 18/30\n    16/16 [==============================] - 6s 357ms/step - loss: 0.2273 - iou_coef: 0.6343 - dice_coef: 0.7727 - val_loss: 0.2822 - val_iou_coef: 0.5747 - val_dice_coef: 0.7178\n    Epoch 19/30\n    16/16 [==============================] - 6s 356ms/step - loss: 0.2183 - iou_coef: 0.6467 - dice_coef: 0.7817 - val_loss: 0.2407 - val_iou_coef: 0.6211 - val_dice_coef: 0.7593\n    Epoch 20/30\n    16/16 [==============================] - 6s 357ms/step - loss: 0.2171 - iou_coef: 0.6477 - dice_coef: 0.7829 - val_loss: 0.2360 - val_iou_coef: 0.6266 - val_dice_coef: 0.7640\n    Epoch 21/30\n    16/16 [==============================] - 6s 358ms/step - loss: 0.2326 - iou_coef: 0.6298 - dice_coef: 0.7674 - val_loss: 0.3109 - val_iou_coef: 0.5314 - val_dice_coef: 0.6891\n    Epoch 22/30\n    16/16 [==============================] - 6s 357ms/step - loss: 0.2262 - iou_coef: 0.6371 - dice_coef: 0.7738 - val_loss: 0.2488 - val_iou_coef: 0.6091 - val_dice_coef: 0.7512\n    Epoch 23/30\n    16/16 [==============================] - 6s 356ms/step - loss: 0.2281 - iou_coef: 0.6350 - dice_coef: 0.7719 - val_loss: 0.3441 - val_iou_coef: 0.4983 - val_dice_coef: 0.6559\n    Epoch 24/30\n    16/16 [==============================] - 6s 357ms/step - loss: 0.2133 - iou_coef: 0.6533 - dice_coef: 0.7867 - val_loss: 0.2467 - val_iou_coef: 0.6122 - val_dice_coef: 0.7533\n    Epoch 25/30\n    16/16 [==============================] - 6s 357ms/step - loss: 0.2141 - iou_coef: 0.6527 - dice_coef: 0.7859 - val_loss: 0.2388 - val_iou_coef: 0.6228 - val_dice_coef: 0.7612\n    Epoch 26/30\n    16/16 [==============================] - 6s 358ms/step - loss: 0.2119 - iou_coef: 0.6549 - dice_coef: 0.7881 - val_loss: 0.2408 - val_iou_coef: 0.6202 - val_dice_coef: 0.7592\n    Epoch 27/30\n    16/16 [==============================] - 6s 357ms/step - loss: 0.1971 - iou_coef: 0.6743 - dice_coef: 0.8029 - val_loss: 0.2382 - val_iou_coef: 0.6234 - val_dice_coef: 0.7618\n    Epoch 28/30\n    16/16 [==============================] - 6s 356ms/step - loss: 0.2002 - iou_coef: 0.6710 - dice_coef: 0.7998 - val_loss: 0.2804 - val_iou_coef: 0.5731 - val_dice_coef: 0.7196\n    Epoch 29/30\n    16/16 [==============================] - 6s 357ms/step - loss: 0.2151 - iou_coef: 0.6501 - dice_coef: 0.7849 - val_loss: 0.2519 - val_iou_coef: 0.6070 - val_dice_coef: 0.7481\n    Epoch 30/30\n    16/16 [==============================] - 6s 357ms/step - loss: 0.2120 - iou_coef: 0.6554 - dice_coef: 0.7880 - val_loss: 0.2359 - val_iou_coef: 0.6262 - val_dice_coef: 0.7641\n    Epoch 1/40\n    8/8 [==============================] - 9s 657ms/step - loss: 0.5749 - iou_coef: 0.2826 - dice_coef: 0.4251 - val_loss: 0.6103 - val_iou_coef: 0.2566 - val_dice_coef: 0.3897\n    Epoch 2/40\n    8/8 [==============================] - 3s 450ms/step - loss: 0.5082 - iou_coef: 0.3386 - dice_coef: 0.4918 - val_loss: 0.6064 - val_iou_coef: 0.2603 - val_dice_coef: 0.3936\n    Epoch 3/40\n    8/8 [==============================] - 3s 450ms/step - loss: 0.4825 - iou_coef: 0.3619 - dice_coef: 0.5175 - val_loss: 0.6064 - val_iou_coef: 0.2603 - val_dice_coef: 0.3936\n    Epoch 4/40\n    8/8 [==============================] - 3s 451ms/step - loss: 0.4653 - iou_coef: 0.3779 - dice_coef: 0.5347 - val_loss: 0.6063 - val_iou_coef: 0.2604 - val_dice_coef: 0.3937\n    Epoch 5/40\n    8/8 [==============================] - 3s 450ms/step - loss: 0.4398 - iou_coef: 0.4008 - dice_coef: 0.5602 - val_loss: 0.6037 - val_iou_coef: 0.2626 - val_dice_coef: 0.3963\n    Epoch 6/40\n    8/8 [==============================] - 3s 453ms/step - loss: 0.4118 - iou_coef: 0.4277 - dice_coef: 0.5882 - val_loss: 0.6004 - val_iou_coef: 0.2649 - val_dice_coef: 0.3996\n    Epoch 7/40\n    8/8 [==============================] - 3s 453ms/step - loss: 0.3778 - iou_coef: 0.4611 - dice_coef: 0.6222 - val_loss: 0.5941 - val_iou_coef: 0.2710 - val_dice_coef: 0.4059\n    Epoch 8/40\n    8/8 [==============================] - 3s 453ms/step - loss: 0.3216 - iou_coef: 0.5228 - dice_coef: 0.6784 - val_loss: 0.5658 - val_iou_coef: 0.2944 - val_dice_coef: 0.4342\n    Epoch 9/40\n    8/8 [==============================] - 3s 452ms/step - loss: 0.2633 - iou_coef: 0.5885 - dice_coef: 0.7367 - val_loss: 0.5164 - val_iou_coef: 0.3389 - val_dice_coef: 0.4836\n    Epoch 10/40\n    8/8 [==============================] - 3s 452ms/step - loss: 0.2611 - iou_coef: 0.5909 - dice_coef: 0.7389 - val_loss: 0.4703 - val_iou_coef: 0.3727 - val_dice_coef: 0.5297\n    Epoch 11/40\n    8/8 [==============================] - 3s 450ms/step - loss: 0.2438 - iou_coef: 0.6144 - dice_coef: 0.7562 - val_loss: 0.4863 - val_iou_coef: 0.3563 - val_dice_coef: 0.5137\n    Epoch 12/40\n    8/8 [==============================] - 3s 450ms/step - loss: 0.2292 - iou_coef: 0.6311 - dice_coef: 0.7708 - val_loss: 0.3317 - val_iou_coef: 0.5170 - val_dice_coef: 0.6683\n    Epoch 13/40\n    8/8 [==============================] - 3s 452ms/step - loss: 0.2300 - iou_coef: 0.6299 - dice_coef: 0.7700 - val_loss: 0.3637 - val_iou_coef: 0.4753 - val_dice_coef: 0.6363\n    Epoch 14/40\n    8/8 [==============================] - 3s 454ms/step - loss: 0.2191 - iou_coef: 0.6443 - dice_coef: 0.7809 - val_loss: 0.3810 - val_iou_coef: 0.4598 - val_dice_coef: 0.6190\n    Epoch 15/40\n    8/8 [==============================] - 3s 453ms/step - loss: 0.2082 - iou_coef: 0.6590 - dice_coef: 0.7918 - val_loss: 0.2986 - val_iou_coef: 0.5494 - val_dice_coef: 0.7014\n    Epoch 16/40\n    8/8 [==============================] - 3s 452ms/step - loss: 0.2144 - iou_coef: 0.6502 - dice_coef: 0.7856 - val_loss: 0.2653 - val_iou_coef: 0.5910 - val_dice_coef: 0.7347\n    Epoch 17/40\n    8/8 [==============================] - 3s 452ms/step - loss: 0.2097 - iou_coef: 0.6576 - dice_coef: 0.7903 - val_loss: 0.2737 - val_iou_coef: 0.5795 - val_dice_coef: 0.7263\n    Epoch 18/40\n    8/8 [==============================] - 3s 452ms/step - loss: 0.2084 - iou_coef: 0.6592 - dice_coef: 0.7916 - val_loss: 0.3772 - val_iou_coef: 0.4578 - val_dice_coef: 0.6228\n    Epoch 19/40\n    8/8 [==============================] - 3s 451ms/step - loss: 0.2334 - iou_coef: 0.6301 - dice_coef: 0.7666 - val_loss: 0.3686 - val_iou_coef: 0.4774 - val_dice_coef: 0.6314\n    Epoch 20/40\n    8/8 [==============================] - 3s 453ms/step - loss: 0.2022 - iou_coef: 0.6672 - dice_coef: 0.7978 - val_loss: 0.3184 - val_iou_coef: 0.5284 - val_dice_coef: 0.6816\n    Epoch 21/40\n    8/8 [==============================] - 3s 453ms/step - loss: 0.1989 - iou_coef: 0.6725 - dice_coef: 0.8011 - val_loss: 0.2678 - val_iou_coef: 0.5886 - val_dice_coef: 0.7322\n    Epoch 22/40\n    8/8 [==============================] - 3s 450ms/step - loss: 0.1913 - iou_coef: 0.6821 - dice_coef: 0.8087 - val_loss: 0.2555 - val_iou_coef: 0.6026 - val_dice_coef: 0.7445\n    Epoch 23/40\n    8/8 [==============================] - 3s 450ms/step - loss: 0.1971 - iou_coef: 0.6741 - dice_coef: 0.8029 - val_loss: 0.3022 - val_iou_coef: 0.5486 - val_dice_coef: 0.6978\n    Epoch 24/40\n    8/8 [==============================] - 3s 452ms/step - loss: 0.1881 - iou_coef: 0.6865 - dice_coef: 0.8119 - val_loss: 0.2788 - val_iou_coef: 0.5753 - val_dice_coef: 0.7212\n    Epoch 25/40\n    8/8 [==============================] - 3s 451ms/step - loss: 0.1893 - iou_coef: 0.6848 - dice_coef: 0.8107 - val_loss: 0.2560 - val_iou_coef: 0.6018 - val_dice_coef: 0.7440\n    Epoch 26/40\n    8/8 [==============================] - 3s 452ms/step - loss: 0.1957 - iou_coef: 0.6763 - dice_coef: 0.8043 - val_loss: 0.3181 - val_iou_coef: 0.5245 - val_dice_coef: 0.6819\n    Epoch 27/40\n    8/8 [==============================] - 3s 452ms/step - loss: 0.1950 - iou_coef: 0.6773 - dice_coef: 0.8050 - val_loss: 0.2959 - val_iou_coef: 0.5522 - val_dice_coef: 0.7041\n    Epoch 28/40\n    8/8 [==============================] - 3s 451ms/step - loss: 0.2058 - iou_coef: 0.6633 - dice_coef: 0.7942 - val_loss: 0.2789 - val_iou_coef: 0.5729 - val_dice_coef: 0.7211\n    Epoch 29/40\n    8/8 [==============================] - 3s 452ms/step - loss: 0.2087 - iou_coef: 0.6587 - dice_coef: 0.7913 - val_loss: 0.2819 - val_iou_coef: 0.5710 - val_dice_coef: 0.7181\n    Epoch 30/40\n    8/8 [==============================] - 3s 452ms/step - loss: 0.1904 - iou_coef: 0.6836 - dice_coef: 0.8096 - val_loss: 0.2552 - val_iou_coef: 0.6031 - val_dice_coef: 0.7448\n    Epoch 31/40\n    8/8 [==============================] - 3s 451ms/step - loss: 0.1701 - iou_coef: 0.7118 - dice_coef: 0.8299 - val_loss: 0.2590 - val_iou_coef: 0.5988 - val_dice_coef: 0.7410\n    Epoch 32/40\n    8/8 [==============================] - 3s 450ms/step - loss: 0.1741 - iou_coef: 0.7060 - dice_coef: 0.8259 - val_loss: 0.2581 - val_iou_coef: 0.6005 - val_dice_coef: 0.7419\n    Epoch 33/40\n    8/8 [==============================] - 3s 449ms/step - loss: 0.1714 - iou_coef: 0.7099 - dice_coef: 0.8286 - val_loss: 0.2636 - val_iou_coef: 0.5931 - val_dice_coef: 0.7364\n    Epoch 34/40\n    8/8 [==============================] - 3s 450ms/step - loss: 0.1728 - iou_coef: 0.7081 - dice_coef: 0.8272 - val_loss: 0.2693 - val_iou_coef: 0.5884 - val_dice_coef: 0.7307\n    Epoch 35/40\n    8/8 [==============================] - 3s 453ms/step - loss: 0.1783 - iou_coef: 0.7007 - dice_coef: 0.8217 - val_loss: 0.2731 - val_iou_coef: 0.5799 - val_dice_coef: 0.7269\n    Epoch 36/40\n    8/8 [==============================] - 3s 449ms/step - loss: 0.1826 - iou_coef: 0.6950 - dice_coef: 0.8174 - val_loss: 0.2582 - val_iou_coef: 0.5978 - val_dice_coef: 0.7418\n    Epoch 37/40\n    8/8 [==============================] - 3s 453ms/step - loss: 0.1746 - iou_coef: 0.7070 - dice_coef: 0.8254 - val_loss: 0.2578 - val_iou_coef: 0.5993 - val_dice_coef: 0.7422\n    Epoch 38/40\n    8/8 [==============================] - 3s 451ms/step - loss: 0.1738 - iou_coef: 0.7070 - dice_coef: 0.8262 - val_loss: 0.2725 - val_iou_coef: 0.5839 - val_dice_coef: 0.7275\n    Epoch 39/40\n    8/8 [==============================] - 3s 452ms/step - loss: 0.1842 - iou_coef: 0.6938 - dice_coef: 0.8158 - val_loss: 0.3095 - val_iou_coef: 0.5379 - val_dice_coef: 0.6905\n    Epoch 40/40\n    8/8 [==============================] - 3s 450ms/step - loss: 0.1806 - iou_coef: 0.6986 - dice_coef: 0.8194 - val_loss: 0.2693 - val_iou_coef: 0.5846 - val_dice_coef: 0.7307\n    Epoch 1/60\n    4/4 [==============================] - 8s 1s/step - loss: 0.6086 - iou_coef: 0.2553 - dice_coef: 0.3914 - val_loss: 0.5977 - val_iou_coef: 0.2677 - val_dice_coef: 0.4023\n    Epoch 2/60\n    4/4 [==============================] - 2s 689ms/step - loss: 0.5153 - iou_coef: 0.3349 - dice_coef: 0.4847 - val_loss: 0.5999 - val_iou_coef: 0.2664 - val_dice_coef: 0.4001\n    Epoch 3/60\n    4/4 [==============================] - 2s 684ms/step - loss: 0.4647 - iou_coef: 0.3801 - dice_coef: 0.5353 - val_loss: 0.6000 - val_iou_coef: 0.2663 - val_dice_coef: 0.4000\n    Epoch 4/60\n    4/4 [==============================] - 2s 689ms/step - loss: 0.4302 - iou_coef: 0.4124 - dice_coef: 0.5698 - val_loss: 0.6000 - val_iou_coef: 0.2663 - val_dice_coef: 0.4000\n    Epoch 5/60\n    4/4 [==============================] - 2s 683ms/step - loss: 0.4153 - iou_coef: 0.4262 - dice_coef: 0.5847 - val_loss: 0.5998 - val_iou_coef: 0.2665 - val_dice_coef: 0.4002\n    Epoch 6/60\n    4/4 [==============================] - 2s 689ms/step - loss: 0.3863 - iou_coef: 0.4548 - dice_coef: 0.6137 - val_loss: 0.5999 - val_iou_coef: 0.2664 - val_dice_coef: 0.4001\n    Epoch 7/60\n    4/4 [==============================] - 2s 695ms/step - loss: 0.3757 - iou_coef: 0.4658 - dice_coef: 0.6243 - val_loss: 0.5988 - val_iou_coef: 0.2672 - val_dice_coef: 0.4012\n    Epoch 8/60\n    4/4 [==============================] - 2s 690ms/step - loss: 0.3698 - iou_coef: 0.4718 - dice_coef: 0.6302 - val_loss: 0.5990 - val_iou_coef: 0.2671 - val_dice_coef: 0.4010\n    Epoch 9/60\n    4/4 [==============================] - 2s 688ms/step - loss: 0.3573 - iou_coef: 0.4850 - dice_coef: 0.6427 - val_loss: 0.5972 - val_iou_coef: 0.2685 - val_dice_coef: 0.4028\n    Epoch 10/60\n    4/4 [==============================] - 2s 690ms/step - loss: 0.3329 - iou_coef: 0.5101 - dice_coef: 0.6671 - val_loss: 0.5853 - val_iou_coef: 0.2771 - val_dice_coef: 0.4147\n    Epoch 11/60\n    4/4 [==============================] - 2s 689ms/step - loss: 0.3119 - iou_coef: 0.5337 - dice_coef: 0.6881 - val_loss: 0.5729 - val_iou_coef: 0.2870 - val_dice_coef: 0.4271\n    Epoch 12/60\n    4/4 [==============================] - 2s 690ms/step - loss: 0.3111 - iou_coef: 0.5351 - dice_coef: 0.6889 - val_loss: 0.5738 - val_iou_coef: 0.2863 - val_dice_coef: 0.4262\n    Epoch 13/60\n    4/4 [==============================] - 2s 689ms/step - loss: 0.3127 - iou_coef: 0.5324 - dice_coef: 0.6873 - val_loss: 0.5657 - val_iou_coef: 0.2926 - val_dice_coef: 0.4343\n    Epoch 14/60\n    4/4 [==============================] - 2s 690ms/step - loss: 0.3066 - iou_coef: 0.5402 - dice_coef: 0.6934 - val_loss: 0.5716 - val_iou_coef: 0.2874 - val_dice_coef: 0.4284\n    Epoch 15/60\n    4/4 [==============================] - 2s 689ms/step - loss: 0.2947 - iou_coef: 0.5534 - dice_coef: 0.7053 - val_loss: 0.5244 - val_iou_coef: 0.3284 - val_dice_coef: 0.4756\n    Epoch 16/60\n    4/4 [==============================] - 2s 688ms/step - loss: 0.2916 - iou_coef: 0.5574 - dice_coef: 0.7084 - val_loss: 0.5604 - val_iou_coef: 0.2968 - val_dice_coef: 0.4396\n    Epoch 17/60\n    4/4 [==============================] - 2s 689ms/step - loss: 0.3013 - iou_coef: 0.5445 - dice_coef: 0.6987 - val_loss: 0.5547 - val_iou_coef: 0.2992 - val_dice_coef: 0.4453\n    Epoch 18/60\n    4/4 [==============================] - 2s 689ms/step - loss: 0.3020 - iou_coef: 0.5475 - dice_coef: 0.6980 - val_loss: 0.5918 - val_iou_coef: 0.2727 - val_dice_coef: 0.4082\n    Epoch 19/60\n    4/4 [==============================] - 2s 689ms/step - loss: 0.2930 - iou_coef: 0.5559 - dice_coef: 0.7070 - val_loss: 0.5274 - val_iou_coef: 0.3244 - val_dice_coef: 0.4726\n    Epoch 20/60\n    4/4 [==============================] - 2s 689ms/step - loss: 0.2883 - iou_coef: 0.5603 - dice_coef: 0.7117 - val_loss: 0.5844 - val_iou_coef: 0.2776 - val_dice_coef: 0.4156\n    Epoch 21/60\n    4/4 [==============================] - 2s 689ms/step - loss: 0.2822 - iou_coef: 0.5701 - dice_coef: 0.7178 - val_loss: 0.5854 - val_iou_coef: 0.2769 - val_dice_coef: 0.4146\n    Epoch 22/60\n    4/4 [==============================] - 2s 688ms/step - loss: 0.2699 - iou_coef: 0.5830 - dice_coef: 0.7301 - val_loss: 0.5291 - val_iou_coef: 0.3207 - val_dice_coef: 0.4709\n    Epoch 23/60\n    4/4 [==============================] - 2s 690ms/step - loss: 0.2605 - iou_coef: 0.5949 - dice_coef: 0.7395 - val_loss: 0.5269 - val_iou_coef: 0.3237 - val_dice_coef: 0.4731\n    Epoch 24/60\n    4/4 [==============================] - 2s 688ms/step - loss: 0.3005 - iou_coef: 0.5450 - dice_coef: 0.6995 - val_loss: 0.5275 - val_iou_coef: 0.3218 - val_dice_coef: 0.4725\n    Epoch 25/60\n    4/4 [==============================] - 2s 688ms/step - loss: 0.2629 - iou_coef: 0.5925 - dice_coef: 0.7371 - val_loss: 0.5611 - val_iou_coef: 0.2965 - val_dice_coef: 0.4389\n    Epoch 26/60\n    4/4 [==============================] - 2s 689ms/step - loss: 0.2603 - iou_coef: 0.5947 - dice_coef: 0.7397 - val_loss: 0.4210 - val_iou_coef: 0.4236 - val_dice_coef: 0.5790\n    Epoch 27/60\n    4/4 [==============================] - 2s 689ms/step - loss: 0.2612 - iou_coef: 0.5935 - dice_coef: 0.7388 - val_loss: 0.5566 - val_iou_coef: 0.2990 - val_dice_coef: 0.4434\n    Epoch 28/60\n    4/4 [==============================] - 2s 688ms/step - loss: 0.2570 - iou_coef: 0.5988 - dice_coef: 0.7430 - val_loss: 0.4526 - val_iou_coef: 0.3946 - val_dice_coef: 0.5474\n    Epoch 29/60\n    4/4 [==============================] - 2s 687ms/step - loss: 0.2583 - iou_coef: 0.5991 - dice_coef: 0.7417 - val_loss: 0.4503 - val_iou_coef: 0.3891 - val_dice_coef: 0.5497\n    Epoch 30/60\n    4/4 [==============================] - 2s 688ms/step - loss: 0.2546 - iou_coef: 0.6027 - dice_coef: 0.7454 - val_loss: 0.4898 - val_iou_coef: 0.3595 - val_dice_coef: 0.5102\n    Epoch 31/60\n    4/4 [==============================] - 2s 689ms/step - loss: 0.2546 - iou_coef: 0.6031 - dice_coef: 0.7454 - val_loss: 0.4289 - val_iou_coef: 0.4102 - val_dice_coef: 0.5711\n    Epoch 32/60\n    4/4 [==============================] - 2s 690ms/step - loss: 0.2836 - iou_coef: 0.5656 - dice_coef: 0.7164 - val_loss: 0.5106 - val_iou_coef: 0.3381 - val_dice_coef: 0.4894\n    Epoch 33/60\n    4/4 [==============================] - 2s 688ms/step - loss: 0.2468 - iou_coef: 0.6114 - dice_coef: 0.7532 - val_loss: 0.4386 - val_iou_coef: 0.4044 - val_dice_coef: 0.5614\n    Epoch 34/60\n    4/4 [==============================] - 2s 691ms/step - loss: 0.2469 - iou_coef: 0.6115 - dice_coef: 0.7531 - val_loss: 0.5358 - val_iou_coef: 0.3170 - val_dice_coef: 0.4642\n    Epoch 35/60\n    4/4 [==============================] - 2s 688ms/step - loss: 0.2369 - iou_coef: 0.6240 - dice_coef: 0.7631 - val_loss: 0.4641 - val_iou_coef: 0.3782 - val_dice_coef: 0.5359\n    Epoch 36/60\n    4/4 [==============================] - 2s 692ms/step - loss: 0.2444 - iou_coef: 0.6143 - dice_coef: 0.7556 - val_loss: 0.5135 - val_iou_coef: 0.3345 - val_dice_coef: 0.4865\n    Epoch 37/60\n    4/4 [==============================] - 2s 688ms/step - loss: 0.2504 - iou_coef: 0.6070 - dice_coef: 0.7496 - val_loss: 0.4917 - val_iou_coef: 0.3568 - val_dice_coef: 0.5083\n    Epoch 38/60\n    4/4 [==============================] - 2s 690ms/step - loss: 0.2359 - iou_coef: 0.6259 - dice_coef: 0.7641 - val_loss: 0.4710 - val_iou_coef: 0.3748 - val_dice_coef: 0.5290\n    Epoch 39/60\n    4/4 [==============================] - 2s 691ms/step - loss: 0.2365 - iou_coef: 0.6240 - dice_coef: 0.7635 - val_loss: 0.4456 - val_iou_coef: 0.3944 - val_dice_coef: 0.5544\n    Epoch 40/60\n    4/4 [==============================] - 2s 691ms/step - loss: 0.2558 - iou_coef: 0.6004 - dice_coef: 0.7442 - val_loss: 0.4221 - val_iou_coef: 0.4194 - val_dice_coef: 0.5779\n    Epoch 41/60\n    4/4 [==============================] - 2s 686ms/step - loss: 0.1810 - iou_coef: 0.6968 - dice_coef: 0.8190 - val_loss: 0.4206 - val_iou_coef: 0.4204 - val_dice_coef: 0.5794\n    Epoch 42/60\n    4/4 [==============================] - 2s 688ms/step - loss: 0.1690 - iou_coef: 0.7143 - dice_coef: 0.8310 - val_loss: 0.4201 - val_iou_coef: 0.4265 - val_dice_coef: 0.5799\n    Epoch 43/60\n    4/4 [==============================] - 2s 688ms/step - loss: 0.1634 - iou_coef: 0.7238 - dice_coef: 0.8366 - val_loss: 0.4228 - val_iou_coef: 0.4150 - val_dice_coef: 0.5772\n    Epoch 44/60\n    4/4 [==============================] - 2s 687ms/step - loss: 0.1916 - iou_coef: 0.6829 - dice_coef: 0.8084 - val_loss: 0.3675 - val_iou_coef: 0.4751 - val_dice_coef: 0.6325\n    Epoch 45/60\n    4/4 [==============================] - 2s 691ms/step - loss: 0.1490 - iou_coef: 0.7432 - dice_coef: 0.8510 - val_loss: 0.3221 - val_iou_coef: 0.5249 - val_dice_coef: 0.6779\n    Epoch 46/60\n    4/4 [==============================] - 2s 688ms/step - loss: 0.1665 - iou_coef: 0.7186 - dice_coef: 0.8335 - val_loss: 0.3709 - val_iou_coef: 0.4700 - val_dice_coef: 0.6291\n    Epoch 47/60\n    4/4 [==============================] - 2s 690ms/step - loss: 0.1404 - iou_coef: 0.7568 - dice_coef: 0.8596 - val_loss: 0.3258 - val_iou_coef: 0.5186 - val_dice_coef: 0.6742\n    Epoch 48/60\n    4/4 [==============================] - 2s 690ms/step - loss: 0.1454 - iou_coef: 0.7485 - dice_coef: 0.8546 - val_loss: 0.3143 - val_iou_coef: 0.5343 - val_dice_coef: 0.6857\n    Epoch 49/60\n    4/4 [==============================] - 2s 683ms/step - loss: 0.1392 - iou_coef: 0.7585 - dice_coef: 0.8608 - val_loss: 0.2910 - val_iou_coef: 0.5609 - val_dice_coef: 0.7090\n    Epoch 50/60\n    4/4 [==============================] - 2s 688ms/step - loss: 0.1358 - iou_coef: 0.7636 - dice_coef: 0.8642 - val_loss: 0.3669 - val_iou_coef: 0.4749 - val_dice_coef: 0.6331\n    Epoch 51/60\n    4/4 [==============================] - 2s 681ms/step - loss: 0.1361 - iou_coef: 0.7631 - dice_coef: 0.8639 - val_loss: 0.2905 - val_iou_coef: 0.5602 - val_dice_coef: 0.7095\n    Epoch 52/60\n    4/4 [==============================] - 2s 688ms/step - loss: 0.1406 - iou_coef: 0.7560 - dice_coef: 0.8594 - val_loss: 0.2949 - val_iou_coef: 0.5558 - val_dice_coef: 0.7051\n    Epoch 53/60\n    4/4 [==============================] - 2s 690ms/step - loss: 0.1398 - iou_coef: 0.7569 - dice_coef: 0.8602 - val_loss: 0.3106 - val_iou_coef: 0.5358 - val_dice_coef: 0.6894\n    Epoch 54/60\n    4/4 [==============================] - 2s 685ms/step - loss: 0.1591 - iou_coef: 0.7310 - dice_coef: 0.8409 - val_loss: 0.3202 - val_iou_coef: 0.5293 - val_dice_coef: 0.6798\n    Epoch 55/60\n    4/4 [==============================] - 2s 691ms/step - loss: 0.1364 - iou_coef: 0.7626 - dice_coef: 0.8636 - val_loss: 0.3119 - val_iou_coef: 0.5337 - val_dice_coef: 0.6881\n    Epoch 56/60\n    4/4 [==============================] - 2s 687ms/step - loss: 0.1419 - iou_coef: 0.7548 - dice_coef: 0.8581 - val_loss: 0.2812 - val_iou_coef: 0.5721 - val_dice_coef: 0.7188\n    Epoch 57/60\n    4/4 [==============================] - 2s 688ms/step - loss: 0.1483 - iou_coef: 0.7446 - dice_coef: 0.8517 - val_loss: 0.3076 - val_iou_coef: 0.5383 - val_dice_coef: 0.6924\n    Epoch 58/60\n    4/4 [==============================] - 2s 689ms/step - loss: 0.1331 - iou_coef: 0.7669 - dice_coef: 0.8669 - val_loss: 0.3180 - val_iou_coef: 0.5259 - val_dice_coef: 0.6820\n    Epoch 59/60\n    4/4 [==============================] - 2s 690ms/step - loss: 0.1396 - iou_coef: 0.7574 - dice_coef: 0.8604 - val_loss: 0.2819 - val_iou_coef: 0.5709 - val_dice_coef: 0.7181\n    Epoch 60/60\n    4/4 [==============================] - 2s 685ms/step - loss: 0.1361 - iou_coef: 0.7619 - dice_coef: 0.8639 - val_loss: 0.3526 - val_iou_coef: 0.4854 - val_dice_coef: 0.6474\n    Epoch 1/120\n    2/2 [==============================] - 7s 3s/step - loss: 0.6735 - iou_coef: 0.2018 - dice_coef: 0.3265 - val_loss: 0.6399 - val_iou_coef: 0.2292 - val_dice_coef: 0.3601\n    Epoch 2/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.6326 - iou_coef: 0.2332 - dice_coef: 0.3674 - val_loss: 0.6373 - val_iou_coef: 0.2321 - val_dice_coef: 0.3627\n    Epoch 3/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.5972 - iou_coef: 0.2610 - dice_coef: 0.4028 - val_loss: 0.6295 - val_iou_coef: 0.2393 - val_dice_coef: 0.3705\n    Epoch 4/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.5681 - iou_coef: 0.2827 - dice_coef: 0.4319 - val_loss: 0.6297 - val_iou_coef: 0.2392 - val_dice_coef: 0.3703\n    Epoch 5/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.5355 - iou_coef: 0.3115 - dice_coef: 0.4645 - val_loss: 0.6297 - val_iou_coef: 0.2392 - val_dice_coef: 0.3703\n    Epoch 6/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.5221 - iou_coef: 0.3234 - dice_coef: 0.4779 - val_loss: 0.6297 - val_iou_coef: 0.2392 - val_dice_coef: 0.3703\n    Epoch 7/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.5114 - iou_coef: 0.3330 - dice_coef: 0.4886 - val_loss: 0.6297 - val_iou_coef: 0.2392 - val_dice_coef: 0.3703\n    Epoch 8/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.5028 - iou_coef: 0.3411 - dice_coef: 0.4972 - val_loss: 0.6297 - val_iou_coef: 0.2392 - val_dice_coef: 0.3703\n    Epoch 9/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.4949 - iou_coef: 0.3484 - dice_coef: 0.5051 - val_loss: 0.6297 - val_iou_coef: 0.2392 - val_dice_coef: 0.3703\n    Epoch 10/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.4872 - iou_coef: 0.3553 - dice_coef: 0.5128 - val_loss: 0.6297 - val_iou_coef: 0.2392 - val_dice_coef: 0.3703\n    Epoch 11/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.4757 - iou_coef: 0.3655 - dice_coef: 0.5243 - val_loss: 0.6297 - val_iou_coef: 0.2392 - val_dice_coef: 0.3703\n    Epoch 12/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.4692 - iou_coef: 0.3710 - dice_coef: 0.5308 - val_loss: 0.6297 - val_iou_coef: 0.2392 - val_dice_coef: 0.3703\n    Epoch 13/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.4585 - iou_coef: 0.3804 - dice_coef: 0.5415 - val_loss: 0.6297 - val_iou_coef: 0.2392 - val_dice_coef: 0.3703\n    Epoch 14/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.4495 - iou_coef: 0.3891 - dice_coef: 0.5505 - val_loss: 0.6297 - val_iou_coef: 0.2392 - val_dice_coef: 0.3703\n    Epoch 15/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.4446 - iou_coef: 0.3939 - dice_coef: 0.5554 - val_loss: 0.6297 - val_iou_coef: 0.2392 - val_dice_coef: 0.3703\n    Epoch 16/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.4271 - iou_coef: 0.4105 - dice_coef: 0.5729 - val_loss: 0.6296 - val_iou_coef: 0.2393 - val_dice_coef: 0.3704\n    Epoch 17/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.4104 - iou_coef: 0.4257 - dice_coef: 0.5896 - val_loss: 0.6291 - val_iou_coef: 0.2396 - val_dice_coef: 0.3709\n    Epoch 18/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.3967 - iou_coef: 0.4391 - dice_coef: 0.6033 - val_loss: 0.6293 - val_iou_coef: 0.2395 - val_dice_coef: 0.3707\n    Epoch 19/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.3915 - iou_coef: 0.4445 - dice_coef: 0.6085 - val_loss: 0.6276 - val_iou_coef: 0.2407 - val_dice_coef: 0.3724\n    Epoch 20/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.3879 - iou_coef: 0.4481 - dice_coef: 0.6121 - val_loss: 0.6268 - val_iou_coef: 0.2413 - val_dice_coef: 0.3732\n    Epoch 21/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.3847 - iou_coef: 0.4510 - dice_coef: 0.6153 - val_loss: 0.6225 - val_iou_coef: 0.2444 - val_dice_coef: 0.3775\n    Epoch 22/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.3768 - iou_coef: 0.4590 - dice_coef: 0.6232 - val_loss: 0.6255 - val_iou_coef: 0.2422 - val_dice_coef: 0.3745\n    Epoch 23/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.3715 - iou_coef: 0.4650 - dice_coef: 0.6285 - val_loss: 0.6181 - val_iou_coef: 0.2479 - val_dice_coef: 0.3819\n    Epoch 24/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.3878 - iou_coef: 0.4467 - dice_coef: 0.6122 - val_loss: 0.6233 - val_iou_coef: 0.2437 - val_dice_coef: 0.3767\n    Epoch 25/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.3676 - iou_coef: 0.4686 - dice_coef: 0.6324 - val_loss: 0.6095 - val_iou_coef: 0.2549 - val_dice_coef: 0.3905\n    Epoch 26/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.3692 - iou_coef: 0.4671 - dice_coef: 0.6308 - val_loss: 0.6262 - val_iou_coef: 0.2418 - val_dice_coef: 0.3738\n    Epoch 27/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.3646 - iou_coef: 0.4717 - dice_coef: 0.6354 - val_loss: 0.6097 - val_iou_coef: 0.2542 - val_dice_coef: 0.3903\n    Epoch 28/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.3626 - iou_coef: 0.4733 - dice_coef: 0.6374 - val_loss: 0.6168 - val_iou_coef: 0.2485 - val_dice_coef: 0.3832\n    Epoch 29/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.3754 - iou_coef: 0.4605 - dice_coef: 0.6246 - val_loss: 0.6160 - val_iou_coef: 0.2492 - val_dice_coef: 0.3840\n    Epoch 30/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.3814 - iou_coef: 0.4538 - dice_coef: 0.6186 - val_loss: 0.5950 - val_iou_coef: 0.2640 - val_dice_coef: 0.4050\n    Epoch 31/120\n    2/2 [==============================] - 2s 2s/step - loss: 0.3556 - iou_coef: 0.4811 - dice_coef: 0.6444 - val_loss: 0.5772 - val_iou_coef: 0.2787 - val_dice_coef: 0.4228\n    Epoch 32/120\n    2/2 [==============================] - ETA: 0s - loss: 0.3558 - iou_coef: 0.4814 - dice_coef: 0.6442\n", "meta": {"hexsha": "a2efae9f4a8bf51952e56e804cc30c052d5ac66d", "size": 60609, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/training of segmentation models.ipynb", "max_stars_repo_name": "arthijayaraman-lab/self-supervised_learning_microscopy_images", "max_stars_repo_head_hexsha": "f7adc86798379ae3934a864e6c41982a15aae870", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/training of segmentation models.ipynb", "max_issues_repo_name": "arthijayaraman-lab/self-supervised_learning_microscopy_images", "max_issues_repo_head_hexsha": "f7adc86798379ae3934a864e6c41982a15aae870", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/training of segmentation models.ipynb", "max_forks_repo_name": "arthijayaraman-lab/self-supervised_learning_microscopy_images", "max_forks_repo_head_hexsha": "f7adc86798379ae3934a864e6c41982a15aae870", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60609.0, "max_line_length": 60609, "alphanum_fraction": 0.5998284083, "converted": true, "num_tokens": 20043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33458944125318596, "lm_q2_score": 0.05921024991122573, "lm_q1q2_score": 0.01981112443425852}}
{"text": "```\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```\ncurrent_path = '/content/drive/My Drive/Colab Notebooks/Project_GANder/gankook_cuda/semantic-segmentation-pytorch/pytorch_room_layout/'\n\nimport os\nos.chdir(current_path)\n!ls\n```\n\n    build\t\t      features\t\t     segment_lsun.py\n    cv2_requirements.txt  info.json\t\t     segment_rl.py\n    datasets\t      lsun.pth.tar\t     segment_st.py\n    data_transforms.py    lu_vp_detect.egg-info  sunrgbd.pth.tar\n    dist\t\t      pics\t\t     test_result\n    drn_d_105_024_val     __pycache__\t     Vanish_Point_Detection\n    drn_d_105_024_val_ms  README.md\t\t     visualize.m\n    drn.py\t\t      requirements.txt\t     XiaohuLuVPDetection\n\n\n### Get Vanishing point, inliers\n\n\n```\n# !python XiaohuLuVPDetection/setup.py build\n# !python XiaohuLuVPDetection/setup.py install\n!pip install -r cv2_requirements.txt\n```\n\n    Collecting opencv-python==4.0.0.21\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/37/49/874d119948a5a084a7ebe98308214098ef3471d76ab74200f9800efeef15/opencv_python-4.0.0.21-cp36-cp36m-manylinux1_x86_64.whl (25.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 25.4MB 97.0MB/s \n    \u001b[?25hCollecting opencv-contrib-python==4.0.0.21\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1f/c0/0463d91f297521b2e15e3d682d7077557fe773db72a03a0d2dba899ab8a5/opencv_contrib_python-4.0.0.21-cp36-cp36m-manylinux1_x86_64.whl (31.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 31.2MB 180kB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.11.3 in /usr/local/lib/python3.6/dist-packages (from opencv-python==4.0.0.21->-r cv2_requirements.txt (line 1)) (1.18.5)\n    \u001b[31mERROR: albumentations 0.1.12 has requirement imgaug<0.2.7,>=0.2.5, but you'll have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Installing collected packages: opencv-python, opencv-contrib-python\n      Found existing installation: opencv-python 4.1.2.30\n        Uninstalling opencv-python-4.1.2.30:\n          Successfully uninstalled opencv-python-4.1.2.30\n      Found existing installation: opencv-contrib-python 4.1.2.30\n        Uninstalling opencv-contrib-python-4.1.2.30:\n          Successfully uninstalled opencv-contrib-python-4.1.2.30\n    Successfully installed opencv-contrib-python-4.0.0.21 opencv-python-4.0.0.21\n\n\n\n```\nimport cv2\ncv2.__version__\n```\n\n\n\n\n    '4.0.0'\n\n\n\n### pytorch.room.layout\n\n\n```\n# !pip install -r requirements.txt\n# !apt install octave\n```\n\n\n```\n# import torch\n# torch.__version__\n```\n\n\n```\n# !python segment_rl.py train -d datasets/lsun/ -c 4 -s 480 --arch drn_d_105 --batch-size 32 --random-scale 1.75 --random-rotate 15 --epochs 100 --lr 0.01 --momentum 0.9 --lr-mode poly --pretrained sunrgbd.pth.tar\n```\n\n\n```\n# !python segment_st.py test -d datasets/sunrgbd/ -c 37 --arch drn_d_105 -s 480 --resume sunrgbd.pth.tar --phase val --batch-size 1 --ms\n```\n\n\n```\n# !python segment_lsun.py test -d ../mask_data/wall/ -o ../mask_layout_data/wall/ -c 4 --arch drn_d_105 -s 320 --resume lsun.pth.tar --phase test --batch-size 1 --ms\n```\n\n### Functions\n\n\n```\n#             Detect Intersection             #\nimport math\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler\nfrom sklearn.cluster import KMeans\nfrom sympy import Line\nfrom sympy.geometry import Ray\n\n\ndef line(p1, p2):\n    A = (p1[1] - p2[1])\n    B = (p2[0] - p1[0])\n    C = (p1[0]*p2[1] - p2[0]*p1[1])\n    return A, B, -C\n\ndef intersection2(L1, L2):\n    D  = L1[0] * L2[1] - L1[1] * L2[0]\n    Dx = L1[2] * L2[1] - L1[1] * L2[2]\n    Dy = L1[0] * L2[2] - L1[2] * L2[0]\n    if D != 0:\n        x = Dx / D\n        y = Dy / D\n        return x,y\n    else:\n        return False\n\n\ndef regression(img, x, y, color=(255, 0, 0), axis=1):\n\n  if axis == 1:\n    y_at_border = np.array([0, img.shape[0]])\n    p = np.polyfit(y, x, deg=1)\n    x_at_border = np.poly1d(p)(y_at_border)\n  else:\n    x_at_border = np.array([0, img.shape[1]])\n    p = np.polyfit(x, y, deg=1)\n    y_at_border = np.poly1d(p)(x_at_border)\n\n  cv2.line(img, (int(x_at_border[0]), int(y_at_border[0])), (int(x_at_border[1]), int(y_at_border[1])), color, 2)\n\n  return x_at_border, y_at_border\n\n\ndef find_reg_points(img, lines, color=(255,0,0), drawlines=False):\n\n  centroids = list()\n  r_xs = list()\n  r_ys = list()\n  for line_ in lines:\n      for rho,theta in line_:\n          a = np.cos(theta)\n          b = np.sin(theta)\n          x0 = a*rho\n          y0 = b*rho\n          x1 = int(x0 + 1000*(-b))\n          y1 = int(y0 + 1000*(a))\n          x2 = int(x0 - 1000*(-b))\n          y2 = int(y0 - 1000*(a))\n\n          slope = (y1 - y0) / float(x1 - x0)\n          angle = math.degrees(math.atan(slope))\n          if abs(angle) > 80:\n            # print(img.shape[1])\n            h_layout = line((0, 0), (img.shape[1], 0))\n            h_layout_lower = line((0, img.shape[0]), (img.shape[1], img.shape[0]))\n            r = intersection2(h_layout, line((x1, y1), (x2, y2)))\n            r_lower = intersection2(h_layout_lower, line((x1, y1), (x2, y2)))\n            # cv2.line(img, (int(x1), int(y1)), (int(x2), int(y2)), color, 2)\n\n            center_p = (int((r[0] + r_lower[0]) / 2), int((r[1] + r_lower[1])/ 2))\n            centroids.append(center_p)\n\n            r_xs.append((r[0], r_lower[0]))\n            r_ys.append((r[1], r_lower[1]))\n\n            if drawlines:\n              cv2.line(img, (int(r[0]), int(r[1])), (int(r_lower[0]), int(r_lower[1])), color, 2)\n              cv2.circle(img, center_p, 10, (255, 0, 255), -1)\n\n  if drawlines:\n    cv2.line(img, (int(0), int(0)), (int(0), int(img.shape[0])), color, 2)\n    cv2.line(img, (int(img.shape[1]), int(0)), (int(img.shape[1]), int(img.shape[0])), color, 2)\n    cv2.circle(img, (0, int(img.shape[0] / 2)), 10, (255, 0, 255), -1)\n    cv2.circle(img, (img.shape[1], int(img.shape[0] / 2)), 10, (255, 0, 255), -1)\n  centroids.append((0, int(img.shape[0] / 2)))\n  centroids.append((img.shape[1], int(img.shape[0] / 2)))\n\n  return r_xs, r_ys, centroids   \n\nfrom scipy.spatial import distance as sci_dist\n\ndef order_points(pts):\n\n  xSorted = pts[np.argsort(pts[:, 0]), :]\n  leftMost = xSorted[:2, :]\n  rightMost = xSorted[2:, :]\n  leftMost = leftMost[np.argsort(leftMost[:, 1]), :]\n  (tl, bl) = leftMost\n  D = sci_dist.cdist(tl[np.newaxis], rightMost, \"euclidean\")[0]\n  (br, tr) = rightMost[np.argsort(D)[::-1], :]\n\n  return np.array([tl, tr, br, bl], dtype=\"float32\")\n\n\ndef drawLines(img, lines, color=(255,255,255), only_horizontal=False):\n    \"\"\"\n    Draw lines on an image\n    \"\"\"\n    for line in lines:\n        for rho,theta in line:\n          a = np.cos(theta)\n          b = np.sin(theta)\n          x0 = a*rho\n          y0 = b*rho\n          x1 = int(x0 + 1000*(-b))\n          y1 = int(y0 + 1000*(a))\n          x2 = int(x0 - 1000*(-b))\n          y2 = int(y0 - 1000*(a))\n\n          slope = (y1 - y0) / float(x1 - x0)\n          angle = math.degrees(math.atan(slope))\n          if only_horizontal:\n            if abs(angle) < 70:\n              cv2.line(img, (x1,y1), (x2,y2), color, 1)\n          else:\n            cv2.line(img, (x1,y1), (x2,y2), color, 1)\n\n\n```\n\n\n```\nfrom PIL import Image\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom XiaohuLuVPDetection.lu_vp_detect.vp_detection import VPDetection\nimport time\n# import os\nimport cv2\n# import pylab as pl\nfrom skimage import morphology as mp\nimport sys\nfrom Vanish_Point_Detection import wrapper\n# from varname import Wrapper\n\n\nlength_thresh = 50\nprincipal_point = None\nfocal_length = 1300 # 1102.79\nseed = 1300\nvpd = VPDetection(length_thresh, principal_point, focal_length, seed)\n\norg_path = 'datasets/lsun/images/' # -> original image\nlayout_path = 'drn_d_105_024_val_ms/images/' # -> layout image (result image frome above model file)\nrefer_path = '../refer_data/wall/myxkehu1kfzggursepnk0tfiyps8zbs5umvzv8d92r6hhxejgawebwsufssgov5q-.jpg'\n\nobject_ = 'wall'\nmask_path = '../mask_data/' + object_ + '/'\n# layout_path = '../test_layout_result/' + object_ + '/'\nlayout_path = '../mask_layout_data/' + object_ + '/'\n# refer_path = './refer_data/' + object_ + '/'\n\nval_image_list = os.listdir(layout_path)\n\none_iter = False\nstart_index = 0\nfor image_index, image in enumerate(val_image_list):\n\n  if image_index < start_index:\n    continue\n\n  # image = '720x480_20190219162540169_bnvKQG536n.png'\n  # print('image_index :', val_image_list.index(image))\n  # one_iter = True\n\n  # print(image)\n  img = Image.open(layout_path + image)\n  # print(type(img))\n  img_np = np.invert(np.asarray(img))\n  # print(img_np.max(), img_np.min())\n  ret, thr = cv2.threshold(img_np, 254, 255, cv2.THRESH_BINARY_INV)\n\n  org = Image.open(mask_path + image)\n  org_color_np, org_np = np.split(np.asarray(org), 2, axis=1)\n  # org_np = np.asarray(org)\n  # gray = cv2.cvtColor(org_np, cv2.COLOR_RGB2GRAY)\n  # print(org_np.shape)\n  # ret, thr = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)\n\n\n  print(image)\n  # plt.subplot(131)\n  # plt.imshow(org)\n  # plt.show()\n  img_size = (org_np.shape[1], org_np.shape[0])\n  \n  scale_factor = 6\n  print('scale_factor :', scale_factor)\n\n  refer = Image.open(refer_path)\n  refer = np.asarray(refer)\n\n  #     refer_size\uc640 img_size\uac00 \ub3d9\uc77c\ud558\uac70\ub098 refer_size\uac00 \uc791\uc740 \uacbd\uc6b0\ub97c \uace0\ub824\ud574\uc57c\ud55c\ub2e4.     #\n  refer = np.tile(refer, (scale_factor, scale_factor, 1))\n  size_ratio = math.floor(min((refer.shape[0] / (org_np.shape[0] * 1.5)), (refer.shape[1] / (org_np.shape[1] * 1.5))))\n  refer = Image.fromarray(refer).resize((int(refer.shape[1] / size_ratio), int(refer.shape[0] / size_ratio)))\n\n  # tun = thr\n  # skl = mp.medial_axis(tun).astype(np.uint8) * 255\n  rho = 1\n  theta = np.pi/180\n  thresh = 50\n  # print(skl.shape, skl.dtype)\n\n  # lines = cv2.HoughLines(org_np.astype(np.uint8), rho, theta, thresh)\n  # lines = cv2.HoughLines(skl, rho, theta, thresh)\n\n  # print(lines)\n  # plt.imshow(skl)\n  # plt.show()\n\n  # Draw all Hough lines in red\n  # img_with_all_lines = np.copy(skl)\n  # img_with_all_lines = cv2.cvtColor(img_with_all_lines, cv2.COLOR_GRAY2RGB)\n  # plt.imshow(img_with_all_lines)\n  # plt.show()\n  org_color_np2 = org_color_np.copy()\n  org_np = org_np.astype(np.uint8)\n  org_np2 = org_np.copy()\n  org_np3 = org_np.copy()\n\n  start = time.time()\n\n  # r_x_list, r_y_list, centroids_list = find_reg_points(org_np, lines,)\n  # drawLines(img_with_all_lines, lines)\n\n  #     Edit Your Mask     #\n  kernel = np.ones((10, 10), np.uint8)\n  \n  # plt.figure(figsize=(20, 15))\n  # for plot_i in range(5):\n  #   plt.subplot(1, 5, plot_i+1)\n  #   if plot_i == 0:\n  #     plt.imshow(org_np2)\n  #   elif plot_i == 1: #      Dilation     #\n  #     plt.imshow(cv2.dilate(org_np2, kernel, iterations=1))\n  #   elif plot_i == 2: #      Closing      #\n  #     plt.imshow(cv2.morphologyEx(org_np2, cv2.MORPH_CLOSE, kernel))\n  #   elif plot_i == 3: #     Erode     #\n  #     plt.imshow(cv2.erode(org_np2, kernel, iterations=1))\n  #   elif plot_i == 4: #     Opening   #\n  #     plt.imshow(cv2.morphologyEx(org_np2, cv2.MORPH_OPEN, kernel))\n  # plt.show()\n\n  # mask_prob = \n\n  org_np2_morp = cv2.morphologyEx(org_np2, cv2.MORPH_CLOSE, kernel)\n  org_np2_copy = org_np2_morp.copy()\n  org_np2_copy_gray = cv2.cvtColor(org_np2_copy, cv2.COLOR_RGB2GRAY)\n\n  vpd.find_vps(org_np2_morp)\n  vps = vpd.vps_2D\n  vl_org_img, vl_list = vpd.create_debug_VP_image()\n\n  ret, thr_org_np2 = cv2.threshold(org_np2_copy, 127, 255, cv2.THRESH_BINARY)\n  thr_org_np2 = cv2.morphologyEx(thr_org_np2, cv2.MORPH_CLOSE, kernel)\n  thr_org_np2_copy = thr_org_np2.copy()\n  vpd.find_vps(thr_org_np2_copy)\n  # vps = vpd.vps_2D\n  vl_thresh_org_img, vl_thresh_org_list = vpd.create_debug_VP_image(show_vl=True)\n\n\n  #       multiply thresh mask to color map      #\n  org_color_np = (vl_thresh_org_img / 255. * org_color_np).astype(np.uint8)\n  vpd.find_vps(org_color_np)\n  vps = vpd.vps_2D\n  vl_color_img, vl_color_list = vpd.create_debug_VP_image()\n\n  # plt.imshow(vl_thresh_org_img)\n  # plt.show()\n\n\n  edge_org_np2 = cv2.Canny(org_np2_morp, 20, 300)\n  edge_org_np2_copy = edge_org_np2.copy()\n  edge_org_np2_copy2 = cv2.Canny((org_np2_copy / 255. * org_np2_copy).astype(np.uint8), 20, 300)\n\n  vpd.find_vps(edge_org_np2)\n  # vps = vpd.vps_2D\n  edge_vl_img, edge_vl_list = vpd.create_debug_VP_image()\n\n  vpd.find_vps(edge_org_np2_copy2)\n  # vps = vpd.vps_2D\n  edge_vl_img2, edge_vl_list2 = vpd.create_debug_VP_image()\n\n  #             Hough Lines Detection           #\n  # print('org_np2.dtype :', org_np2.dtype)\n  # print('org_np2.shape :', org_np2.shape)\n  # plt.imshow(org_np2_copy_gray)\n  # plt.show()\n  # lines = cv2.HoughLines(org_np2_copy_gray, rho, theta, thresh)\n  # drawLines(org_np2_copy_gray, lines)\n  edge_lines = cv2.HoughLines(edge_org_np2_copy, rho, theta, thresh)\n  drawLines(edge_org_np2_copy, edge_lines, only_horizontal=True)\n  edge_lines2 = cv2.HoughLines(edge_org_np2_copy2, rho, theta, thresh)\n  drawLines(edge_org_np2_copy2, edge_lines2, only_horizontal=True)\n  \n  plt.figure(figsize=(15, 10))\n  plt.subplot(151)\n  plt.imshow(vl_org_img)\n  plt.title('vl_org_img')\n\n  plt.subplot(152)\n  # plt.imshow(org_color_np)\n  plt.imshow(vl_color_img)\n\n  plt.subplot(153)\n  plt.imshow(vl_thresh_org_img)\n  plt.title('vl_thresh_org_img')\n\n  plt.subplot(154)\n  plt.imshow(edge_vl_img)\n  plt.title('edge_vl_img')\n\n  plt.subplot(155)\n  plt.imshow(edge_vl_img2)\n  plt.title('edge_vl_img2')\n  plt.show()\n\n\n  vl_list_for_vline = vl_color_list\n  vl_img_for_vline = edge_vl_img2.copy()\n\n  print('#       Used vl_list for vline work       #')\n  print('vl_color_list')\n  print()\n\n  #         Extend v_lines and draw h_lines       #\n  h_border = Line((0, 0), (org_np.shape[1], 0))\n  h_border_lower = Line((0, org_np.shape[0]), (org_np.shape[1], org_np.shape[0]))\n\n  reg_xs = list()\n  reg_ys = list()\n  v_lines = list()\n  h_lines_xrange = list()\n  for vl in vl_list_for_vline:\n      x0, y0, x1, y1 = vl\n      slope = (y1 - y0) / float(x1 - x0)\n      angle = math.degrees(math.atan(slope))\n      # print(angle)\n      if abs(angle) > 80:\n        # cv2.line(skl_copy, (int(x1), int(y1)), (int(x0), int(y0)), (255, 0, 0), 3,\n        #                  cv2.LINE_AA)\n        v_line = Line((x0, y0), (x1, y1))\n        [top_point] = v_line.intersection(h_border)\n        [bot_point] = v_line.intersection(h_border_lower)\n        # v_lines.append()\n        reg_xs.append((float(top_point[0]), float(bot_point[0])))\n        reg_ys.append((float(top_point[1]), float(bot_point[1])))\n\n      if abs(angle) < 70:\n        h_lines_xrange.append((min(x0, x1), max(x0, x1)))\n\n  #           Remove Unnecessary Vline        #\n  # print(\"#        Before vline Removing       #\")\n  # print('reg_xs :', reg_xs)\n  # reg_xs_copy = reg_xs.copy()\n  # reg_ys_copy = reg_ys.copy()\n  # for reg_x, reg_y in zip(reg_xs, reg_ys):\n  #   for x_range in h_lines_xrange:\n  #     if x_range[0] + 5 < np.mean(reg_x) < x_range[1] - 5:\n  #       # print('reg_x :', reg_x)\n  #       reg_xs_copy.remove(reg_x)\n  #       reg_ys_copy.remove(reg_y)\n  #       break\n  # reg_xs = reg_xs_copy\n  # reg_ys = reg_ys_copy\n  # print('#        After Removing      #')\n  # print('reg_xs :', reg_xs)\n\n\n\n\n  print('#        Before Sorting      #')\n  # print('reg_xs :', reg_xs)\n  \n  \n  center_xs = list()\n  for reg_x, reg_y in zip(reg_xs, reg_ys):\n    #     all_closest_inter\uac00 \uc815\ub82c\ub418\uc9c0 \uc54a\uc558\ub2e4\uba74 inters type = list()      #\n    # sum_x = 0\n    # for inter in inters:\n    #   sum_x += inter[0] + inter[2]\n    center_xs.append(np.mean(reg_x))\n    # regression(vl_img_for_vline, reg_x, reg_y)\n    \n  # plt.imshow(vl_img_for_vline)\n  # plt.title('Divided Session')\n  # plt.show()\n\n  # if one_iter:\n  #   break\n  # else:\n  #   continue\n\n  #                       K Means                       #\n  centroids_data = np.array(center_xs).reshape(-1, 1)\n  # print('len(r_x_list), len(r_y_list) :', len(r_x_list), len(r_y_list))\n  print('centroids_data.shape :', centroids_data.shape)\n  mms = MinMaxScaler()\n  cen_data =mms.fit_transform(centroids_data)\n  # print('cen_data :', cen_data)\n\n  # print('cen_data :', cen_data)\n  K = range(1, 7)\n  s_dist = list()\n  for k in K:\n    if cen_data.shape[0] < k:\n      break\n    km = KMeans(n_clusters=k)\n    km = km.fit(cen_data)\n    inertia = km.inertia_\n    s_dist.append(inertia)\n    \n    # if inertia <= 0:\n    #   print('vertical line number =', k)\n    #   break\n  mms2 = MinMaxScaler()\n  mms_s_dist = mms2.fit_transform(np.array(s_dist).reshape(-1, 1))\n  k_thresh = 0.1\n  # plt.plot(range(len(mms_s_dist)), mms_s_dist)\n  # plt.show()\n\n  if cen_data.shape[0] > 1:\n    for i in range(len(mms_s_dist)):\n      if mms_s_dist[i] < k_thresh:\n        k = i + 1\n        break\n  else:\n    k = 0\n\n  #     k Confirmation : Comparing k.cluster_centers_ dist (Regulation of closed vline's minimum distance)  #\n  while True:    \n\n    km = KMeans(n_clusters=k)\n    km = km.fit(cen_data)\n    if k <= 0:\n      break\n\n    cluster_centroids = km.cluster_centers_\n    # print('cluster_centroids :', cluster_centroids)\n    error_exist = False\n    for i in range(len(cluster_centroids) - 1):\n      for j in range(i + 1, len(cluster_centroids)):\n        if abs(cluster_centroids[i] - cluster_centroids[j]) < 0.05:\n          error_exist = True\n    if error_exist:\n      k -= 1\n    else:\n      break\n\n  print('k is', k)\n\n  # predict_cen = km.predict(cen_data)\n  # km = KMeans(n_clusters=k)\n  km = km.fit(centroids_data)\n  predict_cen = km.cluster_centers_\n  print('predict_cen :', predict_cen)\n\n  # keys = list(range(k))\n  # for rm in predict_cen[-2:]:\n  #   keys.remove(rm)\n  # print('keys :', keys)\n\n  #       sorted_predict_cen \ub85c vline \uc744 \uc815\ub9bd\ud55c\ub2e4.      #\n  # sorted_index = list()\n  sorted_predict_cen = sorted(predict_cen)\n\n  # for center_x in sorted_center_xs:\n  #   # print('center_x :', center_x)\n  #   sorted_index.append(center_xs.index(center_x))\n  # # print('sorted_index :', sorted_index)   #\n\n  # sorted_reg_xs = list()\n  # sorted_reg_ys = list()\n  # for s_index in sorted_index:\n  #   sorted_reg_xs.append(reg_xs[s_index])\n  #   sorted_reg_ys.append(reg_ys[s_index])\n  # reg_xs = sorted_reg_xs\n  # reg_ys = sorted_reg_ys\n\n  print()\n  print(\"#        After Sorting       #\")\n  # print('reg_xs :', reg_xs)\n  print('sorted_predict_cen :', sorted_predict_cen)\n  print()\n\n  for reg_x in sorted_predict_cen:\n    cv2.line(vl_img_for_vline, (int(reg_x), int(org_np.shape[0])), (int(reg_x), 0), (100, 156, 245), 2)\n\n  plt.figure(figsize=(15, 10))\n  plt.subplot(131)\n  plt.imshow(vl_img_for_vline)\n  plt.title('Divided Session')\n  # plt.show()\n\n  plt.subplot(132)\n  plt.imshow(edge_org_np2_copy)\n  # plt.show()\n  plt.subplot(133)\n  plt.imshow(edge_org_np2_copy2)\n  plt.show()\n\n  #           VL Segmentation             #\n  # Angle between line1 and x-axis\n  # print(len(vl_list))\n\n  # print('len(v_lines) :', len(v_lines))\n  # print('len(h_lines) :', len(h_lines))\n  \n\n  #     vline \uc774 \uc874\uc7ac\ud558\uc9c0 \uc54a\ub294 \uacbd\uc6b0\ub3c4 \uace0\ub824\ud574\uc57c\ud55c\ub2e4.     #\n  if len(reg_xs) == 0:\n    reg_xs.append([0, 0])\n    reg_ys.append([0, org_np2.shape[0]])\n    \n  #         Divide Session by vline       #\n  for reg_index, reg_x in enumerate(sorted_predict_cen):\n\n\n    #     In a Session     #\n    #     1.  find vanishing point    #\n    #     2.  Find 3 points (vp, top & bottom points)     #\n    #     3.  Do warfine and attach to the black plane      #\n\n    print(\"#      Session Status      #\")\n    print('reg_index, reg_x :', reg_index, reg_x)\n    \n    #     0.  crop by vline     #\n          #   Find Max_x, min_x, (Max_y, min_y = org.shape[0], 0)\n          #   1.    \uc6b0\ud3b8\uc5d0 \ud55c\ud574\uc11c max_x = \uc6b0\ud3b8 vline max_x & min_x = \ud604\uc7ac vline min_x\n          #   2.    \uc88c\ud3b8\uc5d0 \ud55c\ud574\uc11c max_x = \ud604\uc7ac Max_x & min_x = \uc88c\ud3b8 vline min_x\n\n    #      vline \ubcc4\ub85c \uc591\uc606\uc73c\ub85c \uc791\uc5c5\uc744 \ud558\uba74 len(vline) = 1\uc758 \uc791\uc5c5\uc744 \ubc18\ubcf5\ud560 \ud544\uc694\uac00 \uc5c6\uc5b4\uc9c4\ub2e4.    #\n    iter = False\n    while True:\n\n      #                   We need Max, min x & y                #\n      find_pair = True\n\n      if not iter:\n        #       vline \uc6b0\uce21 session      #\n        # print(final_xs)\n        # four_inters.append([final_xs[0], final_ys[0]])\n        # four_inters.append(centroid_inters[0])\n        # print(four_inters)\n\n        #       \uc624\ub978\ucabd \ub05d vline \uc774\uba74        #\n        if reg_index == len(sorted_predict_cen) - 1:\n          print('Rightest Vline')\n          #   1.    \uc6b0\ud3b8\uc5d0 \ud55c\ud574\uc11c max_x = \uc6b0\ud3b8 vline max_x & min_x = \ud604\uc7ac vline min_x\n          max_x = org_np.shape[1]\n          min_x = np.min(reg_x)\n\n        else:\n          print('Middle Vline')\n          next_reg_x = sorted_predict_cen[reg_index + 1]\n          max_x = np.max(next_reg_x)\n          if np.min(reg_x) < 0:\n            min_x = 0\n          else:\n            min_x = np.min(reg_x)\n\n      #     i = 0 \uc5d0 \ud55c\ud574\uc11c\ub9cc \uc67c\ucabd\uc73c\ub85c\ub3c4 refering \uc9c4\ud589, \ub098\uba38\uc9c0\ub294 \uc624\ub978\ucabd\uc73c\ub85c\ub9cc     #\n      else:\n          #   2.    \uc88c\ud3b8\uc5d0 \ud55c\ud574\uc11c max_x = \ud604\uc7ac Max_x & min_x = \uc88c\ud3b8 vline min_x\n          print('Leftest Vline')\n          max_x = np.max(reg_x)\n          min_x = 0\n\n      print('min_x, max_x :', min_x, max_x)\n      # max_y = org_np.shape[0]\n      # min_y = 0\n\n      #     Make Session      #\n      session = org_np2[:, int(min_x):int(max_x)]\n      # plt.imshow(session)\n      # plt.show()\n\n\n      if (max_x - min_x) > 50:\n        length_thresh = 50\n      else:\n        length_thresh = 20\n        if max_x - min_x < 20:\n            #     i != 0 \uc778 \uacbd\uc6b0 break     #\n          if reg_index == 0 and np.sum(sorted_predict_cen) != 0 and not iter:\n            iter = True\n            print('iter :', iter)\n            continue\n          else:\n            break\n      \n      principal_point = None\n      focal_length = 1300 # 1102.79\n      seed = None\n      vpd = VPDetection(length_thresh, principal_point, focal_length, seed)\n\n      try:\n        vpd.find_vps(session)\n        # vps = vpd.vps_2D\n        vl_img, vl_list = vpd.create_debug_VP_image(show_vl=True)\n\n\n        #       Closing Morphing by OpenCV      #\n        kernel = np.ones((10, 10), np.uint8)\n        session = cv2.morphologyEx(session, cv2.MORPH_CLOSE, kernel)\n\n        vpd.find_vps(session)\n        # vps = vpd.vps_2D\n        vl_session_img, vl_session_list = vpd.create_debug_VP_image(show_vl=True)\n\n        #     Feed Binary inv Threshold     #      \n        gray = cv2.cvtColor(session, cv2.COLOR_RGB2GRAY)\n        ret, thr_session = cv2.threshold(session, 127, 255, cv2.THRESH_BINARY)\n        thr_session = cv2.morphologyEx(thr_session, cv2.MORPH_CLOSE, kernel)\n        thr_session_copy = thr_session.copy()\n        vpd.find_vps(thr_session_copy)\n        # vps = vpd.vps_2D\n        vl_thresh_img, vl_thresh_list = vpd.create_debug_VP_image(show_vl=True)\n\n        # plt.imshow(vl_thresh_img)\n        # plt.title('vl_thresh_img')\n        # plt.show()\n\n        #       Edge Session      #\n        edge_session = cv2.Canny(session, 20, 60)\n\n        #     Before Canny    #\n        session_prob = session / 255.\n\n        #     Multiply mask map with Edge => Erase Unnecessary vl line    #\n        #   multiply one time   #\n        session2 = session_prob * (session)\n        edge_session2 = cv2.Canny(session2.astype(np.uint8), 20, 60)\n        #       two time      #\n        # session2 = session_prob**2 * (session)\n        # edge_session2 = cv2.Canny(session2.astype(np.uint8), 20, 60)\n\n\n        vpd.find_vps(edge_session)\n        # vps = vpd.vps_2D      \n        vl_edge_img, vl_edge_list = vpd.create_debug_VP_image(show_vl=True)\n\n        vpd.find_vps(edge_session2)\n        # vps = vpd.vps_2D      \n        vl_edge_img2, vl_edge_list2 = vpd.create_debug_VP_image(show_vl=True)\n      \n      except Exception as e:\n        print(\"Error in vpd Sessions Zone :\", e)\n        print()\n          #     i != 0 \uc778 \uacbd\uc6b0 break     #\n        if reg_index == 0 and np.sum(sorted_predict_cen) != 0 and not iter:\n          iter = True\n          print('iter :', iter)\n          continue\n\n        else:\n          break\n    \n      # session = wrapper.dealAImage(session,True,True,True)\n\n      # #             color             #\n      # session = org_color_np[:, int(min_x):int(max_x)]\n\n      #       Use made vl_img (get more vn_lines)     #\n      # session = vl_org_img[:, int(min_x):int(max_x)]\n\n      \n\n      plt.figure(figsize=(15, 10))\n      plt.subplot(151)\n      plt.imshow(vl_img)\n      plt.title('vl_session_img')\n\n      plt.subplot(152)\n      plt.imshow(vl_thresh_img)\n      plt.title('vl_thresh_img')\n\n      # plt.subplot(152)\n      # plt.imshow(vl_session_img)\n      # plt.title('vl_session_img morphed')\n\n      plt.subplot(153)\n      plt.imshow(edge_session2)\n      plt.title('edge_session2')\n\n      plt.subplot(154)\n      plt.imshow(vl_edge_img)\n      plt.title('vl_edge_img')\n\n      plt.subplot(155)\n      plt.imshow(vl_edge_img2)\n      plt.title('vl_edge_img2')     \n      # plt.imshow(vl_img)\n      # plt.title('vl_img')\n      plt.show()\n\n      h_lines = list()\n      # print('vps :', vps)\n\n      top_vl = list()\n      bottom_vl = list()\n\n      left_vl_list = list()\n      right_vl_list = list()\n\n      left_angle = list()\n      right_angle = list()\n\n      #         What is best vl_list      #\n      vl_list = vl_edge_list2\n      print('#            Used vl_list for hline work          #')\n      print('vl_edge_list2')\n      print()\n\n      for vl in vl_list:\n        x0, y0, x1, y1 = vl\n        slope = (y1 - y0) / float(x1 - x0)\n        angle = math.degrees(math.atan(slope))\n        # print(angle)\n        # if abs(angle) > 80:\n        #   # cv2.line(skl_copy, (int(x1), int(y1)), (int(x0), int(y0)), (255, 0, 0), 3,\n        #   #                  cv2.LINE_AA)\n        #   v_lines.append(vl)\n\n        if abs(angle) < 70:\n          if (y0 + y1) / 2 < vl_img.shape[0] / 2:\n            # print(y0, y1)\n            top_vl.append(vl)\n            if angle < 0:\n              left_vl_list.append(vl)\n              left_angle.append(abs(angle))\n            else:\n              right_vl_list.append(vl)\n              right_angle.append(abs(angle))\n          else:\n            bottom_vl.append(vl)\n            if angle > 0:\n              left_vl_list.append(vl)\n              left_angle.append(abs(angle))\n            else:\n              right_vl_list.append(vl)\n              right_angle.append(abs(angle))\n          # cv2.line(skl_copy, (int(x1), int(y1)), (int(x0), int(y0)), (0, 0, 255), 2,\n          #                  cv2.LINE_AA)\n          h_lines.append(vl)\n        #   regression(vl_img, (x0, x1), (y0, y1), color=(0,255,255),axis=1)\n      print('#        Original vl list        #')\n      print('len(left_vl_list) :', len(left_vl_list))\n      print('len(right_vl_list) :', len(right_vl_list))\n      print()\n\n      print(\"#            Angle Condition           #\")\n      limit_angle = 15\n      print('limit_angle :', limit_angle)\n\n      copy_left_vl_list = left_vl_list.copy()\n      copy_right_vl_list = right_vl_list.copy()\n\n      #             Delete over standarded angle vl             #\n      if len(left_vl_list) != 0:\n        copy_left_angle = left_angle.copy()\n        mean_left_angle = np.array(left_angle).mean()\n        # print('mean_left_angle :', mean_left_angle)\n        # print('left_angle :', left_angle)\n        print('max left_angle gap : ', max(left_angle) - mean_left_angle)\n\n        for angle_index, angle in enumerate(copy_left_angle):\n          if abs(angle - mean_left_angle) > limit_angle:\n            left_vl_list.remove(copy_left_vl_list[angle_index])\n            left_angle.remove(copy_left_angle[angle_index])\n        # standardScaler = StandardScaler()\n        # std_left_angle = standardScaler.fit_transform(np.array(left_angle).reshape(-1, 1))\n        # print('standardScaler.fit_transform(left_angle) :', std_left_angle)\n        # print('left_angle :', left_angle)        \n\n        # for std_index, std_angle in enumerate(std_left_angle):\n        #   if abs(std_angle) > 2:\n        #     left_vl_list.remove(copy_left_vl_list[std_index])\n            # left_angle.remove(copy_left_angle[std_index])\n\n        # print('left_angle :', left_angle)\n\n      if len(right_vl_list) != 0:\n        copy_right_angle = right_angle.copy()\n        mean_right_angle = np.array(right_angle).mean()\n        # print('mean_right_angle :', mean_right_angle)\n        # print('right_angle :', right_angle)\n        print('max right_angle gap : ', max(right_angle) - mean_right_angle)\n\n        for angle_index, angle in enumerate(copy_right_angle):\n          if abs(angle - mean_right_angle) > limit_angle:\n            right_vl_list.remove(copy_right_vl_list[angle_index])\n            right_angle.remove(copy_right_angle[angle_index])\n      \n      print()\n\n      \n      # top_condition = False\n      # bot_condition = False\n      # for vl in left_vl_list:\n      #   if vl in top_vl:\n      #     top_condition = True\n      #   elif vl in bottom_vl:\n      #     bot_condition = True\n      # if top_condition and bot_condition:\n      #   pass\n      # else:\n      #   left_vl_list = list()\n      #   print('left top bot condition False')\n      #   print('top_condition :', top_condition)\n      #   print('bot_condition :', bot_condition)\n\n      # top_condition = False\n      # bot_condition = False\n      # for vl in right_vl_list:\n      #   # print('vl :', vl)\n      #   if vl in top_vl:\n      #     top_condition = True\n      #   elif vl in bottom_vl:\n      #     bot_condition = True\n      # if top_condition and bot_condition:\n      #   pass\n      # else:\n      #   right_vl_list = list()\n      #   print('right top bot condition False')\n      #   print('top_condition :', top_condition)\n      #   print('bot_condition :', bot_condition)\n      \n      # print('-- after --')\n      # print('len(left_vl_list) :', len(left_vl_list))\n      # print('len(right_vl_list) :', len(right_vl_list))\n      # print()\n\n      # for vl in vl_list:\n      #   x0, y0, x1, y1 = vl\n\n      #   # if right_gap < 30:\n      #   #   left_vl_list.append(vl)\n      #   #   print('right_angle :', angle)\n      #   if vl in left_vl_list:\n      #     regression(vl_img, (x0, x1), (y0, y1), color=(0,0,255),axis=1)\n      #   # elif left_gap < 30:\n      #   elif vl in right_vl_list:\n      #     # right_vl_list.append(vl)\n      #     # print('left_angle :', angle)\n      #     regression(vl_img, (x0, x1), (y0, y1), color=(255,0,0),axis=1)\n      if len(left_vl_list) == 0 and len(right_vl_list) == 0:\n          #     i != 0 \uc778 \uacbd\uc6b0 break     #\n        if reg_index == 0 and not iter:\n          iter = True\n          print('iter :', iter)\n          continue\n\n        else:\n          break\n        \n      \n      #                       Find External vn_line                     #\n      h_border_top = Line((0, 0), (vl_img.shape[1], 0))\n      h_border_bot = Line((0, vl_img.shape[0]), (vl_img.shape[1], vl_img.shape[0]))\n      top_down_ratio = 0.66\n      left_margin = 0.33\n      right_margin = 1 - left_margin\n\n      ex_left_top_vl = list()\n      ex_left_bot_vl = list()\n      ex_right_top_vl = list()\n      ex_right_bot_vl = list()\n\n      l2 = Line((0, 0), (0, vl_img.shape[0]))\n      l3 = Line((vl_img.shape[1], 0), (vl_img.shape[1], vl_img.shape[0]))\n\n      for vl in left_vl_list:\n        x0, y0, x1, y1 = vl\n        l1 = Line((x0, y0), (x1, y1))\n        #     v_border line     #\n        [left_point] = l1.intersection(l2)\n        # print('left_point :', left_point)\n        [right_point] = l1.intersection(l3)\n\n        top_bot_pass = False\n        try:\n          [top_point] = l1.intersection(h_border_top)\n          [bot_point] = l1.intersection(h_border_bot)\n        except:\n          top_bot_pass = True\n        # print('top_point :', int(top_point[0]), int(top_point[1]))\n        # print('bot_point :', int(bot_point[0]), int(bot_point[1]))\n\n        #      Figure out current vl is top / bottom vl     #\n        extend = False\n        if vl in top_vl:\n          #      line should have same height (y)     #\n          if (left_point[1] < vl_img.shape[0] * top_down_ratio and right_point[1] < vl_img.shape[0] * top_down_ratio):\n            #     h_border \uc640\uc758 \uad50\ucc28\uc810 \uc870\uac74    #\n            # if not top_bot_pass:\n            # if top_point[0] >= vl_img.shape[1] * right_margin and bot_point[0] <= vl_img.shape[1] * left_margin:\n              # extend = True\n              ex_left_top_vl.append((left_point[0], left_point[1], right_point[0], right_point[1]))\n\n        elif vl in bottom_vl:\n          # print('vl in bottom at left :', vl)\n          #      line should have same height (y)     #\n          if (left_point[1] > vl_img.shape[0] * (1 - top_down_ratio) and right_point[1] > vl_img.shape[0] * (1 - top_down_ratio)):\n            #     h_border \uc640\uc758 \uad50\ucc28\uc810 \uc870\uac74    #\n            # if not top_bot_pass:\n            # if top_point[0] <= vl_img.shape[1] * left_margin and bot_point[0] >= vl_img.shape[1] * right_margin:\n              # extend = True\n              ex_left_bot_vl.append((left_point[0], left_point[1], right_point[0], right_point[1]))\n          \n\n      for vl in right_vl_list:\n        x0, y0, x1, y1 = vl\n        l1 = Line((x0, y0), (x1, y1))\n        #     v_border line     #\n     \n        [left_point] = l1.intersection(l2)\n        # print('left_point :', left_point)\n        [right_point] = l1.intersection(l3)\n        \n        top_bot_pass = False\n        try:\n          [top_point] = l1.intersection(h_border_top)\n          [bot_point] = l1.intersection(h_border_bot)\n        except:\n          top_bot_pass = True\n        # print('top_point :', int(top_point[0]), int(top_point[1]))\n        # print('bot_point :', int(bot_point[0]), int(bot_point[1]))\n\n        #      Figure out current vl is top / bottom vl     #\n        extend = False\n        if vl in top_vl:\n          #      line should have same height (y)     #\n          if (left_point[1] < vl_img.shape[0] * top_down_ratio and right_point[1] < vl_img.shape[0] * top_down_ratio):\n            #     h_border \uc640\uc758 \uad50\ucc28\uc810 \uc870\uac74    #\n            # if top_point[0] <= vl_img.shape[1] * left_margin and bot_point[0] >= vl_img.shape[1] * right_margin:\n              # extend = True\n              ex_right_top_vl.append((left_point[0], left_point[1], right_point[0], right_point[1]))\n\n\n        elif vl in bottom_vl:\n          # print('vl in bottom at right :', vl)\n          #      line should have same height (y)     #\n          if left_point[1] > vl_img.shape[0] * (1 - top_down_ratio) and right_point[1] > vl_img.shape[0] * (1 - top_down_ratio):\n            #     h_border \uc640\uc758 \uad50\ucc28\uc810 \uc870\uac74    #\n            # if top_point[0] >= vl_img.shape[1] * right_margin and bot_point[0] <= vl_img.shape[1] * left_margin:\n              # extend = True          \n              ex_right_bot_vl.append((left_point[0], left_point[1], right_point[0], right_point[1]))\n\n        # if extend:\n        #   ex_right_vl.append((left_point[0], left_point[1], right_point[0], right_point[1]))\n        # print('ex_left_vl[-1] :', ex_left_vl[-1])\n\n      print()\n      print('#          Extended vl list left / right  TB Condition        #')\n      print('len(ex_left_top_vl) :', len(ex_left_top_vl))\n      print('len(ex_left_bot_vl) :', len(ex_left_bot_vl))\n      print('len(ex_right_top_vl) :', len(ex_right_top_vl))\n      print('len(ex_right_bot_vl) :', len(ex_right_bot_vl))\n      print()\n\n      #       find min max Line     #\n      max_y = 0\n      right_bottest_vl = None\n      min_y = vl_img.shape[0]\n      right_toppest_vl = None\n\n      for vl in ex_right_bot_vl:\n        if vl[1] > max_y:\n          right_bottest_vl = vl\n          max_y = vl[1]\n      \n      for vl in ex_right_top_vl:\n        if vl[1] < min_y:\n          right_toppest_vl = vl\n          min_y = vl[1]\n      \n      max_y = 0\n      left_bottest_vl = None\n      min_y = vl_img.shape[0]\n      left_toppest_vl = None\n\n      for vl in ex_left_bot_vl:\n        if vl[3] > max_y:\n          left_bottest_vl = vl\n          max_y = vl[3]\n      \n      for vl in ex_left_top_vl:\n        if vl[3] < min_y:\n          left_toppest_vl = vl\n          min_y = vl[3]\n\n\n      #       Figure out min_y & max_y of thr_session       #\n      # print('thr_session.shape :', thr_session.shape)\n      \n      #     \ubc14\ub2e5\uc740 \uc624\ud788\ub824 \ud558\uba74 \uc548\ub41c\ub2e4.    #\n      thr_session_gray = cv2.cvtColor(thr_session, cv2.COLOR_RGB2GRAY)\n      print('thr_session_gray.shape :', thr_session_gray.shape)\n\n      top_white_cnt = 0\n      bot_white_cnt = 0\n      white_min_x = thr_session_gray.shape[1]\n      white_max_x = 0\n      white_min_y = thr_session.shape[0]\n      white_max_y = 0\n      temp_min_y = white_min_y\n      temp_max_y = white_max_y\n      top_parallel = False\n      bot_parallel = False\n      for i in range(thr_session_gray.shape[1]):\n\n        #     Check Top Condition     #\n        for j in range(int(thr_session_gray.shape[0] / 10)):\n          # if thr_session_gray[j][i] == 255 and j < thr_min_y:\n            # thr_min_y = j\n            # thr_min_y_coord = (i, j)\n          if thr_session_gray[j][i] == 255:\n            top_white_cnt += 1\n            if i > white_max_x:\n              white_max_x = i\n              max_x_coord = (i, j)\n            if i < white_min_x:\n              white_min_x = i\n              min_x_coord = (i, j)\n            if j < temp_min_y:\n              temp_min_y = j\n              temp_min_y_coord = (i, j)\n\n        for j in range(int(thr_session_gray.shape[0] / 10), int(thr_session_gray.shape[0] * 9/10)):\n          if thr_session_gray[j][i] == 255:\n            if j > white_max_y:\n              white_max_y = j\n              max_y_coord = (i, j)\n            if j < white_min_y:\n              white_min_y = j\n              min_y_coord = (i, j)\n\n        #     Check Bot Condition   #\n        for j in range(int(thr_session_gray.shape[0] * 9/10), thr_session_gray.shape[0]):\n          # if thr_session_gray[j][i] == 255 and j < thr_min_y:\n            # thr_min_y = j\n            # thr_min_y_coord = (i, j)\n          if thr_session_gray[j][i] == 255:\n            bot_white_cnt += 1\n            if j > temp_max_y:\n              temp_max_y = j\n              temp_max_y_coord = (i, j)\n            # if i > white_max_x:\n            #   white_max_x = i\n            #   max_x_coord = (i, j)\n            # if i < white_min_x:\n            #   white_min_x = i\n            #   min_x_coord = (i, j)\n\n      if top_white_cnt / (thr_session_gray.shape[1] * int(thr_session_gray.shape[0] / 10)) > 0.5:\n        top_parallel = True\n        min_y_coord = temp_min_y_coord\n      \n      if bot_white_cnt / (thr_session_gray.shape[1] * int(thr_session_gray.shape[0] / 10)) > 0.5:\n        bot_parallel = True\n        max_y_coord = temp_max_y_coord\n\n          # elif thr_session_gray[j][i] == 1 and j > thr_max_y:    \n          #   thr_max_y = j\n          #   thr_max_y_coord = (j, i)\n      # print('thr_min_y :', thr_min_y)\n      # print('thr_min_y_coord :', thr_min_y_coord)\n      try:\n        max_x_coord, min_x_coord\n        print('max_x_coord, min_x_coord :', max_x_coord, min_x_coord)\n      except:\n        pass\n\n\n      #     None \uc774\ub77c\uba74 \ub300\uce6d\uc774\ub3d9\uc744 \ud1b5\ud574 \ub9cc\ub4e4\uc5b4\uc8fc\uc5b4\uc57c\ud55c\ub2e4.     #\n      if len(ex_right_bot_vl) == 0:\n        if right_toppest_vl is not None:\n          x0, y0, x1, y1 = right_toppest_vl\n          slope = (y1 - y0) / float(x1 - x0)\n          angle = - math.degrees(math.atan(slope))\n\n          #       white_max_y \ub97c - toppest_vl angle \ub85c \uc9c0\ub098\ub294 \uc9c1\uc120      #\n          print('max_y_coord :', max_y_coord)\n          print('angle :', angle)\n          endy = 100 * math.sin(math.radians(angle))\n          endx = 100 * math.cos(math.radians(angle))\n          temp_vl = Line(max_y_coord, (max_y_coord[0] + endx, max_y_coord[1] + endy))\n          [left_point] = temp_vl.intersection(l2)\n          [right_point] = temp_vl.intersection(l3)\n          # print('left_point :', left_point)\n          right_bottest_vl = (float(left_point[0]), float(left_point[1]), float(right_point[0]), float(right_point[1]))\n          print('right_bottest_vl :', right_bottest_vl)\n\n      elif len(ex_right_top_vl) == 0:\n        if right_bottest_vl is not None:\n          x0, y0, x1, y1 = right_bottest_vl\n          slope = (y1 - y0) / float(x1 - x0)\n          angle = - math.degrees(math.atan(slope))\n\n          #       white_max_y \ub97c - toppest_vl angle \ub85c \uc9c0\ub098\ub294 \uc9c1\uc120      #\n          print('min_y_coord :', min_y_coord)\n          print('angle :', angle)\n          endy = 100 * math.sin(math.radians(angle))\n          endx = 100 * math.cos(math.radians(angle))\n          temp_vl = Line(min_y_coord, (min_y_coord[0] + endx, min_y_coord[1] + endy))\n          [left_point] = temp_vl.intersection(l2)\n          [right_point] = temp_vl.intersection(l3)\n          # print('left_point :', left_point)\n          right_toppest_vl = (float(left_point[0]), float(left_point[1]), float(right_point[0]), float(right_point[1]))\n          print('right_toppest_vl :', right_toppest_vl)\n\n      try:\n        x1, y1, x0, y0 = right_toppest_vl\n        cv2.line(vl_img, (int(x1), int(y1)), (int(x0), int(y0)), (0, 0, 255), 3, cv2.LINE_AA)\n        x1, y1, x0, y0 = right_bottest_vl\n        cv2.line(vl_img, (int(x1), int(y1)), (int(x0), int(y0)), (0, 0, 255), 3, cv2.LINE_AA)\n      except:\n        pass\n\n      if len(ex_left_bot_vl) == 0:\n        if left_toppest_vl is not None:\n          x0, y0, x1, y1 = left_toppest_vl\n          slope = (y1 - y0) / float(x1 - x0)\n          angle = - math.degrees(math.atan(slope))\n\n          #       white_max_y \ub97c - toppest_vl angle \ub85c \uc9c0\ub098\ub294 \uc9c1\uc120      #\n          print('max_y_coord :', max_y_coord)\n          print('angle :', angle)\n          endy = 100 * math.sin(math.radians(angle))\n          endx = 100 * math.cos(math.radians(angle))\n          temp_vl = Line(max_y_coord, (max_y_coord[0] + endx, max_y_coord[1] + endy))\n          [left_point] = temp_vl.intersection(l2)\n          [right_point] = temp_vl.intersection(l3)\n          # print('left_point :', left_point)\n          left_bottest_vl = (float(left_point[0]), float(left_point[1]), float(right_point[0]), float(right_point[1]))\n          print('left_bottest_vl :', left_bottest_vl)\n\n      elif len(ex_left_top_vl) == 0:\n        if left_bottest_vl is not None:\n          x0, y0, x1, y1 = left_bottest_vl\n          slope = (y1 - y0) / float(x1 - x0)\n          angle = - math.degrees(math.atan(slope))\n\n          #       white_max_y \ub97c - toppest_vl angle \ub85c \uc9c0\ub098\ub294 \uc9c1\uc120      #\n          print('min_y_coord :', min_y_coord)\n          print('angle :', angle)\n          endy = 100 * math.sin(math.radians(angle))\n          endx = 100 * math.cos(math.radians(angle))\n          temp_vl = Line(min_y_coord, (min_y_coord[0] + endx, min_y_coord[1] + endy))\n          [left_point] = temp_vl.intersection(l2)\n          [right_point] = temp_vl.intersection(l3)\n          # print('left_point :', left_point)\n          left_toppest_vl = (float(left_point[0]), float(left_point[1]), float(right_point[0]), float(right_point[1]))\n          print('left_toppest_vl :', left_toppest_vl)\n\n      try:\n        x1, y1, x0, y0 = left_bottest_vl\n        cv2.line(vl_img, (int(x1), int(y1)), (int(x0), int(y0)), (255, 255, 0), 3, cv2.LINE_AA)\n        x1, y1, x0, y0 = left_toppest_vl\n        cv2.line(vl_img, (int(x1), int(y1)), (int(x0), int(y0)), (255, 255, 0), 3, cv2.LINE_AA)\n      except:\n        pass\n\n      #       \uc77c\ub2e8\uc740 \uc704\uc544\ub798 \ub458\ub2e4 \uc788\ub294 \uc870\uac74 \uc131\ub9bd     #\n      #   \uc788\ub294 \ucabd\ub9cc \uc0ac\uc6a9, \uc591\ubc29\ud5a5 \uc18c\uc2e4\uc810 \ub2e4 \uc874\uc7ac\ud558\uba74 \uc18c\uc2e4\uc120 \uac1c\uc218\uac00 \ub354 \ub9ce\uc740 \ucabd \uc0ac\uc6a9   #   \n\n      # left_condition = left_bottest_vl is not None and left_toppest_vl is not None\n      # right_condition = right_bottest_vl is not None and right_toppest_vl is not None\n\n      # if left_condition or right_condition:\n        # print('left_bottest_vl', left_bottest_vl)\n      \n      #       original vl_list \ub294 remove \uac00 \uc874\uc7ac\ud558\uae30 \ub54c\ubb38\uc5d0 copy_ version \uc0ac\uc6a9\ud55c\ub2e4.       #\n      print('len(copy_left_vl_list) :', len(copy_left_vl_list))\n      print('len(copy_right_vl_list) :', len(copy_right_vl_list))\n      if len(copy_left_vl_list) >= len(copy_right_vl_list):\n        #       toppest & bottest vl should be on the min_y & max_y of white mask       #\n        # x1, y1, x0, y0 = left_bottest_vl\n        # cv2.line(vl_img, (int(x1), int(y1)), (int(x0), int(y0)), (0, 0, 255), 3, cv2.LINE_AA)\n        x1, y1, x0, y0 = left_toppest_vl\n        # cv2.line(vl_img, (int(x1), int(y1)), (int(x0), int(y0)), (0, 0, 255), 3, cv2.LINE_AA)\n        \n        # if thr_min_y == 0:\n        #   thr_min_x = thr_session_gray.shape[1]\n        #   for i in range(thr_session_gray.shape[1]):\n        #       if thr_session_gray[0][i] == 255 and i < thr_min_x:\n        #         thr_min_x = i\n        #         thr_min_y_coord = (i, 0)\n        #         break\n        #   print('thr_min_y_coord :', thr_min_y_coord)\n        if top_parallel:\n          top_line = Line((x1, y1), (x0, y0))\n          print('top_line.slope :', float(top_line.slope))            \n          if abs(top_line.slope) < 0.05:\n              max_x_coord = (0, 0)\n          parallel_tl = top_line.parallel_line(min_x_coord)\n          [tl] = parallel_tl.intersection(l2)\n          [tr] = parallel_tl.intersection(l3)\n          br, bl = left_bottest_vl[2:], left_bottest_vl[:2]\n        else:\n          tl, tr, br, bl = left_toppest_vl[:2], left_toppest_vl[2:], left_bottest_vl[2:], left_bottest_vl[:2]\n      \n      else:\n        # x1, y1, x0, y0 = right_bottest_vl\n        # cv2.line(vl_img, (int(x1), int(y1)), (int(x0), int(y0)), (0, 0, 255), 3, cv2.LINE_AA)\n        x1, y1, x0, y0 = right_toppest_vl\n        # cv2.line(vl_img, (int(x1), int(y1)), (int(x0), int(y0)), (0, 0, 255), 3, cv2.LINE_AA)\n\n        # if thr_min_y == 0:\n        #   thr_max_x = 0\n        #   for i in range(thr_session_gray.shape[1] - 1, 0, -1):\n        #       print('i :', i)\n        #       if thr_session_gray[0][i] == 255 and i > thr_max_x:\n        #         thr_max_x = i\n        #         thr_min_y_coord = (i, 0)\n        #         break\n        #   print('thr_min_y_coord :', thr_min_y_coord)\n        if top_parallel:\n          top_line = Line((x1, y1), (x0, y0))\n          print('top_line.slope :', float(top_line.slope))\n          if abs(top_line.slope) < 0.05:\n              max_x_coord = (thr_session_gray.shape[1], 0)\n          parallel_tl = top_line.parallel_line(max_x_coord)\n          [tl] = parallel_tl.intersection(l2)\n          [tr] = parallel_tl.intersection(l3)\n          br, bl = right_bottest_vl[2:], right_bottest_vl[:2]\n        else:\n          tl, tr, br, bl = right_toppest_vl[:2], right_toppest_vl[2:], right_bottest_vl[2:], right_bottest_vl[:2]\n        \n      #       Refering      #\n      refered = np.asarray(refer)[:vl_img.shape[0], :vl_img.shape[1]]\n\n      # plt.imshow(refered)\n      # plt.title('refered')\n      # plt.show()\n\n      #   tl, tr, br, bl    #\n      #     refer\ub97c \uc704\ud574 src_x => 0 \uc73c\ub85c \ub9de\ucdb0\uc900\ub2e4.    #\n      src = np.array([\n          [0, 0],\n          [vl_img.shape[1], 0],\n          [vl_img.shape[1], vl_img.shape[0]],\n          [0, vl_img.shape[0]]], dtype = \"float32\")\n      dst = np.array([list(tl),\n                      list(tr),\n                      list(br),\n                      list(bl)], dtype = \"float32\")\n\n      print()\n      print(\"#          Warping Points        #\")\n      print('src :', src)\n      print('dst :', dst)\n\n      # compute the perspective transform matrix and then apply it\n      matrix = cv2.getPerspectiveTransform(src, dst)\n      refered = cv2.warpPerspective(refered, matrix, (refered.shape[1], refered.shape[0]))\n      \n      plt.subplot(121)\n      plt.imshow(vl_img)\n      plt.title('Session_vl_img')\n      # plt.xlim(np.min(vps[:, [0]]), np.max(vps[:, [0]]))\n      # plt.ylim(np.min(vps[:, [1]]), np.max(vps[:, [1]]))\n      plt.subplot(122) \n      plt.imshow(refered)\n      plt.show() \n\n      org_color_np2[:, int(min_x):int(max_x)] = refered\n\n\n      #     i != 0 \uc778 \uacbd\uc6b0 break     #\n      if reg_index == 0 and np.sum(sorted_predict_cen) != 0 and not iter:\n        iter = True\n        print('iter :', iter)\n\n      else:\n        break\n\n  \n  #         Refer\uc758 \uac80\uc740 \ubd80\ubd84\uc740 original image\ub85c \ucc44\uc6b4\ub2e4.       #\n  for i in range(org_color_np2.shape[1]):\n    for j in range(org_color_np2.shape[0]):\n      if sum(org_color_np2[j][i]) == 0:\n        org_color_np2[j][i] = org_color_np[j][i]\n  \n  print('elapsed time :', time.time() - start)\n  print()\n\n  \n  plt.figure(figsize=(15, 10))\n  plt.subplot(131)\n  plt.imshow(org_np3)\n\n  plt.subplot(132)\n  plt.imshow(org_color_np2)\n  # plt.show()\n\n  # print('np.max(org_np) :', np.max(org_np))\n  org_np = org_np/ 255.\n  refer = org_color_np2\n\n  #     1.wall_mask * reference color image + (1 - wall_mask) * original_image)    #\n  syn_ = org_np * (refer) + (1 - org_np) * org_color_np\n  syn = org_np * syn_ + (1 - org_np) * org_color_np\n  plt.subplot(133)\n  plt.imshow(syn.astype(np.uint8))\n  plt.show()\n\n  \n  if one_iter:\n    break\n  # break\n```\n\n\n    Output hidden; open in https://colab.research.google.com to view.\n\n\n\n```\n\n  # v_border = line((0, 0), (0, skl_copy.shape[0]))\n  # v_border_lower = line((skl_copy.shape[1], 0), (skl_copy.shape[1], skl_copy.shape[0]))\n  # for h_line in h_lines:\n\n  #     #       Find Intersection between v_line, h_line      #\n  #     vh_intersections_x = list()\n  #     vh_intersections_y = list()\n\n  #     hline = line(h_line[:2], h_line[2:])\n  #     for reg_x, reg_y in zip(reg_xs, reg_ys):\n  #       vline = line((reg_x[0], reg_y[0]), (reg_x[1], reg_y[1]))\n\n  #       #     Extract only x - coordination     #\n  #       vh_intersections_x.append(intersection2(vline, hline)[0])\n  #       vh_intersections_y.append(intersection2(vline, hline)[1])\n\n  #     # h_x = np.array([h_line[0], h_line[2]])\n  #     # h_y = np.array([h_line[1], h_line[3]])\n  #     # ex_h_x, ex_h_y = extended(h_x, h_y, 500)\n  #     # ex_h_line = line((int(h_x[0]), int(h_y[0])), (int(h_x[1]), int(h_y[1])))\n  #     r = intersection2(v_border, hline)\n  #     r_lower = intersection2(v_border_lower, hline)\n\n  #     vh_intersections_x.append(r[0])\n  #     vh_intersections_y.append(r[1])\n  #     vh_intersections_x.append(r_lower[0])\n  #     vh_intersections_y.append(r_lower[1])\n\n  #     sorted_vh_inter_x = sorted(vh_intersections_x)\n  #     # print('vh_intersections_x :', vh_intersections_x)\n  #     # print('sorted_vh_inter_x :', sorted_vh_inter_x)\n\n  #     center_h_x = (h_line[0] + h_line[2]) / 2\n  #     # print('center_h_x :', center_h_x)\n      \n  #     #       hline \uc0c1\uc758 \uad50\ucc28\uc810\uc744 \ucc3e\uc544\ub0b4\uc11c \ubc94\uc704 \ub0b4\uc5d0\uc11c \uc5f0\uacb0\ud55c\ub2e4.      #\n  #     for i in range(1, len(sorted_vh_inter_x)):\n\n  #       if sorted_vh_inter_x[i - 1] <= center_h_x <= sorted_vh_inter_x[i]:\n  #         lx, ly = sorted_vh_inter_x[i - 1], vh_intersections_y[vh_intersections_x.index(sorted_vh_inter_x[i - 1])]\n  #         rx, ry = sorted_vh_inter_x[i], vh_intersections_y[vh_intersections_x.index(sorted_vh_inter_x[i])]\n  #         # print('lx, ly, rx, ry :', lx, ly, rx, ry)\n  #         #       \uc774\uacf3\uc758 lx, ly, rx, ry \ub294 close_p \ub2e4. \uc88c\uc6b0\ub85c \ub098\ub258\uc5b4\uc9c4 lx, ly\uac00 \uc544\ub2c8\ub2e4.     #\n            \n  #           #       \uc815\uc81c\ub41c \uad50\ucc28\uc810\uc744 \ub9cc\ub4dc\ub294 hline\ub9cc \uc0ac\uc6a9\ud574\uc57c\ud55c\ub2e4.        #\n  #         for inters in all_closest_inters:\n  #           for inter in inters:\n  #             if lx in inter or rx in inter:\n  #               h_intersections.append((lx, ly, rx, ry))\n  #               # cv2.line(black_plane, (int(lx), int(ly)), (int(rx), int(ry)), (0, 0, 255), 1, cv2.LINE_AA)\n          \n\n  #       vline \uae30\uc900\uc73c\ub85c \uad6c\ud68d\ud574\uc57c\ud55c\ub2e4. -> \uac00\uc7a5 \uc67c\ucabd / \uc624\ub978\ucabd vline + \uad6c\uc5ed \uba3c\uc800 \ucc3e\uc544 \uc791\uc5c5\ud558\uae30     #\n  #       vline \ubcc4\ub85c \uad6c\ud68d \ub098\ub204\uae30      #\n  # h_intersections = list(set(h_intersections))\n  # print('np.array(all_closest_inters).shape :', np.array(all_closest_inters).shape)\n  # all_closest_inters = np.array(all_closest_inters)\n  # print('len(all_closest_inters) :', len(all_closest_inters))\n\n  # center_xs = list()\n  # for inters in all_closest_inters:\n  #   #     all_closest_inter\uac00 \uc815\ub82c\ub418\uc9c0 \uc54a\uc558\ub2e4\uba74 inters type = list()      #\n  #   sum_x = 0\n  #   for inter in inters:\n  #     sum_x += inter[0] + inter[2]\n  #   center_xs.append(sum_x / len(inters) * 2)\n  # sorted_center_xs = sorted(center_xs)\n\n  # sorted_index = list()\n  # for center_x in sorted_center_xs:\n  #   # print('center_x :', center_x)\n  #   sorted_index.append(center_xs.index(center_x))\n  # # print('sorted_index :', sorted_index)\n  # #       sorted_center_xs \uc21c\uc11c\ub85c all_closest_inter\ub97c \uc815\ub82c\ud55c\ub2e4.     #\n  # #       index list\ub97c \ucd94\ucd9c\ud574\uc11c for \ubb38\uc73c\ub85c all_closest_inter\uc758 inters\ub97c \ucd94\ucd9c\ud574\n  # #       sorted_all ... \uc5d0 append \uc2dc\ud0a8\ub2e4.      #\n  # sorted_all_closest_inters = list()\n  # sorted_all_centroid_inters = list()\n  # for s_index in sorted_index:\n  #   sorted_all_closest_inters.append(all_closest_inters[s_index])\n  #   sorted_all_centroid_inters.append(all_centroid_inters[s_index])\n  # all_closest_inters = sorted_all_closest_inters\n  # all_centroid_inters = sorted_all_centroid_inters\n\n```\n\n\n```\n#                                   Refering                                 #\n      #     Find Top left / right & Bottom left / right       #\n      #     ->  tl, tr, bl, br     #\n      four_inters = np.array(four_inters)\n      [tl, tr, br, bl] = order_points(four_inters)\n      # print(four_inters.shape)\n      top_length = math.hypot(tl[0] - tr[0], tl[1] - tr[1])\n      bottom_length = math.hypot(bl[0] - br[0], bl[1] - br[1])\n      max_hlength = max(top_length, bottom_length)\n\n      #     1. Compare left / right height     #\n      l_height = bl[1] - tl[1]\n      r_height = br[1] - tr[1]\n\n      #     2. Extend Shorter Height      #\n      if l_height <= r_height:\n        shorter_points = [bl, tl]\n        longer_points = [br, tr]\n      else:\n        shorter_points = [br, tr]\n        longer_points = [bl, tl]\n\n      ex_shorter_points = np.zeros_like(shorter_points)\n      ex_longer_points = np.zeros_like(longer_points)\n\n      print('shorter_points :', shorter_points)\n      x = (shorter_points[0][0], shorter_points[1][0])\n      y = (shorter_points[0][1], shorter_points[1][1])\n      print('shorter x, y :', x, y)\n\n      y_ext = np.array([org_np.shape[0], 0])\n      p = np.polyfit(y, x , deg=1)\n      x_ext = np.poly1d(p)(y_ext)\n\n      ex_shorter_points[0] = [x_ext[0], y_ext[0]]\n      ex_shorter_points[1] = [x_ext[1], y_ext[1]]\n\n      #     Find intersection between (longer + shorter points)'s parallel line and longer line   #\n      long_short_lower = Line(longer_points[0], shorter_points[0])\n      long_short = Line(longer_points[1], shorter_points[1])\n      p_line_lower = long_short_lower.parallel_line(ex_shorter_points[0])\n      p_line = long_short.parallel_line(ex_shorter_points[1])\n      longer_line = Line(longer_points[0], longer_points[1])\n\n      # print('ex_shorter_points[1] in p_line ? :', ex_shorter_points[1] in p_line)\n      # print('p_line_lower.intersection(longer_line) :', p_line_lower.intersection(longer_line)[0][0])\n      ex_longer_points[0] = [p_line_lower.intersection(longer_line)[0][0], p_line_lower.intersection(longer_line)[0][1]]\n      ex_longer_points[1] = [p_line.intersection(longer_line)[0][0], p_line.intersection(longer_line)[0][1]]\n\n      if l_height <= r_height:\n        ex_bl, ex_tl = ex_shorter_points\n        ex_br, ex_tr = ex_longer_points\n      else:\n        ex_br, ex_tr = ex_shorter_points\n        ex_bl, ex_tl = ex_longer_points\n\n      for ex_p in [ex_bl, ex_br, ex_tl, ex_tr]:\n        print(ex_p)\n        # cv2.circle(black_plane2, (int(ex_p[0]), int(ex_p[1])), 10, (255, 0, 255), -1)\n\n      min_x, max_x = min(ex_bl[0], ex_tl[0]), max(ex_br[0], ex_tr[0])\n      min_y, max_y = min(ex_tl[1], ex_tr[1]), max(ex_bl[1], ex_br[1])\n      src_x = max((max_x - min_x), max_hlength) * math.sqrt(2)\n      print('src_x :',  src_x)\n\n      refered = np.asarray(refer)[:int(max_y - min_y), :int(src_x)]\n\n      # plt.imshow(refered)\n      # plt.title('refered')\n      # plt.show()\n\n      #   tl, tr, br, bl    #\n      #     refer\ub97c \uc704\ud574 src_x => 0 \uc73c\ub85c \ub9de\ucdb0\uc900\ub2e4.    #\n      src = np.array([\n          [0, 0],\n          [src_x, 0],\n          [src_x, max_y - min_y],\n          [0, max_y - min_y]], dtype = \"float32\")\n      dst = np.array([\n                      [ex_tl[0] - min_x, ex_tl[1] - min_y],\n                      [ex_tr[0] - min_x, ex_tr[1] - min_y],\n                      [ex_br[0] - min_x, ex_br[1] - min_y],\n                      [ex_bl[0] - min_x, ex_bl[1] - min_y]], dtype = \"float32\")\n\n      print('src :', src)\n      print('dst :', dst)\n\n      # compute the perspective transform matrix and then apply it\n      matrix = cv2.getPerspectiveTransform(src, dst)\n      refered = cv2.warpPerspective(refered, matrix, (refered.shape[1], refered.shape[0]))\n\n      # print('refered.min() :', refered.min())\n      # print(refered[[0], [0]])\n      # print('refered.shape :', refered.shape)\n      # plt.imshow(refered)\n      # plt.title('warfed')\n      # plt.xlim(min_x, max_x)\n      # plt.xlim(0, max_x - min_x)\n      # plt.ylim(max_y, min_y)\n      # plt.xlim(-1000, 1000)\n      # plt.ylim(1000, -1000)\n      # plt.show()\n      \n      refer_crop = refered[int(abs(min_y)): int(abs(min_y)) + org_np.shape[0], :]\n      # print('refer_crop.shape :', refer_crop.shape)\n\n      # plt.imshow(refer_crop)\n      # plt.title('cropped refer')\n      # plt.show()\n\n      #     Crop Section From Cropped Refer     #\n      #         src_x => 0\uc73c\ub85c \ub9de\ucdb0\uc92c\ub358 \uac83\uc744 \ub418\ub3cc\ub9b0\ub2e4.      #\n      print('int(min_x) :', int(min_x))\n      print('int(min_y) :', int(min_y))\n\n      for i in range(refer_crop.shape[1]):\n        for j in range(refer_crop.shape[0]):\n          if sum(refer_crop[j][i]) != 0:\n            if i + int(min_x) < black_plane2.shape[1]:\n              black_plane2[j][i + int(min_x)] = refer_crop[j][i]\n```\n", "meta": {"hexsha": "c456f86cab900415a62b9cc5e9df501cac5bb2b6", "size": 66436, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Layout Estimation without AI kmeans.ipynb", "max_stars_repo_name": "jaytoone/Indoor_Segmentation", "max_stars_repo_head_hexsha": "d99e502f99cb74000483974d931c2da058071bec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Layout Estimation without AI kmeans.ipynb", "max_issues_repo_name": "jaytoone/Indoor_Segmentation", "max_issues_repo_head_hexsha": "d99e502f99cb74000483974d931c2da058071bec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Layout Estimation without AI kmeans.ipynb", "max_forks_repo_name": "jaytoone/Indoor_Segmentation", "max_forks_repo_head_hexsha": "d99e502f99cb74000483974d931c2da058071bec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-29T15:27:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-29T15:27:56.000Z", "avg_line_length": 66436.0, "max_line_length": 66436, "alphanum_fraction": 0.5595911855, "converted": true, "num_tokens": 17581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.051845463353511735, "lm_q1q2_score": 0.01976450505197486}}
{"text": "# Assignment 1\n**CS283 Computer Vision, Harvard University, Fall 2019**\n\n**Due Wednesday, Sep. 18, at 5:00pm**\n\nName: *(<font color=red>fill name here</font>)*\n\n---\n\nThe intended outcomes of this assignment are for you to be familiar with Python as a tool for manipulating images and to deepen your understanding of model-fitting and the two-dimensional projective plane. There is a **Hints and Information** section at the end of this document that is likely to help you a lot. This will be a common feature in future assignments.\n\nAssignments in this course will use Python 3. The skeleton code we provide will only be tested on JupyterHub (via the course webpage) using a Python 3 notebook and certain pre-installed packages (inlcuding numpy, scipy, and opencv). Likewise, we expect any code that you submit to execute in the course's JupyterHub environment.\n\nThe input image files that are required to complete this assignment can be found in the <tt>pset1.zip</tt> archive that accompanies this notebook on the course website. Be sure to upload this ZIP archive tp JupterHub before running the notebook's first cell (which unpacks the archive into a <tt>./pset1</tt> folder). This will be another common feature in future assignments.\n\nYou will submit your work by editing this notebook and uploading it to the submission system on the course website. It is important that your submission executes and, as much as possible, maintains the notebook's original formatting. Submissions that do not execute or that deviate substantially in terms of formatting risk not being graded. Please read the **CS283 Assignment Submission Guidelines** for more detailed instructions.\n\nRemember that the online submission system closes *exactly* at the stated deadline. If you find yourself in the uncomfortable position of working very close to the deadline, we advise that you upload early and often.\n\n\n```python\n# Extract required pset files \n\nimport os             # for file handling\nimport zipfile as zf  # For unpacking pset ZIP archives\n\n# Extract required pset files \nassert os.path.exists(\"./pset1.zip\"), 'Upload the pset ZIP archive and then re-run the cell.'\nfiles = zf.ZipFile(\"./pset1.zip\", 'r')\nfiles.extractall('.')\nfiles.close()\n```\n\n\n```python\n# Import other required libraries here\nimport cv2           # OpenCV\nimport numpy as np   # numpy\n\n# Use this line to make matplotlib plot inline (only need to call it once when importing matplotlib)\n%matplotlib inline\n\nimport matplotlib.pyplot as plt\n# Modify this line to adjust the displayed plot size. You can also call\n# it with different parameters before specific plots.\nplt.rcParams['figure.figsize'] = [10, 10]\n```\n\n## Question 1 (10 points)\n\nIn the <tt>./pset1/data</tt> folder there is a color image called <tt>baboon.tif</tt>.  This image appears frequently in the image processing literature. \n\n**a.** Write a sequence of Python commands that loads the image using OpenCV and reports its height and width in pixels.\n\n*Hints: See OpenCV documentation for <tt>cv2.imread()</tt> and the <tt>shape</tt> attribute of numpy arrays. Use the built-in Python function <tt>print()</tt> for display text (and note that, unlike Python 2, Python 3 requires parentheses for this function). The <tt>format()</tt> method for string formatting may also be useful.*\n\n\n```python\n# TO DO: your code here\n```\n\n**b.**  Write a sequence of Python commands that converts this image to a grayscale image and displays it using the matplotlib package. In addition, display three other grayscale images that correspond to each of the three separate RGB color components. To do this you will need to understand the way OpenCV represents RGB images and how to decompose them.  Use the <tt>subplot</tt> command of the <tt>matplotlib.pyplot</tt> package to display the four results in a single row.\n\n*Hints: See OpenCV documentation for <tt>cv2.cvtColor()</tt> and matplotlib documentation for <tt>matplotlib.pyplot.imshow()</tt>. To pretty up your plots, see the commands <tt>matplotlib.pyplot.axis()</tt> and <tt>matplotlib.pyplot.title()</tt>. Also note that by default, OpenCV loads images in BGR order and not RGB.*\n\n\n```python\n# TO DO: your code here\n```\n\n**c.** You can use the <tt>cv2.imwrite()</tt> command to write an image to a file in various formats with varying levels of compression. Write code that creates a new JPEG version of the original color image with a quality setting of 95 to the file <tt>baboon_compressed.jpg</tt>, and then reads and displays this new image next to the original image in a single row using <tt>subplot</tt>. Can you tell the difference between the compressed image and the original? \n\n\n```python\n# TO DO: your code here\n```\n\n### Answer:\n*TO DO: Write your answer here.*\n\n**d.** The compression ratio is the ratio between the size of the original file and the size of the compressed file (in bytes). The following cell will query the file sizes and report them. Based on the cell's output (you may need to modify the cell to point to the correct location of your compressed image file), what is the compression ratio for this quality setting of 0.95?\n\n\n```python\nfilesize = os.path.getsize('./pset1/data/baboon.tif')\nfilesize_compressed = os.path.getsize('baboon_compressed.jpg')\nprint(\"The original file is {} bytes and the compressed one is {} bytes\".format(filesize, filesize_compressed))\n```\n\n### Answer:\n*TO DO: Write your answer here.*\n\n**e.** Write code in the following cell that allows you to experiment with the JPEG quality settings, allowing you to visually compare the original and compressed images and also see the compression ratio for any quality setting you desire. Using this code, determine the smallest quality value for which the compressed image is indistinguishable from the original. What is this quality value and what is the associated compression ratio?\n\n\n```python\n# TO DO: your code here\n```\n\n### Answer:\n\n*TO DO: Write your answer here.*\n\n## Question 2 (10 points)\n\nThe <tt>./pset1/data</tt> folder contains another popular image, <tt>cameraman.tif</tt>.\n\n**a.** Write code that loads the image, converts it to grayscale, uses a random number generator to select exactly 10% of the pixels, and then replaces their gray-level values with independent, random integers uniformly distributed between 0 and 255. Display the result. Next, use subplot to display two more results beside this one, where the percentage of randomly replaced pixels in the original image is 25% and 50%, respectively. \n\n*Hints: The functions <tt>numpy.random.choice()</tt> and <tt>numpy.random.randint()</tt>, as well as the <tt>flat</tt> attribute of numpy arrays may be useful.*\n\n\n```python\n# TO DO: your code here\n```\n\n## Question 3 (30 points)\n\nThere is a set of points $\\tilde{\\mathbf{x}}_i=(x_i,y_i)$ in the image plane and we want to find the best line passing through them. \n\nThe next cell defines two functions that calculate the line in two different ways using two different measures of quality. In both functions, the input is two $N\\times 1$ numpy arrays with inhomogeneous coordinates, $\\{x_i\\}$ and $\\{y_i\\}$, of $N$ points. The output is the coordinates of a line $\\boldsymbol\\ell=(a,b,c)$.\n\n1. The function <tt>fit_line_vertical()</tt> solves the problem by finding $(a, c)$ (setting $b = 1$) that most closely satisfy the\nequations $y_i=-ax_i-c$, in a least-squares sense. It minimizes the sum of squares of vertical distances between the points and the line by encoding the constraints in matrix form\n\\begin{equation*}\n\\left.\n\\begin{array}{c}\n-a x_1 - c = y_1 \\\\\n-a x_2 - c = y_2 \\\\\n\\vdots \\\\\n-a x_N - c = y_N\n\\end{array} \\right\\} \\Rightarrow \\underbrace{\\begin{bmatrix}\n-x_1 & -1 \\\\\n-x_2 & -1 \\\\\n\\vdots & \\vdots \\\\\n-x_N & -1\n\\end{bmatrix}}_{\\bf A} \\cdot \\underbrace{\\begin{bmatrix}\na \\\\\nc\n\\end{bmatrix}}_{\\bf v} = \\underbrace{\\begin{bmatrix}\ny_1 \\\\\ny_2 \\\\\n\\vdots \\\\\ny_N\n\\end{bmatrix}}_{\\bf b}\n\\end{equation*}\nand solving\n\\begin{equation*}\n\\text{arg}\\min_\\mathbf{v}\\|\\mathbf{A}\\mathbf{v}-\\mathbf{b}\\|^2.\n\\end{equation*}\n\n2. The function <tt>fit_line_homogeneous()</tt> solves the problem by finding $\\boldsymbol\\ell=(a,\\ b,\\ c)$ that most closely satisfies the equations $ax_i+by_i+c=0$, in a least-squares sense. That is, it minimizes the sum of homogeneous algebraic errors, $\\sum\\left(\\boldsymbol\\ell^\\top \\mathbf{x}_i\\right)^2$ with $\\mathbf{x}_i\\triangleq(x_i,y_i,1)$. It does this by encoding the constraints in matrix form\n\\begin{equation*}\n\\underbrace{\\begin{bmatrix}\nx_1 & y_1 & 1 \\\\\nx_2 & y_2 & 1 \\\\\n\\vdots & \\vdots \\\\\nx_N & y_N & 1 \\\\\n\\end{bmatrix}}_{\\bf A} \\cdot \\underbrace{\\begin{bmatrix}\na \\\\\nb \\\\\nc\n\\end{bmatrix}}_{\\boldsymbol\\ell} = \\underbrace{\\begin{bmatrix}\n0 \\\\\n0 \\\\\n\\vdots \\\\\n0\n\\end{bmatrix}}_{\\bf 0}\n\\end{equation*}\nand solving\n\\begin{equation*}\n\\text{arg}\\min_\\boldsymbol\\ell\\|\\mathbf{A}\\boldsymbol\\ell\\|^2\\quad \\text{ such that } \\|\\boldsymbol\\ell\\|=1.\n\\end{equation*}\n\n\n```python\ndef fit_line_vertical(x, y):\n    # Method A: linear regression (vertical distance)\n    \n    # Construct the Nx2 \"A matrix\"\n    A = -np.concatenate([x[:, np.newaxis], np.ones((x.size, 1))], axis=1)\n\n    # Least squares solution\n    l = np.linalg.lstsq(A, y, rcond=None)[0]\n\n    # Format line as (a,b,c)\n    return l[0], 1.0, l[1]\n\ndef fit_line_homogeneous(x, y):\n    # Method B: Naive homogeneous\n    \n    # Construct the \"A matrix\"\n    A = np.concatenate([x[:, np.newaxis], y[:, np.newaxis], np.ones((x.size, 1))], axis=1)\n\n    # SVD\n    _, _, V = np.linalg.svd(A)\n\n    # Extract last column of V matrix (note that np.linalg.svd() returns a transposed version of V)\n    l = V[2, :]\n\n    return l\n```\n\n**a.** Write code that loads the image <tt>dots.tif</tt> (from the <tt>./pset1/data</tt> folder, as usual) and: i) detects the red, green, and  blue points and obtain their $(x,y)$ image coordinates; ii) calls the functions <tt>fit_line_vertical()</tt> and <tt>fit_line_homogeneous()</tt> to fit two different lines to each set of points; and iii) plots these lines (two lines for each color) superimposed on the image.\n\n*Hints: The functions <tt>numpy.nonzero()</tt>, <tt>numpy.concatenate()</tt>, and <tt>numpy.bitwise_and()</tt> may be useful. You may also want to use <tt>matplotlib.pyplot.xlim()</tt> and <tt>matplotlib.pyplot.ylim()</tt> for plotting. Note that flipping the limits in <tt>matplotlib.pyplot.ylim()</tt> flips the y axis, which may be desirable for images.*\n\n\n```python\n# TO DO: your code here\n```\n\n**b.** Neither of the two solutions from part (a) minimize the sum of squares of perpendicular distances between the points and the line, which for a single point is \n\n\\begin{equation*}\n \\frac{|a x_i + b y_i + c|}{\\sqrt{a^2 + b^2}}.\n\\end{equation*}\n\nWrite code for a new function <tt>fit_line_perpendicular()</tt> that has the same input and output as the previous functions but that provides a solution that minimizes the sum of squares of perpendicular distances.\n\nAlso, write code (adapted from (a)) that calls the function <tt>fit_line_perpendicular()</tt> and plots the fitted lines (one line for each color) superimposed on the image <tt>dots.tif</tt>.\n\n\n```python\n# TO DO: your code here\n```\n\n**c.** These lines do not intersect at a point, but we can find a point that comes \"closest\" to a three-way intersection by finding the point that minimizes the sum of squared perpendicular distances from the point to the three lines found in part (b). For this, you should create a procedure that is analogous to the method you implemented in part (b): formulate and solve an appropriate linear system of the form ${\\bf A}{\\bf x}={\\bf 0}$ with constraints on the solution ${\\bf x}$. Using words and equations, describe your construction of such a constrained linear system and explain why its solution is the minimum of the sum of squared perpendicular distances. Write code that implements your constructioon, computes the \"best point\", and displays this point superimposed on the image and with the three lines found in (b).\n\n### Answer:\n\n*TO DO: Write your answer here.*\n\n\n```python\n# TO DO: your code here\n```\n\n## Question 4 (20 points)\n\nIn the presence of outliers, we require more robust techniques for model fitting. RANSAC is one such method that is both useful and conceptually simple.\n\n**a.** Write code that loads the image <tt>./pset1/data/dots_outliers.tif</tt>, detects the coordinates of the white pixels in the image and then calls your function <tt>fit_line_perpendicular()</tt> to fit a line to these inlying points. Also, write code that displays your result superimposed on the image. Note that, in this case, the image is black-and-white, with the points being white (you may need to zoom-in to see the points clearly).\n\n\n```python\n# TO DO: your code here\n```\n\n**b.** Write code that uses RANSAC to improve the fit and draw a better line, by first identifying a subset of inlying, nearly-collinear points, and then applying <tt>fit_line_perpendicular()</tt> to the inliers. We suggest that the number of iterations be 100 and the threshold used to determine the inlying set for each iteration be a distance of 20 pixels (as defined in the code below). Display your lines from both (a) and (b) together, superimposed on the original image.\n\n\n\n```python\nnum_iter = 100         # number of RANSAC iterations\ninlier_threshold = 20  # threshold for inlier set of each line\n\n# TO DO: your code here\n```\n\n## Question 5 (10 points)\n\nFollowing Hartley & Zisserman, the notation in this question is such that ${\\bf x}$ and $\\tilde{\\bf x}$ indicate homogeneous and inhomogeneous vectors, respectively. \n\nConsider a right triangle with vertices $\\tilde{\\bf x}_1=(0,\\ 0)$, $\\tilde{\\bf x}_2=(m,\\  0)$ and $\\tilde{\\bf x}_3=(0,\\ m)$, and suppose this triangle is warped by an affine transformation such that\n\\begin{equation}\\label{eq:affine}\n\\left(\\begin{array}{c} x' \\\\ y' \\\\ 1\\end{array}\\right)=\n\\left[\\begin{array}{ccc} a_{11} & a_{12} & t_x \\\\ a_{21} & a_{22} & t_y \\\\ 0 & 0 & 1\\end{array}\\right]\n\\left(\\begin{array}{c} x \\\\ y \\\\ 1\\end{array}\\right),\\nonumber\n\\end{equation}\nor ${\\bf x}'={\\bf A}{\\bf x}$.  Derive an expression for the area of the warped triangle defined by $\\tilde{\\bf x}'_1$, $\\tilde{\\bf x}'_2$ and $\\tilde{\\bf x}'_3$.  Use this expression to prove that if two right triangles (with $m=m_1$ and\n$m=m_2$) are warped by the same affine transformation, the ratio of their areas is preserved.\n\n\n\n### Answer:\n\n*TO DO: Write your answer here.*\n\n## Hints and Information\n\n- For help with Python itself, use the Python 3.7 [documentation](https://docs.python.org/3.7/). Throughout the course we will be using popular libraries such as [OpenCV](https://opencv.org/), [numpy, scipy](https://docs.scipy.org/doc/numpy/reference/) and [matplotlib](https://matplotlib.org/), all of which have documentation available online. For refreshing your numpy knowledge, we highly recommend going through a basic numpy tutorial [here](https://docs.scipy.org/doc/numpy/user/quickstart.html). OpenCV is a package for image processing and computer vision which we will be using heavily throughout the course. It stores images and other data as numpy arrays, and therefore we will be working with numpy a lot.\n\n-  A linear least-squares problem is one in which we want to determine the vector ${\\bf x}$ that best satisfies a set of inconsistent linear constraints ${\\bf A}{\\bf x}={\\bf b}$ in the sense of minimum square error. That is, we wish to solve:\n\\begin{equation}\n{\\bf x}^*=\\textrm{arg}\\min_{\\bf x} ||{\\bf A}{\\bf x}-{\\bf b}||^2 =\\textrm{arg}\\min_{\\bf x} ({\\bf A}{\\bf x}-{\\bf b})^\\top({\\bf A}{\\bf x}-{\\bf b}).\n\\end{equation}\nThe solution is found in closed-form by differentiating the objective function with respect to ${\\bf x}$ and equating the result to zero. This yields\n\\begin{equation}\n{\\bf x}^*= ({\\bf A}^\\top{\\bf A})^{-1}{\\bf A}^\\top{\\bf b}.\n\\end{equation}\nIn the above expression, the inverse is used only for notational purpose. The explicit calculation of $({\\bf\nA}^\\top{\\bf A})^{-1}$ is *very bad practice*, because finding the inverse is both very\nexpensive and [numerically unstable](http://blogs.mathworks.com/loren/2007/05/16/purpose-of-inv/). Instead, it is better to use a method such as QR factorization to solve the (consistent) linear system $({\\bf A}^\\top{\\bf A}){\\bf x}={\\bf A}^\\top{\\bf b}$, sometimes called the *normal equation* of the original linear system. In order to solve linear least squares problems in such a way we can use <tt>numpy.linalg.lstsq()</tt> or <tt>numpy.linalg.solve()</tt> (similar to doing <tt>x = A \\ b</tt> in MATLAB).\n\n- Based on the \"CS283 Assignment Submission Guidelines\", your submission should have the following file structure:\n\n<tt>lastname_firstname_psetx.zip</tt><br>\n&emsp;&emsp;<tt>+-- lastname_firstname_psetx.ipynb.............</tt>Jupyter notebook <span style=\"background-color:yellow\">with all code, $\\LaTeX$ answers, and output.</span><br>\n&emsp;&emsp;<tt>+-- lastname_firstname_psetx.html..............</tt>HTML version of notebook <span style=\"background-color:yellow\">with all code, $\\LaTeX$ answers, and output.</span><br>\n&emsp;&emsp;<tt>+-- src/.......................................</tt>External python functions required by the notebook (none for pset1).<br>\n&emsp;&emsp;<tt>+-- img/.......................................</tt>Images embedded in notebook (none expected for pset1).<br>\n&emsp;&emsp;<tt>+-- data/......................................</tt>Image and other data files for the notebook, such as <tt>cameraman.tif</tt> and <tt>baboon.tif</tt>.<br>\n", "meta": {"hexsha": "ba78fa7fdbde915fcfc9ce48239e33a39009677e", "size": 23229, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "pset1 (1).ipynb", "max_stars_repo_name": "nilavghosh/ProtoBuf_Net", "max_stars_repo_head_hexsha": "ee23634dbbb89cc2b91f8054d7b683e4405b964e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pset1 (1).ipynb", "max_issues_repo_name": "nilavghosh/ProtoBuf_Net", "max_issues_repo_head_hexsha": "ee23634dbbb89cc2b91f8054d7b683e4405b964e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pset1 (1).ipynb", "max_forks_repo_name": "nilavghosh/ProtoBuf_Net", "max_forks_repo_head_hexsha": "ee23634dbbb89cc2b91f8054d7b683e4405b964e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.458, "max_line_length": 841, "alphanum_fraction": 0.6229282363, "converted": true, "num_tokens": 4592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22815649691270323, "lm_q2_score": 0.08632348422559333, "lm_q1q2_score": 0.01969526376221037}}
{"text": "```python\n! pip install qeds\nimport pandas as pd\n%matplotlib inline\nimport qeds\nqeds.themes.mpl_style();\n```\n\n    Requirement already satisfied: qeds in c:\\users\\asus\\anaconda3\\lib\\site-packages (0.6.2)\n    Requirement already satisfied: statsmodels in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.10.1)\n    Requirement already satisfied: openpyxl in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (3.0.0)\n    Requirement already satisfied: scipy in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (1.3.1)\n    Requirement already satisfied: pyarrow in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.16.0)\n    Requirement already satisfied: numpy in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (1.16.5)\n    Requirement already satisfied: matplotlib in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (3.1.1)\n    Requirement already satisfied: quantecon in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.4.6)\n    Requirement already satisfied: seaborn in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.9.0)\n    Requirement already satisfied: pandas in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.25.1)\n    Requirement already satisfied: requests in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (2.22.0)\n    Requirement already satisfied: plotly in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (4.5.4)\n    Requirement already satisfied: pandas-datareader in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.8.1)\n    Requirement already satisfied: scikit-learn in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.21.3)\n    Requirement already satisfied: quandl in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (3.5.0)\n    Requirement already satisfied: patsy>=0.4.0 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from statsmodels->qeds) (0.5.1)\n    Requirement already satisfied: et-xmlfile in c:\\users\\asus\\anaconda3\\lib\\site-packages (from openpyxl->qeds) (1.0.1)\n    Requirement already satisfied: jdcal in c:\\users\\asus\\anaconda3\\lib\\site-packages (from openpyxl->qeds) (1.4.1)\n    Requirement already satisfied: six>=1.0.0 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pyarrow->qeds) (1.12.0)\n    Requirement already satisfied: cycler>=0.10 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (1.1.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (2.4.2)\n    Requirement already satisfied: python-dateutil>=2.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (2.8.0)\n    Requirement already satisfied: sympy in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quantecon->qeds) (1.4)\n    Requirement already satisfied: numba>=0.38 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quantecon->qeds) (0.45.1)\n    Requirement already satisfied: pytz>=2017.2 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pandas->qeds) (2019.3)\n    Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (2019.9.11)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (3.0.4)\n    Requirement already satisfied: idna<2.9,>=2.5 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (2.8)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (1.24.2)\n    Requirement already satisfied: retrying>=1.3.3 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from plotly->qeds) (1.3.3)\n    Requirement already satisfied: lxml in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pandas-datareader->qeds) (4.4.1)\n    Requirement already satisfied: joblib>=0.11 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from scikit-learn->qeds) (0.13.2)\n    Requirement already satisfied: inflection>=0.3.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quandl->qeds) (0.3.1)\n    Requirement already satisfied: more-itertools in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quandl->qeds) (7.2.0)\n    Requirement already satisfied: setuptools in c:\\users\\asus\\anaconda3\\lib\\site-packages (from kiwisolver>=1.0.1->matplotlib->qeds) (41.4.0)\n    Requirement already satisfied: mpmath>=0.19 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from sympy->quantecon->qeds) (1.1.0)\n    Requirement already satisfied: llvmlite>=0.29.0dev0 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from numba>=0.38->quantecon->qeds) (0.29.0)\n\n\n# Introduction - Exercises\n\n\n\n**For the purpose of these exercises, we create:**\n\n- **a Series which contains the US unemployment rate every other year starting in 1995**\n\n- **a DataFrame that contains the unemployment rate every other year by region of the US starting in 1995**\n\n\n```python\n#Series which contains the US unemployment rate every other year starting in 1995\nvalues = [5.6, 5.3, 4.3, 4.2, 5.8, 5.3, 4.6, 7.8, 9.1, 8., 5.7]\nyears = list(range(1995, 2017, 2))\n\nunemp = pd.Series(data=values, index=years, name=\"Unemployment\")\nunemp\n```\n\n\n\n\n    1995    5.6\n    1997    5.3\n    1999    4.3\n    2001    4.2\n    2003    5.8\n    2005    5.3\n    2007    4.6\n    2009    7.8\n    2011    9.1\n    2013    8.0\n    2015    5.7\n    Name: Unemployment, dtype: float64\n\n\n\n\n```python\n#DataFrame that contains the unemployment rate every other year by region of the US starting in 1995\ndata = {\n    \"NorthEast\": [5.9,  5.6,  4.4,  3.8,  5.8,  4.9,  4.3,  7.1,  8.3,  7.9,  5.7],\n    \"MidWest\": [4.5,  4.3,  3.6,  4. ,  5.7,  5.7,  4.9,  8.1,  8.7,  7.4,  5.1],\n    \"South\": [5.3,  5.2,  4.2,  4. ,  5.7,  5.2,  4.3,  7.6,  9.1,  7.4,  5.5],\n    \"West\": [6.6, 6., 5.2, 4.6, 6.5, 5.5, 4.5, 8.6, 10.7, 8.5, 6.1],\n    \"National\": [5.6, 5.3, 4.3, 4.2, 5.8, 5.3, 4.6, 7.8, 9.1, 8., 5.7]\n}\n\nunemp_region = pd.DataFrame(data, index=years)\nunemp_region\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>NorthEast</th>\n      <th>MidWest</th>\n      <th>South</th>\n      <th>West</th>\n      <th>National</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>1995</td>\n      <td>5.9</td>\n      <td>4.5</td>\n      <td>5.3</td>\n      <td>6.6</td>\n      <td>5.6</td>\n    </tr>\n    <tr>\n      <td>1997</td>\n      <td>5.6</td>\n      <td>4.3</td>\n      <td>5.2</td>\n      <td>6.0</td>\n      <td>5.3</td>\n    </tr>\n    <tr>\n      <td>1999</td>\n      <td>4.4</td>\n      <td>3.6</td>\n      <td>4.2</td>\n      <td>5.2</td>\n      <td>4.3</td>\n    </tr>\n    <tr>\n      <td>2001</td>\n      <td>3.8</td>\n      <td>4.0</td>\n      <td>4.0</td>\n      <td>4.6</td>\n      <td>4.2</td>\n    </tr>\n    <tr>\n      <td>2003</td>\n      <td>5.8</td>\n      <td>5.7</td>\n      <td>5.7</td>\n      <td>6.5</td>\n      <td>5.8</td>\n    </tr>\n    <tr>\n      <td>2005</td>\n      <td>4.9</td>\n      <td>5.7</td>\n      <td>5.2</td>\n      <td>5.5</td>\n      <td>5.3</td>\n    </tr>\n    <tr>\n      <td>2007</td>\n      <td>4.3</td>\n      <td>4.9</td>\n      <td>4.3</td>\n      <td>4.5</td>\n      <td>4.6</td>\n    </tr>\n    <tr>\n      <td>2009</td>\n      <td>7.1</td>\n      <td>8.1</td>\n      <td>7.6</td>\n      <td>8.6</td>\n      <td>7.8</td>\n    </tr>\n    <tr>\n      <td>2011</td>\n      <td>8.3</td>\n      <td>8.7</td>\n      <td>9.1</td>\n      <td>10.7</td>\n      <td>9.1</td>\n    </tr>\n    <tr>\n      <td>2013</td>\n      <td>7.9</td>\n      <td>7.4</td>\n      <td>7.4</td>\n      <td>8.5</td>\n      <td>8.0</td>\n    </tr>\n    <tr>\n      <td>2015</td>\n      <td>5.7</td>\n      <td>5.1</td>\n      <td>5.5</td>\n      <td>6.1</td>\n      <td>5.7</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Exercise 1\n\n\n1. **Display only the first 2 elements of the Series using the `.head` method.**\n\n\n```python\n# To display only the two first lines, we use the .head function with \"2\" as an argument.\nunemp.head(2)\n```\n\n\n\n\n    1995    5.6\n    1997    5.3\n    Name: Unemployment, dtype: float64\n\n\n\n2. **Using the `plot` method, make a bar plot.**  \n\n\n```python\n# The following makes a bar for each state and for each year.\nunemp.plot.bar()\n# Note that, by default, the index is taken as the x variable here.\n```\n\n3. **Use `.loc` to select the lowest/highest unemployment rate shown in the Series.**  \n\n\n```python\n#lowest temperature\nunemp.loc[unemp.idxmin()]\n```\n\n\n\n\n    4.2\n\n\n\n\n```python\n#highest temperature\nunemp.loc[unemp.idxmax()]\n```\n\n\n\n\n    9.1\n\n\n\n4. **Run the code `unemp.dtype` below. What does it give you? Where do you think it comes from?**\n\n\n```python\nunemp.dtype\n#we get that the dtype is float64\n#this tells us the type of data stored in the series \n```\n\n\n\n\n    dtype('float64')\n\n\n\n## Exercise 2\n\n**Now we create we create a DataFrame that contains the unemployment rate every other year by region of the US starting in 1995.**\n\n1. **Use introspection (or google-fu) to find a way to obtain a list with all of the column names in `unemp_region`.**\n\n\n```python\nlist(unemp_region)\n\n#to get the index, we can do:\n#list(unemp_region.index)\n```\n\n\n\n\n    ['NorthEast', 'MidWest', 'South', 'West', 'National']\n\n\n\n2. **Using the `plot` method, make a bar plot. What does it look like now?**  \n\n\n```python\n# Note that, by default, the index is taken as the x variable here.\nunemp_region.plot.bar()\n\n#We create a column entitled UnweightedMean to play around with other plotting characteristics\nunemp_region[\"UnweightedMean\"] = (unemp_region[\"NorthEast\"] +\n                                  unemp_region[\"MidWest\"] +\n                                  unemp_region[\"South\"] +\n                                  unemp_region[\"West\"])/4\n\n# The following makes a bar for each year, and this bar is the unweighted mean\nunemp_region.plot.bar(y='UnweightedMean')\n# The following makes a bar for each year, but plots the value \"Nation\"\nunemp_region.plot.bar(y='National')\n```\n\n3. **Use `.loc` to select the the unemployment data for the `NorthEast` and `West` for the years 1995, 2005, 2011, and 2015.**  \n\n\n```python\n# .loc \"accesses a group of rows and columns by label(s)...\" Arguments are labels\nunemp_region.loc[[1995, 2005, 2011, 2015], [\"NorthEast\", \"West\"]]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>NorthEast</th>\n      <th>West</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>1995</td>\n      <td>5.9</td>\n      <td>6.6</td>\n    </tr>\n    <tr>\n      <td>2005</td>\n      <td>4.9</td>\n      <td>5.5</td>\n    </tr>\n    <tr>\n      <td>2011</td>\n      <td>8.3</td>\n      <td>10.7</td>\n    </tr>\n    <tr>\n      <td>2015</td>\n      <td>5.7</td>\n      <td>6.1</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n4. **Run the code `unemp_region.dtypes` below. What does it give you? How does this compare with `unemp.dtype`?**\n\n\n```python\nunemp_region.dtypes\n```\n\n\n\n\n    NorthEast         float64\n    MidWest           float64\n    South             float64\n    West              float64\n    National          float64\n    UnweightedMean    float64\n    dtype: object\n\n\n", "meta": {"hexsha": "d4137da4139599737c331ed5642b33452d2bfc1f", "size": 76006, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Session_7/1_intro_exercises.ipynb", "max_stars_repo_name": "remi-sudo/Classes", "max_stars_repo_head_hexsha": "71497927ed4d54ddf6fd5abe2ddabb5966eb0304", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Session_7/1_intro_exercises.ipynb", "max_issues_repo_name": "remi-sudo/Classes", "max_issues_repo_head_hexsha": "71497927ed4d54ddf6fd5abe2ddabb5966eb0304", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Session_7/1_intro_exercises.ipynb", "max_forks_repo_name": "remi-sudo/Classes", "max_forks_repo_head_hexsha": "71497927ed4d54ddf6fd5abe2ddabb5966eb0304", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 111.2825768668, "max_line_length": 19364, "alphanum_fraction": 0.8288293029, "converted": true, "num_tokens": 4178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742625267332647, "lm_q2_score": 0.061875982263751246, "lm_q1q2_score": 0.01964106118046377}}
{"text": "## Initial setup\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```python\nimport tensorflow as tf\nprint(tf.__version__)\n# tensorflow version used is 2.8.0\nimport torch\nprint(torch.__version__)\n# torch version used is 1.10+cu111\n```\n\n    2.8.0\n    1.10.0+cu111\n\n\n\n```python\n!nvidia-smi\n```\n\n    Sun Mar 20 16:57:53 2022       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 460.32.03    Driver Version: 460.32.03    CUDA Version: 11.2     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   47C    P8    10W /  70W |      0MiB / 15109MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    |  No running processes found                                                 |\n    +-----------------------------------------------------------------------------+\n\n\n\n```python\n# Other imports\n! pip install tensorflow_addons\n! pip install tensorflow_io\n! pip install lightgbm\n! pip install xgboost\n! pip install catboost\n\nimport os\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import *\nfrom tensorflow import keras as tfkeras\nimport matplotlib.pyplot as plt\nfrom imutils import paths\nfrom tqdm import tqdm\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nimport tensorflow_datasets as tfds\nimport tensorflow_io as tfio\nimport tensorflow_hub as hub\nimport numpy as np\nimport cv2\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics.pairwise import cosine_similarity as cos\nfrom sympy.utilities.iterables import multiset_permutations\nfrom sklearn.metrics import accuracy_score, f1_score, confusion_matrix, mean_absolute_error, r2_score\nfrom sklearn.model_selection import *\nfrom IPython.display import Image, display\nfrom scipy import ndimage\n\nfrom xgboost import XGBRegressor as xgb\nfrom sklearn.ensemble import ExtraTreesRegressor as extratree\nfrom sklearn.ensemble import RandomForestRegressor as randomforest\nfrom sklearn.svm import NuSVR as svr\nfrom sklearn.gaussian_process import GaussianProcessRegressor as gpr\nfrom sklearn.ensemble import AdaBoostRegressor as ada\nfrom sklearn.tree import DecisionTreeRegressor as tree\nfrom sklearn.ensemble import GradientBoostingRegressor as gdb\nfrom sklearn.neural_network import MLPRegressor as mlp\nfrom sklearn.experimental import enable_hist_gradient_boosting\nfrom sklearn.ensemble import HistGradientBoostingRegressor as hgb\nfrom lightgbm import LGBMRegressor as lgb\nfrom catboost import CatBoostRegressor as cgb\nfrom sklearn.ensemble import StackingRegressor as stk\nfrom sklearn.linear_model import RidgeCV\nfrom sklearn.model_selection import cross_validate, cross_val_predict\nfrom sklearn.ensemble import VotingRegressor as vot\n\nimport zipfile\nimport concurrent.futures\n\n# Random seed fix\nrandom_seed = 42\ntf.random.set_seed(random_seed)\nnp.random.seed(random_seed)\n```\n\n    Collecting tensorflow_addons\n      Downloading tensorflow_addons-0.16.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.1 MB 4.7 MB/s \n    \u001b[?25hRequirement already satisfied: typeguard>=2.7 in /usr/local/lib/python3.7/dist-packages (from tensorflow_addons) (2.7.1)\n    Installing collected packages: tensorflow-addons\n    Successfully installed tensorflow-addons-0.16.1\n    Collecting tensorflow_io\n      Downloading tensorflow_io-0.24.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (23.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 23.4 MB 1.7 MB/s \n    \u001b[?25hRequirement already satisfied: tensorflow-io-gcs-filesystem==0.24.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow_io) (0.24.0)\n    Installing collected packages: tensorflow-io\n    Successfully installed tensorflow-io-0.24.0\n    Requirement already satisfied: lightgbm in /usr/local/lib/python3.7/dist-packages (2.2.3)\n    Requirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from lightgbm) (1.0.2)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from lightgbm) (1.21.5)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from lightgbm) (1.4.1)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->lightgbm) (3.1.0)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->lightgbm) (1.1.0)\n    Requirement already satisfied: xgboost in /usr/local/lib/python3.7/dist-packages (0.90)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from xgboost) (1.21.5)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from xgboost) (1.4.1)\n    Collecting catboost\n      Downloading catboost-1.0.4-cp37-none-manylinux1_x86_64.whl (76.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 76.1 MB 1.2 MB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.16.0 in /usr/local/lib/python3.7/dist-packages (from catboost) (1.21.5)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from catboost) (3.2.2)\n    Requirement already satisfied: plotly in /usr/local/lib/python3.7/dist-packages (from catboost) (5.5.0)\n    Requirement already satisfied: pandas>=0.24.0 in /usr/local/lib/python3.7/dist-packages (from catboost) (1.3.5)\n    Requirement already satisfied: graphviz in /usr/local/lib/python3.7/dist-packages (from catboost) (0.10.1)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from catboost) (1.15.0)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from catboost) (1.4.1)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24.0->catboost) (2.8.2)\n    Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24.0->catboost) (2018.9)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->catboost) (3.0.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->catboost) (1.4.0)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->catboost) (0.11.0)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from kiwisolver>=1.0.1->matplotlib->catboost) (3.10.0.2)\n    Requirement already satisfied: tenacity>=6.2.0 in /usr/local/lib/python3.7/dist-packages (from plotly->catboost) (8.0.1)\n    Installing collected packages: catboost\n    Successfully installed catboost-1.0.4\n\n\n    /usr/local/lib/python3.7/dist-packages/sklearn/experimental/enable_hist_gradient_boosting.py:17: UserWarning: Since version 1.0, it is not needed to import enable_hist_gradient_boosting anymore. HistGradientBoostingClassifier and HistGradientBoostingRegressor are now stable and can be normally imported from sklearn.ensemble.\n      \"Since version 1.0, \"\n\n\n## Dataset gathering and preparation\n\n\n```python\n%cd /content/drive/MyDrive/ML\\ course\\ 2022_Team\\ BNL\n```\n\n    /content/drive/MyDrive/ML course 2022_Team BNL\n\n\n\n```python\nedge_percentage_threshold = np.array([0.00, 0.01, 0.02, 0.05, 0.10])\ncap = np.array([20, 50])\nvalid_images_size = np.array([[2653, 2231, 1811, 1013, 510], [5878, 4943, 3995, 2235, 1186]])\ntraining_data_size = np.array([10, 20, 50, 80, 100, 150, 200])\ndata_percentage_legend = np.arange(len(training_data_size))\n\ncolor_method = ['C3', 'C1', 'C2', 'C3', 'C4']\n# boxplot and violin plot parameters for better aesthetics\nbox_width = 0.15\nshift = 0.3\n# plt.rcParams['axes.prop_cycle'] = plt.cycler(color=plt.cm.tab10.colors)\nplt.rcParams['axes.prop_cycle'] = plt.cycler(color=plt.cm.tab10.colors[3:4] + plt.cm.tab10.colors[0:3] + plt.cm.tab10.colors[4:5])    # avoid having both green and red in the same boxplot format\n\nholder = {}\nfor i in range(len(cap)):\n  for j in range(len(edge_percentage_threshold)):\n    tempo = np.load('performance_log/level1/cap%i_cutoff%1.2f_valid%i.npz' %(cap[i], edge_percentage_threshold[j], valid_images_size[i, j]), allow_pickle=True)\n    holder.update({i * 10 + j: tempo})\n\n\nfor i in range(len(cap)):\n  for j in range(len(edge_percentage_threshold)):\n# plot R_squared.\n    fig = plt.figure(figsize=(12, 5))\n    ax = fig.add_subplot(111)\n\n    ax.set_ylim(0.2, 1.0)\n\n    for k in range(2, len(training_data_size)):\n      box0 = plt.boxplot([np.reshape(holder[i * 10 + j]['ridge'][k, :, 0], -1) for k in range(2, len(training_data_size))], widths=box_width, positions=np.arange(3, 8) - shift * 1.2, notch=True, patch_artist=True, boxprops=dict(facecolor=color_method[0]), medianprops=dict(color=\"black\",linewidth=1.5))\n      box1 = plt.boxplot([np.reshape(holder[i * 10 + j]['rf'][k, :, 0], -1) for k in range(2, len(training_data_size))], widths=box_width, positions=np.arange(3, 8) , notch=True, patch_artist=True, boxprops=dict(facecolor=color_method[1]), medianprops=dict(color=\"black\",linewidth=1.5))\n      box2 = plt.boxplot([np.reshape(holder[i * 10 + j]['mlp'][k, :, 0], -1) for k in range(2, len(training_data_size))], widths=box_width, positions=np.arange(3, 8) + shift * 1.2, notch=True, patch_artist=True, boxprops=dict(facecolor=color_method[2]), medianprops=dict(color=\"black\",linewidth=1.5))\n\n    for p in range(6):\n      ax.vlines(1.5 + p, 0.2, 1.0, colors='grey')\n    ax.set_xticks((data_percentage_legend + 1))\n    ax.set_xticklabels((training_data_size).astype(str))\n    ax.set_xlim(2.5, 7.5)\n    ax.tick_params(labelsize=16, length=4)\n    ax.set_xlabel(r'number of training images', fontsize=20, fontweight='bold')\n    ax.set_ylabel(r'$R^{2}$', fontsize=20, fontweight='bold')\n    ax.legend([box0[\"boxes\"][0], box1[\"boxes\"][0], box2[\"boxes\"][0]], ['ridge-linear', 'random_forest', 'multi-layer perceptron'], fontsize=16, loc='lower right', framealpha=1)\n\n# plot mean average error\n    fig = plt.figure(figsize=(12, 5))\n    ax = fig.add_subplot(111)\n\n    if i == 0:\n      ax.set_ylim(0, 5)\n    else:\n      ax.set_ylim(0, 10)\n\n    for k in range(2, len(training_data_size)):\n      box0 = plt.boxplot([np.reshape(holder[i * 10 + j]['ridge'][k, :, 1], -1) for k in range(2, len(training_data_size))], widths=box_width, positions=np.arange(3, 8) - shift * 1.2, notch=True, patch_artist=True, boxprops=dict(facecolor=color_method[0]), medianprops=dict(color=\"black\",linewidth=1.5))\n      box1 = plt.boxplot([np.reshape(holder[i * 10 + j]['rf'][k, :, 1], -1) for k in range(2, len(training_data_size))], widths=box_width, positions=np.arange(3, 8) , notch=True, patch_artist=True, boxprops=dict(facecolor=color_method[1]), medianprops=dict(color=\"black\",linewidth=1.5))\n      box2 = plt.boxplot([np.reshape(holder[i * 10 + j]['mlp'][k, :, 1], -1) for k in range(2, len(training_data_size))], widths=box_width, positions=np.arange(3, 8) + shift * 1.2, notch=True, patch_artist=True, boxprops=dict(facecolor=color_method[2]), medianprops=dict(color=\"black\",linewidth=1.5))\n\n    for p in range(6):\n      if i == 0:\n        ax.vlines(1.5 + p, 0, 5.0, colors='grey')\n      if i == 1:\n        ax.vlines(1.5 + p, 0, 10.0, colors='grey')\n    ax.set_xticks((data_percentage_legend + 1))\n    ax.set_xticklabels((training_data_size).astype(str))\n    ax.set_xlim(2.5, 7.5)\n    ax.tick_params(labelsize=16, length=4)\n    ax.set_xlabel(r'number of training images', fontsize=20, fontweight='bold')\n    ax.set_ylabel(r'mean average error [$\\mu m$]', fontsize=20, fontweight='bold')\n    # ax.legend([box0[\"boxes\"][0], box1[\"boxes\"][0], box2[\"boxes\"][0]], ['ridge-linear', 'random_forest', 'multi-layer perceptron'], fontsize=16, loc='lower right', framealpha=1)\n\n\n```\n\n\n```python\nprint(np.average(holder[i * 10 + j]['rf'], axis=1))\nprint(np.std(holder[i * 10 + j]['rf'], axis=1))\n```\n\n    [[-0.21639083  7.47460511]\n     [ 0.69821329  5.12855177]\n     [ 0.89179968  3.47963082]\n     [ 0.9233557   2.90292342]\n     [ 0.93089882  2.66149753]\n     [ 0.94185578  2.43684   ]\n     [ 0.9463053   2.31654862]]\n    [[0.74898413 1.07219296]\n     [0.12144482 0.70805477]\n     [0.03172447 0.44216891]\n     [0.0258458  0.40550791]\n     [0.0282795  0.39263678]\n     [0.02288682 0.32602473]\n     [0.02268225 0.32143601]]\n\n", "meta": {"hexsha": "f15ca267067c221a00c94f1e4f3ab7ac68f0e54e", "size": 659573, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/archive/performance_plots_level1.ipynb", "max_stars_repo_name": "evanmacbride/microscope-autofocus", "max_stars_repo_head_hexsha": "5e88dc8b498cc96c3eee0503111fdf67ef867b54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/archive/performance_plots_level1.ipynb", "max_issues_repo_name": "evanmacbride/microscope-autofocus", "max_issues_repo_head_hexsha": "5e88dc8b498cc96c3eee0503111fdf67ef867b54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/archive/performance_plots_level1.ipynb", "max_forks_repo_name": "evanmacbride/microscope-autofocus", "max_forks_repo_head_hexsha": "5e88dc8b498cc96c3eee0503111fdf67ef867b54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 659573.0, "max_line_length": 659573, "alphanum_fraction": 0.9561064507, "converted": true, "num_tokens": 3828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658975016245987, "lm_q2_score": 0.05340332753999997, "lm_q1q2_score": 0.019577112500732602}}
{"text": "# EKE preprocessing\n\nThis notebook shows how to generate the EKE_timeseries.nc file\n\n\n```python\n# Import libraries\nimport xarray as xr\nimport cmocean as cm\nimport cartopy.crs as ccrs\n\nimport pylab as plt\nimport numpy as np\n# Inline plotting\n%matplotlib inline\n```\n\n\n```python\nfrom dask.distributed import Client\n```\n\n\n```python\nfrom utils import area,ccrs_land,add_patches\nimport datetime\n```\n\n\n```python\nc = Client()\nc\n```\n\n\n\n\n<table style=\"border: 2px solid white;\">\n<tr>\n<td style=\"vertical-align: top; border: 0px solid white\">\n<h3 style=\"text-align: left;\">Client</h3>\n<ul style=\"text-align: left; list-style: none; margin: 0; padding: 0;\">\n  <li><b>Scheduler: </b>tcp://127.0.0.1:33109</li>\n  <li><b>Dashboard: </b><a href='/proxy/8787/status' target='_blank'>/proxy/8787/status</a></li>\n</ul>\n</td>\n<td style=\"vertical-align: top; border: 0px solid white\">\n<h3 style=\"text-align: left;\">Cluster</h3>\n<ul style=\"text-align: left; list-style:none; margin: 0; padding: 0;\">\n  <li><b>Workers: </b>6</li>\n  <li><b>Cores: </b>36</li>\n  <li><b>Memory: </b>154.62 GB</li>\n</ul>\n</td>\n</tr>\n</table>\n\n\n\n\n```python\nfiles = '/g/data/ua8/CMEMS_SeaLevel/v2019/*/*.nc'\n# files='path2AVISO+/*.nc'\n```\n\n\n```python\ndataset_AVISO = xr.open_mfdataset(files,parallel=True)\n```\n\n\n```python\ndataset_AVISO\n```\n\n\n\n\n<div><svg style=\"position: absolute; width: 0; height: 0; overflow: hidden\">\n<defs>\n<symbol id=\"icon-database\" viewBox=\"0 0 32 32\">\n<path d=\"M16 0c-8.837 0-16 2.239-16 5v4c0 2.761 7.163 5 16 5s16-2.239 16-5v-4c0-2.761-7.163-5-16-5z\"></path>\n<path d=\"M16 17c-8.837 0-16-2.239-16-5v6c0 2.761 7.163 5 16 5s16-2.239 16-5v-6c0 2.761-7.163 5-16 5z\"></path>\n<path d=\"M16 26c-8.837 0-16-2.239-16-5v6c0 2.761 7.163 5 16 5s16-2.239 16-5v-6c0 2.761-7.163 5-16 5z\"></path>\n</symbol>\n<symbol id=\"icon-file-text2\" viewBox=\"0 0 32 32\">\n<path d=\"M28.681 7.159c-0.694-0.947-1.662-2.053-2.724-3.116s-2.169-2.030-3.116-2.724c-1.612-1.182-2.393-1.319-2.841-1.319h-15.5c-1.378 0-2.5 1.121-2.5 2.5v27c0 1.378 1.122 2.5 2.5 2.5h23c1.378 0 2.5-1.122 2.5-2.5v-19.5c0-0.448-0.137-1.23-1.319-2.841zM24.543 5.457c0.959 0.959 1.712 1.825 2.268 2.543h-4.811v-4.811c0.718 0.556 1.584 1.309 2.543 2.268zM28 29.5c0 0.271-0.229 0.5-0.5 0.5h-23c-0.271 0-0.5-0.229-0.5-0.5v-27c0-0.271 0.229-0.5 0.5-0.5 0 0 15.499-0 15.5 0v7c0 0.552 0.448 1 1 1h7v19.5z\"></path>\n<path d=\"M23 26h-14c-0.552 0-1-0.448-1-1s0.448-1 1-1h14c0.552 0 1 0.448 1 1s-0.448 1-1 1z\"></path>\n<path d=\"M23 22h-14c-0.552 0-1-0.448-1-1s0.448-1 1-1h14c0.552 0 1 0.448 1 1s-0.448 1-1 1z\"></path>\n<path d=\"M23 18h-14c-0.552 0-1-0.448-1-1s0.448-1 1-1h14c0.552 0 1 0.448 1 1s-0.448 1-1 1z\"></path>\n</symbol>\n</defs>\n</svg>\n<style>/* CSS stylesheet for displaying xarray objects in jupyterlab.\n *\n */\n\n:root {\n  --xr-font-color0: var(--jp-content-font-color0, rgba(0, 0, 0, 1));\n  --xr-font-color2: var(--jp-content-font-color2, rgba(0, 0, 0, 0.54));\n  --xr-font-color3: var(--jp-content-font-color3, rgba(0, 0, 0, 0.38));\n  --xr-border-color: var(--jp-border-color2, #e0e0e0);\n  --xr-disabled-color: var(--jp-layout-color3, #bdbdbd);\n  --xr-background-color: var(--jp-layout-color0, white);\n  --xr-background-color-row-even: var(--jp-layout-color1, white);\n  --xr-background-color-row-odd: var(--jp-layout-color2, #eeeeee);\n}\n\nhtml[theme=dark],\nbody.vscode-dark {\n  --xr-font-color0: rgba(255, 255, 255, 1);\n  --xr-font-color2: rgba(255, 255, 255, 0.54);\n  --xr-font-color3: rgba(255, 255, 255, 0.38);\n  --xr-border-color: #1F1F1F;\n  --xr-disabled-color: #515151;\n  --xr-background-color: #111111;\n  --xr-background-color-row-even: #111111;\n  --xr-background-color-row-odd: #313131;\n}\n\n.xr-wrap {\n  display: block;\n  min-width: 300px;\n  max-width: 700px;\n}\n\n.xr-text-repr-fallback {\n  /* fallback to plain text repr when CSS is not injected (untrusted notebook) */\n  display: none;\n}\n\n.xr-header {\n  padding-top: 6px;\n  padding-bottom: 6px;\n  margin-bottom: 4px;\n  border-bottom: solid 1px var(--xr-border-color);\n}\n\n.xr-header > div,\n.xr-header > ul {\n  display: inline;\n  margin-top: 0;\n  margin-bottom: 0;\n}\n\n.xr-obj-type,\n.xr-array-name {\n  margin-left: 2px;\n  margin-right: 10px;\n}\n\n.xr-obj-type {\n  color: var(--xr-font-color2);\n}\n\n.xr-sections {\n  padding-left: 0 !important;\n  display: grid;\n  grid-template-columns: 150px auto auto 1fr 20px 20px;\n}\n\n.xr-section-item {\n  display: contents;\n}\n\n.xr-section-item input {\n  display: none;\n}\n\n.xr-section-item input + label {\n  color: var(--xr-disabled-color);\n}\n\n.xr-section-item input:enabled + label {\n  cursor: pointer;\n  color: var(--xr-font-color2);\n}\n\n.xr-section-item input:enabled + label:hover {\n  color: var(--xr-font-color0);\n}\n\n.xr-section-summary {\n  grid-column: 1;\n  color: var(--xr-font-color2);\n  font-weight: 500;\n}\n\n.xr-section-summary > span {\n  display: inline-block;\n  padding-left: 0.5em;\n}\n\n.xr-section-summary-in:disabled + label {\n  color: var(--xr-font-color2);\n}\n\n.xr-section-summary-in + label:before {\n  display: inline-block;\n  content: '\u25ba';\n  font-size: 11px;\n  width: 15px;\n  text-align: center;\n}\n\n.xr-section-summary-in:disabled + label:before {\n  color: var(--xr-disabled-color);\n}\n\n.xr-section-summary-in:checked + label:before {\n  content: '\u25bc';\n}\n\n.xr-section-summary-in:checked + label > span {\n  display: none;\n}\n\n.xr-section-summary,\n.xr-section-inline-details {\n  padding-top: 4px;\n  padding-bottom: 4px;\n}\n\n.xr-section-inline-details {\n  grid-column: 2 / -1;\n}\n\n.xr-section-details {\n  display: none;\n  grid-column: 1 / -1;\n  margin-bottom: 5px;\n}\n\n.xr-section-summary-in:checked ~ .xr-section-details {\n  display: contents;\n}\n\n.xr-array-wrap {\n  grid-column: 1 / -1;\n  display: grid;\n  grid-template-columns: 20px auto;\n}\n\n.xr-array-wrap > label {\n  grid-column: 1;\n  vertical-align: top;\n}\n\n.xr-preview {\n  color: var(--xr-font-color3);\n}\n\n.xr-array-preview,\n.xr-array-data {\n  padding: 0 5px !important;\n  grid-column: 2;\n}\n\n.xr-array-data,\n.xr-array-in:checked ~ .xr-array-preview {\n  display: none;\n}\n\n.xr-array-in:checked ~ .xr-array-data,\n.xr-array-preview {\n  display: inline-block;\n}\n\n.xr-dim-list {\n  display: inline-block !important;\n  list-style: none;\n  padding: 0 !important;\n  margin: 0;\n}\n\n.xr-dim-list li {\n  display: inline-block;\n  padding: 0;\n  margin: 0;\n}\n\n.xr-dim-list:before {\n  content: '(';\n}\n\n.xr-dim-list:after {\n  content: ')';\n}\n\n.xr-dim-list li:not(:last-child):after {\n  content: ',';\n  padding-right: 5px;\n}\n\n.xr-has-index {\n  font-weight: bold;\n}\n\n.xr-var-list,\n.xr-var-item {\n  display: contents;\n}\n\n.xr-var-item > div,\n.xr-var-item label,\n.xr-var-item > .xr-var-name span {\n  background-color: var(--xr-background-color-row-even);\n  margin-bottom: 0;\n}\n\n.xr-var-item > .xr-var-name:hover span {\n  padding-right: 5px;\n}\n\n.xr-var-list > li:nth-child(odd) > div,\n.xr-var-list > li:nth-child(odd) > label,\n.xr-var-list > li:nth-child(odd) > .xr-var-name span {\n  background-color: var(--xr-background-color-row-odd);\n}\n\n.xr-var-name {\n  grid-column: 1;\n}\n\n.xr-var-dims {\n  grid-column: 2;\n}\n\n.xr-var-dtype {\n  grid-column: 3;\n  text-align: right;\n  color: var(--xr-font-color2);\n}\n\n.xr-var-preview {\n  grid-column: 4;\n}\n\n.xr-var-name,\n.xr-var-dims,\n.xr-var-dtype,\n.xr-preview,\n.xr-attrs dt {\n  white-space: nowrap;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  padding-right: 10px;\n}\n\n.xr-var-name:hover,\n.xr-var-dims:hover,\n.xr-var-dtype:hover,\n.xr-attrs dt:hover {\n  overflow: visible;\n  width: auto;\n  z-index: 1;\n}\n\n.xr-var-attrs,\n.xr-var-data {\n  display: none;\n  background-color: var(--xr-background-color) !important;\n  padding-bottom: 5px !important;\n}\n\n.xr-var-attrs-in:checked ~ .xr-var-attrs,\n.xr-var-data-in:checked ~ .xr-var-data {\n  display: block;\n}\n\n.xr-var-data > table {\n  float: right;\n}\n\n.xr-var-name span,\n.xr-var-data,\n.xr-attrs {\n  padding-left: 25px !important;\n}\n\n.xr-attrs,\n.xr-var-attrs,\n.xr-var-data {\n  grid-column: 1 / -1;\n}\n\ndl.xr-attrs {\n  padding: 0;\n  margin: 0;\n  display: grid;\n  grid-template-columns: 125px auto;\n}\n\n.xr-attrs dt,\n.xr-attrs dd {\n  padding: 0;\n  margin: 0;\n  float: left;\n  padding-right: 10px;\n  width: auto;\n}\n\n.xr-attrs dt {\n  font-weight: normal;\n  grid-column: 1;\n}\n\n.xr-attrs dt:hover span {\n  display: inline-block;\n  background: var(--xr-background-color);\n  padding-right: 10px;\n}\n\n.xr-attrs dd {\n  grid-column: 2;\n  white-space: pre-wrap;\n  word-break: break-all;\n}\n\n.xr-icon-database,\n.xr-icon-file-text2 {\n  display: inline-block;\n  vertical-align: middle;\n  width: 1em;\n  height: 1.5em !important;\n  stroke-width: 0;\n  stroke: currentColor;\n  fill: currentColor;\n}\n</style><pre class='xr-text-repr-fallback'>&lt;xarray.Dataset&gt;\nDimensions:    (latitude: 720, longitude: 1440, nv: 2, time: 9928)\nCoordinates:\n  * time       (time) datetime64[ns] 1993-01-01 1993-01-02 ... 2020-03-07\n  * latitude   (latitude) float32 -89.88 -89.62 -89.38 ... 89.38 89.62 89.88\n  * longitude  (longitude) float32 0.125 0.375 0.625 0.875 ... 359.4 359.6 359.9\n  * nv         (nv) int32 0 1\nData variables:\n    crs        (time) int32 -2147483647 -2147483647 ... -2147483647 -2147483647\n    lat_bnds   (time, latitude, nv) float32 dask.array&lt;chunksize=(1, 720, 2), meta=np.ndarray&gt;\n    lon_bnds   (time, longitude, nv) float32 dask.array&lt;chunksize=(1, 1440, 2), meta=np.ndarray&gt;\n    err        (time, latitude, longitude) float64 dask.array&lt;chunksize=(1, 720, 1440), meta=np.ndarray&gt;\n    adt        (time, latitude, longitude) float64 dask.array&lt;chunksize=(1, 720, 1440), meta=np.ndarray&gt;\n    ugos       (time, latitude, longitude) float64 dask.array&lt;chunksize=(1, 720, 1440), meta=np.ndarray&gt;\n    vgos       (time, latitude, longitude) float64 dask.array&lt;chunksize=(1, 720, 1440), meta=np.ndarray&gt;\n    sla        (time, latitude, longitude) float64 dask.array&lt;chunksize=(1, 720, 1440), meta=np.ndarray&gt;\n    ugosa      (time, latitude, longitude) float64 dask.array&lt;chunksize=(1, 720, 1440), meta=np.ndarray&gt;\n    vgosa      (time, latitude, longitude) float64 dask.array&lt;chunksize=(1, 720, 1440), meta=np.ndarray&gt;\nAttributes:\n    Conventions:                     CF-1.6\n    Metadata_Conventions:            Unidata Dataset Discovery v1.0\n    cdm_data_type:                   Grid\n    comment:                         Sea Surface Height measured by Altimetry...\n    contact:                         servicedesk.cmems@mercator-ocean.eu\n    creator_email:                   servicedesk.cmems@mercator-ocean.eu\n    creator_name:                    CMEMS - Sea Level Thematic Assembly Center\n    creator_url:                     http://marine.copernicus.eu\n    date_created:                    2019-01-17T16:58:50Z\n    date_issued:                     2019-01-17T16:58:50Z\n    date_modified:                   2019-01-17T16:58:50Z\n    geospatial_lat_max:              89.875\n    geospatial_lat_min:              -89.875\n    geospatial_lat_resolution:       0.25\n    geospatial_lat_units:            degrees_north\n    geospatial_lon_max:              359.875\n    geospatial_lon_min:              0.125\n    geospatial_lon_resolution:       0.25\n    geospatial_lon_units:            degrees_east\n    geospatial_vertical_max:         0.0\n    geospatial_vertical_min:         0.0\n    geospatial_vertical_positive:    down\n    geospatial_vertical_resolution:  point\n    geospatial_vertical_units:       m\n    history:                         2019-01-17 16:58:51Z: Creation\n    institution:                     CLS, CNES\n    keywords:                        Oceans &gt; Ocean Topography &gt; Sea Surface ...\n    keywords_vocabulary:             NetCDF COARDS Climate and Forecast Stand...\n    license:                         http://marine.copernicus.eu/web/27-servi...\n    platform:                        ERS-1, Topex/Poseidon,\n    processing_level:                L4\n    product_version:                 2019\n    project:                         COPERNICUS MARINE ENVIRONMENT MONITORING...\n    references:                      http://marine.copernicus.eu\n    software_version:                6.2_DUACS_DT2018_baseline\n    source:                          Altimetry measurements\n    ssalto_duacs_comment:            The reference mission used for the altim...\n    standard_name_vocabulary:        NetCDF Climate and Forecast (CF) Metadat...\n    summary:                         SSALTO/DUACS Delayed-Time Level-4 sea su...\n    time_coverage_duration:          P1D\n    time_coverage_end:               1993-01-01T00:00:00Z\n    time_coverage_resolution:        P1D\n    time_coverage_start:             1993-01-01T00:00:00Z\n    title:                           DT merged all satellites Global Ocean Gr...</pre><div class='xr-wrap' hidden><div class='xr-header'><div class='xr-obj-type'>xarray.Dataset</div></div><ul class='xr-sections'><li class='xr-section-item'><input id='section-ab8a01dd-17dd-4849-8603-6bf38a4296fd' class='xr-section-summary-in' type='checkbox' disabled ><label for='section-ab8a01dd-17dd-4849-8603-6bf38a4296fd' class='xr-section-summary'  title='Expand/collapse section'>Dimensions:</label><div class='xr-section-inline-details'><ul class='xr-dim-list'><li><span class='xr-has-index'>latitude</span>: 720</li><li><span class='xr-has-index'>longitude</span>: 1440</li><li><span class='xr-has-index'>nv</span>: 2</li><li><span class='xr-has-index'>time</span>: 9928</li></ul></div><div class='xr-section-details'></div></li><li class='xr-section-item'><input id='section-f3ccc550-b1cd-4228-a761-5937245727f7' class='xr-section-summary-in' type='checkbox'  checked><label for='section-f3ccc550-b1cd-4228-a761-5937245727f7' class='xr-section-summary' >Coordinates: <span>(4)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><ul class='xr-var-list'><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>time</span></div><div class='xr-var-dims'>(time)</div><div class='xr-var-dtype'>datetime64[ns]</div><div class='xr-var-preview xr-preview'>1993-01-01 ... 2020-03-07</div><input id='attrs-fbe163d9-8ec1-4167-a75d-05c0830fb0f9' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-fbe163d9-8ec1-4167-a75d-05c0830fb0f9' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-118feed7-739f-461c-a961-9e4c72ab651d' class='xr-var-data-in' type='checkbox'><label for='data-118feed7-739f-461c-a961-9e4c72ab651d' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>axis :</span></dt><dd>T</dd><dt><span>long_name :</span></dt><dd>Time</dd><dt><span>standard_name :</span></dt><dd>time</dd></dl></div><div class='xr-var-data'><pre>array([&#x27;1993-01-01T00:00:00.000000000&#x27;, &#x27;1993-01-02T00:00:00.000000000&#x27;,\n       &#x27;1993-01-03T00:00:00.000000000&#x27;, ..., &#x27;2020-03-05T00:00:00.000000000&#x27;,\n       &#x27;2020-03-06T00:00:00.000000000&#x27;, &#x27;2020-03-07T00:00:00.000000000&#x27;],\n      dtype=&#x27;datetime64[ns]&#x27;)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>latitude</span></div><div class='xr-var-dims'>(latitude)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>-89.88 -89.62 ... 89.62 89.88</div><input id='attrs-9ad269cd-8d48-41fd-8c15-cb63480085e2' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-9ad269cd-8d48-41fd-8c15-cb63480085e2' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-c2e3c773-0125-4ca7-8632-501758a55e51' class='xr-var-data-in' type='checkbox'><label for='data-c2e3c773-0125-4ca7-8632-501758a55e51' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>axis :</span></dt><dd>Y</dd><dt><span>bounds :</span></dt><dd>lat_bnds</dd><dt><span>long_name :</span></dt><dd>Latitude</dd><dt><span>standard_name :</span></dt><dd>latitude</dd><dt><span>units :</span></dt><dd>degrees_north</dd><dt><span>valid_max :</span></dt><dd>89.875</dd><dt><span>valid_min :</span></dt><dd>-89.875</dd></dl></div><div class='xr-var-data'><pre>array([-89.875, -89.625, -89.375, ...,  89.375,  89.625,  89.875],\n      dtype=float32)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>longitude</span></div><div class='xr-var-dims'>(longitude)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>0.125 0.375 0.625 ... 359.6 359.9</div><input id='attrs-794c88ca-87f6-4aaf-a030-3f396ac652fa' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-794c88ca-87f6-4aaf-a030-3f396ac652fa' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-15facb94-17ef-4bfd-a8ff-2dfe9cd89126' class='xr-var-data-in' type='checkbox'><label for='data-15facb94-17ef-4bfd-a8ff-2dfe9cd89126' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>axis :</span></dt><dd>X</dd><dt><span>bounds :</span></dt><dd>lon_bnds</dd><dt><span>long_name :</span></dt><dd>Longitude</dd><dt><span>standard_name :</span></dt><dd>longitude</dd><dt><span>units :</span></dt><dd>degrees_east</dd><dt><span>valid_max :</span></dt><dd>359.875</dd><dt><span>valid_min :</span></dt><dd>0.125</dd></dl></div><div class='xr-var-data'><pre>array([1.25000e-01, 3.75000e-01, 6.25000e-01, ..., 3.59375e+02, 3.59625e+02,\n       3.59875e+02], dtype=float32)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>nv</span></div><div class='xr-var-dims'>(nv)</div><div class='xr-var-dtype'>int32</div><div class='xr-var-preview xr-preview'>0 1</div><input id='attrs-3a15403f-7f00-4c2f-ae09-a03e08446552' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-3a15403f-7f00-4c2f-ae09-a03e08446552' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-1b2d3355-cae1-4cb4-beb8-3a65afcca461' class='xr-var-data-in' type='checkbox'><label for='data-1b2d3355-cae1-4cb4-beb8-3a65afcca461' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>comment :</span></dt><dd>Vertex</dd><dt><span>units :</span></dt><dd>1</dd></dl></div><div class='xr-var-data'><pre>array([0, 1], dtype=int32)</pre></div></li></ul></div></li><li class='xr-section-item'><input id='section-e6b875b9-ed38-489f-bd73-14f85725568d' class='xr-section-summary-in' type='checkbox'  checked><label for='section-e6b875b9-ed38-489f-bd73-14f85725568d' class='xr-section-summary' >Data variables: <span>(10)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><ul class='xr-var-list'><li class='xr-var-item'><div class='xr-var-name'><span>crs</span></div><div class='xr-var-dims'>(time)</div><div class='xr-var-dtype'>int32</div><div class='xr-var-preview xr-preview'>-2147483647 ... -2147483647</div><input id='attrs-349eb9c8-b3e9-4603-9e90-4798358e4ef1' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-349eb9c8-b3e9-4603-9e90-4798358e4ef1' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-ccc3e6e2-3edc-41f3-a963-7a3bfeebe014' class='xr-var-data-in' type='checkbox'><label for='data-ccc3e6e2-3edc-41f3-a963-7a3bfeebe014' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>comment :</span></dt><dd>This is a container variable that describes the grid_mapping used by the data in this file. This variable does not contain any data; only information about the geographic coordinate system.</dd><dt><span>grid_mapping_name :</span></dt><dd>latitude_longitude</dd><dt><span>inverse_flattening :</span></dt><dd>298.257</dd><dt><span>semi_major_axis :</span></dt><dd>6378136.3</dd></dl></div><div class='xr-var-data'><pre>array([-2147483647, -2147483647, -2147483647, ..., -2147483647,\n       -2147483647, -2147483647], dtype=int32)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>lat_bnds</span></div><div class='xr-var-dims'>(time, latitude, nv)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>dask.array&lt;chunksize=(1, 720, 2), meta=np.ndarray&gt;</div><input id='attrs-9cfa57ec-e3fc-4519-8209-00696a13110d' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-9cfa57ec-e3fc-4519-8209-00696a13110d' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-77368d0e-6912-4872-9cf6-cba739214359' class='xr-var-data-in' type='checkbox'><label for='data-77368d0e-6912-4872-9cf6-cba739214359' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>comment :</span></dt><dd>latitude values at the north and south bounds of each pixel.</dd><dt><span>units :</span></dt><dd>degrees_north</dd></dl></div><div class='xr-var-data'><table>\n<tr>\n<td>\n<table>\n  <thead>\n    <tr><td> </td><th> Array </th><th> Chunk </th></tr>\n  </thead>\n  <tbody>\n    <tr><th> Bytes </th><td> 57.19 MB </td> <td> 5.76 kB </td></tr>\n    <tr><th> Shape </th><td> (9928, 720, 2) </td> <td> (1, 720, 2) </td></tr>\n    <tr><th> Count </th><td> 39712 Tasks </td><td> 9928 Chunks </td></tr>\n    <tr><th> Type </th><td> float32 </td><td> numpy.ndarray </td></tr>\n  </tbody>\n</table>\n</td>\n<td>\n<svg width=\"156\" height=\"157\" style=\"stroke:rgb(0,0,0);stroke-width:1\" >\n\n  <!-- Horizontal lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"80\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"10\" y1=\"36\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"10\" y2=\"36\" style=\"stroke-width:2\" />\n  <line x1=\"13\" y1=\"3\" x2=\"13\" y2=\"40\" />\n  <line x1=\"17\" y1=\"7\" x2=\"17\" y2=\"44\" />\n  <line x1=\"21\" y1=\"11\" x2=\"21\" y2=\"47\" />\n  <line x1=\"24\" y1=\"14\" x2=\"24\" y2=\"51\" />\n  <line x1=\"28\" y1=\"18\" x2=\"28\" y2=\"55\" />\n  <line x1=\"32\" y1=\"22\" x2=\"32\" y2=\"59\" />\n  <line x1=\"36\" y1=\"26\" x2=\"36\" y2=\"62\" />\n  <line x1=\"39\" y1=\"29\" x2=\"39\" y2=\"66\" />\n  <line x1=\"43\" y1=\"33\" x2=\"43\" y2=\"70\" />\n  <line x1=\"47\" y1=\"37\" x2=\"47\" y2=\"73\" />\n  <line x1=\"50\" y1=\"40\" x2=\"50\" y2=\"77\" />\n  <line x1=\"54\" y1=\"44\" x2=\"54\" y2=\"81\" />\n  <line x1=\"58\" y1=\"48\" x2=\"58\" y2=\"85\" />\n  <line x1=\"62\" y1=\"52\" x2=\"62\" y2=\"88\" />\n  <line x1=\"65\" y1=\"55\" x2=\"65\" y2=\"92\" />\n  <line x1=\"69\" y1=\"59\" x2=\"69\" y2=\"96\" />\n  <line x1=\"73\" y1=\"63\" x2=\"73\" y2=\"99\" />\n  <line x1=\"76\" y1=\"66\" x2=\"76\" y2=\"103\" />\n  <line x1=\"80\" y1=\"70\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"10.0,0.0 80.58823529411765,70.58823529411765 80.58823529411765,107.33790767131957 10.0,36.74967237720192\" style=\"fill:#8B4903A0;stroke-width:0\"/>\n\n  <!-- Horizontal lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"35\" y2=\"0\" style=\"stroke-width:2\" />\n  <line x1=\"13\" y1=\"3\" x2=\"39\" y2=\"3\" />\n  <line x1=\"17\" y1=\"7\" x2=\"42\" y2=\"7\" />\n  <line x1=\"21\" y1=\"11\" x2=\"46\" y2=\"11\" />\n  <line x1=\"24\" y1=\"14\" x2=\"50\" y2=\"14\" />\n  <line x1=\"28\" y1=\"18\" x2=\"53\" y2=\"18\" />\n  <line x1=\"32\" y1=\"22\" x2=\"57\" y2=\"22\" />\n  <line x1=\"36\" y1=\"26\" x2=\"61\" y2=\"26\" />\n  <line x1=\"39\" y1=\"29\" x2=\"65\" y2=\"29\" />\n  <line x1=\"43\" y1=\"33\" x2=\"68\" y2=\"33\" />\n  <line x1=\"47\" y1=\"37\" x2=\"72\" y2=\"37\" />\n  <line x1=\"50\" y1=\"40\" x2=\"76\" y2=\"40\" />\n  <line x1=\"54\" y1=\"44\" x2=\"79\" y2=\"44\" />\n  <line x1=\"58\" y1=\"48\" x2=\"83\" y2=\"48\" />\n  <line x1=\"62\" y1=\"52\" x2=\"87\" y2=\"52\" />\n  <line x1=\"65\" y1=\"55\" x2=\"91\" y2=\"55\" />\n  <line x1=\"69\" y1=\"59\" x2=\"94\" y2=\"59\" />\n  <line x1=\"73\" y1=\"63\" x2=\"98\" y2=\"63\" />\n  <line x1=\"76\" y1=\"66\" x2=\"102\" y2=\"66\" />\n  <line x1=\"80\" y1=\"70\" x2=\"106\" y2=\"70\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"80\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"35\" y1=\"0\" x2=\"106\" y2=\"70\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"10.0,0.0 35.41261651458248,0.0 106.00085180870013,70.58823529411765 80.58823529411765,70.58823529411765\" style=\"fill:#8B4903A0;stroke-width:0\"/>\n\n  <!-- Horizontal lines -->\n  <line x1=\"80\" y1=\"70\" x2=\"106\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"80\" y1=\"107\" x2=\"106\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"80\" y1=\"70\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n  <line x1=\"106\" y1=\"70\" x2=\"106\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"80.58823529411765,70.58823529411765 106.00085180870013,70.58823529411765 106.00085180870013,107.33790767131957 80.58823529411765,107.33790767131957\" style=\"fill:#ECB172A0;stroke-width:0\"/>\n\n  <!-- Text -->\n  <text x=\"93.294544\" y=\"127.337908\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" >2</text>\n  <text x=\"126.000852\" y=\"88.963071\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" transform=\"rotate(-90,126.000852,88.963071)\">720</text>\n  <text x=\"35.294118\" y=\"92.043790\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" transform=\"rotate(45,35.294118,92.043790)\">9928</text>\n</svg>\n</td>\n</tr>\n</table></div></li><li class='xr-var-item'><div class='xr-var-name'><span>lon_bnds</span></div><div class='xr-var-dims'>(time, longitude, nv)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>dask.array&lt;chunksize=(1, 1440, 2), meta=np.ndarray&gt;</div><input id='attrs-a31661e6-52d5-4347-aa3d-94274c35c5c5' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-a31661e6-52d5-4347-aa3d-94274c35c5c5' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-5fd55f16-d455-4d37-a225-062bb2eb58eb' class='xr-var-data-in' type='checkbox'><label for='data-5fd55f16-d455-4d37-a225-062bb2eb58eb' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>comment :</span></dt><dd>longitude values at the west and east bounds of each pixel.</dd><dt><span>units :</span></dt><dd>degrees_east</dd></dl></div><div class='xr-var-data'><table>\n<tr>\n<td>\n<table>\n  <thead>\n    <tr><td> </td><th> Array </th><th> Chunk </th></tr>\n  </thead>\n  <tbody>\n    <tr><th> Bytes </th><td> 114.37 MB </td> <td> 11.52 kB </td></tr>\n    <tr><th> Shape </th><td> (9928, 1440, 2) </td> <td> (1, 1440, 2) </td></tr>\n    <tr><th> Count </th><td> 39712 Tasks </td><td> 9928 Chunks </td></tr>\n    <tr><th> Type </th><td> float32 </td><td> numpy.ndarray </td></tr>\n  </tbody>\n</table>\n</td>\n<td>\n<svg width=\"156\" height=\"161\" style=\"stroke:rgb(0,0,0);stroke-width:1\" >\n\n  <!-- Horizontal lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"80\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"10\" y1=\"40\" x2=\"80\" y2=\"111\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"10\" y2=\"40\" style=\"stroke-width:2\" />\n  <line x1=\"13\" y1=\"3\" x2=\"13\" y2=\"44\" />\n  <line x1=\"17\" y1=\"7\" x2=\"17\" y2=\"47\" />\n  <line x1=\"21\" y1=\"11\" x2=\"21\" y2=\"51\" />\n  <line x1=\"24\" y1=\"14\" x2=\"24\" y2=\"55\" />\n  <line x1=\"28\" y1=\"18\" x2=\"28\" y2=\"59\" />\n  <line x1=\"32\" y1=\"22\" x2=\"32\" y2=\"62\" />\n  <line x1=\"36\" y1=\"26\" x2=\"36\" y2=\"66\" />\n  <line x1=\"39\" y1=\"29\" x2=\"39\" y2=\"70\" />\n  <line x1=\"43\" y1=\"33\" x2=\"43\" y2=\"73\" />\n  <line x1=\"47\" y1=\"37\" x2=\"47\" y2=\"77\" />\n  <line x1=\"50\" y1=\"40\" x2=\"50\" y2=\"81\" />\n  <line x1=\"54\" y1=\"44\" x2=\"54\" y2=\"85\" />\n  <line x1=\"58\" y1=\"48\" x2=\"58\" y2=\"88\" />\n  <line x1=\"62\" y1=\"52\" x2=\"62\" y2=\"92\" />\n  <line x1=\"65\" y1=\"55\" x2=\"65\" y2=\"96\" />\n  <line x1=\"69\" y1=\"59\" x2=\"69\" y2=\"99\" />\n  <line x1=\"73\" y1=\"63\" x2=\"73\" y2=\"103\" />\n  <line x1=\"76\" y1=\"66\" x2=\"76\" y2=\"107\" />\n  <line x1=\"80\" y1=\"70\" x2=\"80\" y2=\"111\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"10.0,0.0 80.58823529411765,70.58823529411765 80.58823529411765,111.13127961619224 10.0,40.54304432207459\" style=\"fill:#8B4903A0;stroke-width:0\"/>\n\n  <!-- Horizontal lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"35\" y2=\"0\" style=\"stroke-width:2\" />\n  <line x1=\"13\" y1=\"3\" x2=\"39\" y2=\"3\" />\n  <line x1=\"17\" y1=\"7\" x2=\"42\" y2=\"7\" />\n  <line x1=\"21\" y1=\"11\" x2=\"46\" y2=\"11\" />\n  <line x1=\"24\" y1=\"14\" x2=\"50\" y2=\"14\" />\n  <line x1=\"28\" y1=\"18\" x2=\"53\" y2=\"18\" />\n  <line x1=\"32\" y1=\"22\" x2=\"57\" y2=\"22\" />\n  <line x1=\"36\" y1=\"26\" x2=\"61\" y2=\"26\" />\n  <line x1=\"39\" y1=\"29\" x2=\"65\" y2=\"29\" />\n  <line x1=\"43\" y1=\"33\" x2=\"68\" y2=\"33\" />\n  <line x1=\"47\" y1=\"37\" x2=\"72\" y2=\"37\" />\n  <line x1=\"50\" y1=\"40\" x2=\"76\" y2=\"40\" />\n  <line x1=\"54\" y1=\"44\" x2=\"79\" y2=\"44\" />\n  <line x1=\"58\" y1=\"48\" x2=\"83\" y2=\"48\" />\n  <line x1=\"62\" y1=\"52\" x2=\"87\" y2=\"52\" />\n  <line x1=\"65\" y1=\"55\" x2=\"91\" y2=\"55\" />\n  <line x1=\"69\" y1=\"59\" x2=\"94\" y2=\"59\" />\n  <line x1=\"73\" y1=\"63\" x2=\"98\" y2=\"63\" />\n  <line x1=\"76\" y1=\"66\" x2=\"102\" y2=\"66\" />\n  <line x1=\"80\" y1=\"70\" x2=\"106\" y2=\"70\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"80\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"35\" y1=\"0\" x2=\"106\" y2=\"70\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"10.0,0.0 35.41261651458248,0.0 106.00085180870013,70.58823529411765 80.58823529411765,70.58823529411765\" style=\"fill:#8B4903A0;stroke-width:0\"/>\n\n  <!-- Horizontal lines -->\n  <line x1=\"80\" y1=\"70\" x2=\"106\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"80\" y1=\"111\" x2=\"106\" y2=\"111\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"80\" y1=\"70\" x2=\"80\" y2=\"111\" style=\"stroke-width:2\" />\n  <line x1=\"106\" y1=\"70\" x2=\"106\" y2=\"111\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"80.58823529411765,70.58823529411765 106.00085180870013,70.58823529411765 106.00085180870013,111.13127961619224 80.58823529411765,111.13127961619224\" style=\"fill:#ECB172A0;stroke-width:0\"/>\n\n  <!-- Text -->\n  <text x=\"93.294544\" y=\"131.131280\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" >2</text>\n  <text x=\"126.000852\" y=\"90.859757\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" transform=\"rotate(-90,126.000852,90.859757)\">1440</text>\n  <text x=\"35.294118\" y=\"95.837162\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" transform=\"rotate(45,35.294118,95.837162)\">9928</text>\n</svg>\n</td>\n</tr>\n</table></div></li><li class='xr-var-item'><div class='xr-var-name'><span>err</span></div><div class='xr-var-dims'>(time, latitude, longitude)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>dask.array&lt;chunksize=(1, 720, 1440), meta=np.ndarray&gt;</div><input id='attrs-576b596b-cdb7-4072-a1c7-2e991ecb8f61' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-576b596b-cdb7-4072-a1c7-2e991ecb8f61' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-916f196b-5108-434f-bdfe-6d921bce4888' class='xr-var-data-in' type='checkbox'><label for='data-916f196b-5108-434f-bdfe-6d921bce4888' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>comment :</span></dt><dd>The formal mapping error represents a purely theoretical mapping error. It mainly traduces errors induced by the constellation sampling capability and consistency with the spatial/temporal scales considered, as described in Le Traon et al (1998) or Ducet et al (2000)</dd><dt><span>grid_mapping :</span></dt><dd>crs</dd><dt><span>long_name :</span></dt><dd>Formal mapping error</dd><dt><span>units :</span></dt><dd>m</dd></dl></div><div class='xr-var-data'><table>\n<tr>\n<td>\n<table>\n  <thead>\n    <tr><td> </td><th> Array </th><th> Chunk </th></tr>\n  </thead>\n  <tbody>\n    <tr><th> Bytes </th><td> 82.35 GB </td> <td> 8.29 MB </td></tr>\n    <tr><th> Shape </th><td> (9928, 720, 1440) </td> <td> (1, 720, 1440) </td></tr>\n    <tr><th> Count </th><td> 29784 Tasks </td><td> 9928 Chunks </td></tr>\n    <tr><th> Type </th><td> float64 </td><td> numpy.ndarray </td></tr>\n  </tbody>\n</table>\n</td>\n<td>\n<svg width=\"171\" height=\"157\" style=\"stroke:rgb(0,0,0);stroke-width:1\" >\n\n  <!-- Horizontal lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"80\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"10\" y1=\"36\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"10\" y2=\"36\" style=\"stroke-width:2\" />\n  <line x1=\"13\" y1=\"3\" x2=\"13\" y2=\"40\" />\n  <line x1=\"17\" y1=\"7\" x2=\"17\" y2=\"44\" />\n  <line x1=\"21\" y1=\"11\" x2=\"21\" y2=\"47\" />\n  <line x1=\"24\" y1=\"14\" x2=\"24\" y2=\"51\" />\n  <line x1=\"28\" y1=\"18\" x2=\"28\" y2=\"55\" />\n  <line x1=\"32\" y1=\"22\" x2=\"32\" y2=\"59\" />\n  <line x1=\"36\" y1=\"26\" x2=\"36\" y2=\"62\" />\n  <line x1=\"39\" y1=\"29\" x2=\"39\" y2=\"66\" />\n  <line x1=\"43\" y1=\"33\" x2=\"43\" y2=\"70\" />\n  <line x1=\"47\" y1=\"37\" x2=\"47\" y2=\"73\" />\n  <line x1=\"50\" y1=\"40\" x2=\"50\" y2=\"77\" />\n  <line x1=\"54\" y1=\"44\" x2=\"54\" y2=\"81\" />\n  <line x1=\"58\" y1=\"48\" x2=\"58\" y2=\"85\" />\n  <line x1=\"62\" y1=\"52\" x2=\"62\" y2=\"88\" />\n  <line x1=\"65\" y1=\"55\" x2=\"65\" y2=\"92\" />\n  <line x1=\"69\" y1=\"59\" x2=\"69\" y2=\"96\" />\n  <line x1=\"73\" y1=\"63\" x2=\"73\" y2=\"99\" />\n  <line x1=\"76\" y1=\"66\" x2=\"76\" y2=\"103\" />\n  <line x1=\"80\" y1=\"70\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"10.0,0.0 80.58823529411765,70.58823529411765 80.58823529411765,107.33790767131957 10.0,36.74967237720192\" style=\"fill:#8B4903A0;stroke-width:0\"/>\n\n  <!-- Horizontal lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"50\" y2=\"0\" style=\"stroke-width:2\" />\n  <line x1=\"13\" y1=\"3\" x2=\"54\" y2=\"3\" />\n  <line x1=\"17\" y1=\"7\" x2=\"57\" y2=\"7\" />\n  <line x1=\"21\" y1=\"11\" x2=\"61\" y2=\"11\" />\n  <line x1=\"24\" y1=\"14\" x2=\"65\" y2=\"14\" />\n  <line x1=\"28\" y1=\"18\" x2=\"69\" y2=\"18\" />\n  <line x1=\"32\" y1=\"22\" x2=\"72\" y2=\"22\" />\n  <line x1=\"36\" y1=\"26\" x2=\"76\" y2=\"26\" />\n  <line x1=\"39\" y1=\"29\" x2=\"80\" y2=\"29\" />\n  <line x1=\"43\" y1=\"33\" x2=\"83\" y2=\"33\" />\n  <line x1=\"47\" y1=\"37\" x2=\"87\" y2=\"37\" />\n  <line x1=\"50\" y1=\"40\" x2=\"91\" y2=\"40\" />\n  <line x1=\"54\" y1=\"44\" x2=\"95\" y2=\"44\" />\n  <line x1=\"58\" y1=\"48\" x2=\"98\" y2=\"48\" />\n  <line x1=\"62\" y1=\"52\" x2=\"102\" y2=\"52\" />\n  <line x1=\"65\" y1=\"55\" x2=\"106\" y2=\"55\" />\n  <line x1=\"69\" y1=\"59\" x2=\"109\" y2=\"59\" />\n  <line x1=\"73\" y1=\"63\" x2=\"113\" y2=\"63\" />\n  <line x1=\"76\" y1=\"66\" x2=\"117\" y2=\"66\" />\n  <line x1=\"80\" y1=\"70\" x2=\"121\" y2=\"70\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"80\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"50\" y1=\"0\" x2=\"121\" y2=\"70\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"10.0,0.0 50.54304432207459,0.0 121.13127961619224,70.58823529411765 80.58823529411765,70.58823529411765\" style=\"fill:#8B4903A0;stroke-width:0\"/>\n\n  <!-- Horizontal lines -->\n  <line x1=\"80\" y1=\"70\" x2=\"121\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"80\" y1=\"107\" x2=\"121\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"80\" y1=\"70\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n  <line x1=\"121\" y1=\"70\" x2=\"121\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"80.58823529411765,70.58823529411765 121.13127961619224,70.58823529411765 121.13127961619224,107.33790767131957 80.58823529411765,107.33790767131957\" style=\"fill:#ECB172A0;stroke-width:0\"/>\n\n  <!-- Text -->\n  <text x=\"100.859757\" y=\"127.337908\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" >1440</text>\n  <text x=\"141.131280\" y=\"88.963071\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" transform=\"rotate(-90,141.131280,88.963071)\">720</text>\n  <text x=\"35.294118\" y=\"92.043790\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" transform=\"rotate(45,35.294118,92.043790)\">9928</text>\n</svg>\n</td>\n</tr>\n</table></div></li><li class='xr-var-item'><div class='xr-var-name'><span>adt</span></div><div class='xr-var-dims'>(time, latitude, longitude)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>dask.array&lt;chunksize=(1, 720, 1440), meta=np.ndarray&gt;</div><input id='attrs-3b57c346-c70b-480f-b26e-b7f0ce2f1702' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-3b57c346-c70b-480f-b26e-b7f0ce2f1702' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-c7b45054-8913-4c51-b421-b3ea2b8d92ed' class='xr-var-data-in' type='checkbox'><label for='data-c7b45054-8913-4c51-b421-b3ea2b8d92ed' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>comment :</span></dt><dd>The absolute dynamic topography is the sea surface height above geoid; the adt is obtained as follows: adt=sla+mdt where mdt is the mean dynamic topography; see the product user manual for details</dd><dt><span>grid_mapping :</span></dt><dd>crs</dd><dt><span>long_name :</span></dt><dd>Absolute dynamic topography</dd><dt><span>standard_name :</span></dt><dd>sea_surface_height_above_geoid</dd><dt><span>units :</span></dt><dd>m</dd></dl></div><div class='xr-var-data'><table>\n<tr>\n<td>\n<table>\n  <thead>\n    <tr><td> </td><th> Array </th><th> Chunk </th></tr>\n  </thead>\n  <tbody>\n    <tr><th> Bytes </th><td> 82.35 GB </td> <td> 8.29 MB </td></tr>\n    <tr><th> Shape </th><td> (9928, 720, 1440) </td> <td> (1, 720, 1440) </td></tr>\n    <tr><th> Count </th><td> 29784 Tasks </td><td> 9928 Chunks </td></tr>\n    <tr><th> Type </th><td> float64 </td><td> numpy.ndarray </td></tr>\n  </tbody>\n</table>\n</td>\n<td>\n<svg width=\"171\" height=\"157\" style=\"stroke:rgb(0,0,0);stroke-width:1\" >\n\n  <!-- Horizontal lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"80\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"10\" y1=\"36\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"10\" y2=\"36\" style=\"stroke-width:2\" />\n  <line x1=\"13\" y1=\"3\" x2=\"13\" y2=\"40\" />\n  <line x1=\"17\" y1=\"7\" x2=\"17\" y2=\"44\" />\n  <line x1=\"21\" y1=\"11\" x2=\"21\" y2=\"47\" />\n  <line x1=\"24\" y1=\"14\" x2=\"24\" y2=\"51\" />\n  <line x1=\"28\" y1=\"18\" x2=\"28\" y2=\"55\" />\n  <line x1=\"32\" y1=\"22\" x2=\"32\" y2=\"59\" />\n  <line x1=\"36\" y1=\"26\" x2=\"36\" y2=\"62\" />\n  <line x1=\"39\" y1=\"29\" x2=\"39\" y2=\"66\" />\n  <line x1=\"43\" y1=\"33\" x2=\"43\" y2=\"70\" />\n  <line x1=\"47\" y1=\"37\" x2=\"47\" y2=\"73\" />\n  <line x1=\"50\" y1=\"40\" x2=\"50\" y2=\"77\" />\n  <line x1=\"54\" y1=\"44\" x2=\"54\" y2=\"81\" />\n  <line x1=\"58\" y1=\"48\" x2=\"58\" y2=\"85\" />\n  <line x1=\"62\" y1=\"52\" x2=\"62\" y2=\"88\" />\n  <line x1=\"65\" y1=\"55\" x2=\"65\" y2=\"92\" />\n  <line x1=\"69\" y1=\"59\" x2=\"69\" y2=\"96\" />\n  <line x1=\"73\" y1=\"63\" x2=\"73\" y2=\"99\" />\n  <line x1=\"76\" y1=\"66\" x2=\"76\" y2=\"103\" />\n  <line x1=\"80\" y1=\"70\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"10.0,0.0 80.58823529411765,70.58823529411765 80.58823529411765,107.33790767131957 10.0,36.74967237720192\" style=\"fill:#8B4903A0;stroke-width:0\"/>\n\n  <!-- Horizontal lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"50\" y2=\"0\" style=\"stroke-width:2\" />\n  <line x1=\"13\" y1=\"3\" x2=\"54\" y2=\"3\" />\n  <line x1=\"17\" y1=\"7\" x2=\"57\" y2=\"7\" />\n  <line x1=\"21\" y1=\"11\" x2=\"61\" y2=\"11\" />\n  <line x1=\"24\" y1=\"14\" x2=\"65\" y2=\"14\" />\n  <line x1=\"28\" y1=\"18\" x2=\"69\" y2=\"18\" />\n  <line x1=\"32\" y1=\"22\" x2=\"72\" y2=\"22\" />\n  <line x1=\"36\" y1=\"26\" x2=\"76\" y2=\"26\" />\n  <line x1=\"39\" y1=\"29\" x2=\"80\" y2=\"29\" />\n  <line x1=\"43\" y1=\"33\" x2=\"83\" y2=\"33\" />\n  <line x1=\"47\" y1=\"37\" x2=\"87\" y2=\"37\" />\n  <line x1=\"50\" y1=\"40\" x2=\"91\" y2=\"40\" />\n  <line x1=\"54\" y1=\"44\" x2=\"95\" y2=\"44\" />\n  <line x1=\"58\" y1=\"48\" x2=\"98\" y2=\"48\" />\n  <line x1=\"62\" y1=\"52\" x2=\"102\" y2=\"52\" />\n  <line x1=\"65\" y1=\"55\" x2=\"106\" y2=\"55\" />\n  <line x1=\"69\" y1=\"59\" x2=\"109\" y2=\"59\" />\n  <line x1=\"73\" y1=\"63\" x2=\"113\" y2=\"63\" />\n  <line x1=\"76\" y1=\"66\" x2=\"117\" y2=\"66\" />\n  <line x1=\"80\" y1=\"70\" x2=\"121\" y2=\"70\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"80\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"50\" y1=\"0\" x2=\"121\" y2=\"70\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"10.0,0.0 50.54304432207459,0.0 121.13127961619224,70.58823529411765 80.58823529411765,70.58823529411765\" style=\"fill:#8B4903A0;stroke-width:0\"/>\n\n  <!-- Horizontal lines -->\n  <line x1=\"80\" y1=\"70\" x2=\"121\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"80\" y1=\"107\" x2=\"121\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"80\" y1=\"70\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n  <line x1=\"121\" y1=\"70\" x2=\"121\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"80.58823529411765,70.58823529411765 121.13127961619224,70.58823529411765 121.13127961619224,107.33790767131957 80.58823529411765,107.33790767131957\" style=\"fill:#ECB172A0;stroke-width:0\"/>\n\n  <!-- Text -->\n  <text x=\"100.859757\" y=\"127.337908\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" >1440</text>\n  <text x=\"141.131280\" y=\"88.963071\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" transform=\"rotate(-90,141.131280,88.963071)\">720</text>\n  <text x=\"35.294118\" y=\"92.043790\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" transform=\"rotate(45,35.294118,92.043790)\">9928</text>\n</svg>\n</td>\n</tr>\n</table></div></li><li class='xr-var-item'><div class='xr-var-name'><span>ugos</span></div><div class='xr-var-dims'>(time, latitude, longitude)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>dask.array&lt;chunksize=(1, 720, 1440), meta=np.ndarray&gt;</div><input id='attrs-d14036f1-36b7-48a6-98c1-05c6396d2e1a' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-d14036f1-36b7-48a6-98c1-05c6396d2e1a' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-8f12246b-2341-415d-a72c-935e7c5b4b33' class='xr-var-data-in' type='checkbox'><label for='data-8f12246b-2341-415d-a72c-935e7c5b4b33' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>grid_mapping :</span></dt><dd>crs</dd><dt><span>long_name :</span></dt><dd>Absolute geostrophic velocity: zonal component</dd><dt><span>standard_name :</span></dt><dd>surface_geostrophic_eastward_sea_water_velocity</dd><dt><span>units :</span></dt><dd>m/s</dd></dl></div><div class='xr-var-data'><table>\n<tr>\n<td>\n<table>\n  <thead>\n    <tr><td> </td><th> Array </th><th> Chunk </th></tr>\n  </thead>\n  <tbody>\n    <tr><th> Bytes </th><td> 82.35 GB </td> <td> 8.29 MB </td></tr>\n    <tr><th> Shape </th><td> (9928, 720, 1440) </td> <td> (1, 720, 1440) </td></tr>\n    <tr><th> Count </th><td> 29784 Tasks </td><td> 9928 Chunks </td></tr>\n    <tr><th> Type </th><td> float64 </td><td> numpy.ndarray </td></tr>\n  </tbody>\n</table>\n</td>\n<td>\n<svg width=\"171\" height=\"157\" style=\"stroke:rgb(0,0,0);stroke-width:1\" >\n\n  <!-- Horizontal lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"80\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"10\" y1=\"36\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"10\" y2=\"36\" style=\"stroke-width:2\" />\n  <line x1=\"13\" y1=\"3\" x2=\"13\" y2=\"40\" />\n  <line x1=\"17\" y1=\"7\" x2=\"17\" y2=\"44\" />\n  <line x1=\"21\" y1=\"11\" x2=\"21\" y2=\"47\" />\n  <line x1=\"24\" y1=\"14\" x2=\"24\" y2=\"51\" />\n  <line x1=\"28\" y1=\"18\" x2=\"28\" y2=\"55\" />\n  <line x1=\"32\" y1=\"22\" x2=\"32\" y2=\"59\" />\n  <line x1=\"36\" y1=\"26\" x2=\"36\" y2=\"62\" />\n  <line x1=\"39\" y1=\"29\" x2=\"39\" y2=\"66\" />\n  <line x1=\"43\" y1=\"33\" x2=\"43\" y2=\"70\" />\n  <line x1=\"47\" y1=\"37\" x2=\"47\" y2=\"73\" />\n  <line x1=\"50\" y1=\"40\" x2=\"50\" y2=\"77\" />\n  <line x1=\"54\" y1=\"44\" x2=\"54\" y2=\"81\" />\n  <line x1=\"58\" y1=\"48\" x2=\"58\" y2=\"85\" />\n  <line x1=\"62\" y1=\"52\" x2=\"62\" y2=\"88\" />\n  <line x1=\"65\" y1=\"55\" x2=\"65\" y2=\"92\" />\n  <line x1=\"69\" y1=\"59\" x2=\"69\" y2=\"96\" />\n  <line x1=\"73\" y1=\"63\" x2=\"73\" y2=\"99\" />\n  <line x1=\"76\" y1=\"66\" x2=\"76\" y2=\"103\" />\n  <line x1=\"80\" y1=\"70\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"10.0,0.0 80.58823529411765,70.58823529411765 80.58823529411765,107.33790767131957 10.0,36.74967237720192\" style=\"fill:#8B4903A0;stroke-width:0\"/>\n\n  <!-- Horizontal lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"50\" y2=\"0\" style=\"stroke-width:2\" />\n  <line x1=\"13\" y1=\"3\" x2=\"54\" y2=\"3\" />\n  <line x1=\"17\" y1=\"7\" x2=\"57\" y2=\"7\" />\n  <line x1=\"21\" y1=\"11\" x2=\"61\" y2=\"11\" />\n  <line x1=\"24\" y1=\"14\" x2=\"65\" y2=\"14\" />\n  <line x1=\"28\" y1=\"18\" x2=\"69\" y2=\"18\" />\n  <line x1=\"32\" y1=\"22\" x2=\"72\" y2=\"22\" />\n  <line x1=\"36\" y1=\"26\" x2=\"76\" y2=\"26\" />\n  <line x1=\"39\" y1=\"29\" x2=\"80\" y2=\"29\" />\n  <line x1=\"43\" y1=\"33\" x2=\"83\" y2=\"33\" />\n  <line x1=\"47\" y1=\"37\" x2=\"87\" y2=\"37\" />\n  <line x1=\"50\" y1=\"40\" x2=\"91\" y2=\"40\" />\n  <line x1=\"54\" y1=\"44\" x2=\"95\" y2=\"44\" />\n  <line x1=\"58\" y1=\"48\" x2=\"98\" y2=\"48\" />\n  <line x1=\"62\" y1=\"52\" x2=\"102\" y2=\"52\" />\n  <line x1=\"65\" y1=\"55\" x2=\"106\" y2=\"55\" />\n  <line x1=\"69\" y1=\"59\" x2=\"109\" y2=\"59\" />\n  <line x1=\"73\" y1=\"63\" x2=\"113\" y2=\"63\" />\n  <line x1=\"76\" y1=\"66\" x2=\"117\" y2=\"66\" />\n  <line x1=\"80\" y1=\"70\" x2=\"121\" y2=\"70\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"80\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"50\" y1=\"0\" x2=\"121\" y2=\"70\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"10.0,0.0 50.54304432207459,0.0 121.13127961619224,70.58823529411765 80.58823529411765,70.58823529411765\" style=\"fill:#8B4903A0;stroke-width:0\"/>\n\n  <!-- Horizontal lines -->\n  <line x1=\"80\" y1=\"70\" x2=\"121\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"80\" y1=\"107\" x2=\"121\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"80\" y1=\"70\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n  <line x1=\"121\" y1=\"70\" x2=\"121\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"80.58823529411765,70.58823529411765 121.13127961619224,70.58823529411765 121.13127961619224,107.33790767131957 80.58823529411765,107.33790767131957\" style=\"fill:#ECB172A0;stroke-width:0\"/>\n\n  <!-- Text -->\n  <text x=\"100.859757\" y=\"127.337908\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" >1440</text>\n  <text x=\"141.131280\" y=\"88.963071\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" transform=\"rotate(-90,141.131280,88.963071)\">720</text>\n  <text x=\"35.294118\" y=\"92.043790\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" transform=\"rotate(45,35.294118,92.043790)\">9928</text>\n</svg>\n</td>\n</tr>\n</table></div></li><li class='xr-var-item'><div class='xr-var-name'><span>vgos</span></div><div class='xr-var-dims'>(time, latitude, longitude)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>dask.array&lt;chunksize=(1, 720, 1440), meta=np.ndarray&gt;</div><input id='attrs-342faed8-218d-44a3-b091-b8319c73c5b6' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-342faed8-218d-44a3-b091-b8319c73c5b6' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-d37c386b-9354-4b6a-a271-9904843d3104' class='xr-var-data-in' type='checkbox'><label for='data-d37c386b-9354-4b6a-a271-9904843d3104' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>grid_mapping :</span></dt><dd>crs</dd><dt><span>long_name :</span></dt><dd>Absolute geostrophic velocity: meridian component</dd><dt><span>standard_name :</span></dt><dd>surface_geostrophic_northward_sea_water_velocity</dd><dt><span>units :</span></dt><dd>m/s</dd></dl></div><div class='xr-var-data'><table>\n<tr>\n<td>\n<table>\n  <thead>\n    <tr><td> </td><th> Array </th><th> Chunk </th></tr>\n  </thead>\n  <tbody>\n    <tr><th> Bytes </th><td> 82.35 GB </td> <td> 8.29 MB </td></tr>\n    <tr><th> Shape </th><td> (9928, 720, 1440) </td> <td> (1, 720, 1440) </td></tr>\n    <tr><th> Count </th><td> 29784 Tasks </td><td> 9928 Chunks </td></tr>\n    <tr><th> Type </th><td> float64 </td><td> numpy.ndarray </td></tr>\n  </tbody>\n</table>\n</td>\n<td>\n<svg width=\"171\" height=\"157\" style=\"stroke:rgb(0,0,0);stroke-width:1\" >\n\n  <!-- Horizontal lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"80\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"10\" y1=\"36\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"10\" y2=\"36\" style=\"stroke-width:2\" />\n  <line x1=\"13\" y1=\"3\" x2=\"13\" y2=\"40\" />\n  <line x1=\"17\" y1=\"7\" x2=\"17\" y2=\"44\" />\n  <line x1=\"21\" y1=\"11\" x2=\"21\" y2=\"47\" />\n  <line x1=\"24\" y1=\"14\" x2=\"24\" y2=\"51\" />\n  <line x1=\"28\" y1=\"18\" x2=\"28\" y2=\"55\" />\n  <line x1=\"32\" y1=\"22\" x2=\"32\" y2=\"59\" />\n  <line x1=\"36\" y1=\"26\" x2=\"36\" y2=\"62\" />\n  <line x1=\"39\" y1=\"29\" x2=\"39\" y2=\"66\" />\n  <line x1=\"43\" y1=\"33\" x2=\"43\" y2=\"70\" />\n  <line x1=\"47\" y1=\"37\" x2=\"47\" y2=\"73\" />\n  <line x1=\"50\" y1=\"40\" x2=\"50\" y2=\"77\" />\n  <line x1=\"54\" y1=\"44\" x2=\"54\" y2=\"81\" />\n  <line x1=\"58\" y1=\"48\" x2=\"58\" y2=\"85\" />\n  <line x1=\"62\" y1=\"52\" x2=\"62\" y2=\"88\" />\n  <line x1=\"65\" y1=\"55\" x2=\"65\" y2=\"92\" />\n  <line x1=\"69\" y1=\"59\" x2=\"69\" y2=\"96\" />\n  <line x1=\"73\" y1=\"63\" x2=\"73\" y2=\"99\" />\n  <line x1=\"76\" y1=\"66\" x2=\"76\" y2=\"103\" />\n  <line x1=\"80\" y1=\"70\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"10.0,0.0 80.58823529411765,70.58823529411765 80.58823529411765,107.33790767131957 10.0,36.74967237720192\" style=\"fill:#8B4903A0;stroke-width:0\"/>\n\n  <!-- Horizontal lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"50\" y2=\"0\" style=\"stroke-width:2\" />\n  <line x1=\"13\" y1=\"3\" x2=\"54\" y2=\"3\" />\n  <line x1=\"17\" y1=\"7\" x2=\"57\" y2=\"7\" />\n  <line x1=\"21\" y1=\"11\" x2=\"61\" y2=\"11\" />\n  <line x1=\"24\" y1=\"14\" x2=\"65\" y2=\"14\" />\n  <line x1=\"28\" y1=\"18\" x2=\"69\" y2=\"18\" />\n  <line x1=\"32\" y1=\"22\" x2=\"72\" y2=\"22\" />\n  <line x1=\"36\" y1=\"26\" x2=\"76\" y2=\"26\" />\n  <line x1=\"39\" y1=\"29\" x2=\"80\" y2=\"29\" />\n  <line x1=\"43\" y1=\"33\" x2=\"83\" y2=\"33\" />\n  <line x1=\"47\" y1=\"37\" x2=\"87\" y2=\"37\" />\n  <line x1=\"50\" y1=\"40\" x2=\"91\" y2=\"40\" />\n  <line x1=\"54\" y1=\"44\" x2=\"95\" y2=\"44\" />\n  <line x1=\"58\" y1=\"48\" x2=\"98\" y2=\"48\" />\n  <line x1=\"62\" y1=\"52\" x2=\"102\" y2=\"52\" />\n  <line x1=\"65\" y1=\"55\" x2=\"106\" y2=\"55\" />\n  <line x1=\"69\" y1=\"59\" x2=\"109\" y2=\"59\" />\n  <line x1=\"73\" y1=\"63\" x2=\"113\" y2=\"63\" />\n  <line x1=\"76\" y1=\"66\" x2=\"117\" y2=\"66\" />\n  <line x1=\"80\" y1=\"70\" x2=\"121\" y2=\"70\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"80\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"50\" y1=\"0\" x2=\"121\" y2=\"70\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"10.0,0.0 50.54304432207459,0.0 121.13127961619224,70.58823529411765 80.58823529411765,70.58823529411765\" style=\"fill:#8B4903A0;stroke-width:0\"/>\n\n  <!-- Horizontal lines -->\n  <line x1=\"80\" y1=\"70\" x2=\"121\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"80\" y1=\"107\" x2=\"121\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"80\" y1=\"70\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n  <line x1=\"121\" y1=\"70\" x2=\"121\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"80.58823529411765,70.58823529411765 121.13127961619224,70.58823529411765 121.13127961619224,107.33790767131957 80.58823529411765,107.33790767131957\" style=\"fill:#ECB172A0;stroke-width:0\"/>\n\n  <!-- Text -->\n  <text x=\"100.859757\" y=\"127.337908\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" >1440</text>\n  <text x=\"141.131280\" y=\"88.963071\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" transform=\"rotate(-90,141.131280,88.963071)\">720</text>\n  <text x=\"35.294118\" y=\"92.043790\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" transform=\"rotate(45,35.294118,92.043790)\">9928</text>\n</svg>\n</td>\n</tr>\n</table></div></li><li class='xr-var-item'><div class='xr-var-name'><span>sla</span></div><div class='xr-var-dims'>(time, latitude, longitude)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>dask.array&lt;chunksize=(1, 720, 1440), meta=np.ndarray&gt;</div><input id='attrs-8f44b60f-524c-46a5-bc69-8f8bfaa00058' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-8f44b60f-524c-46a5-bc69-8f8bfaa00058' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-b4610574-a9fc-4680-b1f9-ec33c817d86b' class='xr-var-data-in' type='checkbox'><label for='data-b4610574-a9fc-4680-b1f9-ec33c817d86b' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>comment :</span></dt><dd>The sea level anomaly is the sea surface height above mean sea surface; it is referenced to the [1993, 2012] period; see the product user manual for details</dd><dt><span>grid_mapping :</span></dt><dd>crs</dd><dt><span>long_name :</span></dt><dd>Sea level anomaly</dd><dt><span>standard_name :</span></dt><dd>sea_surface_height_above_sea_level</dd><dt><span>units :</span></dt><dd>m</dd></dl></div><div class='xr-var-data'><table>\n<tr>\n<td>\n<table>\n  <thead>\n    <tr><td> </td><th> Array </th><th> Chunk </th></tr>\n  </thead>\n  <tbody>\n    <tr><th> Bytes </th><td> 82.35 GB </td> <td> 8.29 MB </td></tr>\n    <tr><th> Shape </th><td> (9928, 720, 1440) </td> <td> (1, 720, 1440) </td></tr>\n    <tr><th> Count </th><td> 29784 Tasks </td><td> 9928 Chunks </td></tr>\n    <tr><th> Type </th><td> float64 </td><td> numpy.ndarray </td></tr>\n  </tbody>\n</table>\n</td>\n<td>\n<svg width=\"171\" height=\"157\" style=\"stroke:rgb(0,0,0);stroke-width:1\" >\n\n  <!-- Horizontal lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"80\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"10\" y1=\"36\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"10\" y2=\"36\" style=\"stroke-width:2\" />\n  <line x1=\"13\" y1=\"3\" x2=\"13\" y2=\"40\" />\n  <line x1=\"17\" y1=\"7\" x2=\"17\" y2=\"44\" />\n  <line x1=\"21\" y1=\"11\" x2=\"21\" y2=\"47\" />\n  <line x1=\"24\" y1=\"14\" x2=\"24\" y2=\"51\" />\n  <line x1=\"28\" y1=\"18\" x2=\"28\" y2=\"55\" />\n  <line x1=\"32\" y1=\"22\" x2=\"32\" y2=\"59\" />\n  <line x1=\"36\" y1=\"26\" x2=\"36\" y2=\"62\" />\n  <line x1=\"39\" y1=\"29\" x2=\"39\" y2=\"66\" />\n  <line x1=\"43\" y1=\"33\" x2=\"43\" y2=\"70\" />\n  <line x1=\"47\" y1=\"37\" x2=\"47\" y2=\"73\" />\n  <line x1=\"50\" y1=\"40\" x2=\"50\" y2=\"77\" />\n  <line x1=\"54\" y1=\"44\" x2=\"54\" y2=\"81\" />\n  <line x1=\"58\" y1=\"48\" x2=\"58\" y2=\"85\" />\n  <line x1=\"62\" y1=\"52\" x2=\"62\" y2=\"88\" />\n  <line x1=\"65\" y1=\"55\" x2=\"65\" y2=\"92\" />\n  <line x1=\"69\" y1=\"59\" x2=\"69\" y2=\"96\" />\n  <line x1=\"73\" y1=\"63\" x2=\"73\" y2=\"99\" />\n  <line x1=\"76\" y1=\"66\" x2=\"76\" y2=\"103\" />\n  <line x1=\"80\" y1=\"70\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"10.0,0.0 80.58823529411765,70.58823529411765 80.58823529411765,107.33790767131957 10.0,36.74967237720192\" style=\"fill:#8B4903A0;stroke-width:0\"/>\n\n  <!-- Horizontal lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"50\" y2=\"0\" style=\"stroke-width:2\" />\n  <line x1=\"13\" y1=\"3\" x2=\"54\" y2=\"3\" />\n  <line x1=\"17\" y1=\"7\" x2=\"57\" y2=\"7\" />\n  <line x1=\"21\" y1=\"11\" x2=\"61\" y2=\"11\" />\n  <line x1=\"24\" y1=\"14\" x2=\"65\" y2=\"14\" />\n  <line x1=\"28\" y1=\"18\" x2=\"69\" y2=\"18\" />\n  <line x1=\"32\" y1=\"22\" x2=\"72\" y2=\"22\" />\n  <line x1=\"36\" y1=\"26\" x2=\"76\" y2=\"26\" />\n  <line x1=\"39\" y1=\"29\" x2=\"80\" y2=\"29\" />\n  <line x1=\"43\" y1=\"33\" x2=\"83\" y2=\"33\" />\n  <line x1=\"47\" y1=\"37\" x2=\"87\" y2=\"37\" />\n  <line x1=\"50\" y1=\"40\" x2=\"91\" y2=\"40\" />\n  <line x1=\"54\" y1=\"44\" x2=\"95\" y2=\"44\" />\n  <line x1=\"58\" y1=\"48\" x2=\"98\" y2=\"48\" />\n  <line x1=\"62\" y1=\"52\" x2=\"102\" y2=\"52\" />\n  <line x1=\"65\" y1=\"55\" x2=\"106\" y2=\"55\" />\n  <line x1=\"69\" y1=\"59\" x2=\"109\" y2=\"59\" />\n  <line x1=\"73\" y1=\"63\" x2=\"113\" y2=\"63\" />\n  <line x1=\"76\" y1=\"66\" x2=\"117\" y2=\"66\" />\n  <line x1=\"80\" y1=\"70\" x2=\"121\" y2=\"70\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"80\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"50\" y1=\"0\" x2=\"121\" y2=\"70\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"10.0,0.0 50.54304432207459,0.0 121.13127961619224,70.58823529411765 80.58823529411765,70.58823529411765\" style=\"fill:#8B4903A0;stroke-width:0\"/>\n\n  <!-- Horizontal lines -->\n  <line x1=\"80\" y1=\"70\" x2=\"121\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"80\" y1=\"107\" x2=\"121\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"80\" y1=\"70\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n  <line x1=\"121\" y1=\"70\" x2=\"121\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"80.58823529411765,70.58823529411765 121.13127961619224,70.58823529411765 121.13127961619224,107.33790767131957 80.58823529411765,107.33790767131957\" style=\"fill:#ECB172A0;stroke-width:0\"/>\n\n  <!-- Text -->\n  <text x=\"100.859757\" y=\"127.337908\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" >1440</text>\n  <text x=\"141.131280\" y=\"88.963071\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" transform=\"rotate(-90,141.131280,88.963071)\">720</text>\n  <text x=\"35.294118\" y=\"92.043790\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" transform=\"rotate(45,35.294118,92.043790)\">9928</text>\n</svg>\n</td>\n</tr>\n</table></div></li><li class='xr-var-item'><div class='xr-var-name'><span>ugosa</span></div><div class='xr-var-dims'>(time, latitude, longitude)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>dask.array&lt;chunksize=(1, 720, 1440), meta=np.ndarray&gt;</div><input id='attrs-c60f9847-a48e-4093-9230-ef332463aa6a' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-c60f9847-a48e-4093-9230-ef332463aa6a' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-a24dff32-9a0a-4dd8-86da-7c608dd747fa' class='xr-var-data-in' type='checkbox'><label for='data-a24dff32-9a0a-4dd8-86da-7c608dd747fa' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>comment :</span></dt><dd>The geostrophic velocity anomalies are referenced to the [1993, 2012] period</dd><dt><span>grid_mapping :</span></dt><dd>crs</dd><dt><span>long_name :</span></dt><dd>Geostrophic velocity anomalies: zonal component</dd><dt><span>standard_name :</span></dt><dd>surface_geostrophic_eastward_sea_water_velocity_assuming_sea_level_for_geoid</dd><dt><span>units :</span></dt><dd>m/s</dd></dl></div><div class='xr-var-data'><table>\n<tr>\n<td>\n<table>\n  <thead>\n    <tr><td> </td><th> Array </th><th> Chunk </th></tr>\n  </thead>\n  <tbody>\n    <tr><th> Bytes </th><td> 82.35 GB </td> <td> 8.29 MB </td></tr>\n    <tr><th> Shape </th><td> (9928, 720, 1440) </td> <td> (1, 720, 1440) </td></tr>\n    <tr><th> Count </th><td> 29784 Tasks </td><td> 9928 Chunks </td></tr>\n    <tr><th> Type </th><td> float64 </td><td> numpy.ndarray </td></tr>\n  </tbody>\n</table>\n</td>\n<td>\n<svg width=\"171\" height=\"157\" style=\"stroke:rgb(0,0,0);stroke-width:1\" >\n\n  <!-- Horizontal lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"80\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"10\" y1=\"36\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"10\" y2=\"36\" style=\"stroke-width:2\" />\n  <line x1=\"13\" y1=\"3\" x2=\"13\" y2=\"40\" />\n  <line x1=\"17\" y1=\"7\" x2=\"17\" y2=\"44\" />\n  <line x1=\"21\" y1=\"11\" x2=\"21\" y2=\"47\" />\n  <line x1=\"24\" y1=\"14\" x2=\"24\" y2=\"51\" />\n  <line x1=\"28\" y1=\"18\" x2=\"28\" y2=\"55\" />\n  <line x1=\"32\" y1=\"22\" x2=\"32\" y2=\"59\" />\n  <line x1=\"36\" y1=\"26\" x2=\"36\" y2=\"62\" />\n  <line x1=\"39\" y1=\"29\" x2=\"39\" y2=\"66\" />\n  <line x1=\"43\" y1=\"33\" x2=\"43\" y2=\"70\" />\n  <line x1=\"47\" y1=\"37\" x2=\"47\" y2=\"73\" />\n  <line x1=\"50\" y1=\"40\" x2=\"50\" y2=\"77\" />\n  <line x1=\"54\" y1=\"44\" x2=\"54\" y2=\"81\" />\n  <line x1=\"58\" y1=\"48\" x2=\"58\" y2=\"85\" />\n  <line x1=\"62\" y1=\"52\" x2=\"62\" y2=\"88\" />\n  <line x1=\"65\" y1=\"55\" x2=\"65\" y2=\"92\" />\n  <line x1=\"69\" y1=\"59\" x2=\"69\" y2=\"96\" />\n  <line x1=\"73\" y1=\"63\" x2=\"73\" y2=\"99\" />\n  <line x1=\"76\" y1=\"66\" x2=\"76\" y2=\"103\" />\n  <line x1=\"80\" y1=\"70\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"10.0,0.0 80.58823529411765,70.58823529411765 80.58823529411765,107.33790767131957 10.0,36.74967237720192\" style=\"fill:#8B4903A0;stroke-width:0\"/>\n\n  <!-- Horizontal lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"50\" y2=\"0\" style=\"stroke-width:2\" />\n  <line x1=\"13\" y1=\"3\" x2=\"54\" y2=\"3\" />\n  <line x1=\"17\" y1=\"7\" x2=\"57\" y2=\"7\" />\n  <line x1=\"21\" y1=\"11\" x2=\"61\" y2=\"11\" />\n  <line x1=\"24\" y1=\"14\" x2=\"65\" y2=\"14\" />\n  <line x1=\"28\" y1=\"18\" x2=\"69\" y2=\"18\" />\n  <line x1=\"32\" y1=\"22\" x2=\"72\" y2=\"22\" />\n  <line x1=\"36\" y1=\"26\" x2=\"76\" y2=\"26\" />\n  <line x1=\"39\" y1=\"29\" x2=\"80\" y2=\"29\" />\n  <line x1=\"43\" y1=\"33\" x2=\"83\" y2=\"33\" />\n  <line x1=\"47\" y1=\"37\" x2=\"87\" y2=\"37\" />\n  <line x1=\"50\" y1=\"40\" x2=\"91\" y2=\"40\" />\n  <line x1=\"54\" y1=\"44\" x2=\"95\" y2=\"44\" />\n  <line x1=\"58\" y1=\"48\" x2=\"98\" y2=\"48\" />\n  <line x1=\"62\" y1=\"52\" x2=\"102\" y2=\"52\" />\n  <line x1=\"65\" y1=\"55\" x2=\"106\" y2=\"55\" />\n  <line x1=\"69\" y1=\"59\" x2=\"109\" y2=\"59\" />\n  <line x1=\"73\" y1=\"63\" x2=\"113\" y2=\"63\" />\n  <line x1=\"76\" y1=\"66\" x2=\"117\" y2=\"66\" />\n  <line x1=\"80\" y1=\"70\" x2=\"121\" y2=\"70\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"80\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"50\" y1=\"0\" x2=\"121\" y2=\"70\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"10.0,0.0 50.54304432207459,0.0 121.13127961619224,70.58823529411765 80.58823529411765,70.58823529411765\" style=\"fill:#8B4903A0;stroke-width:0\"/>\n\n  <!-- Horizontal lines -->\n  <line x1=\"80\" y1=\"70\" x2=\"121\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"80\" y1=\"107\" x2=\"121\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"80\" y1=\"70\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n  <line x1=\"121\" y1=\"70\" x2=\"121\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"80.58823529411765,70.58823529411765 121.13127961619224,70.58823529411765 121.13127961619224,107.33790767131957 80.58823529411765,107.33790767131957\" style=\"fill:#ECB172A0;stroke-width:0\"/>\n\n  <!-- Text -->\n  <text x=\"100.859757\" y=\"127.337908\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" >1440</text>\n  <text x=\"141.131280\" y=\"88.963071\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" transform=\"rotate(-90,141.131280,88.963071)\">720</text>\n  <text x=\"35.294118\" y=\"92.043790\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" transform=\"rotate(45,35.294118,92.043790)\">9928</text>\n</svg>\n</td>\n</tr>\n</table></div></li><li class='xr-var-item'><div class='xr-var-name'><span>vgosa</span></div><div class='xr-var-dims'>(time, latitude, longitude)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>dask.array&lt;chunksize=(1, 720, 1440), meta=np.ndarray&gt;</div><input id='attrs-f63b0adb-8bcc-4728-9a4d-aecf656d6617' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-f63b0adb-8bcc-4728-9a4d-aecf656d6617' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-85ba162a-6611-4a86-b277-28c1174849f5' class='xr-var-data-in' type='checkbox'><label for='data-85ba162a-6611-4a86-b277-28c1174849f5' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>comment :</span></dt><dd>The geostrophic velocity anomalies are referenced to the [1993, 2012] period</dd><dt><span>grid_mapping :</span></dt><dd>crs</dd><dt><span>long_name :</span></dt><dd>Geostrophic velocity anomalies: meridian component</dd><dt><span>standard_name :</span></dt><dd>surface_geostrophic_northward_sea_water_velocity_assuming_sea_level_for_geoid</dd><dt><span>units :</span></dt><dd>m/s</dd></dl></div><div class='xr-var-data'><table>\n<tr>\n<td>\n<table>\n  <thead>\n    <tr><td> </td><th> Array </th><th> Chunk </th></tr>\n  </thead>\n  <tbody>\n    <tr><th> Bytes </th><td> 82.35 GB </td> <td> 8.29 MB </td></tr>\n    <tr><th> Shape </th><td> (9928, 720, 1440) </td> <td> (1, 720, 1440) </td></tr>\n    <tr><th> Count </th><td> 29784 Tasks </td><td> 9928 Chunks </td></tr>\n    <tr><th> Type </th><td> float64 </td><td> numpy.ndarray </td></tr>\n  </tbody>\n</table>\n</td>\n<td>\n<svg width=\"171\" height=\"157\" style=\"stroke:rgb(0,0,0);stroke-width:1\" >\n\n  <!-- Horizontal lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"80\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"10\" y1=\"36\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"10\" y2=\"36\" style=\"stroke-width:2\" />\n  <line x1=\"13\" y1=\"3\" x2=\"13\" y2=\"40\" />\n  <line x1=\"17\" y1=\"7\" x2=\"17\" y2=\"44\" />\n  <line x1=\"21\" y1=\"11\" x2=\"21\" y2=\"47\" />\n  <line x1=\"24\" y1=\"14\" x2=\"24\" y2=\"51\" />\n  <line x1=\"28\" y1=\"18\" x2=\"28\" y2=\"55\" />\n  <line x1=\"32\" y1=\"22\" x2=\"32\" y2=\"59\" />\n  <line x1=\"36\" y1=\"26\" x2=\"36\" y2=\"62\" />\n  <line x1=\"39\" y1=\"29\" x2=\"39\" y2=\"66\" />\n  <line x1=\"43\" y1=\"33\" x2=\"43\" y2=\"70\" />\n  <line x1=\"47\" y1=\"37\" x2=\"47\" y2=\"73\" />\n  <line x1=\"50\" y1=\"40\" x2=\"50\" y2=\"77\" />\n  <line x1=\"54\" y1=\"44\" x2=\"54\" y2=\"81\" />\n  <line x1=\"58\" y1=\"48\" x2=\"58\" y2=\"85\" />\n  <line x1=\"62\" y1=\"52\" x2=\"62\" y2=\"88\" />\n  <line x1=\"65\" y1=\"55\" x2=\"65\" y2=\"92\" />\n  <line x1=\"69\" y1=\"59\" x2=\"69\" y2=\"96\" />\n  <line x1=\"73\" y1=\"63\" x2=\"73\" y2=\"99\" />\n  <line x1=\"76\" y1=\"66\" x2=\"76\" y2=\"103\" />\n  <line x1=\"80\" y1=\"70\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"10.0,0.0 80.58823529411765,70.58823529411765 80.58823529411765,107.33790767131957 10.0,36.74967237720192\" style=\"fill:#8B4903A0;stroke-width:0\"/>\n\n  <!-- Horizontal lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"50\" y2=\"0\" style=\"stroke-width:2\" />\n  <line x1=\"13\" y1=\"3\" x2=\"54\" y2=\"3\" />\n  <line x1=\"17\" y1=\"7\" x2=\"57\" y2=\"7\" />\n  <line x1=\"21\" y1=\"11\" x2=\"61\" y2=\"11\" />\n  <line x1=\"24\" y1=\"14\" x2=\"65\" y2=\"14\" />\n  <line x1=\"28\" y1=\"18\" x2=\"69\" y2=\"18\" />\n  <line x1=\"32\" y1=\"22\" x2=\"72\" y2=\"22\" />\n  <line x1=\"36\" y1=\"26\" x2=\"76\" y2=\"26\" />\n  <line x1=\"39\" y1=\"29\" x2=\"80\" y2=\"29\" />\n  <line x1=\"43\" y1=\"33\" x2=\"83\" y2=\"33\" />\n  <line x1=\"47\" y1=\"37\" x2=\"87\" y2=\"37\" />\n  <line x1=\"50\" y1=\"40\" x2=\"91\" y2=\"40\" />\n  <line x1=\"54\" y1=\"44\" x2=\"95\" y2=\"44\" />\n  <line x1=\"58\" y1=\"48\" x2=\"98\" y2=\"48\" />\n  <line x1=\"62\" y1=\"52\" x2=\"102\" y2=\"52\" />\n  <line x1=\"65\" y1=\"55\" x2=\"106\" y2=\"55\" />\n  <line x1=\"69\" y1=\"59\" x2=\"109\" y2=\"59\" />\n  <line x1=\"73\" y1=\"63\" x2=\"113\" y2=\"63\" />\n  <line x1=\"76\" y1=\"66\" x2=\"117\" y2=\"66\" />\n  <line x1=\"80\" y1=\"70\" x2=\"121\" y2=\"70\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"10\" y1=\"0\" x2=\"80\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"50\" y1=\"0\" x2=\"121\" y2=\"70\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"10.0,0.0 50.54304432207459,0.0 121.13127961619224,70.58823529411765 80.58823529411765,70.58823529411765\" style=\"fill:#8B4903A0;stroke-width:0\"/>\n\n  <!-- Horizontal lines -->\n  <line x1=\"80\" y1=\"70\" x2=\"121\" y2=\"70\" style=\"stroke-width:2\" />\n  <line x1=\"80\" y1=\"107\" x2=\"121\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Vertical lines -->\n  <line x1=\"80\" y1=\"70\" x2=\"80\" y2=\"107\" style=\"stroke-width:2\" />\n  <line x1=\"121\" y1=\"70\" x2=\"121\" y2=\"107\" style=\"stroke-width:2\" />\n\n  <!-- Colored Rectangle -->\n  <polygon points=\"80.58823529411765,70.58823529411765 121.13127961619224,70.58823529411765 121.13127961619224,107.33790767131957 80.58823529411765,107.33790767131957\" style=\"fill:#ECB172A0;stroke-width:0\"/>\n\n  <!-- Text -->\n  <text x=\"100.859757\" y=\"127.337908\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" >1440</text>\n  <text x=\"141.131280\" y=\"88.963071\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" transform=\"rotate(-90,141.131280,88.963071)\">720</text>\n  <text x=\"35.294118\" y=\"92.043790\" font-size=\"1.0rem\" font-weight=\"100\" text-anchor=\"middle\" transform=\"rotate(45,35.294118,92.043790)\">9928</text>\n</svg>\n</td>\n</tr>\n</table></div></li></ul></div></li><li class='xr-section-item'><input id='section-cf5df5c2-9fbe-4728-974c-8ec081928291' class='xr-section-summary-in' type='checkbox'  ><label for='section-cf5df5c2-9fbe-4728-974c-8ec081928291' class='xr-section-summary' >Attributes: <span>(44)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><dl class='xr-attrs'><dt><span>Conventions :</span></dt><dd>CF-1.6</dd><dt><span>Metadata_Conventions :</span></dt><dd>Unidata Dataset Discovery v1.0</dd><dt><span>cdm_data_type :</span></dt><dd>Grid</dd><dt><span>comment :</span></dt><dd>Sea Surface Height measured by Altimetry and derived variables</dd><dt><span>contact :</span></dt><dd>servicedesk.cmems@mercator-ocean.eu</dd><dt><span>creator_email :</span></dt><dd>servicedesk.cmems@mercator-ocean.eu</dd><dt><span>creator_name :</span></dt><dd>CMEMS - Sea Level Thematic Assembly Center</dd><dt><span>creator_url :</span></dt><dd>http://marine.copernicus.eu</dd><dt><span>date_created :</span></dt><dd>2019-01-17T16:58:50Z</dd><dt><span>date_issued :</span></dt><dd>2019-01-17T16:58:50Z</dd><dt><span>date_modified :</span></dt><dd>2019-01-17T16:58:50Z</dd><dt><span>geospatial_lat_max :</span></dt><dd>89.875</dd><dt><span>geospatial_lat_min :</span></dt><dd>-89.875</dd><dt><span>geospatial_lat_resolution :</span></dt><dd>0.25</dd><dt><span>geospatial_lat_units :</span></dt><dd>degrees_north</dd><dt><span>geospatial_lon_max :</span></dt><dd>359.875</dd><dt><span>geospatial_lon_min :</span></dt><dd>0.125</dd><dt><span>geospatial_lon_resolution :</span></dt><dd>0.25</dd><dt><span>geospatial_lon_units :</span></dt><dd>degrees_east</dd><dt><span>geospatial_vertical_max :</span></dt><dd>0.0</dd><dt><span>geospatial_vertical_min :</span></dt><dd>0.0</dd><dt><span>geospatial_vertical_positive :</span></dt><dd>down</dd><dt><span>geospatial_vertical_resolution :</span></dt><dd>point</dd><dt><span>geospatial_vertical_units :</span></dt><dd>m</dd><dt><span>history :</span></dt><dd>2019-01-17 16:58:51Z: Creation</dd><dt><span>institution :</span></dt><dd>CLS, CNES</dd><dt><span>keywords :</span></dt><dd>Oceans &gt; Ocean Topography &gt; Sea Surface Height</dd><dt><span>keywords_vocabulary :</span></dt><dd>NetCDF COARDS Climate and Forecast Standard Names</dd><dt><span>license :</span></dt><dd>http://marine.copernicus.eu/web/27-service-commitments-and-licence.php</dd><dt><span>platform :</span></dt><dd>ERS-1, Topex/Poseidon,</dd><dt><span>processing_level :</span></dt><dd>L4</dd><dt><span>product_version :</span></dt><dd>2019</dd><dt><span>project :</span></dt><dd>COPERNICUS MARINE ENVIRONMENT MONITORING SERVICE (CMEMS)</dd><dt><span>references :</span></dt><dd>http://marine.copernicus.eu</dd><dt><span>software_version :</span></dt><dd>6.2_DUACS_DT2018_baseline</dd><dt><span>source :</span></dt><dd>Altimetry measurements</dd><dt><span>ssalto_duacs_comment :</span></dt><dd>The reference mission used for the altimeter inter-calibration processing is Topex/Poseidon between 1993-01-01 and 2002-04-23, Jason-1 between 2002-04-24 and 2008-10-18, OSTM/Jason-2 between 2008-10-19 and 2016-06-25, Jason-3 since 2016-06-25.</dd><dt><span>standard_name_vocabulary :</span></dt><dd>NetCDF Climate and Forecast (CF) Metadata Convention Standard Name Table v37</dd><dt><span>summary :</span></dt><dd>SSALTO/DUACS Delayed-Time Level-4 sea surface height and derived variables measured by multi-satellite altimetry observations over Global Ocean.</dd><dt><span>time_coverage_duration :</span></dt><dd>P1D</dd><dt><span>time_coverage_end :</span></dt><dd>1993-01-01T00:00:00Z</dd><dt><span>time_coverage_resolution :</span></dt><dd>P1D</dd><dt><span>time_coverage_start :</span></dt><dd>1993-01-01T00:00:00Z</dd><dt><span>title :</span></dt><dd>DT merged all satellites Global Ocean Gridded SSALTO/DUACS Sea Surface Height L4 product and derived variables</dd></dl></div></li></ul></div></div>\n\n\n\n### Compute EKE:\n\n\\begin{equation}\nEKE = \\frac{1}{2} \\left(u'^2+v'^2\\right)\n\\end{equation}\n\nThe provided $u'$ and $v'$ from AVISO is an anomaly from 1993-2012. Changing this period does not affect the main result of the study.\n\n\n```python\nEKE = 1/2 * (dataset_AVISO.ugosa**2 + dataset_AVISO.vgosa**2)\n```\n\nRechunk dataset\n\n\n```python\nEKE_rechunk = EKE.chunk({\"latitude\": 100, \"longitude\": 100,'time':357})\n```\n\nCoarsen dataset to a 1 degree grid.\n\n\n```python\nEKE_coarsen = EKE_rechunk.coarsen({'latitude':4,'longitude':4}).mean()\n```\n\nRoll over 12 months:\n\n\n```python\nEKE_rolled = EKE_coarsen.rolling(time=365,center=True).mean().compute() \n# This computation requires ~ 50 GB of RAM, to decrease the usage of RAM, \n# reduce the size of the chunks.\n```\n\n\n```python\nEKE_rolled = EKE_rolled.to_dataset(name=\"EKE\").rename({'latitude':'lat','longitude':'lon'})\n```\n\n\n```python\nEKE_rolled\n```\n\n\n\n\n<div><svg style=\"position: absolute; width: 0; height: 0; overflow: hidden\">\n<defs>\n<symbol id=\"icon-database\" viewBox=\"0 0 32 32\">\n<path d=\"M16 0c-8.837 0-16 2.239-16 5v4c0 2.761 7.163 5 16 5s16-2.239 16-5v-4c0-2.761-7.163-5-16-5z\"></path>\n<path d=\"M16 17c-8.837 0-16-2.239-16-5v6c0 2.761 7.163 5 16 5s16-2.239 16-5v-6c0 2.761-7.163 5-16 5z\"></path>\n<path d=\"M16 26c-8.837 0-16-2.239-16-5v6c0 2.761 7.163 5 16 5s16-2.239 16-5v-6c0 2.761-7.163 5-16 5z\"></path>\n</symbol>\n<symbol id=\"icon-file-text2\" viewBox=\"0 0 32 32\">\n<path d=\"M28.681 7.159c-0.694-0.947-1.662-2.053-2.724-3.116s-2.169-2.030-3.116-2.724c-1.612-1.182-2.393-1.319-2.841-1.319h-15.5c-1.378 0-2.5 1.121-2.5 2.5v27c0 1.378 1.122 2.5 2.5 2.5h23c1.378 0 2.5-1.122 2.5-2.5v-19.5c0-0.448-0.137-1.23-1.319-2.841zM24.543 5.457c0.959 0.959 1.712 1.825 2.268 2.543h-4.811v-4.811c0.718 0.556 1.584 1.309 2.543 2.268zM28 29.5c0 0.271-0.229 0.5-0.5 0.5h-23c-0.271 0-0.5-0.229-0.5-0.5v-27c0-0.271 0.229-0.5 0.5-0.5 0 0 15.499-0 15.5 0v7c0 0.552 0.448 1 1 1h7v19.5z\"></path>\n<path d=\"M23 26h-14c-0.552 0-1-0.448-1-1s0.448-1 1-1h14c0.552 0 1 0.448 1 1s-0.448 1-1 1z\"></path>\n<path d=\"M23 22h-14c-0.552 0-1-0.448-1-1s0.448-1 1-1h14c0.552 0 1 0.448 1 1s-0.448 1-1 1z\"></path>\n<path d=\"M23 18h-14c-0.552 0-1-0.448-1-1s0.448-1 1-1h14c0.552 0 1 0.448 1 1s-0.448 1-1 1z\"></path>\n</symbol>\n</defs>\n</svg>\n<style>/* CSS stylesheet for displaying xarray objects in jupyterlab.\n *\n */\n\n:root {\n  --xr-font-color0: var(--jp-content-font-color0, rgba(0, 0, 0, 1));\n  --xr-font-color2: var(--jp-content-font-color2, rgba(0, 0, 0, 0.54));\n  --xr-font-color3: var(--jp-content-font-color3, rgba(0, 0, 0, 0.38));\n  --xr-border-color: var(--jp-border-color2, #e0e0e0);\n  --xr-disabled-color: var(--jp-layout-color3, #bdbdbd);\n  --xr-background-color: var(--jp-layout-color0, white);\n  --xr-background-color-row-even: var(--jp-layout-color1, white);\n  --xr-background-color-row-odd: var(--jp-layout-color2, #eeeeee);\n}\n\nhtml[theme=dark],\nbody.vscode-dark {\n  --xr-font-color0: rgba(255, 255, 255, 1);\n  --xr-font-color2: rgba(255, 255, 255, 0.54);\n  --xr-font-color3: rgba(255, 255, 255, 0.38);\n  --xr-border-color: #1F1F1F;\n  --xr-disabled-color: #515151;\n  --xr-background-color: #111111;\n  --xr-background-color-row-even: #111111;\n  --xr-background-color-row-odd: #313131;\n}\n\n.xr-wrap {\n  display: block;\n  min-width: 300px;\n  max-width: 700px;\n}\n\n.xr-text-repr-fallback {\n  /* fallback to plain text repr when CSS is not injected (untrusted notebook) */\n  display: none;\n}\n\n.xr-header {\n  padding-top: 6px;\n  padding-bottom: 6px;\n  margin-bottom: 4px;\n  border-bottom: solid 1px var(--xr-border-color);\n}\n\n.xr-header > div,\n.xr-header > ul {\n  display: inline;\n  margin-top: 0;\n  margin-bottom: 0;\n}\n\n.xr-obj-type,\n.xr-array-name {\n  margin-left: 2px;\n  margin-right: 10px;\n}\n\n.xr-obj-type {\n  color: var(--xr-font-color2);\n}\n\n.xr-sections {\n  padding-left: 0 !important;\n  display: grid;\n  grid-template-columns: 150px auto auto 1fr 20px 20px;\n}\n\n.xr-section-item {\n  display: contents;\n}\n\n.xr-section-item input {\n  display: none;\n}\n\n.xr-section-item input + label {\n  color: var(--xr-disabled-color);\n}\n\n.xr-section-item input:enabled + label {\n  cursor: pointer;\n  color: var(--xr-font-color2);\n}\n\n.xr-section-item input:enabled + label:hover {\n  color: var(--xr-font-color0);\n}\n\n.xr-section-summary {\n  grid-column: 1;\n  color: var(--xr-font-color2);\n  font-weight: 500;\n}\n\n.xr-section-summary > span {\n  display: inline-block;\n  padding-left: 0.5em;\n}\n\n.xr-section-summary-in:disabled + label {\n  color: var(--xr-font-color2);\n}\n\n.xr-section-summary-in + label:before {\n  display: inline-block;\n  content: '\u25ba';\n  font-size: 11px;\n  width: 15px;\n  text-align: center;\n}\n\n.xr-section-summary-in:disabled + label:before {\n  color: var(--xr-disabled-color);\n}\n\n.xr-section-summary-in:checked + label:before {\n  content: '\u25bc';\n}\n\n.xr-section-summary-in:checked + label > span {\n  display: none;\n}\n\n.xr-section-summary,\n.xr-section-inline-details {\n  padding-top: 4px;\n  padding-bottom: 4px;\n}\n\n.xr-section-inline-details {\n  grid-column: 2 / -1;\n}\n\n.xr-section-details {\n  display: none;\n  grid-column: 1 / -1;\n  margin-bottom: 5px;\n}\n\n.xr-section-summary-in:checked ~ .xr-section-details {\n  display: contents;\n}\n\n.xr-array-wrap {\n  grid-column: 1 / -1;\n  display: grid;\n  grid-template-columns: 20px auto;\n}\n\n.xr-array-wrap > label {\n  grid-column: 1;\n  vertical-align: top;\n}\n\n.xr-preview {\n  color: var(--xr-font-color3);\n}\n\n.xr-array-preview,\n.xr-array-data {\n  padding: 0 5px !important;\n  grid-column: 2;\n}\n\n.xr-array-data,\n.xr-array-in:checked ~ .xr-array-preview {\n  display: none;\n}\n\n.xr-array-in:checked ~ .xr-array-data,\n.xr-array-preview {\n  display: inline-block;\n}\n\n.xr-dim-list {\n  display: inline-block !important;\n  list-style: none;\n  padding: 0 !important;\n  margin: 0;\n}\n\n.xr-dim-list li {\n  display: inline-block;\n  padding: 0;\n  margin: 0;\n}\n\n.xr-dim-list:before {\n  content: '(';\n}\n\n.xr-dim-list:after {\n  content: ')';\n}\n\n.xr-dim-list li:not(:last-child):after {\n  content: ',';\n  padding-right: 5px;\n}\n\n.xr-has-index {\n  font-weight: bold;\n}\n\n.xr-var-list,\n.xr-var-item {\n  display: contents;\n}\n\n.xr-var-item > div,\n.xr-var-item label,\n.xr-var-item > .xr-var-name span {\n  background-color: var(--xr-background-color-row-even);\n  margin-bottom: 0;\n}\n\n.xr-var-item > .xr-var-name:hover span {\n  padding-right: 5px;\n}\n\n.xr-var-list > li:nth-child(odd) > div,\n.xr-var-list > li:nth-child(odd) > label,\n.xr-var-list > li:nth-child(odd) > .xr-var-name span {\n  background-color: var(--xr-background-color-row-odd);\n}\n\n.xr-var-name {\n  grid-column: 1;\n}\n\n.xr-var-dims {\n  grid-column: 2;\n}\n\n.xr-var-dtype {\n  grid-column: 3;\n  text-align: right;\n  color: var(--xr-font-color2);\n}\n\n.xr-var-preview {\n  grid-column: 4;\n}\n\n.xr-var-name,\n.xr-var-dims,\n.xr-var-dtype,\n.xr-preview,\n.xr-attrs dt {\n  white-space: nowrap;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  padding-right: 10px;\n}\n\n.xr-var-name:hover,\n.xr-var-dims:hover,\n.xr-var-dtype:hover,\n.xr-attrs dt:hover {\n  overflow: visible;\n  width: auto;\n  z-index: 1;\n}\n\n.xr-var-attrs,\n.xr-var-data {\n  display: none;\n  background-color: var(--xr-background-color) !important;\n  padding-bottom: 5px !important;\n}\n\n.xr-var-attrs-in:checked ~ .xr-var-attrs,\n.xr-var-data-in:checked ~ .xr-var-data {\n  display: block;\n}\n\n.xr-var-data > table {\n  float: right;\n}\n\n.xr-var-name span,\n.xr-var-data,\n.xr-attrs {\n  padding-left: 25px !important;\n}\n\n.xr-attrs,\n.xr-var-attrs,\n.xr-var-data {\n  grid-column: 1 / -1;\n}\n\ndl.xr-attrs {\n  padding: 0;\n  margin: 0;\n  display: grid;\n  grid-template-columns: 125px auto;\n}\n\n.xr-attrs dt,\n.xr-attrs dd {\n  padding: 0;\n  margin: 0;\n  float: left;\n  padding-right: 10px;\n  width: auto;\n}\n\n.xr-attrs dt {\n  font-weight: normal;\n  grid-column: 1;\n}\n\n.xr-attrs dt:hover span {\n  display: inline-block;\n  background: var(--xr-background-color);\n  padding-right: 10px;\n}\n\n.xr-attrs dd {\n  grid-column: 2;\n  white-space: pre-wrap;\n  word-break: break-all;\n}\n\n.xr-icon-database,\n.xr-icon-file-text2 {\n  display: inline-block;\n  vertical-align: middle;\n  width: 1em;\n  height: 1.5em !important;\n  stroke-width: 0;\n  stroke: currentColor;\n  fill: currentColor;\n}\n</style><pre class='xr-text-repr-fallback'>&lt;xarray.Dataset&gt;\nDimensions:  (lat: 180, lon: 360, time: 9928)\nCoordinates:\n  * time     (time) datetime64[ns] 1993-01-01 1993-01-02 ... 2020-03-07\n  * lat      (lat) float32 -89.5 -88.5 -87.5 -86.5 -85.5 ... 86.5 87.5 88.5 89.5\n  * lon      (lon) float32 0.5 1.5 2.5 3.5 4.5 ... 355.5 356.5 357.5 358.5 359.5\nData variables:\n    EKE      (time, lat, lon) float64 nan nan nan nan nan ... nan nan nan nan</pre><div class='xr-wrap' hidden><div class='xr-header'><div class='xr-obj-type'>xarray.Dataset</div></div><ul class='xr-sections'><li class='xr-section-item'><input id='section-5b488a8b-6677-4dc1-8337-2ed7b1866bf9' class='xr-section-summary-in' type='checkbox' disabled ><label for='section-5b488a8b-6677-4dc1-8337-2ed7b1866bf9' class='xr-section-summary'  title='Expand/collapse section'>Dimensions:</label><div class='xr-section-inline-details'><ul class='xr-dim-list'><li><span class='xr-has-index'>lat</span>: 180</li><li><span class='xr-has-index'>lon</span>: 360</li><li><span class='xr-has-index'>time</span>: 9928</li></ul></div><div class='xr-section-details'></div></li><li class='xr-section-item'><input id='section-e7e60457-0833-4b78-b8b8-6fb260bf26ec' class='xr-section-summary-in' type='checkbox'  checked><label for='section-e7e60457-0833-4b78-b8b8-6fb260bf26ec' class='xr-section-summary' >Coordinates: <span>(3)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><ul class='xr-var-list'><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>time</span></div><div class='xr-var-dims'>(time)</div><div class='xr-var-dtype'>datetime64[ns]</div><div class='xr-var-preview xr-preview'>1993-01-01 ... 2020-03-07</div><input id='attrs-3dac1a08-2301-4dfc-b3c3-172536c2b7e8' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-3dac1a08-2301-4dfc-b3c3-172536c2b7e8' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-5763a90a-36dc-4aff-80c7-c47ee718621d' class='xr-var-data-in' type='checkbox'><label for='data-5763a90a-36dc-4aff-80c7-c47ee718621d' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>axis :</span></dt><dd>T</dd><dt><span>long_name :</span></dt><dd>Time</dd><dt><span>standard_name :</span></dt><dd>time</dd></dl></div><div class='xr-var-data'><pre>array([&#x27;1993-01-01T00:00:00.000000000&#x27;, &#x27;1993-01-02T00:00:00.000000000&#x27;,\n       &#x27;1993-01-03T00:00:00.000000000&#x27;, ..., &#x27;2020-03-05T00:00:00.000000000&#x27;,\n       &#x27;2020-03-06T00:00:00.000000000&#x27;, &#x27;2020-03-07T00:00:00.000000000&#x27;],\n      dtype=&#x27;datetime64[ns]&#x27;)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>lat</span></div><div class='xr-var-dims'>(lat)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>-89.5 -88.5 -87.5 ... 88.5 89.5</div><input id='attrs-31a1a7d8-782d-4c93-9e8e-bb9eb21cc2c9' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-31a1a7d8-782d-4c93-9e8e-bb9eb21cc2c9' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-83019038-8420-4063-b5d3-4464e080519d' class='xr-var-data-in' type='checkbox'><label for='data-83019038-8420-4063-b5d3-4464e080519d' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([-89.5, -88.5, -87.5, -86.5, -85.5, -84.5, -83.5, -82.5, -81.5, -80.5,\n       -79.5, -78.5, -77.5, -76.5, -75.5, -74.5, -73.5, -72.5, -71.5, -70.5,\n       -69.5, -68.5, -67.5, -66.5, -65.5, -64.5, -63.5, -62.5, -61.5, -60.5,\n       -59.5, -58.5, -57.5, -56.5, -55.5, -54.5, -53.5, -52.5, -51.5, -50.5,\n       -49.5, -48.5, -47.5, -46.5, -45.5, -44.5, -43.5, -42.5, -41.5, -40.5,\n       -39.5, -38.5, -37.5, -36.5, -35.5, -34.5, -33.5, -32.5, -31.5, -30.5,\n       -29.5, -28.5, -27.5, -26.5, -25.5, -24.5, -23.5, -22.5, -21.5, -20.5,\n       -19.5, -18.5, -17.5, -16.5, -15.5, -14.5, -13.5, -12.5, -11.5, -10.5,\n        -9.5,  -8.5,  -7.5,  -6.5,  -5.5,  -4.5,  -3.5,  -2.5,  -1.5,  -0.5,\n         0.5,   1.5,   2.5,   3.5,   4.5,   5.5,   6.5,   7.5,   8.5,   9.5,\n        10.5,  11.5,  12.5,  13.5,  14.5,  15.5,  16.5,  17.5,  18.5,  19.5,\n        20.5,  21.5,  22.5,  23.5,  24.5,  25.5,  26.5,  27.5,  28.5,  29.5,\n        30.5,  31.5,  32.5,  33.5,  34.5,  35.5,  36.5,  37.5,  38.5,  39.5,\n        40.5,  41.5,  42.5,  43.5,  44.5,  45.5,  46.5,  47.5,  48.5,  49.5,\n        50.5,  51.5,  52.5,  53.5,  54.5,  55.5,  56.5,  57.5,  58.5,  59.5,\n        60.5,  61.5,  62.5,  63.5,  64.5,  65.5,  66.5,  67.5,  68.5,  69.5,\n        70.5,  71.5,  72.5,  73.5,  74.5,  75.5,  76.5,  77.5,  78.5,  79.5,\n        80.5,  81.5,  82.5,  83.5,  84.5,  85.5,  86.5,  87.5,  88.5,  89.5],\n      dtype=float32)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>lon</span></div><div class='xr-var-dims'>(lon)</div><div class='xr-var-dtype'>float32</div><div class='xr-var-preview xr-preview'>0.5 1.5 2.5 ... 357.5 358.5 359.5</div><input id='attrs-abbc13e2-3c23-4349-aef4-46da14e1d8ff' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-abbc13e2-3c23-4349-aef4-46da14e1d8ff' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-0f6c57bf-eeb1-43cd-bb70-086842c8d03f' class='xr-var-data-in' type='checkbox'><label for='data-0f6c57bf-eeb1-43cd-bb70-086842c8d03f' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([  0.5,   1.5,   2.5, ..., 357.5, 358.5, 359.5], dtype=float32)</pre></div></li></ul></div></li><li class='xr-section-item'><input id='section-a43b3029-187e-4394-aa1d-0a6586cac2de' class='xr-section-summary-in' type='checkbox'  checked><label for='section-a43b3029-187e-4394-aa1d-0a6586cac2de' class='xr-section-summary' >Data variables: <span>(1)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><ul class='xr-var-list'><li class='xr-var-item'><div class='xr-var-name'><span>EKE</span></div><div class='xr-var-dims'>(time, lat, lon)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>nan nan nan nan ... nan nan nan nan</div><input id='attrs-ad6cf549-bede-4254-91c6-9227bfaed20f' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-ad6cf549-bede-4254-91c6-9227bfaed20f' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-97e8a6ad-16b8-46de-8544-f7952b690bc6' class='xr-var-data-in' type='checkbox'><label for='data-97e8a6ad-16b8-46de-8544-f7952b690bc6' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([[[nan, nan, nan, ..., nan, nan, nan],\n        [nan, nan, nan, ..., nan, nan, nan],\n        [nan, nan, nan, ..., nan, nan, nan],\n        ...,\n        [nan, nan, nan, ..., nan, nan, nan],\n        [nan, nan, nan, ..., nan, nan, nan],\n        [nan, nan, nan, ..., nan, nan, nan]],\n\n       [[nan, nan, nan, ..., nan, nan, nan],\n        [nan, nan, nan, ..., nan, nan, nan],\n        [nan, nan, nan, ..., nan, nan, nan],\n        ...,\n        [nan, nan, nan, ..., nan, nan, nan],\n        [nan, nan, nan, ..., nan, nan, nan],\n        [nan, nan, nan, ..., nan, nan, nan]],\n\n       [[nan, nan, nan, ..., nan, nan, nan],\n        [nan, nan, nan, ..., nan, nan, nan],\n        [nan, nan, nan, ..., nan, nan, nan],\n        ...,\n...\n        ...,\n        [nan, nan, nan, ..., nan, nan, nan],\n        [nan, nan, nan, ..., nan, nan, nan],\n        [nan, nan, nan, ..., nan, nan, nan]],\n\n       [[nan, nan, nan, ..., nan, nan, nan],\n        [nan, nan, nan, ..., nan, nan, nan],\n        [nan, nan, nan, ..., nan, nan, nan],\n        ...,\n        [nan, nan, nan, ..., nan, nan, nan],\n        [nan, nan, nan, ..., nan, nan, nan],\n        [nan, nan, nan, ..., nan, nan, nan]],\n\n       [[nan, nan, nan, ..., nan, nan, nan],\n        [nan, nan, nan, ..., nan, nan, nan],\n        [nan, nan, nan, ..., nan, nan, nan],\n        ...,\n        [nan, nan, nan, ..., nan, nan, nan],\n        [nan, nan, nan, ..., nan, nan, nan],\n        [nan, nan, nan, ..., nan, nan, nan]]])</pre></div></li></ul></div></li><li class='xr-section-item'><input id='section-e621dbfe-8bcc-49ac-bcb1-e8bbd011b0e5' class='xr-section-summary-in' type='checkbox' disabled ><label for='section-e621dbfe-8bcc-49ac-bcb1-e8bbd011b0e5' class='xr-section-summary'  title='Expand/collapse section'>Attributes: <span>(0)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><dl class='xr-attrs'></dl></div></li></ul></div></div>\n\n\n\n### Add metadata\n\n\n```python\nEKE_rolled.attrs['title'] = \"Eddy Kinetic Energy\"\nEKE_rolled.attrs['Description'] = \"\"\"Eddy Kinetic Energy computed from AVISO+ altimetry products.\"\"\"\nEKE_rolled.attrs['Publication'] = \"Dataset created for Mart\u00ednez-Moreno, J. et. al. 2020: \\n 'Global changes in oceanic mesoscale currents over the satellite altimetry record'\"\nEKE_rolled.attrs['Author'] = \"Josu\u00e9 Mart\u00ednez-Moreno\"\nEKE_rolled.attrs['Contact'] = \"josue.martinezmoreno@anu.edu.au\"\n\nEKE_rolled.attrs['Created date'] = datetime.datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\")\n\ncounter = 0\nunits = [r\"$m^2s^{-2}$\"]\nnames = [\"EKE\"]\nlong_names = [\"Eddy Kinetic Energy\"]\n\nEKE_rolled['EKE'].attrs['units'] = units[counter]\nEKE_rolled['EKE'].attrs['name'] = names[counter]\nEKE_rolled['EKE'].attrs['long_name'] = long_names[counter]\n\nEKE_rolled['EKE'].attrs['missing_value'] = np.nan\nEKE_rolled['EKE'].attrs['valid_min'] = np.nanmin(EKE_rolled['EKE'])\nEKE_rolled['EKE'].attrs['valid_max'] = np.nanmax(EKE_rolled['EKE'])\nEKE_rolled['EKE'].attrs['valid_range'] = [np.nanmin(EKE_rolled['EKE']),np.nanmax(EKE_rolled['EKE'])]\n```\n\n## Store netCDF\n\n\n```python\ncomp = dict(zlib=True, complevel=5)\nencoding = {var: comp for var in EKE_rolled.data_vars}\n\nEKE_rolled.to_netcdf('../datasets/EKE_timeseries.nc', encoding=encoding)\n```\n", "meta": {"hexsha": "e40b075107fb5670b8553ee45601035aa22ad90f", "size": 124661, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "pre-processing/AVISO+_to_EKE_timeseries.ipynb", "max_stars_repo_name": "josuemtzmo/EKE_SST_trends", "max_stars_repo_head_hexsha": "cd3581628eb54f451f1c55ca7390c08377479042", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-08-24T23:44:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T01:43:45.000Z", "max_issues_repo_path": "pre-processing/AVISO+_to_EKE_timeseries.ipynb", "max_issues_repo_name": "josuemtzmo/EKE_SST_trends", "max_issues_repo_head_hexsha": "cd3581628eb54f451f1c55ca7390c08377479042", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-10-16T20:57:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T08:28:30.000Z", "max_forks_repo_path": "pre-processing/AVISO+_to_EKE_timeseries.ipynb", "max_forks_repo_name": "josuemtzmo/EKE_SST_trends", "max_forks_repo_head_hexsha": "cd3581628eb54f451f1c55ca7390c08377479042", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-08-24T23:38:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T07:37:13.000Z", "avg_line_length": 60.1645752896, "max_line_length": 3934, "alphanum_fraction": 0.503469409, "converted": true, "num_tokens": 36316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3557748798522984, "lm_q2_score": 0.055005286744338196, "lm_q1q2_score": 0.019569499282708142}}
{"text": "# Introducci\u00f3n al Aprendizaje por Refuerzos\n\n### Curso Aprendizaje por Refuerzos, Diplomatura en Ciencia de Datos, Aprendizaje Autom\u00e1tico y sus Aplicaciones\n\n### FaMAF, 2019\n\n#### Agenda\n\n* Presentaci\u00f3n Docentes\n* Introducci\u00f3n. Diferencias entre Aprendizaje Supervisado, No Supervisado y Por Refuerzos\n* Modelo Agente Entorno. Agente Situado. Arquitectura Actor-Cr\u00edtico.\n* Aprendizaje por Refuerzos. Elementos. Ciclo del Aprendizaje por Refuerzos. Definici\u00f3n Formal.\n* Procesos de Decisi\u00f3n de Markov. Funci\u00f3n de Valor. Ecuaci\u00f3n de Bellman. Optimalidad.\n* Diferencias Temporales\n* SARSA y Q-Learning\n\n## Docentes\n\n* Jorge A. Palombarini\n* Juan Cruz Barsce\n* Ezequiel Beccar\u00eda\n\n## P\u00e1gina y Libro Sutton\n\nhttp://incompleteideas.net/\n\nhttps://drive.google.com/file/d/1opPSz5AZ_kVa1uWOdOiveNiBFiEOHjkG/view\n\n## Introducci\u00f3n: Diferencias entre Aprendizaje Supervisado, No Supervisado y Por Refuerzos\n\n\n\n## Entidad Inteligente -> Agente Situado\n\n* La idea de aprender por interacci\u00f3n con nuestro entorno es quiz\u00e1s la primera en aparecer cuando pensamos acerca de la naturaleza del aprendizaje.\n\n* Por ejemplo, cuando un ni\u00f1o juega, mueve sus brazos, o mira alrededor, no tiene un \"maestro\" explicito, pero posee una conexion sensorial y motora con su entorno.\n\n* El ejercicio de dicha conexi\u00f3n produce informaci\u00f3n acerca de la relaci\u00f3n causa-efecto y las consecuencias de las acciones que lleva a cabo, y respecto de qu\u00e9 hacer de manera tal de lograr objetivos. As\u00ed, *aprender por interacci\u00f3n* es una idea fundacional de muchas teor\u00edas del aprendizaje y la inteligencia.\n\n*  En este curso, se explorar\u00e1 un **enfoque computacional dirigido por objetivos para *aprender por interacci\u00f3n***: el **Aprendizaje por Refuerzos (Reinforcement Learning)**.\n\n## Agent-Environment Framework\n\n* El desarrollo de la inteligencia requiere que la entidad o el agente est\u00e9 situada/o en un entorno **(Measuring universal intelligence: Towards an anytime intelligence test, Hernandez-Orallo & Dowe, Artificial Intelligence, 2010).**\n\n\n* El agente y su entorno interact\u00faan a trav\u00e9s de la ejecuci\u00f3n de acciones, observaci\u00f3n de estados y se\u00f1ales de reward. La inteligencia tendr\u00e1 efecto s\u00f3lo si el agente tiene claramente definidos objetivos o metas que persigue activamente mientras ocurre la interacci\u00f3n.\n\n\n## Aprendizaje por Refuerzos (Reinforcement Learning)\n\n* **Reinforcement learning** consiste en aprender **qu\u00e9 hacer** -mapear situaciones a acciones- de manera tal de **maximizar** una se\u00f1al num\u00e9rica de recompensa. \n\n* Al aprendiz (**agente**) no se le especifica cu\u00e1les acciones ejecutar, sino que debe descubrir a trav\u00e9s de ***prueba y error*** cu\u00e1les acciones producen la mayor cantidad de recompensa acumulada. En los casos m\u00e1s interesantes, las acciones pueden afectar no solo la recompensa inmediata, sino solamente el estado, recibi\u00e9ndose una recompensa s\u00f3lo en algunos estados o bien al final del episodio (***Delayed-reward***).\n\n* Se conoce simultaneamente como RL al problema de **aprender por interacci\u00f3n**, a las **m\u00e9todos de soluci\u00f3n** de dicho problema, y al **\u00e1rea de la IA que estudia el problema y los m\u00e9todos de soluci\u00f3n**.\n\n* El problema de RL puede ser formalizado empleando **Procesos de Decisi\u00f3n de Markov**.\n\n* La toma de decisiones secuencial involucra aprender sobre nuestro entorno y elegir acciones que maximizan el retorno esperado. El RL computacional, inspirado por estas ideas, las formalizo y produjo un impacto importante en rob\u00f3tica, machine learning y neurociencias.\n\n> El Aprendizaje por Refuerzos (RL) consiste en un agente que se encuentra en alg\u00fan estado $s \\in S$ inmerso en un entorno $E$ y ejecuta acciones $a \\in A$ en busca de una meta. El agente puede ser modelado formalmente como una funci\u00f3n f, que toma un  historial de interacci\u00f3n como entrada, y devuelve una acci\u00f3n a tomar. Una manera conveniente para representar el agente es una medida de probabilidad sobre el set A de acciones, en base a un historial de interacci\u00f3n: $$ f(a_{n}|s_{1}a_{1} r_{2} s_{2}a_{2}...r_{n}s_{n}) $$ que representa la probabilidad de la acci\u00f3n a en el ciclo n dado un historial de interacci\u00f3n.\n\n\n\n* Problema RL: ***\u00bfC\u00f3mo el agente produce la distribuci\u00f3n de probabilidad sobre las acciones?***\n\n* ***Dilema de exploraci\u00f3n - explotaci\u00f3n***: debido a que el Agente no recibe ejemplos de entrenamiento, debe probar alternativas, procesar los resultados de sus acciones y modificar su comportamiento en alg\u00fan sentido. \u00bfCu\u00e1ndo explotar este conocimiento vs. cu\u00e1ndo probar nuevas estrategias?\n\n## Arquitectura Actor-Cr\u00edtico\n\n\n## Elementos del Aprendizaje por Refuerzos\n\n\n* **Policy (Pol\u00edtica): **\n\nUna pol\u00edtica define la manera de comportarse de un agente, en cualquier momento de tiempo dado. Basicamente, es un mapeo de un estado o percepci\u00f3n s a una acci\u00f3n a, pudiendo ser estoc\u00e1sticas.\n\n* **Reward Function (Funci\u00f3n de Recompensa)**\n\nDefine cuantitativamente el objetivo del agente. Es un mapeo de un par estado-acci\u00f3n a un n\u00famero real que indica \"cu\u00e1n deseable\" es ejecutar dicha acci\u00f3n en ese estado. Asimismo, el \u00fanico objetivo del agente es maximizar la recompensa total que recibe a lo large del tiempo. Cabe mencionar que, si bien la funci\u00f3n de reward no puede ser alterada por el agente, provee las bases para cambiar la pol\u00edtica del mismo.\n\n* **Value function (Funci\u00f3n de Valor)**\n\nLa funci\u00f3n de valor se diferencia de la funci\u00f3n de reward en el sentido de que indica \"cu\u00e1n deseable\" es, a largo plazo, ejecutar una acci\u00f3n en un determinado estado. As\u00ed, el valor de un estado *s* es la cantidad total de reward que el agente espera obtener a futuro comenzando la interacci\u00f3n en el estado *s*.\n\n* **Environment (Entorno)**\n\nEl entorno se encuentra constitutido por todo aquel elemento (real o simulado) que el agente no puede controlar. Es con qui\u00e9n el agente interact\u00faa a partir de la ejecuci\u00f3n de acciones de control.\n\n## Ciclo del Aprendizaje por Refuerzos\n\n\n\n\n\n### Definici\u00f3n formal\n\n* Si el problema de RL dado tiene un conjunto finito de estados y acciones y satisface la propiedad de Markov entonces puede definirse como un Proceso de Decisi\u00f3n de Markov\n\n\\begin{equation}\nMDPFinito = (S, A, P(.), R(.), \u03b3)\n\\end{equation}\n\ndonde\n\n$$ S = {s_{1}, s_{2}, ..., s_{n}} $$\nes un conjunto finito de estados.\n\n\n\n\n\n$$ A = {a_{1}, a_{2}, ..., a_{m}} $$\nes un conjunto finito de acciones.\n$$ P_{a}(s,s') = P(s_{t+1} = s | s_{t} = s, a_{t} = a) $$ \nes la probabilidad de que la acci\u00f3n a tomada en tiempo t y en estado s lleve al agente al estado s' en tiempo t+1\n$$ R_{a}(s,s') $$\nes la recompensa inmediata recibido tras transicionar, luego de tomar la acci\u00f3n a, desde el estado s al estado s'\n$$\\gamma \\in  [0,1]$$ \nes el factor de descuento, representando la diferencia en la importancia de la recompensa a corto plazo vs la recompensa a largo plazo.\n\n\n\n\n* Un **episodio** (instancia) de este MDP forma una secuencia finita \n$$s_{0}, a_{0}, r_{1}, s_{1}, a_{1}, r_{2}, s_{2}, ... , s_{n-1}, a_{n-1}, r_{n}, s_{n} $$ \ndonde $$s_{n}$$\nes un estado final (o n es el tiempo de corte).\n\n* La recompensa total del episodio est\u00e1 dado por \n$$ R = r_{1} + r_{2} + ... + r_{n} $$\n\n* En consecuencia, la recompensa a futuro partiendo del tiempo $t$ est\u00e1 dado por \n$$R_{t} = r_{t} + r_{t+1} + ... $$\n\n* Hay que considerar que el ambiente es estoc\u00e1stico en la mayor parte de los entornos reales y, por tanto, la recompensa suele diverger mientras m\u00e1s alejado se encuentre el instante de tiempo considerado. Es por esto que se utiliza un par\u00e1metro $\u03b3$ llamado _factor de descuento_, para descontar el valor de las recompensas futuras. De esta manera,\n\n\\begin{equation} R_{t} = r_{t} + \u03b3r_{t+1} + \u03b3^2r_{t+2} + \u03b3^3r_{t+3} + ... = r_{t} + \u03b3(r_{t+1} + \u03b3r_{t+2} + \u03b3^2r_{t+3} ...) = r_{t} + \u03b3R_{t+1} \\end{equation}\n\n* Si utilizamos $\u03b3=0$, el agente priorizar\u00e1 s\u00f3lo la recompensa inmediata, mientras que $\\gamma=1$ har\u00e1 que considere todas los recompensas de la misma manera, independientemente del momento en donde las reciba.\n\n\n\n* Dado un Proceso de Decisi\u00f3n de Markov, una Pol\u00edtica (determin\u00edstica) es una funci\u00f3n $\\pi$ que a partir de un estado $s \\in S$, devuelve como resultado una acci\u00f3n $a \\in A$. Una pol\u00edtica estoc\u00e1stica devuelve, para un estado $s$ y una acci\u00f3n $a$, una probabilidad.\n\n## Procesos de Decisi\u00f3n de Markov\n\n**Resolver un problema de decisi\u00f3n modelado como un PDM implica encontrar los valores de la funci\u00f3n de valor V**\n\n### Funci\u00f3n de Valor\n\n* El valor de un estado es el retorno esperado por el agente, comenzando la interacci\u00f3n en dicho estado, dependiendo de la pol\u00edtica ejecutada por el agente.\n\n\n\n* El valor de la ejecuci\u00f3n de una acci\u00f3n en un estado es el retorno esperado por el agente, comenzando la interacci\u00f3n en dicho estado a partir de la ejecuci\u00f3n de dicha acci\u00f3n, dependiendo de la pol\u00edtica ejecutada por el agente.\n\n\n\nUna propiedad fundamental de las funciones de valor es que satisfacen ciertas propiedades recursivas. Para cualquier pol\u00edtica  \u03c0 y cualquier estado s, V(s) y Q(s,a) pueden ser definidas recursivamente en t\u00e9rminos de la denominada *Ecuaci\u00f3n de Bellman* ** (Bellman, 1957) **\n\n### Ecuaci\u00f3n de Bellman\n\n* La idea b\u00e1sica es:\n\n\n\n* Entonces,\n\n\n\n* O, sin el operador de valor esperado:\n\n\n\nLa ecuaci\u00f3n anterior refleja el hecho de que el valor de un estado se encuentra definido en t\u00e9rminos de la recompensa inmediata y los valores de los estados siguientes ponderados en funci\u00f3n de las probabilidades de transici\u00f3n, y adicionalmente un factor de descuento.\n\n### Ecuaci\u00f3n de Optimalidad de Bellman\n\nLa Ecuaci\u00f3n de Optimalidad de Bellman refleja el hecho de que el Valor de un estado bajo la pol\u00edtica \u00f3ptima debe ser igual al retorno esperado para la mejor acci\u00f3n en dicho estado:\n\n\n\nAl mismo tiempo, la acci\u00f3n \u00f3ptima para un estado s dada la funci\u00f3n de valor, puede obtenerse mediante:\n\n\n\nLa pol\u00edtica anterior se denomina **Pol\u00edtica Greedy**, dado que selecciona la mejor acci\u00f3n para cada estado, teniendo en cuenta la funci\u00f3n de valor V(s). De manera an\u00e1loga, la funci\u00f3n de acci\u00f3n-valor \u00f3ptima puede expresarse como:\n\n\n\n\n\n## Ejemplo MDP y Pol\u00edticas (*)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\\(*) entorno de ejemplo basado en curso de Aprendizaje Profundo por Refuerzos, dictado por Juan G\u00f3mez Romero en la Escuela de Ciencias Inform\u00e1ticas 2019 - UBA\n\n## Actividad 1\n\n[RL Warm Up Lab!](lab_0_warmup_rl.ipynb)\n\n## Aproximaciones para el aprendizaje de V y Q mediante Soluciones Tabulares\n\n\n\n### Model Based vs. Model Free\n\n* Model-free aprende Q/V directamente y presenta muy baja complejidad computacional.\n\n* Model-based aprende T y R y usa un algoritmo de planning para encontrar la pol\u00edtica. Uso eficiente de los datos/experiencia. Alto costo computacional.\n\n## Aprendizaje por Diferencias Temporales (TD Learning).\n\n* La idea principal es actualizar una predicci\u00f3n de la funci\u00f3n de valor en base al cambio que existe en la misma de un momento al siguiente (**Diferencia Temporal o Temporal Difference**)\n\n\n* Los algoritmos de aprendizaje basados en TD se emplean en mayor medida para realizar el CONTROL respecto de las acciones que ejecuta un agente que interact\u00faa con su entorno. De esa manera, en lugar de aprender la funci\u00f3n de estado-valor **V**, se orientan al aprendizaje de la funci\u00f3n de acci\u00f3n-valor **Q**.\n\n* En particular, existen dos enfoques principales para realizar el aprendizaje de funciones **Q**, ambos considerando el trade-off exploraci\u00f3n/explotaci\u00f3n: **on-policy** y **off-policy**. En particular, los m\u00e9todos **on-policy** estiman $Q_{\u03c0}(s, a)$ para la pol\u00edtica \u03c0 que el agente se encuentra ejecutando, para todos los estados s y acciones a. \n\n* Dicha estimaci\u00f3n puede ser realizada empleando el mismo m\u00e9todo TD descripto anteriormente para actualizar $V_{\u03c0}$, an base a:\n\n\n\n## Trade-off exploraci\u00f3n explotaci\u00f3n\n\n* Es el dilema en que incurre el agente al momento de **elegir entre distintas acciones**.\n\n* Consiste en optar entre elegir una acci\u00f3n (a priori \u00f3ptima) cuyos efectos son conocidos, esperando obtener un resultado similar (_explotar_) o elegir otra (posiblemente no \u00f3ptima) cuyos efectos son desconocidos, pero que puede conducir a aprender m\u00e1s (_explorar_)?\n\n## SARSA: On-Policy TD Learning\n\n* El agente y su entorno interact\u00faan a trav\u00e9s de la ejecuci\u00f3n de acciones, observaci\u00f3n de estados y se\u00f1ales rewards. La inteligencia tendr\u00e1 efecto s\u00f3lo si el agente tiene claramente definidos objetivos o metas que persigue activamente mientras ocurre la interacci\u00f3n.\n\n\n\n## Actividad 2\n\n[Lab Introducci\u00f3n al RL](lab_1_intro_rl.ipynb)\n\n## Bootstrapping\n\n* Bootstrapping in RL puede entenderse como \"emplear uno o m\u00e1s valores estimados en la actualizaci\u00f3n del mismo tipo de valor estimado\".\n\n* En el caso de los m\u00e9todos TD:\n\n\n\n\n* Presenta la desventaja de estar sesgado hacia los valores iniciales de la funci\u00f3n de valor Q o V (Problema importante si empleamos estimadores, el sistema se autorreferencia)\n\n* Empleando trayectorias m\u00e1s largas (M\u00e9todos MC) tenemos el problema de la alta varianza -> Necesitamos mayor cantidad de ejemplos para converger\n\n\n\n## Q-Learning: Off-Policy TD Learning\n\n* Uno de los m\u00e1s importantes avances en RL fue el desarrollo del algoritmo **off-policy** conocido como Q-learning (Watkins, 1989). En su forma m\u00e1s simple, en Q-learning la actualizaci\u00f3n de la funci\u00f3n de acci\u00f3n-valor realizada se define por:\n\n\n\n* Es este caso, la funci\u00f3n de acci\u00f3n-valor Q aproxima directamente q\u2217, es decir, la funci\u00f3n de acci\u00f3n-valor correspondiente a la pol\u00edtica \u00f3ptima, independientemente de la pol\u00edtica seguida por el agente (de ah\u00ed su clasificaci\u00f3n como **off-policy**), la cu\u00e1l tiene efecto en el proceso de selecci\u00f3n de acciones y por lo tanto determina cuales pares estado-acci\u00f3n se actualizan.\n\n\n\n## Ejemplo On-Policy vs. Off-Policy: The Cliff\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "2db187e3beca7d71e9a0740df1404c8b183d2727", "size": 37388, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "1_introduccion_al_aprendizaje_por_refuerzos.ipynb", "max_stars_repo_name": "bomba1990/AprendizajePorRefuerzos", "max_stars_repo_head_hexsha": "03a532674c27d260dba779e3bf628bc4d12af580", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1_introduccion_al_aprendizaje_por_refuerzos.ipynb", "max_issues_repo_name": "bomba1990/AprendizajePorRefuerzos", "max_issues_repo_head_hexsha": "03a532674c27d260dba779e3bf628bc4d12af580", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1_introduccion_al_aprendizaje_por_refuerzos.ipynb", "max_forks_repo_name": "bomba1990/AprendizajePorRefuerzos", "max_forks_repo_head_hexsha": "03a532674c27d260dba779e3bf628bc4d12af580", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.825285338, "max_line_length": 629, "alphanum_fraction": 0.574248422, "converted": true, "num_tokens": 3737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2598256379609837, "lm_q2_score": 0.07477004909308943, "lm_q1q2_score": 0.01942717570598603}}
{"text": "```python\n%matplotlib inline\n\nimport matplotlib\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = (12, 9)\nplt.rcParams[\"font.size\"] = 18\n```\n\n# Reprocessing\n\nReprocessing recovers uranium and plutonium isotopes from spent nuclear fuel (SNF). In this step, some high level waste (HLW) streams may be separated in preparation for special treatment before disposal.\n\n## Learning Objectives\n\nAt the end of this lesson you should be equipped to:\n\n- Understand the motivations for reprocessing.\n- Assess the pros and cons of various reprocessing strategies. \n- Recognize the actinides and the motivation to manage them.\n- Explain the differences in process between major reprocessing strategies.\n- Order the steps of a typical PUREX process. \n- Recall the history of nuclear fuel reprocessing.\n- Recognize the safety challenges encountered historically in nuclear fuel repo\n- Explain the relationship between reprocessing and nonproliferation.\n- Calculate the impact of reprocessing and recycling on fuel utilization.\n- Calculate the impact of reprocessing and recycling on fuel cycle costs.\n\n\n## Used Nuclear Fuel and The Actinides\n\n\n\n\n\n### What are actinides?\n\nActinides are all elements that are heavier than Actinium (Z=89). We typically care about a particular set of actinides called _transuranics_ or TRU. These are all elements heavier than Uranium (Z=92). Particularly:\n\n- Np (Z=93)\n- Pu (Z=94)\n- Am (Z=95)\n- Cm (Z=96)\n\n\n### Management of Actinides\n\nThere are three primary reasons to manage actinides. \n\n- Repository benefit: The decay heat burden of the actinides is a challenge for geologic disposal and increases repository management horizon.\n- Energy Recovery: There is energy stored in many of these actinides, as some are fissile or have fissile daughters.\n- Proliferation Resistence: Actinides can be used to construct a nuclear weapon (specifically, Pu). \n\n### Repository Benefit\n\nLet's look closely at repository benefit in the case of Yucca Mountain. The following plots are from Wigeland et al. [http://www.wmsym.org/archives/2004/pdfs/4333.pdf](http://www.wmsym.org/archives/2004/pdfs/4333.pdf).\n\n\n\n\n\n\n\n\n**Discussion: If reduced SNF heat allows increased fuel loading, how does that impact the cost of the repository?**\n\n\n\n\n**Vote: Do you think the cost of reproccessing is balanced by the savings in repository cost?**\n\n\n\n## Closed and Open Nuclear Fuel Cycles\n\n\n\n\nTo recycle SNF (or, if you prefer, UNF) one must first chemically \"reprocess\" the nuclear fuel that emerges from nuclear reactors.\n\n\n\n\n### Compare Once Through to U-Pu Recycling\n\n\n\n<center> This figure from Michael Corradini, 2006</center>\n\n### Compare to Advanced LWR Fuel Cycles\n\n\n\n\n## Major Accidents in Reprocessing Facilities \nReprocessing facilities have been responsible for more radiation release events than power reactors have, in general. [https://en.wikipedia.org/wiki/International_Nuclear_Event_Scale](https://en.wikipedia.org/wiki/International_Nuclear_Event_Scale).\n\n\n## The Atomic Man\n\nAug. 30, 1976. Harold McCluskey. Hanford. Americium recovery facility. \n\n\n\n\n\n\n\n\n\n\n\nAdditional notes on the medical side of this accident: [https://www.dademoeller.com/dademoellerblog/wp-content/uploads/2014/08/2014-08-Americium-Incident-Carbaugh.pdf](https://www.dademoeller.com/dademoellerblog/wp-content/uploads/2014/08/2014-08-Americium-Incident-Carbaugh.pdf)\n\n## Rocky Flats\n\n\n\nSeptember 11, 1957, (and May 11, 1969) near Golden, Colorado.\n\n\n\n\n \n\n\n<center>Uranium and plutonium are pyrophoric.</center>\n\n\n\n\n## The First Tokai Mura Accident\n\n\n> On the night of Tuesday 11 March 1997, a small explosion occurred in a nuclear reprocessing plant of the D\u014dnen. Windows were smashed and smoke escaped to the atmosphere. On Thursday, workers repaired thirty broken windows and three doors with duct tape. They had been damaged during the blast. At least 37 workers were exposed to elevated levels of radiation during the incident.\n\n\n\n## The Second Tokai Mura Accident\n\nThis accident, Sept. 30, 1999, was a different kind of accident. The previous accidents described were combustion related. This was a criticality accident. \n\n\nWorkers, uninformed about the impact of geometry on criticality, poured approximately 20% enriched uranium into a wide cylindrical bucket. \n\n> The criticality involved about 16 kilograms of 18.8 percent enriched uranium in solution in a tank. The tank is used to precipitate uranium from nitric acid liquid solution. The tank contained far more uranium than allowed for safe operation. The tank should not have contained more than 2.4 kilograms.\n\n\n\n\n\n\n### NRC Review\n\n[http://www.nrc.gov/reading-rm/doc-collections/commission/secys/2000/secy2000-0085/attachment1.pdf](http://www.nrc.gov/reading-rm/doc-collections/commission/secys/2000/secy2000-0085/attachment1.pdf)\n\nAlso: \n[https://www.nrc.gov/docs/ML1704/ML17045A577.pdf](https://www.nrc.gov/docs/ML1704/ML17045A577.pdf)\n\n- Procedure appropriateness\n- Safety culture\n- Regulatory body did not require adequate safety review\n- Training inadequacy\n\n# Separations Methods\n\nSeparations is typically either aqueous or electrochemical (pyro). The most common method, by far, today is aqueous separations via PUREX. \n\nThe basic options are thus:\n\n- Separate U, Pu, (as today).\n- Separate U, Pu+U (small amount of U).\n- Separate U, Pu, minor actinides.\n- Separate U, Pu+Np, Am+Cm.\n- Separate U+Pu all together.\n- Separate U, Pu+actinides, certain fission products\n\nCurrent capacity ([via world nuclear association](http://www.world-nuclear.org/information-library/nuclear-fuel-cycle/fuel-recycling/processing-of-used-nuclear-fuel.aspx)):\n\n|  Reactor | Nation  | Facility  | tonnes per year  |  \n|---|---|---|---|\n| LWR  |  France | La Hague  | 1700  |  \n| LWR  |  UK     | Sellafield (THORP)  | 600  |\n| LWR  |  Russia | Ozersk  (Mayak)  | 400  |   \n| LWR  |  Japan  | Rokkasho  | 800  |  \n| Other  |  UK | Sellafield (Magnox)  | 1500  |   \n| Other  |  India | PHWR  | 330  |   \n| Other  |  Japan |  Tokai, MOX | 40  |   \n\nAn aside on [ANS Position Statements](http://www.ans.org/pi/ps/) :\n\n- [Position Statement 45](http://cdn.ans.org/pi/ps/docs/ps45.pdf)\n- [Position Statement 74](http://www.ans.org/pi/ps/docs/ps74.pdf)\n\n## PUREX\n\nPUREX is simple, conventional separation of FP from U-Pu-MA (Does not reduce radioactivity but separates for further processing). [LLNL Report source material here.](https://e-reports-ext.llnl.gov/pdf/799624.pdf)\n\n- Head end: (Sometimes Voloxidation), Chopping, shearing, dissolving.\n- 1st Processing Phase: Coextraction. \"In the first cycle, uranium and plutonium are co-extracted into an\norganic phase, leaving the fission products and other actinide activation products in the aqueous phase\"\n- Second Processing Phase: Pu Extraction. \"In the second cycle, plutonium is stripped away from the uranium and\nreturned to an aqueous phase,\"\n- Third Processing Phase: \"In the third cycle, uranium is stripped away from the organic phase into dilute nitric acid\"\n- Finally: Additional purification and return to appropriate valences.\n\n\n\n\n\n\n### Chopping, Shearing and Dissolving\n\nThe first step is mostly mechanical, but involves some chemistry. Namely, the cladding is removed, the fuel is chopped, and then it is dissolved. This relies on nitrite solutions.\n\n\n<center>NEEP 571, M. Corradini & PPH Wilson </center>\n\n\n<center>JAEA R&D Review 2011 Copyright(c) Japan Atomic Energy Agency. All Rights Reserved.</center>\n\n\n\n<center>NEEP 571, M. Corradini & PPH Wilson </center>\n\n### Solvent Extraction\n\nThe valence of the Pu and U matter for the rest of this flowsheet. \n\n\n\n\n\n\n\n\n\n\n\n**Based on this diagram, what do you think 'raffinate' refers to?**\n\n### Separation of Pu and U\n\nAdditional solvent extraction steps separate uranium and plutonium into separate streams.\n\n\n\n### Return to appropriate valences\n\n\n\n### PUREX for Weapons\nPUREX was initially created for military applications. \n\n- created separated pure plutonium\n- produced significant high level liquid waste \n\n\n\n\n### PUREX for civilian applications\n\n- Waste handling has been greatly improved\n- Excellent safety record at commercial France and UK plants\n- Produces separated pure plutonium \n\n\n\n## UREX & UREX+\n\n\n<center>NEEP 571, M. Corradini & PPH Wilson </center>\n\n# Pyroprocessing / Electrochemical Separations\n\n\n\nThis brochure from Argonne is a good primer of electrorefining: http://www.cse.anl.gov/pdfs/pyroprocessing_brochure.pdf . \n\nThis image comes from that brochure:\n\n\n\n\n> Electrorefining is very similar to electroplating. Used fuel attached to an anode is suspended in a chemical bath;\nelectric current then dissolves the used fuel and plates out the uranium and other actinides on the cathode.\nThese extracted elements are then sent to the cathode processor where the residual salt from the refining\nprocess is removed.\nFinally, the remaining actinides and uranium are cast into fresh fuel rods and the salt is recycled back into the\nelectrorefiner\n\n\n\n\n\n\n\n\n\n\n\n\n\n# Fuel Utilization\n\nOne reason to consider reprocessing is economic. While right now, the cost of uranium and associated enrichment services is low in comparison to other fuel forms, per kWh, this may not always be the case. \n\n\\begin{align}\nU &= \\frac{\\mbox{mass of fuel consumed}}{\\mbox{mass of resource (e.g., nat U) used}}\\\\\n &= \\frac{M_f}{FF\\times M_l}\\\\\n M_f &= \\mbox{mass of fuel consumed}\\\\\n M_l &= \\mbox{mass of fuel loaded into the core}\\\\\n FF &= \\mbox{enrichment feed factor}\\\\\n\\end{align}\n\n## Aside: $M_f$\nFirst, let's think about the mass of fuel question. Your book states without proof that thermal $^{235}U$ fissions consume about 1.23g per MWd. \n\n\n**Let's show that this is the case.**\n\nFirst, recall :\n\n\\begin{align}\n^{235}_{92}U + ^{1}_{0}n \\rightarrow \\left(^{236}_{92}U\\right)^* \\rightarrow ^{A_1}_{Z_1}X +  ^{A_2}_{Z_2}X + {\\nu ^{1}_{0}n} + Q\n\\end{align}\n\nThat's our fission reaction. For each fission, 200MeV of energy is released. Let's then calculate how many atoms result in a thermal power of one Joule (1 $W\\cdot s$).\n\n\\begin{align}\n\\left(\\frac{1\\mbox{ fission}}{200 MeV}\\right)\n\\left(\\frac{1MeV}{1.6021\\times10^{-13}J}\\right) \n& =3.12\\times 10^{10}\n\\left(\\frac{fissions}{J}\\right)\n\\end{align}\n\nEach fission is one uranium atom, so:\n\\begin{align}\n\\left(\\frac{3.12\\times 10^{10}\\mbox{atoms fissioned}}{J}\\right)\n\\left(235 \\frac{g}{ mol}\\right)\\left(\\frac{1 mol}{6.022\\times10^{23} atoms}\\right)& = 1.22\\times 10^{-11}\\frac{g}{J}\\\\\n\\end{align}\n\nWe need to convert to MWd, so we'll need to know how many joules are in a MWd. \n\n\n\\begin{align}\n\\left(\\frac{1 J}{W\\cdot s}\\right)\n\\left(\\frac{10^6 W}{MW}\\right)\n\\left(\\frac{60\\times60 s}{h}\\right)\n\\left(\\frac{24h}{d}\\right)\n&=\n8.64\\times10^{10}\\frac{J}{MWd}\n\\end{align}\n\nThen, we can multiply J/MWd against g/J to get g/MWd. \n\n\\begin{align}\n\\left(8.64\\times10^{10}\\frac{J}{MWd}\\right)\\left(1.22\\times 10^{-11}\\frac{g}{J}\\right)&= 1.05 \\frac{g}{MWd}\n\\end{align}\n\n**However, we have to correct for the fact that fuel is also consumed by non-fission capture.**\n\n\\begin{align}\n\\frac{\\sigma_c}{\\sigma_f} &= 0.169\\\\\n\\Rightarrow\\frac{\\sigma_f + \\sigma_c}{\\sigma_f} &= 1.169\\\\\n\\end{align}\n\n\nSo, we get:\n\\begin{align}\n\\left(\\frac{g}{MWd}\\right)\\left(\\frac{\\sigma_f + \\sigma_c}{\\sigma_f}\\right)\n&= 1.05 \\frac{g}{MWd}\\times  1.169 = 1.23\n\\end{align}\n\n\n\n```python\nmev_per_fission = 200\nj_per_mev = 1.60218e-13\nfission_per_sec = 1/(mev_per_fission*j_per_mev)\nprint(\"fissions per second\", fission_per_sec)\n\nN_5 = 235/6.022E23\ng_per_fission = fission_per_sec*N_5\nprint(\"g per fission\", g_per_fission)\n\nj_per_mwd = (10**6)*(3600)*(24)\nprint(\"Joule per MWd\", j_per_mwd)\n\ncap_to_fiss = 1 + 0.169\ng_per_mwd = j_per_mwd*g_per_fission*cap_to_fiss\nprint(\"g per MWd\", g_per_mwd)\n\n```\n\n    fissions per second 31207479808.76056\n    g per fission 1.2178275913415362e-11\n    Joule per MWd 86400000000\n    g per MWd 1.230025352496413\n\n\n## U Utilization\n\nAlright, now you have 1.23 g/MWd for uranium 235 fissions. Now you can figure out the mass consumed for some burnup amount. \n\n\\begin{align}\nU &= \\frac{\\mbox{mass of fuel consumed}}{\\mbox{mass of resource (e.g., nat U) used}}\\\\\n &= \\frac{\\frac{1.23g}{MWd}BU(tIHM)}{\\mbox{mass of resource (e.g., nat U) used}}\n\\end{align}\n\n\nNow, though, you need the feed factor, to get the denominator.\n\n\\begin{align}\nFF &= \\frac{x_p - x_w}{x_f - x_w}\\\\ \n\\end{align}\n\n\n\n\\begin{align}\nU &= \\frac{\\frac{1.23g}{MWd}BU(tIHM)}{FF\\times M_l}\n\\end{align}\n\n## Fuel Utilization in Breeders\n\nA breeder reactor has the quality that it encourages the breeding of a secondariy fissile nuclide and thus, gets more fuel utilization.\n\n\nLet's introduce the concept of $\\gamma$, the losses in reprocessing and fuel refabrication. \n\n\\begin{align}\nU &= \\frac{\\frac{M_f}{M_l}}{\\left[\\frac{M_f}{M_l}\\right](1-\\gamma) + \\gamma}\\\\\n\\end{align}\n\nLet's compare once through with a breeder. \n\n\n\\begin{align}\n\\frac{M_f}{M_l} &= \\frac{g}{Mwd}\\times BU\\\\\n              &= \\frac{1.23g}{MWd}\\times\\frac{50MWd}{tHM}\\times\\frac{10^3tHM}{g}\\\\\n              &= 0.0615\n\\end{align}\n\nFor a typical LWR, the feed factor is :\n\n\\begin{align}\nFF &= \\frac{x_p - x_w}{x_f - x_w}\\\\ \n&= \\frac{4 - .2}{0.711 - 0.2}\\\\\n&= 7.436\n\\end{align}\n\nThus, U = 0.0615/7.436 = 0.0082 for a typical LWR.\n\nFor a reprocessing scheme with 2% losses:\n\n\n\\begin{align}\nU &= \\frac{0.0615}{\\left[0.0615\\right](1-0.02) + 0.02}\\\\\n\\end{align}\n\n\n```python\ng_per_kg=1000\nBU=50\nFF=7.436\ngamma = 0.02\nU_lwr = BU*g_per_mwd/(g_per_kg*FF)\nmf_per_ml= BU*g_per_mwd/g_per_kg\nU_breed=mf_per_ml/(mf_per_ml*(1-gamma) + gamma)\nprint(\"u_lwr =\", U_lwr)\nprint(\"M_f/M_l =\", mf_per_ml)\nprint(\"u_breed =\", U_breed)\n\n# In the book, there is a distinction for HM utilization\nBU=80\nmf_per_ml= BU*g_per_mwd/g_per_kg\nHM_breed=mf_per_ml/(mf_per_ml*(1-gamma) + gamma)\nprint(\"M_f/M_l =\", mf_per_ml)\nprint(\"hm_breed =\", HM_breed)\n\n```\n\n    u_lwr = 0.008270746049599336\n    M_f/M_l = 0.06150126762482066\n    u_breed = 0.7661681305015127\n    M_f/M_l = 0.09840202819971304\n    hm_breed = 0.8451314791998584\n\n\n## MOX reactor physics\n\nSNF recycling in MOX is conducted today in many nations, led primarily by France. \n\n> Today MOX is widely used in Europe and in Japan. Currently about 40 reactors in Europe (Belgium, Switzerland, Germany and France) are licensed to use MOX, and over 30 are doing so. In Japan about ten reactors are licensed to use it and several do so. These reactors generally use MOX fuel as about one-third of their core, but some will accept up to 50% MOX assemblies. France aims to have all its 900 MWe series of reactors running with at least one-third MOX. Japan also planned to use MOX in one-third of its reactors in the near future and APDC expects to start up a 1383 MWe (gross) reactor with a complete fuel loading of MOX at the Ohma plant in 2022. Other advanced light water reactors such as the EPR or AP1000 are able to accept complete fuel loadings of MOX if required. --- World Nuclear Association\n\n\n<center>From [WNA](http://www.world-nuclear.org/information-library/nuclear-fuel-cycle/fuel-recycling/mixed-oxide-fuel-mox.aspx)</center>\n\n\n<center>From [WNA](http://www.world-nuclear.org/information-library/nuclear-fuel-cycle/fuel-recycling/mixed-oxide-fuel-mox.aspx)</center>\n\n\nFrench reactors typically do not use 100% MOX fuel because the amount of acceptable plutonium content is limited by reactor physics. \n\n\n\n<center>UOx reactor</center>\n\n\n\n<center>MOx reactor</center>\n\n\n\n\n### Higher fission cross section of Pu causes power peaking.\n\n\n\n### Because of high absorption in Pu, control rod worth is reduced.\n\n\n\n### Lower $\\eta$ value in Pu means that more Pu is needed to acheive same exess reactivity\n\nHowever, slower burnup means less excess reactivity is needed in MOX cores. \n\n\n\n\n### Aside: Delayed Neutron Fraction and Mean Neutron Lifetime\n\n\n\nBy combining the neutron transport equation with a source contribution from\ndelayed neutrons,  we can arrive at the fundamental analysis tool in nuclear reactor\nkinetics. These are a stiff set of PDEs involving nonlinearly coupled\nneutronics, thermodynamics, and hydraulics.\n\nThe delayed neutron precursors obey the equation,\n\n\\begin{align}\n  \\frac{\\partial \\hat{C}_i(t,r)}{\\partial t} =\n  \\beta_i\\nu\\Sigma_f(r,t)\\phi(r,t) -\n  \\lambda_i\\hat{C}_i(r,t)\\\\\n  i\\in [1,6].\n\\end{align}\n\n$\\beta_i$ and $\\lambda_i$ depend on the incident neutron energy, fissionable\nisotope, and precursor group.  In this way, the  linearized Boltzmann transport\nequation has seven dimensions.  Taking delayed neutrons into account, the one\nspeed neutron diffusion equation can be written,\n\n\\begin{align}\n  \\frac{1}{v}\\frac{\\partial \\phi(r,t)}{\\partial t} - D(r,t)\\nabla^2\\phi(r,t) + \\\n  \\Sigma_a(r,t)\\phi(r,t) = (1-\\beta)\\nu\\Sigma_F(r,t)\\phi(r,t) + \\\n  \\sum_{i=1}^6\\lambda_i\\hat{C}_i(r,t).\n\\end{align}\n\nTransient analysis methods seek to solve this equation for changes in the\nparameters caused by a changing reactor conditions. Additional PDEs are added to\nthis calculation to capture the dependence of temperature on heat conduction and\nthe effect of fluid flow.\n\n\n\\begin{equation}\n  \\frac{d}{dt}\\left[\n    \\begin{array}{c}\n      p\\\\\n      \\zeta_1\\\\\n      .\\\\\n      .\\\\\n      .\\\\\n      \\zeta_J\\\\\n      \\omega_1\\\\\n      .\\\\\n      .\\\\\n      .\\\\\n      \\omega_K\\\\\n    \\end{array}\n    \\right]\n    =\n    \\left[\n      \\begin{array}{ c }\n        \\frac{\\rho(t,T_{fuel},T_{cool},\\cdots)-\\beta}{\\Lambda}p +\n        \\displaystyle\\sum^{j=J}_{j=1}\\lambda_j\\zeta_j\\\\\n        \\frac{\\beta_1}{\\Lambda} p - \\lambda_1\\zeta_1\\\\\n        .\\\\\n        .\\\\\n        .\\\\\n        \\frac{\\beta_J}{\\Lambda}p-\\lambda_J\\zeta_J\\\\\n        \\kappa_1p - \\lambda_1\\omega_1\\\\\n        .\\\\\n        .\\\\\n        .\\\\\n        \\kappa_{k}p - \\lambda_k\\omega_{k}\\\\\n      \\end{array}\n      \\right]\n    \\end{equation}\n\n\n\n\n\\begin{align}\n    \\rho(t,&T_{fuel},T_{cool},T_{mod}, T_{refl}) = \\mbox{ reactivity, [pcm]}\\\\\n    \\beta &= \\mbox{ fraction of neutrons that are delayed}\\\\\n    \\beta_j &= \\mbox{ fraction of delayed neutrons from precursor group j}\\\\\n    \\zeta_j &= \\mbox{ concentration of precursors of group j}\\\\\n    \\lambda^{d}_j &= \\mbox{ decay constant of precursor group j}\\\\\n    \\omega_k &= \\mbox{ decay heat from FP group k}\\\\\n    \\kappa_k &= \\mbox{ heat per fission for decay FP group k}\\\\\n    \\lambda^{FP}_k &= \\mbox{ decay constant for decay FP group k}\\\\\n    l &= \\mbox{mean neutron lifetime}\\\\\n      &= \\mbox{mean time for one neutron to be removed from the reactor}\\\\\n      &= \\frac{1}{\\left(\\Sigma_a + DB^2\\right)v}\\\\\n    \\Lambda &= \\mbox{neutron reproduction time}\\\\\n            &= \\mbox{mean time for one neutron to be replaced by another neutron on fissioning}\\\\\n            &= \\frac{1}{\\nu\\Sigma_fv}\\\\\n \\end{align}\n\n**Bottom line: lower fraction of delayed neutrons constrains reactor control.**\n**Bottom line: Similarly, shorter prompt neutron lifetimes neutrons constrain reactor control.**\n\n\n\n\n## Plutonium and Void Coefficients \n\n\\begin{align}\n\\rho &= \\frac{k_{eff} - 1}{k_{eff}}\\\\\n&= \\begin{cases}\n\\rho > 0 & \\mbox{supercritical}\\\\\n\\rho = 0 & \\mbox{critical}\\\\\n\\rho < 0 & \\mbox{subcritical}\\\\\n\\end{cases}\\\\\n\\rho_{tot} &= \\sum \\rho_i\\\\\n\\rho_{void} &= \\mbox{Reactivity from coolant voiding}\\\\\n\\alpha_v &= \\mbox{void reactivity coefficient}\\\\\n&=\\frac{\\partial \\rho}{\\partial v}\n\\end{align}\n\n\n\n# Conversion Ratio\n\nThe conversion ratio is a measure of the evolution of fissile nuclides in the core and their involvement in fission.\n\n\\begin{align}\nCR &= \\frac{\\mbox{production of fissile nuclei}}{\\mbox{depletion of fissile nuclei}}\\\\\n&=\\begin{cases}\n< 1 & \\mbox{burner} \\\\\n> 1 & \\mbox{breeder} \n\\end{cases}\n\\end{align}\n\n## Breeding in Thermal Reactors\n\nFor typical enriched uranium fuel, this is, effectively:\n\n\\begin{align}\nCR &= \\frac{\\mbox{production of } ^{239}Pu}{\\mbox{depletion of } ^{235}U}\n\\end{align}\n\nIn more detail, we could say:\n\n\n\\begin{align}\nCR &= \\frac{\\mbox{production of } ^{239}Pu}{\\mbox{depletion of } ^{235}U + \\mbox{depletion of } ^{239}Pu}\n\\end{align}\n\n\n\n\nIf $\\nu_0$ is the number of neutrons produced for each neutron absorbed in $^{235}U$ is 2.075, then what has to happen in order to have a $^{235}U$ fuelled breeder?\n\n- 1st neutron: creates another fission \n- 2nd neutron: produces $^{239}Pu$\n- 0.08 neutrons left over\n\nIs the above situation likely?\n\n\nThere is an opportunity for thermal spectrum using $^{233}U$, which has a higher $\\nu_0$, equal to 2.296. Of course, the way this works is that $^{232}Th$ is the fertile nuclide and $^{233}U$ is the fissile fuel that is preferentially bred. However, one must start with $^{235}U$. \n\n\n## Breeding in Fast Reactors\n\nWe can do a bit better with a plutonium-based fuel cycle. Since ${239} Pu$ has a high capture to fission cross section at thermal energies, we can only do this by aiming for a harder (faster, less thermal, higher energy) neutron spectrum in the core. \n\n\n<center>[source](http://www.tpub.com/doenuclearphys)</center>\n\nGo to : [https://pollev.com/katyhuff](https://pollev.com/katyhuff)\n\n\n```python\nfrom IPython.display import IFrame\nIFrame(\"https://embed.polleverywhere.com/free_text_polls/PpzDE4SqDrxQGN0?preview=true\", width=1000, height=700)\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n- In a fast reactor of this sort, the neutrons are not thermalized. Instead, $^{239}Pu$ fissions occur at high energies (above 1MeV). \n- At these energies, the fission cross section in $^{239}Pu$ is $\\sigma_f = 1.7b$ \n- and the capture-to-fission ratio is less than 0.03. \n- Also, at about 3 neutrons per fission for ${239} Pu$ fissions at 1MeV, there are plenty of neutrons available for breeding. \n\n\n\n\n\n <center>[source](https://upload.wikimedia.org/wikipedia/commons/thumb/4/46/LMFBR_schematics2.svg/1280px-LMFBR_schematics2.svg.png)</center>\n\n\n### LMFBR Coolant\nFast reactors must avoid thermalization of the neutrons. Thus, moderating coolants are avoided. Instead, liqiud metals are chosen as the coolant for their relatively high mass number A. An added advantage of liquid metals is that they are excellent at heat transfer.\n\nA typical choice for LMFBR coolant is ${23}Na$. Can you think of any downsides of sodium as a coolant?\n\n\n```python\nfrom IPython.display import IFrame\n\nIFrame(\"https://embed.polleverywhere.com/free_text_polls/gvv1yTIP8TMNTaY?preview=true\", width=1000, height=700)\n```\n\n\n\n\n\n\n\n\n\n\n### LMFBR Fuel\n\nThe fuel is typically made of mixed $PuO_2$ (about 80%) and $UO_2$ (about 20%) pellets. Depleted uranium is typically used \n\n**From what type of fuel cycle facility would you acquire depleted uranium?**\n\n\n\n\n\n\n\n\n```python\nfrom IPython.display import IFrame\nIFrame(\"https://embed.polleverywhere.com/ranking_polls/Ija9UIgC1yFsugXWljhJk?controls=none&short_poll=true\", width=800, height=600)\n```\n\n\n\n\n\n\n\n\n\n\n## What about burners?\n\nCR << 1 can be acheived in a number of types of reactors. An extreme option, when burning actinides is the primary goal, is an accelerator driven system. \n\n\n\n<center>[source: MYRRHA](myrrha.sckcen.be)</center>\n\nBut where do we get the spallation neutrons?\n\n\n<center>[source: LANSCE](http://www.lanl.gov)</center>\n\n## Natural Uranium Savings From Recycling U and Pu\n\n\nLet's introduce some new variables:\n\n\\begin{align}\nx_s &= \\mbox{enrichment of uranium in used fuel}\\\\\nfPu &= \\mbox{mass of fissile plutonium}\\\\\ns &= \\mbox{kg of fPu recovered per kg of used fuel}\\\\\nu &= \\mbox{kg of used fuel per kg of fresh fuel}\\\\\n\\end{align}\n\nWe can calculate the savings in natural uranium due to plutonium recycling. \n\nConsider 1 kg of fresh fuel. It contains $x_p$ kg of $^{235}U$. If we replce this kg with MOX (Pu and depleted U tails) we calculate an \"equivalence\":\n\n\\begin{align}\nx_p\\mbox{ kg of }^{235}U \\longleftrightarrow x_w\\mbox{ kg of }^{235}U + \\frac{x_p - x_w}{p}\\mbox{ kg of Pu}\n\\end{align}\n\nSo, if natural uranium is used as feed, FF kg of natural uranium are needed for each kg. If MOX is used instead, the savings is :\n\n\\begin{align}\n\\frac{FF\\cdot p}{x_p - x_w} = \\mbox{(kgU saved per kg fPu)}\n\\end{align}\n\nWe can also describe savings in terms of s (Pu recovered) and amount of fuel discharged:\n\n\\begin{align}\n\\frac{s\\cdot FF\\cdot p}{x_p - x_w} = \\mbox{(kgU saved per kg of fuel discharged)}\n\\end{align}\n\nOr , we can describe it per kg initially loaded into the reactor :\n\\begin{align}\n\\frac{u \\cdot s\\cdot FF\\cdot p}{x_p - x_w} = \\mbox{(kgU saved per kg of fuel initially charged into the reactor )}\n\\end{align}\n\n\nFinally, we can describe it per kg of natural uranium\n\\begin{align}\n\\frac{u \\cdot s \\cdot p}{x_p - x_w} = \\mbox{(kgU saved per kg of natural uranium feed )}\n\\end{align}\n\n\n```python\n\n```\n", "meta": {"hexsha": "a55d511c60e78ab16a4d18f324f698473cfe88e9", "size": 44122, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "reprocessing/reprocessing.ipynb", "max_stars_repo_name": "abachma2/npre412", "max_stars_repo_head_hexsha": "3f105a15edc07745f1dd65cd791777a01136ec23", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reprocessing/reprocessing.ipynb", "max_issues_repo_name": "abachma2/npre412", "max_issues_repo_head_hexsha": "3f105a15edc07745f1dd65cd791777a01136ec23", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reprocessing/reprocessing.ipynb", "max_forks_repo_name": "abachma2/npre412", "max_forks_repo_head_hexsha": "3f105a15edc07745f1dd65cd791777a01136ec23", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.665437788, "max_line_length": 823, "alphanum_fraction": 0.6023525679, "converted": true, "num_tokens": 7114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16451646289656316, "lm_q2_score": 0.11757212581561162, "lm_q1q2_score": 0.019342550274414123}}
{"text": "```python\n    from poser import *\n\n    \n    import toolz\n\n    \n    def to_delayed(f, *args, delayed=None, **kwargs):\n        import functools, typing\n        import poser, importlib\n        import dask.bag.random, toolz\n        Delayed =__import__(\"importlib\").import_module('dask.delayed').Delayed\n\n        function_mapping = {\n            all: dask.bag.Bag.all,\n            any: dask.bag.Bag.any,\n            map: dask.bag.Bag.map,\n            sum: dask.bag.Bag.sum,\n            toolz.itertoolz.take: dask.bag.Bag.take,\n            toolz.itertoolz.count: dask.bag.Bag.count,\n            toolz.itertoolz.unique: dask.bag.Bag.distinct,\n            poser.util.filter: dask.bag.Bag.filter,\n            __import__(\"_operator\").concat: dask.bag.Bag.flatten,\n            toolz.sandbox.fold: dask.bag.Bag.fold,\n            \"frequencies\": dask.bag.Bag.frequencies,\n            toolz.itertoolz.groupby: dask.bag.Bag.groupby,\n            toolz.itertoolz.join: dask.bag.Bag.join,\n            poser.util.map: dask.bag.Bag.map,\n            \"map_partitions\": dask.bag.Bag.map_partitions,\n            max: dask.bag.Bag.max,\n            __import__(\"statistics\").mean: dask.bag.Bag.mean,\n            min: dask.bag.Bag.min,\n            toolz.itertoolz.pluck: dask.bag.Bag.pluck,\n            __import__(\"itertools\").product: dask.bag.Bag.product,\n            __import__(\"_functools\").reduce: dask.bag.Bag.reduction,\n            toolz.itertoolz.random_sample: dask.bag.Bag.random_sample,\n            toolz.itertoolz.remove: dask.bag.Bag.remove,\n            \"repartition\": \"\",\n            __import__(\"itertools\").starmap: dask.bag.Bag.starmap,\n            __import__(\"statistics\").stdev: dask.bag.Bag.std,\n            sum: dask.bag.Bag.sum,\n            toolz.itertoolz.take: dask.bag.Bag.take,\n            \"to_*\": ...,\n            toolz.itertoolz.topk: dask.bag.Bag.topk,\n            __import__(\"statistics\").variance: dask.bag.Bag.var,\n            \"read_*\": ...,\n            \"from_\": ...,\n            \"concat\": dask.bag.concat,\n            zip: dask.bag.zip,\n            __import__(\"random\").choices: dask.bag.random.choices,\n            __import__(\"random\").sample: dask.bag.random.sample,\n            \"to_*\": ...,\n        }\n            \n        if isinstance(f, \u03bb):\n            if f.args:\n                delayed = to_delayed(f.args[0], **f.kwargs)\n                \n            for g in list(f):\n                delayed = to_delayed(g, delayed=delayed)\n            return delayed\n        \n        if isinstance(f, typing.Sequence):\n            return dask.bag.from_sequence(f, **kwargs)\n        \n        if isinstance(f, functools.partial):\n            f, args, kwargs = f.func, f.args, f.keywords\n            \n            \n        if f in {poser.util.map, poser.util.filter}:\n            [kwargs.pop(x, None) for x in \"key property\".split()]\n            \n            \n        if f in function_mapping:\n            if delayed is None:\n                return function_mapping[f](*args, **kwargs)\n            \n            if isinstance(delayed, Delayed):\n                delayed = dask.bag.from_delayed(delayed)\n\n            return function_mapping[f](delayed, *args, **kwargs)\n        \n        if delayed is None:\n            return dask.delayed(f)\n        \n        \n        return dask.delayed(f)(delayed)\n        \n            \n\n    import poser\n\n    \u03bb.delayed = to_delayed\n    \u03bb.visualize = \u03bb[to_delayed].methodcaller('visualize')\n    \u03bb.compute = \u03bb[to_delayed].methodcaller('compute')\n    \u03bb.to_dataframe = \u03bb[to_delayed].methodcaller('to_dataframe')\n```\n\n\n```python\n    f = \u03bb(range(100))[\n        -\u03bb.mod(2) # filter\n        :\u03bb.mul(10)\n        :sum\n    ]\n```\n\n\n```python\n    fd = \u03bb(range(100), npartitions=6)[\n        -\u03bb.mod(2) # filter\n        :\u03bb.mul(10) # map\n        :sum # reduce\n    ]\n```\n\n\n```python\n    # fd.visualize(), fd.delayed()\n    assert fd.compute() == f()\n```\n\n\n```python\n    fd = \u03bb(range(100))[\n        -\u03bb[\u039b%2] # filter\n        :\u03bb[\u039b*10]\n        :sum\n    ]\n    fd.compute()\n```\n\n\n\n\n    24500\n\n\n\n\n```python\n    f = \u03bb(\u03bb.range(20)(), npartitions=10)[\n        -\u03bb.mod(2) # filter divisible by two.\n        :\u03bb[{\"type\": type, \"str\": str, \"range\": range}] # map a dictionary\n    ].to_dataframe(); f\n\n    f, f.compute().T\n```\n\n\n\n\n    (Dask DataFrame Structure:\n                       type     str   range\n     npartitions=10                        \n                     object  object  object\n                        ...     ...     ...\n     ...                ...     ...     ...\n                        ...     ...     ...\n                        ...     ...     ...\n     Dask Name: to_dataframe, 40 tasks,\n                        0              0              0                   0  \\\n     type   <class 'int'>  <class 'int'>  <class 'int'>       <class 'int'>   \n     str                0              2              4                   6   \n     range             ()         (0, 1)   (0, 1, 2, 3)  (0, 1, 2, 3, 4, 5)   \n     \n                                   0                               0  \\\n     type              <class 'int'>                   <class 'int'>   \n     str                           8                              10   \n     range  (0, 1, 2, 3, 4, 5, 6, 7)  (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)   \n     \n                                                 0  \\\n     type                            <class 'int'>   \n     str                                        12   \n     range  (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)   \n     \n                                                         0  \\\n     type                                    <class 'int'>   \n     str                                                14   \n     range  (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)   \n     \n                                                            0  \\\n     type                                       <class 'int'>   \n     str                                                   16   \n     range  (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...   \n     \n                                                            0  \n     type                                       <class 'int'>  \n     str                                                   18  \n     range  (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...  )\n\n\n\n    !gist poser-dask.ipynb -u6bfa54a91a7fd2e9b6f22109119b254a\n\n\n```python\n    from sympy.abc import *\n```\n\nuse dask and sympy together.\n\n\n```python\n    assert \u03bb(\u03bb.range(20)(), npartitions=10).map(x+10).sum().compute() == \u03bb(\u03bb.range(20)()).map(x+10).sum()()\n```\n", "meta": {"hexsha": "cebb1ed7532cd8a29855e11976e0d2b57eba6561", "size": 9591, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tests/test_dask.ipynb", "max_stars_repo_name": "deathbeds/poser", "max_stars_repo_head_hexsha": "f2209497ae416c30e3cd9b4d2237b6d3b6287355", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-04-21T23:44:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-09T17:14:13.000Z", "max_issues_repo_path": "tests/test_dask.ipynb", "max_issues_repo_name": "deathbeds/poser", "max_issues_repo_head_hexsha": "f2209497ae416c30e3cd9b4d2237b6d3b6287355", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-04-24T00:06:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-12T03:03:11.000Z", "max_forks_repo_path": "tests/test_dask.ipynb", "max_forks_repo_name": "deathbeds/poser", "max_forks_repo_head_hexsha": "f2209497ae416c30e3cd9b4d2237b6d3b6287355", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7711267606, "max_line_length": 113, "alphanum_fraction": 0.3857783339, "converted": true, "num_tokens": 1759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4804786780479071, "lm_q2_score": 0.0402379414726846, "lm_q1q2_score": 0.019333472926164552}}
{"text": "# ANEOS MODEL INTERFACE JUPYTER NOTEBOOK\n\nSarah T. Stewart<br>\nsts@ucdavis.edu<br>\nCreated October 22, 2019<br>\nUpdated January 21, 2020<p>\n\n***\n***\n## COMMENTS ON ORIGINAL ANEOS IRON MODEL WITH HIGH-PRESSURE PHASE CHANGE\nThese material parameters for iron were distributed with the original ANEOS in Thompson 1970. The iron parameters were prepared by T.G. Trucano at Sandia according to documentation in the CTH shock code package.\n\nThis version was used in the giant impact papers using the GADGET2 code: Marcus et al. 2009, 2010ab; Cuk & Stewart 2012; Sarid et al. 2015; Lock & Stewart 2017; Lock et al. 2018; Rufu et al. 2017; Carter et al. 2018; Bonomo et al. 2019; Denman et al. submitted. This version of ANEOS iron was also used in many impact cratering studies, e.g.: Pierazzo et al. (1997); Svetsov (2005); Artemieva and Pierazza (2011); Barr and Citron (2011); Quintana et al. (2015); Yue and Di (2017); Moreau et al. (2018).\n\nThe parameters were tabulated in Thompson 1970 as \"IRON 130KB PHASE TRANSITION\" and in Thompson & Lauson 1972 as 'IRON 130PT'. This ANEOS model was used to construct SESAME table 2141 with the aid of the PANDA code. \n\nThis is a condensed phase + vapor ANEOS model with ionization and a high-pressure phase transition for pure iron.\n\nIssues:<br>\n  - No melt curve.<br>\n  - The model includes one high-pressure phase transition, but there are multiple solid phases. The high-pressure phase transition was never completed in ANEOS. It produces artificial discontinuities in the liquid field.<br>\n  - The vapor curve does not match available data. The critical point temperature is too high.<br>\n  - In the original ANEOS, the temperatures are too high and the entropies are too low in the liquid region. The discrepancy arises because the ANEOS model has a limiting 3nR heat capacity; the true heat capacities in liquid iron are larger.<br>\n\n***\n***\n<b>STS ANEOS INTERFACE NOTEBOOK GUIDE</b>\n\n<b>USAGE</b><br>\nThis notebook interacts with multiple outputs from the Stewart-modified version of ANEOS, including phase boundary information and tabulated EOS. \n\nThis notebook is designed to be used in two modes:<br>\n<ul>\n<li> Development mode: ANEOS is called in the local directory to generate new model output. The user can varying the model input parameters and tabular gridding schemes. This notebook produces plots of the equation of state surface and comparisons to experimental data and ab initio calculations.\n<li> Release mode: the notebook interacts with previously created ANEOS model output. This notebook provides detailed documentation of a version-controlled release of the model EOS and enables users to interact with the EOS surface and compare the model to data. \n</ul>\n\nThis notebook is distributed in release mode. Users who wish to use the development mode may request the modified version of ANEOS from the author.<p>\n\nDevelopment mode:<br>\nThe notebook calls a local aneos executable which expects a formatted ANEOS.INPUT ascii file and an ascii gridtable.txt definition file that is generated by this notebook. ANEOS produces an ANEOS.OUTPUT ascii file and gridded ascii SESAME-format EOS tables.<br>\nThe user edits (1) the input parameters in ANEOS.INPUT (separately from this notebook) and (2) the output EOS table parameters in the notebook cell below.<br>\nThis notebook reads some parameters from ANEOS.INPUT and assumes that the variables are spaced by 10 columns.<br> \nWhen the notebook is run, the code issues a system call to run the aneos program in the local directory and reads in results from the ANEOS.OUTPUT, NEW-SESAME-STD.TXT, and NEW-SESAME-EXT.TXT files to make the plots below and to generate the GADGET format EOS table and other miscellaneous files.<p>\n\nRelease mode:<br>\nThis notebook reads in the provided ANEOS.INPUT, EOS tables, and other distribution data to generate the plots below. <p>\n\n<b>OUTPUT/PROVIDED DATA FILES</b><br>\nANEOS.OUTPUT: Plain text file with an overview of the calculated equation of state. Look at this file for any errors in the EOS calculation.<br>\n\nNEW-SESAME-STD.TXT: Standard length Sandia-style SESAME file with 201 table and 301 table (density, temperature, pressure, sp. internal energy, Helmholtz free energy). 301 table units: g/cm$^3$, K, GPa, MJ/kg, MJ/kg. <br>\n\nNEW-SESAME-EXT.TXT: SESAME-style table with extra variables from ANEOS. Contains the standard 201 table and non-standard 301-extra-variables EOS table. The 301 table has: density grid values, temperature grid values, sp. entropy(T,rho), sound speed(T,rho), sp. heat capacity(T,rho), KPA flag(T,rho). 2-D arrays list all densities, looping over each temperature. 301 table units: g/cm$^3$, K, MJ/K/kg, cm/s, MJ/K/kg, integer flag, integer flag. The KPA flag is an ANEOS output with phase information. <br>\n\nNEW-SESAME-HUG.TXT: Ascii table with the reference state Hugoniot. <br>\n\nNEW-SESAME-STD-NOTENSION.TXT: Standard length Sandia-style SESAME file with 201 table and 301 table (density, temperature, pressure, sp. internal energy, Helmholtz free energy) where the ANEOS tension region is removed and replaced with the solid-vapor coexistence region. 301 table units: g/cm$^3$, K, GPa, MJ/kg, MJ/kg. <br>\n\nNEW-GADGET2-STD-NOTENSION.TXT: Standard GADGET2 EOS table generated by interpolating the ANEOS table with no tension. Format: number of density points, number of sp. entropy points, density grid values, sp. entropy grid values, 2-D arrays of pressure, temperature, specific internal energy, sound speed. 2-D array values list all densities, looping over each value for specific entropy. Units: g/cm$^3$, erg/K/g, dynes/cm$^2$, K, erg/g, cm/s. <br>\n\nNEW-GADGET2-EXT-NOTENSION.TXT: Extended variables GADGET2 EOS table generated by interpolating the ANEOS table with no tension. Format: number of density points, number of sp. entropy points, density grid values, sp. entropy grid values, 2-D arrays of Helmholtz free energy, KPA flag, MDQ flag. 2-D array values list all densities, looping over each value for specific entropy. Units: g/cm$^3$, erg/K/g, erg/g, integer flag, integer flag. <br>\n\nThe SESAME tabular equation of state formats are described in Lyon and Johnson (1992).<p>\n\n<b>ANEOS NOTES</b><br>\nThe ANEOS source code was provided by Jay Melosh and Gareth Collins. This version included Melosh's (2007) treatment for molecular gas and the capability to include a melt curve and solid-solid/liquid-liquid transition (Collins & Melosh LPSC 2014).<br>\nIn Stewart et al. 2019, the Melosh and Collins version of ANEOS was modified to adjust the Debye model for the thermal term in the Helmholtz free energy to approach a user-defined heat capacity at high temperatures. The multiplicative factor $f_{cv}$ is entered in input value V44, and the high-temperature heat capacity is $3f_{cv}Nk$.<p>\nThe ANEOSTEST.f routine was modified to output tabulated EOS. Note that the current version of this function sets positive pressures smaller than 1.E-30 GPa equal to 1.E-30 GPa.<br>\nANEOS2.f was modified to increase the number of points tabulated on the melt curve in the ANEOS.OUTPUT file and to gather the variables for the heat capacity modification.<br>\nANHUG.f was modified to output more Hugoniot points.<br>\nANEOS1.f and ANEOS2.f were modified to increase the high temperature limit for the heat capacity (Stewart et al., SCCM19).<p>\n\n<b>CORRECTIONS AND IMPROVEMENTS</b><br>\nPlease send corrections to STS and any requests for data to include in the model-data comparison plots.<p>\n\n\n\n```python\n# this cell has a java script that that enables hiding the raw python code\n\nfrom IPython.display import HTML\n\nHTML('''\n<form action=\"javascript:code_toggle()\"><input type=\"submit\" value=\"Click here to toggle on/off the raw code.\"></form>''')\n```\n\n\n\n\n\n<form action=\"javascript:code_toggle()\"><input type=\"submit\" value=\"Click here to toggle on/off the raw code.\"></form>\n\n\n\n\n```python\n# Record the verions information for these calculation for posterity\nimport platform\nprint('python version: ',platform.python_version())\ndel platform\nimport matplotlib\nprint('matplotlib version: ', matplotlib.__version__)\ndel matplotlib\nimport numpy\nprint('numpy version: ', numpy.__version__)\ndel numpy\nimport scipy\nprint('scipy version: ', scipy.__version__)\ndel scipy\nimport pandas\nprint('pandas version: ', pandas.__version__)\ndel pandas\n\n# this prevents some error messages for inline plotting in a jupyter notebook\n%matplotlib inline \n# import python libraries\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport matplotlib.colors as colors\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom copy import deepcopy\nimport numpy as np\nfrom scipy import interpolate\nimport colormaps as local_cmaps\nimport subprocess\nimport pandas as pd\nfrom matplotlib.collections import PatchCollection\nfrom matplotlib.patches import Rectangle\n#\nplt.rcParams[\"figure.figsize\"] = (20,10)\nplt.rcParams[\"patch.force_edgecolor\"] = True\n```\n\n    python version:  3.7.4\n    matplotlib version:  3.1.1\n    numpy version:  1.17.2\n    scipy version:  1.3.1\n    pandas version:  0.25.1\n\n\n## USER INPUTS FOR SESAME AND GADGET2 TABLE CONSTRUCTION\n\nIf the code cell below is hidden, use the button above to reveal the cell.<p>\n\nIn development mode, the user must input:<br>\n1. Header information for the SESAME table.<br>\n2. Temperature, density and entropy grid points.<p>\n\nThe following code cell also includes the development mode flag and \noption to skip construction of a GADGET2 table if it is not needed.<p>\n\n\n```python\n# -------------------------------------------------------------\n# USER INPUTS\n#-------------------------------------------------------------\n# NOTEBOOK MODE\n#-------------------------------------------------------------\n#\nDEVMODE = 1 # 1=development mode; 0=release mode\n#\n#-------------------------------------------------------------\n# OPTIONS TO REMOVE TENSION REGION AND CONSTRUCT A GADGET2 TABLE\n#-------------------------------------------------------------\n#\nREMOVETENSIONFLAG=0  # 0- keep tension region; 1- remove tension region\nMAKEGADGETTABLE=0  # 1=make table; 0=do not make gadget2 table\n#\n#-------------------------------------------------------------\n# USER MUST SET THESE VALUES TO DEFINE THE TABULATED EOS GRIDS\n#-------------------------------------------------------------\n#\n# ====>>>>>> YOU NEED TO MAKE SURE THESE VALUES MATCH ANEOS.INPUT  <<<<=====\nMODELNAME = 'Iron-ANEOS-SLVTv0.1Gx'\n# Header information must all be compatible with float format\nMATID = 1.0        # MATID number\nDATE = 191022.     # Date as a single 6-digit number YYMMDD\nVERSION = 0.1      # ANEOS Parameters Version number\nFMN = 26.          # Formula weight in atomic numbers for Fe\nFMW = 55.847       # Formula molecular weight (g/cm3) for Fe\n# The following define the default initial state for material in the 201 table\nR0REF   = 8.06     # g/cm3 *** R0REF is inserted into the density array; using gamma-iron for rho0\nK0REF   = 1.33E12  # dynes/cm2; using gamma-iron for rho0\nT0REF   = 298.     # K -- *** T0REF is inserted into the temperature array\nP0REF   = 1.E6     # dynes/cm2 -- this defines the principal Hugoniot calculated below\n#\n# generate output files for other ANEOS models\nmodelflag = 2   # 0 - don't change anything above; 1 - Canup et al. 2013; \n                # 2 - GADGET2 Marcus PhD Thesis & Cuk & Stewart 2012; 3 - ISALE Dellen Collins and Melosh 2014\n#\nif modelflag == 1:\n    MODELNAME = 'IRON WITH MELT CURVE'\n    # Header information must all be compatible with float format\n    MATID = 1.0        # MATID number\n    DATE = 191022.     # Date as a single 6-digit number YYMMDD\n    VERSION = 1.0      # ANEOS Parameters Version number\n    FMN = 26.          # Formula weight in atomic numbers for Mg2SiO4\n    FMW = 55.847       # Formula molecular weight (g/cm3) for Mg2SiO4\n    # The following define the default initial state for material in the 201 table\n    R0REF   = 7.85     # g/cm3 *** R0REF is inserted into the density array\n    K0REF   = 1.45E12  # dynes/cm2  K0=rho0*cs0^2\n    T0REF   = 298.     # K -- *** T0REF is inserted into the temperature array\n    P0REF   = 1.E6     # dynes/cm2 -- this defines the principal Hugoniot calculated below\nif modelflag == 2:\n    MODELNAME = 'IRON 130PT Thompson 1970'\n    # Header information must all be compatible with float format\n    MATID = 1.0        # MATID number\n    DATE = 191022.     # Date as a single 6-digit number YYMMDD\n    VERSION = 1.0      # ANEOS Parameters Version number\n    FMN = 26.          # Formula weight in atomic numbers for Mg2SiO4\n    FMW = 55.847       # Formula molecular weight (g/cm3) for Mg2SiO4\n    # The following define the default initial state for material in the 201 table\n    R0REF   = 7.85     # g/cm3 *** R0REF is inserted into the density array\n    K0REF   = 1.93E12  # dynes/cm2  K0=rho0*cs0^2\n    T0REF   = 298.     # K -- *** T0REF is inserted into the temperature array\n    P0REF   = 1.E6     # dynes/cm2 -- this defines the principal Hugoniot calculated below\n#\n#-------------------------------------------------------------\n# EXAMPLE EOS GRID ARRAYS\n#-------------------------------------------------------------\n#\n# Life is easier if the grid arrays are even in length (after adding T0REF and R0REF below)\n#\n# Flag for easily switching between different table grids during model development\n# 1: high res for testing\ngridflag = 1\n#\n#------------------------------------------------------\nif gridflag == 0: # low resolution grid\n    # define the temperature array for the SESAME table\n    # 0 K is changed to 1 K\n    # T0REF is inserted into the table if it is not present in the original array\n    # need to have extra temperature resolution around the triple point\n    gridtvals  = [0, 1750, 1950, 20000.,1.E5, 1.E7] # K -- this array defines the edges of the segments along the grid, 0 is changed to 1 below\n    gridtstyle = [1,1,1,1,0] # 1 for linear, 0 for log in each segment\n    gridtnpts  = [20, 20, 150.,50.,10.] # number of grid points in each segment\n    # define the density array for the SESAME AND GADGET2 tables\n    # R0REF is inserted into the table if it is not present in the original array\n    # need to have extra density resolution around the triple point\n    # 0 g/cm3 is removed if present\n    gridrvals  = [1.e-20, 0.5, 6.6, 7.4, 20., 30.] # g/cm3 -- this array defines the edges of the segments along the grid\n    gridrstyle = [0, 1, 1, 1, 1] # 1 for linear, 0 for log in each segment\n    gridrnpts  = [50, 20, 20, 40, 20] # number of grid points in each segment\n    # define the specific entropy array for the GADGET2 table\n    # 0 MJ/K/kg is removed if present\n    gridsvals  = [1.e-4,.1] # MJ/K/kg -- this array defines the edges of the segments along the grid\n    gridsstyle = [0] # 1 for linear, 0 for log in each segment\n    gridsnpts  = [200] # number of grid points in each segment\n#\nif gridflag == 1: # new form for the high resolution table entries in 301 table. Try for 1e6 values\n    # define the temperature array for the SESAME table\n    # 0 K is changed to 1 K\n    # T0REF is inserted into the table if it is not present in the original array\n    # need to have extra temperature resolution around the triple point\n    gridtvals  = [0, 100, 1750, 1950, 20000.,1.E5, 1.E7] # K -- this array defines the edges of the segments along the grid, 0 is changed to 1 below\n    gridtstyle = [1,1,1,1,1,0] # 1 for linear, 0 for log in each segment\n    gridtnpts  = [2, 75., 100, 500.,85.,50.] # number of grid points in each segment\n    # define the density array for the SESAME AND GADGET2 tables\n    # R0REF is inserted into the table if it is not present in the original array\n    # need to have extra density resolution around the triple point\n    # 0 g/cm3 is removed if present\n    gridrvals  = [1.e-20, 0.5, 6.6, 7.4, 20., 30.] # g/cm3 -- this array defines the edges of the segments along the grid\n    gridrstyle = [0, 1, 1, 1, 1] # 1 for linear, 0 for log in each segment\n    gridrnpts  = [150, 84, 101, 400, 100] # number of grid points in each segment\n    # define the specific entropy array for the GADGET2 table\n    # 0 MJ/K/kg is removed if present\n    gridsvals  = [1.e-4,.1] # MJ/K/kg -- this array defines the edges of the segments along the grid\n    gridsstyle = [0] # 1 for linear, 0 for log in each segment\n    gridsnpts  = [800] # number of grid points in each segment\n#----------------------------------------\n# END USER INPUT\n#----------------------------------------\n```\n\n\n```python\n# THIS CELL DEFINEs FUNCTIONS \n# define index function (must be a more efficient way to do this...)\nget_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]\n#\n# LOAD EXTERNAL FUNCTIONS AND OBJECT CLASSES\n# defines rational function interpolation functions rf1d and rf2d\n#%run rfinterpolation.py \n# defines class objects for extEOStable and functions to read in ANEOS input and output\n# READ THIS CODE IF YOU WANT TO UNDERSTAND THE FILE STRUCTURES\n%run eostable.py\n#import eostable\n# Run the following help for the functions in the class\n#help(extEOStable())\n```\n\n\n```python\n# THIS CELL HAS CODE TO GENERATE THE GRIDS AND WRITES TO A FILE TO BE READ BY ANEOS\nprint('GENERATING ARRAYS FOR THE INDICES OF THE TABULATED EOS.')\n#-------------- the following code generates the temperature array\ngridtarr = []\nfor iir in  range(1,len(gridtvals)):\n    if gridtstyle[iir-1] == 1:\n        # linear region\n        temptarr = np.arange(gridtnpts[iir-1])/gridtnpts[iir-1]*(gridtvals[iir]-gridtvals[iir-1])+gridtvals[iir-1]\n    if gridtstyle[iir-1] == 0:\n        # log region\n        logstep = (np.log10(gridtvals[iir])-np.log10(gridtvals[iir-1]))/gridtnpts[iir-1]\n        temptarr = np.power(10.,np.log10(gridtvals[iir-1])+(np.arange(gridtnpts[iir-1]))*logstep)\n    gridtarr = np.concatenate((gridtarr,temptarr))\n# check if T0REF already in the grid\n#indexT0REF = get_indexes(T0REF,gridtarr)\nindexT0REF = np.where(abs(T0REF-gridtarr)<1.E-4)[0]\nif len(indexT0REF) == 0:\n    # insert T0REF K into the array\n    indexT0REF = np.where((gridtarr-T0REF)>0.)[0]\n    gridtarr = np.concatenate((gridtarr[0:indexT0REF[0]],[T0REF],gridtarr[indexT0REF[0]::]))\n    if indexT0REF[0]>1:\n        print('Inserted the REFERENCE TEMPERATURE INTO THE ARRAY:',gridtarr[indexT0REF[0]-2:indexT0REF[0]+3])\n    else:\n        print('Inserted the REFERENCE TEMPERATURE INTO THE ARRAY:',gridtarr[indexT0REF[0]-1:indexT0REF[0]+3])\nelse:\n    print('T0REF already in temperature array: ',T0REF,gridtarr[indexT0REF[0]-2:indexT0REF[0]+2])\n# Remove 0 K or convert to 1 K\nindexzero = get_indexes(0.,gridtarr)\nindexone = get_indexes(1.,gridtarr)\nif len(indexzero) == 1 and len(indexone) == 0:\n    gridtarr[indexzero] = 1.\n    print('Zero kelvin changed to 1 kelvin.')\nelse:\n    gridtarr = np.delete(gridtarr, indexzero)\n    print('Deleted zero K index.')\n#\n#gridtsize = len(grdtarr)\nprint('Number of temperature points: ',len(gridtarr))\n#print(gridtarr)\n#------------ the following code generates the density array\ngridrarr = []\nfor iir in range(1,len(gridrvals)):\n    if gridrstyle[iir-1] == 1:\n        # linear region\n        temprarr = np.arange(gridrnpts[iir-1])/gridrnpts[iir-1]*(gridrvals[iir]-gridrvals[iir-1])+gridrvals[iir-1]\n    if gridrstyle[iir-1] == 0:\n        # log region\n        logstep = (np.log10(gridrvals[iir])-np.log10(gridrvals[iir-1]))/gridrnpts[iir-1]\n        temprarr = np.power(10.,np.log10(gridrvals[iir-1])+(np.arange(gridrnpts[iir-1]))*logstep)\n    gridrarr = np.concatenate((gridrarr,temprarr))\n# check if R0REF already in the grid\n#indexR0REF = get_indexes(R0REF,gridrarr)\nindexR0REF = np.where(abs(R0REF-gridrarr)<1.E-4)[0]\nif len(indexR0REF) == 0:\n    # insert R0REF  into the array\n    indexR0REF = np.where((gridrarr-R0REF)>0.)[0]\n    gridrarr = np.concatenate((gridrarr[0:indexR0REF[0]],[R0REF],gridrarr[indexR0REF[0]::]))\n    print('Inserted the REFERENCE DENSITY INTO THE ARRAY:',gridrarr[indexR0REF[0]-2:indexR0REF[0]+3])\n    #print('NOT INSERTING REFERENCE DENSITY INTO THE ARRAY.')\nelse:\n    print('R0REF already in density array: ',R0REF,gridrarr[indexR0REF[0]-2:indexR0REF[0]+2])\n# Remove 0 g/cm3 if present\nindexzero = get_indexes(0.,gridrarr)\nif len(indexzero) == 1:\n    gridrarr = np.delete(gridrarr, indexzero)\n    print('Deleted zero g/cm3 index.')\n#\n#gridrsize = len(gridrarr)\nprint('Number of density points: ',len(gridrarr))\n#print(gridrarr)\n#------------ the following code generates the specific entropy array for gadget tables\ngridsarr = []\nfor iir in range(1,len(gridsvals)):\n    if gridsstyle[iir-1] == 1:\n        # linear region\n        tempsarr = np.arange(gridsnpts[iir-1])/gridsnpts[iir-1]*(gridsvals[iir]-gridsvals[iir-1])+gridsvals[iir-1]\n    if gridsstyle[iir-1] == 0:\n        # log region\n        logstep = (np.log10(gridsvals[iir])-np.log10(gridsvals[iir-1]))/gridsnpts[iir-1]\n        tempsarr = np.power(10.,np.log10(gridsvals[iir-1])+(np.arange(gridsnpts[iir-1]))*logstep)\n    gridsarr = np.concatenate((gridsarr,tempsarr))\n# Remove 0 MJ/K/kg if present\nindexzero = get_indexes(0.,gridsarr)\nif len(indexzero) == 1:\n    gridsarr[indexzero]=1.e-20\n#    gridsarr = np.delete(gridsarr, indexzero)\n    print('replaced zero MJ/K/kg index with 1.E-20')\n#gridssize = len(gridsarr)\n#\nprint('Number of specific entropy points: ',len(gridsarr))\n#print(gridsarr)\n\nprint('Number of words in the standard SESAME 301 table (NR, NT, R, T, P, IE, HFE)=',2.+len(gridrarr)+len(gridtarr)+len(gridrarr)*len(gridtarr)*3.)\n#-----------------------------------------------------------\n#\nif DEVMODE:\n    print('WRITING tablegrid.txt FOR ANEOS in the local directory.\\n')\n    # write the table arrays to a file for the ANEOS driver to read in\n    tablegridfile = open(\"tablegrid.txt\",\"w\")  \n    tablegridfile.write(\"{:.6e}\".format(MATID)+'\\n')  \n    tablegridfile.write(\"{:.6e}\".format(DATE)+'\\n')  \n    tablegridfile.write(\"{:.6e}\".format(VERSION)+'\\n')  \n    tablegridfile.write(\"{:.6e}\".format(FMN)+'\\n')  \n    tablegridfile.write(\"{:.6e}\".format(FMW)+'\\n')  \n    tablegridfile.write(\"{:.6e}\".format(R0REF)+'\\n')  \n    tablegridfile.write(\"{:.6e}\".format(K0REF)+'\\n')  \n    tablegridfile.write(\"{:.6e}\".format(T0REF)+'\\n')  \n    tablegridfile.write(\"{:.6e}\".format(len(gridrarr))+'\\n')  # number of density points\n    tablegridfile.write(\"{:.6e}\".format(len(gridtarr))+'\\n')  # number of temperature points\n    for i in range(0,len(gridrarr)):\n        tablegridfile.write(\"{:.6e}\".format(gridrarr[i])+'\\n')\n    for i in range(0,len(gridtarr)):\n        tablegridfile.write(\"{:.6e}\".format(gridtarr[i])+'\\n')\n    tablegridfile.close()\n#\n#-----------------------------------------------------\n# Output GADGET2 Table information\nif MAKEGADGETTABLE:\n    print('Number of words in the extended GADGET2 EOS table (NR, NS, R, S, P, T, IE, CS, HFE, CV, KPA, MDQ)=',2.+len(gridrarr)+len(gridtarr)+len(gridrarr)*len(gridtarr)*8.)\n#------------------------------------------------------\n\n#----------------------------------------------------\n# Sp. Internal Energy grid for Tillotson\ntillearr = np.power(10.,np.arange(600)/600.*6.-3.) # MJ/kg\ntillearr = np.append(0.,tillearr)\nprint('Number of specific internal energy points for Tillotson EOS: ',len(tillearr))\n#----------------------------------------------------\n# Paranoia check\n# make sure all table grid values are unique\nif (len(np.unique(gridtarr))!=len(gridtarr)):\n    print('NON-UNIQUE VALUES IN TEMP ARRAY')\n    stopthecode\nif (len(np.unique(gridrarr))!=len(gridrarr)):\n    print('NON-UNIQUE VALUES IN DENSITY ARRAY')\n    stopthecode\nif (len(np.unique(gridsarr))!=len(gridsarr)):\n    print('NON-UNIQUE VALUES IN SP. ENTROPY ARRAY')\n    stopthecode\nif (len(np.unique(tillearr))!=len(tillearr)):\n    print('NON-UNIQUE VALUES IN SP. ENERGY ARRAY')\n    stopthecode\n\n#----------------------------------------------------\n\nprint('\\nDone generating EOS grids.\\n')\nprint('\\nCHECK THAT THE GRID ARRAYS ARE EVEN IN LENGTH.\\n')\n\n# END TABLE GRIDDING INFORMATION\n```\n\n    GENERATING ARRAYS FOR THE INDICES OF THE TABULATED EOS.\n    T0REF already in temperature array:  298.0 [254. 276. 298. 320.]\n    Zero kelvin changed to 1 kelvin.\n    Number of temperature points:  812\n    Inserted the REFERENCE DENSITY INTO THE ARRAY: [7.8095 7.841  7.85   7.8725 7.904 ]\n    Number of density points:  836\n    Number of specific entropy points:  800\n    Number of words in the standard SESAME 301 table (NR, NT, R, T, P, IE, HFE)= 2038146.0\n    WRITING tablegrid.txt FOR ANEOS in the local directory.\n    \n    Number of specific internal energy points for Tillotson EOS:  601\n    \n    Done generating EOS grids.\n    \n    \n    CHECK THAT THE GRID ARRAYS ARE EVEN IN LENGTH.\n    \n\n\n\n```python\nif DEVMODE:\n    # call aneos in the local directory\n    # output file is in the local directory\n    print('RUNNING IN DEVELOPMENT MODE')\n    print('Calling aneos in the local directory.')\n    completed = subprocess.run(['./aneos'])\n    print('Aneos call complete. CHECK THAT A NEW ANEOS.OUTPUT FILE WAS CREATED.')\n    print('aneos call result: ', completed.returncode)\n    print('Check ANEOS.OUTPUT file for errors.')\nelse:\n    print('RUNNING IN RELEASE MODE: NO ANEOS SYSTEM CALL.')\n    print('READING IN EOS DISTRIBUTION FILES.')\n```\n\n    RUNNING IN DEVELOPMENT MODE\n    Calling aneos in the local directory.\n    Aneos call complete. CHECK THAT A NEW ANEOS.OUTPUT FILE WAS CREATED.\n    aneos call result:  0\n    Check ANEOS.OUTPUT file for errors.\n\n\n\n```python\n# READ IN NEW ANEOS MODEL and fill the extEOStable class object\n# source in eostable.py\n#------------------------------------------------------------------\nNewEOS  = extEOStable() # FIRST make new empty EOS object\nNewEOS.loadextsesame('NEW-SESAME-EXT.TXT') # LOAD THE EXTENDED 301 SESAME FILE GENERATED BY STSM VERSION OF ANEOS\nNewEOS.loadstdsesame('NEW-SESAME-STD.TXT') # LOAD THE STANDARD 301 SESAME FILE GENERATED BY STSM VERSION OF ANEOS\nNewEOS.MODELNAME = MODELNAME # string set above in user input\nNewEOS.MDQ = np.zeros((NewEOS.NT,NewEOS.ND)) # makes the empty MDQ array\n#print(NewEOS.units) # these are the default units for SESAME rho-T tables\n#'Units: g/cm3, K, GPa, MJ/kg, MJ/kg, MJ/K/kg, cm/s, MJ/K/kg, KPA flag. 2D arrays are (NT,ND).'\n\n# Add the header info to the table. This could be done during the loading. \n# if made from this notebook, these values are set in the user-input above.\n# ** MAKE SURE THEY MATCH ANEOS.INPUT **\nNewEOS.MATID   = MATID\nNewEOS.DATE    = DATE\nNewEOS.VERSION = VERSION\nNewEOS.FMN     = FMN\nNewEOS.FMW     = FMW\nNewEOS.R0REF   = R0REF\nNewEOS.K0REF   = K0REF\nNewEOS.T0REF   = T0REF\nNewEOS.P0REF   = P0REF\n#\n# Load the information from ANEOS.INPUT and ANEOS.OUTPUT\nNewEOS.loadaneos(aneosinfname='ANEOS.INPUT',aneosoutfname='ANEOS.OUTPUT')\n#\n# calculate the principal Hugoniot from the table\nif DEVMODE:\n    # calculate the Hugoniot and write to a file\n    NewEOS.calchugoniot(r0=NewEOS.R0REF,t0=NewEOS.T0REF,writefilename='NEW-SESAME-HUG.TXT')\nelse:\n    # just calculate the Hugoniot and put it in the EOS object\n    NewEOS.calchugoniot(r0=NewEOS.R0REF,t0=NewEOS.T0REF)\n#\n# calculate the 1-bar profile; loop over temp\nNewEOS.onebar.T = np.zeros(NewEOS.NT)\nNewEOS.onebar.S = np.zeros(NewEOS.NT)\nNewEOS.onebar.rho = np.zeros(NewEOS.NT)\nit0 = np.where(NewEOS.T >= NewEOS.T0REF)[0]\nid0 = np.arange(NewEOS.ND)#np.where(NewEOS.rho >= 0.8*NewEOS.R0REF)[0]\nfor iit in range(0,NewEOS.NT):\n    NewEOS.onebar.T[iit] = NewEOS.T[iit]\n    NewEOS.onebar.S[iit] = np.interp(1.E-4,NewEOS.P[iit,id0],NewEOS.S[iit,id0])\n    NewEOS.onebar.rho[iit] = np.interp(1.E-4,NewEOS.P[iit,id0],NewEOS.rho[id0])\n    #print(iit,NewEOS.onebar.rho[iit],NewEOS.onebar.T[iit],NewEOS.onebar.S[iit]*1.E3)\n\n```\n\n    Done loading ANEOS files.\n    ANEOS WAS CALLED WITH THE FOLLOWING INPUT, LOADED FROM FILE  ANEOS.INPUT\n     *ANEOS INPUT FILE FOR STSM JUPYTER NOTEBOOK. VARIABLES MUST BE SPACED BY 10 CHARACTERS.\n     *         EOS#      string for EOS name           .....Hugoniot initial........ long\n     *                                                 T(eV)           Rho(g/cc)     flag\n     ANEOS1    -1        'IRON 130PT Thompson 1970'    THUG=-1         RHUG=-1\n    \n     *\n     *         nelem     type      rho0      temp0(K)  press0    B0/-Cbulk Gamma0    Tdebye(K)\n     *         V01       V02       V03       V04       V05       V06       V07       V08\n     ANEOS2    1         4         7.85      0.        0.        1.93E12   1.75      0.\n    \n     *         TG model  Gamma     Esep      Tmelt(K)  ..Critical Pt..     Thermal Conduction\n     *         or S1     3*C24     erg/g     or -Em    C53       C54       H0        C41\n     *         V09       V10       V11       V12       V13       V14       V15       V16\n     ANEOS3    0         2.        7.3E10    1809.     0.        0.        0.0       0.0\n    \n     *         solid     .....Solid-solid phase transition data.....                 rhol/rhos\n     *         rhomin    D1        D2        D3        D4        D5        Hfusion   or -rholiq\n     *         V17       V18       V19       V20       V21       V22       V23       V24\n     ANEOS4    0         8.36      8.75      1.12E11   2.3E12    5.0E12    0.0       0.0\n    \n     *\n     *         Elements in material (number must = nelem)\n     *         Z         Atomic Fraction\n     ANEOS8    26        1.0\n    \n    READING DATA FROM ANEOS OUTPUT FILE  ANEOS.OUTPUT\n\n\n\n```python\n# Make a NOTENSION TABLE and GADGET TABLE\n################### REMOVE TENSION REGION ###########################\n## The GADGET2 tables do not have a tension region. \n## If the gadget2 table is selected, then must generate a no-tension table\nif MAKEGADGETTABLE:\n    REMOVETENSIONFLAG=1  # 0- keep tension region; 1- remove tension region\n\n# minimum pressure 1.E-30\n# minimum sp energy about 1.E-4 before negative entropy region\n# minimum sp entropy about 1.E-5 before negative entropy region\n# minimum HFE about 1.E-3 before negative entropy region\n# minimum sound speed about 1.E-10 before negative entropy region\n# minimum sp heat capacity about 1.E-4 before negative entropy region\n\n## FUTURE WORK: THIS SECTION COULD USE THE LEVER RULE TO FILL IN THE MISSING POINTS\n## SINCE MANY VALUES ARE NEAR THE LOWER LIMITS IN THE SUBLIMATION REGION ANYWAY, \n## HERE, TENSION REGION VALUES ARE FILLED IN WITH THE ADJACENT S-V DOME VALUES\n## This is obviously bad for interpolations. Fix for future work.\nif REMOVETENSIONFLAG:\n    # First make a deep copy of the original table with the tension region\n    NewEOSorig = deepcopy(NewEOS)\n    NewEOS.MODELNAME = NewEOS.MODELNAME+'notension'\n    # THIS SECTION REWRITES NEGATIVE PRESSURE REGION\n    # The tension region is in the solid-vapor phase boundary. \n    # Use the liquid-vapor phase boundary. Below the temperature of the triple point, it is the sublimation curve.\n    # But the pressures for the solid calculation is spurious at very low pressures, so use the vapor pressure.\n    # HFE = GFE + TS\n    print('REMOVING TENSION REGION FROM THE ORIGINAL ANEOS TABLE.')\n    for itt in range(NewEOS.NT-1,-1,-1):\n        tmp = np.where(NewEOS.P[itt,:] < 0.)\n        if (len(tmp[0]) > 0):\n            badind = tmp[0]\n            if badind[0] > 0:\n                #print(itt, len(badind), NewEOS.T[itt], 'tension only', NewEOS.P[itt,badind[0]-4:badind[0]+1])\n                # at this temperature, all densities are the same pressure in the vapor dome\n                # so use the adjacent positive pressure value\n                # do the same for all the variables since there is very little change in this region of the dome.\n                # Errors introduced by interpolating the vapor curve are comparable to\n                # recalculating the lever rule. Would need to call ANEOS again to get good end point values\n                # to calculate the mass-weighted value via the lever rule.\n                NewEOS.P[itt,badind] = np.full(len(badind),NewEOS.P[itt,badind[0]-1])\n                NewEOS.U[itt,badind] = np.full(len(badind),NewEOS.U[itt,badind[0]-1])\n                NewEOS.S[itt,badind] = np.full(len(badind),NewEOS.S[itt,badind[0]-1])\n                NewEOS.A[itt,badind] = np.full(len(badind),NewEOS.A[itt,badind[0]-1])\n                NewEOS.cs[itt,badind] = np.full(len(badind),NewEOS.cs[itt,badind[0]-1])\n                NewEOS.cv[itt,badind] = np.full(len(badind),NewEOS.cv[itt,badind[0]-1])\n                NewEOS.KPA[itt,badind] = np.full(len(badind),2)\n                NewEOS.MDQ[itt,badind] = np.full(len(badind),-1) # replaced tension region flag\n            else:\n                print('SOMETHING VERY WRONG WITH TENSION IN THE TABLE')\n                makethecodestop # please tell me a more graceful way to stop the notebook\n    #\n    # THIS SECTION RESETS NEGATIVE SPECIFIC ENTROPIES WITH ADJACENT VALUES OR MINIMUM POSITIVE VALUES\n    # THESE VALUES TYPICALLY DEFINE THE COLD COMPRESSION LIMIT OF THE MATERIAL\n    # OR SPURIOUS NEGATIVE ENTROPIES AT VERY LOW PRESSURES (IMPERFECT DEBYE MODEL IN ANEOS)\n    for itt in range(NewEOS.NT-1,-1,-1):\n        tmp = np.where(NewEOS.S[itt,:] < 0.)\n        if (len(tmp[0]) > 0):\n            badind = tmp[0]\n            if badind[0] > 0:\n                #print(itt, antarr[itt], andarr[badind[0]], badind[0],len(badind),'negative entropy', ansarr[itt,badind[0]],ansarr[itt,badind[0]-1])\n                NewEOS.P[itt,badind] = np.full(len(badind),NewEOS.P[itt,badind[0]-1]) # use the adjacent pressure at this temperature in the dome\n                NewEOS.U[itt,badind] = np.full(len(badind),NewEOS.U[itt,badind[0]-1])\n                NewEOS.S[itt,badind] = np.full(len(badind),NewEOS.S[itt,badind[0]-1])\n                NewEOS.A[itt,badind] = np.full(len(badind),NewEOS.A[itt,badind[0]-1])\n                NewEOS.cs[itt,badind] = np.full(len(badind),NewEOS.cs[itt,badind[0]-1])\n                NewEOS.cv[itt,badind] = np.full(len(badind),NewEOS.cv[itt,badind[0]-1])\n                #NewEOS.KPA[itt,badind]  # leave as original region flag\n                NewEOS.MDQ[itt,badind] = np.full(len(badind),-2) # negative entropies flag\n                #print('Some NEGATIVE  S AT THIS INDEX, TEMP(K): ',itt, NewEOS.T[itt],NewEOS.P[itt,badind[0]-1],NewEOS.P[itt,badind[0]-2]) #, badind[0],len(badind),'negative entropy', NewEOS.S[itt,badind[0]])\n            if badind[0] == 0:\n                print('All S VALUES NEGATIVE AT THIS INDEX, TEMP(K): ',itt, NewEOS.T[itt]) #, badind[0],len(badind),'negative entropy', NewEOS.S[itt,badind[0]])\n                NewEOS.S[itt,badind] = np.full(len(badind),1.E-10)            \n                NewEOS.U[itt,badind] = np.full(len(badind),1.E-10) # also replace the negative sp. internal energies           \n                NewEOS.MDQ[itt,badind] = np.full(len(badind),-2) # negative entropies flag\n\n    #### ONLY WRITE A NEW TABLE IN DEVELOPMENT MODE\n    if DEVMODE:\n        #### WRITE NEW SESAME TABLE WITH NO TENSION REGION\n        #     WRITE STANDARD (SHORT) SESAME FILE\n        #     WRITE SESAME TABLE TO FILE LIMITED TO P, E, HFE\n        NewEOS.writestdsesame(writestdsesfname=\"NEW-SESAME-STD-NOTENSION.TXT\")\n\n#### ONLY WRITE A NEW TABLE IN DEVELOPMENT MODE\n#if DEVMODE:\n#    #### WRITE MDQ Flag as a 301-style table\n#    NewEOS.writemdqsesame(writemdqsesfname=\"NEW-SESAME-MDQ.TXT\")\n#\n#--------------------------------------------------------------------------\n########## MAKE GADGET2 EOS TABLE ARRAYS ###################\n# LATER WE CAN TURN THIS INTO A FUNCTION IN THE GADGET EOS OBJECT\n# FLAG IS SET ABOVE IN THE USER INPUT SECTION\n# MAKEGADGETTABLE = 1 # 1 - do it ; 0 - skip it\nif MAKEGADGETTABLE:\n    print('Starting interpolation for GADGET table.')\n    GadEOS  = extGADtable() # make new empty Gadget EOS object\n    #\n    # rho array is andarr to match the SESAME table\n    # S array is gridsarr\n    GadEOS.ND  = len(gridrarr)\n    GadEOS.NS  = len(gridsarr)\n    GadEOS.rho = gridrarr\n    GadEOS.S   = gridsarr\n    GadEOS.P   = np.zeros((GadEOS.NS,GadEOS.ND))\n    GadEOS.T   = np.zeros((GadEOS.NS,GadEOS.ND))\n    GadEOS.U   = np.zeros((GadEOS.NS,GadEOS.ND))\n    GadEOS.A   = np.zeros((GadEOS.NS,GadEOS.ND))\n    GadEOS.cs  = np.zeros((GadEOS.NS,GadEOS.ND))\n    GadEOS.cv  = np.zeros((GadEOS.NS,GadEOS.ND))\n    GadEOS.KPA = np.zeros((GadEOS.NS,GadEOS.ND))\n    GadEOS.MDQ = np.zeros((GadEOS.NS,GadEOS.ND))\n    GadEOS.MODELNAME = NewEOS.MODELNAME+'-gadget-linear-int'\n    #\n    # some combinations of density and sp. entropy are not in the EOS surface\n    # in these cases, apply minimum values\n    gadpmin  = np.min(NewEOS.P) # GPa\n    gadsmin  = 1.E-30     # MJ/K/kg\n    gademin  = np.min(NewEOS.U)    # MJ/kg\n    gadtmin  = 1.     # K\n    gadcmin  = np.min(NewEOS.cs) # cm/s\n    gadcvmin = 0.     # MJ/K/kg\n    gadamin  = np.min(NewEOS.A) # can be negative    # MJ/kg\n    print('Minimum values used in the rational function interpolation scheme:')\n    print('gadpmin,gadsmin,gademin,gadtmin,gadcmin,gadcvmin,gadamin=')\n    print(gadpmin,gadsmin,gademin,gadtmin,gadcmin,gadcvmin,gadamin)\n    #\n    # some combinations of density and sp. entropy are not in the EOS surface\n    # in these cases, fill the region with the adjacent real values from the original T-RHO table\n    # ----------------------------------------------------------\n    # SIMPLE LINEAR INTERPOLATION TO FLIP T-RHO to S-RHO table\n    print(\"LINEAR INTERPOLATION FOR GADGET TABLE.\")\n    for iid in range(0,GadEOS.ND):\n        # same density arrays for the T-rho table and S-rho table\n        sall1d = NewEOS.S[:,iid]\n        pall1d = NewEOS.P[:,iid]\n        eall1d = NewEOS.U[:,iid]\n        tall1d = NewEOS.T[:]\n        call1d = NewEOS.cs[:,iid]\n        cvall1d = NewEOS.cv[:,iid]\n        aall1d = NewEOS.A[:,iid]\n        kall1d = NewEOS.KPA[:,iid]\n        mdqall1d = NewEOS.MDQ[:,iid]\n        # interpolate P at the new S\n        testinterp = interpolate.interp1d(sall1d,pall1d)\n        tmpind = np.where(gridsarr < np.max(sall1d))[0]\n        GadEOS.P[tmpind,iid] = testinterp(gridsarr[tmpind])\n        tmpind = np.where(gridsarr >= np.max(sall1d))[0]\n        GadEOS.P[tmpind,iid] = pall1d[NewEOS.NT-1]\n        # interpolate E at the new S\n        testinterp = interpolate.interp1d(sall1d,eall1d)\n        tmpind = np.where(gridsarr < np.max(sall1d))[0]\n        GadEOS.U[tmpind,iid] = testinterp(gridsarr[tmpind])\n        tmpind = np.where(gridsarr >= np.max(sall1d))[0]\n        GadEOS.U[tmpind,iid] = eall1d[NewEOS.NT-1]\n        # interpolate T at the new S\n        testinterp = interpolate.interp1d(sall1d,tall1d)\n        tmpind = np.where(gridsarr < np.max(sall1d))[0]\n        GadEOS.T[tmpind,iid] = testinterp(gridsarr[tmpind])\n        tmpind = np.where(gridsarr >= np.max(sall1d))[0]\n        GadEOS.T[tmpind,iid] = tall1d[NewEOS.NT-1]\n        # interpolate sound speed at the new S\n        testinterp = interpolate.interp1d(sall1d,call1d)\n        tmpind = np.where(gridsarr < np.max(sall1d))[0]\n        GadEOS.cs[tmpind,iid] = testinterp(gridsarr[tmpind])\n        tmpind = np.where(gridsarr >= np.max(sall1d))[0]\n        GadEOS.cs[tmpind,iid] = call1d[NewEOS.NT-1]\n        # interpolate sp. heat capacity at the new S\n        testinterp = interpolate.interp1d(sall1d,cvall1d)\n        tmpind = np.where(gridsarr < np.max(sall1d))[0]\n        GadEOS.cv[tmpind,iid] = testinterp(gridsarr[tmpind])\n        tmpind = np.where(gridsarr >= np.max(sall1d))[0]\n        GadEOS.cv[tmpind,iid] = call1d[NewEOS.NT-1]\n        # interpolate HFE at the new S\n        testinterp = interpolate.interp1d(sall1d,aall1d)\n        tmpind = np.where(gridsarr < np.max(sall1d))[0]\n        GadEOS.A[tmpind,iid] = testinterp(gridsarr[tmpind])\n        tmpind = np.where(gridsarr >= np.max(sall1d))[0]\n        GadEOS.A[tmpind,iid] = call1d[NewEOS.NT-1]\n        # interpolate phase information KPA flag at the new S\n        testinterp = interpolate.interp1d(sall1d,kall1d)\n        tmpind = np.where(gridsarr < np.max(sall1d))[0]\n        GadEOS.KPA[tmpind,iid] = testinterp(gridsarr[tmpind])\n        tmpind = np.where(gridsarr >= np.max(sall1d))[0]\n        GadEOS.KPA[tmpind,iid] = call1d[NewEOS.NT-1]\n        # interpolate model development quality flag at the new S\n        testinterp = interpolate.interp1d(sall1d,mdqall1d)\n        tmpind = np.where(gridsarr < np.max(sall1d))[0]\n        GadEOS.MDQ[tmpind,iid] = testinterp(gridsarr[tmpind])\n        tmpind = np.where(gridsarr >= np.max(sall1d))[0]\n        GadEOS.MDQ[tmpind,iid] = call1d[NewEOS.NT-1]\n    #\n    GadEOSlin = deepcopy(GadEOS)\n    #\n    '''\n    # ----------------------------------------------------------\n    # 1D RATIONAL FUNCTION INTERPOLATION METHOD FROM KERLEY\n    print(\"RATIONAL FUNCTION INTERPOLATION TO GENERATE GADGET2 EOS TABLE.\")\n    for iid in range(0,GadEOS.ND):\n        GadEOS.MODELNAME = NewEOS.MODELNAME+'-gadget-ratfunc-int'\n        #\n        # same density arrays for the T-rho table and S-rho table\n        sall1d  = NewEOS.S[:,iid]\n        pall1d  = NewEOS.P[:,iid]\n        eall1d  = NewEOS.U[:,iid]\n        tall1d  = NewEOS.T[:]\n        call1d  = NewEOS.cs[:,iid]\n        cvall1d = NewEOS.cv[:,iid]\n        aall1d  = NewEOS.A[:,iid]\n        #kall1d = NewEOS.KPA[:,iid]\n        #mdqall1d = NewEOS.MDQ[:,iid]\n        #\n        # interpolate P at the new S\n        GadEOS.P[:,iid] = rf1d(sall1d,pall1d,gridsarr,gadpmin)\n        # interpolate E at the new S\n        GadEOS.U[:,iid] = rf1d(sall1d,eall1d,gridsarr,gademin)\n        # interpolate T at the new S\n        GadEOS.T[:,iid] = rf1d(sall1d,tall1d,gridsarr,gadtmin)\n        # interpolate sound speed at the new S\n        GadEOS.cs[:,iid] = rf1d(sall1d,call1d,gridsarr,gadcmin)\n        # interpolate sp. heat capacity at the new S\n        GadEOS.cv[:,iid] = rf1d(sall1d,cvall1d,gridsarr,gadcvmin)\n        # interpolate HFE at the new S\n        GadEOS.A[:,iid] = rf1d(sall1d,aall1d,gridsarr,gadamin)\n        # Do not interpolate KPA or MDQ with rational function interp. Use Linear.\n        # do not overwrite the linear interpolation above.\n    '''\n    #\n    print('Done interpolating the gadget2 table.')\n    #print('Using RATIONAL FUNCTION INTERPOLATION EXCEPT FOR KPA and MDQ FLAGS (bilinear).')\n    if DEVMODE:\n        # ONLY WRITE GADGET2 TABLE TO DISK IN DEVELOPMENT MODE\n        #### WRITE NEW GADGET2 TABLE WITH NO TENSION REGION\n        #### This ascii table format follows the sesame table format of 5 columns of numbers in 16.8e format\n        #### the STYLE variable is just a counter to 5 to know when to write a newline\n        GadEOS.writestdgadget(writestdgadgetfname=\"NEW-GADGET-STD-NOTENSION.TXT\")\n        GadEOS.writeextgadget(writeextgadgetfname=\"NEW-GADGET-EXT-NOTENSION.TXT\")\n\n```\n\n\n```python\n# READ IN FORSTERITE MATERIAL DATA SETS\ndatadir='../data/'\n#======================================================================\n#======================================================================\n# Gather some experimental and theoretical data on forsterite\n\nironSTP_S = 0.489211596E-3 # sp. entropy MJ/K/kg JANAF STP value\n\n# iron 1 bar entropy Desai 1986\n#T (K), Cp (J/mol/K), dH0 (J/mol), S (J/mol/K)\nDesai_file=datadir+'tabula-Desai-Table2.csv'\nDesai_datarr = pd.read_csv(Desai_file,nrows=67)\nDesai_tarr = Desai_datarr.iloc[:,0].values # temp K\nDesai_sarr = Desai_datarr.iloc[:,3].values/55.847+0.489211596 # sp. entropy J/mol/K->kJ/kg/K offset by JANAF STP value\n\n# iron 1 bar liquid density Assael et al. PCRD 2006 Table 3\n# T(K), density (kg/m3)\nAssael_file=datadir+'tabula-Assael-Table3.csv'\nAssael_datarr = pd.read_csv(Assael_file,nrows=15)\nAssael_tarr = Assael_datarr.iloc[:,0].values # temp K\nAssael_rarr = Assael_datarr.iloc[:,1].values # rho kg/m3\n\n# Iron alloy solidus Fe-16Si from Fischer et al. 2012 in Fig 1.2A from Fischer AGU 2016\nFischer_file=datadir+'Fischer-Fig1.2-AFischer-lower.csv'\nFischer_datalow = pd.read_csv(Fischer_file,skiprows=1)\nFischer_file=datadir+'Fischer-Fig1.2-AFischer-upper.csv'\nFischer_datahigh = pd.read_csv(Fischer_file,skiprows=1)\n\n# Kraus et al. Nature Geoscience 2015\n# Entropy tie point on the Hugoniot\nZtie_p=507. # GPa\nZtie_perrlow=-85. # GPa\nZtie_perrhigh=+65. # GPa\nZtie_s=2240.E-6 # MJ/K/kg\nZtie_serr=60.E-6 # MJ/K/kg\n\n# http://www.ihed.ras.ru/rusbank/\n# iron data compilation REFERENCES ARE LISTED AT THE END OF THE FILE\n# m [rho0/rho], U=part vel(km/s), D = shockvel(km/s), P (GPa)\nihed_rho0=7.873\nihed_file=datadir+'iron-Russian-shockwave-database.txt'\nihed_datarr = np.loadtxt(ihed_file,skiprows=4,usecols=(0,1,2,3,4),max_rows=571)\nihed_fullden = np.where(ihed_datarr[:,0] == 1.)[0]\n#ihed_datarr.shape\n#print(ihed_datarr[ihed_fullden,3])\n#print(max(ihed_datarr[ihed_fullden,3]))\n\n# http://www.ihed.ras.ru/rusbank/\n# iron data compilation REFERENCES ARE LISTED AT THE END OF THE FILE\n#    m        U        D        Cs          P        R/R0      R          E-E0   Rem  Ref\nihed_file=datadir+'iron-Russian-database-cs.txt'\nihed_csarr = np.loadtxt(ihed_file,skiprows=4,usecols=(0,1,2,3,4,5,6),max_rows=9)\n#ihed_datarr.shape\n#print(ihed_csarr[:,3])\n#print(max(ihed_datarr[ihed_fullden,3]))\n\n# http://www.ihed.ras.ru/rusbank/\n# iron data compilation REFERENCES ARE LISTED AT THE END OF THE FILE\n#    m        U0       P0       U        P     Rem  Ref\nihed_file=datadir+'iron-Russian-database-rel.txt'\nihed_relarr = np.loadtxt(ihed_file,skiprows=4,usecols=(0,1,2,3,4),max_rows=20)\n#ihed_datarr.shape\n#print(ihed_relarr[:,3])\n#print(max(ihed_datarr[ihed_fullden,3]))\n\n# Sjostrom & Crockett 2018 Hugoniot equation from their paper; temperature equation has a problem\nscironuparr = np.arange(300)/300.*30. # km/s\nscironusarr = 3.7885 + 1.25524*scironuparr + 0.518106*scironuparr*np.exp(-0.0866344*scironuparr) # km/s\nscironparr = 7.874*(scironuparr)*(scironusarr) # GPa\nscironrarr = 1./((1./7874.)*(1.-scironuparr/scironusarr))/1.e3 # g/cm3\n#scirontarr = 1.24182E-3*scironparr+2.80723E-6*np.power(scironparr,2.)-1.31703E-9*np.power(scironparr,3.)+1.88449E-13*np.power(scironparr,4.)*11604. # K\n\n# Kraus et al. 2015 fit Hugoniot SOM Equation 7\nkrausironuparr = (np.arange(200)+1)/200.*20. # km/s\nkrausironusarr = 3.41 + 1.84*krausironuparr - 0.036*krausironuparr*krausironuparr # km/s\nkrausironparr = 7854.*(krausironuparr)*(krausironusarr)/1.e3 # GPa\nkrausironrarr = 1./((1./7854.)*(1.-krausironuparr/krausironusarr))/1.e3 # g/cm3\nkrausironsarr = -1.984e4/np.sqrt(krausironparr) + 39.9*np.sqrt(krausironparr)-0.1047*krausironparr+2279.\nkrausironsuarr = -1.845e4/np.sqrt(krausironparr) + 45.7*np.sqrt(krausironparr)-0.1193*krausironparr+2270.\nkrausironslarr = -2.631e4/np.sqrt(krausironparr) + 22.33*np.sqrt(krausironparr)-0.007689*krausironparr+2804.\n\nkrausliqrho = 6.01 # g/cm3 1 bar boiling point, 3133 K Kraus et al. 2015 SOM Equation 6\nkrausironliqusarr = 0.79 + 0.50*krausliqrho + (1.19 + 0.0307*krausliqrho)*krausironuparr # km/s\nkrausironliqparr = krausliqrho*(krausironuparr)*(krausironliqusarr) # GPa\nkrausironliqrarr = 1./((1./krausliqrho)*(1.-krausironuparr/krausironliqusarr)) # g/cm3\nironliq_r0=krausliqrho\nironliq_t0=3133.\n\n\n```\n\n## Color mesh plots of the SESAME Rho-T table\n\n\n\n```python\n# PLOT COLOR SHADED VALUES RHO-T TABLE\nlw=1\nsfont = 15\nds = (10,10)\n\n%matplotlib inline\nfig, ([ax0, ax1], [ax2,ax3], [ax4,ax5])= plt.subplots(nrows=3,ncols=2,figsize=(14,24))\nplt.subplots_adjust(wspace=0.4)\n#plt.tight_layout(pad=0.6)\n\n##================ Pressure\nim1=ax0.pcolormesh(NewEOS.rho,NewEOS.T,(np.log10(NewEOS.P)+25)/29.,cmap=local_cmaps.parula,vmin=0,vmax=1,edgecolors='face')\nax0.plot(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax0.plot(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax0.plot(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax0.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax0.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax0.set_ylim(0.,20000)\nax0.set_xlim(0,30.)\nax0.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax0.set_ylabel('Temperature (K)',size=sfont)\nax0.set_title('Colors=log$_{10}$(P (GPa))',size=sfont)\nax0.tick_params(labelsize=sfont)\n\ndivider0 = make_axes_locatable(ax0)\ncax0 = divider0.append_axes('right', size='5%', pad=0.05)\ncbar0 = fig.colorbar(im1, cax=cax0, ticks = [],orientation='vertical')\n#cbar0.ax.set_yticklabels(['  ','  ','  '])  # vertical colorbar\ncbar0.set_label('Log$_{10}$(P) [GPa]',size=sfont)\n#cbar0.ax.set_yticklabels(['-25','-11','+4'])  # vertical colorbar\n\nim1=ax1.pcolormesh(NewEOS.rho,NewEOS.T,(np.log10(NewEOS.P)+25)/29.,cmap=local_cmaps.parula,vmin=0,vmax=1,edgecolors='face')\nax1.loglog(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax1.loglog(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax1.loglog(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax1.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax1.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax1.set_ylim(10.,1.E7)\nax1.set_xlim(1.E-21,100.)\nax1.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax1.set_ylabel('Temperature (K)',size=sfont)\nax1.set_title('Colors=log$_{10}$(P (GPa))',size=sfont)\nax1.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax1)\ncax = divider.append_axes('right', size='5%', pad=0.05)\ncbar = fig.colorbar(im1, cax=cax, ticks = [0, 0.5, 1], orientation='vertical')\ncbar.ax.set_yticklabels(['-25','-11', '+4'])  # vertical colorbar\ncbar.set_label('Log$_{10}$(P) [GPa]',size=sfont)\n\n\n#================ Sp. Int. Energy\nim1=ax2.pcolormesh(NewEOS.rho,NewEOS.T,(np.log10(NewEOS.U)+4.)/10.,cmap=local_cmaps.parula,vmin=0,vmax=1,edgecolors='face')\nax2.plot(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax2.plot(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax2.plot(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax2.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax2.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax2.set_ylim(0.,20000)\nax2.set_xlim(0,30.)\nax2.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax2.set_ylabel('Temperature (K)',size=sfont)\nax2.set_title('Colors=log$_{10}$(Sp. Int. Energy (MJ/kg))',size=sfont)\nax2.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax2)\ncax = divider.append_axes('right', size='5%', pad=0.05)\n# does not want to label ticks in this location\ncbar = fig.colorbar(im1, cax=cax, ticks = [], orientation='vertical')\n#cbar.ax.set_yticklabels(['','',''])  # vertical colorbar\ncbar.set_label('Log$_{10}$(E) [MJ/kg]',size=sfont)\n#cbar.ax.set_yticklabels(['-4','+1','+6'])  # vertical colorbar\n\n\nax3.pcolormesh(NewEOS.rho,NewEOS.T,(np.log10(NewEOS.U)+4.)/10.,cmap=local_cmaps.parula,vmin=0,vmax=1)\nax3.loglog(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax3.loglog(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax3.loglog(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax3.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax3.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax3.set_ylim(10.,1.E7)\nax3.set_xlim(1.E-21,100.)\nax3.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax3.set_ylabel('Temperature (K)',size=sfont)\nax3.set_title('Colors=log$_{10}$(E (MJ/kg))',size=sfont)\nax3.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax3)\ncax = divider.append_axes('right', size='5%', pad=0.05)\n#cbar = fig.colorbar(im1, cax=cax, ticks = [0, 0.5, 1], orientation='vertical')\n#cbar.ax.set_yticklabels(['-6', '-3.5', '-1'])  # vertical colorbar\ncbar = fig.colorbar(im1, cax=cax, ticks = [0, 0.5, 1], orientation='vertical')\ncbar.ax.set_yticklabels(['-4', '+1','+6'])  # vertical colorbar\ncbar.set_label('Log$_{10}$(E) [MJ/kg]',size=sfont)\n\n#================ Sp. Entropy\nim1=ax4.pcolormesh(NewEOS.rho,NewEOS.T,(np.log10(NewEOS.S)+4.)/4.,cmap=local_cmaps.parula,vmin=0,vmax=1,edgecolors='face')\nax4.plot(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax4.plot(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax4.plot(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax4.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax4.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax4.set_ylim(0.,20000)\nax4.set_xlim(0,30.)\nax4.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax4.set_ylabel('Temperature (K)',size=sfont)\nax4.set_title('Colors=log$_{10}$(Sp. Entropy (MJ/K/kg))',size=sfont)\nax4.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax4)\ncax = divider.append_axes('right', size='5%', pad=0.05)\ncbar = fig.colorbar(im1, cax=cax, ticks = [], orientation='vertical')\n#cbar.ax.set_yticklabels(['-4', '-2', '0'])  # vertical colorbar\ncbar.set_label('Log$_{10}$(S) [MJ/K/kg]',size=sfont)\n\n\nax5.pcolormesh(NewEOS.rho,NewEOS.T,(np.log10(NewEOS.S)+4.)/4.,cmap=local_cmaps.parula,vmin=0,vmax=1)\nax5.loglog(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax5.loglog(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax5.loglog(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax5.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax5.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax5.set_ylim(10.,1.E7)\nax5.set_xlim(1.E-21,100.)\nax5.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax5.set_ylabel('Temperature (K)',size=sfont)\nax5.set_title('Colors=log$_{10}$(Sp. Entropy (MJ/K/kg))',size=sfont)\nax5.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax5)\ncax = divider.append_axes('right', size='5%', pad=0.05)\n#cbar = fig.colorbar(im1, cax=cax, ticks = [0, 0.5, 1], orientation='vertical')\n#cbar.ax.set_yticklabels(['-6', '-3.5', '-1'])  # vertical colorbar\ncbar = fig.colorbar(im1, cax=cax, ticks = [0, 0.5, 1], orientation='vertical')\ncbar.ax.set_yticklabels(['-4', '-2','0'])  # vertical colorbar\ncbar.set_label('Log$_{10}$(S) [MJ/K/kg]',size=sfont)\n\n\n##============= start new plot\nfig2, ([ax0, ax1], [ax2,ax3], [ax4,ax5])= plt.subplots(nrows=3,ncols=2,figsize=(14,24))\nplt.subplots_adjust(wspace=0.4)\n\n#================ Sound Speed\nim1=ax0.pcolormesh(NewEOS.rho,NewEOS.T,(np.log10(NewEOS.cs)+3.)/10.,cmap=local_cmaps.parula,vmin=0,vmax=1,edgecolors='face')\nax0.plot(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax0.plot(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax0.plot(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax0.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax0.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax0.set_ylim(0.,20000)\nax0.set_xlim(0,30.)\nax0.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax0.set_ylabel('Temperature (K)',size=sfont)\nax0.set_title('Colors=log$_{10}$(Sound Speed (cm/s))',size=sfont)\nax0.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax0)\ncax = divider.append_axes('right', size='5%', pad=0.05)\ncbar = fig.colorbar(im1, cax=cax, ticks = [], orientation='vertical')\n#cbar.ax.set_yticklabels(['-3', '+2', '+7'])  # vertical colorbar\ncbar.set_label('Log$_{10}$(Cs) [cm/s]',size=sfont)\n\n\nax1.pcolormesh(NewEOS.rho,NewEOS.T,(np.log10(NewEOS.cs)+3.)/10.,cmap=local_cmaps.parula,vmin=0,vmax=1)\nax1.loglog(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax1.loglog(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax1.loglog(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax1.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax1.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax1.set_ylim(10.,1.E7)\nax1.set_xlim(1.E-21,100.)\nax1.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax1.set_ylabel('Temperature (K)',size=sfont)\nax1.set_title('Colors=log$_{10}$(sound speed (cm/s))',size=sfont)\nax1.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax1)\ncax = divider.append_axes('right', size='5%', pad=0.05)\n#cbar = fig.colorbar(im1, cax=cax, ticks = [0, 0.5, 1], orientation='vertical')\n#cbar.ax.set_yticklabels(['-6', '-3.5', '-1'])  # vertical colorbar\ncbar = fig.colorbar(im1, cax=cax, ticks = [0, 0.5, 1], orientation='vertical')\ncbar.ax.set_yticklabels(['-3', '+2', '+7'])  # vertical colorbar\ncbar.set_label('Log$_{10}$(Cs) [cm/s]',size=sfont)\n\n\n#================ HFE\namin = np.min(NewEOS.A)\namin = -1000.\nalogmax = 1500. #np.max(anaarrodd)-amin #np.max(np.log10(anaarrodd-amin))\n#print('amin, log10(amin)',amin,np.log10(-amin))\n#print('alogmax=',alogmax)\nim1=ax2.pcolormesh(NewEOS.rho,NewEOS.T,(NewEOS.A-amin)/alogmax,cmap=local_cmaps.parula,vmin=0,vmax=1,edgecolors='face')\nax2.plot(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax2.plot(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax2.plot(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax2.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax2.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax2.set_ylim(0.,20000)\nax2.set_xlim(0,30.)\nax2.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax2.set_ylabel('Temperature (K)',size=sfont)\nax2.set_title('Colors=HFE (MJ/kg)',size=sfont)\nax2.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax2)\ncax = divider.append_axes('right', size='5%', pad=0.05)\ncbar = fig.colorbar(im1, cax=cax, ticks = [], orientation='vertical')\n#cbar.ax.set_yticklabels(['-1000','-500','0','500'])  # vertical colorbar\ncbar.set_label('Log$_{10}$(HFE) [MJ/kg]',size=sfont)\n\n\nax3.pcolormesh(NewEOS.rho,NewEOS.T,(NewEOS.A-amin)/alogmax,cmap=local_cmaps.parula,vmin=0,vmax=1)\nax3.loglog(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax3.loglog(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax3.loglog(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax3.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax3.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax3.set_ylim(10.,1.E7)\nax3.set_xlim(1.E-21,100.)\nax3.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax3.set_ylabel('Temperature (K)',size=sfont)\nax3.set_title('Colors=HFE (MJ/kg)',size=sfont)\nax3.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax3)\ncax = divider.append_axes('right', size='5%', pad=0.05)\n#cbar = fig.colorbar(im1, cax=cax, ticks = [0, 0.5, 1], orientation='vertical')\n#cbar.ax.set_yticklabels(['-6', '-3.5', '-1'])  # vertical colorbar\ncbar = fig.colorbar(im1, cax=cax, ticks = [0,.333,.6667,  1], orientation='vertical')\ncbar.ax.set_yticklabels(['-1000','-500','0','500'])  # vertical colorbar\ncbar.set_label('Log$_{10}$(HFE) [MJ/kg]',size=sfont)\n\n\n\n#================ KPA flag\ncmap2 = cm.get_cmap('plasma', 6)    # 6 discrete colors\n\nim1=ax4.pcolormesh(NewEOS.rho,NewEOS.T,((NewEOS.KPA)-0.5)/6.,cmap=cmap2,vmin=0,vmax=1,edgecolors='face')\n#im1=ax4.pcolormesh(NewEOS.rho,NewEOS.T,((NewEOS.KPA))/6.,cmap=local_cmaps.parula,vmin=0,vmax=1,edgecolors='face')\nax4.plot(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax4.plot(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax4.plot(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax4.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax4.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax4.set_ylim(0.,20000)\nax4.set_xlim(0,30.)\nax4.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax4.set_ylabel('Temperature (K)',size=sfont)\nax4.set_title('Colors=KPA flag',size=sfont)\nax4.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax4)\ncax = divider.append_axes('right', size='5%', pad=0.05)\ncbar = fig.colorbar(im1, cax=cax, ticks = [], orientation='vertical')\n#cbar.ax.set_yticklabels(['0','1','2','3','4','5',  '6'])  # vertical colorbar\ncbar.set_label('KPA Flag',size=sfont)\n\n\nax5.pcolormesh(NewEOS.rho,NewEOS.T,((NewEOS.KPA)-0.5)/6.,cmap=cmap2,vmin=0,vmax=1)\nax5.loglog(NewEOS.vc.rl,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax5.loglog(NewEOS.vc.rv,NewEOS.vc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\nax5.loglog(NewEOS.vc.rl[0],NewEOS.vc.T[0],'ko')\nif NewEOS.mc.NT > 0:\n    ax5.plot(NewEOS.mc.rl,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n#    ax5.plot(NewEOS.mc.rs,NewEOS.mc.T,color=\"black\",linewidth=lw,linestyle='--',dashes=ds)\n\nax5.set_ylim(10.,1.E7)\nax5.set_xlim(1.E-21,100.)\nax5.set_xlabel('Density (g/cm$^3$)',size=sfont)\nax5.set_ylabel('Temperature (K)',size=sfont)\nax5.set_title('Colors=KPA flag',size=sfont)\nax5.tick_params(labelsize=sfont)\n\ndivider = make_axes_locatable(ax5)\ncax = divider.append_axes('right', size='5%', pad=0.05)\n#cbar = fig.colorbar(im1, cax=cax, ticks = [0, 0.5, 1], orientation='vertical')\n#cbar.ax.set_yticklabels(['-6', '-3.5', '-1'])  # vertical colorbar\ncbar = fig.colorbar(im1, cax=cax, ticks = np.arange(13)/12, orientation='vertical')\ncbar.ax.set_yticklabels(['','1','','2','','3','','4','','5','',  '6'])  # vertical colorbar\ncbar.set_label('KPA Flag',size=sfont)\n\n\nfig2.show()\n\n\n```\n\n## ANEOS Hugoniots Compared to Experimental Data\n\nThe following plots compare the ANEOS model Hugoniots with laboratory data downloaded from the shock wave database at http://ihed.ras.ru/rusbank/\n\nEntropy on the Principal Hugoniot derived by Kraus et al. 2015.\n\nANEOS Hugoniot: red -- calculated in the ANEOS code using model reference density and temperature.\n\nCalculated Hugoniot: blue -- calculated by linear interpolation of the EOS table starting at model reference density and temperature.\n\nThe liquid Hugoniot is calculated in Kraus et al. 2015 starting at the boiling point of liquid iron at 1 bar: 6.01 g/cm$^3$, 3133 K. The ANEOS model Hugoniot is shown for comparison.\n\n\n```python\n# Display the initial conditions for the Hugoniot in ANEOS.OUTPUT    \nprint('\\nRequested ANEOS Hugoniot initial state from (THUG,RHUG) (red curves in plots below):')\nprint('Initial Pressure (GPa):',NewEOS.anhug.P[0])\nprint('Initial Temperature (K):',NewEOS.anhug.T[0])\nprint('Initial Sp. Entropy (MJ/K/kg):',NewEOS.anhug.S[0])\nprint('Initial Sp. Internal Energy (MJ/kg):',NewEOS.anhug.U[0])\nprint('Initial Density (g/cm3):',NewEOS.anhug.rho[0])\n#\nprint('\\nCalculated Hugoniot using (T0REF,R0REF) initial state (blue curves in plots below):')\nprint('Initial Pressure (GPa):',NewEOS.hug.P[0])\nprint('Initial Temperature (K):',NewEOS.hug.T[0])\nprint('Initial Sp. Entropy (MJ/K/kg):',NewEOS.hug.S[0])\nprint('Initial Sp. Internal Energy (MJ/kg):',NewEOS.hug.U[0])\nprint('Initial Density (g/cm3):',NewEOS.hug.rho[0])\n\n#========== PLOTTING STYLES FOR LOTS OF PLOTS =================\nstyleqmd = ['^','red',5,' ']\nstylezdat = ['+','black',5,'Porous Fe Hugoniot\\n(IHED)']\nstylegg = ['+','blue',5,'STP Hugoniot data\\n(IHED)']\nstyleliq = ['--','orange',7,'Liquid Fe Hugoniot\\n(Kraus et al. 2015)']\nstyleliqhug = ['-','orange',1,'ANEOS Liquid Fe Hugoniot']\nstylezfit = ['-','green',1,' ']\nstyleanhug = ['-','red',1,'ANEOS Hugoniot']\nstylestphug = ['-','blue',1,'Calculated Hugoniot']\nstyleanphase = ['-','black',1,'ANEOS Phase Boundaries']\nstylephasept = ['o','black',6]\n\n\n\n#======================LOTS OF PLOTS============================\n# plot the Hugoniots for comparison\nsfont = 15\nfig, axes = plt.subplots(nrows=3, ncols=2, figsize=(14,18))\nplt.subplots_adjust(wspace=0.4)\n\n#-------------\n# Pressure-Density Data vs. ANEOS\nai=0\naj=0\n#axes[ai,aj].plot(QMDH_r[1::],QMDH_p[1::],styleqmd[0],markersize=styleqmd[2],color=styleqmd[1],label=styleqmd[3])\n#axes[ai,aj].plot(Zdat_r,Zdat_p,stylezdat[0],markersize=stylezdat[2],color=stylezdat[1],label=stylezdat[3])\n#axes[ai,aj].plot(LowHugDat_r,LowHugDat_p,stylegg[0],markersize=stylegg[2],color=stylegg[1],label=stylegg[3])\n#axes[ai,aj].plot(Zfit_r,Zfit_p,stylezfit[0],linewidth=stylezfit[2],color=stylezfit[1],label=stylezfit[3])\naxes[ai,aj].plot(NewEOS.anhug.rho,NewEOS.anhug.P,styleanhug[0],linewidth=styleanhug[2],color=styleanhug[1],label=styleanhug[3])\naxes[ai,aj].plot(NewEOS.hug.rho,NewEOS.hug.P,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(ihed_datarr[ihed_fullden,4]*ihed_rho0,ihed_datarr[ihed_fullden,3],stylegg[0],markersize=stylegg[2],color=stylegg[1],label=stylegg[3])\naxes[ai,aj].plot(scironrarr,scironparr,'-',color='m',label='STP Hugoniot\\n(Sjostrom & Crockett 2018)')\n\n# Kraus Liquid Iron Hugoniot at 1 bar boiling point\naxes[ai,aj].plot(krausironliqrarr[40:100], krausironliqparr[40:100],styleliq[0],markersize=styleliq[2],color=styleliq[1],label=styleliq[3])\n                 #linestyle='-',color='cyan',label='Kraus et al. 2015\\n1-bar Boiling Pt. Liquid Hugoniot')\n\n# ANEOS LIQUID HUGONIOT\n# Calculate the model Hugoniot with the same initial state as Thomas & Asimow 2013\nNewEOS.calchugoniot(r0=ironliq_r0,t0=ironliq_t0)\naxes[ai,aj].plot(NewEOS.hug.rho,NewEOS.hug.P,styleliqhug[0],linewidth=styleliqhug[2],color=styleliqhug[1],label=styleliqhug[3])\n# Put the STP hugoniot back into the structure\nNewEOS.calchugoniot(r0=NewEOS.R0REF,t0=NewEOS.T0REF)\n\naxes[ai,aj].set_ylim(0,1100)\naxes[ai,aj].set_xlim(7.,16.)\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].legend(fontsize=sfont-5)\n\n#-------------\n# Pressure - Temperature Data vs. ANEOS\nai=0\naj=1\n\n#axes[ai,aj].plot(QMDH_p[1::],QMDH_t[1::]/1.E3,styleqmd[0],markersize=styleqmd[2],color=styleqmd[1],label=styleqmd[3])\n#axes[ai,aj].errorbar(ZTdat_p,ZTdat_t/1.E3,xerr=ZTdat_perr,yerr=ZTdat_terr/1.E3,fmt=stylezdat[0],markersize=stylezdat[2],color=stylezdat[1],label=stylezdat[3],elinewidth=1)\n#axes[ai,aj].plot(Zfit_p,Zfit_t/1.E3,stylezfit[0],linewidth=stylezfit[2],color=stylezfit[1],label=stylezfit[3])\naxes[ai,aj].plot(NewEOS.anhug.P,NewEOS.anhug.T/1.E3,styleanhug[0],linewidth=styleanhug[2],color=styleanhug[1],label=styleanhug[3])\naxes[ai,aj].plot(NewEOS.hug.P,NewEOS.hug.T/1.E3,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\n\n## add squares\nrect = Rectangle((240.,5.),6.,.700,linewidth=1,edgecolor='moccasin',facecolor='moccasin')\naxes[ai,aj].add_patch(rect)\naxes[ai,aj].plot(243.,5.350,'d',color='orange',label='Brown & McQueen 1986')\nrect = Rectangle((222.,4.7),6.,1.000,linewidth=1,edgecolor='moccasin',facecolor='moccasin')\naxes[ai,aj].add_patch(rect)\naxes[ai,aj].plot(225.,5.100,'o',color='orange',label='Nguyen & Holmes 2004')\n\naxes[ai,aj].set_xlim(0,500)\naxes[ai,aj].set_ylim(0,20)\naxes[ai,aj].set_ylabel('Temperature (1000 K)',size=sfont)\naxes[ai,aj].set_xlabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].legend(fontsize=sfont-5)\n\n#-------------\n# Particle Velocity vs. Shock Velocity; Data vs. ANEOS\nai=1\naj=0\n\n#axes[ai,aj].plot(QMDH_up[1::],QMDH_us[1::],styleqmd[0],markersize=styleqmd[2],color=styleqmd[1],label=styleqmd[3])\n#axes[ai,aj].errorbar(Zdat_up,Zdat_us,xerr=Zdat_uperr,yerr=Zdat_userr,fmt=stylezdat[0],markersize=stylezdat[2],color=stylezdat[1],label=stylezdat[3],elinewidth=1)\n#axes[ai,aj].plot(LowHugDat_up,LowHugDat_us,stylegg[0],markersize=stylegg[2],color=stylegg[1],label=stylegg[3])\n#axes[ai,aj].plot(Zfit_up,Zfit_us,stylezfit[0],linewidth=stylezfit[2],color=stylezfit[1],label=stylezfit[3])\naxes[ai,aj].plot(NewEOS.anhug.up,NewEOS.anhug.us,styleanhug[0],linewidth=styleanhug[2],color=styleanhug[1],label=styleanhug[3])\naxes[ai,aj].plot(NewEOS.hug.up,NewEOS.hug.us,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(ihed_datarr[ihed_fullden,1],ihed_datarr[ihed_fullden,2],stylegg[0],markersize=stylegg[2],color=stylegg[1],label=stylegg[3])\n\n#axes[ai,aj].plot(foliq_up,foliq_us,styleliq[0],markersize=styleliq[2],color=styleliq[1],label=styleliq[3])\n# ANEOS LIQUID HUGONIOT\n# Calculate the model Hugoniot with the same initial state as Thomas & Asimow 2013\n#NewEOS.calchugoniot(r0=foliq_r0,t0=foliq_t0)\n#axes[ai,aj].plot(NewEOS.hug.up,NewEOS.hug.us,styleliqhug[0],linewidth=styleliqhug[2],color=styleliqhug[1],label=styleliqhug[3])\n# Put the STP hugoniot back into the structure\n#NewEOS.calchugoniot(r0=NewEOS.R0REF,t0=NewEOS.T0REF)\n\naxes[ai,aj].set_xlim(0,11)\naxes[ai,aj].set_ylim(0,20)\naxes[ai,aj].set_xlabel('Particle Velocity (km/s)',size=sfont)\naxes[ai,aj].set_ylabel('Shock Velocity (km/s)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].legend(fontsize=sfont-5)\n\n#-------------\n# Sp. Entropy vs Pressure; Calculated from experiments vs. ANEOS\nai=1\naj=1\n\n#axes[ai,aj].plot(Zfit_p,Zfit_s*1.E3,stylezfit[0],linewidth=stylezfit[2],color=stylezfit[1],label=stylezfit[3])\n#axes[ai,aj].fill_between(Zfit_p,(Zfit_s-Zfit_serr)*1000.,(Zfit_s+Zfit_serr)*1000.,color=stylezfit[1],alpha=0.2)\n# pressure error envelope is tiny and can't be seen on this scale\n#axes[ai,aj].fill_betweenx(Zfit_s*1000.,(Zfit_p-Zfit_perr),(Zfit_p+Zfit_perr),color='red',alpha=0.2)\naxes[ai,aj].plot(NewEOS.anhug.P,NewEOS.anhug.S*1.E3,styleanhug[0],linewidth=styleanhug[2],color=styleanhug[1],label=styleanhug[3])\naxes[ai,aj].plot(NewEOS.hug.P,NewEOS.hug.S*1.E3,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\n# Tie point from Kraus et al. 2015\naxes[ai,aj].plot(Ztie_p,Ztie_s*1.E3,'o',markersize=5,color='red',label='Entropy Tie Point (Kraus et al. 2015)')\naxes[ai,aj].plot([Ztie_p+Ztie_perrlow,Ztie_p+Ztie_perrhigh],[Ztie_s*1.E3,Ztie_s*1.E3],'-',color='red')\naxes[ai,aj].plot([Ztie_p,Ztie_p],[(Ztie_s-Ztie_serr)*1.E3,(Ztie_s+Ztie_serr)*1.E3],'-',color='red')\n# Iron at STP from JANAF\naxes[ai,aj].plot(1.E-4,ironSTP_S*1.E3,'s',markersize=5,color='orange',label='STP (JANAF)')\n\ncolstr='green'\naxes[ai,aj].plot(krausironparr[40:80], krausironsarr[40:80]/1.e3, linestyle='-',color=colstr)\n#axes[ai,aj].plot(krausironparr[40:80], krausironsarr[40:80]/1.e3, linestyle='-',color=colstr,label='Kraus et al. 2015\\nLiquid Region STP Hugoniot')\n#axes[ai,aj].plot(krausironparr[40:80], krausironsuarr[40:80]/1.e3, linestyle=':',color=colstr)\n#axes[ai,aj].plot(krausironparr[40:80], krausironslarr[40:80]/1.e3, linestyle=':',color=colstr)\naxes[ai,aj].fill_between(krausironparr[40:80],krausironslarr[40:80]/1.e3,krausironsuarr[40:80]/1.e3,color='green',alpha=0.2,label='Kraus et al. 2015\\nLiquid Region STP Hugoniot')\n\n\naxes[ai,aj].set_ylim(0,4.)\naxes[ai,aj].set_xlim(0,1200)\naxes[ai,aj].set_ylabel('Specific Entropy (kJ/K/kg)',size=sfont)\naxes[ai,aj].set_xlabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].legend(fontsize=sfont-5)\n\n#-------------\n# Pressure-Density Data vs. ANEOS   LOW PRESSURE + LIQUID HUGONIOT\nai=2\naj=0\n#axes[ai,aj].plot(QMDH_r[1::],QMDH_p[1::],styleqmd[0],markersize=styleqmd[2],color=styleqmd[1],label=styleqmd[3])\n#axes[ai,aj].plot(Zdat_r,Zdat_p,stylezdat[0],markersize=stylezdat[2],color=stylezdat[1],label=stylezdat[3])\n#axes[ai,aj].plot(LowHugDat_r,LowHugDat_p,stylegg[0],markersize=stylegg[2],color=stylegg[1],label=stylegg[3])\n# Liquid forsterite Hugoniot Data\n#axes[ai,aj].plot(foliq_r,foliq_p,styleliq[0],markersize=styleliq[2],color=styleliq[1],label=styleliq[3])\n#axes[ai,aj].plot(foliq_r0,0,styleliq[0],markersize=styleliq[2],color=styleliq[1])\n#axes[ai,aj].plot(Zfit_r,Zfit_p,stylezfit[0],linewidth=stylezfit[2],color=stylezfit[1],label=stylezfit[3])\n# ANEOS REFERENCE POINT (STP) Hugoniots\naxes[ai,aj].plot(NewEOS.anhug.rho,NewEOS.anhug.P,styleanhug[0],linewidth=styleanhug[2],color=styleanhug[1],label=styleanhug[3])\naxes[ai,aj].plot(NewEOS.hug.rho,NewEOS.hug.P,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(ihed_datarr[ihed_fullden,4]*ihed_rho0,ihed_datarr[ihed_fullden,3],stylegg[0],markersize=stylegg[2],color=stylegg[1],label=stylegg[3])\n\n\n# POROUS HUGONIOT m=R0/R00=1.128\nm=1.128\ncolstr='black'\nlabstr='R0/R00=1.128 (+IHED -ANEOS)'\nihed_porous = np.where(ihed_datarr[:,0] == m)[0]\naxes[ai,aj].plot(ihed_datarr[ihed_porous,4]*ihed_rho0,ihed_datarr[ihed_porous,3],'+',markersize=5,color=colstr,label=labstr)\nNewEOS.calcporoushugoniot(r0=NewEOS.R0REF,t0=NewEOS.T0REF,r00=NewEOS.R0REF/m)\naxes[ai,aj].plot(NewEOS.hug.rho,NewEOS.hug.P,styleliqhug[0],linewidth=styleliqhug[2],color=colstr)\n# Put the STP hugoniot back into the structure\nNewEOS.calchugoniot(r0=NewEOS.R0REF,t0=NewEOS.T0REF)\n\n# POROUS HUGONIOT m=R0/R00=1.315\nm=1.315\ncolstr='green'\nlabstr='R0/R00=1.315 (+IHED -ANEOS)'\nihed_porous = np.where(ihed_datarr[:,0] == m)[0]\naxes[ai,aj].plot(ihed_datarr[ihed_porous,4]*ihed_rho0,ihed_datarr[ihed_porous,3],'+',markersize=5,color=colstr,label=labstr)\nNewEOS.calcporoushugoniot(r0=NewEOS.R0REF,t0=NewEOS.T0REF,r00=NewEOS.R0REF/m)\naxes[ai,aj].plot(NewEOS.hug.rho,NewEOS.hug.P,styleliqhug[0],linewidth=styleliqhug[2],color=colstr)\n\n# POROUS HUGONIOT m=R0/R00=1.660\nm=1.660\ncolstr='m'\nlabstr='R0/R00=1.660 (+IHED -ANEOS)'\nihed_porous = np.where(ihed_datarr[:,0] == m)[0]\naxes[ai,aj].plot(ihed_datarr[ihed_porous,4]*ihed_rho0,ihed_datarr[ihed_porous,3],'+',markersize=5,color=colstr,label=labstr)\nNewEOS.calcporoushugoniot(r0=NewEOS.R0REF,t0=NewEOS.T0REF,r00=NewEOS.R0REF/m)\naxes[ai,aj].plot(NewEOS.hug.rho,NewEOS.hug.P,styleliqhug[0],linewidth=styleliqhug[2],color=colstr)\n\n# POROUS HUGONIOT m=R0/R00=2.333\nm=2.333\ncolstr='c'\nlabstr='R0/R00=2.333 (+IHED -ANEOS)'\nihed_porous = np.where(ihed_datarr[:,0] == m)[0]\naxes[ai,aj].plot(ihed_datarr[ihed_porous,4]*ihed_rho0,ihed_datarr[ihed_porous,3],'+',markersize=5,color=colstr,label=labstr)\nNewEOS.calcporoushugoniot(r0=NewEOS.R0REF,t0=NewEOS.T0REF,r00=NewEOS.R0REF/m)\naxes[ai,aj].plot(NewEOS.hug.rho,NewEOS.hug.P,styleliqhug[0],linewidth=styleliqhug[2],color=colstr)\n\n\n# Put the STP hugoniot back into the structure\nNewEOS.calchugoniot(r0=NewEOS.R0REF,t0=NewEOS.T0REF)\n\naxes[ai,aj].set_ylim(-5,200)\naxes[ai,aj].set_xlim(5,12.)\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].legend(fontsize=sfont-5)\n\n#-------------\n# Pressure-Density Data vs. ANEOS   EXTRAPOLATED HIGH PRESSURE\nai=2\naj=1\n#axes[ai,aj].plot(QMDH_r[1::],QMDH_p[1::],styleqmd[0],markersize=styleqmd[2],color=styleqmd[1],label=styleqmd[3])\n#axes[ai,aj].plot(Zdat_r,Zdat_p,stylezdat[0],markersize=stylezdat[2],color=stylezdat[1],label=stylezdat[3])\n#axes[ai,aj].plot(LowHugDat_r,LowHugDat_p,stylegg[0],markersize=stylegg[2],color=stylegg[1],label=stylegg[3])\n#axes[ai,aj].plot(Zfit_r,Zfit_p,stylezfit[0],linewidth=stylezfit[2],color=stylezfit[1],label=stylezfit[3])\naxes[ai,aj].plot(NewEOS.anhug.rho,NewEOS.anhug.P,styleanhug[0],linewidth=styleanhug[2],color=styleanhug[1],label=styleanhug[3])\naxes[ai,aj].plot(NewEOS.hug.rho,NewEOS.hug.P,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(ihed_datarr[ihed_fullden,4]*ihed_rho0,ihed_datarr[ihed_fullden,3],stylegg[0],markersize=stylegg[2],color=stylegg[1],label=stylegg[3])\naxes[ai,aj].plot(scironrarr,scironparr,'-',color='m',label='STP Hugoniot\\n(Sjostrom & Crockett 2018)')\n\naxes[ai,aj].set_ylim(0,6200)\naxes[ai,aj].set_xlim(7.,25.)\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].legend(fontsize=sfont-5)\n\n\n\n```\n\n\n```python\n#======================LOTS OF PLOTS============================\n# plot the Hugoniots for comparison\nsfont = 15\nfig, axes = plt.subplots(nrows=1, ncols=2, figsize=(14,6))\nplt.subplots_adjust(wspace=0.4)\n\n#-------------\n# Pressure-Sound Speed Hugoniot Data vs. ANEOS\nai=0\naj=0\naxes[ai].plot(NewEOS.hug.P,NewEOS.hug.cs,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai].plot(ihed_csarr[:,4],ihed_csarr[:,3],stylegg[0],markersize=stylegg[2],color=stylegg[1],label=stylegg[3])\n\naxes[ai].set_xlim(0,400)\naxes[ai].set_ylim(4.,14.)\naxes[ai].set_ylabel('Sound speed (km/s)',size=sfont)\naxes[ai].set_xlabel('Pressure (GPa)',size=sfont)\naxes[ai].tick_params(labelsize=sfont)\naxes[ai].legend(fontsize=sfont-5)\n\n#-------------\n# Particle velocity - Pressure  Data vs. ANEOS\nai=1\naj=1\n\naxes[ai].semilogy(NewEOS.hug.up,NewEOS.hug.P,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai].plot(ihed_relarr[:,3],ihed_relarr[:,4],'s',markersize=stylegg[2],color='red',label='Partial release (IHED)')\naxes[ai].plot(ihed_relarr[:,1],ihed_relarr[:,2],'s',markersize=stylegg[2],color='red')\n\nuniqrelarr = np.unique(ihed_relarr[:,2])\nfor j in range(0,len(uniqrelarr)):\n    ptarget=uniqrelarr[j]\n    # ANEOS ISENTROPE NEAR SAME PRESSURE\n    ANEOSIsen = isentrope_class() # code in eostable.py\n    Sisen = np.interp(ptarget,NewEOS.hug.P,NewEOS.hug.S) # MJ/K/kg\n    # loop across all densities and extract the values for the requested isentrope\n    for i in range(0,NewEOS.ND):\n        ind = np.where((NewEOS.S[:,i] > 0))[0]\n        interpfunction = interpolate.interp1d(NewEOS.S[ind,i],NewEOS.P[ind,i]) # MJ/K/kg, GPa\n        ANEOSIsen.pressure = np.append(ANEOSIsen.pressure,interpfunction(Sisen)) # GPa\n        interpfunction = interpolate.interp1d(NewEOS.S[ind,i],NewEOS.T[ind]) # MJ/K/kg, GPa\n        ANEOSIsen.temperature = np.append(ANEOSIsen.temperature,interpfunction(Sisen)) # GPa\n        interpfunction = interpolate.interp1d(NewEOS.S[ind,i],NewEOS.cs[ind,i]) # MJ/K/kg, cm/s\n        ANEOSIsen.soundspeed = np.append(ANEOSIsen.soundspeed,interpfunction(Sisen)) # cm/s\n        interpfunction = interpolate.interp1d(NewEOS.S[ind,i],NewEOS.U[ind,i]) # MJ/K/kg, MJ/kg\n        ANEOSIsen.energy = np.append(ANEOSIsen.energy,interpfunction(Sisen)) # MJ/kg\n    ANEOSIsen.density = np.copy(NewEOS.rho)*1000. # kg/m3\n    ANEOSIsen.partvel = np.zeros(NewEOS.ND) # m/s\n    ir0 = int(np.round(np.where(ANEOSIsen.pressure >= ptarget)[0][0])) # go up just past the intersection with Hugoniot\n    ANEOSIsen.partvel[ir0] = np.interp(ptarget,NewEOS.hug.P,NewEOS.hug.up)*1.E3 # m/s\n    #print('ANEOS Starting Pressure:',ptarget)\n    iir=ir0-1\n    while (ANEOSIsen.pressure[iir]>.0001):\n        if iir == ir0-1:\n            dp = (ptarget - ANEOSIsen.pressure[iir])*1.E9 # Pa\n        else:\n            dp = (ANEOSIsen.pressure[iir+1]-ANEOSIsen.pressure[iir])*1.E9 # Pa\n        ANEOSIsen.partvel[iir] = ANEOSIsen.partvel[iir+1] + dp/(ANEOSIsen.density[iir]*ANEOSIsen.soundspeed[iir+1]/1.E2) # m/s\n        #print(iir,ANEOSIsen.pressure[iir],ANEOSIsen.partvel[iir]/1.e3,dp/1.e9,ANEOSIsen.density[iir])\n        iir=iir-1\n    # plot aneos isentrope\n    tmp = np.where((ANEOSIsen.pressure < ptarget)&(ANEOSIsen.pressure > .01))[0]\n    if j == 0:\n        axes[ai].plot(ANEOSIsen.partvel[tmp]/1.e3,ANEOSIsen.pressure[tmp],'--',color='blue',label='ANEOS release isentrope')\n    else:\n        axes[ai].plot(ANEOSIsen.partvel[tmp]/1.e3,ANEOSIsen.pressure[tmp],'--',color='blue')\n\naxes[ai].set_xlim(0,7)\naxes[ai].set_ylim(.01,200)\naxes[ai].set_xlabel('Particle velocity (km/s)',size=sfont)\naxes[ai].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai].tick_params(labelsize=sfont)\naxes[ai].legend(fontsize=sfont-5)\n\n\n```\n\n## Model Critical Point and Shock-Induced Phase Changes\n\n\n\n\n```python\nprint('ANEOS Calculated Critical point:')\nprint('   Temperature (K):       ',NewEOS.cp.T)\nprint('   Pressure (GPa):        ', NewEOS.cp.P)\nprint('   Density (g/cm^3):      ',NewEOS.cp.rho)\nprint('   Sp. Energy (MJ/kg):    ', NewEOS.cp.U)\nprint('   Sp. Entropy (kJ/K/kg): ', NewEOS.cp.S*1.e3)\nprint('\\n')\nprint('ANEOS Calculated Values at 1 bar:')\nprint('   Temperature at melting (K):                     ', NewEOS.onebar.Tmelt)\nprint('   Liquid density at melting (g/cm^3):             ', NewEOS.onebar.rhocm)\nprint('   Sp. Entropy at inc. melting Sim (kJ/K/kg):      ', NewEOS.onebar.Sim*1.E3)\nprint('   Sp. Entropy at com. melting Scm (kJ/K/kg):      ', NewEOS.onebar.Scm*1.E3)\nprint('   Temperature at boiling (K):                     ', NewEOS.onebar.Tvap)\nprint('   Liquid density at boiling (g/cm^3):             ', NewEOS.onebar.rhoiv)\nprint('   Sp. Entropy at inc. vaporization Siv (kJ/K/kg): ', NewEOS.onebar.Siv*1.E3)\nprint('   Sp. Entropy at com. vaporization Scv (kJ/K/kg): ', NewEOS.onebar.Scv*1.E3)\nprint('\\n')\nif NewEOS.tp.T > 0:\n    print('ANEOS Calculated Triple Point:')\n    print('   Temperature (K):                        ',NewEOS.tp.T)\n    print('   Pressure (GPa):                         ', NewEOS.tp.P)\n    print('   Solid density (g/cm^3):                 ',NewEOS.tp.rhos)\n    print('   Liquid density (g/cm^3):                ',NewEOS.tp.rhol)\n    print('   Vapor density (g/cm^3):                 ',NewEOS.tp.rhov)\n    print('   Sp. Entropy at inc. melt Sim (kJ/K/kg): ', NewEOS.tp.Sim*1.E3)\n    print('   Sp. Entropy at com. melt Scm (kJ/K/kg): ', NewEOS.tp.Scm*1.E3)\n    print('   Sp. Entropy at inc. vap. Siv (kJ/K/kg): ', NewEOS.tp.Siv*1.E3)\n    print('   Sp. Entropy at com. vap. Scv (kJ/K/kg): ', NewEOS.tp.Scv*1.E3)\nelse:\n    print('ANEOS: No melt curve or triple point in this calculation.')\nprint('\\n')\nprint('USING MODEL ENTROPIES:')\nprint('Starting at reference conditions (rho,T): ',NewEOS.R0REF,NewEOS.T0REF, ' (g/cm^3, K)')\nprint('ANEOS model conditions for shock-induced vaporization on release to 1 bar:')\nprint('                     :         IM        CM        IV      50%V        CV')\nprint('Shock Pressure (GPa) : {:10.2f}{:10.2f}{:10.2f}{:10.2f}{:10.2f}'.format(\n    np.interp(NewEOS.onebar.Sim,NewEOS.hug.S,NewEOS.hug.P),\n    np.interp(NewEOS.onebar.Scm,NewEOS.hug.S,NewEOS.hug.P),\n    np.interp(NewEOS.onebar.Siv,NewEOS.hug.S,NewEOS.hug.P),\n    np.interp(NewEOS.onebar.Siv+0.5*(NewEOS.onebar.Scv-NewEOS.onebar.Siv),NewEOS.hug.S,NewEOS.hug.P),\n    np.interp(NewEOS.onebar.Scv,NewEOS.hug.S,NewEOS.hug.P)))\nprint('Imp. Match Vel (km/s): {:10.2f}{:10.2f}{:10.2f}{:10.2f}{:10.2f}'.format(\n    np.interp(NewEOS.onebar.Sim,NewEOS.hug.S,NewEOS.hug.up)*2,\n    np.interp(NewEOS.onebar.Scm,NewEOS.hug.S,NewEOS.hug.up)*2,\n    np.interp(NewEOS.onebar.Siv,NewEOS.hug.S,NewEOS.hug.up)*2,\n    np.interp(NewEOS.onebar.Siv+0.5*(NewEOS.onebar.Scv-NewEOS.onebar.Siv),NewEOS.hug.S,NewEOS.hug.up)*2,\n    np.interp(NewEOS.onebar.Scv,NewEOS.hug.S,NewEOS.hug.up)*2))\n\nprint('\\n')\nprint('USING JANAF ENTROPIES AT 1 BAR:')\nprint('Starting at reference conditions (rho,T): ',NewEOS.R0REF,NewEOS.T0REF, ' (g/cm^3, K)')\nprint('ANEOS model conditions for shock-induced vaporization on release to 1 bar (JANAF):')\nprint('                     :         IM        CM        IV      50%V        CV')\nprint('Shock Pressure (GPa) : {:10.2f}{:10.2f}{:10.2f}{:10.2f}{:10.2f}'.format(\n    np.interp(92.190/NewEOS.FMW/1.e3,NewEOS.hug.S,NewEOS.hug.P),\n    np.interp(99.823/NewEOS.FMW/1.e3,NewEOS.hug.S,NewEOS.hug.P),\n    np.interp(2.24e-3,NewEOS.hug.S,NewEOS.hug.P),\n    np.interp(2.24e-3+0.5*((4.238-2.24)*1.e-3),NewEOS.hug.S,NewEOS.hug.P),\n    np.interp(4.238e-3,NewEOS.hug.S,NewEOS.hug.P)))\n\nstop\n```\n\n\n```python\nprint(NewEOS.hug.S)\n```\n\n## Model Phase Boundaries\n\nBlack lines are the ANEOS phase boundaries. Blue curve is the model Principal Hugoniot.\n\nOrange diamonds are the 1-bar boiling point; orange squares are the 1-bar melting point.\n\nThe critical point has not been measured experimentally. There are several ab initio calculations, summarized in Menvedev 2014. The range of calculated critical points are shown below by the light blue box.\n\n\n```python\n# PHASE DIAGRAM PLOTS\n#======================LOTS OF PLOTS============================\n# Plot aneos phase boundaries with focus on the vapor curve\nsfont = 15\nfig, axes = plt.subplots(nrows=4, ncols=2, figsize=(14,24))\nplt.subplots_adjust(wspace=0.4)\n\n#------------------------------\n# entropy-temperature\nai=0\naj=0\naxes[ai,aj].plot(NewEOS.vc.Sl*1.E3,NewEOS.vc.T,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2],label=styleanphase[3])\naxes[ai,aj].plot(NewEOS.vc.Sv*1.E3,NewEOS.vc.T,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\naxes[ai,aj].plot(NewEOS.cp.S*1.E3,NewEOS.cp.T,'o',color=stylephasept[1],markersize=stylephasept[2])\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.Sl*1.E3,NewEOS.mc.T,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n    axes[ai,aj].plot(NewEOS.mc.Ss*1.E3,NewEOS.mc.T,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n\naxes[ai,aj].plot(NewEOS.hug.S*1.E3,NewEOS.hug.T,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(NewEOS.hug.S[0]*1.E3,NewEOS.hug.T[0],'o',color=stylestphug[1])\n\naxes[ai,aj].set_ylim(0,1.5*NewEOS.cp.T)\naxes[ai,aj].set_xlim(0,7)\naxes[ai,aj].set_xlabel('Specific Entropy (kJ/K/kg)',size=sfont)\naxes[ai,aj].set_ylabel('Temperature [K]',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n#-------------------------\n# density-pressure\nai=0\naj=1\naxes[ai,aj].semilogy(NewEOS.vc.rl,NewEOS.vc.Pl,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2],label=styleanphase[3])\naxes[ai,aj].plot(NewEOS.vc.rv,NewEOS.vc.Pv,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\naxes[ai,aj].plot(NewEOS.cp.rho,NewEOS.cp.P,'o',color=stylephasept[1],markersize=stylephasept[2])\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.rl,NewEOS.mc.Pl,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n    axes[ai,aj].plot(NewEOS.mc.rs,NewEOS.mc.Ps,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n\naxes[ai,aj].plot(NewEOS.hug.rho,NewEOS.hug.P,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(NewEOS.hug.rho[0],NewEOS.hug.P[0],'o',color=stylestphug[1])\n\naxes[ai,aj].set_ylim(1.e-5,300)\naxes[ai,aj].set_xlim(0,10)\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n#------\n#entropy-pressure\nai=1\naj=0\naxes[ai,aj].semilogy(NewEOS.vc.Sl*1.E3,NewEOS.vc.Pl,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2],label=styleanphase[3])\naxes[ai,aj].plot(NewEOS.vc.Sv*1.E3,NewEOS.vc.Pv,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\naxes[ai,aj].plot(NewEOS.cp.S*1.E3,NewEOS.cp.P,'o',color=stylephasept[1],markersize=stylephasept[2])\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.Sl*1.E3,NewEOS.mc.Pl,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n    axes[ai,aj].plot(NewEOS.mc.Ss*1.E3,NewEOS.mc.Ps,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n\naxes[ai,aj].plot(NewEOS.hug.S*1.E3,NewEOS.hug.P,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(NewEOS.hug.S[0]*1.E3,NewEOS.hug.P[0],'o',color=stylestphug[1])\n\naxes[ai,aj].set_xlabel('Specific Entropy (kJ/K/kg)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].set_ylim(1.e-12,10000)\naxes[ai,aj].set_xlim(0,7)\n\n#-----------\n# specific energy - pressure\nai=1\naj=1\naxes[ai,aj].semilogy(NewEOS.vc.Ul,NewEOS.vc.Pl,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2],label=styleanphase[3])\naxes[ai,aj].plot(NewEOS.vc.Uv,NewEOS.vc.Pv,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\naxes[ai,aj].plot(NewEOS.cp.U,NewEOS.cp.P,'o',color=stylephasept[1],markersize=stylephasept[2])\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.Ul,NewEOS.mc.Pl,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n    axes[ai,aj].plot(NewEOS.mc.Us,NewEOS.mc.Ps,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n\naxes[ai,aj].plot(NewEOS.hug.U,NewEOS.hug.P,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(NewEOS.hug.U[0],NewEOS.hug.P[0],'o',color=stylestphug[1])\n\naxes[ai,aj].set_xlabel('Specific Internal Energy (MJ/kg)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].set_ylim(1.e-12,10000)\naxes[ai,aj].set_xlim(-3,NewEOS.cp.U*1.5)\n\n#-------\n# temperature - pressure\nai=2\naj=0\naxes[ai,aj].semilogy(NewEOS.vc.T,NewEOS.vc.Pl,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2],label=styleanphase[3])\naxes[ai,aj].plot(NewEOS.vc.T,NewEOS.vc.Pv,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\naxes[ai,aj].plot(NewEOS.cp.T,NewEOS.cp.P,'o',color=stylephasept[1],markersize=stylephasept[2])\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.T,NewEOS.mc.Pl,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n    axes[ai,aj].plot(NewEOS.mc.T,NewEOS.mc.Ps,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n\naxes[ai,aj].plot(NewEOS.hug.T,NewEOS.hug.P,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(NewEOS.hug.T[0],NewEOS.hug.P[0],'o',color=stylestphug[1])\n\naxes[ai,aj].set_xlabel('Temperature (K)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].set_xlim(0,12000)\naxes[ai,aj].set_ylim(1.e-16,100)\n\n#-------\n# pressure - temperature melt curve\nai=2\naj=1\n#axes[ai,aj].plot(NewEOS.vc.Pl,NewEOS.vc.T,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2],label=styleanphase[3])\n#axes[ai,aj].plot(NewEOS.vc.Pv,NewEOS.vc.T,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n#axes[ai,aj].plot(NewEOS.cp.P,NewEOS.cp.T,'o',color=stylephasept[1],markersize=stylephasept[2])\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.Pl,NewEOS.mc.T,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2],label=styleanphase[3])\n    axes[ai,aj].plot(NewEOS.mc.Ps,NewEOS.mc.T,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n\n    axes[ai,aj].plot(NewEOS.hug.P,NewEOS.hug.T,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\n    axes[ai,aj].plot(NewEOS.hug.P[0],NewEOS.hug.T[0],'o',color=stylestphug[1])\n\n    axes[ai,aj].set_ylabel('Temperature (K)',size=sfont)\n    axes[ai,aj].set_xlabel('Pressure (GPa)',size=sfont)\n    axes[ai,aj].tick_params(labelsize=sfont)\n    axes[ai,aj].set_ylim(0,9000)\n    axes[ai,aj].set_xlim(-5,450)\n\n#-------\n# density - pressure melt curve\nai=3\naj=0\n\naxes[ai,aj].plot(NewEOS.hug.rho,NewEOS.hug.P,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(NewEOS.hug.rho[0],NewEOS.hug.P[0],'o',color=stylestphug[1])\naxes[ai,aj].plot(scironrarr,scironparr,'-',color='m',label='STP Hugoniot\\n(Sjostrom & Crockett 2018)')\n\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.rl,NewEOS.mc.Pl,'--',color=styleanphase[1],linewidth=styleanphase[2],label=styleanphase[3])\n    axes[ai,aj].plot(NewEOS.mc.rs,NewEOS.mc.Ps,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n\n\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].set_ylim(100,400)\naxes[ai,aj].set_xlim(10,14)\n\n#-------\n# temperature - pressure zoom out\nai=3\naj=1\naxes[ai,aj].semilogy(NewEOS.vc.T,NewEOS.vc.Pl,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2],label=styleanphase[3])\naxes[ai,aj].plot(NewEOS.vc.T,NewEOS.vc.Pv,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\naxes[ai,aj].plot(NewEOS.cp.T,NewEOS.cp.P,'o',color=stylephasept[1],markersize=stylephasept[2])\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.T,NewEOS.mc.Pl,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n    axes[ai,aj].plot(NewEOS.mc.T,NewEOS.mc.Ps,styleanphase[0],color=styleanphase[1],linewidth=styleanphase[2])\n\naxes[ai,aj].plot(NewEOS.hug.T,NewEOS.hug.P,stylestphug[0],linewidth=stylestphug[2],color=stylestphug[1],label=stylestphug[3])\naxes[ai,aj].plot(NewEOS.hug.T[0],NewEOS.hug.P[0],'o',color=stylestphug[1])\n\naxes[ai,aj].set_xlabel('Temperature (K)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].set_xlim(0,35000)\naxes[ai,aj].set_ylim(1.e-16,100)\n\n#===================================================================\n# PLOT EXPERIMENTAL CONSTRAINTS ON THE ANEOS PHASE BOUNDARIES\nPLOTDATA=1\ndatms = 8\nif PLOTDATA:\n    # entropy-temperature [0,0]\n    ai=0\n    aj=0\n    # range of ab initio predictions for the critical point from Medvedev 2014\n    rect = Rectangle((2.24,7300.),2.,3600,linewidth=1,edgecolor='skyblue',facecolor='skyblue')\n    axes[ai,aj].add_patch(rect)\n   \n    # STP NIST-JANAF\n    axes[ai,aj].plot(ironSTP_S*1.E3,298,'+',color='orange',label='STP (JANAF)')\n    # 1 bar melting point JANAF delta-iron to liquid\n    #1809.000\t\t42.558\t\t92.190\t\t59.772\t\t58.645\t\tDELTA <--> LIQUID\n    #1809.000\t\t46.024\t\t99.823\t\t59.772\t\t72.452\t\tTRANSITION\n    axes[ai,aj].plot(99.823/NewEOS.FMW,1809,'d',color='orange',label='1-bar MP (JANAF)')\n    axes[ai,aj].plot(92.190/NewEOS.FMW,1809,'d',color='orange')\n    # Boiling point NIST-JANAF, Kraus et al. Nature Geoscience 2015 and refs within\n    axes[ai,aj].plot(2.24,3133,'s',color='orange',label='1-bar BP (JANAF)')\n    axes[ai,aj].plot(4.238,3133,'s',color='orange')\n\n    axes[0,0].plot(2.496,8787,'x',color='navy',label='Fortov & Lomonosov 2010 CP',markersize=10)\n    #EOS parameters of the critical point for iron Pc = 1.131 GPa, Tc = 8,787 K, Vc = 0.458cm3/g, Sc = 2.496 J/g/K\n\n    # density-pressure [0,1]\n    ai=0\n    aj=1    \n    # range of ab initio predictions for the critical point from Medvedev 2014\n    rect = Rectangle((1.24,.356),1.,1.35,linewidth=1,edgecolor='skyblue',facecolor='skyblue')\n    axes[ai,aj].add_patch(rect)\n\n    axes[ai,aj].plot(2.1834,1.131,'x',color='navy',label='Fortov & Lomonosov 2010 CP',markersize=10)\n\n\n    # 99.99% Fe melting volume at 1 bar from Blumm & Henderson 2000 3.46%, approx 7.175 g/cm3 for solid at melt pt\n    axes[ai,aj].plot([6.98,6.98*(1.0346)],[1.E-4,1.E-4],'d',color='orange',label='MP (Blumm & Henderson 2000)')\n\n    # 1-bar Fe liquid at boiling point calculation Kraus et al. 2015\n    axes[ai,aj].plot([6.01],[1.E-4],'s',color='orange',label='BP (Kraus et al. 2015)')\n\n    # entropy -- pressure [1,0]\n    ai=1\n    aj=0\n    # range of ab initio predictions for the critical point from Medvedev 2014\n    rect = Rectangle((2.24,.356),2.,1.35,linewidth=1,edgecolor='skyblue',facecolor='skyblue')\n    axes[ai,aj].add_patch(rect)\n    axes[ai,aj].plot(2.496,1.131,'x',color='navy',label='Fortov & Lomonosov 2010 CP',markersize=10)\n\n    \n    # STP NIST-JANAF\n    axes[ai,aj].plot(ironSTP_S*1.E3,1.E-4,'+',color='orange',label='STP (JANAF)')\n    # 1 bar melting point JANAF delta-iron to liquid\n    #1809.000\t\t42.558\t\t92.190\t\t59.772\t\t58.645\t\tDELTA <--> LIQUID\n    #1809.000\t\t46.024\t\t99.823\t\t59.772\t\t72.452\t\tTRANSITION\n    axes[ai,aj].plot(99.823/NewEOS.FMW,1.E-4,'d',color='orange',label='1-bar MP (JANAF)')\n    axes[ai,aj].plot(92.190/NewEOS.FMW,1.E-4,'d',color='orange')\n    # Boiling point NIST-JANAF, Kraus et al. Nature Geoscience 2015 and refs within\n    axes[ai,aj].plot(2.24,1.E-4,'s',color='orange',label='1-bar BP (JANAF)')\n    axes[ai,aj].plot(4.238,1.E-4,'s',color='orange')\n\n    # temperature -- pressure [2,0]\n    ai=2\n    aj=0\n    # range of ab initio predictions for the critical point from Medvedev 2014\n    rect = Rectangle((7300.,.356),3600,1.35,linewidth=1,edgecolor='skyblue',facecolor='skyblue')\n    axes[ai,aj].add_patch(rect)\n\n    # plot Fe experimentally fitted vapor curve from Alcock et al. 1984\n    alcocktarr = np.arange(2100)+1\n    # Fe solid good from 298 to melting point\n    A=7.1\n    B=-21723.\n    C=0.4536\n    D=-0.5846\n    alcockfesolidparr = 1.e-4*np.power(10.,A+B/alcocktarr+C*np.log10(alcocktarr)+D*alcocktarr*1.e-3) #GPa\n\n    # Fe liquid good from melting point to 2100 K\n    A=6.347\n    B=-19574\n    C=0.\n    D=0.\n    alcockfeliquidparr = 1.e-4*np.power(10.,A+B/alcocktarr+C*np.log10(alcocktarr)+D*alcocktarr*1.e-3) #GPa\n\n    axes[ai,aj].plot(alcocktarr[298:1809],alcockfesolidparr[298:1809],color='orange',label='Vapor curve\\nAlcock et al. 1984')\n    axes[ai,aj].plot(alcocktarr[1809:2100],alcockfeliquidparr[1809:2100],color='orange')\n    axes[ai,aj].plot([3133.345],[1.e-4],'o',color='orange',label='1-bar BP (JANAF)')\n    axes[ai,aj].plot(9250.,8750.e-4,'+',color='purple',label='Beutl et al. 1994 CP',markersize=10)\n    axes[ai,aj].plot(8787,1.131,'x',color='navy',label='Fortov & Lomonosov 2010 CP',markersize=10)\n\n\n\n\n    # pressure- temperature [2,1]\n    ai=2\n    aj=1\n    \n    # Anzellini et al. 2013 Science iron melt curve high pressure region up to 200 GPa/5000 K\n    anzmct3arr = (np.arange(100)+1.)/100.*1300.+3700 # K\n    anzmcp3arr = (np.power(anzmct3arr/3712.,1.72)-1.)*161.2 + 98.5 # GPa\n    anzmct2arr = (np.arange(100)+1.)/100.*3700. # K\n    anzmcp2arr = (np.power(anzmct2arr/1991.,2.38)-1.)*27.39 + 5.2 # GPa\n    axes[ai,aj].plot(anzmcp3arr,anzmct3arr,color=\"orange\",linestyle='--',label='Anzellini et al. 2013')\n    axes[ai,aj].plot(anzmcp2arr,anzmct2arr,color=\"orange\",linestyle='--')\n\n    #Fischer et al. 2012 Fe-Si alloys\n    # example solidus of an iron alloy\n    fischerparrlow = Fischer_datalow.iloc[:,0].values # P GPa\n    fischertarrlow = Fischer_datalow.iloc[:,1].values # T K\n    fischerparrhigh = Fischer_datahigh.iloc[:,0].values # P GPa\n    fischertarrhigh = Fischer_datahigh.iloc[:,1].values # T K\n\n    axes[ai,aj].plot(fischerparrhigh,fischertarrhigh,'v',color=\"brown\",label='Fischer et al. 2012 Fe-16Si\\nupper limit solidus')\n    axes[ai,aj].plot(fischerparrlow,fischertarrlow,'^',color=\"brown\",label='lower limit solidus')\n\n    rect = Rectangle((240.,5000.),6.,700,linewidth=1,edgecolor='moccasin',facecolor='moccasin')\n    axes[ai,aj].add_patch(rect)\n    axes[ai,aj].plot(243.,5350,'x',color='orange',label='Brown & McQueen 1986')\n    rect = Rectangle((222.,4700),6.,1000,linewidth=1,edgecolor='moccasin',facecolor='moccasin')\n    axes[ai,aj].add_patch(rect)\n    axes[ai,aj].plot(225.,5100,'*',color='orange',label='Nguyen & Holmes 2004')\n\n    axes[ai,aj].errorbar(100.,3500.,xerr=10.,yerr=200,fmt='s',color='red',label='bcc-hcp-liquid TP\\nMorard et al. 2018')\n\n\n    # density - pressure [3,0]\n    ai=3\n    aj=0\n    axes[ai,aj].plot(12.5,270.,'^',color='orange',label='STP Hug. enters liq. 270 GPa\\n(Sjostrom & Crockett 2018)',markersize=6)\n    if NewEOS.tp.T > 0:\n        axes[ai,aj].plot(np.interp(260.,NewEOS.mc.Pl,NewEOS.mc.rl),260.,'d',color='orange',label='STP Hug. enters liq. 260 GPa\\n(Nguyen & Holmes 2014)',markersize=6)\n        axes[ai,aj].plot(np.interp(225.,NewEOS.mc.Ps,NewEOS.mc.rs),225.,'d',color='red',label='STP Hug. begins to melt 225 GPa\\n(Nguyen & Holmes 2014)',markersize=6)\n   \n    # temperature -- pressure [3,1]\n    ai=3\n    aj=1\n    # range of ab initio predictions for the critical point from Medvedev 2014\n    rect = Rectangle((7300.,.356),3600,1.35,linewidth=1,edgecolor='skyblue',facecolor='skyblue')\n    axes[ai,aj].add_patch(rect)\n\n    # plot Fe experimentally fitted vapor curve from Alcock et al. 1984\n    alcocktarr = np.arange(2100)+1\n    # Fe solid good from 298 to melting point\n    A=7.1\n    B=-21723.\n    C=0.4536\n    D=-0.5846\n    alcockfesolidparr = 1.e-4*np.power(10.,A+B/alcocktarr+C*np.log10(alcocktarr)+D*alcocktarr*1.e-3) #GPa\n\n\naxes[0,0].legend(fontsize=sfont-5)\naxes[0,1].legend(fontsize=sfont-5)\naxes[1,0].legend(fontsize=sfont-5)\naxes[1,1].legend(fontsize=sfont-5)\naxes[2,0].legend(fontsize=sfont-5)\naxes[2,1].legend(fontsize=sfont-5)\naxes[3,0].legend(fontsize=sfont-5)\naxes[3,1].legend(fontsize=sfont-5)\n\nplt.tight_layout(pad=0.6)\n\n```\n\n## ANEOS model comparisons to experimental data\n\nThe original ANEOS with a 3nR limit to the heat capacity does provide a good fit to the liquid region. \n\nDorogokupets et al. 2017 calculated the isotherm for liquid iron at 2200 K. The ANEOS model is a good fit (and then enters the solid phase). \n\nAnzellini et al. (2013) estimated that the temperature at the core-mantle boundary is about 4050 K. Here, I plot the ANEOS isentrope through (the nearest grid point to) 4050 K and 136 GPa and compare the isentrope to PREM (http://ds.iris.edu/spud/earthmodel/9785674). As expected, the ANEOS model isentrope is denser than Earth's core. The model isentrope and 10% and 4% density reductions are compared to PREM. \n\n\n```python\n# INCLUDE A COMPARISON TO EARTH'S STRUCTURE PREM MODEL\nG = 6.67E-11 # Gravitational constant  m3/kg/s2\n\n# Read in PREM: Preliminary Earth Reference Model\nPREM_filename=datadir+'PREM500_IDV.csv' # we love long, readable variable names!\n\n# make a class to hold the PREM data\nclass PREMclass:\n    \"\"\"Class to hold PREM data and other 1-D Earth variables.\"\"\"  # this is a documentation string for this class\n    def __init__(self): # self is the default name of the object for internal referencing of the variables in the class\n        \"\"\"A function to initialize the class object.\"\"\" # this is a documentation string for this function\n        self.NR = 0 # number of radius points\n        self.radius = np.zeros(self.NR) \n        self.density = np.zeros(self.NR)   \n        self.pwavevel = np.zeros(self.NR)   \n        self.swavevel = np.zeros(self.NR)\n        self.pressure = np.zeros(self.NR)\n        self.temperature = np.zeros(self.NR)\n        # not going to use all the variables in the file\n        self.units = '' # I like to keep a text note in a structure about the units\n\n# initialize an empty PREM object\nPREM = PREMclass()\n\n# read the data into the class parameters\nPREM.radius = np.loadtxt(PREM_filename,delimiter=',',skiprows=2,usecols=[0]) # radius in m\nPREM.density = np.loadtxt(PREM_filename,delimiter=',',skiprows=2,usecols=[1]) # density in kg/m3\nPREM.pwavevel = np.loadtxt(PREM_filename,delimiter=',',skiprows=2,usecols=[2]) # p-wave velocity m/s\nPREM.swavevel = np.loadtxt(PREM_filename,delimiter=',',skiprows=2,usecols=[3]) # s-wave velocity m/s\nPREM.NR = len(PREM.radius) # number of radius points\nPREM.units = 'radius (m), density (kg/m3), pwavevel (m/s), swavevel (m/s)'\n\n# start at the surface and integrate via a for loop to the center of the planet\n\n# calculate the thickness of each layer in the PREM model using the roll function\nPREM_dr = np.roll(PREM.radius,-1)-PREM.radius \nPREM_dr[PREM.NR-1] = 0. # we are not using the last entry in the list because there are NR-1 layers\n#print(PREM_dr)\n\n# calculate the mass of each layer\n# density x area x thickness of each layer\nPREM_mass_rad = PREM.density*(4.*np.pi*PREM.radius*PREM.radius*PREM_dr) \n\n# Check that the total mass is the mass of the Earth\n#print('PREM total mass (kg)=',np.sum(PREM_mass_rad))\n#print('PREM total mass (Mearth)=',np.sum(PREM_mass_rad)/5.972E24)\n\nPREM.pressure = np.zeros(PREM.NR) # make array of zeros for pressure of the same length as the arrays in the PREM model\n# The first entry is the middle of the planet, so start at the surface and integrate inwards\nfor i in range(PREM.NR-2,0,-1):\n    # we indent for the code in the for loop\n    PREM.pressure[i] = PREM.pressure[i+1]+G*np.sum(PREM_mass_rad[0:i-1])*PREM.density[i]*PREM_dr[i]/PREM.radius[i]/PREM.radius[i]\n\n# use SESAME units\nPREM.pressure = PREM.pressure/1.E9 # GPa\n\nIronEOS = NewEOS\n# first extract the isentropes for the planet from the EOS tables\ncore = isentrope_class() # code in eostable.py\nScore = 0.0022 # MJ/K/kg\n\n# loop across all densities and extract the values for the requested isentrope\nfor i in range(0,IronEOS.ND):\n    ind = np.where((IronEOS.S[:,i] > 0))[0]\n    interpfunction = interpolate.interp1d(IronEOS.S[ind,i],IronEOS.P[ind,i]) # MJ/K/kg, GPa\n    core.pressure = np.append(core.pressure,interpfunction(Score)) # GPa\n    interpfunction = interpolate.interp1d(IronEOS.S[ind,i],IronEOS.T[ind]) # MJ/K/kg, GPa\n    core.temperature = np.append(core.temperature,interpfunction(Score)) # GPa\ncore.density = IronEOS.rho # g/cm3\n\n#print('Calculated iron isentrope with ',np.round(np.interp(136.,core.pressure,core.temperature)),' K CMB temperature (P=136 GPa)')\n\n# first extract the isentropes for the planet from the EOS tables\ncore2 = isentrope_class() # code in eostable.py\nit0   = np.where(IronEOS.T >= 4050.)[0]\nScore = np.interp(136.,IronEOS.P[it0[0],:],IronEOS.S[it0[0],:])\n#Score = 0.00186 # MJ/K/kg\n\n# loop across all densities and extract the values for the requested isentrope\nfor i in range(0,IronEOS.ND):\n    ind = np.where((IronEOS.S[:,i] > 0))[0]\n    interpfunction = interpolate.interp1d(IronEOS.S[ind,i],IronEOS.P[ind,i]) # MJ/K/kg, GPa\n    core2.pressure = np.append(core2.pressure,interpfunction(Score)) # GPa\n    interpfunction = interpolate.interp1d(IronEOS.S[ind,i],IronEOS.T[ind]) # MJ/K/kg, GPa\n    core2.temperature = np.append(core2.temperature,interpfunction(Score)) # GPa\ncore2.density = IronEOS.rho # g/cm3\nprint('Calculated iron isentrope with ',np.round(np.interp(136.,core2.pressure,core2.temperature)),' K CMB temperature (P=136 GPa)')\n\n```\n\n\n```python\n# 1-bar plots and 298 K plots\n\n# Plot aneos vapor curves\nsfont = 15\nfig, axes = plt.subplots(2, 2, figsize=(14,14))\nplt.subplots_adjust(wspace=0.4)\n\n#--------\n# temperature - entropy at 1 bar\nai=0\naj=0\n\n\naxes[ai,aj].plot(Desai_tarr,Desai_sarr,'-',color='orange',label='Iron data (Desai 1986)',linewidth=3)\naxes[ai,aj].plot(NewEOS.onebar.T,NewEOS.onebar.S*1.E3,'+',color='blue',label='ANEOS 1 bar')\n\naxes[ai,aj].plot(1809.,99.823/NewEOS.FMW,'d',color='orange',label='1-bar MP (JANAF)')\naxes[ai,aj].plot(1809.,92.190/NewEOS.FMW,'d',color='orange')\n# Boiling point NIST-JANAF, Kraus et al. Nature Geoscience 2015 and refs within\naxes[ai,aj].plot(3133.,2.24,'s',color='orange',label='1-bar BP (JANAF)')\naxes[ai,aj].plot(3133.,4.238,'s',color='orange')\n\naxes[ai,aj].set_xlabel('Temperature (K)',size=sfont)\naxes[ai,aj].set_ylabel('Specific Entropy (kJ/K/kg)',size=sfont)\naxes[ai,aj].set_title('1-bar isobar',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].set_ylim(0,5)\naxes[ai,aj].set_xlim(0,4000)\n\n\n#----\n# density-temperature at 1 bar\nai=0\naj=1\n\naxes[ai,aj].plot(Assael_tarr,Assael_rarr/1.e3,'-',color='orange',label='Liquid iron data (Assael et al. 2006)')\naxes[ai,aj].plot(NewEOS.onebar.T,NewEOS.onebar.rho,'+',color='blue',label='ANEOS 1 bar')\naxes[ai,aj].plot(298.,7.873,'+',color='orange',label='STP')\naxes[ai,aj].plot([3133],[6.01],'s',color='orange',label='Boiling point (Kraus et al. 2015)')\n# 3.4% volume change (Askeland 1996) with highest density from Assael et al. 2006\naxes[ai,aj].plot([1809.,1809],[6.99,6.99*(1.034)],'d',color='orange',label='Melt transition')\n\naxes[ai,aj].plot([1811.],[7.019],'X',color='red',label='Anderson & Ahrens 1994')\n\n\naxes[ai,aj].set_ylabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_xlabel('Temperature (K)',size=sfont)\naxes[ai,aj].set_title('1-bar isobar',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].set_ylim(5,9)\naxes[ai,aj].set_xlim(0,4000)\n\n# plot data\n#axes[ai,aj].plot(1890+273.,2.968,'s',color='orange',label='MELTS MP Berman')\n#axes[ai,aj].plot(1890+273.,2.687,'o',color='orange',label='MELTS MP Lange')\n#axes[ai,aj].plot(2273.,2.597,'d',color='orange',label='Thomas & Asimow 2013')\n\n\n#----\n# density-pressure at 298 K\nai=1\naj=0\n\n\n# Guinan & Beshers JPCS 1969 Fe 298 K isotherm\n#K0T = 166.4 # GPa room temp isentrope\n#K0Tp = 5.29\n#R00 = 7.874\n#print(R00)\nGB_cs_stp = np.sqrt(166.4E9/7874.) # m/s\n#print(GB_cs_stp)\n#BM_pressure = 1.5*K0T*(np.power(NewEOS.rho/R00,7./3.)-np.power(NewEOS.rho/R00,5./3.)\n#                      )*(1.+0.75*(K0Tp-4.)*(np.power(NewEOS.rho/R00,2./3.)-1.))\n#igood = np.where((BM_pressure < 14.6))[0]\n#axes[ai,aj].plot(NewEOS.rho[igood],BM_pressure[igood],'-',color='orange',label='alpha-Fe 298-K isentrope\\nGuinan & Beshers 1969')\n\n# Dorogokupets et al. 2017\n# alpha (bcc) iron 298 K 1 bar (low T is ferro; high T is para)\nK0T = 164.001 # GPa room temp isotherm\nK0Tp = 5.5\nR00 = 7.8746\nBM_pressure = 1.5*K0T*(np.power(NewEOS.rho/R00,7./3.)-np.power(NewEOS.rho/R00,5./3.)\n                      )*(1.+0.75*(K0Tp-4.)*(np.power(NewEOS.rho/R00,2./3.)-1.))\nigood = np.where((BM_pressure < 14.6))[0]\naxes[ai,aj].plot(NewEOS.rho[igood],BM_pressure[igood],'-',color='teal',label='alpha-Fe 298-K isotherm\\nDorogokupets et al. 2017')\n\n# Dorogokupets et al. 2017\n# gamma (fcc) iron 298 K 1 bar\nK0T = 146.2 # GPa room temp isotherm\nK0Tp = 4.67\nR00 = 8.06\nBM_pressure = 1.5*K0T*(np.power(NewEOS.rho/R00,7./3.)-np.power(NewEOS.rho/R00,5./3.)\n                      )*(1.+0.75*(K0Tp-4.)*(np.power(NewEOS.rho/R00,2./3.)-1.))\nigood = np.where((BM_pressure < 110))[0]\naxes[ai,aj].plot(NewEOS.rho[igood],BM_pressure[igood],'-',color='cyan',linewidth=4,label='gamma-Fe 298-K isotherm\\nDorogokupets et al. 2017')\n\niT0REF = np.where(NewEOS.T == T0REF)[0]\naxes[ai,aj].plot(NewEOS.rho,NewEOS.P[iT0REF[0],:],'-',color='blue',label='ANEOS 298-K isotherm')\n\n# Dewaele et al. PRL 2006 Fe 298 K isotherm\n# espilon-iron (hcp)\nK0T = 165 # fixed GPa room temp isotherm\nK0Tp = 4.97 # +-0.04 fitted \nR00 = (NewEOS.FMW)*1.*1.6726/(11.234*1.E-3)/1.E3 # kg/m3->g/cm3 \n#print(R00)\nBM_pressure = 1.5*K0T*(np.power(NewEOS.rho/R00,7./3.)-np.power(NewEOS.rho/R00,5./3.)\n                      )*(1.+0.75*(K0Tp-4.)*(np.power(NewEOS.rho/R00,2./3.)-1.))\nigood = np.where((BM_pressure > 17.)&(BM_pressure < 197.))\naxes[ai,aj].plot(NewEOS.rho[igood],BM_pressure[igood],'-',color='brown',linewidth=2,label='epsilon-Fe 298-K isotherm\\nDewaele et al. 2006')\n'''\n# error bars Dewaele et al. PRL 2006 Fe 298 K isotherm\nK0Tp = 4.97-0.04 # +-0.04 fitted \nBM_pressure = 1.5*K0T*(np.power(NewEOS.rho/R00,7./3.)-np.power(NewEOS.rho/R00,5./3.)\n                      )*(1.+0.75*(K0Tp-4.)*(np.power(NewEOS.rho/R00,2./3.)-1.))\nigood = np.where((BM_pressure > 17.)&(BM_pressure < 197.))\naxes[ai,aj].plot(NewEOS.rho[igood],BM_pressure[igood],'--',color='brown')\n# error bars Dewaele et al. PRL 2006 Fe 298 K isotherm\nK0Tp = 4.97+0.04 # +-0.04 fitted \nBM_pressure = 1.5*K0T*(np.power(NewEOS.rho/R00,7./3.)-np.power(NewEOS.rho/R00,5./3.)\n                      )*(1.+0.75*(K0Tp-4.)*(np.power(NewEOS.rho/R00,2./3.)-1.))\nigood = np.where((BM_pressure > 17.)&(BM_pressure < 197.))\naxes[ai,aj].plot(NewEOS.rho[igood],BM_pressure[igood],'--',color='brown')\n'''\n\n#------ LIQUID\n# Dorogokupets et al. 2017\n# liquid iron 2200 K 1 bar\nK0T = 65.2 # GPa isotherm\nK0Tp = 6.48\nR00 = 7.019/1.04\nBM_pressure = 1.5*K0T*(np.power(NewEOS.rho/R00,7./3.)-np.power(NewEOS.rho/R00,5./3.)\n                      )*(1.+0.75*(K0Tp-4.)*(np.power(NewEOS.rho/R00,2./3.)-1.))\nigood = np.where((BM_pressure < 20))[0]\naxes[ai,aj].plot(NewEOS.rho[igood],BM_pressure[igood],'--',color='orange',linewidth=2,label='Liquid Fe 2200-K isotherm\\nDorogokupets et al. 2017')\n\n# plot liquid isotherm\nit0 = np.where(NewEOS.T >= 2200)[0]\n#print('Liquid isotherm at (K) ',NewEOS.T[it0[0]])\nigood = np.where((NewEOS.P[it0[0],:] < 20))[0]\naxes[ai,aj].plot(NewEOS.rho[igood],NewEOS.P[it0[0],igood],'--',color='orangered',label='ANEOS '+str(np.round(NewEOS.T[it0[0]]))+'-K isotherm')\n\n\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].set_title('298-K, 2200-K isotherms',size=sfont)\naxes[ai,aj].set_xlim(6,13)\naxes[ai,aj].set_ylim(0,200)\n\n#----\n# density-pressure at 298 K\nai=1\naj=1\n\naxes[ai,aj].plot(PREM.density[1::]/1.E3,PREM.pressure[1::],'-',color='orange',label='PREM')\n#axes[ai,aj].plot(core.density,core.pressure,'-',color='blue',label='ANEOS '+str(np.round(np.interp(136,core.pressure,core.temperature)))+' K isentrope at CMB',markersize=10)\naxes[ai,aj].plot(core2.density,core2.pressure,'-',color='blue',label='ANEOS isentrope: '+str(np.round(np.interp(136,core2.pressure,core2.temperature)))+' K at CMB',markersize=10)\naxes[ai,aj].plot(0.9*core2.density,core2.pressure,'--',color='blue',label='ANEOS isentrope shifted 10% in density')\naxes[ai,aj].plot(0.96*core2.density,core2.pressure,':',color='blue',label='ANEOS isentrope shifted 4% in density')\n\n\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\naxes[ai,aj].set_title('PREM and ANEOS model isentropes',size=sfont)\naxes[ai,aj].set_xlim(3,14)\naxes[ai,aj].set_ylim(0,360)\n\n# don't show a plot in lower right\n#axes[1,1].axis(\"off\")\n\n\naxes[0,0].legend(fontsize=sfont-5)\naxes[0,1].legend(fontsize=sfont-5)\naxes[1,0].legend(fontsize=sfont-5)\naxes[1,1].legend(fontsize=sfont-5)\n\n#print(PREM.pressure)\n```\n\n## ANEOS Gruneisen parameter and Theta parameter for thermal model\n\nThe Gruneisen parameter for iron liquid has been determined experimentally from shock wave data (e.g., see Kraus et al. 2015). Shockwave data derive the Grueneisen parameter in reference to a known state:\n\\begin{equation}\n\\gamma = \\frac{1}{\\rho}\\frac{(P-P_{\\rm ref})}{(E-E_{\\rm ref})} \\bigg\\rvert _V\n\\end{equation}\n\nThe ANEOS Gruneisen model is split into two parts. For $\\rho \\ge \\rho_{0}$,\n\\begin{equation}\n\\gamma = \\left( \\frac{\\gamma_0 \\rho_0}{\\rho}  + C_{24} \\left( 1-\\frac{\\rho_0}{\\rho} \\right)^2 \\right) (1-C_{60}) + \\left( \\gamma_0 + (C_{24}-\\gamma_0) \\left( 1- \\frac{\\rho_0}{\\rho} \\right)^2 \\right) C_{60}.\n\\end{equation}\nFor $\\rho < \\rho_{0}$,\n\\begin{equation}\n\\gamma = C_{16} \\rho^2 + C_{17}\\rho + 1 + C_{61}.\n\\end{equation}\n\n$C_{16}$ and $C_{17}$ are calculated so that $\\gamma$ and $d \\gamma / d \\rho$ are continuous at $\\rho=\\rho_0$. The model asymptotes to the Thomas-Fermi limit ($\\gamma=2/3$) when $C_{24}=2/3$.\n\nThe gamma function developed by Kraus et al. 2015 (SOM equation 5) is also shown for comparison. This function was derived from the abundant data on shocked porous iron. This calculation assumes E=0.\n\nThe literature values for the Gruneisen parameter of alpha-iron span 1.65 to 1.75: e.g., 1.65 Adams et al. 2006; 1.736 Dorogokupets et al. 2017; 1.75 Sjostrom & Crockett 2018.\n\n\n```python\n# plot the gamma and isotherms\n\n# ANEOS Formulation for Gamma and theta\ntheta0=abs(NewEOS.theta0)\nrhoarr = (1+np.arange(1000))/1000.*NewEOS.R0REF*10.\ngammaarr = (NewEOS.gamma0*NewEOS.R0REF/rhoarr\n           )+NewEOS.C24*np.power(1.0-NewEOS.R0REF/rhoarr,2.)*(1.-NewEOS.C60)+(NewEOS.gamma0 + (NewEOS.C24-NewEOS.gamma0)*np.power(1.-NewEOS.R0REF/rhoarr,2.))*NewEOS.C60\ns3 = NewEOS.C61+1.\nC14 = theta0 * np.exp(1.5*s3-(2.-0.5*NewEOS.C60)*NewEOS.gamma0)/(np.power(NewEOS.R0REF,s3))\nC16 = (s3-(2.-NewEOS.C60)*NewEOS.gamma0)/(NewEOS.R0REF*NewEOS.R0REF)\nC17 = ((3.-NewEOS.C60)*NewEOS.gamma0-2.*s3)/NewEOS.R0REF\ngammaarrlow = C16*rhoarr*rhoarr+C17*rhoarr+s3\nthetaarr = theta0*np.exp((1.-NewEOS.C60)*(1.-NewEOS.R0REF/rhoarr)*NewEOS.gamma0-0.5*(NewEOS.R0REF/rhoarr)*(3.-(NewEOS.R0REF/rhoarr)*(4-(NewEOS.R0REF/rhoarr))))*np.power((rhoarr/NewEOS.R0REF),NewEOS.C24)\nthetalowarr = C14*np.exp(rhoarr*(C17+0.5*C16*rhoarr))*np.power(rhoarr,s3)\n\n\n#-------- plots\nsfont = 15\nfig, axes = plt.subplots(1, 2, figsize=(14,7))\nplt.subplots_adjust(wspace=0.4)\n\n\n# -----\nai=0\nindlow = np.where(rhoarr <= NewEOS.R0REF)\nindhigh = np.where(rhoarr >= NewEOS.R0REF)\n\n\n# Gamma from Kraus et al. 2015 SOM Equation 5\n# this assumes E = 0. I dropped the exp(-phi*E) term. Phi=0.045 kg/MJ.\nkraus_garr = 0.7+(2.1-0.7)*np.power(7.85/NewEOS.rho,1.7)\nkraus_validrange = np.where((NewEOS.rho>9)&(NewEOS.rho<12))[0]\naxes[ai].plot(NewEOS.rho[kraus_validrange],kraus_garr[kraus_validrange],'-',linewidth=6,color='orange',label='Liquid iron fit\\n(Kraus et al. 2015)')\naxes[ai].set_ylim(0,2.5)\naxes[ai].set_xlim(0,25)\n\n# liquid iron at 1 bar 1811 K Anderson and Ahrens\n#axes[ai,aj].plot([7.019],[1.735],'s',color='red',label='Liq. Iron 1811 K, 1 bar')\n#axes[ai,aj].plot([5.5,6.0,6.5,7.019,12.643,13.015,13.417],[1.344,1.547,1.751,1.723,1.419,1.401,1.303],'o',color='red',label='Liquid Iron')\naxes[ai].errorbar([5.5,6.0,6.5,7.019,12.643,13.015,13.417],[1.344,1.547,1.751,1.723,1.419,1.401,1.303], yerr=[0.269,0.309,0.350,0.116,0.272,0.265,0.269], fmt='o', color='orange', ecolor='orange', capthick=2,label='Liquid Fe data\\n(Anderson & Ahrens 1994)')\n\n# solid alpha-iron at STP\naxes[ai].plot([NewEOS.R0REF,NewEOS.R0REF],[1.65,1.75],'-',linewidth=3,color='blue',label='alpha-Fe solid STP')\n\naxes[ai].plot(rhoarr[indhigh[0]],gammaarr[indhigh[0]],label=\"ANEOS Gamma-high\",color='black')\naxes[ai].plot(rhoarr[indlow[0]], gammaarrlow[indlow[0]],label=\"ANEOS Gamma-low\",color='black',ls='--')\n\naxes[ai].plot(NewEOS.R0REF,NewEOS.gamma0,'+',label=\"ANEOS Gamma0\",color='black')\n\n\naxes[ai].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai].set_ylabel('Gamma (-)',size=sfont)\naxes[ai].tick_params(labelsize=sfont)\n\n\n\n# -----\nai=1\naxes[ai].plot(rhoarr[indhigh[0]],thetaarr[indhigh[0]],label=\"ANEOS Theta-high\",color='black')\naxes[ai].plot(rhoarr[indlow[0]],thetalowarr[indlow[0]],label=\"ANEOS Theta-low\",color='black',ls='--')\naxes[ai].plot(NewEOS.R0REF,theta0,'+',label=\"Theta0\",color='black')\n\naxes[ai].set_ylim(0,2000)\naxes[ai].set_xlim(0,25)\n\naxes[ai].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai].set_ylabel('Theta (K)',size=sfont)\naxes[ai].tick_params(labelsize=sfont)\n\n\naxes[0].legend(fontsize=sfont-5)\naxes[1].legend(fontsize=sfont-5)\n\n\n```\n\n# Specific Heat Capacity and Sounds Speeds\n\n\n\n\n```python\n\nsfont = 15\nfig, axes = plt.subplots(2, 2, figsize=(14,14))\nplt.subplots_adjust(wspace=0.4)\n\n\n#-----------------------------\n# Pick isotherms and set color scale\nixtemparr = [298.,1000.,2000.,5000.,20000.]\n# set color scale same for all plots\ntcolmin=0.\ntcolmax=20000.\n\n# find the index closest to the selected temperatures -- no interpolation\nixindarr=np.zeros(len(ixtemparr))\nixlabelarr = []\nfor i in np.arange(len(ixtemparr)):\n    tmpi=int(np.round(np.interp(ixtemparr[i],NewEOS.T,np.arange(NewEOS.NT))))\n    #print(tmpi,antarr[tmpi])\n    ixindarr[i] = tmpi\n    ixlabelarr.append(str(ixtemparr[i])+' K')\n\n\n#-----------------------\nai=0\naj=0\nfor i in np.arange(len(ixtemparr)):\n    icolscale = (ixtemparr[i]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.rho,NewEOS.cv[int(ixindarr[i]),:]*1000.,c=col,linestyle='-',label=ixlabelarr[i])\n\n#axes[ai,aj].plot(QMDH_r1,QMDH_cv*1000.,styleqmd[0],markersize=styleqmd[2],color=styleqmd[1],label='QMD Hugoniot\\n(Root et al. 2018')\n#axes[ai,aj].plot(2.597,1.73736,'^',color='orange',label='1 bar 2273 K liquid Cv\\n(Thomas & Asimow 20133)')\n#axes[ai,aj].plot(3.,180./(NewEOS.FMW/1.E3)/1.E3,'s',color='orange',label='1 bar 2000 K solid Cv\\n(Gillet et al. 1991)')\naxes[ai,aj].set_ylim(0.,3.)\naxes[ai,aj].set_xlim(0,30)\n\naxes[ai,aj].set_ylabel('Specific heat capacity Cv (kJ/K/kg)',size=sfont)\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n#-----------------------\nai=0\naj=1\nfor i in np.arange(len(ixtemparr)):\n    icolscale = (ixtemparr[i]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.rho,NewEOS.cv[int(ixindarr[i]),:]*1000.*1000./1/8.314*NewEOS.FMW/1000.,c=col,linestyle='-',label=ixlabelarr[i])\n\n\n#axes[ai,aj].plot(QMDH_r1,QMDH_cv*1.E6/7/8.314*0.14,styleqmd[0],markersize=styleqmd[2],color=styleqmd[1],label='QMD Hugoniot\\n(Root et al. 2018')\n#axes[ai,aj].plot(2.597,1737./7/8.314*0.140,'^',color='orange',label='1 bar 2273 K liquid Cv\\n(Thomas & Asimow 2013)')\n#axes[ai,aj].plot(3.,180./(NewEOS.FMW/1.E3)/7/8.314*0.140,'s',color='orange',label='1 bar 2000 K solid Cv\\n(Gillet et al. 1991)')\naxes[ai,aj].set_ylim(1.,7.)\naxes[ai,aj].set_xlim(0,30)\n\naxes[ai,aj].set_ylabel('Specific heat capacity Cv (nR)',size=sfont)\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n#-----------------------\n# plot sound speed along isotherms\nai=1\naj=0\nfor i in np.arange(len(ixtemparr)):\n    icolscale = (ixtemparr[i]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.P[int(ixindarr[i]),:],NewEOS.cs[int(ixindarr[i]),:]/1.e5,c=col,linestyle='-',label=ixlabelarr[i])\n\naxes[ai,aj].plot(1.E-4,GB_cs_stp/1.e3,'+',markersize=10,color='orange',label='alph-iron STP\\n(Guinan & Beshers 1968)')\naxes[ai,aj].plot(1.E-4,3.82,'X',markersize=10,color='orange',label='Liquid iron 1809 K\\n(Nasch et al. 1994)')\n\n\naxes[ai,aj].set_ylim(0,10)\naxes[ai,aj].set_xlim(-10,40)\n\naxes[ai,aj].set_ylabel('Bulk Sound Speed (km/s)',size=sfont)\naxes[ai,aj].set_xlabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n\n#-----------------------\n# plot sound speed along isotherms\nai=1\naj=1\nfor i in np.arange(len(ixtemparr)):\n    icolscale = (ixtemparr[i]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.P[int(ixindarr[i]),:],NewEOS.cs[int(ixindarr[i]),:]/1.e5,c=col,linestyle='-',label=ixlabelarr[i])\n\naxes[ai,aj].plot([225,260],[10,9.5],'d',color='orange',label='Nguyen & Holmes 2004 on Hugoniot')\n\n\naxes[ai,aj].set_ylim(0,20)\naxes[ai,aj].set_xlim(0,700)\n\naxes[ai,aj].set_ylabel('Bulk Sound Speed (km/s)',size=sfont)\naxes[ai,aj].set_xlabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\naxes[0,0].legend(fontsize=sfont-5)\naxes[0,1].legend(fontsize=sfont-5)\naxes[1,0].legend(fontsize=sfont-5)\naxes[1,1].legend(fontsize=sfont-5)\n\n```\n\n# Check the Melt Curve in Tabulated EOS\n\nColored lines correspond to isotherms. \n\nThere is no melt curve in this model. The kinks in the isotherms correspond to the high-pressure phase change.\n\n\n```python\n# CHECK MELT CURVE GRIDDING\nsfont = 15\nfig, axes = plt.subplots(nrows=5, ncols=2, figsize=(14,26))\nplt.subplots_adjust(wspace=0.5)\ntcolmin=0.\ntcolmax=1.5*NewEOS.cp.T\ntpltmax=1.5*NewEOS.cp.T\n\ntskip=5\n#-------------\nai=0\naj=0\naxes[ai,aj].plot([],[],' ',label='Low pressure melt curve')\n\nfor it in range(1,NewEOS.NT,tskip):\n    icolscale = (NewEOS.T[it]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.rho,NewEOS.P[it,:],'o',markersize=2,linestyle='-',color=col)\n\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.rl,NewEOS.mc.Pl,color=\"black\")\n    axes[ai,aj].plot(NewEOS.mc.rs,NewEOS.mc.Ps,color=\"black\")\n\naxes[ai,aj].set_ylim(0,50)\naxes[ai,aj].set_xlim(6.5,9.5)\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n#-------------\nai=0\naj=1\naxes[ai,aj].plot([],[],' ',label='High pressure melt curve')\n\nfor it in range(1,NewEOS.NT,tskip):\n    icolscale = (NewEOS.T[it]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.rho,NewEOS.P[it,:],'o',markersize=2,linestyle='-',color=col)\n\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.rl,NewEOS.mc.Pl,color=\"black\")\n    axes[ai,aj].plot(NewEOS.mc.rs,NewEOS.mc.Ps,color=\"black\")\n\naxes[ai,aj].set_ylim(50.,150)\naxes[ai,aj].set_xlim(9.0,11.5)\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n\n#-------------\nai=1\naj=0\naxes[ai,aj].plot([],[],' ',label='Higher pressure melt curve')\n\nfor it in range(1,NewEOS.NT,tskip):\n    icolscale = (NewEOS.T[it]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.rho,NewEOS.P[it,:],'o',markersize=2,linestyle='-',color=col)\n\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.rl,NewEOS.mc.Pl,color=\"black\")\n    axes[ai,aj].plot(NewEOS.mc.rs,NewEOS.mc.Ps,color=\"black\")\n\n\naxes[ai,aj].set_ylim(180.,310)\naxes[ai,aj].set_xlim(11.,13.,)\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n\n#-------------\nai=1\naj=1\naxes[ai,aj].plot([],[],' ',label='Higher pressure melt curve')\n\naxes[ai,aj].set_xlabel('Specific Energy (MJ/kg)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n\nfor it in range(1,NewEOS.NT,tskip):\n    icolscale = (NewEOS.T[it]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.U[it,:],NewEOS.P[it,:],'o',markersize=2,linestyle='-',color=col)\n\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.Ul,NewEOS.mc.Pl,color=\"black\")\n    axes[ai,aj].plot(NewEOS.mc.Us,NewEOS.mc.Ps,color=\"black\")\n\naxes[ai,aj].set_ylim(180.,310)\naxes[ai,aj].set_xlim(4,7.5)\n\n#-------------\n\nai=2\naj=0\naxes[ai,aj].plot([],[],' ',label='Low pressure melt curve')\n\naxes[ai,aj].set_xlabel('Specific Entropy (kJ/K/kg)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\nfor it in range(1,NewEOS.NT,tskip):\n    icolscale = (NewEOS.T[it]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.S[it,:]*1.e3,NewEOS.P[it,:],'o',markersize=2,linestyle='-',color=col)\n\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.Sl*1.e3,NewEOS.mc.Pl,color=\"black\")\n    axes[ai,aj].plot(NewEOS.mc.Ss*1.e3,NewEOS.mc.Ps,color=\"black\")\n\naxes[ai,aj].set_ylim(0.,50)\naxes[ai,aj].set_xlim(1.5,2.)\n\n\n#-------------\n\nai=2\naj=1\naxes[ai,aj].plot([],[],' ',label='High pressure melt curve')\n\naxes[ai,aj].set_xlabel('Specific Entropy (kJ/K/kg)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\nfor it in range(1,NewEOS.NT,tskip):\n    icolscale = (NewEOS.T[it]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.S[it,:]*1.e3,NewEOS.P[it,:],'o',markersize=2,linestyle='-',color=col)\n\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.Sl*1.e3,NewEOS.mc.Pl,color=\"black\")\n    axes[ai,aj].plot(NewEOS.mc.Ss*1.e3,NewEOS.mc.Ps,color=\"black\")\n\naxes[ai,aj].set_ylim(50.,150)\naxes[ai,aj].set_xlim(1.6,2.)\n\n\n#-------------\nai=3\naj=0\naxes[ai,aj].plot([],[],' ',label='Low pressure melt curve')\n\naxes[ai,aj].set_xlabel('Specific Energy (MJ/kg)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n\nfor it in range(1,NewEOS.NT,tskip):\n    icolscale = (NewEOS.T[it]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.U[it,:],NewEOS.P[it,:],'o',markersize=2,linestyle='-',color=col)\n\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.Ul,NewEOS.mc.Pl,color=\"black\")\n    axes[ai,aj].plot(NewEOS.mc.Us,NewEOS.mc.Ps,color=\"black\")\n\naxes[ai,aj].set_xlim(0.5,2.)\naxes[ai,aj].set_ylim(0.,50)\n\n#-------------\nai=3\naj=1\naxes[ai,aj].plot([],[],' ',label='High pressure melt curve')\n\naxes[ai,aj].set_xlabel('Specific Energy (MJ/kg)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n\nfor it in range(1,NewEOS.NT,tskip):\n    icolscale = (NewEOS.T[it]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.U[it,:],NewEOS.P[it,:],'o',markersize=2,linestyle='-',color=col)\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.Ul,NewEOS.mc.Pl,color=\"black\")\n    axes[ai,aj].plot(NewEOS.mc.Us,NewEOS.mc.Ps,color=\"black\")\naxes[ai,aj].set_ylim(50.,150)\naxes[ai,aj].set_xlim(1,4.)\n\n\n\n#-------------\nai=4\naj=0\nfor it in range(1,NewEOS.NT,tskip):\n    icolscale = (NewEOS.T[it]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.rho,NewEOS.P[it,:],'o',markersize=2,color=col,linestyle='-')\n\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.rl,NewEOS.mc.Pl,color=\"black\")\n    axes[ai,aj].plot(NewEOS.mc.rs,NewEOS.mc.Ps,color=\"black\")\n\naxes[ai,aj].set_ylim(300,550)\naxes[ai,aj].set_xlim(13.5,15.)\n\naxes[ai,aj].plot([],[],' ',label='Very high pressure melt curve.')\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n#-------------\nai=4\naj=1\nfor it in range(1,NewEOS.NT,tskip):\n    icolscale = (NewEOS.T[it]-tcolmin)/(tcolmax-tcolmin)\n    col=local_cmaps.parula(icolscale)\n    axes[ai,aj].plot(NewEOS.rho,NewEOS.P[it,:],'o',markersize=2,linestyle='-',color=col)\nif NewEOS.tp.T > 0:\n    axes[ai,aj].plot(NewEOS.mc.rl,NewEOS.mc.Pl,color=\"black\")\n    axes[ai,aj].plot(NewEOS.mc.rs,NewEOS.mc.Ps,color=\"black\")\naxes[ai,aj].set_ylim(800,1000)\naxes[ai,aj].set_xlim(16.5,17.5)\n\naxes[ai,aj].plot([],[],' ',label='Very high pressures')\naxes[ai,aj].set_xlabel('Density (g/cm$^3$)',size=sfont)\naxes[ai,aj].set_ylabel('Pressure (GPa)',size=sfont)\naxes[ai,aj].tick_params(labelsize=sfont)\n\n#------\naxes[0,0].legend(fontsize=sfont-5)\naxes[0,1].legend(fontsize=sfont-5)\naxes[1,0].legend(fontsize=sfont-5)\naxes[1,1].legend(fontsize=sfont-5)\naxes[2,0].legend(fontsize=sfont-5)\naxes[2,1].legend(fontsize=sfont-5)\naxes[3,0].legend(fontsize=sfont-5)\naxes[3,1].legend(fontsize=sfont-5)\naxes[4,0].legend(fontsize=sfont-5)\naxes[4,1].legend(fontsize=sfont-5)\n\n\n```\n\n# References\n\nAdams, J. J., Agosta, D. S., Leisure, R. G., & Ledbetter, H. (2006). Elastic constants of monocrystal iron from 3 to 500 K. Journal of applied physics, 100(11), 113530.\n\nAlcock, C. B., Itkin, V. P., & Horrigan, M. K. (1984). Vapour pressure equations for the metallic elements: 298\u20132500K. Canadian Metallurgical Quarterly, 23(3), 309-313.\n\nAnderson, W. W., & Ahrens, T. J. (1994). An equation of state for liquid iron and implications for the Earth's core. Journal of Geophysical Research: Solid Earth, 99(B3), 4273-4284.\n\nAnzellini, S., Dewaele, A., Mezouar, M., Loubeyre, P., & Morard, G. (2013). Melting of iron at Earth\u2019s inner core boundary based on fast X-ray diffraction. Science, 340(6131), 464-466.\n\nArtemieva, N., & Pierazzo, E. (2011). The Canyon Diablo impact event: 2. Projectile fate and target melting upon impact. Meteoritics & Planetary Science, 46(6), 805-829.\n\nAskeland D R, 1996 Materialwissenschaften (Heidelberg: Spektrum Akademischer Verlag GmbH) p. 203\n\nAssael, M. J., Kakosimos, K., Banish, R. M., Brillo, J., Egry, I., Brooks, R., ... & Wakeham, W. A. (2006). Reference data for the density and viscosity of liquid aluminum and liquid iron. Journal of Physical and Chemical Reference Data, 35(1), 285-300.\n\nBarr, A. C., & Citron, R. I. (2011). Scaling of melt production in hypervelocity impacts from high-resolution numerical simulations. Icarus, 211(1), 913-916.\n\nBeutl, M., Pottlacher, G., & J\u00e4ger, H. (1994). Thermophysical properties of liquid iron. International journal of thermophysics, 15(6), 1323-1331.\n\nBlumm, J., & Henderson, J. B. (2000). Measurement of the volumetric expansion and bulk density of metals in the solid and molten regions. High Temperatures High Pressures, 32(1), 109-114.\n\nBonomo, A. S., Zeng, L., Damasso, M., Leinhardt, Z. M., Justesen, A. B., Lopez, E., ... & Corsaro, E. (2019). A giant impact as the likely origin of different twins in the Kepler-107 exoplanet system. Nature Astronomy, 3(5), 416-423. doi:10.1038/s41550-018-0684-9\n\nBrown, J. M., & McQueen, R. G. (1986). Phase transitions, Gr\u00fcneisen parameter, and elasticity for shocked iron between 77 GPa and 400 GPa. Journal of Geophysical Research: Solid Earth, 91(B7), 7485-7494.\n\nBurakovsky, L., & Preston, D. L. (2004). Analytic model of the Gr\u00fcneisen parameter all densities. Journal of Physics and Chemistry of Solids, 65(8-9), 1581-1587.\n\nBushman, A.V., I. V. Lomonosov and K. V. Khishchenko, et al. (accessed 2019) Shock Wave Database, http://www.ihed.ras.ru/rusbank/\n\nChase Jr, M. W., Curnutt, J. L., Downey Jr, J. R., McDonald, R. A., Syverud, A. N., & Valenzuela, E. A. (1982). JANAF thermochemical tables, 1982 supplement. Journal of Physical and Chemical Reference Data, 11(3), 695-940.  https://janaf.nist.gov\n\nDenman, T. R., Z. M. Leinhardt, P. J. Carter, C. Mordasini. (submitted). Atmosphere loss in planet-planet collisions. MNRAS.\n\nDesai, P. D. (1986). Thermodynamic properties of iron and silicon. Journal of physical and chemical reference data, 15(3), 967-983.\n\nDewaele, A., Loubeyre, P., Occelli, F., Mezouar, M., Dorogokupets, P. I., & Torrent, M. (2006). Quasihydrostatic equation of state of iron above 2 Mbar. Physical Review Letters, 97(21), 215504.\nChicago\t\n\nDorogokupets, P. I., Dymshits, A. M., Litasov, K. D., & Sokolova, T. S. (2017). Thermodynamics and Equations of State of Iron to 350 GPa and 6000 K. Scientific reports, 7, 41863.\n\nDuffy, T., Madhusudhan, N., & Lee, K. K. M. (2015). 2.07 Mineralogy of Super-Earth Planets. Treatise on Geophysics, Second Edition, Elsevier, Oxford.Duffy, T., Madhusudhan, N., & Lee, K. K. M. (2015). 2.07 Mineralogy of Super-Earth Planets. Treatise on Geophysics, Second Edition, Elsevier, Oxford.\n\nDurek, J. J., and G. Ekstrom (1996) Modified PREM (Preliminary Reference Earth Model), doi:10.17611/DP/9785674, http://ds.iris.edu/spud/earthmodel/9785674.\n\nFischer, R. A. (2016). Melting of Fe alloys and the thermal structure of the core. Deep Earth: Physics and chemistry of the lower mantle and core, 217, 3-12.\n\nFischer, R. A., Campbell, A. J., Caracas, R., Reaman, D. M., Dera, P., & Prakapenka, V. B. (2012). Equation of state and phase diagram of Fe\u201316Si alloy as a candidate component of Earth's core. Earth and Planetary Science Letters, 357, 268-276.\n\nFortov, V. E., & Lomonosov, I. V. (2010). Shock waves and equations of state of matter. Shock waves, 20(1), 53-71.\n\nGuinan, M. W., & Beshers, D. N. (1968). Pressure derivatives of the elastic constants of \u03b1-iron to 10 kbs. Journal of Physics and Chemistry of Solids, 29(3), 541-549.\n\nKerley, G. I. (1977). Rational function method of interpolation (No. LA-6903-MS). Los Alamos National Laboratory, Los Alamos, NM (United States).\n\nKerley, G. I. (1993). Multiphase equation of state for iron (No. SAND-93-0027). Sandia National Labs., Albuquerque, NM (United States).\n\nKraus, R. G., Root, S., Lemke, R. W., Stewart, S. T., Jacobsen, S. B., & Mattsson, T. R. (2015). Impact vaporization of planetesimal cores in the late stages of planet formation. Nature Geoscience, 8(4), 269.\n\nLin, J. F., Campbell, A. J., Heinz, D. L., & Shen, G. (2003). Static compression of iron\u2010silicon alloys: Implications for silicon in the Earth's core. Journal of Geophysical Research: Solid Earth, 108(B1).\n\nLyon, S. P., & Johnson, J. D. (1992). SESAME: The LANL equation of state database. Los Alamos National Laboratories Report LAUR-92-3407, Los Alamos, NM.\n\nMedvedev, A. B. (2014). Wide-range multiphase equation of state for iron. Combustion, Explosion, and Shock Waves, 50(5), 582-598.\n\nMorard, G., Boccato, S., Rosa, A. D., Anzellini, S., Miozzi, F., Henry, L., ... & Boulard, E. (2018). Solving controversies on the iron phase diagram under high pressure. Geophysical Research Letters, 45(20), 11-074.\n\nMoreau, J. G., Kohout, T., & W\u00fcnnemann, K. (2018). Melting efficiency of troilite-iron assemblages in shock-darkening: Insight from numerical modeling. Physics of the Earth and Planetary Interiors, 282, 25-38.\n\nNasch, P. M., Manghnani, M. H., & Secco, R. A. (1994). Sound velocity measurements in liquid iron by ultrasonic interferometry. Journal of Geophysical Research: Solid Earth, 99(B3), 4285-4291.\n\nNguyen, J. H., & Holmes, N. C. (2004). Melting of iron at the physical conditions of the Earth's core. Nature, 427(6972), 339.\n\nPierazzo, E., Vickery, A. M., & Melosh, H. J. (1997). A reevaluation of impact melt production. Icarus, 127(2), 408-423.\n\nQuintana, S. N., Crawford, D. A., & Schultz, P. H. (2015). Analysis of impact melt and vapor production in CTH for planetary applications. Procedia Engineering, 103(C).\n\nTillotson, J. H. (1962). Metallic equations of state for hypervelocity impact (No. GA-3216). General Atomics Division, General Dynamics, San Diego, CA.\n\nSarid, G., Stewart, S. T., & Leinhardt, Z. M. (2015). Erosive Hit-and-Run Impact Events: Debris Unbound. Proceedings of the International Astronomical Union, 10(S318), 9-15.\n\nSjostrom, T., & Crockett, S. (2018). Quantum molecular dynamics of warm dense iron and a five-phase equation of state. Physical Review E, 97(5), 053209.\n\nSvetsov, V. V. (2005). Numerical simulations of very large impacts on the Earth. Planetary and Space Science, 53(12), 1205-1220.\n\nYue, Z., & Di, K. (2017). Hydrocode simulation of the impact melt layer distribution underneath Xiuyan Crater, China. Journal of Earth Science, 28(1), 180-186.\n\nZeman, M., Holec, M., & V\u00e1chal, P. (2019). HerEOS: A framework for consistent treatment of the Equation of State in ALE hydrodynamics. Computers & Mathematics with Applications, 78(2), 483-503.\n\n\n## ANEOS references\nCollins, Gareth S., and H. Jay Melosh (2014). Improvements to ANEOS for multiple phase transitions. 45th Lunar Planet. Sci. Conf. Abs. 2664.\n\nMelosh, H. J. (2007). A hydrocode equation of state for SiO$_2$. Meteoritics & Planetary Science, 42(12), 2079-2098.\n\nThompson, S. L. (1990). ANEOS analytic equations of state for shock physics codes input manual. SANDIA REPORT SAND, 89-2951.\n\nThompson, S. L., & Lauson, H. S. (1972). Improvements in the Chart D radiation-hydrodynamic CODE III: Revised analytic equations of state (No. SC-RR--71-0714). Sandia Labs.\n\nStewart, S., et al. (accepted). The shock physics of giant impacts: Key requirements for the equations of state. In J. Lane, T. Germann, and M. Armstrong (Eds.), 21st Biennial APS Conference on Shock Compression of Condensed Matter (SCCM19). AIP Publishing. (https://arxiv.org/abs/1910.04687)\n\nStewart, S. T. (2019). ANEOS Code Modification: Thermal model adjustment parameter. https://github.com/ststewart/aneos-forsterite-2019/EOS-docs/\n\n\nEnd of File\n\n##### \n", "meta": {"hexsha": "0f2cf3bdf03dccffca2bc3b999593c395af2e6ae", "size": 765530, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "aneos-T70/iron_aneos.ipynb", "max_stars_repo_name": "ststewart/aneos-iron-2020", "max_stars_repo_head_hexsha": "131167ae664862882e183ba82433b5fe771c4237", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-22T15:15:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T02:04:40.000Z", "max_issues_repo_path": "aneos-T70/iron_aneos.ipynb", "max_issues_repo_name": "ststewart/aneos-iron-2020", "max_issues_repo_head_hexsha": "131167ae664862882e183ba82433b5fe771c4237", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aneos-T70/iron_aneos.ipynb", "max_forks_repo_name": "ststewart/aneos-iron-2020", "max_forks_repo_head_hexsha": "131167ae664862882e183ba82433b5fe771c4237", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 239.1533895658, "max_line_length": 222044, "alphanum_fraction": 0.8834297807, "converted": true, "num_tokens": 46987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.04023793902695544, "lm_q1q2_score": 0.019333471751043836}}
{"text": "## Initial setup\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```python\nimport tensorflow as tf\nprint(tf.__version__)\nimport torch\nprint(torch.__version__)\nimport matplotlib\nprint(matplotlib.__version__)\n```\n\n    2.8.0\n    1.10.0+cu111\n    3.2.2\n\n\n\n```python\n!nvidia-smi\n```\n\n    Fri Jan 21 19:41:32 2022       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 495.46       Driver Version: 460.32.03    CUDA Version: 11.2     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   34C    P8     9W /  70W |      0MiB / 15109MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    |  No running processes found                                                 |\n    +-----------------------------------------------------------------------------+\n\n\n\n```python\n# Other imports\n! pip install tensorflow_addons\n! pip install tensorflow_io\n\nimport os\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import *\nfrom keras.callbacks import Callback, EarlyStopping, ModelCheckpoint\nfrom tensorflow.keras.applications.resnet50 import preprocess_input\nfrom tensorflow.keras.preprocessing.image import load_img\n\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfrom matplotlib.offsetbox import OffsetImage, AnnotationBbox\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter, AutoMinorLocator\nfrom imutils import paths\nfrom tqdm import tqdm\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nimport tensorflow_datasets as tfds\nimport tensorflow_io as tfio\nimport tensorflow_hub as hub\nimport numpy as np\nimport cv2\nimport pandas as pd\nimport seaborn as sns\nfrom scipy.stats import mannwhitneyu\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.cluster import KMeans\nimport sklearn.manifold\nfrom sklearn.metrics.pairwise import cosine_similarity as cos\nfrom sympy.utilities.iterables import multiset_permutations\nfrom sklearn.metrics import accuracy_score, f1_score,precision_score, recall_score, roc_auc_score, confusion_matrix\nfrom sklearn.model_selection import *\nfrom sklearn.preprocessing import StandardScaler\nfrom IPython.display import Image, display\n\n\nimport zipfile\nimport concurrent.futures\n\n# Random seed fix\nrandom_seed = 42\ntf.random.set_seed(random_seed)\nnp.random.seed(random_seed)\n```\n\n    Collecting tensorflow_addons\n      Downloading tensorflow_addons-0.16.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.1 MB 6.4 MB/s \n    \u001b[?25hRequirement already satisfied: typeguard>=2.7 in /usr/local/lib/python3.7/dist-packages (from tensorflow_addons) (2.7.1)\n    Installing collected packages: tensorflow-addons\n    Successfully installed tensorflow-addons-0.16.1\n    Collecting tensorflow_io\n      Downloading tensorflow_io-0.24.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (23.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 23.4 MB 1.8 MB/s \n    \u001b[?25hRequirement already satisfied: tensorflow-io-gcs-filesystem==0.24.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow_io) (0.24.0)\n    Installing collected packages: tensorflow-io\n    Successfully installed tensorflow-io-0.24.0\n\n\n## Dataset gathering and preparation\n\n\n```python\n%cd /content/drive/MyDrive/nanowire-morphology-classification-project\n```\n\n\n```python\ntraining_batch_size = 4\n\nBATCH_SIZE = training_batch_size\n\nimageSize = 224\n\ncategory_names = ['bundle', 'dispersed', 'network', 'singular']\ncolor_method = ['C0', 'C1', 'C2', 'C3', 'C4']\ncolor = ['black', 'magenta', 'cyan', 'yellow']\nmarker = ['o', 's', '<', '>', '^']\nseaborn_palette = sns.color_palette(\"colorblind\")\n```\n\n# generating the jpg images\n\n\n```python\n# generating jpg images from the original tif images\n\nnp.random.seed(random_seed)\npeptide_morph_train_path = \"/content/drive/MyDrive/TEM image datasets/2022-nanowire-morphology\"\npeptide_morph_images_train = list(paths.list_files(basePath=peptide_morph_train_path, validExts='tif'))\npeptide_morph_images_train = np.random.choice(np.array(peptide_morph_images_train), len(peptide_morph_images_train), replace=False)\nprint(len(peptide_morph_images_train))\n\nfor i in range(len(peptide_morph_images_train)):\n  img = cv2.imread(peptide_morph_images_train[i])\n  if img is None:\n    continue\n  img = cv2.imread(peptide_morph_images_train[i])\n  cv2.imwrite('%s.jpg' %peptide_morph_images_train[i].split(\".\")[0], img)\n```\n\n    400\n\n\n## image data augmentation for the singular morphology\n\n\n```python\n# generating augmented images for the singular morphology\nnp.random.seed(random_seed)\npeptide_morph_train_path = \"/content/drive/MyDrive/TEM image datasets/2022-nanowire-morphology/singular\"\npeptide_morph_images_train = list(paths.list_files(basePath=peptide_morph_train_path, validExts='jpg'))\npeptide_morph_images_train = np.random.choice(np.array(peptide_morph_images_train), len(peptide_morph_images_train), replace=False)\nprint(len(peptide_morph_images_train))\n\nfor i in range(len(peptide_morph_images_train)):\n  # these are for augmentating the singular morphology by generating 3 different rotated images (90, 180, 270 degrees)\n  img = cv2.rotate(img, cv2.cv2.ROTATE_90_CLOCKWISE)\n  cv2.imwrite('%s_1.jpg' %peptide_morph_images_train[i].split(\".\")[0], img)\n  img = cv2.rotate(img, cv2.cv2.ROTATE_90_CLOCKWISE)\n  cv2.imwrite('%s_2.jpg' %peptide_morph_images_train[i].split(\".\")[0], img)\n  img = cv2.rotate(img, cv2.cv2.ROTATE_90_CLOCKWISE)\n  cv2.imwrite('%s_3.jpg' %peptide_morph_images_train[i].split(\".\")[0], img)\n\n```\n\n# generating segmentation ground truth binary maps (seg_mask.npz files)\n\n\n```python\nnp.random.seed(random_seed)\npeptide_morph_seglabel_train_path = \"/content/drive/MyDrive/TEM image datasets/2022-nanowire-morphology\"\npeptide_morph_images_train_seglabel = list(paths.list_files(basePath=peptide_morph_seglabel_train_path, validExts='png'))\npeptide_morph_images_train_seglabel = np.random.choice(np.array(peptide_morph_images_train_seglabel), len(peptide_morph_images_train_seglabel), replace=False)\nprint(len(peptide_morph_images_train_seglabel))\n```\n\n\n```python\ndef generate_ground_truth_images(image, resolution):\n  image_bool = np.ones((resolution, resolution))\n  for i in range(image.shape[0]):\n    for j in range(image.shape[1]):\n      if image[i, j, 1] == image[i, j, 2]:\n        image_bool[i, j] = 0            # background is black with code of 0\n      else: \n        image_bool[i, j] = 1            # nanowire is white with code of 1\n  return image_bool\n```\n\n\n```python\nsegmentation_class_labels = []\nfor i in range(peptide_morph_images_train_seglabel.shape[0]):\n  seg_class_label = peptide_morph_images_train_seglabel[i].split(\"/\")[-2]\n  segmentation_class_labels.append(seg_class_label)\nle = LabelEncoder()\npeptide_morph_train_seg_enc = le.fit_transform(segmentation_class_labels)\n```\n\n\n```python\nimage_mask = np.zeros((len(peptide_morph_images_train_seglabel), imageSize, imageSize))\n\n\nfor i in range(len(peptide_morph_images_train_seglabel)):\n\n  # these were used to create the ground truth grayscale images from the manual segmentation labels.\n  image_string = tf.io.read_file(peptide_morph_images_train_seglabel[i])\n  image = tf.image.decode_image(image_string, channels=3) / 255\n  image = tf.image.resize(image, (imageSize, imageSize))\n  image = tf.image.convert_image_dtype(image, tf.float32)\n  trans_nd_image_array = image.numpy()\n  image_mask[i] = generate_ground_truth_images(trans_nd_image_array, imageSize)\n  \nnp.savez_compressed('seg_mask_res512.npz', mask=image_mask)\n\n# once we have the seg_mask saved, we can directly load from npz file\n# image_mask = np.load('seg_mask_res%i.npz' % (imageSize), allow_pickle=True)['mask']\n```\n\n    WARNING:tensorflow:5 out of the last 5 calls to <function parse_images at 0x7f9490054b90> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for  more details.\n    WARNING:tensorflow:6 out of the last 6 calls to <function parse_images at 0x7f9490054b90> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for  more details.\n\n", "meta": {"hexsha": "3ab8900741de883ae878b182a06970da7f6c1121", "size": 14890, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Preprocess images.ipynb", "max_stars_repo_name": "arthijayaraman-lab/self-supervised_learning_microscopy_images", "max_stars_repo_head_hexsha": "f7adc86798379ae3934a864e6c41982a15aae870", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/Preprocess images.ipynb", "max_issues_repo_name": "arthijayaraman-lab/self-supervised_learning_microscopy_images", "max_issues_repo_head_hexsha": "f7adc86798379ae3934a864e6c41982a15aae870", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/Preprocess images.ipynb", "max_forks_repo_name": "arthijayaraman-lab/self-supervised_learning_microscopy_images", "max_forks_repo_head_hexsha": "f7adc86798379ae3934a864e6c41982a15aae870", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14890.0, "max_line_length": 14890, "alphanum_fraction": 0.6784419073, "converted": true, "num_tokens": 2475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2974699426047947, "lm_q2_score": 0.06465348159779348, "lm_q1q2_score": 0.019232467460095777}}
{"text": "```python\npip install cirq\n```\n\n    Collecting cirq\n      Downloading cirq-0.13.1-py3-none-any.whl (7.7 kB)\n    Collecting cirq-rigetti==0.13.1\n      Downloading cirq_rigetti-0.13.1-py3-none-any.whl (55 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 55 kB 2.2 MB/s \n    \u001b[?25hCollecting cirq-aqt==0.13.1\n      Downloading cirq_aqt-0.13.1-py3-none-any.whl (18 kB)\n    Collecting cirq-pasqal==0.13.1\n      Downloading cirq_pasqal-0.13.1-py3-none-any.whl (29 kB)\n    Collecting cirq-ionq==0.13.1\n      Downloading cirq_ionq-0.13.1-py3-none-any.whl (47 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 47 kB 4.3 MB/s \n    \u001b[?25hCollecting cirq-core==0.13.1\n      Downloading cirq_core-0.13.1-py3-none-any.whl (1.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.6 MB 8.8 MB/s \n    \u001b[?25hCollecting cirq-google==0.13.1\n      Downloading cirq_google-0.13.1-py3-none-any.whl (437 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 437 kB 55.1 MB/s \n    \u001b[?25hCollecting cirq-web==0.13.1\n      Downloading cirq_web-0.13.1-py3-none-any.whl (328 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 328 kB 58.8 MB/s \n    \u001b[?25hRequirement already satisfied: requests~=2.18 in /usr/local/lib/python3.7/dist-packages (from cirq-aqt==0.13.1->cirq) (2.23.0)\n    Requirement already satisfied: networkx~=2.4 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (2.6.3)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (1.4.1)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (4.62.3)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (1.7.1)\n    Collecting duet~=0.2.0\n      Downloading duet-0.2.3-py3-none-any.whl (30 kB)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (3.10.0.2)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (1.3.5)\n    Requirement already satisfied: numpy~=1.16 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (1.21.5)\n    Requirement already satisfied: sortedcontainers~=2.0 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (2.4.0)\n    Requirement already satisfied: matplotlib~=3.0 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.13.1->cirq) (3.2.2)\n    Requirement already satisfied: google-api-core[grpc]<2.0.0dev,>=1.14.0 in /usr/local/lib/python3.7/dist-packages (from cirq-google==0.13.1->cirq) (1.26.3)\n    Requirement already satisfied: protobuf>=3.13.0 in /usr/local/lib/python3.7/dist-packages (from cirq-google==0.13.1->cirq) (3.17.3)\n    Collecting pyjwt~=1.7.1\n      Downloading PyJWT-1.7.1-py2.py3-none-any.whl (18 kB)\n    Collecting rfc3339~=6.2\n      Downloading rfc3339-6.2-py3-none-any.whl (5.5 kB)\n    Collecting iso8601~=0.1.14\n      Downloading iso8601-0.1.16-py2.py3-none-any.whl (10 kB)\n    Collecting qcs-api-client~=0.8.0\n      Downloading qcs_api_client-0.8.0-py3-none-any.whl (97 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 97 kB 5.8 MB/s \n    \u001b[?25hRequirement already satisfied: idna~=2.10 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (2.10)\n    Collecting httpcore~=0.11.1\n      Downloading httpcore-0.11.1-py3-none-any.whl (52 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 52 kB 1.3 MB/s \n    \u001b[?25hRequirement already satisfied: python-dateutil~=2.8.1 in /usr/local/lib/python3.7/dist-packages (from cirq-rigetti==0.13.1->cirq) (2.8.2)\n    Collecting pyquil~=3.0.0\n      Downloading pyquil-3.0.1-py3-none-any.whl (220 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 220 kB 66.0 MB/s \n    \u001b[?25hCollecting retrying~=1.3.3\n      Downloading retrying-1.3.3.tar.gz (10 kB)\n    Collecting attrs~=20.3.0\n      Downloading attrs-20.3.0-py2.py3-none-any.whl (49 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 49 kB 5.4 MB/s \n    \u001b[?25hCollecting sniffio~=1.2.0\n      Downloading sniffio-1.2.0-py3-none-any.whl (10 kB)\n    Collecting rfc3986~=1.5.0\n      Downloading rfc3986-1.5.0-py2.py3-none-any.whl (31 kB)\n    Collecting certifi~=2021.5.30\n      Downloading certifi-2021.5.30-py2.py3-none-any.whl (145 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 145 kB 65.9 MB/s \n    \u001b[?25hCollecting h11~=0.9.0\n      Downloading h11-0.9.0-py2.py3-none-any.whl (53 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 53 kB 1.7 MB/s \n    \u001b[?25hCollecting six~=1.16.0\n      Downloading six-1.16.0-py2.py3-none-any.whl (11 kB)\n    Collecting pydantic~=1.8.2\n      Downloading pydantic-1.8.2-cp37-cp37m-manylinux2014_x86_64.whl (10.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 10.1 MB 25.5 MB/s \n    \u001b[?25hCollecting toml~=0.10.2\n      Downloading toml-0.10.2-py2.py3-none-any.whl (16 kB)\n    Collecting httpx~=0.15.5\n      Downloading httpx-0.15.5-py3-none-any.whl (65 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 65 kB 3.0 MB/s \n    \u001b[?25hRequirement already satisfied: google-auth<2.0dev,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (1.35.0)\n    Requirement already satisfied: setuptools>=40.3.0 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (57.4.0)\n    Requirement already satisfied: pytz in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (2018.9)\n    Requirement already satisfied: packaging>=14.3 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (21.3)\n    Requirement already satisfied: googleapis-common-protos<2.0dev,>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (1.54.0)\n    Requirement already satisfied: grpcio<2.0dev,>=1.29.0 in /usr/local/lib/python3.7/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (1.43.0)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (0.2.8)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (4.2.4)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (4.8)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core==0.13.1->cirq) (3.0.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core==0.13.1->cirq) (1.3.2)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core==0.13.1->cirq) (0.11.0)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2.0dev,>=1.21.1->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.13.1->cirq) (0.4.8)\n    Collecting lark<0.12.0,>=0.11.1\n      Downloading lark-0.11.3.tar.gz (229 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 229 kB 54.2 MB/s \n    \u001b[?25hCollecting scipy\n      Downloading scipy-1.7.3-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (38.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 38.1 MB 1.3 MB/s \n    \u001b[?25hCollecting importlib-metadata<4.0.0,>=3.7.3\n      Downloading importlib_metadata-3.10.1-py3-none-any.whl (14 kB)\n    Collecting rpcq<4.0.0,>=3.6.0\n      Downloading rpcq-3.9.2.tar.gz (43 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 43 kB 1.9 MB/s \n    \u001b[?25hCollecting retry<0.10.0,>=0.9.2\n      Downloading retry-0.9.2-py2.py3-none-any.whl (8.0 kB)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata<4.0.0,>=3.7.3->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (3.7.0)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests~=2.18->cirq-aqt==0.13.1->cirq) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests~=2.18->cirq-aqt==0.13.1->cirq) (3.0.4)\n    Requirement already satisfied: py<2.0.0,>=1.4.26 in /usr/local/lib/python3.7/dist-packages (from retry<0.10.0,>=0.9.2->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (1.11.0)\n    Requirement already satisfied: decorator>=3.4.2 in /usr/local/lib/python3.7/dist-packages (from retry<0.10.0,>=0.9.2->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (4.4.2)\n    Collecting msgpack<1.0,>=0.6\n      Downloading msgpack-0.6.2-cp37-cp37m-manylinux1_x86_64.whl (243 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 243 kB 38.9 MB/s \n    \u001b[?25hCollecting python-rapidjson\n      Downloading python_rapidjson-1.6-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.6 MB 42.3 MB/s \n    \u001b[?25hRequirement already satisfied: pyzmq>=17 in /usr/local/lib/python3.7/dist-packages (from rpcq<4.0.0,>=3.6.0->pyquil~=3.0.0->cirq-rigetti==0.13.1->cirq) (22.3.0)\n    Collecting ruamel.yaml\n      Downloading ruamel.yaml-0.17.21-py3-none-any.whl (109 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 109 kB 51.8 MB/s \n    \u001b[?25hCollecting ruamel.yaml.clib>=0.2.6\n      Downloading ruamel.yaml.clib-0.2.6-cp37-cp37m-manylinux1_x86_64.whl (546 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 546 kB 50.5 MB/s \n    \u001b[?25hRequirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->cirq-core==0.13.1->cirq) (1.2.1)\n    Building wheels for collected packages: lark, retrying, rpcq\n      Building wheel for lark (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for lark: filename=lark-0.11.3-py2.py3-none-any.whl size=99648 sha256=e00413a300dcc7c31665a6a84daffa63402e5eb25916521a2eb67811ec94ac9f\n      Stored in directory: /root/.cache/pip/wheels/d7/61/3c/9ac365f55966367be8d77dbeb21a3ddece3c466e660121e8d6\n      Building wheel for retrying (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for retrying: filename=retrying-1.3.3-py3-none-any.whl size=11447 sha256=f4be6e4398f507241c3daeffc5503293ac6d6dadbff0542c6babd88de4f47c83\n      Stored in directory: /root/.cache/pip/wheels/f9/8d/8d/f6af3f7f9eea3553bc2fe6d53e4b287dad18b06a861ac56ddf\n      Building wheel for rpcq (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for rpcq: filename=rpcq-3.9.2-py3-none-any.whl size=45877 sha256=13e9c19f1bffacc3eca5bdcb1781e0a6b0386b0b5dd8d12be9b78a88ce9d3875\n      Stored in directory: /root/.cache/pip/wheels/96/fb/72/b2179c8c6be1c6ded2d987247ac425957ca56208d81e99a2f2\n    Successfully built lark retrying rpcq\n    Installing collected packages: sniffio, six, rfc3986, h11, ruamel.yaml.clib, httpcore, certifi, toml, ruamel.yaml, rfc3339, retrying, python-rapidjson, pyjwt, pydantic, msgpack, iso8601, httpx, attrs, scipy, rpcq, retry, qcs-api-client, lark, importlib-metadata, duet, pyquil, cirq-core, cirq-web, cirq-rigetti, cirq-pasqal, cirq-ionq, cirq-google, cirq-aqt, cirq\n      Attempting uninstall: six\n        Found existing installation: six 1.15.0\n        Uninstalling six-1.15.0:\n          Successfully uninstalled six-1.15.0\n      Attempting uninstall: certifi\n        Found existing installation: certifi 2021.10.8\n        Uninstalling certifi-2021.10.8:\n          Successfully uninstalled certifi-2021.10.8\n      Attempting uninstall: msgpack\n        Found existing installation: msgpack 1.0.3\n        Uninstalling msgpack-1.0.3:\n          Successfully uninstalled msgpack-1.0.3\n      Attempting uninstall: attrs\n        Found existing installation: attrs 21.4.0\n        Uninstalling attrs-21.4.0:\n          Successfully uninstalled attrs-21.4.0\n      Attempting uninstall: scipy\n        Found existing installation: scipy 1.4.1\n        Uninstalling scipy-1.4.1:\n          Successfully uninstalled scipy-1.4.1\n      Attempting uninstall: importlib-metadata\n        Found existing installation: importlib-metadata 4.11.1\n        Uninstalling importlib-metadata-4.11.1:\n          Successfully uninstalled importlib-metadata-4.11.1\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    tensorflow 2.8.0 requires tf-estimator-nightly==2.8.0.dev2021122109, which is not installed.\n    markdown 3.3.6 requires importlib-metadata>=4.4; python_version < \"3.10\", but you have importlib-metadata 3.10.1 which is incompatible.\n    google-colab 1.0.0 requires six~=1.15.0, but you have six 1.16.0 which is incompatible.\n    datascience 0.10.6 requires folium==0.2.1, but you have folium 0.8.3 which is incompatible.\n    albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Successfully installed attrs-20.3.0 certifi-2021.5.30 cirq-0.13.1 cirq-aqt-0.13.1 cirq-core-0.13.1 cirq-google-0.13.1 cirq-ionq-0.13.1 cirq-pasqal-0.13.1 cirq-rigetti-0.13.1 cirq-web-0.13.1 duet-0.2.3 h11-0.9.0 httpcore-0.11.1 httpx-0.15.5 importlib-metadata-3.10.1 iso8601-0.1.16 lark-0.11.3 msgpack-0.6.2 pydantic-1.8.2 pyjwt-1.7.1 pyquil-3.0.1 python-rapidjson-1.6 qcs-api-client-0.8.0 retry-0.9.2 retrying-1.3.3 rfc3339-6.2 rfc3986-1.5.0 rpcq-3.9.2 ruamel.yaml-0.17.21 ruamel.yaml.clib-0.2.6 scipy-1.7.3 six-1.16.0 sniffio-1.2.0 toml-0.10.2\n\n\n\n\n\n```python\n\"\"\"\nCreated on Thu Feb 24 21:54:47 2022\n\n@author: Ananyo\n\"\"\"\nimport cirq\nimport math\nimport random\nimport fractions\nimport time\nimport matplotlib.pyplot as plt\nimport sympy\nfrom typing import Callable, Optional, Sequence, Union\n\n\"\"\"This Code is capable of implementing the Classical and Quantum Period Finding Part of Shor's Algorithm\"\"\"\n##############################################################################\n#################################  SECTION 1  ################################\n##############################################################################\n\n\"\"\"Functions Implementing the Quantum Period Finding Section of Algorithm\"\"\" \n\n\"\"\"\n    Class employs Quantum Modular Exponentiation (x^e mod(N)) implementation together \n    with the Quantum Phase Estimation to compute the order of x mod(N)\n\"\"\"\nclass QModExp(cirq.ArithmeticOperation):\n\n    def __init__(\n        self,\n        target: Sequence[cirq.Qid],\n        exponent: Union[int, Sequence[cirq.Qid]],\n        base: int,\n        modulus: int,\n    ) -> None:\n        if len(target) < modulus.bit_length():\n            raise ValueError(\n                f'Register with {len(target)} qubits is too small for modulus {modulus}'\n            )\n        self.target = target\n        self.exponent = exponent\n        self.base = base\n        self.modulus = modulus\n\n    def registers(self) -> Sequence[Union[int, Sequence[cirq.Qid]]]:\n        return self.target, self.exponent, self.base, self.modulus\n\n    def with_registers(\n        self,\n        *new_registers: Union[int, Sequence['cirq.Qid']],) -> 'QModExp':\n        if len(new_registers) != 4:\n            raise ValueError(\n                f'Expected 4 registers (target, exponent, base, '\n                f'modulus), but got {len(new_registers)}'\n            )\n        target, exponent, base, modulus = new_registers\n        if not isinstance(target, Sequence):\n            raise ValueError(f'Target must be a qubit register, got {type(target)}')\n        if not isinstance(base, int):\n            raise ValueError(f'Base must be a classical constant, got {type(base)}')\n        if not isinstance(modulus, int):\n            raise ValueError(f'Modulus must be a classical constant, got {type(modulus)}')\n        return QModExp(target, exponent, base, modulus)\n\n    def apply(self, *register_values: int) -> int:\n        assert len(register_values) == 4\n        target, exponent, base, modulus = register_values\n        if target >= modulus:\n            return target\n        return (target * base ** exponent) % modulus\n    \n    \"\"\"\n        Declaring Sybmols to be used for Circuit for Quantum Period Finding\n        Can be uncommented in case the circuit needs to be printed\n    \"\"\"\n\n    # def _circuit_diagram_info_(\n    #     self,\n    #     args: cirq.CircuitDiagramInfoArgs,\n    # ) -> cirq.CircuitDiagramInfo:\n    #     assert args.known_qubits is not None\n    #     wire_symbols: List[str] = []\n    #     t, e = 0, 0\n    #     for qubit in args.known_qubits:\n    #         if qubit in self.target:\n    #             if t == 0:\n    #                 if isinstance(self.exponent, Sequence):\n    #                     e_str = 'e'\n    #                 else:\n    #                     e_str = str(self.exponent)\n    #                 wire_symbols.append(f'QModExp(t*{self.base}**{e_str} % {self.modulus})')\n    #             else:\n    #                 wire_symbols.append('t' + str(t))\n    #             t += 1\n    #         if isinstance(self.exponent, Sequence) and qubit in self.exponent:\n    #             wire_symbols.append('e' + str(e))\n    #             e += 1\n    #     return cirq.CircuitDiagramInfo(wire_symbols=tuple(wire_symbols))\n\n\n\"\"\"\n    Creating the Circuit for Quantum Period Finding \n        x: positive integer whose order modulo n is to be found\n        N: modulus relative to which the order of x is to be found\n    Returns:\n        Quantum circuit for finding the order of x modulo N\n\"\"\"\ndef quantum_period_finding_circuit(x: int, N: int) -> cirq.Circuit:\n    L = N.bit_length()\n    target = cirq.LineQubit.range(L)\n    exponent = cirq.LineQubit.range(L, 3 * L + 3)\n    return cirq.Circuit(\n        cirq.X(target[L - 1]),\n        cirq.H.on_each(*exponent),\n        QModExp(target, exponent, x, N),\n        cirq.qft(*exponent, inverse=True),\n        cirq.measure(*exponent, key='exponent'),\n\n    )\n\n\n    \"\"\"\n       Function used to evaluate s/r where r is the order of x modulo N \n        x: integer whose order is to be computed, must be greater than one\n           and belong to the multiplicative group of integers modulo n (which\n           consists of positive integers relatively prime to n),\n        n: modulus of the multiplicative group.\n    Returns:\n        Smallest positive integer r such that x**r == 1 mod n \n\n    \"\"\"\n\ndef read_eigenphase(result: cirq.Result) -> float:\n\n    exponent_as_integer = result.data['exponent'][0]\n    exponent_num_bits = result.measurements['exponent'].shape[1]\n    return float(exponent_as_integer / 2 ** exponent_num_bits)\n\n    \"\"\"\n    \"\"\"\ndef find_order(x: int, N: int) -> Optional[int]:\n\n    if x < 2 or N <= x or math.gcd(x, N) > 1:\n        raise ValueError(f'Invalid x={x} for modulus n={N}.')\n\n    circuit = quantum_period_finding_circuit(x, N)\n    result = cirq.sample(circuit)\n    eigenphase = read_eigenphase(result)\n    f = fractions.Fraction.from_float(eigenphase).limit_denominator(N)\n    if f.numerator == 0:\n        return None  # coverage: ignore\n    r = f.denominator\n    if x ** r % N != 1:\n        return None  # coverage: ignore\n    return r\n\n\n\n##############################################################################\n#################################  SECTION 2  ################################\n##############################################################################\n\"\"\"\n     CLassical Computation of Shor's Algorithm\n\"\"\"    \n\n\"\"\"\n    Function takes a compostite number N and returns its non-trivial factor\n\"\"\"\ndef find_factor_of_prime_power(n: int) -> Optional[int]:\n\n    for k in range(2, math.floor(math.log2(n)) + 1):\n        c = math.pow(n, 1 / k)\n        c1 = math.floor(c)\n        if c1 ** k == n:\n            return c1\n        c2 = math.ceil(c)\n        if c2 ** k == n:\n            return c2\n    return None\n\n\"\"\"\n    Function checks for prime factors\n\"\"\"\ndef find_factor(\n    n: int, order_finder: Callable[[int, int], Optional[int]], max_attempts: int = 50\n) -> Optional[int]:\n\n    if sympy.isprime(n):\n        return None\n    if n % 2 == 0:\n        return 2\n    c = find_factor_of_prime_power(n)\n    if c is not None:\n        return c\n    for _ in range(max_attempts):\n        x = random.randint(2, n - 1)\n        c = math.gcd(x, n)\n        if 1 < c < n:\n            return c  # coverage: ignore\n        r = order_finder(x, n)\n        if r is None:\n            continue  # coverage: ignore\n        if r % 2 != 0:\n            continue  # coverage: ignore\n        y = x ** (r // 2) % n\n        assert 1 < y < n\n        c = math.gcd(y - 1, n)\n        if 1 < c < n:\n            return c\n    return None  # coverage: ignore\n\n\n##############################################################################\n#################################  SECTION 3  ################################\n##############################################################################\n\"\"\"\n    Main Function Compiling all parts and implementing Shor's Algorithm\n\"\"\"\n#Algorithm can evaluate all the prime factors of the given number\ndef main(\n    n: int,\n    order_finder: Callable[[int, int], Optional[int]] = find_order,\n):\n    if n < 2:\n        raise ValueError('Expected positive integer N must be greater than one.')\n\n    d = find_factor(n, order_finder)\n\n    if d is None:\n #       print(f'No non-trivial factor of {n} found. It is probably a prime.')\n      print(f'{n} is Prime')\n    else:\n        e=n//d\n        f=[e]\n        g=0\n        while(sympy.isprime(e)==False and g!=None):\n            g = find_factor(e, order_finder)\n            f.append(g)    \n            e=e//g\n\n        \n                \n        if d!=e and e!=f[0]:\n            print(f'Prime Factors of {n}: {d}, {e}', end=\" \")\n            for i in range(1,len(f)):\n                if(i!=len(f)-1 and f[i]!=f[1]):\n                    print(\",\",f[i], end=\" \")\n                elif(f[i]!=f[1]):\n                    print(f[i])\n                else:\n                    print(\"\")\n                    break\n        elif d!=e:\n            print(f'Prime Factors of {n}: {d}, {e}')            \n        \n        else:\n            print(f'Prime Factor of {n}: {d}')\n\n        assert 1 < d < n\n        assert n % d == 0\n\nif __name__ == '__main__':\n\n    t=[]\n    for i in range(2,36):\n        st=time.time()\n        main(i,find_order)\n        end=time.time()\n        t.append(end-st)\n        \n\n#Plotting the Runtime Vs Integer Plot \nplt.scatter(list(range(2,36)), t)\nplt.title(\" Runtime for Prime Factorization Vs Integer \")\nplt.xlabel(\"Value of Integer\")\nplt.ylabel(\"Runtime\")\nplt.show()\n```\n\n    2 is Prime\n    3 is Prime\n    Prime Factor of 4: 2\n    5 is Prime\n    Prime Factors of 6: 2, 3\n    7 is Prime\n    Prime Factor of 8: 2\n    Prime Factor of 9: 3\n    Prime Factors of 10: 2, 5\n    11 is Prime\n    Prime Factors of 12: 2, 3 \n    13 is Prime\n    Prime Factors of 14: 2, 7\n    Prime Factors of 15: 3, 5\n    Prime Factor of 16: 2\n    17 is Prime\n    Prime Factors of 18: 2, 3 \n    19 is Prime\n    Prime Factors of 20: 2, 5 \n\n", "meta": {"hexsha": "464257c8e4e0460c59b382ece185d39f27a83366", "size": 31093, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Shor's_Algorithm_Cirq.ipynb", "max_stars_repo_name": "ananyoemon/Quantum-Algorithms", "max_stars_repo_head_hexsha": "1707b67e1181c0b9ddee32de6fb150109caa5119", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Shor's_Algorithm_Cirq.ipynb", "max_issues_repo_name": "ananyoemon/Quantum-Algorithms", "max_issues_repo_head_hexsha": "1707b67e1181c0b9ddee32de6fb150109caa5119", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Shor's_Algorithm_Cirq.ipynb", "max_forks_repo_name": "ananyoemon/Quantum-Algorithms", "max_forks_repo_head_hexsha": "1707b67e1181c0b9ddee32de6fb150109caa5119", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.9013035382, "max_line_length": 560, "alphanum_fraction": 0.4949988743, "converted": true, "num_tokens": 7626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3106943959796865, "lm_q2_score": 0.061875986588615615, "lm_q1q2_score": 0.01922452227879711}}
{"text": "# Prerequsites\n\n\n```python\n# log the time of the experiment\nfrom datetime import datetime\nimport time\n\nexp_time = datetime.now()\nexp_time_str = exp_time.strftime(\"_%H_%M_%S\")\ndate_str = exp_time.strftime(\"%m_%d_%y\")\n```\n\n\n```python\n# Path management for MacOS and Windows\nfrom pathlib import Path\nimport os, sys\n\nscriptPath = Path(sys.path[0])\nparentPath = Path(sys.path[0]).parent\n#libPath = Path(\"/home/tw329/GitHub/ONN_MNIST/\")\nlibPath = Path(\"C:\\\\Users\\\\Logan\\\\Documents\\\\GitHub\\\\ONN_MNIST\")\nsys.path.append(libPath.as_posix())\nsys.path.append(\"C:\\\\Users\\\\Logan\\\\Documents\\\\GitHub\\\\mcmahon_lab_devices\") \n\n# Set the working directory (to save the files)\nresultPath = scriptPath\n\nslmWeightPath = resultPath / \"slm_weights\"\nif not os.path.exists(slmWeightPath.as_posix()):\n    os.makedirs(slmWeightPath.as_posix())\n    \nphoneImagePath = resultPath / \"phone_images\"\nif not os.path.exists(phoneImagePath.as_posix()):\n    os.makedirs(phoneImagePath.as_posix())\n    \nsaveDataPath = resultPath / \"saved_data\"\nif not os.path.exists(saveDataPath.as_posix()):\n    os.makedirs(saveDataPath.as_posix())\n    \nprint(resultPath)\n```\n\n    D:\\McMahon lab Dropbox\\peter mcmahon\\tw329\\Experiments\\12_01_20_4bit_randy_aug_MLP_100_100_MPPC\n\n\n\n```python\nfrom __future__ import print_function\nimport os, sys\nimport argparse\nfrom IPython.core.debugger import set_trace\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\nimport numpy as np\nimport pandas\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\n```\n\n\n```python\n%matplotlib notebook\n```\n\n# Instrument Controls\n\n\n```python\n# Configure the SLM\nfrom src.slmpy import SLMdisplay   # Popoff's simple package for controlling SLM\n\nslm = SLMdisplay(isImageLock = True)\n\nLUT_used=\"AmpLUT_basedon_100120slmbackcali_140509_start5.lut\"\n\nslmParamFile = resultPath / ''.join([\"slm_info\", exp_time_str, \".txt\"])\nwith open(slmParamFile,'w') as slmparams:\n    slmparams.write('LUT\\t\\t\\t{}\\n'.format(LUT_used))\nslmparams.close()\n\n```\n\n    C:/Users/Logan/Documents/GitHub/ONN_MNIST\\src\\slmpy.py:39: wxPyDeprecationWarning: Call to deprecated item EmptyImage. Use :class:`Image` instead.\n      self.img = wx.EmptyImage(2,2)\n\n\n\n```python\nimport pyvisa\nfrom devices import Agilent54845A as AgilentOscope\n\nrm = pyvisa.ResourceManager(\"C:\\\\WINDOWS\\\\System32\\\\visa64.dll\")\ngpib_id = rm.list_resources()[-1]\noscope = AgilentOscope(rm.open_resource(gpib_id))\noscope.set_waveform_source(1)\n\ndef oscope_info(oscope):\n    measure_state = {}\n    measure_state[\"ID\"] = oscope.id()\n    measure_state[\"x_range\"] = oscope.get_xrange()\n    measure_state[\"x_unit\"] = oscope.get_xunits()\n    measure_state[\"y_range\"] = oscope.get_yrange()\n    measure_state[\"y_unit\"] = oscope.get_yunits()\n    measure_state[\"y_offset\"] = oscope.get_offset()\n    measure_state[\"y_bounds\"] = [oscope.get_bottom_bound(), oscope.get_top_bound()]\n    return measure_state\n```\n\n\n```python\n# Configure the phone\n\nfrom Android_Display_Control.Remote_Display.image_stream import AndroidOpenAccessoryBridge as AOAB\n\nPIXEL_VENDOR_ID = 0x18d1\nPIXEL_UNCONFIG_ID =  0x4ee7\nPIXEL_CONFIG_ID = 0x2d01\n\n# Create an AOAB object for managing data send/receive via USB\naoab = AOAB(PIXEL_VENDOR_ID, PIXEL_UNCONFIG_ID, \n  PIXEL_CONFIG_ID,\n  manufacturer='ImageStreamManufacturer',\n  model='ImageStream1',\n  description='Stream Images to Android',\n  version=1,\n  uri=('https://github.com/chris-blay/android-open-accessory-bridge'),\n  serial='AoabSerial')\n```\n\n    Exception ignored in: <function _AutoFinalizedObjectBase.__del__ at 0x000002C0617F6D90>\n    Traceback (most recent call last):\n      File \"C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\usb\\_objfinalizer.py\", line 84, in __del__\n        self.finalize()\n      File \"C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\usb\\_objfinalizer.py\", line 144, in finalize\n        self._finalizer()\n      File \"C:\\Users\\Logan\\Anaconda3\\lib\\weakref.py\", line 552, in __call__\n        return info.func(*info.args, **(info.kwargs or {}))\n      File \"C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\usb\\_objfinalizer.py\", line 104, in _do_finalize_object_ref\n        obj._do_finalize_object()\n      File \"C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\usb\\_objfinalizer.py\", line 71, in _do_finalize_object\n        self._finalize_object()\n      File \"C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\usb\\backend\\libusb1.py\", line 604, in _finalize_object\n        _lib.libusb_unref_device(self.devid)\n    OSError: exception: access violation writing 0x0000000000000024\n\n\n\n```python\ndef PIL_to_bytestream(img_px):\n    array_px = np.array(img_px)\n    byte_array_px = bytearray()\n\n    for i in range(array_px.shape[0]):\n        for j in range(array_px.shape[1]):\n            byte_array_px.append(array_px[i, j, 0])\n            byte_array_px.append(array_px[i, j, 1])\n            byte_array_px.append(array_px[i, j, 2])\n\n    assert(len(byte_array_px) == 1920*1080*3)\n    return byte_array_px\n```\n\n\n```python\n# Load the phone pixel LUT\nlut_p = torch.zeros(1000, dtype=torch.uint8) \nwith open((resultPath/'PhoneLUT_100120_161444c30et20ms_1000.lut').as_posix(),'r') as lutfile:\n        for i in range(len(lut_p)):\n            aline = lutfile.readline().split()\n            lut_p[i] = int(aline[1])\nlutfile.close()\n```\n\n# Helper Functions\n\n\n```python\n\"\"\" Helper functions for generating phone and SLM patterns. \"\"\"\n\nfrom math import sqrt\n\ndef Wrap_vec_to_square (idx_vec, null_element=torch.tensor([-1])):\n    \n    if isinstance(null_element, int):\n        null_element = torch.tensor([null_element])\n        \n    a = int(sqrt(len(idx_vec)))\n    if len(idx_vec) < a*(a+1):\n        px_col_counts = a\n        last_row_supplements = a - 1 - (idx_vec.numel()-1)%a \n    if len(idx_vec) >= a*(a+1):\n        px_col_counts = a+1\n        last_row_supplements = a - (idx_vec.numel()-1)%(a+1)\n    \n    idx_vec = torch.cat((idx_vec, torch.repeat_interleave(null_element, last_row_supplements)))\n    idx_vec = idx_vec.view(-1, px_col_counts)\n    \n    return idx_vec\n\n# Image binarize functions\ndef binarize_img_by_percentile(img, rate):\n    img_b = (img<=np.percentile(img.numpy(), rate))\n    res_ones = int(img_b.sum() - rate/100.0 * img_b.numel())\n    vec_b = img_b.flatten()\n    vec_b[vec_b.nonzero()[:res_ones]] = 0\n    return vec_b.view(img_b.shape)\n\ndef add_surr(img,expan_r):\n    img_shape = np.array(img.shape)\n    expan_img = np.zeros(img_shape*expan_r)\n    expan_img[expan_r//2::expan_r,expan_r//2::expan_r] = img\n    return expan_img\n\ndef expand_pixels(img, expan_r):\n    img_temp = torch.repeat_interleave(img, expan_r, dim=0)\n    return torch.repeat_interleave(img_temp, expan_r, dim=1)\n\ndef Add_frame(pic, frame_px_value):\n    \n    frame = torch.zeros(pic.shape[0]+40, pic.shape[1]+40, dtype=pic.dtype)\n    frame[[0,-1],:] = frame_px_value\n    frame[:,[0,-1]] = frame_px_value\n    frame[20:-20, 20:-20] = pic\n    \n    return frame\n```\n\n# Correction Mask\n\n\n```python\nf_list = []\nfor f in os.listdir(saveDataPath):\n    if f.endswith('.pkl'):\n        f_list.append(f)\nf_list\n```\n\n\n\n\n    ['phonemask_blk600x600_antiatt_phone_mask_onsite_lb640_1_1012_092948.bmp.pkl',\n     'phonemask_blk600x600_antiatt_phone_mask_raw_1012_092948.pkl',\n     'phonemask_blk720x720_antiatt_phone_mask_onsite_lb450_1_1015_233224.bmp.pkl',\n     'phonemask_blk720x720_antiatt_phone_mask_raw_1015_233224.pkl']\n\n\n\n\n```python\ndef im_maxmin(img):\n    plt.figure()\n    plt.imshow(img)\n    plt.colorbar()\n    plt.title(f\"max/min = {img.max():.1f}/{img.min():.1f} = {img.max()/img.min():.2f}\")\n    plt.xlabel(f\"std/mean = {img.std():g}/{img.mean():g} = {img.std()/img.mean():g}\")\n    plt.show()\n```\n\n\n```python\nimport joblib\nmaskPath = saveDataPath\nmaskName = \"phonemask_blk720x720_antiatt_phone_mask_onsite_lb450_1_1015_233224.bmp.pkl\"\nmask_str = \"onsite\"\n# maskName = \"blk600x600_antiatt_phone_mask_raw_0911_142600.bmp\"\n# mask_str = \"rawmask\"\nphone_mask = joblib.load(saveDataPath / maskName)\n# if len(mask.shape)==3:\n#     mask = mask[:,:,1]\nphone_mask\nim_maxmin(phone_mask)\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:5: RuntimeWarning: divide by zero encountered in double_scalars\n      \"\"\"\n\n\n\n```python\nexpan_r = 5\nx_norm_expan = torch.repeat_interleave(torch.ones(28, 28), expan_r, dim=0)\nx_norm_expan = torch.repeat_interleave(x_norm_expan, expan_r, dim=1)\nx_norm_embedded = CenterEmbedding(x_norm_expan, torch.zeros(1920, 1080))\nsub_phone_mask = phone_mask * x_norm_embedded.numpy()\nsub_phone_mask = sub_phone_mask / sub_phone_mask.max()\nplt.figure()\nplt.imshow(sub_phone_mask)\nplt.show()\n```\n\n# Definition of the Neural Network\n\n\n```python\n\"\"\" Define digitized fully connected layers \"\"\"\n\n# Definition of an in-place digitization function.\ndef Digitize(tensor, quant_mode='det', levels=16, min_val=None, max_val=None):\n    if not min_val and not max_val:\n        min_val, max_val = tensor.min().item(), tensor.max().item()\n    tensor.clamp_(min_val, max_val).add_(-1*min_val).mul_(levels-1).div_(max_val-min_val)\n    if quant_mode == \"det\": \n        tensor.round_()\n    elif quant_mode == \"rand\":\n        tensor.add_(torch.rand(tensor.size(), device=tensor.device).add_(-0.5)).round_()\n    tensor.mul_(max_val-min_val).div_(levels-1).add_(min_val)\n    return tensor\n\nclass DigitizeLinear(nn.Linear):\n\n    def __init__(self,  *kargs, a_quant_mode=\"det\", w_quant_mode=\"det\", a_quant_levels=16, w_quant_levels=32, running_weight=0.001, **kwargs):\n        super(DigitizeLinear, self).__init__(*kargs, **kwargs)\n        self.act_quant_mode = a_quant_mode\n        self.weight_quant_mode = w_quant_mode\n        self.register_buffer(\"act_quant_levels\", torch.tensor(a_quant_levels))\n        self.register_buffer(\"weight_quant_levels\", torch.tensor(w_quant_levels))\n        self.register_buffer(\"running_weight\", torch.tensor(running_weight)) \n        self.register_buffer(\"running_min\", None)\n        self.register_buffer(\"running_max\", None)\n\n    def forward(self, input):\n\n        if not self.weight_quant_mode is None: # Set a flag to control weight digitization.\n            if not hasattr(self.weight,'org'):\n                self.weight.org=self.weight.data.clone()\n            self.weight.data=Digitize(self.weight.data, quant_mode=self.weight_quant_mode, levels=self.weight_quant_levels)\n\n        if not self.bias is None:\n            self.bias.org=self.bias.data.clone()    \n        out = nn.functional.linear(input, self.weight, bias=self.bias)\n\n        if not self.act_quant_mode is None: # A flag to control output digitization. \n            if self.training: # Update the running average of min and max only during training\n                with torch.no_grad():\n                    if not self.running_min and not self.running_max:\n                        self.running_min, self.running_max = out.min(), out.max()\n                    self.running_min = (1-self.running_weight) * self.running_min + self.running_weight * out.min()\n                    self.running_max = (1-self.running_weight) * self.running_max + self.running_weight * out.max()\n            out.data=Digitize(out.data, quant_mode=self.act_quant_mode, levels=self.act_quant_levels, min_val=self.running_min, max_val=self.running_max)\n    \n        return out\n```\n\n\n```python\n\"\"\" Define a generic QAT MLP structure (including perceptron) \"\"\"\n\nclass Net(nn.Module):\n    def __init__(self, Nunits, **kwargs):\n        super().__init__()\n        self.fcs = nn.ModuleList([DigitizeLinear(i,j,**kwargs) for i, j in zip(Nunits[:-1], Nunits[1:])])\n\n    def forward(self, X):\n        X = X.view(X.size(0), -1)\n        for i, fc in enumerate(self.fcs):\n            X = fc(X)\n            if fc is not self.fcs[-1]:\n                X = F.relu(X)\n        return X\n    \n    def set_digitize_config(self, a_quant_mode, w_quant_mode, a_quant_levels, w_quant_levels):\n        for fc in self.fcs:\n            fc.act_quant_mode = a_quant_mode\n            fc.weight_quant_mode = w_quant_mode\n            fc.act_quant_levels = torch.tensor(a_quant_levels)\n            fc.weight_quant_levels = torch.tensor(w_quant_levels)\n```\n\n\n```python\n\"\"\" Load the trained model \"\"\"\n\ndevice = \"cpu\"\n\nmodel = Net([784, 100, 100, 10])\nfor l in model.fcs:\n    l.running_min = torch.tensor(0.0)\n    l.running_max = torch.tensor(0.0)\nmodel_ckpt = torch.load(\"./RA_4bit_H2_100_100_lr_0.043_0.50_m_0.87_wep_6_randActDigi_v80_ep97.pt\", map_location=device)\nmodel_state_dict = model_ckpt[\"model_state_dict\"]\nmodel.load_state_dict(model_state_dict)\nmodel.to(device)\nmodel.eval()\n```\n\n\n\n\n    Net(\n      (fcs): ModuleList(\n        (0): DigitizeLinear(in_features=784, out_features=100, bias=True)\n        (1): DigitizeLinear(in_features=100, out_features=100, bias=True)\n        (2): DigitizeLinear(in_features=100, out_features=10, bias=True)\n      )\n    )\n\n\n\n\n```python\n\"\"\" Construct dataloaders \"\"\"\n\ntrainID_range = range(200) # ID of the samples to be passed through the NN\n\n# Import the test data loaders\nkwargs = {'num_workers': 1, 'pin_memory': True} if True else {}\n\ndata_mnist_test = datasets.MNIST('../ML_data', \n                                 train=False, \n                                 transform=transforms.Compose([transforms.ToTensor()]))\n\n# Remember to set the batch size to the length of train ID range, or the dataloader will draw sample one by one.\nsubset_data_loader = torch.utils.data.DataLoader(data_mnist_test, \n                                           batch_size=int(max(trainID_range)+1), \n                                           shuffle=False, **kwargs)\n\n# Remember to set the batch size to the length of train ID range, or the dataloader will draw sample one by one.\ntest_loader = torch.utils.data.DataLoader(data_mnist_test, \n                                           batch_size=1, \n                                           shuffle=False,  **kwargs)\n```\n\n# Notes on ONN Forward Propagation Implementation (Rev. 3)\n\nThe update equation from one neuron layer to the next:\n\n\\begin{equation}\nx_{i}^{L+1} = \\sigma(\\sum_{j}^N{W_{ij}^{L} x_{j}^{L}+b_i^{L}})    \n\\end{equation}\n\nwhere $x_j^L$ is the activation of neuron $j$ in layer $L=0,1,..$.\n\nSince the pixel values in an ONN are intensity encoded, including inputs, activations, and weights, the update equation needs to be modified such that the matrices and vectors to be loaded onto the ONN contain only non-negative numbers. In fact, the possible range of matrix and vector entries is actually limited to positive values, since the phone and SLM pixel values cannot infinitely approach zero in reality, due to hardware limitations. The following framework deals with the most general case where both phone and SLM pixel values cannot be extinguished to zero. If reality, if the resolution permits, the expression can be significantly simplified if either phone or SLM pixels can reach zero within the demanded accuracy.\n\nThe update equation is first rewritten into a vector form to facilitate the following discussion:\n\n\\begin{equation}\nX^{L+1} = \\sigma({W^{L} X^{L} + B^{L}})    \n\\end{equation}\n\nA note on symbol convention: any lower case letter represents a column vector (e.g., $b$, $x$); any captital letter represents a matrix (e.g., $W$, and $X$ actually indicates a batch of data $X = [x_0, x_1, ..., x_{B-1}]$); columns and rows of a matrix is represented in Python indexing convention (i.e., $W[,j]$ and $W[i,]$); element at row $i$ and column $j$ of matrix $W$ is written as $W[i,j]$ instead of $W_{ij}$; the $i$th element in vector a vector is also indicated with Python indexing convention (e.g., $x[i]$ instead of $x_i$). The superscript $L$ indicating the layer of NN is dropped here and below as long as it does not cause any confusion. \n\nTherefore, $W^L[i,j]$ is the weight from neuron i in layer L to neuron j in layer L+1, $X^L[j,k]$ is the actication of neuron j of data batch index k, $B^L[i,k]$ is the bias for neuron i in layer L.\n\nEach element in a row $W[i,]$ can be linearly mapped from interval $[\\text{min}(W[i,]), \\text{max}(W[i,])]$ to $[I_\\text{min}, I_\\text{max}]$, with $I_\\text{max}>I_\\text{min} \\geq 0$. More explicitely, the resultant matrix $\\tilde{W}$ is related to $W$ with the relation:\n\n\\begin{equation}\nW = \\hat{K}\\tilde{W} + \\hat{D}\\mathbb{1}\n\\end{equation}\n\nwhere\n\\begin{equation}\n\\hat{K}=\\frac{1}{I_\\text{max}-I_\\text{min}}diag\\{\\Delta W_i = \\text{max}(W[i,]) - \\text{min}(W[i,])\\}, \n\\hat{D} = \\frac{1}{I_\\text{max}-I_\\text{min}} diag \\{I_\\text{max} \\text{min}(W[i,]) - I_\\text{min} \\text{max}(W[i,]) \\}\n\\end{equation}\nand $\\mathbb{1}$ is all 1 matrix. (Tip: hat implies diagonal matrix; tilde implies the control signal to be sent to a device, such as phone or SLM).\n\n\nThe same transform can be performed on a data batch, which gives $X = \\tilde{X} \\hat{K}_X  +  \\mathbb{1}\\hat{D}_X$ ($\\hat{K}_X$ and $X$ switch position because the definiation of $X$ is transposed from that of $W$.)\n\nNow we can rewrite the update equation as\n\\begin{equation}\nX^{L+1}  = \\sigma( \\hat{K}  \\{\\tilde{W} \\tilde{X}^L\\} \\hat{K}_X  + \\hat{D} \\{\\mathbb{1} \\tilde{X}^L\\} \\hat{K}_X  + \\hat{K} \\{\\tilde{W}\\mathbb{1}\\}\\hat{D}_X + \\hat{D} \\mathbb{1}\\mathbb{1} \\hat{D}_X + b)\n\\end{equation}\n\n\nNote that the matrix products in curly brackets are to be measured expiermentally from the ONN output, and the other quantities are computed once and stored.\n\n\nThe reason to rewrite the update equation in this form is to carry out *each* inner product computation at the full pixel resolution of the smartphone and SLM. The matrices and vectors are always normalized to cover the entire dynamic range of the devices. The normalization factor is stored and later re-applied to the value readout from the ONN to recover the actual numerical value. \n\n\nMore specifically, the passing of NN activation from one layer to the next can be summarized as the following steps:\n1. Normalize $W$ to $\\tilde{W}$, which needs to be done only once for a trained NN and takes $O(MN)$ operations. \n2. Normalize $X$ to $\\tilde{X}$, which needs to be done for every input and layer and takes a total of $NBL$ multiplications. However, these operations can be waived if the phone pixel has high enough bit depth. Since the activations are usually non-negative numbers, it is possible to represent them with pixel intensity without any pre-processing.\n3. Load $\\tilde{X}$ to the phone to control pixel intensity and $\\tilde{W}$ to SLM to control transimission. In this way, $\\tilde{W}$ and $\\tilde{X}$ are both represented with the full resolutin of the devices.\n4. Measure the total pixel value in a region of interest that corresponds to the inner product $\\tilde{W}[i,]\\tilde{X}[,j]$ (read: the input to neuron $i$ for the data batch index $j$) in the captured camera image. In the ideal case, this signal can be measured by a single-pixel detector.\n5. Use the calibration model to find $\\tilde{W}[i,]\\tilde{X}[,j]$ based on the integrated pixel value in the regions of interest, obtained in step (4). \n6. After reading out all the entries of $\\tilde{W}\\tilde{X}$ (W_til_X_til), multiply it with $\\hat{D}$ and $\\hat{D_X}$ digitially, which were obtained in step (1) and (2).\n7. Derive $\\mathbb{1} \\tilde{X}$ (sum_X_til) and $\\tilde{W}\\mathbb{1}$ (sum_W_til) following similar steps as (5) and (6). Essentially they are just special cases of $\\tilde{W}\\tilde{X}$ with either $\\tilde{W} = \\mathbb{1}$ or $\\tilde{X} = \\mathbb{1}$.\n8. Add the computed terms $\\hat{K}\\tilde{W}\\tilde{X}\\hat{K}_X$ (Delta_W_Delta_X), $\\hat{D}\\mathbb{1}\\tilde{X}\\hat{K}_X$ (Offset_W_Delta_X),  $\\hat{K}\\tilde{W}\\mathbb{1}\\hat{D}_X$ (Delta_W_Offset_X), $\\hat{D} \\mathbb{1}\\mathbb{1}\\hat{D}_X$ (Offset_W_Offset_X), and $b$ digitally, and then apply the nonlinear activation function $\\sigma$ to obtain the activations of neurons.\n\n\n\n\n```python\n\"\"\"Auxilitary functions for simulating activation propation in ONN\"\"\"\n\ndef digitize(x, levels=8, min_val=None, max_val=None):\n    \"\"\"\n    digitize activations into the discrete steps, by rounding to the closest level.\n    levels: specifies the number of total discrete levels.\n    min_val: the x value to be mapped to the lowest level\n    max_val: the x value to be mapped to the highest level\n    \"\"\"\n\n    if not min_val and not max_val:\n        min_val, max_val = x.min(), x.max()\n    x = (levels-1)*(x - min_val)/(max_val-min_val)\n    x = x.round()\n    x = torch.min(torch.max(x, torch.zeros_like(x)), torch.ones_like(x)*(levels-1))\n    x = x*(max_val-min_val)/(levels-1) + min_val\n    return x\n\ndef Matrix_Linear_Mapping(W, target_interval):\n    \"\"\"\n    Transform each column of W with the following linear transform: \n    Argument target_interval=[a,b] specifies the lower and upper bound a and b.\n    The minimum of each column of W will be mapped to a, and the maximum of each W column mapped to b.\n    The rest of elements in the column are mapped in-between a and b with linear interporlation.\n    Such operation is repeated for each column individually.\n    \"\"\"\n    \n    W = W.type(torch.double)\n    W_mins, _ = torch.min(W, dim=0) \n    W_maxs, _ = torch.max(W, dim=0)\n    Delta_I = float(target_interval[1] - target_interval[0])\n    Delta_W = W_maxs - W_mins\n    K_W = torch.diag(Delta_W/Delta_I)\n    D_W = target_interval[1]*W_mins - target_interval[0]*W_maxs\n    offset = torch.mm(torch.repeat_interleave(D_W.view(1,-1), W.shape[0],dim=0), torch.diag(1/Delta_W))\n    W_til = torch.mm(W, torch.diag(Delta_I/Delta_W)) - offset\n    \n    return (W_til, K_W, torch.diag(D_W)/Delta_I)\n    \n\ndef ONN_layer_prop(layer, W_transform, X_transform, W_digitize_func=None, X_digitize_func=None, Act_digitize_func=None,  X=None,\n                     W_til_X_til=None, sum_W_til=None, sum_X_til=None):\n    \"\"\"\n    Forward propagate a batch of data for one layer.\n\n    layer: of type torch.nn.module, the layer to propagate the current batch of data through. Both W and b are derived from layer.\n    W_transform: the mapping from the W stored in layer to the control value to be applied to SLM.\n    X_transform: the mapping from the activation values stored in X to the control value to be applied to the smartphone.\n    Act_digitize_func: The function for digitizing the output activation. No digitization is performed if None is given.\n    W_digitize_func: The function for digitizing weight matrix W before the forward propagation. \n                     No digitization is performed if None is assigned to W_digitize_func as default.\n    X_digitize_func: The function for digitizing the batch data X before the forward propagation. \n                     No digitization is performed if None is assigned to X_digitize_func as default.\n    X: Inputs to the current NN layer. \n       If X is not given, an identity matrix is assigned to X as default, such that the W_til_X_til returned by the function equals W_til.\n       X.shape = [batch size, current NN layer width]\n    W: weight matrix derived from layer. W.shape = [current NN layer width, next NN layer size]\n    b: bias vector. b.shape = [next NN layer width]\n    \n    When no digitization is performed on W, X, or Wx+b, only linear stretching is performed on W and X, and the output of the function is \n    almost identical to the results obtained by prop(layer).\n    \"\"\"\n    \n    W = layer.weight.data.t()\n        \n    # Normalize W \n    (W_til, K_W, D_W) = W_transform(W)\n    \n    if X is None: # If X is not given, make it an identity matrix.\n        X = torch.eye(W.shape[0])\n        (X_til, K_X, D_X) = Matrix_Linear_Mapping(X, [0,1])\n    else: # Normalize X\n        (X_til, K_X, D_X) = X_transform(X.t())\n        (X_til, K_X, D_X) = (X_til.t(), K_X.t(), D_X.t())\n    \n    if W_digitize_func is not None:\n        W_til = W_digitize_func(W_til)\n        \n    if X_digitize_func is not None:\n        X_til = X_digitize_func(X_til)\n        \n    W_til_max = W_til[:,0].max()\n    X_til_max = X_til[0,:].max()\n    \n    # First simulate the three measurables from the ONN (defined in Notes on ONN Forward Propagation Implementation (Rev. 3)):\n    if W_til_X_til is None:\n        W_til_X_til = torch.mm(X_til, W_til) # tilde{WX} \n    if sum_X_til is None:\n        sum_X_til = torch.mm(X_til, torch.ones_like(W_til)) * W_til_max # sum(tilde{X[j,:]}), aka the sum of all activations of batch index j.   \n    if sum_W_til is None:\n        sum_W_til = torch.mm(torch.ones_like(X_til), W_til) * X_til_max# sum(tilde{W[:,i]}), aka the sum of all weights into neuron i.\n    \n    # The following terms are defined in Notes on ONN Forward Propagation Implementation (Rev. 3)\n    Delta_W_Delta_X = torch.mm(torch.mm(K_X, W_til_X_til), K_W) \n    Delta_W_Offest_X = torch.mm(torch.mm(K_X, sum_X_til), D_W) / W_til_max\n    Offset_W_Delta_X = torch.mm(D_X, torch.mm(sum_W_til, K_W)) / X_til_max\n    Offset_W_Offset_X = torch.mm(D_X, torch.mm(torch.ones_like(W_til_X_til)*W_til.shape[0], D_W)) \n    \n    Wx = Delta_W_Delta_X + Delta_W_Offest_X + Offset_W_Delta_X + Offset_W_Offset_X  # Wx\n    Wx_b = Wx + torch.repeat_interleave(layer.bias.view(1,-1), W_til_X_til.shape[0], dim=0).type(torch.double) # Wx+b\n    if Act_digitize_func is not None:\n        Wx_b = Act_digitize_func(Wx_b) # digitize(Wx+b)\n    a = F.relu(Wx_b) # ReLU(digitize(Wx+b))\n\n    return {\"norm(W)norm(X)\": W_til_X_til, \"sum(norm(X))\": sum_X_til, \"sum(norm(W))\": sum_W_til, \"Wx\": Wx, \"Wx+b\": Wx_b, \"a\": a}\n```\n\n\n```python\n# Calculate the ground truth of activations of each layer \n# by Propagating each test sample through the trained NN and record activation of each layer.\nimport pandas\n\nX, data_labels = next(iter(subset_data_loader))\nX = X.view(X.size(0), -1)\nX0 = X\n\ndf_layer = {}\n\n# Define the transform and quantization functions for all layers:\nW_transform = lambda W: Matrix_Linear_Mapping(W, [5,2**8-1])\nX_transform = lambda X: Matrix_Linear_Mapping(X, [0,1000-1])\nW_digitize = lambda W: Digitize(W.clone(), levels=2**8-5) # levels of quantization for W\nX_digitize = lambda X: Digitize(X.clone(), levels=1000) # levels of quantization for X\n# One very strange thing is that you cannot lambda function dictionary\n\nfor l, layer in enumerate(model.fcs):\n    # Calculate the ground truth activation by passing through one layer\n    layer.act_quant_mode=None\n    layer.weight_quant_mode=None\n    X0 = F.relu(layer(X0))\n    \n    # Propagate the batch for one layer\n    Act_digitize = lambda X: Digitize(X.clone(), levels=2**4, min_val=layer.running_min.item(), max_val=layer.running_max.item()) # levels of quantization for y=Wx+b\n    results = ONN_layer_prop(layer, W_transform, X_transform, \\\n                             W_digitize_func=W_digitize, X_digitize_func=X_digitize, Act_digitize_func=Act_digitize, X=X)    \n    X = results[\"a\"] # The activation of the current layer is the input to the next layer. \n    \n    results[\"a_true\"] = X0\n    df = {}\n    for k in results.keys():\n        df[k] = pandas.DataFrame(results[k].detach().numpy()).stack(level=-1)\n    df_layer[l] = pandas.concat(df, axis=1)\n        \n# Concatenate the df for each sample into an even larger one to include all the samples spcified.    \ndf_all_acts = pandas.concat(df_layer, axis=0, \\\n                            keys=df_layer.keys(), names=[\"layer\", \"test_ID\", \"output node\"])\ndf_all_acts.index = df_all_acts.index.swaplevel(0,1)\n```\n\n\n```python\ndf_all_acts\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th></th>\n      <th>norm(W)norm(X)</th>\n      <th>sum(norm(X))</th>\n      <th>sum(norm(W))</th>\n      <th>Wx</th>\n      <th>Wx+b</th>\n      <th>a</th>\n      <th>a_true</th>\n    </tr>\n    <tr>\n      <th>test_ID</th>\n      <th>layer</th>\n      <th>output node</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">0</th>\n      <th rowspan=\"5\" valign=\"top\">0</th>\n      <th>0</th>\n      <td>7435548.0</td>\n      <td>18435480.0</td>\n      <td>101575323.0</td>\n      <td>-15.719175</td>\n      <td>-15.587848</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>9019478.0</td>\n      <td>18435480.0</td>\n      <td>99886014.0</td>\n      <td>-3.035051</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>9160499.0</td>\n      <td>18435480.0</td>\n      <td>95635269.0</td>\n      <td>-1.905754</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>9690888.0</td>\n      <td>18435480.0</td>\n      <td>101176722.0</td>\n      <td>2.341606</td>\n      <td>5.428436</td>\n      <td>5.428436</td>\n      <td>2.607136</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>11035015.0</td>\n      <td>18435480.0</td>\n      <td>94579326.0</td>\n      <td>13.105385</td>\n      <td>12.433863</td>\n      <td>12.433863</td>\n      <td>12.107492</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <th>...</th>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">199</th>\n      <th rowspan=\"5\" valign=\"top\">2</th>\n      <th>5</th>\n      <td>596998.0</td>\n      <td>2243745.0</td>\n      <td>10846143.0</td>\n      <td>-502.093804</td>\n      <td>-515.057654</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>604275.0</td>\n      <td>2243745.0</td>\n      <td>9649341.0</td>\n      <td>-495.412649</td>\n      <td>-515.057654</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>1273638.0</td>\n      <td>2243745.0</td>\n      <td>10318671.0</td>\n      <td>119.142521</td>\n      <td>94.972668</td>\n      <td>94.972668</td>\n      <td>101.693199</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>1021207.0</td>\n      <td>2243745.0</td>\n      <td>12271716.0</td>\n      <td>-112.619283</td>\n      <td>-108.370772</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>682060.0</td>\n      <td>2243745.0</td>\n      <td>11444544.0</td>\n      <td>-423.996730</td>\n      <td>-413.385933</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n  </tbody>\n</table>\n<p>42000 rows \u00d7 7 columns</p>\n</div>\n\n\n\n\n```python\nprint(data_labels[50])\ndf_all_acts.loc[(50,0)]\n```\n\n    tensor(6)\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:2: PerformanceWarning: indexing past lexsort depth may impact performance.\n      \n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>norm(W)norm(X)</th>\n      <th>sum(norm(X))</th>\n      <th>sum(norm(W))</th>\n      <th>Wx</th>\n      <th>Wx+b</th>\n      <th>a</th>\n      <th>a_true</th>\n    </tr>\n    <tr>\n      <th>output node</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>10328027.0</td>\n      <td>20142450.0</td>\n      <td>101575323.0</td>\n      <td>0.475091</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>10031575.0</td>\n      <td>20142450.0</td>\n      <td>99886014.0</td>\n      <td>-1.898899</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>11218257.0</td>\n      <td>20142450.0</td>\n      <td>95635269.0</td>\n      <td>7.604060</td>\n      <td>5.428436</td>\n      <td>5.428436</td>\n      <td>6.597994</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>11818030.0</td>\n      <td>20142450.0</td>\n      <td>101176722.0</td>\n      <td>12.407047</td>\n      <td>12.433863</td>\n      <td>12.433863</td>\n      <td>12.708588</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>9299017.0</td>\n      <td>20142450.0</td>\n      <td>94579326.0</td>\n      <td>-7.765229</td>\n      <td>-8.582420</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>95</th>\n      <td>8049976.0</td>\n      <td>20142450.0</td>\n      <td>105060834.0</td>\n      <td>-17.767560</td>\n      <td>-15.587848</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>96</th>\n      <td>9271061.0</td>\n      <td>20142450.0</td>\n      <td>97347555.0</td>\n      <td>-7.989101</td>\n      <td>-8.582420</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>97</th>\n      <td>10241632.0</td>\n      <td>20142450.0</td>\n      <td>106398495.0</td>\n      <td>-0.216761</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>98</th>\n      <td>9954893.0</td>\n      <td>20142450.0</td>\n      <td>100877022.0</td>\n      <td>-2.512969</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>99</th>\n      <td>11442822.0</td>\n      <td>20142450.0</td>\n      <td>97679223.0</td>\n      <td>9.402378</td>\n      <td>5.428436</td>\n      <td>5.428436</td>\n      <td>8.418477</td>\n    </tr>\n  </tbody>\n</table>\n<p>100 rows \u00d7 7 columns</p>\n</div>\n\n\n\n# Generate Phone and SLM Images\n\n\n```python\nL = 2\nif L > 0:\n    df_hidden_layers = {}\n    for l in range(L):\n        df_hidden_layers[l] = pandas.read_hdf((resultPath / f\"fc{l}_acts_ID_130_to_200_float_2pcts.h5\").as_posix(), f\"fc{l}_acts\")\n    \ndf_measured_acts = pandas.concat(df_hidden_layers, axis=0, \\\n                            keys=df_hidden_layers.keys(), names=[\"layer\", \"test_ID\", \"output node\"])\ndf_measured_acts.index = df_measured_acts.index.swaplevel(0,1)\ndf_measured_acts\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th></th>\n      <th>fcs.0.sim</th>\n      <th>ground_truth</th>\n      <th>fcs.0</th>\n      <th>fcs.1.sim</th>\n      <th>fcs.1</th>\n    </tr>\n    <tr>\n      <th>test_ID</th>\n      <th>layer</th>\n      <th>output node</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">130</th>\n      <th rowspan=\"5\" valign=\"top\">0</th>\n      <th>0</th>\n      <td>-2.323618</td>\n      <td>-1.576992</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>-8.439739</td>\n      <td>-8.582420</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>-2.559680</td>\n      <td>-1.576992</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>-4.687803</td>\n      <td>-1.576992</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>-0.305664</td>\n      <td>-1.576992</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <th>...</th>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">199</th>\n      <th rowspan=\"5\" valign=\"top\">1</th>\n      <th>95</th>\n      <td>NaN</td>\n      <td>-184.172670</td>\n      <td>NaN</td>\n      <td>-254.880539</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>96</th>\n      <td>NaN</td>\n      <td>-150.970133</td>\n      <td>NaN</td>\n      <td>-230.141769</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>97</th>\n      <td>NaN</td>\n      <td>-18.159985</td>\n      <td>NaN</td>\n      <td>-109.593086</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>98</th>\n      <td>NaN</td>\n      <td>15.042552</td>\n      <td>NaN</td>\n      <td>-33.087898</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>99</th>\n      <td>NaN</td>\n      <td>-150.970133</td>\n      <td>NaN</td>\n      <td>-192.134460</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>14000 rows \u00d7 5 columns</p>\n</div>\n\n\n\n\n```python\n\"\"\" Generate the weight images to be applied to SLM and save them. \"\"\"\n# Pre-process the SLM weight matrix by shifting all elements to non-negative.\n\nimport numpy as np\nfrom utils.helper_functions import ConvertPhoneImageToSLMImage, NormalizeWeights, CenterEmbedding\n\n# Indicate the current NN layer (the 1st layer has index 0)\nexpan_r = 9+2\n\n# Convert weight matrix to SLM control values using EXACTLY the same sequence of functions as in ONN_layer_prop()\nW = model.fcs[L].weight.data.t()\nW_til,_,_ = W_transform(W)\nW_norm = W_digitize(W_til).t()\nW_norm = W_norm.round().type(torch.uint8)\nblkIdx = Wrap_vec_to_square(torch.tensor(df_measured_acts.index.get_level_values(level=\"output node\").unique().values))\n\nslm_weights_numpy = {}\n\nfor i in range(W_norm.size(0)):\n    # Add a frame for alignment, and embed in a canvas of phone display size\n    w_norm_orig = torch.cat((W_norm[i,:],torch.tensor([0])))[blkIdx]\n    w_norm_expan = torch.repeat_interleave(w_norm_orig, expan_r, dim=0)\n    w_norm_expan = torch.repeat_interleave(w_norm_expan, expan_r, dim=1)\n    w_norm_embedded = CenterEmbedding(w_norm_expan, torch.zeros(1920, 1080, dtype=torch.uint8))\n    w_norm_slm = ConvertPhoneImageToSLMImage(w_norm_embedded, 1.0) # Convert the phone image to SLM image.\n\n    # Save the SLM patterns to image files.\n    w_norm_path = slmWeightPath / (f\"SLM_MLP_{expan_r}x_fc{L}_w{i}.bmp\")\n    w_norm_slm.save(w_norm_path.as_posix(), format = 'bmp') # PIL.Image.save can be saved as 8-bit greyscale bmp\n    \nw_norm_embedded = CenterEmbedding(torch.ones_like(w_norm_expan)*255, torch.zeros(1920, 1080, dtype=torch.uint8))\nw_norm_slm = ConvertPhoneImageToSLMImage(w_norm_embedded, 1.0) # Convert the phone image to SLM image.\n\n# Save the SLM patterns to image files.\nw_norm_path = slmWeightPath / (f\"SLM_MLP_{expan_r}x_fc{L}_wsum.bmp\")\nw_norm_slm.save(w_norm_path.as_posix(), format = 'bmp') # PIL.Image.save can be saved as 8-bit greyscale bmp\n    \n# Plot w_kaleidoscope \nprint(\"The normalized weight matrix to be applied on the SLM looks like below:\")\nfig, ax = plt.subplots()\nim = ax.imshow(w_norm_slm)\nfig.colorbar(im, ax=ax)\nplt.show()\n```\n\n    The normalized weight matrix to be applied on the SLM looks like below:\n\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n\n```python\n\"\"\" Generate the images to be displayed on the phone and save them. \"\"\"\n\ninput_data, data_labels = next(iter(subset_data_loader))\ninput_data = input_data.view(X.size(0), -1)\n\nsubPath = phoneImagePath /  (f\"fc{L}_2pcts\" )\nif not os.path.exists(subPath.as_posix()):\n    os.makedirs(subPath.as_posix())\n\npx_margin = 1\nblankImage = torch.zeros(3, 1920, 1080, dtype=torch.uint8)\n\nfor i, batchIdx in enumerate(range(130, 200)):\n    \n    # x is the output of the previous layer L-1 (L>0) or the input data (L==0).\n    if L > 0:\n        x = torch.tensor(df_measured_acts[\"fcs.1\"].loc[batchIdx, L-1, :].values)\n        #x = torch.tensor(df_all_acts[\"a_true\"].loc[batchIdx, L-1, :].values) # test mode\n    elif L == 0:\n        x = input_data[batchIdx,:]\n    \n    # Normalize each x to its max and min and scale to 7 bit to match the dynamical range of the phone.\n    # The operations here are performed EXACTLY the same as in ONN_layer_prop()\n    x_til,_,_ = X_transform(x.view(-1,1))\n    x_norm = X_digitize(x_til.squeeze()).round().type(torch.long) # round() cannot be omitted for type(torch.long) sometimes work as floor(0)\n    \n    # Add the singla-pixel frame for image alignment.\n    imToPhone = blankImage.clone()\n    x_norm_orig = torch.cat((x_norm,torch.tensor([0])))[blkIdx]\n    x_norm_expan = torch.repeat_interleave(x_norm_orig, expan_r, dim=0)\n    x_norm_expan = torch.repeat_interleave(x_norm_expan, expan_r, dim=1)\n    x_norm_spar = x_norm_expan\n    x_norm_spar[::expan_r,:] = 0\n    x_norm_spar[(expan_r-px_margin)::expan_r,:] = 0\n    x_norm_spar[:,::expan_r] = 0\n    x_norm_spar[:,(expan_r-px_margin)::expan_r] = 0\n    x_norm_embedded = CenterEmbedding(x_norm_spar, blankImage[1,:,:].type(torch.long))\n    imToPhone[1, :, :] = lut_p[x_norm_embedded.type(torch.long)] # no uniformness correction\n    #phone_corr_numpy = lut_p[(x_norm_embedded * sub_phone_mask).type(torch.long)]\n    #imToPhone[1, :, :] = phone_corr_numpy\n\n    # Save the generated image\n    imToPhone_PIL = transforms.ToPILImage()(imToPhone)\n    imToPhone_PIL.save((subPath / f\"test_{expan_r}x_gap2px_MLP_2pcts_fc{L}_digit_{data_labels[batchIdx]}_{batchIdx:05d}.png\").as_posix())\n\n# Generate and save a black image to be displayed on the phone for background and power saving.\nblackImage_PIL = transforms.ToPILImage()(blankImage)\nblackImage_PIL.save((phoneImagePath / \"black.png\").as_posix())\n\nprint(\"The normalized weight matrix to be applied on the SLM looks like below:\")\nfig, ax = plt.subplots()\nim = ax.imshow(imToPhone_PIL)\nfig.colorbar(im, ax=ax)\nplt.show()\n```\n\n    The normalized weight matrix to be applied on the SLM looks like below:\n\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n\n```python\nConvertPhoneImageToSLMImage(imToPhone[1,:,:], 1.0).save((slmWeightPath / \"alignment_check\").as_posix(), format = 'bmp')\n```\n\n# Acquire Data\n\n\n```python\n\"\"\" Set up MPPC experiment scheme. \"\"\"\n\nrepeats = 100\noscope.set_range(6)\noscope.set_offset(2)\noscope_info(oscope)\n```\n\n\n\n\n    {'ID': 'HEWLETT-PACKARD,54845A,US40240103,A.04.50\\n',\n     'x_range': 0.0001,\n     'x_unit': 'SECOND',\n     'y_range': 6.0,\n     'y_unit': 'VOLT',\n     'y_offset': 2.0,\n     'y_bounds': [-1.0, 5.0]}\n\n\n\n\n```python\n\"\"\" Set up the (empty) dataframe table for taking data. \"\"\"\n\nimport pandas\n\nrepeats = 100\ntest_digit_idx = np.arange(200)\nnode_idx = [*range(10), \"sum\", \"bkg\"]\ntime_ranges = [0.0001, ]\n#rowMultiIdx = pandas.MultiIndex.from_product([test_digit_idx, node_idx, time_ranges, np.arange(repeats)], names=[\"test_ID\", \"output_node\", \"time_range\", \"repeats\"])\nrowMultiIdx = pandas.MultiIndex.from_product([node_idx, time_ranges, np.arange(repeats)], names=[\"output_node\", \"time_range\", \"repeats\"])\n#df_volTraces = pandas.DataFrame(index=rowMultiIdx, columns=np.arange(1004))\n\nphoneLoadPath = subPath \nslmLoadPath = slmWeightPath \n\nprint(phoneLoadPath)\nprint(slmLoadPath)\nprint(rowMultiIdx)\n#print(df_volTraces)\n```\n\n    D:\\McMahon lab Dropbox\\peter mcmahon\\tw329\\Experiments\\12_01_20_4bit_randy_aug_MLP_100_100_MPPC\\phone_images\\fc2_2pcts\n    D:\\McMahon lab Dropbox\\peter mcmahon\\tw329\\Experiments\\12_01_20_4bit_randy_aug_MLP_100_100_MPPC\\slm_weights\n    MultiIndex([(    0, 0.0001,  0),\n                (    0, 0.0001,  1),\n                (    0, 0.0001,  2),\n                (    0, 0.0001,  3),\n                (    0, 0.0001,  4),\n                (    0, 0.0001,  5),\n                (    0, 0.0001,  6),\n                (    0, 0.0001,  7),\n                (    0, 0.0001,  8),\n                (    0, 0.0001,  9),\n                ...\n                ('bkg', 0.0001, 90),\n                ('bkg', 0.0001, 91),\n                ('bkg', 0.0001, 92),\n                ('bkg', 0.0001, 93),\n                ('bkg', 0.0001, 94),\n                ('bkg', 0.0001, 95),\n                ('bkg', 0.0001, 96),\n                ('bkg', 0.0001, 97),\n                ('bkg', 0.0001, 98),\n                ('bkg', 0.0001, 99)],\n               names=['output_node', 'time_range', 'repeats'], length=1200)\n\n\n\n```python\n\"\"\" Perform the inference of the trained model with ONN on test digits, and save the data. \"\"\"\n\nimport joblib, pickle, time\n\nexp_time = datetime.now()\nsavePath = resultPath /  (f\"MLP_fc{L}_{expan_r}x_marg_1px_2pcts_MPPC_{exp_time:%m%d_%H%M%S}\")\nprint(savePath)\nif not os.path.exists(savePath.as_posix()):\n    os.makedirs(savePath.as_posix())\n\noscope.instrument.write(\"TIM:RANG 0.0001\")\n\njoblib.dump([oscope_info(oscope),], savePath / 'exp_info.pkl')\ndataFile = pandas.HDFStore((savePath / \"mppc_vol_meas.h5\").as_posix())\n\n# write a black image to the phone to take the background\nblackImage_PIL = Image.open((phoneImagePath / \"black.png\").as_posix())\nblackImage_byte = PIL_to_bytestream(blackImage_PIL)\n\nfor idx in range(130, 200):\n#for idx in range(20):\n    t0 = time.time()\n    # Record background to capture potential voltage bias drift\n    aoab.write(blackImage_byte)\n    #time.sleep(0.5)\n    slmPattern_PIL = Image.open((slmLoadPath / f\"SLM_solid_0.bmp\").as_posix())\n    slm.updateArray((np.array(slmPattern_PIL)).astype('uint8'))\n    time.sleep(0.5)\n    \n    df = pandas.DataFrame(index=rowMultiIdx, columns=np.arange(1004))\n\n    for i in rowMultiIdx.get_level_values(\"repeats\").unique(): \n        trace = oscope.get_waveform()\n        df.loc[(\"bkg\", 0.0001, i), range(len(trace))] = trace\n        time.sleep(0.04)\n    print(f\"time_span=0.0001s, test_ID={idx}, label={data_labels[idx]}, output_node=bkg, voltage={trace.mean()}\")\n        \n    # Load the phone pattern\n    phonePattern_PIL = Image.open((phoneLoadPath / f\"test_{expan_r}x_gap2px_MLP_2pcts_fc{L}_digit_{data_labels[idx]}_{idx:05d}.png\").as_posix())\n    phonePattern_byte = PIL_to_bytestream(phonePattern_PIL)\n    aoab.write(phonePattern_byte)\n    time.sleep(0.5) # Wait for the pattern applied to be stable\n    for n in rowMultiIdx.get_level_values(\"output_node\").unique().drop(\"bkg\"):\n        # refresh the slm pattern\n        slmPattern_PIL = Image.open((slmLoadPath / f\"SLM_MLP_{expan_r}x_fc{L}_w{n}.bmp\").as_posix())\n        slm.updateArray((np.array(slmPattern_PIL)).astype('uint8'))\n        time.sleep(0.5) # Wait for the pattern applied to be stable\n        \n        for i in rowMultiIdx.get_level_values(\"repeats\").unique(): \n            trace = oscope.get_waveform()\n            df.loc[(n, 0.0001, i), range(len(trace))] = trace\n            time.sleep(0.04)\n        print(f\"time_span=0.0001s, test_ID={idx}, label={data_labels[idx]}, output_node={n}, voltage={trace.mean()}\")\n            \n        if n == 9 and idx == 1:\n            print(\"20 s to exit anydesk\")\n            time.sleep(20)  \n            \n    t1 = time.time()\n    print(f\"Time consumed for 1 sample = {t1-t0} s\")\n    t0 = t1\n    dataFile[str(idx)]=df \n    \ndataFile.close()\nprint(\"Finished! Safe to change code now.\")\n```\n\n    D:\\McMahon lab Dropbox\\peter mcmahon\\tw329\\Experiments\\12_01_20_4bit_randy_aug_MLP_100_100_MPPC\\MLP_fc2_11x_marg_1px_2pcts_MPPC_1227_114053\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\IPython\\core\\interactiveshell.py:2878: PerformanceWarning: indexing past lexsort depth may impact performance.\n      raw_cell, store_history, silent, shell_futures)\n\n\n    time_span=0.0001s, test_ID=130, label=6, output_node=bkg, voltage=-0.006759959738701582\n    time_span=0.0001s, test_ID=130, label=6, output_node=0, voltage=0.009698206558823586\n    time_span=0.0001s, test_ID=130, label=6, output_node=1, voltage=0.008337649516761303\n    time_span=0.0001s, test_ID=130, label=6, output_node=2, voltage=0.006151393987238407\n    time_span=0.0001s, test_ID=130, label=6, output_node=3, voltage=0.005393426399677992\n    time_span=0.0001s, test_ID=130, label=6, output_node=4, voltage=0.006217130925506353\n    time_span=0.0001s, test_ID=130, label=6, output_node=5, voltage=0.012744024395942688\n    time_span=0.0001s, test_ID=130, label=6, output_node=6, voltage=0.017599603161215782\n    time_span=0.0001s, test_ID=130, label=6, output_node=7, voltage=0.005928286351263523\n    time_span=0.0001s, test_ID=130, label=6, output_node=8, voltage=0.007575697731226683\n    time_span=0.0001s, test_ID=130, label=6, output_node=9, voltage=0.008573705330491066\n    time_span=0.0001s, test_ID=130, label=6, output_node=sum, voltage=0.03309262916445732\n    Time consumed for 1 sample = 141.21696257591248 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '130'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\pandas\\io\\pytables.py:556: PerformanceWarning: \n    your performance may suffer as PyTables will pickle object types that it cannot\n    map directly to c-types [inferred_type->mixed-integer,key->axis1_level0] [items->None]\n    \n      self.put(key, value)\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\IPython\\core\\interactiveshell.py:3418: PerformanceWarning: \n    your performance may suffer as PyTables will pickle object types that it cannot\n    map directly to c-types [inferred_type->floating,key->block0_values] [items->Int64Index([   0,    1,    2,    3,    4,    5,    6,    7,    8,    9,\n                ...\n                 994,  995,  996,  997,  998,  999, 1000, 1001, 1002, 1003],\n               dtype='int64', length=1004)]\n    \n      exec(code_obj, self.user_global_ns, self.user_ns)\n\n\n    time_span=0.0001s, test_ID=131, label=6, output_node=bkg, voltage=-0.003938246984034777\n    time_span=0.0001s, test_ID=131, label=6, output_node=0, voltage=-0.0023446213454008102\n    time_span=0.0001s, test_ID=131, label=6, output_node=1, voltage=-0.0008336654282175004\n    time_span=0.0001s, test_ID=131, label=6, output_node=2, voltage=-0.001630478072911501\n    time_span=0.0001s, test_ID=131, label=6, output_node=3, voltage=-0.0011503985151648521\n    time_span=0.0001s, test_ID=131, label=6, output_node=4, voltage=-6.474096153397113e-05\n    time_span=0.0001s, test_ID=131, label=6, output_node=5, voltage=0.0018914343090727925\n    time_span=0.0001s, test_ID=131, label=6, output_node=6, voltage=0.002392430556938052\n    time_span=0.0001s, test_ID=131, label=6, output_node=7, voltage=-0.0048177288845181465\n    time_span=0.0001s, test_ID=131, label=6, output_node=8, voltage=9.760964167071506e-05\n    time_span=0.0001s, test_ID=131, label=6, output_node=9, voltage=-0.001352589693851769\n    time_span=0.0001s, test_ID=131, label=6, output_node=sum, voltage=0.006861553527414799\n    Time consumed for 1 sample = 140.6931755542755 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '131'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=132, label=5, output_node=bkg, voltage=-0.0066533866338431835\n    time_span=0.0001s, test_ID=132, label=5, output_node=0, voltage=0.00467529846355319\n    time_span=0.0001s, test_ID=132, label=5, output_node=1, voltage=0.006450199522078037\n    time_span=0.0001s, test_ID=132, label=5, output_node=2, voltage=0.007951195351779461\n    time_span=0.0001s, test_ID=132, label=5, output_node=3, voltage=0.010574700310826302\n    time_span=0.0001s, test_ID=132, label=5, output_node=4, voltage=0.0027260957285761833\n    time_span=0.0001s, test_ID=132, label=5, output_node=5, voltage=0.017033865675330162\n    time_span=0.0001s, test_ID=132, label=5, output_node=6, voltage=0.006096613127738237\n    time_span=0.0001s, test_ID=132, label=5, output_node=7, voltage=0.001071713282726705\n    time_span=0.0001s, test_ID=132, label=5, output_node=8, voltage=0.009194224141538143\n    time_span=0.0001s, test_ID=132, label=5, output_node=9, voltage=0.009290837682783604\n    time_span=0.0001s, test_ID=132, label=5, output_node=sum, voltage=0.028587648645043373\n    Time consumed for 1 sample = 140.75332474708557 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '132'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=133, label=7, output_node=bkg, voltage=-0.006266932003200054\n    time_span=0.0001s, test_ID=133, label=7, output_node=0, voltage=-0.004433267284184694\n    time_span=0.0001s, test_ID=133, label=7, output_node=1, voltage=-0.0018266933038830757\n    time_span=0.0001s, test_ID=133, label=7, output_node=2, voltage=-0.0026125500444322824\n    time_span=0.0001s, test_ID=133, label=7, output_node=3, voltage=-0.001928286743350327\n    time_span=0.0001s, test_ID=133, label=7, output_node=4, voltage=-0.003130478085950017\n    time_span=0.0001s, test_ID=133, label=7, output_node=5, voltage=-0.003263944061473012\n    time_span=0.0001s, test_ID=133, label=7, output_node=6, voltage=-0.00198406376875937\n    time_span=0.0001s, test_ID=133, label=7, output_node=7, voltage=0.0025816732086241245\n    time_span=0.0001s, test_ID=133, label=7, output_node=8, voltage=-0.001129482057876885\n    time_span=0.0001s, test_ID=133, label=7, output_node=9, voltage=-0.0015717130154371262\n    time_span=0.0001s, test_ID=133, label=7, output_node=sum, voltage=0.0024671312421560287\n    Time consumed for 1 sample = 142.97610116004944 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '133'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=134, label=8, output_node=bkg, voltage=-0.007063745055347681\n    time_span=0.0001s, test_ID=134, label=8, output_node=0, voltage=0.005311753135174513\n    time_span=0.0001s, test_ID=134, label=8, output_node=1, voltage=0.005389442201703787\n    time_span=0.0001s, test_ID=134, label=8, output_node=2, voltage=0.006261952221393585\n    time_span=0.0001s, test_ID=134, label=8, output_node=3, voltage=0.007845617830753326\n    time_span=0.0001s, test_ID=134, label=8, output_node=4, voltage=0.005796812474727631\n    time_span=0.0001s, test_ID=134, label=8, output_node=5, voltage=0.005580677650868893\n    time_span=0.0001s, test_ID=134, label=8, output_node=6, voltage=0.0029103585984557867\n    time_span=0.0001s, test_ID=134, label=8, output_node=7, voltage=0.0030866533052176237\n    time_span=0.0001s, test_ID=134, label=8, output_node=8, voltage=0.015442230738699436\n    time_span=0.0001s, test_ID=134, label=8, output_node=9, voltage=0.008116533979773521\n    time_span=0.0001s, test_ID=134, label=8, output_node=sum, voltage=0.023727092891931534\n    Time consumed for 1 sample = 141.7899923324585 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '134'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=135, label=1, output_node=bkg, voltage=-0.00618924293667078\n    time_span=0.0001s, test_ID=135, label=1, output_node=0, voltage=-0.0005667330697178841\n    time_span=0.0001s, test_ID=135, label=1, output_node=1, voltage=0.006971116177737713\n    time_span=0.0001s, test_ID=135, label=1, output_node=2, voltage=-0.0001593624911038205\n    time_span=0.0001s, test_ID=135, label=1, output_node=3, voltage=-0.00042430273606441915\n    time_span=0.0001s, test_ID=135, label=1, output_node=4, voltage=8.466136205242947e-05\n    time_span=0.0001s, test_ID=135, label=1, output_node=5, voltage=-0.0018595617730170488\n    time_span=0.0001s, test_ID=135, label=1, output_node=6, voltage=0.0008167331106960773\n    time_span=0.0001s, test_ID=135, label=1, output_node=7, voltage=0.003261952195316553\n    time_span=0.0001s, test_ID=135, label=1, output_node=8, voltage=0.0028814743272960186\n    time_span=0.0001s, test_ID=135, label=1, output_node=9, voltage=-0.00033067731419578195\n    time_span=0.0001s, test_ID=135, label=1, output_node=sum, voltage=0.01242729090154171\n    Time consumed for 1 sample = 139.57360529899597 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '135'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=136, label=0, output_node=bkg, voltage=-0.005244024097919464\n    time_span=0.0001s, test_ID=136, label=0, output_node=0, voltage=0.01584761030972004\n    time_span=0.0001s, test_ID=136, label=0, output_node=1, voltage=0.002083665458485484\n    time_span=0.0001s, test_ID=136, label=0, output_node=2, voltage=0.005999003536999226\n    time_span=0.0001s, test_ID=136, label=0, output_node=3, voltage=0.004967131651937962\n    time_span=0.0001s, test_ID=136, label=0, output_node=4, voltage=0.005882470402866602\n    time_span=0.0001s, test_ID=136, label=0, output_node=5, voltage=0.008010955527424812\n    time_span=0.0001s, test_ID=136, label=0, output_node=6, voltage=0.008349601179361343\n    time_span=0.0001s, test_ID=136, label=0, output_node=7, voltage=0.008463147096335888\n    time_span=0.0001s, test_ID=136, label=0, output_node=8, voltage=0.005072709172964096\n    time_span=0.0001s, test_ID=136, label=0, output_node=9, voltage=0.00880079623311758\n    time_span=0.0001s, test_ID=136, label=0, output_node=sum, voltage=0.029231075197458267\n    Time consumed for 1 sample = 140.3294596672058 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '136'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=137, label=1, output_node=bkg, voltage=-0.0052260952070355415\n    time_span=0.0001s, test_ID=137, label=1, output_node=0, voltage=-0.0025268925819545984\n    time_span=0.0001s, test_ID=137, label=1, output_node=1, voltage=0.008513943292200565\n    time_span=0.0001s, test_ID=137, label=1, output_node=2, voltage=0.0047051794826984406\n    time_span=0.0001s, test_ID=137, label=1, output_node=3, voltage=0.0014123505679890513\n    time_span=0.0001s, test_ID=137, label=1, output_node=4, voltage=-0.001116533880122006\n    time_span=0.0001s, test_ID=137, label=1, output_node=5, voltage=0.0011972110951319337\n    time_span=0.0001s, test_ID=137, label=1, output_node=6, voltage=6.673305324511603e-05\n    time_span=0.0001s, test_ID=137, label=1, output_node=7, voltage=0.0035806773230433464\n    time_span=0.0001s, test_ID=137, label=1, output_node=8, voltage=0.002546812640503049\n    time_span=0.0001s, test_ID=137, label=1, output_node=9, voltage=0.000565736903809011\n    time_span=0.0001s, test_ID=137, label=1, output_node=sum, voltage=0.014469124376773834\n    Time consumed for 1 sample = 142.83419632911682 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '137'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=138, label=6, output_node=bkg, voltage=-0.006331673823297024\n    time_span=0.0001s, test_ID=138, label=6, output_node=0, voltage=-0.0013356574345380068\n    time_span=0.0001s, test_ID=138, label=6, output_node=1, voltage=-0.0005318725598044693\n    time_span=0.0001s, test_ID=138, label=6, output_node=2, voltage=-0.002659362740814686\n    time_span=0.0001s, test_ID=138, label=6, output_node=3, voltage=-0.003085657488554716\n    time_span=0.0001s, test_ID=138, label=6, output_node=4, voltage=-0.0006623505032621324\n    time_span=0.0001s, test_ID=138, label=6, output_node=5, voltage=-0.0017948206514120102\n    time_span=0.0001s, test_ID=138, label=6, output_node=6, voltage=0.00232768920250237\n    time_span=0.0001s, test_ID=138, label=6, output_node=7, voltage=-0.0012948208022862673\n    time_span=0.0001s, test_ID=138, label=6, output_node=8, voltage=-0.0025129481218755245\n    time_span=0.0001s, test_ID=138, label=6, output_node=9, voltage=-0.005233068019151688\n    time_span=0.0001s, test_ID=138, label=6, output_node=sum, voltage=0.004793824627995491\n    Time consumed for 1 sample = 142.79271364212036 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '138'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=139, label=4, output_node=bkg, voltage=-0.006729083135724068\n    time_span=0.0001s, test_ID=139, label=4, output_node=0, voltage=-0.0026663346216082573\n    time_span=0.0001s, test_ID=139, label=4, output_node=1, voltage=0.000539840548299253\n    time_span=0.0001s, test_ID=139, label=4, output_node=2, voltage=0.0005358565249480307\n    time_span=0.0001s, test_ID=139, label=4, output_node=3, voltage=-0.0021683266386389732\n    time_span=0.0001s, test_ID=139, label=4, output_node=4, voltage=0.0028476098086684942\n    time_span=0.0001s, test_ID=139, label=4, output_node=5, voltage=-0.002203187206760049\n    time_span=0.0001s, test_ID=139, label=4, output_node=6, voltage=-0.003761952044442296\n    time_span=0.0001s, test_ID=139, label=4, output_node=7, voltage=-0.000599601655267179\n    time_span=0.0001s, test_ID=139, label=4, output_node=8, voltage=0.0001952191087184474\n    time_span=0.0001s, test_ID=139, label=4, output_node=9, voltage=-0.003375497879460454\n    time_span=0.0001s, test_ID=139, label=4, output_node=sum, voltage=0.005187251139432192\n    Time consumed for 1 sample = 142.77317118644714 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '139'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=140, label=6, output_node=bkg, voltage=-0.004413346294313669\n    time_span=0.0001s, test_ID=140, label=6, output_node=0, voltage=0.0039671314880251884\n    time_span=0.0001s, test_ID=140, label=6, output_node=1, voltage=0.0030647411476820707\n    time_span=0.0001s, test_ID=140, label=6, output_node=2, voltage=0.0005617530550807714\n    time_span=0.0001s, test_ID=140, label=6, output_node=3, voltage=0.0026603585574775934\n    time_span=0.0001s, test_ID=140, label=6, output_node=4, voltage=0.002095617586746812\n    time_span=0.0001s, test_ID=140, label=6, output_node=5, voltage=0.005095617845654488\n    time_span=0.0001s, test_ID=140, label=6, output_node=6, voltage=0.011499999091029167\n    time_span=0.0001s, test_ID=140, label=6, output_node=7, voltage=-8.864543633535504e-05\n    time_span=0.0001s, test_ID=140, label=6, output_node=8, voltage=-0.0007280874997377396\n    time_span=0.0001s, test_ID=140, label=6, output_node=9, voltage=0.0031862547621130943\n    time_span=0.0001s, test_ID=140, label=6, output_node=sum, voltage=0.015180278569459915\n    Time consumed for 1 sample = 139.64913249015808 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '140'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=141, label=7, output_node=bkg, voltage=-0.006021912209689617\n    time_span=0.0001s, test_ID=141, label=7, output_node=0, voltage=-5.8764864661497995e-05\n    time_span=0.0001s, test_ID=141, label=7, output_node=1, voltage=0.0030079681891947985\n    time_span=0.0001s, test_ID=141, label=7, output_node=2, voltage=0.0015717132482677698\n    time_span=0.0001s, test_ID=141, label=7, output_node=3, voltage=0.0008127490291371942\n    time_span=0.0001s, test_ID=141, label=7, output_node=4, voltage=0.0030687248799949884\n    time_span=0.0001s, test_ID=141, label=7, output_node=5, voltage=0.0017081674886867404\n    time_span=0.0001s, test_ID=141, label=7, output_node=6, voltage=-0.002853585407137871\n    time_span=0.0001s, test_ID=141, label=7, output_node=7, voltage=0.012963146902620792\n    time_span=0.0001s, test_ID=141, label=7, output_node=8, voltage=-0.0007848605164326727\n    time_span=0.0001s, test_ID=141, label=7, output_node=9, voltage=0.006109561771154404\n    time_span=0.0001s, test_ID=141, label=7, output_node=sum, voltage=0.016369521617889404\n    Time consumed for 1 sample = 141.44383764266968 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '141'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=142, label=3, output_node=bkg, voltage=-0.003489044029265642\n    time_span=0.0001s, test_ID=142, label=3, output_node=0, voltage=-0.0013187250588089228\n    time_span=0.0001s, test_ID=142, label=3, output_node=1, voltage=-0.0012499999720603228\n    time_span=0.0001s, test_ID=142, label=3, output_node=2, voltage=0.0009272908209823072\n    time_span=0.0001s, test_ID=142, label=3, output_node=3, voltage=0.0039800796657800674\n    time_span=0.0001s, test_ID=142, label=3, output_node=4, voltage=-0.0032569721806794405\n    time_span=0.0001s, test_ID=142, label=3, output_node=5, voltage=-0.002668326487764716\n    time_span=0.0001s, test_ID=142, label=3, output_node=6, voltage=-0.0043007973581552505\n    time_span=0.0001s, test_ID=142, label=3, output_node=7, voltage=0.00014442235988099128\n    time_span=0.0001s, test_ID=142, label=3, output_node=8, voltage=0.0012330675963312387\n    time_span=0.0001s, test_ID=142, label=3, output_node=9, voltage=0.0006723107071593404\n    time_span=0.0001s, test_ID=142, label=3, output_node=sum, voltage=0.007456175517290831\n    Time consumed for 1 sample = 143.00093126296997 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '142'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=143, label=1, output_node=bkg, voltage=-0.003969123121351004\n    time_span=0.0001s, test_ID=143, label=1, output_node=0, voltage=0.0006762946723029017\n    time_span=0.0001s, test_ID=143, label=1, output_node=1, voltage=0.010885459370911121\n    time_span=0.0001s, test_ID=143, label=1, output_node=2, voltage=0.0024940238799899817\n    time_span=0.0001s, test_ID=143, label=1, output_node=3, voltage=0.0021165339276194572\n    time_span=0.0001s, test_ID=143, label=1, output_node=4, voltage=0.0020976094529032707\n    time_span=0.0001s, test_ID=143, label=1, output_node=5, voltage=-0.000414342648582533\n    time_span=0.0001s, test_ID=143, label=1, output_node=6, voltage=0.0035587649326771498\n    time_span=0.0001s, test_ID=143, label=1, output_node=7, voltage=0.002840637229382992\n    time_span=0.0001s, test_ID=143, label=1, output_node=8, voltage=0.002152390545234084\n    time_span=0.0001s, test_ID=143, label=1, output_node=9, voltage=0.0042888447642326355\n    time_span=0.0001s, test_ID=143, label=1, output_node=sum, voltage=0.011832669377326965\n    Time consumed for 1 sample = 142.3728380203247 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '143'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=144, label=7, output_node=bkg, voltage=-0.00733964191749692\n    time_span=0.0001s, test_ID=144, label=7, output_node=0, voltage=-0.0007878486067056656\n    time_span=0.0001s, test_ID=144, label=7, output_node=1, voltage=0.007036852650344372\n    time_span=0.0001s, test_ID=144, label=7, output_node=2, voltage=0.004127489868551493\n    time_span=0.0001s, test_ID=144, label=7, output_node=3, voltage=0.005478087812662125\n    time_span=0.0001s, test_ID=144, label=7, output_node=4, voltage=0.007064740639179945\n    time_span=0.0001s, test_ID=144, label=7, output_node=5, voltage=-0.0011882471153512597\n    time_span=0.0001s, test_ID=144, label=7, output_node=6, voltage=-0.0031085656955838203\n    time_span=0.0001s, test_ID=144, label=7, output_node=7, voltage=0.013495020568370819\n    time_span=0.0001s, test_ID=144, label=7, output_node=8, voltage=0.0027729084249585867\n    time_span=0.0001s, test_ID=144, label=7, output_node=9, voltage=0.006032868754118681\n    time_span=0.0001s, test_ID=144, label=7, output_node=sum, voltage=0.021497013047337532\n    Time consumed for 1 sample = 142.5978331565857 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '144'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=145, label=1, output_node=bkg, voltage=-0.004660358652472496\n    time_span=0.0001s, test_ID=145, label=1, output_node=0, voltage=0.0018555778078734875\n    time_span=0.0001s, test_ID=145, label=1, output_node=1, voltage=0.013775895349681377\n    time_span=0.0001s, test_ID=145, label=1, output_node=2, voltage=0.002274900209158659\n    time_span=0.0001s, test_ID=145, label=1, output_node=3, voltage=-0.0010079680941998959\n    time_span=0.0001s, test_ID=145, label=1, output_node=4, voltage=0.0020199203863739967\n    time_span=0.0001s, test_ID=145, label=1, output_node=5, voltage=0.0017679281299933791\n    time_span=0.0001s, test_ID=145, label=1, output_node=6, voltage=0.002822709036991\n    time_span=0.0001s, test_ID=145, label=1, output_node=7, voltage=0.002720119431614876\n    time_span=0.0001s, test_ID=145, label=1, output_node=8, voltage=0.004531872924417257\n    time_span=0.0001s, test_ID=145, label=1, output_node=9, voltage=0.004816733300685883\n    time_span=0.0001s, test_ID=145, label=1, output_node=sum, voltage=0.01759462244808674\n    Time consumed for 1 sample = 142.72860383987427 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '145'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=146, label=8, output_node=bkg, voltage=-0.005746015813201666\n    time_span=0.0001s, test_ID=146, label=8, output_node=0, voltage=0.0020179282873868942\n    time_span=0.0001s, test_ID=146, label=8, output_node=1, voltage=0.00022410361270885915\n    time_span=0.0001s, test_ID=146, label=8, output_node=2, voltage=-0.00020517931261565536\n    time_span=0.0001s, test_ID=146, label=8, output_node=3, voltage=0.0026444222312420607\n    time_span=0.0001s, test_ID=146, label=8, output_node=4, voltage=0.000953187292907387\n    time_span=0.0001s, test_ID=146, label=8, output_node=5, voltage=-1.6932350263232365e-05\n    time_span=0.0001s, test_ID=146, label=8, output_node=6, voltage=0.0013824701309204102\n    time_span=0.0001s, test_ID=146, label=8, output_node=7, voltage=0.000523904396686703\n    time_span=0.0001s, test_ID=146, label=8, output_node=8, voltage=0.006905378308147192\n    time_span=0.0001s, test_ID=146, label=8, output_node=9, voltage=0.0036553784739226103\n    time_span=0.0001s, test_ID=146, label=8, output_node=sum, voltage=0.011960159055888653\n    Time consumed for 1 sample = 143.03515791893005 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '146'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=147, label=2, output_node=bkg, voltage=-0.006592629477381706\n    time_span=0.0001s, test_ID=147, label=2, output_node=0, voltage=-0.001467131543904543\n    time_span=0.0001s, test_ID=147, label=2, output_node=1, voltage=-0.003836653660982847\n    time_span=0.0001s, test_ID=147, label=2, output_node=2, voltage=0.002976095536723733\n    time_span=0.0001s, test_ID=147, label=2, output_node=3, voltage=-0.002340637380257249\n    time_span=0.0001s, test_ID=147, label=2, output_node=4, voltage=-0.0008854581392370164\n    time_span=0.0001s, test_ID=147, label=2, output_node=5, voltage=-0.0008525897283107042\n    time_span=0.0001s, test_ID=147, label=2, output_node=6, voltage=-0.003966135438531637\n    time_span=0.0001s, test_ID=147, label=2, output_node=7, voltage=-0.0031294820364564657\n    time_span=0.0001s, test_ID=147, label=2, output_node=8, voltage=-0.0029790839180350304\n    time_span=0.0001s, test_ID=147, label=2, output_node=9, voltage=-0.004823705181479454\n    time_span=0.0001s, test_ID=147, label=2, output_node=sum, voltage=0.0019731074571609497\n    Time consumed for 1 sample = 142.89732193946838 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '147'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=148, label=0, output_node=bkg, voltage=-0.004159362521022558\n    time_span=0.0001s, test_ID=148, label=0, output_node=0, voltage=0.019262949004769325\n    time_span=0.0001s, test_ID=148, label=0, output_node=1, voltage=0.0067350598983466625\n    time_span=0.0001s, test_ID=148, label=0, output_node=2, voltage=0.016277888789772987\n    time_span=0.0001s, test_ID=148, label=0, output_node=3, voltage=0.00564741063863039\n    time_span=0.0001s, test_ID=148, label=0, output_node=4, voltage=0.012670319527387619\n    time_span=0.0001s, test_ID=148, label=0, output_node=5, voltage=0.01409661304205656\n    time_span=0.0001s, test_ID=148, label=0, output_node=6, voltage=0.01619521901011467\n    time_span=0.0001s, test_ID=148, label=0, output_node=7, voltage=0.008811753243207932\n    time_span=0.0001s, test_ID=148, label=0, output_node=8, voltage=0.01583067700266838\n    time_span=0.0001s, test_ID=148, label=0, output_node=9, voltage=0.015818724408745766\n    time_span=0.0001s, test_ID=148, label=0, output_node=sum, voltage=0.04049103707075119\n    Time consumed for 1 sample = 142.98895692825317 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '148'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=149, label=2, output_node=bkg, voltage=-0.006032868288457394\n    time_span=0.0001s, test_ID=149, label=2, output_node=0, voltage=-0.0035756968427449465\n    time_span=0.0001s, test_ID=149, label=2, output_node=1, voltage=-0.0007968127611093223\n    time_span=0.0001s, test_ID=149, label=2, output_node=2, voltage=0.0012420318089425564\n    time_span=0.0001s, test_ID=149, label=2, output_node=3, voltage=-0.002439243020489812\n    time_span=0.0001s, test_ID=149, label=2, output_node=4, voltage=-0.0013635458890348673\n    time_span=0.0001s, test_ID=149, label=2, output_node=5, voltage=-0.0022838644217699766\n    time_span=0.0001s, test_ID=149, label=2, output_node=6, voltage=-0.0032808766700327396\n    time_span=0.0001s, test_ID=149, label=2, output_node=7, voltage=-0.001083665294572711\n    time_span=0.0001s, test_ID=149, label=2, output_node=8, voltage=-0.00584561750292778\n    time_span=0.0001s, test_ID=149, label=2, output_node=9, voltage=-0.0018605580553412437\n    time_span=0.0001s, test_ID=149, label=2, output_node=sum, voltage=0.004359561484307051\n    Time consumed for 1 sample = 143.04958701133728 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '149'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=150, label=9, output_node=bkg, voltage=-0.006157370749861002\n    time_span=0.0001s, test_ID=150, label=9, output_node=0, voltage=0.00802490022033453\n    time_span=0.0001s, test_ID=150, label=9, output_node=1, voltage=0.0011324702063575387\n    time_span=0.0001s, test_ID=150, label=9, output_node=2, voltage=0.005257968325167894\n    time_span=0.0001s, test_ID=150, label=9, output_node=3, voltage=0.006790836341679096\n    time_span=0.0001s, test_ID=150, label=9, output_node=4, voltage=0.013557769358158112\n    time_span=0.0001s, test_ID=150, label=9, output_node=5, voltage=0.012097609229385853\n    time_span=0.0001s, test_ID=150, label=9, output_node=6, voltage=0.008798804134130478\n    time_span=0.0001s, test_ID=150, label=9, output_node=7, voltage=0.005306772887706757\n    time_span=0.0001s, test_ID=150, label=9, output_node=8, voltage=0.012508964166045189\n    time_span=0.0001s, test_ID=150, label=9, output_node=9, voltage=0.015941236168146133\n    time_span=0.0001s, test_ID=150, label=9, output_node=sum, voltage=0.027022909373044968\n    Time consumed for 1 sample = 142.92556405067444 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '150'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=151, label=9, output_node=bkg, voltage=-0.0062639438547194\n    time_span=0.0001s, test_ID=151, label=9, output_node=0, voltage=0.012919322587549686\n    time_span=0.0001s, test_ID=151, label=9, output_node=1, voltage=0.0007778884610161185\n    time_span=0.0001s, test_ID=151, label=9, output_node=2, voltage=0.007199202664196491\n    time_span=0.0001s, test_ID=151, label=9, output_node=3, voltage=0.009761952795088291\n    time_span=0.0001s, test_ID=151, label=9, output_node=4, voltage=0.007801793050020933\n    time_span=0.0001s, test_ID=151, label=9, output_node=5, voltage=0.010450199246406555\n    time_span=0.0001s, test_ID=151, label=9, output_node=6, voltage=0.006483067758381367\n    time_span=0.0001s, test_ID=151, label=9, output_node=7, voltage=0.01092729065567255\n    time_span=0.0001s, test_ID=151, label=9, output_node=8, voltage=0.009032868780195713\n    time_span=0.0001s, test_ID=151, label=9, output_node=9, voltage=0.011588646098971367\n    time_span=0.0001s, test_ID=151, label=9, output_node=sum, voltage=0.03107968159019947\n    Time consumed for 1 sample = 142.7096722126007 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '151'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=152, label=5, output_node=bkg, voltage=-0.007537848316133022\n    time_span=0.0001s, test_ID=152, label=5, output_node=0, voltage=0.0016045814845710993\n    time_span=0.0001s, test_ID=152, label=5, output_node=1, voltage=0.0004950197762809694\n    time_span=0.0001s, test_ID=152, label=5, output_node=2, voltage=0.00233067711815238\n    time_span=0.0001s, test_ID=152, label=5, output_node=3, voltage=0.008410358801484108\n    time_span=0.0001s, test_ID=152, label=5, output_node=4, voltage=0.0015836653765290976\n    time_span=0.0001s, test_ID=152, label=5, output_node=5, voltage=0.010536853224039078\n    time_span=0.0001s, test_ID=152, label=5, output_node=6, voltage=0.002387450309470296\n    time_span=0.0001s, test_ID=152, label=5, output_node=7, voltage=-0.0016593625769019127\n    time_span=0.0001s, test_ID=152, label=5, output_node=8, voltage=0.007215139921754599\n    time_span=0.0001s, test_ID=152, label=5, output_node=9, voltage=0.0034362548030912876\n    time_span=0.0001s, test_ID=152, label=5, output_node=sum, voltage=0.020454183220863342\n    Time consumed for 1 sample = 140.41091656684875 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '152'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=153, label=5, output_node=bkg, voltage=-0.005687251221388578\n    time_span=0.0001s, test_ID=153, label=5, output_node=0, voltage=0.00041633457294665277\n    time_span=0.0001s, test_ID=153, label=5, output_node=1, voltage=0.0022639441303908825\n    time_span=0.0001s, test_ID=153, label=5, output_node=2, voltage=0.0007231076015159488\n    time_span=0.0001s, test_ID=153, label=5, output_node=3, voltage=0.002457171445712447\n    time_span=0.0001s, test_ID=153, label=5, output_node=4, voltage=-0.0008635458652861416\n    time_span=0.0001s, test_ID=153, label=5, output_node=5, voltage=0.007885457947850227\n    time_span=0.0001s, test_ID=153, label=5, output_node=6, voltage=0.002067729365080595\n    time_span=0.0001s, test_ID=153, label=5, output_node=7, voltage=0.00020318719907663763\n    time_span=0.0001s, test_ID=153, label=5, output_node=8, voltage=0.000632470182608813\n    time_span=0.0001s, test_ID=153, label=5, output_node=9, voltage=0.0034123507793992758\n    time_span=0.0001s, test_ID=153, label=5, output_node=sum, voltage=0.016399402171373367\n    Time consumed for 1 sample = 142.1092119216919 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '153'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=154, label=1, output_node=bkg, voltage=-0.004320716951042414\n    time_span=0.0001s, test_ID=154, label=1, output_node=0, voltage=0.0018256971379742026\n    time_span=0.0001s, test_ID=154, label=1, output_node=1, voltage=0.00935856532305479\n    time_span=0.0001s, test_ID=154, label=1, output_node=2, voltage=0.0016294820234179497\n    time_span=0.0001s, test_ID=154, label=1, output_node=3, voltage=0.0007490040734410286\n    time_span=0.0001s, test_ID=154, label=1, output_node=4, voltage=0.005304780788719654\n    time_span=0.0001s, test_ID=154, label=1, output_node=5, voltage=0.008555777370929718\n    time_span=0.0001s, test_ID=154, label=1, output_node=6, voltage=0.0029671313241124153\n    time_span=0.0001s, test_ID=154, label=1, output_node=7, voltage=0.003920319024473429\n    time_span=0.0001s, test_ID=154, label=1, output_node=8, voltage=0.003085657488554716\n    time_span=0.0001s, test_ID=154, label=1, output_node=9, voltage=0.008984063751995564\n    time_span=0.0001s, test_ID=154, label=1, output_node=sum, voltage=0.02029382437467575\n    Time consumed for 1 sample = 142.57586216926575 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '154'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=155, label=5, output_node=bkg, voltage=-0.006508964113891125\n    time_span=0.0001s, test_ID=155, label=5, output_node=0, voltage=0.0003396413812879473\n    time_span=0.0001s, test_ID=155, label=5, output_node=1, voltage=0.002809761092066765\n    time_span=0.0001s, test_ID=155, label=5, output_node=2, voltage=0.0030866533052176237\n    time_span=0.0001s, test_ID=155, label=5, output_node=3, voltage=0.00719223078340292\n    time_span=0.0001s, test_ID=155, label=5, output_node=4, voltage=0.0037778886035084724\n    time_span=0.0001s, test_ID=155, label=5, output_node=5, voltage=0.012493027374148369\n    time_span=0.0001s, test_ID=155, label=5, output_node=6, voltage=0.004584661219269037\n    time_span=0.0001s, test_ID=155, label=5, output_node=7, voltage=-0.0017270913813263178\n    time_span=0.0001s, test_ID=155, label=5, output_node=8, voltage=0.008257968351244926\n    time_span=0.0001s, test_ID=155, label=5, output_node=9, voltage=0.0066195218823850155\n    time_span=0.0001s, test_ID=155, label=5, output_node=sum, voltage=0.020832668989896774\n    Time consumed for 1 sample = 142.6007854938507 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '155'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=156, label=6, output_node=bkg, voltage=-0.005438247229903936\n    time_span=0.0001s, test_ID=156, label=6, output_node=0, voltage=-0.0013197209918871522\n    time_span=0.0001s, test_ID=156, label=6, output_node=1, voltage=-0.002658366458490491\n    time_span=0.0001s, test_ID=156, label=6, output_node=2, voltage=-0.0040189241990447044\n    time_span=0.0001s, test_ID=156, label=6, output_node=3, voltage=-0.004038844723254442\n    time_span=0.0001s, test_ID=156, label=6, output_node=4, voltage=-0.0015697210328653455\n    time_span=0.0001s, test_ID=156, label=6, output_node=5, voltage=-0.0009711156017147005\n    time_span=0.0001s, test_ID=156, label=6, output_node=6, voltage=0.0011713148560374975\n    time_span=0.0001s, test_ID=156, label=6, output_node=7, voltage=-0.002230079611763358\n    time_span=0.0001s, test_ID=156, label=6, output_node=8, voltage=-0.002207171404734254\n    time_span=0.0001s, test_ID=156, label=6, output_node=9, voltage=-0.003804780775681138\n    time_span=0.0001s, test_ID=156, label=6, output_node=sum, voltage=0.006559760309755802\n    Time consumed for 1 sample = 142.99466466903687 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '156'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=157, label=0, output_node=bkg, voltage=-0.004504980053752661\n    time_span=0.0001s, test_ID=157, label=0, output_node=0, voltage=0.008127490058541298\n    time_span=0.0001s, test_ID=157, label=0, output_node=1, voltage=0.0010786851635202765\n    time_span=0.0001s, test_ID=157, label=0, output_node=2, voltage=0.004686255007982254\n    time_span=0.0001s, test_ID=157, label=0, output_node=3, voltage=0.0050268922932446\n    time_span=0.0001s, test_ID=157, label=0, output_node=4, voltage=0.004527888726443052\n    time_span=0.0001s, test_ID=157, label=0, output_node=5, voltage=0.002305777044966817\n    time_span=0.0001s, test_ID=157, label=0, output_node=6, voltage=0.005137450061738491\n    time_span=0.0001s, test_ID=157, label=0, output_node=7, voltage=0.005174302961677313\n    time_span=0.0001s, test_ID=157, label=0, output_node=8, voltage=0.005106573458760977\n    time_span=0.0001s, test_ID=157, label=0, output_node=9, voltage=0.00573007995262742\n    time_span=0.0001s, test_ID=157, label=0, output_node=sum, voltage=0.02017330564558506\n    Time consumed for 1 sample = 140.30959606170654 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '157'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=158, label=3, output_node=bkg, voltage=-0.0068725100718438625\n    time_span=0.0001s, test_ID=158, label=3, output_node=0, voltage=0.006525896489620209\n    time_span=0.0001s, test_ID=158, label=3, output_node=1, voltage=0.0035209162160754204\n    time_span=0.0001s, test_ID=158, label=3, output_node=2, voltage=0.005737051367759705\n    time_span=0.0001s, test_ID=158, label=3, output_node=3, voltage=0.010402390733361244\n    time_span=0.0001s, test_ID=158, label=3, output_node=4, voltage=0.0004910358693450689\n    time_span=0.0001s, test_ID=158, label=3, output_node=5, voltage=0.006182271055877209\n    time_span=0.0001s, test_ID=158, label=3, output_node=6, voltage=0.0030398406088352203\n    time_span=0.0001s, test_ID=158, label=3, output_node=7, voltage=0.002580677391961217\n    time_span=0.0001s, test_ID=158, label=3, output_node=8, voltage=0.001558764954097569\n    time_span=0.0001s, test_ID=158, label=3, output_node=9, voltage=0.003970119636505842\n    time_span=0.0001s, test_ID=158, label=3, output_node=sum, voltage=0.021203188225626945\n    Time consumed for 1 sample = 142.9617884159088 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '158'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=159, label=4, output_node=bkg, voltage=-0.007055777125060558\n    time_span=0.0001s, test_ID=159, label=4, output_node=0, voltage=0.006285856477916241\n    time_span=0.0001s, test_ID=159, label=4, output_node=1, voltage=0.008591633290052414\n    time_span=0.0001s, test_ID=159, label=4, output_node=2, voltage=0.006362549960613251\n    time_span=0.0001s, test_ID=159, label=4, output_node=3, voltage=0.002655378310009837\n    time_span=0.0001s, test_ID=159, label=4, output_node=4, voltage=0.016358565539121628\n    time_span=0.0001s, test_ID=159, label=4, output_node=5, voltage=0.007831673137843609\n    time_span=0.0001s, test_ID=159, label=4, output_node=6, voltage=0.010105577297508717\n    time_span=0.0001s, test_ID=159, label=4, output_node=7, voltage=0.008578685112297535\n    time_span=0.0001s, test_ID=159, label=4, output_node=8, voltage=0.007698207162320614\n    time_span=0.0001s, test_ID=159, label=4, output_node=9, voltage=0.01129880454391241\n    time_span=0.0001s, test_ID=159, label=4, output_node=sum, voltage=0.02206573635339737\n    Time consumed for 1 sample = 142.62367463111877 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '159'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=160, label=4, output_node=bkg, voltage=-0.007307768799364567\n    time_span=0.0001s, test_ID=160, label=4, output_node=0, voltage=-0.003126493887975812\n    time_span=0.0001s, test_ID=160, label=4, output_node=1, voltage=0.0010139443911612034\n    time_span=0.0001s, test_ID=160, label=4, output_node=2, voltage=-0.0037041830364614725\n    time_span=0.0001s, test_ID=160, label=4, output_node=3, voltage=-0.003945218864828348\n    time_span=0.0001s, test_ID=160, label=4, output_node=4, voltage=0.0016175297787413\n    time_span=0.0001s, test_ID=160, label=4, output_node=5, voltage=-0.004324701149016619\n    time_span=0.0001s, test_ID=160, label=4, output_node=6, voltage=-0.0009412351064383984\n    time_span=0.0001s, test_ID=160, label=4, output_node=7, voltage=-0.0023824700620025396\n    time_span=0.0001s, test_ID=160, label=4, output_node=8, voltage=-0.003260955912992358\n    time_span=0.0001s, test_ID=160, label=4, output_node=9, voltage=-0.0005737052415497601\n    time_span=0.0001s, test_ID=160, label=4, output_node=sum, voltage=0.0008197211427614093\n    Time consumed for 1 sample = 143.08824944496155 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '160'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=161, label=6, output_node=bkg, voltage=-0.005316733382642269\n    time_span=0.0001s, test_ID=161, label=6, output_node=0, voltage=0.0035149401519447565\n    time_span=0.0001s, test_ID=161, label=6, output_node=1, voltage=0.0035846612881869078\n    time_span=0.0001s, test_ID=161, label=6, output_node=2, voltage=0.006565737538039684\n    time_span=0.0001s, test_ID=161, label=6, output_node=3, voltage=0.0009093623957596719\n    time_span=0.0001s, test_ID=161, label=6, output_node=4, voltage=0.005091633182018995\n    time_span=0.0001s, test_ID=161, label=6, output_node=5, voltage=0.006866533774882555\n    time_span=0.0001s, test_ID=161, label=6, output_node=6, voltage=0.012694223783910275\n    time_span=0.0001s, test_ID=161, label=6, output_node=7, voltage=0.003761952044442296\n    time_span=0.0001s, test_ID=161, label=6, output_node=8, voltage=0.0034930279944092035\n    time_span=0.0001s, test_ID=161, label=6, output_node=9, voltage=0.00501494063064456\n    time_span=0.0001s, test_ID=161, label=6, output_node=sum, voltage=0.02106374315917492\n    Time consumed for 1 sample = 142.6854019165039 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '161'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=162, label=5, output_node=bkg, voltage=-0.004591633565723896\n    time_span=0.0001s, test_ID=162, label=5, output_node=0, voltage=0.0002649402304086834\n    time_span=0.0001s, test_ID=162, label=5, output_node=1, voltage=-0.0018356574000790715\n    time_span=0.0001s, test_ID=162, label=5, output_node=2, voltage=-0.0012699203798547387\n    time_span=0.0001s, test_ID=162, label=5, output_node=3, voltage=-0.0005288842949084938\n    time_span=0.0001s, test_ID=162, label=5, output_node=4, voltage=-0.0011643426259979606\n    time_span=0.0001s, test_ID=162, label=5, output_node=5, voltage=0.007032868452370167\n    time_span=0.0001s, test_ID=162, label=5, output_node=6, voltage=0.0036952190566807985\n    time_span=0.0001s, test_ID=162, label=5, output_node=7, voltage=-0.0003127489471808076\n    time_span=0.0001s, test_ID=162, label=5, output_node=8, voltage=0.004581673536449671\n    time_span=0.0001s, test_ID=162, label=5, output_node=9, voltage=0.004291832912713289\n    time_span=0.0001s, test_ID=162, label=5, output_node=sum, voltage=0.013205179944634438\n    Time consumed for 1 sample = 142.79645323753357 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '162'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=163, label=4, output_node=bkg, voltage=-0.006829681806266308\n    time_span=0.0001s, test_ID=163, label=4, output_node=0, voltage=-0.001159362611360848\n    time_span=0.0001s, test_ID=163, label=4, output_node=1, voltage=-0.0021264939568936825\n    time_span=0.0001s, test_ID=163, label=4, output_node=2, voltage=-0.0007539840880781412\n    time_span=0.0001s, test_ID=163, label=4, output_node=3, voltage=-0.0007928285631351173\n    time_span=0.0001s, test_ID=163, label=4, output_node=4, voltage=0.0064691235311329365\n    time_span=0.0001s, test_ID=163, label=4, output_node=5, voltage=-0.0023984063882380724\n    time_span=0.0001s, test_ID=163, label=4, output_node=6, voltage=0.0006414342205971479\n    time_span=0.0001s, test_ID=163, label=4, output_node=7, voltage=0.0005727091920562088\n    time_span=0.0001s, test_ID=163, label=4, output_node=8, voltage=-0.0010717131663113832\n    time_span=0.0001s, test_ID=163, label=4, output_node=9, voltage=0.00014940224355086684\n    time_span=0.0001s, test_ID=163, label=4, output_node=sum, voltage=0.00817828718572855\n    Time consumed for 1 sample = 142.79759788513184 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '163'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=164, label=6, output_node=bkg, voltage=-0.004695218987762928\n    time_span=0.0001s, test_ID=164, label=6, output_node=0, voltage=-0.0015816733939573169\n    time_span=0.0001s, test_ID=164, label=6, output_node=1, voltage=-0.0024601593613624573\n    time_span=0.0001s, test_ID=164, label=6, output_node=2, voltage=-0.003498008009046316\n    time_span=0.0001s, test_ID=164, label=6, output_node=3, voltage=-0.002749003702774644\n    time_span=0.0001s, test_ID=164, label=6, output_node=4, voltage=-0.0013515936443582177\n    time_span=0.0001s, test_ID=164, label=6, output_node=5, voltage=-1.9920211343560368e-05\n    time_span=0.0001s, test_ID=164, label=6, output_node=6, voltage=0.001535856630653143\n    time_span=0.0001s, test_ID=164, label=6, output_node=7, voltage=-0.003588645253330469\n    time_span=0.0001s, test_ID=164, label=6, output_node=8, voltage=-0.0022729083430022\n    time_span=0.0001s, test_ID=164, label=6, output_node=9, voltage=-0.004321713000535965\n    time_span=0.0001s, test_ID=164, label=6, output_node=sum, voltage=0.003981075715273619\n    Time consumed for 1 sample = 142.98908281326294 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '164'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=165, label=5, output_node=bkg, voltage=-0.005724103190004826\n    time_span=0.0001s, test_ID=165, label=5, output_node=0, voltage=0.00524103594943881\n    time_span=0.0001s, test_ID=165, label=5, output_node=1, voltage=0.011157370172441006\n    time_span=0.0001s, test_ID=165, label=5, output_node=2, voltage=0.005865537561476231\n    time_span=0.0001s, test_ID=165, label=5, output_node=3, voltage=0.018606573343276978\n    time_span=0.0001s, test_ID=165, label=5, output_node=4, voltage=0.002498007845133543\n    time_span=0.0001s, test_ID=165, label=5, output_node=5, voltage=0.018501991406083107\n    time_span=0.0001s, test_ID=165, label=5, output_node=6, voltage=0.00720019917935133\n    time_span=0.0001s, test_ID=165, label=5, output_node=7, voltage=0.005239043850451708\n    time_span=0.0001s, test_ID=165, label=5, output_node=8, voltage=0.009141434915363789\n    time_span=0.0001s, test_ID=165, label=5, output_node=9, voltage=0.010926295071840286\n    time_span=0.0001s, test_ID=165, label=5, output_node=sum, voltage=0.03152589499950409\n    Time consumed for 1 sample = 143.02093815803528 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '165'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=166, label=4, output_node=bkg, voltage=-0.005098605528473854\n    time_span=0.0001s, test_ID=166, label=4, output_node=0, voltage=-0.0010258962865918875\n    time_span=0.0001s, test_ID=166, label=4, output_node=1, voltage=-0.00032370525877922773\n    time_span=0.0001s, test_ID=166, label=4, output_node=2, voltage=-0.00013147405115887523\n    time_span=0.0001s, test_ID=166, label=4, output_node=3, voltage=0.0008844622643664479\n    time_span=0.0001s, test_ID=166, label=4, output_node=4, voltage=0.008981076069176197\n    time_span=0.0001s, test_ID=166, label=4, output_node=5, voltage=0.000553784950170666\n    time_span=0.0001s, test_ID=166, label=4, output_node=6, voltage=-0.00011553772492334247\n    time_span=0.0001s, test_ID=166, label=4, output_node=7, voltage=0.0007788845105096698\n    time_span=0.0001s, test_ID=166, label=4, output_node=8, voltage=0.00032171307248063385\n    time_span=0.0001s, test_ID=166, label=4, output_node=9, voltage=0.0009900397853925824\n    time_span=0.0001s, test_ID=166, label=4, output_node=sum, voltage=0.013871514238417149\n    Time consumed for 1 sample = 142.82771110534668 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '166'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=167, label=5, output_node=bkg, voltage=-0.006564741022884846\n    time_span=0.0001s, test_ID=167, label=5, output_node=0, voltage=0.0006852589431218803\n    time_span=0.0001s, test_ID=167, label=5, output_node=1, voltage=0.0030348605941981077\n    time_span=0.0001s, test_ID=167, label=5, output_node=2, voltage=0.0009233066812157631\n    time_span=0.0001s, test_ID=167, label=5, output_node=3, voltage=0.0010507968254387379\n    time_span=0.0001s, test_ID=167, label=5, output_node=4, voltage=0.00022709144104737788\n    time_span=0.0001s, test_ID=167, label=5, output_node=5, voltage=0.0068685258738696575\n    time_span=0.0001s, test_ID=167, label=5, output_node=6, voltage=0.0043406374752521515\n    time_span=0.0001s, test_ID=167, label=5, output_node=7, voltage=-0.0004980079247616231\n    time_span=0.0001s, test_ID=167, label=5, output_node=8, voltage=0.005487051792442799\n    time_span=0.0001s, test_ID=167, label=5, output_node=9, voltage=-0.0009013945236802101\n    time_span=0.0001s, test_ID=167, label=5, output_node=sum, voltage=0.014569721184670925\n    Time consumed for 1 sample = 142.82998895645142 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '167'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=168, label=1, output_node=bkg, voltage=-0.004901393782347441\n    time_span=0.0001s, test_ID=168, label=1, output_node=0, voltage=0.002469123573973775\n    time_span=0.0001s, test_ID=168, label=1, output_node=1, voltage=0.010079680941998959\n    time_span=0.0001s, test_ID=168, label=1, output_node=2, voltage=0.005175299011170864\n    time_span=0.0001s, test_ID=168, label=1, output_node=3, voltage=0.0012689242139458656\n    time_span=0.0001s, test_ID=168, label=1, output_node=4, voltage=0.006342629436403513\n    time_span=0.0001s, test_ID=168, label=1, output_node=5, voltage=0.004608565475791693\n    time_span=0.0001s, test_ID=168, label=1, output_node=6, voltage=0.005606574006378651\n    time_span=0.0001s, test_ID=168, label=1, output_node=7, voltage=0.005907370243221521\n    time_span=0.0001s, test_ID=168, label=1, output_node=8, voltage=0.0032639445271342993\n    time_span=0.0001s, test_ID=168, label=1, output_node=9, voltage=0.003700199304148555\n    time_span=0.0001s, test_ID=168, label=1, output_node=sum, voltage=0.019928285852074623\n    Time consumed for 1 sample = 142.78917264938354 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '168'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=169, label=4, output_node=bkg, voltage=-0.006567729637026787\n    time_span=0.0001s, test_ID=169, label=4, output_node=0, voltage=-0.0036852587945759296\n    time_span=0.0001s, test_ID=169, label=4, output_node=1, voltage=0.00082171312533319\n    time_span=0.0001s, test_ID=169, label=4, output_node=2, voltage=-0.0008007968426682055\n    time_span=0.0001s, test_ID=169, label=4, output_node=3, voltage=0.003000000026077032\n    time_span=0.0001s, test_ID=169, label=4, output_node=4, voltage=0.006429282948374748\n    time_span=0.0001s, test_ID=169, label=4, output_node=5, voltage=0.0044013941660523415\n    time_span=0.0001s, test_ID=169, label=4, output_node=6, voltage=-2.290836891916115e-05\n    time_span=0.0001s, test_ID=169, label=4, output_node=7, voltage=0.0061205183155834675\n    time_span=0.0001s, test_ID=169, label=4, output_node=8, voltage=-2.0916242647217587e-05\n    time_span=0.0001s, test_ID=169, label=4, output_node=9, voltage=0.0058804783038794994\n    time_span=0.0001s, test_ID=169, label=4, output_node=sum, voltage=0.013860557228326797\n    Time consumed for 1 sample = 143.00380539894104 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '169'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=170, label=4, output_node=bkg, voltage=-0.006539840716868639\n    time_span=0.0001s, test_ID=170, label=4, output_node=0, voltage=5.9761019656434655e-05\n    time_span=0.0001s, test_ID=170, label=4, output_node=1, voltage=-1.494028401793912e-05\n    time_span=0.0001s, test_ID=170, label=4, output_node=2, voltage=0.002194223226979375\n    time_span=0.0001s, test_ID=170, label=4, output_node=3, voltage=0.0016882471973076463\n    time_span=0.0001s, test_ID=170, label=4, output_node=4, voltage=0.011501992121338844\n    time_span=0.0001s, test_ID=170, label=4, output_node=5, voltage=0.003858565352857113\n    time_span=0.0001s, test_ID=170, label=4, output_node=6, voltage=-0.0007719122804701328\n    time_span=0.0001s, test_ID=170, label=4, output_node=7, voltage=0.0037440238520503044\n    time_span=0.0001s, test_ID=170, label=4, output_node=8, voltage=-0.00039641422335989773\n    time_span=0.0001s, test_ID=170, label=4, output_node=9, voltage=0.006010956130921841\n    time_span=0.0001s, test_ID=170, label=4, output_node=sum, voltage=0.0068336655385792255\n    Time consumed for 1 sample = 142.69733595848083 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '170'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=171, label=7, output_node=bkg, voltage=-0.005951195489615202\n    time_span=0.0001s, test_ID=171, label=7, output_node=0, voltage=-0.0015866532921791077\n    time_span=0.0001s, test_ID=171, label=7, output_node=1, voltage=-0.0010856573935598135\n    time_span=0.0001s, test_ID=171, label=7, output_node=2, voltage=-0.002439243020489812\n    time_span=0.0001s, test_ID=171, label=7, output_node=3, voltage=-0.0021245020907372236\n    time_span=0.0001s, test_ID=171, label=7, output_node=4, voltage=-0.002321713138371706\n    time_span=0.0001s, test_ID=171, label=7, output_node=5, voltage=-0.004387449938803911\n    time_span=0.0001s, test_ID=171, label=7, output_node=6, voltage=-0.003451195079833269\n    time_span=0.0001s, test_ID=171, label=7, output_node=7, voltage=-0.0012221115175634623\n    time_span=0.0001s, test_ID=171, label=7, output_node=8, voltage=-0.0014701193431392312\n    time_span=0.0001s, test_ID=171, label=7, output_node=9, voltage=-0.0006205178797245026\n    time_span=0.0001s, test_ID=171, label=7, output_node=sum, voltage=0.0015368525637313724\n    Time consumed for 1 sample = 143.1260049343109 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '171'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=172, label=2, output_node=bkg, voltage=-0.005514939781278372\n    time_span=0.0001s, test_ID=172, label=2, output_node=0, voltage=0.0024970120284706354\n    time_span=0.0001s, test_ID=172, label=2, output_node=1, voltage=0.0018615536391735077\n    time_span=0.0001s, test_ID=172, label=2, output_node=2, voltage=0.008976094424724579\n    time_span=0.0001s, test_ID=172, label=2, output_node=3, voltage=0.004522908478975296\n    time_span=0.0001s, test_ID=172, label=2, output_node=4, voltage=-0.0003187250404153019\n    time_span=0.0001s, test_ID=172, label=2, output_node=5, voltage=0.0011075696675106883\n    time_span=0.0001s, test_ID=172, label=2, output_node=6, voltage=-0.0007211156189441681\n    time_span=0.0001s, test_ID=172, label=2, output_node=7, voltage=0.00363844633102417\n    time_span=0.0001s, test_ID=172, label=2, output_node=8, voltage=0.0014252987457439303\n    time_span=0.0001s, test_ID=172, label=2, output_node=9, voltage=0.0013884463114663959\n    time_span=0.0001s, test_ID=172, label=2, output_node=sum, voltage=0.012276892550289631\n    Time consumed for 1 sample = 143.01832795143127 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '172'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=173, label=3, output_node=bkg, voltage=-0.004290836397558451\n    time_span=0.0001s, test_ID=173, label=3, output_node=0, voltage=-0.0008715139701962471\n    time_span=0.0001s, test_ID=173, label=3, output_node=1, voltage=0.0030607569497078657\n    time_span=0.0001s, test_ID=173, label=3, output_node=2, voltage=-0.0007788845105096698\n    time_span=0.0001s, test_ID=173, label=3, output_node=3, voltage=0.005792828742414713\n    time_span=0.0001s, test_ID=173, label=3, output_node=4, voltage=-0.0019800798036158085\n    time_span=0.0001s, test_ID=173, label=3, output_node=5, voltage=0.0042768921703100204\n    time_span=0.0001s, test_ID=173, label=3, output_node=6, voltage=-0.0014591632643714547\n    time_span=0.0001s, test_ID=173, label=3, output_node=7, voltage=-0.0006653386517427862\n    time_span=0.0001s, test_ID=173, label=3, output_node=8, voltage=0.001283864607103169\n    time_span=0.0001s, test_ID=173, label=3, output_node=9, voltage=0.000166334692039527\n    time_span=0.0001s, test_ID=173, label=3, output_node=sum, voltage=0.013476095162332058\n    Time consumed for 1 sample = 143.0496838092804 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '173'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=174, label=2, output_node=bkg, voltage=-0.006749999243766069\n    time_span=0.0001s, test_ID=174, label=2, output_node=0, voltage=0.0040229083970189095\n    time_span=0.0001s, test_ID=174, label=2, output_node=1, voltage=0.002350597409531474\n    time_span=0.0001s, test_ID=174, label=2, output_node=2, voltage=0.01659860648214817\n    time_span=0.0001s, test_ID=174, label=2, output_node=3, voltage=0.005478087812662125\n    time_span=0.0001s, test_ID=174, label=2, output_node=4, voltage=0.0029003985691815615\n    time_span=0.0001s, test_ID=174, label=2, output_node=5, voltage=0.004011952318251133\n    time_span=0.0001s, test_ID=174, label=2, output_node=6, voltage=0.005159362684935331\n    time_span=0.0001s, test_ID=174, label=2, output_node=7, voltage=0.0045159365981817245\n    time_span=0.0001s, test_ID=174, label=2, output_node=8, voltage=0.006006972398608923\n    time_span=0.0001s, test_ID=174, label=2, output_node=9, voltage=0.0012978088343515992\n    time_span=0.0001s, test_ID=174, label=2, output_node=sum, voltage=0.025207171216607094\n    Time consumed for 1 sample = 142.87121105194092 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '174'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=175, label=7, output_node=bkg, voltage=-0.004967132117599249\n    time_span=0.0001s, test_ID=175, label=7, output_node=0, voltage=-0.003575697308406234\n    time_span=0.0001s, test_ID=175, label=7, output_node=1, voltage=0.002467131707817316\n    time_span=0.0001s, test_ID=175, label=7, output_node=2, voltage=-0.0007440239423885942\n    time_span=0.0001s, test_ID=175, label=7, output_node=3, voltage=0.003108565928414464\n    time_span=0.0001s, test_ID=175, label=7, output_node=4, voltage=-0.0007749004871584475\n    time_span=0.0001s, test_ID=175, label=7, output_node=5, voltage=-0.0020946215372532606\n    time_span=0.0001s, test_ID=175, label=7, output_node=6, voltage=-0.002454183530062437\n    time_span=0.0001s, test_ID=175, label=7, output_node=7, voltage=0.0044651394709944725\n    time_span=0.0001s, test_ID=175, label=7, output_node=8, voltage=-0.0010149403242394328\n    time_span=0.0001s, test_ID=175, label=7, output_node=9, voltage=-0.0035846612881869078\n    time_span=0.0001s, test_ID=175, label=7, output_node=sum, voltage=0.006737051531672478\n    Time consumed for 1 sample = 142.96738934516907 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '175'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=176, label=1, output_node=bkg, voltage=-0.0061762952245771885\n    time_span=0.0001s, test_ID=176, label=1, output_node=0, voltage=0.005249999929219484\n    time_span=0.0001s, test_ID=176, label=1, output_node=1, voltage=0.012781872414052486\n    time_span=0.0001s, test_ID=176, label=1, output_node=2, voltage=0.004719123709946871\n    time_span=0.0001s, test_ID=176, label=1, output_node=3, voltage=0.006990039721131325\n    time_span=0.0001s, test_ID=176, label=1, output_node=4, voltage=0.00856274925172329\n    time_span=0.0001s, test_ID=176, label=1, output_node=5, voltage=0.005185259040445089\n    time_span=0.0001s, test_ID=176, label=1, output_node=6, voltage=0.005345616955310106\n    time_span=0.0001s, test_ID=176, label=1, output_node=7, voltage=0.0048177288845181465\n    time_span=0.0001s, test_ID=176, label=1, output_node=8, voltage=0.009210159070789814\n    time_span=0.0001s, test_ID=176, label=1, output_node=9, voltage=0.003598605515435338\n    time_span=0.0001s, test_ID=176, label=1, output_node=sum, voltage=0.022982070222496986\n    Time consumed for 1 sample = 143.04778480529785 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '176'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=177, label=8, output_node=bkg, voltage=-0.0062978086061775684\n    time_span=0.0001s, test_ID=177, label=8, output_node=0, voltage=0.015248008072376251\n    time_span=0.0001s, test_ID=177, label=8, output_node=1, voltage=0.00832370575517416\n    time_span=0.0001s, test_ID=177, label=8, output_node=2, voltage=0.009822709485888481\n    time_span=0.0001s, test_ID=177, label=8, output_node=3, voltage=0.016911353915929794\n    time_span=0.0001s, test_ID=177, label=8, output_node=4, voltage=0.008250996470451355\n    time_span=0.0001s, test_ID=177, label=8, output_node=5, voltage=0.011436255648732185\n    time_span=0.0001s, test_ID=177, label=8, output_node=6, voltage=0.009882469661533833\n    time_span=0.0001s, test_ID=177, label=8, output_node=7, voltage=0.00971912406384945\n    time_span=0.0001s, test_ID=177, label=8, output_node=8, voltage=0.017057769000530243\n    time_span=0.0001s, test_ID=177, label=8, output_node=9, voltage=0.013280875980854034\n    time_span=0.0001s, test_ID=177, label=8, output_node=sum, voltage=0.041450195014476776\n    Time consumed for 1 sample = 143.54011130332947 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '177'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=178, label=1, output_node=bkg, voltage=-0.006568724289536476\n    time_span=0.0001s, test_ID=178, label=1, output_node=0, voltage=0.0024880478158593178\n    time_span=0.0001s, test_ID=178, label=1, output_node=1, voltage=0.012786852195858955\n    time_span=0.0001s, test_ID=178, label=1, output_node=2, voltage=0.0031484065111726522\n    time_span=0.0001s, test_ID=178, label=1, output_node=3, voltage=0.004387449938803911\n    time_span=0.0001s, test_ID=178, label=1, output_node=4, voltage=0.0059880479238927364\n    time_span=0.0001s, test_ID=178, label=1, output_node=5, voltage=0.004415338858962059\n    time_span=0.0001s, test_ID=178, label=1, output_node=6, voltage=0.0011583665618672967\n    time_span=0.0001s, test_ID=178, label=1, output_node=7, voltage=0.0047480082139372826\n    time_span=0.0001s, test_ID=178, label=1, output_node=8, voltage=0.007527888752520084\n    time_span=0.0001s, test_ID=178, label=1, output_node=9, voltage=0.007917330600321293\n    time_span=0.0001s, test_ID=178, label=1, output_node=sum, voltage=0.020798804238438606\n    Time consumed for 1 sample = 141.86593294143677 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '178'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=179, label=8, output_node=bkg, voltage=-0.004215139430016279\n    time_span=0.0001s, test_ID=179, label=8, output_node=0, voltage=0.0059362552128732204\n    time_span=0.0001s, test_ID=179, label=8, output_node=1, voltage=0.007464142981916666\n    time_span=0.0001s, test_ID=179, label=8, output_node=2, voltage=0.011183267459273338\n    time_span=0.0001s, test_ID=179, label=8, output_node=3, voltage=0.015081673860549927\n    time_span=0.0001s, test_ID=179, label=8, output_node=4, voltage=0.006929283030331135\n    time_span=0.0001s, test_ID=179, label=8, output_node=5, voltage=0.010278884321451187\n    time_span=0.0001s, test_ID=179, label=8, output_node=6, voltage=0.007188247051090002\n    time_span=0.0001s, test_ID=179, label=8, output_node=7, voltage=0.007680278737097979\n    time_span=0.0001s, test_ID=179, label=8, output_node=8, voltage=0.022005975246429443\n    time_span=0.0001s, test_ID=179, label=8, output_node=9, voltage=0.013451195321977139\n    time_span=0.0001s, test_ID=179, label=8, output_node=sum, voltage=0.03442530333995819\n    Time consumed for 1 sample = 143.3343780040741 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '179'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=180, label=1, output_node=bkg, voltage=-0.004734063521027565\n    time_span=0.0001s, test_ID=180, label=1, output_node=0, voltage=0.003209163434803486\n    time_span=0.0001s, test_ID=180, label=1, output_node=1, voltage=0.010510957799851894\n    time_span=0.0001s, test_ID=180, label=1, output_node=2, voltage=0.004423306789249182\n    time_span=0.0001s, test_ID=180, label=1, output_node=3, voltage=0.006408366374671459\n    time_span=0.0001s, test_ID=180, label=1, output_node=4, voltage=0.011015936732292175\n    time_span=0.0001s, test_ID=180, label=1, output_node=5, voltage=0.004922311287373304\n    time_span=0.0001s, test_ID=180, label=1, output_node=6, voltage=0.0026025897823274136\n    time_span=0.0001s, test_ID=180, label=1, output_node=7, voltage=0.004349601920694113\n    time_span=0.0001s, test_ID=180, label=1, output_node=8, voltage=0.007505976129323244\n    time_span=0.0001s, test_ID=180, label=1, output_node=9, voltage=0.011033863760530949\n    time_span=0.0001s, test_ID=180, label=1, output_node=sum, voltage=0.02264043688774109\n    Time consumed for 1 sample = 142.74456143379211 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '180'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=181, label=8, output_node=bkg, voltage=-0.005891434382647276\n    time_span=0.0001s, test_ID=181, label=8, output_node=0, voltage=0.007023904472589493\n    time_span=0.0001s, test_ID=181, label=8, output_node=1, voltage=0.002216135384514928\n    time_span=0.0001s, test_ID=181, label=8, output_node=2, voltage=0.005342629738152027\n    time_span=0.0001s, test_ID=181, label=8, output_node=3, voltage=0.007739043794572353\n    time_span=0.0001s, test_ID=181, label=8, output_node=4, voltage=0.00315537815913558\n    time_span=0.0001s, test_ID=181, label=8, output_node=5, voltage=0.011412350460886955\n    time_span=0.0001s, test_ID=181, label=8, output_node=6, voltage=0.008196215145289898\n    time_span=0.0001s, test_ID=181, label=8, output_node=7, voltage=0.0020388448610901833\n    time_span=0.0001s, test_ID=181, label=8, output_node=8, voltage=0.014664342626929283\n    time_span=0.0001s, test_ID=181, label=8, output_node=9, voltage=0.005273904651403427\n    time_span=0.0001s, test_ID=181, label=8, output_node=sum, voltage=0.02277589775621891\n    Time consumed for 1 sample = 142.9493489265442 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '181'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=182, label=5, output_node=bkg, voltage=-0.0053077684715390205\n    time_span=0.0001s, test_ID=182, label=5, output_node=0, voltage=0.0049731070175766945\n    time_span=0.0001s, test_ID=182, label=5, output_node=1, voltage=0.0013306774199008942\n    time_span=0.0001s, test_ID=182, label=5, output_node=2, voltage=0.007993027567863464\n    time_span=0.0001s, test_ID=182, label=5, output_node=3, voltage=0.007041832897812128\n    time_span=0.0001s, test_ID=182, label=5, output_node=4, voltage=0.004467131104320288\n    time_span=0.0001s, test_ID=182, label=5, output_node=5, voltage=0.015222110785543919\n    time_span=0.0001s, test_ID=182, label=5, output_node=6, voltage=0.005253983661532402\n    time_span=0.0001s, test_ID=182, label=5, output_node=7, voltage=0.0018356575164943933\n    time_span=0.0001s, test_ID=182, label=5, output_node=8, voltage=0.013074701651930809\n    time_span=0.0001s, test_ID=182, label=5, output_node=9, voltage=0.00790737010538578\n    time_span=0.0001s, test_ID=182, label=5, output_node=sum, voltage=0.026111552491784096\n    Time consumed for 1 sample = 142.970365524292 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '182'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=183, label=0, output_node=bkg, voltage=-0.004816733300685883\n    time_span=0.0001s, test_ID=183, label=0, output_node=0, voltage=0.01781374402344227\n    time_span=0.0001s, test_ID=183, label=0, output_node=1, voltage=0.0029551791958510876\n    time_span=0.0001s, test_ID=183, label=0, output_node=2, voltage=0.007419323083013296\n    time_span=0.0001s, test_ID=183, label=0, output_node=3, voltage=0.005735060200095177\n    time_span=0.0001s, test_ID=183, label=0, output_node=4, voltage=0.010465139523148537\n    time_span=0.0001s, test_ID=183, label=0, output_node=5, voltage=0.007029880303889513\n    time_span=0.0001s, test_ID=183, label=0, output_node=6, voltage=0.01066533848643303\n    time_span=0.0001s, test_ID=183, label=0, output_node=7, voltage=0.006750995758920908\n    time_span=0.0001s, test_ID=183, label=0, output_node=8, voltage=0.006219123490154743\n    time_span=0.0001s, test_ID=183, label=0, output_node=9, voltage=0.009598605334758759\n    time_span=0.0001s, test_ID=183, label=0, output_node=sum, voltage=0.03356773033738136\n    Time consumed for 1 sample = 142.90083599090576 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '183'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=184, label=8, output_node=bkg, voltage=-0.00396812753751874\n    time_span=0.0001s, test_ID=184, label=8, output_node=0, voltage=0.0019790837541222572\n    time_span=0.0001s, test_ID=184, label=8, output_node=1, voltage=0.0008735060109756887\n    time_span=0.0001s, test_ID=184, label=8, output_node=2, voltage=0.0019103585509583354\n    time_span=0.0001s, test_ID=184, label=8, output_node=3, voltage=0.005577689036726952\n    time_span=0.0001s, test_ID=184, label=8, output_node=4, voltage=0.0021394421346485615\n    time_span=0.0001s, test_ID=184, label=8, output_node=5, voltage=0.004286852665245533\n    time_span=0.0001s, test_ID=184, label=8, output_node=6, voltage=0.0012430277420207858\n    time_span=0.0001s, test_ID=184, label=8, output_node=7, voltage=0.0003157371247652918\n    time_span=0.0001s, test_ID=184, label=8, output_node=8, voltage=0.0047011952847242355\n    time_span=0.0001s, test_ID=184, label=8, output_node=9, voltage=0.0038914342876523733\n    time_span=0.0001s, test_ID=184, label=8, output_node=sum, voltage=0.016101593151688576\n    Time consumed for 1 sample = 142.78313636779785 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '184'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=185, label=9, output_node=bkg, voltage=-0.007802789099514484\n    time_span=0.0001s, test_ID=185, label=9, output_node=0, voltage=0.006961155217140913\n    time_span=0.0001s, test_ID=185, label=9, output_node=1, voltage=0.0020219124853610992\n    time_span=0.0001s, test_ID=185, label=9, output_node=2, voltage=0.00564741063863039\n    time_span=0.0001s, test_ID=185, label=9, output_node=3, voltage=0.0035308762453496456\n    time_span=0.0001s, test_ID=185, label=9, output_node=4, voltage=0.008161354809999466\n    time_span=0.0001s, test_ID=185, label=9, output_node=5, voltage=0.002436255104839802\n    time_span=0.0001s, test_ID=185, label=9, output_node=6, voltage=0.002832669299095869\n    time_span=0.0001s, test_ID=185, label=9, output_node=7, voltage=0.004928286653012037\n    time_span=0.0001s, test_ID=185, label=9, output_node=8, voltage=0.0044770915992558\n    time_span=0.0001s, test_ID=185, label=9, output_node=9, voltage=0.009733067825436592\n    time_span=0.0001s, test_ID=185, label=9, output_node=sum, voltage=0.019928285852074623\n    Time consumed for 1 sample = 142.66982340812683 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '185'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=186, label=2, output_node=bkg, voltage=-0.005473107565194368\n    time_span=0.0001s, test_ID=186, label=2, output_node=0, voltage=0.0031503986101597548\n    time_span=0.0001s, test_ID=186, label=2, output_node=1, voltage=0.003785856766626239\n    time_span=0.0001s, test_ID=186, label=2, output_node=2, voltage=0.012203187681734562\n    time_span=0.0001s, test_ID=186, label=2, output_node=3, voltage=0.006649401970207691\n    time_span=0.0001s, test_ID=186, label=2, output_node=4, voltage=-0.0005896413349546492\n    time_span=0.0001s, test_ID=186, label=2, output_node=5, voltage=-0.00018227094551548362\n    time_span=0.0001s, test_ID=186, label=2, output_node=6, voltage=0.001725099515169859\n    time_span=0.0001s, test_ID=186, label=2, output_node=7, voltage=0.005234064068645239\n    time_span=0.0001s, test_ID=186, label=2, output_node=8, voltage=0.00234960182569921\n    time_span=0.0001s, test_ID=186, label=2, output_node=9, voltage=0.0003237052296753973\n    time_span=0.0001s, test_ID=186, label=2, output_node=sum, voltage=0.01680079661309719\n    Time consumed for 1 sample = 142.7672574520111 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '186'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=187, label=5, output_node=bkg, voltage=-0.007356573361903429\n    time_span=0.0001s, test_ID=187, label=5, output_node=0, voltage=0.0016434263670817018\n    time_span=0.0001s, test_ID=187, label=5, output_node=1, voltage=0.004041832871735096\n    time_span=0.0001s, test_ID=187, label=5, output_node=2, voltage=0.0044352589175105095\n    time_span=0.0001s, test_ID=187, label=5, output_node=3, voltage=0.011695219203829765\n    time_span=0.0001s, test_ID=187, label=5, output_node=4, voltage=-0.0017131473869085312\n    time_span=0.0001s, test_ID=187, label=5, output_node=5, voltage=0.013123506680130959\n    time_span=0.0001s, test_ID=187, label=5, output_node=6, voltage=0.003612549975514412\n    time_span=0.0001s, test_ID=187, label=5, output_node=7, voltage=0.005360557697713375\n    time_span=0.0001s, test_ID=187, label=5, output_node=8, voltage=0.0030049802735447884\n    time_span=0.0001s, test_ID=187, label=5, output_node=9, voltage=0.0037041830364614725\n    time_span=0.0001s, test_ID=187, label=5, output_node=sum, voltage=0.020648404955863953\n    Time consumed for 1 sample = 143.31164240837097 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '187'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=188, label=0, output_node=bkg, voltage=-0.005416335072368383\n    time_span=0.0001s, test_ID=188, label=0, output_node=0, voltage=0.01061255019158125\n    time_span=0.0001s, test_ID=188, label=0, output_node=1, voltage=-0.0024681277573108673\n    time_span=0.0001s, test_ID=188, label=0, output_node=2, voltage=0.004540836438536644\n    time_span=0.0001s, test_ID=188, label=0, output_node=3, voltage=-0.00040039842133410275\n    time_span=0.0001s, test_ID=188, label=0, output_node=4, voltage=0.0026344622019678354\n    time_span=0.0001s, test_ID=188, label=0, output_node=5, voltage=0.0033784860279411077\n    time_span=0.0001s, test_ID=188, label=0, output_node=6, voltage=0.0029103585984557867\n    time_span=0.0001s, test_ID=188, label=0, output_node=7, voltage=0.004344622138887644\n    time_span=0.0001s, test_ID=188, label=0, output_node=8, voltage=0.0023595616221427917\n    time_span=0.0001s, test_ID=188, label=0, output_node=9, voltage=0.003737051971256733\n    time_span=0.0001s, test_ID=188, label=0, output_node=sum, voltage=0.014931274577975273\n    Time consumed for 1 sample = 142.73633646965027 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '188'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=189, label=1, output_node=bkg, voltage=-0.00528784841299057\n    time_span=0.0001s, test_ID=189, label=1, output_node=0, voltage=-0.004040836822241545\n    time_span=0.0001s, test_ID=189, label=1, output_node=1, voltage=-0.00017928275337908417\n    time_span=0.0001s, test_ID=189, label=1, output_node=2, voltage=-0.0030368526931852102\n    time_span=0.0001s, test_ID=189, label=1, output_node=3, voltage=-0.0031254980713129044\n    time_span=0.0001s, test_ID=189, label=1, output_node=4, voltage=-0.0030886451713740826\n    time_span=0.0001s, test_ID=189, label=1, output_node=5, voltage=-0.0028067731764167547\n    time_span=0.0001s, test_ID=189, label=1, output_node=6, voltage=-0.0023326692171394825\n    time_span=0.0001s, test_ID=189, label=1, output_node=7, voltage=-0.005078685004264116\n    time_span=0.0001s, test_ID=189, label=1, output_node=8, voltage=-0.004642430692911148\n    time_span=0.0001s, test_ID=189, label=1, output_node=9, voltage=-0.0044442228972911835\n    time_span=0.0001s, test_ID=189, label=1, output_node=sum, voltage=0.0015169321559369564\n    Time consumed for 1 sample = 143.20273542404175 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '189'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=190, label=1, output_node=bkg, voltage=-0.004986055660992861\n    time_span=0.0001s, test_ID=190, label=1, output_node=0, voltage=0.0028177290223538876\n    time_span=0.0001s, test_ID=190, label=1, output_node=1, voltage=0.006914342287927866\n    time_span=0.0001s, test_ID=190, label=1, output_node=2, voltage=0.0015009959461167455\n    time_span=0.0001s, test_ID=190, label=1, output_node=3, voltage=-0.0016444223001599312\n    time_span=0.0001s, test_ID=190, label=1, output_node=4, voltage=0.0036015936639159918\n    time_span=0.0001s, test_ID=190, label=1, output_node=5, voltage=-0.001476095523685217\n    time_span=0.0001s, test_ID=190, label=1, output_node=6, voltage=0.00039741041837260127\n    time_span=0.0001s, test_ID=190, label=1, output_node=7, voltage=0.0030448208563029766\n    time_span=0.0001s, test_ID=190, label=1, output_node=8, voltage=-0.0020776891615241766\n    time_span=0.0001s, test_ID=190, label=1, output_node=9, voltage=0.003945218864828348\n    time_span=0.0001s, test_ID=190, label=1, output_node=sum, voltage=0.011664343066513538\n    Time consumed for 1 sample = 142.71098041534424 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '190'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=191, label=1, output_node=bkg, voltage=-0.005224103573709726\n    time_span=0.0001s, test_ID=191, label=1, output_node=0, voltage=0.005763943772763014\n    time_span=0.0001s, test_ID=191, label=1, output_node=1, voltage=0.008820716291666031\n    time_span=0.0001s, test_ID=191, label=1, output_node=2, voltage=0.006242031697183847\n    time_span=0.0001s, test_ID=191, label=1, output_node=3, voltage=0.017926296219229698\n    time_span=0.0001s, test_ID=191, label=1, output_node=4, voltage=0.005851593799889088\n    time_span=0.0001s, test_ID=191, label=1, output_node=5, voltage=0.017244024202227592\n    time_span=0.0001s, test_ID=191, label=1, output_node=6, voltage=0.007526892237365246\n    time_span=0.0001s, test_ID=191, label=1, output_node=7, voltage=0.005662350449711084\n    time_span=0.0001s, test_ID=191, label=1, output_node=8, voltage=0.007782868575304747\n    time_span=0.0001s, test_ID=191, label=1, output_node=9, voltage=0.006142430007457733\n    time_span=0.0001s, test_ID=191, label=1, output_node=sum, voltage=0.031649403274059296\n    Time consumed for 1 sample = 142.93549418449402 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '191'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=192, label=0, output_node=bkg, voltage=-0.005308764986693859\n    time_span=0.0001s, test_ID=192, label=0, output_node=0, voltage=0.012598605826497078\n    time_span=0.0001s, test_ID=192, label=0, output_node=1, voltage=0.0003077689034398645\n    time_span=0.0001s, test_ID=192, label=0, output_node=2, voltage=0.008330677635967731\n    time_span=0.0001s, test_ID=192, label=0, output_node=3, voltage=0.0033286851830780506\n    time_span=0.0001s, test_ID=192, label=0, output_node=4, voltage=-0.0003346613666508347\n    time_span=0.0001s, test_ID=192, label=0, output_node=5, voltage=0.001922310795634985\n    time_span=0.0001s, test_ID=192, label=0, output_node=6, voltage=0.0009362549753859639\n    time_span=0.0001s, test_ID=192, label=0, output_node=7, voltage=0.0036792827304452658\n    time_span=0.0001s, test_ID=192, label=0, output_node=8, voltage=0.006755976006388664\n    time_span=0.0001s, test_ID=192, label=0, output_node=9, voltage=-9.96015023702057e-06\n    time_span=0.0001s, test_ID=192, label=0, output_node=sum, voltage=0.021812748163938522\n    Time consumed for 1 sample = 142.62078285217285 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '192'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=193, label=9, output_node=bkg, voltage=-0.005538844503462315\n    time_span=0.0001s, test_ID=193, label=9, output_node=0, voltage=-0.0009990039980039\n    time_span=0.0001s, test_ID=193, label=9, output_node=1, voltage=-0.0036005976144224405\n    time_span=0.0001s, test_ID=193, label=9, output_node=2, voltage=0.0007559760706499219\n    time_span=0.0001s, test_ID=193, label=9, output_node=3, voltage=7.669329352211207e-05\n    time_span=0.0001s, test_ID=193, label=9, output_node=4, voltage=0.0040786853060126305\n    time_span=0.0001s, test_ID=193, label=9, output_node=5, voltage=-7.968123099999502e-05\n    time_span=0.0001s, test_ID=193, label=9, output_node=6, voltage=-0.0007988048018887639\n    time_span=0.0001s, test_ID=193, label=9, output_node=7, voltage=0.002586653456091881\n    time_span=0.0001s, test_ID=193, label=9, output_node=8, voltage=0.0035547807347029448\n    time_span=0.0001s, test_ID=193, label=9, output_node=9, voltage=0.007067729253321886\n    time_span=0.0001s, test_ID=193, label=9, output_node=sum, voltage=0.01018725149333477\n    Time consumed for 1 sample = 142.9061164855957 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '193'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=194, label=0, output_node=bkg, voltage=-0.007037848699837923\n    time_span=0.0001s, test_ID=194, label=0, output_node=0, voltage=0.004767928272485733\n    time_span=0.0001s, test_ID=194, label=0, output_node=1, voltage=-0.0046235062181949615\n    time_span=0.0001s, test_ID=194, label=0, output_node=2, voltage=-0.0009003984159789979\n    time_span=0.0001s, test_ID=194, label=0, output_node=3, voltage=-0.0012231074506416917\n    time_span=0.0001s, test_ID=194, label=0, output_node=4, voltage=-0.00040936251753009856\n    time_span=0.0001s, test_ID=194, label=0, output_node=5, voltage=0.0002450198517180979\n    time_span=0.0001s, test_ID=194, label=0, output_node=6, voltage=-0.0022948209661990404\n    time_span=0.0001s, test_ID=194, label=0, output_node=7, voltage=0.0007440238841809332\n    time_span=0.0001s, test_ID=194, label=0, output_node=8, voltage=0.0003804781299550086\n    time_span=0.0001s, test_ID=194, label=0, output_node=9, voltage=0.0033456175588071346\n    time_span=0.0001s, test_ID=194, label=0, output_node=sum, voltage=0.011741035617887974\n    Time consumed for 1 sample = 143.04227471351624 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '194'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=195, label=3, output_node=bkg, voltage=-0.006745020393282175\n    time_span=0.0001s, test_ID=195, label=3, output_node=0, voltage=0.0023486055433750153\n    time_span=0.0001s, test_ID=195, label=3, output_node=1, voltage=0.005274899769574404\n    time_span=0.0001s, test_ID=195, label=3, output_node=2, voltage=0.005839641205966473\n    time_span=0.0001s, test_ID=195, label=3, output_node=3, voltage=0.010786852799355984\n    time_span=0.0001s, test_ID=195, label=3, output_node=4, voltage=0.0028505974914878607\n    time_span=0.0001s, test_ID=195, label=3, output_node=5, voltage=0.00818725023418665\n    time_span=0.0001s, test_ID=195, label=3, output_node=6, voltage=0.002091633388772607\n    time_span=0.0001s, test_ID=195, label=3, output_node=7, voltage=0.00391932250931859\n    time_span=0.0001s, test_ID=195, label=3, output_node=8, voltage=0.012895418331027031\n    time_span=0.0001s, test_ID=195, label=3, output_node=9, voltage=0.009275896474719048\n    time_span=0.0001s, test_ID=195, label=3, output_node=sum, voltage=0.024047810584306717\n    Time consumed for 1 sample = 142.87357378005981 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '195'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=196, label=1, output_node=bkg, voltage=-0.003044820623472333\n    time_span=0.0001s, test_ID=196, label=1, output_node=0, voltage=0.0022480080369859934\n    time_span=0.0001s, test_ID=196, label=1, output_node=1, voltage=0.013447210192680359\n    time_span=0.0001s, test_ID=196, label=1, output_node=2, voltage=0.004240039736032486\n    time_span=0.0001s, test_ID=196, label=1, output_node=3, voltage=-0.0002609559742268175\n    time_span=0.0001s, test_ID=196, label=1, output_node=4, voltage=-0.00024900404969230294\n    time_span=0.0001s, test_ID=196, label=1, output_node=5, voltage=0.0035737049765884876\n    time_span=0.0001s, test_ID=196, label=1, output_node=6, voltage=0.004412350244820118\n    time_span=0.0001s, test_ID=196, label=1, output_node=7, voltage=0.0031673309858888388\n    time_span=0.0001s, test_ID=196, label=1, output_node=8, voltage=0.0069611556828022\n    time_span=0.0001s, test_ID=196, label=1, output_node=9, voltage=0.002191235078498721\n    time_span=0.0001s, test_ID=196, label=1, output_node=sum, voltage=0.016586653888225555\n    Time consumed for 1 sample = 142.65911865234375 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '196'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=197, label=6, output_node=bkg, voltage=-0.005171315278857946\n    time_span=0.0001s, test_ID=197, label=6, output_node=0, voltage=0.0013466135133057833\n    time_span=0.0001s, test_ID=197, label=6, output_node=1, voltage=0.0009741036337800324\n    time_span=0.0001s, test_ID=197, label=6, output_node=2, voltage=0.0014760957565158606\n    time_span=0.0001s, test_ID=197, label=6, output_node=3, voltage=0.0008107570465654135\n    time_span=0.0001s, test_ID=197, label=6, output_node=4, voltage=0.0020607567857950926\n    time_span=0.0001s, test_ID=197, label=6, output_node=5, voltage=0.0023207173217087984\n    time_span=0.0001s, test_ID=197, label=6, output_node=6, voltage=0.008688246831297874\n    time_span=0.0001s, test_ID=197, label=6, output_node=7, voltage=-0.0012589640682563186\n    time_span=0.0001s, test_ID=197, label=6, output_node=8, voltage=0.003098605666309595\n    time_span=0.0001s, test_ID=197, label=6, output_node=9, voltage=0.0005199203151278198\n    time_span=0.0001s, test_ID=197, label=6, output_node=sum, voltage=0.015403387136757374\n    Time consumed for 1 sample = 142.8042185306549 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '197'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=198, label=4, output_node=bkg, voltage=-0.005055777262896299\n    time_span=0.0001s, test_ID=198, label=4, output_node=0, voltage=0.0006792829371988773\n    time_span=0.0001s, test_ID=198, label=4, output_node=1, voltage=-0.002221115864813328\n    time_span=0.0001s, test_ID=198, label=4, output_node=2, voltage=0.00013545814726967365\n    time_span=0.0001s, test_ID=198, label=4, output_node=3, voltage=0.0010756971314549446\n    time_span=0.0001s, test_ID=198, label=4, output_node=4, voltage=0.006471115164458752\n    time_span=0.0001s, test_ID=198, label=4, output_node=5, voltage=-0.0024661351926624775\n    time_span=0.0001s, test_ID=198, label=4, output_node=6, voltage=0.0002480078546795994\n    time_span=0.0001s, test_ID=198, label=4, output_node=7, voltage=-0.0005318724433891475\n    time_span=0.0001s, test_ID=198, label=4, output_node=8, voltage=0.0013027888489887118\n    time_span=0.0001s, test_ID=198, label=4, output_node=9, voltage=0.006488047540187836\n    time_span=0.0001s, test_ID=198, label=4, output_node=sum, voltage=0.008476096205413342\n    Time consumed for 1 sample = 143.0208761692047 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '198'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=199, label=2, output_node=bkg, voltage=-0.005965139716863632\n    time_span=0.0001s, test_ID=199, label=2, output_node=0, voltage=0.0019003984052687883\n    time_span=0.0001s, test_ID=199, label=2, output_node=1, voltage=0.003062749281525612\n    time_span=0.0001s, test_ID=199, label=2, output_node=2, voltage=0.009628485888242722\n    time_span=0.0001s, test_ID=199, label=2, output_node=3, voltage=0.0022181274835020304\n    time_span=0.0001s, test_ID=199, label=2, output_node=4, voltage=-0.00014641426969319582\n    time_span=0.0001s, test_ID=199, label=2, output_node=5, voltage=-0.002848605625331402\n    time_span=0.0001s, test_ID=199, label=2, output_node=6, voltage=-0.00012649400741793215\n    time_span=0.0001s, test_ID=199, label=2, output_node=7, voltage=0.007098605390638113\n    time_span=0.0001s, test_ID=199, label=2, output_node=8, voltage=0.0007998008513823152\n    time_span=0.0001s, test_ID=199, label=2, output_node=9, voltage=-0.0012390437768772244\n    time_span=0.0001s, test_ID=199, label=2, output_node=sum, voltage=0.013694223947823048\n    Time consumed for 1 sample = 142.92731380462646 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '199'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    Finished! Safe to change code now.\n\n\n\n```python\ndf_temp = pandas.read_hdf((savePath / \"mppc_vol_meas.h5\").as_posix(), key='26')\ndf_temp\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th></th>\n      <th>0</th>\n      <th>1</th>\n      <th>2</th>\n      <th>3</th>\n      <th>4</th>\n      <th>5</th>\n      <th>6</th>\n      <th>7</th>\n      <th>8</th>\n      <th>9</th>\n      <th>...</th>\n      <th>994</th>\n      <th>995</th>\n      <th>996</th>\n      <th>997</th>\n      <th>998</th>\n      <th>999</th>\n      <th>1000</th>\n      <th>1001</th>\n      <th>1002</th>\n      <th>1003</th>\n    </tr>\n    <tr>\n      <th>output_node</th>\n      <th>time_range</th>\n      <th>repeats</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">0</th>\n      <th rowspan=\"5\" valign=\"top\">0.0001</th>\n      <th>0</th>\n      <td>0.024</td>\n      <td>0.027</td>\n      <td>0.018</td>\n      <td>0.002</td>\n      <td>-0.005</td>\n      <td>-0.008</td>\n      <td>0</td>\n      <td>0.016</td>\n      <td>0.026</td>\n      <td>0.032</td>\n      <td>...</td>\n      <td>0.01</td>\n      <td>0.008</td>\n      <td>0.006</td>\n      <td>-0.005</td>\n      <td>-0.012</td>\n      <td>-0.009</td>\n      <td>-0.004</td>\n      <td>-0.005</td>\n      <td>-0.005</td>\n      <td>0.003</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.033</td>\n      <td>0.028</td>\n      <td>0.025</td>\n      <td>0.015</td>\n      <td>0.005</td>\n      <td>0.002</td>\n      <td>0.004</td>\n      <td>0.007</td>\n      <td>0.008</td>\n      <td>0.01</td>\n      <td>...</td>\n      <td>0.02</td>\n      <td>0.029</td>\n      <td>0.043</td>\n      <td>0.033</td>\n      <td>0.035</td>\n      <td>0.033</td>\n      <td>0.013</td>\n      <td>0.009</td>\n      <td>0.018</td>\n      <td>0.027</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.011</td>\n      <td>0.008</td>\n      <td>0.006</td>\n      <td>0.007</td>\n      <td>0.004</td>\n      <td>-0.003</td>\n      <td>0.002</td>\n      <td>0.011</td>\n      <td>0.005</td>\n      <td>0.001</td>\n      <td>...</td>\n      <td>0.017</td>\n      <td>0.018</td>\n      <td>0.01</td>\n      <td>0.01</td>\n      <td>0.014</td>\n      <td>0.033</td>\n      <td>0.014</td>\n      <td>0.021</td>\n      <td>0.021</td>\n      <td>0.025</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.016</td>\n      <td>0.003</td>\n      <td>0.001</td>\n      <td>0.003</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>-0.002</td>\n      <td>-0.003</td>\n      <td>-0.007</td>\n      <td>...</td>\n      <td>0.013</td>\n      <td>0.014</td>\n      <td>0.025</td>\n      <td>0.032</td>\n      <td>0.037</td>\n      <td>0.043</td>\n      <td>0.033</td>\n      <td>0.026</td>\n      <td>0.021</td>\n      <td>0.016</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.002</td>\n      <td>-0.002</td>\n      <td>-0.003</td>\n      <td>-0.006</td>\n      <td>-0.006</td>\n      <td>0</td>\n      <td>0.004</td>\n      <td>0.011</td>\n      <td>0.02</td>\n      <td>0.013</td>\n      <td>...</td>\n      <td>0.036</td>\n      <td>0.021</td>\n      <td>0.008</td>\n      <td>0.001</td>\n      <td>0.01</td>\n      <td>0.029</td>\n      <td>0.036</td>\n      <td>0.04</td>\n      <td>0.033</td>\n      <td>0.016</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <th>...</th>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">bkg</th>\n      <th rowspan=\"5\" valign=\"top\">0.0001</th>\n      <th>95</th>\n      <td>0.008</td>\n      <td>0.009</td>\n      <td>0.015</td>\n      <td>0.017</td>\n      <td>0.008</td>\n      <td>0</td>\n      <td>0.006</td>\n      <td>0.012</td>\n      <td>0.011</td>\n      <td>0.007</td>\n      <td>...</td>\n      <td>-0.004</td>\n      <td>-0.005</td>\n      <td>-0.002</td>\n      <td>-0.002</td>\n      <td>-0.006</td>\n      <td>-0.014</td>\n      <td>-0.019</td>\n      <td>-0.022</td>\n      <td>-0.024</td>\n      <td>-0.019</td>\n    </tr>\n    <tr>\n      <th>96</th>\n      <td>0.002</td>\n      <td>-0.002</td>\n      <td>-0.002</td>\n      <td>-0.002</td>\n      <td>-0.005</td>\n      <td>-0.008</td>\n      <td>-0.006</td>\n      <td>-0.002</td>\n      <td>-0.003</td>\n      <td>-0.001</td>\n      <td>...</td>\n      <td>-0.003</td>\n      <td>-0.006</td>\n      <td>-0.011</td>\n      <td>-0.021</td>\n      <td>-0.026</td>\n      <td>-0.021</td>\n      <td>-0.019</td>\n      <td>-0.012</td>\n      <td>-0.007</td>\n      <td>-0.007</td>\n    </tr>\n    <tr>\n      <th>97</th>\n      <td>-0.006</td>\n      <td>-0.003</td>\n      <td>-0.004</td>\n      <td>-0.004</td>\n      <td>-0.005</td>\n      <td>-0.014</td>\n      <td>-0.022</td>\n      <td>-0.022</td>\n      <td>-0.018</td>\n      <td>-0.006</td>\n      <td>...</td>\n      <td>-0.003</td>\n      <td>-0.021</td>\n      <td>-0.034</td>\n      <td>-0.022</td>\n      <td>-0.005</td>\n      <td>0.014</td>\n      <td>0.013</td>\n      <td>0.002</td>\n      <td>-0.015</td>\n      <td>-0.02</td>\n    </tr>\n    <tr>\n      <th>98</th>\n      <td>-0.021</td>\n      <td>-0.019</td>\n      <td>-0.011</td>\n      <td>-0.005</td>\n      <td>-0.006</td>\n      <td>-0.006</td>\n      <td>-0.007</td>\n      <td>-0.003</td>\n      <td>-0.003</td>\n      <td>-0.002</td>\n      <td>...</td>\n      <td>-0.007</td>\n      <td>-0.003</td>\n      <td>0.004</td>\n      <td>0.006</td>\n      <td>0.004</td>\n      <td>0.009</td>\n      <td>0.01</td>\n      <td>0.008</td>\n      <td>0.013</td>\n      <td>0.005</td>\n    </tr>\n    <tr>\n      <th>99</th>\n      <td>-0.007</td>\n      <td>-0.007</td>\n      <td>-0.008</td>\n      <td>-0.014</td>\n      <td>-0.018</td>\n      <td>-0.019</td>\n      <td>-0.022</td>\n      <td>-0.014</td>\n      <td>-0.008</td>\n      <td>-0.01</td>\n      <td>...</td>\n      <td>-0.007</td>\n      <td>-0.009</td>\n      <td>-0.015</td>\n      <td>-0.011</td>\n      <td>-0.006</td>\n      <td>-0.01</td>\n      <td>-0.009</td>\n      <td>-0.004</td>\n      <td>-0.003</td>\n      <td>-0.004</td>\n    </tr>\n  </tbody>\n</table>\n<p>10200 rows \u00d7 1004 columns</p>\n</div>\n\n\n\n\n```python\ndf\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th></th>\n      <th>0</th>\n      <th>1</th>\n      <th>2</th>\n      <th>3</th>\n      <th>4</th>\n      <th>5</th>\n      <th>6</th>\n      <th>7</th>\n      <th>8</th>\n      <th>9</th>\n      <th>...</th>\n      <th>994</th>\n      <th>995</th>\n      <th>996</th>\n      <th>997</th>\n      <th>998</th>\n      <th>999</th>\n      <th>1000</th>\n      <th>1001</th>\n      <th>1002</th>\n      <th>1003</th>\n    </tr>\n    <tr>\n      <th>output_node</th>\n      <th>time_range</th>\n      <th>repeats</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">0</th>\n      <th rowspan=\"5\" valign=\"top\">0.0001</th>\n      <th>0</th>\n      <td>0.015</td>\n      <td>0.005</td>\n      <td>-0.006</td>\n      <td>-0.018</td>\n      <td>-0.023</td>\n      <td>-0.02</td>\n      <td>-0.02</td>\n      <td>-0.016</td>\n      <td>-0.011</td>\n      <td>-0.014</td>\n      <td>...</td>\n      <td>-0.012</td>\n      <td>-0.006</td>\n      <td>-0.003</td>\n      <td>0.005</td>\n      <td>0.012</td>\n      <td>0.013</td>\n      <td>0.01</td>\n      <td>0.011</td>\n      <td>0.015</td>\n      <td>0.016</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>-0.007</td>\n      <td>-0.006</td>\n      <td>-0.003</td>\n      <td>0</td>\n      <td>0.011</td>\n      <td>0.018</td>\n      <td>0.014</td>\n      <td>0.016</td>\n      <td>0.015</td>\n      <td>0.013</td>\n      <td>...</td>\n      <td>-0.003</td>\n      <td>-0.007</td>\n      <td>-0.01</td>\n      <td>-0.012</td>\n      <td>-0.012</td>\n      <td>-0.009</td>\n      <td>-0.016</td>\n      <td>-0.014</td>\n      <td>-0.005</td>\n      <td>0.001</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.008</td>\n      <td>0.011</td>\n      <td>0.01</td>\n      <td>0.005</td>\n      <td>0.005</td>\n      <td>-0.001</td>\n      <td>-0.005</td>\n      <td>0.005</td>\n      <td>0.002</td>\n      <td>-0.007</td>\n      <td>...</td>\n      <td>0.014</td>\n      <td>0.008</td>\n      <td>-0.002</td>\n      <td>-0.002</td>\n      <td>-0.01</td>\n      <td>-0.019</td>\n      <td>-0.018</td>\n      <td>-0.018</td>\n      <td>-0.01</td>\n      <td>-0.001</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.013</td>\n      <td>0.022</td>\n      <td>0.033</td>\n      <td>0.024</td>\n      <td>0.014</td>\n      <td>0</td>\n      <td>-0.007</td>\n      <td>-0.007</td>\n      <td>-0.005</td>\n      <td>-0.001</td>\n      <td>...</td>\n      <td>-0.009</td>\n      <td>-0.001</td>\n      <td>0.008</td>\n      <td>0.01</td>\n      <td>0.009</td>\n      <td>0</td>\n      <td>-0.009</td>\n      <td>0.001</td>\n      <td>0.009</td>\n      <td>0.01</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>-0.011</td>\n      <td>-0.008</td>\n      <td>-0.005</td>\n      <td>-0.003</td>\n      <td>0.006</td>\n      <td>0.014</td>\n      <td>0.016</td>\n      <td>0.01</td>\n      <td>-0.004</td>\n      <td>-0.011</td>\n      <td>...</td>\n      <td>-0.01</td>\n      <td>-0.011</td>\n      <td>-0.012</td>\n      <td>-0.001</td>\n      <td>0.012</td>\n      <td>0.04</td>\n      <td>0.011</td>\n      <td>0.003</td>\n      <td>-0.005</td>\n      <td>-0.004</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <th>...</th>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">bkg</th>\n      <th rowspan=\"5\" valign=\"top\">0.0001</th>\n      <th>95</th>\n      <td>-0.024</td>\n      <td>-0.02</td>\n      <td>-0.019</td>\n      <td>-0.016</td>\n      <td>-0.019</td>\n      <td>-0.023</td>\n      <td>-0.025</td>\n      <td>-0.02</td>\n      <td>-0.012</td>\n      <td>-0.009</td>\n      <td>...</td>\n      <td>-0.003</td>\n      <td>-0.004</td>\n      <td>-0.002</td>\n      <td>-0.01</td>\n      <td>-0.017</td>\n      <td>-0.022</td>\n      <td>-0.027</td>\n      <td>-0.021</td>\n      <td>-0.012</td>\n      <td>-0.007</td>\n    </tr>\n    <tr>\n      <th>96</th>\n      <td>-0.009</td>\n      <td>-0.012</td>\n      <td>-0.012</td>\n      <td>-0.009</td>\n      <td>-0.006</td>\n      <td>-0.006</td>\n      <td>-0.01</td>\n      <td>-0.011</td>\n      <td>-0.014</td>\n      <td>-0.013</td>\n      <td>...</td>\n      <td>-0.007</td>\n      <td>-0.007</td>\n      <td>-0.004</td>\n      <td>-0.003</td>\n      <td>0.001</td>\n      <td>0.009</td>\n      <td>0.008</td>\n      <td>0.013</td>\n      <td>0.014</td>\n      <td>0.004</td>\n    </tr>\n    <tr>\n      <th>97</th>\n      <td>-0.006</td>\n      <td>-0.01</td>\n      <td>-0.014</td>\n      <td>-0.011</td>\n      <td>-0.014</td>\n      <td>-0.014</td>\n      <td>-0.009</td>\n      <td>-0.007</td>\n      <td>-0.003</td>\n      <td>0.003</td>\n      <td>...</td>\n      <td>0.001</td>\n      <td>-0.008</td>\n      <td>-0.003</td>\n      <td>-0.003</td>\n      <td>-0.001</td>\n      <td>0</td>\n      <td>0.001</td>\n      <td>0.004</td>\n      <td>0.007</td>\n      <td>0.005</td>\n    </tr>\n    <tr>\n      <th>98</th>\n      <td>-0.007</td>\n      <td>-0.009</td>\n      <td>-0.006</td>\n      <td>-0.009</td>\n      <td>-0.014</td>\n      <td>-0.02</td>\n      <td>-0.027</td>\n      <td>-0.026</td>\n      <td>-0.022</td>\n      <td>-0.013</td>\n      <td>...</td>\n      <td>0.004</td>\n      <td>0.006</td>\n      <td>0.003</td>\n      <td>-0.002</td>\n      <td>-0.005</td>\n      <td>-0.009</td>\n      <td>-0.01</td>\n      <td>-0.011</td>\n      <td>-0.009</td>\n      <td>-0.005</td>\n    </tr>\n    <tr>\n      <th>99</th>\n      <td>-0.003</td>\n      <td>-0.008</td>\n      <td>-0.011</td>\n      <td>-0.011</td>\n      <td>-0.012</td>\n      <td>-0.01</td>\n      <td>-0.011</td>\n      <td>-0.006</td>\n      <td>0.002</td>\n      <td>0.003</td>\n      <td>...</td>\n      <td>-0.005</td>\n      <td>-0.002</td>\n      <td>-0.005</td>\n      <td>-0.009</td>\n      <td>-0.01</td>\n      <td>-0.011</td>\n      <td>-0.009</td>\n      <td>-0.005</td>\n      <td>0</td>\n      <td>0.001</td>\n    </tr>\n  </tbody>\n</table>\n<p>1200 rows \u00d7 1004 columns</p>\n</div>\n\n\n\n\n```python\ndf_volTraces.loc[0,].dropna(axis=\"columns\").astype(float).mean(level=[0,1]).mean(axis=1)*100\n```\n\n\n\n\n    output_node  time_range\n    0            0.0001        1.108908\n    1            0.0001        0.135558\n    2            0.0001        0.954472\n    3            0.0001        1.069739\n    4            0.0001        0.617894\n    5            0.0001        0.339468\n    6            0.0001        0.495554\n    7            0.0001        1.219645\n    8            0.0001        0.718153\n    9            0.0001        0.582032\n    dtype: float64\n\n\n\n\n```python\ndf_all_acts.loc[0,0]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>norm(W)norm(X)</th>\n      <th>sum(norm(X))</th>\n      <th>sum(norm(W))</th>\n      <th>Wx</th>\n      <th>Wx+b</th>\n      <th>a</th>\n      <th>a_true</th>\n    </tr>\n    <tr>\n      <th>output node</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>12298065.0</td>\n      <td>18435480.0</td>\n      <td>131674194.0</td>\n      <td>0.956051</td>\n      <td>-0.552092</td>\n      <td>0.000000</td>\n      <td>0.453606</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>5819807.0</td>\n      <td>18435480.0</td>\n      <td>79005915.0</td>\n      <td>-10.673519</td>\n      <td>-10.590518</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>11277890.0</td>\n      <td>18435480.0</td>\n      <td>122052825.0</td>\n      <td>1.561747</td>\n      <td>1.957514</td>\n      <td>1.957514</td>\n      <td>1.641961</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>11975186.0</td>\n      <td>18435480.0</td>\n      <td>117449433.0</td>\n      <td>5.828900</td>\n      <td>4.467121</td>\n      <td>4.467121</td>\n      <td>5.462904</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>9023111.0</td>\n      <td>18435480.0</td>\n      <td>101583315.0</td>\n      <td>-3.535693</td>\n      <td>-3.061699</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>7405579.0</td>\n      <td>18435480.0</td>\n      <td>84927987.0</td>\n      <td>-1.884187</td>\n      <td>-0.552092</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>8327609.0</td>\n      <td>18435480.0</td>\n      <td>110240649.0</td>\n      <td>-8.759407</td>\n      <td>-8.080911</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>13082552.0</td>\n      <td>18435480.0</td>\n      <td>119804076.0</td>\n      <td>11.431123</td>\n      <td>11.995940</td>\n      <td>11.995940</td>\n      <td>12.365005</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>9697962.0</td>\n      <td>18435480.0</td>\n      <td>102857040.0</td>\n      <td>1.703591</td>\n      <td>-0.552092</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>8986474.0</td>\n      <td>18435480.0</td>\n      <td>88276635.0</td>\n      <td>3.274412</td>\n      <td>1.957514</td>\n      <td>1.957514</td>\n      <td>2.905186</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf_volTraces.to_hdf((savePath / \"mppc_vol_meas.h5\").as_posix(), key=\" \", mode='w')\njoblib.dump([oscope_info(oscope),], savePath / 'exp_info.pkl')\n```\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: ' '; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\pandas\\core\\generic.py:2505: PerformanceWarning: \n    your performance may suffer as PyTables will pickle object types that it cannot\n    map directly to c-types [inferred_type->floating,key->block0_values] [items->Int64Index([   0,    1,    2,    3,    4,    5,    6,    7,    8,    9,\n                ...\n                1590, 1591, 1592, 1593, 1594, 1595, 1596, 1597, 1598, 1599],\n               dtype='int64', length=1600)]\n    \n      encoding=encoding,\n\n\n\n\n\n    ['D:\\\\McMahon lab Dropbox\\\\peter mcmahon\\\\tw329\\\\Experiments\\\\11_05_20_Perceptron_MPPC\\\\Percep_4bit_5x_gap2px_MPPC_1107_210954\\\\exp_info.pkl']\n\n\n\n\n```python\nblackImage_PIL = Image.open((phoneImagePath / \"black.png\").as_posix())\nblackImage_byte = PIL_to_bytestream(blackImage_PIL)\naoab.write(blackImage_byte)\n```\n\n# Troubleshoot Blocks\n\n\n```python\n# Debug alignment \nfrom PIL import Image\ntestImagePath = phoneImagePath / f\"test_digit_7_00000.png\"\nimToPhone_PIL = Image.open(testImagePath)\nimToPhone_byte = PIL_to_bytestream(imToPhone_PIL)\nslm.updateArray(slm_weights_numpy[\"ordered\"])\naoab.write(imToPhone_byte)\n```\n\n\n```python\n# Debug alignment \nfrom PIL import Image\nalignImagePath = resultPath.parent / \"alignment_images\" \nimToPhone_PIL = Image.open((alignImagePath / \"TheGreenViewFinder.png\").as_posix())\nimToPhone_byte = PIL_to_bytestream(imToPhone_PIL)\naoab.write(imToPhone_byte)\nimToSLM = Image.open((alignImagePath / \"TheGreenViewFinder_SLM.bmp\").as_posix())\nslm.updateArray(np.array(imToSLM))\n```\n\n\n```python\n# Debug alignment \nfrom PIL import Image\nalignImagePath = resultPath.parent / \"alignment_images\" \nimToPhone_PIL = Image.open((alignImagePath / \"Horizontal_stripes_period_4.png\").as_posix())\nimToPhone_byte = PIL_to_bytestream(imToPhone_PIL)\naoab.write(imToPhone_byte)\nimToSLM = Image.open((alignImagePath / \"Horizontal_stripes_period_4_SLM.bmp\").as_posix())\nslm.updateArray(np.array(imToSLM))\n```\n\n\n```python\n# Debug alignment \nfrom PIL import Image\nalignImagePath = resultPath.parent / \"alignment_images\" \nimToPhone_PIL = Image.open((alignImagePath / \"Vertical_stripes_period_4.png\").as_posix())\nimToPhone_byte = PIL_to_bytestream(imToPhone_PIL)\naoab.write(imToPhone_byte)\nimToSLM = Image.open((alignImagePath / \"Vertical_stripes_period_4_SLM.bmp\").as_posix())\nslm.updateArray(np.array(imToSLM))\n```\n", "meta": {"hexsha": "e52cdd4100b01b2db9f39902f41ce59abf54701b", "size": 467809, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "data_collection/run_MLP_MPPC_fc2_2pcts.ipynb", "max_stars_repo_name": "ConnectionMaster/ONN-device-control", "max_stars_repo_head_hexsha": "0b909c48272ec0f92c79dfa1d7fb8b8b6c55766a", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-18T15:59:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T03:00:19.000Z", "max_issues_repo_path": "data_collection/run_MLP_MPPC_fc2_2pcts.ipynb", "max_issues_repo_name": "mcmahon-lab/ONN-device-control", "max_issues_repo_head_hexsha": "ecb0b6e8afef57c3c9ceeaa7e00d76860135a8ab", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-11T14:44:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-11T14:44:56.000Z", "max_forks_repo_path": "data_collection/run_MLP_MPPC_fc2_2pcts.ipynb", "max_forks_repo_name": "ConnectionMaster/ONN-device-control", "max_forks_repo_head_hexsha": "0b909c48272ec0f92c79dfa1d7fb8b8b6c55766a", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-11T14:43:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-11T14:43:40.000Z", "avg_line_length": 60.0679250128, "max_line_length": 55416, "alphanum_fraction": 0.6202916147, "converted": true, "num_tokens": 60592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.05500528248426954, "lm_q1q2_score": 0.01917732415581007}}
{"text": "<div class=\"alert alert-block alert-warning\">\n<b>Disclaimer:</b> The objective of this notebook is to introduce Project Jupyter and then give a short introduction about its functionalities.\n</div>\n\n# What is the Jupyter project?\n\n\n\n## History \nProject *Jupyter* is a non-profit, open-source project, born out of the *IPython* Project in 2014 as it evolved to support interactive data science and scientific computing across many programming languages.\n\n*Jupyter* is an acronym for **Ju**lia, **Pyt**hon, and **R**. These three languages were the first target languages of the *Jupyter* application, but nowadays, the notebook technology also support many other languages (C, C#, C++, Scala, Ruby, Perl, Javascript, Fortran,...).\n\n*Jupyter* allows users to create and share documents that contain live code, equations, visualizations and narrative text.\n\n**References**  \n- https://jupyter.org\n- https://www.nature.com/articles/d41586-018-07196-1\n- https://opencredo.com/blogs/writing-a-custom-jupyterhub-spawner/\n\n## What are Jupyter hub, lab notebook app and notebook document? \n\n### JupyterHub\nFrom https://jupyter.org/hub\n> *JupyterHub* brings the power of notebooks to groups of users. It gives them access to computational environments and resources without burdening with installation and maintenance tasks. Users can get their work done in their own workspaces on shared resources which can be managed efficiently by system administrators. *JupyterHub* runs in the cloud or on users' own hardware, and makes it possible to serve a pre-configured data science environment to any user in the world. It is customizable and scalable, and is suitable for small and large teams, academic courses, and large-scale infrastructure. \n\n### JupyterLab\n<div>\n\n<div style=\"text-align:center\"> <span style=\"font-style:italic; font-size:1em;\"> JupterLab launcher </span></div>\n</div>\n\n*Jupyterlab* is the next-generation web interface for the project *Jupyter*. It offers all the building blocks of the *Jupyter Notebook*, with additional drag-and-drop functionality, file browsers, data viewers, text editors and a command console. Users can arrange multiple documents and activities side by side in the work area using tabs and splitters. Documents and activities integrate with each other, enabling new workflows for interactive computing. *JupyterLab* will eventually replace the classic *Jupyter Notebook App*.\n\n<div>\n\n<div style=\"text-align:center\"> <span style=\"font-style:italic; font-size:1em;\"> Example of layout of JupterLab showing a terminal, a running jupyter notebook, a rendered markdown file and the file browser.</span></div>\n</div>\n\n**References:**  \n- https://github.com/jupyterlab/jupyterlab\n\n- https://jupyterlab.readthedocs.io/en/latest/\n\n### Jupyter Notebook App\nA *Jupyter Notebook App* is a web-based interactive development environment for creating notebook documents.\n\n### Jupyter Notebook document\nA *Jupyter Notebook* document consists of a list of input and output ordered cells that can contain computer code, [Markdown text](https://en.wikipedia.org/wiki/Markdown), mathematical expressions, plots, figures, links,... It is a [JavaScript Object Notation](https://en.wikipedia.org/wiki/JSON) (JSON) document. Its standard extension is `.ipynb`; but it can be converted to different formats such as `html`, slides, `pdf` or `Python` script.\n\n**Reference:** https://jupyter-notebook.readthedocs.io/en/stable/\n\n#### Kernels \n*Jupyter* supports over 40 programming languages including Python, Julia, R, C. \n\n*Notebook kernels* are processes that run interactive code in a particular programming language and return output to the user. \n\nOpening a *Jupyter Notebook* document automatically launches the associated kernel. When executing the notebook either cell-by-cell or in its entirety, this kernel performs the computation and produces the results, which are displayed in the output cells of the *Jupyter Notebook* document. \n\n[TryJupyter](https://jupyter.org/try) to try in your browser without any required installation.\n\n**Reference:** https://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/what_is_jupyter.html\n\n# Short introduction about Jupyter notebook\n\n## Jupyter dashboard\nThe dashboard displays the folders and notebooks in the current directory and allows users to launch or create *Jupyter* notebooks in any subfolders. \n\n<div>\n\n<div style=\"text-align:center\"> <span style=\"font-style:italic; font-size:1em;\"> Example of Jupyter dashboard.</span></div>\n</div>\n\n### Exercises\n#### Exercise 1\n- Create a new folder by clicking on `New` (upper right corner)\n\n\n\n- Rename the folder 'MyNewFolder'.  \nTo do so, click in the checkbox next to the directory name and choose `Rename`. A new window will open in which you can type the new name of the directory. You can use this same process to rename any folder.\n- Remove this newly created folder.  \nIn this case, make sure that the checkbox next to your folder is still ticked, click on the 'Trash bin' button and confirm the deletion.\n\n#### Exercise 2\n- Create a new notebook by clicking the `New` dropdown (upper right corner) and select `Python 3` as kernel.\n\n\n\n- You should get a new tab in your browser, which looks like the figure below\n\n\n\n- Rename it 'MyNewNotebook' by clicking on the 'Untitled' at the top of the page.\n\n\n\n- Go back to the dashboard (clicking on the `Home` tab, *i.e.* the previously open tab in your browser) and check that your notebook is in the displayed list with a green icon (showing that it is running).\n\n- To close the notebook, check that the checkbox is ticked and click on `Shutdown` in the top left set of icons as show below\n\n<div>\n\n<div style=\"text-align:center\"> <span style=\"font-style:italic; font-size:1em;\"> How to close a notebook: select the notebook you want to close by ticking the checkbox next to it and then click on the `Shutdown` button.</span></div>\n</div>\n\n#### Note\nThe material used during this half-day training is composed of different notebooks stored in the `python-ikon-course/notebooks` folder.\n\n**References**\n- [Python for Data Science Cheat Sheet - Jupyter notebook](https://datacamp-community-prod.s3.amazonaws.com/48093c40-5303-45f4-bbf9-0c96c0133c40)\n\n- [Jupyter notebook cheat sheet from edureka!](https://www.edureka.co/blog/wp-content/uploads/2018/10/Jupyter_Notebook_CheatSheet_Edureka.pdf)\n\n## Jupyter notebook\n### Menu bar and toolbar\n<div>\n\n<div style=\"text-align:center\"> <span style=\"font-style:italic; font-size:1em;\"> Menubar, toolbar and additional buttons and dropdowns related to installed notebook extensions \"nbextensions\", such as spellchecker,opening the command panel... </span></div>\n</div>\n\nThe menu bar presents different options that may be used to manipulate how the notebook functions. For example, from `Kernel`, you can interrupt, change or restart the kernel with the option of clearing the cells' output.  \nThe toolbar gives a quick access to the most-used operations by clicking on an icon. Among these operations, one can save, add or remove a cell, change between code cell and a markdown cell, or run a cell.\n\n### Cells\n#### Types of cells\nThe content of the notebook is a linear sequence of cells, where users can write code or text on mutiple lines. The content of each cell can be executed using `<shift>+<enter>` or by clicking on the `Play` button of the toolbar. \n\n#### Modal editor\nDepending on which mode the Notebook is in, typing on the keyboard can have different outcomes. There are two possible modes:\n- **Edit mode**  \nThe *Edit mode* is indicated by a green cell border and a prompt in the cell allowing you to type in.\n\n\n\nTo enter the *Edit mode*, press `<enter>` or click on the cell you want to edit.\n\n- **Command mode**  \nThe *Command mode* is indicated by a grey cell border with a blue left margin\n\n\n\nIn the *Command mode*,  \n- you can edit the notebook as a whole, but you cannot type into individual cells.  \n- the keyboard is mapped to a set of shortcuts that let you perform notebook and cell actions efficiently. For example, if you are in command mode and you press `l`, you will display the line numbers in the current cell - no modifier is needed. The list of defined \"Keyboard shortcuts\" can be accessed by clicking on the `Help` dropdown of the menu bar.\n\nNote that trying to type into a cell when in the *Command mode* might result in unexpected things to happen. \n\nTo enter the *Command mode*, press `<esc>` or click outside a cell\u2019s editor area. Pressing `<control>+<enter>` will run the current cell and also enter the *Command mode*.\n\n#### Running the cells\nTo run a cell, use `<shift>+<enter>` or press the `Play` button in the toolbar.\nThe output depends on the cell type:\n- a markdown cell is rendered\n- for a code cell, its content is sent to the associated kernel and the result of the computation is displayed below the input cell, which is marked with '[\\*]' indicating that the kernel is running and then with '[$n$]', $n$ being a number indicating that this cell is the $n^{th}$ code cell to be run as shown below:\n\n\n  \n**Exercise**\n- Try typing something like `print(\"Hello World\")` into the cell below (it should be a *Code* cell).  \n- To run the code in the cell and see the output, click the Run button (`Play` icon) on the toolbar, or press `<shift>+<enter>`:\n\n\n```python\n# -- YOUR CODE BELOW --\n\n```\n\n#### Saving your Notebook\nOnce you start editing your Notebook, it is best practice to save it regularly. Pressing `<ctrl> + S` or `<command> + S` will save your notebook by calling the \"Save and Checkpoint\" command (from the `File` dropdown in the menu bar).\n\n**Note:** What is a checkpoint?  \nFrom https://www.codecademy.com/articles/how-to-use-jupyter-notebooks\n> Every time you create a new notebook, a checkpoint file is created as well as your notebook file; it will be located within a hidden subdirectory of your save location called .ipynb_checkpoints and is also a .ipynb file. By default, *Jupyter* will autosave your notebook every 120 seconds to this checkpoint file without altering your primary notebook file. When you \"Save and Checkpoint,\" both the notebook and checkpoint files are updated. Hence, the checkpoint enables you to recover your unsaved work in the event of an unexpected issue. You can revert to the checkpoint from the menu via \"File > Revert to Checkpoint.\"\n\n#### Closing your Notebook\nAs mentioned above, when a notebook is opened, its kernel is automatically started. Closing the notebook browser tab will not shut down the kernel.\n\nTo shut down the notebook and its kernel, from the menu bar of the notebook, click on  `File` and select `Close and Halt`. Another option is, from the Notebook Dashboard, to select the *Running* notebook you want to close and then click on the `Shutdown` button.\n\n#### Downloading your Notebook\nIf you want to run the Notebook you created on your own system or if you want to convert it to another format (`Python` script, `.pdf`...), it can be downloaded and converted using, from the `File` dropdown, `Downloads as`.\n\n### Short tutorial about Markdown\nBelow are a few examples of what can be done in Markdown.\n\n**References**  \n- https://www.markdowntutorial.com/ \n- https://guides.github.com/features/mastering-markdown/\n\n#### Fonts\nYou can write text in *italic*, **bold**.  \n\nHere is a blockquote:\n\n> This is a quote.  \n  It can be on several lines.\n\n##### LaTeX equations\nLaTeX equations can be written in Markdown cells, such as\n\n$$\\psi_f(s)=\\sum_{n=0}^{\\infty}\\frac{1}{n^s} \\qquad \\beta(t)=\\prod_p\\frac{1}{\\alpha - p^{-t}} \\qquad I=\\int_0^{\\pi}\\sin^2(\\omega t)$$\n\n$$\\begin{equation*}\n\\mathbf{V}_1 \\times \\mathbf{V}_2 =  \\begin{vmatrix}\n\\mathbf{i} & \\mathbf{j} & \\mathbf{k} \\\\\n\\frac{\\partial X}{\\partial u} &  \\frac{\\partial Y}{\\partial u} & 0 \\\\\n\\frac{\\partial X}{\\partial v} &  \\frac{\\partial Y}{\\partial v} & 0\n\\end{vmatrix}\n\\end{equation*} $$\n\n*Maxwell's equations*\n\n$$\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\   \\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align} $$\n\n##### Embedded code\nCode can also be written in markdown using specific languages' highlighting. For example, using the Python syntax:\n\n```python\nprint('bar')\n```\n\n##### Colors\nWe can write text in different colors, for example, <font color='red'>red</font>, <font color='blue'>blue</font>... \n\n#### Layout\nYou can add horizontal rules:\n\n---\n\n##### Headings\nExamples of the hierarchy of headings:\n\n---\n\n# Header 1\n## Header 2\n### Header 3 \n#### Header 4 ####\n##### Header 5 #####\n###### Header 6 ######\n\n---\n\n#### Lists\nYou can build nested itemized or enumerated lists:\n\n* First element of list\n    - Sublist item1\n        - Subsublist\n    - Sublist item2\n        - Subsublist item1\n        - Subsublist item2\n* Second element of list\n  - Sublist\n* Third element of list\n  - Sublist\n\nNow another list:\n\n1. First element of enumerated list\n    1. Example of embedded enumerated list\n    2. Second iem of this enumerated sublist\n2. Second element of enumerated list\n3. Third element of enumerated list\n\n#### Links\nYou can also add links:\n\n[Jupyter website](https://jupyter.org)\n\n#### Tables     \nYou can create tables very easily\n\n| Header    | in first    | row       |\n| :---      |   :----:    |      ---: |\n| left      | centered    | right     |\n| aligned   | text        | aligned   |\n\nNot even aligning the borders and you can modify the font style with stars double stars or quotes\n\nMarkdown | Less | Pretty\n--- | --- | ---\n*Still* | `renders` | **nicely**\n1 | 2 | 3\n\n#### Magic commands\nMagic commands are enhancements that `IPython` offers compared to the standard Python shell. These magic commands act as convenient functions where `Python` syntax is not the most natural one. In other words, you can run code in different languages in different cells within your notebook.\n\n##### Types of magic commands\n- **Line magics**  \nThey use input on the same line. They start with **%** character.\n- **Cell magics**  \nThey start with **%%** characters. They can operate on multiline inputs.  \n\n*Examples:*  \n- `%lsmagic`: list all magic commands\n- `%history`: display previous inputs at once\n- `%run`: run external code  \nFor example\n```python\n# the following command will execute and show the output from all code cells of the specified notebook\n%run ./plotting-with-matplotlib.ipynb\n```\n- `%who`: list all variables of global scope.\n```python\n%who str\n```\n\n- `%matplotline inline` to show matplotlib plots inline the notebook\n- `%%writefile` magic saves the contents of that cell to an external file. \n- `%pycat` does the opposite, and shows you (in a popup) the syntax highlighted contents of an external file.\n\n*Example:* using the following two cells, you start with writing the content of the first cell in a `Python` script, `simple_python_script.py`, and you execute it in the second cell.\n\n\n```python\n%%writefile simple_python_script.py\n\ndef print_info():\n    import datetime\n    now = datetime.datetime.now()\n    print(\"This is a test of magic commands run on {}\". format(now))\n    \nprint_info()\n```\n\n\n```python\n%run simple_python_script.py\n```\n\n##### Executing shell commands\nAnother useful modifier is the exclamation mark **!**.\nIt allows to execute shell commands from the notebook. Below are a few  examples:  \n\nTo check the *Jupyter notebooks* in the same folder as the running document:  \n``` python\n!ls *.ipynb\n```\n\nTo check packages, you can use\n``` python\n!pip install numpy\n!pip list | grep pandas\n```\n\n**Note:** Difference between **!** and **%**  \n\nFrom https://stackoverflow.com/questions/45784499/difference-between-and-in-jupyter-notebooks  \n> **!** calls out to a shell (in a new process), while **%** affects the notebook itself. Many **%** commands have no shell equivalent.  \n`!cd foo`, by itself, has no lasting effect, since the process with the changed directory immediayely terminates. `%cd foo` changes the current directory of the notebook process, which is a lasting effect.\n\n**References:**\n- [Built-in magic commands](https://ipython.readthedocs.io/en/stable/interactive/magics.html)\n\n- [demonstration of how to use Python, Julia, Fortran and R cooperatively to analyze data, in the same process](https://nbviewer.jupyter.org/gist/fperez/5b49246af4e340c37549265a90894ce6/polyglot-ds.ipynb)\n\n##### Examples using HTML, bash and perl\nCode cells can be run using a different kernel, for example, `Html`, `LaTeX`, `bash`... \n\n\n```bash\n%%bash\necho $HOME\n```\n\n\n```python\n%%HTML\n<H4>Text entered in code cell, rendered as HTML</H4>\n```\n\n\n```perl\n%%perl\n@months = (\"Jan\", \"Feb\", \"Mar\");\nprint($months[1])\n```\n\n# Inline help\n\n\n```python\nhelp([])\n```\n\nThe `help` function output the documentation for an object.\n\n\n```python\nhelp(dict())\n```\n\nAnother way to get help with Jupyter and ipython os to use the '?' at the end of an object.\n\n\n```python\ndict?\n```\n\nTyping the name of an object on the last line in a cell output information about the object\n\n\n```python\na = dict(a=3, b=5)\na\n```\n\nbut it has to be on the last line. The following will not create an output\n\n\n```python\nb = range(10)\nb\nc = 3\n```\n\nunless we use `print`\n\n\n```python\nb = range(10)\nprint(b)\nc = 3\n```\n\nThe wonderful **`TAB`** key. `TAB` invokes auto-completion.\n\nTry type \"l\" immediately followed by TAB in the cell below and see what happens\n\n\n```python\n# -- YOUR CODE BELOW --\n\n```\n\nIt list the ways that the \"l\" can be completed. If there is only one option, it will just complete your input for you. If you type \"li\" followed by `TAB` it will list those starting with \"li\" and so on. Note that you can select from the drop down menu that appears.\n\nTry to type 'from numpy import ' followed by `TAB`. \n\n\n```python\n# -- YOUR CODE BELOW --\n\n```\n\n## Customizing my notebook\nThere is a number of ways to add features and customize your jupyter notebooks. For example, with [Jupyter Notebook extensions](https://towardsdatascience.com/jupyter-notebook-extensions-517fa69d2231), one can include:\n- table of contents\n- add a spellchecker\n- scratchpad\n- freeze (read-only cells)\n\n## Examples in scientific community\n  - [neutron imaging community](https://github.com/neutrons/IPythonNotebookTutorial)\n  - [icet tutorials](https://gitlab.com/materials-modeling/icet-tutorials): scientific software for constructing atomic scale models of materials\n  - [Atomic Simulation Environment](https://github.com/ajjackson/ase-tutorial-symmetry)\n  - [qef](https://github.com/jmborr/qef/tree/master/notebooks): lmfit models for fitting quasielastic neutron scattering data\n  - [QENS models](https://github.com/QENSlibrary/QENSmodels/tree/master/examples-binder)\n  - [McStasScript](https://github.com/PaNOSC-ViNYL/McStasScript/tree/master/examples)\n  - [scipp](https://scipp.github.io/visualization/plotting-overview.html): multi-dimensional data arrays with labeled dimensions \n  -  Google group [Jupyter at Research Facilities](https://groups.google.com/forum/#!forum/jupyter-research-facilities)\n\n# Additional materials\n## Uploading my files to JupyterHub\nIf you want to use your own datafiles, click on the `Upload` button as shown in the figure below:\n\n<div>\n\n<div style=\"text-align:center\"> <span style=\"font-style:italic; font-size:1em;\"> Screenshot of Jupyter dashboard highlighting the `Upload` button to load user's own file(s) in the dashboard.  </span></div>\n</div>\n\n## Installation (not required for this workshop)\nAlthough it is possible to run each notebook of this repository using the *JupyterHub* (meaning that they are run on an external compute resources), you may want to try writing your own *Jupyter* notebooks and *Python* code.\n\nIf it is the case, you will have to install *Jupyter* notebooks locally (*e.g.* on your own laptop or desktop). This can be achieved by downloading and installing Anaconda. This is available for Windows, macOS and Linux [here](https://www.anaconda.com/distribution/#download-section).\n\nOnce installed the *Jupyter* notebooks can be opened, like how it is done during this training session. This creates a new window in your web browser: this is the *Jupyter* file navigator. Using this you can navigate to a specific folder, open an existing notebook or create a new one and save it on your system.\n\n## ipywidgets\n* [basic widget tutorial](../3_using_external_libraries/3_ipywidgets.ipynb)\n* [complete collection of jupyter widgets tutorials](https://github.com/jupyter-widgets/tutorial/tree/master/notebooks)\n* [list of widgets](https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20List.html)\n\n## What to do when things go wrong?\n\nhttps://jupyter-notebook.readthedocs.io/en/stable/troubleshooting.html\n\n## Trusting notebooks\nhttps://jupyter-notebook.readthedocs.io/en/latest/security.html#notebook-security\n\n\n```python\n\n```\n", "meta": {"hexsha": "2c0865383b8c41e8b5cf9d8d7fa03873802d9d23", "size": 30643, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/1_jupyter_basics/jupyter-notebook-intro.ipynb", "max_stars_repo_name": "celinedurniak/python-course-ikon", "max_stars_repo_head_hexsha": "047365373e163527ccdcf8227f5ff041dcc835d2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/1_jupyter_basics/jupyter-notebook-intro.ipynb", "max_issues_repo_name": "celinedurniak/python-course-ikon", "max_issues_repo_head_hexsha": "047365373e163527ccdcf8227f5ff041dcc835d2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 60, "max_issues_repo_issues_event_min_datetime": "2020-01-30T12:47:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T08:09:39.000Z", "max_forks_repo_path": "notebooks/1_jupyter_basics/jupyter-notebook-intro.ipynb", "max_forks_repo_name": "pan-training/python-course-ikon", "max_forks_repo_head_hexsha": "047365373e163527ccdcf8227f5ff041dcc835d2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-02-07T08:20:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T11:33:05.000Z", "avg_line_length": 42.6189151599, "max_line_length": 638, "alphanum_fraction": 0.6182814999, "converted": true, "num_tokens": 5119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12765261204695083, "lm_q2_score": 0.15002882244222637, "lm_q1q2_score": 0.019151571067078394}}
{"text": "# Jupyter notebook tricks\n\nSee also:\n\n- https://towardsdatascience.com/productivity-tips-for-jupyter-python-a3614d70c770\n\n## Magics\n\n\n```python\n%lsmagic\n# I.E. Use %env to list all environment variables\n```\n\n\n\n\n    Available line magics:\n    %alias  %alias_magic  %autocall  %automagic  %autosave  %bookmark  %cat  %cd  %clear  %colors  %config  %connect_info  %cp  %debug  %dhist  %dirs  %doctest_mode  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %less  %lf  %lk  %ll  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %lx  %macro  %magic  %man  %matplotlib  %mkdir  %more  %mv  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %popd  %pprint  %precision  %profile  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %rep  %rerun  %reset  %reset_selective  %rm  %rmdir  %run  %save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode\n    \n    Available cell magics:\n    %%!  %%HTML  %%SVG  %%bash  %%capture  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%markdown  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile\n    \n    Automagic is ON, % prefix IS NOT needed for line magics.\n\n\n\n### Using different languages inside single notebook\n\nIf you're missing those much, using other computational kernels:\n\n-  %%python2\n-   %%python3\n-   %%ruby\n-   %%perl\n-   %%bash\n-   %%R\n\n\n\n```ruby\n%%ruby\nputs 'Hi, this is ruby.'\n```\n\n\n```bash\n%%bash\necho \"Hello world!\"\n```\n\n    Hello world!\n\n\n### Bash commands\n\n\n```python\nres = !ping -c 1 google.com\nres\n```\n\n\n\n\n    ['PING google.com (216.58.199.78) 56(84) bytes of data.',\n     '64 bytes from syd15s01-in-f78.1e100.net (216.58.199.78): icmp_seq=1 ttl=55 time=85.8 ms',\n     '',\n     '--- google.com ping statistics ---',\n     '1 packets transmitted, 1 received, 0% packet loss, time 0ms',\n     'rtt min/avg/max/mdev = 85.815/85.815/85.815/0.000 ms']\n\n\n\n### Other magics\n\n\n```python\nimport time\n\n# %time will time whatever you evaluate\n%time time.sleep(1)\n# %timeit will time whatever you evaluate multiple times and give you the best, and the average times\n%timeit time.sleep(1)\n```\n\n    CPU times: user 2.06 ms, sys: 0 ns, total: 2.06 ms\n    Wall time: 1 s\n    1 s \u00b1 65.6 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1 loop each)\n\n\n\n```python\n# show the sources of train_test_split function in the pop-up window\ntime.sleep??\n```\n\n\n```python\n# you can use ? to get details about magics, for instance:\n%pycat?\n```\n\n\n```python\n# %who: analyze variables of global scope\n%who\n```\n\n    res\t time\t \n\n\n\n```python\n# To write a file (i.e. pythoncode.py) in a cell use %%writefile pythoncode.py.\n# To visualize python files use %pycat pythoncode.py\n```\n\n\n```python\n%pdb\n\ndef pick_and_take():\n#      picked = numpy.random.randint(0, 1000)\n     raise NotImplementedError()\n    \npick_and_take()\n```\n\n\n```latex\n%%latex\n\\begin{align}\na = \\frac{1}{2} && b = \\frac{1}{3} && c = \\frac{1}{4} \\\\\na && b && c \\\\\n1 && 2 && 3\n\\end{align}\n\n$$E = mc^2$$\n$$e^{i \\pi} = -1$$\n```\n\n\n\\begin{align}\na = \\frac{1}{2} && b = \\frac{1}{3} && c = \\frac{1}{4} \\\\\na && b && c \\\\\n1 && 2 && 3\n\\end{align}\n$$E = mc^2$$\n$$e^{i \\pi} = -1$$\n\n\n\n\n```python\n%load\n```\n\n\n```python\n# Auto save every 60 secs\n%autosave 60\n```\n\n## Big data analysis\n\nA number of solutions are available for querying/processing large data samples:\n\n- ipyparallel (formerly ipython cluster) is a good option for simple map-reduce operations in python. We use it in rep to train many machine learning models in parallel\n- pyspark\n- spark-sql magic [%%sql](https://github.com/jupyter-incubator/sparkmagic)\n\n\n\n## Embedding HTML, PDF and Videos\n\n\n```python\n%%HTML\n\n<h3>Rendering HTML</h3>\n```\n\n\n\n<h3>Rendering HTML</h3>\n\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('https://en.wikipedia.org/wiki/HTTPS', width=800, height=450)\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('https://arxiv.org/pdf/1406.2661.pdf', width=800, height=450)\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\nfrom IPython.display import YouTubeVideo\n\nYouTubeVideo('mJeNghZXtMo', width=800, height=300)\n```\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "c31bdd7309fb0c510243b95e1f103f68dc556fef", "size": 34732, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/learning/jupyter-notebook-tricks.ipynb", "max_stars_repo_name": "fsquillace/notebooks", "max_stars_repo_head_hexsha": "504af230610603806f91dde64456accc60371617", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-04-16T08:47:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-22T04:03:41.000Z", "max_issues_repo_path": "notebooks/learning/jupyter-notebook-tricks.ipynb", "max_issues_repo_name": "fsquillace/jupyter-notebooks-examples", "max_issues_repo_head_hexsha": "504af230610603806f91dde64456accc60371617", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/learning/jupyter-notebook-tricks.ipynb", "max_forks_repo_name": "fsquillace/jupyter-notebooks-examples", "max_forks_repo_head_hexsha": "504af230610603806f91dde64456accc60371617", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.676975945, "max_line_length": 19993, "alphanum_fraction": 0.7657779569, "converted": true, "num_tokens": 1426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19682621306573764, "lm_q2_score": 0.09670578808943049, "lm_q1q2_score": 0.019034234051180317}}
{"text": "```python\n!pip install qiskit\n```\n\n    Collecting qiskit\n      Downloading https://files.pythonhosted.org/packages/6f/61/cb7506e17a2566dc8a31a3e1924d91ac0bdd8ff07c71ec698c06647b6306/qiskit-0.26.2.tar.gz\n    Collecting qiskit-terra==0.17.4\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/b3/0c/3c7a8dd451dae0907263e9de9e3e34909e15e18c88a589b44581972c8511/qiskit_terra-0.17.4-cp37-cp37m-manylinux2010_x86_64.whl (6.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.0MB 10.0MB/s \n    \u001b[?25hCollecting qiskit-aer==0.8.2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/c2/d2/6ff15c370b5465b32529b528bf3f4ce1e01f74498be16203aa1c04b67022/qiskit_aer-0.8.2-cp37-cp37m-manylinux2010_x86_64.whl (18.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 18.0MB 219kB/s \n    \u001b[?25hCollecting qiskit-ibmq-provider==0.13.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/be/99/74bbb901f88603a7d850d4889abc06d81ba702e4227151f4a5b66f2631fe/qiskit_ibmq_provider-0.13.1-py3-none-any.whl (228kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 235kB 55.0MB/s \n    \u001b[?25hCollecting qiskit-ignis==0.6.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/54/be/a13c828e457e09d979667a61bddbd8c7246aafa94e2501b6a9154429cbea/qiskit_ignis-0.6.0-py3-none-any.whl (207kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 215kB 24.1MB/s \n    \u001b[?25hCollecting qiskit-aqua==0.9.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/88/79/392c57b978decbb24b902344b536af52c40a751aed0ebbaefa8bc2964cb5/qiskit_aqua-0.9.1-py3-none-any.whl (2.1MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.1MB 30.3MB/s \n    \u001b[?25hRequirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (1.7.1)\n    Collecting ply>=3.10\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/a3/58/35da89ee790598a0700ea49b2a66594140f44dec458c07e8e3d4979137fc/ply-3.11-py2.py3-none-any.whl (49kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 6.9MB/s \n    \u001b[?25hCollecting python-constraint>=1.4\n      Downloading https://files.pythonhosted.org/packages/37/8b/5f1bc2734ca611943e1d6733ee244238679f6410a10cd45ede55a61a8402/python-constraint-1.4.0.tar.bz2\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (2.8.1)\n    Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (1.19.5)\n    Collecting retworkx>=0.8.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/9e/cd/70d436f170aa1ead2ac9e4c19c8838633355d48b530f09455eab0af2f98e/retworkx-0.9.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.5MB 30.0MB/s \n    \u001b[?25hCollecting fastjsonschema>=2.10\n      Downloading https://files.pythonhosted.org/packages/d1/fb/ea090e917b18320f79be31d754bbe496b715175e865603cfce1eaed2e774/fastjsonschema-2.15.1-py3-none-any.whl\n    Requirement already satisfied: scipy>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (1.4.1)\n    Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (2.6.0)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (5.4.8)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (0.3.3)\n    Collecting pybind11>=2.6\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/8d/43/7339dbabbc2793718d59703aace4166f53c29ee1c202f6ff5bf8a26c4d91/pybind11-2.6.2-py2.py3-none-any.whl (191kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 194kB 44.6MB/s \n    \u001b[?25hCollecting requests-ntlm>=1.1.0\n      Downloading https://files.pythonhosted.org/packages/03/4b/8b9a1afde8072c4d5710d9fa91433d504325821b038e00237dc8d6d833dc/requests_ntlm-1.1.0-py2.py3-none-any.whl\n    Collecting websockets>=8\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/84/64/78c2b3fe37730b30dca3c93d1f7f4a4286767f86e7c04cf3571b39bc2fb7/websockets-9.1-cp37-cp37m-manylinux2010_x86_64.whl (103kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 112kB 46.1MB/s \n    \u001b[?25hRequirement already satisfied: nest-asyncio!=1.1.0,>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit) (1.5.1)\n    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit) (1.24.3)\n    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit) (2.23.0)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ignis==0.6.0->qiskit) (57.0.0)\n    Collecting yfinance<=0.1.55\n      Downloading https://files.pythonhosted.org/packages/7a/e8/b9d7104d3a4bf39924799067592d9e59119fcfc900a425a12e80a3123ec8/yfinance-0.1.55.tar.gz\n    Collecting docplex<=2.20.204; sys_platform != \"darwin\"\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/87/99/6f7c219b39fd58c84688ad0713eb932bfcf6be81fc74519e43ea9c915b56/docplex-2.20.204.tar.gz (611kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 614kB 32.6MB/s \n    \u001b[?25hCollecting dlx<=1.0.4\n      Downloading https://files.pythonhosted.org/packages/54/c0/b8fb5bb727e983b6f5251433ef941b48f38c65bb0bd6ec509e9185bcd406/dlx-1.0.4.tar.gz\n    Requirement already satisfied: fastdtw<=0.3.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (0.3.4)\n    Requirement already satisfied: h5py<=3.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (3.1.0)\n    Requirement already satisfied: pandas<=1.2.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (1.1.5)\n    Collecting quandl<=3.6.0\n      Downloading https://files.pythonhosted.org/packages/c2/58/9f0e69d836045e3865d263e9ed49f42b23a58526fdabb30f74c430baee3f/Quandl-3.6.0-py2.py3-none-any.whl\n    Requirement already satisfied: scikit-learn<=0.24.1,>=0.20.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (0.22.2.post1)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra==0.17.4->qiskit) (1.2.1)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.8.0->qiskit-terra==0.17.4->qiskit) (1.15.0)\n    Collecting ntlm-auth>=1.0.2\n      Downloading https://files.pythonhosted.org/packages/ff/84/97c550164b54942b0e908c31ef09d9469f3ba4cd7332a671e2125732f63b/ntlm_auth-1.5.0-py2.py3-none-any.whl\n    Collecting cryptography>=1.3\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/b2/26/7af637e6a7e87258b963f1731c5982fb31cd507f0d90d91836e446955d02/cryptography-3.4.7-cp36-abi3-manylinux2014_x86_64.whl (3.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.2MB 30.9MB/s \n    \u001b[?25hRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit) (2020.12.5)\n    Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance<=0.1.55->qiskit-aqua==0.9.1->qiskit) (0.0.9)\n    Collecting lxml>=4.5.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/30/c0/d0526314971fc661b083ab135747dc68446a3022686da8c16d25fcf6ef07/lxml-4.6.3-cp37-cp37m-manylinux2014_x86_64.whl (6.3MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.3MB 31.6MB/s \n    \u001b[?25hRequirement already satisfied: cached-property; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from h5py<=3.1.0->qiskit-aqua==0.9.1->qiskit) (1.5.2)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas<=1.2.3->qiskit-aqua==0.9.1->qiskit) (2018.9)\n    Requirement already satisfied: more-itertools in /usr/local/lib/python3.7/dist-packages (from quandl<=3.6.0->qiskit-aqua==0.9.1->qiskit) (8.7.0)\n    Collecting inflection>=0.3.1\n      Downloading https://files.pythonhosted.org/packages/59/91/aa6bde563e0085a02a435aa99b49ef75b0a4b062635e606dab23ce18d720/inflection-0.5.1-py2.py3-none-any.whl\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn<=0.24.1,>=0.20.0->qiskit-aqua==0.9.1->qiskit) (1.0.1)\n    Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit) (1.14.5)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit) (2.20)\n    Building wheels for collected packages: qiskit, python-constraint, yfinance, docplex, dlx\n      Building wheel for qiskit (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for qiskit: filename=qiskit-0.26.2-cp37-none-any.whl size=10506 sha256=51cc7e311fecc07502036fe968fc5e69fc7d1cbaa5516ccbf407187e63d3c7f3\n      Stored in directory: /root/.cache/pip/wheels/89/89/34/524839952d5a58a7be9789e580bfc1ca883bf6579152444568\n      Building wheel for python-constraint (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for python-constraint: filename=python_constraint-1.4.0-py2.py3-none-any.whl size=24079 sha256=9b7bca318b0da7e3aa3bc2bb5ab22ff1eb4c392590adfb7cad8c394e3dec4def\n      Stored in directory: /root/.cache/pip/wheels/34/31/15/7b070b25d0a549d20ce2e9fe6d727471c2c61ef904720fd40c\n      Building wheel for yfinance (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for yfinance: filename=yfinance-0.1.55-py2.py3-none-any.whl size=22627 sha256=badc54ad6fa6b26ba427b55ff9fcc0f57700716b3ee6a261d9d6fdbb3298492d\n      Stored in directory: /root/.cache/pip/wheels/04/98/cc/2702a4242d60bdc14f48b4557c427ded1fe92aedf257d4565c\n      Building wheel for docplex (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for docplex: filename=docplex-2.20.204-cp37-none-any.whl size=675396 sha256=d0073f4efacd3894d25b232609339ddedc81f00407b8cd93699acabaf19d84f8\n      Stored in directory: /root/.cache/pip/wheels/ae/2c/e2/a099ebb6fda8adeba9c5fc2e25659d195ad2f5c6cc5fb75fd4\n      Building wheel for dlx (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for dlx: filename=dlx-1.0.4-cp37-none-any.whl size=5720 sha256=f1e0369545938a651a5b82b9013d34215a1311c3bc5dfa4bdc0af3afcb293f8a\n      Stored in directory: /root/.cache/pip/wheels/bb/ba/15/fdd0deb104df3254912998150ba9245668db06b00af5912d1a\n    Successfully built qiskit python-constraint yfinance docplex dlx\n    \u001b[31mERROR: qiskit-aqua 0.9.1 has requirement retworkx<=0.8.0,>=0.7.0, but you'll have retworkx 0.9.0 which is incompatible.\u001b[0m\n    Installing collected packages: ply, python-constraint, retworkx, fastjsonschema, qiskit-terra, pybind11, qiskit-aer, ntlm-auth, cryptography, requests-ntlm, websockets, qiskit-ibmq-provider, qiskit-ignis, lxml, yfinance, docplex, dlx, inflection, quandl, qiskit-aqua, qiskit\n      Found existing installation: lxml 4.2.6\n        Uninstalling lxml-4.2.6:\n          Successfully uninstalled lxml-4.2.6\n    Successfully installed cryptography-3.4.7 dlx-1.0.4 docplex-2.20.204 fastjsonschema-2.15.1 inflection-0.5.1 lxml-4.6.3 ntlm-auth-1.5.0 ply-3.11 pybind11-2.6.2 python-constraint-1.4.0 qiskit-0.26.2 qiskit-aer-0.8.2 qiskit-aqua-0.9.1 qiskit-ibmq-provider-0.13.1 qiskit-ignis-0.6.0 qiskit-terra-0.17.4 quandl-3.6.0 requests-ntlm-1.1.0 retworkx-0.9.0 websockets-9.1 yfinance-0.1.55\n\n\n\n```python\n!git clone https://github.com/arnavdas88/QuGlassyIsing\n```\n\n    Cloning into 'QuGlassyIsing'...\n    remote: Enumerating objects: 282, done.\u001b[K\n    remote: Counting objects: 100% (282/282), done.\u001b[K\n    remote: Compressing objects: 100% (189/189), done.\u001b[K\n    remote: Total 282 (delta 127), reused 226 (delta 80), pack-reused 0\u001b[K\n    Receiving objects: 100% (282/282), 2.13 MiB | 23.69 MiB/s, done.\n    Resolving deltas: 100% (127/127), done.\n\n\n\n```python\n!mv QuGlassyIsing/research/pickle-files/ ./pickle\n```\n\n\n```python\nfrom qiskit.providers.aer import QasmSimulator  \nfrom qiskit.providers.aer import AerSimulator\nfrom qiskit import Aer, transpile\nfrom qiskit.circuit.library import TwoLocal\nfrom qiskit.algorithms import VQE\nfrom qiskit.algorithms.optimizers import COBYLA \nfrom qiskit.circuit.library import EfficientSU2\n# opflow is Qiskit's module for creating operators like yours\nfrom qiskit import *\nfrom qiskit.opflow import OperatorBase\nfrom qiskit.opflow import Z, X, I  # Pauli Z, X matrices and identity\nimport pylab\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n%matplotlib inline\n\nimport os\nimport pickle\n```\n\n\n```python\nfile_list = []\nfor dirlist in os.walk('./pickle'):\n    base, dir, files = dirlist\n    if 'j=1' in base:\n        for f in files:\n            file_list += [os.path.join(base, f)]\n\nprint(file_list) \n```\n\n    ['./pickle/2D Ising Model/j=1/AntiFerromagmetic/2D_Ising_Model_CountsAF3.kl', './pickle/2D Ising Model/j=1/AntiFerromagmetic/2D_Ising_Model_CountsAF1.pkl', './pickle/2D Ising Model/j=1/AntiFerromagmetic/2D_Ising_Model_CountsAF2.pkl', './pickle/2D Ising Model/j=1/Disordered/2D_Ising_Model_CountsDIS3.pkl', './pickle/2D Ising Model/j=1/Disordered/2D_Ising_Model_CountsDIS2.pkl', './pickle/2D Ising Model/j=1/Disordered/2D_Ising_Model_CountsDIS1.pkl']\n\n\n\n```python\nprint(\"Loading Optimization History\")\ncounts_values = {}\nfor f in file_list:\n    with open(f, 'rb') as handle:\n        counts_values[f] = pickle.load(handle)\n\n```\n\n    Loading Optimization History\n\n\n\n```python\nlist(counts_values.values())[0]\n```\n\n\n\n\n    {'vqe_result': {'optimal_parameters': {ParameterVectorElement(\u03b8[0]): -3.1746030798542333, ParameterVectorElement(\u03b8[10]): -3.100635416244281, ParameterVectorElement(\u03b8[11]): 6.328377883126882, ParameterVectorElement(\u03b8[12]): 2.9164261352270766, ParameterVectorElement(\u03b8[13]): -0.0037798946555328812, ParameterVectorElement(\u03b8[14]): -3.0350271957058883, ParameterVectorElement(\u03b8[15]): 3.166037002855905, ParameterVectorElement(\u03b8[16]): 6.297030729554503, ParameterVectorElement(\u03b8[17]): -3.108097885816586, ParameterVectorElement(\u03b8[18]): -0.04585685172297921, ParameterVectorElement(\u03b8[19]): -3.142182731729604, ParameterVectorElement(\u03b8[1]): -0.05777967803668499, ParameterVectorElement(\u03b8[20]): -4.7966215907963905, ParameterVectorElement(\u03b8[21]): 6.360102167275139, ParameterVectorElement(\u03b8[22]): 3.144073556477021, ParameterVectorElement(\u03b8[23]): -0.005766496893526079, ParameterVectorElement(\u03b8[24]): -2.9818101545752858, ParameterVectorElement(\u03b8[25]): -0.02678563432074167, ParameterVectorElement(\u03b8[26]): 0.2039131152360063, ParameterVectorElement(\u03b8[27]): 3.137908143882592, ParameterVectorElement(\u03b8[28]): 6.235410911266704, ParameterVectorElement(\u03b8[29]): 3.1538996948607956, ParameterVectorElement(\u03b8[2]): 3.1481769675707154, ParameterVectorElement(\u03b8[30]): 6.36243443901691, ParameterVectorElement(\u03b8[31]): -3.1172656134583487, ParameterVectorElement(\u03b8[32]): 2.967529546003407, ParameterVectorElement(\u03b8[33]): -0.018601476682845446, ParameterVectorElement(\u03b8[34]): -3.0806176055753003, ParameterVectorElement(\u03b8[35]): 6.3245066155335925, ParameterVectorElement(\u03b8[36]): -3.634226080863497, ParameterVectorElement(\u03b8[37]): -4.66227425246615, ParameterVectorElement(\u03b8[38]): -4.0520163039908255, ParameterVectorElement(\u03b8[39]): 3.2896698749701723, ParameterVectorElement(\u03b8[3]): -3.088063376005831, ParameterVectorElement(\u03b8[40]): 1.5195959727415742, ParameterVectorElement(\u03b8[41]): 0.4633002400573142, ParameterVectorElement(\u03b8[42]): -4.8293287619907685, ParameterVectorElement(\u03b8[43]): 2.703986994706933, ParameterVectorElement(\u03b8[44]): 0.3555617805754537, ParameterVectorElement(\u03b8[45]): 2.9929656633855375, ParameterVectorElement(\u03b8[46]): -3.668790699994091, ParameterVectorElement(\u03b8[47]): 3.840705680834548, ParameterVectorElement(\u03b8[48]): -6.709437619297109, ParameterVectorElement(\u03b8[49]): -4.203188688125719, ParameterVectorElement(\u03b8[4]): 6.232679863877247, ParameterVectorElement(\u03b8[50]): 3.3077696896916096, ParameterVectorElement(\u03b8[51]): 5.456782607512087, ParameterVectorElement(\u03b8[52]): -3.789000277286082, ParameterVectorElement(\u03b8[53]): 0.9701173607244663, ParameterVectorElement(\u03b8[54]): 8.004294647639963, ParameterVectorElement(\u03b8[55]): -3.41893222843782, ParameterVectorElement(\u03b8[56]): 5.954595925520237, ParameterVectorElement(\u03b8[57]): -4.702585312187972, ParameterVectorElement(\u03b8[58]): -3.555913806030308, ParameterVectorElement(\u03b8[59]): 5.536007200925312, ParameterVectorElement(\u03b8[5]): -3.1716010212845864, ParameterVectorElement(\u03b8[60]): -2.2100367422854807, ParameterVectorElement(\u03b8[61]): 1.8098201501033953, ParameterVectorElement(\u03b8[62]): 0.7030720634029217, ParameterVectorElement(\u03b8[63]): -3.8676333447556206, ParameterVectorElement(\u03b8[64]): -4.183183152634768, ParameterVectorElement(\u03b8[65]): -3.9996276898466503, ParameterVectorElement(\u03b8[66]): -3.5372745763429716, ParameterVectorElement(\u03b8[67]): 0.6455297281180165, ParameterVectorElement(\u03b8[68]): -3.0783346559958193, ParameterVectorElement(\u03b8[69]): 0.21004089588803004, ParameterVectorElement(\u03b8[6]): 0.05174891893831379, ParameterVectorElement(\u03b8[70]): -1.9118001719909354, ParameterVectorElement(\u03b8[71]): 3.3988677244137264, ParameterVectorElement(\u03b8[7]): -3.0633497462982, ParameterVectorElement(\u03b8[8]): 6.191816517035589, ParameterVectorElement(\u03b8[9]): -6.08644720536311}, 'optimal_point': array([-3.17460308e+00, -3.10063542e+00,  6.32837788e+00,  2.91642614e+00,\n            -3.77989466e-03, -3.03502720e+00,  3.16603700e+00,  6.29703073e+00,\n            -3.10809789e+00, -4.58568517e-02, -3.14218273e+00, -5.77796780e-02,\n            -4.79662159e+00,  6.36010217e+00,  3.14407356e+00, -5.76649689e-03,\n            -2.98181015e+00, -2.67856343e-02,  2.03913115e-01,  3.13790814e+00,\n             6.23541091e+00,  3.15389969e+00,  3.14817697e+00,  6.36243444e+00,\n            -3.11726561e+00,  2.96752955e+00, -1.86014767e-02, -3.08061761e+00,\n             6.32450662e+00, -3.63422608e+00, -4.66227425e+00, -4.05201630e+00,\n             3.28966987e+00, -3.08806338e+00,  1.51959597e+00,  4.63300240e-01,\n            -4.82932876e+00,  2.70398699e+00,  3.55561781e-01,  2.99296566e+00,\n            -3.66879070e+00,  3.84070568e+00, -6.70943762e+00, -4.20318869e+00,\n             6.23267986e+00,  3.30776969e+00,  5.45678261e+00, -3.78900028e+00,\n             9.70117361e-01,  8.00429465e+00, -3.41893223e+00,  5.95459593e+00,\n            -4.70258531e+00, -3.55591381e+00,  5.53600720e+00, -3.17160102e+00,\n            -2.21003674e+00,  1.80982015e+00,  7.03072063e-01, -3.86763334e+00,\n            -4.18318315e+00, -3.99962769e+00, -3.53727458e+00,  6.45529728e-01,\n            -3.07833466e+00,  2.10040896e-01,  5.17489189e-02, -1.91180017e+00,\n             3.39886772e+00, -3.06334975e+00,  6.19181652e+00, -6.08644721e+00]), 'optimal_value': -91.49267578125001, 'optimizer_evals': 1000, 'optimizer_time': 15296.228350877762, 'eigenvalue': (-91.49267578125001+0j), 'eigenstate': {'010110101001010010101100010010100101': 1, '010110101001010111101101010010101101': 1, '010110111001010010101101010010101101': 2, '010110101001010110101100011010101101': 1, '010110101001010110001101010010101101': 1, '010110101001010111101100010010101101': 1, '010110101101010010101100110010101101': 1, '010010101001010110101101011010101101': 1, '010010101001010010101100010010101101': 1, '010110101001010110101101010010100101': 2, '010110101001010110101101010010111101': 3, '010110101001010010101101010011101101': 2, '010110101001110110101101010010101101': 1, '010110101001010010101101110010101101': 2, '010110101001010010001101010010101101': 1, '010110101001010010101101010010101111': 1, '010111101001010110101101010010101101': 6, '010011101001010010101101010010101101': 1, '010100101001010110101101010010101101': 1, '010110101101010010101101010010101101': 43, '010110101101010110101101010010101101': 43, '010110101001010110101001010010101101': 5, '010110101001010010101101010110101101': 14, '010110101001010010101001010010101101': 13, '010110101001010110101100010010101101': 42, '010110101000010110101101010010101101': 21, '010110101001010010101100010010101101': 50, '010110101001010110101101011010101101': 31, '010110101001010010101101010000101101': 4, '010110101000010010101101010010101101': 21, '010110101001010010101100011010101101': 1, '010110101101010010101101011010101101': 2, '010110101001010110101101110010101101': 2, '010111101001010010101101010010101101': 8, '010110101001010110101101010110101101': 8, '010110101001010010101101010010100101': 5, '010110101001010011101101010010101101': 3, '010110101001011010101101010010101101': 6, '010010101001010110101101010010101101': 30, '000110101001010010101101010010101101': 4, '010110101001010110101101010010001101': 1, '010110101001010110101101010011101101': 4, '010110101001010110101101010010101111': 5, '010110101001010010101101010010001101': 1, '010110101011010010101101010010101101': 1, '010010101001010010101101010000101101': 1, '000110101001010110101101010010101101': 1, '010110101001010110101101010010101101': 3554, '010110101001010110101101010000101101': 7, '010110101001010010101101011010101101': 42, '010110101001010010101101010010101101': 4143, '010110101001011110101101010010101101': 5, '010010101001010010101101010010101101': 33, '010010101000010110101101010010101101': 1, '010110101001010110101101000010101101': 6, '010110101000010010101100010010101101': 1}, 'cost_function_evals': 1000}}\n\n\n\n\n```python\ntempdata = [ v for v in counts_values.values() ]\n```\n\n\n```python\ndef flatten(x): return sum(x, [])\n\ndef build_graph_data(x):\n    sqrt = len(x)**(float(1)/2)\n    sqrt = int(sqrt)\n    if not sqrt**2 == len(x):\n        raise Exception(\"not able to form a square\")\n    result = []\n    xa = np.asarray([float(i) for i in x])\n    return xa.reshape((sqrt, sqrt)), x\n\n\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pylab as plt\n\ndef draw_graph(x, t):\n    plt.figure(figsize=(7, 7))\n    plt.title(t, pad=6.2, fontsize=18, wrap=True)\n    plt.imshow(x, cmap='copper', interpolation='nearest', aspect='auto')\n    # plt.xticks(X, X/10, label=\"Bx\", rotation=90, fontsize=16)\n    # plt.xlabel('Bx \u2192', fontsize=24)\n    # plt.yticks(Y, label=\"Bz\", fontsize=16)\n    # plt.ylabel('Bz \u2192', fontsize=24)\n    # plt.colorbar()\n    # plt.savefig(\"Heatmap representing the change of `Minimum Ground State Energy` in Bx vs Bz.png\", bbox_inches='tight', dpi=1080)\n    plt.show()\n\ndef build_graph_data_from_list(x):\n    for i in x:\n        p, t = build_graph_data(i)\n        draw_graph(p, t)\n```\n\n# 1st Max\n\n\n```python\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pylab as plt\nfrom qiskit.visualization import plot_histogram\n\ndef show_counts_data_1st(tempdata_i, max_val = 0):\n    arr = tempdata_i['vqe_result']\n    arr = arr['eigenstate']\n    data = np.asarray(arr)\n    # print(list(arr.keys()))\n    arr = {a: arr[a] for a in arr if arr[a] == max(list(arr.values()))}\n    # return plot_histogram(arr)\n    return arr\n    # return len(list(arr.keys()))\n\n    # return data\n```\n\n\n```python\nde = {  k: show_counts_data_2nd(v)  for k, v in counts_values.items() if not \"AF1\" in k }\n\nfor k, e in de.items():\n    print(k)\n    build_graph_data_from_list(list(e.keys()))\n```\n\n# 2nd Max\n\n\n```python\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pylab as plt\nfrom qiskit.visualization import plot_histogram\n\ndef max_2nd(x):\n    x.remove(max(x))\n    return max(x)\n\ndef show_counts_data_2nd(tempdata_i, max_val = 0):\n    arr = tempdata_i['vqe_result']\n    arr = arr['eigenstate']\n    data = np.asarray(arr)\n    # print(list(arr.keys()))\n    arr = {a: arr[a] for a in arr if arr[a] == max_2nd(list(arr.values()))}\n    # return plot_histogram(arr)\n    return arr\n    # return len(list(arr.keys()))\n\n    # return data\n```\n\n\n```python\nde = {  k: show_counts_data_2nd(v)  for k, v in counts_values.items() if not \"AF1\" in k }\n\nfor k, e in de.items():\n    print(k)\n    build_graph_data_from_list(list(e.keys()))\n```\n\n# 3rd Max\n\n\n```python\n\ndef max_3rd(x):\n    x.remove(max(x))\n    x.remove(max(x))\n    return max(x)\n\ndef show_counts_data_3rd(tempdata_i, max_val = 0):\n    arr = tempdata_i['vqe_result']\n    arr = arr['eigenstate']\n    data = np.asarray(arr)\n    # print(list(arr.keys()))\n    arr = {a: arr[a] for a in arr if arr[a] == max_3rd(list(arr.values()))}\n    # return plot_histogram(arr)\n    return arr\n```\n\n\n```python\nde = {  k: show_counts_data_3rd(v)  for k, v in counts_values.items()  if not \"AF1\" in k  }\n\nfor k, e in de.items():\n    print(k)\n    build_graph_data_from_list(list(e.keys()))\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "4ccb7443d438e8a514a660d2dcd1903d06b81522", "size": 164443, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "research/glassy grid/[1st_Max_&_2nd_Max_&_3rd_Max]_QuGlassyIsing_Graphs.ipynb", "max_stars_repo_name": "arnavdas88/QuGlassyIsing", "max_stars_repo_head_hexsha": "6b6514d58646130c03619aebefb9f9aed4e5646a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-19T16:06:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T17:03:31.000Z", "max_issues_repo_path": "research/glassy grid/[1st_Max_&_2nd_Max_&_3rd_Max]_QuGlassyIsing_Graphs.ipynb", "max_issues_repo_name": "IshmamShah/QuGlassyIsing", "max_issues_repo_head_hexsha": "6c3ff2ebd77ed9b34a0e731083f1e56b7eacb7ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "research/glassy grid/[1st_Max_&_2nd_Max_&_3rd_Max]_QuGlassyIsing_Graphs.ipynb", "max_forks_repo_name": "IshmamShah/QuGlassyIsing", "max_forks_repo_head_hexsha": "6c3ff2ebd77ed9b34a0e731083f1e56b7eacb7ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-19T16:06:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T06:51:18.000Z", "avg_line_length": 193.2350176263, "max_line_length": 8334, "alphanum_fraction": 0.867929921, "converted": true, "num_tokens": 9468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28140560742914383, "lm_q2_score": 0.06754669160889748, "lm_q1q2_score": 0.01900801778203085}}
{"text": "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"></ul></div>\n\n\n```\n   \"source\": [\n    \"from src.model import *\\n\",\n    \"# In TensorFlow a device name is a string of the following form:\\n\",\n    \"#   /job:<name>/replica:<replica>/task:<task>/device:<type>:<device_num>\\n\",\n    \"#\\n\",\n    \"# <name> is a short identifier conforming to the regexp\\n\",\n    \"#     [a-zA-Z][_a-zA-Z]*\\n\",\n    \"# <type> is a supported device type (e.g. 'cpu' or 'gpu')\\n\",\n    \"# <replica>, <task>, <device_num> are small non-negative integers and are\\n\",\n    \"# densely allocated (except in tests).\\n\",\n    \"#\\n\",\n    \"# For some purposes, we also allow device patterns, which can specify\\n\",\n    \"# some or none of the specific fields above, with missing components,\\n\",\n    \"# or \\\"<component>:*\\\" indicating \\\"any value allowed for that component.\\n\",\n    \"#\\n\",\n    \"# For example:\\n\",\n    \"#   \\\"/job:param_server\\\"   - Consider any devices in the \\\"param_server\\\" job\\n\",\n    \"#   \\\"/device:cpu:*\\\"       - Consider any cpu devices in any job/task/replica\\n\",\n    \"#   \\\"/job:*/replica:*/task:*/device:cpu:*\\\"  - Consider any cpu devices in any\\n\",\n    \"#                                             job/task/replica\\n\",\n    \"#   \\\"/job:w/replica:0/task:0/device:gpu:*\\\"  - Consider any gpu devices in\\n\",\n    \"#                                             replica 0, task 0, of job \\\"w\\\"\"\n   ]\n  },\n```\n\n\n```\n    \"dataload = Sass('/home/penalvad/stattus4/test/', num_samples=5, number_of_batches=1, split_tax=.9, freq_size=480, time_size=640, same_data_validation=True)\\n\",\n    \"dataload_2 = Sass('/home/penalvad/stattus4/benchfull/', num_samples=7, number_of_batches=1, split_tax=.9, freq_size=600, time_size=80, same_data_validation=True)\"\n```\n\n\n```\n    \"dtrain = dataload.training()\\n\",\n    \"dtrain_2 = dataload_2.training()\"\n```\n\n\n```\n\n    \"dtrain = dataload.training()\\n\",\n    \"dtest = dataload.testing()\\n\",\n    \"\\n\",\n    \"data_train = np.ndarray( shape=(14,600,80,3) )\\n\",\n    \"data_test = np.ndarray( shape=(8,600,50,3) )\\n\",\n    \"\\n\",\n    \"for i in range(6):\\n\",\n    \"    \\n\",\n    \"  data_train[2*i,:,:,:] = dtrain[i][0][2]\\n\",\n    \"  data_train[2*i+1,:,:,:] = dtrain[i][1][2]\\n\",\n    \"\\n\",\n    \"#for i in range(4):\\n\",\n    \"\\n\",\n    \"  #data_test[2*i,:,:,0] = dtest[i][0][2]\\n\",\n    \"  #data_test[2*i+1,:,:,0] = dtest[i][1][2]\"\n```\n\n\n```\n    \"# Architecture Basics\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {\n    \"colab_type\": \"text\",\n    \"id\": \"99BygeASuBJD\"\n   },\n   \"source\": [\n    \"##  Gated CNN\\n\",\n    \"  Gated CNN is a doubled CNN in whom one of the convoluted signals does the role of opening/closing the network, giving an **Attention Mechanism** to the convolution, for being activated by a sigmoid.\\n\",\n    \"  It gives non-vanishing gradient, since the multiplication rule for the derivative applies, also, applies gradient to the linear convoluted part.\\n\",\n    \"  \"\n```\n\n\n```\n    \"### GCNN 2D\\n\",\n    \"  This unit uses sigmoid function in all frame pixels and do element-wise multiplication. Use it for images or time-series TF Features frame. The standard convolution mode is Valid. The output size of the convolution is given by:\\n\",\n    \" \\n\",\n    \" Padding Valid\\n\",\n    \"\\\\begin{align}\\n\",\n    \"dimemsion output size = \\\\ceil{ \\\\frac{dim size - (kernel dim size - 1)*dilation rate}{stride} }\\n\",\n    \"\\\\end{align} \\n\",\n    \"\\n\",\n    \"Where dilation rate is how may pixel are each filter spaced from each other, when dilation rate >= 1 then stride = 1 (since if you stride will be losing information from the data).\"\n```\n\n\n```\n    \"#Cascading deepness networks mem size\\n\",\n    \"    \\n\",\n    \"def channeling_rule(channelin, filterlist):        \\n\",\n    \"  channellist = [channelin]\\n\",\n    \"  for filter in filterlist:\\n\",\n    \"    channellist.append(channellist[-1] + filter + 3)  \\n\",\n    \"\\n\",\n    \"  return channellist \"\n   ]\n```\n\n\n```\n    \"# Label Vector Feed\\n\",\n    \"# dtrain[0][0][1]\\n\",\n    \"ltrain = []\\n\",\n    \"ltest = []\\n\",\n    \"\\n\",\n    \"for i in range(14):    \\n\",\n    \"  ltrain.append([0,1])   \\n\",\n    \"  ltrain.append([1,0])\\n\",\n    \"    \\n\",\n    \"#for i in range(4):\\n\",\n    \"  #ltest.append([0,1])    \\n\",\n    \"  #ltest.append([1,0])\"\n   ]\n```\n\n\n```\n \"for i in range(10):  \\n\",\n    \"  feed_dict[buildgraph.signal_in[i]] = data_train[:14,:,8*i:8*(i+1),:]\\n\",\n    \"\\n\",\n    \"feed_dict[buildgraph.label_tensor] = ltrain[:14]\\n\",\n    \"feed_dict[buildgraph.learning_rate] = 0.00001 \\n\",\n    \"\\n\",\n    \"output = buildgraph.run_cgraph(feed_dict, op_to_run = [buildgraph.namescopes['softmax'][-1].name, buildgraph.namescopes['softmax_3'][-1].name, buildgraph.namescopes['softmax_2'][-1].name, buildgraph.namescopes['softmax_4'][-1].name, buildgraph.namescopes['softmax_5'][-1].name, buildgraph.namescopes['softmax_6'][-1].name], number_of_runs = 40, mode = 'minimize', ckpt_dir_name='../ckpt/model', new_session=True, output_log = True, stop=0.4, adaptative_lr=True, verbose=True)\\n\",\n    \"\\n\",\n    \"#for i in range(10):  \\n\",\n    \"  #feed_dict[buildgraph.signal_in[i]] = data_train[:,:,5*i:5*(i+1),:]\\n\",\n    \"\\n\",\n    \"#feed_dict[buildgraph.l_vec] = ltrain[:14]\\n\",\n    \"#feed_dict[buildgraph.learning_rate] = 0.00001 \\n\",\n    \"\\n\",\n    \"#acc = buildgraph.run_cgraph(feed_dict, op_to_run = buildgraph.namescopes['reducemean'][-1].name, number_of_runs = 1, mode = 'x', new_session=True, output_log = True, auto_lr = False, verbose=True)\\n\",\n    \"\\n\",\n    \"#print('Tensor {}'.format(buildgraph.namescopes.gcnn2d_1[1].name))\\n\"\n```\n\n\n```\n# Example of Recovering Model from .meta and .data. It uses .index and checkpoint to map variables and last checkpoint to the graph \\n\",\ngraph = tf.Graph()\n    \nwith graph.as_default():\n    \n    saver = tf.train.import_meta_graph(\\\"../ckpt/model.meta\\\", import_scope='')\n    feed_dict = {}\n    with tf.Session(graph=graph) as sess:\n    Restore variables from disk.\n    \"    \\n\",\n    \"    saver.restore(sess, tf.train.latest_checkpoint('../ckpt/') )    \\n\",\n    \"    feed_dict[sess.graph.get_tensor_by_name('signal_in:0')] = data_train[:14,:,:8,:]\\n\",\n    \"    for i in np.arange(1,10):  \\n\",\n    \"      feed_dict[sess.graph.get_tensor_by_name('signal_in_'+str(i)+':0')] = data_train[:14,:,8*i:8*(i+1),:]\\n\",\n    \"    feed_dict[sess.graph.get_tensor_by_name('losscrossentropy/labels:0')] = ltrain[:14]\\n\",\n    \"    feed_dict[sess.graph.get_tensor_by_name('learning_rate:0')] = 0.0001      \\n\",\n    \"  #for op in graph.get_operations():\\n\",\n    \"    #print(2*'\\\\n')\\n\",\n    \"    #print(op.name)  \\n\",\n    \"    minimize_op = sess.graph.get_operation_by_name('losscrossentropy/Adam')\\n\",\n    \"    loss = sess.graph.get_tensor_by_name('losscrossentropy/categorical_crossentropy/weighted_loss/value:0')\\n\",\n    \"    acc = sess.graph.get_tensor_by_name('reducemean/Mean:0')\\n\",\n    \"    for i in range(400):\\n\",\n    \"      lossval,_ = sess.run([loss,minimize_op], feed_dict=feed_dict)\\n\",\n    \"      accval = sess.run([acc], feed_dict=feed_dict)\\n\",\n          if lossval < 0.3:\\n\",\n            saver.save(sess, '../ckpt/model2')\\n\",\n            print('\\\\n')\\n\",\n            print('saving')\\n\",\n            print('\\\\n')\\n\",\n            \\n\",\n          print('loss ',lossval)     \\n\",\n          print('acc ', accval)\\n\",\n          print(2*'\\\\n')\\n\",\n    \n\n```\n", "meta": {"hexsha": "bcea80b58e4cc1fd83bfb481d822b78969ff752e", "size": 10590, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Untitled.ipynb", "max_stars_repo_name": "Uiuran/stattus4-audio-models", "max_stars_repo_head_hexsha": "1ef4a9eca5d7540585c77d9fac85d5d4b3a7b07e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/Untitled.ipynb", "max_issues_repo_name": "Uiuran/stattus4-audio-models", "max_issues_repo_head_hexsha": "1ef4a9eca5d7540585c77d9fac85d5d4b3a7b07e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/Untitled.ipynb", "max_forks_repo_name": "Uiuran/stattus4-audio-models", "max_forks_repo_head_hexsha": "1ef4a9eca5d7540585c77d9fac85d5d4b3a7b07e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0465116279, "max_line_length": 496, "alphanum_fraction": 0.4955618508, "converted": true, "num_tokens": 2239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.043365794436662754, "lm_q1q2_score": 0.01898656386212688}}
{"text": "# Prerequsites\n\n\n```python\n# log the time of the experiment\nfrom datetime import datetime\nimport time\n\nexp_time = datetime.now()\nexp_time_str = exp_time.strftime(\"_%H_%M_%S\")\ndate_str = exp_time.strftime(\"%m_%d_%y\")\n```\n\n\n```python\n# Path management for MacOS and Windows\nfrom pathlib import Path\nimport os, sys\n\nscriptPath = Path(sys.path[0])\nparentPath = Path(sys.path[0]).parent\n#libPath = Path(\"/home/tw329/GitHub/ONN_MNIST/\")\nlibPath = Path(\"C:\\\\Users\\\\Logan\\\\Documents\\\\GitHub\\\\ONN_MNIST\")\nsys.path.append(libPath.as_posix())\nsys.path.append(\"C:\\\\Users\\\\Logan\\\\Documents\\\\GitHub\\\\mcmahon_lab_devices\") \n\n# Set the working directory (to save the files)\nresultPath = scriptPath\n\nslmWeightPath = resultPath / \"slm_weights\"\nif not os.path.exists(slmWeightPath.as_posix()):\n    os.makedirs(slmWeightPath.as_posix())\n    \nphoneImagePath = resultPath / \"phone_images\"\nif not os.path.exists(phoneImagePath.as_posix()):\n    os.makedirs(phoneImagePath.as_posix())\n    \nsaveDataPath = resultPath / \"saved_data\"\nif not os.path.exists(saveDataPath.as_posix()):\n    os.makedirs(saveDataPath.as_posix())\n    \nprint(resultPath)\n```\n\n    D:\\McMahon lab Dropbox\\peter mcmahon\\tw329\\Experiments\\12_01_20_4bit_randy_aug_MLP_100_100_MPPC\n\n\n\n```python\nfrom __future__ import print_function\nimport os, sys\nimport argparse\nfrom IPython.core.debugger import set_trace\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\nimport numpy as np\nimport pandas\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\n```\n\n\n```python\n%matplotlib notebook\n```\n\n# Instrument Controls\n\n\n```python\n# Configure the SLM\nfrom src.slmpy import SLMdisplay   # Popoff's simple package for controlling SLM\n\nslm = SLMdisplay(isImageLock = True)\n\nLUT_used=\"AmpLUT_basedon_100120slmbackcali_140509_start5.lut\"\n\nslmParamFile = resultPath / ''.join([\"slm_info\", exp_time_str, \".txt\"])\nwith open(slmParamFile,'w') as slmparams:\n    slmparams.write('LUT\\t\\t\\t{}\\n'.format(LUT_used))\nslmparams.close()\n\n```\n\n    C:/Users/Logan/Documents/GitHub/ONN_MNIST\\src\\slmpy.py:39: wxPyDeprecationWarning: Call to deprecated item EmptyImage. Use :class:`Image` instead.\n      self.img = wx.EmptyImage(2,2)\n\n\n\n```python\nimport pyvisa\nfrom devices import Agilent54845A as AgilentOscope\n\nrm = pyvisa.ResourceManager(\"C:\\\\WINDOWS\\\\System32\\\\visa64.dll\")\ngpib_id = rm.list_resources()[-1]\noscope = AgilentOscope(rm.open_resource(gpib_id))\noscope.set_waveform_source(1)\n\ndef oscope_info(oscope):\n    measure_state = {}\n    measure_state[\"ID\"] = oscope.id()\n    measure_state[\"x_range\"] = oscope.get_xrange()\n    measure_state[\"x_unit\"] = oscope.get_xunits()\n    measure_state[\"y_range\"] = oscope.get_yrange()\n    measure_state[\"y_unit\"] = oscope.get_yunits()\n    measure_state[\"y_offset\"] = oscope.get_offset()\n    measure_state[\"y_bounds\"] = [oscope.get_bottom_bound(), oscope.get_top_bound()]\n    return measure_state\n```\n\n\n```python\n# Configure the phone\n\nfrom Android_Display_Control.Remote_Display.image_stream import AndroidOpenAccessoryBridge as AOAB\n\nPIXEL_VENDOR_ID = 0x18d1\nPIXEL_UNCONFIG_ID =  0x4ee7\nPIXEL_CONFIG_ID = 0x2d01\n\n# Create an AOAB object for managing data send/receive via USB\naoab = AOAB(PIXEL_VENDOR_ID, PIXEL_UNCONFIG_ID, \n  PIXEL_CONFIG_ID,\n  manufacturer='ImageStreamManufacturer',\n  model='ImageStream1',\n  description='Stream Images to Android',\n  version=1,\n  uri=('https://github.com/chris-blay/android-open-accessory-bridge'),\n  serial='AoabSerial')\n```\n\n    Exception ignored in: <function _AutoFinalizedObjectBase.__del__ at 0x00000274F01F4C80>\n    Traceback (most recent call last):\n      File \"C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\usb\\_objfinalizer.py\", line 84, in __del__\n        self.finalize()\n      File \"C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\usb\\_objfinalizer.py\", line 144, in finalize\n        self._finalizer()\n      File \"C:\\Users\\Logan\\Anaconda3\\lib\\weakref.py\", line 552, in __call__\n        return info.func(*info.args, **(info.kwargs or {}))\n      File \"C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\usb\\_objfinalizer.py\", line 104, in _do_finalize_object_ref\n        obj._do_finalize_object()\n      File \"C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\usb\\_objfinalizer.py\", line 71, in _do_finalize_object\n        self._finalize_object()\n      File \"C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\usb\\backend\\libusb1.py\", line 604, in _finalize_object\n        _lib.libusb_unref_device(self.devid)\n    OSError: exception: access violation writing 0x0000000000000024\n\n\n\n```python\ndef PIL_to_bytestream(img_px):\n    array_px = np.array(img_px)\n    byte_array_px = bytearray()\n\n    for i in range(array_px.shape[0]):\n        for j in range(array_px.shape[1]):\n            byte_array_px.append(array_px[i, j, 0])\n            byte_array_px.append(array_px[i, j, 1])\n            byte_array_px.append(array_px[i, j, 2])\n\n    assert(len(byte_array_px) == 1920*1080*3)\n    return byte_array_px\n```\n\n\n```python\n# Load the phone pixel LUT\nlut_p = torch.zeros(1000, dtype=torch.uint8) \nwith open((resultPath/'PhoneLUT_100120_161444c30et20ms_1000.lut').as_posix(),'r') as lutfile:\n        for i in range(len(lut_p)):\n            aline = lutfile.readline().split()\n            lut_p[i] = int(aline[1])\nlutfile.close()\n```\n\n# Helper Functions\n\n\n```python\n\"\"\" Helper functions for generating phone and SLM patterns. \"\"\"\n\nfrom math import sqrt\n\ndef Wrap_vec_to_square (idx_vec, null_element=torch.tensor([-1])):\n    \n    if isinstance(null_element, int):\n        null_element = torch.tensor([null_element])\n        \n    a = int(sqrt(len(idx_vec)))\n    if len(idx_vec) < a*(a+1):\n        px_col_counts = a\n        last_row_supplements = a - 1 - (idx_vec.numel()-1)%a \n    if len(idx_vec) >= a*(a+1):\n        px_col_counts = a+1\n        last_row_supplements = a - (idx_vec.numel()-1)%(a+1)\n    \n    idx_vec = torch.cat((idx_vec, torch.repeat_interleave(null_element, last_row_supplements)))\n    idx_vec = idx_vec.view(-1, px_col_counts)\n    \n    return idx_vec\n\n# Image binarize functions\ndef binarize_img_by_percentile(img, rate):\n    img_b = (img<=np.percentile(img.numpy(), rate))\n    res_ones = int(img_b.sum() - rate/100.0 * img_b.numel())\n    vec_b = img_b.flatten()\n    vec_b[vec_b.nonzero()[:res_ones]] = 0\n    return vec_b.view(img_b.shape)\n\ndef add_surr(img,expan_r):\n    img_shape = np.array(img.shape)\n    expan_img = np.zeros(img_shape*expan_r)\n    expan_img[expan_r//2::expan_r,expan_r//2::expan_r] = img\n    return expan_img\n\ndef expand_pixels(img, expan_r):\n    img_temp = torch.repeat_interleave(img, expan_r, dim=0)\n    return torch.repeat_interleave(img_temp, expan_r, dim=1)\n\ndef Add_frame(pic, frame_px_value):\n    \n    frame = torch.zeros(pic.shape[0]+40, pic.shape[1]+40, dtype=pic.dtype)\n    frame[[0,-1],:] = frame_px_value\n    frame[:,[0,-1]] = frame_px_value\n    frame[20:-20, 20:-20] = pic\n    \n    return frame\n```\n\n# Correction Mask\n\n\n```python\nf_list = []\nfor f in os.listdir(saveDataPath):\n    if f.endswith('.pkl'):\n        f_list.append(f)\nf_list\n```\n\n\n\n\n    ['phonemask_blk600x600_antiatt_phone_mask_onsite_lb640_1_1012_092948.bmp.pkl',\n     'phonemask_blk600x600_antiatt_phone_mask_raw_1012_092948.pkl',\n     'phonemask_blk720x720_antiatt_phone_mask_onsite_lb450_1_1015_233224.bmp.pkl',\n     'phonemask_blk720x720_antiatt_phone_mask_raw_1015_233224.pkl']\n\n\n\n\n```python\ndef im_maxmin(img):\n    plt.figure()\n    plt.imshow(img)\n    plt.colorbar()\n    plt.title(f\"max/min = {img.max():.1f}/{img.min():.1f} = {img.max()/img.min():.2f}\")\n    plt.xlabel(f\"std/mean = {img.std():g}/{img.mean():g} = {img.std()/img.mean():g}\")\n    plt.show()\n```\n\n\n```python\nimport joblib\nmaskPath = saveDataPath\nmaskName = \"phonemask_blk720x720_antiatt_phone_mask_onsite_lb450_1_1015_233224.bmp.pkl\"\nmask_str = \"onsite\"\n# maskName = \"blk600x600_antiatt_phone_mask_raw_0911_142600.bmp\"\n# mask_str = \"rawmask\"\nphone_mask = joblib.load(saveDataPath / maskName)\n# if len(mask.shape)==3:\n#     mask = mask[:,:,1]\nphone_mask\nim_maxmin(phone_mask)\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:5: RuntimeWarning: divide by zero encountered in double_scalars\n      \"\"\"\n\n\n\n```python\nexpan_r = 5\nx_norm_expan = torch.repeat_interleave(torch.ones(28, 28), expan_r, dim=0)\nx_norm_expan = torch.repeat_interleave(x_norm_expan, expan_r, dim=1)\nx_norm_embedded = CenterEmbedding(x_norm_expan, torch.zeros(1920, 1080))\nsub_phone_mask = phone_mask * x_norm_embedded.numpy()\nsub_phone_mask = sub_phone_mask / sub_phone_mask.max()\nplt.figure()\nplt.imshow(sub_phone_mask)\nplt.show()\n```\n\n# Definition of the Neural Network\n\n\n```python\n\"\"\" Define digitized fully connected layers \"\"\"\n\n# Definition of an in-place digitization function.\ndef Digitize(tensor, quant_mode='det', levels=16, min_val=None, max_val=None):\n    if not min_val and not max_val:\n        min_val, max_val = tensor.min().item(), tensor.max().item()\n    tensor.clamp_(min_val, max_val).add_(-1*min_val).mul_(levels-1).div_(max_val-min_val)\n    if quant_mode == \"det\": \n        tensor.round_()\n    elif quant_mode == \"rand\":\n        tensor.add_(torch.rand(tensor.size(), device=tensor.device).add_(-0.5)).round_()\n    tensor.mul_(max_val-min_val).div_(levels-1).add_(min_val)\n    return tensor\n\nclass DigitizeLinear(nn.Linear):\n\n    def __init__(self,  *kargs, a_quant_mode=\"det\", w_quant_mode=\"det\", a_quant_levels=16, w_quant_levels=32, running_weight=0.001, **kwargs):\n        super(DigitizeLinear, self).__init__(*kargs, **kwargs)\n        self.act_quant_mode = a_quant_mode\n        self.weight_quant_mode = w_quant_mode\n        self.register_buffer(\"act_quant_levels\", torch.tensor(a_quant_levels))\n        self.register_buffer(\"weight_quant_levels\", torch.tensor(w_quant_levels))\n        self.register_buffer(\"running_weight\", torch.tensor(running_weight)) \n        self.register_buffer(\"running_min\", None)\n        self.register_buffer(\"running_max\", None)\n\n    def forward(self, input):\n\n        if not self.weight_quant_mode is None: # Set a flag to control weight digitization.\n            if not hasattr(self.weight,'org'):\n                self.weight.org=self.weight.data.clone()\n            self.weight.data=Digitize(self.weight.data, quant_mode=self.weight_quant_mode, levels=self.weight_quant_levels)\n\n        if not self.bias is None:\n            self.bias.org=self.bias.data.clone()    \n        out = nn.functional.linear(input, self.weight, bias=self.bias)\n\n        if not self.act_quant_mode is None: # A flag to control output digitization. \n            if self.training: # Update the running average of min and max only during training\n                with torch.no_grad():\n                    if not self.running_min and not self.running_max:\n                        self.running_min, self.running_max = out.min(), out.max()\n                    self.running_min = (1-self.running_weight) * self.running_min + self.running_weight * out.min()\n                    self.running_max = (1-self.running_weight) * self.running_max + self.running_weight * out.max()\n            out.data=Digitize(out.data, quant_mode=self.act_quant_mode, levels=self.act_quant_levels, min_val=self.running_min, max_val=self.running_max)\n    \n        return out\n```\n\n\n```python\n\"\"\" Define a generic QAT MLP structure (including perceptron) \"\"\"\n\nclass Net(nn.Module):\n    def __init__(self, Nunits, **kwargs):\n        super().__init__()\n        self.fcs = nn.ModuleList([DigitizeLinear(i,j,**kwargs) for i, j in zip(Nunits[:-1], Nunits[1:])])\n\n    def forward(self, X):\n        X = X.view(X.size(0), -1)\n        for i, fc in enumerate(self.fcs):\n            X = fc(X)\n            if fc is not self.fcs[-1]:\n                X = F.relu(X)\n        return X\n    \n    def set_digitize_config(self, a_quant_mode, w_quant_mode, a_quant_levels, w_quant_levels):\n        for fc in self.fcs:\n            fc.act_quant_mode = a_quant_mode\n            fc.weight_quant_mode = w_quant_mode\n            fc.act_quant_levels = torch.tensor(a_quant_levels)\n            fc.weight_quant_levels = torch.tensor(w_quant_levels)\n```\n\n\n```python\n\"\"\" Load the trained model \"\"\"\n\ndevice = \"cpu\"\n\nmodel = Net([784, 100, 100, 10])\nfor l in model.fcs:\n    l.running_min = torch.tensor(0.0)\n    l.running_max = torch.tensor(0.0)\nmodel_ckpt = torch.load(\"./RA_4bit_H2_100_100_lr_0.043_0.50_m_0.87_wep_6_randActDigi_v80_ep97.pt\", map_location=device)\nmodel_state_dict = model_ckpt[\"model_state_dict\"]\nmodel.load_state_dict(model_state_dict)\nmodel.to(device)\nmodel.eval()\n```\n\n\n\n\n    Net(\n      (fcs): ModuleList(\n        (0): DigitizeLinear(in_features=784, out_features=100, bias=True)\n        (1): DigitizeLinear(in_features=100, out_features=100, bias=True)\n        (2): DigitizeLinear(in_features=100, out_features=10, bias=True)\n      )\n    )\n\n\n\n\n```python\n\"\"\" Construct dataloaders \"\"\"\n\ntrainID_range = range(200) # ID of the samples to be passed through the NN\n\n# Import the test data loaders\nkwargs = {'num_workers': 1, 'pin_memory': True} if True else {}\n\ndata_mnist_test = datasets.MNIST('../ML_data', \n                                 train=False, \n                                 transform=transforms.Compose([transforms.ToTensor()]))\n\n# Remember to set the batch size to the length of train ID range, or the dataloader will draw sample one by one.\nsubset_data_loader = torch.utils.data.DataLoader(data_mnist_test, \n                                           batch_size=int(max(trainID_range)+1), \n                                           shuffle=False, **kwargs)\n\n# Remember to set the batch size to the length of train ID range, or the dataloader will draw sample one by one.\ntest_loader = torch.utils.data.DataLoader(data_mnist_test, \n                                           batch_size=1, \n                                           shuffle=False,  **kwargs)\n```\n\n# Notes on ONN Forward Propagation Implementation (Rev. 3)\n\nThe update equation from one neuron layer to the next:\n\n\\begin{equation}\nx_{i}^{L+1} = \\sigma(\\sum_{j}^N{W_{ij}^{L} x_{j}^{L}+b_i^{L}})    \n\\end{equation}\n\nwhere $x_j^L$ is the activation of neuron $j$ in layer $L=0,1,..$.\n\nSince the pixel values in an ONN are intensity encoded, including inputs, activations, and weights, the update equation needs to be modified such that the matrices and vectors to be loaded onto the ONN contain only non-negative numbers. In fact, the possible range of matrix and vector entries is actually limited to positive values, since the phone and SLM pixel values cannot infinitely approach zero in reality, due to hardware limitations. The following framework deals with the most general case where both phone and SLM pixel values cannot be extinguished to zero. If reality, if the resolution permits, the expression can be significantly simplified if either phone or SLM pixels can reach zero within the demanded accuracy.\n\nThe update equation is first rewritten into a vector form to facilitate the following discussion:\n\n\\begin{equation}\nX^{L+1} = \\sigma({W^{L} X^{L} + B^{L}})    \n\\end{equation}\n\nA note on symbol convention: any lower case letter represents a column vector (e.g., $b$, $x$); any captital letter represents a matrix (e.g., $W$, and $X$ actually indicates a batch of data $X = [x_0, x_1, ..., x_{B-1}]$); columns and rows of a matrix is represented in Python indexing convention (i.e., $W[,j]$ and $W[i,]$); element at row $i$ and column $j$ of matrix $W$ is written as $W[i,j]$ instead of $W_{ij}$; the $i$th element in vector a vector is also indicated with Python indexing convention (e.g., $x[i]$ instead of $x_i$). The superscript $L$ indicating the layer of NN is dropped here and below as long as it does not cause any confusion. \n\nTherefore, $W^L[i,j]$ is the weight from neuron i in layer L to neuron j in layer L+1, $X^L[j,k]$ is the actication of neuron j of data batch index k, $B^L[i,k]$ is the bias for neuron i in layer L.\n\nEach element in a row $W[i,]$ can be linearly mapped from interval $[\\text{min}(W[i,]), \\text{max}(W[i,])]$ to $[I_\\text{min}, I_\\text{max}]$, with $I_\\text{max}>I_\\text{min} \\geq 0$. More explicitely, the resultant matrix $\\tilde{W}$ is related to $W$ with the relation:\n\n\\begin{equation}\nW = \\hat{K}\\tilde{W} + \\hat{D}\\mathbb{1}\n\\end{equation}\n\nwhere\n\\begin{equation}\n\\hat{K}=\\frac{1}{I_\\text{max}-I_\\text{min}}diag\\{\\Delta W_i = \\text{max}(W[i,]) - \\text{min}(W[i,])\\}, \n\\hat{D} = \\frac{1}{I_\\text{max}-I_\\text{min}} diag \\{I_\\text{max} \\text{min}(W[i,]) - I_\\text{min} \\text{max}(W[i,]) \\}\n\\end{equation}\nand $\\mathbb{1}$ is all 1 matrix. (Tip: hat implies diagonal matrix; tilde implies the control signal to be sent to a device, such as phone or SLM).\n\n\nThe same transform can be performed on a data batch, which gives $X = \\tilde{X} \\hat{K}_X  +  \\mathbb{1}\\hat{D}_X$ ($\\hat{K}_X$ and $X$ switch position because the definiation of $X$ is transposed from that of $W$.)\n\nNow we can rewrite the update equation as\n\\begin{equation}\nX^{L+1}  = \\sigma( \\hat{K}  \\{\\tilde{W} \\tilde{X}^L\\} \\hat{K}_X  + \\hat{D} \\{\\mathbb{1} \\tilde{X}^L\\} \\hat{K}_X  + \\hat{K} \\{\\tilde{W}\\mathbb{1}\\}\\hat{D}_X + \\hat{D} \\mathbb{1}\\mathbb{1} \\hat{D}_X + b)\n\\end{equation}\n\n\nNote that the matrix products in curly brackets are to be measured expiermentally from the ONN output, and the other quantities are computed once and stored.\n\n\nThe reason to rewrite the update equation in this form is to carry out *each* inner product computation at the full pixel resolution of the smartphone and SLM. The matrices and vectors are always normalized to cover the entire dynamic range of the devices. The normalization factor is stored and later re-applied to the value readout from the ONN to recover the actual numerical value. \n\n\nMore specifically, the passing of NN activation from one layer to the next can be summarized as the following steps:\n1. Normalize $W$ to $\\tilde{W}$, which needs to be done only once for a trained NN and takes $O(MN)$ operations. \n2. Normalize $X$ to $\\tilde{X}$, which needs to be done for every input and layer and takes a total of $NBL$ multiplications. However, these operations can be waived if the phone pixel has high enough bit depth. Since the activations are usually non-negative numbers, it is possible to represent them with pixel intensity without any pre-processing.\n3. Load $\\tilde{X}$ to the phone to control pixel intensity and $\\tilde{W}$ to SLM to control transimission. In this way, $\\tilde{W}$ and $\\tilde{X}$ are both represented with the full resolutin of the devices.\n4. Measure the total pixel value in a region of interest that corresponds to the inner product $\\tilde{W}[i,]\\tilde{X}[,j]$ (read: the input to neuron $i$ for the data batch index $j$) in the captured camera image. In the ideal case, this signal can be measured by a single-pixel detector.\n5. Use the calibration model to find $\\tilde{W}[i,]\\tilde{X}[,j]$ based on the integrated pixel value in the regions of interest, obtained in step (4). \n6. After reading out all the entries of $\\tilde{W}\\tilde{X}$ (W_til_X_til), multiply it with $\\hat{D}$ and $\\hat{D_X}$ digitially, which were obtained in step (1) and (2).\n7. Derive $\\mathbb{1} \\tilde{X}$ (sum_X_til) and $\\tilde{W}\\mathbb{1}$ (sum_W_til) following similar steps as (5) and (6). Essentially they are just special cases of $\\tilde{W}\\tilde{X}$ with either $\\tilde{W} = \\mathbb{1}$ or $\\tilde{X} = \\mathbb{1}$.\n8. Add the computed terms $\\hat{K}\\tilde{W}\\tilde{X}\\hat{K}_X$ (Delta_W_Delta_X), $\\hat{D}\\mathbb{1}\\tilde{X}\\hat{K}_X$ (Offset_W_Delta_X),  $\\hat{K}\\tilde{W}\\mathbb{1}\\hat{D}_X$ (Delta_W_Offset_X), $\\hat{D} \\mathbb{1}\\mathbb{1}\\hat{D}_X$ (Offset_W_Offset_X), and $b$ digitally, and then apply the nonlinear activation function $\\sigma$ to obtain the activations of neurons.\n\n\n\n\n```python\n\"\"\"Auxilitary functions for simulating activation propation in ONN\"\"\"\n\ndef digitize(x, levels=8, min_val=None, max_val=None):\n    \"\"\"\n    digitize activations into the discrete steps, by rounding to the closest level.\n    levels: specifies the number of total discrete levels.\n    min_val: the x value to be mapped to the lowest level\n    max_val: the x value to be mapped to the highest level\n    \"\"\"\n\n    if not min_val and not max_val:\n        min_val, max_val = x.min(), x.max()\n    x = (levels-1)*(x - min_val)/(max_val-min_val)\n    x = x.round()\n    x = torch.min(torch.max(x, torch.zeros_like(x)), torch.ones_like(x)*(levels-1))\n    x = x*(max_val-min_val)/(levels-1) + min_val\n    return x\n\ndef Matrix_Linear_Mapping(W, target_interval):\n    \"\"\"\n    Transform each column of W with the following linear transform: \n    Argument target_interval=[a,b] specifies the lower and upper bound a and b.\n    The minimum of each column of W will be mapped to a, and the maximum of each W column mapped to b.\n    The rest of elements in the column are mapped in-between a and b with linear interporlation.\n    Such operation is repeated for each column individually.\n    \"\"\"\n    \n    W = W.type(torch.double)\n    W_mins, _ = torch.min(W, dim=0) \n    W_maxs, _ = torch.max(W, dim=0)\n    Delta_I = float(target_interval[1] - target_interval[0])\n    Delta_W = W_maxs - W_mins\n    K_W = torch.diag(Delta_W/Delta_I)\n    D_W = target_interval[1]*W_mins - target_interval[0]*W_maxs\n    offset = torch.mm(torch.repeat_interleave(D_W.view(1,-1), W.shape[0],dim=0), torch.diag(1/Delta_W))\n    W_til = torch.mm(W, torch.diag(Delta_I/Delta_W)) - offset\n    \n    return (W_til, K_W, torch.diag(D_W)/Delta_I)\n    \n\ndef ONN_layer_prop(layer, W_transform, X_transform, W_digitize_func=None, X_digitize_func=None, Act_digitize_func=None,  X=None,\n                     W_til_X_til=None, sum_W_til=None, sum_X_til=None):\n    \"\"\"\n    Forward propagate a batch of data for one layer.\n\n    layer: of type torch.nn.module, the layer to propagate the current batch of data through. Both W and b are derived from layer.\n    W_transform: the mapping from the W stored in layer to the control value to be applied to SLM.\n    X_transform: the mapping from the activation values stored in X to the control value to be applied to the smartphone.\n    Act_digitize_func: The function for digitizing the output activation. No digitization is performed if None is given.\n    W_digitize_func: The function for digitizing weight matrix W before the forward propagation. \n                     No digitization is performed if None is assigned to W_digitize_func as default.\n    X_digitize_func: The function for digitizing the batch data X before the forward propagation. \n                     No digitization is performed if None is assigned to X_digitize_func as default.\n    X: Inputs to the current NN layer. \n       If X is not given, an identity matrix is assigned to X as default, such that the W_til_X_til returned by the function equals W_til.\n       X.shape = [batch size, current NN layer width]\n    W: weight matrix derived from layer. W.shape = [current NN layer width, next NN layer size]\n    b: bias vector. b.shape = [next NN layer width]\n    \n    When no digitization is performed on W, X, or Wx+b, only linear stretching is performed on W and X, and the output of the function is \n    almost identical to the results obtained by prop(layer).\n    \"\"\"\n    \n    W = layer.weight.data.t()\n        \n    # Normalize W \n    (W_til, K_W, D_W) = W_transform(W)\n    \n    if X is None: # If X is not given, make it an identity matrix.\n        X = torch.eye(W.shape[0])\n        (X_til, K_X, D_X) = Matrix_Linear_Mapping(X, [0,1])\n    else: # Normalize X\n        (X_til, K_X, D_X) = X_transform(X.t())\n        (X_til, K_X, D_X) = (X_til.t(), K_X.t(), D_X.t())\n    \n    if W_digitize_func is not None:\n        W_til = W_digitize_func(W_til)\n        \n    if X_digitize_func is not None:\n        X_til = X_digitize_func(X_til)\n        \n    W_til_max = W_til[:,0].max()\n    X_til_max = X_til[0,:].max()\n    \n    # First simulate the three measurables from the ONN (defined in Notes on ONN Forward Propagation Implementation (Rev. 3)):\n    if W_til_X_til is None:\n        W_til_X_til = torch.mm(X_til, W_til) # tilde{WX} \n    if sum_X_til is None:\n        sum_X_til = torch.mm(X_til, torch.ones_like(W_til)) * W_til_max # sum(tilde{X[j,:]}), aka the sum of all activations of batch index j.   \n    if sum_W_til is None:\n        sum_W_til = torch.mm(torch.ones_like(X_til), W_til) * X_til_max# sum(tilde{W[:,i]}), aka the sum of all weights into neuron i.\n    \n    # The following terms are defined in Notes on ONN Forward Propagation Implementation (Rev. 3)\n    Delta_W_Delta_X = torch.mm(torch.mm(K_X, W_til_X_til), K_W) \n    Delta_W_Offest_X = torch.mm(torch.mm(K_X, sum_X_til), D_W) / W_til_max\n    Offset_W_Delta_X = torch.mm(D_X, torch.mm(sum_W_til, K_W)) / X_til_max\n    Offset_W_Offset_X = torch.mm(D_X, torch.mm(torch.ones_like(W_til_X_til)*W_til.shape[0], D_W)) \n    \n    Wx = Delta_W_Delta_X + Delta_W_Offest_X + Offset_W_Delta_X + Offset_W_Offset_X  # Wx\n    Wx_b = Wx + torch.repeat_interleave(layer.bias.view(1,-1), W_til_X_til.shape[0], dim=0).type(torch.double) # Wx+b\n    if Act_digitize_func is not None:\n        Wx_b = Act_digitize_func(Wx_b) # digitize(Wx+b)\n    a = F.relu(Wx_b) # ReLU(digitize(Wx+b))\n\n    return {\"norm(W)norm(X)\": W_til_X_til, \"sum(norm(X))\": sum_X_til, \"sum(norm(W))\": sum_W_til, \"Wx\": Wx, \"Wx+b\": Wx_b, \"a\": a}\n```\n\n\n```python\n# Calculate the ground truth of activations of each layer \n# by Propagating each test sample through the trained NN and record activation of each layer.\nimport pandas\n\nX, data_labels = next(iter(subset_data_loader))\nX = X.view(X.size(0), -1)\nX0 = X\n\ndf_layer = {}\n\n# Define the transform and quantization functions for all layers:\nW_transform = lambda W: Matrix_Linear_Mapping(W, [5,2**8-1])\nX_transform = lambda X: Matrix_Linear_Mapping(X, [0,1000-1])\nW_digitize = lambda W: Digitize(W.clone(), levels=2**8-5) # levels of quantization for W\nX_digitize = lambda X: Digitize(X.clone(), levels=1000) # levels of quantization for X\n# One very strange thing is that you cannot lambda function dictionary\n\nfor l, layer in enumerate(model.fcs):\n    # Calculate the ground truth activation by passing through one layer\n    layer.act_quant_mode=None\n    layer.weight_quant_mode=None\n    X0 = F.relu(layer(X0))\n    \n    # Propagate the batch for one layer\n    Act_digitize = lambda X: Digitize(X.clone(), levels=2**4, min_val=layer.running_min.item(), max_val=layer.running_max.item()) # levels of quantization for y=Wx+b\n    results = ONN_layer_prop(layer, W_transform, X_transform, \\\n                             W_digitize_func=W_digitize, X_digitize_func=X_digitize, Act_digitize_func=Act_digitize, X=X)    \n    X = results[\"a\"] # The activation of the current layer is the input to the next layer. \n    \n    results[\"a_true\"] = X0\n    df = {}\n    for k in results.keys():\n        df[k] = pandas.DataFrame(results[k].detach().numpy()).stack(level=-1)\n    df_layer[l] = pandas.concat(df, axis=1)\n        \n# Concatenate the df for each sample into an even larger one to include all the samples spcified.    \ndf_all_acts = pandas.concat(df_layer, axis=0, \\\n                            keys=df_layer.keys(), names=[\"layer\", \"test_ID\", \"output node\"])\ndf_all_acts.index = df_all_acts.index.swaplevel(0,1)\n```\n\n\n```python\ndf_all_acts\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th></th>\n      <th>norm(W)norm(X)</th>\n      <th>sum(norm(X))</th>\n      <th>sum(norm(W))</th>\n      <th>Wx</th>\n      <th>Wx+b</th>\n      <th>a</th>\n      <th>a_true</th>\n    </tr>\n    <tr>\n      <th>test_ID</th>\n      <th>layer</th>\n      <th>output node</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">0</th>\n      <th rowspan=\"5\" valign=\"top\">0</th>\n      <th>0</th>\n      <td>7435548.0</td>\n      <td>18435480.0</td>\n      <td>101575323.0</td>\n      <td>-15.719175</td>\n      <td>-15.587848</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>9019478.0</td>\n      <td>18435480.0</td>\n      <td>99886014.0</td>\n      <td>-3.035051</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>9160499.0</td>\n      <td>18435480.0</td>\n      <td>95635269.0</td>\n      <td>-1.905754</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>9690888.0</td>\n      <td>18435480.0</td>\n      <td>101176722.0</td>\n      <td>2.341606</td>\n      <td>5.428436</td>\n      <td>5.428436</td>\n      <td>2.607136</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>11035015.0</td>\n      <td>18435480.0</td>\n      <td>94579326.0</td>\n      <td>13.105385</td>\n      <td>12.433863</td>\n      <td>12.433863</td>\n      <td>12.107492</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <th>...</th>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">199</th>\n      <th rowspan=\"5\" valign=\"top\">2</th>\n      <th>5</th>\n      <td>596998.0</td>\n      <td>2243745.0</td>\n      <td>10846143.0</td>\n      <td>-502.093804</td>\n      <td>-515.057654</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>604275.0</td>\n      <td>2243745.0</td>\n      <td>9649341.0</td>\n      <td>-495.412649</td>\n      <td>-515.057654</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>1273638.0</td>\n      <td>2243745.0</td>\n      <td>10318671.0</td>\n      <td>119.142521</td>\n      <td>94.972668</td>\n      <td>94.972668</td>\n      <td>101.693199</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>1021207.0</td>\n      <td>2243745.0</td>\n      <td>12271716.0</td>\n      <td>-112.619283</td>\n      <td>-108.370772</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>682060.0</td>\n      <td>2243745.0</td>\n      <td>11444544.0</td>\n      <td>-423.996730</td>\n      <td>-413.385933</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n  </tbody>\n</table>\n<p>42000 rows \u00d7 7 columns</p>\n</div>\n\n\n\n\n```python\nprint(data_labels[50])\ndf_all_acts.loc[(50,0)]\n```\n\n    tensor(6)\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:2: PerformanceWarning: indexing past lexsort depth may impact performance.\n      \n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>norm(W)norm(X)</th>\n      <th>sum(norm(X))</th>\n      <th>sum(norm(W))</th>\n      <th>Wx</th>\n      <th>Wx+b</th>\n      <th>a</th>\n      <th>a_true</th>\n    </tr>\n    <tr>\n      <th>output node</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>10328027.0</td>\n      <td>20142450.0</td>\n      <td>101575323.0</td>\n      <td>0.475091</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>10031575.0</td>\n      <td>20142450.0</td>\n      <td>99886014.0</td>\n      <td>-1.898899</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>11218257.0</td>\n      <td>20142450.0</td>\n      <td>95635269.0</td>\n      <td>7.604060</td>\n      <td>5.428436</td>\n      <td>5.428436</td>\n      <td>6.597994</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>11818030.0</td>\n      <td>20142450.0</td>\n      <td>101176722.0</td>\n      <td>12.407047</td>\n      <td>12.433863</td>\n      <td>12.433863</td>\n      <td>12.708588</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>9299017.0</td>\n      <td>20142450.0</td>\n      <td>94579326.0</td>\n      <td>-7.765229</td>\n      <td>-8.582420</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>95</th>\n      <td>8049976.0</td>\n      <td>20142450.0</td>\n      <td>105060834.0</td>\n      <td>-17.767560</td>\n      <td>-15.587848</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>96</th>\n      <td>9271061.0</td>\n      <td>20142450.0</td>\n      <td>97347555.0</td>\n      <td>-7.989101</td>\n      <td>-8.582420</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>97</th>\n      <td>10241632.0</td>\n      <td>20142450.0</td>\n      <td>106398495.0</td>\n      <td>-0.216761</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>98</th>\n      <td>9954893.0</td>\n      <td>20142450.0</td>\n      <td>100877022.0</td>\n      <td>-2.512969</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>99</th>\n      <td>11442822.0</td>\n      <td>20142450.0</td>\n      <td>97679223.0</td>\n      <td>9.402378</td>\n      <td>5.428436</td>\n      <td>5.428436</td>\n      <td>8.418477</td>\n    </tr>\n  </tbody>\n</table>\n<p>100 rows \u00d7 7 columns</p>\n</div>\n\n\n\n# Generate Phone and SLM Images\n\n\n```python\nL = 1\nif L > 0:\n    df_hidden_layers = {}\n    for l in range(L):\n        df_hidden_layers[l] = pandas.read_hdf((resultPath / f\"fc{l}_acts_ID_130_to_200_float_2pcts.h5\").as_posix(), f\"fc{l}_acts\")\n    \ndf_measured_acts = pandas.concat(df_hidden_layers, axis=0, \\\n                            keys=df_hidden_layers.keys(), names=[\"layer\", \"test_ID\", \"output node\"])\ndf_measured_acts.index = df_measured_acts.index.swaplevel(0,1)\ndf_measured_acts.loc[130]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>fcs.0.sim</th>\n      <th>ground_truth</th>\n      <th>fcs.0</th>\n    </tr>\n    <tr>\n      <th>layer</th>\n      <th>output node</th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"11\" valign=\"top\">0</th>\n      <th>0</th>\n      <td>-2.323618</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>-8.439739</td>\n      <td>-8.582420</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>-2.559680</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>-4.687803</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>-0.305664</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>95</th>\n      <td>-24.565556</td>\n      <td>-22.593276</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>96</th>\n      <td>-11.417867</td>\n      <td>-8.582420</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>97</th>\n      <td>-7.416481</td>\n      <td>-8.582420</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>98</th>\n      <td>-0.445431</td>\n      <td>-1.576992</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>99</th>\n      <td>10.123972</td>\n      <td>12.433863</td>\n      <td>16.756596</td>\n    </tr>\n  </tbody>\n</table>\n<p>100 rows \u00d7 3 columns</p>\n</div>\n\n\n\n\n```python\n\"\"\" Generate the weight images to be applied to SLM and save them. \"\"\"\n# Pre-process the SLM weight matrix by shifting all elements to non-negative.\n\nimport numpy as np\nfrom utils.helper_functions import ConvertPhoneImageToSLMImage, NormalizeWeights, CenterEmbedding\n\n# Indicate the current NN layer (the 1st layer has index 0)\nexpan_r = 9+2\n\n# Convert weight matrix to SLM control values using EXACTLY the same sequence of functions as in ONN_layer_prop()\nW = model.fcs[L].weight.data.t()\nW_til,_,_ = W_transform(W)\nW_norm = W_digitize(W_til).t()\nW_norm = W_norm.round().type(torch.uint8)\nblkIdx = Wrap_vec_to_square(torch.tensor(df_measured_acts.index.get_level_values(level=\"output node\").unique().values))\n\nslm_weights_numpy = {}\n\nfor i in range(W_norm.size(0)):\n    # Add a frame for alignment, and embed in a canvas of phone display size\n    w_norm_orig = torch.cat((W_norm[i,:],torch.tensor([0])))[blkIdx]\n    w_norm_expan = torch.repeat_interleave(w_norm_orig, expan_r, dim=0)\n    w_norm_expan = torch.repeat_interleave(w_norm_expan, expan_r, dim=1)\n    w_norm_embedded = CenterEmbedding(w_norm_expan, torch.zeros(1920, 1080, dtype=torch.uint8))\n    w_norm_slm = ConvertPhoneImageToSLMImage(w_norm_embedded, 1.0) # Convert the phone image to SLM image.\n\n    # Save the SLM patterns to image files.\n    w_norm_path = slmWeightPath / (f\"SLM_MLP_{expan_r}x_fc{L}_w{i}.bmp\")\n    w_norm_slm.save(w_norm_path.as_posix(), format = 'bmp') # PIL.Image.save can be saved as 8-bit greyscale bmp\n    \nw_norm_embedded = CenterEmbedding(torch.ones_like(w_norm_expan)*255, torch.zeros(1920, 1080, dtype=torch.uint8))\nw_norm_slm = ConvertPhoneImageToSLMImage(w_norm_embedded, 1.0) # Convert the phone image to SLM image.\n\n# Save the SLM patterns to image files.\nw_norm_path = slmWeightPath / (f\"SLM_MLP_{expan_r}x_fc{L}_wsum.bmp\")\nw_norm_slm.save(w_norm_path.as_posix(), format = 'bmp') # PIL.Image.save can be saved as 8-bit greyscale bmp\n    \n# Plot w_kaleidoscope \nprint(\"The normalized weight matrix to be applied on the SLM looks like below:\")\nfig, ax = plt.subplots()\nim = ax.imshow(w_norm_slm)\nfig.colorbar(im, ax=ax)\nplt.show()\n```\n\n    The normalized weight matrix to be applied on the SLM looks like below:\n\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n\n```python\n\"\"\" Generate the images to be displayed on the phone and save them. \"\"\"\n\ninput_data, data_labels = next(iter(subset_data_loader))\ninput_data = input_data.view(X.size(0), -1)\n\nsubPath = phoneImagePath /  (f\"fc{L}_2pcts\" )\nif not os.path.exists(subPath.as_posix()):\n    os.makedirs(subPath.as_posix())\n\npx_margin = 1\nblankImage = torch.zeros(3, 1920, 1080, dtype=torch.uint8)\n\nfor i, batchIdx in enumerate(range(130, 200)):\n    \n    # x is the output of the previous layer L-1 (L>0) or the input data (L==0).\n    if L > 0:\n        x = torch.tensor(df_measured_acts[\"fcs.0\"].loc[batchIdx, L-1, :].values)\n        #x = torch.tensor(df_all_acts[\"a_true\"].loc[batchIdx, L-1, :].values) # test mode\n    elif L == 0:\n        x = input_data[batchIdx,:]\n    \n    # Normalize each x to its max and min and scale to 7 bit to match the dynamical range of the phone.\n    # The operations here are performed EXACTLY the same as in ONN_layer_prop()\n    x_til,_,_ = X_transform(x.view(-1,1))\n    x_norm = X_digitize(x_til.squeeze()).round().type(torch.long) # round() cannot be omitted for type(torch.long) sometimes work as floor(0)\n    \n    # Add the singla-pixel frame for image alignment.\n    imToPhone = blankImage.clone()\n    x_norm_orig = torch.cat((x_norm,torch.tensor([0])))[blkIdx]\n    x_norm_expan = torch.repeat_interleave(x_norm_orig, expan_r, dim=0)\n    x_norm_expan = torch.repeat_interleave(x_norm_expan, expan_r, dim=1)\n    x_norm_spar = x_norm_expan\n    x_norm_spar[::expan_r,:] = 0\n    x_norm_spar[(expan_r-px_margin)::expan_r,:] = 0\n    x_norm_spar[:,::expan_r] = 0\n    x_norm_spar[:,(expan_r-px_margin)::expan_r] = 0\n    x_norm_embedded = CenterEmbedding(x_norm_spar, blankImage[1,:,:].type(torch.long))\n    imToPhone[1, :, :] = lut_p[x_norm_embedded.type(torch.long)] # no uniformness correction\n    #phone_corr_numpy = lut_p[(x_norm_embedded * sub_phone_mask).type(torch.long)]\n    #imToPhone[1, :, :] = phone_corr_numpy\n\n    # Save the generated image\n    imToPhone_PIL = transforms.ToPILImage()(imToPhone)\n    imToPhone_PIL.save((subPath / f\"test_{expan_r}x_gap2px_MLP_2pcts_fc{L}_digit_{data_labels[batchIdx]}_{batchIdx:05d}.png\").as_posix())\n\n# Generate and save a black image to be displayed on the phone for background and power saving.\nblackImage_PIL = transforms.ToPILImage()(blankImage)\nblackImage_PIL.save((phoneImagePath / \"black.png\").as_posix())\n\nprint(\"The normalized weight matrix to be applied on the SLM looks like below:\")\nfig, ax = plt.subplots()\nim = ax.imshow(imToPhone_PIL)\nfig.colorbar(im, ax=ax)\nplt.show()\n```\n\n    The normalized weight matrix to be applied on the SLM looks like below:\n\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n\n```python\nConvertPhoneImageToSLMImage(imToPhone[1,:,:], 1.0).save((slmWeightPath / \"alignment_check\").as_posix(), format = 'bmp')\n```\n\n# Acquire Data\n\n\n```python\n\"\"\" Set up MPPC experiment scheme. \"\"\"\n\nrepeats = 100\noscope.set_range(6)\noscope.set_offset(2)\noscope_info(oscope)\n```\n\n\n\n\n    {'ID': 'HEWLETT-PACKARD,54845A,US40240103,A.04.50\\n',\n     'x_range': 0.0001,\n     'x_unit': 'SECOND',\n     'y_range': 6.0,\n     'y_unit': 'VOLT',\n     'y_offset': 2.0,\n     'y_bounds': [-1.0, 5.0]}\n\n\n\n\n```python\n\"\"\" Set up the (empty) dataframe table for taking data. \"\"\"\n\nimport pandas\n\nrepeats = 50\ntest_digit_idx = np.arange(40)\nnode_idx = [*range(100), \"sum\", \"bkg\"]\ntime_ranges = [0.0001, ]\n#rowMultiIdx = pandas.MultiIndex.from_product([test_digit_idx, node_idx, time_ranges, np.arange(repeats)], names=[\"test_ID\", \"output_node\", \"time_range\", \"repeats\"])\nrowMultiIdx = pandas.MultiIndex.from_product([node_idx, time_ranges, np.arange(repeats)], names=[\"output_node\", \"time_range\", \"repeats\"])\n#df_volTraces = pandas.DataFrame(index=rowMultiIdx, columns=np.arange(1004))\n\nphoneLoadPath = phoneImagePath / f\"fc{L}_2pcts\"\nslmLoadPath = slmWeightPath \n\nprint(phoneLoadPath)\nprint(slmLoadPath)\nprint(rowMultiIdx)\n#print(df_volTraces)\n```\n\n    D:\\McMahon lab Dropbox\\peter mcmahon\\tw329\\Experiments\\12_01_20_4bit_randy_aug_MLP_100_100_MPPC\\phone_images\\fc1_2pcts\n    D:\\McMahon lab Dropbox\\peter mcmahon\\tw329\\Experiments\\12_01_20_4bit_randy_aug_MLP_100_100_MPPC\\slm_weights\n    MultiIndex([(    0, 0.0001,  0),\n                (    0, 0.0001,  1),\n                (    0, 0.0001,  2),\n                (    0, 0.0001,  3),\n                (    0, 0.0001,  4),\n                (    0, 0.0001,  5),\n                (    0, 0.0001,  6),\n                (    0, 0.0001,  7),\n                (    0, 0.0001,  8),\n                (    0, 0.0001,  9),\n                ...\n                ('bkg', 0.0001, 40),\n                ('bkg', 0.0001, 41),\n                ('bkg', 0.0001, 42),\n                ('bkg', 0.0001, 43),\n                ('bkg', 0.0001, 44),\n                ('bkg', 0.0001, 45),\n                ('bkg', 0.0001, 46),\n                ('bkg', 0.0001, 47),\n                ('bkg', 0.0001, 48),\n                ('bkg', 0.0001, 49)],\n               names=['output_node', 'time_range', 'repeats'], length=5100)\n\n\n\n```python\n\"\"\" Perform the inference of the trained model with ONN on test digits, and save the data. \"\"\"\n\nimport joblib, pickle, time\n\nexp_time = datetime.now()\nsavePath = resultPath /  (f\"MLP_fc{L}_{expan_r}x_marg_1px_2pcts_MPPC_{exp_time:%m%d_%H%M%S}\")\nprint(savePath)\nif not os.path.exists(savePath.as_posix()):\n    os.makedirs(savePath.as_posix())\n\noscope.instrument.write(\"TIM:RANG 0.0001\")\n\njoblib.dump([oscope_info(oscope),], savePath / 'exp_info.pkl')\ndataFile = pandas.HDFStore((savePath / \"mppc_vol_meas.h5\").as_posix())\n\n# write a black image to the phone to take the background\nblackImage_PIL = Image.open((phoneImagePath / \"black.png\").as_posix())\nblackImage_byte = PIL_to_bytestream(blackImage_PIL)\n\nfor idx in range(170, 200):\n#for idx in range(20):\n    t0 = time.time()\n    # Record background to capture potential voltage bias drift\n    aoab.write(blackImage_byte)\n    #time.sleep(0.5)\n    slmPattern_PIL = Image.open((slmLoadPath / f\"SLM_solid_0.bmp\").as_posix())\n    slm.updateArray((np.array(slmPattern_PIL)).astype('uint8'))\n    time.sleep(0.5)\n    \n    df = pandas.DataFrame(index=rowMultiIdx, columns=np.arange(1004))\n\n    for i in rowMultiIdx.get_level_values(\"repeats\").unique(): \n        trace = oscope.get_waveform()\n        df.loc[(\"bkg\", 0.0001, i), range(len(trace))] = trace\n        time.sleep(0.04)\n    print(f\"time_span=0.0001s, test_ID={idx}, label={data_labels[idx]}, output_node=bkg, voltage={trace.mean()}\")\n        \n    # Load the phone pattern\n    phonePattern_PIL = Image.open((phoneLoadPath / f\"test_{expan_r}x_gap2px_MLP_2pcts_fc{L}_digit_{data_labels[idx]}_{idx:05d}.png\").as_posix())\n    phonePattern_byte = PIL_to_bytestream(phonePattern_PIL)\n    aoab.write(phonePattern_byte)\n    time.sleep(0.5) # Wait for the pattern applied to be stable\n    for n in rowMultiIdx.get_level_values(\"output_node\").unique().drop(\"bkg\"):\n        # refresh the slm pattern\n        slmPattern_PIL = Image.open((slmLoadPath / f\"SLM_MLP_{expan_r}x_fc{L}_w{n}.bmp\").as_posix())\n        slm.updateArray((np.array(slmPattern_PIL)).astype('uint8'))\n        time.sleep(0.5) # Wait for the pattern applied to be stable\n        \n        for i in rowMultiIdx.get_level_values(\"repeats\").unique(): \n            trace = oscope.get_waveform()\n            df.loc[(n, 0.0001, i), range(len(trace))] = trace\n            time.sleep(0.04)\n        print(f\"time_span=0.0001s, test_ID={idx}, label={data_labels[idx]}, output_node={n}, voltage={trace.mean()}\")\n            \n        if n == 11 and idx == 170:\n            print(\"20 s to exit anydesk\")\n            time.sleep(20)  \n            \n    t1 = time.time()\n    print(f\"Time consumed for 1 sample = {t1-t0} s\")\n    t0 = t1\n    dataFile[str(idx)]=df \n    \ndataFile.close()\naoab.write(blackImage_byte)\nprint(\"Finished! Safe to change code now.\")\n```\n\n    D:\\McMahon lab Dropbox\\peter mcmahon\\tw329\\Experiments\\12_01_20_4bit_randy_aug_MLP_100_100_MPPC\\MLP_fc1_11x_marg_1px_2pcts_MPPC_1221_134418\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\IPython\\core\\interactiveshell.py:2878: PerformanceWarning: indexing past lexsort depth may impact performance.\n      raw_cell, store_history, silent, shell_futures)\n\n\n    time_span=0.0001s, test_ID=170, label=4, output_node=bkg, voltage=-0.003399402368813753\n    time_span=0.0001s, test_ID=170, label=4, output_node=0, voltage=0.01005079597234726\n    time_span=0.0001s, test_ID=170, label=4, output_node=1, voltage=0.01328486017882824\n    time_span=0.0001s, test_ID=170, label=4, output_node=2, voltage=0.008850596845149994\n    time_span=0.0001s, test_ID=170, label=4, output_node=3, voltage=0.008786853402853012\n    time_span=0.0001s, test_ID=170, label=4, output_node=4, voltage=0.004506971687078476\n    time_span=0.0001s, test_ID=170, label=4, output_node=5, voltage=0.007943226955831051\n    time_span=0.0001s, test_ID=170, label=4, output_node=6, voltage=0.010580677539110184\n    time_span=0.0001s, test_ID=170, label=4, output_node=7, voltage=0.010625497438013554\n    time_span=0.0001s, test_ID=170, label=4, output_node=8, voltage=0.007668327074497938\n    time_span=0.0001s, test_ID=170, label=4, output_node=9, voltage=0.008696215227246284\n    time_span=0.0001s, test_ID=170, label=4, output_node=10, voltage=0.0032838645856827497\n    time_span=0.0001s, test_ID=170, label=4, output_node=11, voltage=0.0061294822953641415\n    20 s to exit anydesk\n    time_span=0.0001s, test_ID=170, label=4, output_node=12, voltage=0.012250996194779873\n    time_span=0.0001s, test_ID=170, label=4, output_node=13, voltage=0.009659362956881523\n    time_span=0.0001s, test_ID=170, label=4, output_node=14, voltage=0.0067191231064498425\n    time_span=0.0001s, test_ID=170, label=4, output_node=15, voltage=0.010052789002656937\n    time_span=0.0001s, test_ID=170, label=4, output_node=16, voltage=0.011414341628551483\n    time_span=0.0001s, test_ID=170, label=4, output_node=17, voltage=0.008653386496007442\n    time_span=0.0001s, test_ID=170, label=4, output_node=18, voltage=0.00556872459128499\n    time_span=0.0001s, test_ID=170, label=4, output_node=19, voltage=0.01107768900692463\n    time_span=0.0001s, test_ID=170, label=4, output_node=20, voltage=0.009838645346462727\n    time_span=0.0001s, test_ID=170, label=4, output_node=21, voltage=0.007299800403416157\n    time_span=0.0001s, test_ID=170, label=4, output_node=22, voltage=0.008098606020212173\n    time_span=0.0001s, test_ID=170, label=4, output_node=23, voltage=0.0066832671873271465\n    time_span=0.0001s, test_ID=170, label=4, output_node=24, voltage=0.00548804784193635\n    time_span=0.0001s, test_ID=170, label=4, output_node=25, voltage=0.006579681299626827\n    time_span=0.0001s, test_ID=170, label=4, output_node=26, voltage=0.006564741022884846\n    time_span=0.0001s, test_ID=170, label=4, output_node=27, voltage=0.016387449577450752\n    time_span=0.0001s, test_ID=170, label=4, output_node=28, voltage=0.013970119878649712\n    time_span=0.0001s, test_ID=170, label=4, output_node=29, voltage=0.008704183623194695\n    time_span=0.0001s, test_ID=170, label=4, output_node=30, voltage=0.012421314604580402\n    time_span=0.0001s, test_ID=170, label=4, output_node=31, voltage=0.008914342150092125\n    time_span=0.0001s, test_ID=170, label=4, output_node=32, voltage=0.0030507969204336405\n    time_span=0.0001s, test_ID=170, label=4, output_node=33, voltage=0.016500994563102722\n    time_span=0.0001s, test_ID=170, label=4, output_node=34, voltage=0.007738047279417515\n    time_span=0.0001s, test_ID=170, label=4, output_node=35, voltage=0.013986055739223957\n    time_span=0.0001s, test_ID=170, label=4, output_node=36, voltage=0.013273904100060463\n    time_span=0.0001s, test_ID=170, label=4, output_node=37, voltage=0.008307769894599915\n    time_span=0.0001s, test_ID=170, label=4, output_node=38, voltage=0.005158367101103067\n    time_span=0.0001s, test_ID=170, label=4, output_node=39, voltage=0.0067878481931984425\n    time_span=0.0001s, test_ID=170, label=4, output_node=40, voltage=0.006198207847774029\n    time_span=0.0001s, test_ID=170, label=4, output_node=41, voltage=0.0046633463352918625\n    time_span=0.0001s, test_ID=170, label=4, output_node=42, voltage=0.010501992888748646\n    time_span=0.0001s, test_ID=170, label=4, output_node=43, voltage=0.005869521759450436\n    time_span=0.0001s, test_ID=170, label=4, output_node=44, voltage=0.0069292825646698475\n    time_span=0.0001s, test_ID=170, label=4, output_node=45, voltage=0.008931274525821209\n    time_span=0.0001s, test_ID=170, label=4, output_node=46, voltage=0.0048944223672151566\n    time_span=0.0001s, test_ID=170, label=4, output_node=47, voltage=0.011803784407675266\n    time_span=0.0001s, test_ID=170, label=4, output_node=48, voltage=0.013121513649821281\n    time_span=0.0001s, test_ID=170, label=4, output_node=49, voltage=0.008278884924948215\n    time_span=0.0001s, test_ID=170, label=4, output_node=50, voltage=0.005970119033008814\n    time_span=0.0001s, test_ID=170, label=4, output_node=51, voltage=0.009897410869598389\n    time_span=0.0001s, test_ID=170, label=4, output_node=52, voltage=0.008660358376801014\n    time_span=0.0001s, test_ID=170, label=4, output_node=53, voltage=0.007962151430547237\n    time_span=0.0001s, test_ID=170, label=4, output_node=54, voltage=0.005396414548158646\n    time_span=0.0001s, test_ID=170, label=4, output_node=55, voltage=0.006895418744534254\n    time_span=0.0001s, test_ID=170, label=4, output_node=56, voltage=0.010104581713676453\n    time_span=0.0001s, test_ID=170, label=4, output_node=57, voltage=0.011682271026074886\n    time_span=0.0001s, test_ID=170, label=4, output_node=58, voltage=0.007012948393821716\n    time_span=0.0001s, test_ID=170, label=4, output_node=59, voltage=0.011600596830248833\n    time_span=0.0001s, test_ID=170, label=4, output_node=60, voltage=0.007185259368270636\n    time_span=0.0001s, test_ID=170, label=4, output_node=61, voltage=0.009334661066532135\n    time_span=0.0001s, test_ID=170, label=4, output_node=62, voltage=0.0059621515683829784\n    time_span=0.0001s, test_ID=170, label=4, output_node=63, voltage=0.00447111576795578\n    time_span=0.0001s, test_ID=170, label=4, output_node=64, voltage=0.016039840877056122\n    time_span=0.0001s, test_ID=170, label=4, output_node=65, voltage=0.005549801047891378\n    time_span=0.0001s, test_ID=170, label=4, output_node=66, voltage=0.008071713149547577\n    time_span=0.0001s, test_ID=170, label=4, output_node=67, voltage=0.004887450486421585\n    time_span=0.0001s, test_ID=170, label=4, output_node=68, voltage=0.010992031544446945\n    time_span=0.0001s, test_ID=170, label=4, output_node=69, voltage=0.00933864526450634\n    time_span=0.0001s, test_ID=170, label=4, output_node=70, voltage=0.01199103519320488\n    time_span=0.0001s, test_ID=170, label=4, output_node=71, voltage=0.0066752987913787365\n    time_span=0.0001s, test_ID=170, label=4, output_node=72, voltage=0.009789841249585152\n    time_span=0.0001s, test_ID=170, label=4, output_node=73, voltage=0.011051792651414871\n    time_span=0.0001s, test_ID=170, label=4, output_node=74, voltage=0.008026892319321632\n    time_span=0.0001s, test_ID=170, label=4, output_node=75, voltage=0.0034402392338961363\n    time_span=0.0001s, test_ID=170, label=4, output_node=76, voltage=0.006162350997328758\n    time_span=0.0001s, test_ID=170, label=4, output_node=77, voltage=0.005591633729636669\n    time_span=0.0001s, test_ID=170, label=4, output_node=78, voltage=0.004601593594998121\n    time_span=0.0001s, test_ID=170, label=4, output_node=79, voltage=0.009227091446518898\n    time_span=0.0001s, test_ID=170, label=4, output_node=80, voltage=0.006412350572645664\n    time_span=0.0001s, test_ID=170, label=4, output_node=81, voltage=0.007789840921759605\n    time_span=0.0001s, test_ID=170, label=4, output_node=82, voltage=0.008646414615213871\n    time_span=0.0001s, test_ID=170, label=4, output_node=83, voltage=0.009317729622125626\n    time_span=0.0001s, test_ID=170, label=4, output_node=84, voltage=0.004818725399672985\n    time_span=0.0001s, test_ID=170, label=4, output_node=85, voltage=0.012066733092069626\n    time_span=0.0001s, test_ID=170, label=4, output_node=86, voltage=0.011552789248526096\n    time_span=0.0001s, test_ID=170, label=4, output_node=87, voltage=0.011325697414577007\n    time_span=0.0001s, test_ID=170, label=4, output_node=88, voltage=0.0059203184209764\n    time_span=0.0001s, test_ID=170, label=4, output_node=89, voltage=0.005653386935591698\n    time_span=0.0001s, test_ID=170, label=4, output_node=90, voltage=0.011809761635959148\n    time_span=0.0001s, test_ID=170, label=4, output_node=91, voltage=0.004232071805745363\n    time_span=0.0001s, test_ID=170, label=4, output_node=92, voltage=0.012215139344334602\n    time_span=0.0001s, test_ID=170, label=4, output_node=93, voltage=0.01081374567002058\n    time_span=0.0001s, test_ID=170, label=4, output_node=94, voltage=0.016099603846669197\n    time_span=0.0001s, test_ID=170, label=4, output_node=95, voltage=0.015372510068118572\n    time_span=0.0001s, test_ID=170, label=4, output_node=96, voltage=0.01223306730389595\n    time_span=0.0001s, test_ID=170, label=4, output_node=97, voltage=0.005257967859506607\n    time_span=0.0001s, test_ID=170, label=4, output_node=98, voltage=0.007733067497611046\n    time_span=0.0001s, test_ID=170, label=4, output_node=99, voltage=0.013783865608274937\n    time_span=0.0001s, test_ID=170, label=4, output_node=sum, voltage=0.026667330414056778\n    Time consumed for 1 sample = 642.5427150726318 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '170'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\pandas\\io\\pytables.py:556: PerformanceWarning: \n    your performance may suffer as PyTables will pickle object types that it cannot\n    map directly to c-types [inferred_type->mixed-integer,key->axis1_level0] [items->None]\n    \n      self.put(key, value)\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\IPython\\core\\interactiveshell.py:3418: PerformanceWarning: \n    your performance may suffer as PyTables will pickle object types that it cannot\n    map directly to c-types [inferred_type->floating,key->block0_values] [items->Int64Index([   0,    1,    2,    3,    4,    5,    6,    7,    8,    9,\n                ...\n                 994,  995,  996,  997,  998,  999, 1000, 1001, 1002, 1003],\n               dtype='int64', length=1004)]\n    \n      exec(code_obj, self.user_global_ns, self.user_ns)\n\n\n    time_span=0.0001s, test_ID=171, label=7, output_node=bkg, voltage=-0.0038087647408246994\n    time_span=0.0001s, test_ID=171, label=7, output_node=0, voltage=0.017330676317214966\n    time_span=0.0001s, test_ID=171, label=7, output_node=1, voltage=0.012082669883966446\n    time_span=0.0001s, test_ID=171, label=7, output_node=2, voltage=0.007800797000527382\n    time_span=0.0001s, test_ID=171, label=7, output_node=3, voltage=0.007703186944127083\n    time_span=0.0001s, test_ID=171, label=7, output_node=4, voltage=0.013669323176145554\n    time_span=0.0001s, test_ID=171, label=7, output_node=5, voltage=0.008218128234148026\n    time_span=0.0001s, test_ID=171, label=7, output_node=6, voltage=0.0066583664156496525\n    time_span=0.0001s, test_ID=171, label=7, output_node=7, voltage=0.011818725615739822\n    time_span=0.0001s, test_ID=171, label=7, output_node=8, voltage=0.0152370510622859\n    time_span=0.0001s, test_ID=171, label=7, output_node=9, voltage=0.012012948282063007\n    time_span=0.0001s, test_ID=171, label=7, output_node=10, voltage=0.01404382474720478\n    time_span=0.0001s, test_ID=171, label=7, output_node=11, voltage=0.009355578571557999\n    time_span=0.0001s, test_ID=171, label=7, output_node=12, voltage=0.008410358801484108\n    time_span=0.0001s, test_ID=171, label=7, output_node=13, voltage=0.008019920438528061\n    time_span=0.0001s, test_ID=171, label=7, output_node=14, voltage=0.00907968170940876\n    time_span=0.0001s, test_ID=171, label=7, output_node=15, voltage=0.009910359047353268\n    time_span=0.0001s, test_ID=171, label=7, output_node=16, voltage=0.014188246801495552\n    time_span=0.0001s, test_ID=171, label=7, output_node=17, voltage=0.005577689502388239\n    time_span=0.0001s, test_ID=171, label=7, output_node=18, voltage=0.009334661066532135\n    time_span=0.0001s, test_ID=171, label=7, output_node=19, voltage=0.008165339007973671\n    time_span=0.0001s, test_ID=171, label=7, output_node=20, voltage=0.011656374670565128\n    time_span=0.0001s, test_ID=171, label=7, output_node=21, voltage=0.008749004453420639\n    time_span=0.0001s, test_ID=171, label=7, output_node=22, voltage=0.011355578899383545\n    time_span=0.0001s, test_ID=171, label=7, output_node=23, voltage=0.008721115067601204\n    time_span=0.0001s, test_ID=171, label=7, output_node=24, voltage=0.01452091708779335\n    time_span=0.0001s, test_ID=171, label=7, output_node=25, voltage=0.011758963577449322\n    time_span=0.0001s, test_ID=171, label=7, output_node=26, voltage=0.01373306754976511\n    time_span=0.0001s, test_ID=171, label=7, output_node=27, voltage=0.012059761211276054\n    time_span=0.0001s, test_ID=171, label=7, output_node=28, voltage=0.01108864601701498\n    time_span=0.0001s, test_ID=171, label=7, output_node=29, voltage=0.004007968120276928\n    time_span=0.0001s, test_ID=171, label=7, output_node=30, voltage=0.009730080142617226\n    time_span=0.0001s, test_ID=171, label=7, output_node=31, voltage=0.01027689315378666\n    time_span=0.0001s, test_ID=171, label=7, output_node=32, voltage=0.009341632947325706\n    time_span=0.0001s, test_ID=171, label=7, output_node=33, voltage=0.011164342053234577\n    time_span=0.0001s, test_ID=171, label=7, output_node=34, voltage=0.010048805736005306\n    time_span=0.0001s, test_ID=171, label=7, output_node=35, voltage=0.006782868877053261\n    time_span=0.0001s, test_ID=171, label=7, output_node=36, voltage=0.01619621552526951\n    time_span=0.0001s, test_ID=171, label=7, output_node=37, voltage=0.009641434997320175\n    time_span=0.0001s, test_ID=171, label=7, output_node=38, voltage=0.010470119304955006\n    time_span=0.0001s, test_ID=171, label=7, output_node=39, voltage=0.009680278599262238\n    time_span=0.0001s, test_ID=171, label=7, output_node=40, voltage=0.011156374588608742\n    time_span=0.0001s, test_ID=171, label=7, output_node=41, voltage=0.010319720953702927\n    time_span=0.0001s, test_ID=171, label=7, output_node=42, voltage=0.013946214690804482\n    time_span=0.0001s, test_ID=171, label=7, output_node=43, voltage=0.016100598499178886\n    time_span=0.0001s, test_ID=171, label=7, output_node=44, voltage=0.013908366672694683\n    time_span=0.0001s, test_ID=171, label=7, output_node=45, voltage=0.011685259640216827\n    time_span=0.0001s, test_ID=171, label=7, output_node=46, voltage=0.008787848986685276\n    time_span=0.0001s, test_ID=171, label=7, output_node=47, voltage=0.008761952631175518\n    time_span=0.0001s, test_ID=171, label=7, output_node=48, voltage=0.007719123736023903\n    time_span=0.0001s, test_ID=171, label=7, output_node=49, voltage=0.008925299160182476\n    time_span=0.0001s, test_ID=171, label=7, output_node=50, voltage=0.013182271271944046\n    time_span=0.0001s, test_ID=171, label=7, output_node=51, voltage=0.005576693452894688\n    time_span=0.0001s, test_ID=171, label=7, output_node=52, voltage=0.018480081111192703\n    time_span=0.0001s, test_ID=171, label=7, output_node=53, voltage=0.009752987883985043\n    time_span=0.0001s, test_ID=171, label=7, output_node=54, voltage=0.009190238080918789\n    time_span=0.0001s, test_ID=171, label=7, output_node=55, voltage=0.007212151773273945\n    time_span=0.0001s, test_ID=171, label=7, output_node=56, voltage=0.005602590274065733\n    time_span=0.0001s, test_ID=171, label=7, output_node=57, voltage=0.005599601194262505\n    time_span=0.0001s, test_ID=171, label=7, output_node=58, voltage=0.017298804596066475\n    time_span=0.0001s, test_ID=171, label=7, output_node=59, voltage=0.008019920438528061\n    time_span=0.0001s, test_ID=171, label=7, output_node=60, voltage=0.01018725149333477\n    time_span=0.0001s, test_ID=171, label=7, output_node=61, voltage=0.011757967993617058\n    time_span=0.0001s, test_ID=171, label=7, output_node=62, voltage=0.006950198672711849\n    time_span=0.0001s, test_ID=171, label=7, output_node=63, voltage=0.01374900434166193\n    time_span=0.0001s, test_ID=171, label=7, output_node=64, voltage=0.01003784779459238\n    time_span=0.0001s, test_ID=171, label=7, output_node=65, voltage=0.010218127630650997\n    time_span=0.0001s, test_ID=171, label=7, output_node=66, voltage=0.007633466739207506\n    time_span=0.0001s, test_ID=171, label=7, output_node=67, voltage=0.008686254732310772\n    time_span=0.0001s, test_ID=171, label=7, output_node=68, voltage=0.011750000528991222\n    time_span=0.0001s, test_ID=171, label=7, output_node=69, voltage=0.010092630051076412\n    time_span=0.0001s, test_ID=171, label=7, output_node=70, voltage=0.01060856506228447\n    time_span=0.0001s, test_ID=171, label=7, output_node=71, voltage=0.006535856518894434\n    time_span=0.0001s, test_ID=171, label=7, output_node=72, voltage=0.01397111639380455\n    time_span=0.0001s, test_ID=171, label=7, output_node=73, voltage=0.01176394522190094\n    time_span=0.0001s, test_ID=171, label=7, output_node=74, voltage=0.016659362241625786\n    time_span=0.0001s, test_ID=171, label=7, output_node=75, voltage=0.002397410338744521\n    time_span=0.0001s, test_ID=171, label=7, output_node=76, voltage=0.010708167217671871\n    time_span=0.0001s, test_ID=171, label=7, output_node=77, voltage=0.011057768948376179\n    time_span=0.0001s, test_ID=171, label=7, output_node=78, voltage=0.00907968170940876\n    time_span=0.0001s, test_ID=171, label=7, output_node=79, voltage=0.010621513240039349\n    time_span=0.0001s, test_ID=171, label=7, output_node=80, voltage=0.011370518244802952\n    time_span=0.0001s, test_ID=171, label=7, output_node=81, voltage=0.011703187599778175\n    time_span=0.0001s, test_ID=171, label=7, output_node=82, voltage=0.011907370761036873\n    time_span=0.0001s, test_ID=171, label=7, output_node=83, voltage=0.013612549751996994\n    time_span=0.0001s, test_ID=171, label=7, output_node=84, voltage=0.0030348605941981077\n    time_span=0.0001s, test_ID=171, label=7, output_node=85, voltage=0.015064741484820843\n    time_span=0.0001s, test_ID=171, label=7, output_node=86, voltage=0.011193227022886276\n    time_span=0.0001s, test_ID=171, label=7, output_node=87, voltage=0.008607570081949234\n    time_span=0.0001s, test_ID=171, label=7, output_node=88, voltage=0.005424303002655506\n    time_span=0.0001s, test_ID=171, label=7, output_node=89, voltage=0.01883864589035511\n    time_span=0.0001s, test_ID=171, label=7, output_node=90, voltage=0.0178376492112875\n    time_span=0.0001s, test_ID=171, label=7, output_node=91, voltage=0.009889442473649979\n    time_span=0.0001s, test_ID=171, label=7, output_node=92, voltage=0.01424601674079895\n    time_span=0.0001s, test_ID=171, label=7, output_node=93, voltage=0.012680279091000557\n    time_span=0.0001s, test_ID=171, label=7, output_node=94, voltage=0.008329682052135468\n    time_span=0.0001s, test_ID=171, label=7, output_node=95, voltage=0.012271911837160587\n    time_span=0.0001s, test_ID=171, label=7, output_node=96, voltage=0.015134462155401707\n    time_span=0.0001s, test_ID=171, label=7, output_node=97, voltage=0.009549800306558609\n    time_span=0.0001s, test_ID=171, label=7, output_node=98, voltage=0.01356772892177105\n    time_span=0.0001s, test_ID=171, label=7, output_node=99, voltage=0.015331672504544258\n    time_span=0.0001s, test_ID=171, label=7, output_node=sum, voltage=0.03271215409040451\n    Time consumed for 1 sample = 625.5949375629425 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '171'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=172, label=2, output_node=bkg, voltage=-0.004269920289516449\n    time_span=0.0001s, test_ID=172, label=2, output_node=0, voltage=0.009460159577429295\n    time_span=0.0001s, test_ID=172, label=2, output_node=1, voltage=0.009093624539673328\n    time_span=0.0001s, test_ID=172, label=2, output_node=2, voltage=0.018907371908426285\n    time_span=0.0001s, test_ID=172, label=2, output_node=3, voltage=0.011152391321957111\n    time_span=0.0001s, test_ID=172, label=2, output_node=4, voltage=0.016702190041542053\n    time_span=0.0001s, test_ID=172, label=2, output_node=5, voltage=0.017623506486415863\n    time_span=0.0001s, test_ID=172, label=2, output_node=6, voltage=0.01776294782757759\n    time_span=0.0001s, test_ID=172, label=2, output_node=7, voltage=0.0055707176215946674\n    time_span=0.0001s, test_ID=172, label=2, output_node=8, voltage=0.008940238505601883\n    time_span=0.0001s, test_ID=172, label=2, output_node=9, voltage=0.013458166271448135\n    time_span=0.0001s, test_ID=172, label=2, output_node=10, voltage=0.008355577476322651\n    time_span=0.0001s, test_ID=172, label=2, output_node=11, voltage=0.01524501945823431\n    time_span=0.0001s, test_ID=172, label=2, output_node=12, voltage=0.010335656814277172\n    time_span=0.0001s, test_ID=172, label=2, output_node=13, voltage=0.015072708949446678\n    time_span=0.0001s, test_ID=172, label=2, output_node=14, voltage=0.01548406295478344\n    time_span=0.0001s, test_ID=172, label=2, output_node=15, voltage=0.012654383666813374\n    time_span=0.0001s, test_ID=172, label=2, output_node=16, voltage=0.014960158616304398\n    time_span=0.0001s, test_ID=172, label=2, output_node=17, voltage=0.014360558241605759\n    time_span=0.0001s, test_ID=172, label=2, output_node=18, voltage=0.014811753295361996\n    time_span=0.0001s, test_ID=172, label=2, output_node=19, voltage=0.00625796802341938\n    time_span=0.0001s, test_ID=172, label=2, output_node=20, voltage=0.01708366535604\n    time_span=0.0001s, test_ID=172, label=2, output_node=21, voltage=0.011657370254397392\n    time_span=0.0001s, test_ID=172, label=2, output_node=22, voltage=0.01230179239064455\n    time_span=0.0001s, test_ID=172, label=2, output_node=23, voltage=0.01971215195953846\n    time_span=0.0001s, test_ID=172, label=2, output_node=24, voltage=0.018274899572134018\n    time_span=0.0001s, test_ID=172, label=2, output_node=25, voltage=0.01330079697072506\n    time_span=0.0001s, test_ID=172, label=2, output_node=26, voltage=0.015868525952100754\n    time_span=0.0001s, test_ID=172, label=2, output_node=27, voltage=0.004763944074511528\n    time_span=0.0001s, test_ID=172, label=2, output_node=28, voltage=0.011496015824377537\n    time_span=0.0001s, test_ID=172, label=2, output_node=29, voltage=0.014183267019689083\n    time_span=0.0001s, test_ID=172, label=2, output_node=30, voltage=0.009987052530050278\n    time_span=0.0001s, test_ID=172, label=2, output_node=31, voltage=0.009901394136250019\n    time_span=0.0001s, test_ID=172, label=2, output_node=32, voltage=0.01521713100373745\n    time_span=0.0001s, test_ID=172, label=2, output_node=33, voltage=0.008313745260238647\n    time_span=0.0001s, test_ID=172, label=2, output_node=34, voltage=0.014127490110695362\n    time_span=0.0001s, test_ID=172, label=2, output_node=35, voltage=0.008294820785522461\n    time_span=0.0001s, test_ID=172, label=2, output_node=36, voltage=0.004393426701426506\n    time_span=0.0001s, test_ID=172, label=2, output_node=37, voltage=0.007832669652998447\n    time_span=0.0001s, test_ID=172, label=2, output_node=38, voltage=0.009213147684931755\n    time_span=0.0001s, test_ID=172, label=2, output_node=39, voltage=0.01376095600426197\n    time_span=0.0001s, test_ID=172, label=2, output_node=40, voltage=0.016018925234675407\n    time_span=0.0001s, test_ID=172, label=2, output_node=41, voltage=0.013932271860539913\n    time_span=0.0001s, test_ID=172, label=2, output_node=42, voltage=0.011657371185719967\n    time_span=0.0001s, test_ID=172, label=2, output_node=43, voltage=0.015146414749324322\n    time_span=0.0001s, test_ID=172, label=2, output_node=44, voltage=0.015410359017550945\n    time_span=0.0001s, test_ID=172, label=2, output_node=45, voltage=0.013044821098446846\n    time_span=0.0001s, test_ID=172, label=2, output_node=46, voltage=0.009339641779661179\n    time_span=0.0001s, test_ID=172, label=2, output_node=47, voltage=0.013338644988834858\n    time_span=0.0001s, test_ID=172, label=2, output_node=48, voltage=0.011290837079286575\n    time_span=0.0001s, test_ID=172, label=2, output_node=49, voltage=0.011914342641830444\n    time_span=0.0001s, test_ID=172, label=2, output_node=50, voltage=0.008627490140497684\n    time_span=0.0001s, test_ID=172, label=2, output_node=51, voltage=0.0103575699031353\n    time_span=0.0001s, test_ID=172, label=2, output_node=52, voltage=0.012997012585401535\n    time_span=0.0001s, test_ID=172, label=2, output_node=53, voltage=0.010574701242148876\n    time_span=0.0001s, test_ID=172, label=2, output_node=54, voltage=0.01608266867697239\n    time_span=0.0001s, test_ID=172, label=2, output_node=55, voltage=0.01703486032783985\n    time_span=0.0001s, test_ID=172, label=2, output_node=56, voltage=0.008059759624302387\n    time_span=0.0001s, test_ID=172, label=2, output_node=57, voltage=0.010921315290033817\n    time_span=0.0001s, test_ID=172, label=2, output_node=58, voltage=0.015147410333156586\n    time_span=0.0001s, test_ID=172, label=2, output_node=59, voltage=0.01068924367427826\n    time_span=0.0001s, test_ID=172, label=2, output_node=60, voltage=0.005924302618950605\n    time_span=0.0001s, test_ID=172, label=2, output_node=61, voltage=0.015827689319849014\n    time_span=0.0001s, test_ID=172, label=2, output_node=62, voltage=0.011667330749332905\n    time_span=0.0001s, test_ID=172, label=2, output_node=63, voltage=0.017450200393795967\n    time_span=0.0001s, test_ID=172, label=2, output_node=64, voltage=0.0036653385031968355\n    time_span=0.0001s, test_ID=172, label=2, output_node=65, voltage=0.013808765448629856\n    time_span=0.0001s, test_ID=172, label=2, output_node=66, voltage=0.011886454187333584\n    time_span=0.0001s, test_ID=172, label=2, output_node=67, voltage=0.008972112089395523\n    time_span=0.0001s, test_ID=172, label=2, output_node=68, voltage=0.012420319020748138\n    time_span=0.0001s, test_ID=172, label=2, output_node=69, voltage=0.011299800127744675\n    time_span=0.0001s, test_ID=172, label=2, output_node=70, voltage=0.014250995591282845\n    time_span=0.0001s, test_ID=172, label=2, output_node=71, voltage=0.014325697906315327\n    time_span=0.0001s, test_ID=172, label=2, output_node=72, voltage=0.01447709184139967\n    time_span=0.0001s, test_ID=172, label=2, output_node=73, voltage=0.007388445548713207\n    time_span=0.0001s, test_ID=172, label=2, output_node=74, voltage=0.007552789058536291\n    time_span=0.0001s, test_ID=172, label=2, output_node=75, voltage=0.015396413393318653\n    time_span=0.0001s, test_ID=172, label=2, output_node=76, voltage=0.007623506244271994\n    time_span=0.0001s, test_ID=172, label=2, output_node=77, voltage=0.014159361831843853\n    time_span=0.0001s, test_ID=172, label=2, output_node=78, voltage=0.015020916238427162\n    time_span=0.0001s, test_ID=172, label=2, output_node=79, voltage=0.01184462197124958\n    time_span=0.0001s, test_ID=172, label=2, output_node=80, voltage=0.006987051572650671\n    time_span=0.0001s, test_ID=172, label=2, output_node=81, voltage=0.01619621552526951\n    time_span=0.0001s, test_ID=172, label=2, output_node=82, voltage=0.011996015906333923\n    time_span=0.0001s, test_ID=172, label=2, output_node=83, voltage=0.008112550713121891\n    time_span=0.0001s, test_ID=172, label=2, output_node=84, voltage=0.013801793567836285\n    time_span=0.0001s, test_ID=172, label=2, output_node=85, voltage=0.007127490360289812\n    time_span=0.0001s, test_ID=172, label=2, output_node=86, voltage=0.013100597076117992\n    time_span=0.0001s, test_ID=172, label=2, output_node=87, voltage=0.008799801580607891\n    time_span=0.0001s, test_ID=172, label=2, output_node=88, voltage=0.008990040980279446\n    time_span=0.0001s, test_ID=172, label=2, output_node=89, voltage=0.012929283082485199\n    time_span=0.0001s, test_ID=172, label=2, output_node=90, voltage=0.014281872659921646\n    time_span=0.0001s, test_ID=172, label=2, output_node=91, voltage=0.009530876763164997\n    time_span=0.0001s, test_ID=172, label=2, output_node=92, voltage=0.013500995934009552\n    time_span=0.0001s, test_ID=172, label=2, output_node=93, voltage=0.010249003767967224\n    time_span=0.0001s, test_ID=172, label=2, output_node=94, voltage=0.006524900905787945\n    time_span=0.0001s, test_ID=172, label=2, output_node=95, voltage=0.007897410541772842\n    time_span=0.0001s, test_ID=172, label=2, output_node=96, voltage=0.005906374659389257\n    time_span=0.0001s, test_ID=172, label=2, output_node=97, voltage=0.016772909089922905\n    time_span=0.0001s, test_ID=172, label=2, output_node=98, voltage=0.013591633178293705\n    time_span=0.0001s, test_ID=172, label=2, output_node=99, voltage=0.008452191017568111\n    time_span=0.0001s, test_ID=172, label=2, output_node=sum, voltage=0.03448307141661644\n    Time consumed for 1 sample = 626.4017517566681 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '172'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=173, label=3, output_node=bkg, voltage=-0.005169322248548269\n    time_span=0.0001s, test_ID=173, label=3, output_node=0, voltage=0.008794820867478848\n    time_span=0.0001s, test_ID=173, label=3, output_node=1, voltage=0.004312749020755291\n    time_span=0.0001s, test_ID=173, label=3, output_node=2, voltage=0.010720119811594486\n    time_span=0.0001s, test_ID=173, label=3, output_node=3, voltage=0.008540837094187737\n    time_span=0.0001s, test_ID=173, label=3, output_node=4, voltage=0.008799800649285316\n    time_span=0.0001s, test_ID=173, label=3, output_node=5, voltage=0.009125499054789543\n    time_span=0.0001s, test_ID=173, label=3, output_node=6, voltage=0.008900399319827557\n    time_span=0.0001s, test_ID=173, label=3, output_node=7, voltage=0.006000996567308903\n    time_span=0.0001s, test_ID=173, label=3, output_node=8, voltage=0.0020697209984064102\n    time_span=0.0001s, test_ID=173, label=3, output_node=9, voltage=0.004312749020755291\n    time_span=0.0001s, test_ID=173, label=3, output_node=10, voltage=0.0019561753142625093\n    time_span=0.0001s, test_ID=173, label=3, output_node=11, voltage=0.006944223307073116\n    time_span=0.0001s, test_ID=173, label=3, output_node=12, voltage=0.004721115343272686\n    time_span=0.0001s, test_ID=173, label=3, output_node=13, voltage=0.011118525639176369\n    time_span=0.0001s, test_ID=173, label=3, output_node=14, voltage=0.010513943620026112\n    time_span=0.0001s, test_ID=173, label=3, output_node=15, voltage=0.0044601596891880035\n    time_span=0.0001s, test_ID=173, label=3, output_node=16, voltage=0.009736056439578533\n    time_span=0.0001s, test_ID=173, label=3, output_node=17, voltage=0.006506972014904022\n    time_span=0.0001s, test_ID=173, label=3, output_node=18, voltage=0.004493027459830046\n    time_span=0.0001s, test_ID=173, label=3, output_node=19, voltage=0.008520916104316711\n    time_span=0.0001s, test_ID=173, label=3, output_node=20, voltage=0.004181274678558111\n    time_span=0.0001s, test_ID=173, label=3, output_node=21, voltage=0.004260955844074488\n    time_span=0.0001s, test_ID=173, label=3, output_node=22, voltage=0.009154382161796093\n    time_span=0.0001s, test_ID=173, label=3, output_node=23, voltage=0.013990039005875587\n    time_span=0.0001s, test_ID=173, label=3, output_node=24, voltage=0.006345618050545454\n    time_span=0.0001s, test_ID=173, label=3, output_node=25, voltage=0.00705677317455411\n    time_span=0.0001s, test_ID=173, label=3, output_node=26, voltage=0.008729083463549614\n    time_span=0.0001s, test_ID=173, label=3, output_node=27, voltage=0.006022908259183168\n    time_span=0.0001s, test_ID=173, label=3, output_node=28, voltage=0.006845617666840553\n    time_span=0.0001s, test_ID=173, label=3, output_node=29, voltage=0.004153386689722538\n    time_span=0.0001s, test_ID=173, label=3, output_node=30, voltage=0.004867529962211847\n    time_span=0.0001s, test_ID=173, label=3, output_node=31, voltage=0.007750995922833681\n    time_span=0.0001s, test_ID=173, label=3, output_node=32, voltage=0.008667330257594585\n    time_span=0.0001s, test_ID=173, label=3, output_node=33, voltage=0.0025766934268176556\n    time_span=0.0001s, test_ID=173, label=3, output_node=34, voltage=0.0006195218884386122\n    time_span=0.0001s, test_ID=173, label=3, output_node=35, voltage=0.01129482127726078\n    time_span=0.0001s, test_ID=173, label=3, output_node=36, voltage=0.003796813078224659\n    time_span=0.0001s, test_ID=173, label=3, output_node=37, voltage=0.0022191237658262253\n    time_span=0.0001s, test_ID=173, label=3, output_node=38, voltage=0.007098606321960688\n    time_span=0.0001s, test_ID=173, label=3, output_node=39, voltage=0.005673306994140148\n    time_span=0.0001s, test_ID=173, label=3, output_node=40, voltage=0.00907270796597004\n    time_span=0.0001s, test_ID=173, label=3, output_node=41, voltage=0.009462151676416397\n    time_span=0.0001s, test_ID=173, label=3, output_node=42, voltage=0.0033187251538038254\n    time_span=0.0001s, test_ID=173, label=3, output_node=43, voltage=0.010066733695566654\n    time_span=0.0001s, test_ID=173, label=3, output_node=44, voltage=0.008553784340620041\n    time_span=0.0001s, test_ID=173, label=3, output_node=45, voltage=0.008095617406070232\n    time_span=0.0001s, test_ID=173, label=3, output_node=46, voltage=0.005862549412995577\n    time_span=0.0001s, test_ID=173, label=3, output_node=47, voltage=0.00998207088559866\n    time_span=0.0001s, test_ID=173, label=3, output_node=48, voltage=0.0030737051274627447\n    time_span=0.0001s, test_ID=173, label=3, output_node=49, voltage=0.002921314910054207\n    time_span=0.0001s, test_ID=173, label=3, output_node=50, voltage=0.007836653850972652\n    time_span=0.0001s, test_ID=173, label=3, output_node=51, voltage=0.004458167124539614\n    time_span=0.0001s, test_ID=173, label=3, output_node=52, voltage=0.009768924675881863\n    time_span=0.0001s, test_ID=173, label=3, output_node=53, voltage=0.013039839453995228\n    time_span=0.0001s, test_ID=173, label=3, output_node=54, voltage=0.010718126781284809\n    time_span=0.0001s, test_ID=173, label=3, output_node=55, voltage=0.010023904964327812\n    time_span=0.0001s, test_ID=173, label=3, output_node=56, voltage=0.010557767935097218\n    time_span=0.0001s, test_ID=173, label=3, output_node=57, voltage=0.009605578146874905\n    time_span=0.0001s, test_ID=173, label=3, output_node=58, voltage=0.006467131432145834\n    time_span=0.0001s, test_ID=173, label=3, output_node=59, voltage=0.0072340634651482105\n    time_span=0.0001s, test_ID=173, label=3, output_node=60, voltage=0.00536653446033597\n    time_span=0.0001s, test_ID=173, label=3, output_node=61, voltage=0.012284860014915466\n    time_span=0.0001s, test_ID=173, label=3, output_node=62, voltage=0.003353585721924901\n    time_span=0.0001s, test_ID=173, label=3, output_node=63, voltage=0.0064780875109136105\n    time_span=0.0001s, test_ID=173, label=3, output_node=64, voltage=0.005094621330499649\n    time_span=0.0001s, test_ID=173, label=3, output_node=65, voltage=0.0027818724047392607\n    time_span=0.0001s, test_ID=173, label=3, output_node=66, voltage=0.004054781049489975\n    time_span=0.0001s, test_ID=173, label=3, output_node=67, voltage=0.007375498302280903\n    time_span=0.0001s, test_ID=173, label=3, output_node=68, voltage=0.006270916201174259\n    time_span=0.0001s, test_ID=173, label=3, output_node=69, voltage=0.013585656881332397\n    time_span=0.0001s, test_ID=173, label=3, output_node=70, voltage=0.008209164254367352\n    time_span=0.0001s, test_ID=173, label=3, output_node=71, voltage=0.012687251903116703\n    time_span=0.0001s, test_ID=173, label=3, output_node=72, voltage=0.008972111158072948\n    time_span=0.0001s, test_ID=173, label=3, output_node=73, voltage=0.007289840839803219\n    time_span=0.0001s, test_ID=173, label=3, output_node=74, voltage=0.009569722227752209\n    time_span=0.0001s, test_ID=173, label=3, output_node=75, voltage=0.007043824531137943\n    time_span=0.0001s, test_ID=173, label=3, output_node=76, voltage=0.0065727089531719685\n    time_span=0.0001s, test_ID=173, label=3, output_node=77, voltage=0.00804083701223135\n    time_span=0.0001s, test_ID=173, label=3, output_node=78, voltage=0.0024551793467253447\n    time_span=0.0001s, test_ID=173, label=3, output_node=79, voltage=0.007733067497611046\n    time_span=0.0001s, test_ID=173, label=3, output_node=80, voltage=0.0009980081813409925\n    time_span=0.0001s, test_ID=173, label=3, output_node=81, voltage=0.010686255060136318\n    time_span=0.0001s, test_ID=173, label=3, output_node=82, voltage=0.011811752803623676\n    time_span=0.0001s, test_ID=173, label=3, output_node=83, voltage=0.012986055575311184\n    time_span=0.0001s, test_ID=173, label=3, output_node=84, voltage=0.0012559760361909866\n    time_span=0.0001s, test_ID=173, label=3, output_node=85, voltage=0.002297808649018407\n    time_span=0.0001s, test_ID=173, label=3, output_node=86, voltage=0.011392430402338505\n    time_span=0.0001s, test_ID=173, label=3, output_node=87, voltage=0.008828685618937016\n    time_span=0.0001s, test_ID=173, label=3, output_node=88, voltage=0.01611354760825634\n    time_span=0.0001s, test_ID=173, label=3, output_node=89, voltage=0.007189243100583553\n    time_span=0.0001s, test_ID=173, label=3, output_node=90, voltage=0.006406374741345644\n    time_span=0.0001s, test_ID=173, label=3, output_node=91, voltage=0.002818725071847439\n    time_span=0.0001s, test_ID=173, label=3, output_node=92, voltage=0.005951195489615202\n    time_span=0.0001s, test_ID=173, label=3, output_node=93, voltage=0.007690239232033491\n    time_span=0.0001s, test_ID=173, label=3, output_node=94, voltage=0.006936255376785994\n    time_span=0.0001s, test_ID=173, label=3, output_node=95, voltage=0.003617529757320881\n    time_span=0.0001s, test_ID=173, label=3, output_node=96, voltage=0.010356573387980461\n    time_span=0.0001s, test_ID=173, label=3, output_node=97, voltage=0.010611552745103836\n    time_span=0.0001s, test_ID=173, label=3, output_node=98, voltage=0.006140438374131918\n    time_span=0.0001s, test_ID=173, label=3, output_node=99, voltage=0.009714143350720406\n    time_span=0.0001s, test_ID=173, label=3, output_node=sum, voltage=0.026760956272482872\n    Time consumed for 1 sample = 625.0013835430145 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '173'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=174, label=2, output_node=bkg, voltage=-0.005049800965934992\n    time_span=0.0001s, test_ID=174, label=2, output_node=0, voltage=0.0066533866338431835\n    time_span=0.0001s, test_ID=174, label=2, output_node=1, voltage=0.006783864460885525\n    time_span=0.0001s, test_ID=174, label=2, output_node=2, voltage=0.012615538202226162\n    time_span=0.0001s, test_ID=174, label=2, output_node=3, voltage=0.008738048374652863\n    time_span=0.0001s, test_ID=174, label=2, output_node=4, voltage=0.020632470026612282\n    time_span=0.0001s, test_ID=174, label=2, output_node=5, voltage=0.013416334986686707\n    time_span=0.0001s, test_ID=174, label=2, output_node=6, voltage=0.015367529354989529\n    time_span=0.0001s, test_ID=174, label=2, output_node=7, voltage=0.004054781049489975\n    time_span=0.0001s, test_ID=174, label=2, output_node=8, voltage=0.018146412447094917\n    time_span=0.0001s, test_ID=174, label=2, output_node=9, voltage=0.018093625083565712\n    time_span=0.0001s, test_ID=174, label=2, output_node=10, voltage=0.007746016141027212\n    time_span=0.0001s, test_ID=174, label=2, output_node=11, voltage=0.011828684248030186\n    time_span=0.0001s, test_ID=174, label=2, output_node=12, voltage=0.012076693587005138\n    time_span=0.0001s, test_ID=174, label=2, output_node=13, voltage=0.008598605170845985\n    time_span=0.0001s, test_ID=174, label=2, output_node=14, voltage=0.010566731914877892\n    time_span=0.0001s, test_ID=174, label=2, output_node=15, voltage=0.009893426671624184\n    time_span=0.0001s, test_ID=174, label=2, output_node=16, voltage=0.00868426263332367\n    time_span=0.0001s, test_ID=174, label=2, output_node=17, voltage=0.008779879659414291\n    time_span=0.0001s, test_ID=174, label=2, output_node=18, voltage=0.009536853060126305\n    time_span=0.0001s, test_ID=174, label=2, output_node=19, voltage=0.019763944670557976\n    time_span=0.0001s, test_ID=174, label=2, output_node=20, voltage=0.015973107889294624\n    time_span=0.0001s, test_ID=174, label=2, output_node=21, voltage=0.013454183004796505\n    time_span=0.0001s, test_ID=174, label=2, output_node=22, voltage=0.014440239407122135\n    time_span=0.0001s, test_ID=174, label=2, output_node=23, voltage=0.012885458767414093\n    time_span=0.0001s, test_ID=174, label=2, output_node=24, voltage=0.01766035705804825\n    time_span=0.0001s, test_ID=174, label=2, output_node=25, voltage=0.013719123788177967\n    time_span=0.0001s, test_ID=174, label=2, output_node=26, voltage=0.01668824814260006\n    time_span=0.0001s, test_ID=174, label=2, output_node=27, voltage=0.0063705178909003735\n    time_span=0.0001s, test_ID=174, label=2, output_node=28, voltage=0.015756972134113312\n    time_span=0.0001s, test_ID=174, label=2, output_node=29, voltage=0.012209163047373295\n    time_span=0.0001s, test_ID=174, label=2, output_node=30, voltage=0.008161354809999466\n    time_span=0.0001s, test_ID=174, label=2, output_node=31, voltage=0.010402390733361244\n    time_span=0.0001s, test_ID=174, label=2, output_node=32, voltage=0.013338645920157433\n    time_span=0.0001s, test_ID=174, label=2, output_node=33, voltage=0.009233067743480206\n    time_span=0.0001s, test_ID=174, label=2, output_node=34, voltage=0.01342231035232544\n    time_span=0.0001s, test_ID=174, label=2, output_node=35, voltage=0.004491036292165518\n    time_span=0.0001s, test_ID=174, label=2, output_node=36, voltage=0.01102788932621479\n    time_span=0.0001s, test_ID=174, label=2, output_node=37, voltage=0.015129481442272663\n    time_span=0.0001s, test_ID=174, label=2, output_node=38, voltage=0.013063745573163033\n    time_span=0.0001s, test_ID=174, label=2, output_node=39, voltage=0.01148207113146782\n    time_span=0.0001s, test_ID=174, label=2, output_node=40, voltage=0.011563745327293873\n    time_span=0.0001s, test_ID=174, label=2, output_node=41, voltage=0.008075697347521782\n    time_span=0.0001s, test_ID=174, label=2, output_node=42, voltage=0.01168724987655878\n    time_span=0.0001s, test_ID=174, label=2, output_node=43, voltage=0.013416334055364132\n    time_span=0.0001s, test_ID=174, label=2, output_node=44, voltage=0.017147410660982132\n    time_span=0.0001s, test_ID=174, label=2, output_node=45, voltage=0.016670318320393562\n    time_span=0.0001s, test_ID=174, label=2, output_node=46, voltage=0.009440239518880844\n    time_span=0.0001s, test_ID=174, label=2, output_node=47, voltage=0.013689243234694004\n    time_span=0.0001s, test_ID=174, label=2, output_node=48, voltage=0.00960956234484911\n    time_span=0.0001s, test_ID=174, label=2, output_node=49, voltage=0.012307769618928432\n    time_span=0.0001s, test_ID=174, label=2, output_node=50, voltage=0.014078686013817787\n    time_span=0.0001s, test_ID=174, label=2, output_node=51, voltage=0.0114571712911129\n    time_span=0.0001s, test_ID=174, label=2, output_node=52, voltage=0.015149402432143688\n    time_span=0.0001s, test_ID=174, label=2, output_node=53, voltage=0.013885458000004292\n    time_span=0.0001s, test_ID=174, label=2, output_node=54, voltage=0.01812748797237873\n    time_span=0.0001s, test_ID=174, label=2, output_node=55, voltage=0.011411354877054691\n    time_span=0.0001s, test_ID=174, label=2, output_node=56, voltage=0.008881473913788795\n    time_span=0.0001s, test_ID=174, label=2, output_node=57, voltage=0.004001992288976908\n    time_span=0.0001s, test_ID=174, label=2, output_node=58, voltage=0.021790839731693268\n    time_span=0.0001s, test_ID=174, label=2, output_node=59, voltage=0.01583864539861679\n    time_span=0.0001s, test_ID=174, label=2, output_node=60, voltage=0.010618526488542557\n    time_span=0.0001s, test_ID=174, label=2, output_node=61, voltage=0.013366534374654293\n    time_span=0.0001s, test_ID=174, label=2, output_node=62, voltage=0.011624501086771488\n    time_span=0.0001s, test_ID=174, label=2, output_node=63, voltage=0.019966134801506996\n    time_span=0.0001s, test_ID=174, label=2, output_node=64, voltage=0.011755975894629955\n    time_span=0.0001s, test_ID=174, label=2, output_node=65, voltage=0.007916335016489029\n    time_span=0.0001s, test_ID=174, label=2, output_node=66, voltage=0.012901394627988338\n    time_span=0.0001s, test_ID=174, label=2, output_node=67, voltage=0.01102490071207285\n    time_span=0.0001s, test_ID=174, label=2, output_node=68, voltage=0.008454183116555214\n    time_span=0.0001s, test_ID=174, label=2, output_node=69, voltage=0.009751992300152779\n    time_span=0.0001s, test_ID=174, label=2, output_node=70, voltage=0.013138446025550365\n    time_span=0.0001s, test_ID=174, label=2, output_node=71, voltage=0.01130776945501566\n    time_span=0.0001s, test_ID=174, label=2, output_node=72, voltage=0.014705179259181023\n    time_span=0.0001s, test_ID=174, label=2, output_node=73, voltage=0.010611552745103836\n    time_span=0.0001s, test_ID=174, label=2, output_node=74, voltage=0.014563744887709618\n    time_span=0.0001s, test_ID=174, label=2, output_node=75, voltage=0.00549402367323637\n    time_span=0.0001s, test_ID=174, label=2, output_node=76, voltage=0.012566732242703438\n    time_span=0.0001s, test_ID=174, label=2, output_node=77, voltage=0.011651393957436085\n    time_span=0.0001s, test_ID=174, label=2, output_node=78, voltage=0.011197212152183056\n    time_span=0.0001s, test_ID=174, label=2, output_node=79, voltage=0.00886155292391777\n    time_span=0.0001s, test_ID=174, label=2, output_node=80, voltage=0.009311753325164318\n    time_span=0.0001s, test_ID=174, label=2, output_node=81, voltage=0.011199203319847584\n    time_span=0.0001s, test_ID=174, label=2, output_node=82, voltage=0.01610458269715309\n    time_span=0.0001s, test_ID=174, label=2, output_node=83, voltage=0.008528884500265121\n    time_span=0.0001s, test_ID=174, label=2, output_node=84, voltage=0.013252987526357174\n    time_span=0.0001s, test_ID=174, label=2, output_node=85, voltage=0.013233068399131298\n    time_span=0.0001s, test_ID=174, label=2, output_node=86, voltage=0.008729083463549614\n    time_span=0.0001s, test_ID=174, label=2, output_node=87, voltage=0.0069581675343215466\n    time_span=0.0001s, test_ID=174, label=2, output_node=88, voltage=0.009377489797770977\n    time_span=0.0001s, test_ID=174, label=2, output_node=89, voltage=0.013659361749887466\n    time_span=0.0001s, test_ID=174, label=2, output_node=90, voltage=0.012562748976051807\n    time_span=0.0001s, test_ID=174, label=2, output_node=91, voltage=0.016587648540735245\n    time_span=0.0001s, test_ID=174, label=2, output_node=92, voltage=0.013069720938801765\n    time_span=0.0001s, test_ID=174, label=2, output_node=93, voltage=0.010443227365612984\n    time_span=0.0001s, test_ID=174, label=2, output_node=94, voltage=0.008381473831832409\n    time_span=0.0001s, test_ID=174, label=2, output_node=95, voltage=0.01350298710167408\n    time_span=0.0001s, test_ID=174, label=2, output_node=96, voltage=0.01182470191270113\n    time_span=0.0001s, test_ID=174, label=2, output_node=97, voltage=0.010452190414071083\n    time_span=0.0001s, test_ID=174, label=2, output_node=98, voltage=0.017646413296461105\n    time_span=0.0001s, test_ID=174, label=2, output_node=99, voltage=0.007490039803087711\n    time_span=0.0001s, test_ID=174, label=2, output_node=sum, voltage=0.03800199180841446\n    Time consumed for 1 sample = 625.9293675422668 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '174'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=175, label=7, output_node=bkg, voltage=-0.006293824873864651\n    time_span=0.0001s, test_ID=175, label=7, output_node=0, voltage=0.019269920885562897\n    time_span=0.0001s, test_ID=175, label=7, output_node=1, voltage=0.01579183340072632\n    time_span=0.0001s, test_ID=175, label=7, output_node=2, voltage=0.019240040332078934\n    time_span=0.0001s, test_ID=175, label=7, output_node=3, voltage=0.01644521951675415\n    time_span=0.0001s, test_ID=175, label=7, output_node=4, voltage=0.021767927333712578\n    time_span=0.0001s, test_ID=175, label=7, output_node=5, voltage=0.01804482191801071\n    time_span=0.0001s, test_ID=175, label=7, output_node=6, voltage=0.019369520246982574\n    time_span=0.0001s, test_ID=175, label=7, output_node=7, voltage=0.02262350544333458\n    time_span=0.0001s, test_ID=175, label=7, output_node=8, voltage=0.02085059881210327\n    time_span=0.0001s, test_ID=175, label=7, output_node=9, voltage=0.014828684739768505\n    time_span=0.0001s, test_ID=175, label=7, output_node=10, voltage=0.01614541746675968\n    time_span=0.0001s, test_ID=175, label=7, output_node=11, voltage=0.02329183556139469\n    time_span=0.0001s, test_ID=175, label=7, output_node=12, voltage=0.02117629535496235\n    time_span=0.0001s, test_ID=175, label=7, output_node=13, voltage=0.021140439435839653\n    time_span=0.0001s, test_ID=175, label=7, output_node=14, voltage=0.016711154952645302\n    time_span=0.0001s, test_ID=175, label=7, output_node=15, voltage=0.02050597593188286\n    time_span=0.0001s, test_ID=175, label=7, output_node=16, voltage=0.013404382392764091\n    time_span=0.0001s, test_ID=175, label=7, output_node=17, voltage=0.01603286899626255\n    time_span=0.0001s, test_ID=175, label=7, output_node=18, voltage=0.019506970420479774\n    time_span=0.0001s, test_ID=175, label=7, output_node=19, voltage=0.016465140506625175\n    time_span=0.0001s, test_ID=175, label=7, output_node=20, voltage=0.021778883412480354\n    time_span=0.0001s, test_ID=175, label=7, output_node=21, voltage=0.01347808726131916\n    time_span=0.0001s, test_ID=175, label=7, output_node=22, voltage=0.014460159465670586\n    time_span=0.0001s, test_ID=175, label=7, output_node=23, voltage=0.022362548857927322\n    time_span=0.0001s, test_ID=175, label=7, output_node=24, voltage=0.017548805102705956\n    time_span=0.0001s, test_ID=175, label=7, output_node=25, voltage=0.016748009249567986\n    time_span=0.0001s, test_ID=175, label=7, output_node=26, voltage=0.019297808408737183\n    time_span=0.0001s, test_ID=175, label=7, output_node=27, voltage=0.015818724408745766\n    time_span=0.0001s, test_ID=175, label=7, output_node=28, voltage=0.01860458217561245\n    time_span=0.0001s, test_ID=175, label=7, output_node=29, voltage=0.015803785994648933\n    time_span=0.0001s, test_ID=175, label=7, output_node=30, voltage=0.018617529422044754\n    time_span=0.0001s, test_ID=175, label=7, output_node=31, voltage=0.016620518639683723\n    time_span=0.0001s, test_ID=175, label=7, output_node=32, voltage=0.016010956838726997\n    time_span=0.0001s, test_ID=175, label=7, output_node=33, voltage=0.021706175059080124\n    time_span=0.0001s, test_ID=175, label=7, output_node=34, voltage=0.0145498001947999\n    time_span=0.0001s, test_ID=175, label=7, output_node=35, voltage=0.013163345865905285\n    time_span=0.0001s, test_ID=175, label=7, output_node=36, voltage=0.01625796966254711\n    time_span=0.0001s, test_ID=175, label=7, output_node=37, voltage=0.01998705230653286\n    time_span=0.0001s, test_ID=175, label=7, output_node=38, voltage=0.012948207557201385\n    time_span=0.0001s, test_ID=175, label=7, output_node=39, voltage=0.01471513882279396\n    time_span=0.0001s, test_ID=175, label=7, output_node=40, voltage=0.017438245937228203\n    time_span=0.0001s, test_ID=175, label=7, output_node=41, voltage=0.019360557198524475\n    time_span=0.0001s, test_ID=175, label=7, output_node=42, voltage=0.019716134294867516\n    time_span=0.0001s, test_ID=175, label=7, output_node=43, voltage=0.0187998004257679\n    time_span=0.0001s, test_ID=175, label=7, output_node=44, voltage=0.020329680293798447\n    time_span=0.0001s, test_ID=175, label=7, output_node=45, voltage=0.02598804607987404\n    time_span=0.0001s, test_ID=175, label=7, output_node=46, voltage=0.01547609455883503\n    time_span=0.0001s, test_ID=175, label=7, output_node=47, voltage=0.013342629186809063\n    time_span=0.0001s, test_ID=175, label=7, output_node=48, voltage=0.0146095622330904\n    time_span=0.0001s, test_ID=175, label=7, output_node=49, voltage=0.016803782433271408\n    time_span=0.0001s, test_ID=175, label=7, output_node=50, voltage=0.02238844707608223\n    time_span=0.0001s, test_ID=175, label=7, output_node=51, voltage=0.014587649144232273\n    time_span=0.0001s, test_ID=175, label=7, output_node=52, voltage=0.026137448847293854\n    time_span=0.0001s, test_ID=175, label=7, output_node=53, voltage=0.018508965149521828\n    time_span=0.0001s, test_ID=175, label=7, output_node=54, voltage=0.017436254769563675\n    time_span=0.0001s, test_ID=175, label=7, output_node=55, voltage=0.017065737396478653\n    time_span=0.0001s, test_ID=175, label=7, output_node=56, voltage=0.013308764435350895\n    time_span=0.0001s, test_ID=175, label=7, output_node=57, voltage=0.015729082748293877\n    time_span=0.0001s, test_ID=175, label=7, output_node=58, voltage=0.021469123661518097\n    time_span=0.0001s, test_ID=175, label=7, output_node=59, voltage=0.019125496968626976\n    time_span=0.0001s, test_ID=175, label=7, output_node=60, voltage=0.015593625605106354\n    time_span=0.0001s, test_ID=175, label=7, output_node=61, voltage=0.016070717945694923\n    time_span=0.0001s, test_ID=175, label=7, output_node=62, voltage=0.01857270859181881\n    time_span=0.0001s, test_ID=175, label=7, output_node=63, voltage=0.020313745364546776\n    time_span=0.0001s, test_ID=175, label=7, output_node=64, voltage=0.018966134637594223\n    time_span=0.0001s, test_ID=175, label=7, output_node=65, voltage=0.02255079708993435\n    time_span=0.0001s, test_ID=175, label=7, output_node=66, voltage=0.015012947842478752\n    time_span=0.0001s, test_ID=175, label=7, output_node=67, voltage=0.020371513441205025\n    time_span=0.0001s, test_ID=175, label=7, output_node=68, voltage=0.01356274913996458\n    time_span=0.0001s, test_ID=175, label=7, output_node=69, voltage=0.020074699074029922\n    time_span=0.0001s, test_ID=175, label=7, output_node=70, voltage=0.020539842545986176\n    time_span=0.0001s, test_ID=175, label=7, output_node=71, voltage=0.016748007386922836\n    time_span=0.0001s, test_ID=175, label=7, output_node=72, voltage=0.018099602311849594\n    time_span=0.0001s, test_ID=175, label=7, output_node=73, voltage=0.017579682171344757\n    time_span=0.0001s, test_ID=175, label=7, output_node=74, voltage=0.0269492045044899\n    time_span=0.0001s, test_ID=175, label=7, output_node=75, voltage=0.015521912835538387\n    time_span=0.0001s, test_ID=175, label=7, output_node=76, voltage=0.015885457396507263\n    time_span=0.0001s, test_ID=175, label=7, output_node=77, voltage=0.015939243137836456\n    time_span=0.0001s, test_ID=175, label=7, output_node=78, voltage=0.022222112864255905\n    time_span=0.0001s, test_ID=175, label=7, output_node=79, voltage=0.019601594656705856\n    time_span=0.0001s, test_ID=175, label=7, output_node=80, voltage=0.012497011572122574\n    time_span=0.0001s, test_ID=175, label=7, output_node=81, voltage=0.024924304336309433\n    time_span=0.0001s, test_ID=175, label=7, output_node=82, voltage=0.017015935853123665\n    time_span=0.0001s, test_ID=175, label=7, output_node=83, voltage=0.01802988164126873\n    time_span=0.0001s, test_ID=175, label=7, output_node=84, voltage=0.009712152183055878\n    time_span=0.0001s, test_ID=175, label=7, output_node=85, voltage=0.01726992055773735\n    time_span=0.0001s, test_ID=175, label=7, output_node=86, voltage=0.019261952489614487\n    time_span=0.0001s, test_ID=175, label=7, output_node=87, voltage=0.012669322080910206\n    time_span=0.0001s, test_ID=175, label=7, output_node=88, voltage=0.016095617786049843\n    time_span=0.0001s, test_ID=175, label=7, output_node=89, voltage=0.016399402171373367\n    time_span=0.0001s, test_ID=175, label=7, output_node=90, voltage=0.02571812830865383\n    time_span=0.0001s, test_ID=175, label=7, output_node=91, voltage=0.016852591186761856\n    time_span=0.0001s, test_ID=175, label=7, output_node=92, voltage=0.018129481002688408\n    time_span=0.0001s, test_ID=175, label=7, output_node=93, voltage=0.02320418506860733\n    time_span=0.0001s, test_ID=175, label=7, output_node=94, voltage=0.012426295317709446\n    time_span=0.0001s, test_ID=175, label=7, output_node=95, voltage=0.01748804561793804\n    time_span=0.0001s, test_ID=175, label=7, output_node=96, voltage=0.018211156129837036\n    time_span=0.0001s, test_ID=175, label=7, output_node=97, voltage=0.01808764971792698\n    time_span=0.0001s, test_ID=175, label=7, output_node=98, voltage=0.02357769012451172\n    time_span=0.0001s, test_ID=175, label=7, output_node=99, voltage=0.01531274989247322\n    time_span=0.0001s, test_ID=175, label=7, output_node=sum, voltage=0.050093624740839005\n    Time consumed for 1 sample = 628.5884926319122 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '175'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=176, label=1, output_node=bkg, voltage=-0.0026563743595033884\n    time_span=0.0001s, test_ID=176, label=1, output_node=0, voltage=0.0045717135071754456\n    time_span=0.0001s, test_ID=176, label=1, output_node=1, voltage=0.004067729227244854\n    time_span=0.0001s, test_ID=176, label=1, output_node=2, voltage=0.006113545969128609\n    time_span=0.0001s, test_ID=176, label=1, output_node=3, voltage=0.0011165337637066841\n    time_span=0.0001s, test_ID=176, label=1, output_node=4, voltage=0.00512848561629653\n    time_span=0.0001s, test_ID=176, label=1, output_node=5, voltage=0.0017998007824644446\n    time_span=0.0001s, test_ID=176, label=1, output_node=6, voltage=0.00240239012055099\n    time_span=0.0001s, test_ID=176, label=1, output_node=7, voltage=0.0039322711527347565\n    time_span=0.0001s, test_ID=176, label=1, output_node=8, voltage=0.004878486506640911\n    time_span=0.0001s, test_ID=176, label=1, output_node=9, voltage=0.003736055688932538\n    time_span=0.0001s, test_ID=176, label=1, output_node=10, voltage=0.004241035785526037\n    time_span=0.0001s, test_ID=176, label=1, output_node=11, voltage=0.0017659362638369203\n    time_span=0.0001s, test_ID=176, label=1, output_node=12, voltage=0.011338646523654461\n    time_span=0.0001s, test_ID=176, label=1, output_node=13, voltage=0.0024930278304964304\n    time_span=0.0001s, test_ID=176, label=1, output_node=14, voltage=0.00596912344917655\n    time_span=0.0001s, test_ID=176, label=1, output_node=15, voltage=0.00603187270462513\n    time_span=0.0001s, test_ID=176, label=1, output_node=16, voltage=0.007460159715265036\n    time_span=0.0001s, test_ID=176, label=1, output_node=17, voltage=0.005703187081962824\n    time_span=0.0001s, test_ID=176, label=1, output_node=18, voltage=0.002894422272220254\n    time_span=0.0001s, test_ID=176, label=1, output_node=19, voltage=0.004183266777545214\n    time_span=0.0001s, test_ID=176, label=1, output_node=20, voltage=0.007678287103772163\n    time_span=0.0001s, test_ID=176, label=1, output_node=21, voltage=0.0036394421476870775\n    time_span=0.0001s, test_ID=176, label=1, output_node=22, voltage=0.0001822708873078227\n    time_span=0.0001s, test_ID=176, label=1, output_node=23, voltage=0.005568725056946278\n    time_span=0.0001s, test_ID=176, label=1, output_node=24, voltage=0.0040099602192640305\n    time_span=0.0001s, test_ID=176, label=1, output_node=25, voltage=0.002604581881314516\n    time_span=0.0001s, test_ID=176, label=1, output_node=26, voltage=0.003669322468340397\n    time_span=0.0001s, test_ID=176, label=1, output_node=27, voltage=0.006603585556149483\n    time_span=0.0001s, test_ID=176, label=1, output_node=28, voltage=0.0035846612881869078\n    time_span=0.0001s, test_ID=176, label=1, output_node=29, voltage=0.006897409446537495\n    time_span=0.0001s, test_ID=176, label=1, output_node=30, voltage=0.0030557767022401094\n    time_span=0.0001s, test_ID=176, label=1, output_node=31, voltage=0.0037998007610440254\n    time_span=0.0001s, test_ID=176, label=1, output_node=32, voltage=0.004944223444908857\n    time_span=0.0001s, test_ID=176, label=1, output_node=33, voltage=0.007348604965955019\n    time_span=0.0001s, test_ID=176, label=1, output_node=34, voltage=0.01098804734647274\n    time_span=0.0001s, test_ID=176, label=1, output_node=35, voltage=0.0032898406498134136\n    time_span=0.0001s, test_ID=176, label=1, output_node=36, voltage=0.004139442462474108\n    time_span=0.0001s, test_ID=176, label=1, output_node=37, voltage=0.004481075797230005\n    time_span=0.0001s, test_ID=176, label=1, output_node=38, voltage=0.003452191362157464\n    time_span=0.0001s, test_ID=176, label=1, output_node=39, voltage=0.0023954182397574186\n    time_span=0.0001s, test_ID=176, label=1, output_node=40, voltage=0.0022798804566264153\n    time_span=0.0001s, test_ID=176, label=1, output_node=41, voltage=0.005524900276213884\n    time_span=0.0001s, test_ID=176, label=1, output_node=42, voltage=0.001157370745204389\n    time_span=0.0001s, test_ID=176, label=1, output_node=43, voltage=0.0017958167009055614\n    time_span=0.0001s, test_ID=176, label=1, output_node=44, voltage=0.007702190894633532\n    time_span=0.0001s, test_ID=176, label=1, output_node=45, voltage=0.0019183268304914236\n    time_span=0.0001s, test_ID=176, label=1, output_node=46, voltage=0.00295418337918818\n    time_span=0.0001s, test_ID=176, label=1, output_node=47, voltage=0.002217131434008479\n    time_span=0.0001s, test_ID=176, label=1, output_node=48, voltage=-0.0017330677947029471\n    time_span=0.0001s, test_ID=176, label=1, output_node=49, voltage=0.0063187251798808575\n    time_span=0.0001s, test_ID=176, label=1, output_node=50, voltage=0.0046752989292144775\n    time_span=0.0001s, test_ID=176, label=1, output_node=51, voltage=-0.0002888445742428303\n    time_span=0.0001s, test_ID=176, label=1, output_node=52, voltage=0.00956075731664896\n    time_span=0.0001s, test_ID=176, label=1, output_node=53, voltage=0.004012948367744684\n    time_span=0.0001s, test_ID=176, label=1, output_node=54, voltage=0.0042460160329937935\n    time_span=0.0001s, test_ID=176, label=1, output_node=55, voltage=0.004273904487490654\n    time_span=0.0001s, test_ID=176, label=1, output_node=56, voltage=0.006839641369879246\n    time_span=0.0001s, test_ID=176, label=1, output_node=57, voltage=0.00585557846352458\n    time_span=0.0001s, test_ID=176, label=1, output_node=58, voltage=0.004971115849912167\n    time_span=0.0001s, test_ID=176, label=1, output_node=59, voltage=0.003023904748260975\n    time_span=0.0001s, test_ID=176, label=1, output_node=60, voltage=0.0009521913016214967\n    time_span=0.0001s, test_ID=176, label=1, output_node=61, voltage=0.004856573883444071\n    time_span=0.0001s, test_ID=176, label=1, output_node=62, voltage=0.004498007707297802\n    time_span=0.0001s, test_ID=176, label=1, output_node=63, voltage=0.009023904800415039\n    time_span=0.0001s, test_ID=176, label=1, output_node=64, voltage=0.006634462624788284\n    time_span=0.0001s, test_ID=176, label=1, output_node=65, voltage=0.006916334852576256\n    time_span=0.0001s, test_ID=176, label=1, output_node=66, voltage=0.0025448205415159464\n    time_span=0.0001s, test_ID=176, label=1, output_node=67, voltage=0.00452390406280756\n    time_span=0.0001s, test_ID=176, label=1, output_node=68, voltage=0.007067728787660599\n    time_span=0.0001s, test_ID=176, label=1, output_node=69, voltage=0.005636454559862614\n    time_span=0.0001s, test_ID=176, label=1, output_node=70, voltage=0.0032659361604601145\n    time_span=0.0001s, test_ID=176, label=1, output_node=71, voltage=0.006089641712605953\n    time_span=0.0001s, test_ID=176, label=1, output_node=72, voltage=0.003994024358689785\n    time_span=0.0001s, test_ID=176, label=1, output_node=73, voltage=0.0004641433770302683\n    time_span=0.0001s, test_ID=176, label=1, output_node=74, voltage=0.007660358678549528\n    time_span=0.0001s, test_ID=176, label=1, output_node=75, voltage=0.004734063986688852\n    time_span=0.0001s, test_ID=176, label=1, output_node=76, voltage=0.008903387002646923\n    time_span=0.0001s, test_ID=176, label=1, output_node=77, voltage=0.006341633852571249\n    time_span=0.0001s, test_ID=176, label=1, output_node=78, voltage=0.005424303002655506\n    time_span=0.0001s, test_ID=176, label=1, output_node=79, voltage=0.004555777180939913\n    time_span=0.0001s, test_ID=176, label=1, output_node=80, voltage=0.0031782868318259716\n    time_span=0.0001s, test_ID=176, label=1, output_node=81, voltage=0.0035029880236834288\n    time_span=0.0001s, test_ID=176, label=1, output_node=82, voltage=0.004168326500803232\n    time_span=0.0001s, test_ID=176, label=1, output_node=83, voltage=0.005637450609356165\n    time_span=0.0001s, test_ID=176, label=1, output_node=84, voltage=0.002113546011969447\n    time_span=0.0001s, test_ID=176, label=1, output_node=85, voltage=0.006738048046827316\n    time_span=0.0001s, test_ID=176, label=1, output_node=86, voltage=0.004239043686538935\n    time_span=0.0001s, test_ID=176, label=1, output_node=87, voltage=0.0006573706050403416\n    time_span=0.0001s, test_ID=176, label=1, output_node=88, voltage=0.0040737055242061615\n    time_span=0.0001s, test_ID=176, label=1, output_node=89, voltage=0.003072709310799837\n    time_span=0.0001s, test_ID=176, label=1, output_node=90, voltage=0.00740039860829711\n    time_span=0.0001s, test_ID=176, label=1, output_node=91, voltage=0.0038625497836619616\n    time_span=0.0001s, test_ID=176, label=1, output_node=92, voltage=0.008205180056393147\n    time_span=0.0001s, test_ID=176, label=1, output_node=93, voltage=0.002186254831030965\n    time_span=0.0001s, test_ID=176, label=1, output_node=94, voltage=0.005547808948904276\n    time_span=0.0001s, test_ID=176, label=1, output_node=95, voltage=0.01106075756251812\n    time_span=0.0001s, test_ID=176, label=1, output_node=96, voltage=0.001601593685336411\n    time_span=0.0001s, test_ID=176, label=1, output_node=97, voltage=0.006414342205971479\n    time_span=0.0001s, test_ID=176, label=1, output_node=98, voltage=0.0060647414065897465\n    time_span=0.0001s, test_ID=176, label=1, output_node=99, voltage=0.0042071714997291565\n    time_span=0.0001s, test_ID=176, label=1, output_node=sum, voltage=0.01804780773818493\n    Time consumed for 1 sample = 624.0635030269623 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '176'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=177, label=8, output_node=bkg, voltage=-0.00598306767642498\n    time_span=0.0001s, test_ID=177, label=8, output_node=0, voltage=0.011112549342215061\n    time_span=0.0001s, test_ID=177, label=8, output_node=1, voltage=0.007689242716878653\n    time_span=0.0001s, test_ID=177, label=8, output_node=2, voltage=0.00705478060990572\n    time_span=0.0001s, test_ID=177, label=8, output_node=3, voltage=-0.0005179282161407173\n    time_span=0.0001s, test_ID=177, label=8, output_node=4, voltage=0.0017808766569942236\n    time_span=0.0001s, test_ID=177, label=8, output_node=5, voltage=0.007596613373607397\n    time_span=0.0001s, test_ID=177, label=8, output_node=6, voltage=0.007759960368275642\n    time_span=0.0001s, test_ID=177, label=8, output_node=7, voltage=0.0033386454451829195\n    time_span=0.0001s, test_ID=177, label=8, output_node=8, voltage=0.007032868918031454\n    time_span=0.0001s, test_ID=177, label=8, output_node=9, voltage=0.006600597407668829\n    time_span=0.0001s, test_ID=177, label=8, output_node=10, voltage=0.005813744850456715\n    time_span=0.0001s, test_ID=177, label=8, output_node=11, voltage=0.0023107570596039295\n    time_span=0.0001s, test_ID=177, label=8, output_node=12, voltage=0.003992031794041395\n    time_span=0.0001s, test_ID=177, label=8, output_node=13, voltage=0.0066583664156496525\n    time_span=0.0001s, test_ID=177, label=8, output_node=14, voltage=0.004312749020755291\n    time_span=0.0001s, test_ID=177, label=8, output_node=15, voltage=0.009119521826505661\n    time_span=0.0001s, test_ID=177, label=8, output_node=16, voltage=0.006076693069189787\n    time_span=0.0001s, test_ID=177, label=8, output_node=17, voltage=0.007901394739747047\n    time_span=0.0001s, test_ID=177, label=8, output_node=18, voltage=0.0070667327381670475\n    time_span=0.0001s, test_ID=177, label=8, output_node=19, voltage=0.0032430279534310102\n    time_span=0.0001s, test_ID=177, label=8, output_node=20, voltage=0.0046762945130467415\n    time_span=0.0001s, test_ID=177, label=8, output_node=21, voltage=0.001057768939062953\n    time_span=0.0001s, test_ID=177, label=8, output_node=22, voltage=0.003920318558812141\n    time_span=0.0001s, test_ID=177, label=8, output_node=23, voltage=0.00446912320330739\n    time_span=0.0001s, test_ID=177, label=8, output_node=24, voltage=0.0023486055433750153\n    time_span=0.0001s, test_ID=177, label=8, output_node=25, voltage=0.008534860797226429\n    time_span=0.0001s, test_ID=177, label=8, output_node=26, voltage=0.0039033866487443447\n    time_span=0.0001s, test_ID=177, label=8, output_node=27, voltage=0.00239641428925097\n    time_span=0.0001s, test_ID=177, label=8, output_node=28, voltage=0.0025557768531143665\n    time_span=0.0001s, test_ID=177, label=8, output_node=29, voltage=0.00604382436722517\n    time_span=0.0001s, test_ID=177, label=8, output_node=30, voltage=0.00014840633957646787\n    time_span=0.0001s, test_ID=177, label=8, output_node=31, voltage=0.00474601611495018\n    time_span=0.0001s, test_ID=177, label=8, output_node=32, voltage=0.005365537945181131\n    time_span=0.0001s, test_ID=177, label=8, output_node=33, voltage=0.004505976103246212\n    time_span=0.0001s, test_ID=177, label=8, output_node=34, voltage=0.003323705168440938\n    time_span=0.0001s, test_ID=177, label=8, output_node=35, voltage=0.006998008117079735\n    time_span=0.0001s, test_ID=177, label=8, output_node=36, voltage=0.007939242757856846\n    time_span=0.0001s, test_ID=177, label=8, output_node=37, voltage=0.005020915996283293\n    time_span=0.0001s, test_ID=177, label=8, output_node=38, voltage=0.0011474103666841984\n    time_span=0.0001s, test_ID=177, label=8, output_node=39, voltage=0.004868526477366686\n    time_span=0.0001s, test_ID=177, label=8, output_node=40, voltage=0.004500995855778456\n    time_span=0.0001s, test_ID=177, label=8, output_node=41, voltage=0.004296812694519758\n    time_span=0.0001s, test_ID=177, label=8, output_node=42, voltage=0.004592629615217447\n    time_span=0.0001s, test_ID=177, label=8, output_node=43, voltage=0.0044731078669428825\n    time_span=0.0001s, test_ID=177, label=8, output_node=44, voltage=0.007601593621075153\n    time_span=0.0001s, test_ID=177, label=8, output_node=45, voltage=0.007432270795106888\n    time_span=0.0001s, test_ID=177, label=8, output_node=46, voltage=0.002434263238683343\n    time_span=0.0001s, test_ID=177, label=8, output_node=47, voltage=0.008670318871736526\n    time_span=0.0001s, test_ID=177, label=8, output_node=48, voltage=0.009031873196363449\n    time_span=0.0001s, test_ID=177, label=8, output_node=49, voltage=0.003254980081692338\n    time_span=0.0001s, test_ID=177, label=8, output_node=50, voltage=0.011889442801475525\n    time_span=0.0001s, test_ID=177, label=8, output_node=51, voltage=0.0051912348717451096\n    time_span=0.0001s, test_ID=177, label=8, output_node=52, voltage=0.007081673014909029\n    time_span=0.0001s, test_ID=177, label=8, output_node=53, voltage=0.009353585541248322\n    time_span=0.0001s, test_ID=177, label=8, output_node=54, voltage=0.004112549591809511\n    time_span=0.0001s, test_ID=177, label=8, output_node=55, voltage=0.004494023974984884\n    time_span=0.0001s, test_ID=177, label=8, output_node=56, voltage=0.004438247065991163\n    time_span=0.0001s, test_ID=177, label=8, output_node=57, voltage=0.005791832692921162\n    time_span=0.0001s, test_ID=177, label=8, output_node=58, voltage=0.010725099593400955\n    time_span=0.0001s, test_ID=177, label=8, output_node=59, voltage=0.0040059760212898254\n    time_span=0.0001s, test_ID=177, label=8, output_node=60, voltage=0.0021364542189985514\n    time_span=0.0001s, test_ID=177, label=8, output_node=61, voltage=0.004368525464087725\n    time_span=0.0001s, test_ID=177, label=8, output_node=62, voltage=0.0035288843791931868\n    time_span=0.0001s, test_ID=177, label=8, output_node=63, voltage=0.005614541936665773\n    time_span=0.0001s, test_ID=177, label=8, output_node=64, voltage=0.0028894422575831413\n    time_span=0.0001s, test_ID=177, label=8, output_node=65, voltage=0.010400397703051567\n    time_span=0.0001s, test_ID=177, label=8, output_node=66, voltage=0.0025408368092030287\n    time_span=0.0001s, test_ID=177, label=8, output_node=67, voltage=0.0033834660425782204\n    time_span=0.0001s, test_ID=177, label=8, output_node=68, voltage=0.008383465930819511\n    time_span=0.0001s, test_ID=177, label=8, output_node=69, voltage=0.005624502431601286\n    time_span=0.0001s, test_ID=177, label=8, output_node=70, voltage=0.006320716813206673\n    time_span=0.0001s, test_ID=177, label=8, output_node=71, voltage=0.009572708979249\n    time_span=0.0001s, test_ID=177, label=8, output_node=72, voltage=0.0069452193565666676\n    time_span=0.0001s, test_ID=177, label=8, output_node=73, voltage=0.010954182595014572\n    time_span=0.0001s, test_ID=177, label=8, output_node=74, voltage=0.005946215242147446\n    time_span=0.0001s, test_ID=177, label=8, output_node=75, voltage=0.0048296814784407616\n    time_span=0.0001s, test_ID=177, label=8, output_node=76, voltage=0.005744024179875851\n    time_span=0.0001s, test_ID=177, label=8, output_node=77, voltage=0.007032868452370167\n    time_span=0.0001s, test_ID=177, label=8, output_node=78, voltage=0.0029362549539655447\n    time_span=0.0001s, test_ID=177, label=8, output_node=79, voltage=0.005430278368294239\n    time_span=0.0001s, test_ID=177, label=8, output_node=80, voltage=0.004976096097379923\n    time_span=0.0001s, test_ID=177, label=8, output_node=81, voltage=0.006148406304419041\n    time_span=0.0001s, test_ID=177, label=8, output_node=82, voltage=0.007170319091528654\n    time_span=0.0001s, test_ID=177, label=8, output_node=83, voltage=0.0068037849850952625\n    time_span=0.0001s, test_ID=177, label=8, output_node=84, voltage=0.00624402379617095\n    time_span=0.0001s, test_ID=177, label=8, output_node=85, voltage=0.008197211660444736\n    time_span=0.0001s, test_ID=177, label=8, output_node=86, voltage=0.005468127317726612\n    time_span=0.0001s, test_ID=177, label=8, output_node=87, voltage=0.0036434263456612825\n    time_span=0.0001s, test_ID=177, label=8, output_node=88, voltage=0.007855577394366264\n    time_span=0.0001s, test_ID=177, label=8, output_node=89, voltage=0.005627490114420652\n    time_span=0.0001s, test_ID=177, label=8, output_node=90, voltage=0.005120517686009407\n    time_span=0.0001s, test_ID=177, label=8, output_node=91, voltage=0.005318725481629372\n    time_span=0.0001s, test_ID=177, label=8, output_node=92, voltage=0.006277889013290405\n    time_span=0.0001s, test_ID=177, label=8, output_node=93, voltage=0.0061942231841385365\n    time_span=0.0001s, test_ID=177, label=8, output_node=94, voltage=0.005064741242676973\n    time_span=0.0001s, test_ID=177, label=8, output_node=95, voltage=0.003576693357899785\n    time_span=0.0001s, test_ID=177, label=8, output_node=96, voltage=0.0056952196173369884\n    time_span=0.0001s, test_ID=177, label=8, output_node=97, voltage=0.004215139430016279\n    time_span=0.0001s, test_ID=177, label=8, output_node=98, voltage=0.00720816757529974\n    time_span=0.0001s, test_ID=177, label=8, output_node=99, voltage=0.0038754979614168406\n    time_span=0.0001s, test_ID=177, label=8, output_node=sum, voltage=0.01784362643957138\n    Time consumed for 1 sample = 624.2755033969879 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '177'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=178, label=1, output_node=bkg, voltage=-0.004025896079838276\n    time_span=0.0001s, test_ID=178, label=1, output_node=0, voltage=0.01281573623418808\n    time_span=0.0001s, test_ID=178, label=1, output_node=1, voltage=0.008461154997348785\n    time_span=0.0001s, test_ID=178, label=1, output_node=2, voltage=0.012302787974476814\n    time_span=0.0001s, test_ID=178, label=1, output_node=3, voltage=0.006489044055342674\n    time_span=0.0001s, test_ID=178, label=1, output_node=4, voltage=0.009961155243217945\n    time_span=0.0001s, test_ID=178, label=1, output_node=5, voltage=0.012699203565716743\n    time_span=0.0001s, test_ID=178, label=1, output_node=6, voltage=0.012198206968605518\n    time_span=0.0001s, test_ID=178, label=1, output_node=7, voltage=0.005522908642888069\n    time_span=0.0001s, test_ID=178, label=1, output_node=8, voltage=0.009229083545506\n    time_span=0.0001s, test_ID=178, label=1, output_node=9, voltage=0.008132469840347767\n    time_span=0.0001s, test_ID=178, label=1, output_node=10, voltage=0.008915338665246964\n    time_span=0.0001s, test_ID=178, label=1, output_node=11, voltage=0.014987052418291569\n    time_span=0.0001s, test_ID=178, label=1, output_node=12, voltage=0.017312748357653618\n    time_span=0.0001s, test_ID=178, label=1, output_node=13, voltage=0.012018924579024315\n    time_span=0.0001s, test_ID=178, label=1, output_node=14, voltage=0.011530876159667969\n    time_span=0.0001s, test_ID=178, label=1, output_node=15, voltage=0.007590637542307377\n    time_span=0.0001s, test_ID=178, label=1, output_node=16, voltage=0.008616534061729908\n    time_span=0.0001s, test_ID=178, label=1, output_node=17, voltage=0.010099601931869984\n    time_span=0.0001s, test_ID=178, label=1, output_node=18, voltage=0.01100398413836956\n    time_span=0.0001s, test_ID=178, label=1, output_node=19, voltage=0.00889840628951788\n    time_span=0.0001s, test_ID=178, label=1, output_node=20, voltage=0.013455180451273918\n    time_span=0.0001s, test_ID=178, label=1, output_node=21, voltage=0.0079521918669343\n    time_span=0.0001s, test_ID=178, label=1, output_node=22, voltage=0.0063097612001001835\n    time_span=0.0001s, test_ID=178, label=1, output_node=23, voltage=0.013847609050571918\n    time_span=0.0001s, test_ID=178, label=1, output_node=24, voltage=0.009583665058016777\n    time_span=0.0001s, test_ID=178, label=1, output_node=25, voltage=0.004566733259707689\n    time_span=0.0001s, test_ID=178, label=1, output_node=26, voltage=0.01244721096009016\n    time_span=0.0001s, test_ID=178, label=1, output_node=27, voltage=0.009323704987764359\n    time_span=0.0001s, test_ID=178, label=1, output_node=28, voltage=0.01404382474720478\n    time_span=0.0001s, test_ID=178, label=1, output_node=29, voltage=0.011262948624789715\n    time_span=0.0001s, test_ID=178, label=1, output_node=30, voltage=0.007089641410857439\n    time_span=0.0001s, test_ID=178, label=1, output_node=31, voltage=0.011979084461927414\n    time_span=0.0001s, test_ID=178, label=1, output_node=32, voltage=0.010234063491225243\n    time_span=0.0001s, test_ID=178, label=1, output_node=33, voltage=0.011575696989893913\n    time_span=0.0001s, test_ID=178, label=1, output_node=34, voltage=0.010523904114961624\n    time_span=0.0001s, test_ID=178, label=1, output_node=35, voltage=0.011305776424705982\n    time_span=0.0001s, test_ID=178, label=1, output_node=36, voltage=0.012806772254407406\n    time_span=0.0001s, test_ID=178, label=1, output_node=37, voltage=0.005506972316652536\n    time_span=0.0001s, test_ID=178, label=1, output_node=38, voltage=0.008273904211819172\n    time_span=0.0001s, test_ID=178, label=1, output_node=39, voltage=0.006363545544445515\n    time_span=0.0001s, test_ID=178, label=1, output_node=40, voltage=0.010961155407130718\n    time_span=0.0001s, test_ID=178, label=1, output_node=41, voltage=0.013513945043087006\n    time_span=0.0001s, test_ID=178, label=1, output_node=42, voltage=0.007975099608302116\n    time_span=0.0001s, test_ID=178, label=1, output_node=43, voltage=0.010023905895650387\n    time_span=0.0001s, test_ID=178, label=1, output_node=44, voltage=0.013735058717429638\n    time_span=0.0001s, test_ID=178, label=1, output_node=45, voltage=0.009267929010093212\n    time_span=0.0001s, test_ID=178, label=1, output_node=46, voltage=0.005335657857358456\n    time_span=0.0001s, test_ID=178, label=1, output_node=47, voltage=0.0037938246969133615\n    time_span=0.0001s, test_ID=178, label=1, output_node=48, voltage=0.009273904375731945\n    time_span=0.0001s, test_ID=178, label=1, output_node=49, voltage=0.015061752870678902\n    time_span=0.0001s, test_ID=178, label=1, output_node=50, voltage=0.013020915910601616\n    time_span=0.0001s, test_ID=178, label=1, output_node=51, voltage=0.008205179125070572\n    time_span=0.0001s, test_ID=178, label=1, output_node=52, voltage=0.009808764792978764\n    time_span=0.0001s, test_ID=178, label=1, output_node=53, voltage=0.007658366113901138\n    time_span=0.0001s, test_ID=178, label=1, output_node=54, voltage=0.013288845308125019\n    time_span=0.0001s, test_ID=178, label=1, output_node=55, voltage=0.010088644921779633\n    time_span=0.0001s, test_ID=178, label=1, output_node=56, voltage=0.008381473831832409\n    time_span=0.0001s, test_ID=178, label=1, output_node=57, voltage=0.009093625470995903\n    time_span=0.0001s, test_ID=178, label=1, output_node=58, voltage=0.009274900890886784\n    time_span=0.0001s, test_ID=178, label=1, output_node=59, voltage=0.016126494854688644\n    time_span=0.0001s, test_ID=178, label=1, output_node=60, voltage=0.0098476093262434\n    time_span=0.0001s, test_ID=178, label=1, output_node=61, voltage=0.00958964042365551\n    time_span=0.0001s, test_ID=178, label=1, output_node=62, voltage=0.013331673108041286\n    time_span=0.0001s, test_ID=178, label=1, output_node=63, voltage=0.009321711957454681\n    time_span=0.0001s, test_ID=178, label=1, output_node=64, voltage=0.008558765053749084\n    time_span=0.0001s, test_ID=178, label=1, output_node=65, voltage=0.008383465930819511\n    time_span=0.0001s, test_ID=178, label=1, output_node=66, voltage=0.012495020404458046\n    time_span=0.0001s, test_ID=178, label=1, output_node=67, voltage=0.008400398306548595\n    time_span=0.0001s, test_ID=178, label=1, output_node=68, voltage=0.008049801923334599\n    time_span=0.0001s, test_ID=178, label=1, output_node=69, voltage=0.015215139836072922\n    time_span=0.0001s, test_ID=178, label=1, output_node=70, voltage=0.004887450020760298\n    time_span=0.0001s, test_ID=178, label=1, output_node=71, voltage=0.007396413944661617\n    time_span=0.0001s, test_ID=178, label=1, output_node=72, voltage=0.014220119453966618\n    time_span=0.0001s, test_ID=178, label=1, output_node=73, voltage=0.010728087276220322\n    time_span=0.0001s, test_ID=178, label=1, output_node=74, voltage=0.014748007990419865\n    time_span=0.0001s, test_ID=178, label=1, output_node=75, voltage=0.013511952012777328\n    time_span=0.0001s, test_ID=178, label=1, output_node=76, voltage=0.013080677017569542\n    time_span=0.0001s, test_ID=178, label=1, output_node=77, voltage=0.01174004003405571\n    time_span=0.0001s, test_ID=178, label=1, output_node=78, voltage=0.015203187242150307\n    time_span=0.0001s, test_ID=178, label=1, output_node=79, voltage=0.004896414000540972\n    time_span=0.0001s, test_ID=178, label=1, output_node=80, voltage=0.007649401668459177\n    time_span=0.0001s, test_ID=178, label=1, output_node=81, voltage=0.011682271026074886\n    time_span=0.0001s, test_ID=178, label=1, output_node=82, voltage=0.007464143447577953\n    time_span=0.0001s, test_ID=178, label=1, output_node=83, voltage=0.011247011832892895\n    time_span=0.0001s, test_ID=178, label=1, output_node=84, voltage=0.00492430292069912\n    time_span=0.0001s, test_ID=178, label=1, output_node=85, voltage=0.012120518833398819\n    time_span=0.0001s, test_ID=178, label=1, output_node=86, voltage=0.014089641161262989\n    time_span=0.0001s, test_ID=178, label=1, output_node=87, voltage=0.003508963854983449\n    time_span=0.0001s, test_ID=178, label=1, output_node=88, voltage=0.005600597709417343\n    time_span=0.0001s, test_ID=178, label=1, output_node=89, voltage=0.0014173306990414858\n    time_span=0.0001s, test_ID=178, label=1, output_node=90, voltage=0.013951195403933525\n    time_span=0.0001s, test_ID=178, label=1, output_node=91, voltage=0.011175298132002354\n    time_span=0.0001s, test_ID=178, label=1, output_node=92, voltage=0.014153387397527695\n    time_span=0.0001s, test_ID=178, label=1, output_node=93, voltage=0.007494024001061916\n    time_span=0.0001s, test_ID=178, label=1, output_node=94, voltage=0.0074800788424909115\n    time_span=0.0001s, test_ID=178, label=1, output_node=95, voltage=0.01303386501967907\n    time_span=0.0001s, test_ID=178, label=1, output_node=96, voltage=0.00820219051092863\n    time_span=0.0001s, test_ID=178, label=1, output_node=97, voltage=0.00817430391907692\n    time_span=0.0001s, test_ID=178, label=1, output_node=98, voltage=0.012349601835012436\n    time_span=0.0001s, test_ID=178, label=1, output_node=99, voltage=0.006140438374131918\n    time_span=0.0001s, test_ID=178, label=1, output_node=sum, voltage=0.028287848457694054\n    Time consumed for 1 sample = 625.7654640674591 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '178'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=179, label=8, output_node=bkg, voltage=-0.005910358391702175\n    time_span=0.0001s, test_ID=179, label=8, output_node=0, voltage=0.0014442228712141514\n    time_span=0.0001s, test_ID=179, label=8, output_node=1, voltage=0.003065737197175622\n    time_span=0.0001s, test_ID=179, label=8, output_node=2, voltage=0.0017848605057224631\n    time_span=0.0001s, test_ID=179, label=8, output_node=3, voltage=-0.00036653393181040883\n    time_span=0.0001s, test_ID=179, label=8, output_node=4, voltage=9.860567661235109e-05\n    time_span=0.0001s, test_ID=179, label=8, output_node=5, voltage=0.0065936255268752575\n    time_span=0.0001s, test_ID=179, label=8, output_node=6, voltage=0.002470119623467326\n    time_span=0.0001s, test_ID=179, label=8, output_node=7, voltage=-0.0030507969204336405\n    time_span=0.0001s, test_ID=179, label=8, output_node=8, voltage=0.0033017927780747414\n    time_span=0.0001s, test_ID=179, label=8, output_node=9, voltage=0.0012758963275700808\n    time_span=0.0001s, test_ID=179, label=8, output_node=10, voltage=0.002491035731509328\n    time_span=0.0001s, test_ID=179, label=8, output_node=11, voltage=0.0027569723315536976\n    time_span=0.0001s, test_ID=179, label=8, output_node=12, voltage=0.005858565680682659\n    time_span=0.0001s, test_ID=179, label=8, output_node=13, voltage=0.0035149401519447565\n    time_span=0.0001s, test_ID=179, label=8, output_node=14, voltage=0.0037350598722696304\n    time_span=0.0001s, test_ID=179, label=8, output_node=15, voltage=0.0011802788358181715\n    time_span=0.0001s, test_ID=179, label=8, output_node=16, voltage=0.005712151061743498\n    time_span=0.0001s, test_ID=179, label=8, output_node=17, voltage=0.001873506000265479\n    time_span=0.0001s, test_ID=179, label=8, output_node=18, voltage=0.0033675299491733313\n    time_span=0.0001s, test_ID=179, label=8, output_node=19, voltage=-0.0003067727666348219\n    time_span=0.0001s, test_ID=179, label=8, output_node=20, voltage=0.0026165337767452\n    time_span=0.0001s, test_ID=179, label=8, output_node=21, voltage=-0.0001394421560689807\n    time_span=0.0001s, test_ID=179, label=8, output_node=22, voltage=-0.0002749004343058914\n    time_span=0.0001s, test_ID=179, label=8, output_node=23, voltage=0.006215139292180538\n    time_span=0.0001s, test_ID=179, label=8, output_node=24, voltage=0.0031105580274015665\n    time_span=0.0001s, test_ID=179, label=8, output_node=25, voltage=0.0009402390569448471\n    time_span=0.0001s, test_ID=179, label=8, output_node=26, voltage=0.0017788844415917993\n    time_span=0.0001s, test_ID=179, label=8, output_node=27, voltage=0.00030478090047836304\n    time_span=0.0001s, test_ID=179, label=8, output_node=28, voltage=0.0013256974052637815\n    time_span=0.0001s, test_ID=179, label=8, output_node=29, voltage=0.0026603585574775934\n    time_span=0.0001s, test_ID=179, label=8, output_node=30, voltage=-0.0004641433770302683\n    time_span=0.0001s, test_ID=179, label=8, output_node=31, voltage=0.007858566008508205\n    time_span=0.0001s, test_ID=179, label=8, output_node=32, voltage=0.002537848660722375\n    time_span=0.0001s, test_ID=179, label=8, output_node=33, voltage=0.0009621513891033828\n    time_span=0.0001s, test_ID=179, label=8, output_node=34, voltage=0.0007768924697302282\n    time_span=0.0001s, test_ID=179, label=8, output_node=35, voltage=0.00011553784861462191\n    time_span=0.0001s, test_ID=179, label=8, output_node=36, voltage=0.00023804788361303508\n    time_span=0.0001s, test_ID=179, label=8, output_node=37, voltage=0.00041633466025814414\n    time_span=0.0001s, test_ID=179, label=8, output_node=38, voltage=8.665341010782868e-05\n    time_span=0.0001s, test_ID=179, label=8, output_node=39, voltage=0.0029223107267171144\n    time_span=0.0001s, test_ID=179, label=8, output_node=40, voltage=0.0016354583203792572\n    time_span=0.0001s, test_ID=179, label=8, output_node=41, voltage=0.006620517931878567\n    time_span=0.0001s, test_ID=179, label=8, output_node=42, voltage=0.0005936254747211933\n    time_span=0.0001s, test_ID=179, label=8, output_node=43, voltage=0.0019332668744027615\n    time_span=0.0001s, test_ID=179, label=8, output_node=44, voltage=0.00612051784992218\n    time_span=0.0001s, test_ID=179, label=8, output_node=45, voltage=0.00761454226449132\n    time_span=0.0001s, test_ID=179, label=8, output_node=46, voltage=-0.0009870518697425723\n    time_span=0.0001s, test_ID=179, label=8, output_node=47, voltage=0.003536852775141597\n    time_span=0.0001s, test_ID=179, label=8, output_node=48, voltage=0.003563745180144906\n    time_span=0.0001s, test_ID=179, label=8, output_node=49, voltage=0.0030507969204336405\n    time_span=0.0001s, test_ID=179, label=8, output_node=50, voltage=0.0047519919462502\n    time_span=0.0001s, test_ID=179, label=8, output_node=51, voltage=-0.00011553778313100338\n    time_span=0.0001s, test_ID=179, label=8, output_node=52, voltage=0.0010527888080105186\n    time_span=0.0001s, test_ID=179, label=8, output_node=53, voltage=0.005058765411376953\n    time_span=0.0001s, test_ID=179, label=8, output_node=54, voltage=0.0017559760017320514\n    time_span=0.0001s, test_ID=179, label=8, output_node=55, voltage=0.003467131406068802\n    time_span=0.0001s, test_ID=179, label=8, output_node=56, voltage=0.0019063743529841304\n    time_span=0.0001s, test_ID=179, label=8, output_node=57, voltage=0.0014750997070223093\n    time_span=0.0001s, test_ID=179, label=8, output_node=58, voltage=0.007330677006393671\n    time_span=0.0001s, test_ID=179, label=8, output_node=59, voltage=0.00047111554886214435\n    time_span=0.0001s, test_ID=179, label=8, output_node=60, voltage=-0.0016185259446501732\n    time_span=0.0001s, test_ID=179, label=8, output_node=61, voltage=0.001988047966733575\n    time_span=0.0001s, test_ID=179, label=8, output_node=62, voltage=0.0049721114337444305\n    time_span=0.0001s, test_ID=179, label=8, output_node=63, voltage=0.0029980079270899296\n    time_span=0.0001s, test_ID=179, label=8, output_node=64, voltage=0.004066733177751303\n    time_span=0.0001s, test_ID=179, label=8, output_node=65, voltage=0.003154382575303316\n    time_span=0.0001s, test_ID=179, label=8, output_node=66, voltage=0.0008406374836340547\n    time_span=0.0001s, test_ID=179, label=8, output_node=67, voltage=0.005890437867492437\n    time_span=0.0001s, test_ID=179, label=8, output_node=68, voltage=0.0047061750665307045\n    time_span=0.0001s, test_ID=179, label=8, output_node=69, voltage=0.0019452192354947329\n    time_span=0.0001s, test_ID=179, label=8, output_node=70, voltage=0.003257967997342348\n    time_span=0.0001s, test_ID=179, label=8, output_node=71, voltage=0.0046454183757305145\n    time_span=0.0001s, test_ID=179, label=8, output_node=72, voltage=0.0017569720512256026\n    time_span=0.0001s, test_ID=179, label=8, output_node=73, voltage=0.0023416331969201565\n    time_span=0.0001s, test_ID=179, label=8, output_node=74, voltage=6.274902989389375e-05\n    time_span=0.0001s, test_ID=179, label=8, output_node=75, voltage=0.005262948106974363\n    time_span=0.0001s, test_ID=179, label=8, output_node=76, voltage=0.0033426296431571245\n    time_span=0.0001s, test_ID=179, label=8, output_node=77, voltage=0.007104581221938133\n    time_span=0.0001s, test_ID=179, label=8, output_node=78, voltage=-0.000503983988892287\n    time_span=0.0001s, test_ID=179, label=8, output_node=79, voltage=0.0013147410936653614\n    time_span=0.0001s, test_ID=179, label=8, output_node=80, voltage=-0.00025398400612175465\n    time_span=0.0001s, test_ID=179, label=8, output_node=81, voltage=0.0065816729329526424\n    time_span=0.0001s, test_ID=179, label=8, output_node=82, voltage=0.005739043932408094\n    time_span=0.0001s, test_ID=179, label=8, output_node=83, voltage=0.0022988049313426018\n    time_span=0.0001s, test_ID=179, label=8, output_node=84, voltage=0.00032669329084455967\n    time_span=0.0001s, test_ID=179, label=8, output_node=85, voltage=0.0045418329536914825\n    time_span=0.0001s, test_ID=179, label=8, output_node=86, voltage=0.0014960159314796329\n    time_span=0.0001s, test_ID=179, label=8, output_node=87, voltage=-0.002781872171908617\n    time_span=0.0001s, test_ID=179, label=8, output_node=88, voltage=0.00510358577594161\n    time_span=0.0001s, test_ID=179, label=8, output_node=89, voltage=0.0013914343435317278\n    time_span=0.0001s, test_ID=179, label=8, output_node=90, voltage=0.0012031871592625976\n    time_span=0.0001s, test_ID=179, label=8, output_node=91, voltage=0.0025169323198497295\n    time_span=0.0001s, test_ID=179, label=8, output_node=92, voltage=0.0014601594302803278\n    time_span=0.0001s, test_ID=179, label=8, output_node=93, voltage=-0.001522908452898264\n    time_span=0.0001s, test_ID=179, label=8, output_node=94, voltage=0.00032669329084455967\n    time_span=0.0001s, test_ID=179, label=8, output_node=95, voltage=0.001531872432678938\n    time_span=0.0001s, test_ID=179, label=8, output_node=96, voltage=-0.000956175266765058\n    time_span=0.0001s, test_ID=179, label=8, output_node=97, voltage=0.00030378493829630315\n    time_span=0.0001s, test_ID=179, label=8, output_node=98, voltage=0.0040189241990447044\n    time_span=0.0001s, test_ID=179, label=8, output_node=99, voltage=0.0007669324986636639\n    time_span=0.0001s, test_ID=179, label=8, output_node=sum, voltage=0.008410358801484108\n    Time consumed for 1 sample = 624.4022438526154 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '179'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=180, label=1, output_node=bkg, voltage=-0.005330677609890699\n    time_span=0.0001s, test_ID=180, label=1, output_node=0, voltage=0.0023665339685976505\n    time_span=0.0001s, test_ID=180, label=1, output_node=1, voltage=0.0031593625899404287\n    time_span=0.0001s, test_ID=180, label=1, output_node=2, voltage=0.004900398664176464\n    time_span=0.0001s, test_ID=180, label=1, output_node=3, voltage=0.0005039840470999479\n    time_span=0.0001s, test_ID=180, label=1, output_node=4, voltage=0.004766932688653469\n    time_span=0.0001s, test_ID=180, label=1, output_node=5, voltage=0.0025458165910094976\n    time_span=0.0001s, test_ID=180, label=1, output_node=6, voltage=0.003327689366415143\n    time_span=0.0001s, test_ID=180, label=1, output_node=7, voltage=0.004801793023943901\n    time_span=0.0001s, test_ID=180, label=1, output_node=8, voltage=0.0007709164638072252\n    time_span=0.0001s, test_ID=180, label=1, output_node=9, voltage=0.001109561650082469\n    time_span=0.0001s, test_ID=180, label=1, output_node=10, voltage=0.0026693225372582674\n    time_span=0.0001s, test_ID=180, label=1, output_node=11, voltage=0.002960159443318844\n    time_span=0.0001s, test_ID=180, label=1, output_node=12, voltage=0.008985059335827827\n    time_span=0.0001s, test_ID=180, label=1, output_node=13, voltage=0.0047310758382081985\n    time_span=0.0001s, test_ID=180, label=1, output_node=14, voltage=0.004841633606702089\n    time_span=0.0001s, test_ID=180, label=1, output_node=15, voltage=0.0037211156450212\n    time_span=0.0001s, test_ID=180, label=1, output_node=16, voltage=0.003501992207020521\n    time_span=0.0001s, test_ID=180, label=1, output_node=17, voltage=0.00519920326769352\n    time_span=0.0001s, test_ID=180, label=1, output_node=18, voltage=0.007723107933998108\n    time_span=0.0001s, test_ID=180, label=1, output_node=19, voltage=0.0007380478200502694\n    time_span=0.0001s, test_ID=180, label=1, output_node=20, voltage=0.0050019919872283936\n    time_span=0.0001s, test_ID=180, label=1, output_node=21, voltage=0.0019372511887922883\n    time_span=0.0001s, test_ID=180, label=1, output_node=22, voltage=0.0008007966098375618\n    time_span=0.0001s, test_ID=180, label=1, output_node=23, voltage=0.0035766931250691414\n    time_span=0.0001s, test_ID=180, label=1, output_node=24, voltage=0.0023426294792443514\n    time_span=0.0001s, test_ID=180, label=1, output_node=25, voltage=-8.466133294859901e-05\n    time_span=0.0001s, test_ID=180, label=1, output_node=26, voltage=0.0006035857368260622\n    time_span=0.0001s, test_ID=180, label=1, output_node=27, voltage=0.004214143380522728\n    time_span=0.0001s, test_ID=180, label=1, output_node=28, voltage=0.005675298627465963\n    time_span=0.0001s, test_ID=180, label=1, output_node=29, voltage=0.005384462419897318\n    time_span=0.0001s, test_ID=180, label=1, output_node=30, voltage=0.002791832899674773\n    time_span=0.0001s, test_ID=180, label=1, output_node=31, voltage=0.002866534050554037\n    time_span=0.0001s, test_ID=180, label=1, output_node=32, voltage=0.0040747011080384254\n    time_span=0.0001s, test_ID=180, label=1, output_node=33, voltage=0.009518924169242382\n    time_span=0.0001s, test_ID=180, label=1, output_node=34, voltage=0.000379481993149966\n    time_span=0.0001s, test_ID=180, label=1, output_node=35, voltage=0.0027659363113343716\n    time_span=0.0001s, test_ID=180, label=1, output_node=36, voltage=0.002419322496280074\n    time_span=0.0001s, test_ID=180, label=1, output_node=37, voltage=0.0028964143712073565\n    time_span=0.0001s, test_ID=180, label=1, output_node=38, voltage=0.00043127487879246473\n    time_span=0.0001s, test_ID=180, label=1, output_node=39, voltage=0.0028027889784425497\n    time_span=0.0001s, test_ID=180, label=1, output_node=40, voltage=0.0018974106060341\n    time_span=0.0001s, test_ID=180, label=1, output_node=41, voltage=0.004148406442254782\n    time_span=0.0001s, test_ID=180, label=1, output_node=42, voltage=0.0001005976228043437\n    time_span=0.0001s, test_ID=180, label=1, output_node=43, voltage=0.0070537845604121685\n    time_span=0.0001s, test_ID=180, label=1, output_node=44, voltage=0.00013645406579598784\n    time_span=0.0001s, test_ID=180, label=1, output_node=45, voltage=0.002436254872009158\n    time_span=0.0001s, test_ID=180, label=1, output_node=46, voltage=0.0035149403847754\n    time_span=0.0001s, test_ID=180, label=1, output_node=47, voltage=-0.002905378583818674\n    time_span=0.0001s, test_ID=180, label=1, output_node=48, voltage=0.0017001992091536522\n    time_span=0.0001s, test_ID=180, label=1, output_node=49, voltage=0.003205179236829281\n    time_span=0.0001s, test_ID=180, label=1, output_node=50, voltage=0.0008117530378513038\n    time_span=0.0001s, test_ID=180, label=1, output_node=51, voltage=-0.0007499999483115971\n    time_span=0.0001s, test_ID=180, label=1, output_node=52, voltage=0.005499999970197678\n    time_span=0.0001s, test_ID=180, label=1, output_node=53, voltage=-0.0005956175155006349\n    time_span=0.0001s, test_ID=180, label=1, output_node=54, voltage=0.002351593691855669\n    time_span=0.0001s, test_ID=180, label=1, output_node=55, voltage=0.003963147290050983\n    time_span=0.0001s, test_ID=180, label=1, output_node=56, voltage=0.0007529882132075727\n    time_span=0.0001s, test_ID=180, label=1, output_node=57, voltage=0.004334661643952131\n    time_span=0.0001s, test_ID=180, label=1, output_node=58, voltage=0.004540836438536644\n    time_span=0.0001s, test_ID=180, label=1, output_node=59, voltage=0.003072709310799837\n    time_span=0.0001s, test_ID=180, label=1, output_node=60, voltage=-0.00010856576409423724\n    time_span=0.0001s, test_ID=180, label=1, output_node=61, voltage=0.0032818722538650036\n    time_span=0.0001s, test_ID=180, label=1, output_node=62, voltage=0.005007967818528414\n    time_span=0.0001s, test_ID=180, label=1, output_node=63, voltage=0.0026105577126145363\n    time_span=0.0001s, test_ID=180, label=1, output_node=64, voltage=0.002234063809737563\n    time_span=0.0001s, test_ID=180, label=1, output_node=65, voltage=0.0032818724866956472\n    time_span=0.0001s, test_ID=180, label=1, output_node=66, voltage=0.0036494024097919464\n    time_span=0.0001s, test_ID=180, label=1, output_node=67, voltage=0.0025826692581176758\n    time_span=0.0001s, test_ID=180, label=1, output_node=68, voltage=0.003624501870945096\n    time_span=0.0001s, test_ID=180, label=1, output_node=69, voltage=0.002420318778604269\n    time_span=0.0001s, test_ID=180, label=1, output_node=70, voltage=-4.382468614494428e-05\n    time_span=0.0001s, test_ID=180, label=1, output_node=71, voltage=-4.3824729800689965e-05\n    time_span=0.0001s, test_ID=180, label=1, output_node=72, voltage=0.005190238822251558\n    time_span=0.0001s, test_ID=180, label=1, output_node=73, voltage=-0.00013745014439336956\n    time_span=0.0001s, test_ID=180, label=1, output_node=74, voltage=0.002648406196385622\n    time_span=0.0001s, test_ID=180, label=1, output_node=75, voltage=0.0031762949656695127\n    time_span=0.0001s, test_ID=180, label=1, output_node=76, voltage=0.00419621542096138\n    time_span=0.0001s, test_ID=180, label=1, output_node=77, voltage=0.0015438246773555875\n    time_span=0.0001s, test_ID=180, label=1, output_node=78, voltage=0.006695219315588474\n    time_span=0.0001s, test_ID=180, label=1, output_node=79, voltage=0.0010727093322202563\n    time_span=0.0001s, test_ID=180, label=1, output_node=80, voltage=0.0007231075433082879\n    time_span=0.0001s, test_ID=180, label=1, output_node=81, voltage=0.004970119334757328\n    time_span=0.0001s, test_ID=180, label=1, output_node=82, voltage=0.0023436257615685463\n    time_span=0.0001s, test_ID=180, label=1, output_node=83, voltage=0.0011872509494423866\n    time_span=0.0001s, test_ID=180, label=1, output_node=84, voltage=0.002961155492812395\n    time_span=0.0001s, test_ID=180, label=1, output_node=85, voltage=0.0035996015649288893\n    time_span=0.0001s, test_ID=180, label=1, output_node=86, voltage=0.008640437386929989\n    time_span=0.0001s, test_ID=180, label=1, output_node=87, voltage=-0.0010936255566775799\n    time_span=0.0001s, test_ID=180, label=1, output_node=88, voltage=0.002702191239222884\n    time_span=0.0001s, test_ID=180, label=1, output_node=89, voltage=-0.001250996021553874\n    time_span=0.0001s, test_ID=180, label=1, output_node=90, voltage=0.006074700970202684\n    time_span=0.0001s, test_ID=180, label=1, output_node=91, voltage=3.187254333170131e-05\n    time_span=0.0001s, test_ID=180, label=1, output_node=92, voltage=0.0068217129446566105\n    time_span=0.0001s, test_ID=180, label=1, output_node=93, voltage=0.0020049801096320152\n    time_span=0.0001s, test_ID=180, label=1, output_node=94, voltage=0.0012001991271972656\n    time_span=0.0001s, test_ID=180, label=1, output_node=95, voltage=0.005132469814270735\n    time_span=0.0001s, test_ID=180, label=1, output_node=96, voltage=0.0009183267829939723\n    time_span=0.0001s, test_ID=180, label=1, output_node=97, voltage=0.006280876230448484\n    time_span=0.0001s, test_ID=180, label=1, output_node=98, voltage=0.006236055865883827\n    time_span=0.0001s, test_ID=180, label=1, output_node=99, voltage=0.002426294842734933\n    time_span=0.0001s, test_ID=180, label=1, output_node=sum, voltage=0.013295818120241165\n    Time consumed for 1 sample = 624.3238091468811 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '180'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=181, label=8, output_node=bkg, voltage=-0.0064163352362811565\n    time_span=0.0001s, test_ID=181, label=8, output_node=0, voltage=0.007659363094717264\n    time_span=0.0001s, test_ID=181, label=8, output_node=1, voltage=0.004023904446512461\n    time_span=0.0001s, test_ID=181, label=8, output_node=2, voltage=0.009185259230434895\n    time_span=0.0001s, test_ID=181, label=8, output_node=3, voltage=0.0033147407229989767\n    time_span=0.0001s, test_ID=181, label=8, output_node=4, voltage=0.0031752989161759615\n    time_span=0.0001s, test_ID=181, label=8, output_node=5, voltage=0.011468127369880676\n    time_span=0.0001s, test_ID=181, label=8, output_node=6, voltage=0.007974104024469852\n    time_span=0.0001s, test_ID=181, label=8, output_node=7, voltage=0.0018456177785992622\n    time_span=0.0001s, test_ID=181, label=8, output_node=8, voltage=0.004679282661527395\n    time_span=0.0001s, test_ID=181, label=8, output_node=9, voltage=0.007257967721670866\n    time_span=0.0001s, test_ID=181, label=8, output_node=10, voltage=0.002728087594732642\n    time_span=0.0001s, test_ID=181, label=8, output_node=11, voltage=0.001359561807475984\n    time_span=0.0001s, test_ID=181, label=8, output_node=12, voltage=0.0045727090910077095\n    time_span=0.0001s, test_ID=181, label=8, output_node=13, voltage=0.006229083985090256\n    time_span=0.0001s, test_ID=181, label=8, output_node=14, voltage=0.005779880564659834\n    time_span=0.0001s, test_ID=181, label=8, output_node=15, voltage=0.0065288846381008625\n    time_span=0.0001s, test_ID=181, label=8, output_node=16, voltage=0.005646414589136839\n    time_span=0.0001s, test_ID=181, label=8, output_node=17, voltage=0.00610856618732214\n    time_span=0.0001s, test_ID=181, label=8, output_node=18, voltage=0.006979084108024836\n    time_span=0.0001s, test_ID=181, label=8, output_node=19, voltage=0.003951195161789656\n    time_span=0.0001s, test_ID=181, label=8, output_node=20, voltage=0.00598107511177659\n    time_span=0.0001s, test_ID=181, label=8, output_node=21, voltage=0.0042938245460391045\n    time_span=0.0001s, test_ID=181, label=8, output_node=22, voltage=0.001238047843798995\n    time_span=0.0001s, test_ID=181, label=8, output_node=23, voltage=0.00777191249653697\n    time_span=0.0001s, test_ID=181, label=8, output_node=24, voltage=0.005508964415639639\n    time_span=0.0001s, test_ID=181, label=8, output_node=25, voltage=0.0032589640468358994\n    time_span=0.0001s, test_ID=181, label=8, output_node=26, voltage=0.009202191606163979\n    time_span=0.0001s, test_ID=181, label=8, output_node=27, voltage=0.0039960159920156\n    time_span=0.0001s, test_ID=181, label=8, output_node=28, voltage=0.005323705263435841\n    time_span=0.0001s, test_ID=181, label=8, output_node=29, voltage=0.007257968187332153\n    time_span=0.0001s, test_ID=181, label=8, output_node=30, voltage=0.0021782871335744858\n    time_span=0.0001s, test_ID=181, label=8, output_node=31, voltage=0.009495020844042301\n    time_span=0.0001s, test_ID=181, label=8, output_node=32, voltage=0.007371514104306698\n    time_span=0.0001s, test_ID=181, label=8, output_node=33, voltage=0.006559761241078377\n    time_span=0.0001s, test_ID=181, label=8, output_node=34, voltage=0.0033645418006926775\n    time_span=0.0001s, test_ID=181, label=8, output_node=35, voltage=0.005887450650334358\n    time_span=0.0001s, test_ID=181, label=8, output_node=36, voltage=0.0036533863749355078\n    time_span=0.0001s, test_ID=181, label=8, output_node=37, voltage=0.002197211142629385\n    time_span=0.0001s, test_ID=181, label=8, output_node=38, voltage=0.0060607572086155415\n    time_span=0.0001s, test_ID=181, label=8, output_node=39, voltage=0.005192231386899948\n    time_span=0.0001s, test_ID=181, label=8, output_node=40, voltage=0.004771912470459938\n    time_span=0.0001s, test_ID=181, label=8, output_node=41, voltage=0.002600597683340311\n    time_span=0.0001s, test_ID=181, label=8, output_node=42, voltage=0.005916334223002195\n    time_span=0.0001s, test_ID=181, label=8, output_node=43, voltage=0.006936254911124706\n    time_span=0.0001s, test_ID=181, label=8, output_node=44, voltage=0.01034960150718689\n    time_span=0.0001s, test_ID=181, label=8, output_node=45, voltage=0.010433266870677471\n    time_span=0.0001s, test_ID=181, label=8, output_node=46, voltage=0.005231075920164585\n    time_span=0.0001s, test_ID=181, label=8, output_node=47, voltage=0.010377490893006325\n    time_span=0.0001s, test_ID=181, label=8, output_node=48, voltage=0.008246015757322311\n    time_span=0.0001s, test_ID=181, label=8, output_node=49, voltage=0.004753984045237303\n    time_span=0.0001s, test_ID=181, label=8, output_node=50, voltage=0.01223306730389595\n    time_span=0.0001s, test_ID=181, label=8, output_node=51, voltage=0.005422310903668404\n    time_span=0.0001s, test_ID=181, label=8, output_node=52, voltage=0.005186254624277353\n    time_span=0.0001s, test_ID=181, label=8, output_node=53, voltage=0.013277887366712093\n    time_span=0.0001s, test_ID=181, label=8, output_node=54, voltage=0.006758964620530605\n    time_span=0.0001s, test_ID=181, label=8, output_node=55, voltage=0.008899401873350143\n    time_span=0.0001s, test_ID=181, label=8, output_node=56, voltage=0.006056772544980049\n    time_span=0.0001s, test_ID=181, label=8, output_node=57, voltage=0.006870517507195473\n    time_span=0.0001s, test_ID=181, label=8, output_node=58, voltage=0.009389442391693592\n    time_span=0.0001s, test_ID=181, label=8, output_node=59, voltage=0.003677290864288807\n    time_span=0.0001s, test_ID=181, label=8, output_node=60, voltage=0.0012410357594490051\n    time_span=0.0001s, test_ID=181, label=8, output_node=61, voltage=0.004569721408188343\n    time_span=0.0001s, test_ID=181, label=8, output_node=62, voltage=0.006386453751474619\n    time_span=0.0001s, test_ID=181, label=8, output_node=63, voltage=0.009809761308133602\n    time_span=0.0001s, test_ID=181, label=8, output_node=64, voltage=0.0032500000670552254\n    time_span=0.0001s, test_ID=181, label=8, output_node=65, voltage=0.004797808825969696\n    time_span=0.0001s, test_ID=181, label=8, output_node=66, voltage=0.0039003982674330473\n    time_span=0.0001s, test_ID=181, label=8, output_node=67, voltage=0.011442231945693493\n    time_span=0.0001s, test_ID=181, label=8, output_node=68, voltage=0.0014741035411134362\n    time_span=0.0001s, test_ID=181, label=8, output_node=69, voltage=0.004767927806824446\n    time_span=0.0001s, test_ID=181, label=8, output_node=70, voltage=0.009832669049501419\n    time_span=0.0001s, test_ID=181, label=8, output_node=71, voltage=0.009790836833417416\n    time_span=0.0001s, test_ID=181, label=8, output_node=72, voltage=0.006857569795101881\n    time_span=0.0001s, test_ID=181, label=8, output_node=73, voltage=0.008014939725399017\n    time_span=0.0001s, test_ID=181, label=8, output_node=74, voltage=0.007073705550283194\n    time_span=0.0001s, test_ID=181, label=8, output_node=75, voltage=0.007753984536975622\n    time_span=0.0001s, test_ID=181, label=8, output_node=76, voltage=0.004626493901014328\n    time_span=0.0001s, test_ID=181, label=8, output_node=77, voltage=0.01209163386374712\n    time_span=0.0001s, test_ID=181, label=8, output_node=78, voltage=0.0069760954938828945\n    time_span=0.0001s, test_ID=181, label=8, output_node=79, voltage=0.0046494025737047195\n    time_span=0.0001s, test_ID=181, label=8, output_node=80, voltage=0.002446215134114027\n    time_span=0.0001s, test_ID=181, label=8, output_node=81, voltage=0.00697808712720871\n    time_span=0.0001s, test_ID=181, label=8, output_node=82, voltage=0.006987052038311958\n    time_span=0.0001s, test_ID=181, label=8, output_node=83, voltage=0.005852589849382639\n    time_span=0.0001s, test_ID=181, label=8, output_node=84, voltage=0.008679283782839775\n    time_span=0.0001s, test_ID=181, label=8, output_node=85, voltage=0.007898406125605106\n    time_span=0.0001s, test_ID=181, label=8, output_node=86, voltage=0.009175298735499382\n    time_span=0.0001s, test_ID=181, label=8, output_node=87, voltage=0.0043964143842458725\n    time_span=0.0001s, test_ID=181, label=8, output_node=88, voltage=0.009846612811088562\n    time_span=0.0001s, test_ID=181, label=8, output_node=89, voltage=0.006192231085151434\n    time_span=0.0001s, test_ID=181, label=8, output_node=90, voltage=0.0047998009249567986\n    time_span=0.0001s, test_ID=181, label=8, output_node=91, voltage=0.0044093625620007515\n    time_span=0.0001s, test_ID=181, label=8, output_node=92, voltage=0.005852589849382639\n    time_span=0.0001s, test_ID=181, label=8, output_node=93, voltage=0.0022808765061199665\n    time_span=0.0001s, test_ID=181, label=8, output_node=94, voltage=0.00673306779935956\n    time_span=0.0001s, test_ID=181, label=8, output_node=95, voltage=0.005663346499204636\n    time_span=0.0001s, test_ID=181, label=8, output_node=96, voltage=0.00678585609421134\n    time_span=0.0001s, test_ID=181, label=8, output_node=97, voltage=0.006210159510374069\n    time_span=0.0001s, test_ID=181, label=8, output_node=98, voltage=0.00680179288610816\n    time_span=0.0001s, test_ID=181, label=8, output_node=99, voltage=0.006355577148497105\n    time_span=0.0001s, test_ID=181, label=8, output_node=sum, voltage=0.022654380649328232\n    Time consumed for 1 sample = 624.5628709793091 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '181'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=182, label=5, output_node=bkg, voltage=-0.0044442228972911835\n    time_span=0.0001s, test_ID=182, label=5, output_node=0, voltage=0.013402391225099564\n    time_span=0.0001s, test_ID=182, label=5, output_node=1, voltage=0.003934262786060572\n    time_span=0.0001s, test_ID=182, label=5, output_node=2, voltage=0.0037828683853149414\n    time_span=0.0001s, test_ID=182, label=5, output_node=3, voltage=0.0007021911442279816\n    time_span=0.0001s, test_ID=182, label=5, output_node=4, voltage=0.002113546011969447\n    time_span=0.0001s, test_ID=182, label=5, output_node=5, voltage=0.008553784340620041\n    time_span=0.0001s, test_ID=182, label=5, output_node=6, voltage=0.013320717960596085\n    time_span=0.0001s, test_ID=182, label=5, output_node=7, voltage=0.003896414302289486\n    time_span=0.0001s, test_ID=182, label=5, output_node=8, voltage=0.009898406453430653\n    time_span=0.0001s, test_ID=182, label=5, output_node=9, voltage=0.0047061750665307045\n    time_span=0.0001s, test_ID=182, label=5, output_node=10, voltage=0.0030009960755705833\n    time_span=0.0001s, test_ID=182, label=5, output_node=11, voltage=0.00765637494623661\n    time_span=0.0001s, test_ID=182, label=5, output_node=12, voltage=0.004587649367749691\n    time_span=0.0001s, test_ID=182, label=5, output_node=13, voltage=0.0068346611224114895\n    time_span=0.0001s, test_ID=182, label=5, output_node=14, voltage=0.0018227093387395144\n    time_span=0.0001s, test_ID=182, label=5, output_node=15, voltage=0.004367529880255461\n    time_span=0.0001s, test_ID=182, label=5, output_node=16, voltage=0.008923306129872799\n    time_span=0.0001s, test_ID=182, label=5, output_node=17, voltage=0.008390437811613083\n    time_span=0.0001s, test_ID=182, label=5, output_node=18, voltage=0.007098605390638113\n    time_span=0.0001s, test_ID=182, label=5, output_node=19, voltage=0.006721115671098232\n    time_span=0.0001s, test_ID=182, label=5, output_node=20, voltage=0.0032390442211180925\n    time_span=0.0001s, test_ID=182, label=5, output_node=21, voltage=0.006832669023424387\n    time_span=0.0001s, test_ID=182, label=5, output_node=22, voltage=0.0009123505442403257\n    time_span=0.0001s, test_ID=182, label=5, output_node=23, voltage=0.007031872868537903\n    time_span=0.0001s, test_ID=182, label=5, output_node=24, voltage=0.007583665661513805\n    time_span=0.0001s, test_ID=182, label=5, output_node=25, voltage=0.006647410336881876\n    time_span=0.0001s, test_ID=182, label=5, output_node=26, voltage=0.006704183295369148\n    time_span=0.0001s, test_ID=182, label=5, output_node=27, voltage=0.005343625787645578\n    time_span=0.0001s, test_ID=182, label=5, output_node=28, voltage=0.0031055777799338102\n    time_span=0.0001s, test_ID=182, label=5, output_node=29, voltage=0.006363545544445515\n    time_span=0.0001s, test_ID=182, label=5, output_node=30, voltage=0.003356573637574911\n    time_span=0.0001s, test_ID=182, label=5, output_node=31, voltage=0.014037848450243473\n    time_span=0.0001s, test_ID=182, label=5, output_node=32, voltage=0.0062111555598676205\n    time_span=0.0001s, test_ID=182, label=5, output_node=33, voltage=0.00987251102924347\n    time_span=0.0001s, test_ID=182, label=5, output_node=34, voltage=0.005375498440116644\n    time_span=0.0001s, test_ID=182, label=5, output_node=35, voltage=0.003536852775141597\n    time_span=0.0001s, test_ID=182, label=5, output_node=36, voltage=0.007565736770629883\n    time_span=0.0001s, test_ID=182, label=5, output_node=37, voltage=0.009278884157538414\n    time_span=0.0001s, test_ID=182, label=5, output_node=38, voltage=0.004681274760514498\n    time_span=0.0001s, test_ID=182, label=5, output_node=39, voltage=0.009856573306024075\n    time_span=0.0001s, test_ID=182, label=5, output_node=40, voltage=0.009381473995745182\n    time_span=0.0001s, test_ID=182, label=5, output_node=41, voltage=0.007807768881320953\n    time_span=0.0001s, test_ID=182, label=5, output_node=42, voltage=0.0058456179685890675\n    time_span=0.0001s, test_ID=182, label=5, output_node=43, voltage=0.007894422858953476\n    time_span=0.0001s, test_ID=182, label=5, output_node=44, voltage=0.0092978086322546\n    time_span=0.0001s, test_ID=182, label=5, output_node=45, voltage=0.009894422255456448\n    time_span=0.0001s, test_ID=182, label=5, output_node=46, voltage=0.0060438248328864574\n    time_span=0.0001s, test_ID=182, label=5, output_node=47, voltage=0.011964143253862858\n    time_span=0.0001s, test_ID=182, label=5, output_node=48, voltage=0.006048804614692926\n    time_span=0.0001s, test_ID=182, label=5, output_node=49, voltage=0.0021952190436422825\n    time_span=0.0001s, test_ID=182, label=5, output_node=50, voltage=0.00924203172326088\n    time_span=0.0001s, test_ID=182, label=5, output_node=51, voltage=0.007811753079295158\n    time_span=0.0001s, test_ID=182, label=5, output_node=52, voltage=0.007589641492813826\n    time_span=0.0001s, test_ID=182, label=5, output_node=53, voltage=0.01240737084299326\n    time_span=0.0001s, test_ID=182, label=5, output_node=54, voltage=0.0048994021490216255\n    time_span=0.0001s, test_ID=182, label=5, output_node=55, voltage=0.005783864762634039\n    time_span=0.0001s, test_ID=182, label=5, output_node=56, voltage=0.0018137451261281967\n    time_span=0.0001s, test_ID=182, label=5, output_node=57, voltage=0.017226096242666245\n    time_span=0.0001s, test_ID=182, label=5, output_node=58, voltage=0.009119521826505661\n    time_span=0.0001s, test_ID=182, label=5, output_node=59, voltage=0.0031842628959566355\n    time_span=0.0001s, test_ID=182, label=5, output_node=60, voltage=0.005362549796700478\n    time_span=0.0001s, test_ID=182, label=5, output_node=61, voltage=0.012472111731767654\n    time_span=0.0001s, test_ID=182, label=5, output_node=62, voltage=0.010091633535921574\n    time_span=0.0001s, test_ID=182, label=5, output_node=63, voltage=0.007330677006393671\n    time_span=0.0001s, test_ID=182, label=5, output_node=64, voltage=0.0034193226601928473\n    time_span=0.0001s, test_ID=182, label=5, output_node=65, voltage=0.008212151005864143\n    time_span=0.0001s, test_ID=182, label=5, output_node=66, voltage=0.004451195243746042\n    time_span=0.0001s, test_ID=182, label=5, output_node=67, voltage=0.002628485905006528\n    time_span=0.0001s, test_ID=182, label=5, output_node=68, voltage=0.011029880493879318\n    time_span=0.0001s, test_ID=182, label=5, output_node=69, voltage=0.008641434833407402\n    time_span=0.0001s, test_ID=182, label=5, output_node=70, voltage=0.014587649144232273\n    time_span=0.0001s, test_ID=182, label=5, output_node=71, voltage=0.01441235188394785\n    time_span=0.0001s, test_ID=182, label=5, output_node=72, voltage=0.011403386481106281\n    time_span=0.0001s, test_ID=182, label=5, output_node=73, voltage=0.005701194982975721\n    time_span=0.0001s, test_ID=182, label=5, output_node=74, voltage=0.0022320717107504606\n    time_span=0.0001s, test_ID=182, label=5, output_node=75, voltage=0.009343625977635384\n    time_span=0.0001s, test_ID=182, label=5, output_node=76, voltage=0.002080677542835474\n    time_span=0.0001s, test_ID=182, label=5, output_node=77, voltage=0.0072729079984128475\n    time_span=0.0001s, test_ID=182, label=5, output_node=78, voltage=0.005766932386904955\n    time_span=0.0001s, test_ID=182, label=5, output_node=79, voltage=0.006994024384766817\n    time_span=0.0001s, test_ID=182, label=5, output_node=80, voltage=0.006369521841406822\n    time_span=0.0001s, test_ID=182, label=5, output_node=81, voltage=0.005315736867487431\n    time_span=0.0001s, test_ID=182, label=5, output_node=82, voltage=0.00783466175198555\n    time_span=0.0001s, test_ID=182, label=5, output_node=83, voltage=0.008132469840347767\n    time_span=0.0001s, test_ID=182, label=5, output_node=84, voltage=0.0031593625899404287\n    time_span=0.0001s, test_ID=182, label=5, output_node=85, voltage=0.0074970112182199955\n    time_span=0.0001s, test_ID=182, label=5, output_node=86, voltage=0.00551593629643321\n    time_span=0.0001s, test_ID=182, label=5, output_node=87, voltage=0.007954183034598827\n    time_span=0.0001s, test_ID=182, label=5, output_node=88, voltage=0.004424302838742733\n    time_span=0.0001s, test_ID=182, label=5, output_node=89, voltage=0.004338645376265049\n    time_span=0.0001s, test_ID=182, label=5, output_node=90, voltage=0.005684262607246637\n    time_span=0.0001s, test_ID=182, label=5, output_node=91, voltage=0.005387450568377972\n    time_span=0.0001s, test_ID=182, label=5, output_node=92, voltage=0.0043665338307619095\n    time_span=0.0001s, test_ID=182, label=5, output_node=93, voltage=0.008786853402853012\n    time_span=0.0001s, test_ID=182, label=5, output_node=94, voltage=0.004095617216080427\n    time_span=0.0001s, test_ID=182, label=5, output_node=95, voltage=0.004065736662596464\n    time_span=0.0001s, test_ID=182, label=5, output_node=96, voltage=0.008034860715270042\n    time_span=0.0001s, test_ID=182, label=5, output_node=97, voltage=0.0036643424537032843\n    time_span=0.0001s, test_ID=182, label=5, output_node=98, voltage=0.006919322069734335\n    time_span=0.0001s, test_ID=182, label=5, output_node=99, voltage=0.0052001988515257835\n    time_span=0.0001s, test_ID=182, label=5, output_node=sum, voltage=0.02343127690255642\n    Time consumed for 1 sample = 624.8788557052612 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '182'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=183, label=0, output_node=bkg, voltage=-0.003738047555088997\n    time_span=0.0001s, test_ID=183, label=0, output_node=0, voltage=0.005315736867487431\n    time_span=0.0001s, test_ID=183, label=0, output_node=1, voltage=0.004865537863224745\n    time_span=0.0001s, test_ID=183, label=0, output_node=2, voltage=0.00794422347098589\n    time_span=0.0001s, test_ID=183, label=0, output_node=3, voltage=0.0049332669004797935\n    time_span=0.0001s, test_ID=183, label=0, output_node=4, voltage=0.004381474107503891\n    time_span=0.0001s, test_ID=183, label=0, output_node=5, voltage=0.007794820237904787\n    time_span=0.0001s, test_ID=183, label=0, output_node=6, voltage=0.006806773133575916\n    time_span=0.0001s, test_ID=183, label=0, output_node=7, voltage=0.0034661355894058943\n    time_span=0.0001s, test_ID=183, label=0, output_node=8, voltage=0.009118526242673397\n    time_span=0.0001s, test_ID=183, label=0, output_node=9, voltage=0.008596613071858883\n    time_span=0.0001s, test_ID=183, label=0, output_node=10, voltage=0.006772908382117748\n    time_span=0.0001s, test_ID=183, label=0, output_node=11, voltage=0.007479084189981222\n    time_span=0.0001s, test_ID=183, label=0, output_node=12, voltage=0.0025328686460852623\n    time_span=0.0001s, test_ID=183, label=0, output_node=13, voltage=0.00564741063863039\n    time_span=0.0001s, test_ID=183, label=0, output_node=14, voltage=0.004475099500268698\n    time_span=0.0001s, test_ID=183, label=0, output_node=15, voltage=0.006252987775951624\n    time_span=0.0001s, test_ID=183, label=0, output_node=16, voltage=0.00589442253112793\n    time_span=0.0001s, test_ID=183, label=0, output_node=17, voltage=0.009426293894648552\n    time_span=0.0001s, test_ID=183, label=0, output_node=18, voltage=0.0019083665683865547\n    time_span=0.0001s, test_ID=183, label=0, output_node=19, voltage=0.003995019476860762\n    time_span=0.0001s, test_ID=183, label=0, output_node=20, voltage=0.006068725138902664\n    time_span=0.0001s, test_ID=183, label=0, output_node=21, voltage=0.003755975980311632\n    time_span=0.0001s, test_ID=183, label=0, output_node=22, voltage=0.004076693207025528\n    time_span=0.0001s, test_ID=183, label=0, output_node=23, voltage=0.004010956268757582\n    time_span=0.0001s, test_ID=183, label=0, output_node=24, voltage=0.004007967654615641\n    time_span=0.0001s, test_ID=183, label=0, output_node=25, voltage=0.012163346633315086\n    time_span=0.0001s, test_ID=183, label=0, output_node=26, voltage=0.006500000134110451\n    time_span=0.0001s, test_ID=183, label=0, output_node=27, voltage=-0.000422310724388808\n    time_span=0.0001s, test_ID=183, label=0, output_node=28, voltage=0.007214143872261047\n    time_span=0.0001s, test_ID=183, label=0, output_node=29, voltage=0.010153386741876602\n    time_span=0.0001s, test_ID=183, label=0, output_node=30, voltage=0.003497011959552765\n    time_span=0.0001s, test_ID=183, label=0, output_node=31, voltage=0.0008247012738138437\n    time_span=0.0001s, test_ID=183, label=0, output_node=32, voltage=0.003661354770883918\n    time_span=0.0001s, test_ID=183, label=0, output_node=33, voltage=-0.0010946214897558093\n    time_span=0.0001s, test_ID=183, label=0, output_node=34, voltage=0.004377489909529686\n    time_span=0.0001s, test_ID=183, label=0, output_node=35, voltage=0.006910358089953661\n    time_span=0.0001s, test_ID=183, label=0, output_node=36, voltage=0.0031553786247968674\n    time_span=0.0001s, test_ID=183, label=0, output_node=37, voltage=0.004389442503452301\n    time_span=0.0001s, test_ID=183, label=0, output_node=38, voltage=0.003510956186801195\n    time_span=0.0001s, test_ID=183, label=0, output_node=39, voltage=0.003909362945705652\n    time_span=0.0001s, test_ID=183, label=0, output_node=40, voltage=0.01005079597234726\n    time_span=0.0001s, test_ID=183, label=0, output_node=41, voltage=0.0023774898145347834\n    time_span=0.0001s, test_ID=183, label=0, output_node=42, voltage=0.012315738014876842\n    time_span=0.0001s, test_ID=183, label=0, output_node=43, voltage=0.0041772909462451935\n    time_span=0.0001s, test_ID=183, label=0, output_node=44, voltage=0.0037669322919100523\n    time_span=0.0001s, test_ID=183, label=0, output_node=45, voltage=0.008580677211284637\n    time_span=0.0001s, test_ID=183, label=0, output_node=46, voltage=0.009759959764778614\n    time_span=0.0001s, test_ID=183, label=0, output_node=47, voltage=0.01286454126238823\n    time_span=0.0001s, test_ID=183, label=0, output_node=48, voltage=0.005744023714214563\n    time_span=0.0001s, test_ID=183, label=0, output_node=49, voltage=0.00645617488771677\n    time_span=0.0001s, test_ID=183, label=0, output_node=50, voltage=0.004670318681746721\n    time_span=0.0001s, test_ID=183, label=0, output_node=51, voltage=0.004989044275134802\n    time_span=0.0001s, test_ID=183, label=0, output_node=52, voltage=0.008217131718993187\n    time_span=0.0001s, test_ID=183, label=0, output_node=53, voltage=0.005862549878656864\n    time_span=0.0001s, test_ID=183, label=0, output_node=54, voltage=0.005180278792977333\n    time_span=0.0001s, test_ID=183, label=0, output_node=55, voltage=0.004083665553480387\n    time_span=0.0001s, test_ID=183, label=0, output_node=56, voltage=0.0010567730059847236\n    time_span=0.0001s, test_ID=183, label=0, output_node=57, voltage=0.0044053783640265465\n    time_span=0.0001s, test_ID=183, label=0, output_node=58, voltage=0.00493824714794755\n    time_span=0.0001s, test_ID=183, label=0, output_node=59, voltage=0.0038147412706166506\n    time_span=0.0001s, test_ID=183, label=0, output_node=60, voltage=0.005868526175618172\n    time_span=0.0001s, test_ID=183, label=0, output_node=61, voltage=0.005290836561471224\n    time_span=0.0001s, test_ID=183, label=0, output_node=62, voltage=0.006734063848853111\n    time_span=0.0001s, test_ID=183, label=0, output_node=63, voltage=0.009897410869598389\n    time_span=0.0001s, test_ID=183, label=0, output_node=64, voltage=0.0016434263670817018\n    time_span=0.0001s, test_ID=183, label=0, output_node=65, voltage=0.0050268922932446\n    time_span=0.0001s, test_ID=183, label=0, output_node=66, voltage=0.0030816730577498674\n    time_span=0.0001s, test_ID=183, label=0, output_node=67, voltage=0.002628485905006528\n    time_span=0.0001s, test_ID=183, label=0, output_node=68, voltage=0.006162350531667471\n    time_span=0.0001s, test_ID=183, label=0, output_node=69, voltage=0.00540537852793932\n    time_span=0.0001s, test_ID=183, label=0, output_node=70, voltage=0.00827490072697401\n    time_span=0.0001s, test_ID=183, label=0, output_node=71, voltage=0.010529880411922932\n    time_span=0.0001s, test_ID=183, label=0, output_node=72, voltage=0.0011513944482430816\n    time_span=0.0001s, test_ID=183, label=0, output_node=73, voltage=0.0046404385939240456\n    time_span=0.0001s, test_ID=183, label=0, output_node=74, voltage=0.002825697185471654\n    time_span=0.0001s, test_ID=183, label=0, output_node=75, voltage=0.004442231263965368\n    time_span=0.0001s, test_ID=183, label=0, output_node=76, voltage=0.005446214694529772\n    time_span=0.0001s, test_ID=183, label=0, output_node=77, voltage=0.0031723107676953077\n    time_span=0.0001s, test_ID=183, label=0, output_node=78, voltage=0.005596613511443138\n    time_span=0.0001s, test_ID=183, label=0, output_node=79, voltage=0.01286752987653017\n    time_span=0.0001s, test_ID=183, label=0, output_node=80, voltage=0.007994023151695728\n    time_span=0.0001s, test_ID=183, label=0, output_node=81, voltage=0.008669323287904263\n    time_span=0.0001s, test_ID=183, label=0, output_node=82, voltage=0.0030677292961627245\n    time_span=0.0001s, test_ID=183, label=0, output_node=83, voltage=0.006059760693460703\n    time_span=0.0001s, test_ID=183, label=0, output_node=84, voltage=0.00980278942734003\n    time_span=0.0001s, test_ID=183, label=0, output_node=85, voltage=0.003536852775141597\n    time_span=0.0001s, test_ID=183, label=0, output_node=86, voltage=0.0022778885904699564\n    time_span=0.0001s, test_ID=183, label=0, output_node=87, voltage=0.010312749072909355\n    time_span=0.0001s, test_ID=183, label=0, output_node=88, voltage=0.006333665456622839\n    time_span=0.0001s, test_ID=183, label=0, output_node=89, voltage=0.007633466273546219\n    time_span=0.0001s, test_ID=183, label=0, output_node=90, voltage=0.0049860551953315735\n    time_span=0.0001s, test_ID=183, label=0, output_node=91, voltage=0.00867131445556879\n    time_span=0.0001s, test_ID=183, label=0, output_node=92, voltage=0.003250995883718133\n    time_span=0.0001s, test_ID=183, label=0, output_node=93, voltage=0.009921315126121044\n    time_span=0.0001s, test_ID=183, label=0, output_node=94, voltage=0.003668326884508133\n    time_span=0.0001s, test_ID=183, label=0, output_node=95, voltage=0.004118525423109531\n    time_span=0.0001s, test_ID=183, label=0, output_node=96, voltage=0.00596314761787653\n    time_span=0.0001s, test_ID=183, label=0, output_node=97, voltage=0.0032121515832841396\n    time_span=0.0001s, test_ID=183, label=0, output_node=98, voltage=0.005029880441725254\n    time_span=0.0001s, test_ID=183, label=0, output_node=99, voltage=0.004493027459830046\n    time_span=0.0001s, test_ID=183, label=0, output_node=sum, voltage=0.020273903384804726\n    Time consumed for 1 sample = 624.3566334247589 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '183'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=184, label=8, output_node=bkg, voltage=-0.005237051751464605\n    time_span=0.0001s, test_ID=184, label=8, output_node=0, voltage=0.004578685387969017\n    time_span=0.0001s, test_ID=184, label=8, output_node=1, voltage=0.008129483088850975\n    time_span=0.0001s, test_ID=184, label=8, output_node=2, voltage=0.013182271271944046\n    time_span=0.0001s, test_ID=184, label=8, output_node=3, voltage=0.003263944061473012\n    time_span=0.0001s, test_ID=184, label=8, output_node=4, voltage=0.01147310808300972\n    time_span=0.0001s, test_ID=184, label=8, output_node=5, voltage=0.012974104844033718\n    time_span=0.0001s, test_ID=184, label=8, output_node=6, voltage=0.008326693437993526\n    time_span=0.0001s, test_ID=184, label=8, output_node=7, voltage=0.009015936404466629\n    time_span=0.0001s, test_ID=184, label=8, output_node=8, voltage=0.005151394288986921\n    time_span=0.0001s, test_ID=184, label=8, output_node=9, voltage=0.008993026800453663\n    time_span=0.0001s, test_ID=184, label=8, output_node=10, voltage=0.011649402789771557\n    time_span=0.0001s, test_ID=184, label=8, output_node=11, voltage=0.00660956185311079\n    time_span=0.0001s, test_ID=184, label=8, output_node=12, voltage=0.0027649402618408203\n    time_span=0.0001s, test_ID=184, label=8, output_node=13, voltage=0.010326692834496498\n    time_span=0.0001s, test_ID=184, label=8, output_node=14, voltage=0.012982072308659554\n    time_span=0.0001s, test_ID=184, label=8, output_node=15, voltage=0.006159362383186817\n    time_span=0.0001s, test_ID=184, label=8, output_node=16, voltage=0.010444222949445248\n    time_span=0.0001s, test_ID=184, label=8, output_node=17, voltage=0.009609561413526535\n    time_span=0.0001s, test_ID=184, label=8, output_node=18, voltage=0.010190239176154137\n    time_span=0.0001s, test_ID=184, label=8, output_node=19, voltage=0.005957171320915222\n    time_span=0.0001s, test_ID=184, label=8, output_node=20, voltage=0.008458167314529419\n    time_span=0.0001s, test_ID=184, label=8, output_node=21, voltage=0.008899401873350143\n    time_span=0.0001s, test_ID=184, label=8, output_node=22, voltage=0.012186255306005478\n    time_span=0.0001s, test_ID=184, label=8, output_node=23, voltage=0.009545816108584404\n    time_span=0.0001s, test_ID=184, label=8, output_node=24, voltage=0.007693226914852858\n    time_span=0.0001s, test_ID=184, label=8, output_node=25, voltage=0.012356573715806007\n    time_span=0.0001s, test_ID=184, label=8, output_node=26, voltage=0.01067729014903307\n    time_span=0.0001s, test_ID=184, label=8, output_node=27, voltage=0.00947609543800354\n    time_span=0.0001s, test_ID=184, label=8, output_node=28, voltage=0.005866533610969782\n    time_span=0.0001s, test_ID=184, label=8, output_node=29, voltage=0.01156175322830677\n    time_span=0.0001s, test_ID=184, label=8, output_node=30, voltage=0.0064731077291071415\n    time_span=0.0001s, test_ID=184, label=8, output_node=31, voltage=0.010962151922285557\n    time_span=0.0001s, test_ID=184, label=8, output_node=32, voltage=0.012501992285251617\n    time_span=0.0001s, test_ID=184, label=8, output_node=33, voltage=0.009908366948366165\n    time_span=0.0001s, test_ID=184, label=8, output_node=34, voltage=0.008158366195857525\n    time_span=0.0001s, test_ID=184, label=8, output_node=35, voltage=0.009912350215017796\n    time_span=0.0001s, test_ID=184, label=8, output_node=36, voltage=0.008015936240553856\n    time_span=0.0001s, test_ID=184, label=8, output_node=37, voltage=0.0040747011080384254\n    time_span=0.0001s, test_ID=184, label=8, output_node=38, voltage=0.014123505912721157\n    time_span=0.0001s, test_ID=184, label=8, output_node=39, voltage=0.008449203334748745\n    time_span=0.0001s, test_ID=184, label=8, output_node=40, voltage=0.01245219074189663\n    time_span=0.0001s, test_ID=184, label=8, output_node=41, voltage=0.007707171142101288\n    time_span=0.0001s, test_ID=184, label=8, output_node=42, voltage=0.0065936255268752575\n    time_span=0.0001s, test_ID=184, label=8, output_node=43, voltage=0.01045020017772913\n    time_span=0.0001s, test_ID=184, label=8, output_node=44, voltage=0.01319123525172472\n    time_span=0.0001s, test_ID=184, label=8, output_node=45, voltage=0.009456174448132515\n    time_span=0.0001s, test_ID=184, label=8, output_node=46, voltage=0.0071822707541286945\n    time_span=0.0001s, test_ID=184, label=8, output_node=47, voltage=0.014476096257567406\n    time_span=0.0001s, test_ID=184, label=8, output_node=48, voltage=0.006467131432145834\n    time_span=0.0001s, test_ID=184, label=8, output_node=49, voltage=0.008507967926561832\n    time_span=0.0001s, test_ID=184, label=8, output_node=50, voltage=0.012665337882936\n    time_span=0.0001s, test_ID=184, label=8, output_node=51, voltage=0.009645418263971806\n    time_span=0.0001s, test_ID=184, label=8, output_node=52, voltage=0.009331673383712769\n    time_span=0.0001s, test_ID=184, label=8, output_node=53, voltage=0.011739043518900871\n    time_span=0.0001s, test_ID=184, label=8, output_node=54, voltage=0.011095617897808552\n    time_span=0.0001s, test_ID=184, label=8, output_node=55, voltage=0.016079682856798172\n    time_span=0.0001s, test_ID=184, label=8, output_node=56, voltage=0.012743028812110424\n    time_span=0.0001s, test_ID=184, label=8, output_node=57, voltage=0.012101594358682632\n    time_span=0.0001s, test_ID=184, label=8, output_node=58, voltage=0.008723107166588306\n    time_span=0.0001s, test_ID=184, label=8, output_node=59, voltage=0.005693227052688599\n    time_span=0.0001s, test_ID=184, label=8, output_node=60, voltage=0.005691234953701496\n    time_span=0.0001s, test_ID=184, label=8, output_node=61, voltage=0.009287849068641663\n    time_span=0.0001s, test_ID=184, label=8, output_node=62, voltage=0.004496016073971987\n    time_span=0.0001s, test_ID=184, label=8, output_node=63, voltage=0.009348604828119278\n    time_span=0.0001s, test_ID=184, label=8, output_node=64, voltage=0.0061384462751448154\n    time_span=0.0001s, test_ID=184, label=8, output_node=65, voltage=0.007087649777531624\n    time_span=0.0001s, test_ID=184, label=8, output_node=66, voltage=0.021415337920188904\n    time_span=0.0001s, test_ID=184, label=8, output_node=67, voltage=0.011847608722746372\n    time_span=0.0001s, test_ID=184, label=8, output_node=68, voltage=0.011033865623176098\n    time_span=0.0001s, test_ID=184, label=8, output_node=69, voltage=0.008789841085672379\n    time_span=0.0001s, test_ID=184, label=8, output_node=70, voltage=0.008497011847794056\n    time_span=0.0001s, test_ID=184, label=8, output_node=71, voltage=0.011908366344869137\n    time_span=0.0001s, test_ID=184, label=8, output_node=72, voltage=0.01000099629163742\n    time_span=0.0001s, test_ID=184, label=8, output_node=73, voltage=0.008284860290586948\n    time_span=0.0001s, test_ID=184, label=8, output_node=74, voltage=0.009074700996279716\n    time_span=0.0001s, test_ID=184, label=8, output_node=75, voltage=0.013804781250655651\n    time_span=0.0001s, test_ID=184, label=8, output_node=76, voltage=0.009801791980862617\n    time_span=0.0001s, test_ID=184, label=8, output_node=77, voltage=0.015658367425203323\n    time_span=0.0001s, test_ID=184, label=8, output_node=78, voltage=0.007802788633853197\n    time_span=0.0001s, test_ID=184, label=8, output_node=79, voltage=0.006491036154329777\n    time_span=0.0001s, test_ID=184, label=8, output_node=80, voltage=0.0016982073429971933\n    time_span=0.0001s, test_ID=184, label=8, output_node=81, voltage=0.009000997059047222\n    time_span=0.0001s, test_ID=184, label=8, output_node=82, voltage=0.009333665482699871\n    time_span=0.0001s, test_ID=184, label=8, output_node=83, voltage=0.011555776000022888\n    time_span=0.0001s, test_ID=184, label=8, output_node=84, voltage=0.006879481486976147\n    time_span=0.0001s, test_ID=184, label=8, output_node=85, voltage=0.0074422312900424\n    time_span=0.0001s, test_ID=184, label=8, output_node=86, voltage=0.013511952012777328\n    time_span=0.0001s, test_ID=184, label=8, output_node=87, voltage=0.012085657566785812\n    time_span=0.0001s, test_ID=184, label=8, output_node=88, voltage=0.01048207189887762\n    time_span=0.0001s, test_ID=184, label=8, output_node=89, voltage=0.008874502032995224\n    time_span=0.0001s, test_ID=184, label=8, output_node=90, voltage=0.008823703974485397\n    time_span=0.0001s, test_ID=184, label=8, output_node=91, voltage=0.0049681272357702255\n    time_span=0.0001s, test_ID=184, label=8, output_node=92, voltage=0.007924302481114864\n    time_span=0.0001s, test_ID=184, label=8, output_node=93, voltage=0.006665339227765799\n    time_span=0.0001s, test_ID=184, label=8, output_node=94, voltage=0.01159860473126173\n    time_span=0.0001s, test_ID=184, label=8, output_node=95, voltage=0.010087649337947369\n    time_span=0.0001s, test_ID=184, label=8, output_node=96, voltage=0.007155378349125385\n    time_span=0.0001s, test_ID=184, label=8, output_node=97, voltage=0.01169123500585556\n    time_span=0.0001s, test_ID=184, label=8, output_node=98, voltage=0.0006543825147673488\n    time_span=0.0001s, test_ID=184, label=8, output_node=99, voltage=0.01512051746249199\n    time_span=0.0001s, test_ID=184, label=8, output_node=sum, voltage=0.03181872516870499\n    Time consumed for 1 sample = 622.2333791255951 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '184'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=185, label=9, output_node=bkg, voltage=-0.006102589424699545\n    time_span=0.0001s, test_ID=185, label=9, output_node=0, voltage=0.0041344622150063515\n    time_span=0.0001s, test_ID=185, label=9, output_node=1, voltage=0.005355577450245619\n    time_span=0.0001s, test_ID=185, label=9, output_node=2, voltage=0.0022649401798844337\n    time_span=0.0001s, test_ID=185, label=9, output_node=3, voltage=0.0024750996381044388\n    time_span=0.0001s, test_ID=185, label=9, output_node=4, voltage=0.005984063725918531\n    time_span=0.0001s, test_ID=185, label=9, output_node=5, voltage=0.002386454027146101\n    time_span=0.0001s, test_ID=185, label=9, output_node=6, voltage=0.0027260954957455397\n    time_span=0.0001s, test_ID=185, label=9, output_node=7, voltage=0.006391433998942375\n    time_span=0.0001s, test_ID=185, label=9, output_node=8, voltage=0.0025527889374643564\n    time_span=0.0001s, test_ID=185, label=9, output_node=9, voltage=0.005948207341134548\n    time_span=0.0001s, test_ID=185, label=9, output_node=10, voltage=0.00721613597124815\n    time_span=0.0001s, test_ID=185, label=9, output_node=11, voltage=0.0016424302011728287\n    time_span=0.0001s, test_ID=185, label=9, output_node=12, voltage=0.005857569631189108\n    time_span=0.0001s, test_ID=185, label=9, output_node=13, voltage=0.002702191239222884\n    time_span=0.0001s, test_ID=185, label=9, output_node=14, voltage=0.0028725098818540573\n    time_span=0.0001s, test_ID=185, label=9, output_node=15, voltage=0.0048436252400279045\n    time_span=0.0001s, test_ID=185, label=9, output_node=16, voltage=0.004222111776471138\n    time_span=0.0001s, test_ID=185, label=9, output_node=17, voltage=0.0043017929419875145\n    time_span=0.0001s, test_ID=185, label=9, output_node=18, voltage=0.003196215257048607\n    time_span=0.0001s, test_ID=185, label=9, output_node=19, voltage=0.001736055826768279\n    time_span=0.0001s, test_ID=185, label=9, output_node=20, voltage=0.005062749143689871\n    time_span=0.0001s, test_ID=185, label=9, output_node=21, voltage=0.005698206834495068\n    time_span=0.0001s, test_ID=185, label=9, output_node=22, voltage=0.006874502170830965\n    time_span=0.0001s, test_ID=185, label=9, output_node=23, voltage=0.0014033865882083774\n    time_span=0.0001s, test_ID=185, label=9, output_node=24, voltage=0.0036015938967466354\n    time_span=0.0001s, test_ID=185, label=9, output_node=25, voltage=0.003368525533005595\n    time_span=0.0001s, test_ID=185, label=9, output_node=26, voltage=0.0018057769630104303\n    time_span=0.0001s, test_ID=185, label=9, output_node=27, voltage=0.0084043825045228\n    time_span=0.0001s, test_ID=185, label=9, output_node=28, voltage=0.008939243853092194\n    time_span=0.0001s, test_ID=185, label=9, output_node=29, voltage=0.007986055687069893\n    time_span=0.0001s, test_ID=185, label=9, output_node=30, voltage=0.0037450199015438557\n    time_span=0.0001s, test_ID=185, label=9, output_node=31, voltage=0.000976095674559474\n    time_span=0.0001s, test_ID=185, label=9, output_node=32, voltage=0.0021235060412436724\n    time_span=0.0001s, test_ID=185, label=9, output_node=33, voltage=0.006641434505581856\n    time_span=0.0001s, test_ID=185, label=9, output_node=34, voltage=0.003437251318246126\n    time_span=0.0001s, test_ID=185, label=9, output_node=35, voltage=0.00660956185311079\n    time_span=0.0001s, test_ID=185, label=9, output_node=36, voltage=0.011744024232029915\n    time_span=0.0001s, test_ID=185, label=9, output_node=37, voltage=0.008961155079305172\n    time_span=0.0001s, test_ID=185, label=9, output_node=38, voltage=0.005375497974455357\n    time_span=0.0001s, test_ID=185, label=9, output_node=39, voltage=-0.0011334661394357681\n    time_span=0.0001s, test_ID=185, label=9, output_node=40, voltage=0.0052041830494999886\n    time_span=0.0001s, test_ID=185, label=9, output_node=41, voltage=0.0010239045368507504\n    time_span=0.0001s, test_ID=185, label=9, output_node=42, voltage=0.008422311395406723\n    time_span=0.0001s, test_ID=185, label=9, output_node=43, voltage=0.006963147781789303\n    time_span=0.0001s, test_ID=185, label=9, output_node=44, voltage=0.0032111553009599447\n    time_span=0.0001s, test_ID=185, label=9, output_node=45, voltage=0.005848605651408434\n    time_span=0.0001s, test_ID=185, label=9, output_node=46, voltage=0.006186254788190126\n    time_span=0.0001s, test_ID=185, label=9, output_node=47, voltage=0.006218127440661192\n    time_span=0.0001s, test_ID=185, label=9, output_node=48, voltage=0.003386454191058874\n    time_span=0.0001s, test_ID=185, label=9, output_node=49, voltage=0.005513944197446108\n    time_span=0.0001s, test_ID=185, label=9, output_node=50, voltage=0.0013794820988550782\n    time_span=0.0001s, test_ID=185, label=9, output_node=51, voltage=0.005656374618411064\n    time_span=0.0001s, test_ID=185, label=9, output_node=52, voltage=0.007439243141561747\n    time_span=0.0001s, test_ID=185, label=9, output_node=53, voltage=0.0032898406498134136\n    time_span=0.0001s, test_ID=185, label=9, output_node=54, voltage=0.0010229083709418774\n    time_span=0.0001s, test_ID=185, label=9, output_node=55, voltage=0.004205179400742054\n    time_span=0.0001s, test_ID=185, label=9, output_node=56, voltage=0.006139442324638367\n    time_span=0.0001s, test_ID=185, label=9, output_node=57, voltage=0.006176294758915901\n    time_span=0.0001s, test_ID=185, label=9, output_node=58, voltage=0.003361554117873311\n    time_span=0.0001s, test_ID=185, label=9, output_node=59, voltage=0.007674303371459246\n    time_span=0.0001s, test_ID=185, label=9, output_node=60, voltage=0.004185258876532316\n    time_span=0.0001s, test_ID=185, label=9, output_node=61, voltage=-0.00035856571048498154\n    time_span=0.0001s, test_ID=185, label=9, output_node=62, voltage=0.003220119746401906\n    time_span=0.0001s, test_ID=185, label=9, output_node=63, voltage=-0.000520916364621371\n    time_span=0.0001s, test_ID=185, label=9, output_node=64, voltage=0.007066733203828335\n    time_span=0.0001s, test_ID=185, label=9, output_node=65, voltage=0.003921314608305693\n    time_span=0.0001s, test_ID=185, label=9, output_node=66, voltage=0.0023565739393234253\n    time_span=0.0001s, test_ID=185, label=9, output_node=67, voltage=0.002334661316126585\n    time_span=0.0001s, test_ID=185, label=9, output_node=68, voltage=0.0025926295202225447\n    time_span=0.0001s, test_ID=185, label=9, output_node=69, voltage=0.005058764945715666\n    time_span=0.0001s, test_ID=185, label=9, output_node=70, voltage=0.004303785040974617\n    time_span=0.0001s, test_ID=185, label=9, output_node=71, voltage=0.003948207478970289\n    time_span=0.0001s, test_ID=185, label=9, output_node=72, voltage=0.003101593814790249\n    time_span=0.0001s, test_ID=185, label=9, output_node=73, voltage=0.008443226106464863\n    time_span=0.0001s, test_ID=185, label=9, output_node=74, voltage=0.007809761445969343\n    time_span=0.0001s, test_ID=185, label=9, output_node=75, voltage=0.0009312749025411904\n    time_span=0.0001s, test_ID=185, label=9, output_node=76, voltage=0.005984063725918531\n    time_span=0.0001s, test_ID=185, label=9, output_node=77, voltage=-0.0005717130843549967\n    time_span=0.0001s, test_ID=185, label=9, output_node=78, voltage=0.004598605912178755\n    time_span=0.0001s, test_ID=185, label=9, output_node=79, voltage=0.008549800142645836\n    time_span=0.0001s, test_ID=185, label=9, output_node=80, voltage=0.004422310274094343\n    time_span=0.0001s, test_ID=185, label=9, output_node=81, voltage=0.0008306772797368467\n    time_span=0.0001s, test_ID=185, label=9, output_node=82, voltage=0.0015507967909798026\n    time_span=0.0001s, test_ID=185, label=9, output_node=83, voltage=0.0043456172570586205\n    time_span=0.0001s, test_ID=185, label=9, output_node=84, voltage=0.0013456175802275538\n    time_span=0.0001s, test_ID=185, label=9, output_node=85, voltage=0.010536853224039078\n    time_span=0.0001s, test_ID=185, label=9, output_node=86, voltage=0.004758963827043772\n    time_span=0.0001s, test_ID=185, label=9, output_node=87, voltage=0.006634462624788284\n    time_span=0.0001s, test_ID=185, label=9, output_node=88, voltage=0.002450199332088232\n    time_span=0.0001s, test_ID=185, label=9, output_node=89, voltage=0.006475099362432957\n    time_span=0.0001s, test_ID=185, label=9, output_node=90, voltage=0.003535856492817402\n    time_span=0.0001s, test_ID=185, label=9, output_node=91, voltage=0.007354581728577614\n    time_span=0.0001s, test_ID=185, label=9, output_node=92, voltage=0.005861553363502026\n    time_span=0.0001s, test_ID=185, label=9, output_node=93, voltage=0.00806573685258627\n    time_span=0.0001s, test_ID=185, label=9, output_node=94, voltage=0.006831673439592123\n    time_span=0.0001s, test_ID=185, label=9, output_node=95, voltage=0.00850996095687151\n    time_span=0.0001s, test_ID=185, label=9, output_node=96, voltage=0.004739043768495321\n    time_span=0.0001s, test_ID=185, label=9, output_node=97, voltage=0.0018386454321444035\n    time_span=0.0001s, test_ID=185, label=9, output_node=98, voltage=0.0059790839441120625\n    time_span=0.0001s, test_ID=185, label=9, output_node=99, voltage=0.006259960122406483\n    time_span=0.0001s, test_ID=185, label=9, output_node=sum, voltage=0.018223106861114502\n    Time consumed for 1 sample = 624.2364876270294 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '185'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=186, label=2, output_node=bkg, voltage=-0.004178286995738745\n    time_span=0.0001s, test_ID=186, label=2, output_node=0, voltage=0.010653385892510414\n    time_span=0.0001s, test_ID=186, label=2, output_node=1, voltage=0.004676294978708029\n    time_span=0.0001s, test_ID=186, label=2, output_node=2, voltage=0.015117529779672623\n    time_span=0.0001s, test_ID=186, label=2, output_node=3, voltage=0.010404382832348347\n    time_span=0.0001s, test_ID=186, label=2, output_node=4, voltage=0.01555677317082882\n    time_span=0.0001s, test_ID=186, label=2, output_node=5, voltage=0.01241533923894167\n    time_span=0.0001s, test_ID=186, label=2, output_node=6, voltage=0.013439242728054523\n    time_span=0.0001s, test_ID=186, label=2, output_node=7, voltage=0.005326693411916494\n    time_span=0.0001s, test_ID=186, label=2, output_node=8, voltage=0.010747010819613934\n    time_span=0.0001s, test_ID=186, label=2, output_node=9, voltage=0.013253984041512012\n    time_span=0.0001s, test_ID=186, label=2, output_node=10, voltage=0.007991036400198936\n    time_span=0.0001s, test_ID=186, label=2, output_node=11, voltage=0.00993227120488882\n    time_span=0.0001s, test_ID=186, label=2, output_node=12, voltage=0.012429283000528812\n    time_span=0.0001s, test_ID=186, label=2, output_node=13, voltage=0.012289841659367085\n    time_span=0.0001s, test_ID=186, label=2, output_node=14, voltage=0.011523904278874397\n    time_span=0.0001s, test_ID=186, label=2, output_node=15, voltage=0.011478087864816189\n    time_span=0.0001s, test_ID=186, label=2, output_node=16, voltage=0.010540836490690708\n    time_span=0.0001s, test_ID=186, label=2, output_node=17, voltage=0.009644422680139542\n    time_span=0.0001s, test_ID=186, label=2, output_node=18, voltage=0.00848904438316822\n    time_span=0.0001s, test_ID=186, label=2, output_node=19, voltage=0.0048177288845181465\n    time_span=0.0001s, test_ID=186, label=2, output_node=20, voltage=0.01715836673974991\n    time_span=0.0001s, test_ID=186, label=2, output_node=21, voltage=0.011050796136260033\n    time_span=0.0001s, test_ID=186, label=2, output_node=22, voltage=0.009383466094732285\n    time_span=0.0001s, test_ID=186, label=2, output_node=23, voltage=0.017313744872808456\n    time_span=0.0001s, test_ID=186, label=2, output_node=24, voltage=0.020846614614129066\n    time_span=0.0001s, test_ID=186, label=2, output_node=25, voltage=0.013541832566261292\n    time_span=0.0001s, test_ID=186, label=2, output_node=26, voltage=0.012501992285251617\n    time_span=0.0001s, test_ID=186, label=2, output_node=27, voltage=-5.776895341114141e-05\n    time_span=0.0001s, test_ID=186, label=2, output_node=28, voltage=0.010980079881846905\n    time_span=0.0001s, test_ID=186, label=2, output_node=29, voltage=0.011793824844062328\n    time_span=0.0001s, test_ID=186, label=2, output_node=30, voltage=0.006603585556149483\n    time_span=0.0001s, test_ID=186, label=2, output_node=31, voltage=0.011194223538041115\n    time_span=0.0001s, test_ID=186, label=2, output_node=32, voltage=0.01140438299626112\n    time_span=0.0001s, test_ID=186, label=2, output_node=33, voltage=0.007774900179356337\n    time_span=0.0001s, test_ID=186, label=2, output_node=34, voltage=0.010633466765284538\n    time_span=0.0001s, test_ID=186, label=2, output_node=35, voltage=0.004314740654081106\n    time_span=0.0001s, test_ID=186, label=2, output_node=36, voltage=0.008421314880251884\n    time_span=0.0001s, test_ID=186, label=2, output_node=37, voltage=0.0059272912330925465\n    time_span=0.0001s, test_ID=186, label=2, output_node=38, voltage=0.009919322095811367\n    time_span=0.0001s, test_ID=186, label=2, output_node=39, voltage=0.010348604992032051\n    time_span=0.0001s, test_ID=186, label=2, output_node=40, voltage=0.016774900257587433\n    time_span=0.0001s, test_ID=186, label=2, output_node=41, voltage=0.01106972061097622\n    time_span=0.0001s, test_ID=186, label=2, output_node=42, voltage=0.010610558092594147\n    time_span=0.0001s, test_ID=186, label=2, output_node=43, voltage=0.01493027899414301\n    time_span=0.0001s, test_ID=186, label=2, output_node=44, voltage=0.015371514484286308\n    time_span=0.0001s, test_ID=186, label=2, output_node=45, voltage=0.014346612617373466\n    time_span=0.0001s, test_ID=186, label=2, output_node=46, voltage=0.008222111500799656\n    time_span=0.0001s, test_ID=186, label=2, output_node=47, voltage=0.012005976401269436\n    time_span=0.0001s, test_ID=186, label=2, output_node=48, voltage=0.013102589175105095\n    time_span=0.0001s, test_ID=186, label=2, output_node=49, voltage=0.0065298802219331264\n    time_span=0.0001s, test_ID=186, label=2, output_node=50, voltage=0.012946214526891708\n    time_span=0.0001s, test_ID=186, label=2, output_node=51, voltage=0.008220119401812553\n    time_span=0.0001s, test_ID=186, label=2, output_node=52, voltage=0.01252091582864523\n    time_span=0.0001s, test_ID=186, label=2, output_node=53, voltage=0.011350597254931927\n    time_span=0.0001s, test_ID=186, label=2, output_node=54, voltage=0.014350597746670246\n    time_span=0.0001s, test_ID=186, label=2, output_node=55, voltage=0.012439243495464325\n    time_span=0.0001s, test_ID=186, label=2, output_node=56, voltage=0.00584761006757617\n    time_span=0.0001s, test_ID=186, label=2, output_node=57, voltage=0.006982070859521627\n    time_span=0.0001s, test_ID=186, label=2, output_node=58, voltage=0.015779880806803703\n    time_span=0.0001s, test_ID=186, label=2, output_node=59, voltage=0.009456174448132515\n    time_span=0.0001s, test_ID=186, label=2, output_node=60, voltage=0.0109073705971241\n    time_span=0.0001s, test_ID=186, label=2, output_node=61, voltage=0.012358564883470535\n    time_span=0.0001s, test_ID=186, label=2, output_node=62, voltage=0.011286851949989796\n    time_span=0.0001s, test_ID=186, label=2, output_node=63, voltage=0.01226992066949606\n    time_span=0.0001s, test_ID=186, label=2, output_node=64, voltage=0.002845617476850748\n    time_span=0.0001s, test_ID=186, label=2, output_node=65, voltage=0.009753984399139881\n    time_span=0.0001s, test_ID=186, label=2, output_node=66, voltage=0.009729083627462387\n    time_span=0.0001s, test_ID=186, label=2, output_node=67, voltage=0.007726095616817474\n    time_span=0.0001s, test_ID=186, label=2, output_node=68, voltage=0.012154382653534412\n    time_span=0.0001s, test_ID=186, label=2, output_node=69, voltage=0.012185257859528065\n    time_span=0.0001s, test_ID=186, label=2, output_node=70, voltage=0.009406374767422676\n    time_span=0.0001s, test_ID=186, label=2, output_node=71, voltage=0.014344622381031513\n    time_span=0.0001s, test_ID=186, label=2, output_node=72, voltage=0.010780875571072102\n    time_span=0.0001s, test_ID=186, label=2, output_node=73, voltage=0.006871514022350311\n    time_span=0.0001s, test_ID=186, label=2, output_node=74, voltage=0.007808764930814505\n    time_span=0.0001s, test_ID=186, label=2, output_node=75, voltage=0.015138445422053337\n    time_span=0.0001s, test_ID=186, label=2, output_node=76, voltage=0.007241035811603069\n    time_span=0.0001s, test_ID=186, label=2, output_node=77, voltage=0.013343625701963902\n    time_span=0.0001s, test_ID=186, label=2, output_node=78, voltage=0.011493027210235596\n    time_span=0.0001s, test_ID=186, label=2, output_node=79, voltage=0.007978088222444057\n    time_span=0.0001s, test_ID=186, label=2, output_node=80, voltage=0.006900398060679436\n    time_span=0.0001s, test_ID=186, label=2, output_node=81, voltage=0.011677291244268417\n    time_span=0.0001s, test_ID=186, label=2, output_node=82, voltage=0.012840637937188148\n    time_span=0.0001s, test_ID=186, label=2, output_node=83, voltage=0.008076692931354046\n    time_span=0.0001s, test_ID=186, label=2, output_node=84, voltage=0.007546812295913696\n    time_span=0.0001s, test_ID=186, label=2, output_node=85, voltage=0.009454184211790562\n    time_span=0.0001s, test_ID=186, label=2, output_node=86, voltage=0.0105348601937294\n    time_span=0.0001s, test_ID=186, label=2, output_node=87, voltage=0.00868725124746561\n    time_span=0.0001s, test_ID=186, label=2, output_node=88, voltage=0.01047908328473568\n    time_span=0.0001s, test_ID=186, label=2, output_node=89, voltage=0.009487051516771317\n    time_span=0.0001s, test_ID=186, label=2, output_node=90, voltage=0.012685257941484451\n    time_span=0.0001s, test_ID=186, label=2, output_node=91, voltage=0.01056772843003273\n    time_span=0.0001s, test_ID=186, label=2, output_node=92, voltage=0.005600597709417343\n    time_span=0.0001s, test_ID=186, label=2, output_node=93, voltage=0.009910358116030693\n    time_span=0.0001s, test_ID=186, label=2, output_node=94, voltage=0.0026603585574775934\n    time_span=0.0001s, test_ID=186, label=2, output_node=95, voltage=0.0034501992631703615\n    time_span=0.0001s, test_ID=186, label=2, output_node=96, voltage=0.005216136109083891\n    time_span=0.0001s, test_ID=186, label=2, output_node=97, voltage=0.012083666399121284\n    time_span=0.0001s, test_ID=186, label=2, output_node=98, voltage=0.010403386317193508\n    time_span=0.0001s, test_ID=186, label=2, output_node=99, voltage=0.006036852486431599\n    time_span=0.0001s, test_ID=186, label=2, output_node=sum, voltage=0.031762950122356415\n    Time consumed for 1 sample = 625.6967051029205 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '186'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=187, label=5, output_node=bkg, voltage=-0.0037499999161809683\n    time_span=0.0001s, test_ID=187, label=5, output_node=0, voltage=0.011499999091029167\n    time_span=0.0001s, test_ID=187, label=5, output_node=1, voltage=0.006857569795101881\n    time_span=0.0001s, test_ID=187, label=5, output_node=2, voltage=0.008406374603509903\n    time_span=0.0001s, test_ID=187, label=5, output_node=3, voltage=0.006681275088340044\n    time_span=0.0001s, test_ID=187, label=5, output_node=4, voltage=0.011984063312411308\n    time_span=0.0001s, test_ID=187, label=5, output_node=5, voltage=0.016377490013837814\n    time_span=0.0001s, test_ID=187, label=5, output_node=6, voltage=0.013311753049492836\n    time_span=0.0001s, test_ID=187, label=5, output_node=7, voltage=0.005210159346461296\n    time_span=0.0001s, test_ID=187, label=5, output_node=8, voltage=0.010043825022876263\n    time_span=0.0001s, test_ID=187, label=5, output_node=9, voltage=0.006938247010111809\n    time_span=0.0001s, test_ID=187, label=5, output_node=10, voltage=0.005579681601375341\n    time_span=0.0001s, test_ID=187, label=5, output_node=11, voltage=0.012824700213968754\n    time_span=0.0001s, test_ID=187, label=5, output_node=12, voltage=0.007621513679623604\n    time_span=0.0001s, test_ID=187, label=5, output_node=13, voltage=0.010338645428419113\n    time_span=0.0001s, test_ID=187, label=5, output_node=14, voltage=0.009243028238415718\n    time_span=0.0001s, test_ID=187, label=5, output_node=15, voltage=0.008514939807355404\n    time_span=0.0001s, test_ID=187, label=5, output_node=16, voltage=0.010211154818534851\n    time_span=0.0001s, test_ID=187, label=5, output_node=17, voltage=0.006590637378394604\n    time_span=0.0001s, test_ID=187, label=5, output_node=18, voltage=0.009722110815346241\n    time_span=0.0001s, test_ID=187, label=5, output_node=19, voltage=0.009804780595004559\n    time_span=0.0001s, test_ID=187, label=5, output_node=20, voltage=0.007716135121881962\n    time_span=0.0001s, test_ID=187, label=5, output_node=21, voltage=0.005579681601375341\n    time_span=0.0001s, test_ID=187, label=5, output_node=22, voltage=0.008218127302825451\n    time_span=0.0001s, test_ID=187, label=5, output_node=23, voltage=0.011892430484294891\n    time_span=0.0001s, test_ID=187, label=5, output_node=24, voltage=0.00992928259074688\n    time_span=0.0001s, test_ID=187, label=5, output_node=25, voltage=0.004963147919625044\n    time_span=0.0001s, test_ID=187, label=5, output_node=26, voltage=0.013181274756789207\n    time_span=0.0001s, test_ID=187, label=5, output_node=27, voltage=0.0057848612777888775\n    time_span=0.0001s, test_ID=187, label=5, output_node=28, voltage=0.006074700970202684\n    time_span=0.0001s, test_ID=187, label=5, output_node=29, voltage=0.008218128234148026\n    time_span=0.0001s, test_ID=187, label=5, output_node=30, voltage=0.00487749045714736\n    time_span=0.0001s, test_ID=187, label=5, output_node=31, voltage=0.005117530468851328\n    time_span=0.0001s, test_ID=187, label=5, output_node=32, voltage=0.008172310888767242\n    time_span=0.0001s, test_ID=187, label=5, output_node=33, voltage=0.00624402379617095\n    time_span=0.0001s, test_ID=187, label=5, output_node=34, voltage=0.006031872238963842\n    time_span=0.0001s, test_ID=187, label=5, output_node=35, voltage=0.010546812787652016\n    time_span=0.0001s, test_ID=187, label=5, output_node=36, voltage=0.004193227272480726\n    time_span=0.0001s, test_ID=187, label=5, output_node=37, voltage=0.004137449897825718\n    time_span=0.0001s, test_ID=187, label=5, output_node=38, voltage=0.012707171030342579\n    time_span=0.0001s, test_ID=187, label=5, output_node=39, voltage=0.010167330503463745\n    time_span=0.0001s, test_ID=187, label=5, output_node=40, voltage=0.007494024001061916\n    time_span=0.0001s, test_ID=187, label=5, output_node=41, voltage=0.005503984168171883\n    time_span=0.0001s, test_ID=187, label=5, output_node=42, voltage=0.0059531875886023045\n    time_span=0.0001s, test_ID=187, label=5, output_node=43, voltage=0.01007868442684412\n    time_span=0.0001s, test_ID=187, label=5, output_node=44, voltage=0.013484063558280468\n    time_span=0.0001s, test_ID=187, label=5, output_node=45, voltage=0.009536853060126305\n    time_span=0.0001s, test_ID=187, label=5, output_node=46, voltage=0.0047350600361824036\n    time_span=0.0001s, test_ID=187, label=5, output_node=47, voltage=0.00920916348695755\n    time_span=0.0001s, test_ID=187, label=5, output_node=48, voltage=0.011178286746144295\n    time_span=0.0001s, test_ID=187, label=5, output_node=49, voltage=0.0036703189834952354\n    time_span=0.0001s, test_ID=187, label=5, output_node=50, voltage=0.009622509591281414\n    time_span=0.0001s, test_ID=187, label=5, output_node=51, voltage=0.010682270862162113\n    time_span=0.0001s, test_ID=187, label=5, output_node=52, voltage=0.007352589629590511\n    time_span=0.0001s, test_ID=187, label=5, output_node=53, voltage=0.015169323422014713\n    time_span=0.0001s, test_ID=187, label=5, output_node=54, voltage=0.014105577021837234\n    time_span=0.0001s, test_ID=187, label=5, output_node=55, voltage=0.015007968991994858\n    time_span=0.0001s, test_ID=187, label=5, output_node=56, voltage=0.007465139962732792\n    time_span=0.0001s, test_ID=187, label=5, output_node=57, voltage=0.014273904263973236\n    time_span=0.0001s, test_ID=187, label=5, output_node=58, voltage=0.008786852471530437\n    time_span=0.0001s, test_ID=187, label=5, output_node=59, voltage=0.00717529933899641\n    time_span=0.0001s, test_ID=187, label=5, output_node=60, voltage=0.007257968187332153\n    time_span=0.0001s, test_ID=187, label=5, output_node=61, voltage=0.013661354780197144\n    time_span=0.0001s, test_ID=187, label=5, output_node=62, voltage=0.010839641094207764\n    time_span=0.0001s, test_ID=187, label=5, output_node=63, voltage=0.011316732503473759\n    time_span=0.0001s, test_ID=187, label=5, output_node=64, voltage=0.009302789345383644\n    time_span=0.0001s, test_ID=187, label=5, output_node=65, voltage=0.006962151266634464\n    time_span=0.0001s, test_ID=187, label=5, output_node=66, voltage=0.007845617830753326\n    time_span=0.0001s, test_ID=187, label=5, output_node=67, voltage=0.005836653523147106\n    time_span=0.0001s, test_ID=187, label=5, output_node=68, voltage=0.004142430145293474\n    time_span=0.0001s, test_ID=187, label=5, output_node=69, voltage=0.01357968244701624\n    time_span=0.0001s, test_ID=187, label=5, output_node=70, voltage=0.015957171097397804\n    time_span=0.0001s, test_ID=187, label=5, output_node=71, voltage=0.0176912359893322\n    time_span=0.0001s, test_ID=187, label=5, output_node=72, voltage=0.014183267019689083\n    time_span=0.0001s, test_ID=187, label=5, output_node=73, voltage=0.009895417839288712\n    time_span=0.0001s, test_ID=187, label=5, output_node=74, voltage=0.006045816466212273\n    time_span=0.0001s, test_ID=187, label=5, output_node=75, voltage=0.0025368526112288237\n    time_span=0.0001s, test_ID=187, label=5, output_node=76, voltage=0.0055318730883300304\n    time_span=0.0001s, test_ID=187, label=5, output_node=77, voltage=0.013803784735500813\n    time_span=0.0001s, test_ID=187, label=5, output_node=78, voltage=0.005705179646611214\n    time_span=0.0001s, test_ID=187, label=5, output_node=79, voltage=0.008013945072889328\n    time_span=0.0001s, test_ID=187, label=5, output_node=80, voltage=0.010517927818000317\n    time_span=0.0001s, test_ID=187, label=5, output_node=81, voltage=0.014530875720083714\n    time_span=0.0001s, test_ID=187, label=5, output_node=82, voltage=0.012886454351246357\n    time_span=0.0001s, test_ID=187, label=5, output_node=83, voltage=0.009193227626383305\n    time_span=0.0001s, test_ID=187, label=5, output_node=84, voltage=0.007761952001601458\n    time_span=0.0001s, test_ID=187, label=5, output_node=85, voltage=0.010339641943573952\n    time_span=0.0001s, test_ID=187, label=5, output_node=86, voltage=0.0062629482708871365\n    time_span=0.0001s, test_ID=187, label=5, output_node=87, voltage=0.009642429649829865\n    time_span=0.0001s, test_ID=187, label=5, output_node=88, voltage=0.008747011423110962\n    time_span=0.0001s, test_ID=187, label=5, output_node=89, voltage=0.011706175282597542\n    time_span=0.0001s, test_ID=187, label=5, output_node=90, voltage=0.006050796713680029\n    time_span=0.0001s, test_ID=187, label=5, output_node=91, voltage=0.009546812623739243\n    time_span=0.0001s, test_ID=187, label=5, output_node=92, voltage=0.004096613265573978\n    time_span=0.0001s, test_ID=187, label=5, output_node=93, voltage=0.005067729391157627\n    time_span=0.0001s, test_ID=187, label=5, output_node=94, voltage=0.004039840307086706\n    time_span=0.0001s, test_ID=187, label=5, output_node=95, voltage=0.005199202802032232\n    time_span=0.0001s, test_ID=187, label=5, output_node=96, voltage=0.009623507037758827\n    time_span=0.0001s, test_ID=187, label=5, output_node=97, voltage=0.0038665339816361666\n    time_span=0.0001s, test_ID=187, label=5, output_node=98, voltage=0.008905378170311451\n    time_span=0.0001s, test_ID=187, label=5, output_node=99, voltage=0.008895417675375938\n    time_span=0.0001s, test_ID=187, label=5, output_node=sum, voltage=0.02326095663011074\n    Time consumed for 1 sample = 625.6111996173859 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '187'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=188, label=0, output_node=bkg, voltage=-0.0027848605532199144\n    time_span=0.0001s, test_ID=188, label=0, output_node=0, voltage=0.01024003978818655\n    time_span=0.0001s, test_ID=188, label=0, output_node=1, voltage=0.013449203222990036\n    time_span=0.0001s, test_ID=188, label=0, output_node=2, voltage=0.009738048538565636\n    time_span=0.0001s, test_ID=188, label=0, output_node=3, voltage=0.0064890431240201\n    time_span=0.0001s, test_ID=188, label=0, output_node=4, voltage=0.013107569888234138\n    time_span=0.0001s, test_ID=188, label=0, output_node=5, voltage=0.01142430305480957\n    time_span=0.0001s, test_ID=188, label=0, output_node=6, voltage=0.008928286843001842\n    time_span=0.0001s, test_ID=188, label=0, output_node=7, voltage=0.01250398438423872\n    time_span=0.0001s, test_ID=188, label=0, output_node=8, voltage=0.006567729637026787\n    time_span=0.0001s, test_ID=188, label=0, output_node=9, voltage=0.013539840467274189\n    time_span=0.0001s, test_ID=188, label=0, output_node=10, voltage=0.007713147439062595\n    time_span=0.0001s, test_ID=188, label=0, output_node=11, voltage=0.009952192194759846\n    time_span=0.0001s, test_ID=188, label=0, output_node=12, voltage=0.005732072051614523\n    time_span=0.0001s, test_ID=188, label=0, output_node=13, voltage=0.012079681269824505\n    time_span=0.0001s, test_ID=188, label=0, output_node=14, voltage=0.007159362081438303\n    time_span=0.0001s, test_ID=188, label=0, output_node=15, voltage=0.009595618583261967\n    time_span=0.0001s, test_ID=188, label=0, output_node=16, voltage=0.009537848643958569\n    time_span=0.0001s, test_ID=188, label=0, output_node=17, voltage=0.012981075793504715\n    time_span=0.0001s, test_ID=188, label=0, output_node=18, voltage=0.009494023397564888\n    time_span=0.0001s, test_ID=188, label=0, output_node=19, voltage=0.002254979917779565\n    time_span=0.0001s, test_ID=188, label=0, output_node=20, voltage=0.011693227104842663\n    time_span=0.0001s, test_ID=188, label=0, output_node=21, voltage=0.007652390282601118\n    time_span=0.0001s, test_ID=188, label=0, output_node=22, voltage=0.005088645499199629\n    time_span=0.0001s, test_ID=188, label=0, output_node=23, voltage=0.013122511096298695\n    time_span=0.0001s, test_ID=188, label=0, output_node=24, voltage=0.012197211384773254\n    time_span=0.0001s, test_ID=188, label=0, output_node=25, voltage=0.016991036012768745\n    time_span=0.0001s, test_ID=188, label=0, output_node=26, voltage=0.009936254471540451\n    time_span=0.0001s, test_ID=188, label=0, output_node=27, voltage=0.004578685387969017\n    time_span=0.0001s, test_ID=188, label=0, output_node=28, voltage=0.006836653687059879\n    time_span=0.0001s, test_ID=188, label=0, output_node=29, voltage=0.0052609555423259735\n    time_span=0.0001s, test_ID=188, label=0, output_node=30, voltage=0.013435259461402893\n    time_span=0.0001s, test_ID=188, label=0, output_node=31, voltage=0.007374502252787352\n    time_span=0.0001s, test_ID=188, label=0, output_node=32, voltage=0.013899402692914009\n    time_span=0.0001s, test_ID=188, label=0, output_node=33, voltage=0.0031872508116066456\n    time_span=0.0001s, test_ID=188, label=0, output_node=34, voltage=0.00983565766364336\n    time_span=0.0001s, test_ID=188, label=0, output_node=35, voltage=0.006512948777526617\n    time_span=0.0001s, test_ID=188, label=0, output_node=36, voltage=0.007692230865359306\n    time_span=0.0001s, test_ID=188, label=0, output_node=37, voltage=0.00495219137519598\n    time_span=0.0001s, test_ID=188, label=0, output_node=38, voltage=0.010209163650870323\n    time_span=0.0001s, test_ID=188, label=0, output_node=39, voltage=0.014639442786574364\n    time_span=0.0001s, test_ID=188, label=0, output_node=40, voltage=0.01487749069929123\n    time_span=0.0001s, test_ID=188, label=0, output_node=41, voltage=0.009442230686545372\n    time_span=0.0001s, test_ID=188, label=0, output_node=42, voltage=0.009299800731241703\n    time_span=0.0001s, test_ID=188, label=0, output_node=43, voltage=0.010698207654058933\n    time_span=0.0001s, test_ID=188, label=0, output_node=44, voltage=0.005643426440656185\n    time_span=0.0001s, test_ID=188, label=0, output_node=45, voltage=0.01858067885041237\n    time_span=0.0001s, test_ID=188, label=0, output_node=46, voltage=0.01375298760831356\n    time_span=0.0001s, test_ID=188, label=0, output_node=47, voltage=0.010388446971774101\n    time_span=0.0001s, test_ID=188, label=0, output_node=48, voltage=0.011204184032976627\n    time_span=0.0001s, test_ID=188, label=0, output_node=49, voltage=0.00369621510617435\n    time_span=0.0001s, test_ID=188, label=0, output_node=50, voltage=0.007094621658325195\n    time_span=0.0001s, test_ID=188, label=0, output_node=51, voltage=0.009078685194253922\n    time_span=0.0001s, test_ID=188, label=0, output_node=52, voltage=0.010391434654593468\n    time_span=0.0001s, test_ID=188, label=0, output_node=53, voltage=0.011445220559835434\n    time_span=0.0001s, test_ID=188, label=0, output_node=54, voltage=0.006184263154864311\n    time_span=0.0001s, test_ID=188, label=0, output_node=55, voltage=0.009648406878113747\n    time_span=0.0001s, test_ID=188, label=0, output_node=56, voltage=0.005651394370943308\n    time_span=0.0001s, test_ID=188, label=0, output_node=57, voltage=0.008095617406070232\n    time_span=0.0001s, test_ID=188, label=0, output_node=58, voltage=0.007812748663127422\n    time_span=0.0001s, test_ID=188, label=0, output_node=59, voltage=0.006769920699298382\n    time_span=0.0001s, test_ID=188, label=0, output_node=60, voltage=0.014025895856320858\n    time_span=0.0001s, test_ID=188, label=0, output_node=61, voltage=0.006016931962221861\n    time_span=0.0001s, test_ID=188, label=0, output_node=62, voltage=0.0082958173006773\n    time_span=0.0001s, test_ID=188, label=0, output_node=63, voltage=0.014820718206465244\n    time_span=0.0001s, test_ID=188, label=0, output_node=64, voltage=0.007249999791383743\n    time_span=0.0001s, test_ID=188, label=0, output_node=65, voltage=0.0074571711011230946\n    time_span=0.0001s, test_ID=188, label=0, output_node=66, voltage=0.0023276894353330135\n    time_span=0.0001s, test_ID=188, label=0, output_node=67, voltage=0.007805777247995138\n    time_span=0.0001s, test_ID=188, label=0, output_node=68, voltage=0.015433266758918762\n    time_span=0.0001s, test_ID=188, label=0, output_node=69, voltage=0.007463147398084402\n    time_span=0.0001s, test_ID=188, label=0, output_node=70, voltage=0.015697211027145386\n    time_span=0.0001s, test_ID=188, label=0, output_node=71, voltage=0.012086653150618076\n    time_span=0.0001s, test_ID=188, label=0, output_node=72, voltage=0.010250000283122063\n    time_span=0.0001s, test_ID=188, label=0, output_node=73, voltage=0.006768924184143543\n    time_span=0.0001s, test_ID=188, label=0, output_node=74, voltage=0.006624502129852772\n    time_span=0.0001s, test_ID=188, label=0, output_node=75, voltage=0.00935856532305479\n    time_span=0.0001s, test_ID=188, label=0, output_node=76, voltage=0.0031543823424726725\n    time_span=0.0001s, test_ID=188, label=0, output_node=77, voltage=0.004839641507714987\n    time_span=0.0001s, test_ID=188, label=0, output_node=78, voltage=0.008709163405001163\n    time_span=0.0001s, test_ID=188, label=0, output_node=79, voltage=0.0162589643150568\n    time_span=0.0001s, test_ID=188, label=0, output_node=80, voltage=0.011296812444925308\n    time_span=0.0001s, test_ID=188, label=0, output_node=81, voltage=0.011972111649811268\n    time_span=0.0001s, test_ID=188, label=0, output_node=82, voltage=0.010688248090445995\n    time_span=0.0001s, test_ID=188, label=0, output_node=83, voltage=0.012420319020748138\n    time_span=0.0001s, test_ID=188, label=0, output_node=84, voltage=0.011039840057492256\n    time_span=0.0001s, test_ID=188, label=0, output_node=85, voltage=0.007725099567323923\n    time_span=0.0001s, test_ID=188, label=0, output_node=86, voltage=0.004518924281001091\n    time_span=0.0001s, test_ID=188, label=0, output_node=87, voltage=0.012236055918037891\n    time_span=0.0001s, test_ID=188, label=0, output_node=88, voltage=0.009915339760482311\n    time_span=0.0001s, test_ID=188, label=0, output_node=89, voltage=0.01649402268230915\n    time_span=0.0001s, test_ID=188, label=0, output_node=90, voltage=0.008542828261852264\n    time_span=0.0001s, test_ID=188, label=0, output_node=91, voltage=0.011884461157023907\n    time_span=0.0001s, test_ID=188, label=0, output_node=92, voltage=0.009673306718468666\n    time_span=0.0001s, test_ID=188, label=0, output_node=93, voltage=0.0158067736774683\n    time_span=0.0001s, test_ID=188, label=0, output_node=94, voltage=0.010112550109624863\n    time_span=0.0001s, test_ID=188, label=0, output_node=95, voltage=0.009070717729628086\n    time_span=0.0001s, test_ID=188, label=0, output_node=96, voltage=0.010529881343245506\n    time_span=0.0001s, test_ID=188, label=0, output_node=97, voltage=0.012800795957446098\n    time_span=0.0001s, test_ID=188, label=0, output_node=98, voltage=0.005930278450250626\n    time_span=0.0001s, test_ID=188, label=0, output_node=99, voltage=0.012204183265566826\n    time_span=0.0001s, test_ID=188, label=0, output_node=sum, voltage=0.029530879110097885\n    Time consumed for 1 sample = 625.2047350406647 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '188'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=189, label=1, output_node=bkg, voltage=-0.005440238863229752\n    time_span=0.0001s, test_ID=189, label=1, output_node=0, voltage=0.01866832748055458\n    time_span=0.0001s, test_ID=189, label=1, output_node=1, voltage=0.012000995688140392\n    time_span=0.0001s, test_ID=189, label=1, output_node=2, voltage=0.012400397099554539\n    time_span=0.0001s, test_ID=189, label=1, output_node=3, voltage=0.01046713162213564\n    time_span=0.0001s, test_ID=189, label=1, output_node=4, voltage=0.01464243046939373\n    time_span=0.0001s, test_ID=189, label=1, output_node=5, voltage=0.014455179683864117\n    time_span=0.0001s, test_ID=189, label=1, output_node=6, voltage=0.015451195649802685\n    time_span=0.0001s, test_ID=189, label=1, output_node=7, voltage=0.00933864526450634\n    time_span=0.0001s, test_ID=189, label=1, output_node=8, voltage=0.01429183129221201\n    time_span=0.0001s, test_ID=189, label=1, output_node=9, voltage=0.013955178670585155\n    time_span=0.0001s, test_ID=189, label=1, output_node=10, voltage=0.007975099608302116\n    time_span=0.0001s, test_ID=189, label=1, output_node=11, voltage=0.019637450575828552\n    time_span=0.0001s, test_ID=189, label=1, output_node=12, voltage=0.012296812608838081\n    time_span=0.0001s, test_ID=189, label=1, output_node=13, voltage=0.007708167657256126\n    time_span=0.0001s, test_ID=189, label=1, output_node=14, voltage=0.011018924415111542\n    time_span=0.0001s, test_ID=189, label=1, output_node=15, voltage=0.011531872674822807\n    time_span=0.0001s, test_ID=189, label=1, output_node=16, voltage=0.01824004016816616\n    time_span=0.0001s, test_ID=189, label=1, output_node=17, voltage=0.015149403363466263\n    time_span=0.0001s, test_ID=189, label=1, output_node=18, voltage=0.01468326710164547\n    time_span=0.0001s, test_ID=189, label=1, output_node=19, voltage=0.00951195228844881\n    time_span=0.0001s, test_ID=189, label=1, output_node=20, voltage=0.011135458014905453\n    time_span=0.0001s, test_ID=189, label=1, output_node=21, voltage=0.010720119811594486\n    time_span=0.0001s, test_ID=189, label=1, output_node=22, voltage=0.011125498451292515\n    time_span=0.0001s, test_ID=189, label=1, output_node=23, voltage=0.013895418494939804\n    time_span=0.0001s, test_ID=189, label=1, output_node=24, voltage=0.01437151338905096\n    time_span=0.0001s, test_ID=189, label=1, output_node=25, voltage=0.01102490071207285\n    time_span=0.0001s, test_ID=189, label=1, output_node=26, voltage=0.012607569806277752\n    time_span=0.0001s, test_ID=189, label=1, output_node=27, voltage=0.01273406483232975\n    time_span=0.0001s, test_ID=189, label=1, output_node=28, voltage=0.01909860409796238\n    time_span=0.0001s, test_ID=189, label=1, output_node=29, voltage=0.008859561756253242\n    time_span=0.0001s, test_ID=189, label=1, output_node=30, voltage=0.011997012421488762\n    time_span=0.0001s, test_ID=189, label=1, output_node=31, voltage=0.01145318802446127\n    time_span=0.0001s, test_ID=189, label=1, output_node=32, voltage=0.012020916678011417\n    time_span=0.0001s, test_ID=189, label=1, output_node=33, voltage=0.019570717588067055\n    time_span=0.0001s, test_ID=189, label=1, output_node=34, voltage=0.01828984171152115\n    time_span=0.0001s, test_ID=189, label=1, output_node=35, voltage=0.012103586457669735\n    time_span=0.0001s, test_ID=189, label=1, output_node=36, voltage=0.015503983944654465\n    time_span=0.0001s, test_ID=189, label=1, output_node=37, voltage=0.009766931645572186\n    time_span=0.0001s, test_ID=189, label=1, output_node=38, voltage=0.01226494088768959\n    time_span=0.0001s, test_ID=189, label=1, output_node=39, voltage=0.017167331650853157\n    time_span=0.0001s, test_ID=189, label=1, output_node=40, voltage=0.008232071064412594\n    time_span=0.0001s, test_ID=189, label=1, output_node=41, voltage=0.014740039594471455\n    time_span=0.0001s, test_ID=189, label=1, output_node=42, voltage=0.014414343051612377\n    time_span=0.0001s, test_ID=189, label=1, output_node=43, voltage=0.01571115478873253\n    time_span=0.0001s, test_ID=189, label=1, output_node=44, voltage=0.009501992724835873\n    time_span=0.0001s, test_ID=189, label=1, output_node=45, voltage=0.016562748700380325\n    time_span=0.0001s, test_ID=189, label=1, output_node=46, voltage=0.00679980032145977\n    time_span=0.0001s, test_ID=189, label=1, output_node=47, voltage=0.012387450784444809\n    time_span=0.0001s, test_ID=189, label=1, output_node=48, voltage=0.015341633930802345\n    time_span=0.0001s, test_ID=189, label=1, output_node=49, voltage=0.01153784804046154\n    time_span=0.0001s, test_ID=189, label=1, output_node=50, voltage=0.01598505862057209\n    time_span=0.0001s, test_ID=189, label=1, output_node=51, voltage=0.018561754375696182\n    time_span=0.0001s, test_ID=189, label=1, output_node=52, voltage=0.010104581713676453\n    time_span=0.0001s, test_ID=189, label=1, output_node=53, voltage=0.00916832685470581\n    time_span=0.0001s, test_ID=189, label=1, output_node=54, voltage=0.011804780922830105\n    time_span=0.0001s, test_ID=189, label=1, output_node=55, voltage=0.009434263221919537\n    time_span=0.0001s, test_ID=189, label=1, output_node=56, voltage=0.01319920178502798\n    time_span=0.0001s, test_ID=189, label=1, output_node=57, voltage=0.012852589599788189\n    time_span=0.0001s, test_ID=189, label=1, output_node=58, voltage=0.013991035521030426\n    time_span=0.0001s, test_ID=189, label=1, output_node=59, voltage=0.01402489934116602\n    time_span=0.0001s, test_ID=189, label=1, output_node=60, voltage=0.012327688746154308\n    time_span=0.0001s, test_ID=189, label=1, output_node=61, voltage=0.009397409856319427\n    time_span=0.0001s, test_ID=189, label=1, output_node=62, voltage=0.01889442279934883\n    time_span=0.0001s, test_ID=189, label=1, output_node=63, voltage=0.010566731914877892\n    time_span=0.0001s, test_ID=189, label=1, output_node=64, voltage=0.013521912507712841\n    time_span=0.0001s, test_ID=189, label=1, output_node=65, voltage=0.01325199194252491\n    time_span=0.0001s, test_ID=189, label=1, output_node=66, voltage=0.016504980623722076\n    time_span=0.0001s, test_ID=189, label=1, output_node=67, voltage=0.012616533786058426\n    time_span=0.0001s, test_ID=189, label=1, output_node=68, voltage=0.010214142501354218\n    time_span=0.0001s, test_ID=189, label=1, output_node=69, voltage=0.009594621136784554\n    time_span=0.0001s, test_ID=189, label=1, output_node=70, voltage=0.013741035014390945\n    time_span=0.0001s, test_ID=189, label=1, output_node=71, voltage=0.014077689498662949\n    time_span=0.0001s, test_ID=189, label=1, output_node=72, voltage=0.011618525721132755\n    time_span=0.0001s, test_ID=189, label=1, output_node=73, voltage=0.01018326822668314\n    time_span=0.0001s, test_ID=189, label=1, output_node=74, voltage=0.013002987951040268\n    time_span=0.0001s, test_ID=189, label=1, output_node=75, voltage=0.010188247077167034\n    time_span=0.0001s, test_ID=189, label=1, output_node=76, voltage=0.00975896418094635\n    time_span=0.0001s, test_ID=189, label=1, output_node=77, voltage=0.015282869338989258\n    time_span=0.0001s, test_ID=189, label=1, output_node=78, voltage=0.01881573721766472\n    time_span=0.0001s, test_ID=189, label=1, output_node=79, voltage=0.008784860372543335\n    time_span=0.0001s, test_ID=189, label=1, output_node=80, voltage=0.01572609692811966\n    time_span=0.0001s, test_ID=189, label=1, output_node=81, voltage=0.013921314850449562\n    time_span=0.0001s, test_ID=189, label=1, output_node=82, voltage=0.006035856436938047\n    time_span=0.0001s, test_ID=189, label=1, output_node=83, voltage=0.011743028648197651\n    time_span=0.0001s, test_ID=189, label=1, output_node=84, voltage=0.016577690839767456\n    time_span=0.0001s, test_ID=189, label=1, output_node=85, voltage=0.010044820606708527\n    time_span=0.0001s, test_ID=189, label=1, output_node=86, voltage=0.011310757137835026\n    time_span=0.0001s, test_ID=189, label=1, output_node=87, voltage=0.009724103845655918\n    time_span=0.0001s, test_ID=189, label=1, output_node=88, voltage=0.014281871728599072\n    time_span=0.0001s, test_ID=189, label=1, output_node=89, voltage=0.00965737085789442\n    time_span=0.0001s, test_ID=189, label=1, output_node=90, voltage=0.011701194569468498\n    time_span=0.0001s, test_ID=189, label=1, output_node=91, voltage=0.01508764922618866\n    time_span=0.0001s, test_ID=189, label=1, output_node=92, voltage=0.012094622477889061\n    time_span=0.0001s, test_ID=189, label=1, output_node=93, voltage=0.013840637169778347\n    time_span=0.0001s, test_ID=189, label=1, output_node=94, voltage=0.013580677099525928\n    time_span=0.0001s, test_ID=189, label=1, output_node=95, voltage=0.014248007908463478\n    time_span=0.0001s, test_ID=189, label=1, output_node=96, voltage=0.012653387151658535\n    time_span=0.0001s, test_ID=189, label=1, output_node=97, voltage=0.008355577476322651\n    time_span=0.0001s, test_ID=189, label=1, output_node=98, voltage=0.013808765448629856\n    time_span=0.0001s, test_ID=189, label=1, output_node=99, voltage=0.008474103175103664\n    time_span=0.0001s, test_ID=189, label=1, output_node=sum, voltage=0.03699402138590813\n    Time consumed for 1 sample = 624.9476170539856 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '189'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=190, label=1, output_node=bkg, voltage=-0.005422310903668404\n    time_span=0.0001s, test_ID=190, label=1, output_node=0, voltage=0.018341634422540665\n    time_span=0.0001s, test_ID=190, label=1, output_node=1, voltage=0.010230079293251038\n    time_span=0.0001s, test_ID=190, label=1, output_node=2, voltage=0.020368525758385658\n    time_span=0.0001s, test_ID=190, label=1, output_node=3, voltage=0.0070318724028766155\n    time_span=0.0001s, test_ID=190, label=1, output_node=4, voltage=0.01902390457689762\n    time_span=0.0001s, test_ID=190, label=1, output_node=5, voltage=0.01530976127833128\n    time_span=0.0001s, test_ID=190, label=1, output_node=6, voltage=0.02017330564558506\n    time_span=0.0001s, test_ID=190, label=1, output_node=7, voltage=0.008855577558279037\n    time_span=0.0001s, test_ID=190, label=1, output_node=8, voltage=0.016269918531179428\n    time_span=0.0001s, test_ID=190, label=1, output_node=9, voltage=0.013602589257061481\n    time_span=0.0001s, test_ID=190, label=1, output_node=10, voltage=0.013408366590738297\n    time_span=0.0001s, test_ID=190, label=1, output_node=11, voltage=0.012363545596599579\n    time_span=0.0001s, test_ID=190, label=1, output_node=12, voltage=0.017090637236833572\n    time_span=0.0001s, test_ID=190, label=1, output_node=13, voltage=0.01579083688557148\n    time_span=0.0001s, test_ID=190, label=1, output_node=14, voltage=0.01630876585841179\n    time_span=0.0001s, test_ID=190, label=1, output_node=15, voltage=0.012485060840845108\n    time_span=0.0001s, test_ID=190, label=1, output_node=16, voltage=0.016391435638070107\n    time_span=0.0001s, test_ID=190, label=1, output_node=17, voltage=0.014796813018620014\n    time_span=0.0001s, test_ID=190, label=1, output_node=18, voltage=0.012263944372534752\n    time_span=0.0001s, test_ID=190, label=1, output_node=19, voltage=0.014192230999469757\n    time_span=0.0001s, test_ID=190, label=1, output_node=20, voltage=0.019967133179306984\n    time_span=0.0001s, test_ID=190, label=1, output_node=21, voltage=0.009404381737112999\n    time_span=0.0001s, test_ID=190, label=1, output_node=22, voltage=0.01123107597231865\n    time_span=0.0001s, test_ID=190, label=1, output_node=23, voltage=0.013306772336363792\n    time_span=0.0001s, test_ID=190, label=1, output_node=24, voltage=0.014434262178838253\n    time_span=0.0001s, test_ID=190, label=1, output_node=25, voltage=0.012644423171877861\n    time_span=0.0001s, test_ID=190, label=1, output_node=26, voltage=0.013674302957952023\n    time_span=0.0001s, test_ID=190, label=1, output_node=27, voltage=0.013200199231505394\n    time_span=0.0001s, test_ID=190, label=1, output_node=28, voltage=0.022004980593919754\n    time_span=0.0001s, test_ID=190, label=1, output_node=29, voltage=0.014754979871213436\n    time_span=0.0001s, test_ID=190, label=1, output_node=30, voltage=0.016118526458740234\n    time_span=0.0001s, test_ID=190, label=1, output_node=31, voltage=0.01665736921131611\n    time_span=0.0001s, test_ID=190, label=1, output_node=32, voltage=0.014997011050581932\n    time_span=0.0001s, test_ID=190, label=1, output_node=33, voltage=0.018211156129837036\n    time_span=0.0001s, test_ID=190, label=1, output_node=34, voltage=0.014466135762631893\n    time_span=0.0001s, test_ID=190, label=1, output_node=35, voltage=0.015018925070762634\n    time_span=0.0001s, test_ID=190, label=1, output_node=36, voltage=0.017340637743473053\n    time_span=0.0001s, test_ID=190, label=1, output_node=37, voltage=0.014613544568419456\n    time_span=0.0001s, test_ID=190, label=1, output_node=38, voltage=0.009871515445411205\n    time_span=0.0001s, test_ID=190, label=1, output_node=39, voltage=0.016224103048443794\n    time_span=0.0001s, test_ID=190, label=1, output_node=40, voltage=0.013413346372544765\n    time_span=0.0001s, test_ID=190, label=1, output_node=41, voltage=0.014818725176155567\n    time_span=0.0001s, test_ID=190, label=1, output_node=42, voltage=0.01288446132093668\n    time_span=0.0001s, test_ID=190, label=1, output_node=43, voltage=0.01681872271001339\n    time_span=0.0001s, test_ID=190, label=1, output_node=44, voltage=0.016409361734986305\n    time_span=0.0001s, test_ID=190, label=1, output_node=45, voltage=0.016374502331018448\n    time_span=0.0001s, test_ID=190, label=1, output_node=46, voltage=0.01300896517932415\n    time_span=0.0001s, test_ID=190, label=1, output_node=47, voltage=0.006099601276218891\n    time_span=0.0001s, test_ID=190, label=1, output_node=48, voltage=0.01219223067164421\n    time_span=0.0001s, test_ID=190, label=1, output_node=49, voltage=0.014224103651940823\n    time_span=0.0001s, test_ID=190, label=1, output_node=50, voltage=0.02020617574453354\n    time_span=0.0001s, test_ID=190, label=1, output_node=51, voltage=0.012883465737104416\n    time_span=0.0001s, test_ID=190, label=1, output_node=52, voltage=0.015199203044176102\n    time_span=0.0001s, test_ID=190, label=1, output_node=53, voltage=0.01115836575627327\n    time_span=0.0001s, test_ID=190, label=1, output_node=54, voltage=0.015421314164996147\n    time_span=0.0001s, test_ID=190, label=1, output_node=55, voltage=0.01838545687496662\n    time_span=0.0001s, test_ID=190, label=1, output_node=56, voltage=0.011297808960080147\n    time_span=0.0001s, test_ID=190, label=1, output_node=57, voltage=0.013281871564686298\n    time_span=0.0001s, test_ID=190, label=1, output_node=58, voltage=0.013721114955842495\n    time_span=0.0001s, test_ID=190, label=1, output_node=59, voltage=0.017470119521021843\n    time_span=0.0001s, test_ID=190, label=1, output_node=60, voltage=0.010749999433755875\n    time_span=0.0001s, test_ID=190, label=1, output_node=61, voltage=0.01332868542522192\n    time_span=0.0001s, test_ID=190, label=1, output_node=62, voltage=0.01371314749121666\n    time_span=0.0001s, test_ID=190, label=1, output_node=63, voltage=0.008900398388504982\n    time_span=0.0001s, test_ID=190, label=1, output_node=64, voltage=0.01590537838637829\n    time_span=0.0001s, test_ID=190, label=1, output_node=65, voltage=0.016120517626404762\n    time_span=0.0001s, test_ID=190, label=1, output_node=66, voltage=0.010630478151142597\n    time_span=0.0001s, test_ID=190, label=1, output_node=67, voltage=0.010985059663653374\n    time_span=0.0001s, test_ID=190, label=1, output_node=68, voltage=0.01408864464610815\n    time_span=0.0001s, test_ID=190, label=1, output_node=69, voltage=0.015225098468363285\n    time_span=0.0001s, test_ID=190, label=1, output_node=70, voltage=0.011053784750401974\n    time_span=0.0001s, test_ID=190, label=1, output_node=71, voltage=0.011332669295370579\n    time_span=0.0001s, test_ID=190, label=1, output_node=72, voltage=0.0161304771900177\n    time_span=0.0001s, test_ID=190, label=1, output_node=73, voltage=0.01560159306973219\n    time_span=0.0001s, test_ID=190, label=1, output_node=74, voltage=0.017252987250685692\n    time_span=0.0001s, test_ID=190, label=1, output_node=75, voltage=0.015809759497642517\n    time_span=0.0001s, test_ID=190, label=1, output_node=76, voltage=0.006562748923897743\n    time_span=0.0001s, test_ID=190, label=1, output_node=77, voltage=0.014635458588600159\n    time_span=0.0001s, test_ID=190, label=1, output_node=78, voltage=0.016522908583283424\n    time_span=0.0001s, test_ID=190, label=1, output_node=79, voltage=0.011280876584351063\n    time_span=0.0001s, test_ID=190, label=1, output_node=80, voltage=0.01507470104843378\n    time_span=0.0001s, test_ID=190, label=1, output_node=81, voltage=0.017972111701965332\n    time_span=0.0001s, test_ID=190, label=1, output_node=82, voltage=0.011593625880777836\n    time_span=0.0001s, test_ID=190, label=1, output_node=83, voltage=0.013450199738144875\n    time_span=0.0001s, test_ID=190, label=1, output_node=84, voltage=0.00901991967111826\n    time_span=0.0001s, test_ID=190, label=1, output_node=85, voltage=0.015869522467255592\n    time_span=0.0001s, test_ID=190, label=1, output_node=86, voltage=0.013893425464630127\n    time_span=0.0001s, test_ID=190, label=1, output_node=87, voltage=0.0072420318610966206\n    time_span=0.0001s, test_ID=190, label=1, output_node=88, voltage=0.01117729116231203\n    time_span=0.0001s, test_ID=190, label=1, output_node=89, voltage=0.01068027876317501\n    time_span=0.0001s, test_ID=190, label=1, output_node=90, voltage=0.023007966578006744\n    time_span=0.0001s, test_ID=190, label=1, output_node=91, voltage=0.013213148340582848\n    time_span=0.0001s, test_ID=190, label=1, output_node=92, voltage=0.021250000223517418\n    time_span=0.0001s, test_ID=190, label=1, output_node=93, voltage=0.016020916402339935\n    time_span=0.0001s, test_ID=190, label=1, output_node=94, voltage=0.013855579309165478\n    time_span=0.0001s, test_ID=190, label=1, output_node=95, voltage=0.021310755982995033\n    time_span=0.0001s, test_ID=190, label=1, output_node=96, voltage=0.01629183255136013\n    time_span=0.0001s, test_ID=190, label=1, output_node=97, voltage=0.015322708524763584\n    time_span=0.0001s, test_ID=190, label=1, output_node=98, voltage=0.01552788820117712\n    time_span=0.0001s, test_ID=190, label=1, output_node=99, voltage=0.012305776588618755\n    time_span=0.0001s, test_ID=190, label=1, output_node=sum, voltage=0.042687252163887024\n    Time consumed for 1 sample = 626.7681727409363 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '190'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=191, label=1, output_node=bkg, voltage=-0.005209163762629032\n    time_span=0.0001s, test_ID=191, label=1, output_node=0, voltage=0.0035448207054287195\n    time_span=0.0001s, test_ID=191, label=1, output_node=1, voltage=0.0014272909611463547\n    time_span=0.0001s, test_ID=191, label=1, output_node=2, voltage=0.006487052422016859\n    time_span=0.0001s, test_ID=191, label=1, output_node=3, voltage=-0.0008874501218087971\n    time_span=0.0001s, test_ID=191, label=1, output_node=4, voltage=0.0011235057609155774\n    time_span=0.0001s, test_ID=191, label=1, output_node=5, voltage=0.007520915940403938\n    time_span=0.0001s, test_ID=191, label=1, output_node=6, voltage=0.0038635460659861565\n    time_span=0.0001s, test_ID=191, label=1, output_node=7, voltage=0.0041125500574707985\n    time_span=0.0001s, test_ID=191, label=1, output_node=8, voltage=0.002315737074241042\n    time_span=0.0001s, test_ID=191, label=1, output_node=9, voltage=0.003561753313988447\n    time_span=0.0001s, test_ID=191, label=1, output_node=10, voltage=0.0028207169380038977\n    time_span=0.0001s, test_ID=191, label=1, output_node=11, voltage=0.005546812899410725\n    time_span=0.0001s, test_ID=191, label=1, output_node=12, voltage=0.005131474230438471\n    time_span=0.0001s, test_ID=191, label=1, output_node=13, voltage=0.0035986057482659817\n    time_span=0.0001s, test_ID=191, label=1, output_node=14, voltage=0.006336653605103493\n    time_span=0.0001s, test_ID=191, label=1, output_node=15, voltage=0.0016294820234179497\n    time_span=0.0001s, test_ID=191, label=1, output_node=16, voltage=0.005791832227259874\n    time_span=0.0001s, test_ID=191, label=1, output_node=17, voltage=-0.0003635457542259246\n    time_span=0.0001s, test_ID=191, label=1, output_node=18, voltage=0.003324701450765133\n    time_span=0.0001s, test_ID=191, label=1, output_node=19, voltage=-0.00015338644152507186\n    time_span=0.0001s, test_ID=191, label=1, output_node=20, voltage=0.0010119520593434572\n    time_span=0.0001s, test_ID=191, label=1, output_node=21, voltage=0.003188247326761484\n    time_span=0.0001s, test_ID=191, label=1, output_node=22, voltage=0.0026474103797227144\n    time_span=0.0001s, test_ID=191, label=1, output_node=23, voltage=0.005337649490684271\n    time_span=0.0001s, test_ID=191, label=1, output_node=24, voltage=0.002150398213416338\n    time_span=0.0001s, test_ID=191, label=1, output_node=25, voltage=0.0002998009149450809\n    time_span=0.0001s, test_ID=191, label=1, output_node=26, voltage=0.00399402342736721\n    time_span=0.0001s, test_ID=191, label=1, output_node=27, voltage=0.0013774902326986194\n    time_span=0.0001s, test_ID=191, label=1, output_node=28, voltage=-0.0006772907800041139\n    time_span=0.0001s, test_ID=191, label=1, output_node=29, voltage=0.0044920314103364944\n    time_span=0.0001s, test_ID=191, label=1, output_node=30, voltage=0.003278884571045637\n    time_span=0.0001s, test_ID=191, label=1, output_node=31, voltage=0.005469123832881451\n    time_span=0.0001s, test_ID=191, label=1, output_node=32, voltage=0.0065627493895590305\n    time_span=0.0001s, test_ID=191, label=1, output_node=33, voltage=0.0032300797756761312\n    time_span=0.0001s, test_ID=191, label=1, output_node=34, voltage=0.001421314780600369\n    time_span=0.0001s, test_ID=191, label=1, output_node=35, voltage=0.0025009959936141968\n    time_span=0.0001s, test_ID=191, label=1, output_node=36, voltage=0.0029243030585348606\n    time_span=0.0001s, test_ID=191, label=1, output_node=37, voltage=-0.0014701195759698749\n    time_span=0.0001s, test_ID=191, label=1, output_node=38, voltage=0.003776892554014921\n    time_span=0.0001s, test_ID=191, label=1, output_node=39, voltage=0.004825696814805269\n    time_span=0.0001s, test_ID=191, label=1, output_node=40, voltage=0.003947210963815451\n    time_span=0.0001s, test_ID=191, label=1, output_node=41, voltage=0.0041952189058065414\n    time_span=0.0001s, test_ID=191, label=1, output_node=42, voltage=0.004399402067065239\n    time_span=0.0001s, test_ID=191, label=1, output_node=43, voltage=0.0051782866939902306\n    time_span=0.0001s, test_ID=191, label=1, output_node=44, voltage=0.0012011952931061387\n    time_span=0.0001s, test_ID=191, label=1, output_node=45, voltage=0.002439243020489812\n    time_span=0.0001s, test_ID=191, label=1, output_node=46, voltage=-0.000276892475085333\n    time_span=0.0001s, test_ID=191, label=1, output_node=47, voltage=0.005561753176152706\n    time_span=0.0001s, test_ID=191, label=1, output_node=48, voltage=0.0042679281905293465\n    time_span=0.0001s, test_ID=191, label=1, output_node=49, voltage=0.003523904364556074\n    time_span=0.0001s, test_ID=191, label=1, output_node=50, voltage=0.002840637695044279\n    time_span=0.0001s, test_ID=191, label=1, output_node=51, voltage=0.005826693028211594\n    time_span=0.0001s, test_ID=191, label=1, output_node=52, voltage=0.001704183523543179\n    time_span=0.0001s, test_ID=191, label=1, output_node=53, voltage=0.004310757387429476\n    time_span=0.0001s, test_ID=191, label=1, output_node=54, voltage=0.004535856656730175\n    time_span=0.0001s, test_ID=191, label=1, output_node=55, voltage=0.001906374585814774\n    time_span=0.0001s, test_ID=191, label=1, output_node=56, voltage=0.0020249004010111094\n    time_span=0.0001s, test_ID=191, label=1, output_node=57, voltage=0.003349601523950696\n    time_span=0.0001s, test_ID=191, label=1, output_node=58, voltage=0.002912350930273533\n    time_span=0.0001s, test_ID=191, label=1, output_node=59, voltage=0.0022549801506102085\n    time_span=0.0001s, test_ID=191, label=1, output_node=60, voltage=0.0008974104421213269\n    time_span=0.0001s, test_ID=191, label=1, output_node=61, voltage=0.0034750993363559246\n    time_span=0.0001s, test_ID=191, label=1, output_node=62, voltage=0.005954183172434568\n    time_span=0.0001s, test_ID=191, label=1, output_node=63, voltage=0.0034601592924445868\n    time_span=0.0001s, test_ID=191, label=1, output_node=64, voltage=0.0004691235371865332\n    time_span=0.0001s, test_ID=191, label=1, output_node=65, voltage=0.0023486055433750153\n    time_span=0.0001s, test_ID=191, label=1, output_node=66, voltage=0.004420318640768528\n    time_span=0.0001s, test_ID=191, label=1, output_node=67, voltage=0.0035448207054287195\n    time_span=0.0001s, test_ID=191, label=1, output_node=68, voltage=0.0014900397509336472\n    time_span=0.0001s, test_ID=191, label=1, output_node=69, voltage=0.003068725112825632\n    time_span=0.0001s, test_ID=191, label=1, output_node=70, voltage=0.004439242649823427\n    time_span=0.0001s, test_ID=191, label=1, output_node=71, voltage=0.0032549803145229816\n    time_span=0.0001s, test_ID=191, label=1, output_node=72, voltage=0.0012081675231456757\n    time_span=0.0001s, test_ID=191, label=1, output_node=73, voltage=0.00015239055210258812\n    time_span=0.0001s, test_ID=191, label=1, output_node=74, voltage=0.0018087648786604404\n    time_span=0.0001s, test_ID=191, label=1, output_node=75, voltage=0.005866533610969782\n    time_span=0.0001s, test_ID=191, label=1, output_node=76, voltage=0.002926294691860676\n    time_span=0.0001s, test_ID=191, label=1, output_node=77, voltage=0.006173306610435247\n    time_span=0.0001s, test_ID=191, label=1, output_node=78, voltage=0.005749999545514584\n    time_span=0.0001s, test_ID=191, label=1, output_node=79, voltage=0.0014372511068359017\n    time_span=0.0001s, test_ID=191, label=1, output_node=80, voltage=0.0020258964505046606\n    time_span=0.0001s, test_ID=191, label=1, output_node=81, voltage=0.0020408369600772858\n    time_span=0.0001s, test_ID=191, label=1, output_node=82, voltage=0.003574701491743326\n    time_span=0.0001s, test_ID=191, label=1, output_node=83, voltage=0.004346613306552172\n    time_span=0.0001s, test_ID=191, label=1, output_node=84, voltage=0.002899402752518654\n    time_span=0.0001s, test_ID=191, label=1, output_node=85, voltage=0.0020099603570997715\n    time_span=0.0001s, test_ID=191, label=1, output_node=86, voltage=0.002747011836618185\n    time_span=0.0001s, test_ID=191, label=1, output_node=87, voltage=-0.000324701308272779\n    time_span=0.0001s, test_ID=191, label=1, output_node=88, voltage=0.0037350598722696304\n    time_span=0.0001s, test_ID=191, label=1, output_node=89, voltage=0.0020308764651417732\n    time_span=0.0001s, test_ID=191, label=1, output_node=90, voltage=0.0025169323198497295\n    time_span=0.0001s, test_ID=191, label=1, output_node=91, voltage=-0.00037848614738322794\n    time_span=0.0001s, test_ID=191, label=1, output_node=92, voltage=0.0044262949377298355\n    time_span=0.0001s, test_ID=191, label=1, output_node=93, voltage=0.0008067729650065303\n    time_span=0.0001s, test_ID=191, label=1, output_node=94, voltage=-0.0005717132589779794\n    time_span=0.0001s, test_ID=191, label=1, output_node=95, voltage=0.0012818725081160665\n    time_span=0.0001s, test_ID=191, label=1, output_node=96, voltage=0.0004820717149414122\n    time_span=0.0001s, test_ID=191, label=1, output_node=97, voltage=0.004494023974984884\n    time_span=0.0001s, test_ID=191, label=1, output_node=98, voltage=0.0018256971379742026\n    time_span=0.0001s, test_ID=191, label=1, output_node=99, voltage=0.0019492029678076506\n    time_span=0.0001s, test_ID=191, label=1, output_node=sum, voltage=0.013252987526357174\n    Time consumed for 1 sample = 623.8872616291046 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '191'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=192, label=0, output_node=bkg, voltage=-0.0029143427964299917\n    time_span=0.0001s, test_ID=192, label=0, output_node=0, voltage=0.00817430391907692\n    time_span=0.0001s, test_ID=192, label=0, output_node=1, voltage=0.005395418033003807\n    time_span=0.0001s, test_ID=192, label=0, output_node=2, voltage=0.00939143542200327\n    time_span=0.0001s, test_ID=192, label=0, output_node=3, voltage=0.004431275185197592\n    time_span=0.0001s, test_ID=192, label=0, output_node=4, voltage=0.004488047212362289\n    time_span=0.0001s, test_ID=192, label=0, output_node=5, voltage=0.005181274842470884\n    time_span=0.0001s, test_ID=192, label=0, output_node=6, voltage=0.0065488051623106\n    time_span=0.0001s, test_ID=192, label=0, output_node=7, voltage=0.0065587651915848255\n    time_span=0.0001s, test_ID=192, label=0, output_node=8, voltage=0.004060756415128708\n    time_span=0.0001s, test_ID=192, label=0, output_node=9, voltage=0.012485059909522533\n    time_span=0.0001s, test_ID=192, label=0, output_node=10, voltage=0.0036334660835564137\n    time_span=0.0001s, test_ID=192, label=0, output_node=11, voltage=0.006756971590220928\n    time_span=0.0001s, test_ID=192, label=0, output_node=12, voltage=-0.0001464143570046872\n    time_span=0.0001s, test_ID=192, label=0, output_node=13, voltage=0.006775896530598402\n    time_span=0.0001s, test_ID=192, label=0, output_node=14, voltage=0.004589641932398081\n    time_span=0.0001s, test_ID=192, label=0, output_node=15, voltage=0.0046673305332660675\n    time_span=0.0001s, test_ID=192, label=0, output_node=16, voltage=0.0065378486178815365\n    time_span=0.0001s, test_ID=192, label=0, output_node=17, voltage=0.00905577652156353\n    time_span=0.0001s, test_ID=192, label=0, output_node=18, voltage=0.003065737197175622\n    time_span=0.0001s, test_ID=192, label=0, output_node=19, voltage=0.004521912429481745\n    time_span=0.0001s, test_ID=192, label=0, output_node=20, voltage=0.006821713410317898\n    time_span=0.0001s, test_ID=192, label=0, output_node=21, voltage=0.008160358294844627\n    time_span=0.0001s, test_ID=192, label=0, output_node=22, voltage=0.005119522102177143\n    time_span=0.0001s, test_ID=192, label=0, output_node=23, voltage=0.006127490662038326\n    time_span=0.0001s, test_ID=192, label=0, output_node=24, voltage=0.007730080280452967\n    time_span=0.0001s, test_ID=192, label=0, output_node=25, voltage=0.01188944187015295\n    time_span=0.0001s, test_ID=192, label=0, output_node=26, voltage=0.006286852527409792\n    time_span=0.0001s, test_ID=192, label=0, output_node=27, voltage=0.003242031903937459\n    time_span=0.0001s, test_ID=192, label=0, output_node=28, voltage=0.007755976170301437\n    time_span=0.0001s, test_ID=192, label=0, output_node=29, voltage=0.0042978087440133095\n    time_span=0.0001s, test_ID=192, label=0, output_node=30, voltage=0.006531872786581516\n    time_span=0.0001s, test_ID=192, label=0, output_node=31, voltage=0.006595617160201073\n    time_span=0.0001s, test_ID=192, label=0, output_node=32, voltage=0.007978088222444057\n    time_span=0.0001s, test_ID=192, label=0, output_node=33, voltage=0.0027211157139390707\n    time_span=0.0001s, test_ID=192, label=0, output_node=34, voltage=0.006608565803617239\n    time_span=0.0001s, test_ID=192, label=0, output_node=35, voltage=0.0025428286753594875\n    time_span=0.0001s, test_ID=192, label=0, output_node=36, voltage=0.008082669228315353\n    time_span=0.0001s, test_ID=192, label=0, output_node=37, voltage=0.004844621289521456\n    time_span=0.0001s, test_ID=192, label=0, output_node=38, voltage=0.007107569370418787\n    time_span=0.0001s, test_ID=192, label=0, output_node=39, voltage=0.009972111321985722\n    time_span=0.0001s, test_ID=192, label=0, output_node=40, voltage=0.009462151676416397\n    time_span=0.0001s, test_ID=192, label=0, output_node=41, voltage=0.00598306767642498\n    time_span=0.0001s, test_ID=192, label=0, output_node=42, voltage=0.008400398306548595\n    time_span=0.0001s, test_ID=192, label=0, output_node=43, voltage=0.00805278867483139\n    time_span=0.0001s, test_ID=192, label=0, output_node=44, voltage=0.0015159363392740488\n    time_span=0.0001s, test_ID=192, label=0, output_node=45, voltage=0.00992529932409525\n    time_span=0.0001s, test_ID=192, label=0, output_node=46, voltage=0.0069840638898313046\n    time_span=0.0001s, test_ID=192, label=0, output_node=47, voltage=0.00923705194145441\n    time_span=0.0001s, test_ID=192, label=0, output_node=48, voltage=0.00232768920250237\n    time_span=0.0001s, test_ID=192, label=0, output_node=49, voltage=0.003670318750664592\n    time_span=0.0001s, test_ID=192, label=0, output_node=50, voltage=0.00586952269077301\n    time_span=0.0001s, test_ID=192, label=0, output_node=51, voltage=0.009172310121357441\n    time_span=0.0001s, test_ID=192, label=0, output_node=52, voltage=0.01156673301011324\n    time_span=0.0001s, test_ID=192, label=0, output_node=53, voltage=0.00765637494623661\n    time_span=0.0001s, test_ID=192, label=0, output_node=54, voltage=0.004368525929749012\n    time_span=0.0001s, test_ID=192, label=0, output_node=55, voltage=0.008944222703576088\n    time_span=0.0001s, test_ID=192, label=0, output_node=56, voltage=0.002735059941187501\n    time_span=0.0001s, test_ID=192, label=0, output_node=57, voltage=0.005168326664716005\n    time_span=0.0001s, test_ID=192, label=0, output_node=58, voltage=0.004772908054292202\n    time_span=0.0001s, test_ID=192, label=0, output_node=59, voltage=0.004428287036716938\n    time_span=0.0001s, test_ID=192, label=0, output_node=60, voltage=0.013269919902086258\n    time_span=0.0001s, test_ID=192, label=0, output_node=61, voltage=0.0037828683853149414\n    time_span=0.0001s, test_ID=192, label=0, output_node=62, voltage=0.004566733259707689\n    time_span=0.0001s, test_ID=192, label=0, output_node=63, voltage=0.007996016182005405\n    time_span=0.0001s, test_ID=192, label=0, output_node=64, voltage=-0.0007290836656466126\n    time_span=0.0001s, test_ID=192, label=0, output_node=65, voltage=0.008399401791393757\n    time_span=0.0001s, test_ID=192, label=0, output_node=66, voltage=-0.00016533868620172143\n    time_span=0.0001s, test_ID=192, label=0, output_node=67, voltage=0.0021752987522631884\n    time_span=0.0001s, test_ID=192, label=0, output_node=68, voltage=0.009773904457688332\n    time_span=0.0001s, test_ID=192, label=0, output_node=69, voltage=0.005703187081962824\n    time_span=0.0001s, test_ID=192, label=0, output_node=70, voltage=0.008434262126684189\n    time_span=0.0001s, test_ID=192, label=0, output_node=71, voltage=0.006930279079824686\n    time_span=0.0001s, test_ID=192, label=0, output_node=72, voltage=0.004097609780728817\n    time_span=0.0001s, test_ID=192, label=0, output_node=73, voltage=0.006380478385835886\n    time_span=0.0001s, test_ID=192, label=0, output_node=74, voltage=0.007333665154874325\n    time_span=0.0001s, test_ID=192, label=0, output_node=75, voltage=0.007128485944122076\n    time_span=0.0001s, test_ID=192, label=0, output_node=76, voltage=0.0065816729329526424\n    time_span=0.0001s, test_ID=192, label=0, output_node=77, voltage=0.007529880851507187\n    time_span=0.0001s, test_ID=192, label=0, output_node=78, voltage=0.0059402394108474255\n    time_span=0.0001s, test_ID=192, label=0, output_node=79, voltage=0.008657369762659073\n    time_span=0.0001s, test_ID=192, label=0, output_node=80, voltage=0.008929283358156681\n    time_span=0.0001s, test_ID=192, label=0, output_node=81, voltage=0.006338645704090595\n    time_span=0.0001s, test_ID=192, label=0, output_node=82, voltage=0.006047808565199375\n    time_span=0.0001s, test_ID=192, label=0, output_node=83, voltage=0.005971115548163652\n    time_span=0.0001s, test_ID=192, label=0, output_node=84, voltage=0.0069372509606182575\n    time_span=0.0001s, test_ID=192, label=0, output_node=85, voltage=0.00777788832783699\n    time_span=0.0001s, test_ID=192, label=0, output_node=86, voltage=0.004659363068640232\n    time_span=0.0001s, test_ID=192, label=0, output_node=87, voltage=0.004906374495476484\n    time_span=0.0001s, test_ID=192, label=0, output_node=88, voltage=0.0037539841141551733\n    time_span=0.0001s, test_ID=192, label=0, output_node=89, voltage=0.0113884462043643\n    time_span=0.0001s, test_ID=192, label=0, output_node=90, voltage=0.006223107688128948\n    time_span=0.0001s, test_ID=192, label=0, output_node=91, voltage=0.006372509989887476\n    time_span=0.0001s, test_ID=192, label=0, output_node=92, voltage=0.0044013941660523415\n    time_span=0.0001s, test_ID=192, label=0, output_node=93, voltage=0.007782868575304747\n    time_span=0.0001s, test_ID=192, label=0, output_node=94, voltage=0.0066364542581140995\n    time_span=0.0001s, test_ID=192, label=0, output_node=95, voltage=0.0065936255268752575\n    time_span=0.0001s, test_ID=192, label=0, output_node=96, voltage=0.005016931798309088\n    time_span=0.0001s, test_ID=192, label=0, output_node=97, voltage=0.004368525929749012\n    time_span=0.0001s, test_ID=192, label=0, output_node=98, voltage=0.008790836669504642\n    time_span=0.0001s, test_ID=192, label=0, output_node=99, voltage=0.005235059652477503\n    time_span=0.0001s, test_ID=192, label=0, output_node=sum, voltage=0.023112552240490913\n    Time consumed for 1 sample = 624.0467610359192 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '192'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=193, label=9, output_node=bkg, voltage=-0.005460159387439489\n    time_span=0.0001s, test_ID=193, label=9, output_node=0, voltage=0.013395417481660843\n    time_span=0.0001s, test_ID=193, label=9, output_node=1, voltage=0.006880478002130985\n    time_span=0.0001s, test_ID=193, label=9, output_node=2, voltage=0.01024003978818655\n    time_span=0.0001s, test_ID=193, label=9, output_node=3, voltage=0.013390438631176949\n    time_span=0.0001s, test_ID=193, label=9, output_node=4, voltage=0.012340637855231762\n    time_span=0.0001s, test_ID=193, label=9, output_node=5, voltage=0.010153386741876602\n    time_span=0.0001s, test_ID=193, label=9, output_node=6, voltage=0.015142430551350117\n    time_span=0.0001s, test_ID=193, label=9, output_node=7, voltage=0.008907370269298553\n    time_span=0.0001s, test_ID=193, label=9, output_node=8, voltage=0.012340637855231762\n    time_span=0.0001s, test_ID=193, label=9, output_node=9, voltage=0.007626494392752647\n    time_span=0.0001s, test_ID=193, label=9, output_node=10, voltage=0.011596613563597202\n    time_span=0.0001s, test_ID=193, label=9, output_node=11, voltage=0.008531872183084488\n    time_span=0.0001s, test_ID=193, label=9, output_node=12, voltage=0.01467131543904543\n    time_span=0.0001s, test_ID=193, label=9, output_node=13, voltage=0.012049800716340542\n    time_span=0.0001s, test_ID=193, label=9, output_node=14, voltage=0.00681175384670496\n    time_span=0.0001s, test_ID=193, label=9, output_node=15, voltage=0.013934263028204441\n    time_span=0.0001s, test_ID=193, label=9, output_node=16, voltage=0.009814741089940071\n    time_span=0.0001s, test_ID=193, label=9, output_node=17, voltage=0.0024262946099042892\n    time_span=0.0001s, test_ID=193, label=9, output_node=18, voltage=0.009352589026093483\n    time_span=0.0001s, test_ID=193, label=9, output_node=19, voltage=0.015278884209692478\n    time_span=0.0001s, test_ID=193, label=9, output_node=20, voltage=0.004911354277282953\n    time_span=0.0001s, test_ID=193, label=9, output_node=21, voltage=0.008622509427368641\n    time_span=0.0001s, test_ID=193, label=9, output_node=22, voltage=0.006973107345402241\n    time_span=0.0001s, test_ID=193, label=9, output_node=23, voltage=0.007850597612559795\n    time_span=0.0001s, test_ID=193, label=9, output_node=24, voltage=0.006742031779140234\n    time_span=0.0001s, test_ID=193, label=9, output_node=25, voltage=0.006394422613084316\n    time_span=0.0001s, test_ID=193, label=9, output_node=26, voltage=0.01086354535073042\n    time_span=0.0001s, test_ID=193, label=9, output_node=27, voltage=0.014896413311362267\n    time_span=0.0001s, test_ID=193, label=9, output_node=28, voltage=0.007012948393821716\n    time_span=0.0001s, test_ID=193, label=9, output_node=29, voltage=0.009253984317183495\n    time_span=0.0001s, test_ID=193, label=9, output_node=30, voltage=0.00775597570464015\n    time_span=0.0001s, test_ID=193, label=9, output_node=31, voltage=0.012972111813724041\n    time_span=0.0001s, test_ID=193, label=9, output_node=32, voltage=0.011467131786048412\n    time_span=0.0001s, test_ID=193, label=9, output_node=33, voltage=0.014819720759987831\n    time_span=0.0001s, test_ID=193, label=9, output_node=34, voltage=0.007743027526885271\n    time_span=0.0001s, test_ID=193, label=9, output_node=35, voltage=0.010213146917521954\n    time_span=0.0001s, test_ID=193, label=9, output_node=36, voltage=0.010517928749322891\n    time_span=0.0001s, test_ID=193, label=9, output_node=37, voltage=0.008367530070245266\n    time_span=0.0001s, test_ID=193, label=9, output_node=38, voltage=0.007970119826495647\n    time_span=0.0001s, test_ID=193, label=9, output_node=39, voltage=0.01241533923894167\n    time_span=0.0001s, test_ID=193, label=9, output_node=40, voltage=0.005311753135174513\n    time_span=0.0001s, test_ID=193, label=9, output_node=41, voltage=0.0077280872501432896\n    time_span=0.0001s, test_ID=193, label=9, output_node=42, voltage=0.01026095636188984\n    time_span=0.0001s, test_ID=193, label=9, output_node=43, voltage=0.010944223031401634\n    time_span=0.0001s, test_ID=193, label=9, output_node=44, voltage=0.013789840042591095\n    time_span=0.0001s, test_ID=193, label=9, output_node=45, voltage=0.011173306033015251\n    time_span=0.0001s, test_ID=193, label=9, output_node=46, voltage=0.010488048195838928\n    time_span=0.0001s, test_ID=193, label=9, output_node=47, voltage=0.008463147096335888\n    time_span=0.0001s, test_ID=193, label=9, output_node=48, voltage=0.013076692819595337\n    time_span=0.0001s, test_ID=193, label=9, output_node=49, voltage=0.0071095614694058895\n    time_span=0.0001s, test_ID=193, label=9, output_node=50, voltage=0.009238047525286674\n    time_span=0.0001s, test_ID=193, label=9, output_node=51, voltage=0.011692231521010399\n    time_span=0.0001s, test_ID=193, label=9, output_node=52, voltage=0.014693225733935833\n    time_span=0.0001s, test_ID=193, label=9, output_node=53, voltage=0.011248009279370308\n    time_span=0.0001s, test_ID=193, label=9, output_node=54, voltage=0.012429283000528812\n    time_span=0.0001s, test_ID=193, label=9, output_node=55, voltage=0.007804780267179012\n    time_span=0.0001s, test_ID=193, label=9, output_node=56, voltage=0.007873506285250187\n    time_span=0.0001s, test_ID=193, label=9, output_node=57, voltage=0.019472112879157066\n    time_span=0.0001s, test_ID=193, label=9, output_node=58, voltage=0.007252988405525684\n    time_span=0.0001s, test_ID=193, label=9, output_node=59, voltage=0.007213147357106209\n    time_span=0.0001s, test_ID=193, label=9, output_node=60, voltage=0.0037370522040873766\n    time_span=0.0001s, test_ID=193, label=9, output_node=61, voltage=0.009123506024479866\n    time_span=0.0001s, test_ID=193, label=9, output_node=62, voltage=0.002803785027936101\n    time_span=0.0001s, test_ID=193, label=9, output_node=63, voltage=0.010463147424161434\n    time_span=0.0001s, test_ID=193, label=9, output_node=64, voltage=0.012283864431083202\n    time_span=0.0001s, test_ID=193, label=9, output_node=65, voltage=0.009966135025024414\n    time_span=0.0001s, test_ID=193, label=9, output_node=66, voltage=0.014116534031927586\n    time_span=0.0001s, test_ID=193, label=9, output_node=67, voltage=0.009830676950514317\n    time_span=0.0001s, test_ID=193, label=9, output_node=68, voltage=0.004419323056936264\n    time_span=0.0001s, test_ID=193, label=9, output_node=69, voltage=0.008978087455034256\n    time_span=0.0001s, test_ID=193, label=9, output_node=70, voltage=0.015450199134647846\n    time_span=0.0001s, test_ID=193, label=9, output_node=71, voltage=0.009983067400753498\n    time_span=0.0001s, test_ID=193, label=9, output_node=72, voltage=0.011906375177204609\n    time_span=0.0001s, test_ID=193, label=9, output_node=73, voltage=0.016294822096824646\n    time_span=0.0001s, test_ID=193, label=9, output_node=74, voltage=0.017273904755711555\n    time_span=0.0001s, test_ID=193, label=9, output_node=75, voltage=0.004006972070783377\n    time_span=0.0001s, test_ID=193, label=9, output_node=76, voltage=0.014619521796703339\n    time_span=0.0001s, test_ID=193, label=9, output_node=77, voltage=0.008317728526890278\n    time_span=0.0001s, test_ID=193, label=9, output_node=78, voltage=0.008023904636502266\n    time_span=0.0001s, test_ID=193, label=9, output_node=79, voltage=0.011427290737628937\n    time_span=0.0001s, test_ID=193, label=9, output_node=80, voltage=0.012686255387961864\n    time_span=0.0001s, test_ID=193, label=9, output_node=81, voltage=0.00971812754869461\n    time_span=0.0001s, test_ID=193, label=9, output_node=82, voltage=0.017445219680666924\n    time_span=0.0001s, test_ID=193, label=9, output_node=83, voltage=0.011731075122952461\n    time_span=0.0001s, test_ID=193, label=9, output_node=84, voltage=0.006142430007457733\n    time_span=0.0001s, test_ID=193, label=9, output_node=85, voltage=0.01181673351675272\n    time_span=0.0001s, test_ID=193, label=9, output_node=86, voltage=0.014474103227257729\n    time_span=0.0001s, test_ID=193, label=9, output_node=87, voltage=0.01388246938586235\n    time_span=0.0001s, test_ID=193, label=9, output_node=88, voltage=0.014158366248011589\n    time_span=0.0001s, test_ID=193, label=9, output_node=89, voltage=0.0081294821575284\n    time_span=0.0001s, test_ID=193, label=9, output_node=90, voltage=0.01226992066949606\n    time_span=0.0001s, test_ID=193, label=9, output_node=91, voltage=0.0069541833363473415\n    time_span=0.0001s, test_ID=193, label=9, output_node=92, voltage=0.013026893138885498\n    time_span=0.0001s, test_ID=193, label=9, output_node=93, voltage=0.013872510753571987\n    time_span=0.0001s, test_ID=193, label=9, output_node=94, voltage=0.0119093619287014\n    time_span=0.0001s, test_ID=193, label=9, output_node=95, voltage=0.011976095847785473\n    time_span=0.0001s, test_ID=193, label=9, output_node=96, voltage=0.021759960800409317\n    time_span=0.0001s, test_ID=193, label=9, output_node=97, voltage=0.0047231074422597885\n    time_span=0.0001s, test_ID=193, label=9, output_node=98, voltage=0.004815737251192331\n    time_span=0.0001s, test_ID=193, label=9, output_node=99, voltage=0.011016933247447014\n    time_span=0.0001s, test_ID=193, label=9, output_node=sum, voltage=0.030075697228312492\n    Time consumed for 1 sample = 625.0321803092957 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '193'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=194, label=0, output_node=bkg, voltage=-0.005109562072902918\n    time_span=0.0001s, test_ID=194, label=0, output_node=0, voltage=0.023264940828084946\n    time_span=0.0001s, test_ID=194, label=0, output_node=1, voltage=0.01843525841832161\n    time_span=0.0001s, test_ID=194, label=0, output_node=2, voltage=0.027526892721652985\n    time_span=0.0001s, test_ID=194, label=0, output_node=3, voltage=0.014588646590709686\n    time_span=0.0001s, test_ID=194, label=0, output_node=4, voltage=0.014730080030858517\n    time_span=0.0001s, test_ID=194, label=0, output_node=5, voltage=0.024258965626358986\n    time_span=0.0001s, test_ID=194, label=0, output_node=6, voltage=0.023991037160158157\n    time_span=0.0001s, test_ID=194, label=0, output_node=7, voltage=0.02316334657371044\n    time_span=0.0001s, test_ID=194, label=0, output_node=8, voltage=0.021795816719532013\n    time_span=0.0001s, test_ID=194, label=0, output_node=9, voltage=0.016189243644475937\n    time_span=0.0001s, test_ID=194, label=0, output_node=10, voltage=0.020355578511953354\n    time_span=0.0001s, test_ID=194, label=0, output_node=11, voltage=0.022916333749890327\n    time_span=0.0001s, test_ID=194, label=0, output_node=12, voltage=0.02017231099307537\n    time_span=0.0001s, test_ID=194, label=0, output_node=13, voltage=0.030373504385352135\n    time_span=0.0001s, test_ID=194, label=0, output_node=14, voltage=0.016887450590729713\n    time_span=0.0001s, test_ID=194, label=0, output_node=15, voltage=0.02237948216497898\n    time_span=0.0001s, test_ID=194, label=0, output_node=16, voltage=0.019426293671131134\n    time_span=0.0001s, test_ID=194, label=0, output_node=17, voltage=0.024055777117609978\n    time_span=0.0001s, test_ID=194, label=0, output_node=18, voltage=0.01875697262585163\n    time_span=0.0001s, test_ID=194, label=0, output_node=19, voltage=0.01582370512187481\n    time_span=0.0001s, test_ID=194, label=0, output_node=20, voltage=0.0213047806173563\n    time_span=0.0001s, test_ID=194, label=0, output_node=21, voltage=0.015850597992539406\n    time_span=0.0001s, test_ID=194, label=0, output_node=22, voltage=0.01585657335817814\n    time_span=0.0001s, test_ID=194, label=0, output_node=23, voltage=0.02277589775621891\n    time_span=0.0001s, test_ID=194, label=0, output_node=24, voltage=0.023435257375240326\n    time_span=0.0001s, test_ID=194, label=0, output_node=25, voltage=0.027195220813155174\n    time_span=0.0001s, test_ID=194, label=0, output_node=26, voltage=0.018231075257062912\n    time_span=0.0001s, test_ID=194, label=0, output_node=27, voltage=0.012685258872807026\n    time_span=0.0001s, test_ID=194, label=0, output_node=28, voltage=0.021421315148472786\n    time_span=0.0001s, test_ID=194, label=0, output_node=29, voltage=0.019700199365615845\n    time_span=0.0001s, test_ID=194, label=0, output_node=30, voltage=0.018462151288986206\n    time_span=0.0001s, test_ID=194, label=0, output_node=31, voltage=0.019983068108558655\n    time_span=0.0001s, test_ID=194, label=0, output_node=32, voltage=0.01910557597875595\n    time_span=0.0001s, test_ID=194, label=0, output_node=33, voltage=0.008848605677485466\n    time_span=0.0001s, test_ID=194, label=0, output_node=34, voltage=0.017744025215506554\n    time_span=0.0001s, test_ID=194, label=0, output_node=35, voltage=0.018335657194256783\n    time_span=0.0001s, test_ID=194, label=0, output_node=36, voltage=0.022005977109074593\n    time_span=0.0001s, test_ID=194, label=0, output_node=37, voltage=0.018732070922851562\n    time_span=0.0001s, test_ID=194, label=0, output_node=38, voltage=0.02051294967532158\n    time_span=0.0001s, test_ID=194, label=0, output_node=39, voltage=0.023347608745098114\n    time_span=0.0001s, test_ID=194, label=0, output_node=40, voltage=0.029922310262918472\n    time_span=0.0001s, test_ID=194, label=0, output_node=41, voltage=0.022327689453959465\n    time_span=0.0001s, test_ID=194, label=0, output_node=42, voltage=0.02382868528366089\n    time_span=0.0001s, test_ID=194, label=0, output_node=43, voltage=0.01918725110590458\n    time_span=0.0001s, test_ID=194, label=0, output_node=44, voltage=0.017468126490712166\n    time_span=0.0001s, test_ID=194, label=0, output_node=45, voltage=0.037375498563051224\n    time_span=0.0001s, test_ID=194, label=0, output_node=46, voltage=0.026022909209132195\n    time_span=0.0001s, test_ID=194, label=0, output_node=47, voltage=0.02626992017030716\n    time_span=0.0001s, test_ID=194, label=0, output_node=48, voltage=0.025078684091567993\n    time_span=0.0001s, test_ID=194, label=0, output_node=49, voltage=0.01684960164129734\n    time_span=0.0001s, test_ID=194, label=0, output_node=50, voltage=0.024559760466217995\n    time_span=0.0001s, test_ID=194, label=0, output_node=51, voltage=0.021371515467762947\n    time_span=0.0001s, test_ID=194, label=0, output_node=52, voltage=0.028643425554037094\n    time_span=0.0001s, test_ID=194, label=0, output_node=53, voltage=0.023111552000045776\n    time_span=0.0001s, test_ID=194, label=0, output_node=54, voltage=0.021795816719532013\n    time_span=0.0001s, test_ID=194, label=0, output_node=55, voltage=0.025389444082975388\n    time_span=0.0001s, test_ID=194, label=0, output_node=56, voltage=0.013574700802564621\n    time_span=0.0001s, test_ID=194, label=0, output_node=57, voltage=0.025602590292692184\n    time_span=0.0001s, test_ID=194, label=0, output_node=58, voltage=0.020944222807884216\n    time_span=0.0001s, test_ID=194, label=0, output_node=59, voltage=0.016051793470978737\n    time_span=0.0001s, test_ID=194, label=0, output_node=60, voltage=0.024674301967024803\n    time_span=0.0001s, test_ID=194, label=0, output_node=61, voltage=0.023085659369826317\n    time_span=0.0001s, test_ID=194, label=0, output_node=62, voltage=0.0181922297924757\n    time_span=0.0001s, test_ID=194, label=0, output_node=63, voltage=0.030779879540205002\n    time_span=0.0001s, test_ID=194, label=0, output_node=64, voltage=0.01506772916764021\n    time_span=0.0001s, test_ID=194, label=0, output_node=65, voltage=0.019747011363506317\n    time_span=0.0001s, test_ID=194, label=0, output_node=66, voltage=0.011443227529525757\n    time_span=0.0001s, test_ID=194, label=0, output_node=67, voltage=0.013582669198513031\n    time_span=0.0001s, test_ID=194, label=0, output_node=68, voltage=0.027553783729672432\n    time_span=0.0001s, test_ID=194, label=0, output_node=69, voltage=0.024260956794023514\n    time_span=0.0001s, test_ID=194, label=0, output_node=70, voltage=0.02348107472062111\n    time_span=0.0001s, test_ID=194, label=0, output_node=71, voltage=0.02537151426076889\n    time_span=0.0001s, test_ID=194, label=0, output_node=72, voltage=0.02139342576265335\n    time_span=0.0001s, test_ID=194, label=0, output_node=73, voltage=0.02285856567323208\n    time_span=0.0001s, test_ID=194, label=0, output_node=74, voltage=0.02178884483873844\n    time_span=0.0001s, test_ID=194, label=0, output_node=75, voltage=0.02368227206170559\n    time_span=0.0001s, test_ID=194, label=0, output_node=76, voltage=0.01864541880786419\n    time_span=0.0001s, test_ID=194, label=0, output_node=77, voltage=0.018384462222456932\n    time_span=0.0001s, test_ID=194, label=0, output_node=78, voltage=0.01449701189994812\n    time_span=0.0001s, test_ID=194, label=0, output_node=79, voltage=0.03237151354551315\n    time_span=0.0001s, test_ID=194, label=0, output_node=80, voltage=0.0205776896327734\n    time_span=0.0001s, test_ID=194, label=0, output_node=81, voltage=0.025423308834433556\n    time_span=0.0001s, test_ID=194, label=0, output_node=82, voltage=0.02185557782649994\n    time_span=0.0001s, test_ID=194, label=0, output_node=83, voltage=0.021800797432661057\n    time_span=0.0001s, test_ID=194, label=0, output_node=84, voltage=0.018137449398636818\n    time_span=0.0001s, test_ID=194, label=0, output_node=85, voltage=0.02135358564555645\n    time_span=0.0001s, test_ID=194, label=0, output_node=86, voltage=0.01951095648109913\n    time_span=0.0001s, test_ID=194, label=0, output_node=87, voltage=0.02383565716445446\n    time_span=0.0001s, test_ID=194, label=0, output_node=88, voltage=0.023295816034078598\n    time_span=0.0001s, test_ID=194, label=0, output_node=89, voltage=0.031537849456071854\n    time_span=0.0001s, test_ID=194, label=0, output_node=90, voltage=0.023405378684401512\n    time_span=0.0001s, test_ID=194, label=0, output_node=91, voltage=0.01718027889728546\n    time_span=0.0001s, test_ID=194, label=0, output_node=92, voltage=0.02275298722088337\n    time_span=0.0001s, test_ID=194, label=0, output_node=93, voltage=0.02786155417561531\n    time_span=0.0001s, test_ID=194, label=0, output_node=94, voltage=0.014207172207534313\n    time_span=0.0001s, test_ID=194, label=0, output_node=95, voltage=0.021342629566788673\n    time_span=0.0001s, test_ID=194, label=0, output_node=96, voltage=0.018940238282084465\n    time_span=0.0001s, test_ID=194, label=0, output_node=97, voltage=0.024051792919635773\n    time_span=0.0001s, test_ID=194, label=0, output_node=98, voltage=0.01608964055776596\n    time_span=0.0001s, test_ID=194, label=0, output_node=99, voltage=0.025577690452337265\n    time_span=0.0001s, test_ID=194, label=0, output_node=sum, voltage=0.05790338292717934\n    Time consumed for 1 sample = 629.7298924922943 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '194'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=195, label=3, output_node=bkg, voltage=-0.004971115849912167\n    time_span=0.0001s, test_ID=195, label=3, output_node=0, voltage=0.006182270590215921\n    time_span=0.0001s, test_ID=195, label=3, output_node=1, voltage=0.0007250996422953904\n    time_span=0.0001s, test_ID=195, label=3, output_node=2, voltage=0.007852589711546898\n    time_span=0.0001s, test_ID=195, label=3, output_node=3, voltage=0.002423306927084923\n    time_span=0.0001s, test_ID=195, label=3, output_node=4, voltage=0.005725099705159664\n    time_span=0.0001s, test_ID=195, label=3, output_node=5, voltage=0.005596613977104425\n    time_span=0.0001s, test_ID=195, label=3, output_node=6, voltage=0.0019352590898051858\n    time_span=0.0001s, test_ID=195, label=3, output_node=7, voltage=2.5896437364281155e-05\n    time_span=0.0001s, test_ID=195, label=3, output_node=8, voltage=0.0025906371884047985\n    time_span=0.0001s, test_ID=195, label=3, output_node=9, voltage=0.0019442233024165034\n    time_span=0.0001s, test_ID=195, label=3, output_node=10, voltage=-0.0016782868187874556\n    time_span=0.0001s, test_ID=195, label=3, output_node=11, voltage=0.00426294794306159\n    time_span=0.0001s, test_ID=195, label=3, output_node=12, voltage=0.0034850595984607935\n    time_span=0.0001s, test_ID=195, label=3, output_node=13, voltage=0.0019342629238963127\n    time_span=0.0001s, test_ID=195, label=3, output_node=14, voltage=0.004763944074511528\n    time_span=0.0001s, test_ID=195, label=3, output_node=15, voltage=0.0015886453911662102\n    time_span=0.0001s, test_ID=195, label=3, output_node=16, voltage=0.0041683269664645195\n    time_span=0.0001s, test_ID=195, label=3, output_node=17, voltage=0.001977091422304511\n    time_span=0.0001s, test_ID=195, label=3, output_node=18, voltage=0.000835657468996942\n    time_span=0.0001s, test_ID=195, label=3, output_node=19, voltage=0.000785856565926224\n    time_span=0.0001s, test_ID=195, label=3, output_node=20, voltage=0.00431972136721015\n    time_span=0.0001s, test_ID=195, label=3, output_node=21, voltage=-0.0007798804435878992\n    time_span=0.0001s, test_ID=195, label=3, output_node=22, voltage=0.00526593578979373\n    time_span=0.0001s, test_ID=195, label=3, output_node=23, voltage=0.0016633464256301522\n    time_span=0.0001s, test_ID=195, label=3, output_node=24, voltage=0.0035776891745626926\n    time_span=0.0001s, test_ID=195, label=3, output_node=25, voltage=0.0006533864652737975\n    time_span=0.0001s, test_ID=195, label=3, output_node=26, voltage=0.005268924403935671\n    time_span=0.0001s, test_ID=195, label=3, output_node=27, voltage=0.003784860484302044\n    time_span=0.0001s, test_ID=195, label=3, output_node=28, voltage=-7.968203135533258e-06\n    time_span=0.0001s, test_ID=195, label=3, output_node=29, voltage=0.001051792991347611\n    time_span=0.0001s, test_ID=195, label=3, output_node=30, voltage=0.0006643424858339131\n    time_span=0.0001s, test_ID=195, label=3, output_node=31, voltage=0.005065736826509237\n    time_span=0.0001s, test_ID=195, label=3, output_node=32, voltage=5.6772769312374294e-05\n    time_span=0.0001s, test_ID=195, label=3, output_node=33, voltage=0.0066274902783334255\n    time_span=0.0001s, test_ID=195, label=3, output_node=34, voltage=0.004008964169770479\n    time_span=0.0001s, test_ID=195, label=3, output_node=35, voltage=0.001656374428421259\n    time_span=0.0001s, test_ID=195, label=3, output_node=36, voltage=0.0025587650015950203\n    time_span=0.0001s, test_ID=195, label=3, output_node=37, voltage=-0.00011852591705974191\n    time_span=0.0001s, test_ID=195, label=3, output_node=38, voltage=-0.00033366528805345297\n    time_span=0.0001s, test_ID=195, label=3, output_node=39, voltage=0.004953187424689531\n    time_span=0.0001s, test_ID=195, label=3, output_node=40, voltage=-0.0003326693258713931\n    time_span=0.0001s, test_ID=195, label=3, output_node=41, voltage=0.002792828483507037\n    time_span=0.0001s, test_ID=195, label=3, output_node=42, voltage=0.003010955872014165\n    time_span=0.0001s, test_ID=195, label=3, output_node=43, voltage=0.0021205181255936623\n    time_span=0.0001s, test_ID=195, label=3, output_node=44, voltage=0.0018854581285268068\n    time_span=0.0001s, test_ID=195, label=3, output_node=45, voltage=0.0022300798445940018\n    time_span=0.0001s, test_ID=195, label=3, output_node=46, voltage=-0.00029681279556825757\n    time_span=0.0001s, test_ID=195, label=3, output_node=47, voltage=0.0011155377142131329\n    time_span=0.0001s, test_ID=195, label=3, output_node=48, voltage=0.005782868713140488\n    time_span=0.0001s, test_ID=195, label=3, output_node=49, voltage=-0.0007828685338608921\n    time_span=0.0001s, test_ID=195, label=3, output_node=50, voltage=0.007054781075567007\n    time_span=0.0001s, test_ID=195, label=3, output_node=51, voltage=0.005142430309206247\n    time_span=0.0001s, test_ID=195, label=3, output_node=52, voltage=0.004058764781802893\n    time_span=0.0001s, test_ID=195, label=3, output_node=53, voltage=0.0040876492857933044\n    time_span=0.0001s, test_ID=195, label=3, output_node=54, voltage=0.003320717252790928\n    time_span=0.0001s, test_ID=195, label=3, output_node=55, voltage=-0.0002619522565510124\n    time_span=0.0001s, test_ID=195, label=3, output_node=56, voltage=0.003303784877061844\n    time_span=0.0001s, test_ID=195, label=3, output_node=57, voltage=0.001954183215275407\n    time_span=0.0001s, test_ID=195, label=3, output_node=58, voltage=0.0016175296623259783\n    time_span=0.0001s, test_ID=195, label=3, output_node=59, voltage=0.0012918327702209353\n    time_span=0.0001s, test_ID=195, label=3, output_node=60, voltage=-6.972021765250247e-06\n    time_span=0.0001s, test_ID=195, label=3, output_node=61, voltage=0.002845617476850748\n    time_span=0.0001s, test_ID=195, label=3, output_node=62, voltage=0.0022151395678520203\n    time_span=0.0001s, test_ID=195, label=3, output_node=63, voltage=0.004481075797230005\n    time_span=0.0001s, test_ID=195, label=3, output_node=64, voltage=-0.00013247012975625694\n    time_span=0.0001s, test_ID=195, label=3, output_node=65, voltage=0.001464143511839211\n    time_span=0.0001s, test_ID=195, label=3, output_node=66, voltage=0.005170318763703108\n    time_span=0.0001s, test_ID=195, label=3, output_node=67, voltage=0.0006105576758272946\n    time_span=0.0001s, test_ID=195, label=3, output_node=68, voltage=0.0009721116512082517\n    time_span=0.0001s, test_ID=195, label=3, output_node=69, voltage=0.003058764850720763\n    time_span=0.0001s, test_ID=195, label=3, output_node=70, voltage=0.0030428285244852304\n    time_span=0.0001s, test_ID=195, label=3, output_node=71, voltage=0.002101593418046832\n    time_span=0.0001s, test_ID=195, label=3, output_node=72, voltage=0.0002171314408769831\n    time_span=0.0001s, test_ID=195, label=3, output_node=73, voltage=0.0034063744824379683\n    time_span=0.0001s, test_ID=195, label=3, output_node=74, voltage=0.0012320716632530093\n    time_span=0.0001s, test_ID=195, label=3, output_node=75, voltage=0.0048944223672151566\n    time_span=0.0001s, test_ID=195, label=3, output_node=76, voltage=0.0018256971379742026\n    time_span=0.0001s, test_ID=195, label=3, output_node=77, voltage=0.0025627489667385817\n    time_span=0.0001s, test_ID=195, label=3, output_node=78, voltage=-7.968131831148639e-05\n    time_span=0.0001s, test_ID=195, label=3, output_node=79, voltage=-2.4900344214984216e-05\n    time_span=0.0001s, test_ID=195, label=3, output_node=80, voltage=-3.585658851079643e-05\n    time_span=0.0001s, test_ID=195, label=3, output_node=81, voltage=0.002371513983234763\n    time_span=0.0001s, test_ID=195, label=3, output_node=82, voltage=0.004941234830766916\n    time_span=0.0001s, test_ID=195, label=3, output_node=83, voltage=0.0002460161049384624\n    time_span=0.0001s, test_ID=195, label=3, output_node=84, voltage=0.0025408368092030287\n    time_span=0.0001s, test_ID=195, label=3, output_node=85, voltage=0.002510956022888422\n    time_span=0.0001s, test_ID=195, label=3, output_node=86, voltage=0.0010627490701153874\n    time_span=0.0001s, test_ID=195, label=3, output_node=87, voltage=0.0011334660230204463\n    time_span=0.0001s, test_ID=195, label=3, output_node=88, voltage=0.0005318725598044693\n    time_span=0.0001s, test_ID=195, label=3, output_node=89, voltage=-0.00028685247525572777\n    time_span=0.0001s, test_ID=195, label=3, output_node=90, voltage=0.0021852590143680573\n    time_span=0.0001s, test_ID=195, label=3, output_node=91, voltage=0.0026663346216082573\n    time_span=0.0001s, test_ID=195, label=3, output_node=92, voltage=0.0008446215651929379\n    time_span=0.0001s, test_ID=195, label=3, output_node=93, voltage=0.0011762948706746101\n    time_span=0.0001s, test_ID=195, label=3, output_node=94, voltage=0.0008625497575849295\n    time_span=0.0001s, test_ID=195, label=3, output_node=95, voltage=-0.0018615537555888295\n    time_span=0.0001s, test_ID=195, label=3, output_node=96, voltage=0.0009671314619481564\n    time_span=0.0001s, test_ID=195, label=3, output_node=97, voltage=-0.0006075695855543017\n    time_span=0.0001s, test_ID=195, label=3, output_node=98, voltage=0.0011882471153512597\n    time_span=0.0001s, test_ID=195, label=3, output_node=99, voltage=0.0005089641781523824\n    time_span=0.0001s, test_ID=195, label=3, output_node=sum, voltage=0.010706175118684769\n    Time consumed for 1 sample = 625.1107811927795 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '195'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=196, label=1, output_node=bkg, voltage=-0.003730079857632518\n    time_span=0.0001s, test_ID=196, label=1, output_node=0, voltage=0.006988047622144222\n    time_span=0.0001s, test_ID=196, label=1, output_node=1, voltage=0.012644422240555286\n    time_span=0.0001s, test_ID=196, label=1, output_node=2, voltage=0.0055448212660849094\n    time_span=0.0001s, test_ID=196, label=1, output_node=3, voltage=0.005519920494407415\n    time_span=0.0001s, test_ID=196, label=1, output_node=4, voltage=0.003015936352312565\n    time_span=0.0001s, test_ID=196, label=1, output_node=5, voltage=0.00560358539223671\n    time_span=0.0001s, test_ID=196, label=1, output_node=6, voltage=0.007257967721670866\n    time_span=0.0001s, test_ID=196, label=1, output_node=7, voltage=0.0032808766700327396\n    time_span=0.0001s, test_ID=196, label=1, output_node=8, voltage=0.0063874502666294575\n    time_span=0.0001s, test_ID=196, label=1, output_node=9, voltage=0.00711454264819622\n    time_span=0.0001s, test_ID=196, label=1, output_node=10, voltage=0.009292828850448132\n    time_span=0.0001s, test_ID=196, label=1, output_node=11, voltage=0.004914342425763607\n    time_span=0.0001s, test_ID=196, label=1, output_node=12, voltage=0.00909661315381527\n    time_span=0.0001s, test_ID=196, label=1, output_node=13, voltage=0.005957171320915222\n    time_span=0.0001s, test_ID=196, label=1, output_node=14, voltage=0.006242032162845135\n    time_span=0.0001s, test_ID=196, label=1, output_node=15, voltage=0.01150199119001627\n    time_span=0.0001s, test_ID=196, label=1, output_node=16, voltage=0.012581673450767994\n    time_span=0.0001s, test_ID=196, label=1, output_node=17, voltage=0.009542828425765038\n    time_span=0.0001s, test_ID=196, label=1, output_node=18, voltage=0.007994024083018303\n    time_span=0.0001s, test_ID=196, label=1, output_node=19, voltage=0.008496016263961792\n    time_span=0.0001s, test_ID=196, label=1, output_node=20, voltage=0.0118695218116045\n    time_span=0.0001s, test_ID=196, label=1, output_node=21, voltage=0.00609860522672534\n    time_span=0.0001s, test_ID=196, label=1, output_node=22, voltage=0.005673306994140148\n    time_span=0.0001s, test_ID=196, label=1, output_node=23, voltage=0.008492032065987587\n    time_span=0.0001s, test_ID=196, label=1, output_node=24, voltage=0.005487051792442799\n    time_span=0.0001s, test_ID=196, label=1, output_node=25, voltage=0.00859462097287178\n    time_span=0.0001s, test_ID=196, label=1, output_node=26, voltage=0.004163346718996763\n    time_span=0.0001s, test_ID=196, label=1, output_node=27, voltage=0.010383466258645058\n    time_span=0.0001s, test_ID=196, label=1, output_node=28, voltage=0.00971513893455267\n    time_span=0.0001s, test_ID=196, label=1, output_node=29, voltage=0.012388446368277073\n    time_span=0.0001s, test_ID=196, label=1, output_node=30, voltage=0.007782868575304747\n    time_span=0.0001s, test_ID=196, label=1, output_node=31, voltage=0.008312749676406384\n    time_span=0.0001s, test_ID=196, label=1, output_node=32, voltage=0.006113545503467321\n    time_span=0.0001s, test_ID=196, label=1, output_node=33, voltage=0.01340637356042862\n    time_span=0.0001s, test_ID=196, label=1, output_node=34, voltage=0.01156673301011324\n    time_span=0.0001s, test_ID=196, label=1, output_node=35, voltage=0.009866533800959587\n    time_span=0.0001s, test_ID=196, label=1, output_node=36, voltage=0.006241035647690296\n    time_span=0.0001s, test_ID=196, label=1, output_node=37, voltage=0.004772908054292202\n    time_span=0.0001s, test_ID=196, label=1, output_node=38, voltage=0.00482868542894721\n    time_span=0.0001s, test_ID=196, label=1, output_node=39, voltage=0.008383465930819511\n    time_span=0.0001s, test_ID=196, label=1, output_node=40, voltage=0.00481274863705039\n    time_span=0.0001s, test_ID=196, label=1, output_node=41, voltage=0.008739043958485126\n    time_span=0.0001s, test_ID=196, label=1, output_node=42, voltage=0.004183266777545214\n    time_span=0.0001s, test_ID=196, label=1, output_node=43, voltage=0.00794820673763752\n    time_span=0.0001s, test_ID=196, label=1, output_node=44, voltage=0.006766933016479015\n    time_span=0.0001s, test_ID=196, label=1, output_node=45, voltage=0.006840637419372797\n    time_span=0.0001s, test_ID=196, label=1, output_node=46, voltage=0.003428286872804165\n    time_span=0.0001s, test_ID=196, label=1, output_node=47, voltage=0.003084661206230521\n    time_span=0.0001s, test_ID=196, label=1, output_node=48, voltage=0.0034342629369348288\n    time_span=0.0001s, test_ID=196, label=1, output_node=49, voltage=0.011743026785552502\n    time_span=0.0001s, test_ID=196, label=1, output_node=50, voltage=0.013495019637048244\n    time_span=0.0001s, test_ID=196, label=1, output_node=51, voltage=0.0046972110867500305\n    time_span=0.0001s, test_ID=196, label=1, output_node=52, voltage=0.010847610421478748\n    time_span=0.0001s, test_ID=196, label=1, output_node=53, voltage=0.008082669228315353\n    time_span=0.0001s, test_ID=196, label=1, output_node=54, voltage=0.005560757126659155\n    time_span=0.0001s, test_ID=196, label=1, output_node=55, voltage=0.005867529660463333\n    time_span=0.0001s, test_ID=196, label=1, output_node=56, voltage=0.003681275062263012\n    time_span=0.0001s, test_ID=196, label=1, output_node=57, voltage=0.006382470019161701\n    time_span=0.0001s, test_ID=196, label=1, output_node=58, voltage=0.009083665907382965\n    time_span=0.0001s, test_ID=196, label=1, output_node=59, voltage=0.0069581675343215466\n    time_span=0.0001s, test_ID=196, label=1, output_node=60, voltage=0.0039541833102703094\n    time_span=0.0001s, test_ID=196, label=1, output_node=61, voltage=0.004489043727517128\n    time_span=0.0001s, test_ID=196, label=1, output_node=62, voltage=0.01363944262266159\n    time_span=0.0001s, test_ID=196, label=1, output_node=63, voltage=0.007622509729117155\n    time_span=0.0001s, test_ID=196, label=1, output_node=64, voltage=0.007694222964346409\n    time_span=0.0001s, test_ID=196, label=1, output_node=65, voltage=0.008814741857349873\n    time_span=0.0001s, test_ID=196, label=1, output_node=66, voltage=0.008603585883975029\n    time_span=0.0001s, test_ID=196, label=1, output_node=67, voltage=0.004488048143684864\n    time_span=0.0001s, test_ID=196, label=1, output_node=68, voltage=0.011701194569468498\n    time_span=0.0001s, test_ID=196, label=1, output_node=69, voltage=0.009351593442261219\n    time_span=0.0001s, test_ID=196, label=1, output_node=70, voltage=0.008145418018102646\n    time_span=0.0001s, test_ID=196, label=1, output_node=71, voltage=0.006830677390098572\n    time_span=0.0001s, test_ID=196, label=1, output_node=72, voltage=0.010017928667366505\n    time_span=0.0001s, test_ID=196, label=1, output_node=73, voltage=0.002658366458490491\n    time_span=0.0001s, test_ID=196, label=1, output_node=74, voltage=0.01120717078447342\n    time_span=0.0001s, test_ID=196, label=1, output_node=75, voltage=0.007569720968604088\n    time_span=0.0001s, test_ID=196, label=1, output_node=76, voltage=0.0049501992762088776\n    time_span=0.0001s, test_ID=196, label=1, output_node=77, voltage=0.0099850594997406\n    time_span=0.0001s, test_ID=196, label=1, output_node=78, voltage=0.010164342820644379\n    time_span=0.0001s, test_ID=196, label=1, output_node=79, voltage=0.00805278867483139\n    time_span=0.0001s, test_ID=196, label=1, output_node=80, voltage=0.005141433794051409\n    time_span=0.0001s, test_ID=196, label=1, output_node=81, voltage=0.007388446480035782\n    time_span=0.0001s, test_ID=196, label=1, output_node=82, voltage=0.00687848636880517\n    time_span=0.0001s, test_ID=196, label=1, output_node=83, voltage=0.008965139277279377\n    time_span=0.0001s, test_ID=196, label=1, output_node=84, voltage=0.005487051792442799\n    time_span=0.0001s, test_ID=196, label=1, output_node=85, voltage=0.007722111884504557\n    time_span=0.0001s, test_ID=196, label=1, output_node=86, voltage=0.006392430514097214\n    time_span=0.0001s, test_ID=196, label=1, output_node=87, voltage=0.0015906376065686345\n    time_span=0.0001s, test_ID=196, label=1, output_node=88, voltage=0.007264940068125725\n    time_span=0.0001s, test_ID=196, label=1, output_node=89, voltage=0.005687251221388578\n    time_span=0.0001s, test_ID=196, label=1, output_node=90, voltage=0.00823107548058033\n    time_span=0.0001s, test_ID=196, label=1, output_node=91, voltage=0.009178287349641323\n    time_span=0.0001s, test_ID=196, label=1, output_node=92, voltage=0.013495019637048244\n    time_span=0.0001s, test_ID=196, label=1, output_node=93, voltage=0.006514939945191145\n    time_span=0.0001s, test_ID=196, label=1, output_node=94, voltage=0.010468128137290478\n    time_span=0.0001s, test_ID=196, label=1, output_node=95, voltage=0.014046812430024147\n    time_span=0.0001s, test_ID=196, label=1, output_node=96, voltage=0.009836654178798199\n    time_span=0.0001s, test_ID=196, label=1, output_node=97, voltage=0.007157370448112488\n    time_span=0.0001s, test_ID=196, label=1, output_node=98, voltage=0.008349602110683918\n    time_span=0.0001s, test_ID=196, label=1, output_node=99, voltage=0.005976095795631409\n    time_span=0.0001s, test_ID=196, label=1, output_node=sum, voltage=0.02557270973920822\n    Time consumed for 1 sample = 625.1571102142334 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '196'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=197, label=6, output_node=bkg, voltage=-0.007271912414580584\n    time_span=0.0001s, test_ID=197, label=6, output_node=0, voltage=0.006547808647155762\n    time_span=0.0001s, test_ID=197, label=6, output_node=1, voltage=0.013249004259705544\n    time_span=0.0001s, test_ID=197, label=6, output_node=2, voltage=0.012923306785523891\n    time_span=0.0001s, test_ID=197, label=6, output_node=3, voltage=0.005179282743483782\n    time_span=0.0001s, test_ID=197, label=6, output_node=4, voltage=0.011773904785513878\n    time_span=0.0001s, test_ID=197, label=6, output_node=5, voltage=0.017254982143640518\n    time_span=0.0001s, test_ID=197, label=6, output_node=6, voltage=0.01993725076317787\n    time_span=0.0001s, test_ID=197, label=6, output_node=7, voltage=0.0037749004550278187\n    time_span=0.0001s, test_ID=197, label=6, output_node=8, voltage=0.007940239273011684\n    time_span=0.0001s, test_ID=197, label=6, output_node=9, voltage=0.008575696498155594\n    time_span=0.0001s, test_ID=197, label=6, output_node=10, voltage=0.012712151743471622\n    time_span=0.0001s, test_ID=197, label=6, output_node=11, voltage=0.0060737053863704205\n    time_span=0.0001s, test_ID=197, label=6, output_node=12, voltage=0.009063745848834515\n    time_span=0.0001s, test_ID=197, label=6, output_node=13, voltage=0.003876493778079748\n    time_span=0.0001s, test_ID=197, label=6, output_node=14, voltage=0.008431275375187397\n    time_span=0.0001s, test_ID=197, label=6, output_node=15, voltage=0.008007967844605446\n    time_span=0.0001s, test_ID=197, label=6, output_node=16, voltage=0.010087649337947369\n    time_span=0.0001s, test_ID=197, label=6, output_node=17, voltage=0.014773904345929623\n    time_span=0.0001s, test_ID=197, label=6, output_node=18, voltage=0.009672311134636402\n    time_span=0.0001s, test_ID=197, label=6, output_node=19, voltage=0.008102590218186378\n    time_span=0.0001s, test_ID=197, label=6, output_node=20, voltage=0.012957172468304634\n    time_span=0.0001s, test_ID=197, label=6, output_node=21, voltage=0.007607569452375174\n    time_span=0.0001s, test_ID=197, label=6, output_node=22, voltage=0.012514940463006496\n    time_span=0.0001s, test_ID=197, label=6, output_node=23, voltage=0.009554781019687653\n    time_span=0.0001s, test_ID=197, label=6, output_node=24, voltage=0.0109760956838727\n    time_span=0.0001s, test_ID=197, label=6, output_node=25, voltage=0.013621513731777668\n    time_span=0.0001s, test_ID=197, label=6, output_node=26, voltage=0.007144422270357609\n    time_span=0.0001s, test_ID=197, label=6, output_node=27, voltage=0.007723107468336821\n    time_span=0.0001s, test_ID=197, label=6, output_node=28, voltage=0.011730080470442772\n    time_span=0.0001s, test_ID=197, label=6, output_node=29, voltage=0.01370517909526825\n    time_span=0.0001s, test_ID=197, label=6, output_node=30, voltage=0.006350597366690636\n    time_span=0.0001s, test_ID=197, label=6, output_node=31, voltage=0.007233067881315947\n    time_span=0.0001s, test_ID=197, label=6, output_node=32, voltage=0.003554781200364232\n    time_span=0.0001s, test_ID=197, label=6, output_node=33, voltage=0.008779880590736866\n    time_span=0.0001s, test_ID=197, label=6, output_node=34, voltage=0.013405377976596355\n    time_span=0.0001s, test_ID=197, label=6, output_node=35, voltage=0.010060756467282772\n    time_span=0.0001s, test_ID=197, label=6, output_node=36, voltage=0.014142430387437344\n    time_span=0.0001s, test_ID=197, label=6, output_node=37, voltage=0.014874502085149288\n    time_span=0.0001s, test_ID=197, label=6, output_node=38, voltage=0.011157370172441006\n    time_span=0.0001s, test_ID=197, label=6, output_node=39, voltage=0.009038844145834446\n    time_span=0.0001s, test_ID=197, label=6, output_node=40, voltage=0.01090239081531763\n    time_span=0.0001s, test_ID=197, label=6, output_node=41, voltage=0.0032370518893003464\n    time_span=0.0001s, test_ID=197, label=6, output_node=42, voltage=0.010359562002122402\n    time_span=0.0001s, test_ID=197, label=6, output_node=43, voltage=0.00887748971581459\n    time_span=0.0001s, test_ID=197, label=6, output_node=44, voltage=0.007969123311340809\n    time_span=0.0001s, test_ID=197, label=6, output_node=45, voltage=0.011741035617887974\n    time_span=0.0001s, test_ID=197, label=6, output_node=46, voltage=0.007396414410322905\n    time_span=0.0001s, test_ID=197, label=6, output_node=47, voltage=0.006505975965410471\n    time_span=0.0001s, test_ID=197, label=6, output_node=48, voltage=0.009062749333679676\n    time_span=0.0001s, test_ID=197, label=6, output_node=49, voltage=0.005009959917515516\n    time_span=0.0001s, test_ID=197, label=6, output_node=50, voltage=0.01478784903883934\n    time_span=0.0001s, test_ID=197, label=6, output_node=51, voltage=0.01108565740287304\n    time_span=0.0001s, test_ID=197, label=6, output_node=52, voltage=0.0007659363327547908\n    time_span=0.0001s, test_ID=197, label=6, output_node=53, voltage=0.009443226270377636\n    time_span=0.0001s, test_ID=197, label=6, output_node=54, voltage=0.010720119811594486\n    time_span=0.0001s, test_ID=197, label=6, output_node=55, voltage=0.010943226516246796\n    time_span=0.0001s, test_ID=197, label=6, output_node=56, voltage=0.010040836408734322\n    time_span=0.0001s, test_ID=197, label=6, output_node=57, voltage=0.0103575699031353\n    time_span=0.0001s, test_ID=197, label=6, output_node=58, voltage=0.008756971918046474\n    time_span=0.0001s, test_ID=197, label=6, output_node=59, voltage=0.008187251165509224\n    time_span=0.0001s, test_ID=197, label=6, output_node=60, voltage=0.009702191688120365\n    time_span=0.0001s, test_ID=197, label=6, output_node=61, voltage=0.0077360556460917\n    time_span=0.0001s, test_ID=197, label=6, output_node=62, voltage=0.004941234830766916\n    time_span=0.0001s, test_ID=197, label=6, output_node=63, voltage=0.009764940477907658\n    time_span=0.0001s, test_ID=197, label=6, output_node=64, voltage=0.011793823912739754\n    time_span=0.0001s, test_ID=197, label=6, output_node=65, voltage=0.00865936279296875\n    time_span=0.0001s, test_ID=197, label=6, output_node=66, voltage=0.007791832555085421\n    time_span=0.0001s, test_ID=197, label=6, output_node=67, voltage=0.007779880426824093\n    time_span=0.0001s, test_ID=197, label=6, output_node=68, voltage=0.008686254732310772\n    time_span=0.0001s, test_ID=197, label=6, output_node=69, voltage=0.007787847891449928\n    time_span=0.0001s, test_ID=197, label=6, output_node=70, voltage=0.013339641503989697\n    time_span=0.0001s, test_ID=197, label=6, output_node=71, voltage=0.011234063655138016\n    time_span=0.0001s, test_ID=197, label=6, output_node=72, voltage=0.005809761118143797\n    time_span=0.0001s, test_ID=197, label=6, output_node=73, voltage=0.01014741137623787\n    time_span=0.0001s, test_ID=197, label=6, output_node=74, voltage=0.008002988062798977\n    time_span=0.0001s, test_ID=197, label=6, output_node=75, voltage=0.011993028223514557\n    time_span=0.0001s, test_ID=197, label=6, output_node=76, voltage=0.011105578392744064\n    time_span=0.0001s, test_ID=197, label=6, output_node=77, voltage=0.008992032147943974\n    time_span=0.0001s, test_ID=197, label=6, output_node=78, voltage=0.008622510358691216\n    time_span=0.0001s, test_ID=197, label=6, output_node=79, voltage=0.01026493962854147\n    time_span=0.0001s, test_ID=197, label=6, output_node=80, voltage=0.008689243346452713\n    time_span=0.0001s, test_ID=197, label=6, output_node=81, voltage=0.009687250480055809\n    time_span=0.0001s, test_ID=197, label=6, output_node=82, voltage=0.015329682268202305\n    time_span=0.0001s, test_ID=197, label=6, output_node=83, voltage=0.012238048017024994\n    time_span=0.0001s, test_ID=197, label=6, output_node=84, voltage=0.017009960487484932\n    time_span=0.0001s, test_ID=197, label=6, output_node=85, voltage=0.012478087097406387\n    time_span=0.0001s, test_ID=197, label=6, output_node=86, voltage=0.0018595617730170488\n    time_span=0.0001s, test_ID=197, label=6, output_node=87, voltage=0.008056772872805595\n    time_span=0.0001s, test_ID=197, label=6, output_node=88, voltage=0.006912350654602051\n    time_span=0.0001s, test_ID=197, label=6, output_node=89, voltage=0.012528885155916214\n    time_span=0.0001s, test_ID=197, label=6, output_node=90, voltage=0.006802788935601711\n    time_span=0.0001s, test_ID=197, label=6, output_node=91, voltage=0.01399900484830141\n    time_span=0.0001s, test_ID=197, label=6, output_node=92, voltage=0.010879481211304665\n    time_span=0.0001s, test_ID=197, label=6, output_node=93, voltage=0.004512948449701071\n    time_span=0.0001s, test_ID=197, label=6, output_node=94, voltage=0.01257270947098732\n    time_span=0.0001s, test_ID=197, label=6, output_node=95, voltage=0.011313743889331818\n    time_span=0.0001s, test_ID=197, label=6, output_node=96, voltage=0.008462151512503624\n    time_span=0.0001s, test_ID=197, label=6, output_node=97, voltage=0.006037849001586437\n    time_span=0.0001s, test_ID=197, label=6, output_node=98, voltage=0.00965836737304926\n    time_span=0.0001s, test_ID=197, label=6, output_node=99, voltage=0.0031354581005871296\n    time_span=0.0001s, test_ID=197, label=6, output_node=sum, voltage=0.02812948264181614\n    Time consumed for 1 sample = 625.0127325057983 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '197'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=198, label=4, output_node=bkg, voltage=-0.005246016196906567\n    time_span=0.0001s, test_ID=198, label=4, output_node=0, voltage=0.023278886452317238\n    time_span=0.0001s, test_ID=198, label=4, output_node=1, voltage=0.023574700579047203\n    time_span=0.0001s, test_ID=198, label=4, output_node=2, voltage=0.018057769164443016\n    time_span=0.0001s, test_ID=198, label=4, output_node=3, voltage=0.015258966013789177\n    time_span=0.0001s, test_ID=198, label=4, output_node=4, voltage=0.01343824714422226\n    time_span=0.0001s, test_ID=198, label=4, output_node=5, voltage=0.020442230626940727\n    time_span=0.0001s, test_ID=198, label=4, output_node=6, voltage=0.019465139135718346\n    time_span=0.0001s, test_ID=198, label=4, output_node=7, voltage=0.02159561775624752\n    time_span=0.0001s, test_ID=198, label=4, output_node=8, voltage=0.01948506012558937\n    time_span=0.0001s, test_ID=198, label=4, output_node=9, voltage=0.011081674136221409\n    time_span=0.0001s, test_ID=198, label=4, output_node=10, voltage=0.01709263026714325\n    time_span=0.0001s, test_ID=198, label=4, output_node=11, voltage=0.017476094886660576\n    time_span=0.0001s, test_ID=198, label=4, output_node=12, voltage=0.020839640870690346\n    time_span=0.0001s, test_ID=198, label=4, output_node=13, voltage=0.01878386363387108\n    time_span=0.0001s, test_ID=198, label=4, output_node=14, voltage=0.012208167463541031\n    time_span=0.0001s, test_ID=198, label=4, output_node=15, voltage=0.022716134786605835\n    time_span=0.0001s, test_ID=198, label=4, output_node=16, voltage=0.018181271851062775\n    time_span=0.0001s, test_ID=198, label=4, output_node=17, voltage=0.017301790416240692\n    time_span=0.0001s, test_ID=198, label=4, output_node=18, voltage=0.021932272240519524\n    time_span=0.0001s, test_ID=198, label=4, output_node=19, voltage=0.02059462107717991\n    time_span=0.0001s, test_ID=198, label=4, output_node=20, voltage=0.015549801290035248\n    time_span=0.0001s, test_ID=198, label=4, output_node=21, voltage=0.011380478739738464\n    time_span=0.0001s, test_ID=198, label=4, output_node=22, voltage=0.011496015824377537\n    time_span=0.0001s, test_ID=198, label=4, output_node=23, voltage=0.016885457560420036\n    time_span=0.0001s, test_ID=198, label=4, output_node=24, voltage=0.02098008058965206\n    time_span=0.0001s, test_ID=198, label=4, output_node=25, voltage=0.016966136172413826\n    time_span=0.0001s, test_ID=198, label=4, output_node=26, voltage=0.019473105669021606\n    time_span=0.0001s, test_ID=198, label=4, output_node=27, voltage=0.02824103645980358\n    time_span=0.0001s, test_ID=198, label=4, output_node=28, voltage=0.014596613124012947\n    time_span=0.0001s, test_ID=198, label=4, output_node=29, voltage=0.01942928321659565\n    time_span=0.0001s, test_ID=198, label=4, output_node=30, voltage=0.020750001072883606\n    time_span=0.0001s, test_ID=198, label=4, output_node=31, voltage=0.02141035906970501\n    time_span=0.0001s, test_ID=198, label=4, output_node=32, voltage=0.011743027716875076\n    time_span=0.0001s, test_ID=198, label=4, output_node=33, voltage=0.022305777296423912\n    time_span=0.0001s, test_ID=198, label=4, output_node=34, voltage=0.015770917758345604\n    time_span=0.0001s, test_ID=198, label=4, output_node=35, voltage=0.023354582488536835\n    time_span=0.0001s, test_ID=198, label=4, output_node=36, voltage=0.023774901404976845\n    time_span=0.0001s, test_ID=198, label=4, output_node=37, voltage=0.016530876979231834\n    time_span=0.0001s, test_ID=198, label=4, output_node=38, voltage=0.01017131470143795\n    time_span=0.0001s, test_ID=198, label=4, output_node=39, voltage=0.017143426463007927\n    time_span=0.0001s, test_ID=198, label=4, output_node=40, voltage=0.014827690087258816\n    time_span=0.0001s, test_ID=198, label=4, output_node=41, voltage=0.0097390441223979\n    time_span=0.0001s, test_ID=198, label=4, output_node=42, voltage=0.02027888596057892\n    time_span=0.0001s, test_ID=198, label=4, output_node=43, voltage=0.017146414145827293\n    time_span=0.0001s, test_ID=198, label=4, output_node=44, voltage=0.022921312600374222\n    time_span=0.0001s, test_ID=198, label=4, output_node=45, voltage=0.019094623625278473\n    time_span=0.0001s, test_ID=198, label=4, output_node=46, voltage=0.00965438224375248\n    time_span=0.0001s, test_ID=198, label=4, output_node=47, voltage=0.016408365219831467\n    time_span=0.0001s, test_ID=198, label=4, output_node=48, voltage=0.019346613436937332\n    time_span=0.0001s, test_ID=198, label=4, output_node=49, voltage=0.019451195374131203\n    time_span=0.0001s, test_ID=198, label=4, output_node=50, voltage=0.021728085353970528\n    time_span=0.0001s, test_ID=198, label=4, output_node=51, voltage=0.02022111415863037\n    time_span=0.0001s, test_ID=198, label=4, output_node=52, voltage=0.019876495003700256\n    time_span=0.0001s, test_ID=198, label=4, output_node=53, voltage=0.020742032676935196\n    time_span=0.0001s, test_ID=198, label=4, output_node=54, voltage=0.01088645402342081\n    time_span=0.0001s, test_ID=198, label=4, output_node=55, voltage=0.01786952279508114\n    time_span=0.0001s, test_ID=198, label=4, output_node=56, voltage=0.019844621419906616\n    time_span=0.0001s, test_ID=198, label=4, output_node=57, voltage=0.023904383182525635\n    time_span=0.0001s, test_ID=198, label=4, output_node=58, voltage=0.013097609393298626\n    time_span=0.0001s, test_ID=198, label=4, output_node=59, voltage=0.015383466146886349\n    time_span=0.0001s, test_ID=198, label=4, output_node=60, voltage=0.016068726778030396\n    time_span=0.0001s, test_ID=198, label=4, output_node=61, voltage=0.018899403512477875\n    time_span=0.0001s, test_ID=198, label=4, output_node=62, voltage=0.010213146917521954\n    time_span=0.0001s, test_ID=198, label=4, output_node=63, voltage=0.019667331129312515\n    time_span=0.0001s, test_ID=198, label=4, output_node=64, voltage=0.021001992747187614\n    time_span=0.0001s, test_ID=198, label=4, output_node=65, voltage=0.01991533674299717\n    time_span=0.0001s, test_ID=198, label=4, output_node=66, voltage=0.016854580491781235\n    time_span=0.0001s, test_ID=198, label=4, output_node=67, voltage=0.014755976386368275\n    time_span=0.0001s, test_ID=198, label=4, output_node=68, voltage=0.020303785800933838\n    time_span=0.0001s, test_ID=198, label=4, output_node=69, voltage=0.013881474733352661\n    time_span=0.0001s, test_ID=198, label=4, output_node=70, voltage=0.018278883770108223\n    time_span=0.0001s, test_ID=198, label=4, output_node=71, voltage=0.012973107397556305\n    time_span=0.0001s, test_ID=198, label=4, output_node=72, voltage=0.01684163324534893\n    time_span=0.0001s, test_ID=198, label=4, output_node=73, voltage=0.0255747027695179\n    time_span=0.0001s, test_ID=198, label=4, output_node=74, voltage=0.025653386488556862\n    time_span=0.0001s, test_ID=198, label=4, output_node=75, voltage=0.01174800843000412\n    time_span=0.0001s, test_ID=198, label=4, output_node=76, voltage=0.025326695293188095\n    time_span=0.0001s, test_ID=198, label=4, output_node=77, voltage=0.01847410388290882\n    time_span=0.0001s, test_ID=198, label=4, output_node=78, voltage=0.017454182729125023\n    time_span=0.0001s, test_ID=198, label=4, output_node=79, voltage=0.013528884388506413\n    time_span=0.0001s, test_ID=198, label=4, output_node=80, voltage=0.017662351951003075\n    time_span=0.0001s, test_ID=198, label=4, output_node=81, voltage=0.007237051613628864\n    time_span=0.0001s, test_ID=198, label=4, output_node=82, voltage=0.019422311335802078\n    time_span=0.0001s, test_ID=198, label=4, output_node=83, voltage=0.024974102154374123\n    time_span=0.0001s, test_ID=198, label=4, output_node=84, voltage=0.013632470741868019\n    time_span=0.0001s, test_ID=198, label=4, output_node=85, voltage=0.021542830392718315\n    time_span=0.0001s, test_ID=198, label=4, output_node=86, voltage=0.01937250979244709\n    time_span=0.0001s, test_ID=198, label=4, output_node=87, voltage=0.02099800854921341\n    time_span=0.0001s, test_ID=198, label=4, output_node=88, voltage=0.014423307962715626\n    time_span=0.0001s, test_ID=198, label=4, output_node=89, voltage=0.013072709552943707\n    time_span=0.0001s, test_ID=198, label=4, output_node=90, voltage=0.018981074914336205\n    time_span=0.0001s, test_ID=198, label=4, output_node=91, voltage=0.01732669398188591\n    time_span=0.0001s, test_ID=198, label=4, output_node=92, voltage=0.026877490803599358\n    time_span=0.0001s, test_ID=198, label=4, output_node=93, voltage=0.023073704913258553\n    time_span=0.0001s, test_ID=198, label=4, output_node=94, voltage=0.02455677092075348\n    time_span=0.0001s, test_ID=198, label=4, output_node=95, voltage=0.03173306584358215\n    time_span=0.0001s, test_ID=198, label=4, output_node=96, voltage=0.025796812027692795\n    time_span=0.0001s, test_ID=198, label=4, output_node=97, voltage=0.011350597254931927\n    time_span=0.0001s, test_ID=198, label=4, output_node=98, voltage=0.01937350630760193\n    time_span=0.0001s, test_ID=198, label=4, output_node=99, voltage=0.02110259048640728\n    time_span=0.0001s, test_ID=198, label=4, output_node=sum, voltage=0.048226095736026764\n    Time consumed for 1 sample = 628.3138289451599 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '198'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    time_span=0.0001s, test_ID=199, label=2, output_node=bkg, voltage=-0.004962151870131493\n    time_span=0.0001s, test_ID=199, label=2, output_node=0, voltage=0.025384461507201195\n    time_span=0.0001s, test_ID=199, label=2, output_node=1, voltage=0.017056772485375404\n    time_span=0.0001s, test_ID=199, label=2, output_node=2, voltage=0.026743028312921524\n    time_span=0.0001s, test_ID=199, label=2, output_node=3, voltage=0.014409362338483334\n    time_span=0.0001s, test_ID=199, label=2, output_node=4, voltage=0.030002988874912262\n    time_span=0.0001s, test_ID=199, label=2, output_node=5, voltage=0.028739044442772865\n    time_span=0.0001s, test_ID=199, label=2, output_node=6, voltage=0.0260358564555645\n    time_span=0.0001s, test_ID=199, label=2, output_node=7, voltage=0.023720117285847664\n    time_span=0.0001s, test_ID=199, label=2, output_node=8, voltage=0.033751994371414185\n    time_span=0.0001s, test_ID=199, label=2, output_node=9, voltage=0.03199202939867973\n    time_span=0.0001s, test_ID=199, label=2, output_node=10, voltage=0.01887848600745201\n    time_span=0.0001s, test_ID=199, label=2, output_node=11, voltage=0.029862551018595695\n    time_span=0.0001s, test_ID=199, label=2, output_node=12, voltage=0.021363547071814537\n    time_span=0.0001s, test_ID=199, label=2, output_node=13, voltage=0.03428984433412552\n    time_span=0.0001s, test_ID=199, label=2, output_node=14, voltage=0.02260657213628292\n    time_span=0.0001s, test_ID=199, label=2, output_node=15, voltage=0.02843725122511387\n    time_span=0.0001s, test_ID=199, label=2, output_node=16, voltage=0.023194223642349243\n    time_span=0.0001s, test_ID=199, label=2, output_node=17, voltage=0.025330675765872\n    time_span=0.0001s, test_ID=199, label=2, output_node=18, voltage=0.030475100502371788\n    time_span=0.0001s, test_ID=199, label=2, output_node=19, voltage=0.02379482053220272\n    time_span=0.0001s, test_ID=199, label=2, output_node=20, voltage=0.031054779887199402\n    time_span=0.0001s, test_ID=199, label=2, output_node=21, voltage=0.026791833341121674\n    time_span=0.0001s, test_ID=199, label=2, output_node=22, voltage=0.02671513892710209\n    time_span=0.0001s, test_ID=199, label=2, output_node=23, voltage=0.02729780785739422\n    time_span=0.0001s, test_ID=199, label=2, output_node=24, voltage=0.03428386151790619\n    time_span=0.0001s, test_ID=199, label=2, output_node=25, voltage=0.025481075048446655\n    time_span=0.0001s, test_ID=199, label=2, output_node=26, voltage=0.028563745319843292\n    time_span=0.0001s, test_ID=199, label=2, output_node=27, voltage=0.009334661066532135\n    time_span=0.0001s, test_ID=199, label=2, output_node=28, voltage=0.02522709220647812\n    time_span=0.0001s, test_ID=199, label=2, output_node=29, voltage=0.024657370522618294\n    time_span=0.0001s, test_ID=199, label=2, output_node=30, voltage=0.023703189566731453\n    time_span=0.0001s, test_ID=199, label=2, output_node=31, voltage=0.023206176236271858\n    time_span=0.0001s, test_ID=199, label=2, output_node=32, voltage=0.027017928659915924\n    time_span=0.0001s, test_ID=199, label=2, output_node=33, voltage=0.018470117822289467\n    time_span=0.0001s, test_ID=199, label=2, output_node=34, voltage=0.019102590158581734\n    time_span=0.0001s, test_ID=199, label=2, output_node=35, voltage=0.018294820562005043\n    time_span=0.0001s, test_ID=199, label=2, output_node=36, voltage=0.028644423931837082\n    time_span=0.0001s, test_ID=199, label=2, output_node=37, voltage=0.020556772127747536\n    time_span=0.0001s, test_ID=199, label=2, output_node=38, voltage=0.028168324381113052\n    time_span=0.0001s, test_ID=199, label=2, output_node=39, voltage=0.02234860509634018\n    time_span=0.0001s, test_ID=199, label=2, output_node=40, voltage=0.029243027791380882\n    time_span=0.0001s, test_ID=199, label=2, output_node=41, voltage=0.024996014311909676\n    time_span=0.0001s, test_ID=199, label=2, output_node=42, voltage=0.028992030769586563\n    time_span=0.0001s, test_ID=199, label=2, output_node=43, voltage=0.029549799859523773\n    time_span=0.0001s, test_ID=199, label=2, output_node=44, voltage=0.030980080366134644\n    time_span=0.0001s, test_ID=199, label=2, output_node=45, voltage=0.03709661215543747\n    time_span=0.0001s, test_ID=199, label=2, output_node=46, voltage=0.023950200527906418\n    time_span=0.0001s, test_ID=199, label=2, output_node=47, voltage=0.021787848323583603\n    time_span=0.0001s, test_ID=199, label=2, output_node=48, voltage=0.018161356449127197\n    time_span=0.0001s, test_ID=199, label=2, output_node=49, voltage=0.027095617726445198\n    time_span=0.0001s, test_ID=199, label=2, output_node=50, voltage=0.02907470241189003\n    time_span=0.0001s, test_ID=199, label=2, output_node=51, voltage=0.030275896191596985\n    time_span=0.0001s, test_ID=199, label=2, output_node=52, voltage=0.029288845136761665\n    time_span=0.0001s, test_ID=199, label=2, output_node=53, voltage=0.028401393443346024\n    time_span=0.0001s, test_ID=199, label=2, output_node=54, voltage=0.02945617586374283\n    time_span=0.0001s, test_ID=199, label=2, output_node=55, voltage=0.024050796404480934\n    time_span=0.0001s, test_ID=199, label=2, output_node=56, voltage=0.020886452868580818\n    time_span=0.0001s, test_ID=199, label=2, output_node=57, voltage=0.02120916359126568\n    time_span=0.0001s, test_ID=199, label=2, output_node=58, voltage=0.032022908329963684\n    time_span=0.0001s, test_ID=199, label=2, output_node=59, voltage=0.027922311797738075\n    time_span=0.0001s, test_ID=199, label=2, output_node=60, voltage=0.01530976127833128\n    time_span=0.0001s, test_ID=199, label=2, output_node=61, voltage=0.0261553805321455\n    time_span=0.0001s, test_ID=199, label=2, output_node=62, voltage=0.019189244136214256\n    time_span=0.0001s, test_ID=199, label=2, output_node=63, voltage=0.026393426582217216\n    time_span=0.0001s, test_ID=199, label=2, output_node=64, voltage=0.022143429145216942\n    time_span=0.0001s, test_ID=199, label=2, output_node=65, voltage=0.02829183265566826\n    time_span=0.0001s, test_ID=199, label=2, output_node=66, voltage=0.030145417898893356\n    time_span=0.0001s, test_ID=199, label=2, output_node=67, voltage=0.028538843616843224\n    time_span=0.0001s, test_ID=199, label=2, output_node=68, voltage=0.021153384819626808\n    time_span=0.0001s, test_ID=199, label=2, output_node=69, voltage=0.023603586480021477\n    time_span=0.0001s, test_ID=199, label=2, output_node=70, voltage=0.018001994118094444\n    time_span=0.0001s, test_ID=199, label=2, output_node=71, voltage=0.026078686118125916\n    time_span=0.0001s, test_ID=199, label=2, output_node=72, voltage=0.025674303993582726\n    time_span=0.0001s, test_ID=199, label=2, output_node=73, voltage=0.030169323086738586\n    time_span=0.0001s, test_ID=199, label=2, output_node=74, voltage=0.03303585946559906\n    time_span=0.0001s, test_ID=199, label=2, output_node=75, voltage=0.0238854568451643\n    time_span=0.0001s, test_ID=199, label=2, output_node=76, voltage=0.02371514029800892\n    time_span=0.0001s, test_ID=199, label=2, output_node=77, voltage=0.029840640723705292\n    time_span=0.0001s, test_ID=199, label=2, output_node=78, voltage=0.029069721698760986\n    time_span=0.0001s, test_ID=199, label=2, output_node=79, voltage=0.02876892499625683\n    time_span=0.0001s, test_ID=199, label=2, output_node=80, voltage=0.02511354722082615\n    time_span=0.0001s, test_ID=199, label=2, output_node=81, voltage=0.03028685413300991\n    time_span=0.0001s, test_ID=199, label=2, output_node=82, voltage=0.027062751352787018\n    time_span=0.0001s, test_ID=199, label=2, output_node=83, voltage=0.016805775463581085\n    time_span=0.0001s, test_ID=199, label=2, output_node=84, voltage=0.022442232817411423\n    time_span=0.0001s, test_ID=199, label=2, output_node=85, voltage=0.02686752937734127\n    time_span=0.0001s, test_ID=199, label=2, output_node=86, voltage=0.023651394993066788\n    time_span=0.0001s, test_ID=199, label=2, output_node=87, voltage=0.020354580134153366\n    time_span=0.0001s, test_ID=199, label=2, output_node=88, voltage=0.026467131450772285\n    time_span=0.0001s, test_ID=199, label=2, output_node=89, voltage=0.02103884518146515\n    time_span=0.0001s, test_ID=199, label=2, output_node=90, voltage=0.029368525370955467\n    time_span=0.0001s, test_ID=199, label=2, output_node=91, voltage=0.027678286656737328\n    time_span=0.0001s, test_ID=199, label=2, output_node=92, voltage=0.025093626230955124\n    time_span=0.0001s, test_ID=199, label=2, output_node=93, voltage=0.0268824715167284\n    time_span=0.0001s, test_ID=199, label=2, output_node=94, voltage=0.010188247077167034\n    time_span=0.0001s, test_ID=199, label=2, output_node=95, voltage=0.023452190682291985\n    time_span=0.0001s, test_ID=199, label=2, output_node=96, voltage=0.022206176072359085\n    time_span=0.0001s, test_ID=199, label=2, output_node=97, voltage=0.02476493827998638\n    time_span=0.0001s, test_ID=199, label=2, output_node=98, voltage=0.02698804810643196\n    time_span=0.0001s, test_ID=199, label=2, output_node=99, voltage=0.027816735208034515\n    time_span=0.0001s, test_ID=199, label=2, output_node=sum, voltage=0.06931672990322113\n    Time consumed for 1 sample = 631.4060275554657 s\n\n\n    C:\\Users\\Logan\\Anaconda3\\lib\\site-packages\\tables\\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: '199'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though\n      check_attribute_name(name)\n\n\n    Finished! Safe to change code now.\n\n\n\n```python\ndf\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th></th>\n      <th>0</th>\n      <th>1</th>\n      <th>2</th>\n      <th>3</th>\n      <th>4</th>\n      <th>5</th>\n      <th>6</th>\n      <th>7</th>\n      <th>8</th>\n      <th>9</th>\n      <th>...</th>\n      <th>994</th>\n      <th>995</th>\n      <th>996</th>\n      <th>997</th>\n      <th>998</th>\n      <th>999</th>\n      <th>1000</th>\n      <th>1001</th>\n      <th>1002</th>\n      <th>1003</th>\n    </tr>\n    <tr>\n      <th>output_node</th>\n      <th>time_range</th>\n      <th>repeats</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">0</th>\n      <th rowspan=\"5\" valign=\"top\">0.0001</th>\n      <th>0</th>\n      <td>0.009</td>\n      <td>-0.005</td>\n      <td>-0.022</td>\n      <td>-0.011</td>\n      <td>0.015</td>\n      <td>0.129</td>\n      <td>0.047</td>\n      <td>0.041</td>\n      <td>0.016</td>\n      <td>0.016</td>\n      <td>...</td>\n      <td>0.035</td>\n      <td>0.036</td>\n      <td>0.041</td>\n      <td>0.036</td>\n      <td>0.029</td>\n      <td>0.014</td>\n      <td>0.018</td>\n      <td>0.032</td>\n      <td>0.039</td>\n      <td>0.051</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>-0.007</td>\n      <td>-0.004</td>\n      <td>-0.005</td>\n      <td>0.007</td>\n      <td>0.021</td>\n      <td>0.019</td>\n      <td>0.022</td>\n      <td>0.018</td>\n      <td>0.009</td>\n      <td>0.013</td>\n      <td>...</td>\n      <td>0.036</td>\n      <td>0.009</td>\n      <td>-0.012</td>\n      <td>-0.016</td>\n      <td>-0.01</td>\n      <td>0.007</td>\n      <td>0.026</td>\n      <td>0.033</td>\n      <td>0.035</td>\n      <td>0.032</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.026</td>\n      <td>0.017</td>\n      <td>0.017</td>\n      <td>0.017</td>\n      <td>0.017</td>\n      <td>0.032</td>\n      <td>0.032</td>\n      <td>0.04</td>\n      <td>0.053</td>\n      <td>0.057</td>\n      <td>...</td>\n      <td>0.028</td>\n      <td>0.044</td>\n      <td>0.121</td>\n      <td>0.016</td>\n      <td>0.036</td>\n      <td>0.027</td>\n      <td>0.037</td>\n      <td>0.039</td>\n      <td>0.046</td>\n      <td>0.052</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.025</td>\n      <td>0.023</td>\n      <td>0.012</td>\n      <td>-0.004</td>\n      <td>0.001</td>\n      <td>0.011</td>\n      <td>0.012</td>\n      <td>0.015</td>\n      <td>0.016</td>\n      <td>0.014</td>\n      <td>...</td>\n      <td>-0.001</td>\n      <td>-0.005</td>\n      <td>0.002</td>\n      <td>0.007</td>\n      <td>0.007</td>\n      <td>0.009</td>\n      <td>-0.002</td>\n      <td>-0.013</td>\n      <td>-0.012</td>\n      <td>-0.001</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.03</td>\n      <td>0.033</td>\n      <td>0.028</td>\n      <td>0.025</td>\n      <td>0.025</td>\n      <td>0.024</td>\n      <td>0.02</td>\n      <td>0.027</td>\n      <td>0.024</td>\n      <td>0.016</td>\n      <td>...</td>\n      <td>0.027</td>\n      <td>0.018</td>\n      <td>0.011</td>\n      <td>0.015</td>\n      <td>0.016</td>\n      <td>0.016</td>\n      <td>0.033</td>\n      <td>0.051</td>\n      <td>0.107</td>\n      <td>0.069</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <th>...</th>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th rowspan=\"5\" valign=\"top\">bkg</th>\n      <th rowspan=\"5\" valign=\"top\">0.0001</th>\n      <th>45</th>\n      <td>-0.007</td>\n      <td>-0.006</td>\n      <td>-0.004</td>\n      <td>-0.003</td>\n      <td>-0.007</td>\n      <td>-0.011</td>\n      <td>-0.01</td>\n      <td>-0.005</td>\n      <td>0.005</td>\n      <td>0.015</td>\n      <td>...</td>\n      <td>-0.005</td>\n      <td>-0.006</td>\n      <td>-0.006</td>\n      <td>-0.01</td>\n      <td>-0.011</td>\n      <td>-0.012</td>\n      <td>-0.009</td>\n      <td>-0.004</td>\n      <td>-0.005</td>\n      <td>-0.005</td>\n    </tr>\n    <tr>\n      <th>46</th>\n      <td>-0.014</td>\n      <td>-0.008</td>\n      <td>-0.006</td>\n      <td>-0.014</td>\n      <td>-0.024</td>\n      <td>-0.024</td>\n      <td>-0.025</td>\n      <td>-0.016</td>\n      <td>-0.007</td>\n      <td>0.003</td>\n      <td>...</td>\n      <td>-0.029</td>\n      <td>-0.019</td>\n      <td>0.003</td>\n      <td>0.014</td>\n      <td>0.016</td>\n      <td>0.011</td>\n      <td>0.002</td>\n      <td>0.002</td>\n      <td>0.004</td>\n      <td>0.006</td>\n    </tr>\n    <tr>\n      <th>47</th>\n      <td>-0.01</td>\n      <td>-0.005</td>\n      <td>0.005</td>\n      <td>0.009</td>\n      <td>0.009</td>\n      <td>0.005</td>\n      <td>0.001</td>\n      <td>-0.005</td>\n      <td>-0.013</td>\n      <td>-0.021</td>\n      <td>...</td>\n      <td>-0.005</td>\n      <td>-0.005</td>\n      <td>-0.003</td>\n      <td>-0.004</td>\n      <td>-0.004</td>\n      <td>0.006</td>\n      <td>0.01</td>\n      <td>0.006</td>\n      <td>0.005</td>\n      <td>-0.001</td>\n    </tr>\n    <tr>\n      <th>48</th>\n      <td>0.01</td>\n      <td>0.003</td>\n      <td>-0.016</td>\n      <td>-0.03</td>\n      <td>-0.037</td>\n      <td>-0.026</td>\n      <td>-0.006</td>\n      <td>0.011</td>\n      <td>0.016</td>\n      <td>0.008</td>\n      <td>...</td>\n      <td>-0.023</td>\n      <td>-0.029</td>\n      <td>-0.034</td>\n      <td>-0.02</td>\n      <td>-0.007</td>\n      <td>-0.005</td>\n      <td>-0.012</td>\n      <td>-0.019</td>\n      <td>-0.025</td>\n      <td>-0.018</td>\n    </tr>\n    <tr>\n      <th>49</th>\n      <td>-0.002</td>\n      <td>0.004</td>\n      <td>0.006</td>\n      <td>0.005</td>\n      <td>0</td>\n      <td>-0.013</td>\n      <td>-0.024</td>\n      <td>-0.026</td>\n      <td>-0.024</td>\n      <td>-0.016</td>\n      <td>...</td>\n      <td>-0.007</td>\n      <td>-0.001</td>\n      <td>0.001</td>\n      <td>-0.001</td>\n      <td>-0.007</td>\n      <td>-0.011</td>\n      <td>-0.014</td>\n      <td>-0.013</td>\n      <td>-0.011</td>\n      <td>-0.005</td>\n    </tr>\n  </tbody>\n</table>\n<p>5100 rows \u00d7 1004 columns</p>\n</div>\n\n\n\n\n```python\ndf_volTraces.loc[0,].dropna(axis=\"columns\").astype(float).mean(level=[0,1]).mean(axis=1)*100\n```\n\n\n\n\n    output_node  time_range\n    0            0.0001        1.108908\n    1            0.0001        0.135558\n    2            0.0001        0.954472\n    3            0.0001        1.069739\n    4            0.0001        0.617894\n    5            0.0001        0.339468\n    6            0.0001        0.495554\n    7            0.0001        1.219645\n    8            0.0001        0.718153\n    9            0.0001        0.582032\n    dtype: float64\n\n\n\n\n```python\ndf_all_acts.loc[0,0]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>norm(W)norm(X)</th>\n      <th>sum(norm(X))</th>\n      <th>sum(norm(W))</th>\n      <th>Wx</th>\n      <th>Wx+b</th>\n      <th>a</th>\n      <th>a_true</th>\n    </tr>\n    <tr>\n      <th>output node</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>12298065.0</td>\n      <td>18435480.0</td>\n      <td>131674194.0</td>\n      <td>0.956051</td>\n      <td>-0.552092</td>\n      <td>0.000000</td>\n      <td>0.453606</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>5819807.0</td>\n      <td>18435480.0</td>\n      <td>79005915.0</td>\n      <td>-10.673519</td>\n      <td>-10.590518</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>11277890.0</td>\n      <td>18435480.0</td>\n      <td>122052825.0</td>\n      <td>1.561747</td>\n      <td>1.957514</td>\n      <td>1.957514</td>\n      <td>1.641961</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>11975186.0</td>\n      <td>18435480.0</td>\n      <td>117449433.0</td>\n      <td>5.828900</td>\n      <td>4.467121</td>\n      <td>4.467121</td>\n      <td>5.462904</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>9023111.0</td>\n      <td>18435480.0</td>\n      <td>101583315.0</td>\n      <td>-3.535693</td>\n      <td>-3.061699</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>7405579.0</td>\n      <td>18435480.0</td>\n      <td>84927987.0</td>\n      <td>-1.884187</td>\n      <td>-0.552092</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>8327609.0</td>\n      <td>18435480.0</td>\n      <td>110240649.0</td>\n      <td>-8.759407</td>\n      <td>-8.080911</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>13082552.0</td>\n      <td>18435480.0</td>\n      <td>119804076.0</td>\n      <td>11.431123</td>\n      <td>11.995940</td>\n      <td>11.995940</td>\n      <td>12.365005</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>9697962.0</td>\n      <td>18435480.0</td>\n      <td>102857040.0</td>\n      <td>1.703591</td>\n      <td>-0.552092</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>8986474.0</td>\n      <td>18435480.0</td>\n      <td>88276635.0</td>\n      <td>3.274412</td>\n      <td>1.957514</td>\n      <td>1.957514</td>\n      <td>2.905186</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf_volTraces.to_hdf((savePath / \"mppc_vol_meas.h5\").as_posix(), key=\" \", mode='w')\njoblib.dump([oscope_info(oscope),], savePath / 'exp_info.pkl')\n```\n\n\n```python\nblackImage_PIL = Image.open((phoneImagePath / \"black.png\").as_posix())\nblackImage_byte = PIL_to_bytestream(blackImage_PIL)\naoab.write(blackImage_byte)\n```\n\n# Troubleshoot Blocks\n\n\n```python\n# Debug alignment \nfrom PIL import Image\ntestImagePath = phoneImagePath / f\"test_digit_7_00000.png\"\nimToPhone_PIL = Image.open(testImagePath)\nimToPhone_byte = PIL_to_bytestream(imToPhone_PIL)\nslm.updateArray(slm_weights_numpy[\"ordered\"])\naoab.write(imToPhone_byte)\n```\n\n\n```python\n# Debug alignment \nfrom PIL import Image\nalignImagePath = resultPath.parent / \"alignment_images\" \nimToPhone_PIL = Image.open((alignImagePath / \"TheGreenViewFinder.png\").as_posix())\nimToPhone_byte = PIL_to_bytestream(imToPhone_PIL)\naoab.write(imToPhone_byte)\nimToSLM = Image.open((alignImagePath / \"TheGreenViewFinder_SLM.bmp\").as_posix())\nslm.updateArray(np.array(imToSLM))\n```\n\n\n```python\n# Debug alignment \nfrom PIL import Image\nalignImagePath = resultPath.parent / \"alignment_images\" \nimToPhone_PIL = Image.open((alignImagePath / \"Horizontal_stripes_period_4.png\").as_posix())\nimToPhone_byte = PIL_to_bytestream(imToPhone_PIL)\naoab.write(imToPhone_byte)\nimToSLM = Image.open((alignImagePath / \"Horizontal_stripes_period_4_SLM.bmp\").as_posix())\nslm.updateArray(np.array(imToSLM))\n```\n\n\n```python\n# Debug alignment \nfrom PIL import Image\nalignImagePath = resultPath.parent / \"alignment_images\" \nimToPhone_PIL = Image.open((alignImagePath / \"Vertical_stripes_period_4.png\").as_posix())\nimToPhone_byte = PIL_to_bytestream(imToPhone_PIL)\naoab.write(imToPhone_byte)\nimToSLM = Image.open((alignImagePath / \"Vertical_stripes_period_4_SLM.bmp\").as_posix())\nslm.updateArray(np.array(imToSLM))\n```\n", "meta": {"hexsha": "e390a59d5e0e1fd0f159fc2f213d724788c320e7", "size": 645762, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "data_collection/run_MLP_MPPC_fc1_2pcts.ipynb", "max_stars_repo_name": "ConnectionMaster/ONN-device-control", "max_stars_repo_head_hexsha": "0b909c48272ec0f92c79dfa1d7fb8b8b6c55766a", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-18T15:59:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T03:00:19.000Z", "max_issues_repo_path": "data_collection/run_MLP_MPPC_fc1_2pcts.ipynb", "max_issues_repo_name": "mcmahon-lab/ONN-device-control", "max_issues_repo_head_hexsha": "ecb0b6e8afef57c3c9ceeaa7e00d76860135a8ab", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-11T14:44:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-11T14:44:56.000Z", "max_forks_repo_path": "data_collection/run_MLP_MPPC_fc1_2pcts.ipynb", "max_forks_repo_name": "ConnectionMaster/ONN-device-control", "max_forks_repo_head_hexsha": "0b909c48272ec0f92c79dfa1d7fb8b8b6c55766a", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-11T14:43:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-11T14:43:40.000Z", "avg_line_length": 70.8150016449, "max_line_length": 55416, "alphanum_fraction": 0.6679984267, "converted": true, "num_tokens": 130505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510527095787247, "lm_q2_score": 0.05500529100440717, "lm_q1q2_score": 0.01898261585619256}}
{"text": "# Week 2 \n## Introduction to Solid State \n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport subprocess\nfrom polypy.read import History\nfrom polypy.msd import MSD\nfrom polypy import plotting\n\ndef get_diffusion(file, atom):\n    \n    with open(file) as f:\n        y = False\n        for line in f:\n            if str(\"atom        D \") in line:\n                y = True\n            if y == True and str(atom) in line:\n                d = line.split()\n                break\n    return d\n```\n\nNow that you are familiar with molecular dynamics, you are now going to use it to tackle some real world problems. In the next three weeks you will investigate the transport properties of a simple fluorite material - Ca$F_2$. The transport properties of a material determine many properties that are utilised for modern technological applications. For example, solid oxide fuel cell (SOFCs - Alternative to batteries) materials are dependent on the movement of charge carriers through the solid electrolyte and  nuclear fuel materials oxidise and fall apart and this corrosive behaviour is dependent on the diffusion of oxygen into the lattice. Due to the importance of the transport properties of these materials, scientists and engineers spend large amounts of their time tring to optomise these properties using different stoichiometries, introducing defects and by using different syntheisis techniques. Over the next three weeks you will investigate how the transport properties of Ca$F_2$ are affected by temperature, structural defects (Schottky and Frenkel) and by chemcial dopants (e.g. different cations). A rough breakdown looks as follows\n- Week 2 \n    - Introduction to DL_POLY\n    - Tutorial on the calculation of diffusion coefficients\n    - Tutorial on the Arhennius equation\n    - Molecular dynamics simulations of stoichiomteric Ca$F_2$\n- Week 3 \n    - Frenkel and Schottky defects\n- Week 4 \n    - Dopants\n    \n\n\n## Introduction to DL_POLY\n\nDL_POLY is a molecular dynamics program maintained by Daresbury laboratories. In contrast to pylj, DL_POLY is a three dimensional molecular dynamics code that is used worldwide by computational scientists for molecular simulation, but it should be noted that the theory is exactly the same and any understanding gained from pylj is completely applicable to DL_POLY. For the next three weeks you will use DL_POLY to run short molecular dynamics simulations on Ca$F_2$. You first need to understand the input files required for DL_POLY. \n- CONTROL - This is the file that contains all of the simulation parameters, e.g. simulation temperature, pressure, number of steps e.t.c\n- CONFIG - This is the file that contains the structure - i.e. the atomic coordinates of each atom. \n- FIELD - This is the file that contains the force field or potential model e.g. Lennard Jones. \n\nContained within the folder \"Input\" you will find a file called input.txt. This is the main file that you will interact with over the next three weeks and is used to generate the FIELD, CONTROL and CONFIG. Essentially it is easier to meddle with input.txt than it is to meddle with the 3 DL_POLY files everytime you want to change something. To run metadise we will use the subprocess python module. You specify what program you want to run and the file that you want to run it in, you will need to ensure the file path is correct. \n\n#### It is essential that the codes that were downloaded from [here](https://people.bath.ac.uk/chsscp/teach/adv.bho/progs.zip) are in the Codes/ folder in the parent directory, or this following cell will crash. \n\n\n```python\nsubprocess.call('../Codes/metadise.exe', cwd='Input/')\nos.rename('Input/control_o0001.dlp', 'Input/CONTROL')\nos.rename('Input/config__o0001.dlp', 'Input/CONFIG')\nos.rename('Input/field___o0001.dlp', 'Input/FIELD')\n```\n\nNow you should have a CONFIG, CONTROL and FIELD file within the input directory. In theory you could just call the DL_POLY program on this directory and your simulation would run. However we need to tweak the CONTROL file in order to set up our desired simulation. Make a new subdirectory in the week 2 directory named \"Example\" and copy CONFIG, CONTROL and FIELD to that subdirectory. Now edit the CONTROL file.  \n\nWe want to change the following   \n\n`Temperature 300 ---> Temperature 1500`  \n`Steps 5001 ---> Steps 40000`  \n`ensemble nve ---> ensemble npt hoover 0.1 0.5`  \n`trajectory nstraj= 1    istraj=   250 keytrj=0 ---> trajectory nstraj= 0    istraj= 100  keytrj=0`  \n  \nNow your simulation is ready. As a point of interest it is always good to check your structure before and after the simulation. You can view the CONFIG file in three dimensions using the VESTA program. It is available for free at http://www.jp-minerals.org/vesta/en/download.html . Download it and use it to view your CONFIG, a demonstrator can help if necessary. VESTA can generate nice pictures which will look very good in a lab report. \n\n<center>\n    <br>\n    \n    <i>Figure 1. Fluorite Ca$F_2$ unit cell visualised in VESTA.</i>\n    <br>\n</center>\n\n\nTo run DL_POLY from within a notebook use the below command. Keep in mind that this simulation will take 20 or so minutes so be patient. \n\nIf you are not comfortable with running things through this notebook then you can copy and paste the dlpoly_classic.exe executable into the Example/ sub directory and then double click the .exe file\n\n\n```python\nsubprocess.call('../Codes/dlpoly_classic.exe', cwd='Example/')\n```\n\nOnce DL_POLY has completed you will find several files relating to your simulaton. \n- HISTORY - This file contains the configuration of your system at each step during the simulation. You can view this as a movie using the VMD program - Ask a demonstrator for details\n- REVCON - This is the configuration at the end of the simulation - Can be viewed in VESTA - why not check to see how it has changed. \n- STATIS - Contains the stats at each step in the simulation. \n- OUTPUT - Contains properties \n\nIt is now important to understand how we can actually use the details of the simulation to get some information on the properties of the material, e.g. Diffusion coefficients and activation energies. \n\n## Mean Squared Displacements - Calculating diffusion coefficients\n\nAs we have seen molecules in liquds, gases and solids do not stay in the same place and move constantly. Think about a drop of dye in a glass of water, as time passes the dye distributes throughout the water. This process is called diffusion and is common throughout nature.  \n\nUsing the dye as an example, the motion of a dye molecule is not simple. As it moves it is jostled by collisions with other molecules, preventing it from moving in a straight path. If the path is examined in close detail, it will be seen to be a good approximation to a random walk. In mathmatics a random walk is a series of steps, each taken in a random direction. This was analysed by Albert Einstein in a study of Brownian motion and he showed that the mean square of the distance travelled by a particle following a random walk is proportional to the time elapsed. \n\\begin{align}\n\\Big \\langle r^2 \\big \\rangle & = 6 D_t + C \n\\end{align}\n\nwhere $\\Big \\langle r^2 \\big \\rangle$ is the mean squared distance, t is time, D is the diffusion rate and C is a constant. \n\n## What is the mean squared displacement\n\nGoing back to the example of the dye in water, lets assume for the sake of simplicity that we are in one dimension. Each step can either be forwards or backwards and we cannot predict which. From a given starting position, what distance is our dye molecule likely to travel after 1000 steps? This can be determined simply by adding together the steps, taking into account the fact that steps backwards subtract from the total, while steps forward add to the total. Since both forward and backward steps are equally probable, we come to the surprising conclusion that the probable distance travelled sums up to zero.\n\nBy adding the square of the distance we will always be adding positive numbers to our total which now increases linearly with time. Based upon equation 1 it should now be clear that a plot of $\\Big \\langle r^2 \\big \\rangle$ vs time with produce a line, the gradient of which is equal to 6D. Giving us direct access to the diffusion coefficient of the system. \n\nLets try explore this with an example. Run a short DL_POLY simulation on the input files provided. \n\nYou will a small MSD program called MSD.py to analyse your simulation results. First you need to read in the data, the HISTORY file contains a list of the atomic coordiantes held by the atoms during the simulation. \n\n\n```python\n# Read in the HISTORY file\n\n## Provide the path to the simulation and the atom that you want data for.\ndata = History(\"Example/HISTORY\", \"F\")\n```\n\ndata is a dictionary variable containing the atomic trajectories, lattice vectors, total number of atoms, and total number of timesteps. \n\ndata = {'trajectories':trajectories, 'lv':lv, 'timesteps':timesteps, 'natoms':natoms}\n\nThe next step is to calculate the MSD. \n\n\n```python\n# Run the MSD calculation\nf_msd = MSD(data.trajectory, sweeps=2)\n\noutput = f_msd.msd()\n```\n\nrun_msd returns a dictionary containing the total MSD, the dimensional MSD values and the time. \nmsd_data = {'msd': msd, 'xmsd': xmsd, 'ymsd': ymsd, 'zmsd': zmsd, 'time': time}\n\nThis can then be plotted to give a nice linear relationship. \n\n\n```python\nax = plotting.msd_plot(output)\nplt.show()\n```\n\n\n```python\nprint(\"Three Dimensional Diffusion Coefficient\", output.xyz_diffusion_coefficient())\nprint(\"One Dimensional Diffusion Coefficient in X\", output.x_diffusion_coefficient())\nprint(\"One Dimensional Diffusion Coefficient in Y\", output.y_diffusion_coefficient())\nprint(\"One Dimensional Diffusion Coefficient in Z\", output.z_diffusion_coefficient())\n```\n\n    Three Dimensional Diffusion Coefficient 1.4603905458958724\n    One Dimensional Diffusion Coefficient in X 1.5340510899794775\n    One Dimensional Diffusion Coefficient in Y 1.563758244863093\n    One Dimensional Diffusion Coefficient in Z 1.283362302845045\n\n\n## Simulation Length\n\nIt is important to consider the lenght of your simulation (Number of steps). Create a new folder called \"Example_2\", copy the CONFIG, FIELD and CONTROL files from your previous simulation but this time change the number of steps to 10000. Now rerun the simulation.\n\n\n```python\nsubprocess.call('../Codes/dlpoly_classic.exe', cwd='Example_2/')\n```\n\n\n```python\ndata = History(\"Example_2/HISTORY\", \"F\")\n\n# Run the MSD calculation\nf_msd = MSD(data.trajectory, sweeps=2)\n\noutput = f_msd.msd()\nax = plotting.msd_plot(output)\nplt.show()\n```\n\n\n```python\nprint(\"Three Dimensional Diffusion Coefficient\", output.xyz_diffusion_coefficient())\nprint(\"One Dimensional Diffusion Coefficient in X\", output.x_diffusion_coefficient())\nprint(\"One Dimensional Diffusion Coefficient in Y\", output.y_diffusion_coefficient())\nprint(\"One Dimensional Diffusion Coefficient in Z\", output.z_diffusion_coefficient())\n```\n\nYou will hopefully see that your MSD plot has become considerably less linear. This shows that your simulation has not run long enough and your results will be unrealiable. You will hopefully also see a change to the value of your diffusion coefficient.  The length of your simulation is something that you should keep in mind for the next 3 weeks. \n\n## Arrhenius\n\nThe next thing is to use the diffusion coefficients to calcaulte the activation energy for F diffusion. This rea=quires diffusion coefficients from a temperature range. Common sense and chemical intuition suggest that the higher the temperature, the faster a given chemical reaction will proceed. Quantitatively this relationship between the rate a reaction proceeds and its temperature is determined by the Arrhenius Equation. At higher temperatures, the probability that two molecules will collide is higher. This higher collision rate results in a higher kinetic energy, which has an effect on the activation energy of the reaction. The activation energy is the amount of energy required to ensure that a reaction happens.  \n  \n\\begin{align}\nk = A * e^{(-Ea / RT)}\n\\end{align}\n  \nwhere k is the rate coefficient, A is a constant, Ea is the activation energy, R is the universal gas constant, and T is the temperature (in kelvin).\n\n\n\n## Week 2 Exercise\n\nUsing what you have learned over the last 45 mins your task this week is to calculate the activation energy of F diffusion in Ca$F_2$. You will need to select a temperature range and carry out simulations at different temperatures within that range. \n#### Questions to answer\n- In what temperature range is Ca$F_2$ completely solid i.e. no diffusion?\n- In what range is fluorine essentially liquid i.e. fluorine diffusion with no calcium diffusion?\n- What is the melting temperature?\n- Plot an Arrhenius plot and determine the activation energies in temperature range - You will need to rearange the equation. \n\n\nYou are encouraged to split the work up within your group and to learn how to view the simulation \"movie\" using VMD (Ask a demonstrator). VMD is a fantastic program that allows you to visualise your simulation, included below is a video showing a short snippet of an MD simulation of Ca$F_2$. A single F atom has been highlighted to show that diffusion is occuring. \n\n\n```python\n%%HTML\n<div align=\"middle\">\n</div>\n```\n\n\n<div align=\"middle\">\n</div>\n\n\n\nFurthermore, VMD can also be used to generate images showing the entire trajectory of the simulation, e.g.\n\n\n\n<center>\n    <br>\n    \n    <i>Figure 2. A figure showing all positions occupied by F during an MD simulation at 1500 K. F positions are shown in orange and Ca atoms are shown in green.</i>\n    <br>\n</center>\n  \n\n  To save you the time you can use the function declared at the start of this notebook to pull out a diffusion coefficient directly from the simulation output file. MSD.py is a small code to allow visualisation of the MSD plot but it is not neccesary every time you want the diffusion coefficient. \n\nIt is up to you how you organise/create your directories but it is reccomended that you start a new notebook. Use the commands/functions used in this notebook to generate your input files, run DL_POLY and extract the diffusion coefficients. The write your own code to generate an Arrhenius plot and calculate the activation energies. \nIf you finish early then feel free to start week 3. \n\n\n```python\n\n```\n", "meta": {"hexsha": "12c8fd9fb934ed3dc479b5a0421797542e80345c", "size": 86296, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Week_3/.ipynb_checkpoints/week_3-checkpoint.ipynb", "max_stars_repo_name": "james-grant1/Advanced_Practical_Chemistry_Year_3", "max_stars_repo_head_hexsha": "b20e0d0df2a79fda04a8161db6581e6d3f60946e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-24T20:18:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T20:18:13.000Z", "max_issues_repo_path": "Week_3/.ipynb_checkpoints/week_3-checkpoint.ipynb", "max_issues_repo_name": "james-grant1/Advanced_Practical_Chemistry_Year_3", "max_issues_repo_head_hexsha": "b20e0d0df2a79fda04a8161db6581e6d3f60946e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week_3/.ipynb_checkpoints/week_3-checkpoint.ipynb", "max_forks_repo_name": "james-grant1/Advanced_Practical_Chemistry_Year_3", "max_forks_repo_head_hexsha": "b20e0d0df2a79fda04a8161db6581e6d3f60946e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-09-16T14:59:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-28T09:50:29.000Z", "avg_line_length": 200.222737819, "max_line_length": 66616, "alphanum_fraction": 0.8960670251, "converted": true, "num_tokens": 3280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.0566524292897824, "lm_q1q2_score": 0.018955304661703924}}
{"text": "# Jupyter Lab\n\n- [Startup exercise](#Startup-exercise)\n- [Use in reproducible research](#Use-in-reproducible-research)\n- [History and JupyterLab](#History-and-JupyterLab)\n- [Other uses](#Other-uses)\n- [Slideshows](#Slideshows)\n\n### How to use Jupyter Lab for this course\n\n- download the course (via web or git clone) in a /download folder\n- copy only the current day in your /course folder. (you should have /course/day1 there)\n- open jupyter lab server on /course, not on /course/day1\ncd /path/to/course/\nconda create -n biopy37 python=3.7\nconda activate biopy37\nconda install jupyterlab\njupyter lab\n## Startup exercise\nTask:\n- Start your own Jupyter server\n\nOn Windows, you can find a launcher for IPython Notebook under Anaconda in the Start menu. Alternatively you can open a command prompt, navigate to your folder and use the command bellow.\n\nOn Linux or OS X, you can start IPython Notebook from the command line. First open a terminal window, use 'cd' to navigate to the directory where you want to store your Python files and notebook document files. Then run this command:\n\n```\njupyter lab\n```\n\nYou will see something like:\n\n```\n[NotebookApp] Serving notebooks from current/directory/pathway\n```\n\nMake sure the course material is in that directory.\n\nHere is how to specify a different home directory:\n\n```\njupyter notebook --notebook-dir=/path/to/course/dir\n```\n\nKeep in mind that on Windows the paths are specified in a different manner.\n\n## Use in reproducible research\n\n\n> Open source, interactive data science and scientific computing across over 40 programming languages. The Jupyter Notebook is a web application that allows you to create and share documents that contain live code, equations, visualizations and explanatory text. Uses include: data cleaning and transformation, numerical simulation, statistical modeling, machine learning and much more. Read more about [Jupyter](https://jupyter.org/).\n\nWe are concerned, among other things (it is to be hoped), with increasing the capability of our NBIS staff, collaborators, and wider public to reproduce/resell/recycle/hack our work. Like many others, I used Jupyter and similar platforms for several reasons:\n\n- As a way to hand out research results to my collaborators and public.\n- Keeping track of my work (internal notebooks).\n- Organize course material.\n- Cloud development on the go with Sage, Picloud, etc.\n- Provide a fast OS independent web GUI toolkit.\n- Use of a Star Trek bridge from which to run/edit scripts in multiple languages. If you are like me and worked with some fifty programming languages over a 27 years timeframe, having to constantly change editors and displays kind of sucks.\n- Scallable computing (big data interface).\n\nOther uses of Jupyter, that are common enough, but I was less concerned with before include:\n\n- Documenting a program, pipeline or library.\n- Colaborative work.\n- Batch running, scheduling\n\nWe shall take those points one by one with some examples.\n\n### JupyterLab\n\nRead here about the future of the Jupyter Notebook: [https://blog.jupyter.org/2016/07/14/jupyter-lab-alpha/](https://blog.jupyter.org/2016/07/14/jupyter-lab-alpha/). Some of my key remarks:\n- Python and Julia remain central.\n- Separate file browser, console and code editor added to the notebook server.\n- The project moves out of Berkeley (partnership with Continuum Analytics, Tech at Bloomberg).\n\n### History\n\nI don't know the early beginnings, but I first saw notebooks that can compute in an Astronomy lab from the nineties, where they were using Mathematica notebooks for symbolic mathematics computations. Among mathematicians there is a tribe that became hateful of too much symbolic writing, and they were the first enthusiasts. Two major developments happened since: the ability to write code cells and the web.\n\nJupyter name is an agglutination of Julia, Python and R and is pronounced in reference to a pie rather than a planet. It originates at Berkeley (also home of Julia and Apache Spark) from a project that now is independent, called [IPython](https://ipython.org/). IPython is the best interactive shell for Python for scientific computing and now provides one of many kernels for running Python code in Jupyter.\n\nProjects similar to Jupyter:\n- [Mathematica](http://www.wolfram.com/cdf/?source=nav) has its own notebook. Somehow I could never afford it. Matlab, Octave, Sage and the like all integrate into Jupyter but often develop their own notebooks.\n- R:\n    - [R Markdown](http://rmarkdown.rstudio.com/) often used with report generation with [knitr](http://yihui.name/knitr/).\n    - [Shiny](http://shiny.rstudio.com/) is often viewed as something similar. Purely web application frameworks for Python similar even moe similar to Shiny would include Flask and Django. \n    - Other R possibilities range from  to the \"R only\" Jupyter clone [RCloud](http://att.github.io/rcloud/) to web publishing with [RPubs](http://www.rpubs.com/). Taken together, they make up a decent Jupyter replacement. For R.\n- The latest efforts come unsurprisingly from big data, such as [spark-notebook](http://spark-notebook.io/) and [Beaker](http://beakernotebook.com/).\n\n### Can you cook eggs with Jupyter? Yes, you need a frying pan and an oven...\n\nDon't expect Jupyter to always work. It is very dependent on your ability to have their latest update on the computer, wait for bugs to be solved, and circumvent problems. If you stay on the beaten track the user experience is fabulous, although limited.\n\nSome known limitations:\n- Support for Python is the best, anything else is less than optimal.\n- Collaborative tools are new and not super fun.\n- Jupyter provides a non-native aproach to parallel computing. Many parallel computing machines have their own platforms.\n- You cannot open notebooks with a double click. This CAN be done, with average OS admin skill, it is just not how things work (yet?) by default. You have to open a web server first. This is not an acessible Office replacer.\n- It won't replace Wiki. The wiki is much better at displaying collaborative content for the web. So our Confluence wiki pages are better left where they sit.\n- For great looks, Javascript and web development is essential.\n\n\n```python\n# Embed an image\nfrom IPython.display import Image\nImage('https://blog.jupyter.org/content/images/2016/07/jlab-screenshot-nb-con-term-2.png')\n\n```\n\n\n```python\n\n```\n\n### And now, the Hello World! Oh noo\n\nTo start using Jupyter please follow this [notebook](https://github.com/grokkaine/biopycourse/blob/master/day1/what.ipynb) that I use during my Python classes. Or help yourself with Dr Google. THE point about Jupyter is that you can do this thing (called a code cell):\n\n\n```python\nm = \"Hello World!\"\n```\n\n\n```python\ndef f(message):\n    print(message)\n```\n\n    Hello World!\n\n\nEach code cell will communicate with the others because underneath a notebook is the same shell/kernel/language (IPython/Python in this particular case, but you can just as well use [IRkernel](https://irkernel.github.io/)/R). If you created a notebook with a Kernel other than IPython you will have\\* to type the code in the appropriate languages. Some languages (kernels) however are very xenophoric, most notably Python and Julia, so you can call many other languages if you use them.\n\nNote: \\*A different kernel can be set for a certain code cell.\n\n\n\n```python\nm = 8\n```\n\n\n```python\nf(m)\n```\n\n    8\n\n\nThe text cells are commonly typed in [Markdown](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). They can also include html and latex.\n\n<table><tr><td>Static</td></tr><tr><td>HTML</td><td>TABLE</td></table>\n\nStatic latex: $$c = \\sqrt{a^2 + b^2}$$\n\nDynamic latex and html:\n\n\n```latex\n%%latex\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n```\n\n\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n\n\n\n```python\nfrom IPython.core.display import HTML\nHTML('<iframe src=http://nbis.se/?useformat=mobile width=700 height=350>')\n```\n\n\n\n\n<iframe src=http://nbis.se/?useformat=mobile width=700 height=350>\n\n\n\n\n```python\n%%HTML\n<div style=\"background-color:cyan; border:solid black; width:300px; padding:20px;\">\nValue for 'foo': <input type=\"text\" id=\"foo\" value=\"bar\"><br>\n<button onclick=\"set_value()\">Set Value</button>\n</div>\n\nHere is how Javascript communicates with Python:\n```\n\n\n<div style=\"background-color:cyan; border:solid black; width:300px; padding:20px;\">\nValue for 'foo': <input type=\"text\" id=\"foo\" value=\"bar\"><br>\n<button onclick=\"set_value()\">Set Value</button>\n</div>\n\nHere is how Javascript communicates with Python:\n\n\n\n```python\nfoo\n```\n\n\n\n\n    'test'\n\n\n\nThe examples above use % which is a way to invoke kernel commands known as \"[magics](https://ipython.org/ipython-doc/3/interactive/magics.html)\". Next is a plot example that will use a magic to load matplotlib.pylab module and specify that we want an inline figure rather than a standalone GUI for our plot.\n\n\n```python\n%pylab inline\nx = linspace(0, 3*pi, 500)\nplot(x, sin(x**2))\ntitle('adjustment to day-night cycle in northern sweden');\n```\n\n\n```python\n%load_ext rpy2.ipython\n```\n\n    /home/sergiun/programs/anaconda3/lib/python3.5/site-packages/rpy2/robjects/robject.py:6: UserWarning: Error in dyn.load(file, DLLpath = DLLpath, ...) : \n      unable to load shared object '/usr/lib/R/library/stats/libs/stats.so':\n      /home/sergiun/programs/anaconda3/bin/../lib/libgfortran.so.3: version `GFORTRAN_1.4' not found (required by /usr/lib/liblapack.so.3)\n    \n      rpy2.rinterface.initr()\n    /home/sergiun/programs/anaconda3/lib/python3.5/site-packages/rpy2/robjects/robject.py:6: UserWarning: During startup - \n      rpy2.rinterface.initr()\n    /home/sergiun/programs/anaconda3/lib/python3.5/site-packages/rpy2/robjects/robject.py:6: UserWarning: Warning message:\n    \n      rpy2.rinterface.initr()\n    /home/sergiun/programs/anaconda3/lib/python3.5/site-packages/rpy2/robjects/robject.py:6: UserWarning: package \u2018stats\u2019 in options(\"defaultPackages\") was not found \n    \n      rpy2.rinterface.initr()\n\n\n\n```r\n%%R\nplot_r <- function(x) {\n    p <- plot(x);\n    print(p);\n}\n```\n\n\n```python\n!conda install rp2\n```\n\n    Solving environment: failed\n    \n    PackagesNotFoundError: The following packages are not available from current channels:\n    \n      - rp2\n    \n    Current channels:\n    \n      - https://repo.anaconda.com/pkgs/main/linux-64\n      - https://repo.anaconda.com/pkgs/main/noarch\n      - https://repo.anaconda.com/pkgs/free/linux-64\n      - https://repo.anaconda.com/pkgs/free/noarch\n      - https://repo.anaconda.com/pkgs/r/linux-64\n      - https://repo.anaconda.com/pkgs/r/noarch\n      - https://repo.anaconda.com/pkgs/pro/linux-64\n      - https://repo.anaconda.com/pkgs/pro/noarch\n    \n    To search for alternate channels that may provide the conda package you're\n    looking for, navigate to\n    \n        https://anaconda.org\n    \n    and use the search bar at the top of the page.\n    \n    \n\n\n\n```python\nprint(\"Yellow R this is Python can you please plot this array for me?\")\nimport numpy as np\nx = np.random.rand(10)\nprint(x)\n%Rpush x\n%R plot_r(x)\n```\n\n## Other uses\n\n### A way to hand out research results to collaborators and public.\n\nA notebook can be displayed on the web provided you use a notebook aware server. The default notebook service is called [Nbviewer](http://nbviewer.jupyter.org/) and can be configured to display public notebooks on a web server. It is widely used on Github, and a large part of Jupyter popularity probably came from having the Github exposed notebooks available publicly.\n\n> FAQ: What is this Notebook Viewer? IPython Notebook Viewer is a free webservice that allows you to share static html versions of hosted notebook files. If a notebook is publicly available, by giving its url to the Viewer, you should be able to view it. You can also directly browse collections of notebooks in public GitHub repositories, for example the IPython examples.\n\nHere is a lenghty blog post about deploying the notebook on other clouds:\n\n[https://blog.ouseful.info/2014/12/12/seven-ways-of-running-ipython-notebooks/](https://blog.ouseful.info/2014/12/12/seven-ways-of-running-ipython-notebooks/)\n\nMost often, a collaborator that is not computer savy will need pdf or html conversion, which can be done in batch mode or interactive using the notebook file menu.\n\nFor text processing, batch conversion into markdown is also possible. Apart from this, notebooks can also be saved into the native kernel language, such as Python, Julia, R (untested). The native format of a notebook file, .ipynb is a json format.\n\n\n### Keeping track of my work (internal notebooks)\n\nThis is how I use Jupyter most of the time. Taking log notes is not fun, how about taking log notes while you document your ideas while you program? It is possible to add a time log to it, although I personally don't like it and prefer to add a date when I feel like.\n\nIt is easier to keep them private because you want the ability to make annotations that would otherwise be difficult to explain. (For example making a note about what a direct repeat is. You might have heard about it before, but now you just wanted to put it there and clarify it. A collaborator or a client however can think you are an unqualified.)\n\nWhile I do have a few projects where an integrated code editor is essential, I do a lot of the work in these notebook logs, assembling the code only when needed. They are especially good for exploratory studies. At the end I assemble a few presentation notebooks from the logs. Is this a good ideea for reproducible research? In my opinion publicly documenting every little detail is detrimental, I would not try to reproduce a bit of research that is detailed in too many files. But, having the record, even if private, allows someone the get to the details when needed, and that too is reproducible research. I am guessing there is a trade off somewhere between actual work and administration. Are all of Einstein's mind mapping scribbled bits of paper being kept, maybe they are, maybe they aren't public. He had a weird take on what desk order means. What do you think?\n\nAdvices:\n- Do not keep long notebooks! Since each notebook is a shell it will get filled with data to the point where it gets hard to manage properly.\n- Keep important scripts and programs running independently. You can run anything from a notebook, you can import your code easily.\n- Consider each notebook as a task record rather than a time record. Example: installing and running program x, this is a task, it can be done in different days and you may refine it from time to time.\n- Code cells can be run sequentially so it is best to have a top-down approach. Although it is possible to insert cells on the top that use the notebook data, this is only useful for fast testing and those cells should be deleted or moved.\n\nExamples:\n- TODO: add link to Andersson project logs\n- TODO: add time log as an example, and consider other logging features\n\n### Organize course/training material\n\nWell if you heard about IPython or Jupyter, it probably is because you have seen courses. My most recent is here:\nhttps://github.com/grokkaine/biopycourse/blob/master/Syllabus.ipynb\n\nHere are some links:\n- https://www.biostars.org/p/149243/\n- http://microbe.net/2014/05/01/teaching-bioinformatics-using-ipython-notebooks/\n\nMy experience:\n\nIt is best if you use Docker and a cloud to provide a controlled experience. It is also good to use a single Python distribution. It is good as in any interactive course if the class is not too big. I found that I can't take more than ten without a super drop in the quality of the teaching.\n\n### Cloud development on the go with Sage, AWS, Picloud, etc\n\nMost clouds today can be configured or natively run Jupyter. Some of Jupyter kernels are especially great in clouds, having parralel computing capabilities. For some, this has some collaboration benefits too.\n\nMy use of this feature was mostly to access clouds from my mobile. Having a small kid it is hard to open a laptop do do any work in the evenings or during weekends, so my Nexus 4 became a work tool.\n\n### Provide a fast OS independent web GUI\n\nTODO: a widget example to plot spacer graphs.\n\n### Multiple language interface\n\nI have shown how multiple languages can be used from the same notebook. In most case though you would want to have each notebook code in its kernel's native language.\n\n### Documenting a program, pipeline or library\n\nBecause of Github integration, this became a popular feature. Notebooks can be converted to ReStructuredText markup (.reST), which feeds into a popular documentation generator called Sphinx, which created a popular fork named Read The Docs, able to regen after every commit.\n\nI liked for example how [cobrapy](https://cobrapy.readthedocs.io/en/stable/getting_started.html) structured documentation. Send me mail if you have a special mention. Here is another, a metagenomic framework [http://pythonhosted.org/mgkit/index.html](http://pythonhosted.org/mgkit/index.html).\n\n### Collaborative work\n\n[coLaboratory](http://colaboratory.jupyter.org/welcome/) is hosted on Jupyter site and currently offers collaborative support through Google Drive. There are other minor developments, if you had some experience with one or another please let me know.\n\nYou can always co-edit a git repo hosting notebooks, but hardcore collaborative edits (as in concurential editing of the same code cell) will break the internal json structure of your document. Unless you have a git genius on your sleeve, better find alternatives. Content management is not in the plans neither.\n\nWorth mentioning:\n- [JupyterHub](https://jupyterhub.readthedocs.io/en/latest/). A Jupyter server spawning user authenticated instances.\n- [Dashboard](https://github.com/jupyter-incubator/dashboards_server) can display Jupyter notebooks as dynamic dashboards outside of the Jupyter Notebook server. (NodeJS based)\n\n### Scallable computing\n\nBecause the emergent big data architectures have their own notebook implementations, sometimes natively (examples were given) this will be a hard test for Jupyter. The most recent succesful story for Jupyter was Scala and Spark integration among its kernels. Ultimately, Jupyter is powered by Berkeley, \"love\" and open source.\n\nThe main website has a small example of Jupyter-Spark integration, and other examples that you can test-run at will.\n[https://try.jupyter.org/](https://try.jupyter.org/)\n\n### Batch scheduling\n\nLet's say you made a detailed notebook making a number of plots and you need to rerun it because you got some new data. Notebooks can be re-run at any moment from a terminal or from any job scheduler. An example is here: [https://blog.dominodatalab.com/lesser-known-ways-of-using-notebooks/](https://blog.dominodatalab.com/lesser-known-ways-of-using-notebooks/)\n\n## Making re-generative slides\n\nJupyter is cool for modern slide-shows. Test it on the command line by switching to your day1 folder and running:\n\n$ jupyter nbconvert jupyter_slides.ipynb --to slides --post serve\n\n\n```python\n\n```\n", "meta": {"hexsha": "a6f26cd7dc5797dbed68ad25c0b39761ec63988a", "size": 752261, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "day1/.ipynb_checkpoints/jupyter-checkpoint.ipynb", "max_stars_repo_name": "grokkaine/biopycourse", "max_stars_repo_head_hexsha": "cb8b554abb987e6f657c5e522c7e28ecbc9fb4d5", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2017-05-16T06:07:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-06T14:58:28.000Z", "max_issues_repo_path": "day1/.ipynb_checkpoints/jupyter-checkpoint.ipynb", "max_issues_repo_name": "grokkaine/biopycourse", "max_issues_repo_head_hexsha": "cb8b554abb987e6f657c5e522c7e28ecbc9fb4d5", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day1/.ipynb_checkpoints/jupyter-checkpoint.ipynb", "max_forks_repo_name": "grokkaine/biopycourse", "max_forks_repo_head_hexsha": "cb8b554abb987e6f657c5e522c7e28ecbc9fb4d5", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2017-05-16T07:25:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-22T19:22:53.000Z", "avg_line_length": 1008.3927613941, "max_line_length": 671976, "alphanum_fraction": 0.9447784745, "converted": true, "num_tokens": 4784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1540575588075327, "lm_q2_score": 0.12252322213041654, "lm_q1q2_score": 0.018875628498645037}}
{"text": "```python\n# imports \n\nimport xml.etree.ElementTree as ET\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom ipywidgets import interact, interactive, fixed, interact_manual\nimport ipywidgets as widgets\nfrom IPython.display import display,clear_output\nimport glob\n\nimport scipy as scipy\nimport scipy.signal as signal\nfrom scipy.interpolate import interp1d\nfrom scipy.optimize import leastsq\nfrom sympy import pprint\nimport sympy \nfrom scipy.optimize import curve_fit\nimport peakutils\n\n\nimport mpld3\nmpld3.enable_notebook()\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\n```\n\n\n```python\n# XML reader\nclass XML2DataFrame:\n\n    def __init__(self, xml_data):\n        self.root = ET.XML(xml_data)\n\n    def parse_root(self, root):\n        return [self.parse_element(child) for child in iter(root)]\n\n    def parse_element(self, element, parsed=None):\n        if parsed is None:\n            parsed = dict()\n        for key in element.keys():\n            parsed[element.tag +\"_\"+ key] = element.attrib.get(key)\n#         display(element.tag)\n        if element.text:\n            parsed[  element.tag ] = element.text\n        for child in list(element):\n            self.parse_element(child, parsed)\n        return parsed\n\n    def process_data(self):\n        structure_data = self.parse_root(self.root)\n        return pd.DataFrame(structure_data)\n\n\n\n```\n\n\n```python\n#\nrecordings = [file for file in  sorted(glob.glob('./Data/*.xml'))][::-1]\n\nprint('number of files: %s (%s subjects)'%(len(recordings),len(recordings)/8))\nfiles_dropdown=widgets.Dropdown(\n    options=recordings,\n    description='recording:',\n    disabled=False, layout=widgets.Layout(width='50%'))\ndisplay(files_dropdown)\n\n\n\n\n\n```\n\n    number of files: 2 (0.25 subjects)\n\n\n\n<p>Failed to display Jupyter Widget of type <code>Dropdown</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n# Load individual recording\n\n\n```python\n# Loading vr data\ndef LOAD(dataFile):\n\n\n    xml2df = XML2DataFrame(open( dataFile).read())\n    df = xml2df.process_data()\n\n    df=df.drop(['frame'], axis=1)\n    df=df.apply(pd.to_numeric, errors='ignore',downcast='integer')\n\n    return df\n\ndf=LOAD(files_dropdown.value)\n# print(df.info())\n# display(df.columns.values)\ndisplay(df.head())\n```\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Heading_Value_X</th>\n      <th>Heading_Value_Y</th>\n      <th>Participant_Age</th>\n      <th>Participant_Gender</th>\n      <th>Participant_Name</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>P</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1209.094</td>\n      <td>361.3125</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>P</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1209.094</td>\n      <td>361.3125</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>P</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1209.094</td>\n      <td>361.3125</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>P</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1209.094</td>\n      <td>361.3125</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>P</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n```python\ndf.plot(y='Heading_Value_X')\n```\n", "meta": {"hexsha": "a7e8a8d8484bc43e8285470bc496e1a745f40d51", "size": 29606, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "EyeMRTK/.ipynb_checkpoints/Python_code_to_XML_recordings-checkpoint.ipynb", "max_stars_repo_name": "The-COGAIN-Association/EyeMRTK", "max_stars_repo_head_hexsha": "6a50594dff5ba233cdd30802402075d7e3361029", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-03-28T10:30:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T18:02:27.000Z", "max_issues_repo_path": "EyeMRTK/.ipynb_checkpoints/Python_code_to_XML_recordings-checkpoint.ipynb", "max_issues_repo_name": "The-COGAIN-Association/EyeMRTK", "max_issues_repo_head_hexsha": "6a50594dff5ba233cdd30802402075d7e3361029", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EyeMRTK/.ipynb_checkpoints/Python_code_to_XML_recordings-checkpoint.ipynb", "max_forks_repo_name": "The-COGAIN-Association/EyeMRTK", "max_forks_repo_head_hexsha": "6a50594dff5ba233cdd30802402075d7e3361029", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-03-31T18:15:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T17:23:27.000Z", "avg_line_length": 88.9069069069, "max_line_length": 20392, "alphanum_fraction": 0.8092278592, "converted": true, "num_tokens": 1142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022540649291935, "lm_q2_score": 0.05033062743375412, "lm_q1q2_score": 0.018633677000705298}}
{"text": "# The Jupyter Notebook\n\nThis is an introduction to Jupyter IPython Notebooks, highlighting some of their key functionality. Please read through and execute cells with **`Shift + Enter`** to get an understanding of what Jupyter Notebooks can do.\n\nPlease do not be concerned if this is a little confusing at this stage, try returning to this notebook at the end of the course when you have more experience using the notebooks.\n\n## What is a Jupyter Notebook?\n\nAn Ipython Jupyter Notebook is:\n\n- an interactive environment for writing and running code  \n- a notebooke that weaves code, data, prose, equations, analysis, and visualization  \n- a tool for prototyping new code and analysis  \n- a method for creating a reproducible workflow for scientific research  \n\n\n### Writing and Running Code\n\nThe Jupyter Notebook consists of an ordered list of cells, there are four main cell types:\n* **Code**\n* **Markdown**\n* **Heading**\n* **Raw**\n\nHere we briefly introduce how Code Cells work. We will return to the other three cell types later.\n\n### Code Cells\n\n\n```python\n# This is a code cell made up of Python comments\n# We can execute it by clicking on it with the mouse\n# then clicking the \"Run Cell\" button\n# or if this does not work try pressing \"Ctrl + Enter\" or \"Shift + Enter\"\n```\n\n\n```python\n# A comment is a pretty boring piece of code\n# This code cell generates \"Hello, World\" when executed\n\nprint(\"Hello, World\")\nprint(1.2 + 2.2)\n```\n\n\n```python\n# Code cells can also generate graphical output\n%matplotlib inline\nimport matplotlib\nmatplotlib.pyplot.hist([0, 1, 2, 2, 3, 3, 3, 4, 4, 4, 10]);\n```\n\n## Modal editor\n\nStarting with IPython 2.0, the IPython Notebook has a modal user interface. This means that the keyboard does different things depending on which mode the Notebook is in. There are two modes: edit mode and command mode.\n\n### Edit mode\n\nEdit mode is indicated by a green cell border and a prompt showing in the editor area:\n\n\n\nWhen a cell is in edit mode, you can type into the cell, like a normal text editor.\n\n<div class=\"alert alert-success\" style=\"margin: 10px\">\nEnter edit mode by pressing `enter` or using the mouse to click on a cell's editor area.\n</div>\n\n<div class=\"alert alert-success\" style=\"margin: 10px\">\nWhile in edit mode, tab-completion works for variables the kernel knows about from executing previous cells.\n</div>\n\n### Command mode\n\nCommand mode is indicated by a grey cell border:\n\n\n\nWhen you are in command mode, you are able to edit the notebook as a whole, but not type into individual cells. Most importantly, in command mode, the keyboard is mapped to a set of shortcuts that let you perform notebook and cell actions efficiently. For example, if you are in command mode and you press `c`, you will copy the current cell - no modifier is needed.\n\n<div class=\"alert alert-error\" style=\"margin: 10px\">\nDon't try to type into a cell in command mode; unexpected things will happen!\n</div>\n\n<div class=\"alert alert-success\" style=\"margin: 10px\">\nEnter command mode by pressing `esc` or using the mouse to click *outside* a cell's editor area.\n</div>\n\n## Mouse navigation\n\nAll navigation and actions in the Notebook are available using the mouse through the menubar and toolbar, which are both above the main Notebook area:\n\n\n\nThe first idea of mouse based navigation is that **cells can be selected by clicking on them.** The currently selected cell gets a grey or green border depending on whether the notebook is in edit or command mode. If you click inside a cell's editor area, you will enter edit mode. If you click on the prompt or output area of a cell you will enter command mode.\n\nIf you are running this notebook in a live session (not on http://nbviewer.ipython.org) try selecting different cells and going between edit and command mode. Try typing into a cell.\n\nThe second idea of mouse based navigation is that **cell actions usually apply to the currently selected cell**. Thus if you want to run the code in a cell, you would select it and click the \"Play\" button in the toolbar or the \"Cell:Run\" menu item. Similarly, to copy a cell you would select it and click the \"Copy\" button in the toolbar or the \"Edit:Copy\" menu item. With this simple pattern, you should be able to do most everything you need with the mouse.\n\nMarkdown and heading cells have one other state that can be modified with the mouse. These cells can either be rendered or unrendered. When they are rendered, you will see a nice formatted representation of the cell's contents. When they are unrendered, you will see the raw text source of the cell. To render the selected cell with the mouse, click the \"Play\" button in the toolbar or the \"Cell:Run\" menu item. To unrender the selected cell, double click on the cell.\n\n## Keyboard Navigation\n\nThe modal user interface of the IPython Notebook has been optimized for efficient keyboard usage. This is made possible by having two different sets of keyboard shortcuts: one set that is active in edit mode and another in command mode.\n\nThe most important keyboard shortcuts are **`enter`**, which enters edit mode, and **`esc`**, which enters command mode.\n\nIn edit mode, most of the keyboard is dedicated to typing into the cell's editor. Thus, in edit mode there are relatively few shortcuts:\n\nIn command mode, the entire keyboard is available for shortcuts:\n\nHere the rough order in which the IPython Developers recommend learning the command mode **shortcuts**:\n\n1. Basic navigation: `enter`, `shift-enter`, `up/k`, `down/j`\n2. Saving the notebook: `s`\n2. Cell types: `y`, `m`, `1-6`, `t`\n3. Cell creation and movement: `a`, `b`, `ctrl+k`, `ctrl+j`\n4. Cell editing: `x`, `c`, `v`, `d`, `z`, `shift+=`\n5. Kernel operations: `i`, `0`\n\n## The IPython Notebook Architecture\n\nSo far, we have learned the basics of using IPython Notebooks.\n\nFor simple demonstrations, the typical user doesn't need to understand how the computations are being handled, but to successfully write and present computational notebooks, **you** will need to understand how the notebook architecture works.\n\nA *live* notebook is composed of an interactive web page (the front end), a running IPython session (the kernel or back end), and a web server responsible for handling communication between the two (the, err..., middle-end)\n\nA *static* notebook, as for example seen on NBViewer, is a static view of the notebook's content.  The default format is HTML, but a notebook can also be output in PDF or other formats.\n\nThe centerpiece of an IPython Notebook is the \"kernel\", the IPython instance responsible for executing all code.  Your IPython kernel maintains its state between executed cells.\n\n\n```python\nx = 0\nprint(x)\n```\n\n\n```python\nx += 1\nprint(x)\n```\n\nThere are two important actions for interacting with the kernel.  The first is to interrupt it.  This is the same as sending a Control-C from the command line.  The second is to restart it.  This completely terminates the kernel and starts it anew.  None of the kernel state is saved across a restart. \n\n## Markdown cells\n\nText can be added to IPython Notebooks using Markdown cells.  Markdown is a popular markup language that is a superset of HTML.  Its specification can be found here:\n\n<http://daringfireball.net/projects/markdown/>\n\n## Markdown basics\n\n### Text formatting\n\nYou can make text *italic* or **bold** or `monospace`\n\n### Itemized Lists\n\n* One\n    - Sublist\n        - This\n  - Sublist\n        - That\n        - The other thing\n* Two\n  - Sublist\n* Three\n  - Sublist\n\n### Enumerated Lists\n\n1. Here we go\n    1. Sublist\n    2. Sublist\n2. There we go\n3. Now this\n\n### Horizontal Rules\n\n---\n\n---\n\n---\n\n### Blockquotes\n\n> To me programming is more than an important practical art. It is also a gigantic undertaking in the foundations of knowledge. -- Rear Admiral Grace Hopper\n\n### Links\n\n[IPython's website](http://ipython.org)\n\n### Code\n\nThis is a code snippet:    \n    \n```Python\ndef f(x):\n    \"\"\"a docstring\"\"\"\n    return x**2\n```\n        \nThis is an example of a **Python** function\n\nYou can also use triple-backticks to denote code blocks.\nThis also allows you to choose the appropriate syntax highlighter.\n\n```C\nif (i=0; i<n; i++) {\n  printf(\"hello %d\\n\", i);\n  x += 4;\n}\n```\n\n### Tables\n\nTime (s) | Audience Interest\n---------|------------------\n 0       | High\n 1       | Medium\n 5       | Facebook\n\n### Images\n\n\n\n### YouTube\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('vW_DRAJ0dtc')\n```\n\n### Other HTML\n\n<strong> Be Bold! </strong>\n\n## Mathematical Equations\n\nCourtesy of MathJax, you can beautifully render mathematical expressions, both inline: \n$e^{i\\pi} + 1 = 0$, and displayed:\n\n$$e^x=\\sum_{i=0}^\\infty \\frac{1}{i!}x^i$$\n\n### Equation Environments\n\nYou can also use a number of equation environments, such as `align`:\n\n\\begin{align}\n  x &= 4 \\\\\ny+z &= x\n\\end{align}\n\n[A full list of available TeX and LaTeX commands is maintained by Dr. Carol Burns.](http://www.onemathematicalcat.org/MathJaxDocumentation/TeXSyntax.htm)\n\n### Other Useful MathJax Notes\n\n* inline math is demarcated by `$ $`, or `\\( \\)`\n* displayed math is demarcated by `$$ $$` or `\\[ \\]`\n* displayed math environments can also be directly demarcated by `\\begin` and `\\end`\n* `\\newcommand` and `\\def` are supported, *within* areas MathJax processes (such as in a `\\[ \\]` block)\n* equation numbering is not officially supported, but it can be indirectly enabled\n\n## A Note about Notebook Security\n\nBy default, a notebook downloaded to a new computer is *untrusted*\n\n* HTML and Javascript in Markdown cells is now *never* executed\n* HTML and Javascript code outputs must be explicitly *re-executed*\n* Some of these restrictions can be mitigrated through shared accounts (Sage MathCloud) and secrets\n\nMore information on notebook security is in the [IPython Notebook documentation](http://ipython.org/ipython-doc/stable/notebook/security.html)\n\n## Magics\n\nIPython kernels execute a superset of the Python language.  The extension functions, commonly referred to as *magics*, come in two variants.  \n\n### Line Magics\n\n* A *line magic* looks like a command line call.  The most important of these is `%matplotlib inline`, which embeds all matplotlib plot output as images in the notebook itself.\n\n\n```python\n%matplotlib inline\n```\n\n\n```python\n%whos\n```\n\n### Cell Magics\n\n* A *cell magic* takes its entire cell as an argument.  Although there are a number of useful cell magics, you may find `%%timeit` to be useful for exploring code performance.\n\n\n```python\n%%timeit\n\nimport numpy as np\nnp.sum(np.random.rand(1000))\n```\n\n### Execute Code as Python 2\n\n\n```python\n%%python2\n\ni = 10**60\nprint type(i)\n```\n\n### Interacting with the Command Line\n\nIPython supports one final trick, the ability to interact directly with your  shell by using the `!` operator.\n\n\n```python\n!ls\n```\n\n\n```python\nx = !ls\n```\n\n\n```python\nprint(x)\n```\n\n## A Note about Notebook Version Control\n\nThe IPython Notebook is stored using canonicalized JSON for ease of use with version control systems.\n\nThere are two things to be aware of:\n\n* By default, IPython embeds all content and saves kernel execution numbers.  You may want to get in the habit of clearing all cells before committing.\n\n* As of IPython 2.0, all notebooks are signed on save.  This increases the chances of a commit collision during merge, forcing a manual resolution.  Either signature can be safely deleted in this situation.\n", "meta": {"hexsha": "9b23f5f14364fcba4c288c52d1627ac97b149d94", "size": 24979, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lectures/01_intro/code/teach_python_in_notebooks/00_introduction_to_jupyter_notebooks.ipynb", "max_stars_repo_name": "tp5uiuc/soft_systems_course", "max_stars_repo_head_hexsha": "c9585c8fdc7fbc2fd539b4a1ed5e3b43a889a1ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-01-12T21:54:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T09:31:40.000Z", "max_issues_repo_path": "lectures/01_intro/code/teach_python_in_notebooks/00_introduction_to_jupyter_notebooks.ipynb", "max_issues_repo_name": "tp5uiuc/soft_systems_course", "max_issues_repo_head_hexsha": "c9585c8fdc7fbc2fd539b4a1ed5e3b43a889a1ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lectures/01_intro/code/teach_python_in_notebooks/00_introduction_to_jupyter_notebooks.ipynb", "max_forks_repo_name": "tp5uiuc/soft_systems_course", "max_forks_repo_head_hexsha": "c9585c8fdc7fbc2fd539b4a1ed5e3b43a889a1ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8118721461, "max_line_length": 478, "alphanum_fraction": 0.5479402698, "converted": true, "num_tokens": 2720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09807932347046004, "lm_q2_score": 0.18952109819626, "lm_q1q2_score": 0.018588101094467808}}
{"text": "<a href=\"https://colab.research.google.com/github/ChrizZhuang/marginalized_graph_kernel_protein/blob/main/Docking_0609.ipynb\" target=\"_parent\"></a>\n\n\n```\n!nvidia-smi\n```\n\n    Wed Jun  9 15:30:48 2021       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 465.27       Driver Version: 460.32.03    CUDA Version: 11.2     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   34C    P8     9W /  70W |      0MiB / 15109MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    |  No running processes found                                                 |\n    +-----------------------------------------------------------------------------+\n\n\n\n```\n#!pip install pymatgen==2020.12.31\n!pip install pymatgen==2019.11.11\n!pip install --pre graphdot\n!pip install gdown\n```\n\n    Requirement already satisfied: pymatgen==2019.11.11 in /usr/local/lib/python3.7/dist-packages (2019.11.11)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (0.17.8)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.1.5)\n    Requirement already satisfied: numpy>=1.14.3 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.19.5)\n    Requirement already satisfied: pydispatcher>=2.0.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.0.5)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (3.2.2)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (3.3.0)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.7.1)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.5.1)\n    Requirement already satisfied: scipy>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.4.1)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2021.5.9)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.23.0)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (0.8.9)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.16.1)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen==2019.11.11) (0.2.2)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen==2019.11.11) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen==2019.11.11) (2018.9)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (1.3.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (0.10.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (2.4.7)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->pymatgen==2019.11.11) (1.2.1)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.2->pymatgen==2019.11.11) (4.4.2)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (2020.12.5)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas->pymatgen==2019.11.11) (1.15.0)\n    Requirement already satisfied: graphdot in /usr/local/lib/python3.7/dist-packages (0.8a17)\n    Requirement already satisfied: scipy>=1.3.0 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.4.1)\n    Requirement already satisfied: pymatgen==2019.11.11 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2019.11.11)\n    Requirement already satisfied: pycuda>=2019 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2021.1)\n    Requirement already satisfied: mendeleev>=0.7 in /usr/local/lib/python3.7/dist-packages (from graphdot) (0.7.0)\n    Requirement already satisfied: kahypar>=1.1.4 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.1.6)\n    Requirement already satisfied: treelib>=1.6.1 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.6.1)\n    Requirement already satisfied: tqdm>=4.55 in /usr/local/lib/python3.7/dist-packages (from graphdot) (4.61.0)\n    Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.19.5)\n    Requirement already satisfied: ase>=3.17 in /usr/local/lib/python3.7/dist-packages (from graphdot) (3.21.1)\n    Requirement already satisfied: networkx>=2.4 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2.5.1)\n    Requirement already satisfied: numba>=0.51.0 in /usr/local/lib/python3.7/dist-packages (from graphdot) (0.51.2)\n    Requirement already satisfied: pandas>=0.24 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.1.5)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.7.1)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (0.17.8)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (0.8.9)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (1.16.1)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (3.2.2)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2021.5.9)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (3.3.0)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2.23.0)\n    Requirement already satisfied: pydispatcher>=2.0.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2.0.5)\n    Requirement already satisfied: pytools>=2011.2 in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (2021.2.7)\n    Requirement already satisfied: mako in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (1.1.4)\n    Requirement already satisfied: appdirs>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (1.4.4)\n    Requirement already satisfied: pyfiglet<0.9,>=0.8.post1 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (0.8.post1)\n    Requirement already satisfied: colorama<0.5.0,>=0.4.4 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (0.4.4)\n    Requirement already satisfied: Pygments<3.0.0,>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (2.9.0)\n    Requirement already satisfied: six<2.0.0,>=1.15.0 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (1.15.0)\n    Requirement already satisfied: SQLAlchemy<2.0.0,>=1.3.23 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (1.4.15)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from treelib>=1.6.1->graphdot) (0.16.0)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.4->graphdot) (4.4.2)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from numba>=0.51.0->graphdot) (57.0.0)\n    Requirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba>=0.51.0->graphdot) (0.34.0)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->graphdot) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->graphdot) (2018.9)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->graphdot) (1.2.1)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen==2019.11.11->graphdot) (0.2.2)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11->graphdot) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11->graphdot) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11->graphdot) (1.3.1)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (3.0.4)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (2020.12.5)\n    Requirement already satisfied: MarkupSafe>=0.9.2 in /usr/local/lib/python3.7/dist-packages (from mako->pycuda>=2019->graphdot) (2.0.1)\n    Requirement already satisfied: greenlet!=0.4.17; python_version >= \"3\" in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (1.1.0)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (4.0.1)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (3.4.1)\n    Requirement already satisfied: typing-extensions>=3.6.4; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (3.7.4.3)\n    Requirement already satisfied: gdown in /usr/local/lib/python3.7/dist-packages (3.6.4)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from gdown) (2.23.0)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from gdown) (4.61.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from gdown) (1.15.0)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (3.0.4)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (2020.12.5)\n\n\n\n```\n%matplotlib inline\nimport io\nimport sys\nsys.path.append('/usr/local/lib/python3.6/site-packages/')\nimport os\nimport urllib\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport graphdot\nfrom graphdot import Graph\nfrom graphdot.graph.adjacency import AtomicAdjacency\nfrom graphdot.graph.reorder import rcm\nfrom graphdot.kernel.marginalized import MarginalizedGraphKernel # https://graphdot.readthedocs.io/en/latest/apidoc/graphdot.kernel.marginalized.html\nfrom graphdot.kernel.marginalized.starting_probability import Uniform\nfrom graphdot.model.gaussian_process import (\n    GaussianProcessRegressor,\n    LowRankApproximateGPR\n)\nfrom graphdot.kernel.fix import Normalization\nimport graphdot.microkernel as uX\nimport ase.io\n\n# for getting all file names into a list under a directory \nfrom os import listdir\n# for getting file names that match certain pattern\nimport glob\nimport time\n```\n\n    /usr/local/lib/python3.7/dist-packages/graphdot/graph/__init__.py:24: UserWarning: Cannot import RDKit, `graph.from_rdkit()` will be unavailable.\n    \n      'Cannot import RDKit, `graph.from_rdkit()` will be unavailable.\\n'\n\n\n\n```\nfrom google.colab import drive\ndrive.mount('/content/gdrive', force_remount=True)\n```\n\n    Mounted at /content/gdrive\n\n\n\n```\n#cd gdrive/MyDrive/Google\\ Colab/Covid-Data\n%cd gdrive/MyDrive/Covid-Data/\n```\n\n    /content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data\n\n\n\n```\n!pwd\n```\n\n    /content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data\n\n\n\n```\n#!ls\n```\n\n\n```\nfiles  = ['uncharged_NSP15_6W01_A_3_H.Orderable_zinc_db_enaHLL.2col.csv.1.xz']\ndataset = pd.read_pickle(files[0])\n#files  = [f for f in listdir('/content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data')]\n#files = glob.glob(\"uncharged_NSP15_6W01_A_3_H.Orderable_zinc_db_enaHLL.2col.csv.*.xz\")\n#print(files[0:5])\n# concatenate all files into 1 dataset\n#dataset = pd.DataFrame()\n#for i in range(len(files[0:1])):\n#  data = pd.read_pickle(files[i])\n#  print(\"i: \" + str(i) + \" - length of data: \" + str(len(data)))\n#  dataset = pd.concat([dataset, data])\n#frames = [pd.read_pickle(f) for f in files]\n#dataset = pd.concat(frames)\n```\n\n\n```\ntarget = 'energy'\n#N_train = len(dataset)//4\nN_train = 5000\n#N_test = 3 * len(dataset)//4\nN_test = 2500\nprint(N_train)\nprint(N_test)\n```\n\n    5000\n    2500\n\n\n\n```\nnp.random.seed(0)\n# select train and test data\ntrain_sel = np.random.choice(len(dataset), N_train, replace=False)\ntest_sel = np.random.choice(np.setxor1d(np.arange(len(dataset)), train_sel), N_test, replace=False)\ntrain_data = dataset.iloc[train_sel]\ntest_data = dataset.iloc[test_sel]\n```\n\n\n```\ntrain_data.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>energy</th>\n      <th>smiles</th>\n      <th>graphs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>3582</th>\n      <td>-2.874773</td>\n      <td>CN(Cc1nc(no1)c2cccc(c2)Br)C(=O)Nc3cccc(c3)OC</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>60498</th>\n      <td>-3.469760</td>\n      <td>CCOC(=O)c1ccc(c(c1)C)NC(=S)NCCOc2ccc(cc2)C</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>53227</th>\n      <td>-0.487984</td>\n      <td>Cc1ccc(cc1S(=O)(=O)Nc2ccccc2OC)NC(=O)c3nc4nc(c...</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>21333</th>\n      <td>-1.808283</td>\n      <td>COc1ccc(cc1OC)CCNC(=O)COc2ccc(cc2)[N@@](Cc3ccc...</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>3885</th>\n      <td>-2.457642</td>\n      <td>Cc1cc(ccc1NCc2ccc(c(c2OC)C)OC)Br</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\n#uX.SquareExponential?\n```\n\n\n```\ngpr = GaussianProcessRegressor(\n    # kernel is the covariance function of the gaussian process (GP)\n    kernel=Normalization( # kernel equals to normalization -> normalizes a kernel using the cosine of angle formula, k_normalized(x,y) = k(x,y)/sqrt(k(x,x)*k(y,y))\n        # graphdot.kernel.fix.Normalization(kernel), set kernel as marginalized graph kernel, which is used to calculate the similarity between 2 graphs\n        # implement the random walk-based graph similarity kernel as Kashima, H., Tsuda, K., & Inokuchi, A. (2003). Marginalized kernels between labeled graphs. ICML\n        MarginalizedGraphKernel( \n            # node_kernel - A kernelet that computes the similarity between individual nodes\n            # uX - graphdot.microkernel - microkernels are positive-semidefinite functions between individual nodes and edges of graphs\n            node_kernel=uX.Additive( # addition of kernal matrices: sum of k_a(X_a, Y_a) cross for a in features\n                # uX.Constant - a kernel that returns a constant value, always mutlipled with other microkernels as an adjustable weight\n                #   c, the first input arg. as 0.5, (0.01, 10) the lower and upper bounds of c that is allowed to vary during hyperpara. optimizartion\n                # uX.KroneckerDelta - a kronecker delta returns 1 when two features are equal and return h (the first input arg here, which is 0.5 in this case) otherwise\n                #   (0.1, 0.9) the lower and upper bounds that h is allowed to vary during hyperpara. optimization\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 2nd element of graphdot.graph.Graph.nodes\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 3rd element of graphdot.graph.Graph.nodes\n                # uX.SquareExponential - Equ. 26 in the paper\n                # input arg. length_sacle is a float32, set as 1 in this case, which correspond to approx. 1 of the kernal value. \n                # This is used to determins how quicklys should the kernel decay to zero.\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0), # the 4th element of graphdot.graph.Graph.nodes\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 5th element of graphdot.graph.Graph.nodes\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0), # the 6th element of graphdot.graph.Graph.nodes\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 7th element of graphdot.graph.Graph.nodes\n                # uX.Convolution - a convolutional microkernel which averages evaluations of a base microkernel between pairs pf elememts of two variable-length feature sequences\n                # uX.KroneckerDelta as the base kernel\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9))) # the 8th element of graphdot.graph.Graph.nodes\n            ).normalized,\n            # edge_kernel - A kernelet that computes the similarity between individual edge\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 3rd element of graphdot.graph.Graph.nodes\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 4th element of graphdot.graph.Graph.nodes\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 5th element of graphdot.graph.Graph.nodes\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 6th element of graphdot.graph.Graph.nodes\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)) # the 7th element of graphdot.graph.Graph.nodes\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'), # the strating probability of the random walk on each node\n            q=0.05 # the probability for the random walk to stop during each step\n        )\n    ),\n    alpha=1e-4, # value added to the diagonal of the kernel matrix during fitting\n    optimizer=True, # default optimizer of L-BFGS-B based on scipy.optimize.minimize\n    normalize_y=True, # normalize the y values so taht the means and variance is 0 and 1, repsectively. Will be reversed when predicions are returned\n    regularization='+', # alpha (1e-4 in this case) is added to the diagonals of the kernal matrix\n)\n```\n\n\n```\ndef train_pipeline(model, train_dataset, test_dataset, target, repeat, batch_number = 10, verbose = True):\n  start_time = time.time()\n  batch_size = len(train_dataset) // batch_number\n\n  for i in range(batch_number):\n    if i <= 2:\n      train = train_dataset[i*batch_size : (i+1)*batch_size]\n      start_time_i = time.time()\n      model.fit(train.graphs, train[target], repeat=repeat, verbose=verbose)\n      mu = gpr.predict(train.graphs)\n      print('Training set')\n      print('MAE:', np.mean(np.abs(train[target] - mu)))\n      print('RMSE:', np.std(train[target] - mu))\n      mu_test = gpr.predict(test_dataset.graphs)\n      print('Test set')\n      print('MAE:', np.mean(np.abs(test_dataset[target] - mu_test)))\n      print('RMSE:', np.std(test_dataset[target] - mu_test))\n      end_time_i = time.time()\n      print(\"the time consumption for batch \" + str(i) + \" is \" + str(end_time_i - start_time_i) + \".\")\n  \n  end_time = time.time()\n  print(\"the total time consumption is \" + str(end_time - start_time) + \".\")\n```\n\n\n```\n#gpr.fit(train.graphs, train[target], repeat=3, verbose=True)\n# using the molecular graph to predict the energy\n#start_time = time.time()\n#gpr.fit(train.graphs, train[target], repeat=5, verbose=True)\n#end_time = time.time()\n#print(\"the total time consumption is \" + str(end_time - start_time) + \".\")\ntrain_pipeline(gpr, train_data, test_data, target, repeat=1)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  1.0686e+06|  1.1561e+07|   1.072e+06|     -3372.3|  4.0075e+06|       5.8|     0.066|\n    |  6.5657e+05|  8.4731e+06|  6.5964e+05|     -3076.5|  3.3511e+06|       4.6|     0.042|\n    |  4.7205e+05|  6.4569e+06|  4.7494e+05|       -2892|  2.8251e+06|       4.5|     0.043|\n    |   3.582e+05|  4.9102e+06|  3.6095e+05|     -2745.7|  2.3723e+06|       4.4|     0.042|\n    |  2.8733e+05|  3.7866e+06|  2.8996e+05|     -2629.6|  2.0062e+06|       4.3|     0.071|\n    |  2.3926e+05|  2.9416e+06|   2.418e+05|     -2533.9|  1.7145e+06|       4.1|     0.071|\n    |  2.0836e+05|  2.4263e+06|  2.1082e+05|     -2460.6|  1.5218e+06|         4|     0.072|\n    |  1.9248e+05|  2.1623e+06|   1.949e+05|     -2420.5|  1.4096e+06|       3.9|     0.042|\n    |  1.8951e+05|  2.1479e+06|  1.9191e+05|     -2404.1|    1.44e+06|       4.1|     0.068|\n    |  1.8335e+05|  2.0428e+06|  1.8574e+05|     -2392.8|  1.3692e+06|         4|     0.068|\n    |  1.8235e+05|  2.0205e+06|  1.8474e+05|     -2391.5|  1.3487e+06|       3.9|     0.068|\n    |  1.8155e+05|  2.0126e+06|  1.8394e+05|     -2388.5|  1.3505e+06|         4|     0.062|\n    |  1.8109e+05|  2.0082e+06|  1.8347e+05|     -2386.3|  1.3521e+06|         4|     0.072|\n    |  1.8076e+05|  2.0013e+06|  1.8314e+05|     -2385.6|  1.3486e+06|         4|      0.07|\n    |  1.7988e+05|  1.9805e+06|  1.8227e+05|     -2383.5|  1.3339e+06|         4|     0.071|\n    |  1.7964e+05|  1.9755e+06|  1.8202e+05|     -2383.1|  1.3308e+06|         4|      0.07|\n    |  1.7966e+05|  1.9868e+06|  1.8205e+05|       -2382|  1.3298e+06|         4|     0.067|\n    |  1.7958e+05|  1.9795e+06|  1.8196e+05|     -2382.4|  1.3297e+06|         4|     0.042|\n    |  1.7949e+05|   1.978e+06|  1.8187e+05|     -2382.3|  1.3297e+06|         4|     0.045|\n    |  1.7946e+05|   1.978e+06|  1.8184e+05|     -2382.3|  1.3312e+06|         4|     0.075|\n    |  1.7945e+05|  1.9792e+06|  1.8183e+05|     -2382.2|  1.3324e+06|         4|     0.044|\n    |  1.7943e+05|  1.9809e+06|  1.8181e+05|     -2382.2|  1.3337e+06|         4|     0.048|\n    |  1.7945e+05|  1.9844e+06|  1.8184e+05|       -2382|  1.3374e+06|         4|     0.045|\n    |  1.7943e+05|  1.9813e+06|  1.8181e+05|     -2382.1|  1.3341e+06|         4|     0.047|\n    |  1.7941e+05|  1.9805e+06|  1.8179e+05|     -2382.2|  1.3339e+06|         4|     0.076|\n    |  1.7944e+05|  1.9811e+06|  1.8183e+05|     -2382.2|  1.3337e+06|         4|     0.045|\n    |  1.7943e+05|  1.9809e+06|  1.8181e+05|     -2382.2|  1.3337e+06|         4|     0.044|\n    Optimization result:\n          fun: 179429.33945432983\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 1.97950660e+02,  4.51465922e+01,  9.75776696e+00,  2.80002062e+02,\n            4.79031407e+03,  9.43677731e+01,  0.00000000e+00, -3.27468997e+01,\n            2.76421864e+01, -6.99571613e+02,  0.00000000e+00,  4.14971737e+01,\n            9.89558226e+00,  2.68693145e+02,  5.44413646e+03, -4.46075546e+01,\n            5.01709192e+02,  2.49072829e+02,  9.62701354e+02, -2.43018885e+02,\n            4.01947022e+01,  2.12996409e+01,  0.00000000e+00,  1.76477218e+01,\n            2.10190476e+00])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 27\n          nit: 21\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.52503017, -1.92448336,  1.52571156, -2.30258509,\n           -4.60517019,  0.        , -3.80030321, -2.28445206,  2.28700937,\n           -3.07684882, -4.54886626, -1.93096015,  1.65258103, -2.30258509,\n            1.31814606, -2.30258509,  2.00790191, -2.30258509, -2.31025904,\n           -2.30258509, -4.02817508, -0.22314355, -3.89470687, -1.4314819 ])\n    Training set\n    MAE: 0.06004411620625151\n    RMSE: 0.09084672884630779\n    Test set\n    MAE: 1.452499239189198\n    RMSE: 1.8559467353539987\n    the time consumption for batch 0 is 143.84946727752686.\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  1.2519e+05|  1.4263e+06|  1.2753e+05|     -2340.4|  1.0959e+06|       4.8|     0.051|\n    |  1.2735e+05|  1.4715e+06|   1.297e+05|     -2347.1|  1.1142e+06|       3.9|     0.046|\n    |  1.2479e+05|  1.4247e+06|  1.2713e+05|     -2338.8|  1.0937e+06|       3.9|     0.071|\n    |  1.2471e+05|  1.4217e+06|  1.2705e+05|     -2339.7|   1.093e+06|       3.9|     0.045|\n    |  1.2472e+05|  1.4218e+06|  1.2706e+05|     -2339.9|  1.0928e+06|       3.9|     0.041|\n    |  1.2471e+05|  1.4215e+06|  1.2705e+05|     -2339.7|  1.0927e+06|       3.9|     0.062|\n    |   1.247e+05|  1.4215e+06|  1.2704e+05|     -2339.7|  1.0926e+06|       3.9|     0.043|\n    |  1.2471e+05|  1.4217e+06|  1.2705e+05|     -2339.8|  1.0924e+06|       3.9|     0.049|\n    Optimization result:\n          fun: 124713.25761098729\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 142.06797693,   32.71973127,    7.66978489,  168.49263942,\n           2981.37759073,   72.44456019,    0.        ,   92.02534613,\n              7.4341269 , -374.68754709,    0.        ,   17.78156936,\n              9.82757948,   -8.96274872, 4280.9257646 ,   97.61438828,\n            469.6004514 , -118.87164162,  818.70664099,   -7.06578695,\n             15.03482579,   20.0156464 ,    0.        ,    8.35943418,\n              4.40017506])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 8\n          nit: 3\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.52927632, -1.93502958,  1.31553678, -2.30258509,\n           -4.60517019,  0.        , -3.82752096, -2.28541438,  2.30258509,\n           -3.07684882, -4.55147707, -1.94147927,  1.67086347, -2.30258509,\n            1.3304876 , -2.30258509,  1.84742514, -2.30258509, -2.18739265,\n           -2.30258509, -4.04480684, -0.22314355, -3.91414659, -1.45495599])\n    Training set\n    MAE: 0.044935290520298224\n    RMSE: 0.06407467957179624\n    Test set\n    MAE: 1.396688836482435\n    RMSE: 1.785417211722668\n    the time consumption for batch 1 is 56.310078620910645.\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  1.3991e+05|   1.546e+06|  1.4229e+05|     -2376.4|   1.653e+06|       4.8|     0.067|\n    |  1.4845e+05|  1.7231e+06|  1.5084e+05|     -2393.4|  1.6804e+06|       4.3|     0.072|\n    |   1.399e+05|  1.5491e+06|  1.4227e+05|     -2375.9|  1.6506e+06|         4|     0.071|\n    |  1.3988e+05|  1.5494e+06|  1.4226e+05|       -2376|  1.6499e+06|         4|     0.068|\n    |  1.3986e+05|  1.5518e+06|  1.4223e+05|     -2376.6|  1.6456e+06|         4|      0.07|\n    |  1.3986e+05|  1.5507e+06|  1.4224e+05|     -2376.8|  1.6423e+06|         4|     0.042|\n    |  1.3986e+05|  1.5515e+06|  1.4224e+05|     -2376.7|  1.6448e+06|         4|     0.042|\n    |  1.3985e+05|  1.5515e+06|  1.4222e+05|     -2376.6|   1.645e+06|         4|     0.047|\n    |  1.3986e+05|  1.5518e+06|  1.4224e+05|     -2376.6|  1.6456e+06|         4|     0.071|\n    |  1.3984e+05|  1.5514e+06|  1.4222e+05|     -2376.6|  1.6447e+06|         4|     0.073|\n    |  1.3986e+05|  1.5514e+06|  1.4223e+05|     -2376.7|  1.6443e+06|         4|     0.067|\n    |  1.3987e+05|  1.5519e+06|  1.4224e+05|     -2376.7|  1.6453e+06|         4|     0.068|\n    |  1.3987e+05|  1.5521e+06|  1.4224e+05|     -2376.6|  1.6451e+06|         4|     0.042|\n    |  1.3986e+05|  1.5518e+06|  1.4224e+05|     -2376.6|  1.6454e+06|         4|     0.072|\n    |  1.3986e+05|  1.5517e+06|  1.4223e+05|     -2376.6|  1.6449e+06|         4|     0.042|\n    |  1.3986e+05|  1.5518e+06|  1.4224e+05|     -2376.6|  1.6453e+06|         4|     0.072|\n    Optimization result:\n          fun: 139858.54231746125\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 1.55067944e+02,  3.39372833e+01,  8.21098564e+00, -1.81093154e+02,\n            3.23569126e+03,  7.77863796e+01,  0.00000000e+00,  7.19133999e+00,\n            1.80194003e+01, -6.17865950e+01,  0.00000000e+00,  1.85569835e+01,\n            1.04652942e+01,  1.04958302e+02,  4.69377143e+03,  1.88000365e-01,\n            4.41563891e+02,  8.54861306e+01,  8.77936918e+02, -1.11022300e+02,\n            2.86753540e+01,  2.08028991e+01,  0.00000000e+00,  4.50016196e+00,\n            5.77578017e+00])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 16\n          nit: 5\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.54052483, -1.94205752,  1.31385133, -2.30258509,\n           -4.60517019,  0.        , -3.83956236, -2.29095655,  2.2832246 ,\n           -3.07684882, -4.55755202, -1.94913988,  1.69446449, -2.30258509,\n            1.19464039, -2.30258509,  1.89273098, -2.30258509, -2.10196547,\n           -2.30258509, -4.05788703, -0.22314355, -3.9241983 , -1.46729946])\n    Training set\n    MAE: 0.04892710125797727\n    RMSE: 0.07245733796229265\n    Test set\n    MAE: 1.4723089749991387\n    RMSE: 1.8777894382007123\n    the time consumption for batch 2 is 91.03702187538147.\n    the total time consumption is 291.19914746284485.\n\n\n\n```\ngpr.kernel.hyperparameters\n```\n\n\n\n\n    starting_probability : Uniform\n    \tp : 1.0\n    stopping_probability : 0.00010000000000000009\n    node_kernel : Composite\n    \taromatic : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.02343420535068002\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.18860200789175988\n    \tatomic_number : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 5.400776905055444\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tcharge : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.0145590563621646\n    \t\trhs : SquareExponential\n    \t\t\tlength_scale : 1.0\n    \tchiral : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.05149063984443944\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.12853164901299938\n    \thcount : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 10.000000000000002\n    \t\trhs : SquareExponential\n    \t\t\tlength_scale : 0.07795674396128768\n    \thybridization : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.02783411902444354\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.17414808329497075\n    \tring_list : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 6.550981640628747\n    \t\trhs : Convolution\n    \t\t\tbase : KroneckerDelta\n    \t\t\t\th : 0.10000000000000002\n    edge_kernel : Composite\n    \taromatic : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 2.331300736214766\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tconjugated : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 3.166641607522053\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \torder : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.05549109210250382\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.25478481015091287\n    \tring_stereo : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.033323606027544916\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.8\n    \tstereo : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.1324351226762118\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.14521546104851712\n\n\n\n\n```\nmu = gpr.predict(train.graphs)\n```\n\n\n```\nplt.scatter(train[target], mu)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.2074369392067814\n    RMSE: 0.3195501910711287\n\n\n\n```\nmu_test = gpr.predict(test.graphs)\n```\n\n\n```\nplt.scatter(test[target], mu_test)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 1.2461703788060545\n    RMSE: 1.6040210737240486\n\n\nWork\u0001on the kernel. Find a kernel that trains and predicts well.\n\n\n```\ngpr2 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-2, #different from gpr in alpha where gpr's alpha is 1e-4\n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\n#gpr2.fit(train.graphs, train[target], repeat=3, verbose=True)\ngpr2.fit(train.graphs, train[target], repeat=1, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |   1.667e+05|   1.928e+05|  1.7773e+05|      -11034|  2.2742e+05|   1.3e+02|       1.7|\n    |  1.5585e+05|  2.2171e+05|  1.6671e+05|      -10857|  2.2218e+05|   1.3e+02|       1.7|\n    |  1.3711e+05|  2.4873e+05|  1.4756e+05|      -10447|  2.0803e+05|   1.2e+02|       1.8|\n    |  1.3286e+05|  2.3627e+05|   1.432e+05|      -10338|  2.0336e+05|   1.1e+02|       1.7|\n    |  1.2977e+05|  2.2744e+05|  1.4002e+05|      -10249|  1.9714e+05|   1.1e+02|       1.7|\n    |  1.3006e+05|  2.1429e+05|  1.4032e+05|      -10258|  2.0119e+05|     1e+02|       1.7|\n    |  1.2923e+05|  2.2103e+05|  1.3946e+05|      -10238|  1.9906e+05|   1.1e+02|       1.7|\n    |  1.2888e+05|  2.2097e+05|  1.3911e+05|      -10228|  1.9865e+05|   1.1e+02|       1.7|\n    |  1.2843e+05|  2.2338e+05|  1.3864e+05|      -10211|  1.9582e+05|   1.1e+02|       1.7|\n    |  1.2837e+05|  2.2244e+05|  1.3858e+05|      -10212|   1.969e+05|   1.1e+02|       1.7|\n    |  1.2836e+05|  2.2225e+05|  1.3857e+05|      -10212|  1.9696e+05|   1.1e+02|       1.7|\n    |  1.2831e+05|  2.2155e+05|  1.3852e+05|      -10211|  1.9715e+05|   1.1e+02|       1.7|\n    |  1.2826e+05|  2.2184e+05|  1.3847e+05|      -10209|  1.9704e+05|   1.1e+02|       1.7|\n    |  1.2821e+05|  2.2181e+05|  1.3841e+05|      -10207|  1.9671e+05|   1.1e+02|       1.7|\n    |  1.2819e+05|  2.2165e+05|   1.384e+05|      -10207|  1.9664e+05|   1.1e+02|       1.8|\n    |  1.2818e+05|  2.2125e+05|  1.3838e+05|      -10207|  1.9671e+05|   1.1e+02|       1.8|\n    |  1.2817e+05|  2.2114e+05|  1.3838e+05|      -10207|  1.9673e+05|   1.1e+02|       1.7|\n    |  1.2815e+05|  2.2077e+05|  1.3836e+05|      -10207|  1.9677e+05|   1.1e+02|       1.7|\n    |  1.2812e+05|   2.185e+05|  1.3833e+05|      -10209|  1.9695e+05|   1.1e+02|       1.7|\n    |  1.2809e+05|   2.178e+05|   1.383e+05|      -10209|    1.97e+05|   1.1e+02|       1.7|\n    |  1.2807e+05|  2.1764e+05|  1.3828e+05|      -10208|  1.9695e+05|   1.1e+02|       1.7|\n    |  1.2805e+05|  2.1597e+05|  1.3826e+05|      -10209|  1.9693e+05|   1.1e+02|       1.7|\n    |  1.2805e+05|   2.172e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1693e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.8|\n    |  1.2804e+05|  2.1674e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1691e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2805e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.8|\n    |  1.2805e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    Optimization result:\n          fun: 128045.20193517115\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 21.67035135,   5.42797631,   0.91584794,   6.62684845,\n           636.88297304,  10.22203408,   0.        ,   6.13155297,\n             0.80318432, -45.79780911,   0.        ,   9.32446636,\n             2.06137402,   7.94609186, 767.483899  ,  -8.19180354,\n            92.93654292,   7.92503084, 118.62629465,   3.36719643,\n            38.71995733,   7.96834618,   0.        , -11.08475724,\n             7.2860016 ])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 31\n          nit: 21\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.51710969, -1.98267626,  1.72521606, -2.30258509,\n           -4.60517019,  0.        , -4.60517019, -1.8070945 ,  2.30258509,\n           -2.88031384, -3.6019383 , -2.30258509,  1.91177723, -2.30258509,\n            0.28746812, -2.30258509,  0.54884256, -2.30258509, -0.5686784 ,\n           -2.30258509, -4.35637808, -0.22314355, -2.55717239, -2.21179129])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7f6bf00630d0>\n\n\n\n\n```\nmu = gpr2.predict(train.graphs)\nplt.scatter(train[target], mu)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.7238389142657052\n    RMSE: 0.9634943206325994\n\n\n\n```\nmu_test = gpr2.predict(test.graphs)\nplt.scatter(test[target], mu_test)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 0.9561539409612109\n    RMSE: 1.2284268143181998\n\n", "meta": {"hexsha": "2ad498e4c92ed8267dea089f5a2fd4fb0241c9e9", "size": 117473, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Docking_0609.ipynb", "max_stars_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_stars_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Docking_0609.ipynb", "max_issues_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_issues_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Docking_0609.ipynb", "max_forks_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_forks_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 96.0531479967, "max_line_length": 16574, "alphanum_fraction": 0.7104100517, "converted": true, "num_tokens": 16573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180267058489, "lm_q2_score": 0.04742586880186649, "lm_q1q2_score": 0.018430547548591837}}
{"text": "# Ray RLlib - Introduction to Reinforcement Learning\n\n\u00a9 2019-2022, Anyscale. All Rights Reserved\n\n\n\n_Reinforcement Learning_ is the category of machine learning that focuses on training one or more _agents_ to achieve maximal _rewards_ while operating in an environment. This lesson discusses the core concepts of RL, while subsequent lessons explore RLlib in depth. We'll use two examples with exercises to give you a taste of RL. If you already understand RL concepts, you can either skim this lesson or skip to the [next lesson](02-Introduction-to-RLlib.ipynb).\n\n## What Is Reinforcement Learning?\n\nLet's explore the basic concepts of RL, specifically the _Markov Decision Process_ abstraction, and to show its use in Python.\n\nConsider the following image:\n\n\n\nIn RL, one or more **agents** interact with an **environment** to maximize a **reward**. The agents make **observations** about the **state** of the environment and take **actions** that are believed will maximize the long-term reward. However, at any particular moment, the agents can only observe the immediate reward. So, the training process usually involves lots and lot of replay of the game, the robot simulator traversing a virtual space, etc., so the agents can learn from repeated trials what decisions/actions work best to maximize the long-term, cumulative reward.\n\nThe trial and error search and delayed reward are the distinguishing characterists of RL vs. other ML methods ([Sutton 2018](06-RL-References.ipynb#Books)).\n\nThe way to formalize trial and error is the **exploitation vs. exploration tradeoff**. When an agent finds what appears to be a \"rewarding\" sequence of actions, the agent may naturally want to continue to **exploit** these actions. However, even better actions may exist. An agent won't know whether alternatives are better or not unless some percentage of actions taken **explore** the alternatives. So, all RL algorithms include a strategy for exploitation and exploration.\n\n## RL Applications\n\nRL has many potential applications. RL became \"famous\" due to these successes, including achieving expert game play, training robots, autonomous vehicles, and other simulated agents:\n\n\n\nThe famous Alpha Go Game\n\n\n\nPlaying Atari with Deep Reinforcement Learning \n\n\n\nLearning to stack legos using RL\n\n\n\nThe famous walking man scenario\n\n\n\nThe autonous vehicles increasingly becoming prevalent\n\n\n\nThe cartonish two-legged robot, Cassie\n\n\nCredits and References:\n* [AlphaGo](https://www.youtube.com/watch?v=l7ngy56GY6k)\n* [Breakout](https://towardsdatascience.com/tutorial-double-deep-q-learning-with-dueling-network-architectures-4c1b3fb7f756) ([paper](https://arxiv.org/abs/1312.5602))\n* [Stacking Legos with Sawyer](https://robohub.org/soft-actor-critic-deep-reinforcement-learning-with-real-world-robots/)\n* [Walking Man](https://openai.com/blog/openai-baselines-ppo/)\n* [Autonomous Vehicle](https://www.daimler.com/innovation/case/autonomous/intelligent-drive-2.html)\n* [\"Cassie\": Two-legged Robot](https://mime.oregonstate.edu/research/drl/robots/cassie/) (Uses Ray!)\n\nRecently, other industry applications have emerged, include the following:\n\n* **Process optimization:** industrial processes (factories, pipelines) and other business processes, routing problems, cluster optimization.\n* **Ad serving and recommendations:** Some of the traditional methods, including _collaborative filtering_, are hard to scale for very large data sets. RL systems are being developed to do an effective job more efficiently than traditional methods.\n* **Finance:** Markets are time-oriented _environments_ where automated trading systems are the _agents_. \n\n## Markov Decision Processes\n\nAt its core, Reinforcement learning builds on the concepts of [Markov Decision Process (MDP)](https://en.wikipedia.org/wiki/Markov_decision_process), where the current state, the possible actions that can be taken, and overall goal are the building blocks.\n\nAn MDP model's sequential interactions with an external environment consists of the following:\n\n- a **state space** where the current state of the system is sometimes called the **context**.\n- a set of **actions** that can be taken at a particular state $s$ (or sometimes the same set for all states).\n- a **transition function** that describes the probability of being in a state $s'$ at time $t+1$ given that the MDP was in state $s$ at time $t$ and an action $a$ was taken. The next state is selected stochastically based on these probabilities.\n- a **reward function**, which determines the reward received at time $t$ following action $a$, based on the decision of **policy** $\\pi$.\n\nThe goal of MDP is to develop a **policy** $\\pi$ that specifies what action $a$ should be chosen for a given state $s$ so that the cumulative reward is maximized. When it is possible for the policy \"trainer\" to fully observe all the possible states, actions, and rewards, it can define a deterministic policy, fixing a single action choice for each state. In this scenario, the transition probabilities reduce to the probability of transitioning to state $s'$ given the current state is $s$, independent of actions, because the state now leads to a deterministic action choice. Various algorithms can be used to compute this policy. \n\nPut another way, if the policy isn't deterministic, then the transition probability to state $s'$ at a time $t+1$ when action $a$ is taken for state $s$ at time $t$, is given by:\n\n\\begin{equation}\nP_a(s',s) = P(s_{t+1} = s'|s_t=s,a)\n\\end{equation}\n\nWhen the policy is deterministic, this transition probability reduces to the following, independent of $a$:\n\n\\begin{equation}\nP(s',s) = P(s_{t+1} = s'|s_t=s)\n\\end{equation}\n\nTo be clear, a deterministic policy means that one and only one action will always be selected for a given state $s$, but the next state $s'$ will still be selected stochastically.\n\nIn the general case of RL, it isn't possible to fully know all this information, some of which might be hidden and evolving, so it isn't possible to specify a fully-deterministic policy.\n\nOften this cumulative reward is computed using the **discounted sum** over all rewards observed:\n\n\\begin{equation}\n\\arg\\max_{\\pi} \\sum_{t=1}^T \\gamma^t R_t(\\pi),\n\\end{equation}\n\nwhere $T$ is the number of steps taken in the MDP (this is a random variable and may depend on $\\pi$), $R_t$ is the reward received at time $t$ (also a random variable which depends on $\\pi$), and $\\gamma$ is the **discount factor**. The value of $\\gamma$ is between 0 and 1, meaning it has the effect of \"discounting\" earlier rewards vs. more recent rewards. \n\nThe [Wikipedia page on MDP](https://en.wikipedia.org/wiki/Markov_decision_process) provides more details. Note what we said in the third bullet, that the new state only depends on the previous state and the action taken. The assumption is that we can simplify our effort by ignoring all the previous states except the last one and still achieve good results. This is known as the [Markov property](https://en.wikipedia.org/wiki/Markov_property). This assumption often works well and it greatly reduces the resources required.\n\n## The Elements of RL\n\nHere are the elements of RL that expand on MDP concepts (see [Sutton 2018](https://mitpress.mit.edu/books/reinforcement-learning-second-edition) for more details):\n\n#### Policies\n\nUnlike MDP, the **transition function** probabilities are often not known in advance, but must be learned. Learning is done through repeated \"play,\" where the agent interacts with the environment.\n\nThis makes the **policy** $\\pi$ harder to determine. Because the fully state space usually can't be fully known, the choice of an action $a$ for given state $s$ almostly always remains a stochastic choice, never deterministic, unlike MDP.\n\n#### Reward Signal\n\nThe idea of a **reward signal** encapsulates the desired goal for the system and provides feedback for updating the policy based on how well particular events or actions contribute rewards towards the goal.\n\n#### Value Function\n\nThe **value function** encapsulates the maximum cumulative reward likely to be achieved starting from a given state for an **episode**. This is harder to determine than the simple reward returned after taking an action. In fact, much of the research in RL over the decades has focused on finding better and more efficient implementations of value functions. To illustrate the challenge, repeatedly taking one sequence of actions may yield low rewards for a while, but eventually provide large rewards. Conversely, always choosing a different sequence of actions may yield a good reward at each step, but be suboptimal for the cumulative reward.\n\n#### Episode\n\nA sequence of steps by the agent starting in an initial state. At each step, the agent observes the current state, chooses the next action, and receives the new reward. Episodes are used for both training policies and replaying with an existing policy (called _rollout_).\n\n#### Model\n\nAn optional feature, some RL algorithms develop or use a **model** of the environment to anticipate the resulting states and rewards for future actions. Hence, they are useful for _planning_ scenarios. Methods for solving RL problems that use models are called _model-based methods_, while methods that learn by trial and error are called _model-free methods_.\n\n## Reinforcement Learning Example\n\nLet's finish this introduction and let's learn about the popular \"hello world\" [1] example environment for RL, balancing a pole vertically on a moving cart, called `CartPole`. Then we'll see how to use RLlib to train a policy using a popular RL algorithm, _Proximal Policy Optimization_, again using `CartPole`.\n\n[1] In books and tutorials on programming languages, it is a tradition that the very first program shown prints the message \"Hello World!\"\n\n### CartPole and OpenAI\n\nThe popular [OpenAI \"gym\" environment](https://gym.openai.com/) provides MDP interfaces to a variety of simulated environments. Perhaps the most popular for learning RL is `CartPole`, a simple environment that simulates the physics of balancing a pole on a moving cart. The `CartPole` problem is described at https://gym.openai.com/envs/CartPole-v1. Here is an image from that website, where the pole is currently falling to the right, which means the cart will need to move to the right to restore balance:\n\n\n\nThis example fits into the MDP framework as follows:\n- The **state** consists of the position and velocity of the cart (moving in one dimension from left to right) as well as the angle and angular velocity of the pole that is balancing on the cart.\n- The **actions** are to decrease or increase the cart's velocity by one unit. A negative velocity means it is moving to the left.\n- The **transition function** is deterministic and is determined by simulating physical laws. Specifically, for a given **state**, what should we choose as the next velocity value? In the RL context, the correct velocity value to choose has to be learned. Hence, we learn a _policy_ that approximates the optimal transition function that could be calculated from the laws of physics.\n- The **reward function** is a constant 1 as long as the pole is upright, and 0 once the pole has fallen over. Therefore, maximizing the reward means balancing the pole for as long as possible.\n- The **discount factor** in this case can be taken to be 1, meaning we treat the rewards at all time steps equally and don't discount any of them.\n\nMore information about the `gym` Python module is available at https://gym.openai.com/. The list of all the available Gym environments is in [this wiki page](https://github.com/openai/gym/wiki/Table-of-environments). We'll use a few more of them and even create our own in subsequent lessons.\n\n\n```python\nimport gym\nimport numpy as np\nimport pandas as pd\nimport json\n```\n\nThe code below illustrates how to create and manipulate MDPs in Python. An MDP can be created by calling `gym.make`. Gym environments are identified by names like `CartPole-v1`. A **catalog of built-in environments** can be found at https://gym.openai.com/envs.\n\n\n```python\nenv = gym.make(\"CartPole-v1\")\nprint(\"Created env:\", env)\n```\n\n    Created env: <TimeLimit<CartPoleEnv<CartPole-v1>>>\n\n\nReset the state of the MDP by calling `env.reset()`. This call returns the initial state of the MDP.\n\n\n```python\nstate = env.reset()\nprint(\"The starting state is:\", state)\n```\n\n    The starting state is: [ 0.04093885 -0.03678606  0.02658814  0.01931461]\n\n\nRecall that the state is the position of the cart, its velocity, the angle of the pole, and the angular velocity of the pole.\n\nThe `env.step` method takes an action. In the case of the `CartPole` environment, the appropriate actions are 0 or 1, for pushing the cart to the left or right, respectively. `env.step()` returns a tuple of four things:\n1. the new state of the environment\n2. a reward\n3. a boolean indicating whether the simulation has finished\n4. a dictionary of miscellaneous extra information\n\nLet's show what happens if we take one step with an action of 0.\n\n\n```python\naction = 0\nstate, reward, done, info = env.step(action)\nprint(state, reward, done, info)\n```\n\n    [ 0.04020313 -0.23227903  0.02697443  0.3202664 ] 1.0 False {}\n\n\nA **rollout** is a simulation of a policy in an environment. It is used both during training and when running simulations with a trained policy. \n\nThe code below performs a rollout in a given environment. It takes **random actions** until the simulation has finished and returns the cumulative reward.\n\n\n```python\ndef random_rollout(env):\n    state = env.reset()\n    \n    done = False\n    cumulative_reward = 0\n\n    # Keep looping as long as the simulation has not finished.\n    while not done:\n        # Choose a random action (either 0 or 1).\n        action = np.random.choice([0, 1])\n        \n        # Take the action in the environment.\n        state, reward, done, _ = env.step(action)\n        \n        # Update the cumulative reward.\n        cumulative_reward += reward\n    \n    # Return the cumulative reward.\n    return cumulative_reward    \n```\n\nTry rerunning the following cell a few times. How much do the answers change? Note that the maximum possible reward for `CartPole-v1` is 500. You'll probably get numbers well under 500.\n\n\n```python\nreward = random_rollout(env)\nprint(reward)\n\nreward = random_rollout(env)\nprint(reward)\n```\n\n    17.0\n    48.0\n\n\n### Exercise 1\n\nChoosing actions at random in `random_rollout` is not a very effective policy, as the previous results showed. Finish implementing the `rollout_policy` function below, which takes an environment *and* a policy. Recall that the *policy* is a function that takes in a *state* and returns an *action*. The main difference is that instead of choosing a **random action**, like we just did (with poor results), the action should be chosen **with the policy** (as a function of the state).\n\n> **Note:** Exercise solutions for this tutorial can be found [here](solutions/Ray-RLlib-Solutions.ipynb).\n\n\n```python\ndef rollout_policy(env, policy):\n    state = env.reset()\n    \n    done = False\n    cumulative_reward = 0\n\n    # EXERCISE: Fill out this function by copying the appropriate part of 'random_rollout'\n    # and modifying it to choose the action using the policy.\n    raise NotImplementedError\n\n    # Return the cumulative reward.\n    return cumulative_reward\n\ndef sample_policy1(state):\n    return 0 if state[0] < 0 else 1\n\ndef sample_policy2(state):\n    return 1 if state[0] < 0 else 0\n\nreward1 = np.mean([rollout_policy(env, sample_policy1) for _ in range(100)])\nreward2 = np.mean([rollout_policy(env, sample_policy2) for _ in range(100)])\n\nprint('The first sample policy got an average reward of {}.'.format(reward1))\nprint('The second sample policy got an average reward of {}.'.format(reward2))\n\nassert 5 < reward1 < 15, ('Make sure that rollout_policy computes the action '\n                          'by applying the policy to the state.')\nassert 25 < reward2 < 35, ('Make sure that rollout_policy computes the action '\n                           'by applying the policy to the state.')\n```\n\nWe'll return to `CartPole` in lesson [01: Application Cart Pole](explore-rllib/01-Application-Cart-Pole.ipynb) in the `explore-rllib` section.\n\n### RLlib Reinforcement Learning Example: Cart Pole with Proximal Policy Optimization\n\nThis section demonstrates how to use the _proximal policy optimization_ (PPO) algorithm implemented by [RLlib](http://rllib.io). PPO is a popular way to develop a policy. RLlib also uses [Ray Tune](http://tune.io), the Ray Hyperparameter Tuning framework, which is covered in the [Ray Tune Tutorial](../ray-tune/00-Ray-Tune-Overview.ipynb).\n\nWe'll provide relatively little explanation of **RLlib** concepts for now, but explore them in greater depth in subsequent lessons. For more on RLlib, see the documentation at http://rllib.io.\n\nPPO is described in detail in [this paper](https://arxiv.org/abs/1707.06347). It is a variant of _Trust Region Policy Optimization_ (TRPO) described in [this earlier paper](https://arxiv.org/abs/1502.05477). [This OpenAI post](https://openai.com/blog/openai-baselines-ppo/) provides a more accessible introduction to PPO.\n\nPPO works in two phases. In the first phase, a large number of rollouts are performed in parallel. The rollouts are then aggregated on the driver and a surrogate optimization objective is defined based on those rollouts. In the second phase, we use SGD (_stochastic gradient descent_) to find the policy that maximizes that objective with a penalty term for diverging too much from the current policy.\n\n\n\n> **NOTE:** The SGD optimization step is best performed in a data-parallel manner over multiple GPUs. This is exposed through the `num_gpus` field of the `config` dictionary. Hence, for normal usage, one or more GPUs is recommended.\n\n(The original version of this example can be found [here](https://raw.githubusercontent.com/ucbrise/risecamp/risecamp2018/ray/tutorial/rllib_exercises/)).\n\n\n```python\nimport ray\nfrom ray.rllib.agents.ppo import PPOTrainer, DEFAULT_CONFIG\nfrom ray.tune.logger import pretty_print\n```\n\nInitialize Ray. If you are running these tutorials on your laptop, then a single-node Ray cluster will be started by the next cell. If you are running in the Anyscale platform, it will connect to the running Ray cluster.\n\n\n```python\ninfo = ray.init(ignore_reinit_error=True, log_to_driver=False)\nprint(info)\n```\n\n    2022-03-17 16:09:28,771\tINFO services.py:1412 -- View the Ray dashboard at \u001b[1m\u001b[32mhttp://127.0.0.1:8265\u001b[39m\u001b[22m\n\n\n    {'node_ip_address': '127.0.0.1', 'raylet_ip_address': '127.0.0.1', 'redis_address': None, 'object_store_address': '/tmp/ray/session_2022-03-17_16-09-26_550801_99855/sockets/plasma_store', 'raylet_socket_name': '/tmp/ray/session_2022-03-17_16-09-26_550801_99855/sockets/raylet', 'webui_url': '127.0.0.1:8265', 'session_dir': '/tmp/ray/session_2022-03-17_16-09-26_550801_99855', 'metrics_export_port': 62444, 'gcs_address': '127.0.0.1:53561', 'address': '127.0.0.1:53561', 'node_id': 'b948df77a0e95112f1432667f1fe3d29c78870984c4409b6b96232ab'}\n\n\n> **Tip:** Having trouble starting Ray? See the [Troubleshooting](../reference/Troubleshooting-Tips-Tricks.ipynb) tips.\n\nThe next cell prints the URL for the Ray Dashboard. **This is only correct if you are running this tutorial on a laptop.** Click the link to open the dashboard.\n\nIf you are running on the Anyscale platform, use the URL provided by your instructor to open the Dashboard.\n\n\n```python\nprint(\"Dashboard URL: http://{}\".format(info[\"webui_url\"]))\n```\n\n    Dashboard URL: http://127.0.0.1:8265\n\n\nInstantiate a PPOTrainer object. We pass in a config object that specifies how the network and training procedure should be configured. Some of the parameters are the following.\n\n- `num_workers` is the number of actors that the agent will create. This determines the degree of parallelism that will be used. In a cluster, these actors will be spread over the available nodes.\n- `num_sgd_iter` is the number of epochs of SGD (stochastic gradient descent, i.e., passes through the data) that will be used to optimize the PPO surrogate objective at each iteration of PPO, for each _minibatch_ (\"chunk\") of training data. Using minibatches is more efficient than training with one record at a time.\n- `sgd_minibatch_size` is the SGD minibatch size (batches of data) that will be used to optimize the PPO surrogate objective.\n- `model` contains a dictionary of parameters describing the neural net used to parameterize the policy. The `fcnet_hiddens` parameter is a list of the sizes of the hidden layers. Here, we have two hidden layers of size 100, each.\n- `num_cpus_per_worker` when set to 0 prevents Ray from pinning a CPU core to each worker, which means we could run out of workers in a constrained environment like a laptop or a cloud VM.\n\n\n```python\nconfig = DEFAULT_CONFIG.copy()\nconfig['num_workers'] = 1\nconfig['num_sgd_iter'] = 30\nconfig['sgd_minibatch_size'] = 128\nconfig['model']['fcnet_hiddens'] = [100, 100]\nconfig['num_cpus_per_worker'] = 0 \n```\n\n\n```python\nagent = PPOTrainer(config, 'CartPole-v1')\n```\n\n    2022-03-17 16:09:49,745\tWARNING util.py:55 -- Install gputil for GPU system monitoring.\n\n\nNow let's train the policy on the `CartPole-v1` environment for `N` steps. The JSON object returned by each call to `agent.train()` contains a lot of information we'll inspect below. For now, we'll extract information we'll graph, such as `episode_reward_mean`. The _mean_ values are more useful for determining successful training.\n\n\n```python\nN = 10\nresults = []\nepisode_data = []\nepisode_json = []\n\nfor n in range(N):\n    result = agent.train()\n    results.append(result)\n    \n    episode = {'n': n, \n               'episode_reward_min':  result['episode_reward_min'],  \n               'episode_reward_mean': result['episode_reward_mean'], \n               'episode_reward_max':  result['episode_reward_max'],  \n               'episode_len_mean':    result['episode_len_mean']} \n    \n    episode_data.append(episode)\n    episode_json.append(json.dumps(episode))\n    \n    print(f'{n:3d}: Min/Mean/Max reward: {result[\"episode_reward_min\"]:8.4f}/{result[\"episode_reward_mean\"]:8.4f}/{result[\"episode_reward_max\"]:8.4f}')\n```\n\n      0: Min/Mean/Max reward:   8.0000/ 22.4157/ 92.0000\n      1: Min/Mean/Max reward:   9.0000/ 37.3868/123.0000\n      2: Min/Mean/Max reward:   9.0000/ 54.8000/138.0000\n      3: Min/Mean/Max reward:  10.0000/ 84.6300/379.0000\n      4: Min/Mean/Max reward:  10.0000/117.7400/397.0000\n      5: Min/Mean/Max reward:  10.0000/149.7000/500.0000\n      6: Min/Mean/Max reward:  10.0000/178.4400/500.0000\n      7: Min/Mean/Max reward:  12.0000/209.8400/500.0000\n      8: Min/Mean/Max reward:  12.0000/244.6100/500.0000\n      9: Min/Mean/Max reward:  12.0000/270.0500/500.0000\n\n\nNow let's convert the episode data to a Pandas `DataFrame` for easy manipulation. The results indicate how much reward the policy is receiving (`episode_reward_*`) and how many time steps of the environment the policy ran (`episode_len_mean`). The maximum possible reward for this problem is `500`. The reward mean and trajectory length are very close because the agent receives a reward of one for every time step that it survives. However, this is specific to this environment and not true in general.\n\n\n```python\ndf = pd.DataFrame(data=episode_data)\ndf\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>n</th>\n      <th>episode_reward_min</th>\n      <th>episode_reward_mean</th>\n      <th>episode_reward_max</th>\n      <th>episode_len_mean</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0</td>\n      <td>8.0</td>\n      <td>22.415730</td>\n      <td>92.0</td>\n      <td>22.415730</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>9.0</td>\n      <td>37.386792</td>\n      <td>123.0</td>\n      <td>37.386792</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2</td>\n      <td>9.0</td>\n      <td>54.800000</td>\n      <td>138.0</td>\n      <td>54.800000</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>3</td>\n      <td>10.0</td>\n      <td>84.630000</td>\n      <td>379.0</td>\n      <td>84.630000</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>4</td>\n      <td>10.0</td>\n      <td>117.740000</td>\n      <td>397.0</td>\n      <td>117.740000</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>5</td>\n      <td>10.0</td>\n      <td>149.700000</td>\n      <td>500.0</td>\n      <td>149.700000</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>6</td>\n      <td>10.0</td>\n      <td>178.440000</td>\n      <td>500.0</td>\n      <td>178.440000</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>7</td>\n      <td>12.0</td>\n      <td>209.840000</td>\n      <td>500.0</td>\n      <td>209.840000</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>8</td>\n      <td>12.0</td>\n      <td>244.610000</td>\n      <td>500.0</td>\n      <td>244.610000</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>9</td>\n      <td>12.0</td>\n      <td>270.050000</td>\n      <td>500.0</td>\n      <td>270.050000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf.columns.tolist()\n```\n\n\n\n\n    ['n',\n     'episode_reward_min',\n     'episode_reward_mean',\n     'episode_reward_max',\n     'episode_len_mean']\n\n\n\nLet's plot the data. Since the length and reward means are equal, we'll only plot one line:\n\n\n```python\ndf.plot(x=\"n\", y=[\"episode_reward_mean\", \"episode_reward_min\", \"episode_reward_max\"], secondary_y=True)\n```\n\nThe model is quickly able to hit the maximum value of 500, but the mean is what's most valuable. After 10 steps, we're more than half way there.\n\nFYI, here are two views of the whole value for one result. First, a \"pretty print\" output.\n\n> **Tip:** The output will be long. When this happens for a cell, right click and select _Enable scrolling for outputs_.\n\n\n```python\nprint(pretty_print(results[-1]))\n```\n\n    agent_timesteps_total: 40000\n    custom_metrics: {}\n    date: 2022-03-17_16-11-03\n    done: false\n    episode_len_mean: 270.05\n    episode_media: {}\n    episode_reward_max: 500.0\n    episode_reward_mean: 270.05\n    episode_reward_min: 12.0\n    episodes_this_iter: 12\n    episodes_total: 441\n    experiment_id: 73459c6b55f748bdae8d42fe303b6f9a\n    hostname: Juless-MacBook-Pro-16-inch-2019\n    info:\n      learner:\n        default_policy:\n          custom_metrics: {}\n          learner_stats:\n            cur_kl_coeff: 0.03750000149011612\n            cur_lr: 4.999999873689376e-05\n            entropy: 0.5147084593772888\n            entropy_coeff: 0.0\n            kl: 0.004637665580958128\n            model: {}\n            policy_loss: -0.00826053787022829\n            total_loss: 832.4736328125\n            vf_explained_var: 0.16725607216358185\n            vf_loss: 832.4817504882812\n      num_agent_steps_sampled: 40000\n      num_agent_steps_trained: 40000\n      num_steps_sampled: 40000\n      num_steps_trained: 40000\n      num_steps_trained_this_iter: 4000\n    iterations_since_restore: 10\n    node_ip: 127.0.0.1\n    num_healthy_workers: 1\n    off_policy_estimator: {}\n    perf:\n      cpu_util_percent: 0.0\n      ram_util_percent: 51.42\n    pid: 99855\n    policy_reward_max: {}\n    policy_reward_mean: {}\n    policy_reward_min: {}\n    sampler_perf:\n      mean_action_processing_ms: 0.04614653261891873\n      mean_env_render_ms: 0.0\n      mean_env_wait_ms: 0.04571587329741563\n      mean_inference_ms: 0.42432151722661793\n      mean_raw_obs_processing_ms: 0.06788292425999021\n    time_since_restore: 36.21382212638855\n    time_this_iter_s: 3.654078960418701\n    time_total_s: 36.21382212638855\n    timers:\n      learn_throughput: 3203.836\n      learn_time_ms: 1248.504\n      load_throughput: 16727034.895\n      load_time_ms: 0.239\n      sample_throughput: 553.77\n      sample_time_ms: 7223.22\n      update_time_ms: 1.596\n    timestamp: 1647558663\n    timesteps_since_restore: 40000\n    timesteps_this_iter: 4000\n    timesteps_total: 40000\n    training_iteration: 10\n    trial_id: default\n    \n\n\nWe'll learn about more of these values as continue the tutorial.\n\nThe whole, long JSON blob, which includes the historical stats about episode rewards and lengths:\n\n\n```python\nresults[-1]\n```\n\n\n\n\n    {'episode_reward_max': 500.0,\n     'episode_reward_min': 12.0,\n     'episode_reward_mean': 270.05,\n     'episode_len_mean': 270.05,\n     'episode_media': {},\n     'episodes_this_iter': 12,\n     'policy_reward_min': {},\n     'policy_reward_max': {},\n     'policy_reward_mean': {},\n     'custom_metrics': {},\n     'hist_stats': {'episode_reward': [34.0,\n       241.0,\n       191.0,\n       171.0,\n       83.0,\n       237.0,\n       151.0,\n       124.0,\n       18.0,\n       206.0,\n       66.0,\n       140.0,\n       32.0,\n       132.0,\n       186.0,\n       144.0,\n       73.0,\n       148.0,\n       106.0,\n       182.0,\n       159.0,\n       75.0,\n       191.0,\n       186.0,\n       275.0,\n       184.0,\n       236.0,\n       252.0,\n       317.0,\n       152.0,\n       174.0,\n       397.0,\n       103.0,\n       262.0,\n       156.0,\n       328.0,\n       261.0,\n       189.0,\n       243.0,\n       141.0,\n       12.0,\n       176.0,\n       330.0,\n       250.0,\n       323.0,\n       214.0,\n       270.0,\n       272.0,\n       289.0,\n       286.0,\n       243.0,\n       295.0,\n       261.0,\n       383.0,\n       500.0,\n       163.0,\n       215.0,\n       140.0,\n       342.0,\n       165.0,\n       295.0,\n       439.0,\n       300.0,\n       398.0,\n       475.0,\n       329.0,\n       330.0,\n       88.0,\n       367.0,\n       242.0,\n       500.0,\n       476.0,\n       381.0,\n       401.0,\n       388.0,\n       500.0,\n       182.0,\n       370.0,\n       500.0,\n       500.0,\n       424.0,\n       456.0,\n       500.0,\n       456.0,\n       406.0,\n       500.0,\n       500.0,\n       355.0,\n       500.0,\n       500.0,\n       90.0,\n       255.0,\n       341.0,\n       261.0,\n       375.0,\n       337.0,\n       500.0,\n       190.0,\n       173.0,\n       350.0],\n      'episode_lengths': [34,\n       241,\n       191,\n       171,\n       83,\n       237,\n       151,\n       124,\n       18,\n       206,\n       66,\n       140,\n       32,\n       132,\n       186,\n       144,\n       73,\n       148,\n       106,\n       182,\n       159,\n       75,\n       191,\n       186,\n       275,\n       184,\n       236,\n       252,\n       317,\n       152,\n       174,\n       397,\n       103,\n       262,\n       156,\n       328,\n       261,\n       189,\n       243,\n       141,\n       12,\n       176,\n       330,\n       250,\n       323,\n       214,\n       270,\n       272,\n       289,\n       286,\n       243,\n       295,\n       261,\n       383,\n       500,\n       163,\n       215,\n       140,\n       342,\n       165,\n       295,\n       439,\n       300,\n       398,\n       475,\n       329,\n       330,\n       88,\n       367,\n       242,\n       500,\n       476,\n       381,\n       401,\n       388,\n       500,\n       182,\n       370,\n       500,\n       500,\n       424,\n       456,\n       500,\n       456,\n       406,\n       500,\n       500,\n       355,\n       500,\n       500,\n       90,\n       255,\n       341,\n       261,\n       375,\n       337,\n       500,\n       190,\n       173,\n       350]},\n     'sampler_perf': {'mean_raw_obs_processing_ms': 0.06788292425999021,\n      'mean_inference_ms': 0.42432151722661793,\n      'mean_action_processing_ms': 0.04614653261891873,\n      'mean_env_wait_ms': 0.04571587329741563,\n      'mean_env_render_ms': 0.0},\n     'off_policy_estimator': {},\n     'num_healthy_workers': 1,\n     'timesteps_total': 40000,\n     'timesteps_this_iter': 4000,\n     'agent_timesteps_total': 40000,\n     'timers': {'sample_time_ms': 7223.22,\n      'sample_throughput': 553.77,\n      'load_time_ms': 0.239,\n      'load_throughput': 16727034.895,\n      'learn_time_ms': 1248.504,\n      'learn_throughput': 3203.836,\n      'update_time_ms': 1.596},\n     'info': {'learner': {'default_policy': {'learner_stats': {'cur_kl_coeff': 0.03750000149011612,\n         'cur_lr': 4.999999873689376e-05,\n         'total_loss': 832.47363,\n         'policy_loss': -0.008260538,\n         'vf_loss': 832.48175,\n         'vf_explained_var': 0.16725607,\n         'kl': 0.0046376656,\n         'entropy': 0.51470846,\n         'entropy_coeff': 0.0,\n         'model': {}},\n        'custom_metrics': {}}},\n      'num_steps_sampled': 40000,\n      'num_agent_steps_sampled': 40000,\n      'num_steps_trained': 40000,\n      'num_steps_trained_this_iter': 4000,\n      'num_agent_steps_trained': 40000},\n     'done': False,\n     'episodes_total': 441,\n     'training_iteration': 10,\n     'trial_id': 'default',\n     'experiment_id': '73459c6b55f748bdae8d42fe303b6f9a',\n     'date': '2022-03-17_16-11-03',\n     'timestamp': 1647558663,\n     'time_this_iter_s': 3.654078960418701,\n     'time_total_s': 36.21382212638855,\n     'pid': 99855,\n     'hostname': 'Juless-MacBook-Pro-16-inch-2019',\n     'node_ip': '127.0.0.1',\n     'config': {'num_workers': 1,\n      'num_envs_per_worker': 1,\n      'create_env_on_driver': False,\n      'rollout_fragment_length': 200,\n      'batch_mode': 'truncate_episodes',\n      'gamma': 0.99,\n      'lr': 5e-05,\n      'train_batch_size': 4000,\n      'model': {'_use_default_native_models': False,\n       '_disable_preprocessor_api': False,\n       '_disable_action_flattening': False,\n       'fcnet_hiddens': [100, 100],\n       'fcnet_activation': 'tanh',\n       'conv_filters': None,\n       'conv_activation': 'relu',\n       'post_fcnet_hiddens': [],\n       'post_fcnet_activation': 'relu',\n       'free_log_std': False,\n       'no_final_linear': False,\n       'vf_share_layers': False,\n       'use_lstm': False,\n       'max_seq_len': 20,\n       'lstm_cell_size': 256,\n       'lstm_use_prev_action': False,\n       'lstm_use_prev_reward': False,\n       '_time_major': False,\n       'use_attention': False,\n       'attention_num_transformer_units': 1,\n       'attention_dim': 64,\n       'attention_num_heads': 1,\n       'attention_head_dim': 32,\n       'attention_memory_inference': 50,\n       'attention_memory_training': 50,\n       'attention_position_wise_mlp_dim': 32,\n       'attention_init_gru_gate_bias': 2.0,\n       'attention_use_n_prev_actions': 0,\n       'attention_use_n_prev_rewards': 0,\n       'framestack': True,\n       'dim': 84,\n       'grayscale': False,\n       'zero_mean': True,\n       'custom_model': None,\n       'custom_model_config': {},\n       'custom_action_dist': None,\n       'custom_preprocessor': None,\n       'lstm_use_prev_action_reward': -1},\n      'optimizer': {},\n      'horizon': None,\n      'soft_horizon': False,\n      'no_done_at_end': False,\n      'env': 'CartPole-v1',\n      'observation_space': None,\n      'action_space': None,\n      'env_config': {},\n      'remote_worker_envs': False,\n      'remote_env_batch_wait_ms': 0,\n      'env_task_fn': None,\n      'render_env': False,\n      'record_env': False,\n      'clip_rewards': None,\n      'normalize_actions': True,\n      'clip_actions': False,\n      'preprocessor_pref': 'deepmind',\n      'log_level': 'WARN',\n      'callbacks': ray.rllib.agents.callbacks.DefaultCallbacks,\n      'ignore_worker_failures': False,\n      'log_sys_usage': True,\n      'fake_sampler': False,\n      'framework': 'tf',\n      'eager_tracing': False,\n      'eager_max_retraces': 20,\n      'explore': True,\n      'exploration_config': {'type': 'StochasticSampling'},\n      'evaluation_interval': None,\n      'evaluation_duration': 10,\n      'evaluation_duration_unit': 'episodes',\n      'evaluation_parallel_to_training': False,\n      'in_evaluation': False,\n      'evaluation_config': {'num_workers': 1,\n       'num_envs_per_worker': 1,\n       'create_env_on_driver': False,\n       'rollout_fragment_length': 200,\n       'batch_mode': 'truncate_episodes',\n       'gamma': 0.99,\n       'lr': 5e-05,\n       'train_batch_size': 4000,\n       'model': {'_use_default_native_models': False,\n        '_disable_preprocessor_api': False,\n        '_disable_action_flattening': False,\n        'fcnet_hiddens': [100, 100],\n        'fcnet_activation': 'tanh',\n        'conv_filters': None,\n        'conv_activation': 'relu',\n        'post_fcnet_hiddens': [],\n        'post_fcnet_activation': 'relu',\n        'free_log_std': False,\n        'no_final_linear': False,\n        'vf_share_layers': False,\n        'use_lstm': False,\n        'max_seq_len': 20,\n        'lstm_cell_size': 256,\n        'lstm_use_prev_action': False,\n        'lstm_use_prev_reward': False,\n        '_time_major': False,\n        'use_attention': False,\n        'attention_num_transformer_units': 1,\n        'attention_dim': 64,\n        'attention_num_heads': 1,\n        'attention_head_dim': 32,\n        'attention_memory_inference': 50,\n        'attention_memory_training': 50,\n        'attention_position_wise_mlp_dim': 32,\n        'attention_init_gru_gate_bias': 2.0,\n        'attention_use_n_prev_actions': 0,\n        'attention_use_n_prev_rewards': 0,\n        'framestack': True,\n        'dim': 84,\n        'grayscale': False,\n        'zero_mean': True,\n        'custom_model': None,\n        'custom_model_config': {},\n        'custom_action_dist': None,\n        'custom_preprocessor': None,\n        'lstm_use_prev_action_reward': -1},\n       'optimizer': {},\n       'horizon': None,\n       'soft_horizon': False,\n       'no_done_at_end': False,\n       'env': 'CartPole-v1',\n       'observation_space': None,\n       'action_space': None,\n       'env_config': {},\n       'remote_worker_envs': False,\n       'remote_env_batch_wait_ms': 0,\n       'env_task_fn': None,\n       'render_env': False,\n       'record_env': False,\n       'clip_rewards': None,\n       'normalize_actions': True,\n       'clip_actions': False,\n       'preprocessor_pref': 'deepmind',\n       'log_level': 'WARN',\n       'callbacks': ray.rllib.agents.callbacks.DefaultCallbacks,\n       'ignore_worker_failures': False,\n       'log_sys_usage': True,\n       'fake_sampler': False,\n       'framework': 'tf',\n       'eager_tracing': False,\n       'eager_max_retraces': 20,\n       'explore': True,\n       'exploration_config': {'type': 'StochasticSampling'},\n       'evaluation_interval': None,\n       'evaluation_duration': 10,\n       'evaluation_duration_unit': 'episodes',\n       'evaluation_parallel_to_training': False,\n       'in_evaluation': False,\n       'evaluation_config': {},\n       'evaluation_num_workers': 0,\n       'custom_eval_function': None,\n       'always_attach_evaluation_results': False,\n       'sample_async': False,\n       'sample_collector': ray.rllib.evaluation.collectors.simple_list_collector.SimpleListCollector,\n       'observation_filter': 'NoFilter',\n       'synchronize_filters': True,\n       'tf_session_args': {'intra_op_parallelism_threads': 2,\n        'inter_op_parallelism_threads': 2,\n        'gpu_options': {'allow_growth': True},\n        'log_device_placement': False,\n        'device_count': {'CPU': 1},\n        'allow_soft_placement': True},\n       'local_tf_session_args': {'intra_op_parallelism_threads': 8,\n        'inter_op_parallelism_threads': 8},\n       'compress_observations': False,\n       'metrics_episode_collection_timeout_s': 180,\n       'metrics_num_episodes_for_smoothing': 100,\n       'min_time_s_per_reporting': None,\n       'min_train_timesteps_per_reporting': None,\n       'min_sample_timesteps_per_reporting': 0,\n       'seed': None,\n       'extra_python_environs_for_driver': {},\n       'extra_python_environs_for_worker': {},\n       'num_gpus': 0,\n       '_fake_gpus': False,\n       'num_cpus_per_worker': 0,\n       'num_gpus_per_worker': 0,\n       'custom_resources_per_worker': {},\n       'num_cpus_for_driver': 1,\n       'placement_strategy': 'PACK',\n       'input': 'sampler',\n       'input_config': {},\n       'actions_in_input_normalized': False,\n       'input_evaluation': ['is', 'wis'],\n       'postprocess_inputs': False,\n       'shuffle_buffer_size': 0,\n       'output': None,\n       'output_compress_columns': ['obs', 'new_obs'],\n       'output_max_file_size': 67108864,\n       'multiagent': {'policies': {'default_policy': PolicySpec(policy_class=<class 'ray.rllib.policy.tf_policy_template.PPOTFPolicy'>, observation_space=Box([-4.8000002e+00 -3.4028235e+38 -4.1887903e-01 -3.4028235e+38], [4.8000002e+00 3.4028235e+38 4.1887903e-01 3.4028235e+38], (4,), float32), action_space=Discrete(2), config={})},\n        'policy_map_capacity': 100,\n        'policy_map_cache': None,\n        'policy_mapping_fn': None,\n        'policies_to_train': None,\n        'observation_fn': None,\n        'replay_mode': 'independent',\n        'count_steps_by': 'env_steps'},\n       'logger_config': None,\n       '_tf_policy_handles_more_than_one_loss': False,\n       '_disable_preprocessor_api': False,\n       '_disable_action_flattening': False,\n       '_disable_execution_plan_api': False,\n       'simple_optimizer': False,\n       'monitor': -1,\n       'evaluation_num_episodes': -1,\n       'metrics_smoothing_episodes': -1,\n       'timesteps_per_iteration': 0,\n       'min_iter_time_s': -1,\n       'collect_metrics_timeout': -1,\n       'use_critic': True,\n       'use_gae': True,\n       'lambda': 1.0,\n       'kl_coeff': 0.2,\n       'sgd_minibatch_size': 128,\n       'shuffle_sequences': True,\n       'num_sgd_iter': 30,\n       'lr_schedule': None,\n       'vf_loss_coeff': 1.0,\n       'entropy_coeff': 0.0,\n       'entropy_coeff_schedule': None,\n       'clip_param': 0.3,\n       'vf_clip_param': 10.0,\n       'grad_clip': None,\n       'kl_target': 0.01,\n       'vf_share_layers': -1},\n      'evaluation_num_workers': 0,\n      'custom_eval_function': None,\n      'always_attach_evaluation_results': False,\n      'sample_async': False,\n      'sample_collector': ray.rllib.evaluation.collectors.simple_list_collector.SimpleListCollector,\n      'observation_filter': 'NoFilter',\n      'synchronize_filters': True,\n      'tf_session_args': {'intra_op_parallelism_threads': 2,\n       'inter_op_parallelism_threads': 2,\n       'gpu_options': {'allow_growth': True},\n       'log_device_placement': False,\n       'device_count': {'CPU': 1},\n       'allow_soft_placement': True},\n      'local_tf_session_args': {'intra_op_parallelism_threads': 8,\n       'inter_op_parallelism_threads': 8},\n      'compress_observations': False,\n      'metrics_episode_collection_timeout_s': 180,\n      'metrics_num_episodes_for_smoothing': 100,\n      'min_time_s_per_reporting': None,\n      'min_train_timesteps_per_reporting': None,\n      'min_sample_timesteps_per_reporting': 0,\n      'seed': None,\n      'extra_python_environs_for_driver': {},\n      'extra_python_environs_for_worker': {},\n      'num_gpus': 0,\n      '_fake_gpus': False,\n      'num_cpus_per_worker': 0,\n      'num_gpus_per_worker': 0,\n      'custom_resources_per_worker': {},\n      'num_cpus_for_driver': 1,\n      'placement_strategy': 'PACK',\n      'input': 'sampler',\n      'input_config': {},\n      'actions_in_input_normalized': False,\n      'input_evaluation': ['is', 'wis'],\n      'postprocess_inputs': False,\n      'shuffle_buffer_size': 0,\n      'output': None,\n      'output_compress_columns': ['obs', 'new_obs'],\n      'output_max_file_size': 67108864,\n      'multiagent': {'policies': {'default_policy': PolicySpec(policy_class=<class 'ray.rllib.policy.tf_policy_template.PPOTFPolicy'>, observation_space=Box([-4.8000002e+00 -3.4028235e+38 -4.1887903e-01 -3.4028235e+38], [4.8000002e+00 3.4028235e+38 4.1887903e-01 3.4028235e+38], (4,), float32), action_space=Discrete(2), config={})},\n       'policy_map_capacity': 100,\n       'policy_map_cache': None,\n       'policy_mapping_fn': None,\n       'policies_to_train': None,\n       'observation_fn': None,\n       'replay_mode': 'independent',\n       'count_steps_by': 'env_steps'},\n      'logger_config': None,\n      '_tf_policy_handles_more_than_one_loss': False,\n      '_disable_preprocessor_api': False,\n      '_disable_action_flattening': False,\n      '_disable_execution_plan_api': False,\n      'simple_optimizer': False,\n      'monitor': -1,\n      'evaluation_num_episodes': -1,\n      'metrics_smoothing_episodes': -1,\n      'timesteps_per_iteration': 0,\n      'min_iter_time_s': -1,\n      'collect_metrics_timeout': -1,\n      'use_critic': True,\n      'use_gae': True,\n      'lambda': 1.0,\n      'kl_coeff': 0.2,\n      'sgd_minibatch_size': 128,\n      'shuffle_sequences': True,\n      'num_sgd_iter': 30,\n      'lr_schedule': None,\n      'vf_loss_coeff': 1.0,\n      'entropy_coeff': 0.0,\n      'entropy_coeff_schedule': None,\n      'clip_param': 0.3,\n      'vf_clip_param': 10.0,\n      'grad_clip': None,\n      'kl_target': 0.01,\n      'vf_share_layers': -1},\n     'time_since_restore': 36.21382212638855,\n     'timesteps_since_restore': 40000,\n     'iterations_since_restore': 10,\n     'perf': {'cpu_util_percent': 0.0, 'ram_util_percent': 51.42}}\n\n\n\nLet's plot the `episode_reward` values:\n\n\n```python\nepisode_rewards = results[-1]['hist_stats']['episode_reward']\ndf_episode_rewards = pd.DataFrame(data={'episode':range(len(episode_rewards)), 'reward':episode_rewards})\n\ndf_episode_rewards.plot(x=\"episode\", y=\"reward\")\n```\n\nFor a well-trained model, most runs do very well while occasional runs do poorly. Try plotting other results episodes by changing the array index in `results[-1]` to another number between `0` and `9`. (The length of `results` is `10`.)\n\n### Exercise 2\n\nThe current network and training configuration are too large and heavy-duty for a simple problem like `CartPole`. Modify the configuration to use a smaller network (the `config['model']['fcnet_hiddens']` setting) and to speed up the optimization of the surrogate objective. (Fewer SGD iterations and a larger batch size should help.)\n\n\n```python\n# Make edits here:\nconfig = DEFAULT_CONFIG.copy()\nconfig['num_workers'] = 3\nconfig['num_sgd_iter'] = 30\nconfig['sgd_minibatch_size'] = 128\nconfig['model']['fcnet_hiddens'] = [100, 100]\nconfig['num_cpus_per_worker'] = 0\n\nagent = PPOTrainer(config, 'CartPole-v1')\n```\n\n    2022-03-17 16:12:27,542\tWARNING ppo.py:223 -- `train_batch_size` (4000) cannot be achieved with your other settings (num_workers=3 num_envs_per_worker=1 rollout_fragment_length=200)! Auto-adjusting `rollout_fragment_length` to 1333.\n\n\nTrain the agent and try to get a reward of 500. If it's training too slowly you may need to modify the config above to use fewer hidden units, a larger `sgd_minibatch_size`, a smaller `num_sgd_iter`, or a larger `num_workers`.\n\nThis should take around `N` = 20 or 30 training iterations.\n\n\n```python\nN = 5\nresults = []\nepisode_data = []\nepisode_json = []\n\nfor n in range(N):\n    result = agent.train()\n    results.append(result)\n    \n    episode = {'n': n, \n               'episode_reward_mean': result['episode_reward_mean'], \n               'episode_reward_max': result['episode_reward_max'],  \n               'episode_len_mean': result['episode_len_mean']}   \n    \n    episode_data.append(episode)\n    episode_json.append(json.dumps(episode))\n    \n    print(f'Max reward: {episode[\"episode_reward_max\"]}')\n```\n\n    Max reward: 86.0\n    Max reward: 114.0\n    Max reward: 255.0\n    Max reward: 373.0\n    Max reward: 500.0\n\n\n# Using Checkpoints\n\nYou checkpoint the current state of a trainer to save what it has learned. Checkpoints are used for subsequent _rollouts_ and also to continue training later from a known-good state.  Calling `agent.save()` creates the checkpoint and returns the path to the checkpoint file, which can be used later to restore the current state to a new trainer. Here we'll load the trained policy into the same process, but often it would be loaded in a new process, for example on a production cluster for serving that is separate from the training cluster.\n\n\n```python\ncheckpoint_path = agent.save()\nprint(checkpoint_path)\n```\n\n    /Users/jules/ray_results/PPOTrainer_CartPole-v1_2022-03-17_16-12-27gdrnqw6v/checkpoint_000005/checkpoint-5\n\n\nNow load the checkpoint in a new trainer:\n\n\n```python\ntrained_config = config.copy()\ntest_agent = PPOTrainer(trained_config, \"CartPole-v1\")\ntest_agent.restore(checkpoint_path)\n```\n\n    2022-03-17 16:13:24,362\tWARNING ppo.py:223 -- `train_batch_size` (4000) cannot be achieved with your other settings (num_workers=3 num_envs_per_worker=1 rollout_fragment_length=200)! Auto-adjusting `rollout_fragment_length` to 1333.\n    2022-03-17 16:13:30,386\tINFO trainable.py:495 -- Restored on 127.0.0.1 from checkpoint: /Users/jules/ray_results/PPOTrainer_CartPole-v1_2022-03-17_16-12-27gdrnqw6v/checkpoint_000005/checkpoint-5\n    2022-03-17 16:13:30,387\tINFO trainable.py:503 -- Current state after restoring: {'_iteration': 5, '_timesteps_total': 39990, '_time_total': 20.854461193084717, '_episodes_total': 686}\n\n\nUse the previously-trained policy to act in an environment. The key line is the call to `test_agent.compute_action(state)` which uses the trained policy to choose an action. This is an example of _rollout_, which we'll study in a subsequent lesson.\n\nVerify that the cumulative reward received roughly matches up with the reward printed above. It will be at or near 500.\n\n\n```python\nenv = gym.make(\"CartPole-v1\")\nstate = env.reset()\ndone = False\ncumulative_reward = 0\n\nwhile not done:\n    action = test_agent.compute_single_action(state)  # key line; get the next action\n    state, reward, done, _ = env.step(action)\n    cumulative_reward += reward\n\nprint(cumulative_reward)\n```\n\n    375.0\n\n\n\n```python\nray.shutdown()\n```\n\nThe next lesson, [02: Introduction to RLlib](02-Introduction-to-RLlib.ipynb) steps back to introduce to RLlib, its goals and the capabilities it provides.\n", "meta": {"hexsha": "2c70cdba1411de96ff559de74bdaeded08e099cd", "size": 127947, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb", "max_stars_repo_name": "dmatrix/academy", "max_stars_repo_head_hexsha": "dbcac28e08caf83a9d7937f3bcb2747d6f6e67ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb", "max_issues_repo_name": "dmatrix/academy", "max_issues_repo_head_hexsha": "dbcac28e08caf83a9d7937f3bcb2747d6f6e67ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb", "max_forks_repo_name": "dmatrix/academy", "max_forks_repo_head_hexsha": "dbcac28e08caf83a9d7937f3bcb2747d6f6e67ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.2626820693, "max_line_length": 35192, "alphanum_fraction": 0.7318030122, "converted": true, "num_tokens": 13522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30074557894124154, "lm_q2_score": 0.06097517489257286, "lm_q1q2_score": 0.018338014274110283}}
{"text": "```python\nfrom IPython.display import Markdown, display\n\ndisplay(Markdown(\"models.md\"))\n```\n\n\n## Introduction\n\nAfter an initial outbreak in early 2020 in Wuhan, China, Severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2) has spread globally. SARS-CoV-2 is capable of sustained human-to-human trans-\nmission, and may cause severe disease, especially in older individuals. The COVID-19 pandemic has, in general, shown a remarkedly low incidence among children and young adults. Children have a lower susceptibility to infection and a lower propensity to show clinical symptoms. Furthermore, pre-symptomatic transmission is a major contributor to SARS-CoV-2 spread.\nUnfortunately, pharmaceutical interventions such as vaccination and antiviral drugs are not yet available. On March 13th, 2020, the Belgian governments imposed strict social restrictions after tracing methods had failed to prevent large-scale spread of SARS-CoV-2. One and a half months later, the curve was succesfully flattened and social restrictions were gradually relaxed during the months of May, June and the beginning of July. In spite of these relaxations, hospitalizations kept declining. It is expected that during the coming year(s), preventing COVID-19 outbreaks will depend mostly on the successful implementation of non-pharmaceutical interventions such as social distancing, testing, contact tracing and quarantine. Hence the need for well-informed models that can assist policymakers in choosing the best non-pharmaceutical interventions in case of another large-scale SARS-CoV-2 outbreak. Currently, two other models exist to make predictions for Belgium, the agent-based model of Willem et al. and the discrete-time, stochastic metapopulation model of Coletti et al.\n\nWe built a deterministic, continuous-time, age-stratified, extended SEIRD model and calibrated it to national Belgian hospitalization data. The model accounts for pre-symptomatic and asymptomatic transmission. Furthermore, the susceptibility to SARS-CoV-2, the severity of the disease and the susceptibility to a subclinical infection depend on the age of the individual. We used social contact rates from a 2012 study by Willem to model age-specific social mixing. Because detailed hospitalization data are not made publicly available by the Belgian Scientific Institute of Public Health (Sciensano), we derived age-stratified hospitalization parameters from data of 370 patients treated in two Ghent (Belgium) hospitals. To overcome this unconstructive data policy, we used the computed hospitalization parameters as temporary proxies to fit the model to the total number of patients in Belgian hospitals and ICU units. Using the model, we computed the basic reproduction number ($R_0$) during the March 2020 epidemic. Because the model systematically overestimates the hospitalizations during lockdown relaxation, we re-estimated the basic reproduction using data from May 2020 until July 2020.\n\n## The model\n\n### Model dynamics\n\nThe SEIR(D) model was first proposed in 1929 by two Scottish scientists. It is a compartmental model that subdivides the human population into four groups: 1) susceptible individuals, 2) exposed individuals in the latent phase 1, 3) infectious individuals capable of transmitting the disease and 4) individuals removed from the population either through immunization or death. Despite being a simple and idealized reality, the SEIR(D) dynamics are used extensively to predict the outbreak of infectious diseases and this was no different during the SARS-CoV-2 outbreak earlier this year.\n\nIn this work, we extend the SEIRD model to incorporate more expert knowledge on SARS-CoV-2. For that purpose, the infectious compartment is split into four parts. The first is a period of presymptomatic infectiousness because several studies have shown that pre-symptomatic transmission is a dominant transmission mechanism of SARS-CoV-2. After the period of pre-symptomatic transmission, three possible infectious outcomes are modeled: (1) Asymptomatic outcome, for individuals who show no symptoms at all, (2) Mild outcome, for individuals with mild symptoms who recover at home, and (3) Hospitalization, when mild symptoms worsen. Children and young adults have a high propensity to experience an asymptomatic or mild outcome, while older individual have a high propensity to be hospitalized.\n\nIn general, Belgian hospitals have two wards for COVID-19 patients: 1) Cohort, where patients are not monitored permanently and 2) Intensive care, for patients with the most severe symptoms. Intensive care includes permanent monitoring, the use of ventilators or the use of extracorporeal membrane oxygenation (ECMO). Patients generally spend limited time in the emergency room and/or in a buffer ward before going to Cohort. After spending limited time in Cohort, some patients are transferred to ICU. Patients can perish in both wards, but mortalities are generally lower in Cohort. After a stay in an ICU, patients return to Cohort for recovery in the hospital. During the recovery stay, mortality is limited. The above is a short summary of hospital dynamics based on interviewing Ghent University hospital staff and examining the hospital data.\n\n<p align=\"center\">\n\n\n<em> Extended SEIRD dynamics of the BIOMATH COVID-19 model. Nodes represent model states, edges denote transfers. An overview of the model parameters can be found on the bottom of this page.</em>\n</p>\n\n### Model framework and equations\n\n#### Age-stratification\nWe introduced heterogeneity in the deterministic implementation by means of age-stratification. Every population compartment is split into a number of age classes, the age-groups have different contact rates with other age-groups and the disease progresses differently for each age-group, making the model behaviour more realistic. Our age-stratified model consists of 9 age classes, i.e., [0-10[, [10-20[, [20-30[, [30-40[, [40-50[, [50-60[, [60-70[, [70-80[, [80- $\\infty$[. The age-stratified implementation provides a good balance between added complexity and computational resources.\n\n#### Deterministic framework\n\nOur extended SEIRD model is implemented using two frameworks: a deterministic and a stochastic framework. The deterministic equations are obtained by writing down the following equation,\n\n`rate of change = in - out`,\n\nfor every of the 11 population compartments. This results in the following system of coupled ordinary differential equations,\n\n$$\n\\begin{eqnarray}\n\\dot{S_i} &=& - \\beta s_i S_i \\sum_{j=1}^{N} N_{c,ij}  \\Big( \\frac{I_j+A_j}{T_j} \\Big) + \\zeta R_i, \\\\\n\\dot{E_i} &=& \\beta s_i  S_i \\sum_{j=1}^{N} N_{c,ij} \\Big( \\frac{I_j+A_j}{T_j} \\Big) - (1/\\sigma) \\cdot E_i,  \\\\\n\\dot{I_i} &=& (1/\\sigma) E_i - (1/\\omega) I_i, \\\\\n\\dot{A_i} &=& (\\text{a}_i/\\omega) I_i - (1/d_{\\text{a}}) A_i, \\\\\n\\dot{M_i} &=&  ((1-\\text{a}_i) / \\omega ) I_i - ( (1-h_i)/d_m + h_i/d_{\\text{hospital}} ) M_i, \\\\\n\\dot{ER_i} &=& (h_i/d_{\\text{hospital}}) M_i - (1/d_{\\text{ER}}) ER_i, \\\\\n\\dot{C_i} &=& c_i (1/d_{\\text{ER}}) ER_i  - (m_{C, i}/d_{c,D}) C_i - ((1 - m_{C, i})/d_{c,R}) C_i, \\\\\n\\dot{ICU_i} &=& (1-c_i) (1/d_{\\text{ER}}) ER_i - (m_{ICU,i}/d_{\\text{ICU},D}) ICU_i  \\\\\n&& - ((1-m_{ICU,i})/d_{\\text{ICU},R}) ICU_i,\\\\\n\\dot{C}_{\\text{ICU,rec,i}} &=& ((1-m_{ICU,i})/d_{\\text{ICU},R}) ICU_i - (1/d_{\\text{ICU,rec}}) C_{\\text{ICU,rec,i}}, \\\\\n\\dot{D_i} &=&  (m_{ICU,i}/d_{\\text{ICU},D}) ICU_i +  (m_{C,i}/d_{\\text{c},D}) C_i , \\\\\n\\dot{R_i} &=&  (1/d_a) A_i + ((1-h_i)/d_m) M_i + ((1-m_{C,i})/d_{c,R}) C_i \\\\\n&& + (1/d_{\\text{ICU,rec}}) C_{\\text{ICU,rec,i}} - \\zeta R_i,\n\\end{eqnarray}\n$$\n\nfor $i = 1,2,...,9$. Here, $T_i$ stands for total population, $S_i$ stands for susceptible, $E_i$ for exposed, $I_i$ for pre-symptomatic and infectious, $A_i$ for asymptomatic and infectious, $M_i$ for mildly symptomatic and infectious, $ER_i$ for emergency room and/or buffer ward, $C_i$ for cohort, $C_{\\text{ICU,rec,i}}$ for a recovery stay in Cohort coming from Intensive Care, $ICU_i$ for Intensive Care Unit, $D_i$ for dead and $R_i$ for recovered. Using the above notation, all model states are 9x1 vectors,\n\n$$\n\\begin{equation}\n     \\mathbf{S} = [S_1(t)\\ S_2(t)\\ ...\\ S_i(t)]^T,\n\\end{equation}\n$$\n\nwhere $S_i(t)$ denotes the number of susceptibles in age-class i at time t after the introduction of the virus in the population.\n\nThese equations are implemented in the function `COVID19_SEIRD` located in `src/covid19model/models.py`. The integration is performed in `_sim_single` located in `src/covid19model/base.py` by using Scipy's `solve_ivp`. The integrator timestep depends on the rate of change of the system and the solver method is thus referred to as a 'continuous-time' solver. The implementation uses non-integer individuals.\n\n#### Stochastic framework\n\nBy defining the probabilities of transitioning (propensities) from one state to another, a system of coupled stochastic difference equations (SDEs) can be obtained. The probability to transition from one state to another is assumed to be exponentially distributed. As an example, consider the average time a patient spends in an ICU when recovering, which is $d_{\\text{ICU,R}} = 9.9$ days. The chances of survival in ICU are $(1-m_{\\text{ICU,i}})$, where $m_{\\text{ICU,i}}$ is the mortality in ICU for an individual in age group $i$. The probability of transitioning from state ICU to state $C_{\\text{ICU,rec}}$ on any given day and for an individual in age group $i$ is,\n\n$$\n\\begin{equation}\nP(ICU_i \\rightarrow C_{\\text{ICU,rec,i}}) = 1 - \\text{exp} \\Bigg[ - \\frac{1-m_{\\text{ICU},i}}{d_{\\text{ICU,R}}}\\Bigg].\n\\end{equation}\n$$\n\nIf a transitioning between states is defined as \"succes\", we can regard the number of individuals transitioning from ICU to a Cohort recovery ward as a binomial experiment. On a given day, the number of individuals transitioning is,\n\n$$\n\\begin{equation}\n(\\text{ICU}_i \\rightarrow C_{\\text{ICU,rec,i}})(k) \\sim \\text{Binomial}\\Bigg(\\text{ICU}_i(k),\\ 1 - \\text{exp}\\Bigg[- \\frac{1-m_{\\text{ICU,i}}}{d_{\\text{ICU,R}}}\\Bigg]\\Bigg).\n\\end{equation}\n$$\n\nFor a discrete stepsize $l$, there are 15 possible transitions,\n\n$$\n\\begin{eqnarray}\n(S_i \\rightarrow E_i) (k) &\\sim& \\text{Binomial}\\Bigg(S_i(k), 1 - \\text{exp}\\Bigg[- l \\beta s_i \\sum_{j=1}^{N} N_{c,ij}  \\Big( \\frac{I_j+A_j}{T_j} \\Big) \\Bigg]\\Bigg)\\\\\n(E_i \\rightarrow I_i) (k) &\\sim& \\text{Binomial}\\Bigg(E_i(k), 1 - \\text{exp}\\Bigg[- l\\ \\frac{1}{\\sigma}\\Bigg]\\Bigg)\\\\\n(I_i \\rightarrow A_i) (k) &\\sim& \\text{Binomial}\\Bigg(I_i(k), 1 - \\text{exp}\\Bigg[- l\\ \\frac{a_i}{\\omega}\\Bigg]\\Bigg)\\\\\n(I_i \\rightarrow M_i) (k) &\\sim& \\text{Binomial}\\Bigg(I_i(k), 1 - \\text{exp}\\Bigg[- l\\ \\frac{1-a_i}{\\omega}\\Bigg]\\Bigg)\\\\\n(A_i \\rightarrow R_i) (k) &\\sim& \\text{Binomial}\\Bigg(A_i(k), 1 - \\text{exp}\\Bigg[- l\\ \\frac{1}{d_a}\\Bigg]\\Bigg)\\\\\n(M_i \\rightarrow R_i) (k) &\\sim& \\text{Binomial}\\Bigg(M_i(k), 1 - \\text{exp}\\Bigg[- l\\ \\frac{1-h_i}{d_m}\\Bigg]\\Bigg)\\\\\n(M_i \\rightarrow ER_i) (k) &\\sim& \\text{Binomial}\\Bigg(M_i(k), 1 - \\text{exp}\\Bigg[- l\\ \\frac{h_i}{d_{\\text{hospital}}}\\Bigg]\\Bigg)\\\\\n(ER_i \\rightarrow C_i) (k) &\\sim& \\text{Binomial}\\Bigg(ER_i(k), 1 - \\text{exp}\\Bigg[- l\\ \\frac{c_i}{d_{\\text{ER}}}\\Bigg]\\Bigg)\\\\\n(ER_i \\rightarrow ICU_i) (k) &\\sim& \\text{Binomial}\\Bigg(ER_i(k), 1 - \\text{exp}\\Bigg[- l\\ \\frac{1-c_i}{d_{\\text{ER}}}\\Bigg]\\Bigg)\\\\\n(C_i \\rightarrow R_i) (k) &\\sim& \\text{Binomial}\\Bigg(C_i(k), 1 - \\text{exp}\\Bigg[- l\\ \\frac{1-m_{C,i}}{d_{C,R}}\\Bigg]\\Bigg)\\\\\n(ICU_i \\rightarrow C_{\\text{ICU,rec,i}}) (k) &\\sim& \\text{Binomial}\\Bigg(ICU_i(k), 1 - \\text{exp}\\Bigg[- l\\ \\frac{1-m_{\\text{ICU,i}}}{d_{ICU,R}}\\Bigg]\\Bigg)\\\\\n(C_{\\text{ICU,rec,i}} \\rightarrow R_i) (k) &\\sim& \\text{Binomial}\\Bigg(C_{\\text{ICU,rec,i}}(k), 1 - \\text{exp}\\Bigg[- l\\ \\frac{1}{d_{\\text{ICU,rec}}}\\Bigg]\\Bigg)\\\\\n(C_i \\rightarrow D_i) (k) &\\sim& \\text{Binomial}\\Bigg(C_i(k), 1 - \\text{exp}\\Bigg[- l\\ \\frac{m_{C,i}}{d_{C,D}}\\Bigg]\\Bigg)\\\\\n(ICU_i \\rightarrow D_i) (k) &\\sim& \\text{Binomial}\\Bigg(ICU_i(k), 1 - \\text{exp}\\Bigg[- l\\ \\frac{m_{\\text{ICU,i}}}{d_{\\text{ICU,D}}}\\Bigg]\\Bigg)\\\\\n(R_i \\rightarrow S_i) (k) &\\sim& \\text{Binomial}\\Bigg(R_i(k), 1 - \\text{exp}\\Bigg[- l\\ \\zeta \\Bigg]\\Bigg)\\\\\n\\end{eqnarray}\n$$\n\nAnd the system of equations becomes,\n\n$$\n\\begin{eqnarray}\nS_i(k+1) &=& S_i(k) + (R_i \\rightarrow S_i) (k) - (S_i \\rightarrow E_i) (k) \\\\\nE_i(k+1) &=& E_i(k) + (S_i \\rightarrow E_i) (k) - (E_i \\rightarrow I_i) (k) \\\\\nI_i(k+1) &=& I_i(k) + (E_i \\rightarrow I_i) (k) - (I_i \\rightarrow A_i) - (I_i \\rightarrow M_i) (k) \\\\\nA_i(k+1) &=& A_i(k) + (I_i \\rightarrow A_i) (k) - (A_i \\rightarrow R_i) (k) \\\\\nM_i(k+1) &=& M_i(k) + (I_i \\rightarrow M_i) (k) - (M_i \\rightarrow R_i) (k) - (M_i \\rightarrow ER_i) (k) \\\\\nER_i(k+1) &=& ER_i(k) + (M_i \\rightarrow ER_i) (k) - (ER_i \\rightarrow C_i) (k) - (ER_i \\rightarrow ICU_i) (k) \\\\\nC_i(k+1) &=& C_i(k) + (ER_i \\rightarrow C_i) (k) - (C_i \\rightarrow R_i) (k) - (C_i \\rightarrow D_i) (k) \\\\\nC_{\\text{ICU,rec,i}}(k+1) &=& C_{\\text{ICU,rec,i}}(k)  + (ICU_i \\rightarrow C_{\\text{ICU,rec,i}}) (k) - (C_{\\text{ICU,rec,i}} \\rightarrow R_i) (k) \\\\\nR_i(k+1) &=& R_i(k) + (A_i \\rightarrow R_i) (k)  + (M_i \\rightarrow R_i) (k) + (C_i \\rightarrow R_i) (k)\\\\\n&& + (C_{\\text{ICU,rec,i}} \\rightarrow R_i) (k)  - (R_i \\rightarrow S_i) (k) \\\\\nD_i(k+1) &=& D_i(k) + (ICU_i \\rightarrow D_i) (k) + (C_i \\rightarrow D_i) (k) \\\\\n\\end{eqnarray}\n$$\n\nThese equations are implemented in the function `COVID19_SEIRD_sto` located in `src/covid19model/models.py`. The computation itself is performed in the function `solve_discrete` located in `src/covid19model/base.py`. Please note that the deterministic model uses **differentials** in the model defenition and must be integrated, while the stochastic model uses **differences** and must be iterated. The discrete timestep is fixed at one day. The stochastic implementation only uses integer individuals, which is considered an advantage over the deterministic implementation.\n\n### Spatial extension\n\nRather than considering the entire nation as a homogeneous collection of compartments, it is more realistic to consider spatially distinct regions that are mutually connected. The relevance of this approach becomes clear by looking at the spatial spread in the data (embedded video below): the occurence of confirmed cases is not entirely homogeneous.\n\n<figure class=\"video_container\">\n  \n</figure>\n\nThe main motivation for investigating spatial relations is to quantify the effect of certain types of mobility on the severity and speed of the spread of COVID19, and the effect of spatial isolation of key regions. We consider e.g. the 43 Belgian arrondissements or the 10 Belgian provinces (plus Brussels-Capital). These regions are considered internally homogeneous and are connected through known or estimated mobility matrices.\n\nBelow, the spatially explicit model is worked out in a deterministic framework and a stochastic framework. These are largely based on the approach taken in [this 2020 paper](https://www.medrxiv.org/content/10.1101/2020.03.21.20040022v1) by Arenas et al.\n\n#### Deterministic spatial framework\n\nThe deterministic approach is largely the same as in the non-spatial framework, only this time every 'patch' (either arrondissement or province) exhibits the dynamics explained before. We make the following assumptions from the mobility:\n1. The effective population of a patch is not the same as the registered population, because (during the daytime) some people will leave their home patch and go to another, e.g. for their profession\n2. People can get become exposed in their home patch or in the patch they visit\n3. The overall mobility is scaled with a single parameter $p$, ranging between 0 and 1, where 0 means no mobility is possible, and 1 indicates regular mobility. This mobility parameter is typically below 1 in a pandemic situation, due to travelling restrictions.\n4. Social contact rates are (slightly) different in every patch. Following Arenas et al., this translates to a rescaling of the overall contact rate with respect to density.\n\nMathematically, the **effective population** in a particular patch $g$ is\n\n$$\n\\begin{equation}\nT^g_{i,\\text{eff}} = \\sum_{h=1}^G [(1-p_i)\\delta^{gh} + p_i P_i^{hg}]T_i^h,\n\\end{equation}\n$$\n\nwhere $G$ is the total number of patches (e.g. 43 arrondissements), $p_i$ the mobility parameter (stratified per age $i$), $\\delta^{gh}$ the Kronecker delta, $P_i^{hg}$ the recurrent mobility *from* patch $h$ *to* patch $g$ (stratified per age $i$), and $T_i^h$ the registered population in age class $i$ and patch $h$. The same formula works goes for $I^g_{i,\\text{eff}}$ and $E^g_{i,\\text{eff}}$. Note that $T^g_{i,eff} = T^g_i$ if $p_i = 0$. Note: $P_i^{hg}$ is implemented in the code as `place`.\n\nBecause people can get exposed in their own *or* another patch, we need an expression for the **number of susceptibles** from patch $g$ that reside in patch $h$, in age class $i$:\n\n$$\n\\begin{equation}\n    S_i^{gh} = p_i P_i^{gh} S_i^g + (1-p_i) \\delta^{gh} S_i^g\n\\end{equation}\n$$\n\nWe now have a **social contact matrix** for every patch, $N^g_{c,ij}$. We follow the suggestion in Arenas et al. that the contact rate is proportional to a population density function $f$, or\n\n$$\n\\begin{equation}\nN^g_{c,ij} \\propto f\\left( \\frac{T^g_\\text{eff}}{a^g} \\right).\n\\end{equation}\n$$\n\nHere $T^g_\\text{eff}$ is again the effective population of patch $g$, and $a^g$ its area. The function $f$ is defined as\n\n$$\n\\begin{equation}\n    f(x) = 1 + (1-e^{-\\xi x}),\n\\end{equation}\n$$\n\nand increases monotonically from 1 to 2 (see figure below)\n<p align=\"center\">\n\n    \nThis allows us to rewrite $N^g_{c,ij}$:\n\n$$\n\\begin{equation}\n    N^g_{c,ij} = z_i f\\left( \\frac{T^g_\\text{eff}}{a^g} \\right) N_{c,ij},\n\\end{equation}\n$$\n\nwhere Arenas et al. call $z_i$ the 'normalisation factor':\n\n$$\n\\begin{equation}\n    z_i = \\frac{ T_i }{ \\sum\\limits_{h=1}^G f\\left(\\dfrac{T^h_\\text{eff}}{a^h}\\right) T^h_{i,\\text{eff}}},\n    \\label{eq:z_i-normalisation}\n\\end{equation}\n$$\n\nwith $T_i$ the total population in age class $i$.\n\n\nHaving that background, we define a quantity\n\n$$\n\\begin{equation}\n    B^g_i \\equiv \\sum_{j=1}^N \\beta s_i z_i f\\left(\\frac{T_\\text{eff}^g}{a^g}\\right) N_{c,ij} \\frac{I_{j,\\text{eff}}^g + A_{j,\\text{eff}}^g}{T_{j,\\text{eff}}^g}\n\\end{equation}\n$$\n\nThe **coupled ordinary differential equations** can be rewritten to the spatial situation\n$$\n\\begin{eqnarray}\n\\dot{S}_i^g &=& - \\sum_{h=1}^G S_i^{gh} B^h_i + \\zeta R_i^g, \\\\\n\\dot{E}_i^g &=& \\sum_{h=1}^G S_i^{gh} B^h_i - (1/\\sigma) \\cdot E_i^g,  \\\\\n\\dot{I}_i^g &=& (1/\\sigma) E_i - (1/\\omega) I_i^g, \\\\\n\\dot{A}_i^g &=& (\\text{a}_i/\\omega) I_i^g - (1/d_{\\text{a}}) A_i^g, \\\\\n\\dot{M}_i^g &=&  ((1-\\text{a}_i) / \\omega ) I_i^g - ( (1-h_i)/d_m + h_i/d_{\\text{hospital}} ) M_i^g, \\\\\n\\dot{ER}_i^g &=& (h_i/d_{\\text{hospital}}) M_i^g - (1/d_{\\text{ER}}) ER_i^g, \\\\\n\\dot{C}_i^g &=& c_i (1/d_{\\text{ER}}) ER_i^g  - (m_{C, i}/d_{c,D}) C_i^g - ((1 - m_{C, i})/d_{c,R}) C_i^g, \\\\\n\\dot{ICU}+i^g &=& (1-c_i) (1/d_{\\text{ER}}) ER_i^g - (m_{ICU,i}/d_{\\text{ICU},D}) ICU_i^g  \\\\\n&& - ((1-m_{ICU,i})/d_{\\text{ICU},R}) ICU_i^g,\\\\\n\\dot{C}_{\\text{ICU,rec,i}}^g &=& ((1-m_{ICU,i})/d_{\\text{ICU},R}) ICU_i^g - (1/d_{\\text{ICU,rec}}) C_{\\text{ICU,rec,i}}^g, \\\\\n\\dot{D}_i^g &=&  (m_{ICU,i}/d_{\\text{ICU},D}) ICU_i^g +  (m_{C,i}/d_{\\text{c},D}) C_i^g , \\\\\n\\dot{R}_i^g &=&  (1/d_a) A_i + ((1-h_i)/d_m) M_i^g + ((1-m_{C,i})/d_{c,R}) C_i^g \\\\\n&& + (1/d_{\\text{ICU,rec}}) C_{\\text{ICU,rec,i}}^g - \\zeta R_i^g,\n\\end{eqnarray}\n$$\n\nAll state matrices have dimensions $G \\times N$, so integrating these ODEs takes (more than) $G$ times the computation time compared to the non-spatial case. Note that, if relevant and available, all parameters may be further stratified per patch $g$.\n\nThese equations are implemented in the function `COVID19_SEIRD_spatial` located in `src/covid19model/models.py`. When creating the simulation, these equations are integrated numerically.\n\n#### Stochastic spatial framework\n\nExtending the deterministic spatial framework to a (discrete) stochastic one is straightforward. The probability of being infected in patch $g$ in the next timestep (stepsize $\\ell$) for a susceptible individual is\n\n$$\n\\begin{equation}\n    P^g_i = 1 - \\exp\\left( - \\ell \\sum\\limits_{j=1}^N \\beta s_i z_i f\\left( \\frac{T_\\text{eff}^g}{a^g} \\right) N_{c,ij} \\frac{ I^{g}_{j, \\text{eff}} + A^{g}_{j, \\text{eff}}}{T_{j,\\text{eff}}^g} \\right)\n\\end{equation}\n$$\n\nThe same delocalised infection happens here, again depending on the overall mobility $p_i$ and the recurrent mobility matrix $P_i^{gh}$:\n\\begin{equation}\n    \\Pi_i^g = P_i^g + p_i\\sum\\limits_{\\substack{h=1 \\\\ h\\neq g}}^G P_i^{gh}P_i^h\n\\end{equation}\nThe **overall probability of exposure** for an agent in age class $i$ and patch $g$, $\\Pi_i^g$, is a sum of\n1. The probability of being infected at home, *plus*\n2. The probability of being infected outside the home patch, weighed by the mobility to that patch\n\nNote that a higher mobility parameter does *not* necessarily mean that the exposure probability $\\Pi_i^g$ is larger, because the probability of becoming infected in the home patch, $P_i^g$, is also dependant on the mobility parameter $p_i$.\n\nThis translates to the same **set of stochastic equations** as in the non-spatial case, but now with spatial stratification and a slightly adjusted probability in the binomial experiment:\n$$\n\\begin{eqnarray}\n(S_i^g \\rightarrow E_i^g) (k) &\\sim& \\text{Binomial}\\Bigg(S_i^g(k), \\Pi_i^g(k) \\Bigg)\\\\\n(E_i^g \\rightarrow I_i^g) (k) &\\sim& \\text{Binomial}\\Bigg(E_i^g(k), \\Pi_i^g(k) \\Bigg)\\\\\n\\end{eqnarray}\n$$\n\nThese in turn determine the discrete development of the stochastic model:\n\n$$\n\\begin{eqnarray}\nS_i^g(k+1) &=& S_i^g(k) + (R_i^g \\rightarrow S_i^g) (k) - (S_i^g \\rightarrow E_i^g) (k) \\\\\nE_i^g(k+1) &=& E_i^g(k) + (S_i^g \\rightarrow E_i^g) (k) - (E_i^g \\rightarrow I_i^g) (k) \\\\\n\\end{eqnarray}\n$$\n\n... etcetera (see non-spatial case).\n\nAn **example** of the stochastic spatial framework is shown in the video below.\n\n<figure class=\"video_container\">\n  \n</figure>\n<em>Simulation with the stochastic model and an initial condition where at time = 0, 5 exposed individuals in age class 30-40 years are 'released' in Arlon, all the way on the south-easter side of the country. At the onset, it is clear how the 'wave' of new exposures travels through the country, hitting the densely populated patches first. At day 40, measures are taken that bring down the effective reproduction constant below zero.</em>\n\nThese equations are implemented in the function `COVID19_SEIRD_sto_spatial` located in `src/covid19model/models.py`. The computation itself is performed in the function `solve_discrete` located in `src/covid19model/base.py`. Please note that the deterministic model uses **differentials** in the model definition and must be integrated, while the stochastic model uses **differences** and must be iterated. The discrete timestep is fixed at one day. The stochastic implementation only uses integer individuals, which is considered an advantage over the deterministic implementation.\n\n#### Spatial: remaining issues and tasks\n\nThe theory at the basis of both the deterministic and the stochastic spatial model is still subject to change. Some of these 'to-dos' are listed below.\n\n1. In the original implementation of the spatial method, the type of contact in the exposure probability was related to whether or not the contact takes place in the home patch or not (see equation below, in the original notation). The reason is that e.g. home contact ($N_{\\text{home},ij}$ is not relevant when visiting other places; if the individual does not work in his home patch, the work vs home, school, leisure, other human-to-human contacts must be seperate. Whilst this is certainly true, it is currently unclear whether this additional complication is worth pursuing.\n$$\n\\begin{eqnarray}\n    P(S_{i,g} \\rightarrow E_{i,g}) (k) &=& 1 - \\text{exp} \\Bigg[ \\underbrace{\\text{P}_{g,g} \\Bigg\\{ - l \\beta s_i \\sum_{j=1}^{N} N_{\\text{c, tot, ij}} \\Bigg( \\frac{I_{j,g} + A_{j,g}}{T_{j,g}} \\Bigg) \\Bigg\\}}_{\\text{individual working in residence patch}}  \\\\\n    &+& \\sum_{l=1\\\\ l \\neq g}^{G} \\text{P}_{g,l} \\Bigg\\{ \\underbrace{- l \\beta s_i \\sum_{j=1}^{N} N_{\\text{c, work, ij}} \\Bigg( \\frac{I_{j,l} + A_{j,l}}{T_{j,l}} \\Bigg)}_{\\text{work interactions in work patch (subscript l)}} \\\\\n     &-& \\underbrace{l \\beta s_i \\sum_{j=1}^{N} (N_{\\text{c, home, ij}} + N_{\\text{c, school, ij}} + N_{\\text{c, leisure, ij}} + N_{\\text{c, others, ij}}) \\Bigg( \\frac{I_{j,g} + A_{j,g}}{T_{j,g}} \\Bigg)}_{\\text{all other interactions in home patch (subscript g)}} \\Bigg\\} \\Bigg]\n\\end{eqnarray}\n$$\n2. Many parameters, most notably the mobility parameter $p_i$, can (and often should) be stratified further.\n3. The calibration methods are still under construction and are more difficult, mainly because of the higher number of possible choices:\n    * Should every patch have its own $\\beta^g$ value?\n    * How do we go about choosing an initial condition for the calibration?\n4. A good spatial model is largely dependant on good mobility data. The currently available data is a mobility matrix from 2011, which is quite certainly not representative for the 2020 pandemic situation. Ideally we have *current* mobility data, stratified per *age class* and per *activity* (work/school/leisure/...) \n5. This model currently does *not* account for importation of exposed individuals, which in a highly populated region like Western Europe is undoubtedly an important factor.\n6. The contact rate's dependence on the density may be omitted -- it has little effect -- but is currently implemented to parallel Arenas et al.'s approach.\n7. Arguably, stratification at the level of arrondissements is too highly detailed in a 'big city' like Belgium. Data analysis of the current situation may point out that it is justified to aggregate some arrondissements with a similar time series morphology together.\n\n### Transmission rates and social contact data\n\nIn our model, the transmission rate of the disease depends on the product of four contributions. The first contribution, $(I+A)/T$, is the fraction of contagious individuals in the population. The second contribution, $\\mathbf{N}_c$, is the average number of human-to-human interactions per day. The third contribution, $s_i$, is the relative susceptiblity to SARS-CoV-2 infection in age group $i$, and the fourth contribution, $\\beta$, is the probability of contracting COVID-19 when encountering a contagious individual under the assumption of 100 \\% susceptibility to SARS-CoV-2 infection. We assume that the per contact transmission probability $\\beta$ is independent of age and we will infer its distribution by calibrating the model to national Belgian hospitalization data. The number of human-human interactions, $\\mathbf{N}_c$, are both place and age-dependent. These matrices assume the form of a 9x9 *interaction matrix* where an entry X, Y denotes the number of social contacts age group X has with age group Y per day. These matrices are available for homes, schools, workplaces, in public transport, and leisure activities, from a survey study by Lander Willem (2012). The total number of social interactions is given by the sum of the contributions in different places,\n\n$$\n\\begin{equation}\\label{eq:interaction_matrices}\n\\mathbf{N_{\\text{c}}} = \\mathbf{N_{\\text{c, home}}} + \\mathbf{N_{\\text{c, schools}}} + \\mathbf{N_{\\text{c, work}}} + \\mathbf{N_{\\text{c, transport}}} + \\mathbf{N_{\\text{c, leisure}}} + \\mathbf{N_{\\text{c, others}}}.\n\\end{equation}\n$$\n\nCoefficients can be added to the contributing contact matrices to model a goverment policy. For instance, to model the Belgian lockdown, the mobility reductions deduced from the Google community mobility reports were used as coefficients for the different interaction matrices. We assumed workplace interactions were down to only 40 % of their prepandemic values before the lockdown.\n\n### Modeling social intertia\n\nThe model takes into account the effect of *social inertia* when measures are taken. In reality, social restrictions or relaxations represent a change in behaviour which is gradual and cannot be modeled using a step-wise change of the social interaction matrix $\\mathbf{N_c}$. This can be seen when closely inspecting the *Google community mobility report* above. Multiple functions can be used to model the effects of social compliance, e.g. a delayed or non-delayed ramp, or a logistic function. In our model, we use a delayed ramp to model compliance,\n\n$$\n\\begin{equation}\n\\mathbf{N_{c}}^{k} = \\mathbf{N_{\\text{c, old}}} + f^{k} (\\mathbf{N_{\\text{c, new}}} - \\mathbf{N_{\\text{c, old}}})\n\\end{equation}\n$$\n\nwhere,\n\n$$\n\\begin{equation}\n    f^k=\n\\begin{cases}\n\t0.0,& \\text{if } k\\leq \\tau\\\\\n    \\frac{k}{l} - \\frac{\\tau}{l},& \\text{if } \\tau < k\\leq \\tau + l\\\\\n    1.0,              & \\text{otherwise}\n\\end{cases}\n\\end{equation}\n$$\n\nwhere $\\tau$ is the number of days before measures start having an effect and $l$ is the number of additional days after the time delay until full compliance is reached. Both parameters were calibrated to the daily number of hospitalizations in Belgium (notebooks `notebooks/0.1-twallema-calibration-deterministic.ipynb` and `notebooks/0.1-twallema-calibration-stochastic.ipynb`). $k$ denotes the number of days since a change in social policy.\n\n### Basic reproduction number\n\nThe basic reproduction number $R_0$, defined as the expected number of secondary cases directly generated by one case in a population where all individuals are susceptible to infection, is computed using the next generation matrix (NGM) approach introducted by Diekmann. For our model, the basic reproduction number of age group $i$ is,\n\n$$\n\\begin{equation}\\label{eq:reproduction_number}\nR_{0,i} = (a_i d_a + \\omega) \\beta s_i \\sum_{j=1}^{N} N_{c,ij}\n\\end{equation}\n$$\n\nand the population basic reproduction number is calculated as the weighted average over all age groups using the demographics of Belgium. The detailed algebra underlying the computation equation of the basic reproduction number is presented in the supplementary materials of our manuscript (see section *Previous work*).\n\n### Model parameters\n\nAn in-depth motivation of the model parameters is provided in our manuscript (see section *Previous work*). Hospital parameters were derived from a dataset obtained from two hospitals in Ghent (Belgium).\n\n<p align=\"center\">\n\n<em> Overview of BIOMATH COVID-19 model parameters. </em>\n</p>\n\n\n", "meta": {"hexsha": "cf7707347653fb71933072937a2a8f342dcd1caa", "size": 37381, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/Markdown reading tool for Notebook.ipynb", "max_stars_repo_name": "UGentBiomath/COVID19-Model", "max_stars_repo_head_hexsha": "ef04f6ec78a3c3dc9217cea68ae5276d159ba0c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2020-04-22T16:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-06T08:44:02.000Z", "max_issues_repo_path": "docs/Markdown reading tool for Notebook.ipynb", "max_issues_repo_name": "UGentBiomath/COVID19-Model", "max_issues_repo_head_hexsha": "ef04f6ec78a3c3dc9217cea68ae5276d159ba0c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 90, "max_issues_repo_issues_event_min_datetime": "2020-04-17T19:25:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T12:34:39.000Z", "max_forks_repo_path": "docs/Markdown reading tool for Notebook.ipynb", "max_forks_repo_name": "UGentBiomath/COVID19-Model", "max_forks_repo_head_hexsha": "ef04f6ec78a3c3dc9217cea68ae5276d159ba0c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2020-04-06T06:09:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-21T22:40:40.000Z", "avg_line_length": 86.3302540416, "max_line_length": 1301, "alphanum_fraction": 0.6304004708, "converted": true, "num_tokens": 9096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.04672495879202332, "lm_q1q2_score": 0.01833192222215119}}
{"text": "# Simple linear regression using Kaldi nnet3 set of libraries\n\nThis notebook is a tutorial which tries to explain the mechanism of designing ANNs using the nnet3 library included in the Kaldi project.\n\nKaldi is a very elaborate speech recognition toolkit with a long history and plenty of tools and models apart from ANNs. \n\n*nnet3* is a part of the project that deals with the latest implementation of various DNN architectures. The main difference being the easy configurability of the C++-based library, without having to do any actual C++ programming.\n\nAs with most Kaldi setups, the usage is based around many small binaries that perform simple, atomic operations. These can be run using shell scripts or from other programming languages with the help of \"exec\" or \"popen\" syscalls.\n\nAs a convinience, a python library is included with the project that has a few methods to make life easier. As of writing this, everything there is still very much work in progress, so there is no guarantees this notebook will work out-of-the-box in a few months time...\n\nFormal documentation to the toolkit and it's ANN portion can be found here: http://kaldi-asr.org/doc/dnn3.html\n\n## The setup\n\nIf you don't have it, you need to download Kaldi. Detailed explanation can be found on http://kaldi-ast.org, but the TL;DR is as follow:\n\n  1. cd into some conveninet location and do ```git clone https://github.com/kaldi-asr/kaldi```\n  2. go to ```kaldi/tools``` and simply do ```make``` in there - if the script mentions you need to install anything, simply install the missing tools/libraries\n  3. go to ```kaldi/src``` and do ```./configure``` in there - it would be good to have CUDA installed and recognized in this step, as you can benefit from GPU acceleration a lot\n  4. after configuring simply do ```make``` and wait - if you have a very new version of gcc (>6) it may be a good idea to install something like 4.9 and simply modify the kaldi.mk file \n  \nOne thing about Kaldi is that it is completely contained in a single directory, which makes it easy to move and locate. That is why most scripts utilized with Kaldi rely on the following path. You need to set this to wherever you stored Kaldi on your computer: \n\n\n```python\nKALDI_ROOT='~/apps/kaldi'\n```\n\nFollowing that, we create a small work directory as a subdirectory of this notebook and add to it some files from the Kaldi project:\n  * a symlink to the steps dir from the WSJ example - this contains lots of useful scripts and the nnet3 python library\n  * a copy of the path.sh file - used to load the path environment with the locations of all the binaries in the Kaldi project\n  \nThe path.sh file is also modified to include the actual path to Kaldi.\n\n\n```python\nimport os\nfrom shutil import copyfile\nimport fileinput\nimport stat\n\nKALDI_ROOT=os.path.expanduser(KALDI_ROOT)\nKALDI_ROOT=os.path.abspath(KALDI_ROOT)\n\nif not os.getcwd().endswith('/work'):\n    if not os.path.exists('work'):\n        os.mkdir('work')\n    os.chdir('work')\n\nif not os.path.exists('steps'):\n    os.symlink(KALDI_ROOT+'/egs/wsj/s5/steps','steps')\n\nif not os.path.exists('path.sh'):\n    copyfile(KALDI_ROOT+'/egs/wsj/s5/path.sh','path.sh')\n    for line in fileinput.input('path.sh',inplace=True):\n        if line.startswith('export KALDI_ROOT='):\n            print 'export KALDI_ROOT='+KALDI_ROOT\n        else:\n            print line[:-1]\n    os.chmod('path.sh',0755)\n```\n\nThe python library is located in the steps/nnet3 subfolder:\n\n\n```python\nimport sys\n\nsys.path.append('steps/nnet3')\n\nimport nnet3_train_lib as ntl\n```\n\nOnce we load the library, we have access to all sorts of methods, but RunKaldiCommand should be sufficient for now.\n\nThe next problem is that while path.sh script is useful if you run programs locally from your terminal, it doesn't work in the Notebook environemt, since the notebook process is already running and we can't modify its environment by running the script in any way. This simple hack prints out the whole path string after running the script and simply modifies the environemnt manually. Make sure you don't run this cell more than once:\n\n\n```python\npath = ntl.RunKaldiCommand('source ./path.sh ; printenv | grep ^PATH=')[0]\n\nprint 'Setting '+path\n\nos.environ['PATH']=path.split('=')[1]\n```\n\n    Setting PATH=/home/PJWSTK/danijel/apps/kaldi/src/bin:/home/PJWSTK/danijel/apps/kaldi/src/chainbin:/home/PJWSTK/danijel/apps/kaldi/src/featbin:/home/PJWSTK/danijel/apps/kaldi/src/fgmmbin:/home/PJWSTK/danijel/apps/kaldi/src/fstbin:/home/PJWSTK/danijel/apps/kaldi/src/gmmbin:/home/PJWSTK/danijel/apps/kaldi/src/ivectorbin:/home/PJWSTK/danijel/apps/kaldi/src/kwsbin:/home/PJWSTK/danijel/apps/kaldi/src/latbin:/home/PJWSTK/danijel/apps/kaldi/src/lmbin:/home/PJWSTK/danijel/apps/kaldi/src/nnet2bin:/home/PJWSTK/danijel/apps/kaldi/src/nnet3bin:/home/PJWSTK/danijel/apps/kaldi/src/nnetbin:/home/PJWSTK/danijel/apps/kaldi/src/online2bin:/home/PJWSTK/danijel/apps/kaldi/src/onlinebin:/home/PJWSTK/danijel/apps/kaldi/src/sgmm2bin:/home/PJWSTK/danijel/apps/kaldi/src/sgmmbin:/home/pjwstk.edu.pl/danijel/python_venv/venv1/ASRDemos/notebooks/work/utils/:/home/PJWSTK/danijel/apps/kaldi/tools/openfst/bin:/home/pjwstk.edu.pl/danijel/python_venv/venv1/ASRDemos/notebooks/work:/home/pjwstk.edu.pl/danijel/python_venv/venv1/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/PJWSTK/danijel/.local/bin:/home/PJWSTK/danijel/bin:/home/pjwstk.edu.pl/danijel/apps/kaldi/tools/srilm/bin:/home/pjwstk.edu.pl/danijel/apps/kaldi/tools/srilm/bin/i686-m64:/home/pjwstk.edu.pl/danijel/apps/kaldi/tools/irstlm/bin\n    \n\n\n## Linear regression\n\nLinear regression is probably the simplest problem you can implment using an ANN library. The problem is stated like this. Say we define a function using a linear equation, for example:\n\n\\begin{equation}\ny = 0.3 x_1 + 0.1 x_2 + 0.2\n\\end{equation}\n\nNow let's ask our friend to guess the formula of the function, but all we can tell him is what the output is given any input. To him, it's essentially a black-box.\n\nTo make his life easier, we tell him that the function is linear and that it takes two inputs and gives one output. He may decide to describe his problem thusly:\n\n\\begin{equation}\ny = w_1 \\cdot x_1 + w_2 \\cdot x_2 + b\n\\end{equation}\n\nFor any $x_1$ and $x_2$ given to the formula above, with the $w_1$, $w_2$, and $b$ such that the $y$ computed using that function is as close to the one in the unknown, black-box function.\n\nTo help him solve the proble, we will provide our buddy with a 100 examples of random input-output pairs. First let's define our function:\n\n\n```python\ndef problem(x):\n        return x[0]*0.3+x[1]*0.1+0.2\n```\n\nNow let generate 100 inputs and outputs. You can modify these two cells to see if the rest of the notebook will adjust accordingly.\n\n\n```python\nimport numpy as np\n\nnp.random.seed(1234)\n\ninput_dim=2\ndata_num=100\n\ninputs=np.random.random((data_num,input_dim))\noutputs=np.array([problem(x) for x in inputs])\nif outputs.ndim==1:\n        outputs=outputs.reshape(outputs.shape[0],1)\n```\n\n### Data storage\n\nKaldi accepts the inputs to its programs in specific formats. The nnet3 nets accept a specific EGS input format. The python function below converts two numpy arrays into a file stored using that format.\n\n\n```python\ndef write_simple_egs(filename,inputs,outputs):\n    input_dim=inputs.shape[1]\n    output_dim=outputs.shape[1]\n    with open(filename,'w') as f:\n        for i,l in enumerate(inputs):\n            \n            f.write('data-{} '.format(i))\n            f.write('<Nnet3Eg> ')\n            f.write('<NumIo> {} '.format(input_dim))\n\n            f.write('<NnetIo> input ')\n            f.write('<I1V> 1 <I1> 0 0 0  ')\n            f.write('[\\n  ')\n            for d in l:\n                f.write('{} '.format(d))\n            f.write(']\\n')\n            f.write('</NnetIo> ')\n\n            f.write('<NnetIo> output ')\n            f.write('<I1V> 1 <I1> 0 0 0  ')\n            f.write('[\\n  ')\n            for d in outputs[i]:\n                f.write('{} '.format(d))\n            f.write(']\\n')\n            f.write('</NnetIo> ')\n\n            f.write('</Nnet3Eg> ')\n            \nwrite_simple_egs('nnet.egs',inputs,outputs)\n```\n\nWe can check out a few example lines:\n\n\n```python\n!head -n 10 nnet.egs\n```\n\n    data-0 <Nnet3Eg> <NumIo> 2 <NnetIo> input <I1V> 1 <I1> 0 0 0  [\r\n      0.191519450379 0.62210877104 ]\r\n    </NnetIo> <NnetIo> output <I1V> 1 <I1> 0 0 0  [\r\n      0.319666712218 ]\r\n    </NnetIo> </Nnet3Eg> data-1 <Nnet3Eg> <NumIo> 2 <NnetIo> input <I1V> 1 <I1> 0 0 0  [\r\n      0.437727739007 0.785358583714 ]\r\n    </NnetIo> <NnetIo> output <I1V> 1 <I1> 0 0 0  [\r\n      0.409854180074 ]\r\n    </NnetIo> </Nnet3Eg> data-2 <Nnet3Eg> <NumIo> 2 <NnetIo> input <I1V> 1 <I1> 0 0 0  [\r\n      0.779975808119 0.272592605283 ]\r\n\n\nIt may look complicated, but it's not that bad:\n  * each input sequence starts with a unique name followed by an ```<Nnet3Eg>``` xml-linke block - this example creates one value per input sequence, but normally you would create many values per sequence, where one sequence corresponds to one file or utterance\n  * The ```<Nnet3Eg>``` is followed by a sequence of observation (in this case there is only one per file) which is opened by the ```<NumIo>``` block informing us what is the number of values stored in this observation\n  * Following that is the sequence of ```<NnetIO>``` blocks with the actual data - in this case we have two such blocks per observation: input and output\n  * the first item inside the ```<NnetIo>``` block is the name of the data point\n  * next is the index of the data point - ```<I1V>``` is the number of index values and ```<I1>``` is the actual index values - you can read more about indexes here: http://kaldi-asr.org/doc/dnn3_code_data_types.html#dnn3_dt_datastruct_index\n  * after that is the actual values of the data - in our case both input and output are expressed in the *dense matrix* form - it's a bit strange  with its use of newlines, but it is a standard form used throughout kaldi\n  * alternatively, instead of the *dense matrix* form, a *sparse matrix* is sometimes used when trying to express posteriors - it begins with a ```SM``` token followed by ```row=``` and ```dim=``` - it won't be described in this tutorial\n  \n  \n### Config file\n\nThe whole *nnet3* system is based around the confguration files, which allow creating almost any topology (feed-forward or recurrent) in a graphical manner. This file consists of two sets of information:\n  * components - describing the sets of weights in the ANN\n  * nodes - describing the connections between the components\n  \nIn our simple example we create a single component describing the dense weights of the model in an *affine* operation (in other words weighted sum with bias). It has two dimension parameters (input and output) and you can also set the learning rate here. Note that the name of the component is later used in the graph description.\n\nOther types of components include different type of fixed (ie constant) and dynamic weight containers and various activation functions. You can also define your own components, if you need to.\n\nThe second portion of the file include the connections between the individual components. These connections are represented by graph nodes. Two nodes are defined for any model: input-node and output-node. They are linked to input and output values in our EGS file above (note that the names of these nodes match the names of the matrices in the EGS file). \n\nThe input-node also needs to define the dimension of the input data (for graph construction purposes). Also note that you can have many input nodes per model.\n\nAll other nodes apart from the input node have an input parameter denoting what they are connected to. Component nodes also have a component attribute linking it to the component from the list above the nodes. The output node can also define an objective function - currently only `quadratic` is available (for MSE) and `linear` (for cross-entropy, but computed on likelihoods).\n\n\n```python\n%%writefile nnet.config\n# First the components\ncomponent name=wts type=AffineComponent input-dim=2 output-dim=1 learning-rate=0.6\n# Next the nodes\ninput-node name=input dim=2\ncomponent-node name=wts_node component=wts input=input\noutput-node name=output input=wts_node objective=quadratic\n```\n\n    Overwriting nnet.config\n\n\n### Network initialization\n\nUsing the config file, we can create a randomly initialized network using the `nnet3-init` program:\n\n\n```python\nprint ntl.RunKaldiCommand('nnet3-init {} {}'.format('nnet.config','nnet.init'))[1]\n```\n\n    nnet3-init nnet.config nnet.init \n    LOG (nnet3-init:main():nnet3-init.cc:80) Initialized raw neural net and wrote it to nnet.init\n    \n\n\nWe can see the description of the network with the `nnet3-info` program:\n\n\n```python\nprint ntl.RunKaldiCommand('nnet3-info {}'.format('nnet.init'))[0]\n```\n\n    num-parameters: 3\n    modulus: 1\n    input-node name=input dim=2\n    component-node name=wts_node component=wts input=input input-dim=2 output-dim=1\n    output-node name=output input=wts_node dim=1 objective=quadratic\n    component name=wts type=AffineComponent, input-dim=2, output-dim=1, learning-rate=0.6, linear-params-rms=1.089, bias-{mean,stddev}=0.479,0\n    \n\n\nOr even draw it to a DOT file (this looks far more impressive for bigger models):\n\n\n```python\nfrom IPython.display import SVG, Image, display\nfrom subprocess import check_call\n\nntl.RunKaldiCommand('nnet3-info {} | python steps/nnet3/dot/nnet3_to_dot.py {}'.format('nnet.init','nnet.dot'))\n#my installation of dot doesn't support PNG, so I have to resort to SVG\ncheck_call(['dot','-Tsvg','nnet.dot','-o','nnet.svg'])\n#SVG can't be scaled in notebook, but I can use imagemagick to convert to PNG\ncheck_call(['convert','nnet.svg','nnet.png'])\ndisplay(Image('nnet.png'))\n```\n\nThe networks are stored in a binary (comressed) format, but we can see their contents (eg. weights) using the `nnet3-copy` program:\n\n\n```python\nprint ntl.RunKaldiCommand('nnet3-copy --binary=false {} {}'.format('nnet.init','-'))[0]\n```\n\n    <Nnet3> \n    input-node name=input dim=2\n    component-node name=wts_node component=wts input=input\n    output-node name=output input=wts_node objective=quadratic\n    \n    <NumComponents> 1 \n    <ComponentName> wts <AffineComponent> <LearningRate> 0.6 <LinearParams>  [\n      -0.8441005 1.287315 ]\n    <BiasParams>  [ 0.4790476 ]\n    <IsGradient> F </AffineComponent> \n    </Nnet3> \n\n\n### Training\n\nThis network is totally random for now and doesn't do much. This command trains the network using the provided EGS data and stores the trained network into an output file:\n\n\n```python\nprint ntl.RunKaldiCommand('nnet3-train {} ark,t:{} {}'.format('nnet.init','nnet.egs','nnet.out'))[1]\n```\n\n    nnet3-train nnet.init ark,t:nnet.egs nnet.out \n    WARNING (nnet3-train:SelectGpuId():cu-device.cc:182) Suggestion: use 'nvidia-smi -c 3' to set compute exclusive mode\n    LOG (nnet3-train:SelectGpuIdAuto():cu-device.cc:300) Selecting from 6 GPUs\n    LOG (nnet3-train:SelectGpuIdAuto():cu-device.cc:315) cudaSetDevice(0): Tesla K80\tfree:11328M, used:190M, total:11519M, free/total:0.983435\n    LOG (nnet3-train:SelectGpuIdAuto():cu-device.cc:315) cudaSetDevice(1): Tesla K80\tfree:11396M, used:122M, total:11519M, free/total:0.989352\n    LOG (nnet3-train:SelectGpuIdAuto():cu-device.cc:315) cudaSetDevice(2): Tesla K80\tfree:11396M, used:122M, total:11519M, free/total:0.98935\n    LOG (nnet3-train:SelectGpuIdAuto():cu-device.cc:315) cudaSetDevice(3): Tesla K80\tfree:11396M, used:122M, total:11519M, free/total:0.989352\n    LOG (nnet3-train:SelectGpuIdAuto():cu-device.cc:315) cudaSetDevice(4): Tesla K80\tfree:11396M, used:122M, total:11519M, free/total:0.98935\n    LOG (nnet3-train:SelectGpuIdAuto():cu-device.cc:315) cudaSetDevice(5): Tesla K80\tfree:11396M, used:122M, total:11519M, free/total:0.98935\n    LOG (nnet3-train:SelectGpuIdAuto():cu-device.cc:364) Trying to select device: 1 (automatically), mem_ratio: 0.989352\n    LOG (nnet3-train:SelectGpuIdAuto():cu-device.cc:383) Success selecting device 1 free mem ratio: 0.989352\n    LOG (nnet3-train:FinalizeActiveGpu():cu-device.cc:225) The active GPU is [1]: Tesla K80\tfree:11382M, used:136M, total:11519M, free/total:0.988137 version 3.7\n    LOG (nnet3-train:PrintTotalStats():nnet-training.cc:187) Overall average objective function for 'output' is -0.0249837 over 100 frames.\n    LOG (nnet3-train:PrintTotalStats():nnet-training.cc:194) [this line is to be parsed by a script:] log-prob-per-frame=-0.0249837\n    LOG (nnet3-train:PrintProfile():cu-device.cc:427) -----\n    [cudevice profile]\n    Destroy\t0.000334501s\n    CuMatrix::Resize\t0.000437737s\n    Set\t0.00146961s\n    AddVec\t0.00149488s\n    CuMatrix::SetZero\t0.00174952s\n    CopyRowsFromVec\t0.00175142s\n    AddMatVec\t0.00187111s\n    CuVector::Resize\t0.00218081s\n    CuMatrixBase::CopyFromMat(from CPU)\t0.00235319s\n    CopyToVec\t0.00295281s\n    CuVector::SetZero\t0.00302505s\n    AddMat\t0.00325632s\n    VecVec\t0.00367117s\n    AddMatMat\t0.00450778s\n    TraceMatMat\t0.0069685s\n    Total GPU time:\t0.0380883s (may involve some double-counting)\n    -----\n    LOG (nnet3-train:PrintMemoryUsage():cu-allocator.cc:127) Memory usage: 44 bytes currently allocated (max: 44); 24 currently in use by user (max: 44); 8/604 calls to Malloc* resulted in CUDA calls.\n    LOG (nnet3-train:PrintMemoryUsage():cu-allocator.cc:134) Time taken in cudaMallocPitch=0, in cudaMalloc=8.10623e-05, in cudaFree=0, in this->MallocPitch()=0.00075531\n    LOG (nnet3-train:PrintMemoryUsage():cu-device.cc:400) Memory used (according to the device): 0 bytes.\n    LOG (nnet3-train:main():nnet3-train.cc:86) Wrote model to nnet.out\n    \n\n\nObviously, to get a better result, it's a good idea to run this several times for a couple of epochs. With such a simple problem and high learning rate, only a few steps is enough to reach equilibrium:\n\n\n```python\nprint ntl.RunKaldiCommand('nnet3-copy --binary=false {} {}'.format('nnet.out','-'))[0]\nfor i in range(3):\n    ntl.RunKaldiCommand('nnet3-train {} ark,t:{} {}'.format('nnet.out','nnet.egs','nnet.out'))\n    print ntl.RunKaldiCommand('nnet3-copy --binary=false {} {}'.format('nnet.out','-'))[0]\n```\n\n    <Nnet3> \n    input-node name=input dim=2\n    component-node name=wts_node component=wts input=input\n    output-node name=output input=wts_node objective=quadratic\n    \n    <NumComponents> 1 \n    <ComponentName> wts <AffineComponent> <LearningRate> 0.6 <LinearParams>  [\n      0.2909224 0.1076631 ]\n    <BiasParams>  [ 0.1960226 ]\n    <IsGradient> F </AffineComponent> \n    </Nnet3> \n    <Nnet3> \n    input-node name=input dim=2\n    component-node name=wts_node component=wts input=input\n    output-node name=output input=wts_node objective=quadratic\n    \n    <NumComponents> 1 \n    <ComponentName> wts <AffineComponent> <LearningRate> 0.6 <LinearParams>  [\n      0.2999439 0.1000724 ]\n    <BiasParams>  [ 0.199928 ]\n    <IsGradient> F </AffineComponent> \n    </Nnet3> \n    <Nnet3> \n    input-node name=input dim=2\n    component-node name=wts_node component=wts input=input\n    output-node name=output input=wts_node objective=quadratic\n    \n    <NumComponents> 1 \n    <ComponentName> wts <AffineComponent> <LearningRate> 0.6 <LinearParams>  [\n      0.2999998 0.1000008 ]\n    <BiasParams>  [ 0.1999988 ]\n    <IsGradient> F </AffineComponent> \n    </Nnet3> \n    <Nnet3> \n    input-node name=input dim=2\n    component-node name=wts_node component=wts input=input\n    output-node name=output input=wts_node objective=quadratic\n    \n    <NumComponents> 1 \n    <ComponentName> wts <AffineComponent> <LearningRate> 0.6 <LinearParams>  [\n      0.3 0.1 ]\n    <BiasParams>  [ 0.2 ]\n    <IsGradient> F </AffineComponent> \n    </Nnet3> \n\n\nAnd now you can see that the values of the weights match exactly to the values of our secret equation. The method works!\n\n### Computation\n\nOne final question you may ask is, how can we use a trained network on new data? Well, let's create some random data first:\n\n\n```python\ntest_num=10\n\ntest=np.random.random((test_num,input_dim))\n\nprint test\n```\n\n    [[ 0.97903882  0.88123225]\n     [ 0.62768192  0.93048653]\n     [ 0.72478995  0.71667789]\n     [ 0.04107857  0.43948178]\n     [ 0.28206978  0.33499597]\n     [ 0.08352701  0.76084915]\n     [ 0.50927245  0.66104742]\n     [ 0.63031444  0.37092683]\n     [ 0.44674015  0.41510822]\n     [ 0.48038851  0.98332357]]\n\n\nThese are the values we should get:\n\n\n```python\nfor x in test:\n    print problem(x)\n```\n\n    0.581834870614\n    0.481353229779\n    0.489104774536\n    0.256271747492\n    0.318120531824\n    0.301143016819\n    0.41888647591\n    0.426187015491\n    0.375532867539\n    0.442448909743\n\n\nLet's store the data in a matrix file, for Kaldi to be able to process:\n\n\n```python\nwith open('test.mat','w') as f:\n    f.write('test [')\n    for row in test:\n        f.write('\\n  ')\n        f.write(' '.join([`num` for num in row]))\n    f.write('  ]\\n')\n%cat test.mat\n```\n\n    test [\r\n      0.9790388199339376 0.88123224633892705\r\n      0.62768192146397517 0.93048653340266563\r\n      0.72478995310243888 0.71667788605535621\r\n      0.041078566584183851 0.43948177516747489\r\n      0.28206978311608777 0.33499596889192729\r\n      0.083527007044400303 0.76084914705738604\r\n      0.50927244716395392 0.6610474176084522\r\n      0.63031444248428148 0.37092682745752747\r\n      0.44674015173084469 0.41510822019759319\r\n      0.4803885080134066 0.98332357338846621  ]\r\n\n\nNow let's use the trained net to compute the results:\n\n\n```python\nprint ntl.RunKaldiCommand('nnet3-compute {} ark,t:{} ark,t:{}'.format('nnet.out','test.mat','-'))[0]\n```\n\n    test  [\n      0.5818349 \n      0.4813533 \n      0.4891048 \n      0.2562718 \n      0.3181205 \n      0.3011431 \n      0.4188865 \n      0.426187 \n      0.3755329 \n      0.4424489 ]\n    \n\n\n\n```python\n\n```\n", "meta": {"hexsha": "f48693e27fc7671fe4a24d7856f2dd827616d6e9", "size": 50232, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/SimpleRegressionKaldi.ipynb", "max_stars_repo_name": "danijel3/ASRDemos", "max_stars_repo_head_hexsha": "33b82d56eba5b508f53f0120193b15f72859173b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 57, "max_stars_repo_stars_event_min_datetime": "2016-02-10T02:11:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-23T15:39:00.000Z", "max_issues_repo_path": "notebooks/SimpleRegressionKaldi.ipynb", "max_issues_repo_name": "danijel3/ASRDemos", "max_issues_repo_head_hexsha": "33b82d56eba5b508f53f0120193b15f72859173b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/SimpleRegressionKaldi.ipynb", "max_forks_repo_name": "danijel3/ASRDemos", "max_forks_repo_head_hexsha": "33b82d56eba5b508f53f0120193b15f72859173b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2016-04-05T19:31:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-07T12:17:10.000Z", "avg_line_length": 62.0148148148, "max_line_length": 19830, "alphanum_fraction": 0.7436494665, "converted": true, "num_tokens": 6509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276683008207139, "lm_q2_score": 0.05582314506158598, "lm_q1q2_score": 0.018291475088798102}}
{"text": " \u0423 \u043d\u0430\u0441 \u0438\u043c\u0435\u044e\u0442\u0441\u044f \u0442\u0430\u0431\u043b\u0438\u0446\u044b \u0441 \u0434\u0430\u043d\u043d\u044b\u043c\u0438 \u043a\u0430\u0442\u0430\u043b\u043e\u0433\u043e\u0432:\n- SDSS (glist_s), \n- 2MRS (glist_2).\n \nSDSS - Sloan Digital Sky Survey \u0441 \u0430\u043d\u0433\u043b.\u2009\u2014\u2009\u00ab\u0421\u043b\u043e\u0443\u043d\u043e\u0432\u0441\u043a\u0438\u0439 \u0446\u0438\u0444\u0440\u043e\u0432\u043e\u0439 \u043d\u0435\u0431\u0435\u0441\u043d\u044b\u0439 \u043e\u0431\u0437\u043e\u0440\u00bb) \u2014 \u043f\u0440\u043e\u0435\u043a\u0442 \u0448\u0438\u0440\u043e\u043a\u043e\u043c\u0430\u0441\u0448\u0442\u0430\u0431\u043d\u043e\u0433\u043e \u0438\u0441\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u043d\u0438\u044f \u043c\u043d\u043e\u0433\u043e\u0441\u043f\u0435\u043a\u0442\u0440\u0430\u043b\u044c\u043d\u044b\u0445 \u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u0439 \u0438 \u0441\u043f\u0435\u043a\u0442\u0440\u043e\u0432 \u043a\u0440\u0430\u0441\u043d\u043e\u0433\u043e \u0441\u043c\u0435\u0449\u0435\u043d\u0438\u044f \u0437\u0432\u0451\u0437\u0434 \u0438 \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a \u043f\u0440\u0438 \u043f\u043e\u043c\u043e\u0449\u0438 2,5-\u043c\u0435\u0442\u0440\u043e\u0432\u043e\u0433\u043e \u0448\u0438\u0440\u043e\u043a\u043e\u0443\u0433\u043e\u043b\u044c\u043d\u043e\u0433\u043e \u0442\u0435\u043b\u0435\u0441\u043a\u043e\u043f\u0430 \u0432 \u043e\u0431\u0441\u0435\u0440\u0432\u0430\u0442\u043e\u0440\u0438\u0438 \u0410\u043f\u0430\u0447\u0438-\u041f\u043e\u0439\u043d\u0442 \u0432 \u0448\u0442\u0430\u0442\u0435 \u041d\u044c\u044e-\u041c\u0435\u043a\u0441\u0438\u043a\u043e. \u041f\u0440\u043e\u0435\u043a\u0442 \u043d\u0430\u0437\u0432\u0430\u043d \u0432 \u0447\u0435\u0441\u0442\u044c \u0444\u043e\u043d\u0434\u0430 \u0410\u043b\u044c\u0444\u0440\u0435\u0434\u0430 \u0421\u043b\u043e\u0443\u043d\u0430.\n\n\u0418\u0441\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u043d\u0438\u044f \u043d\u0430\u0447\u0430\u043b\u0438\u0441\u044c \u0432 2000 \u0433\u043e\u0434\u0443, \u0432 \u0445\u043e\u0434\u0435 \u0440\u0430\u0431\u043e\u0442\u044b \u043f\u0440\u043e\u0435\u043a\u0442\u0430 \u0431\u044b\u043b\u043e \u043f\u0440\u043e\u0432\u0435\u0434\u0435\u043d\u043e \u043a\u0430\u0440\u0442\u043e\u0433\u0440\u0430\u0444\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435 \u0431\u043e\u043b\u0435\u0435 35 % \u043d\u0435\u0431\u0435\u0441\u043d\u043e\u0439 \u0441\u0444\u0435\u0440\u044b \u0441 \u0444\u043e\u0442\u043e\u043c\u0435\u0442\u0440\u0438\u0447\u0435\u0441\u043a\u0438\u043c\u0438 \u043d\u0430\u0431\u043b\u044e\u0434\u0435\u043d\u0438\u044f\u043c\u0438 \u043f\u043e\u0440\u044f\u0434\u043a\u0430 500 \u043c\u0438\u043b\u043b\u0438\u043e\u043d\u043e\u0432 \u043e\u0431\u044a\u0435\u043a\u0442\u043e\u0432 \u0438 \u043f\u043e\u043b\u0443\u0447\u0435\u043d\u0438\u0435\u043c \u0441\u043f\u0435\u043a\u0442\u0440\u043e\u0432 \u0431\u043e\u043b\u0435\u0435 \u0447\u0435\u043c \u0434\u043b\u044f 3 \u043c\u0438\u043b\u043b\u0438\u043e\u043d\u043e\u0432 \u043e\u0431\u044a\u0435\u043a\u0442\u043e\u0432. \u0421\u0440\u0435\u0434\u043d\u0435\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u043a\u0440\u0430\u0441\u043d\u043e\u0433\u043e \u0441\u043c\u0435\u0449\u0435\u043d\u0438\u044f \u043f\u043e \u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u044f\u043c \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a \u0441\u043e\u0441\u0442\u0430\u0432\u0438\u043b\u043e 0.1; \u0434\u043b\u044f \u044f\u0440\u043a\u0438\u0445 \u043a\u0440\u0430\u0441\u043d\u044b\u0445 \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a \u0432\u043f\u043b\u043e\u0442\u044c \u0434\u043e z=0,4, \u0434\u043b\u044f \u043a\u0432\u0430\u0437\u0430\u0440\u043e\u0432 \u0434\u043e z=5. \u041d\u0430\u0431\u043b\u044e\u0434\u0435\u043d\u0438\u044f \u0432 \u0440\u0430\u043c\u043a\u0430\u0445 \u043e\u0431\u0437\u043e\u0440\u0430 \u0441\u043f\u043e\u0441\u043e\u0431\u0441\u0442\u0432\u043e\u0432\u0430\u043b\u0438 \u043e\u0431\u043d\u0430\u0440\u0443\u0436\u0435\u043d\u0438\u044e \u043a\u0432\u0430\u0437\u0430\u0440\u043e\u0432 \u0441\u043e \u0441\u0434\u0432\u0438\u0433\u043e\u043c \u0431\u043e\u043b\u0435\u0435 6.\n\n\u041f\u0440\u043e\u0435\u043a\u0442 \u0434\u0435\u043b\u0438\u0442\u0441\u044f \u043d\u0430 \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u0444\u0430\u0437: SDSS-I (2000\u20142005), SDSS-II (2005\u20142008), SDSS-III (2008\u20142014), SDSS-IV (2014\u20142020). \u0421\u043e\u0431\u0440\u0430\u043d\u043d\u044b\u0435 \u0432 \u0445\u043e\u0434\u0435 \u043e\u0431\u0437\u043e\u0440\u043e\u0432 \u0434\u0430\u043d\u043d\u044b\u0435 \u043f\u0443\u0431\u043b\u0438\u043a\u0443\u044e\u0442\u0441\u044f \u0432 \u0432\u0438\u0434\u0435 \u043e\u0442\u0434\u0435\u043b\u044c\u043d\u044b\u0445 \u0440\u0435\u043b\u0438\u0437\u043e\u0432 (Data Release), \u043f\u043e\u0441\u043b\u0435\u0434\u043d\u0438\u0439 \u0438\u0437 \u043d\u0438\u0445, DR13 \u043e\u043f\u0443\u0431\u043b\u0438\u043a\u043e\u0432\u0430\u043d \u0432 \u0430\u0432\u0433\u0443\u0441\u0442\u0435 2016 \u0433\u043e\u0434\u0430.\n\n2MASS Redshift Survey -  aims to map the distribution of galaxies and dark matter in the local universe, out to a mean redshift of z = 0.03 (roughly equivalent to 115 Mpc or 370 million light-years). It is based on galaxy selection in the near infra-red from the Two Micron All-Sky Survey (2MASS). 2MASS has now mapped all of the sky in the near infra-red J, H and K-bands. This photometric survey is complete and fully available to the public (IRSA). The 2MASS extended source catalog (XSC) includes roughly half a million galaxies to a limiting K magnitude of K=13.5 mag. 2MRS ultimately aims to determine the redshifts of all galaxies in the XSC to a magnitude of K=12.2 mag (about 100,000 galaxies) and to within 5 deg of the Galactic plane. The second phase of 2MRS is now complete, providing an all-sky survey of 45,000 galaxies with redshifts to a limiting magnitude of K=11.75 mag. It is the densest sampled all-sky redshift survey to date and its selection in the near infra-red reduces the impact of the zone of avoidance (where the plane of our own Galaxy obscures extragalactic objects). 2MRS provides complementary redshift information to deeper surveys like SDSS and the 2dFRGS which cover much smaller fractions of the sky. It improves on the IRAS redshift survey IRAS PSCz which was not able to distinguish galaxies in regions of high density (ie. clusters).\n\n\n```python\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\n```\n\n\n```python\ndata = pd.read_csv('glist_2.csv')\n```\n\n\n```python\ndata.info()\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 1200 entries, 0 to 1199\n    Data columns (total 21 columns):\n    iGalID            1200 non-null int64\n    iGrID             1200 non-null int64\n    Name              1200 non-null object\n    RAJ2000_gal       1200 non-null float64\n    DEJ2000_gal       1200 non-null float64\n    z_gal             1200 non-null float64\n    logMstar_gal      425 non-null float64\n    RAJ2000_group     1200 non-null float64\n    DEJ2000_group     1200 non-null float64\n    z_group           1200 non-null float64\n    logLtot           1200 non-null float64\n    logLobs           1200 non-null float64\n    logMtot           1200 non-null float64\n    logMstar_group    1165 non-null float64\n    NMstar            1200 non-null int64\n    logMdyn           1200 non-null float64\n    sigma             1200 non-null float64\n    Rad               1200 non-null float64\n    angRad            1200 non-null float64\n    DL                1200 non-null float64\n    Ntot              1200 non-null int64\n    dtypes: float64(16), int64(4), object(1)\n    memory usage: 197.0+ KB\n\n\n\n```python\nfrom IPython.display import Image \nImage(\"projections.png\") \n```\n\n\u0412 \u0430\u0441\u0442\u0440\u043e\u0444\u0438\u0437\u0438\u043a\u0435 \u043f\u0440\u0438\u043d\u044f\u0442\u043e \u0440\u0430\u0441\u0441\u043c\u0430\u0442\u0440\u0438\u0432\u0430\u0442\u044c \u043d\u0435\u0431\u0435\u0441\u043d\u044b\u0435 \u043e\u0431\u044a\u0435\u043a\u0442\u044b \u0432 \u043f\u0440\u043e\u0435\u043a\u0446\u0438\u0438 \u043d\u0430 \u043d\u0435\u0431\u0435\u0441\u043d\u0443\u044e \u0441\u0444\u0435\u0440\u0443.    \n\n\u041f\u0440\u0435\u0434\u043f\u043e\u043b\u0430\u0433\u0430\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u043d\u0430\u0431\u043b\u044e\u0434\u0430\u0442\u0435\u043b\u044c \u0440\u0430\u0441\u043f\u043e\u043b\u0430\u0433\u0430\u0435\u0442\u0441\u044f \u0432 \u0432\u0435\u0440\u0448\u0438\u043d\u0435 \u0443\u0433\u043b\u0430 $a$.\n\u043d\u0430 \u0440\u0438\u0441\u0443\u043d\u043a\u0435 \u043e\u0431\u043e\u0437\u043d\u0430\u0447\u0435\u043d\u043e:\n\n$O$ - \u0446\u0435\u043d\u0442\u0440 \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u043e\u0433\u043e \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u044f,\n\n$A_0$ - \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u0430\u044f \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a\u0430 \u0438\u0437 \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u044f,\n\n$r_0$ - \u0432\u0435\u043a\u0442\u043e\u0440, \u0441\u043e\u0435\u0434\u0438\u043d\u044f\u044e\u0449\u0438\u0439 \u0433\u043b\u0430\u0437 \u043d\u0430\u0431\u043b\u044e\u0434\u0430\u0442\u0435\u043b\u044f \u0438 \u0446\u0435\u043d\u0442\u0440 \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u044f $O$,\n\n$r_1$ - \u0432\u0435\u043a\u0442\u043e\u0440, \u0441\u043e\u0435\u0434\u0438\u043d\u044f\u044e\u0449\u0438\u0439 \u0433\u043b\u0430\u0437 \u043d\u0430\u0431\u043b\u044e\u0434\u0430\u0442\u0435\u043b\u044f \u0438 \u043e\u0431\u044a\u0435\u043a\u0442 $A_0$,\n\n$P$ - \u043f\u043b\u043e\u0441\u043a\u043e\u0441\u0442\u044c \u043f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u043d\u0430\u044f \u0442\u0430\u043a\u0438\u043c \u043e\u0431\u0440\u0430\u0437\u043e\u043c, \u0447\u0442\u043e \u043e\u043d\u0430 \u043f\u0435\u0440\u043f\u0435\u043d\u0434\u0438\u043a\u0443\u043b\u044f\u0440\u043d\u0430 \u0432\u0435\u043a\u0442\u043e\u0440\u0443   $r_0$ \u0438 \u043f\u0440\u043e\u0445\u043e\u0434\u0438\u0442 \u0447\u0435\u0440\u0435\u0437 \u0446\u0435\u043d\u0442\u0440 \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u044f $O$,\n\n$A$ - \u0442\u043e\u0447\u043a\u0430 \u043f\u0435\u0440\u0435\u0441\u0435\u0447\u0435\u043d\u0438\u044f \u043b\u0443\u0447\u0430, \u0438\u0434\u0443\u0449\u0435\u0433\u043e \u0438\u0437 \u0433\u043b\u0430\u0437\u0430 \u043d\u0430\u0431\u043b\u044e\u0434\u0430\u0442\u0435\u043b\u044f \u0447\u0435\u0440\u0435\u0437 \u043e\u0431\u044a\u0435\u043a\u0442 $\u0410_0$ \u0441 \u043f\u043b\u043e\u0441\u043a\u043e\u0441\u0442\u044c\u044e $P$,\n\n$H$ - \u043f\u0435\u0440\u043f\u0435\u043d\u0434\u0438\u043a\u0443\u043b\u044f\u0440, \u043e\u043f\u0443\u0449\u0435\u043d\u043d\u044b\u0439 \u0438\u0437 \u0438\u0437  $A_0$ \u043d\u0430 \u043f\u043b\u043e\u0441\u043a\u043e\u0441\u0442\u044c $H$,\n\n$a$ - \u043b\u0438\u043d\u0435\u0439\u043d\u044b\u0439 \u0443\u0433\u043e\u043b \u043c\u0435\u0436\u0434\u0443 \u0432\u0435\u043a\u0442\u043e\u0440\u0430\u043c\u0438 $r_0$ \u0438 $r_1$,\n\n\u043a\u0440\u0430\u0441\u043d\u044b\u0435 \u043e\u0442\u0440\u0435\u0437\u043a\u0438 $OA(OH)$ -  \u043f\u0440\u043e\u0435\u043a\u0446\u0438\u0438 \u043d\u0430 \u043f\u043b\u043e\u0441\u043a\u043e\u0441\u0442\u044c \u0420.\n\n###### \u0422\u0430\u043a \u043a\u0430\u043a \u043d\u0430\u0431\u043b\u044e\u0434\u0435\u043d\u0438\u044f \u043f\u0440\u043e\u0432\u043e\u0434\u044f\u0442\u0441\u044f \u0438\u0437 \u043e\u0434\u043d\u043e\u0439 \u0442\u043e\u0447\u043a\u0438, \u0442\u043e \u0438\u043d\u0442\u0435\u0440\u0435\u0441\u0443\u044e\u0449\u0430\u044f \u043d\u0430\u0441 \u043f\u0440\u043e\u0435\u043a\u0446\u0438\u044f - \u0446\u0435\u043d\u0442\u0440\u0430\u043b\u044c\u043d\u0430\u044f. \n\n\u041f\u043e\u0441\u043a\u043e\u043b\u044c\u043a\u0443 \u0434\u0430\u043d\u043d\u044b\u0435 \u043e\u0431 \u0443\u0433\u043b\u0430\u0445  right ascention (RAJ2000) \u0438 declination (DEJ2000) \u0443\u043a\u0430\u0437\u0430\u043d\u044b \u0432 \u0433\u0440\u0430\u0434\u0443\u0441\u0430\u0445, \u0430 \u0432\u044b\u0447\u0438\u0441\u043b\u0435\u043d\u0438\u044f\u0445 \u043c\u044b \u0431\u0443\u0434\u0435\u043c \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c\u0441\u044f \u0440\u0430\u0434\u0438\u0430\u043d\u0430\u043c\u0438, \u0442\u043e \u0441 \u043f\u043e\u043c\u043e\u0449\u044c\u044e \u0444\u043e\u0440\u043c\u0443\u043b\u044b \u043f\u0435\u0440\u0435\u0439\u0434\u0435\u043c \u043e\u0442 \u043e\u0434\u043d\u0438\u0445 \u0435\u0434\u0438\u043d\u0438\u0446 \u0438\u0437\u043c\u0435\u0440\u0435\u043d\u0438\u044f \u043a \u0434\u0440\u0443\u0433\u0438\u043c:\n\n\\begin{equation}\n\\alpha_{rad} = \\pi \\frac{\\alpha_{grad}}{180}\n\\end{equation}\n\n\n```python\n# data['RAJ2000_gal_rad'] = np.pi*data['RAJ2000_gal']/180\n# data['DEJ2000_gal_rad'] = np.pi*data['DEJ2000_gal']/180\n# data['RAJ2000_group_rad'] = np.pi*data['RAJ2000_group']/180\n# data['DEJ2000_group_rad'] = np.pi*data['DEJ2000_group']/180\n```\n\n\u0427\u0435\u0440\u0435\u0437 \u0434\u0430\u043d\u043d\u044b\u0435 \u043e\u0431 \u0443\u0433\u043b\u0430\u0445 \u043d\u0430\u043a\u043b\u043e\u043d\u0435\u043d\u0438\u044f (DEC=DEJ2000) \u0438 \u0432\u043e\u0437\u043d\u0435\u0441\u0435\u043d\u0438\u044f (RA=RAJ2000) \u0432\u044b\u0447\u0438\u0441\u043b\u044f\u044e\u0442\u0441\u044f \u043a\u043e\u043e\u0440\u0434\u0438\u043d\u0430\u0442\u044b \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0449\u0435\u0433\u043e \u043e\u0431\u044a\u0435\u043a\u0442\u0430 \u043d\u0430 \u0435\u0434\u0438\u043d\u0438\u0447\u043d\u043e\u0439 \u0441\u0444\u0435\u0440\u0435:\n\n \\begin{equation}\n\\left\\{ \\begin{array}{ll}\n    x = \\cos(DEC)\\cos(RA) \\\\\n    y = \\cos(DEC)\\sin(RA)\\\\\n    z = \\sin(DEC)\n\\end{array} \\right.\n\\end{equation}\n\n\u0414\u0430\u043b\u0435\u0435 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u0432\u044b\u0447\u0438\u0441\u043b\u0438\u0442\u044c \u0434\u043b\u0438\u043d\u043d\u0443 \u043f\u0440\u043e\u0435\u043a\u0446\u0438\u0438 $OA$  \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0439 \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a\u0438 \u0438\u0437 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0449\u0435\u0433\u043e \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u044f \u043f\u043e \u0432\u0441\u0435\u043c \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u044f\u043c \u0441 \u043f\u043e\u043c\u043e\u0449\u044c\u044e \u0444\u043e\u0440\u043c\u0443\u043b\u044b: \n\n\\begin{equation}\n     r_{pr} = r_0 \\tan(a),\n\\end{equation}\n\n\u0433\u0434\u0435 \u0443\u0433\u043e\u043b $\u0430$ - \u043b\u0438\u043d\u0435\u0439\u043d\u044b\u0439 \u0443\u0433\u043e\u043b \u043c\u0435\u0436\u0434\u0443 \u043b\u0443\u0447\u0430\u043c\u0438, \u0441\u043e\u0435\u0434\u0438\u043d\u044f\u044e\u0449\u0438\u043c\u0438 \u043d\u0430\u0431\u043b\u044e\u0434\u0430\u0442\u0435\u043b\u044f \u0441 \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a\u043e\u0439 \u0432 \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u0438 \u0438 \u043d\u0430\u0431\u043b\u044e\u0434\u0430\u0442\u0435\u043b\u044f \u0441 \u0446\u0435\u043d\u0442\u0440\u043e\u043c \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u044f. \u0417\u043d\u0430\u044f \u0443\u0433\u043b\u044b \u043d\u0430\u043a\u043b\u043e\u043d\u0435\u043d\u0438\u044f (DEC=DEJ2000) \u0438 \u0432\u043e\u0437\u043d\u0435\u0441\u0435\u043d\u0438\u044f (RA=RAJ2000), \u043c\u043e\u0436\u043d\u043e \u0432\u044b\u0447\u0438\u0441\u043b\u0438\u0442\u044c \u0442\u0430\u043d\u0433\u0435\u043d\u0441 \u0443\u0433\u043b\u0430 $\u0430$:\n\n \\begin{equation}\n\\left\\{ \\begin{array}{ll}\n    x = \\cos(DEC)\\cos(RA) \\\\\n    y = \\cos(DEC)\\sin(RA)\\\\\n    z = \\sin(DEC)\n\\end{array} \\right.\n\\end{equation}\n\n\\begin{equation}\n\\cos(a) = x_{centr}x_{gal} + y_{centr}y_{gal}+z_{centr}z_{gal}\n\\end{equation}\n\n\\begin{equation}\n\\tan(a) = \\frac{\\sqrt{1-\\cos^2(a)}}{\\cos(a)}\n\\end{equation}\n\n\u0412\u0432\u0435\u0434\u0435\u043c \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c\u044b\u0435 \u0432 \u0434\u0430\u043b\u044c\u043d\u0435\u0439\u0448\u0435\u043c \u0438\u0441\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u043d\u0438\u0438 \u043a\u043e\u0441\u043c\u043e\u043b\u043e\u0433\u0438\u0447\u0435\u0441\u043a\u0438\u0435 \u043f\u043e\u0441\u0442\u043e\u044f\u043d\u043d\u044b\u0435:\n\n\n```python\nC = 300000  # km/s -  \u0441\u043a\u043e\u0440\u043e\u0441\u0442\u044c \u0441\u0432\u0435\u0442\u0430 \u0432 \u0432\u0430\u043a\u0443\u0443\u043c\u0435\nMpc = 3.086e+19 # km -  \u043c\u0435\u0433\u0430\u043f\u0430\u0440\u0441\u0435\u043a\n```\n\n\n```python\n# x0 = np.cos(data['DEJ2000_group_rad'])*np.cos(data['RAJ2000_group_rad'])\n# y0 = np.cos(data['DEJ2000_group_rad'])*np.sin(data['RAJ2000_group_rad'])\n# z0 = np.sin(data['DEJ2000_group_rad'])\n\n# x1 = np.cos(data['DEJ2000_gal_rad'])*np.cos(data['RAJ2000_gal_rad'])\n# y1 = np.cos(data['DEJ2000_gal_rad'])*np.sin(data['RAJ2000_gal_rad'])\n# z1 = np.sin(data['DEJ2000_gal_rad'])\n\n# cos_a = x0*x1+y0*y1+z0*z1\n\n# tan_a = pd.Series(np.sqrt(1-cos_a**2)/cos_a).fillna(0)\n```\n\n\n```python\n# data['r_pr'] = data['DL']*tan_a\n```\n\n\u0421\u043a\u043e\u0440\u043e\u0441\u0442\u0438 \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a \u0432 \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u0438 \u043e\u0442\u043d\u043e\u0441\u0438\u0442\u0435\u043b\u044c\u043d\u043e \u0446\u0435\u043d\u0442\u0440\u0430 \u044d\u0442\u043e\u0433\u043e \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u044f \u0432\u044b\u0441\u0447\u0438\u0442\u044b\u0432\u0430\u043b\u0438\u0441\u044c \u0441 \u043f\u043e\u043c\u043e\u0449\u044c\u044e \u0444\u043e\u0440\u043c\u0443\u043b\u044b: \n\n\\begin{equation}\n    v = c\\frac{z_{gal} - z_{cent}}{1 + z_{cent}}\n\\end{equation}\n\n\u041e\u0442\u043c\u0435\u0442\u0438\u043c, \u0447\u0442\u043e \u0432\u0441\u0435 \u044d\u0442\u0438 \u0441\u043a\u043e\u0440\u043e\u0441\u0442\u0438 \u043c\u043e\u0433\u0443\u0442 \u0432\u044b\u0447\u0438\u0441\u043b\u0435\u043d\u044b \u0442\u043e\u043b\u044c\u043a\u043e \u0432\u0434\u043e\u043b\u044c \u043b\u0443\u0447\u0430 \u0437\u0440\u0435\u043d\u0438\u044f (line-of-sight) \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0430\u043d\u0438\u0438 \u0438\u0437\u043c\u0435\u0440\u0435\u043d\u0438\u0439 \u043a\u0440\u0430\u0441\u043d\u043e\u0433\u043e \u0441\u043c\u0435\u0449\u0435\u043d\u0438\u044f (red shift)  $z$ \u0440\u0430\u0441\u0441\u043c\u0430\u0442\u0440\u0438\u0432\u0430\u0435\u043c\u043e\u0433\u043e \u043e\u0431\u044a\u0435\u043a\u0442\u0430. \u041f\u043e\u043f\u0435\u0440\u0435\u0447\u043d\u044b\u0435 \u0441\u043a\u043e\u0440\u043e\u0441\u0442\u0438 \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u044c \u0441\u043b\u043e\u0436\u043d\u043e, \u0442\u0430\u043a \u043a\u0430\u043a \u0432\u0440\u0435\u043c\u044f \u0441\u044a\u0435\u043c\u043a\u0438 \u0442\u0435\u043b\u0435\u0441\u043a\u043e\u043f\u043e\u043c \u0434\u0430\u043d\u043d\u043e\u0433\u043e \u0443\u0447\u0430\u0441\u0442\u043a\u0430 \u043d\u0435\u0431\u0430 \u043f\u043e \u0441\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u044e \u0441 \u043f\u0435\u0440\u0435\u043c\u0435\u0449\u0435\u043d\u0438\u0435\u043c \u043e\u0431\u044a\u0435\u043a\u0442\u0430 \u043f\u043e \u043d\u0435\u0431\u0435\u0441\u043d\u043e\u0439 \u0441\u0444\u0435\u0440\u0435 \u043d\u0438\u0447\u0442\u043e\u0436\u043d\u043e \u043c\u0430\u043b\u043e, \u0430 \u043f\u043e\u0442\u043e\u043c\u0443 \u0443\u0432\u0438\u0434\u0435\u0442\u044c \u043a\u0430\u043a\u0438\u0435-\u0442\u043e \u0432\u0438\u0434\u0438\u043c\u044b\u0435 \u0438\u0437\u043c\u0435\u043d\u0438\u044f \u0432 \u043f\u043e\u043b\u043e\u0436\u0435\u043d\u0438\u0438 \u043e\u0431\u044a\u0435\u043a\u0442\u0430 \u043d\u0430 \u043d\u0435\u0431\u0435 \u043f\u043e\u043a\u0430 \u043d\u0435 \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u0432\u043e\u0437\u043c\u043e\u0436\u043d\u044b\u043c.\n\n\n```python\n# data['v'] = C*(data['z_gal']-data['z_group'])/(1+data['z_group'])\n```\n\n\n```python\n# data.info()\n```\n\n\n```python\n# def drawPlot(data, GrID, ax, c):\n#     x_max = data['r_pr'].max()\n#     y_max = abs(data['v']).max()\n#     gr = data[data['iGrID'] == GrID] \n#     x = gr['r_pr']\n#     y = gr['v'] \n#     ax.scatter(x, y, c=c, marker='*')\n#     ax.set_xlabel('Distance from center of the cluster, [Mpc]')\n#     ax.set_ylabel('Relative velocity in the cluster, [km/s]')\n#     ax.set_title('iGrID = %d' % (GrID))\n#     ax.set_ylim(top=y_max, bottom=-y_max)\n#     ax.set_xlim((0,x_max))\n#     ax.grid(True)\n```\n\n\n```python\n# fig, axs = plt.subplots(7, 3, figsize=(15,25))\n# GrIDs = data['iGrID'].unique() #\u0421\u043e\u0437\u0434\u0430\u0451\u043c \u0432\u0435\u043a\u0442\u043e\u0440 \u0432\u0441\u0435\u0445 \u0433\u0440\u0443\u043f\u043f\n# for i in range(21):\n#     drawPlot(data, GrIDs[i], axs[i//3, i%3], 'blue') #\u0414\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0439 \u0433\u0440\u0443\u043f\u043f\u044b \u0432\u044b\u0437\u044b\u0432\u0430\u0435\u043c \u0444\u0443\u043d\u043a\u0446\u0438\u044e \u0438 \u043f\u0435\u0440\u0435\u0434\u0430\u0451\u043c \u0435\u0439 \u043d\u0443\u0436\u043d\u044b\u0439 '\u043f\u043e\u0434\u0433\u0440\u0430\u0444\u0438\u043a'\n# plt.tight_layout()\n```\n\n\u0414\u0430\u043b\u0435\u0435 \u0432\u043e\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c\u0441\u044f \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u043e\u0439 'Caustic mass estimator for astrophysical systems', \u0432\u0437\u044f\u0442\u043e\u0439 \u0441 \u0440\u0435\u043f\u043e\u0437\u0438\u0442\u043e\u0440\u0438\u044f  Dan Gifford \u043d\u0430 GitHub http://github.com/giffordw . \u0414\u0430\u043d\u043d\u0430\u044f \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0430 \u043f\u043e\u0437\u0432\u043e\u043b\u044f\u0435\u0442 \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0435 \u0434\u0430\u043d\u043d\u044b\u0445 \u043e\u0431 \u0443\u0433\u043b\u0430\u0445   RA, DEC \u0438 \u043a\u0440\u0430\u0441\u043d\u043e\u0433\u043e \u0441\u043c\u0435\u0449\u0435\u043d\u0438\u044f z \u0441\u0442\u0440\u043e\u0438\u0442\u044c \u043a\u0430\u0443\u0441\u0442\u0438\u0447\u0435\u0441\u043a\u0438\u0435 \u043a\u0440\u0438\u0432\u044b\u0435 \u0434\u043b\u044f \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u0439 \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a. \u041f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u043d\u044b\u0439 \u043a\u043e\u0434 \u043e\u0441\u043d\u043e\u0432\u044b\u0432\u0430\u0435\u0442\u0441\u044f \u043d\u0430 \u043c\u0435\u0442\u043e\u0434\u0430\u0445, \u043e\u043f\u0438\u0441\u0430\u043d\u043d\u044b\u0445 \u0432 \u0441\u0442\u0430\u0442\u044c\u044f\u0445:\n- A.Diafferio. Mass estimation in the outer regions of galaxy clusters. 1999.\n- Gifford et al. A Systematic Analysis of Caustic Methods for Galaxy Cluster Masses. 2013.\n- Gifford & Miller. Velocity Anisotropy and Shape Bias in the Caustic Technique. 2013.\n\n\u041a\u0430\u0443\u0441\u0442\u0438\u043a\u0438 - \u044d\u0442\u043e \u043d\u0435\u043a\u0438\u0435 \u043a\u0440\u0438\u0432\u044b\u0435 \u0432 \u0444\u0430\u0437\u043e\u0432\u043e\u0439 \u043f\u043b\u043e\u0441\u043a\u043e\u0441\u0442\u0438 (r,v), \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0440\u0430\u0437\u0434\u0435\u043b\u044f\u044e\u0442 \u044d\u0442\u0443 \u043f\u043b\u043e\u0441\u043a\u043e\u0441\u0442\u044c \u043d\u0430 \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u0441\u0435\u0433\u043c\u0435\u0442\u043e\u0432: \u0446\u0435\u043d\u0442\u0440\u0430\u043b\u044c\u043d\u044b\u0439, \u043d\u0438\u0436\u043d\u0438\u0439 \u0438 \u0432\u0435\u0440\u0445\u043d\u0438\u0439. \u0418\u0437 \u0432\u0437\u0430\u0438\u043c\u043d\u043e\u0433\u043e \u043f\u043e\u043b\u043e\u0436\u0435\u043d\u0438\u044f \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a \u0432 \u043a\u043e\u043f\u043b\u0435\u043d\u0438\u0438 \u0438 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0449\u0438\u0445 \u043a\u0430\u0443\u0441\u0442\u0438\u043a \u043d\u0430 \u0444\u0430\u0437\u043e\u0432\u043e\u0439 \u043f\u043b\u043e\u0441\u043a\u043e\u0441\u0442\u0438 \u043c\u043e\u0436\u043d\u043e \u0441\u0443\u0434\u0438\u0442\u044c \u043e \u0431\u0443\u0434\u0443\u044e\u0449\u0435\u043c \u044d\u0442\u043e\u0433\u043e \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u044f. \u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0435\u0441\u043b\u0438 \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a\u0438 \u043b\u0435\u0436\u0430\u0442 \u0432\u043d\u0435 \u0446\u0435\u043d\u0442\u0440\u0430\u043b\u044c\u043d\u043e\u0439 \u043e\u0431\u043b\u0430\u0441\u0442\u0438, \u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u043d\u043e\u0439 \u043a\u0430\u0443\u0441\u0442\u0438\u043a\u0430\u043c\u0438, \u0442\u043e \u043c\u043e\u0436\u043d\u043e \u0437\u0430\u043a\u043b\u044e\u0447\u0438\u0442\u044c, \u0447\u0442\u043e \u0434\u0430\u043d\u043d\u0430\u044f \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a\u0430 \u0432 \u0431\u0443\u0434\u0443\u0449\u0435\u043c \u043f\u043e\u043a\u0438\u043d\u0435\u0442 \u044d\u0442\u043e \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u0435.\n\n\n```python\n# !pip install cosmolopy\n```\n\n\n```python\n# !pip install scikit-image\n```\n\n\n```python\nfrom causticpy import *\n```\n\n\n```python\niGrID = data['iGrID'].unique()[0:1]\n```\n\n\n```python\ndata.columns\n```\n\n\n\n\n    Index(['iGalID', 'iGrID', 'Name', 'RAJ2000_gal', 'DEJ2000_gal', 'z_gal',\n           'logMstar_gal', 'RAJ2000_group', 'DEJ2000_group', 'z_group', 'logLtot',\n           'logLobs', 'logMtot', 'logMstar_group', 'NMstar', 'logMdyn', 'sigma',\n           'Rad', 'angRad', 'DL', 'Ntot'],\n          dtype='object')\n\n\n\n\n```python\nnew = (data[data['iGrID'].isin(iGrID)][['RAJ2000_gal', 'DEJ2000_gal', 'z_gal', \n                                          'RAJ2000_group', 'DEJ2000_group', 'z_group', 'iGrID', 'DL']])\n```\n\n\n```python\n# new\n```\n\n\n```python\nnew['z_group'] = new.loc[10,'z_gal']\nnew['RAJ2000_group'] = new.loc[10,'RAJ2000_gal'] \nnew['DEJ2000_group'] = new.loc[10,'DEJ2000_gal'] \n```\n\n\n```python\n# new\n```\n\n\n```python\ndata = new\n```\n\n\n```python\ndata['RAJ2000_gal_rad'] = np.pi*data['RAJ2000_gal']/180\ndata['DEJ2000_gal_rad'] = np.pi*data['DEJ2000_gal']/180\ndata['RAJ2000_group_rad'] = np.pi*data['RAJ2000_group']/180\ndata['DEJ2000_group_rad'] = np.pi*data['DEJ2000_group']/180\n```\n\n\n```python\n\n\nx0 = np.cos(data['DEJ2000_group_rad'])*np.cos(data['RAJ2000_group_rad'])\ny0 = np.cos(data['DEJ2000_group_rad'])*np.sin(data['RAJ2000_group_rad'])\nz0 = np.sin(data['DEJ2000_group_rad'])\n\nx1 = np.cos(data['DEJ2000_gal_rad'])*np.cos(data['RAJ2000_gal_rad'])\ny1 = np.cos(data['DEJ2000_gal_rad'])*np.sin(data['RAJ2000_gal_rad'])\nz1 = np.sin(data['DEJ2000_gal_rad'])\n\ncos_a = x0*x1+y0*y1+z0*z1\n\ntan_a = pd.Series(np.sqrt(1-cos_a**2)/cos_a).fillna(0)\n```\n\n\n```python\ndata['r_pr'] = data['DL']*tan_a\n```\n\n\n```python\ndata['v'] = C*(data['z_gal']-data['z_group'])/(1+data['z_group'])\n```\n\n\n```python\ngalaxydata = data.to_numpy()\n```\n\n\n```python\n# galaxydata\n```\n\n\n```python\n# galaxydata[:,3].mean()\n```\n\n\n```python\nc = Caustic()\ngood_flag = c.run_caustic(galaxydata, \n                          clus_ra=galaxydata[:,3].mean(),\n                          clus_dec=galaxydata[:,4].mean(),\n                          clus_z=galaxydata[:,5].mean())#, r200=0.743, clus_ra=195.095, clus_dec=19.131,clus_z=0.063)\n```\n\n    DATA SET SIZE 43\n    Pre_r200= 0.44956051186426654\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 97.54155922752271\n    Combined Vdisp= 97.54155922752271\n    Calculating initial surface\n    complete\n    r200 estimate:  0.16901661771294996\n    M200 estimate:  587909596836.2314\n\n\n\n```python\nfig, ax = plt.subplots(1, 1, figsize=(7,5))\nx_max = data['r_pr'].max()\ny_max = abs(data['v']).max()\ngr = data\nx = gr['r_pr']\ny = gr['v'] \nax.scatter(x, y, c=gr['iGrID'], marker='*')\nax.plot(c.x_range, c.caustic_profile, c='red')\nax.plot(c.x_range, -c.caustic_profile, c='red')\nax.set_xlabel('Distance from center of the cluster, [Mpc]')\nax.set_ylabel('Relative velocity in the cluster, [km/s]')\n# ax.set_title('iGrID = %d' % (iGrID))\nax.set_ylim(top=y_max*1.1, bottom=-y_max*1.1)\nax.set_xlim((0,10))\nax.grid(True)\n```\n\n\n```python\nfig, ax = plt.subplots(1, 1, figsize=(7,5))\nx_max = data['r_pr'].max()\ny_max = abs(data['v']).max()\ngr = data\nx = gr['r_pr']\ny = gr['v'] \nax.scatter(x, y, c=gr['iGrID'], marker='*')\nax.plot(c.x_range, c.caustic_profile, c='red')\nax.plot(c.x_range, -c.caustic_profile, c='red')\nax.set_xlabel('Distance from center of the cluster, [Mpc]')\nax.set_ylabel('Relative velocity in the cluster, [km/s]')\n# ax.set_title('iGrID = %d' % (iGrID))\nax.set_ylim(top=y_max*1.1, bottom=-y_max*1.1)\nax.set_xlim((0,10))\nax.grid(True)\n```\n\n\n```python\nfrom pylab import *\nplot(c.r,c.v,'o', c='black')\nshow()\n```\n\n\n```python\nplot(data[data['iGrID']==iGrID]['r_pr'],data[data['iGrID']==iGrID]['v'],'o', c='black')\nshow()\n```\n\n\u041f\u043e\u043d\u044f\u0442\u044c \u043a\u0430\u043a \u043e\u043d\u0438 \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u044f\u044e\u0442 \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u044f. \u041e\u0447\u0435\u0432\u0438\u0434\u043d\u043e, \u0447\u0442\u043e \u043d\u0435\u043c\u043d\u043e\u0433\u043e \u043f\u043e-\u0434\u0440\u0443\u0433\u043e\u043c\u0443. \u042d\u0442\u043e \u043c\u043e\u0436\u0435\u0442 \u0431\u044b\u0442\u044c \u043f\u0440\u0438\u0447\u0438\u043d\u043e\u0439 \u0440\u0430\u0437\u043b\u0438\u0447\u0438\u044f \u0432 \u043e\u0446\u0435\u043d\u0435\u043d\u043d\u044b\u0445 \u043c\u0430\u0441\u0441\u0430\u0445 \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0435 \u043a\u0430\u0443\u0441\u0442\u0438\u043a \u0438 Mtot \u0438\u0437 \u0442\u0430\u0431\u043b\u0438\u0446.\n\nTo make two pictures made above look simular we made same changes in the \n- file \"\\__init\\__\"\n- in class Caustic\n- in function run_caustic\n- in function findangle(self,ra,dec,clus_RA,clus_DEC)\n\nBecause with a previous code a projected radius was calculated another way.\n\n\n```python\nm = MassCalc(ri = c.x_range,\n    A = c.caustic_profile,\n    vdisp = c.vdisp_gal,\n    clus_z = galaxydata[:,5].mean(),\n    r200=2.0,\n    conc1=5,\n    beta=0.25,\n    fbr=None,\n    H0=100.0,)\n```\n\n\n```python\ndata[data['iGrID']==iGrID]['sigma'].mean()\n```\n\n\n\n\n    215.73010000000005\n\n\n\n\n```python\nm.M200\n```\n\n\n\n\n    17403720159393.834\n\n\n\n\n```python\n12427715478374.973 # for native radius calculatiouns\n12427715478374.607 # data[data['iGrID']==iGrID]['sigma'].mean()\n12427715478374.607 # for c.vdisp_gal\n```\n\n\n\n\n    12427715478374.607\n\n\n\nLet's put caustic profile onto the galaxy cluster in a phase space\n\n\n```python\nc.caustic_profile.shape\n```\n\n\n\n\n    (120,)\n\n\n\n\n```python\nc.x_range.shape\n```\n\n\n\n\n    (120,)\n\n\n\n\n```python\nfig, ax = plt.subplots(1, 1, figsize=(7,5))\nx_max = data[data['iGrID']==iGrID]['r_pr'].max()\ny_max = abs(data[data['iGrID']==iGrID]['v']).max()\ngr = data[data['iGrID'] == iGrID] \nx = gr['r_pr']\ny = gr['v'] \nax.scatter(x, y, c='blue', marker='*')\nax.plot(c.x_range, c.caustic_profile, c='black')\nax.plot(c.x_range, -c.caustic_profile, c='black')\nax.set_xlabel('Distance from center of the cluster, [Mpc]')\nax.set_ylabel('Relative velocity in the cluster, [km/s]')\nax.set_title('iGrID = %d' % (iGrID))\nax.set_ylim(top=y_max*1.1, bottom=-y_max*1.1)\nax.set_xlim((0,x_max*1.1))\nax.grid(True)\n```\n\n\n```python\nm.M200/np.power(10, data[data['iGrID']==iGrID]['logMtot'])[-1:]\n```\n\n\n\n\n    42    0.329088\n    Name: logMtot, dtype: float64\n\n\n\n\n```python\n# def drawPlot_caustic(data, GrID, ax, color):\n#     x_max = data['r_pr'].max()\n#     y_max = abs(data['v']).max()\n#     gr = data[data['iGrID'] == GrID] \n#     x = gr['r_pr']\n#     y = gr['v'] \n#     ax.scatter(x, y, c=color, marker='*')\n#     ax.plot(c.x_range.shape, c.caustic_profile, c='black')\n#     ax.plot(c.x_range.shape, -c.caustic_profile, c='black')\n#     ax.set_xlabel('Distance from center of the cluster, [Mpc]')\n#     ax.set_ylabel('Relative velocity in the cluster, [km/s]')\n#     ax.set_title('iGrID = %d' % (GrID))\n#     ax.set_ylim(top=y_max, bottom=-y_max)\n#     ax.set_xlim((0,x_max))\n#     ax.grid(True)\n\n```\n\n\n```python\n# fig, axs = plt.subplots(7, 3, figsize=(15,25))\n# GrIDs = data['iGrID'].unique() #\u0421\u043e\u0437\u0434\u0430\u0451\u043c \u0432\u0435\u043a\u0442\u043e\u0440 \u0432\u0441\u0435\u0445 \u0433\u0440\u0443\u043f\u043f\n# for i in range(21):\n#     drawPlot_caustic(data, GrIDs[i], axs[i//3, i%3], 'blue') #\u0414\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0439 \u0433\u0440\u0443\u043f\u043f\u044b \u0432\u044b\u0437\u044b\u0432\u0430\u0435\u043c \u0444\u0443\u043d\u043a\u0446\u0438\u044e \u0438 \u043f\u0435\u0440\u0435\u0434\u0430\u0451\u043c \u0435\u0439 \u043d\u0443\u0436\u043d\u044b\u0439 '\u043f\u043e\u0434\u0433\u0440\u0430\u0444\u0438\u043a'\n# plt.tight_layout()\n```\n\n\n```python\nfor iGrID in data['iGrID'].unique():\n\n    galaxydata = (data[data['iGrID']==iGrID][['RAJ2000_gal', 'DEJ2000_gal', 'z_gal', \n                                          'RAJ2000_group', 'DEJ2000_group', 'z_group']]).to_numpy()\n\n    c = Caustic()\n    good_flag = c.run_caustic(galaxydata, \n                          clus_ra=galaxydata[:,3].mean(),\n                          clus_dec=galaxydata[:,4].mean(),\n                          clus_z=galaxydata[:,5].mean()) #, r200=0.743, clus_ra=195.095, \n                                                        #clus_dec=19.131,clus_z=0.063\n\n    m = MassCalc(ri = c.x_range,\n                A = c.caustic_profile,\n                vdisp = c.vdisp_gal,\n                clus_z = galaxydata[:,5].mean(),\n                r200=2.5,\n                conc1=5,\n                beta=0.25,\n                fbr=None,\n                H0=73,)\n    for i in data[data['iGrID']==iGrID].index:\n        data.loc[i, 'M200'] = m.M200\n```\n\n    DATA SET SIZE 43\n    Pre_r200= 0.35374227608257586\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 118.4137724813458\n    Combined Vdisp= 118.4137724813458\n    Calculating initial surface\n    complete\n    r200 estimate:  0.2338076934627482\n    M200 estimate:  1550714469573.0642\n    DATA SET SIZE 205\n    Pre_r200= 0.6798314334871322\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 744.170128332981\n    Combined Vdisp= 744.170128332981\n    Calculating initial surface\n    complete\n    r200 estimate:  1.5979078856549322\n    M200 estimate:  507194570879603.3\n    DATA SET SIZE 40\n    Pre_r200= 0.7173606684728591\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 281.107133783919\n    Combined Vdisp= 281.107133783919\n    Calculating initial surface\n    complete\n    r200 estimate:  0.5849161329127088\n    M200 estimate:  24718592905296.79\n    DATA SET SIZE 31\n    Pre_r200= 0.5758685663785436\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 280.4271572873902\n    Combined Vdisp= 280.4271572873902\n    Calculating initial surface\n    complete\n    r200 estimate:  0.5686943037020485\n    M200 estimate:  22739530261437.12\n    DATA SET SIZE 66\n    Pre_r200= 0.9543044880057066\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 913.007041570078\n    Combined Vdisp= 913.007041570078\n    Calculating initial surface\n    complete\n    r200 estimate:  1.7228561392588617\n    M200 estimate:  638592111591100.2\n    DATA SET SIZE 34\n    Pre_r200= 0.5288378526323049\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 359.20688021497773\n    Combined Vdisp= 359.20688021497773\n    Calculating initial surface\n    complete\n    r200 estimate:  0.8048584217703311\n    M200 estimate:  65243641933732.78\n    DATA SET SIZE 31\n    Pre_r200= 0.6401967348530284\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 433.7597912711197\n    Combined Vdisp= 433.7597912711197\n    Calculating initial surface\n    complete\n    r200 estimate:  0.9208674248066417\n    M200 estimate:  97242516023380.22\n    DATA SET SIZE 35\n    Pre_r200= 0.61946789863605\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 464.3876364738075\n    Combined Vdisp= 464.3876364738075\n    Calculating initial surface\n    complete\n    r200 estimate:  0.935861084666734\n    M200 estimate:  102537029110083.88\n    DATA SET SIZE 39\n    Pre_r200= 0.8200657445895702\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 527.2768546516704\n    Combined Vdisp= 527.2768546516704\n    Calculating initial surface\n    complete\n    r200 estimate:  0.9734900249535211\n    M200 estimate:  114751484669260.66\n    DATA SET SIZE 38\n    Pre_r200= 0.6401967348530284\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 537.3159524109603\n    Combined Vdisp= 537.3159524109603\n    Calculating initial surface\n    complete\n    r200 estimate:  0.9745336967772709\n    M200 estimate:  115586433982072.28\n    DATA SET SIZE 104\n    Pre_r200= 0.98173696340138\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 884.368394754098\n    Combined Vdisp= 884.368394754098\n    Calculating initial surface\n    complete\n    r200 estimate:  1.5881304982780433\n    M200 estimate:  502011112371446.2\n    DATA SET SIZE 99\n    Pre_r200= 1.1563067303060888\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 1082.3716775371581\n    Combined Vdisp= 1082.3716775371581\n    Calculating initial surface\n    complete\n    r200 estimate:  1.832805080486725\n    M200 estimate:  771814216063607.5\n    DATA SET SIZE 76\n    Pre_r200= 0.9260925126542184\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 715.3012356521505\n    Combined Vdisp= 715.3012356521505\n    Calculating initial surface\n    complete\n    r200 estimate:  1.357070160707917\n    M200 estimate:  312410446603144.3\n    DATA SET SIZE 35\n    Pre_r200= 0.6988381416127446\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 578.7349716292651\n    Combined Vdisp= 578.7349716292651\n    Calculating initial surface\n    complete\n    r200 estimate:  1.1289366597617534\n    M200 estimate:  179915771098599.0\n    DATA SET SIZE 34\n    Pre_r200= 0.5980500924528229\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 411.52680635685306\n    Combined Vdisp= 411.52680635685306\n    Calculating initial surface\n    complete\n    r200 estimate:  0.806534667714553\n    M200 estimate:  65692124929959.78\n    DATA SET SIZE 39\n    Pre_r200= 0.6401967348530284\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 423.31257548234356\n    Combined Vdisp= 423.31257548234356\n    Calculating initial surface\n    complete\n    r200 estimate:  0.9644649534128976\n    M200 estimate:  112371787254418.25\n    DATA SET SIZE 82\n    Pre_r200= 0.8670322317530142\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 1119.5492632423875\n    Combined Vdisp= 1119.5492632423875\n    Calculating initial surface\n    complete\n    r200 estimate:  1.914378935849855\n    M200 estimate:  884495679622821.2\n    DATA SET SIZE 54\n    Pre_r200= 0.6988381416127446\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 492.86208239395\n    Combined Vdisp= 492.86208239395\n    Calculating initial surface\n    complete\n    r200 estimate:  1.0504520782496083\n    M200 estimate:  145254626979393.03\n    DATA SET SIZE 33\n    Pre_r200= 0.5758685663785436\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 770.0063935000467\n    Combined Vdisp= 770.0063935000467\n    Calculating initial surface\n    complete\n    r200 estimate:  1.540922594167981\n    M200 estimate:  463160078687338.6\n    DATA SET SIZE 47\n    Pre_r200= 0.7354346773940376\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 508.6717666224595\n    Combined Vdisp= 508.6717666224595\n    Calculating initial surface\n    complete\n    r200 estimate:  1.1106625048574335\n    M200 estimate:  172446341455641.94\n    DATA SET SIZE 32\n    Pre_r200= 0.5980500924528229\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 427.1985483226475\n    Combined Vdisp= 427.1985483226475\n    Calculating initial surface\n    complete\n    r200 estimate:  0.9005681752128453\n    M200 estimate:  92097474027556.7\n\n\n\n```python\n# data\n```\n\n\n```python\nnp.array(data['iGrID'].unique())\n```\n\n\n\n\n    array([   6,    8,   10,   47,   91,  157,  179,  277,  279,  293,  298,\n            344,  354,  387,  396,  400,  442,  539,  732, 1007, 1069])\n\n\n\n\n```python\nfig, ax = plt.subplots(1, 1, figsize=(12,7))\ndata.sort_values(by='Ntot', ascending=True, inplace=True)\nax.plot([i for i in range(len(data['iGrID'].unique()))], np.array(data['M200'].unique()), marker='*', label='M200')\nax.plot([i for i in range(len(data['iGrID'].unique()))], np.array(np.power(10, data['logMtot'].unique())), marker='*', label='Mtot')\n# ax.set_xlabel('Distance from center of the cluster, [Mpc]')\nax.set_ylabel('Estimated mass, [M_sol]')\nax.legend()\n# ax.set_title('iGrID = %d' % (iGrID))\n\nax.grid(True)\n```\n\n\n```python\n(data['M200']/np.power(10, data['logMtot'])).describe()\n```\n\n\n\n\n    count    1200.000000\n    mean        0.850548\n    std         0.297530\n    min         0.368063\n    25%         0.638311\n    50%         0.804982\n    75%         1.071443\n    max         1.636950\n    dtype: float64\n\n\n\n\n```python\npip install tqdm\n```\n\n    Defaulting to user installation because normal site-packages is not writeable\n    Collecting tqdm\n      Downloading tqdm-4.43.0-py2.py3-none-any.whl (59 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 59 kB 1.4 MB/s eta 0:00:011\n    \u001b[?25hInstalling collected packages: tqdm\n    Successfully installed tqdm-4.43.0\n    Note: you may need to restart the kernel to use updated packages.\n\n\n\n```python\nfrom tqdm import tqdm\nfor i in tqdm(range(100)):\n    pd.read_csv('glist_s.csv')\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 100/100 [00:11<00:00,  8.88it/s]\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "cd805102497aa08808771263d3d228a96a49581b", "size": 206408, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "caustics/Galaxy_data_preparing.ipynb", "max_stars_repo_name": "Azarodnyuk/galaxymass", "max_stars_repo_head_hexsha": "cee5f9dc05b5675d0a3a0de111d18c24f057f6a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-09T13:05:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-09T13:05:02.000Z", "max_issues_repo_path": "caustics/Galaxy_data_preparing.ipynb", "max_issues_repo_name": "Azarodnyuk/galaxymass", "max_issues_repo_head_hexsha": "cee5f9dc05b5675d0a3a0de111d18c24f057f6a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "caustics/Galaxy_data_preparing.ipynb", "max_forks_repo_name": "Azarodnyuk/galaxymass", "max_forks_repo_head_hexsha": "cee5f9dc05b5675d0a3a0de111d18c24f057f6a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 159.5115919629, "max_line_length": 53740, "alphanum_fraction": 0.8881341808, "converted": true, "num_tokens": 8954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.04208772626352764, "lm_q1q2_score": 0.018265293094111238}}
{"text": "```python\n%env QXToken=5cd4fb14ed1e310399096fe9bd62d528d5999de11ad231bf5e0ca742f7a4e3dd0960a5ddcde760edfbda609b5411e036f45965998ec4993e6336d7b2ed414701\n%env QC_GRADING_ENDPOINT=https://qac-grading.quantum-computing.ibm.com\n%env QXAuthURL=https://auth.quantum-computing.ibm.com/api\n\n```\n\n    env: QXToken=5cd4fb14ed1e310399096fe9bd62d528d5999de11ad231bf5e0ca742f7a4e3dd0960a5ddcde760edfbda609b5411e036f45965998ec4993e6336d7b2ed414701\n    env: QC_GRADING_ENDPOINT=https://qac-grading.quantum-computing.ibm.com\n    env: QXAuthURL=https://auth.quantum-computing.ibm.com/api\n\n\n\n```python\nimport os\n# verify enviroment setting\nprint((os.environ['QXToken'],\nos.environ['QC_GRADING_ENDPOINT'],\nos.environ['QXAuthURL']))\n```\n\n    ('5cd4fb14ed1e310399096fe9bd62d528d5999de11ad231bf5e0ca742f7a4e3dd0960a5ddcde760edfbda609b5411e036f45965998ec4993e6336d7b2ed414701', 'https://qac-grading.quantum-computing.ibm.com', 'https://auth.quantum-computing.ibm.com/api')\n\n\n\n```python\n!pip install --upgrade git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git --user\n!pip install qiskit[all]\n```\n\n    Collecting git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git\n      Cloning https://github.com/qiskit-community/Quantum-Challenge-Grader.git to c:\\users\\sun\\appdata\\local\\temp\\pip-req-build-xkjr_296\n    Requirement already satisfied: numpy in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qc-grader==0.8.7) (1.20.1)\n    Requirement already satisfied: qiskit>=0.25 in e:\\anaconda\\lib\\site-packages (from qc-grader==0.8.7) (0.26.0)\n    Requirement already satisfied: requests in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qc-grader==0.8.7) (2.26.0)\n    Requirement already satisfied: networkx in e:\\anaconda\\lib\\site-packages (from qc-grader==0.8.7) (2.5.1)\n    Requirement already satisfied: ipycytoscape in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qc-grader==0.8.7) (1.2.2)\n    Requirement already satisfied: plotly in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qc-grader==0.8.7) (5.3.1)\n    Requirement already satisfied: jsonpickle in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qc-grader==0.8.7) (2.0.0)\n    Requirement already satisfied: typeguard in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qc-grader==0.8.7) (2.13.0)\n    Requirement already satisfied: jupyterplot in e:\\anaconda\\lib\\site-packages (from qc-grader==0.8.7) (0.0.3)\n    Requirement already satisfied: qiskit-ibmq-provider==0.13.1 in e:\\anaconda\\lib\\site-packages (from qiskit>=0.25->qc-grader==0.8.7) (0.13.1)\n    Requirement already satisfied: qiskit-terra==0.17.3 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit>=0.25->qc-grader==0.8.7) (0.17.3)\n    Requirement already satisfied: qiskit-aqua==0.9.1 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit>=0.25->qc-grader==0.8.7) (0.9.1)\n    Requirement already satisfied: qiskit-ignis==0.6.0 in e:\\anaconda\\lib\\site-packages (from qiskit>=0.25->qc-grader==0.8.7) (0.6.0)\n    Requirement already satisfied: qiskit-aer==0.8.2 in e:\\anaconda\\lib\\site-packages (from qiskit>=0.25->qc-grader==0.8.7) (0.8.2)\n    Requirement already satisfied: scipy>=1.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-aer==0.8.2->qiskit>=0.25->qc-grader==0.8.7) (1.6.1)\n    Requirement already satisfied: pybind11>=2.6 in e:\\anaconda\\lib\\site-packages (from qiskit-aer==0.8.2->qiskit>=0.25->qc-grader==0.8.7) (2.6.2)\n    Requirement already satisfied: pandas<=1.2.3 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-aqua==0.9.1->qiskit>=0.25->qc-grader==0.8.7) (1.2.3)\n    Requirement already satisfied: quandl<=3.6.0 in e:\\anaconda\\lib\\site-packages (from qiskit-aqua==0.9.1->qiskit>=0.25->qc-grader==0.8.7) (3.6.0)\n    Requirement already satisfied: setuptools>=40.1.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-aqua==0.9.1->qiskit>=0.25->qc-grader==0.8.7) (58.5.2)\n    Requirement already satisfied: yfinance<=0.1.55 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-aqua==0.9.1->qiskit>=0.25->qc-grader==0.8.7) (0.1.55)\n    Requirement already satisfied: docplex<=2.20.204 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-aqua==0.9.1->qiskit>=0.25->qc-grader==0.8.7) (2.20.204)\n    Requirement already satisfied: sympy<=1.7.1,>=1.3 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-aqua==0.9.1->qiskit>=0.25->qc-grader==0.8.7) (1.7.1)\n    Requirement already satisfied: h5py<=3.1.0 in e:\\anaconda\\lib\\site-packages (from qiskit-aqua==0.9.1->qiskit>=0.25->qc-grader==0.8.7) (2.10.0)\n    Requirement already satisfied: dlx<=1.0.4 in e:\\anaconda\\lib\\site-packages (from qiskit-aqua==0.9.1->qiskit>=0.25->qc-grader==0.8.7) (1.0.4)\n    Requirement already satisfied: retworkx<=0.8.0,>=0.7.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-aqua==0.9.1->qiskit>=0.25->qc-grader==0.8.7) (0.8.0)\n    Requirement already satisfied: fastdtw<=0.3.4 in e:\\anaconda\\lib\\site-packages (from qiskit-aqua==0.9.1->qiskit>=0.25->qc-grader==0.8.7) (0.3.4)\n    Requirement already satisfied: scikit-learn<=0.24.1,>=0.20.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-aqua==0.9.1->qiskit>=0.25->qc-grader==0.8.7) (0.24.1)\n    Requirement already satisfied: psutil<=5.8.0,>=5 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-aqua==0.9.1->qiskit>=0.25->qc-grader==0.8.7) (5.8.0)\n    Requirement already satisfied: urllib3>=1.21.1 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-ibmq-provider==0.13.1->qiskit>=0.25->qc-grader==0.8.7) (1.26.7)\n    Requirement already satisfied: python-dateutil>=2.8.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-ibmq-provider==0.13.1->qiskit>=0.25->qc-grader==0.8.7) (2.8.2)\n    Requirement already satisfied: nest-asyncio!=1.1.0,>=1.0.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-ibmq-provider==0.13.1->qiskit>=0.25->qc-grader==0.8.7) (1.5.1)\n    Requirement already satisfied: dill>=0.3 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-ibmq-provider==0.13.1->qiskit>=0.25->qc-grader==0.8.7) (0.3.4)\n    Requirement already satisfied: websockets>=8 in e:\\anaconda\\lib\\site-packages (from qiskit-ibmq-provider==0.13.1->qiskit>=0.25->qc-grader==0.8.7) (9.0.1)\n    Requirement already satisfied: requests-ntlm>=1.1.0 in e:\\anaconda\\lib\\site-packages (from qiskit-ibmq-provider==0.13.1->qiskit>=0.25->qc-grader==0.8.7) (1.1.0)\n    Requirement already satisfied: jsonschema>=2.6 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-terra==0.17.3->qiskit>=0.25->qc-grader==0.8.7) (4.2.0)\n    Requirement already satisfied: fastjsonschema>=2.10 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-terra==0.17.3->qiskit>=0.25->qc-grader==0.8.7) (2.15.1)\n    Requirement already satisfied: python-constraint>=1.4 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-terra==0.17.3->qiskit>=0.25->qc-grader==0.8.7) (1.4.0)\n    Requirement already satisfied: ply>=3.10 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-terra==0.17.3->qiskit>=0.25->qc-grader==0.8.7) (3.11)\n    Requirement already satisfied: six in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from docplex<=2.20.204->qiskit-aqua==0.9.1->qiskit>=0.25->qc-grader==0.8.7) (1.16.0)\n    Requirement already satisfied: importlib-resources in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from jsonschema>=2.6->qiskit-terra==0.17.3->qiskit>=0.25->qc-grader==0.8.7) (5.4.0)\n    Requirement already satisfied: attrs>=17.4.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from jsonschema>=2.6->qiskit-terra==0.17.3->qiskit>=0.25->qc-grader==0.8.7) (21.2.0)\n    Requirement already satisfied: pyrsistent!=0.17.0,!=0.17.1,!=0.17.2,>=0.14.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from jsonschema>=2.6->qiskit-terra==0.17.3->qiskit>=0.25->qc-grader==0.8.7) (0.18.0)\n    Requirement already satisfied: pytz>=2017.3 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from pandas<=1.2.3->qiskit-aqua==0.9.1->qiskit>=0.25->qc-grader==0.8.7) (2021.3)\n    Requirement already satisfied: inflection>=0.3.1 in e:\\anaconda\\lib\\site-packages (from quandl<=3.6.0->qiskit-aqua==0.9.1->qiskit>=0.25->qc-grader==0.8.7) (0.5.1)\n    Requirement already satisfied: more-itertools in e:\\anaconda\\lib\\site-packages (from quandl<=3.6.0->qiskit-aqua==0.9.1->qiskit>=0.25->qc-grader==0.8.7) (8.8.0)\n    Requirement already satisfied: charset-normalizer~=2.0.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from requests->qc-grader==0.8.7) (2.0.7)\n    Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from requests->qc-grader==0.8.7) (2021.10.8)\n    Requirement already satisfied: idna<4,>=2.5 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from requests->qc-grader==0.8.7) (3.3)\n    Requirement already satisfied: ntlm-auth>=1.0.2 in e:\\anaconda\\lib\\site-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit>=0.25->qc-grader==0.8.7) (1.5.0)\n    Requirement already satisfied: cryptography>=1.3 in e:\\anaconda\\lib\\site-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit>=0.25->qc-grader==0.8.7) (3.4.7)\n    Requirement already satisfied: cffi>=1.12 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit>=0.25->qc-grader==0.8.7) (1.15.0)\n    Requirement already satisfied: pycparser in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit>=0.25->qc-grader==0.8.7) (2.20)\n    Requirement already satisfied: joblib>=0.11 in e:\\anaconda\\lib\\site-packages (from scikit-learn<=0.24.1,>=0.20.0->qiskit-aqua==0.9.1->qiskit>=0.25->qc-grader==0.8.7) (1.0.1)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from scikit-learn<=0.24.1,>=0.20.0->qiskit-aqua==0.9.1->qiskit>=0.25->qc-grader==0.8.7) (3.0.0)\n    Requirement already satisfied: mpmath>=0.19 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from sympy<=1.7.1,>=1.3->qiskit-aqua==0.9.1->qiskit>=0.25->qc-grader==0.8.7) (1.2.1)\n    Requirement already satisfied: lxml>=4.5.1 in e:\\anaconda\\lib\\site-packages (from yfinance<=0.1.55->qiskit-aqua==0.9.1->qiskit>=0.25->qc-grader==0.8.7) (4.6.3)\n    Requirement already satisfied: multitasking>=0.0.7 in e:\\anaconda\\lib\\site-packages (from yfinance<=0.1.55->qiskit-aqua==0.9.1->qiskit>=0.25->qc-grader==0.8.7) (0.0.9)\n    Requirement already satisfied: zipp>=3.1.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from importlib-resources->jsonschema>=2.6->qiskit-terra==0.17.3->qiskit>=0.25->qc-grader==0.8.7) (3.6.0)\n    Requirement already satisfied: spectate>=1.0.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipycytoscape->qc-grader==0.8.7) (1.0.1)\n    Requirement already satisfied: ipywidgets>=7.6.0 in e:\\anaconda\\lib\\site-packages (from ipycytoscape->qc-grader==0.8.7) (7.6.4)\n    Requirement already satisfied: nbformat>=4.2.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (5.1.3)\n    Requirement already satisfied: jupyterlab-widgets>=1.0.0 in e:\\anaconda\\lib\\site-packages (from ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (1.0.0)\n    Requirement already satisfied: traitlets>=4.3.1 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (5.1.1)\n    Requirement already satisfied: widgetsnbextension~=3.5.0 in e:\\anaconda\\lib\\site-packages (from ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (3.5.1)\n    Requirement already satisfied: ipython>=4.0.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (7.29.0)\n    Requirement already satisfied: ipython-genutils~=0.2.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (0.2.0)\n    Requirement already satisfied: ipykernel>=4.5.1 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (6.5.0)\n    Requirement already satisfied: jupyter-client<8.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipykernel>=4.5.1->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (7.0.6)\n    Requirement already satisfied: debugpy<2.0,>=1.0.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipykernel>=4.5.1->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (1.5.1)\n    Requirement already satisfied: tornado<7.0,>=4.2 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipykernel>=4.5.1->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (6.1)\n    Requirement already satisfied: matplotlib-inline<0.2.0,>=0.1.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipykernel>=4.5.1->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (0.1.3)\n    Requirement already satisfied: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipython>=4.0.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (3.0.22)\n    Requirement already satisfied: colorama in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipython>=4.0.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (0.4.4)\n    Requirement already satisfied: backcall in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipython>=4.0.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (0.2.0)\n    Requirement already satisfied: pickleshare in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipython>=4.0.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (0.7.5)\n    Requirement already satisfied: decorator in e:\\anaconda\\lib\\site-packages (from ipython>=4.0.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (4.4.2)\n    Requirement already satisfied: jedi>=0.16 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipython>=4.0.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (0.18.0)\n    Requirement already satisfied: pygments in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipython>=4.0.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (2.10.0)\n    Requirement already satisfied: parso<0.9.0,>=0.8.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from jedi>=0.16->ipython>=4.0.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (0.8.2)\n    Requirement already satisfied: pyzmq>=13 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from jupyter-client<8.0->ipykernel>=4.5.1->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (22.3.0)\n    Requirement already satisfied: entrypoints in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from jupyter-client<8.0->ipykernel>=4.5.1->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (0.3)\n    Requirement already satisfied: jupyter-core>=4.6.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from jupyter-client<8.0->ipykernel>=4.5.1->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (4.9.1)\n    Requirement already satisfied: pywin32>=1.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from jupyter-core>=4.6.0->jupyter-client<8.0->ipykernel>=4.5.1->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (302)\n    Requirement already satisfied: wcwidth in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->ipython>=4.0.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (0.2.5)\n    Requirement already satisfied: notebook>=4.4.1 in e:\\anaconda\\lib\\site-packages (from widgetsnbextension~=3.5.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (6.4.3)\n    Requirement already satisfied: prometheus-client in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (0.12.0)\n    Requirement already satisfied: argon2-cffi in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (21.1.0)\n    Requirement already satisfied: jinja2 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (3.0.2)\n    Requirement already satisfied: Send2Trash>=1.5.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (1.8.0)\n    Requirement already satisfied: terminado>=0.8.3 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (0.12.1)\n    Requirement already satisfied: nbconvert in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (6.2.0)\n    Requirement already satisfied: pywinpty>=1.1.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from terminado>=0.8.3->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (1.1.5)\n    Requirement already satisfied: MarkupSafe>=2.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from jinja2->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (2.0.1)\n    Requirement already satisfied: matplotlib in e:\\anaconda\\lib\\site-packages (from jupyterplot->qc-grader==0.8.7) (3.4.2)\n    Requirement already satisfied: lrcurve==1.1.0 in e:\\anaconda\\lib\\site-packages (from jupyterplot->qc-grader==0.8.7) (1.1.0)\n    Requirement already satisfied: pillow>=6.2.0 in e:\\anaconda\\lib\\site-packages (from matplotlib->jupyterplot->qc-grader==0.8.7) (8.3.1)\n    Requirement already satisfied: kiwisolver>=1.0.1 in e:\\anaconda\\lib\\site-packages (from matplotlib->jupyterplot->qc-grader==0.8.7) (1.3.1)\n    Requirement already satisfied: pyparsing>=2.2.1 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from matplotlib->jupyterplot->qc-grader==0.8.7) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in e:\\anaconda\\lib\\site-packages (from matplotlib->jupyterplot->qc-grader==0.8.7) (0.10.0)\n    Requirement already satisfied: defusedxml in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (0.7.1)\n    Requirement already satisfied: pandocfilters>=1.4.1 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (1.5.0)\n    Requirement already satisfied: jupyterlab-pygments in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (0.1.2)\n    Requirement already satisfied: testpath in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (0.5.0)\n    Requirement already satisfied: mistune<2,>=0.8.1 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (0.8.4)\n    Requirement already satisfied: bleach in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (4.1.0)\n    Requirement already satisfied: nbclient<0.6.0,>=0.5.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (0.5.4)\n    Requirement already satisfied: webencodings in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (0.5.1)\n    Requirement already satisfied: packaging in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.6.0->ipycytoscape->qc-grader==0.8.7) (21.2)\n    Requirement already satisfied: tenacity>=6.2.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from plotly->qc-grader==0.8.7) (8.0.1)\n\n\n      Running command git clone -q https://github.com/qiskit-community/Quantum-Challenge-Grader.git 'C:\\Users\\sun\\AppData\\Local\\Temp\\pip-req-build-xkjr_296'\n\n\n    Requirement already satisfied: qiskit[all] in e:\\anaconda\\lib\\site-packages (0.26.0)\n    Requirement already satisfied: qiskit-ignis==0.6.0 in e:\\anaconda\\lib\\site-packages (from qiskit[all]) (0.6.0)\n    Requirement already satisfied: qiskit-terra==0.17.3 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit[all]) (0.17.3)\n    Requirement already satisfied: qiskit-aqua==0.9.1 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit[all]) (0.9.1)\n    Requirement already satisfied: qiskit-ibmq-provider==0.13.1 in e:\\anaconda\\lib\\site-packages (from qiskit[all]) (0.13.1)\n    Requirement already satisfied: qiskit-aer==0.8.2 in e:\\anaconda\\lib\\site-packages (from qiskit[all]) (0.8.2)\n    Collecting qiskit-machine-learning==0.1.0\n      Downloading qiskit_machine_learning-0.1.0-py3-none-any.whl (84 kB)\n    Requirement already satisfied: pylatexenc>=1.4 in e:\\anaconda\\lib\\site-packages (from qiskit[all]) (2.10)\n    Collecting qiskit-optimization==0.1.0\n      Using cached qiskit_optimization-0.1.0-py3-none-any.whl (115 kB)\n    Requirement already satisfied: pydot in e:\\anaconda\\lib\\site-packages (from qiskit[all]) (1.4.2)\n    Collecting qiskit-nature==0.1.2\n      Downloading qiskit_nature-0.1.2-py3-none-any.whl (1.5 MB)\n    Requirement already satisfied: matplotlib>=2.1 in e:\\anaconda\\lib\\site-packages (from qiskit[all]) (3.4.2)\n    Requirement already satisfied: ipywidgets>=7.3.0 in e:\\anaconda\\lib\\site-packages (from qiskit[all]) (7.6.4)\n    Requirement already satisfied: pygments>=2.4 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit[all]) (2.10.0)\n    Requirement already satisfied: pillow>=4.2.1 in e:\\anaconda\\lib\\site-packages (from qiskit[all]) (8.3.1)\n    Collecting qiskit-finance==0.1.0\n      Downloading qiskit_finance-0.1.0-py3-none-any.whl (47 kB)\n    Requirement already satisfied: seaborn>=0.9.0 in e:\\anaconda\\lib\\site-packages (from qiskit[all]) (0.11.0)\n    Requirement already satisfied: pybind11>=2.6 in e:\\anaconda\\lib\\site-packages (from qiskit-aer==0.8.2->qiskit[all]) (2.6.2)\n    Requirement already satisfied: numpy>=1.16.3 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-aer==0.8.2->qiskit[all]) (1.20.1)\n    Requirement already satisfied: scipy>=1.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-aer==0.8.2->qiskit[all]) (1.6.1)\n    Requirement already satisfied: fastdtw<=0.3.4 in e:\\anaconda\\lib\\site-packages (from qiskit-aqua==0.9.1->qiskit[all]) (0.3.4)\n    Requirement already satisfied: docplex<=2.20.204 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-aqua==0.9.1->qiskit[all]) (2.20.204)\n    Requirement already satisfied: scikit-learn<=0.24.1,>=0.20.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-aqua==0.9.1->qiskit[all]) (0.24.1)\n    Requirement already satisfied: psutil<=5.8.0,>=5 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-aqua==0.9.1->qiskit[all]) (5.8.0)\n    Requirement already satisfied: yfinance<=0.1.55 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-aqua==0.9.1->qiskit[all]) (0.1.55)\n    Requirement already satisfied: setuptools>=40.1.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-aqua==0.9.1->qiskit[all]) (58.5.2)\n    Requirement already satisfied: dlx<=1.0.4 in e:\\anaconda\\lib\\site-packages (from qiskit-aqua==0.9.1->qiskit[all]) (1.0.4)\n    Requirement already satisfied: retworkx<=0.8.0,>=0.7.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-aqua==0.9.1->qiskit[all]) (0.8.0)\n    Requirement already satisfied: sympy<=1.7.1,>=1.3 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-aqua==0.9.1->qiskit[all]) (1.7.1)\n    Requirement already satisfied: quandl<=3.6.0 in e:\\anaconda\\lib\\site-packages (from qiskit-aqua==0.9.1->qiskit[all]) (3.6.0)\n    Requirement already satisfied: pandas<=1.2.3 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-aqua==0.9.1->qiskit[all]) (1.2.3)\n    Requirement already satisfied: h5py<=3.1.0 in e:\\anaconda\\lib\\site-packages (from qiskit-aqua==0.9.1->qiskit[all]) (2.10.0)\n    Requirement already satisfied: nest-asyncio!=1.1.0,>=1.0.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-ibmq-provider==0.13.1->qiskit[all]) (1.5.1)\n    Requirement already satisfied: websockets>=8 in e:\\anaconda\\lib\\site-packages (from qiskit-ibmq-provider==0.13.1->qiskit[all]) (9.0.1)\n    Requirement already satisfied: dill>=0.3 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-ibmq-provider==0.13.1->qiskit[all]) (0.3.4)\n    Requirement already satisfied: requests>=2.19 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-ibmq-provider==0.13.1->qiskit[all]) (2.26.0)\n    Requirement already satisfied: requests-ntlm>=1.1.0 in e:\\anaconda\\lib\\site-packages (from qiskit-ibmq-provider==0.13.1->qiskit[all]) (1.1.0)\n    Requirement already satisfied: python-dateutil>=2.8.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-ibmq-provider==0.13.1->qiskit[all]) (2.8.2)\n    Requirement already satisfied: urllib3>=1.21.1 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-ibmq-provider==0.13.1->qiskit[all]) (1.26.7)\n    Collecting sparse\n      Downloading sparse-0.13.0-py2.py3-none-any.whl (77 kB)\n    Requirement already satisfied: networkx>=2.2 in e:\\anaconda\\lib\\site-packages (from qiskit-optimization==0.1.0->qiskit[all]) (2.5.1)\n    Requirement already satisfied: python-constraint>=1.4 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-terra==0.17.3->qiskit[all]) (1.4.0)\n    Requirement already satisfied: ply>=3.10 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-terra==0.17.3->qiskit[all]) (3.11)\n    Requirement already satisfied: fastjsonschema>=2.10 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-terra==0.17.3->qiskit[all]) (2.15.1)\n    Requirement already satisfied: jsonschema>=2.6 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from qiskit-terra==0.17.3->qiskit[all]) (4.2.0)\n    Requirement already satisfied: six in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from docplex<=2.20.204->qiskit-aqua==0.9.1->qiskit[all]) (1.16.0)\n    Requirement already satisfied: ipykernel>=4.5.1 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipywidgets>=7.3.0->qiskit[all]) (6.5.0)\n    Requirement already satisfied: nbformat>=4.2.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipywidgets>=7.3.0->qiskit[all]) (5.1.3)\n    Requirement already satisfied: jupyterlab-widgets>=1.0.0 in e:\\anaconda\\lib\\site-packages (from ipywidgets>=7.3.0->qiskit[all]) (1.0.0)\n    Requirement already satisfied: ipython-genutils~=0.2.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipywidgets>=7.3.0->qiskit[all]) (0.2.0)\n    Requirement already satisfied: ipython>=4.0.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipywidgets>=7.3.0->qiskit[all]) (7.29.0)\n    Requirement already satisfied: widgetsnbextension~=3.5.0 in e:\\anaconda\\lib\\site-packages (from ipywidgets>=7.3.0->qiskit[all]) (3.5.1)\n    Requirement already satisfied: traitlets>=4.3.1 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipywidgets>=7.3.0->qiskit[all]) (5.1.1)\n    Requirement already satisfied: matplotlib-inline<0.2.0,>=0.1.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipykernel>=4.5.1->ipywidgets>=7.3.0->qiskit[all]) (0.1.3)\n    Requirement already satisfied: tornado<7.0,>=4.2 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipykernel>=4.5.1->ipywidgets>=7.3.0->qiskit[all]) (6.1)\n    Requirement already satisfied: jupyter-client<8.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipykernel>=4.5.1->ipywidgets>=7.3.0->qiskit[all]) (7.0.6)\n    Requirement already satisfied: debugpy<2.0,>=1.0.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipykernel>=4.5.1->ipywidgets>=7.3.0->qiskit[all]) (1.5.1)\n    Requirement already satisfied: pickleshare in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[all]) (0.7.5)\n    Requirement already satisfied: colorama in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[all]) (0.4.4)\n    Requirement already satisfied: jedi>=0.16 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[all]) (0.18.0)\n    Requirement already satisfied: backcall in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[all]) (0.2.0)\n    Requirement already satisfied: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[all]) (3.0.22)\n    Requirement already satisfied: decorator in e:\\anaconda\\lib\\site-packages (from ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[all]) (4.4.2)\n    Requirement already satisfied: parso<0.9.0,>=0.8.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from jedi>=0.16->ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[all]) (0.8.2)\n    Requirement already satisfied: importlib-resources in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from jsonschema>=2.6->qiskit-terra==0.17.3->qiskit[all]) (5.4.0)\n    Requirement already satisfied: pyrsistent!=0.17.0,!=0.17.1,!=0.17.2,>=0.14.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from jsonschema>=2.6->qiskit-terra==0.17.3->qiskit[all]) (0.18.0)\n    Requirement already satisfied: attrs>=17.4.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from jsonschema>=2.6->qiskit-terra==0.17.3->qiskit[all]) (21.2.0)\n    Requirement already satisfied: pyzmq>=13 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from jupyter-client<8.0->ipykernel>=4.5.1->ipywidgets>=7.3.0->qiskit[all]) (22.3.0)\n    Requirement already satisfied: jupyter-core>=4.6.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from jupyter-client<8.0->ipykernel>=4.5.1->ipywidgets>=7.3.0->qiskit[all]) (4.9.1)\n    Requirement already satisfied: entrypoints in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from jupyter-client<8.0->ipykernel>=4.5.1->ipywidgets>=7.3.0->qiskit[all]) (0.3)\n    Requirement already satisfied: pywin32>=1.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from jupyter-core>=4.6.0->jupyter-client<8.0->ipykernel>=4.5.1->ipywidgets>=7.3.0->qiskit[all]) (302)\n    Requirement already satisfied: cycler>=0.10 in e:\\anaconda\\lib\\site-packages (from matplotlib>=2.1->qiskit[all]) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in e:\\anaconda\\lib\\site-packages (from matplotlib>=2.1->qiskit[all]) (1.3.1)\n    Requirement already satisfied: pyparsing>=2.2.1 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from matplotlib>=2.1->qiskit[all]) (2.4.7)\n    Requirement already satisfied: pytz>=2017.3 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from pandas<=1.2.3->qiskit-aqua==0.9.1->qiskit[all]) (2021.3)\n    Requirement already satisfied: wcwidth in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->ipython>=4.0.0->ipywidgets>=7.3.0->qiskit[all]) (0.2.5)\n    Requirement already satisfied: more-itertools in e:\\anaconda\\lib\\site-packages (from quandl<=3.6.0->qiskit-aqua==0.9.1->qiskit[all]) (8.8.0)\n    Requirement already satisfied: inflection>=0.3.1 in e:\\anaconda\\lib\\site-packages (from quandl<=3.6.0->qiskit-aqua==0.9.1->qiskit[all]) (0.5.1)\n    Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit[all]) (2021.10.8)\n    Requirement already satisfied: charset-normalizer~=2.0.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit[all]) (2.0.7)\n    Requirement already satisfied: idna<4,>=2.5 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit[all]) (3.3)\n    Requirement already satisfied: ntlm-auth>=1.0.2 in e:\\anaconda\\lib\\site-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit[all]) (1.5.0)\n    Requirement already satisfied: cryptography>=1.3 in e:\\anaconda\\lib\\site-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit[all]) (3.4.7)\n    Requirement already satisfied: cffi>=1.12 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit[all]) (1.15.0)\n    Requirement already satisfied: pycparser in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit[all]) (2.20)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from scikit-learn<=0.24.1,>=0.20.0->qiskit-aqua==0.9.1->qiskit[all]) (3.0.0)\n    Requirement already satisfied: joblib>=0.11 in e:\\anaconda\\lib\\site-packages (from scikit-learn<=0.24.1,>=0.20.0->qiskit-aqua==0.9.1->qiskit[all]) (1.0.1)\n    Requirement already satisfied: mpmath>=0.19 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from sympy<=1.7.1,>=1.3->qiskit-aqua==0.9.1->qiskit[all]) (1.2.1)\n    Requirement already satisfied: notebook>=4.4.1 in e:\\anaconda\\lib\\site-packages (from widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[all]) (6.4.3)\n    Requirement already satisfied: terminado>=0.8.3 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[all]) (0.12.1)\n    Requirement already satisfied: prometheus-client in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[all]) (0.12.0)\n    Requirement already satisfied: jinja2 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[all]) (3.0.2)\n    Requirement already satisfied: nbconvert in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[all]) (6.2.0)\n    Requirement already satisfied: Send2Trash>=1.5.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[all]) (1.8.0)\n    Requirement already satisfied: argon2-cffi in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[all]) (21.1.0)\n    Requirement already satisfied: pywinpty>=1.1.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from terminado>=0.8.3->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[all]) (1.1.5)\n    Requirement already satisfied: lxml>=4.5.1 in e:\\anaconda\\lib\\site-packages (from yfinance<=0.1.55->qiskit-aqua==0.9.1->qiskit[all]) (4.6.3)\n    Requirement already satisfied: multitasking>=0.0.7 in e:\\anaconda\\lib\\site-packages (from yfinance<=0.1.55->qiskit-aqua==0.9.1->qiskit[all]) (0.0.9)\n    Requirement already satisfied: zipp>=3.1.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from importlib-resources->jsonschema>=2.6->qiskit-terra==0.17.3->qiskit[all]) (3.6.0)\n    Requirement already satisfied: MarkupSafe>=2.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from jinja2->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[all]) (2.0.1)\n    Requirement already satisfied: mistune<2,>=0.8.1 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[all]) (0.8.4)\n    Requirement already satisfied: defusedxml in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[all]) (0.7.1)\n    Requirement already satisfied: nbclient<0.6.0,>=0.5.0 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[all]) (0.5.4)\n    Requirement already satisfied: pandocfilters>=1.4.1 in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[all]) (1.5.0)\n    Requirement already satisfied: testpath in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[all]) (0.5.0)\n    Requirement already satisfied: bleach in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[all]) (4.1.0)\n    Requirement already satisfied: jupyterlab-pygments in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[all]) (0.1.2)\n    Requirement already satisfied: packaging in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[all]) (21.2)\n    Requirement already satisfied: webencodings in c:\\users\\sun\\appdata\\roaming\\python\\python38\\site-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0->qiskit[all]) (0.5.1)\n    Requirement already satisfied: numba>=0.49 in e:\\anaconda\\lib\\site-packages (from sparse->qiskit-machine-learning==0.1.0->qiskit[all]) (0.53.1)\n    Requirement already satisfied: llvmlite<0.37,>=0.36.0rc1 in e:\\anaconda\\lib\\site-packages (from numba>=0.49->sparse->qiskit-machine-learning==0.1.0->qiskit[all]) (0.36.0)\n    Installing collected packages: sparse, qiskit-optimization, qiskit-nature, qiskit-machine-learning, qiskit-finance\n      Attempting uninstall: qiskit-optimization\n        Found existing installation: qiskit-optimization 0.2.3\n        Uninstalling qiskit-optimization-0.2.3:\n          Successfully uninstalled qiskit-optimization-0.2.3\n      Attempting uninstall: qiskit-nature\n        Found existing installation: qiskit-nature 0.2.2\n        Uninstalling qiskit-nature-0.2.2:\n          Successfully uninstalled qiskit-nature-0.2.2\n      Attempting uninstall: qiskit-machine-learning\n        Found existing installation: qiskit-machine-learning 0.2.1\n        Uninstalling qiskit-machine-learning-0.2.1:\n          Successfully uninstalled qiskit-machine-learning-0.2.1\n      Attempting uninstall: qiskit-finance\n        Found existing installation: qiskit-finance 0.2.1\n        Uninstalling qiskit-finance-0.2.1:\n          Successfully uninstalled qiskit-finance-0.2.1\n    Successfully installed qiskit-finance-0.1.0 qiskit-machine-learning-0.1.0 qiskit-nature-0.1.2 qiskit-optimization-0.1.0 sparse-0.13.0\n\n\n\n```python\nfrom typing import List, Union\nimport math\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, assemble\nfrom qiskit.compiler import transpile\nfrom qiskit.circuit import Gate\nfrom qiskit.circuit.library.standard_gates import *\nfrom qiskit.circuit.library import QFT\n```\n\n\n```python\ninstance_examples = [\n    {\n        'L1': [3, 7, 3, 4, 2, 6, 2, 2, 4, 6, 6],\n        'L2': [7, 8, 7, 6, 6, 9, 6, 7, 6, 7, 7],\n        'C1': [2, 2, 2, 3, 2, 4, 2, 2, 2, 2, 2],\n        'C2': [4, 3, 3, 4, 4, 5, 3, 4, 4, 3, 4],\n        'C_max': 33\n    },\n    {\n        'L1': [4, 2, 2, 3, 5, 3, 6, 3, 8, 3, 2],\n        'L2': [6, 5, 8, 5, 6, 6, 9, 7, 9, 5, 8],\n        'C1': [3, 3, 2, 3, 4, 2, 2, 3, 4, 2, 2],\n        'C2': [4, 4, 3, 5, 5, 3, 4, 5, 5, 3, 5],\n        'C_max': 38\n    },\n    {\n        'L1': [5, 4, 3, 3, 3, 7, 6, 4, 3, 5, 3],\n        'L2': [9, 7, 5, 5, 7, 8, 8, 7, 5, 7, 9],\n        'C1': [2, 2, 4, 2, 3, 4, 2, 2, 2, 2, 2],\n        'C2': [3, 4, 5, 4, 4, 5, 3, 3, 5, 3, 5],\n        'C_max': 35\n    }\n]\n```\n\n\n```python\ndef phase_return(index_qubits: int, gamma: float, L1: list, L2: list, to_gate=True) -> Union[Gate, QuantumCircuit]:\n    qr_index = QuantumRegister(index_qubits, \"index\")\n    qc = QuantumCircuit(qr_index)\n    \n    ##############################\n    # U_1(gamma * (lambda2 - lambda1)) for each qubit\n    for i in range(index_qubits):\n        qc.rz(-0.78*gamma*(L2[i]-L1[i]), qr_index[i])\n    # qc.decompose.draw()\n    ##############################\n    \n    return qc.to_gate(label=\" phase return \") if to_gate else qc\n```\n\n\n```python\ndef subroutine_add_const(data_qubits: int, const: int, to_gate=True) -> Union[Gate, QuantumCircuit]:\n    qc = QuantumCircuit(data_qubits)\n    ##############################\n    ### Phase Rotation ###\n    m = 0\n    pre = 1\n    if const < 0:\n        const = -const\n        pre = -1\n\n    const_b = format(const, f'0{data_qubits}b')\n    const_b = const_b[::-1]\n    # print(f'const_b: {const_b}')    \n    # solution 1\n    if const:\n        for i in range(data_qubits): # i is 0, 1,..,n-1\n            for j in range(i+1): # j in [0],..,[0,..,data_qubits-1]\n                if int(const_b[j]): # b='00 000 000 01{0}'\n                    m += 1/2**(i-j)\n            if (math.pi*m)%(2*math.pi) !=0:\n                qc.p(pre*(math.pi*m)%(2*math.pi), i)\n                m=0\n            #print(f'i: {i}, j in: {data_qubits-i}, m: {m}, const_b: {const_b[data_qubits-j-1]}')\n    # solution 2\n    # for j in range(data_qubits):\n    #     for k in range(data_qubits - j):\n    #         lam = math.pi / (2 ** k)\n    #         if int(const_b[j]):\n    #             qc.p(lam, j+k)\n    # print(qc)\n\n    ##############################\n    return qc.to_gate(label=\" [+\"+str(const)+\"] \") if to_gate else qc\n\n```\n\n\n```python\ndef const_adder(data_qubits: int, const: int, to_gate=True) -> Union[Gate, QuantumCircuit]:\n    \n    qr_data = QuantumRegister(data_qubits, \"data\")\n    qc = QuantumCircuit(qr_data)\n    \n    ##############################\n    ### QFT ###\n    qc.append(QFT(num_qubits=data_qubits, do_swaps=False).to_gate(), qr_data[:])\n\n    ### Phase Rotation ###\n    # Use `subroutine_add_const`\n    qc.append(subroutine_add_const(data_qubits=data_qubits, const=const), qr_data[:])\n\n    ### IQFT ###\n    qc.append(QFT(num_qubits=data_qubits, inverse=True, do_swaps=False).to_gate(), qr_data[:])\n\n    ##############################\n    return qc.to_gate(label=\" [ +\" + str(const) + \"] \") if to_gate else qc\n```\n\n\n```python\n# penalty part\ndef cost_calculation(index_qubits: int, data_qubits: int, list1: list, list2: list, to_gate = True) -> Union[Gate, QuantumCircuit]:\n    qr_index = QuantumRegister(index_qubits, \"index\")\n    qr_data = QuantumRegister(data_qubits, \"data\")\n    qc = QuantumCircuit(qr_index, qr_data)\n\n    for i, (val1, val2) in enumerate(zip(list1, list2)):\n        \n        ##############################\n        ### Add val2 using const_adder controlled by i-th index register (set to 1) ###\n        # Provide your code here\n        qc.append(const_adder(data_qubits=data_qubits, const=val2).control(), [qr_index[i]] + qr_data[:])\n\n        qc.x(qr_index[i]) # flip control qubit\n        \n        ##############################\n        ### Add val1 using const_adder controlled by i-th index register (set to 0) ###\n        # Provide your code here\n        qc.append(const_adder(data_qubits=data_qubits, const=val1).control(), [qr_index[i]] + qr_data[:])\n\n        qc.x(qr_index[i]) # flip control qubit\n\n    return qc.to_gate(label=\" Cost Calculation \") if to_gate else qc\n```\n\n\n```python\n# penalty part\ndef cost_calculation(index_qubits: int, data_qubits: int, list1: list, list2: list, to_gate = True) -> Union[Gate, QuantumCircuit]:\n    qr_index = QuantumRegister(index_qubits, \"index\")\n    qr_data = QuantumRegister(data_qubits, \"data\")\n    qc = QuantumCircuit(qr_index, qr_data)\n\n    qc.append(QFT(num_qubits=data_qubits, do_swaps=False).to_gate(), qr_data[:])\n\n    for i, (val1, val2) in enumerate(zip(list1, list2)):\n\n        ##############################\n        ### Add val2 using const_adder controlled by i-th index register (set to 1) ###\n        # Provide your code here\n        const = val2\n        m = 0\n        pre = 1\n        if const < 0:\n            const = -const\n            pre = -1\n\n        const_b = format(const, f'0{data_qubits}b')\n        const_b = const_b[::-1]\n        # print(f'const_b: {const_b}')    \n        # solution 1\n        if const:\n            for k in range(data_qubits): # i is 0, 1,..,n-1\n                for j in range(k+1): # j in [0],..,[0,..,data_qubits-1]\n                    if int(const_b[j]): # b='00 000 000 01{0}'\n                        m += 1/2**(k-j)\n                if (math.pi*m)%(2*math.pi) !=0:\n                    qc.cp(pre*(math.pi*m)%(2*math.pi), qr_index[i], qr_data[k])\n                    m=0\n        #qc.append(const_adder(data_qubits=data_qubits, const=val2).control(), [qr_index[i]] + qr_data[:])\n        #qc.append(const_adder(data_qubits=data_qubits, const=val2).control(), [qr_index[index_qubits-i-1]] + qr_data[:])\n\n        qc.x(qr_index[i]) # flip control qubit\n\n        ##############################\n        ### Add val1 using const_adder controlled by i-th index register (set to 0) ###\n        # Provide your code here\n        const = val1\n        if const < 0:\n            const = -const\n            pre = -1\n\n        const_b = format(const, f'0{data_qubits}b')\n        const_b = const_b[::-1]\n        # print(f'const_b: {const_b}')    \n        # solution 1\n        if const:\n            for k in range(data_qubits): # i is 0, 1,..,n-1\n                for j in range(k+1): # j in [0],..,[0,..,data_qubits-1]\n                    if int(const_b[j]): # b='00 000 000 01{0}'\n                        m += 1/2**(k-j)\n                if (math.pi*m)%(2*math.pi) !=0:\n                    qc.cp(pre*(math.pi*m)%(2*math.pi), qr_index[i], qr_data[k])\n                    m=0\n        # qc.append(const_adder(data_qubits=data_qubits, const=val1).control(), [qr_index[index_qubits-i-1]] + qr_data[:])\n\n        qc.x(qr_index[i]) # flip control qubit\n    \n    qc.append(QFT(num_qubits=data_qubits, inverse=True, do_swaps=False).to_gate(), qr_data[:])\n\n    return qc.to_gate(label=\" Cost Calculation \") if to_gate else qc\n```\n\n\n```python\ndef constraint_testing(data_qubits: int, C_max: int, to_gate = True) -> Union[Gate, QuantumCircuit]:\n    \n    qr_data = QuantumRegister(data_qubits, \"data\")\n    qr_f = QuantumRegister(1, \"flag\")\n    qc = QuantumCircuit(qr_data, qr_f)\n    \n    ##############################\n    ### Set the flag register for indices with costs larger than C_max ###\n    # Provide your code here\n    # c_max_b = format(C_max, f'0{data_qubits}b') # binary formulation of C_max\n    # if C_max <= 2**(data_qubits) - 1: # sum of cost can exceed the c_max\n    #     # searching '0' in binary formulation of C_max\n    #     fst_one_index = 0\n    #     for i, b in enumerate(c_max_b):\n    #         if int(b) == 1:\n    #             fst_one_index = data_qubits - i - 1\n    #             break\n    #     zero_indexs = [i for i, b in enumerate(c_max_b) if int(b) == 0]\n    #     print(f'zeros: {zero_indexs}, fst_one_index: {fst_one_index}')\n    #     ctrl_gates = []\n    #     addr_gates = []\n        \n    #     if zero_indexs:\n    #         for zero_i in zero_indexs:\n    #             end_index = zero_indexs.pop()\n    #             num_ctrl_qubits = fst_one_index - end_index + 1 # num_qubits = fst_one_index - end_index + 1\n    #             sub_cir = QuantumCircuit(num_ctrl_qubits + 1)\n    #             ctrl_gates.append(sub_cir.x(0).to_gate().control(num_ctrl_qubits = num_ctrl_qubits)]\n    #             addr_gates.append([fst_one_index, end_index])\n    #         qc_ctrls = QuantumRegister(len(ctrl_gates), \"ctrl_gates\")\n    qc.append(QFT(num_qubits=data_qubits, do_swaps=False).to_gate(), qr_data[:])\n    c = (C_max).bit_length()\n    gap = 2**c - C_max\n    const = gap\n    m = 0\n    pre = 1\n    if const < 0:\n        const = -const\n        pre = -1\n\n    const_b = format(const, f'0{data_qubits}b')\n    const_b = const_b[::-1]\n    # print(f'const_b: {const_b}')    \n    # solution 1\n    if const:\n        for k in range(data_qubits): # i is 0, 1,..,n-1\n            for j in range(k+1): # j in [0],..,[0,..,data_qubits-1]\n                if int(const_b[j]): # b='00 000 000 01{0}'\n                    m += 1/2**(k-j)\n            if (math.pi*m)%(2*math.pi) !=0:\n                qc.p(pre*(math.pi*m)%(2*math.pi), qr_data[k])\n                m=0\n    qc.append(QFT(num_qubits=data_qubits, inverse=True, do_swaps=False).to_gate(), qr_data[:])\n    sub_cir = QuantumCircuit(1)\n    sub_cir.x(0)\n    qc.append(sub_cir.to_gate().control(num_ctrl_qubits=data_qubits-c, ctrl_state=0), qr_data[c:] + [qr_f[0]])\n\n    qc.append(QFT(num_qubits=data_qubits, do_swaps=False).to_gate(), qr_data[:])\n\n    const = -gap\n    m = 0\n    pre = 1\n    if const < 0:\n        const = -const\n        pre = -1\n\n    const_b = format(const, f'0{data_qubits}b')\n    const_b = const_b[::-1]\n    # print(f'const_b: {const_b}')    \n    # solution 1\n    if const:\n        for k in range(data_qubits): # i is 0, 1,..,n-1\n            for j in range(k+1): # j in [0],..,[0,..,data_qubits-1]\n                if int(const_b[j]): # b='00 000 000 01{0}'\n                    m += 1/2**(k-j)\n            if (math.pi*m)%(2*math.pi) !=0:\n                qc.p(pre*(math.pi*m)%(2*math.pi), qr_data[k])\n                m=0\n    qc.x(qr_f[0])\n    qc.append(QFT(num_qubits=data_qubits, inverse=True, do_swaps=False).to_gate(), qr_data[:])\n    ##############################\n    \n    return qc.to_gate(label=\" Constraint Testing \") if to_gate else qc\n```\n\n\n```python\n# penalty part\ndef penalty_dephasing(data_qubits: int, alpha: float, gamma: float, to_gate = True) -> Union[Gate, QuantumCircuit]:\n\n    qr_data = QuantumRegister(data_qubits, \"data\")\n    qr_f = QuantumRegister(1, \"flag\")\n    qc = QuantumCircuit(qr_data, qr_f)\n    # c = (C_max).bit_length()\n\n    ##############################\n    ### Phase Rotation ###\n\n    for i in range(data_qubits):\n        qc.cp(1.02*2**i*alpha*gamma, qr_f[0], i)\n    qc.p(-1.02*C_max*alpha*gamma, qr_f[0])\n    # qc.p(C_max*alpha*gamma, qr_f[0])\n\n    ##############################\n\n    return qc.to_gate(label=\" Penalty Dephasing \") if to_gate else qc\n    \ndef reinitialization(index_qubits: int, data_qubits: int, C1: list, C2: list, C_max: int, to_gate = True) -> Union[Gate, QuantumCircuit]:\n    \n    qr_index = QuantumRegister(index_qubits, \"index\")\n    qr_data = QuantumRegister(data_qubits, \"data\")\n    qr_f = QuantumRegister(1, \"flag\")\n    qc = QuantumCircuit(qr_index, qr_data, qr_f)\n    \n    ##############################\n    ### Reinitialization Circuit ###\n    \n    qc.append(constraint_testing(data_qubits=data_qubits, C_max=C_max).inverse(), qr_data[:] + qr_f[:])\n    qc.append(cost_calculation(index_qubits=index_qubits, data_qubits=data_qubits, list1=C1, list2=C2).inverse(), qr_index[:] + qr_data[:])\n    \n    # to_gate = False\n    # qc.reset(qr_data[:])\n    # qc.reset(qr_f[:])\n    \n    ##############################\n    \n    return qc.to_gate(label=\" Reinitialization \") if to_gate else qc\n```\n\n\n```python\nfrom qiskit import QuantumCircuit, assemble, Aer\nfrom qiskit.visualization import plot_histogram\nexample = instance_examples[0]\nc1 = example['C1']\nc2 = example['C2']\nC_max = example['C_max']\n\n# L1 = [5,3,3,6,9,7,1]\n# L2 = [8,4,5,12,10,11,2]\n# c1 = [1,1,2,1,1,1,2]\n# c2 = [3,2,3,2,4,3,3]\n# C_max = 8\n\np = 5\nalpha = 1\ni = 0\nbeta = 1 - (i + 1) / p\ngamma = (i + 1) / p\n#C_Max = 10\ndata_qubits = len(example['L1'])\nindex_qubits = len(example['L1'])\n\nindex_reg = QuantumRegister(index_qubits, \"indexRegister\")\ndata_reg = QuantumRegister(data_qubits, \"dataRegister\")\nflag_reg = QuantumRegister(1, \"flagRegister\")\nc_bits = ClassicalRegister(data_qubits , \"classicalRegister\")\nc_max_flag = ClassicalRegister(1, \"cmaxflag\")\n\nqc = QuantumCircuit(index_reg, data_reg, flag_reg, c_bits, c_max_flag)\n# test 1: index reg = 00..00 => take value only from L1 and C1\n# test 2:  ..       = 11..11 => take value only from L2 and C2\n# test 3: with qc.h without qc.x to test reinitilization\n# qc.x(index_reg[:])\nqc.h(index_reg[:])\n# total cost\nqc.append(cost_calculation(index_qubits=index_qubits, data_qubits=data_qubits, list1=c1, list2=c2), index_reg[:]+data_reg[:])\n# flag\nqc.append(constraint_testing(data_qubits=data_qubits, C_max= C_max), data_reg[:]+flag_reg[:])\n\n\nqc.append(penalty_dephasing(data_qubits=data_qubits, alpha=alpha, gamma=gamma), data_reg[:]+flag_reg[:])\nqc.append(reinitialization(index_qubits=index_qubits,data_qubits=data_qubits,C1=c1,C2=c2, C_max=C_max), index_reg[:] + data_reg[:] + flag_reg[:])\n\nqc.measure(data_reg[:], c_bits[:])\nqc.measure(flag_reg[:], c_max_flag[:])\nprint(f'circuit: {qc}')\n```\n\n    circuit:                       \u250c\u2500\u2500\u2500\u2510\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510                          \u00bb\n         indexRegister_0: \u2524 X \u251c\u25240                     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                          \u251c\u2500\u2500\u2500\u2524\u2502                      \u2502                          \u00bb\n         indexRegister_1: \u2524 X \u251c\u25241                     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                          \u251c\u2500\u2500\u2500\u2524\u2502                      \u2502                          \u00bb\n         indexRegister_2: \u2524 X \u251c\u25242                     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                          \u251c\u2500\u2500\u2500\u2524\u2502                      \u2502                          \u00bb\n         indexRegister_3: \u2524 X \u251c\u25243                     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                          \u251c\u2500\u2500\u2500\u2524\u2502                      \u2502                          \u00bb\n         indexRegister_4: \u2524 X \u251c\u25244                     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                          \u251c\u2500\u2500\u2500\u2524\u2502                      \u2502                          \u00bb\n         indexRegister_5: \u2524 X \u251c\u25245                     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                          \u251c\u2500\u2500\u2500\u2524\u2502                      \u2502                          \u00bb\n         indexRegister_6: \u2524 X \u251c\u25246                     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                          \u251c\u2500\u2500\u2500\u2524\u2502                      \u2502                          \u00bb\n         indexRegister_7: \u2524 X \u251c\u25247                     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                          \u251c\u2500\u2500\u2500\u2524\u2502                      \u2502                          \u00bb\n         indexRegister_8: \u2524 X \u251c\u25248                     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                          \u251c\u2500\u2500\u2500\u2524\u2502                      \u2502                          \u00bb\n         indexRegister_9: \u2524 X \u251c\u25249                     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                          \u251c\u2500\u2500\u2500\u2524\u2502                      \u2502                          \u00bb\n        indexRegister_10: \u2524 X \u251c\u252410                    \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n                          \u2514\u2500\u2500\u2500\u2518\u2502    Cost Calculation  \u2502\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u00bb\n          dataRegister_0: \u2500\u2500\u2500\u2500\u2500\u252411                    \u251c\u25240                       \u251c\u00bb\n                               \u2502                      \u2502\u2502                        \u2502\u00bb\n          dataRegister_1: \u2500\u2500\u2500\u2500\u2500\u252412                    \u251c\u25241                       \u251c\u00bb\n                               \u2502                      \u2502\u2502                        \u2502\u00bb\n          dataRegister_2: \u2500\u2500\u2500\u2500\u2500\u252413                    \u251c\u25242                       \u251c\u00bb\n                               \u2502                      \u2502\u2502                        \u2502\u00bb\n          dataRegister_3: \u2500\u2500\u2500\u2500\u2500\u252414                    \u251c\u25243                       \u251c\u00bb\n                               \u2502                      \u2502\u2502                        \u2502\u00bb\n          dataRegister_4: \u2500\u2500\u2500\u2500\u2500\u252415                    \u251c\u25244                       \u251c\u00bb\n                               \u2502                      \u2502\u2502                        \u2502\u00bb\n          dataRegister_5: \u2500\u2500\u2500\u2500\u2500\u252416                    \u251c\u25245                       \u251c\u00bb\n                               \u2502                      \u2502\u2502    Constraint Testing  \u2502\u00bb\n          dataRegister_6: \u2500\u2500\u2500\u2500\u2500\u252417                    \u251c\u25246                       \u251c\u00bb\n                               \u2502                      \u2502\u2502                        \u2502\u00bb\n          dataRegister_7: \u2500\u2500\u2500\u2500\u2500\u252418                    \u251c\u25247                       \u251c\u00bb\n                               \u2502                      \u2502\u2502                        \u2502\u00bb\n          dataRegister_8: \u2500\u2500\u2500\u2500\u2500\u252419                    \u251c\u25248                       \u251c\u00bb\n                               \u2502                      \u2502\u2502                        \u2502\u00bb\n          dataRegister_9: \u2500\u2500\u2500\u2500\u2500\u252420                    \u251c\u25249                       \u251c\u00bb\n                               \u2502                      \u2502\u2502                        \u2502\u00bb\n         dataRegister_10: \u2500\u2500\u2500\u2500\u2500\u252421                    \u251c\u252410                      \u251c\u00bb\n                               \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2502                        \u2502\u00bb\n          flagRegister_0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252411                      \u251c\u00bb\n                                                       \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u00bb\n    classicalRegister: 11/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u00bb\n                                                                                 \u00bb\n              cmaxflag: 1/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u00bb\n                                                                                 \u00bb\n    \u00ab                                               \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510      \u00bb\n    \u00ab     indexRegister_0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25240                     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n    \u00ab                                               \u2502                      \u2502      \u00bb\n    \u00ab     indexRegister_1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25241                     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n    \u00ab                                               \u2502                      \u2502      \u00bb\n    \u00ab     indexRegister_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25242                     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n    \u00ab                                               \u2502                      \u2502      \u00bb\n    \u00ab     indexRegister_3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25243                     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n    \u00ab                                               \u2502                      \u2502      \u00bb\n    \u00ab     indexRegister_4: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25244                     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n    \u00ab                                               \u2502                      \u2502      \u00bb\n    \u00ab     indexRegister_5: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25245                     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n    \u00ab                                               \u2502                      \u2502      \u00bb\n    \u00ab     indexRegister_6: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25246                     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n    \u00ab                                               \u2502                      \u2502      \u00bb\n    \u00ab     indexRegister_7: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25247                     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n    \u00ab                                               \u2502                      \u2502      \u00bb\n    \u00ab     indexRegister_8: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25248                     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n    \u00ab                                               \u2502                      \u2502      \u00bb\n    \u00ab     indexRegister_9: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25249                     \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n    \u00ab                                               \u2502                      \u2502      \u00bb\n    \u00ab    indexRegister_10: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252410                    \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u00bb\n    \u00ab                      \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u2502                      \u2502\u250c\u2500\u2510   \u00bb\n    \u00ab      dataRegister_0: \u25240                      \u251c\u252411  Reinitialization  \u251c\u2524M\u251c\u2500\u2500\u2500\u00bb\n    \u00ab                      \u2502                       \u2502\u2502                      \u2502\u2514\u2565\u2518\u250c\u2500\u2510\u00bb\n    \u00ab      dataRegister_1: \u25241                      \u251c\u252412                    \u251c\u2500\u256b\u2500\u2524M\u251c\u00bb\n    \u00ab                      \u2502                       \u2502\u2502                      \u2502 \u2551 \u2514\u2565\u2518\u00bb\n    \u00ab      dataRegister_2: \u25242                      \u251c\u252413                    \u251c\u2500\u256b\u2500\u2500\u256b\u2500\u00bb\n    \u00ab                      \u2502                       \u2502\u2502                      \u2502 \u2551  \u2551 \u00bb\n    \u00ab      dataRegister_3: \u25243                      \u251c\u252414                    \u251c\u2500\u256b\u2500\u2500\u256b\u2500\u00bb\n    \u00ab                      \u2502                       \u2502\u2502                      \u2502 \u2551  \u2551 \u00bb\n    \u00ab      dataRegister_4: \u25244                      \u251c\u252415                    \u251c\u2500\u256b\u2500\u2500\u256b\u2500\u00bb\n    \u00ab                      \u2502                       \u2502\u2502                      \u2502 \u2551  \u2551 \u00bb\n    \u00ab      dataRegister_5: \u25245                      \u251c\u252416                    \u251c\u2500\u256b\u2500\u2500\u256b\u2500\u00bb\n    \u00ab                      \u2502    Penalty Dephasing  \u2502\u2502                      \u2502 \u2551  \u2551 \u00bb\n    \u00ab      dataRegister_6: \u25246                      \u251c\u252417                    \u251c\u2500\u256b\u2500\u2500\u256b\u2500\u00bb\n    \u00ab                      \u2502                       \u2502\u2502                      \u2502 \u2551  \u2551 \u00bb\n    \u00ab      dataRegister_7: \u25247                      \u251c\u252418                    \u251c\u2500\u256b\u2500\u2500\u256b\u2500\u00bb\n    \u00ab                      \u2502                       \u2502\u2502                      \u2502 \u2551  \u2551 \u00bb\n    \u00ab      dataRegister_8: \u25248                      \u251c\u252419                    \u251c\u2500\u256b\u2500\u2500\u256b\u2500\u00bb\n    \u00ab                      \u2502                       \u2502\u2502                      \u2502 \u2551  \u2551 \u00bb\n    \u00ab      dataRegister_9: \u25249                      \u251c\u252420                    \u251c\u2500\u256b\u2500\u2500\u256b\u2500\u00bb\n    \u00ab                      \u2502                       \u2502\u2502                      \u2502 \u2551  \u2551 \u00bb\n    \u00ab     dataRegister_10: \u252410                     \u251c\u252421                    \u251c\u2500\u256b\u2500\u2500\u256b\u2500\u00bb\n    \u00ab                      \u2502                       \u2502\u2502                      \u2502 \u2551  \u2551 \u00bb\n    \u00ab      flagRegister_0: \u252411                     \u251c\u252422                    \u251c\u2500\u256b\u2500\u2500\u256b\u2500\u00bb\n    \u00ab                      \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2551  \u2551 \u00bb\n    \u00abclassicalRegister: 11/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u00bb\n    \u00ab                                                                        0  1 \u00bb\n    \u00ab          cmaxflag: 1/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u00bb\n    \u00ab                                                                             \u00bb\n    \u00ab                                                    \n    \u00ab     indexRegister_0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                                                    \n    \u00ab     indexRegister_1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                                                    \n    \u00ab     indexRegister_2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                                                    \n    \u00ab     indexRegister_3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                                                    \n    \u00ab     indexRegister_4: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                                                    \n    \u00ab     indexRegister_5: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                                                    \n    \u00ab     indexRegister_6: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                                                    \n    \u00ab     indexRegister_7: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                                                    \n    \u00ab     indexRegister_8: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                                                    \n    \u00ab     indexRegister_9: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                                                    \n    \u00ab    indexRegister_10: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                                                    \n    \u00ab      dataRegister_0: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                                                    \n    \u00ab      dataRegister_1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                      \u250c\u2500\u2510                           \n    \u00ab      dataRegister_2: \u2524M\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                      \u2514\u2565\u2518\u250c\u2500\u2510                        \n    \u00ab      dataRegister_3: \u2500\u256b\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                       \u2551 \u2514\u2565\u2518\u250c\u2500\u2510                     \n    \u00ab      dataRegister_4: \u2500\u256b\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                       \u2551  \u2551 \u2514\u2565\u2518\u250c\u2500\u2510                  \n    \u00ab      dataRegister_5: \u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                       \u2551  \u2551  \u2551 \u2514\u2565\u2518\u250c\u2500\u2510               \n    \u00ab      dataRegister_6: \u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                       \u2551  \u2551  \u2551  \u2551 \u2514\u2565\u2518\u250c\u2500\u2510            \n    \u00ab      dataRegister_7: \u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                       \u2551  \u2551  \u2551  \u2551  \u2551 \u2514\u2565\u2518\u250c\u2500\u2510         \n    \u00ab      dataRegister_8: \u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                       \u2551  \u2551  \u2551  \u2551  \u2551  \u2551 \u2514\u2565\u2518\u250c\u2500\u2510      \n    \u00ab      dataRegister_9: \u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u2500\u2500\u2500\u2500\u2500\n    \u00ab                       \u2551  \u2551  \u2551  \u2551  \u2551  \u2551  \u2551 \u2514\u2565\u2518\u250c\u2500\u2510   \n    \u00ab     dataRegister_10: \u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2524M\u251c\u2500\u2500\u2500\n    \u00ab                       \u2551  \u2551  \u2551  \u2551  \u2551  \u2551  \u2551  \u2551 \u2514\u2565\u2518\u250c\u2500\u2510\n    \u00ab      flagRegister_0: \u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2500\u256b\u2500\u2524M\u251c\n    \u00ab                       \u2551  \u2551  \u2551  \u2551  \u2551  \u2551  \u2551  \u2551  \u2551 \u2514\u2565\u2518\n    \u00abclassicalRegister: 11/\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2550\u256c\u2550\n    \u00ab                       2  3  4  5  6  7  8  9  10 \u2551 \n    \u00ab          cmaxflag: 1/\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\n    \u00ab                                                  0 \n\n\n\n```python\n# test run\nsim = Aer.get_backend(\"aer_simulator\")\ntrans_adder = transpile(qc, sim)\nresult = sim.run(trans_adder, shots=1000).result()\ncounts = result.get_counts()\nprint(counts)\nplot_histogram(counts)\n```\n\n\n```python\ndef solver_function(L1: list, L2: list, C1: list, C2: list, C_max: int) -> QuantumCircuit:\n    \n    # the number of qubits representing answers\n    index_qubits = len(L1)\n    \n    # the maximum possible total cost\n    max_c = sum([max(l0, l1) for l0, l1 in zip(C1, C2)])\n    \n    # the number of qubits representing data values can be defined using the maximum possible total cost as follows:\n    data_qubits = math.ceil(math.log(max_c, 2)) + 1 if not max_c & (max_c - 1) == 0 else math.ceil(math.log(max_c, 2)) + 2\n    \n    ### Phase Operator ###\n    # return part\n    ws=[0.78,1.02,-1.02]\n    #ws = [0.2*0.78*math.pi, 0.2*1.02*math.pi, -1.02*0.2*math.pi]\n    def phase_return(index_qubits: int, gamma: float, L1: list, L2: list, to_gate=True) -> Union[Gate, QuantumCircuit]:\n        ##############################\n        #param = np.array([l1-l2 for l1, l2 in zip(L1, L2)]).std()\n        qr_index = QuantumRegister(index_qubits, \"index\")\n        qc = QuantumCircuit(qr_index)\n        param = 0\n        for i in range(index_qubits):\n            qc.p(-ws[0]*(1-param)*gamma*(L2[i]-L1[i]), qr_index[i])\n            # qc.p(gamma*(L2[i]-L1[i]), qr_index[index_qubits-1-i])\n            # qc.barrier()\n        # qc.decompose.draw()\n\n        ##############################\n        \n        return qc.to_gate(label=\" phase return \") if to_gate else qc\n    \n    # penalty part\n    def subroutine_add_const(data_qubits: int, const: int, to_gate=True) -> Union[Gate, QuantumCircuit]:\n        qc = QuantumCircuit(data_qubits)\n        ##############################\n        ### Phase Rotation ###\n        m = 0\n        pre = 1\n        if const < 0:\n            const = -const\n            pre = -1\n\n        const_b = format(const, f'0{data_qubits}b')\n        const_b = const_b[::-1]\n        # print(f'const_b: {const_b}')    \n        # solution 1\n        if const:\n            for i in range(data_qubits): # i is 0, 1,..,n-1\n                for j in range(i+1): # j in [0],..,[0,..,data_qubits-1]\n                    if int(const_b[j]): # b='00 000 000 01{0}'\n                        m += 1/2**(i-j)\n                if (math.pi*m)%(2*math.pi) !=0:\n                    qc.p(pre*(math.pi*m)%(2*math.pi), i)\n                    m=0\n                    #print(f'i: {i}, j in: {data_qubits-i}, m: {m}, const_b: {const_b[data_qubits-j-1]}')\n        # solution 2\n        # for j in range(data_qubits):\n        #     for k in range(data_qubits - j):\n        #         lam = pre*math.pi / (2 ** k)\n        #         if int(const_b[j]):\n        #             qc.p(lam, j+k)\n        # print(qc)\n\n        ##############################\n        return qc.to_gate(label=\" [+\"+str(const)+\"] \") if to_gate else qc\n\n    # penalty part\n    def const_adder(data_qubits: int, const: int, to_gate=True) -> Union[Gate, QuantumCircuit]:\n    \n        qr_data = QuantumRegister(data_qubits, \"data\")\n        qc = QuantumCircuit(qr_data)\n\n        ##############################\n        ### QFT ###\n        qc.append(QFT(num_qubits=data_qubits, do_swaps=False).to_gate(), qr_data[:])\n\n        ### Phase Rotation ###\n        # Use `subroutine_add_const`\n        qc.append(subroutine_add_const(data_qubits=data_qubits, const=const), qr_data[:])\n\n        ### IQFT ###\n        qc.append(QFT(num_qubits=data_qubits, inverse=True, do_swaps=False).to_gate(), qr_data[:])\n\n        ##############################\n        return qc.to_gate(label=\" [ +\" + str(const) + \"] \") if to_gate else qc \n    \n    # penalty part\n    def cost_calculation(index_qubits: int, data_qubits: int, list1: list, list2: list, to_gate = True) -> Union[Gate, QuantumCircuit]:\n        qr_index = QuantumRegister(index_qubits, \"index\")\n        qr_data = QuantumRegister(data_qubits, \"data\")\n        qc = QuantumCircuit(qr_index, qr_data)\n\n        for i, (val1, val2) in enumerate(zip(list1, list2)):\n\n            ##############################\n            ### Add val2 using const_adder controlled by i-th index register (set to 1) ###\n            # Provide your code here\n            qc.append(const_adder(data_qubits=data_qubits, const=val2).control(), [qr_index[i]] + qr_data[:])\n            #qc.append(const_adder(data_qubits=data_qubits, const=val2).control(), [qr_index[index_qubits-i-1]] + qr_data[:])\n\n            qc.x(qr_index[i]) # flip control qubit\n\n            ##############################\n            ### Add val1 using const_adder controlled by i-th index register (set to 0) ###\n            # Provide your code here\n            qc.append(const_adder(data_qubits=data_qubits, const=val1).control(), [qr_index[i]] + qr_data[:])\n            # qc.append(const_adder(data_qubits=data_qubits, const=val1).control(), [qr_index[index_qubits-i-1]] + qr_data[:])\n\n            qc.x(qr_index[i]) # flip control qubit\n\n        return qc.to_gate(label=\" Cost Calculation \") if to_gate else qc\n    \n    # penalty part\n    def constraint_testing(data_qubits: int, C_max: int, to_gate = True) -> Union[Gate, QuantumCircuit]:\n    \n        qr_data = QuantumRegister(data_qubits, \"data\")\n        qr_f = QuantumRegister(1, \"flag\")\n        qc = QuantumCircuit(qr_data, qr_f)\n\n        ##############################\n        ### Set the flag register for indices with costs larger than C_max ###\n        c = (C_max).bit_length()\n        #   1101\n        # c = 4\n        # 0{0}1101 \n        gap = 2**c - C_max\n        qc.append(const_adder(data_qubits=data_qubits, const=gap), qr_data[:])\n        sub_cir = QuantumCircuit(1)\n        sub_cir.x(0)\n        qc.append(sub_cir.to_gate().control(num_ctrl_qubits=data_qubits-c, ctrl_state=0), qr_data[c:] + [qr_f[0]])\n        \n        qc.append(const_adder(data_qubits=data_qubits, const=-gap), qr_data[:]) # minus the gap\n        qc.x(qr_f[0])\n        ##############################\n\n        return qc.to_gate(label=\" Constraint Testing \") if to_gate else qc\n    \n    # penalty part\n    def penalty_dephasing(data_qubits: int, alpha: float, gamma: float, to_gate = True) -> Union[Gate, QuantumCircuit]:\n    \n        qr_data = QuantumRegister(data_qubits, \"data\")\n        qr_f = QuantumRegister(1, \"flag\")\n        qc = QuantumCircuit(qr_data, qr_f)\n        #param = np.array([l1-l2 for l1, l2 in zip(L1, L2)]).std()\n        # c = (C_max).bit_length()\n\n        ##############################\n        ### Phase Rotation ###\n        param = 0\n        for i in range(data_qubits):\n            qc.cp(ws[1]*(1-param)*(2**i)*alpha*gamma, qr_f[0], i)\n        #qc.p(ws[2]*(0.2+param)*C_max*alpha*gamma, qr_f[0])\n        qc.p(ws[2]*C_max*alpha*gamma, qr_f[0])\n        # qc.p(C_max*alpha*gamma, qr_f[0])\n\n        ##############################\n\n        return qc.to_gate(label=\" Penalty Dephasing \") if to_gate else qc\n        \n    def reinitialization(index_qubits: int, data_qubits: int, C1: list, C2: list, C_max: int, to_gate = True) -> Union[Gate, QuantumCircuit]:\n        \n        qr_index = QuantumRegister(index_qubits, \"index\")\n        qr_data = QuantumRegister(data_qubits, \"data\")\n        qr_f = QuantumRegister(1, \"flag\")\n        qc = QuantumCircuit(qr_index, qr_data, qr_f)\n        \n        ##############################\n        ### Reinitialization Circuit ###\n        \n        qc.append(constraint_testing(data_qubits=data_qubits, C_max=C_max).inverse(), qr_data[:] + qr_f[:])\n        qc.append(cost_calculation(index_qubits=index_qubits, data_qubits=data_qubits, list1=C1, list2=C2).inverse(), qr_index[:] + qr_data[:])\n        \n        # to_gate = False\n        # qc.reset(qr_data[:])\n        # qc.reset(qr_f[:])\n        \n        ##############################\n        \n        return qc.to_gate(label=\" Reinitialization \") if to_gate else qc\n\n    ### Mixing Operator ###\n    def mixing_operator(index_qubits: int, beta: float, to_gate = True) -> Union[Gate, QuantumCircuit]:\n        \n        qr_index = QuantumRegister(index_qubits, \"index\")\n        qc = QuantumCircuit(qr_index)\n        \n        ##############################\n        ### Mixing Operator ###\n        \n        for i in range(index_qubits):\n            qc.rx(2*beta, qr_index[i])\n        \n        \n        ##############################\n        \n        return qc.to_gate(label=\" Mixing Operator \") if to_gate else qc\n\n        \n    qr_index = QuantumRegister(index_qubits, \"index\") # index register\n    qr_data = QuantumRegister(data_qubits, \"data\") # data register\n    qr_f = QuantumRegister(1, \"flag\") # flag register\n    cr_index = ClassicalRegister(index_qubits, \"c_index\") # classical register storing the measurement result of index register\n    qc = QuantumCircuit(qr_index, qr_data, qr_f, cr_index)\n    \n    ### initialize the index register with uniform superposition state ###\n    qc.h(qr_index)\n    \n    ### DO NOT CHANGE THE CODE BELOW\n    p = 5\n    alpha = 1\n    for i in range(p):\n        \n        ### set fixed parameters for each round ###\n        beta = 1 - (i + 1) / p\n        gamma = (i + 1) / p\n        \n        ### return part ###\n        qc.append(phase_return(index_qubits, gamma, L1, L2), qr_index)\n        \n        ### step 1: cost calculation ###\n        qc.append(cost_calculation(index_qubits, data_qubits, C1, C2), qr_index[:] + qr_data[:])\n        \n        ### step 2: Constraint testing ###\n        qc.append(constraint_testing(data_qubits, C_max), qr_data[:] + qr_f[:])\n        \n        ### step 3: penalty dephasing ###\n        qc.append(penalty_dephasing(data_qubits, alpha, gamma), qr_data[:] + qr_f[:])\n        \n        ### step 4: reinitialization ###\n        qc.append(reinitialization(index_qubits, data_qubits, C1, C2, C_max), qr_index[:] + qr_data[:] + qr_f[:])\n        \n        ### mixing operator ###\n        qc.append(mixing_operator(index_qubits, beta), qr_index)\n\n    ### measure the index ###\n    ### since the default measurement outcome is shown in big endian, it is necessary to reverse the classical bits in order to unify the endian ###\n    qc.measure(qr_index, cr_index[::-1])\n    \n    return qc\n```\n\n\n```python\ndef solver_function(L1: list, L2: list, C1: list, C2: list, C_max: int) -> QuantumCircuit:\n    \n    # the number of qubits representing answers\n    index_qubits = len(L1)\n    \n    # the maximum possible total cost\n    max_c = sum([max(l0, l1) for l0, l1 in zip(C1, C2)])\n    \n    # the number of qubits representing data values can be defined using the maximum possible total cost as follows:\n    data_qubits = math.ceil(math.log(max_c, 2)) + 1 if not max_c & (max_c - 1) == 0 else math.ceil(math.log(max_c, 2)) + 2\n    \n    ### Phase Operator ###\n    # return part\n    ws = [0.2*0.78*math.pi, 0.2*1.02*math.pi, -0.2*1.02*math.pi]\n    def phase_return(index_qubits: int, gamma: float, L1: list, L2: list, to_gate=True) -> Union[Gate, QuantumCircuit]:\n        ##############################\n        \n        qr_index = QuantumRegister(index_qubits, \"index\")\n        qc = QuantumCircuit(qr_index)\n        for i in range(index_qubits):\n            qc.p(-ws[0]*gamma*(L2[i]-L1[i]), qr_index[i])\n        # qc.decompose.draw()\n\n        ##############################\n        \n        return qc.to_gate(label=\" phase return \") if to_gate else qc\n    \n    # penalty part\n    def subroutine_add_const(data_qubits: int, const: int, to_gate=True) -> Union[Gate, QuantumCircuit]:\n        qc = QuantumCircuit(data_qubits)\n        ##############################\n        ### Phase Rotation ###\n\n        ##############################\n        return qc.to_gate(label=\" [+\"+str(const)+\"] \") if to_gate else qc\n\n    # penalty part\n    def const_adder(data_qubits: int, const: int, to_gate=True) -> Union[Gate, QuantumCircuit]:\n    \n        qr_data = QuantumRegister(data_qubits, \"data\")\n        qc = QuantumCircuit(qr_data)\n\n        ##############################\n        ### QFT ###\n        ##############################\n        return qc.to_gate(label=\" [ +\" + str(const) + \"] \") if to_gate else qc \n    \n    def cost_calculation(index_qubits: int, data_qubits: int, list1: list, list2: list, to_gate = True) -> Union[Gate, QuantumCircuit]:\n        qr_index = QuantumRegister(index_qubits, \"index\")\n        qr_data = QuantumRegister(data_qubits, \"data\")\n        qc = QuantumCircuit(qr_index, qr_data)\n\n        qc.append(QFT(num_qubits=data_qubits, do_swaps=False).to_gate(), qr_data[:])\n\n        for i, (val1, val2) in enumerate(zip(list1, list2)):\n\n            ##############################\n            ### Add val2 using const_adder controlled by i-th index register (set to 1) ###\n            # Provide your code here\n            if val1 != val2:\n                const = val2\n                m = 0\n                pre = 1\n                if const < 0:\n                    const = -const\n                    pre = -1\n\n                const_b = format(const, f'0{data_qubits}b')\n                const_b = const_b[::-1]\n                # print(f'const_b: {const_b}')    \n                # solution 1\n                if const:\n                    for k in range(data_qubits): # i is 0, 1,..,n-1\n                        for j in range(k+1): # j in [0],..,[0,..,data_qubits-1]\n                            if int(const_b[j]): # b='00 000 000 01{0}'\n                                m += 1/2**(k-j)\n                        if (math.pi*m)%(2*math.pi) !=0:\n                            qc.cp(pre*(math.pi*m)%(2*math.pi), qr_index[i], qr_data[k])\n                            m=0\n\n                qc.x(qr_index[i]) # flip control qubit\n\n                ##############################\n                ### Add val1 using const_adder controlled by i-th index register (set to 0) ###\n                # Provide your code here\n                const = val1\n                if const < 0:\n                    const = -const\n                    pre = -1\n\n                const_b = format(const, f'0{data_qubits}b')\n                const_b = const_b[::-1]\n                # print(f'const_b: {const_b}')    \n                # solution 1\n                if const:\n                    for k in range(data_qubits): # i is 0, 1,..,n-1\n                        for j in range(k+1): # j in [0],..,[0,..,data_qubits-1]\n                            if int(const_b[j]): # b='00 000 000 01{0}'\n                                m += 1/2**(k-j)\n                        if (math.pi*m)%(2*math.pi) !=0:\n                            qc.cp(pre*(math.pi*m)%(2*math.pi), qr_index[i], qr_data[k])\n                            m=0\n\n                qc.x(qr_index[i]) # flip control qubit\n            else:\n                const = val2\n                m = 0\n                pre = 1\n                if const < 0:\n                    const = -const\n                    pre = -1\n\n                const_b = format(const, f'0{data_qubits}b')\n                const_b = const_b[::-1]\n                # print(f'const_b: {const_b}')    \n                # solution 1\n                if const:\n                    for k in range(data_qubits): # i is 0, 1,..,n-1\n                        for j in range(k+1): # j in [0],..,[0,..,data_qubits-1]\n                            if int(const_b[j]): # b='00 000 000 01{0}'\n                                m += 1/2**(k-j)\n                        if (math.pi*m)%(2*math.pi) !=0:\n                            qc.p(pre*(math.pi*m)%(2*math.pi), qr_data[k])\n                            m=0\n\n        # qc.append(QFT(num_qubits=data_qubits, inverse=True, do_swaps=False).to_gate(), qr_data[:])\n        qc=transpile(qc, seed_transpiler=42, optimization_level=2)\n        return qc.to_gate(label=\" Cost Calculation \") if to_gate else qc\n    \n    # constraint_testing\n    def constraint_testing(data_qubits: int, C_max: int, to_gate = True) -> Union[Gate, QuantumCircuit]:\n    \n        qr_data = QuantumRegister(data_qubits, \"data\")\n        qr_f = QuantumRegister(1, \"flag\")\n        qc = QuantumCircuit(qr_data, qr_f)\n\n        ##############################\n        ### Set the flag register for indices with costs larger than C_max ###\n        \n        # qc.append(QFT(num_qubits=data_qubits, do_swaps=False).to_gate(), qr_data[:])\n        \n        c = (C_max).bit_length()\n        gap = 2**c - C_max\n        const = gap\n        m = 0\n        pre = 1\n        if const < 0:\n            const = -const\n            pre = -1\n\n        const_b = format(const, f'0{data_qubits}b')\n        const_b = const_b[::-1]\n        # print(f'const_b: {const_b}')    \n        # solution 1\n        if const:\n            for k in range(data_qubits): # i is 0, 1,..,n-1\n                for j in range(k+1): # j in [0],..,[0,..,data_qubits-1]\n                    if int(const_b[j]): # b='00 000 000 01{0}'\n                        m += 1/2**(k-j)\n                if (math.pi*m)%(2*math.pi) !=0:\n                    qc.p(pre*(math.pi*m)%(2*math.pi), qr_data[k])\n                    m=0\n        #qc.append(QFT(num_qubits=data_qubits, inverse=True, do_swaps=False).to_gate(), qr_data[:])\n        sub_cir = QuantumCircuit(1)\n        sub_cir.x(0)\n        qc.append(sub_cir.to_gate().control(num_ctrl_qubits=data_qubits-c, ctrl_state=0), qr_data[c:] + [qr_f[0]])\n\n        #qc.append(QFT(num_qubits=data_qubits, do_swaps=False).to_gate(), qr_data[:])\n\n        const = -gap\n        m = 0\n        pre = 1\n        if const < 0:\n            const = -const\n            pre = -1\n\n        const_b = format(const, f'0{data_qubits}b')\n        const_b = const_b[::-1]\n        # print(f'const_b: {const_b}')    \n        # solution 1\n        if const:\n            for k in range(data_qubits): # i is 0, 1,..,n-1\n                for j in range(k+1): # j in [0],..,[0,..,data_qubits-1]\n                    if int(const_b[j]): # b='00 000 000 01{0}'\n                        m += 1/2**(k-j)\n                if (math.pi*m)%(2*math.pi) !=0:\n                    qc.p(pre*(math.pi*m)%(2*math.pi), qr_data[k])\n                    m=0\n        qc.x(qr_f[0])\n        #qc.append(QFT(num_qubits=data_qubits, inverse=True, do_swaps=False).to_gate(), qr_data[:])\n        ##############################\n\n        return qc.to_gate(label=\" Constraint Testing \") if to_gate else qc\n\n    # penalty part\n    def penalty_dephasing(data_qubits: int, alpha: float, gamma: float, to_gate = True) -> Union[Gate, QuantumCircuit]:\n    \n        qr_data = QuantumRegister(data_qubits, \"data\")\n        qr_f = QuantumRegister(1, \"flag\")\n        qc = QuantumCircuit(qr_data, qr_f)\n        # c = (C_max).bit_length()\n\n        ##############################\n        ### Phase Rotation ###\n        for i in range(data_qubits):\n            qc.cp(ws[1]*(2**i)*alpha*gamma, qr_f[0], i)\n        qc.p(ws[2]*C_max*alpha*gamma, qr_f[0])\n\n        ##############################\n\n        return qc.to_gate(label=\" Penalty Dephasing \") if to_gate else qc\n        \n    def reinitialization(index_qubits: int, data_qubits: int, C1: list, C2: list, C_max: int, to_gate = True) -> Union[Gate, QuantumCircuit]:\n        \n        qr_index = QuantumRegister(index_qubits, \"index\")\n        qr_data = QuantumRegister(data_qubits, \"data\")\n        qr_f = QuantumRegister(1, \"flag\")\n        qc = QuantumCircuit(qr_index, qr_data, qr_f)\n        \n        ##############################\n        ### Reinitialization Circuit ###\n        \n        qc.append(constraint_testing(data_qubits=data_qubits, C_max=C_max).inverse(), qr_data[:] + qr_f[:])\n        qc.append(cost_calculation(index_qubits=index_qubits, data_qubits=data_qubits, list1=C1, list2=C2).inverse(), qr_index[:] + qr_data[:])\n        \n        ##############################\n        \n        return qc.to_gate(label=\" Reinitialization \") if to_gate else qc\n\n    ### Mixing Operator ###\n    def mixing_operator(index_qubits: int, beta: float, to_gate = True) -> Union[Gate, QuantumCircuit]:\n        \n        qr_index = QuantumRegister(index_qubits, \"index\")\n        qc = QuantumCircuit(qr_index)\n        \n        ##############################\n        ### Mixing Operator ###\n        \n        for i in range(index_qubits):\n            qc.rx(2*beta, qr_index[i])\n        \n        \n        ##############################\n        \n        return qc.to_gate(label=\" Mixing Operator \") if to_gate else qc\n\n        \n    qr_index = QuantumRegister(index_qubits, \"index\") # index register\n    qr_data = QuantumRegister(data_qubits, \"data\") # data register\n    qr_f = QuantumRegister(1, \"flag\") # flag register\n    cr_index = ClassicalRegister(index_qubits, \"c_index\") # classical register storing the measurement result of index register\n    qc = QuantumCircuit(qr_index, qr_data, qr_f, cr_index)\n    \n    ### initialize the index register with uniform superposition state ###\n    qc.h(qr_index)\n    \n    ### DO NOT CHANGE THE CODE BELOW\n    p = 5\n    alpha = 1\n    for i in range(p):\n        \n        ### set fixed parameters for each round ###\n        beta = 1 - (i + 1) / p\n        gamma = (i + 1) / p\n        \n        ### return part ###\n        qc.append(phase_return(index_qubits, gamma, L1, L2), qr_index)\n        \n        ### step 1: cost calculation ###\n        qc.append(cost_calculation(index_qubits, data_qubits, C1, C2), qr_index[:] + qr_data[:])\n        \n        ### step 2: Constraint testing ###\n        qc.append(constraint_testing(data_qubits, C_max), qr_data[:] + qr_f[:])\n        \n        ### step 3: penalty dephasing ###\n        qc.append(penalty_dephasing(data_qubits, alpha, gamma), qr_data[:] + qr_f[:])\n        \n        ### step 4: reinitialization ###\n        qc.append(reinitialization(index_qubits, data_qubits, C1, C2, C_max), qr_index[:] + qr_data[:] + qr_f[:])\n        \n        ### mixing operator ###\n        qc.append(mixing_operator(index_qubits, beta), qr_index)\n\n    ### measure the index ###\n    ### since the default measurement outcome is shown in big endian, it is necessary to reverse the classical bits in order to unify the endian ###\n    qc.measure(qr_index, cr_index[::-1])\n    \n    return qc\n```\n\n\n```python\nfrom qc_grader import prepare_ex4c\njob = prepare_ex4c(solver_function)\nresult = job.result()\n```\n\n    Running \"solver_function\" (1/8)... \n    Running \"solver_function\" (2/8)... \n    Running \"solver_function\" (3/8)... \n    Running \"solver_function\" (4/8)... \n    Running \"solver_function\" (5/8)... \n    Running \"solver_function\" (6/8)... \n    Running \"solver_function\" (7/8)... \n    Running \"solver_function\" (8/8)... \n    Starting experiments. Please wait...\n    You may monitor the job (id: 61854e30ce94111eee6be965) status and proceed to grading when it successfully completes.\n\n\n\n```python\nimport qc_grader\nqc_grader.__version__\nfrom qc_grader.grade import grade_job\ngrade_job(job, '4c')\n#  grade_ex4c(job)\n```\n\n    Grading your answer for 4c. Please wait...\n    \n    Oops \ud83d\ude15! The average precision for the 4 fixed data set is lower than the threshold 0.8. Please try again.\n    Please review your answer and try again.\n\n\n\n\n\n    (False, None)\n\n\n\n\n```python\nfrom qc_grader import grade_ex4c\ngrade_ex4c(job)\n```\n\n    Submitting your answer for 4c. Please wait...\n    Congratulations \ud83c\udf89! Your answer is correct and has been submitted.\n    Your score is 1023424.\n\n\n\n```python\nfor j in range(3):\n    locals().update(instance_examples[j])\n    L_opts = [67, 62, 66]\n    L_opt = L_opts[j]\n    qc = solver_function(L1=L1, L2=L2, C1=C1, C2=C2, C_max=C_max)\n\n    sim = Aer.get_backend(\"aer_simulator\")\n    trans_adder = transpile(qc, sim)\n    result = sim.run(trans_adder, shots=512).result()\n    counts = result.get_counts()\n    # print(counts)\n    # plot_histogram(counts, figsize=(15,5))\n\n    def calculator(bitstr):\n        C=0\n        L=0\n        for j,i in enumerate(bitstr):\n            if i=='0':\n                C+=C1[j]\n                L+=L1[j]\n            else:\n                C+=C2[j]\n                L+=L2[j]\n        # print(L, C)\n        return L, C\n\n    def score():\n        L_min = sum([min(l0, l1) for l0, l1 in zip(L1, L2)])\n        N_f = 0\n        S = 0\n        for c in counts.items():\n            L, C = calculator(c[0])\n            if C <= C_max:\n                S += (L-L_min)*c[1]\n                N_f += c[1]\n        \n        S /= N_f*(L_opt-L_min)\n        print(S)\n        return S\n    score()\n```\n\n    0.8451178451178452\n    0.8003663003663004\n    0.9638888888888889\n\n\n\n```python\nfrom qiskit import QuantumCircuit, assemble, Aer\nfrom qiskit.visualization import plot_histogram\nfrom qiskit_optimization.algorithms import MinimumEigenOptimizer\nfrom qiskit import Aer\nfrom qiskit.utils import algorithm_globals, QuantumInstance\nfrom qiskit.algorithms import QAOA, NumPyMinimumEigensolver\nimport numpy as np\nfrom qiskit_optimization.applications import Knapsack\n\n```\n\n\n```python\ninstance_examples = [\n    {\n        'L1': [3, 7, 3, 4, 2, 6, 2, 2, 4, 6, 6],\n        'L2': [7, 8, 7, 6, 6, 9, 6, 7, 6, 7, 7],\n        'C1': [2, 2, 2, 3, 2, 4, 2, 2, 2, 2, 2],\n        'C2': [4, 3, 3, 4, 4, 5, 3, 4, 4, 3, 4],\n        'C_max': 33\n    },\n    {\n        'L1': [4, 2, 2, 3, 5, 3, 6, 3, 8, 3, 2],\n        'L2': [6, 5, 8, 5, 6, 6, 9, 7, 9, 5, 8],\n        'C1': [3, 3, 2, 3, 4, 2, 2, 3, 4, 2, 2],\n        'C2': [4, 4, 3, 5, 5, 3, 4, 5, 5, 3, 5],\n        'C_max': 38\n    },\n    {\n        'L1': [5, 4, 3, 3, 3, 7, 6, 4, 3, 5, 3],\n        'L2': [9, 7, 5, 5, 7, 8, 8, 7, 5, 7, 9],\n        'C1': [2, 2, 4, 2, 3, 4, 2, 2, 2, 2, 2],\n        'C2': [3, 4, 5, 4, 4, 5, 3, 3, 5, 3, 5],\n        'C_max': 35\n    }\n]\n```\n\n\n```python\nfrom qiskit.aqua.components.optimizers import COBYLA\nsc = 0\nfor j in range(3):\n    def object_function(w:list):\n        locals().update(instance_examples[j])\n        L_opts = [67, 62, 66]\n        L_opt = L_opts[j]\n        qc = solver_function(L1=L1, L2=L2, C1=C1, C2=C2, C_max=C_max, ws=w)\n\n        sim = Aer.get_backend(\"aer_simulator\")\n        trans_adder = transpile(qc, sim)\n        result = sim.run(trans_adder, shots=512).result()\n        counts = result.get_counts()\n        # print(counts)\n        # plot_histogram(counts, figsize=(15,5))\n\n        def calculator(bitstr):\n            C=0\n            L=0\n            for j,i in enumerate(bitstr):\n                if i=='0':\n                    C+=C1[j]\n                    L+=L1[j]\n                else:\n                    C+=C2[j]\n                    L+=L2[j]\n            # print(L, C)\n            return L, C\n\n        def score():\n            L_min = sum([min(l0, l1) for l0, l1 in zip(L1, L2)])\n            N_f = 0\n            S = 0\n            for c in counts.items():\n                L, C = calculator(c[0])\n                if C <= C_max:\n                    S += (L-L_min)*c[1]\n                    N_f += c[1]\n            \n            S /= N_f*(L_opt-L_min)*(-1)# COBYLA is minimize optimizer\n            sc = S\n            print(S)\n            return S\n        return score()\n\n    ws= ([0.8, 3, -2],[],[]) # [0.78, 1.02, -1.02]\n    for tol in [0.01, 0.001, 0.00001]:\n        optimizer = COBYLA(maxiter=1, tol=tol)\n        ws = optimizer.optimize(num_vars=3, objective_function=object_function, initial_point=ws[0])\n        print(f'score: {sc}, weights with step {tol} for return: {ws[0][0]}, cost: {ws[0][1]}, cmax: {ws[0][2]}')\n\n```\n\n\n```python\nimport qc_grader\nqc_grader.__version__\n```\n\n\n\n\n    '0.8.7'\n\n\n\n\n```python\nfrom qiskit import IBMQ\nIBMQ.save_account('5cd4fb14ed1e310399096fe9bd62d528d5999de11ad231bf5e0ca742f7a4e3dd0960a5ddcde760edfbda609b5411e036f45965998ec4993e6336d7b2ed414701')\nIBMQ.load_account()\nIBMQ.providers()\n```\n\n    configrc.store_credentials:WARNING:2021-11-05 10:59:05,738: Credentials already present. Set overwrite=True to overwrite.\n\n\n\n\n\n    [<AccountProvider for IBMQ(hub='ibm-q', group='open', project='main')>,\n     <AccountProvider for IBMQ(hub='iqc-fall-21-1', group='challenge-2', project='rech3qVe7pj1PiIoe')>]\n\n\n\n\n```python\nfrom qc_grader import prepare_ex4c\njob = prepare_ex4c(solver_function)\n\nresult = job.result()\n```\n\n    Running \"solver_function\" (1/8)... \n    Running \"solver_function\" (2/8)... \n    Running \"solver_function\" (3/8)... \n    Running \"solver_function\" (4/8)... \n    Running \"solver_function\" (5/8)... \n    Running \"solver_function\" (6/8)... \n    Running \"solver_function\" (7/8)... \n    Running \"solver_function\" (8/8)... \n    Starting experiments. Please wait...\n    You may monitor the job (id: 61850826ee4ec478d986a0fd) status and proceed to grading when it successfully completes.\n\n\n\n```python\n# Check your answer and submit using the following code\nimport qc_grader\nqc_grader.__version__\nfrom qc_grader.grade import grade_job\ngrade_job(job, '4c')\n#  grade_ex4c(job)\n```\n\n    Grading your answer for 4c. Please wait...\n    Failed: Gateway Time-out\n\n\n\n\n\n    (False, None)\n\n\n\n\n```python\nfrom qc_grader import grade_ex4c\ngrade_ex4c(job)\n```\n\n    Submitting your answer for 4c. Please wait...\n    Congratulations \ud83c\udf89! Your answer is correct and has been submitted.\n    Your score is 1468824.\n\n", "meta": {"hexsha": "feaedba3dd8fb2b1412038a6a41b1890b457ef39", "size": 163981, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "content/challenge-4/test.ipynb", "max_stars_repo_name": "YizeSun/ibm-quantum-challenge-fall-2021", "max_stars_repo_head_hexsha": "83a9a825b2b71e6dde4708a61d167242dae913a1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "content/challenge-4/test.ipynb", "max_issues_repo_name": "YizeSun/ibm-quantum-challenge-fall-2021", "max_issues_repo_head_hexsha": "83a9a825b2b71e6dde4708a61d167242dae913a1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "content/challenge-4/test.ipynb", "max_forks_repo_name": "YizeSun/ibm-quantum-challenge-fall-2021", "max_forks_repo_head_hexsha": "83a9a825b2b71e6dde4708a61d167242dae913a1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-02T12:45:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T12:45:21.000Z", "avg_line_length": 84.3957797221, "max_line_length": 12778, "alphanum_fraction": 0.6119672401, "converted": true, "num_tokens": 30511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1732881888514755, "lm_q2_score": 0.10521052688338609, "lm_q1q2_score": 0.01823174165173145}}
{"text": "# Hands-on Introduction to Python And Machine Learning\n\nInstructor: Tak-Kei Lam\n\n(Readers are assumed to have a little bit programming background.)\n\n\n# Getting started with Python\n(adapted from [this github repository](https://github.com/ehmatthes/intro_programming))\n\n## Variables\nA variable holds a value of various types such as string, integer, real number and boolean.\n\n\n```python\nmessage = \"Hello world!\" # message is a variable of type string, it holds 'Hello world!'\nprint(message)\n```\n\nIn Python, the value of a variable can be modified.\n\n\n```python\nmessage = \"Hello world!\"\nprint(message)\n\nmessage = 'Hello world! I love Python!' # message's value is changed here\nprint(message)\n```\n\n### Naming rules\n\n+ Variables can contain only letters, numbers, and underscores. Variable names can start with a letter or an underscore, but can not start with a number\n\n+ Spaces are not allowed in variable names, so we use underscores instead of spaces. For example, use student_name instead of \"student name\"\n\n+ You cannot use [Python keywords](http://docs.python.org/3/reference/lexical_analysis.html#keywords) as variable names\n\n+ Variable names should be descriptive, without being too long\n\n+ *Case sensitive*\n\n+ The naming rules actually also apply to other Python constructs\n\n\nIf you don't follow the rules, the Python interpreter will shout at you...\n\n\n```python\n1lovehk = 'I love HK'\n```\n\n\n```python\ni love hk = 'I love HK'\n```\n\n\n```python\nfor='Hong kong forever! (so does Wakanda)'\n```\n\nIf you attempt to use variables that have not been defined...\n\n\n```python\nmessage = 'What are the differences between a python and an anaconda?'\nprint(mesage)\n```\n\nBeware of typing mistakes!\n\n** Exercise **:\n- Try to create a variable of any kind, name it in whatever way and see whether there are errors\n- And then type:\n<code>\ntype(your variable)\n</code>\n\n## Strings\nStrings are sets of characters.\n\n### Single and double quotes\nStrings are contained by either single or double quotes.\n\n\n```python\nmy_string = \"This is a double-quoted string.\"\nmy_string = 'This is a single-quoted string.' # use single quote if you are lazy\n```\n\nThis lets us make strings that contain quotations without the need of _escape characters_.\n\nBy the way, the inventor of another programming language, Perl, stated the *three virtues of a great programmer*:\n> Laziness: The quality that makes you go to great effort to reduce overall energy expenditure. It makes you write labor-saving programs that other people will find useful and document what you wrote so you don't have to answer so many questions about it.\n>\n> Impatience: The anger you feel when the computer is being lazy. This makes you write programs that don't just react to your needs, but actually anticipate them. Or at least pretend to.\n>\n> Hubris: The quality that makes you write (and maintain) programs that other people won't want to say bad things about.\n\n\n\n```python\nquote = \"Linus Torvalds once said, 'Any program is only as good as it is useful.'\"\nprint(quote)\n```\n\n### Changing case\nYou can easily change the case of a string, to present it the way you want it to look.\n\n\n```python\nname = 'ada wong '\n\nprint(name)\nprint(name.title())\n```\n\n\n```python\nfirst_name = 'ada'\n\nprint(first_name)\nprint(first_name.title())\nprint(first_name.upper())\n\nfirst_name = 'Ada'\nprint(first_name.lower())\n```\n\nYou will see this syntax quite often, where a variable name is followed by a dot and then the name of an action, followed by a set of parentheses. The parentheses may be empty, or they may contain some values.\n\nvariable_name.action()\n\nIn this example, the word \"action\" is the name of a method. A method is something that can be done to a variable. The methods 'lower', 'title', and 'upper' are all functions that have been written into the Python language, which do something to strings. Later on, you will learn to write your own methods.\n\n### Combining strings (concatenation)\nIt is often very useful to be able to combine strings into a message or page element that we want to display. Again, this is easier to understand through an example.\n\n\n```python\nfirst_name = 'ada'\nlast_name = 'wong'\n\nfull_name = first_name + ' ' + last_name\n\nprint(full_name.title())\n```\n\nThe plus sign combines two strings into one, which is called \"concatenation\". You can use as many plus signs as you want in composing messages.\n\n\n```python\nfirst_name = 'ada'\nlast_name = 'lovelace'\nfull_name = first_name + ' ' + last_name\n\nmessage = full_name.title() + ' ' + \"was considered the world's first computer programmer.\"\n\nprint(message)\n```\n\n### Whitespace\nThe term \"whitespace\" refers to characters that the computer is aware of, but are invisible to readers. The most common whitespace characters are spaces, tabs, and newlines.\n\nA space is just \" \". The two-character sequence \"\\t\" makes a tab appear in a string. Tabs can be used anywhere you like in a string. Similarly, newlines are created by a two-character sequence \"\\n\".\n\n\n```python\nprint('Hello everyone!')\n```\n\n\n```python\nprint('\\tHello everyone!')\n```\n\n\n```python\nprint('Hello \\teveryone!')\n```\n\nThe combination \"\\n\" makes a newline appear in a string. You can use newlines anywhere you like in a string.\n\n\n```python\nprint('Hello everyone!')\n```\n\n\n```python\nprint('\\nHello everyone!'')\n      \n```\n\n\n```python\nprint('Hello \\neveryone!')\n```\n\n\n```python\nprint('\\n\\n\\nHello everyone!')\n```\n\n### Stripping whitespace\n\nMany times you will allow users to enter text into a box, and then you will read that text and use it. It is really easy for people to include extra whitespace at the beginning or end of their text. Whitespace includes spaces, tabs, and newlines.\n\nIt is often a good idea to strip this whitespace from strings before you start working with them. In Python, it is really easy to strip whitespace from the left side, the right side, or both sides of a string.\n\n\n```python\nname = ' ada '\n\nprint(name.lstrip()) # strip the spaces on the left hand side\nprint(name.rstrip()) # strip the spaces on the right hand side\nprint(name.strip())  # strip the spaces on both sides\n```\n\nIt's hard to see exactly what is happening, so maybe the following will make it a little more clear:\n\n\n```python\nname = ' ada '\n\nprint('-' + name.lstrip() + '-')\nprint('-' + name.rstrip() + '-')\nprint('-' + name.strip() + '-')\n```\n\n** Exercise **:\n- Try to print the following lines using only one print() (excluding the #s):\n\n\n```python\n#********************************************************\n#*                                                      *\n#*   I'm loving Python                                  *\n#*              Let's make programming GREAT again      *\n#*                                                      *\n#********************************************************\n```\n\n## Numbers\nDealing with simple numerical data is fairly straightforward in Python, but there are a few things you should know about.\n\n### Integers\n\nYou can do all of the basic arithmetic operations with integers, and everything should behave as you expect.\n\n\n```python\nprint(3+2)\n```\n\n\n```python\nprint(3-2)\n```\n\n\n```python\nprint(3*2)\n```\n\n\n```python\nprint(3/2)\n```\n\n\n```python\nprint(3**2)\n```\n\n\n### Arithmetic Operators\n\n| Symbol | Task Performed |\n|----|---|\n| +  | Addition |\n| -  | Subtraction |\n| *  | multiplication |\n| **  | to the power of |\n| /  | division |\n| //  | floor division (divide and then round down to the nearest integer)|\n| %  | mod |\n\nYou can use parenthesis to modify the standard order of operations.\n\n\n```python\nstandard_order = 2+3*4\nprint(standard_order)\n```\n\n\n```python\nmy_order = (2+3)*4\nprint(my_order)\n```\n\n### Floating-point numbers\nFloating-point numbers refer to any number with a decimal point. Most of the time, you can think of floating point numbers as decimals, and they will behave as you expect them to. All the arithematic operators also apply to them.\n\n\n```python\nprint(0.1+0.1)\n```\n\nHowever, sometimes you will get an answer with an unexpectly long decimal part:\n\n\n```python\nprint(0.1+0.2)\n```\n\nThis happens because of the way computers represent numbers internally; this has nothing to do with Python itself. Basically, we are used to working in powers of ten, where one tenth plus two tenths is just three tenths. But computers work in powers of two. So your computer has to represent 0.1 in a power of two, and then 0.2 as a power of two, and express their sum as a power of two. There is no exact representation for 0.3 in powers of two, and we see that in the answer to 0.1+0.2.\n\nPython tries to hide this kind of stuff when possible. Don't worry about it much for now; just don't be surprised by it, and know that we will learn to clean up our results a little later on.\n\nYou can also get the same kind of result with other operations.\n\n\n```python\nprint(3*0.1)\n```\n\n### Floating-point division\n\n\n```python\nprint(4/2) \n\n# Note: the behaviour of Python 3 and Python 2 regarding floating-point division is different.\n# In Python 2, the result will be 2.\n\n# If you are getting numerical results that you don't expect, or that don't make sense, \n# check if the version of Python you are using is treating integers differently than you expect.\n```\n\n\n```python\nprint(3/2)\n\n# Note: the behaviour of Python 3 and Python 2 regarding floating-point division is different.\n# In Python 2, the result will be 2.\n\n# If you are getting numerical results that you don't expect, or that don't make sense, \n# check if the version of Python you are using is treating integers differently than you expect.\n```\n\n** Exercise **:\n- Write some code that calculates the roots of a quadratic function given the variable coefficients:a, b, c\n\nThe formula is: $ \\frac{-b \\pm \\sqrt{b^2-4ac}}{2a}$.\n\nIf there are no roots, print \"I'm groot!\"; print the roots otherwise.\n\n## Comments\nAs you begin to write more complicated code, you will have to spend more time thinking about how to code solutions to the problems you want to solve. Once you come up with an idea, you will spend a fair amount of time troubleshooting your code, and revising your overall approach.\n\nComments allow you to write more detailed and more human readable explanations about your program. In Python, any line that starts with a pound (#) symbol is ignored by the Python interpreter and is known as a line of comment.\n\n\n```python\n# This line is a comment.\nprint('# This line is not a comment, it is code.')\n```\n\n### What makes a good comment?\n- It is short and to the point, but a complete thought. Most comments should be written in complete sentences\n- It explains your thinking, so that when you return to the code later you will understand how you were approaching the problem\n- It explains your thinking, so that others who work with your code will understand your overall approach to a problem\n- It explains particularly difficult sections of code in detail\n\n### When should you write comments?\n\n- When you have to think about code before writing it\n- When you are likely to forget later exactly how you were approaching a problem\n- When there is more than one way to solve a problem\n- When others are unlikely to anticipate your way of thinking about a problem\n\nWriting good comments is one of the clear signs of a good programmer. If you have any real interest in taking programming seriously, start using comments now.\n\n## Lists\n\nA list is a collection of items, that is stored in a variable. The items should be related in some way, but there are no restrictions on what can be stored in a list. Here is a simple example of a list, and how we can quickly access each item in the list.\n\n\n```python\nstudents = ['bernice', 'aaron', 'cody']\n\nfor student in students: # Hey this is a for-loop. We'll study it later.\n    print(\"Hello, \" + student.title() + \"!\")\n```\n\n### Naming and defining a list\nSince lists are collection of objects, it is good practice to give them a plural name. If each item in your list is a car, call the list 'cars'. If each item is a dog, call your list 'dogs'. This gives you a straightforward way to refer to the entire list ('dogs'), and to a single item in the list ('dog').\n\nIn Python, square brackets designate a list. To define a list, you give the name of the list, the equals sign, and the values you want to include in your list within square brackets.\n\n** Exercise **:\n- Declare a list of numbers\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n```\n\n### Accessing one item in a list\nItems in a list are identified by their position in the list, **starting with zero**. This will almost certainly trip you up at some point. Believe it or not, programmers even joke about how often we all make \"off-by-one\" errors, so don't feel bad when you make this kind of error.\n\nTo access the first element in a list, you give the name of the list, followed by a zero in parentheses.\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n\ndog = dogs[0]\nprint(dog.title())\n```\n\nThe number in parentheses is called the _index_ of the item. Because lists start at zero, the index of an item is always one less than its position in the list. So to get the second item in the list, we need to use an index of 1.\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n\ndog = dogs[1]\nprint(dog.title())\n```\n\n### Accessing the last items in a list\nYou can probably see that to get the last item in this list, we would use an index of 2. This works, but it would only work because our list has exactly three items. To get the last item in a list, no matter how long the list is, you can use an index of -1. (Negative index are not quite common in programming languages. )\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n\ndog = dogs[-1]\nprint(dog.title())\n```\n\nThis syntax also works for the second to last item, the third to last, and so forth.\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n\ndog = dogs[-2]\nprint(dog.title())\n```\n\nYou cannot use a number larger than the length of the list.\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n\ndog = dogs[3]\nprint(dog.title())\n```\n\nSimilarly, you can't use a negative number larger than the length of the list.\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n\ndog = dogs[-4]\nprint(dog.title())\n```\n\n## Lists and Looping\n\n### Accessing all elements in a list\nThis is one of the most important concepts related to lists. You can have a list with a million items in it, and in three lines of code you can write a sentence for each of those million items. If you want to understand lists, and become a competent programmer, make sure you take the time to understand this section.\n\nWe use a loop to access all the elements in a list. A loop is a block of code that repeats itself until it runs out of items to work with, or until a certain condition is met. In this case, our loop will run once for every item in our list. With a list that is three items long, our loop will run three times.\n\nLet's take a look at how we access all the items in a list, and then try to understand how it works.\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n\nfor dog in dogs:\n    print(dog) # hey, why is this line indented?\n```\n\nWe have already seen how to create a list, so we are really just trying to understand how the last two lines work. These last two lines make up a loop, and the language here can help us see what is happening:\n```python\n    for dog in dogs:\n```\n- The keyword \"for\" tells Python to get ready to use a loop.\n- The variable \"dog\", with no \"s\" on it, is a temporary placeholder variable. This is the variable that Python will place each item in the list into, one at a time.\n- The first time through the loop, the value of \"dog\" will be 'border collie'.\n- The second time through the loop, the value of \"dog\" will be 'australian cattle dog'.\n- The third time through, \"dog\" will be 'labrador retriever'.\n- After this, there are no more items in the list, and the loop will end.\n\n### Doing more with each item\n\nWe can do whatever we want with the value of \"dog\" inside the loop. In this case, we just print the name of the dog.\n```python\n    print(dog)\n```\nWe are not limited to just printing the word dog. We can do whatever we want with this value, and this action will be carried out for every item in the list. Let's say something about each dog in our list.\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n\nfor dog in dogs:\n    print('I like ' + dog + 's.')\n```\n\n### Inside and outside the loop\n\nPython uses **indentation** to decide what is inside the loop and what is outside the loop. Code that is inside the loop will be run for every item in the list. Code that is not indented, which comes after the loop, will be run once just like regular code.\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n\nfor dog in dogs:\n    # are we doing two or three things per iteration?\n    print('I like ' + dog + 's.')\n    print('No, I really really like ' + dog +'s!\\n')\n    \nprint(\"\\nThat's just how I feel about dogs.\")\n```\n\n\n```python\n# how about this version?\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n\nfor dog in dogs:\n    # how about writing the code in this way?\n    print('I like ' + dog + 's.')\nprint('No, I really really like ' + dog +'s!\\n')\n    \nprint(\"\\nThat's just how I feel about dogs.\")\n```\n\nBy the way, indentation in Python really matters. Please pay attention to it when writing Python. We should be consistent: if we use two spaces for one level of indentation on one line, don't use three or four or other amount of spaces on other lines.\n\n\n\nYou may be intersted in this article: \n[https://stackoverflow.blog/2017/06/15/developers-use-spaces-make-money-use-tabs/](https://stackoverflow.blog/2017/06/15/developers-use-spaces-make-money-use-tabs/)\n\n### Enumerating a list\nWhen you are looping through a list, you may want to know the index of the current item. You could always use the *list.index(value)* syntax, but there is a simpler way. The *enumerate()* function tracks the index of each item for you, as it loops through the list:\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n\nprint(\"Results for the dog show are as follows:\\n\")\nfor index, dog in enumerate(dogs):\n    place = str(index)\n    print(\"Place: \" + place + \" Dog: \" + dog.title())\n```\n\nTo enumerate a list, you need to add an *index* variable to hold the current index. So instead of\n```python\n    for dog in dogs:\n```\n    \nYou have\n```python\n    for index, dog in enumerate(dogs)\n ```\n \nThe value in the variable *index* is always an integer. If you want to print it in a string, you have to turn the integer into a string:\n```python\n    str(index)\n```\n    \nThe index always starts at 0, so in this example the value of *place* should actually be the current index, plus one:\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n\nprint(\"Results for the dog show are as follows:\\n\")\nfor index, dog in enumerate(dogs):\n    place = str(index + 1)\n    print(\"Place: \" + place + \" Dog: \" + dog.title())\n```\n\nList enumeration is particularly useful when a data is represented by multiple elements from different arrays (not a good practice, though). For instance: \n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\nbark = ['bark', 'bark bark', 'bark bark bark']\n\nprint('Barking dogs:\\n')\nfor index, dog in enumerate(dogs):\n      print(dogs[index] + ': ' + bark[index])\n```\n\n## Common list operations\n\n### Modifying elements in a list\nYou can change the value of any element in a list if you know the position of that item.\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n\ndogs[0] = 'australian shepherd'\nprint(dogs)\n```\n\n### Finding an element in a list\nIf you want to find out the position of an element in a list, you can use the index() function.\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n\nprint(dogs.index('australian cattle dog')) # the function index() here is not the variable 'index' we used in the previous examples\n```\n\nThis method returns a ValueError if the requested item is not in the list.\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n\nprint(dogs.index('poodle'))\n```\n\n### Testing whether an item is in a list\nYou can test whether an item is in a list using the \"in\" keyword. This will become more useful after learning how to use if-else statements.\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n\nprint('australian cattle dog' in dogs)\nprint('poodle' in dogs)\n```\n\n### Adding items to a list\n#### Appending items to the end of a list\nWe can add an item to a list using the append() method. This method adds the new item to the end of the list.\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\ndogs.append('poodle')\n\nfor dog in dogs:\n    print(dog.title() + \"s are cool.\")\n```\n\n#### Inserting items into a list\nWe can also insert items anywhere we want in a list, using the **insert()** function. We specify the position we want the item to have, and everything from that point on is shifted one position to the right. In other words, the index of every item after the new item is increased by one.\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\ndogs.insert(1, 'poodle')\n\nprint(dogs)\n```\n\nNote that you have to give the position of the new item first, and then the value of the new item. If you do it in the reverse order, you will get an error.\n\n### Creating an empty list\nNow that we know how to add items to a list after it is created, we can use lists more dynamically. We are no longer stuck defining our entire list at once.\n\nA common approach with lists is to define an empty list, and then let your program add items to the list as necessary. This approach works, for example, when starting to build an interactive web site. Your list of users might start out empty, and then as people register for the site it will grow. This is a simplified approach to how web sites actually work, but the idea is realistic.\n\nHere is a brief example of how to start with an empty list, start to fill it up, and work with the items in the list. The only new thing here is the way we define an empty list, which is just an empty set of square brackets.\n\n\n```python\n# Create an empty list to hold our users.\nusernames = []\n\n# Add some users.\nusernames.append('bernice')\nusernames.append('cody')\nusernames.append('aaron')\n\n# Greet all of our users.\nfor username in usernames:\n    print(\"Welcome, \" + username.title() + '!')\n```\n\nIf we don't change the order in our list, we can use the list to figure out who our oldest and newest users are.\n\n\n```python\n# Create an empty list to hold our users.\nusernames = []\n\n# Add some users.\nusernames.append('bernice')\nusernames.append('cody')\nusernames.append('aaron')\n\n# Greet all of our users.\nfor username in usernames:\n    print(\"Welcome, \" + username.title() + '!')\n\n# Recognize our first user, and welcome our newest user.\nprint(\"\\nThank you for being our very first user, \" + usernames[0].title() + '!')\nprint(\"And a warm welcome to our newest user, \" + usernames[-1].title() + '!')\n```\n\nNote that the code welcoming our newest user will always work, because we have used the index -1. If we had used the index 2 we would always get the third user, even as our list of users grows and grows.\n\n### Sorting a List\nWe can sort a list alphabetically, in either order.\n\n\n```python\nstudents = ['bernice', 'aaron', 'cody']\n\n# Put students in alphabetical order.\nstudents.sort()\n\n# Display the list in its current order.\nprint(\"Our students are currently in alphabetical order.\")\nfor student in students:\n    print(student.title())\n\n#Put students in reverse alphabetical order.\nstudents.sort(reverse=True)\n\n# Display the list in its current order.\nprint(\"\\nOur students are now in reverse alphabetical order.\")\nfor student in studenbts:\n    print(student.title())\n```\n\n#### *sorted()* vs. *sort()*\nWhenever you consider sorting a list using sort(), keep in mind that you can not recover the original order. If you want to display a list in sorted order, but preserve the original order, you can use the *sorted()* function. The *sorted()* function also accepts the optional *reverse=True* argument. Please note that sorted() is not a function of the list datastructure.\n\n\n```python\nstudents = ['bernice', 'aaron', 'cody']\n\n# Display students in alphabetical order, but keep the original order.\nprint(\"Here is the list in alphabetical order:\")\nfor student in sorted(students):\n    print(student.title())\n\n# Display students in reverse alphabetical order, but keep the original order.\nprint(\"\\nHere is the list in reverse alphabetical order:\")\nfor student in sorted(students, reverse=True):\n    print(student.title())\n\nprint(\"\\nHere is the list in its original order:\")\n# Show that the list is still in its original order.\nfor student in students:\n    print(student.title())\n```\n\n#### Reversing a list\nWe have seen three possible orders for a list:\n- The original order in which the list was created\n- Alphabetical order\n- Reverse alphabetical order\n\nThere is one more order we can use, and that is the reverse of the original order of the list. The *reverse()* function gives us this order.\n\n\n```python\nstudents = ['bernice', 'aaron', 'cody']\nstudents.reverse()\n\nprint(students)\n```\n\nNote that reverse is permanent, although you could follow up with another call to *reverse()* and get back the original order of the list.\n\n#### Sorting a numerical list\nAll of the sorting functions work for numerical lists as well.\n\n\n```python\nnumbers = [1, 3, 4, 2]\n\n# sort() puts numbers in increasing order.\nnumbers.sort()\nprint(numbers)\n\n# sort(reverse=True) puts numbers in decreasing order.\nnumbers.sort(reverse=True)\nprint(numbers)\n\n```\n\n\n```python\nnumbers = [1, 3, 4, 2]\n\n# sorted() preserves the original order of the list:\nprint(sorted(numbers))\nprint(numbers)\n```\n\n\n```python\nnumbers = [1, 3, 4, 2]\n\n# The reverse() function also works for numerical lists.\nnumbers.reverse()\nprint(numbers)\n```\n\n** Exercise **:\n- Write a program to find the 2nd largest of an integer array.\n- If the array is not large enough, print \"Not enough data\"; print the result otherwise.\n\nFor example, suppose the interger array (<code>intarray</code>) is:\nintarray = [1, 2, 3, 4, 5, 6, 7, 9, 10]\n\nThe result should be 9.\n\n### Finding the length of a list\nYou can find the length of a list using the *len()* function.\n\n\n```python\nusernames = ['bernice', 'cody', 'aaron']\nuser_count = len(usernames)\n\nprint(user_count)\n```\n\nThere are many situations where you might want to know how many items in a list. If you have a list that stores your users, you can find the length of your list at any time, and know how many users you have.\n\n\n```python\n# Create an empty list to hold our users.\nusernames = []\n\n# Add some users, and report on how many users we have.\nusernames.append('bernice')\nuser_count = len(usernames)\n\nprint(\"We have \" + str(user_count) + \" user!\")\n\nusernames.append('cody')\nusernames.append('aaron')\nuser_count = len(usernames)\n\nprint(\"We have \" + str(user_count) + \" users!\")\n```\n\nOn a technical note, the *len()* function returns an integer, which can't be printed directly with strings. We use the *str()* function to turn the integer into a string so that it prints nicely:\n\n\n```python\nusernames = ['bernice', 'cody', 'aaron']\nuser_count = len(usernames)\n\nprint(\"This will cause an error: \" + user_count)\n```\n\n\n```python\nusernames = ['bernice', 'cody', 'aaron']\nuser_count = len(usernames)\n\nprint(\"This will work: \" + str(user_count))\n```\n\n### Removing Items from a List\nHopefully you can see by now that lists are a dynamic structure. We can define an empty list and then fill it up as information comes into our program. To become really dynamic, we need some ways to remove items from a list when we no longer need them. You can remove items from a list through their position, or through their value.\n\n#### Removing items by position\nIf you know the position of an item in a list, you can remove that item using the *del* command. To use this approach, give the command *del* and the name of your list, with the index of the item you want to move in square brackets:\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n# Remove the first dog from the list.\ndel dogs[0]\n\nprint(dogs)\n```\n\n#### Removing items by value\nYou can also remove an item from a list if you know its value. To do this, we use the *remove()* function. Give the name of the list, followed by the word remove with the value of the item you want to remove in parentheses. Python looks through your list, finds the first item with this value, and removes it.\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n# Remove australian cattle dog from the list.\ndogs.remove('australian cattle dog')\n\nprint(dogs)\n```\n\nBe careful to note, however, that *only* the first item with this value is removed. If you have multiple items with the same value, you will have some items with this value left in your list.\n\n\n```python\nletters = ['a', 'b', 'c', 'a', 'b', 'c']\n# Remove the letter a from the list.\nletters.remove('a')\n\nprint(letters)\n```\n\n### Popping items from a list\n\nThere is a cool concept in programming called \"popping\" items from a collection. Every programming language has some sort of data structure similar to Python's lists. All of these structures can be used as queues, and there are various ways of processing the items in a queue.\n\nOne simple approach is to start with an empty list, and then add items to that list. When you want to work with the items in the list, you always take the last item from the list, do something with it, and then remove that item. The *pop()* function makes this easy. It removes the last item from the list, and gives it to us so we can work with it. This is easier to show with an example:\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\nlast_dog = dogs.pop()\n\nprint(last_dog)\nprint(dogs)\n```\n\nThis is an example of a first-in, last-out approach. The first item in the list would be the last item processed if you kept using this approach. We will see a full implementation of this approach later on, when we learn about *while* loops.\n\nYou can actually pop any item you want from a list, by giving the index of the item you want to pop. So we could do a first-in, first-out approach by popping the first iem in the list:\n\n\n```python\ndogs = ['border collie', 'australian cattle dog', 'labrador retriever']\nfirst_dog = dogs.pop(0)\n\nprint(first_dog)\nprint(dogs)\n```\n\n** Exercise **:\n- Write code to delete consecutive duplicates of list elements\n\nFor example, given:\nx = [1, 1, 2, 3, 4, 5, 6, 6, 6, 7]\n\nThe result should be:\n[1, 2, 3, 4, 5, 6, 7]\n\n** Exercise **:\n- Write code to duplicate the elements of a list\n\nFor example, given:\nx = [1, 1, 2, 3, 4, 5, 6, 6, 6, 7]\n\nThe result should be:\n[1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7]\n\n### Slicing a List\nSince a list is a collection of items, we should be able to get any subset of those items. For example, if we want to get just the first three items from the list, we should be able to do so easily. The same should be true for any three items in the middle of the list, or the last three items, or any x items from anywhere in the list. These subsets of a list are called *slices*.\n\nTo get a subset of a list, we give the position of the first item we want, and the position of the first item we do *not* want to include in the subset. So the slice *list[0:3]* will return a list containing items 0, 1, and 2, but not item 3. Here is how you get a batch containing the first three items.\n\n\n```python\nusernames = ['bernice', 'cody', 'aaron', 'ever', 'dalia']\n\n# Grab the first three users in the list.\nfirst_batch = usernames[0:3]\n\nfor user in first_batch:\n    print(user.title())\n```\n\nIf you want to grab everything up to a certain position in the list, you can also leave the first index blank:\n\n\n```python\nusernames = ['bernice', 'cody', 'aaron', 'ever', 'dalia']\n\n# Grab the first three users in the list.\nfirst_batch = usernames[:3]\n\nfor user in first_batch:\n    print(user.title())\n```\n\nWhen we grab a slice from a list, the original list is not affected:\n\n\n```python\nusernames = ['bernice', 'cody', 'aaron', 'ever', 'dalia']\n\n# Grab the first three users in the list.\nfirst_batch = usernames[0:3]\n\n# The original list is unaffected.\nfor user in usernames:\n    print(user.title())\n```\n\nWe can get any segment of a list we want, using the slice method:\n\n\n```python\nusernames = ['bernice', 'cody', 'aaron', 'ever', 'dalia']\n\n# Grab a batch from the middle of the list.\nmiddle_batch = usernames[1:4]\n\nfor user in middle_batch:\n    print(user.title())\n```\n\nTo get all items from one position in the list to the end of the list, we can leave off the second index:\n\n\n```python\nusernames = ['bernice', 'cody', 'aaron', 'ever', 'dalia']\n\n# Grab all users from the third to the end.\nend_batch = usernames[2:]\n\nfor user in end_batch:\n    print(user.title())\n```\n\n### Copying a list (Please pay attention to this section)\nYou can use the slice notation to make a copy of a list, by leaving out both the starting and the ending index. This causes the slice to consist of everything from the first item to the last, which is the entire list.\n\n\n```python\nusernames = ['bernice', 'cody', 'aaron', 'ever', 'dalia']\n\n# Make a copy of the list.\ncopied_usernames = usernames[:]\nprint(\"The full copied list:\\n\\t\", copied_usernames)\n\n# Remove the first two users from the copied list.\ndel copied_usernames[0]\ndel copied_usernames[0]\nprint(\"\\nTwo users removed from copied list:\\n\\t\", copied_usernames)\n\n# The original list is unaffected.\nprint(\"\\nThe original list:\\n\\t\", usernames)\n```\n\n## Numerical lists\nThere is nothing special about lists of numbers, but there are some functions you can use to make working with numerical lists more efficient. Let's make a list of the first ten numbers, and start working with it to see how we can use numbers in a list.\n\n\n```python\n# Print out the first ten numbers.\nnumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\nfor number in numbers:\n    print(number)\n```\n\n** Exercise **:\n- Shift the elements of an integer list by one to the left, and then increment the value of each cell by its new index. The rightmost element of the original list should be placed at the end after shifting.\n\nFor example,\nx = [1, 2, 3, 4]\n\nAfter shifting, the result should be:\n[2, 3, 4, 1]\n\nThe final result should be:\n[2, 4, 6, 4]\n\n### The *range()* function\nThis works, but it is not very efficient if we want to work with a large set of numbers. The *range()* function helps us generate long lists of numbers. Here are two ways to do the same thing, using the *range* function.\n\n\n```python\n# Print the first ten numbers.\nfor number in range(1,11):\n    print(number)\n```\n\nThe range function takes in a starting number, and an end number. You get all integers, up to but not including the end number. You can also add a *step* value, which tells the *range* function how big of a step to take between numbers:\n\n\n```python\n# Print the first ten odd numbers.\nfor number in range(1,21,2):\n    print(number)\n```\n\nIf we want to store these numbers in a list, we can use the *list()* function. This function takes in a range, and turns it into a list:\n\n\n```python\n# Create a list of the first ten numbers.\nnumbers = list(range(1,11))\nprint(numbers)\n```\n\nThis is incredibly powerful; we can now create a list of the first million numbers, just as easily as we made a list of the first ten numbers. It doesn't really make sense to print the million numbers here, but we can show that the list really does have one million items in it, and we can print the last ten items to show that the list is correct.\n\n\n```python\n# Store the first million numbers in a list.\nnumbers = list(range(1,1000001))\n\n# Show the length of the list:\nprint(\"The list 'numbers' has \" + str(len(numbers)) + \" numbers in it.\")\n\n# Show the last ten numbers:\nprint(\"\\nThe last ten numbers in the list are:\")\nfor number in numbers[-10:]:\n    print(number)\n```\n\nThere are two things here that might be a little unclear. The expression\n\n    str(len(numbers))\n\ntakes the length of the *numbers* list, and turns it into a string that can be printed.\n\nThe expression \n\n    numbers[-10:]\n\ngives us a *slice* of the list. The index `-1` is the last item in the list, and the index `-10` is the item ten places from the end of the list. So the slice `numbers[-10:]` gives us everything from that item to the end of the list.\n\n** Exercise **:\n- Split a list into two. The first list should contain N randomly drawn elements from the original list of length L; whereas the second list should contain the remaining (L-N) elements in the original list.\n\nYou can use the following code to generate a list of random integers (please modify it according to your need):\n\n\n```python\nimport numpy as np\n\nnp.random.randint(low=0,high=10,size=10)\n```\n\n### The *min()*, *max()*, and *sum()* functions\n\nThere are three functions you can easily use with numerical lists. As you might expect, the *min()* function returns the smallest number in the list, the *max()* function returns the largest number in the list, and the *sum()* function returns the total of all numbers in the list.\n\n\n```python\nages = [23, 16, 14, 28, 19, 11, 38]\n\nyoungest = min(ages)\noldest = max(ages)\ntotal_years = sum(ages)\n\nprint(\"Our youngest reader is \" + str(youngest) + \" years old.\")\nprint(\"Our oldest reader is \" + str(oldest) + \" years old.\")\nprint(\"Together, we have \" + str(total_years) + \" years worth of life experience.\")\n```\n\n## List comprehensions\nIf you are brand new to programming, list comprehensions may look confusing at first. They are a shorthand way of creating and working with lists. It is good to be aware of list comprehensions, because you will see them in other people's code, and they are really useful when you understand how to use them. That said, if they don't make sense to you yet, don't worry about using them right away. When you have worked with enough lists, you will want to use comprehensions. For now, it is good enough to know they exist, and to recognize them when you see them. If you like them, go ahead and start trying to use them now. (Using list comprehensions is a more idiomatic way of programming in Python.)\n\n### Numerical comprehensions\nLet's consider how we might make a list of the first ten square numbers. We could do it like this:\n\n\n```python\n# Store the first ten square numbers in a list.\n# Make an empty list that will hold our square numbers.\nsquares = []\n\n# Go through the first ten numbers, square them, and add them to our list.\nfor number in range(1,11):\n    new_square = number**2\n    squares.append(new_square)\n    \n# Show that our list is correct.\nfor square in squares:\n    print(square)\n```\n\nThis should make sense at this point. If it doesn't, go over the code with these thoughts in mind:\n- We make an empty list called *squares* that will hold the values we are interested in.\n- Using the *range()* function, we start a loop that will go through the numbers 1-10.\n- Each time we pass through the loop, we find the square of the current number by raising it to the second power.\n- We add this new value to our list *squares*.\n- We go through our newly-defined list and print out each square.\n\nNow let's make this code more efficient. We don't really need to store the new square in its own variable *new_square*; we can just add it directly to the list of squares. The line\n\n    new_square = number**2\n\nis taken out, and the next line takes care of the squaring:\n\n\n```python\n# Store the first ten square numbers in a list.\n# Make an empty list that will hold our square numbers.\nsquares = []\n\n# Go through the first ten numbers, square them, and add them to our list.\nfor number in range(1,11):\n    squares.append(number**2)\n    \n# Show that our list is correct.\nfor square in squares:\n    print(square)\n```\n\nList comprehensions allow us to collapse the first three lines of code into one line. Here's what it looks like:\n\n\n```python\n# Store the first ten square numbers in a list.\nsquares = [number**2 for number in range(1,11)]\n\n# Show that our list is correct.\nfor square in squares:\n    print(square)\n```\n\nIt should be pretty clear that this code is more efficient than our previous approach, but it may not be clear what is happening. Let's take a look at everything that is happening in that first line:\n\nWe define a list called *squares*.\n\nLook at the second part of what's in square brackets:\n```python\n    for number in range(1,11)\n```\nThis sets up a loop that goes through the numbers 1-10, storing each value in the variable *number*. Now we can see what happens to each *number* in the loop:\n```python\n    number**2\n```\nEach number is raised to the second power, and this is the value that is stored in the list we defined. We might read this line in the following way:\n\nsquares = [raise *number* to the second power, for each *number* in the range 1-10]\n\nOr more mathematical:\n\\begin{align}\n\\text{squares} &= \\{x^2  |  x \\in \\mathbb{Z} \\land x >=1 \\land x<10\\}\n\\end{align}\n\nIt is probably helpful to see a few more examples of how comprehensions can be used. Let's try to make the first ten even numbers, the longer way:\n\n\n```python\n# Make an empty list that will hold the even numbers.\nevens = []\n\n# Loop through the numbers 1-10, double each one, and add it to our list.\nfor number in range(1,11):\n    evens.append(number*2)\n    \n# Show that our list is correct:\nfor even in evens:\n    print(even)\n```\n\nHere's how we might think of doing the same thing, using a list comprehension:\n\nevens = [multiply each *number* by 2, for each *number* in the range 1-10]\n\nHere is the same line in code:\n\n\n```python\n# Make a list of the first ten even numbers.\nevens = [number*2 for number in range(1,11)]\n\nfor even in evens:\n    print(even)\n```\n\n### Non-numerical comprehensions\nWe can use comprehensions with non-numerical lists as well. In this case, we will create an initial list, and then use a comprehension to make a second list from the first one. Here is a simple example, without using comprehensions:\n\n\n```python\n# Consider some students.\nstudents = ['bernice', 'aaron', 'cody']\n\n# Let's turn them into great students.\ngreat_students = []\nfor student in students:\n    great_students.append(student.title() + \" the great!\")\n\n# Let's greet each great student.\nfor great_student in great_students:\n    print(\"Hello, \" + great_student)\n```\n\nTo use a comprehension in this code, we want to write something like this:\n\ngreat_students = [add 'the great' to each *student*, for each *student* in the list of *students*]\n\nHere's what it looks like:\n\n\n```python\n# Consider some students.\nstudents = ['bernice', 'aaron', 'cody']\n\n# Let's turn them into great students.\ngreat_students = [student.title() + \" the great!\" for student in students]\n\n# Let's greet each great student.\nfor great_student in great_students:\n    print(\"Hello, \" + great_student)\n```\n\n## Strings as Lists\n\nNow that you have some familiarity with lists, we can take a second look at strings. A string is really a list of characters, so many of the concepts from working with lists behave the same with strings.\n\n### Strings as a list of characters\nWe can loop through a string using a *for* loop, just like we loop through a list:\n\n\n```python\nmessage = \"Hello!\"\n\nfor letter in message:\n    print(letter)\n```\n\nWe can create a list from a string. The list will have one element for each character in the string:\n\n\n```python\nmessage = \"Hello world!\"\n\nmessage_list = list(message)\nprint(message_list)\n```\n\n### Slicing strings\nWe can access any character in a string by its position, just as we access individual items in a list:\n\n\n```python\nmessage = \"Hello World!\"\nfirst_char = message[0]\nlast_char = message[-1]\n\nprint(first_char, last_char)\n```\n\nWe can extend this to take slices of a string:\n\n\n```python\nmessage = \"Hello World!\"\nfirst_three = message[:3]\nlast_three = message[-3:]\n\nprint(first_three, last_three)\n```\n\n### Finding substrings\nNow that you have seen what indexes mean for strings, we can search for *substrings*. A substring is a series of characters that appears in a string.\n\nYou can use the *in* keyword to find out whether a particular substring appears in a string:\n\n\n```python\nmessage = \"I like cats and dogs.\"\ndog_present = 'dog' in message\nprint(dog_present)\n```\n\nIf you want to know where a substring appears in a string, you can use the *find()* method. The *find()* method tells you the index at which the substring begins.\n\n\n```python\nmessage = \"I like cats and dogs.\"\ndog_index = message.find('dog')\nprint(dog_index)\n```\n\nNote, however, that this function only returns the index of the first appearance of the substring you are looking for. If the substring appears more than once, you will miss the other substrings.\n\n\n```python\nmessage = \"I like cats and dogs, but I'd much rather own a dog.\"\ndog_index = message.find('dog')\nprint(dog_index)\n```\n\nIf you want to find the last appearance of a substring, you can use the *rfind()* function:\n\n\n```python\nmessage = \"I like cats and dogs, but I'd much rather own a dog.\"\nlast_dog_index = message.rfind('dog')\nprint(last_dog_index)\n```\n\n### Replacing substrings\nYou can use the *replace()* function to replace any substring with another substring. To use the *replace()* function, give the substring you want to replace, and then the substring you want to replace it with. You also need to store the new string, either in the same string variable or in a new variable.\n\n\n```python\nmessage = \"I like cats and dogs, but I'd much rather own a dog.\"\nmessage = message.replace('dog', 'snake')\nprint(message)\n```\n\n### Counting substrings\nIf you want to know how many times a substring appears within a string, you can use the *count()* method.\n\n\n```python\nmessage = \"I like cats and dogs, but I'd much rather own a dog.\"\nnumber_dogs = message.count('dog')\nprint(number_dogs)\n```\n\n### Splitting strings\nStrings can be split into a set of substrings when they are separated by a repeated character. If a string consists of a simple sentence, the string can be split based on spaces. The *split()* function returns a list of substrings. The *split()* function takes one argument, the character that separates the parts of the string.\n\n\n```python\nmessage = \"I like cats and dogs, but I'd much rather own a dog.\"\nwords = message.split(' ')\nprint(words)\n```\n\nNotice that the punctuation is left in the substrings.\n\nIt is more common to split strings that are really lists, separated by something like a comma. The *split()* function gives you an easy way to turn comma-separated strings, which you can't do much with in Python, into lists. Once you have your data in a list, you can work with it in much more powerful ways.\n\n\n```python\nanimals = \"dog, cat, tiger, mouse, liger, bear\"\n\n# Rewrite the string as a list, and store it in the same variable\nanimals = animals.split(',')\nprint(animals)\n```\n\nNotice that in this case, the spaces are also ignored. It is a good idea to test the output of the *split()* function and make sure it is doing what you want with the data you are interested in.\n\nOne use of this is to work with spreadsheet data in your Python programs. Most spreadsheet applications allow you to dump your data into a comma-separated text file. You can read this file into your Python program, or even copy and paste from the text file into your program file, and then turn the data into a list. You can then process your spreadsheet data using a *for* loop.\n\n### Other string methods\nThere are a number of [other string methods](https://docs.python.org/3.8/library/stdtypes.html#string-methods) that we won't go into right here, but you might want to take a look at them. Most of these methods should make sense to you at this point. You might not have use for any of them right now, but it is good to know what you can do with strings. This way you will have a sense of how to solve certain problems, even if it means referring back to the list of methods to remind yourself how to write the correct syntax when you need it.\n\n## Tuples\nTuples are basically lists that can never be changed. Lists are quite dynamic; they can grow as you append and insert items, and they can shrink as you remove items. You can modify any element you want to in a list. Sometimes we like this behavior, but other times we may want to ensure that no user or no part of a program can change a list. That's what tuples are for.\n\nTechnically, lists are *mutable* objects and tuples are *immutable* objects. Mutable objects can change (think of *mutations*), and immutable objects can not change.\n\n### Defining tuples, and accessing elements\n\nYou define a tuple just like you define a list, except you use parentheses instead of square brackets. Once you have a tuple, you can access individual elements just like you can with a list, and you can loop through the tuple with a *for* loop:\n\n\n```python\ncolors = ('red', 'green', 'blue')\nprint(\"The first color is: \" + colors[0])\n\nprint(\"\\nThe available colors are:\")\nfor color in colors:\n    print(\"- \" + color)\n```\n\nIf you try to add something to a tuple, you will get an error:\n\n\n```python\ncolors = ('red', 'green', 'blue')\ncolors.append('purple')\n```\n\nThe same kind of thing happens when you try to remove something from a tuple, or modify one of its elements. Once you define a tuple, you can be confident that its values will not change.\n\n### Using tuples to make strings\nWe have seen that it is pretty useful to be able to mix raw English strings with values that are stored in variables, as in the following:\n\n\n```python\nanimal = 'dog'\nprint(\"I have a \" + animal + \".\")\n```\n\nThis was especially useful when we had a series of similar statements to make:\n\n\n```python\nanimals = ['dog', 'cat', 'bear']\nfor animal in animals:\n    print(\"I have a \" + animal + \".\")\n```\n\nI like this approach of using the plus sign to build strings because it is fairly intuitive. We can see that we are adding several smaller strings together to make one longer string. This is intuitive, but it is a lot of typing. There is a shorter way to do this, using *placeholders*.\n\nPython ignores most of the characters we put inside of strings. There are a few characters that Python pays attention to, as we saw with strings such as \"\\t\" and \"\\n\". Python also pays attention to \"%s\" and \"%d\". These are placeholders. When Python sees the \"%s\" placeholder, it looks ahead and pulls in the first argument after the % sign:\n\n\n```python\nanimal = 'dog'\nprint(\"I have a %s.\" % animal)\n```\n\nThis is a much cleaner way of generating strings that include values. We compose our sentence all in one string, and then tell Python what values to pull into the string, in the appropriate places.\n\nThis is called *string formatting*, and it looks the same when you use a list:\n\n\n```python\nanimals = ['dog', 'cat', 'bear']\nfor animal in animals:\n    print(\"I have a %s.\" % animal)\n```\n\nIf you have more than one value to put into the string you are composing, you have to pack the values into a tuple:\n\n\n```python\nanimals = ['dog', 'cat', 'bear']\nprint(\"I have a %s, a %s, and a %s.\" % (animals[0], animals[1], animals[2]))\n```\n\n### String formatting with numbers\n\nIf you recall, printing a number with a string can cause an error:\n\n\n```python\nnumber = 23\nprint(\"My favorite number is \" + number + \".\")\n```\n\nPython knows that you could be talking about the value 23, or the characters '23'. So it throws an error, forcing us to clarify that we want Python to treat the number as a string. We do this by *casting* the number into a string using the *str()* function:\n\n\n```python\nnumber = 23\nprint(\"My favorite number is \" + str(number) + \".\")\n```\n\nThe format string \"%d\" takes care of this for us. Watch how clean this code is:\n\n\n```python\nnumber = 23\nprint(\"My favorite number is %d.\" % number)\n```\n\nIf you want to use a series of numbers, you pack them into a tuple just like we saw with strings:\n\n\n```python\nnumbers = [7, 23, 42]\nprint(\"My favorite numbers are %d, %d, and %d.\" % (numbers[0], numbers[1], numbers[2]))\n```\n\nJust for clarification, look at how much longer the code is if you use concatenation instead of string formatting:\n\n\n```python\nnumbers = [7, 23, 42]\nprint(\"My favorite numbers are \" + str(numbers[0]) + \", \" + str(numbers[1]) + \", and \" + str(numbers[2]) + \".\")\n```\n\nYou can mix string and numerical placeholders in any order you want.\n\n\n```python\nnames = ['Ada', 'ever']\nnumbers = [23, 2]\nprint(\"%s's favorite number is %d, and %s's favorite number is %d.\" % (names[0].title(), numbers[0], names[1].title(), numbers[1]))\n```\n\nThere are more sophisticated ways to do string formatting in Python 3, but we will save that for later because it's a bit less intuitive than this approach. For now, you can use whichever approach consistently gets you the output that you want to see.\n\n## If Statements\nBy allowing you to respond selectively to different situations and conditions, if statements open up whole new possibilities for your programs. In this section, you will learn how to test for certain conditions, and then respond in appropriate ways to those conditions.\n\n### What is an *if* statement?\nAn *if* statement tests for a condition, and then responds to that condition. If the condition is true, then whatever action is listed next gets carried out. You can test for multiple conditions at the same time, and respond appropriately to each condition.\n\nHere is an example that shows a number of the desserts I like. It lists those desserts, but lets you know which one is my favorite.\n\n\n```python\n# A list of desserts I like.\ndesserts = ['ice cream', 'chocolate', 'apple crisp', 'cookies']\nfavorite_dessert = 'apple crisp'\n\n# Print the desserts out, but let everyone know my favorite dessert.\nfor dessert in desserts:\n    if dessert == favorite_dessert:\n        # This dessert is my favorite, let's let everyone know!\n        print(\"%s is my favorite dessert!\" % dessert.title())\n    else:\n        # I like these desserts, but they are not my favorite.\n        print(\"I like %s.\" % dessert)\n```\n\n#### What happens in this program?\n\n- The program starts out with a list of desserts, and one dessert is identified as a favorite.\n- The for loop runs through all the desserts.\n- Inside the for loop, each item in the list is tested.\n    - If the current value of *dessert* is equal to the value of *favorite_dessert*, a message is printed that this is my favorite.\n    - If the current value of *dessert* is not equal to the value of *favorite_dessert*, a message is printed that I just like the dessert.\n    \nYou can test as many conditions as you want in an if statement, as you will see in a little bit.\n\n### Logical Tests\nEvery if statement evaluates to *True* or *False*. *True* and *False* are Python keywords, which have special meanings attached to them. You can test for the following conditions in your if statements:\n\n- [equality](#equality) (==)\n- [inequality](#inequality) (!=)\n- [other inequalities](#other_inequalities)\n    - greater than (>)\n    - greater than or equal to (>=)\n    - less than (<)\n    - less than or equal to (<=)\n- [You can test if an item is **in** a list.](#in_list)\n\n\n#### Equality\nTwo items are *equal* if they have the same value. You can test for equality between numbers, strings, and a number of other objects which you will learn about later. Some of these results may be surprising, so take a careful look at the examples below.\n\nIn Python, as in many programming languages, two equals signs tests for equality.\n\n**Watch out!** Be careful of accidentally using one equals sign, which can really throw things off because that one equals sign actually sets your item to the value you are testing for!\n\n\n```python\n5 == 5\n```\n\n\n```python\n3 == 5 \n```\n\n\n```python\n5 == 5.0\n```\n\n\n```python\n'ada' == 'ada'\n```\n\n\n```python\n'Ada' == 'ada'\n```\n\n\n```python\n'Ada'.lower() == 'ada'.lower()\n```\n\n\n```python\n'5' == 5\n```\n\n\n```python\n'5' == str(5)\n```\n\n#### Inequality\nTwo items are *inequal* if they do not have the same value. In Python, we test for inequality using the exclamation point and one equals sign.\n\nSometimes you want to test for equality and if that fails, assume inequality. Sometimes it makes more sense to test for inequality directly.\n\n\n```python\n3 != 5\n```\n\n\n```python\n5 != 5\n```\n\n\n```python\n'Ada' != 'ada'\n```\n\n#### Other Inequalities\n##### greater than\n\n\n```python\n5 > 3\n```\n\n##### greater than or equal to\n\n\n```python\n5 >= 3\n```\n\n\n```python\n3 >= 3\n```\n\n##### less than\n\n\n```python\n3 < 5\n```\n\n##### less than or equal to\n\n\n```python\n3 <= 5\n```\n\n\n```python\n3 <= 3\n```\n\n### Checking if an item is **in** a list\nYou can check if an item is in a list using the **in** keyword.\n\n\n```python\nvowels = ['a', 'e', 'i', 'o', 'u']\n'a' in vowels\n```\n\n\n```python\nvowels = ['a', 'e', 'i', 'o', 'u']\n'b' in vowels\n```\n\n### The if-elif...else chain\nYou can test whatever series of conditions you want to, and you can test your conditions in any combination you want.\n\n### Simple if statements\nThe simplest test has a single **if** statement, and a single statement to execute if the condition is **True**.\n\n\n```python\ndogs = ['willie', 'hootz', 'peso', 'juno']\n\nif len(dogs) > 3:\n    print(\"Wow, we have a lot of dogs here!\")\n```\n\nIn this situation, nothing happens if the test does not pass.\n\n\n```python\ndogs = ['willie', 'hootz']\n\nif len(dogs) > 3:\n    print(\"Wow, we have a lot of dogs here!\")\n```\n\nNotice that there are no errors. The condition `len(dogs) > 3` evaluates to False, and the program moves on to any lines after the **if** block.\n\n### if-else statements\nMany times you will want to respond in two possible ways to a test. If the test evaluates to **True**, you will want to do one thing. If the test evaluates to **False**, you will want to do something else. The **if-else** structure lets you do that easily. Here's what it looks like:\n\n\n```python\ndogs = ['willie', 'hootz', 'peso', 'juno']\n\nif len(dogs) > 3:\n    print(\"Wow, we have a lot of dogs here!\")\nelse:\n    print(\"Okay, this is a reasonable number of dogs.\")\n```\n\nOur results have not changed in this case, because if the test evaluates to **True** only the statements under the **if** statement are executed. The statements under **else** area only executed if the test fails:\n\n\n```python\ndogs = ['willie', 'hootz']\n\nif len(dogs) > 3:\n    print(\"Wow, we have a lot of dogs here!\")\nelse:\n    print(\"Okay, this is a reasonable number of dogs.\")\n```\n\nThe test evaluated to **False**, so only the statement under `else` is run.\n\n### if-elif...else chains\nMany times, you will want to test a series of conditions, rather than just an either-or situation. You can do this with a series of if-elif-else statements\n\nThere is no limit to how many conditions you can test. You always need one if statement to start the chain, and you can never have more than one else statement. But you can have as many elif statements as you want.\n\n\n```python\ndogs = ['willie', 'hootz', 'peso', 'monty', 'juno', 'turkey']\n\nif len(dogs) >= 5:\n    print(\"Holy mackerel, we might as well start a dog hostel!\")\nelif len(dogs) >= 3:\n    print(\"Wow, we have a lot of dogs here!\")\nelse:\n    print(\"Okay, this is a reasonable number of dogs.\")\n```\n\nIt is important to note that in situations like this, only the first test is evaluated. In an if-elif-else chain, once a test passes the rest of the conditions are ignored.\n\n\n```python\ndogs = ['willie', 'hootz', 'peso', 'monty']\n\nif len(dogs) >= 5:\n    print(\"Holy mackerel, we might as well start a dog hostel!\")\nelif len(dogs) >= 3:\n    print(\"Wow, we have a lot of dogs here!\")\nelse:\n    print(\"Okay, this is a reasonable number of dogs.\")\n```\n\nThe first test failed, so Python evaluated the second test. That test passed, so the statement corresponding to `len(dogs) >= 3` is executed.\n\n\n```python\ndogs = ['willie', 'hootz']\n\nif len(dogs) >= 5:\n    print(\"Holy mackerel, we might as well start a dog hostel!\")\nelif len(dogs) >= 3:\n    print(\"Wow, we have a lot of dogs here!\")\nelse:\n    print(\"Okay, this is a reasonable number of dogs.\")\n```\n\nIn this situation, the first two tests fail, so the statement in the else clause is executed. Note that this statement would be executed even if there are no dogs at all:\n\n\n```python\ndogs = []\n\nif len(dogs) >= 5:\n    print(\"Holy mackerel, we might as well start a dog hostel!\")\nelif len(dogs) >= 3:\n    print(\"Wow, we have a lot of dogs here!\")\nelse:\n    print(\"Okay, this is a reasonable number of dogs.\")\n```\n\nNote that you don't have to take any action at all when you start a series of if statements. You could simply do nothing in the situation that there are no dogs by replacing the `else` clause with another `elif` clause:\n\n\n```python\ndogs = []\n\nif len(dogs) >= 5:\n    print(\"Holy mackerel, we might as well start a dog hostel!\")\nelif len(dogs) >= 3:\n    print(\"Wow, we have a lot of dogs here!\")\nelif len(dogs) >= 1:\n    print(\"Okay, this is a reasonable number of dogs.\")\n```\n\nIn this case, we only print a message if there is at least one dog present. Of course, you could add a new `else` clause to respond to the situation in which there are no dogs at all:\n\n\n```python\ndogs = []\n\nif len(dogs) >= 5:\n    print(\"Holy mackerel, we might as well start a dog hostel!\")\nelif len(dogs) >= 3:\n    print(\"Wow, we have a lot of dogs here!\")\nelif len(dogs) >= 1:\n    print(\"Okay, this is a reasonable number of dogs.\")\nelse:\n    print(\"I wish we had a dog here.\")\n```\n\nAs you can see, the if-elif-else chain lets you respond in very specific ways to any given situation.\n\n### More than one passing test\nIn all of the examples we have seen so far, only one test can pass. As soon as the first test passes, the rest of the tests are ignored. This is really good, because it allows our code to run more efficiently. Many times only one condition can be true, so testing every condition after one passes would be meaningless.\n\nThere are situations in which you want to run a series of tests, where every single test runs. These are situations where any or all of the tests could pass, and you want to respond to each passing test. Consider the following example, where we want to greet each dog that is present:\n\n\n```python\ndogs = ['willie', 'hootz']\n\nif 'willie' in dogs:\n    print(\"Hello, Willie!\")\nif 'hootz' in dogs:\n    print(\"Hello, Hootz!\")\nif 'peso' in dogs:\n    print(\"Hello, Peso!\")\nif 'monty' in dogs:\n    print(\"Hello, Monty!\")\n```\n\nIf we had done this using an if-elif-else chain, only the first dog that is present would be greeted:\n\n\n```python\ndogs = ['willie', 'hootz']\n\nif 'willie' in dogs:\n    print(\"Hello, Willie!\")\nelif 'hootz' in dogs:\n    print(\"Hello, Hootz!\")\nelif 'peso' in dogs:\n    print(\"Hello, Peso!\")\nelif 'monty' in dogs:\n    print(\"Hello, Monty!\")\n```\n\nOf course, this could be written much more cleanly using lists and for loops. See if you can follow this code.\n\n\n```python\ndogs_we_know = ['willie', 'hootz', 'peso', 'monty', 'juno', 'turkey']\ndogs_present = ['willie', 'hootz']\n\n# Go through all the dogs that are present, and greet the dogs we know.\nfor dog in dogs_present:\n    if dog in dogs_we_know:\n        print(\"Hello, %s!\" % dog.title())\n```\n\nThis is the kind of code you should be aiming to write. It is fine to come up with code that is less efficient at first. When you notice yourself writing the same kind of code repeatedly in one program, look to see if you can use a loop or a function to make your code more efficient.\n\n## True and False values\nEvery value can be evaluated as True or False. The general rule is that any non-zero or non-empty value will evaluate to True. If you are ever unsure, you can open a Python terminal and write two lines to find out if the value you are considering is True or False. Take a look at the following examples, keep them in mind, and test any value you are curious about. I am using a slightly longer test just to make sure something gets printed each time.\n\n\n```python\nif 0:\n    print(\"This evaluates to True.\")\nelse:\n    print(\"This evaluates to False.\")\n```\n\n\n```python\nif 1:\n    print(\"This evaluates to True.\")\nelse:\n    print(\"This evaluates to False.\")\n```\n\n\n```python\n# Arbitrary non-zero numbers evaluate to True.\nif 1253756:\n    print(\"This evaluates to True.\")\nelse:\n    print(\"This evaluates to False.\")\n```\n\n\n```python\n# Negative numbers are not zero, so they evaluate to True.\nif -1:\n    print(\"This evaluates to True.\")\nelse:\n    print(\"This evaluates to False.\")\n```\n\n\n```python\n# An empty string evaluates to False.\nif '':\n    print(\"This evaluates to True.\")\nelse:\n    print(\"This evaluates to False.\")\n```\n\n\n```python\n# Any other string, including a space, evaluates to True.\nif ' ':\n    print(\"This evaluates to True.\")\nelse:\n    print(\"This evaluates to False.\")\n```\n\n\n```python\n# Any other string, including a space, evaluates to True.\nif 'hello':\n    print(\"This evaluates to True.\")\nelse:\n    print(\"This evaluates to False.\")\n```\n\n\n```python\n# None is a special object in Python. It evaluates to False.\nif None:\n    print(\"This evaluates to True.\")\nelse:\n    print(\"This evaluates to False.\")\n```\n\n** Exercise (the exercises are getting harder from now on) **:\n- Given two strings a and b, find the longest substring in A that can be found in B. The index of the first character of the matched longest substring in B should also be reported.\n\nFor example,\n\na = \"a dream\"\n\nb = \"I have a dream that one day this nation will rise up\"\n\nThe result is \"a dream\". The index of the 'a' in \"a dream\" is 7 in b.\n\n## While Loops\n\n\nA while loop tests an initial condition. If that condition is true, the loop starts executing. Every time the loop finishes, the condition is reevaluated. As long as the condition remains true, the loop keeps executing. As soon as the condition becomes false, the loop stops executing.\n\n### General syntax\n\n\n\n```python\n# Set an initial condition.\ngame_active = True\n\n# Set up the while loop.\nwhile game_active:\n    # Run the game.\n    # At some point, the game ends and game_active will be set to False.\n    #   When that happens, the loop will stop executing.\n    \n# Do anything else you want done after the loop runs.\n```\n\n- Every while loop needs an initial condition that starts out true.\n- The `while` statement includes a condition to test.\n- All of the code in the loop will run as long as the condition remains true.\n- As soon as something in the loop changes the condition such that the test no longer passes, the loop stops executing.\n- Any code that is defined after the loop will run at this point.\n\nHere is a simple example, showing how a game will stay active as long as the player has enough power.\n\n\n```python\n# The player's power starts out at 5.\npower = 5\n\n# The player is allowed to keep playing as long as their power is over 0.\nwhile power > 0:\n    print(\"You are still playing, because your power is %d.\" % power)\n    # Your game code would go here, which includes challenges that make it\n    #   possible to lose power.\n    # We can represent that by just taking away from the power.\n    power = power - 1\n    \nprint(\"\\nOh no, your power dropped to 0! Game Over.\")\n```\n\n** Exercise **:\n- Write the functionally equivalent while-loop version for the following code:\n\n```\nsum = 0\nfor i in range(1, 100, 2):\n    sum = sum + i\n```\n\n** Exercise **:\n- Write the functionally equivalent while-loop version for the following code:\n\n```\nsum = 9999\nfor i in range(100, 0, -1):\n    sum = sum - i\n```\n\n** Exercise **:\n- Write the functionally equivalent while-loop version for the following code:\n\n```\nsum = 9999\nfor i in range(100, 0):\n    sum = sum - i\n```\n\n** Exercise **:\n- State whether the following code fragments are functionally equivalent:\n\n```\ni = 0\ns = 0\nfor i in range(0, 9999):\n    if i % 4 != 0:\n        s += i\n```\n\n```\ni = 0\ns = 0\nwhile i < 9999:\n    if i % 4 != 0:\n        s += i\n        i +=1 \n```\n\n```\ni = 0\ns = 0\nwhile ++i < 9999:\n    if i % 4 != 0:\n        s += i\n```\n\n\n### Accidental Infinite loops\nSometimes we want a while loop to run until a defined action is completed, such as emptying out a list. Sometimes we want a loop to run for an unknown period of time, for example when we are allowing users to give as much input as they want. What we rarely want, however, is a true 'runaway' infinite loop.\n\nTake a look at the following example. Can you pick out why this loop will never stop?\n\n```python\n# /////////////////////////////////////////\n# /// don't execute thie piece of code! ///\n# /////////////////////////////////////////\n\n\ncurrent_number = 1\n\n# Count up to 5, printing the number each time.\nwhile current_number <= 5:\n    print(current_number)\n```\n\n\n```python\n1\n1\n1\n1\n1\n...\n```\n\nI faked that output, because if I ran it the output would fill up the browser. You can try to run it on your computer, as long as you know how to interrupt runaway processes:\n\n- On most systems, Ctrl-C will interrupt the currently running program.\n- If you are using Geany, your output is displayed in a popup terminal window. You can either press Ctrl-C, or you can use your pointer to close the terminal window.\n\nThe loop runs forever, because there is no way for the test condition to ever fail. The programmer probably meant to add a line that increments current_number by 1 each time through the loop:\n\n\n```python\ncurrent_number = 1\n\n# Count up to 5, printing the number each time.\nwhile current_number <= 5:\n    print(current_number)\n    current_number = current_number + 1\n```\n\nYou will certainly make some loops run infintely at some point. When you do, just interrupt the loop and figure out the logical error you made.\n\nInfinite loops will not be a real problem until you have users who run your programs on their machines. You won't want infinite loops then, because your users would have to shut down your program, and they would consider it buggy and unreliable. Learn to spot infinite loops, and make sure they don't pop up in your polished programs later on.\n\nHere is one more example of an accidental infinite loop:\n\n```python\n# /////////////////////////////////////////\n# /// don't execute thie piece of code! ///\n# /////////////////////////////////////////\n\n\n\ncurrent_number = 1\n\n# Count up to 5, printing the number each time.\nwhile current_number <= 5:\n    print(current_number)\n    current_number = current_number - 1\n```\n\n\n```python\n1\n0\n-1\n-2\n-3\n...\n```\n\nIn this example, we accidentally started counting down. The value of `current_number` will always be less than 5, so the loop will run forever.\n\n## Introducing Functions\nOne of the core principles of any programming language is, \"Don't Repeat Yourself\". If you have an action that should occur many times, you can define that action once and then call that code whenever you need to carry out that action.\n\nWe are already repeating ourselves in our code, so this is a good time to introduce simple functions. Functions mean less work for us as programmers, and effective use of functions results in code that is less error-prone.\n\nFunctions are a set of actions that we group together, and give a name to. You have already used a number of functions from the core Python language, such as *string.title()* and *list.sort()*. We can define our own functions, which allows us to \"teach\" Python new behavior.\n\n### General Syntax\nA general function looks something like this:\n\n\n```python\n# Let's define a function.\ndef function_name(argument_1, argument_2):\n\t# Do whatever we want this function to do,\n\t#  using argument_1 and argument_2\n\n# Use function_name to call the function.\nfunction_name(value_1, value_2)\n```\n\nThis code will not run, but it shows how functions are used in general.\n\n- **Defining a function**\n    - Give the keyword `def`, which tells Python that you are about to *define* a function.\n    - Give your function a name. A variable name tells you what kind of value the variable contains; a function name should tell you what the function does.\n    - Give names for each value the function needs in order to do its work.\n        - These are basically variable names, but they are only used in the function.\n        - They can be different names than what you use in the rest of your program.\n        - These are called the function's *arguments*.\n    - Make sure the function definition line ends with a colon.\n    - Inside the function, write whatever code you need to make the function do its work.\n- **Using your function**\n    - To *call* your function, write its name followed by parentheses.\n    - Inside the parentheses, give the values you want the function to work with.\n        - These can be variables such as `current_name` and `current_age`, or they can be actual values such as 'ada' and 5.\n\n\n```python\nprint(\"You are doing good work, Adriana!\")\nprint(\"Thank you very much for your efforts on this project.\")\n\nprint(\"\\nYou are doing good work, Billy!\")\nprint(\"Thank you very much for your efforts on this project.\")\n\nprint(\"\\nYou are doing good work, Caroline!\")\nprint(\"Thank you very much for your efforts on this project.\")\n```\n\nFunctions take repeated code, put it in one place, and then you call that code when you want to use it. Here's what the same program looks like with a function.\n\n\n```python\ndef thank_you(name):\n    # This function prints a two-line personalized thank you message.\n    print(\"\\nYou are doing good work, %s!\" % name)\n    print(\"Thank you very much for your efforts on this project.\")\n    \nthank_you('Adriana')\nthank_you('Billy')\nthank_you('Caroline')\n```\n\nIn our original code, each pair of print statements was run three times, and the only difference was the name of the person being thanked. When you see repetition like this, you can usually make your program more efficient by defining a function.\n\nThe keyword *def* tells Python that we are about to define a function. We give our function a name, *thank\\_you()* in this case. A variable's name should tell us what kind of information it holds; a function's name should tell us what the variable does.  We then put parentheses. Inside these parenthese we create variable names for any variable the function will need to be given in order to do its job. In this case the function will need a name to include in the thank you message. The variable `name` will hold the value that is passed into the function *thank\\_you()*.\n\nTo use a function we give the function's name, and then put any values the function needs in order to do its work. In this case we call the function three times, each time passing it a different name.\n\n### A common error\nA function must be defined before you use it in your program. For example, putting the function at the end of the program would not work.\n\n\n```python\nthank_you('Adriana')\nthank_you('Billy')\nthank_you('Caroline')\n\ndef thank_you(name):\n    # This function prints a two-line personalized thank you message.\n    print(\"\\nYou are doing good work, %s!\" % name)\n    print(\"Thank you very much for your efforts on this project.\")\n```\n\nOn the first line we ask Python to run the function *thank\\_you()*, but Python does not yet know how to do this function. We define our functions at the beginning of our programs, and then we can use them when we need to.\n\nA second example\n---\nWhen we introduced the different methods for [sorting a list](Python%20-%20Hands-on%20Introduction%20to%20Python%20and%20Machine%20Learning.ipynb#Sorting-a-List), our code got very repetitive. It takes two lines of code to print a list using a for loop, so these two lines are repeated whenever you want to print out the contents of a list. This is the perfect opportunity to use a function, so let's see how the code looks with a function.\n\nFirst, let's see the code we had without a function:\n\n\n```python\nstudents = ['bernice', 'aaron', 'cody']\n\n# Put students in alphabetical order.\nstudents.sort()\n\n# Display the list in its current order.\nprint(\"Our students are currently in alphabetical order.\")\nfor student in students:\n    print(student.title())\n\n# Put students in reverse alphabetical order.\nstudents.sort(reverse=True)\n\n# Display the list in its current order.\nprint(\"\\nOur students are now in reverse alphabetical order.\")\nfor student in students:\n    print(student.title())\n```\n\nHere's what the same code looks like, using a function to print out the list:\n\n\n```python\ndef show_students(students, message):\n    # Print out a message, and then the list of students\n    print(message)\n    for student in students:\n        print(student.title())\n\nstudents = ['bernice', 'aaron', 'cody']\n\n# Put students in alphabetical order.\nstudents.sort()\nshow_students(students, \"Our students are currently in alphabetical order.\")\n\n#Put students in reverse alphabetical order.\nstudents.sort(reverse=True)\nshow_students(students, \"\\nOur students are now in reverse alphabetical order.\")\n```\n\nThis is much cleaner code. We have an action we want to take, which is to show the students in our list along with a message. We give this action a name, *show\\_students()*. \n\nThis function needs two pieces of information to do its work, the list of students and a message to display. Inside the function, the code for printing the message and looping through the list is exactly as it was in the non-function code.\n\nNow the rest of our program is cleaner, because it gets to focus on the things we are changing in the list, rather than having code for printing the list. We define the list, then we sort it and call our function to print the list. We sort it again, and then call the printing function a second time, with a different message. This is much more readable code.\n\n### Advantages of using functions\nYou might be able to see some advantages of using functions, through this example:\n\n- We write a set of instructions once. We save some work in this simple example, and we save even more work in larger programs.\n- When our function works, we don't have to worry about that code anymore. Every time you repeat code in your program, you introduce an opportunity to make a mistake. Writing a function means there is one place to fix mistakes, and when those bugs are fixed, we can be confident that this function will continue to work correctly.\n- We can modify our function's behavior, and that change takes effect every time the function is called. This is much better than deciding we need some new behavior, and then having to change code in many different places in our program.\n\nFor a quick example, let's say we decide our printed output would look better with some form of a bulleted list. Without functions, we'd have to change each print statement. With a function, we change just the print statement in the function:\n\n\n```python\ndef show_students(students, message):\n    # Print out a message, and then the list of students\n    print(message)\n    for student in students:\n        print(\"- \" + student.title())\n\nstudents = ['bernice', 'aaron', 'cody']\n\n# Put students in alphabetical order.\nstudents.sort()\nshow_students(students, \"Our students are currently in alphabetical order.\")\n\n#Put students in reverse alphabetical order.\nstudents.sort(reverse=True)\nshow_students(students, \"\\nOur students are now in reverse alphabetical order.\")\n```\n\nYou can think of functions as a way to \"teach\" Python some new behavior. In this case, we taught Python how to create a list of students using hyphens; now we can tell Python to do this with our students whenever we want to.\n\n### Returning a Value\nEach function you create can return a value. This can be in addition to the primary work the function does, or it can be the function's main job. The following function takes in a number, and returns the corresponding word for that number:\n\n\n```python\ndef get_number_word(number):\n    # Takes in a numerical value, and returns\n    #  the word corresponding to that number.\n    if number == 1:\n        return 'one'\n    elif number == 2:\n        return 'two'\n    elif number == 3:\n        return 'three'\n    # ...\n    \n# Let's try out our function.\nfor current_number in range(0,4):\n    number_word = get_number_word(current_number)\n    print(current_number, number_word)\n```\n\nIt's helpful sometimes to see programs that don't quite work as they are supposed to, and then see how those programs can be improved. In this case, there are no Python errors; all of the code has proper Python syntax. But there is a logical error, in the first line of the output.\n\nWe want to either not include 0 in the range we send to the function, or have the function return something other than `None` when it receives a value that it doesn't know. Let's teach our function the word 'zero', but let's also add an `else` clause that returns a more informative message for numbers that are not in the if-chain.\n\n\n```python\ndef get_number_word(number):\n    # Takes in a numerical value, and returns\n    #  the word corresponding to that number.\n    if number == 0:\n        return 'zero'\n    elif number == 1:\n        return 'one'\n    elif number == 2:\n        return 'two'\n    elif number == 3:\n        return 'three'\n    else:\n        return \"I'm sorry, I don't know that number.\"\n    \n# Let's try out our function.\nfor current_number in range(0,6):\n    number_word = get_number_word(current_number)\n    print(current_number, number_word)\n```\n\nIf you use a return statement in one of your functions, keep in mind that the function stops executing as soon as it hits a return statement. For example, we can add a line to the *get\\_number\\_word()* function that will never execute, because it comes after the function has returned a value:\n\n\n```python\ndef get_number_word(number):\n    # Takes in a numerical value, and returns\n    #  the word corresponding to that number.\n    if number == 0:\n        return 'zero'\n    elif number == 1:\n        return 'one'\n    elif number == 2:\n        return 'two'\n    elif number == 3:\n        return 'three'\n    else:\n        return \"I'm sorry, I don't know that number.\"\n    \n    # This line will never execute, because the function has already\n    #  returned a value and stopped executing.\n    print(\"This message will never be printed.\")\n    \n# Let's try out our function.\nfor current_number in range(0,6):\n    number_word = get_number_word(current_number)\n    print(current_number, number_word)\n```\n\n### More Later\nThere is much more to learn about functions, but we will get to those details later. For now, feel free to use functions whenever you find yourself writing the same code several times in a program. Some of the things you will learn when we focus on functions:\n\n- How to give the arguments in your function default values.\n- How to let your functions accept different numbers of arguments.\n\n## User input\nAlmost all interesting programs accept input from the user at some point. You can start accepting user input in your programs by using the `input()` function. The input function displays a messaget to the user describing the kind of input you are looking for, and then it waits for the user to enter a value. When the user presses Enter, the value is passed to your variable.\n\n### General syntax\nThe general case for accepting input looks something like this:\n\n\n```python\n# Get some input from the user.\nvariable = input('Please enter a value: ')\n# Do something with the value that was entered.\n```\n\nYou need a variable that will hold whatever value the user enters, and you need a message that will be displayed to the user.\n\n<a id=\"Example-input\"></a>\nIn the following example, we have a list of names. We ask the user for a name, and we add it to our list of names.\n\n\n```python\n# Start with a list containing several names.\nnames = ['guido', 'tim', 'jesse']\n\n# Ask the user for a name.\nnew_name = input(\"Please tell me someone I should know: \")\n\n# Add the new name to our list.\nnames.append(new_name)\n\n# Show that the name has been added to the list.\nprint(names)\n```\n\n### Using while loops to keep your programs running\nMost of the programs we use every day run until we tell them to quit, and in the background this is often done with a while loop. Here is an example of how to let the user enter an arbitrary number of names.\n\n\n```python\n# Start with an empty list. You can 'seed' the list with\n#  some predefined values if you like.\nnames = []\n\n# Set new_name to something other than 'quit'.\nnew_name = ''\n\n# Start a loop that will run until the user enters 'quit'.\nwhile new_name != 'quit':\n    # Ask the user for a name.\n    new_name = input(\"Please tell me someone I should know, or enter 'quit': \")\n\n    # Add the new name to our list.\n    names.append(new_name)\n\n# Show that the name has been added to the list.\nprint(names)\n```\n\nThat worked, except we ended up with the name 'quit' in our list. We can use a simple `if` test to eliminate this bug:\n\n\n```python\n# Start with an empty list. You can 'seed' the list with\n#  some predefined values if you like.\nnames = []\n\n# Set new_name to something other than 'quit'.\nnew_name = ''\n\n# Start a loop that will run until the user enters 'quit'.\nwhile new_name != 'quit':\n    # Ask the user for a name.\n    new_name = input(\"Please tell me someone I should know, or enter 'quit': \")\n\n    # Add the new name to our list.\n    if new_name != 'quit':\n        names.append(new_name)\n\n# Show that the name has been added to the list.\nprint(names)\n```\n\nThis is pretty cool! We now have a way to accept input from users while our programs run, and we have a way to let our programs  run until our users are finished working.\n\n#### Using while loops to make menus\nYou now have enough Python under your belt to offer users a set of choices, and then respond to those choices until they choose to quit. Let's look at a simple example, and then analyze the code:\n\n\n```python\n# Give the user some context.\nprint(\"\\nWelcome to the nature center. What would you like to do?\")\n\n# Set an initial value for choice other than the value for 'quit'.\nchoice = ''\n\n# Start a loop that runs until the user enters the value for 'quit'.\nwhile choice != 'q':\n    # Give all the choices in a series of print statements.\n    print(\"\\n[1] Enter 1 to take a bicycle ride.\")\n    print(\"[2] Enter 2 to go for a run.\")\n    print(\"[3] Enter 3 to climb a mountain.\")\n    print(\"[q] Enter q to quit.\")\n    \n    # Ask for the user's choice.\n    choice = input(\"\\nWhat would you like to do? \")\n    \n    # Respond to the user's choice.\n    if choice == '1':\n        print(\"\\nHere's a bicycle. Have fun!\\n\")\n    elif choice == '2':\n        print(\"\\nHere are some running shoes. Run fast!\\n\")\n    elif choice == '3':\n        print(\"\\nHere's a map. Can you leave a trip plan for us?\\n\")\n    elif choice == 'q':\n        print(\"\\nThanks for playing. See you later.\\n\")\n    else:\n        print(\"\\nI don't understand that choice, please try again.\\n\")\n        \n# Print a message that we are all finished.\nprint(\"Thanks again, bye now.\")\n```\n\nOur programs are getting rich enough now, that we could do many different things with them. Let's clean this up in one really useful way. There are three main choices here, so let's define a function for each of those items. This way, our menu code remains really simple even as we add more complicated code to the actions of riding a bicycle, going for a run, or climbing a mountain.\n\n\n```python\n# Define the actions for each choice we want to offer.\ndef ride_bicycle():\n    print(\"\\nHere's a bicycle. Have fun!\\n\")\n    \ndef go_running():\n    print(\"\\nHere are some running shoes. Run fast!\\n\")\n    \ndef climb_mountain():\n    print(\"\\nHere's a map. Can you leave a trip plan for us?\\n\")\n\n# Give the user some context.\nprint(\"\\nWelcome to the nature center. What would you like to do?\")\n\n# Set an initial value for choice other than the value for 'quit'.\nchoice = ''\n\n# Start a loop that runs until the user enters the value for 'quit'.\nwhile choice != 'q':\n    # Give all the choices in a series of print statements.\n    print(\"\\n[1] Enter 1 to take a bicycle ride.\")\n    print(\"[2] Enter 2 to go for a run.\")\n    print(\"[3] Enter 3 to climb a mountain.\")\n    print(\"[q] Enter q to quit.\")\n    \n    # Ask for the user's choice.\n    choice = input(\"\\nWhat would you like to do? \")\n    \n    # Respond to the user's choice.\n    if choice == '1':\n        ride_bicycle()\n    elif choice == '2':\n        go_running()\n    elif choice == '3':\n        climb_mountain()\n    elif choice == 'q':\n        print(\"\\nThanks for playing. See you later.\\n\")\n    else:\n        print(\"\\nI don't understand that choice, please try again.\\n\")\n        \n# Print a message that we are all finished.\nprint(\"Thanks again, bye now.\")\n```\n\nThis is much cleaner code, and it gives us space to separate the details of taking an action from the act of choosing that action.\n\n### Using while loops to process items in a list\nIn the section on Lists, you saw that we can `pop()` items from a list. You can use a while list to pop items one at a time from one list, and work with them in whatever way you need. Let's look at an example where we process a list of unconfirmed users.\n\n\n```python\n# Start with a list of unconfirmed users, and an empty list of confirmed users.\nunconfirmed_users = ['ada', 'billy', 'clarence', 'daria']\nconfirmed_users = []\n\n# Work through the list, and confirm each user.\nwhile len(unconfirmed_users) > 0:\n    \n    # Get the latest unconfirmed user, and process them.\n    current_user = unconfirmed_users.pop()\n    print(\"Confirming user %s...confirmed!\" % current_user.title())\n    \n    # Move the current user to the list of confirmed users.\n    confirmed_users.append(current_user)\n    \n# Prove that we have finished confirming all users.\nprint(\"\\nUnconfirmed users:\")\nfor user in unconfirmed_users:\n    print('- ' + user.title())\n    \nprint(\"\\nConfirmed users:\")\nfor user in confirmed_users:\n    print('- ' + user.title())\n```\n\nThis works, but let's make one small improvement. The current program always works with the most recently added user. If users are joining faster than we can confirm them, we will leave some users behind. If we want to work on a 'first come, first served' model, or a 'first in first out' model, we can pop the first item in the list each time.\n\n\n```python\n# Start with a list of unconfirmed users, and an empty list of confirmed users.\nunconfirmed_users = ['ada', 'billy', 'clarence', 'daria']\nconfirmed_users = []\n\n# Work through the list, and confirm each user.\nwhile len(unconfirmed_users) > 0:\n    \n    # Get the latest unconfirmed user, and process them.\n    current_user = unconfirmed_users.pop(0)\n    print(\"Confirming user %s...confirmed!\" % current_user.title())\n    \n    # Move the current user to the list of confirmed users.\n    confirmed_users.append(current_user)\n    \n# Prove that we have finished confirming all users.\nprint(\"\\nUnconfirmed users:\")\nfor user in unconfirmed_users:\n    print('- ' + user.title())\n    \nprint(\"\\nConfirmed users:\")\nfor user in confirmed_users:\n    print('- ' + user.title())\n```\n\nThis is a little nicer, because we are sure to get to everyone, even when our program is running under a heavy load. We also preserve the order of people as they join our project. Notice that this all came about by adding *one character* to our program!\n\n** Exercise **:\n- Write a program that asks the user to enter a string and do the followings:\n    1. Determine the length of the string, $l$\n    2. Set $n = l$\n    3. Repeat printing the string for $n$ times on the same new line\n    4. Decrement $n$ by 1\n    5. Repeat Step 3 to 4 until $n$ is zero\n    \n    (This is just the *pseudo code*. You may use other methods and approaches to achieve the goal.)\n    \nFor example, if the user enters -\\_-, the result should be:\n\n```\n-_--_--_-\n-_--_-\n-_-\n```\n\nIf the user enters \u56e7\u56e7\u56e7, the result has to be:\n\n```\n\u56e7\u56e7\u56e7\u56e7\u56e7\u56e7\u56e7\u56e7\u56e7\n\u56e7\u56e7\u56e7\u56e7\u56e7\u56e7\n\u56e7\u56e7\u56e7\n```\n\n** Exercise **:\n- Write a function to take a string input from the user, and return it\n- Write a function <code>encrypt(input)</code> that takes a string, and encrypt it using the following algorithm:\n  - For each letter $c$, if $c \\in \\{a \\dots y\\}$ or if $c \\in \\{A \\dots Y\\}$ , shift it to the next character. That means, for instances, 'a' in the original string will be changed to 'b', 'Y' will be changed to 'Z'.\n  - Other letters (including punctuation marks) remain unchanged in the result.\n  \nFor example, given \"I go to school by bus\", the result is \"J hp up tdippm cz cvt\".\n\n** Exercise **:\n- Write a function to compute the mean of a list of integers\n- Write a function to compute the standard deviation of a list of integers\n- Write a function to compute the maximum of a list of integers\n- Write a function to compute the minimum of a list of integers\n- Write a function to compute the median of a list of integers\n", "meta": {"hexsha": "de565b96cc327acaf634e650ee973ea54d645b62", "size": 143471, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Python - Hands-on Introduction to Python And Machine Learning.ipynb", "max_stars_repo_name": "tklam/hands-on-python-machine-learning", "max_stars_repo_head_hexsha": "e797fd9fff51ad42db75aa4df05a494086aeb3a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2018-07-03T03:32:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-14T03:15:45.000Z", "max_issues_repo_path": "Python - Hands-on Introduction to Python And Machine Learning.ipynb", "max_issues_repo_name": "tklam/hands-on-python-machine-learning", "max_issues_repo_head_hexsha": "e797fd9fff51ad42db75aa4df05a494086aeb3a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python - Hands-on Introduction to Python And Machine Learning.ipynb", "max_forks_repo_name": "tklam/hands-on-python-machine-learning", "max_forks_repo_head_hexsha": "e797fd9fff51ad42db75aa4df05a494086aeb3a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-07-03T14:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T11:45:47.000Z", "avg_line_length": 31.5528920167, "max_line_length": 709, "alphanum_fraction": 0.5803542179, "converted": true, "num_tokens": 22662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13296423676207597, "lm_q2_score": 0.13660839002621936, "lm_q1q2_score": 0.018164030315132248}}
{"text": "```python\nfrom IPython.display import HTML\n\nHTML('''\nThe raw code for this IPython notebook is by default hidden for easier reading.\nTo toggle on/off the raw code, click <a href=\"javascript:code_toggle()\">here</a>.''')\n\n```\n\n\n\n\n\nThe raw code for this IPython notebook is by default hidden for easier reading.\nTo toggle on/off the raw code, click <a href=\"javascript:code_toggle()\">here</a>.\n\n\n\n\n```python\n# Modules\n\nimport string\nimport numpy as np\nimport pandas as pd\nimport qgrid as q\nimport matplotlib.pyplot as plt\n\n# Widgets & Display modules, etc..\n\nfrom ipywidgets import widgets as w\nfrom ipywidgets import Button, Layout, widgets\nfrom IPython.display import display, Javascript, Markdown\n\n# grid features for interactive grids \n\ngrid_features = { 'fullWidthRows': True,\n                  'syncColumnCellResize': True,\n                  'forceFitColumns': True,\n                  'rowHeight': 40,\n                  'enableColumnReorder': True,\n                  'enableTextSelectionOnCells': True,\n                  'editable': True,\n                  'filterable': False,\n                  'sortable': False,\n                  'highlightSelectedRow': True}\n```\n\n \n\n\n```python\nfrom ipywidgets import Button , Layout , interact,widgets\nfrom IPython.display import Javascript, display\n\n# Function: executes previous cell on button widget click event and hides achievement indicators message\n\ndef run_current(ev):\n    \n    display(Javascript('IPython.notebook.execute_cell_range(IPython.notebook.get_selected_index()+0,IPython.notebook.get_selected_index()+1)'))    \n    \n# Counter for toggling achievement indicator on/off\n\nbutton_ctr = 0\n\n# Achievement Indicators\n\nline_1 = \"#### Achievement Indicators\"\nline_2 = \"**General Outcome: **\"\nline_3 = \"* Examine and visualize concepts and examples related to the bubonic plague.\"\nline_4 = \"* Examine the timeline/map of the Black Death.\"\nline_5 = \"* Visualize mathematical model that shows the recovery, infection, and removal rates.\"\n\n# Use to print lines, then save in lines_list\n\ndef print_lines(n):\n    \n    lines_str = \"\"\n    \n    for i in range(1,n+1):\n        lines_str = lines_str + \"line_\"+str(i)+\",\"\n        \n    lines_str = lines_str[:-1]\n\n    print(lines_str)\n    \nlines_list = [line_1,line_2,line_3,line_4,line_5]\n    \n# Show/Hide buttons\n\nai_button_show = widgets.Button(button_style='info',description=\"Show Achievement Indicators\", layout=Layout(width='25%', height='30px') )\nai_button_hide = widgets.Button(button_style='info',description=\"Hide Achievement Indicators\", layout=Layout(width='25%', height='30px') )\n\ndisplay(Markdown(\"For instructors:\"))\n```\n\n\nFor instructors:\n\n\n\n```python\nbutton_ctr += 1\n\nif(button_ctr % 2 == 0):\n\n    for line in lines_list:\n        display(Markdown(line))\n    \n    display(ai_button_hide)\n    ai_button_hide.on_click( run_current )\n    \nelse:\n\n    display(ai_button_show)\n    ai_button_show.on_click( run_current )\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n#### Achievement Indicators\n\n\n\n**General Outcome: **\n\n\n\n* Examine and visualize concepts and examples related to the bubonic plague.\n\n\n\n* Examine the timeline/map of the Black Death.\n\n\n\n* Visualize mathematical model that shows the recovery, infection, and removal rates.\n\n\n\n<p>Failed to display Jupyter Widget of type <code>Button</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n<h1 align='center'>Black Death</h1>\n\n<h4 align = 'center'> $\\mid$ Grade 8 $\\mid$ Social Sciences $\\mid$</h4>\n\n<h2 align='center'>Abstract</h2>\n\nThe **Black Death** is an important historical event, that took place in the XIVth century in Europe. It was an *outbreak* of a disease called the *bubonic plague* that impacted mainly Europe and resulted in the death of roughly half of the European population over the course of five years.\n\nIn this notebook we will discuss this disease, the bubonic plague, illustrate the dynamic of how it did spread through Europe during the Black Death period, and illustrate the dramatic effect of the plague over a small English village through a mathematical model.\n\n---\n\n<h2 align='center'>The bubonic plague: an overview</h2>\n\nThe bubonic plague is a very serious *infectious disease* that has been impacting human population for above two thousand years now. Infectious means that it is caused by a *pathogen*, i.e. a micro-organism that enters the human body and develops within the body, disrupting its normal way to function. This results in an *infection* which, in the case of the bubonic plague, is likely to be fatal unless it is treated by appropriate medications, a plague vaccine. \n\nThe pathogen responsible of the bubonic plague is a *bacteria* called *Yersinia pestis*. This name is composed of the Latin name of the plague, *pestis* prefixed by a Latin version of the name of the person who first discovered the bacteria, <a href=\"https://en.wikipedia.org/wiki/Alexandre_Yersin\">Alexandre Yersin</a>.\n\nThe infection caused by *Yersinia pestis* causes flu-like symptoms such as headaches and a high fever, a common symptom of many infections, together with visible symptoms such as the apparition in some specific parts of the body of swelling (named *bubos*, which gave the name bubonic to the plague) and the development of black spots on the skin, which motivated the \"Black Death\" name. In general, an untreated patient dies within a few days. \n\n---\n\n<h2 align='center'>Infectious diseases</h2>\n\nInfectious diseases, as mentioned above, are caused by pathogens. There are various types of pathogens, including *viruses*, *bacterias* and *parasites*. Viruses causes for example diseases such as the flu (<a href=\"https://en.wikipedia.org/wiki/Influenza\">influenza</a>), <a href=\"https://en.wikipedia.org/wiki/Measles\">measles</a> or <a href=\"https://en.wikipedia.org/wiki/Mumps\">mumps</a>. Bacterias are responsible for many diseases such as  <a href=\"https://en.wikipedia.org/wiki/Tuberculosis\">tuberculosis</a>, or plague. Last parasites are larger micro-organisms, such as roundworms for example; examples of parasitic diseases include <a href=\"https://en.wikipedia.org/wiki/Malaria\">malaria</a> or the <a href=\"https://en.wikipedia.org/wiki/Dengue_fever\">dengue</a>.\n\n---\n\n<h2 align='center'>How does the bubonic plague pathogen infect humans?</h2>\n\nAn individual becomes sick with the bubonic plague when the pathogen agent <i>Yersinia pestis</i> enters its body. The most common way this happens is when the individual is bitten by a <i>flea</i> that carries the pathogen in its gut and injects it when biting (it is a little more complicated actually). The flea is called a <i>vector</i> of the disease: it does not cause the disease by itself, but helps the pathogen to move from the environment to within an individual. \n\nIt is widely accepted that the kinds of fleas that carry <i>Yersinia pestis</i> are not human fleas (i.e. the kind of fleas that naturally feed on human blood) but <i>rodent</i> fleas, that usually feed on the blood of rats, mice, squirrels, prairie dogs and so on. So why do they suddenly bite humans? This is because the rodents they use to feed on are also infected by the plague agent, and so they die, forcing the fleas to look for other sources of food. If the concerned rodent population (called the <i>reservoir</i> of the disease) lives close to human populations (like urban rats), then the natural new hosts are humans. The figure below illustrates this cycle. \n\n<figure>\n<center>\n\n</center>\n</figure>\n\nWe will get back to this when explaining how the plague spread so well in Europe during the Black Death.\n\n---\n\n<h2 align='center'>Infectious diseases outbreaks</h2>\n\nAn *outbreak* occurs when a disease, that might have been present or not within a population, suddenly starts to infect more people than usual in a given place (in general a city or a region ). When an outbreak spreads over a larger region it is called an <i>epidemic</i>, or even a <i>pandemic</i> when it happens over a very large region such as a continent.\n\nOutbreaks occur very often. We can think for example to the annual flu outbreak that hits every Canadian city every winter. This is not too scary and the local health authorities know how to handle it, through a campaign of flu vaccination. But even now more serious outbreaks occur quite often, such as the Ebola epidemic in Western Africa in 2013-2016 that caused thousands of death and was very challenging for local and global health authorities.\n\nThere has been many other dramatic outbreaks, epidemic and pandemics in history, the Black Death that we will describe below being one of the most present in human memory. But closer to us, we can think about several smallpox epidemic in the late XIXth century that spread through first nations communities of the Pacific North West and had a devastating impact. \n\n---\n\n<h2 align='center'>The Black Death Timeline</h2>\n\nThe Black Death was a bubonic plague pandemic, that concerned all of Western Europe. It started outside of Europe, in Asia, where it infected soldiers of a Mongol army who were besieging a Genoese trade post in Crimea, the city of Kaffa. After the siege, the Genoese traders (from the Italian city of Geona) sailed back home without knowing they were themselves infected. This is how the disease was introduced in Western Europe, through Italy. \n\nAt the time people did not know the principles of infectious diseases and did not intervene quickly to try to conceal the disease to a city or a few cities where the outbreak(s) would have ended likely quickly. Instead, unaware of the dramatic situation that was unfolding, traders from Italian cities maintained very active relationships with the rest of Europe, through marine or land trading routes. This resulted in the disease spreading very fast to Southern Europe within 6 months, and from there turning into a European-wide pandemic within three years.\n\nThe dynamic map below illustrates this.\n\nGiven there was no precise record of population numbers at this time, it is difficult to have a precise estimation of the number of death. But by analyzing local reports of casualties, historians have arrived to the conclusion that roughly half of the European population at this time died from the bubonic plague. We propose at the end of this notebook a small example based on real data of a 1665 plague outbreak in an English village that illustrates how quickly the bubonic plague can wipe out a community.\n\n\n```python\n%%html\n\n<style>\n\n* {box-sizing:border-box}\n\n/* Slideshow container */\n.slideshow-container {\n  max-width: 1000px;\n  position: relative;\n  margin: auto;\n}\n\n/* Hide the images by default */\n.mySlides {\n    display: none;\n}\n\n/* Next & previous buttons */\n.prev, .next {\n  cursor: pointer;\n  position: absolute;\n  top: 50%;\n  width: auto;\n  margin-top: -22px;\n  padding: 16px;\n  color: black;\n  font-weight: bold;\n  font-size: 18px;\n  transition: 0.6s ease;\n  border-radius: 0 3px 3px 0;\n}\n\n/* Position the \"next button\" to the right */\n.next {\n  right: 0;\n  border-radius: 3px 0 0 3px;\n}\n\n/* On hover, add a black background color with a little bit see-through */\n.prev:hover, .next:hover {\n  background-color: rgba(0,0,0,0.8);\n}\n\n/* Caption text */\n.text {\n  color: #000000;\n  font-size: 15px;\n  padding: 8px 12px;\n  position: absolute;\n  bottom: 8px;\n  width: 100%;\n  text-align: right;\n}\n\n/* Number text (1/3 etc) */\n.numbertext {\n  color: #f2f2f2;\n  font-size: 12px;\n  padding: 8px 12px;\n  position: absolute;\n  top: 0;\n}\n\n/* The dots/bullets/indicators */\n.dot {\n  cursor: pointer;\n  height: 15px;\n  width: 15px;\n  margin: 0 2px;\n  background-color: black;\n  border-radius: 50%;\n  display: inline-block;\n  transition: background-color 0.6s ease;\n}\n\n.active, .dot:hover {\n  background-color: #717171;\n}\n\n/* Fading animation */\n.fade {\n  -webkit-animation-name: fade;\n  -webkit-animation-duration: 1.5s;\n  animation-name: fade;\n  animation-duration: 1.5s;\n}\n\n@-webkit-keyframes fade {\n  from {opacity: .4} \n  to {opacity: 1}\n}\n\n@keyframes fade {\n  from {opacity: .4} \n  to {opacity: 1}\n}\n\n</style>\n\n\n\n<body>\n<div class=\"slideshow-container\">\n\n  <!-- Full-width images with number and caption text -->\n  <div class=\"mySlides\">\n    <div class=\"numbertext\">1 / 9</div>\n    \n    <div class=\"text\">Before Plague</div>\n  </div>\n\n  <div class=\"mySlides\">\n    <div class=\"numbertext\">2 / 9</div>\n    \n    <div class=\"text\">Plague Expansion 1347</div>\n  </div>\n\n  <div class=\"mySlides\">\n    <div class=\"numbertext\">3 / 9</div>\n    \n    <div class=\"text\">Plague Expansion Mid 1348</div>\n  </div>\n\n  <div class=\"mySlides\">\n    <div class=\"numbertext\">4 / 9</div>\n    \n    <div class=\"text\">Plague Expansion Early 1349</div>\n  </div>\n \n<div class=\"mySlides\">\n    <div class=\"numbertext\">5 / 9</div>\n    \n    <div class=\"text\">Plague Expansion Late 1349</div>\n  </div>\n\n<div class=\"mySlides\">\n    <div class=\"numbertext\">6 / 9</div>\n    \n    <div class=\"text\">Plague Expansion by 1350</div>\n  </div>\n\n<div class=\"mySlides\">\n    <div class=\"numbertext\">7 / 9</div>\n    \n    <div class=\"text\">Plague Expansion by 1351</div>\n  </div>\n\n<div class=\"mySlides\">\n    <div class=\"numbertext\">8 / 9</div>\n    \n    <div class=\"text\">Plague Expansion After 1351</div>\n  </div>\n\n<div class=\"mySlides\">\n    <div class=\"numbertext\">9 / 9</div>\n    \n    <div class=\"text\">Minor Outbreak</div>\n  </div>\n\n  <!-- Next and previous buttons -->\n  <a class=\"prev\" onclick=\"plusSlides(-1)\">&#10094;</a>\n  <a class=\"next\" onclick=\"plusSlides(1)\">&#10095;</a>\n</div>\n<br>\n\n<!-- The dots/circles -->\n<div style=\"text-align:center\">\n  <span class=\"dot\" onclick=\"currentSlide(1)\"></span> \n  <span class=\"dot\" onclick=\"currentSlide(2)\"></span> \n  <span class=\"dot\" onclick=\"currentSlide(3)\"></span> \n    <span class=\"dot\" onclick=\"currentSlide(4)\"></span> \n    <span class=\"dot\" onclick=\"currentSlide(5)\"></span> \n    <span class=\"dot\" onclick=\"currentSlide(6)\"></span> \n    <span class=\"dot\" onclick=\"currentSlide(7)\"></span> \n    <span class=\"dot\" onclick=\"currentSlide(8)\"></span> \n    <span class=\"dot\" onclick=\"currentSlide(9)\"></span> \n</div>\n<figure>\n<center>\n<figcaption>The Black Death Timeline. Images Retrieved https://en.wikipedia.org/wiki/Consequences_of_the_Black_Death</figcaption>\n</center>\n</figure>\n\n\n</body>\n\n```\n\n\n\n<style>\n\n* {box-sizing:border-box}\n\n/* Slideshow container */\n.slideshow-container {\n  max-width: 1000px;\n  position: relative;\n  margin: auto;\n}\n\n/* Hide the images by default */\n.mySlides {\n    display: none;\n}\n\n/* Next & previous buttons */\n.prev, .next {\n  cursor: pointer;\n  position: absolute;\n  top: 50%;\n  width: auto;\n  margin-top: -22px;\n  padding: 16px;\n  color: black;\n  font-weight: bold;\n  font-size: 18px;\n  transition: 0.6s ease;\n  border-radius: 0 3px 3px 0;\n}\n\n/* Position the \"next button\" to the right */\n.next {\n  right: 0;\n  border-radius: 3px 0 0 3px;\n}\n\n/* On hover, add a black background color with a little bit see-through */\n.prev:hover, .next:hover {\n  background-color: rgba(0,0,0,0.8);\n}\n\n/* Caption text */\n.text {\n  color: #000000;\n  font-size: 15px;\n  padding: 8px 12px;\n  position: absolute;\n  bottom: 8px;\n  width: 100%;\n  text-align: right;\n}\n\n/* Number text (1/3 etc) */\n.numbertext {\n  color: #f2f2f2;\n  font-size: 12px;\n  padding: 8px 12px;\n  position: absolute;\n  top: 0;\n}\n\n/* The dots/bullets/indicators */\n.dot {\n  cursor: pointer;\n  height: 15px;\n  width: 15px;\n  margin: 0 2px;\n  background-color: black;\n  border-radius: 50%;\n  display: inline-block;\n  transition: background-color 0.6s ease;\n}\n\n.active, .dot:hover {\n  background-color: #717171;\n}\n\n/* Fading animation */\n.fade {\n  -webkit-animation-name: fade;\n  -webkit-animation-duration: 1.5s;\n  animation-name: fade;\n  animation-duration: 1.5s;\n}\n\n@-webkit-keyframes fade {\n  from {opacity: .4} \n  to {opacity: 1}\n}\n\n@keyframes fade {\n  from {opacity: .4} \n  to {opacity: 1}\n}\n\n</style>\n\n\n\n<body>\n<div class=\"slideshow-container\">\n\n  <!-- Full-width images with number and caption text -->\n  <div class=\"mySlides\">\n    <div class=\"numbertext\">1 / 9</div>\n    \n    <div class=\"text\">Before Plague</div>\n  </div>\n\n  <div class=\"mySlides\">\n    <div class=\"numbertext\">2 / 9</div>\n    \n    <div class=\"text\">Plague Expansion 1347</div>\n  </div>\n\n  <div class=\"mySlides\">\n    <div class=\"numbertext\">3 / 9</div>\n    \n    <div class=\"text\">Plague Expansion Mid 1348</div>\n  </div>\n\n  <div class=\"mySlides\">\n    <div class=\"numbertext\">4 / 9</div>\n    \n    <div class=\"text\">Plague Expansion Early 1349</div>\n  </div>\n\n<div class=\"mySlides\">\n    <div class=\"numbertext\">5 / 9</div>\n    \n    <div class=\"text\">Plague Expansion Late 1349</div>\n  </div>\n\n<div class=\"mySlides\">\n    <div class=\"numbertext\">6 / 9</div>\n    \n    <div class=\"text\">Plague Expansion by 1350</div>\n  </div>\n\n<div class=\"mySlides\">\n    <div class=\"numbertext\">7 / 9</div>\n    \n    <div class=\"text\">Plague Expansion by 1351</div>\n  </div>\n\n<div class=\"mySlides\">\n    <div class=\"numbertext\">8 / 9</div>\n    \n    <div class=\"text\">Plague Expansion After 1351</div>\n  </div>\n\n<div class=\"mySlides\">\n    <div class=\"numbertext\">9 / 9</div>\n    \n    <div class=\"text\">Minor Outbreak</div>\n  </div>\n\n  <!-- Next and previous buttons -->\n  <a class=\"prev\" onclick=\"plusSlides(-1)\">&#10094;</a>\n  <a class=\"next\" onclick=\"plusSlides(1)\">&#10095;</a>\n</div>\n<br>\n\n<!-- The dots/circles -->\n<div style=\"text-align:center\">\n  <span class=\"dot\" onclick=\"currentSlide(1)\"></span> \n  <span class=\"dot\" onclick=\"currentSlide(2)\"></span> \n  <span class=\"dot\" onclick=\"currentSlide(3)\"></span> \n    <span class=\"dot\" onclick=\"currentSlide(4)\"></span> \n    <span class=\"dot\" onclick=\"currentSlide(5)\"></span> \n    <span class=\"dot\" onclick=\"currentSlide(6)\"></span> \n    <span class=\"dot\" onclick=\"currentSlide(7)\"></span> \n    <span class=\"dot\" onclick=\"currentSlide(8)\"></span> \n    <span class=\"dot\" onclick=\"currentSlide(9)\"></span> \n</div>\n<figure>\n<center>\n<figcaption>The Black Death Timeline. Images Retrieved https://en.wikipedia.org/wiki/Consequences_of_the_Black_Death</figcaption>\n</center>\n</figure>\n\n\n</body>\n\n\n<h2 align='center'>Historical plague outbreaks</h2>\n\nThe Black Death was not the only major plague pandemic. Before this medieval pandemic, in the Vth century (in 541-542 precisely), the *Justinian Plague* developed as an epidemic in the  Eastern part of the Mediteranean region and many Mediterranean port cities. It is known as the first major plague pandemic.\n\nThe Black Death itself lasted much longer than the few years illustrated in the map above. The years 1347-1351 correspond to the most acute part of the pandemic. But after this, plague remained present in Europe for almost 400 years, flaring up here and there in dramatic outbreaks, although none that turned into a pandemic. People had learned from the Black Death, and as soon as plague reappeared in a community, the community was isolated to prevent the disease spread. Nevertheless, some important outbreaks impacted large cities such as the Great Plague of London (1665-1666) or the Marseille Plague (1722). This very long pandemic is known as the second major plague pandemic.\n\nPast the Marseille plague in 1722, the disease seemed to disappear from Europe, although it remained present in Asia. This is there, in the Chinese province of the Yunan, in 1855 precisely, that the third major plague pandemic started. It did not move out of China for a long time, but then reached Hong-Kong in 1894, and from there, following again the maritime trade routes, it reached the rest of the world and was considered as an active pandemic by the World Health Organization until 1959.\n\nCurrently, there is no bubonic plague pandemic, but outbreaks occur regularly. The most serious ones are in the African island of Madagascar, but there are also regular small outbreaks in the South-West of the United States, where prairie dogs act as a reservoir for the disease.\n\n---\n\n<h2 align='center'>The discovery of the <i>Yersinia pestis</i> bacteria</h2>\n\nThis is during the 1894 Hong-Kong outbreak of the third pandemic that, finally, scientists discovered the cause of the bubonic plague. Until this date, people did not know what caused this dramatic disease. But during the 1984 outbreak, both French and Japanese authorities sent scientists, Alexandre Yersin for the French side and Kitasato Shibasabur\u014d for the Japanese side, to try to discover the cause of the disease.\n\n<figure>\n<center>\n<table>\n<tr>\n    <td></td>\n    <td></td>\n</tr>\n</table>\n<figcaption>Kitasato Shibasabur\u014d (left) and Alexandre Yersin (right)</figcaption>\n</center>\n</figure>\n\nBoth were competing hard to be the first one to find the pathogen causing the disease. Yersin was fortunate enough that his lab was actually a shed with no cooling system, which resulted in the bacteria <i>Yersinia pestis</i> reproducing faster than in the well equipped lab of Shibasabur\u014d, which lead him the finding the tiny micro-organisms in large numbers in the lungs of deceased patients.\n\n---\n\n\n<h2 align='center'>Was the Black Death a bubonic plague outbreak?</h2>\n\nThis is actually a good question. Indeed, nobody did the same work than Yersin and  Shibasabur\u014d during the Black Death pandemic. Bacterias were actually not known at the time. So in order to declare it a plague, historians relied on written records from people chronicling the dramatic pandemic. Nevertheless, most chroniclers were not physicians and as such they did not use the medical vocabulary developed in the XIXth century when the mechanisms of infectious diseases were discovered. It did not help that, at the time of the Black Death, the word *plague* was   a generic word used to describe infectious diseases outbreaks in general.\n\nAs a result of this lack of precise documentation about the Black Death pandemic, there was a long-standing debate about the cause of this pandemic, with a strongly supported hypothesis that the disease was actually due to an Ebola-like virus. \n\nIt is only in 2011, that an international team led by a Canadian scientist, <a href=\"https://socialsciences.mcmaster.ca/people/poinar-hendrik\">Hendrik Poinar</a>, from McMaster University in Hamilton, was able to extract, from the dental pulp of the body of victims of the Black Death in London, the genome of the bacteria *Yersinia pestis*, thus closing the debate over the actual disease that caused the Black Death.\n\n---\n\n<h2 align='center'>Conclusion</h2>\nThe  Black Death was a dramatic event in European history, as shown by the extant and speed of its spread across the continent.  While it is now a well known event (a plague pandemic), it is interesting to reflect on the fact that this results from tremendous progress of sciences over the last century or so. Our understanding of this pandemic follows up from the discovery of infectious diseases, the precise identification of the plague agent and even very recent work on ancient DNA. The story is however not closed. The Plague stayed in Europe for almost 400 years after the Black Death before disappearing from the continent; it is still an open question to understand both how a disease can last for so long and why it can vanish quite suddenly with no human intervention.\n\n---\n\n<h2 align='center'>Modeling a Bubonic Plague Outbreak</h2>\n\n<h4 align = 'center'> $\\mid$ Grade 11 $\\mid$ Social Sciences $\\mid$</h4>\n\nWe are interested in modeling a bubonic plague outbreak. We part from the assumption that the total population can be subdivided into a set of classes, each of which depends on the state of the infection. The **SIR Model** is the simplest one and, as its name suggests, it divides the population into three classes. \n\n<h2 align='center'>The SIR Outbreak Model</h2>\n\n### Population Parameters\n\nIn this model, the total population considered is divided into three groups of individuals:\n\n* Susceptible: the individuals that are not infected but can become infected\n* Infected: the individuals that are infected\n* Removed: the individuals that are either dead (the pessimistic point of view) or survived \n\nWe are concerned about the predicting the changes, over the course of an outbreak, of the **number of people who are susceptible**, the **number of people who are infected**, and the **number of people who are removed**. We denote these parameters to be $S, I, R$ respectively. In other words we want to understand how, when time passes, the number of individuals in each group evolves. \n\nIf we have a realistic model, then it might be useful to predict the long-term outcome of an outbreak and inform public health interventions. For example if we can predict that the number of removed people will stay low and the number of infected people will quickly go down to zero, then there is no need to intervene and we can let the outbreak ends by itself, only taking care to provide medical attention to the infected people. Conversely if we predict a large increase of the numbers of infected and removed individuals, then the outbreak needs a quick intervention to be tamed before it touches too many people and results in a large number of casualties. In a plague outbreak this intervention would for example be to make sure there is no contact between infected and susceptible people.\n\nWe now describe the SIR mathematical model (SIR stands for Susceptible, Infected, Removed) of an outbreak. We assume we record the number of individuals at several time points (for example every week). We write $S_n, I_n, R_n$ to denote the number, respectively, of susceptible, infected and removed individuals at time point $n$ (with $n=1$ being the first recorded time point, $n=2$ the second and so on). We call *time unit* the time elapsed between two time points.\n\nIn this model, we assume that the **total population is constant** (so births and deaths are ignored) for the duration of the model simulation. We denote the total population size by $N$, and so at any time point $n$ we have $$N=S_n + I_n + R_n.$$\n\n### Modelling the outbreak / disease progression\n\nWe assume that a susceptible individual can become infected only by contact with an already infected individual. Once infected, we assume that the disease takes a constant amount of time to progress within an individual until he/she is removed (i.e. either dies or recovers). So there are two processes in play: infection and removal. We need to define these processes and model how they impact the transition from a state of the population at time point $n$, described by the triplet of numbers  $(S_n,I_n,R_n)$, to the next state $(S_{n+1},I_{n+1},R_{n+1})$ at time point $n+1$.\n\n\n\nThe occurrences of new infections of is modeled using a parameter $\\beta$, that gives the proportion of contacts between susceptible people and infected people, during one time unit, that results in a susceptible being infected. Then we can describe the number of newly infected people  as $\\dfrac{\\beta S_n I_n}{N}$, where the term $S_n I_n$ represents the set of all possible contacts between susceptible and infected individuals. We discuss this term later.\n\nThe occurrence of removals of infected people is modeled using a parameter denoted by $\\gamma$. It is defined to be proportion of infected individuals that die or recover between two time points. If we are given that the duration of an infection is $T$ (i.e. how many time points it takes for an individual between its infection and its removal), then $\\gamma = \\dfrac{1}{T}$. \n\n\n\nTaking into account the rate of contact $\\beta$ and rate of removal $\\gamma$, then each group population changes within one unit of time (i.e. between two successive time points) as follows\n\n$$\n\\begin{align}\nS_{n+1} &= S_n -  \\dfrac{{\\beta} S_n I_n}{N}\\\\\nI_{n+1} &= I_n +  \\dfrac{{\\beta} S_n I_n}{N} - \\gamma I_n \\\\\nR_{n+1} &= R_n + \\gamma I_n\\\\\nN&=S_n + I_n + R_n\n\\end{align}\n$$\n\nThese equations form the SIR model. They allow, from knowing the parameters of the model (i.e. the characteristics of the disease outbreak at play, $\\beta$ and $\\gamma$) and the current state $(S_n,I_n,R_n)$ of a population to predict the next states of the population for later time points. Such models are critical in our days for monitoring and controlling infectious diseases outbreaks.\n\n##### Technical remarks.\nFirst, note that the SIR model does not enforce that the values $S_n,I_n,R_n$ at a given time point are integers. As $\\beta$ and $\\gamma$ are actually floating numbers, these values are actually most of the time not integers. This is fine as the SIR model is an approximate model and aims mostly at predicting the general dynamics of an outbreak, not the precise values for the number of susceptible, infected and removed individuals.\n\nNext, one can ask how to find the values of the parameters $\\beta$ and $\\gamma$, that are necessary to have a full SIR model. \n\nAs discussed above, the parameter $\\gamma$ is relatively easy to find from knowing how the disease progress in a patient, as it is mostly the inverse of the average time a patient is sick. \n\nThe parameter $\\beta$ is less easy to obtain. Reading the equations , we can see that during a time point, out of the $S_n$ susceptible individuals, the number that get infected is $(\\dfrac{{\\beta}}{N}) S_n I_n$. As mentioned above, the product $S_nI_n$ can be interpreted as the set of all possible contacts between the $S_n$ susceptible individuals and the $I_n$ infected individuals and is often a large number, much larger than $S_n$ and in the order of $N^2$. The division by $N$ aims to lower this number, mostly to normalize it by the total population, to make sure it is in order of $N$ and not quadratic in $N$. So in order for the number of newly infected individuals during a time unit to be reasonable, $\\beta$ is generally a  small number between $0$ and $1$. But formally, if we pick a value for $\\beta$ that is too large, then the SIR model will predict value for $S_n$ that can be negative, which is inconsistent with the modeled phenomenon. So choosing the value of $\\beta$ is the crucial step in modelling an outbreak.\n\n---\n\n\n```python\n# This function takes as input a vector y holding all initial values,\n#    n the number of time points\n#    beta: beta parameter of the SIR \n#    gamma: gamma parameter of the SIR\n#    S1,I1,R1 = initial values\n\ndef discrete_SIR(S1,I1,R1,n,beta,gamma):\n    # Empy arrays for each class\n    S = []\n    I = []\n    R = []\n    N = S1+I1+R1\n    \n    # Append initial values\n    S.append(S1)\n    I.append(I1)\n    R.append(R1)\n    \n    # apply SIR model: iterate over the total number of days - 1\n    for i in range(n-1):\n        S_next = S[i] - (beta/N)*((S[i]*I[i]))\n        S.append(S_next)\n        \n        I_next = I[i] + (beta/N)*((S[i]*I[i])) - gamma*I[i]\n        I.append(I_next)\n        \n        R_next = R[i] + gamma * I[i]\n        R.append(R_next)\n    \n    # return arrays S,I,R whose entries are various values for susceptible, infected, removed \n    return((S,I,R))\n```\n\n<h2 align='center'> Modeling an outbreak related to the Great Plague of London</h2>\n\nBetween 1665 and 1666 occurred the last major epidemic of the bubonic plague in England ([click here for further reading](https://www.britannica.com/event/Great-Plague-of-London)). This epidemic did not kill as many people as the Black Death (1347 - 1351), however it is remembered as the \"Great Plague of London\" as it was the last widespread outbreak that affected England. \n\n\"City records indicate that some 68,596 people died during the epidemic, though the actual number of deaths is suspected to have exceeded 100,000 out of a total population estimated at 460,000. \" [Great Plague of London\"; Encyclop\u00e6dia Britannica; Encyclop\u00e6dia Britannica, inc.; September 08, 2016](https://www.britannica.com/event/Great-Plague-of-London)\n\nWhen the bubonic plague outbreak hit London, people started to leave the city and go to the countryside, hoping to avoid the disease. But as can be expected, some of these people were already infected when they left London, and so carried the disease to start other outbreaks in some nearby villages. This happened in the village of Eyam. When Eyam authorities realized a plague outbreak had started, they took the difficult decision to close the village in order to avoid to spread the disease further. So nobody was allowed to enter or leave the village and people stayed there hoping the outbreak would end by itself without too many casualties; note that from a mathematical point of view, that implies that the assumption that the sum of the numbers of susceptible, infected and removed individuals, the population, is constant. And also the village authorities recorded regularly the number of infected and dead people; these data are described in the table below, for the period from June 19 1665 to October 19 1665, with data being recorded every 2 weeks. Obviously this data is imperfect (some people did not declare they were sick by fear of being ostracized, some people died too fast for the plague to be diagnosed, ...), but nevertheless, they provide us with interesting data to see if the SIR model is an appropriate model for such a plague outbreak. \n\n\n| Date  |Day Number |Susceptible | Infected | \n|-------||-------------|----------|\n|June 19 1665|0|254|7| \n|July 3 1665|14|235|14|\n|July 19 1665|28|201|22|\n|Aug 3 1665|42|153|29|\n|Aug 19 1665|56|121| 21|\n|Sept 3 1665|70|108|8|\n|Sept 19 1665|84|121|21|\n|Oct 3 1665| 98|NA | NA|\n|Oct 19 1665|112| 83 | 0|\n\nThe average time an infected individual remains infected by the bubonic plague is 11 days.\n\nWith the information above, we will be able to get the parameters of the SIR model for this outbreak and observe if indeed what this model predicts generates results corresponding to what happened in reality.\n\n### Question 1:\n\nAssuming that on June 19 no individuals had deceased, i.e. no one was in the Removed class, what is the value of $N$, i.e. the size (number of individuals) of the total population?\n\n\n```python\nfrom ipywidgets import interact_manual, widgets\n# define style\ns = {'description_width': 'initial'}\n\n# Run Interact Button parameters\n@interact_manual(answer=widgets.Textarea(\n    value=' ',\n    placeholder='Type something',\n    description='What is the total population?',\n    disabled=False,\n    style=s\n))\n\n# Get correct answer\ndef get_pop(answer):\n    if \"261\" in answer or answer==\"Two hundred and sixty one\":\n        print(\"Correct! \\nThe total population is given by S_1 + I_1 + R_1 = 254 + 7 + 0  = 261.\")\n    else:\n        print(\"That does not look ok. Try again.\\n \\nRemember: N = S_1 + I_1 + R_1.\\n \\nS_1 = 254, I_1 = 7, R_1 = 0.\");\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>interactive</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n\n```python\nprint(\"Press the Run Interact Button to Obtain the True Answer\")\n# Reveal true answer\ndef true_population():\n    print(\"Since we are assuming the population is constant, and since S_1 = 254, I_1 = 7, R_1 = 0, then \\nfrom our model we know N = 254 + 7 + 0 = 261.\")\n    \ninteract_manual(true_population);\n```\n\n    Press the Run Interact Button to Obtain the True Answer\n\n\n\n<p>Failed to display Jupyter Widget of type <code>interactive</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n### Question 2:\n\nWe know that the average time an individual remained infected is 11 days. With this information in mind, what is the rate of removal $\\gamma$?\n\n\n```python\nfrom ipywidgets import interact_manual, widgets\n# Define style\ns = {'description_width': 'initial'}\n\n# Set parameters for Run Interact button\n@interact_manual(answer=widgets.Textarea(\n    value=' ',\n    placeholder='Type something',\n    description='What is the value of $\\gamma$?',\n    disabled=False,\n    style=s\n))\n\n# Set correct answer\ndef correct_answer(answer):\n    if \"1/11\" in answer:\n        print(\"Correct! \\nThe rate of removal is equal to 1/11=0.0909..., as it takes on average 11 days for an individual to remain infected.\")\n    else:\n        print(\"That does not look ok. Try again. \\n \\nRemember: 1 individual dies every 11 days.\");\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>interactive</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n\n```python\nprint(\"Press the Run Interact Button to Obtain the True Answer\")\n\n# reveal true value of gamma\ndef true_gamma():\n    print(\"We know that, on average, every 11 days an infected person dies. \\nThis is equivalent to stating that 1 individual moves to the removed class for every 11 days. \\nWe can express this idea mathematically as 1/11.\")\n    \ninteract_manual(true_gamma);\n```\n\n    Press the Run Interact Button to Obtain the True Answer\n\n\n\n<p>Failed to display Jupyter Widget of type <code>interactive</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n### Question 3:\n\nWe are now trying something more difficult but more interesting. We introduced a mathematical model for outbreaks, but nothing so far shows that this SIR model is appropriate to model an outbreak such as the Eyam plague outbreak. we want to answer this question now.\n\nFrom questions 1 and 2 above, we know the values of $N$ and $\\gamma$. From the data table we also know $S_1,I_1,R_1$, the state of the population aty the start of the outbreak. So if we want to apply the SIR model we need to find  a value for $\\beta$ the parameter involved in the equation giving the number susceptible people becoming infected during a time uni. We consider here that a time unit is 1 day; the Eyam outbreak spanned 112 days, so 112 time units, even if data were recorded every 2 weeks only. \n\nA standard scientific approach for the problem of finding $\\beta$ is to try various values and see if there is one that leads to predicted values for $S_n,I_n,R_n$ for various time points that match the observed data given in the data table. In order to evaluate this match, we focus on the number of infected people, the most important element of an outbreak.\n\nThe activity below allows you to do this: you can choose a value of $\\beta$, click on the \"Run interact\" button and it will show on the same graph a set of 8 blue dots (the true number of infected people from the data table) and a set of 112 red dots, corresponding to the predicted number of infected individuals for the chosen value of $\\beta$.\n\nWhile there are several mathematical ways to define what would be the *best fit*, here we are not getting into this and you are just asked to try to find a value of $\\beta$ that generated blue dots being more or less on the graph defined by the red dots.\n\n##### Warning.\nThe SIR model is a very simple approximation of the dynamics of a true outbreak, so do not expect to find a value of $\\beta$ that generates a graph that contains exactly all data points (blue dots). In particular note that the data points of September 3 and 19 seem to be somewhat of an anomaly as we observe a sharp decrease in the number of infected followed by a surge. This could be due to many reasons, for example poor statistics recording (we are considering a group of people under heavy stress likely more motivated by trying to stay alive than to record accurate vital statistics). So here we are interested in finding a parameter $\\beta$ that captures the general dynamics (increase followed by a post-peak decrease) of the outbreak. You can expect to find a reasonable value for $\\beta$ but be aware that many values, especially too high, will result in a very poor match between real data and model predictions.\n\n\n```python\nfrom ipywidgets import interact_manual, widgets\nimport matplotlib.pyplot as plt\n\n# set style\ns = {'description_width': 'initial'}\n\n# Set interact manual box widget for beta\n@interact_manual(answer=widgets.FloatText(\n    value=1.50,\n    description='Enter a value for ' + r'$ \\beta$',\n    disabled=False,\n    style = s,\n    step=0.01\n))\n\n# define function to find the appropriate value of beta\n# this function takes as input a floating value and outputs a plot with the best fit curve\ndef find_beta(answer):\n    \n    # set initial values for SIR model\n    S1,I1,R1 = 254,7,0\n    \n    # Use original data on Number of infected from table in the notebook\n    ori_data = [7,14,22,29,21,8,21,0]\n    \n    # use days, time data was provided biweekly, we transform to days here\n    ori_days = [1,14,28,42,56,70,84,112]\n    \n    # set number of days as the second to last entry on the ori_days array \n    n = ori_days[len(ori_days)-1]-ori_days[0]+1\n    \n    # get beta from answer - to be sure transform to float\n    beta = float(answer)\n    \n    # Gamma was obtained from disease\n    gamma = 1/11\n    \n    # Compute SIR values using our discrete_SIR function\n    (S,I,R) = discrete_SIR(S1,I1,R1,n,beta,gamma)\n    \n    # Figure\n    fig,ax = plt.subplots(figsize=(10,10))\n \n    # Scatter plot of original number of infected in the course of 112 days\n    plt.scatter(ori_days,ori_data,c=\"blue\", label=\"Original data\")\n    \n    # Scatter plot of infected obtained from SIR mode, in the course of 112 days\n    plt.scatter(range(n),I,c=\"red\",label=\"SIR Model Predictions\")\n    \n    # Make the plot pretty\n    plt.xlabel('Time (days)')\n    plt.ylabel('Infected Individuals')\n    plt.title('Real Data vs Model')\n    legend = ax.legend()\n    plt.show()\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>interactive</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n\n```python\nprint(\"Press the Run Interact Button to Obtain the True Answer\")\n\ndef true_beta():\n    print('The best value for Beta is approximately   0.14909440503418078.')\n    \ninteract_manual(true_beta);\n```\n\n    Press the Run Interact Button to Obtain the True Answer\n\n\n\n<p>Failed to display Jupyter Widget of type <code>interactive</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n<h2 align='center'>Simulating a Disease Outbreak</h2>\n\nTo conclude, we will use the widgets below to simulate a disease outbreak using the SIR model. \nYou can chose the values of all the elements of the model (sizes of the compartments of the population at the beginning of the outbreak, parameters $\\gamma$ and $\\beta$, duration in days (one time unit is one day then) of the outbreak. The default parameters are the ones of the Eyam plague outbreak.\n\nThe result is a series of three graphs that shows how the three compartment of the population evolve during the outbreak. It gives you the possibility to appreciate visually the impact of changes in the parameters $\\gamma$ and $\\beta$, such as increasing $\\beta$ (making the outbreak progress faster) or reducing $\\gamma$ (i.e. reducing the rate of removal).\n\nYou can use this interactive tool to try to apply by hand the SIR model with simple parameters and see if your calculations match with the model outcome.\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom math import ceil\n\n# This function takes as input initial values of susceptible, infected and removed, number of days, beta and gamma\n# it plots the SIR model with the above conditions\ndef plot_SIR(S1,I1,R1,n,beta,gamma):\n    \n    # Initialize figure\n    fig = plt.figure(facecolor='w',figsize=(17,5))\n    ax  = fig.add_subplot(111,facecolor = '#ffffff')\n    \n    # Compute SIR values for our initial data and parameters\n    (S_f,I_f,R_f) = discrete_SIR(S1,I1,R1,n,beta,gamma)    \n    \n    # Set x axis\n    x = [i for i in range(n)]\n   \n    # Scatter plot of evolution of susceptible over the course of x days\n    plt.scatter(x,S_f,c= 'b',label='Susceptible')\n    \n    # Scatter plot of evolution of infected over the course of x days\n    plt.scatter(x,I_f,c='r',label='Infected')\n    \n    # Scatter plot of evolution of removed over the course of x days\n    plt.scatter(x,R_f,c='g',label='Removed')\n\n    # Make the plot pretty\n    plt.xlabel('Time (days)')\n    plt.ylabel('Number of individuals')\n    plt.title('Simulation of a disease outbreak using the SIR model')\n    legend = ax.legend()\n    plt.show()\n    \n    # Print messages to aid student understand and interpret what is happening in the plot\n    print(\"SIMULATION DATA\\n\")\n    print(\"Beta: \" + str(beta))\n    print(\"Gamma: \" + str(gamma))\n    print(\"\\n\")\n    print(\"Initial Conditions:\")\n    print(\"Total number of Susceptible: \"  + str(ceil(S_f[0])))\n    print(\"Total number of Infected: \"  + str(ceil(I_f[0])))\n    print(\"Total number of Removed: \"  + str(ceil(R_f[0])))\n    print(\"\\n\")\n    print(\"After \" + str(n) + \" days:\")\n    print(\"Total number of Susceptible: \"  + str(ceil(S_f[n-1])))\n    print(\"Total number of Infected: \"  + str(ceil(I_f[n-1])) )\n    print(\"Total number of Removed: \"  + str(ceil(R_f[n-1])))\n# Tweaking initial Values\nfrom ipywidgets import widgets, interact, interact_manual\n\n# Set function above so that the user can set all parameters and manually start simulation\ns = {'description_width': 'initial'}\ninteract_manual(plot_SIR,\n        S1  =widgets.IntSlider(value = 254,\n                               min = 200,\n                               max = 1000,\n                               step = 1,\n                               style=s,\n                               description=\"Susceptible Initial\",\n                               disabled=False,\n                               orientation='horizontal',\n                               readout=True),\n        I1 = widgets.IntSlider(value = 7,\n                               min = 0,\n                               max = 500,\n                               step = 1,\n                               style=s,\n                               description=\"Infected Initial\",\n                               disabled=False,\n                               orientation='horizontal',\n                               readout=True),\n         R1 = widgets.IntSlider(value = 0,\n                               min = 0,\n                               max = 500,\n                               step = 1,\n                               style=s,\n                               description=\"Removed Initial\",\n                               disabled=False,\n                               orientation='horizontal',\n                               readout=True),\n         n = widgets.IntSlider(value = 112,\n                               min = 0,\n                               max = 500,\n                               step = 1,\n                               style=s,\n                               description=\"Time (days)\",\n                               disabled=False,\n                               orientation='horizontal',\n                               readout=True),\n         beta = widgets.FloatText(\n    value=1.50,\n    description=r'$ \\beta$ parameter',\n    disabled=False,\n    style = s,\n    step=0.01\n),\n        gamma = widgets.FloatText(\n    value=1.50,\n    description= r'$ \\gamma$ parameter',\n    disabled=False,\n    style = s,\n    step=0.01\n)\n        );\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>interactive</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n<h2 align='center'>Conclusion</h2>\n\nIn this notebook we learned about the SIR discrete model to model an outbreak. We learned that this model is one of the simplest ones and that it separates the total population $N$ (a constant) into three categories: Infected, Susceptible and Removed. We learned about rates of infection and removal and how this affects the number of individuals in each class. \n\nWe also ran a basic but realistic simulation of a bubonic plague outbreak of the Great Plague of London that took place in the village Eyam in 1665 and learned about the devastating effect this had on the population. \n\n\n```python\n# Counter for toggling achievement indicator on/off\n\nphoto_ctr = 0\n\n# Photo sources\n\n#### Picture Sources:\n\npline_1 = \"#### Picture Sources\"\npline_2 = \"The sources of pictures (ordered by appearance in the notebook from top to bottom) are listed below:\"\npline_2 = \"[1] The plague transmission cycle. http://www.columbia.edu/itc/cerc/danoff-burg/invasion_bio/inv_spp_summ/Yersinia_pestis.htm on June 13, 2018.\"\npline_3 = \"[2] The Black Death Timeline. https://en.wikipedia.org/wiki/Consequences_of_the_Black_Death and modified by notebook authors.\"\npline_4 = \"[3] Kitasato Shibasabur\u014d (left) and Alexandre Yersin (right). Left image retrieved from https://commons.wikimedia.org/wiki/File:Shibasaburo_Kitasato.jpg ; Right image retrieved from https://en.wikipedia.org/wiki/Alexandre_Yersin#/media/File:Petit-Yersin.jpg\"\n\n# Use to print lines, then save in lines_list\n\ndef print_plines(n):\n    \n    lines_str = \"\"\n    \n    for i in range(1,n+1):\n        lines_str = lines_str + \"pline_\"+str(i)+\",\"\n        \n    lines_str = lines_str[:-1]\n\n    print(lines_str)\n\nplines_list = [pline_1,pline_2,pline_3,pline_4]\n\n# Show/Hide buttons\n\nps_button_show = widgets.Button(button_style='info',description=\"Show Picture Sources\", layout=Layout(width='25%', height='30px') )\nps_button_hide = widgets.Button(button_style='info',description=\"Hide Picture Sources\", layout=Layout(width='25%', height='30px') )\n```\n\n\n```python\nphoto_ctr += 1\n\nif(photo_ctr % 2 == 0):\n\n    for pline in plines_list:\n        display(Markdown(pline))\n    \n    display(ps_button_hide)\n    ps_button_hide.on_click( run_current )\n    \nelse:\n\n    display(ps_button_show)\n    ps_button_show.on_click( run_current )\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n#### Picture Sources\n\n\n\n[1] The plague transmission cycle. http://www.columbia.edu/itc/cerc/danoff-burg/invasion_bio/inv_spp_summ/Yersinia_pestis.htm on June 13, 2018.\n\n\n\n[2] The Black Death Timeline. https://en.wikipedia.org/wiki/Consequences_of_the_Black_Death and modified by notebook authors.\n\n\n\n[3] Kitasato Shibasabur\u014d (left) and Alexandre Yersin (right). Left image retrieved from https://commons.wikimedia.org/wiki/File:Shibasaburo_Kitasato.jpg ; Right image retrieved from https://en.wikipedia.org/wiki/Alexandre_Yersin#/media/File:Petit-Yersin.jpg\n\n\n\n<p>Failed to display Jupyter Widget of type <code>Button</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n \n", "meta": {"hexsha": "ee93506b82b1172395b3ef41eed89670e791a884", "size": 82885, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Humanities/BubonicPlague/bubonic-plague-and-SIR-model.ipynb", "max_stars_repo_name": "jazwinkicks/jaz-callysto", "max_stars_repo_head_hexsha": "f9414e275c3cc38bc7266f105e0dcb57ad483ae0", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Humanities/BubonicPlague/bubonic-plague-and-SIR-model.ipynb", "max_issues_repo_name": "jazwinkicks/jaz-callysto", "max_issues_repo_head_hexsha": "f9414e275c3cc38bc7266f105e0dcb57ad483ae0", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Humanities/BubonicPlague/bubonic-plague-and-SIR-model.ipynb", "max_forks_repo_name": "jazwinkicks/jaz-callysto", "max_forks_repo_head_hexsha": "f9414e275c3cc38bc7266f105e0dcb57ad483ae0", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.2527901786, "max_line_length": 1375, "alphanum_fraction": 0.594944803, "converted": true, "num_tokens": 13539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1403362494900832, "lm_q2_score": 0.12940272991290905, "lm_q1q2_score": 0.018159893789755854}}
{"text": "<a href=\"https://colab.research.google.com/github/ChrizZhuang/marginalized_graph_kernel_protein/blob/main/Docking_0612.ipynb\" target=\"_parent\"></a>\n\n## Set up the environment\n\n\n```\n!nvidia-smi\n```\n\n    NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver. Make sure that the latest NVIDIA driver is installed and running.\n    \n\n\n\n```\n#!pip install pymatgen==2020.12.31\n!pip install pymatgen==2019.11.11\n!pip install --pre graphdot\n!pip install gdown\n```\n\n    Collecting pymatgen==2019.11.11\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/57/f8/1d5f9bacde237107f917a5ca31bdf73e55a774ffb8e7b9e5f9cd7d7cf114/pymatgen-2019.11.11.tar.gz (2.5MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.5MB 6.7MB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.14.3 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.19.5)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.23.0)\n    Collecting ruamel.yaml>=0.15.6\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/74/c6/0aa1aaaa56c9d320f19d9ca3f8304bc6ace8fab95932b1602cbe091ae4a3/ruamel.yaml-0.17.9-py3-none-any.whl (108kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 112kB 32.3MB/s \n    \u001b[?25hCollecting monty>=3.0.2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/31/26/e14afc57b4dd6c9b8c6d4b3f70dd0b4f1550ba263711e345845354bc84d9/monty-2021.6.10-py3-none-any.whl (65kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 71kB 7.1MB/s \n    \u001b[?25hRequirement already satisfied: scipy>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.4.1)\n    Collecting pydispatcher>=2.0.5\n      Downloading https://files.pythonhosted.org/packages/cd/37/39aca520918ce1935bea9c356bcbb7ed7e52ad4e31bff9b943dfc8e7115b/PyDispatcher-2.0.5.tar.gz\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (0.8.9)\n    Collecting spglib>=1.9.9.44\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/4b/98/fa4760b9c71e2eace5a60b85dbf36dece49c379f8291cf1203056f287766/spglib-1.16.1-cp37-cp37m-manylinux2010_x86_64.whl (296kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 296kB 29.7MB/s \n    \u001b[?25hRequirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.5.1)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (3.2.2)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (3.3.0)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.7.1)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.1.5)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (2020.12.5)\n    Collecting ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\"\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/5e/6e/f652c56bbb2c3d3fca252ffc7c0358597f57a1bbdf484dac683054950c63/ruamel.yaml.clib-0.2.2-cp37-cp37m-manylinux1_x86_64.whl (547kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 552kB 33.3MB/s \n    \u001b[?25hRequirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.2->pymatgen==2019.11.11) (4.4.2)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (0.10.0)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (2.8.1)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (1.3.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (2.4.7)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->pymatgen==2019.11.11) (1.2.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen==2019.11.11) (2018.9)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from cycler>=0.10->matplotlib>=1.5->pymatgen==2019.11.11) (1.15.0)\n    Building wheels for collected packages: pymatgen, pydispatcher\n      Building wheel for pymatgen (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pymatgen: filename=pymatgen-2019.11.11-cp37-cp37m-linux_x86_64.whl size=3324761 sha256=6cf93e611e6c47a15bab07470b9e6718adc4a580ac5569075626887f5b463b02\n      Stored in directory: /root/.cache/pip/wheels/98/23/3c/3b929997e5f8976361933411e8a3b9bdf1b2702e7830e7a7ad\n      Building wheel for pydispatcher (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pydispatcher: filename=PyDispatcher-2.0.5-cp37-none-any.whl size=11517 sha256=9b0107e8759a73beda58fbdf3018d4c4562209d5d65c3b4ccdda07dedb62904e\n      Stored in directory: /root/.cache/pip/wheels/88/99/96/cfef6665f9cb1522ee6757ae5955feedf2fe25f1737f91fa7f\n    Successfully built pymatgen pydispatcher\n    Installing collected packages: ruamel.yaml.clib, ruamel.yaml, monty, pydispatcher, spglib, pymatgen\n    Successfully installed monty-2021.6.10 pydispatcher-2.0.5 pymatgen-2019.11.11 ruamel.yaml-0.17.9 ruamel.yaml.clib-0.2.2 spglib-1.16.1\n    Collecting graphdot\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/71/e6/af9d1784a6757a9e70a8ef2160f006d0fc46a913c82354b2825cd79a4e40/graphdot-0.8a17.tar.gz (103kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 112kB 6.9MB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.19.5)\n    Requirement already satisfied: scipy>=1.3.0 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.4.1)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.7.1)\n    Requirement already satisfied: pandas>=0.24 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.1.5)\n    Requirement already satisfied: networkx>=2.4 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2.5.1)\n    Collecting pycuda>=2019\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/5a/56/4682a5118a234d15aa1c8768a528aac4858c7b04d2674e18d586d3dfda04/pycuda-2021.1.tar.gz (1.7MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.7MB 10.0MB/s \n    \u001b[?25h  Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n      Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n        Preparing wheel metadata ... \u001b[?25l\u001b[?25hdone\n    Collecting treelib>=1.6.1\n      Downloading https://files.pythonhosted.org/packages/04/b0/2269c328abffbb63979f7143351a24a066776b87526d79956aea5018b80a/treelib-1.6.1.tar.gz\n    Collecting kahypar>=1.1.4\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/d2/c6/4b6ff807f2136079e9bc7289a793544541de4a04b402c678524647d6b0cb/kahypar-1.1.6-cp37-cp37m-manylinux2014_x86_64.whl (1.1MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.1MB 24.3MB/s \n    \u001b[?25hRequirement already satisfied: numba>=0.51.0 in /usr/local/lib/python3.7/dist-packages (from graphdot) (0.51.2)\n    Collecting tqdm>=4.55\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/42/d7/f357d98e9b50346bcb6095fe3ad205d8db3174eb5edb03edfe7c4099576d/tqdm-4.61.0-py2.py3-none-any.whl (75kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 81kB 7.5MB/s \n    \u001b[?25hCollecting ase>=3.17\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/a5/36/de17e79f29e06d9a92746d0dd9ec4636487ab03f6af10e78586aae533f7a/ase-3.21.1-py3-none-any.whl (2.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.2MB 39.4MB/s \n    \u001b[?25hRequirement already satisfied: pymatgen==2019.11.11 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2019.11.11)\n    Collecting mendeleev>=0.7\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1d/8c/364f691a79162bed173069e3882c39baa315daf1336434c6c9b322078e61/mendeleev-0.7.0-py3-none-any.whl (175kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 184kB 40.5MB/s \n    \u001b[?25hRequirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->graphdot) (1.2.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->graphdot) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->graphdot) (2.8.1)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.4->graphdot) (4.4.2)\n    Collecting pytools>=2011.2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/52/26/c7ab098ceb4e4e3f0e66e21257a286bb455ea22af7afefbd704d9ccf324c/pytools-2021.2.7.tar.gz (63kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 71kB 7.8MB/s \n    \u001b[?25hRequirement already satisfied: appdirs>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (1.4.4)\n    Collecting mako\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/f3/54/dbc07fbb20865d3b78fdb7cf7fa713e2cba4f87f71100074ef2dc9f9d1f7/Mako-1.1.4-py2.py3-none-any.whl (75kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 81kB 8.5MB/s \n    \u001b[?25hRequirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from treelib>=1.6.1->graphdot) (0.16.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from numba>=0.51.0->graphdot) (57.0.0)\n    Requirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba>=0.51.0->graphdot) (0.34.0)\n    Requirement already satisfied: matplotlib>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from ase>=3.17->graphdot) (3.2.2)\n    Requirement already satisfied: pydispatcher>=2.0.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2.0.5)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2021.6.10)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (1.16.1)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (0.17.9)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (0.8.9)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2.23.0)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (3.3.0)\n    Collecting Pygments<3.0.0,>=2.8.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/a6/c9/be11fce9810793676017f79ffab3c6cb18575844a6c7b8d4ed92f95de604/Pygments-2.9.0-py3-none-any.whl (1.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.0MB 39.8MB/s \n    \u001b[?25hRequirement already satisfied: six<2.0.0,>=1.15.0 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (1.15.0)\n    Requirement already satisfied: SQLAlchemy<2.0.0,>=1.3.23 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (1.4.15)\n    Collecting pyfiglet<0.9,>=0.8.post1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/33/07/fcfdd7a2872f5b348953de35acce1544dab0c1e8368dca54279b1cde5c15/pyfiglet-0.8.post1-py2.py3-none-any.whl (865kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 870kB 38.4MB/s \n    \u001b[?25hCollecting colorama<0.5.0,>=0.4.4\n      Downloading https://files.pythonhosted.org/packages/44/98/5b86278fbbf250d239ae0ecb724f8572af1c91f4a11edf4d36a206189440/colorama-0.4.4-py2.py3-none-any.whl\n    Requirement already satisfied: MarkupSafe>=0.9.2 in /usr/local/lib/python3.7/dist-packages (from mako->pycuda>=2019->graphdot) (2.0.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.0.0->ase>=3.17->graphdot) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.0.0->ase>=3.17->graphdot) (1.3.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.0.0->ase>=3.17->graphdot) (2.4.7)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen==2019.11.11->graphdot) (0.2.2)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (1.24.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (2020.12.5)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (2.10)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (4.0.1)\n    Requirement already satisfied: greenlet!=0.4.17; python_version >= \"3\" in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (1.1.0)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (3.4.1)\n    Requirement already satisfied: typing-extensions>=3.6.4; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (3.7.4.3)\n    Building wheels for collected packages: pycuda\n      Building wheel for pycuda (PEP 517) ... \u001b[?25l\u001b[?25hcanceled\n    \u001b[31mERROR: Operation cancelled by user\u001b[0m\n    Requirement already satisfied: gdown in /usr/local/lib/python3.7/dist-packages (3.6.4)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from gdown) (2.23.0)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from gdown) (4.41.1)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from gdown) (1.15.0)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (2.10)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (2020.12.5)\n\n\n\n```\n%matplotlib inline\nimport io\nimport sys\nsys.path.append('/usr/local/lib/python3.6/site-packages/')\nimport os\nimport urllib\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport graphdot\nfrom graphdot import Graph\nfrom graphdot.graph.adjacency import AtomicAdjacency\nfrom graphdot.graph.reorder import rcm\nfrom graphdot.kernel.marginalized import MarginalizedGraphKernel # https://graphdot.readthedocs.io/en/latest/apidoc/graphdot.kernel.marginalized.html\nfrom graphdot.kernel.marginalized.starting_probability import Uniform\nfrom graphdot.model.gaussian_process import (\n    GaussianProcessRegressor,\n    LowRankApproximateGPR\n)\nfrom graphdot.kernel.fix import Normalization\nimport graphdot.microkernel as uX\nimport ase.io\n\n# for getting all file names into a list under a directory \nfrom os import listdir\n# for getting file names that match certain pattern\nimport glob\nimport time\n```\n\n\n```\nfrom google.colab import drive\ndrive.mount('/content/gdrive', force_remount=True)\n```\n\n\n```\n#cd gdrive/MyDrive/Google\\ Colab/Covid-Data\n%cd gdrive/MyDrive/Covid-Data/\n```\n\n    /content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data\n\n\n\n```\n!pwd\n```\n\n    /content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data\n\n\n\n```\n!mkdir /content/pkls\n```\n\n## load the data\n\n\n```\nfiles  = ['uncharged_NSP15_6W01_A_3_H.Orderable_zinc_db_enaHLL.2col.csv.1.xz']\ndataset = pd.read_pickle(files[0]) # length of each csv file is 100000\n```\n\n\n```\ntarget = 'energy'\nbatch_size = 1000\nbatch_num_train = 0.8*len(dataset)//batch_size # batch number of training\nnum_test = 0.2*len(dataset)\ntrain_data = dataset.iloc[:int(batch_num_train)*batch_size]\ntest_data = dataset.iloc[int(batch_num_train)*batch_size:len(dataset)]\n#print(len(train_data))\n#print(len(test_data))\n```\n\n\n```\ngpr = GaussianProcessRegressor(\n    # kernel is the covariance function of the gaussian process (GP)\n    kernel=Normalization( # kernel equals to normalization -> normalizes a kernel using the cosine of angle formula, k_normalized(x,y) = k(x,y)/sqrt(k(x,x)*k(y,y))\n        # graphdot.kernel.fix.Normalization(kernel), set kernel as marginalized graph kernel, which is used to calculate the similarity between 2 graphs\n        # implement the random walk-based graph similarity kernel as Kashima, H., Tsuda, K., & Inokuchi, A. (2003). Marginalized kernels between labeled graphs. ICML\n        MarginalizedGraphKernel( \n            # node_kernel - A kernelet that computes the similarity between individual nodes\n            # uX - graphdot.microkernel - microkernels are positive-semidefinite functions between individual nodes and edges of graphs\n            node_kernel=uX.Additive( # addition of kernal matrices: sum of k_a(X_a, Y_a) cross for a in features\n                # uX.Constant - a kernel that returns a constant value, always mutlipled with other microkernels as an adjustable weight\n                #   c, the first input arg. as 0.5, (0.01, 10) the lower and upper bounds of c that is allowed to vary during hyperpara. optimizartion\n                # uX.KroneckerDelta - a kronecker delta returns 1 when two features are equal and return h (the first input arg here, which is 0.5 in this case) otherwise\n                #   (0.1, 0.9) the lower and upper bounds that h is allowed to vary during hyperpara. optimization\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 2nd element of graphdot.graph.Graph.nodes\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 3rd element of graphdot.graph.Graph.nodes\n                # uX.SquareExponential - Equ. 26 in the paper\n                # input arg. length_sacle is a float32, set as 1 in this case, which correspond to approx. 1 of the kernal value. \n                # This is used to determins how quicklys should the kernel decay to zero.\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0), # the 4th element of graphdot.graph.Graph.nodes\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 5th element of graphdot.graph.Graph.nodes\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0), # the 6th element of graphdot.graph.Graph.nodes\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 7th element of graphdot.graph.Graph.nodes\n                # uX.Convolution - a convolutional microkernel which averages evaluations of a base microkernel between pairs pf elememts of two variable-length feature sequences\n                # uX.KroneckerDelta as the base kernel\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9))) # the 8th element of graphdot.graph.Graph.nodes\n            ).normalized,\n            # edge_kernel - A kernelet that computes the similarity between individual edge\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 3rd element of graphdot.graph.Graph.nodes\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 4th element of graphdot.graph.Graph.nodes\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 5th element of graphdot.graph.Graph.nodes\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 6th element of graphdot.graph.Graph.nodes\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)) # the 7th element of graphdot.graph.Graph.nodes\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'), # the strating probability of the random walk on each node\n            q=0.05 # the probability for the random walk to stop during each step\n        )\n    ),\n    alpha=1e-4, # value added to the diagonal of the kernel matrix during fitting\n    optimizer=True, # default optimizer of L-BFGS-B based on scipy.optimize.minimize\n    normalize_y=True, # normalize the y values so taht the means and variance is 0 and 1, repsectively. Will be reversed when predicions are returned\n    regularization='+', # alpha (1e-4 in this case) is added to the diagonals of the kernal matrix\n)\n```\n\n\n```\ndef train_pipeline_batch(model, train_dataset, test_dataset, target, repeats, batch_num_train, batch_size, verbose = True, print_batch = True, print_repeat = True):\n  start_time = time.time()\n  for repeat in range(0, repeats):\n    for batch in range(0, int(batch_num_train)-1):\n      batch_dataset = dataset.iloc[batch*batch_size:(batch+1)*batch_size] # divide the training data into different batches\n      np.random.seed(0)\n      if batch == 0 and repeat == 0:\n        model.fit(batch_dataset.graphs, batch_dataset[target], repeat=1, verbose=verbose)\n        model.save(path=\"/content/pkls\", filename='batch_0_repeat_0.pkl', overwrite=True)\n      elif batch == 0 and repeat !=0:\n        filename_load = 'batch_0_repeat_'+str(repeat-1)+'.pkl'\n        filename_save = 'batch_0_repeat_'+str(repeat)+'.pkl'\n        model.load(path=\"/content/pkls\", filename=filename_load)\n        model.fit(batch_dataset.graphs, batch_dataset[target], repeat=1, verbose=verbose)\n        model.save(path=\"/content/pkls\", filename=filename_save, overwrite=True)\n      else:\n        filename_load = 'batch_'+str(batch-1)+'_repeat_'+str(repeat)+'.pkl'\n        filename_save = 'batch_'+str(batch)+'_repeat_'+str(repeat)+'.pkl'\n        model.load(path=\"/content/pkls\", filename=filename_load)\n        model.fit(batch_dataset.graphs, batch_dataset[target], repeat=1, verbose=verbose)\n        model.save(path=\"/content/pkls\", filename=filename_save, overwrite=True)\n      \n      if print_batch:\n        mu = gpr.predict(train_dataset.graphs)\n        print('Training set of repeat '+str(repeat)+' and batch '+str(batch))\n        print('MAE '+str(repeat)+' and batch '+str(batch)+' '+str(np.mean(np.abs(train_dataset[target] - mu))))\n        print('MAE '+str(repeat)+' and batch '+str(batch)+' '+str(np.std(train_dataset[target] - mu)))\n\n    if print_repeat:\n      mu = gpr.predict(train_dataset.graphs)\n      print('Training set of repeat '+str(repeat))\n      print('MAE '+str(repeat)+' '+str(np.mean(np.abs(train_dataset[target] - mu))))\n      print('RMSE '+str(repeat)+' '+str(np.std(train_dataset[target] - mu)))\n\n      mu = gpr.predict(test_dataset.graphs)\n      print('Test set of repeat '+str(repeat))\n      print('MAE '+str(repeat)+' '+str(np.mean(np.abs(test_dataset[target] - mu))))\n      print('RMSE '+str(repeat)+' '+str(np.std(test_dataset[target] - mu)))\n    \n  \n  end_time = time.time()\n  print(\"the total time consumption is \" + str(end_time - start_time) + \".\")\n```\n\n\n```\ntrain_pipeline_batch(gpr, train_data, test_data, target, repeats=2, batch_num_train=batch_num_train, batch_size=batch_size, print_batch = False, print_repeat = True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  2.7019e+06|  2.2685e+07|  2.7092e+06|       -7280|  8.8043e+06|        24|      0.25|\n    |  1.8512e+06|  1.8823e+07|  1.8579e+06|     -6735.2|  8.2346e+06|        19|      0.27|\n    |  1.2939e+06|  1.4683e+07|  1.3001e+06|     -6265.2|  7.4903e+06|        19|      0.24|\n    |   1.021e+06|  1.1806e+07|   1.027e+06|     -5976.5|  6.9101e+06|        18|      0.24|\n    |  8.4287e+05|  9.4751e+06|  8.4862e+05|     -5749.5|  6.3466e+06|        18|      0.23|\n    |  7.2809e+05|  7.8466e+06|  7.3366e+05|     -5576.7|  5.8859e+06|        17|      0.25|\n    |  6.6283e+05|  6.9824e+06|   6.683e+05|     -5466.4|  5.6067e+06|        17|      0.24|\n    |   6.453e+05|  6.6156e+06|  6.5075e+05|     -5449.8|  5.3891e+06|        16|      0.26|\n    |  6.2547e+05|  6.4794e+06|  6.3087e+05|     -5403.8|  5.3829e+06|        17|      0.24|\n    |  6.2055e+05|  6.4456e+06|  6.2594e+05|     -5391.4|   5.384e+06|        17|      0.24|\n    |  6.1894e+05|  6.4304e+06|  6.2433e+05|     -5388.3|  5.3926e+06|        17|      0.25|\n    |   6.178e+05|  6.4214e+06|  6.2318e+05|     -5386.2|  5.3914e+06|        17|      0.24|\n    |  6.1814e+05|  6.3747e+06|  6.2354e+05|     -5397.9|  5.3791e+06|        17|      0.25|\n    |  6.1618e+05|  6.3821e+06|  6.2157e+05|     -5388.5|  5.3778e+06|        17|      0.25|\n    |  6.1335e+05|  6.3652e+06|  6.1873e+05|     -5381.7|  5.3525e+06|        17|      0.26|\n    |  6.1233e+05|  6.3563e+06|  6.1771e+05|     -5379.5|  5.3384e+06|        17|      0.25|\n    |  6.1205e+05|  6.3576e+06|  6.1743e+05|     -5378.5|  5.3368e+06|        17|      0.26|\n    |  6.1146e+05|  6.3598e+06|  6.1684e+05|       -5377|  5.3372e+06|        17|      0.24|\n    |  6.1112e+05|  6.3567e+06|  6.1649e+05|     -5377.5|  5.3386e+06|        17|      0.26|\n    |  6.1095e+05|  6.3619e+06|  6.1633e+05|     -5379.9|  5.3312e+06|        17|      0.25|\n    |  6.1097e+05|  6.3587e+06|  6.1635e+05|     -5379.1|  5.3324e+06|        17|      0.24|\n    |  6.1098e+05|  6.3615e+06|  6.1636e+05|     -5379.6|   5.331e+06|        17|      0.25|\n    |  6.1095e+05|  6.3619e+06|  6.1633e+05|     -5379.8|  5.3323e+06|        17|      0.27|\n    |  6.1109e+05|   6.364e+06|  6.1647e+05|     -5379.7|  5.3318e+06|        17|      0.25|\n    |  6.1094e+05|  6.3613e+06|  6.1632e+05|     -5379.8|  5.3306e+06|        17|      0.25|\n    |  6.1084e+05|  6.3595e+06|  6.1622e+05|     -5379.8|  5.3289e+06|        17|      0.26|\n    |  6.1099e+05|  6.3624e+06|  6.1637e+05|     -5379.8|  5.3313e+06|        17|      0.25|\n    |  6.1114e+05|   6.366e+06|  6.1652e+05|     -5379.8|  5.3311e+06|        17|      0.24|\n    |  6.1091e+05|  6.3612e+06|  6.1629e+05|     -5379.8|  5.3308e+06|        17|      0.25|\n    |  6.1081e+05|  6.3455e+06|  6.1619e+05|     -5378.9|  5.3347e+06|        17|      0.26|\n    |  6.1077e+05|  6.3501e+06|  6.1615e+05|     -5378.8|  5.3316e+06|        17|      0.25|\n    |  6.1084e+05|  6.3545e+06|  6.1622e+05|     -5378.8|  5.3302e+06|        17|      0.27|\n    |  6.1078e+05|  6.3509e+06|  6.1616e+05|     -5378.8|   5.336e+06|        17|      0.25|\n    |  6.1085e+05|  6.3511e+06|  6.1622e+05|     -5378.8|  5.3315e+06|        17|      0.24|\n    |  6.1093e+05|  6.3539e+06|  6.1631e+05|     -5378.8|  5.3313e+06|        17|      0.25|\n    |  6.1077e+05|  6.3502e+06|  6.1614e+05|     -5378.8|  5.3306e+06|        17|      0.26|\n    |  6.1078e+05|  6.3505e+06|  6.1616e+05|     -5378.8|   5.332e+06|        17|      0.25|\n    |  6.1086e+05|  6.3518e+06|  6.1624e+05|     -5378.8|  5.3318e+06|        17|      0.25|\n    Optimization result:\n          fun: 610859.9288216699\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 6.34797657e+02,  1.24118936e+02,  2.81935737e+01, -3.04708834e+01,\n            1.44803317e+04,  2.72483890e+02,  0.00000000e+00,  1.70986591e+01,\n            3.73893389e+01, -3.08340510e+02,  6.74914910e-19,  9.64312176e+01,\n            3.50275984e+01, -1.88838360e+02,  1.59526427e+04,  1.86513089e+02,\n            2.60343189e+03,  2.09813558e+02,  2.99666451e+03, -4.67071932e+02,\n            1.27795063e+02,  1.00516230e+02,  0.00000000e+00, -3.03309420e+01,\n            3.52006775e+02])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 38\n          nit: 22\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -1.83482135,  1.56469333, -2.30258509,\n           -4.60517019,  0.        , -4.34462918, -2.30258509,  2.30258509,\n           -2.38498025, -4.60517019, -1.79605729,  1.66070648, -2.30258509,\n            0.85422024, -2.30258509,  0.995156  , -2.30258509, -2.68851944,\n           -2.30258509, -4.60517019, -0.22314355, -1.16410687, -2.30258509])\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  5.9481e+05|  6.2118e+06|  6.0024e+05|     -5429.6|  5.7437e+06|        18|      0.24|\n    |  6.0133e+05|  6.1615e+06|  6.0679e+05|     -5458.5|  5.8272e+06|        17|      0.25|\n    |   5.944e+05|  6.1849e+06|  5.9983e+05|     -5431.9|  5.7542e+06|        17|      0.28|\n    |  5.9439e+05|  6.1855e+06|  5.9982e+05|     -5431.7|  5.7515e+06|        17|      0.25|\n    |  5.9431e+05|  6.1854e+06|  5.9974e+05|     -5430.8|  5.7528e+06|        17|      0.25|\n    |  5.9384e+05|  6.1725e+06|  5.9927e+05|       -5430|  5.7482e+06|        17|      0.24|\n    |   5.938e+05|  6.1683e+06|  5.9923e+05|     -5429.8|  5.7531e+06|        17|      0.26|\n    |   5.937e+05|  6.1624e+06|  5.9913e+05|     -5429.9|  5.7516e+06|        17|      0.25|\n    |   5.937e+05|  6.1583e+06|  5.9913e+05|       -5430|   5.752e+06|        17|      0.24|\n    |  5.9345e+05|  6.1559e+06|  5.9888e+05|     -5429.9|  5.7505e+06|        17|      0.24|\n    |  5.9359e+05|    6.15e+06|  5.9902e+05|       -5430|  5.7568e+06|        17|      0.24|\n    |  5.9367e+05|  6.1598e+06|   5.991e+05|     -5429.9|  5.7535e+06|        17|      0.24|\n    |  5.9365e+05|  6.1605e+06|  5.9908e+05|     -5429.9|  5.7486e+06|        17|      0.24|\n    |   5.935e+05|  6.1566e+06|  5.9893e+05|     -5429.9|  5.7468e+06|        17|      0.25|\n    |   5.936e+05|  6.1592e+06|  5.9903e+05|     -5429.9|  5.7476e+06|        17|      0.25|\n    |  5.9361e+05|  6.1594e+06|  5.9904e+05|     -5429.9|   5.754e+06|        17|      0.24|\n    |  5.9352e+05|  6.1573e+06|  5.9895e+05|     -5429.9|  5.7496e+06|        17|      0.25|\n    Optimization result:\n          fun: 593521.9933959157\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 6.15385325e+02,  1.01738091e+02,  2.82061742e+01, -1.82698311e+02,\n            1.40009664e+04,  2.61063767e+02,  0.00000000e+00,  9.53384764e+01,\n            2.31015442e+01, -1.30701897e+02,  6.56896566e-19, -5.34736159e+01,\n            8.94133316e+01, -1.06596521e+02,  1.42422016e+04,  3.80569253e+02,\n            2.36758463e+03, -3.88042888e+01,  2.54268625e+03, -3.44421752e+02,\n            1.49739713e+02,  7.35780675e+01,  0.00000000e+00, -6.95844521e+01,\n            8.65877797e+01])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 17\n          nit: 8\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -1.89424069,  1.5728804 , -2.30258509,\n           -4.60517019,  0.        , -4.45529998, -2.30258509,  2.30258509,\n           -2.38498025, -4.05997156, -1.8923729 ,  1.59072464, -2.30258509,\n            1.08135167, -2.30258509,  1.13352734, -2.30258509, -1.99203168,\n           -2.30258509, -4.60517019, -0.22314355, -2.33867933, -2.30258509])\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  6.7918e+05|  6.7795e+06|  6.8463e+05|     -5443.6|  5.6734e+06|        19|      0.25|\n    |  6.8865e+05|  7.0808e+06|   6.941e+05|     -5452.2|  5.6674e+06|        18|      0.27|\n    |  6.7806e+05|   6.816e+06|   6.835e+05|       -5439|  5.6573e+06|        18|      0.25|\n    |  6.7756e+05|  6.8056e+06|    6.83e+05|     -5439.1|  5.6628e+06|        18|      0.24|\n    |  6.7769e+05|  6.8098e+06|  6.8312e+05|     -5439.1|  5.6645e+06|        18|      0.23|\n    |  6.7751e+05|  6.8055e+06|  6.8295e+05|     -5439.1|  5.6599e+06|        18|      0.25|\n    |  6.7756e+05|  6.8066e+06|    6.83e+05|     -5439.1|  5.6626e+06|        18|      0.25|\n    |   6.775e+05|  6.8048e+06|  6.8294e+05|     -5439.1|    5.66e+06|        18|      0.26|\n    |  6.7761e+05|  6.8072e+06|  6.8305e+05|     -5439.1|  5.6612e+06|        18|      0.24|\n    |  6.7753e+05|  6.8053e+06|  6.8297e+05|     -5439.1|  5.6621e+06|        18|      0.26|\n    |  6.7773e+05|    6.81e+06|  6.8317e+05|     -5439.1|  5.6581e+06|        18|      0.24|\n    |  6.7767e+05|  6.8085e+06|  6.8311e+05|     -5439.1|   5.661e+06|        18|      0.24|\n    |  6.7769e+05|  6.8095e+06|  6.8313e+05|     -5439.1|  5.6576e+06|        18|      0.23|\n    |  6.7766e+05|  6.8076e+06|   6.831e+05|     -5439.1|  5.6636e+06|        18|      0.24|\n    |  6.7761e+05|  6.8066e+06|  6.8305e+05|     -5439.1|  5.6631e+06|        18|      0.24|\n    |  6.7769e+05|  6.8089e+06|  6.8313e+05|     -5439.1|  5.6632e+06|        18|      0.25|\n    Optimization result:\n          fun: 677692.6401785224\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 6.80512584e+02,  1.28840642e+02,  2.96629868e+01, -7.29874759e+02,\n            1.36275207e+04,  2.98268612e+02,  0.00000000e+00, -1.77306432e+02,\n            6.43238550e+01, -1.79567708e+02,  6.78413983e-19,  5.27798047e+01,\n            7.98979646e+01,  6.02840236e+02,  1.72504386e+04,  4.53894124e+02,\n            2.48814034e+03, -1.14971440e+03,  3.28390348e+03,  5.53570210e+01,\n            1.40288671e+02,  8.81082261e+01,  0.00000000e+00,  5.53603835e+02,\n            2.79202758e+01])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 16\n          nit: 4\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -1.9033415 ,  1.40832592, -2.30258509,\n           -4.60517019,  0.        , -4.30759609, -2.30258509,  2.1892741 ,\n           -2.38498025, -4.07223178, -1.90198197,  1.65353414, -2.30258509,\n            0.95306768, -2.30258509,  1.17073124, -2.30258509, -1.89984995,\n           -2.30258509, -4.60517019, -0.22314355, -2.39282005, -2.30258509])\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  5.8564e+05|   6.384e+06|  5.9109e+05|     -5447.9|  5.8972e+06|        19|      0.25|\n    |  5.9558e+05|  6.7613e+06|  6.0105e+05|     -5478.2|  5.9725e+06|        18|      0.26|\n    |  5.8358e+05|  6.4363e+06|  5.8903e+05|     -5448.4|  5.9087e+06|        17|      0.24|\n    |  5.8333e+05|  6.4272e+06|  5.8878e+05|     -5448.5|  5.9124e+06|        18|      0.25|\n    |  5.8349e+05|  6.4306e+06|  5.8894e+05|     -5448.6|  5.9182e+06|        18|      0.24|\n    |   5.834e+05|  6.4289e+06|  5.8885e+05|     -5448.5|  5.9177e+06|        18|      0.24|\n    |  5.8332e+05|  6.4267e+06|  5.8877e+05|     -5448.5|  5.9153e+06|        18|      0.24|\n    |  5.8345e+05|  6.4296e+06|  5.8889e+05|     -5448.5|  5.9147e+06|        18|      0.26|\n    |  5.8339e+05|  6.4282e+06|  5.8884e+05|     -5448.5|  5.9176e+06|        17|      0.24|\n    |   5.835e+05|  6.4307e+06|  5.8895e+05|     -5448.5|  5.9164e+06|        17|      0.24|\n    Optimization result:\n          fun: 583498.1821292299\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 6.42636679e+02,  1.49586433e+02,  2.61368055e+01, -7.23074350e+02,\n            1.43314276e+04,  3.00500436e+02,  0.00000000e+00, -2.05942373e+02,\n            7.55571246e+01, -7.56525792e+02,  5.58467338e-19,  1.68639173e+02,\n            5.83197677e+01,  1.03984575e+03,  1.81859964e+04,  5.85507772e+02,\n            1.73017504e+03, -4.20613902e+02,  2.69164210e+03,  2.03198468e+02,\n            8.87212800e+01,  7.15099972e+01,  0.00000000e+00, -4.38153824e+02,\n            1.30113827e+02])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 10\n          nit: 3\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -1.91300979,  1.451537  , -2.30258509,\n           -4.60517019,  0.        , -4.14911734, -2.30258509,  2.03112438,\n           -2.38498025, -4.0860788 , -1.91191534,  1.70143255, -2.30258509,\n            0.81516434, -2.30258509,  1.20228816, -2.30258509, -1.96563782,\n           -2.30258509, -4.60517019, -0.22314355, -2.27803721, -2.30258509])\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  5.6983e+05|  6.1842e+06|   5.752e+05|     -5376.5|  5.3707e+06|        19|      0.24|\n    |  5.7184e+05|  6.0505e+06|  5.7724e+05|     -5396.4|  5.4669e+06|        17|      0.24|\n    |  5.6769e+05|  6.0911e+06|  5.7307e+05|       -5379|  5.4036e+06|        17|      0.23|\n    |  5.6717e+05|  6.0754e+06|  5.7255e+05|     -5378.1|  5.3927e+06|        17|      0.24|\n    |   5.672e+05|  6.0787e+06|  5.7258e+05|     -5378.2|  5.3932e+06|        17|      0.23|\n    |  5.6724e+05|  6.0771e+06|  5.7261e+05|     -5378.1|   5.396e+06|        17|      0.24|\n    |  5.6712e+05|  6.0745e+06|   5.725e+05|     -5378.1|  5.3921e+06|        17|      0.25|\n    |  5.6718e+05|  6.0754e+06|  5.7256e+05|     -5378.1|  5.3904e+06|        17|      0.24|\n    |  5.6719e+05|  6.0766e+06|  5.7257e+05|     -5378.1|  5.3949e+06|        17|      0.25|\n    |  5.6715e+05|  6.0753e+06|  5.7253e+05|     -5378.1|  5.3903e+06|        17|      0.23|\n    |  5.6725e+05|    6.08e+06|  5.7262e+05|     -5378.2|  5.3918e+06|        17|      0.23|\n    |  5.6717e+05|  6.0761e+06|  5.7255e+05|     -5378.1|  5.3925e+06|        17|      0.25|\n    |  5.6715e+05|  6.0754e+06|  5.7253e+05|     -5378.1|  5.3897e+06|        17|      0.24|\n    |  5.6708e+05|  6.0739e+06|  5.7245e+05|     -5378.1|  5.3918e+06|        17|      0.24|\n    |  5.6736e+05|  6.0803e+06|  5.7274e+05|     -5378.1|  5.3887e+06|        17|      0.25|\n    |  5.6724e+05|  6.0783e+06|  5.7261e+05|     -5378.1|  5.3911e+06|        17|      0.24|\n    |  5.6717e+05|  6.0757e+06|  5.7254e+05|     -5378.1|  5.3936e+06|        17|      0.24|\n    Optimization result:\n          fun: 567166.579508662\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 6.07208753e+02,  1.16400806e+02,  2.94031809e+01, -1.72776793e+03,\n            1.35443977e+04,  2.88635663e+02,  0.00000000e+00, -1.08433778e+03,\n            1.83096192e+02,  2.13385801e+03,  6.02314568e-19,  1.24870900e+02,\n            6.00556807e+01,  1.45101987e+02,  1.41791665e+04,  1.50959272e+03,\n            2.28162930e+03, -1.61859228e+03,  3.18130856e+03, -3.51209513e+02,\n            2.08717946e+02,  9.51302212e+01,  0.00000000e+00,  3.65194505e+02,\n            5.97260799e+01])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 17\n          nit: 4\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -1.92550128,  1.42696149, -2.30258509,\n           -4.60517019,  0.        , -3.93589447, -2.30258509,  2.10117436,\n           -2.38498025, -4.10359282, -1.9247698 ,  1.4879669 , -2.30258509,\n            0.84022785, -2.30258509,  1.04438252, -2.30258509, -1.82947763,\n           -2.30258509, -4.60517019, -0.22314355, -2.35477534, -2.30258509])\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  6.0983e+05|  6.5503e+06|  6.1526e+05|       -5422|  5.6888e+06|        19|      0.23|\n    |  6.2633e+05|  7.0232e+06|  6.3178e+05|     -5450.2|  5.7844e+06|        18|      0.24|\n    |  6.0916e+05|  6.5794e+06|  6.1458e+05|       -5421|  5.6922e+06|        17|      0.23|\n    |  6.0896e+05|   6.576e+06|  6.1438e+05|     -5420.9|  5.6982e+06|        17|      0.25|\n    |  6.0878e+05|  6.5684e+06|   6.142e+05|     -5422.1|  5.7015e+06|        17|      0.24|\n    |  6.0878e+05|    6.57e+06|   6.142e+05|     -5422.5|  5.7048e+06|        17|      0.23|\n    |  6.0875e+05|  6.5676e+06|  6.1417e+05|     -5422.2|  5.7044e+06|        17|      0.25|\n    |  6.0865e+05|  6.5657e+06|  6.1407e+05|     -5422.2|  5.7012e+06|        17|      0.24|\n    |  6.0856e+05|  6.5647e+06|  6.1399e+05|     -5422.4|  5.7036e+06|        17|      0.24|\n    |   6.087e+05|  6.5675e+06|  6.1412e+05|     -5422.4|  5.7052e+06|        17|      0.25|\n    |  6.0858e+05|  6.5645e+06|    6.14e+05|     -5422.4|  5.7034e+06|        17|      0.25|\n    |  6.0817e+05|  6.5775e+06|   6.136e+05|     -5426.9|  5.7249e+06|        17|      0.25|\n    |   6.079e+05|   6.572e+06|  6.1333e+05|     -5424.7|  5.7167e+06|        17|      0.25|\n    |  6.0784e+05|  6.5813e+06|  6.1326e+05|       -5424|   5.709e+06|        18|      0.25|\n    |  6.0782e+05|  6.5832e+06|  6.1325e+05|     -5424.1|  5.7066e+06|        18|      0.26|\n    |  6.0774e+05|  6.5826e+06|  6.1316e+05|       -5424|  5.7022e+06|        17|      0.24|\n    |  6.0778e+05|  6.5896e+06|  6.1321e+05|     -5423.9|  5.7019e+06|        17|      0.24|\n    |   6.078e+05|   6.586e+06|  6.1322e+05|       -5424|  5.7052e+06|        17|      0.23|\n    |  6.0772e+05|  6.5833e+06|  6.1314e+05|       -5424|  5.7057e+06|        17|      0.25|\n    |  6.0775e+05|  6.5827e+06|  6.1317e+05|       -5424|  5.7018e+06|        17|      0.24|\n    |  6.0771e+05|  6.5828e+06|  6.1313e+05|       -5424|  5.7036e+06|        17|      0.23|\n    |   6.078e+05|  6.5908e+06|  6.1322e+05|     -5424.2|  5.7032e+06|        17|      0.23|\n    |  6.0783e+05|  6.5851e+06|  6.1325e+05|     -5424.1|  5.7023e+06|        17|      0.22|\n    |  6.0773e+05|  6.5828e+06|  6.1315e+05|       -5424|  5.7061e+06|        17|      0.23|\n    |  6.0772e+05|   6.583e+06|  6.1314e+05|       -5424|  5.7041e+06|        17|      0.23|\n\n\n\n```\ngpr.kernel.hyperparameters\n```\n\n\n\n\n    starting_probability : Uniform\n    \tp : 1.0\n    stopping_probability : 0.00010000000000000009\n    node_kernel : Composite\n    \taromatic : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.02343420535068002\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.18860200789175988\n    \tatomic_number : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 5.400776905055444\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tcharge : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.0145590563621646\n    \t\trhs : SquareExponential\n    \t\t\tlength_scale : 1.0\n    \tchiral : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.05149063984443944\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.12853164901299938\n    \thcount : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 10.000000000000002\n    \t\trhs : SquareExponential\n    \t\t\tlength_scale : 0.07795674396128768\n    \thybridization : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.02783411902444354\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.17414808329497075\n    \tring_list : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 6.550981640628747\n    \t\trhs : Convolution\n    \t\t\tbase : KroneckerDelta\n    \t\t\t\th : 0.10000000000000002\n    edge_kernel : Composite\n    \taromatic : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 2.331300736214766\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tconjugated : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 3.166641607522053\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \torder : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.05549109210250382\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.25478481015091287\n    \tring_stereo : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.033323606027544916\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.8\n    \tstereo : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.1324351226762118\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.14521546104851712\n\n\n\n\n```\nmu = gpr.predict(train.graphs)\n```\n\n\n```\nplt.scatter(train[target], mu)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.2074369392067814\n    RMSE: 0.3195501910711287\n\n\n\n```\nmu_test = gpr.predict(test.graphs)\n```\n\n\n```\nplt.scatter(test[target], mu_test)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 1.2461703788060545\n    RMSE: 1.6040210737240486\n\n\nWork\u0001on the kernel. Find a kernel that trains and predicts well.\n\n\n```\ngpr2 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-2, #different from gpr in alpha where gpr's alpha is 1e-4\n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\n#gpr2.fit(train.graphs, train[target], repeat=3, verbose=True)\ngpr2.fit(train.graphs, train[target], repeat=1, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |   1.667e+05|   1.928e+05|  1.7773e+05|      -11034|  2.2742e+05|   1.3e+02|       1.7|\n    |  1.5585e+05|  2.2171e+05|  1.6671e+05|      -10857|  2.2218e+05|   1.3e+02|       1.7|\n    |  1.3711e+05|  2.4873e+05|  1.4756e+05|      -10447|  2.0803e+05|   1.2e+02|       1.8|\n    |  1.3286e+05|  2.3627e+05|   1.432e+05|      -10338|  2.0336e+05|   1.1e+02|       1.7|\n    |  1.2977e+05|  2.2744e+05|  1.4002e+05|      -10249|  1.9714e+05|   1.1e+02|       1.7|\n    |  1.3006e+05|  2.1429e+05|  1.4032e+05|      -10258|  2.0119e+05|     1e+02|       1.7|\n    |  1.2923e+05|  2.2103e+05|  1.3946e+05|      -10238|  1.9906e+05|   1.1e+02|       1.7|\n    |  1.2888e+05|  2.2097e+05|  1.3911e+05|      -10228|  1.9865e+05|   1.1e+02|       1.7|\n    |  1.2843e+05|  2.2338e+05|  1.3864e+05|      -10211|  1.9582e+05|   1.1e+02|       1.7|\n    |  1.2837e+05|  2.2244e+05|  1.3858e+05|      -10212|   1.969e+05|   1.1e+02|       1.7|\n    |  1.2836e+05|  2.2225e+05|  1.3857e+05|      -10212|  1.9696e+05|   1.1e+02|       1.7|\n    |  1.2831e+05|  2.2155e+05|  1.3852e+05|      -10211|  1.9715e+05|   1.1e+02|       1.7|\n    |  1.2826e+05|  2.2184e+05|  1.3847e+05|      -10209|  1.9704e+05|   1.1e+02|       1.7|\n    |  1.2821e+05|  2.2181e+05|  1.3841e+05|      -10207|  1.9671e+05|   1.1e+02|       1.7|\n    |  1.2819e+05|  2.2165e+05|   1.384e+05|      -10207|  1.9664e+05|   1.1e+02|       1.8|\n    |  1.2818e+05|  2.2125e+05|  1.3838e+05|      -10207|  1.9671e+05|   1.1e+02|       1.8|\n    |  1.2817e+05|  2.2114e+05|  1.3838e+05|      -10207|  1.9673e+05|   1.1e+02|       1.7|\n    |  1.2815e+05|  2.2077e+05|  1.3836e+05|      -10207|  1.9677e+05|   1.1e+02|       1.7|\n    |  1.2812e+05|   2.185e+05|  1.3833e+05|      -10209|  1.9695e+05|   1.1e+02|       1.7|\n    |  1.2809e+05|   2.178e+05|   1.383e+05|      -10209|    1.97e+05|   1.1e+02|       1.7|\n    |  1.2807e+05|  2.1764e+05|  1.3828e+05|      -10208|  1.9695e+05|   1.1e+02|       1.7|\n    |  1.2805e+05|  2.1597e+05|  1.3826e+05|      -10209|  1.9693e+05|   1.1e+02|       1.7|\n    |  1.2805e+05|   2.172e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1693e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.8|\n    |  1.2804e+05|  2.1674e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1691e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2805e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.8|\n    |  1.2805e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    Optimization result:\n          fun: 128045.20193517115\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 21.67035135,   5.42797631,   0.91584794,   6.62684845,\n           636.88297304,  10.22203408,   0.        ,   6.13155297,\n             0.80318432, -45.79780911,   0.        ,   9.32446636,\n             2.06137402,   7.94609186, 767.483899  ,  -8.19180354,\n            92.93654292,   7.92503084, 118.62629465,   3.36719643,\n            38.71995733,   7.96834618,   0.        , -11.08475724,\n             7.2860016 ])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 31\n          nit: 21\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.51710969, -1.98267626,  1.72521606, -2.30258509,\n           -4.60517019,  0.        , -4.60517019, -1.8070945 ,  2.30258509,\n           -2.88031384, -3.6019383 , -2.30258509,  1.91177723, -2.30258509,\n            0.28746812, -2.30258509,  0.54884256, -2.30258509, -0.5686784 ,\n           -2.30258509, -4.35637808, -0.22314355, -2.55717239, -2.21179129])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7f6bf00630d0>\n\n\n\n\n```\nmu = gpr2.predict(train.graphs)\nplt.scatter(train[target], mu)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.7238389142657052\n    RMSE: 0.9634943206325994\n\n\n\n```\nmu_test = gpr2.predict(test.graphs)\nplt.scatter(test[target], mu_test)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 0.9561539409612109\n    RMSE: 1.2284268143181998\n\n", "meta": {"hexsha": "b04146460ce26680a4cfb1027e8298d9682cfb35", "size": 128473, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Docking_0612.ipynb", "max_stars_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_stars_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Docking_0612.ipynb", "max_issues_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_issues_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Docking_0612.ipynb", "max_forks_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_forks_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 104.4495934959, "max_line_length": 16574, "alphanum_fraction": 0.7023966125, "converted": true, "num_tokens": 22694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3451052574867685, "lm_q2_score": 0.052618953347713764, "lm_q1q2_score": 0.018159077443747017}}
{"text": "```python\n# code for loading the format for the notebook\nimport os\n\n# path : store the current path to convert back to it later\npath = os.getcwd()\nos.chdir( os.path.join('..', 'notebook_format') )\nfrom formats import load_style\nload_style()\n```\n\n\n\n\n<style>\n@import url('http://fonts.googleapis.com/css?family=Source+Code+Pro');\n@import url('http://fonts.googleapis.com/css?family=Vollkorn');\n@import url('http://fonts.googleapis.com/css?family=Arimo');\n@import url('http://fonts.googleapis.com/css?family=Fira_sans');\n\n    div.cell {\n        width: 1000px;\n        margin-left: 0% !important;\n        margin-right: auto;\n    }\n    div.text_cell code {\n        background: transparent;\n        color: #000000;\n        font-weight: 600;\n        font-size: 12pt;\n        font-style: bold;\n        font-family:  'Source Code Pro', Consolas, monocco, monospace;\n    }\n    h1 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n\t}\n\n    div.input_area {\n        background: #F6F6F9;\n        border: 1px solid #586e75;\n    }\n\n    .text_cell_render h1 {\n        font-weight: 200;\n        font-size: 30pt;\n        line-height: 100%;\n        color:#c76c0c;\n        margin-bottom: 0.5em;\n        margin-top: 1em;\n        display: block;\n        white-space: wrap;\n        text-align: left;\n    } \n    h2 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n        text-align: left;\n    }\n    .text_cell_render h2 {\n        font-weight: 200;\n        font-size: 16pt;\n        font-style: italic;\n        line-height: 100%;\n        color:#c76c0c;\n        margin-bottom: 0.5em;\n        margin-top: 1.5em;\n        display: block;\n        white-space: wrap;\n        text-align: left;\n    } \n    h3 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n    }\n    .text_cell_render h3 {\n        font-weight: 200;\n        font-size: 14pt;\n        line-height: 100%;\n        color:#d77c0c;\n        margin-bottom: 0.5em;\n        margin-top: 2em;\n        display: block;\n        white-space: wrap;\n        text-align: left;\n    }\n    h4 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n    }\n    .text_cell_render h4 {\n        font-weight: 100;\n        font-size: 14pt;\n        color:#d77c0c;\n        margin-bottom: 0.5em;\n        margin-top: 0.5em;\n        display: block;\n        white-space: nowrap;\n    }\n    h5 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n    }\n    .text_cell_render h5 {\n        font-weight: 200;\n        font-style: normal;\n        color: #1d3b84;\n        font-size: 16pt;\n        margin-bottom: 0em;\n        margin-top: 0.5em;\n        display: block;\n        white-space: nowrap;\n    }\n    div.text_cell_render{\n        font-family: 'Fira sans', verdana,arial,sans-serif;\n        line-height: 125%;\n        font-size: 115%;\n        text-align:justify;\n        text-justify:inter-word;\n    }\n    div.output_wrapper{\n        margin-top:0.2em;\n        margin-bottom:0.2em;\n    }\n\n    code{\n      font-size: 70%;\n    }\n    .rendered_html code{\n    background-color: transparent;\n    }\n    ul{\n        margin: 2em;\n    }\n    ul li{\n        padding-left: 0.5em; \n        margin-bottom: 0.5em; \n        margin-top: 0.5em; \n    }\n    ul li li{\n        padding-left: 0.2em; \n        margin-bottom: 0.2em; \n        margin-top: 0.2em; \n    }\n    ol{\n        margin: 2em;\n    }\n    ol li{\n        padding-left: 0.5em; \n        margin-bottom: 0.5em; \n        margin-top: 0.5em; \n    }\n    ul li{\n        padding-left: 0.5em; \n        margin-bottom: 0.5em; \n        margin-top: 0.2em; \n    }\n    a:link{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:visited{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:hover{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:focus{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:active{\n       font-weight: bold;\n       color:#447adb;\n    }\n    .rendered_html :link {\n       text-decoration: underline; \n    }\n    .rendered_html :hover {\n       text-decoration: none; \n    }\n    .rendered_html :visited {\n      text-decoration: none;\n    }\n    .rendered_html :focus {\n      text-decoration: none;\n    }\n    .rendered_html :active {\n      text-decoration: none;\n    }\n    .warning{\n        color: rgb( 240, 20, 20 )\n    } \n    hr {\n      color: #f3f3f3;\n      background-color: #f3f3f3;\n      height: 1px;\n    }\n    blockquote{\n      display:block;\n      background: #fcfcfc;\n      border-left: 5px solid #c76c0c;\n      font-family: 'Open sans',verdana,arial,sans-serif;\n      width:680px;\n      padding: 10px 10px 10px 10px;\n      text-align:justify;\n      text-justify:inter-word;\n      }\n      blockquote p {\n        margin-bottom: 0;\n        line-height: 125%;\n        font-size: 100%;\n      }\n</style>\n\n\n\n\n\n\n```python\nos.chdir(path)\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# 1. magic for inline plot\n# 2. magic to print version\n# 3. magic so that the notebook will reload external python modules\n%matplotlib inline\n%load_ext watermark\n%load_ext autoreload \n%autoreload 2\n\nfrom sklearn import datasets\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\n\n%watermark -a 'Ethen' -d -t -v -p numpy,pandas,matplotlib,sklearn\n```\n\n    Ethen 2017-06-22 14:02:06 \n    \n    CPython 3.5.2\n    IPython 5.4.1\n    \n    numpy 1.12.1\n    pandas 0.20.2\n    matplotlib 2.0.2\n    sklearn 0.18.1\n\n\n# Softmax Regression\n\n**Softmax Regression** is a generalization of logistic regression that we can use for multi-class classification. If we want to assign probabilities to an object being one of several different things, softmax is the thing to do. Even later on, when we start training neural network models, the final step will be a layer of softmax.\n\nA softmax regression has two steps: first we add up the evidence of our input being in certain classes, and then we convert that evidence into probabilities.\n\nIn **Softmax Regression**, we replace the sigmoid logistic function by the so-called *softmax* function $\\phi(\\cdot)$.\n\n$$P(y=j \\mid z^{(i)}) = \\phi(z^{(i)}) = \\frac{e^{z^{(i)}}}{\\sum_{j=1}^{k} e^{z_{j}^{(i)}}}$$\n\nwhere we define the net input *z* as \n\n$$z = w_1x_1 + ... + w_mx_m  + b= \\sum_{l=1}^{m} w_l x_l + b= \\mathbf{w}^T\\mathbf{x} + b$$ \n\n(**w** is the weight vector, $\\mathbf{x}$ is the feature vector of 1 training sample. Each $w$ corresponds to a feature $x$ and there're $m$ of them in total. $b$ is the bias unit. $k$ denotes the total number of classes.)   \n\nNow, this softmax function computes the probability that the $i_{th}$ training sample $\\mathbf{x}^{(i)}$ belongs to class $l$ given the weight and net input $z^{(i)}$. So given the obtained weight $w$, we're basically compute the probability, $p(y = j \\mid \\mathbf{x^{(i)}; w}_j)$, the probability of the training sample belonging to class $j$ for each class label in $j = 1, \\ldots, k$. Note the normalization term in the denominator which causes these class probabilities to sum up to one.\n\nWe can picture our softmax regression as looking something like the following, although with a lot more $x_s$. For each output, we compute a weighted sum of the $x_s$, add a bias, and then apply softmax.\n\n\n\nIf we write that out as equations, we get:\n\n\n\nWe can \"vectorize\" this procedure, turning it into a matrix multiplication and vector addition. This is helpful for computational efficiency. (It's also a useful way to think.)\n\n\n\nTo illustrate the concept of softmax, let us walk through a concrete example. Suppose we have a training set consisting of 4 samples from 3 different classes (0, 1, and 2)\n\n- $x_0 \\rightarrow \\text{class }0$\n- $x_1 \\rightarrow \\text{class }1$\n- $x_2 \\rightarrow \\text{class }2$\n- $x_3 \\rightarrow \\text{class }2$\n\nFirst, we apply one-hot encoding to encode the class labels into a format that we can more easily work with.\n\n\n```python\ny = np.array([0, 1, 2, 2])\n\ndef one_hot_encode(y):\n    n_class = np.unique(y).shape[0]\n    y_encode = np.zeros((y.shape[0], n_class))\n    for idx, val in enumerate(y):\n        y_encode[idx, val] = 1.0\n    \n    return y_encode\n\ny_encode = one_hot_encode(y)\ny_encode\n```\n\n\n\n\n    array([[ 1.,  0.,  0.],\n           [ 0.,  1.,  0.],\n           [ 0.,  0.,  1.],\n           [ 0.,  0.,  1.]])\n\n\n\nA sample that belongs to class 0 (the first row) has a 1 in the first cell, a sample that belongs to class 1 has a 1 in the second cell of its row, and so forth.\n\nNext, let us define the feature matrix of our 4 training samples. Here, we assume that our dataset consists of 2 features; thus, we create a 4x2 dimensional matrix of our samples and features.\nSimilarly, we create a 2x3 dimensional weight matrix (one row per feature and one column for each class).\n\n\n```python\nX = np.array([[0.1, 0.5],\n              [1.1, 2.3],\n              [-1.1, -2.3],\n              [-1.5, -2.5]])\n\nW = np.array([[0.1, 0.2, 0.3],\n              [0.1, 0.2, 0.3]])\n\nbias = np.array([0.01, 0.1, 0.1])\n\nprint('Inputs X:\\n', X)\nprint('\\nWeights W:\\n', W)\nprint('\\nbias:\\n', bias)\n```\n\n    Inputs X:\n     [[ 0.1  0.5]\n     [ 1.1  2.3]\n     [-1.1 -2.3]\n     [-1.5 -2.5]]\n    \n    Weights W:\n     [[ 0.1  0.2  0.3]\n     [ 0.1  0.2  0.3]]\n    \n    bias:\n     [ 0.01  0.1   0.1 ]\n\n\nTo compute the net input, we multiply the 4x2 matrix feature matrix `X` with the 2x3 (n_features x n_classes) weight matrix `W`, which yields a 4x3 output matrix (n_samples x n_classes) to which we then add the bias unit: \n\n$$\\mathbf{Z} = \\mathbf{X}\\mathbf{W} + \\mathbf{b}$$\n\n\n```python\ndef net_input(X, W, b):\n    return X.dot(W) + b\n\nnet_in = net_input(X, W, bias)\nprint('net input:\\n', net_in)\n```\n\n    net input:\n     [[ 0.07  0.22  0.28]\n     [ 0.35  0.78  1.12]\n     [-0.33 -0.58 -0.92]\n     [-0.39 -0.7  -1.1 ]]\n\n\nNow, it's time to compute the softmax activation that we discussed earlier:\n\n$$P(y=j \\mid z^{(i)}) = \\phi_{softmax}(z^{(i)}) = \\frac{e^{z^{(i)}}}{\\sum_{j=1}^{k} e^{z_{j}^{(i)}}}$$\n\n\n```python\ndef softmax(z):\n    return np.exp(z) / np.sum(np.exp(z), axis = 1, keepdims = True)\n\nsmax = softmax(net_in)\nprint('softmax:\\n', smax)\n```\n\n    softmax:\n     [[ 0.29450637  0.34216758  0.36332605]\n     [ 0.21290077  0.32728332  0.45981591]\n     [ 0.42860913  0.33380113  0.23758974]\n     [ 0.44941979  0.32962558  0.22095463]]\n\n\nAs we can see, the values for each sample (row) nicely sum up to 1 now. E.g., we can say that the first sample  `[ 0.29450637  0.34216758  0.36332605]` has a 29.45% probability to belong to class 0. Now, in order to turn these probabilities back into class labels, we could simply take the argmax-index position of each row:\n\n[[ 0.29450637  0.34216758  **0.36332605**] -> 2   \n[ 0.21290077  0.32728332  **0.45981591**]  -> 2  \n[ **0.42860913**  0.33380113  0.23758974]  -> 0  \n[ **0.44941979**  0.32962558  0.22095463]] -> 0  \n\n\n```python\ndef to_classlabel(z):\n    return z.argmax(axis = 1)\n\nprint('predicted class labels: ', to_classlabel(smax))\n```\n\n    predicted class labels:  [2 2 0 0]\n\n\nAs we can see, our predictions are terribly wrong, since the correct class labels are `[0, 1, 2, 2]`. Now, in order to train our model we need to measuring how inefficient our predictions are for describing the truth and then optimize on it. To do so we first need to define a loss/cost function $J(\\cdot)$ that we want to minimize. One very common function is \"cross-entropy\":\n\n$$J(\\mathbf{W}; \\mathbf{b}) = \\frac{1}{n} \\sum_{i=1}^{n} H( T^{(i)}, O^{(i)} )$$\n\nwhich is the average of all cross-entropies $H$ over our $n$ training samples. The cross-entropy  function is defined as:\n\n$$H( T^{(i)}, O^{(i)} ) = -\\sum_k T^{(i)} \\cdot log(O^{(i)})$$\n\nWhere:\n\n- $T$ stands for \"target\" (i.e., the *true* class labels) \n- $O$ stands for output -- the computed *probability* via softmax; **not** the predicted class label.\n- $\\sum_k$ denotes adding up the difference between the target and the output for all classes.\n\n\n```python\ndef cross_entropy_cost(y_target, output):\n    return np.mean(-np.sum(y_target * np.log(output), axis = 1))\n\ncost = cross_entropy_cost(y_target = y_encode, output = smax)\nprint('Cross Entropy Cost:', cost)\n```\n\n    Cross Entropy Cost: 1.32159787159\n\n\n## Gradient Descent\n\nOur objective in training a neural network is to find a set of weights that gives us the lowest error when we run it against our training data. There're many ways to find these weights and simplest one is so called **gradient descent**. It does this by giving us directions (using derivatives) on how to \"shift\" our weights to an optimum. It tells us whether we should increase or decrease the value of a specific weight in order to lower the error function.\n\nLet's imagine we have a function $f(x) = x^4 - 3x^3 + 2$ and we want to find the minimum of this function using gradient descent. Here's a graph of that function:\n\n\n```python\nfrom sympy.plotting import plot\nfrom sympy import symbols, init_printing\n\n# change default figure and font size\nplt.rcParams['figure.figsize'] = 6, 4 \nplt.rcParams['font.size'] = 12\n\n# plotting f(x) = x^4 - 3x^3 + 2, showing -2 < x <4\ninit_printing()\nx = symbols('x')\nfx = x ** 4 - 3 * x ** 3 + 2\np1 = plot(fx, (x, -2, 4), ylim = (-10, 50))\n```\n\nAs you can see, there appears to be a minimum around ~2.3 or so. Gradient descent answers this question: If we were to start with a random value of x, which direction should we go if we want to get to the lowest point on this function? Let's imagine we pick a random x value, say <b>x = 4</b>, which would be somewhere way up on the right side of the graph. We obviously need to start going to the left if we want to get to the bottom. This is obvious when the function is an easily visualizable 2d plot, but when dealing with functions of multiple variables, we need to rely on the raw mathematics.\n\nCalculus tells us that the derivative of a function at a particular point is the rate of change/slope of the tangent to that part of the function. So let's use derivatives to help us get to the bottom of this function. The derivative of $f(x) = x^4 - 3x^3 + 2$ is $f'(x) = 4x^3 - 9x^2$. So if we plug in our random point from above (x=4) into the first derivative of $f(x)$ we get $f'(4) = 4(4)^3 - 9(4)^2 = 112$. So how does 112 tell us where to go? Well, first of all, it's positive. If we were to compute $f'(-1)$ we get a negative number (-13). So it looks like we can say that whenever the $f'(x)$ for a particular $x$ is positive, we should move to the left (decrease x) and whenever it's negative, we should move to the right (increase x).\n\nWe'll now formalize this: When we start with a random x and compute it's deriative $f'(x)$, our <b>new x</b> should then be proportional to $x - f'(x)$. The word proportional is there because we wish to control <em>to what degree</em> we move at each step, for example when we compute $f'(4)=112$, do we really want our new $x$ to be $x - 112 = -108$? No, if we jump all the way to -108, we're even farther from the minimum than we were before. Instead, we want to take relatively <em>small</em> steps toward the minimum. \n\nLet's say that for any random $x$, we want to take a step (change $x$ a little bit) such that our <b>new $x$</b> $ = x - \\alpha*f'(x)$. We'll call $\\alpha$ (alpha) our <em>learning rate or step size</em> because it determines how big of a step we take. $\\alpha$ is something we will just have to play around with to find a good value. Some functions might require bigger steps, others smaller steps.\n\nSuppose we've set our $\\alpha$ to be 0.001. This means, if we randomly started at $f'(4)=112$ then our new $x$ will be $ = 4 - (0.001 * 112) = 3.888$. So we moved to the left a little bit, toward the optimum. Let's do it again. $x_{new} = x - \\alpha*f'(3.888) = 3.888 - (0.001 * 99.0436) = 3.79$. Nice, we're indeed moving to the left, closer to the minimum of $f(x)$, little by little. And we'll keep on doing this until we've reached convergence. By convergence, we mean that if the absolute value of the difference between the updated $x$ and the old $x$ is smaller than some randomly small number that we set, denoted as $\\epsilon$ (epsilon).\n\n\n```python\nx_old = 0\nx_new = 4 # The algorithm starts at x = 4\nalpha = 0.01 # step size\nepsilon = 0.00001\n\ndef f_derivative(x):\n    return 4 * x ** 3 - 9 * x ** 2\n\nwhile abs(x_new - x_old) > epsilon:\n    x_old = x_new\n    x_new = x_old - alpha * f_derivative(x_old)\n\nprint(\"Local minimum occurs at\", x_new)\n```\n\n    Local minimum occurs at 2.2500325268933734\n\n\nThe script above says that if the absolute difference of $x$ between the two iterations is not changing by more than 0.00001, then we're probably at the bottom of the \"bowl\" because our slope is approaching 0, and therefore we should stop and call it a day. Now, if you remember some calculus and algebra, you could have solved for this minimum analytically, and you should get 2.25. Very close to what our gradient descent algorithm above found.\n\n## More Gradient Descent...\n\nAs you might imagine, when we use gradient descent for a neural network, things get a lot more complicated. Not because gradient descent gets more complicated, it still ends up just being a matter of taking small steps downhill, it's that we need that pesky derivative in order to use gradient descent, and the derivative of a neural network cost function (with respect to its weights) is pretty intense. It's not a matter of just analytically solving $f(x)=x^2, f'(x)=2x$ , because the output of a neural net has many nested or \"inner\" functions.\n\nAlso unlike our toy math problem above, a neural network may have many weights. We need to find the optimal value for each individual weight to lower the cost for our entire neural net output. This requires taking the partial derivative of the cost/error function with respect to a single weight, and then running gradient descent for each individual weight. Thus, for any individual weight $W_j$, we'll compute the following:\n\n$$ W_j^{(t + 1)} = W_j^{(t)} - \\alpha * \\frac{\\partial L}{\\partial W_j}$$ \n\nWhere:\n\n- $L$ denotes the loss function that we've defined.\n- $W_j^{(t)}$ denotes the weight of the $j_{th}$ feature at iteration $t$.\n\nAnd as before, we do this iteratively for each weight, many times, until the whole network's cost function is minimized.\n\nIn order to learn the weight for our softmax model via gradient descent, we then need to compute the gradient of our cost function for each class $j \\in \\{0, 1, ..., k\\}$.\n\n$$\\nabla \\mathbf{w}_j \\, J(\\mathbf{W}; \\mathbf{b})$$\n\nWe won't be going through the tedious details here, but this cost's gradient turns out to be simply:\n\n$$\\nabla \\mathbf{w}_j \\, J(\\mathbf{W}; \\mathbf{b}) = \\frac{1}{n} \\sum^{n}_{i=0} \\big[\\mathbf{x}^{(i)}_j\\ \\big( O^{(i)} - T^{(i)} \\big) \\big]$$\n\nWe can then use the cost derivate to update the weights in opposite direction of the cost gradient with learning rate $\\eta$:\n\n$$\\mathbf{w}_j := \\mathbf{w}_j - \\eta \\nabla \\mathbf{w}_j \\, J(\\mathbf{W}; \\mathbf{b})$$ \n\n(note that $\\mathbf{w}_j$ is the weight vector for the class $y=j$), and we update the bias units using:\n\n$$\n\\mathbf{b}_j := \\mathbf{b}_j   - \\eta \\bigg[ \\frac{1}{n} \\sum^{n}_{i=0} \\big( O^{(i)} - T^{(i)} \\big) \\bigg]\n$$ \n \n\nAs a penalty against complexity, an approach to reduce the variance of our model and decrease the degree of overfitting by adding additional bias, we can further add a regularization term such as the L2 term with the regularization parameter $\\lambda$:\n    \n$$\\frac{\\lambda}{2} ||\\mathbf{w}||_{2}^{2}$$\n\nwhere $||\\mathbf{w}||_{2}^{2}$ simply means adding up the squared weights across all the features and classes.\n\n$$||\\mathbf{w}||_{2}^{2} = \\sum^{m}_{l=0} \\sum^{k}_{j=0} w_{l, j}^2$$\n\nso that our cost function becomes\n\n$$\nJ(\\mathbf{W}; \\mathbf{b}) = \\frac{1}{n} \\sum_{i=1}^{n} H( T^{(i)}, O^{(i)} ) + \\frac{\\lambda}{2} ||\\mathbf{w}||_{2}^{2}\n$$\n\nand we define the \"regularized\" weight update as\n\n$$\n\\mathbf{w}_j := \\mathbf{w}_j -  \\eta \\big[\\nabla \\mathbf{w}_j \\, J(\\mathbf{W}) + \\lambda \\mathbf{w}_j \\big]\n$$\n\nNote that we don't regularize the bias term, thus the update function for it stays the same.\n\n## Softmax Regression Code\n\nBringing the concepts together, we could come up with an implementation as follows: Note that for the weight and bias parameter, we'll have initialize a value for it. Here we'll simply draw the weights from a normal distribution and set the bias as zero. The code can be obtained [here](https://github.com/ethen8181/machine-learning/blob/master/deep_learning/softmax.py).\n\n\n```python\n# import some data to play with\niris = datasets.load_iris()\nX = iris.data\ny = iris.target\n\n# standardize the input features\nscaler = StandardScaler()\nX_std = scaler.fit_transform(X)\n```\n\n\n```python\nfrom softmax import SoftmaxRegression\n\n# train the softmax using batch gradient descent,\n# eta: learning rate, epochs : number of iterations, minibatches, number of \n# training data to use for training at each iteration\nsoftmax_reg = SoftmaxRegression(eta = 0.1, epochs = 10, minibatches = y.shape[0])\nsoftmax_reg.fit(X_std, y)\n\n# print the training accuracy\ny_pred = softmax_reg.predict(X_std)\naccuracy = np.sum(y_pred == y) / y.shape[0]\nprint('accuracy: ', accuracy)\n\n# use a library to ensure comparable results\nlog_reg = LogisticRegression()\nlog_reg.fit(X_std, y)\ny_pred = log_reg.predict(X_std)\nprint('accuracy library: ', accuracy_score(y_true = y, y_pred = y_pred))\n```\n\n    accuracy:  0.953333333333\n    accuracy library:  0.926666666667\n\n\n# Reference\n\n- [Blog: Softmax Regression](http://nbviewer.jupyter.org/github/rasbt/python-machine-learning-book/blob/master/code/bonus/softmax-regression.ipynb)\n- [Blog: Gradient Descent with Backpropagation](http://outlace.com/Beginner-Tutorial-Backpropagation/)\n- [TensorFlow Documentation: MNIST For ML Beginners](https://www.tensorflow.org/get_started/mnist/beginners)\n", "meta": {"hexsha": "c579b98c76dbf4f5682042569fbb1eaec0d9db2f", "size": 50716, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "deep_learning/softmax.ipynb", "max_stars_repo_name": "awesome-archive/machine-learning", "max_stars_repo_head_hexsha": "8494f3fe73db511f7b97d082c786097bfbe71463", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-22T20:35:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T20:35:30.000Z", "max_issues_repo_path": "deep_learning/softmax.ipynb", "max_issues_repo_name": "awesome-archive/machine-learning", "max_issues_repo_head_hexsha": "8494f3fe73db511f7b97d082c786097bfbe71463", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deep_learning/softmax.ipynb", "max_forks_repo_name": "awesome-archive/machine-learning", "max_forks_repo_head_hexsha": "8494f3fe73db511f7b97d082c786097bfbe71463", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-08T17:36:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-08T17:36:36.000Z", "avg_line_length": 60.5925925926, "max_line_length": 18296, "alphanum_fraction": 0.6827431185, "converted": true, "num_tokens": 6495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1500288091408361, "lm_q2_score": 0.12085322774082716, "lm_q1q2_score": 0.018131465838782557}}
{"text": "<a href=\"https://colab.research.google.com/github/robertalanm/TT_tests/blob/master/new_actions.ipynb\" target=\"_parent\"></a>\n\n# Requisites\n\n> ## Old Tensortrade\n\n\n```python\n!pip install git+https://github.com/robertalanm/Tensortrade-old\n```\n\n    Collecting git+https://github.com/robertalanm/Tensortrade-old\n      Cloning https://github.com/robertalanm/Tensortrade-old to /tmp/pip-req-build-hherwi4m\n      Running command git clone -q https://github.com/robertalanm/Tensortrade-old /tmp/pip-req-build-hherwi4m\n    Requirement already satisfied (use --upgrade to upgrade): tensortrade==0.0.1a17 from git+https://github.com/robertalanm/Tensortrade-old in /usr/local/lib/python3.6/dist-packages\n    Requirement already satisfied: numpy==1.16.4 in /usr/local/lib/python3.6/dist-packages (from tensortrade==0.0.1a17) (1.16.4)\n    Requirement already satisfied: pandas==0.25.0 in /usr/local/lib/python3.6/dist-packages (from tensortrade==0.0.1a17) (0.25.0)\n    Requirement already satisfied: gym==0.14.0 in /usr/local/lib/python3.6/dist-packages (from tensortrade==0.0.1a17) (0.14.0)\n    Requirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas==0.25.0->tensortrade==0.0.1a17) (2.6.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas==0.25.0->tensortrade==0.0.1a17) (2018.9)\n    Requirement already satisfied: cloudpickle~=1.2.0 in /usr/local/lib/python3.6/dist-packages (from gym==0.14.0->tensortrade==0.0.1a17) (1.2.2)\n    Requirement already satisfied: pyglet<=1.3.2,>=1.2.0 in /usr/local/lib/python3.6/dist-packages (from gym==0.14.0->tensortrade==0.0.1a17) (1.3.2)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from gym==0.14.0->tensortrade==0.0.1a17) (1.12.0)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from gym==0.14.0->tensortrade==0.0.1a17) (1.4.1)\n    Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from pyglet<=1.3.2,>=1.2.0->gym==0.14.0->tensortrade==0.0.1a17) (0.16.0)\n    Building wheels for collected packages: tensortrade\n      Building wheel for tensortrade (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for tensortrade: filename=tensortrade-0.0.1a17-cp36-none-any.whl size=54534 sha256=4efaea3dec894da3c54a12ba2cec54dd6fcaf587725d6131bc80039f6673b03a\n      Stored in directory: /tmp/pip-ephem-wheel-cache-1sp35rwr/wheels/92/a4/ec/dbcdbc6e8596c3d995ec5009d5bbc60fdf1560ab25dcca351a\n    Successfully built tensortrade\n\n\n\n```python\n%cd /content\n!wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz\n!tar -xzf ta-lib-0.4.0-src.tar.gz\n%cd ta-lib/\n!./configure --prefix=/usr\n!make\n!sudo make install\n%cd /content\n```\n\n\n```python\n!pip install ccxt stochastic tensorforce==0.5.2\n!pip install git+https://github.com/mrjbq7/ta-lib\n```\n\n    Requirement already satisfied: ccxt in /usr/local/lib/python3.6/dist-packages (1.21.59)\n    Requirement already satisfied: stochastic in /usr/local/lib/python3.6/dist-packages (0.4.0)\n    Collecting tensorforce==0.5.2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/d7/7b/cebafd140baec0f452543d01494beaae152d90d988545188798a031bde41/Tensorforce-0.5.2-py3-none-any.whl (308kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 317kB 5.1MB/s \n    \u001b[?25hRequirement already satisfied: cryptography>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from ccxt) (2.8)\n    Requirement already satisfied: aiodns==1.1.1; python_version >= \"3.5.2\" in /usr/local/lib/python3.6/dist-packages (from ccxt) (1.1.1)\n    Requirement already satisfied: certifi>=2018.1.18 in /usr/local/lib/python3.6/dist-packages (from ccxt) (2019.11.28)\n    Requirement already satisfied: yarl==1.1.0; python_version >= \"3.5.2\" in /usr/local/lib/python3.6/dist-packages (from ccxt) (1.1.0)\n    Requirement already satisfied: setuptools>=38.5.1 in /usr/local/lib/python3.6/dist-packages (from ccxt) (42.0.2)\n    Requirement already satisfied: requests>=2.18.4 in /usr/local/lib/python3.6/dist-packages (from ccxt) (2.21.0)\n    Requirement already satisfied: aiohttp==3.6.2; python_version >= \"3.5.2\" in /usr/local/lib/python3.6/dist-packages (from ccxt) (3.6.2)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from stochastic) (1.4.1)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from stochastic) (1.16.4)\n    Requirement already satisfied: pytest in /usr/local/lib/python3.6/dist-packages (from tensorforce==0.5.2) (3.6.4)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.6/dist-packages (from tensorforce==0.5.2) (3.1.2)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from tensorforce==0.5.2) (4.28.1)\n    Requirement already satisfied: six>=1.4.1 in /usr/local/lib/python3.6/dist-packages (from cryptography>=2.6.1->ccxt) (1.12.0)\n    Requirement already satisfied: cffi!=1.11.3,>=1.8 in /usr/local/lib/python3.6/dist-packages (from cryptography>=2.6.1->ccxt) (1.13.2)\n    Requirement already satisfied: pycares>=1.0.0 in /usr/local/lib/python3.6/dist-packages (from aiodns==1.1.1; python_version >= \"3.5.2\"->ccxt) (3.1.1)\n    Requirement already satisfied: multidict>=4.0 in /usr/local/lib/python3.6/dist-packages (from yarl==1.1.0; python_version >= \"3.5.2\"->ccxt) (4.7.4)\n    Requirement already satisfied: idna>=2.0 in /usr/local/lib/python3.6/dist-packages (from yarl==1.1.0; python_version >= \"3.5.2\"->ccxt) (2.8)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.18.4->ccxt) (3.0.4)\n    Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests>=2.18.4->ccxt) (1.24.3)\n    Requirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.6/dist-packages (from aiohttp==3.6.2; python_version >= \"3.5.2\"->ccxt) (19.3.0)\n    Requirement already satisfied: async-timeout<4.0,>=3.0 in /usr/local/lib/python3.6/dist-packages (from aiohttp==3.6.2; python_version >= \"3.5.2\"->ccxt) (3.0.1)\n    Requirement already satisfied: idna-ssl>=1.0; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from aiohttp==3.6.2; python_version >= \"3.5.2\"->ccxt) (1.1.0)\n    Requirement already satisfied: typing-extensions>=3.6.5; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from aiohttp==3.6.2; python_version >= \"3.5.2\"->ccxt) (3.6.6)\n    Requirement already satisfied: more-itertools>=4.0.0 in /usr/local/lib/python3.6/dist-packages (from pytest->tensorforce==0.5.2) (8.0.2)\n    Requirement already satisfied: pluggy<0.8,>=0.5 in /usr/local/lib/python3.6/dist-packages (from pytest->tensorforce==0.5.2) (0.7.1)\n    Requirement already satisfied: atomicwrites>=1.0 in /usr/local/lib/python3.6/dist-packages (from pytest->tensorforce==0.5.2) (1.3.0)\n    Requirement already satisfied: py>=1.5.0 in /usr/local/lib/python3.6/dist-packages (from pytest->tensorforce==0.5.2) (1.8.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib->tensorforce==0.5.2) (0.10.0)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->tensorforce==0.5.2) (2.6.1)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->tensorforce==0.5.2) (1.1.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->tensorforce==0.5.2) (2.4.6)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.6/dist-packages (from cffi!=1.11.3,>=1.8->cryptography>=2.6.1->ccxt) (2.19)\n    Installing collected packages: tensorforce\n      Found existing installation: tensorforce 0.4.4\n        Uninstalling tensorforce-0.4.4:\n          Successfully uninstalled tensorforce-0.4.4\n    Successfully installed tensorforce-0.5.2\n\n\n\n\n    Collecting git+https://github.com/mrjbq7/ta-lib\n      Cloning https://github.com/mrjbq7/ta-lib to /tmp/pip-req-build-4fo6rsm7\n      Running command git clone -q https://github.com/mrjbq7/ta-lib /tmp/pip-req-build-4fo6rsm7\n    Requirement already satisfied (use --upgrade to upgrade): TA-Lib==0.4.18 from git+https://github.com/mrjbq7/ta-lib in /usr/local/lib/python3.6/dist-packages\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from TA-Lib==0.4.18) (1.16.4)\n    Building wheels for collected packages: TA-Lib\n      Building wheel for TA-Lib (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for TA-Lib: filename=TA_Lib-0.4.18-cp36-cp36m-linux_x86_64.whl size=1528881 sha256=1e3a74fe829c408d0a5ca9d6290f4c7a1f42c79184a1e8edce7eaaf515e7eb4b\n      Stored in directory: /tmp/pip-ephem-wheel-cache-lw3gbogl/wheels/7c/09/16/87b01ae949260f15a1821ae29d58a15642c203fcc03d049fcb\n    Successfully built TA-Lib\n\n\n> ## Latest Tensortrade\n\n\n```python\n#!pip install git+https://github.com/robertalanm/TT_tests\n!pip install git+https://github.com/notadamking/tensortrade\n```\n\n    Collecting git+https://github.com/notadamking/tensortrade\n      Cloning https://github.com/notadamking/tensortrade to /tmp/pip-req-build-836lq9n9\n      Running command git clone -q https://github.com/notadamking/tensortrade /tmp/pip-req-build-836lq9n9\n    Requirement already satisfied: numpy==1.16.4 in /usr/local/lib/python3.6/dist-packages (from tensortrade==0.1.0rc1) (1.16.4)\n    Requirement already satisfied: pandas==0.25.0 in /usr/local/lib/python3.6/dist-packages (from tensortrade==0.1.0rc1) (0.25.0)\n    Requirement already satisfied: gym==0.14.0 in /usr/local/lib/python3.6/dist-packages (from tensortrade==0.1.0rc1) (0.14.0)\n    Collecting pyyaml==5.1.2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/e3/e8/b3212641ee2718d556df0f23f78de8303f068fe29cdaa7a91018849582fe/PyYAML-5.1.2.tar.gz (265kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 266kB 5.0MB/s \n    \u001b[?25hCollecting sympy==1.4\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/21/21/f4105795ca7f35c541d82c5b06be684dd2f5cb4f508fb487cd7aea4de776/sympy-1.4-py2.py3-none-any.whl (5.3MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5.3MB 10.9MB/s \n    \u001b[?25hRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas==0.25.0->tensortrade==0.1.0rc1) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas==0.25.0->tensortrade==0.1.0rc1) (2.6.1)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from gym==0.14.0->tensortrade==0.1.0rc1) (1.4.1)\n    Requirement already satisfied: cloudpickle~=1.2.0 in /usr/local/lib/python3.6/dist-packages (from gym==0.14.0->tensortrade==0.1.0rc1) (1.2.2)\n    Requirement already satisfied: pyglet<=1.3.2,>=1.2.0 in /usr/local/lib/python3.6/dist-packages (from gym==0.14.0->tensortrade==0.1.0rc1) (1.3.2)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from gym==0.14.0->tensortrade==0.1.0rc1) (1.12.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy==1.4->tensortrade==0.1.0rc1) (1.1.0)\n    Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from pyglet<=1.3.2,>=1.2.0->gym==0.14.0->tensortrade==0.1.0rc1) (0.16.0)\n    Building wheels for collected packages: tensortrade, pyyaml\n      Building wheel for tensortrade (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for tensortrade: filename=tensortrade-0.1.0rc1-cp36-none-any.whl size=92945 sha256=f087deff3dfddfeb63ef006483630c261dd61950f8af2e85bf070918bddc5ed3\n      Stored in directory: /tmp/pip-ephem-wheel-cache-zw0_gkf_/wheels/7c/ed/66/c708e8f58e006fa34ffc022ac50de732e7a2aabb91654774f5\n      Building wheel for pyyaml (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pyyaml: filename=PyYAML-5.1.2-cp36-cp36m-linux_x86_64.whl size=44104 sha256=90fde1115e28f20c2394c87960a590a70bc432d8c4a78d7c0264de0ac276b90d\n      Stored in directory: /root/.cache/pip/wheels/d9/45/dd/65f0b38450c47cf7e5312883deb97d065e030c5cca0a365030\n    Successfully built tensortrade pyyaml\n    Installing collected packages: pyyaml, sympy, tensortrade\n      Found existing installation: PyYAML 3.13\n        Uninstalling PyYAML-3.13:\n          Successfully uninstalled PyYAML-3.13\n      Found existing installation: sympy 1.1.1\n        Uninstalling sympy-1.1.1:\n          Successfully uninstalled sympy-1.1.1\n      Found existing installation: tensortrade 0.0.1a17\n        Uninstalling tensortrade-0.0.1a17:\n          Successfully uninstalled tensortrade-0.0.1a17\n    Successfully installed pyyaml-5.1.2 sympy-1.4 tensortrade-0.1.0rc1\n\n\n\n\n\n```python\n!pip install ccxt stochastic tensorforce==0.5.2 ta\n```\n\n    Requirement already satisfied: ccxt in /usr/local/lib/python3.6/dist-packages (1.21.59)\n    Requirement already satisfied: stochastic in /usr/local/lib/python3.6/dist-packages (0.4.0)\n    Requirement already satisfied: tensorforce==0.5.2 in /usr/local/lib/python3.6/dist-packages (0.5.2)\n    Requirement already satisfied: ta in /usr/local/lib/python3.6/dist-packages (0.5.11)\n    Requirement already satisfied: certifi>=2018.1.18 in /usr/local/lib/python3.6/dist-packages (from ccxt) (2019.11.28)\n    Requirement already satisfied: setuptools>=38.5.1 in /usr/local/lib/python3.6/dist-packages (from ccxt) (42.0.2)\n    Requirement already satisfied: aiodns==1.1.1; python_version >= \"3.5.2\" in /usr/local/lib/python3.6/dist-packages (from ccxt) (1.1.1)\n    Requirement already satisfied: yarl==1.1.0; python_version >= \"3.5.2\" in /usr/local/lib/python3.6/dist-packages (from ccxt) (1.1.0)\n    Requirement already satisfied: requests>=2.18.4 in /usr/local/lib/python3.6/dist-packages (from ccxt) (2.21.0)\n    Requirement already satisfied: cryptography>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from ccxt) (2.8)\n    Requirement already satisfied: aiohttp==3.6.2; python_version >= \"3.5.2\" in /usr/local/lib/python3.6/dist-packages (from ccxt) (3.6.2)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from stochastic) (1.4.1)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from stochastic) (1.16.4)\n    Requirement already satisfied: pytest in /usr/local/lib/python3.6/dist-packages (from tensorforce==0.5.2) (3.6.4)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from tensorforce==0.5.2) (4.28.1)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.6/dist-packages (from tensorforce==0.5.2) (3.1.2)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from ta) (0.25.0)\n    Requirement already satisfied: pycares>=1.0.0 in /usr/local/lib/python3.6/dist-packages (from aiodns==1.1.1; python_version >= \"3.5.2\"->ccxt) (3.1.1)\n    Requirement already satisfied: idna>=2.0 in /usr/local/lib/python3.6/dist-packages (from yarl==1.1.0; python_version >= \"3.5.2\"->ccxt) (2.8)\n    Requirement already satisfied: multidict>=4.0 in /usr/local/lib/python3.6/dist-packages (from yarl==1.1.0; python_version >= \"3.5.2\"->ccxt) (4.7.4)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.18.4->ccxt) (3.0.4)\n    Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests>=2.18.4->ccxt) (1.24.3)\n    Requirement already satisfied: cffi!=1.11.3,>=1.8 in /usr/local/lib/python3.6/dist-packages (from cryptography>=2.6.1->ccxt) (1.13.2)\n    Requirement already satisfied: six>=1.4.1 in /usr/local/lib/python3.6/dist-packages (from cryptography>=2.6.1->ccxt) (1.12.0)\n    Requirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.6/dist-packages (from aiohttp==3.6.2; python_version >= \"3.5.2\"->ccxt) (19.3.0)\n    Requirement already satisfied: idna-ssl>=1.0; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from aiohttp==3.6.2; python_version >= \"3.5.2\"->ccxt) (1.1.0)\n    Requirement already satisfied: async-timeout<4.0,>=3.0 in /usr/local/lib/python3.6/dist-packages (from aiohttp==3.6.2; python_version >= \"3.5.2\"->ccxt) (3.0.1)\n    Requirement already satisfied: typing-extensions>=3.6.5; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from aiohttp==3.6.2; python_version >= \"3.5.2\"->ccxt) (3.6.6)\n    Requirement already satisfied: atomicwrites>=1.0 in /usr/local/lib/python3.6/dist-packages (from pytest->tensorforce==0.5.2) (1.3.0)\n    Requirement already satisfied: pluggy<0.8,>=0.5 in /usr/local/lib/python3.6/dist-packages (from pytest->tensorforce==0.5.2) (0.7.1)\n    Requirement already satisfied: more-itertools>=4.0.0 in /usr/local/lib/python3.6/dist-packages (from pytest->tensorforce==0.5.2) (8.0.2)\n    Requirement already satisfied: py>=1.5.0 in /usr/local/lib/python3.6/dist-packages (from pytest->tensorforce==0.5.2) (1.8.1)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->tensorforce==0.5.2) (2.6.1)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->tensorforce==0.5.2) (1.1.0)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib->tensorforce==0.5.2) (0.10.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->tensorforce==0.5.2) (2.4.6)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas->ta) (2018.9)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.6/dist-packages (from cffi!=1.11.3,>=1.8->cryptography>=2.6.1->ccxt) (2.19)\n\n\n# Data Fetcher\n\n> ## pull data\n\n\n```python\nimport requests\nimport time\nimport csv\nimport json\nimport sys, os\nimport datetime\n\n#fetching data from bitstamp and write to a csv file\nF_Z = \"%Y-%m-%dT%H:%M:%S.%fZ\"\n'''\ncurrency_pairs = ['BTC-USD', 'BTC-EUR', 'BTC-GBP',\n                  'ETH-USD', 'ETH-EUR', 'ETH-GBP',\n                  'BCH-USD', 'BCH-EUR', 'BCH-GBP',\n                  'LTC-USD', 'LTC-EUR', 'LTC-GBP',\n                    'ETC-USD', 'ETC-EUR', 'ETC-GBP',\n\n                  ]\n'''\n\ncurrency_pairs = ['BTC-USD']\n\nOB_url = 'https://api.pro.coinbase.com/products/%s/book?level=2'\ntrans_url = 'https://api.pro.coinbase.com/products/%s/trades'\n\ntrimmed_ob_limit = 30\ntime_sleep = 25\nlast_transaction = {}\nfor i in currency_pairs:\n    last_transaction[i] = {'trade_id': '', 'time': str(datetime.datetime.utcnow().strftime(F_Z))}\n\ndef try_parsing_date(text):\n    for fmt in ('%Y-%m-%dT%H:%M:%S.%fZ', '%Y-%m-%dT%H:%M:%SZ'):\n        try:\n            return datetime.datetime.strptime(text, fmt)\n        except ValueError:\n            pass\n    raise ValueError('no valid date format found')\n\n\nwhile True:\n    for curr_pair in currency_pairs:\n        try:\n            resp = requests.get(url=OB_url % curr_pair)\n            ob_snapshot = resp.json()\n            transactions = requests.get(url=trans_url % curr_pair).json()\n            transaction_recent = transactions[0] if len(transactions) > 0 else {'trade_id': ''}\n\n            last_transaction_time = try_parsing_date(last_transaction[curr_pair]['time']).timestamp()\n\n            filtered_list = [\n                {'side': i['side'], 'trade_id': i['trade_id'], 'price': i['price'],\n                 'size': i['size'], 'time': try_parsing_date(i['time']).timestamp()\n                 }\n                for i in transactions if \\\n                                try_parsing_date(i['time']).timestamp() >\n                             last_transaction_time]\n\n            recorded_transaction = json.dumps(filtered_list)  \\\n                if last_transaction[curr_pair]['trade_id'] != transaction_recent['trade_id'] else ''\n\n            filename = 'cb_%s.csv' % curr_pair\n\n            with open(filename, 'a') as csvfile:\n                fieldnames = ['timestamp', 'transactions', 'ob']\n                timestamp = int(time.time())\n                trimmed_ob = json.dumps({'bid': [[i[0], i[1]] for i in ob_snapshot['bids'][:trimmed_ob_limit]],\n                              'ask': [[i[0], i[1]] for i in ob_snapshot['asks'][:trimmed_ob_limit]]})\n                writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n                writer.writerow({'timestamp': timestamp, 'transactions': recorded_transaction, 'ob': trimmed_ob})\n                last_transaction[curr_pair] = transaction_recent\n        except Exception as e:\n            exc_type, exc_obj, exc_tb = sys.exc_info()\n            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n            print(exc_type, fname, exc_tb.tb_lineno, e)\n        time.sleep(0.5)\n    time.sleep(time_sleep)\n```\n\n> ## Feature Transformation\n\n\n```python\n\nimport pandas as pd\nimport numpy as np\nimport json\nimport ast\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nmpl.style.use('seaborn')\n\n# df = pd.read_csv('bitstamp_btcusd.csv', header=None, names=['timestamp', 'trades', 'book'])\ndf = pd.read_csv('cb_BTC-USD.csv', header=None, names=['timestamp', 'trades', 'book'])\n\ndf['trades'] = df['trades'].apply(lambda d: json.loads(d) if isinstance(d, str) else [])\ndf['book'] = df['book'].apply(lambda d: json.loads(d))\ndf.iloc[1]\ndf.shape\n# df.iloc[1382]['book']\n```\n\n\n\n\n    (4253, 3)\n\n\n\n\n```python\nimport math\ndef trades_to_weighted_px(trades_arr):\n    notional = 0\n    qty = 0\n    for trade in trades_arr:\n        notional += float(trade['price']) * float(trade['size'])\n        qty += float(trade['size'])\n    \n    return notional / (qty + 1e-16)\n\ndef trades_to_latest_px(trades_arr):\n    max_time = 0\n    trade_px = 0\n    for trade in trades_arr:\n        timestamp = int(trade['time'])\n        if timestamp > max_time:\n            trade_px = float(trade['price'])\n    return trade_px\n\ndef trades_to_vol(trades):\n    qty = sum([float(trade['size']) for trade in trades])\n    return qty \n\ndef trades_to_high(row):\n    if len(row['trades']) > 0:\n        return max(float(trade['price']) for trade in row['trades'])\n    else:\n        return row['latest_trade_px']\n\n# def trades_to_low(trades):\n#     return min(float(trade['price']) for trade in trades)\n\ndef trades_to_low(row):\n    if len(row['trades']) > 0:\n        return min(float(trade['price']) for trade in row['trades'])\n    else:\n        return row['latest_trade_px']\n\ndef interpolate_tradepx(df):\n    for i in range(len(df)):\n        trade_px = df.iloc[i]['trade_px']\n        if trade_px == 0:\n            if i == 0:\n                new_trade_px = 0\n                for j in range(len(df)):\n                    if df.iloc[j]['trade_px'] != 0:\n                        new_trade_px = df.iloc[j]['trade_px']\n                        break\n                df.iloc[i]['trade_px'] = new_trade_px\n            else:\n                df.iloc[i]['trade_px'] = df.iloc[i - 1]['trade_px'] \n\n\ndef get_log_close(df):\n  for i in range(len(df)):\n    if i == 0:\n      return 0\n    if i > 0:\n      df['log_close'][i] = (math.log(df['bid_px'][i]) - math.log(df['ask_px'][i].shift(1)))\n\n\n\ndef get_base_features(old_df):\n    df = old_df.copy()\n    \n    #generate base data\n    df['trade_px'] = df['trades'].apply(trades_to_weighted_px)\n    df['volume'] = df['trades'].apply(trades_to_vol)\n    df['latest_trade_px'] = df['trades'].apply(trades_to_latest_px)\n    df['latest_trade_px'] = df['latest_trade_px'].replace(to_replace=0, method='ffill')\n    df['bid_px'] = df['book'].apply(lambda x: float(x['bid'][0][0]))\n    df['ask_px'] = df['book'].apply(lambda x: float(x['ask'][0][0]))\n    df['bid_vol'] = df['book'].apply(lambda x: float(x['bid'][0][1]))\n    df['ask_vol'] = df['book'].apply(lambda x: float(x['ask'][0][1]))\n    df['mid_px'] = (df['bid_px'] + df['ask_px'])/2\n\n    #TA modules\n    df['High'] = df.apply(trades_to_high, axis=1)\n    df['Low'] = df.apply(trades_to_low, axis=1)\n    df['Timestamp'] = df['timestamp']\n    df['Close'] = df['latest_trade_px']\n    df['Open'] = df['latest_trade_px'].shift(1)\n    df['Volume'] = df['volume']\n    \n    # y\n    df['change_pct_latest_px'] = df['latest_trade_px'].pct_change()\n    df['px_change'] = df['latest_trade_px'].diff()\n    \n    # generate features\n    df['spread'] = df['ask_px'] - df['bid_px']\n    df['l1imbalance'] = (df['bid_vol'] - df['ask_vol']) / ((df['bid_vol'] + df['ask_vol']) + 1e-9)\n    df['bid_delta'] = df['bid_px'] - df['bid_px'].shift(1)\n    df['ask_delta'] = df['ask_px'] - df['ask_px'].shift(1)\n    df['bid_vol_delta'] = df['bid_vol'] - df['bid_vol'].shift(1)\n    df['ask_vol_delta'] = df['ask_vol'] - df['ask_vol'].shift(1)\n    df['bid_vol_acceleration'] = ((df['bid_vol_delta'] - df['bid_vol_delta'].shift(1)) / \n            (df['bid_vol_delta'].shift(1) + 1e-9))\n    df['ask_vol_acceleration'] = ((df['ask_vol_delta'] - df['ask_vol_delta'].shift(1)) / \n            (df['ask_vol_delta'].shift(1) + 1e-9))\n    \n    df['time_delta'] = df['timestamp'] - df['timestamp'].shift(1)\n    df['time_delta'] = df['time_delta'].apply(lambda seconds: np.nan if seconds > 40 else seconds)\n    \n    #l2 features\n    \n    \n    df = df.replace([np.inf, -np.inf], np.nan)\n    \n    return df\n```\n\n\n```python\nnew_df = get_base_features(df).dropna()\nnew_df.drop(df.iloc[:, 1:3], inplace = True, axis = 1)\nnew_df.shape\nnew_df\n# new_df.rolling(window=5).mean()\nnew_df.to_csv('NEW_DF.csv')\n```\n\n# Running Code\n\n> ## Models\n\n> ## Impl\n\n> > ### Use with Tensorforce 0.5.2\n\n\n```python\nimport tensorflow as tf\nimport pandas as pd\nimport ccxt\n\nfrom stable_baselines.common.policies import MlpLnLstmPolicy\nfrom stable_baselines import PPO2, ACER\n\nfrom tensorforce.agents import Agent\n\nfrom tensortrade.strategies import StableBaselinesTradingStrategy, TensorforceTradingStrategy\nfrom tensortrade.environments import TradingEnvironment\nfrom tensortrade.rewards import RiskAdjustedReturns\nfrom tensortrade.actions import ManagedRiskOrders, DynamicOrders\nfrom tensortrade.instruments import Quantity, TradingPair, BTC, USD\nfrom tensortrade.orders.criteria import Stop, StopDirection\nfrom tensortrade.wallets import Wallet, Portfolio\nfrom tensortrade.exchanges.simulated import SimulatedExchange\nfrom tensortrade.exchanges.live import CCXTExchange\nfrom tensortrade.features.stationarity import LogDifference\nfrom tensortrade.features.scalers import MinMaxNormalizer\nfrom tensortrade.features import FeaturePipeline\n\nWINDOW_SIZE = 4\n#PRICE_COLUMN = 'change_pct_latest_px'\nPRICE_COLUMN = 'close'\n\nnormalize = MinMaxNormalizer(inplace=True)\ndifference = LogDifference(inplace=True)\nfeature_pipeline = FeaturePipeline(steps=[normalize, difference])\n\naction_scheme = ManagedRiskOrders(pairs=[USD/BTC], stop_loss_percentages=0.05, take_profit_percentages=0.6)\nreward_scheme = RiskAdjustedReturns(return_algorithm=\"sharpe\")\n\ncsv_file = tf.keras.utils.get_file('Coinbase_BTCUSD_1h.csv', 'http://www.cryptodatadownload.com/cdd/Coinbase_BTCUSD_1h.csv')\n#ohlcv_data = pd.read_csv('NEW_DF.csv', skiprows=0, index_col=\"timestamp\")\nohlcv_data = pd.read_csv(csv_file, skiprows=1, index_col=\"Date\")\nohlcv_data.columns = map(str.lower, ohlcv_data.columns)\nohlcv_data = ohlcv_data.rename(columns={'volume btc': 'volume'})\n\n\n#coinbase = ccxt.coinbasepro()\n#exchange = CCXTExchange(exchange=coinbase, base_instrument='USD')\nexchange = SimulatedExchange(data_frame=ohlcv_data, price_column=PRICE_COLUMN, randomize_time_slices=True)\n\nwallets = [(exchange, USD, 100), (exchange, BTC, 0)]\n\nportfolio = Portfolio(base_instrument=USD, wallets=wallets)\n\nenvironment = TradingEnvironment(exchange=exchange,\n                                 portfolio=portfolio,\n                                 action_scheme=action_scheme,\n                                 reward_scheme=reward_scheme,\n                                 feature_pipeline=feature_pipeline,\n                                 window_size=WINDOW_SIZE,\n                                 observe_wallets=[USD, BTC])\n\nprint('Observation Data:')\nprint(environment.observation_columns)\n\nmodel = PPO2\n#model = ACER\npolicy = MlpLnLstmPolicy\nparams = { \"learning_rate\": 1e-5, 'nminibatches': 1,  }\n#params = { \"learning_rate\": 1e-5,  }\n\nbase_strategy = StableBaselinesTradingStrategy(environment=environment,\n                                          model=model,\n                                          policy=policy,\n                                          model_kwargs=params)\n\n\nagent = Agent.create(\n    agent='dueling_dqn',\n    states=dict(type='float', shape=(4,10)),\n    actions=dict(type='int', num_values=3),\n    max_episode_timesteps=100,\n    #memory=10000,\n    #update=dict(unit='timesteps', batch_size=64),\n    #optimizer=dict(type='adam', learning_rate=3e-4),\n    #policy=dict(network='auto'),\n    #objective='policy_gradient',\n    #reward_estimation=dict(horizon=20)\n)\n\nforce_strategy = TensorforceTradingStrategy(environment=environment, \n                                      agent=agent, max_episode_timesteps=20000)\n\nforce_strategy.run(steps=1000)\nprint(f\"Tensorforce net worth: {portfolio.net_worth}\")\nbase_strategy.run(steps=1000)\nprint(f\"Baselines net worth: {portfolio.net_worth}\")\n\n```\n\n    /usr/local/lib/python3.6/dist-packages/pandas/core/indexing.py:362: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      self.obj[key] = _infer_fill_value(value)\n    /usr/local/lib/python3.6/dist-packages/pandas/core/indexing.py:480: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      self.obj[item] = s\n\n\n    Observation Data:\n    ['open' 'high' 'low' 'close' 'volume' 'volume usd' 'USD' 'BTC'\n     'USD_pending' 'BTC_pending']\n\n\n    \n    \n    \n    \n    \n    \n    Timesteps:   0%|          | 0/1000 [00:00<?, ?it/s, mean_reward=n/a]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A/usr/local/lib/python3.6/dist-packages/pandas/core/indexing.py:362: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      self.obj[key] = _infer_fill_value(value)\n    /usr/local/lib/python3.6/dist-packages/pandas/core/indexing.py:480: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      self.obj[item] = s\n    \n    \n    \n    \n    \n    \n    \u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\n\n    Finished running strategy.\n    Total episodes: 0 (1000 timesteps).\n    Average reward: -19.26090056459747.\n    Tensorforce net worth: 102.60238106685298\n    Baselines net worth: 106.2635740482776\n\n\n> > ### Use with Tensorforce 0.4.4\n\n\n```python\nimport os\nimport sys\nimport warnings\nimport numpy\nimport pandas as pd\n\ndef warn(*args, **kwargs):\n    pass\n\nwarnings.warn = warn\nwarnings.simplefilter(action='ignore', category=FutureWarning)\nnumpy.seterr(divide = 'ignore') \n#%% Module version check\nimport tensorforce\nimport tensorflow as tf\n\n#%% Actions & Rewards\nfrom tensortrade.strategies import TensorforceTradingStrategy\n#from tensortrade.rewards import PositionReward\n#from tensortrade.actions import FuturePositionStrategy\n\nfrom tensortrade.actions import DiscreteActionStrategy\n\naction_scheme = DiscreteActionStrategy(n_actions=20, instrument_symbol='BTC')\n\nfrom tensortrade.rewards import RiskAdjustedReturnStrategy\n\nreward_scheme = RiskAdjustedReturnStrategy(return_algorithm=\"sortino\")\n#reward_strategy = PositionReward()\n#action_strategy = FuturePositionStrategy(n_actions = 11)\n\n#%% Feature Pipeline\nfrom tensortrade.features.stationarity import FractionalDifference\nfrom tensortrade.features.scalers import MinMaxNormalizer\nfrom tensortrade.features import FeaturePipeline\n\nnormalize = MinMaxNormalizer(inplace=True)\ndifference = FractionalDifference(difference_order=0.6,\n                                  inplace=True)\nfeature_pipeline = FeaturePipeline(steps=[])\n\n#%% Data Input (Exchanges)\nfrom tensortrade.exchanges.simulated import SimulatedExchange\n#from tensortrade.exchanges.simulated.future_exchange_position import FutureExchangePosition\n#csv_file = tf.keras.utils.get_file(\n#    'Coinbase_BTCUSD_1h.csv', 'http://www.cryptodatadownload.com/cdd/Coinbase_BTCUSD_1h.csv')\n#data = pd.read_csv(csv_file, skiprows=1, index_col=\"Date\")\ndata = pd.read_csv('NEW_DF.csv',index_col = 0)\ndata.columns = map(str.lower, data.columns)\n\n#data = data[data.index % 60 == 0]\n#data = data.reset_index(drop = True)\n\n\n#exchange = FutureExchangePosition(data, base_instrument = 'USD', exclude_close = True,\n#                          initial_balance = 50000, observe_position = True)\n\nexchange = SimulatedExchange(base_instrument='USD',\n                             data_frame=data,\n                             price_column='close',\n                             window_size=1,\n                             pretransform=False)\n\n#%% Agent Specification\nnetwork_spec = [\n    dict(type='dense', size=128, activation=\"tanh\"),\n    dict(type='dense', size=64, activation=\"tanh\"),\n    dict(type='dense', size=32, activation=\"tanh\")\n]\n\nagent_spec = {\n    \"type\": \"a2c\",\n    \"learning_rate\": 0.0003,\n    \"discount\": 1.0,\n    \"estimate_terminal\": False,\n    \"max_episode_timesteps\": 20000,\n    \"network\": network_spec,\n    \"batch_size\": 100,\n    \"update_frequency\":100\n}\n\n\n#%%Environment Setup\nfrom tensortrade.environments import TradingEnvironment\n\nenvironment = TradingEnvironment(exchange=exchange,\n                                 action_strategy=action_scheme,\n                                 reward_strategy=reward_scheme,\n                                 feature_pipeline=feature_pipeline)\n\n\nstrategy = TensorforceTradingStrategy(environment=environment, \n                                      agent_spec=agent_spec, save_best_agent=False)\n#%%Start Over\nperformance = strategy.run(episodes=100, evaluation=False)\n\n#manually store agent\n#strategy.save_agent(directory = 'save/', filename = '01')\n\n#%% Restore and Continue \n'''\nstrategy.restore_agent(directory = 'save/', filename = '01')\nperformance = strategy.run(episodes=(strategy._runner.agent.episodes + 20), evaluation=False)\n'''\n#%% Analysis\nperformance =(pd.DataFrame(data = self._performance.T, columns = ['balance','net_worth','open_amount','price']))\nlearning_curve = pd.Series(strategy._runner.episode_rewards)\nlearning_curve.plot()\n```\n", "meta": {"hexsha": "36e26efab1246eb4446f92294101665a11c8c1ba", "size": 57346, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "new_actions.ipynb", "max_stars_repo_name": "robertalanm/TT_tests", "max_stars_repo_head_hexsha": "2bc2b29a9812d1141b7016a1906475897ae4daa3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "new_actions.ipynb", "max_issues_repo_name": "robertalanm/TT_tests", "max_issues_repo_head_hexsha": "2bc2b29a9812d1141b7016a1906475897ae4daa3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "new_actions.ipynb", "max_forks_repo_name": "robertalanm/TT_tests", "max_forks_repo_head_hexsha": "2bc2b29a9812d1141b7016a1906475897ae4daa3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.7954971857, "max_line_length": 1252, "alphanum_fraction": 0.5589753427, "converted": true, "num_tokens": 10473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749474, "lm_q2_score": 0.039638840093660095, "lm_q1q2_score": 0.01812036921926584}}
{"text": "# KAIST AI605 Assignment 2: Text Retrieval\nTA in charge: Yongrae Jo (yongrae@kaist.ac.kr)\n\n**Due Date:** October 27 (Wed) 11:00pm, 2021\n\n## Your Submission\nIf you are a KAIST student, you will submit your assignment via [KLMS](https://klms.kaist.ac.kr). If you are a NAVER student, you will submit via [Google Form](https://forms.gle/aGZZ86YpCdv2zEVt9). \n\nYou need to submit both (1) a PDF of this notebook, and (2) a link to CoLab for execution (.ipynb file is also allowed).\n\nUse in-line LaTeX (see below) for mathematical expressions. Collaboration among students is allowed but it is not a group assignment so make sure your answer and code are your own. Make sure to mention your collaborators in your assignment with their names and their student ids.\n\n## Grading\nThe entire assignment is out of 20 points. You can obtain up to 5 bonus points (i.e. max score is 25 points). For every late day, your grade will be deducted by 2 points (KAIST students only). You can use one of your no-penalty late days (7 days in total). Make sure to mention this in your submission. You will receive a grade of zero if you submit after 7 days.\n\n\n## Environment\nYou will only use Python 3.7 and PyTorch 1.9, which is already available on Colab:\n\n\n```python\nfrom platform import python_version\nimport torch\nimport numpy as np\nfrom tqdm import tqdm\nimport time\n\nprint(\"python\", python_version())\nprint(\"torch\", torch.__version__)\n```\n\n    python 3.7.12\n    torch 1.9.0+cu111\n\n\nYou will use two datasets, namely SQuAD, for retrieval. Note that this is a MRC dataset but we will view them as retrieval task by trying to find the correct document corresponding to the question among all the documents in the **validation** data. \n\n\n```python\n!pip install -q datasets\n```\n\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 290 kB 5.4 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 243 kB 43.5 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 56 kB 3.7 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 125 kB 59.8 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.3 MB 45.7 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 271 kB 48.9 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 160 kB 44.1 MB/s \n    \u001b[?25h\n\n\n```python\nfrom datasets import load_dataset\nfrom pprint import pprint\n\nsquad_dataset = load_dataset('squad')\npprint(squad_dataset['train'][0]) # 'context' contains the document\n```\n\n\n    Downloading:   0%|          | 0.00/1.97k [00:00<?, ?B/s]\n\n\n\n    Downloading:   0%|          | 0.00/1.02k [00:00<?, ?B/s]\n\n\n    Downloading and preparing dataset squad/plain_text (download: 33.51 MiB, generated: 85.63 MiB, post-processed: Unknown size, total: 119.14 MiB) to /root/.cache/huggingface/datasets/squad/plain_text/1.0.0/d6ec3ceb99ca480ce37cdd35555d6cb2511d223b9150cce08a837ef62ffea453...\n\n\n\n      0%|          | 0/2 [00:00<?, ?it/s]\n\n\n\n    Downloading:   0%|          | 0.00/8.12M [00:00<?, ?B/s]\n\n\n\n    Downloading:   0%|          | 0.00/1.05M [00:00<?, ?B/s]\n\n\n\n      0%|          | 0/2 [00:00<?, ?it/s]\n\n\n\n    0 examples [00:00, ? examples/s]\n\n\n\n    0 examples [00:00, ? examples/s]\n\n\n    Dataset squad downloaded and prepared to /root/.cache/huggingface/datasets/squad/plain_text/1.0.0/d6ec3ceb99ca480ce37cdd35555d6cb2511d223b9150cce08a837ef62ffea453. Subsequent calls will reuse this data.\n\n\n\n      0%|          | 0/2 [00:00<?, ?it/s]\n\n\n    {'answers': {'answer_start': [515], 'text': ['Saint Bernadette Soubirous']},\n     'context': 'Architecturally, the school has a Catholic character. Atop the '\n                \"Main Building's gold dome is a golden statue of the Virgin Mary. \"\n                'Immediately in front of the Main Building and facing it, is a '\n                'copper statue of Christ with arms upraised with the legend '\n                '\"Venite Ad Me Omnes\". Next to the Main Building is the Basilica '\n                'of the Sacred Heart. Immediately behind the basilica is the '\n                'Grotto, a Marian place of prayer and reflection. It is a replica '\n                'of the grotto at Lourdes, France where the Virgin Mary reputedly '\n                'appeared to Saint Bernadette Soubirous in 1858. At the end of the '\n                'main drive (and in a direct line that connects through 3 statues '\n                'and the Gold Dome), is a simple, modern stone statue of Mary.',\n     'id': '5733be284776f41900661182',\n     'question': 'To whom did the Virgin Mary allegedly appear in 1858 in Lourdes '\n                 'France?',\n     'title': 'University_of_Notre_Dame'}\n\n\n## 1. Measuring Similarity\nWe discussed in Lecture 08 that there are several ways to measure similarity between two vectors, such as L2 (Euclidean) distance, L1 (Manhattan) distance, inner product, and cosine distance. Here, except for inner product, all other measures are *metric* (see *Definition* at https://en.wikipedia.org/wiki/Metric_(mathematics)).\n\n> **Problem 1.1** *(2 points)* Using the definition of metric above, prove that L1 distance is a metric.\n\n**(Proof)**\nFor L1 distance, for $x,y \\in \\mathbb{R}^n$, $d(x,y) = \\sum_{i=1}^n|x_i-y_i|$.\n\n($i$) \n\\begin{align}\nd(x,y) &= \\sum_{i=1}^n|x_i-y_i| = 0 \\\\\n      &\\iff |x_i-y_i| = 0 ~~\\text{for every }i\\in [n] \\\\\n      &\\iff x_i = y_i ~~\\text{for every }i\\in [n] \\\\\n      &\\iff x=y ~~ \\text{(identity of indiscernibles)}\n\\end{align}\n\n($ii$)  \n\\begin{align}\nd(x,y) &= \\sum_{i=1}^n|x_i-y_i| \\\\\n&= \\sum_{i=1}^n|y_i-x_i| \\\\\n&= d(y,x) ~~ \\text{(symmetry)}\n\\end{align}\n\n($iii$)\n\\begin{align}\nd(x,y) &= \\sum_{i=1}^n|x_i-y_i| \\\\\n&= \\sum_{i=1}^n|x_i-z_i+z_i-y_i| \\\\\n&\\leq \\sum_{i=1}^n|x_i-z_i| + \\sum_{i=1}^n|z_i-y_i| \\\\\n&= d(x,z) + d(z,y) ~~ \\text{(triangular inequality)}\n\\end{align}\n\nTherefore, L1 distance is a metric.\n\n> **Problem 1.2** *(2 points)* Prove that negative inner product is NOT a metric.\n\n**(Proof)**\nNegative inner product is not a metric, since it does not satisfy the identity of indiscernibles. If $x=[1,0]$ and $y=[0,1]$, negative inner product $d(x,y)=0$, but $x\\neq y$.\n\n> **Problem 1.3** *(2 points)* Prove that cosine distance (1 - cosine similarity) is a metric.\n\n**(Proof)**\nCosine distance is **NOT** a metric. It does not even hold the identity of indiscernibles. If two vectors $x,y$ have same direction and different scale, e.g., $x=[1,0]$ and $y=[2,0]$, cosine disntance $d(x,y) = 1-\\frac{x\\cdot y}{\\|x\\|\\cdot\\|y\\|}=0$, but $x\\neq y$.\n\n> **Problem 1.4 (bonus)** *(3 points)* Given a model that can perform nearest neighbor search in L2 space, can you modify your query and your key vectors to perform maximum inner product search? (Hint: Recall the difference between MIPS and L2 NNS in Lecture 09. Can you modify key vectors so that the difference becomes 0?)\n\n**(Proof)**\nWe can make L2 NNS equivalent to MIPS via **normalizing the query and key vectors.** In other words, \n\\begin{align}\n\\arg \\min_i \\|q-k_i\\|_2 \n&= \\arg \\min_i \\|q-k_i\\|^2_2 \\\\\n&= \\arg \\min_i \\|q\\|^2_2 + \\|k_i\\|^2_2 - 2\\cdot q\\cdot k_i \\\\ \n&= \\arg \\max_i q\\cdot k_i \n\\end{align}\nwhere the last equality holds because $q$ and $k_i$ are normalized and the norm is constant as 1. \n\nWe first create an abstract class for performing similarity search as follows (`raise NotImplementedError()` means you have to override these methods when you subclass the class):\n\n\n```python\nclass SimilaritySearch(object):\n  def __init__(self):\n    raise NotImplementedError()\n\n  def train(self, documents: list):\n    raise NotImplementedError()\n\n  #Add documents (a list of text)\n  def add(self, documents: list):\n    raise NotImplementedError()\n\n  #Returns the indices of top-k documents among the added documents\n  #that are most similar to the input query \n  def search(self, query: list, k: int) -> list:\n    raise NotImplementedError()\n\n```\n\nYou will use the same space-based tokenizer that you used in Assignment 1, with lowercasing to make it case insensitive.\n\n## 2. Sparse Search\n\n\n\n> **Problem 2.1** *(2 points)* We will first start with Bag of Words that we discussed in Lecture 08. Using the definition in the class (don't worry about the exact definition though), implement `BagOfWords` class that subclasses `SimilaritySearch` class.\n\n\n```python\nclass BagOfWords(SimilaritySearch):\n  def __init__(self, dataset):\n    self.words = dict(UNK=0)\n    self.documents = []\n    self.dataset = dataset\n\n    for i in range(len(dataset)):\n      sentence_ = dataset[i]['context'].split(' ')\n      self.train(sentence_)\n\n    for i in range(len(dataset)):\n      self.add(dataset[i]['context'].split(' '))\n\n  def train(self, documents):\n    for word_ in documents:\n      word = word_.lower()\n      if word not in self.words:\n        self.words[word] = len(self.words)\n\n  def add(self, documents):\n    sentence_to_idx = {}\n    for word_ in documents:\n      word = word_.lower()\n      if self.words[word] in sentence_to_idx:\n        sentence_to_idx[self.words[word]] += 1\n      else:\n        sentence_to_idx[self.words[word]] = 1\n    self.documents.append(sentence_to_idx)\n\n  def search(self, query, k):\n    query_bag_of_words = {0:0}\n    for word_ in query:\n      word = word_.lower()\n      if word not in self.words:\n        query_bag_of_words[0] += 1   # UNK\n      elif word not in query_bag_of_words:\n        query_bag_of_words[self.words[word]] = 1\n      else:\n        query_bag_of_words[self.words[word]] += 1 \n\n    scores = []\n    for doc in range(len(self.documents)):\n      score = 0\n      for text_idx in query_bag_of_words:\n        if text_idx == 0:\n          continue\n        if text_idx in self.documents[doc]:\n          score += query_bag_of_words[text_idx] * self.documents[doc][text_idx]\n      scores.append(score)\n    indices = np.argsort(scores)[-k:][::-1]\n\n    return indices, scores\n```\n\n> **Problem 2.2** *(2 points)* Using the definition in Lecture 08 (don't worry about the exact definition though), implement `TFIDF` class that subclasses `BagOfWords` class.\n\n\n```python\nclass TFIDF(BagOfWords):\n  def __init__(self, dataset):\n    self.words = dict(UNK=0)\n    self.word_count = {0:0}\n    self.word_idf = {0:0}\n    self.documents = []\n    self.dataset = dataset\n\n    for i in range(len(dataset)):\n      sentence_ = dataset[i]['context'].split(' ')\n      self.train(sentence_)\n    \n    for idx in self.word_count:\n      if self.word_count[idx] == 0:\n        self.word_idf[idx] = 0\n      else:\n        self.word_idf[idx] = np.log(len(self.dataset) / self.word_count[idx])\n\n    for i in range(len(dataset)):\n      self.add(dataset[i]['context'].split(' '))\n\n  def train(self, documents):\n    ll = []\n    for word_ in documents:\n      word = word_.lower()\n      if word not in self.words:\n        self.words[word] = len(self.words)\n        self.word_count[self.words[word]] = 0\n      if word not in ll:\n        self.word_count[self.words[word]] += 1\n        ll.append(word)\n\n  def add(self, documents):\n    sentence_to_idx = {}\n    num_words = len(documents)\n    for word_ in documents:\n      word = word_.lower()\n      if self.words[word] in sentence_to_idx:\n        sentence_to_idx[self.words[word]] += 1 / num_words * self.word_idf[self.words[word]]\n      else:\n        sentence_to_idx[self.words[word]] = 1 / num_words * self.word_idf[self.words[word]]\n    self.documents.append(sentence_to_idx)\n\n  def search(self, query, k):\n    query_bag_of_words = {0:0}\n    num_words = len(query)\n    for word_ in query:\n      word = word_.lower()\n      if word not in self.words:\n        continue   # UNK\n      elif word not in query_bag_of_words:\n        query_bag_of_words[self.words[word]] = 1 / num_words * self.word_idf[self.words[word]]\n      else:\n        query_bag_of_words[self.words[word]] += 1 / num_words * self.word_idf[self.words[word]]\n\n    scores = []\n    for doc in range(len(self.documents)):\n      score = 0\n      for text_idx in query_bag_of_words:\n        if text_idx == 0:\n          continue\n        if text_idx in self.documents[doc]:\n          score += query_bag_of_words[text_idx] * self.documents[doc][text_idx]\n      scores.append(score)\n    indices = np.argsort(scores)[-k:][::-1]\n\n    return indices, scores\n```\n\n> **Problem 2.3** *(2 points)* Use `TFIDF` to masure the recall rate of the correct document when 10 documents (contexts) are retrieved (this is called **Recall@10**) in SQuAD **validation** set.\n\nRecall@10 of TFIDF is 55.3%. (see the code)\n\n\n```python\ndataset = squad_dataset['validation']\ntfidf = TFIDF(dataset)\nrecall = 0\nfor doc in tqdm(range(len(dataset))):\n  question = dataset[doc]['question'].split(' ')\n  indices,_ = tfidf.search(question, 10)\n  if doc in indices:\n    recall += 1\nrecall /= len(dataset)\n\nprint(recall)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 10570/10570 [06:47<00:00, 25.94it/s]\n\n    0.5528855250709556\n\n\n    \n\n\n> **Problem 2.4 (bonus)** *(2 points)* Implement `BM25` that sublcasses `BagOfWords` and repeat Problem 2.3 for BM25.\n\nRecall@10 of BM25 is 46.3%. (see the code)\n\n\n```python\nclass BM25(BagOfWords):\n  def __init__(self, dataset):\n    self.words = dict(UNK=0)\n    self.word_count = {0:0}\n    self.word_idf = {0:0}\n    self.documents = []\n    self.document_length = []\n    self.dataset = dataset\n\n    for i in range(len(dataset)):\n      sentence_ = dataset[i]['context'].split(' ')\n      self.train(sentence_)\n    \n    for idx in self.word_count:\n      if self.word_count[idx] == 0:\n        self.word_idf[idx] = 0\n      else:\n        self.word_idf[idx] = np.log(len(self.dataset) / self.word_count[idx])\n\n    for i in range(len(dataset)):\n      self.add(dataset[i]['context'].split(' '))\n\n  def train(self, documents):\n    ll = []\n    for word_ in documents:\n      word = word_.lower()\n      if word not in self.words:\n        self.words[word] = len(self.words)\n        self.word_count[self.words[word]] = 0\n      if word not in ll:\n        self.word_count[self.words[word]] += 1\n        ll.append(word)\n\n  def add(self, documents):\n    sentence_to_idx = {}\n    num_words = len(documents)\n    for word_ in documents:\n      word = word_.lower()\n      if self.words[word] in sentence_to_idx:\n        sentence_to_idx[self.words[word]] += 1 / num_words * self.word_idf[self.words[word]]\n      else:\n        sentence_to_idx[self.words[word]] = 1 / num_words * self.word_idf[self.words[word]]\n    self.documents.append(sentence_to_idx)\n    self.document_length.append(num_words)\n\n  def search(self, query, k):\n    query_bag_of_words = {0:0}\n    num_words = len(query)\n    for word_ in query:\n      word = word_.lower()\n      if word not in self.words:\n        continue   # UNK\n      elif word not in query_bag_of_words:\n        query_bag_of_words[self.words[word]] = self.word_idf[self.words[word]]\n      else:\n        query_bag_of_words[self.words[word]] += self.word_idf[self.words[word]]\n\n    scores = []\n    k1, b = 1.5, 0.75\n    avgdl = np.mean(self.document_length)\n    for doc in range(len(self.documents)):\n      score = 0\n      for text_idx in query_bag_of_words:\n        if text_idx == 0:\n          continue\n        if text_idx in self.documents[doc]:\n          score += query_bag_of_words[text_idx] * (self.documents[doc][text_idx] * (k1+1)) \\\n                   / (self.documents[doc][text_idx] + k1 * (1-b + b * self.document_length[doc] / avgdl))\n      scores.append(score)\n    indices = np.argsort(scores)[-k:][::-1]\n\n    return indices, scores\n```\n\n\n```python\ndataset = squad_dataset['validation']\nbm25 = BM25(dataset)\nrecall = 0\nfor doc in tqdm(range(len(dataset))):\n  question = dataset[doc]['question'].split(' ')\n  indices,_ = bm25.search(question, 10)\n  if doc in indices:\n    recall += 1\nrecall /= len(dataset)\n\nprint(recall)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 10570/10570 [11:19<00:00, 15.55it/s]\n\n    0.46253547776726583\n\n\n    \n\n\n## 3. Dense Search\n\nTo obtain the embedding of each document and query, you will use GloVe embedding (Pennington et al., 2014). Go to https://nlp.stanford.edu/projects/glove/ and download `glove.6B.zip`. You are also welcome to use other more convenient ways to access the GloVe embeddings. You will compute the document's embedding by simply averaging the embeddings of all words in the document (same for the query), and then normalizing it. This way, inner product effectively becomes cosine similarity.\n\n\n```python\n!wget https://nlp.stanford.edu/data/glove.6B.zip\n!unzip glove.6B.zip\n```\n\n    --2021-10-25 15:10:35--  https://nlp.stanford.edu/data/glove.6B.zip\n    Resolving nlp.stanford.edu (nlp.stanford.edu)... 171.64.67.140\n    Connecting to nlp.stanford.edu (nlp.stanford.edu)|171.64.67.140|:443... connected.\n    HTTP request sent, awaiting response... 301 Moved Permanently\n    Location: http://downloads.cs.stanford.edu/nlp/data/glove.6B.zip [following]\n    --2021-10-25 15:10:35--  http://downloads.cs.stanford.edu/nlp/data/glove.6B.zip\n    Resolving downloads.cs.stanford.edu (downloads.cs.stanford.edu)... 171.64.64.22\n    Connecting to downloads.cs.stanford.edu (downloads.cs.stanford.edu)|171.64.64.22|:80... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 862182613 (822M) [application/zip]\n    Saving to: \u2018glove.6B.zip\u2019\n    \n    glove.6B.zip        100%[===================>] 822.24M  4.81MB/s    in 2m 52s  \n    \n    2021-10-25 15:13:28 (4.77 MB/s) - \u2018glove.6B.zip\u2019 saved [862182613/862182613]\n    \n    Archive:  glove.6B.zip\n      inflating: glove.6B.50d.txt        \n      inflating: glove.6B.100d.txt       \n      inflating: glove.6B.200d.txt       \n      inflating: glove.6B.300d.txt       \n\n\n> **Problem 3.1** *(3 points)* Implement `GloVeAverage` class that subclasses `SimilaritySearch` class, using PyTorch's tensor native operation for the dense search. \n\n\n```python\nvocab = []\nembedding = np.zeros((400000, 300), dtype=np.float32)\n#embedding[0,:] = np.random.randn(300)  # random number for UNK\nwith open('./glove.6B.300d.txt') as f:\n  for i, line in enumerate(f.readlines()):\n    vocab.append(line.split(' ')[0])\n    embedding[i] = np.array(line.split(' ')[1:], dtype=np.float32)\nembedding = torch.from_numpy(embedding)\nword2id = {word: id_ for id_, word in enumerate(vocab)}\n```\n\n\n```python\nclass GloVeAverage(SimilaritySearch):\n  def __init__(self, dataset, voacb, embedding, word2id):\n    self.dataset = dataset\n    self.vocab = vocab\n    self.embedding = embedding\n    self.word2id = word2id\n    self.documents = []\n\n    for i in tqdm(range(len(dataset))):\n      self.add(dataset[i]['context'].split(' '))\n\n  def train(self, documents):\n    pass\n\n  def add(self, documents):\n    sentence_to_idx = []\n    ll = []\n    for word_ in documents:\n      word = word_.lower()\n      if word in ll:\n        continue\n      if word not in self.vocab:\n        continue\n      idx = self.word2id[word]\n      sentence_to_idx.append(idx)\n      ll.append(word)\n    emb = self.embedding[sentence_to_idx].mean(0)\n    self.documents.append(emb)\n\n  def search(self, query_set, k):\n    start_time = time.time()\n    query_emb_documents = []\n    for doc in tqdm(range(len(query_set))):\n      query = query_set[doc]['question'].split(' ')\n      sentence_to_idx = []\n      for word_ in query:\n        word = word_.lower()\n        if word not in self.vocab:\n          continue\n        idx = self.word2id[word]\n        sentence_to_idx.append(idx)\n      query_emb = self.embedding[sentence_to_idx].mean(0)\n      query_emb_documents.append(query_emb)\n    query_emb_documents = torch.nn.functional.normalize(torch.stack(query_emb_documents, 0), dim=1)\n    \n    documents = torch.nn.functional.normalize(torch.stack(self.documents, 0), dim=1)\n    scores = torch.mm(query_emb_documents, documents.transpose(0, 1))\n    indices = torch.topk(scores, k, dim=1)[1]\n    \n    end_time = time.time() - start_time\n    print('Search Time: {}s'.format(end_time))\n    return indices\n```\n\n> **Problem 3.2** *(2 points)* Use `GloVeAverage` to measure the recall at 10 for SQuAD validation dataset. How does it compare to TFIDF?\n\nRecall@10 of GloveAverage is 31.5%. (see the code) TFIDF was better than GloVeAverage for SQuAD valiation set.\n\n\n```python\ndataset = squad_dataset['validation']\ngloveaverage = GloVeAverage(dataset, vocab, embedding, word2id)\nrecall = 0\nindices = gloveaverage.search(dataset, 10)\nfor i in range(len(indices)):\n  if i in indices[i]:\n    recall += 1\nrecall /= len(dataset)\n\nprint(recall)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 10570/10570 [24:21<00:00,  7.23it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 10570/10570 [01:59<00:00, 88.78it/s]\n\n\n    Search Time: 121.20724582672119s\n    0.31494796594134344\n\n\n> **Problem 3.3** *(2 points)* Implement `GloVeAverageFaiss` that subclasses `SimilaritySearch` and uses Faiss `IndexFlatIP` instead of PyTorch native tensor operation for search. Refer to the Faiss wiki (https://github.com/facebookresearch/faiss/wiki/Getting-started) for instructions.\n\n\n```python\n!pip install faiss-cpu\nimport faiss\n```\n\n    Collecting faiss-cpu\n      Downloading faiss_cpu-1.7.1.post2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (8.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 8.4 MB 4.4 MB/s \n    \u001b[?25hInstalling collected packages: faiss-cpu\n    Successfully installed faiss-cpu-1.7.1.post2\n\n\n\n```python\nclass GloVeAverageFaiss(SimilaritySearch):\n  def __init__(self, dataset, voacb, embedding, word2id):\n    self.dataset = dataset\n    self.vocab = vocab\n    self.embedding = embedding.numpy()\n    self.d = self.embedding.shape[1]\n    self.index = faiss.IndexFlatIP(self.d)\n    self.word2id = word2id\n    self.documents = []\n\n    for i in tqdm(range(len(dataset))):\n      self.add(dataset[i]['context'].split(' '))\n    # print(self.index.ntotal)\n\n  def train(self, documents):\n    pass\n\n  def add(self, documents):\n    sentence_to_idx = []\n    ll = []\n    for word_ in documents:\n      word = word_.lower()\n      if word in ll:\n        continue\n      if word not in self.vocab:\n        continue\n      idx = self.word2id[word]\n      sentence_to_idx.append(idx)\n      ll.append(word)\n    emb = self.embedding[sentence_to_idx].mean(0, keepdims=True)\n    emb = emb / np.linalg.norm(emb, 2, 1, keepdims=True)\n    self.index.add(emb)\n\n  def search(self, query_set, k):\n    start_time = time.time()\n    query_emb_documents = []\n    for doc in tqdm(range(len(query_set))):\n      query = query_set[doc]['question'].split(' ')\n      sentence_to_idx = []\n      for word_ in query:\n        word = word_.lower()\n        if word not in self.vocab:\n          continue\n        idx = self.word2id[word]\n        sentence_to_idx.append(idx)\n      query_emb = self.embedding[sentence_to_idx].mean(0)\n      query_emb_documents.append(query_emb)\n\n    query_emb_documents = np.stack(query_emb_documents, 0)\n    query_emb_documents = query_emb_documents / np.linalg.norm(query_emb_documents, 2, 1, keepdims=True)\n    \n    D, I = self.index.search(query_emb_documents, k)\n    end_time = time.time() - start_time\n    print('Search Time: {}s'.format(end_time))\n    return I\n```\n\n> **Problem 3.4** *(1 points)* Compare the speed between `GloVeAverage` and `GloVeAverageFaiss` on SQuAD. To make the measurement accurate, perform search many times (at least more than 1000) and take the average.\n\nGloVeAverage vs. GloVeAverageFaiss : 121.2s vs. 119.9s (over 10000 searches)\n\nThe procedure of adding query vectors to arrays was a bottleneck, so there was not much difference in total time.\n\n\n```python\ndataset = squad_dataset['validation']\ngloveaveragefaiss = GloVeAverageFaiss(dataset, vocab, embedding, word2id)\nrecall = 0\nindices = gloveaveragefaiss.search(dataset, 10)\nfor i in range(len(indices)):\n  if i in indices[i]:\n    recall += 1\nrecall /= len(dataset)\n\nprint(recall)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 10570/10570 [24:27<00:00,  7.20it/s]\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 10570/10570 [01:58<00:00, 89.13it/s]\n\n\n    Search Time: 119.89045238494873s\n    0.31494796594134344\n\n", "meta": {"hexsha": "4e70938cfe2ddfb51c7432a0a27e2f80efa12f44", "size": 136890, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "AI605/KAIST_AI605_Assignment_2.ipynb", "max_stars_repo_name": "sungnyun/AI-assignments", "max_stars_repo_head_hexsha": "6451fd6db33fd8671ca362b4ad4c190979a98c22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AI605/KAIST_AI605_Assignment_2.ipynb", "max_issues_repo_name": "sungnyun/AI-assignments", "max_issues_repo_head_hexsha": "6451fd6db33fd8671ca362b4ad4c190979a98c22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AI605/KAIST_AI605_Assignment_2.ipynb", "max_forks_repo_name": "sungnyun/AI-assignments", "max_forks_repo_head_hexsha": "6451fd6db33fd8671ca362b4ad4c190979a98c22", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1113636364, "max_line_length": 492, "alphanum_fraction": 0.5750237417, "converted": true, "num_tokens": 6701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1666754046879767, "lm_q2_score": 0.10818895456207037, "lm_q1q2_score": 0.0180324377844022}}
{"text": "# 1. Loading data\n\n\n```python\nimport gc\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Load subset of the training data\nX_train = pd.read_csv('data/train.csv', nrows=1000000, parse_dates=['click_time'])\n\n# Show the head of the table\nX_train.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>ip</th>\n      <th>app</th>\n      <th>device</th>\n      <th>os</th>\n      <th>channel</th>\n      <th>click_time</th>\n      <th>attributed_time</th>\n      <th>is_attributed</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>83230</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:32:21</td>\n      <td>NaN</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>17357</td>\n      <td>3</td>\n      <td>1</td>\n      <td>19</td>\n      <td>379</td>\n      <td>2017-11-06 14:33:34</td>\n      <td>NaN</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>35810</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:34:12</td>\n      <td>NaN</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>45745</td>\n      <td>14</td>\n      <td>1</td>\n      <td>13</td>\n      <td>478</td>\n      <td>2017-11-06 14:34:52</td>\n      <td>NaN</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>161007</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:35:08</td>\n      <td>NaN</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n# 2. Creating Features\n## 2.1 Extracting time information\nFirst extract day, minute, hour, second from the click_time. \n\n\n```python\nX_train['day'] = X_train['click_time'].dt.day.astype('uint8')\nX_train['hour'] = X_train['click_time'].dt.hour.astype('uint8')\nX_train['minute'] = X_train['click_time'].dt.minute.astype('uint8')\nX_train['second'] = X_train['click_time'].dt.second.astype('uint8')\nX_train.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>ip</th>\n      <th>app</th>\n      <th>device</th>\n      <th>os</th>\n      <th>channel</th>\n      <th>click_time</th>\n      <th>attributed_time</th>\n      <th>is_attributed</th>\n      <th>day</th>\n      <th>hour</th>\n      <th>minute</th>\n      <th>second</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>83230</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:32:21</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>32</td>\n      <td>21</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>17357</td>\n      <td>3</td>\n      <td>1</td>\n      <td>19</td>\n      <td>379</td>\n      <td>2017-11-06 14:33:34</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>33</td>\n      <td>34</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>35810</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:34:12</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>34</td>\n      <td>12</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>45745</td>\n      <td>14</td>\n      <td>1</td>\n      <td>13</td>\n      <td>478</td>\n      <td>2017-11-06 14:34:52</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>34</td>\n      <td>52</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>161007</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:35:08</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>35</td>\n      <td>8</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nday = X_train['day'].value_counts()\nday.plot(kind='barh')\n```\n\n\n```python\nhour = X_train['hour'].value_counts()\nhour.plot(kind='barh')\n```\n\n\n```python\nminute = X_train['minute'].value_counts()\nminute.plot(kind='barh')\n```\n\n\n```python\nsecond = X_train['second'].value_counts()\nsecond.plot(kind='barh')\n```\n\n## 2.2. Confidence Rates for is_attributed\nMy thought is that some ips, apps, devices, etc. might have higher frequencies of is_attributed, and I wish to add that information, i.e. I'm calculating the following \"attributed rates\":\n\n\\begin{equation}\n\\text{P}\\,\\text{(is_attributed}\\,\\,|\\,\\,\\text{category)}\n\\end{equation}\n\nor in some cases two- or multiple-paired combinations:\n\n\\begin{equation}\n\\text{P}\\,\\text{(is_attributed}\\,\\,|\\,\\,\\text{category_1, category_2)}\n\\end{equation}\n\nThe danger of this is that if a given category-combination has very few clicks, then the statistical significance of above equations cannot be trusted. Therefore I'll be weighing the rates by the following confidence rates:\n\n\\begin{equation}\n    \\text{conf}_{\\text{is_attributed}} = \\frac{\\log(\\text{views}_{\\text{category_1}})}{\\log(100000)}\n\\end{equation}\n\nwhere the value 100000 has been chosen arbitrarily to such that if a given category has 1000 views, then it gets a confidence weight of 60%, if it has 100 views then onfly a confidence weight of 40% etc.\n\n\n```python\nATTRIBUTION_CATEGORIES = [        \n    # V1 Features #\n    ###############\n    ['ip'], ['app'], ['device'], ['os'], ['channel'],\n    \n    # V2 Features #\n    ###############\n    ['app', 'channel'],\n    ['app', 'os'],\n    ['app', 'device'],\n    \n    # V3 Features #\n    ###############\n    ['channel', 'os'],\n    ['channel', 'device'],\n    ['os', 'device']\n]\n\ncovs = []\ncorrs = []\n# Find frequency of is_attributed for each unique value in column\nfreqs = {}\nfor cols in ATTRIBUTION_CATEGORIES:\n    \n    # New feature name\n    new_feature = '_'.join(cols)+'_confRate'  \n    covs.append(new_feature)\n    corrs.append(new_feature)\n    \n    # Perform the groupby\n    group_object = X_train.groupby(cols)\n    \n    # Group sizes    \n    group_sizes = group_object.size()\n    log_group = np.log(100000) # 1000 views -> 60% confidence, 100 views -> 40% confidence \n    print(\">> Calculating confidence-weighted rate for: {}.\\n   Saving to: {}. Group Max /Mean / Median / Min: {} / {} / {} / {}\".format(\n        cols, new_feature, \n        group_sizes.max(), \n        np.round(group_sizes.mean(), 2),\n        np.round(group_sizes.median(), 2),\n        group_sizes.min()\n    ))\n    \n    # Aggregation function\n    def rate_calculation(x):\n        \"\"\"Calculate the attributed rate. Scale by confidence\"\"\"\n        rate = x.sum() / float(x.count())\n        conf = np.min([1, np.log(x.count()) / log_group])\n        return rate * conf\n    \n    # Perform the merge\n    X_train = X_train.merge(\n        group_object['is_attributed']. \\\n            apply(rate_calculation). \\\n            reset_index(). \\\n            rename( \n                index=str,\n                columns={'is_attributed': new_feature}\n            )[cols + [new_feature]],\n        on=cols, how='left'\n    )\n    \nX_train.head()\nX_train\n```\n\n    >> Calculating confidence-weighted rate for: ['ip'].\n       Saving to: ip_confRate. Group Max /Mean / Median / Min: 6437 / 25.25 / 10.0 / 1\n    >> Calculating confidence-weighted rate for: ['app'].\n       Saving to: app_confRate. Group Max /Mean / Median / Min: 141851 / 4672.9 / 12.0 / 1\n    >> Calculating confidence-weighted rate for: ['device'].\n       Saving to: device_confRate. Group Max /Mean / Median / Min: 938053 / 3355.7 / 1.0 / 1\n    >> Calculating confidence-weighted rate for: ['os'].\n       Saving to: os_confRate. Group Max /Mean / Median / Min: 239642 / 6250.0 / 38.0 / 1\n    >> Calculating confidence-weighted rate for: ['channel'].\n       Saving to: channel_confRate. Group Max /Mean / Median / Min: 92534 / 6493.51 / 1200.0 / 1\n    >> Calculating confidence-weighted rate for: ['app', 'channel'].\n       Saving to: app_channel_confRate. Group Max /Mean / Median / Min: 61413 / 1915.71 / 18.0 / 1\n    >> Calculating confidence-weighted rate for: ['app', 'os'].\n       Saving to: app_os_confRate. Group Max /Mean / Median / Min: 34853 / 352.24 / 8.0 / 1\n    >> Calculating confidence-weighted rate for: ['app', 'device'].\n       Saving to: app_device_confRate. Group Max /Mean / Median / Min: 134290 / 1342.28 / 2.0 / 1\n    >> Calculating confidence-weighted rate for: ['channel', 'os'].\n       Saving to: channel_os_confRate. Group Max /Mean / Median / Min: 22462 / 174.76 / 15.0 / 1\n    >> Calculating confidence-weighted rate for: ['channel', 'device'].\n       Saving to: channel_device_confRate. Group Max /Mean / Median / Min: 87519 / 1300.39 / 3.0 / 1\n    >> Calculating confidence-weighted rate for: ['os', 'device'].\n       Saving to: os_device_confRate. Group Max /Mean / Median / Min: 233133 / 1721.17 / 3.0 / 1\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>ip</th>\n      <th>app</th>\n      <th>device</th>\n      <th>os</th>\n      <th>channel</th>\n      <th>click_time</th>\n      <th>attributed_time</th>\n      <th>is_attributed</th>\n      <th>day</th>\n      <th>hour</th>\n      <th>...</th>\n      <th>app_confRate</th>\n      <th>device_confRate</th>\n      <th>os_confRate</th>\n      <th>channel_confRate</th>\n      <th>app_channel_confRate</th>\n      <th>app_os_confRate</th>\n      <th>app_device_confRate</th>\n      <th>channel_os_confRate</th>\n      <th>channel_device_confRate</th>\n      <th>os_device_confRate</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>83230</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:32:21</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.001146</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000366</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000499</td>\n      <td>0.001182</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>17357</td>\n      <td>3</td>\n      <td>1</td>\n      <td>19</td>\n      <td>379</td>\n      <td>2017-11-06 14:33:34</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.001394</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000275</td>\n      <td>0.000444</td>\n      <td>0.000235</td>\n      <td>0.000499</td>\n      <td>0.001428</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>35810</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:34:12</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.001146</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000366</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000499</td>\n      <td>0.001182</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>45745</td>\n      <td>14</td>\n      <td>1</td>\n      <td>13</td>\n      <td>478</td>\n      <td>2017-11-06 14:34:52</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000431</td>\n      <td>0.001193</td>\n      <td>0.001146</td>\n      <td>0.004071</td>\n      <td>0.004164</td>\n      <td>0.000201</td>\n      <td>0.000445</td>\n      <td>0.001835</td>\n      <td>0.004109</td>\n      <td>0.001182</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>161007</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:35:08</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.001146</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000366</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000499</td>\n      <td>0.001182</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>18787</td>\n      <td>3</td>\n      <td>1</td>\n      <td>16</td>\n      <td>379</td>\n      <td>2017-11-06 14:36:26</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.000851</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000559</td>\n      <td>0.000444</td>\n      <td>0.002329</td>\n      <td>0.000499</td>\n      <td>0.000882</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>103022</td>\n      <td>3</td>\n      <td>1</td>\n      <td>23</td>\n      <td>379</td>\n      <td>2017-11-06 14:37:44</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.000328</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000000</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000499</td>\n      <td>0.000336</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>114221</td>\n      <td>3</td>\n      <td>1</td>\n      <td>19</td>\n      <td>379</td>\n      <td>2017-11-06 14:37:59</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.001394</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000275</td>\n      <td>0.000444</td>\n      <td>0.000235</td>\n      <td>0.000499</td>\n      <td>0.001428</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>165970</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:38:10</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.001146</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000366</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000499</td>\n      <td>0.001182</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>74544</td>\n      <td>64</td>\n      <td>1</td>\n      <td>22</td>\n      <td>459</td>\n      <td>2017-11-06 14:38:23</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000256</td>\n      <td>0.001193</td>\n      <td>0.001859</td>\n      <td>0.000161</td>\n      <td>0.000256</td>\n      <td>0.000000</td>\n      <td>0.000260</td>\n      <td>0.000000</td>\n      <td>0.000165</td>\n      <td>0.001944</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>172522</td>\n      <td>3</td>\n      <td>1</td>\n      <td>25</td>\n      <td>379</td>\n      <td>2017-11-06 14:38:27</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.000922</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000212</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000499</td>\n      <td>0.000956</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>105861</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:38:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.001146</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000366</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000499</td>\n      <td>0.001182</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>210962</td>\n      <td>3</td>\n      <td>1</td>\n      <td>19</td>\n      <td>379</td>\n      <td>2017-11-06 14:39:29</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.001394</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000275</td>\n      <td>0.000444</td>\n      <td>0.000235</td>\n      <td>0.000499</td>\n      <td>0.001428</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>124979</td>\n      <td>3</td>\n      <td>1</td>\n      <td>18</td>\n      <td>379</td>\n      <td>2017-11-06 14:40:16</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.000914</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000318</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000499</td>\n      <td>0.000925</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>38816</td>\n      <td>3</td>\n      <td>1</td>\n      <td>18</td>\n      <td>379</td>\n      <td>2017-11-06 14:40:39</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.000914</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000318</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000499</td>\n      <td>0.000925</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>80447</td>\n      <td>3</td>\n      <td>1</td>\n      <td>19</td>\n      <td>379</td>\n      <td>2017-11-06 14:40:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.001394</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000275</td>\n      <td>0.000444</td>\n      <td>0.000235</td>\n      <td>0.000499</td>\n      <td>0.001428</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>134575</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:43:10</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.001146</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000366</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000499</td>\n      <td>0.001182</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>57576</td>\n      <td>3</td>\n      <td>1</td>\n      <td>19</td>\n      <td>379</td>\n      <td>2017-11-06 14:43:14</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.001394</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000275</td>\n      <td>0.000444</td>\n      <td>0.000235</td>\n      <td>0.000499</td>\n      <td>0.001428</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>7755</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:43:25</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.001146</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000366</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000499</td>\n      <td>0.001182</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>91749</td>\n      <td>3</td>\n      <td>1</td>\n      <td>19</td>\n      <td>379</td>\n      <td>2017-11-06 14:43:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.001394</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000275</td>\n      <td>0.000444</td>\n      <td>0.000235</td>\n      <td>0.000499</td>\n      <td>0.001428</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>50694</td>\n      <td>3</td>\n      <td>1</td>\n      <td>18</td>\n      <td>379</td>\n      <td>2017-11-06 14:44:02</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.000914</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000318</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000499</td>\n      <td>0.000925</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>111385</td>\n      <td>3</td>\n      <td>1</td>\n      <td>18</td>\n      <td>379</td>\n      <td>2017-11-06 14:44:15</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.000914</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000318</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000499</td>\n      <td>0.000925</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>125222</td>\n      <td>14</td>\n      <td>1</td>\n      <td>3</td>\n      <td>478</td>\n      <td>2017-11-06 14:44:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000431</td>\n      <td>0.001193</td>\n      <td>0.000766</td>\n      <td>0.004071</td>\n      <td>0.004164</td>\n      <td>0.000000</td>\n      <td>0.000445</td>\n      <td>0.000000</td>\n      <td>0.004109</td>\n      <td>0.000789</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>191759</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:44:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.001146</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000366</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000499</td>\n      <td>0.001182</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>53418</td>\n      <td>3</td>\n      <td>1</td>\n      <td>17</td>\n      <td>379</td>\n      <td>2017-11-06 14:44:52</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.000893</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000304</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000499</td>\n      <td>0.000944</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>183168</td>\n      <td>3</td>\n      <td>1</td>\n      <td>19</td>\n      <td>379</td>\n      <td>2017-11-06 14:47:49</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.001394</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000275</td>\n      <td>0.000444</td>\n      <td>0.000235</td>\n      <td>0.000499</td>\n      <td>0.001428</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>47902</td>\n      <td>3</td>\n      <td>1</td>\n      <td>17</td>\n      <td>379</td>\n      <td>2017-11-06 14:48:07</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.000893</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000304</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000499</td>\n      <td>0.000944</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>209663</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:48:55</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.001146</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000366</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000499</td>\n      <td>0.001182</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>129614</td>\n      <td>3</td>\n      <td>1</td>\n      <td>20</td>\n      <td>379</td>\n      <td>2017-11-06 14:49:36</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.000958</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000220</td>\n      <td>0.000444</td>\n      <td>0.002091</td>\n      <td>0.000499</td>\n      <td>0.001000</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>208347</td>\n      <td>3</td>\n      <td>1</td>\n      <td>19</td>\n      <td>379</td>\n      <td>2017-11-06 14:49:38</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.001394</td>\n      <td>0.000497</td>\n      <td>0.000360</td>\n      <td>0.000275</td>\n      <td>0.000444</td>\n      <td>0.000235</td>\n      <td>0.000499</td>\n      <td>0.001428</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>999970</th>\n      <td>32115</td>\n      <td>18</td>\n      <td>1</td>\n      <td>22</td>\n      <td>134</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000369</td>\n      <td>0.001193</td>\n      <td>0.001859</td>\n      <td>0.000562</td>\n      <td>0.000700</td>\n      <td>0.000478</td>\n      <td>0.000402</td>\n      <td>0.002892</td>\n      <td>0.000583</td>\n      <td>0.001944</td>\n    </tr>\n    <tr>\n      <th>999971</th>\n      <td>28113</td>\n      <td>15</td>\n      <td>1</td>\n      <td>13</td>\n      <td>245</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000210</td>\n      <td>0.001193</td>\n      <td>0.001146</td>\n      <td>0.000064</td>\n      <td>0.000078</td>\n      <td>0.000069</td>\n      <td>0.000220</td>\n      <td>0.000042</td>\n      <td>0.000068</td>\n      <td>0.001182</td>\n    </tr>\n    <tr>\n      <th>999972</th>\n      <td>175237</td>\n      <td>18</td>\n      <td>1</td>\n      <td>19</td>\n      <td>439</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000369</td>\n      <td>0.001193</td>\n      <td>0.001394</td>\n      <td>0.000470</td>\n      <td>0.000351</td>\n      <td>0.000737</td>\n      <td>0.000402</td>\n      <td>0.000255</td>\n      <td>0.000471</td>\n      <td>0.001428</td>\n    </tr>\n    <tr>\n      <th>999973</th>\n      <td>114656</td>\n      <td>3</td>\n      <td>1</td>\n      <td>36</td>\n      <td>137</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.000000</td>\n      <td>0.000393</td>\n      <td>0.000347</td>\n      <td>0.000000</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000434</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>999974</th>\n      <td>43793</td>\n      <td>6</td>\n      <td>1</td>\n      <td>18</td>\n      <td>125</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000085</td>\n      <td>0.001193</td>\n      <td>0.000914</td>\n      <td>0.000063</td>\n      <td>0.000069</td>\n      <td>0.000523</td>\n      <td>0.000087</td>\n      <td>0.000000</td>\n      <td>0.000065</td>\n      <td>0.000925</td>\n    </tr>\n    <tr>\n      <th>999975</th>\n      <td>166358</td>\n      <td>26</td>\n      <td>1</td>\n      <td>12</td>\n      <td>266</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000564</td>\n      <td>0.001193</td>\n      <td>0.000753</td>\n      <td>0.001060</td>\n      <td>0.001060</td>\n      <td>0.000000</td>\n      <td>0.000566</td>\n      <td>0.000000</td>\n      <td>0.001063</td>\n      <td>0.000778</td>\n    </tr>\n    <tr>\n      <th>999976</th>\n      <td>67494</td>\n      <td>9</td>\n      <td>1</td>\n      <td>19</td>\n      <td>234</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000848</td>\n      <td>0.001193</td>\n      <td>0.001394</td>\n      <td>0.000749</td>\n      <td>0.000749</td>\n      <td>0.000841</td>\n      <td>0.000888</td>\n      <td>0.000988</td>\n      <td>0.000859</td>\n      <td>0.001428</td>\n    </tr>\n    <tr>\n      <th>999977</th>\n      <td>73516</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>280</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.001146</td>\n      <td>0.000351</td>\n      <td>0.000320</td>\n      <td>0.000366</td>\n      <td>0.000444</td>\n      <td>0.000625</td>\n      <td>0.000304</td>\n      <td>0.001182</td>\n    </tr>\n    <tr>\n      <th>999978</th>\n      <td>109744</td>\n      <td>9</td>\n      <td>1</td>\n      <td>20</td>\n      <td>234</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000848</td>\n      <td>0.001193</td>\n      <td>0.000958</td>\n      <td>0.000749</td>\n      <td>0.000749</td>\n      <td>0.000973</td>\n      <td>0.000888</td>\n      <td>0.000000</td>\n      <td>0.000859</td>\n      <td>0.001000</td>\n    </tr>\n    <tr>\n      <th>999979</th>\n      <td>61706</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>280</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.001146</td>\n      <td>0.000351</td>\n      <td>0.000320</td>\n      <td>0.000366</td>\n      <td>0.000444</td>\n      <td>0.000625</td>\n      <td>0.000304</td>\n      <td>0.001182</td>\n    </tr>\n    <tr>\n      <th>999980</th>\n      <td>141925</td>\n      <td>28</td>\n      <td>1</td>\n      <td>19</td>\n      <td>135</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000145</td>\n      <td>0.001193</td>\n      <td>0.001394</td>\n      <td>0.000303</td>\n      <td>0.000145</td>\n      <td>0.000000</td>\n      <td>0.000145</td>\n      <td>0.000000</td>\n      <td>0.000309</td>\n      <td>0.001428</td>\n    </tr>\n    <tr>\n      <th>999981</th>\n      <td>93155</td>\n      <td>12</td>\n      <td>1</td>\n      <td>19</td>\n      <td>178</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000134</td>\n      <td>0.001193</td>\n      <td>0.001394</td>\n      <td>0.000147</td>\n      <td>0.000157</td>\n      <td>0.000104</td>\n      <td>0.000141</td>\n      <td>0.000216</td>\n      <td>0.000157</td>\n      <td>0.001428</td>\n    </tr>\n    <tr>\n      <th>999982</th>\n      <td>15530</td>\n      <td>9</td>\n      <td>1</td>\n      <td>18</td>\n      <td>466</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000848</td>\n      <td>0.001193</td>\n      <td>0.000914</td>\n      <td>0.000865</td>\n      <td>0.000757</td>\n      <td>0.000256</td>\n      <td>0.000888</td>\n      <td>0.000000</td>\n      <td>0.000867</td>\n      <td>0.000925</td>\n    </tr>\n    <tr>\n      <th>999983</th>\n      <td>2698</td>\n      <td>25</td>\n      <td>1</td>\n      <td>30</td>\n      <td>259</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000101</td>\n      <td>0.001193</td>\n      <td>0.000144</td>\n      <td>0.000519</td>\n      <td>0.000101</td>\n      <td>0.000000</td>\n      <td>0.000104</td>\n      <td>0.000000</td>\n      <td>0.000574</td>\n      <td>0.000155</td>\n    </tr>\n    <tr>\n      <th>999984</th>\n      <td>29290</td>\n      <td>3</td>\n      <td>1</td>\n      <td>10</td>\n      <td>480</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.000962</td>\n      <td>0.000174</td>\n      <td>0.000162</td>\n      <td>0.000000</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000175</td>\n      <td>0.000995</td>\n    </tr>\n    <tr>\n      <th>999985</th>\n      <td>38277</td>\n      <td>3</td>\n      <td>1</td>\n      <td>12</td>\n      <td>137</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.000753</td>\n      <td>0.000393</td>\n      <td>0.000347</td>\n      <td>0.000000</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000434</td>\n      <td>0.000778</td>\n    </tr>\n    <tr>\n      <th>999986</th>\n      <td>131635</td>\n      <td>24</td>\n      <td>1</td>\n      <td>1</td>\n      <td>105</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000315</td>\n      <td>0.001193</td>\n      <td>0.001424</td>\n      <td>0.000333</td>\n      <td>0.000339</td>\n      <td>0.000000</td>\n      <td>0.000389</td>\n      <td>0.000000</td>\n      <td>0.000413</td>\n      <td>0.001470</td>\n    </tr>\n    <tr>\n      <th>999987</th>\n      <td>43698</td>\n      <td>18</td>\n      <td>1</td>\n      <td>19</td>\n      <td>121</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000369</td>\n      <td>0.001193</td>\n      <td>0.001394</td>\n      <td>0.000271</td>\n      <td>0.000280</td>\n      <td>0.000737</td>\n      <td>0.000402</td>\n      <td>0.000547</td>\n      <td>0.000280</td>\n      <td>0.001428</td>\n    </tr>\n    <tr>\n      <th>999988</th>\n      <td>27838</td>\n      <td>12</td>\n      <td>1</td>\n      <td>19</td>\n      <td>265</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000134</td>\n      <td>0.001193</td>\n      <td>0.001394</td>\n      <td>0.000079</td>\n      <td>0.000048</td>\n      <td>0.000104</td>\n      <td>0.000141</td>\n      <td>0.000000</td>\n      <td>0.000082</td>\n      <td>0.001428</td>\n    </tr>\n    <tr>\n      <th>999989</th>\n      <td>70271</td>\n      <td>2</td>\n      <td>1</td>\n      <td>6</td>\n      <td>435</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000262</td>\n      <td>0.001193</td>\n      <td>0.001548</td>\n      <td>0.000100</td>\n      <td>0.000100</td>\n      <td>0.000223</td>\n      <td>0.000278</td>\n      <td>0.000000</td>\n      <td>0.000101</td>\n      <td>0.001592</td>\n    </tr>\n    <tr>\n      <th>999990</th>\n      <td>76788</td>\n      <td>3</td>\n      <td>1</td>\n      <td>12</td>\n      <td>205</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.000753</td>\n      <td>0.000192</td>\n      <td>0.000492</td>\n      <td>0.000000</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000216</td>\n      <td>0.000778</td>\n    </tr>\n    <tr>\n      <th>999991</th>\n      <td>191894</td>\n      <td>24</td>\n      <td>2</td>\n      <td>15</td>\n      <td>105</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000315</td>\n      <td>0.000171</td>\n      <td>0.000604</td>\n      <td>0.000333</td>\n      <td>0.000339</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>999992</th>\n      <td>105560</td>\n      <td>3</td>\n      <td>1</td>\n      <td>19</td>\n      <td>137</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000446</td>\n      <td>0.001193</td>\n      <td>0.001394</td>\n      <td>0.000393</td>\n      <td>0.000347</td>\n      <td>0.000275</td>\n      <td>0.000444</td>\n      <td>0.000000</td>\n      <td>0.000434</td>\n      <td>0.001428</td>\n    </tr>\n    <tr>\n      <th>999993</th>\n      <td>73516</td>\n      <td>9</td>\n      <td>2</td>\n      <td>13</td>\n      <td>134</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000848</td>\n      <td>0.000171</td>\n      <td>0.001146</td>\n      <td>0.000562</td>\n      <td>0.000655</td>\n      <td>0.000809</td>\n      <td>0.000214</td>\n      <td>0.000418</td>\n      <td>0.000000</td>\n      <td>0.000253</td>\n    </tr>\n    <tr>\n      <th>999994</th>\n      <td>6578</td>\n      <td>9</td>\n      <td>1</td>\n      <td>18</td>\n      <td>244</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000848</td>\n      <td>0.001193</td>\n      <td>0.000914</td>\n      <td>0.001919</td>\n      <td>0.001919</td>\n      <td>0.000256</td>\n      <td>0.000888</td>\n      <td>0.000000</td>\n      <td>0.002049</td>\n      <td>0.000925</td>\n    </tr>\n    <tr>\n      <th>999995</th>\n      <td>29748</td>\n      <td>9</td>\n      <td>1</td>\n      <td>12</td>\n      <td>134</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000848</td>\n      <td>0.001193</td>\n      <td>0.000753</td>\n      <td>0.000562</td>\n      <td>0.000655</td>\n      <td>0.000000</td>\n      <td>0.000888</td>\n      <td>0.000000</td>\n      <td>0.000583</td>\n      <td>0.000778</td>\n    </tr>\n    <tr>\n      <th>999996</th>\n      <td>124520</td>\n      <td>12</td>\n      <td>1</td>\n      <td>15</td>\n      <td>178</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000134</td>\n      <td>0.001193</td>\n      <td>0.000604</td>\n      <td>0.000147</td>\n      <td>0.000157</td>\n      <td>0.000000</td>\n      <td>0.000141</td>\n      <td>0.000000</td>\n      <td>0.000157</td>\n      <td>0.000628</td>\n    </tr>\n    <tr>\n      <th>999997</th>\n      <td>206446</td>\n      <td>18</td>\n      <td>1</td>\n      <td>42</td>\n      <td>107</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000369</td>\n      <td>0.001193</td>\n      <td>0.000000</td>\n      <td>0.000318</td>\n      <td>0.000318</td>\n      <td>0.000000</td>\n      <td>0.000402</td>\n      <td>0.000000</td>\n      <td>0.000383</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>999998</th>\n      <td>167577</td>\n      <td>12</td>\n      <td>1</td>\n      <td>13</td>\n      <td>265</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000134</td>\n      <td>0.001193</td>\n      <td>0.001146</td>\n      <td>0.000079</td>\n      <td>0.000048</td>\n      <td>0.000081</td>\n      <td>0.000141</td>\n      <td>0.000000</td>\n      <td>0.000082</td>\n      <td>0.001182</td>\n    </tr>\n    <tr>\n      <th>999999</th>\n      <td>121848</td>\n      <td>24</td>\n      <td>1</td>\n      <td>19</td>\n      <td>105</td>\n      <td>2017-11-06 16:21:51</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>16</td>\n      <td>...</td>\n      <td>0.000315</td>\n      <td>0.001193</td>\n      <td>0.001394</td>\n      <td>0.000333</td>\n      <td>0.000339</td>\n      <td>0.000394</td>\n      <td>0.000389</td>\n      <td>0.000416</td>\n      <td>0.000413</td>\n      <td>0.001428</td>\n    </tr>\n  </tbody>\n</table>\n<p>1000000 rows \u00d7 67 columns</p>\n</div>\n\n\n\n\n```python\ncovsp = {}\nfor c in covs:\n    sub_df = X_train[[c, 'is_attributed']]\n    covsp[c] = sub_df[c].cov(sub_df.is_attributed)\ncovsp\n```\n\n\n\n\n    {'app_channel_confRate': 0.00019634360938933638,\n     'app_confRate': 0.00020067377284722137,\n     'app_device_confRate': 0.0001803796749384625,\n     'app_os_confRate': 0.00014759553678794408,\n     'channel_confRate': 0.00016506487130292825,\n     'channel_device_confRate': 0.0001415220356796749,\n     'channel_os_confRate': 0.0001149070616583554,\n     'device_confRate': 3.8231808785780286e-05,\n     'ip_confRate': 2.0701035635506238e-05,\n     'os_confRate': 4.7006330764345326e-05,\n     'os_device_confRate': 3.514337207089287e-05}\n\n\n\n\n```python\n# histogram of covariance of each new column\nplt.bar(covsp.keys(), covsp.values())\nplt.xticks(rotation=90)\n```\n\n\n```python\ncorrsp = {}\nfor c in corrs:\n    sub_df = X_train[[c, 'is_attributed']]\n    corrsp[c] = sub_df[c].cov(sub_df.is_attributed)\ncorrsp\n```\n\n\n\n\n    {'app_channel_confRate': 0.00019634360938933638,\n     'app_confRate': 0.00020067377284722137,\n     'app_device_confRate': 0.0001803796749384625,\n     'app_os_confRate': 0.00014759553678794408,\n     'channel_confRate': 0.00016506487130292825,\n     'channel_device_confRate': 0.0001415220356796749,\n     'channel_os_confRate': 0.0001149070616583554,\n     'device_confRate': 3.8231808785780286e-05,\n     'ip_confRate': 2.0701035635506238e-05,\n     'os_confRate': 4.7006330764345326e-05,\n     'os_device_confRate': 3.514337207089287e-05}\n\n\n\n\n```python\n# histogram of correlation of each column\nplt.bar(corrsp.keys(), corrsp.values())\nplt.xticks(rotation=90)\n```\n\n## 2.3. Group-By-Aggregation\n\n\n```python\n# Define all the groupby transformations\nGROUPBY_AGGREGATIONS = [\n    \n    # V1 - GroupBy Features #\n    #########################    \n    # Variance in day, for ip-app-channel\n    {'groupby': ['ip','app','channel'], 'select': 'day', 'agg': 'var'},\n    # Variance in hour, for ip-app-os\n    {'groupby': ['ip','app','os'], 'select': 'hour', 'agg': 'var'},\n    # Variance in hour, for ip-day-channel\n    {'groupby': ['ip','day','channel'], 'select': 'hour', 'agg': 'var'},\n    # Count, for ip-day-hour\n    {'groupby': ['ip','day','hour'], 'select': 'channel', 'agg': 'count'},\n    # Count, for ip-app\n    {'groupby': ['ip', 'app'], 'select': 'channel', 'agg': 'count'},        \n    # Count, for ip-app-os\n    {'groupby': ['ip', 'app', 'os'], 'select': 'channel', 'agg': 'count'},\n    # Count, for ip-app-day-hour\n    {'groupby': ['ip','app','day','hour'], 'select': 'channel', 'agg': 'count'},\n    # Mean hour, for ip-app-channel\n    {'groupby': ['ip','app','channel'], 'select': 'hour', 'agg': 'mean'}, \n    \n    # V2 - GroupBy Features #\n    #########################\n    # Average clicks on app by distinct users; is it an app they return to?\n    {'groupby': ['app'], \n     'select': 'ip', \n     'agg': lambda x: float(len(x)) / len(x.unique()), \n     'agg_name': 'AvgViewPerDistinct'\n    },\n    # How popular is the app or channel?\n    {'groupby': ['app'], 'select': 'channel', 'agg': 'count'},\n    {'groupby': ['channel'], 'select': 'app', 'agg': 'count'},\n    \n    # V3 - GroupBy Features                                              #\n    # https://www.kaggle.com/bk0000/non-blending-lightgbm-model-lb-0-977 #\n    ###################################################################### \n    {'groupby': ['ip'], 'select': 'channel', 'agg': 'nunique'}, \n    {'groupby': ['ip'], 'select': 'app', 'agg': 'nunique'}, \n    {'groupby': ['ip','day'], 'select': 'hour', 'agg': 'nunique'}, \n    {'groupby': ['ip','app'], 'select': 'os', 'agg': 'nunique'}, \n    {'groupby': ['ip'], 'select': 'device', 'agg': 'nunique'}, \n    {'groupby': ['app'], 'select': 'channel', 'agg': 'nunique'}, \n    {'groupby': ['ip', 'device', 'os'], 'select': 'app', 'agg': 'nunique'}, \n    {'groupby': ['ip','device','os'], 'select': 'app', 'agg': 'cumcount'}, \n    {'groupby': ['ip'], 'select': 'app', 'agg': 'cumcount'}, \n    {'groupby': ['ip'], 'select': 'os', 'agg': 'cumcount'}, \n    {'groupby': ['ip','day','channel'], 'select': 'hour', 'agg': 'var'}    \n]\ncovs = []\ncorrs = []\n# Apply all the groupby transformations\nfor spec in GROUPBY_AGGREGATIONS:\n    \n    # Name of the aggregation we're applying\n    agg_name = spec['agg_name'] if 'agg_name' in spec else spec['agg']\n    \n    # Name of new feature\n    new_feature = '{}_{}_{}'.format('_'.join(spec['groupby']), agg_name, spec['select'])\n    covs.append(new_feature)\n    corrs.append(new_feature)\n    \n    # Info\n    print(\"Grouping by {}, and aggregating {} with {}\".format(\n        spec['groupby'], spec['select'], agg_name\n    ))\n    \n    # Unique list of features to select\n    all_features = list(set(spec['groupby'] + [spec['select']]))\n    \n    # Perform the groupby\n    gp = X_train[all_features]. \\\n        groupby(spec['groupby'])[spec['select']]. \\\n        agg(spec['agg']). \\\n        reset_index(). \\\n        rename(index=str, columns={spec['select']: new_feature})\n        \n    # Merge back to X_total\n    if 'cumcount' == spec['agg']:\n        X_train[new_feature] = gp[0].values\n    else:\n        X_train = X_train.merge(gp, on=spec['groupby'], how='left')\n        \n     # Clear memory\n    del gp\n    gc.collect()\n\nX_train.head()\n```\n\n    Grouping by ['ip', 'app', 'channel'], and aggregating day with var\n    Grouping by ['ip', 'app', 'os'], and aggregating hour with var\n    Grouping by ['ip', 'day', 'channel'], and aggregating hour with var\n    Grouping by ['ip', 'day', 'hour'], and aggregating channel with count\n    Grouping by ['ip', 'app'], and aggregating channel with count\n    Grouping by ['ip', 'app', 'os'], and aggregating channel with count\n    Grouping by ['ip', 'app', 'day', 'hour'], and aggregating channel with count\n    Grouping by ['ip', 'app', 'channel'], and aggregating hour with mean\n    Grouping by ['app'], and aggregating ip with AvgViewPerDistinct\n    Grouping by ['app'], and aggregating channel with count\n    Grouping by ['channel'], and aggregating app with count\n    Grouping by ['ip'], and aggregating channel with nunique\n    Grouping by ['ip'], and aggregating app with nunique\n    Grouping by ['ip', 'day'], and aggregating hour with nunique\n    Grouping by ['ip', 'app'], and aggregating os with nunique\n    Grouping by ['ip'], and aggregating device with nunique\n    Grouping by ['app'], and aggregating channel with nunique\n    Grouping by ['ip', 'device', 'os'], and aggregating app with nunique\n    Grouping by ['ip', 'device', 'os'], and aggregating app with cumcount\n    Grouping by ['ip'], and aggregating app with cumcount\n    Grouping by ['ip'], and aggregating os with cumcount\n    Grouping by ['ip', 'day', 'channel'], and aggregating hour with var\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>ip</th>\n      <th>app</th>\n      <th>device</th>\n      <th>os</th>\n      <th>channel</th>\n      <th>click_time</th>\n      <th>attributed_time</th>\n      <th>is_attributed</th>\n      <th>day</th>\n      <th>hour</th>\n      <th>...</th>\n      <th>ip_nunique_app</th>\n      <th>ip_day_nunique_hour</th>\n      <th>ip_app_nunique_os</th>\n      <th>ip_nunique_device</th>\n      <th>app_nunique_channel</th>\n      <th>ip_device_os_nunique_app</th>\n      <th>ip_device_os_cumcount_app</th>\n      <th>ip_cumcount_app</th>\n      <th>ip_cumcount_os</th>\n      <th>ip_day_channel_var_hour_y</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>83230</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:32:21</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>19</td>\n      <td>2</td>\n      <td>5</td>\n      <td>1</td>\n      <td>34</td>\n      <td>16</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1.333333</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>17357</td>\n      <td>3</td>\n      <td>1</td>\n      <td>19</td>\n      <td>379</td>\n      <td>2017-11-06 14:33:34</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>20</td>\n      <td>3</td>\n      <td>8</td>\n      <td>1</td>\n      <td>34</td>\n      <td>11</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>35810</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:34:12</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>17</td>\n      <td>2</td>\n      <td>6</td>\n      <td>3</td>\n      <td>34</td>\n      <td>10</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2.000000</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>45745</td>\n      <td>14</td>\n      <td>1</td>\n      <td>13</td>\n      <td>478</td>\n      <td>2017-11-06 14:34:52</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>31</td>\n      <td>2</td>\n      <td>18</td>\n      <td>6</td>\n      <td>26</td>\n      <td>24</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>161007</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:35:08</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>34</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 45 columns</p>\n</div>\n\n\n\n\n```python\ncovsp = {}\nfor c in covs:\n    sub_df = X_train[[c, 'is_attributed']]\n    covsp[c] = sub_df[c].cov(sub_df.is_attributed)\ncovsp\n```\n\n\n\n\n    {'app_channel_confRate': 0.00019634360938933638,\n     'app_confRate': 0.00020067377284722137,\n     'app_device_confRate': 0.0001803796749384625,\n     'app_os_confRate': 0.00014759553678794408,\n     'channel_confRate': 0.00016506487130292825,\n     'channel_device_confRate': 0.0001415220356796749,\n     'channel_os_confRate': 0.0001149070616583554,\n     'device_confRate': 3.8231808785780286e-05,\n     'ip_confRate': 2.0701035635506238e-05,\n     'os_confRate': 4.7006330764345326e-05,\n     'os_device_confRate': 3.514337207089287e-05}\n\n\n\n\n```python\n# histogram of covariance of each new column\nplt.bar(covsp.keys(), covsp.values())\nplt.xticks(rotation=90)\n```\n\n\n```python\ncorrsp = {}\nfor c in corrs:\n    sub_df = X_train[[c, 'is_attributed']]\n    corrsp[c] = sub_df[c].cov(sub_df.is_attributed)\ncorrsp\n```\n\n\n\n\n    {'app_channel_confRate': 0.00019634360938933638,\n     'app_confRate': 0.00020067377284722137,\n     'app_device_confRate': 0.0001803796749384625,\n     'app_os_confRate': 0.00014759553678794408,\n     'channel_confRate': 0.00016506487130292825,\n     'channel_device_confRate': 0.0001415220356796749,\n     'channel_os_confRate': 0.0001149070616583554,\n     'device_confRate': 3.8231808785780286e-05,\n     'ip_confRate': 2.0701035635506238e-05,\n     'os_confRate': 4.7006330764345326e-05,\n     'os_device_confRate': 3.514337207089287e-05}\n\n\n\n\n```python\n# histogram of correlation of each column\nplt.bar(corrsp.keys(), corrsp.values())\nplt.xticks(rotation=90)\n```\n\n# 2.4. Time till next click\nIt might be interesting to know e.g. how long it takes for a given ip-app-channel before they perform the next click. So I'll create some features for these as well. ****\n\n\n```python\nGROUP_BY_NEXT_CLICKS = [\n    \n    # V1\n    {'groupby': ['ip']},\n    {'groupby': ['ip', 'app']},\n    {'groupby': ['ip', 'channel']},\n    {'groupby': ['ip', 'os']},\n    \n    # V3\n    {'groupby': ['ip', 'app', 'device', 'os', 'channel']},\n    {'groupby': ['ip', 'os', 'device']},\n    {'groupby': ['ip', 'os', 'device', 'app']}\n]\ncovs = []\ncorrs = []\n# Calculate the time to next click for each group\nfor spec in GROUP_BY_NEXT_CLICKS:\n    # Name of new feature\n    new_feature = '{}_nextClick'.format('_'.join(spec['groupby']))    \n\n    covs.append(new_feature)\n    corrs.append(new_feature)\n    \n    # Unique list of features to select\n    all_features = spec['groupby'] + ['click_time']\n    \n    # Run calculation\n    print(f\">> Grouping by {spec['groupby']}, and saving time to next click in: {new_feature}\")\n    X_train[new_feature] = X_train[all_features].groupby(spec['groupby']).click_time.transform(lambda x: x.diff().shift(-1)).dt.seconds\n    \nX_train.head()\n```\n\n    >> Grouping by ['ip'], and saving time to next click in: ip_nextClick\n    >> Grouping by ['ip', 'app'], and saving time to next click in: ip_app_nextClick\n    >> Grouping by ['ip', 'channel'], and saving time to next click in: ip_channel_nextClick\n    >> Grouping by ['ip', 'os'], and saving time to next click in: ip_os_nextClick\n    >> Grouping by ['ip', 'app', 'device', 'os', 'channel'], and saving time to next click in: ip_app_device_os_channel_nextClick\n    >> Grouping by ['ip', 'os', 'device'], and saving time to next click in: ip_os_device_nextClick\n    >> Grouping by ['ip', 'os', 'device', 'app'], and saving time to next click in: ip_os_device_app_nextClick\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>ip</th>\n      <th>app</th>\n      <th>device</th>\n      <th>os</th>\n      <th>channel</th>\n      <th>click_time</th>\n      <th>attributed_time</th>\n      <th>is_attributed</th>\n      <th>day</th>\n      <th>hour</th>\n      <th>...</th>\n      <th>channel_os_confRate</th>\n      <th>channel_device_confRate</th>\n      <th>os_device_confRate</th>\n      <th>ip_nextClick</th>\n      <th>ip_app_nextClick</th>\n      <th>ip_channel_nextClick</th>\n      <th>ip_os_nextClick</th>\n      <th>ip_app_device_os_channel_nextClick</th>\n      <th>ip_os_device_nextClick</th>\n      <th>ip_os_device_app_nextClick</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>83230</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:32:21</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000000</td>\n      <td>0.000499</td>\n      <td>0.001182</td>\n      <td>5290.0</td>\n      <td>5340.0</td>\n      <td>5444.0</td>\n      <td>5307.0</td>\n      <td>NaN</td>\n      <td>5307.0</td>\n      <td>5340.0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>17357</td>\n      <td>3</td>\n      <td>1</td>\n      <td>19</td>\n      <td>379</td>\n      <td>2017-11-06 14:33:34</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000235</td>\n      <td>0.000499</td>\n      <td>0.001428</td>\n      <td>5177.0</td>\n      <td>5177.0</td>\n      <td>5177.0</td>\n      <td>5239.0</td>\n      <td>NaN</td>\n      <td>5239.0</td>\n      <td>5547.0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>35810</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:34:12</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000000</td>\n      <td>0.000499</td>\n      <td>0.001182</td>\n      <td>5175.0</td>\n      <td>5175.0</td>\n      <td>6005.0</td>\n      <td>5205.0</td>\n      <td>NaN</td>\n      <td>5205.0</td>\n      <td>5925.0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>45745</td>\n      <td>14</td>\n      <td>1</td>\n      <td>13</td>\n      <td>478</td>\n      <td>2017-11-06 14:34:52</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.001835</td>\n      <td>0.004109</td>\n      <td>0.001182</td>\n      <td>5108.0</td>\n      <td>5110.0</td>\n      <td>5137.0</td>\n      <td>5108.0</td>\n      <td>NaN</td>\n      <td>5108.0</td>\n      <td>5110.0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>161007</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:35:08</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>0.000000</td>\n      <td>0.000499</td>\n      <td>0.001182</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 74 columns</p>\n</div>\n\n\n\n\n```python\ncovsp = {}\nfor c in covs:\n    sub_df = X_train[[c, 'is_attributed']]\n    covsp[c] = sub_df[c].cov(sub_df.is_attributed)\ncovsp\n```\n\n\n\n\n    {'ip_app_device_os_channel_nextClick': 0.013632224912572783,\n     'ip_app_nextClick': 0.02012430954452766,\n     'ip_channel_nextClick': 0.021197197943624572,\n     'ip_nextClick': 0.07429679676171368,\n     'ip_os_device_app_nextClick': 0.014365914228217959,\n     'ip_os_device_nextClick': 0.03967463776528343,\n     'ip_os_nextClick': 0.041616729090613515}\n\n\n\n\n```python\n# histogram of covariance of each new column\nplt.bar(covsp.keys(), covsp.values())\nplt.xticks(rotation=90)\n```\n\n\n```python\ncorrsp = {}\nfor c in corrs:\n    sub_df = X_train[[c, 'is_attributed']]\n    corrsp[c] = sub_df[c].cov(sub_df.is_attributed)\ncorrsp\n```\n\n\n\n\n    {'ip_app_device_os_channel_nextClick': 0.013632224912572783,\n     'ip_app_nextClick': 0.02012430954452766,\n     'ip_channel_nextClick': 0.021197197943624572,\n     'ip_nextClick': 0.07429679676171368,\n     'ip_os_device_app_nextClick': 0.014365914228217959,\n     'ip_os_device_nextClick': 0.03967463776528343,\n     'ip_os_nextClick': 0.041616729090613515}\n\n\n\n\n```python\n# histogram of correlation of each column\nplt.bar(corrsp.keys(), corrsp.values())\nplt.xticks(rotation=90)\n```\n\n## 2.5. Clicks on app ad before & after\nHas the user previously or subsequently clicked the exact same app-device-os-channel? I thought that might be an interesting feature to test out as well.\n\n\n```python\nHISTORY_CLICKS = {\n    'identical_clicks': ['ip', 'app', 'device', 'os', 'channel'],\n    'app_clicks': ['ip', 'app']\n}\n\ncovs = []\ncorrs = []\n# Go through different group-by combinations\nfor fname, fset in HISTORY_CLICKS.items():\n    covs.append('prev_'+fname)\n    corrs.append('prev_'+fname)\n    \n    covs.append('future_'+fname)\n    corrs.append('future_'+fname)\n    \n    # Clicks in the past\n    X_train['prev_'+fname] = X_train. \\\n        groupby(fset). \\\n        cumcount(). \\\n        rename('prev_'+fname)\n        \n    # Clicks in the future\n    X_train['future_'+fname] = X_train.iloc[::-1]. \\\n        groupby(fset). \\\n        cumcount(). \\\n        rename('future_'+fname).iloc[::-1]\n\n# Count cumulative subsequent clicks\nX_train.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>ip</th>\n      <th>app</th>\n      <th>device</th>\n      <th>os</th>\n      <th>channel</th>\n      <th>click_time</th>\n      <th>attributed_time</th>\n      <th>is_attributed</th>\n      <th>day</th>\n      <th>hour</th>\n      <th>...</th>\n      <th>ip_app_nextClick</th>\n      <th>ip_channel_nextClick</th>\n      <th>ip_os_nextClick</th>\n      <th>ip_app_device_os_channel_nextClick</th>\n      <th>ip_os_device_nextClick</th>\n      <th>ip_os_device_app_nextClick</th>\n      <th>prev_identical_clicks</th>\n      <th>future_identical_clicks</th>\n      <th>prev_app_clicks</th>\n      <th>future_app_clicks</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>83230</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:32:21</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>5340.0</td>\n      <td>5444.0</td>\n      <td>5307.0</td>\n      <td>NaN</td>\n      <td>5307.0</td>\n      <td>5340.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>18</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>17357</td>\n      <td>3</td>\n      <td>1</td>\n      <td>19</td>\n      <td>379</td>\n      <td>2017-11-06 14:33:34</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>5177.0</td>\n      <td>5177.0</td>\n      <td>5239.0</td>\n      <td>NaN</td>\n      <td>5239.0</td>\n      <td>5547.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>22</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>35810</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:34:12</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>5175.0</td>\n      <td>6005.0</td>\n      <td>5205.0</td>\n      <td>NaN</td>\n      <td>5205.0</td>\n      <td>5925.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>9</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>45745</td>\n      <td>14</td>\n      <td>1</td>\n      <td>13</td>\n      <td>478</td>\n      <td>2017-11-06 14:34:52</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>5110.0</td>\n      <td>5137.0</td>\n      <td>5108.0</td>\n      <td>NaN</td>\n      <td>5108.0</td>\n      <td>5110.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>68</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>161007</td>\n      <td>3</td>\n      <td>1</td>\n      <td>13</td>\n      <td>379</td>\n      <td>2017-11-06 14:35:08</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>6</td>\n      <td>14</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 78 columns</p>\n</div>\n\n\n\n\n```python\ncovsp = {}\nfor c in covs:\n    sub_df = X_train[[c, 'is_attributed']]\n    covsp[c] = sub_df[c].cov(sub_df.is_attributed)\ncovsp\n```\n\n\n\n\n    {'future_app_clicks': -0.030995220328220385,\n     'future_identical_clicks': -0.004277924923924924,\n     'prev_app_clicks': -0.030175219508219452,\n     'prev_identical_clicks': -0.0035849242309242235}\n\n\n\n\n```python\n# histogram of covariance of each new column\nplt.bar(covsp.keys(), covsp.values())\nplt.xticks(rotation=90)\n```\n\n\n```python\ncorrsp = {}\nfor c in corrs:\n    sub_df = X_train[[c, 'is_attributed']]\n    corrsp[c] = sub_df[c].cov(sub_df.is_attributed)\ncorrsp\n```\n\n\n\n\n    {'future_app_clicks': -0.030995220328220385,\n     'future_identical_clicks': -0.004277924923924924,\n     'prev_app_clicks': -0.030175219508219452,\n     'prev_identical_clicks': -0.0035849242309242235}\n\n\n\n\n```python\n# histogram of correlation of each column\nplt.bar(corrsp.keys(), corrsp.values())\nplt.xticks(rotation=90)\n```\n\n# 3. Evaluating Feature Importance\nHaving created heaps of features, I'll fit xgBoost to the data, and evaluate the feature importances. First split into X and y\n\n\n```python\nimport xgboost as xgb\n\n# Split into X and y\ny = X_train['is_attributed']\nX = X_train.drop('is_attributed', axis=1).select_dtypes(include=[np.number])\n\n# Create a model\n# Params from: https://www.kaggle.com/aharless/swetha-s-xgboost-revised\nclf_xgBoost = xgb.XGBClassifier(\n    max_depth = 4,\n    subsample = 0.8,\n    colsample_bytree = 0.7,\n    colsample_bylevel = 0.7,\n    scale_pos_weight = 9,\n    min_child_weight = 0,\n    reg_alpha = 4,\n    n_jobs = 4, \n    objective = 'binary:logistic'\n)\n# Fit the models\nclf_xgBoost.fit(X, y)\n```\n\n\n\n\n    XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=0.7,\n           colsample_bytree=0.7, gamma=0, learning_rate=0.1, max_delta_step=0,\n           max_depth=4, min_child_weight=0, missing=None, n_estimators=100,\n           n_jobs=4, nthread=None, objective='binary:logistic', random_state=0,\n           reg_alpha=4, reg_lambda=1, scale_pos_weight=9, seed=None,\n           silent=True, subsample=0.8)\n\n\n\nThe feature importances are MinMax scaled, put into a DataFrame, and finally plotted ordered by the mean feature importance.\n\n\n```python\nfrom sklearn import preprocessing\n\n# Get xgBoost importances\nimportance_dict = {}\nfor import_type in ['weight', 'gain', 'cover']:\n    importance_dict['xgBoost-'+import_type] = clf_xgBoost.get_booster().get_score(importance_type=import_type)\n    \n# MinMax scale all importances\nimportance_df = pd.DataFrame(importance_dict).fillna(0)\nimportance_df = pd.DataFrame(\n    preprocessing.MinMaxScaler().fit_transform(importance_df),\n    columns=importance_df.columns,\n    index=importance_df.index\n)\n\n# Create mean column\nimportance_df['mean'] = importance_df.mean(axis=1)\n\n# Plot the feature importances\nimportance_df.sort_values('mean').plot(kind='bar', figsize=(20, 7))\n```\n\nThe code in the document is licensed under the MIT License: https://opensource.org/licenses/MIT\n\nAll writing in the document is licensed bt The Creative Commons Attribution 3.0 https://creativecommons.org/licenses/by/3.0/us/.\n", "meta": {"hexsha": "fa9b6b1e07f16f33e0b8e6db085832e87da88a5e", "size": 402421, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Feature_creation_pre.ipynb", "max_stars_repo_name": "Yidi0221/TalkingData-Ad-Fraud-Detection", "max_stars_repo_head_hexsha": "e82c99df543599f03f04ff13fedc40e5ac3fd170", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Feature_creation_pre.ipynb", "max_issues_repo_name": "Yidi0221/TalkingData-Ad-Fraud-Detection", "max_issues_repo_head_hexsha": "e82c99df543599f03f04ff13fedc40e5ac3fd170", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Feature_creation_pre.ipynb", "max_forks_repo_name": "Yidi0221/TalkingData-Ad-Fraud-Detection", "max_forks_repo_head_hexsha": "e82c99df543599f03f04ff13fedc40e5ac3fd170", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 100.2793421381, "max_line_length": 73260, "alphanum_fraction": 0.7446579577, "converted": true, "num_tokens": 25808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3174262655876759, "lm_q2_score": 0.0566524201316231, "lm_q1q2_score": 0.017982966158885193}}
{"text": "<center>\n    \n</center>\n\n# Reading Files Python\n\nEstimated time needed: **40** minutes\n\n## Objectives\n\nAfter completing this lab you will be able to:\n\n-   Read text files using Python libraries\n\n\n<h2>Table of Contents</h2>\n<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n    <ul>\n        <li><a href=\"download\">Download Data</a></li>\n        <li><a href=\"read\">Reading Text Files</a></li>\n        <li><a href=\"better\">A Better Way to Open a File</a></li>\n    </ul>\n \n</div>\n\n<hr>\n\n\n<h2 id=\"download\">Download Data</h2>\n\n\n\n```python\nimport urllib.request\nurl = 'https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/labs/example1.txt'\nfilename = 'Example1.txt'\nurllib.request.urlretrieve(url, filename)\n```\n\n\n\n\n    ('Example1.txt', <http.client.HTTPMessage at 0x7fc204142c18>)\n\n\n\n\n```python\n# Download Example file\n\n!wget -O /resources/data/Example1.txt https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/labs/example1.txt\n```\n\n    --2021-01-29 11:39:14--  https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/labs/example1.txt\n    Resolving s3-api.us-geo.objectstorage.softlayer.net (s3-api.us-geo.objectstorage.softlayer.net)... 67.228.254.196\n    Connecting to s3-api.us-geo.objectstorage.softlayer.net (s3-api.us-geo.objectstorage.softlayer.net)|67.228.254.196|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 45 [text/plain]\n    Saving to: \u2018/resources/data/Example1.txt\u2019\n    \n    /resources/data/Exa 100%[===================>]      45  --.-KB/s    in 0s      \n    \n    2021-01-29 11:39:14 (11.6 MB/s) - \u2018/resources/data/Example1.txt\u2019 saved [45/45]\n    \n\n\n<hr>\n\n\n<h2 id=\"read\">Reading Text Files</h2>\n\n\nOne way to read or write a file in Python is to use the built-in <code>open</code> function. The <code>open</code> function provides a <b>File object</b> that contains the methods and attributes you need in order to read, save, and manipulate the file. In this notebook, we will only cover <b>.txt</b> files. The first parameter you need is the file path and the file name. An example is shown as follow:\n\n\n\n\n\n The mode argument is optional and the default value is <b>r</b>. In this notebook we only cover two modes: \n\n<ul>\n    <li><b>r</b> Read mode for reading files </li>\n    <li><b>w</b> Write mode for writing files</li>\n</ul>\n\n\nFor the next example, we will use the text file <b>Example1.txt</b>. The file is shown as follow:\n\n\n\n\n\n We read the file: \n\n\n\n```python\n# Read the Example1.txt\n\nexample1 = \"Example1.txt\"\nfile1 = open(example1, \"r\")\n```\n\n We can view the attributes of the file.\n\n\nThe name of the file:\n\n\n\n```python\n# Print the path of file\n\nfile1.name\n```\n\n\n\n\n    'Example1.txt'\n\n\n\n The mode the file object is in:\n\n\n\n```python\n# Print the mode of file, either 'r' or 'w'\n\nfile1.mode\n```\n\n\n\n\n    'r'\n\n\n\nWe can read the file and assign it to a variable :\n\n\n\n```python\n# Read the file\n\nFileContent = file1.read()\nFileContent\n```\n\n\n\n\n    'This is line 1 \\nThis is line 2\\nThis is line 3'\n\n\n\nThe <b>/n</b> means that there is a new line. \n\n\nWe can print the file: \n\n\n\n```python\n# Print the file with '\\n' as a new line\n\nprint(FileContent)\n```\n\n    This is line 1 \n    This is line 2\n    This is line 3\n\n\nThe file is of type string:\n\n\n\n```python\n# Type of file content\n\ntype(FileContent)\n```\n\n\n\n\n    str\n\n\n\nIt is very important that the file is closed in the end. This frees up resources and ensures consistency across different python versions.\n\n\n\n```python\n# Close file after finish\n\nfile1.close()\n```\n\n<hr>\n\n\n<h2 id=\"better\">A Better Way to Open a File</h2>\n\n\nUsing the <code>with</code> statement is better practice, it automatically closes the file even if the code encounters an exception. The code will run everything in the indent block then close the file object. \n\n\n\n```python\n# Open file using with\n\nwith open(example1, \"r\") as file1:\n    FileContent = file1.read()\n    print(FileContent)\n```\n\n    This is line 1 \n    This is line 2\n    This is line 3\n\n\nThe file object is closed, you can verify it by running the following cell:  \n\n\n\n```python\n# Verify if the file is closed\n\nfile1.closed\n```\n\n\n\n\n    True\n\n\n\n We can see the info in the file:\n\n\n\n```python\n# See the content of file\n\nprint(FileContent)\n```\n\n    This is line 1 \n    This is line 2\n    This is line 3\n\n\nThe syntax is a little confusing as the file object is after the <code>as</code> statement. We also don\u2019t explicitly close the file. Therefore we summarize the steps in a figure:\n\n\n\n\n\nWe don\u2019t have to read the entire file, for example, we can read the first 4 characters by entering three as a parameter to the method **.read()**:\n\n\n\n```python\n# Read first four characters\n\nwith open(example1, \"r\") as file1:\n    print(file1.read(4))\n```\n\n    This\n\n\nOnce the method <code>.read(4)</code> is called the first 4 characters are called. If we call the method again, the next 4 characters are called. The output for the following cell will demonstrate the process for different inputs to the method <code>read()</code>:\n\n\n\n```python\n# Read certain amount of characters\n\nwith open(example1, \"r\") as file1:\n    print(file1.read(4))\n    print(file1.read(4))\n    print(file1.read(7))\n    print(file1.read(15))\n```\n\n    This\n     is \n    line 1 \n    \n    This is line 2\n\n\nThe process is illustrated in the below figure, and each color represents the part of the file read after the method <code>read()</code> is called:\n\n\n\n\n\n Here is an example using the same file, but instead we read 16, 5, and then 9 characters at a time: \n\n\n\n```python\n# Read certain amount of characters\n\nwith open(example1, \"r\") as file1:\n    print(file1.read(16))\n    print(file1.read(5))\n    print(file1.read(9))\n```\n\n    This is line 1 \n    \n    This \n    is line 2\n\n\nWe can also read one line of the file at a time using the method <code>readline()</code>: \n\n\n\n```python\n# Read one line\n\nwith open(example1, \"r\") as file1:\n    print(\"first line: \" + file1.readline())\n```\n\n    first line: This is line 1 \n    \n\n\nWe can also pass an argument to <code> readline() </code> to specify the number of charecters we want to read. However, unlike <code> read()</code>, <code> readline()</code> can only read one line at most.\n\n\n\n```python\nwith open(example1, \"r\") as file1:\n    print(file1.readline(20)) # does not read past the end of line\n    print(file1.read(20)) # Returns the next 20 chars\n\n```\n\n    This is line 1 \n    \n    This is line 2\n    This \n\n\n We can use a loop to iterate through each line: \n\n\n\n```python\n# Iterate through the lines\n\nwith open(example1,\"r\") as file1:\n        i = 0;\n        for line in file1:\n            print(\"Iteration\", str(i), \": \", line)\n            i = i + 1\n```\n\n    Iteration 0 :  This is line 1 \n    \n    Iteration 1 :  This is line 2\n    \n    Iteration 2 :  This is line 3\n\n\nWe can use the method <code>readlines()</code> to save the text file to a list: \n\n\n\n```python\n# Read all lines and save as a list\n\nwith open(example1, \"r\") as file1:\n    FileasList = file1.readlines()\n```\n\n Each element of the list corresponds to a line of text:\n\n\n\n```python\n# Print the first line\n\nFileasList[0]\n```\n\n\n\n\n    'This is line 1 \\n'\n\n\n\n# Print the second line\n\nFileasList[1]\n\n\n\n```python\n# Print the third line\n\nFileasList[2]\n```\n\n\n\n\n    'This is line 3'\n\n\n\n<hr>\n\n\n<h2> Exercise </h2>\n\n\n<h4>Weather Data</h4>\n\n\nYour friend, a rising star in the field of meterology, has called on you to write a script to perform some analysis on weather station data. Given below is a file \"resources/ex4.csv\", which contains some precipiation data for the month of June.\nEach line in the file has the format - Date,Precipation (upto two decimal places). Note how the data is seperated using ','. The first row of the file contains headers and should be ignored.\n\nYour task is to complete the <code>getNAvg</code> function that computes a simple moving average for N days for the precipiation data, where N is a parameter. Your function should return a list of moving averages for the given data. \n\nThe formula for a k day moving average over a series - $n_{0},n_{1},n_{2},n_{3}....n_{m}$is:\n\\begin{align}\nM_{i} = M_{i-1} + \\frac{n_{i} - n_{i-k}}{k}, \\text{for i = k to m }\n\\\\ \\text{where $M_{i}$ is the moving average}\n\\end{align}\nThe skeleton code has been provided below. Edit only the required function.\n\n\n<details><summary>Click here for the solution</summary>\n\n```python\n- Each line of the file has a '\\n' char which should be removed\n- The lines in the file are read as strings and need to be typecasted to floats\n- For a k day moving average, The data points for the last k days must be known\n    \n```\n\n</details>\n\n\n\n```python\n##Download the file \n\n!wget https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%204/ex4.csv\n```\n\n    --2021-01-29 12:15:18--  https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%204/ex4.csv\n    Resolving cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud (cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud)... 169.63.118.104\n    Connecting to cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud (cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud)|169.63.118.104|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 718 [text/csv]\n    Saving to: \u2018ex4.csv\u2019\n    \n    ex4.csv             100%[===================>]     718  --.-KB/s    in 0.001s  \n    \n    2021-01-29 12:15:18 (999 KB/s) - \u2018ex4.csv\u2019 saved [718/718]\n    \n\n\n\n```python\nimport matplotlib.pyplot as plt\n\nstatData =\"ex4.csv\"\n\ndef getNAvg(file,N):\n    \n    row = 0 # keep track of rows\n    lastN = [] # keep track of last N points\n    mean = [0] # running avg\n\n\n    with open(file,\"r\") as rawData: \n        for line in rawData:\n            if (row == 0): # Ignore the headers\n                row = row + 1\n                continue\n\n            line = line.strip('\\n')\n            lineData = float(line.split(',')[1])\n\n            if (row<=N): \n                lastN.append(lineData)\n                mean[0] = (lineData + mean[0]*(row-1))/row\n            else:\n                mean.append( mean[row - N -1]+ (lineData - lastN[0])/N)\n                lastN = lastN[1:]\n                lastN.append(lineData)\n\n            row = row +1            \n        return mean\n\n    pass\n                    \ndef plotData(mean,N):\n        \n    mean = [round(x,3) for x in mean]\n    plt.plot(mean,label=str(N) + ' day average')\n    plt.xlabel('Day')\n    plt.ylabel('Precipiation')\n    plt.legend()\n\n\n\n\n```\n\n#### Once you have finished, you can you use the block below to plot your data\n\n\n\n```python\nplotData(getNAvg(statData,1),1)\nplotData ([0 for x in range(1,5)]+ getNAvg(statData,5),5 )\nplotData([0 for x in range(1,7)] + getNAvg(statData,7),7)\n```\n\nYou can use the code below to verify your progress -\n\n\n\n```python\navg5 =[4.18,4.78,4.34,4.72,5.48,5.84,6.84,6.76,6.74,5.46,4.18,2.74,2.52,2.02,2.16,2.82,2.92,4.36,4.74,5.12,5.34,6.4,6.56,6.1,5.74,5.62,4.26]\navg7 =[4.043,4.757,5.071,5.629,6.343,5.886,6.157,5.871,5.243,4.386,3.514,2.714,2.586,2.443,2.571,3.643,4.143,4.443,4.814,5.6,6.314,6.414,5.429,5.443,4.986]\n\ndef testMsg(passed):\n    if passed:\n       return 'Test Passed'\n    else :\n       return ' Test Failed'\n\nprint(\"getNAvg : \")\ntry:\n    sol5 = getNAvg(statData,5)\n    sol7 = getNAvg(statData,7)\n    \n    if(len(sol5)==len( avg5) and (len(sol7)==len(avg7))):\n        err5 = sum([abs(avg5[index] - sol5[index])for index in range(len(avg5))])\n        err7 = sum([abs(avg7[index] - sol7[index])for index in range(len(avg7))])\n        print(testMsg((err5 < 1) and (err7 <1)))\n        \n    else:\n        print(testMsg(False))\nexcept NameError as e: \n    print('Error! Code: {c}, Message: {m}'.format(c = type(e).__name__, m = str(e)))\nexcept:\n    print(\"An error occured. Recheck your function\")\n\n\n```\n\n<details><summary>Click here for the solution</summary>\n\n```python\nimport matplotlib.pyplot as plt\n\nstatData =\"ex4.csv\"\n\ndef getNAvg(file,N):\n    \"\"\"\n    file - File containting all the raw weather station data\n    N - The number of days to compute the moving average over\n    \n    Return a list of containg the moving average of all data points\n    \"\"\"\n    row = 0 # keep track of rows\n    lastN = [] # keep track of last N points\n    mean = [0] # running avg\n    \n    \n    with open(file,\"r\") as rawData: \n        for line in rawData:\n            if (row == 0): # Ignore the headers\n                row = row + 1\n                continue\n            \n            line = line.strip('\\n')\n            lineData = float(line.split(',')[1])\n            \n            if (row<=N): \n                lastN.append(lineData)\n                mean[0] = (lineData + mean[0]*(row-1))/row\n            else:\n                mean.append( mean[row - N -1]+ (lineData - lastN[0])/N)\n                lastN = lastN[1:]\n                lastN.append(lineData)\n            \n            row = row +1            \n        return mean\n                    \ndef plotData(mean,N):\n        \"\"\" Plots running averages \"\"\"\n        mean = [round(x,3) for x in mean]\n        plt.plot(mean,label=str(N) + ' day average')\n        plt.xlabel('Day')\n        plt.ylabel('Precipiation')\n        plt.legend()\n       \n\n        \nplotData(getNAvg(statData,1),1)\nplotData ([0 for x in range(1,5)]+ getNAvg(statData,5),5 )\nplotData([0 for x in range(1,7)] + getNAvg(statData,7),7)\n\n    \n```\n\n</details>\n\n\n<div class=\"alert alert-success\">\n    Note: Files with sets of data seperated using ',' or other charecters are called '.csv' files.\n    They are a very common way to store data. Usually when dealing with them, An external library is used that does the nitpicky tasks for you. In fact, There are numerous libraries for statistical functions to. You will learn about such libraries later in the course. \n</div>\n\n\n<hr>\n<h2>The last exercise!</h2>\n<p>Congratulations, you have completed your first lesson and hands-on lab in Python. However, there is one more thing you need to do. The Data Science community encourages sharing work. The best way to share and showcase your work is to share it on GitHub. By sharing your notebook on GitHub you are not only building your reputation with fellow data scientists, but you can also show it off when applying for a job. Even though this was your first piece of work, it is never too early to start building good habits. So, please read and follow <a href=\"https://cognitiveclass.ai/blog/data-scientists-stand-out-by-sharing-your-notebooks/\" target=\"_blank\">this article</a> to learn how to share your work.\n<hr>\n\n\n## Author\n\n<a href=\"https://www.linkedin.com/in/joseph-s-50398b136/\" target=\"_blank\">Joseph Santarcangelo</a>\n\n## Other contributors\n\n<a href=\"www.linkedin.com/in/jiahui-mavis-zhou-a4537814a\">Mavis Zhou</a>\n\n## Change Log\n\n| Date (YYYY-MM-DD) | Version | Changed By    | Change Description                                        |\n| ----------------- | ------- | ------------- | --------------------------------------------------------- |\n| 2020-09-30        | 1.2     | Malika Singla | Weather Data dataset link added                           |\n| 2020-09-30        | 1.1     | Arjun Swani   | Added exericse \"Weather Data\"                             |\n| 2020-09-30        | 1.0     | Arjun Swani   | Added blurbs about closing files and read() vs readline() |\n| 2020-08-26        | 0.2     | Lavanya       | Moved lab to course repo in GitLab                        |\n|                   |         |               |                                                           |\n|                   |         |               |                                                           |\n\n<hr/>\n\n## <h3 align=\"center\"> \u00a9 IBM Corporation 2020. All rights reserved. <h3/>\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "09aa4b9f80502f9e24c70883ff547cd81e43415c", "size": 66654, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "material/PY0101EN-4-1-ReadFile.ipynb", "max_stars_repo_name": "sergiodealencar/courses", "max_stars_repo_head_hexsha": "c9d86b27b0185cc82624b01ed76653dbc12554a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "material/PY0101EN-4-1-ReadFile.ipynb", "max_issues_repo_name": "sergiodealencar/courses", "max_issues_repo_head_hexsha": "c9d86b27b0185cc82624b01ed76653dbc12554a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "material/PY0101EN-4-1-ReadFile.ipynb", "max_forks_repo_name": "sergiodealencar/courses", "max_forks_repo_head_hexsha": "c9d86b27b0185cc82624b01ed76653dbc12554a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.3192272309, "max_line_length": 37648, "alphanum_fraction": 0.7648003121, "converted": true, "num_tokens": 4361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10970577969958142, "lm_q2_score": 0.16238004274695514, "lm_q1q2_score": 0.017814029197206076}}
{"text": "##### Copyright 2018 The TF-Agents Authors.\n\n\n```\n#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# Introduction to RL and Deep Q Networks\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n  <td>\n    <a target=\"_blank\" href=\"https://www.tensorflow.org/agents/tutorials/0_intro_rl\">\n    \n    View on TensorFlow.org</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/agents/blob/master/docs/tutorials/0_intro_rl.ipynb\">\n    \n    Run in Google Colab</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://github.com/tensorflow/agents/blob/master/docs/tutorials/0_intro_rl.ipynb\">\n    \n    View source on GitHub</a>\n  </td>\n  <td>\n    <a href=\"https://storage.googleapis.com/tensorflow_docs/agents/docs/tutorials/0_intro_rl.ipynb\">Download notebook</a>\n  </td>\n</table>\n\n## Introduction\n\nReinforcement learning (RL) is a general framework where agents learn to perform actions in an environment so as to maximize a reward. The two main components are the environment, which represents the problem to be solved, and the agent, which represents the learning algorithm.\n\nThe agent and environment continuously interact with each other. At each time step, the agent takes an action on the environment based on its *policy* $\\pi(a_t|s_t)$, where $s_t$ is the current observation from the environment, and receives a reward $r_{t+1}$ and the next observation $s_{t+1}$ from the environment. The goal is to improve the policy so as to maximize the sum of rewards (return).\n\nNote: It is important to distinguish between the `state` of the environment and the `observation`, which is the part of the environment `state` that the agent can see, e.g. in a poker game, the environment state consists of the cards belonging to all the players and the community cards, but the agent can observe only its own cards and a few community cards. In most literature, these terms are used interchangeably and observation is also denoted as $s$.\n\n\n\nThis is a very general framework and can model a variety of sequential decision making problems such as games, robotics etc. \n\n\n## The Cartpole Environment\n\nThe Cartpole environment is one of the most well known classic reinforcement learning problems ( the *\"Hello, World!\"* of RL). A pole is attached to a cart, which can move along a frictionless track. The pole starts upright and the goal is to prevent it from falling over by controlling the cart.  \n\n*   The observation from the environment $s_t$ is a 4D vector representing the position and velocity of the cart, and the angle and angular velocity of the pole. \n*   The agent can control the system by taking one of 2 actions $a_t$: push the cart right (+1) or left (-1). \n*   A reward $r_{t+1} = 1$ is provided for every timestep that the pole remains upright. The episode ends when one of the following is true:\n  * the pole tips over some angle limit\n  * the cart moves outside of the world edges\n  * 200 time steps pass. \n\nThe goal of the agent is to learn a policy $\\pi(a_t|s_t)$ so as to maximize the sum of rewards in an episode $\\sum_{t=0}^{T} \\gamma^t r_t$. Here $\\gamma$ is a discount factor in $[0, 1]$ that discounts future rewards relative to immediate rewards. This parameter helps us focus the policy, making it care more about obtaining rewards quickly.\n\n\n## The DQN Agent\n\nThe  [DQN (Deep Q-Network) algorithm](https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf) was developed by DeepMind in 2015. It was able to solve a wide range of Atari games (some to superhuman level) by combining reinforcement learning and deep neural networks at scale. The algorithm was developed by enhancing a classic RL algorithm called Q-Learning with deep neural networks and a technique called *experience replay*.\n\n### Q-Learning\n\nQ-Learning is based on the notion of a Q-function. The Q-function (a.k.a the state-action value function) of a policy $\\pi$, $Q^{\\pi}(s, a)$, measures the expected return or discounted sum of rewards obtained from state $s$ by taking action $a$ first and following policy $\\pi$ thereafter. We define the optimal Q-function $Q^*(s, a)$ as the maximum return that can be obtained starting from observation $s$, taking action $a$ and following the optimal policy thereafter. The optimal Q-function obeys the following *Bellman* optimality equation: \n\n$\\begin{equation}Q^\\ast(s, a) = \\mathbb{E}[ r + \\gamma \\max_{a'} Q^\\ast(s', a') ]\\end{equation}$\n\nThis means that the maximum return from state $s$ and action $a$ is the sum of the immediate reward $r$ and the return (discounted by $\\gamma$) obtained by following the optimal policy therafter until the end of the episode (i.e., the maximum reward from the next state $s'$). The expectation is computed both over the distribution of immediate rewards $r$ and possible next states $s'$.\n\nThe basic idea behind Q-Learning is to use the Bellman optimality equation as an iterative update $Q_{i+1}(s, a) \\leftarrow \\mathbb{E}\\left[ r + \\gamma \\max_{a'} Q_{i}(s', a')\\right]$, and it can be shown that this converges to the optimal $Q$-function, i.e. $Q_i \\rightarrow Q^*$ as $i \\rightarrow \\infty$ (see the [DQN paper](https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf)).\n\n\n### Deep Q-Learning\n\nFor most problems, it is impractical to represent the $Q$-function as a table containing values for each combination of $s$ and $a$. Instead, we train a function approximator, such as a neural network with parameters $\\theta$, to estimate the Q-values, i.e. $Q(s, a; \\theta) \\approx Q^*(s, a)$. This can done by minimizing the following loss at each step $i$:\n\n$\\begin{equation}L_i(\\theta_i) = \\mathbb{E}_{s, a, r, s'\\sim \\rho(.)} \\left[ (y_i - Q(s, a; \\theta_i))^2 \\right]\\end{equation}$ where $y_i = r +  \\gamma \\max_{a'} Q(s', a'; \\theta_{i-1})$\n\nHere, $y_i$ is called the TD (temporal difference) target, and $y_i - Q$ is called the TD error. $\\rho$ represents the behaviour distribution, the distribution over transitions $\\{s, a, r, s'\\}$ collected from the environment. \n\nNote that the parameters from the previous iteration $\\theta_{i-1}$ are fixed and not updated. In practice we use a snapshot of the network parameters from a few iterations ago instead of the last iteration. This copy is called the *target network*.\n\nQ-Learning is an *off-policy* algorithm that learns about the greedy policy $a = \\max_{a} Q(s, a; \\theta)$ while using a different behaviour policy for acting in the environment/collecting data. This behaviour policy is usually an $\\epsilon$-greedy policy that selects the greedy action with probability $1-\\epsilon$ and a random action with probability $\\epsilon$ to ensure good coverage of the state-action space.\n\n### Experience Replay\n\nTo avoid computing the full expectation in the DQN loss, we can minimize it using stochastic gradient descent. If the loss is computed using just the last transition $\\{s, a, r, s'\\}$, this reduces to standard Q-Learning. \n\nThe Atari DQN work introduced a technique called Experience Replay to make the network updates more stable. At each time step of data collection, the transitions are added to a circular buffer called the *replay buffer*. Then during training, instead of using just the latest transition to compute the loss and its gradient, we compute them using a mini-batch of transitions sampled from the replay buffer. This has two advantages: better data efficiency by reusing each transition in many updates, and better stability using uncorrelated transitions in a batch.\n\n\n## DQN on Cartpole in TF-Agents\n\nTF-Agents provides all the components necessary to train a DQN agent, such as the agent itself, the environment, policies, networks, replay buffers, data collection loops, and metrics. These components are implemented as Python functions or TensorFlow graph ops, and we also have wrappers for converting between them. Additionally, TF-Agents supports TensorFlow 2.0 mode, which enables us to use TF in imperative mode. \n\nNext, take a look at the [tutorial for training a DQN agent on the Cartpole environment using TF-Agents](https://github.com/tensorflow/agents/blob/master/docs/tutorials/1_dqn_tutorial.ipynb).\n\n", "meta": {"hexsha": "ec3b4105def252ec71c1ba62a405c8faadf6333e", "size": 11480, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "site/en-snapshot/agents/tutorials/0_intro_rl.ipynb", "max_stars_repo_name": "sti320a/docs-l10n", "max_stars_repo_head_hexsha": "98f6ccaed5944b290a18a39246fb322b858d578f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-29T07:31:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-13T08:16:18.000Z", "max_issues_repo_path": "site/en-snapshot/agents/tutorials/0_intro_rl.ipynb", "max_issues_repo_name": "sti320a/docs-l10n", "max_issues_repo_head_hexsha": "98f6ccaed5944b290a18a39246fb322b858d578f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "site/en-snapshot/agents/tutorials/0_intro_rl.ipynb", "max_forks_repo_name": "sti320a/docs-l10n", "max_forks_repo_head_hexsha": "98f6ccaed5944b290a18a39246fb322b858d578f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 67.134502924, "max_line_length": 574, "alphanum_fraction": 0.6383275261, "converted": true, "num_tokens": 2103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.056652419733442295, "lm_q1q2_score": 0.01779172329239218}}
{"text": "```\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```\ncurrent_path = '/content/drive/My Drive/Colab Notebooks/Project_GANder/gankook_cuda/semantic-segmentation-pytorch/pytorch_room_layout/'\n\nimport os\nos.chdir(current_path)\n!ls\n```\n\n     build\t\t        info.json\t        segment_st.py\n     cv2_requirements.txt   lsun.pth.tar\t       'sunrgbd (1).zip'\n     datasets\t        lu_vp_detect.egg-info   sunrgbd.pth.tar\n     data_transforms.py     pics\t\t        test_result\n     dist\t\t        __pycache__\t        Vanish_Point_Detection\n     drn_d_105_024_val      README.md\t        visualize.m\n     drn_d_105_024_val_ms   requirements.txt        XiaohuLuVPDetection\n     drn.py\t\t        segment_lsun.py\n     features\t        segment_rl.py\n\n\n### Get Vanishing point, inliers\n\n\n```\n# !python XiaohuLuVPDetection/setup.py build\n# !python XiaohuLuVPDetection/setup.py install\n!pip install -r cv2_requirements.txt\n```\n\n    Collecting opencv-python==4.0.0.21\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/37/49/874d119948a5a084a7ebe98308214098ef3471d76ab74200f9800efeef15/opencv_python-4.0.0.21-cp36-cp36m-manylinux1_x86_64.whl (25.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 25.4MB 1.6MB/s \n    \u001b[?25hCollecting opencv-contrib-python==4.0.0.21\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1f/c0/0463d91f297521b2e15e3d682d7077557fe773db72a03a0d2dba899ab8a5/opencv_contrib_python-4.0.0.21-cp36-cp36m-manylinux1_x86_64.whl (31.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 31.2MB 184kB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.11.3 in /usr/local/lib/python3.6/dist-packages (from opencv-python==4.0.0.21->-r cv2_requirements.txt (line 1)) (1.18.5)\n    \u001b[31mERROR: albumentations 0.1.12 has requirement imgaug<0.2.7,>=0.2.5, but you'll have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Installing collected packages: opencv-python, opencv-contrib-python\n      Found existing installation: opencv-python 4.1.2.30\n        Uninstalling opencv-python-4.1.2.30:\n          Successfully uninstalled opencv-python-4.1.2.30\n      Found existing installation: opencv-contrib-python 4.1.2.30\n        Uninstalling opencv-contrib-python-4.1.2.30:\n          Successfully uninstalled opencv-contrib-python-4.1.2.30\n    Successfully installed opencv-contrib-python-4.0.0.21 opencv-python-4.0.0.21\n\n\n\n```\nimport cv2\ncv2.__version__\n```\n\n\n\n\n    '4.0.0'\n\n\n\n### Functions\n\n\n```\nfrom PIL import Image\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom XiaohuLuVPDetection.lu_vp_detect.vp_detection import VPDetection\nimport time\n# import os\nimport cv2\n# import pylab as pl\nfrom skimage import morphology as mp\nimport sys\n```\n\n\n```\n#             Detect Intersection             #\nimport math\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler\nfrom sklearn.cluster import KMeans\nfrom sympy import Line\nfrom sympy.geometry import Ray\n\n\ndef drawLines(img, lines, color=(255,255,255)):\n    \"\"\"\n    Draw lines on an image\n    \"\"\"\n    for line in lines:\n        for rho,theta in line:\n          a = np.cos(theta)\n          b = np.sin(theta)\n          x0 = a*rho\n          y0 = b*rho\n          x1 = int(x0 + 1000*(-b))\n          y1 = int(y0 + 1000*(a))\n          x2 = int(x0 - 1000*(-b))\n          y2 = int(y0 - 1000*(a))\n\n          slope = (y1 - y0) / float(x1 - x0)\n          angle = math.degrees(math.atan(slope))\n          # if abs(angle) < 70:\n          cv2.line(img, (x1,y1), (x2,y2), color, 1)\n\ndef line(p1, p2):\n    A = (p1[1] - p2[1])\n    B = (p2[0] - p1[0])\n    C = (p1[0]*p2[1] - p2[0]*p1[1])\n    return A, B, -C\n\ndef intersection2(L1, L2):\n    D  = L1[0] * L2[1] - L1[1] * L2[0]\n    Dx = L1[2] * L2[1] - L1[1] * L2[2]\n    Dy = L1[0] * L2[2] - L1[2] * L2[0]\n    if D != 0:\n        x = Dx / D\n        y = Dy / D\n        return x,y\n    else:\n        return False\n\n\ndef regression(img, x, y, color=(255, 0, 0), axis=1):\n\n  if axis == 1:\n    y_at_border = np.array([0, img.shape[0]])\n    p = np.polyfit(y, x, deg=1)\n    x_at_border = np.poly1d(p)(y_at_border)\n  else:\n    x_at_border = np.array([0, img.shape[1]])\n    p = np.polyfit(x, y, deg=1)\n    y_at_border = np.poly1d(p)(x_at_border)\n\n  cv2.line(img, (int(x_at_border[0]), int(y_at_border[0])), (int(x_at_border[1]), int(y_at_border[1])), color, 2)\n\n  return x_at_border, y_at_border\n\n\ndef find_reg_points(img, lines, color=(255,0,0), drawlines=False):\n\n  centroids = list()\n  r_xs = list()\n  r_ys = list()\n  for line_ in lines:\n      for rho,theta in line_:\n          a = np.cos(theta)\n          b = np.sin(theta)\n          x0 = a*rho\n          y0 = b*rho\n          x1 = int(x0 + 1000*(-b))\n          y1 = int(y0 + 1000*(a))\n          x2 = int(x0 - 1000*(-b))\n          y2 = int(y0 - 1000*(a))\n\n          slope = (y1 - y0) / float(x1 - x0)\n          angle = math.degrees(math.atan(slope))\n          if abs(angle) > 80:\n            # print(img.shape[1])\n            h_layout = line((0, 0), (img.shape[1], 0))\n            h_layout_lower = line((0, img.shape[0]), (img.shape[1], img.shape[0]))\n            r = intersection2(h_layout, line((x1, y1), (x2, y2)))\n            r_lower = intersection2(h_layout_lower, line((x1, y1), (x2, y2)))\n            # cv2.line(img, (int(x1), int(y1)), (int(x2), int(y2)), color, 2)\n\n            center_p = (int((r[0] + r_lower[0]) / 2), int((r[1] + r_lower[1])/ 2))\n            centroids.append(center_p)\n\n            r_xs.append((r[0], r_lower[0]))\n            r_ys.append((r[1], r_lower[1]))\n\n            if drawlines:\n              cv2.line(img, (int(r[0]), int(r[1])), (int(r_lower[0]), int(r_lower[1])), color, 2)\n              cv2.circle(img, center_p, 10, (255, 0, 255), -1)\n\n  if drawlines:\n    cv2.line(img, (int(0), int(0)), (int(0), int(img.shape[0])), color, 2)\n    cv2.line(img, (int(img.shape[1]), int(0)), (int(img.shape[1]), int(img.shape[0])), color, 2)\n    cv2.circle(img, (0, int(img.shape[0] / 2)), 10, (255, 0, 255), -1)\n    cv2.circle(img, (img.shape[1], int(img.shape[0] / 2)), 10, (255, 0, 255), -1)\n  centroids.append((0, int(img.shape[0] / 2)))\n  centroids.append((img.shape[1], int(img.shape[0] / 2)))\n\n  return r_xs, r_ys, centroids   \n\nfrom scipy.spatial import distance as sci_dist\n\ndef order_points(pts):\n\n  xSorted = pts[np.argsort(pts[:, 0]), :]\n  leftMost = xSorted[:2, :]\n  rightMost = xSorted[2:, :]\n  leftMost = leftMost[np.argsort(leftMost[:, 1]), :]\n  (tl, bl) = leftMost\n  D = sci_dist.cdist(tl[np.newaxis], rightMost, \"euclidean\")[0]\n  (br, tr) = rightMost[np.argsort(D)[::-1], :]\n\n  return np.array([tl, tr, br, bl], dtype=\"float32\")\n\n\ndef get_vline_points_inborder(vpd, img, show_vline=False):\n\n  vpd.find_vps(img)\n  # vps = vpd.vps_2D\n  vl_img, vl_list = vpd.create_debug_VP_image(show_vl=True)\n\n\n  vl_list_for_vline = vl_list\n  vl_img_for_vline = vl_img.copy()\n\n  # print('#       Used vl_list for vline work       #')\n  # print('vl_list')\n  # print()\n\n  #           Extract Vertical line            #\n  h_border = Line((0, 0), (img.shape[1], 0))\n  h_border_lower = Line((0, img.shape[0]), (img.shape[1], img.shape[0]))\n\n  reg_xs = list()\n  reg_ys = list()\n  v_lines = list()\n  # h_lines_xrange = list()\n  for vl in vl_list_for_vline:\n      x0, y0, x1, y1 = vl\n      slope = (y1 - y0) / float(x1 - x0)\n      angle = math.degrees(math.atan(slope))\n      # print(angle)\n      if abs(angle) > 80:\n        # cv2.line(skl_copy, (int(x1), int(y1)), (int(x0), int(y0)), (255, 0, 0), 3,\n        #                  cv2.LINE_AA)\n        v_line = Line((x0, y0), (x1, y1))\n        [top_point] = v_line.intersection(h_border)\n        [bot_point] = v_line.intersection(h_border_lower)\n        # v_lines.append()\n        reg_xs.append((float(top_point[0]), float(bot_point[0])))\n        reg_ys.append((float(top_point[1]), float(bot_point[1])))\n\n      # if abs(angle) < 70:\n      #   h_lines_xrange.append((min(x0, x1), max(x0, x1)))\n\n\n  # print('#        Before Sorting      #')\n  # print('reg_xs :', reg_xs)\n  \n  \n  center_xs = list()\n  for reg_x, reg_y in zip(reg_xs, reg_ys):\n    center_xs.append(np.mean(reg_x))\n    #           Draw Line         #\n    regression(vl_img_for_vline, reg_x, reg_y)\n    \n  if show_vline:\n    plt.imshow(vl_img_for_vline)\n    plt.title('Divided Session')\n    plt.show()\n\n  sorted_index = list()\n  sorted_center_xs = sorted(center_xs)\n\n  for center_x in sorted_center_xs:\n    # print('center_x :', center_x)\n    sorted_index.append(center_xs.index(center_x))\n  print('sorted_index :', sorted_index)   #\n\n  sorted_reg_xs = list()\n  sorted_reg_ys = list()\n  for s_index in sorted_index:\n    sorted_reg_xs.append(reg_xs[s_index])\n    sorted_reg_ys.append(reg_ys[s_index])\n  reg_xs = sorted_reg_xs\n  reg_ys = sorted_reg_ys\n\n  print()\n  # print(\"#        After Sorting       #\")\n  # print('reg_xs :', reg_xs)\n  # print()\n\n  return reg_xs\n\n\ndef remove_outlier_angle(vl_list, copy_vl_list, angle_list, limit_angle=15):\n\n    if len(vl_list) != 0:\n      copy_angle_list = angle_list.copy()\n      mean_angle_list = np.array(angle_list).mean()\n      # print('mean_angle_list :', mean_angle_list)\n      # print('angle_list :', angle_list)\n      print('max angle_list gap : ', max(angle_list) - mean_angle_list)\n\n      for angle_index, angle in enumerate(copy_angle_list):\n        if abs(angle - mean_angle_list) > limit_angle:\n          vl_list.remove(copy_vl_list[angle_index])\n          # angle_list.remove(copy_angle_list[angle_index])\n\n      return\n\ndef get_hline_points_inborder(img, left_border, right_border, vl_list, top_vl, bot_vl, top_down_ratio=0.66):\n\n  ex_top_vl = list()\n  ex_bot_vl = list()\n\n  for vl in vl_list:\n\n    x0, y0, x1, y1 = vl\n    l1 = Line((x0, y0), (x1, y1))\n    #     v_border line     #\n    [left_point] = l1.intersection(left_border)\n    # print('left_point :', left_point)\n    [right_point] = l1.intersection(right_border)\n\n    #      Figure out current vl is top / bottom vl     #\n    if vl in top_vl:\n      if (left_point[1] < img.shape[0] * top_down_ratio and right_point[1] < img.shape[0] * top_down_ratio):\n          ex_top_vl.append((left_point[0], left_point[1], right_point[0], right_point[1]))\n\n    elif vl in bot_vl:\n      if (left_point[1] > img.shape[0] * (1 - top_down_ratio) and right_point[1] > img.shape[0] * (1 - top_down_ratio)):\n          ex_bot_vl.append((left_point[0], left_point[1], right_point[0], right_point[1]))\n\n  return ex_top_vl, ex_bot_vl\n\n\ndef toppest_bottest_vl(img, top_vl, bot_vl, direction):\n\n    max_y = 0\n    min_y = img.shape[0]\n    toppest_vl = None\n    bottest_vl = None\n    index = 1 if direction == 'right' else 3\n\n    for vl in top_vl:\n      if vl[index] < min_y:\n        toppest_vl = vl\n        min_y = vl[index]\n\n    for vl in bot_vl:\n      if vl[index] > max_y:\n        bottest_vl = vl\n        max_y = vl[index]\n\n    return toppest_vl, bottest_vl\n\n\ndef line_mirroring(src_vl, src_point, left_border, right_border):\n\n    x0, y0, x1, y1 = src_vl\n    slope = (y1 - y0) / float(x1 - x0)\n    angle = - math.degrees(math.atan(slope))\n\n    #       white_max_y \ub97c - toppest_vl angle \ub85c \uc9c0\ub098\ub294 \uc9c1\uc120      #\n    print('src_point :', src_point)\n    print('angle :', angle)\n    endy = 100 * math.sin(math.radians(angle))\n    endx = 100 * math.cos(math.radians(angle))\n    temp_vl = Line(src_point, (src_point[0] + endx, src_point[1] + endy))\n    [left_point] = temp_vl.intersection(left_border)\n    [right_point] = temp_vl.intersection(right_border)\n    # print('left_point :', left_point)\n    mirrored_vl = (float(left_point[0]), float(left_point[1]), float(right_point[0]), float(right_point[1]))\n\n    return mirrored_vl\n\n\ndef choose_4points(toppest_vl, bottest_vl, src_point, left_border, right_border, parallel):\n\n  x1, y1, x0, y0 = toppest_vl\n  if parallel:\n    top_line = Line((x1, y1), (x0, y0))\n    print('top_line.slope :', float(top_line.slope))            \n    if abs(top_line.slope) < 0.05:\n        src_point = (0, 0)\n    parallel_tl = top_line.parallel_line(src_point)\n\n    [tl] = parallel_tl.intersection(left_border)\n    [tr] = parallel_tl.intersection(right_border)\n    br, bl = bottest_vl[2:], bottest_vl[:2]\n  else:\n    tl, tr, br, bl = toppest_vl[:2], toppest_vl[2:], bottest_vl[2:], bottest_vl[:2]\n\n  return tl, tr, br, bl\n\n\ndef top_bot_mask(mask_img, threshold=1/10):\n\n    top_white_cnt = 0\n    bot_white_cnt = 0\n    white_min_x = mask_img.shape[1]\n    white_max_x = 0\n    white_min_y = mask_img.shape[0]\n    white_max_y = 0\n    temp_min_y = white_min_y\n    temp_max_y = white_max_y\n    min_x_coord, max_x_coord, min_y_coord, max_y_coord = None, None, None, None\n    top_parallel = False\n    bot_parallel = False\n    for i in range(mask_img.shape[1]):\n\n      #     Check Top Condition     #\n      for j in range(int(mask_img.shape[0] * threshold)):\n        # if mask_img[j][i] == 255 and j < thr_min_y:\n          # thr_min_y = j\n          # thr_min_y_coord = (i, j)\n        if mask_img[j][i] == 255:\n          top_white_cnt += 1\n          if i > white_max_x:\n            white_max_x = i\n            max_x_coord = (i, j)\n          if i < white_min_x:\n            white_min_x = i\n            min_x_coord = (i, j)\n\n          if j < temp_min_y:\n            temp_min_y = j\n            temp_min_y_coord = (i, j)\n\n      #           Middle Condition        #\n      for j in range(int(mask_img.shape[0] * threshold), int(mask_img.shape[0] * (1 - threshold))):\n        if mask_img[j][i] == 255:\n          if j > white_max_y:\n            white_max_y = j\n            max_y_coord = (i, j)\n          if j < white_min_y:\n            white_min_y = j\n            min_y_coord = (i, j)\n\n      #     Check Bot Condition   #\n      for j in range(int(mask_img.shape[0] * (1 - threshold)), mask_img.shape[0]):\n        # if mask_img[j][i] == 255 and j < thr_min_y:\n          # thr_min_y = j\n          # thr_min_y_coord = (i, j)\n        if mask_img[j][i] == 255:\n          bot_white_cnt += 1\n          if j > temp_max_y:\n            temp_max_y = j\n            temp_max_y_coord = (i, j)\n\n    if top_white_cnt / (mask_img.shape[1] * int(mask_img.shape[0] * threshold)) > 0.5:\n      top_parallel = True\n      min_y_coord = temp_min_y_coord\n    \n    if bot_white_cnt / (mask_img.shape[1] * int(mask_img.shape[0] * threshold)) > 0.5:\n      #     \ubc14\ub2e5\uc740 \ud3c9\ud589 \uc774\ub3d9 \uc0ac\uc6a9\ud558\uc9c0 \uc54a\ub294\ub2e4.    #\n      # bot_parallel = True\n      max_y_coord = temp_max_y_coord\n\n    return min_x_coord, max_x_coord, min_y_coord, max_y_coord, top_parallel, bot_parallel\n\n\ndef crop_and_warp(refer, vl_img, src_4p, dst_4p):\n\n\n  #       Crop      #\n  refered = np.asarray(refer)[:vl_img.shape[0], :vl_img.shape[1]]\n\n  # plt.imshow(refered)\n  # plt.title('refered')\n  # plt.show()\n\n  # compute the perspective transform matrix and then apply it\n  matrix = cv2.getPerspectiveTransform(src_4p, dst_4p)\n  refered = cv2.warpPerspective(refered, matrix, (refered.shape[1], refered.shape[0]))\n\n  return refered\n```\n\n\n```\n#     Refering for one image data   #\ndef synthesize(org_image, refer_image, vpd, scale_factor=6, show_img=False):\n\n  #       Layout Part       #\n  # img = Image.open(layout_path + image)\n  # # print(type(img))\n  # img_np = np.invert(np.asarray(img))\n  # # print(img_np.max(), img_np.min())\n  # ret, thr = cv2.threshold(img_np, 254, 255, cv2.THRESH_BINARY_INV)\n\n  #       Mask Part         #\n  org_color_np, org_np = np.split(np.asarray(org_image), 2, axis=1)\n  # org_np = np.asarray(org)\n  # gray = cv2.cvtColor(org_np, cv2.COLOR_RGB2GRAY)\n  # print(org_np.shape)\n  # ret, thr = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)\n\n  print(image)\n  # plt.subplot(131)\n  # plt.imshow(org)\n  # plt.show()\n  img_size = (org_np.shape[1], org_np.shape[0])\n  \n  print('scale_factor :', scale_factor)\n\n  # refer = Image.open(refer_path)\n  refer = np.asarray(refer_image)\n\n  #     refer_size\uc640 img_size\uac00 \ub3d9\uc77c\ud558\uac70\ub098 refer_size\uac00 \uc791\uc740 \uacbd\uc6b0\ub97c \uace0\ub824\ud574\uc57c\ud55c\ub2e4.     #\n  refer = np.tile(refer, (scale_factor, scale_factor, 1))\n  size_ratio = math.floor(min((refer.shape[0] / (org_np.shape[0] * 1.5)), (refer.shape[1] / (org_np.shape[1] * 1.5))))\n  refer = Image.fromarray(refer).resize((int(refer.shape[1] / size_ratio), int(refer.shape[0] / size_ratio)))\n\n  org_color_np2 = org_color_np.copy()\n  org_np = org_np.astype(np.uint8)\n  org_np2 = org_np.copy()\n  org_np3 = org_np.copy()\n\n  start = time.time()\n\n\n  #                   Find Best Vline_list                #\n  kernel = np.ones((10, 10), np.uint8)\n\n  org_np2_morp = cv2.morphologyEx(org_np2, cv2.MORPH_CLOSE, kernel)\n  org_np2_copy = org_np2_morp.copy()\n  # org_np2_copy_gray = cv2.cvtColor(org_np2_copy, cv2.COLOR_RGB2GRAY)\n\n  ret, thr_org_np2 = cv2.threshold(org_np2_copy, 127, 255, cv2.THRESH_BINARY)\n  thr_org_np2 = cv2.morphologyEx(thr_org_np2, cv2.MORPH_CLOSE, kernel)\n  thr_org_np2_copy = thr_org_np2.copy()\n  \n  edge_org_np2 = cv2.Canny(org_np2_morp, 20, 100)\n  edge_org_np2_copy = edge_org_np2.copy()\n  edge_org_np2_copy2 = cv2.Canny((org_np2_copy / 255. * org_np2_copy).astype(np.uint8), 20, 60)\n  \n  reg_xs = get_vline_points_inborder(vpd, edge_org_np2_copy2)\n  print('#            Used vl_list for vline work          #')\n  print('edge_org_np2_copy2')\n  print()\n\n  #                                     Find Best Hline                                      #\n  #     vline \uc774 \uc874\uc7ac\ud558\uc9c0 \uc54a\ub294 \uacbd\uc6b0\ub3c4 \uace0\ub824\ud574\uc57c\ud55c\ub2e4.     #\n  if len(reg_xs) == 0:\n    reg_xs.append([0, 0])\n    # reg_ys.append([0, org_np2.shape[0]])\n    \n  #         Divide Session by vline       #\n  for reg_index, reg_x in enumerate(reg_xs):\n\n\n    #     In a Session     #\n    #     1.  find vanishing point    #\n    #     2.  Find 3 points (vp, top & bottom points)     #\n    #     3.  Do warfine and attach to the black plane      #\n\n    print(\"#      Session Status      #\")\n    print('reg_index, reg_x :', reg_index, reg_x)\n    \n    #     0.  crop by vline     #\n          #   Find Max_x, min_x, (Max_y, min_y = org.shape[0], 0)\n          #   1.    \uc6b0\ud3b8\uc5d0 \ud55c\ud574\uc11c max_x = \uc6b0\ud3b8 vline max_x & min_x = \ud604\uc7ac vline min_x\n          #   2.    \uc88c\ud3b8\uc5d0 \ud55c\ud574\uc11c max_x = \ud604\uc7ac Max_x & min_x = \uc88c\ud3b8 vline min_x\n\n    #      vline \ubcc4\ub85c \uc591\uc606\uc73c\ub85c \uc791\uc5c5\uc744 \ud558\uba74 len(vline) = 1\uc758 \uc791\uc5c5\uc744 \ubc18\ubcf5\ud560 \ud544\uc694\uac00 \uc5c6\uc5b4\uc9c4\ub2e4.    #\n    iter = False\n    while True:\n\n      #                   We need Max, min x & y                #\n      # four_inters = list()\n      find_pair = True\n      # centroid_inters = all_centroid_inters[inters_i]\n\n      if not iter:\n\n        #       \uc624\ub978\ucabd \ub05d vline \uc774\uba74        #\n        if reg_index == len(reg_xs) - 1:\n          print('rightest vline')\n          #   1.    \uc6b0\ud3b8\uc5d0 \ud55c\ud574\uc11c max_x = \uc6b0\ud3b8 vline max_x & min_x = \ud604\uc7ac vline min_x\n          max_x = org_np.shape[1]\n          min_x = np.min(reg_x)\n\n        else:\n          print('middle vline')\n          next_reg_x = reg_xs[reg_index + 1]\n          max_x = np.max(next_reg_x)\n          if np.min(reg_x) < 0:\n            min_x = 0\n          else:\n            min_x = np.min(reg_x)\n\n      #     i = 0 \uc5d0 \ud55c\ud574\uc11c\ub9cc \uc67c\ucabd\uc73c\ub85c\ub3c4 refering \uc9c4\ud589, \ub098\uba38\uc9c0\ub294 \uc624\ub978\ucabd\uc73c\ub85c\ub9cc     #\n      else:\n          #   2.    \uc88c\ud3b8\uc5d0 \ud55c\ud574\uc11c max_x = \ud604\uc7ac Max_x & min_x = \uc88c\ud3b8 vline min_x\n          max_x = np.max(reg_x)\n          min_x = 0\n\n      print('min_x, max_x :', min_x, max_x)\n      # max_y = org_np.shape[0]\n      # min_y = 0\n\n      #     Make Session      #\n      session = org_np2[:, int(min_x):int(max_x)]\n      # plt.imshow(session)\n      # plt.show()\n\n\n      if (max_x - min_x) > 50:\n        length_thresh = 50\n      else:\n        length_thresh = 20\n        if max_x - min_x < 20:\n            #     i != 0 \uc778 \uacbd\uc6b0 break     #\n          if reg_index == 0 and np.sum(reg_xs) != 0 and not iter:\n            iter = True\n            print('iter :', iter)\n            continue\n          else:\n            break\n      \n      principal_point = None\n      focal_length = 1300 # 1102.79\n      seed = None\n      vpd = VPDetection(length_thresh, principal_point, focal_length, seed)\n\n      try:\n        vpd.find_vps(session)\n        # vps = vpd.vps_2D\n        vl_img, vl_list = vpd.create_debug_VP_image(show_vl=True)\n\n\n        #       Closing Morphing by OpenCV      #\n        kernel = np.ones((10, 10), np.uint8)\n        session = cv2.morphologyEx(session, cv2.MORPH_CLOSE, kernel)\n\n        #     Before Canny    #\n        session_prob = session / 255.\n\n        #     Multiply mask map with Edge => Erase Unnecessary vl line    #\n        #   multiply one time   #\n        session2 = session_prob * (session)\n        edge_session2 = cv2.Canny(session2.astype(np.uint8), 20, 60)\n        #       two time      #\n        # session2 = session_prob**2 * (session)\n        # edge_session2 = cv2.Canny(session2.astype(np.uint8), 20, 60)\n\n        vpd.find_vps(edge_session2)\n        # vps = vpd.vps_2D      \n        vl_edge_img2, vl_edge_list2 = vpd.create_debug_VP_image(show_vl=True)\n      \n      except Exception as e:\n        print(\"Error in vpd Sessions Zone :\", e)\n        print()\n          #     i != 0 \uc778 \uacbd\uc6b0 break     #\n        if reg_index == 0 and np.sum(reg_xs) != 0 and not iter:\n          iter = True\n          print('iter :', iter)\n          continue\n\n        else:\n          break\n\n\n      #         What is best vl_list      #\n      vl_list = vl_edge_list2\n      print('#            Used vl_list for hline work          #')\n      print('vl_edge_list2')\n      print()\n\n      h_lines = list()\n      # print('vps :', vps)\n\n      top_vl = list()\n      bot_vl = list()\n\n      left_vl_list = list()\n      right_vl_list = list()\n\n      left_angle = list()\n      right_angle = list()\n\n      for vl in vl_list:\n        x0, y0, x1, y1 = vl\n        slope = (y1 - y0) / float(x1 - x0)\n        angle = math.degrees(math.atan(slope))\n\n        if abs(angle) < 70:\n          if (y0 + y1) / 2 < vl_img.shape[0] / 2:\n            # print(y0, y1)\n            top_vl.append(vl)\n            if angle < 0:\n              left_vl_list.append(vl)\n              left_angle.append(abs(angle))\n            else:\n              right_vl_list.append(vl)\n              right_angle.append(abs(angle))\n          else:\n            bot_vl.append(vl)\n            if angle > 0:\n              left_vl_list.append(vl)\n              left_angle.append(abs(angle))\n            else:\n              right_vl_list.append(vl)\n              right_angle.append(abs(angle))\n          # cv2.line(skl_copy, (int(x1), int(y1)), (int(x0), int(y0)), (0, 0, 255), 2,\n          #                  cv2.LINE_AA)\n          h_lines.append(vl)\n        #   regression(vl_img, (x0, x1), (y0, y1), color=(0,255,255),axis=1)\n        \n      print('#        Original vl list        #')\n      print('len(left_vl_list) :', len(left_vl_list))\n      print('len(right_vl_list) :', len(right_vl_list))\n      print()\n\n      #             \uc18c\uc2e4\uc810 \ubc29\ud5a5 \uc120\ud0dd            #\n      #       original vl_list \ub294 remove \uac00 \uc874\uc7ac\ud558\uae30 \ub54c\ubb38\uc5d0 copy_ version \uc0ac\uc6a9\ud55c\ub2e4.       #\n      copy_left_vl_list = left_vl_list.copy()\n      copy_right_vl_list = right_vl_list.copy()\n      print('len(copy_left_vl_list) :', len(copy_left_vl_list))\n      print('len(copy_right_vl_list) :', len(copy_right_vl_list))\n\n      if len(copy_left_vl_list) >= len(copy_right_vl_list):\n        direction = 'left'\n        vl_list, copy_vl_list, angle = left_vl_list, copy_left_vl_list, left_angle\n      else:\n        direction = 'right'\n        vl_list, copy_vl_list, angle = right_vl_list, copy_right_vl_list, right_angle\n\n\n      print(\"#            Remove Outliered Angle in Hlines           #\")\n      remove_outlier_angle(vl_list, copy_vl_list, angle)\n      # remove_outlier_angle(right_vl_list, copy_right_vl_list, right_angle)\n      print()\n\n      print('len(left_vl_list) :', len(left_vl_list))\n      print('len(right_vl_list) :', len(right_vl_list))\n      print()\n\n      \n      # if len(left_vl_list) == 0 and len(right_vl_list) == 0:\n      if len(vl_list) == 0:\n        #     i != 0 \uc778 \uacbd\uc6b0 break     #\n        if reg_index == 0 and not iter:\n          iter = True\n          print('iter :', iter)\n          continue\n\n        else:\n          break\n      \n      #                       Find External vn_line                     #\n      # h_border_top = Line((0, 0), (vl_img.shape[1], 0))\n      # h_border_bot = Line((0, vl_img.shape[0]), (vl_img.shape[1], vl_img.shape[0]))\n      l2 = Line((0, 0), (0, vl_img.shape[0]))\n      l3 = Line((vl_img.shape[1], 0), (vl_img.shape[1], vl_img.shape[0]))\n\n      ex_top_vl, ex_bot_vl = get_hline_points_inborder(vl_img, l2, l3, vl_list, top_vl, bot_vl)\n      # ex_left_top_vl, ex_left_bot_vl = get_hline_points_inborder(vl_img, l2, l3, left_vl_list, top_vl, bot_vl)\n      # ex_right_top_vl, ex_right_bot_vl = get_hline_points_inborder(vl_img, l2, l3, right_vl_list, top_vl, bot_vl)\n          \n\n      print()\n      print('#          Extended vl list left / right  TB Condition        #')\n      print('len(ex_top_vl) :', len(ex_top_vl))\n      print('len(ex_bot_vl) :', len(ex_bot_vl))\n      # print('len(ex_left_top_vl) :', len(ex_left_top_vl))\n      # print('len(ex_left_bot_vl) :', len(ex_left_bot_vl))\n      # print('len(ex_right_top_vl) :', len(ex_right_top_vl))\n      # print('len(ex_right_bot_vl) :', len(ex_right_bot_vl))\n      print()\n\n      #       find min max Line     #\n      toppest_vl, bottest_vl = toppest_bottest_vl(vl_img, ex_top_vl, ex_bot_vl, direction)\n      # right_toppest_vl, right_bottest_vl = toppest_bottest_vl(vl_img, ex_right_top_vl, ex_right_bot_vl, 'right')\n      # left_toppest_vl, left_bottest_vl = toppest_bottest_vl(vl_img, ex_left_top_vl, ex_left_bot_vl, 'left')\n\n\n      #       Figure out min_y & max_y of thr_session       #\n      # print('thr_session.shape :', thr_session.shape)\n      gray = cv2.cvtColor(session, cv2.COLOR_RGB2GRAY)\n      ret, thr_session = cv2.threshold(session, 127, 255, cv2.THRESH_BINARY)\n      thr_session = cv2.morphologyEx(thr_session, cv2.MORPH_CLOSE, kernel)\n      thr_session_gray = cv2.cvtColor(thr_session, cv2.COLOR_RGB2GRAY)\n      print('thr_session_gray.shape :', thr_session_gray.shape)\n\n      min_x_coord, max_x_coord, min_y_coord, max_y_coord, top_parallel, _ = top_bot_mask(thr_session_gray)\n      \n      \n      print('max_x_coord, min_x_coord :', max_x_coord, min_x_coord)\n      print('max_y_coord, min_y_coord :', max_y_coord, min_y_coord)\n\n      try:\n\n        #     None \uc774\ub77c\uba74 \ub300\uce6d\uc774\ub3d9\uc744 \ud1b5\ud574 \ub9cc\ub4e4\uc5b4\uc8fc\uc5b4\uc57c\ud55c\ub2e4.     #\n        if len(ex_bot_vl) == 0:\n          if toppest_vl is not None:\n            bottest_vl = line_mirroring(toppest_vl, max_y_coord, l2, l3)\n            print('bottest_vl :', bottest_vl)\n\n        elif len(ex_top_vl) == 0:\n          if bottest_vl is not None:\n            toppest_vl = line_mirroring(bottest_vl, min_y_coord, l2, l3)\n            print('toppest_vl :', toppest_vl)\n\n        # if len(ex_right_bot_vl) == 0:\n        #   if right_toppest_vl is not None:\n        #     right_bottest_vl = line_mirroring(right_toppest_vl, max_y_coord, l2, l3)\n        #     print('right_bottest_vl :', right_bottest_vl)\n\n        # elif len(ex_right_top_vl) == 0:\n        #   if right_bottest_vl is not None:\n        #     right_toppest_vl = line_mirroring(right_bottest_vl, min_y_coord, l2, l3)\n        #     print('right_toppest_vl :', right_toppest_vl)\n\n        # if len(ex_left_bot_vl) == 0:\n        #   if left_toppest_vl is not None:\n        #     left_bottest_vl = line_mirroring(left_toppest_vl, max_y_coord, l2, l3)\n        #     print('left_bottest_vl :', left_bottest_vl)\n\n        # elif len(ex_left_top_vl) == 0:\n        #   if left_bottest_vl is not None:\n        #     left_toppest_vl = line_mirroring(left_bottest_vl, min_y_coord, l2, l3)\n        #     print('left_toppest_vl :', left_toppest_vl)\n\n        for (x1, y1, x0, y0) in [toppest_vl, bottest_vl]:\n          cv2.line(vl_img, (int(x1), int(y1)), (int(x0), int(y0)), (0, 0, 255), 3, cv2.LINE_AA)\n        # for (x1, y1, x0, y0) in [right_toppest_vl, right_bottest_vl]:\n        #   cv2.line(vl_img, (int(x1), int(y1)), (int(x0), int(y0)), (0, 0, 255), 3, cv2.LINE_AA)\n        # for (x1, y1, x0, y0) in [left_toppest_vl, left_bottest_vl]:\n        #   cv2.line(vl_img, (int(x1), int(y1)), (int(x0), int(y0)), (255, 255, 0), 3, cv2.LINE_AA)\n      except Exception as e:\n        print('Error in drawing top, bot -est lines :', e)\n      \n        #     i != 0 \uc778 \uacbd\uc6b0 break     #\n        if reg_index == 0 and not iter:\n          iter = True\n          print('iter :', iter)\n          continue\n\n        else:\n          break\n        \n\n      #               Choose 4 points             #\n      tl, tr, br, bl = choose_4points(toppest_vl, bottest_vl, min_x_coord, l2, l3, top_parallel)\n\n      # if len(copy_left_vl_list) >= len(copy_right_vl_list):\n      #   #       toppest & bottest vl should be on the min_y & max_y of white mask       #\n      #   tl, tr, br, bl = choose_4points(left_toppest_vl, left_bottest_vl, min_x_coord, top_parallel)\n      # else:\n      #   tl, tr, br, bl = choose_4points(right_toppest_vl, right_bottest_vl, min_x_coord, top_parallel)\n        \n      #       Refering      #\n      #   tl, tr, br, bl    #\n      #     refer\ub97c \uc704\ud574 src_x => 0 \uc73c\ub85c \ub9de\ucdb0\uc900\ub2e4.    #\n      src = np.array([\n          [0, 0],\n          [vl_img.shape[1], 0],\n          [vl_img.shape[1], vl_img.shape[0]],\n          [0, vl_img.shape[0]]], dtype = \"float32\")\n      dst = np.array([list(tl),\n                      list(tr),\n                      list(br),\n                      list(bl)], dtype = \"float32\")\n\n      print()\n      print(\"#          Warping Points        #\")\n      print('src :', src)\n      print('dst :', dst)\n\n      refered = crop_and_warp(refer, vl_img, src, dst)\n      \n      \n      # plt.subplot(121)\n      # plt.imshow(vl_img)\n      # plt.title('Session_vl_img')\n      # # plt.xlim(np.min(vps[:, [0]]), np.max(vps[:, [0]]))\n      # # plt.ylim(np.min(vps[:, [1]]), np.max(vps[:, [1]]))\n      # plt.subplot(122) \n      # plt.imshow(refered)\n      # plt.show() \n\n      org_color_np2[:, int(min_x):int(max_x)] = refered\n\n\n      #     i != 0 \uc778 \uacbd\uc6b0 break     #\n      if reg_index == 0 and np.sum(reg_xs) != 0 and not iter:\n        iter = True\n        print('iter :', iter)\n\n      else:\n        break\n\n  \n  #         Refer\uc758 \uac80\uc740 \ubd80\ubd84\uc740 original image\ub85c \ucc44\uc6b4\ub2e4.       #\n  org_color_np2 = np.where(org_color_np2 == 0, org_color_np, org_color_np2)\n  \n  print('elapsed time :', time.time() - start)\n  print()\n\n\n  # print('np.max(org_np) :', np.max(org_np))\n  org_np = org_np / 255.\n  refer = org_color_np2\n  # plt.show()\n\n  #     1.wall_mask * reference color image + (1 - wall_mask) * original_image)    #\n  syn_ = org_np * (refer) + (1 - org_np) * org_color_np\n  syn = org_np * syn_ + (1 - org_np) * org_color_np\n\n  #       Brightness Preservation      #\n  org_hsv = cv2.cvtColor(np.uint8(org_color_np), cv2.COLOR_RGB2HSV)\n  syn_hsv = cv2.cvtColor(np.uint8(syn), cv2.COLOR_RGB2HSV)\n\n  org_h, org_s, org_v = cv2.split(org_hsv)\n  syn_h, syn_s, syn_v = cv2.split(syn_hsv)\n\n  mask_map = org_np[:, :, 0]\n  # print(mask_map.shape)\n\n  w = org_v / 255.\n  w = w / 1.87\n  syn_v2 = mask_map * syn_v + (1 - mask_map) * org_v\n  syn_v2 = (1 - w) * syn_v2 + w * org_v\n  syn_v2 = syn_v2.astype(np.uint8)\n\n  final_syn_hsv = cv2.merge([syn_h, syn_s, syn_v2])\n  final_syn = cv2.cvtColor(final_syn_hsv, cv2.COLOR_HSV2RGB)\n  \n  if show_img:\n\n    plt.figure(figsize=(15, 10))\n    plt.subplot(131)\n    plt.imshow(org_np3)\n\n    plt.subplot(132)\n    plt.imshow(org_color_np2)\n\n    plt.subplot(133)\n    plt.imshow(final_syn)\n    plt.show()\n\n  return final_syn\n```\n\n\n```\nif __name__ == '__main__':\n\n  org_path = 'datasets/lsun/images/' # -> original image\n  layout_path = 'drn_d_105_024_val_ms/images/' # -> layout image (result image frome above model file)\n  refer_path = '../refer_data/wall/myxkehu1kfzggursepnk0tfiyps8zbs5umvzv8d92r6hhxejgawebwsufssgov5q-.jpg'\n\n  object_ = 'wall'\n  mask_path = '../test_data/' + object_ + '/'\n  # layout_path = '../test_layout_result/' + object_ + '/'\n  # layout_path = '../mask_layout_data/' + object_ + '/'\n  # layout_list = os.listdir(layout_path)\n\n  refer_path = './refer_data/' + object_ + '/'\n\n\n\n  length_thresh = 70\n  principal_point = None\n  focal_length = 1300 # 1102.79\n  seed = 1300\n  vpd = VPDetection(length_thresh, principal_point, focal_length, seed)\n\n\n  for image in os.listdir(mask_path):\n\n    for refer in os.listdir(refer_path):\n\n      try:\n        \n        image = '720x480_20191004110915620_aVLsnTL8a4.png'\n\n        org = Image.open(mask_path + image)\n        refer = Image.open(refer_path + refer)\n        synthesize(org, refer, vpd)\n\n      except Exception as e:\n        print('Error in load images :', e)\n\n      # break\n\n```\n\n\n```\n6.486232280731201\nelapsed time : 6.074836015701294\nelapsed time : 6.072072744369507\nelapsed time : 6.072662591934204\nelapsed time : 6.140763998031616\n---\nelapsed time : 4.42145848274231\nelapsed time : 4.432448148727417\nelapsed time : 4.47941255569458\n---\nelapsed time : 2.750857353210449\nelapsed time : 2.7681655883789062\nelapsed time : 2.7948927879333496\nelapsed time : 2.882319927215576\n\n\n```\n", "meta": {"hexsha": "b59e6d3f7bb4245ae1823005365860f52f5af17b", "size": 267869, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Layout Estimation Func Final without AI_origin.ipynb", "max_stars_repo_name": "jaytoone/Indoor_Segmentation", "max_stars_repo_head_hexsha": "d99e502f99cb74000483974d931c2da058071bec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Layout Estimation Func Final without AI_origin.ipynb", "max_issues_repo_name": "jaytoone/Indoor_Segmentation", "max_issues_repo_head_hexsha": "d99e502f99cb74000483974d931c2da058071bec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Layout Estimation Func Final without AI_origin.ipynb", "max_forks_repo_name": "jaytoone/Indoor_Segmentation", "max_forks_repo_head_hexsha": "d99e502f99cb74000483974d931c2da058071bec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-29T15:27:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-29T15:27:56.000Z", "avg_line_length": 267869.0, "max_line_length": 267869, "alphanum_fraction": 0.8847160366, "converted": true, "num_tokens": 10279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276682876897044, "lm_q2_score": 0.05419872600392664, "lm_q1q2_score": 0.017759203744670098}}
{"text": "<a href=\"https://colab.research.google.com/github/vidhya0810/ctrl-sum/blob/master/peg_abs_summary.ipynb\" target=\"_parent\"></a>\n\n\n```\n%tensorflow_version 1.x\n```\n\n    TensorFlow 1.x selected.\n\n\n\n```\n!npx degit google-research/pegasus -f\n```\n\n    \u001b[K\u001b[?25hnpx: installed 1 in 1.899s\n    \u001b[36m> destination directory is not empty. Using --force, continuing\u001b[39m\n    \u001b[36m> cloned \u001b[1mgoogle-research/pegasus\u001b[22m#\u001b[1mmaster\u001b[22m\u001b[39m\n\n\n\n```\nimport os\nos.environ['PYTHONPATH'] += ':/content'\n```\n\n\n```\n!pip install -r requirements.txt\n```\n\n    Requirement already satisfied: absl-py in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 1)) (0.10.0)\n    Collecting mock\n      Downloading https://files.pythonhosted.org/packages/5c/03/b7e605db4a57c0f6fba744b11ef3ddf4ddebcada35022927a2b5fc623fdf/mock-4.0.3-py3-none-any.whl\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 3)) (1.19.5)\n    Collecting rouge-score\n      Downloading https://files.pythonhosted.org/packages/1f/56/a81022436c08b9405a5247b71635394d44fe7e1dbedc4b28c740e09c2840/rouge_score-0.0.4-py2.py3-none-any.whl\n    Collecting sacrebleu\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/7e/57/0c7ca4e31a126189dab99c19951910bd081dea5bbd25f24b77107750eae7/sacrebleu-1.5.1-py3-none-any.whl (54kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 61kB 7.5MB/s \n    \u001b[?25hCollecting sentencepiece\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/f5/99/e0808cb947ba10f575839c43e8fafc9cc44e4a7a2c8f79c60db48220a577/sentencepiece-0.1.95-cp37-cp37m-manylinux2014_x86_64.whl (1.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.2MB 31.9MB/s \n    \u001b[?25hCollecting tensorflow-text==1.15.0rc0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/dd/67/9e503c06d4a8d451ffaa9e9da587e51529292360cb69a2ade0bf691a0871/tensorflow_text-1.15.0rc0-cp37-cp37m-manylinux1_x86_64.whl (8.6MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 8.6MB 52.3MB/s \n    \u001b[?25hCollecting tensor2tensor==1.15.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/0f/a6/0f6a95a5548cf9fbfed0bbec69959355bda594e85298ebbba5f808ca0fc5/tensor2tensor-1.15.0-py2.py3-none-any.whl (1.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.4MB 49.9MB/s \n    \u001b[?25hCollecting tfds-nightly\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/4f/3a/5853827bf08f60349d4f50ae13c46310e4e80ae1c2630ef5788dbb452250/tfds_nightly-4.2.0.dev202103230107-py3-none-any.whl (3.8MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.8MB 42.8MB/s \n    \u001b[?25hCollecting tensorflow-gpu==1.15.2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/92/42/7bddc0d5bc169596fbd13b6e1b844f832491ab671381e483da3bf5292ca9/tensorflow_gpu-1.15.2-cp37-cp37m-manylinux2010_x86_64.whl (410.9MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 411.0MB 39kB/s \n    \u001b[?25hRequirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from absl-py->-r requirements.txt (line 1)) (1.15.0)\n    Requirement already satisfied: nltk in /usr/local/lib/python3.7/dist-packages (from rouge-score->-r requirements.txt (line 4)) (3.2.5)\n    Collecting portalocker==2.0.0\n      Downloading https://files.pythonhosted.org/packages/89/a6/3814b7107e0788040870e8825eebf214d72166adf656ba7d4bf14759a06a/portalocker-2.0.0-py2.py3-none-any.whl\n    Requirement already satisfied: tensorflow<1.16,>=1.15.0 in /tensorflow-1.15.2/python3.7 (from tensorflow-text==1.15.0rc0->-r requirements.txt (line 7)) (1.15.2)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.7.1)\n    Requirement already satisfied: opencv-python in /usr/local/lib/python3.7/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (4.1.2.30)\n    Requirement already satisfied: tensorflow-probability==0.7.0 in /tensorflow-1.15.2/python3.7 (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.7.0)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (2.23.0)\n    Requirement already satisfied: gunicorn in /tensorflow-1.15.2/python3.7 (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (20.0.4)\n    Requirement already satisfied: flask in /usr/local/lib/python3.7/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.1.2)\n    Requirement already satisfied: Pillow in /usr/local/lib/python3.7/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (7.0.0)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.4.1)\n    Requirement already satisfied: google-api-python-client in /usr/local/lib/python3.7/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.12.8)\n    Requirement already satisfied: kfac in /tensorflow-1.15.2/python3.7 (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.2.0)\n    Requirement already satisfied: mesh-tensorflow in /tensorflow-1.15.2/python3.7 (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.1.12)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.16.0)\n    Requirement already satisfied: h5py in /usr/local/lib/python3.7/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (2.10.0)\n    Requirement already satisfied: tensorflow-gan in /tensorflow-1.15.2/python3.7 (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (2.0.0)\n    Requirement already satisfied: dopamine-rl in /usr/local/lib/python3.7/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.0.5)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (4.41.1)\n    Requirement already satisfied: tensorflow-datasets in /usr/local/lib/python3.7/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (4.0.1)\n    Requirement already satisfied: oauth2client in /usr/local/lib/python3.7/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (4.1.3)\n    Requirement already satisfied: gevent in /tensorflow-1.15.2/python3.7 (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.4.0)\n    Requirement already satisfied: gin-config in /usr/local/lib/python3.7/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.4.0)\n    Requirement already satisfied: gym in /usr/local/lib/python3.7/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.17.3)\n    Requirement already satisfied: pypng in /tensorflow-1.15.2/python3.7 (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.0.20)\n    Requirement already satisfied: bz2file in /tensorflow-1.15.2/python3.7 (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.98)\n    Collecting tf-slim\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/02/97/b0f4a64df018ca018cc035d44f2ef08f91e2e8aa67271f6f19633a015ff7/tf_slim-1.1.0-py2.py3-none-any.whl (352kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 358kB 52.4MB/s \n    \u001b[?25hRequirement already satisfied: tensorflow-metadata in /usr/local/lib/python3.7/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (0.28.0)\n    Requirement already satisfied: dill in /usr/local/lib/python3.7/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (0.3.3)\n    Requirement already satisfied: importlib-resources; python_version < \"3.9\" in /usr/local/lib/python3.7/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (5.1.2)\n    Requirement already satisfied: termcolor in /usr/local/lib/python3.7/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (1.1.0)\n    Requirement already satisfied: protobuf>=3.12.2 in /usr/local/lib/python3.7/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (3.12.4)\n    Requirement already satisfied: typing-extensions; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (3.7.4.3)\n    Requirement already satisfied: promise in /usr/local/lib/python3.7/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (2.3)\n    Requirement already satisfied: attrs>=18.1.0 in /usr/local/lib/python3.7/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (20.3.0)\n    Requirement already satisfied: tensorboard<1.16.0,>=1.15.0 in /tensorflow-1.15.2/python3.7 (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (1.15.0)\n    Collecting gast==0.2.2\n      Downloading https://files.pythonhosted.org/packages/4e/35/11749bf99b2d4e3cceb4d55ca22590b0d7c2c62b9de38ac4a4a7f4687421/gast-0.2.2.tar.gz\n    Requirement already satisfied: astor>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (0.8.1)\n    Requirement already satisfied: tensorflow-estimator==1.15.1 in /tensorflow-1.15.2/python3.7 (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (1.15.1)\n    Requirement already satisfied: keras-preprocessing>=1.0.5 in /usr/local/lib/python3.7/dist-packages (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (1.1.2)\n    Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.7/dist-packages (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (1.32.0)\n    Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (3.3.0)\n    Requirement already satisfied: google-pasta>=0.1.6 in /usr/local/lib/python3.7/dist-packages (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (0.2.0)\n    Requirement already satisfied: keras-applications>=1.0.8 in /tensorflow-1.15.2/python3.7 (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (1.0.8)\n    Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (1.12.1)\n    Requirement already satisfied: wheel>=0.26; python_version >= \"3\" in /usr/local/lib/python3.7/dist-packages (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (0.36.2)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.2.1)\n    Requirement already satisfied: cloudpickle>=0.6.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow-probability==0.7.0->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.3.0)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.7/dist-packages (from tensorflow-probability==0.7.0->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (4.4.2)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (2020.12.5)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (2.10)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.24.3)\n    Requirement already satisfied: setuptools>=3.0 in /usr/local/lib/python3.7/dist-packages (from gunicorn->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (54.1.2)\n    Requirement already satisfied: click>=5.1 in /usr/local/lib/python3.7/dist-packages (from flask->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (7.1.2)\n    Requirement already satisfied: Jinja2>=2.10.1 in /usr/local/lib/python3.7/dist-packages (from flask->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (2.11.3)\n    Requirement already satisfied: itsdangerous>=0.24 in /usr/local/lib/python3.7/dist-packages (from flask->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.1.0)\n    Requirement already satisfied: Werkzeug>=0.15 in /usr/local/lib/python3.7/dist-packages (from flask->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.0.1)\n    Requirement already satisfied: google-auth>=1.16.0 in /usr/local/lib/python3.7/dist-packages (from google-api-python-client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.27.1)\n    Requirement already satisfied: google-auth-httplib2>=0.0.3 in /usr/local/lib/python3.7/dist-packages (from google-api-python-client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.0.4)\n    Requirement already satisfied: uritemplate<4dev,>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from google-api-python-client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (3.0.1)\n    Requirement already satisfied: httplib2<1dev,>=0.15.0 in /usr/local/lib/python3.7/dist-packages (from google-api-python-client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.17.4)\n    Requirement already satisfied: google-api-core<2dev,>=1.21.0 in /usr/local/lib/python3.7/dist-packages (from google-api-python-client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.26.1)\n    Requirement already satisfied: tensorflow-hub>=0.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow-gan->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.11.0)\n    Requirement already satisfied: dm-tree in /usr/local/lib/python3.7/dist-packages (from tensorflow-datasets->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.1.5)\n    Requirement already satisfied: pyasn1>=0.1.7 in /usr/local/lib/python3.7/dist-packages (from oauth2client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.4.8)\n    Requirement already satisfied: rsa>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from oauth2client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (4.7.2)\n    Requirement already satisfied: pyasn1-modules>=0.0.5 in /usr/local/lib/python3.7/dist-packages (from oauth2client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.2.8)\n    Requirement already satisfied: greenlet>=0.4.14; platform_python_implementation == \"CPython\" in /tensorflow-1.15.2/python3.7 (from gevent->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.4.15)\n    Requirement already satisfied: pyglet<=1.5.0,>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from gym->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.5.0)\n    Requirement already satisfied: googleapis-common-protos<2,>=1.52.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow-metadata->tfds-nightly->-r requirements.txt (line 9)) (1.53.0)\n    Requirement already satisfied: zipp>=0.4; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from importlib-resources; python_version < \"3.9\"->tfds-nightly->-r requirements.txt (line 9)) (3.4.1)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard<1.16.0,>=1.15.0->tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (3.3.4)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from Jinja2>=2.10.1->flask->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.1.1)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth>=1.16.0->google-api-python-client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (4.2.1)\n    Requirement already satisfied: packaging>=14.3 in /usr/local/lib/python3.7/dist-packages (from google-api-core<2dev,>=1.21.0->google-api-python-client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (20.9)\n    Requirement already satisfied: pytz in /usr/local/lib/python3.7/dist-packages (from google-api-core<2dev,>=1.21.0->google-api-python-client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (2018.9)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from markdown>=2.6.8->tensorboard<1.16.0,>=1.15.0->tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (3.7.2)\n    Requirement already satisfied: pyparsing>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging>=14.3->google-api-core<2dev,>=1.21.0->google-api-python-client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (2.4.7)\n    Building wheels for collected packages: gast\n      Building wheel for gast (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for gast: filename=gast-0.2.2-cp37-none-any.whl size=7540 sha256=6c58354f576deb4f98fe89e7e4d440480690a87e86267d19fadeb36b00b22c7c\n      Stored in directory: /root/.cache/pip/wheels/5c/2e/7e/a1d4d4fcebe6c381f378ce7743a3ced3699feb89bcfbdadadd\n    Successfully built gast\n    Installing collected packages: mock, rouge-score, portalocker, sacrebleu, sentencepiece, tensorflow-text, tf-slim, tensor2tensor, tfds-nightly, gast, tensorflow-gpu\n      Found existing installation: tensor2tensor 1.14.1\n        Uninstalling tensor2tensor-1.14.1:\n          Successfully uninstalled tensor2tensor-1.14.1\n      Found existing installation: gast 0.3.3\n        Uninstalling gast-0.3.3:\n          Successfully uninstalled gast-0.3.3\n    Successfully installed gast-0.2.2 mock-4.0.3 portalocker-2.0.0 rouge-score-0.0.4 sacrebleu-1.5.1 sentencepiece-0.1.95 tensor2tensor-1.15.0 tensorflow-gpu-1.15.2 tensorflow-text-1.15.0rc0 tf-slim-1.1.0 tfds-nightly-4.2.0.dev202103230107\n\n\n\n```\n!pip install mock rouge-score sacrebleu sentencepiece tensorflow-text==1.15.1\n```\n\n    Requirement already satisfied: mock in /usr/local/lib/python3.7/dist-packages (4.0.3)\n    Requirement already satisfied: rouge-score in /usr/local/lib/python3.7/dist-packages (0.0.4)\n    Requirement already satisfied: sacrebleu in /usr/local/lib/python3.7/dist-packages (1.5.1)\n    Requirement already satisfied: sentencepiece in /usr/local/lib/python3.7/dist-packages (0.1.95)\n    Collecting tensorflow-text==1.15.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/51/10/9f45f5ae2b9b082c312c6fbfd19e05d8b8917f4d4c4c5ffc3fae8a5bd3c7/tensorflow_text-1.15.1-cp37-cp37m-manylinux1_x86_64.whl (9.1MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 9.1MB 11.7MB/s \n    \u001b[?25hRequirement already satisfied: nltk in /usr/local/lib/python3.7/dist-packages (from rouge-score) (3.2.5)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from rouge-score) (1.19.5)\n    Requirement already satisfied: six>=1.14.0 in /usr/local/lib/python3.7/dist-packages (from rouge-score) (1.15.0)\n    Requirement already satisfied: absl-py in /usr/local/lib/python3.7/dist-packages (from rouge-score) (0.10.0)\n    Requirement already satisfied: portalocker==2.0.0 in /usr/local/lib/python3.7/dist-packages (from sacrebleu) (2.0.0)\n    Requirement already satisfied: tensorflow<1.16,>=1.15.0 in /tensorflow-1.15.2/python3.7 (from tensorflow-text==1.15.1) (1.15.2)\n    Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow<1.16,>=1.15.0->tensorflow-text==1.15.1) (1.1.0)\n    Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.7/dist-packages (from tensorflow<1.16,>=1.15.0->tensorflow-text==1.15.1) (1.32.0)\n    Requirement already satisfied: keras-preprocessing>=1.0.5 in /usr/local/lib/python3.7/dist-packages (from tensorflow<1.16,>=1.15.0->tensorflow-text==1.15.1) (1.1.2)\n    Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow<1.16,>=1.15.0->tensorflow-text==1.15.1) (1.12.1)\n    Requirement already satisfied: google-pasta>=0.1.6 in /usr/local/lib/python3.7/dist-packages (from tensorflow<1.16,>=1.15.0->tensorflow-text==1.15.1) (0.2.0)\n    Requirement already satisfied: tensorflow-estimator==1.15.1 in /tensorflow-1.15.2/python3.7 (from tensorflow<1.16,>=1.15.0->tensorflow-text==1.15.1) (1.15.1)\n    Requirement already satisfied: keras-applications>=1.0.8 in /tensorflow-1.15.2/python3.7 (from tensorflow<1.16,>=1.15.0->tensorflow-text==1.15.1) (1.0.8)\n    Requirement already satisfied: protobuf>=3.6.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow<1.16,>=1.15.0->tensorflow-text==1.15.1) (3.12.4)\n    Requirement already satisfied: gast==0.2.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow<1.16,>=1.15.0->tensorflow-text==1.15.1) (0.2.2)\n    Requirement already satisfied: astor>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow<1.16,>=1.15.0->tensorflow-text==1.15.1) (0.8.1)\n    Requirement already satisfied: tensorboard<1.16.0,>=1.15.0 in /tensorflow-1.15.2/python3.7 (from tensorflow<1.16,>=1.15.0->tensorflow-text==1.15.1) (1.15.0)\n    Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow<1.16,>=1.15.0->tensorflow-text==1.15.1) (3.3.0)\n    Requirement already satisfied: wheel>=0.26; python_version >= \"3\" in /usr/local/lib/python3.7/dist-packages (from tensorflow<1.16,>=1.15.0->tensorflow-text==1.15.1) (0.36.2)\n    Requirement already satisfied: h5py in /usr/local/lib/python3.7/dist-packages (from keras-applications>=1.0.8->tensorflow<1.16,>=1.15.0->tensorflow-text==1.15.1) (2.10.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from protobuf>=3.6.1->tensorflow<1.16,>=1.15.0->tensorflow-text==1.15.1) (54.1.2)\n    Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard<1.16.0,>=1.15.0->tensorflow<1.16,>=1.15.0->tensorflow-text==1.15.1) (1.0.1)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard<1.16.0,>=1.15.0->tensorflow<1.16,>=1.15.0->tensorflow-text==1.15.1) (3.3.4)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from markdown>=2.6.8->tensorboard<1.16.0,>=1.15.0->tensorflow<1.16,>=1.15.0->tensorflow-text==1.15.1) (3.7.2)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->markdown>=2.6.8->tensorboard<1.16.0,>=1.15.0->tensorflow<1.16,>=1.15.0->tensorflow-text==1.15.1) (3.4.1)\n    Requirement already satisfied: typing-extensions>=3.6.4; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->markdown>=2.6.8->tensorboard<1.16.0,>=1.15.0->tensorflow<1.16,>=1.15.0->tensorflow-text==1.15.1) (3.7.4.3)\n    Installing collected packages: tensorflow-text\n      Found existing installation: tensorflow-text 1.15.0rc0\n        Uninstalling tensorflow-text-1.15.0rc0:\n          Successfully uninstalled tensorflow-text-1.15.0rc0\n    Successfully installed tensorflow-text-1.15.1\n\n\n\n```\nmkdir ckpt\n```\n\n\n```\n!pip install tensorflow-datasets==3.0.0\n!pip install tfds-nightly==3.1.0.dev202006230105\n```\n\n    Collecting tensorflow-datasets==3.0.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/76/41/8404fabb295025c1ced13bb150246f75770619889d8637afa523a4d09cdb/tensorflow_datasets-3.0.0-py3-none-any.whl (3.3MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.3MB 16.4MB/s \n    \u001b[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from tensorflow-datasets==3.0.0) (1.19.5)\n    Requirement already satisfied: attrs>=18.1.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow-datasets==3.0.0) (20.3.0)\n    Requirement already satisfied: promise in /usr/local/lib/python3.7/dist-packages (from tensorflow-datasets==3.0.0) (2.3)\n    Requirement already satisfied: absl-py in /usr/local/lib/python3.7/dist-packages (from tensorflow-datasets==3.0.0) (0.10.0)\n    Requirement already satisfied: requests>=2.19.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow-datasets==3.0.0) (2.23.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from tensorflow-datasets==3.0.0) (1.15.0)\n    Requirement already satisfied: termcolor in /usr/local/lib/python3.7/dist-packages (from tensorflow-datasets==3.0.0) (1.1.0)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from tensorflow-datasets==3.0.0) (0.16.0)\n    Requirement already satisfied: dill in /usr/local/lib/python3.7/dist-packages (from tensorflow-datasets==3.0.0) (0.3.3)\n    Requirement already satisfied: tensorflow-metadata in /usr/local/lib/python3.7/dist-packages (from tensorflow-datasets==3.0.0) (0.28.0)\n    Requirement already satisfied: wrapt in /usr/local/lib/python3.7/dist-packages (from tensorflow-datasets==3.0.0) (1.12.1)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from tensorflow-datasets==3.0.0) (4.41.1)\n    Requirement already satisfied: protobuf>=3.6.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow-datasets==3.0.0) (3.12.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->tensorflow-datasets==3.0.0) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->tensorflow-datasets==3.0.0) (3.0.4)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->tensorflow-datasets==3.0.0) (1.24.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->tensorflow-datasets==3.0.0) (2020.12.5)\n    Requirement already satisfied: googleapis-common-protos<2,>=1.52.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow-metadata->tensorflow-datasets==3.0.0) (1.53.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from protobuf>=3.6.1->tensorflow-datasets==3.0.0) (54.1.2)\n    Installing collected packages: tensorflow-datasets\n      Found existing installation: tensorflow-datasets 4.0.1\n        Uninstalling tensorflow-datasets-4.0.1:\n          Successfully uninstalled tensorflow-datasets-4.0.1\n    Successfully installed tensorflow-datasets-3.0.0\n    Collecting tfds-nightly==3.1.0.dev202006230105\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/09/fa/877491b455a10fe38fa8902e1339c99bcd48890a47351cfce26f408d1537/tfds_nightly-3.1.0.dev202006230105-py3-none-any.whl (3.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.4MB 19.4MB/s \n    \u001b[?25hRequirement already satisfied: protobuf>=3.6.1 in /usr/local/lib/python3.7/dist-packages (from tfds-nightly==3.1.0.dev202006230105) (3.12.4)\n    Requirement already satisfied: termcolor in /usr/local/lib/python3.7/dist-packages (from tfds-nightly==3.1.0.dev202006230105) (1.1.0)\n    Requirement already satisfied: wrapt in /usr/local/lib/python3.7/dist-packages (from tfds-nightly==3.1.0.dev202006230105) (1.12.1)\n    Requirement already satisfied: tensorflow-metadata in /usr/local/lib/python3.7/dist-packages (from tfds-nightly==3.1.0.dev202006230105) (0.28.0)\n    Requirement already satisfied: requests>=2.19.0 in /usr/local/lib/python3.7/dist-packages (from tfds-nightly==3.1.0.dev202006230105) (2.23.0)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from tfds-nightly==3.1.0.dev202006230105) (4.41.1)\n    Requirement already satisfied: absl-py in /usr/local/lib/python3.7/dist-packages (from tfds-nightly==3.1.0.dev202006230105) (0.10.0)\n    Requirement already satisfied: dill in /usr/local/lib/python3.7/dist-packages (from tfds-nightly==3.1.0.dev202006230105) (0.3.3)\n    Requirement already satisfied: attrs>=18.1.0 in /usr/local/lib/python3.7/dist-packages (from tfds-nightly==3.1.0.dev202006230105) (20.3.0)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from tfds-nightly==3.1.0.dev202006230105) (1.19.5)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from tfds-nightly==3.1.0.dev202006230105) (0.16.0)\n    Requirement already satisfied: promise in /usr/local/lib/python3.7/dist-packages (from tfds-nightly==3.1.0.dev202006230105) (2.3)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from tfds-nightly==3.1.0.dev202006230105) (1.15.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from protobuf>=3.6.1->tfds-nightly==3.1.0.dev202006230105) (54.1.2)\n    Requirement already satisfied: googleapis-common-protos<2,>=1.52.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow-metadata->tfds-nightly==3.1.0.dev202006230105) (1.53.0)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->tfds-nightly==3.1.0.dev202006230105) (2020.12.5)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->tfds-nightly==3.1.0.dev202006230105) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->tfds-nightly==3.1.0.dev202006230105) (2.10)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->tfds-nightly==3.1.0.dev202006230105) (1.24.3)\n    Installing collected packages: tfds-nightly\n      Found existing installation: tfds-nightly 4.2.0.dev202103230107\n        Uninstalling tfds-nightly-4.2.0.dev202103230107:\n          Successfully uninstalled tfds-nightly-4.2.0.dev202103230107\n    Successfully installed tfds-nightly-3.1.0.dev202006230105\n\n\n\n```\n!gsutil cp -r gs://pegasus_ckpt/aeslc/ ckpt\n```\n\n    Copying gs://pegasus_ckpt/aeslc/model.ckpt-32000.data-00000-of-00001...\n    Copying gs://pegasus_ckpt/aeslc/model.ckpt-32000.index...\n    Copying gs://pegasus_ckpt/aeslc/model.ckpt-32000.meta...\n    \\ [3 files][  2.1 GiB/  2.1 GiB]   67.4 MiB/s                                   \n    Operation completed over 3 objects/2.1 GiB.                                      \n\n\n\n```\n!gsutil cp -r gs://pegasus_ckpt/c4.unigram.newline.10pct.96000.model/ ckpt\n```\n\n    Copying gs://pegasus_ckpt/c4.unigram.newline.10pct.96000.model...\n    / [1 files][  1.8 MiB/  1.8 MiB]                                                \r\n    Operation completed over 1 objects/1.8 MiB.                                      \n\n\n\n```\n!gsutil cp -r gs://pegasus_ckpt/c4.unigram.newline.10pct.96000.vocab/ ckpt\n```\n\n    Copying gs://pegasus_ckpt/c4.unigram.newline.10pct.96000.vocab...\n    / [1 files][  1.7 MiB/  1.7 MiB]                                                \r\n    Operation completed over 1 objects/1.7 MiB.                                      \n\n\n\n```\n!gsutil cp -r gs://pegasus_ckpt/checkpoint/ ckpt\n```\n\n    Copying gs://pegasus_ckpt/checkpoint...\n    / [1 files][   93.0 B/   93.0 B]                                                \r\n    Operation completed over 1 objects/93.0 B.                                       \n\n\n\n```\n!gsutil cp -r gs://pegasus_ckpt/cnn_dailymail/ ckpt\n```\n\n    Copying gs://pegasus_ckpt/cnn_dailymail/model.ckpt-210000.data-00000-of-00001...\n    Copying gs://pegasus_ckpt/cnn_dailymail/model.ckpt-210000.index...\n    Copying gs://pegasus_ckpt/cnn_dailymail/model.ckpt-210000.meta...\n    / [3 files][  2.1 GiB/  2.1 GiB]   39.4 MiB/s                                   \n    Operation completed over 3 objects/2.1 GiB.                                      \n\n\n\n```\n!gsutil cp -r gs://pegasus_ckpt/model.ckpt-1500000.data-00000-of-00001/ ckpt\n```\n\n    Copying gs://pegasus_ckpt/model.ckpt-1500000.data-00000-of-00001...\n    \\ [1 files][  2.1 GiB/  2.1 GiB]   72.5 MiB/s                                   \n    Operation completed over 1 objects/2.1 GiB.                                      \n\n\n\n```\n!gsutil cp -r gs://pegasus_ckpt/model.ckpt-1500000.index/ ckpt\n```\n\n    Copying gs://pegasus_ckpt/model.ckpt-1500000.index...\n    / [1 files][ 16.7 KiB/ 16.7 KiB]                                                \r\n    Operation completed over 1 objects/16.7 KiB.                                     \n\n\n\n```\n!gsutil cp -r gs://pegasus_ckpt/model.ckpt-1500000.meta/ ckpt\n```\n\n    Copying gs://pegasus_ckpt/model.ckpt-1500000.meta...\n    | [1 files][220.4 MiB/220.4 MiB]                                                \n    Operation completed over 1 objects/220.4 MiB.                                    \n\n\n\n```\n!python3 pegasus/bin/train.py --params=aeslc_transformer \\\n--param_overrides=vocab_filename=ckpt/c4.unigram.newline.10pct.96000.model \\\n--train_init_checkpoint=ckpt/model.ckpt-1500000 \\\n--model_dir=ckpt/aeslc\n```\n\n    WARNING:tensorflow:From pegasus/bin/train.py:94: The name tf.app.run is deprecated. Please use tf.compat.v1.app.run instead.\n    \n    WARNING:tensorflow:From /content/pegasus/ops/public_parsing_ops.py:93: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n    \n    W0323 09:42:42.337186 140015849629568 module_wrapper.py:139] From /content/pegasus/ops/public_parsing_ops.py:93: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n    \n    WARNING:tensorflow:From /content/pegasus/params/estimator_utils.py:49: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead.\n    \n    W0323 09:42:42.475074 140015849629568 module_wrapper.py:139] From /content/pegasus/params/estimator_utils.py:49: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead.\n    \n    WARNING:tensorflow:Estimator's model_fn (<function _estimator_model_fn.<locals>.model_fn at 0x7f577ef88200>) includes params argument, but params are not passed to Estimator.\n    W0323 09:42:42.475606 140015849629568 estimator.py:1994] Estimator's model_fn (<function _estimator_model_fn.<locals>.model_fn at 0x7f577ef88200>) includes params argument, but params are not passed to Estimator.\n    INFO:tensorflow:Using config: {'_model_dir': 'ckpt/aeslc', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': 1000, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true\n    , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': None, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7f577ef7be50>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1, '_tpu_config': TPUConfig(iterations_per_loop=1000, num_shards=None, num_cores_per_replica=None, per_host_input_for_training=2, tpu_job_name=None, initial_infeed_sleep_secs=None, input_partition_dims=None, eval_training_input_configuration=2, experimental_host_call_every_n_steps=1), '_cluster': None}\n    I0323 09:42:42.477227 140015849629568 estimator.py:212] Using config: {'_model_dir': 'ckpt/aeslc', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': 1000, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true\n    , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': None, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7f577ef7be50>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1, '_tpu_config': TPUConfig(iterations_per_loop=1000, num_shards=None, num_cores_per_replica=None, per_host_input_for_training=2, tpu_job_name=None, initial_infeed_sleep_secs=None, input_partition_dims=None, eval_training_input_configuration=2, experimental_host_call_every_n_steps=1), '_cluster': None}\n    INFO:tensorflow:_TPUContext: eval_on_tpu True\n    I0323 09:42:42.477473 140015849629568 tpu_context.py:220] _TPUContext: eval_on_tpu True\n    WARNING:tensorflow:eval_on_tpu ignored because use_tpu is False.\n    W0323 09:42:42.477704 140015849629568 tpu_context.py:222] eval_on_tpu ignored because use_tpu is False.\n    WARNING:tensorflow:From /tensorflow-1.15.2/python3.7/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\n    Instructions for updating:\n    If using Keras pass *_constraint arguments to layers.\n    W0323 09:42:42.488204 140015849629568 deprecation.py:506] From /tensorflow-1.15.2/python3.7/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\n    Instructions for updating:\n    If using Keras pass *_constraint arguments to layers.\n    WARNING:tensorflow:From /tensorflow-1.15.2/python3.7/tensorflow_core/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.\n    W0323 09:42:42.488598 140015849629568 deprecation.py:323] From /tensorflow-1.15.2/python3.7/tensorflow_core/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.\n    I0323 09:42:42.545305 140015849629568 dataset_info.py:427] Load pre-computed DatasetInfo (eg: splits, num examples,...) from GCS: aeslc/1.0.0\n    I0323 09:42:42.665326 140015849629568 dataset_info.py:358] Load dataset info from /tmp/tmp2u64csbatfds\n    I0323 09:42:42.666739 140015849629568 dataset_info.py:398] Field info.description from disk and from code do not match. Keeping the one from code.\n    I0323 09:42:42.666898 140015849629568 dataset_info.py:398] Field info.citation from disk and from code do not match. Keeping the one from code.\n    I0323 09:42:42.667275 140015849629568 dataset_builder.py:345] Generating dataset aeslc (/root/tensorflow_datasets/aeslc/1.0.0)\n    \u001b[1mDownloading and preparing dataset aeslc/1.0.0 (download: 11.10 MiB, generated: Unknown size, total: 11.10 MiB) to /root/tensorflow_datasets/aeslc/1.0.0...\u001b[0m\n    Dl Completed...: 0 url [00:00, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[AI0323 09:42:42.776161 140015849629568 download_manager.py:477] Downloading https://github.com/ryanzhumich/AESLC/archive/master.zip into /root/tensorflow_datasets/downloads/ryanzhumich_AESLC_archive_masterACSpoxw627Ay4UrkswMeyz6RrOey8kKfkhEM4VySJWU.zip.tmp.07002748dac047c8a0dcc3fd9a6b7613...\n    Dl Completed...:   0% 0/1 [00:00<?, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:00<?, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:00<?, ? url/s]\n    Dl Size...: 1 MiB [00:00,  3.11 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:00<?, ? url/s]\n    Dl Size...: 2 MiB [00:00,  3.82 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:00<?, ? url/s]\n    Dl Size...: 3 MiB [00:00,  4.59 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:00<?, ? url/s]\n    Dl Size...: 4 MiB [00:00,  5.39 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:00<?, ? url/s]\n    Dl Size...: 5 MiB [00:00,  6.12 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:00<?, ? url/s]\n    Dl Size...: 6 MiB [00:00,  6.62 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:01<?, ? url/s]\n    Dl Size...: 7 MiB [00:01,  7.05 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:01, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:01<?, ? url/s]\n    Dl Size...: 8 MiB [00:01,  7.45 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:01, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:01<?, ? url/s]\n    Dl Size...: 9 MiB [00:01,  7.72 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:01<?, ? url/s]\n    Dl Size...: 10 MiB [00:01,  7.72 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:01<?, ? url/s]\n    Dl Size...: 11 MiB [00:01,  7.72 MiB/s]\u001b[A\n    \n    Dl Completed...: 100% 1/1 [00:01<00:00,  1.30s/ url]\n    Dl Size...: 11 MiB [00:01,  7.72 MiB/s]\u001b[A\n    \n    Dl Completed...: 100% 1/1 [00:01<00:00,  1.30s/ url]\n    Dl Size...: 11 MiB [00:01,  7.72 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:01<?, ? file/s]\u001b[A\u001b[A\n    \n    Dl Completed...: 100% 1/1 [00:07<00:00,  1.30s/ url]\n    Dl Size...: 11 MiB [00:07,  7.72 MiB/s]\u001b[A\n    \n    Extraction completed...: 100% 1/1 [00:07<00:00,  7.82s/ file]\u001b[A\u001b[A\n    Extraction completed...: 100% 1/1 [00:07<00:00,  7.83s/ file]\n    \n    Dl Size...: 11 MiB [00:07,  1.41 MiB/s]\n    \n    Dl Completed...: 100% 1/1 [00:07<00:00,  7.83s/ url]\n    I0323 09:42:50.602668 140015849629568 dataset_builder.py:946] Generating split train\n    Shuffling and writing examples to /root/tensorflow_datasets/aeslc/1.0.0.incompleteW0JYQ2/aeslc-train.tfrecord\n      0% 0/14436 [00:00<?, ? examples/s]I0323 09:42:56.521217 140015849629568 tfrecords_writer.py:230] Done writing /root/tensorflow_datasets/aeslc/1.0.0.incompleteW0JYQ2/aeslc-train.tfrecord. Shard lengths: [14436]\n    I0323 09:42:56.525305 140015849629568 dataset_builder.py:946] Generating split validation\n    Shuffling and writing examples to /root/tensorflow_datasets/aeslc/1.0.0.incompleteW0JYQ2/aeslc-validation.tfrecord\n      0% 0/1960 [00:00<?, ? examples/s]I0323 09:42:57.411416 140015849629568 tfrecords_writer.py:230] Done writing /root/tensorflow_datasets/aeslc/1.0.0.incompleteW0JYQ2/aeslc-validation.tfrecord. Shard lengths: [1960]\n    I0323 09:42:57.412200 140015849629568 dataset_builder.py:946] Generating split test\n    Shuffling and writing examples to /root/tensorflow_datasets/aeslc/1.0.0.incompleteW0JYQ2/aeslc-test.tfrecord\n      0% 0/1906 [00:00<?, ? examples/s]I0323 09:42:58.161666 140015849629568 tfrecords_writer.py:230] Done writing /root/tensorflow_datasets/aeslc/1.0.0.incompleteW0JYQ2/aeslc-test.tfrecord. Shard lengths: [1906]\n    I0323 09:42:58.162671 140015849629568 dataset_builder.py:400] Skipping computing stats for mode ComputeStatsMode.AUTO.\n    \u001b[1mDataset aeslc downloaded and prepared to /root/tensorflow_datasets/aeslc/1.0.0. Subsequent calls will reuse this data.\u001b[0m\n    I0323 09:42:58.163849 140015849629568 dataset_builder.py:499] Constructing tf.data.Dataset for split train, from /root/tensorflow_datasets/aeslc/1.0.0\n    I0323 09:42:58.400106 140015849629568 datasets.py:215] Number of examples for config aeslc train is 14436\n    2021-03-23 09:42:59.067226: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1\n    2021-03-23 09:42:59.140056: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n    2021-03-23 09:42:59.140655: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \n    name: Tesla T4 major: 7 minor: 5 memoryClockRate(GHz): 1.59\n    pciBusID: 0000:00:04.0\n    2021-03-23 09:42:59.228943: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n    2021-03-23 09:42:59.421176: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n    2021-03-23 09:42:59.563578: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n    2021-03-23 09:42:59.595956: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n    2021-03-23 09:42:59.854564: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n    2021-03-23 09:42:59.868934: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n    2021-03-23 09:43:00.375740: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n    2021-03-23 09:43:00.375974: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n    2021-03-23 09:43:00.376682: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n    2021-03-23 09:43:00.377206: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n    WARNING:tensorflow:From /tensorflow-1.15.2/python3.7/tensorflow_core/python/ops/ragged/ragged_tensor.py:1586: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use tf.where in 2.0, which has the same broadcast rule as np.where\n    W0323 09:43:00.471799 140015849629568 deprecation.py:323] From /tensorflow-1.15.2/python3.7/tensorflow_core/python/ops/ragged/ragged_tensor.py:1586: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use tf.where in 2.0, which has the same broadcast rule as np.where\n    INFO:tensorflow:Calling model_fn.\n    I0323 09:43:00.715790 140015849629568 estimator.py:1148] Calling model_fn.\n    INFO:tensorflow:Running train on CPU\n    I0323 09:43:00.716070 140015849629568 tpu_estimator.py:3124] Running train on CPU\n    WARNING:tensorflow:From /content/pegasus/params/estimator_utils.py:78: The name tf.get_variable_scope is deprecated. Please use tf.compat.v1.get_variable_scope instead.\n    \n    W0323 09:43:00.716448 140015849629568 module_wrapper.py:139] From /content/pegasus/params/estimator_utils.py:78: The name tf.get_variable_scope is deprecated. Please use tf.compat.v1.get_variable_scope instead.\n    \n    WARNING:tensorflow:From /content/pegasus/layers/attention.py:41: The name tf.layers.Dense is deprecated. Please use tf.compat.v1.layers.Dense instead.\n    \n    W0323 09:43:00.716814 140015849629568 module_wrapper.py:139] From /content/pegasus/layers/attention.py:41: The name tf.layers.Dense is deprecated. Please use tf.compat.v1.layers.Dense instead.\n    \n    WARNING:tensorflow:From /content/pegasus/layers/embedding.py:57: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n    \n    W0323 09:43:00.756722 140015849629568 module_wrapper.py:139] From /content/pegasus/layers/embedding.py:57: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n    \n    WARNING:tensorflow:From /content/pegasus/layers/embedding.py:57: The name tf.AUTO_REUSE is deprecated. Please use tf.compat.v1.AUTO_REUSE instead.\n    \n    W0323 09:43:00.756910 140015849629568 module_wrapper.py:139] From /content/pegasus/layers/embedding.py:57: The name tf.AUTO_REUSE is deprecated. Please use tf.compat.v1.AUTO_REUSE instead.\n    \n    WARNING:tensorflow:From /content/pegasus/layers/embedding.py:61: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n    \n    W0323 09:43:00.757146 140015849629568 module_wrapper.py:139] From /content/pegasus/layers/embedding.py:61: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n    \n    WARNING:tensorflow:From /content/pegasus/layers/embedding.py:64: calling RandomNormal.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Call initializer instance with the dtype argument instead of passing it to the constructor\n    W0323 09:43:00.757384 140015849629568 deprecation.py:506] From /content/pegasus/layers/embedding.py:64: calling RandomNormal.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Call initializer instance with the dtype argument instead of passing it to the constructor\n    WARNING:tensorflow:From /content/pegasus/layers/attention.py:106: The name tf.matrix_band_part is deprecated. Please use tf.linalg.band_part instead.\n    \n    W0323 09:43:03.239101 140015849629568 module_wrapper.py:139] From /content/pegasus/layers/attention.py:106: The name tf.matrix_band_part is deprecated. Please use tf.linalg.band_part instead.\n    \n    WARNING:tensorflow:From /content/pegasus/models/transformer.py:108: The name tf.losses.softmax_cross_entropy is deprecated. Please use tf.compat.v1.losses.softmax_cross_entropy instead.\n    \n    W0323 09:43:07.268426 140015849629568 module_wrapper.py:139] From /content/pegasus/models/transformer.py:108: The name tf.losses.softmax_cross_entropy is deprecated. Please use tf.compat.v1.losses.softmax_cross_entropy instead.\n    \n    WARNING:tensorflow:From /content/pegasus/params/estimator_utils.py:113: The name tf.train.get_global_step is deprecated. Please use tf.compat.v1.train.get_global_step instead.\n    \n    W0323 09:43:07.311040 140015849629568 module_wrapper.py:139] From /content/pegasus/params/estimator_utils.py:113: The name tf.train.get_global_step is deprecated. Please use tf.compat.v1.train.get_global_step instead.\n    \n    WARNING:tensorflow:From /content/pegasus/params/estimator_utils.py:114: The name tf.rsqrt is deprecated. Please use tf.math.rsqrt instead.\n    \n    W0323 09:43:07.311391 140015849629568 module_wrapper.py:139] From /content/pegasus/params/estimator_utils.py:114: The name tf.rsqrt is deprecated. Please use tf.math.rsqrt instead.\n    \n    WARNING:tensorflow:From /content/pegasus/params/estimator_utils.py:115: to_float (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    W0323 09:43:07.311611 140015849629568 deprecation.py:323] From /content/pegasus/params/estimator_utils.py:115: to_float (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    WARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/tensor2tensor/utils/adafactor.py:315: The name tf.train.get_or_create_global_step is deprecated. Please use tf.compat.v1.train.get_or_create_global_step instead.\n    \n    W0323 09:43:07.322172 140015849629568 module_wrapper.py:139] From /usr/local/lib/python3.7/dist-packages/tensor2tensor/utils/adafactor.py:315: The name tf.train.get_or_create_global_step is deprecated. Please use tf.compat.v1.train.get_or_create_global_step instead.\n    \n    WARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/tensor2tensor/utils/quantization.py:147: 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    W0323 09:43:07.326635 140015849629568 deprecation.py:323] From /usr/local/lib/python3.7/dist-packages/tensor2tensor/utils/quantization.py:147: 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    WARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/tensor2tensor/utils/quantization.py:156: The name tf.mod is deprecated. Please use tf.math.mod instead.\n    \n    W0323 09:43:07.328975 140015849629568 module_wrapper.py:139] From /usr/local/lib/python3.7/dist-packages/tensor2tensor/utils/quantization.py:156: The name tf.mod is deprecated. Please use tf.math.mod instead.\n    \n    WARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/tensor2tensor/utils/adafactor.py:244: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead.\n    \n    W0323 09:43:19.015337 140015849629568 module_wrapper.py:139] From /usr/local/lib/python3.7/dist-packages/tensor2tensor/utils/adafactor.py:244: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead.\n    \n    WARNING:tensorflow:From /content/pegasus/params/estimator_utils.py:189: The name tf.trainable_variables is deprecated. Please use tf.compat.v1.trainable_variables instead.\n    \n    W0323 09:43:31.032931 140015849629568 module_wrapper.py:139] From /content/pegasus/params/estimator_utils.py:189: The name tf.trainable_variables is deprecated. Please use tf.compat.v1.trainable_variables instead.\n    \n    WARNING:tensorflow:From /content/pegasus/params/estimator_utils.py:205: The name tf.train.init_from_checkpoint is deprecated. Please use tf.compat.v1.train.init_from_checkpoint instead.\n    \n    W0323 09:43:31.038644 140015849629568 module_wrapper.py:139] From /content/pegasus/params/estimator_utils.py:205: The name tf.train.init_from_checkpoint is deprecated. Please use tf.compat.v1.train.init_from_checkpoint instead.\n    \n    I0323 09:43:32.218361 140015849629568 estimator_utils.py:207] **** Trainable Variables ****\n    I0323 09:43:32.218551 140015849629568 estimator_utils.py:212]   name = embeddings/weights:0, shape = (96103, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.218656 140015849629568 estimator_utils.py:212]   name = encoder/layer_0/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.218749 140015849629568 estimator_utils.py:212]   name = encoder/layer_0/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.218822 140015849629568 estimator_utils.py:212]   name = encoder/layer_0/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.218923 140015849629568 estimator_utils.py:212]   name = encoder/layer_0/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.219001 140015849629568 estimator_utils.py:212]   name = encoder/layer_0/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.219077 140015849629568 estimator_utils.py:212]   name = encoder/layer_0/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.219160 140015849629568 estimator_utils.py:212]   name = encoder/layer_0/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.219234 140015849629568 estimator_utils.py:212]   name = encoder/layer_0/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.219309 140015849629568 estimator_utils.py:212]   name = encoder/layer_0/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.219383 140015849629568 estimator_utils.py:212]   name = encoder/layer_0/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.219456 140015849629568 estimator_utils.py:212]   name = encoder/layer_0/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.219530 140015849629568 estimator_utils.py:212]   name = encoder/layer_0/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.219600 140015849629568 estimator_utils.py:212]   name = encoder/layer_1/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.219668 140015849629568 estimator_utils.py:212]   name = encoder/layer_1/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.219738 140015849629568 estimator_utils.py:212]   name = encoder/layer_1/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.219811 140015849629568 estimator_utils.py:212]   name = encoder/layer_1/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.219896 140015849629568 estimator_utils.py:212]   name = encoder/layer_1/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.219971 140015849629568 estimator_utils.py:212]   name = encoder/layer_1/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.220046 140015849629568 estimator_utils.py:212]   name = encoder/layer_1/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.220118 140015849629568 estimator_utils.py:212]   name = encoder/layer_1/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.220225 140015849629568 estimator_utils.py:212]   name = encoder/layer_1/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.220314 140015849629568 estimator_utils.py:212]   name = encoder/layer_1/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.220398 140015849629568 estimator_utils.py:212]   name = encoder/layer_1/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.220494 140015849629568 estimator_utils.py:212]   name = encoder/layer_1/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.220577 140015849629568 estimator_utils.py:212]   name = encoder/layer_2/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.220659 140015849629568 estimator_utils.py:212]   name = encoder/layer_2/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.220746 140015849629568 estimator_utils.py:212]   name = encoder/layer_2/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.220844 140015849629568 estimator_utils.py:212]   name = encoder/layer_2/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.220929 140015849629568 estimator_utils.py:212]   name = encoder/layer_2/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.221016 140015849629568 estimator_utils.py:212]   name = encoder/layer_2/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.221103 140015849629568 estimator_utils.py:212]   name = encoder/layer_2/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.221193 140015849629568 estimator_utils.py:212]   name = encoder/layer_2/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.221284 140015849629568 estimator_utils.py:212]   name = encoder/layer_2/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.221368 140015849629568 estimator_utils.py:212]   name = encoder/layer_2/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.221437 140015849629568 estimator_utils.py:212]   name = encoder/layer_2/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.221509 140015849629568 estimator_utils.py:212]   name = encoder/layer_2/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.221582 140015849629568 estimator_utils.py:212]   name = encoder/layer_3/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.221654 140015849629568 estimator_utils.py:212]   name = encoder/layer_3/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.221723 140015849629568 estimator_utils.py:212]   name = encoder/layer_3/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.221794 140015849629568 estimator_utils.py:212]   name = encoder/layer_3/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.221877 140015849629568 estimator_utils.py:212]   name = encoder/layer_3/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.221952 140015849629568 estimator_utils.py:212]   name = encoder/layer_3/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.222025 140015849629568 estimator_utils.py:212]   name = encoder/layer_3/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.222094 140015849629568 estimator_utils.py:212]   name = encoder/layer_3/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.222170 140015849629568 estimator_utils.py:212]   name = encoder/layer_3/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.222242 140015849629568 estimator_utils.py:212]   name = encoder/layer_3/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.222312 140015849629568 estimator_utils.py:212]   name = encoder/layer_3/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.222383 140015849629568 estimator_utils.py:212]   name = encoder/layer_3/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.222452 140015849629568 estimator_utils.py:212]   name = encoder/layer_4/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.222524 140015849629568 estimator_utils.py:212]   name = encoder/layer_4/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.222594 140015849629568 estimator_utils.py:212]   name = encoder/layer_4/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.222665 140015849629568 estimator_utils.py:212]   name = encoder/layer_4/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.222738 140015849629568 estimator_utils.py:212]   name = encoder/layer_4/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.222810 140015849629568 estimator_utils.py:212]   name = encoder/layer_4/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.222899 140015849629568 estimator_utils.py:212]   name = encoder/layer_4/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.222968 140015849629568 estimator_utils.py:212]   name = encoder/layer_4/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.223040 140015849629568 estimator_utils.py:212]   name = encoder/layer_4/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.223118 140015849629568 estimator_utils.py:212]   name = encoder/layer_4/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.223194 140015849629568 estimator_utils.py:212]   name = encoder/layer_4/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.223266 140015849629568 estimator_utils.py:212]   name = encoder/layer_4/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.223336 140015849629568 estimator_utils.py:212]   name = encoder/layer_5/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.223404 140015849629568 estimator_utils.py:212]   name = encoder/layer_5/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.223472 140015849629568 estimator_utils.py:212]   name = encoder/layer_5/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.223543 140015849629568 estimator_utils.py:212]   name = encoder/layer_5/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.223614 140015849629568 estimator_utils.py:212]   name = encoder/layer_5/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.223685 140015849629568 estimator_utils.py:212]   name = encoder/layer_5/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.223757 140015849629568 estimator_utils.py:212]   name = encoder/layer_5/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.223837 140015849629568 estimator_utils.py:212]   name = encoder/layer_5/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.223910 140015849629568 estimator_utils.py:212]   name = encoder/layer_5/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.223980 140015849629568 estimator_utils.py:212]   name = encoder/layer_5/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.224048 140015849629568 estimator_utils.py:212]   name = encoder/layer_5/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.224118 140015849629568 estimator_utils.py:212]   name = encoder/layer_5/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.224192 140015849629568 estimator_utils.py:212]   name = encoder/layer_6/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.224261 140015849629568 estimator_utils.py:212]   name = encoder/layer_6/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.224330 140015849629568 estimator_utils.py:212]   name = encoder/layer_6/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.224400 140015849629568 estimator_utils.py:212]   name = encoder/layer_6/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.224472 140015849629568 estimator_utils.py:212]   name = encoder/layer_6/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.224543 140015849629568 estimator_utils.py:212]   name = encoder/layer_6/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.224614 140015849629568 estimator_utils.py:212]   name = encoder/layer_6/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.224684 140015849629568 estimator_utils.py:212]   name = encoder/layer_6/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.224752 140015849629568 estimator_utils.py:212]   name = encoder/layer_6/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.224822 140015849629568 estimator_utils.py:212]   name = encoder/layer_6/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.224906 140015849629568 estimator_utils.py:212]   name = encoder/layer_6/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.224975 140015849629568 estimator_utils.py:212]   name = encoder/layer_6/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.225044 140015849629568 estimator_utils.py:212]   name = encoder/layer_7/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.225114 140015849629568 estimator_utils.py:212]   name = encoder/layer_7/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.225188 140015849629568 estimator_utils.py:212]   name = encoder/layer_7/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.225260 140015849629568 estimator_utils.py:212]   name = encoder/layer_7/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.225331 140015849629568 estimator_utils.py:212]   name = encoder/layer_7/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.225402 140015849629568 estimator_utils.py:212]   name = encoder/layer_7/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.225478 140015849629568 estimator_utils.py:212]   name = encoder/layer_7/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.225547 140015849629568 estimator_utils.py:212]   name = encoder/layer_7/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.225617 140015849629568 estimator_utils.py:212]   name = encoder/layer_7/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.225689 140015849629568 estimator_utils.py:212]   name = encoder/layer_7/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.225757 140015849629568 estimator_utils.py:212]   name = encoder/layer_7/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.225837 140015849629568 estimator_utils.py:212]   name = encoder/layer_7/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.225910 140015849629568 estimator_utils.py:212]   name = encoder/layer_8/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.225978 140015849629568 estimator_utils.py:212]   name = encoder/layer_8/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.226045 140015849629568 estimator_utils.py:212]   name = encoder/layer_8/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.226116 140015849629568 estimator_utils.py:212]   name = encoder/layer_8/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.226195 140015849629568 estimator_utils.py:212]   name = encoder/layer_8/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.226269 140015849629568 estimator_utils.py:212]   name = encoder/layer_8/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.226341 140015849629568 estimator_utils.py:212]   name = encoder/layer_8/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.226409 140015849629568 estimator_utils.py:212]   name = encoder/layer_8/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.226477 140015849629568 estimator_utils.py:212]   name = encoder/layer_8/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.226546 140015849629568 estimator_utils.py:212]   name = encoder/layer_8/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.226614 140015849629568 estimator_utils.py:212]   name = encoder/layer_8/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.226688 140015849629568 estimator_utils.py:212]   name = encoder/layer_8/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.226755 140015849629568 estimator_utils.py:212]   name = encoder/layer_9/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.226824 140015849629568 estimator_utils.py:212]   name = encoder/layer_9/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.226906 140015849629568 estimator_utils.py:212]   name = encoder/layer_9/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.226976 140015849629568 estimator_utils.py:212]   name = encoder/layer_9/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.227048 140015849629568 estimator_utils.py:212]   name = encoder/layer_9/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.227120 140015849629568 estimator_utils.py:212]   name = encoder/layer_9/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.227197 140015849629568 estimator_utils.py:212]   name = encoder/layer_9/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.227270 140015849629568 estimator_utils.py:212]   name = encoder/layer_9/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.227340 140015849629568 estimator_utils.py:212]   name = encoder/layer_9/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.227413 140015849629568 estimator_utils.py:212]   name = encoder/layer_9/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.227483 140015849629568 estimator_utils.py:212]   name = encoder/layer_9/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.231266 140015849629568 estimator_utils.py:212]   name = encoder/layer_9/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.231428 140015849629568 estimator_utils.py:212]   name = encoder/layer_10/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.231549 140015849629568 estimator_utils.py:212]   name = encoder/layer_10/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.231663 140015849629568 estimator_utils.py:212]   name = encoder/layer_10/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.231776 140015849629568 estimator_utils.py:212]   name = encoder/layer_10/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.231908 140015849629568 estimator_utils.py:212]   name = encoder/layer_10/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.232019 140015849629568 estimator_utils.py:212]   name = encoder/layer_10/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.232125 140015849629568 estimator_utils.py:212]   name = encoder/layer_10/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.232243 140015849629568 estimator_utils.py:212]   name = encoder/layer_10/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.232332 140015849629568 estimator_utils.py:212]   name = encoder/layer_10/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.232419 140015849629568 estimator_utils.py:212]   name = encoder/layer_10/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.232501 140015849629568 estimator_utils.py:212]   name = encoder/layer_10/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.232587 140015849629568 estimator_utils.py:212]   name = encoder/layer_10/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.232674 140015849629568 estimator_utils.py:212]   name = encoder/layer_11/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.232764 140015849629568 estimator_utils.py:212]   name = encoder/layer_11/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.232866 140015849629568 estimator_utils.py:212]   name = encoder/layer_11/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.232968 140015849629568 estimator_utils.py:212]   name = encoder/layer_11/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.233064 140015849629568 estimator_utils.py:212]   name = encoder/layer_11/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.233180 140015849629568 estimator_utils.py:212]   name = encoder/layer_11/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.233288 140015849629568 estimator_utils.py:212]   name = encoder/layer_11/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.233381 140015849629568 estimator_utils.py:212]   name = encoder/layer_11/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.233472 140015849629568 estimator_utils.py:212]   name = encoder/layer_11/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.233570 140015849629568 estimator_utils.py:212]   name = encoder/layer_11/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.233664 140015849629568 estimator_utils.py:212]   name = encoder/layer_11/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.233762 140015849629568 estimator_utils.py:212]   name = encoder/layer_11/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.233869 140015849629568 estimator_utils.py:212]   name = encoder/layer_12/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.233970 140015849629568 estimator_utils.py:212]   name = encoder/layer_12/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.234064 140015849629568 estimator_utils.py:212]   name = encoder/layer_12/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.234170 140015849629568 estimator_utils.py:212]   name = encoder/layer_12/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.234268 140015849629568 estimator_utils.py:212]   name = encoder/layer_12/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.234343 140015849629568 estimator_utils.py:212]   name = encoder/layer_12/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.234415 140015849629568 estimator_utils.py:212]   name = encoder/layer_12/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.234487 140015849629568 estimator_utils.py:212]   name = encoder/layer_12/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.234560 140015849629568 estimator_utils.py:212]   name = encoder/layer_12/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.234634 140015849629568 estimator_utils.py:212]   name = encoder/layer_12/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.234707 140015849629568 estimator_utils.py:212]   name = encoder/layer_12/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.234782 140015849629568 estimator_utils.py:212]   name = encoder/layer_12/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.234865 140015849629568 estimator_utils.py:212]   name = encoder/layer_13/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.234935 140015849629568 estimator_utils.py:212]   name = encoder/layer_13/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.235006 140015849629568 estimator_utils.py:212]   name = encoder/layer_13/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.235079 140015849629568 estimator_utils.py:212]   name = encoder/layer_13/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.235158 140015849629568 estimator_utils.py:212]   name = encoder/layer_13/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.235232 140015849629568 estimator_utils.py:212]   name = encoder/layer_13/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.235307 140015849629568 estimator_utils.py:212]   name = encoder/layer_13/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.235378 140015849629568 estimator_utils.py:212]   name = encoder/layer_13/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.235447 140015849629568 estimator_utils.py:212]   name = encoder/layer_13/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.235520 140015849629568 estimator_utils.py:212]   name = encoder/layer_13/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.235591 140015849629568 estimator_utils.py:212]   name = encoder/layer_13/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.235665 140015849629568 estimator_utils.py:212]   name = encoder/layer_13/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.235737 140015849629568 estimator_utils.py:212]   name = encoder/layer_14/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.235808 140015849629568 estimator_utils.py:212]   name = encoder/layer_14/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.235888 140015849629568 estimator_utils.py:212]   name = encoder/layer_14/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.235963 140015849629568 estimator_utils.py:212]   name = encoder/layer_14/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.236036 140015849629568 estimator_utils.py:212]   name = encoder/layer_14/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.236109 140015849629568 estimator_utils.py:212]   name = encoder/layer_14/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.236192 140015849629568 estimator_utils.py:212]   name = encoder/layer_14/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.236264 140015849629568 estimator_utils.py:212]   name = encoder/layer_14/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.236334 140015849629568 estimator_utils.py:212]   name = encoder/layer_14/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.236406 140015849629568 estimator_utils.py:212]   name = encoder/layer_14/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.236476 140015849629568 estimator_utils.py:212]   name = encoder/layer_14/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.236548 140015849629568 estimator_utils.py:212]   name = encoder/layer_14/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.236618 140015849629568 estimator_utils.py:212]   name = encoder/layer_15/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.236689 140015849629568 estimator_utils.py:212]   name = encoder/layer_15/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.236760 140015849629568 estimator_utils.py:212]   name = encoder/layer_15/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.236842 140015849629568 estimator_utils.py:212]   name = encoder/layer_15/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.236915 140015849629568 estimator_utils.py:212]   name = encoder/layer_15/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.236990 140015849629568 estimator_utils.py:212]   name = encoder/layer_15/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.237064 140015849629568 estimator_utils.py:212]   name = encoder/layer_15/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.237134 140015849629568 estimator_utils.py:212]   name = encoder/layer_15/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.237212 140015849629568 estimator_utils.py:212]   name = encoder/layer_15/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.237285 140015849629568 estimator_utils.py:212]   name = encoder/layer_15/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.237355 140015849629568 estimator_utils.py:212]   name = encoder/layer_15/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.237428 140015849629568 estimator_utils.py:212]   name = encoder/layer_15/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.237498 140015849629568 estimator_utils.py:212]   name = encoder/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.237576 140015849629568 estimator_utils.py:212]   name = encoder/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.237646 140015849629568 estimator_utils.py:212]   name = decoder/layer_0/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.237719 140015849629568 estimator_utils.py:212]   name = decoder/layer_0/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.237791 140015849629568 estimator_utils.py:212]   name = decoder/layer_0/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.237872 140015849629568 estimator_utils.py:212]   name = decoder/layer_0/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.237946 140015849629568 estimator_utils.py:212]   name = decoder/layer_0/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.238020 140015849629568 estimator_utils.py:212]   name = decoder/layer_0/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.238094 140015849629568 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.238171 140015849629568 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.238241 140015849629568 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.238315 140015849629568 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.238389 140015849629568 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.238462 140015849629568 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.238536 140015849629568 estimator_utils.py:212]   name = decoder/layer_0/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.238606 140015849629568 estimator_utils.py:212]   name = decoder/layer_0/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.238677 140015849629568 estimator_utils.py:212]   name = decoder/layer_0/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.238750 140015849629568 estimator_utils.py:212]   name = decoder/layer_0/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.238821 140015849629568 estimator_utils.py:212]   name = decoder/layer_0/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.238902 140015849629568 estimator_utils.py:212]   name = decoder/layer_0/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.238975 140015849629568 estimator_utils.py:212]   name = decoder/layer_1/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.239044 140015849629568 estimator_utils.py:212]   name = decoder/layer_1/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.239113 140015849629568 estimator_utils.py:212]   name = decoder/layer_1/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.239192 140015849629568 estimator_utils.py:212]   name = decoder/layer_1/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.239273 140015849629568 estimator_utils.py:212]   name = decoder/layer_1/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.239348 140015849629568 estimator_utils.py:212]   name = decoder/layer_1/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.239422 140015849629568 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.239492 140015849629568 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.239562 140015849629568 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.239635 140015849629568 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.239709 140015849629568 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.239782 140015849629568 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.239864 140015849629568 estimator_utils.py:212]   name = decoder/layer_1/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.239936 140015849629568 estimator_utils.py:212]   name = decoder/layer_1/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.240007 140015849629568 estimator_utils.py:212]   name = decoder/layer_1/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.240079 140015849629568 estimator_utils.py:212]   name = decoder/layer_1/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.240165 140015849629568 estimator_utils.py:212]   name = decoder/layer_1/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.240276 140015849629568 estimator_utils.py:212]   name = decoder/layer_1/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.240358 140015849629568 estimator_utils.py:212]   name = decoder/layer_2/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.240443 140015849629568 estimator_utils.py:212]   name = decoder/layer_2/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.240524 140015849629568 estimator_utils.py:212]   name = decoder/layer_2/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.240609 140015849629568 estimator_utils.py:212]   name = decoder/layer_2/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.240694 140015849629568 estimator_utils.py:212]   name = decoder/layer_2/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.240779 140015849629568 estimator_utils.py:212]   name = decoder/layer_2/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.240875 140015849629568 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.240958 140015849629568 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.241040 140015849629568 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.241124 140015849629568 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.241224 140015849629568 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.241328 140015849629568 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.241410 140015849629568 estimator_utils.py:212]   name = decoder/layer_2/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.241480 140015849629568 estimator_utils.py:212]   name = decoder/layer_2/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.241550 140015849629568 estimator_utils.py:212]   name = decoder/layer_2/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.241624 140015849629568 estimator_utils.py:212]   name = decoder/layer_2/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.241695 140015849629568 estimator_utils.py:212]   name = decoder/layer_2/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.241768 140015849629568 estimator_utils.py:212]   name = decoder/layer_2/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.332492 140015849629568 estimator_utils.py:212]   name = decoder/layer_3/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.332652 140015849629568 estimator_utils.py:212]   name = decoder/layer_3/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.332785 140015849629568 estimator_utils.py:212]   name = decoder/layer_3/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.332934 140015849629568 estimator_utils.py:212]   name = decoder/layer_3/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.333051 140015849629568 estimator_utils.py:212]   name = decoder/layer_3/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.333172 140015849629568 estimator_utils.py:212]   name = decoder/layer_3/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.333285 140015849629568 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.333382 140015849629568 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.333477 140015849629568 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.333576 140015849629568 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.333680 140015849629568 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.333781 140015849629568 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.333900 140015849629568 estimator_utils.py:212]   name = decoder/layer_3/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.334002 140015849629568 estimator_utils.py:212]   name = decoder/layer_3/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.334095 140015849629568 estimator_utils.py:212]   name = decoder/layer_3/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.334207 140015849629568 estimator_utils.py:212]   name = decoder/layer_3/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.334306 140015849629568 estimator_utils.py:212]   name = decoder/layer_3/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.334389 140015849629568 estimator_utils.py:212]   name = decoder/layer_3/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.334459 140015849629568 estimator_utils.py:212]   name = decoder/layer_4/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.334525 140015849629568 estimator_utils.py:212]   name = decoder/layer_4/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.334595 140015849629568 estimator_utils.py:212]   name = decoder/layer_4/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.334670 140015849629568 estimator_utils.py:212]   name = decoder/layer_4/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.334744 140015849629568 estimator_utils.py:212]   name = decoder/layer_4/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.334817 140015849629568 estimator_utils.py:212]   name = decoder/layer_4/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.334908 140015849629568 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.334978 140015849629568 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.335048 140015849629568 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.335121 140015849629568 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.335209 140015849629568 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.335284 140015849629568 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.335357 140015849629568 estimator_utils.py:212]   name = decoder/layer_4/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.335427 140015849629568 estimator_utils.py:212]   name = decoder/layer_4/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.335497 140015849629568 estimator_utils.py:212]   name = decoder/layer_4/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.335569 140015849629568 estimator_utils.py:212]   name = decoder/layer_4/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.335639 140015849629568 estimator_utils.py:212]   name = decoder/layer_4/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.335711 140015849629568 estimator_utils.py:212]   name = decoder/layer_4/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.335783 140015849629568 estimator_utils.py:212]   name = decoder/layer_5/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.335865 140015849629568 estimator_utils.py:212]   name = decoder/layer_5/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.335935 140015849629568 estimator_utils.py:212]   name = decoder/layer_5/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.336014 140015849629568 estimator_utils.py:212]   name = decoder/layer_5/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.336086 140015849629568 estimator_utils.py:212]   name = decoder/layer_5/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.336165 140015849629568 estimator_utils.py:212]   name = decoder/layer_5/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.336237 140015849629568 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.336308 140015849629568 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.336377 140015849629568 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.336449 140015849629568 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.336522 140015849629568 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.336594 140015849629568 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.336665 140015849629568 estimator_utils.py:212]   name = decoder/layer_5/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.336735 140015849629568 estimator_utils.py:212]   name = decoder/layer_5/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.336805 140015849629568 estimator_utils.py:212]   name = decoder/layer_5/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.336897 140015849629568 estimator_utils.py:212]   name = decoder/layer_5/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.336966 140015849629568 estimator_utils.py:212]   name = decoder/layer_5/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.337038 140015849629568 estimator_utils.py:212]   name = decoder/layer_5/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.337108 140015849629568 estimator_utils.py:212]   name = decoder/layer_6/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.337183 140015849629568 estimator_utils.py:212]   name = decoder/layer_6/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.337254 140015849629568 estimator_utils.py:212]   name = decoder/layer_6/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.337326 140015849629568 estimator_utils.py:212]   name = decoder/layer_6/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.337398 140015849629568 estimator_utils.py:212]   name = decoder/layer_6/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.337470 140015849629568 estimator_utils.py:212]   name = decoder/layer_6/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.337543 140015849629568 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.337611 140015849629568 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.337680 140015849629568 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.337754 140015849629568 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.337836 140015849629568 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.337913 140015849629568 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.337986 140015849629568 estimator_utils.py:212]   name = decoder/layer_6/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.338057 140015849629568 estimator_utils.py:212]   name = decoder/layer_6/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.338125 140015849629568 estimator_utils.py:212]   name = decoder/layer_6/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.338205 140015849629568 estimator_utils.py:212]   name = decoder/layer_6/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.338276 140015849629568 estimator_utils.py:212]   name = decoder/layer_6/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.338347 140015849629568 estimator_utils.py:212]   name = decoder/layer_6/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.338417 140015849629568 estimator_utils.py:212]   name = decoder/layer_7/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.338485 140015849629568 estimator_utils.py:212]   name = decoder/layer_7/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.338552 140015849629568 estimator_utils.py:212]   name = decoder/layer_7/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.338624 140015849629568 estimator_utils.py:212]   name = decoder/layer_7/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.338697 140015849629568 estimator_utils.py:212]   name = decoder/layer_7/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.338772 140015849629568 estimator_utils.py:212]   name = decoder/layer_7/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.338857 140015849629568 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.338928 140015849629568 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.339002 140015849629568 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.339075 140015849629568 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.339154 140015849629568 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.339229 140015849629568 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.339304 140015849629568 estimator_utils.py:212]   name = decoder/layer_7/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.339377 140015849629568 estimator_utils.py:212]   name = decoder/layer_7/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.339449 140015849629568 estimator_utils.py:212]   name = decoder/layer_7/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.339522 140015849629568 estimator_utils.py:212]   name = decoder/layer_7/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.339593 140015849629568 estimator_utils.py:212]   name = decoder/layer_7/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.339667 140015849629568 estimator_utils.py:212]   name = decoder/layer_7/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.339738 140015849629568 estimator_utils.py:212]   name = decoder/layer_8/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.339806 140015849629568 estimator_utils.py:212]   name = decoder/layer_8/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.339899 140015849629568 estimator_utils.py:212]   name = decoder/layer_8/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.339972 140015849629568 estimator_utils.py:212]   name = decoder/layer_8/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.340045 140015849629568 estimator_utils.py:212]   name = decoder/layer_8/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.340119 140015849629568 estimator_utils.py:212]   name = decoder/layer_8/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.340238 140015849629568 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.340320 140015849629568 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.340402 140015849629568 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.340490 140015849629568 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.340575 140015849629568 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.340661 140015849629568 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.340748 140015849629568 estimator_utils.py:212]   name = decoder/layer_8/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.340842 140015849629568 estimator_utils.py:212]   name = decoder/layer_8/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.340923 140015849629568 estimator_utils.py:212]   name = decoder/layer_8/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.341008 140015849629568 estimator_utils.py:212]   name = decoder/layer_8/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.341090 140015849629568 estimator_utils.py:212]   name = decoder/layer_8/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.341179 140015849629568 estimator_utils.py:212]   name = decoder/layer_8/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.341263 140015849629568 estimator_utils.py:212]   name = decoder/layer_9/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.341365 140015849629568 estimator_utils.py:212]   name = decoder/layer_9/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.341435 140015849629568 estimator_utils.py:212]   name = decoder/layer_9/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.341508 140015849629568 estimator_utils.py:212]   name = decoder/layer_9/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.341581 140015849629568 estimator_utils.py:212]   name = decoder/layer_9/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.341655 140015849629568 estimator_utils.py:212]   name = decoder/layer_9/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.341730 140015849629568 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.341800 140015849629568 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.341883 140015849629568 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.341959 140015849629568 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.342032 140015849629568 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.342105 140015849629568 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.342192 140015849629568 estimator_utils.py:212]   name = decoder/layer_9/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.342264 140015849629568 estimator_utils.py:212]   name = decoder/layer_9/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.342333 140015849629568 estimator_utils.py:212]   name = decoder/layer_9/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.433445 140015849629568 estimator_utils.py:212]   name = decoder/layer_9/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.433609 140015849629568 estimator_utils.py:212]   name = decoder/layer_9/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.433751 140015849629568 estimator_utils.py:212]   name = decoder/layer_9/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.433883 140015849629568 estimator_utils.py:212]   name = decoder/layer_10/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.433999 140015849629568 estimator_utils.py:212]   name = decoder/layer_10/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.434098 140015849629568 estimator_utils.py:212]   name = decoder/layer_10/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.434213 140015849629568 estimator_utils.py:212]   name = decoder/layer_10/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.434314 140015849629568 estimator_utils.py:212]   name = decoder/layer_10/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.434404 140015849629568 estimator_utils.py:212]   name = decoder/layer_10/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.434489 140015849629568 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.434562 140015849629568 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.434629 140015849629568 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.434700 140015849629568 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.434767 140015849629568 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.434847 140015849629568 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.434921 140015849629568 estimator_utils.py:212]   name = decoder/layer_10/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.434986 140015849629568 estimator_utils.py:212]   name = decoder/layer_10/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.435051 140015849629568 estimator_utils.py:212]   name = decoder/layer_10/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.435121 140015849629568 estimator_utils.py:212]   name = decoder/layer_10/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.435227 140015849629568 estimator_utils.py:212]   name = decoder/layer_10/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.435322 140015849629568 estimator_utils.py:212]   name = decoder/layer_10/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.435406 140015849629568 estimator_utils.py:212]   name = decoder/layer_11/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.435493 140015849629568 estimator_utils.py:212]   name = decoder/layer_11/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.435578 140015849629568 estimator_utils.py:212]   name = decoder/layer_11/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.435667 140015849629568 estimator_utils.py:212]   name = decoder/layer_11/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.435761 140015849629568 estimator_utils.py:212]   name = decoder/layer_11/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.435864 140015849629568 estimator_utils.py:212]   name = decoder/layer_11/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.435948 140015849629568 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.436028 140015849629568 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.436101 140015849629568 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.436192 140015849629568 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.436273 140015849629568 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.436350 140015849629568 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.436429 140015849629568 estimator_utils.py:212]   name = decoder/layer_11/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.436504 140015849629568 estimator_utils.py:212]   name = decoder/layer_11/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.436582 140015849629568 estimator_utils.py:212]   name = decoder/layer_11/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.436670 140015849629568 estimator_utils.py:212]   name = decoder/layer_11/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.436751 140015849629568 estimator_utils.py:212]   name = decoder/layer_11/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.436852 140015849629568 estimator_utils.py:212]   name = decoder/layer_11/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.436933 140015849629568 estimator_utils.py:212]   name = decoder/layer_12/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.437003 140015849629568 estimator_utils.py:212]   name = decoder/layer_12/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.437070 140015849629568 estimator_utils.py:212]   name = decoder/layer_12/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.437149 140015849629568 estimator_utils.py:212]   name = decoder/layer_12/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.437220 140015849629568 estimator_utils.py:212]   name = decoder/layer_12/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.437291 140015849629568 estimator_utils.py:212]   name = decoder/layer_12/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.437362 140015849629568 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.437431 140015849629568 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.437505 140015849629568 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.437584 140015849629568 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.437662 140015849629568 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.437745 140015849629568 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.437819 140015849629568 estimator_utils.py:212]   name = decoder/layer_12/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.437910 140015849629568 estimator_utils.py:212]   name = decoder/layer_12/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.437981 140015849629568 estimator_utils.py:212]   name = decoder/layer_12/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.438057 140015849629568 estimator_utils.py:212]   name = decoder/layer_12/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.438132 140015849629568 estimator_utils.py:212]   name = decoder/layer_12/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.438220 140015849629568 estimator_utils.py:212]   name = decoder/layer_12/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.438289 140015849629568 estimator_utils.py:212]   name = decoder/layer_13/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.438360 140015849629568 estimator_utils.py:212]   name = decoder/layer_13/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.438428 140015849629568 estimator_utils.py:212]   name = decoder/layer_13/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.438506 140015849629568 estimator_utils.py:212]   name = decoder/layer_13/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.438580 140015849629568 estimator_utils.py:212]   name = decoder/layer_13/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.438657 140015849629568 estimator_utils.py:212]   name = decoder/layer_13/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.438735 140015849629568 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.438811 140015849629568 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.438904 140015849629568 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.438982 140015849629568 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.439058 140015849629568 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.439132 140015849629568 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.439222 140015849629568 estimator_utils.py:212]   name = decoder/layer_13/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.439300 140015849629568 estimator_utils.py:212]   name = decoder/layer_13/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.439390 140015849629568 estimator_utils.py:212]   name = decoder/layer_13/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.439485 140015849629568 estimator_utils.py:212]   name = decoder/layer_13/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.439578 140015849629568 estimator_utils.py:212]   name = decoder/layer_13/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.439678 140015849629568 estimator_utils.py:212]   name = decoder/layer_13/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.439776 140015849629568 estimator_utils.py:212]   name = decoder/layer_14/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.439886 140015849629568 estimator_utils.py:212]   name = decoder/layer_14/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.439987 140015849629568 estimator_utils.py:212]   name = decoder/layer_14/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.440090 140015849629568 estimator_utils.py:212]   name = decoder/layer_14/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.440250 140015849629568 estimator_utils.py:212]   name = decoder/layer_14/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.440375 140015849629568 estimator_utils.py:212]   name = decoder/layer_14/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.440502 140015849629568 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.440621 140015849629568 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.440739 140015849629568 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.440872 140015849629568 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.440992 140015849629568 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.441100 140015849629568 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.441219 140015849629568 estimator_utils.py:212]   name = decoder/layer_14/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.441350 140015849629568 estimator_utils.py:212]   name = decoder/layer_14/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.441440 140015849629568 estimator_utils.py:212]   name = decoder/layer_14/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.441535 140015849629568 estimator_utils.py:212]   name = decoder/layer_14/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.441618 140015849629568 estimator_utils.py:212]   name = decoder/layer_14/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.441696 140015849629568 estimator_utils.py:212]   name = decoder/layer_14/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.441766 140015849629568 estimator_utils.py:212]   name = decoder/layer_15/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.441849 140015849629568 estimator_utils.py:212]   name = decoder/layer_15/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.441924 140015849629568 estimator_utils.py:212]   name = decoder/layer_15/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.441995 140015849629568 estimator_utils.py:212]   name = decoder/layer_15/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.442071 140015849629568 estimator_utils.py:212]   name = decoder/layer_15/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.442189 140015849629568 estimator_utils.py:212]   name = decoder/layer_15/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.442285 140015849629568 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.442373 140015849629568 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.442454 140015849629568 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.442531 140015849629568 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.442607 140015849629568 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.442705 140015849629568 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.442797 140015849629568 estimator_utils.py:212]   name = decoder/layer_15/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.442889 140015849629568 estimator_utils.py:212]   name = decoder/layer_15/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.442965 140015849629568 estimator_utils.py:212]   name = decoder/layer_15/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0323 09:43:32.443040 140015849629568 estimator_utils.py:212]   name = decoder/layer_15/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0323 09:43:32.443119 140015849629568 estimator_utils.py:212]   name = decoder/layer_15/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0323 09:43:32.443209 140015849629568 estimator_utils.py:212]   name = decoder/layer_15/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.443305 140015849629568 estimator_utils.py:212]   name = decoder/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0323 09:43:32.443403 140015849629568 estimator_utils.py:212]   name = decoder/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    INFO:tensorflow:Done calling model_fn.\n    I0323 09:43:32.462981 140015849629568 estimator.py:1150] Done calling model_fn.\n    INFO:tensorflow:Create CheckpointSaverHook.\n    I0323 09:43:32.464104 140015849629568 basic_session_run_hooks.py:541] Create CheckpointSaverHook.\n    INFO:tensorflow:Graph was finalized.\n    I0323 09:43:39.422322 140015849629568 monitored_session.py:240] Graph was finalized.\n    2021-03-23 09:43:39.433174: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2199995000 Hz\n    2021-03-23 09:43:39.433499: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x555afaa73100 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n    2021-03-23 09:43:39.433628: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version\n    2021-03-23 09:43:39.554076: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n    2021-03-23 09:43:39.554751: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x555afaa73480 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n    2021-03-23 09:43:39.554781: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Tesla T4, Compute Capability 7.5\n    2021-03-23 09:43:39.555077: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n    2021-03-23 09:43:39.555607: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \n    name: Tesla T4 major: 7 minor: 5 memoryClockRate(GHz): 1.59\n    pciBusID: 0000:00:04.0\n    2021-03-23 09:43:39.555703: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n    2021-03-23 09:43:39.555736: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n    2021-03-23 09:43:39.555765: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n    2021-03-23 09:43:39.555791: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n    2021-03-23 09:43:39.555814: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n    2021-03-23 09:43:39.555854: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n    2021-03-23 09:43:39.555886: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n    2021-03-23 09:43:39.555985: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n    2021-03-23 09:43:39.556568: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n    2021-03-23 09:43:39.557075: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n    2021-03-23 09:43:39.560350: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n    2021-03-23 09:43:39.562783: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n    2021-03-23 09:43:39.562817: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186]      0 \n    2021-03-23 09:43:39.562843: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0:   N \n    2021-03-23 09:43:39.564132: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n    2021-03-23 09:43:39.564743: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n    2021-03-23 09:43:39.565282: W tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:39] Overriding allow_growth setting because the TF_FORCE_GPU_ALLOW_GROWTH environment variable is set. Original config value was 0.\n    2021-03-23 09:43:39.565326: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 14257 MB memory) -> physical GPU (device: 0, name: Tesla T4, pci bus id: 0000:00:04.0, compute capability: 7.5)\n    INFO:tensorflow:Running local_init_op.\n    I0323 09:43:53.398160 140015849629568 session_manager.py:500] Running local_init_op.\n    INFO:tensorflow:Done running local_init_op.\n    I0323 09:43:54.111346 140015849629568 session_manager.py:502] Done running local_init_op.\n    INFO:tensorflow:Saving checkpoints for 0 into ckpt/aeslc/model.ckpt.\n    I0323 09:44:13.725221 140015849629568 basic_session_run_hooks.py:606] Saving checkpoints for 0 into ckpt/aeslc/model.ckpt.\n    2021-03-23 09:44:51.040895: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 16777216 exceeds 10% of system memory.\n    2021-03-23 09:44:51.072007: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 16777216 exceeds 10% of system memory.\n    2021-03-23 09:44:51.072070: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 16777216 exceeds 10% of system memory.\n    2021-03-23 09:44:51.277187: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 16777216 exceeds 10% of system memory.\n    2021-03-23 09:44:51.281719: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 16777216 exceeds 10% of system memory.\n    2021-03-23 09:45:26.473739: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n    INFO:tensorflow:global_step/sec: 0.0242657\n    I0323 09:46:18.352407 140015849629568 tpu_estimator.py:2307] global_step/sec: 0.0242657\n    INFO:tensorflow:examples/sec: 0.194126\n    I0323 09:46:18.353016 140015849629568 tpu_estimator.py:2308] examples/sec: 0.194126\n    INFO:tensorflow:global_step/sec: 0.432297\n    I0323 09:46:20.665547 140015849629568 tpu_estimator.py:2307] global_step/sec: 0.432297\n    INFO:tensorflow:examples/sec: 3.45838\n    I0323 09:46:20.665931 140015849629568 tpu_estimator.py:2308] examples/sec: 3.45838\n    INFO:tensorflow:global_step/sec: 0.424376\n    I0323 09:46:23.021980 140015849629568 tpu_estimator.py:2307] global_step/sec: 0.424376\n    INFO:tensorflow:examples/sec: 3.39501\n    I0323 09:46:23.022383 140015849629568 tpu_estimator.py:2308] examples/sec: 3.39501\n    INFO:tensorflow:global_step/sec: 0.428958\n    I0323 09:46:25.353182 140015849629568 tpu_estimator.py:2307] global_step/sec: 0.428958\n    INFO:tensorflow:examples/sec: 3.43166\n    I0323 09:46:25.353410 140015849629568 tpu_estimator.py:2308] examples/sec: 3.43166\n    INFO:tensorflow:global_step/sec: 0.42771\n    I0323 09:46:27.691224 140015849629568 tpu_estimator.py:2307] global_step/sec: 0.42771\n    INFO:tensorflow:examples/sec: 3.42168\n    I0323 09:46:27.691456 140015849629568 tpu_estimator.py:2308] examples/sec: 3.42168\n    INFO:tensorflow:global_step/sec: 0.425015\n    I0323 09:46:30.044064 140015849629568 tpu_estimator.py:2307] global_step/sec: 0.425015\n    INFO:tensorflow:examples/sec: 3.40012\n    I0323 09:46:30.044290 140015849629568 tpu_estimator.py:2308] examples/sec: 3.40012\n    INFO:tensorflow:global_step/sec: 0.425547\n    I0323 09:46:32.394001 140015849629568 tpu_estimator.py:2307] global_step/sec: 0.425547\n    INFO:tensorflow:examples/sec: 3.40438\n    I0323 09:46:32.394251 140015849629568 tpu_estimator.py:2308] examples/sec: 3.40438\n    INFO:tensorflow:global_step/sec: 0.423838\n    I0323 09:46:34.753371 140015849629568 tpu_estimator.py:2307] global_step/sec: 0.423838\n    INFO:tensorflow:examples/sec: 3.3907\n    I0323 09:46:34.753606 140015849629568 tpu_estimator.py:2308] examples/sec: 3.3907\n    INFO:tensorflow:global_step/sec: 0.419245\n    I0323 09:46:37.138610 140015849629568 tpu_estimator.py:2307] global_step/sec: 0.419245\n    INFO:tensorflow:examples/sec: 3.35396\n    I0323 09:46:37.138849 140015849629568 tpu_estimator.py:2308] examples/sec: 3.35396\n    INFO:tensorflow:global_step/sec: 0.420715\n    I0323 09:46:39.515527 140015849629568 tpu_estimator.py:2307] global_step/sec: 0.420715\n    INFO:tensorflow:examples/sec: 3.36572\n    I0323 09:46:39.515770 140015849629568 tpu_estimator.py:2308] examples/sec: 3.36572\n    INFO:tensorflow:global_step/sec: 0.417823\n    I0323 09:46:41.908904 140015849629568 tpu_estimator.py:2307] global_step/sec: 0.417823\n    INFO:tensorflow:examples/sec: 3.34258\n    I0323 09:46:41.909526 140015849629568 tpu_estimator.py:2308] examples/sec: 3.34258\n    INFO:tensorflow:global_step/sec: 0.419327\n    I0323 09:46:44.293651 140015849629568 tpu_estimator.py:2307] global_step/sec: 0.419327\n    INFO:tensorflow:examples/sec: 3.35462\n    I0323 09:46:44.293982 140015849629568 tpu_estimator.py:2308] examples/sec: 3.35462\n    INFO:tensorflow:global_step/sec: 0.41948\n    I0323 09:46:46.677553 140015849629568 tpu_estimator.py:2307] global_step/sec: 0.41948\n    INFO:tensorflow:examples/sec: 3.35584\n    I0323 09:46:46.677786 140015849629568 tpu_estimator.py:2308] examples/sec: 3.35584\n    INFO:tensorflow:global_step/sec: 0.41854\n    I0323 09:46:49.066837 140015849629568 tpu_estimator.py:2307] global_step/sec: 0.41854\n    INFO:tensorflow:examples/sec: 3.34832\n    I0323 09:46:49.067070 140015849629568 tpu_estimator.py:2308] examples/sec: 3.34832\n    INFO:tensorflow:global_step/sec: 0.415718\n    I0323 09:46:51.472283 140015849629568 tpu_estimator.py:2307] global_step/sec: 0.415718\n    INFO:tensorflow:examples/sec: 3.32574\n    I0323 09:46:51.472512 140015849629568 tpu_estimator.py:2308] examples/sec: 3.32574\n    INFO:tensorflow:global_step/sec: 0.413858\n    I0323 09:46:53.888569 140015849629568 tpu_estimator.py:2307] global_step/sec: 0.413858\n    INFO:tensorflow:examples/sec: 3.31087\n    I0323 09:46:53.888791 140015849629568 tpu_estimator.py:2308] examples/sec: 3.31087\n    INFO:tensorflow:global_step/sec: 0.41378\n    I0323 09:46:56.305333 140015849629568 tpu_estimator.py:2307] global_step/sec: 0.41378\n    INFO:tensorflow:examples/sec: 3.31024\n    I0323 09:46:56.305731 140015849629568 tpu_estimator.py:2308] examples/sec: 3.31024\n    INFO:tensorflow:global_step/sec: 0.413859\n    I0323 09:46:58.721612 140015849629568 tpu_estimator.py:2307] global_step/sec: 0.413859\n    INFO:tensorflow:examples/sec: 3.31087\n    I0323 09:46:58.722032 140015849629568 tpu_estimator.py:2308] examples/sec: 3.31087\n    INFO:tensorflow:global_step/sec: 0.406715\n    I0323 09:47:01.180323 140015849629568 tpu_estimator.py:2307] global_step/sec: 0.406715\n    INFO:tensorflow:examples/sec: 3.25372\n    I0323 09:47:01.180566 140015849629568 tpu_estimator.py:2308] examples/sec: 3.25372\n\n\n\n```\n!python3 pegasus/bin/evaluate.py --params=aeslc_transformer \\\n--param_overrides=vocab_filename=ckpt/c4.unigram.newline.10pct.96000.model,batch_size=1,beam_size=5,beam_alpha=0.6 \\\n--model_dir=ckpt/aeslc\n```\n", "meta": {"hexsha": "9bc0a6f9e95ecb6799e562e9e5f599a5849861a8", "size": 163782, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "peg_abs_summary.ipynb", "max_stars_repo_name": "vidhya0810/ctrl-sum", "max_stars_repo_head_hexsha": "88c5ae63669a58f81eb18f0db739adc02422a62a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "peg_abs_summary.ipynb", "max_issues_repo_name": "vidhya0810/ctrl-sum", "max_issues_repo_head_hexsha": "88c5ae63669a58f81eb18f0db739adc02422a62a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "peg_abs_summary.ipynb", "max_forks_repo_name": "vidhya0810/ctrl-sum", "max_forks_repo_head_hexsha": "88c5ae63669a58f81eb18f0db739adc02422a62a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 112.8752584425, "max_line_length": 919, "alphanum_fraction": 0.6760510923, "converted": true, "num_tokens": 49191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.0534033271633626, "lm_q1q2_score": 0.01768289578565447}}
{"text": "```python\n# %load ../../preconfig.py\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(color_codes=True)\nplt.rcParams['axes.grid'] = False\n\nimport numpy as np\n#import pandas as pd\n\n#import sklearn\n\n#import itertools\n\nimport logging\nlogger = logging.getLogger()\n\n```\n\n2 MapReduce and the New Software Stack\n=====================\n\n\"big-data\" analysis:\n\n1. manage immense amounts of data quickly.\n\n2. data is extremely regular $\\to$ exploit parallelism.\n\nnew software stack:     \n\"distributed file system\" $\\to$ MapReduce\n\nWhen designing MapReduce algorithms, we often find that the greatest cost is in the communication.\n\n### 2.1 Distributed File Systems\ncommodity hardware + network\n\n#### 2.1.1 Physical Organization of Compute Nodes\n*cluster computing*: the new parallel-computing architecture.\n\n*racks*: compute nodes are stored on racks.\n\ncommunication:\n\n1. The nodes on a single rack are connected by a network, typically gigabit Ethernet. And racks are connected by another level of network or a switch.\n\n2. The bandwidth of *inter-rack* communication is somewhat greater than the *intrarack* Ethernet.\n\n\n```python\nplt.imshow(plt.imread('./res/fig2_1.png'))\n```\n\nthe solution for components failure (loss of node or rack):\n\n1. Files must be stored redundantly.\n\n2. Computations must be divided into tasks.\n\n#### 2.1.2 Large-Scale File-System Organization\nDFS: distributed file system\n\n1. Google File System (GFS)\n\n2. Hadoop Distributed File System (HDFS)\n\n3. CloudStore\n\nIt is typically used as follows:\n\n1. Files can be enormous, possibly a terabyte in size.\n\n2. Files are rarely updated.\n\nmanage:\n\n1. Files are divided into chunks.       \n   Chunks are replicated at different compute nodes of different racks.\n   \n2. *master node* or *name node*: another small file to find the chunks of a file.\n   master node is iteself replicated, and a directory for the file systme as a whole knows where to find its copies.      \n   The directory itself can be replicated, and all participants using the DFS know where the directory copies are.\n\n### 2.2 MapReduce\nAll you need to write are two functions, called Map and Reduce.\n\na MapReduce computation executes as follows:\n\n1. Map function: Map tasks turn the chunk given into a sequence of *key-value* pairs.\n\n2. The key-value pairs from each Map task are collected by a *master controller* and sorted by key.     \n   divide by key: all pairs with same key $\\to$ same Reduce task.\n   \n3. Reduce function: The Reduce tasks work on one key at a time, and combine all the values associated with that key in some way.\n\n\n```python\nplt.imshow(plt.imread('./res/fig2_2.png'))\n```\n\n#### 2.2.1 The Map Tasks\nThe Map function takes an input element as its argument and produces zero or more key-value pairs.\n\n#### 2.2.2 Grouping by Key\nGroup: the key-value pairs are groued by key, which is performed by the system.\n\npartition: hash keys to reduce tasks.\n\n#### 2.2.3 The Reduce Tasks\nreducer: the application of the Reduce function to a single key and its associated list of values.\n\na Reduce task executes one or more reducers.\n\nwhy not to execute each reducer a separate Reduce task for maximum parallelism?\n\n+ There is overhead associated with each task we create.     \n  number of Reduce tasks $<$ number of reducers.\n\n+ There is often significant variation in the lengths of the value lists for different keys, so different reducers take different amount of time. $\\to$ skew.      \n  if keys are sent randomly to less Reduce tasks $\\to$ expect that time is average. $\\to$ number of Reduce tasks $<$ compute nodes.\n\n#### 2.2.4 Combiners\nIf a Reduce function is associative and commutative, (the values to be combined can be combined in any order, with the same result), we can push some of what the reducers do to the Map tasks (combiner).\n\n#### 2.2.5 Details of MapReduce Execution\n\n\n```python\nplt.imshow(plt.imread('./res/fig2_3.png'))\n```\n\n#### 2.2.6 Coping With Node Failures\n1. Master fails $\\to$ restart.\n\n2. Map worker fails $\\to$ all the Map tasks assigned to the worker will have to redone. and also inform each Reduce task about the change.\n\n3. Reduce worker fails. $\\to$ resheduled on another reduce worker later.\n\n#### 2.2.7 Exercises for Section 2.2\n##### (a)\nYes, significant skew exists. The word frequent is not equal in text.\n\n##### (b)\nthe skew should be insignificant.      \n\n10,000 more significant.\n\n##### (c)\n\ncombiner can help reduce skew.\n\n### 2.3 Algorithms Using MapReduce\nOperations that can use MapReduce effectively:\n\n1. very large matrix-vector multiplicatons\n\n2. relational-algebra opertions\n\n#### 2.3.1 Matrix-Vector Multiplication by MapReduce\n\\begin{align}\n    \\mathbf{X}_{1 \\times n} &= \\mathbf{M}_{n \\times n} \\mathbf{v}_{1 \\times n} \\\\\n    x_i &= \\displaystyle \\sum_{j=1}^n m_{ij} v_j \n\\end{align}\n\nWe first assume that $n$ is large, but not so larget that $\\mathbf{v}$ cannot fit in main memory and thus be available to every Map task.\n\n+ Map:\n  1. read $\\mathbf{v}$.\n  2. produces $(i, m_{ij} v_j)$\n  \n+ Reduce:\n  simply sums all the values and produces pair $(i, x_i)$.\n\n#### 2.3.2 If the Vector $\\mathbf{v}$ Cannot Fit in Main Memory\nWe can divide the matrix into vertical *stripes* of equal width and divide the vector into an equal number of horizontal stripes, of the same height.\n\n\n```python\nplt.imshow(plt.imread('./res/fig2_4.png'))\n```\n\nEach Map task is assigned a chunk from one of the stripes of the matrix and gets the entire corresponding stripe of the vector.\n\nparticular application (PageRank calculation) has an additional constraint that the result vector should be partitioned in the same way as the input vector.\n\nWe shall see there that the best strategy involves partitioning the matrix $\\mathbf{M}$ into square blocks, rahter than stripes.\n\n#### 2.3.3 Relational-Algebra Operations\nThere are many operations on data that can be described easily in terms of the common database-query primitives.\n\na *relation* is a table with column headers called *attributes*.\n\nRows of the relation are called *tuples*.\n\nThe set of attributes of a relation is called its *schema*.\n\n$R(A_1, A_2, \\dotsc, A_n)$: the relation name is $R$ and its attributes are $A_1, A_2, \\dotsc, A_n$.\n\n\n```python\nplt.imshow(plt.imread('./res/fig2_5.png'))\n```\n\n*relational algebra*: several standard operations on relations.\n\n1. Selection $\\sigma{C} (R)$: select tuples that satisfy $C$\n   + **Map**: produce $(t, t)$ if $t$ satisfies $C$ where $t \\in R$.\n   + **Reduce**: simple passes each key-value pair to the output.\n\n2. Projection $\\pi_{S} (R)$: produces subset $S$ of the attributed\n   + **Map**: output $(t', t')$ where $t'$ is subset of $t$.\n   + **Reduce**: eliminate duplicates, turns $(t', [t', t', \\dotsc, t'])$ into $(t', t')$.\n     associative and commutative $\\to$ combiner\n\n3. Union, Intersection, and Difference\n   1. Union:\n      + **Map**: turn $t$ into $(t, t)$.\n      + **Reduce**: Produce $(t, t)$ for input $(t, [t])$ or $(t, [t, t])$.\n      \n   2. Intersection:\n      + **Map**: turn $t$ into $(t, t)$.\n      + **Reduce**: produce $(t, t)$ if input $(t, [t, t])$.\n      \n   3. Difference $S - R$:\n      + **Map**: produce $(t, R)$ where $t \\in R$, or $(t, S)$ where $t \\in S$.\n      + **Reduce**: produce $(t, t)$ if input $(t, [R])$.\n\n4. Natural Join $R \\bowtie S$ \n   + **Map**: produce $(b, (R, a))$ for $(a, b) \\in R$, or $(b, (S, c))$ for $(b, c) \\in S$.\n   + **Reduce**: $(a, b, c)$ when input $(b, [(R, a), (S, c)])$.\n\n5. Grouping and Aggregation $\\gamma_{X} (R)$:\n   where $X$ consists of:\n   + a grouping attribute,\n   + an expression $\\theta(A)$\n   \n   Let $R(A, B, C)$, for $\\gamma_{A, \\theta(B)} (R)$:\n   + **Map**: produce $(a, b)$ for each tuple $(a, b, c)$.\n   + **Reduce**: apply the aggregation operator $\\theta$ to the list $[b_1, b_2, \\dotsc, b_n]$ of B-values associated with key $a$.\n\n#### 2.3.9 Matrix Multiplication\n\n$\\mathbf{M} \\times \\mathbf{N}$\n\ngrouping and aggregation\n\n##### two MapReduce step\n1. 1st MapReduce\n   + **Map**: $(j, (M, i, m_{ij}))$ and $(j, (N, k, n_{jk}))$.\n   + **Reduce**: $((i, k), m_{ij} n_{jk})$ for its associated values of each key $j$.\n   \n2. 2nd MapReduce\n   + **Map**: identity\n   + **Reduce**: for each key $(i, k)$, produce the sum of the list of values associated with this key.\n   \n##### one MapReduce step\n+ **Map**:\n  - for each $m_{ij}$, produce all pairs $((i, k), (M, j, m_{ij}))$ for $k = 1, 2, \\dotsc$.     \n  - for each $n_{jk}$, produce all pairs $((i, k), (N, j, n_{jk}))$ for $i = 1, 2, \\dotsc$.\n  \n+ **Reduce**:\n  Each key $(i, k)$ will have an associated list with all the values $(M, j, m_{ij})$ and $(N, j, n_{jk})$, for all possible values of $j$.\n  - connect the two values on the list that have the same values of $j$: An easy way to do this step is to sort by $j$ the values.\n  - then multiply and sum.\n\n#### 2.3.11 Exercises for Section 2.3\nEx 2.3.5\n\n### 2.4 Extensions to MapReduce\nsome extensions and modifications, share the same characteristics:\n1. built on a distributed file system.\n2. very large numbers of tasks, and a small number of user-written functions.\n3. dealing with most of the failures without restart.\n\n#### 2.4.1 Workflow Systems\nidea: two-step workflow (Map, Reduce) $\\to$ any collection of functions\n\ntwo experimental systems\n+ Clustera\n+ Hyracks\n\nadvantage: without need to store the temporary file that is output of one MapReduce job in the distributed file system.\n\n\n```python\nplt.imshow(plt.imread('./res/fig2_6.png'))\n```\n\n#### 2.4.2 Recursive Extensions to MapReduce\nMany large-scale computations are really recursions.\n\nmutually recursive tasks: modify input (flow graphs that are not acyclic), so it is not feasible to simple start when some node failed.\n\n**solution A**: split to two step $\\to$ backup data\n\nExample 2.6\n\n\n```python\nplt.imshow(plt.imread('./res/fig2_7.png'))\n```\n\n#### 2.4.3 Pregel\n**solution B**: backup entire stats of each task **checkpoints**, so recovery the backup point if fail.\n\ncheckpoints is triggered at fixed *supersteps*.\n\n#### 2.4.4 Exercises for Section 2.4\n###### Ex 2.4.1\nfor the prob of a taks, success is $(1-p)^t$, fail is $(1 - (1 - p)^t)$ . So the expected execution time of a task is $(1-p)^t t  + (1 - (1-p)^t) 10 t = 10t - 9t(1-p)^t$.\n\nThus, total expected time is $n(10t - 9t (1-p)^t) = nt(10 - 9 (1-p)^t)$.\n\n\n```python\ndef calc_prob(p, t):\n    return 10 - 9 * ((1 - p)**t)\n\np = np.linspace(0, 1, 100)\n\ny1 = calc_prob(p, 10)\ny2 = calc_prob(p, 100)\nplt.plot(p, y1, 'b', p, y2, 'g')\n```\n\n###### Ex 2.4.2\nsuppose that supersteps should be $n$, the time of one execting a superstep is $t$.\n\n\n\n### 2.5 The Communication Cost Model\nfor many applications, the bottleneck is moving data among tasks.\n\n#### 2.5.1 Communication-Cost for Task Networks\nThe *communication cost* of a task is the size of the input to the task. we shall often use the number of tuples as a measure size, rather than bytes.\n\nThe *communication cost* of an algorithm is the sum of the communication cost of all the tasks implementing that algorithm. We shall focus on the communication cost as the way to measure the efficiency of an algorithm, since the exceptions, where execution time of tasks dominates, are rare in practice.\n\nWe count only input size, and not output size.\n\n#### 2.5.2 Wall-Clock Time\nBesides communication cost, we must also be aware of the importance of *wall-clock time*, the time it takes a prallel algorithm to finish.\n\nThe algorithms shall have the property that the work is divided fairly among the tasks.\n\n#### 2.5.3 Multiway Joins\nexample: $R(A, B) \\bowtie S(B, C) \\bowtie T(C, D)$.\n\nSuppose that the relation $R, S, T$ have sizes $r, s$, and $t$, respectively. and for simplicity, suppose $p$ is the probability that any two tuples in each relations agree on the item they share.\n\n##### Solution 1: general theory\n$\\operatorname{join} \\left ( \\operatorname{join} \\left ( R(A, B) \\bowtie S(B, C) \\right ) \\bowtie T(C, D) \\right )$\nor exchange the sequence of join.\n\n1. 1st MapReduce\n   $\\operatorname{join} \\left ( R(A, B) \\bowtie S(B, C) \\right )$\n   $O(t + prs)$\n\n2. 2nd MapReduce\n   $O(r + s + t + prs)$\n   \n\n##### Solution 2: use a single MapReduce job that joins the three relations at once.\n\nAssume: \n\n+ We plan to use $k$ reducers for the job.\n\n+ $b, c$ represents the number of buckets into which we shall hash $B-$ and $C-$values, respectively.\n\n  - $h(B) \\to b$.\n  \n  - $g(C) \\to c$.\n  \n  we require $b c = k$.\n  \nSo, the reducer corresponding to bucket pair $(i, j)$ is responsible for joining the tuples $R(u, v), S(v, w)$, and $T(w, x)$ whenever $h(v) = i$ and $g(w) = j$.\n\n1. $S(v, w)$ to reducer $(h(v), g(w))$.\n   communication cost: $s$\n\n2. $R(u, v)$ to $c$ reducers $(h(v), c)$.\n   communication cost: $c r$\n\n3. $T(w, x)$ to $b$ reducers $(b, g(w))$.\n   communication cost: $b t$\n   \nThere is also a *fixed* cost $r + s + t$ to make each tuple of each relation be input to one of the Map tasks.\n\nThe problem arises:\n$$\\operatorname{arg \\, min}_{b, c} s + cr + bt \\text{where} bc = k$$\nWe get the solution: $c = \\sqrt{kt / r}$ and $b = \\sqrt{kr / t}$. So $s + cr + bt  = s  + 2 \\sqrt{k r t}$. \n\nIn all, the total communication cost is $r + 2s + t + 2 \\sqrt{k r t}$.\n\n####  2.5.4 Exercises for Section 2.5\n`#todo`\n\n### 2.6 Complexity Theory for MapReduce\nour desire in the section:\n\n+ to shrink the wall-clock time\n\n+ to execute each reducer in main memory\n\n#### 2.6.1 Reducer Size and Replication Rate\ntwo parameters that characterize families of MapReduce algorithms:\n\n1. **reducer size**$q$: the upper bound on the number of values that are allowed to appear in the list associated with a single key.\n   It can be selected with at least two goals in mind:\n   1. By making the reducer size small $\\to$ we get many reducers.\n   2. By making the reducer size small $\\to$ computation in reducer can be exected entirely in the main memory.\n   \n2. **replication rate**$r$: the number of key-value pairs producted by all the Map tasks on all the inputs, divided by the number of inputs. It is the average communication from Map tasks to Reduce tasks per input.\n\n#### 2.6.2 An Example: Similarity Joins\nwe are given a large set of element $X$ and a similarity measure $s(x, y)$ which is symmetric. The output of the algorithm is those pairs whose similarity exceeds a given threshold $t$.     \n\neg: discover similar images in a collection of one million images.    \nsolution:\n1. $(\\{i, j\\}, [P_i, P_j])$\n   this algorithm will fail completely:\n   the reducer size is small, however, the replication rate is 999,999 $\\to$ the communication cost is extremelly large.\n   \n2. We can group pictures into $g$ groups, each of $10^6 / g$ pictures.\n\n#### 2.6.3 A Graph Model for MapReduce Problems\nIn this section, we hope to prove lower bounds on the replication rate. The first step is to introduce a graph model of problems.\n\nFor each problem solvable by a MapReduce algorithm there is:\n\n1. A set of inputs.\n\n2. A set of outputs.\n\n3. A many-many relationship between the inputs and outputs, which describes which inputs are necessary to produce which outputs.\n\n\n```python\nplt.imshow(plt.imread('./res/fig2_9.png'))\n```\n\n#### 2.6.4 Mapping Schemas\n*mapping schema* expresses how outputs are produced by the various reducers. \n\nA mapping schema for a given problem with a given reducer size $q$ is an assignment of inputs to one or more reducers, such that:\n\n1. No reducer is assigned more than $q$ inputs.\n\n2. For every output of the problem, there is at least one reducer that is assigned all the inputs that are related to that output. We say this reducer *covers* the output.\n\n#### 2.6.5 When Not All Inputs Are Present\nThe only way the absense of some inputs makes a difference is that we may wish to rethink the desired value of the reducer size $q$ when we select an algorithm from the family of possible algorithms.\n\n#### 2.6.6 Lower Bounds on Replication Rate\nminimum possible communication is known if we can prove a matching lower bound.\n\nHere is an outline of the technique:\n\n1. Prove an upper bound $g(q)$ on how many outputs a reducer with $q$ inputs can cover.\n\n2. Determine the total number of outputs produced by the problem.\n\n3. Suppose that there are $k$ reducers, and the $i$th reducer has $q_i < q$ inputs. \n   Observe that $\\sum_{i=1}^k g(q_i)$ must be no less than the number of outputs computed in step (2).\n   \n4. Manipulate the inequality from (3) to get a lower bound on $\\sum_{i=1}^k q_i$.\n   Often, the trick used is to replace some factors of $q_i$ by their upper bound $q$, but leave a single factor of $q_i$ in the term for $i$.\n   \n5. Since $\\sum_{i=1}^k q_i$ is the total communication from Map tasks to Reduce tasks, divide to lower bound from (4) on this quantity by the number of inputs.\n   The result is a lower bound on the replication rate.\n\n#### 2.6.7 Case Study: Matrix Multiplication\n\n#### 2.6.8 Exercises for Section 2.6\n", "meta": {"hexsha": "d60b680d8f05a677af1e436cad26d150cea6c223", "size": 410788, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Mining_of_Massive_Datasets/MapReduce_and_the_New_Software_Stack/note.ipynb", "max_stars_repo_name": "ningchi/book_notes", "max_stars_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-12-31T12:10:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T15:49:34.000Z", "max_issues_repo_path": "Mining_of_Massive_Datasets/MapReduce_and_the_New_Software_Stack/note.ipynb", "max_issues_repo_name": "ningchi/book_notes", "max_issues_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-12-05T13:04:14.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-07T16:24:50.000Z", "max_forks_repo_path": "Mining_of_Massive_Datasets/MapReduce_and_the_New_Software_Stack/note.ipynb", "max_forks_repo_name": "ningchi/book_notes", "max_forks_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-06-27T07:19:28.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-19T08:57:35.000Z", "avg_line_length": 429.6945606695, "max_line_length": 66044, "alphanum_fraction": 0.925567446, "converted": true, "num_tokens": 4703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14608725076600917, "lm_q2_score": 0.12085324515618749, "lm_q1q2_score": 0.017655118331017947}}
{"text": "```python\n!pip install coremltools\n```\n\n    Requirement already satisfied: coremltools in /usr/local/lib/python3.7/dist-packages (4.1)\n    Requirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.7/dist-packages (from coremltools) (1.15.0)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from coremltools) (4.41.1)\n    Requirement already satisfied: attr in /usr/local/lib/python3.7/dist-packages (from coremltools) (0.3.1)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from coremltools) (1.4.1)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from coremltools) (1.7.1)\n    Requirement already satisfied: attrs in /usr/local/lib/python3.7/dist-packages (from coremltools) (20.3.0)\n    Requirement already satisfied: numpy<1.20,>=1.14.5 in /usr/local/lib/python3.7/dist-packages (from coremltools) (1.19.5)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from coremltools) (20.9)\n    Requirement already satisfied: protobuf>=3.1.0 in /usr/local/lib/python3.7/dist-packages (from coremltools) (3.12.4)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->coremltools) (1.2.1)\n    Requirement already satisfied: pyparsing>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->coremltools) (2.4.7)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from protobuf>=3.1.0->coremltools) (54.2.0)\n\n\n\n```python\n# Initialise packages \nfrom u2net import U2NETP\nimport coremltools as ct\nfrom coremltools.proto import FeatureTypes_pb2 as ft\nimport torch\nimport torch.nn as nn   \nfrom torch.autograd import Variable\nimport os\nimport numpy as np\nfrom PIL import Image\nfrom torchvision import transforms\nfrom skimage import io, transform\n```\n\n\n```python\nfrom torchvision import transforms\n\ndef save_output(pred, image):\n    print(pred.shape)\n    predict = pred\n    predict = predict.squeeze()\n    print(predict.shape)\n    predict_np = predict.cpu().data.numpy()\n    im = Image.fromarray(predict_np * 255).convert('RGB')\n    imo = im.resize((image.size[0],image.size[1]),resample=Image.BILINEAR)\n    \n    display(imo)\n```\n\n\n```python\n# Pre-processing\ndef tensor_lab(sample):\n    image = sample\n\n    tmpImg = np.zeros((image.shape[0],image.shape[1],3))\n    image = image/np.max(image)\n    \n    tmpImg[:,:,0] = (image[:,:,0]-0.485)/0.229\n    tmpImg[:,:,1] = (image[:,:,1]-0.485)/0.229\n    tmpImg[:,:,2] = (image[:,:,2]-0.485)/0.229\n\n        # change the r,g,b to b,r,g from [0,255] to [0,1]\n    tmpImg = tmpImg.transpose((2, 0, 1))\n\n    return torch.from_numpy(tmpImg)\n\ndef input_test_image(image_name):\n    inputs_test = Image.open(image_name)\n    inputs_test = inputs_test.resize((320, 320))\n    inputs_test = np.asarray(inputs_test)\n    inputs_test = tensor_lab(inputs_test)\n    inputs_test = inputs_test.unsqueeze_(0)\n    inputs_test = inputs_test.type(torch.FloatTensor)\n\n    return inputs_test\n```\n\n\n```python\nimage_name = \"gordos.jpg\"\ninput_image = input_test_image(image_name)\nnet = U2NETP(3,1)\ndevice = torch.device('cpu')\nnet.load_state_dict(torch.load(\"u2netp.pth\", map_location=device))\nnet.cpu()\nnet.eval()\nd1,d2,d3,d4,d5,d6,d7 = net(input_image)\n```\n\n    /usr/local/lib/python3.7/dist-packages/torch/nn/functional.py:3328: UserWarning: nn.functional.upsample is deprecated. Use nn.functional.interpolate instead.\n      warnings.warn(\"nn.functional.upsample is deprecated. Use nn.functional.interpolate instead.\")\n    /usr/local/lib/python3.7/dist-packages/torch/nn/functional.py:3458: UserWarning: Default upsampling behavior when mode=bilinear is changed to align_corners=False since 0.4.0. Please specify align_corners=True if the old behavior is desired. See the documentation of nn.Upsample for details.\n      \"See the documentation of nn.Upsample for details.\".format(mode)\n    /usr/local/lib/python3.7/dist-packages/torch/nn/functional.py:1709: UserWarning: nn.functional.sigmoid is deprecated. Use torch.sigmoid instead.\n      warnings.warn(\"nn.functional.sigmoid is deprecated. Use torch.sigmoid instead.\")\n\n\n\n```python\nsave_output(d1, Image.open(image_name))\n```\n\n\n```python\n# Initialise Baseline UNETP model.\nnet = U2NETP(3,1)\ndevice = torch.device('cpu')\nnet.load_state_dict(torch.load(\"u2netp.pth\", map_location=device))\nnet.cpu()\nnet.eval()\n```\n\n\n```python\n# Trace the model.\ninput_image = input_test_image(image_name)\ntraced_model = torch.jit.trace(net, input_image)\n```\n\n    /usr/local/lib/python3.7/dist-packages/torch/nn/functional.py:3328: UserWarning: nn.functional.upsample is deprecated. Use nn.functional.interpolate instead.\n      warnings.warn(\"nn.functional.upsample is deprecated. Use nn.functional.interpolate instead.\")\n    /usr/local/lib/python3.7/dist-packages/torch/nn/functional.py:3458: UserWarning: Default upsampling behavior when mode=bilinear is changed to align_corners=False since 0.4.0. Please specify align_corners=True if the old behavior is desired. See the documentation of nn.Upsample for details.\n      \"See the documentation of nn.Upsample for details.\".format(mode)\n    /usr/local/lib/python3.7/dist-packages/torch/nn/functional.py:1709: UserWarning: nn.functional.sigmoid is deprecated. Use torch.sigmoid instead.\n      warnings.warn(\"nn.functional.sigmoid is deprecated. Use torch.sigmoid instead.\")\n\n\n\n```python\n# Convert the model\n_inputs = ct.ImageType(\n    name = \"input_1\",\n    shape = input_image.shape,\n    scale = 1.0/255.0/0.226,\n    bias=(-0.485/0.226, -0.456/0.226, -0.406/0.226),\n    channel_first = True\n    )\n\nmodel = ct.convert(traced_model, inputs=[_inputs])\n```\n\n    WARNING:root:Tuple detected at graph output. This will be flattened in the converted model.\n    Converting Frontend ==> MIL Ops:  98%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a| 1461/1490 [00:03<00:00, 423.85 ops/s]\n    Running MIL optimization passes: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 18/18 [00:01<00:00, 16.78 passes/s]\n    Translating MIL ==> MLModel Ops: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1977/1977 [00:00<00:00, 8523.21 ops/s]\n\n\n\n```python\n# Add metadata\nmodel.short_description = \"U2-Net: Going Deeper with Nested U-Structure for Salient Object Detection\"\nmodel.license = \"Apache 2.0\"\nmodel.author = \"Qin, Xuebin and Zhang, Zichen and Huang, Chenyang and Dehghan, Masood and Zaiane, Osmar and Jagersand, Martin\"\n```\n\n\n```python\n# Rename inputs\nspec = model.get_spec()\nct.utils.rename_feature(spec, \"input_1\", \"in_0\")\nct.utils.rename_feature(spec,\"2169\",\"out_a0\")\nct.utils.rename_feature(spec,\"2170\",\"out_a1\")\nct.utils.rename_feature(spec,\"2171\",\"out_a2\")\nct.utils.rename_feature(spec,\"2172\",\"out_a3\")\nct.utils.rename_feature(spec,\"2173\",\"out_a4\")\nct.utils.rename_feature(spec,\"2174\",\"out_a5\")\nct.utils.rename_feature(spec,\"2175\",\"out_a6\")\nmodel = ct.models.MLModel(spec)\nmodel.save(\"u2netp_temp.mlmodel\")\n```\n\n\n```python\n# Re-open model for modification\nmodel = ct.models.MLModel(\"u2netp_temp.mlmodel\")\n```\n\n\n```python\n# Get the model specifications\nspec = model.get_spec()\n```\n\n\n```python\n# Change model input and save\n'''\ninput = spec.description.input[0]\ninput.type.imageType.colorSpace = ft.ImageFeatureType.RGB\ninput.type.imageType.height = 320 \ninput.type.imageType.width = 320\n\nct.utils.save_spec(spec, \"u2netp_temp_new_input.mlmodel\")\n'''\n```\n\n\n```python\n# Re-open model for modification\nmodel = ct.models.MLModel(\"u2netp_temp.mlmodel\")\nspec = model.get_spec()\nspec_layers = getattr(spec, spec.WhichOneof(\"Type\")).layers\noutput_layers = spec_layers[476:] # Get only the last output layers, may change with full-size U^2net\n```\n\n\n```python\n# Append new layers\nnew_layers = []\nlayernum = 0;\nfor layer in output_layers:\n    new_layer = spec_layers.add()\n    new_layer.name = 'out_p' + str(layernum)\n    new_layers.append('out_p' + str(layernum))\n\n    new_layer.activation.linear.alpha = 255\n    new_layer.activation.linear.beta = 0\n\n    new_layer.input.append('out_a' + str(layernum))\n    new_layer.output.append('out_p' + str(layernum))\n    output_description = next(x for x in spec.description.output if x.name==output_layers[layernum].output[0])\n    output_description.name = new_layer.name\n\n    layernum = layernum + 1\n```\n\n\n```python\n# Specify the outputs as grayscale images.\nfor output in spec.description.output: \n    if output.name not in new_layers: \n        continue\n    if output.type.WhichOneof('Type') != 'multiArrayType': \n        raise ValueError(\"%s is not a multiarray type\" % output.name) \n\n    array_shape = tuple(output.type.multiArrayType.shape) \n    # print(array_shape)\n    # print(output.type)\n\n\n    output.type.imageType.colorSpace = ft.ImageFeatureType.ColorSpace.Value('GRAYSCALE')\n    output.type.imageType.width = 320 \n    output.type.imageType.height = 320\n```\n\n\n```python\nupdated_model = ct.models.MLModel(spec)\nmodel.short_description = \"U2-Net: Going Deeper with Nested U-Structure for Salient Object Detection\"\nmodel.license = \"Apache 2.0\"\nmodel.author = \"Qin, Xuebin and Zhang, Zichen and Huang, Chenyang and Dehghan, Masood and Zaiane, Osmar and Jagersand, Martin\"\n\nupdated_model.save(\"updated_model.mlmodel\")\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "d9a8bb8e20d230c66d512eecd464c79b914b861a", "size": 249423, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "CoreML_Conversion_U2NETP_FINAL.ipynb", "max_stars_repo_name": "jb-apps/U-2-Net", "max_stars_repo_head_hexsha": "c8016e05202853b0203d32254f49e44de908ea60", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CoreML_Conversion_U2NETP_FINAL.ipynb", "max_issues_repo_name": "jb-apps/U-2-Net", "max_issues_repo_head_hexsha": "c8016e05202853b0203d32254f49e44de908ea60", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CoreML_Conversion_U2NETP_FINAL.ipynb", "max_forks_repo_name": "jb-apps/U-2-Net", "max_forks_repo_head_hexsha": "c8016e05202853b0203d32254f49e44de908ea60", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-19T03:46:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-19T03:46:00.000Z", "avg_line_length": 529.5605095541, "max_line_length": 232634, "alphanum_fraction": 0.9401899584, "converted": true, "num_tokens": 2476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2974699426047947, "lm_q2_score": 0.05921025074128592, "lm_q1q2_score": 0.017613269889625825}}
{"text": "<center><h1>Elektromagnetska kompatibilnost (<a href='https://nastava.fesb.unist.hr/nastava/predmeti/13207' target='_blank' rel='noopener noreferrer'>FELO21</a>)</h1></center>\n<center>~ Akademska godina 2021/2022 ~</center>\n<center>Ante Loji\u0107 Kapetanovi\u0107</center>\n<center>Fakultet elektrotehnike, strojastva i brodogradnje</center>\n<center>Sveu\u010dili\u0161te u Splitu, Split, Hrvatska</center>\n\n---\n\n### Plan izvedbe\n\n1. laboratorijska vje\u017eba - **Uvod u kolegij**\n    - teoretski pregled\n    - uvod u programsku okolinu `Jupyter Notebook` i programski jezik `Python 3.x`\n    - uvod u simulacijski softver `PSpice`\n2. laboratorijska vje\u017eba - nisko propusni filtri\n3. laboratorijska vje\u017eba - visoko i pojasno propusni filtri\n4. laboratorijska vje\u017eba - primjena filtera na stvarnim primjerima\n5. laboratorijska vje\u017eba - **Pokazna vje\u017eba** primjena filtera u inverznoj identifikaciji sustava\n6. laboratorijska vje\u017eba - **Nadoknada** vje\u017ebi\n\n---\n\n### 1. Uvod u kolegij\n\n#### 1.0. Op\u0107enito o izvo\u0111enju\n\n- Uz uvodnu, ukupno \u0107e se odr\u017eavati 5 laboratorijskih vje\u017ebi.\n- Za sve naredne vje\u017ebe koje \u0107e se odvijati u laboratoriju, potrebno je pro\u010ditati pripadna upustva, postavljena na [ovoj web stranici](http://adria.fesb.hr/~alojic00/teaching/emc/reading/), prije dolaska na vje\u017ebe.\n- Ukupno mo\u017eete izostati s jednih vje\u017ebi a nadoknade \u0107e se odr\u017eati po dogovoru u predzadnjem tjednu semestra.\n\n#### 1.1. Teoretski pregled\n- Dodatni preporu\u010deni materijal:\n    1. [Teorija elektromagnetskih polja s primjenama u in\u017eenjerstvu](https://shop.skolskaknjiga.hr/teorija-elektromagnetskih-polja-s-primjenama-u-inzenjerstvu.html) - poglavlje 28. Osnove elektromagnetske kompatibilnosti;\n    2. [Advanced Modeling in Computational Electromagnetic Compatibility](https://onlinelibrary.wiley.com/doi/book/10.1002/0470116889).\n\nPod pojmom elektromagnetska kompatibilnosti (*electromagnetic compatibility* - EMC) podrazumijeva se sposobnost ure\u0111aja da zadovoljavaju\u0107e funkcionira unutar elektromagnetskog okru\u017eenja:\n- ure\u0111aj ili sustav ne smije biti ometan vanjskim poljem te ne smije biti izvor smetnji kao \u0161to su netolerabilna elektromagnetska ometanja elektroni\u010dkog sustava u bliskom okru\u017eenju;\n- zadovoljavaju\u0107e funkcioniranje ure\u0111aja ili sustava implicira pravilan rad i imunost na smetenje koje se smatraju uobi\u010dajenima u okru\u017eenju.\n\nZada\u0107a EMC-a je potisnuti bilo kakvu vrstu elektromagnetske smetnje (*electromagnetic interference* -EMI) kroz 2 osnovna zahtjeva:\n1. testiranje imunosti (*immunity testing*) - nakon realizacije i konstrukcije ure\u0111aja, potrebno je ispitati je li ure\u0111aj potencijalna \u017ertva smetenje, odnosno zadovoljava li EMC zahtjev da ga ne ometaju pri radu bilo kakvi vanjski izvori elektromagnetske smetnje proizvedeni u njegovom bliskom okru\u017eenju;\n2. testiranje emisije (*emission testing*) - tijekom same realizacije i konstrukcije ure\u0111aja, potrebno je uvjeriti se da ure\u0111aj nije izvor elektromagnetske smetenje za bilo koje druge ure\u0111aje ili okolni sustav u bliskom okru\u017eenju.\n\nKako bi se izbjegli tro\u0161kovi realizacije i konstrukcije ve\u0107 spomenutih elektroni\u010dkih ure\u0111aja ili sustava, osnovna zada\u0107a **ra\u010dunalne** elektromagnetske kompatibilnosti (naspram do sada spomenute eksperimentalne) je **simulacija** elektromagnetskog pona\u0161anja za vrlo \u0161irok opseg parametara - razli\u010diti po\u010detni i rubni uvjeti, oblici pobude te naposlijetku konfiguracija i geometrija samog sustava. Osnovni ra\u010dunalni EMC model uklju\u010duje **izvor smetnje** (npr., radiooda\u0161ilja\u010d, mobilni telefon, udar munje ili neki drugi tip elektromagnetskog impulsa), **stazu sprege** koja se odnosi na elektromagnetska polja koja se propagiraju u slobodnom prostoru, materijalu ili vodi\u010du i **\u017ertvu smetnje** (npr., radioprijemnik, medicinska elektroni\u010dka oprema, ljudsko tijelo).\n\n\n(4 osnovna mehanizma sprege: konduktivni, kapacitivni, induktivni, i zra\u010denje. ref: https://en.wikipedia.org/wiki/Electromagnetic_compatibility)\n\nSvi EMC ra\u010dunalni modeli proizlaze iz koncepta rigorozne elektromagnetske teroije i temelja zasnovanih na Maxwellovim jednad\u017ebama - prikazane u diferencijalnoj vektorskoj formi kako slijedi:\n$$\n\\begin{align}\n    \\nabla \\times \\vec E &= - \\frac{\\partial \\vec B}{\\partial t}\\\\\n    \\nabla \\times \\vec H &= \\frac{\\partial \\vec D}{\\partial t} + \\vec J\\\\\n    \\nabla \\vec D &= \\rho\\\\\n    \\nabla \\vec B &= 0\\\\\n\\end{align}\n$$\n\nEMC modeli realiziraju se primjenom analiti\u010dkih ili numeri\u010dkih relacija i metoda. Analiti\u010dki modeli se koriste za jednostavne geometrije visokog stupnja simetrije (kanonski problemi), dok se numeri\u010dki modeli koriste za precizne simulacije slo\u017eenih prakti\u010dnih in\u017eenjerskih problema koji oklju\u010duju realisti\u010dne scenarije i kompleksne geometrije domene.\n\nOsnovna klasifikacija EMC ra\u010dunalnih modela koji se koriste u istra\u017eivanju, ali i u in\u017eenjerskoj praksi:\n1. modeli teorije krugova zasnovani na konceptu koncentriranih elektri\u010dnih parametara;\n2. modeli prijenosnih linija zasnovani na distribuiranim parametrima koji vrijede za spregu s poljima niskih frekvencija;\n3. modeli zastnovani na teoriji antena kod kojih se uzimaju u obzir efekti zra\u010denja za rje\u0161avanje problema propagacije elektromagnetskih valova.\n\nU svojoj osnovi, svi spomenuti modeli mogu se dodatno klasificirati na:\n1. stacionarne probleme (*continuous wave problems*);\n2. prijalazne pojave (*transients*).\n\nS obzirom na stazu sprege, smetnje dijelimo na dvije velike grupe:\n1. vo\u0111ene smetnje (npr. inducirani prenaponi, harmonici);\n2. zra\u010dene smetenje (npr. naponi inducirani udarom munje, zra\u010denjem antenskih sustava, prislu\u0161kivanjem).\n\n#### 1.2. Uvod u programsku okolinu `Jupyter Notebook` i programski jezik `Python 3.x`\n- bilje\u017enica za vje\u017ebe: 01-lab-ex.ipynb\n- dodatni preporu\u010deni materijali:\n    1. [Learn X in Y minutes](https://learnxinyminutes.com/docs/python/)\n    2. [Whirlwind Tour of Python](https://github.com/jakevdp/WhirlwindTourOfPython)\n    3. [Getting started with Python for science](https://scipy-lectures.org/intro/index.html)\n    4. [A Primer on Scientific Programming with Python](https://link.springer.com/book/10.1007%2F978-3-642-54959-5)\n\n#### 1.3. Uvod u simulacijsku aplikaciju `PSpice`\n- klikni za skidanje .exe datoteke: [download](http://adria.fesb.hr/~alojic00/teaching/emc/lab/PSpice/91pspstu_PSPICE_9_1.exe)\n- instalacija: http://adria.fesb.hr/~alojic00/emc/lab/PSpice/docs/installation_win10.pdf\n- tutorial: http://adria.fesb.hr/~alojic00/emc/PSpice/docs/tutorial.pdf\n\n- `PSpice` omogu\u0107uje simulaciju pona\u0161anja elektroni\u010dkih sklopova na digitalnom ra\u010dunalu i emulira generator signala, te mjernu opremu poput multimetara, osciloskopa ili analizatora frekvencijskog spektra\n- 4 osnovna tipa analize elektroni\u010dke opreme kroz `PSpice`:\n    1. *Bias point* analiza u elektromagnetskoj kompatibilnosti; u ovom re\u017eimu, simulator ra\u010duna inicijalne uvjete za po\u010detak *DC* ili *AC sweep* analize; \n    2. *DC sweep* analiza izlaza u lineranoj ili logaritamskoj skali s obzirom na napon pode\u0161en na ulazu sklopa;\n    3. *AC sweep* analiza izlaza u linearnoj ili logaritamskoj skali s obzirom na frekvenciju pode\u0161enu kao radnu za promatrani elektroni\u010dki sklop;\n    4. tranzijentna analiza koja omogu\u0107uju promatranje izlaza kao funkcije vremena s obzirom na parametre sklopa koji se testiraju.\n", "meta": {"hexsha": "75d8c87d1fade9a13d83e12d8631c1d8078f998f", "size": 9018, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "emc_512/lab/Python/00-introduction.ipynb", "max_stars_repo_name": "antelk/teaching", "max_stars_repo_head_hexsha": "4482456b8f51ff20e9560cbb6409f93c8a6d0d1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "emc_512/lab/Python/00-introduction.ipynb", "max_issues_repo_name": "antelk/teaching", "max_issues_repo_head_hexsha": "4482456b8f51ff20e9560cbb6409f93c8a6d0d1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "emc_512/lab/Python/00-introduction.ipynb", "max_forks_repo_name": "antelk/teaching", "max_forks_repo_head_hexsha": "4482456b8f51ff20e9560cbb6409f93c8a6d0d1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.5234899329, "max_line_length": 773, "alphanum_fraction": 0.7035928144, "converted": true, "num_tokens": 2629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16451646699291614, "lm_q2_score": 0.10669059678604235, "lm_q1q2_score": 0.01755236004460546}}
{"text": "## Visualization \n\n### Overview\n\nVisualization poses a significant challenge for the space weather community: output from models and data are very domain-specific, both in content (coordinate systems, units) and in representation (file formats and data structures). On the other hand, science users also have their preferred context for analyzing these results - for instance, they may only want simulation results interpolated on a satellite trajectory and in a specific coordinate system with their own prefered units.\n\nKamodo aims to strike a balance between the intent of the model (or data) provider and the goals of the user, by making it easy for developers to provide context for their output and for users to easily change that context. It accomplishes this in two ways:\n\n* By leveraging default arguments given by model and data providers \n* By mapping the shape of function inputs and output to certain registered plot types\n\nThis strategy allows Kamodo to automatically generate plots for arbitrary model output and data sources, while still allowing for customization by the end user.\n\n### Available Plot Types\n\nKamodo keeps a registry of plotting functions, indexed by argument shape and output shape.\n\n\n```python\nfrom kamodo.plotting import plot_types\nplot_types\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>plot_type</th>\n      <th>function</th>\n    </tr>\n    <tr>\n      <th>out_shape</th>\n      <th>arg_shapes</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>(1,)</th>\n      <th>((N, M), (N, M), (N, M))</th>\n      <td>3d-parametric</td>\n      <td>&lt;function surface at 0x12e9b2620&gt;</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">(N,)</th>\n      <th>((N,),)</th>\n      <td>1d-line</td>\n      <td>&lt;function line_plot at 0x11cbc3a60&gt;</td>\n    </tr>\n    <tr>\n      <th>((N,), (N,), (N,))</th>\n      <td>3d-line-scalar</td>\n      <td>&lt;function line_plot at 0x11cbc3a60&gt;</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">(N, 2)</th>\n      <th>((N,),)</th>\n      <td>2d-line</td>\n      <td>&lt;function line_plot at 0x11cbc3a60&gt;</td>\n    </tr>\n    <tr>\n      <th>((N, 2),)</th>\n      <td>2d-vector</td>\n      <td>&lt;function vector_plot at 0x12e9b2378&gt;</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">(N, 3)</th>\n      <th>((N,),)</th>\n      <td>3d-line</td>\n      <td>&lt;function line_plot at 0x11cbc3a60&gt;</td>\n    </tr>\n    <tr>\n      <th>((N, 3),)</th>\n      <td>3d-vector</td>\n      <td>&lt;function vector_plot at 0x12e9b2378&gt;</td>\n    </tr>\n    <tr>\n      <th rowspan=\"6\" valign=\"top\">(N, M)</th>\n      <th>((N,), (M,))</th>\n      <td>2d-contour</td>\n      <td>&lt;function contour_plot at 0x12e9b2488&gt;</td>\n    </tr>\n    <tr>\n      <th>((N, M), (N, M))</th>\n      <td>2d-contour-skew</td>\n      <td>&lt;function contour_plot at 0x12e9b2488&gt;</td>\n    </tr>\n    <tr>\n      <th>((N, M), (N, M), (N, M))</th>\n      <td>3d-parametric-scalar</td>\n      <td>&lt;function surface at 0x12e9b2620&gt;</td>\n    </tr>\n    <tr>\n      <th>((1,), (N, M), (N, M))</th>\n      <td>3d-plane</td>\n      <td>&lt;function plane at 0x12e9b2598&gt;</td>\n    </tr>\n    <tr>\n      <th>((N, M), (1,), (N, M))</th>\n      <td>3d-plane</td>\n      <td>&lt;function plane at 0x12e9b2598&gt;</td>\n    </tr>\n    <tr>\n      <th>((N, M), (N, M), (1,))</th>\n      <td>3d-plane</td>\n      <td>&lt;function plane at 0x12e9b2598&gt;</td>\n    </tr>\n    <tr>\n      <th rowspan=\"3\" valign=\"top\">(N, M, 1)</th>\n      <th>((1,), (N,), (M,))</th>\n      <td>3d-plane</td>\n      <td>&lt;function plane at 0x12e9b2598&gt;</td>\n    </tr>\n    <tr>\n      <th>((N,), (1,), (M,))</th>\n      <td>3d-plane</td>\n      <td>&lt;function plane at 0x12e9b2598&gt;</td>\n    </tr>\n    <tr>\n      <th>((N,), (M,), (1,))</th>\n      <td>3d-plane</td>\n      <td>&lt;function plane at 0x12e9b2598&gt;</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nWhen a user tries to plot a given variable, a lookup is made into the table above and the corresponding plotting function is used to generate the output. Examples below demonstrate the intended workflow.\n\n### 1-Dimensional line plots\n\n\n```python\nfrom kamodo import Kamodo, kamodofy\nkamodo = Kamodo('g_N[kg] = x_N**2')\nkamodo['f[g]'] = 'g_N'\nkamodo\n```\n\n\n\n\n\\begin{equation}\\operatorname{g_{N}}{\\left(x_{N} \\right)} [kg] = x_{N}^{2}\\end{equation}\\begin{equation}f{\\left(x_{N} \\right)} [g] = 1000 \\operatorname{g_{N}}{\\left(x_{N} \\right)}\\end{equation}\n\n\n\nHere we have defined a function $g_N$ which returns an array of shape $N$. As input, it takes one argument $x_N$ which also has size $N$. We also generate a function $f$ which is the same as $g_N$ but with a different units.\n\n!!! note\n    We could have named the function $g$ instead of $g_N$. The variable names have no bearing on the resulting plots - only the argument input shapes and output shapes matter.\n\nWhen we call Kamodo's plot function, we define which variable we are plotting and domain over which the arguments are applied:\n\n\n```python\nimport numpy as np\nimport plotly.io as pio\n\nfig = kamodo.plot(f = dict(x_N = np.linspace(-4, 3, 30)))\npio.write_image(fig, 'images/1d-line.svg')\n```\n\n\n\nThis is the graph $f(x_n)$ for $x_N \\in [-4,3]$.\n\n### Time series data\nThe process for time series data is the same, except we use a pandas datetime index for the input argument.\n\n\n```python\nimport pandas as pd\nt_N = pd.date_range('Nov 9, 2018', 'Nov 20, 2018', freq = 'H')\n```\n\n\n```python\n@kamodofy(units = 'kg/m^3')\ndef rho_N(t_N = t_N):\n    dt_days = (t_N - t_N[0]).total_seconds()/(24*3600)\n    return 1+np.sin(dt_days) + .1*np.random.random(len(dt_days))\n\nkamodo = Kamodo(rho_N = rho_N, verbose = False)\nkamodo\n```\n\n\n\n\n\\begin{equation}\\rho_{N}{\\left(t_{N} \\right)} [kg/m^3] = \\lambda{\\left(t_{N} \\right)}\\end{equation}\n\n\n\n\n```python\nfig = kamodo.plot('rho_N')\n```\n\nIn this case, we only need to name the variable we wish to plot, because we have already defined a function $rho_N(t_N)$ with a default parameter for $t_N$. \n\n\n```python\npio.write_image(fig, 'images/1d-time-series.svg')\n```\n\n\n\n!!! note\n    By providing default parameters, the function author can insure that anyone plotting the variable will not need to know where to place resolution!\n\n## 2-D Parametric charts\n\nFor 2-D Plots, the output function must have input shape $(N,1)$ and output shape $(N,2)$.\n\n\n```python\nfrom kamodo import Kamodo\n@kamodofy(units = 'cm')\ndef x_Ncomma2(theta_N = np.linspace(0,6*np.pi, 200)):\n    r = theta_N\n    x = r*np.cos(theta_N)\n    y = r*np.sin(theta_N)\n    return np.array(list(zip(x,y)))\n\nkamodo = Kamodo(x_Ncomma2 = x_Ncomma2)\nkamodo\n```\n\n\n\n\n\\begin{equation}\\operatorname{x_{N,2}}{\\left(\\theta_{N} \\right)} [cm] = \\lambda{\\left(\\theta_{N} \\right)}\\end{equation}\n\n\n\nHere, we again provide a default array for $\\theta_N$ so the end user does not need to:\n\n\n```python\nfig = kamodo.plot('x_Ncomma2')\npio.write_image(fig, 'images/fig-2d.svg')\n```\n\n\n\n## 3-Dimensional parametric curves\n\nFor 3-D parametric curves, the output function must have input shape $(N,1)$ and output shape $(N,3)$.\n\n\n```python\n@kamodofy(units = 'km')\ndef x_Ncomma3(t_N = pd.date_range('Nov 12, 2018', 'Dec 30, 2018', freq = '4 H')):\n    dt_days = (t_N - t_N[0]).total_seconds()/(24*3600)\n    theta = dt_days*np.pi/5\n    r = theta\n    x = r*np.cos(theta)\n    y = r*np.sin(theta)\n    z = r\n    return np.array(list(zip(x,y,z)))\n\nkamodo = Kamodo(x_Ncomma3 = x_Ncomma3)\nkamodo\n```\n\n\n\n\n\\begin{equation}\\operatorname{x_{N,3}}{\\left(t_{N} \\right)} [km] = \\lambda{\\left(t_{N} \\right)}\\end{equation}\n\n\n\n\n```python\nfig = kamodo.plot('x_Ncomma3')\npio.write_image(fig, 'images/3d-line.svg')\n```\n\n\n\nFunctions of three N-d arrays are also interpreted as 3D parametric plots, but with an additonal color component.\n\n\n```python\ns = np.linspace(0, 8*np.pi, 100)\nx = 10*np.sin(s/8)\ny = 10*np.sin(s)\nz = s\n\n@kamodofy(units = 'kg')\ndef f_N(x_N = x, y_N = y, z_N = z):\n    return x_N**2+y_N**2+z_N**2\n\nkamodo = Kamodo(f_N = f_N)\nkamodo\n```\n\n\n\n\n\\begin{equation}\\operatorname{f_{N}}{\\left(x_{N},y_{N},z_{N} \\right)} [kg] = \\lambda{\\left(x_{N},y_{N},z_{N} \\right)}\\end{equation}\n\n\n\n\n```python\nfig = kamodo.plot('f_N')\npio.write_image(fig, 'images/3d-points.svg')\n```\n\n\n\n# Vector fields\n\nKamodo generates a 2-d vector (quiver) plot for functions of one variable, if both the input and output have shape (N,2). The input positions are assumed to be $x$,$y$ and the output vectors are assumed to be $v_x$, $v_y$\n\n\n```python\ntheta_N = np.linspace(0,6*np.pi, 200)\nr = theta_N\nx = r*np.cos(theta_N)\ny = r*np.sin(theta_N)\npoints = np.array(list(zip(x,y)))\n\n@kamodofy(units = 'cm')\ndef fvec_Ncomma2(rvec_Ncomma2 = points):\n    return rvec_Ncomma2\n\nkamodo = Kamodo(fvec_Ncomma2 = fvec_Ncomma2)\nkamodo\n```\n\n\n\n\n\\begin{equation}\\vec{f}_{N,2}{\\left(\\vec{r}_{N,2} \\right)} [cm] = \\lambda{\\left(\\vec{r}_{N,2} \\right)}\\end{equation}\n\n\n\n\n```python\nfig = kamodo.plot('fvec_Ncomma2')\npio.write_image(fig, 'images/fig2d-vector.svg')\n```\n\n\n\nIf we wish to represent a grid of vectors, we must first unravel the grid as a string of points.\n\n\n```python\nx = np.linspace(-np.pi, np.pi, 25)\ny = np.linspace(-np.pi, np.pi, 30)\nxx, yy = np.meshgrid(x,y)\npoints = np.array(list(zip(xx.ravel(), yy.ravel())))\n\ndef fvec_Ncomma2(rvec_Ncomma2 = points):\n    ux = np.sin(rvec_Ncomma2[:,0])\n    uy = np.cos(rvec_Ncomma2[:,1])\n    return np.vstack((ux,uy)).T\n    \nkamodo = Kamodo(fvec_Ncomma2 = fvec_Ncomma2)\nkamodo\n```\n\n\n\n\n\\begin{equation}\\vec{f}_{N,2}{\\left(\\vec{r}_{N,2} \\right)} = \\lambda{\\left(\\vec{r}_{N,2} \\right)}\\end{equation}\n\n\n\n\n```python\nfig = kamodo.plot('fvec_Ncomma2')\npio.write_image(fig, 'images/fig2d-vector-field.svg')\n```\n\n\n\n### 3D vector fields\n\nFunctions representing 3D vector fields should have one argument of shape (N,3) and an output shape of (N,3)\n\n\n```python\nx, y, z = np.meshgrid(np.linspace(-2,2,4),\n                      np.linspace(-3,3,6),\n                      np.linspace(-5,5,10))\npoints = np.array(list(zip(x.ravel(), y.ravel(), z.ravel())))\ndef fvec_Ncomma3(rvec_Ncomma3 = points):\n    return rvec_Ncomma3\n\nkamodo = Kamodo(fvec_Ncomma3 = fvec_Ncomma3)\nkamodo\n```\n\n\n\n\n\\begin{equation}\\vec{f}_{N,3}{\\left(\\vec{r}_{N,3} \\right)} = \\lambda{\\left(\\vec{r}_{N,3} \\right)}\\end{equation}\n\n\n\n\n```python\nfig = kamodo.plot('fvec_Ncomma3')\npio.write_image(fig, 'images/fig3d-vector.svg')\n```\n\n\n\n# Contour plots\n\nScalar functions of two variables of size (N) and (M) and output size (N,M) will generate contour plots. Kamodo can handle both ```ij``` indexing and ```xy``` indexing.\n\n\n```python\nfrom kamodo import Kamodo\n@kamodofy(units = 'cm^2')\ndef f_NcommaM(x_N = np.linspace(0, 8*np.pi,100), y_M = np.linspace(0, 5, 90)):\n    x, y = np.meshgrid(x_N, y_M, indexing = 'xy')\n    return np.sin(x)*y\n\nkamodo = Kamodo(f_NcommaM = f_NcommaM)\nkamodo\n```\n\n\n\n\n\\begin{equation}\\operatorname{f_{N,M}}{\\left(x_{N},y_{M} \\right)} [cm^2] = \\lambda{\\left(x_{N},y_{M} \\right)}\\end{equation}\n\n\n\n\n```python\nfig = kamodo.plot('f_NcommaM')\npio.write_image(fig, 'images/fig2d-contour.svg')\n```\n\n\n\nSince $x_N$ and $y_M$ have differnt sizes, we could have used ```indexing=ij``` as an argument to meshgrid and kamodo would have produced the same figure - Kamodo swaps the ordering where appropriate. In the event that *both* arguments have the same size, we can pass an ```indexing``` argument as an option to the plot function.\n\n\n```python\n@kamodofy(units = 'cm^2')\ndef f_NN(x_N = np.linspace(0, 8*np.pi, 90), y_N = np.linspace(0, 5, 90)):\n    x, y = np.meshgrid(x_N, y_N, indexing = 'xy')\n    return np.sin(x)*y\n\nkamodo = Kamodo(f_NN = f_NN)\nkamodo\n```\n\n\n\n\n\\begin{equation}\\operatorname{f_{NN}}{\\left(x_{N},y_{N} \\right)} [cm^2] = \\lambda{\\left(x_{N},y_{N} \\right)}\\end{equation}\n\n\n\n\n```python\nfig = kamodo.plot(f_NN = dict(indexing = 'xy'))\npio.write_image(fig, 'images/fig2d-contour-xy.svg')\n```\n\n\n\n# Skew (Carpet) Plots\n\nFunctions of two arguments each having shape (N,M) matching the output shape will produce skewed contour plots, whereby the x and y components of the grid are independent.\n\n\n```python\nr = np.linspace(1, 3, 20)\ntheta = np.linspace(0, np.pi, 14)\nr_, theta_ = np.meshgrid(r,theta)\nXX = r_*np.cos(theta_)\nYY = r_*np.sin(theta_)\n\n@kamodofy(units = 'cm^2')\ndef f_NM(x_NM = XX, y_NM = YY):\n    return np.sin(x_NM)+y_NM\n\nkamodo = Kamodo(f_NM = f_NM)\nkamodo\n```\n\n\n\n\n\\begin{equation}\\operatorname{f_{NM}}{\\left(x_{NM},y_{NM} \\right)} [cm^2] = \\lambda{\\left(x_{NM},y_{NM} \\right)}\\end{equation}\n\n\n\n\n```python\nfig = kamodo.plot('f_NM')\npio.write_image(fig, 'images/fig2d-skew.svg')\n```\n\n\n\n# Parametric surfaces\n\nTo generate a purely geometrical parametric surface, supply a functions of three variables, each of size (N,M) and of output shape (1).\n\n\n```python\nfrom kamodo import Kamodo\nu = np.linspace(-2, 2, 40)\nv = np.linspace(-2, 2, 50)\nuu, vv = np.meshgrid(u,v)\n\n@kamodofy(units = 'cm')\ndef parametric(x_NM = uu*np.sin(vv*np.pi), \n               y_NM = vv, \n               z_NM = np.exp(-uu**2-vv**2)):\n    return np.array([1])\nkamodo = Kamodo(p = parametric)\nkamodo\n```\n\n\n\n\n\\begin{equation}p{\\left(x_{NM},y_{NM},z_{NM} \\right)} [cm] = \\lambda{\\left(x_{NM},y_{NM},z_{NM} \\right)}\\end{equation}\n\n\n\n\n```python\nfig = kamodo.plot('p')\npio.write_image(fig, 'images/3d-parametric.svg')\n```\n\n\n\nTo control the color of the parametric surface, have the output shape be (N,M).\n\n\n```python\nR = 1\ntheta = np.linspace(.2*np.pi, .8*np.pi, 40)\nphi = np.linspace(0, 2*np.pi, 50)\ntheta_, phi_ = np.meshgrid(theta, phi)\nr = (R +.1*(np.cos(10*theta_)*np.sin(14*phi_)))\n\nxx = r*np.sin(theta_)*np.cos(phi_)\nyy = r*np.sin(theta_)*np.sin(phi_)\nzz = r*np.cos(theta_)\n\n@kamodofy(units = 'cm')\ndef spherelike(x_NM = xx, y_NM = yy, z_NM = zz):\n    return .1*x_NM + x_NM**2 + y_NM**2 + z_NM**2\n\nkamodo = Kamodo(h_NM = spherelike)\nkamodo\n```\n\n\n\n\n\\begin{equation}\\operatorname{h_{NM}}{\\left(x_{NM},y_{NM},z_{NM} \\right)} [cm] = \\lambda{\\left(x_{NM},y_{NM},z_{NM} \\right)}\\end{equation}\n\n\n\n\n```python\nfig = kamodo.plot('h_NM')\npio.write_image(fig, 'images/3d-parametric-color.svg')\n```\n\n\n\n## Map-to-plane\nWe often need to produce slices through a volumetric grid of data. This may be accomplished through the use of volumetric grid interpolators equipped with default values for each of the input arguments. Suppose such a function has default input arguments of size (L), (M), (N), and output shape (L,M,N), then a cartesian plane will be generated if the user overrides one of these defaults (e.g. setting $L = 1$).\n\n\n```python\n@kamodofy(units = 'g/cm^3')\ndef f_LMN(\n      x_L = np.linspace(-5, 5, 50), \n      y_M = np.linspace(0, 10, 75), \n      z_N = np.linspace(-20, 20, 100)):\n    xx, yy, zz = np.meshgrid(x_L,y_M,z_N, indexing = 'xy')\n    return xx + yy + zz\n\nkamodo = Kamodo(f_LMN = f_LMN)\nkamodo\n```\n\n\n\n\n\\begin{equation}\\operatorname{f_{LMN}}{\\left(x_{L},y_{M},z_{N} \\right)} [g/cm^3] = \\lambda{\\left(x_{L},y_{M},z_{N} \\right)}\\end{equation}\n\n\n\n\n```python\nfig = kamodo.plot(f_LMN = dict(z_N = -5))\npio.write_image(fig,'images/fig2d-map-to-plane.svg')\n```\n\n\n\n!!!tip\n    By providing appropriate defaults for the undelying grid structure, the interpolator author can ensure that the user can generate figures with optimal resolution!\n\n# Multiple traces\n\nKamodo supports multiple traces in the same figure. Simply provide ```plot``` with multiple function-argument pairs.\n\n\n```python\nfrom kamodo import Kamodo\nt_N = pd.date_range('Nov 9, 2018', 'Nov 20, 2018', freq = 'H')\n\n@kamodofy(units = 'kg/m^3')\ndef rho_N(t_N = t_N):\n    dt_days = (t_N - t_N[0]).total_seconds()/(24*3600)\n    return 1+np.sin(dt_days) + .1*np.random.random(len(dt_days))\n\n@kamodofy(units = 'nPa')\ndef p_N(t_N = t_N):\n    dt_days = (t_N - t_N[0]).total_seconds()/(24*3600)\n    return 1+np.sin(2*dt_days) + .1*np.random.random(len(dt_days))\n\n\nkamodo = Kamodo(rho_N = rho_N, p_N = p_N, verbose = False)\nkamodo\n```\n\n\n\n\n\\begin{equation}\\rho_{N}{\\left(t_{N} \\right)} [kg/m^3] = \\lambda{\\left(t_{N} \\right)}\\end{equation}\\begin{equation}\\operatorname{p_{N}}{\\left(t_{N} \\right)} [nPa] = \\lambda{\\left(t_{N} \\right)}\\end{equation}\n\n\n\n\n```python\nfig = kamodo.plot('p_N','rho_N')\npio.write_image(fig, 'images/multi-trace.svg')\n```\n\n\n\n!!! note\n    Plot types must be compatible for kamodo to plot different variables on the same axes.\n\nKamodo can also handle multiple traces in 3D\n\n\n```python\nfrom kamodo import Kamodo, kamodofy\n\n@kamodofy(units = 'g/cm^3')\ndef f_LMN(\n      x_L = np.linspace(-5, 5, 50), \n      y_M = np.linspace(0, 10, 75), \n      z_N = np.linspace(-20, 20, 100)):\n    xx, yy, zz = np.meshgrid(x_L,y_M,z_N, indexing = 'xy')\n    return xx + yy + zz\n\nkamodo = Kamodo(f_LMN = f_LMN, g_LMN = f_LMN)\nkamodo\n```\n\n\n\n\n\\begin{equation}\\operatorname{f_{LMN}}{\\left(x_{L},y_{M},z_{N} \\right)} [g/cm^3] = \\lambda{\\left(x_{L},y_{M},z_{N} \\right)}\\end{equation}\\begin{equation}\\operatorname{g_{LMN}}{\\left(x_{L},y_{M},z_{N} \\right)} [g/cm^3] = \\lambda{\\left(x_{L},y_{M},z_{N} \\right)}\\end{equation}\n\n\n\n\n```python\nfig = kamodo.plot(f_LMN = dict(z_N = 0), \n                  g_LMN = dict(y_M = 5))\n```\n\n\n```python\npio.write_image(fig, 'images/multi-trace3d.svg')\n```\n\n\n\n!!! bug\n    Multiple traces results in different colorbars which may overlap. More control over the layout will be available in future updates. \n\n# Interactive Plotting\n\nFor interactive 3d plots, we take advantage of Plotly's in-browser plotting library.\n\n\n```python\nfrom plotly.offline import iplot, plot, init_notebook_mode\n```\n\nTo generate a separate interactive html page, use `iplot` instead of `plot`:\n\n\n```python\nplot(fig, filename = 'sample_plot.html') #uncomment to render 3D interactive plot in this cell \n```\n\n\n\n\n    'sample_plot.html'\n\n\n\nnavigate to the 3d interactive plot: [sample_plot.html](sample_plot.html).\n\nAlternatively, you may work with interactive plots directly in jupyter notebooks:\n\n\n```python\n# init_notebook_mode() # uncomment to initialize plotly for notebook\n# iplot(fig) #uncomment to render 3D interactive plot in this cell \n```\n\n!!! note\n    We have commented out the above lines because they do not render properly on the documentation server, but rest assured they do work!\n", "meta": {"hexsha": "2533143a997f843808342107eac9f374e2da6a86", "size": 186087, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/notebooks/Visualization.ipynb", "max_stars_repo_name": "iamjavaexpert/Kamodo", "max_stars_repo_head_hexsha": "26e7de66e67b9196ab19f13e73136db75832813c", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/notebooks/Visualization.ipynb", "max_issues_repo_name": "iamjavaexpert/Kamodo", "max_issues_repo_head_hexsha": "26e7de66e67b9196ab19f13e73136db75832813c", "max_issues_repo_licenses": ["NASA-1.3"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/notebooks/Visualization.ipynb", "max_forks_repo_name": "iamjavaexpert/Kamodo", "max_forks_repo_head_hexsha": "26e7de66e67b9196ab19f13e73136db75832813c", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.2276171765, "max_line_length": 496, "alphanum_fraction": 0.4694363389, "converted": true, "num_tokens": 6023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505578320071, "lm_q2_score": 0.055823144276191644, "lm_q1q2_score": 0.0175312895998746}}
{"text": " \u0423 \u043d\u0430\u0441 \u0438\u043c\u0435\u044e\u0442\u0441\u044f \u0442\u0430\u0431\u043b\u0438\u0446\u044b \u0441 \u0434\u0430\u043d\u043d\u044b\u043c\u0438 \u043a\u0430\u0442\u0430\u043b\u043e\u0433\u043e\u0432:\n- SDSS (glist_s), \n- 2MRS (glist_2).\n \nSDSS - Sloan Digital Sky Survey \u0441 \u0430\u043d\u0433\u043b.\u2009\u2014\u2009\u00ab\u0421\u043b\u043e\u0443\u043d\u043e\u0432\u0441\u043a\u0438\u0439 \u0446\u0438\u0444\u0440\u043e\u0432\u043e\u0439 \u043d\u0435\u0431\u0435\u0441\u043d\u044b\u0439 \u043e\u0431\u0437\u043e\u0440\u00bb) \u2014 \u043f\u0440\u043e\u0435\u043a\u0442 \u0448\u0438\u0440\u043e\u043a\u043e\u043c\u0430\u0441\u0448\u0442\u0430\u0431\u043d\u043e\u0433\u043e \u0438\u0441\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u043d\u0438\u044f \u043c\u043d\u043e\u0433\u043e\u0441\u043f\u0435\u043a\u0442\u0440\u0430\u043b\u044c\u043d\u044b\u0445 \u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u0439 \u0438 \u0441\u043f\u0435\u043a\u0442\u0440\u043e\u0432 \u043a\u0440\u0430\u0441\u043d\u043e\u0433\u043e \u0441\u043c\u0435\u0449\u0435\u043d\u0438\u044f \u0437\u0432\u0451\u0437\u0434 \u0438 \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a \u043f\u0440\u0438 \u043f\u043e\u043c\u043e\u0449\u0438 2,5-\u043c\u0435\u0442\u0440\u043e\u0432\u043e\u0433\u043e \u0448\u0438\u0440\u043e\u043a\u043e\u0443\u0433\u043e\u043b\u044c\u043d\u043e\u0433\u043e \u0442\u0435\u043b\u0435\u0441\u043a\u043e\u043f\u0430 \u0432 \u043e\u0431\u0441\u0435\u0440\u0432\u0430\u0442\u043e\u0440\u0438\u0438 \u0410\u043f\u0430\u0447\u0438-\u041f\u043e\u0439\u043d\u0442 \u0432 \u0448\u0442\u0430\u0442\u0435 \u041d\u044c\u044e-\u041c\u0435\u043a\u0441\u0438\u043a\u043e. \u041f\u0440\u043e\u0435\u043a\u0442 \u043d\u0430\u0437\u0432\u0430\u043d \u0432 \u0447\u0435\u0441\u0442\u044c \u0444\u043e\u043d\u0434\u0430 \u0410\u043b\u044c\u0444\u0440\u0435\u0434\u0430 \u0421\u043b\u043e\u0443\u043d\u0430.\n\n\u0418\u0441\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u043d\u0438\u044f \u043d\u0430\u0447\u0430\u043b\u0438\u0441\u044c \u0432 2000 \u0433\u043e\u0434\u0443, \u0432 \u0445\u043e\u0434\u0435 \u0440\u0430\u0431\u043e\u0442\u044b \u043f\u0440\u043e\u0435\u043a\u0442\u0430 \u0431\u044b\u043b\u043e \u043f\u0440\u043e\u0432\u0435\u0434\u0435\u043d\u043e \u043a\u0430\u0440\u0442\u043e\u0433\u0440\u0430\u0444\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435 \u0431\u043e\u043b\u0435\u0435 35 % \u043d\u0435\u0431\u0435\u0441\u043d\u043e\u0439 \u0441\u0444\u0435\u0440\u044b \u0441 \u0444\u043e\u0442\u043e\u043c\u0435\u0442\u0440\u0438\u0447\u0435\u0441\u043a\u0438\u043c\u0438 \u043d\u0430\u0431\u043b\u044e\u0434\u0435\u043d\u0438\u044f\u043c\u0438 \u043f\u043e\u0440\u044f\u0434\u043a\u0430 500 \u043c\u0438\u043b\u043b\u0438\u043e\u043d\u043e\u0432 \u043e\u0431\u044a\u0435\u043a\u0442\u043e\u0432 \u0438 \u043f\u043e\u043b\u0443\u0447\u0435\u043d\u0438\u0435\u043c \u0441\u043f\u0435\u043a\u0442\u0440\u043e\u0432 \u0431\u043e\u043b\u0435\u0435 \u0447\u0435\u043c \u0434\u043b\u044f 3 \u043c\u0438\u043b\u043b\u0438\u043e\u043d\u043e\u0432 \u043e\u0431\u044a\u0435\u043a\u0442\u043e\u0432. \u0421\u0440\u0435\u0434\u043d\u0435\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u043a\u0440\u0430\u0441\u043d\u043e\u0433\u043e \u0441\u043c\u0435\u0449\u0435\u043d\u0438\u044f \u043f\u043e \u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u044f\u043c \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a \u0441\u043e\u0441\u0442\u0430\u0432\u0438\u043b\u043e 0.1; \u0434\u043b\u044f \u044f\u0440\u043a\u0438\u0445 \u043a\u0440\u0430\u0441\u043d\u044b\u0445 \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a \u0432\u043f\u043b\u043e\u0442\u044c \u0434\u043e z=0,4, \u0434\u043b\u044f \u043a\u0432\u0430\u0437\u0430\u0440\u043e\u0432 \u0434\u043e z=5. \u041d\u0430\u0431\u043b\u044e\u0434\u0435\u043d\u0438\u044f \u0432 \u0440\u0430\u043c\u043a\u0430\u0445 \u043e\u0431\u0437\u043e\u0440\u0430 \u0441\u043f\u043e\u0441\u043e\u0431\u0441\u0442\u0432\u043e\u0432\u0430\u043b\u0438 \u043e\u0431\u043d\u0430\u0440\u0443\u0436\u0435\u043d\u0438\u044e \u043a\u0432\u0430\u0437\u0430\u0440\u043e\u0432 \u0441\u043e \u0441\u0434\u0432\u0438\u0433\u043e\u043c \u0431\u043e\u043b\u0435\u0435 6.\n\n\u041f\u0440\u043e\u0435\u043a\u0442 \u0434\u0435\u043b\u0438\u0442\u0441\u044f \u043d\u0430 \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u0444\u0430\u0437: SDSS-I (2000\u20142005), SDSS-II (2005\u20142008), SDSS-III (2008\u20142014), SDSS-IV (2014\u20142020). \u0421\u043e\u0431\u0440\u0430\u043d\u043d\u044b\u0435 \u0432 \u0445\u043e\u0434\u0435 \u043e\u0431\u0437\u043e\u0440\u043e\u0432 \u0434\u0430\u043d\u043d\u044b\u0435 \u043f\u0443\u0431\u043b\u0438\u043a\u0443\u044e\u0442\u0441\u044f \u0432 \u0432\u0438\u0434\u0435 \u043e\u0442\u0434\u0435\u043b\u044c\u043d\u044b\u0445 \u0440\u0435\u043b\u0438\u0437\u043e\u0432 (Data Release), \u043f\u043e\u0441\u043b\u0435\u0434\u043d\u0438\u0439 \u0438\u0437 \u043d\u0438\u0445, DR13 \u043e\u043f\u0443\u0431\u043b\u0438\u043a\u043e\u0432\u0430\u043d \u0432 \u0430\u0432\u0433\u0443\u0441\u0442\u0435 2016 \u0433\u043e\u0434\u0430.\n\n2MASS Redshift Survey -  aims to map the distribution of galaxies and dark matter in the local universe, out to a mean redshift of z = 0.03 (roughly equivalent to 115 Mpc or 370 million light-years). It is based on galaxy selection in the near infra-red from the Two Micron All-Sky Survey (2MASS). 2MASS has now mapped all of the sky in the near infra-red J, H and K-bands. This photometric survey is complete and fully available to the public (IRSA). The 2MASS extended source catalog (XSC) includes roughly half a million galaxies to a limiting K magnitude of K=13.5 mag. 2MRS ultimately aims to determine the redshifts of all galaxies in the XSC to a magnitude of K=12.2 mag (about 100,000 galaxies) and to within 5 deg of the Galactic plane. The second phase of 2MRS is now complete, providing an all-sky survey of 45,000 galaxies with redshifts to a limiting magnitude of K=11.75 mag. It is the densest sampled all-sky redshift survey to date and its selection in the near infra-red reduces the impact of the zone of avoidance (where the plane of our own Galaxy obscures extragalactic objects). 2MRS provides complementary redshift information to deeper surveys like SDSS and the 2dFRGS which cover much smaller fractions of the sky. It improves on the IRAS redshift survey IRAS PSCz which was not able to distinguish galaxies in regions of high density (ie. clusters).\n\n\n```python\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\n```\n\n\n```python\ndata = pd.read_csv('glist_2.csv')\n```\n\n\n```python\ndata.info()\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 1200 entries, 0 to 1199\n    Data columns (total 21 columns):\n    iGalID            1200 non-null int64\n    iGrID             1200 non-null int64\n    Name              1200 non-null object\n    RAJ2000_gal       1200 non-null float64\n    DEJ2000_gal       1200 non-null float64\n    z_gal             1200 non-null float64\n    logMstar_gal      425 non-null float64\n    RAJ2000_group     1200 non-null float64\n    DEJ2000_group     1200 non-null float64\n    z_group           1200 non-null float64\n    logLtot           1200 non-null float64\n    logLobs           1200 non-null float64\n    logMtot           1200 non-null float64\n    logMstar_group    1165 non-null float64\n    NMstar            1200 non-null int64\n    logMdyn           1200 non-null float64\n    sigma             1200 non-null float64\n    Rad               1200 non-null float64\n    angRad            1200 non-null float64\n    DL                1200 non-null float64\n    Ntot              1200 non-null int64\n    dtypes: float64(16), int64(4), object(1)\n    memory usage: 197.0+ KB\n\n\n\n```python\nfrom IPython.display import Image \nImage(\"projections.png\") \n```\n\n\u0412 \u0430\u0441\u0442\u0440\u043e\u0444\u0438\u0437\u0438\u043a\u0435 \u043f\u0440\u0438\u043d\u044f\u0442\u043e \u0440\u0430\u0441\u0441\u043c\u0430\u0442\u0440\u0438\u0432\u0430\u0442\u044c \u043d\u0435\u0431\u0435\u0441\u043d\u044b\u0435 \u043e\u0431\u044a\u0435\u043a\u0442\u044b \u0432 \u043f\u0440\u043e\u0435\u043a\u0446\u0438\u0438 \u043d\u0430 \u043d\u0435\u0431\u0435\u0441\u043d\u0443\u044e \u0441\u0444\u0435\u0440\u0443.    \n\n\u041f\u0440\u0435\u0434\u043f\u043e\u043b\u0430\u0433\u0430\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u043d\u0430\u0431\u043b\u044e\u0434\u0430\u0442\u0435\u043b\u044c \u0440\u0430\u0441\u043f\u043e\u043b\u0430\u0433\u0430\u0435\u0442\u0441\u044f \u0432 \u0432\u0435\u0440\u0448\u0438\u043d\u0435 \u0443\u0433\u043b\u0430 $a$.\n\u043d\u0430 \u0440\u0438\u0441\u0443\u043d\u043a\u0435 \u043e\u0431\u043e\u0437\u043d\u0430\u0447\u0435\u043d\u043e:\n\n$O$ - \u0446\u0435\u043d\u0442\u0440 \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u043e\u0433\u043e \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u044f,\n\n$A_0$ - \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u0430\u044f \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a\u0430 \u0438\u0437 \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u044f,\n\n$r_0$ - \u0432\u0435\u043a\u0442\u043e\u0440, \u0441\u043e\u0435\u0434\u0438\u043d\u044f\u044e\u0449\u0438\u0439 \u0433\u043b\u0430\u0437 \u043d\u0430\u0431\u043b\u044e\u0434\u0430\u0442\u0435\u043b\u044f \u0438 \u0446\u0435\u043d\u0442\u0440 \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u044f $O$,\n\n$r_1$ - \u0432\u0435\u043a\u0442\u043e\u0440, \u0441\u043e\u0435\u0434\u0438\u043d\u044f\u044e\u0449\u0438\u0439 \u0433\u043b\u0430\u0437 \u043d\u0430\u0431\u043b\u044e\u0434\u0430\u0442\u0435\u043b\u044f \u0438 \u043e\u0431\u044a\u0435\u043a\u0442 $A_0$,\n\n$P$ - \u043f\u043b\u043e\u0441\u043a\u043e\u0441\u0442\u044c \u043f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u043d\u0430\u044f \u0442\u0430\u043a\u0438\u043c \u043e\u0431\u0440\u0430\u0437\u043e\u043c, \u0447\u0442\u043e \u043e\u043d\u0430 \u043f\u0435\u0440\u043f\u0435\u043d\u0434\u0438\u043a\u0443\u043b\u044f\u0440\u043d\u0430 \u0432\u0435\u043a\u0442\u043e\u0440\u0443   $r_0$ \u0438 \u043f\u0440\u043e\u0445\u043e\u0434\u0438\u0442 \u0447\u0435\u0440\u0435\u0437 \u0446\u0435\u043d\u0442\u0440 \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u044f $O$,\n\n$A$ - \u0442\u043e\u0447\u043a\u0430 \u043f\u0435\u0440\u0435\u0441\u0435\u0447\u0435\u043d\u0438\u044f \u043b\u0443\u0447\u0430, \u0438\u0434\u0443\u0449\u0435\u0433\u043e \u0438\u0437 \u0433\u043b\u0430\u0437\u0430 \u043d\u0430\u0431\u043b\u044e\u0434\u0430\u0442\u0435\u043b\u044f \u0447\u0435\u0440\u0435\u0437 \u043e\u0431\u044a\u0435\u043a\u0442 $\u0410_0$ \u0441 \u043f\u043b\u043e\u0441\u043a\u043e\u0441\u0442\u044c\u044e $P$,\n\n$H$ - \u043f\u0435\u0440\u043f\u0435\u043d\u0434\u0438\u043a\u0443\u043b\u044f\u0440, \u043e\u043f\u0443\u0449\u0435\u043d\u043d\u044b\u0439 \u0438\u0437 \u0438\u0437  $A_0$ \u043d\u0430 \u043f\u043b\u043e\u0441\u043a\u043e\u0441\u0442\u044c $H$,\n\n$a$ - \u043b\u0438\u043d\u0435\u0439\u043d\u044b\u0439 \u0443\u0433\u043e\u043b \u043c\u0435\u0436\u0434\u0443 \u0432\u0435\u043a\u0442\u043e\u0440\u0430\u043c\u0438 $r_0$ \u0438 $r_1$,\n\n\u043a\u0440\u0430\u0441\u043d\u044b\u0435 \u043e\u0442\u0440\u0435\u0437\u043a\u0438 $OA(OH)$ -  \u043f\u0440\u043e\u0435\u043a\u0446\u0438\u0438 \u043d\u0430 \u043f\u043b\u043e\u0441\u043a\u043e\u0441\u0442\u044c \u0420.\n\n###### \u0422\u0430\u043a \u043a\u0430\u043a \u043d\u0430\u0431\u043b\u044e\u0434\u0435\u043d\u0438\u044f \u043f\u0440\u043e\u0432\u043e\u0434\u044f\u0442\u0441\u044f \u0438\u0437 \u043e\u0434\u043d\u043e\u0439 \u0442\u043e\u0447\u043a\u0438, \u0442\u043e \u0438\u043d\u0442\u0435\u0440\u0435\u0441\u0443\u044e\u0449\u0430\u044f \u043d\u0430\u0441 \u043f\u0440\u043e\u0435\u043a\u0446\u0438\u044f - \u0446\u0435\u043d\u0442\u0440\u0430\u043b\u044c\u043d\u0430\u044f. \n\n\u041f\u043e\u0441\u043a\u043e\u043b\u044c\u043a\u0443 \u0434\u0430\u043d\u043d\u044b\u0435 \u043e\u0431 \u0443\u0433\u043b\u0430\u0445  right ascention (RAJ2000) \u0438 declination (DEJ2000) \u0443\u043a\u0430\u0437\u0430\u043d\u044b \u0432 \u0433\u0440\u0430\u0434\u0443\u0441\u0430\u0445, \u0430 \u0432\u044b\u0447\u0438\u0441\u043b\u0435\u043d\u0438\u044f\u0445 \u043c\u044b \u0431\u0443\u0434\u0435\u043c \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c\u0441\u044f \u0440\u0430\u0434\u0438\u0430\u043d\u0430\u043c\u0438, \u0442\u043e \u0441 \u043f\u043e\u043c\u043e\u0449\u044c\u044e \u0444\u043e\u0440\u043c\u0443\u043b\u044b \u043f\u0435\u0440\u0435\u0439\u0434\u0435\u043c \u043e\u0442 \u043e\u0434\u043d\u0438\u0445 \u0435\u0434\u0438\u043d\u0438\u0446 \u0438\u0437\u043c\u0435\u0440\u0435\u043d\u0438\u044f \u043a \u0434\u0440\u0443\u0433\u0438\u043c:\n\n\\begin{equation}\n\\alpha_{rad} = \\pi \\frac{\\alpha_{grad}}{180}\n\\end{equation}\n\n\n```python\n# data['RAJ2000_gal_rad'] = np.pi*data['RAJ2000_gal']/180\n# data['DEJ2000_gal_rad'] = np.pi*data['DEJ2000_gal']/180\n# data['RAJ2000_group_rad'] = np.pi*data['RAJ2000_group']/180\n# data['DEJ2000_group_rad'] = np.pi*data['DEJ2000_group']/180\n```\n\n\u0427\u0435\u0440\u0435\u0437 \u0434\u0430\u043d\u043d\u044b\u0435 \u043e\u0431 \u0443\u0433\u043b\u0430\u0445 \u043d\u0430\u043a\u043b\u043e\u043d\u0435\u043d\u0438\u044f (DEC=DEJ2000) \u0438 \u0432\u043e\u0437\u043d\u0435\u0441\u0435\u043d\u0438\u044f (RA=RAJ2000) \u0432\u044b\u0447\u0438\u0441\u043b\u044f\u044e\u0442\u0441\u044f \u043a\u043e\u043e\u0440\u0434\u0438\u043d\u0430\u0442\u044b \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0449\u0435\u0433\u043e \u043e\u0431\u044a\u0435\u043a\u0442\u0430 \u043d\u0430 \u0435\u0434\u0438\u043d\u0438\u0447\u043d\u043e\u0439 \u0441\u0444\u0435\u0440\u0435:\n\n \\begin{equation}\n\\left\\{ \\begin{array}{ll}\n    x = \\cos(DEC)\\cos(RA) \\\\\n    y = \\cos(DEC)\\sin(RA)\\\\\n    z = \\sin(DEC)\n\\end{array} \\right.\n\\end{equation}\n\n\u0414\u0430\u043b\u0435\u0435 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u0432\u044b\u0447\u0438\u0441\u043b\u0438\u0442\u044c \u0434\u043b\u0438\u043d\u043d\u0443 \u043f\u0440\u043e\u0435\u043a\u0446\u0438\u0438 $OA$  \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0439 \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a\u0438 \u0438\u0437 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0449\u0435\u0433\u043e \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u044f \u043f\u043e \u0432\u0441\u0435\u043c \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u044f\u043c \u0441 \u043f\u043e\u043c\u043e\u0449\u044c\u044e \u0444\u043e\u0440\u043c\u0443\u043b\u044b: \n\n\\begin{equation}\n     r_{pr} = r_0 \\tan(a),\n\\end{equation}\n\n\u0433\u0434\u0435 \u0443\u0433\u043e\u043b $\u0430$ - \u043b\u0438\u043d\u0435\u0439\u043d\u044b\u0439 \u0443\u0433\u043e\u043b \u043c\u0435\u0436\u0434\u0443 \u043b\u0443\u0447\u0430\u043c\u0438, \u0441\u043e\u0435\u0434\u0438\u043d\u044f\u044e\u0449\u0438\u043c\u0438 \u043d\u0430\u0431\u043b\u044e\u0434\u0430\u0442\u0435\u043b\u044f \u0441 \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a\u043e\u0439 \u0432 \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u0438 \u0438 \u043d\u0430\u0431\u043b\u044e\u0434\u0430\u0442\u0435\u043b\u044f \u0441 \u0446\u0435\u043d\u0442\u0440\u043e\u043c \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u044f. \u0417\u043d\u0430\u044f \u0443\u0433\u043b\u044b \u043d\u0430\u043a\u043b\u043e\u043d\u0435\u043d\u0438\u044f (DEC=DEJ2000) \u0438 \u0432\u043e\u0437\u043d\u0435\u0441\u0435\u043d\u0438\u044f (RA=RAJ2000), \u043c\u043e\u0436\u043d\u043e \u0432\u044b\u0447\u0438\u0441\u043b\u0438\u0442\u044c \u0442\u0430\u043d\u0433\u0435\u043d\u0441 \u0443\u0433\u043b\u0430 $\u0430$:\n\n \\begin{equation}\n\\left\\{ \\begin{array}{ll}\n    x = \\cos(DEC)\\cos(RA) \\\\\n    y = \\cos(DEC)\\sin(RA)\\\\\n    z = \\sin(DEC)\n\\end{array} \\right.\n\\end{equation}\n\n\\begin{equation}\n\\cos(a) = x_{centr}x_{gal} + y_{centr}y_{gal}+z_{centr}z_{gal}\n\\end{equation}\n\n\\begin{equation}\n\\tan(a) = \\frac{\\sqrt{1-\\cos^2(a)}}{\\cos(a)}\n\\end{equation}\n\n\u0412\u0432\u0435\u0434\u0435\u043c \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c\u044b\u0435 \u0432 \u0434\u0430\u043b\u044c\u043d\u0435\u0439\u0448\u0435\u043c \u0438\u0441\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u043d\u0438\u0438 \u043a\u043e\u0441\u043c\u043e\u043b\u043e\u0433\u0438\u0447\u0435\u0441\u043a\u0438\u0435 \u043f\u043e\u0441\u0442\u043e\u044f\u043d\u043d\u044b\u0435:\n\n\n```python\nC = 300000  # km/s -  \u0441\u043a\u043e\u0440\u043e\u0441\u0442\u044c \u0441\u0432\u0435\u0442\u0430 \u0432 \u0432\u0430\u043a\u0443\u0443\u043c\u0435\nMpc = 3.086e+19 # km -  \u043c\u0435\u0433\u0430\u043f\u0430\u0440\u0441\u0435\u043a\n```\n\n\n```python\n# x0 = np.cos(data['DEJ2000_group_rad'])*np.cos(data['RAJ2000_group_rad'])\n# y0 = np.cos(data['DEJ2000_group_rad'])*np.sin(data['RAJ2000_group_rad'])\n# z0 = np.sin(data['DEJ2000_group_rad'])\n\n# x1 = np.cos(data['DEJ2000_gal_rad'])*np.cos(data['RAJ2000_gal_rad'])\n# y1 = np.cos(data['DEJ2000_gal_rad'])*np.sin(data['RAJ2000_gal_rad'])\n# z1 = np.sin(data['DEJ2000_gal_rad'])\n\n# cos_a = x0*x1+y0*y1+z0*z1\n\n# tan_a = pd.Series(np.sqrt(1-cos_a**2)/cos_a).fillna(0)\n```\n\n\n```python\n# data['r_pr'] = data['DL']*tan_a\n```\n\n\u0421\u043a\u043e\u0440\u043e\u0441\u0442\u0438 \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a \u0432 \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u0438 \u043e\u0442\u043d\u043e\u0441\u0438\u0442\u0435\u043b\u044c\u043d\u043e \u0446\u0435\u043d\u0442\u0440\u0430 \u044d\u0442\u043e\u0433\u043e \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u044f \u0432\u044b\u0441\u0447\u0438\u0442\u044b\u0432\u0430\u043b\u0438\u0441\u044c \u0441 \u043f\u043e\u043c\u043e\u0449\u044c\u044e \u0444\u043e\u0440\u043c\u0443\u043b\u044b: \n\n\\begin{equation}\n    v = c\\frac{z_{gal} - z_{cent}}{1 + z_{cent}}\n\\end{equation}\n\n\u041e\u0442\u043c\u0435\u0442\u0438\u043c, \u0447\u0442\u043e \u0432\u0441\u0435 \u044d\u0442\u0438 \u0441\u043a\u043e\u0440\u043e\u0441\u0442\u0438 \u043c\u043e\u0433\u0443\u0442 \u0432\u044b\u0447\u0438\u0441\u043b\u0435\u043d\u044b \u0442\u043e\u043b\u044c\u043a\u043e \u0432\u0434\u043e\u043b\u044c \u043b\u0443\u0447\u0430 \u0437\u0440\u0435\u043d\u0438\u044f (line-of-sight) \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0430\u043d\u0438\u0438 \u0438\u0437\u043c\u0435\u0440\u0435\u043d\u0438\u0439 \u043a\u0440\u0430\u0441\u043d\u043e\u0433\u043e \u0441\u043c\u0435\u0449\u0435\u043d\u0438\u044f (red shift)  $z$ \u0440\u0430\u0441\u0441\u043c\u0430\u0442\u0440\u0438\u0432\u0430\u0435\u043c\u043e\u0433\u043e \u043e\u0431\u044a\u0435\u043a\u0442\u0430. \u041f\u043e\u043f\u0435\u0440\u0435\u0447\u043d\u044b\u0435 \u0441\u043a\u043e\u0440\u043e\u0441\u0442\u0438 \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u044c \u0441\u043b\u043e\u0436\u043d\u043e, \u0442\u0430\u043a \u043a\u0430\u043a \u0432\u0440\u0435\u043c\u044f \u0441\u044a\u0435\u043c\u043a\u0438 \u0442\u0435\u043b\u0435\u0441\u043a\u043e\u043f\u043e\u043c \u0434\u0430\u043d\u043d\u043e\u0433\u043e \u0443\u0447\u0430\u0441\u0442\u043a\u0430 \u043d\u0435\u0431\u0430 \u043f\u043e \u0441\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u044e \u0441 \u043f\u0435\u0440\u0435\u043c\u0435\u0449\u0435\u043d\u0438\u0435\u043c \u043e\u0431\u044a\u0435\u043a\u0442\u0430 \u043f\u043e \u043d\u0435\u0431\u0435\u0441\u043d\u043e\u0439 \u0441\u0444\u0435\u0440\u0435 \u043d\u0438\u0447\u0442\u043e\u0436\u043d\u043e \u043c\u0430\u043b\u043e, \u0430 \u043f\u043e\u0442\u043e\u043c\u0443 \u0443\u0432\u0438\u0434\u0435\u0442\u044c \u043a\u0430\u043a\u0438\u0435-\u0442\u043e \u0432\u0438\u0434\u0438\u043c\u044b\u0435 \u0438\u0437\u043c\u0435\u043d\u0438\u044f \u0432 \u043f\u043e\u043b\u043e\u0436\u0435\u043d\u0438\u0438 \u043e\u0431\u044a\u0435\u043a\u0442\u0430 \u043d\u0430 \u043d\u0435\u0431\u0435 \u043f\u043e\u043a\u0430 \u043d\u0435 \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u0432\u043e\u0437\u043c\u043e\u0436\u043d\u044b\u043c.\n\n\n```python\n# data['v'] = C*(data['z_gal']-data['z_group'])/(1+data['z_group'])\n```\n\n\n```python\n# data.info()\n```\n\n\n```python\n# def drawPlot(data, GrID, ax, c):\n#     x_max = data['r_pr'].max()\n#     y_max = abs(data['v']).max()\n#     gr = data[data['iGrID'] == GrID] \n#     x = gr['r_pr']\n#     y = gr['v'] \n#     ax.scatter(x, y, c=c, marker='*')\n#     ax.set_xlabel('Distance from center of the cluster, [Mpc]')\n#     ax.set_ylabel('Relative velocity in the cluster, [km/s]')\n#     ax.set_title('iGrID = %d' % (GrID))\n#     ax.set_ylim(top=y_max, bottom=-y_max)\n#     ax.set_xlim((0,x_max))\n#     ax.grid(True)\n```\n\n\n```python\n# fig, axs = plt.subplots(7, 3, figsize=(15,25))\n# GrIDs = data['iGrID'].unique() #\u0421\u043e\u0437\u0434\u0430\u0451\u043c \u0432\u0435\u043a\u0442\u043e\u0440 \u0432\u0441\u0435\u0445 \u0433\u0440\u0443\u043f\u043f\n# for i in range(21):\n#     drawPlot(data, GrIDs[i], axs[i//3, i%3], 'blue') #\u0414\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0439 \u0433\u0440\u0443\u043f\u043f\u044b \u0432\u044b\u0437\u044b\u0432\u0430\u0435\u043c \u0444\u0443\u043d\u043a\u0446\u0438\u044e \u0438 \u043f\u0435\u0440\u0435\u0434\u0430\u0451\u043c \u0435\u0439 \u043d\u0443\u0436\u043d\u044b\u0439 '\u043f\u043e\u0434\u0433\u0440\u0430\u0444\u0438\u043a'\n# plt.tight_layout()\n```\n\n\u0414\u0430\u043b\u0435\u0435 \u0432\u043e\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c\u0441\u044f \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u043e\u0439 'Caustic mass estimator for astrophysical systems', \u0432\u0437\u044f\u0442\u043e\u0439 \u0441 \u0440\u0435\u043f\u043e\u0437\u0438\u0442\u043e\u0440\u0438\u044f  Dan Gifford \u043d\u0430 GitHub http://github.com/giffordw . \u0414\u0430\u043d\u043d\u0430\u044f \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0430 \u043f\u043e\u0437\u0432\u043e\u043b\u044f\u0435\u0442 \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0435 \u0434\u0430\u043d\u043d\u044b\u0445 \u043e\u0431 \u0443\u0433\u043b\u0430\u0445   RA, DEC \u0438 \u043a\u0440\u0430\u0441\u043d\u043e\u0433\u043e \u0441\u043c\u0435\u0449\u0435\u043d\u0438\u044f z \u0441\u0442\u0440\u043e\u0438\u0442\u044c \u043a\u0430\u0443\u0441\u0442\u0438\u0447\u0435\u0441\u043a\u0438\u0435 \u043a\u0440\u0438\u0432\u044b\u0435 \u0434\u043b\u044f \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u0439 \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a. \u041f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u043d\u044b\u0439 \u043a\u043e\u0434 \u043e\u0441\u043d\u043e\u0432\u044b\u0432\u0430\u0435\u0442\u0441\u044f \u043d\u0430 \u043c\u0435\u0442\u043e\u0434\u0430\u0445, \u043e\u043f\u0438\u0441\u0430\u043d\u043d\u044b\u0445 \u0432 \u0441\u0442\u0430\u0442\u044c\u044f\u0445:\n- A.Diafferio. Mass estimation in the outer regions of galaxy clusters. 1999.\n- Gifford et al. A Systematic Analysis of Caustic Methods for Galaxy Cluster Masses. 2013.\n- Gifford & Miller. Velocity Anisotropy and Shape Bias in the Caustic Technique. 2013.\n\n\u041a\u0430\u0443\u0441\u0442\u0438\u043a\u0438 - \u044d\u0442\u043e \u043d\u0435\u043a\u0438\u0435 \u043a\u0440\u0438\u0432\u044b\u0435 \u0432 \u0444\u0430\u0437\u043e\u0432\u043e\u0439 \u043f\u043b\u043e\u0441\u043a\u043e\u0441\u0442\u0438 (r,v), \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0440\u0430\u0437\u0434\u0435\u043b\u044f\u044e\u0442 \u044d\u0442\u0443 \u043f\u043b\u043e\u0441\u043a\u043e\u0441\u0442\u044c \u043d\u0430 \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u0441\u0435\u0433\u043c\u0435\u0442\u043e\u0432: \u0446\u0435\u043d\u0442\u0440\u0430\u043b\u044c\u043d\u044b\u0439, \u043d\u0438\u0436\u043d\u0438\u0439 \u0438 \u0432\u0435\u0440\u0445\u043d\u0438\u0439. \u0418\u0437 \u0432\u0437\u0430\u0438\u043c\u043d\u043e\u0433\u043e \u043f\u043e\u043b\u043e\u0436\u0435\u043d\u0438\u044f \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a \u0432 \u043a\u043e\u043f\u043b\u0435\u043d\u0438\u0438 \u0438 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0449\u0438\u0445 \u043a\u0430\u0443\u0441\u0442\u0438\u043a \u043d\u0430 \u0444\u0430\u0437\u043e\u0432\u043e\u0439 \u043f\u043b\u043e\u0441\u043a\u043e\u0441\u0442\u0438 \u043c\u043e\u0436\u043d\u043e \u0441\u0443\u0434\u0438\u0442\u044c \u043e \u0431\u0443\u0434\u0443\u044e\u0449\u0435\u043c \u044d\u0442\u043e\u0433\u043e \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u044f. \u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0435\u0441\u043b\u0438 \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a\u0438 \u043b\u0435\u0436\u0430\u0442 \u0432\u043d\u0435 \u0446\u0435\u043d\u0442\u0440\u0430\u043b\u044c\u043d\u043e\u0439 \u043e\u0431\u043b\u0430\u0441\u0442\u0438, \u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u043d\u043e\u0439 \u043a\u0430\u0443\u0441\u0442\u0438\u043a\u0430\u043c\u0438, \u0442\u043e \u043c\u043e\u0436\u043d\u043e \u0437\u0430\u043a\u043b\u044e\u0447\u0438\u0442\u044c, \u0447\u0442\u043e \u0434\u0430\u043d\u043d\u0430\u044f \u0433\u0430\u043b\u0430\u043a\u0442\u0438\u043a\u0430 \u0432 \u0431\u0443\u0434\u0443\u0449\u0435\u043c \u043f\u043e\u043a\u0438\u043d\u0435\u0442 \u044d\u0442\u043e \u0441\u043a\u043e\u043f\u043b\u0435\u043d\u0438\u0435.\n\n\n```python\n# !pip install cosmolopy\n```\n\n\n```python\n# !pip install scikit-image\n```\n\n\n```python\nfrom causticpy import *\n```\n\n\n```python\niGrID = data['iGrID'].unique()[0:1]\n```\n\n\n```python\ndata.columns\n```\n\n\n\n\n    Index(['iGalID', 'iGrID', 'Name', 'RAJ2000_gal', 'DEJ2000_gal', 'z_gal',\n           'logMstar_gal', 'RAJ2000_group', 'DEJ2000_group', 'z_group', 'logLtot',\n           'logLobs', 'logMtot', 'logMstar_group', 'NMstar', 'logMdyn', 'sigma',\n           'Rad', 'angRad', 'DL', 'Ntot'],\n          dtype='object')\n\n\n\n\n```python\nnew = (data[data['iGrID'].isin(iGrID)][['RAJ2000_gal', 'DEJ2000_gal', 'z_gal', \n                                          'RAJ2000_group', 'DEJ2000_group', 'z_group', 'iGrID', 'DL']])\n```\n\n\n```python\n# new\n```\n\n\n```python\nnew['z_group'] = new.loc[10,'z_gal']\nnew['RAJ2000_group'] = new.loc[10,'RAJ2000_gal'] \nnew['DEJ2000_group'] = new.loc[10,'DEJ2000_gal'] \n```\n\n\n```python\n# new\n```\n\n\n```python\ndata = new\n```\n\n\n```python\ndata['RAJ2000_gal_rad'] = np.pi*data['RAJ2000_gal']/180\ndata['DEJ2000_gal_rad'] = np.pi*data['DEJ2000_gal']/180\ndata['RAJ2000_group_rad'] = np.pi*data['RAJ2000_group']/180\ndata['DEJ2000_group_rad'] = np.pi*data['DEJ2000_group']/180\n```\n\n\n```python\n\n\nx0 = np.cos(data['DEJ2000_group_rad'])*np.cos(data['RAJ2000_group_rad'])\ny0 = np.cos(data['DEJ2000_group_rad'])*np.sin(data['RAJ2000_group_rad'])\nz0 = np.sin(data['DEJ2000_group_rad'])\n\nx1 = np.cos(data['DEJ2000_gal_rad'])*np.cos(data['RAJ2000_gal_rad'])\ny1 = np.cos(data['DEJ2000_gal_rad'])*np.sin(data['RAJ2000_gal_rad'])\nz1 = np.sin(data['DEJ2000_gal_rad'])\n\ncos_a = x0*x1+y0*y1+z0*z1\n\ntan_a = pd.Series(np.sqrt(1-cos_a**2)/cos_a).fillna(0)\n```\n\n\n```python\ndata['r_pr'] = data['DL']*tan_a\n```\n\n\n```python\ndata['v'] = C*(data['z_gal']-data['z_group'])/(1+data['z_group'])\n```\n\n\n```python\ngalaxydata = data.to_numpy()\n```\n\n\n```python\n# galaxydata\n```\n\n\n```python\n# galaxydata[:,3].mean()\n```\n\n\n```python\nc = Caustic()\ngood_flag = c.run_caustic(galaxydata, \n                          clus_ra=galaxydata[:,3].mean(),\n                          clus_dec=galaxydata[:,4].mean(),\n                          clus_z=galaxydata[:,5].mean())#, r200=0.743, clus_ra=195.095, clus_dec=19.131,clus_z=0.063)\n```\n\n    DATA SET SIZE 43\n    Pre_r200= 0.44956051186426654\n    Calculating Density w/Mirrored Data\n    Vdisp from galaxies= 97.54155922752271\n    Combined Vdisp= 97.54155922752271\n    Calculating initial surface\n    complete\n    r200 estimate:  0.16901661771294996\n    M200 estimate:  587909596836.2314\n\n\n\n```python\nfig, ax = plt.subplots(1, 1, figsize=(7,5))\nx_max = data['r_pr'].max()\ny_max = abs(data['v']).max()\ngr = data\nx = gr['r_pr']\ny = gr['v'] \nax.scatter(x, y, c=gr['iGrID'], marker='*')\nax.plot(c.x_range, c.caustic_profile, c='red')\nax.plot(c.x_range, -c.caustic_profile, c='red')\nax.set_xlabel('Distance from center of the cluster, [Mpc]')\nax.set_ylabel('Relative velocity in the cluster, [km/s]')\n# ax.set_title('iGrID = %d' % (iGrID))\nax.set_ylim(top=y_max*1.1, bottom=-y_max*1.1)\nax.set_xlim((0,10))\nax.grid(True)\nplt.savefig(\"caustic.png\")\n```\n\n\n```python\n# from IPython.display import Image \nImage(\"caustic.png\") \n```\n\n\n```python\nfrom pylab import *\nplot(c.r,c.v,'o', c='black')\nplt.savefig(\"caustic.png\")\nImage(\"caustic.png\") \n```\n\n\n```python\n# \u041f\u0440\u043e\u0432\u0435\u0440\u0438\u0442\u044c \u043f\u043e\u0447\u0435\u043c\u0443 \u043d\u0435 \u0440\u0430\u0431\u043e\u0442\u0430\u0435\u0442???\n\n# plot(data[data['iGrID']==iGrID]['r_pr'],data[data['iGrID']==iGrID]['v'],'o', c='black')\n# show()\n```\n\n\u041f\u043e\u043d\u044f\u0442\u044c \u043a\u0430\u043a \u043e\u043d\u0438 \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u044f\u044e\u0442 \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u044f. \u041e\u0447\u0435\u0432\u0438\u0434\u043d\u043e, \u0447\u0442\u043e \u043d\u0435\u043c\u043d\u043e\u0433\u043e \u043f\u043e-\u0434\u0440\u0443\u0433\u043e\u043c\u0443. \u042d\u0442\u043e \u043c\u043e\u0436\u0435\u0442 \u0431\u044b\u0442\u044c \u043f\u0440\u0438\u0447\u0438\u043d\u043e\u0439 \u0440\u0430\u0437\u043b\u0438\u0447\u0438\u044f \u0432 \u043e\u0446\u0435\u043d\u0435\u043d\u043d\u044b\u0445 \u043c\u0430\u0441\u0441\u0430\u0445 \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0435 \u043a\u0430\u0443\u0441\u0442\u0438\u043a \u0438 Mtot \u0438\u0437 \u0442\u0430\u0431\u043b\u0438\u0446.\n\nTo make two pictures made above look simular we made same changes in the \n- file \"\\__init\\__\"\n- in class Caustic\n- in function run_caustic\n- in function findangle(self,ra,dec,clus_RA,clus_DEC)\n\nBecause with a previous code a projected radius was calculated another way.\n\n\n```python\nm = MassCalc(ri = c.x_range,\n    A = c.caustic_profile,\n    vdisp = c.vdisp_gal,\n    clus_z = galaxydata[:,5].mean(),\n    r200=2.0,\n    conc1=5,\n    beta=0.25,\n    fbr=None,\n    H0=100.0,)\n```\n\n\n```python\nm.M200\n```\n\n\n\n\n    13065539260081.135\n\n\n\n\n```python\n12427715478374.973 # for native radius calculatiouns\n12427715478374.607 # data[data['iGrID']==iGrID]['sigma'].mean()\n12427715478374.607 # for c.vdisp_gal\n```\n\n\n\n\n    12427715478374.607\n\n\n\nLet's put caustic profile onto the galaxy cluster in a phase space\n", "meta": {"hexsha": "ff9dbdd230c78c97e6ab83b4fc9c132bffdbef87", "size": 98018, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "caustics/About_caustics.ipynb", "max_stars_repo_name": "Azarodnyuk/galaxymass", "max_stars_repo_head_hexsha": "cee5f9dc05b5675d0a3a0de111d18c24f057f6a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-09T13:05:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-09T13:05:02.000Z", "max_issues_repo_path": "caustics/About_caustics.ipynb", "max_issues_repo_name": "Azarodnyuk/galaxymass", "max_issues_repo_head_hexsha": "cee5f9dc05b5675d0a3a0de111d18c24f057f6a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "caustics/About_caustics.ipynb", "max_forks_repo_name": "Azarodnyuk/galaxymass", "max_forks_repo_head_hexsha": "cee5f9dc05b5675d0a3a0de111d18c24f057f6a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 132.6359945873, "max_line_length": 30912, "alphanum_fraction": 0.8736048481, "converted": true, "num_tokens": 5197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368443773709, "lm_q2_score": 0.04468087329388051, "lm_q1q2_score": 0.017529952832146225}}
{"text": "```python\n!pip install --upgrade tensorflow tensorflow-quantum matplotlib numpy sympy cirq pydot graphviz gast==0.2.2\n```\n\n    Requirement already up-to-date: tensorflow in /usr/local/lib/python3.6/dist-packages (2.2.0rc1)\n    Requirement already up-to-date: tensorflow-quantum in /usr/local/lib/python3.6/dist-packages (0.2.0)\n    Requirement already up-to-date: matplotlib in /usr/local/lib/python3.6/dist-packages (3.2.1)\n    Requirement already up-to-date: numpy in /usr/local/lib/python3.6/dist-packages (1.18.2)\n    Requirement already up-to-date: sympy in /usr/local/lib/python3.6/dist-packages (1.5.1)\n    Requirement already up-to-date: cirq in /usr/local/lib/python3.6/dist-packages (0.7.0)\n    Requirement already up-to-date: pydot in /usr/local/lib/python3.6/dist-packages (1.4.1)\n    Requirement already up-to-date: graphviz in /usr/local/lib/python3.6/dist-packages (0.13.2)\n    Requirement already satisfied, skipping upgrade: keras-preprocessing>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.1.0)\n    Requirement already satisfied, skipping upgrade: absl-py>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (0.9.0)\n    Requirement already satisfied, skipping upgrade: astunparse==1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.6.3)\n    Requirement already satisfied, skipping upgrade: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.12.1)\n    Requirement already satisfied, skipping upgrade: six>=1.12.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.12.0)\n    Requirement already satisfied, skipping upgrade: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.27.2)\n    Requirement already satisfied, skipping upgrade: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.1.0)\n    Requirement already satisfied, skipping upgrade: scipy==1.4.1; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.4.1)\n    Requirement already satisfied, skipping upgrade: tensorflow-estimator<2.3.0,>=2.2.0rc0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (2.2.0rc0)\n    Requirement already satisfied, skipping upgrade: tensorboard<2.2.0,>=2.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (2.1.1)\n    Requirement already satisfied, skipping upgrade: google-pasta>=0.1.8 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (0.2.0)\n    Requirement already satisfied, skipping upgrade: wheel>=0.26; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from tensorflow) (0.34.2)\n    Requirement already satisfied, skipping upgrade: protobuf>=3.8.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (3.10.0)\n    Requirement already satisfied, skipping upgrade: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (3.2.0)\n    Requirement already satisfied, skipping upgrade: gast==0.3.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (0.3.3)\n    Requirement already satisfied, skipping upgrade: h5py<2.11.0,>=2.10.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (2.10.0)\n    Requirement already satisfied, skipping upgrade: python-dateutil>=2.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib) (2.8.1)\n    Requirement already satisfied, skipping upgrade: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib) (1.1.0)\n    Requirement already satisfied, skipping upgrade: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib) (2.4.6)\n    Requirement already satisfied, skipping upgrade: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib) (0.10.0)\n    Requirement already satisfied, skipping upgrade: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy) (1.1.0)\n    Requirement already satisfied, skipping upgrade: networkx==2.3 in /usr/local/lib/python3.6/dist-packages (from cirq) (2.3)\n    Requirement already satisfied, skipping upgrade: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from cirq) (0.7)\n    Requirement already satisfied, skipping upgrade: google-api-python-client~=1.6 in /usr/local/lib/python3.6/dist-packages (from cirq) (1.7.12)\n    Requirement already satisfied, skipping upgrade: requests~=2.18 in /usr/local/lib/python3.6/dist-packages (from cirq) (2.21.0)\n    Requirement already satisfied, skipping upgrade: sortedcontainers~=2.0 in /usr/local/lib/python3.6/dist-packages (from cirq) (2.1.0)\n    Requirement already satisfied, skipping upgrade: typing-extensions in /usr/local/lib/python3.6/dist-packages (from cirq) (3.6.6)\n    Requirement already satisfied, skipping upgrade: pandas in /usr/local/lib/python3.6/dist-packages (from cirq) (0.25.3)\n    Requirement already satisfied, skipping upgrade: google-auth<2,>=1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.2.0,>=2.1.0->tensorflow) (1.7.2)\n    Requirement already satisfied, skipping upgrade: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.2.0,>=2.1.0->tensorflow) (0.4.1)\n    Requirement already satisfied, skipping upgrade: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.2.0,>=2.1.0->tensorflow) (3.2.1)\n    Requirement already satisfied, skipping upgrade: setuptools>=41.0.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.2.0,>=2.1.0->tensorflow) (46.0.0)\n    Requirement already satisfied, skipping upgrade: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.2.0,>=2.1.0->tensorflow) (1.0.0)\n    Requirement already satisfied, skipping upgrade: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx==2.3->cirq) (4.4.2)\n    Requirement already satisfied, skipping upgrade: uritemplate<4dev,>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client~=1.6->cirq) (3.0.1)\n    Requirement already satisfied, skipping upgrade: google-auth-httplib2>=0.0.3 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client~=1.6->cirq) (0.0.3)\n    Requirement already satisfied, skipping upgrade: httplib2<1dev,>=0.17.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client~=1.6->cirq) (0.17.0)\n    Requirement already satisfied, skipping upgrade: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (2.8)\n    Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (2019.11.28)\n    Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (3.0.4)\n    Requirement already satisfied, skipping upgrade: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (1.24.3)\n    Requirement already satisfied, skipping upgrade: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas->cirq) (2018.9)\n    Requirement already satisfied, skipping upgrade: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.2.0,>=2.1.0->tensorflow) (0.2.8)\n    Requirement already satisfied, skipping upgrade: rsa<4.1,>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.2.0,>=2.1.0->tensorflow) (4.0)\n    Requirement already satisfied, skipping upgrade: cachetools<3.2,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.2.0,>=2.1.0->tensorflow) (3.1.1)\n    Requirement already satisfied, skipping upgrade: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.2.0,>=2.1.0->tensorflow) (1.3.0)\n    Requirement already satisfied, skipping upgrade: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.6/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard<2.2.0,>=2.1.0->tensorflow) (0.4.8)\n    Requirement already satisfied, skipping upgrade: oauthlib>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.2.0,>=2.1.0->tensorflow) (3.1.0)\n\n\n\n```python\n!pip install --upgrade tensorflow pydot graphviz\n```\n\n    Requirement already up-to-date: tensorflow in /usr/local/lib/python3.6/dist-packages (2.2.0rc1)\n    Requirement already up-to-date: pydot in /usr/local/lib/python3.6/dist-packages (1.4.1)\n    Requirement already up-to-date: graphviz in /usr/local/lib/python3.6/dist-packages (0.13.2)\n    Requirement already satisfied, skipping upgrade: tensorboard<2.2.0,>=2.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (2.1.1)\n    Requirement already satisfied, skipping upgrade: protobuf>=3.8.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (3.10.0)\n    Requirement already satisfied, skipping upgrade: gast==0.3.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (0.3.3)\n    Requirement already satisfied, skipping upgrade: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.1.0)\n    Requirement already satisfied, skipping upgrade: absl-py>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (0.9.0)\n    Requirement already satisfied, skipping upgrade: wheel>=0.26; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from tensorflow) (0.34.2)\n    Requirement already satisfied, skipping upgrade: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.12.1)\n    Requirement already satisfied, skipping upgrade: scipy==1.4.1; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.4.1)\n    Requirement already satisfied, skipping upgrade: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (3.2.0)\n    Requirement already satisfied, skipping upgrade: h5py<2.11.0,>=2.10.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (2.10.0)\n    Requirement already satisfied, skipping upgrade: keras-preprocessing>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.1.0)\n    Requirement already satisfied, skipping upgrade: google-pasta>=0.1.8 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (0.2.0)\n    Requirement already satisfied, skipping upgrade: astunparse==1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.6.3)\n    Requirement already satisfied, skipping upgrade: six>=1.12.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.12.0)\n    Requirement already satisfied, skipping upgrade: numpy<2.0,>=1.16.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.18.2)\n    Requirement already satisfied, skipping upgrade: tensorflow-estimator<2.3.0,>=2.2.0rc0 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (2.2.0rc0)\n    Requirement already satisfied, skipping upgrade: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow) (1.27.2)\n    Requirement already satisfied, skipping upgrade: pyparsing>=2.1.4 in /usr/local/lib/python3.6/dist-packages (from pydot) (2.4.6)\n    Requirement already satisfied, skipping upgrade: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.2.0,>=2.1.0->tensorflow) (3.2.1)\n    Requirement already satisfied, skipping upgrade: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.2.0,>=2.1.0->tensorflow) (0.4.1)\n    Requirement already satisfied, skipping upgrade: google-auth<2,>=1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.2.0,>=2.1.0->tensorflow) (1.7.2)\n    Requirement already satisfied, skipping upgrade: requests<3,>=2.21.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.2.0,>=2.1.0->tensorflow) (2.21.0)\n    Requirement already satisfied, skipping upgrade: setuptools>=41.0.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.2.0,>=2.1.0->tensorflow) (46.0.0)\n    Requirement already satisfied, skipping upgrade: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.2.0,>=2.1.0->tensorflow) (1.0.0)\n    Requirement already satisfied, skipping upgrade: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.2.0,>=2.1.0->tensorflow) (1.3.0)\n    Requirement already satisfied, skipping upgrade: rsa<4.1,>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.2.0,>=2.1.0->tensorflow) (4.0)\n    Requirement already satisfied, skipping upgrade: cachetools<3.2,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.2.0,>=2.1.0->tensorflow) (3.1.1)\n    Requirement already satisfied, skipping upgrade: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.2.0,>=2.1.0->tensorflow) (0.2.8)\n    Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tensorboard<2.2.0,>=2.1.0->tensorflow) (3.0.4)\n    Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tensorboard<2.2.0,>=2.1.0->tensorflow) (2019.11.28)\n    Requirement already satisfied, skipping upgrade: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tensorboard<2.2.0,>=2.1.0->tensorflow) (1.24.3)\n    Requirement already satisfied, skipping upgrade: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tensorboard<2.2.0,>=2.1.0->tensorflow) (2.8)\n    Requirement already satisfied, skipping upgrade: oauthlib>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.2.0,>=2.1.0->tensorflow) (3.1.0)\n    Requirement already satisfied, skipping upgrade: pyasn1>=0.1.3 in /usr/local/lib/python3.6/dist-packages (from rsa<4.1,>=3.1.4->google-auth<2,>=1.6.3->tensorboard<2.2.0,>=2.1.0->tensorflow) (0.4.8)\n\n\n\n```python\n!pip install tensorflow==1.15.0 gast==0.2.2\n```\n\n    Collecting tensorflow==1.15.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/3f/98/5a99af92fb911d7a88a0005ad55005f35b4c1ba8d75fba02df726cd936e6/tensorflow-1.15.0-cp36-cp36m-manylinux2010_x86_64.whl (412.3MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 412.3MB 38kB/s \n    \u001b[?25hRequirement already satisfied: keras-preprocessing>=1.0.5 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15.0) (1.1.0)\n    Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15.0) (1.27.2)\n    Requirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15.0) (1.12.0)\n    Requirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15.0) (0.9.0)\n    Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15.0) (1.12.1)\n    Processing /root/.cache/pip/wheels/5c/2e/7e/a1d4d4fcebe6c381f378ce7743a3ced3699feb89bcfbdadadd/gast-0.2.2-cp36-none-any.whl\n    Requirement already satisfied: astor>=0.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15.0) (0.8.1)\n    Requirement already satisfied: google-pasta>=0.1.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15.0) (0.2.0)\n    Requirement already satisfied: numpy<2.0,>=1.16.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15.0) (1.18.2)\n    Collecting tensorflow-estimator==1.15.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/de/62/2ee9cd74c9fa2fa450877847ba560b260f5d0fb70ee0595203082dafcc9d/tensorflow_estimator-1.15.1-py2.py3-none-any.whl (503kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 512kB 43.6MB/s \n    \u001b[?25hRequirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15.0) (3.2.0)\n    Collecting tensorboard<1.16.0,>=1.15.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1e/e9/d3d747a97f7188f48aa5eda486907f3b345cd409f0a0850468ba867db246/tensorboard-1.15.0-py3-none-any.whl (3.8MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.8MB 48.1MB/s \n    \u001b[?25hRequirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15.0) (0.34.2)\n    Requirement already satisfied: keras-applications>=1.0.8 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15.0) (1.0.8)\n    Requirement already satisfied: protobuf>=3.6.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15.0) (3.10.0)\n    Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15.0) (1.1.0)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard<1.16.0,>=1.15.0->tensorflow==1.15.0) (3.2.1)\n    Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard<1.16.0,>=1.15.0->tensorflow==1.15.0) (46.0.0)\n    Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tensorboard<1.16.0,>=1.15.0->tensorflow==1.15.0) (1.0.0)\n    Requirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from keras-applications>=1.0.8->tensorflow==1.15.0) (2.10.0)\n    Installing collected packages: gast, tensorflow-estimator, tensorboard, tensorflow\n      Found existing installation: gast 0.3.3\n        Uninstalling gast-0.3.3:\n          Successfully uninstalled gast-0.3.3\n      Found existing installation: tensorflow-estimator 2.2.0rc0\n        Uninstalling tensorflow-estimator-2.2.0rc0:\n          Successfully uninstalled tensorflow-estimator-2.2.0rc0\n      Found existing installation: tensorboard 2.1.1\n        Uninstalling tensorboard-2.1.1:\n          Successfully uninstalled tensorboard-2.1.1\n      Found existing installation: tensorflow 2.2.0rc1\n        Uninstalling tensorflow-2.2.0rc1:\n          Successfully uninstalled tensorflow-2.2.0rc1\n    Successfully installed gast-0.2.2 tensorboard-1.15.0 tensorflow-2.1.0 tensorflow-estimator-2.1.0\n\n\n\n\n\n```python\n!pip install tensorflow-quantum gast==0.2.2\n```\n\n    Requirement already satisfied: tensorflow-quantum in /usr/local/lib/python3.6/dist-packages (0.2.0)\n    Requirement already satisfied: cirq>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-quantum) (0.7.0)\n    Requirement already satisfied: sortedcontainers~=2.0 in /usr/local/lib/python3.6/dist-packages (from cirq>=0.7.0->tensorflow-quantum) (2.1.0)\n    Collecting sympy==1.4\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/21/21/f4105795ca7f35c541d82c5b06be684dd2f5cb4f508fb487cd7aea4de776/sympy-1.4-py2.py3-none-any.whl (5.3MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5.3MB 2.6MB/s \n    \u001b[?25hRequirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from cirq>=0.7.0->tensorflow-quantum) (0.7)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from cirq>=0.7.0->tensorflow-quantum) (0.25.3)\n    Collecting protobuf==3.8.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/d2/fb/29de8d08967f0cce1bb10b39846d836b0f3bf6776ddc36aed7c73498ca7e/protobuf-3.8.0-cp36-cp36m-manylinux1_x86_64.whl (1.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.2MB 40.5MB/s \n    \u001b[?25hRequirement already satisfied: networkx==2.3 in /usr/local/lib/python3.6/dist-packages (from cirq>=0.7.0->tensorflow-quantum) (2.3)\n    Requirement already satisfied: google-api-python-client~=1.6 in /usr/local/lib/python3.6/dist-packages (from cirq>=0.7.0->tensorflow-quantum) (1.7.12)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.6/dist-packages (from cirq>=0.7.0->tensorflow-quantum) (3.6.6)\n    Requirement already satisfied: numpy~=1.16 in /usr/local/lib/python3.6/dist-packages (from cirq>=0.7.0->tensorflow-quantum) (1.18.2)\n    Requirement already satisfied: matplotlib~=3.0 in /usr/local/lib/python3.6/dist-packages (from cirq>=0.7.0->tensorflow-quantum) (3.2.1)\n    Requirement already satisfied: requests~=2.18 in /usr/local/lib/python3.6/dist-packages (from cirq>=0.7.0->tensorflow-quantum) (2.21.0)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from cirq>=0.7.0->tensorflow-quantum) (1.4.1)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy==1.4->cirq>=0.7.0->tensorflow-quantum) (1.1.0)\n    Requirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas->cirq>=0.7.0->tensorflow-quantum) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas->cirq>=0.7.0->tensorflow-quantum) (2018.9)\n    Requirement already satisfied: six>=1.9 in /usr/local/lib/python3.6/dist-packages (from protobuf==3.8.0->cirq>=0.7.0->tensorflow-quantum) (1.12.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from protobuf==3.8.0->cirq>=0.7.0->tensorflow-quantum) (46.0.0)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx==2.3->cirq>=0.7.0->tensorflow-quantum) (4.4.2)\n    Requirement already satisfied: google-auth-httplib2>=0.0.3 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client~=1.6->cirq>=0.7.0->tensorflow-quantum) (0.0.3)\n    Requirement already satisfied: httplib2<1dev,>=0.17.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client~=1.6->cirq>=0.7.0->tensorflow-quantum) (0.17.0)\n    Requirement already satisfied: google-auth>=1.4.1 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client~=1.6->cirq>=0.7.0->tensorflow-quantum) (1.7.2)\n    Requirement already satisfied: uritemplate<4dev,>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client~=1.6->cirq>=0.7.0->tensorflow-quantum) (3.0.1)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq>=0.7.0->tensorflow-quantum) (1.1.0)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq>=0.7.0->tensorflow-quantum) (0.10.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq>=0.7.0->tensorflow-quantum) (2.4.6)\n    Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq>=0.7.0->tensorflow-quantum) (1.24.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq>=0.7.0->tensorflow-quantum) (2019.11.28)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq>=0.7.0->tensorflow-quantum) (3.0.4)\n    Requirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq>=0.7.0->tensorflow-quantum) (2.8)\n    Requirement already satisfied: cachetools<3.2,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth>=1.4.1->google-api-python-client~=1.6->cirq>=0.7.0->tensorflow-quantum) (3.1.1)\n    Requirement already satisfied: rsa<4.1,>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from google-auth>=1.4.1->google-api-python-client~=1.6->cirq>=0.7.0->tensorflow-quantum) (4.0)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.6/dist-packages (from google-auth>=1.4.1->google-api-python-client~=1.6->cirq>=0.7.0->tensorflow-quantum) (0.2.8)\n    Requirement already satisfied: pyasn1>=0.1.3 in /usr/local/lib/python3.6/dist-packages (from rsa<4.1,>=3.1.4->google-auth>=1.4.1->google-api-python-client~=1.6->cirq>=0.7.0->tensorflow-quantum) (0.4.8)\n    \u001b[31mERROR: tensorflow 2.1.0 has requirement tensorboard<2.2.0,>=2.1.0, but you'll have tensorboard 1.15.0 which is incompatible.\u001b[0m\n    Installing collected packages: sympy, protobuf\n      Found existing installation: sympy 1.5.1\n        Uninstalling sympy-1.5.1:\n          Successfully uninstalled sympy-1.5.1\n      Found existing installation: protobuf 3.10.0\n        Uninstalling protobuf-3.10.0:\n          Successfully uninstalled protobuf-3.10.0\n    Successfully installed protobuf-3.8.0 sympy-1.4\n\n\n\n\n\n```python\nimport tensorflow as tf\nimport tensorflow_quantum as tfq\n\nimport numpy as np\nimport sympy\nimport cirq\nimport seaborn as sns\nimport pandas as pd\n\n%matplotlib inline\nfrom matplotlib import style\nstyle.use('bmh')\nstyle.use('dark_background')\n\nimport matplotlib.pyplot as plt\nfrom cirq.contrib.svg import SVGCircuit\nimport pydot\nimport graphviz\n\n%tensorflow_version 1.15\nprint(tf.__version__)\n```\n\n## Loading data\n\n\n```python\ndata = np.asanyarray(pd.read_csv('./LabelledTheta.csv', delimiter=',', header=None))\n\nNUM_CHANNELS = 14\nNUM_THETA_VALUES_PER_CHANNEL = 36\nAVG_COUNT = 2\nNEW_NUM_THETA_VALUES_PER_CHANNEL = NUM_THETA_VALUES_PER_CHANNEL // AVG_COUNT -2\ndata\n```\n\n\n\n\n    array([['Ankur_sir_6', 2.661255444814941, 15.135894568013981, ...,\n            -0.08990728367798795, 0.5375088857254013, 'Like'],\n           ['Sandeep_32', -4.419225848654918, -24.76187675161037, ...,\n            -4.8016568491540434, 4.845698165412274, 'Disike'],\n           ['mahendra_28', -1.5454615508228926, 0.4458772299785068, ...,\n            0.3909845728846051, 0.3820759724008127, 'Like'],\n           ...,\n           ['mahendra_5', -12.76711513386849, -101.29815015753748, ...,\n            -1.77307011766662, -6.1868765157224885, 'Like'],\n           ['taufiq_10', -1.75569285697388, -6.889485709512044, ...,\n            -2.2842198988711147, -8.576907597818206, 'Disike'],\n           ['Vijay_32', 2.191135723676666, 10.285410138660891, ...,\n            -2.9141951374834605, -3.2100352800372605, 'Disike']], dtype=object)\n\n\n\n\n```python\ndef normalize(X_data):\n    for i in range(len(X_data)):\n        mu = X_data[i].mean()\n        sigma = X_data[i].std()\n        \n        X_data[i] = (X_data[i] - mu) / sigma\n        \n        for j in range(len(X_data[i])):\n            if X_data[i][j] > 2:\n                X_data[i][j] = 2\n            elif X_data[i][j] < -2:\n                X_data[i][j] = -2\n                \n        X_data[i] = ((X_data[i] / 5) + 0.5)\n            \n    return X_data\n```\n\n\n```python\ndef get_angles(X_data):\n    for i in range(len(X_data)):\n        X_data[i] = np.array([2 * np.arcsin(np.sqrt(x)) for x in X_data[i]])\n            \n    return X_data\n```\n\n\n```python\ndef reduce_data_size(X_data):\n  X_data_reduced = []\n  for i in range(len(X_data)):\n    X_i = []\n    for j in range(NUM_CHANNELS):\n      for k in range(2, NUM_THETA_VALUES_PER_CHANNEL-2, AVG_COUNT):\n        idx = j * NUM_THETA_VALUES_PER_CHANNEL + k\n        X_i.append((X_data[i][idx] + X_data[i][idx+1])/2)\n    \n    X_data_reduced.append(np.array(X_i))\n\n  return X_data_reduced\n```\n\n\n```python\nX = []\nY = []\nfor i in range(len(data)):\n    X.append(data[i][1:-1])\n    Y.append(data[i][-1])\n    \nX_norm = normalize(X)\nX_ang_36 = get_angles(X_norm)\n```\n\n\n```python\nprint(type(X_ang_36), type(X_ang_36[0]))\n```\n\n    <class 'list'> <class 'numpy.ndarray'>\n\n\n\n```python\nX_ang = reduce_data_size(X_ang_36)\n```\n\n\n```python\nprint(len(X_ang), len(X_ang[0]))\n```\n\n    1045 224\n\n\n\n```python\ntrain_idxs = int(len(X_ang)*0.7)+1\ntest_idxs = int(train_idxs + len(X_ang)*0.2)\n\nX_train = X_ang[:train_idxs]\nY_train = Y[:train_idxs]\n\nX_test = X_ang[train_idxs:test_idxs]\nY_test = Y[train_idxs:test_idxs]\n\nX_val = X_ang[test_idxs:]\nY_val = Y[test_idxs:]\n```\n\n\n```python\nY_train_bin = np.array([1 if y == 'Like' else -1 for y in Y_train])\nY_test_bin = np.array([1 if y == 'Like' else -1 for y in Y_test])\nY_val_bin = np.array([1 if y == 'Like' else -1 for y in Y_val])\n```\n\n## Creating a quantum circuit\n\n\n```python\ndef convert_to_circuit(one_channel_X_data):\n    '''Encode values in the quantum circuit by applying rotation gates.'''\n    qubits = cirq.GridQubit.rect(4, 4)\n    circuit = cirq.Circuit()\n    for i in range(len(one_channel_X_data)):\n        circuit.append(cirq.rx(one_channel_X_data[i]).on(qubits[i]))\n    return circuit\n```\n\n\n```python\ndef create_circuit_list(X_data):\n  X_circ = []\n  for i in range(NUM_CHANNELS):\n    X_i = []\n    start = i * NEW_NUM_THETA_VALUES_PER_CHANNEL\n    end = start + NEW_NUM_THETA_VALUES_PER_CHANNEL\n    for j in range(len(X_data)):\n      X_i.append(convert_to_circuit(X_data[j][start:end]))\n    \n    X_circ.append(tfq.convert_to_tensor(X_i))\n\n  return X_circ\n```\n\n\n```python\nX_train_circ = create_circuit_list(X_train)\nX_test_circ = create_circuit_list(X_test)\nX_val_circ = create_circuit_list(X_val)\n```\n\n\n```python\nprint(len(X_train_circ), X_train_circ[0].shape)\nprint(len(X_test_circ), X_test_circ[0].shape)\nprint(len(X_val_circ), X_val_circ[0].shape)\n```\n\n    14 (732,)\n    14 (209,)\n    14 (104,)\n\n\n#### The cluster state circuit\n\n\n```python\ndef cluster_state_circuit(bits):\n    \"\"\"Return a cluster state on the qubits in `bits`.\"\"\"\n    circuit = cirq.Circuit()\n    circuit.append(cirq.H.on_each(bits))\n    for this_bit, next_bit in zip(bits, bits[1:] + [bits[0]]):\n        circuit.append(cirq.CZ(this_bit, next_bit))\n    return circuit\n```\n\n#### QCNN Layers\n\n\n```python\ndef one_qubit_unitary(bit, symbols):\n    \"\"\"Make a Cirq circuit enacting a rotation of the bloch sphere about the X,\n    Y and Z axis, that depends on the values in `symbols`.\n    \"\"\"\n    return cirq.Circuit(\n        cirq.X(bit)**symbols[0],\n        cirq.Y(bit)**symbols[1],\n        cirq.Z(bit)**symbols[2])\n\n\ndef two_qubit_unitary(bits, symbols):\n    \"\"\"Make a Cirq circuit that creates an arbitrary two qubit unitary.\"\"\"\n    circuit = cirq.Circuit()\n    circuit += one_qubit_unitary(bits[0], symbols[0:3])\n    circuit += one_qubit_unitary(bits[1], symbols[3:6])\n    circuit += [cirq.ZZ(*bits)**symbols[7]]\n    circuit += [cirq.YY(*bits)**symbols[8]]\n    circuit += [cirq.XX(*bits)**symbols[9]]\n    circuit += one_qubit_unitary(bits[0], symbols[9:12])\n    circuit += one_qubit_unitary(bits[1], symbols[12:])\n    return circuit\n\n\ndef two_qubit_pool(source_qubit, sink_qubit, symbols):\n    \"\"\"Make a Cirq circuit to do a parameterized 'pooling' operation, which\n    attempts to reduce entanglement down from two qubits to just one.\"\"\"\n    pool_circuit = cirq.Circuit()\n    sink_basis_selector = one_qubit_unitary(sink_qubit, symbols[0:3])\n    source_basis_selector = one_qubit_unitary(source_qubit, symbols[3:6])\n    pool_circuit.append(sink_basis_selector)\n    pool_circuit.append(source_basis_selector)\n    pool_circuit.append(cirq.CNOT(control=source_qubit, target=sink_qubit))\n    pool_circuit.append(sink_basis_selector**-1)\n    return pool_circuit\n```\n\n#### Quantum Convolution\n\n\n```python\ndef quantum_conv_circuit(bits, symbols):\n    \"\"\"Quantum Convolution Layer following the above diagram.\n    Return a Cirq circuit with the cascade of `two_qubit_unitary` applied\n    to all pairs of qubits in `bits` as in the diagram above.\n    \"\"\"\n    circuit = cirq.Circuit()\n    for first, second in zip(bits[0::2], bits[1::2]):\n        circuit += two_qubit_unitary([first, second], symbols)\n    for first, second in zip(bits[1::2], bits[2::2] + [bits[0]]):\n        circuit += two_qubit_unitary([first, second], symbols)\n    return circuit\n```\n\n#### Quantum Pooling\n\n\n```python\ndef quantum_pool_circuit(source_bits, sink_bits, symbols):\n    \"\"\"A layer that specifies a quantum pooling operation.\n    A Quantum pool tries to learn to pool the relevant information from two\n    qubits onto 1.\n    \"\"\"\n    circuit = cirq.Circuit()\n    for source, sink in zip(source_bits, sink_bits):\n        circuit += two_qubit_pool(source, sink, symbols)\n    return circuit\n```\n\n### Defining the cluster state bits\n\n\n```python\ncluster_state_bits = cirq.GridQubit.rect(4, 4)\nreadouts = [cirq.Z(bit) for bit in cluster_state_bits[12:]]\n```\n\n### Model definition\n\n\n```python\ndef multi_readout_model_circuit(qubits):\n    \"\"\"Make a model circuit with less quantum pool and conv operations.\"\"\"\n    split_idx = len(qubits)//2\n    model_circuit = cirq.Circuit()\n    symbols = sympy.symbols('qconv0:21')\n    model_circuit += quantum_conv_circuit(qubits, symbols[0:15])\n    model_circuit += quantum_pool_circuit(qubits[:split_idx], qubits[split_idx:], symbols[15:21])\n    return model_circuit\n```\n\n\n```python\n# Input layer\neeg_input = tf.keras.Input(shape=(), dtype=tf.dtypes.string)\n\n# Cluster state layer\ncluster_state_layer = tfq.layers.AddCircuit()(eeg_input, prepend=cluster_state_circuit(cluster_state_bits))\n\n# Quantum layers\nquantum_layers = []\n\nfor i in range(3):\n  quantum_layers.append(tfq.layers.PQC(multi_readout_model_circuit(cluster_state_bits), readouts)(cluster_state_layer))\n\n# Contenate layer\nconcat_out = tf.keras.layers.concatenate(quantum_layers)\n\n# Classical dense layers\ndense_1 = tf.keras.layers.Dense(16)(concat_out)\ndense_2 = tf.keras.layers.Dense(8)(dense_1)\ndense_3 = tf.keras.layers.Dense(1)(dense_2)\n\n# The ML model\nhybrid_qcnn_model = tf.keras.Model(inputs=[eeg_input], outputs=[dense_3])\n\n# Print the model\ntf.keras.utils.plot_model(hybrid_qcnn_model,\n                          show_shapes=True,\n                          show_layer_names=False,\n                          dpi=70)\n```\n\n### Custom accuracy metric\n\n\n```python\n# Custom accuracy metric.\n@tf.function\ndef custom_accuracy(y_true, y_pred):\n    y_true = tf.squeeze(y_true)\n    y_pred = tf.map_fn(lambda x: 1.0 if x >= 0 else -1.0, y_pred)\n    return tf.keras.backend.mean(tf.keras.backend.equal(y_true, y_pred))\n```\n\n\n```python\nhybrid_qcnn_model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.02),\n                          loss=tf.losses.mse,\n                          metrics=[custom_accuracy])\n```\n\n\n```python\nhybrid_qcnn_history = hybrid_qcnn_model.fit(x=X_train_circ[0],\n                                            y=Y_train_bin,\n                                            batch_size=1,\n                                            epochs=1,\n                                            verbose=1,\n                                            validation_data=(X_test_circ[0], Y_test_bin))\n```\n\n    Train on 732 samples, validate on 209 samples\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "82212d2edef555497fed95f8aff5a7cc6f567557", "size": 136413, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Quantum_layer_TFQ.ipynb", "max_stars_repo_name": "AbeerVaishnav13/QNN-for-predicting-state-of-mind", "max_stars_repo_head_hexsha": "d891a3a5e51867f81bd9ceb92e83571de8fd6693", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-04T09:25:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-08T21:06:00.000Z", "max_issues_repo_path": "Quantum_layer_TFQ.ipynb", "max_issues_repo_name": "AbeerVaishnav13/QNN-for-predicting-state-of-mind", "max_issues_repo_head_hexsha": "d891a3a5e51867f81bd9ceb92e83571de8fd6693", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Quantum_layer_TFQ.ipynb", "max_forks_repo_name": "AbeerVaishnav13/QNN-for-predicting-state-of-mind", "max_forks_repo_head_hexsha": "d891a3a5e51867f81bd9ceb92e83571de8fd6693", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 136413.0, "max_line_length": 136413, "alphanum_fraction": 0.8051212128, "converted": true, "num_tokens": 10748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297238231752, "lm_q2_score": 0.06371499202962878, "lm_q1q2_score": 0.017529888160507576}}
{"text": "```python\nimport pandas as pd\nimport numpy as np\nimport xgboost as xgb\nfrom patsy import dmatrices\n\npd.options.display.max_columns = 999\npd.options.display.max_rows = 999\n```\n\n\n```python\n# pbp_data = pd.read_csv(\"./results/base-epa.csv\", encoding=\"utf-8\")\npbp_data = pd.DataFrame()\nyears = range(2014,2020)\nfor i in years:\n    url = f\"https://raw.githubusercontent.com/saiemgilani/cfbscrapR-data/master/data/parquet/pbp_players_pos_{i}.parquet\"\n    print(f\"Pulling url {url}\")\n    i_data = pd.read_parquet(url, engine='pyarrow')\n\n    #sort=True eliminates a warning and alphabetically sorts columns\n    pbp_data = pbp_data.append(i_data, sort=True)\n\n#Give each row a unique index\npbp_data.reset_index(drop=True, inplace=True)\npbp_data.head()\n```\n\n    Pulling url https://raw.githubusercontent.com/saiemgilani/cfbscrapR-data/master/data/parquet/pbp_players_pos_2014.parquet\n    Pulling url https://raw.githubusercontent.com/saiemgilani/cfbscrapR-data/master/data/parquet/pbp_players_pos_2015.parquet\n    Pulling url https://raw.githubusercontent.com/saiemgilani/cfbscrapR-data/master/data/parquet/pbp_players_pos_2016.parquet\n    Pulling url https://raw.githubusercontent.com/saiemgilani/cfbscrapR-data/master/data/parquet/pbp_players_pos_2017.parquet\n    Pulling url https://raw.githubusercontent.com/saiemgilani/cfbscrapR-data/master/data/parquet/pbp_players_pos_2018.parquet\n    Pulling url https://raw.githubusercontent.com/saiemgilani/cfbscrapR-data/master/data/parquet/pbp_players_pos_2019.parquet\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>EPA</th>\n      <th>ExpScoreDiff</th>\n      <th>ExpScoreDiff_Time_Ratio</th>\n      <th>FG_after</th>\n      <th>FG_before</th>\n      <th>Goal_To_Go</th>\n      <th>Goal_To_Go_end</th>\n      <th>No_Score_after</th>\n      <th>No_Score_before</th>\n      <th>Opp_FG_after</th>\n      <th>Opp_FG_before</th>\n      <th>Opp_Safety_after</th>\n      <th>Opp_Safety_before</th>\n      <th>Opp_TD_after</th>\n      <th>Opp_TD_before</th>\n      <th>Safety_after</th>\n      <th>Safety_before</th>\n      <th>TD_after</th>\n      <th>TD_before</th>\n      <th>TimeSecsRem</th>\n      <th>TimeSecsRem_end</th>\n      <th>Under_three</th>\n      <th>Under_two</th>\n      <th>Under_two_end</th>\n      <th>adj_TimeSecsRem</th>\n      <th>away</th>\n      <th>away_EPA</th>\n      <th>away_EPA_pass</th>\n      <th>away_EPA_rush</th>\n      <th>away_wp_after</th>\n      <th>away_wp_before</th>\n      <th>change_of_pos_team</th>\n      <th>change_of_poss</th>\n      <th>clock.minutes</th>\n      <th>clock.seconds</th>\n      <th>completion</th>\n      <th>completion_player</th>\n      <th>completion_player_id</th>\n      <th>completion_yds</th>\n      <th>def_EPA</th>\n      <th>def_pos_team</th>\n      <th>def_pos_team_score</th>\n      <th>def_pos_team_timeouts</th>\n      <th>def_pos_team_timeouts_rem_before</th>\n      <th>def_timeout_called</th>\n      <th>def_timeouts_rem_before</th>\n      <th>def_wp_after</th>\n      <th>def_wp_before</th>\n      <th>defense_conference</th>\n      <th>defense_play</th>\n      <th>defense_score</th>\n      <th>defense_score_play</th>\n      <th>defense_timeouts</th>\n      <th>distance</th>\n      <th>distance_end</th>\n      <th>down</th>\n      <th>down_end</th>\n      <th>downs_turnover</th>\n      <th>drive_end_period</th>\n      <th>drive_end_yards_to_goal</th>\n      <th>drive_event_number</th>\n      <th>drive_id</th>\n      <th>drive_num</th>\n      <th>drive_number</th>\n      <th>drive_numbers</th>\n      <th>drive_play_number</th>\n      <th>drive_pts</th>\n      <th>drive_result</th>\n      <th>drive_result2</th>\n      <th>drive_result_detailed</th>\n      <th>drive_result_detailed_flag</th>\n      <th>drive_scoring</th>\n      <th>drive_start_period</th>\n      <th>drive_start_yards_to_goal</th>\n      <th>drive_time_minutes_elapsed</th>\n      <th>drive_time_minutes_end</th>\n      <th>drive_time_minutes_start</th>\n      <th>drive_time_seconds_elapsed</th>\n      <th>drive_time_seconds_end</th>\n      <th>drive_time_seconds_start</th>\n      <th>drive_yards</th>\n      <th>end_of_half</th>\n      <th>ep_after</th>\n      <th>ep_before</th>\n      <th>epa_success</th>\n      <th>fg_block_player_name</th>\n      <th>fg_inds</th>\n      <th>fg_kicker_player_name</th>\n      <th>fg_made</th>\n      <th>fg_make_prob</th>\n      <th>fg_return_player_name</th>\n      <th>firstD_by_kickoff</th>\n      <th>firstD_by_penalty</th>\n      <th>firstD_by_poss</th>\n      <th>firstD_by_yards</th>\n      <th>first_by_penalty</th>\n      <th>first_by_yards</th>\n      <th>fumble_forced_player</th>\n      <th>fumble_forced_player_id</th>\n      <th>fumble_forced_player_name</th>\n      <th>fumble_forced_stat</th>\n      <th>fumble_player</th>\n      <th>fumble_player_id</th>\n      <th>fumble_player_name</th>\n      <th>fumble_recovered_player</th>\n      <th>fumble_recovered_player_id</th>\n      <th>fumble_recovered_player_name</th>\n      <th>fumble_recovered_stat</th>\n      <th>fumble_stat</th>\n      <th>fumble_vec</th>\n      <th>game_id</th>\n      <th>game_play_number</th>\n      <th>half</th>\n      <th>half_clock.minutes</th>\n      <th>half_play_number</th>\n      <th>home</th>\n      <th>home_EPA</th>\n      <th>home_EPA_pass</th>\n      <th>home_EPA_rush</th>\n      <th>home_wp_after</th>\n      <th>home_wp_before</th>\n      <th>id_drive</th>\n      <th>id_play</th>\n      <th>incompletion_player</th>\n      <th>incompletion_player_id</th>\n      <th>incompletion_stat</th>\n      <th>int</th>\n      <th>int_td</th>\n      <th>interception_player</th>\n      <th>interception_player_id</th>\n      <th>interception_player_name</th>\n      <th>interception_stat</th>\n      <th>interception_thrown_player</th>\n      <th>interception_thrown_player_id</th>\n      <th>interception_thrown_stat</th>\n      <th>kick_play</th>\n      <th>kickoff_downed</th>\n      <th>kickoff_fair_catch</th>\n      <th>kickoff_onside</th>\n      <th>kickoff_oob</th>\n      <th>kickoff_play</th>\n      <th>kickoff_player_name</th>\n      <th>kickoff_returner_player_name</th>\n      <th>kickoff_safety</th>\n      <th>kickoff_tb</th>\n      <th>lag_change_of_pos_team</th>\n      <th>lag_change_of_pos_team2</th>\n      <th>lag_change_of_poss</th>\n      <th>lag_defense_score_play</th>\n      <th>lag_downs_turnover</th>\n      <th>lag_drive_result_detailed</th>\n      <th>lag_first_by_penalty</th>\n      <th>lag_first_by_penalty2</th>\n      <th>lag_first_by_yards</th>\n      <th>lag_first_by_yards2</th>\n      <th>lag_kickoff_play</th>\n      <th>lag_new_drive_pts</th>\n      <th>lag_play_text</th>\n      <th>lag_play_text2</th>\n      <th>lag_play_type</th>\n      <th>lag_play_type2</th>\n      <th>lag_play_type3</th>\n      <th>lag_pos_team</th>\n      <th>lag_punt</th>\n      <th>lag_punt2</th>\n      <th>lag_scoring_play</th>\n      <th>lag_turnover_vec</th>\n      <th>lead_drive_result_detailed</th>\n      <th>lead_play_text</th>\n      <th>lead_play_type</th>\n      <th>lead_pos_team</th>\n      <th>log_ydstogo</th>\n      <th>log_ydstogo_end</th>\n      <th>middle_8</th>\n      <th>missing_yard_flag</th>\n      <th>net_away_EPA</th>\n      <th>net_away_EPA_pass</th>\n      <th>net_away_EPA_rush</th>\n      <th>net_home_EPA</th>\n      <th>net_home_EPA_pass</th>\n      <th>net_home_EPA_rush</th>\n      <th>new_drive_pts</th>\n      <th>new_id</th>\n      <th>new_series</th>\n      <th>number_of_drives</th>\n      <th>off_timeout_called</th>\n      <th>off_timeouts_rem_before</th>\n      <th>offense_conference</th>\n      <th>offense_play</th>\n      <th>offense_receives_2H_kickoff</th>\n      <th>offense_score</th>\n      <th>offense_score_play</th>\n      <th>offense_timeouts</th>\n      <th>opponent</th>\n      <th>opponent_score</th>\n      <th>orig_drive_number</th>\n      <th>orig_play_type</th>\n      <th>pass</th>\n      <th>pass_attempt</th>\n      <th>pass_breakup_player</th>\n      <th>pass_breakup_player_id</th>\n      <th>pass_breakup_player_name</th>\n      <th>pass_breakup_stat</th>\n      <th>pass_td</th>\n      <th>passer_player_name</th>\n      <th>penalty_1st_conv</th>\n      <th>penalty_declined</th>\n      <th>penalty_detail</th>\n      <th>penalty_flag</th>\n      <th>penalty_no_play</th>\n      <th>penalty_offset</th>\n      <th>penalty_play_text</th>\n      <th>penalty_safety</th>\n      <th>penalty_text</th>\n      <th>period</th>\n      <th>play_after_turnover</th>\n      <th>play_id</th>\n      <th>play_text</th>\n      <th>play_type</th>\n      <th>pos_score_diff</th>\n      <th>pos_score_diff_start</th>\n      <th>pos_score_diff_start_end</th>\n      <th>pos_score_pts</th>\n      <th>pos_team</th>\n      <th>pos_team_receives_2H_kickoff</th>\n      <th>pos_team_score</th>\n      <th>pos_team_timeouts</th>\n      <th>pos_team_timeouts_rem_before</th>\n      <th>position_completion</th>\n      <th>position_fumble</th>\n      <th>position_fumble_forced</th>\n      <th>position_fumble_recovered</th>\n      <th>position_incompletion</th>\n      <th>position_interception</th>\n      <th>position_interception_thrown</th>\n      <th>position_pass_breakup</th>\n      <th>position_reception</th>\n      <th>position_rush</th>\n      <th>position_sack</th>\n      <th>position_sack_taken</th>\n      <th>position_target</th>\n      <th>position_touchdown</th>\n      <th>ppa</th>\n      <th>pts_scored</th>\n      <th>punt</th>\n      <th>punt_block_player_name</th>\n      <th>punt_block_return_player_name</th>\n      <th>punt_blocked</th>\n      <th>punt_downed</th>\n      <th>punt_fair_catch</th>\n      <th>punt_oob</th>\n      <th>punt_play</th>\n      <th>punt_returner_player_name</th>\n      <th>punt_safety</th>\n      <th>punt_tb</th>\n      <th>punter_player_name</th>\n      <th>receiver_player_name</th>\n      <th>receives_2H_kickoff</th>\n      <th>reception_player</th>\n      <th>reception_player_id</th>\n      <th>reception_yds</th>\n      <th>row</th>\n      <th>rush</th>\n      <th>rush_player</th>\n      <th>rush_player_id</th>\n      <th>rush_td</th>\n      <th>rush_yds</th>\n      <th>rusher_player_name</th>\n      <th>rz_play</th>\n      <th>sack</th>\n      <th>sack_player</th>\n      <th>sack_player_id</th>\n      <th>sack_player_name</th>\n      <th>sack_player_name2</th>\n      <th>sack_players</th>\n      <th>sack_stat</th>\n      <th>sack_taken_player</th>\n      <th>sack_taken_player_id</th>\n      <th>sack_taken_stat</th>\n      <th>sack_vec</th>\n      <th>safety</th>\n      <th>score_diff</th>\n      <th>score_diff_start</th>\n      <th>score_pts</th>\n      <th>scoring</th>\n      <th>scoring_opp</th>\n      <th>scoring_play</th>\n      <th>season</th>\n      <th>stuffed_run</th>\n      <th>success</th>\n      <th>target</th>\n      <th>target_player</th>\n      <th>target_player_id</th>\n      <th>target_stat</th>\n      <th>td_play</th>\n      <th>team_score</th>\n      <th>total_away_EPA</th>\n      <th>total_away_EPA_pass</th>\n      <th>total_away_EPA_rush</th>\n      <th>total_home_EPA</th>\n      <th>total_home_EPA_pass</th>\n      <th>total_home_EPA_rush</th>\n      <th>touchdown</th>\n      <th>touchdown_player</th>\n      <th>touchdown_player_id</th>\n      <th>touchdown_stat</th>\n      <th>turnover</th>\n      <th>turnover_indicator</th>\n      <th>turnover_vec</th>\n      <th>turnover_vec_lag</th>\n      <th>week</th>\n      <th>wp_after</th>\n      <th>wp_before</th>\n      <th>wpa</th>\n      <th>yard_line</th>\n      <th>yards_gained</th>\n      <th>yards_to_goal</th>\n      <th>yards_to_goal_end</th>\n      <th>yds_fg</th>\n      <th>yds_fumble_return</th>\n      <th>yds_int_return</th>\n      <th>yds_kickoff</th>\n      <th>yds_kickoff_return</th>\n      <th>yds_penalty</th>\n      <th>yds_punt_gained</th>\n      <th>yds_punt_return</th>\n      <th>yds_punted</th>\n      <th>yds_receiving</th>\n      <th>yds_rushed</th>\n      <th>yds_sacked</th>\n      <th>year</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>-0.565384</td>\n      <td>0.835848</td>\n      <td>0.000232</td>\n      <td>0.132497</td>\n      <td>0.170311</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002218</td>\n      <td>0.001810</td>\n      <td>0.123708</td>\n      <td>0.089125</td>\n      <td>0.004623</td>\n      <td>0.001920</td>\n      <td>0.349311</td>\n      <td>0.260266</td>\n      <td>0.002997</td>\n      <td>0.002954</td>\n      <td>0.384646</td>\n      <td>0.473614</td>\n      <td>1795</td>\n      <td>1795.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3595</td>\n      <td>Temple</td>\n      <td>-0.565384</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.469500</td>\n      <td>0.491924</td>\n      <td>0</td>\n      <td>1</td>\n      <td>14</td>\n      <td>55</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.565384</td>\n      <td>Vanderbilt</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.530500</td>\n      <td>0.508076</td>\n      <td>American Athletic</td>\n      <td>Temple</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>63</td>\n      <td>1</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>35</td>\n      <td>2</td>\n      <td>12</td>\n      <td>15</td>\n      <td>53</td>\n      <td>7</td>\n      <td>0</td>\n      <td>18</td>\n      <td>0</td>\n      <td>0.270464</td>\n      <td>0.835848</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547640</td>\n      <td>1</td>\n      <td>1</td>\n      <td>29</td>\n      <td>1</td>\n      <td>Vanderbilt</td>\n      <td>0.565384</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.530500</td>\n      <td>0.508076</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Hayden Lekacz</td>\n      <td>Khalif Herbin</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>Temple</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>TEMPLE Penalty, False Start (5 Yards) to the T...</td>\n      <td>Penalty</td>\n      <td>Temple</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>-1.130768</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1.130768</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0</td>\n      <td>101854401</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>SEC</td>\n      <td>Vanderbilt</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>Kickoff Return (Offense)</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>Hayden Lekacz kickoff for 64 yds , Khalif Herb...</td>\n      <td>Kickoff Return (Offense)</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Temple</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>-0.565384</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.565384</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0.469500</td>\n      <td>0.491924</td>\n      <td>-0.022424</td>\n      <td>35</td>\n      <td>18</td>\n      <td>65</td>\n      <td>81.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>64.0</td>\n      <td>18.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>-0.469578</td>\n      <td>0.270464</td>\n      <td>0.000075</td>\n      <td>0.120739</td>\n      <td>0.132497</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002423</td>\n      <td>0.002218</td>\n      <td>0.134912</td>\n      <td>0.123708</td>\n      <td>0.006027</td>\n      <td>0.004623</td>\n      <td>0.377211</td>\n      <td>0.349311</td>\n      <td>0.002977</td>\n      <td>0.002997</td>\n      <td>0.355712</td>\n      <td>0.384646</td>\n      <td>1795</td>\n      <td>1785.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3595</td>\n      <td>Temple</td>\n      <td>-0.469578</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.442379</td>\n      <td>0.469500</td>\n      <td>0</td>\n      <td>0</td>\n      <td>14</td>\n      <td>55</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.469578</td>\n      <td>Vanderbilt</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.557621</td>\n      <td>0.530500</td>\n      <td>SEC</td>\n      <td>Vanderbilt</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>63</td>\n      <td>2</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>35</td>\n      <td>2</td>\n      <td>12</td>\n      <td>15</td>\n      <td>53</td>\n      <td>7</td>\n      <td>0</td>\n      <td>18</td>\n      <td>0</td>\n      <td>-0.199114</td>\n      <td>0.270464</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547640</td>\n      <td>1</td>\n      <td>1</td>\n      <td>29</td>\n      <td>1</td>\n      <td>Vanderbilt</td>\n      <td>0.469578</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.557621</td>\n      <td>0.530500</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>Hayden Lekacz kickoff for 64 yds , Khalif Herb...</td>\n      <td>None</td>\n      <td>Kickoff Return (Offense)</td>\n      <td>None</td>\n      <td>None</td>\n      <td>Temple</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>P.J. Walker pass complete to Jalen Fitzpatrick...</td>\n      <td>Pass Reception</td>\n      <td>Temple</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>-2.069924</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>2.069924</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0</td>\n      <td>101854402</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>Temple</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>Penalty</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False Start</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>Penalty, False Start (5 Yards) to the Temp 14</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>TEMPLE Penalty, False Start (5 Yards) to the T...</td>\n      <td>Penalty</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Temple</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>-1.034962</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1.034962</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.442379</td>\n      <td>0.469500</td>\n      <td>-0.027121</td>\n      <td>81</td>\n      <td>-5</td>\n      <td>81</td>\n      <td>86.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>-5.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>-0.484325</td>\n      <td>-0.488417</td>\n      <td>-0.000136</td>\n      <td>0.111865</td>\n      <td>0.139679</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002728</td>\n      <td>0.002383</td>\n      <td>0.149630</td>\n      <td>0.134811</td>\n      <td>0.005772</td>\n      <td>0.006593</td>\n      <td>0.424451</td>\n      <td>0.392052</td>\n      <td>0.003125</td>\n      <td>0.003371</td>\n      <td>0.302429</td>\n      <td>0.321112</td>\n      <td>1785</td>\n      <td>1760.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3585</td>\n      <td>Temple</td>\n      <td>-0.484325</td>\n      <td>-0.484325</td>\n      <td>NaN</td>\n      <td>0.430545</td>\n      <td>0.442379</td>\n      <td>0</td>\n      <td>0</td>\n      <td>14</td>\n      <td>45</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.484325</td>\n      <td>Vanderbilt</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.569455</td>\n      <td>0.557621</td>\n      <td>SEC</td>\n      <td>Vanderbilt</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>15.0</td>\n      <td>12.0</td>\n      <td>1.0</td>\n      <td>2.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>63</td>\n      <td>3</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>35</td>\n      <td>2</td>\n      <td>12</td>\n      <td>15</td>\n      <td>53</td>\n      <td>7</td>\n      <td>0</td>\n      <td>18</td>\n      <td>0</td>\n      <td>-0.972742</td>\n      <td>-0.488417</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547640</td>\n      <td>2</td>\n      <td>1</td>\n      <td>29</td>\n      <td>2</td>\n      <td>Vanderbilt</td>\n      <td>0.484325</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.569455</td>\n      <td>0.557621</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>TEMPLE Penalty, False Start (5 Yards) to the T...</td>\n      <td>Hayden Lekacz kickoff for 64 yds , Khalif Herb...</td>\n      <td>Penalty</td>\n      <td>Kickoff Return (Offense)</td>\n      <td>None</td>\n      <td>Temple</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Kenneth Harper run for 5 yds to the Temp 22</td>\n      <td>Rush</td>\n      <td>Temple</td>\n      <td>2.708050</td>\n      <td>2.484907</td>\n      <td>False</td>\n      <td>False</td>\n      <td>-3.038574</td>\n      <td>-0.484325</td>\n      <td>0.000000</td>\n      <td>3.038574</td>\n      <td>0.484325</td>\n      <td>0.000000</td>\n      <td>0</td>\n      <td>101855401</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>Temple</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>Vanderbilt</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Reception</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>P.J. Walker</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>P.J. Walker pass complete to Jalen Fitzpatrick...</td>\n      <td>Pass Reception</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Temple</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>-0.100269</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Jalen Fitzpatrick</td>\n      <td>1.0</td>\n      <td>Jalen Fitzpatrick</td>\n      <td>513398.0</td>\n      <td>3.0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>-1.519287</td>\n      <td>-0.484325</td>\n      <td>0.000000</td>\n      <td>1.519287</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.430545</td>\n      <td>0.442379</td>\n      <td>-0.011835</td>\n      <td>86</td>\n      <td>3</td>\n      <td>86</td>\n      <td>83.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>3.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>-0.214516</td>\n      <td>-0.972742</td>\n      <td>-0.000273</td>\n      <td>0.093482</td>\n      <td>0.111865</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002888</td>\n      <td>0.002728</td>\n      <td>0.155241</td>\n      <td>0.149630</td>\n      <td>0.004866</td>\n      <td>0.005772</td>\n      <td>0.441455</td>\n      <td>0.424451</td>\n      <td>0.003306</td>\n      <td>0.003125</td>\n      <td>0.298761</td>\n      <td>0.302429</td>\n      <td>1760</td>\n      <td>1730.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3560</td>\n      <td>Temple</td>\n      <td>-0.214516</td>\n      <td>NaN</td>\n      <td>-0.214516</td>\n      <td>0.430455</td>\n      <td>0.430545</td>\n      <td>0</td>\n      <td>0</td>\n      <td>14</td>\n      <td>20</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.214516</td>\n      <td>Vanderbilt</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.569545</td>\n      <td>0.569455</td>\n      <td>SEC</td>\n      <td>Vanderbilt</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>12.0</td>\n      <td>7.0</td>\n      <td>2.0</td>\n      <td>3.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>63</td>\n      <td>4</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>35</td>\n      <td>2</td>\n      <td>12</td>\n      <td>15</td>\n      <td>53</td>\n      <td>7</td>\n      <td>0</td>\n      <td>18</td>\n      <td>0</td>\n      <td>-1.187259</td>\n      <td>-0.972742</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547640</td>\n      <td>3</td>\n      <td>1</td>\n      <td>29</td>\n      <td>3</td>\n      <td>Vanderbilt</td>\n      <td>0.214516</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.569545</td>\n      <td>0.569455</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>P.J. Walker pass complete to Jalen Fitzpatrick...</td>\n      <td>TEMPLE Penalty, False Start (5 Yards) to the T...</td>\n      <td>Pass Reception</td>\n      <td>Penalty</td>\n      <td>Kickoff Return (Offense)</td>\n      <td>Temple</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>P.J. Walker pass complete to Jalen Fitzpatrick...</td>\n      <td>Pass Reception</td>\n      <td>Temple</td>\n      <td>2.484907</td>\n      <td>1.945910</td>\n      <td>False</td>\n      <td>False</td>\n      <td>-3.467607</td>\n      <td>-0.484325</td>\n      <td>-0.214516</td>\n      <td>3.467607</td>\n      <td>0.484325</td>\n      <td>0.214516</td>\n      <td>0</td>\n      <td>101857901</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>Temple</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>Vanderbilt</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Rush</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Kenneth Harper run for 5 yds to the Temp 22</td>\n      <td>Rush</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Temple</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>RB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.024724</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Kenneth Harper</td>\n      <td>513403.0</td>\n      <td>0</td>\n      <td>5.0</td>\n      <td>Kenneth Harper</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>-1.733803</td>\n      <td>-0.484325</td>\n      <td>-0.214516</td>\n      <td>1.733803</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.430455</td>\n      <td>0.430545</td>\n      <td>-0.000090</td>\n      <td>83</td>\n      <td>5</td>\n      <td>83</td>\n      <td>78.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>5.0</td>\n      <td>NaN</td>\n      <td>2014</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>2.529815</td>\n      <td>-1.187259</td>\n      <td>-0.000336</td>\n      <td>0.158063</td>\n      <td>0.093482</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002756</td>\n      <td>0.002888</td>\n      <td>0.097974</td>\n      <td>0.155241</td>\n      <td>0.002650</td>\n      <td>0.004866</td>\n      <td>0.284786</td>\n      <td>0.441455</td>\n      <td>0.003061</td>\n      <td>0.003306</td>\n      <td>0.450710</td>\n      <td>0.298761</td>\n      <td>1730</td>\n      <td>1705.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3530</td>\n      <td>Temple</td>\n      <td>2.529815</td>\n      <td>2.529815</td>\n      <td>NaN</td>\n      <td>0.537439</td>\n      <td>0.430455</td>\n      <td>0</td>\n      <td>0</td>\n      <td>13</td>\n      <td>50</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>-2.529815</td>\n      <td>Vanderbilt</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.462561</td>\n      <td>0.569545</td>\n      <td>SEC</td>\n      <td>Vanderbilt</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>7.0</td>\n      <td>10.0</td>\n      <td>3.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>63</td>\n      <td>5</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>4</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>35</td>\n      <td>2</td>\n      <td>12</td>\n      <td>15</td>\n      <td>53</td>\n      <td>7</td>\n      <td>0</td>\n      <td>18</td>\n      <td>0</td>\n      <td>1.342556</td>\n      <td>-1.187259</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547640</td>\n      <td>4</td>\n      <td>1</td>\n      <td>28</td>\n      <td>4</td>\n      <td>Vanderbilt</td>\n      <td>-2.529815</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.462561</td>\n      <td>0.569545</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Kenneth Harper run for 5 yds to the Temp 22</td>\n      <td>P.J. Walker pass complete to Jalen Fitzpatrick...</td>\n      <td>Rush</td>\n      <td>Pass Reception</td>\n      <td>Penalty</td>\n      <td>Temple</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>P.J. Walker pass complete to Nate Hairston for...</td>\n      <td>Pass Reception</td>\n      <td>Temple</td>\n      <td>1.945910</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>1.592023</td>\n      <td>2.045490</td>\n      <td>-0.214516</td>\n      <td>-1.592023</td>\n      <td>-2.045490</td>\n      <td>0.214516</td>\n      <td>0</td>\n      <td>101864901</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>Temple</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>Vanderbilt</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Reception</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>P.J. Walker</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>P.J. Walker pass complete to Jalen Fitzpatrick...</td>\n      <td>Pass Reception</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Temple</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>1.385952</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Jalen Fitzpatrick</td>\n      <td>1.0</td>\n      <td>Jalen Fitzpatrick</td>\n      <td>513398.0</td>\n      <td>8.0</td>\n      <td>5</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.796012</td>\n      <td>2.045490</td>\n      <td>-0.214516</td>\n      <td>-0.796012</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.537439</td>\n      <td>0.430455</td>\n      <td>0.106984</td>\n      <td>78</td>\n      <td>8</td>\n      <td>78</td>\n      <td>70.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>8.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ngame_data = pd.DataFrame()\nspread_data = pd.DataFrame()\n\n# downloaded files from collegefootballdata.com\ndef retrieveCfbDataFile(endpoint, year):\n    return pd.read_csv(f\"data/{endpoint}/{year}.csv\", encoding='latin-1')\n\nfor i in range(2014, 2020):\n    gm = retrieveCfbDataFile('games',i)\n    gm['game_id'] = gm['id']\n    gm['year'] = i\n    gm['winner'] = np.where(gm.home_points > gm.away_points, gm.home_team, gm.away_team)\n    game_data = game_data.append(gm, sort=False)\n    \n    bets = retrieveCfbDataFile('lines', i)\n    bets = bets[bets.lineProvider == \"consensus\"]\n    bets['game_id'] = bets['id']\n    bets['year'] = i\n    bets['spread'] = -1 * bets.spread # spread is negative for home favorite; positive for away favorite, but NFLfastR uses \"(how many points home team was favored by) for this\"\n    spread_data = spread_data.append(bets, sort=False)\n    \n\nprint(f\"Total Games: {len(game_data)}\")\nprint(f\"Total Spreads: {len(spread_data)}\")\n```\n\n    Total Games: 5018\n    Total Spreads: 4775\n\n\n\n```python\npbp_data = pd.merge(pbp_data, game_data[['game_id','winner']], left_on=\"game_id\", right_on=\"game_id\")\npbp_data = pbp_data[pbp_data.game_id != 400603838]\npbp_data.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>EPA</th>\n      <th>ExpScoreDiff</th>\n      <th>ExpScoreDiff_Time_Ratio</th>\n      <th>FG_after</th>\n      <th>FG_before</th>\n      <th>Goal_To_Go</th>\n      <th>Goal_To_Go_end</th>\n      <th>No_Score_after</th>\n      <th>No_Score_before</th>\n      <th>Opp_FG_after</th>\n      <th>Opp_FG_before</th>\n      <th>Opp_Safety_after</th>\n      <th>Opp_Safety_before</th>\n      <th>Opp_TD_after</th>\n      <th>Opp_TD_before</th>\n      <th>Safety_after</th>\n      <th>Safety_before</th>\n      <th>TD_after</th>\n      <th>TD_before</th>\n      <th>TimeSecsRem</th>\n      <th>TimeSecsRem_end</th>\n      <th>Under_three</th>\n      <th>Under_two</th>\n      <th>Under_two_end</th>\n      <th>adj_TimeSecsRem</th>\n      <th>away</th>\n      <th>away_EPA</th>\n      <th>away_EPA_pass</th>\n      <th>away_EPA_rush</th>\n      <th>away_wp_after</th>\n      <th>away_wp_before</th>\n      <th>change_of_pos_team</th>\n      <th>change_of_poss</th>\n      <th>clock.minutes</th>\n      <th>clock.seconds</th>\n      <th>completion</th>\n      <th>completion_player</th>\n      <th>completion_player_id</th>\n      <th>completion_yds</th>\n      <th>def_EPA</th>\n      <th>def_pos_team</th>\n      <th>def_pos_team_score</th>\n      <th>def_pos_team_timeouts</th>\n      <th>def_pos_team_timeouts_rem_before</th>\n      <th>def_timeout_called</th>\n      <th>def_timeouts_rem_before</th>\n      <th>def_wp_after</th>\n      <th>def_wp_before</th>\n      <th>defense_conference</th>\n      <th>defense_play</th>\n      <th>defense_score</th>\n      <th>defense_score_play</th>\n      <th>defense_timeouts</th>\n      <th>distance</th>\n      <th>distance_end</th>\n      <th>down</th>\n      <th>down_end</th>\n      <th>downs_turnover</th>\n      <th>drive_end_period</th>\n      <th>drive_end_yards_to_goal</th>\n      <th>drive_event_number</th>\n      <th>drive_id</th>\n      <th>drive_num</th>\n      <th>drive_number</th>\n      <th>drive_numbers</th>\n      <th>drive_play_number</th>\n      <th>drive_pts</th>\n      <th>drive_result</th>\n      <th>drive_result2</th>\n      <th>drive_result_detailed</th>\n      <th>drive_result_detailed_flag</th>\n      <th>drive_scoring</th>\n      <th>drive_start_period</th>\n      <th>drive_start_yards_to_goal</th>\n      <th>drive_time_minutes_elapsed</th>\n      <th>drive_time_minutes_end</th>\n      <th>drive_time_minutes_start</th>\n      <th>drive_time_seconds_elapsed</th>\n      <th>drive_time_seconds_end</th>\n      <th>drive_time_seconds_start</th>\n      <th>drive_yards</th>\n      <th>end_of_half</th>\n      <th>ep_after</th>\n      <th>ep_before</th>\n      <th>epa_success</th>\n      <th>fg_block_player_name</th>\n      <th>fg_inds</th>\n      <th>fg_kicker_player_name</th>\n      <th>fg_made</th>\n      <th>fg_make_prob</th>\n      <th>fg_return_player_name</th>\n      <th>firstD_by_kickoff</th>\n      <th>firstD_by_penalty</th>\n      <th>firstD_by_poss</th>\n      <th>firstD_by_yards</th>\n      <th>first_by_penalty</th>\n      <th>first_by_yards</th>\n      <th>fumble_forced_player</th>\n      <th>fumble_forced_player_id</th>\n      <th>fumble_forced_player_name</th>\n      <th>fumble_forced_stat</th>\n      <th>fumble_player</th>\n      <th>fumble_player_id</th>\n      <th>fumble_player_name</th>\n      <th>fumble_recovered_player</th>\n      <th>fumble_recovered_player_id</th>\n      <th>fumble_recovered_player_name</th>\n      <th>fumble_recovered_stat</th>\n      <th>fumble_stat</th>\n      <th>fumble_vec</th>\n      <th>game_id</th>\n      <th>game_play_number</th>\n      <th>half</th>\n      <th>half_clock.minutes</th>\n      <th>half_play_number</th>\n      <th>home</th>\n      <th>home_EPA</th>\n      <th>home_EPA_pass</th>\n      <th>home_EPA_rush</th>\n      <th>home_wp_after</th>\n      <th>home_wp_before</th>\n      <th>id_drive</th>\n      <th>id_play</th>\n      <th>incompletion_player</th>\n      <th>incompletion_player_id</th>\n      <th>incompletion_stat</th>\n      <th>int</th>\n      <th>int_td</th>\n      <th>interception_player</th>\n      <th>interception_player_id</th>\n      <th>interception_player_name</th>\n      <th>interception_stat</th>\n      <th>interception_thrown_player</th>\n      <th>interception_thrown_player_id</th>\n      <th>interception_thrown_stat</th>\n      <th>kick_play</th>\n      <th>kickoff_downed</th>\n      <th>kickoff_fair_catch</th>\n      <th>kickoff_onside</th>\n      <th>kickoff_oob</th>\n      <th>kickoff_play</th>\n      <th>kickoff_player_name</th>\n      <th>kickoff_returner_player_name</th>\n      <th>kickoff_safety</th>\n      <th>kickoff_tb</th>\n      <th>lag_change_of_pos_team</th>\n      <th>lag_change_of_pos_team2</th>\n      <th>lag_change_of_poss</th>\n      <th>lag_defense_score_play</th>\n      <th>lag_downs_turnover</th>\n      <th>lag_drive_result_detailed</th>\n      <th>lag_first_by_penalty</th>\n      <th>lag_first_by_penalty2</th>\n      <th>lag_first_by_yards</th>\n      <th>lag_first_by_yards2</th>\n      <th>lag_kickoff_play</th>\n      <th>lag_new_drive_pts</th>\n      <th>lag_play_text</th>\n      <th>lag_play_text2</th>\n      <th>lag_play_type</th>\n      <th>lag_play_type2</th>\n      <th>lag_play_type3</th>\n      <th>lag_pos_team</th>\n      <th>lag_punt</th>\n      <th>lag_punt2</th>\n      <th>lag_scoring_play</th>\n      <th>lag_turnover_vec</th>\n      <th>lead_drive_result_detailed</th>\n      <th>lead_play_text</th>\n      <th>lead_play_type</th>\n      <th>lead_pos_team</th>\n      <th>log_ydstogo</th>\n      <th>log_ydstogo_end</th>\n      <th>middle_8</th>\n      <th>missing_yard_flag</th>\n      <th>net_away_EPA</th>\n      <th>net_away_EPA_pass</th>\n      <th>net_away_EPA_rush</th>\n      <th>net_home_EPA</th>\n      <th>net_home_EPA_pass</th>\n      <th>net_home_EPA_rush</th>\n      <th>new_drive_pts</th>\n      <th>new_id</th>\n      <th>new_series</th>\n      <th>number_of_drives</th>\n      <th>off_timeout_called</th>\n      <th>off_timeouts_rem_before</th>\n      <th>offense_conference</th>\n      <th>offense_play</th>\n      <th>offense_receives_2H_kickoff</th>\n      <th>offense_score</th>\n      <th>offense_score_play</th>\n      <th>offense_timeouts</th>\n      <th>opponent</th>\n      <th>opponent_score</th>\n      <th>orig_drive_number</th>\n      <th>orig_play_type</th>\n      <th>pass</th>\n      <th>pass_attempt</th>\n      <th>pass_breakup_player</th>\n      <th>pass_breakup_player_id</th>\n      <th>pass_breakup_player_name</th>\n      <th>pass_breakup_stat</th>\n      <th>pass_td</th>\n      <th>passer_player_name</th>\n      <th>penalty_1st_conv</th>\n      <th>penalty_declined</th>\n      <th>penalty_detail</th>\n      <th>penalty_flag</th>\n      <th>penalty_no_play</th>\n      <th>penalty_offset</th>\n      <th>penalty_play_text</th>\n      <th>penalty_safety</th>\n      <th>penalty_text</th>\n      <th>period</th>\n      <th>play_after_turnover</th>\n      <th>play_id</th>\n      <th>play_text</th>\n      <th>play_type</th>\n      <th>pos_score_diff</th>\n      <th>pos_score_diff_start</th>\n      <th>pos_score_diff_start_end</th>\n      <th>pos_score_pts</th>\n      <th>pos_team</th>\n      <th>pos_team_receives_2H_kickoff</th>\n      <th>pos_team_score</th>\n      <th>pos_team_timeouts</th>\n      <th>pos_team_timeouts_rem_before</th>\n      <th>position_completion</th>\n      <th>position_fumble</th>\n      <th>position_fumble_forced</th>\n      <th>position_fumble_recovered</th>\n      <th>position_incompletion</th>\n      <th>position_interception</th>\n      <th>position_interception_thrown</th>\n      <th>position_pass_breakup</th>\n      <th>position_reception</th>\n      <th>position_rush</th>\n      <th>position_sack</th>\n      <th>position_sack_taken</th>\n      <th>position_target</th>\n      <th>position_touchdown</th>\n      <th>ppa</th>\n      <th>pts_scored</th>\n      <th>punt</th>\n      <th>punt_block_player_name</th>\n      <th>punt_block_return_player_name</th>\n      <th>punt_blocked</th>\n      <th>punt_downed</th>\n      <th>punt_fair_catch</th>\n      <th>punt_oob</th>\n      <th>punt_play</th>\n      <th>punt_returner_player_name</th>\n      <th>punt_safety</th>\n      <th>punt_tb</th>\n      <th>punter_player_name</th>\n      <th>receiver_player_name</th>\n      <th>receives_2H_kickoff</th>\n      <th>reception_player</th>\n      <th>reception_player_id</th>\n      <th>reception_yds</th>\n      <th>row</th>\n      <th>rush</th>\n      <th>rush_player</th>\n      <th>rush_player_id</th>\n      <th>rush_td</th>\n      <th>rush_yds</th>\n      <th>rusher_player_name</th>\n      <th>rz_play</th>\n      <th>sack</th>\n      <th>sack_player</th>\n      <th>sack_player_id</th>\n      <th>sack_player_name</th>\n      <th>sack_player_name2</th>\n      <th>sack_players</th>\n      <th>sack_stat</th>\n      <th>sack_taken_player</th>\n      <th>sack_taken_player_id</th>\n      <th>sack_taken_stat</th>\n      <th>sack_vec</th>\n      <th>safety</th>\n      <th>score_diff</th>\n      <th>score_diff_start</th>\n      <th>score_pts</th>\n      <th>scoring</th>\n      <th>scoring_opp</th>\n      <th>scoring_play</th>\n      <th>season</th>\n      <th>stuffed_run</th>\n      <th>success</th>\n      <th>target</th>\n      <th>target_player</th>\n      <th>target_player_id</th>\n      <th>target_stat</th>\n      <th>td_play</th>\n      <th>team_score</th>\n      <th>total_away_EPA</th>\n      <th>total_away_EPA_pass</th>\n      <th>total_away_EPA_rush</th>\n      <th>total_home_EPA</th>\n      <th>total_home_EPA_pass</th>\n      <th>total_home_EPA_rush</th>\n      <th>touchdown</th>\n      <th>touchdown_player</th>\n      <th>touchdown_player_id</th>\n      <th>touchdown_stat</th>\n      <th>turnover</th>\n      <th>turnover_indicator</th>\n      <th>turnover_vec</th>\n      <th>turnover_vec_lag</th>\n      <th>week</th>\n      <th>wp_after</th>\n      <th>wp_before</th>\n      <th>wpa</th>\n      <th>yard_line</th>\n      <th>yards_gained</th>\n      <th>yards_to_goal</th>\n      <th>yards_to_goal_end</th>\n      <th>yds_fg</th>\n      <th>yds_fumble_return</th>\n      <th>yds_int_return</th>\n      <th>yds_kickoff</th>\n      <th>yds_kickoff_return</th>\n      <th>yds_penalty</th>\n      <th>yds_punt_gained</th>\n      <th>yds_punt_return</th>\n      <th>yds_punted</th>\n      <th>yds_receiving</th>\n      <th>yds_rushed</th>\n      <th>yds_sacked</th>\n      <th>year</th>\n      <th>winner</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>-0.565384</td>\n      <td>0.835848</td>\n      <td>0.000232</td>\n      <td>0.132497</td>\n      <td>0.170311</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002218</td>\n      <td>0.001810</td>\n      <td>0.123708</td>\n      <td>0.089125</td>\n      <td>0.004623</td>\n      <td>0.001920</td>\n      <td>0.349311</td>\n      <td>0.260266</td>\n      <td>0.002997</td>\n      <td>0.002954</td>\n      <td>0.384646</td>\n      <td>0.473614</td>\n      <td>1795</td>\n      <td>1795.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3595</td>\n      <td>Temple</td>\n      <td>-0.565384</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.469500</td>\n      <td>0.491924</td>\n      <td>0</td>\n      <td>1</td>\n      <td>14</td>\n      <td>55</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.565384</td>\n      <td>Vanderbilt</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.530500</td>\n      <td>0.508076</td>\n      <td>American Athletic</td>\n      <td>Temple</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>63</td>\n      <td>1</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>35</td>\n      <td>2</td>\n      <td>12</td>\n      <td>15</td>\n      <td>53</td>\n      <td>7</td>\n      <td>0</td>\n      <td>18</td>\n      <td>0</td>\n      <td>0.270464</td>\n      <td>0.835848</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547640</td>\n      <td>1</td>\n      <td>1</td>\n      <td>29</td>\n      <td>1</td>\n      <td>Vanderbilt</td>\n      <td>0.565384</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.530500</td>\n      <td>0.508076</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Hayden Lekacz</td>\n      <td>Khalif Herbin</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>Temple</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>TEMPLE Penalty, False Start (5 Yards) to the T...</td>\n      <td>Penalty</td>\n      <td>Temple</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>-1.130768</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1.130768</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0</td>\n      <td>101854401</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>SEC</td>\n      <td>Vanderbilt</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>Kickoff Return (Offense)</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>Hayden Lekacz kickoff for 64 yds , Khalif Herb...</td>\n      <td>Kickoff Return (Offense)</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Temple</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>-0.565384</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.565384</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0.469500</td>\n      <td>0.491924</td>\n      <td>-0.022424</td>\n      <td>35</td>\n      <td>18</td>\n      <td>65</td>\n      <td>81.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>64.0</td>\n      <td>18.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>Temple</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>-0.469578</td>\n      <td>0.270464</td>\n      <td>0.000075</td>\n      <td>0.120739</td>\n      <td>0.132497</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002423</td>\n      <td>0.002218</td>\n      <td>0.134912</td>\n      <td>0.123708</td>\n      <td>0.006027</td>\n      <td>0.004623</td>\n      <td>0.377211</td>\n      <td>0.349311</td>\n      <td>0.002977</td>\n      <td>0.002997</td>\n      <td>0.355712</td>\n      <td>0.384646</td>\n      <td>1795</td>\n      <td>1785.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3595</td>\n      <td>Temple</td>\n      <td>-0.469578</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.442379</td>\n      <td>0.469500</td>\n      <td>0</td>\n      <td>0</td>\n      <td>14</td>\n      <td>55</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.469578</td>\n      <td>Vanderbilt</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.557621</td>\n      <td>0.530500</td>\n      <td>SEC</td>\n      <td>Vanderbilt</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>63</td>\n      <td>2</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>35</td>\n      <td>2</td>\n      <td>12</td>\n      <td>15</td>\n      <td>53</td>\n      <td>7</td>\n      <td>0</td>\n      <td>18</td>\n      <td>0</td>\n      <td>-0.199114</td>\n      <td>0.270464</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547640</td>\n      <td>1</td>\n      <td>1</td>\n      <td>29</td>\n      <td>1</td>\n      <td>Vanderbilt</td>\n      <td>0.469578</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.557621</td>\n      <td>0.530500</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>Hayden Lekacz kickoff for 64 yds , Khalif Herb...</td>\n      <td>None</td>\n      <td>Kickoff Return (Offense)</td>\n      <td>None</td>\n      <td>None</td>\n      <td>Temple</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>P.J. Walker pass complete to Jalen Fitzpatrick...</td>\n      <td>Pass Reception</td>\n      <td>Temple</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>-2.069924</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>2.069924</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0</td>\n      <td>101854402</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>Temple</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>Penalty</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False Start</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>Penalty, False Start (5 Yards) to the Temp 14</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>TEMPLE Penalty, False Start (5 Yards) to the T...</td>\n      <td>Penalty</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Temple</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>-1.034962</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1.034962</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.442379</td>\n      <td>0.469500</td>\n      <td>-0.027121</td>\n      <td>81</td>\n      <td>-5</td>\n      <td>81</td>\n      <td>86.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>-5.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>Temple</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>-0.484325</td>\n      <td>-0.488417</td>\n      <td>-0.000136</td>\n      <td>0.111865</td>\n      <td>0.139679</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002728</td>\n      <td>0.002383</td>\n      <td>0.149630</td>\n      <td>0.134811</td>\n      <td>0.005772</td>\n      <td>0.006593</td>\n      <td>0.424451</td>\n      <td>0.392052</td>\n      <td>0.003125</td>\n      <td>0.003371</td>\n      <td>0.302429</td>\n      <td>0.321112</td>\n      <td>1785</td>\n      <td>1760.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3585</td>\n      <td>Temple</td>\n      <td>-0.484325</td>\n      <td>-0.484325</td>\n      <td>NaN</td>\n      <td>0.430545</td>\n      <td>0.442379</td>\n      <td>0</td>\n      <td>0</td>\n      <td>14</td>\n      <td>45</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.484325</td>\n      <td>Vanderbilt</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.569455</td>\n      <td>0.557621</td>\n      <td>SEC</td>\n      <td>Vanderbilt</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>15.0</td>\n      <td>12.0</td>\n      <td>1.0</td>\n      <td>2.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>63</td>\n      <td>3</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>35</td>\n      <td>2</td>\n      <td>12</td>\n      <td>15</td>\n      <td>53</td>\n      <td>7</td>\n      <td>0</td>\n      <td>18</td>\n      <td>0</td>\n      <td>-0.972742</td>\n      <td>-0.488417</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547640</td>\n      <td>2</td>\n      <td>1</td>\n      <td>29</td>\n      <td>2</td>\n      <td>Vanderbilt</td>\n      <td>0.484325</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.569455</td>\n      <td>0.557621</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>TEMPLE Penalty, False Start (5 Yards) to the T...</td>\n      <td>Hayden Lekacz kickoff for 64 yds , Khalif Herb...</td>\n      <td>Penalty</td>\n      <td>Kickoff Return (Offense)</td>\n      <td>None</td>\n      <td>Temple</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Kenneth Harper run for 5 yds to the Temp 22</td>\n      <td>Rush</td>\n      <td>Temple</td>\n      <td>2.708050</td>\n      <td>2.484907</td>\n      <td>False</td>\n      <td>False</td>\n      <td>-3.038574</td>\n      <td>-0.484325</td>\n      <td>0.000000</td>\n      <td>3.038574</td>\n      <td>0.484325</td>\n      <td>0.000000</td>\n      <td>0</td>\n      <td>101855401</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>Temple</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>Vanderbilt</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Reception</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>P.J. Walker</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>P.J. Walker pass complete to Jalen Fitzpatrick...</td>\n      <td>Pass Reception</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Temple</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>-0.100269</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Jalen Fitzpatrick</td>\n      <td>1.0</td>\n      <td>Jalen Fitzpatrick</td>\n      <td>513398.0</td>\n      <td>3.0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>-1.519287</td>\n      <td>-0.484325</td>\n      <td>0.000000</td>\n      <td>1.519287</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.430545</td>\n      <td>0.442379</td>\n      <td>-0.011835</td>\n      <td>86</td>\n      <td>3</td>\n      <td>86</td>\n      <td>83.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>3.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>Temple</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>-0.214516</td>\n      <td>-0.972742</td>\n      <td>-0.000273</td>\n      <td>0.093482</td>\n      <td>0.111865</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002888</td>\n      <td>0.002728</td>\n      <td>0.155241</td>\n      <td>0.149630</td>\n      <td>0.004866</td>\n      <td>0.005772</td>\n      <td>0.441455</td>\n      <td>0.424451</td>\n      <td>0.003306</td>\n      <td>0.003125</td>\n      <td>0.298761</td>\n      <td>0.302429</td>\n      <td>1760</td>\n      <td>1730.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3560</td>\n      <td>Temple</td>\n      <td>-0.214516</td>\n      <td>NaN</td>\n      <td>-0.214516</td>\n      <td>0.430455</td>\n      <td>0.430545</td>\n      <td>0</td>\n      <td>0</td>\n      <td>14</td>\n      <td>20</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.214516</td>\n      <td>Vanderbilt</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.569545</td>\n      <td>0.569455</td>\n      <td>SEC</td>\n      <td>Vanderbilt</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>12.0</td>\n      <td>7.0</td>\n      <td>2.0</td>\n      <td>3.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>63</td>\n      <td>4</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>35</td>\n      <td>2</td>\n      <td>12</td>\n      <td>15</td>\n      <td>53</td>\n      <td>7</td>\n      <td>0</td>\n      <td>18</td>\n      <td>0</td>\n      <td>-1.187259</td>\n      <td>-0.972742</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547640</td>\n      <td>3</td>\n      <td>1</td>\n      <td>29</td>\n      <td>3</td>\n      <td>Vanderbilt</td>\n      <td>0.214516</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.569545</td>\n      <td>0.569455</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>P.J. Walker pass complete to Jalen Fitzpatrick...</td>\n      <td>TEMPLE Penalty, False Start (5 Yards) to the T...</td>\n      <td>Pass Reception</td>\n      <td>Penalty</td>\n      <td>Kickoff Return (Offense)</td>\n      <td>Temple</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>P.J. Walker pass complete to Jalen Fitzpatrick...</td>\n      <td>Pass Reception</td>\n      <td>Temple</td>\n      <td>2.484907</td>\n      <td>1.945910</td>\n      <td>False</td>\n      <td>False</td>\n      <td>-3.467607</td>\n      <td>-0.484325</td>\n      <td>-0.214516</td>\n      <td>3.467607</td>\n      <td>0.484325</td>\n      <td>0.214516</td>\n      <td>0</td>\n      <td>101857901</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>Temple</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>Vanderbilt</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Rush</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Kenneth Harper run for 5 yds to the Temp 22</td>\n      <td>Rush</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Temple</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>RB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.024724</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Kenneth Harper</td>\n      <td>513403.0</td>\n      <td>0</td>\n      <td>5.0</td>\n      <td>Kenneth Harper</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>-1.733803</td>\n      <td>-0.484325</td>\n      <td>-0.214516</td>\n      <td>1.733803</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.430455</td>\n      <td>0.430545</td>\n      <td>-0.000090</td>\n      <td>83</td>\n      <td>5</td>\n      <td>83</td>\n      <td>78.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>5.0</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>Temple</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>2.529815</td>\n      <td>-1.187259</td>\n      <td>-0.000336</td>\n      <td>0.158063</td>\n      <td>0.093482</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002756</td>\n      <td>0.002888</td>\n      <td>0.097974</td>\n      <td>0.155241</td>\n      <td>0.002650</td>\n      <td>0.004866</td>\n      <td>0.284786</td>\n      <td>0.441455</td>\n      <td>0.003061</td>\n      <td>0.003306</td>\n      <td>0.450710</td>\n      <td>0.298761</td>\n      <td>1730</td>\n      <td>1705.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3530</td>\n      <td>Temple</td>\n      <td>2.529815</td>\n      <td>2.529815</td>\n      <td>NaN</td>\n      <td>0.537439</td>\n      <td>0.430455</td>\n      <td>0</td>\n      <td>0</td>\n      <td>13</td>\n      <td>50</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>-2.529815</td>\n      <td>Vanderbilt</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.462561</td>\n      <td>0.569545</td>\n      <td>SEC</td>\n      <td>Vanderbilt</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>7.0</td>\n      <td>10.0</td>\n      <td>3.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>63</td>\n      <td>5</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>4</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>35</td>\n      <td>2</td>\n      <td>12</td>\n      <td>15</td>\n      <td>53</td>\n      <td>7</td>\n      <td>0</td>\n      <td>18</td>\n      <td>0</td>\n      <td>1.342556</td>\n      <td>-1.187259</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547640</td>\n      <td>4</td>\n      <td>1</td>\n      <td>28</td>\n      <td>4</td>\n      <td>Vanderbilt</td>\n      <td>-2.529815</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.462561</td>\n      <td>0.569545</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Kenneth Harper run for 5 yds to the Temp 22</td>\n      <td>P.J. Walker pass complete to Jalen Fitzpatrick...</td>\n      <td>Rush</td>\n      <td>Pass Reception</td>\n      <td>Penalty</td>\n      <td>Temple</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>P.J. Walker pass complete to Nate Hairston for...</td>\n      <td>Pass Reception</td>\n      <td>Temple</td>\n      <td>1.945910</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>1.592023</td>\n      <td>2.045490</td>\n      <td>-0.214516</td>\n      <td>-1.592023</td>\n      <td>-2.045490</td>\n      <td>0.214516</td>\n      <td>0</td>\n      <td>101864901</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>Temple</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>Vanderbilt</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Reception</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>P.J. Walker</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>P.J. Walker pass complete to Jalen Fitzpatrick...</td>\n      <td>Pass Reception</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Temple</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>1.385952</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Jalen Fitzpatrick</td>\n      <td>1.0</td>\n      <td>Jalen Fitzpatrick</td>\n      <td>513398.0</td>\n      <td>8.0</td>\n      <td>5</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.796012</td>\n      <td>2.045490</td>\n      <td>-0.214516</td>\n      <td>-0.796012</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.537439</td>\n      <td>0.430455</td>\n      <td>0.106984</td>\n      <td>78</td>\n      <td>8</td>\n      <td>78</td>\n      <td>70.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>8.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>Temple</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\npbp_data = pd.merge(pbp_data, spread_data[['game_id','spread']], left_on=\"game_id\", right_on=\"game_id\")\npbp_data.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>EPA</th>\n      <th>ExpScoreDiff</th>\n      <th>ExpScoreDiff_Time_Ratio</th>\n      <th>FG_after</th>\n      <th>FG_before</th>\n      <th>Goal_To_Go</th>\n      <th>Goal_To_Go_end</th>\n      <th>No_Score_after</th>\n      <th>No_Score_before</th>\n      <th>Opp_FG_after</th>\n      <th>Opp_FG_before</th>\n      <th>Opp_Safety_after</th>\n      <th>Opp_Safety_before</th>\n      <th>Opp_TD_after</th>\n      <th>Opp_TD_before</th>\n      <th>Safety_after</th>\n      <th>Safety_before</th>\n      <th>TD_after</th>\n      <th>TD_before</th>\n      <th>TimeSecsRem</th>\n      <th>TimeSecsRem_end</th>\n      <th>Under_three</th>\n      <th>Under_two</th>\n      <th>Under_two_end</th>\n      <th>adj_TimeSecsRem</th>\n      <th>away</th>\n      <th>away_EPA</th>\n      <th>away_EPA_pass</th>\n      <th>away_EPA_rush</th>\n      <th>away_wp_after</th>\n      <th>away_wp_before</th>\n      <th>change_of_pos_team</th>\n      <th>change_of_poss</th>\n      <th>clock.minutes</th>\n      <th>clock.seconds</th>\n      <th>completion</th>\n      <th>completion_player</th>\n      <th>completion_player_id</th>\n      <th>completion_yds</th>\n      <th>def_EPA</th>\n      <th>def_pos_team</th>\n      <th>def_pos_team_score</th>\n      <th>def_pos_team_timeouts</th>\n      <th>def_pos_team_timeouts_rem_before</th>\n      <th>def_timeout_called</th>\n      <th>def_timeouts_rem_before</th>\n      <th>def_wp_after</th>\n      <th>def_wp_before</th>\n      <th>defense_conference</th>\n      <th>defense_play</th>\n      <th>defense_score</th>\n      <th>defense_score_play</th>\n      <th>defense_timeouts</th>\n      <th>distance</th>\n      <th>distance_end</th>\n      <th>down</th>\n      <th>down_end</th>\n      <th>downs_turnover</th>\n      <th>drive_end_period</th>\n      <th>drive_end_yards_to_goal</th>\n      <th>drive_event_number</th>\n      <th>drive_id</th>\n      <th>drive_num</th>\n      <th>drive_number</th>\n      <th>drive_numbers</th>\n      <th>drive_play_number</th>\n      <th>drive_pts</th>\n      <th>drive_result</th>\n      <th>drive_result2</th>\n      <th>drive_result_detailed</th>\n      <th>drive_result_detailed_flag</th>\n      <th>drive_scoring</th>\n      <th>drive_start_period</th>\n      <th>drive_start_yards_to_goal</th>\n      <th>drive_time_minutes_elapsed</th>\n      <th>drive_time_minutes_end</th>\n      <th>drive_time_minutes_start</th>\n      <th>drive_time_seconds_elapsed</th>\n      <th>drive_time_seconds_end</th>\n      <th>drive_time_seconds_start</th>\n      <th>drive_yards</th>\n      <th>end_of_half</th>\n      <th>ep_after</th>\n      <th>ep_before</th>\n      <th>epa_success</th>\n      <th>fg_block_player_name</th>\n      <th>fg_inds</th>\n      <th>fg_kicker_player_name</th>\n      <th>fg_made</th>\n      <th>fg_make_prob</th>\n      <th>fg_return_player_name</th>\n      <th>firstD_by_kickoff</th>\n      <th>firstD_by_penalty</th>\n      <th>firstD_by_poss</th>\n      <th>firstD_by_yards</th>\n      <th>first_by_penalty</th>\n      <th>first_by_yards</th>\n      <th>fumble_forced_player</th>\n      <th>fumble_forced_player_id</th>\n      <th>fumble_forced_player_name</th>\n      <th>fumble_forced_stat</th>\n      <th>fumble_player</th>\n      <th>fumble_player_id</th>\n      <th>fumble_player_name</th>\n      <th>fumble_recovered_player</th>\n      <th>fumble_recovered_player_id</th>\n      <th>fumble_recovered_player_name</th>\n      <th>fumble_recovered_stat</th>\n      <th>fumble_stat</th>\n      <th>fumble_vec</th>\n      <th>game_id</th>\n      <th>game_play_number</th>\n      <th>half</th>\n      <th>half_clock.minutes</th>\n      <th>half_play_number</th>\n      <th>home</th>\n      <th>home_EPA</th>\n      <th>home_EPA_pass</th>\n      <th>home_EPA_rush</th>\n      <th>home_wp_after</th>\n      <th>home_wp_before</th>\n      <th>id_drive</th>\n      <th>id_play</th>\n      <th>incompletion_player</th>\n      <th>incompletion_player_id</th>\n      <th>incompletion_stat</th>\n      <th>int</th>\n      <th>int_td</th>\n      <th>interception_player</th>\n      <th>interception_player_id</th>\n      <th>interception_player_name</th>\n      <th>interception_stat</th>\n      <th>interception_thrown_player</th>\n      <th>interception_thrown_player_id</th>\n      <th>interception_thrown_stat</th>\n      <th>kick_play</th>\n      <th>kickoff_downed</th>\n      <th>kickoff_fair_catch</th>\n      <th>kickoff_onside</th>\n      <th>kickoff_oob</th>\n      <th>kickoff_play</th>\n      <th>kickoff_player_name</th>\n      <th>kickoff_returner_player_name</th>\n      <th>kickoff_safety</th>\n      <th>kickoff_tb</th>\n      <th>lag_change_of_pos_team</th>\n      <th>lag_change_of_pos_team2</th>\n      <th>lag_change_of_poss</th>\n      <th>lag_defense_score_play</th>\n      <th>lag_downs_turnover</th>\n      <th>lag_drive_result_detailed</th>\n      <th>lag_first_by_penalty</th>\n      <th>lag_first_by_penalty2</th>\n      <th>lag_first_by_yards</th>\n      <th>lag_first_by_yards2</th>\n      <th>lag_kickoff_play</th>\n      <th>lag_new_drive_pts</th>\n      <th>lag_play_text</th>\n      <th>lag_play_text2</th>\n      <th>lag_play_type</th>\n      <th>lag_play_type2</th>\n      <th>lag_play_type3</th>\n      <th>lag_pos_team</th>\n      <th>lag_punt</th>\n      <th>lag_punt2</th>\n      <th>lag_scoring_play</th>\n      <th>lag_turnover_vec</th>\n      <th>lead_drive_result_detailed</th>\n      <th>lead_play_text</th>\n      <th>lead_play_type</th>\n      <th>lead_pos_team</th>\n      <th>log_ydstogo</th>\n      <th>log_ydstogo_end</th>\n      <th>middle_8</th>\n      <th>missing_yard_flag</th>\n      <th>net_away_EPA</th>\n      <th>net_away_EPA_pass</th>\n      <th>net_away_EPA_rush</th>\n      <th>net_home_EPA</th>\n      <th>net_home_EPA_pass</th>\n      <th>net_home_EPA_rush</th>\n      <th>new_drive_pts</th>\n      <th>new_id</th>\n      <th>new_series</th>\n      <th>number_of_drives</th>\n      <th>off_timeout_called</th>\n      <th>off_timeouts_rem_before</th>\n      <th>offense_conference</th>\n      <th>offense_play</th>\n      <th>offense_receives_2H_kickoff</th>\n      <th>offense_score</th>\n      <th>offense_score_play</th>\n      <th>offense_timeouts</th>\n      <th>opponent</th>\n      <th>opponent_score</th>\n      <th>orig_drive_number</th>\n      <th>orig_play_type</th>\n      <th>pass</th>\n      <th>pass_attempt</th>\n      <th>pass_breakup_player</th>\n      <th>pass_breakup_player_id</th>\n      <th>pass_breakup_player_name</th>\n      <th>pass_breakup_stat</th>\n      <th>pass_td</th>\n      <th>passer_player_name</th>\n      <th>penalty_1st_conv</th>\n      <th>penalty_declined</th>\n      <th>penalty_detail</th>\n      <th>penalty_flag</th>\n      <th>penalty_no_play</th>\n      <th>penalty_offset</th>\n      <th>penalty_play_text</th>\n      <th>penalty_safety</th>\n      <th>penalty_text</th>\n      <th>period</th>\n      <th>play_after_turnover</th>\n      <th>play_id</th>\n      <th>play_text</th>\n      <th>play_type</th>\n      <th>pos_score_diff</th>\n      <th>pos_score_diff_start</th>\n      <th>pos_score_diff_start_end</th>\n      <th>pos_score_pts</th>\n      <th>pos_team</th>\n      <th>pos_team_receives_2H_kickoff</th>\n      <th>pos_team_score</th>\n      <th>pos_team_timeouts</th>\n      <th>pos_team_timeouts_rem_before</th>\n      <th>position_completion</th>\n      <th>position_fumble</th>\n      <th>position_fumble_forced</th>\n      <th>position_fumble_recovered</th>\n      <th>position_incompletion</th>\n      <th>position_interception</th>\n      <th>position_interception_thrown</th>\n      <th>position_pass_breakup</th>\n      <th>position_reception</th>\n      <th>position_rush</th>\n      <th>position_sack</th>\n      <th>position_sack_taken</th>\n      <th>position_target</th>\n      <th>position_touchdown</th>\n      <th>ppa</th>\n      <th>pts_scored</th>\n      <th>punt</th>\n      <th>punt_block_player_name</th>\n      <th>punt_block_return_player_name</th>\n      <th>punt_blocked</th>\n      <th>punt_downed</th>\n      <th>punt_fair_catch</th>\n      <th>punt_oob</th>\n      <th>punt_play</th>\n      <th>punt_returner_player_name</th>\n      <th>punt_safety</th>\n      <th>punt_tb</th>\n      <th>punter_player_name</th>\n      <th>receiver_player_name</th>\n      <th>receives_2H_kickoff</th>\n      <th>reception_player</th>\n      <th>reception_player_id</th>\n      <th>reception_yds</th>\n      <th>row</th>\n      <th>rush</th>\n      <th>rush_player</th>\n      <th>rush_player_id</th>\n      <th>rush_td</th>\n      <th>rush_yds</th>\n      <th>rusher_player_name</th>\n      <th>rz_play</th>\n      <th>sack</th>\n      <th>sack_player</th>\n      <th>sack_player_id</th>\n      <th>sack_player_name</th>\n      <th>sack_player_name2</th>\n      <th>sack_players</th>\n      <th>sack_stat</th>\n      <th>sack_taken_player</th>\n      <th>sack_taken_player_id</th>\n      <th>sack_taken_stat</th>\n      <th>sack_vec</th>\n      <th>safety</th>\n      <th>score_diff</th>\n      <th>score_diff_start</th>\n      <th>score_pts</th>\n      <th>scoring</th>\n      <th>scoring_opp</th>\n      <th>scoring_play</th>\n      <th>season</th>\n      <th>stuffed_run</th>\n      <th>success</th>\n      <th>target</th>\n      <th>target_player</th>\n      <th>target_player_id</th>\n      <th>target_stat</th>\n      <th>td_play</th>\n      <th>team_score</th>\n      <th>total_away_EPA</th>\n      <th>total_away_EPA_pass</th>\n      <th>total_away_EPA_rush</th>\n      <th>total_home_EPA</th>\n      <th>total_home_EPA_pass</th>\n      <th>total_home_EPA_rush</th>\n      <th>touchdown</th>\n      <th>touchdown_player</th>\n      <th>touchdown_player_id</th>\n      <th>touchdown_stat</th>\n      <th>turnover</th>\n      <th>turnover_indicator</th>\n      <th>turnover_vec</th>\n      <th>turnover_vec_lag</th>\n      <th>week</th>\n      <th>wp_after</th>\n      <th>wp_before</th>\n      <th>wpa</th>\n      <th>yard_line</th>\n      <th>yards_gained</th>\n      <th>yards_to_goal</th>\n      <th>yards_to_goal_end</th>\n      <th>yds_fg</th>\n      <th>yds_fumble_return</th>\n      <th>yds_int_return</th>\n      <th>yds_kickoff</th>\n      <th>yds_kickoff_return</th>\n      <th>yds_penalty</th>\n      <th>yds_punt_gained</th>\n      <th>yds_punt_return</th>\n      <th>yds_punted</th>\n      <th>yds_receiving</th>\n      <th>yds_rushed</th>\n      <th>yds_sacked</th>\n      <th>year</th>\n      <th>winner</th>\n      <th>spread</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>-0.470573</td>\n      <td>0.833168</td>\n      <td>0.000231</td>\n      <td>0.134882</td>\n      <td>0.170347</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002152</td>\n      <td>0.001775</td>\n      <td>0.121537</td>\n      <td>0.089202</td>\n      <td>0.004375</td>\n      <td>0.001915</td>\n      <td>0.343792</td>\n      <td>0.260404</td>\n      <td>0.002997</td>\n      <td>0.002950</td>\n      <td>0.390266</td>\n      <td>0.473408</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>0.470573</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.528336</td>\n      <td>0.509680</td>\n      <td>0</td>\n      <td>1</td>\n      <td>15</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.470573</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.528336</td>\n      <td>0.509680</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>1</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>0.362595</td>\n      <td>0.833168</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>1</td>\n      <td>1</td>\n      <td>30</td>\n      <td>1</td>\n      <td>East Carolina</td>\n      <td>-0.470573</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.471664</td>\n      <td>0.490320</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Brandon McLaren</td>\n      <td>Isaiah Jones</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Pass Reception</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.941145</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>-0.941145</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849902</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>Kickoff</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>Brandon McLaren kickoff for 51 yds , Isaiah Jo...</td>\n      <td>Kickoff</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.470573</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-0.470573</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0.471664</td>\n      <td>0.490320</td>\n      <td>-0.018655</td>\n      <td>65</td>\n      <td>6</td>\n      <td>65</td>\n      <td>80.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>51.0</td>\n      <td>6.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>-0.168094</td>\n      <td>0.362595</td>\n      <td>0.000101</td>\n      <td>0.128390</td>\n      <td>0.134882</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002141</td>\n      <td>0.002152</td>\n      <td>0.124954</td>\n      <td>0.121537</td>\n      <td>0.003679</td>\n      <td>0.004375</td>\n      <td>0.355615</td>\n      <td>0.343792</td>\n      <td>0.003138</td>\n      <td>0.002997</td>\n      <td>0.382083</td>\n      <td>0.390266</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>0.168094</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.535004</td>\n      <td>0.528336</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>4.0</td>\n      <td>0.168094</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.535004</td>\n      <td>0.528336</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>6.0</td>\n      <td>1.0</td>\n      <td>2.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>2</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>0.194501</td>\n      <td>0.362595</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>2</td>\n      <td>1</td>\n      <td>30</td>\n      <td>2</td>\n      <td>East Carolina</td>\n      <td>-0.168094</td>\n      <td>-0.168094</td>\n      <td>NaN</td>\n      <td>0.464996</td>\n      <td>0.471664</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>Brandon McLaren kickoff for 51 yds , Isaiah Jo...</td>\n      <td>None</td>\n      <td>Kickoff</td>\n      <td>None</td>\n      <td>None</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Pass Reception</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>1.791759</td>\n      <td>False</td>\n      <td>False</td>\n      <td>1.277333</td>\n      <td>0.168094</td>\n      <td>0.0</td>\n      <td>-1.277333</td>\n      <td>-0.168094</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849903</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>North Carolina Central</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Reception</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Pass Reception</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>-0.088432</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Justin Hardy</td>\n      <td>0.0</td>\n      <td>Justin Hardy</td>\n      <td>505407.0</td>\n      <td>4.0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.638667</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-0.638667</td>\n      <td>-0.168094</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.464996</td>\n      <td>0.471664</td>\n      <td>-0.006668</td>\n      <td>20</td>\n      <td>4</td>\n      <td>80</td>\n      <td>76.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>4.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2.283941</td>\n      <td>0.194501</td>\n      <td>0.000054</td>\n      <td>0.190673</td>\n      <td>0.128390</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.001539</td>\n      <td>0.002141</td>\n      <td>0.072094</td>\n      <td>0.124954</td>\n      <td>0.001135</td>\n      <td>0.003679</td>\n      <td>0.214480</td>\n      <td>0.355615</td>\n      <td>0.002843</td>\n      <td>0.003138</td>\n      <td>0.517235</td>\n      <td>0.382083</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>-2.283941</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.445405</td>\n      <td>0.535004</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>20.0</td>\n      <td>-2.283941</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.445405</td>\n      <td>0.535004</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>6.0</td>\n      <td>10.0</td>\n      <td>2.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>3</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>2.478443</td>\n      <td>0.194501</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>3</td>\n      <td>1</td>\n      <td>30</td>\n      <td>3</td>\n      <td>East Carolina</td>\n      <td>2.283941</td>\n      <td>2.283941</td>\n      <td>NaN</td>\n      <td>0.554595</td>\n      <td>0.464996</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Brandon McLaren kickoff for 51 yds , Isaiah Jo...</td>\n      <td>Pass Reception</td>\n      <td>Kickoff</td>\n      <td>None</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass incomplete to Justin Hardy, ...</td>\n      <td>Pass Incompletion</td>\n      <td>East Carolina</td>\n      <td>1.791759</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>-3.290549</td>\n      <td>-2.115847</td>\n      <td>0.0</td>\n      <td>3.290549</td>\n      <td>2.115847</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849904</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>North Carolina Central</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Reception</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Pass Reception</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>2.104307</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Cam Worthy</td>\n      <td>0.0</td>\n      <td>Cam Worthy</td>\n      <td>552953.0</td>\n      <td>20.0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>-1.645275</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.645275</td>\n      <td>2.115847</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.554595</td>\n      <td>0.464996</td>\n      <td>0.089599</td>\n      <td>24</td>\n      <td>20</td>\n      <td>76</td>\n      <td>56.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>20.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>-0.855503</td>\n      <td>2.478443</td>\n      <td>0.000688</td>\n      <td>0.193531</td>\n      <td>0.190673</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.001703</td>\n      <td>0.001539</td>\n      <td>0.087026</td>\n      <td>0.072094</td>\n      <td>0.001516</td>\n      <td>0.001135</td>\n      <td>0.263697</td>\n      <td>0.214480</td>\n      <td>0.003072</td>\n      <td>0.002843</td>\n      <td>0.449456</td>\n      <td>0.517235</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>0.855503</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.478562</td>\n      <td>0.445405</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.855503</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.478562</td>\n      <td>0.445405</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>1.0</td>\n      <td>2.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>4</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>4</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>1.622940</td>\n      <td>2.478443</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>4</td>\n      <td>1</td>\n      <td>30</td>\n      <td>4</td>\n      <td>East Carolina</td>\n      <td>-0.855503</td>\n      <td>-0.855503</td>\n      <td>NaN</td>\n      <td>0.521438</td>\n      <td>0.554595</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Pass Reception</td>\n      <td>Pass Reception</td>\n      <td>Kickoff</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass incomplete to Davon Grayson</td>\n      <td>Pass Incompletion</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>-1.579543</td>\n      <td>-1.260344</td>\n      <td>0.0</td>\n      <td>1.579543</td>\n      <td>1.260344</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849905</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Incompletion</td>\n      <td>1</td>\n      <td>1</td>\n      <td>Michael Jones</td>\n      <td>164873.0</td>\n      <td>Michael Jones</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass incomplete to Justin Hardy, ...</td>\n      <td>Pass Incompletion</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>-1.161247</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Justin Hardy</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>4</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Justin Hardy</td>\n      <td>505407.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>-0.789771</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.789771</td>\n      <td>1.260344</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.521438</td>\n      <td>0.554595</td>\n      <td>-0.033156</td>\n      <td>44</td>\n      <td>0</td>\n      <td>56</td>\n      <td>56.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>-1.130810</td>\n      <td>1.622940</td>\n      <td>0.000451</td>\n      <td>0.185681</td>\n      <td>0.193531</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.001837</td>\n      <td>0.001703</td>\n      <td>0.109427</td>\n      <td>0.087026</td>\n      <td>0.002270</td>\n      <td>0.001516</td>\n      <td>0.329919</td>\n      <td>0.263697</td>\n      <td>0.003745</td>\n      <td>0.003072</td>\n      <td>0.367121</td>\n      <td>0.449456</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>1.130810</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.523197</td>\n      <td>0.478562</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1.130810</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.523197</td>\n      <td>0.478562</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>2.0</td>\n      <td>3.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>5</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>5</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>0.492129</td>\n      <td>1.622940</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>5</td>\n      <td>1</td>\n      <td>30</td>\n      <td>5</td>\n      <td>East Carolina</td>\n      <td>-1.130810</td>\n      <td>-1.130810</td>\n      <td>NaN</td>\n      <td>0.476803</td>\n      <td>0.521438</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Shane Carden pass incomplete to Justin Hardy, ...</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Pass Incompletion</td>\n      <td>Pass Reception</td>\n      <td>Pass Reception</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>EAST CAROLINA Penalty, false start (-5 Yards) ...</td>\n      <td>Penalty</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.682078</td>\n      <td>-0.129534</td>\n      <td>0.0</td>\n      <td>-0.682078</td>\n      <td>0.129534</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849906</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>North Carolina Central</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Incompletion</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass incomplete to Davon Grayson</td>\n      <td>Pass Incompletion</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>-0.881290</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Davon Grayson</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>5</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Davon Grayson</td>\n      <td>552937.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.341039</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-0.341039</td>\n      <td>0.129534</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.476803</td>\n      <td>0.521438</td>\n      <td>-0.044636</td>\n      <td>44</td>\n      <td>0</td>\n      <td>56</td>\n      <td>56.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\npbp_data['pos_team_spread'] = np.where(pbp_data.pos_team == pbp_data.home, pbp_data.spread, -1 * pbp_data.spread)\npbp_data['elapsed_share'] = (3600 - pbp_data.adj_TimeSecsRem) / 3600\npbp_data['spread_time'] = pbp_data.pos_team_spread * np.exp(-4 * pbp_data.elapsed_share)\npbp_data['is_home'] = np.where(pbp_data.pos_team == pbp_data.home, 1, 0)\npbp_data.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>EPA</th>\n      <th>ExpScoreDiff</th>\n      <th>ExpScoreDiff_Time_Ratio</th>\n      <th>FG_after</th>\n      <th>FG_before</th>\n      <th>Goal_To_Go</th>\n      <th>Goal_To_Go_end</th>\n      <th>No_Score_after</th>\n      <th>No_Score_before</th>\n      <th>Opp_FG_after</th>\n      <th>Opp_FG_before</th>\n      <th>Opp_Safety_after</th>\n      <th>Opp_Safety_before</th>\n      <th>Opp_TD_after</th>\n      <th>Opp_TD_before</th>\n      <th>Safety_after</th>\n      <th>Safety_before</th>\n      <th>TD_after</th>\n      <th>TD_before</th>\n      <th>TimeSecsRem</th>\n      <th>TimeSecsRem_end</th>\n      <th>Under_three</th>\n      <th>Under_two</th>\n      <th>Under_two_end</th>\n      <th>adj_TimeSecsRem</th>\n      <th>away</th>\n      <th>away_EPA</th>\n      <th>away_EPA_pass</th>\n      <th>away_EPA_rush</th>\n      <th>away_wp_after</th>\n      <th>away_wp_before</th>\n      <th>change_of_pos_team</th>\n      <th>change_of_poss</th>\n      <th>clock.minutes</th>\n      <th>clock.seconds</th>\n      <th>completion</th>\n      <th>completion_player</th>\n      <th>completion_player_id</th>\n      <th>completion_yds</th>\n      <th>def_EPA</th>\n      <th>def_pos_team</th>\n      <th>def_pos_team_score</th>\n      <th>def_pos_team_timeouts</th>\n      <th>def_pos_team_timeouts_rem_before</th>\n      <th>def_timeout_called</th>\n      <th>def_timeouts_rem_before</th>\n      <th>def_wp_after</th>\n      <th>def_wp_before</th>\n      <th>defense_conference</th>\n      <th>defense_play</th>\n      <th>defense_score</th>\n      <th>defense_score_play</th>\n      <th>defense_timeouts</th>\n      <th>distance</th>\n      <th>distance_end</th>\n      <th>down</th>\n      <th>down_end</th>\n      <th>downs_turnover</th>\n      <th>drive_end_period</th>\n      <th>drive_end_yards_to_goal</th>\n      <th>drive_event_number</th>\n      <th>drive_id</th>\n      <th>drive_num</th>\n      <th>drive_number</th>\n      <th>drive_numbers</th>\n      <th>drive_play_number</th>\n      <th>drive_pts</th>\n      <th>drive_result</th>\n      <th>drive_result2</th>\n      <th>drive_result_detailed</th>\n      <th>drive_result_detailed_flag</th>\n      <th>drive_scoring</th>\n      <th>drive_start_period</th>\n      <th>drive_start_yards_to_goal</th>\n      <th>drive_time_minutes_elapsed</th>\n      <th>drive_time_minutes_end</th>\n      <th>drive_time_minutes_start</th>\n      <th>drive_time_seconds_elapsed</th>\n      <th>drive_time_seconds_end</th>\n      <th>drive_time_seconds_start</th>\n      <th>drive_yards</th>\n      <th>end_of_half</th>\n      <th>ep_after</th>\n      <th>ep_before</th>\n      <th>epa_success</th>\n      <th>fg_block_player_name</th>\n      <th>fg_inds</th>\n      <th>fg_kicker_player_name</th>\n      <th>fg_made</th>\n      <th>fg_make_prob</th>\n      <th>fg_return_player_name</th>\n      <th>firstD_by_kickoff</th>\n      <th>firstD_by_penalty</th>\n      <th>firstD_by_poss</th>\n      <th>firstD_by_yards</th>\n      <th>first_by_penalty</th>\n      <th>first_by_yards</th>\n      <th>fumble_forced_player</th>\n      <th>fumble_forced_player_id</th>\n      <th>fumble_forced_player_name</th>\n      <th>fumble_forced_stat</th>\n      <th>fumble_player</th>\n      <th>fumble_player_id</th>\n      <th>fumble_player_name</th>\n      <th>fumble_recovered_player</th>\n      <th>fumble_recovered_player_id</th>\n      <th>fumble_recovered_player_name</th>\n      <th>fumble_recovered_stat</th>\n      <th>fumble_stat</th>\n      <th>fumble_vec</th>\n      <th>game_id</th>\n      <th>game_play_number</th>\n      <th>half</th>\n      <th>half_clock.minutes</th>\n      <th>half_play_number</th>\n      <th>home</th>\n      <th>home_EPA</th>\n      <th>home_EPA_pass</th>\n      <th>home_EPA_rush</th>\n      <th>home_wp_after</th>\n      <th>home_wp_before</th>\n      <th>id_drive</th>\n      <th>id_play</th>\n      <th>incompletion_player</th>\n      <th>incompletion_player_id</th>\n      <th>incompletion_stat</th>\n      <th>int</th>\n      <th>int_td</th>\n      <th>interception_player</th>\n      <th>interception_player_id</th>\n      <th>interception_player_name</th>\n      <th>interception_stat</th>\n      <th>interception_thrown_player</th>\n      <th>interception_thrown_player_id</th>\n      <th>interception_thrown_stat</th>\n      <th>kick_play</th>\n      <th>kickoff_downed</th>\n      <th>kickoff_fair_catch</th>\n      <th>kickoff_onside</th>\n      <th>kickoff_oob</th>\n      <th>kickoff_play</th>\n      <th>kickoff_player_name</th>\n      <th>kickoff_returner_player_name</th>\n      <th>kickoff_safety</th>\n      <th>kickoff_tb</th>\n      <th>lag_change_of_pos_team</th>\n      <th>lag_change_of_pos_team2</th>\n      <th>lag_change_of_poss</th>\n      <th>lag_defense_score_play</th>\n      <th>lag_downs_turnover</th>\n      <th>lag_drive_result_detailed</th>\n      <th>lag_first_by_penalty</th>\n      <th>lag_first_by_penalty2</th>\n      <th>lag_first_by_yards</th>\n      <th>lag_first_by_yards2</th>\n      <th>lag_kickoff_play</th>\n      <th>lag_new_drive_pts</th>\n      <th>lag_play_text</th>\n      <th>lag_play_text2</th>\n      <th>lag_play_type</th>\n      <th>lag_play_type2</th>\n      <th>lag_play_type3</th>\n      <th>lag_pos_team</th>\n      <th>lag_punt</th>\n      <th>lag_punt2</th>\n      <th>lag_scoring_play</th>\n      <th>lag_turnover_vec</th>\n      <th>lead_drive_result_detailed</th>\n      <th>lead_play_text</th>\n      <th>lead_play_type</th>\n      <th>lead_pos_team</th>\n      <th>log_ydstogo</th>\n      <th>log_ydstogo_end</th>\n      <th>middle_8</th>\n      <th>missing_yard_flag</th>\n      <th>net_away_EPA</th>\n      <th>net_away_EPA_pass</th>\n      <th>net_away_EPA_rush</th>\n      <th>net_home_EPA</th>\n      <th>net_home_EPA_pass</th>\n      <th>net_home_EPA_rush</th>\n      <th>new_drive_pts</th>\n      <th>new_id</th>\n      <th>new_series</th>\n      <th>number_of_drives</th>\n      <th>off_timeout_called</th>\n      <th>off_timeouts_rem_before</th>\n      <th>offense_conference</th>\n      <th>offense_play</th>\n      <th>offense_receives_2H_kickoff</th>\n      <th>offense_score</th>\n      <th>offense_score_play</th>\n      <th>offense_timeouts</th>\n      <th>opponent</th>\n      <th>opponent_score</th>\n      <th>orig_drive_number</th>\n      <th>orig_play_type</th>\n      <th>pass</th>\n      <th>pass_attempt</th>\n      <th>pass_breakup_player</th>\n      <th>pass_breakup_player_id</th>\n      <th>pass_breakup_player_name</th>\n      <th>pass_breakup_stat</th>\n      <th>pass_td</th>\n      <th>passer_player_name</th>\n      <th>penalty_1st_conv</th>\n      <th>penalty_declined</th>\n      <th>penalty_detail</th>\n      <th>penalty_flag</th>\n      <th>penalty_no_play</th>\n      <th>penalty_offset</th>\n      <th>penalty_play_text</th>\n      <th>penalty_safety</th>\n      <th>penalty_text</th>\n      <th>period</th>\n      <th>play_after_turnover</th>\n      <th>play_id</th>\n      <th>play_text</th>\n      <th>play_type</th>\n      <th>pos_score_diff</th>\n      <th>pos_score_diff_start</th>\n      <th>pos_score_diff_start_end</th>\n      <th>pos_score_pts</th>\n      <th>pos_team</th>\n      <th>pos_team_receives_2H_kickoff</th>\n      <th>pos_team_score</th>\n      <th>pos_team_timeouts</th>\n      <th>pos_team_timeouts_rem_before</th>\n      <th>position_completion</th>\n      <th>position_fumble</th>\n      <th>position_fumble_forced</th>\n      <th>position_fumble_recovered</th>\n      <th>position_incompletion</th>\n      <th>position_interception</th>\n      <th>position_interception_thrown</th>\n      <th>position_pass_breakup</th>\n      <th>position_reception</th>\n      <th>position_rush</th>\n      <th>position_sack</th>\n      <th>position_sack_taken</th>\n      <th>position_target</th>\n      <th>position_touchdown</th>\n      <th>ppa</th>\n      <th>pts_scored</th>\n      <th>punt</th>\n      <th>punt_block_player_name</th>\n      <th>punt_block_return_player_name</th>\n      <th>punt_blocked</th>\n      <th>punt_downed</th>\n      <th>punt_fair_catch</th>\n      <th>punt_oob</th>\n      <th>punt_play</th>\n      <th>punt_returner_player_name</th>\n      <th>punt_safety</th>\n      <th>punt_tb</th>\n      <th>punter_player_name</th>\n      <th>receiver_player_name</th>\n      <th>receives_2H_kickoff</th>\n      <th>reception_player</th>\n      <th>reception_player_id</th>\n      <th>reception_yds</th>\n      <th>row</th>\n      <th>rush</th>\n      <th>rush_player</th>\n      <th>rush_player_id</th>\n      <th>rush_td</th>\n      <th>rush_yds</th>\n      <th>rusher_player_name</th>\n      <th>rz_play</th>\n      <th>sack</th>\n      <th>sack_player</th>\n      <th>sack_player_id</th>\n      <th>sack_player_name</th>\n      <th>sack_player_name2</th>\n      <th>sack_players</th>\n      <th>sack_stat</th>\n      <th>sack_taken_player</th>\n      <th>sack_taken_player_id</th>\n      <th>sack_taken_stat</th>\n      <th>sack_vec</th>\n      <th>safety</th>\n      <th>score_diff</th>\n      <th>score_diff_start</th>\n      <th>score_pts</th>\n      <th>scoring</th>\n      <th>scoring_opp</th>\n      <th>scoring_play</th>\n      <th>season</th>\n      <th>stuffed_run</th>\n      <th>success</th>\n      <th>target</th>\n      <th>target_player</th>\n      <th>target_player_id</th>\n      <th>target_stat</th>\n      <th>td_play</th>\n      <th>team_score</th>\n      <th>total_away_EPA</th>\n      <th>total_away_EPA_pass</th>\n      <th>total_away_EPA_rush</th>\n      <th>total_home_EPA</th>\n      <th>total_home_EPA_pass</th>\n      <th>total_home_EPA_rush</th>\n      <th>touchdown</th>\n      <th>touchdown_player</th>\n      <th>touchdown_player_id</th>\n      <th>touchdown_stat</th>\n      <th>turnover</th>\n      <th>turnover_indicator</th>\n      <th>turnover_vec</th>\n      <th>turnover_vec_lag</th>\n      <th>week</th>\n      <th>wp_after</th>\n      <th>wp_before</th>\n      <th>wpa</th>\n      <th>yard_line</th>\n      <th>yards_gained</th>\n      <th>yards_to_goal</th>\n      <th>yards_to_goal_end</th>\n      <th>yds_fg</th>\n      <th>yds_fumble_return</th>\n      <th>yds_int_return</th>\n      <th>yds_kickoff</th>\n      <th>yds_kickoff_return</th>\n      <th>yds_penalty</th>\n      <th>yds_punt_gained</th>\n      <th>yds_punt_return</th>\n      <th>yds_punted</th>\n      <th>yds_receiving</th>\n      <th>yds_rushed</th>\n      <th>yds_sacked</th>\n      <th>year</th>\n      <th>winner</th>\n      <th>spread</th>\n      <th>pos_team_spread</th>\n      <th>elapsed_share</th>\n      <th>spread_time</th>\n      <th>is_home</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>-0.470573</td>\n      <td>0.833168</td>\n      <td>0.000231</td>\n      <td>0.134882</td>\n      <td>0.170347</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002152</td>\n      <td>0.001775</td>\n      <td>0.121537</td>\n      <td>0.089202</td>\n      <td>0.004375</td>\n      <td>0.001915</td>\n      <td>0.343792</td>\n      <td>0.260404</td>\n      <td>0.002997</td>\n      <td>0.002950</td>\n      <td>0.390266</td>\n      <td>0.473408</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>0.470573</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.528336</td>\n      <td>0.509680</td>\n      <td>0</td>\n      <td>1</td>\n      <td>15</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.470573</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.528336</td>\n      <td>0.509680</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>1</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>0.362595</td>\n      <td>0.833168</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>1</td>\n      <td>1</td>\n      <td>30</td>\n      <td>1</td>\n      <td>East Carolina</td>\n      <td>-0.470573</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.471664</td>\n      <td>0.490320</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Brandon McLaren</td>\n      <td>Isaiah Jones</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Pass Reception</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.941145</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>-0.941145</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849902</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>Kickoff</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>Brandon McLaren kickoff for 51 yds , Isaiah Jo...</td>\n      <td>Kickoff</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.470573</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-0.470573</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0.471664</td>\n      <td>0.490320</td>\n      <td>-0.018655</td>\n      <td>65</td>\n      <td>6</td>\n      <td>65</td>\n      <td>80.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>51.0</td>\n      <td>6.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>-0.168094</td>\n      <td>0.362595</td>\n      <td>0.000101</td>\n      <td>0.128390</td>\n      <td>0.134882</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002141</td>\n      <td>0.002152</td>\n      <td>0.124954</td>\n      <td>0.121537</td>\n      <td>0.003679</td>\n      <td>0.004375</td>\n      <td>0.355615</td>\n      <td>0.343792</td>\n      <td>0.003138</td>\n      <td>0.002997</td>\n      <td>0.382083</td>\n      <td>0.390266</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>0.168094</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.535004</td>\n      <td>0.528336</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>4.0</td>\n      <td>0.168094</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.535004</td>\n      <td>0.528336</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>6.0</td>\n      <td>1.0</td>\n      <td>2.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>2</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>0.194501</td>\n      <td>0.362595</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>2</td>\n      <td>1</td>\n      <td>30</td>\n      <td>2</td>\n      <td>East Carolina</td>\n      <td>-0.168094</td>\n      <td>-0.168094</td>\n      <td>NaN</td>\n      <td>0.464996</td>\n      <td>0.471664</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>Brandon McLaren kickoff for 51 yds , Isaiah Jo...</td>\n      <td>None</td>\n      <td>Kickoff</td>\n      <td>None</td>\n      <td>None</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Pass Reception</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>1.791759</td>\n      <td>False</td>\n      <td>False</td>\n      <td>1.277333</td>\n      <td>0.168094</td>\n      <td>0.0</td>\n      <td>-1.277333</td>\n      <td>-0.168094</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849903</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>North Carolina Central</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Reception</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Pass Reception</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>-0.088432</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Justin Hardy</td>\n      <td>0.0</td>\n      <td>Justin Hardy</td>\n      <td>505407.0</td>\n      <td>4.0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.638667</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-0.638667</td>\n      <td>-0.168094</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.464996</td>\n      <td>0.471664</td>\n      <td>-0.006668</td>\n      <td>20</td>\n      <td>4</td>\n      <td>80</td>\n      <td>76.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>4.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2.283941</td>\n      <td>0.194501</td>\n      <td>0.000054</td>\n      <td>0.190673</td>\n      <td>0.128390</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.001539</td>\n      <td>0.002141</td>\n      <td>0.072094</td>\n      <td>0.124954</td>\n      <td>0.001135</td>\n      <td>0.003679</td>\n      <td>0.214480</td>\n      <td>0.355615</td>\n      <td>0.002843</td>\n      <td>0.003138</td>\n      <td>0.517235</td>\n      <td>0.382083</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>-2.283941</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.445405</td>\n      <td>0.535004</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>20.0</td>\n      <td>-2.283941</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.445405</td>\n      <td>0.535004</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>6.0</td>\n      <td>10.0</td>\n      <td>2.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>3</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>2.478443</td>\n      <td>0.194501</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>3</td>\n      <td>1</td>\n      <td>30</td>\n      <td>3</td>\n      <td>East Carolina</td>\n      <td>2.283941</td>\n      <td>2.283941</td>\n      <td>NaN</td>\n      <td>0.554595</td>\n      <td>0.464996</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Brandon McLaren kickoff for 51 yds , Isaiah Jo...</td>\n      <td>Pass Reception</td>\n      <td>Kickoff</td>\n      <td>None</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass incomplete to Justin Hardy, ...</td>\n      <td>Pass Incompletion</td>\n      <td>East Carolina</td>\n      <td>1.791759</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>-3.290549</td>\n      <td>-2.115847</td>\n      <td>0.0</td>\n      <td>3.290549</td>\n      <td>2.115847</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849904</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>North Carolina Central</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Reception</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Pass Reception</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>2.104307</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Cam Worthy</td>\n      <td>0.0</td>\n      <td>Cam Worthy</td>\n      <td>552953.0</td>\n      <td>20.0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>-1.645275</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.645275</td>\n      <td>2.115847</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.554595</td>\n      <td>0.464996</td>\n      <td>0.089599</td>\n      <td>24</td>\n      <td>20</td>\n      <td>76</td>\n      <td>56.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>20.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>-0.855503</td>\n      <td>2.478443</td>\n      <td>0.000688</td>\n      <td>0.193531</td>\n      <td>0.190673</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.001703</td>\n      <td>0.001539</td>\n      <td>0.087026</td>\n      <td>0.072094</td>\n      <td>0.001516</td>\n      <td>0.001135</td>\n      <td>0.263697</td>\n      <td>0.214480</td>\n      <td>0.003072</td>\n      <td>0.002843</td>\n      <td>0.449456</td>\n      <td>0.517235</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>0.855503</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.478562</td>\n      <td>0.445405</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.855503</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.478562</td>\n      <td>0.445405</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>1.0</td>\n      <td>2.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>4</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>4</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>1.622940</td>\n      <td>2.478443</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>4</td>\n      <td>1</td>\n      <td>30</td>\n      <td>4</td>\n      <td>East Carolina</td>\n      <td>-0.855503</td>\n      <td>-0.855503</td>\n      <td>NaN</td>\n      <td>0.521438</td>\n      <td>0.554595</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Pass Reception</td>\n      <td>Pass Reception</td>\n      <td>Kickoff</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass incomplete to Davon Grayson</td>\n      <td>Pass Incompletion</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>-1.579543</td>\n      <td>-1.260344</td>\n      <td>0.0</td>\n      <td>1.579543</td>\n      <td>1.260344</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849905</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Incompletion</td>\n      <td>1</td>\n      <td>1</td>\n      <td>Michael Jones</td>\n      <td>164873.0</td>\n      <td>Michael Jones</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass incomplete to Justin Hardy, ...</td>\n      <td>Pass Incompletion</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>-1.161247</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Justin Hardy</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>4</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Justin Hardy</td>\n      <td>505407.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>-0.789771</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.789771</td>\n      <td>1.260344</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.521438</td>\n      <td>0.554595</td>\n      <td>-0.033156</td>\n      <td>44</td>\n      <td>0</td>\n      <td>56</td>\n      <td>56.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>-1.130810</td>\n      <td>1.622940</td>\n      <td>0.000451</td>\n      <td>0.185681</td>\n      <td>0.193531</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.001837</td>\n      <td>0.001703</td>\n      <td>0.109427</td>\n      <td>0.087026</td>\n      <td>0.002270</td>\n      <td>0.001516</td>\n      <td>0.329919</td>\n      <td>0.263697</td>\n      <td>0.003745</td>\n      <td>0.003072</td>\n      <td>0.367121</td>\n      <td>0.449456</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>1.130810</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.523197</td>\n      <td>0.478562</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1.130810</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.523197</td>\n      <td>0.478562</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>2.0</td>\n      <td>3.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>5</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>5</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>0.492129</td>\n      <td>1.622940</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>5</td>\n      <td>1</td>\n      <td>30</td>\n      <td>5</td>\n      <td>East Carolina</td>\n      <td>-1.130810</td>\n      <td>-1.130810</td>\n      <td>NaN</td>\n      <td>0.476803</td>\n      <td>0.521438</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Shane Carden pass incomplete to Justin Hardy, ...</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Pass Incompletion</td>\n      <td>Pass Reception</td>\n      <td>Pass Reception</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>EAST CAROLINA Penalty, false start (-5 Yards) ...</td>\n      <td>Penalty</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.682078</td>\n      <td>-0.129534</td>\n      <td>0.0</td>\n      <td>-0.682078</td>\n      <td>0.129534</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849906</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>North Carolina Central</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Incompletion</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass incomplete to Davon Grayson</td>\n      <td>Pass Incompletion</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>-0.881290</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Davon Grayson</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>5</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Davon Grayson</td>\n      <td>552937.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.341039</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-0.341039</td>\n      <td>0.129534</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.476803</td>\n      <td>0.521438</td>\n      <td>-0.044636</td>\n      <td>44</td>\n      <td>0</td>\n      <td>56</td>\n      <td>56.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\npbp_data['win_indicator'] = pbp_data.pos_team == pbp_data.winner\npbp_data.half = pbp_data.half.astype(int)\npbp_data.loc[pbp_data.off_timeouts_rem_before.isna(), \"off_timeouts_rem_before\"] = 0\npbp_data.loc[pbp_data.def_timeouts_rem_before.isna(), \"def_timeouts_rem_before\"] = 0\n\n# https://zacharyst.com/2019/03/06/group_by-mutate-using-pandas/\n# def determine_receive_2h_ko(data):\n# #     print(data.game_id.iloc[0])\n#     val = data.sort_values(by=\"play_id\")[(data.period == 3) & (~data.play_type.str.contains(\"Kickoff\"))].pos_team\n#     ret_val = None\n#     if (len(val) != 0):\n#         ret_val = val.iloc[0]\n#     data['receive_2h_ko'] = ret_val\n#     return data\n\n# pbp_data = pbp_data.groupby('game_id').apply(determine_receive_2h_ko)\n# pbp_data.loc[pbp_data.turnover_vec_lag.isna(), 'turnover_vec_lag'] = 0\npbp_data.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>EPA</th>\n      <th>ExpScoreDiff</th>\n      <th>ExpScoreDiff_Time_Ratio</th>\n      <th>FG_after</th>\n      <th>FG_before</th>\n      <th>Goal_To_Go</th>\n      <th>Goal_To_Go_end</th>\n      <th>No_Score_after</th>\n      <th>No_Score_before</th>\n      <th>Opp_FG_after</th>\n      <th>Opp_FG_before</th>\n      <th>Opp_Safety_after</th>\n      <th>Opp_Safety_before</th>\n      <th>Opp_TD_after</th>\n      <th>Opp_TD_before</th>\n      <th>Safety_after</th>\n      <th>Safety_before</th>\n      <th>TD_after</th>\n      <th>TD_before</th>\n      <th>TimeSecsRem</th>\n      <th>TimeSecsRem_end</th>\n      <th>Under_three</th>\n      <th>Under_two</th>\n      <th>Under_two_end</th>\n      <th>adj_TimeSecsRem</th>\n      <th>away</th>\n      <th>away_EPA</th>\n      <th>away_EPA_pass</th>\n      <th>away_EPA_rush</th>\n      <th>away_wp_after</th>\n      <th>away_wp_before</th>\n      <th>change_of_pos_team</th>\n      <th>change_of_poss</th>\n      <th>clock.minutes</th>\n      <th>clock.seconds</th>\n      <th>completion</th>\n      <th>completion_player</th>\n      <th>completion_player_id</th>\n      <th>completion_yds</th>\n      <th>def_EPA</th>\n      <th>def_pos_team</th>\n      <th>def_pos_team_score</th>\n      <th>def_pos_team_timeouts</th>\n      <th>def_pos_team_timeouts_rem_before</th>\n      <th>def_timeout_called</th>\n      <th>def_timeouts_rem_before</th>\n      <th>def_wp_after</th>\n      <th>def_wp_before</th>\n      <th>defense_conference</th>\n      <th>defense_play</th>\n      <th>defense_score</th>\n      <th>defense_score_play</th>\n      <th>defense_timeouts</th>\n      <th>distance</th>\n      <th>distance_end</th>\n      <th>down</th>\n      <th>down_end</th>\n      <th>downs_turnover</th>\n      <th>drive_end_period</th>\n      <th>drive_end_yards_to_goal</th>\n      <th>drive_event_number</th>\n      <th>drive_id</th>\n      <th>drive_num</th>\n      <th>drive_number</th>\n      <th>drive_numbers</th>\n      <th>drive_play_number</th>\n      <th>drive_pts</th>\n      <th>drive_result</th>\n      <th>drive_result2</th>\n      <th>drive_result_detailed</th>\n      <th>drive_result_detailed_flag</th>\n      <th>drive_scoring</th>\n      <th>drive_start_period</th>\n      <th>drive_start_yards_to_goal</th>\n      <th>drive_time_minutes_elapsed</th>\n      <th>drive_time_minutes_end</th>\n      <th>drive_time_minutes_start</th>\n      <th>drive_time_seconds_elapsed</th>\n      <th>drive_time_seconds_end</th>\n      <th>drive_time_seconds_start</th>\n      <th>drive_yards</th>\n      <th>end_of_half</th>\n      <th>ep_after</th>\n      <th>ep_before</th>\n      <th>epa_success</th>\n      <th>fg_block_player_name</th>\n      <th>fg_inds</th>\n      <th>fg_kicker_player_name</th>\n      <th>fg_made</th>\n      <th>fg_make_prob</th>\n      <th>fg_return_player_name</th>\n      <th>firstD_by_kickoff</th>\n      <th>firstD_by_penalty</th>\n      <th>firstD_by_poss</th>\n      <th>firstD_by_yards</th>\n      <th>first_by_penalty</th>\n      <th>first_by_yards</th>\n      <th>fumble_forced_player</th>\n      <th>fumble_forced_player_id</th>\n      <th>fumble_forced_player_name</th>\n      <th>fumble_forced_stat</th>\n      <th>fumble_player</th>\n      <th>fumble_player_id</th>\n      <th>fumble_player_name</th>\n      <th>fumble_recovered_player</th>\n      <th>fumble_recovered_player_id</th>\n      <th>fumble_recovered_player_name</th>\n      <th>fumble_recovered_stat</th>\n      <th>fumble_stat</th>\n      <th>fumble_vec</th>\n      <th>game_id</th>\n      <th>game_play_number</th>\n      <th>half</th>\n      <th>half_clock.minutes</th>\n      <th>half_play_number</th>\n      <th>home</th>\n      <th>home_EPA</th>\n      <th>home_EPA_pass</th>\n      <th>home_EPA_rush</th>\n      <th>home_wp_after</th>\n      <th>home_wp_before</th>\n      <th>id_drive</th>\n      <th>id_play</th>\n      <th>incompletion_player</th>\n      <th>incompletion_player_id</th>\n      <th>incompletion_stat</th>\n      <th>int</th>\n      <th>int_td</th>\n      <th>interception_player</th>\n      <th>interception_player_id</th>\n      <th>interception_player_name</th>\n      <th>interception_stat</th>\n      <th>interception_thrown_player</th>\n      <th>interception_thrown_player_id</th>\n      <th>interception_thrown_stat</th>\n      <th>kick_play</th>\n      <th>kickoff_downed</th>\n      <th>kickoff_fair_catch</th>\n      <th>kickoff_onside</th>\n      <th>kickoff_oob</th>\n      <th>kickoff_play</th>\n      <th>kickoff_player_name</th>\n      <th>kickoff_returner_player_name</th>\n      <th>kickoff_safety</th>\n      <th>kickoff_tb</th>\n      <th>lag_change_of_pos_team</th>\n      <th>lag_change_of_pos_team2</th>\n      <th>lag_change_of_poss</th>\n      <th>lag_defense_score_play</th>\n      <th>lag_downs_turnover</th>\n      <th>lag_drive_result_detailed</th>\n      <th>lag_first_by_penalty</th>\n      <th>lag_first_by_penalty2</th>\n      <th>lag_first_by_yards</th>\n      <th>lag_first_by_yards2</th>\n      <th>lag_kickoff_play</th>\n      <th>lag_new_drive_pts</th>\n      <th>lag_play_text</th>\n      <th>lag_play_text2</th>\n      <th>lag_play_type</th>\n      <th>lag_play_type2</th>\n      <th>lag_play_type3</th>\n      <th>lag_pos_team</th>\n      <th>lag_punt</th>\n      <th>lag_punt2</th>\n      <th>lag_scoring_play</th>\n      <th>lag_turnover_vec</th>\n      <th>lead_drive_result_detailed</th>\n      <th>lead_play_text</th>\n      <th>lead_play_type</th>\n      <th>lead_pos_team</th>\n      <th>log_ydstogo</th>\n      <th>log_ydstogo_end</th>\n      <th>middle_8</th>\n      <th>missing_yard_flag</th>\n      <th>net_away_EPA</th>\n      <th>net_away_EPA_pass</th>\n      <th>net_away_EPA_rush</th>\n      <th>net_home_EPA</th>\n      <th>net_home_EPA_pass</th>\n      <th>net_home_EPA_rush</th>\n      <th>new_drive_pts</th>\n      <th>new_id</th>\n      <th>new_series</th>\n      <th>number_of_drives</th>\n      <th>off_timeout_called</th>\n      <th>off_timeouts_rem_before</th>\n      <th>offense_conference</th>\n      <th>offense_play</th>\n      <th>offense_receives_2H_kickoff</th>\n      <th>offense_score</th>\n      <th>offense_score_play</th>\n      <th>offense_timeouts</th>\n      <th>opponent</th>\n      <th>opponent_score</th>\n      <th>orig_drive_number</th>\n      <th>orig_play_type</th>\n      <th>pass</th>\n      <th>pass_attempt</th>\n      <th>pass_breakup_player</th>\n      <th>pass_breakup_player_id</th>\n      <th>pass_breakup_player_name</th>\n      <th>pass_breakup_stat</th>\n      <th>pass_td</th>\n      <th>passer_player_name</th>\n      <th>penalty_1st_conv</th>\n      <th>penalty_declined</th>\n      <th>penalty_detail</th>\n      <th>penalty_flag</th>\n      <th>penalty_no_play</th>\n      <th>penalty_offset</th>\n      <th>penalty_play_text</th>\n      <th>penalty_safety</th>\n      <th>penalty_text</th>\n      <th>period</th>\n      <th>play_after_turnover</th>\n      <th>play_id</th>\n      <th>play_text</th>\n      <th>play_type</th>\n      <th>pos_score_diff</th>\n      <th>pos_score_diff_start</th>\n      <th>pos_score_diff_start_end</th>\n      <th>pos_score_pts</th>\n      <th>pos_team</th>\n      <th>pos_team_receives_2H_kickoff</th>\n      <th>pos_team_score</th>\n      <th>pos_team_timeouts</th>\n      <th>pos_team_timeouts_rem_before</th>\n      <th>position_completion</th>\n      <th>position_fumble</th>\n      <th>position_fumble_forced</th>\n      <th>position_fumble_recovered</th>\n      <th>position_incompletion</th>\n      <th>position_interception</th>\n      <th>position_interception_thrown</th>\n      <th>position_pass_breakup</th>\n      <th>position_reception</th>\n      <th>position_rush</th>\n      <th>position_sack</th>\n      <th>position_sack_taken</th>\n      <th>position_target</th>\n      <th>position_touchdown</th>\n      <th>ppa</th>\n      <th>pts_scored</th>\n      <th>punt</th>\n      <th>punt_block_player_name</th>\n      <th>punt_block_return_player_name</th>\n      <th>punt_blocked</th>\n      <th>punt_downed</th>\n      <th>punt_fair_catch</th>\n      <th>punt_oob</th>\n      <th>punt_play</th>\n      <th>punt_returner_player_name</th>\n      <th>punt_safety</th>\n      <th>punt_tb</th>\n      <th>punter_player_name</th>\n      <th>receiver_player_name</th>\n      <th>receives_2H_kickoff</th>\n      <th>reception_player</th>\n      <th>reception_player_id</th>\n      <th>reception_yds</th>\n      <th>row</th>\n      <th>rush</th>\n      <th>rush_player</th>\n      <th>rush_player_id</th>\n      <th>rush_td</th>\n      <th>rush_yds</th>\n      <th>rusher_player_name</th>\n      <th>rz_play</th>\n      <th>sack</th>\n      <th>sack_player</th>\n      <th>sack_player_id</th>\n      <th>sack_player_name</th>\n      <th>sack_player_name2</th>\n      <th>sack_players</th>\n      <th>sack_stat</th>\n      <th>sack_taken_player</th>\n      <th>sack_taken_player_id</th>\n      <th>sack_taken_stat</th>\n      <th>sack_vec</th>\n      <th>safety</th>\n      <th>score_diff</th>\n      <th>score_diff_start</th>\n      <th>score_pts</th>\n      <th>scoring</th>\n      <th>scoring_opp</th>\n      <th>scoring_play</th>\n      <th>season</th>\n      <th>stuffed_run</th>\n      <th>success</th>\n      <th>target</th>\n      <th>target_player</th>\n      <th>target_player_id</th>\n      <th>target_stat</th>\n      <th>td_play</th>\n      <th>team_score</th>\n      <th>total_away_EPA</th>\n      <th>total_away_EPA_pass</th>\n      <th>total_away_EPA_rush</th>\n      <th>total_home_EPA</th>\n      <th>total_home_EPA_pass</th>\n      <th>total_home_EPA_rush</th>\n      <th>touchdown</th>\n      <th>touchdown_player</th>\n      <th>touchdown_player_id</th>\n      <th>touchdown_stat</th>\n      <th>turnover</th>\n      <th>turnover_indicator</th>\n      <th>turnover_vec</th>\n      <th>turnover_vec_lag</th>\n      <th>week</th>\n      <th>wp_after</th>\n      <th>wp_before</th>\n      <th>wpa</th>\n      <th>yard_line</th>\n      <th>yards_gained</th>\n      <th>yards_to_goal</th>\n      <th>yards_to_goal_end</th>\n      <th>yds_fg</th>\n      <th>yds_fumble_return</th>\n      <th>yds_int_return</th>\n      <th>yds_kickoff</th>\n      <th>yds_kickoff_return</th>\n      <th>yds_penalty</th>\n      <th>yds_punt_gained</th>\n      <th>yds_punt_return</th>\n      <th>yds_punted</th>\n      <th>yds_receiving</th>\n      <th>yds_rushed</th>\n      <th>yds_sacked</th>\n      <th>year</th>\n      <th>winner</th>\n      <th>spread</th>\n      <th>pos_team_spread</th>\n      <th>elapsed_share</th>\n      <th>spread_time</th>\n      <th>is_home</th>\n      <th>win_indicator</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>-0.470573</td>\n      <td>0.833168</td>\n      <td>0.000231</td>\n      <td>0.134882</td>\n      <td>0.170347</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002152</td>\n      <td>0.001775</td>\n      <td>0.121537</td>\n      <td>0.089202</td>\n      <td>0.004375</td>\n      <td>0.001915</td>\n      <td>0.343792</td>\n      <td>0.260404</td>\n      <td>0.002997</td>\n      <td>0.002950</td>\n      <td>0.390266</td>\n      <td>0.473408</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>0.470573</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.528336</td>\n      <td>0.509680</td>\n      <td>0</td>\n      <td>1</td>\n      <td>15</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.470573</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.528336</td>\n      <td>0.509680</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>1</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>0.362595</td>\n      <td>0.833168</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>1</td>\n      <td>1</td>\n      <td>30</td>\n      <td>1</td>\n      <td>East Carolina</td>\n      <td>-0.470573</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.471664</td>\n      <td>0.490320</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Brandon McLaren</td>\n      <td>Isaiah Jones</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Pass Reception</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.941145</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>-0.941145</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849902</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>Kickoff</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>Brandon McLaren kickoff for 51 yds , Isaiah Jo...</td>\n      <td>Kickoff</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.470573</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-0.470573</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0.471664</td>\n      <td>0.490320</td>\n      <td>-0.018655</td>\n      <td>65</td>\n      <td>6</td>\n      <td>65</td>\n      <td>80.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>51.0</td>\n      <td>6.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>-0.168094</td>\n      <td>0.362595</td>\n      <td>0.000101</td>\n      <td>0.128390</td>\n      <td>0.134882</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002141</td>\n      <td>0.002152</td>\n      <td>0.124954</td>\n      <td>0.121537</td>\n      <td>0.003679</td>\n      <td>0.004375</td>\n      <td>0.355615</td>\n      <td>0.343792</td>\n      <td>0.003138</td>\n      <td>0.002997</td>\n      <td>0.382083</td>\n      <td>0.390266</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>0.168094</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.535004</td>\n      <td>0.528336</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>4.0</td>\n      <td>0.168094</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.535004</td>\n      <td>0.528336</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>6.0</td>\n      <td>1.0</td>\n      <td>2.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>2</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>0.194501</td>\n      <td>0.362595</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>2</td>\n      <td>1</td>\n      <td>30</td>\n      <td>2</td>\n      <td>East Carolina</td>\n      <td>-0.168094</td>\n      <td>-0.168094</td>\n      <td>NaN</td>\n      <td>0.464996</td>\n      <td>0.471664</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>Brandon McLaren kickoff for 51 yds , Isaiah Jo...</td>\n      <td>None</td>\n      <td>Kickoff</td>\n      <td>None</td>\n      <td>None</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Pass Reception</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>1.791759</td>\n      <td>False</td>\n      <td>False</td>\n      <td>1.277333</td>\n      <td>0.168094</td>\n      <td>0.0</td>\n      <td>-1.277333</td>\n      <td>-0.168094</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849903</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>North Carolina Central</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Reception</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Pass Reception</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>-0.088432</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Justin Hardy</td>\n      <td>0.0</td>\n      <td>Justin Hardy</td>\n      <td>505407.0</td>\n      <td>4.0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.638667</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-0.638667</td>\n      <td>-0.168094</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.464996</td>\n      <td>0.471664</td>\n      <td>-0.006668</td>\n      <td>20</td>\n      <td>4</td>\n      <td>80</td>\n      <td>76.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>4.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2.283941</td>\n      <td>0.194501</td>\n      <td>0.000054</td>\n      <td>0.190673</td>\n      <td>0.128390</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.001539</td>\n      <td>0.002141</td>\n      <td>0.072094</td>\n      <td>0.124954</td>\n      <td>0.001135</td>\n      <td>0.003679</td>\n      <td>0.214480</td>\n      <td>0.355615</td>\n      <td>0.002843</td>\n      <td>0.003138</td>\n      <td>0.517235</td>\n      <td>0.382083</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>-2.283941</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.445405</td>\n      <td>0.535004</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>20.0</td>\n      <td>-2.283941</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.445405</td>\n      <td>0.535004</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>6.0</td>\n      <td>10.0</td>\n      <td>2.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>3</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>2.478443</td>\n      <td>0.194501</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>3</td>\n      <td>1</td>\n      <td>30</td>\n      <td>3</td>\n      <td>East Carolina</td>\n      <td>2.283941</td>\n      <td>2.283941</td>\n      <td>NaN</td>\n      <td>0.554595</td>\n      <td>0.464996</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Brandon McLaren kickoff for 51 yds , Isaiah Jo...</td>\n      <td>Pass Reception</td>\n      <td>Kickoff</td>\n      <td>None</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass incomplete to Justin Hardy, ...</td>\n      <td>Pass Incompletion</td>\n      <td>East Carolina</td>\n      <td>1.791759</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>-3.290549</td>\n      <td>-2.115847</td>\n      <td>0.0</td>\n      <td>3.290549</td>\n      <td>2.115847</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849904</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>North Carolina Central</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Reception</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Pass Reception</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>2.104307</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Cam Worthy</td>\n      <td>0.0</td>\n      <td>Cam Worthy</td>\n      <td>552953.0</td>\n      <td>20.0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>-1.645275</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.645275</td>\n      <td>2.115847</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.554595</td>\n      <td>0.464996</td>\n      <td>0.089599</td>\n      <td>24</td>\n      <td>20</td>\n      <td>76</td>\n      <td>56.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>20.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>-0.855503</td>\n      <td>2.478443</td>\n      <td>0.000688</td>\n      <td>0.193531</td>\n      <td>0.190673</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.001703</td>\n      <td>0.001539</td>\n      <td>0.087026</td>\n      <td>0.072094</td>\n      <td>0.001516</td>\n      <td>0.001135</td>\n      <td>0.263697</td>\n      <td>0.214480</td>\n      <td>0.003072</td>\n      <td>0.002843</td>\n      <td>0.449456</td>\n      <td>0.517235</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>0.855503</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.478562</td>\n      <td>0.445405</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.855503</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.478562</td>\n      <td>0.445405</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>1.0</td>\n      <td>2.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>4</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>4</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>1.622940</td>\n      <td>2.478443</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>4</td>\n      <td>1</td>\n      <td>30</td>\n      <td>4</td>\n      <td>East Carolina</td>\n      <td>-0.855503</td>\n      <td>-0.855503</td>\n      <td>NaN</td>\n      <td>0.521438</td>\n      <td>0.554595</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Pass Reception</td>\n      <td>Pass Reception</td>\n      <td>Kickoff</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass incomplete to Davon Grayson</td>\n      <td>Pass Incompletion</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>-1.579543</td>\n      <td>-1.260344</td>\n      <td>0.0</td>\n      <td>1.579543</td>\n      <td>1.260344</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849905</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Incompletion</td>\n      <td>1</td>\n      <td>1</td>\n      <td>Michael Jones</td>\n      <td>164873.0</td>\n      <td>Michael Jones</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass incomplete to Justin Hardy, ...</td>\n      <td>Pass Incompletion</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>-1.161247</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Justin Hardy</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>4</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Justin Hardy</td>\n      <td>505407.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>-0.789771</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.789771</td>\n      <td>1.260344</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.521438</td>\n      <td>0.554595</td>\n      <td>-0.033156</td>\n      <td>44</td>\n      <td>0</td>\n      <td>56</td>\n      <td>56.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>-1.130810</td>\n      <td>1.622940</td>\n      <td>0.000451</td>\n      <td>0.185681</td>\n      <td>0.193531</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.001837</td>\n      <td>0.001703</td>\n      <td>0.109427</td>\n      <td>0.087026</td>\n      <td>0.002270</td>\n      <td>0.001516</td>\n      <td>0.329919</td>\n      <td>0.263697</td>\n      <td>0.003745</td>\n      <td>0.003072</td>\n      <td>0.367121</td>\n      <td>0.449456</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>1.130810</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.523197</td>\n      <td>0.478562</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1.130810</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.523197</td>\n      <td>0.478562</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>2.0</td>\n      <td>3.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>5</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>5</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>0.492129</td>\n      <td>1.622940</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>5</td>\n      <td>1</td>\n      <td>30</td>\n      <td>5</td>\n      <td>East Carolina</td>\n      <td>-1.130810</td>\n      <td>-1.130810</td>\n      <td>NaN</td>\n      <td>0.476803</td>\n      <td>0.521438</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Shane Carden pass incomplete to Justin Hardy, ...</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Pass Incompletion</td>\n      <td>Pass Reception</td>\n      <td>Pass Reception</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>EAST CAROLINA Penalty, false start (-5 Yards) ...</td>\n      <td>Penalty</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.682078</td>\n      <td>-0.129534</td>\n      <td>0.0</td>\n      <td>-0.682078</td>\n      <td>0.129534</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849906</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>North Carolina Central</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Incompletion</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass incomplete to Davon Grayson</td>\n      <td>Pass Incompletion</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>-0.881290</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Davon Grayson</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>5</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Davon Grayson</td>\n      <td>552937.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.341039</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-0.341039</td>\n      <td>0.129534</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.476803</td>\n      <td>0.521438</td>\n      <td>-0.044636</td>\n      <td>44</td>\n      <td>0</td>\n      <td>56</td>\n      <td>56.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n      <td>True</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nfiltered_pbp_data = pbp_data[\n    (pbp_data.ep_before.notna())\n    & (pbp_data.score_diff.notna())\n    & (pbp_data.play_type.notna())\n    & (pbp_data.win_indicator.notna())\n    & (pbp_data.off_timeouts_rem_before.notna())\n    & (pbp_data.def_timeouts_rem_before.notna())\n    & (pbp_data.yards_to_goal.notna())\n    & (pbp_data.period <= 4)\n]\n```\n\n\n```python\nspread_nrounds = 760\nspread_params = {\n    \"booster\":\"gbtree\",\n    \"objective\":\"binary:logistic\",\n    \"eval_metric\": [\"logloss\"],\n    \"eta\":0.02,\n    \"gamma\":0.3445502,\n    \"subsample\":0.7204741,\n    \"colsample_bytree\":0.5714286,\n    \"max_depth\":5,\n    \"min_child_weight\":14\n}\nbefore_spread_columns = [\"pos_team_receives_2H_kickoff\",\"spread_time\",\"TimeSecsRem\",\"adj_TimeSecsRem\",\"ExpScoreDiff_Time_Ratio\",\"pos_score_diff_start\",\"down\",\"distance\",\"yards_to_goal\",\"is_home\",\"pos_team_timeouts_rem_before\",\"def_pos_team_timeouts_rem_before\",\"period\"]\nafter_spread_columns = [\"pos_team_receives_2H_kickoff\",\"spread_time_end\",\"TimeSecsRem_end\",\"adj_TimeSecsRem_end\",\"ExpScoreDiff_Time_Ratio_end\",\"pos_score_diff_start_end\",\"down_end\",\"distance_end\",\"yards_to_goal_end\",\"is_home\",\"pos_team_timeouts\",\"def_pos_team_timeouts\",\"period\"]\n\ndtrain_spread = xgb.DMatrix(filtered_pbp_data[before_spread_columns], label=filtered_pbp_data.win_indicator)\ndtrain_spread\n```\n\n\n\n\n    <xgboost.core.DMatrix at 0x7fb6dfd54590>\n\n\n\n\n```python\nwp_model_spread = xgb.train(spread_params, dtrain_spread, num_boost_round=spread_nrounds, verbose_eval=2)\n# save for debug\nwp_model_spread.dump_model('wp_spread_xgb_dump.json', with_stats=True, dump_format='json')\nwp_model_spread.save_model('wp_spread.model')\n```\n\n\n```python\nno_spread_nrounds = 65\nno_spread_params = {\n    \"booster\":\"gbtree\",\n    \"objective\":\"binary:logistic\",\n    \"eval_metric\": [\"logloss\"],\n    \"eta\":0.2,\n    \"gamma\":0,\n    \"subsample\":0.8,\n    \"colsample_bytree\":0.8,\n    \"max_depth\":4,\n    \"min_child_weight\":1\n}\n\nbefore_no_spread_columns = [\"pos_team_receives_2H_kickoff\",\"TimeSecsRem\",\"adj_TimeSecsRem\",\"ExpScoreDiff_Time_Ratio\",\"pos_score_diff_start\",\"down\",\"distance\",\"yards_to_goal\",\"is_home\",\"pos_team_timeouts_rem_before\",\"def_pos_team_timeouts_rem_before\",\"period\"]\nafter_no_spread_columns = [\"pos_team_receives_2H_kickoff\",\"TimeSecsRem_end\",\"adj_TimeSecsRem_end\",\"ExpScoreDiff_Time_Ratio_end\",\"pos_score_diff_start_end\",\"down_end\",\"distance_end\",\"yards_to_goal_end\",\"is_home\",\"pos_team_timeouts\",\"def_pos_team_timeouts\",\"period\"]\n\nno_spread_dtrain = xgb.DMatrix(filtered_pbp_data[before_no_spread_columns], label=filtered_pbp_data.win_indicator)\nno_spread_dtrain\n```\n\n\n\n\n    <xgboost.core.DMatrix at 0x7fb6dfee5a90>\n\n\n\n\n```python\nno_spread_wp_model = xgb.train(no_spread_params, no_spread_dtrain, num_boost_round=no_spread_nrounds, verbose_eval=2)\n# save for debug\nno_spread_wp_model.dump_model('wp_xgb_dump.json', with_stats=True, dump_format='json')\nno_spread_wp_model.save_model('wp_no_spread.model')\n```\n\n\n```python\nwp_model = wp_model_spread\ntarget_file_name = \"CFBSpreadWPA\"\nmodel_columns_before = before_spread_columns\nmodel_columns_after = after_spread_columns\n\nprint(\"MODEL DETAILS:\")\nprint(f\"Filename: {target_file_name}.mlmodel\")\nprint(f\"Using Spread: { 'spread_time' in model_columns_before}\")\nprint(f\"Model Columns: {model_columns_before}\")\n\n```\n\n    MODEL DETAILS:\n    Filename: CFBSpreadWPA.mlmodel\n    Using Spread: True\n    Model Columns: ['pos_team_receives_2H_kickoff', 'spread_time', 'TimeSecsRem', 'adj_TimeSecsRem', 'ExpScoreDiff_Time_Ratio', 'pos_score_diff_start', 'down', 'distance', 'yards_to_goal', 'is_home', 'pos_team_timeouts_rem_before', 'def_pos_team_timeouts_rem_before', 'period']\n\n\n\n```python\n# Test with all data\nbase_data = pbp_data.copy() #pd.read_parquet(\"https://raw.githubusercontent.com/saiemgilani/cfbscrapR-data/master/data/parquet/pbp_players_pos_2020.parquet\")\n# print(base_data.columns.to_list())\n\n# games_2020 = retrieveCfbDataFile('games', 2020)\n# games_2020['game_id'] = games_2020['\u00ef\u00bb\u00bfid']\n# games_2020['year'] = 2020\n# games_2020 = games_2020[games_2020.home_points != games_2020.away_points]\n# games_2020['winner'] = np.where(games_2020.home_points > games_2020.away_points, games_2020.home_team, games_2020.away_team)\n\n# spread_2020 = retrieveCfbDataFile('lines', 2020)\n# spread_2020 = spread_2020[spread_2020.lineProvider == \"consensus\"]\n# spread_2020['spread'] = -1 * spread_2020.spread # spread is negative for home favorite; positive for away favorite, but NFLfastR uses \"(how many points home team was favored by) for this\"\n# spread_2020['game_id'] = spread_2020['\u00ef\u00bb\u00bfid']\n# spread_2020['year'] = 2020\n# base_data = pd.merge(base_data, spread_2020[['game_id','spread']], left_on=\"game_id\", right_on=\"game_id\")\n# base_data = pd.merge(base_data, games_2020[['game_id','winner']], left_on=\"game_id\", right_on=\"game_id\")\nbase_data.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>EPA</th>\n      <th>ExpScoreDiff</th>\n      <th>ExpScoreDiff_Time_Ratio</th>\n      <th>FG_after</th>\n      <th>FG_before</th>\n      <th>Goal_To_Go</th>\n      <th>Goal_To_Go_end</th>\n      <th>No_Score_after</th>\n      <th>No_Score_before</th>\n      <th>Opp_FG_after</th>\n      <th>Opp_FG_before</th>\n      <th>Opp_Safety_after</th>\n      <th>Opp_Safety_before</th>\n      <th>Opp_TD_after</th>\n      <th>Opp_TD_before</th>\n      <th>Safety_after</th>\n      <th>Safety_before</th>\n      <th>TD_after</th>\n      <th>TD_before</th>\n      <th>TimeSecsRem</th>\n      <th>TimeSecsRem_end</th>\n      <th>Under_three</th>\n      <th>Under_two</th>\n      <th>Under_two_end</th>\n      <th>adj_TimeSecsRem</th>\n      <th>away</th>\n      <th>away_EPA</th>\n      <th>away_EPA_pass</th>\n      <th>away_EPA_rush</th>\n      <th>away_wp_after</th>\n      <th>away_wp_before</th>\n      <th>change_of_pos_team</th>\n      <th>change_of_poss</th>\n      <th>clock.minutes</th>\n      <th>clock.seconds</th>\n      <th>completion</th>\n      <th>completion_player</th>\n      <th>completion_player_id</th>\n      <th>completion_yds</th>\n      <th>def_EPA</th>\n      <th>def_pos_team</th>\n      <th>def_pos_team_score</th>\n      <th>def_pos_team_timeouts</th>\n      <th>def_pos_team_timeouts_rem_before</th>\n      <th>def_timeout_called</th>\n      <th>def_timeouts_rem_before</th>\n      <th>def_wp_after</th>\n      <th>def_wp_before</th>\n      <th>defense_conference</th>\n      <th>defense_play</th>\n      <th>defense_score</th>\n      <th>defense_score_play</th>\n      <th>defense_timeouts</th>\n      <th>distance</th>\n      <th>distance_end</th>\n      <th>down</th>\n      <th>down_end</th>\n      <th>downs_turnover</th>\n      <th>drive_end_period</th>\n      <th>drive_end_yards_to_goal</th>\n      <th>drive_event_number</th>\n      <th>drive_id</th>\n      <th>drive_num</th>\n      <th>drive_number</th>\n      <th>drive_numbers</th>\n      <th>drive_play_number</th>\n      <th>drive_pts</th>\n      <th>drive_result</th>\n      <th>drive_result2</th>\n      <th>drive_result_detailed</th>\n      <th>drive_result_detailed_flag</th>\n      <th>drive_scoring</th>\n      <th>drive_start_period</th>\n      <th>drive_start_yards_to_goal</th>\n      <th>drive_time_minutes_elapsed</th>\n      <th>drive_time_minutes_end</th>\n      <th>drive_time_minutes_start</th>\n      <th>drive_time_seconds_elapsed</th>\n      <th>drive_time_seconds_end</th>\n      <th>drive_time_seconds_start</th>\n      <th>drive_yards</th>\n      <th>end_of_half</th>\n      <th>ep_after</th>\n      <th>ep_before</th>\n      <th>epa_success</th>\n      <th>fg_block_player_name</th>\n      <th>fg_inds</th>\n      <th>fg_kicker_player_name</th>\n      <th>fg_made</th>\n      <th>fg_make_prob</th>\n      <th>fg_return_player_name</th>\n      <th>firstD_by_kickoff</th>\n      <th>firstD_by_penalty</th>\n      <th>firstD_by_poss</th>\n      <th>firstD_by_yards</th>\n      <th>first_by_penalty</th>\n      <th>first_by_yards</th>\n      <th>fumble_forced_player</th>\n      <th>fumble_forced_player_id</th>\n      <th>fumble_forced_player_name</th>\n      <th>fumble_forced_stat</th>\n      <th>fumble_player</th>\n      <th>fumble_player_id</th>\n      <th>fumble_player_name</th>\n      <th>fumble_recovered_player</th>\n      <th>fumble_recovered_player_id</th>\n      <th>fumble_recovered_player_name</th>\n      <th>fumble_recovered_stat</th>\n      <th>fumble_stat</th>\n      <th>fumble_vec</th>\n      <th>game_id</th>\n      <th>game_play_number</th>\n      <th>half</th>\n      <th>half_clock.minutes</th>\n      <th>half_play_number</th>\n      <th>home</th>\n      <th>home_EPA</th>\n      <th>home_EPA_pass</th>\n      <th>home_EPA_rush</th>\n      <th>home_wp_after</th>\n      <th>home_wp_before</th>\n      <th>id_drive</th>\n      <th>id_play</th>\n      <th>incompletion_player</th>\n      <th>incompletion_player_id</th>\n      <th>incompletion_stat</th>\n      <th>int</th>\n      <th>int_td</th>\n      <th>interception_player</th>\n      <th>interception_player_id</th>\n      <th>interception_player_name</th>\n      <th>interception_stat</th>\n      <th>interception_thrown_player</th>\n      <th>interception_thrown_player_id</th>\n      <th>interception_thrown_stat</th>\n      <th>kick_play</th>\n      <th>kickoff_downed</th>\n      <th>kickoff_fair_catch</th>\n      <th>kickoff_onside</th>\n      <th>kickoff_oob</th>\n      <th>kickoff_play</th>\n      <th>kickoff_player_name</th>\n      <th>kickoff_returner_player_name</th>\n      <th>kickoff_safety</th>\n      <th>kickoff_tb</th>\n      <th>lag_change_of_pos_team</th>\n      <th>lag_change_of_pos_team2</th>\n      <th>lag_change_of_poss</th>\n      <th>lag_defense_score_play</th>\n      <th>lag_downs_turnover</th>\n      <th>lag_drive_result_detailed</th>\n      <th>lag_first_by_penalty</th>\n      <th>lag_first_by_penalty2</th>\n      <th>lag_first_by_yards</th>\n      <th>lag_first_by_yards2</th>\n      <th>lag_kickoff_play</th>\n      <th>lag_new_drive_pts</th>\n      <th>lag_play_text</th>\n      <th>lag_play_text2</th>\n      <th>lag_play_type</th>\n      <th>lag_play_type2</th>\n      <th>lag_play_type3</th>\n      <th>lag_pos_team</th>\n      <th>lag_punt</th>\n      <th>lag_punt2</th>\n      <th>lag_scoring_play</th>\n      <th>lag_turnover_vec</th>\n      <th>lead_drive_result_detailed</th>\n      <th>lead_play_text</th>\n      <th>lead_play_type</th>\n      <th>lead_pos_team</th>\n      <th>log_ydstogo</th>\n      <th>log_ydstogo_end</th>\n      <th>middle_8</th>\n      <th>missing_yard_flag</th>\n      <th>net_away_EPA</th>\n      <th>net_away_EPA_pass</th>\n      <th>net_away_EPA_rush</th>\n      <th>net_home_EPA</th>\n      <th>net_home_EPA_pass</th>\n      <th>net_home_EPA_rush</th>\n      <th>new_drive_pts</th>\n      <th>new_id</th>\n      <th>new_series</th>\n      <th>number_of_drives</th>\n      <th>off_timeout_called</th>\n      <th>off_timeouts_rem_before</th>\n      <th>offense_conference</th>\n      <th>offense_play</th>\n      <th>offense_receives_2H_kickoff</th>\n      <th>offense_score</th>\n      <th>offense_score_play</th>\n      <th>offense_timeouts</th>\n      <th>opponent</th>\n      <th>opponent_score</th>\n      <th>orig_drive_number</th>\n      <th>orig_play_type</th>\n      <th>pass</th>\n      <th>pass_attempt</th>\n      <th>pass_breakup_player</th>\n      <th>pass_breakup_player_id</th>\n      <th>pass_breakup_player_name</th>\n      <th>pass_breakup_stat</th>\n      <th>pass_td</th>\n      <th>passer_player_name</th>\n      <th>penalty_1st_conv</th>\n      <th>penalty_declined</th>\n      <th>penalty_detail</th>\n      <th>penalty_flag</th>\n      <th>penalty_no_play</th>\n      <th>penalty_offset</th>\n      <th>penalty_play_text</th>\n      <th>penalty_safety</th>\n      <th>penalty_text</th>\n      <th>period</th>\n      <th>play_after_turnover</th>\n      <th>play_id</th>\n      <th>play_text</th>\n      <th>play_type</th>\n      <th>pos_score_diff</th>\n      <th>pos_score_diff_start</th>\n      <th>pos_score_diff_start_end</th>\n      <th>pos_score_pts</th>\n      <th>pos_team</th>\n      <th>pos_team_receives_2H_kickoff</th>\n      <th>pos_team_score</th>\n      <th>pos_team_timeouts</th>\n      <th>pos_team_timeouts_rem_before</th>\n      <th>position_completion</th>\n      <th>position_fumble</th>\n      <th>position_fumble_forced</th>\n      <th>position_fumble_recovered</th>\n      <th>position_incompletion</th>\n      <th>position_interception</th>\n      <th>position_interception_thrown</th>\n      <th>position_pass_breakup</th>\n      <th>position_reception</th>\n      <th>position_rush</th>\n      <th>position_sack</th>\n      <th>position_sack_taken</th>\n      <th>position_target</th>\n      <th>position_touchdown</th>\n      <th>ppa</th>\n      <th>pts_scored</th>\n      <th>punt</th>\n      <th>punt_block_player_name</th>\n      <th>punt_block_return_player_name</th>\n      <th>punt_blocked</th>\n      <th>punt_downed</th>\n      <th>punt_fair_catch</th>\n      <th>punt_oob</th>\n      <th>punt_play</th>\n      <th>punt_returner_player_name</th>\n      <th>punt_safety</th>\n      <th>punt_tb</th>\n      <th>punter_player_name</th>\n      <th>receiver_player_name</th>\n      <th>receives_2H_kickoff</th>\n      <th>reception_player</th>\n      <th>reception_player_id</th>\n      <th>reception_yds</th>\n      <th>row</th>\n      <th>rush</th>\n      <th>rush_player</th>\n      <th>rush_player_id</th>\n      <th>rush_td</th>\n      <th>rush_yds</th>\n      <th>rusher_player_name</th>\n      <th>rz_play</th>\n      <th>sack</th>\n      <th>sack_player</th>\n      <th>sack_player_id</th>\n      <th>sack_player_name</th>\n      <th>sack_player_name2</th>\n      <th>sack_players</th>\n      <th>sack_stat</th>\n      <th>sack_taken_player</th>\n      <th>sack_taken_player_id</th>\n      <th>sack_taken_stat</th>\n      <th>sack_vec</th>\n      <th>safety</th>\n      <th>score_diff</th>\n      <th>score_diff_start</th>\n      <th>score_pts</th>\n      <th>scoring</th>\n      <th>scoring_opp</th>\n      <th>scoring_play</th>\n      <th>season</th>\n      <th>stuffed_run</th>\n      <th>success</th>\n      <th>target</th>\n      <th>target_player</th>\n      <th>target_player_id</th>\n      <th>target_stat</th>\n      <th>td_play</th>\n      <th>team_score</th>\n      <th>total_away_EPA</th>\n      <th>total_away_EPA_pass</th>\n      <th>total_away_EPA_rush</th>\n      <th>total_home_EPA</th>\n      <th>total_home_EPA_pass</th>\n      <th>total_home_EPA_rush</th>\n      <th>touchdown</th>\n      <th>touchdown_player</th>\n      <th>touchdown_player_id</th>\n      <th>touchdown_stat</th>\n      <th>turnover</th>\n      <th>turnover_indicator</th>\n      <th>turnover_vec</th>\n      <th>turnover_vec_lag</th>\n      <th>week</th>\n      <th>wp_after</th>\n      <th>wp_before</th>\n      <th>wpa</th>\n      <th>yard_line</th>\n      <th>yards_gained</th>\n      <th>yards_to_goal</th>\n      <th>yards_to_goal_end</th>\n      <th>yds_fg</th>\n      <th>yds_fumble_return</th>\n      <th>yds_int_return</th>\n      <th>yds_kickoff</th>\n      <th>yds_kickoff_return</th>\n      <th>yds_penalty</th>\n      <th>yds_punt_gained</th>\n      <th>yds_punt_return</th>\n      <th>yds_punted</th>\n      <th>yds_receiving</th>\n      <th>yds_rushed</th>\n      <th>yds_sacked</th>\n      <th>year</th>\n      <th>winner</th>\n      <th>spread</th>\n      <th>pos_team_spread</th>\n      <th>elapsed_share</th>\n      <th>spread_time</th>\n      <th>is_home</th>\n      <th>win_indicator</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>-0.470573</td>\n      <td>0.833168</td>\n      <td>0.000231</td>\n      <td>0.134882</td>\n      <td>0.170347</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002152</td>\n      <td>0.001775</td>\n      <td>0.121537</td>\n      <td>0.089202</td>\n      <td>0.004375</td>\n      <td>0.001915</td>\n      <td>0.343792</td>\n      <td>0.260404</td>\n      <td>0.002997</td>\n      <td>0.002950</td>\n      <td>0.390266</td>\n      <td>0.473408</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>0.470573</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.528336</td>\n      <td>0.509680</td>\n      <td>0</td>\n      <td>1</td>\n      <td>15</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.470573</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.528336</td>\n      <td>0.509680</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>1</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>0.362595</td>\n      <td>0.833168</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>1</td>\n      <td>1</td>\n      <td>30</td>\n      <td>1</td>\n      <td>East Carolina</td>\n      <td>-0.470573</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.471664</td>\n      <td>0.490320</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Brandon McLaren</td>\n      <td>Isaiah Jones</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Pass Reception</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.941145</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>-0.941145</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849902</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>Kickoff</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>Brandon McLaren kickoff for 51 yds , Isaiah Jo...</td>\n      <td>Kickoff</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.470573</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-0.470573</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0.471664</td>\n      <td>0.490320</td>\n      <td>-0.018655</td>\n      <td>65</td>\n      <td>6</td>\n      <td>65</td>\n      <td>80.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>51.0</td>\n      <td>6.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>-0.168094</td>\n      <td>0.362595</td>\n      <td>0.000101</td>\n      <td>0.128390</td>\n      <td>0.134882</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002141</td>\n      <td>0.002152</td>\n      <td>0.124954</td>\n      <td>0.121537</td>\n      <td>0.003679</td>\n      <td>0.004375</td>\n      <td>0.355615</td>\n      <td>0.343792</td>\n      <td>0.003138</td>\n      <td>0.002997</td>\n      <td>0.382083</td>\n      <td>0.390266</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>0.168094</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.535004</td>\n      <td>0.528336</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>4.0</td>\n      <td>0.168094</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.535004</td>\n      <td>0.528336</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>6.0</td>\n      <td>1.0</td>\n      <td>2.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>2</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>0.194501</td>\n      <td>0.362595</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>2</td>\n      <td>1</td>\n      <td>30</td>\n      <td>2</td>\n      <td>East Carolina</td>\n      <td>-0.168094</td>\n      <td>-0.168094</td>\n      <td>NaN</td>\n      <td>0.464996</td>\n      <td>0.471664</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>Brandon McLaren kickoff for 51 yds , Isaiah Jo...</td>\n      <td>None</td>\n      <td>Kickoff</td>\n      <td>None</td>\n      <td>None</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Pass Reception</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>1.791759</td>\n      <td>False</td>\n      <td>False</td>\n      <td>1.277333</td>\n      <td>0.168094</td>\n      <td>0.0</td>\n      <td>-1.277333</td>\n      <td>-0.168094</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849903</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>North Carolina Central</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Reception</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Pass Reception</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>-0.088432</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Justin Hardy</td>\n      <td>0.0</td>\n      <td>Justin Hardy</td>\n      <td>505407.0</td>\n      <td>4.0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.638667</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-0.638667</td>\n      <td>-0.168094</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.464996</td>\n      <td>0.471664</td>\n      <td>-0.006668</td>\n      <td>20</td>\n      <td>4</td>\n      <td>80</td>\n      <td>76.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>4.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2.283941</td>\n      <td>0.194501</td>\n      <td>0.000054</td>\n      <td>0.190673</td>\n      <td>0.128390</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.001539</td>\n      <td>0.002141</td>\n      <td>0.072094</td>\n      <td>0.124954</td>\n      <td>0.001135</td>\n      <td>0.003679</td>\n      <td>0.214480</td>\n      <td>0.355615</td>\n      <td>0.002843</td>\n      <td>0.003138</td>\n      <td>0.517235</td>\n      <td>0.382083</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>-2.283941</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.445405</td>\n      <td>0.535004</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>20.0</td>\n      <td>-2.283941</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.445405</td>\n      <td>0.535004</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>6.0</td>\n      <td>10.0</td>\n      <td>2.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>3</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>2.478443</td>\n      <td>0.194501</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>3</td>\n      <td>1</td>\n      <td>30</td>\n      <td>3</td>\n      <td>East Carolina</td>\n      <td>2.283941</td>\n      <td>2.283941</td>\n      <td>NaN</td>\n      <td>0.554595</td>\n      <td>0.464996</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Brandon McLaren kickoff for 51 yds , Isaiah Jo...</td>\n      <td>Pass Reception</td>\n      <td>Kickoff</td>\n      <td>None</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass incomplete to Justin Hardy, ...</td>\n      <td>Pass Incompletion</td>\n      <td>East Carolina</td>\n      <td>1.791759</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>-3.290549</td>\n      <td>-2.115847</td>\n      <td>0.0</td>\n      <td>3.290549</td>\n      <td>2.115847</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849904</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>North Carolina Central</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Reception</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Pass Reception</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>2.104307</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Cam Worthy</td>\n      <td>0.0</td>\n      <td>Cam Worthy</td>\n      <td>552953.0</td>\n      <td>20.0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>-1.645275</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.645275</td>\n      <td>2.115847</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.554595</td>\n      <td>0.464996</td>\n      <td>0.089599</td>\n      <td>24</td>\n      <td>20</td>\n      <td>76</td>\n      <td>56.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>20.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>-0.855503</td>\n      <td>2.478443</td>\n      <td>0.000688</td>\n      <td>0.193531</td>\n      <td>0.190673</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.001703</td>\n      <td>0.001539</td>\n      <td>0.087026</td>\n      <td>0.072094</td>\n      <td>0.001516</td>\n      <td>0.001135</td>\n      <td>0.263697</td>\n      <td>0.214480</td>\n      <td>0.003072</td>\n      <td>0.002843</td>\n      <td>0.449456</td>\n      <td>0.517235</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>0.855503</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.478562</td>\n      <td>0.445405</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.855503</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.478562</td>\n      <td>0.445405</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>1.0</td>\n      <td>2.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>4</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>4</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>1.622940</td>\n      <td>2.478443</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>4</td>\n      <td>1</td>\n      <td>30</td>\n      <td>4</td>\n      <td>East Carolina</td>\n      <td>-0.855503</td>\n      <td>-0.855503</td>\n      <td>NaN</td>\n      <td>0.521438</td>\n      <td>0.554595</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Pass Reception</td>\n      <td>Pass Reception</td>\n      <td>Kickoff</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass incomplete to Davon Grayson</td>\n      <td>Pass Incompletion</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>-1.579543</td>\n      <td>-1.260344</td>\n      <td>0.0</td>\n      <td>1.579543</td>\n      <td>1.260344</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849905</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Incompletion</td>\n      <td>1</td>\n      <td>1</td>\n      <td>Michael Jones</td>\n      <td>164873.0</td>\n      <td>Michael Jones</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass incomplete to Justin Hardy, ...</td>\n      <td>Pass Incompletion</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>-1.161247</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Justin Hardy</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>4</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Justin Hardy</td>\n      <td>505407.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>-0.789771</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.789771</td>\n      <td>1.260344</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.521438</td>\n      <td>0.554595</td>\n      <td>-0.033156</td>\n      <td>44</td>\n      <td>0</td>\n      <td>56</td>\n      <td>56.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>-1.130810</td>\n      <td>1.622940</td>\n      <td>0.000451</td>\n      <td>0.185681</td>\n      <td>0.193531</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.001837</td>\n      <td>0.001703</td>\n      <td>0.109427</td>\n      <td>0.087026</td>\n      <td>0.002270</td>\n      <td>0.001516</td>\n      <td>0.329919</td>\n      <td>0.263697</td>\n      <td>0.003745</td>\n      <td>0.003072</td>\n      <td>0.367121</td>\n      <td>0.449456</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>1.130810</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.523197</td>\n      <td>0.478562</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1.130810</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.523197</td>\n      <td>0.478562</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>2.0</td>\n      <td>3.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>5</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>5</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>0.492129</td>\n      <td>1.622940</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>5</td>\n      <td>1</td>\n      <td>30</td>\n      <td>5</td>\n      <td>East Carolina</td>\n      <td>-1.130810</td>\n      <td>-1.130810</td>\n      <td>NaN</td>\n      <td>0.476803</td>\n      <td>0.521438</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Shane Carden pass incomplete to Justin Hardy, ...</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Pass Incompletion</td>\n      <td>Pass Reception</td>\n      <td>Pass Reception</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>EAST CAROLINA Penalty, false start (-5 Yards) ...</td>\n      <td>Penalty</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.682078</td>\n      <td>-0.129534</td>\n      <td>0.0</td>\n      <td>-0.682078</td>\n      <td>0.129534</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849906</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>North Carolina Central</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Incompletion</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass incomplete to Davon Grayson</td>\n      <td>Pass Incompletion</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>-0.881290</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Davon Grayson</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>5</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Davon Grayson</td>\n      <td>552937.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.341039</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-0.341039</td>\n      <td>0.129534</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.476803</td>\n      <td>0.521438</td>\n      <td>-0.044636</td>\n      <td>44</td>\n      <td>0</td>\n      <td>56</td>\n      <td>56.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n      <td>True</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nbase_data[base_data.down_end.isna()].play_type.value_counts()\n```\n\n\n\n\n    End Period                       10801\n    End of Half                       4716\n    End of Game                       3119\n    Rush                              1158\n    Pass Incompletion                  378\n    Pass Reception                     313\n    Rushing Touchdown                  158\n    Timeout                            156\n    Passing Touchdown                  155\n    Penalty                            127\n    Field Goal Good                    121\n    Sack                                55\n    Field Goal Missed                   46\n    Interception Return                 34\n    Fumble Recovery (Own)               16\n    Fumble Recovery (Opponent)          14\n    Blocked Field Goal                   5\n    Uncategorized                        3\n    Fumble Return Touchdown              2\n    Defensive 2pt Conversion             2\n    Interception Return Touchdown        1\n    Two Point Rush                       1\n    Coin Toss                            1\n    Name: play_type, dtype: int64\n\n\n\n\n```python\nbase_data['win_indicator'] = np.where(base_data.pos_team == base_data.winner, 1, 0)\nbase_data['ExpScoreDiff_end'] = base_data.score_diff_start + base_data.ep_after\nbase_data['adj_TimeSecsRem_end'] = np.where(base_data.half == 1, 1800 + base_data.adj_TimeSecsRem, base_data.adj_TimeSecsRem)\nbase_data['ExpScoreDiff_Time_Ratio_end'] = base_data.ExpScoreDiff_end / (base_data.adj_TimeSecsRem_end + 1)\nbase_data['pos_team_spread'] = np.where(base_data.pos_team == base_data.home, base_data.spread, -1 * base_data.spread)\nbase_data['elapsed_share'] = (3600 - base_data.adj_TimeSecsRem) / 3600\nbase_data['elapsed_share_end'] = (3600 - base_data.adj_TimeSecsRem_end) / 3600\nbase_data['spread_time'] = base_data.pos_team_spread * np.exp(-4 * base_data.elapsed_share)\nbase_data['spread_time_end'] = base_data.pos_team_spread * np.exp(-4 * base_data.elapsed_share_end)\nbase_data['is_home'] = np.where(base_data.pos_team == base_data.home, 1, 0)\nbase_data.head()\n\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>EPA</th>\n      <th>ExpScoreDiff</th>\n      <th>ExpScoreDiff_Time_Ratio</th>\n      <th>FG_after</th>\n      <th>FG_before</th>\n      <th>Goal_To_Go</th>\n      <th>Goal_To_Go_end</th>\n      <th>No_Score_after</th>\n      <th>No_Score_before</th>\n      <th>Opp_FG_after</th>\n      <th>Opp_FG_before</th>\n      <th>Opp_Safety_after</th>\n      <th>Opp_Safety_before</th>\n      <th>Opp_TD_after</th>\n      <th>Opp_TD_before</th>\n      <th>Safety_after</th>\n      <th>Safety_before</th>\n      <th>TD_after</th>\n      <th>TD_before</th>\n      <th>TimeSecsRem</th>\n      <th>TimeSecsRem_end</th>\n      <th>Under_three</th>\n      <th>Under_two</th>\n      <th>Under_two_end</th>\n      <th>adj_TimeSecsRem</th>\n      <th>away</th>\n      <th>away_EPA</th>\n      <th>away_EPA_pass</th>\n      <th>away_EPA_rush</th>\n      <th>away_wp_after</th>\n      <th>away_wp_before</th>\n      <th>change_of_pos_team</th>\n      <th>change_of_poss</th>\n      <th>clock.minutes</th>\n      <th>clock.seconds</th>\n      <th>completion</th>\n      <th>completion_player</th>\n      <th>completion_player_id</th>\n      <th>completion_yds</th>\n      <th>def_EPA</th>\n      <th>def_pos_team</th>\n      <th>def_pos_team_score</th>\n      <th>def_pos_team_timeouts</th>\n      <th>def_pos_team_timeouts_rem_before</th>\n      <th>def_timeout_called</th>\n      <th>def_timeouts_rem_before</th>\n      <th>def_wp_after</th>\n      <th>def_wp_before</th>\n      <th>defense_conference</th>\n      <th>defense_play</th>\n      <th>defense_score</th>\n      <th>defense_score_play</th>\n      <th>defense_timeouts</th>\n      <th>distance</th>\n      <th>distance_end</th>\n      <th>down</th>\n      <th>down_end</th>\n      <th>downs_turnover</th>\n      <th>drive_end_period</th>\n      <th>drive_end_yards_to_goal</th>\n      <th>drive_event_number</th>\n      <th>drive_id</th>\n      <th>drive_num</th>\n      <th>drive_number</th>\n      <th>drive_numbers</th>\n      <th>drive_play_number</th>\n      <th>drive_pts</th>\n      <th>drive_result</th>\n      <th>drive_result2</th>\n      <th>drive_result_detailed</th>\n      <th>drive_result_detailed_flag</th>\n      <th>drive_scoring</th>\n      <th>drive_start_period</th>\n      <th>drive_start_yards_to_goal</th>\n      <th>drive_time_minutes_elapsed</th>\n      <th>drive_time_minutes_end</th>\n      <th>drive_time_minutes_start</th>\n      <th>drive_time_seconds_elapsed</th>\n      <th>drive_time_seconds_end</th>\n      <th>drive_time_seconds_start</th>\n      <th>drive_yards</th>\n      <th>end_of_half</th>\n      <th>ep_after</th>\n      <th>ep_before</th>\n      <th>epa_success</th>\n      <th>fg_block_player_name</th>\n      <th>fg_inds</th>\n      <th>fg_kicker_player_name</th>\n      <th>fg_made</th>\n      <th>fg_make_prob</th>\n      <th>fg_return_player_name</th>\n      <th>firstD_by_kickoff</th>\n      <th>firstD_by_penalty</th>\n      <th>firstD_by_poss</th>\n      <th>firstD_by_yards</th>\n      <th>first_by_penalty</th>\n      <th>first_by_yards</th>\n      <th>fumble_forced_player</th>\n      <th>fumble_forced_player_id</th>\n      <th>fumble_forced_player_name</th>\n      <th>fumble_forced_stat</th>\n      <th>fumble_player</th>\n      <th>fumble_player_id</th>\n      <th>fumble_player_name</th>\n      <th>fumble_recovered_player</th>\n      <th>fumble_recovered_player_id</th>\n      <th>fumble_recovered_player_name</th>\n      <th>fumble_recovered_stat</th>\n      <th>fumble_stat</th>\n      <th>fumble_vec</th>\n      <th>game_id</th>\n      <th>game_play_number</th>\n      <th>half</th>\n      <th>half_clock.minutes</th>\n      <th>half_play_number</th>\n      <th>home</th>\n      <th>home_EPA</th>\n      <th>home_EPA_pass</th>\n      <th>home_EPA_rush</th>\n      <th>home_wp_after</th>\n      <th>home_wp_before</th>\n      <th>id_drive</th>\n      <th>id_play</th>\n      <th>incompletion_player</th>\n      <th>incompletion_player_id</th>\n      <th>incompletion_stat</th>\n      <th>int</th>\n      <th>int_td</th>\n      <th>interception_player</th>\n      <th>interception_player_id</th>\n      <th>interception_player_name</th>\n      <th>interception_stat</th>\n      <th>interception_thrown_player</th>\n      <th>interception_thrown_player_id</th>\n      <th>interception_thrown_stat</th>\n      <th>kick_play</th>\n      <th>kickoff_downed</th>\n      <th>kickoff_fair_catch</th>\n      <th>kickoff_onside</th>\n      <th>kickoff_oob</th>\n      <th>kickoff_play</th>\n      <th>kickoff_player_name</th>\n      <th>kickoff_returner_player_name</th>\n      <th>kickoff_safety</th>\n      <th>kickoff_tb</th>\n      <th>lag_change_of_pos_team</th>\n      <th>lag_change_of_pos_team2</th>\n      <th>lag_change_of_poss</th>\n      <th>lag_defense_score_play</th>\n      <th>lag_downs_turnover</th>\n      <th>lag_drive_result_detailed</th>\n      <th>lag_first_by_penalty</th>\n      <th>lag_first_by_penalty2</th>\n      <th>lag_first_by_yards</th>\n      <th>lag_first_by_yards2</th>\n      <th>lag_kickoff_play</th>\n      <th>lag_new_drive_pts</th>\n      <th>lag_play_text</th>\n      <th>lag_play_text2</th>\n      <th>lag_play_type</th>\n      <th>lag_play_type2</th>\n      <th>lag_play_type3</th>\n      <th>lag_pos_team</th>\n      <th>lag_punt</th>\n      <th>lag_punt2</th>\n      <th>lag_scoring_play</th>\n      <th>lag_turnover_vec</th>\n      <th>lead_drive_result_detailed</th>\n      <th>lead_play_text</th>\n      <th>lead_play_type</th>\n      <th>lead_pos_team</th>\n      <th>log_ydstogo</th>\n      <th>log_ydstogo_end</th>\n      <th>middle_8</th>\n      <th>missing_yard_flag</th>\n      <th>net_away_EPA</th>\n      <th>net_away_EPA_pass</th>\n      <th>net_away_EPA_rush</th>\n      <th>net_home_EPA</th>\n      <th>net_home_EPA_pass</th>\n      <th>net_home_EPA_rush</th>\n      <th>new_drive_pts</th>\n      <th>new_id</th>\n      <th>new_series</th>\n      <th>number_of_drives</th>\n      <th>off_timeout_called</th>\n      <th>off_timeouts_rem_before</th>\n      <th>offense_conference</th>\n      <th>offense_play</th>\n      <th>offense_receives_2H_kickoff</th>\n      <th>offense_score</th>\n      <th>offense_score_play</th>\n      <th>offense_timeouts</th>\n      <th>opponent</th>\n      <th>opponent_score</th>\n      <th>orig_drive_number</th>\n      <th>orig_play_type</th>\n      <th>pass</th>\n      <th>pass_attempt</th>\n      <th>pass_breakup_player</th>\n      <th>pass_breakup_player_id</th>\n      <th>pass_breakup_player_name</th>\n      <th>pass_breakup_stat</th>\n      <th>pass_td</th>\n      <th>passer_player_name</th>\n      <th>penalty_1st_conv</th>\n      <th>penalty_declined</th>\n      <th>penalty_detail</th>\n      <th>penalty_flag</th>\n      <th>penalty_no_play</th>\n      <th>penalty_offset</th>\n      <th>penalty_play_text</th>\n      <th>penalty_safety</th>\n      <th>penalty_text</th>\n      <th>period</th>\n      <th>play_after_turnover</th>\n      <th>play_id</th>\n      <th>play_text</th>\n      <th>play_type</th>\n      <th>pos_score_diff</th>\n      <th>pos_score_diff_start</th>\n      <th>pos_score_diff_start_end</th>\n      <th>pos_score_pts</th>\n      <th>pos_team</th>\n      <th>pos_team_receives_2H_kickoff</th>\n      <th>pos_team_score</th>\n      <th>pos_team_timeouts</th>\n      <th>pos_team_timeouts_rem_before</th>\n      <th>position_completion</th>\n      <th>position_fumble</th>\n      <th>position_fumble_forced</th>\n      <th>position_fumble_recovered</th>\n      <th>position_incompletion</th>\n      <th>position_interception</th>\n      <th>position_interception_thrown</th>\n      <th>position_pass_breakup</th>\n      <th>position_reception</th>\n      <th>position_rush</th>\n      <th>position_sack</th>\n      <th>position_sack_taken</th>\n      <th>position_target</th>\n      <th>position_touchdown</th>\n      <th>ppa</th>\n      <th>pts_scored</th>\n      <th>punt</th>\n      <th>punt_block_player_name</th>\n      <th>punt_block_return_player_name</th>\n      <th>punt_blocked</th>\n      <th>punt_downed</th>\n      <th>punt_fair_catch</th>\n      <th>punt_oob</th>\n      <th>punt_play</th>\n      <th>punt_returner_player_name</th>\n      <th>punt_safety</th>\n      <th>punt_tb</th>\n      <th>punter_player_name</th>\n      <th>receiver_player_name</th>\n      <th>receives_2H_kickoff</th>\n      <th>reception_player</th>\n      <th>reception_player_id</th>\n      <th>reception_yds</th>\n      <th>row</th>\n      <th>rush</th>\n      <th>rush_player</th>\n      <th>rush_player_id</th>\n      <th>rush_td</th>\n      <th>rush_yds</th>\n      <th>rusher_player_name</th>\n      <th>rz_play</th>\n      <th>sack</th>\n      <th>sack_player</th>\n      <th>sack_player_id</th>\n      <th>sack_player_name</th>\n      <th>sack_player_name2</th>\n      <th>sack_players</th>\n      <th>sack_stat</th>\n      <th>sack_taken_player</th>\n      <th>sack_taken_player_id</th>\n      <th>sack_taken_stat</th>\n      <th>sack_vec</th>\n      <th>safety</th>\n      <th>score_diff</th>\n      <th>score_diff_start</th>\n      <th>score_pts</th>\n      <th>scoring</th>\n      <th>scoring_opp</th>\n      <th>scoring_play</th>\n      <th>season</th>\n      <th>stuffed_run</th>\n      <th>success</th>\n      <th>target</th>\n      <th>target_player</th>\n      <th>target_player_id</th>\n      <th>target_stat</th>\n      <th>td_play</th>\n      <th>team_score</th>\n      <th>total_away_EPA</th>\n      <th>total_away_EPA_pass</th>\n      <th>total_away_EPA_rush</th>\n      <th>total_home_EPA</th>\n      <th>total_home_EPA_pass</th>\n      <th>total_home_EPA_rush</th>\n      <th>touchdown</th>\n      <th>touchdown_player</th>\n      <th>touchdown_player_id</th>\n      <th>touchdown_stat</th>\n      <th>turnover</th>\n      <th>turnover_indicator</th>\n      <th>turnover_vec</th>\n      <th>turnover_vec_lag</th>\n      <th>week</th>\n      <th>wp_after</th>\n      <th>wp_before</th>\n      <th>wpa</th>\n      <th>yard_line</th>\n      <th>yards_gained</th>\n      <th>yards_to_goal</th>\n      <th>yards_to_goal_end</th>\n      <th>yds_fg</th>\n      <th>yds_fumble_return</th>\n      <th>yds_int_return</th>\n      <th>yds_kickoff</th>\n      <th>yds_kickoff_return</th>\n      <th>yds_penalty</th>\n      <th>yds_punt_gained</th>\n      <th>yds_punt_return</th>\n      <th>yds_punted</th>\n      <th>yds_receiving</th>\n      <th>yds_rushed</th>\n      <th>yds_sacked</th>\n      <th>year</th>\n      <th>winner</th>\n      <th>spread</th>\n      <th>pos_team_spread</th>\n      <th>elapsed_share</th>\n      <th>spread_time</th>\n      <th>is_home</th>\n      <th>win_indicator</th>\n      <th>ExpScoreDiff_end</th>\n      <th>adj_TimeSecsRem_end</th>\n      <th>ExpScoreDiff_Time_Ratio_end</th>\n      <th>elapsed_share_end</th>\n      <th>spread_time_end</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>-0.470573</td>\n      <td>0.833168</td>\n      <td>0.000231</td>\n      <td>0.134882</td>\n      <td>0.170347</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002152</td>\n      <td>0.001775</td>\n      <td>0.121537</td>\n      <td>0.089202</td>\n      <td>0.004375</td>\n      <td>0.001915</td>\n      <td>0.343792</td>\n      <td>0.260404</td>\n      <td>0.002997</td>\n      <td>0.002950</td>\n      <td>0.390266</td>\n      <td>0.473408</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>0.470573</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.528336</td>\n      <td>0.509680</td>\n      <td>0</td>\n      <td>1</td>\n      <td>15</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.470573</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.528336</td>\n      <td>0.509680</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>1</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>0.362595</td>\n      <td>0.833168</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>1</td>\n      <td>1</td>\n      <td>30</td>\n      <td>1</td>\n      <td>East Carolina</td>\n      <td>-0.470573</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.471664</td>\n      <td>0.490320</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Brandon McLaren</td>\n      <td>Isaiah Jones</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Pass Reception</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.941145</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>-0.941145</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849902</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>Kickoff</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>Brandon McLaren kickoff for 51 yds , Isaiah Jo...</td>\n      <td>Kickoff</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.470573</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-0.470573</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0.471664</td>\n      <td>0.490320</td>\n      <td>-0.018655</td>\n      <td>65</td>\n      <td>6</td>\n      <td>65</td>\n      <td>80.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>51.0</td>\n      <td>6.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0.362595</td>\n      <td>5400</td>\n      <td>0.000067</td>\n      <td>-0.5</td>\n      <td>288.173188</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>-0.168094</td>\n      <td>0.362595</td>\n      <td>0.000101</td>\n      <td>0.128390</td>\n      <td>0.134882</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002141</td>\n      <td>0.002152</td>\n      <td>0.124954</td>\n      <td>0.121537</td>\n      <td>0.003679</td>\n      <td>0.004375</td>\n      <td>0.355615</td>\n      <td>0.343792</td>\n      <td>0.003138</td>\n      <td>0.002997</td>\n      <td>0.382083</td>\n      <td>0.390266</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>0.168094</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.535004</td>\n      <td>0.528336</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>4.0</td>\n      <td>0.168094</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.535004</td>\n      <td>0.528336</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>6.0</td>\n      <td>1.0</td>\n      <td>2.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>2</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>0.194501</td>\n      <td>0.362595</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>2</td>\n      <td>1</td>\n      <td>30</td>\n      <td>2</td>\n      <td>East Carolina</td>\n      <td>-0.168094</td>\n      <td>-0.168094</td>\n      <td>NaN</td>\n      <td>0.464996</td>\n      <td>0.471664</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>Brandon McLaren kickoff for 51 yds , Isaiah Jo...</td>\n      <td>None</td>\n      <td>Kickoff</td>\n      <td>None</td>\n      <td>None</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Pass Reception</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>1.791759</td>\n      <td>False</td>\n      <td>False</td>\n      <td>1.277333</td>\n      <td>0.168094</td>\n      <td>0.0</td>\n      <td>-1.277333</td>\n      <td>-0.168094</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849903</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>North Carolina Central</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Reception</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Pass Reception</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>-0.088432</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Justin Hardy</td>\n      <td>0.0</td>\n      <td>Justin Hardy</td>\n      <td>505407.0</td>\n      <td>4.0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.638667</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-0.638667</td>\n      <td>-0.168094</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.464996</td>\n      <td>0.471664</td>\n      <td>-0.006668</td>\n      <td>20</td>\n      <td>4</td>\n      <td>80</td>\n      <td>76.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>4.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0.194501</td>\n      <td>5400</td>\n      <td>0.000036</td>\n      <td>-0.5</td>\n      <td>288.173188</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2.283941</td>\n      <td>0.194501</td>\n      <td>0.000054</td>\n      <td>0.190673</td>\n      <td>0.128390</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.001539</td>\n      <td>0.002141</td>\n      <td>0.072094</td>\n      <td>0.124954</td>\n      <td>0.001135</td>\n      <td>0.003679</td>\n      <td>0.214480</td>\n      <td>0.355615</td>\n      <td>0.002843</td>\n      <td>0.003138</td>\n      <td>0.517235</td>\n      <td>0.382083</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>-2.283941</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.445405</td>\n      <td>0.535004</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>20.0</td>\n      <td>-2.283941</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.445405</td>\n      <td>0.535004</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>6.0</td>\n      <td>10.0</td>\n      <td>2.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>3</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>2.478443</td>\n      <td>0.194501</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>3</td>\n      <td>1</td>\n      <td>30</td>\n      <td>3</td>\n      <td>East Carolina</td>\n      <td>2.283941</td>\n      <td>2.283941</td>\n      <td>NaN</td>\n      <td>0.554595</td>\n      <td>0.464996</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Brandon McLaren kickoff for 51 yds , Isaiah Jo...</td>\n      <td>Pass Reception</td>\n      <td>Kickoff</td>\n      <td>None</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass incomplete to Justin Hardy, ...</td>\n      <td>Pass Incompletion</td>\n      <td>East Carolina</td>\n      <td>1.791759</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>-3.290549</td>\n      <td>-2.115847</td>\n      <td>0.0</td>\n      <td>3.290549</td>\n      <td>2.115847</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849904</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>North Carolina Central</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Reception</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Pass Reception</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>2.104307</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Cam Worthy</td>\n      <td>0.0</td>\n      <td>Cam Worthy</td>\n      <td>552953.0</td>\n      <td>20.0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>-1.645275</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.645275</td>\n      <td>2.115847</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.554595</td>\n      <td>0.464996</td>\n      <td>0.089599</td>\n      <td>24</td>\n      <td>20</td>\n      <td>76</td>\n      <td>56.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>20.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>2.478443</td>\n      <td>5400</td>\n      <td>0.000459</td>\n      <td>-0.5</td>\n      <td>288.173188</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>-0.855503</td>\n      <td>2.478443</td>\n      <td>0.000688</td>\n      <td>0.193531</td>\n      <td>0.190673</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.001703</td>\n      <td>0.001539</td>\n      <td>0.087026</td>\n      <td>0.072094</td>\n      <td>0.001516</td>\n      <td>0.001135</td>\n      <td>0.263697</td>\n      <td>0.214480</td>\n      <td>0.003072</td>\n      <td>0.002843</td>\n      <td>0.449456</td>\n      <td>0.517235</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>0.855503</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.478562</td>\n      <td>0.445405</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.855503</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.478562</td>\n      <td>0.445405</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>1.0</td>\n      <td>2.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>4</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>4</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>1.622940</td>\n      <td>2.478443</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>4</td>\n      <td>1</td>\n      <td>30</td>\n      <td>4</td>\n      <td>East Carolina</td>\n      <td>-0.855503</td>\n      <td>-0.855503</td>\n      <td>NaN</td>\n      <td>0.521438</td>\n      <td>0.554595</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Pass Reception</td>\n      <td>Pass Reception</td>\n      <td>Kickoff</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass incomplete to Davon Grayson</td>\n      <td>Pass Incompletion</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>-1.579543</td>\n      <td>-1.260344</td>\n      <td>0.0</td>\n      <td>1.579543</td>\n      <td>1.260344</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849905</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Incompletion</td>\n      <td>1</td>\n      <td>1</td>\n      <td>Michael Jones</td>\n      <td>164873.0</td>\n      <td>Michael Jones</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass incomplete to Justin Hardy, ...</td>\n      <td>Pass Incompletion</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>-1.161247</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Justin Hardy</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>4</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Justin Hardy</td>\n      <td>505407.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>-0.789771</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.789771</td>\n      <td>1.260344</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.521438</td>\n      <td>0.554595</td>\n      <td>-0.033156</td>\n      <td>44</td>\n      <td>0</td>\n      <td>56</td>\n      <td>56.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1.622940</td>\n      <td>5400</td>\n      <td>0.000300</td>\n      <td>-0.5</td>\n      <td>288.173188</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>-1.130810</td>\n      <td>1.622940</td>\n      <td>0.000451</td>\n      <td>0.185681</td>\n      <td>0.193531</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.001837</td>\n      <td>0.001703</td>\n      <td>0.109427</td>\n      <td>0.087026</td>\n      <td>0.002270</td>\n      <td>0.001516</td>\n      <td>0.329919</td>\n      <td>0.263697</td>\n      <td>0.003745</td>\n      <td>0.003072</td>\n      <td>0.367121</td>\n      <td>0.449456</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>1.130810</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.523197</td>\n      <td>0.478562</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1.130810</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.523197</td>\n      <td>0.478562</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>2.0</td>\n      <td>3.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>5</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>5</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>0.492129</td>\n      <td>1.622940</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>5</td>\n      <td>1</td>\n      <td>30</td>\n      <td>5</td>\n      <td>East Carolina</td>\n      <td>-1.130810</td>\n      <td>-1.130810</td>\n      <td>NaN</td>\n      <td>0.476803</td>\n      <td>0.521438</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Shane Carden pass incomplete to Justin Hardy, ...</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Pass Incompletion</td>\n      <td>Pass Reception</td>\n      <td>Pass Reception</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>EAST CAROLINA Penalty, false start (-5 Yards) ...</td>\n      <td>Penalty</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.682078</td>\n      <td>-0.129534</td>\n      <td>0.0</td>\n      <td>-0.682078</td>\n      <td>0.129534</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849906</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>North Carolina Central</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Incompletion</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass incomplete to Davon Grayson</td>\n      <td>Pass Incompletion</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>-0.881290</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Davon Grayson</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>5</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Davon Grayson</td>\n      <td>552937.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.341039</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-0.341039</td>\n      <td>0.129534</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.476803</td>\n      <td>0.521438</td>\n      <td>-0.044636</td>\n      <td>44</td>\n      <td>0</td>\n      <td>56</td>\n      <td>56.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0.492129</td>\n      <td>5400</td>\n      <td>0.000091</td>\n      <td>-0.5</td>\n      <td>288.173188</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nbase_data = base_data[\n    (base_data.ep_before.notna())\n    & (base_data.pos_score_diff_start.notna())\n    & (base_data.play_type.notna())\n    & (base_data.win_indicator.notna())\n    & (base_data.pos_team_timeouts_rem_before.notna())\n    & (base_data.def_pos_team_timeouts_rem_before.notna())\n    & (base_data.yards_to_goal.notna())\n    & (base_data.period <= 4)\n\n    & (base_data.ep_after.notna())\n    & (base_data.pos_score_diff_start_end.notna())\n    & (base_data.pos_team_timeouts.notna())\n    & (base_data.def_pos_team_timeouts.notna())\n    & (base_data.yards_to_goal_end.notna())\n\n    & (base_data.down_end.notna())\n]\nbase_data.down_end = base_data.down_end.astype(int)\n```\n\n\n```python\n# leave-one-season-out\ndef calculate_wpa(yr):\n    data = base_data[base_data.year != yr]\n    dtest_start = xgb.DMatrix(data[model_columns_before], label=data.win_indicator)\n    WP_start = wp_model.predict(dtest_start)\n\n    end_data = data[model_columns_after]\n    end_data.columns = model_columns_before\n\n    dtest_end = xgb.DMatrix(end_data, label=data.win_indicator)\n    WP_end = wp_model.predict(dtest_end)\n\n    base_data.loc[data.index, 'WP_NFL_start'] = WP_start\n    base_data.loc[data.index,'WP_NFL_end'] = WP_end\n    base_data.loc[data.index,'WPA_NFL'] = base_data['WP_NFL_end'] - base_data['WP_NFL_start']\n\nyears_range = range(min(pbp_data.year), max(pbp_data.year) + 1)\nfor yr in years_range:\n    calculate_wpa(yr)\n\nbase_data.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>EPA</th>\n      <th>ExpScoreDiff</th>\n      <th>ExpScoreDiff_Time_Ratio</th>\n      <th>FG_after</th>\n      <th>FG_before</th>\n      <th>Goal_To_Go</th>\n      <th>Goal_To_Go_end</th>\n      <th>No_Score_after</th>\n      <th>No_Score_before</th>\n      <th>Opp_FG_after</th>\n      <th>Opp_FG_before</th>\n      <th>Opp_Safety_after</th>\n      <th>Opp_Safety_before</th>\n      <th>Opp_TD_after</th>\n      <th>Opp_TD_before</th>\n      <th>Safety_after</th>\n      <th>Safety_before</th>\n      <th>TD_after</th>\n      <th>TD_before</th>\n      <th>TimeSecsRem</th>\n      <th>TimeSecsRem_end</th>\n      <th>Under_three</th>\n      <th>Under_two</th>\n      <th>Under_two_end</th>\n      <th>adj_TimeSecsRem</th>\n      <th>away</th>\n      <th>away_EPA</th>\n      <th>away_EPA_pass</th>\n      <th>away_EPA_rush</th>\n      <th>away_wp_after</th>\n      <th>away_wp_before</th>\n      <th>change_of_pos_team</th>\n      <th>change_of_poss</th>\n      <th>clock.minutes</th>\n      <th>clock.seconds</th>\n      <th>completion</th>\n      <th>completion_player</th>\n      <th>completion_player_id</th>\n      <th>completion_yds</th>\n      <th>def_EPA</th>\n      <th>def_pos_team</th>\n      <th>def_pos_team_score</th>\n      <th>def_pos_team_timeouts</th>\n      <th>def_pos_team_timeouts_rem_before</th>\n      <th>def_timeout_called</th>\n      <th>def_timeouts_rem_before</th>\n      <th>def_wp_after</th>\n      <th>def_wp_before</th>\n      <th>defense_conference</th>\n      <th>defense_play</th>\n      <th>defense_score</th>\n      <th>defense_score_play</th>\n      <th>defense_timeouts</th>\n      <th>distance</th>\n      <th>distance_end</th>\n      <th>down</th>\n      <th>down_end</th>\n      <th>downs_turnover</th>\n      <th>drive_end_period</th>\n      <th>drive_end_yards_to_goal</th>\n      <th>drive_event_number</th>\n      <th>drive_id</th>\n      <th>drive_num</th>\n      <th>drive_number</th>\n      <th>drive_numbers</th>\n      <th>drive_play_number</th>\n      <th>drive_pts</th>\n      <th>drive_result</th>\n      <th>drive_result2</th>\n      <th>drive_result_detailed</th>\n      <th>drive_result_detailed_flag</th>\n      <th>drive_scoring</th>\n      <th>drive_start_period</th>\n      <th>drive_start_yards_to_goal</th>\n      <th>drive_time_minutes_elapsed</th>\n      <th>drive_time_minutes_end</th>\n      <th>drive_time_minutes_start</th>\n      <th>drive_time_seconds_elapsed</th>\n      <th>drive_time_seconds_end</th>\n      <th>drive_time_seconds_start</th>\n      <th>drive_yards</th>\n      <th>end_of_half</th>\n      <th>ep_after</th>\n      <th>ep_before</th>\n      <th>epa_success</th>\n      <th>fg_block_player_name</th>\n      <th>fg_inds</th>\n      <th>fg_kicker_player_name</th>\n      <th>fg_made</th>\n      <th>fg_make_prob</th>\n      <th>fg_return_player_name</th>\n      <th>firstD_by_kickoff</th>\n      <th>firstD_by_penalty</th>\n      <th>firstD_by_poss</th>\n      <th>firstD_by_yards</th>\n      <th>first_by_penalty</th>\n      <th>first_by_yards</th>\n      <th>fumble_forced_player</th>\n      <th>fumble_forced_player_id</th>\n      <th>fumble_forced_player_name</th>\n      <th>fumble_forced_stat</th>\n      <th>fumble_player</th>\n      <th>fumble_player_id</th>\n      <th>fumble_player_name</th>\n      <th>fumble_recovered_player</th>\n      <th>fumble_recovered_player_id</th>\n      <th>fumble_recovered_player_name</th>\n      <th>fumble_recovered_stat</th>\n      <th>fumble_stat</th>\n      <th>fumble_vec</th>\n      <th>game_id</th>\n      <th>game_play_number</th>\n      <th>half</th>\n      <th>half_clock.minutes</th>\n      <th>half_play_number</th>\n      <th>home</th>\n      <th>home_EPA</th>\n      <th>home_EPA_pass</th>\n      <th>home_EPA_rush</th>\n      <th>home_wp_after</th>\n      <th>home_wp_before</th>\n      <th>id_drive</th>\n      <th>id_play</th>\n      <th>incompletion_player</th>\n      <th>incompletion_player_id</th>\n      <th>incompletion_stat</th>\n      <th>int</th>\n      <th>int_td</th>\n      <th>interception_player</th>\n      <th>interception_player_id</th>\n      <th>interception_player_name</th>\n      <th>interception_stat</th>\n      <th>interception_thrown_player</th>\n      <th>interception_thrown_player_id</th>\n      <th>interception_thrown_stat</th>\n      <th>kick_play</th>\n      <th>kickoff_downed</th>\n      <th>kickoff_fair_catch</th>\n      <th>kickoff_onside</th>\n      <th>kickoff_oob</th>\n      <th>kickoff_play</th>\n      <th>kickoff_player_name</th>\n      <th>kickoff_returner_player_name</th>\n      <th>kickoff_safety</th>\n      <th>kickoff_tb</th>\n      <th>lag_change_of_pos_team</th>\n      <th>lag_change_of_pos_team2</th>\n      <th>lag_change_of_poss</th>\n      <th>lag_defense_score_play</th>\n      <th>lag_downs_turnover</th>\n      <th>lag_drive_result_detailed</th>\n      <th>lag_first_by_penalty</th>\n      <th>lag_first_by_penalty2</th>\n      <th>lag_first_by_yards</th>\n      <th>lag_first_by_yards2</th>\n      <th>lag_kickoff_play</th>\n      <th>lag_new_drive_pts</th>\n      <th>lag_play_text</th>\n      <th>lag_play_text2</th>\n      <th>lag_play_type</th>\n      <th>lag_play_type2</th>\n      <th>lag_play_type3</th>\n      <th>lag_pos_team</th>\n      <th>lag_punt</th>\n      <th>lag_punt2</th>\n      <th>lag_scoring_play</th>\n      <th>lag_turnover_vec</th>\n      <th>lead_drive_result_detailed</th>\n      <th>lead_play_text</th>\n      <th>lead_play_type</th>\n      <th>lead_pos_team</th>\n      <th>log_ydstogo</th>\n      <th>log_ydstogo_end</th>\n      <th>middle_8</th>\n      <th>missing_yard_flag</th>\n      <th>net_away_EPA</th>\n      <th>net_away_EPA_pass</th>\n      <th>net_away_EPA_rush</th>\n      <th>net_home_EPA</th>\n      <th>net_home_EPA_pass</th>\n      <th>net_home_EPA_rush</th>\n      <th>new_drive_pts</th>\n      <th>new_id</th>\n      <th>new_series</th>\n      <th>number_of_drives</th>\n      <th>off_timeout_called</th>\n      <th>off_timeouts_rem_before</th>\n      <th>offense_conference</th>\n      <th>offense_play</th>\n      <th>offense_receives_2H_kickoff</th>\n      <th>offense_score</th>\n      <th>offense_score_play</th>\n      <th>offense_timeouts</th>\n      <th>opponent</th>\n      <th>opponent_score</th>\n      <th>orig_drive_number</th>\n      <th>orig_play_type</th>\n      <th>pass</th>\n      <th>pass_attempt</th>\n      <th>pass_breakup_player</th>\n      <th>pass_breakup_player_id</th>\n      <th>pass_breakup_player_name</th>\n      <th>pass_breakup_stat</th>\n      <th>pass_td</th>\n      <th>passer_player_name</th>\n      <th>penalty_1st_conv</th>\n      <th>penalty_declined</th>\n      <th>penalty_detail</th>\n      <th>penalty_flag</th>\n      <th>penalty_no_play</th>\n      <th>penalty_offset</th>\n      <th>penalty_play_text</th>\n      <th>penalty_safety</th>\n      <th>penalty_text</th>\n      <th>period</th>\n      <th>play_after_turnover</th>\n      <th>play_id</th>\n      <th>play_text</th>\n      <th>play_type</th>\n      <th>pos_score_diff</th>\n      <th>pos_score_diff_start</th>\n      <th>pos_score_diff_start_end</th>\n      <th>pos_score_pts</th>\n      <th>pos_team</th>\n      <th>pos_team_receives_2H_kickoff</th>\n      <th>pos_team_score</th>\n      <th>pos_team_timeouts</th>\n      <th>pos_team_timeouts_rem_before</th>\n      <th>position_completion</th>\n      <th>position_fumble</th>\n      <th>position_fumble_forced</th>\n      <th>position_fumble_recovered</th>\n      <th>position_incompletion</th>\n      <th>position_interception</th>\n      <th>position_interception_thrown</th>\n      <th>position_pass_breakup</th>\n      <th>position_reception</th>\n      <th>position_rush</th>\n      <th>position_sack</th>\n      <th>position_sack_taken</th>\n      <th>position_target</th>\n      <th>position_touchdown</th>\n      <th>ppa</th>\n      <th>pts_scored</th>\n      <th>punt</th>\n      <th>punt_block_player_name</th>\n      <th>punt_block_return_player_name</th>\n      <th>punt_blocked</th>\n      <th>punt_downed</th>\n      <th>punt_fair_catch</th>\n      <th>punt_oob</th>\n      <th>punt_play</th>\n      <th>punt_returner_player_name</th>\n      <th>punt_safety</th>\n      <th>punt_tb</th>\n      <th>punter_player_name</th>\n      <th>receiver_player_name</th>\n      <th>receives_2H_kickoff</th>\n      <th>reception_player</th>\n      <th>reception_player_id</th>\n      <th>reception_yds</th>\n      <th>row</th>\n      <th>rush</th>\n      <th>rush_player</th>\n      <th>rush_player_id</th>\n      <th>rush_td</th>\n      <th>rush_yds</th>\n      <th>rusher_player_name</th>\n      <th>rz_play</th>\n      <th>sack</th>\n      <th>sack_player</th>\n      <th>sack_player_id</th>\n      <th>sack_player_name</th>\n      <th>sack_player_name2</th>\n      <th>sack_players</th>\n      <th>sack_stat</th>\n      <th>sack_taken_player</th>\n      <th>sack_taken_player_id</th>\n      <th>sack_taken_stat</th>\n      <th>sack_vec</th>\n      <th>safety</th>\n      <th>score_diff</th>\n      <th>score_diff_start</th>\n      <th>score_pts</th>\n      <th>scoring</th>\n      <th>scoring_opp</th>\n      <th>scoring_play</th>\n      <th>season</th>\n      <th>stuffed_run</th>\n      <th>success</th>\n      <th>target</th>\n      <th>target_player</th>\n      <th>target_player_id</th>\n      <th>target_stat</th>\n      <th>td_play</th>\n      <th>team_score</th>\n      <th>total_away_EPA</th>\n      <th>total_away_EPA_pass</th>\n      <th>total_away_EPA_rush</th>\n      <th>total_home_EPA</th>\n      <th>total_home_EPA_pass</th>\n      <th>total_home_EPA_rush</th>\n      <th>touchdown</th>\n      <th>touchdown_player</th>\n      <th>touchdown_player_id</th>\n      <th>touchdown_stat</th>\n      <th>turnover</th>\n      <th>turnover_indicator</th>\n      <th>turnover_vec</th>\n      <th>turnover_vec_lag</th>\n      <th>week</th>\n      <th>wp_after</th>\n      <th>wp_before</th>\n      <th>wpa</th>\n      <th>yard_line</th>\n      <th>yards_gained</th>\n      <th>yards_to_goal</th>\n      <th>yards_to_goal_end</th>\n      <th>yds_fg</th>\n      <th>yds_fumble_return</th>\n      <th>yds_int_return</th>\n      <th>yds_kickoff</th>\n      <th>yds_kickoff_return</th>\n      <th>yds_penalty</th>\n      <th>yds_punt_gained</th>\n      <th>yds_punt_return</th>\n      <th>yds_punted</th>\n      <th>yds_receiving</th>\n      <th>yds_rushed</th>\n      <th>yds_sacked</th>\n      <th>year</th>\n      <th>winner</th>\n      <th>spread</th>\n      <th>pos_team_spread</th>\n      <th>elapsed_share</th>\n      <th>spread_time</th>\n      <th>is_home</th>\n      <th>win_indicator</th>\n      <th>ExpScoreDiff_end</th>\n      <th>adj_TimeSecsRem_end</th>\n      <th>ExpScoreDiff_Time_Ratio_end</th>\n      <th>elapsed_share_end</th>\n      <th>spread_time_end</th>\n      <th>WP_NFL_start</th>\n      <th>WP_NFL_end</th>\n      <th>WPA_NFL</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>-0.470573</td>\n      <td>0.833168</td>\n      <td>0.000231</td>\n      <td>0.134882</td>\n      <td>0.170347</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002152</td>\n      <td>0.001775</td>\n      <td>0.121537</td>\n      <td>0.089202</td>\n      <td>0.004375</td>\n      <td>0.001915</td>\n      <td>0.343792</td>\n      <td>0.260404</td>\n      <td>0.002997</td>\n      <td>0.002950</td>\n      <td>0.390266</td>\n      <td>0.473408</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>0.470573</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.528336</td>\n      <td>0.509680</td>\n      <td>0</td>\n      <td>1</td>\n      <td>15</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.470573</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.528336</td>\n      <td>0.509680</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>1</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>0.362595</td>\n      <td>0.833168</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>1</td>\n      <td>1</td>\n      <td>30</td>\n      <td>1</td>\n      <td>East Carolina</td>\n      <td>-0.470573</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.471664</td>\n      <td>0.490320</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Brandon McLaren</td>\n      <td>Isaiah Jones</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Pass Reception</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.941145</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>-0.941145</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849902</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>Kickoff</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>Brandon McLaren kickoff for 51 yds , Isaiah Jo...</td>\n      <td>Kickoff</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.470573</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-0.470573</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>1</td>\n      <td>0.471664</td>\n      <td>0.490320</td>\n      <td>-0.018655</td>\n      <td>65</td>\n      <td>6</td>\n      <td>65</td>\n      <td>80.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>51.0</td>\n      <td>6.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0.362595</td>\n      <td>5400</td>\n      <td>0.000067</td>\n      <td>-0.5</td>\n      <td>288.173188</td>\n      <td>0.985915</td>\n      <td>0.983851</td>\n      <td>-0.002065</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>-0.168094</td>\n      <td>0.362595</td>\n      <td>0.000101</td>\n      <td>0.128390</td>\n      <td>0.134882</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.002141</td>\n      <td>0.002152</td>\n      <td>0.124954</td>\n      <td>0.121537</td>\n      <td>0.003679</td>\n      <td>0.004375</td>\n      <td>0.355615</td>\n      <td>0.343792</td>\n      <td>0.003138</td>\n      <td>0.002997</td>\n      <td>0.382083</td>\n      <td>0.390266</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>0.168094</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.535004</td>\n      <td>0.528336</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>4.0</td>\n      <td>0.168094</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.535004</td>\n      <td>0.528336</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>6.0</td>\n      <td>1.0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>2</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>0.194501</td>\n      <td>0.362595</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>2</td>\n      <td>1</td>\n      <td>30</td>\n      <td>2</td>\n      <td>East Carolina</td>\n      <td>-0.168094</td>\n      <td>-0.168094</td>\n      <td>NaN</td>\n      <td>0.464996</td>\n      <td>0.471664</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>Brandon McLaren kickoff for 51 yds , Isaiah Jo...</td>\n      <td>None</td>\n      <td>Kickoff</td>\n      <td>None</td>\n      <td>None</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Pass Reception</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>1.791759</td>\n      <td>False</td>\n      <td>False</td>\n      <td>1.277333</td>\n      <td>0.168094</td>\n      <td>0.0</td>\n      <td>-1.277333</td>\n      <td>-0.168094</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849903</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>North Carolina Central</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Reception</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Pass Reception</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>-0.088432</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Justin Hardy</td>\n      <td>0.0</td>\n      <td>Justin Hardy</td>\n      <td>505407.0</td>\n      <td>4.0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.638667</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-0.638667</td>\n      <td>-0.168094</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.464996</td>\n      <td>0.471664</td>\n      <td>-0.006668</td>\n      <td>20</td>\n      <td>4</td>\n      <td>80</td>\n      <td>76.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>4.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0.194501</td>\n      <td>5400</td>\n      <td>0.000036</td>\n      <td>-0.5</td>\n      <td>288.173188</td>\n      <td>0.984520</td>\n      <td>0.983389</td>\n      <td>-0.001131</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2.283941</td>\n      <td>0.194501</td>\n      <td>0.000054</td>\n      <td>0.190673</td>\n      <td>0.128390</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.001539</td>\n      <td>0.002141</td>\n      <td>0.072094</td>\n      <td>0.124954</td>\n      <td>0.001135</td>\n      <td>0.003679</td>\n      <td>0.214480</td>\n      <td>0.355615</td>\n      <td>0.002843</td>\n      <td>0.003138</td>\n      <td>0.517235</td>\n      <td>0.382083</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>-2.283941</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.445405</td>\n      <td>0.535004</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>20.0</td>\n      <td>-2.283941</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.445405</td>\n      <td>0.535004</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>6.0</td>\n      <td>10.0</td>\n      <td>2.0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>3</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>2.478443</td>\n      <td>0.194501</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>3</td>\n      <td>1</td>\n      <td>30</td>\n      <td>3</td>\n      <td>East Carolina</td>\n      <td>2.283941</td>\n      <td>2.283941</td>\n      <td>NaN</td>\n      <td>0.554595</td>\n      <td>0.464996</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Brandon McLaren kickoff for 51 yds , Isaiah Jo...</td>\n      <td>Pass Reception</td>\n      <td>Kickoff</td>\n      <td>None</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass incomplete to Justin Hardy, ...</td>\n      <td>Pass Incompletion</td>\n      <td>East Carolina</td>\n      <td>1.791759</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>-3.290549</td>\n      <td>-2.115847</td>\n      <td>0.0</td>\n      <td>3.290549</td>\n      <td>2.115847</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849904</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>North Carolina Central</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Reception</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Pass Reception</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>2.104307</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Cam Worthy</td>\n      <td>0.0</td>\n      <td>Cam Worthy</td>\n      <td>552953.0</td>\n      <td>20.0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>-1.645275</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.645275</td>\n      <td>2.115847</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.554595</td>\n      <td>0.464996</td>\n      <td>0.089599</td>\n      <td>24</td>\n      <td>20</td>\n      <td>76</td>\n      <td>56.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>20.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>2.478443</td>\n      <td>5400</td>\n      <td>0.000459</td>\n      <td>-0.5</td>\n      <td>288.173188</td>\n      <td>0.983777</td>\n      <td>0.989738</td>\n      <td>0.005961</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>-0.855503</td>\n      <td>2.478443</td>\n      <td>0.000688</td>\n      <td>0.193531</td>\n      <td>0.190673</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.001703</td>\n      <td>0.001539</td>\n      <td>0.087026</td>\n      <td>0.072094</td>\n      <td>0.001516</td>\n      <td>0.001135</td>\n      <td>0.263697</td>\n      <td>0.214480</td>\n      <td>0.003072</td>\n      <td>0.002843</td>\n      <td>0.449456</td>\n      <td>0.517235</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>0.855503</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.478562</td>\n      <td>0.445405</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.855503</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.478562</td>\n      <td>0.445405</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>1.0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>4</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>4</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>1.622940</td>\n      <td>2.478443</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>4</td>\n      <td>1</td>\n      <td>30</td>\n      <td>4</td>\n      <td>East Carolina</td>\n      <td>-0.855503</td>\n      <td>-0.855503</td>\n      <td>NaN</td>\n      <td>0.521438</td>\n      <td>0.554595</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Shane Carden pass complete to Justin Hardy for...</td>\n      <td>Pass Reception</td>\n      <td>Pass Reception</td>\n      <td>Kickoff</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>Shane Carden pass incomplete to Davon Grayson</td>\n      <td>Pass Incompletion</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>-1.579543</td>\n      <td>-1.260344</td>\n      <td>0.0</td>\n      <td>1.579543</td>\n      <td>1.260344</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849905</td>\n      <td>1.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Incompletion</td>\n      <td>1</td>\n      <td>1</td>\n      <td>Michael Jones</td>\n      <td>164873.0</td>\n      <td>Michael Jones</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass incomplete to Justin Hardy, ...</td>\n      <td>Pass Incompletion</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>-1.161247</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Justin Hardy</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>4</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Justin Hardy</td>\n      <td>505407.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>-0.789771</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.789771</td>\n      <td>1.260344</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.521438</td>\n      <td>0.554595</td>\n      <td>-0.033156</td>\n      <td>44</td>\n      <td>0</td>\n      <td>56</td>\n      <td>56.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1.622940</td>\n      <td>5400</td>\n      <td>0.000300</td>\n      <td>-0.5</td>\n      <td>288.173188</td>\n      <td>0.991003</td>\n      <td>0.989213</td>\n      <td>-0.001790</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>-1.130810</td>\n      <td>1.622940</td>\n      <td>0.000451</td>\n      <td>0.185681</td>\n      <td>0.193531</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.001837</td>\n      <td>0.001703</td>\n      <td>0.109427</td>\n      <td>0.087026</td>\n      <td>0.002270</td>\n      <td>0.001516</td>\n      <td>0.329919</td>\n      <td>0.263697</td>\n      <td>0.003745</td>\n      <td>0.003072</td>\n      <td>0.367121</td>\n      <td>0.449456</td>\n      <td>1800</td>\n      <td>1800.0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3600</td>\n      <td>North Carolina Central</td>\n      <td>1.130810</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.523197</td>\n      <td>0.478562</td>\n      <td>0</td>\n      <td>0</td>\n      <td>15</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1.130810</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>0.523197</td>\n      <td>0.478562</td>\n      <td>None</td>\n      <td>North Carolina Central</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>10.0</td>\n      <td>10.0</td>\n      <td>2.0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>1</td>\n      <td>66</td>\n      <td>5</td>\n      <td>4.005476e+09</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>5</td>\n      <td>0</td>\n      <td>PUNT</td>\n      <td>PUNT</td>\n      <td>Punt</td>\n      <td>None</td>\n      <td>0</td>\n      <td>1</td>\n      <td>80</td>\n      <td>1</td>\n      <td>13</td>\n      <td>15</td>\n      <td>26</td>\n      <td>34</td>\n      <td>0</td>\n      <td>14</td>\n      <td>0</td>\n      <td>0.492129</td>\n      <td>1.622940</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>400547643</td>\n      <td>5</td>\n      <td>1</td>\n      <td>30</td>\n      <td>5</td>\n      <td>East Carolina</td>\n      <td>-1.130810</td>\n      <td>-1.130810</td>\n      <td>NaN</td>\n      <td>0.476803</td>\n      <td>0.521438</td>\n      <td>4.005476e+09</td>\n      <td>4.005476e+17</td>\n      <td>Shane Carden</td>\n      <td>500938.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Shane Carden pass incomplete to Justin Hardy, ...</td>\n      <td>Shane Carden pass complete to Cam Worthy for 2...</td>\n      <td>Pass Incompletion</td>\n      <td>Pass Reception</td>\n      <td>Pass Reception</td>\n      <td>East Carolina</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>Punt</td>\n      <td>EAST CAROLINA Penalty, false start (-5 Yards) ...</td>\n      <td>Penalty</td>\n      <td>East Carolina</td>\n      <td>2.302585</td>\n      <td>2.302585</td>\n      <td>False</td>\n      <td>False</td>\n      <td>0.682078</td>\n      <td>-0.129534</td>\n      <td>0.0</td>\n      <td>-0.682078</td>\n      <td>0.129534</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>101849906</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>3.0</td>\n      <td>American Athletic</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>North Carolina Central</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Pass Incompletion</td>\n      <td>1</td>\n      <td>1</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>Shane Carden</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>None</td>\n      <td>0</td>\n      <td>False</td>\n      <td>1</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>Shane Carden pass incomplete to Davon Grayson</td>\n      <td>Pass Incompletion</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>East Carolina</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3.0</td>\n      <td>3.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>QB</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>WR</td>\n      <td>None</td>\n      <td>-0.881290</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Davon Grayson</td>\n      <td>0.0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>5</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2014.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>Davon Grayson</td>\n      <td>552937.0</td>\n      <td>1.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0.341039</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-0.341039</td>\n      <td>0.129534</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>0</td>\n      <td>0.0</td>\n      <td>1</td>\n      <td>0.476803</td>\n      <td>0.521438</td>\n      <td>-0.044636</td>\n      <td>44</td>\n      <td>0</td>\n      <td>56</td>\n      <td>56.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2014</td>\n      <td>East Carolina</td>\n      <td>39.0</td>\n      <td>39.0</td>\n      <td>0.0</td>\n      <td>39.0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0.492129</td>\n      <td>5400</td>\n      <td>0.000091</td>\n      <td>-0.5</td>\n      <td>288.173188</td>\n      <td>0.989819</td>\n      <td>0.984534</td>\n      <td>-0.005285</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nprint(\"Diff from cfbscrapR model:\")\nprint(f\"Diff of WPA: {(base_data['wpa'] - base_data['WPA_NFL']).mean()}\")\nprint(f\"Diff of WP_start: {(base_data['wp_before'] - base_data['WP_NFL_start']).mean()}\")\nprint(f\"Diff of WP_end: {(base_data['wp_after'] - base_data['WP_NFL_end']).mean()}\")\n```\n\n    Diff from cfbscrapR model:\n    Diff of WPA: -0.0007160050340341484\n    Diff of WP_start: -0.0016404073332568982\n    Diff of WP_end: -0.0024357032654589513\n\n\n\n```python\nbase_data[[\"wp_before\",\"wp_after\",\"wpa\",\"WP_NFL_start\",\"WP_NFL_end\",\"WPA_NFL\"]].head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>wp_before</th>\n      <th>wp_after</th>\n      <th>wpa</th>\n      <th>WP_NFL_start</th>\n      <th>WP_NFL_end</th>\n      <th>WPA_NFL</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.490320</td>\n      <td>0.471664</td>\n      <td>-0.018655</td>\n      <td>0.985915</td>\n      <td>0.983851</td>\n      <td>-0.002065</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.471664</td>\n      <td>0.464996</td>\n      <td>-0.006668</td>\n      <td>0.984520</td>\n      <td>0.983389</td>\n      <td>-0.001131</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.464996</td>\n      <td>0.554595</td>\n      <td>0.089599</td>\n      <td>0.983777</td>\n      <td>0.989738</td>\n      <td>0.005961</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.554595</td>\n      <td>0.521438</td>\n      <td>-0.033156</td>\n      <td>0.991003</td>\n      <td>0.989213</td>\n      <td>-0.001790</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.521438</td>\n      <td>0.476803</td>\n      <td>-0.044636</td>\n      <td>0.989819</td>\n      <td>0.984534</td>\n      <td>-0.005285</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ngathered = base_data.melt(id_vars=[\"period\",\"win_indicator\"], value_vars=[\"WP_NFL_start\"],value_name=\"pred_prob\")\ngathered\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>period</th>\n      <th>win_indicator</th>\n      <th>variable</th>\n      <th>pred_prob</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>1</td>\n      <td>WP_NFL_start</td>\n      <td>0.985915</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>1</td>\n      <td>WP_NFL_start</td>\n      <td>0.984520</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1</td>\n      <td>1</td>\n      <td>WP_NFL_start</td>\n      <td>0.983777</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1</td>\n      <td>1</td>\n      <td>WP_NFL_start</td>\n      <td>0.991003</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1</td>\n      <td>1</td>\n      <td>WP_NFL_start</td>\n      <td>0.989819</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>845808</th>\n      <td>4</td>\n      <td>0</td>\n      <td>WP_NFL_start</td>\n      <td>0.012452</td>\n    </tr>\n    <tr>\n      <th>845809</th>\n      <td>4</td>\n      <td>1</td>\n      <td>WP_NFL_start</td>\n      <td>0.977425</td>\n    </tr>\n    <tr>\n      <th>845810</th>\n      <td>4</td>\n      <td>1</td>\n      <td>WP_NFL_start</td>\n      <td>0.982198</td>\n    </tr>\n    <tr>\n      <th>845811</th>\n      <td>4</td>\n      <td>1</td>\n      <td>WP_NFL_start</td>\n      <td>0.981976</td>\n    </tr>\n    <tr>\n      <th>845812</th>\n      <td>4</td>\n      <td>1</td>\n      <td>WP_NFL_start</td>\n      <td>0.958588</td>\n    </tr>\n  </tbody>\n</table>\n<p>845813 rows \u00d7 4 columns</p>\n</div>\n\n\n\n\n```python\ngathered['bin_pred_prob'] = (round(gathered.pred_prob / 0.05) * .05)\ngathered\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>period</th>\n      <th>win_indicator</th>\n      <th>variable</th>\n      <th>pred_prob</th>\n      <th>bin_pred_prob</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>1</td>\n      <td>WP_NFL_start</td>\n      <td>0.985915</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>1</td>\n      <td>WP_NFL_start</td>\n      <td>0.984520</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1</td>\n      <td>1</td>\n      <td>WP_NFL_start</td>\n      <td>0.983777</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1</td>\n      <td>1</td>\n      <td>WP_NFL_start</td>\n      <td>0.991003</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1</td>\n      <td>1</td>\n      <td>WP_NFL_start</td>\n      <td>0.989819</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>845808</th>\n      <td>4</td>\n      <td>0</td>\n      <td>WP_NFL_start</td>\n      <td>0.012452</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>845809</th>\n      <td>4</td>\n      <td>1</td>\n      <td>WP_NFL_start</td>\n      <td>0.977425</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>845810</th>\n      <td>4</td>\n      <td>1</td>\n      <td>WP_NFL_start</td>\n      <td>0.982198</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>845811</th>\n      <td>4</td>\n      <td>1</td>\n      <td>WP_NFL_start</td>\n      <td>0.981976</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>845812</th>\n      <td>4</td>\n      <td>1</td>\n      <td>WP_NFL_start</td>\n      <td>0.958588</td>\n      <td>0.95</td>\n    </tr>\n  </tbody>\n</table>\n<p>845813 rows \u00d7 5 columns</p>\n</div>\n\n\n\n\n```python\ngathered['bin_pred_prob'].value_counts()\n```\n\n\n\n\n    0.00    132152\n    1.00    127837\n    0.05     60967\n    0.95     60185\n    0.90     41096\n    0.10     40615\n    0.85     32765\n    0.15     32151\n    0.20     29521\n    0.80     28438\n    0.25     26931\n    0.75     26711\n    0.70     25440\n    0.30     24750\n    0.65     23929\n    0.35     23432\n    0.60     22842\n    0.55     21968\n    0.40     21943\n    0.45     21173\n    0.50     20967\n    Name: bin_pred_prob, dtype: int64\n\n\n\n\n```python\ngrouped_score = gathered.groupby(['period','bin_pred_prob'])\ndef organize(grp):\n    d = {}\n    d['n_plays'] = len(grp)\n    d['n_wins'] = len(grp[grp.win_indicator == True])\n    d['bin_actual_prob'] = d['n_wins'] / d['n_plays']\n    return pd.Series(d, index=['n_plays','n_wins','bin_actual_prob'])\n\norganized = grouped_score.apply(organize)\norganized = organized.reset_index()\norganized\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>period</th>\n      <th>bin_pred_prob</th>\n      <th>n_plays</th>\n      <th>n_wins</th>\n      <th>bin_actual_prob</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>0.00</td>\n      <td>15064.0</td>\n      <td>65.0</td>\n      <td>0.004315</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>0.05</td>\n      <td>13636.0</td>\n      <td>656.0</td>\n      <td>0.048108</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1</td>\n      <td>0.10</td>\n      <td>10373.0</td>\n      <td>939.0</td>\n      <td>0.090523</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1</td>\n      <td>0.15</td>\n      <td>9494.0</td>\n      <td>1380.0</td>\n      <td>0.145355</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1</td>\n      <td>0.20</td>\n      <td>10012.0</td>\n      <td>2041.0</td>\n      <td>0.203855</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>1</td>\n      <td>0.25</td>\n      <td>9238.0</td>\n      <td>2451.0</td>\n      <td>0.265317</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>1</td>\n      <td>0.30</td>\n      <td>8494.0</td>\n      <td>2475.0</td>\n      <td>0.291382</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>1</td>\n      <td>0.35</td>\n      <td>7565.0</td>\n      <td>2675.0</td>\n      <td>0.353602</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>1</td>\n      <td>0.40</td>\n      <td>7659.0</td>\n      <td>3016.0</td>\n      <td>0.393785</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>1</td>\n      <td>0.45</td>\n      <td>7285.0</td>\n      <td>3277.0</td>\n      <td>0.449828</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>1</td>\n      <td>0.50</td>\n      <td>7239.0</td>\n      <td>3569.0</td>\n      <td>0.493024</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>1</td>\n      <td>0.55</td>\n      <td>7439.0</td>\n      <td>4192.0</td>\n      <td>0.563517</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>1</td>\n      <td>0.60</td>\n      <td>7752.0</td>\n      <td>4676.0</td>\n      <td>0.603199</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>1</td>\n      <td>0.65</td>\n      <td>7279.0</td>\n      <td>4677.0</td>\n      <td>0.642533</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>1</td>\n      <td>0.70</td>\n      <td>8129.0</td>\n      <td>5751.0</td>\n      <td>0.707467</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>1</td>\n      <td>0.75</td>\n      <td>9212.0</td>\n      <td>6937.0</td>\n      <td>0.753040</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>1</td>\n      <td>0.80</td>\n      <td>9731.0</td>\n      <td>7697.0</td>\n      <td>0.790977</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>1</td>\n      <td>0.85</td>\n      <td>10655.0</td>\n      <td>8987.0</td>\n      <td>0.843454</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>1</td>\n      <td>0.90</td>\n      <td>11170.0</td>\n      <td>10108.0</td>\n      <td>0.904924</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>1</td>\n      <td>0.95</td>\n      <td>13981.0</td>\n      <td>13437.0</td>\n      <td>0.961090</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>1</td>\n      <td>1.00</td>\n      <td>13584.0</td>\n      <td>13500.0</td>\n      <td>0.993816</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>2</td>\n      <td>0.00</td>\n      <td>24279.0</td>\n      <td>99.0</td>\n      <td>0.004078</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>2</td>\n      <td>0.05</td>\n      <td>19178.0</td>\n      <td>784.0</td>\n      <td>0.040880</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>2</td>\n      <td>0.10</td>\n      <td>13734.0</td>\n      <td>1370.0</td>\n      <td>0.099752</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>2</td>\n      <td>0.15</td>\n      <td>10834.0</td>\n      <td>1628.0</td>\n      <td>0.150268</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>2</td>\n      <td>0.20</td>\n      <td>9308.0</td>\n      <td>1889.0</td>\n      <td>0.202944</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>2</td>\n      <td>0.25</td>\n      <td>8199.0</td>\n      <td>2146.0</td>\n      <td>0.261739</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>2</td>\n      <td>0.30</td>\n      <td>7447.0</td>\n      <td>2226.0</td>\n      <td>0.298912</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>2</td>\n      <td>0.35</td>\n      <td>7529.0</td>\n      <td>2544.0</td>\n      <td>0.337893</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>2</td>\n      <td>0.40</td>\n      <td>6615.0</td>\n      <td>2605.0</td>\n      <td>0.393802</td>\n    </tr>\n    <tr>\n      <th>30</th>\n      <td>2</td>\n      <td>0.45</td>\n      <td>6309.0</td>\n      <td>2780.0</td>\n      <td>0.440640</td>\n    </tr>\n    <tr>\n      <th>31</th>\n      <td>2</td>\n      <td>0.50</td>\n      <td>6224.0</td>\n      <td>3176.0</td>\n      <td>0.510283</td>\n    </tr>\n    <tr>\n      <th>32</th>\n      <td>2</td>\n      <td>0.55</td>\n      <td>6609.0</td>\n      <td>3600.0</td>\n      <td>0.544712</td>\n    </tr>\n    <tr>\n      <th>33</th>\n      <td>2</td>\n      <td>0.60</td>\n      <td>6888.0</td>\n      <td>4286.0</td>\n      <td>0.622242</td>\n    </tr>\n    <tr>\n      <th>34</th>\n      <td>2</td>\n      <td>0.65</td>\n      <td>7700.0</td>\n      <td>4975.0</td>\n      <td>0.646104</td>\n    </tr>\n    <tr>\n      <th>35</th>\n      <td>2</td>\n      <td>0.70</td>\n      <td>8082.0</td>\n      <td>5685.0</td>\n      <td>0.703415</td>\n    </tr>\n    <tr>\n      <th>36</th>\n      <td>2</td>\n      <td>0.75</td>\n      <td>8224.0</td>\n      <td>6164.0</td>\n      <td>0.749514</td>\n    </tr>\n    <tr>\n      <th>37</th>\n      <td>2</td>\n      <td>0.80</td>\n      <td>8951.0</td>\n      <td>7075.0</td>\n      <td>0.790414</td>\n    </tr>\n    <tr>\n      <th>38</th>\n      <td>2</td>\n      <td>0.85</td>\n      <td>10528.0</td>\n      <td>8929.0</td>\n      <td>0.848119</td>\n    </tr>\n    <tr>\n      <th>39</th>\n      <td>2</td>\n      <td>0.90</td>\n      <td>13933.0</td>\n      <td>12546.0</td>\n      <td>0.900452</td>\n    </tr>\n    <tr>\n      <th>40</th>\n      <td>2</td>\n      <td>0.95</td>\n      <td>17790.0</td>\n      <td>17095.0</td>\n      <td>0.960933</td>\n    </tr>\n    <tr>\n      <th>41</th>\n      <td>2</td>\n      <td>1.00</td>\n      <td>23880.0</td>\n      <td>23765.0</td>\n      <td>0.995184</td>\n    </tr>\n    <tr>\n      <th>42</th>\n      <td>3</td>\n      <td>0.00</td>\n      <td>36908.0</td>\n      <td>143.0</td>\n      <td>0.003874</td>\n    </tr>\n    <tr>\n      <th>43</th>\n      <td>3</td>\n      <td>0.05</td>\n      <td>15314.0</td>\n      <td>612.0</td>\n      <td>0.039963</td>\n    </tr>\n    <tr>\n      <th>44</th>\n      <td>3</td>\n      <td>0.10</td>\n      <td>9229.0</td>\n      <td>803.0</td>\n      <td>0.087008</td>\n    </tr>\n    <tr>\n      <th>45</th>\n      <td>3</td>\n      <td>0.15</td>\n      <td>6305.0</td>\n      <td>905.0</td>\n      <td>0.143537</td>\n    </tr>\n    <tr>\n      <th>46</th>\n      <td>3</td>\n      <td>0.20</td>\n      <td>5809.0</td>\n      <td>1181.0</td>\n      <td>0.203305</td>\n    </tr>\n    <tr>\n      <th>47</th>\n      <td>3</td>\n      <td>0.25</td>\n      <td>5527.0</td>\n      <td>1347.0</td>\n      <td>0.243713</td>\n    </tr>\n    <tr>\n      <th>48</th>\n      <td>3</td>\n      <td>0.30</td>\n      <td>5185.0</td>\n      <td>1569.0</td>\n      <td>0.302604</td>\n    </tr>\n    <tr>\n      <th>49</th>\n      <td>3</td>\n      <td>0.35</td>\n      <td>5071.0</td>\n      <td>1818.0</td>\n      <td>0.358509</td>\n    </tr>\n    <tr>\n      <th>50</th>\n      <td>3</td>\n      <td>0.40</td>\n      <td>4501.0</td>\n      <td>1835.0</td>\n      <td>0.407687</td>\n    </tr>\n    <tr>\n      <th>51</th>\n      <td>3</td>\n      <td>0.45</td>\n      <td>4629.0</td>\n      <td>2053.0</td>\n      <td>0.443508</td>\n    </tr>\n    <tr>\n      <th>52</th>\n      <td>3</td>\n      <td>0.50</td>\n      <td>4512.0</td>\n      <td>2261.0</td>\n      <td>0.501108</td>\n    </tr>\n    <tr>\n      <th>53</th>\n      <td>3</td>\n      <td>0.55</td>\n      <td>4742.0</td>\n      <td>2525.0</td>\n      <td>0.532476</td>\n    </tr>\n    <tr>\n      <th>54</th>\n      <td>3</td>\n      <td>0.60</td>\n      <td>4860.0</td>\n      <td>2852.0</td>\n      <td>0.586831</td>\n    </tr>\n    <tr>\n      <th>55</th>\n      <td>3</td>\n      <td>0.65</td>\n      <td>5458.0</td>\n      <td>3537.0</td>\n      <td>0.648040</td>\n    </tr>\n    <tr>\n      <th>56</th>\n      <td>3</td>\n      <td>0.70</td>\n      <td>5753.0</td>\n      <td>3997.0</td>\n      <td>0.694768</td>\n    </tr>\n    <tr>\n      <th>57</th>\n      <td>3</td>\n      <td>0.75</td>\n      <td>5593.0</td>\n      <td>4309.0</td>\n      <td>0.770427</td>\n    </tr>\n    <tr>\n      <th>58</th>\n      <td>3</td>\n      <td>0.80</td>\n      <td>5603.0</td>\n      <td>4498.0</td>\n      <td>0.802784</td>\n    </tr>\n    <tr>\n      <th>59</th>\n      <td>3</td>\n      <td>0.85</td>\n      <td>6372.0</td>\n      <td>5508.0</td>\n      <td>0.864407</td>\n    </tr>\n    <tr>\n      <th>60</th>\n      <td>3</td>\n      <td>0.90</td>\n      <td>8816.0</td>\n      <td>8022.0</td>\n      <td>0.909936</td>\n    </tr>\n    <tr>\n      <th>61</th>\n      <td>3</td>\n      <td>0.95</td>\n      <td>15604.0</td>\n      <td>15046.0</td>\n      <td>0.964240</td>\n    </tr>\n    <tr>\n      <th>62</th>\n      <td>3</td>\n      <td>1.00</td>\n      <td>34933.0</td>\n      <td>34756.0</td>\n      <td>0.994933</td>\n    </tr>\n    <tr>\n      <th>63</th>\n      <td>4</td>\n      <td>0.00</td>\n      <td>55901.0</td>\n      <td>89.0</td>\n      <td>0.001592</td>\n    </tr>\n    <tr>\n      <th>64</th>\n      <td>4</td>\n      <td>0.05</td>\n      <td>12839.0</td>\n      <td>499.0</td>\n      <td>0.038866</td>\n    </tr>\n    <tr>\n      <th>65</th>\n      <td>4</td>\n      <td>0.10</td>\n      <td>7279.0</td>\n      <td>665.0</td>\n      <td>0.091359</td>\n    </tr>\n    <tr>\n      <th>66</th>\n      <td>4</td>\n      <td>0.15</td>\n      <td>5518.0</td>\n      <td>785.0</td>\n      <td>0.142262</td>\n    </tr>\n    <tr>\n      <th>67</th>\n      <td>4</td>\n      <td>0.20</td>\n      <td>4392.0</td>\n      <td>835.0</td>\n      <td>0.190118</td>\n    </tr>\n    <tr>\n      <th>68</th>\n      <td>4</td>\n      <td>0.25</td>\n      <td>3967.0</td>\n      <td>1022.0</td>\n      <td>0.257625</td>\n    </tr>\n    <tr>\n      <th>69</th>\n      <td>4</td>\n      <td>0.30</td>\n      <td>3624.0</td>\n      <td>1072.0</td>\n      <td>0.295806</td>\n    </tr>\n    <tr>\n      <th>70</th>\n      <td>4</td>\n      <td>0.35</td>\n      <td>3267.0</td>\n      <td>1167.0</td>\n      <td>0.357208</td>\n    </tr>\n    <tr>\n      <th>71</th>\n      <td>4</td>\n      <td>0.40</td>\n      <td>3168.0</td>\n      <td>1356.0</td>\n      <td>0.428030</td>\n    </tr>\n    <tr>\n      <th>72</th>\n      <td>4</td>\n      <td>0.45</td>\n      <td>2950.0</td>\n      <td>1339.0</td>\n      <td>0.453898</td>\n    </tr>\n    <tr>\n      <th>73</th>\n      <td>4</td>\n      <td>0.50</td>\n      <td>2992.0</td>\n      <td>1486.0</td>\n      <td>0.496658</td>\n    </tr>\n    <tr>\n      <th>74</th>\n      <td>4</td>\n      <td>0.55</td>\n      <td>3178.0</td>\n      <td>1696.0</td>\n      <td>0.533669</td>\n    </tr>\n    <tr>\n      <th>75</th>\n      <td>4</td>\n      <td>0.60</td>\n      <td>3342.0</td>\n      <td>1971.0</td>\n      <td>0.589767</td>\n    </tr>\n    <tr>\n      <th>76</th>\n      <td>4</td>\n      <td>0.65</td>\n      <td>3492.0</td>\n      <td>2229.0</td>\n      <td>0.638316</td>\n    </tr>\n    <tr>\n      <th>77</th>\n      <td>4</td>\n      <td>0.70</td>\n      <td>3476.0</td>\n      <td>2481.0</td>\n      <td>0.713751</td>\n    </tr>\n    <tr>\n      <th>78</th>\n      <td>4</td>\n      <td>0.75</td>\n      <td>3682.0</td>\n      <td>2776.0</td>\n      <td>0.753938</td>\n    </tr>\n    <tr>\n      <th>79</th>\n      <td>4</td>\n      <td>0.80</td>\n      <td>4153.0</td>\n      <td>3362.0</td>\n      <td>0.809535</td>\n    </tr>\n    <tr>\n      <th>80</th>\n      <td>4</td>\n      <td>0.85</td>\n      <td>5210.0</td>\n      <td>4466.0</td>\n      <td>0.857198</td>\n    </tr>\n    <tr>\n      <th>81</th>\n      <td>4</td>\n      <td>0.90</td>\n      <td>7177.0</td>\n      <td>6459.0</td>\n      <td>0.899958</td>\n    </tr>\n    <tr>\n      <th>82</th>\n      <td>4</td>\n      <td>0.95</td>\n      <td>12810.0</td>\n      <td>12316.0</td>\n      <td>0.961436</td>\n    </tr>\n    <tr>\n      <th>83</th>\n      <td>4</td>\n      <td>1.00</td>\n      <td>55440.0</td>\n      <td>55337.0</td>\n      <td>0.998142</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\norganized['cal_diff'] = abs(organized.bin_pred_prob - organized.bin_actual_prob)\norganized\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>period</th>\n      <th>bin_pred_prob</th>\n      <th>n_plays</th>\n      <th>n_wins</th>\n      <th>bin_actual_prob</th>\n      <th>cal_diff</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>0.00</td>\n      <td>15064.0</td>\n      <td>65.0</td>\n      <td>0.004315</td>\n      <td>0.004315</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>0.05</td>\n      <td>13636.0</td>\n      <td>656.0</td>\n      <td>0.048108</td>\n      <td>0.001892</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1</td>\n      <td>0.10</td>\n      <td>10373.0</td>\n      <td>939.0</td>\n      <td>0.090523</td>\n      <td>0.009477</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1</td>\n      <td>0.15</td>\n      <td>9494.0</td>\n      <td>1380.0</td>\n      <td>0.145355</td>\n      <td>0.004645</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1</td>\n      <td>0.20</td>\n      <td>10012.0</td>\n      <td>2041.0</td>\n      <td>0.203855</td>\n      <td>0.003855</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>1</td>\n      <td>0.25</td>\n      <td>9238.0</td>\n      <td>2451.0</td>\n      <td>0.265317</td>\n      <td>0.015317</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>1</td>\n      <td>0.30</td>\n      <td>8494.0</td>\n      <td>2475.0</td>\n      <td>0.291382</td>\n      <td>0.008618</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>1</td>\n      <td>0.35</td>\n      <td>7565.0</td>\n      <td>2675.0</td>\n      <td>0.353602</td>\n      <td>0.003602</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>1</td>\n      <td>0.40</td>\n      <td>7659.0</td>\n      <td>3016.0</td>\n      <td>0.393785</td>\n      <td>0.006215</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>1</td>\n      <td>0.45</td>\n      <td>7285.0</td>\n      <td>3277.0</td>\n      <td>0.449828</td>\n      <td>0.000172</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>1</td>\n      <td>0.50</td>\n      <td>7239.0</td>\n      <td>3569.0</td>\n      <td>0.493024</td>\n      <td>0.006976</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>1</td>\n      <td>0.55</td>\n      <td>7439.0</td>\n      <td>4192.0</td>\n      <td>0.563517</td>\n      <td>0.013517</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>1</td>\n      <td>0.60</td>\n      <td>7752.0</td>\n      <td>4676.0</td>\n      <td>0.603199</td>\n      <td>0.003199</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>1</td>\n      <td>0.65</td>\n      <td>7279.0</td>\n      <td>4677.0</td>\n      <td>0.642533</td>\n      <td>0.007467</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>1</td>\n      <td>0.70</td>\n      <td>8129.0</td>\n      <td>5751.0</td>\n      <td>0.707467</td>\n      <td>0.007467</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>1</td>\n      <td>0.75</td>\n      <td>9212.0</td>\n      <td>6937.0</td>\n      <td>0.753040</td>\n      <td>0.003040</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>1</td>\n      <td>0.80</td>\n      <td>9731.0</td>\n      <td>7697.0</td>\n      <td>0.790977</td>\n      <td>0.009023</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>1</td>\n      <td>0.85</td>\n      <td>10655.0</td>\n      <td>8987.0</td>\n      <td>0.843454</td>\n      <td>0.006546</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>1</td>\n      <td>0.90</td>\n      <td>11170.0</td>\n      <td>10108.0</td>\n      <td>0.904924</td>\n      <td>0.004924</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>1</td>\n      <td>0.95</td>\n      <td>13981.0</td>\n      <td>13437.0</td>\n      <td>0.961090</td>\n      <td>0.011090</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>1</td>\n      <td>1.00</td>\n      <td>13584.0</td>\n      <td>13500.0</td>\n      <td>0.993816</td>\n      <td>0.006184</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>2</td>\n      <td>0.00</td>\n      <td>24279.0</td>\n      <td>99.0</td>\n      <td>0.004078</td>\n      <td>0.004078</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>2</td>\n      <td>0.05</td>\n      <td>19178.0</td>\n      <td>784.0</td>\n      <td>0.040880</td>\n      <td>0.009120</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>2</td>\n      <td>0.10</td>\n      <td>13734.0</td>\n      <td>1370.0</td>\n      <td>0.099752</td>\n      <td>0.000248</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>2</td>\n      <td>0.15</td>\n      <td>10834.0</td>\n      <td>1628.0</td>\n      <td>0.150268</td>\n      <td>0.000268</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>2</td>\n      <td>0.20</td>\n      <td>9308.0</td>\n      <td>1889.0</td>\n      <td>0.202944</td>\n      <td>0.002944</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>2</td>\n      <td>0.25</td>\n      <td>8199.0</td>\n      <td>2146.0</td>\n      <td>0.261739</td>\n      <td>0.011739</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>2</td>\n      <td>0.30</td>\n      <td>7447.0</td>\n      <td>2226.0</td>\n      <td>0.298912</td>\n      <td>0.001088</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>2</td>\n      <td>0.35</td>\n      <td>7529.0</td>\n      <td>2544.0</td>\n      <td>0.337893</td>\n      <td>0.012107</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>2</td>\n      <td>0.40</td>\n      <td>6615.0</td>\n      <td>2605.0</td>\n      <td>0.393802</td>\n      <td>0.006198</td>\n    </tr>\n    <tr>\n      <th>30</th>\n      <td>2</td>\n      <td>0.45</td>\n      <td>6309.0</td>\n      <td>2780.0</td>\n      <td>0.440640</td>\n      <td>0.009360</td>\n    </tr>\n    <tr>\n      <th>31</th>\n      <td>2</td>\n      <td>0.50</td>\n      <td>6224.0</td>\n      <td>3176.0</td>\n      <td>0.510283</td>\n      <td>0.010283</td>\n    </tr>\n    <tr>\n      <th>32</th>\n      <td>2</td>\n      <td>0.55</td>\n      <td>6609.0</td>\n      <td>3600.0</td>\n      <td>0.544712</td>\n      <td>0.005288</td>\n    </tr>\n    <tr>\n      <th>33</th>\n      <td>2</td>\n      <td>0.60</td>\n      <td>6888.0</td>\n      <td>4286.0</td>\n      <td>0.622242</td>\n      <td>0.022242</td>\n    </tr>\n    <tr>\n      <th>34</th>\n      <td>2</td>\n      <td>0.65</td>\n      <td>7700.0</td>\n      <td>4975.0</td>\n      <td>0.646104</td>\n      <td>0.003896</td>\n    </tr>\n    <tr>\n      <th>35</th>\n      <td>2</td>\n      <td>0.70</td>\n      <td>8082.0</td>\n      <td>5685.0</td>\n      <td>0.703415</td>\n      <td>0.003415</td>\n    </tr>\n    <tr>\n      <th>36</th>\n      <td>2</td>\n      <td>0.75</td>\n      <td>8224.0</td>\n      <td>6164.0</td>\n      <td>0.749514</td>\n      <td>0.000486</td>\n    </tr>\n    <tr>\n      <th>37</th>\n      <td>2</td>\n      <td>0.80</td>\n      <td>8951.0</td>\n      <td>7075.0</td>\n      <td>0.790414</td>\n      <td>0.009586</td>\n    </tr>\n    <tr>\n      <th>38</th>\n      <td>2</td>\n      <td>0.85</td>\n      <td>10528.0</td>\n      <td>8929.0</td>\n      <td>0.848119</td>\n      <td>0.001881</td>\n    </tr>\n    <tr>\n      <th>39</th>\n      <td>2</td>\n      <td>0.90</td>\n      <td>13933.0</td>\n      <td>12546.0</td>\n      <td>0.900452</td>\n      <td>0.000452</td>\n    </tr>\n    <tr>\n      <th>40</th>\n      <td>2</td>\n      <td>0.95</td>\n      <td>17790.0</td>\n      <td>17095.0</td>\n      <td>0.960933</td>\n      <td>0.010933</td>\n    </tr>\n    <tr>\n      <th>41</th>\n      <td>2</td>\n      <td>1.00</td>\n      <td>23880.0</td>\n      <td>23765.0</td>\n      <td>0.995184</td>\n      <td>0.004816</td>\n    </tr>\n    <tr>\n      <th>42</th>\n      <td>3</td>\n      <td>0.00</td>\n      <td>36908.0</td>\n      <td>143.0</td>\n      <td>0.003874</td>\n      <td>0.003874</td>\n    </tr>\n    <tr>\n      <th>43</th>\n      <td>3</td>\n      <td>0.05</td>\n      <td>15314.0</td>\n      <td>612.0</td>\n      <td>0.039963</td>\n      <td>0.010037</td>\n    </tr>\n    <tr>\n      <th>44</th>\n      <td>3</td>\n      <td>0.10</td>\n      <td>9229.0</td>\n      <td>803.0</td>\n      <td>0.087008</td>\n      <td>0.012992</td>\n    </tr>\n    <tr>\n      <th>45</th>\n      <td>3</td>\n      <td>0.15</td>\n      <td>6305.0</td>\n      <td>905.0</td>\n      <td>0.143537</td>\n      <td>0.006463</td>\n    </tr>\n    <tr>\n      <th>46</th>\n      <td>3</td>\n      <td>0.20</td>\n      <td>5809.0</td>\n      <td>1181.0</td>\n      <td>0.203305</td>\n      <td>0.003305</td>\n    </tr>\n    <tr>\n      <th>47</th>\n      <td>3</td>\n      <td>0.25</td>\n      <td>5527.0</td>\n      <td>1347.0</td>\n      <td>0.243713</td>\n      <td>0.006287</td>\n    </tr>\n    <tr>\n      <th>48</th>\n      <td>3</td>\n      <td>0.30</td>\n      <td>5185.0</td>\n      <td>1569.0</td>\n      <td>0.302604</td>\n      <td>0.002604</td>\n    </tr>\n    <tr>\n      <th>49</th>\n      <td>3</td>\n      <td>0.35</td>\n      <td>5071.0</td>\n      <td>1818.0</td>\n      <td>0.358509</td>\n      <td>0.008509</td>\n    </tr>\n    <tr>\n      <th>50</th>\n      <td>3</td>\n      <td>0.40</td>\n      <td>4501.0</td>\n      <td>1835.0</td>\n      <td>0.407687</td>\n      <td>0.007687</td>\n    </tr>\n    <tr>\n      <th>51</th>\n      <td>3</td>\n      <td>0.45</td>\n      <td>4629.0</td>\n      <td>2053.0</td>\n      <td>0.443508</td>\n      <td>0.006492</td>\n    </tr>\n    <tr>\n      <th>52</th>\n      <td>3</td>\n      <td>0.50</td>\n      <td>4512.0</td>\n      <td>2261.0</td>\n      <td>0.501108</td>\n      <td>0.001108</td>\n    </tr>\n    <tr>\n      <th>53</th>\n      <td>3</td>\n      <td>0.55</td>\n      <td>4742.0</td>\n      <td>2525.0</td>\n      <td>0.532476</td>\n      <td>0.017524</td>\n    </tr>\n    <tr>\n      <th>54</th>\n      <td>3</td>\n      <td>0.60</td>\n      <td>4860.0</td>\n      <td>2852.0</td>\n      <td>0.586831</td>\n      <td>0.013169</td>\n    </tr>\n    <tr>\n      <th>55</th>\n      <td>3</td>\n      <td>0.65</td>\n      <td>5458.0</td>\n      <td>3537.0</td>\n      <td>0.648040</td>\n      <td>0.001960</td>\n    </tr>\n    <tr>\n      <th>56</th>\n      <td>3</td>\n      <td>0.70</td>\n      <td>5753.0</td>\n      <td>3997.0</td>\n      <td>0.694768</td>\n      <td>0.005232</td>\n    </tr>\n    <tr>\n      <th>57</th>\n      <td>3</td>\n      <td>0.75</td>\n      <td>5593.0</td>\n      <td>4309.0</td>\n      <td>0.770427</td>\n      <td>0.020427</td>\n    </tr>\n    <tr>\n      <th>58</th>\n      <td>3</td>\n      <td>0.80</td>\n      <td>5603.0</td>\n      <td>4498.0</td>\n      <td>0.802784</td>\n      <td>0.002784</td>\n    </tr>\n    <tr>\n      <th>59</th>\n      <td>3</td>\n      <td>0.85</td>\n      <td>6372.0</td>\n      <td>5508.0</td>\n      <td>0.864407</td>\n      <td>0.014407</td>\n    </tr>\n    <tr>\n      <th>60</th>\n      <td>3</td>\n      <td>0.90</td>\n      <td>8816.0</td>\n      <td>8022.0</td>\n      <td>0.909936</td>\n      <td>0.009936</td>\n    </tr>\n    <tr>\n      <th>61</th>\n      <td>3</td>\n      <td>0.95</td>\n      <td>15604.0</td>\n      <td>15046.0</td>\n      <td>0.964240</td>\n      <td>0.014240</td>\n    </tr>\n    <tr>\n      <th>62</th>\n      <td>3</td>\n      <td>1.00</td>\n      <td>34933.0</td>\n      <td>34756.0</td>\n      <td>0.994933</td>\n      <td>0.005067</td>\n    </tr>\n    <tr>\n      <th>63</th>\n      <td>4</td>\n      <td>0.00</td>\n      <td>55901.0</td>\n      <td>89.0</td>\n      <td>0.001592</td>\n      <td>0.001592</td>\n    </tr>\n    <tr>\n      <th>64</th>\n      <td>4</td>\n      <td>0.05</td>\n      <td>12839.0</td>\n      <td>499.0</td>\n      <td>0.038866</td>\n      <td>0.011134</td>\n    </tr>\n    <tr>\n      <th>65</th>\n      <td>4</td>\n      <td>0.10</td>\n      <td>7279.0</td>\n      <td>665.0</td>\n      <td>0.091359</td>\n      <td>0.008641</td>\n    </tr>\n    <tr>\n      <th>66</th>\n      <td>4</td>\n      <td>0.15</td>\n      <td>5518.0</td>\n      <td>785.0</td>\n      <td>0.142262</td>\n      <td>0.007738</td>\n    </tr>\n    <tr>\n      <th>67</th>\n      <td>4</td>\n      <td>0.20</td>\n      <td>4392.0</td>\n      <td>835.0</td>\n      <td>0.190118</td>\n      <td>0.009882</td>\n    </tr>\n    <tr>\n      <th>68</th>\n      <td>4</td>\n      <td>0.25</td>\n      <td>3967.0</td>\n      <td>1022.0</td>\n      <td>0.257625</td>\n      <td>0.007625</td>\n    </tr>\n    <tr>\n      <th>69</th>\n      <td>4</td>\n      <td>0.30</td>\n      <td>3624.0</td>\n      <td>1072.0</td>\n      <td>0.295806</td>\n      <td>0.004194</td>\n    </tr>\n    <tr>\n      <th>70</th>\n      <td>4</td>\n      <td>0.35</td>\n      <td>3267.0</td>\n      <td>1167.0</td>\n      <td>0.357208</td>\n      <td>0.007208</td>\n    </tr>\n    <tr>\n      <th>71</th>\n      <td>4</td>\n      <td>0.40</td>\n      <td>3168.0</td>\n      <td>1356.0</td>\n      <td>0.428030</td>\n      <td>0.028030</td>\n    </tr>\n    <tr>\n      <th>72</th>\n      <td>4</td>\n      <td>0.45</td>\n      <td>2950.0</td>\n      <td>1339.0</td>\n      <td>0.453898</td>\n      <td>0.003898</td>\n    </tr>\n    <tr>\n      <th>73</th>\n      <td>4</td>\n      <td>0.50</td>\n      <td>2992.0</td>\n      <td>1486.0</td>\n      <td>0.496658</td>\n      <td>0.003342</td>\n    </tr>\n    <tr>\n      <th>74</th>\n      <td>4</td>\n      <td>0.55</td>\n      <td>3178.0</td>\n      <td>1696.0</td>\n      <td>0.533669</td>\n      <td>0.016331</td>\n    </tr>\n    <tr>\n      <th>75</th>\n      <td>4</td>\n      <td>0.60</td>\n      <td>3342.0</td>\n      <td>1971.0</td>\n      <td>0.589767</td>\n      <td>0.010233</td>\n    </tr>\n    <tr>\n      <th>76</th>\n      <td>4</td>\n      <td>0.65</td>\n      <td>3492.0</td>\n      <td>2229.0</td>\n      <td>0.638316</td>\n      <td>0.011684</td>\n    </tr>\n    <tr>\n      <th>77</th>\n      <td>4</td>\n      <td>0.70</td>\n      <td>3476.0</td>\n      <td>2481.0</td>\n      <td>0.713751</td>\n      <td>0.013751</td>\n    </tr>\n    <tr>\n      <th>78</th>\n      <td>4</td>\n      <td>0.75</td>\n      <td>3682.0</td>\n      <td>2776.0</td>\n      <td>0.753938</td>\n      <td>0.003938</td>\n    </tr>\n    <tr>\n      <th>79</th>\n      <td>4</td>\n      <td>0.80</td>\n      <td>4153.0</td>\n      <td>3362.0</td>\n      <td>0.809535</td>\n      <td>0.009535</td>\n    </tr>\n    <tr>\n      <th>80</th>\n      <td>4</td>\n      <td>0.85</td>\n      <td>5210.0</td>\n      <td>4466.0</td>\n      <td>0.857198</td>\n      <td>0.007198</td>\n    </tr>\n    <tr>\n      <th>81</th>\n      <td>4</td>\n      <td>0.90</td>\n      <td>7177.0</td>\n      <td>6459.0</td>\n      <td>0.899958</td>\n      <td>0.000042</td>\n    </tr>\n    <tr>\n      <th>82</th>\n      <td>4</td>\n      <td>0.95</td>\n      <td>12810.0</td>\n      <td>12316.0</td>\n      <td>0.961436</td>\n      <td>0.011436</td>\n    </tr>\n    <tr>\n      <th>83</th>\n      <td>4</td>\n      <td>1.00</td>\n      <td>55440.0</td>\n      <td>55337.0</td>\n      <td>0.998142</td>\n      <td>0.001858</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndef organize_cal_err(grp):\n    d = {}\n    d['weight_cal_err'] = np.average(grp.cal_diff, weights=grp.n_plays)\n    d['n_wins'] = sum(grp.n_wins)\n    return pd.Series(d, index=['weight_cal_err', 'n_wins'])\n\ncv_cal_error = organized.groupby('period')\nfinal_cal_error = cv_cal_error.apply(organize_cal_err)\nfinal_cal_error = final_cal_error.reset_index()\nfinal_cal_error\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>period</th>\n      <th>weight_cal_err</th>\n      <th>n_wins</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>0.006503</td>\n      <td>102506.0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2</td>\n      <td>0.005763</td>\n      <td>115367.0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>3</td>\n      <td>0.007642</td>\n      <td>99577.0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>4</td>\n      <td>0.005178</td>\n      <td>103408.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nweighted_cal_err_final = np.average(final_cal_error.weight_cal_err, weights=final_cal_error.n_wins)\nprint(f\"Weighted calibration error: {weighted_cal_err_final}\")\n```\n\n    Weighted calibration error: 0.00624410573370445\n\n\n\n```python\nimport sys\n!{sys.executable} -m pip install coremltools==4.0\n```\n\n    Requirement already satisfied: coremltools==4.0 in /Users/akeaswaran/anaconda3/lib/python3.7/site-packages (4.0)\n    Requirement already satisfied: tqdm in /Users/akeaswaran/anaconda3/lib/python3.7/site-packages (from coremltools==4.0) (4.54.0)\n    Requirement already satisfied: scipy in /Users/akeaswaran/anaconda3/lib/python3.7/site-packages (from coremltools==4.0) (1.5.3)\n    Requirement already satisfied: attr in /Users/akeaswaran/anaconda3/lib/python3.7/site-packages (from coremltools==4.0) (0.3.1)\n    Requirement already satisfied: packaging in /Users/akeaswaran/anaconda3/lib/python3.7/site-packages (from coremltools==4.0) (20.4)\n    Requirement already satisfied: protobuf>=3.1.0 in /Users/akeaswaran/anaconda3/lib/python3.7/site-packages (from coremltools==4.0) (3.13.0)\n    Requirement already satisfied: sympy in /Users/akeaswaran/anaconda3/lib/python3.7/site-packages (from coremltools==4.0) (1.7)\n    Requirement already satisfied: numpy>=1.14.5 in /Users/akeaswaran/anaconda3/lib/python3.7/site-packages (from coremltools==4.0) (1.19.4)\n    Requirement already satisfied: attrs in /Users/akeaswaran/anaconda3/lib/python3.7/site-packages (from coremltools==4.0) (20.3.0)\n    Requirement already satisfied: six>=1.10.0 in /Users/akeaswaran/anaconda3/lib/python3.7/site-packages (from coremltools==4.0) (1.15.0)\n    Requirement already satisfied: pyparsing>=2.0.2 in /Users/akeaswaran/anaconda3/lib/python3.7/site-packages (from packaging->coremltools==4.0) (2.4.7)\n    Requirement already satisfied: setuptools in /Users/akeaswaran/anaconda3/lib/python3.7/site-packages (from protobuf>=3.1.0->coremltools==4.0) (49.6.0.post20201009)\n    Requirement already satisfied: mpmath>=0.19 in /Users/akeaswaran/anaconda3/lib/python3.7/site-packages (from sympy->coremltools==4.0) (1.1.0)\n\n\n\n```python\n# # CoreML model\nimport coremltools as cml\n# print(cml.version)\n\ncml_inputs = {\n    \"pos_team_receives_2H_kickoff\" : \"If the current offense will receive the second half kickoff\",\n    \"spread_time\" : \"The number of points that the offense is favored by, scaled by e^x, where x is the elapsed portion of the game ((3600 - adj_TimeSecsRem) / 3600)\",\n    \"TimeSecsRem\" : \"The number of seconds left in the half.\",\n    \"adj_TimeSecsRem\" : \"The number of seconds left in the game.\",\n    \"ExpScoreDiff_Time_Ratio\" : \"The expected point differential divided by the number of seconds remaining in the game (plus 1).\",\n    \"pos_score_diff_start\" : \"The current difference in score from the offense's perspective.\",\n    \"down\" : \"The current down.\",\n    \"distance\" : \"How many yards the offense must gain for a first down.\",\n    \"yards_to_goal\" : \"The yards left until the current offense reaches the goal line.\",\n    \"is_home\" : \"If the current offense is the home team\",\n    \"pos_team_timeouts_rem_before\" : \"How many timeouts the current offense has remaining\",\n    \"def_pos_team_timeouts_rem_before\" : \"How many timeouts the current defense has remaining\",\n    \"period\" : \"The current quarter.\"\n}\n\ntarget_outputs = {\n    \"column\" : \"win_indicator\",\n    \"description\" : \"The probability of the current offense winning the game.\"\n}\n\ndef create_coreml_model(xgb_model, author, description, input_details, target_details, file_name):\n    cml_model = cml.converters.xgboost.convert(xgb_model, mode=\"regressor\", target=target_details['column'])\n\n    cml_model.author = author#'Ben Baldwin (@benbbaldwin on Twitter, @guga31bb on GitHub) and Sebastian Carl (@mrcaseb on Twitter/GitHub) for model creation code; Saiem Gilani and Meyappan Subbiah for cfbscrapR training data; Akshay Easwaran for Python port.'\n    cml_model.license = 'MIT'\n    cml_model.short_description = description #''\n\n    # Set feature descriptions manually\n    for (column, desc) in input_details.items():\n        cml_model.input_description[column] = desc\n\n    # Set the output descriptions\n    cml_model.output_description[target_details['column']] = target_details['description']\n\n    # Save the model\n    cml_model.save(f'{file_name}.mlmodel')\n#     cml_model.get_spec()\n    return cml_model\n    \ncoreml_mdl_file = create_coreml_model(wp_model, \"Ben Baldwin (@benbbaldwin on Twitter, @guga31bb on GitHub) and Sebastian Carl (@mrcaseb on Twitter/GitHub) for model creation code; Saiem Gilani and Meyappan Subbiah for cfbscrapR training data; Akshay Easwaran for Python port.\", \"Predicts the win probability of the offense for a given play. Translated from R, original model available as part of https://github.com/mrcaseb/nflfastR/.\", cml_inputs, target_outputs, target_file_name)\n# coreml_mdl_file.get_spec()\n```\n\n    WARNING:root:scikit-learn version 0.23.0 is not supported. Minimum required version: 0.17. Maximum required version: 0.19.2. Disabling scikit-learn conversion API.\n\n\n\n```python\n# test_json = pd.read_json(\"wp_xgb_dump.json\")\n# test_json.head()\n```\n\n\n```python\n# len(test_json[test_json['split_condition'].isna()])\n```\n\n\n```python\ngrouped_plays = base_data[(base_data.down < 5) & (base_data.period < 5) & (~((base_data.play_text.str.contains(\"penalty\")) | (base_data.play_text.str.contains(\"PENALTY\"))))].groupby('play_type')\nselected_groups = [\"Passing Touchdown\",\"Fumble Return Touchdown\",\"Rushing Touchdown\",\"Pass Completion\",\"Field Goal Good\",\"Pass Interception\",\"Pass Incompletion\",\"Rush\",\"Field Goal Missed\",\"Punt\",\"Safety\",\"Sack\"]\ncomposite_df = grouped_plays.apply(lambda x: x.sample(1)).reset_index(drop=True)\nselection = composite_df[composite_df.play_type.isin(selected_groups)]\nselection['time_spent'] = selection.TimeSecsRem - selection.TimeSecsRem_end\n\ncols = [\"id_play\", \"pos_team\", \"def_pos_team\", \"home\", \"away\", \"offense_score\",\"defense_score\",\"play_type\",\"play_text\",\"clock.minutes\",\"clock.seconds\",\"time_spent\"] + model_columns_before + [\"ep_before\",\"ep_after\",\"EPA\",\"WP_NFL_start\",\"WP_NFL_end\",\"WPA_NFL\"]\n\nselection[cols].to_json(\"./wpa-model-test-items.json\", orient=\"records\")\nselection\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "e28a0153c871ba08792164f0254bb89239feadab", "size": 1027784, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "cfbscrapR-wpa.ipynb", "max_stars_repo_name": "akeaswaran/cfb-pbp-analysis", "max_stars_repo_head_hexsha": "8209c0a731a1abf7abd2dd2165c8abeab8587130", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-29T02:40:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T02:40:41.000Z", "max_issues_repo_path": "cfbscrapR-wpa.ipynb", "max_issues_repo_name": "akeaswaran/cfb-pbp-analysis", "max_issues_repo_head_hexsha": "8209c0a731a1abf7abd2dd2165c8abeab8587130", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cfbscrapR-wpa.ipynb", "max_forks_repo_name": "akeaswaran/cfb-pbp-analysis", "max_forks_repo_head_hexsha": "8209c0a731a1abf7abd2dd2165c8abeab8587130", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-27T15:55:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-27T15:55:09.000Z", "avg_line_length": 42.0086650862, "max_line_length": 535, "alphanum_fraction": 0.312899403, "converted": true, "num_tokens": 172261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771241500058, "lm_q2_score": 0.05184546097287379, "lm_q1q2_score": 0.017527764345940534}}
{"text": "<a href=\"https://colab.research.google.com/github/ChrizZhuang/marginalized_graph_kernel_protein/blob/main/Docking_0608.ipynb\" target=\"_parent\"></a>\n\n\n```\n!nvidia-smi\n```\n\n    Tue Jun  8 01:01:30 2021       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 465.27       Driver Version: 460.32.03    CUDA Version: 11.2     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   42C    P8    10W /  70W |      0MiB / 15109MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    |  No running processes found                                                 |\n    +-----------------------------------------------------------------------------+\n\n\n\n```\n#!pip install pymatgen==2020.12.31\n!pip install pymatgen==2019.11.11\n!pip install --pre graphdot\n!pip install gdown\n```\n\n    Requirement already satisfied: pymatgen==2019.11.11 in /usr/local/lib/python3.7/dist-packages (2019.11.11)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (3.3.0)\n    Requirement already satisfied: pydispatcher>=2.0.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.0.5)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (0.17.7)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.16.1)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.5.1)\n    Requirement already satisfied: numpy>=1.14.3 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.19.5)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (0.8.9)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.23.0)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.1.5)\n    Requirement already satisfied: scipy>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.4.1)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.7.1)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (3.2.2)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2021.5.9)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen==2019.11.11) (0.2.2)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.2->pymatgen==2019.11.11) (4.4.2)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (2020.12.5)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (1.24.3)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen==2019.11.11) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen==2019.11.11) (2018.9)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->pymatgen==2019.11.11) (1.2.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (1.3.1)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas->pymatgen==2019.11.11) (1.15.0)\n    Requirement already satisfied: graphdot in /usr/local/lib/python3.7/dist-packages (0.8a17)\n    Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.19.5)\n    Requirement already satisfied: scipy>=1.3.0 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.4.1)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.7.1)\n    Requirement already satisfied: networkx>=2.4 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2.5.1)\n    Requirement already satisfied: pandas>=0.24 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.1.5)\n    Requirement already satisfied: pymatgen==2019.11.11 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2019.11.11)\n    Requirement already satisfied: numba>=0.51.0 in /usr/local/lib/python3.7/dist-packages (from graphdot) (0.51.2)\n    Requirement already satisfied: kahypar>=1.1.4 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.1.6)\n    Requirement already satisfied: mendeleev>=0.7 in /usr/local/lib/python3.7/dist-packages (from graphdot) (0.7.0)\n    Requirement already satisfied: treelib>=1.6.1 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.6.1)\n    Requirement already satisfied: ase>=3.17 in /usr/local/lib/python3.7/dist-packages (from graphdot) (3.21.1)\n    Requirement already satisfied: pycuda>=2019 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2021.1)\n    Requirement already satisfied: tqdm>=4.55 in /usr/local/lib/python3.7/dist-packages (from graphdot) (4.61.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->graphdot) (1.2.1)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.4->graphdot) (4.4.2)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->graphdot) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->graphdot) (2018.9)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (3.3.0)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2021.5.9)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (0.17.7)\n    Requirement already satisfied: pydispatcher>=2.0.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2.0.5)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (1.16.1)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2.23.0)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (3.2.2)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (0.8.9)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from numba>=0.51.0->graphdot) (57.0.0)\n    Requirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba>=0.51.0->graphdot) (0.34.0)\n    Requirement already satisfied: six<2.0.0,>=1.15.0 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (1.15.0)\n    Requirement already satisfied: colorama<0.5.0,>=0.4.4 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (0.4.4)\n    Requirement already satisfied: pyfiglet<0.9,>=0.8.post1 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (0.8.post1)\n    Requirement already satisfied: Pygments<3.0.0,>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (2.9.0)\n    Requirement already satisfied: SQLAlchemy<2.0.0,>=1.3.23 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (1.4.15)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from treelib>=1.6.1->graphdot) (0.16.0)\n    Requirement already satisfied: pytools>=2011.2 in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (2021.2.7)\n    Requirement already satisfied: appdirs>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (1.4.4)\n    Requirement already satisfied: mako in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (1.1.4)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen==2019.11.11->graphdot) (0.2.2)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (2020.12.5)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (3.0.4)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (1.24.3)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11->graphdot) (1.3.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11->graphdot) (0.10.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11->graphdot) (2.4.7)\n    Requirement already satisfied: greenlet!=0.4.17; python_version >= \"3\" in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (1.1.0)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (4.0.1)\n    Requirement already satisfied: MarkupSafe>=0.9.2 in /usr/local/lib/python3.7/dist-packages (from mako->pycuda>=2019->graphdot) (2.0.1)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (3.4.1)\n    Requirement already satisfied: typing-extensions>=3.6.4; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (3.7.4.3)\n    Requirement already satisfied: gdown in /usr/local/lib/python3.7/dist-packages (3.6.4)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from gdown) (4.61.0)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from gdown) (2.23.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from gdown) (1.15.0)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (3.0.4)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (1.24.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (2020.12.5)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (2.10)\n\n\n\n```\n%matplotlib inline\nimport io\nimport sys\nsys.path.append('/usr/local/lib/python3.6/site-packages/')\nimport os\nimport urllib\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport graphdot\nfrom graphdot import Graph\nfrom graphdot.graph.adjacency import AtomicAdjacency\nfrom graphdot.graph.reorder import rcm\nfrom graphdot.kernel.marginalized import MarginalizedGraphKernel # https://graphdot.readthedocs.io/en/latest/apidoc/graphdot.kernel.marginalized.html\nfrom graphdot.kernel.marginalized.starting_probability import Uniform\nfrom graphdot.model.gaussian_process import (\n    GaussianProcessRegressor,\n    LowRankApproximateGPR\n)\nfrom graphdot.kernel.fix import Normalization\nimport graphdot.microkernel as uX\nimport ase.io\n\n# for getting all file names into a list under a directory \nfrom os import listdir\n# for getting file names that match certain pattern\nimport glob\nimport time\n```\n\n\n```\nfrom google.colab import drive\ndrive.mount('/content/gdrive', force_remount=True)\n```\n\n    Mounted at /content/gdrive\n\n\n\n```\n#cd gdrive/MyDrive/Google\\ Colab/Covid-Data\n%cd gdrive/MyDrive/Covid-Data/\n```\n\n    /content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data\n\n\n\n```\n!pwd\n```\n\n    /content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data\n\n\n\n```\n#!ls\n```\n\n\n```\n#files  = ['uncharged_NSP15_6W01_A_3_H.Orderable_zinc_db_enaHLL.2col.csv.1.xz']\n#files  = [f for f in listdir('/content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data')]\nfiles = glob.glob(\"uncharged_NSP15_6W01_A_3_H.Orderable_zinc_db_enaHLL.2col.csv.*.xz\")\n#print(files[0:5])\n# concatenate all files into 1 dataset\ndataset = pd.DataFrame()\nfor i in range(len(files[0:5])):\n  data = pd.read_pickle(files[i])\n  dataset = pd.concat([dataset, data])\n#frames = [pd.read_pickle(f) for f in files]\n#dataset = pd.concat(frames)\n```\n\n\n```\nlen(dataset)\n```\n\n\n\n\n    500000\n\n\n\n\n```\ntarget = 'energy'\nN_train = len(dataset)//2\nN_test = len(dataset)//2\n```\n\n\n```\nnp.random.seed(0)\n# select train and test data\ntrain_sel = np.random.choice(len(dataset), N_train, replace=False)\ntest_sel = np.random.choice(np.setxor1d(np.arange(len(dataset)), train_sel), N_test, replace=False)\ntrain = dataset.iloc[train_sel]\ntest = dataset.iloc[test_sel]\n```\n\n\n```\n#uX.SquareExponential?\n```\n\n\n```\ngpr = GaussianProcessRegressor(\n    # kernel is the covariance function of the gaussian process (GP)\n    kernel=Normalization( # kernel equals to normalization -> normalizes a kernel using the cosine of angle formula, k_normalized(x,y) = k(x,y)/sqrt(k(x,x)*k(y,y))\n        # graphdot.kernel.fix.Normalization(kernel), set kernel as marginalized graph kernel, which is used to calculate the similarity between 2 graphs\n        # implement the random walk-based graph similarity kernel as Kashima, H., Tsuda, K., & Inokuchi, A. (2003). Marginalized kernels between labeled graphs. ICML\n        MarginalizedGraphKernel( \n            # node_kernel - A kernelet that computes the similarity between individual nodes\n            # uX - graphdot.microkernel - microkernels are positive-semidefinite functions between individual nodes and edges of graphs\n            node_kernel=uX.Additive( # addition of kernal matrices: sum of k_a(X_a, Y_a) cross for a in features\n                # uX.Constant - a kernel that returns a constant value, always mutlipled with other microkernels as an adjustable weight\n                #   c, the first input arg. as 0.5, (0.01, 10) the lower and upper bounds of c that is allowed to vary during hyperpara. optimizartion\n                # uX.KroneckerDelta - a kronecker delta returns 1 when two features are equal and return h (the first input arg here, which is 0.5 in this case) otherwise\n                #   (0.1, 0.9) the lower and upper bounds that h is allowed to vary during hyperpara. optimization\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 2nd element of graphdot.graph.Graph.nodes\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 3rd element of graphdot.graph.Graph.nodes\n                # uX.SquareExponential - Equ. 26 in the paper\n                # input arg. length_sacle is a float32, set as 1 in this case, which correspond to approx. 1 of the kernal value. \n                # This is used to determins how quicklys should the kernel decay to zero.\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0), # the 4th element of graphdot.graph.Graph.nodes\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 5th element of graphdot.graph.Graph.nodes\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0), # the 6th element of graphdot.graph.Graph.nodes\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 7th element of graphdot.graph.Graph.nodes\n                # uX.Convolution - a convolutional microkernel which averages evaluations of a base microkernel between pairs pf elememts of two variable-length feature sequences\n                # uX.KroneckerDelta as the base kernel\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9))) # the 8th element of graphdot.graph.Graph.nodes\n            ).normalized,\n            # edge_kernel - A kernelet that computes the similarity between individual edge\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 3rd element of graphdot.graph.Graph.nodes\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 4th element of graphdot.graph.Graph.nodes\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 5th element of graphdot.graph.Graph.nodes\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 6th element of graphdot.graph.Graph.nodes\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)) # the 7th element of graphdot.graph.Graph.nodes\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'), # the strating probability of the random walk on each node\n            q=0.05 # the probability for the random walk to stop during each step\n        )\n    ),\n    alpha=1e-4, # value added to the diagonal of the kernel matrix during fitting\n    optimizer=True, # default optimizer of L-BFGS-B based on scipy.optimize.minimize\n    normalize_y=True, # normalize the y values so taht the means and variance is 0 and 1, repsectively. Will be reversed when predicions are returned\n    regularization='+', # alpha (1e-4 in this case) is added to the diagonals of the kernal matrix\n)\n```\n\n    the total time consumption is 0.0034666061401367188.\n\n\n\n```\n#gpr.fit(train.graphs, train[target], repeat=3, verbose=True)\n# using the molecular graph to predict the energy\nstart_time = time.time()\ngpr.fit(train.graphs, train[target], repeat=5, verbose=True)\nend_time = time.time()\nprint(\"the total time consumption is \" + str(end_time - start_time) + \".\")\n```\n\n\n```\ngpr.kernel.hyperparameters\n```\n\n\n\n\n    starting_probability : Uniform\n    \tp : 1.0\n    stopping_probability : 0.00010000000000000009\n    node_kernel : Composite\n    \taromatic : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.02343420535068002\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.18860200789175988\n    \tatomic_number : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 5.400776905055444\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tcharge : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.0145590563621646\n    \t\trhs : SquareExponential\n    \t\t\tlength_scale : 1.0\n    \tchiral : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.05149063984443944\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.12853164901299938\n    \thcount : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 10.000000000000002\n    \t\trhs : SquareExponential\n    \t\t\tlength_scale : 0.07795674396128768\n    \thybridization : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.02783411902444354\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.17414808329497075\n    \tring_list : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 6.550981640628747\n    \t\trhs : Convolution\n    \t\t\tbase : KroneckerDelta\n    \t\t\t\th : 0.10000000000000002\n    edge_kernel : Composite\n    \taromatic : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 2.331300736214766\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \tconjugated : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 3.166641607522053\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.10000000000000002\n    \torder : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.05549109210250382\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.25478481015091287\n    \tring_stereo : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.033323606027544916\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.8\n    \tstereo : Multiply\n    \t\tlhs : Constant\n    \t\t\tc : 0.1324351226762118\n    \t\trhs : KroneckerDelta\n    \t\t\th : 0.14521546104851712\n\n\n\n\n```\nmu = gpr.predict(train.graphs)\n```\n\n\n```\nplt.scatter(train[target], mu)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.2074369392067814\n    RMSE: 0.3195501910711287\n\n\n\n```\nmu_test = gpr.predict(test.graphs)\n```\n\n\n```\nplt.scatter(test[target], mu_test)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 1.2461703788060545\n    RMSE: 1.6040210737240486\n\n\nWork\u0001on the kernel. Find a kernel that trains and predicts well.\n\n\n```\ngpr2 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-2, #different from gpr in alpha where gpr's alpha is 1e-4\n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\n#gpr2.fit(train.graphs, train[target], repeat=3, verbose=True)\ngpr2.fit(train.graphs, train[target], repeat=1, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |   1.667e+05|   1.928e+05|  1.7773e+05|      -11034|  2.2742e+05|   1.3e+02|       1.7|\n    |  1.5585e+05|  2.2171e+05|  1.6671e+05|      -10857|  2.2218e+05|   1.3e+02|       1.7|\n    |  1.3711e+05|  2.4873e+05|  1.4756e+05|      -10447|  2.0803e+05|   1.2e+02|       1.8|\n    |  1.3286e+05|  2.3627e+05|   1.432e+05|      -10338|  2.0336e+05|   1.1e+02|       1.7|\n    |  1.2977e+05|  2.2744e+05|  1.4002e+05|      -10249|  1.9714e+05|   1.1e+02|       1.7|\n    |  1.3006e+05|  2.1429e+05|  1.4032e+05|      -10258|  2.0119e+05|     1e+02|       1.7|\n    |  1.2923e+05|  2.2103e+05|  1.3946e+05|      -10238|  1.9906e+05|   1.1e+02|       1.7|\n    |  1.2888e+05|  2.2097e+05|  1.3911e+05|      -10228|  1.9865e+05|   1.1e+02|       1.7|\n    |  1.2843e+05|  2.2338e+05|  1.3864e+05|      -10211|  1.9582e+05|   1.1e+02|       1.7|\n    |  1.2837e+05|  2.2244e+05|  1.3858e+05|      -10212|   1.969e+05|   1.1e+02|       1.7|\n    |  1.2836e+05|  2.2225e+05|  1.3857e+05|      -10212|  1.9696e+05|   1.1e+02|       1.7|\n    |  1.2831e+05|  2.2155e+05|  1.3852e+05|      -10211|  1.9715e+05|   1.1e+02|       1.7|\n    |  1.2826e+05|  2.2184e+05|  1.3847e+05|      -10209|  1.9704e+05|   1.1e+02|       1.7|\n    |  1.2821e+05|  2.2181e+05|  1.3841e+05|      -10207|  1.9671e+05|   1.1e+02|       1.7|\n    |  1.2819e+05|  2.2165e+05|   1.384e+05|      -10207|  1.9664e+05|   1.1e+02|       1.8|\n    |  1.2818e+05|  2.2125e+05|  1.3838e+05|      -10207|  1.9671e+05|   1.1e+02|       1.8|\n    |  1.2817e+05|  2.2114e+05|  1.3838e+05|      -10207|  1.9673e+05|   1.1e+02|       1.7|\n    |  1.2815e+05|  2.2077e+05|  1.3836e+05|      -10207|  1.9677e+05|   1.1e+02|       1.7|\n    |  1.2812e+05|   2.185e+05|  1.3833e+05|      -10209|  1.9695e+05|   1.1e+02|       1.7|\n    |  1.2809e+05|   2.178e+05|   1.383e+05|      -10209|    1.97e+05|   1.1e+02|       1.7|\n    |  1.2807e+05|  2.1764e+05|  1.3828e+05|      -10208|  1.9695e+05|   1.1e+02|       1.7|\n    |  1.2805e+05|  2.1597e+05|  1.3826e+05|      -10209|  1.9693e+05|   1.1e+02|       1.7|\n    |  1.2805e+05|   2.172e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1693e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.8|\n    |  1.2804e+05|  2.1674e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1691e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2805e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    |  1.2804e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.8|\n    |  1.2805e+05|  2.1694e+05|  1.3825e+05|      -10208|  1.9694e+05|   1.1e+02|       1.7|\n    Optimization result:\n          fun: 128045.20193517115\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 21.67035135,   5.42797631,   0.91584794,   6.62684845,\n           636.88297304,  10.22203408,   0.        ,   6.13155297,\n             0.80318432, -45.79780911,   0.        ,   9.32446636,\n             2.06137402,   7.94609186, 767.483899  ,  -8.19180354,\n            92.93654292,   7.92503084, 118.62629465,   3.36719643,\n            38.71995733,   7.96834618,   0.        , -11.08475724,\n             7.2860016 ])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 31\n          nit: 21\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.51710969, -1.98267626,  1.72521606, -2.30258509,\n           -4.60517019,  0.        , -4.60517019, -1.8070945 ,  2.30258509,\n           -2.88031384, -3.6019383 , -2.30258509,  1.91177723, -2.30258509,\n            0.28746812, -2.30258509,  0.54884256, -2.30258509, -0.5686784 ,\n           -2.30258509, -4.35637808, -0.22314355, -2.55717239, -2.21179129])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7f6bf00630d0>\n\n\n\n\n```\nmu = gpr2.predict(train.graphs)\nplt.scatter(train[target], mu)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.7238389142657052\n    RMSE: 0.9634943206325994\n\n\n\n```\nmu_test = gpr2.predict(test.graphs)\nplt.scatter(test[target], mu_test)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 0.9561539409612109\n    RMSE: 1.2284268143181998\n\n", "meta": {"hexsha": "ecccb700415f4b3bbc4e9eab699893e105fc2258", "size": 100532, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Docking_0608.ipynb", "max_stars_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_stars_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Docking_0608.ipynb", "max_issues_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_issues_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Docking_0608.ipynb", "max_forks_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_forks_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 105.6008403361, "max_line_length": 16574, "alphanum_fraction": 0.760126129, "converted": true, "num_tokens": 10512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681520167196, "lm_q2_score": 0.04401864845207065, "lm_q1q2_score": 0.017434384746685256}}
{"text": "```python\n!pip install pennylane pennylane-ionq qiskit[visualization]\n```\n\n    Requirement already satisfied: pennylane in /usr/local/lib/python3.7/dist-packages (0.16.0)\n    Requirement already satisfied: pennylane-ionq in /usr/local/lib/python3.7/dist-packages (0.16.0)\n    Requirement already satisfied: qiskit[visualization] in /usr/local/lib/python3.7/dist-packages (0.27.0)\n    Requirement already satisfied: autoray in /usr/local/lib/python3.7/dist-packages (from pennylane) (0.2.5)\n    Requirement already satisfied: toml in /usr/local/lib/python3.7/dist-packages (from pennylane) (0.10.2)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from pennylane) (1.19.5)\n    Requirement already satisfied: autograd in /usr/local/lib/python3.7/dist-packages (from pennylane) (1.3)\n    Requirement already satisfied: networkx in /usr/local/lib/python3.7/dist-packages (from pennylane) (2.5.1)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from pennylane) (1.4.1)\n    Requirement already satisfied: semantic-version==2.6 in /usr/local/lib/python3.7/dist-packages (from pennylane) (2.6.0)\n    Requirement already satisfied: appdirs in /usr/local/lib/python3.7/dist-packages (from pennylane) (1.4.4)\n    Requirement already satisfied: python-dateutil in /usr/local/lib/python3.7/dist-packages (from pennylane-ionq) (2.8.1)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pennylane-ionq) (2.23.0)\n    Requirement already satisfied: qiskit-terra==0.17.4 in /usr/local/lib/python3.7/dist-packages (from qiskit[visualization]) (0.17.4)\n    Requirement already satisfied: qiskit-aqua==0.9.2 in /usr/local/lib/python3.7/dist-packages (from qiskit[visualization]) (0.9.2)\n    Requirement already satisfied: qiskit-ignis==0.6.0 in /usr/local/lib/python3.7/dist-packages (from qiskit[visualization]) (0.6.0)\n    Requirement already satisfied: qiskit-ibmq-provider==0.14.0 in /usr/local/lib/python3.7/dist-packages (from qiskit[visualization]) (0.14.0)\n    Requirement already satisfied: qiskit-aer==0.8.2 in /usr/local/lib/python3.7/dist-packages (from qiskit[visualization]) (0.8.2)\n    Requirement already satisfied: ipywidgets>=7.3.0; extra == \"visualization\" in /usr/local/lib/python3.7/dist-packages (from qiskit[visualization]) (7.6.3)\n    Requirement already satisfied: pylatexenc>=1.4; extra == \"visualization\" in /usr/local/lib/python3.7/dist-packages (from qiskit[visualization]) (2.10)\n    Requirement already satisfied: seaborn>=0.9.0; extra == \"visualization\" in /usr/local/lib/python3.7/dist-packages (from qiskit[visualization]) (0.11.1)\n    Requirement already satisfied: pygments>=2.4; extra == \"visualization\" in /usr/local/lib/python3.7/dist-packages (from qiskit[visualization]) (2.6.1)\n    Requirement already satisfied: pydot; extra == \"visualization\" in /usr/local/lib/python3.7/dist-packages (from qiskit[visualization]) (1.3.0)\n    Requirement already satisfied: pillow>=4.2.1; extra == \"visualization\" in /usr/local/lib/python3.7/dist-packages (from qiskit[visualization]) (7.1.2)\n    Requirement already satisfied: matplotlib>=2.1; extra == \"visualization\" in /usr/local/lib/python3.7/dist-packages (from qiskit[visualization]) (3.2.2)\n    Requirement already satisfied: future>=0.15.2 in /usr/local/lib/python3.7/dist-packages (from autograd->pennylane) (0.16.0)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx->pennylane) (4.4.2)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil->pennylane-ionq) (1.15.0)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pennylane-ionq) (2021.5.30)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pennylane-ionq) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pennylane-ionq) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pennylane-ionq) (3.0.4)\n    Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit[visualization]) (2.6.0)\n    Requirement already satisfied: retworkx>=0.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit[visualization]) (0.9.0)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit[visualization]) (0.3.4)\n    Requirement already satisfied: fastjsonschema>=2.10 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit[visualization]) (2.15.1)\n    Requirement already satisfied: ply>=3.10 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit[visualization]) (3.11)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit[visualization]) (1.7.1)\n    Requirement already satisfied: python-constraint>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit[visualization]) (1.4.0)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit[visualization]) (5.4.8)\n    Requirement already satisfied: dlx<=1.0.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.2->qiskit[visualization]) (1.0.4)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.2->qiskit[visualization]) (57.0.0)\n    Requirement already satisfied: h5py in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.2->qiskit[visualization]) (3.1.0)\n    Requirement already satisfied: yfinance in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.2->qiskit[visualization]) (0.1.59)\n    Requirement already satisfied: quandl in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.2->qiskit[visualization]) (3.6.1)\n    Requirement already satisfied: fastdtw<=0.3.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.2->qiskit[visualization]) (0.3.4)\n    Requirement already satisfied: scikit-learn>=0.20.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.2->qiskit[visualization]) (0.22.2.post1)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.2->qiskit[visualization]) (1.1.5)\n    Requirement already satisfied: docplex<=2.20.204; sys_platform != \"darwin\" in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.2->qiskit[visualization]) (2.20.204)\n    Requirement already satisfied: requests-ntlm>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.14.0->qiskit[visualization]) (1.1.0)\n    Requirement already satisfied: websocket-client>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.14.0->qiskit[visualization]) (1.1.0)\n    Requirement already satisfied: pybind11>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.8.2->qiskit[visualization]) (2.6.2)\n    Requirement already satisfied: jupyterlab-widgets>=1.0.0; python_version >= \"3.6\" in /usr/local/lib/python3.7/dist-packages (from ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (1.0.0)\n    Requirement already satisfied: nbformat>=4.2.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (5.1.3)\n    Requirement already satisfied: traitlets>=4.3.1 in /usr/local/lib/python3.7/dist-packages (from ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (5.0.5)\n    Requirement already satisfied: ipykernel>=4.5.1 in /usr/local/lib/python3.7/dist-packages (from ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (4.10.1)\n    Requirement already satisfied: ipython>=4.0.0; python_version >= \"3.3\" in /usr/local/lib/python3.7/dist-packages (from ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (5.5.0)\n    Requirement already satisfied: widgetsnbextension~=3.5.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (3.5.1)\n    Requirement already satisfied: pyparsing>=2.1.4 in /usr/local/lib/python3.7/dist-packages (from pydot; extra == \"visualization\"->qiskit[visualization]) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.1; extra == \"visualization\"->qiskit[visualization]) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.1; extra == \"visualization\"->qiskit[visualization]) (1.3.1)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra==0.17.4->qiskit[visualization]) (1.2.1)\n    Requirement already satisfied: cached-property; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from h5py->qiskit-aqua==0.9.2->qiskit[visualization]) (1.5.2)\n    Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance->qiskit-aqua==0.9.2->qiskit[visualization]) (0.0.9)\n    Requirement already satisfied: lxml>=4.5.1 in /usr/local/lib/python3.7/dist-packages (from yfinance->qiskit-aqua==0.9.2->qiskit[visualization]) (4.6.3)\n    Requirement already satisfied: more-itertools in /usr/local/lib/python3.7/dist-packages (from quandl->qiskit-aqua==0.9.2->qiskit[visualization]) (8.8.0)\n    Requirement already satisfied: inflection>=0.3.1 in /usr/local/lib/python3.7/dist-packages (from quandl->qiskit-aqua==0.9.2->qiskit[visualization]) (0.5.1)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.9.2->qiskit[visualization]) (1.0.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->qiskit-aqua==0.9.2->qiskit[visualization]) (2018.9)\n    Requirement already satisfied: cryptography>=1.3 in /usr/local/lib/python3.7/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.14.0->qiskit[visualization]) (3.4.7)\n    Requirement already satisfied: ntlm-auth>=1.0.2 in /usr/local/lib/python3.7/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.14.0->qiskit[visualization]) (1.5.0)\n    Requirement already satisfied: ipython-genutils in /usr/local/lib/python3.7/dist-packages (from nbformat>=4.2.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.2.0)\n    Requirement already satisfied: jupyter-core in /usr/local/lib/python3.7/dist-packages (from nbformat>=4.2.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (4.7.1)\n    Requirement already satisfied: tornado>=4.0 in /usr/local/lib/python3.7/dist-packages (from ipykernel>=4.5.1->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (5.1.1)\n    Requirement already satisfied: jupyter-client in /usr/local/lib/python3.7/dist-packages (from ipykernel>=4.5.1->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (5.3.5)\n    Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (1.0.18)\n    Requirement already satisfied: pickleshare in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.7.5)\n    Requirement already satisfied: pexpect; sys_platform != \"win32\" in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (4.8.0)\n    Requirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.8.1)\n    Requirement already satisfied: notebook>=4.4.1 in /usr/local/lib/python3.7/dist-packages (from widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (5.3.1)\n    Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.14.0->qiskit[visualization]) (1.14.5)\n    Requirement already satisfied: pyzmq>=13 in /usr/local/lib/python3.7/dist-packages (from jupyter-client->ipykernel>=4.5.1->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (22.1.0)\n    Requirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.2.5)\n    Requirement already satisfied: ptyprocess>=0.5 in /usr/local/lib/python3.7/dist-packages (from pexpect; sys_platform != \"win32\"->ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.7.0)\n    Requirement already satisfied: nbconvert in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (5.6.1)\n    Requirement already satisfied: terminado>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.10.1)\n    Requirement already satisfied: Send2Trash in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (1.5.0)\n    Requirement already satisfied: jinja2 in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (2.11.3)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.14.0->qiskit[visualization]) (2.20)\n    Requirement already satisfied: mistune<2,>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.8.4)\n    Requirement already satisfied: defusedxml in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.7.1)\n    Requirement already satisfied: bleach in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (3.3.0)\n    Requirement already satisfied: entrypoints>=0.2.2 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.3)\n    Requirement already satisfied: testpath in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.5.0)\n    Requirement already satisfied: pandocfilters>=1.4.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (1.4.3)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (2.0.1)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (20.9)\n    Requirement already satisfied: webencodings in /usr/local/lib/python3.7/dist-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets>=7.3.0; extra == \"visualization\"->qiskit[visualization]) (0.5.1)\n\n\n\n```python\nimport os\nimport pennylane as qml\nfrom pennylane import numpy as np\nfrom pennylane.templates import RandomLayers\nfrom pennylane_ionq import ops\nimport matplotlib.pyplot as plt\nfrom qiskit import *\nimport torch\nfrom torch.autograd import Variable\nfrom torchvision import datasets, transforms\nimport torch.optim as optim\nimport torch.nn.functional as F\n```\n\n\n```python\nuse_cuda = torch.cuda.is_available()\nprint(use_cuda)\n```\n\n    True\n\n\n\n```python\nn_epochs = 30   # Number of optimization epochs\nn_layers = 1    # Number of random layers\nn_train = 128    # Size of the train dataset\nn_test = 32     # Size of the test dataset\n\nSAVE_PATH = \"quanvolution_pqc/\" # Data saving folder\nPREPROCESS = True           # If False, skip quantum processing and load data from SAVE_PATH\n# np.random.seed(0)           # Seed for NumPy random number generator\n# tf.random.set_seed(0)       # Seed for TensorFlow random number generator\n```\n\n\n```python\nBATCH_SIZE = 16\nfrom torch.utils.data import SubsetRandomSampler\ntrain_dataset = datasets.MNIST(root = \"./data\",\n                               train = True,\n                               download = True,\n                               transform = transforms.ToTensor())\n\ntest_dataset = datasets.MNIST(root = \"./data\",\n                              train = False,\n                              transform = transforms.ToTensor())\n\n# train_dataset = Subset(train_dataset,range(n_train))\n# test_dataset = Subset(test_dataset,range(n_test))\n\ntrain_sampler = SubsetRandomSampler(range(n_train))\ntest_sampler = SubsetRandomSampler(range(n_test))\n\ntrain_loader = torch.utils.data.DataLoader(dataset = train_dataset,\n                                           batch_size = BATCH_SIZE,\n                                           shuffle = False,\n                                           sampler = train_sampler)\n\ntest_loader = torch.utils.data.DataLoader(dataset = test_dataset,\n                                          batch_size = BATCH_SIZE,\n                                          shuffle = False,\n                                          sampler = test_sampler)\n```\n\n    Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\n    Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz to ./data/MNIST/raw/train-images-idx3-ubyte.gz\n\n\n\n    HBox(children=(FloatProgress(value=0.0, max=9912422.0), HTML(value='')))\n\n\n    \n    Extracting ./data/MNIST/raw/train-images-idx3-ubyte.gz to ./data/MNIST/raw\n    \n    Downloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz\n    Downloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz to ./data/MNIST/raw/train-labels-idx1-ubyte.gz\n\n\n\n    HBox(children=(FloatProgress(value=0.0, max=28881.0), HTML(value='')))\n\n\n    \n    Extracting ./data/MNIST/raw/train-labels-idx1-ubyte.gz to ./data/MNIST/raw\n    \n    Downloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz\n    Downloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz to ./data/MNIST/raw/t10k-images-idx3-ubyte.gz\n    Failed to download (trying next):\n    HTTP Error 503: Service Unavailable\n    \n    Downloading https://ossci-datasets.s3.amazonaws.com/mnist/t10k-images-idx3-ubyte.gz\n    Downloading https://ossci-datasets.s3.amazonaws.com/mnist/t10k-images-idx3-ubyte.gz to ./data/MNIST/raw/t10k-images-idx3-ubyte.gz\n\n\n\n    HBox(children=(FloatProgress(value=0.0, max=1648877.0), HTML(value='')))\n\n\n    \n    Extracting ./data/MNIST/raw/t10k-images-idx3-ubyte.gz to ./data/MNIST/raw\n    \n    Downloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz\n    Failed to download (trying next):\n    HTTP Error 503: Service Unavailable\n    \n    Downloading https://ossci-datasets.s3.amazonaws.com/mnist/t10k-labels-idx1-ubyte.gz\n    Downloading https://ossci-datasets.s3.amazonaws.com/mnist/t10k-labels-idx1-ubyte.gz to ./data/MNIST/raw/t10k-labels-idx1-ubyte.gz\n\n\n\n    HBox(children=(FloatProgress(value=0.0, max=4542.0), HTML(value='')))\n\n\n    \n    Extracting ./data/MNIST/raw/t10k-labels-idx1-ubyte.gz to ./data/MNIST/raw\n    \n\n\n    /usr/local/lib/python3.7/dist-packages/torchvision/datasets/mnist.py:498: UserWarning: The given NumPy array is not writeable, and PyTorch does not support non-writeable tensors. This means you can write to the underlying (supposedly non-writeable) NumPy array using the tensor. You may want to copy the array to protect its data or make it writeable before converting it to a tensor. This type of warning will be suppressed for the rest of this program. (Triggered internally at  /pytorch/torch/csrc/utils/tensor_numpy.cpp:180.)\n      return torch.from_numpy(parsed.astype(m[2], copy=False)).view(*s)\n\n\n\n```python\nos.environ['IONQ_API_KEY']='1LCa7Dvzz5P35g6B3gwoxzFO04n7gWYH'\ndev = qml.device(\"ionq.qpu\", wires=9)\n\n# Random circuit parameters\n\n@qml.qnode(dev, interface='torch')\ndef pqc(data,params):\n    # Encoding of 9 classical input values\n    # len(params) = 2 * 9\n    # print(\"data: \",data)\n    # print(\"params: \",params)\n    n_qubits = 9\n    for j in range(n_qubits):\n        qml.RY(np.pi * data[j], wires=j)\n    \n    # rand_params = np.random.uniform(high=2 * np.pi, size=(n_layers, 9))\n    # print(\"rand\", rand_params)\n    # PQC\n    for i in range(n_qubits):\n        qml.RY(params[i], wires=i)\n    for i in range(n_qubits-1):\n        qml.CNOT(wires=[i,i+1])    \n    qml.CNOT(wires=[n_qubits-1,0])\n    for i in range(n_qubits):\n        qml.RY(params[i+n_qubits], wires=i)\n    # Measurement producing 9 classical output values\n    return qml.expval(qml.PauliZ(0))\n```\n\n    1LCa7Dvzz5P35g6B3gwoxzFO04n7gWYH\n\n\n\n```python\nprint(pqc([1,0,2,1,2,3,1,2,0],[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]))\n```\n\n\n```python\nclass QuanvNet(torch.nn.Module):\n    def __init__(self,qc=True,opt=True):\n        super().__init__()\n        self.n_qubits = 9\n        self.filters = 1\n        self.conv_opt = torch.nn.Conv2d(in_channels=self.filters,out_channels=self.filters,kernel_size=3)\n        self.conv1 = torch.nn.Conv2d(in_channels=self.filters,out_channels=8,kernel_size=3)\n        self.pre_pool = torch.nn.AvgPool2d(2)\n        self.pool = torch.nn.MaxPool2d(2)\n        self.conv2 = torch.nn.Conv2d(in_channels=8,out_channels=8,kernel_size=3)\n        if qc == True:\n          self.fc1 = torch.nn.Linear(32,16)\n        else:\n          self.fc1 = torch.nn.Linear(32,16)\n        self.fc2 = torch.nn.Linear(16,10)\n        self.dropout = torch.nn.Dropout(0.4)\n        self.q_params = torch.nn.Parameter(2*np.pi*torch.rand(12,12,self.filters,2*self.n_qubits))\n        self.q_params.requires_grad = True\n\n    def forward(self, inputs):\n        inputs = self.pre_pool(inputs)/255\n        qc = False\n        if qc == True:\n          out = torch.zeros((BATCH_SIZE,self.filters,12,12))\n          for bat, image in enumerate(inputs):\n              for j in range(1, 13, 1):\n                  for k in range(1, 13, 1):\n                      for i in range(self.filters):\n                          q_results = pqc(\n                          [\n                              image[0, j - 1, k - 1].item(),\n                              image[0, j - 1, k].item(),\n                              image[0, j - 1, k + 1].item(),\n                              image[0, j, k - 1].item(),\n                              image[0, j, k].item(),\n                              image[0, j, k + 1].item(),\n                              image[0, j + 1, k - 1].item(),\n                              image[0, j + 1, k].item(),\n                              image[0, j + 1, k + 1].item()\n                          ],\n                              self.q_params[j-1,k-1,i]\n                          )\n                          out[bat,i,j - 1, k - 1] = q_results\n        else:\n          out = torch.zeros((BATCH_SIZE,self.filters,14,14))\n          out = inputs\n        # print(out.size())\n        if opt==True:\n          out = self.conv_opt(inputs)\n        x = self.pool(F.relu(self.conv1(out)))\n        # print(x.size())\n        x = self.pool(F.relu(self.conv2(x)))\n        x = torch.flatten(x,1)\n        # print(x.size())\n        x = F.relu(self.fc1(x))\n        x = self.dropout(x)\n        x = F.softmax(self.fc2(x))\n        return x\n\n\n```\n\n\n```python\nfrom torchsummary import summary\ncriterion = torch.nn.CrossEntropyLoss()\nmodel = QuanvNet(qc=False,opt=True)\nif use_cuda:\n    model.cuda()\nopt = optim.Adam(model.parameters(),lr=0.01)\nsummary(model,(1,28,28))\n```\n\n    ----------------------------------------------------------------\n            Layer (type)               Output Shape         Param #\n    ================================================================\n             AvgPool2d-1            [-1, 1, 14, 14]               0\n                Conv2d-2            [-1, 8, 12, 12]              80\n             MaxPool2d-3              [-1, 8, 6, 6]               0\n                Conv2d-4              [-1, 8, 4, 4]             584\n             MaxPool2d-5              [-1, 8, 2, 2]               0\n                Linear-6                   [-1, 16]             528\n               Dropout-7                   [-1, 16]               0\n                Linear-8                   [-1, 10]             170\n    ================================================================\n    Total params: 1,362\n    Trainable params: 1,362\n    Non-trainable params: 0\n    ----------------------------------------------------------------\n    Input size (MB): 0.00\n    Forward/backward pass size (MB): 0.01\n    Params size (MB): 0.01\n    Estimated Total Size (MB): 0.02\n    ----------------------------------------------------------------\n\n\n    /usr/local/lib/python3.7/dist-packages/torch/nn/functional.py:718: UserWarning: Named tensors and all their associated APIs are an experimental feature and subject to change. Please do not use them for anything important until they are released as stable. (Triggered internally at  /pytorch/c10/core/TensorImpl.h:1156.)\n      return torch.max_pool2d(input, kernel_size, stride, padding, dilation, ceil_mode)\n    /usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:57: UserWarning: Implicit dimension choice for softmax has been deprecated. Change the call to include dim=X as an argument.\n\n\n\n```python\nfor p in model.parameters():\n    print(p.shape)\n```\n\n    torch.Size([12, 12, 1, 18])\n    torch.Size([1, 1, 3, 3])\n    torch.Size([1])\n    torch.Size([8, 1, 3, 3])\n    torch.Size([8])\n    torch.Size([8, 8, 3, 3])\n    torch.Size([8])\n    torch.Size([16, 32])\n    torch.Size([16])\n    torch.Size([10, 16])\n    torch.Size([10])\n\n\n\n```python\nlosses = []\naccs = []\nfor epoch in range(10000):\n  train_loss = 0\n  acc = 0\n  for (x_train, y_train) in train_loader:\n    # print(y_train)\n    opt.zero_grad()\n    outputs = model(x_train.cuda() if use_cuda else x_train)\n    _, preds = torch.max(outputs,1)\n    acc += (preds==(y_train.cuda() if use_cuda else y_train)).sum().item()\n    loss = criterion(outputs,(y_train.cuda() if use_cuda else y_train))\n    loss.backward()\n    opt.step()\n    train_loss += loss\n    del loss\n  acc /= n_train\n  train_loss /= (n_train/BATCH_SIZE)\n  if epoch%10 == 9:\n    if epoch%100 == 99:\n      print(epoch+1,train_loss)\n    losses.append(train_loss.item())\n  if epoch%10 == 9:\n    accs.append(acc) \n  del acc\n```\n\n    /usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:57: UserWarning: Implicit dimension choice for softmax has been deprecated. Change the call to include dim=X as an argument.\n\n\n    100 tensor(2.2774, device='cuda:0', grad_fn=<DivBackward0>)\n    200 tensor(2.0464, device='cuda:0', grad_fn=<DivBackward0>)\n    300 tensor(1.8611, device='cuda:0', grad_fn=<DivBackward0>)\n    400 tensor(1.8236, device='cuda:0', grad_fn=<DivBackward0>)\n    500 tensor(1.7977, device='cuda:0', grad_fn=<DivBackward0>)\n    600 tensor(1.7520, device='cuda:0', grad_fn=<DivBackward0>)\n    700 tensor(1.7200, device='cuda:0', grad_fn=<DivBackward0>)\n    800 tensor(1.7683, device='cuda:0', grad_fn=<DivBackward0>)\n    900 tensor(1.7078, device='cuda:0', grad_fn=<DivBackward0>)\n    1000 tensor(1.7500, device='cuda:0', grad_fn=<DivBackward0>)\n    1100 tensor(1.7332, device='cuda:0', grad_fn=<DivBackward0>)\n    1200 tensor(1.7049, device='cuda:0', grad_fn=<DivBackward0>)\n    1300 tensor(1.7317, device='cuda:0', grad_fn=<DivBackward0>)\n    1400 tensor(1.7285, device='cuda:0', grad_fn=<DivBackward0>)\n    1500 tensor(1.7367, device='cuda:0', grad_fn=<DivBackward0>)\n    1600 tensor(1.7035, device='cuda:0', grad_fn=<DivBackward0>)\n    1700 tensor(1.7171, device='cuda:0', grad_fn=<DivBackward0>)\n    1800 tensor(1.7270, device='cuda:0', grad_fn=<DivBackward0>)\n    1900 tensor(1.7131, device='cuda:0', grad_fn=<DivBackward0>)\n    2000 tensor(1.7252, device='cuda:0', grad_fn=<DivBackward0>)\n    2100 tensor(1.7049, device='cuda:0', grad_fn=<DivBackward0>)\n    2200 tensor(1.7134, device='cuda:0', grad_fn=<DivBackward0>)\n    2300 tensor(1.6944, device='cuda:0', grad_fn=<DivBackward0>)\n    2400 tensor(1.7162, device='cuda:0', grad_fn=<DivBackward0>)\n    2500 tensor(1.7796, device='cuda:0', grad_fn=<DivBackward0>)\n    2600 tensor(1.7119, device='cuda:0', grad_fn=<DivBackward0>)\n    2700 tensor(1.6704, device='cuda:0', grad_fn=<DivBackward0>)\n    2800 tensor(1.7935, device='cuda:0', grad_fn=<DivBackward0>)\n    2900 tensor(1.7494, device='cuda:0', grad_fn=<DivBackward0>)\n    3000 tensor(1.7575, device='cuda:0', grad_fn=<DivBackward0>)\n    3100 tensor(1.7545, device='cuda:0', grad_fn=<DivBackward0>)\n    3200 tensor(1.7485, device='cuda:0', grad_fn=<DivBackward0>)\n    3300 tensor(1.7043, device='cuda:0', grad_fn=<DivBackward0>)\n    3400 tensor(1.6991, device='cuda:0', grad_fn=<DivBackward0>)\n    3500 tensor(1.7404, device='cuda:0', grad_fn=<DivBackward0>)\n    3600 tensor(1.7043, device='cuda:0', grad_fn=<DivBackward0>)\n    3700 tensor(1.7025, device='cuda:0', grad_fn=<DivBackward0>)\n    3800 tensor(1.7457, device='cuda:0', grad_fn=<DivBackward0>)\n    3900 tensor(1.7696, device='cuda:0', grad_fn=<DivBackward0>)\n    4000 tensor(1.7692, device='cuda:0', grad_fn=<DivBackward0>)\n    4100 tensor(1.7070, device='cuda:0', grad_fn=<DivBackward0>)\n    4200 tensor(1.6875, device='cuda:0', grad_fn=<DivBackward0>)\n    4300 tensor(1.6958, device='cuda:0', grad_fn=<DivBackward0>)\n    4400 tensor(1.7299, device='cuda:0', grad_fn=<DivBackward0>)\n    4500 tensor(1.7323, device='cuda:0', grad_fn=<DivBackward0>)\n    4600 tensor(1.7272, device='cuda:0', grad_fn=<DivBackward0>)\n    4700 tensor(1.7499, device='cuda:0', grad_fn=<DivBackward0>)\n    4800 tensor(1.7509, device='cuda:0', grad_fn=<DivBackward0>)\n    4900 tensor(1.6996, device='cuda:0', grad_fn=<DivBackward0>)\n    5000 tensor(1.6813, device='cuda:0', grad_fn=<DivBackward0>)\n    5100 tensor(1.7018, device='cuda:0', grad_fn=<DivBackward0>)\n    5200 tensor(1.7215, device='cuda:0', grad_fn=<DivBackward0>)\n    5300 tensor(1.7707, device='cuda:0', grad_fn=<DivBackward0>)\n    5400 tensor(1.7116, device='cuda:0', grad_fn=<DivBackward0>)\n    5500 tensor(1.6995, device='cuda:0', grad_fn=<DivBackward0>)\n    5600 tensor(1.7852, device='cuda:0', grad_fn=<DivBackward0>)\n    5700 tensor(1.6981, device='cuda:0', grad_fn=<DivBackward0>)\n    5800 tensor(1.7513, device='cuda:0', grad_fn=<DivBackward0>)\n    5900 tensor(1.7203, device='cuda:0', grad_fn=<DivBackward0>)\n    6000 tensor(1.6599, device='cuda:0', grad_fn=<DivBackward0>)\n    6100 tensor(1.7213, device='cuda:0', grad_fn=<DivBackward0>)\n    6200 tensor(1.7631, device='cuda:0', grad_fn=<DivBackward0>)\n    6300 tensor(1.7060, device='cuda:0', grad_fn=<DivBackward0>)\n    6400 tensor(1.7958, device='cuda:0', grad_fn=<DivBackward0>)\n    6500 tensor(1.6994, device='cuda:0', grad_fn=<DivBackward0>)\n    6600 tensor(1.7302, device='cuda:0', grad_fn=<DivBackward0>)\n    6700 tensor(1.7280, device='cuda:0', grad_fn=<DivBackward0>)\n    6800 tensor(1.7143, device='cuda:0', grad_fn=<DivBackward0>)\n    6900 tensor(1.7274, device='cuda:0', grad_fn=<DivBackward0>)\n    7000 tensor(1.7194, device='cuda:0', grad_fn=<DivBackward0>)\n    7100 tensor(1.7159, device='cuda:0', grad_fn=<DivBackward0>)\n    7200 tensor(1.7235, device='cuda:0', grad_fn=<DivBackward0>)\n    7300 tensor(1.6964, device='cuda:0', grad_fn=<DivBackward0>)\n    7400 tensor(1.7048, device='cuda:0', grad_fn=<DivBackward0>)\n    7500 tensor(1.7398, device='cuda:0', grad_fn=<DivBackward0>)\n    7600 tensor(1.7498, device='cuda:0', grad_fn=<DivBackward0>)\n    7700 tensor(1.6925, device='cuda:0', grad_fn=<DivBackward0>)\n    7800 tensor(1.6970, device='cuda:0', grad_fn=<DivBackward0>)\n    7900 tensor(1.6918, device='cuda:0', grad_fn=<DivBackward0>)\n    8000 tensor(1.9402, device='cuda:0', grad_fn=<DivBackward0>)\n    8100 tensor(1.7627, device='cuda:0', grad_fn=<DivBackward0>)\n    8200 tensor(1.7777, device='cuda:0', grad_fn=<DivBackward0>)\n    8300 tensor(1.7291, device='cuda:0', grad_fn=<DivBackward0>)\n    8400 tensor(1.7341, device='cuda:0', grad_fn=<DivBackward0>)\n    8500 tensor(1.7646, device='cuda:0', grad_fn=<DivBackward0>)\n    8600 tensor(1.7169, device='cuda:0', grad_fn=<DivBackward0>)\n    8700 tensor(1.6884, device='cuda:0', grad_fn=<DivBackward0>)\n    8800 tensor(1.6726, device='cuda:0', grad_fn=<DivBackward0>)\n    8900 tensor(1.7408, device='cuda:0', grad_fn=<DivBackward0>)\n    9000 tensor(1.6919, device='cuda:0', grad_fn=<DivBackward0>)\n    9100 tensor(1.7121, device='cuda:0', grad_fn=<DivBackward0>)\n    9200 tensor(1.8130, device='cuda:0', grad_fn=<DivBackward0>)\n    9300 tensor(1.6796, device='cuda:0', grad_fn=<DivBackward0>)\n    9400 tensor(1.7852, device='cuda:0', grad_fn=<DivBackward0>)\n    9500 tensor(1.7346, device='cuda:0', grad_fn=<DivBackward0>)\n    9600 tensor(1.7184, device='cuda:0', grad_fn=<DivBackward0>)\n    9700 tensor(1.7418, device='cuda:0', grad_fn=<DivBackward0>)\n    9800 tensor(1.7182, device='cuda:0', grad_fn=<DivBackward0>)\n    9900 tensor(1.7344, device='cuda:0', grad_fn=<DivBackward0>)\n    10000 tensor(1.7457, device='cuda:0', grad_fn=<DivBackward0>)\n\n\n\n```python\nfrom matplotlib.pyplot import plot\nx = np.arange(0,10000,10)\nplot(x,losses)\n```\n\n\n```python\nx = np.arange(0,10000,10)\nplot(x,accs)\n```\n", "meta": {"hexsha": "96da608a4bc7e549dc8b6eff5351cbadebb5f223", "size": 126660, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Yunseo Kim/quanvolution-pennylane.ipynb", "max_stars_repo_name": "JadeKim/2021QuantumHackatonKorea", "max_stars_repo_head_hexsha": "dec44087af4e843b33483e8d53c4725916e4b24b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-06-23T08:57:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T10:09:24.000Z", "max_issues_repo_path": "Yunseo Kim/quanvolution-pennylane.ipynb", "max_issues_repo_name": "JadeKim/2021QuantumHackatonKorea", "max_issues_repo_head_hexsha": "dec44087af4e843b33483e8d53c4725916e4b24b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Yunseo Kim/quanvolution-pennylane.ipynb", "max_forks_repo_name": "JadeKim/2021QuantumHackatonKorea", "max_forks_repo_head_hexsha": "dec44087af4e843b33483e8d53c4725916e4b24b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-20T03:02:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-21T10:54:58.000Z", "avg_line_length": 67.6964190273, "max_line_length": 20482, "alphanum_fraction": 0.6706537186, "converted": true, "num_tokens": 10784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414096510108, "lm_q2_score": 0.06465349105959628, "lm_q1q2_score": 0.01738800102442685}}
{"text": "# <span style='color:darkred'> 4 Trajectory Analysis </span>\n\n***\n\n**<span style='color:darkred'> Important Note </span>**\n\nBefore proceeding to the rest of the analysis, it is a good time to define a path that points to the location of the MD simulation data, which we will analyze here.\n\nIf you successfully ran the MD simulation, the correct path should be:\n\n\n```python\n# Execute the cell to define the path to your simulation files\npath=\"OxCompBio-Datafiles/run\"\n```\n\nIf however, you need/want to use the data from the simulation that has been already performed, uncomment the command below to instead define the path that points to the prerun simulation.\n\n\n```python\n# Uncomment the line below and execute the cell to define the path to the prerun simulation files\n#path=\"OxCompBio-Datafiles/prerun/run\"\n```\n\n## <span style='color:darkred'> 4.1 Visualize the simulation </span>\n\nThe simplest and easiest type of analysis you should always do is to look at it with your eyes! Your eyes will tell you if something strange is happening immediately. A numerical analysis may not.\n\n### <span style='color:darkred'>  4.1.1 VMD </span>\n\n*Note: Again, this step is optional. If you don't have VMD, go to section 4.1.2 below to visualize the trajectory with NGLView instead.*\n\nLet us look at the simulations on VMD.\n\nOpen your vmd, by typing on your terminal:\n\n`% vmd`\n\nWhen it has finished placing all the windows on the screen. Click on `File` in the VMD main menu window and select `New Molecule`. The Molecule File Browser window should appear. Click on `Browse...` then select the `OxCompBio-Datafiles` and then the `run` directory and finally select `em.gro` (i.e. the file you made that has protein system energy minimized). Click `OK` and then click `Load`. It should load up the starting coordinates into the main window. Then click `Browse...` in the Molecule File Browser window. Select again the `OxCompBio-Datafiles`, then the `run` directory and then `md.xtc`. Select `OK` and then hit `Load`. The trajectory should start loading into the main VMD window. \n\nAlthough things will be moving, you can see that it is quite difficult to visualize the individual components. That is one of the problems with simulating such large and complicated systems. VMD makes it quite easy to look at individual components of a system. For example, let us consider the protein only. On the VMD Main menu, left-click on Graphics and select `Representations`. A new menu will appear (`Graphical Representations`). In the box entitled `Selected Atoms` type protein and hit enter. Only those atoms that form part of the protein are now selected. Various other selections and drawing methods will help to visualize different aspects of the simulation. \n\n<span style='color:Blue'> **Questions**  </span> \n\n* How would you say the protein behaves? \n\n\n* Is it doing anything unexpected? What would you consider unexpected behaviour?\n\n\n* Can you add representations for the ASP and the ARG residues only? Can you observe if they form any inter-subunit interactions? We will quantify those later on.\n\n### <span style='color:darkred'> 4.1.2 NGLView </span>\n\n\nYou have already tested NGLView at the Python tutorial (Notebook `12_ProteinAnalysis`) and at the beginning of this tutorial. This time however, you can visualize the trajectory you generated after carrying out the MD simulation.\n\nYou should also be familiar now with the MDAnalysis Python library that we will use to analyze the MD trajectory. We will also use it below, to create a Universe and load it on NGLView.\n\n\n```python\n# Import MDAnalysis and NGLView\nimport MDAnalysis\nimport nglview\n\n# Load the protein structure and the trajectory as a universe named protein\nprotein=MDAnalysis.Universe(f\"{path}/em.gro\", f\"{path}/md_fit.xtc\")\nprotein_view = nglview.show_mdanalysis(protein)\nprotein_view.gui_style = 'ngl'\n\n#Color the protein based on its secondary structure\nprotein_view.update_cartoon(color='sstruc')\nprotein_view\n```\n\n<span style='color:Blue'> **Questions**  </span> \n\n* How would you say the protein behaves? \n\n\n* Is it doing anything unexpected? What would you consider unexpected behaviour?\n\n\n* Can you add representations for the ASP and the ARG residues only? Can you observe if they form any inter-subunit interactions? We will quantify those later on.\n\nNow that we are sure the simulation is not doing anything ridiculous, we can start to ask questions about the simulation. The first thing to establish is whether the simulation has equilibrated to some state. So what are some measures of the system\nbeing equilibrated? And what can we use to test the reliability of the simulation?\n\n## <span style='color:darkred'> 4.2 System Equilibration </span> \n\n### <span style='color:darkred'> 4.2.1 Temperature fluctuation </span>\n\nThe system temperature as a function of time was calculated in the previous section, with the built-in GROMACS tool `gmx energy`, but we still have not looked at it. It is now time to plot the temperature *vs* time and assess the results.\n\n<span style='color:Blue'> **Questions**  </span> \n\n* Does the temperature fluctuate around an equilibrium  value?\n\n\n* Does this value correspond to the temperature that we predefined in the `md.mdp` input file?\n\nImport numpy and pyplot from matplotlib, required to read and plot the data, respectively.\n\n\n```python\n# We declare matplotlib inline to make sure it plots properly\n%matplotlib inline\n# We need to import numpy \nimport numpy as np\n# We need pyplot from matplotlib to generate our plots\nfrom matplotlib import pyplot\n```\n\nNow, using numpy, we can read the data from the `1hsg_temperature.xvg` file; the first column is the time (in ps) and the secong is the system temperature (in K).\n\n\n```python\n# Read the file that contains the system temperature for each frame\ntime=np.loadtxt(f\"{path}/1hsg_temperature.xvg\", comments=['#','@'])[:, 0]\ntemperature=np.loadtxt(f\"{path}/1hsg_temperature.xvg\", comments=['#','@'])[:, 1] \n```\n\nYou can use numpy again to compute the average temperature and its standard deviation.\n\n\n```python\n# Calculate and print the mean temperature and the standard deviation\n# Keep only two decimal points\nmean_temperature=round(np.mean(temperature), 2)\nstd_temperature=round(np.std(temperature), 2)\nprint(f\"The mean temperature is {mean_temperature} \u00b1 {std_temperature} K\")\n```\n\nFinally, you can plot the temperature *vs* simulation time.\n\n\n```python\n# Plot the temperature\npyplot.plot(time, temperature, color='darkred')\npyplot.title(\"Temperature over time\")\npyplot.xlabel(\"Time [ps]\")\npyplot.ylabel(\"Temperature [K]\")\npyplot.show()\n```\n\n### <span style='color:darkred'> 4.2.2 Energy of the system </span> \n\nAnother set of properties that is quite useful to examine is the various energetic contributions to the energy. The total\nenergy should be constant. but the various contributions can change and this can sometimes indicate something\ninteresting or strange happening in your simulation. Let us look at some energetic properties of the simulation.\n\nWe have already exctracted the Lennard-Jones energy, the Coulomb energy and the potential energy using again the GROMACS built-in tool `gmx energy`. The data of these three energetic components are saved in the same file called `1hsg_energies.xvg`; the first column contains the time (in ps) and the columns that follow contain the energies (in kJ/mol), in the same order as they were generated.\n\nWe can now read the data from the `1hsg_energies.xvg` file using numpy.\n\n\n```python\n# Read the file that contains the various energetic components for each frame\ntime=np.loadtxt(f\"{path}/1hsg_energies.xvg\", comments=['#','@'])[:, 0]\nlennard_jones=np.loadtxt(f\"{path}/1hsg_energies.xvg\", comments=['#','@'])[:, 1]\ncoulomb=np.loadtxt(f\"{path}/1hsg_energies.xvg\", comments=['#','@'])[:, 2]\npotential=np.loadtxt(f\"{path}/1hsg_energies.xvg\", comments=['#','@'])[:, 3]\n```\n\nAnd now that we read the data file, we can plot the energetic components *vs* simulation time in separate plots using matplotlib.\n\n\n```python\n# Plot the Lennard-Jones energy\npyplot.plot(time, lennard_jones, color='blue')\npyplot.title(\"Lennard Jones energy over time\")\npyplot.xlabel(\"Time [ps]\")\npyplot.ylabel(\"LJ energy [kJ/mol]\")\npyplot.show()\n\n# Plot the electrostatic energy\n\n\n# Plot the potential energy\n\n```\n\n<span style='color:Blue'> **Questions**  </span> \n\n* Can you plot the Coulomb energy and the potential energy, following the same steps as above? \n\n\n* Is the total energy stable in this simulation? \n\n\n* What is the dominant contribution to the potential energy?\n\n## <span style='color:darkred'> 4.3 Analysis of Protein </span>\n\n*Hint:* Ideally, you should visualize the trajectory with either VMD or NGLView and combine the information you extract from the plots with what you observe visually. That applies to all the structural analysis that you perform. So feel free at any point to go back to VMD or NGLView to verify the results you get from the analysis below.\n\n### <span style='color:darkred'> 4.3.1 Root mean square deviation (RMSD) of 1HSG </span>\n\nThe RMSD gives us an idea of how 'stable' our protein is when compared to our starting, static, structure. The lower the RMSD is, the more stable we can say our protein is. \n\nThe RMSD as a function of time, $\\rho (t)$, can be defined by the following equation:\n\n\\begin{equation}\n\\\\\n\\rho (t) = \\sqrt{\\frac{1}{N}\\sum^N_{i=1}w_i\\big(\\mathbf{x}_i(t) - \\mathbf{x}^{\\text{ref}}_i\\big)^2}\n\\end{equation}\n\nLuckily MDAnalysis has its own built-in function to calculate this and we can import it.\n\n\n\n\n```python\n# Import built-in MDAnalysis tools for alignment and RMSD.\nfrom MDAnalysis.analysis import align\nfrom MDAnalysis.analysis.rms import RMSD as rmsd\n\n# Define the simulation universe and the reference structure (protein structure at first frame)\nprotein = MDAnalysis.Universe(f\"{path}/md.gro\", f\"{path}/md_fit.xtc\")\nprotein_ref = MDAnalysis.Universe(f\"{path}/em.gro\", f\"{path}/md_fit.xtc\")\nprotein_ref.trajectory[0]\n\n# Call the MDAnalysis align function to align the MD simulation universe to the reference (first frame) universe\nalign_strucs = align.AlignTraj(protein, protein_ref, select=\"backbone\", weights=\"mass\", in_memory=True, verbose=True)\n\nR = align_strucs.run()\nrmsd_data = R.rmsd\n\n# Plot the RMSD\npyplot.plot(rmsd_data)\npyplot.title(\"RMSD over time\")\npyplot.xlabel(\"Frame number\")\npyplot.ylabel(\"RMSD (Angstrom)\")\npyplot.show()\n\n```\n\n<span style='color:Blue'> **Questions**  </span> \n\n* What does this tell you about the stability of the protein? Is it in a state of equilibrium and if so why and at what time?\n\n\n* Can you think of a situation where this approach might not be a very good indication of stability?\n\n### <span style='color:darkred'> 4.3.2 Root mean square fluctuation (RMSF) of 1HSG </span>\n\nA similar property that is particularly useful is the root mean square fluctuation (RMSF), which shows how each residue flucuates over its average position.\n\nThe RMSF for an atom, $\\rho_i$, is given by:\n\n\\begin{equation}\n\\rho_i = \\sqrt{\\sum^N_{i=1} \\big\\langle(\\mathbf{x}_i - \\langle \\mathbf{x}_i \\rangle )^2 \\big\\rangle }\n\\end{equation}\n\n\n```python\nfrom MDAnalysis.analysis.rms import RMSF as rmsf\n\n# Define again the simulation universe, using however the renumbered .gro file that you had generated earlier\nprotein = MDAnalysis.Universe(f\"{path}/em.gro\", f\"{path}/md_fit.xtc\")\n\n# Reset the trajectory to the first frame\nprotein.trajectory[0]\n\n# We will need to select the alpha Carbons only\ncalphas = protein.select_atoms(\"name CA\")\n\n# Compute the RMSF of alpha carbons. Omit the first 20 frames,\n# assuming that the system needs this amount of time (200 ps) to equilibrate\nrmsf_calc = rmsf(calphas, verbose=True).run(start=20)\n\n# Plot the RMSF\npyplot.plot(calphas.resindices+1, rmsf_calc.rmsf, color='darkorange' )\npyplot.title(\"Per-Residue Alpha Carbon RMSF\")\npyplot.xlabel(\"Residue Number\")\npyplot.ylabel(\"RMSF (Angstrom)\")\npyplot.show()\n```\n\n<span style='color:Blue'> **Questions**  </span> \n\n* Can you identify structural regions alone from this plot and does that fit in with the structure?\n\n\n* Residues 43-58 form part of the flexible flap that covers the binding site. How does this region behave in the simulation? Remember that you have a homodimer, so chain A contains residues 1-99 and chain B contains residues 100 to 198.\n\n### <span style='color:darkred'> 4.3.3 Hydrogen Bond Formation </span>\n\nWe can also use the simulation to monitor the formation of any hydrogen bonds that may be of interest.\n\nIn the case of HIV-1 protease, the hydrogen bonds (HB) that are formed between the ARG8', the ASP29 and the ARG87 amino acids at the interface of the two subunits act in stabilising the dimer.\n\nWe can analyse the trajectory and monitor the stability of these interactions *vs* simulation time.\n\n\n```python\n# Import the MDAnalysis built-in tool for HB Analysis\nfrom MDAnalysis.analysis.hydrogenbonds.hbond_analysis import HydrogenBondAnalysis as HBA\n\n# Define the protein universe\n# Note that when using this tool, it is recommended to include the .tpr file instead of the .gro file,\n# because it contains bond information, required for the identification of donors and acceptors.\nprotein = MDAnalysis.Universe(f\"{path}/md.tpr\", f\"{path}/md.xtc\")\n\n# Define the atom selections for the HB calculation.\n# In this case, the ARG hydrogens and the ASP oxygens, which act as the HB acceptors are specifically defined.\nhbonds = HBA(universe=protein, hydrogens_sel='resname ARG and name HH21 HH22', acceptors_sel='resname ASP and name OD1 OD2')\n\n# Perform the HB calculation\nhbonds.run()\n    \n# Plot the total number of ASP-ARG HBs vs time\nhbonds_time=hbonds.times\nhbonds_data=hbonds.count_by_time()\n\npyplot.plot(hbonds_time, hbonds_data, color='cyan')\npyplot.title(\"ASP-ARG Hydrogen Bonds\")\npyplot.xlabel(\"Time [ps]\")\npyplot.ylabel(\"# Hydrogen Bonds\")\npyplot.show()\n\n# Compute and print the average number of HBs and the standard deviation\naver_hbonds=round(np.mean(hbonds_data), 2)\nstd_hbonds=round(np.std(hbonds_data), 2)\nprint(f\"The average number of ASP-ARG HBs is {aver_hbonds} \u00b1 {std_hbonds}\")\n```\n\n<span style='color:Blue'> **Questions**  </span> \n\n* How much variation is there in the number of hydrogen bonds?\n\n\n* Do any break and not reform? \n\n\n* Using VMD, can you observe the HB formation and breakage throughout the simulation?\n\n***\n\nThis concludes the analysis section, but the aim was only to give you an idea of the numerous information that we can gain when analysing an MD trajectory. Feel free to ask and attempt to answer your own questions, utilising the tools that you were introduced to during the tutorial.\n\n## <span style='color:darkred'> 4.4 Further Reading </span>\n\n\nThe texts recommended here are the same as those mentioned in the lecture:\n* \"Molecular Modelling. Principles and Applications\". Andrew Leach. Publisher: Prentice Hall. ISBN: 0582382106. This book has rapidly become the defacto introductory text for all aspects of simulation.\n* \"Computer simulation of liquids\". Allen, Michael P., and Dominic J. Tildesley. Oxford university press, 2017.\n* \"Molecular Dynamics Simulation: Elementary Methods\". J.M. Haile. Publisher: Wiley. ISBN: 047118439X. This text provides a more focus but slightly more old-fashioned view of simulation. It has some nice simple examples of how to code (in fortran) some of the algorithms though.\n\n\n## <span style='color:darkred'> End of Tutorial </span>\n\nCongratulations, you have finished the MD tutorial. Hopefully, by you are familiar with the molecular dynamics method, the GROMACS software that we have used to perform the simulation, and you have an idea of the type of information that we can extract from an MD run and how we can visualize, compute and plot the data of interest.\n", "meta": {"hexsha": "6bb989192eaebec94604fac61c5919c8699882b5", "size": 21881, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorials/MD/04_Trajectory_Analysis.ipynb", "max_stars_repo_name": "bigginlab/OxCompBio", "max_stars_repo_head_hexsha": "f9d1c9e6e2f51bb4e6bd7cbba83f33f5efef8726", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-12-29T23:59:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T09:45:18.000Z", "max_issues_repo_path": "tutorials/MD/04_Trajectory_Analysis.ipynb", "max_issues_repo_name": "bigginlab/OxCompBio", "max_issues_repo_head_hexsha": "f9d1c9e6e2f51bb4e6bd7cbba83f33f5efef8726", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 97, "max_issues_repo_issues_event_min_datetime": "2019-12-11T12:19:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T12:01:50.000Z", "max_forks_repo_path": "tutorials/MD/remote/04_Trajectory_Analysis.ipynb", "max_forks_repo_name": "bigginlab/OxCompBio", "max_forks_repo_head_hexsha": "f9d1c9e6e2f51bb4e6bd7cbba83f33f5efef8726", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-12-09T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T11:21:32.000Z", "avg_line_length": 39.2132616487, "max_line_length": 709, "alphanum_fraction": 0.6333348567, "converted": true, "num_tokens": 3854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2068940537061185, "lm_q2_score": 0.08389038698317784, "lm_q1q2_score": 0.01735642222992466}}
{"text": "# Setup\n\n\n```python\n%matplotlib inline\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\n```\n\n\n```python\ndata = pd.read_csv(\"articles_2017-11-01_2017-11-30.csv\", index_col=\"id\", \\\n                   parse_dates=[\"published\", \"discovered\"])\ndata.head()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>publisher_name</th>\n      <th>publisher_id</th>\n      <th>mins_as_lead</th>\n      <th>mins_on_front</th>\n      <th>num_articles_on_front</th>\n      <th>fb_brand_page</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>4b92d2afc3eb0becb58ee0f8a866e8bb3e0c6c3c</th>\n      <td>https://www.nytimes.com/2017/11/01/travel/new-...</td>\n      <td>How I Rolled on the Crescent: New York to New ...</td>\n      <td>2017-11-01 10:39:10.125</td>\n      <td>2017-11-01</td>\n      <td>198</td>\n      <td>0.590325</td>\n      <td>2017-11-01T23:02:04.537Z</td>\n      <td>40</td>\n      <td>103</td>\n      <td>55</td>\n      <td>New York Times</td>\n      <td>nytimes_com</td>\n      <td>0</td>\n      <td>2613</td>\n      <td>118.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>120</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>eedd25b64e2cf37cf2198783311a1a823e26965a</th>\n      <td>https://www.nytimes.com/2017/11/01/world/austr...</td>\n      <td>Australia Bans Climbing on Uluru, a Popular Si...</td>\n      <td>2017-11-01 10:54:17.225</td>\n      <td>2017-11-01</td>\n      <td>592</td>\n      <td>1.197048</td>\n      <td>2017-11-01T13:07:04.833Z</td>\n      <td>98</td>\n      <td>302</td>\n      <td>192</td>\n      <td>New York Times</td>\n      <td>nytimes_com</td>\n      <td>0</td>\n      <td>6475</td>\n      <td>120.0</td>\n      <td>True</td>\n      <td>14837915.0</td>\n      <td>2017-11-03T06:25:01.000Z</td>\n      <td>120</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>68cf97046a5705f8c6826ab1fc3ce6e98e845a0d</th>\n      <td>https://www.thetimes.co.uk/article/in-pictures...</td>\n      <td>In pictures: terror in New York</td>\n      <td>2017-11-01 09:59:07.929</td>\n      <td>2017-11-01</td>\n      <td>2</td>\n      <td>0.016398</td>\n      <td>2017-11-01T17:17:03.982Z</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>840</td>\n      <td>275.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>ff04a763b2f01746c4b4718bf2ad150468918bb0</th>\n      <td>https://www.nytimes.com/2017/11/01/upshot/why-...</td>\n      <td>Why Advertising Is a Poor Choice to Tackle the...</td>\n      <td>2017-11-01 10:03:09.094</td>\n      <td>2017-11-01</td>\n      <td>537</td>\n      <td>1.986755</td>\n      <td>2017-11-01T10:14:11.018Z</td>\n      <td>112</td>\n      <td>291</td>\n      <td>134</td>\n      <td>New York Times</td>\n      <td>nytimes_com</td>\n      <td>0</td>\n      <td>5825</td>\n      <td>119.0</td>\n      <td>True</td>\n      <td>14830035.0</td>\n      <td>2017-11-01T10:00:34.000Z</td>\n      <td>120</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1bf0cb152322d6d4ec6f0910f7bbaac27976fe6e</th>\n      <td>https://www.nytimes.com/2017/11/01/podcasts/th...</td>\n      <td>Listen to \u2018The Daily\u2019: Mueller\u2019s Strategy, and...</td>\n      <td>2017-11-01 11:14:11.268</td>\n      <td>2017-11-01</td>\n      <td>164</td>\n      <td>1.393823</td>\n      <td>2017-11-01T12:26:12.465Z</td>\n      <td>30</td>\n      <td>110</td>\n      <td>24</td>\n      <td>New York Times</td>\n      <td>nytimes_com</td>\n      <td>0</td>\n      <td>1375</td>\n      <td>121.0</td>\n      <td>True</td>\n      <td>14830043.0</td>\n      <td>2017-11-01T11:23:06.000Z</td>\n      <td>120</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n# Response Score\n\nThe response score is a number between 0 and 50 that indicates the level of response to an article.\n\n\n\nPerhaps in the future we may choose to include other factors, but for now we just include engagements on Facebook. The maximum score of 50 should be achieved by an article that does really well compared with others.\n\n\n```python\npd.options.display.float_format = '{:.2f}'.format\ndata.fb_engagements.describe([0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count   155376.00\n    mean      1117.87\n    std       8083.39\n    min          0.00\n    50%         24.00\n    75%        233.00\n    90%       1454.00\n    95%       4059.25\n    99%      21166.75\n    99.5%    33982.38\n    99.9%    93932.13\n    max     814679.00\n    Name: fb_engagements, dtype: float64\n\n\n\nThere's no articles with more than 1 million engagements this month.\n\n\n```python\ndata[data.fb_engagements > 1000000]\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>publisher_name</th>\n      <th>publisher_id</th>\n      <th>mins_as_lead</th>\n      <th>mins_on_front</th>\n      <th>num_articles_on_front</th>\n      <th>fb_brand_page</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndata.fb_engagements.mode()\n```\n\n\n\n\n    0    0\n    dtype: int64\n\n\n\nGoing back to the enagement counts, we see the mean is 1,117, mode is zero, median is 24, 90th percentile is 1,453, 99th percentile is 21,166, 99.5th percentile is 33,982. The standard deviation is 8,083, significantly higher than the mean, so this is not a normal distribution. \n\nKey publishers stats\n\n\n```python\ndata.groupby(\"publisher_id\").agg({'url': 'count', 'fb_engagements': ['sum', 'median', 'mean']})\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th>url</th>\n      <th colspan=\"3\" halign=\"left\">fb_engagements</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>count</th>\n      <th>sum</th>\n      <th>median</th>\n      <th>mean</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>46</td>\n      <td>115733</td>\n      <td>1570.00</td>\n      <td>2515.93</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>12497</td>\n      <td>9327679</td>\n      <td>32.00</td>\n      <td>746.39</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>2702</td>\n      <td>11917358</td>\n      <td>224.50</td>\n      <td>4410.57</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>52</td>\n      <td>30476</td>\n      <td>181.50</td>\n      <td>586.08</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>1609</td>\n      <td>4482917</td>\n      <td>159.00</td>\n      <td>2786.15</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>3425</td>\n      <td>17299480</td>\n      <td>550.00</td>\n      <td>5050.94</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>23842</td>\n      <td>17151377</td>\n      <td>28.00</td>\n      <td>719.38</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>581</td>\n      <td>190826</td>\n      <td>30.00</td>\n      <td>328.44</td>\n    </tr>\n    <tr>\n      <th>evolvepolitics_com</th>\n      <td>61</td>\n      <td>153821</td>\n      <td>1413.00</td>\n      <td>2521.66</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>5323</td>\n      <td>15572831</td>\n      <td>74.00</td>\n      <td>2925.57</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>4997</td>\n      <td>344064</td>\n      <td>4.00</td>\n      <td>68.85</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>9772</td>\n      <td>13145495</td>\n      <td>11.00</td>\n      <td>1345.22</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>6567</td>\n      <td>8859577</td>\n      <td>36.00</td>\n      <td>1349.11</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>545</td>\n      <td>765012</td>\n      <td>107.00</td>\n      <td>1403.69</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>3991</td>\n      <td>2567387</td>\n      <td>76.00</td>\n      <td>643.29</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>170</td>\n      <td>2676</td>\n      <td>7.00</td>\n      <td>15.74</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>10121</td>\n      <td>6778308</td>\n      <td>46.00</td>\n      <td>669.73</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>2003</td>\n      <td>6196290</td>\n      <td>478.00</td>\n      <td>3093.50</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>526</td>\n      <td>83158</td>\n      <td>22.00</td>\n      <td>158.10</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>2102</td>\n      <td>6461653</td>\n      <td>160.00</td>\n      <td>3074.05</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>4830</td>\n      <td>18352173</td>\n      <td>214.00</td>\n      <td>3799.62</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>267</td>\n      <td>95238</td>\n      <td>143.00</td>\n      <td>356.70</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>57</td>\n      <td>68028</td>\n      <td>365.00</td>\n      <td>1193.47</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>5952</td>\n      <td>1866563</td>\n      <td>23.00</td>\n      <td>313.60</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>2691</td>\n      <td>2228324</td>\n      <td>207.00</td>\n      <td>828.07</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>117</td>\n      <td>57044</td>\n      <td>284.00</td>\n      <td>487.56</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>7571</td>\n      <td>2685206</td>\n      <td>16.00</td>\n      <td>354.67</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>251</td>\n      <td>363674</td>\n      <td>849.00</td>\n      <td>1448.90</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>8493</td>\n      <td>10074837</td>\n      <td>137.00</td>\n      <td>1186.25</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>9195</td>\n      <td>292184</td>\n      <td>1.00</td>\n      <td>31.78</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>24278</td>\n      <td>14213560</td>\n      <td>0.00</td>\n      <td>585.45</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>350</td>\n      <td>429874</td>\n      <td>40.00</td>\n      <td>1228.21</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>392</td>\n      <td>1517525</td>\n      <td>232.00</td>\n      <td>3871.24</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\n\nnon_zero_fb_enagagements = data.fb_engagements[data.fb_engagements > 0]\n```\n\nThat's a bit better, but still way too clustered at the low end. Let's look at a log normal distribution.\n\n\n```python\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\nninety = data.fb_engagements.quantile(.90)\nninetyfive = data.fb_engagements.quantile(.95)\nninetynine = data.fb_engagements.quantile(.99)\n\nplt.figure(figsize=(12,4.5))\nplt.hist(np.log(non_zero_fb_enagagements + median), bins=50)\nplt.axvline(np.log(mean), linestyle=':', label=f'Mean ({mean:,.0f})', color='green')\nplt.axvline(np.log(median), label=f'Median ({median:,.0f})', color='green')\nplt.axvline(np.log(ninety), linestyle='--', label=f'90% percentile ({ninety:,.0f})', color='red')\nplt.axvline(np.log(ninetyfive), linestyle='-.', label=f'95% percentile ({ninetyfive:,.0f})', color='red')\nplt.axvline(np.log(ninetynine), linestyle=':', label=f'99% percentile ({ninetynine:,.0f})', color='red')\nleg = plt.legend()\n\n```\n\n\n```python\neng = data.fb_engagements[(data.fb_engagements < 5000)]\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\nninety = data.fb_engagements.quantile(.90)\nninetyfive = data.fb_engagements.quantile(.95)\nninetynine = data.fb_engagements.quantile(.99)\n\nplt.figure(figsize=(15,7))\nplt.hist(eng, bins=50)\nplt.title(\"Article count by engagements\")\nplt.axvline(median, label=f'Median ({median:,.0f})', color='green')\nplt.axvline(mean, linestyle=':', label=f'Mean ({mean:,.0f})', color='green')\nplt.axvline(ninety, linestyle='--', label=f'90% percentile ({ninety:,.0f})', color='red')\nplt.axvline(ninetyfive, linestyle='-.', label=f'95% percentile ({ninetyfive:,.0f})', color='red')\n# plt.axvline(ninetynine, linestyle=':', label=f'99% percentile ({ninetynine:,.0f})', color='red')\nleg = plt.legend()\n\n```\n\n\n```python\nlog_engagements = (non_zero_fb_enagagements\n                   .clip_upper(data.fb_engagements.quantile(.999))\n                   .apply(lambda x: np.log(x + median))\n                  )\nlog_engagements.describe()\n```\n\n\n\n\n    count   124947.00\n    mean         4.98\n    std          1.76\n    min          3.22\n    25%          3.50\n    50%          4.39\n    75%          6.03\n    max         11.45\n    Name: fb_engagements, dtype: float64\n\n\n\nUse standard feature scaling to bring that to a 1 to 50 range\n\n\n\n```python\ndef scale_log_engagements(engagements_logged):\n    return np.ceil(\n        50 * (engagements_logged - log_engagements.min()) / (log_engagements.max() - log_engagements.min())\n    )\n\ndef scale_engagements(engagements):\n    return scale_log_engagements(np.log(engagements + median))\n\nscaled_non_zero_engagements = scale_log_engagements(log_engagements)\nscaled_non_zero_engagements.describe()\n```\n\n\n\n\n    count   124947.00\n    mean        11.17\n    std         10.74\n    min          0.00\n    25%          2.00\n    50%          8.00\n    75%         18.00\n    max         50.00\n    Name: fb_engagements, dtype: float64\n\n\n\n\n```python\n# add in the zeros, as zero\nscaled_engagements = pd.concat([scaled_non_zero_engagements, data.fb_engagements[data.fb_engagements == 0]])\n```\n\n\n```python\nproposed = pd.DataFrame({\"fb_engagements\": data.fb_engagements, \"response_score\": scaled_engagements})\nproposed.response_score.plot.hist(bins=50)\n```\n\nLooks good to me, lets save that.\n\n\n```python\ndata[\"response_score\"] = proposed.response_score\n```\n\n### Proposal\n\nThe maximum of 50 points is awarded when the engagements are greater than the 99.9th percentile, rolling over the last month. \n\ni.e. where $limit$ is the 99.5th percentile of engagements calculated over the previous month, the response score for article $a$ is:\n\n\\begin{align}\nbasicScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   \\log(\\min(engagements_a,limit) + median(engagements))      & \\text{if } engagements_a > 0\n\\end{cases} \\\\\nresponseScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   50 \\cdot \\frac{basicScore_a - \\min(basicScore)}{\\max(basicScore) - \\min(basicScore)}       & \\text{if } engagements_a > 0\n\\end{cases} \\\\\n\\\\\n\\text{The latter equation can be expanded to:} \\\\\nresponseScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   50 \\cdot \n   \\frac{\\log(\\min(engagements_a,limit) + median(engagements)) - \\log(1 + median(engagements))}\n   {\\log(limit + median(engagements)) - \\log(1 + median(engagements))}       & \\text{if } engagements_a > 0\n\\end{cases} \\\\\n\\end{align}\n\n# Promotion Score\n\nThe aim of the promotion score is to indicate how important the article was to the publisher, by tracking where they chose to promote it. This is a number between 0 and 50 comprised of:\n\n- 20 points based on whether the article was promoted as the \"lead\" story on the publisher's home page\n- 15 points based on how long the article was promoted anywhere on the publisher's home page\n- 15 points based on whether the article was promoted on the publisher's main facebook brand page\n\nThe first two should be scaled by the popularity/reach of the home page, for which we use the alexa page rank as a proxy.\n\nThe last should be scaled by the popularity/reach of the brand page, for which we use the number of likes the brand page has.\n\n### Lead story (20 points)\n\n\n```python\ndata.mins_as_lead.describe([0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count   155376.00\n    mean         9.19\n    std        103.71\n    min          0.00\n    50%          0.00\n    75%          0.00\n    90%          0.00\n    95%          0.00\n    99%        269.00\n    99.5%      574.00\n    99.9%     1219.00\n    max      22314.00\n    Name: mins_as_lead, dtype: float64\n\n\n\nAs expected, the vast majority of articles don't make it as lead. Let's explore how long typically publishers put something as lead for.\n\n\n```python\nlead_articles = data[data.mins_as_lead > 0]\n```\n\n\n```python\nlead_articles.mins_as_lead.describe([0.25, 0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count    4321.00\n    mean      330.52\n    std       529.72\n    min         4.00\n    25%        80.00\n    50%       174.00\n    75%       412.00\n    90%       869.00\n    95%      1105.00\n    99%      1609.80\n    99.5%    1938.40\n    99.9%    4460.68\n    max     22314.00\n    Name: mins_as_lead, dtype: float64\n\n\n\n\n```python\nlead_articles.mins_as_lead.plot.hist(bins=50)\n```\n\nFor lead, it's a  significant thing for an article to be lead at all, so although we want to penalise articles that were lead for a very short time, mostly we want to score the maximum even if it wasn't lead for ages. So we'll give maximum points when something has been lead for an hour.\n\n\n```python\nlead_articles.mins_as_lead.clip_upper(60).plot.hist(bins=50)\n```\n\nWe also want to scale this by the alexa page rank, such that the maximum score of 20 points is for an article that was on the front for 4 hours for the most popular site.\n\nSo lets explore the alexa nunbers.\n\n\n```python\nalexa_ranks = data.groupby(by=\"publisher_id\").alexa_rank.mean().sort_values()\nalexa_ranks\n```\n\n\n\n\n    publisher_id\n    bbc_co_uk                               96\n    cnn_com                                105\n    nytimes_com                            120\n    theguardian_com                        142\n    buzzfeed_com                           147\n    dailymail_co_uk                        158\n    washingtonpost_com                     191\n    huffingtonpost_com                     215\n    foxnews_com                            285\n    rt_com                                 365\n    telegraph_co_uk                        370\n    independent_co_uk                      386\n    reuters_com                            497\n    npr_org                                594\n    lemonde_fr                             618\n    mirror_co_uk                           706\n    nbcnews_com                            826\n    breitbart_com                          994\n    ft_com                                1596\n    economist_com                         1825\n    indy100_com                           5014\n    thetimes_co_uk                        6435\n    newstatesman_com                     12769\n    thecanary_co                         15686\n    propublica_org                       16066\n    yournewswire_com                     22568\n    order-order_com                      32515\n    anotherangryvoice_blogspot_co_uk     77827\n    westmonster_com                      97775\n    evolvepolitics_com                  119412\n    skwawkbox_org                       152475\n    libdemvoice_org                     344992\n    brexitcentral_com                   469149\n    Name: alexa_rank, dtype: int64\n\n\n\n\n```python\nalexa_ranks.plot.bar(figsize=[10,5])\n```\n\nLet's try the simple option first: just divide the number of minutes as lead by the alexa rank. What's the scale of numbers we get then.\n\n\n```python\nlead_proposal_1 = lead_articles.mins_as_lead.clip_upper(60) / lead_articles.alexa_rank\nlead_proposal_1.plot.hist()\n```\n\nLooks like there's too much of a cluster around 0. Have we massively over penalised the publishers with a high alexa rank?\n\n\n```python\nlead_proposal_1.groupby(data.publisher_id).mean().plot.bar(figsize=[10,5])\n```\n\nYes. Let's try taking the log of the alexa rank and see if that looks better.\n\n\n```python\nlead_proposal_2 = (lead_articles.mins_as_lead.clip_upper(60) / np.log(lead_articles.alexa_rank))\nlead_proposal_2.plot.hist()\n```\n\n\n```python\nlead_proposal_2.groupby(data.publisher_id).describe()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>25%</th>\n      <th>50%</th>\n      <th>75%</th>\n      <th>max</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>46.00</td>\n      <td>5.26</td>\n      <td>0.47</td>\n      <td>2.13</td>\n      <td>5.33</td>\n      <td>5.33</td>\n      <td>5.33</td>\n      <td>5.33</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>95.00</td>\n      <td>12.89</td>\n      <td>1.14</td>\n      <td>5.26</td>\n      <td>13.15</td>\n      <td>13.15</td>\n      <td>13.15</td>\n      <td>13.15</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>183.00</td>\n      <td>8.43</td>\n      <td>0.94</td>\n      <td>3.48</td>\n      <td>8.69</td>\n      <td>8.69</td>\n      <td>8.69</td>\n      <td>8.69</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>39.00</td>\n      <td>4.49</td>\n      <td>0.63</td>\n      <td>0.69</td>\n      <td>4.59</td>\n      <td>4.59</td>\n      <td>4.59</td>\n      <td>4.59</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>302.00</td>\n      <td>11.75</td>\n      <td>1.16</td>\n      <td>3.01</td>\n      <td>12.02</td>\n      <td>12.02</td>\n      <td>12.02</td>\n      <td>12.02</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>201.00</td>\n      <td>12.27</td>\n      <td>1.97</td>\n      <td>2.15</td>\n      <td>12.89</td>\n      <td>12.89</td>\n      <td>12.89</td>\n      <td>12.89</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>165.00</td>\n      <td>11.45</td>\n      <td>1.58</td>\n      <td>2.77</td>\n      <td>11.85</td>\n      <td>11.85</td>\n      <td>11.85</td>\n      <td>11.85</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>65.00</td>\n      <td>7.65</td>\n      <td>1.56</td>\n      <td>0.53</td>\n      <td>7.99</td>\n      <td>7.99</td>\n      <td>7.99</td>\n      <td>7.99</td>\n    </tr>\n    <tr>\n      <th>evolvepolitics_com</th>\n      <td>24.00</td>\n      <td>5.13</td>\n      <td>0.00</td>\n      <td>5.13</td>\n      <td>5.13</td>\n      <td>5.13</td>\n      <td>5.13</td>\n      <td>5.13</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>106.00</td>\n      <td>10.47</td>\n      <td>1.07</td>\n      <td>0.88</td>\n      <td>10.61</td>\n      <td>10.61</td>\n      <td>10.61</td>\n      <td>10.61</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>93.00</td>\n      <td>7.21</td>\n      <td>2.11</td>\n      <td>0.54</td>\n      <td>8.14</td>\n      <td>8.14</td>\n      <td>8.14</td>\n      <td>8.14</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>177.00</td>\n      <td>10.92</td>\n      <td>1.04</td>\n      <td>2.79</td>\n      <td>11.17</td>\n      <td>11.17</td>\n      <td>11.17</td>\n      <td>11.17</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>136.00</td>\n      <td>9.75</td>\n      <td>1.33</td>\n      <td>1.68</td>\n      <td>10.07</td>\n      <td>10.07</td>\n      <td>10.07</td>\n      <td>10.07</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>192.00</td>\n      <td>5.52</td>\n      <td>2.00</td>\n      <td>0.59</td>\n      <td>3.87</td>\n      <td>7.04</td>\n      <td>7.04</td>\n      <td>7.04</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>162.00</td>\n      <td>8.74</td>\n      <td>1.73</td>\n      <td>0.62</td>\n      <td>9.34</td>\n      <td>9.34</td>\n      <td>9.34</td>\n      <td>9.34</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>146.00</td>\n      <td>4.58</td>\n      <td>0.52</td>\n      <td>1.49</td>\n      <td>4.71</td>\n      <td>4.71</td>\n      <td>4.71</td>\n      <td>4.71</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>317.00</td>\n      <td>8.65</td>\n      <td>1.37</td>\n      <td>2.29</td>\n      <td>9.15</td>\n      <td>9.15</td>\n      <td>9.15</td>\n      <td>9.15</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>109.00</td>\n      <td>8.85</td>\n      <td>0.74</td>\n      <td>1.34</td>\n      <td>8.93</td>\n      <td>8.93</td>\n      <td>8.93</td>\n      <td>8.93</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>64.00</td>\n      <td>6.04</td>\n      <td>1.03</td>\n      <td>0.42</td>\n      <td>6.35</td>\n      <td>6.35</td>\n      <td>6.35</td>\n      <td>6.35</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>163.00</td>\n      <td>8.89</td>\n      <td>1.68</td>\n      <td>0.63</td>\n      <td>9.39</td>\n      <td>9.39</td>\n      <td>9.39</td>\n      <td>9.39</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>53.00</td>\n      <td>12.27</td>\n      <td>1.60</td>\n      <td>1.04</td>\n      <td>12.53</td>\n      <td>12.53</td>\n      <td>12.53</td>\n      <td>12.53</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>258.00</td>\n      <td>4.48</td>\n      <td>1.59</td>\n      <td>0.39</td>\n      <td>3.27</td>\n      <td>5.68</td>\n      <td>5.78</td>\n      <td>5.78</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>24.00</td>\n      <td>5.80</td>\n      <td>1.36</td>\n      <td>0.52</td>\n      <td>6.20</td>\n      <td>6.20</td>\n      <td>6.20</td>\n      <td>6.20</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>90.00</td>\n      <td>9.24</td>\n      <td>1.73</td>\n      <td>0.81</td>\n      <td>9.66</td>\n      <td>9.66</td>\n      <td>9.66</td>\n      <td>9.66</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>128.00</td>\n      <td>9.22</td>\n      <td>2.50</td>\n      <td>0.85</td>\n      <td>10.17</td>\n      <td>10.17</td>\n      <td>10.17</td>\n      <td>10.17</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>116.00</td>\n      <td>4.70</td>\n      <td>0.92</td>\n      <td>0.42</td>\n      <td>5.03</td>\n      <td>5.03</td>\n      <td>5.03</td>\n      <td>5.03</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>84.00</td>\n      <td>9.87</td>\n      <td>1.38</td>\n      <td>0.85</td>\n      <td>10.15</td>\n      <td>10.15</td>\n      <td>10.15</td>\n      <td>10.15</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>228.00</td>\n      <td>4.70</td>\n      <td>1.70</td>\n      <td>0.52</td>\n      <td>3.52</td>\n      <td>5.18</td>\n      <td>6.21</td>\n      <td>6.21</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>141.00</td>\n      <td>11.49</td>\n      <td>2.01</td>\n      <td>2.02</td>\n      <td>12.11</td>\n      <td>12.11</td>\n      <td>12.11</td>\n      <td>12.11</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>73.00</td>\n      <td>6.82</td>\n      <td>0.21</td>\n      <td>5.02</td>\n      <td>6.84</td>\n      <td>6.84</td>\n      <td>6.84</td>\n      <td>6.84</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>90.00</td>\n      <td>11.17</td>\n      <td>1.20</td>\n      <td>3.62</td>\n      <td>11.42</td>\n      <td>11.42</td>\n      <td>11.42</td>\n      <td>11.42</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>77.00</td>\n      <td>4.71</td>\n      <td>1.23</td>\n      <td>0.78</td>\n      <td>5.22</td>\n      <td>5.22</td>\n      <td>5.22</td>\n      <td>5.22</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>174.00</td>\n      <td>5.68</td>\n      <td>0.68</td>\n      <td>2.39</td>\n      <td>5.79</td>\n      <td>5.99</td>\n      <td>5.99</td>\n      <td>5.99</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nlead_proposal_2.groupby(data.publisher_id).min().plot.bar(figsize=[10,5])\n```\n\nThat looks about right, as long as the smaller publishers were closer to zero. So let's apply feature scaling to this, to give a number between 1 and 20. (Anything not as lead will pass though as zero.)\n\n\n```python\ndef rescale(series):\n    return (series - series.min()) / (series.max() - series.min())\n\nlead_proposal_3 = np.ceil(20 * rescale(lead_proposal_2))\n```\n\n\n```python\nlead_proposal_2.min(), lead_proposal_2.max()\n```\n\n\n\n\n    (0.38500569152790032, 13.145359968846892)\n\n\n\n\n```python\nlead_proposal_3.plot.hist()\n```\n\n\n```python\nlead_proposal_3.groupby(data.publisher_id).median().plot.bar(figsize=[10,5])\n```\n\n\n```python\ndata[\"lead_score\"] = pd.concat([lead_proposal_3, data.mins_as_lead[data.mins_as_lead==0]])\n```\n\n\n```python\ndata.lead_score.value_counts().sort_index()\n```\n\n\n\n\n    0.00     151057\n    1.00         47\n    2.00         34\n    3.00         54\n    4.00         75\n    5.00         78\n    6.00         67\n    7.00        272\n    8.00        303\n    9.00        312\n    10.00       199\n    11.00       193\n    12.00        89\n    13.00       101\n    14.00       556\n    15.00       375\n    16.00       320\n    17.00       280\n    18.00       244\n    19.00       403\n    20.00       317\n    Name: lead_score, dtype: int64\n\n\n\n\n```python\ndata.lead_score.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    8.00\n    bbc_co_uk                          20.00\n    breitbart_com                      14.00\n    brexitcentral_com                   7.00\n    buzzfeed_com                       19.00\n    cnn_com                            20.00\n    dailymail_co_uk                    18.00\n    economist_com                      12.00\n    evolvepolitics_com                  8.00\n    foxnews_com                        17.00\n    ft_com                             13.00\n    huffingtonpost_com                 17.00\n    independent_co_uk                  16.00\n    indy100_com                        11.00\n    lemonde_fr                         15.00\n    libdemvoice_org                     7.00\n    mirror_co_uk                       14.00\n    nbcnews_com                        14.00\n    newstatesman_com                   10.00\n    npr_org                            15.00\n    nytimes_com                        20.00\n    order-order_com                     9.00\n    propublica_org                     10.00\n    reuters_com                        15.00\n    rt_com                             16.00\n    skwawkbox_org                       8.00\n    telegraph_co_uk                    16.00\n    thecanary_co                       10.00\n    theguardian_com                    19.00\n    thetimes_co_uk                     11.00\n    washingtonpost_com                 18.00\n    westmonster_com                     8.00\n    yournewswire_com                    9.00\n    Name: lead_score, dtype: float64\n\n\n\nIn summary then, score for article $a$ is:\n\n\n$$\nunscaledLeadScore_a = \\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)}\\\\\nleadScore_a = 19 \\cdot \n\\frac{unscaledLeadScore_a - \\min(unscaledLeadScore)}\n{\\max(unscaledLeadScore) - \\min(unscaledLeadScore)} \n+ 1\n$$\n\nSince the minium value of $minsAsLead$ is 1, $\\min(unscaledLeadScore)$ is pretty insignificant. So we can simplify this to:\n\n$$\nleadScore_a = 20 \\cdot \n\\frac{unscaledLeadScore_a }\n     {\\max(unscaledLeadScore)} \n$$\n\nor: \n\n$$\nleadScore_a = 20 \\cdot \n\\frac{\\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)} }\n     {\\frac{60}{\\log(\\max(alexaRank))}} \n$$\n\n$$\nleadScore_a = \\left( 20 \\cdot \n\\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)} \\cdot\n     {\\frac{\\log(\\max(alexaRank))}{60}} \\right)\n$$\n\n## Time on front score (15 points)\n\nThis is similar to time as lead, so lets try doing the same calculation, except we also want to factor in the number of slots on the front:\n\n\n$$frontScore_a = \n15 \n\\left(\\frac{\\min(minsOnFront_a, 1440)}{alexaRank_a \\cdot numArticlesOnFront_a}\\right) \n\\left( \\frac{\\min(alexaRank \\cdot numArticlesOnFront)}{1440} \\right)$$\n\n\n```python\n(data.alexa_rank * data.num_articles_on_front).min() / 1440\n```\n\n\n\n\n    2.4500000000000002\n\n\n\n\n```python\ntime_on_front_proposal_1 = np.ceil(data.mins_on_front.clip_upper(1440) / (data.alexa_rank * data.num_articles_on_front) * (2.45) * 15)\n```\n\n\n```python\ntime_on_front_proposal_1.plot.hist(figsize=(15, 7), bins=15)\n```\n\n\n```python\ntime_on_front_proposal_1.value_counts().sort_index()\n```\n\n\n\n\n    1.00     72664\n    2.00      6937\n    3.00      4459\n    4.00      3846\n    5.00       845\n    6.00       539\n    7.00       513\n    8.00       706\n    9.00       678\n    10.00      222\n    11.00      339\n    12.00      298\n    13.00      145\n    14.00       96\n    15.00       47\n    dtype: int64\n\n\n\n\n```python\ntime_on_front_proposal_1.groupby(data.publisher_id).sum()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk      46.00\n    bbc_co_uk                          15119.00\n    breitbart_com                       2606.00\n    brexitcentral_com                     52.00\n    buzzfeed_com                        9698.00\n    cnn_com                            11792.00\n    dailymail_co_uk                    13965.00\n    economist_com                        319.00\n    evolvepolitics_com                    60.00\n    foxnews_com                         6473.00\n    ft_com                              3167.00\n    huffingtonpost_com                  7534.00\n    independent_co_uk                   4431.00\n    indy100_com                          534.00\n    lemonde_fr                          3972.00\n    libdemvoice_org                      170.00\n    mirror_co_uk                        9502.00\n    nbcnews_com                         1937.00\n    newstatesman_com                     515.00\n    npr_org                             2449.00\n    nytimes_com                         9488.00\n    order-order_com                      267.00\n    propublica_org                        57.00\n    reuters_com                         6863.00\n    rt_com                              4421.00\n    skwawkbox_org                        117.00\n    telegraph_co_uk                     4950.00\n    thecanary_co                         249.00\n    theguardian_com                    12252.00\n    thetimes_co_uk                      9155.00\n    washingtonpost_com                  8679.00\n    westmonster_com                      327.00\n    yournewswire_com                     392.00\n    dtype: float64\n\n\n\nThat looks good to me.\n\n\n```python\ndata[\"front_score\"] = np.ceil(data.mins_on_front.clip_upper(1440) / (data.alexa_rank * data.num_articles_on_front) * (2.45) * 15).fillna(0)\n```\n\n\n```python\ndata.front_score \n```\n\n\n\n\n    id\n    4b92d2afc3eb0becb58ee0f8a866e8bb3e0c6c3c   4.00\n    eedd25b64e2cf37cf2198783311a1a823e26965a   4.00\n    68cf97046a5705f8c6826ab1fc3ce6e98e845a0d   1.00\n    ff04a763b2f01746c4b4718bf2ad150468918bb0   4.00\n    1bf0cb152322d6d4ec6f0910f7bbaac27976fe6e   4.00\n    60192d56f7ff0332b325c51b3a9c5ac59d42c525   1.00\n    40a59853e4642a4ababa6938176089b8775c4016   1.00\n    d1e05106c3ec699a37bf8f26ab63e4dbebcd4971   4.00\n    ed61f808ac7756c2d73dfdf6855c34786bc9de02   2.00\n    bbadee9289eea2f0b6b6220f9f613578c37ef621   1.00\n    063a022e6f66ec2763b22a815ec25471e22287e3   1.00\n    478f397e1c731872fba60a4189bc72c924cfc847   1.00\n    17f0678815a01ee8e4914e30d612c294c78c68b8   1.00\n    1b7a6a9b1aea0996b27cf0f5460fa23bdd179067   1.00\n    348163ba67b3cd7e989236ce8a739b74f81cd67e   1.00\n    99f97d2f01a3c2dc40da166b18abacdbc85b9634   1.00\n    587272809793b00754536e86b8f535cc5fbc9700   1.00\n    57326012898026faf47a6e5969e4e3a6ebe9005d   1.00\n    13ac494c2c23dfe4395decfd9882e4851a1cd679   1.00\n    e3a02a337c53a78300d7e3c238a7ba2084705106   1.00\n    d00575f8a0fddb2cf4481ad4844aea24f481d07c   1.00\n    079efcd636a42a2302cdc5f8ec20ea640189dd03   1.00\n    487fb90db5d16301835c7c6b85e27183ab20f96d   1.00\n    13316d1e0c194706fed4d779a5fbc431aa845187   1.00\n    89444e353ce245b819ed5e42a16bfbd31df8a367   1.00\n    faf1c9acda717cd3729d4093cec850f5fda1a615   1.00\n    a96249330370dd853da8021f2c1f42a83a2e9c76   1.00\n    bb78be89d6a53016f4378af44c02edc5a29c7eca   1.00\n    0da8e2a7525e7d8f5037f87d00641bb7def15a0e   1.00\n    710e0b5316bc13656fda544dbcea145c1e62094b   1.00\n                                               ... \n    4945d0f879fe8c25617b8d0f04e5395d0d02c6a7   0.00\n    b7d2aa4539fd0bcc0ad944702db6f3353e3437f3   1.00\n    f6d35f22cec3ec9e9d1ec62f1b9b9b2cab96ba3b   0.00\n    3c35b93d4d2e7273ac60fcf566ec04cd2ed52040   0.00\n    a8d249980496930270c3f62ea40437b569b4a576   1.00\n    35d67981fc107b0db3b7e2c380dc6c48d1a276a7   1.00\n    780d2a1296546116e450fba4fd0fb48e312fbb6f   0.00\n    5d838bb1a1bd01e170c8e46e77f9a6d042e910c0   0.00\n    fdb933725e53ed0d1cbb57bacf915e72e42d6976   1.00\n    0e330800c766a79bb09a8750b3e2f2a0f3b495a9   1.00\n    ed642f48391d369b5d362c3bd0a58a9441b2e47d   2.00\n    00b2260e4769744ec5cf2dc1973736cf26113947   1.00\n    3c262b96680f65dcfcce7b33c0fc9a5c42e5ae06   0.00\n    7c426e09e5f44abd8316c21e2d753c67b53c6b3b   0.00\n    20600f6fd9847e684df22803751f6c1ea4854fc4   2.00\n    a3cf9f323bb8e614c64ac8528216820b752fe965   0.00\n    0272fffeb0b5bb264a2ae049a34f101303d73350   0.00\n    bc4c1078dd7ee60f67d89c574aa2ead98b4a7f6a   1.00\n    8953c649cea6fad178563a9630ac88cb37f45515   0.00\n    b545fcbbc649daa5be3e2f678de536e2cd3eb8cc   1.00\n    1ab07de99305bb0052286646d8619c73aa47b6a8   0.00\n    302a10f2a9db8c489f079ff7cf04ec43967b899c   0.00\n    e0717c56dc5adbb093e3061d99985f2a7e32a78d   0.00\n    2e6ec6e3dcbcee6d16eaf7f2d6423bbf95ee243d   1.00\n    83fbd4044262f67fe0582658b64b69644013992a   0.00\n    1b578330a91e65cb11e9a5ce7ea7770ff0c0c2dd   3.00\n    cec0dd5ed9522d45461cad6451329493993bffe4   1.00\n    31fa3fd4a146c7e6ca5a68ae61a7cd84dba9708f   2.00\n    301e95874ced17644b54ce912152dd955f1b36f7   1.00\n    7dfb319c50b823a7a353edbb239d34cdaa5d8378   0.00\n    Name: front_score, Length: 155376, dtype: float64\n\n\n\n## Facebook brand page promotion (15 points)\n\nOne way a publisher has of promoting content is to post to their brand page. The significance of doing so is stronger when the brand page has more followers (likes).\n\n$$ facebookPromotionProposed1_a = 15 \\left( \\frac {brandPageLikes_a} {\\max(brandPageLikes)} \\right) $$\n\nNow lets explore the data to see if that makes sense. **tr;dr the formula above is incorrect**\n\n\n```python\ndata.fb_brand_page_likes.max()\n```\n\n\n\n\n    45013800.0\n\n\n\n\n```python\nfacebook_promotion_proposed_1 = np.ceil((15 * (data.fb_brand_page_likes / data.fb_brand_page_likes.max())).fillna(0))\n```\n\n\n```python\nfacebook_promotion_proposed_1.value_counts().sort_index().plot.bar()\n```\n\n\n```python\nfacebook_promotion_proposed_1.groupby(data.publisher_id).describe()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>25%</th>\n      <th>50%</th>\n      <th>75%</th>\n      <th>max</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>46.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>12497.00</td>\n      <td>0.58</td>\n      <td>2.89</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>15.00</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>2702.00</td>\n      <td>0.84</td>\n      <td>0.99</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>52.00</td>\n      <td>0.98</td>\n      <td>0.14</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>1609.00</td>\n      <td>0.30</td>\n      <td>0.46</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>3425.00</td>\n      <td>2.79</td>\n      <td>4.49</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>10.00</td>\n      <td>10.00</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>23842.00</td>\n      <td>0.56</td>\n      <td>1.58</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>5.00</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>581.00</td>\n      <td>2.32</td>\n      <td>1.26</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>evolvepolitics_com</th>\n      <td>61.00</td>\n      <td>0.90</td>\n      <td>0.30</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>5323.00</td>\n      <td>0.81</td>\n      <td>2.05</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>6.00</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>4997.00</td>\n      <td>0.41</td>\n      <td>0.81</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>9772.00</td>\n      <td>0.46</td>\n      <td>1.27</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>6567.00</td>\n      <td>0.57</td>\n      <td>1.17</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>545.00</td>\n      <td>0.67</td>\n      <td>0.47</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>3991.00</td>\n      <td>0.79</td>\n      <td>0.98</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>170.00</td>\n      <td>0.88</td>\n      <td>0.32</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>10121.00</td>\n      <td>0.25</td>\n      <td>0.43</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>2003.00</td>\n      <td>2.29</td>\n      <td>1.98</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>526.00</td>\n      <td>0.74</td>\n      <td>0.44</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>2102.00</td>\n      <td>1.36</td>\n      <td>1.49</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>4830.00</td>\n      <td>1.55</td>\n      <td>2.31</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>5.00</td>\n      <td>5.00</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>267.00</td>\n      <td>0.80</td>\n      <td>0.40</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>57.00</td>\n      <td>0.82</td>\n      <td>0.38</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>5952.00</td>\n      <td>0.61</td>\n      <td>0.92</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>2691.00</td>\n      <td>0.93</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>117.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>7571.00</td>\n      <td>0.50</td>\n      <td>0.87</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>251.00</td>\n      <td>0.98</td>\n      <td>0.15</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>8493.00</td>\n      <td>0.52</td>\n      <td>1.13</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>9195.00</td>\n      <td>0.05</td>\n      <td>0.23</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>24278.00</td>\n      <td>0.17</td>\n      <td>0.69</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>350.00</td>\n      <td>0.26</td>\n      <td>0.44</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>392.00</td>\n      <td>0.08</td>\n      <td>0.27</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThat's too much variation: sites like the Guardian, which have a respectable 7.5m likes, should not be scoring a 3. Lets try applying a log to it, and then standard feature scaling again.\n\n\n```python\ndata.fb_brand_page_likes.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk     330305.00\n    bbc_co_uk                          45013800.00\n    breitbart_com                       3748243.00\n    brexitcentral_com                     12499.00\n    buzzfeed_com                        2795165.00\n    cnn_com                            29252657.00\n    dailymail_co_uk                    13536602.00\n    economist_com                       8387474.00\n    evolvepolitics_com                   114880.00\n    foxnews_com                        16052065.00\n    ft_com                              3709965.00\n    huffingtonpost_com                  9815158.00\n    independent_co_uk                   7842115.00\n    indy100_com                          231700.00\n    lemonde_fr                          3949946.00\n    libdemvoice_org                        8615.00\n    mirror_co_uk                        2926052.00\n    nbcnews_com                         9381825.00\n    newstatesman_com                     154735.00\n    npr_org                             6252770.00\n    nytimes_com                        14989576.00\n    order-order_com                       45143.00\n    propublica_org                       371738.00\n    reuters_com                         3914921.00\n    rt_com                              4705596.00\n    skwawkbox_org                          6104.00\n    telegraph_co_uk                     4390313.00\n    thecanary_co                         156466.00\n    theguardian_com                     7809686.00\n    thetimes_co_uk                       718296.00\n    washingtonpost_com                  6090176.00\n    westmonster_com                       16158.00\n    yournewswire_com                      27271.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\nnp.log(2149)\n```\n\n\n\n\n    7.6727578966425103\n\n\n\n\n```python\nnp.log(data.fb_brand_page_likes.groupby(data.publisher_id).max())\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk   12.71\n    bbc_co_uk                          17.62\n    breitbart_com                      15.14\n    brexitcentral_com                   9.43\n    buzzfeed_com                       14.84\n    cnn_com                            17.19\n    dailymail_co_uk                    16.42\n    economist_com                      15.94\n    evolvepolitics_com                 11.65\n    foxnews_com                        16.59\n    ft_com                             15.13\n    huffingtonpost_com                 16.10\n    independent_co_uk                  15.88\n    indy100_com                        12.35\n    lemonde_fr                         15.19\n    libdemvoice_org                     9.06\n    mirror_co_uk                       14.89\n    nbcnews_com                        16.05\n    newstatesman_com                   11.95\n    npr_org                            15.65\n    nytimes_com                        16.52\n    order-order_com                    10.72\n    propublica_org                     12.83\n    reuters_com                        15.18\n    rt_com                             15.36\n    skwawkbox_org                       8.72\n    telegraph_co_uk                    15.29\n    thecanary_co                       11.96\n    theguardian_com                    15.87\n    thetimes_co_uk                     13.48\n    washingtonpost_com                 15.62\n    westmonster_com                     9.69\n    yournewswire_com                   10.21\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\nThat's more like it, but the lower numbers should be smaller.\n\n\n```python\nnp.log(data.fb_brand_page_likes.groupby(data.publisher_id).max() / 1000)\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    5.80\n    bbc_co_uk                          10.71\n    breitbart_com                       8.23\n    brexitcentral_com                   2.53\n    buzzfeed_com                        7.94\n    cnn_com                            10.28\n    dailymail_co_uk                     9.51\n    economist_com                       9.03\n    evolvepolitics_com                  4.74\n    foxnews_com                         9.68\n    ft_com                              8.22\n    huffingtonpost_com                  9.19\n    independent_co_uk                   8.97\n    indy100_com                         5.45\n    lemonde_fr                          8.28\n    libdemvoice_org                     2.15\n    mirror_co_uk                        7.98\n    nbcnews_com                         9.15\n    newstatesman_com                    5.04\n    npr_org                             8.74\n    nytimes_com                         9.62\n    order-order_com                     3.81\n    propublica_org                      5.92\n    reuters_com                         8.27\n    rt_com                              8.46\n    skwawkbox_org                       1.81\n    telegraph_co_uk                     8.39\n    thecanary_co                        5.05\n    theguardian_com                     8.96\n    thetimes_co_uk                      6.58\n    washingtonpost_com                  8.71\n    westmonster_com                     2.78\n    yournewswire_com                    3.31\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\nscaled_fb_brand_page_likes = (data.fb_brand_page_likes / 1000)\nfacebook_promotion_proposed_2 = np.ceil(\\\n    (15 * \\\n     (np.log(scaled_fb_brand_page_likes) / np.log(scaled_fb_brand_page_likes.max()))\\\n    )\\\n                                       ).fillna(0)\n```\n\n\n```python\nfacebook_promotion_proposed_2.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    9.00\n    bbc_co_uk                          15.00\n    breitbart_com                      12.00\n    brexitcentral_com                   4.00\n    buzzfeed_com                       12.00\n    cnn_com                            15.00\n    dailymail_co_uk                    14.00\n    economist_com                      13.00\n    evolvepolitics_com                  7.00\n    foxnews_com                        14.00\n    ft_com                             12.00\n    huffingtonpost_com                 13.00\n    independent_co_uk                  13.00\n    indy100_com                         8.00\n    lemonde_fr                         12.00\n    libdemvoice_org                     4.00\n    mirror_co_uk                       12.00\n    nbcnews_com                        13.00\n    newstatesman_com                    8.00\n    npr_org                            13.00\n    nytimes_com                        14.00\n    order-order_com                     6.00\n    propublica_org                      9.00\n    reuters_com                        12.00\n    rt_com                             12.00\n    skwawkbox_org                       3.00\n    telegraph_co_uk                    12.00\n    thecanary_co                        8.00\n    theguardian_com                    13.00\n    thetimes_co_uk                     10.00\n    washingtonpost_com                 13.00\n    westmonster_com                     4.00\n    yournewswire_com                    5.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\nLGTM. So the equation is\n\n\n$$ facebookPromotion_a = 15 \\left( \n\\frac {\\log(\\frac {brandPageLikes_a}{1000})} \n{\\log(\\frac {\\max(brandPageLikes)}{1000}))} \\right) $$\n\n\nNow, let's try applying standard feature scaling approch to this, rather than using a magic number of 1,000. That equation would be:\n\n\\begin{align}\nunscaledFacebookPromotion_a &= \n   \\log(brandPageLikes_a) \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{unscaledFacebookPromotion_a - \\min(unscaledFacebookPromotion)}{\\max(unscaledFacebookPromotion) - \\min(unscaledFacebookPromotion)}  \\\\\n\\\\\n\\text{The scaling can be simplified to:} \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{unscaledFacebookPromotion_a - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))}  \\\\\n\\\\\n\\text{Meaning the overall equation becomes:} \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{\\log(brandPageLikes_a) - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))} \n   \\end{align}\n\n\n\n```python\nfacebook_promotion_proposed_3 = np.ceil(\n    (14 * \n     ( \n         (np.log(data.fb_brand_page_likes) - np.log(data.fb_brand_page_likes.min()) ) /\n         (np.log(data.fb_brand_page_likes.max()) - np.log(data.fb_brand_page_likes.min()))\n     )\n    ) + 1\n                                       )\n```\n\n\n```python\nfacebook_promotion_proposed_3.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    8.00\n    bbc_co_uk                          15.00\n    breitbart_com                      12.00\n    brexitcentral_com                   3.00\n    buzzfeed_com                       11.00\n    cnn_com                            15.00\n    dailymail_co_uk                    14.00\n    economist_com                      13.00\n    evolvepolitics_com                  6.00\n    foxnews_com                        14.00\n    ft_com                             12.00\n    huffingtonpost_com                 13.00\n    independent_co_uk                  13.00\n    indy100_com                         7.00\n    lemonde_fr                         12.00\n    libdemvoice_org                     2.00\n    mirror_co_uk                       11.00\n    nbcnews_com                        13.00\n    newstatesman_com                    7.00\n    npr_org                            12.00\n    nytimes_com                        14.00\n    order-order_com                     5.00\n    propublica_org                      8.00\n    reuters_com                        12.00\n    rt_com                             12.00\n    skwawkbox_org                       2.00\n    telegraph_co_uk                    12.00\n    thecanary_co                        7.00\n    theguardian_com                    13.00\n    thetimes_co_uk                      9.00\n    washingtonpost_com                 12.00\n    westmonster_com                     3.00\n    yournewswire_com                    4.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\ndata[\"facebook_promotion_score\"] = facebook_promotion_proposed_3.fillna(0.0)\n```\n\n# Review\n\n\n```python\ndata[\"promotion_score\"] = (data.lead_score + data.front_score + data.facebook_promotion_score)\ndata[\"attention_index\"] = (data.promotion_score + data.response_score)\n```\n\n\n```python\ndata.promotion_score.plot.hist(bins=np.arange(50), figsize=(15,6))\n```\n\n\n```python\ndata.attention_index.plot.hist(bins=np.arange(100), figsize=(15,6))\n```\n\n\n```python\ndata.attention_index.value_counts().sort_index()\n```\n\n\n\n\n    0.00     26228\n    1.00     18738\n    2.00     11875\n    3.00      8299\n    4.00      6777\n    5.00      5670\n    6.00      4580\n    7.00      4152\n    8.00      3592\n    9.00      3395\n    10.00     3052\n    11.00     2790\n    12.00     2610\n    13.00     2552\n    14.00     2289\n    15.00     2188\n    16.00     2124\n    17.00     1923\n    18.00     1939\n    19.00     1810\n    20.00     1731\n    21.00     1709\n    22.00     1636\n    23.00     1592\n    24.00     1610\n    25.00     1574\n    26.00     1515\n    27.00     1385\n    28.00     1367\n    29.00     1322\n             ...  \n    65.00      127\n    66.00      111\n    67.00       84\n    68.00       93\n    69.00       88\n    70.00       54\n    71.00       61\n    72.00       41\n    73.00       54\n    74.00       43\n    75.00       33\n    76.00       41\n    77.00       40\n    78.00       30\n    79.00       36\n    80.00       24\n    81.00       20\n    82.00       23\n    83.00       20\n    84.00       22\n    85.00       17\n    86.00       10\n    87.00       10\n    88.00       16\n    89.00        9\n    90.00        7\n    91.00        6\n    92.00        6\n    93.00        5\n    94.00        2\n    Name: attention_index, Length: 95, dtype: int64\n\n\n\n\n```python\n# and lets see the articles with the biggest attention index\ndata.sort_values(\"attention_index\", ascending=False)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>73ea9633c21733c5931c0c9c18b066285cb1bf39</th>\n      <td>http://www.cnn.com/2017/11/27/europe/prince-ha...</td>\n      <td>Prince Harry and Meghan Markle are engaged</td>\n      <td>2017-11-27 10:10:13.896</td>\n      <td>2017-11-27 10:06:10.000</td>\n      <td>120080</td>\n      <td>374.58</td>\n      <td>2017-11-27T10:21:10.556Z</td>\n      <td>17091</td>\n      <td>95550</td>\n      <td>7439</td>\n      <td>...</td>\n      <td>29210147.00</td>\n      <td>2017-11-27T10:10:57.000Z</td>\n      <td>105</td>\n      <td>30.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>0844561b92420804aad85219a5552042ce4d265c</th>\n      <td>http://money.cnn.com/2017/11/29/media/matt-lau...</td>\n      <td>Matt Lauer fired from NBC News</td>\n      <td>2017-11-29 12:13:21.006</td>\n      <td>2017-11-29 12:03:48.000</td>\n      <td>280472</td>\n      <td>1059.42</td>\n      <td>2017-11-29T12:25:04.420Z</td>\n      <td>121197</td>\n      <td>131299</td>\n      <td>27976</td>\n      <td>...</td>\n      <td>29221482.00</td>\n      <td>2017-11-29T12:10:25.000Z</td>\n      <td>105</td>\n      <td>nan</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>d89e12f04f8c41a417503f4ddd8738eb9e3a4fbe</th>\n      <td>http://www.cnn.com/2017/11/03/politics/bowe-be...</td>\n      <td>Bowe Bergdahl case: Judge reaches decision on ...</td>\n      <td>2017-11-03 15:13:06.928</td>\n      <td>2017-11-03 15:09:11.000</td>\n      <td>116359</td>\n      <td>254.01</td>\n      <td>2017-11-03T17:16:12.979Z</td>\n      <td>57923</td>\n      <td>48747</td>\n      <td>9689</td>\n      <td>...</td>\n      <td>29117755.00</td>\n      <td>2017-11-03T15:50:13.000Z</td>\n      <td>105</td>\n      <td>710.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>e517b876ffba73e2f5ffd10ba0f8f429906d29f5</th>\n      <td>https://www.buzzfeed.com/briannasacks/trump-is...</td>\n      <td>Trump Is Allowing Hunters To Import Elephant T...</td>\n      <td>2017-11-16 03:58:19.582</td>\n      <td>2017-11-16 03:38:35.000</td>\n      <td>123141</td>\n      <td>109.65</td>\n      <td>2017-11-16T14:11:09.991Z</td>\n      <td>30123</td>\n      <td>80287</td>\n      <td>12731</td>\n      <td>...</td>\n      <td>2764495.00</td>\n      <td>2017-11-19T16:02:00.000Z</td>\n      <td>147</td>\n      <td>741.00</td>\n      <td>50.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>fc4d4c9056d6150a5d077277d6cbbad6d94cd9eb</th>\n      <td>http://www.bbc.co.uk/news/world-africa-42071488</td>\n      <td>Zimbabwe's President Mugabe 'resigns'</td>\n      <td>2017-11-21 15:55:05.471</td>\n      <td>2017-11-21 15:51:28.000</td>\n      <td>83318</td>\n      <td>945.12</td>\n      <td>2017-11-21T16:06:25.141Z</td>\n      <td>11043</td>\n      <td>61549</td>\n      <td>10726</td>\n      <td>...</td>\n      <td>44879347.00</td>\n      <td>2017-11-21T15:54:48.000Z</td>\n      <td>96</td>\n      <td>59.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>eb5cf786e76b63b71b65ee2d768bc6b852cd09f5</th>\n      <td>http://www.cnn.com/2017/11/26/politics/tom-ste...</td>\n      <td>Tom Steyer defends $20M ad campaign calling to...</td>\n      <td>2017-11-26 20:52:30.134</td>\n      <td>2017-11-26 20:51:09.000</td>\n      <td>72391</td>\n      <td>345.35</td>\n      <td>2017-11-26T23:19:13.135Z</td>\n      <td>12739</td>\n      <td>56089</td>\n      <td>3563</td>\n      <td>...</td>\n      <td>29208375.00</td>\n      <td>2017-11-26T23:00:07.000Z</td>\n      <td>105</td>\n      <td>583.00</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>f4068619cf024977dd22e0f55df457e8a5e1e81a</th>\n      <td>http://www.cnn.com/2017/11/11/politics/preside...</td>\n      <td>Trump says he believes Putin's election meddli...</td>\n      <td>2017-11-11 11:13:12.620</td>\n      <td>2017-11-11 11:07:35.000</td>\n      <td>119370</td>\n      <td>217.41</td>\n      <td>2017-11-11T16:54:07.932Z</td>\n      <td>42730</td>\n      <td>63073</td>\n      <td>13567</td>\n      <td>...</td>\n      <td>29149649.00</td>\n      <td>2017-11-11T11:55:15.000Z</td>\n      <td>105</td>\n      <td>269.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>ae93aeb0b54e4226e91f871104402b5d593c017a</th>\n      <td>http://www.cnn.com/2017/11/04/politics/the-las...</td>\n      <td>George H.W. Bush labels Trump a 'blowhard' in ...</td>\n      <td>2017-11-04 04:04:21.998</td>\n      <td>2017-11-04 04:01:21.000</td>\n      <td>64884</td>\n      <td>201.01</td>\n      <td>2017-11-04T13:15:03.379Z</td>\n      <td>10290</td>\n      <td>47483</td>\n      <td>7111</td>\n      <td>...</td>\n      <td>29121177.00</td>\n      <td>2017-11-04T12:46:27.000Z</td>\n      <td>105</td>\n      <td>1268.00</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>bac634126d3948d4a630e9ed45fc43daf5e47512</th>\n      <td>http://www.bbc.co.uk/news/world-middle-east-42...</td>\n      <td>Bomb attack on mosque in Egypt's Sinai</td>\n      <td>2017-11-24 11:40:13.945</td>\n      <td>2017-11-24 11:36:06.000</td>\n      <td>73270</td>\n      <td>111.27</td>\n      <td>2017-11-24T15:22:11.248Z</td>\n      <td>9639</td>\n      <td>53547</td>\n      <td>10084</td>\n      <td>...</td>\n      <td>44919422.00</td>\n      <td>2017-11-24T15:12:31.000Z</td>\n      <td>96</td>\n      <td>64.00</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>7f547d36c1b7a45ce5561d1f1bb893ad6b1a4b16</th>\n      <td>http://www.bbc.co.uk/news/uk-41876942</td>\n      <td>Tax haven secrets of ultra-rich exposed</td>\n      <td>2017-11-05 18:03:06.595</td>\n      <td>2017-11-05 18:00:10.000</td>\n      <td>47663</td>\n      <td>1509.05</td>\n      <td>2017-11-05T20:07:12.413Z</td>\n      <td>14615</td>\n      <td>22927</td>\n      <td>10121</td>\n      <td>...</td>\n      <td>44674035.00</td>\n      <td>2017-11-05T18:02:24.000Z</td>\n      <td>96</td>\n      <td>1092.00</td>\n      <td>46.00</td>\n      <td>20.00</td>\n      <td>11.00</td>\n      <td>15.00</td>\n      <td>46.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>1d314f93ee2e693abc8db7f0c5c0b5bc88e1b189</th>\n      <td>http://www.bbc.co.uk/news/uk-42137179</td>\n      <td>Prince Harry to marry girlfriend Meghan Markle</td>\n      <td>2017-11-27 10:07:08.120</td>\n      <td>2017-11-27 10:04:47.000</td>\n      <td>185430</td>\n      <td>796.22</td>\n      <td>2017-11-27T10:18:09.644Z</td>\n      <td>32779</td>\n      <td>138647</td>\n      <td>14004</td>\n      <td>...</td>\n      <td>44955978.00</td>\n      <td>2017-11-27T10:10:16.000Z</td>\n      <td>96</td>\n      <td>64.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>3e124661440aaee9ff2f5abd6580c96de9c409cd</th>\n      <td>http://www.cnn.com/2017/11/16/politics/al-fran...</td>\n      <td>Woman alleges Franken groped, kissed her witho...</td>\n      <td>2017-11-16 16:25:14.114</td>\n      <td>2017-11-16 16:21:00.000</td>\n      <td>64085</td>\n      <td>419.10</td>\n      <td>2017-11-16T18:31:07.975Z</td>\n      <td>39607</td>\n      <td>18265</td>\n      <td>6213</td>\n      <td>...</td>\n      <td>29165786.00</td>\n      <td>2017-11-16T16:34:06.000Z</td>\n      <td>105</td>\n      <td>394.00</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>25571e148ab673e2bee73a203ccbc469ad2c2fcb</th>\n      <td>http://www.cnn.com/2017/11/29/politics/preside...</td>\n      <td>Trump's behavior raises questions of competency</td>\n      <td>2017-11-29 18:43:33.556</td>\n      <td>2017-11-29 18:38:30.000</td>\n      <td>73526</td>\n      <td>189.80</td>\n      <td>2017-11-29T21:42:10.905Z</td>\n      <td>30333</td>\n      <td>33827</td>\n      <td>9366</td>\n      <td>...</td>\n      <td>29240975.00</td>\n      <td>2017-12-03T13:30:19.000Z</td>\n      <td>105</td>\n      <td>1098.00</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>4e4483f28e1fb45e7cd2efd68013d8713e093689</th>\n      <td>http://www.cnn.com/2017/11/24/africa/egypt-sin...</td>\n      <td>Egypt attack: 'Dozens killed' at North Sinai m...</td>\n      <td>2017-11-24 13:10:12.702</td>\n      <td>2017-11-24 13:05:02.000</td>\n      <td>76701</td>\n      <td>146.55</td>\n      <td>2017-11-24T14:16:10.600Z</td>\n      <td>11338</td>\n      <td>52336</td>\n      <td>13027</td>\n      <td>...</td>\n      <td>29200399.00</td>\n      <td>2017-11-24T13:30:59.000Z</td>\n      <td>105</td>\n      <td>77.00</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>eddf6f1f068d000d109a9f590f254b217f9231ec</th>\n      <td>http://www.cnn.com/2017/11/12/middleeast/iraq-...</td>\n      <td>Powerful earthquake strikes near Iraqi city of...</td>\n      <td>2017-11-12 19:07:11.950</td>\n      <td>2017-11-12 19:05:17.000</td>\n      <td>54567</td>\n      <td>160.80</td>\n      <td>2017-11-12T23:42:07.318Z</td>\n      <td>6011</td>\n      <td>39256</td>\n      <td>9300</td>\n      <td>...</td>\n      <td>29153473.00</td>\n      <td>2017-11-12T23:30:23.000Z</td>\n      <td>105</td>\n      <td>44.00</td>\n      <td>47.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>8936b3dfe6df7390975e0b3613010b294dea585f</th>\n      <td>http://www.cnn.com/2017/11/05/us/texas-church-...</td>\n      <td>FBI responding to the scene of a shooting outs...</td>\n      <td>2017-11-05 19:28:26.968</td>\n      <td>2017-11-05 19:25:20.000</td>\n      <td>472479</td>\n      <td>1474.19</td>\n      <td>2017-11-05T21:33:10.123Z</td>\n      <td>103331</td>\n      <td>319098</td>\n      <td>50050</td>\n      <td>...</td>\n      <td>29130688.00</td>\n      <td>2017-11-05T19:33:59.000Z</td>\n      <td>105</td>\n      <td>93.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>9bcec31a0af3473e657194f655644e361f4c6112</th>\n      <td>http://www.cnn.com/2017/11/21/entertainment/da...</td>\n      <td>David Cassidy, '70s teen heartthrob, dies at a...</td>\n      <td>2017-11-22 02:10:11.664</td>\n      <td>2017-11-22 02:07:07.000</td>\n      <td>308761</td>\n      <td>1149.44</td>\n      <td>2017-11-22T02:43:07.665Z</td>\n      <td>55066</td>\n      <td>213732</td>\n      <td>39963</td>\n      <td>...</td>\n      <td>29180211.00</td>\n      <td>2017-11-22T02:29:19.000Z</td>\n      <td>105</td>\n      <td>524.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>56d4fd37d920ed660cbad59ea6783a1ac316d3f1</th>\n      <td>http://www.cnn.com/2017/11/07/politics/2017-us...</td>\n      <td>US election tests nation's mood a year after T...</td>\n      <td>2017-11-07 17:28:21.597</td>\n      <td>2017-11-07 17:22:09.000</td>\n      <td>110855</td>\n      <td>657.61</td>\n      <td>2017-11-08T02:48:10.555Z</td>\n      <td>11024</td>\n      <td>92195</td>\n      <td>7636</td>\n      <td>...</td>\n      <td>29140017.00</td>\n      <td>2017-11-08T02:16:05.000Z</td>\n      <td>105</td>\n      <td>730.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>c60580cced4a93dea0f1501fb8fc11b9568d8d09</th>\n      <td>http://www.cnn.com/2017/11/20/politics/al-fran...</td>\n      <td>Woman says Al Franken inappropriately touched ...</td>\n      <td>2017-11-20 14:04:08.927</td>\n      <td>2017-11-20 14:01:00.000</td>\n      <td>60999</td>\n      <td>151.83</td>\n      <td>2017-11-20T16:08:05.371Z</td>\n      <td>39924</td>\n      <td>15995</td>\n      <td>5080</td>\n      <td>...</td>\n      <td>29174292.00</td>\n      <td>2017-11-20T14:34:07.000Z</td>\n      <td>105</td>\n      <td>1237.00</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>ea8c249c77726779692648c4b61e6f17e2c20ef1</th>\n      <td>http://www.cnn.com/2017/11/21/politics/donald-...</td>\n      <td>Trump all but endorses Roy Moore</td>\n      <td>2017-11-21 20:43:22.621</td>\n      <td>2017-11-21 20:39:42.000</td>\n      <td>61716</td>\n      <td>1075.54</td>\n      <td>2017-11-21T22:07:09.250Z</td>\n      <td>28421</td>\n      <td>25460</td>\n      <td>7835</td>\n      <td>...</td>\n      <td>29179024.00</td>\n      <td>2017-11-21T23:00:28.000Z</td>\n      <td>105</td>\n      <td>113.00</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>fe697d4d58f41d6e1de381fbfd12e8df7afd83f8</th>\n      <td>https://www.buzzfeed.com/jimdalrympleii/oil-sp...</td>\n      <td>More Than 200,000 Gallons Of Oil Spill Along T...</td>\n      <td>2017-11-16 21:28:15.945</td>\n      <td>2017-11-16 21:27:17.000</td>\n      <td>54944</td>\n      <td>148.26</td>\n      <td>2017-11-16T22:11:10.231Z</td>\n      <td>9329</td>\n      <td>35136</td>\n      <td>10479</td>\n      <td>...</td>\n      <td>2763703.00</td>\n      <td>2017-11-18T20:04:00.000Z</td>\n      <td>147</td>\n      <td>115.00</td>\n      <td>47.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>7be688e97f64c952e8183855c713ded615bb9aa0</th>\n      <td>https://www.buzzfeed.com/josephbernstein/sourc...</td>\n      <td>Sources: McMaster Mocked Trump\u2019s Intelligence ...</td>\n      <td>2017-11-20 17:07:12.434</td>\n      <td>2017-11-15 19:51:02.000</td>\n      <td>39274</td>\n      <td>406.15</td>\n      <td>2017-11-20T20:14:06.158Z</td>\n      <td>6108</td>\n      <td>28213</td>\n      <td>4953</td>\n      <td>...</td>\n      <td>2765039.00</td>\n      <td>2017-11-20T17:09:20.000Z</td>\n      <td>147</td>\n      <td>867.00</td>\n      <td>45.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>918dd1da248df1e030da129727d26ff87d2c476d</th>\n      <td>http://www.bbc.co.uk/news/world-australia-4199...</td>\n      <td>Australians back gay marriage in non-binding vote</td>\n      <td>2017-11-14 23:07:07.371</td>\n      <td>2017-11-14 23:04:51.000</td>\n      <td>193635</td>\n      <td>2130.00</td>\n      <td>2017-11-15T08:05:11.694Z</td>\n      <td>15567</td>\n      <td>165814</td>\n      <td>12254</td>\n      <td>...</td>\n      <td>44796279.00</td>\n      <td>2017-11-14T23:06:11.000Z</td>\n      <td>96</td>\n      <td>64.00</td>\n      <td>50.00</td>\n      <td>13.00</td>\n      <td>12.00</td>\n      <td>15.00</td>\n      <td>40.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>3f232a19515eafff49d19aa97622c92ced9e94aa</th>\n      <td>http://www.bbc.co.uk/news/world-us-canada-4216...</td>\n      <td>Trump account retweets anti-Muslim videos</td>\n      <td>2017-11-29 11:58:11.714</td>\n      <td>2017-11-29 11:56:08.000</td>\n      <td>61587</td>\n      <td>836.41</td>\n      <td>2017-11-29T18:04:08.063Z</td>\n      <td>22107</td>\n      <td>30644</td>\n      <td>8836</td>\n      <td>...</td>\n      <td>44978694.00</td>\n      <td>2017-11-29T12:01:35.000Z</td>\n      <td>96</td>\n      <td>64.00</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>2443904aef281c6a4cdff93a466908084cfa403d</th>\n      <td>https://www.buzzfeed.com/katiejmbaker/more-tha...</td>\n      <td>More Than 180 Women Have Reported Sexual Assau...</td>\n      <td>2017-11-26 16:25:18.372</td>\n      <td>2017-11-22 22:15:18.000</td>\n      <td>45167</td>\n      <td>28.91</td>\n      <td>2017-11-26T22:37:06.578Z</td>\n      <td>15799</td>\n      <td>23122</td>\n      <td>6246</td>\n      <td>...</td>\n      <td>2775117.00</td>\n      <td>2017-11-26T16:41:11.000Z</td>\n      <td>147</td>\n      <td>4608.00</td>\n      <td>46.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>740f28a60dc9f4c080b5f2495e839a579134b05f</th>\n      <td>http://www.cnn.com/2017/11/06/us/texas-church-...</td>\n      <td>Texas church shooting: Of 26 dead, 8 came from...</td>\n      <td>2017-11-06 09:25:15.499</td>\n      <td>2017-11-06 09:18:43.000</td>\n      <td>48754</td>\n      <td>67.26</td>\n      <td>2017-11-06T14:55:11.872Z</td>\n      <td>14626</td>\n      <td>27026</td>\n      <td>7102</td>\n      <td>...</td>\n      <td>29134644.00</td>\n      <td>2017-11-06T10:00:05.000Z</td>\n      <td>105</td>\n      <td>1327.00</td>\n      <td>47.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>882f5d32bf5d563b1b4804a5b5054e7bf38fd49e</th>\n      <td>https://www.huffingtonpost.com/entry/charles-m...</td>\n      <td>Manson Family Leader Charles Manson Dead At 83</td>\n      <td>2017-11-20 05:58:17.677</td>\n      <td>2017-11-20 05:55:41.000</td>\n      <td>120366</td>\n      <td>468.15</td>\n      <td>2017-11-20T06:10:05.971Z</td>\n      <td>32275</td>\n      <td>67753</td>\n      <td>20338</td>\n      <td>...</td>\n      <td>9801729.00</td>\n      <td>2017-11-20T05:57:04.000Z</td>\n      <td>215</td>\n      <td>918.00</td>\n      <td>50.00</td>\n      <td>17.00</td>\n      <td>9.00</td>\n      <td>13.00</td>\n      <td>39.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>eab0bd7eddf6530830d0739c2b95df91c04311af</th>\n      <td>http://www.cnn.com/2017/11/20/politics/trump-t...</td>\n      <td>Trump says Raiders running back should be susp...</td>\n      <td>2017-11-20 12:49:19.171</td>\n      <td>2017-11-20 12:44:47.000</td>\n      <td>42682</td>\n      <td>202.44</td>\n      <td>2017-11-20T14:12:06.345Z</td>\n      <td>17683</td>\n      <td>21738</td>\n      <td>3261</td>\n      <td>...</td>\n      <td>29174331.00</td>\n      <td>2017-11-20T13:50:04.000Z</td>\n      <td>105</td>\n      <td>242.00</td>\n      <td>46.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>fb1e8caeac265f01e6f14acd89b5caa950fad9db</th>\n      <td>http://money.cnn.com/2017/11/02/technology/don...</td>\n      <td>Trump's Twitter handle disappeared. Everyone f...</td>\n      <td>2017-11-02 23:48:14.601</td>\n      <td>2017-11-02 23:25:28.000</td>\n      <td>45644</td>\n      <td>179.60</td>\n      <td>2017-11-03T19:05:07.586Z</td>\n      <td>7000</td>\n      <td>32402</td>\n      <td>6242</td>\n      <td>...</td>\n      <td>29115629.00</td>\n      <td>2017-11-02T23:45:09.000Z</td>\n      <td>105</td>\n      <td>nan</td>\n      <td>46.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>786ccbf412c44c9929f14d99f69b26c08b41c7c4</th>\n      <td>http://www.cnn.com/2017/11/14/us/california-te...</td>\n      <td>At least 3 people killed in Northern California</td>\n      <td>2017-11-14 19:25:25.795</td>\n      <td>2017-11-14 19:21:15.000</td>\n      <td>64970</td>\n      <td>764.73</td>\n      <td>2017-11-15T04:03:14.627Z</td>\n      <td>19633</td>\n      <td>35757</td>\n      <td>9580</td>\n      <td>...</td>\n      <td>29159769.00</td>\n      <td>2017-11-14T20:30:12.000Z</td>\n      <td>105</td>\n      <td>137.00</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>f4e1249cdcc101d0aa1d61fdcad594b5ffaedd7a</th>\n      <td>http://www.dailymail.co.uk/news/article-510517...</td>\n      <td>Police search for New York City synagogue vandals</td>\n      <td>2017-11-21 19:52:18.617</td>\n      <td>2017-11-21 19:49:15.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-11-21T22:04:09.231Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>263.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>1f0aec88f260aee14d77dc39b8e2db114d5e53f1</th>\n      <td>https://www.washingtonpost.com/national/review...</td>\n      <td>Review: Billy Bragg delivers the news on \u2018Brid...</td>\n      <td>2017-11-06 15:52:16.276</td>\n      <td>2017-11-06 15:48:17.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-06T19:06:11.406Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>303.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>5848ab7e4866902978ed29f58a718ebe38fe533b</th>\n      <td>https://www.washingtonpost.com/sports/dcunited...</td>\n      <td>Emenalo quits as Chelsea\u2019s technical director,...</td>\n      <td>2017-11-06 15:49:15.654</td>\n      <td>2017-11-06 15:39:14.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-11-06T17:01:11.481Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>105.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>56fc6dab69d6747825f30071b3d55405bd7bc76a</th>\n      <td>https://www.washingtonpost.com/business/footba...</td>\n      <td>Football helped NBC to another ratings touchdo...</td>\n      <td>2017-11-21 20:04:13.555</td>\n      <td>2017-11-21 19:50:11.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-21T22:17:11.052Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>129.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>5a93a40fee0828de942d2ed87e6498fb5539e771</th>\n      <td>https://www.washingtonpost.com/world/europe/ru...</td>\n      <td>Russian lawmaker detained in France in tax fra...</td>\n      <td>2017-11-21 20:01:12.291</td>\n      <td>2017-11-21 19:53:16.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-21T22:13:21.095Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>150.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>fd9f75db2dd6cf003a4d3710f78c96a183c900af</th>\n      <td>https://www.huffingtonpost.com/entry/inside-th...</td>\n      <td>Inside the Digital World Of Vanity Fair With P...</td>\n      <td>2017-11-21 20:01:16.478</td>\n      <td>2017-11-21 19:54:00.473</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-21T22:13:21.100Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>1217.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>3af22a8a9f33acd7d3563e43053bab8d724d5996</th>\n      <td>https://www.washingtonpost.com/national/caregi...</td>\n      <td>Caregiver accused of trying to suffocate 88-ye...</td>\n      <td>2017-11-21 19:58:09.299</td>\n      <td>2017-11-21 19:54:09.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-11-22T15:28:10.555Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>147.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>f0c3ae6a6bd50e9ad6b4cc46f1783efd157bd243</th>\n      <td>https://www.huffingtonpost.com/entry/what-they...</td>\n      <td>What they'll say on Brietbart after Trump is gone</td>\n      <td>2017-11-06 15:55:23.957</td>\n      <td>2017-11-06 15:37:56.366</td>\n      <td>1</td>\n      <td>0.00</td>\n      <td>2017-11-06T19:10:03.159Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>733.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>fc50cf94337627a443e18ff0a668562b265cce5b</th>\n      <td>https://www.washingtonpost.com/national/police...</td>\n      <td>Police arrest man who identified himself as de...</td>\n      <td>2017-11-06 15:46:11.188</td>\n      <td>2017-11-06 15:37:15.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-06T17:59:10.516Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>154.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>c32fd52c8d2e02aba70271c4492b975099262983</th>\n      <td>https://www.huffingtonpost.com/entry/new-york-...</td>\n      <td>New York City Spends $1 Billion with MWBE Firms</td>\n      <td>2017-11-21 19:46:15.255</td>\n      <td>2017-11-21 19:39:14.242</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-11-21T20:58:06.182Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>549.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>c9304216196c1409380a7c249333cb66955928d1</th>\n      <td>https://www.washingtonpost.com/national/qanda-...</td>\n      <td>Q&amp;A: Donations for victims of the Las Vegas ma...</td>\n      <td>2017-11-21 19:43:16.407</td>\n      <td>2017-11-21 19:38:35.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-21T22:58:04.726Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>816.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>4eb3c48a8a54ccdc973efb7c2782a9f07d7329ab</th>\n      <td>https://www.huffingtonpost.com/entry/real-time...</td>\n      <td>Real Time Data Adoption Still Slow in the Ente...</td>\n      <td>2017-11-06 16:04:12.393</td>\n      <td>2017-11-06 15:57:49.261</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-06T18:17:06.170Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>838.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>8541d646246355defc696897573ce52e5c2f1b87</th>\n      <td>http://www.bbc.co.uk/news/uk-scotland-edinburg...</td>\n      <td>Queensferry Crossing death may have been 'frea...</td>\n      <td>2017-11-21 19:34:12.361</td>\n      <td>2017-11-21 19:30:26.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-11-22T08:58:11.287Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>633.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>5c377078cea6e6bdba3be1bba123e19d0d15bd79</th>\n      <td>https://www.huffingtonpost.com/entry/how-to-av...</td>\n      <td>How to Avoid Downloading a Fake App</td>\n      <td>2017-11-21 19:31:19.133</td>\n      <td>2017-11-21 19:28:53.673</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-11-21T20:43:10.304Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>849.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>c6616c46ae04437d27a12cfbf64ebebb3d89be33</th>\n      <td>https://www.huffingtonpost.com/entry/a-gratitu...</td>\n      <td>A Gratitude Ritual</td>\n      <td>2017-11-21 19:31:18.735</td>\n      <td>2017-11-21 19:28:58.462</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-21T23:46:09.078Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>794.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>997b3e829e98b6ef68e0072e17477310b9095fae</th>\n      <td>https://www.washingtonpost.com/national/religi...</td>\n      <td>Vatican beefs up oversight of diplomats after ...</td>\n      <td>2017-11-21 19:34:14.437</td>\n      <td>2017-11-21 19:29:11.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-11-21T23:49:10.183Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>151.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>8061f2b3380e8915d26970a1124b761fe9c0add7</th>\n      <td>https://www.ft.com/content/fec7e1a8-c2df-11e7-...</td>\n      <td>Dialectical face-off: Christmas Eve at the Ust...</td>\n      <td>2017-11-06 15:52:25.344</td>\n      <td>2017-11-06 15:50:58.000</td>\n      <td>1</td>\n      <td>0.09</td>\n      <td>2017-11-06T16:04:03.421Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>1596</td>\n      <td>371.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>5b0911c3e20f654862c8519206cfcdb33c76290f</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Jenkins leads Jackrabbits past Iowa 80-72</td>\n      <td>2017-11-21 19:31:13.727</td>\n      <td>2017-11-21 19:29:25.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-21T23:46:09.059Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>337.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>2c4c90d724d8fc6817ebc18815d13fdc5cf4b908</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Is J.T. Barrett the best QB to ever play at Oh...</td>\n      <td>2017-11-21 19:31:13.939</td>\n      <td>2017-11-21 19:29:25.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-21T23:46:09.064Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>781.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>c75e906a52a20db93508391aefd3860f18d1eb5c</th>\n      <td>http://www.bbc.co.uk/news/av/world-africa-4207...</td>\n      <td>Zimbabwe reacts to Mugabe resignation</td>\n      <td>2017-11-21 19:34:13.130</td>\n      <td>2017-11-21 19:30:10.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-21T21:47:10.450Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>76df4362a0be5fbb7bfc02168d7f391aa194912d</th>\n      <td>https://www.washingtonpost.com/lifestyle/home/...</td>\n      <td>Craftivism: Melding of crafting, activism is h...</td>\n      <td>2017-11-21 19:40:15.940</td>\n      <td>2017-11-21 19:30:27.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-21T22:53:13.683Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>766.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>9405dd882af60d34ebdeabb88e1e5a3fd5eb6403</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Missouri\u2019s Porter Jr. out for season after bac...</td>\n      <td>2017-11-21 19:52:15.804</td>\n      <td>2017-11-21 19:38:21.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-22T00:06:05.554Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>146.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>7c66cddb70a24a69f9c687a5409bd9b41e413c27</th>\n      <td>http://www.telegraph.co.uk/music/what-to-liste...</td>\n      <td>Frank Turner interview: 'People who take pride...</td>\n      <td>2017-11-21 19:34:08.979</td>\n      <td>2017-11-21 19:32:18.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-21T21:47:10.436Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>370</td>\n      <td>120.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>a6c0dde1c0e8750d03e600bf6fc0b7dd0667536b</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Vols\u2019 heralded senior class having disappointi...</td>\n      <td>2017-11-21 19:40:16.255</td>\n      <td>2017-11-21 19:32:32.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-21T22:53:13.692Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>740.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>365c6f16c05b07ec35b5fc2afdf8a21ac9d9678a</th>\n      <td>https://www.washingtonpost.com/national/health...</td>\n      <td>Diary: Inmate got over-the-counter drugs befor...</td>\n      <td>2017-11-21 19:43:16.707</td>\n      <td>2017-11-21 19:34:36.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-21T22:58:04.728Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>141.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>f253306fa278a178f948b4c13682a248dbc5eef0</th>\n      <td>https://www.washingtonpost.com/business/liz-we...</td>\n      <td>Liz Weston: 4 Steps to Disaster-Proof Your Fin...</td>\n      <td>2017-11-06 15:58:18.131</td>\n      <td>2017-11-06 15:48:22.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-11-06T17:11:04.540Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>833.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>96fffc46028063fc811a83deeac400c0a3f53839</th>\n      <td>http://www.dailymail.co.uk/sport/rugbyunion/ar...</td>\n      <td>Wales star Justin Tipuric a major doubt to fac...</td>\n      <td>2017-11-06 15:52:22.247</td>\n      <td>2017-11-06 15:48:17.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-11-06T17:05:02.995Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>401.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>6132ea1ddd3b6547eb97e272a10df1adbba7bccc</th>\n      <td>http://www.washingtonpost.com/video/world/cele...</td>\n      <td>Celebration in Zimbabwe as Mugabe resigns</td>\n      <td>2017-11-21 20:13:15.874</td>\n      <td>2017-11-21 19:38:10.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-21T21:26:06.149Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>fe1be446d676c9d8ff35367b6302f4f670f3813b</th>\n      <td>https://www.huffingtonpost.com/entry/lock-down...</td>\n      <td>Lock-Down Theology</td>\n      <td>2017-11-21 19:46:15.287</td>\n      <td>2017-11-21 19:38:18.176</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-22T00:01:05.534Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>498.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>7dfb319c50b823a7a353edbb239d34cdaa5d8378</th>\n      <td>http://www.dailymail.co.uk/tvshowbiz/article-5...</td>\n      <td>Australia decides: Did Kyle Sandilands just fa...</td>\n      <td>2017-12-01 00:08:02.425</td>\n      <td>2017-11-30 23:59:57.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-01T01:20:14.296Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>566.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>155376 rows \u00d7 26 columns</p>\n</div>\n\n\n\n\n```python\ndata[\"score_diff\"] = data.promotion_score - data.response_score\n```\n\n\n```python\n# promoted but low response\ndata.sort_values(\"score_diff\", ascending=False).head(25)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n      <th>score_diff</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>8fecd816fc621ac4816c2a7aae0d71d3b97e2489</th>\n      <td>https://www.buzzfeed.com/keelyflaherty/meet-th...</td>\n      <td>Meet the Breakout Star of \u201cLady Bird\u201d</td>\n      <td>2017-11-22 17:49:17.714</td>\n      <td>2017-11-20 18:36:28.000</td>\n      <td>1</td>\n      <td>0.09</td>\n      <td>2017-11-22T18:01:13.856Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>2017-11-24T05:32:00.000Z</td>\n      <td>147</td>\n      <td>1258.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>45.00</td>\n      <td>45.00</td>\n    </tr>\n    <tr>\n      <th>c4c68e90d29b9da58609f78ce13692d2bae1ab88</th>\n      <td>https://www.buzzfeed.com/borzoudaragahi/afghan...</td>\n      <td>Afghanistan\u2019s Hipsters Have Found Themselves A...</td>\n      <td>2017-11-18 14:04:23.015</td>\n      <td>2017-11-17 13:47:19.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-18T14:16:04.593Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2017-11-26T19:05:00.000Z</td>\n      <td>147</td>\n      <td>996.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>44.00</td>\n      <td>44.00</td>\n    </tr>\n    <tr>\n      <th>fcf67d8979ac5c70155e54a80b87b875f6768244</th>\n      <td>https://www.buzzfeed.com/danvergano/beam-me-up...</td>\n      <td>A Russian Billionaire Just Founded The First \u201c...</td>\n      <td>2017-11-25 14:04:25.111</td>\n      <td>2017-11-22 16:45:35.000</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>2017-11-25T14:15:15.289Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>2017-11-26T00:33:01.000Z</td>\n      <td>147</td>\n      <td>820.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>44.00</td>\n      <td>44.00</td>\n    </tr>\n    <tr>\n      <th>b38c9b0fc469585120c9f6b904463e406916a695</th>\n      <td>https://www.buzzfeed.com/adolfoflores/these-ce...</td>\n      <td>These Central American Children Wonder Why Tru...</td>\n      <td>2017-11-16 16:55:17.963</td>\n      <td>2017-11-14 21:02:32.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-16T17:06:10.897Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2017-11-18T04:45:00.000Z</td>\n      <td>147</td>\n      <td>2728.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>44.00</td>\n      <td>44.00</td>\n    </tr>\n    <tr>\n      <th>b3466fdbf642535131f7ef5beaaf63a868a607f6</th>\n      <td>https://www.buzzfeed.com/mollyhensleyclancy/wh...</td>\n      <td>Why Betsy DeVos May Be The Beauty School Indus...</td>\n      <td>2017-12-01 14:01:26.916</td>\n      <td>2017-11-29 19:52:29.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-01T14:12:11.651Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2017-12-02T00:44:01.000Z</td>\n      <td>147</td>\n      <td>5706.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>43.00</td>\n      <td>43.00</td>\n    </tr>\n    <tr>\n      <th>7aaf046bf5bbc5ef14e91b7be017c6b1989439c3</th>\n      <td>https://www.buzzfeed.com/sylviaobell/nola-darling</td>\n      <td>Here\u2019s Why You\u2019ll Love And Hate Nola Darling I...</td>\n      <td>2017-11-24 16:19:21.409</td>\n      <td>2017-11-22 22:57:31.000</td>\n      <td>3</td>\n      <td>0.10</td>\n      <td>2017-11-24T16:30:18.887Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>...</td>\n      <td>2017-11-28T05:10:00.000Z</td>\n      <td>147</td>\n      <td>2489.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>45.00</td>\n      <td>43.00</td>\n    </tr>\n    <tr>\n      <th>ffd6202df243fe5f684c605e023e977a07fafc50</th>\n      <td>https://www.buzzfeed.com/doree/meet-the-people...</td>\n      <td>Meet the People Who Listen to Podcasts at Supe...</td>\n      <td>2017-11-12 17:25:14.647</td>\n      <td>2017-11-09 15:06:16.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-12T17:36:07.410Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2017-11-13T07:04:00.000Z</td>\n      <td>147</td>\n      <td>1958.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>42.00</td>\n      <td>42.00</td>\n    </tr>\n    <tr>\n      <th>1e74e5aa86a20450f01357ff3222b67c6c248e58</th>\n      <td>https://www.buzzfeed.com/tomphillips/we-found-...</td>\n      <td>We Found 45 Suspected Bot Accounts Sharing Pro...</td>\n      <td>2017-11-24 09:46:18.952</td>\n      <td>2017-11-22 11:18:59.000</td>\n      <td>10</td>\n      <td>0.92</td>\n      <td>2017-11-24T09:58:03.524Z</td>\n      <td>0</td>\n      <td>5</td>\n      <td>5</td>\n      <td>...</td>\n      <td>2017-11-24T09:48:09.000Z</td>\n      <td>147</td>\n      <td>1781.00</td>\n      <td>2.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>46.00</td>\n      <td>42.00</td>\n    </tr>\n    <tr>\n      <th>c4b00967f43439a68074164f3e522875295d49e8</th>\n      <td>https://www.buzzfeed.com/charliewarzel/youtube...</td>\n      <td>YouTube Is Disabling Predatory Comments \u2014 But ...</td>\n      <td>2017-12-01 01:58:17.657</td>\n      <td>2017-11-29 22:41:29.000</td>\n      <td>2</td>\n      <td>0.20</td>\n      <td>2017-12-01T02:09:08.636Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>...</td>\n      <td>2017-12-01T03:24:00.000Z</td>\n      <td>147</td>\n      <td>686.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>43.00</td>\n      <td>41.00</td>\n    </tr>\n    <tr>\n      <th>3490bec24e123c369936928039cb08188e505c1b</th>\n      <td>https://www.buzzfeed.com/danvergano/chronic-pa...</td>\n      <td>He Took Opioids To Manage His Chronic Pain. Wh...</td>\n      <td>2017-11-30 16:54:26.538</td>\n      <td>2017-11-27 22:52:18.000</td>\n      <td>21</td>\n      <td>0.09</td>\n      <td>2017-11-30T17:06:09.056Z</td>\n      <td>2</td>\n      <td>1</td>\n      <td>18</td>\n      <td>...</td>\n      <td>2017-12-03T14:44:00.000Z</td>\n      <td>147</td>\n      <td>2844.00</td>\n      <td>4.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>48.00</td>\n      <td>40.00</td>\n    </tr>\n    <tr>\n      <th>29347b55be2bdb740e4cc77c14811a90fef18bcf</th>\n      <td>https://www.huffingtonpost.com/entry/trump-sex...</td>\n      <td>In Post-Weinstein Era, Trump Sexual Assault Ac...</td>\n      <td>2017-11-17 15:07:20.628</td>\n      <td>2017-11-17 14:56:56.877</td>\n      <td>0</td>\n      <td>1156.88</td>\n      <td>2017-11-24T16:46:06.417Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2017-11-17T17:00:24.000Z</td>\n      <td>215</td>\n      <td>412.00</td>\n      <td>0.00</td>\n      <td>17.00</td>\n      <td>9.00</td>\n      <td>13.00</td>\n      <td>39.00</td>\n      <td>39.00</td>\n      <td>39.00</td>\n    </tr>\n    <tr>\n      <th>60c4cb79498808a6c041b44af17c5a120edcf1d9</th>\n      <td>https://www.buzzfeed.com/nicolenguyen/amazon-s...</td>\n      <td>How To Avoid Buying Crap On Amazon</td>\n      <td>2017-11-21 16:37:18.191</td>\n      <td>2017-11-20 17:04:57.000</td>\n      <td>33</td>\n      <td>0.48</td>\n      <td>2017-11-21T17:49:13.029Z</td>\n      <td>2</td>\n      <td>7</td>\n      <td>24</td>\n      <td>...</td>\n      <td>2017-11-21T18:42:41.000Z</td>\n      <td>147</td>\n      <td>1546.00</td>\n      <td>6.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>50.00</td>\n      <td>38.00</td>\n    </tr>\n    <tr>\n      <th>0fd43fe79e1ff67ed2b12bcfc5fdd7d75c82d28b</th>\n      <td>https://www.buzzfeed.com/nidhisubbaraman/insec...</td>\n      <td>We\u2019re Headed Toward A Thanksgiving Brimming Wi...</td>\n      <td>2017-11-23 14:09:20.028</td>\n      <td>2017-11-22 13:43:54.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-23T14:21:08.008Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2017-11-24T01:32:00.000Z</td>\n      <td>147</td>\n      <td>813.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>7.00</td>\n      <td>11.00</td>\n      <td>37.00</td>\n      <td>37.00</td>\n      <td>37.00</td>\n    </tr>\n    <tr>\n      <th>281a6307f00daeb13f754eaef9d0487156ed6a1a</th>\n      <td>https://www.buzzfeed.com/allensalkin/have-your...</td>\n      <td>Have Yourself A Very Lit Thanksgiving</td>\n      <td>2017-11-22 18:37:16.501</td>\n      <td>2017-11-21 22:19:56.000</td>\n      <td>69</td>\n      <td>0.62</td>\n      <td>2017-11-22T19:50:11.243Z</td>\n      <td>6</td>\n      <td>55</td>\n      <td>8</td>\n      <td>...</td>\n      <td>2017-11-22T19:22:12.000Z</td>\n      <td>147</td>\n      <td>1856.00</td>\n      <td>8.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>53.00</td>\n      <td>37.00</td>\n    </tr>\n    <tr>\n      <th>7f69c2b2f31a885208536abb26a93d6798ef2e70</th>\n      <td>https://www.theguardian.com/world/2017/nov/15/...</td>\n      <td>Mugabe family in detention after military take...</td>\n      <td>2017-11-15 10:28:08.000</td>\n      <td>2017-11-15 10:26:33.000</td>\n      <td>0</td>\n      <td>32.43</td>\n      <td>2017-11-15T12:11:12.027Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2017-11-15T11:00:00.000Z</td>\n      <td>142</td>\n      <td>1418.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>4.00</td>\n      <td>13.00</td>\n      <td>36.00</td>\n      <td>36.00</td>\n      <td>36.00</td>\n    </tr>\n    <tr>\n      <th>27da2db0438e2a96fd75fbb198e72c9642dad8f5</th>\n      <td>https://www.buzzfeed.com/lissandravilla/former...</td>\n      <td>Former Congresswoman Who Oversaw Complaints Ag...</td>\n      <td>2017-11-28 20:58:15.872</td>\n      <td>2017-11-28 20:54:08.000</td>\n      <td>60</td>\n      <td>0.70</td>\n      <td>2017-11-28T21:09:09.916Z</td>\n      <td>5</td>\n      <td>12</td>\n      <td>43</td>\n      <td>...</td>\n      <td>2017-11-28T21:02:12.000Z</td>\n      <td>147</td>\n      <td>782.00</td>\n      <td>8.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>51.00</td>\n      <td>35.00</td>\n    </tr>\n    <tr>\n      <th>6901f2ad5c91f1eed99b0c2da1a7e2a50070f138</th>\n      <td>https://www.buzzfeed.com/laurendecicca/these-d...</td>\n      <td>These Deported Mothers Are Being Forced To Wat...</td>\n      <td>2017-11-24 14:04:21.741</td>\n      <td>2017-11-22 17:39:23.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-11-24T14:16:11.011Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>602.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>0.00</td>\n      <td>33.00</td>\n      <td>33.00</td>\n      <td>33.00</td>\n    </tr>\n    <tr>\n      <th>a0863d12a71fad8de6714b609a611d44c6ef6925</th>\n      <td>https://www.buzzfeed.com/borzoudaragahi/papado...</td>\n      <td>Papadopoulos And Flynn Client Both Tied To Isr...</td>\n      <td>2017-11-03 18:43:19.766</td>\n      <td>2017-11-03 16:31:10.000</td>\n      <td>110</td>\n      <td>0.43</td>\n      <td>2017-11-03T19:56:03.804Z</td>\n      <td>9</td>\n      <td>57</td>\n      <td>44</td>\n      <td>...</td>\n      <td>2017-11-03T19:14:00.000Z</td>\n      <td>147</td>\n      <td>636.00</td>\n      <td>11.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>55.00</td>\n      <td>33.00</td>\n    </tr>\n    <tr>\n      <th>f21fc06eb19142e842343339aaff297895aeb3ad</th>\n      <td>https://www.buzzfeed.com/sandirankaduwa/itsamo...</td>\n      <td>Meghan Markle Is The Future Of A Monarchy With...</td>\n      <td>2017-11-30 18:54:12.449</td>\n      <td>2017-11-29 22:41:16.000</td>\n      <td>128</td>\n      <td>0.62</td>\n      <td>2017-11-30T23:09:10.406Z</td>\n      <td>19</td>\n      <td>55</td>\n      <td>54</td>\n      <td>...</td>\n      <td>2017-12-01T01:24:00.000Z</td>\n      <td>147</td>\n      <td>2561.00</td>\n      <td>11.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>55.00</td>\n      <td>33.00</td>\n    </tr>\n    <tr>\n      <th>5291b060730148ba1031d21f8802481a198b97c2</th>\n      <td>https://www.buzzfeed.com/nidhiprakash/pelosi-w...</td>\n      <td>Pelosi Won't Say If She'll Ask Conyers To Step...</td>\n      <td>2017-11-26 15:46:19.929</td>\n      <td>2017-11-26 15:35:42.000</td>\n      <td>109</td>\n      <td>0.64</td>\n      <td>2017-11-26T19:01:06.024Z</td>\n      <td>11</td>\n      <td>61</td>\n      <td>37</td>\n      <td>...</td>\n      <td>2017-11-26T18:10:37.000Z</td>\n      <td>147</td>\n      <td>404.00</td>\n      <td>11.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>55.00</td>\n      <td>33.00</td>\n    </tr>\n    <tr>\n      <th>795037b8fd7078d17f6daa14e7aa401914a3fc70</th>\n      <td>https://www.buzzfeed.com/tomiobaro/greta-gerwi...</td>\n      <td>Complicated Teen Girls Are Finally Front And C...</td>\n      <td>2017-11-11 17:49:12.479</td>\n      <td>2017-11-11 00:33:05.000</td>\n      <td>66</td>\n      <td>0.40</td>\n      <td>2017-11-11T18:00:10.036Z</td>\n      <td>11</td>\n      <td>43</td>\n      <td>12</td>\n      <td>...</td>\n      <td>2017-11-12T22:04:00.000Z</td>\n      <td>147</td>\n      <td>1964.00</td>\n      <td>8.00</td>\n      <td>19.00</td>\n      <td>11.00</td>\n      <td>11.00</td>\n      <td>41.00</td>\n      <td>49.00</td>\n      <td>33.00</td>\n    </tr>\n    <tr>\n      <th>009db07e4f0df962b373de327ba80d4e70563ca0</th>\n      <td>https://www.buzzfeed.com/alexkantrowitz/how-to...</td>\n      <td>How To Tell If The Thanksgiving Content In You...</td>\n      <td>2017-11-23 17:31:19.975</td>\n      <td>2017-11-22 19:09:25.000</td>\n      <td>67</td>\n      <td>0.70</td>\n      <td>2017-11-23T19:45:12.565Z</td>\n      <td>1</td>\n      <td>43</td>\n      <td>23</td>\n      <td>...</td>\n      <td>2017-11-23T18:30:01.000Z</td>\n      <td>147</td>\n      <td>832.00</td>\n      <td>8.00</td>\n      <td>19.00</td>\n      <td>10.00</td>\n      <td>11.00</td>\n      <td>40.00</td>\n      <td>48.00</td>\n      <td>32.00</td>\n    </tr>\n    <tr>\n      <th>d2abaf54b688b990a34f79e83b6773bd7ef15bcb</th>\n      <td>http://www.dailymail.co.uk/news/article-511482...</td>\n      <td>Hundreds evacuated from Oxford Circus</td>\n      <td>2017-11-24 16:58:25.583</td>\n      <td>2017-11-24 16:56:02.000</td>\n      <td>2</td>\n      <td>209.58</td>\n      <td>2017-11-24T17:42:09.102Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>...</td>\n      <td>2017-11-24T16:57:51.000Z</td>\n      <td>158</td>\n      <td>16.00</td>\n      <td>1.00</td>\n      <td>18.00</td>\n      <td>1.00</td>\n      <td>14.00</td>\n      <td>33.00</td>\n      <td>34.00</td>\n      <td>32.00</td>\n    </tr>\n    <tr>\n      <th>948a86924f6b6cdc8e649b980130dcfbe3320f81</th>\n      <td>https://www.buzzfeed.com/tamerragriffin/zimbab...</td>\n      <td>Zimbabwe\u2019s Ruling Party Have Voted To Sack Rob...</td>\n      <td>2017-11-19 12:31:23.195</td>\n      <td>2017-11-19 12:25:11.000</td>\n      <td>188</td>\n      <td>0.67</td>\n      <td>2017-11-19T15:44:16.396Z</td>\n      <td>7</td>\n      <td>124</td>\n      <td>57</td>\n      <td>...</td>\n      <td>2017-11-19T14:52:00.000Z</td>\n      <td>147</td>\n      <td>116.00</td>\n      <td>13.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>57.00</td>\n      <td>31.00</td>\n    </tr>\n    <tr>\n      <th>4549ccb32d5e26888b5503af566de4bc1ae610da</th>\n      <td>https://www.npr.org/2017/11/26/566006195/6-pos...</td>\n      <td>6 Possible Hurdles For The GOP Tax Plan</td>\n      <td>2017-11-26 11:31:23.184</td>\n      <td>2017-11-26 11:01:00.000</td>\n      <td>0</td>\n      <td>1130.43</td>\n      <td>2017-11-27T07:22:09.101Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2017-11-26T13:55:00.000Z</td>\n      <td>594</td>\n      <td>853.00</td>\n      <td>0.00</td>\n      <td>15.00</td>\n      <td>3.00</td>\n      <td>12.00</td>\n      <td>30.00</td>\n      <td>30.00</td>\n      <td>30.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>25 rows \u00d7 27 columns</p>\n</div>\n\n\n\n\n```python\n# high response but not promoted\ndata.sort_values(\"score_diff\", ascending=True).head(25)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n      <th>score_diff</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>42028ce3b987d9ec95e01274b992204bf27fdb1a</th>\n      <td>https://www.huffingtonpost.com/entry/exposing-...</td>\n      <td>Exposing America's Biggest Hypocrites: Evangel...</td>\n      <td>2017-11-24 17:31:31.338</td>\n      <td>2017-11-24 17:27:39.012</td>\n      <td>86827</td>\n      <td>79.97</td>\n      <td>2017-11-25T17:20:19.095Z</td>\n      <td>18763</td>\n      <td>56521</td>\n      <td>11543</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>953.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>0d1704ce4fcd2856a1357d444ab6ddd4610db8f8</th>\n      <td>https://www.huffingtonpost.com/entry/since-you...</td>\n      <td>Since you asked, Roy Moore, here is why victim...</td>\n      <td>2017-11-11 18:01:19.973</td>\n      <td>2017-11-11 17:49:19.798</td>\n      <td>85116</td>\n      <td>21.63</td>\n      <td>2017-11-16T01:28:12.610Z</td>\n      <td>11355</td>\n      <td>56808</td>\n      <td>16953</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>1261.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>93f4b0a5428fd4f228b02b823c4f3922e6130bff</th>\n      <td>https://www.nytimes.com/2017/11/26/business/me...</td>\n      <td>Time Inc. Is Said to Near Sale in Deal Backed ...</td>\n      <td>2017-11-26 21:07:10.424</td>\n      <td>2017-11-26 21:05:08.000</td>\n      <td>94430</td>\n      <td>328.39</td>\n      <td>2017-11-27T03:06:04.999Z</td>\n      <td>20502</td>\n      <td>59091</td>\n      <td>14837</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>120</td>\n      <td>680.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>36a95aa544343e37d69586a3f628b6ebe4e04220</th>\n      <td>https://www.buzzfeed.com/alexandrearagao/manif...</td>\n      <td>Manifestantes p\u00f5em fogo em boneca de fil\u00f3sofa ...</td>\n      <td>2017-11-07 14:46:25.813</td>\n      <td>2017-11-07 14:35:57.000</td>\n      <td>80375</td>\n      <td>206.32</td>\n      <td>2017-11-07T16:10:08.489Z</td>\n      <td>11476</td>\n      <td>63186</td>\n      <td>5713</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>nan</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>71e02bf08d789e6191eac1f32dfefd85c6f71a27</th>\n      <td>http://insider.foxnews.com/2017/11/07/mike-pen...</td>\n      <td>WATCH: Pence Responds to Attacks on Prayer Aft...</td>\n      <td>2017-11-08 04:59:07.133</td>\n      <td>2017-11-07 23:50:00.000</td>\n      <td>109556</td>\n      <td>229.75</td>\n      <td>2017-11-08T12:27:07.534Z</td>\n      <td>14945</td>\n      <td>89516</td>\n      <td>5095</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>197.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>21e7fb448ff66db53054103e7e866ebd8faafdb6</th>\n      <td>http://www.foxnews.com/politics/2017/11/03/tru...</td>\n      <td>Trump embarks on 13-day foreign trip to Asia</td>\n      <td>2017-11-03 15:34:17.642</td>\n      <td>2017-11-03 15:21:29.000</td>\n      <td>80522</td>\n      <td>162.73</td>\n      <td>2017-11-03T22:02:04.064Z</td>\n      <td>9910</td>\n      <td>68673</td>\n      <td>1939</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>1053.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>c08460b2595b412be2e6a31d0c42234a67ba7d21</th>\n      <td>http://www.foxnews.com/entertainment/2017/11/3...</td>\n      <td>Jim Nabors dead; star best known as Gomer Pyle...</td>\n      <td>2017-11-30 18:09:13.397</td>\n      <td>2017-11-30 18:03:53.000</td>\n      <td>102762</td>\n      <td>303.00</td>\n      <td>2017-11-30T20:17:10.889Z</td>\n      <td>16818</td>\n      <td>70041</td>\n      <td>15903</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>172.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>9b07e5f6fc081861f8d0c6d6bb478e6c43d3fba6</th>\n      <td>http://yournewswire.com/jay-z-jesus-fake-lucifer/</td>\n      <td>Jay-Z: 'Jesus Is Fake News; Lucifer Is Way Of ...</td>\n      <td>2017-11-13 17:54:26.080</td>\n      <td>2017-11-13 17:27:17.000</td>\n      <td>85940</td>\n      <td>32.63</td>\n      <td>2017-11-14T16:17:12.675Z</td>\n      <td>42233</td>\n      <td>33501</td>\n      <td>10206</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>22568</td>\n      <td>521.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>26f86dbc9b9cc02d1e3130f085f97195b585a3a4</th>\n      <td>https://www.washingtonpost.com/news/sports/wp/...</td>\n      <td>Shalane Flanagan becomes first American woman ...</td>\n      <td>2017-11-05 16:59:18.064</td>\n      <td>2017-11-05 16:56:00.000</td>\n      <td>114335</td>\n      <td>1522.95</td>\n      <td>2017-11-06T16:28:13.194Z</td>\n      <td>3220</td>\n      <td>106152</td>\n      <td>4963</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>32.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>6d75837f69cebb8b1cefae20422de0c1ea000beb</th>\n      <td>https://www.theguardian.com/environment/2017/n...</td>\n      <td>Michael Bloomberg\u2019s \u2018war on coal\u2019 goes global ...</td>\n      <td>2017-11-09 06:49:05.637</td>\n      <td>2017-11-09 06:45:06.000</td>\n      <td>328658</td>\n      <td>409.75</td>\n      <td>2017-11-11T18:03:11.221Z</td>\n      <td>462</td>\n      <td>327101</td>\n      <td>1095</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>142</td>\n      <td>740.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>52.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>8ebbbf91d0f0d5617002ef50d4738426ba4d72b2</th>\n      <td>https://www.huffingtonpost.com/entry/repent-an...</td>\n      <td>Repent and Believe in the Gospel! Over 300 Chr...</td>\n      <td>2017-11-20 20:46:19.033</td>\n      <td>2017-11-20 20:40:02.257</td>\n      <td>62306</td>\n      <td>29.13</td>\n      <td>2017-11-21T17:00:04.727Z</td>\n      <td>9176</td>\n      <td>41868</td>\n      <td>11262</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>981.00</td>\n      <td>48.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>48.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>6f2b23a4e1bcf2a0aaec840d0c405f2555e0021c</th>\n      <td>https://www.buzzfeed.com/beatrizserranomolina/...</td>\n      <td>\u00bfY c\u00f3mo se supone que se tiene que comportar u...</td>\n      <td>2017-11-15 13:01:19.016</td>\n      <td>2017-11-15 11:47:22.000</td>\n      <td>61572</td>\n      <td>54.31</td>\n      <td>2017-11-15T22:11:07.513Z</td>\n      <td>7987</td>\n      <td>43761</td>\n      <td>9824</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>1010.00</td>\n      <td>48.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>48.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>bbbf07f32f7cd2f97ab067f0cca7236f88d75347</th>\n      <td>https://www.washingtonpost.com/news/education/...</td>\n      <td>Teachers spend nearly $1,000 a year on supplie...</td>\n      <td>2017-11-03 00:37:11.237</td>\n      <td>2017-11-03 00:24:13.000</td>\n      <td>62320</td>\n      <td>28.91</td>\n      <td>2017-11-04T16:16:11.718Z</td>\n      <td>13950</td>\n      <td>36628</td>\n      <td>11742</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>554.00</td>\n      <td>48.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>48.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>ba4dd0d3636f52b2c3acace3a81c55dd0ccb4a7e</th>\n      <td>http://www.independent.co.uk/life-style/people...</td>\n      <td>People who put up Christmas decorations early ...</td>\n      <td>2017-11-20 15:19:18.674</td>\n      <td>2017-11-20 15:18:29.000</td>\n      <td>57406</td>\n      <td>220.70</td>\n      <td>2017-11-21T16:08:07.332Z</td>\n      <td>23434</td>\n      <td>30356</td>\n      <td>3616</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>386</td>\n      <td>363.00</td>\n      <td>48.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>48.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>40c8c55d685b08a0be04a3ff12d943c00dfc1d95</th>\n      <td>https://www.huffingtonpost.com/entry/what-work...</td>\n      <td>What Working People Face</td>\n      <td>2017-11-05 20:01:14.905</td>\n      <td>2017-11-05 19:57:11.582</td>\n      <td>55579</td>\n      <td>29.91</td>\n      <td>2017-11-06T18:32:10.656Z</td>\n      <td>2505</td>\n      <td>48871</td>\n      <td>4203</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>832.00</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>47.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>328125a8ff5f9d8fa2f27e87f31f825a8d84afbb</th>\n      <td>https://www.nytimes.com/2017/11/25/us/ohio-hov...</td>\n      <td>In America\u2019s Heartland, the Nazi Sympathizer N...</td>\n      <td>2017-11-25 16:22:14.136</td>\n      <td>2017-11-25 16:18:53.000</td>\n      <td>63540</td>\n      <td>45.21</td>\n      <td>2017-11-26T00:09:05.054Z</td>\n      <td>29483</td>\n      <td>26172</td>\n      <td>7885</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>120</td>\n      <td>2267.00</td>\n      <td>48.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>49.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>5d4dffaf16d73098cf982bdb11b7c43ceae43104</th>\n      <td>http://www.foxnews.com/politics/2017/11/16/tru...</td>\n      <td>Trump to lift ban on importing elephant trophi...</td>\n      <td>2017-11-16 07:24:13.207</td>\n      <td>2017-11-16 06:46:06.000</td>\n      <td>54014</td>\n      <td>69.05</td>\n      <td>2017-11-16T15:56:07.176Z</td>\n      <td>22421</td>\n      <td>25194</td>\n      <td>6399</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>355.00</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>48.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>8a826e4e1f393df72e7860ce819b52385cb47ff7</th>\n      <td>https://www.washingtonpost.com/news/wonk/wp/20...</td>\n      <td>37 of 38 economists said the GOP tax plans wou...</td>\n      <td>2017-11-22 16:01:20.600</td>\n      <td>2017-11-22 15:47:42.000</td>\n      <td>50910</td>\n      <td>140.55</td>\n      <td>2017-11-22T22:25:10.300Z</td>\n      <td>6022</td>\n      <td>35960</td>\n      <td>8928</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>672.00</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>48.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>90d101797f1de9c57000613cd336854586fd7fa4</th>\n      <td>https://www.washingtonpost.com/news/national/w...</td>\n      <td>Charles Manson, the fiery-eyed cult leader who...</td>\n      <td>2017-11-20 05:59:15.649</td>\n      <td>2017-11-20 05:53:00.000</td>\n      <td>51672</td>\n      <td>174.73</td>\n      <td>2017-11-20T06:10:05.982Z</td>\n      <td>13170</td>\n      <td>31137</td>\n      <td>7365</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>146.00</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>48.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>069b9faa8dfdb74f280b47a0ad9ce97c73bd7d4d</th>\n      <td>http://www.foxnews.com/science/2017/11/07/hell...</td>\n      <td>'Hell is Here' for burning elephants in award-...</td>\n      <td>2017-11-07 16:54:16.736</td>\n      <td>2017-11-07 16:54:16.736</td>\n      <td>50714</td>\n      <td>248.06</td>\n      <td>2017-11-08T14:06:07.932Z</td>\n      <td>12146</td>\n      <td>32338</td>\n      <td>6230</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>380.00</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>48.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>766d2bd690e1055b804eaae1ea439964586aa8c8</th>\n      <td>https://www.washingtonpost.com/news/politics/w...</td>\n      <td>In a rarity, Trump says administration will ba...</td>\n      <td>2017-11-18 01:49:14.023</td>\n      <td>2017-11-18 01:45:00.000</td>\n      <td>49202</td>\n      <td>234.59</td>\n      <td>2017-11-18T18:22:05.966Z</td>\n      <td>8326</td>\n      <td>34803</td>\n      <td>6073</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>73.00</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>48.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>2491314cee8db9dfac626a215a1efcf87fa340e7</th>\n      <td>https://www.huffingtonpost.com/entry/kaeptain-...</td>\n      <td>KAEPtain America: This Is What A Patriot Looks...</td>\n      <td>2017-11-13 23:16:13.630</td>\n      <td>2017-11-13 23:10:19.532</td>\n      <td>47303</td>\n      <td>78.29</td>\n      <td>2017-11-14T02:29:06.819Z</td>\n      <td>6663</td>\n      <td>38123</td>\n      <td>2517</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>847.00</td>\n      <td>46.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>46.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>c6d5ebd4e61ff24c3d1a6860a0eeebe586ebbd4b</th>\n      <td>http://yournewswire.com/cia-agent-deathbed-bob...</td>\n      <td>CIA Agent Confesses On Deathbed: \u2018I Killed Bob...</td>\n      <td>2017-11-30 17:24:36.210</td>\n      <td>2017-11-30 16:56:00.000</td>\n      <td>109979</td>\n      <td>46.52</td>\n      <td>2017-12-02T15:10:16.853Z</td>\n      <td>34047</td>\n      <td>49632</td>\n      <td>26300</td>\n      <td>...</td>\n      <td>2017-12-01T15:04:01.000Z</td>\n      <td>22568</td>\n      <td>907.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>4.00</td>\n      <td>5.00</td>\n      <td>55.00</td>\n      <td>-45.00</td>\n    </tr>\n    <tr>\n      <th>844ef6eb6931cdb104db43fbb85318c886a6f89d</th>\n      <td>https://www.theguardian.com/australia-news/201...</td>\n      <td>Same-sex marriage bill passes in Australian Se...</td>\n      <td>2017-11-29 02:37:10.818</td>\n      <td>2017-11-29 02:34:52.000</td>\n      <td>35803</td>\n      <td>144.64</td>\n      <td>2017-11-29T02:48:15.367Z</td>\n      <td>2219</td>\n      <td>31450</td>\n      <td>2134</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>142</td>\n      <td>693.00</td>\n      <td>45.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>45.00</td>\n      <td>-45.00</td>\n    </tr>\n    <tr>\n      <th>66d9977c8749c1bd45ecdfe077fbabdf5012f716</th>\n      <td>http://www.breitbart.com/big-government/2017/1...</td>\n      <td>President Trump Will Permit Citizens to Buy Mi...</td>\n      <td>2017-11-24 23:24:17.385</td>\n      <td>2017-11-24 12:09:26.000</td>\n      <td>46124</td>\n      <td>24.30</td>\n      <td>2017-11-26T17:40:16.302Z</td>\n      <td>6806</td>\n      <td>35818</td>\n      <td>3500</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>994</td>\n      <td>266.00</td>\n      <td>46.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>47.00</td>\n      <td>-45.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>25 rows \u00d7 27 columns</p>\n</div>\n\n\n\nWrite that data to a file. Note that the scores here are provisional for two reasons:\n1. they should be using a rolling-month based on the article publication date to calculate medians/min/max etc, whereas in this workbook we as just using values for the month of May\n2. for analysis, we've rounded the numbers; we don't expect to do that for the actual scores\n\n\n```python\ndata.to_csv(\"articles_with_provisional_scores_2017-10-01_2017-10-31.csv\")\n```\n\n# Summary\n\nThe attention index of an article is comprised of four components:\n\n- *lead score* (max 20 points) based on how long an article was the lead story on the publisher's home page, scaled by the traffic to that publisher\n- *front score* (max 15 points) based on how long an article was present on the publisher's home page, scaled by traffic to that publisher\n- *Facebook promotion score* (max 15 points) based on whether the article was promoted to the publisher's Facebook brand page, scaled by the reach of that brand page\n- *response score* (max 50 points) based on the number of Facebook engagements the article received, relative to other articles\n\nOr, in other words:\n\n\\begin{align}\nattentionIndex_a &= leadScore_a + frontScore_a + facebookPromotionScore_a + responseScore_a \\\\\nleadScore_a &= 20 \\cdot \\left(\\frac{\\min(minsAsLead_a, 60)}{alexaRank_a}\\right) \\cdot \\left( \\frac{\\min(alexaRank)}{60} \\right) \\\\\nfrontScore_a &= \n15 \\cdot\n\\left(\\frac{\\min(minsOnFront_a, 1440)}{alexaRank_a \\cdot numArticlesOnFront_a}\\right) \\cdot\n\\left( \\frac{\\min(alexaRank \\cdot numArticlesOnFront)}{1440} \\right) \\\\\nfacebookPromotion_a &= \n\\begin{cases}\n 0 \\text{ if not shared on brand page }\\\\\n   15 \\cdot \\frac{\\log(brandPageLikes_a) - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))}  \\text{ otherwise }\n\\end{cases}   \n\\\\\nresponseScore_a &= \n\\begin{cases} \n   0 \\text{ if } engagements_a = 0 \\\\\n   50 \\cdot \n   \\frac{\\log(\\min(engagements_a,limit) + median(engagements)) - \\log(1 + median(engagements))}\n   {\\log(limit + median(engagements)) - \\log(1 + median(engagements))} \\text{ if } engagements_a > 0\n\\end{cases} \\\\\n\\end{align} \n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "ba6c6409a73ec33cf5f366144b8c93debbf1cf46", "size": 734697, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "data/attention-index-november.ipynb", "max_stars_repo_name": "kaleida/attention-index", "max_stars_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2017-06-03T11:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T10:02:06.000Z", "max_issues_repo_path": "data/attention-index-november.ipynb", "max_issues_repo_name": "kaleida/attention-index", "max_issues_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data/attention-index-november.ipynb", "max_forks_repo_name": "kaleida/attention-index", "max_forks_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 85.0639110802, "max_line_length": 47074, "alphanum_fraction": 0.6952185731, "converted": true, "num_tokens": 56652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33458942798284697, "lm_q2_score": 0.05184546371976373, "lm_q1q2_score": 0.01734694404950119}}
{"text": "```python\n!pip install qiskit\n```\n\n    Collecting qiskit\n      Downloading https://files.pythonhosted.org/packages/6f/61/cb7506e17a2566dc8a31a3e1924d91ac0bdd8ff07c71ec698c06647b6306/qiskit-0.26.2.tar.gz\n    Collecting qiskit-terra==0.17.4\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/b3/0c/3c7a8dd451dae0907263e9de9e3e34909e15e18c88a589b44581972c8511/qiskit_terra-0.17.4-cp37-cp37m-manylinux2010_x86_64.whl (6.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.0MB 14.5MB/s \n    \u001b[?25hCollecting qiskit-aer==0.8.2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/c2/d2/6ff15c370b5465b32529b528bf3f4ce1e01f74498be16203aa1c04b67022/qiskit_aer-0.8.2-cp37-cp37m-manylinux2010_x86_64.whl (18.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 18.0MB 231kB/s \n    \u001b[?25hCollecting qiskit-ibmq-provider==0.13.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/be/99/74bbb901f88603a7d850d4889abc06d81ba702e4227151f4a5b66f2631fe/qiskit_ibmq_provider-0.13.1-py3-none-any.whl (228kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 235kB 59.0MB/s \n    \u001b[?25hCollecting qiskit-ignis==0.6.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/54/be/a13c828e457e09d979667a61bddbd8c7246aafa94e2501b6a9154429cbea/qiskit_ignis-0.6.0-py3-none-any.whl (207kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 215kB 53.3MB/s \n    \u001b[?25hCollecting qiskit-aqua==0.9.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/88/79/392c57b978decbb24b902344b536af52c40a751aed0ebbaefa8bc2964cb5/qiskit_aqua-0.9.1-py3-none-any.whl (2.1MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.1MB 38.1MB/s \n    \u001b[?25hCollecting retworkx>=0.8.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/9e/cd/70d436f170aa1ead2ac9e4c19c8838633355d48b530f09455eab0af2f98e/retworkx-0.9.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.5MB 33.3MB/s \n    \u001b[?25hRequirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (1.7.1)\n    Collecting ply>=3.10\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/a3/58/35da89ee790598a0700ea49b2a66594140f44dec458c07e8e3d4979137fc/ply-3.11-py2.py3-none-any.whl (49kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 5.6MB/s \n    \u001b[?25hRequirement already satisfied: scipy>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (1.4.1)\n    Collecting python-constraint>=1.4\n      Downloading https://files.pythonhosted.org/packages/37/8b/5f1bc2734ca611943e1d6733ee244238679f6410a10cd45ede55a61a8402/python-constraint-1.4.0.tar.bz2\n    Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (1.19.5)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (5.4.8)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (2.8.1)\n    Collecting fastjsonschema>=2.10\n      Downloading https://files.pythonhosted.org/packages/d1/fb/ea090e917b18320f79be31d754bbe496b715175e865603cfce1eaed2e774/fastjsonschema-2.15.1-py3-none-any.whl\n    Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (2.6.0)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.17.4->qiskit) (0.3.3)\n    Collecting pybind11>=2.6\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/8d/43/7339dbabbc2793718d59703aace4166f53c29ee1c202f6ff5bf8a26c4d91/pybind11-2.6.2-py2.py3-none-any.whl (191kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 194kB 44.0MB/s \n    \u001b[?25hRequirement already satisfied: nest-asyncio!=1.1.0,>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit) (1.5.1)\n    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit) (1.24.3)\n    Collecting websockets>=8\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/84/64/78c2b3fe37730b30dca3c93d1f7f4a4286767f86e7c04cf3571b39bc2fb7/websockets-9.1-cp37-cp37m-manylinux2010_x86_64.whl (103kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 112kB 47.3MB/s \n    \u001b[?25hCollecting requests-ntlm>=1.1.0\n      Downloading https://files.pythonhosted.org/packages/03/4b/8b9a1afde8072c4d5710d9fa91433d504325821b038e00237dc8d6d833dc/requests_ntlm-1.1.0-py2.py3-none-any.whl\n    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.13.1->qiskit) (2.23.0)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ignis==0.6.0->qiskit) (56.1.0)\n    Collecting quandl<=3.6.0\n      Downloading https://files.pythonhosted.org/packages/c2/58/9f0e69d836045e3865d263e9ed49f42b23a58526fdabb30f74c430baee3f/Quandl-3.6.0-py2.py3-none-any.whl\n    Requirement already satisfied: fastdtw<=0.3.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (0.3.4)\n    Requirement already satisfied: pandas<=1.2.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (1.1.5)\n    Collecting docplex<=2.20.204; sys_platform != \"darwin\"\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/87/99/6f7c219b39fd58c84688ad0713eb932bfcf6be81fc74519e43ea9c915b56/docplex-2.20.204.tar.gz (611kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 614kB 35.8MB/s \n    \u001b[?25hCollecting dlx<=1.0.4\n      Downloading https://files.pythonhosted.org/packages/54/c0/b8fb5bb727e983b6f5251433ef941b48f38c65bb0bd6ec509e9185bcd406/dlx-1.0.4.tar.gz\n    Requirement already satisfied: h5py<=3.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (3.1.0)\n    Requirement already satisfied: scikit-learn<=0.24.1,>=0.20.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aqua==0.9.1->qiskit) (0.22.2.post1)\n    Collecting yfinance<=0.1.55\n      Downloading https://files.pythonhosted.org/packages/7a/e8/b9d7104d3a4bf39924799067592d9e59119fcfc900a425a12e80a3123ec8/yfinance-0.1.55.tar.gz\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra==0.17.4->qiskit) (1.2.1)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.8.0->qiskit-terra==0.17.4->qiskit) (1.15.0)\n    Collecting ntlm-auth>=1.0.2\n      Downloading https://files.pythonhosted.org/packages/ff/84/97c550164b54942b0e908c31ef09d9469f3ba4cd7332a671e2125732f63b/ntlm_auth-1.5.0-py2.py3-none-any.whl\n    Collecting cryptography>=1.3\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/b2/26/7af637e6a7e87258b963f1731c5982fb31cd507f0d90d91836e446955d02/cryptography-3.4.7-cp36-abi3-manylinux2014_x86_64.whl (3.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.2MB 36.2MB/s \n    \u001b[?25hRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.13.1->qiskit) (2020.12.5)\n    Collecting inflection>=0.3.1\n      Downloading https://files.pythonhosted.org/packages/59/91/aa6bde563e0085a02a435aa99b49ef75b0a4b062635e606dab23ce18d720/inflection-0.5.1-py2.py3-none-any.whl\n    Requirement already satisfied: more-itertools in /usr/local/lib/python3.7/dist-packages (from quandl<=3.6.0->qiskit-aqua==0.9.1->qiskit) (8.7.0)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas<=1.2.3->qiskit-aqua==0.9.1->qiskit) (2018.9)\n    Requirement already satisfied: cached-property; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from h5py<=3.1.0->qiskit-aqua==0.9.1->qiskit) (1.5.2)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn<=0.24.1,>=0.20.0->qiskit-aqua==0.9.1->qiskit) (1.0.1)\n    Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance<=0.1.55->qiskit-aqua==0.9.1->qiskit) (0.0.9)\n    Collecting lxml>=4.5.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/30/c0/d0526314971fc661b083ab135747dc68446a3022686da8c16d25fcf6ef07/lxml-4.6.3-cp37-cp37m-manylinux2014_x86_64.whl (6.3MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.3MB 32.4MB/s \n    \u001b[?25hRequirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit) (1.14.5)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.13.1->qiskit) (2.20)\n    Building wheels for collected packages: qiskit, python-constraint, docplex, dlx, yfinance\n      Building wheel for qiskit (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for qiskit: filename=qiskit-0.26.2-cp37-none-any.whl size=10491 sha256=938a68eae297c0d3ed016ab50ed6996f7c73c766851b97a48900c6dd0a20a90c\n      Stored in directory: /root/.cache/pip/wheels/89/89/34/524839952d5a58a7be9789e580bfc1ca883bf6579152444568\n      Building wheel for python-constraint (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for python-constraint: filename=python_constraint-1.4.0-py2.py3-none-any.whl size=24079 sha256=449e87ca835a6185aedb48201e24d61ed321b5e2a3ffb284196c83819333f3c2\n      Stored in directory: /root/.cache/pip/wheels/34/31/15/7b070b25d0a549d20ce2e9fe6d727471c2c61ef904720fd40c\n      Building wheel for docplex (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for docplex: filename=docplex-2.20.204-cp37-none-any.whl size=675362 sha256=bb9657b5981b38865d30d87ca199102f30d8e17b030048a825716b600f87c11c\n      Stored in directory: /root/.cache/pip/wheels/ae/2c/e2/a099ebb6fda8adeba9c5fc2e25659d195ad2f5c6cc5fb75fd4\n      Building wheel for dlx (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for dlx: filename=dlx-1.0.4-cp37-none-any.whl size=5712 sha256=2caaeb5548bc8c32b07ea3f4911709d212843a3229cace41e9cac51546df60ca\n      Stored in directory: /root/.cache/pip/wheels/bb/ba/15/fdd0deb104df3254912998150ba9245668db06b00af5912d1a\n      Building wheel for yfinance (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for yfinance: filename=yfinance-0.1.55-py2.py3-none-any.whl size=22616 sha256=cda9371b25d0220c339c4326516bbd505b991bfb53188273409113fbb84900ab\n      Stored in directory: /root/.cache/pip/wheels/04/98/cc/2702a4242d60bdc14f48b4557c427ded1fe92aedf257d4565c\n    Successfully built qiskit python-constraint docplex dlx yfinance\n    \u001b[31mERROR: qiskit-aqua 0.9.1 has requirement retworkx<=0.8.0,>=0.7.0, but you'll have retworkx 0.9.0 which is incompatible.\u001b[0m\n    Installing collected packages: retworkx, ply, python-constraint, fastjsonschema, qiskit-terra, pybind11, qiskit-aer, websockets, ntlm-auth, cryptography, requests-ntlm, qiskit-ibmq-provider, qiskit-ignis, inflection, quandl, docplex, dlx, lxml, yfinance, qiskit-aqua, qiskit\n      Found existing installation: lxml 4.2.6\n        Uninstalling lxml-4.2.6:\n          Successfully uninstalled lxml-4.2.6\n    Successfully installed cryptography-3.4.7 dlx-1.0.4 docplex-2.20.204 fastjsonschema-2.15.1 inflection-0.5.1 lxml-4.6.3 ntlm-auth-1.5.0 ply-3.11 pybind11-2.6.2 python-constraint-1.4.0 qiskit-0.26.2 qiskit-aer-0.8.2 qiskit-aqua-0.9.1 qiskit-ibmq-provider-0.13.1 qiskit-ignis-0.6.0 qiskit-terra-0.17.4 quandl-3.6.0 requests-ntlm-1.1.0 retworkx-0.9.0 websockets-9.1 yfinance-0.1.55\n\n\n\n```python\nfrom qiskit.providers.aer import AerSimulator, QasmSimulator\nfrom qiskit.algorithms import VQE\nfrom qiskit.algorithms.optimizers import COBYLA \nfrom qiskit.circuit.library import TwoLocal\n# opflow is Qiskit's module for creating operators like yours\nfrom qiskit import *\nfrom qiskit.opflow import OperatorBase\nfrom qiskit.opflow import Z, X, I  # Pauli Z, X matrices and identity\nimport pylab\nimport matplotlib.pyplot as plt\nimport numpy as np\n```\n\n\n```python\ndef store_intermediate_result(eval_count, parameters, mean, std):\n  counts.append(eval_count)\n  values.append(mean)\n\ndef get_gradient(values, counts):\n    rvalues = []\n    rcounts = []\n    for i in range(1, len(values)):\n        rvalues += [ (values[i - 1] - values[i]) ]\n    rcounts = [ i for i in range(len(rvalues)) ]\n    return rvalues, rcounts\n\ndef get_absolute(values):\n    return [ (v if v > 0 else -v) for v in values]\n\n```\n\n\n```python\n# J = 1.0\ncounts = []\nvalues = []\n\nH =   (504.0 * I^I^I^I^I^I^I^Z) + (1008.0 * I^I^I^I^I^I^Z^I) + (2016.0 * I^I^I^I^I^Z^I^I) + (504.0 * I^I^I^I^Z^I^I^I) + (1143.7999999999997 * I^I^I^Z^I^I^I^I) + (2287.6 * I^I^Z^I^I^I^I^I) + (4575.200000000001 * I^Z^I^I^I^I^I^I) + (1143.7999999999997 * Z^I^I^I^I^I^I^I) + (98.0 * I^I^I^I^I^I^Z^Z) + (196.0 * I^I^I^I^I^Z^I^Z) + (392.0 * I^I^I^I^I^Z^Z^I) + (49.0 * I^I^I^I^Z^I^I^Z) + (98.0 * I^I^I^I^Z^I^Z^I) + (196.0 * I^I^I^I^Z^Z^I^I) + (93.1 * I^I^Z^Z^I^I^I^I) + (186.2 * I^Z^I^Z^I^I^I^I) + (372.4 * I^Z^Z^I^I^I^I^I) + (46.55 * Z^I^I^Z^I^I^I^I) + (93.1 * Z^I^Z^I^I^I^I^I) + (186.2 * Z^Z^I^I^I^I^I^I)\n\n# you can swap this for a real quantum device and keep the rest of the code the same!\n# backend = AerSimulator(method='matrix_product_state')\n\nbackend = QasmSimulator()\n\n# COBYLA usually works well for small problems like this one\noptimizer = COBYLA(maxiter=2000)\n\n# EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library\nansatz = TwoLocal(num_qubits=8, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True)\n# set the algorithm\nvqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result)\n\n#run it with the Hamiltonian we defined above\nresult = vqe.compute_minimum_eigenvalue(H)  \n\n#print the result (it contains lot's of information)\nprint(result) \n```\n\n    {   'aux_operator_eigenvalues': None,\n        'cost_function_evals': 205,\n        'eigenstate': {   '11011111': 0.03125,\n                          '11110110': 0.04419417382415922,\n                          '11110111': 0.1875,\n                          '11111010': 0.03125,\n                          '11111101': 0.03125,\n                          '11111110': 0.125,\n                          '11111111': 0.9717694878416383},\n        'eigenvalue': -11153.551171875,\n        'optimal_parameters': {   ParameterVectorElement(\u03b8[1]): 3.046753482782516,\n                                  ParameterVectorElement(\u03b8[2]): 3.086210873485022,\n                                  ParameterVectorElement(\u03b8[0]): -2.90679844920079,\n                                  ParameterVectorElement(\u03b8[3]): -3.517745868482567,\n                                  ParameterVectorElement(\u03b8[5]): 3.0678710122000035,\n                                  ParameterVectorElement(\u03b8[8]): 7.900632289038266,\n                                  ParameterVectorElement(\u03b8[12]): -3.42596275263934,\n                                  ParameterVectorElement(\u03b8[10]): -0.2766063880344648,\n                                  ParameterVectorElement(\u03b8[6]): 3.128657974494508,\n                                  ParameterVectorElement(\u03b8[4]): -3.146939556266644,\n                                  ParameterVectorElement(\u03b8[9]): -1.596493351599472,\n                                  ParameterVectorElement(\u03b8[7]): 3.132115702422145,\n                                  ParameterVectorElement(\u03b8[11]): 2.1434175744649955,\n                                  ParameterVectorElement(\u03b8[14]): 1.4724479624926472,\n                                  ParameterVectorElement(\u03b8[13]): -2.124174149035791,\n                                  ParameterVectorElement(\u03b8[15]): -5.539345664240221},\n        'optimal_point': array([-2.90679845, -0.27660639,  2.14341757, -3.42596275, -2.12417415,\n            1.47244796, -5.53934566,  3.04675348,  3.08621087, -3.51774587,\n           -3.14693956,  3.06787101,  3.12865797,  3.1321157 ,  7.90063229,\n           -1.59649335]),\n        'optimal_value': -11153.551171875,\n        'optimizer_evals': 205,\n        'optimizer_time': 5.959498167037964}\n\n\n\n```python\nv1, c1 = get_gradient(values, counts)\nplt.figure(figsize=(15,15))\nplt.plot(c1,v1)\nplt.xlabel('optimization step')\nplt.ylabel('E')\nplt.show()\n```\n\n\n```python\ncounts = []\nvalues = []\n\n```\n\n\n```python\nH = (504.0 * I^I^I^I^I^I^I^Z) + (1008.0 * I^I^I^I^I^I^Z^I) +  (2016.0 * I^I^I^I^I^Z^I^I) + (504.0 * I^I^I^I^Z^I^I^I) +  (1143.7999999999997 * I^I^I^Z^I^I^I^I) +  (2287.6 * I^I^Z^I^I^I^I^I) +  (4575.200000000001 * I^Z^I^I^I^I^I^I) +  (1143.7999999999997 * Z^I^I^I^I^I^I^I) +  (98.0 * I^I^I^I^I^I^Z^Z) +  (196.0 * I^I^I^I^I^Z^I^Z) +  (392.0 * I^I^I^I^I^Z^Z^I) +  (49.0 * I^I^I^I^Z^I^I^Z) +  (98.0 * I^I^I^I^Z^I^Z^I) +  (196.0 * I^I^I^I^Z^Z^I^I) +  (93.1 * I^I^Z^Z^I^I^I^I) +  (186.2 * I^Z^I^Z^I^I^I^I) +  (372.4 * I^Z^Z^I^I^I^I^I) +  (46.55 * Z^I^I^Z^I^I^I^I) +  (93.1 * Z^I^Z^I^I^I^I^I) +  (186.2 * Z^Z^I^I^I^I^I^I)\n# you can swap this for a real quantum device and keep the rest of the code the same!\n# backend = AerSimulator(method='matrix_product_state')\n\nbackend = QasmSimulator()\n\n# COBYLA usually works well for small problems like this one\noptimizer = COBYLA(maxiter=2000)\n\n# EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library\nansatz = TwoLocal(num_qubits=8, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True)\n# set the algorithm\nvqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result)\n\n#run it with the Hamiltonian we defined above\nresult = vqe.compute_minimum_eigenvalue(H)  \n\n#print the result (it contains lot's of information)\nprint(result) \n```\n\n    {   'aux_operator_eigenvalues': None,\n        'cost_function_evals': 255,\n        'eigenstate': {   '01101111': 0.03125,\n                          '01111101': 0.03125,\n                          '01111111': 0.05412658773652741,\n                          '11101101': 0.03125,\n                          '11101111': 0.32923917977664807,\n                          '11111011': 0.03125,\n                          '11111101': 0.10364452469860624,\n                          '11111110': 0.03125,\n                          '11111111': 0.9343697742328784},\n        'eigenvalue': -10965.57451171875,\n        'optimal_parameters': {   ParameterVectorElement(\u03b8[5]): -3.165102845135186,\n                                  ParameterVectorElement(\u03b8[4]): 8.748449247035973,\n                                  ParameterVectorElement(\u03b8[3]): 3.1491153413860373,\n                                  ParameterVectorElement(\u03b8[2]): 3.2184621487031806,\n                                  ParameterVectorElement(\u03b8[1]): 2.9172726271812377,\n                                  ParameterVectorElement(\u03b8[0]): -3.233065992970459,\n                                  ParameterVectorElement(\u03b8[15]): -1.6486371526981256,\n                                  ParameterVectorElement(\u03b8[14]): -5.202419493700512,\n                                  ParameterVectorElement(\u03b8[13]): 2.66845475048185,\n                                  ParameterVectorElement(\u03b8[8]): 2.861947847378163,\n                                  ParameterVectorElement(\u03b8[7]): 3.0156205976029224,\n                                  ParameterVectorElement(\u03b8[9]): -5.806327276587659,\n                                  ParameterVectorElement(\u03b8[6]): 3.196220984325266,\n                                  ParameterVectorElement(\u03b8[12]): -4.927292036226532,\n                                  ParameterVectorElement(\u03b8[10]): -0.6884567108267369,\n                                  ParameterVectorElement(\u03b8[11]): -4.889955253296066},\n        'optimal_point': array([-3.23306599, -0.68845671, -4.88995525, -4.92729204,  2.66845475,\n           -5.20241949, -1.64863715,  2.91727263,  3.21846215,  3.14911534,\n            8.74844925, -3.16510285,  3.19622098,  3.0156206 ,  2.86194785,\n           -5.80632728]),\n        'optimal_value': -10965.57451171875,\n        'optimizer_evals': 255,\n        'optimizer_time': 6.513612508773804}\n\n\n\n```python\nv2, c2 = get_gradient(values, counts)\nplt.figure(figsize=(15,15))\nplt.plot(c2,v2)\nplt.xlabel('optimization step')\nplt.ylabel('E')\nplt.show()\n```\n\n\n```python\ncounts = []\nvalues = []\n```\n\n\n```python\nH = (504.0 * I^I^I^I^I^I^I^Z) + (1008.0 * I^I^I^I^I^I^Z^I) + (2016.0 * I^I^I^I^I^Z^I^I) + (504.0 * I^I^I^I^Z^I^I^I) + (1143.7999999999997 * I^I^I^Z^I^I^I^I) + (2287.6 * I^I^Z^I^I^I^I^I) + (4575.200000000001 * I^Z^I^I^I^I^I^I) + (1143.7999999999997 * Z^I^I^I^I^I^I^I) + (98.0 * I^I^I^I^I^I^Z^Z)+(196.0 * I^I^I^I^I^Z^I^Z) + (392.0 * I^I^I^I^I^Z^Z^I) +  (49.0 * I^I^I^I^Z^I^I^Z) +  (98.0 * I^I^I^I^Z^I^Z^I) +  (196.0 * I^I^I^I^Z^Z^I^I) +  (93.1 * I^I^Z^Z^I^I^I^I) +  (186.2 * I^Z^I^Z^I^I^I^I)+  (372.4 * I^Z^Z^I^I^I^I^I) +  (46.55 * Z^I^I^Z^I^I^I^I) +  (93.1 * Z^I^Z^I^I^I^I^I) +  (186.2 * Z^Z^I^I^I^I^I^I)\n\n# you can swap this for a real quantum device and keep the rest of the code the same!\n# backend = AerSimulator(method='matrix_product_state')\n\nbackend = QasmSimulator()\n\n# COBYLA usually works well for small problems like this one\noptimizer = COBYLA(maxiter=2000)\n\n# EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library\nansatz = TwoLocal(num_qubits=8, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True)\n# set the algorithm\nvqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result)\n\n#run it with the Hamiltonian we defined above\nresult = vqe.compute_minimum_eigenvalue(H)  \n\n#print the result (it contains lot's of information)\nprint(result) \n```\n\n    {   'aux_operator_eigenvalues': None,\n        'cost_function_evals': 214,\n        'eigenstate': {   '01111110': 0.04419417382415922,\n                          '01111111': 0.08267972847076846,\n                          '10111110': 0.04419417382415922,\n                          '10111111': 0.03125,\n                          '11101111': 0.03125,\n                          '11110110': 0.2049199538844375,\n                          '11110111': 0.3321920566479578,\n                          '11111011': 0.03125,\n                          '11111110': 0.46351240544347894,\n                          '11111111': 0.7868548945008857},\n        'eigenvalue': -10992.766503906249,\n        'optimal_parameters': {   ParameterVectorElement(\u03b8[2]): 3.0754720787264387,\n                                  ParameterVectorElement(\u03b8[0]): -2.0394715204534624,\n                                  ParameterVectorElement(\u03b8[1]): 3.1508103200825435,\n                                  ParameterVectorElement(\u03b8[10]): -1.6945307029822305,\n                                  ParameterVectorElement(\u03b8[14]): -0.49360231223732737,\n                                  ParameterVectorElement(\u03b8[13]): -4.6801055701797445,\n                                  ParameterVectorElement(\u03b8[9]): 4.153760587461629,\n                                  ParameterVectorElement(\u03b8[11]): 6.018932414251311,\n                                  ParameterVectorElement(\u03b8[12]): 3.2037597470228123,\n                                  ParameterVectorElement(\u03b8[8]): 1.5798555821165452,\n                                  ParameterVectorElement(\u03b8[6]): -3.2219695042036944,\n                                  ParameterVectorElement(\u03b8[7]): -2.9484899978240806,\n                                  ParameterVectorElement(\u03b8[5]): 3.1941277844827902,\n                                  ParameterVectorElement(\u03b8[4]): -3.1597007294710098,\n                                  ParameterVectorElement(\u03b8[3]): -3.891670254356035,\n                                  ParameterVectorElement(\u03b8[15]): -1.2843062805907928},\n        'optimal_point': array([-2.03947152, -1.6945307 ,  6.01893241,  3.20375975, -4.68010557,\n           -0.49360231, -1.28430628,  3.15081032,  3.07547208, -3.89167025,\n           -3.15970073,  3.19412778, -3.2219695 , -2.94849   ,  1.57985558,\n            4.15376059]),\n        'optimal_value': -10992.766503906249,\n        'optimizer_evals': 214,\n        'optimizer_time': 7.787711143493652}\n\n\n\n```python\nv3, c3 = get_gradient(values, counts)\nplt.figure(figsize=(15,15))\nplt.plot(c3,v3)\nplt.xlabel('optimization step')\nplt.ylabel('E')\nplt.show()\n```\n\n\n```python\ncounts = []\nvalues = []\n```\n\n\n```python\nH = (504.0 * I^I^I^I^I^I^I^Z) +  (1008.0 * I^I^I^I^I^I^Z^I) +  (2016.0 * I^I^I^I^I^Z^I^I) +  (504.0 * I^I^I^I^Z^I^I^I) +  (1143.7999999999997 * I^I^I^Z^I^I^I^I) +  (2287.6 * I^I^Z^I^I^I^I^I) +  (4575.200000000001 * I^Z^I^I^I^I^I^I) +  (1143.7999999999997 * Z^I^I^I^I^I^I^I)+  (98.0 * I^I^I^I^I^I^Z^Z) +  (196.0 * I^I^I^I^I^Z^I^Z) +  (392.0 * I^I^I^I^I^Z^Z^I) +  (49.0 * I^I^I^I^Z^I^I^Z)+  (98.0 * I^I^I^I^Z^I^Z^I)+  (196.0 * I^I^I^I^Z^Z^I^I) +  (93.1 * I^I^Z^Z^I^I^I^I)+  (186.2 * I^Z^I^Z^I^I^I^I)+  (372.4 * I^Z^Z^I^I^I^I^I)+  (46.55 * Z^I^I^Z^I^I^I^I)+  (93.1 * Z^I^Z^I^I^I^I^I)+  (186.2 * Z^Z^I^I^I^I^I^I)\n\n# you can swap this for a real quantum device and keep the rest of the code the same!\n# backend = AerSimulator(method='matrix_product_state')\n\nbackend = QasmSimulator()\n\n# COBYLA usually works well for small problems like this one\noptimizer = COBYLA(maxiter=2000)\n\n# EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library\nansatz = TwoLocal(num_qubits=8, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True)\n# set the algorithm\nvqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result)\n\n#run it with the Hamiltonian we defined above\nresult = vqe.compute_minimum_eigenvalue(H)  \n\n#print the result (it contains lot's of information)\nprint(result) \n```\n\n    {   'aux_operator_eigenvalues': None,\n        'cost_function_evals': 184,\n        'eigenstate': {   '11100111': 0.03125,\n                          '11101110': 0.03125,\n                          '11110011': 0.04419417382415922,\n                          '11110110': 0.23385358667337133,\n                          '11110111': 0.649519052838329,\n                          '11111010': 0.03125,\n                          '11111011': 0.03125,\n                          '11111101': 0.05412658773652741,\n                          '11111110': 0.24206145913796356,\n                          '11111111': 0.6753182120304472},\n        'eigenvalue': -10963.80126953125,\n        'optimal_parameters': {   ParameterVectorElement(\u03b8[7]): -3.0764720942752097,\n                                  ParameterVectorElement(\u03b8[9]): -2.9562550418913713,\n                                  ParameterVectorElement(\u03b8[6]): 3.1672992325151417,\n                                  ParameterVectorElement(\u03b8[4]): -3.0813931010365248,\n                                  ParameterVectorElement(\u03b8[8]): 2.104987703370218,\n                                  ParameterVectorElement(\u03b8[12]): -5.736766438853289,\n                                  ParameterVectorElement(\u03b8[2]): -3.047317376298203,\n                                  ParameterVectorElement(\u03b8[10]): 0.6228108551453106,\n                                  ParameterVectorElement(\u03b8[11]): 7.221157300557545,\n                                  ParameterVectorElement(\u03b8[5]): 3.1023633907103267,\n                                  ParameterVectorElement(\u03b8[3]): 4.643156654705857,\n                                  ParameterVectorElement(\u03b8[14]): -3.4173058051282617,\n                                  ParameterVectorElement(\u03b8[13]): 5.145241204885928,\n                                  ParameterVectorElement(\u03b8[15]): -3.0333728595768443,\n                                  ParameterVectorElement(\u03b8[1]): 3.0637009227102765,\n                                  ParameterVectorElement(\u03b8[0]): 3.849449691053329},\n        'optimal_point': array([ 3.84944969,  0.62281086,  7.2211573 , -5.73676644,  5.1452412 ,\n           -3.41730581, -3.03337286,  3.06370092, -3.04731738,  4.64315665,\n           -3.0813931 ,  3.10236339,  3.16729923, -3.07647209,  2.1049877 ,\n           -2.95625504]),\n        'optimal_value': -10963.80126953125,\n        'optimizer_evals': 184,\n        'optimizer_time': 6.882545471191406}\n\n\n\n```python\nv4, c4 = get_gradient(values, counts)\nplt.figure(figsize=(15,15))\nplt.plot(c4,v4)\nplt.xlabel('optimization step')\nplt.ylabel('E')\nplt.show()\n```\n\n\n```python\n# 2nd Order Der\n\nv1, c1 = get_gradient(v1, c1)\nv2, c2 = get_gradient(v2, c2)\nv3, c3 = get_gradient(v3, c3)\nv4, c4 = get_gradient(v4, c4)\n\n```\n\n\n```python\nv1 = get_absolute(v1)\nv2 = get_absolute(v2)\nv3 = get_absolute(v3)\nv4 = get_absolute(v4)\n```\n\n\n```python\nplt.figure(figsize=(15,15))\nplt.plot(c1,v1, label=\"R1\")\nplt.plot(c2,v2, label=\"R2\")\nplt.plot(c3,v3, label=\"R3\")\nplt.plot(c4,v4, label=\"R4\")\nplt.xlabel('comparison optimization step')\nplt.ylabel('E')\nplt.legend()\nplt.show()\n```\n\n\n```python\nplt.figure(figsize=(15,15))\nplt.plot(c1[:100],v1[:100], label=\"R1\")\nplt.plot(c2[:100],v2[:100], label=\"R2\")\nplt.plot(c3[:100],v3[:100], label=\"R3\")\nplt.plot(c4[:100],v4[:100], label=\"R4\")\nplt.xlabel('comparison optimization step')\nplt.ylabel('E')\nplt.legend()\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "0d18f05703a8274532c41b85f6ad2f2250ac8954", "size": 503351, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "research/notebooks/CPM/CPM_VQE_QISKIT_org.ipynb", "max_stars_repo_name": "arnavdas88/QuGlassyIsing", "max_stars_repo_head_hexsha": "6b6514d58646130c03619aebefb9f9aed4e5646a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-19T16:06:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T17:03:31.000Z", "max_issues_repo_path": "research/rough-work-misc/CPM_VQE_QISKIT_org.ipynb", "max_issues_repo_name": "IshmamShah/QuGlassyIsing", "max_issues_repo_head_hexsha": "6c3ff2ebd77ed9b34a0e731083f1e56b7eacb7ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "research/rough-work-misc/CPM_VQE_QISKIT_org.ipynb", "max_forks_repo_name": "IshmamShah/QuGlassyIsing", "max_forks_repo_head_hexsha": "6c3ff2ebd77ed9b34a0e731083f1e56b7eacb7ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-19T16:06:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T06:51:18.000Z", "avg_line_length": 629.18875, "max_line_length": 117358, "alphanum_fraction": 0.9309527546, "converted": true, "num_tokens": 10822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245392906821, "lm_q2_score": 0.06371498891835771, "lm_q1q2_score": 0.01733204050642717}}
{"text": "- title: Active Perception in Adversarial Scenarios\n- summary: Accumulating evidence about peers to discriminate potential threats.\n- author: Daniel Cox\n- date: 2019-09-22\n- category: arXiv highlights\n- image: /static/images/arXiv.gif\n\n# This week\n\nThis week's paper is [Active Perception in Adversarial Scenarios using Maximum Entropy Deep Reinforcement Learning](https://arxiv.org/abs/1902.05644v1). The idea is that an agent interacting with another agent can learn to assess the threat it may pose. It does this by actively testing the opponent agent's behavior, and does not assume the opponent's behavior remains stationary. It uses Bayesian filtering to update its belief about the disposition of the opponent, and that's why this paper caught my eye. I'm on a Bayesian kick lately.\n\n> To summarize, the contribution here is the development of a scalable robust active perception method in scenarios where a potential adversary opponent could be actively hostile to the intent recognition activity, which extends and outperforms the POMDP methods.\n\nI'm a bit short on time this week, so I apologize for the amount of jargon and the unusually high level of confusion.\n\n# Problem setup\n\n> We model the active perception problem as a planning problem, defined by the tuple $\\langle S,A^a,A^o,T,O,R,b_0,\\gamma \\rangle$, where $S=\\langle S^o,S^p \\rangle$ is the state of the world, consisting of the set of observable states $S^o$ and the set of partially observable states $S^p$; $A^a$ is the set of actions of the autonomous agent; $A^o$ is the set of actions of the opponent; we further assume that regardless of the intention, the opponent has the same set of observable actions. Otherwise, an intention is easily identifiable once an action that is uniquely corresponding to that type of intention is observed. $T:S \\times A^a \\times A^o \\rightarrow \\Delta_S $ is the transition probability, where $\\Delta_{\\bullet}$ denotes the space of probability distribution over the space $\\bullet$. $O: S \\times A^a \\rightarrow \\Delta_{A^o}$ is the observation probability; $R: S \\times A^a \\times A^o \\rightarrow  \\mathbb{R}$ is the reward function; $b_0$ is the prior probability of the opponent being an adversary; and $\\gamma$ is the discount factor.\n\nFurther, the opponent is assumed to be either neutral (merely self-interested, in a known way) or hostile (goal-directed, as defined by a known MDP), with bounded rationality, (it may not be able to take the optimal action) and it is likely to behave deceptively.\n\nNotice that the actual behavior of the opponent is known if its disposition is known, which to my mind may or may not be a reasonable assumption, depending on the setting. Since I've had AI safety on the brain lately, it strikes me as _unrealistic_ in a situation where your opponent is smarter than you are. It may be more realistic in settings where everyone has the same goal and it's relatively clear how anyway would try to achieve it if they didn't have to deal with other agents.\n\nThe authors' adversarial model is interesting. ($\\lambda$ is the parameter to $\\pi^o$ that specifies whether the agent is neutral: $\\lambda=0$, or adversarial: $\\lambda=1$):\n\n> We use the following equation to model an adversarial agent's policy $\\pi^o$:\n$$\n\\begin{align}\n\\pi^o(a^o_t|s_t,\\lambda=1;\\alpha,\\beta)= & \\text{argmin}_{\\pi \\in \\Delta} \\{\\mathbb{KL}(\\pi|\\pi^{\\text{MDP}}_{\\alpha})\\\\\n& +\\beta \\mathbb{KL}(\\pi|\\pi^o(\\cdot|s_t,\\lambda=0)) \\}\n\\pi^{\\text{MDP}}_{\\alpha}(a_t^o|s_t,\\lambda=1)=e^{\\alpha Q(s_t,a_t^o)}/Z(s_t)\n\\end{align}\n$$\n\nThe thing to take away from this is that both rationality and deception are tunable parameters. The rationality of the opponent is controlled by the temperature parameter $\\alpha$, by adjusting how well the opponent makes use of the optimal Q function. The degree to which the opponent is _deceptive_ is controlled by $\\beta$, which adjusts how much the KL-divergence of the existing policy from the _neutral_ policy affects the opponent's search for an optimal strategy.\n\n# Bayesian filtering\n\n> We maintain a belief $b_t(\\lambda)$ over the hidden variable by Bayesian filtering.\n\nAs I mentioned, I'm rather short on time today, so I must apologize again for not actually spending the time to explain this. For now, suffice it to say that the opponent is either neutral ($\\lambda=0$) or hostile ($\\lambda=1$), and how your agent reacts to it depends very much on which one of those it believes it is playing against. Bayesian filtering will allow it to make the most of the evidence available, so it can use its best guess as it trains. \n\n> We define a hybrid belief-state dependent reward to balance exploration and safety\n\\begin{equation}\n\\begin{aligned}\nr(b_t,s_t,a^a_t)&=-H(b_t)+r(s_t,a^a_t)\\\\\n&=b\\log b+(1-b)\\log(1-b)+r(s_t,a^a_t),\n\\end{aligned}\n\\label{eq6}\n\\end{equation}\nwhere we use the shorthand $b$ to denote $b_t(\\lambda=1)$, the belief that the opponent is an adversary; and $r(s_t,a^a_t)$ is the state dependent reward.\n\n>This reward balances exploration behavior and safety. The negative entropy reward $-H(b_t)$ can be interpreted as maximizing the expected logarithm of true positive rate (TPR) and true negative rate (TNR). The state-dependent reward $r(s_t,a^a_t)$ depends both on the observable state and the partially observable intent state $\\lambda$, as well as the action of the autonomous agent. This reward \nis used to ensure safety. For instance, some actions could be dangerous to the neutral [opponent], which are discouraged by a large negative reward.\n\nOur agent is trained using [Soft-Q Learning](https://arxiv.org/abs/1702.08165) while values of $\\lambda$ are varied, with corresponding opponent behavior. Interestingly, in the case study section the authors mention that the actual adversary models were not always provided in the learning phase.\n\n> The active perception agent has to identify the hidden intent while bein grobust to this model uncertainty, which is challenging.\n\n# Parting thoughts\n\n1. I admit to being a bit confused by this paper. The authors claim to do Bayesian filtering, but it's not an explicit feature of the algorithm. In fact, they seem to be sampling $\\lambda$ for use in training by using only $b_0$, their prior probability for their belief state. Perhaps it's a typo.\n2. They also seem to claim that the two models of the opponent behavior must be known, but then they mention they're not available during the learning phase in their case study. Drop me a line if this makes sense to you.\n", "meta": {"hexsha": "94d41f5048a743d9d95233aa44197cf63490975f", "size": 7910, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "content/Active Perception in Adversarial Scenarios.ipynb", "max_stars_repo_name": "computableai/computableai.github.io", "max_stars_repo_head_hexsha": "5dff9eb1a4adc2a9c5d10328c4bd8d665f13d0f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-13T17:14:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-07T20:17:06.000Z", "max_issues_repo_path": "content/Active Perception in Adversarial Scenarios.ipynb", "max_issues_repo_name": "computableai/computableai.github.io", "max_issues_repo_head_hexsha": "5dff9eb1a4adc2a9c5d10328c4bd8d665f13d0f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2019-06-29T23:13:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T23:46:45.000Z", "max_forks_repo_path": "content/Active Perception in Adversarial Scenarios.ipynb", "max_forks_repo_name": "computableai/computableai.github.io", "max_forks_repo_head_hexsha": "5dff9eb1a4adc2a9c5d10328c4bd8d665f13d0f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-06-05T00:20:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T07:19:34.000Z", "avg_line_length": 68.7826086957, "max_line_length": 1088, "alphanum_fraction": 0.6896333755, "converted": true, "num_tokens": 1579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2877678279774722, "lm_q2_score": 0.06008665227791172, "lm_q1q2_score": 0.017291005416452288}}
{"text": "##### Copyright 2020 The Cirq Developers\n\n\n```\n#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# Introduction to Cirq\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n  <td>\n    <a target=\"_blank\" href=\"https://quantumai.google/cirq/tutorials/educators/intro\">View on QuantumAI</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/Cirq/blob/master/docs/tutorials/educators/intro.ipynb\">Run in Google Colab</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://github.com/quantumlib/Cirq/blob/master/docs/tutorials/educators/intro.ipynb\">View source on GitHub</a>\n  </td>\n  <td>\n    <a href=\"https://storage.googleapis.com/tensorflow_docs/Cirq/docs/tutorials/educators/intro.ipynb\">Download notebook</a>\n  </td>\n</table>\n\n[Cirq](https://github.com/quantumlib/cirq) is a framework for writing quantum algorithms for noisy intermediate scale quantum (NISQ) devices. Roughly speaking, NISQ devices are those with O(100) qubits that can enact O(1000) gates.  Because the resources for NISQ devices are so constrained, we believe that a framework for writing programs on these devices needs to be aware of all of the architectural properties of the device on which the algorithm is written. This is in contrast to other frameworks where there is a clean separation between the abstract model being used and the details of the device.  \n\nIn this tutorial we will walk through the basics of writing quantum algorithms in Cirq. Our final goal will be to write a variational ansatz for use in an optimization algorithm.\n\n## Installing Cirq\n\nTo use Cirq one first needs to install Cirq.  Installation instructions are available at [quantumai.google/cirq under \"Installing Cirq\"](https://quantumai.google/cirq/install).  For the purpose of this tutorial, we run `pip install cirq` as shown in the following code cell to install the latest release of Cirq. \n\n> Different notebook execution systems exist, but for most part they have \"run\" button on a cell which you can click, or \"shift + enter\" is often the shortcut to run the cell. \n\n\n```\ntry:\n    import cirq\nexcept ImportError:\n    print(\"installing cirq...\")\n    !pip install --quiet cirq --pre\n    print(\"installed cirq.\")\n    import cirq\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n```\n\nNote: this notebook relies on unreleased Cirq features. If you want to try these features, make sure you install cirq via `pip install cirq --pre`.\nLet's check that Cirq has been successfully installed by importing Cirq and printing out a diagram of Google's Bristlecone device shown below.\n\n\n\n\n```\n\"\"\"Test successful installation by printing out the Bristlecone device.\"\"\"\nimport cirq_google\nprint(cirq_google.Bristlecone)\n```\n\n                                                 (0, 5)\u2500\u2500\u2500\u2500(0, 6)\n                                                 \u2502         \u2502\n                                                 \u2502         \u2502\n                                        (1, 4)\u2500\u2500\u2500(1, 5)\u2500\u2500\u2500\u2500(1, 6)\u2500\u2500\u2500\u2500(1, 7)\n                                        \u2502        \u2502         \u2502         \u2502\n                                        \u2502        \u2502         \u2502         \u2502\n                               (2, 3)\u2500\u2500\u2500(2, 4)\u2500\u2500\u2500(2, 5)\u2500\u2500\u2500\u2500(2, 6)\u2500\u2500\u2500\u2500(2, 7)\u2500\u2500\u2500(2, 8)\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                      (3, 2)\u2500\u2500\u2500(3, 3)\u2500\u2500\u2500(3, 4)\u2500\u2500\u2500(3, 5)\u2500\u2500\u2500\u2500(3, 6)\u2500\u2500\u2500\u2500(3, 7)\u2500\u2500\u2500(3, 8)\u2500\u2500\u2500(3, 9)\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n             (4, 1)\u2500\u2500\u2500(4, 2)\u2500\u2500\u2500(4, 3)\u2500\u2500\u2500(4, 4)\u2500\u2500\u2500(4, 5)\u2500\u2500\u2500\u2500(4, 6)\u2500\u2500\u2500\u2500(4, 7)\u2500\u2500\u2500(4, 8)\u2500\u2500\u2500(4, 9)\u2500\u2500\u2500(4, 10)\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n    (5, 0)\u2500\u2500\u2500(5, 1)\u2500\u2500\u2500(5, 2)\u2500\u2500\u2500(5, 3)\u2500\u2500\u2500(5, 4)\u2500\u2500\u2500(5, 5)\u2500\u2500\u2500\u2500(5, 6)\u2500\u2500\u2500\u2500(5, 7)\u2500\u2500\u2500(5, 8)\u2500\u2500\u2500(5, 9)\u2500\u2500\u2500(5, 10)\u2500\u2500\u2500(5, 11)\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n             (6, 1)\u2500\u2500\u2500(6, 2)\u2500\u2500\u2500(6, 3)\u2500\u2500\u2500(6, 4)\u2500\u2500\u2500(6, 5)\u2500\u2500\u2500\u2500(6, 6)\u2500\u2500\u2500\u2500(6, 7)\u2500\u2500\u2500(6, 8)\u2500\u2500\u2500(6, 9)\u2500\u2500\u2500(6, 10)\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n                      (7, 2)\u2500\u2500\u2500(7, 3)\u2500\u2500\u2500(7, 4)\u2500\u2500\u2500(7, 5)\u2500\u2500\u2500\u2500(7, 6)\u2500\u2500\u2500\u2500(7, 7)\u2500\u2500\u2500(7, 8)\u2500\u2500\u2500(7, 9)\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                               (8, 3)\u2500\u2500\u2500(8, 4)\u2500\u2500\u2500(8, 5)\u2500\u2500\u2500\u2500(8, 6)\u2500\u2500\u2500\u2500(8, 7)\u2500\u2500\u2500(8, 8)\n                                        \u2502        \u2502         \u2502         \u2502\n                                        \u2502        \u2502         \u2502         \u2502\n                                        (9, 4)\u2500\u2500\u2500(9, 5)\u2500\u2500\u2500\u2500(9, 6)\u2500\u2500\u2500\u2500(9, 7)\n                                                 \u2502         \u2502\n                                                 \u2502         \u2502\n                                                 (10, 5)\u2500\u2500\u2500(10, 6)\n\n\nThis cell should run successfully, and the output should in fact be the grid of qubits for the Bristlecone device. If so, the install worked!\n\n> Be aware that Cirq is still alpha software, meaning **breaking changes can happen at any time**. If you don't want your project to suddenly go from working to not working when we a new version is released, you should depend on a *specific version* of Cirq and periodically bump that version to the latest one. For example, you can run `pip install cirq==x.y.z` to install version `x.y.z` of Cirq.\n\n## Qubits, Operations, Moments and Circuits\n\nIn Cirq, circuits are represented either by a `Circuit` object. Conceptually:\n\n- A `Circuit` is a collection of `Moment`s. \n- A `Moment` is a collection of `Operation`s that all act during the same abstract time slice. \n- An `Operation` is a an effect that operates on a specific subset of Qubits. \n  - The most common type of `Operation` is a `Gate` applied to several qubits (a \"`GateOperation`\"). \n- The `Qubit`s of a circuit are implicitly defined by the operations - you can't allocate qubits to a Circuit\n  \n\n\n\nThese ideas are illustrated by the above diagram, where time goes from left to right, horizontal lines are different qubits, operations acting on qubits are the boxes (sometimes spanning multiple qubits) and a moment is a group of operations that \"happen at the same time\". \n\n### Create a `Circuit`\n\nA typical way to create a `Circuit` is shown below.\n\n\n```\n\"\"\"Creating a circuit.\"\"\"\n# Define three qubits.\na = cirq.NamedQubit(\"a\")\nb = cirq.NamedQubit(\"b\")\nc = cirq.NamedQubit(\"c\")\n\n# Define a list of operations.\nops = [cirq.H(a), cirq.H(b), cirq.CNOT(b, c), cirq.H(b)]\n\n# Create a circuit from the list of operations.\ncircuit = cirq.Circuit(ops)\nprint(\"Circuit:\\n\")\nprint(circuit)\n```\n\n    Circuit:\n    \n    a: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    b: \u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\n              \u2502\n    c: \u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n### Exercise: Create a Circuit\n\nWrite a program to create the following circuit.\n\n```\n          \u250c\u2500\u2500\u2510\n0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n            \u2502\n1: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500@\u253c\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\n           \u2502\u2502\n2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n            \u2502\n3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n          \u2514\u2500\u2500\u2518\n```\n\nNote that the circuit has a total of 3 different moments.\n\n\n```\n#@title Attempt the solution here\n\n# Define 4 qubits.\n\n# Define a list of operations.\n\n# Create a circuit from the list of operations.\n```\n\n\n```\n#@title Expand to view the solution\n\"\"\"Creating a circuit.\"\"\"\n# Define four line qubits. NamedQubits would also work, however this demonstrates a more succint syntax.\nq = cirq.LineQubit.range(4)\n\n# Define a list of operations.\nops = [cirq.H(q[0]), cirq.H(q[1]), cirq.CNOT(q[1], q[2]), cirq.CNOT(q[0], q[3]), cirq.H(q[2])]\n\n# Create a circuit from the list of operations.\nprint(\"Circuit:\\n\")\nprint(cirq.Circuit(ops))\n```\n\n    Circuit:\n    \n              \u250c\u2500\u2500\u2510\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                \u2502\n    1: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500@\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n               \u2502\u2502\n    2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u253c\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\n                \u2502\n    3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n              \u2514\u2500\u2500\u2518\n\n\n### Unpacking the circuit\nWe can unpack this a bit and see all of the components for the circuit.\n\nThe first thing we do is pick some qubits to use. There are many different types of qubits in Cirq, and you can define your own by inheriting from the `cirq.Qid` class. There's nothing inherently special or magical about these quantum id types such as `cirq.NamedQubit`. They simply identify what you wish to operate on, which is relevant when you are targeting a specific device. For example, if we were creating a circuit for the Bristlecone device and wanted to refer to the qubit in the left-most position, we would use `cirq.GridQubit(5, 0)`. (See the first diagram of the Bristlecone device we printed out.) For simplicity, in the previous cell we defined `cirq.NamedQubit`s which are simply qubits that can be identified by a name.\n\nNext, we encounter the object `cirq.H` which is a Hadamard gate with unitary\n\n$$\nH = {1 \\over \\sqrt{2}} \\left[ \\begin{array}[cc]  & 1 & 1  \\\\ 1 & -1 \\end{array}\\right] .\n$$\n\nIn Cirq, `cirq.H` is an instance of the `cirq.HPowGate` class, which itself is a subclass of `Gate` (along with other classes). We can use Cirq to see the unitary matrix of `Gate` objects as follows.\n\n\n```\n\"\"\"Get the unitary of a gate, here the Hadamard gate.\"\"\"\ncirq.unitary(cirq.H)\n```\n\n\n\n\n    array([[ 0.70710678+0.j,  0.70710678+0.j],\n           [ 0.70710678+0.j, -0.70710678+0.j]])\n\n\n\nWe see that this agrees with the unitary for the Hadamard gate above.\n\n`Gate` objects have the ability to be applied \"on\" one or more qubits.  There are two ways to do this for gates, either using the `on` method or by directly calling the gate on the qubits as if the gate were a function and the qubits were arguments.  For example to apply the `H` on qubit `a` we can say `cirq.H.on(a)` or `cirq.H(a)`.\n\nThe result of those expressions is a `GateOperation` object, which is a type of `Operation`.\n\n> **Note**: In Cirq, there is a strong distinction between `Operation`s and `Gate`s. An `Operation` is associated with specific qubits and can be put in `Circuit`s. A `Gate` has unspecified qubits, and will produce an operation when acting on qubits.\n\nOnce you have a collection of operations, you can construct a `Circuit` by passing the operations into the constructor for a `Circuit`:\n\n```\nops = [list of operations]\ncircuit = cirq.Circuit(ops)\n```\n\nThe last thing we did in the example code was use the (surprisingly useful) ability to print the circuit as a text diagram.\n\nThe diagram is visually helpful, but it doesn't really get into the internal details of how the `Circuit` is represented. As mentioned, a `Circuit` is made up of a sequence of `Moment` objects, and each `Moment` object is a list of non-overlapping `Operation`s. To see this internal structure, we can iterate over the `Moment`s in the `Circuit` and print them out.\n\n\n```\n\"\"\"Print out the moments in a circuit.\"\"\"\nprint(\"Circuit:\\n\")\nprint(circuit)\n\n# Inspecting individual moments.\nprint(\"\\nMoments in the circuit:\\n\")\nfor i, moment in enumerate(circuit):\n    print('Moment {}: \\n{}'.format(i, moment))\n```\n\n    Circuit:\n    \n    a: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    b: \u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\n              \u2502\n    c: \u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    Moments in the circuit:\n    \n    Moment 0: \n      \u2577 None\n    \u2576\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\n    a \u2502 H\n      \u2502\n    b \u2502 H\n      \u2502\n    Moment 1: \n      \u2577 None\n    \u2576\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\n    b \u2502 @\n      \u2502 \u2502\n    c \u2502 X\n      \u2502\n    Moment 2: \n      \u2577 None\n    \u2576\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\n    b \u2502 H\n      \u2502\n\n\nWe see that this circuit consists of three moments. For even more on the underlying structure of a circuit, we can print the circuit's `repr`. This returns a more detailed (and usually less readable) expression.\n\n\n```\n\"\"\"Print the repr of a circuit.\"\"\"\nprint(repr(circuit))\n```\n\n    cirq.Circuit([\n        cirq.Moment(\n            cirq.H(cirq.NamedQubit('a')),\n            cirq.H(cirq.NamedQubit('b')),\n        ),\n        cirq.Moment(\n            cirq.CNOT(cirq.NamedQubit('b'), cirq.NamedQubit('c')),\n        ),\n        cirq.Moment(\n            cirq.H(cirq.NamedQubit('b')),\n        ),\n    ])\n\n\nAlthough it is less readable, the usefulness of printing the `repr` is that it includes *all* the gory details which can be useful when debugging. The `repr` is also a valid python expression that evaluates to the circuit.\nFor example, if we notice that a circuit generated in some complicated way triggers a bug in a simulator, copy-pasting the generated circuit's `repr` into a test, and then working from there, is a simple way to decouple the reproduction of the bug from the circuit generation code.\n\n### More ways to create `Circuit`s\n\nAbove we created a `Circuit` by passing in a list of operations to its constructor.  In Cirq, there are many ways to construct and modify circuits, and each of these is useful in different contexts.  Here are a few examples:\n\n\n1. `Circuit(...)`: This is the simplest way to make a circuit. Give this method some operations, and out pops a circuit.\n2.  `append`:  `Circuit`s are mutable. You can start with an empty `circuit = cirq.Circuit()` and simply `circuit.append(operations)` to add on more and more operations .\n3. `insert`:  Instead of appending, you can insert before a particular moment location (labeled by an integer index).\n\nOne interesting, and extremely convenient, fact about `Circuit(...)`, `append`, and `insert` is that they \"auto flatten\" whatever you give them.\nYou *can* give them a list of operations, but you can also give them\n\n- a list *of lists* of operations,\n- a generator function that sometimes yields tuples of operations and other times yields individual operations,\n- or just a single operation (without a list around it).\n\nIf it can recursively iterated into individual operations, these three methods will take it.\n\n> The above idea uses a concept we call an `OP_TREE` in Cirq. An `OP_TREE` is not a class, but a contract. The basic idea is that if the input can be iteratively flattened into a list of operations, then the input is an `OP_TREE`.\n\nThe main place where auto-flattening is useful is when you are building a circuit's operations using generators. \n\n> Recall that, in Python, functions that have a `yield` statement are *generators*. Generators are functions that act as *iterators*. \n\nIn this context, auto-flattening means that generators producing operations for a circuit can simply `yield` sub-generators (instead of iterating over them and yielding their items). We show an example of this below.\n\n\n```\n\"\"\"Creating a circuit from generator functions.\"\"\"\ndef xor_swap(a, b):\n    \"\"\"Swaps two qubits with three CNOTs.\"\"\"\n    yield cirq.CNOT(a, b) # |a> |b> --> |a> |a ^ b>\n    yield cirq.CNOT(b, a) # |a> |a ^ b> --> |a ^ a ^ b> | a ^ b> = |b>|a^b>\n    yield cirq.CNOT(a, b) # |b> |a ^ b> --> |b>|a ^ b ^ b> = |b> |a>\n\ncirq.Circuit(xor_swap(a, b))\n```\n\n\n\n\n<pre style=\"overflow: auto; white-space: pre;\">a: \u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500\n      \u2502   \u2502   \u2502\nb: \u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500</pre>\n\n\n\n### Exercise: Create a circuit to left rotate 5 qubits. \n\nNow that we've learnt how to build a circuit to swap the state of two qubits, use this to build a circuit which left rotates 5 qubits i.e. on applying the circuit on 5 qubits (0 - 4), the state of qubits should change as follows:\n``` \n0 --> 4 \n4 --> 3\n3 --> 2\n2 --> 1\n1 --> 0\n```\n\n\n```\n#@title Attempt the solution here\n```\n\n\n```\n#@title Expand to view the solution\ndef left_rotate(qubits):\n    \"\"\"Rotates qubits to the left.\"\"\"\n    for i in range(len(qubits) - 1):\n        a, b = qubits[i: i + 2]\n        yield xor_swap(a, b)\n\n\n# Get five qubits on a line.\nline = cirq.LineQubit.range(5)\n\n# Create a circuit which rotates the qubits to the left.\n# uncomment the next line to compare with your circuit\n# print(cirq.Circuit(left_rotate(line)))\n```\n\nOne can see how this method of creating circuits is quite powerful. \n\n> Note that `cirq.SWAP` is a pre-defined gate in Cirq. We used three `cirq.CNOT`s instead of `cirq.SWAP` in the above example to demonstrate auto-flattening with generators.\n\n### Insert strategies\n\nYou may have noticed that there is a hole in what we've explained so far. We have been passing a one-dimensional sequence of operations, but the output is a two-dimensional circuit (a list-of-lists-of-operations). There is a degree of freedom that hasn't been account for. Specifically, how does Cirq choose the moment that each operation will be placed within?\n\nThe answer is the concept of a `cirq.InsertStrategy`. An `InsertStrategy` defines how `Operation`s are placed in a `Circuit` when requested to be inserted at a given location. Here a `location` is identified by the index of the `Moment` in the `Circuit` that operations should be placed before. \n\n> *Note*: In the case of `Circuit.append` this means inserting at the index `len(circuit)` which is one more than the largest moment index and so represents the end of the circuit.\n\nThere are currently four insertion strategies in Cirq:\n\n1. `InsertStrategy.EARLIEST` (the default),\n2. `InsertStrategy.NEW`,\n3. `InsertStrategy.INLINE`,\n4. `InsertStrategy.NEW_THEN_INLINE`.\n\nThe strategy `InsertStrategy.EARLIEST` is defined as follows:\n\n> `InsertStrategy.EARLIEST`: Scans backward from the insert\n> location until a moment with operations touching qubits affected by the\n> operation to insert is found. The operation is added into the moment just\n> after that location.\n\nFor example, if we first create an `Operation` in a single moment,\nand then use `InsertStrategy.EARLIEST` the `Operation` can slide back to this\nfirst `Moment` if there is space.\n\n\n```\n\"\"\"Appending operations with InsertStrategy.EARLIEST.\"\"\"\n# Create an empty circuit.\ncircuit = cirq.Circuit()\n\n# Append an operation.\n# Note: InsertStrategy.EARLIEST is used by default if not otherwise specified.\ncircuit.append([cirq.CZ(a, b)])\n\n# Append more operations.\n# Note: InsertStrategy.EARLIEST is used by default if not otherwise specified.\ncircuit.append([cirq.H(a), cirq.H(b), cirq.H(c)])\n\n# Display the circuit.\nprint(\"Circuit:\\n\")\nprint(circuit)\n```\n\n    Circuit:\n    \n    a: \u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\n          \u2502\n    b: \u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\n    \n    c: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\nAfter creating the first moment with a `CZ` gate, the second\nappend uses the `InsertStrategy.EARLIEST` strategy. The\n`H` on ``a`` and ``b`` cannot slide back, while the `H` on ``c`` can and so ends up in the first `Moment`.\n\nWhile `InsertStrategy.EARLIEST` is the default strategy, the second most important strategy is `InsertStrategy.NEW_THEN_INLINE`, defined as follows:\n\n> `InsertStrategy.NEW_THEN_INLINE`: For the first operation, add it to a new \n> `Moment` the insertion point.  Attempts to add the operation after the first \n> operation to insert into the moment just before the desired insert location. \n> But, if there's already an existing operation affecting any of the qubits\n> touched by the operation to insert, a new moment is created instead and this \n> `Moment` is the one that is subsequently used for insertions.\n\nTo see an example of this strategy, we create a circuit with the same operations but inserting them with a different strategy.\n\n\n```\n\"\"\"Appending operations with InsertStrategy.NEW_THEN_INLINE.\"\"\"\n# Create an empty circuit.\ncircuit = cirq.Circuit()\n\n# Append an operation.\ncircuit.append([cirq.CZ(a, b)], strategy=cirq.InsertStrategy.NEW_THEN_INLINE)\n\n# Append more operations.\ncircuit.append([cirq.H(a), cirq.H(b), cirq.H(c)], strategy=cirq.InsertStrategy.NEW_THEN_INLINE)\n\n# Display the circuit.\nprint(\"Circuit:\\n\")\nprint(circuit)\n```\n\n    Circuit:\n    \n    a: \u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\n          \u2502\n    b: \u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\n    \n    c: \u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\n\n\nIn contrast to the previous codeblock using `InsertStrategy.EARLIEST`, we see that the three `cirq.H` gates appended after the `cirq.CZ` gate appear in the same moment when we use `InsertStrategy.NEW_THEN_INLINE`.\n\n### Exercise: Create the given circuit using least number of appends\n\nNow that you've learned about `InsertStrategy`s, here is an exercise to validate your understanding.  Create, **using the least number of appends**, the following circuit:\n\n\n\n```\na: \u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\n      \u2502\nb: \u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\nc: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n```\n\nHere imagine that you want exactly the moments indicated by the spacing of the circuit so that there are six moments in this circuit.\n\n\n```\n#@title Attempt the solution here\n```\n\n\n```\n#@title Expand to view the solution\n# Define three qubits.\na = cirq.NamedQubit('a')\nb = cirq.NamedQubit('b')\nc = cirq.NamedQubit('c')\n\n# Get an empty circuit.\ncircuit = cirq.Circuit()\n\n# Append these gates using cirq.InsertStrategy.EARLIEST (the default strategy).\ncircuit.append([cirq.CZ(a, b), cirq.H(c), cirq.H(a)])\n\n# Append these gates using cirq.InsertStrategy.NEW_THEN_INLINE.\ncircuit.append(\n    [cirq.H(b), cirq.CZ(b, c), cirq.H(b), cirq.H(a), cirq.H(a)],\n    strategy=cirq.InsertStrategy.NEW_THEN_INLINE\n)\n\n# Display the circuit.\nprint(\"Circuit:\\n\")\nprint(circuit)\n```\n\n    Circuit:\n    \n    a: \u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\n          \u2502\n    b: \u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502\n    c: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n## Simulations of a Circuit\n\nNow that we know how to construct `Circuit`s in Cirq, let's see how to execute them on a simulator. First we create a simple circuit to simulate in the following cell.\n\n\n```\n\"\"\"Get a circuit to simulate.\"\"\"\ndef basic_circuit(measure=True):\n    \"\"\"Returns a simple circuit with some one- and two-qubit gates,\n    as well as (optionally) measurements.\n    \"\"\"\n    # Gates we will use in the circuit.\n    sqrt_x = cirq.X**0.5\n    cz = cirq.CZ\n    \n    # Yield the operations.\n    yield sqrt_x(a), sqrt_x(b)\n    yield cz(a, b)\n    yield sqrt_x(a), sqrt_x(b)\n    if measure:\n        yield cirq.measure(a,b)\n\n# Create a circuit including measurements.\ncircuit = cirq.Circuit(basic_circuit())\nprint(circuit)\n```\n\n    a: \u2500\u2500\u2500X^0.5\u2500\u2500\u2500@\u2500\u2500\u2500X^0.5\u2500\u2500\u2500M\u2500\u2500\u2500\n                  \u2502           \u2502\n    b: \u2500\u2500\u2500X^0.5\u2500\u2500\u2500@\u2500\u2500\u2500X^0.5\u2500\u2500\u2500M\u2500\u2500\u2500\n\n\nThe main simulator in Cirq is the `cirq.Simulator`. The general pattern of simulation is to instantiate this simulator, then pass in a circuit to either the `run` or `simulate` methods (more on this below).\n\n\n```\n\"\"\"Example of simulating a circuit in Cirq.\"\"\"\n# Get a simulator.\nsimulator = cirq.Simulator()\n\n# Pass the circuit to the simulator.run method.\nresult = simulator.run(circuit, repetitions=1)\nprint(\"Measurement results:\")\nprint(result)\n```\n\n    Measurement results:\n    a,b=1, 0\n\n\nRunning this multiple times should result in different measurement results, since the circuit produces a superposition over all computational basis states.\n\nAbove we used the `run` method of the `simulator`. In Cirq, `run` methods mimic the actual hardware in that they don't give one access to unphysical objects like the wavefunction. The `repetitions` argument is how many times to sample from the circuit.\n\n\n\nIf one wants to get the wavefunction, the `simulate` methods can be used as shown below.\n\n\n```\n\"\"\"Simulating a circuit with the `simulate` method.\"\"\"\n# Get a circuit without measurements.\ncircuit = cirq.Circuit(basic_circuit(measure=False))\n\n# Simulate the circuit.\nresult = simulator.simulate(circuit, qubit_order=[a, b])\n\n# Print the final state vector (wavefunction).\nprint(\"State vector:\")\nprint(np.around(result.final_state_vector, 3))\n\n# Print the state vector in Dirac notation.\nprint(\"\\nDirac notation:\")\nprint(result.dirac_notation())\n```\n\n    State vector:\n    [0.5+0.j  0. +0.5j 0. +0.5j 0.5+0.j ]\n    \n    Dirac notation:\n    0.5|00\u27e9 + 0.5j|01\u27e9 + 0.5j|10\u27e9 + 0.5|11\u27e9\n\n\nNotice that we passed a `qubit_order` into the `simulate` method.  This order helps define the order of the kronecker (tensor) product used in the resulting `final_state_vector`.  \n\n> *Note*: The `qubit_order` argument is optional. When it is omitted, qubits are sorted ascending according to the ordering methods defined by their Python class (for example `cirq.NamedQubit` sorts lexicographically by name).\nIf there are multiple types of qubits in one circuit, the name of the type is used as a tie breaker.\n\nThe simplest `qubit_order` value you can provide is a list of the qubits in the desired order. Any qubits from the circuit that are not in the list will be ordered using the  default `__str__` ordering, but come after qubits that are in the list. \n\n> **Note**: Be aware that all qubits in the list are included in the simulation, even if they are not operated on by the circuit.\n\nThe mapping from the order of the qubits to the order of the  amplitudes in the wave function can be tricky to understand.  Basically, it is the same as the ordering used by `numpy.kron`.\n\n> If the state vector is the array \n>> (0.1, 0.2, 0.3, 0.4),\n\n> then this is \n>> 0.1|00\u27e9 + 0.2|01\u27e9 + 0.3|10\u27e9 + 0.4|11\u27e9 \n\n> in Dirac notation. If \n>> qubit order = [a, b]\n\n> then |00> means qubit a is in 0 and qubit b is in 0, |01> means \n> qubit a is 0 and qubit b is 1, etc.\n\nAnother way to think about the qubit-to-amplitude ordering is as \"for loop ordering\":\n\n```\nfor a in [0, 1]:\n    for b in [0, 1]:\n        print(a, b)\n```\n\nThe first index (the outermost loop) is the slowest to vary.\n\n### Repetitions and histograms\n\nAs mentioned, the simulator `run` methods also take an option for repeating the circuit, namely, the `repetitions` argument. If the measurements in the circuit are terminal and all other operations are unitary, this simulator is optimized to not recompute the state vector before sampling from the circuit.\n\n\n```\n\"\"\"Simulate a circuit using 1000 repetitions.\"\"\"\n# Get a circuit with terminal measurements to simulate.\ncircuit = cirq.Circuit(basic_circuit())\n\n# Sample from the circuit 1000 times.\nresult = simulator.run(circuit, repetitions=1000)\n\n# Get a histogram of measurement results.\nprint(result.histogram(key=\"a,b\"))\n```\n\n    Counter({2: 265, 0: 250, 3: 247, 1: 238})\n\n\nHere we have also demonstrated the use of the `histogram` method on the `result` which sums over all the different results for all of the different repetitions.\n\nThe `histogram` method can also be given a `fold_func` argument, in order to group measurement results under some key before counting them up.\nFor example, we can group by whether or not the two measurement results agreed:\n\n\n```\nprint(result.histogram(key=\"a,b\", fold_func=lambda bits: \"agree\" if bits[0] == bits[1] else \"disagree\"))\n```\n\n    Counter({'disagree': 503, 'agree': 497})\n\n\n## The Deutsch-Jozsa Algorithm\n\nThe very first indication that quantum computers could be more powerful than classical computers was provided by David Deutsch in his 1985 paper\n\n> David Deutsch,  \"[Quantum Theory, the Church-Turing Principle and the Universal Quantum Computer](https://people.eecs.berkeley.edu/~christos/classics/Deutsch_quantum_theory.pdf)\" *Proc. R. Soc. Lond.* A **400** 97\u2013117. http://doi.org/10.1098/rspa.1985.0070\n\nThis algorithm was extended by Deutsch and Richard Jozsa to a more convincing algorithmic seperation and what is now called the Deutsch-Jozsa algorithm.  In this section we will show how to write circuits for the Deutsch algorithm and then as an exercise in using Cirq for algorithms for a small version of the Deutsch-Jozsa algorithm.\n\nLet's begin with the Deutsch algorithm.  In Deutsch's algorithm you are given access to a box which computes a one bit boolean function.  That is it is a box which takes in a bit and outputs a bit.  If we want to be a mathematician or theoretical computer scientist we write the function $f$ as $f: \\{0, 1\\} \\rightarrow \\{0, 1\\}$.  There are exactly four such boolean functions which we can write out in a table\n\n| $x$ | $f_0$ | $f_1$ | $f_x$ | $f_{\\bar{x}}$ |\n| --- |  --- | --- | --- | --- |\n| 0 | 0 | 1 | 0 | 1\n| 1 | 0 | 1 | 1 | 0\n\nThe first two of these are *constant* functions, $f_0$ and $f_1$.  That is they always output a constant value (independent of the input).  The other two $f_x$ and $f_\\bar{x}$ are *balanced*.  Over their inputs $0$ and $1$, they have an equal number of $0$s and $1$s in their truth table.  \n\nWe can now state Deutsch's problem:\n\n> Given access to a one bit input one bit output boolean function, determine by querying the function whether the function is *balanced* or *constant*.\n\nIt shouldn't take you much to convince yourself that in order to solve this problem classically you need to call the function on both possible input values.  The easiest way to see this is just to consider what happens if you query the function on one particular input and notice that, for either input, learning the value of the function does not separate the constant from balanced functions. In summary:\n\n*Classically one must query the binary function twice to distinguish the constant function from the balanced function.*\n\nNow lets turn to the quantum approach to this problem.  There is one bit of book keeping we need to take care of.  Above we have described a classical function on bits that is not reversible.  That is, knowing the values of the output does not allow us to determine uniquely the value of the input.  In order to run this on a quantum computer, however we need to make this computation reversible.  A trick for taking a classical non-reversible function and making it \"quantum happy\" is to compute the value in an extra register and store the input.  Suppose we have an $n$ bit input $x$ and we are computing a (potentially non-reverisble) boolean function $f(x)$.  Then we can implement this via a Unitary $U_f$ that acts like on $n + 1$ qubits\n\n$$\nU_f |x\\rangle |y\\rangle = |x\\rangle | y \\oplus f(x)\\rangle .\n$$\n\nHere $\\oplus$ is addition modulo $2$ (XOR) and we have identified how $U_f$ acts by its action on all computational basis states $|x\\rangle$ ($n$ input qubits) and $|y\\rangle$ ($1$ output qubit). To see that this is reversible one can note that applying the transformation twice returns the state to its original form.\n\nLet's see how to implement these functions in Cirq.\n\n$f_0$ enacts the transform\n$$\n\\begin{eqnarray}\n|00\\rangle &\\rightarrow&  |00\\rangle \\\\\n|01\\rangle &\\rightarrow&  |01\\rangle \\\\\n|10\\rangle &\\rightarrow&  |10\\rangle \\\\\n|11\\rangle &\\rightarrow&  |11\\rangle \\\\\n\\end{eqnarray}\n$$\nWell this is just the identity transform, i.e. an empty circuit.\n\n$f_1$ enacts the transform\n$$\n\\begin{eqnarray}\n|00\\rangle &\\rightarrow&  |01\\rangle \\\\\n|01\\rangle &\\rightarrow&  |00\\rangle \\\\\n|10\\rangle &\\rightarrow&  |11\\rangle \\\\\n|11\\rangle &\\rightarrow&  |10\\rangle \\\\\n\\end{eqnarray}\n$$\nThis is the `cirq.X` bit flip gate on the second qubit.\n\n$f_x$ enacts the transform\n$$\n\\begin{eqnarray}\n|00\\rangle &\\rightarrow&  |00\\rangle \\\\\n|01\\rangle &\\rightarrow&  |01\\rangle \\\\\n|10\\rangle &\\rightarrow&  |11\\rangle \\\\\n|11\\rangle &\\rightarrow&  |10\\rangle \\\\\n\\end{eqnarray}\n$$\nThis is nothing more than a `cirq.CNOT` from the first bit to the second bit.\n\nFinally $f_\\bar{x}$ enacts the transform\n$$\n\\begin{eqnarray}\n|00\\rangle &\\rightarrow&  |01\\rangle \\\\\n|01\\rangle &\\rightarrow&  |00\\rangle \\\\\n|10\\rangle &\\rightarrow&  |10\\rangle \\\\\n|11\\rangle &\\rightarrow&  |11\\rangle \\\\\n\\end{eqnarray}\n$$\nwhich is a `cirq.CNOT` from the first bit to the second bit followed by a `cirq.X` on the second bit.\n\nWe can encapulate these functions into a dictionary from a oracle name to the operations in the circuit needed to enact this function.\n\n\n```\n\"\"\"Store the operations to query each function in a dictionary.\"\"\"\n# Get qubits for the operations to act on.\nq0, q1 = cirq.LineQubit.range(2)\n\n# Define the dictionary of operations. The key of each dictionary entry\n# is the subscript of the function f in the above explanatory text.\noracles = {\n    '0': [],\n    '1': [cirq.X(q1)],\n    'x': [cirq.CNOT(q0, q1)],\n    'notx': [cirq.CNOT(q0, q1), cirq.X(q1)]\n}    \n```\n\nWe now turn to Deutsch's algorithm.  Suppose we are given access to the reversible oracle functions we have defined above.  By a similar argument for our irreversible classical functions you can show that you cannot distinguish the balanced from the constant functions by using this oracle only once.  But now we can ask the question: what if we are allowed to query this box in superposition, i.e. what if we can use the power of quantum computing?\n\nDeutsch was able to show that you could solve this problem now, with quantum computers, using only a single query.  To see how this works we need two simple insights.\n\nSuppose that we prepare the second qubit in the superposition state $|-\\rangle=\\frac{1}{\\sqrt{2}}(|0\\rangle-|1\\rangle)$ and apply the oracle.  Then we can check that\n$$ \nU_f |x\\rangle |-\\rangle = U_f|x\\rangle \\frac{1}{\\sqrt{2}}(|0\\rangle -|1\\rangle ) = |x\\rangle \\frac{1}{\\sqrt{2}}(|f(x)\\rangle -|f(x) \\oplus 1\\rangle ) =  (-1)^{f(x)} |x\\rangle |-\\rangle .\n$$  \nThis is the so called \"phase kickback trick\".  By applying $U_f$ onto a target which is in superposition, the value of the function ends up showing up in the global phase.  \n\nHow can we leverage this to distinguish between the constant and balanced functions?  Note that for the constant functions the phase that is applied is the same for all inputs $|x\\rangle$, whereas for the balanced functions the phase is different for each value of $x$.  In other words, if we use the phase kickback trick then for each of the oracles we apply the following transform on the first qubit:\n\n$$\n\\begin{eqnarray}\nf_0 \\rightarrow I, &&\nf_1 \\rightarrow -I, &&\nf_x \\rightarrow Z, &&\nf_\\bar{x} \\rightarrow -Z &&\n\\end{eqnarray}\n$$\n\nNow we only need, on the first qubit, to distinguish between the identity gate and the $Z$ gate.  But we can do this by recalling the identity\n\n$$ \nH Z H = X\n$$\n\nwhere $H$ is the Hamadard gate.\n\nThis means that we can turn a phase flip into a bit flip by applying Hadamards before and after the phase flip.  If we look at the constant and balanced functions we see that this means that the constant functions will be proportional to $I$ and the balanced functions will be proportional to $X$.  If we feed in $|0\\rangle$ to this register, then in the first cases we will only see $|0\\rangle$ and in the second case we will only see $|1\\rangle$.  In other words we will be able to distinguish constant from balanced using a single query of the oracle.\n\nLet's code this up.\n\n\n```\n\"\"\"Creating the circuit used in Deutsch's algorithm.\"\"\"\ndef deutsch_algorithm(oracle):\n    \"\"\"Returns the circuit for Deutsch's algorithm given an input\n    oracle, i.e., a sequence of operations to query a particular function.\n    \"\"\"\n    yield cirq.X(q1)\n    yield cirq.H(q0), cirq.H(q1)\n    yield oracle\n    yield cirq.H(q0)\n    yield cirq.measure(q0)\n\nfor key, oracle in oracles.items():\n    print(f\"Circuit for f_{key}:\")\n    print(cirq.Circuit(deutsch_algorithm(oracle)), end=\"\\n\\n\")\n```\n\n    Circuit for f_0:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\n    \n    1: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    Circuit for f_1:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\n    \n    1: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\n    \n    Circuit for f_x:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\n                  \u2502\n    1: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    Circuit for f_notx:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\n                  \u2502\n    1: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n\n\nLets run these circuits a bunch of times to see that the measurement result ends up correctly distinguishing constant from balanced.\n\n\n```\n\"\"\"Simulate each of the circuits.\"\"\"\nsimulator = cirq.Simulator()\nfor key, oracle in oracles.items():\n    result = simulator.run(cirq.Circuit(deutsch_algorithm(oracle)), \n                          repetitions=10)\n    print('oracle: f_{:<4} results: {}'.format(key, result))\n```\n\n    oracle: f_0    results: 0=0000000000\n    oracle: f_1    results: 0=0000000000\n    oracle: f_x    results: 0=1111111111\n    oracle: f_notx results: 0=1111111111\n\n\nWe interpret the simulation results as follows:\n\n- For the first two functions $f_0$ and $f_1$, we always measure $0$. Therefore, we know that these functions are constant.\n- For the second two functions $f_x$ and $f_{\\bar{x}}$, we always measure $1$. Therefore, we know that these functions are balanced.\n\n### Exercise: Two Bit Deutsch-Jozsa Algorithm\n\nAll boolean functions for one input bit are either constant or balanced.  For boolean functions from two input bits not all functions are constant or balanced.  There are two constant functions, $f(x_0, x_1) = 0$ and $f(x_0, x_1)=1$, while there are ${4 \\choose 2} = 6$ balanced functions.  The following code gives you the operations for these functions where we take two input qubits and compute the function in the third qubit.\n\n\n```\n\"\"\"Operations to query all possible functions on two bits.\nTwo of these functions are constant, and six of these functions are balanced.\n\"\"\"\n# Define three qubits to use.\nq0, q1, q2 = cirq.LineQubit.range(3)\n\n# Define the operations to query each of the two constant functions.\nconstant = (\n    [], \n    [cirq.X(q2)]\n)\n\n# Define the operations to query each of the six balanced functions.\nbalanced = (\n    [cirq.CNOT(q0, q2)], \n    [cirq.CNOT(q1, q2)], \n    [cirq.CNOT(q0, q2), cirq.CNOT(q1, q2)],\n    [cirq.CNOT(q0, q2), cirq.X(q2)], \n    [cirq.CNOT(q1, q2), cirq.X(q2)], \n    [cirq.CNOT(q0, q2), cirq.CNOT(q1, q2), cirq.X(q2)]\n)\n```\n\nAn extension of Deutsch's orginal algorithm is the Deutsch-Jozsa algorithm, which can distinguish constant from balanced functions like these using a single query to the oracle.  **The goal of this exercise** is to write a quantum circuit that can distinguish these.\n\n\n```\n#@title Attempt the solution here\n\"\"\"Exercise: Write a quantum circuit that can distinguish \nconstant from balanced functions on two bits.\n\"\"\"\ndef your_circuit(oracle):\n    # Your code here!\n    yield oracle\n    # Your code here!\n    yield cirq.measure(q2)\n```\n\nYou can check your circuit by running the follow cell which simulates the circuit for all oracles.\n\n\n```\n\"\"\"Check your answer by running this cell.\"\"\"\nsimulator = cirq.Simulator()\n    \nprint(\"\\nYour result on constant functions:\")\nfor oracle in constant:\n    result = simulator.run(cirq.Circuit(your_circuit(oracle)), repetitions=10)\n    print(result)\n    \nprint(\"\\nYour result on balanced functions:\")\nfor oracle in balanced:\n    result = simulator.run(cirq.Circuit(your_circuit(oracle)), repetitions=10)\n    print(result)\n```\n\n    \n    Your result on constant functions:\n    2=0000000000\n    2=1111111111\n    \n    Your result on balanced functions:\n    2=0000000000\n    2=0000000000\n    2=0000000000\n    2=1111111111\n    2=1111111111\n    2=1111111111\n\n\n\n```\n#@title Expand to view the solution\ndef dj_circuit(oracle):\n    # Phase kickback trick.\n    yield cirq.X(q2), cirq.H(q2)\n    \n    # Get an equal superposition over input bits.\n    yield cirq.H(q0), cirq.H(q1)\n    \n    # Query the function.\n    yield oracle\n    \n    # Use interference to get result, put last qubit into |1>.\n    yield cirq.H(q0), cirq.H(q1), cirq.H(q2)\n    \n    # Use a final OR gate to put result in final qubit.\n    yield cirq.X(q0), cirq.X(q1), cirq.CCX(q0, q1, q2)\n    yield cirq.measure(q2)\n```\n\nAs above, we can check the solution by running the circuit with each of the oracles.\n\n\n```\n\"\"\"Simulate the Deutsch-Jozsa circuit and check the results.\"\"\"\nprint(\"Result on constant functions:\")\nfor oracle in constant:\n    result = simulator.run(cirq.Circuit(dj_circuit(oracle)), repetitions=10)\n    print(result)\n    \nprint(\"\\nResult on balanced functions:\")\nfor oracle in balanced:\n    result = simulator.run(cirq.Circuit(dj_circuit(oracle)), repetitions=10)\n    print(result)\n```\n\n    Result on constant functions:\n    2=0000000000\n    2=0000000000\n    \n    Result on balanced functions:\n    2=1111111111\n    2=1111111111\n    2=1111111111\n    2=1111111111\n    2=1111111111\n    2=1111111111\n\n\nAs with the single-bit case (Deutsch's algorithm), we always measure $0$ for constant functions and always measure $1$ for balanced functions.\n\n## Gates\n\nCirq comes with a plethora of common quantum gates.  Here we show a few of them.\n\n\n```\n\"\"\"Examples of common gates defined in Cirq.\"\"\"\n# Get some qubits.\nq0, q1, q2 = cirq.LineQubit.range(3)\n\n# Get a bunch of common gates defined in Cirq.\nops = [\n    cirq.X(q0),                     # Pauli-X.\n    cirq.Y(q1),                     # Pauli-Y.\n    cirq.Z(q2),                     # Pauli-Z.\n    cirq.CZ(q0,q1),                 # Controlled-Z gate.\n    cirq.CNOT(q1,q2),               # Controlled-X gate.\n    cirq.H(q0),                     # Hadamard gate.\n    cirq.T(q1),                     # T gate.\n    cirq.S(q2),                     # S gate.\n    cirq.CCZ(q0, q1, q2),           # Controlled CZ gate.\n    cirq.SWAP(q0, q1),              # Swap gate.\n    cirq.CSWAP(q0, q1, q2),         # Controlled swap gate.\n    cirq.CCX(q0, q1, q2),           # Toffoli (CCNOT) gate.\n    cirq.ISWAP(q0, q1),             # ISWAP gate.\n    cirq.Rx(rads=0.5 * np.pi)(q0),  # Rotation about X.\n    cirq.Ry(rads=0.5 * np.pi)(q1),  # Rotation about Y.\n    cirq.Rz(rads=0.5 * np.pi)(q2),  # Rotation about Z.\n    cirq.X(q0) ** 0.5,              # Sqrt of NOT gate.\n]\n\n# Display a circuit with all of these operations.\nprint(cirq.Circuit(ops))\n```\n\n    0: \u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u00d7\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500Rx(0.5\u03c0)\u2500\u2500\u2500X^0.5\u2500\u2500\u2500\n              \u2502           \u2502   \u2502   \u2502   \u2502   \u2502\n    1: \u2500\u2500\u2500Y\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500T\u2500\u2500\u2500@\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u00d7\u2500\u2500\u2500@\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500Ry(0.5\u03c0)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502       \u2502       \u2502   \u2502\n    2: \u2500\u2500\u2500Z\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500S\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00d7\u2500\u2500\u2500X\u2500\u2500\u2500Rz(0.5\u03c0)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\nFor each of these gates, you can figure out how they act on the computational basis by calling `cirq.unitary` on the gate.  For example, to see the unitary of `CNOT`, we can do:\n\n\n```\n\"\"\"Get the unitary of CNOT.\"\"\"\nprint(cirq.unitary(cirq.CNOT))\n```\n\n    [[1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 1.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 1.+0.j]\n     [0.+0.j 0.+0.j 1.+0.j 0.+0.j]]\n\n\nFor single qubit gates, we have named gates like `cirq.H` for the Hadmard gate as well as the single qubit rotation gates defined as follows.\n\n$$ \n{\\tt cirq.Rx(\\theta)}: \\exp(-i \\frac{\\theta}{2} X) = cos \\frac{\\theta}{2} I - i \\sin \\frac{\\theta}{2} X =\\left[ \\begin{array} ~\\cos \\frac{\\theta}{2} & -i \\sin \\frac{\\theta}{2} \\\\ -i \\sin \\frac{\\theta}{2} & \\cos \\frac{\\theta}{2}\\end{array} \\right] \\\\\n$$ \n$$ \n{\\tt cirq.Ry(\\theta)}: \\exp(-i \\frac{\\theta}{2} Y) = cos \\frac{\\theta}{2} I - i \\sin \\frac{\\theta}{2} Y =\\left[ \\begin{array} ~\\cos \\frac{\\theta}{2} &  -\\sin \\frac{\\theta}{2} \\\\  \\sin \\frac{\\theta}{2} & \\cos \\frac{\\theta}{2}\\end{array} \\right] \\\\\n$$ \n$$ \n{\\tt cirq.Rz(\\theta)}: \\exp(-i \\frac{\\theta}{2} Z) = cos \\frac{\\theta}{2} I - i \\sin \\frac{\\theta}{2} Z =\\left[ \\begin{array} ~e^{i \\frac{\\theta}{2}} & 0 \\\\ 0 & e^{-i \\frac{\\theta}{2}} \\end{array} \\right] \\\\\n$$ \n\nIn addition to `cirq.unitary` another important method (behind the scenes, anyways) is `cirq.apply_unitary`.  This allows you to apply a unitary gate onto a state.  Of course we could have applied the unitary directly to the state, using `cirq.unitary`.   We'll see below in understanding how these methods are implemented that the `cirq.apply_unitary` can be used to apply the gate more directly onto the state and can save allocations of memory to store the unitary.  \n\nIf we apply `cirq.Rx` to a state we can see how it rotates the state.  To do this let us introduce a new simulate method `simulate_moment_steps`.  This allows us to simulate the circuit `Moment` by `Moment`.  At each point we can access the state.  For example here we can use this to create a circuit that is a series of small `cirq.Rx` rotations and plot the probability of measuring the state in the $|0\\rangle$ state:\n\n\n```\n\"\"\"Plot the probability of measuring a qubit in the ground state.\"\"\"\n# Get a qubit.\na = cirq.NamedQubit('a')\n\n# Get a circuit of a bunch of X rotations.\nnum_angles = 200\ncircuit = cirq.Circuit([cirq.Rx(rads=np.pi / 50.0)(a) for theta in range(num_angles)])\n\n# List to store probabilities of the ground state.\nprobs = []\n\n# Step through the simulation results.\nfor step in simulator.simulate_moment_steps(circuit):\n    prob = np.abs(step.state_vector()) ** 2\n    probs.append(prob[0])\n\n# Plot the probability of the ground state at each simulation step.\nplt.style.use('seaborn-whitegrid')\nplt.plot(probs, 'o')\nplt.xlabel(\"Step\")\nplt.ylabel(\"Probability of ground state\");\n```\n\nAbove we have given ourselves direct access to the wave function and calculated the exact probabilities.  Suppose we wanted to sample from the wave function at each point instead.  \n\n\n```\n\"\"\"Plot the probability of measuring a qubit in the ground state by sampling.\"\"\"\n# Number of times to sample.\nrepetitions = 100\n\n# List to store the probability of the ground state.\nsampled_probs = []\n\nfor i, step in enumerate(simulator.simulate_moment_steps(circuit)):\n    samples = step.sample([a], repetitions=repetitions)\n    prob = np.sum(samples, axis=0)[0] / repetitions\n    sampled_probs.append(prob)\n    \n\n# Plot the probability of the ground state at each simulation step.\nplt.style.use('seaborn-whitegrid')\nplt.plot(sampled_probs, 'o')\nplt.xlabel(\"Step\")\nplt.ylabel(\"Probability of ground state\");\n```\n\n## Custom gates\n\nSuppose there is a gate that you want Cirq to support, but it is not implemented in Cirq.  How do you go about defining your new gate?  \n\nCirq aims to be Pythonic.  One way in which it does this is that it relies on Python's **protocol** pattern.  Protocols are similar to interfaces, in that they define a collection of methods that an object must support to implement a protocol, but different in that this requirement is more informal and not a part of a class or interface declaration.  An object supports a protocol if it implements the methods that the protocol defines.  You're probably familiar with this if you've ever done something like defined your own `Container` in Python.  To do this for an object you simply define the `__contains__`, `__setitem__`, and `__getitem__` methods on your object, and then you can use this object anywere the Container protocol is supported.  \n\nLet's see how this works for defining a custom gate.  The gate we will define is a single qubit gate that has only rational amplitudes. This is based on the famous 3, 4, 5 triangle you may remember from a long ago math class: $3^2 + 4^2 = 5^2$.  Using this observation we can construct normalized vectors and a unitary transform using the ratios of $3$, $4$, and $5$: \n$$\n\\zeta =\\left[ \\begin{array}\n~\\frac{3}{5} & \\frac{4}{5} \\\\\n-\\frac{4}{5} & \\frac{3}{5}\n\\end{array} \\right]\n$$\n\nBelow is a simple implementation of this gate in Cirq.  To do this we simply define a class that inherits from `cirq.SingleQubitGate` and implements the `cirq.SupportsUnitary` protocol by implementing the `_unitary_(self)` method.  We also define an optional `__str__` representation which Cirq will use when printing this gate out in a circuit diagram.\n\n\n```\n\"\"\"Example of defining a custom gate in Cirq.\"\"\"\nclass RationalGate(cirq.SingleQubitGate):\n    \n    def _unitary_(self):\n        return np.array([[3 / 5, 4 / 5], [-4 / 5, 3 / 5]])\n    \n    def __str__(self):\n        return '\u03b6'\n```\n\nWe can now use this custom gate just like any other gate in Cirq.\n\n\n```\n\"\"\"Using the custom gate in a circuit.\"\"\"\na = cirq.NamedQubit('a')\nrg = RationalGate()\nprint(cirq.Circuit(rg(a)))\n```\n\n    a: \u2500\u2500\u2500\u03b6\u2500\u2500\u2500\n\n\nWe can also get its unitary, as shown below, because the `RationalGate` defines a `_unitary_` method.\n\n\n```\nprint(cirq.unitary(rg))\n```\n\n    [[ 0.6  0.8]\n     [-0.8  0.6]]\n\n\nLet's check that we can use this gate in a simulation.\n\n\n```\n\"\"\"Simulate a circuit with a custom gate.\"\"\"\ncircuit = cirq.Circuit(rg(a))\nsimulator = cirq.Simulator()\nresult = simulator.simulate(circuit)\nprint(result.final_state_vector)\n```\n\n    [ 0.6+0.j -0.8+0.j]\n\n\n> *Note on simulating circuits with custom gates.* The `_unitary_` method is extremely inefficient for gates over many qubits. In most cases the method `_apply_unitary_` will be used instead, if it is available.\nThis method allows much more fine grained control on how a unitary is applied to a state, but it is harder to implement, for example because it is expected to use the pre-allocated workspace buffer that was given to it.\nAlmost all of the basic gates we have defined in Cirq have this method implemented. If you need to get performant, custom multi-qubit gates, you should implement a custom `_apply_unitary_` method for such gates.\n\n### Exercise: Custom Controlled Rx gate\n\nRecall that the `cirq.Rx` gate is a rotation about the $X$ Pauli axis:\n$$ \n{\\tt cirq.Rx(\u03b8)}: \\exp(-i \\frac{\\theta}{2} X) = cos \\frac{\\theta}{2} I - i \\sin \\frac{\\theta}{2} X =\\left[ \\begin{array} ~\\cos \\frac{\\theta}{2} & -i \\sin \\frac{\\theta}{2} \\\\ -i \\sin \\frac{\\theta}{2} & \\cos \\frac{\\theta}{2}\\end{array} \\right] . \\\\\n$$ \n\nAs an exercise, create a two-qubit controlled `cirq.Rx` gate defined as follows:\n$$\n{\\tt CRx(\\theta)}:\n\\left[\\begin{array}\n~1 & 0 & 0 & 0 \\\\\n0 & 1 & 0 & 0  \\\\\n0 & 0 & \\cos \\frac{\\theta}{2} & -i \\sin \\frac{\\theta}{2} \\\\\n0 & 0 & -i \\sin \\frac{\\theta}{2} & \\cos \\frac{\\theta}{2}\n\\end{array} \\right] .\n$$\n\n\n```\n#@title Attempt the solution here\n\"\"\"Define a custom controlled cirq.rx gate here.\"\"\"\nclass CRx(cirq.TwoQubitGate):\n    def __init__(self, theta):\n        self.theta = theta\n\n    def _unitary_(self):\n        return np.array([\n            # Your code here!\n        ])\n\n\n# Print out its unitary.\nprint(np.around(cirq.unitary(CRx(0.5 * np.pi)), 3))     \n```\n\n    []\n\n\n\n```\n#@title Expand to view the solution\n\"\"\"Defining a custom controlled cirq.Rx gate.\"\"\"\nclass CRx(cirq.TwoQubitGate):\n    def __init__(self, theta):\n        self.theta = theta\n\n    def _unitary_(self):\n        return np.array([\n            [1, 0, 0, 0],\n            [0, 1, 0, 0],\n            [0, 0, np.cos(self.theta/2), -1j * np.sin(self.theta/2)],\n            [0, 0, -1j * np.sin(self.theta/2), np.cos(self.theta/2)]\n        ])\n    \n    def _circuit_diagram_info_(self, args):\n        return '@', 'Rx({}\u03c0)'.format(self.theta / np.pi)\n\n\n# Print out its unitary.\nprint(np.around(cirq.unitary(CRx(0.5 * np.pi)), 3))    \n```\n\n    [[1.   +0.j    0.   +0.j    0.   +0.j    0.   +0.j   ]\n     [0.   +0.j    1.   +0.j    0.   +0.j    0.   +0.j   ]\n     [0.   +0.j    0.   +0.j    0.707+0.j    0.   -0.707j]\n     [0.   +0.j    0.   +0.j    0.   -0.707j 0.707+0.j   ]]\n\n\nNote that we also define the `_circuit_diagram_info_` method which tells Cirq how to display the gate in a circuit diagram. The first string in the tuple is the symbol for the top wire, and the second string in the tuple is the symbol for the bottom wire. We can use this in a circuit to see the diagram info as shown below.\n\n\n```\n\"\"\"Display a circuit with the custom gate.\"\"\"\n# Get qubits.\na = cirq.NamedQubit('a')\nb = cirq.NamedQubit('b')\n\n# Display the circuit.\nprint('Circuit diagram:')\nprint(cirq.Circuit(CRx(0.25 * np.pi)(a, b)))\n```\n\n    Circuit diagram:\n    a: \u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n          \u2502\n    b: \u2500\u2500\u2500Rx(0.25\u03c0)\u2500\u2500\u2500\n\n\n### Gate decompositions\n\nIn many contexts, the notion of what gate you can apply is defined either by the physical hardware you are running or perhaps by the quantum error correcting code you are working with.  In quantum computing we typically talk about **gate sets** and work with respect to a given gate set.  Cirq supports gate decomposition via the `decompose` protocol.  Below we show how one can construct a gate that can be decomposed into two gates.\n\n\n```\n\"\"\"Example of a custom gate which supports the decompose protocol.\"\"\"\nclass HXGate(cirq.SingleQubitGate):\n    \n    def _decompose_(self, qubits):\n        return cirq.H(*qubits), cirq.X(*qubits)\n    \n    def __str__(self):\n        return 'HX'\n```\n\nWe can use this gate in a circuit as follows.\n\n\n```\n\"\"\"Use the gate in a circuit.\"\"\"\nHX = HXGate()\n\na = cirq.NamedQubit('a')\ncircuit = cirq.Circuit(HX(a))\nprint(circuit)\n```\n\n    a: \u2500\u2500\u2500HX\u2500\u2500\u2500\n\n\nThe symbol `HX` is a single gate, not a product of two gates. We can decompose the `HXGate` using `cirq.decompose` as shown below.\n\n\n```\n\"\"\"Decompose the gate.\"\"\"\nprint(cirq.Circuit(cirq.decompose(circuit)))\n```\n\n    a: \u2500\u2500\u2500Y^0.5\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\n\n\nNote that this not only decomposed the `HX` gate into `H` and `X`, it also decomposed `H` into `Y**0.5` and `X`.  In order to decompose only once, one can use `cirq.decompose_once`:\n\n\n```\n\"\"\"Decompose the gate once.\"\"\"\nprint(cirq.Circuit(cirq.decompose_once(HX(a))))\n```\n\n    a: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\n\n\nWhen we define a gate, it is good practice to give a default decomposition in terms of common gates.  However, often you will want to change this decomposition at run time for the specific hardware or context you are working in.  To do this we can define an interceptor function which does this decomposition before falling back to the default.\n\n\n```\n\"\"\"Define a custom decomposer.\"\"\"\ndef my_decompose(op):\n    if isinstance(op, cirq.GateOperation) and isinstance(op.gate, HXGate):\n        return cirq.Z(*op.qubits), cirq.H(*op.qubits)\n\n# Decompose the circuit according to this custom decomposer.\ncirq.Circuit(cirq.decompose(HX(a), intercepting_decomposer=my_decompose))\n```\n\n\n\n\n<pre style=\"overflow: auto; white-space: pre;\">a: \u2500\u2500\u2500Z\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500X\u2500\u2500\u2500</pre>\n\n\n\nYou can also define a predicate that says which gates to keep without decomposing further. This predicate should return `True` for all gates that should not be decomposed further, and `False` for all gates that should be decomposed further.\n\n> The default predicate is to only keep gates that cannot be decomposed.\n\n\n```\n\"\"\"Define a predicate of which gates to keep without decomposing.\"\"\"\ndef keep_h_and_x(op):\n    return isinstance(op, cirq.GateOperation) and op.gate in [cirq.H, cirq.X]\n\n\n# Decompose the HXGate using a custom predicate for which gates to not decompose.\nprint(cirq.decompose(HX(a), keep=keep_h_and_x))\n```\n\n    [cirq.H(cirq.NamedQubit('a')), cirq.X(cirq.NamedQubit('a'))]\n\n\nIn this case, we see that neither `H` nor `X` have been decomposed, as we have specified in `keep_h_and_x`.\n\n## Parameterized Circuits\n\nIn addition to circuit gates with fixed values, Cirq also supports parameterized gates with symbolic values via `sympy`. These are placeholder values, such as `sympy.Symbol('x')`, that will only be resolved at *run-time*. For simulators these values are resolved by providing a `ParamResolver`.  A `ParamResolver` provides a map from the `Symbol`'s name to its assigned value.  \n\n> Plain Python dictionaries can also be used whenever a `ParamResolver` is needed.\n\n\n```\n\"\"\"Define a circuit with parameterized gates.\"\"\"\n# Import sympy for parameterized values.\nimport sympy as sp\n\n# Get qubits to use in the circuit.\na = cirq.NamedQubit(\"a\")\nb = cirq.NamedQubit(\"b\")\n\n# Define a parameterized value.\nval = sp.Symbol(\"s\")\n\n# Create a circuit.\ncircuit = cirq.Circuit(cirq.X.on(a) ** val, cirq.X.on(b) ** val)\n\n# Display it.\nprint(\"Circuit with parameterized gates:\\n\")\nprint(circuit)\n```\n\n    Circuit with parameterized gates:\n    \n    a: \u2500\u2500\u2500X^s\u2500\u2500\u2500\n    \n    b: \u2500\u2500\u2500X^s\u2500\u2500\u2500\n\n\nWhen we simulate this circuit, we must provide a `param_resolver` as mentioned.\n\n\n```\n\"\"\"Simulate the circuit at multiple parameter values.\"\"\"\nsimulator = cirq.Simulator()\n\n# Simulate the circuit for several values of the parameter.\nnum_params = 5\nfor y in range(num_params):\n    result = simulator.simulate(circuit, param_resolver={\"s\": y / 4.0})\n    print(\"s={}: {}\\n\".format(y, np.around(result.final_state_vector, 2)))\n```\n\n    s=0: [1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n    \n    s=1: [ 0.6 +0.6j   0.25-0.25j  0.25-0.25j -0.1 -0.1j ]\n    \n    s=2: [0. +0.5j 0.5+0.j  0.5+0.j  0. -0.5j]\n    \n    s=3: [-0.1 +0.1j   0.25+0.25j  0.25+0.25j  0.6 -0.6j ]\n    \n    s=4: [0.+0.j 0.+0.j 0.+0.j 1.+0.j]\n    \n\n\nHere we see that the `Symbol` is used in two gates, and then the resolver provides this value at run time.\n\nParameterized values are most useful in defining what we call a `cirq.Sweep`.  A `cirq.Sweep` is a collection of parameter resolvers. Our `cirq.Simulator` and `cirq.Sampler` (for real devices) interfaces support parameter sweeps. The `run_sweep` method allows the user to a parameterized circuit with each of the configurations. Within each run, the user might specify the number of repetitions as well which determines the sample size for each run.  Running parameter sweeps returns a list of `cirq.Result`s, one per set of fixed parameter values and repetitions. Example:\n\n\n\n```\n\"\"\"Simulate the circuit at multiple parameter values.\"\"\"\n# Get a list of param resolvers.\nnum_params = 5\nresolvers = [cirq.ParamResolver({'s': y / 8.0}) for y in range(num_params)]\n\n# Add measurements to the circuit.\ncircuit.append([cirq.measure(a), cirq.measure(b)])\n\n# Simulate the circuit using run_sweep.\nresults = simulator.run_sweep(\n    program=circuit,\n    params=resolvers,\n    repetitions=10\n)\n\nfor i, result in enumerate(results):\n    print('params: {}\\n{}\\n'.format(result.params.param_dict, result))\n```\n\n    params: OrderedDict([('s', 0.0)])\n    a=0000000000\n    b=0000000000\n    \n    params: OrderedDict([('s', 0.125)])\n    a=0000000000\n    b=1000000000\n    \n    params: OrderedDict([('s', 0.25)])\n    a=0000000000\n    b=1000101001\n    \n    params: OrderedDict([('s', 0.375)])\n    a=0000000100\n    b=0000000101\n    \n    params: OrderedDict([('s', 0.5)])\n    a=1010111000\n    b=1011010110\n    \n\n\nA very similar method to `run_sweep` is the `sample` method. This returns a pandas `DataFrame`, where each column is a parameter/measurement key and each row is a repetition.\n\n\n\n```\nresults = simulator.sample(\n    program=circuit,\n    params=resolvers,\n    repetitions=10\n)\n\nresults.describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>s</th>\n      <th>a</th>\n      <th>b</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>50.000000</td>\n      <td>50.000000</td>\n      <td>50.000000</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>0.250000</td>\n      <td>0.200000</td>\n      <td>0.260000</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>0.178571</td>\n      <td>0.404061</td>\n      <td>0.443087</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>0.125000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>0.250000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>0.375000</td>\n      <td>0.000000</td>\n      <td>0.750000</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>0.500000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nAbove we passed in a list of `ParamResolver`s to the `params` parameter of `run_sweep` and `sample`.  But one can also pass in a `Sweepable`.  There are some useful methods for generating `Sweepable`s, for example to generate an equally spaced set of `ParamResolver`s one can use `Linspace`\n\n\n\n```\n\"\"\"Alternative method of getting a sequence of param resolvers.\"\"\"\nlinspace = cirq.Linspace(start=0, stop=1.0, length=11, key='x')\nfor p in linspace:\n    print(p)\n```\n\n    cirq.ParamResolver({'x': 0.0})\n    cirq.ParamResolver({'x': 0.1})\n    cirq.ParamResolver({'x': 0.2})\n    cirq.ParamResolver({'x': 0.3})\n    cirq.ParamResolver({'x': 0.4})\n    cirq.ParamResolver({'x': 0.5})\n    cirq.ParamResolver({'x': 0.6})\n    cirq.ParamResolver({'x': 0.7})\n    cirq.ParamResolver({'x': 0.8})\n    cirq.ParamResolver({'x': 0.9})\n    cirq.ParamResolver({'x': 1.0})\n\n\n### Exercise: Rotate a qubit\n\nLet's do the equivalent of a Rabi-flop experiment.  That is, let's apply a `XPowGate` rotating about the `X` axis for a linearly spaced set of values followed by a computational basis measurement.  The end result should be a plot of the sampled fraction that were $|1\\rangle$ as a function of gates of $X^t$ for $t$ between 0 and $1$ for 100 values of $t$ and each result sampled 100 times.\n\n\n```\n#@title Attempt the solution here\nimport pandas\nq = cirq.NamedQubit(\"q\")\ntheta = sp.Symbol(\"theta\")\nparameterized_circuit = cirq.Circuit(\n    # your code here\n    cirq.measure(q)\n)\n# replace None with something else\nparam_resolvers = None\nrepetitions = 100\nresults = cirq.Simulator().sample(\n    program=parameterized_circuit,\n    params=param_resolvers,\n    repetitions=repetitions\n)\n\n# You can test with the following plot\n# pandas.crosstab(results.theta, results.q).plot()\n```\n\n\n```\n#@title Expand to view the solution\nimport pandas\nq = cirq.NamedQubit(\"q\")\nparameterized_circuit = cirq.Circuit([cirq.Rx(rads=sp.Symbol(\"theta\"))(q), cirq.measure(q)])\nparam_resolvers = cirq.Linspace(start=0, stop=np.pi, length=100, key='theta')\nresults = cirq.Simulator().sample(\n    program=parameterized_circuit,\n    params=param_resolvers,\n    repetitions=repetitions\n)\npandas.crosstab(results.theta, results.q).plot()\n```\n\n## Noise\n\nIn addition to circuits with unitary gates, Cirq also has support for modeling noisy quantum evolutions. This is useful when modeling what will happen when running on actual hardware.\n\nCirq currently supports noise that fits within the context of *operator sum representations* of noise (a.k.a quantum operations, quantum dyanamical maps, superoperators, etc).  This formalism models the evolution of a density matrix via \n\n$$ \n\\rho \\rightarrow \\sum_k A_k \\rho A_k^\\dagger \n$$\n\nwhere the $A_k$ are *Kraus operators*.  These operators are not necessarily unitary and satisfy the property\n\n$$ \n\\sum_k A_k^\\dagger A_k = I . \n$$\n\nAn example of a noise operator is the depolarizing channel on one qubit.  This takes\n\n$$\n\\rho \\rightarrow (1-p) \\rho + \\frac{p}{3} (X \\rho X + Y \\rho Y + Z \\rho Z) .\n$$\n\nIn Cirq we can define such a channel and use it in a quantum circuit:\n\n\n```\n\"\"\"Create a circuit with a depolarizing channel.\"\"\"\ncircuit = cirq.Circuit(cirq.depolarize(0.2)(a), cirq.measure(a))\nprint(circuit)\n```\n\n    a: \u2500\u2500\u2500D(0.2)\u2500\u2500\u2500M\u2500\u2500\u2500\n\n\nPreviously we saw that gates could implement that `_unitary_` protocol, and by doing so they could be used to perform wave function simulation.  For noise the gates implement the `_kraus_` protocol.  Classes that implement this protocol return the Krauss operators on their `_kraus_` method.  Thus\n\n\n```\nfor i, kraus in enumerate(cirq.kraus(cirq.depolarize(0.2))):\n    print(f\"Kraus operator {i} is:\", kraus, sep=\"\\n\", end=\"\\n\\n\")\n```\n\n    Kraus operator 0 is:\n    [[0.89442719 0.        ]\n     [0.         0.89442719]]\n    \n    Kraus operator 1 is:\n    [[0.        +0.j 0.25819889+0.j]\n     [0.25819889+0.j 0.        +0.j]]\n    \n    Kraus operator 2 is:\n    [[0.+0.j         0.-0.25819889j]\n     [0.+0.25819889j 0.+0.j        ]]\n    \n    Kraus operator 3 is:\n    [[ 0.25819889+0.j  0.        +0.j]\n     [ 0.        +0.j -0.25819889+0.j]]\n    \n\n\nThe Kraus operators are often more conveniently represented in a Pauli basis. We can do this in Cirq as shown below.\n\n\n```\nfor i, kraus in enumerate(cirq.kraus(cirq.depolarize(0.2))):\n    pauli_ex = cirq.expand_matrix_in_orthogonal_basis(kraus, cirq.PAULI_BASIS)\n    print(f\"Kraus operator {i} is:\", pauli_ex, sep=\"\\n\", end=\"\\n\\n\")\n```\n\n    Kraus operator 0 is:\n    0.894*I\n    \n    Kraus operator 1 is:\n    0.258*X\n    \n    Kraus operator 2 is:\n    0.258*Y\n    \n    Kraus operator 3 is:\n    0.258*Z\n    \n\n\nIn addition to the wavefunction simulator, Cirq also has a density matrix simulator.  Instead of keeping track of the wavefunction, this simulator keeps track of the density matrix.  It has the same `run` and `simulate` type methods.  For example we can use this to simulate depolarizing channel and return the final density matrix of the system.\n\n\n```\n\"\"\"Example of simulating a noisy circuit with the density matrix simulator.\"\"\"\n# Circuit to simulate.\ncircuit = cirq.Circuit(cirq.depolarize(0.2)(a))\nprint('Circuit:\\n{}\\n'.format(circuit))\n\n# Get the density matrix simulator.\nsimulator = cirq.DensityMatrixSimulator()\n\n# Simulate the circuit and get the final density matrix.\nmatrix = simulator.simulate(circuit).final_density_matrix\nprint('Final density matrix:\\n{}'.format(matrix))\n```\n\n    Circuit:\n    a: \u2500\u2500\u2500D(0.2)\u2500\u2500\u2500\n    \n    Final density matrix:\n    [[0.8666666 +0.j 0.        +0.j]\n     [0.        +0.j 0.13333333+0.j]]\n\n\nOne thing to note is that the density matrix simulator simulates measurement statistically, and not as a channel where the outcome is not known. Consider the following example.\n\n\n```\n\"\"\"Simulating a circuit with measurements using the DensityMatrixSimulator.\"\"\"\n# Get a circuit with measurements.\ncircuit = cirq.Circuit(cirq.depolarize(0.5)(a), cirq.measure(a))\n\n# Simulate with the density matrix multiple times.\ndmat1 = simulator.simulate(circuit).final_density_matrix\ndmat2 = simulator.simulate(circuit).final_density_matrix\n\nprint(np.allclose(dmat1, dmat2))\n```\n\n    True\n\n\nBecause the final density matrix is statistical due to the measurements, the output of the above cell will change when executed multiple times.\n\n### Monte carlo simulations\n\nDensity matrix simulations are more expensive than pure state wave function simulations.  However some channels allow an interpreation of randomly applying one of a fixed set of unitaries with differing probabilites.  For example the depolarizing channel above can be interpretted as: \n\n- With probability $1-p$ apply the identity to the state, and\n- with probability $p$ apply one of the three Pauli matrices $X$, $Y$, or $Z$ with equal probability.\n\nChannels that can be interpretted in this form can be simulating using a wavefunction simulator: when this channel is simulated the simulation will sample a unitary with the appropriate probability.  \n\nFor channels of these type, the channel can, instead of implementing the `_kraus_` protocol, implement the `_mixture_` protocol:\n\n\n```\n\"\"\"Use the cirq.mixture protocol on the cirq.depolarize channel.\"\"\"\nfor p, u in cirq.mixture(cirq.depolarize(0.2)):\n    print(\"prob = {}\\nunitary: \\n{}\\n\".format(p, u))\n```\n\n    prob = 0.8\n    unitary: \n    [[1. 0.]\n     [0. 1.]]\n    \n    prob = 0.06666666666666667\n    unitary: \n    [[0.+0.j 1.+0.j]\n     [1.+0.j 0.+0.j]]\n    \n    prob = 0.06666666666666667\n    unitary: \n    [[0.+0.j 0.-1.j]\n     [0.+1.j 0.+0.j]]\n    \n    prob = 0.06666666666666667\n    unitary: \n    [[ 1.+0.j  0.+0.j]\n     [ 0.+0.j -1.+0.j]]\n    \n\n\nIn fact the depolarizing channel does not implement `_kraus_`.  Instead it only implements `_mixture_` and the `cirq.channel` method notices this and derives the channel from the mixture.\n\n\n```\n\"\"\"Check if cirq.depolarize has _kraus_ and _mixture_ methods.\"\"\"\n# Get a depolarizing channel.\nd = cirq.depolarize(0.2)\n\n# Check if it has _kraus_ implemented.\nprint('does cirq.depolarize(0.2) have _kraus_? {}'.format('yes' if getattr(d, '_kraus_', None) else 'no'))\n\n# Check if it has _mixture_ implemented.\nprint('does cirq.depolarize(0.2) have _mixture_? {}'.format('yes' if getattr(d, '_mixture_', None) else 'no'))\n```\n\n    does cirq.depolarize(0.2) have _kraus_? no\n    does cirq.depolarize(0.2) have _mixture_? yes\n\n\nWhen channels implement mixture then, as we said, we can use the wavefunction simulator:\n\n\n```\n\"\"\"Use the wavefunction simulator on a channel that implements the mixture protocol.\"\"\"\ncircuit = cirq.Circuit(cirq.depolarize(0.5).on(a), cirq.measure(a))\nsimulator = cirq.Simulator()\nresult = simulator.run(circuit, repetitions=10)\nprint(result)\n```\n\n    a=1000010001\n\n\nBecause the unitary Kraus operators are applied stochastically, executing the above cell multiple times will produce different outputs.\n\n### Adding noise to circuits and simulations\n\nTo add noise to circuits or during simulations, we provide the notion of a `NoiseModel`.  A `NoiseModel` may add noise operation by operation, or it may add noise moment by moment, or it may add noise across a list of moments.\n\nFor example we can define a noise model that add a single qubit depolarizing for every qubit in each moment.  \n\n\n```\n\"\"\"Adding noise to a circuit.\"\"\"\n# Get a noiseless circuit.\nnoise = cirq.ConstantQubitNoiseModel(cirq.depolarize(0.2))\ncircuit = cirq.Circuit(cirq.H(a), cirq.CNOT(a, b), cirq.measure(a, b))\nprint('Circuit with no noise:\\n{}\\n'.format(circuit))\n\n# Add noise to the circuit.\nsystem_qubits = sorted(circuit.all_qubits())\nnoisy_circuit = cirq.Circuit()\nfor moment in circuit:\n    noisy_circuit.append(noise.noisy_moment(moment, system_qubits))\nprint('Circuit with noise:\\n{}'.format(noisy_circuit))\n```\n\n    Circuit with no noise:\n    a: \u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500M\u2500\u2500\u2500\n              \u2502   \u2502\n    b: \u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500M\u2500\u2500\u2500\n    \n    Circuit with noise:\n    a: \u2500\u2500\u2500H\u2500\u2500\u2500D(0.2)[cirq.VirtualTag()]\u2500\u2500\u2500@\u2500\u2500\u2500D(0.2)[cirq.VirtualTag()]\u2500\u2500\u2500M\u2500\u2500\u2500D(0.2)[cirq.VirtualTag()]\u2500\u2500\u2500\n                                          \u2502                               \u2502\n    b: \u2500\u2500\u2500\u2500\u2500\u2500\u2500D(0.2)[cirq.VirtualTag()]\u2500\u2500\u2500X\u2500\u2500\u2500D(0.2)[cirq.VirtualTag()]\u2500\u2500\u2500M\u2500\u2500\u2500D(0.2)[cirq.VirtualTag()]\u2500\u2500\u2500\n\n\nWe can also pass a noise model into the `cirq.DensityMatrixSimulator` and execute a noisy circuit in this manner.\n\n\n```\n\"\"\"Perform noisy simulation by defining a density matrix simulator with a noise model.\"\"\"\n# Define a noise model.\nnoise = cirq.ConstantQubitNoiseModel(cirq.depolarize(0.2))\n\n# Pass this noise model into the simulator.\nsimulator = cirq.DensityMatrixSimulator(noise=noise)\n\n# Get a circuit to simulate.\ncircuit = cirq.Circuit(cirq.H(a), cirq.CNOT(a, b), cirq.measure(a, b))\n\n# Simulate the circuit in steps.\nfor i, step in enumerate(simulator.simulate_moment_steps(circuit)):\n    print('After step {} state was\\n{}\\n'.format(i, step.density_matrix()))\n```\n\n    After step 0 state was\n    [[0.4333333 +0.j 0.        +0.j 0.31777775+0.j 0.        +0.j]\n     [0.        +0.j 0.06666666+0.j 0.        +0.j 0.04888888+0.j]\n     [0.31777775+0.j 0.        +0.j 0.4333333 +0.j 0.        +0.j]\n     [0.        +0.j 0.04888888+0.j 0.        +0.j 0.06666666+0.j]]\n    \n    After step 1 state was\n    [[0.34859255+0.j 0.        +0.j 0.        +0.j 0.17089382+0.j]\n     [0.        +0.j 0.15140739+0.j 0.02629136+0.j 0.        +0.j]\n     [0.        +0.j 0.02629136+0.j 0.15140739+0.j 0.        +0.j]\n     [0.17089382+0.j 0.        +0.j 0.        +0.j 0.34859255+0.j]]\n    \n    After step 2 state was\n    [[0.01777777+0.j 0.        +0.j 0.        +0.j 0.        +0.j]\n     [0.        +0.j 0.11555553+0.j 0.        +0.j 0.        +0.j]\n     [0.        +0.j 0.        +0.j 0.11555554+0.j 0.        +0.j]\n     [0.        +0.j 0.        +0.j 0.        +0.j 0.75111103+0.j]]\n    \n\n\n## Devices\n\nNISQ algorithms work in a regime where every gate counts.  A key philosophy behind Cirq is that we believe the details of the hardware, the performance characteristics, as well as device constraints, will be key to getting the most out of NISQ algorithms.  Towards this end these hardware features are contained in the `Device` class.\n\nFor example, here is Google's Bristleconde device which we printed out at the start of this notebook.\n\n\n```\nprint(cirq_google.Bristlecone)\n```\n\n                                                 (0, 5)\u2500\u2500\u2500\u2500(0, 6)\n                                                 \u2502         \u2502\n                                                 \u2502         \u2502\n                                        (1, 4)\u2500\u2500\u2500(1, 5)\u2500\u2500\u2500\u2500(1, 6)\u2500\u2500\u2500\u2500(1, 7)\n                                        \u2502        \u2502         \u2502         \u2502\n                                        \u2502        \u2502         \u2502         \u2502\n                               (2, 3)\u2500\u2500\u2500(2, 4)\u2500\u2500\u2500(2, 5)\u2500\u2500\u2500\u2500(2, 6)\u2500\u2500\u2500\u2500(2, 7)\u2500\u2500\u2500(2, 8)\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                      (3, 2)\u2500\u2500\u2500(3, 3)\u2500\u2500\u2500(3, 4)\u2500\u2500\u2500(3, 5)\u2500\u2500\u2500\u2500(3, 6)\u2500\u2500\u2500\u2500(3, 7)\u2500\u2500\u2500(3, 8)\u2500\u2500\u2500(3, 9)\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n             (4, 1)\u2500\u2500\u2500(4, 2)\u2500\u2500\u2500(4, 3)\u2500\u2500\u2500(4, 4)\u2500\u2500\u2500(4, 5)\u2500\u2500\u2500\u2500(4, 6)\u2500\u2500\u2500\u2500(4, 7)\u2500\u2500\u2500(4, 8)\u2500\u2500\u2500(4, 9)\u2500\u2500\u2500(4, 10)\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n    (5, 0)\u2500\u2500\u2500(5, 1)\u2500\u2500\u2500(5, 2)\u2500\u2500\u2500(5, 3)\u2500\u2500\u2500(5, 4)\u2500\u2500\u2500(5, 5)\u2500\u2500\u2500\u2500(5, 6)\u2500\u2500\u2500\u2500(5, 7)\u2500\u2500\u2500(5, 8)\u2500\u2500\u2500(5, 9)\u2500\u2500\u2500(5, 10)\u2500\u2500\u2500(5, 11)\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n             (6, 1)\u2500\u2500\u2500(6, 2)\u2500\u2500\u2500(6, 3)\u2500\u2500\u2500(6, 4)\u2500\u2500\u2500(6, 5)\u2500\u2500\u2500\u2500(6, 6)\u2500\u2500\u2500\u2500(6, 7)\u2500\u2500\u2500(6, 8)\u2500\u2500\u2500(6, 9)\u2500\u2500\u2500(6, 10)\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n                      (7, 2)\u2500\u2500\u2500(7, 3)\u2500\u2500\u2500(7, 4)\u2500\u2500\u2500(7, 5)\u2500\u2500\u2500\u2500(7, 6)\u2500\u2500\u2500\u2500(7, 7)\u2500\u2500\u2500(7, 8)\u2500\u2500\u2500(7, 9)\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                               (8, 3)\u2500\u2500\u2500(8, 4)\u2500\u2500\u2500(8, 5)\u2500\u2500\u2500\u2500(8, 6)\u2500\u2500\u2500\u2500(8, 7)\u2500\u2500\u2500(8, 8)\n                                        \u2502        \u2502         \u2502         \u2502\n                                        \u2502        \u2502         \u2502         \u2502\n                                        (9, 4)\u2500\u2500\u2500(9, 5)\u2500\u2500\u2500\u2500(9, 6)\u2500\u2500\u2500\u2500(9, 7)\n                                                 \u2502         \u2502\n                                                 \u2502         \u2502\n                                                 (10, 5)\u2500\u2500\u2500(10, 6)\n\n\nIn a future version, we intend for each `Device` to define a noise model.\n\n`Device`s also contain more information about the timing of the device.  For example here we can calculate the duration of an `X` on the `Bristlecone` device.\n\n\n```\n\"\"\"Get the duration of an operation.\"\"\"\nbrissy = cirq_google.Bristlecone\nop = cirq.X.on(cirq.GridQubit(5, 5))\nprint(brissy.duration_of(op))\n```\n\n    20 ns\n\n\nAnother property of devices is that they can be used to enforce constraints from the hardware, both checking that these constraints are satisfied, but also enforcing the constraints on the device.  For example, on the `Bristlecone` device, a two-qubit gate has the property that one cannot simultaneously perform a pair of two-qubit gates that act on adjacent qubits. So for example if we create such a `Circuit` and validate it using the device, we will see an error.\n\n\n```\n\"\"\"Validate operations on a device.\"\"\"\n# Get adjacent qubits on the Bristlecone device.\nq55 = cirq.GridQubit(5, 5)\nq56 = cirq.GridQubit(5, 6)\nq66 = cirq.GridQubit(6, 6)\nq67 = cirq.GridQubit(6, 7)\n\n# Define operations on adjacent qubits.\nops = [cirq.CZ(q55, q56), cirq.CZ(q66, q67)]\ncircuit = cirq.Circuit(ops)\nprint(circuit)\n\ntry: \n  cirq_google.Bristlecone.validate_circuit(circuit)\nexcept ValueError as ex:\n  print(f\"error, as expected: \\n{ex}\")\n```\n\n    (5, 5): \u2500\u2500\u2500@\u2500\u2500\u2500\n               \u2502\n    (5, 6): \u2500\u2500\u2500@\u2500\u2500\u2500\n    \n    (6, 6): \u2500\u2500\u2500@\u2500\u2500\u2500\n               \u2502\n    (6, 7): \u2500\u2500\u2500@\u2500\u2500\u2500\n    error, as expected: \n    Adjacent Exp11 operations:   \u2577 5 6 7\n    \u2576\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    5 \u2502 @\u2500@\n      \u2502\n    6 \u2502   @\u2500@\n      \u2502.\n\n\nBut more interestingly we could have passed the device into the `Circuit` and it will perform the creation of the circuit (using the insertion semantics as described above) such that the device cannot violate the constraints.\n\n\n```\n\"\"\"Create a circuit for a particular device.\"\"\"\n# Same adjacent operations as above.\nops = [cirq.CZ(q55, q56), cirq.CZ(q66, q67)]\n\n# Create a circuit on the Bristlecone device.\ncircuit = cirq.Circuit(device=cirq_google.Bristlecone)\n\n\n# When we append operations now, they are put into different moments.\ncircuit.append(ops)\nprint(circuit)\n```\n\n    (5, 5): \u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n               \u2502\n    (5, 6): \u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    (6, 6): \u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\n                   \u2502\n    (6, 7): \u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\n\n\n### Exercise: Make a Device\n\nConstruct a device that acts on a square sized lattice, and only allows Hadamard, CZ, and measurement gates.\n\n\n```\n#@title Attempt the solution here\n```\n\n\n```\n#@title Expand to view the solution\nclass SquareDevice(cirq.Device):\n    \"\"\"A Square Grid Device.\n    \n    The device that only allows \n        1) Grid Qubits from (0, 0) to (grid_size - 1, grid_size - 1)\n        2) H, CZ and MeasurementGate gates.\n    \"\"\"\n    def __init__(self, grid_size):\n        self.qubits = []\n        for i in range(grid_size):\n            for j in range(grid_size):\n                self.qubits.append(cirq.GridQubit(i, j))\n\n    def validate_operation(self, operation: 'cirq.Operation') -> None:\n        if not isinstance(operation, cirq.GateOperation):\n            raise ValueError(f\"Unsupported operation {operation}\")\n        if not (operation.gate in [cirq.H, cirq.CZ] or isinstance(operation.gate, cirq.MeasurementGate)):\n            raise ValueError(f\"Unsupported gate {operation.gate}\")\n        for qubit in operation.qubits:\n            if qubit not in self.qubits:\n                raise ValueError(f\"Qubit {qubit} not on device\")\n```\n\n## Compiling / Optimizing\n\nCirq's philosophy for what are often called compilation steps is slightly non-traditional.  In particular we believe that NISQ devices perform so few gates that many compiliations will be one or a few passes. A useful class of optimization code for this is the `PointOptimizer`. For example, here is a `PointOptimizer` that recognizes that a `X` gate followed by a `Z` gate is equivalent to a `Y` gate\n\n\n```\n\"\"\"Example of defining a custom cirq.PointOptimizer.\"\"\"\nclass XZOptimizer(cirq.PointOptimizer):\n    \"\"\"Replaces an X followed by a Z with a Y.\"\"\"\n    \n    def optimization_at(self, circuit, index, op):\n        # Is the gate an X gate?\n        if isinstance(op, cirq.GateOperation) and (op.gate == cirq.X):\n            next_op_index = circuit.next_moment_operating_on(op.qubits, index + 1)\n            qubit = op.qubits[0]\n            if next_op_index is not None:\n                next_op = circuit.operation_at(qubit, next_op_index)\n                if isinstance(next_op, cirq.GateOperation) and  (next_op.gate == cirq.Z):\n                    new_op = cirq.Y.on(qubit)\n                    return cirq.PointOptimizationSummary(\n                        clear_span = next_op_index - index + 1,\n                        clear_qubits=op.qubits, \n                        new_operations=[new_op])\n        \nopt = XZOptimizer()\ncircuit = cirq.Circuit(cirq.X(a), cirq.Z(a), cirq.CZ(a, b), cirq.X(a))\nprint(\"Before optimizing:\\n{}\\n\". format(circuit))\nopt.optimize_circuit(circuit)\nprint(\"After optimizing:\\n{}\".format(circuit))\n```\n\n    Before optimizing:\n    a: \u2500\u2500\u2500X\u2500\u2500\u2500Z\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500\n                  \u2502\n    b: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    After optimizing:\n    a: \u2500\u2500\u2500Y\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500\n                  \u2502\n    b: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n### Exercise: Simplify flipped CNOTs\n\nWrite an PointOptimizer that performs (greedily) the simplification that\n\n```\na: \u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\n          \u2502\nb: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\n```\nis equal to\n\n\n```\na: \u2500\u2500\u2500X\u2500\u2500\u2500\n      \u2502\nb: \u2500\u2500\u2500@\u2500\u2500\u2500\n```\n\n\n\n```\n#@title Attempt the solution here\n\n\"\"\"Test your optimizer on this circuit.\"\"\"\ncircuit = cirq.Circuit(\n    cirq.H.on_each(a, b, c), \n    cirq.CNOT(a, b), \n    cirq.H.on_each(a, b), \n    cirq.CZ(a, b)\n)\n# Instantiate your optimizer\n# my_opt = \n\n# And check that it worked.\n# print(my_opt.optimizer_circuit(circuit))\n```\n\n\n```\n#@title Expand to view the solution\nclass CXOptimizer(cirq.PointOptimizer):\n    \"\"\"Replaces a CX surrounded by Hadamards\n\n        Note: This implementation does not generalize for all situations. It is\n        a simplified version which works for the trivial case where Hs, CX, Hs\n        are present in consecutive moments, as given in the sample input.\n    \"\"\"\n    \n    def optimization_at(self, circuit, index, op):\n        if isinstance(op, cirq.GateOperation) and (op.gate == cirq.H):\n            q0, = op.qubits\n            next_op = circuit.operation_at(q0, index + 1)\n            if isinstance(next_op, cirq.GateOperation) and next_op.gate == cirq.CX:\n                qubits = circuit.operation_at(q0, index + 1).qubits\n                if all(\n                    circuit.operation_at(q, idx).gate == cirq.H\n                    for idx in [index, index + 2]\n                    for q in qubits\n                ):\n                    return cirq.PointOptimizationSummary(\n                        clear_span = 3,\n                        clear_qubits = qubits,\n                        new_operations = [cirq.CX(qubits[1], qubits[0])]\n                    )\n        \nopt = CXOptimizer()\ncircuit = cirq.Circuit(\n    cirq.H.on_each(a, b, c), \n    cirq.CNOT(a, b), \n    cirq.H.on_each(a, b), \n    cirq.CZ(a, b)\n)\nprint(\"Before optimizing:\\n{}\\n\". format(circuit))\nopt.optimize_circuit(circuit)\nprint(\"After optimizing:\\n{}\".format(circuit))\n```\n\n    Before optimizing:\n    a: \u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500\n              \u2502       \u2502\n    b: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500\n    \n    c: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    After optimizing:\n    a: \u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\n          \u2502           \u2502\n    b: \u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\n    \n    c: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n## Google's Xmon Gates\n\nWe built Cirq at Google because we thought that it was important that hardware details flow up through the level of abstractions in a framework for NISQ algorithms.  And we also built it because Google has a class of superconducting qubit devices where we want to explore NISQ algorithms.  \n\nWhat sort of gates does the xmon architecture support?  At the hardware level the basic gate set is rotations about the Pauli $Z$ axis\n\n$$\n\\exp(-iZt) = \\left[ \n\\begin{matrix}\n e^{it} & 0 \\\\\n 0 & e^{-it}\n\\end{matrix}\n\\right]\n$$\n\nRotations about any axis in the Pauli $X$ and $Y$ plane:\n\n$$\n\\exp(-i(\\cos \\theta X + \\sin \\theta Y) t) = \n\\left[\n\\begin{matrix}\n\\cos t & -i\\sin t e^{-i \\theta} \\\\\n-i\\sin t e^{i \\theta} & \\cos t\n\\end{matrix}\n\\right]\n$$\n\nThe two qubit gate is a phase about the $|11\\rangle$ state:\n\n$$\n\\exp(-it |11\\rangle \\langle 11|) =\n\\left[ \n\\begin{matrix}\n1 & 0 & 0 & 0 \\\\\n0 & 1 & 0 & 0 \\\\\n0 & 0 & 1 & 0 \\\\\n0 & 0 & 0 & \\exp(-it)\n\\end{matrix}\n\\right]\n$$\n\nAnd finally measurements in the computational basis.\n\nMany of the common gates in Cirq are directly accessible on this hardware.  To check whether the gate you are using is in the xmon gate set, one can use the `is_supported_operation` as shown below.\n\n\n```\n\"\"\"Check if an operation is supported by the XMON gate set.\"\"\"\n# Get the XMON gate set.\nxmon = cirq_google.XMON\n\n# Check if X is supported.\nxmon.is_supported_operation(cirq.X.on(cirq.NamedQubit(\"a\")))\n```\n\n\n\n\n    True\n\n\n\nThus, `cirq.X` is supported by the xmon gate set. As mentioned above, `cirq.CNOT` is not supported, so the following code block should return `False`.\n\n\n```\n\"\"\"Check if CNOT is supported.\"\"\"\nxmon.is_supported_operation(cirq.CNOT.on(cirq.NamedQubit('a'), cirq.NamedQubit('b')))\n```\n\n\n\n\n    False\n\n\n\nWhen a gate is not a native xmon gate, Cirq can often convert it to an xmon native gate.\n\n\n```\n\"\"\"Convert a gate to xmon gates.\"\"\"\n# Get a converter.\nconverter = cirq_google.ConvertToXmonGates()\n\n# Do the conversion.\nconverted = converter.convert(cirq.CNOT.on(cirq.NamedQubit(\"a\"), cirq.NamedQubit(\"b\")))\nprint(cirq.Circuit(converted))\n```\n\n    a: \u2500\u2500\u2500Z^0.75\u2500\u2500\u2500\u2500X^0.5\u2500\u2500\u2500\u2500S^-1\u2500\u2500\u2500Y^-0.5\u2500\u2500\u2500@\u2500\u2500\u2500S^-1\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500\u2500\u2500Z^-0.75\u2500\u2500\u2500\n                                             \u2502\n    b: \u2500\u2500\u2500X^-0.25\u2500\u2500\u2500Y^-0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500S^-1\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500X^-0.25\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\nThis isn't very optimized because what it has done is first rely on the decompose of `CNOT` and then decomposed each of these into native xmon gates.  There are many tricks that one can use to simplify xmon gates.  To apply many of these one can use the `cirq_google.optimize_from_xmon` method:\n\n\n```\n\"\"\"Optimize a circuit for the xmon gate set.\"\"\"\ncircuit = cirq.Circuit(\n    cirq.CNOT.on(cirq.NamedQubit(\"a\"), cirq.NamedQubit(\"b\"))\n)\nprint(cirq_google.optimized_for_xmon(circuit))\n```\n\n    a: \u2500\u2500\u2500PhXZ(a=0.375,x=1,z=0)\u2500\u2500\u2500\u2500@\u2500\u2500\u2500PhXZ(a=0.375,x=1,z=0)\u2500\u2500\u2500\u2500\u2500\n                                   \u2502\n    b: \u2500\u2500\u2500PhXZ(a=-0.5,x=0.5,z=0)\u2500\u2500\u2500@\u2500\u2500\u2500PhXZ(a=-0.5,x=0.5,z=-1)\u2500\u2500\u2500\n\n\nBecause xmon gates can be executed on Google hardware, they will need to be transmitted as machine code to the quantum computer.  This means that they have a serialized form.  We use protobuffers as the serialization.  To see what this form looks like we can do the following.\n\n\n```\n\"\"\"Serialize an operation.\"\"\"\nxmon.serialize_op(cirq.X.on(cirq.GridQubit(5, 5)))\n```\n\n\n\n\n    gate {\n      id: \"xy\"\n    }\n    args {\n      key: \"axis_half_turns\"\n      value {\n        arg_value {\n          float_value: 0.0\n        }\n      }\n    }\n    args {\n      key: \"half_turns\"\n      value {\n        arg_value {\n          float_value: 1.0\n        }\n      }\n    }\n    qubits {\n      id: \"5_5\"\n    }\n\n\n\n## Other interesting things in Cirq\n\n**Experiments**. The `cirq.experiments` package can perform and plot the results of some basic experiments for understanding how well a system is performing.\n\n\n\n```\nresult = cirq.experiments.rabi_oscillations(\n    sampler=cirq.Simulator(),  # In case of Google QCS or other hardware providers, sampler could point at real hardware.\n    qubit=cirq.LineQubit(0),\n    num_points=200,\n    repetitions=1000,\n)\nresult.plot();\n```\n\n**Testing**. The `cirq.testing` package has useful debugging and testing methods like `cirq.testing.assert_implements_consistent_protocols` and `cirq.testing.assert_allclose_up_to_global_phase`.\n\n\n\n```\nclass InconsistentXGate(cirq.SingleQubitGate):\n\n    def _decompose_(self, qubits):\n        yield cirq.H(qubits[0])\n        yield cirq.Z(qubits[0])\n        yield cirq.H(qubits[0])\n\n    def _unitary_(self):\n        return np.array([[0, -1j], [1j, 0]])  # Oops! Y instead of X!\n\n# cirq.testing.assert_decompose_is_consistent_with_unitary(InconsistentXGate())\n```\n\n**Export**. You can export a circuit as Qasm.\n\n\n```\n\"\"\"Export a circuit to Qasm.\"\"\"\na, b, c = cirq.LineQubit.range(3)\ncircuit = cirq.Circuit(cirq.H(a), cirq.H(c), cirq.CNOT(a, b), cirq.CCZ(a, b, c))\nprint(circuit.to_qasm())\n```\n\n    // Generated from Cirq v0.11.0.dev\n    \n    OPENQASM 2.0;\n    include \"qelib1.inc\";\n    \n    \n    // Qubits: [0, 1, 2]\n    qreg q[3];\n    \n    \n    h q[0];\n    h q[2];\n    cx q[0],q[1];\n    \n    // Gate: CCZ\n    h q[2];\n    ccx q[0],q[1],q[2];\n    h q[2];\n    \n\n\nYou can also export a circuit as QUIL:\n\n\n```\n\"\"\"Export a circuit to QUIL.\"\"\"\nprint(circuit.to_quil())\n```\n\n    # Created using Cirq.\n    \n    H 0\n    H 2\n    CNOT 0 1\n    H 2\n    CCNOT 0 1 2\n    H 2\n    \n\n\nYou can also turn a circuit into a link to the drag-and-drop web simulation Quirk (though somewhat inconveniently).\n\n\n```\n\"\"\"Export a circuit to a Quirk URL.\"\"\"\nfrom cirq.contrib.quirk.export_to_quirk import circuit_to_quirk_url\nprint(circuit_to_quirk_url(circuit))\n```\n\n    http://algassert.com/quirk#circuit=%7B%22cols%22%3A%5B%5B%22H%22%2C1%2C%22H%22%5D%2C%5B%22%E2%80%A2%22%2C%22X%22%5D%2C%5B%22%E2%80%A2%22%2C%22%E2%80%A2%22%2C%22Z%22%5D%5D%7D\n\n", "meta": {"hexsha": "99798650fffc34c4cc1200a23e2caee121e0a2de", "size": 517295, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/educators/intro.ipynb", "max_stars_repo_name": "Saibaba-Alapati/Cirq", "max_stars_repo_head_hexsha": "782efcd04c3bbf73a0d630306a3d1cfd9966521d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/tutorials/educators/intro.ipynb", "max_issues_repo_name": "Saibaba-Alapati/Cirq", "max_issues_repo_head_hexsha": "782efcd04c3bbf73a0d630306a3d1cfd9966521d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/tutorials/educators/intro.ipynb", "max_forks_repo_name": "Saibaba-Alapati/Cirq", "max_forks_repo_head_hexsha": "782efcd04c3bbf73a0d630306a3d1cfd9966521d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 124.7997587455, "max_line_length": 293793, "alphanum_fraction": 0.8498999604, "converted": true, "num_tokens": 25171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17106118322668998, "lm_q2_score": 0.1008786267847576, "lm_q1q2_score": 0.017256417260084297}}
{"text": "```python\n%matplotlib inline\n```\n\n## Intro\n\nEste tutorial \u00e9 baseado no tutorial [Aten\u00e7\u00e3o \u00e9 tudo que voc\u00ea precisa](http://nlp.seas.harvard.edu/2018/04/03/attention.html)\n\nO transformador descrito no artigo `Attention is All You Need` tem sido de grande interesse para v\u00e1rios pesquisadores em redes neurais. Al\u00e9m de produzir ganhos significativos em tarefas de tradu\u00e7\u00e3o, este modelo prov\u00ea uma nova arquitetura para muitas tarefas de processamento de linguagem natural (`NLP`).\n\nO artigo \u00e9 extremamente bem escrito, mas \u00e9 de conhecimento comum que esta arquitetura \u00e9 bastante dif\u00edcil de implementar de forma correta. Sendo assim, Alexander Rush escreveu esta vers\u00e3o linha-a-linha de como o modelo \u00e9 implementado. Ele tamb\u00e9m teve ajuda de Vincent Nguyen e Guilherme Klein.\n\nDe toda forma, eu espero que eu possa capturar de forma correta os argumentos/ideias descritas no artigo e explanadas pelos pesquisadores citados acima.\n\n### Depend\u00eancias\n\n* torchtext\n* spacy\n* seaborn\n* torchtext\n* matplotlib\n\n\n```python\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math, copy, time\nfrom torch.autograd import Variable\nimport matplotlib.pyplot as plt\nimport seaborn\nseaborn.set_context(context=\"talk\")\n\n# Removendo warning por conta da issue: https://github.com/NVIDIA/DeepRecommender/issues/21\nimport warnings\nwarnings.filterwarnings('ignore')\n```\n\n## Contexto\n\nIntra-aten\u00e7\u00e3o (`self-attention`) \u00e9 um mecanismo de aten\u00e7\u00e3o que relaciona diferentes posi\u00e7\u00f5es de uma \u00fanica sequ\u00eancia de modo a computar a representa\u00e7\u00e3o daquela sequ\u00eancia. Intra-anten\u00e7\u00e3o foi utilizado com sucesso em uma variedade de tarefas cujos nomes eu n\u00e3o me arrisco a traduzir (reading comprehension, abstractive summarization, textual entailment and learning task-independent sentence representations).\n\nRedes neurais nesta arquitetura s\u00e3o baseadas em aten\u00e7\u00e3o recorrente ao inv\u00e9s de alinhamentos sequenciais e foi comprovado que esta arquitetura performa bem em tarefas de perguntas e respostas ou na representa\u00e7\u00e3o de modelos de linguage. \n\n# Arquitetura\n\nAssim como a maioria dos modelos de sequ\u00eancia mais robustos, a arquiterura deste modelo segue a estrutura de um codificador-decodificador. \n\nAqui, o codificador mapeia uma sequ\u00eancia de entrada com s\u00edmbolos ($x_1, ..., x_n$) para uma sequ\u00eancia de representa\u00e7\u00e3o continua z = ($z_1, ..., z_n$). \n\nDado z, o decodificador gera ent\u00e3o uma sequ\u00eancia de s\u00edmbolos de sa\u00edda ($y_1, ..., y_n$) - um s\u00edmbolo a cada intervalo de tempo. A cada intervalo de tempo, o modelo \u00e9 auto-regressivo, consumindo a \u00faltima sequ\u00eancia de s\u00edmbolos como parte da entrada.\n\n\n```python\nclass EncoderDecoder(nn.Module):\n    \"\"\"\n    A standard Encoder-Decoder architecture. Base for this and many \n    other models.\n    \"\"\"\n    def __init__(self, encoder, decoder, src_embed, tgt_embed, generator):\n        super(EncoderDecoder, self).__init__()\n        self.encoder = encoder\n        self.decoder = decoder\n        self.src_embed = src_embed\n        self.tgt_embed = tgt_embed\n        self.generator = generator\n        \n    def forward(self, src, tgt, src_mask, tgt_mask):\n        \"Take in and process masked src and target sequences.\"\n        return self.decode(self.encode(src, src_mask), src_mask,\n                            tgt, tgt_mask)\n    \n    def encode(self, src, src_mask):\n        return self.encoder(self.src_embed(src), src_mask)\n    \n    def decode(self, memory, src_mask, tgt, tgt_mask):\n        return self.decoder(self.tgt_embed(tgt), memory, src_mask, tgt_mask)\n```\n\n\n```python\nclass Generator(nn.Module):\n    \"Define standard linear + softmax generation step.\"\n    def __init__(self, d_model, vocab):\n        super(Generator, self).__init__()\n        self.proj = nn.Linear(d_model, vocab)\n\n    def forward(self, x):\n        return F.log_softmax(self.proj(x), dim=-1)\n```\n\nO transformador segue esta arquitetura empilhando uma s\u00e9rie de camadas de intra-aten\u00e7\u00e3o, al\u00e9m de camadas densamente conectadas tanto no codificador quanto no decodificador, conforme exibidor no lado esquerdo e lado direito inferior da figura:\n\n\n\n`mais detalhes explicando a figura em breve....`\n\n# Pilha de Codificadores e Decodificadores \n\n## Codificador\n\nO codificador \u00e9 composto de uma pilha de $N = 6$ camadas id\u00eanticas\n\n\n```python\ndef clones(module, N):\n    \"Produce N identical layers.\"\n    return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])\n```\n\n\n```python\nclass Encoder(nn.Module):\n    \"Core encoder is a stack of N layers\"\n    def __init__(self, layer, N):\n        super(Encoder, self).__init__()\n        self.layers = clones(layer, N)\n        self.norm = LayerNorm(layer.size)\n        \n    def forward(self, x, mask):\n        \"Pass the input (and mask) through each layer in turn.\"\n        for layer in self.layers:\n            x = layer(x, mask)\n        return self.norm(x)\n```\n\nAplicamos uma camada residual a cada duas camadas, e em seguida, utilizamos uma camada de normaliza\u00e7\u00e3o:\n\n\n```python\nclass LayerNorm(nn.Module):\n    \"Construct a layernorm module (See citation for details).\"\n    def __init__(self, features, eps=1e-6):\n        super(LayerNorm, self).__init__()\n        self.a_2 = nn.Parameter(torch.ones(features))\n        self.b_2 = nn.Parameter(torch.zeros(features))\n        self.eps = eps\n\n    def forward(self, x):\n        mean = x.mean(-1, keepdim=True)\n        std = x.std(-1, keepdim=True)\n        return self.a_2 * (x - mean) / (std + self.eps) + self.b_2\n```\n\nEm outras palavras, a sa\u00edda de cada uma dessas camadas \u00e9 uma $CamadaNormalizacao(x + SubCamada(x))$, onde $SubCamada(x)$ \u00e9 a fun\u00e7\u00e3o implementada pela sub-camada. Tamb\u00e9m aplicamos dropout na sa\u00edda de cada sub-camada antes de adicionarmos e normalizarmos os valores de entrada.\n\nPara facilitar a conex\u00e3o entre estas camadas, todas as sub-camadas do modelo assim como as camadas intermedi\u00e1rias produzem sa\u00eddas cujas dimens\u00f5es s\u00e3o $d_{model} = 512$\n\n\n```python\nclass SublayerConnection(nn.Module):\n    \"\"\"\n    A residual connection followed by a layer norm.\n    Note for code simplicity the norm is first as opposed to last.\n    \"\"\"\n    def __init__(self, size, dropout):\n        super(SublayerConnection, self).__init__()\n        self.norm = LayerNorm(size)\n        self.dropout = nn.Dropout(dropout)\n\n    def forward(self, x, sublayer):\n        \"Apply residual connection to any sublayer with the same size.\"\n        return x + self.dropout(sublayer(self.norm(x)))\n```\n\nCada camada possui duas sub-camadas. A primeira, implementa um mecanismo de intra-aten\u00e7\u00e3o m\u00faltipla enquanto que a segunda camada implementa um algoritmo de feed-forward posicional\n\n\n```python\nclass EncoderLayer(nn.Module):\n    \"Encoder is made up of self-attn and feed forward (defined below)\"\n    def __init__(self, size, self_attn, feed_forward, dropout):\n        super(EncoderLayer, self).__init__()\n        self.self_attn = self_attn\n        self.feed_forward = feed_forward\n        self.sublayer = clones(SublayerConnection(size, dropout), 2)\n        self.size = size\n\n    def forward(self, x, mask):\n        \"Follow Figure 1 (left) for connections.\"\n        x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask))\n        return self.sublayer[1](x, self.feed_forward)\n```\n\n## Decodificador\n\nO decodificador tamb\u00e9m \u00e9 composto de uma pilha de $N = 6$ camadas id\u00eanticas\n\n\n```python\nclass Decoder(nn.Module):\n    \"Generic N layer decoder with masking.\"\n    def __init__(self, layer, N):\n        super(Decoder, self).__init__()\n        self.layers = clones(layer, N)\n        self.norm = LayerNorm(layer.size)\n        \n    def forward(self, x, memory, src_mask, tgt_mask):\n        for layer in self.layers:\n            x = layer(x, memory, src_mask, tgt_mask)\n        return self.norm(x)\n```\n\nEm adi\u00e7\u00e3o as duas sub-camadas existentes no codificador, o decodificador tamb\u00e9m possui uma terceira sub-camada, que computa aten\u00e7\u00e3o m\u00faltipla na sa\u00edda da pilha de codificadores. De forma similar ao codificador, tamb\u00e9m utilizamos conex\u00f5es residuais em cada subcamada, seguidas por uma camada de normaliza\u00e7\u00e3o.\n\n\n```python\nclass DecoderLayer(nn.Module):\n    \"Decoder is made of self-attn, src-attn, and feed forward (defined below)\"\n    def __init__(self, size, self_attn, src_attn, feed_forward, dropout):\n        super(DecoderLayer, self).__init__()\n        self.size = size\n        self.self_attn = self_attn\n        self.src_attn = src_attn\n        self.feed_forward = feed_forward\n        self.sublayer = clones(SublayerConnection(size, dropout), 3)\n \n    def forward(self, x, memory, src_mask, tgt_mask):\n        \"Follow Figure 1 (right) for connections.\"\n        m = memory\n        x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, tgt_mask))\n        x = self.sublayer[1](x, lambda x: self.src_attn(x, m, m, src_mask))\n        return self.sublayer[2](x, self.feed_forward)\n```\n\nTamb\u00e9m \u00e9 necess\u00e1rio que modifiquemos a camada de intra-aten\u00e7\u00e3o na pilha de decodificadores para previnir que uma determinada posi\u00e7\u00e3o atenda \u00e0 posi\u00e7\u00f5es subsequentes. Esta modifica\u00e7\u00e3o introduz um mecanismo de obfusca\u00e7\u00e3o (ou m\u00e1scara) que combinado com o fato dos vetores estarem deslocados uma posi\u00e7\u00e3o para a direita assegura que as predi\u00e7\u00f5es na posi\u00e7\u00e3o $i$ depender\u00e3o s\u00f3 e somente de sa\u00eddas menores que $i$\n\n\n```python\ndef subsequent_mask(size):\n    \"Mask out subsequent positions.\"\n    attn_shape = (1, size, size)\n    subsequent_mask = np.triu(np.ones(attn_shape), k=1).astype('uint8')\n    return torch.from_numpy(subsequent_mask) == 0\n```\n\n> Below the attention mask shows the position each tgt word (row) is allowed to look at (column). Words are blocked for attending to future words during training.\n\n\n```python\nplt.figure(figsize=(5,5))\nplt.imshow(subsequent_mask(20)[0])\nNone\n```\n\n# Aten\u00e7\u00e3o\n\nUma fun\u00e7\u00e3o de aten\u00e7\u00e3o pode ser descrita como uma fun\u00e7\u00e3o que mapeia um consulta (`Q`) e um conjunto de chaves e valores (`K` e `V `) onde a consulta, chaves e valores assim como a sa\u00edda da fun\u00e7\u00e3o s\u00e3o todos vetores. A sa\u00edda \u00e9 computada como uma soma ponderada dos valores, onde os pesos atribu\u00eddos a cada valor s\u00e3o computados atrav\u00e9s de uma fun\u00e7\u00e3o de compatibilidade entre a consulta e a sua correspondente chave.\n\nCada mecanismo individual de aten\u00e7\u00e3o \u00e9 chamado de **aten\u00e7\u00e3o de produto escalar** (`Scaled Dot-Product Attention`).\nOs dados de entrada consistem de uma consulta e chaves de dimens\u00e3o $d_K$ e valores de dimens\u00e3o $d_v$. Nos executamos o produto de cada termo da consulta com cada chave, dividindo cada um por $\\sqrt{d_K}$ e aplicando softmax para obter os pesos de cada valor computado.\n\n\n\n___\n**nota pessoal:** \n\nH\u00e1 muita confus\u00e3o quanto aos valores que `Q`, `K` e `V` podem assumir. No grupo de discuss\u00f5es de redes neurais, o aluno que explicou da seguinte forma:\n\n\n`TODO`\n\n___\n\nNa pr\u00e1tica, computamos a fun\u00e7\u00e3o de aten\u00e7\u00e3o em um conjunto de consultas simultaneamente. As consultas s\u00e3o agrupadas em uma matriz `Q` assim como as chaves e valores s\u00e3o agrupados em matrizes `K` e `V`. As matrizes de sa\u00edda s\u00e3o computadas como:\n\n\\begin{equation}\n    Attention(Q, K, V) = softmax\\Big(\\frac{QK^T}{\\sqrt{d_k}}\\Big)V\n\\end{equation}\n\n\n```python\ndef attention(query, key, value, mask=None, dropout=None):\n    \"Compute 'Scaled Dot Product Attention'\"\n    d_k = query.size(-1)\n    scores = torch.matmul(query, key.transpose(-2, -1)) \\\n             / math.sqrt(d_k) # primeira caixa roxa (baixo para cima)\n    if mask is not None:\n        scores = scores.masked_fill(mask == 0, -1e9)\n    p_attn = F.softmax(scores, dim = -1) # caixa verde na figura\n    if dropout is not None:\n        p_attn = dropout(p_attn)\n    return torch.matmul(p_attn, value), p_attn \n\n# s\u00e3o retornados dois valores, o primeiro \u00e9 o resultado da fun\u00e7\u00e3o de ante\u00e7\u00e3o (multiplica\u00e7\u00e3o de matrizes)\n# o segundo \u00e9 s\u00e3o os vetores de aten\u00e7\u00e3o, obtidos ap\u00f3s o softmax.\n# TODO: indicar onde o vetor de aten\u00e7\u00e3o \u00e9 utilizado em etapas posteriores do notebook\n```\n\nAs duas fun\u00e7\u00f5es mais comuns de aten\u00e7\u00e3o s\u00e3o aten\u00e7\u00e3o-aditiva e aten\u00e7\u00e3o-produto-escalar. A aten\u00e7\u00e3o por produto escalar \u00e9 id\u00eantica ao algoritmo acima exceto por um fator escalar (caixa amarela na imagem?) de $\\frac{1}{\\sqrt{d_k}}$. \n\nApesar de teoricamente serem semelhantes, a aten\u00e7\u00e3o por produto escalar \u00e9 mais r\u00e1pida uma vez que ela pode se beneficiar de c\u00f3digos que optimizam a multiplica\u00e7\u00e3o de matrizes. No entanto, h\u00e1 cen\u00e1rios onde a aten\u00e7\u00e3o aditiva \u00e9 superior. Para uma discuss\u00e3o mais detalhada, direcionamos o leitor ao artigo original.\n\n## Aten\u00e7\u00e3o m\u00faltipla\n\n\n\nAten\u00e7\u00e3o m\u00faltipla permite ao modelo \"atender\" mutuamente a diferentes representa\u00e7\u00f5es em diferentes posi\u00e7\u00f5es do mesmo sub-espa\u00e7o.\n\n\\begin{equation}\n    MultiHead(Q, K, V) = Concat(head_1, head-2,.... head_h)W^O\n\\end{equation}\n\nonde :\n\n\\begin{equation}\n    head_i = Attention(QW_i^Q, KW_i^K, VW_i^V)\n\\end{equation}\n\ne as proje\u00e7\u00f5es s\u00e3o matrizes parametrizadas na forma:\n\n* $W_i^Q \\in \\mathbb{R}^{d_{model} \\times d_k}$\n\n* $W_i^K \\in \\mathbb{R}^{d_{model} \\times d_k}$\n\n* $W_i^V \\in \\mathbb{R}^{d_{model} \\times d_k}$\n\n* $W^O \\in \\mathbb{R}^{hd_v \\times d_{model}}$\n\nNo artigo, \u00e9 utilizado $h = 8$ aten\u00e7\u00f5es m\u00faltiplas, ou cabe\u00e7as. Para cada uma, n\u00f3s utilizamos $d_k = d_v = \\frac{d_{model}}{h} = 64$. Devido as redu\u00e7\u00f5es de dimensionalidade de cada cabe\u00e7a, o custo computacional total \u00e9 relativamente similar ao de um mecanismo de aten\u00e7\u00e3o com uma \u00fanica cabe\u00e7a utilizando as dimens\u00f5es originais do modelo (i.e. $d_{model} = 512$).\n\n\n```python\nclass MultiHeadedAttention(nn.Module):\n    def __init__(self, h, d_model, dropout=0.1):\n        \"Take in model size and number of heads.\"\n        super(MultiHeadedAttention, self).__init__()\n        assert d_model % h == 0\n        # We assume d_v always equals d_k\n        self.d_k = d_model // h\n        self.h = h\n        # N\u00e3o estou certo porque \u00e9 preciso dessas 4 linear layers aqui\n        self.linears = clones(nn.Linear(d_model, d_model), 4) \n        self.attn = None\n        self.dropout = nn.Dropout(p=dropout)\n        \n    def forward(self, query, key, value, mask=None):\n        \"Implements Figure 2\"\n        if mask is not None:\n            # Same mask applied to all h heads.\n            mask = mask.unsqueeze(1)\n        nbatches = query.size(0)\n        \n        # 1) Do all the linear projections in batch from d_model => h x d_k \n        query, key, value = \\\n            [l(x).view(nbatches, -1, self.h, self.d_k).transpose(1, 2)\n             for l, x in zip(self.linears, (query, key, value))]\n        \n        # 2) Apply attention on all the projected vectors in batch. \n        x, self.attn = attention(query, key, value, mask=mask, \n                                 dropout=self.dropout)\n        \n        # 3) \"Concat\" using a view and apply a final linear. \n        x = x.transpose(1, 2).contiguous() \\\n             .view(nbatches, -1, self.h * self.d_k)\n        return self.linears[-1](x)\n```\n\n## Aplica\u00e7\u00f5es do mecanismo de aten\u00e7\u00e3o em nosso modelo\n\n___\n**nota pessoal:** copiando e colando a figura para faciliar a explica\u00e7\u00e3o a seguir:\n\n\n\nO transformador utiliza aten\u00e7\u00e3o m\u00faltipla de 3 formas distintas:\n\n**1.** H\u00e1 um mecanismo de aten\u00e7\u00e3o entre o codificador e o decodificador, onde as consultas vem da camada de decodifica\u00e7\u00e3o anterior e a mem\u00f3ria com as chaves e valores vem da sa\u00edda do codificador. Isto serve para replicar o mecanismo de aten\u00e7\u00e3o normalmente utilizado em arquiteturas t\u00edpicas encontradas em codificadores-decodificadores.\n\n> **nota pessoal**: o codificador \u00e9 o lado esquerdo da figura, o decodificador o lado direito. Ent\u00e3o apesar das duas setas que saem do codificador indicarem que elas seriam (Q e K) na verdade a ordem das setas no decodificador \u00e9 invertida. No caso as setas da caixa laranja superior do decodificador devem ser lidas na seguinte ordem: V, K, Q\n\n**2.** O codificador cont\u00e9m camadas de intra-aten\u00e7\u00e3o. Em uma camada de intra-aten\u00e7\u00e3o, todas as consultas, chaves e valores vem do mesmo lugar, neste caso, a sa\u00edda da camada anterior do codificador.\n\n**3.** De forma an\u00e1loga as camadas do decodificador usam intra-aten\u00e7\u00e3o para que cada posi\u00e7\u00e3o atenda a si mesma e a posi\u00e7\u00f5es anteriores. No decodificador, \u00e9 necess\u00e1rio previnir que informa\u00e7\u00f5es vindas de posi\u00e7\u00f5es a esquerda da posi\u00e7\u00e3o atual possam comprometer a propriedade auto-regrassiva de nosso modelo. Para isto, mascaramos qualquer dado de entrada que s\u00e3o oriundos de conex\u00f5es ilegais.\n\n> **nota pessoal**: explicar melhor essa propriedade\n\n## Mecanismo de Feed-Forward (`Position-wise Feed-Forward Networks`)\n\nEm adi\u00e7\u00e3o aos mecanismos de aten\u00e7\u00e3o nas sub-camadas do modelo, cada uma das camadas de nosso codificador e decodificador contem uma rede densamente conecta com um mecanismo de feed-forward. Este mecanismo \u00e9 aplicado a cada posi\u00e7\u00e3o individualmente e separadamente. Este mecanismo consiste de duas camadas lineares com uma ativa\u00e7\u00e3o ReLU entre as camadas. \n\n\\begin{equation}\n    FNN(x) = max(0, xW_1 +b_1)W_2 + b_2\n\\end{equation}\n\nApesar das transforma\u00e7\u00f5es lineares serem sempre as mesmas, elas usam diferentes par\u00e2metros em cada camada.\nOutra forma de descrever esse mecanismo \u00e9 pensar nele como duas camadas convolucionais com kernels de tamanho 1. A dimensionalidade da entrada e sa\u00edda \u00e9 $d_{model} = 512$ e cada camada linear tem dimens\u00f5es $d_{ff} = 2048$\n\n\n```python\nclass PositionwiseFeedForward(nn.Module):\n    \"Implements FFN equation.\"\n    def __init__(self, d_model, d_ff, dropout=0.1):\n        super(PositionwiseFeedForward, self).__init__()\n        self.w_1 = nn.Linear(d_model, d_ff)\n        self.w_2 = nn.Linear(d_ff, d_model)\n        self.dropout = nn.Dropout(dropout)\n\n    def forward(self, x):\n        return self.w_2(self.dropout(F.relu(self.w_1(x))))\n```\n\n## Vetores e Sofmax\n\nSimilar a outros modelos de sequ\u00eancia, n\u00f3s utilizamos representa\u00e7\u00f5es (`embeddings`) previamente aprendidas para converter sequ\u00eancias de entrada em sequ\u00eancias de sa\u00edda de dimens\u00e3o $d_{model}$. Tamb\u00e9m utilizamos uma camada linear e uma fun\u00e7\u00e3o de softmax na sa\u00edda do decodificador para predizer a probabilidade do pr\u00f3ximo token na sequ\u00eancia.\n\nEm nosso modelo, n\u00f3s compartilhamos as mesmas matrizes ?intermedi\u00e1rias? (`weight matrix`) entre as duas camadas de representa\u00e7\u00f5es e a camada linear de softmax. Na camada de representa\u00e7\u00e3o, n\u00f3s multiplicamos os valores intermedi\u00e1rios por $\\sqrt{d_{model}}$\n\n\n```python\nclass Embeddings(nn.Module):\n    def __init__(self, d_model, vocab):\n        super(Embeddings, self).__init__()\n        self.lut = nn.Embedding(vocab, d_model)\n        self.d_model = d_model\n\n    def forward(self, x):\n        return self.lut(x) * math.sqrt(self.d_model)\n```\n\n## Vetor de Posi\u00e7\u00e3o\n\nNosso modelo n\u00e3o cont\u00e9m nenhuma recorr\u00eancia ou convolu\u00e7\u00e3o. Entretanto, precisamos utilizar informa\u00e7\u00f5es sobre a ordem dos tokens na sequ\u00eancia. Para isto, precisamos inferir algo como a posi\u00e7\u00e3o relativa ou absoluta de um token em nossa sequ\u00eancia de entrada.\n\nPara isto, n\u00f3s adicionamos vetores posicionais aos vetores de entrada de nossos codificadores e decodificadores. Estes vetores posicionais tem a mesma dimensionalidade dos vetores de entrada de modo que eles possam ser somados. \n\nNeste artigo, s\u00e3o utilizados duas fun\u00e7\u00f5es de diferentes frequ\u00eancias:\n\n\\begin{equation}\n    PE(pos, 2i) = sin(pos/10000^{2i/d_{model}})\n    \\\\\n    PE(pos, 2i+1) = cos(pos/10000^{2i/d_{model}})\n\\end{equation}\n\nOnde $pos$ \u00e9 a i-\u00e9sima posi\u00e7\u00e3o de um token na sequ\u00eancia. `Mais detalhes no artigo.`\n\n\n\n\n```python\nclass PositionalEncoding(nn.Module):\n    \"Implement the PE function.\"\n    def __init__(self, d_model, dropout, max_len=5000):\n        super(PositionalEncoding, self).__init__()\n        self.dropout = nn.Dropout(p=dropout)\n        \n        # Compute the positional encodings once in log space.\n        pe = torch.zeros(max_len, d_model)\n        \n        # https://stackoverflow.com/questions/52922445/runtimeerror-exp-not-implemented-for-torch-longtensor\n        # Pequeno fix no artigo original devido ao problema acima\n        position = torch.arange(0., max_len).unsqueeze(1)\n        div_term = torch.exp(torch.arange(0., d_model, 2) * -(math.log(10000.0) / d_model))\n        pe[:, 0::2] = torch.sin(position * div_term)\n        pe[:, 1::2] = torch.cos(position * div_term)\n        pe = pe.unsqueeze(0)\n        self.register_buffer('pe', pe)\n        \n    def forward(self, x):\n        x = x + Variable(self.pe[:, :x.size(1)], \n                         requires_grad=False)\n        return self.dropout(x)\n```\n\n___\n> **nota pessoal:** Eu preferi abstrair toda a discuss\u00e3o sobre as fun\u00e7\u00f5es de seno e cosseno. Intuitivamente, basta que voc\u00ea compreenda que eu preciso codificar a posi\u00e7\u00e3o do token na sequ\u00eancia. Isto n\u00e3o pode ser feito de forma hard-coded utilizando apenas um \u00edndice $i$ porque as posi\u00e7\u00f5es relativas ter\u00e3o $i$s que conflitar\u00e3o. Al\u00e9m disso, no final a rede \u00e9 apenas uma sequ\u00eancia de fun\u00e7\u00f5es que s\u00e3o utilizadas para computar as probabilidades. Sendo assim, precisamos de uma fun\u00e7\u00e3o que codifique a posi\u00e7\u00e3o dos tokens.\n\n> Dado um valor suficientemente grande, i.e. 10000.0, se utilizarmos $i$ como a pot\u00eancia deste valor e duas fun\u00e7\u00f5es distintas para $i$s pares ou \u00edmpares, \u00e9 prov\u00e1vel que as posi\u00e7\u00f5es nunca colidam. \n___\n\nA intui\u00e7\u00e3o acima \u00e9 exemplificada plotando as fun\u00e7\u00f5es de seno e cosseno (nesse caso com $d_{model} = 20$):\n\n\n```python\nplt.figure(figsize=(15, 5))\npe = PositionalEncoding(20, 0)\ny = pe.forward(Variable(torch.zeros(1, 100, 20)))\nplt.plot(np.arange(100), y[0, :, 4:8].data.numpy())\nplt.legend([\"dim %d\"%p for p in [4,5,6,7]])\nNone\n```\n\n## Modelo Completo\n\nPara o modelo completo, precisamos definir uma fun\u00e7\u00e3o que recebe hiper-par\u00e2metros de entrada e produz, como sa\u00edda, o nosso modelo.\n\nRelembrando todos os par\u00e2metros de entrada:\n\n`EncoderDecoder(encoder, decoder, src_embed, tgt_embed, generator)`\n\nonde:\n\n* `Encoder(layer, N)` \n   * `EncoderLayer(size, self_attn, feed_forward, dropout)`\n\n\n* `Decoder(layer, N)`\n   * `DecoderLayer(size, self_attn, src_attn, feed_forward, dropout)`\n   \n\n\n```python\ndef make_model(src_vocab, tgt_vocab, N=6, \n               d_model=512, d_ff=2048, h=8, dropout=0.1):\n    \"Helper: Construct a model from hyperparameters.\"\n    c = copy.deepcopy\n    \n    # mecanismos utilizados tanto no encoder quanto decoder\n    attn = MultiHeadedAttention(h, d_model) # mecanismo de aten\u00e7\u00e3o m\u00faltipla\n    ff = PositionwiseFeedForward(d_model, d_ff, dropout) # feed forward\n    position = PositionalEncoding(d_model, dropout) # vetores posicionais\n    \n    model = EncoderDecoder(\n        Encoder(EncoderLayer(d_model, c(attn), c(ff), dropout), N),\n        Decoder(DecoderLayer(d_model, c(attn), c(attn), \n                             c(ff), dropout), N),\n        nn.Sequential(Embeddings(d_model, src_vocab), c(position)),\n        nn.Sequential(Embeddings(d_model, tgt_vocab), c(position)),\n        Generator(d_model, tgt_vocab))\n    \n    # This was important from their code. \n    # Initialize parameters with Glorot / fan_avg.\n    for p in model.parameters():\n        if p.dim() > 1:\n            nn.init.xavier_uniform(p)\n    return model\n```\n\n> **nota pessoal:** phew! Se voc\u00ea leu tudo at\u00e9 aqui, obrigado pelo esfor\u00e7o e paci\u00eancia. \n\n\n```python\n# Small example model.\ntmp_model = make_model(10, 10, 2)\nNone\n```\n\n# Treino\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n## Batches e obfusca\u00e7\u00e3o\n\n\n```python\nclass Batch:\n    \"Object for holding a batch of data with mask during training.\"\n    def __init__(self, src, trg=None, pad=0):\n        self.src = src\n        self.src_mask = (src != pad).unsqueeze(-2)\n        if trg is not None:\n            self.trg = trg[:, :-1]\n            self.trg_y = trg[:, 1:]\n            self.trg_mask = \\\n                self.make_std_mask(self.trg, pad)\n            self.ntokens = (self.trg_y != pad).data.sum()\n    \n    @staticmethod\n    def make_std_mask(tgt, pad):\n        \"Create a mask to hide padding and future words.\"\n        tgt_mask = (tgt != pad).unsqueeze(-2)\n        tgt_mask = tgt_mask & Variable(\n            subsequent_mask(tgt.size(-1)).type_as(tgt_mask.data))\n        return tgt_mask\n```\n\n## Loop de treino\n\n\n```python\ndef run_epoch(data_iter, model, loss_compute):\n    \"Standard Training and Logging Function\"\n    start = time.time()\n    total_tokens = 0\n    total_loss = 0\n    tokens = 0\n    for i, batch in enumerate(data_iter):\n        out = model.forward(batch.src, batch.trg, \n                            batch.src_mask, batch.trg_mask)\n        loss = loss_compute(out, batch.trg_y, batch.ntokens)\n        total_loss += loss\n        total_tokens += batch.ntokens\n        tokens += batch.ntokens\n        if i % 50 == 1:\n            elapsed = time.time() - start\n            print(\"Epoch Step: %d Loss: %f Tokens per Sec: %f\" %\n                    (i, loss / batch.ntokens, tokens / elapsed))\n            start = time.time()\n            tokens = 0\n    return total_loss / total_tokens\n```\n\n\n```python\n\n```\n\n## Training Data and Batching\n\n\n```python\nglobal max_src_in_batch, max_tgt_in_batch\ndef batch_size_fn(new, count, sofar):\n    \"Keep augmenting batch and calculate total number of tokens + padding.\"\n    global max_src_in_batch, max_tgt_in_batch\n    if count == 1:\n        max_src_in_batch = 0\n        max_tgt_in_batch = 0\n    max_src_in_batch = max(max_src_in_batch,  len(new.src))\n    max_tgt_in_batch = max(max_tgt_in_batch,  len(new.trg) + 2)\n    src_elements = count * max_src_in_batch\n    tgt_elements = count * max_tgt_in_batch\n    return max(src_elements, tgt_elements)\n```\n\n## Hardware\n\n\n```python\n\n```\n\n## Optimizer\n\n\n```python\nclass NoamOpt:\n    \"Optim wrapper that implements rate.\"\n    def __init__(self, model_size, factor, warmup, optimizer):\n        self.optimizer = optimizer\n        self._step = 0\n        self.warmup = warmup\n        self.factor = factor\n        self.model_size = model_size\n        self._rate = 0\n        \n    def step(self):\n        \"Update parameters and rate\"\n        self._step += 1\n        rate = self.rate()\n        for p in self.optimizer.param_groups:\n            p['lr'] = rate\n        self._rate = rate\n        self.optimizer.step()\n        \n    def rate(self, step = None):\n        \"Implement `lrate` above\"\n        if step is None:\n            step = self._step\n        return self.factor * \\\n            (self.model_size ** (-0.5) *\n            min(step ** (-0.5), step * self.warmup ** (-1.5)))\n        \ndef get_std_opt(model):\n    return NoamOpt(model.src_embed[0].d_model, 2, 4000,\n            torch.optim.Adam(model.parameters(), lr=0, betas=(0.9, 0.98), eps=1e-9))\n```\n\n\n```python\n\n```\n\n\n```python\n# Three settings of the lrate hyperparameters.\nopts = [NoamOpt(512, 1, 4000, None), \n        NoamOpt(512, 1, 8000, None),\n        NoamOpt(256, 1, 4000, None)]\nplt.plot(np.arange(1, 20000), [[opt.rate(i) for opt in opts] for i in range(1, 20000)])\nplt.legend([\"512:4000\", \"512:8000\", \"256:4000\"])\nNone\n```\n\n\n```python\n\n```\n\n## Regulariza\u00e7\u00e3o\n\n\n```python\nclass LabelSmoothing(nn.Module):\n    \"Implement label smoothing.\"\n    def __init__(self, size, padding_idx, smoothing=0.0):\n        super(LabelSmoothing, self).__init__()\n        self.criterion = nn.KLDivLoss(size_average=False)\n        self.padding_idx = padding_idx\n        self.confidence = 1.0 - smoothing\n        self.smoothing = smoothing\n        self.size = size\n        self.true_dist = None\n        \n    def forward(self, x, target):\n        assert x.size(1) == self.size\n        true_dist = x.data.clone()\n        true_dist.fill_(self.smoothing / (self.size - 2))\n        true_dist.scatter_(1, target.data.unsqueeze(1), self.confidence)\n        true_dist[:, self.padding_idx] = 0\n        mask = torch.nonzero(target.data == self.padding_idx)\n        if mask.dim() > 0:\n            true_dist.index_fill_(0, mask.squeeze(), 0.0)\n        self.true_dist = true_dist\n        return self.criterion(x, Variable(true_dist, requires_grad=False))\n```\n\n\n```python\n\n```\n\n\n```python\n# Example of label smoothing.\ncrit = LabelSmoothing(5, 0, 0.4)\npredict = torch.FloatTensor([[0, 0.2, 0.7, 0.1, 0],\n                             [0, 0.2, 0.7, 0.1, 0], \n                             [0, 0.2, 0.7, 0.1, 0]])\nv = crit(Variable(predict.log()), \n         Variable(torch.LongTensor([2, 1, 0])))\n\n# Show the target distributions expected by the system.\nplt.imshow(crit.true_dist)\nNone\n```\n\n\n```python\n\n```\n\n\n```python\ncrit = LabelSmoothing(5, 0, 0.1)\ndef loss(x):\n    d = x + 3 * 1\n    predict = torch.FloatTensor([[0, x / d, 1 / d, 1 / d, 1 / d],\n                                 ])\n    #checar -- https://github.com/NVIDIA/flownet2-pytorch/issues/113    \n    return crit(Variable(predict.log()),\n                 Variable(torch.LongTensor([1]))).data\nplt.plot(np.arange(1, 100), [loss(x) for x in range(1, 100)])\nNone\n```\n\n# Exemplo Inicial\n\n## Dados sint\u00e9ticos\n\n\n```python\ndef data_gen(V, batch, nbatches):\n    \"Generate random data for a src-tgt copy task.\"\n    for i in range(nbatches):\n        data = torch.from_numpy(np.random.randint(1, V, size=(batch, 10)))\n        data[:, 0] = 1\n        src = Variable(data, requires_grad=False)\n        tgt = Variable(data, requires_grad=False)\n        yield Batch(src, tgt, 0)\n```\n\n\n```python\nclass SimpleLossCompute:\n    \"A simple loss compute and train function.\"\n    def __init__(self, generator, criterion, opt=None):\n        self.generator = generator\n        self.criterion = criterion\n        self.opt = opt\n        \n    def __call__(self, x, y, norm):\n        x = self.generator(x)\n        loss = self.criterion(x.contiguous().view(-1, x.size(-1)), \n                              y.contiguous().view(-1)) / norm\n        loss.backward()\n        if self.opt is not None:\n            self.opt.step()\n            self.opt.optimizer.zero_grad()\n        return loss.data * norm\n```\n\n\n```python\n# Train the simple copy task.\nV = 11\ncriterion = LabelSmoothing(size=V, padding_idx=0, smoothing=0.0)\nmodel = make_model(V, V, N=2)\nmodel_opt = NoamOpt(model.src_embed[0].d_model, 1, 400,\n        torch.optim.Adam(model.parameters(), lr=0, betas=(0.9, 0.98), eps=1e-9))\n\nfor epoch in range(10):\n    model.train()\n    run_epoch(data_gen(V, 30, 20), model, \n              SimpleLossCompute(model.generator, criterion, model_opt))\n    model.eval()\n    print(run_epoch(data_gen(V, 30, 5), model, \n                    SimpleLossCompute(model.generator, criterion, None)))\n```\n\n\n```python\ndef greedy_decode(model, src, src_mask, max_len, start_symbol):\n    memory = model.encode(src, src_mask)\n    ys = torch.ones(1, 1).fill_(start_symbol).type_as(src.data)\n    for i in range(max_len-1):\n        out = model.decode(memory, src_mask, \n                           Variable(ys), \n                           Variable(subsequent_mask(ys.size(1))\n                                    .type_as(src.data)))\n        prob = model.generator(out[:, -1])\n        _, next_word = torch.max(prob, dim = 1)\n        next_word = next_word.data[0]\n        ys = torch.cat([ys, \n                        torch.ones(1, 1).type_as(src.data).fill_(next_word)], dim=1)\n    return ys\n\nmodel.eval()\nsrc = Variable(torch.LongTensor([[1,2,3,4,5,6,7,8,9,10]]) )\nsrc_mask = Variable(torch.ones(1, 1, 10) )\nprint(greedy_decode(model, src, src_mask, max_len=10, start_symbol=1))\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n## Outras refer\u00eancias:\n\n* [Jay Alammar blog](http://jalammar.github.io/illustrated-transformer/)\n* [The transformer neural network](https://ai.googleblog.com/2017/08/transformer-novel-neural-network.html)\n", "meta": {"hexsha": "e616bf7829e4d2fa4c3c4c888c2a6c5150c8fc57", "size": 203219, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "attention-is-all-you-need/atencao-eh-tudo-que-vc-precisa.ipynb", "max_stars_repo_name": "marquesarthur/tensorflow-brasil", "max_stars_repo_head_hexsha": "037a32feafd2d80046e850120c88f81b177ea7fc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-30T08:47:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-30T08:47:03.000Z", "max_issues_repo_path": "attention-is-all-you-need/atencao-eh-tudo-que-vc-precisa.ipynb", "max_issues_repo_name": "marquesarthur/tensorflow-brasil", "max_issues_repo_head_hexsha": "037a32feafd2d80046e850120c88f81b177ea7fc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "attention-is-all-you-need/atencao-eh-tudo-que-vc-precisa.ipynb", "max_forks_repo_name": "marquesarthur/tensorflow-brasil", "max_forks_repo_head_hexsha": "037a32feafd2d80046e850120c88f81b177ea7fc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 154.3044798785, "max_line_length": 95188, "alphanum_fraction": 0.8759072724, "converted": true, "num_tokens": 8403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2628418489200747, "lm_q2_score": 0.06560483152162024, "lm_q1q2_score": 0.01724369521523266}}
{"text": "# nbconvert latex test\n\n**Lorem ipsum** dolor sit amet, consectetur adipiscing elit. Nunc luctus bibendum felis dictum sodales. Ut suscipit, orci ut interdum imperdiet, purus ligula mollis *justo*, non malesuada nisl augue eget lorem. Donec bibendum, erat sit amet porttitor aliquam, urna lorem ornare libero, in vehicula diam diam ut ante. Nam non urna rhoncus, accumsan elit sit amet, mollis tellus. Vestibulum nec tellus metus. Vestibulum tempor, ligula et vehicula rhoncus, sapien turpis faucibus lorem, id dapibus turpis mauris ac orci. Sed volutpat vestibulum venenatis.\n\n$\\LaTeX ~ \\TeX$\n\nThis is a test list:\n\n1. item 1\n   - subitem 1\n   - subitem 2\n2. item 2\n3. item 3\n\n## Printed Using Python\n\n\n```python\nnext_paragraph = \"\"\"\nAenean vitae diam consectetur, tempus arcu quis, ultricies urna. Vivamus venenatis sem \nquis orci condimentum, sed feugiat dui porta.\n\"\"\"\n\ndef identity_dec(ob):\n    return ob\n\n@identity_dec\ndef nifty_print(text):\n    \"\"\"Used to test syntax highlighting\"\"\"\n    \n    print(text * 2)\n\nnifty_print(next_paragraph)\n```\n\n    \n    Aenean vitae diam consectetur, tempus arcu quis, ultricies urna. Vivamus venenatis sem \n    quis orci condimentum, sed feugiat dui porta.\n    \n    Aenean vitae diam consectetur, tempus arcu quis, ultricies urna. Vivamus venenatis sem \n    quis orci condimentum, sed feugiat dui porta.\n    \n\n\n## Pyout (and Text Wrapping)\n\n\n```python\nText = \"\"\"\nAliquam blandit aliquet enim, eget scelerisque eros adipiscing quis. Nunc sed metus \nut lorem condimentum condimentum nec id enim. Sed malesuada cursus hendrerit. Praesent \net commodo justo. Interdum et malesuada fames ac ante ipsum primis in faucibus. \nCurabitur et magna ante. Proin luctus tellus sit amet egestas laoreet. Sed dapibus \nneque ac nulla mollis cursus. Fusce mollis egestas libero mattis facilisis.\n\"\"\"\nText #Use print(Text) instead to get text wrapping in pdf\n```\n\n\n\n\n    '\\nAliquam blandit aliquet enim, eget scelerisque eros adipiscing quis. Nunc sed metus \\nut lorem condimentum condimentum nec id enim. Sed malesuada cursus hendrerit. Praesent \\net commodo justo. Interdum et malesuada fames ac ante ipsum primis in faucibus. \\nCurabitur et magna ante. Proin luctus tellus sit amet egestas laoreet. Sed dapibus \\nneque ac nulla mollis cursus. Fusce mollis egestas libero mattis facilisis.\\n'\n\n\n\n\n```python\nprint(Text)\n```\n\n    \n    Aliquam blandit aliquet enim, eget scelerisque eros adipiscing quis. Nunc sed metus \n    ut lorem condimentum condimentum nec id enim. Sed malesuada cursus hendrerit. Praesent \n    et commodo justo. Interdum et malesuada fames ac ante ipsum primis in faucibus. \n    Curabitur et magna ante. Proin luctus tellus sit amet egestas laoreet. Sed dapibus \n    neque ac nulla mollis cursus. Fusce mollis egestas libero mattis facilisis.\n    \n\n\n\n```python\nimport numpy as np\n\na = np.random.rand(10,10)\nprint(a)\na\n```\n\n    [[0.28568166 0.8747998  0.87645362 0.51011938 0.06167899 0.6253242\n      0.21695898 0.35406203 0.76399062 0.38721428]\n     [0.59226394 0.23033422 0.11576507 0.0131951  0.34366223 0.96629731\n      0.2867491  0.95194302 0.60324146 0.55986092]\n     [0.36955543 0.78864789 0.73933855 0.39474922 0.74616752 0.9144543\n      0.88600249 0.42611302 0.49375306 0.4260594 ]\n     [0.40550295 0.85035162 0.5525894  0.21827199 0.67949174 0.93909704\n      0.0331135  0.27240638 0.39332899 0.19852766]\n     [0.32876315 0.97305405 0.11060386 0.20685979 0.3897287  0.01538051\n      0.44747911 0.99865014 0.89374066 0.5141975 ]\n     [0.10450336 0.42284722 0.95628045 0.32792639 0.11370905 0.32150692\n      0.28631773 0.58203321 0.21240863 0.87954985]\n     [0.62257223 0.79092658 0.72718477 0.0039627  0.61581427 0.28007586\n      0.4653752  0.24737437 0.97801711 0.31160009]\n     [0.03592867 0.56885907 0.05229575 0.12322391 0.45236765 0.98892923\n      0.15013782 0.81404334 0.71795481 0.60145161]\n     [0.01582381 0.23420526 0.18574213 0.6497537  0.71730148 0.0068443\n      0.32733317 0.81837686 0.58895758 0.37633478]\n     [0.64226276 0.77550803 0.23729951 0.9287232  0.14250076 0.23955818\n      0.70490581 0.84959453 0.46939408 0.01230405]]\n\n\n\n\n\n    array([[0.28568166, 0.8747998 , 0.87645362, 0.51011938, 0.06167899,\n            0.6253242 , 0.21695898, 0.35406203, 0.76399062, 0.38721428],\n           [0.59226394, 0.23033422, 0.11576507, 0.0131951 , 0.34366223,\n            0.96629731, 0.2867491 , 0.95194302, 0.60324146, 0.55986092],\n           [0.36955543, 0.78864789, 0.73933855, 0.39474922, 0.74616752,\n            0.9144543 , 0.88600249, 0.42611302, 0.49375306, 0.4260594 ],\n           [0.40550295, 0.85035162, 0.5525894 , 0.21827199, 0.67949174,\n            0.93909704, 0.0331135 , 0.27240638, 0.39332899, 0.19852766],\n           [0.32876315, 0.97305405, 0.11060386, 0.20685979, 0.3897287 ,\n            0.01538051, 0.44747911, 0.99865014, 0.89374066, 0.5141975 ],\n           [0.10450336, 0.42284722, 0.95628045, 0.32792639, 0.11370905,\n            0.32150692, 0.28631773, 0.58203321, 0.21240863, 0.87954985],\n           [0.62257223, 0.79092658, 0.72718477, 0.0039627 , 0.61581427,\n            0.28007586, 0.4653752 , 0.24737437, 0.97801711, 0.31160009],\n           [0.03592867, 0.56885907, 0.05229575, 0.12322391, 0.45236765,\n            0.98892923, 0.15013782, 0.81404334, 0.71795481, 0.60145161],\n           [0.01582381, 0.23420526, 0.18574213, 0.6497537 , 0.71730148,\n            0.0068443 , 0.32733317, 0.81837686, 0.58895758, 0.37633478],\n           [0.64226276, 0.77550803, 0.23729951, 0.9287232 , 0.14250076,\n            0.23955818, 0.70490581, 0.84959453, 0.46939408, 0.01230405]])\n\n\n\n### Image\n\n\n```python\nfrom IPython.core.display import Image\nImage(data=\"http://ipython.org/_static/IPy_header.png\")\n```\n\n\n```python\nprint('text')\n```\n\n    text\n\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\n```\n\n\n```python\nx = np.arange(1,100)\ny = np.sin(x)\nplt.plot(x,y)\nplt.show()\n```\n\n### Operator Highlighing Check\n\n\n```python\n#This is a comment with an operation x @ y in it.\ntest = 5**9 + 2 - x@ y / (7 % 2) + True * 7\nprint(test)\n\na = set([1,2,3,4,5,6,7,8,9,0])\nb = set([2,4,6,8,0])\na & b\n```\n\n    1953188.1556827284\n\n\n\n\n\n    {0, 2, 4, 6, 8}\n\n\n\n#### Pandas Output\n\nHere we test the output of **Pandas**\n\nFirst a *markdown* table:\n\nColumn 1 | Column 2\n---------|-----------\n 1       | 3\n~~a~~    | b\n        4| & \n\n#### Pandas\n\n\n```python\nimport pandas as pd\npd.DataFrame(np.random.randn(10,3))\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>0</th>\n      <th>1</th>\n      <th>2</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>-1.565342</td>\n      <td>-0.260043</td>\n      <td>-1.427162</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>-0.267812</td>\n      <td>1.022688</td>\n      <td>-0.268030</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.104852</td>\n      <td>0.415075</td>\n      <td>0.958796</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.210758</td>\n      <td>-0.500437</td>\n      <td>-1.584460</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>-0.754263</td>\n      <td>-2.317940</td>\n      <td>-0.384726</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>-0.062044</td>\n      <td>-0.804551</td>\n      <td>0.914101</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>-2.193517</td>\n      <td>2.356933</td>\n      <td>0.542824</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>-1.246683</td>\n      <td>0.981807</td>\n      <td>-0.216905</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>-0.784741</td>\n      <td>-0.647911</td>\n      <td>0.134776</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>0.008086</td>\n      <td>1.652312</td>\n      <td>-0.468785</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n##### Sympy output\n\n\n```python\nimport sympy\nfrom sympy.abc import x, n, m\nsympy.init_printing()\ntheta = sympy.Symbol('theta')\nphi = sympy.Symbol('phi')\n\nsympy.simplify(sympy.Ynm(n,m,theta,phi).expand(func=True))\n```\n\nx + y as plain text.\n\n$\\frac{P_{n}^{\\left(m\\right)}\\left(\\cos{\\left (\\theta \\right )}\\right)}{2 \\sqrt{\\pi}} \\sqrt{\\frac{\\left(- m + n\\right)!}{\\left(m + n\\right)!} \\left(2 n + 1\\right)} e^{i m \\phi}$\n\n##### Line Length\n\n\n```python\n1 3 5 7 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99 103\n```\n", "meta": {"hexsha": "7661622747b3eaf61a4b42a72a44f270c11bb83f", "size": 70659, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "example/test.ipynb", "max_stars_repo_name": "t-makaro/nb_pdf_template", "max_stars_repo_head_hexsha": "274420de58e33ea467a17f8ee5cb0c99090fd712", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 132, "max_stars_repo_stars_event_min_datetime": "2018-01-02T13:19:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T16:38:38.000Z", "max_issues_repo_path": "example/test.ipynb", "max_issues_repo_name": "t-makaro/nbconvert_pdf_template", "max_issues_repo_head_hexsha": "274420de58e33ea467a17f8ee5cb0c99090fd712", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2018-01-05T11:43:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-13T17:26:55.000Z", "max_forks_repo_path": "example/test.ipynb", "max_forks_repo_name": "t-makaro/nbconvert_pdf_template", "max_forks_repo_head_hexsha": "274420de58e33ea467a17f8ee5cb0c99090fd712", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2018-04-15T08:07:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T23:44:16.000Z", "avg_line_length": 128.0054347826, "max_line_length": 39224, "alphanum_fraction": 0.8617019771, "converted": true, "num_tokens": 3362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18242551491653522, "lm_q2_score": 0.09401017517449256, "lm_q1q2_score": 0.017149854613600482}}
{"text": "## Initial setup\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```python\nimport tensorflow as tf\nprint(tf.__version__)\nimport torch\nprint(torch.__version__)\nimport matplotlib\nprint(matplotlib.__version__)\n```\n\n    2.8.0\n    1.10.0+cu111\n    3.2.2\n\n\n\n```python\n!nvidia-smi\n```\n\n    Fri Jan 21 19:41:32 2022       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 495.46       Driver Version: 460.32.03    CUDA Version: 11.2     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   34C    P8     9W /  70W |      0MiB / 15109MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    |  No running processes found                                                 |\n    +-----------------------------------------------------------------------------+\n\n\n\n```python\n# Other imports\n! pip install tensorflow_addons\n! pip install tensorflow_io\n\nimport os\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import *\nfrom keras.callbacks import Callback, EarlyStopping, ModelCheckpoint\nfrom tensorflow.keras.applications.resnet50 import preprocess_input\nfrom tensorflow.keras.preprocessing.image import load_img\n\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfrom matplotlib.offsetbox import OffsetImage, AnnotationBbox\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter, AutoMinorLocator\nfrom imutils import paths\nfrom tqdm import tqdm\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nimport tensorflow_datasets as tfds\nimport tensorflow_io as tfio\nimport tensorflow_hub as hub\nimport numpy as np\nimport cv2\nimport pandas as pd\nimport seaborn as sns\nfrom scipy.stats import mannwhitneyu\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.cluster import KMeans\nimport sklearn.manifold\nfrom sklearn.metrics.pairwise import cosine_similarity as cos\nfrom sympy.utilities.iterables import multiset_permutations\nfrom sklearn.metrics import accuracy_score, f1_score,precision_score, recall_score, roc_auc_score, confusion_matrix\nfrom sklearn.model_selection import *\nfrom sklearn.preprocessing import StandardScaler\nfrom IPython.display import Image, display\n\n\nimport zipfile\nimport concurrent.futures\n\n# Random seed fix\nrandom_seed = 42\ntf.random.set_seed(random_seed)\nnp.random.seed(random_seed)\n```\n\n    Collecting tensorflow_addons\n      Downloading tensorflow_addons-0.16.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.1 MB 6.4 MB/s \n    \u001b[?25hRequirement already satisfied: typeguard>=2.7 in /usr/local/lib/python3.7/dist-packages (from tensorflow_addons) (2.7.1)\n    Installing collected packages: tensorflow-addons\n    Successfully installed tensorflow-addons-0.16.1\n    Collecting tensorflow_io\n      Downloading tensorflow_io-0.24.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (23.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 23.4 MB 1.8 MB/s \n    \u001b[?25hRequirement already satisfied: tensorflow-io-gcs-filesystem==0.24.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow_io) (0.24.0)\n    Installing collected packages: tensorflow-io\n    Successfully installed tensorflow-io-0.24.0\n\n\n## Dataset gathering and preparation\n\n\n```python\n%cd /content/drive/MyDrive/nanowire-morphology-classification-project\n```\n\n\n```python\ntraining_batch_size = 4\n\nBATCH_SIZE = training_batch_size\n\nimageSize = 224\n\ncategory_names = ['bundle', 'dispersed', 'network', 'singular']\ncolor_method = ['C0', 'C1', 'C2', 'C3', 'C4']\ncolor = ['black', 'magenta', 'cyan', 'yellow']\nmarker = ['o', 's', '<', '>', '^']\nseaborn_palette = sns.color_palette(\"colorblind\")\n```\n\n\n```python\nnp.random.seed(random_seed)\npeptide_morph_train_path = \"/content/drive/MyDrive/TEM image datasets/2022-nanowire-morphology\"\npeptide_morph_images_train = list(paths.list_files(basePath=peptide_morph_train_path, validExts='jpg'))\npeptide_morph_images_train = np.random.choice(np.array(peptide_morph_images_train), len(peptide_morph_images_train), replace=False)\nprint(len(peptide_morph_images_train))\n```\n\n    400\n\n\n\n```python\ntrain_labels = []\nfor i in range(peptide_morph_images_train.shape[0]):\n  train_label = peptide_morph_images_train[i].split(\"/\")[-2]\n  train_labels.append(train_label)\nle = LabelEncoder()\npeptide_morph_train_enc = le.fit_transform(train_labels)\n```\n\n\n```python\n# Image preprocessing utils\n@tf.function\ndef parse_images(image_path):\n    image_string = tf.io.read_file(image_path)\n    image = tf.image.decode_jpeg(image_string, channels=3)\n    # image = tfio.experimental.image.decode_tiff(image_string)[:, :, :3]   # in the doc, it transforms tiff to 4 channels, with additional channel of opacity which is not needed.\n    image = tf.image.convert_image_dtype(image, tf.float32)\n    image = tf.image.resize(image, size=[imageSize, imageSize])\n\n    return image\n```\n\n\n```python\ntrain_ds = tf.data.Dataset.from_tensor_slices(peptide_morph_images_train)\ntrain_ds = (\n    train_ds\n    .map(parse_images, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n    # .shuffle(200)\n    .batch(training_batch_size\n          #  , drop_remainder=True\n           )\n    .prefetch(tf.data.experimental.AUTOTUNE)\n)\n\ndatagen = tf. keras.preprocessing.image.ImageDataGenerator(preprocessing_function=tf.keras.applications.resnet50.preprocess_input)\n```\n\n\n```python\nnp.random.seed(random_seed)\npeptide_morph_seglabel_train_path = \"/content/drive/MyDrive/TEM image datasets/2022-nanowire-morphology\"\npeptide_morph_images_train_seglabel = list(paths.list_files(basePath=peptide_morph_seglabel_train_path, validExts='png'))\npeptide_morph_images_train_seglabel = np.random.choice(np.array(peptide_morph_images_train_seglabel), len(peptide_morph_images_train_seglabel), replace=False)\nprint(len(peptide_morph_images_train_seglabel))\n```\n\n\n```python\ndef generate_ground_truth_images(image, resolution):\n  image_bool = np.ones((resolution, resolution))\n  for i in range(image.shape[0]):\n    for j in range(image.shape[1]):\n      if image[i, j, 1] == image[i, j, 2]:\n        image_bool[i, j] = 0            # background is black with code of 0\n      else: \n        image_bool[i, j] = 1            # nanowire is white with code of 1\n  return image_bool\n```\n\n\n```python\nsegmentation_class_labels = []\nfor i in range(peptide_morph_images_train_seglabel.shape[0]):\n  seg_class_label = peptide_morph_images_train_seglabel[i].split(\"/\")[-2]\n  segmentation_class_labels.append(seg_class_label)\nle = LabelEncoder()\npeptide_morph_train_seg_enc = le.fit_transform(segmentation_class_labels)\n```\n\n\n```python\n# image_mask = np.zeros((len(peptide_morph_images_train_seglabel), imageSize, imageSize))\nimages_no_annotation_directory = []\nimages_no_annotation = np.zeros((len(peptide_morph_images_train_seglabel), imageSize, imageSize, 3))\n\nfor i in range(len(peptide_morph_images_train_seglabel)):\n  images_no_annotation_directory.append('%s.jpg' % (peptide_morph_images_train_seglabel[i].split(\"_\")[0] + \"_\" + peptide_morph_images_train_seglabel[i].split(\"_\")[1]))\n  images_no_annotation[i] = parse_images(images_no_annotation_directory[i])\n\n  # these were used to create the ground truth grayscale images from the manual segmentation labels.\n  # image_string = tf.io.read_file(peptide_morph_images_train_seglabel[i])\n  # image = tf.image.decode_image(image_string, channels=3) / 255\n  # image = tf.image.resize(image, (imageSize, imageSize))\n  # image = tf.image.convert_image_dtype(image, tf.float32)\n  # trans_nd_image_array = image.numpy()\n  # image_mask[i] = generate_ground_truth_images(trans_nd_image_array, imageSize)\n  \n# np.savez_compressed('seg_mask_res512.npz', mask=image_mask)\n\n# once we have the seg_mask saved, we can directly load from npz file\nimage_mask = np.load('seg_mask_res%i.npz' % (imageSize), allow_pickle=True)['mask']\n```\n\n## Initiate self-supervised models\n\n\n```python\nResnet50_transfer = tf.keras.applications.ResNet50(\n    include_top=False,\n    weights=\"imagenet\",\n    input_tensor=None,\n    input_shape=(imageSize, imageSize, 3), \n    pooling=None,\n)\n\nResnet50_transfer.trainable = False\n```\n\n    Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/resnet/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5\n    94773248/94765736 [==============================] - 1s 0us/step\n    94781440/94765736 [==============================] - 1s 0us/step\n\n\n\n```python\n# Resnet as backbone\ndef get_resnet_self_supervise_model(hidden_1, hidden_2, hidden_3):\n    base_model = Resnet50_transfer\n    base_model.trainable = True\n    inputs = Input((imageSize, imageSize, 3))\n    h = base_model(inputs, training=True)\n    h = GlobalAveragePooling2D()(h)\n\n    projection_1 = Dense(hidden_1)(h)                                        \n    projection_1 = Activation(\"relu\")(projection_1)\n    projection_1 = BatchNormalization(epsilon=0.001)(projection_1)\n    # projection_1 = Dropout(rate=0.5)(projection_1)\n    projection_2 = Dense(hidden_2)(projection_1)\n    projection_2 = Activation(\"relu\")(projection_2)\n    projection_2 = BatchNormalization(epsilon=0.001)(projection_2)\n    # projection_2 = Dropout(rate=0.5)(projection_2)\n    projection_3 = Dense(hidden_3)(projection_2)\n    projection_3 = BatchNormalization(epsilon=0.001)(projection_3)\n    # projection_3 = Dropout(rate=0.5)(projection_3)\n\n    resnet_model = Model(inputs, projection_3)\n    \n    return resnet_model\n```\n\n## Initiate downstream classification model\n\n\n```python\ndef get_linear_model(features):                                                                                  \n    linear_model = Sequential([                                                                                  \n\t\t\t                              Input(shape=(features,)),\n\t\t                                Dense(4, activation=\"softmax\")])\n    return linear_model\n```\n\n## One-shot learning and tsne visualizations\n\n\n\n```python\ndef visualize_scatter_with_images(X_2d_data, images_directory, true_label, ax, image_zoom=1, boxthickness=2):\n\n    for xy, i, label in zip(X_2d_data, images_directory, true_label):\n        x0, y0 = xy\n        img = parse_images(i)\n        img = OffsetImage(img, zoom=image_zoom)\n        ab = AnnotationBbox(img, (x0, y0), xycoords='data', frameon=True,\n                            bboxprops =dict(edgecolor=color[label], lw=boxthickness), pad=1)\n        artists.append(ax.add_artist(ab))\n    ax.update_datalim(X_2d_data)\n```\n\n\n```python\ndef visualize_anchor_images(X_2d_data, images_directory, true_label, ax, image_zoom=1, boxthickness=2):\n\n    for xy, i, label in zip(X_2d_data, images_directory, true_label):\n        x0, y0 = xy\n        img = parse_images(i)\n        img = OffsetImage(img, zoom=image_zoom)\n        ab = AnnotationBbox(img, (x0, y0), xycoords='data', frameon=True,\n                            bboxprops =dict(edgecolor=color[label], lw=boxthickness), pad=0)\n        artists.append(ax.add_artist(ab))\n    ax.update_datalim(X_2d_data)\n```\n\n\n```python\n# calculate nanowire pixel density for each segmentation mask from the two morphologies\nnanowire_pixel_density = np.zeros((image_mask.shape[0]))\nfor i in range(image_mask.shape[0]):\n  nanowire_pixel_density[i] = np.sum(image_mask[i]) / imageSize / imageSize \nfig, ax = plt.subplots(figsize=(5, 5))\nplt.hist(nanowire_pixel_density[np.where(peptide_morph_train_seg_enc == 0)], color=color[1], label='dispersed')\nplt.hist(nanowire_pixel_density[np.where(peptide_morph_train_seg_enc == 1)], color=color[2], label='network')\nplt.legend(fontsize=16)\nax.tick_params(labelsize=16, length=4)\nax.set_xlabel(r'nanowire pixel density', fontsize=20, fontweight='bold')\nax.set_ylabel(r'image count', fontsize=20, fontweight='bold')\nax.xaxis.set_major_locator(MultipleLocator(0.10))\nax.xaxis.set_minor_locator(MultipleLocator(0.05))\nax.xaxis.set_major_formatter(FormatStrFormatter('%1.2f'))\nax.set_xlim(-0.02, 0.52)\n```\n\n\n```python\n# this code block is for generating tsne plots and nanowire density plots only for the good and bad anchors for each five encoder.\n# Random seed fix\nrandom_seed_list = np.array([42, 43, 44, 45, 46])\nrandom_seed_for_split = np.linspace(42, 42 + 19, 20).astype(int)\n\n# list of models\nmodels = ['barlow_tem']\n\nplt.rcParams['axes.prop_cycle'] = plt.cycler(color=plt.cm.tab10.colors)\n\nclassification_result = {}\nfor i in range(len(models)):\n  y = np.load('classify_scores_main_result/%s_classification_result.npz' % (models[i])\n      , allow_pickle=True)\n  classification_result.update({'%s' % (models[i]): y['scores']})\n\nfor i in range(len(random_seed_list)):\n\n  seed_max = np.argmax(classification_result['%s' % (models[0])][-1][i], axis=0)[0]\n  seed_min = np.argmin(classification_result['%s' % (models[0])][-1][i], axis=0)[0]\n  seed_to_look = np.array([seed_max, seed_min])\n  print(np.max(classification_result['%s' % (models[0])][-1][i], axis=0))\n  print(np.min(classification_result['%s' % (models[0])][-1][i], axis=0))\n\n  resnet_model = get_resnet_self_supervise_model(128, 64, 1024)\n  resnet_model.load_weights('barlow_resnet_batch64_project128_64_1024_seed%i.h5' % (random_seed_list[i]))\n  resnet_model.layers[1].trainable = False\n\n  feature_extraction_model = Model(resnet_model.input, resnet_model.layers[-9].output)\n\n  # Extract train and test features\n  features = feature_extraction_model.predict(train_ds)\n  \n  for j in range(2):\n\n    train_feature, test_feature, train_label, test_label = train_test_split(features, peptide_morph_train_enc, test_size=0.2, shuffle=True, stratify=peptide_morph_train_enc, random_state=random_seed_for_split[seed_to_look[j]])\n    train_filename, test_filename, train_label, test_label = train_test_split(peptide_morph_images_train, peptide_morph_train_enc, test_size=0.2, shuffle=True, stratify=peptide_morph_train_enc, random_state=random_seed_for_split[seed_to_look[j]])      \n    train_label_storage = pd.DataFrame(np.concatenate((train_filename.reshape(1, -1).transpose(), train_label.reshape(1, -1).transpose()), axis=-1), columns=['filename', 'label'])\n    test_label_storage = pd.DataFrame(np.concatenate((test_filename.reshape(1, -1).transpose(), test_label.reshape(1, -1).transpose()), axis=-1), columns=['filename', 'label'])\n    train_feature_map = train_feature[train_label_storage.groupby('label').sample(n=1, random_state = 42).index.to_numpy()]\n    train_images_directory = train_label_storage.groupby('label').sample(n=1, random_state = 42)['filename'].to_numpy().astype(str)\n    train_images_label = train_label_storage.groupby('label').sample(n=1, random_state = 42)['label'].to_numpy().astype(int)\n\n    img1 = load_img(train_images_directory[0])\n    img2 = load_img(train_images_directory[1])\n    img3 = load_img(train_images_directory[2])\n    img4 = load_img(train_images_directory[3])\n    images_to_plot = np.asarray([np.array(img1), np.array(img2), np.array(img3), np.array(img4)])\n\n    f, ax = plt.subplots(ncols=4, nrows=1, figsize=(10, 10))\n    for m in range(4):\n        ax[m].set_title(category_names[m], fontsize=14)\n        ax[m].imshow(images_to_plot[m])\n        ax[m].axis('off')\n    plt.tight_layout()\n    plt.show()\n\n    # checking the nanowire_pixel_densities of the anchor and test images from dispersed and network morphologies\n    dispersed_anchor_filename = train_images_directory[1].split(\".\")[0] + \"_label.png\"\n    network_anchor_filename = train_images_directory[2].split(\".\")[0] + \"_label.png\"\n\n    dispersed_anchor = nanowire_pixel_density[np.where(peptide_morph_images_train_seglabel==dispersed_anchor_filename)]\n    network_anchor = nanowire_pixel_density[np.where(peptide_morph_images_train_seglabel==network_anchor_filename)]\n    print(dispersed_anchor)\n    print(network_anchor)\n\n    dispersed_filenames = [test_filename[np.where(test_label==1)][i].split(\".\")[0] + \"_label.png\" for i in range(20)]\n    dispersed_pixel_densities = np.array([nanowire_pixel_density[np.where(peptide_morph_images_train_seglabel==dispersed_filenames[i])] for i in range(20)]).reshape(-1)\n    network_filenames = [test_filename[np.where(test_label==2)][i].split(\".\")[0] + \"_label.png\" for i in range(20)]\n    network_pixel_densities = np.array([nanowire_pixel_density[np.where(peptide_morph_images_train_seglabel==network_filenames[i])] for i in range(20)]).reshape(-1)\n    fig, ax = plt.subplots(figsize=(5, 5))\n    plt.hist(dispersed_pixel_densities, color=color[1], label='dispersed')\n    plt.hist(network_pixel_densities, color=color[2], label='network')\n    plt.vlines(dispersed_anchor, 0, 4, colors='k', ls='solid')\n    plt.vlines(np.median(dispersed_pixel_densities), 0, 4, colors='k', ls='--')\n    plt.vlines(network_anchor, 0, 4, colors='k', ls='solid')\n    plt.vlines(np.median(network_pixel_densities), 0, 4, colors='k', ls='--')\n    plt.legend(fontsize=16)\n    ax.tick_params(labelsize=16, length=4)\n    ax.set_xlabel(r'nanowire pixel density', fontsize=20, fontweight='bold')\n    ax.set_ylabel(r'image count', fontsize=20, fontweight='bold')\n    ax.xaxis.set_major_locator(MultipleLocator(0.10))\n    ax.xaxis.set_minor_locator(MultipleLocator(0.05))\n    ax.xaxis.set_major_formatter(FormatStrFormatter('%1.2f'))\n    ax.set_xlim(-0.02, 0.52)\n\n    # unsupervised tsne cluster assignment visualization\n    tsne = sklearn.manifold.TSNE(n_components=2, perplexity=50, init='pca', n_jobs=8, random_state=42)\n    test_tsne = np.vstack((test_feature, train_feature_map))\n    test_tsne = np.array(tsne.fit_transform(test_tsne))\n    test_tsne = StandardScaler().fit_transform(test_tsne)\n\n    # plot the tsne plot with true labels\n    fig, ax = plt.subplots(figsize=(80, 80))\n    artists = []\n\n    visualize_scatter_with_images(test_tsne[:-4], test_filename, test_label, ax, image_zoom=1.00, boxthickness=8)\n    visualize_anchor_images(test_tsne[-4:], train_images_directory, train_images_label, ax, image_zoom=1.00, boxthickness=40)\n\n    ax.autoscale()\n    plt.show()\n\n    linear_model = get_linear_model(test_feature.shape[1])\n    linear_model.load_weights('best_classify_models_main_result/%s_%iper_class_seed%i_seed%i_linear.h5' \n                                    % (models[0], 1, random_seed_list[i], random_seed_for_split[seed_to_look[j]]))\n    y_pred_linear = np.argmax(linear_model.predict(test_feature), axis=-1)\n\n    # plot the tsne plot with predicted labels\n    fig, ax = plt.subplots(figsize=(80, 80))\n    artists = []\n\n    visualize_scatter_with_images(test_tsne[:-4], test_filename, y_pred_linear, ax, image_zoom=1.00, boxthickness=8)\n    visualize_anchor_images(test_tsne[-4:], train_images_directory, train_images_label, ax, image_zoom=1.00, boxthickness=40)\n\n    ax.autoscale()\n    plt.show()\n\n```\n\n\n```python\n# looking for causal effect between nanowire density (anchor - median) distance and classification accuracy for all 100 anchor sets.\n\n# Random seed fix\nrandom_seed_list = np.array([42, 43, 44, 45, 46])\nrandom_seed_for_split = np.linspace(42, 42 + 19, 20).astype(int)\n\n# list of models\nmodels = ['barlow_tem']\n\nplt.rcParams['axes.prop_cycle'] = plt.cycler(color=plt.cm.tab10.colors)\n\nclassification_result = {}\nfor i in range(len(models)):\n  y = np.load('classify_scores_main_result/%s_classification_result.npz' % (models[i])\n      , allow_pickle=True)\n  classification_result.update({'%s' % (models[i]): y['scores']})\n\ndistance_anchor_median = np.zeros((len(random_seed_list), len(random_seed_for_split)))\nabs_dist_anchor_median = np.zeros((len(random_seed_list), len(random_seed_for_split)))\nsign_anchor_median = np.zeros((len(random_seed_list), len(random_seed_for_split)))\nfor i in range(len(random_seed_list)):\n\n  seed_max = np.argmax(classification_result['%s' % (models[0])][-1][i], axis=0)[0]\n  seed_min = np.argmin(classification_result['%s' % (models[0])][-1][i], axis=0)[0]\n  seed_to_look = np.array([seed_max, seed_min])\n  print(np.max(classification_result['%s' % (models[0])][-1][i], axis=0))\n  print(np.min(classification_result['%s' % (models[0])][-1][i], axis=0))\n\n  resnet_model = get_resnet_self_supervise_model(128, 64, 1024)\n  resnet_model.load_weights('barlow_resnet_batch64_project128_64_1024_seed%i.h5' % (random_seed_list[i]))\n  resnet_model.layers[1].trainable = False\n\n  feature_extraction_model = Model(resnet_model.input, resnet_model.layers[-9].output)\n\n  # Extract train and test features\n  features = feature_extraction_model.predict(train_ds)\n  \n  for j in range(len(random_seed_for_split)):\n\n    train_feature, test_feature, train_label, test_label = train_test_split(features, peptide_morph_train_enc, test_size=0.2, shuffle=True, stratify=peptide_morph_train_enc, random_state=random_seed_for_split[j])\n    train_filename, test_filename, train_label, test_label = train_test_split(peptide_morph_images_train, peptide_morph_train_enc, test_size=0.2, shuffle=True, stratify=peptide_morph_train_enc, random_state=random_seed_for_split[j])      \n    train_label_storage = pd.DataFrame(np.concatenate((train_filename.reshape(1, -1).transpose(), train_label.reshape(1, -1).transpose()), axis=-1), columns=['filename', 'label'])\n    test_label_storage = pd.DataFrame(np.concatenate((test_filename.reshape(1, -1).transpose(), test_label.reshape(1, -1).transpose()), axis=-1), columns=['filename', 'label'])\n    train_feature_map = train_feature[train_label_storage.groupby('label').sample(n=1, random_state = 42).index.to_numpy()]\n    train_images_directory = train_label_storage.groupby('label').sample(n=1, random_state = 42)['filename'].to_numpy().astype(str)\n    train_images_label = train_label_storage.groupby('label').sample(n=1, random_state = 42)['label'].to_numpy().astype(int)\n\n    img1 = load_img(train_images_directory[0])\n    img2 = load_img(train_images_directory[1])\n    img3 = load_img(train_images_directory[2])\n    img4 = load_img(train_images_directory[3])\n    images_to_plot = np.asarray([np.array(img1), np.array(img2), np.array(img3), np.array(img4)])\n\n    f, ax = plt.subplots(ncols=4, nrows=1, figsize=(10, 10))\n    for m in range(4):\n        ax[m].set_title(category_names[m], fontsize=14)\n        ax[m].imshow(images_to_plot[m])\n        ax[m].axis('off')\n    plt.tight_layout()\n    plt.show()\n\n    # checking the nanowire_pixel_densities of the anchor and test images from dispersed and network morphologies\n    dispersed_anchor_filename = train_images_directory[1].split(\".\")[0] + \"_label.png\"\n    network_anchor_filename = train_images_directory[2].split(\".\")[0] + \"_label.png\"\n\n    dispersed_anchor = nanowire_pixel_density[np.where(peptide_morph_images_train_seglabel==dispersed_anchor_filename)]\n    network_anchor = nanowire_pixel_density[np.where(peptide_morph_images_train_seglabel==network_anchor_filename)]\n    print(dispersed_anchor)\n    print(network_anchor)\n\n    dispersed_filenames = [test_filename[np.where(test_label==1)][i].split(\".\")[0] + \"_label.png\" for i in range(20)]\n    dispersed_pixel_densities = np.array([nanowire_pixel_density[np.where(peptide_morph_images_train_seglabel==dispersed_filenames[i])] for i in range(20)]).reshape(-1)\n    network_filenames = [test_filename[np.where(test_label==2)][i].split(\".\")[0] + \"_label.png\" for i in range(20)]\n    network_pixel_densities = np.array([nanowire_pixel_density[np.where(peptide_morph_images_train_seglabel==network_filenames[i])] for i in range(20)]).reshape(-1)\n    fig, ax = plt.subplots(figsize=(5, 5))\n    plt.hist(dispersed_pixel_densities, color=color[1], label='dispersed')\n    plt.hist(network_pixel_densities, color=color[2], label='network')\n    plt.vlines(dispersed_anchor, 0, 1, colors='k')\n    plt.vlines(np.median(dispersed_pixel_densities), 0, 1, colors='g')\n    plt.vlines(network_anchor, 0, 1, colors='k')\n    plt.vlines(np.median(network_pixel_densities), 0, 1, colors='g')\n    plt.legend(fontsize=16)\n    ax.tick_params(labelsize=16, length=4)\n    ax.set_xlabel(r'nanowire pixel density', fontsize=20, fontweight='bold')\n    ax.set_ylabel(r'image count', fontsize=20, fontweight='bold')\n    ax.xaxis.set_major_locator(MultipleLocator(0.10))\n    ax.xaxis.set_minor_locator(MultipleLocator(0.05))\n    ax.xaxis.set_major_formatter(FormatStrFormatter('%1.2f'))\n    ax.set_xlim(-0.02, 0.52)\n    distance_anchor_median[i, j] = (dispersed_anchor - np.median(dispersed_pixel_densities)) - (network_anchor - np.median(network_pixel_densities))\n    abs_dist_anchor_median[i, j] = np.abs(dispersed_anchor - np.median(dispersed_pixel_densities)) + np.abs(network_anchor - np.median(network_pixel_densities))\n    sign_anchor_median[i, j] = np.sign((dispersed_anchor - np.median(dispersed_pixel_densities)) * (network_anchor - np.median(network_pixel_densities)))\n```\n\n\n```python\n# plot the classification accuracy of anchors on opposite or on the same side of the medians of the two morphologies\nnega = np.reshape(classification_result['%s' % (models[0])][-1][:, :, 0], (-1, 1))[np.where(np.reshape(sign_anchor_median, (-1, 1))==-1)[0]]\nposi = np.reshape(classification_result['%s' % (models[0])][-1][:, :, 0], (-1, 1))[np.where(np.reshape(sign_anchor_median, (-1, 1))==1)[0]]\nfig, ax= plt.subplots()\nplt.boxplot([nega, posi], notch=True, positions=[1, 1.3])\nax.set_xticks(([1, 1.3]))\nax.set_xticklabels(['opposite', 'same'])\nax.tick_params(labelsize=16, length=4)\nax.set_xlabel(r'two anchor positions', fontsize=20, fontweight='bold')\nax.set_ylabel(r'accuracy', fontsize=20, fontweight='bold')\n```\n", "meta": {"hexsha": "8a25107ac9e3384dc986cc41fb1dfae033ce0452", "size": 68867, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/one-shot learning result plots.ipynb", "max_stars_repo_name": "arthijayaraman-lab/self-supervised_learning_microscopy_images", "max_stars_repo_head_hexsha": "f7adc86798379ae3934a864e6c41982a15aae870", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/one-shot learning result plots.ipynb", "max_issues_repo_name": "arthijayaraman-lab/self-supervised_learning_microscopy_images", "max_issues_repo_head_hexsha": "f7adc86798379ae3934a864e6c41982a15aae870", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/one-shot learning result plots.ipynb", "max_forks_repo_name": "arthijayaraman-lab/self-supervised_learning_microscopy_images", "max_forks_repo_head_hexsha": "f7adc86798379ae3934a864e6c41982a15aae870", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 68867.0, "max_line_length": 68867, "alphanum_fraction": 0.8213367796, "converted": true, "num_tokens": 6734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423539898095244, "lm_q2_score": 0.05261894963358463, "lm_q1q2_score": 0.01706092612840395}}
{"text": "#Extracting text from LaTex file of any research paper\n\nImporting the necessary libraries:\n\n\n```\nimport re\nimport json  \n```\n\nReading the latex file:\n\n\n```\ndata = open('p1.tex').read()\n```\n\nGetting rid of all the unwanted tags before extraction of text:\n\n\n```\ndef purge_images(data):\n    imgs = re.findall(r'begin{figure}(.*?)end{figure}', data,re.S)\n    start = \"\\\\begin{figure}\"\n    end = \"end{figure}\"\n    imgs = [start + img + end for img in imgs]\n    for img in imgs:\n        data = data.replace(img,\" \")\n    return data\n\ndef purge_table(data):\n    tables = re.findall(r'begin{table}(.*?)end{table}', data,re.S)\n    start = \"\\\\begin{table}\"\n    end = \"end{table}\"\n    tables = [start + table + end for table in tables]\n    for table in tables:\n        data = data.replace(table,\" \")\n    return data\n\ndef purge_equation(data):\n    equations = re.findall(r'begin{equation}(.*?)end{equation}', data,re.S)\n    start = \"\\\\begin{equation}\"\n    end = \"end{equation}\"\n    equations = [start + equation + end for equation in equations]\n    for equation in equations:\n        data = data.replace(equation,\" \")\n    return data\n\ndata = purge_images(data)\ndata = purge_table(data)\ndata = purge_equation(data)   \n```\n\nFunction to convert list to string since the findall function returns a list\n\n\n```\ndef listToString(s):  \n    # initialize an empty string \n    str1 = \"\"  \n    # traverse in the string   \n    for ele in s:  \n        str1 += ele   \n    # return string   \n    return str1  \n```\n\nExtracting the title:\n\n\n```\ntitle = re.findall(r'title{(.*?)}',data,re.S)\ntitle = listToString(title)\nprint(title)\n```\n\n    A Sample Research Paper\n\n\nExtracting the authors:\n\n\n```\nauthor = re.findall(r'author{(.*?)}',data,re.S)\nauthor = listToString(author)\nprint(author)\n```\n\n    I.M. Great and So.R. Yu\n\n\nExtracting the abstract:\n\n\n```\nabstract = re.findall(r'\\\\begin{abstract}(.*?)\\\\end{abstract}', data, re.S)\nabstract = listToString(abstract)\nprint(abstract)\n```\n\n    \n    An abstract is a great convenience for the reader and is required by all journals. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam convallis diam at lobortis dapibus. In id efficitur libero. Vestibulum vel ullamcorper neque. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Quisque et felis commodo, rutrum erat at, sodales odio. Nam mi ipsum, imperdiet vitae augue non, convallis accumsan ante. Vivamus in lacus id nisi gravida condimentum vitae convallis tortor. In viverra congue sollicitudin. Quisque eget leo feugiat, tincidunt enim et, pretium orci. Duis condimentum maximus turpis at malesuada. Morbi laoreet metus felis, et varius odio consequat ac. Curabitur rutrum ac sapien ut ultrices. Donec et pretium elit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.\n    \n\n\nExtracting the introduction:\n\n\n```\nintroduction = re.findall(r'\\\\section{Introduction}(.*?)\\\\',data,re.S)\nintroduction = listToString(introduction)\nprint(introduction)\n```\n\n    \n    \n    Using latex is pretty easy if you have a sample document you can follow.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed volutpat ornare odio et faucibus. Donec fringilla massa eget auctor viverra. Mauris a imperdiet est. Cras tincidunt nulla ut elit tristique ultricies. Phasellus nec orci vel mi suscipit maximus at vitae tortor. Vivamus sed libero vel lacus aliquam rhoncus. Ut in lacinia nunc. Nullam quis mauris leo. Phasellus vitae nisl condimentum quam congue volutpat. Quisque et dapibus ipsum. Curabitur fringilla pellentesque elit, non posuere purus malesuada id. Pellentesque rutrum vitae urna eu mattis.\n    \n    Maecenas ac congue massa. Quisque a sem turpis. Duis et diam ex. Suspendisse et enim interdum, sodales risus eu, ultrices est. Suspendisse eu odio enim. In vulputate odio porttitor tincidunt vestibulum. Praesent tincidunt ullamcorper purus, quis semper felis volutpat quis.\n    \n    \n\n\nExtracting the results:\n\n\n```\nresults = re.findall(r'\\\\section{Results}(.*?)\\\\',data,re.S)\nresults = listToString(results)\nprint(results)\n```\n\n    \n    Including figures, tables, and equations is easy. Latex also permits easy reference to document elements (figures, tables, sections). Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam tincidunt lorem luctus eros dictum faucibus. Fusce euismod libero et erat pretium dapibus. Pellentesque faucibus hendrerit est, ac fringilla urna. In porta, ante eu dictum vestibulum, nisl nulla euismod purus, ac bibendum nibh ante vel elit. Fusce diam ante, tincidunt id eleifend a, hendrerit vitae tellus. Duis pretium urna ac vestibulum eleifend. Suspendisse potenti. Aliquam varius odio in pretium semper. Ut faucibus lobortis mauris vel sollicitudin. Nullam condimentum, lacus quis mattis pellentesque, massa nulla cursus nisi, aliquet eleifend est tellus ut libero.\n    \n     \n    \n     \n    \n     \n    \n    \n\n\nExtracting the conclusions:\n\n\n```\nconclusions = re.findall(r'\\\\section{Conclusions}(.*?)\\\\',data,re.S)\nconclusions = listToString(conclusions)\nprint(conclusions)\n```\n\n    \n    \n    Man, latex is great! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam tincidunt lorem luctus eros dictum faucibus. Fusce euismod libero et erat pretium dapibus. Pellentesque faucibus hendrerit est, ac fringilla urna. In porta, ante eu dictum vestibulum, nisl nulla euismod purus, ac bibendum nibh ante vel elit. Fusce diam ante, tincidunt id eleifend a, hendrerit vitae tellus. Duis pretium urna ac vestibulum eleifend. Suspendisse potenti. Aliquam varius odio in pretium semper. Ut faucibus lobortis mauris vel sollicitudin. Nullam condimentum, lacus quis mattis pellentesque, massa nulla cursus nisi, aliquet eleifend est tellus ut libero.\n    \n    \n\n\nExtracting the acknowledgments:\n\n\n```\nacknowledgments = re.findall(r'\\\\acknowledgments(.*?)\\\\',data,re.S)\nacknowledgments = listToString(acknowledgments)\nprint(acknowledgments)\n```\n\n    \n    The author is grateful to Donald Knuth for inventing tex, and making publication quality typesetting a reality for scientists around the world.\n    \n    \n\n\nCreating a dictionary of all the extracted text:\n\n\n```\na_dict = {}\n\nfor variable in [\"title\", \"author\", \"abstract\",\"introduction\",\"results\",\"conclusions\",\"acknowledgments\"]:\n    a_dict[variable] = eval(variable)\n    dict_1.append(a_dict)\n\nprint(a_dict)\n```\n\nConverting the dictionary into a JSON file:\n\n\n```\nwith open(\"extracted_data.json\", \"w\") as outfile:  \n    json.dump(a_dict, outfile) \n```\n", "meta": {"hexsha": "21d510103bd830e72e723d21e5ac1470defd1ec0", "size": 15181, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Scripts/Miscellaneous/Research_paper_latex_parser/parser.ipynb", "max_stars_repo_name": "ShivangiPatel102/Python_and_the_Web", "max_stars_repo_head_hexsha": "6d3b55aef20feeda3cfff941d7bbdc26cbcc70d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 437, "max_stars_repo_stars_event_min_datetime": "2020-09-24T13:57:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:45:56.000Z", "max_issues_repo_path": "Scripts/Miscellaneous/Research_paper_latex_parser/parser.ipynb", "max_issues_repo_name": "ShivangiPatel102/Python_and_the_Web", "max_issues_repo_head_hexsha": "6d3b55aef20feeda3cfff941d7bbdc26cbcc70d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 355, "max_issues_repo_issues_event_min_datetime": "2020-09-24T13:53:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T04:20:40.000Z", "max_forks_repo_path": "Scripts/Miscellaneous/Research_paper_latex_parser/parser.ipynb", "max_forks_repo_name": "ShivangiPatel102/Python_and_the_Web", "max_forks_repo_head_hexsha": "6d3b55aef20feeda3cfff941d7bbdc26cbcc70d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 315, "max_forks_repo_forks_event_min_datetime": "2020-09-24T18:41:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T05:53:01.000Z", "avg_line_length": 30.7307692308, "max_line_length": 882, "alphanum_fraction": 0.5048415783, "converted": true, "num_tokens": 1710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2658804614657029, "lm_q2_score": 0.0637149969187693, "lm_q1q2_score": 0.01694057278304822}}
{"text": "```python\n! pip install qeds\nimport pandas as pd\nimport numpy as np\n```\n\n    Requirement already satisfied: qeds in c:\\users\\asus\\anaconda3\\lib\\site-packages (0.6.2)\n    Requirement already satisfied: matplotlib in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (3.1.1)\n    Requirement already satisfied: pandas in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.25.1)\n    Requirement already satisfied: pyarrow in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.16.0)\n    Requirement already satisfied: openpyxl in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (3.0.0)\n    Requirement already satisfied: plotly in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (4.5.4)\n    Requirement already satisfied: pandas-datareader in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.8.1)\n    Requirement already satisfied: seaborn in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.9.0)\n    Requirement already satisfied: scipy in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (1.3.1)\n    Requirement already satisfied: scikit-learn in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.21.3)\n    Requirement already satisfied: statsmodels in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.10.1)\n    Requirement already satisfied: numpy in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (1.16.5)\n    Requirement already satisfied: requests in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (2.22.0)\n    Requirement already satisfied: quantecon in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.4.6)\n    Requirement already satisfied: quandl in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (3.5.0)\n    Requirement already satisfied: cycler>=0.10 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (1.1.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (2.4.2)\n    Requirement already satisfied: python-dateutil>=2.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (2.8.0)\n    Requirement already satisfied: pytz>=2017.2 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pandas->qeds) (2019.3)\n    Requirement already satisfied: six>=1.0.0 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pyarrow->qeds) (1.12.0)\n    Requirement already satisfied: et-xmlfile in c:\\users\\asus\\anaconda3\\lib\\site-packages (from openpyxl->qeds) (1.0.1)\n    Requirement already satisfied: jdcal in c:\\users\\asus\\anaconda3\\lib\\site-packages (from openpyxl->qeds) (1.4.1)\n    Requirement already satisfied: retrying>=1.3.3 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from plotly->qeds) (1.3.3)\n    Requirement already satisfied: lxml in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pandas-datareader->qeds) (4.4.1)\n    Requirement already satisfied: joblib>=0.11 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from scikit-learn->qeds) (0.13.2)\n    Requirement already satisfied: patsy>=0.4.0 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from statsmodels->qeds) (0.5.1)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (2019.9.11)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (1.24.2)\n    Requirement already satisfied: idna<2.9,>=2.5 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (2.8)\n    Requirement already satisfied: numba>=0.38 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quantecon->qeds) (0.45.1)\n    Requirement already satisfied: sympy in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quantecon->qeds) (1.4)\n    Requirement already satisfied: inflection>=0.3.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quandl->qeds) (0.3.1)\n    Requirement already satisfied: more-itertools in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quandl->qeds) (7.2.0)\n    Requirement already satisfied: setuptools in c:\\users\\asus\\anaconda3\\lib\\site-packages (from kiwisolver>=1.0.1->matplotlib->qeds) (41.4.0)\n    Requirement already satisfied: llvmlite>=0.29.0dev0 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from numba>=0.38->quantecon->qeds) (0.29.0)\n    Requirement already satisfied: mpmath>=0.19 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from sympy->quantecon->qeds) (1.1.0)\n\n\n# The Index - Exercises\n\n**For these exercises we load data on GDP components collected from the World Bank\u2019s World Development Indicators Dataset.**\n\n## Exercise 1\n\n**For the purpose of this exercise we extract smaller DataFrames.**\n\n\n```python\nurl = \"https://datascience.quantecon.org/assets/data/wdi_data.csv\"\ndf = pd.read_csv(url)\n#df.head()\n```\n\n\n```python\ndf_small = df.head(5)\n#df_small\n```\n\n\n```python\ndf_tiny = df.iloc[[0, 3, 2, 4], :]\n#df_tiny\n```\n\n\n```python\nim_ex = df_small[[\"Imports\", \"Exports\"]]\nim_ex_copy = im_ex.copy()\n#im_ex_copy\n```\n\n1. **Create a new DataFrame as follows: im_ex_tiny = df_tiny + im_ex. Analyze the outcome.**\n\n\n```python\nim_ex_tiny = df_tiny + im_ex\nim_ex_tiny\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>GDP</th>\n      <th>GovExpend</th>\n      <th>Imports</th>\n      <th>country</th>\n      <th>year</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>NaN</td>\n      <td>1.165661</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1.200063</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>NaN</td>\n      <td>1.137718</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1.151585</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>NaN</td>\n      <td>1.100646</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1.144688</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>NaN</td>\n      <td>1.036081</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1.117272</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n2. **What happens when you apply the mean method to im_ex_tiny? In particular, what happens to columns that have missing data?**\n\n    - HINT: also looking at the output of the sum method might help\n\n\n```python\nim_ex_tiny.mean()\n\n#we get missing values for the columns where all values are missing (NaN)\n#the mean is computed for the other columns even though there are missing values\n```\n\n\n\n\n    Consumption         NaN\n    Exports        1.110027\n    GDP                 NaN\n    GovExpend           NaN\n    Imports        1.153402\n    country             NaN\n    year                NaN\n    dtype: float64\n\n\n\n\n```python\nim_ex_tiny.sum() \n\n#we get 0s for the columns where all values are missing (NaN)\n#the sum is computed for the other columns (even though there are missing values)\n```\n\n\n\n\n    Consumption    0.000000\n    Exports        4.440106\n    GDP            0.000000\n    GovExpend      0.000000\n    Imports        4.613608\n    country        0.000000\n    year           0.000000\n    dtype: float64\n\n\n\n## Exercises 2-6\n\n**We create a new DataFrame to use throughout the exercises 2-6. Now we set \"country\" and \"year\" as indices.**\n\n\n```python\nwdi = df.set_index([\"country\", \"year\"])\nwdi.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>GovExpend</th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>Imports</th>\n      <th>GDP</th>\n    </tr>\n    <tr>\n      <th>country</th>\n      <th>year</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td rowspan=\"5\" valign=\"top\">Canada</td>\n      <td>2017</td>\n      <td>0.372665</td>\n      <td>1.095475</td>\n      <td>0.582831</td>\n      <td>0.600031</td>\n      <td>1.868164</td>\n    </tr>\n    <tr>\n      <td>2016</td>\n      <td>0.364899</td>\n      <td>1.058426</td>\n      <td>0.576394</td>\n      <td>0.575775</td>\n      <td>1.814016</td>\n    </tr>\n    <tr>\n      <td>2015</td>\n      <td>0.358303</td>\n      <td>1.035208</td>\n      <td>0.568859</td>\n      <td>0.575793</td>\n      <td>1.794270</td>\n    </tr>\n    <tr>\n      <td>2014</td>\n      <td>0.353485</td>\n      <td>1.011988</td>\n      <td>0.550323</td>\n      <td>0.572344</td>\n      <td>1.782252</td>\n    </tr>\n    <tr>\n      <td>2013</td>\n      <td>0.351541</td>\n      <td>0.986400</td>\n      <td>0.518040</td>\n      <td>0.558636</td>\n      <td>1.732714</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Exercise 2\n\n**For each of the examples below do the following and write your answers:**\n\n    - Determine which of the rules above applies.\n    - Identify the type of the returned value.\n    - Explain why the slicing operation returned the data it did.\n\n\n```python\nwdi.loc[[\"United States\", \"Canada\"]]\n\n#row slicing\n#all rows where the outer-most index is either \"United States\" or \"Canada\"\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>GovExpend</th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>Imports</th>\n      <th>GDP</th>\n    </tr>\n    <tr>\n      <th>country</th>\n      <th>year</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td rowspan=\"18\" valign=\"top\">Canada</td>\n      <td>2017</td>\n      <td>0.372665</td>\n      <td>1.095475</td>\n      <td>0.582831</td>\n      <td>0.600031</td>\n      <td>1.868164</td>\n    </tr>\n    <tr>\n      <td>2016</td>\n      <td>0.364899</td>\n      <td>1.058426</td>\n      <td>0.576394</td>\n      <td>0.575775</td>\n      <td>1.814016</td>\n    </tr>\n    <tr>\n      <td>2015</td>\n      <td>0.358303</td>\n      <td>1.035208</td>\n      <td>0.568859</td>\n      <td>0.575793</td>\n      <td>1.794270</td>\n    </tr>\n    <tr>\n      <td>2014</td>\n      <td>0.353485</td>\n      <td>1.011988</td>\n      <td>0.550323</td>\n      <td>0.572344</td>\n      <td>1.782252</td>\n    </tr>\n    <tr>\n      <td>2013</td>\n      <td>0.351541</td>\n      <td>0.986400</td>\n      <td>0.518040</td>\n      <td>0.558636</td>\n      <td>1.732714</td>\n    </tr>\n    <tr>\n      <td>2012</td>\n      <td>0.354342</td>\n      <td>0.961226</td>\n      <td>0.505969</td>\n      <td>0.547756</td>\n      <td>1.693428</td>\n    </tr>\n    <tr>\n      <td>2011</td>\n      <td>0.351887</td>\n      <td>0.943145</td>\n      <td>0.492349</td>\n      <td>0.528227</td>\n      <td>1.664240</td>\n    </tr>\n    <tr>\n      <td>2010</td>\n      <td>0.347332</td>\n      <td>0.921952</td>\n      <td>0.469949</td>\n      <td>0.500341</td>\n      <td>1.613543</td>\n    </tr>\n    <tr>\n      <td>2009</td>\n      <td>0.339686</td>\n      <td>0.890078</td>\n      <td>0.440692</td>\n      <td>0.439796</td>\n      <td>1.565291</td>\n    </tr>\n    <tr>\n      <td>2008</td>\n      <td>0.330766</td>\n      <td>0.889602</td>\n      <td>0.506350</td>\n      <td>0.502281</td>\n      <td>1.612862</td>\n    </tr>\n    <tr>\n      <td>2007</td>\n      <td>0.318777</td>\n      <td>0.864012</td>\n      <td>0.530453</td>\n      <td>0.498002</td>\n      <td>1.596876</td>\n    </tr>\n    <tr>\n      <td>2006</td>\n      <td>0.311382</td>\n      <td>0.827643</td>\n      <td>0.524461</td>\n      <td>0.470931</td>\n      <td>1.564608</td>\n    </tr>\n    <tr>\n      <td>2005</td>\n      <td>0.303043</td>\n      <td>0.794390</td>\n      <td>0.519950</td>\n      <td>0.447222</td>\n      <td>1.524608</td>\n    </tr>\n    <tr>\n      <td>2004</td>\n      <td>0.299854</td>\n      <td>0.764357</td>\n      <td>0.508657</td>\n      <td>0.416754</td>\n      <td>1.477317</td>\n    </tr>\n    <tr>\n      <td>2003</td>\n      <td>0.294335</td>\n      <td>0.741796</td>\n      <td>0.481993</td>\n      <td>0.384199</td>\n      <td>1.433089</td>\n    </tr>\n    <tr>\n      <td>2002</td>\n      <td>0.286094</td>\n      <td>0.721974</td>\n      <td>0.490465</td>\n      <td>0.368615</td>\n      <td>1.407725</td>\n    </tr>\n    <tr>\n      <td>2001</td>\n      <td>0.279767</td>\n      <td>0.694230</td>\n      <td>0.484696</td>\n      <td>0.362023</td>\n      <td>1.366590</td>\n    </tr>\n    <tr>\n      <td>2000</td>\n      <td>0.270553</td>\n      <td>0.677713</td>\n      <td>0.499526</td>\n      <td>0.380823</td>\n      <td>1.342805</td>\n    </tr>\n    <tr>\n      <td rowspan=\"18\" valign=\"top\">United States</td>\n      <td>2017</td>\n      <td>2.405743</td>\n      <td>12.019266</td>\n      <td>2.287071</td>\n      <td>3.069954</td>\n      <td>17.348627</td>\n    </tr>\n    <tr>\n      <td>2016</td>\n      <td>2.407981</td>\n      <td>11.722133</td>\n      <td>2.219937</td>\n      <td>2.936004</td>\n      <td>16.972348</td>\n    </tr>\n    <tr>\n      <td>2015</td>\n      <td>2.373130</td>\n      <td>11.409800</td>\n      <td>2.222228</td>\n      <td>2.881337</td>\n      <td>16.710459</td>\n    </tr>\n    <tr>\n      <td>2014</td>\n      <td>2.334071</td>\n      <td>11.000619</td>\n      <td>2.209555</td>\n      <td>2.732228</td>\n      <td>16.242526</td>\n    </tr>\n    <tr>\n      <td>2013</td>\n      <td>2.353381</td>\n      <td>10.687214</td>\n      <td>2.118639</td>\n      <td>2.600198</td>\n      <td>15.853796</td>\n    </tr>\n    <tr>\n      <td>2012</td>\n      <td>2.398873</td>\n      <td>10.534042</td>\n      <td>2.045509</td>\n      <td>2.560677</td>\n      <td>15.567038</td>\n    </tr>\n    <tr>\n      <td>2011</td>\n      <td>2.434378</td>\n      <td>10.378060</td>\n      <td>1.978083</td>\n      <td>2.493194</td>\n      <td>15.224555</td>\n    </tr>\n    <tr>\n      <td>2010</td>\n      <td>2.510143</td>\n      <td>10.185836</td>\n      <td>1.846280</td>\n      <td>2.360183</td>\n      <td>14.992053</td>\n    </tr>\n    <tr>\n      <td>2009</td>\n      <td>2.507390</td>\n      <td>10.010687</td>\n      <td>1.646432</td>\n      <td>2.086299</td>\n      <td>14.617299</td>\n    </tr>\n    <tr>\n      <td>2008</td>\n      <td>2.407771</td>\n      <td>10.137847</td>\n      <td>1.797347</td>\n      <td>2.400349</td>\n      <td>14.997756</td>\n    </tr>\n    <tr>\n      <td>2007</td>\n      <td>2.351987</td>\n      <td>10.159387</td>\n      <td>1.701096</td>\n      <td>2.455016</td>\n      <td>15.018268</td>\n    </tr>\n    <tr>\n      <td>2006</td>\n      <td>2.314957</td>\n      <td>9.938503</td>\n      <td>1.564920</td>\n      <td>2.395189</td>\n      <td>14.741688</td>\n    </tr>\n    <tr>\n      <td>2005</td>\n      <td>2.287022</td>\n      <td>9.643098</td>\n      <td>1.431205</td>\n      <td>2.246246</td>\n      <td>14.332500</td>\n    </tr>\n    <tr>\n      <td>2004</td>\n      <td>2.267999</td>\n      <td>9.311431</td>\n      <td>1.335978</td>\n      <td>2.108585</td>\n      <td>13.846058</td>\n    </tr>\n    <tr>\n      <td>2003</td>\n      <td>2.233519</td>\n      <td>8.974708</td>\n      <td>1.218199</td>\n      <td>1.892825</td>\n      <td>13.339312</td>\n    </tr>\n    <tr>\n      <td>2002</td>\n      <td>2.193188</td>\n      <td>8.698306</td>\n      <td>1.192180</td>\n      <td>1.804105</td>\n      <td>12.968263</td>\n    </tr>\n    <tr>\n      <td>2001</td>\n      <td>2.112038</td>\n      <td>8.480461</td>\n      <td>1.213253</td>\n      <td>1.740797</td>\n      <td>12.746262</td>\n    </tr>\n    <tr>\n      <td>2000</td>\n      <td>2.040500</td>\n      <td>8.272097</td>\n      <td>1.287739</td>\n      <td>1.790995</td>\n      <td>12.620268</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nwdi.loc[([\"United States\", \"Canada\"], [2010, 2011, 2012]), :]\n\n#row slicing\n#all rows where the outer-most index is either \"United States or \"Canada\" AND \n#where the second level index is either 2010 or 2011 or 2012\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>GovExpend</th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>Imports</th>\n      <th>GDP</th>\n    </tr>\n    <tr>\n      <th>country</th>\n      <th>year</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td rowspan=\"3\" valign=\"top\">Canada</td>\n      <td>2012</td>\n      <td>0.354342</td>\n      <td>0.961226</td>\n      <td>0.505969</td>\n      <td>0.547756</td>\n      <td>1.693428</td>\n    </tr>\n    <tr>\n      <td>2011</td>\n      <td>0.351887</td>\n      <td>0.943145</td>\n      <td>0.492349</td>\n      <td>0.528227</td>\n      <td>1.664240</td>\n    </tr>\n    <tr>\n      <td>2010</td>\n      <td>0.347332</td>\n      <td>0.921952</td>\n      <td>0.469949</td>\n      <td>0.500341</td>\n      <td>1.613543</td>\n    </tr>\n    <tr>\n      <td rowspan=\"3\" valign=\"top\">United States</td>\n      <td>2012</td>\n      <td>2.398873</td>\n      <td>10.534042</td>\n      <td>2.045509</td>\n      <td>2.560677</td>\n      <td>15.567038</td>\n    </tr>\n    <tr>\n      <td>2011</td>\n      <td>2.434378</td>\n      <td>10.378060</td>\n      <td>1.978083</td>\n      <td>2.493194</td>\n      <td>15.224555</td>\n    </tr>\n    <tr>\n      <td>2010</td>\n      <td>2.510143</td>\n      <td>10.185836</td>\n      <td>1.846280</td>\n      <td>2.360183</td>\n      <td>14.992053</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nwdi.loc[\"United States\"]\n\n#row slicing\n#all rows where the outer most index value is equal to United States\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>GovExpend</th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>Imports</th>\n      <th>GDP</th>\n    </tr>\n    <tr>\n      <th>year</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>2017</td>\n      <td>2.405743</td>\n      <td>12.019266</td>\n      <td>2.287071</td>\n      <td>3.069954</td>\n      <td>17.348627</td>\n    </tr>\n    <tr>\n      <td>2016</td>\n      <td>2.407981</td>\n      <td>11.722133</td>\n      <td>2.219937</td>\n      <td>2.936004</td>\n      <td>16.972348</td>\n    </tr>\n    <tr>\n      <td>2015</td>\n      <td>2.373130</td>\n      <td>11.409800</td>\n      <td>2.222228</td>\n      <td>2.881337</td>\n      <td>16.710459</td>\n    </tr>\n    <tr>\n      <td>2014</td>\n      <td>2.334071</td>\n      <td>11.000619</td>\n      <td>2.209555</td>\n      <td>2.732228</td>\n      <td>16.242526</td>\n    </tr>\n    <tr>\n      <td>2013</td>\n      <td>2.353381</td>\n      <td>10.687214</td>\n      <td>2.118639</td>\n      <td>2.600198</td>\n      <td>15.853796</td>\n    </tr>\n    <tr>\n      <td>2012</td>\n      <td>2.398873</td>\n      <td>10.534042</td>\n      <td>2.045509</td>\n      <td>2.560677</td>\n      <td>15.567038</td>\n    </tr>\n    <tr>\n      <td>2011</td>\n      <td>2.434378</td>\n      <td>10.378060</td>\n      <td>1.978083</td>\n      <td>2.493194</td>\n      <td>15.224555</td>\n    </tr>\n    <tr>\n      <td>2010</td>\n      <td>2.510143</td>\n      <td>10.185836</td>\n      <td>1.846280</td>\n      <td>2.360183</td>\n      <td>14.992053</td>\n    </tr>\n    <tr>\n      <td>2009</td>\n      <td>2.507390</td>\n      <td>10.010687</td>\n      <td>1.646432</td>\n      <td>2.086299</td>\n      <td>14.617299</td>\n    </tr>\n    <tr>\n      <td>2008</td>\n      <td>2.407771</td>\n      <td>10.137847</td>\n      <td>1.797347</td>\n      <td>2.400349</td>\n      <td>14.997756</td>\n    </tr>\n    <tr>\n      <td>2007</td>\n      <td>2.351987</td>\n      <td>10.159387</td>\n      <td>1.701096</td>\n      <td>2.455016</td>\n      <td>15.018268</td>\n    </tr>\n    <tr>\n      <td>2006</td>\n      <td>2.314957</td>\n      <td>9.938503</td>\n      <td>1.564920</td>\n      <td>2.395189</td>\n      <td>14.741688</td>\n    </tr>\n    <tr>\n      <td>2005</td>\n      <td>2.287022</td>\n      <td>9.643098</td>\n      <td>1.431205</td>\n      <td>2.246246</td>\n      <td>14.332500</td>\n    </tr>\n    <tr>\n      <td>2004</td>\n      <td>2.267999</td>\n      <td>9.311431</td>\n      <td>1.335978</td>\n      <td>2.108585</td>\n      <td>13.846058</td>\n    </tr>\n    <tr>\n      <td>2003</td>\n      <td>2.233519</td>\n      <td>8.974708</td>\n      <td>1.218199</td>\n      <td>1.892825</td>\n      <td>13.339312</td>\n    </tr>\n    <tr>\n      <td>2002</td>\n      <td>2.193188</td>\n      <td>8.698306</td>\n      <td>1.192180</td>\n      <td>1.804105</td>\n      <td>12.968263</td>\n    </tr>\n    <tr>\n      <td>2001</td>\n      <td>2.112038</td>\n      <td>8.480461</td>\n      <td>1.213253</td>\n      <td>1.740797</td>\n      <td>12.746262</td>\n    </tr>\n    <tr>\n      <td>2000</td>\n      <td>2.040500</td>\n      <td>8.272097</td>\n      <td>1.287739</td>\n      <td>1.790995</td>\n      <td>12.620268</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nwdi.loc[(\"United States\", 2010), [\"GDP\", \"Exports\"]] \n\n#row + column slicing\n#we get the values for the GDP and Exports columns in the United States in 2010 \n#however, this is not presented as expected (the column names appear as indices)\n# Tuple used to select united states on year 2010. Then, only GDP and Exports columns are extracted\n```\n\n\n\n\n    GDP        14.992053\n    Exports     1.846280\n    Name: (United States, 2010), dtype: float64\n\n\n\n\n```python\nwdi.loc[(\"United States\", 2010)]\n\n#row slicing\n#we get the values for all columns in the United States in 2010 \n#however, this is not presented as expected (the column names appear as indices)\n```\n\n\n\n\n    GovExpend       2.510143\n    Consumption    10.185836\n    Exports         1.846280\n    Imports         2.360183\n    GDP            14.992053\n    Name: (United States, 2010), dtype: float64\n\n\n\n\n```python\nwdi.loc[[(\"United States\", 2010), (\"Canada\", 2015)]]\n\n#row slicing\n#all rows where the the two hierarchical indices are either (\"United States\", 2010) or (\"Canada\", 2015)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>GovExpend</th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>Imports</th>\n      <th>GDP</th>\n    </tr>\n    <tr>\n      <th>country</th>\n      <th>year</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>United States</td>\n      <td>2010</td>\n      <td>2.510143</td>\n      <td>10.185836</td>\n      <td>1.846280</td>\n      <td>2.360183</td>\n      <td>14.992053</td>\n    </tr>\n    <tr>\n      <td>Canada</td>\n      <td>2015</td>\n      <td>0.358303</td>\n      <td>1.035208</td>\n      <td>0.568859</td>\n      <td>0.575793</td>\n      <td>1.794270</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nwdi.loc[[\"United States\", \"Canada\"], \"GDP\"]\n\n#row + column slicing\n#all rows for United States or Canada only for the column GDP\n```\n\n\n\n\n    country        year\n    Canada         2017     1.868164\n                   2016     1.814016\n                   2015     1.794270\n                   2014     1.782252\n                   2013     1.732714\n                   2012     1.693428\n                   2011     1.664240\n                   2010     1.613543\n                   2009     1.565291\n                   2008     1.612862\n                   2007     1.596876\n                   2006     1.564608\n                   2005     1.524608\n                   2004     1.477317\n                   2003     1.433089\n                   2002     1.407725\n                   2001     1.366590\n                   2000     1.342805\n    United States  2017    17.348627\n                   2016    16.972348\n                   2015    16.710459\n                   2014    16.242526\n                   2013    15.853796\n                   2012    15.567038\n                   2011    15.224555\n                   2010    14.992053\n                   2009    14.617299\n                   2008    14.997756\n                   2007    15.018268\n                   2006    14.741688\n                   2005    14.332500\n                   2004    13.846058\n                   2003    13.339312\n                   2002    12.968263\n                   2001    12.746262\n                   2000    12.620268\n    Name: GDP, dtype: float64\n\n\n\n\n```python\nwdi.loc[\"United States\", \"GDP\"]\n\n#row + column slicing\n#all rows for the US for column GDP\n```\n\n\n\n\n    year\n    2017    17.348627\n    2016    16.972348\n    2015    16.710459\n    2014    16.242526\n    2013    15.853796\n    2012    15.567038\n    2011    15.224555\n    2010    14.992053\n    2009    14.617299\n    2008    14.997756\n    2007    15.018268\n    2006    14.741688\n    2005    14.332500\n    2004    13.846058\n    2003    13.339312\n    2002    12.968263\n    2001    12.746262\n    2000    12.620268\n    Name: GDP, dtype: float64\n\n\n\n## Exercise 3\n\n1. **Try setting my_df to some subset of the rows in wdi (use one of the .loc variations above).**\n\n\n```python\n#below we take a few examples (we comment the ones not used in the analysis below)\n\nmy_df = wdi.loc[[(\"United States\", 2010), (\"Canada\", 2015)]]\n#my_df = wdi.loc[\"United States\"]\n#my_df = wdi.loc[(\"United States\", 2010)]\n#my_df = wdi.loc[\"United States\", \"GDP\"]\n#my_df = wdi.loc[[\"United States\", \"Canada\"]]\n\nmy_df\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>GovExpend</th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>Imports</th>\n      <th>GDP</th>\n    </tr>\n    <tr>\n      <th>country</th>\n      <th>year</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>United States</td>\n      <td>2010</td>\n      <td>2.510143</td>\n      <td>10.185836</td>\n      <td>1.846280</td>\n      <td>2.360183</td>\n      <td>14.992053</td>\n    </tr>\n    <tr>\n      <td>Canada</td>\n      <td>2015</td>\n      <td>0.358303</td>\n      <td>1.035208</td>\n      <td>0.568859</td>\n      <td>0.575793</td>\n      <td>1.794270</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n2. **Then see what happens when you do wdi / my_df or my_df ** wdi.**\n\n\n```python\n#we create a variable that does wdi/my_df and we analyze the outcome\nx = wdi / my_df\nx\n\n#since it is not clear at a first look, it's better if we extract the subsets used before to see what happens (uncomment to check):\n    #x_df = x.loc[[(\"United States\", 2010), (\"Canada\", 2015)]]\n    #x_df = x.loc[\"United States\"]\n    #x_df = x.loc[(\"United States\", 2010)]\n    #x_df = x.loc[\"United States\", \"GDP\"]\n    #x_df = x.loc[[\"United States\", \"Canada\"]]\n    #x_df\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>GovExpend</th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>Imports</th>\n      <th>GDP</th>\n    </tr>\n    <tr>\n      <th>country</th>\n      <th>year</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td rowspan=\"5\" valign=\"top\">Canada</td>\n      <td>2000</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2001</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2002</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2003</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2004</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <td rowspan=\"5\" valign=\"top\">United States</td>\n      <td>2013</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2014</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2015</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2016</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2017</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n<p>72 rows \u00d7 5 columns</p>\n</div>\n\n\n\n\n```python\n#we create a variable that does wdi**my_df and we analyze the outcome\ny = wdi ** my_df\ny\n\n#since it is not clear at a first look, it's better if we extract the subsets used before to see what happens (uncomment to check):\n    #y_df = y.loc[[(\"United States\", 2010), (\"Canada\", 2015)]]\n    #y_df = y.loc[\"United States\"]\n    #y_df = y.loc[(\"United States\", 2010)]\n    #y_df = y.loc[\"United States\", \"GDP\"]\n    #y_df = y.loc[[\"United States\", \"Canada\"]]\n    #y_df\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>GovExpend</th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>Imports</th>\n      <th>GDP</th>\n    </tr>\n    <tr>\n      <th>country</th>\n      <th>year</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td rowspan=\"5\" valign=\"top\">Canada</td>\n      <td>2000</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2001</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2002</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2003</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2004</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <td rowspan=\"5\" valign=\"top\">United States</td>\n      <td>2013</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2014</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2015</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2016</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <td>2017</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n<p>72 rows \u00d7 5 columns</p>\n</div>\n\n\n\n3. **Try changing the subset of rows in my_df and repeat until you understand what is happening.**\n\n\n```python\n#conclusion: the operation applies only to the subset my_df and not to the entire DataFrame wdi\n```\n\n## Exercise 4\n\n1. **Below, we create wdi2, which is the same as df4 except that the levels of the index are swapped.**\n\n\n```python\nwdi2 = df.set_index([\"year\", \"country\"])\nwdi2.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>GovExpend</th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>Imports</th>\n      <th>GDP</th>\n    </tr>\n    <tr>\n      <th>year</th>\n      <th>country</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>2017</td>\n      <td>Canada</td>\n      <td>0.372665</td>\n      <td>1.095475</td>\n      <td>0.582831</td>\n      <td>0.600031</td>\n      <td>1.868164</td>\n    </tr>\n    <tr>\n      <td>2016</td>\n      <td>Canada</td>\n      <td>0.364899</td>\n      <td>1.058426</td>\n      <td>0.576394</td>\n      <td>0.575775</td>\n      <td>1.814016</td>\n    </tr>\n    <tr>\n      <td>2015</td>\n      <td>Canada</td>\n      <td>0.358303</td>\n      <td>1.035208</td>\n      <td>0.568859</td>\n      <td>0.575793</td>\n      <td>1.794270</td>\n    </tr>\n    <tr>\n      <td>2014</td>\n      <td>Canada</td>\n      <td>0.353485</td>\n      <td>1.011988</td>\n      <td>0.550323</td>\n      <td>0.572344</td>\n      <td>1.782252</td>\n    </tr>\n    <tr>\n      <td>2013</td>\n      <td>Canada</td>\n      <td>0.351541</td>\n      <td>0.986400</td>\n      <td>0.518040</td>\n      <td>0.558636</td>\n      <td>1.732714</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n2. **In the cells after df6 is defined, we have commented out a few of the slicing examples from the previous exercise. For each of these examples, use pd.IndexSlice to extract the same data from df6.**\n\n    - HINT: You will need to swap the order of the row slicing arguments within the pd.IndexSlice.\n\n\n```python\n#the equivalent of wdi.loc[\"United States\"] is below:\n\n#we create a shortcut for pd.IndexSlice to use in what follows\nidx = pd.IndexSlice\n\nwdi.loc[idx[\"United States\",:],:]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>GovExpend</th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>Imports</th>\n      <th>GDP</th>\n    </tr>\n    <tr>\n      <th>country</th>\n      <th>year</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td rowspan=\"18\" valign=\"top\">United States</td>\n      <td>2017</td>\n      <td>2.405743</td>\n      <td>12.019266</td>\n      <td>2.287071</td>\n      <td>3.069954</td>\n      <td>17.348627</td>\n    </tr>\n    <tr>\n      <td>2016</td>\n      <td>2.407981</td>\n      <td>11.722133</td>\n      <td>2.219937</td>\n      <td>2.936004</td>\n      <td>16.972348</td>\n    </tr>\n    <tr>\n      <td>2015</td>\n      <td>2.373130</td>\n      <td>11.409800</td>\n      <td>2.222228</td>\n      <td>2.881337</td>\n      <td>16.710459</td>\n    </tr>\n    <tr>\n      <td>2014</td>\n      <td>2.334071</td>\n      <td>11.000619</td>\n      <td>2.209555</td>\n      <td>2.732228</td>\n      <td>16.242526</td>\n    </tr>\n    <tr>\n      <td>2013</td>\n      <td>2.353381</td>\n      <td>10.687214</td>\n      <td>2.118639</td>\n      <td>2.600198</td>\n      <td>15.853796</td>\n    </tr>\n    <tr>\n      <td>2012</td>\n      <td>2.398873</td>\n      <td>10.534042</td>\n      <td>2.045509</td>\n      <td>2.560677</td>\n      <td>15.567038</td>\n    </tr>\n    <tr>\n      <td>2011</td>\n      <td>2.434378</td>\n      <td>10.378060</td>\n      <td>1.978083</td>\n      <td>2.493194</td>\n      <td>15.224555</td>\n    </tr>\n    <tr>\n      <td>2010</td>\n      <td>2.510143</td>\n      <td>10.185836</td>\n      <td>1.846280</td>\n      <td>2.360183</td>\n      <td>14.992053</td>\n    </tr>\n    <tr>\n      <td>2009</td>\n      <td>2.507390</td>\n      <td>10.010687</td>\n      <td>1.646432</td>\n      <td>2.086299</td>\n      <td>14.617299</td>\n    </tr>\n    <tr>\n      <td>2008</td>\n      <td>2.407771</td>\n      <td>10.137847</td>\n      <td>1.797347</td>\n      <td>2.400349</td>\n      <td>14.997756</td>\n    </tr>\n    <tr>\n      <td>2007</td>\n      <td>2.351987</td>\n      <td>10.159387</td>\n      <td>1.701096</td>\n      <td>2.455016</td>\n      <td>15.018268</td>\n    </tr>\n    <tr>\n      <td>2006</td>\n      <td>2.314957</td>\n      <td>9.938503</td>\n      <td>1.564920</td>\n      <td>2.395189</td>\n      <td>14.741688</td>\n    </tr>\n    <tr>\n      <td>2005</td>\n      <td>2.287022</td>\n      <td>9.643098</td>\n      <td>1.431205</td>\n      <td>2.246246</td>\n      <td>14.332500</td>\n    </tr>\n    <tr>\n      <td>2004</td>\n      <td>2.267999</td>\n      <td>9.311431</td>\n      <td>1.335978</td>\n      <td>2.108585</td>\n      <td>13.846058</td>\n    </tr>\n    <tr>\n      <td>2003</td>\n      <td>2.233519</td>\n      <td>8.974708</td>\n      <td>1.218199</td>\n      <td>1.892825</td>\n      <td>13.339312</td>\n    </tr>\n    <tr>\n      <td>2002</td>\n      <td>2.193188</td>\n      <td>8.698306</td>\n      <td>1.192180</td>\n      <td>1.804105</td>\n      <td>12.968263</td>\n    </tr>\n    <tr>\n      <td>2001</td>\n      <td>2.112038</td>\n      <td>8.480461</td>\n      <td>1.213253</td>\n      <td>1.740797</td>\n      <td>12.746262</td>\n    </tr>\n    <tr>\n      <td>2000</td>\n      <td>2.040500</td>\n      <td>8.272097</td>\n      <td>1.287739</td>\n      <td>1.790995</td>\n      <td>12.620268</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n#the equivalent of wdi.loc[([\"United States\", \"Canada\"], [2010, 2011, 2012]), :] is below:\n\nwdi.loc[idx[([\"United States\", \"Canada\"],[2010, 2011, 2012])], :]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>GovExpend</th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>Imports</th>\n      <th>GDP</th>\n    </tr>\n    <tr>\n      <th>country</th>\n      <th>year</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td rowspan=\"3\" valign=\"top\">Canada</td>\n      <td>2012</td>\n      <td>0.354342</td>\n      <td>0.961226</td>\n      <td>0.505969</td>\n      <td>0.547756</td>\n      <td>1.693428</td>\n    </tr>\n    <tr>\n      <td>2011</td>\n      <td>0.351887</td>\n      <td>0.943145</td>\n      <td>0.492349</td>\n      <td>0.528227</td>\n      <td>1.664240</td>\n    </tr>\n    <tr>\n      <td>2010</td>\n      <td>0.347332</td>\n      <td>0.921952</td>\n      <td>0.469949</td>\n      <td>0.500341</td>\n      <td>1.613543</td>\n    </tr>\n    <tr>\n      <td rowspan=\"3\" valign=\"top\">United States</td>\n      <td>2012</td>\n      <td>2.398873</td>\n      <td>10.534042</td>\n      <td>2.045509</td>\n      <td>2.560677</td>\n      <td>15.567038</td>\n    </tr>\n    <tr>\n      <td>2011</td>\n      <td>2.434378</td>\n      <td>10.378060</td>\n      <td>1.978083</td>\n      <td>2.493194</td>\n      <td>15.224555</td>\n    </tr>\n    <tr>\n      <td>2010</td>\n      <td>2.510143</td>\n      <td>10.185836</td>\n      <td>1.846280</td>\n      <td>2.360183</td>\n      <td>14.992053</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n#the equivalent of wdi.loc[[\"United States\", \"Canada\"], \"GDP\"] is below:\n\nwdi.loc[idx[[\"United States\", \"Canada\"],:], \"GDP\"]\n```\n\n\n\n\n    country        year\n    Canada         2017     1.868164\n                   2016     1.814016\n                   2015     1.794270\n                   2014     1.782252\n                   2013     1.732714\n                   2012     1.693428\n                   2011     1.664240\n                   2010     1.613543\n                   2009     1.565291\n                   2008     1.612862\n                   2007     1.596876\n                   2006     1.564608\n                   2005     1.524608\n                   2004     1.477317\n                   2003     1.433089\n                   2002     1.407725\n                   2001     1.366590\n                   2000     1.342805\n    United States  2017    17.348627\n                   2016    16.972348\n                   2015    16.710459\n                   2014    16.242526\n                   2013    15.853796\n                   2012    15.567038\n                   2011    15.224555\n                   2010    14.992053\n                   2009    14.617299\n                   2008    14.997756\n                   2007    15.018268\n                   2006    14.741688\n                   2005    14.332500\n                   2004    13.846058\n                   2003    13.339312\n                   2002    12.968263\n                   2001    12.746262\n                   2000    12.620268\n    Name: GDP, dtype: float64\n\n\n\n## Exercise 5\n\n**For the purpose of this exercise, we create a new DataFrame that swaps the rows and columns of the wdi DataFrame.**\n\n\n```python\nwdiT = wdi.T  # .T means \"transpose\" or \"swap rows and columns\"\nwdiT\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th>country</th>\n      <th colspan=\"10\" halign=\"left\">Canada</th>\n      <th>...</th>\n      <th colspan=\"10\" halign=\"left\">United States</th>\n    </tr>\n    <tr>\n      <th>year</th>\n      <th>2017</th>\n      <th>2016</th>\n      <th>2015</th>\n      <th>2014</th>\n      <th>2013</th>\n      <th>2012</th>\n      <th>2011</th>\n      <th>2010</th>\n      <th>2009</th>\n      <th>2008</th>\n      <th>...</th>\n      <th>2009</th>\n      <th>2008</th>\n      <th>2007</th>\n      <th>2006</th>\n      <th>2005</th>\n      <th>2004</th>\n      <th>2003</th>\n      <th>2002</th>\n      <th>2001</th>\n      <th>2000</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>GovExpend</td>\n      <td>0.372665</td>\n      <td>0.364899</td>\n      <td>0.358303</td>\n      <td>0.353485</td>\n      <td>0.351541</td>\n      <td>0.354342</td>\n      <td>0.351887</td>\n      <td>0.347332</td>\n      <td>0.339686</td>\n      <td>0.330766</td>\n      <td>...</td>\n      <td>2.507390</td>\n      <td>2.407771</td>\n      <td>2.351987</td>\n      <td>2.314957</td>\n      <td>2.287022</td>\n      <td>2.267999</td>\n      <td>2.233519</td>\n      <td>2.193188</td>\n      <td>2.112038</td>\n      <td>2.040500</td>\n    </tr>\n    <tr>\n      <td>Consumption</td>\n      <td>1.095475</td>\n      <td>1.058426</td>\n      <td>1.035208</td>\n      <td>1.011988</td>\n      <td>0.986400</td>\n      <td>0.961226</td>\n      <td>0.943145</td>\n      <td>0.921952</td>\n      <td>0.890078</td>\n      <td>0.889602</td>\n      <td>...</td>\n      <td>10.010687</td>\n      <td>10.137847</td>\n      <td>10.159387</td>\n      <td>9.938503</td>\n      <td>9.643098</td>\n      <td>9.311431</td>\n      <td>8.974708</td>\n      <td>8.698306</td>\n      <td>8.480461</td>\n      <td>8.272097</td>\n    </tr>\n    <tr>\n      <td>Exports</td>\n      <td>0.582831</td>\n      <td>0.576394</td>\n      <td>0.568859</td>\n      <td>0.550323</td>\n      <td>0.518040</td>\n      <td>0.505969</td>\n      <td>0.492349</td>\n      <td>0.469949</td>\n      <td>0.440692</td>\n      <td>0.506350</td>\n      <td>...</td>\n      <td>1.646432</td>\n      <td>1.797347</td>\n      <td>1.701096</td>\n      <td>1.564920</td>\n      <td>1.431205</td>\n      <td>1.335978</td>\n      <td>1.218199</td>\n      <td>1.192180</td>\n      <td>1.213253</td>\n      <td>1.287739</td>\n    </tr>\n    <tr>\n      <td>Imports</td>\n      <td>0.600031</td>\n      <td>0.575775</td>\n      <td>0.575793</td>\n      <td>0.572344</td>\n      <td>0.558636</td>\n      <td>0.547756</td>\n      <td>0.528227</td>\n      <td>0.500341</td>\n      <td>0.439796</td>\n      <td>0.502281</td>\n      <td>...</td>\n      <td>2.086299</td>\n      <td>2.400349</td>\n      <td>2.455016</td>\n      <td>2.395189</td>\n      <td>2.246246</td>\n      <td>2.108585</td>\n      <td>1.892825</td>\n      <td>1.804105</td>\n      <td>1.740797</td>\n      <td>1.790995</td>\n    </tr>\n    <tr>\n      <td>GDP</td>\n      <td>1.868164</td>\n      <td>1.814016</td>\n      <td>1.794270</td>\n      <td>1.782252</td>\n      <td>1.732714</td>\n      <td>1.693428</td>\n      <td>1.664240</td>\n      <td>1.613543</td>\n      <td>1.565291</td>\n      <td>1.612862</td>\n      <td>...</td>\n      <td>14.617299</td>\n      <td>14.997756</td>\n      <td>15.018268</td>\n      <td>14.741688</td>\n      <td>14.332500</td>\n      <td>13.846058</td>\n      <td>13.339312</td>\n      <td>12.968263</td>\n      <td>12.746262</td>\n      <td>12.620268</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 72 columns</p>\n</div>\n\n\n\n**Use pd.IndexSlice to extract all data from wdiT where the year level of the column names (the second level) is one of 2010, 2012, and 2014.**\n\n\n```python\nwdiT.loc[:, idx[:,[2010, 2012, 2014]]]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th>country</th>\n      <th colspan=\"3\" halign=\"left\">Canada</th>\n      <th colspan=\"3\" halign=\"left\">Germany</th>\n      <th colspan=\"3\" halign=\"left\">United Kingdom</th>\n      <th colspan=\"3\" halign=\"left\">United States</th>\n    </tr>\n    <tr>\n      <th>year</th>\n      <th>2014</th>\n      <th>2012</th>\n      <th>2010</th>\n      <th>2014</th>\n      <th>2012</th>\n      <th>2010</th>\n      <th>2014</th>\n      <th>2012</th>\n      <th>2010</th>\n      <th>2014</th>\n      <th>2012</th>\n      <th>2010</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>GovExpend</td>\n      <td>0.353485</td>\n      <td>0.354342</td>\n      <td>0.347332</td>\n      <td>0.685990</td>\n      <td>0.666454</td>\n      <td>0.653386</td>\n      <td>0.538888</td>\n      <td>0.528194</td>\n      <td>0.521146</td>\n      <td>2.334071</td>\n      <td>2.398873</td>\n      <td>2.510143</td>\n    </tr>\n    <tr>\n      <td>Consumption</td>\n      <td>1.011988</td>\n      <td>0.961226</td>\n      <td>0.921952</td>\n      <td>1.999953</td>\n      <td>1.967390</td>\n      <td>1.915481</td>\n      <td>1.675716</td>\n      <td>1.612550</td>\n      <td>1.598563</td>\n      <td>11.000619</td>\n      <td>10.534042</td>\n      <td>10.185836</td>\n    </tr>\n    <tr>\n      <td>Exports</td>\n      <td>0.550323</td>\n      <td>0.505969</td>\n      <td>0.469949</td>\n      <td>1.712270</td>\n      <td>1.607455</td>\n      <td>1.443735</td>\n      <td>0.774022</td>\n      <td>0.745484</td>\n      <td>0.690824</td>\n      <td>2.209555</td>\n      <td>2.045509</td>\n      <td>1.846280</td>\n    </tr>\n    <tr>\n      <td>Imports</td>\n      <td>0.572344</td>\n      <td>0.547756</td>\n      <td>0.500341</td>\n      <td>1.445409</td>\n      <td>1.354122</td>\n      <td>1.266126</td>\n      <td>0.827311</td>\n      <td>0.772692</td>\n      <td>0.745065</td>\n      <td>2.732228</td>\n      <td>2.560677</td>\n      <td>2.360183</td>\n    </tr>\n    <tr>\n      <td>GDP</td>\n      <td>1.782252</td>\n      <td>1.693428</td>\n      <td>1.613543</td>\n      <td>3.654924</td>\n      <td>3.559587</td>\n      <td>3.417095</td>\n      <td>2.657159</td>\n      <td>2.529323</td>\n      <td>2.452900</td>\n      <td>16.242526</td>\n      <td>15.567038</td>\n      <td>14.992053</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Exercise 6\n\n1. **Move just the `year` level of the index back as a column.**\n\n\n```python\n# remove just year level and add as column\nwdi_1 = df.set_index([\"country\", \"year\"])\nwdi_1.reset_index([\"year\"])\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>year</th>\n      <th>GovExpend</th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>Imports</th>\n      <th>GDP</th>\n    </tr>\n    <tr>\n      <th>country</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>Canada</td>\n      <td>2017</td>\n      <td>0.372665</td>\n      <td>1.095475</td>\n      <td>0.582831</td>\n      <td>0.600031</td>\n      <td>1.868164</td>\n    </tr>\n    <tr>\n      <td>Canada</td>\n      <td>2016</td>\n      <td>0.364899</td>\n      <td>1.058426</td>\n      <td>0.576394</td>\n      <td>0.575775</td>\n      <td>1.814016</td>\n    </tr>\n    <tr>\n      <td>Canada</td>\n      <td>2015</td>\n      <td>0.358303</td>\n      <td>1.035208</td>\n      <td>0.568859</td>\n      <td>0.575793</td>\n      <td>1.794270</td>\n    </tr>\n    <tr>\n      <td>Canada</td>\n      <td>2014</td>\n      <td>0.353485</td>\n      <td>1.011988</td>\n      <td>0.550323</td>\n      <td>0.572344</td>\n      <td>1.782252</td>\n    </tr>\n    <tr>\n      <td>Canada</td>\n      <td>2013</td>\n      <td>0.351541</td>\n      <td>0.986400</td>\n      <td>0.518040</td>\n      <td>0.558636</td>\n      <td>1.732714</td>\n    </tr>\n    <tr>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <td>United States</td>\n      <td>2004</td>\n      <td>2.267999</td>\n      <td>9.311431</td>\n      <td>1.335978</td>\n      <td>2.108585</td>\n      <td>13.846058</td>\n    </tr>\n    <tr>\n      <td>United States</td>\n      <td>2003</td>\n      <td>2.233519</td>\n      <td>8.974708</td>\n      <td>1.218199</td>\n      <td>1.892825</td>\n      <td>13.339312</td>\n    </tr>\n    <tr>\n      <td>United States</td>\n      <td>2002</td>\n      <td>2.193188</td>\n      <td>8.698306</td>\n      <td>1.192180</td>\n      <td>1.804105</td>\n      <td>12.968263</td>\n    </tr>\n    <tr>\n      <td>United States</td>\n      <td>2001</td>\n      <td>2.112038</td>\n      <td>8.480461</td>\n      <td>1.213253</td>\n      <td>1.740797</td>\n      <td>12.746262</td>\n    </tr>\n    <tr>\n      <td>United States</td>\n      <td>2000</td>\n      <td>2.040500</td>\n      <td>8.272097</td>\n      <td>1.287739</td>\n      <td>1.790995</td>\n      <td>12.620268</td>\n    </tr>\n  </tbody>\n</table>\n<p>72 rows \u00d7 6 columns</p>\n</div>\n\n\n\n2. **Completely throw away all levels of the index.**  \n\n\n```python\n# throw away all levels of index\nwdi_2 = df.set_index([\"country\", \"year\"])\nwdi_2.reset_index()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>country</th>\n      <th>year</th>\n      <th>GovExpend</th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>Imports</th>\n      <th>GDP</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>Canada</td>\n      <td>2017</td>\n      <td>0.372665</td>\n      <td>1.095475</td>\n      <td>0.582831</td>\n      <td>0.600031</td>\n      <td>1.868164</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>Canada</td>\n      <td>2016</td>\n      <td>0.364899</td>\n      <td>1.058426</td>\n      <td>0.576394</td>\n      <td>0.575775</td>\n      <td>1.814016</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>Canada</td>\n      <td>2015</td>\n      <td>0.358303</td>\n      <td>1.035208</td>\n      <td>0.568859</td>\n      <td>0.575793</td>\n      <td>1.794270</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>Canada</td>\n      <td>2014</td>\n      <td>0.353485</td>\n      <td>1.011988</td>\n      <td>0.550323</td>\n      <td>0.572344</td>\n      <td>1.782252</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>Canada</td>\n      <td>2013</td>\n      <td>0.351541</td>\n      <td>0.986400</td>\n      <td>0.518040</td>\n      <td>0.558636</td>\n      <td>1.732714</td>\n    </tr>\n    <tr>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <td>67</td>\n      <td>United States</td>\n      <td>2004</td>\n      <td>2.267999</td>\n      <td>9.311431</td>\n      <td>1.335978</td>\n      <td>2.108585</td>\n      <td>13.846058</td>\n    </tr>\n    <tr>\n      <td>68</td>\n      <td>United States</td>\n      <td>2003</td>\n      <td>2.233519</td>\n      <td>8.974708</td>\n      <td>1.218199</td>\n      <td>1.892825</td>\n      <td>13.339312</td>\n    </tr>\n    <tr>\n      <td>69</td>\n      <td>United States</td>\n      <td>2002</td>\n      <td>2.193188</td>\n      <td>8.698306</td>\n      <td>1.192180</td>\n      <td>1.804105</td>\n      <td>12.968263</td>\n    </tr>\n    <tr>\n      <td>70</td>\n      <td>United States</td>\n      <td>2001</td>\n      <td>2.112038</td>\n      <td>8.480461</td>\n      <td>1.213253</td>\n      <td>1.740797</td>\n      <td>12.746262</td>\n    </tr>\n    <tr>\n      <td>71</td>\n      <td>United States</td>\n      <td>2000</td>\n      <td>2.040500</td>\n      <td>8.272097</td>\n      <td>1.287739</td>\n      <td>1.790995</td>\n      <td>12.620268</td>\n    </tr>\n  </tbody>\n</table>\n<p>72 rows \u00d7 7 columns</p>\n</div>\n\n\n\n3. **Remove the `country` of the index and *do not* keep it as a column.**\n\n\n```python\n# Remove country from the index -- don't keep it as a column\nwdi_3 = df.set_index([\"country\", \"year\"])\nwdi_3.reset_index([\"country\"], drop=True)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>GovExpend</th>\n      <th>Consumption</th>\n      <th>Exports</th>\n      <th>Imports</th>\n      <th>GDP</th>\n    </tr>\n    <tr>\n      <th>year</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>2017</td>\n      <td>0.372665</td>\n      <td>1.095475</td>\n      <td>0.582831</td>\n      <td>0.600031</td>\n      <td>1.868164</td>\n    </tr>\n    <tr>\n      <td>2016</td>\n      <td>0.364899</td>\n      <td>1.058426</td>\n      <td>0.576394</td>\n      <td>0.575775</td>\n      <td>1.814016</td>\n    </tr>\n    <tr>\n      <td>2015</td>\n      <td>0.358303</td>\n      <td>1.035208</td>\n      <td>0.568859</td>\n      <td>0.575793</td>\n      <td>1.794270</td>\n    </tr>\n    <tr>\n      <td>2014</td>\n      <td>0.353485</td>\n      <td>1.011988</td>\n      <td>0.550323</td>\n      <td>0.572344</td>\n      <td>1.782252</td>\n    </tr>\n    <tr>\n      <td>2013</td>\n      <td>0.351541</td>\n      <td>0.986400</td>\n      <td>0.518040</td>\n      <td>0.558636</td>\n      <td>1.732714</td>\n    </tr>\n    <tr>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <td>2004</td>\n      <td>2.267999</td>\n      <td>9.311431</td>\n      <td>1.335978</td>\n      <td>2.108585</td>\n      <td>13.846058</td>\n    </tr>\n    <tr>\n      <td>2003</td>\n      <td>2.233519</td>\n      <td>8.974708</td>\n      <td>1.218199</td>\n      <td>1.892825</td>\n      <td>13.339312</td>\n    </tr>\n    <tr>\n      <td>2002</td>\n      <td>2.193188</td>\n      <td>8.698306</td>\n      <td>1.192180</td>\n      <td>1.804105</td>\n      <td>12.968263</td>\n    </tr>\n    <tr>\n      <td>2001</td>\n      <td>2.112038</td>\n      <td>8.480461</td>\n      <td>1.213253</td>\n      <td>1.740797</td>\n      <td>12.746262</td>\n    </tr>\n    <tr>\n      <td>2000</td>\n      <td>2.040500</td>\n      <td>8.272097</td>\n      <td>1.287739</td>\n      <td>1.790995</td>\n      <td>12.620268</td>\n    </tr>\n  </tbody>\n</table>\n<p>72 rows \u00d7 5 columns</p>\n</div>\n\n\n", "meta": {"hexsha": "e631853f91183cb205018cfca3da36468d69f734", "size": 115972, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Session_7/3_the_index_exercises.ipynb", "max_stars_repo_name": "remi-sudo/Classes", "max_stars_repo_head_hexsha": "71497927ed4d54ddf6fd5abe2ddabb5966eb0304", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Session_7/3_the_index_exercises.ipynb", "max_issues_repo_name": "remi-sudo/Classes", "max_issues_repo_head_hexsha": "71497927ed4d54ddf6fd5abe2ddabb5966eb0304", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Session_7/3_the_index_exercises.ipynb", "max_forks_repo_name": "remi-sudo/Classes", "max_forks_repo_head_hexsha": "71497927ed4d54ddf6fd5abe2ddabb5966eb0304", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6736353078, "max_line_length": 211, "alphanum_fraction": 0.3740902977, "converted": true, "num_tokens": 22156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28140560742914383, "lm_q2_score": 0.06008665522337757, "lm_q1q2_score": 0.0169087217115201}}
{"text": "# Rich Output\n\nIn Python, objects can declare their textual representation using the `__repr__` method.  IPython expands on this idea and allows objects to declare other, rich representations including:\n\n* HTML\n* JSON\n* PNG\n* JPEG\n* SVG\n* LaTeX\n\nA single object can declare some or all of these representations; all are handled by IPython's *display system*. This Notebook shows how you can use this display system to incorporate a broad range of content into your Notebooks.\n\n## Basic display imports\n\nThe `display` function is a general purpose tool for displaying different representations of objects. Think of it as `print` for these rich representations.\n\n\n```python\nfrom IPython.display import display\n```\n\nA few points:\n\n* Calling `display` on an object will send **all** possible representations to the Notebook.\n* These representations are stored in the Notebook document.\n* In general the Notebook will use the richest available representation.\n\nIf you want to display a particular representation, there are specific functions for that:\n\n\n```python\nfrom IPython.display import (\n    display_pretty, display_html, display_jpeg,\n    display_png, display_json, display_latex, display_svg\n)\n```\n\n## Images\n\nTo work with images (JPEG, PNG) use the `Image` class.\n\n\n```python\nfrom IPython.display import Image\n```\n\n\n```python\ni = Image(filename='images/ipython_logo.png')\n```\n\nReturning an `Image` object from an expression will automatically display it:\n\n\n```python\ni\n```\n\nOr you can pass an object with a rich representation to `display`:\n\n\n```python\ndisplay(i)\n```\n\nAn image can also be displayed from raw data or a URL.\n\n\n```python\nImage(url='http://python.org/images/python-logo.gif')\n```\n\n\n\n\n\n\n\n\nSVG images are also supported out of the box.\n\n\n```python\nfrom IPython.display import SVG\nSVG(filename='images/python_logo.svg')\n```\n\n\n\n\n    \n\n    \n\n\n\n### Embedded vs non-embedded Images\n\nBy default, image data is embedded in the notebook document so that the images can be viewed offline. However it is also possible to tell the `Image` class to only store a *link* to the image. Let's see how this works using a webcam at Berkeley.\n\n\n```python\nfrom IPython.display import Image\nimg_url = 'http://www.lawrencehallofscience.org/static/scienceview/scienceview.berkeley.edu/html/view/view_assets/images/newview.jpg'\n\n# by default Image data are embedded\nEmbed      = Image(img_url)\n\n# if kwarg `url` is given, the embedding is assumed to be false\nSoftLinked = Image(url=img_url)\n\n# In each case, embed can be specified explicitly with the `embed` kwarg\n# ForceEmbed = Image(url=img_url, embed=True)\n```\n\nHere is the embedded version. Note that this image was pulled from the webcam when this code cell was originally run and stored in the Notebook. Unless we rerun this cell, this is not today's image.\n\n\n```python\nEmbed\n```\n\n\n\n\n    \n\n    \n\n\n\nHere is today's image from same webcam at Berkeley, (refreshed every minutes, if you reload the notebook), visible only with an active internet connection, that should be different from the previous one. Notebooks saved with this kind of image will be smaller and always reflect the current version of the source, but the image won't display offline.\n\n\n```python\nSoftLinked\n```\n\n\n\n\n\n\n\n\nOf course, if you re-run this Notebook, the two images will be the same again.\n\n## HTML\n\nPython objects can declare HTML representations that will be displayed in the Notebook. If you have some HTML you want to display, simply use the `HTML` class.\n\n\n```python\nfrom IPython.display import HTML\n```\n\n\n```python\ns = \"\"\"<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\"\"\"\n```\n\n\n```python\nh = HTML(s)\n```\n\n\n```python\ndisplay(h)\n```\n\n\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n\n\nYou can also use the `%%html` cell magic to accomplish the same thing.\n\n\n```python\n%%html\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n```\n\n\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n\n\n## JavaScript\n\nThe Notebook also enables objects to declare a JavaScript representation. At first, this may seem odd as  output is inherently visual and JavaScript is a programming language. However, this opens the door for rich output that leverages the full power of JavaScript and associated libraries such as [d3.js](http://d3js.org) for output.\n\n\n```python\nfrom IPython.display import Javascript\n```\n\nPass a string of JavaScript source code to the `JavaScript` object and then display it.\n\n\n```python\njs = Javascript('alert(\"hi\")');\n```\n\n\n```python\ndisplay(js)\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\nThe same thing can be accomplished using the `%%javascript` cell magic:\n\n\n```javascript\n%%javascript\n\nalert(\"hi\");\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\nHere is a more complicated example that loads `d3.js` from a CDN, uses the `%%html` magic to load CSS styles onto the page and then runs ones of the `d3.js` examples.\n\n\n```python\nJavascript(\n    \"\"\"$.getScript('//cdnjs.cloudflare.com/ajax/libs/d3/3.2.2/d3.v3.min.js')\"\"\"\n)\n```\n\n\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n```python\n%%html\n<style type=\"text/css\">\n\ncircle {\n  fill: rgb(31, 119, 180);\n  fill-opacity: .25;\n  stroke: rgb(31, 119, 180);\n  stroke-width: 1px;\n}\n\n.leaf circle {\n  fill: #ff7f0e;\n  fill-opacity: 1;\n}\n\ntext {\n  font: 10px sans-serif;\n}\n\n</style>\n```\n\n\n<style type=\"text/css\">\n\ncircle {\n  fill: rgb(31, 119, 180);\n  fill-opacity: .25;\n  stroke: rgb(31, 119, 180);\n  stroke-width: 1px;\n}\n\n.leaf circle {\n  fill: #ff7f0e;\n  fill-opacity: 1;\n}\n\ntext {\n  font: 10px sans-serif;\n}\n\n</style>\n\n\n\n```javascript\n%%javascript\n\n// element is the jQuery element we will append to\nvar e = element.get(0);\n    \nvar diameter = 600,\n    format = d3.format(\",d\");\n\nvar pack = d3.layout.pack()\n    .size([diameter - 4, diameter - 4])\n    .value(function(d) { return d.size; });\n\nvar svg = d3.select(e).append(\"svg\")\n    .attr(\"width\", diameter)\n    .attr(\"height\", diameter)\n  .append(\"g\")\n    .attr(\"transform\", \"translate(2,2)\");\n\nd3.json(\"data/flare.json\", function(error, root) {\n  var node = svg.datum(root).selectAll(\".node\")\n      .data(pack.nodes)\n    .enter().append(\"g\")\n      .attr(\"class\", function(d) { return d.children ? \"node\" : \"leaf node\"; })\n      .attr(\"transform\", function(d) { return \"translate(\" + d.x + \",\" + d.y + \")\"; });\n\n  node.append(\"title\")\n      .text(function(d) { return d.name + (d.children ? \"\" : \": \" + format(d.size)); });\n\n  node.append(\"circle\")\n      .attr(\"r\", function(d) { return d.r; });\n\n  node.filter(function(d) { return !d.children; }).append(\"text\")\n      .attr(\"dy\", \".3em\")\n      .style(\"text-anchor\", \"middle\")\n      .text(function(d) { return d.name.substring(0, d.r / 3); });\n});\n\nd3.select(self.frameElement).style(\"height\", diameter + \"px\");\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n## LaTeX\n\nThe IPython display system also has builtin support for the display of mathematical expressions typeset in LaTeX, which is rendered in the browser using [MathJax](http://mathjax.org).\n\nYou can pass raw LaTeX test as a string to the `Math` object:\n\n\n```python\nfrom IPython.display import Math\nMath(r'F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx')\n```\n\n\n\n\n$$F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx$$\n\n\n\nWith the `Latex` class, you have to include the delimiters yourself.  This allows you to use other LaTeX modes such as `eqnarray`:\n\n\n```python\nfrom IPython.display import Latex\nLatex(r\"\"\"\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\"\"\")\n```\n\n\n\n\n\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\n\n\n\nOr you can enter LaTeX directly with the `%%latex` cell magic:\n\n\n```latex\n%%latex\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n```\n\n\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n\n\n## Audio\n\nIPython makes it easy to work with sounds interactively. The `Audio` display class allows you to create an audio control that is embedded in the Notebook. The interface is analogous to the interface of the `Image` display class. All audio formats supported by the browser can be used. Note that no single format is presently supported in all browsers.\n\n\n```python\nfrom IPython.display import Audio\nAudio(url=\"http://www.nch.com.au/acm/8k16bitpcm.wav\")\n```\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"http://www.nch.com.au/acm/8k16bitpcm.wav\" type=\"audio/x-wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\nA NumPy array can be auralized automatically. The `Audio` class normalizes and encodes the data and embeds the resulting audio in the Notebook.\n\nFor instance, when two sine waves with almost the same frequency are superimposed a phenomena known as [beats](https://en.wikipedia.org/wiki/Beat_%28acoustics%29) occur. This can be auralised as follows:\n\n\n```python\nimport numpy as np\nmax_time = 3\nf1 = 220.0\nf2 = 224.0\nrate = 8000\nL = 3\ntimes = np.linspace(0,L,rate*L)\nsignal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times)\n\nAudio(data=signal, rate=rate)\n```\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"data:audio/wav;base64,UklGRqS7AABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YYC7AAAAADUWvSvyPzdS/WHKbjt4Bn7+fxV+WXj3bjhifVJDQBYslBZiAC/qpdRswCGuU557kf2HJIIcgPWBoIfykKKdTa15v5rTEuk7/2kV8CopP3ZRSmEqbrJ3mH2vf+Z9TXgNb3Bi11K9QK0sQxcmAQPrhNVPwQOvLZ9IkreIxYKggFiC34cLkZOdFq0bvxbTbeh4/o0UASosPnNQSGAwbcd2w3z2fk9923fGblZi7FL/QBwt3hfoAefrg9ZlwiawVqBuk9OJzoOOgSSDg4iAkdadJa31vrvS3ue5/aIT8Sj/PDBP+F7da3t1h3vUfU98BncibuhhuVIJQWQtYRilAtjso9eqw4mxzKHtlE+LPYXkgleEiolTkm6ee60Hv4jSZuf//KsSwyeiO65NXF0zas9z5nlJfOh6zXUhbSdhPlLaQIItzBhbA9Xt39gexSmzjqPCliuNEYeihPKF9YqDk1mfGq5Uv3/SCOdN/KkReCYYOvBLd1szaMVx4HdYehp5MXTDaxNgfFFwQHUtHRkJBNvuN9q9xgW1l6XsmGOPR4nGhvKHwowPlZegAa/bv6LSxOak+58QFCVkOPhJSVnhZV9veXUCeOh2MnIIaqpecVDLPzwtUxmsBOjvp9uFyBm356dmm/aR3otOiVeK8Y73limiMLCewPHSneYG+48PmSOINslH11Y+Y6BssnJJdVF002/yZ+5cHU/rPtYsbBlEBfvwLd11ymO5e6ownuGU1I44jB+NgZE6mQ+kqLGcwW7Tk+Z1+noOCCKGNGVFI1ROYIppj28vcllxFG2CZeBagU3PPUMsZxnOBRHyyN6IzOC7T61GoSGYJZKBj0aQbpTXm0WmZ7PWwhjUp+by+WMNZCBhMtBCMFEUXSFmEWy4bgJu+Gm6YoFYnkt3PIIrQxlJBinzdOC9zo2+YLCkpLKbz5Unk8yTuJfLns2obrVMxPDU2+Z/+UwMsB4dMAxAAU6TWWdiPGjlak9qgWaaX9FVdEnjOpIq/xi0Bj/0L+IQ0WfBq7NHqJKfzpkml6yXXJsVoqSru7f9xffVL+ce+TYL7hy8LR09m0rOVWFeFGS6ZkJmsmImXNNSBEcVOXQpmhgMB1P19+N/02rELbctrL2jH557m+SbVp+zpciuTrroxy3XpefP+CQKIRtAKwY6/0bKURNanF87YuBhjV5gWIlPUEQMNycoFBhRB2P2yeUG1pTH4bpPsC+ovaIioHGgpKOhqTiyJL0OypHYPOiU+BgJSxmuKMo2M0OJTX9V2FpsXStdF1pKVPVLWUHKNKsmbBeCB2v3o+ej2OHKxb6stOOspacYpU6lQ6jdrfG1PMBtzCTa9ehu+BMIbhcHJm0zOT8RSatQzVVRWCdYUVXoTxlIID5PMgIloRadB2z4gulT203O08I+udax0qxXqneqLq1ksvC5k8MDz+Tb0ele+BcHjRVPI/MvFztmRJtLf1DvUtlSQVA9S/dDqTqeLysjtBWiB2P5ZOsS3tXRCccBvgK3P7Lcr+mvYrIytzK+KcfP0dHdz+pl+CYGqxOJIF4szzaMP1RG80pJTUVN6kpNRpQ/9ja3LCghpRSPB076Ru3e4HTVYcvxwmO86beitZ6127dEvLXC+srQ1Orf8OuE+EIFyRG5HbQoZzKIOtpALkVkR29HUUUbQfI6CDOcKfkecxNkByv7Ju+z4yjZ2M8JyPXByb2ju5K7lL2VwXXHA88E2C7iM+27+GsE6w/gGvck4i1eNTI7ND9HQV1BeT+sOxU25C5QJqAcHxIgB/r7AvGO5u3catREzbHH28PbwcHBiMMhx27MQ9No25zkmO4L+aQDEg4DGCshRSkTMGI1DDn2OhQ7aTkENgExiyrVIh4aqhDEBrr82PJt6b/gEdmd0pTNGcpFyCPIs8nlzJ3RtNf63jLnHfB0+e0CQAwkFVUdlCSsKm8vujJ2NJk0JTMnMLkrASYtH3QXEw9NBmj9pvRL7Jrkyt0Q2JfTfdDazrbOENDa0v3WVdy34u/pxPH3+UgCeApGEncZ1B8uJV0pQyzNLfEtsSwaKkImSiFbG6UUXQ2+BQP+aPYo73rokeKY3bXZA9eV1XLVmNb92IrcIeGd5tDsifOT+rYBuwhsD5UVCRueHzMjryUBJyInFCbiI6AgaRxiF7IRiAsVBYz+Hvj/8VzsYOcw4+rfpd1w3FLcSN1I30DiFeap6tTvbvVJ+zcBDAeZDLQRNxYAGvUcAh8YIDIgUx+FHdgaYxdEE54OlQlSBAD/xvnO9DzwNOzS6C/mXeRm41DjGeS25RroLevX7vjyb/cY/M0AbAXPCdYNYhFbFKoWQRgXGScZdBgHF+0UOxIGD2oLhgd3A2D/XvuS9xf0CPF67n/sJOtx6mfqBetD7BPuZfAl8zr2jPkA/XgA3AMRB/8JjwyxDlYQdBEEEgYSfBFuEOcO9QyqChoIWwWDAqr/5PxI+un32PUj9NXy9vGK8ZHxB/Ln8ib0uPWO95j5xPsA/jkAYAJiBDIGwwcKCQAKnwrmCtUKcQq/CcgIlQc0BrAEFwN3Ad7/V/7v/K/7n/rI+Sv5zPis+Mf4Gfme+U/6IvsQ/A79FP4Y/xAA9wDFAXQCAQNpA6sDyAPCA5wDWgMBA5cCIQKnAS4BvABUAPz/tv+D/2X/W/9j/3z/ov/Q/wIANABiAIcAngClAJkAeQBFAP7/pP87/8j+Tv7V/WD99/yg/GD8PPw5/Fn8nvwJ/Zn9S/4c/wMA/gACAgcDBQTxBMEFbgbwBj4HVAcuB8oGKQZMBTgE9QKJAQAAZv7G/C/7rflP+CH3L/aD9Sb1HfVr9RL2Dvdc+PL5x/vN/fb/MAJrBJUGmwhsCvgLLw0HDnQOcQ78DRMNvQsACucHggXiAhoAQP1p+q33IvXe8vXwd+9z7vXtA+6f7sjvd/Gj8zz2Mflq/NH/SgO8BgoKGg3RDxkS3hMOFZ4VhxXFFF0TVRG8DqMLIAhOBEkAMvwl+EX0sfCG7eDq1Oh259Pm9ObZ54Dp3+vk7nzyjPb1+pf/TATyCGQNfBEbFSAYdBoAHLYcjhyFG6EZ7RZ8E2cPzArMBY4APPv99fvwXuxM6OfkTOKR4Mbf9t8h4UHjSeYj6rTu2vNv+Uf/NQUNC58QvxVEGgge7CDXIrYjgSM1ItofgBw9GDITgw1bB+kAYPrx88/tLOg04xHf5NvK2dXYD9l72g/du+Bk5ejqHvHY9+L+BAYKDboT4BlKH8wjQieMKZgqWSrPKAMmCCL6HP8WQhD4CFgBnvkD8sbqHuRC3mHZotUn0wTSRtLt0/DWOduq4BvnW+409mn+ugboDrIW2h0oJGgpby0cMFYxEjFPLxcsgSevIcoaCBOjCtsB9fg18ODnOOB52dvTi8+tzFrLoMt+zenQydX821LjlOuE9N39VQemEIUZrCHaKNYubzN+Nuo3pTetNRAy5ixWJpEe0RVYDHECZ/iH7iDlfNze1IXOpMlixt3EIsUyxwDLcNBc147fyujJ8j791wdDEjEcUSVdLRM0PDmwPFA+DD7lO+k3MjLtKk8imhgXDhgD8/f77Iji7dh10GPJ8cNLwJG+0r4PwTnFMsvP0tbbAuYG8Y78Pgi+E7QeySitMRo50z6rQoFEQ0TyQZw9YTdvLwImYRveD9EDmPeR6xrgjtU/zHjEd75tuny4trgau5q/FcZazivYPuM97837jAgXFQ0hDyzHNec9L0RrSHhKQ0rNRyVDbTzXM6QpIh6pEZgEV/dK6tfdYdJByMm/O7nNtKSy0rJatSi6HMEAypLUgOBw7f76wAhNFjojIi+oOXdCSknqTTBQCFByTX5IUUEhODMt2yB3E24FL/cl6cDbaM9+xFm7QbRwrw2tLa3Sr+m0TbzGxQ7Rzd2i6yL63AhgFzslADJNPcdGIk4lU6VVjVXcUqNNCkZJPKswiCNGFVEGH/ck6NbZpcz4wCu3jK9ZqrunyqeHquCvrLexwaPNJtvU6Tr54AhPGA0nqDS0QNJKs1IXWNJazVoFWI9SkkpLQAg0JyYSFz8HJ/dH5xvYGsqxvUKzIKuNpbSir6J/pRKrPbPDvVTKkNgI6Ef4zAgbGbEoFzfaQ5dO+Va8XLJfw1/qXD1X5k4jREc3tSjbGDYIRveN5o7Wx8esuqKvAacPofud352+oISmBa8CuibHDNZD5kz3owjDGSYqTDm+RhJS8FoRYUJka2SGYapbAVPNR2U6LiueGjQJevf25THVsMXqt0ysMqPknJWZYJlJnDqiCKtwthrEntOF5Er2ZAhJGmsrRjtdSUJVl14RZX5owWjVZdBf31ZFS109jy1XHDkKwveB5QTU08NttUSptZ8PmYWVNJUimDmeSqcSszbBStHR4kP1EgisGoEsBT23SyNY6WG7aGJswWzSaaxjfFqITixA1i8FHkELHvgv5QbTM8I3s4qmjpySlc6RYJFOlIOaz6Psr3y+Ec8p4Tn0rQfuGmcthz7JTbVa5mQLbOtvaHB7bTpn1V2SUdBCADKlH0wMjPj95DjSz8BJsSGkvZlwknOO543RkB2XmqAArfC798yR3y/zNwcPGx0uzT+TT/Vcimf+bhdzs3PMcHhq5mBfVEVFCjQ1IVcNC/ns5JnRp7+jrwqiRpesj3eLy4qujQmUrp1SqpS5/soK3iXysQYQG6Uu1UAUUeJe1GmTceJ1nnbCc2FtrGPtVohH8TWyIl8OmPn75CnRvb5HrkagKZVHjd2IEIjnikyRDpvkp2u3KcmX3B3xHAbzGv4uoUFMUnxgw2vHc0p4KHlZdvJvJGY5WZZJszcaJGQPMvon5efQD74zrdaeaJNDi6eGuIV/iOeOv5i7pXi1e8c62xvwfAW4GikvMUI7U8JhVW2adU96TnuReCpyS2hAW21LTDlrJWMQ2fpw5dLQnr1qrLudBZKiidaExYN5ht2MwZbYo76z9sX22SDv0ARhGigvhELgU7Niim4Jd+17D31legV0H2r+XApNvDqjJloRifvV5enQaL3pq/Sc/pBliGuDOILWhDCLF5U+oj6yncTM2C7uHATvGfsunUI8VE9jYW8UeCN9Z37We4J1nWtzXmpO/ju+J0cSQfxU5izRbb2xq4KcVpCMh2iCE4GYg+OJxJPuoPywcsO/10ftYQNkGaMue0JQVJdj22+7ePJ9WH/gfJ92xWycX41PEj28KCgT//zr5pjRrL3Bq2ScDJAYh86BWIDBgveIyZLsn/qvdsLR1mzsoALBGCMuIEIcVItj92/9eFh+33+EfVt3k214YG9Q9T2aKfsTwv2Y5yzSI74ZrJqcH5AIh5yBBoBRgmyIKJI4nzmvrMED1qHr3AEJGHwtjUGhUyxjtW/beFZ+/H/AfbR3B24EYQ9Rpj5WKr8Uh/5b6ObS0b62rCKdjpBch9OBHYBJgkSI4ZHVnrquFsFZ1ebqFgE9F64sxEDiUntiF29UeOp9r3+Ufap3IG4/YWxRIj/vKnAVTf8w6cbTtL+XrfydWpEUiHKCn4CpgoCI9pHCnn+utMDT1D/qUABfFr4rxz/fUXphHm5rdxd9+H7/fDx33G0pYYRRaD9iKw4WEAAW6sjUy8C7riWfgJIviXmDioFygyCJaJIBn4quicBz1Kvpjv9xFasqlz6aUClgy2wfdt172X0DfGt2PW3AYFZRdz+vK5YW0gAL6+rVE8IgsJyg/5OqiuaE3oKihCOKNpOTn9uulsA61C7pz/51FHkpNz0WT4xeIWt0dD16UXyfejZ1QWwFYOJQTj/TKwgXjgEO7CzXi8PEsWCi1ZWGjLiGmoQ5homLYJR4oHOv3MAq1MnoFv5tEykoqDtUTaNcIGlpcjl4YnrVeJ9z6Gr2XiZQ7D7OK2EXQwIb7YrYMMWks22kAJi+ju6Iu4Y2iFKN5pWwoVKwW8FF1HzoZf1bEr4m7jlXS3Jay2YDcNN1DnimdqVxNGmVXSNPUD6eK6AX8AIx7gHa/8a9tcGmfppSkYWLQYmXinyPyJc6o3mxFMKK1EvovvxBETolCjghSftXJWRCbQxzV3UTdEtvJWfiW9lNej1DK8MXkgNO75Hb98gOuFqpS50/lHqOKYxbjQaSBJoXpeeyCMP71DboIfwiEJ8jADa2RkFVMWEqauhvQHIgcZJsvWTcWUhMaTy7KsoXKARv8DbdE8uTujSsZaCBl8yRcI9+kO2UmZxEp5y0NsSZ1T3okvv/DvAh0TMYREdS8l2+ZmpsyW7NbXxp/GGHV29KHTsHKrMXsQST8e7eU81JvUyvyaMWm3aVFJMAlDGYhZ/CqZe2n8Vk1mToEfvaDS8ggTFLQRFPa1oCY5Ro+Godagxm5V7iVFFIlzklKX4XKgW48rfgss8twKCycqf6nneZEpfcl86bx6KOrNi4Qsdc16nooPq2DGAeEy9QPqFLoFb4Xmpkz2YUZkNieVvvUe5F1jcWKCkXkgXb843iLtI8wyu2Xqspo8mdZpsQnMKfW6anr127H8mC2A7pQfqUC4MciiwtO/xHlFKkWvBfUWK2YSVevFewTkdD3TXZJrMW6AX79G/kxNRzxuq5ia+gp2miDKCZoAmkQKoLsyW+NcvW2ZTp9Pl3Cp0a6SnlNyVES04LVipbg10EXbVZsFMoS15AqjNvJR0WKwYW9lrmcNfNydi97rNarFSnAaVypaGocq63ti7BhM1X2zvqu/lfCa8YMid6NB9AykkxUR1WaFgEWPZUWE9YRzU9QDHYI2UVWQYp90voMNpIzfPBirhTsYSsQaqYqoWt77KqunfECdAE3QPrmPlQCLsWaSTwMPA7FUUbTMtQBVO6Uu1PuEpEQ845oC4UIowUcgY0+D/qAd3f0DbGV72GtvWxxq8GsLKys7ffvv3HxNLe3u3rivlLB8UUkSFMLZs3MUDMRjxLX00pTZ1K0kXuPio2zCslIJITdAY0+Tbs39+P1JzKUsLvu6K3jLW4tSS4urxUw73LstXj4Pjsk/lRBs8Srh6RKSUzITtKQXJFe0dXRwtFqkBaOk0yxCgLHnUSXwYo+ivuyOJV2CLPdceIwYe9jrupu9a9AcIGyLbP0tgS4yXutPlkBdsQwRvCJZEu6zWaO3Q/XEFIQTo/RjuLNTkuiyXHGzgRMwYO+x3wt+Us3MPTvcxOx57Dx8HUwcPDgsfyzOTTI9xr5XPv7fmFBOwOzxjkIeQpkzDBNUY5CjsCOzE5qDWFMPIpJCJaGdoP7gXk+wryq+gQ4HvYI9I6zeHJMcg0yOjJO80S0kXYoN/r5+LwPvq2AwMN2hX5HSIlHyvEL+4yiTSJNPMy1i9LK3olkB7HFlsOkAWr/O7zoOv/40XdpNdH00zQyM7Ezj3QJtNk19TcSeOR6nDyqPr5AiML5hIHGlEgkyWoKXIs3i3kLYcs1CniJdQg0xoOFL0MGQVf/cn1k+705x3iOt1w2djWhdV+1cDWPtni3I7hG+db7R30LPtOAk4J9Q8RFnMb9B9zI9clECcXJ/AlpyNPIAYc7hYzEQELiQQB/pj3gfHr6/7m4eKv34HdY9xc3Gndft+K4nDmEutI8On1yPu1AYUHCg0aEo8WSBoqHSIfJCApIDYfVB2VGhEX5hI2DicJ4QOP/ln5aPTg7+XrkugA5kDkXONZ4zPk4uVV6HbrK+9V89H3ffwxAcwFKQomDqcRkhTTFlsYIBkfGV0Y4Ba5FPsRvQ4aCzAHIAMJ/wv7RPfR88zwSu5c7A/raupu6hrrZOxA7pzwY/N/9tX5Sv3CACMEUwc5CsEM2Q5zEIURChIAEmoRUhDBDscMdgrhBx8FRgJu/6v8E/q697D1A/S+8unxhvGX8Rby/vJF9N31uPfF+fP7MP5oAIwCiwRWBuEHIgkQCqgK6ArQCmUKrQmwCHoHFQaOBPUCVQG9/zj+0vyW+4v6uPkh+cf4rPjL+CP5rPlf+jX7JPwk/Sr+Lf8kAAkB1AGBAgsDcAOvA8kDwAOXA1MD+AKNAhcCnQEkAbIATAD2/7H/gP9j/1v/Zf9//6X/1P8GADgAZQCJAJ8ApQCXAHYAQAD3/5z/Mv++/kT+y/1X/e/8mvxc/Dr8Ovxd/Kb8FP2n/Vz+Lv8YABMBGAIdAxkEAwXRBXsG+AZCB1MHKAe/BhkGNwUfBNgCaQHf/0T+pPwO+475NPgL9x72efUi9SD1dvUj9if3e/gX+vD7+v0kAGACmgTCBsQIkAoVDEUNFA54DmwO7Q37DJsL1gm3B0wFqALe/wP9Lfp19+/0svLQ8FzvZO7x7Qrusu7n76Hx1/N49nP5svwaAJQDBAdOClcNBhBEEv0TIBWjFX0VrRQ3EyMRfg5bC9EH+gPz/9r70ff282nwSe2u6rDoYefO5v/m9ees6RnsLO/O8uf2Vvv7/7EEVAm/Dc8RYRVZGJ0aGBy7HIAcZRtvGaoWKxMKD2QKXgUdAMv6j/WU8AHs/eeo5B7id+DB3wXgReF545Pmfuod70306fnF/7MFhwsRESYWnBpPHh8h9CK8I3AjDSKcHy0c2Re+EgMN0wZeANX5avNR7bvn0+LD3q3bqtnO2CLZp9pT3RXh0eVm66rxbPh6/5wGnA1DFFsatB8hJH4nrymfKkUqoCi6JaYhgxx2FqsPWAizAPn4ZPEx6pnj0N0F2WHVAdP80VzSINQ/16PbK+Gv5/7u4PYa/2sHkw9SF2oeoyTKKbYtRDBfMfswGC/CKxEnJSEsGloS6gkdATj4fu81557f9thy0z/PgsxQy7jLuM1D0UHWjtz6403sSPWm/h8IaRE7Gk8iZilGL8AzrTb1N4s3cDWwMWcsvCXfHQ0ViAubAZH3ue1f5M7bStQOzk7JMcbRxDzFcsdky/bQ/9dK4JnppfMg/rgIHRP8HAkm+i2RNJc55TxdPvE9ojt/N6YxQiqKIcEXMA0rAgb3Fuyy4SzYz8/eyJHDE8CDvu6+VcGnxcXLg9Ol3Obm+PGH/TYJrxSVH5MpWjKlOTg/5kKQRCZEqUEpPcc2sy4qJXMa4A7MApT2luov37rUicvmww2+L7psuNS4ZrsSwLTGHc8M2TbkRfDd/JsJHRYCIuwshTaAPp5ErEiKSiVKf0epQsc7DDO6KCAdlxB+Az32OenY3HvRfMcqv8e4ibSRsvGyqrWousfB0sqE1Yzhje4j/OUJaBdDJBIwdjodQ8NJMk5FUOlPH036R6BASDc4LMYfUBI/BAD2AOit2nDOqMOsusOzJa/3rE2tJ7BwtQO9psYR0uve0uxb+xUKjxhXJgEzKj55R6VOc1O9VW1VhFIYTU5FYzuhL2IiDBQNBdz16+ax2JzLE8BytgWvB6qip+un4KpvsG24nsK1zlXcF+uH+i0Kkhk8KLk1oEGRSz9TbFjsWqxaqlf9Uc1JWD/vMvAkxhXoBdH1++Xj1gDJvrx9spCqNaWYos+i3KWoqwe0vL51y8/ZXemn+SwKcBryKTg41ERiT45XF13QX6JfjFylVhdOJEMgNm0nfhfNBt31L+VG1Z7Gq7nRrmimsaDcnQCeHqEgp9ivBrtUyFvXqOe9+BQKKht3K306xkfpUo9bcmFkZEpkJmELWypSxEYwOdgpMRm7BwD2h+TY03fE3LZwq5CigJxymYCZqpzbouOrf7dVxfvU+eXL9+YJwBvMLIY8ckojVj5feWWjaKFocmUtXwBWMkocPCws2xqwCDn2A+Sc0o3CU7RdqAqfpJhelVOVhZjeniyoKrR8wrPSU+TT9qMJMhzwLVI+10wPWZhiKGmKbKJsbmkFY5dZbE3hPmcufByrCYb2ouOQ0d/AEbKZpdqbIZWkkX6Rs5Qsm7ekDLHMv4bQuOLX9UwJghzjLuE/9U6qW51lfmwXcEtwFm2QZupcblB8QYYwEB6oCuf2Y+O10G+/GLAnowKZ+pFFjgOON5HJl4ehJ65IvXbOLOHY9OIIsBymLzJByVDzXUhod29Gc5dzZnDKafZfNVPoQ4YylR+oC1n3RuML0D2+aK4HoYSWMI9Gi+aKFI64lJ+ef6v0uobMr9/Z82cIvBw4MEVCVFLpX5lqEXIVdoV2W3OxbLhivVUkRmU0CSGmDNz3SuOQz0m9Aq07n2CUxoypiCmITYv8kQOcF6nRuLnKRN7b8t0HqBybMBpDlVOLYY9sSnSBeBB583VBby1lBFgsSB82aSKjDW74beNFz5K856vEnZmSvopvhs+F5IiYj7aZ8abkthLJ79zh8UUHdhzPMLJDi1TXYiduInaIejh7K3h4cVJnCFr/SbM3tCOaDgz5r+Mozxm8FqujnDCRGImahNqD3YaOjbqXEaUttZLHsNvs8KAGJhzVMAxEN1XOY2FvlXcqfPt8AXpUcyVpxFuYSx455iSMD7b5DeQ5z927j6rWmyWQ14csg0uCOYXiixGWeaOxszzGitr/7/EFuhutMCpEmFVwZD1wpHhkfVZ+c3vRdKNqOF33TF46/iV1EGr6h+R3z927U6pgm3iP+oYmgiSB+oOUir6UKqJxshPFgNkb7zoFMxtbMA1EsFW8ZLpwT3k2fkl/gHzvdctrYV4YTnE7+iZTESX7GuXfzxi8X6o+myqPgoaJgWWAIYOmicKTKKFusRjElNhD7nsEkxrdL7VDgFWzZNlwlHmfftJ/JX2tdptsPV/7TlM81yclEub7xuVx0Iy8tKpxmzqPb4ZUgRGAroIZiR+Tc6CssE7Dxtd47bgD3Bk3LyRDCFVXZJtwdHmffvJ/ZH0IdxFtyl+dTwU9lCjoEqv8iOYq0Tm9T6v3m6iPwYaJgSaApILviNaSDKArsLXCGte87PECEBlqLlxCSVSnY/9v8Hg2fqh/O30BdyxtCWD8T4Q9LymcE3P9XucK0h2+MKzPnHKQeIcmgqWAAYMoieiS95/ur1HCkdYR7CoCMBh4LV5BRlOmYgdvCHhlffR+qXyXdu1s9l8YUM49pik9FDr+R+gO0zW/Va35nZiRkYgqg46BxoPDiVWTMqD0ryHCLdZ662MBPxdjLCxAAFJVYbRtvnYtfNd9sHvJdVJskl/vT+I99ynKFAD/QOk01IDAvK5xnxeTDIqWhN+C84TCih+UvqA/sCjC7tX36p4APhYsK8g+eVC2XwlsE3WOelJ8UHqZdFpr3V6BT789IipCFcL/SOp71fzBYrA3oe6U54tnhpiEh4YkjEOVnaHQsGfC19WL6uD/LxXXKTU9s07KXQZqCHOLeGZ6iXgGcwhq1V3NTmU9JSqjFX4AXOvf1qbDRrJHoxuXII6biLeGgIjojcSWzqKosd7C6dU26ib/FhRlKHQ7sUyWW69noXAmdhR4XnYScVpoe1zSTdI8/inrFTQBe+xe2HzFZrSfpZuZtZAxizqJ3YoMkJ+YUKTGso3DJdb76XX+8xLYJok5dkoaWQdl321gc191z3O+blJm0FqRTAU8rikZFuABoe332XvHvbY9qGyco5MnjiCMnI2QktOaJKYqtHfEi9ba6c39yRE0JXY3A0hbVg9ixWo8cEly4HALbPFj1FgKS/86MiksFoICzu6n26HJSrkdq4qf6JZ4kWWPvJBylWCdSKjUtZnFHNfV6TH9mhB6Iz41XUVaU8teV2e9bNVukW37aDlhiFY9ScA5iigiFhgD/+9r3evLCbw9rvOif5ojlQeTOpSvmESgvKrEt/XG2tft6aP8aA+tIeMyhkIcUD5bl2PmaAZr5mmRZSpe7VMrR0c4tyf7FZ8DMvFA31bO976ZsaKmZ54lmQOXEphGnH2jfa34uYvIxNgj6iP8NQ7PH2kwgT+kTG1XiV+8ZN5m4WXPYchaBVHURJU2tya2FRcEZPIl4d/QEsIttZWqmqJ4nVabQpwzoAini7BwvFnK2tl46rP7Aw3kHdItUjz1SFlTMVtAYGFihmG3XRRX0007Qqo0iiVRFX4ElfMW44PTVMX2uMeuFqcbovufxqBzpOOq47Mqv2DMHdvt6lX71AvtGyEr/DgTRQlPk1Z4W5Rd2VxOWRJTVkphP4gyMiTNFNMEwfQS5T/WvMjwvDWz1asHp/Ckm6UEqQyvgrckwp3Oi9yB6wr7qwruGVsogzUCQX9Ks1FoVnpY3VeXVMROlEZHPC8wrSIpFBUF6PUV5xDZRcwXwdq31LA6rC6qvarhrX6zaLtexRHRJt427NL6iAnoF4El6zHHPMFFlkwTURhTllKVTy5KjULvOKEt/CBjE0IFBvcd6fLb7M9mxbG8DravsbOvKLAHsze4j7/UyLrT7d8L7bD6bgjeFZciNy5kONJAQEeAS3JNCU1MSlJFRT5bNd4qIB9+ElkFG/gn6+PerNPaybbBfrtgt3m11rVxuDS998OEzJbW3eEB7qP6XwfUE6EfayrfM7c7t0GyRY1HO0fBRDZAvjmPMeonGx13EVsFJPkx7d7hg9duzuXGIMFJvXu7w7scvnDCm8hs0KPZ+OMY7636XAbKEaAciiY9L3U2/zuwP25BMEH4Ptw6/jSMLcUk7BpQEEUFIfo57+LkbNsf0znM7sZkw7XB68ECxObHeM2I1N/cOuZP8M/6ZgXFD5oZmiKAKhExHTZ9ORs77Tr2OEk1BjBWKXEhlRgJDxcFD/s88evnZN/n16zR48ytySHISMgfypTNidLX2EngpOim8Qj7gATFDZAWnB6uJZArFjAgM5g0dzTAMoIv2yrwJPIdGRaiDdIE7vs48/bqZuPB3DrX+dId0LnO1c5u0HPTzNdU3d3jNOsd81r7qQPNC4UTlhrMIPYl8CmeLOwt1C1aLIspgSVdIEkadxMdDHQEu/wr9f/tb+er4d7cLNmv1njVjNXp1oHZPN384Zrn5+2y9MT75QLgCX0QjBbdG0kgsSP8JRwnCifKJWkj/B+gG3oWshB5Cv4Ddv0S9wTxeuue5pPid99e3VjcaNyL3bbf1eLM5nzrvPBk9kb8MwL/B3sNgBLmFo4aXR1BHy4gHiAXHyEdURq+FoYSzQ24CG8DHv7t+AP0hu+X61To0uUk5FPjY+NP5A/mkejA64DvsvM0+OH8lQEsBoIKdg7sEckU+xZyGCcZFhlEGLkWhBS6EXIOyArbBsgCsv64+vf2jPOR8BvuOuz76mPqduov64bsbe7T8KPzxPYe+pX9CwFpBJQHcwrzDAEPjxCWEQ4S+BFYETUQmw6ZDEEKqAfjBAkCMv9y/N75i/eI9eTzqPLc8YPxnfEm8hbzZPQC9uL38/kj/GD+lwC4ArQEegb/BzkJIAqxCukKygpZCpsJmQheB/UFbQTSAjIBnP8Z/rb8fvt4+qn5F/nD+Kz40fgs+bn5cPpI+zn8Ov0//kL/OAAbAeQBjgIVA3cDswPKA74DkwNMA/AChAINApMBGwGpAEQA7/+s/33/Yv9b/2b/gf+p/9j/CgA8AGkAiwCgAKQAlQByADoA8P+T/yn/tP46/sH9Tv3n/JT8WPw5/Dv8Yvyt/B/9tf1s/kH/LAApAS4CMgMuBBUF4QWHBgAHRgdSByIHtAYIBiIFBgS6AkkBvv8h/oH87fpw+Rn49PYN9m71HvUk9YH1NvZA95v4PPoa/Cf+UwCQAskE7wbtCLMKMgxaDSAOfA5mDt0N4gx5C6wJhgcWBW0Cov/G/PL5Pfe89IbyrfBD71Xu7e0T7sfuB/DM8Qv0tfa2+fn8ZADfA0wHkgqUDTsQbhIbFDEVphVyFZUUERPwEEAOFAuCB6UDnP+D+3z3p/Mi8AvtfeqN6E3ny+YM5xPo2elU7HTvIvND97j7XgAVBbUJGg4gEqcVkRjEGi4cvxxxHEMbOxlnFtkSqw78CfAErf9a+iL1LvCm66/naeTy4V7gvd8W4Gvhs+Pf5trqhu/C9GT6QwAxBgEMgxGMFvMalB5QIQ8jwSNdI+MhXB/ZG3MXSRKDDEwG0/9K+eXy1exL53Tid95324zZydg32dXamd1x4UHm5us28gD5EQA0By8OyxTVGhwgdCS5J9AppSovKm4obiVCIQoc6xUUD7cHDgBV+MbwnukV41/drNgh1d7S9tF00lbUkdcO3K3hROih7473zP8bCD0Q8Bf4HhwlKir6LWowZTHhMN8uayueJpogjRmrETEJXwB798jui+YG33TYC9P2zlnMScvTy/TNoNG71iLdo+QH7Q32cf/oCCoS7xrxIvAptC8ONNk2/TdvNzA1TjHmKx8lKx1IFLcKxAC89uzsoOMj27jTms37yALGyMRaxbbHy8t+0aTYCOFp6oH0Av+ZCfYTxh2+JpQuDDXvORY9Zj7SPVs7EzcXMZQpwyDmFkkMPQEZ9jLr3eBt1yzPXMg0w9+/eL4Ov5/BGcZbzDnUdd3L5+vygP4vCp4VdCBbKgUzLjqaPx5Dm0QFRFxBszwrNvUtTySDGeINyAGR9ZvpRt7p09bKV8OnvfW5X7j1uLW7jMBXx+PP79kw5U7x7f2pCiIX9iLHLUA3FT8JRepIl0oCSixHKkIeOz8yzicdHIMPYwIk9Sno2tuX0LnGjr5XuEi0grIVs/+1LLt2wqfLedaZ4qvvSf0JC4IYSyX+MEA7v0M4SnZOVVDFT8hMckfrP2w2OyuvHikRDwPR9NvmnNl6zdbCBLpKs96u5axxrYCw/LW+vYrHFtMK4APulfxOC70Zcif/MwQ/KEgjT71Tz1VIVSlSiEyORHk6ky45IdESygOZ9LPljdeVyjK/vbWCrrqpjqcQqD6rArExuY7Dys+H3Vvs1Pt5C9MaaSnINohCTEzHU7xYAluHWktXZlEDSWE+0jG2I3kUkQR69LDkrtXpx867vLEEquKkgaL1oj2mQqzWtLm/mMwR27PqB/uMC8QbMCtXOctFKVAfWG1d6V99XylcB1ZETSJC9TQkJiAWZAV19NLj/9N4xa24Ba7TpVigwp0lnoKhwKewsA+8hcms2A7pLvqFC48cxiyrO8pIu1MoXM5hf2QlZMBgaFpOUbZF+TeAKMIXQgaH9BnjgtJCw9G1maryoSGcVZmlmRGdgaPDrJK4k8Za1m/nTPlnCzUdKi7CPYJLAFffX9tlwmh8aAplhV4dVRpJ2TrGKl4ZJwew9IbiNtFKwTyze6dknj+YPZV4le+YiJ8TqUa1xcMf1NflY/gzC7cdXS+bP/RN9llCY5BprWx+bARpWGKtWEtMkz31LPEaEwjv9BbiHdCPv++wrqQtm7eUgJGikR6V2pukpTCyH8H+0UnkdffqChQeXTA3QR1Qm1xOZutsPXAocKts4GX6W0ZPJEAJL3kcBAlC9crhNc8TvuuuMqJNmIqRHo4mjqOReph5olOvpL74z8jigvaNCk4eLDGTQvtR7V4Baepvb3N1c/pvF2kCXwZSiEL/MPMd+Amp9aHhf87WvDGtCqDHlbuOG4sHi4CObJWWn7GsWLwRzlXhjvUdCmYeyjGxQ5BT62BZa4lyQXZkdu9y/GvAYYlUvUTWMl4f7Qoh9pvh+s3Yu8KrNp6dk0yMeohJiLmLspL+nE6qPLpMzPPfmfSdCVweNjKPRNlUlGJVbcd0sXjyeId1i24xZMtWv0aJNLYg4Aup9rXhps0Zu5+quJzQkT6KPYbthVGJT5Czmi2oU7iryqXep/MNCTIecjIvRdZV52PzbqN2vHoce8B3wXBUZstYjUgXNvoh0QxA9+7hgc2ZusepkJtikJSIZYT1g0mHRo65mE+mobYwyWzdufJvCOkdfzKQRYlW5GQycBt4YHzgfJZ5nHImaIVaI0p+NycjvA3k90bijM1WujqpvppSj0+H9IJkgqOFmYwRl7mkKLXex0vc0PHGB4MdXjK0RfBWi2UTcS55nX0+fgp7GnSjafdbf0u7ODwkoQ6T+LvixM1RuvmoQpqhjm6G64E7gWKES4u+lWuj6bO3xkTb8PASBwAdDzKbRQxX22WUcdx5cn4zfxh8OXXLaiBdoEzMOTUlfA9L+UvjKc6IugGpHZpPjvOFS4F6gIeDW4rBlGii57K9xVnaGvBWBmMclTFHRd9W1mW2cSR63n6/f8B8+HWca/1dgk2uOhImTRAK+vXjuM76ulOpTZpcjt6FE4EjgBODzYkclLKhJLLyxIvZT++UBa4b8TC4RGlWfGV6cQd64X7hfwF9VnYVbIxeJk5hO88mERHQ+rbkcc+lu+2p0ZrIji2GRYE1gAWDoInRk0qhobFYxN7Yku7MBOEaJDDwQ6xVzWTgcIV5e36af9p8UnYzbM1eiE7iO2wnxhGY+43lUdCJvM2qqZuQj+KG4IGygGCD1YnfkzChYLHxw1LY5e0DBP8ZMS/xQqhUzWPpb594rH3pfkx863X3a75eqE4wPOcnaxJj/HnmV9GivfOr0py1kPmH44KXgSKEbYpJlGehYrG9w+nXSu04AwsZGS69QWFTe2KXblZ3dXzOfVZ7InVga19ehE5JPD4o/RIt/XbngdLwvlutS540knOJTITmgkuFaIsNle6hqLG+w6XXwexuAgUY3ixWQNhR2mDrbKt12XpMfPp59nNvaq9dHE4tPG8oexP1/YPozNNwwAWvE6AMlE6LHIachNuGxYwtlseiMrL2w4fXTuyoAfEWgyu+Pg5Q7V7naqFz13hiejd4aHIiaa5cb03aO3ko5BO6/p7pNtUfwu6wJqI7loiNT4i5htCIhI6nl/GjArNkxJDX8evmANAVCir4PAhOtVyOaDlxcnYTeBB2eXB7Z1xbfUxQO1woNRR4/8Xqvdb8wxKzgqS9mB2Q5Io6iSmLo5B7mWulF7QKxcLXq+srAKMUdSgGO8ZLNVrjZXZurXNhdYVzKm56ZblZRUuOOhYobhQuAPbrX9gDxnC1JaeRmw2T2Y0djOWNIZOomzancbXpxR3Yf+t5/28TxybqOExJcFfnYlpriXBNcppwfWshY8ZXyEmTOaYnjRTcAC7tGdozyAW4DKq0nlSWK5FgjwCR/JUtnlGpELcAx6LYbuvR/jQSAiWoNp5GaVSfX+lnCm3bbk9tdGhwYIRVBkhgOAsnkBR/AWvu6duHys26M60hou6Z1pQAk3mUM5kIobqr9LhPyFLZeOs1/vQQKCNCNL1DI1ENXCdkM2kNa6hpEGVqXfRSAEb0NkYmeBQVAqzvy93+zMW9lrDXpdmd2Jj7lk2Yw5w4pHCuHLvXyS3an+um/bMPPSG7Ma5Aok01WBVgB2XnZqhlVWESWhhQt0NRNVUlQhScAu7wvt+Uz+rAM7TQqRCiLZ1Mm3mcqaC5p3Kxhr2WyzPb5Osm/XEOQx8XL3M96kkbVLlbimBsYlJhRV1oVvFMLEF1Mzkk7xMUAy/yv+FG0jnEBrgKrpCm0aHwn/mg4qSLq760MsCNzWXcR+y2/DENPB1YLBE6/UXCTxZXwVugXalc41hvUoFJYD5jMfIifBN8A23zy+MR1a7HC7yAslWrwKbjpMqla6mpr1G4HsO6z8LdyexY/PYLKxuBKYo24UEwSzFSrlaHWLFXM1QsTstFVTscL38h6xLQA6b04OXy10bLPcAtt1qw9ashqueqQa4RtCm8R8Yc0krfau0N/MAKExmXJuMymT1oRg1NV1EmU25SOU+gSdJBDTifLOIfOhISBNj1++fl2vvOmsQOvJq1bbGlr02wX7PAuEPArcmz1P3gK+7V+5EJ9habIx8vKjlvQbFHwEuATeZM+EnQRJg9ijTvKRoeaRE+BAL3Gero3czSG8kewRG7Ibdrtfi1wrixvZ3ETc1819niC++z+20I1xSSIEMrlzRKPCBC70WbRxtHdES+PyA5zzANJykceBBWBCH4OOz34LTWvs1YxrrADr1tu+G7Zb7iwjLJI9F22t7kDPCn+1MHuRJ+HVEn5i/9NmA86D99QRNBsz5wOm003Sz8IxAaaA9XBDX5Vu4P5K/afdK3y5HGLsOnwQbCRMRNyADOL9We3QvnLPGx+0cGnRBjGk4jGiuMMXU2sTkpO9Q6uDjoNIQvuSi9IM8XOA5BBDr6b/At57neVdc30Y7Me8kTyF/IWcrvzQPTa9nz4F/pbPLS+0gFhg5DFz4fOCb+K2YwTzOlNGI0iTIsL2gqZSRSHWkV6QwUBDH7g/JN6s7iQNzT1q7S8c+tzunOoNDE0zfY1t1z5NjryvML/FoEdwwjFCQbRSFXJjcqxyz4LcItKyxBKR4l5B++Gd4SewvPAxf8jfRt7evmOuGE3OvYidZt1Z3VFNfF2ZjdbOIa6HTuR/Vc/HwDcQoFEQUXRBycIO0jICYmJ/smoiUqI6gfOhsEFjEQ8AlyA+z8jfaJ8AzrP+ZH4kDfPt1O3HbcsN3w3yLjKufn6zLx4PbF/LECdwjsDeQSPBfSGo8dXx82IBIg9h7uHAwaahYmEmMNSAj+Aq79gfie8yzvS+sW6KblCuRM427jbeQ95s/oC+zV7w/0lvhG/fkBiwbaCsUOLxL/FCIXiRgtGQwZKhiQFk4UeREoDncKhQZxAlz+Zfqq9kjzV/Dt7Rns5+pf6n/qRuup7JzuC/Hj8wr3Z/rf/VQBrwTUB6wKIw0nD6sQpRESEvARRBEXEHMOagwMCm4HpgTMAfb+Ofyq+V33YfXF85Py0PGB8aTxNvIu84P0KPYM+CD6UvyP/sUA5ALcBJ0GHAhPCTAKuQrqCsQKTAqHCYAIQQfWBUsErwIQAXr/+v2b/Gb7ZPqb+Q75v/it+Nb4NvnH+YH6XPtO/E/9Vf5X/0wALQHzAZsCHwN9A7YDygO7A44DRQPnAnoCAwKJAREBoAA8AOn/p/96/2H/W/9o/4T/rP/c/w4AQABsAI4AoQCkAJMAbgA1AOn/i/8f/6r+MP63/UX94PyO/FT8OPw9/Gb8tfwq/cP9ff5U/0EAPgFEAkgDQgQoBfAFkwYIB0kHUAcbB6gG9wUMBewDnQIpAZz//v1f/Mz6Uvn/99/2/fVk9Rz1KPWM9Un2Wve7+GL6RPxV/oMAvwL4BBsHFQnWCk4Mbw0sDn4OXw7MDcgMVwuBCVUH3wQzAmX/ify3+QX3ivRb8orwKu9H7uvtHO7c7ifw9/FA9PL2+vlB/a4AKQSUB9UK0Q1uEJcSOBRCFagVZhV7FOkSvBABDssKMgdQA0X/LPso91jz3O/P7E3qa+g758nmG+cx6Afqkey973bzn/ca/MMAeQUVCnQOcRLrFccY6hpCHMEcYRwgGwcZIhaFEkwOlAmBBDv/6fm19MjvS+ti5y3kx+FH4LvfKeCS4e7jLec36/HvNvXg+sEArwZ6DPQR8RZJG9gefyEoI8MjSCO3IRsfhBsMF9QRAgzDBUj/wPhf8lns3OYW4i3eQ9tx2cfYTtkF2+HdzuGy5mfsw/KV+aoAywfADlIVThuCIMQk8SfuKagqFio6KCAl3SCQG2AVew4WB2r/svcp8AvpkuLw3FTY5NS90vPRj9KO1OXXe9ww4troRvA7+HwAywjmEI0YhB+TJYgqPC6OMGkxxTCjLhErKSYNIOwY+xB3CKL/v/YT7uPlcN7116bSsM4zzEXL8cs0zv/RONe43U7lwu3T9joAsAnrEqIbkSN4Kh8wWTQCNwI4TzftNOkwYiuAJHYcgRPmCe//6PUf7OLiedoo0yjNq8jWxcPEe8X8xzbMCdJM2cfhO+te9eT/eQrOFI8ecSctL4Q1RDpFPWw+sD0RO6M2hTDkKPofChZgC08ALfVP6grgsdaMzt7H28Kuv3G+Mr/swY3G9Mzx1Ejesujf83r/JguMFlEhISuuM7M6+D9SQ6NE4EMMQTk8izU1LXMjkhjkDMMAjvSi6F7dGdMmysvCRL2+uVa4G7kJvAvB/cer0NXaK+ZY8v3+twsmGOgjny74N6c/cEUjSaFK3EnWRqZBcjpuMeAmFxtvDkgBC/Qa597atc/5xfW967cMtHeyPLNYtrS7KcN/zHDXqOPJ8G7+LQybGVAm6DEIPF5EqUq1TmFQnU9tTOZGMz+MNTwqlx0AEN8Bo/O45Y3Yh8wHwl+51LKbrtismq3esIy2fL5wyB7ULOE279D9hwzqGooo+zTaP9NInU8CVN5VH1XJUfRLy0OLOYMtDiCVEYUCV/N85GvWkclUvgy1A65yqX6nOqigq5qx+rmCxOLQut6g7SL9xgwTHJQq1DdtQwNNSlQHWRNbXVrnVspQNUhnPbMweiIrEzoDJfNm43rU1cbiugCxfKmUpG+iH6OjpuCsqbW6wL/NVdwK7Gf86gwWHWwsczq+RutQq1i+XfxfUl/CW2VVbUwbQcgz2CTAFPsDDfN34rvSVMS0tz2tQqUEoK2dUJ7soWWojLEbvbnK/9l26qD79gzzHRIu1jzKSYhUvFwlYpZk+mNVYMBZblCkRL42JSdSFsgEDvOt4S7REMLLtMapWaHHmz2Z0Jl+nSukp62oudTHvNfm6M766AypHoYv+z6PTNhXfGA3ZttoUmidZNddNVT/R5I5XinfF54FJ/MK4dPPCsApsp6mxJ3glyOVopVdmTig/qlnthHFjtVd5/T5www6H8cw4kAMT9ha52PyaclsVGyVaKdhvlcnS0E8gCtlGXwGWPOM4KzOQ77Rr8ejhJpSlGKRzJGOlY6clqZZs3bCeNPc5RP5iAylH9UxiUJAUYZd+2ZTbV1w/m86bCplBVsZTsg+iS3hGmAHnvMz4LfNu7zCrUKhnZcfkf2NT44UkjKZcaODsATAfdFm5C34NwzsH7Ay8UMpU+FftWlXcJJzTXOIb19oCF7SUCRBdi9QHEgI+PP+3/bMc7v+qxGfEZVLjveKL4vyjiaWkqDorb+9n8/94kP30wsPIFgzGUXHVOdhE2z7cmh2PXZ8ckFrwmBPU1FDRDGxHTIJZvTt32fMa7qHqjad4JLXi1OIb4gsjG6T/p2Kq6q74s2k4Vj2XAsPIM4zAUYYVphjFW4+ddp4zXgUdc5tMGONVU5F8DIBHx0K5fT+3wnMo7lcqbGbDZHFiRKGEYbDiQ2Rtpttqce5R8xd4G711QrtHxM0qUYeV/JkuW8ed+h6+HpNdwNwUWWJVxdHeDQ/IAYLdfUw4N3LG7l9qIKamY8XiDeEGIS6hwSPvZmSpxm40soq34b0PgqsHyc0EUfWV/Rl/XCaeJB8v3wled5xIWdBWalI2zVnIewLEvaB4OHL07jqp6uZhI7OhsOChIIUhleNFpj+paK2g8kO3qPzmglLHws0OkdDWKBm4nGxedB9H36aelxznmiyWgNKFDd3IswMvPbx4BTMyLijpyuZz43phbeBWIHShAiMw5axpGW1X8gK3cby6gjMHsEzJkdkWPVmZ3Jjeqh+Fn+qe310xmnaWyNLIzhvI6UNcfd94XXM+7iopwGZeo1rhROBlYD0gxeLxpWuo2S0Zscg3PLxMQgyHkoz1UY6WPNmjXKuehd/pX9UfD11mGq3XAZMBjlKJHUOL/gl4gLNa7n3py6ZhI1ThdmAO4B+g4aKH5X2oqCzmsZT2yjxbwd+HacySEbGV5tmU3KTehx/yn+XfJ51E2tJXatMujkJJTkP9Pjm4rrNFbqPqLGZ7Y2ghQmBS4Bug1eK0ZSMohuz/8Wk2mrwpwaxHNsxgUUKV+5lu3EUerh+hX90fJx1NGuMXQ9NPTqoJfAPvvm+45vO+LpvqYeatY5ShqGBxYDFg4mK3ZRvoteylMUV2rrv2wXOG+YwgUQGVu5kxXAveex91n7oezl1/GqCXTNNjzomJpgQjPqs5KLPE7yVqrGb2Y9oh6GCqIGEhB6LQpWiotSyW8Wo2RvvDQXWGswvS0O+VJxjc2/nd7d8v332enN0amonXRRNrTqCJi8RW/ut5c/QY70ArCudWJHiiAmE9IKqhRSMApYkoxSzV8Ve2Y3uPgTMGY0u4UEyU/phx209dhx7P3ydeUxzfWl9XLJMmDq6JrMRKfzA5h/S576srfSeMZO8iteFqIQ2h22NG5f2o5izh8U42RLucQOxGCwtREBlUQpgwmszdBx5WHred8NxNmiDWw1MTDrMJiQS9fzi55DTnMCZrwqhYZX2jAmIwoYniSaPj5gYpWC07sU52aztpwKIF6wreD5aT89dZ2nLcbl2DHi7ddlvlWY4WiNLyzm4Jn4SvP0R6R/Vf8LDsWuj5peMj56KQIl8iz+RXJqLpmy1isZh2V3t4gFTFg8qfzwSTUpbuWYHb/RzXHU1c5BtnGSeWPVJEzl8JsISfv5M6srWjsQntBKmvZp9kpKNIYwzjreTgpxNqLy2Xsex2SbtJQEUFVcoWjqSSoBYumPqa9FwS3JNcOpqSmK0VoJIIzgYJuwSN/+P647Yx8bDtv+o453FleOQYY9KkYyW/55eqlC4acgq2gjtcADNE4cmDjjbR3JVbWB3aFJt224Hbedno198VMxG/TaLJf0S5//Z7GnaJsmUuSysVaFimY+UAJO+lLyZ0aG9rCm6q8nM2gTtx/+AEqIknjXxRCVS1lyxZHppD2tlaYpkplz3UdJEnzXTJPMSigAo7lncqMuWvJivEKVQnZGY+JaOmEWd+KRor0O8JcuY2xztKP8wEakiCzPXQZxO+FicYE5l62ZpZdZgVlkmT5ZCCjTyI84SIgF571reSs7Hvz6zEKmLoeecR5u1nCShcKhesqC+1syO3FDtmP7fD6AgWTCRPtpK11Q8XNBgcmIYYc1ctlULTBlAPjLmIosSqwHK8GrgCtEiwxq3Ua0Qpo2h6Z8woValN6ydtT7BvM6v3aLtF/6ODokejC0iO+RGeFCUVwRcp11zXHNYyFGoSFw9PDCwISsSJAIa8ofi5NOkxiq7z7HZqn2m26T9pdepS7AjuRrE2dD73hHupv1ADWccpiqON71C3UuqUu9WkFiAV8tTj00ARWA6BS5QIKwRjAJm863k1dZJymi/hbbkr7WrGKoWq6WuqLTuvDTHKtNw4J/uR/33Cz0aqifYM2k+DEeATZZRL1NCUthODkkUQSg3myvGHg8R4QKs9Nvm2tkOztDDb7sqtS+xm694sLyzTLn6wIrKrtUP4kvv+/y0Cg0YnSQFMO05CUIeSPxLik2+TJ9JSUToPLYz/SgTHVMQIwPq9Q3p79zv0V/IicCouue2YLUethe5Mr5GxRjOZNjX4xbww/x6CdoVgSEYLE012TyGQihGpkf3RiNEQz9+OAwwLyY2G3gPUQMf90DrEeDn1RDNzsVZwNe8YrsDvLK+V8PNyd7RStvH5QHxofxKCKYTWh4VKI0wgTe+PB1Ah0H0QGo+ADrbMywsMSMzGX4OaQNJ+HTtPeP02d7ROcs3xvvCnMEjwonEt8iMztfVXt7e5wryk/wnB3QRKhsAJLErBTLLNuI5Mzu4Onc4hDQBLxkoByAIF2YNawNm+aTvb+YQ3sXWxdA9zE3JCch5yJbKTs6A0wLan+Eb6jLznfwRBkYP9hfdH8AmaiyzMHszrzRKNFAy1C70KdcjsRy5FC8MVgN1+s7xpek54sDbbdZm0sfPo87/ztbQFtSk2FreCuV97Hj0vfwKBSANwBSwG7whtiZ6Ku4sAS6uLfkr9Ci4JGkfMhlFEtoKKgN0+/Hz2+xp5szgLNys2GXWZNWw1ULXDNr23d7inOgC79z19fwTBAILixF9F6oc7SAnJEEmLifqJnkl6SJSH9IajRWvD2cJ5wJi/An2DvCe6uLl/eEL3x/dR9yG3NbdK+Bw44jnU+yo8V33RP0uA+8IWw5HE5AXFRu/HXofPSADINMeuBzFGRUWxRH5DNkHjAI+/RX4O/PT7v/q2+d85fLjRuN744zkbeYO6VfsLPBt9Pn4q/1cAuoGMgsTD3ESMxVHF54YMhkAGQ4YZhYXFDYR3A0lCi4GGQIG/hP6XvYF8x7wwO3569bqW+qK6l7rzuzL7kTxI/RQ97H6Kf6dAfUEFAjlClMNTA/FELQRFBLnETAR+A9MDjoM1gk0B2oEjwG6/gD8dvkv9zv1qPN+8sXxgPGs8UfyR/Ok9E72N/hO+oL8v/70ABADAwXABjkIZQk+CsAK6gq9Cj4KdAloCCQHtgUpBI0C7QBZ/9v9f/xP+1H6jfkF+bv4rvjc+EH51fmS+m/7Y/xl/Wv+bP9fAD4BAwKnAigDgwO5A8oDuQOJAz4D3wJwAvkBfwEHAZgANQDj/6P/d/9f/1z/av+H/7D/4f8TAEQAbwCQAKIAowCRAGoALwDi/4L/Fv+g/ib+rf08/dj8iPxR/Df8P/xs/L78Nf3R/Y7+Z/9VAFQBWQJdA1YEOgX/BZ8GEAdMB04HFAebBuYF9gTRA38CCQF6/9z9Pfyr+jT55PfJ9u71W/UZ9S31mfVc9nX32/iI+m/8gv6yAO8CJwVHBz0J+QpqDIINNw6ADlcOuw2tDDMLVgkjB6gE+AEo/0z8fPnO9lj0MPJp8BLvOu7q7Sfu8u5J8CTydvQv9z36if34AHIE2wcYCw0OoRDAElQUUBWpFVkVXxTBEocQwA2CCuIG+wLt/tX61PYK85bvlOwf6kvoKufI5irnUeg36s/sCPDL8/z3fPwnAd0FdQrNDsASLxb8GA8bVRzCHE4c+xrQGNsVMRLrDSoJEgTJ/nj5SfRk7/LqFufx457hMuC63z7gu+Er5Hvnlutd8Kz1XPtAAS0H8gxjElQXnRsZH60hQCPDIzEjiSHXHiwboxZdEYELOwW8/jX42/He62/muuHl3RHbV9nG2GfZN9sq3i7iJOfp7FDzK/pCAWIIUQ/YFcUb5yATJSgoCiqoKvspBCjQJHUgFBvTFOENdAbF/g73jO966BHig9z/16nUn9Ly0azSyNQ72OvctuJy6evw6fguAXsJjxEqGQ8gCCbkKnsurjBqMaYwZS61KrIlfh9KGEsQvQfk/gP2X+085dvdd9dE0mzOD8xEyxLMds5h0rfXUN775X7umfcEAXgKqxNUHC8k/SqIMKE0JzcEOC03pzSCMNwq3yO/G7oSFAkZ/xT1VOsm4tLZmtK5zF7IrsXAxJ/FRsijzJfS9tmI4g3sPPbFAFkLpBVWHyIowi/6NZU6cD1vPoo9xDowNvAvMSgvHywVdwpi/0H0bek53/bV7s1ix4XCgL9uvlm/PMIFx5DNrNUd35rp1PRyAB0MeRctIuUrUzQ1O1NAgkOnRLhDuEC8O+k0cSyVIp8X5Au//4vzqud43E3SeclDwuW8i7lRuEW5YLyNwabId9G82yjnYvMMAMUMKRnYJHUvrTg2QNRFWUmnSrFJfUYgQcI5mzDvJREaWg0tAPLyDebk2dfOPMVgvYO307NwsmiztLY/vN7DWs1p2Ljk6fGU/1ANsxpUJ9AyzDz5RBZL8E5oUHBPDUxXRnc+qjQ6KX0c1g6vAHXyl+SA15fLO8G+uGOyXa7QrMetQLEgtz2/Wcko1U/iavAK/74NFhygKfM1rUB6SRNQQ1TnVfFUZFFcSwRDmzhxLOIeVxBBARXyR+NM1ZHIer1ftImtL6l0p2ioB6w2sse6ecX80e/f5+5w/hEOUh28K904T0S2TchUTVkfWy1aflYrUGNHaTyRLz0h2xHjAdDxHuJJ08TF+rlHsPmoSqRhok+jDqeErYC2vsHozprdY+3H/UgOZx6lLYw7rUepUTJZCl4LYCJfVVu/VJFLEUCXMosjXxOSAqbxHeF50TTDvrZ5rLektZ+dnYCeWqIPqWyyKr7wy1Tb3+sS/WUOVR9cL/09xkpRVUxddmKnZMpj5V8TWYlPj0OANcgl4RRNA5bxQ+Dcz+HAyLP4qMagc5sqmQCa753bpJCuw7oYyR/ZX+pR/GgOGyDfMDBAmE2rWBRhjmbvaCFoKmQlXUlT30ZIOPQnYBYUBKDxkN9zzs6+G7HGpSidhpcNldOV0ZntoO+qi7dhxv/W5OiF+1IOuyAuMiRCIVC1W4ZkT2rgbCRsH2jvYMtW/knsOgkq1xfjBMHxBN8+zfq8t67louGZ85NJkfuRBJZHnY2nhrTQw/XUcOey+iUONCFJM9hDX1JtXqFntW12cM9vw2tvZAxa6ExqPQcsRxm6Bfrxnt49zGa7nqxXoPOWu5DijX6OjJLumW2kt7FowQTTBebY+eENhyExNEtFU1TQYGJqvXCvcx9zEG+gZwldmk+9P+otqxqXBknyXd5vyxO60KoenmCU4o3Zil2La4/mlpOhI68rvzDRp+T5+IgNtiHkNH5G+VXeYsdsZ3OHdhB2BHKAar5fEVLjQa8vAxx3B6zyQd7WygK5UKk7nCmSaYsxiJuIpYwwlAOfyqwcvXrPV+MY+BsNwCFkNW5HU1eWZM9urnX9eKF4m3QLbSliSlTZQ1QxSx1ZCCLzSd5wyjK4HaivmlCQU4nuhTyGPIrQkb6csao/u+bNF+I295wMpyGxNR5IYFj3ZXhwk3cOe8561XY/b0dkQ1adRdcygh47Carzct48yqK3N6d6mdeOoIcPhEGEM4jIj8ea2qiVuXbM6uBU9g0MbCHMNY5IH1n/ZsJxE3m5fJd8rXgZcRZm+FcsRzQ0pB8bCkH0vt45ylO3nqadmL2NU4aYgquCi4YcjiGZSKchuCvL0t929W4LESG2Nb1IkVmwZ6xyLnr8ffl9I3qYcpJnZ1mESGs1sSD3Cub0KN9nykO3U6YZmASNa4WJgX2BR4XLjM+X/KXmtgnK0d6d9MIKlyBwNa1ItlkJaDVz43rXfvN+NXu6c7toj1qiSXg2piHNC5j1sd/EynO3U6bsl6uM6YTjgLiAaITZi9CW+aTltRHJ6d3L8wsK/x/8NF9IkFkKaF1zMXtJf4R/4Xt8dI9pbVuFSlo3gSKbDFT2V+BPy9+3oKYWmLKMzoSmgFuA74NHiyiWQKQgtUbIHN0B80oJTB9bNNRHHlm1ZyZzGXtRf6t/J3zfdAtqAFwrSw84QCNgDRn3F+EGzIi4NqeWmBmNGYXTgGmA3YMVi9iV06OZtKjHa9xC8oIIfx6PMw1HY1gKZ5BynHrvfml/BnzgdC9qR1yTS5U44SMZDuX38OHnzGy5Fqhsmd+NyYVpgeCAMYREi+CVs6NRtDrH2tuQ8bQHmh2ZMg1GYFcKZptxuXklfr1+fnuAdPtpQFy6S+s4YyTEDrX44eLxzYi6PKmVmgKP3oZngsCB7YTUi0GW4aNKtP3GaNvs8OIGnxx8MdZEFla4ZEpwcnjzfKl9j3q/c21p6luhSw45xCRgD4j55uMhz9u7qaoQnIGQVojNgwmDD4bHjPyWXqSFtPPGGNtZ8A4GkBs5MGhDiFQUY51uyXZZeyx8OnmccoZoRltFS/84AiXqD1z6/uR10GK9WKzbnVuSMIqZhbqEl4cajhCYKqUCtRzH7NrX7zoFcBrTLsdBuFIiYZdsv3RbeUd6f3cYcUVnU1qnSrs4HCViEDD7J+bs0Ry/Sa70n4yUaozKh9GGhInOj32ZRabCtXrH5Npp72gEPxlNLfU/p1DjXjtqVnL4dv53YHU0b6tlEFnFSUM4EiXGEAD8XueC0wbBeLBYohOXAY9dikyJ1YvikUObr6fFtg3IAtsQ75kDARinK/Q9Wk5bXIpnkW81dFF13nLxbLljflehSJU34CQUEcz8o+g21R3D4rIEpe6Z85FRjSuMh45UlGGdaakLuNbIR9vN7tECtxbmKcg700uLWYdkc2wScUJy+29Qam9hnlU5R7E2iCRLEZH98ekF117FhrX2pxidPZWikGmPmpEil9afcKuUudXJs9uj7g8CZRULKHI5FEl4VjZh/miTbdVuumxUZ9BecFOORZc1CCRpEU7+SOvr2MfHX7grq4+g3JhNlASTCpVLmqCixK1huwvLSNyR7lcBCxQZJvY2IUYjU5pdNmW8aQxrHGn/Y9xb9VChQ0Y0XyNuEQH/pOzo2lXKa7uerk+kzZxQmPuW1JjNnb2lZLBvvXbMBd2a7qoArBITJFg0/UKST7dZHWGPZepmJWVSYJZYME5yQcAyjSJYEaj/BO733ATNpr5MslWoC6GnnEib9pykoSupTrO+vxjO7N2+7goASxH7IZkxqz/HS49VuVwQYXJi2WBRXABVIUsDPwMxkiEmEUEAZu8X39LPDcIztp2slKVNoeifbaHOpeisgbZNwu/P+9797nj/6Q/UH70uMDzHRyhRDVhDXKpdOVz+Vx1Ry0dUPBIvbSDYEMwAx/BE4bvSnMVMuiKxYqpAptikNaZIqvGw+rkaxfrRNeBa7/T+iQ6hHcgrjziVQ4ZMHlMsV5NYS1deU+9MMERoOe0sHx9tEEcBJvJ847zVT8mWvuG1cq95qxOqSasOr0S1t70kyDnUl+HU74L+LQ1lG7woyzQ1P6xH703RUTRTEVJzTnlIUkBBNpQqqR3kD7EBgPO85dHYI80Kw9S6vrT2sJavprAdtNy5tcFpy6vWIuNs8CH+1gsiGZ0l6DCsOqBChkg0TJBNkkxCSb9DNDzfMgooCRw9DwgC0/QB6PjbE9Gmx/i/Q7qwtlq1R7Zvube+8sXnzk7Z1eQi8dT9hwraFm8i6yz/NWU96EJdRq1H0EbPQ8Q+2TdGL08lQhp4DkwCHfZK6i3fHdVlzEjF+r+kvFu7KbwCv9DDasqb0iDcsOb28Zr9QQmSFDQf1ygwMQI4GD1PQI5B0UAePo05RTN4K2UiVBiVDXsCXveT7G3iOtlB0b7K4MXLwpXBRMLRxCTJGs+C1iHfsejo8nb9BghKEvAbsCRGLHoyHjcPOjs7mTozOB00ei54J08fQBaTDJQCkvjZ7rTlad041lbQ7sshyQLIlsjWyq/O/tOa2k3i2Or582f92QYGEKcYeyBFJ9Ms/TCkM7Y0LzQUMnkufSlIIw4cBxR0C5gCufka8f/opOFD2wrWINKgz5zOGM8O0WvUFNng3qLlI+0n9W/9uQXIDVsVOhwxIhMnvCoTLQguly3FK6UoUSTtHqQYqxE3CoUC0fpU80vs6eVf4Nbbb9hD1l7VxdVy11XaVd5R4x/pkO9y9o39qQSSCxAS8xcPHT0hXyRhJjQn1iZNJaYi+h5oGhUVLQ/eCFsC2PuF9ZTvMuqG5bXh194D3ULcl9z+3Wjgv+Po58DsHvLZ98L9qwNnCckOqRPjF1cb7R2UH0Eg8x+vHoEcfhm+FWMRjwxpBxoCzfyq99jye+616qDnUuXb40LjieOs5J7mTumj7IPwzPRc+Q/+vwJJB4kLYQ+yEmcVaxeyGDUZ9BjyFzsW3xPzEJAN0gnYBcIBsP3B+RP2wvLm75Tt2+vF6ljqlep36/Ps/O5+8WX0l/f6+nP+5gE6BVQIHQuBDXEP3hDBERYS3REbEdkPIw4KDKAJ+gYtBFIBf/7I+0P5AvcW9YvzavK78X/xtfFY8mHzxPR09mL4fPqx/O/+IgE7AysF4gZVCHsJTQrHCuoKtgowCmAJTwgHB5YFBwRqAssAOP+9/WT8N/s++n/5/Pi3+LD44/hL+eP5o/qD+3j8e/2B/oH/cwBQARICswIxA4kDvAPKA7YDgwM3A9YCZwLvAXUB/QCPAC0A3f+e/3T/Xv9c/2z/iv+0/+X/FwBIAHMAkgCjAKMAjwBmACkA2v96/wz/lv4b/qP9M/3Q/IL8Tfw2/EH8cfzG/EH94P2f/nr/agBpAW8CcwNqBEsFDgaqBhcHTgdMBwwHjgbUBd8EtwNhAugAV/+5/Rv8i/oW+cv3tPbf9VP1GPUz9ab1cfaQ9/34rvqa/LD+4gAfA1UFcgdlCRoLhQyVDUEOgQ5ODqkNkgwPCyoJ8AZwBL0B6/4P/EH5l/Yn9AbySPD77i7u6e0y7grvbPBR8qz0bveC+tH9QgG8BCMIWgtIDtMQ5xJvFF4VqRVLFUMUlxJREIANOAqRBqYClv5/+oH2vfJR71rs8eks6BvnyeY753PoaOoO7VPwIPRZ+N78jAFABtUKJQ8PE3EWLxkyG2ccwRw7HNUamRiUFdsRig3BCKIDWP4I+d3zAO+Z6szmt+N34R7gvN9U4ObhaeTM5/bryfAi9tj7vwGqB2oN0hK3F+8bWh/YIVUjwiMYI1ohkh7UGjkW5RD+CrEEMf6s91fxZOsD5l/hnt3h2j/ZyNiC2Wvbdt6P4pjnbO3f88D62wH4COEPXRY7HEkhYCVcKCQqpirdKcsnfiQMIJYaRRRHDdIFIP5r9vDu6ueR4RjcrNdx1IPS9NHL0gXVk9hc3T3jCuqR8Zj54AEqCjYSxBmYIHsmPiu4Ls0waDGEMCQuVyo4Je4epheZDwIHJv5H9avsl+RJ3fzW5NErzu/LRcs1zLvOxtI42OreqeY872D4zwFAC2oUBR3LJIEr7jDnNEo3AjgHN140FzBTKjwjBhvxEUEIQv5A9Inqa+Es2Q/STMwUyInFwcTGxZLIE80n06LaS+Ph7Bv3qAE5DHoWHCDRKFUwbDbkOpc9bz5hPXQ6uzVZL30nYh5NFI0JdP5W84zoad4+1VPN6cYywla/br6Dv5DCgMcuzmnW89+E6sn1bAEUDWUYByOmLPY0tDuqQK5DqESMQ2FAPDtENKwrtSGrFuQKuv6J8rPmlNuC0c7IvsGJvFy5ULhyubq8EsJSyUXSptwm6G30HAHSDSsaxiVIMF85wkA0RotJqUqCSR9GlkAQOcUv/SQIGUQME//a8QHl7Nj7zYLEz7wet5+zbrKYsxW3zryXxDfOZdnL5QnzuQByDskbVii1M409kUV/SydPbFA/T6lLw0W4PcUzNShhG6wNgP9J8XbjddaqynPAIbj2sSSuy6z5raaxuLcCwEbKNdZ0457xRAD1DkAdtSrpNn1BHUqFUH9U7FW+VPxQwEo5Qqc3XCu0HRkP/v/U8BPiLtSTx6O8trMTrfCobqecqHKs1rKXu3TGGdMm4S7wvv9cD5Ae4izjOSxFZE5CVY9ZJlv5WRBWh0+NRmg7bC79H4oQiwB88NjgGtK2xBW5k697qAakWaKEo36nLK5at8XCFNDi3rzuKP+mD7cf3S6hPJhIY1K0WVFeFGDtXuNaE1SxSgQ/ZDE7Iv0RKAFA8MXfOdAXwsy1uqsxpGyfk522ns6ivalQsz6/Ks2s3ErthP7UD7UgozAhP75LFVbWXcNismSUY29fYlihTnZCPzRqJG8T0wEf8Nrejc62v8qyL6g3oCSbHpk2mmaekKV9r+G7XsqF2tnr0/3oD4whNjJjQZxOelmmYeBm/WjrZ7FjblxYUrxF+zaHJt4UigIY8BjeFc2VvRCw8qSSnDKX/pQJlkuap6Hjq7O4tMdy2GzqF/3hDzoikzNkQzBRjVwgZaVq8Wzua6RnM2DSVdFIlDmQKEkWSwMs8H3d0su0u6GtCKJEmZqTN5ExkoCWBp6IqLe1LcV01gXpUfzCD8EiuzQkRXpTTl9CaBBuinCab0ZrrmMNWbNLBzyCKqwXFQRX8ArdxMoVun6rcZ9Oll2QzY2zjgqTsZpvpfCyzsKO1Kbng/uKDyEjrzWiRndVumEKax5xxXPqcpFu3GYFXF5OUj5bLAUZ5gSa8L3c7Mm4uKepMJ20k3+NwYqRi+qPq5eaomKwmcDD0lLmsPo8D1sjbTbeRydX0GN2bcxzoXbddYRxuWm2Xs9QcEAXLlMavAXy8JfcSMmctx6oRZt4kQGLFojOiCSN+JQNoA+ukr4W0Qvl2PnaDm8j9jbYSIpYj2WEbxh2GXlveBx0QmwdYQNTYEK1L5MblQZf8ZXc2cjDtuOmspmZj+eI0IVthruKmZLLnfururyIz9Pj/vhjDl4jTDeQSZ1Z9mYycQF4LnueelZ2dW45Y/hUH0QyMcMccAff8bfcncgttvald5gajjCH74NwhLKIk5DXmyeqFbsdzqziI/jaDSsjbjcGSmNaBWiBcoV523xofC94T3AGZapWqkWLMuAdSghw8vzclMjXtVillZf8jN+FdILZggmH5o4ympeopLnWzJnhSvdBDdUiXjc7Stpaumhvc6R6In7MfaZ5znGCZhhYAEe/M+keIQkR82LdvcjDtQelDJc/jPOEYoGpgcSFlY3fmEynari3y5vgdPaZDGAiHTcwSgRbF2n8c1x7/37Ifrl68HKrZz9ZHUjKNNwf9Qm/8+fdFsnutQSl25bii26EuoDhgOOEoozgl0imarfAyrTfpPXlC8shrDblSeFaHGkodK57c39cf2d7tXN/aB5aAEmsNbYgwQp69IrenslYtk2lA5fni1CEeoCCgGiEDYw3l46lpLb0yefe2/QlCxkhDDZcSXJayWjzc5h7fn+Gf7B7GXT9aLNaqEliNnYhhgs/9UrfVMoAt+KlgZdLjJmEpICNgFKE2Ivklh+lG7ZUyTXeG/RcCkwgQDWWSLhZIGhecx17H39Gf5J7HnQlafxaEkrqNhkiQQwL9iTgNsvjt8GmVZgQjUeFOIEBgaSEBIzplvyk0LXjyKDdZ/OMCWUfSTSWR7RYIWdrcjx6V36efg17wXP0aPlaPUpDN54i7wzf9hfhQcwAueinfpkyjlqGNILegVyFkYxGlyalxbWiyCvdv/K2CGceKjNcRmlXzmUacfd4J32MfSF6BHNraKhaKUpsNwQjkA229yDidc1Wulap+pqxj9GHmIMlg3uGf437l52l+rWSyNXcJvLdB1Qd4zHrRNlVKWRtb053kHsRfNB45nGJZwpa00ljN0kjIQ6Q+D3jzs7huwirx5yLkaqJYoXShP+Hzo4KmWOmcLa0yKLcnfECBy0ceDBGQwVUNWJnbUV1k3kwehl3Z3BOZh1ZPUknN2sjoQ5r+W3kS9Cgvf2s456+k+SLkYfnhuiJfJBxmnanKLcKyZHcJvEoBvUa6i5uQfFR818Ia9xyMnfqd/90iG67ZOJXZEi4NmkjDg9E+q3l6dGQvzGvSqFHlnyOI4pfiTSMipIwnNmoIriTyaXcxPBQBa4ZPS1nP55PZl1VaBZwb3Q/dYFyTGzQYllWSEcUNkMjZg8a+/vmpdOuwaKx+6MkmW+RFo07jOKO9pRGnomqXrlRyt/cdvB9BFoYcisyPRBNkVpPZfZsTXEzcqNvsmmPYIJU60U8NfYiqQ/r+1ToftX5w02086ZSnLqUZpB2j/CRvpeyoIas3LpFyz/dPvCvA/sWjCnTOklKeFf6YYBpz23JbmZsvGb4XV9STEQuNIMi1A+1/LfpcNdsxi+3LqrNn1yYEpQPk1uV4Jpzo9CunLxtzMbdH/DpApQVjidMOE1HHVRZXrVl92kCa85obmMOW/BPa0LrMugh6A92/SLredkFyUS6qK2So0+cFZgDlyCZWp6GpmSxnb7KzXTeGPAtAicUeyWiNR9Eg1BwWpphymXiZtxkyV/RVzZNSkBzMSYh4Q8t/pHsltvBy4q9X7Gep5GgbJxOmz2dKqLrqUK038Bdz0vfLPB8AbYSVCPWMsJAsExDVjJdSmFtYpRgz1tGVDRK6T3HLzsgwA/Y/gPuxd2czvzAT7Xtqx2lE6Hsn6+hTKadrWi3X8Mj0UngWvDYAEQRHiHsLzs9pkjUUYJYfFynXfpbhVdtUOtGSjvmLSgfhA91/3bvA+CU0ZjEc7l5sPCpB6bapHGmvqqcsdS6HcYe03DhpPBCANIP2h7nLIw5aUQqTY5TZFeSWBBX7VJKTF1DbTjSK+0dLA8CAOfwTOKk1FnIx71AtQSvQqsUqoGre6/jtYO+F8lL1cDiC/G8/2IOjBzLKbo1/j9ISFpOB1I1U9xRCk7fR40/VjWLKYoctw6AAFTyn+TL1zvMSMI9ule0wbCUr9mwgbRvunPCS8yq1zfkjvFH//cMNRqbJskxaTsyQ+tIaEySTWFM4kgxQ347BTIUJ/8aJg7tALzz+OYD2zvQ8MZqv+G5frZXtXW2zLk+v6HGuM862tXlLvLk/pML2hdaI7strjbuPUZDjkawR6RGd0NCPjI3fi5sJE0Zdw1GARz1VelL3lTUvMvExJ+/dLxYu1K8Vr9MxArLWtP53Jvn7PKU/jcKfBUNIJcp0jGAOHA9fUCSQapAzj0XOa0ywiqXIXQXqgyMAXP2s+ue4YPYp9BFyozFn8KRwWnCHMWUyavPL9fk34bpx/NY/uUIHxO1HF4l2SztMm43Ojo/O3c67De0M/Et1CaVHncVwAu+Ab/3D+765MTcrdXpz6LL+cj+x7bIGcsSz3/UNdv74pbrwPQx/qAHxBBXGRYhyCc6LUUxyzO7NBE01TEcLgQptyJpG1UTuQraAf74Z/Ba6BLhyNqp1dzRfM+YzjPPSNHC1IXZaN885srt1vUg/mgGbw72FcMcpCJtJ/sqNS0MLn0tjytUKOgjbx4WGBARlQngAS76ufK762rl9N+C2zXYI9Za1dzVpNeg2rfexeOj6R/wCPcl/kAFIQyUEmgYcR2KIZUkfiY4J8EmHyViIqEe/RmcFKkOVAjPAU/7AvUb78fpLOVu4abe6Nw+3KvcKN6m4BHkSegu7ZbyVvhB/igE3gk3DwoUNBiXGxoerB9EIOIfiR5JHDQZZxUAESMM+AaoAV78P/d28iXubOpn5yvlxeM/45njzuTR5o/p8ezb8Cv1wPl0/iIDpwfgC60P8hKYFY0XxRg3GeUY1BcPFqYTrxBDDX8JgQVqAVr9b/nI9YDyr+9p7b3rtepX6qLqkesZ7S3vuPGm9N33RPu+/i8CfgWSCFQLrw2UD/YQzhEXEtIRBRG4D/oN2QtpCb8G8QMVAUP+kPsQ+db28fRu81fysvF/8b/xa/J78+b0m/aO+Kv64fwe/1ABZgNSBQMHcAiPCVoKzQroCq0KIQpMCTUI6gZ1BeUDRwKpABj/n/1J/CH7LPpy+fT4tPiy+On4Vvny+bX6lvuN/JH9l/6W/4YAYQEgAr8COgOPA78DygOzA34DMAPNAl0C5QFqAfQAhgAmANf/mv9x/13/Xf9u/43/uP/p/xsATAB2AJQApACiAIwAYgAjANP/cf8D/4v+Ef6Z/Sr9yfx9/Er8NvxE/Hf8z/xN/e79sP6N/38AfwGFAogDfQRdBR0GtQYdB1AHSQcEB4EGwgXJBJwDQwLIADX/lv35+2r6+fix96D20PVK9Rb1OfWz9YX2q/ce+dX6xfze/hEBTwOEBZ4HjAk8C58MqA1LDoEORQ6WDXUM6gr+CL0GOASBAa7+0/sG+WD29vPd8Sfw5e4j7urtP+4i74/wf/Lj9Kz3xvoa/o0BBgVpCJsLgg4EEQ0TiRRrFagVOxUlFGwSGhA+De0JPwZQAj7+KPou9nDyDe8h7MXpDugM58vmTueV6JnqTu2f8Hf0t/hB/fEBpAY0C30PXROyFmIZVBt3HL4cJRyuGmAYSxWFESgNVggzA+b9l/hx853uQuqC5n/jUeEN4L/fbOAT4qnkHehX7DfxmfZV/D4CJwjiDUATGBhBHJgfAiJpI74j/SIpIUseehrOFWwQewooBKX9IvfT8OvqmOUG4Vrds9oq2czYn9mh28Pe8eIN6PDtbvRX+3MCjglwEOEWrxyrIasljig7KqIqvSmRJyokoR8XGrUTrAwvBXv9yfVV7lznE+Gv21vXO9Rp0vjR7dJE1e3Yz93G46XqOPJH+pEC2QrdEl4aICHsJpUr8i7oMGQxYDDgLfYpvSRcHgEX5g5HBmj9jPT56/LjuNyD1ofR7M3Ry0rLXMwDzy3Tu9iF31nn+u8n+ZkCBwwoFbMdZiUCLFExKjVqN/433zYSNKovyCmXIkwaJxFuB2z9bfPA6bHgiNiG0ePLzcdnxcXE8cXiyIbNutNQ2xDktu3694oCGA1PF98gfinmMNw2Lzu8PWs+NT0gOkI1vy7GJpMdbROiCIX9a/Ks55vdiNS7zHPG4sEvv3K+sb/owv7H0M4p18zgbuu/9mYCCg5QGeAjZS2WNTA8/kDXQ6VEXEMGQLg6mzPjKtMgthXjCbT9iPG+5bHautAnyDzBMbwwuVO4o7kYvZvCAcoV05HdJul59SwC3g4rG7ImGTEOOklBkUa5SaZKUEm9RQhAWjjtLggk/xctC/j9w/D34/bXIc3Mw0G8vrZus3CyzLN6t2C9VMUYz2Pa3uYq9N8BlA/eHFUplzRLPiRG40taT2pQCk9CSyxF9jzdMi8nRBqADE/+HPBX4mzVv8muv4e3jbHvrcysL64RslS4y8A1y0TXm+TT8n4BLBBpHscr3DdJQrxK8lC3VO1Vh1SOUB9KakGxNkQqhBzaDbn+k+/h4BPTmMbQuxGzoqy1qG2n1KjirHqza7xxxzjUX+J38QwBphDLHwYu5joGRg9PuFXLWShbwFmeVd5OtEVkOkUtvB45DzT/KO+T3+7QrMM1uOOuAqjHo1aivaPzp9iuObjQw0PRLOAX8IgAAxEFIREwsz1/SRhTMlqTXhhgs15sWmNTzUnzPS4w6SCaEL//2u5u3v3O/cDftACrr6Mnn46d8J5Ho3GqObRVwGfOBd617vb/QhEUIugxQkCyTNVWXF4KY7hkWWP1XqtXtE1aQfwyCSP8EVgAqO5z3UDNjr7QsWqnrp/bmhaZcZrjnkmmbrADvajL7dtU7Vb/ZhH7IoozkUKcT0NaM2IsZwVpsGczY7FbYlGVRKs1GCVcE/8Aku6h3LrLX7wLrySkAZzklvSURJbKmmai3azfuQrJ59n166n+bxG4I/U0n0Q8UmBdtWX2avxss2skZ3Ff1VShRzk4FSe4FLIBl+7422nKcrqQrDChrJhGkyuRbZICl8qeiKnsto7G9deb6vH9XRFNJCs2bEaQVCpg3mhmbpdwXm/DauhiClh6SqI6+ygPFm8Cte5420/Jx7hiqpGesJUFkL6N7o6Nk3mbdaYttDjEGtZJ6S/9MxG5JCo39UeXVp9irGt5cdVzr3INbhJm/FoeTeM8yipdFzQD7O4g22vIX7eCqEecD5Mija+Ky4tvkHaYpaOmsQzCWdT/52f88BD+JPM3O0lRWL1kHm4rdLR2o3X/cO1oqF2IT/o+fiyiGAAEOu/u2r3HO7bwplWazJCgigKICImqjcWVHaFZrwvAs9LB5pj7lxAcJYY4Pkq7WYNmMnB8di95NniWc3RrDGC3UeRAFC7ZGdAEnu/k2kXHWbWtpbuY6I6BiLmFpYZBi2mT3p5IrTm+LdGQ5cb6KRAUJeQ4/krWWvBn5nFpeEZ7Z3rQdaVtJWKoU55Ciy8CG6QFFvD+2gHHu7S6pHqXZI3GhtSDp4Q3iWOR7Jx4q5i8x89w5PL5pw/oJA05e0uiWwRpOXPxefd8M3yqd39v8GNXVSVE3zAaHHgGoPA82/LGX7QWpJOWQYxxhVeCDYOOh7aPSJvqqSq7hM5h4x75FA+YJAM5tksfXL9pLHQTe0B+mX0ief5wa2XEVnhFDzIfHUsHPPGd2xXHRrTAowWWgIuChEOB24FHhmWO9pmgqPO5Z81m4kz4cA4mJMY4r0tNXCBqvHTPeyB/l343eiFylGbqV5RGGTMQHhsI5/Ef3GvHbbS5o9GVIIv6g5eAEYFkhXCN9pidp/O4ccyB4X73vg2VI1g4Z0stXChq63QjfJd/LX/neudyamfKWHhH+jPpHucIoPLA3PHH1bQApPWVIYvZg1WAr4DnhNqMS5jipiy4pcu04Lb2/wzkIro34ErAW9hpuXQRfKV/Wn8ye05z6mdgWSFIsTSpH6wJZfN/3abIe7WTpHGWhIsfhHyAt4DPhKOM9pdwpqG3BMsB4PX1NQwXIu82G0oHWzBpJ3SYe0h/HX8Xe1VzFGitWY1IPDVPIGgKM/Ra3ojJXrZxpUWXRozLhA2BKYEdhcuM95dKplO3kMpp3z71YwsvIfc1GkkEWjFoNXO5eoN+d36Vevxy52etWb1ImTXYIBoLCfVP35XKfLeZpm6YaI3dhQeCBILShVSNUJhvpkO3Ssrv3pL0igouINU030e4WN9m5HF1eVV9aH2teUNyY2diWa1IxzVCIb8L5fVc4MzL1LgIqOqZ545Th2mDR4Pthj6OAZnhpnK3NMqU3vPzrAkWH4oza0YmVzllOHDNd7978XtgeClxhmbJWF5IxDWOIVYMxfZ+4SnNY7q9qbmbwZAriTKF8oRtiIiPCZqgp+K3T8pZ3mTzygjpHRoywURPVUJjMG7EdcR5EnqtdrBvUWXjV85HkDW3Id4Mp/e14qzOJ7y2q9ed9ZJli1+HA4dSijGRaputqJK4nMpA3uXy6AepHIYw5EI2U/1g0Gtbc2V3z3eXdNdtxWOwVv5GKjW/IVQNifj941HQHb7vrUKggJX8jfCJeYmZjDmTIp0HqoK5HMtK3njyBwdZG9Au1UDdUG1eGmmVcKN0J3UecqBr4mEwVe1FkTSjIbcNaflV5RbSQ8BmsPeiYJjwkOGMUYxDj56VMJ+tq7W6z8t53h/yKAb7GfwsmD5JTpNbEmZ0bYJxHnJFbw1pqV9iU5pEwzNiIQYORvq55vnTlsIYs/SlkZs9lDGQio9Lkl+Yk6GhrSi8t8zM3tvxTgWQGAsrMDx6S3NYuWL8aQVut24NbB9mG11JUQZDwjL8ID8OHfsp6PfVFMUCtjWpEZ/hl9yTIJOxlXqbS6Tfr9y90s1F367xewQcFwEpnzl1SBFVE18vZi1q82p6aNhiOlrlTjJBjTFwIGAO7Pug6QzYuMchubes26LWm9+XEZdymeyeVadostC/Ic/l35jxrwOhFeEm6DY9RXBRJVsRYgBm1maNZDpfCFc4TB8/JDC9H2oOs/wf6zjagMpxvHew7aYboDacWZuKnbSir6o6tQPCpNCr4Jvx7gIhFKwkEDTWQZRN8VamXYBhY2JLYElbh1NCScw8hy7jHloObv2h7HXcac3vv2+0QaurpN6g9Z/2oc6mV65TuHTEW9KZ4bjxOQKdEmYiGDFCPoBJfFLyWLFcn122WwdXuU8GRjw6tyziHTAOHf4l7sPeb9CXw5241a+CqdOl4aSzpjirSrKxuyPHRNSu4u/xkAEZEREgBC6HOjlFyk35U5hXjFjRVndSoUuGQm83tCq5HOsNv/6p7x7hj9Nlx/y8pLScrg+rGaq9q+2vhrZTvw3KYNbq40Ly9gCWD7Ed2CqnNsNA4EjATjlSMFOjUZ1NQkfFPmk0gChpG4sNUf8q8YPjxtZWy4nBqbnzs5CwmK8Qseq0B7s0wzDNrNhN5bDybAAXDkgblyemMiI8wUNMSZhMkE0tTH1IoELEOikxHCbzGQ4N0/+m8u/lEdplzz7G4L6DuU+2WbWntiy6yr9Tx4vQKNvX5jvz9P+eDNgYRCSJLlo3cz6gQ7tGr0d1RhtDvT2HNrMtiCNWGHUMQQAc9GHoa92P0xfLRMRIv0i8Wbt+vK2/y8StyxvU092H6OPzjv8sC2YW4yBUKnAy+zjEPadAkkGAQHs9njgSMgoqxyCTFr8LngCJ9dTq0eDP1xDQ0Mk8xXbCkcGQwmvFBso+0N7XquBc6qf0O//ECfMTeB0KJmktXTO6N2E6QDtSOqI3RzNmLS4m2h2sFOwK5wDs9kbtQeQh3CTVfs9Zy9PI/MfZyF/LeM8D1dHbrONV7Ij1/P5nCIIRBRqwIUkony2KMe4zvDTxM5QxvC2JKCUixBqhEv0JHAFD+LXvtueC4E7aS9Wb0VrPls5Sz4XRHNX42fHf1uZx7oX20v4XBxUPjhZKHRUjxSc4K1QtDi5hLVcrASh9I+8dhhd0EPIIOwGM+R/yLevs5IvfMNv81wXWWNX21djX7doZ3zvkKOqv8J73vv7VBbAMFxPcGNId1iHJJJkmOiepJu8kGyJGHpEZIhQlDssHRAHF+n/0o+5d6dTkKeF33s/cPdzA3FPe5+Bj5Kzone0O89P4wP6kBFQKow9qFIUY1RtFHsIfRiDOH2IeDxzqGA4VnBC3C4gGNwHu+9b2FfLP7SXqMOcF5bLjPuOr4/HkBOfR6UDtM/GL9SP62f6EAwQINQz4DzETyRWvF9YYOBnWGLUX4RVsE2oQ9gwsCSsFEwEF/R75fvVA8nnvP+2h66fqV+qw6qzrQO1f7/Px6PQl+I77CP93AsMF0QiKC9wNtw8OEdkRFhLGEe4Qlw/QDagLMgmEBrQD2AAI/lj73fiq9s30U/NF8qnxgPHJ8X7ylvMH9cP2ufjZ+hH9Tv9+AZEDeAUlB4sIpAlnCtMK5wqlChIKNwkcCMwGVQXDAyQChgD3/oH9L/wK+xr6Zfns+LL4tPjw+GH5AfrG+qr7o/yn/az+q/+ZAHIBLwLLAkIDlAPBA8kDrwN4AygDxAJTAtoBYAHqAH4AHgDR/5b/b/9d/17/cP+R/7z/7f8fAFAAeQCWAKQAoQCJAF0AHQDL/2j/+f6B/gf+kP0h/cL8d/xH/Db8R/x9/Nj8Wf39/cL+of+UAJUBmwKdA5EEbgUrBr8GJAdSB0UH+wZzBq8FsQSBAyUCpwAT/3P91/tK+tz4mPeM9sL1Q/UW9UD1wvWb9sf3QPn9+vD8DP9BAX4DsgXJB7IJXAu5DLkNVA6ADjsOgg1YDMUK0QiKBgAERgFx/pb7zPgq9sbztPEI8NDuGe7s7UzuO++08K3yG/Xs9wv7Y/7XAU8FsAjdC7wONREyE6IUdhWlFSoVBxRAEuIP+wyiCe0F+gHn/dL52/Uk8sru6eua6fLnAOfO5mLnuejN6o/t7fDO9Bb5pP1VAgcHkwvUD6kT8haTGXQbhRy6HA4chBolGAEVLRHFDOsHwgJ0/Sf4B/M77uvpO+ZI4y3h/d/D34bgQeLr5HDoueyl8RH30vy8AqMIWA6tE3gYkBzVHyoieiO5I+Ei9SADHh4aYhXyD/cJngMZ/Zn2UfBz6i7lruAX3YfaFtnS2L/Z2dsT31bjg+h17v707fsLAyQK/hBkFyIdCiL0Jb4oUCqcKpspVCfUIzQflxklEw8MjATW/Cb1u+3O5pfgSNsM1wfUUtL/0RLThtVK2UTeUORA6+Dy9vpDA4gLgxP2GqYhXCfqKyovATFdMTkwmi2TKUAkxx1bFjIOiwWq/NHzR+tP4yncDNYs0bDNtstRy4XMTc+W00DZI+AK6Lrw7/ljA84M5RVhHv4lgCyyMWo1hzf3N7M2wzM7Lzsp8CGRGVwQmgaV/Jry+Oj53+fX/9B8y4nHSMXNxB7GNcn7zU/UANzW5Izu2fhtA/YNIhiiISkqdDFJN3c73T1kPgU9yTnHNCIuDCbDHIwStweX/ILxzebP3NTTJcwAxpbBDL95vuO/QsN/yHPP69em4VrstvdfA/8OORq2JCIuMzapPE5B/UOeRClDpz8yOvAyGSrvH8AU4Qiv/IjwyuTR2fTPgse9wN27CblauNi5er0nw7PK6NN/3ibqhvY9A+oPKRycJ+gxujrOQelG4kmgShlJWEV3P6E3ES4RI/MWFgrd/K3v7eID10rMGMO3u2G2QrN2sgS04rf3vRPG+89j2/PnTPUFA7UQ8R1SKnY1Bj+0RkRMiE9lUNFO1kqRRDA88jEmJiUZVAsf/fHuOuFl1NjI7L7ytiixvq3RrGqugLL0uJfBKMxW2MPlCfS5AmERkB/WLMw4EkNYS1tR6lToVUtUHFB7SZhAtzUrKVMbmgx0/VTusN/70aDFALtxsjWsgKhwpxGpVq0jtEO9csha1ZnjwPJaAu8RBSEnL+Y73Ua1TylWA1olW4NZJ1UxTtZEXDkcLHkd5g3c/dXtUN7Ez6TCWLc4ro2njaNZovyjbKiIrxy53sR00nfhcvHpAV4SUSJEMcI+Y0rJU6pa0F4XYHNe8FmvUuZI3jz2LpYfNg9V/nXtGt3Czee/9bNKqjOj6J6OnTCfxKMpqya1b8Gnz2DfIfBoAbASciMqM2BBok2QV9xeS2O5ZBljdV7wVsJMOUC2MaYhhxDe/jLtDtz2y2q92rCqpiqfl5oVmbKaZJ8Ip2SxKb71zFfd0O7YAOQSaCTbNL1DmFAIW7ticmcIaW9nsGLwWmhQakNYNKcj2BF2/w3tLdthyi67Ca5ao3abm5bxlIaWT5sqo9utD7tiyl7bgO05APwSNCVVNtdFQ1MvXkRmQmsAbXFrnmarXtRTbEbaNpclJxMZAAPtddoDyTS5hKtdoBmY+ZIlka6SiZeTn46qJbjyx3nZM+yQ//gS1iWXN7BHolUBYXRptm6fcB1vO2odYgFXPUk5OXIncRTJABTt6Nndx363TKm2nRaVs4+1jS+PFpRGnICnbrWmxanX7Orb/toSTyaiOERJs1d+Y0lszXHfc25yg21DZe5Z2UtyOzYptBWCAT7thNntxgu2Yqdkm3CSy4ykigyM+ZBHmbak7rKBw/HVreke/qMSnyZ2OZRKdVmkZcFuhHTAdmJ1dHAaaJVcPU6BPeEq7xZEAoLtSNk1xt20yKVrmSeQRYr0h0eJNY6ZljGiprCIwVTUeOhZ/VQSxyYSOqBL6FpxZ9pw2XY+efd3CnOfavZeZ1BkP3AsHhgLA9ztNNm0xfOzfaTKlz2OIoioheSGzYs+lPafm668v9TST+eP/O4RyCZ5OmhMClzlaJNyynhYeyl6RHXPbAxhVFIZQeEtQBnXA03uRtloxU6zg6ODlrSMY4bBg+SEw4k5kgaezqwfvnPRNObC+3MRoiapOuxM3Fz+aexzVnoMffd7HneobtViAFSdQjEvUxqlBNHuftlTxeyy2aKWlY2LCoVBgkmDGYiNkGScQqu1vDTQKuXz+uUQWCalOixNXl2+auJ0fHtYfl99mHgncE9ka1XtQ14wVBt0BWjv2tlxxc2yfqIElceKGIQqgRSC0YY7jxKb+ql/uxrPMuQl+kYQ6yVsOilNkV0ja3d1O3w7f19+rnlLcXllkVYIRWUxQhxCBhDwWNrDxfGydKLMlGSKjIN7gEiB7IVFjhKa9qh/uiXOT+NZ+ZYPXCUBOuVMdF0va6l1kny1f/d+YHoTck9mcVfrRUYyGh0MB8fw99pGxlWzt6LtlGKKaYM2gOSAbYWtjWWZOqi4uVnNguKR+NgOrSRmOWBMCl3hanp1gnzFfyd/rXp8ctJmCViVRv4y2x3RB4vxttv6xvqzSaNolcOKrINbgOmAUoVzjQ2ZxqcrubbMzuHP9w4O4COaOJxLUlw6aul0DHxrf+1+lXqGcv9mWFgFR4szgx6PCFvykdzdx920JqQ6loOLVoTqgFiBnYWZjQuZnKfauD/MNOEW9zoN9iKhN5tKT1s9afhzLnuofkl+F3oxctVmXVg4R+wzDx9ECTTzid3syP21TqVil6SMZoXhgTCCT4YejmCZvafGuPXLteBm9l0M8iF9Nl5JAlrqZ6ly7Hl8fT19Mnl8cVVmFlgtRx80fx/uCRT0md4lyle3v6bfmCKO24ZBg3CDZocDjwyaKqjvuNnLVODC9XoL1iAuNedHblhDZvxwRnjoe8l76XdncH5lg1flRiM00B+LCvr0wd+Iy+m4d6ivmv2Ps4gIhRiF4ohHkA6b4qhXue3LE+Ar9ZIKox+5MzlGk1ZKZPNuPXbvee55O3bzbk9kpFZdRvczAiAbC+P1/+AQzbK6c6rQnDKS7IozhyaHworrkWic6Kn/uTLM8d+k9KgJXB4eMlZEdlQCYpJs1HORd613KXQgbcpieVWVRZkzEyCaC872T+K8zq+8saw+n7+UhI3DiZiJBY3tkxmeOavnuqjM8d8t9L0IAx1hMEFCGFJuX9ppDnHRdAl1tXHvau9gAlSNRAozAiAIDLj3sOOK0Ny+Lq/4oaGXeJCzjG6MqY9Llh+g16wPvFDNFODJ89MHmhuDLvw/fU+PXM5m7G2xcQNy4W5jaL5ePlJFQ0kyzR9iDKD4H+V30jjB57H7pNaaxpMCkKOPrZIFmXqiwK53vSvOW+B48+0GJBqILIo9p0xqWXJjcmo0bp5urmt8ZTlcL1C9QVQxdB+oDIT5m+aA1L/D2bRCqFmea5eskzeTDpYZnCil9LAevznPxuA98wwGoxhyKu86mUkCVshfo2Zeat1qIGg8YmJZ1032Py0w9h7ZDGL6Ieii1m7GAbjLqymiY5uulyWXyZmEnyiocbMFwXrQV+EY8zIFGhdEKCw4WEZZUtVbgmIwZsNmOWSnXjpWNUvwPdIuUx7yDDj7runb2ELJXLuSr0Cmq58GnGqb251Eo3irNrYqw+7RDeIK82AEihUBJkc15UJ0TptXFF6wYVNi/F++WsNSTEisO0UtiR3zDAX8QOso2zjM5b6Ts5uqPqSuoASgQqJVpxWvQrmNxZTT6uIW85kD9hOrI0EyRj9XSiBTXVnhXJFdbFuEVgBPHkUrOYYrmhzbDMb81eyG3U3PmcLLtzavGamjpe2k+aa2q/2yk7wsyGzV7eM6894CYBJGIR4vfjsGRmZOYFTGV4JYjlb9UfRKrEFvNpUphBupDHv9a+7y333SdcY1vAy0N67hqiKq/qtjsC23JsAFy3bXFuV58zACyhDUHuIrkDeEQXRJIk9mUihTZVEsTaFG+T15M3MnSBpdDCH+APBp4sTVdMrNwBq5k7NjsJ+vS7FXtaK7+MMYzrDZZebT85IBNw9YHJAogTPXPExEqEnETIlN9EsVSAtCBzpLMCIl5hj1C7j+kfHp5CDZks6OxVq+Krkktl+13baQulnACMhh0Rjc2udJ9AMBqA3VGSslVS8DOPU+90PlRqpHQka8QjU92jXnLKIiXhdyCz3/HPNu543cy9J1ysfD9L4gvF27rrwIwE3FUszf1K/edOna9IYAIQxOF7ghDysMM3M5FD7OQI9BUkAlPSI4dDFPKfYfsRXTCrH/oPT26QbgHNd7z13J78RQwpTBu8K8xXzK09CP2HHhMuuH9RwAogrFFDketCb3LcozBDiFOj07KjpVN9gy2CyHJR4d4RMYChEAGvZ/7IrjgNue1BfPE8uxyP7H/siny+HPiNVv3F7kFe1Q9sb/LQk+ErIaSCLIKAEuzDEPNLs0zTNQMVotCyiQIR0a7RFBCV4AifcF7xTn89/X2e/UXdE7z5fOcs/E0XjVbdp84HPnGu8194T/xQe6DyYX0B2FIxsocitxLQ0uQy0cK6wnECNuHfUW1w9OCJYA6viF8aDqcOQj3+Daxtfq1VjVEtYP2Dzbft+y5K7qQPE1+Fb/awY9DZkTThkyHh8i+ySyJjknjya9JNMh6h0kGacToQ1AB7gAPfr+8yzu9Oh85OXgSd643D3c2NyB3ijht+QP6QzuhvNR+T//IAXKCg8QyRTTGBIcbh7XH0UguR85HtMbnhi1FDgQSwsXBsUAf/ts9rTxe+3e6fnm4OSf4z/jvuMW5TnnFeqP7Yzx6/WH+j3/5gNhCIoMQxBvE/kVzxflGDcZxRiVF7MVMRMkEKgM2AjUBLsAsPzO+DX1//FE7xftheua6ljqvurI62ntku8v8iv1bPjX+1L/vwIGBg4JwAsJDtkPJBHkERUSuRHWEHYPpQ12C/sISQZ3A5sAzf0h+6v4f/ap9DjzNPKh8YLx1PGR8rLzKvXr9uX4CPtB/X3/qwG8A54FRQemCLcJdArYCuQKnAoDCiEJAQiuBjQFoQMCAmQA1/5j/RT89PoJ+lj55fiw+Lf4+Pht+RD62Pq++7j8vP3C/r//rACDAT0C1gJLA5oDwwPIA6wDcgMgA7sCSQLQAVYB4QB1ABcAy/+S/23/XP9f/3L/lP/A//L/JABUAHwAmAClAJ8AhgBZABcAxP9g/+/+d/79/Yb9Gf27/HL8Rfw2/Er8g/zh/GX9Df7T/rT/qQCrAbECsgOkBH8FOQbKBioHUwdBB/IGZQacBZoEZQMGAoYA8P5R/bX7Kvq/+ID3efa09Tz1FvVH9dD1sfbk92P5JPsc/Tv/cQGuA+AF9AfYCX0L0gzKDVwOfw4wDm0NOwyfCqMIVgbHAwoBNP5a+5L49PWW843x6e+87hDu7u1b7lXv2fDd8lT1LPhR+6z+IQKZBfYIHQz1DmQRVxO6FIEVoRUZFecTExKpD7gMVgmbBaQBj/17+Yn12PGH7rLrcOnW5/Tm0+Z3597oAevR7TvxJvV1+Qf+ugJqB/ELKxD1EzEXwxmTG5IctBz2G1oa6he1FNQQYgx/B1ICAv24953y2u2W6fTlEuMK4e7fyt+h4HHiLuXE6BztFPKJ90/9OwMgCc4OGRTWGN4cECBQIoojsiPCIsAguR3BGfQUdw9zCRQDjvwQ9s/v/OnG5Fjg1txe2gXZ2tjg2RPcZN+84/vo++6P9YT8pAO5CowR5heUHWgiOybsKGMqkyp3KRUnfCPGHhUZkxJzC+kDMfyF9CLtQuYc4OLav9bV0z7SCNI508nVqdm73tzk3euJ86b79QM2DCgUjRsqIsknPCxgLxcxUzEPMFItLSnAIzIdsxV9Dc8E7PsX85fqruKb25jV1NB3zZ7LW8uxzJrPAtTI2cLgveh68bj6LgSUDaEWDR+VJv0sETKnNaE37TeFNnIzyS6rKEch0xiRD8YFv/vI8THoQ99H13zQGMtIxyzF18RPxovJdM7m1LLcneVj77n5TwTUDvUYYiLRKgAysze8O/o9WT7SPG85STSDLVEl8RuqEcsGqfuY8PDlBNwj05PLkMVNwe2+g74YwKDDA8ka0K/YguJH7a34WQT0DyIbiiXdLs42Hj2bQR9Ek0TyQkY/qDlCMkwpCR/IE98HqvuI79fj89gxz+DGQsCMu+W4ZbgRuuC9tsNpy73Ubt8p65P3TQT1ECcdhCizMmM7T0I+RwhKlUrfSO9E4j7lNjQtGCLnFf4IwvuX7ubhEdZ2y2jCMLsIthqzgLJAtE+4kb7WxuHQZdwK6W/2KwTVEQMfTStTNr0/QEehTLNPW1CTTmZK8kNmOwUxGyUFGCgK7vvG7R7gYdPzxy6+YLbHsJKt2qyprvOymLlnwh3Nadnt5kD18wOWErYg5C25OddD70u/URlV31ULVKZP00jDP7o0DiggGloLMPwV7YHe5NCrxDW61LHNq0+oeadSqc+t0LQfvnbJf9bV5Ar0qAM3Ez4iRjDiPK9HV1CVVjZaHVtAWatUgE31Q1I47yo1HJMMhPyE7A7dnc6gwX+2ka0dp1ejYKI/pOqoPrADuu/FqNPE4s/ySgO5E5sjczLOP0JLdVQeWwdfEGAvXnBZ9lH6R8c7ui1BHtEN7PwR7Mfbi8zUvg+zmKm7oq6elJ12n0ek5asWto3C6dC94I/x2gIcFM0kajR6Qo5OR1hXX4djtGTTYvBdMFbNSxY/bDBCIBIPZP2+66var8pJvOiv7qWrnliaGZn5muufy6deslK/Rc7D3k3wWgJhFNMlKTbkRJBRyFs9Y7NnBWkoZydiKVpqTztCAjM1IlQQ6/2I67rZDMkAugytlqLwmliW85TNltmb86PdrkO8vsvY3AzvywGIFK4msTcMR0ZU+F7NZodrAG0qaxJm313NUjNFeTUXJJURgf5w6/XYoMf6t3yqkJ+Ml7GSJZH2kheYYaCXq2K5WMn+2sztLwGSFF4nADnwSK9W02EEagBvoHDVbqxpTGH0VftHzTfnJdISJP9z61rYbcY4tjqo35yDlGaPs413j6aUGZ2QqLS2Fsc52ZHshwCBFOMnFzqPSspYWGTfbBty43MncvNsb2TbWJBK/TmhJwoU0v+S6+rXcsW7tEemhprWkXuMn4pTjIqRHZrLpTq0+sSL113r1f9VFD4o9jrpS5VahWZdb9d0xnYcdeNvQ2d+W+5MBDxDKTsViADL66TXsMSDs6SkhZiHj/CJ7YeOiceOcpdLo/ixCMP21TDqGv8PFHAonDv+TA9cWWh8cTB3R3mxd3hyxWnaXRJP4T3KKmIWRgEc7IfXJsSRslKj3paYjcmHnoUph1+MGZUTofKvQsF91A/pWP6yE3koCjzOTTld02k7cyV5ZHvkebJ09GvtX/tQkD80LH0XCwKF7JHX08PksVGikZUKjAaGtIMnhVWKFZMmnyiuqr8i0/vnkv0/E1soQjxYThJe82qYdLV6Gn20e412zG21YaVSEEF/LYoY0wID7cLXt8N8saGhoJTeiqqEMoKLg6qIaZGFnZ+sQ77n0fXmyPy2EhcoQzyeTplet2uTdd57aX4dfQd4S28uYw1UXkKpLocZnQOV7RnY0MNYsUKhCZQVirSDF4FUgmGHF5AznFirD73P0AHm/fsbEq4nDzygTtBeIWwrdqB8Tn8gfh55cHBXZDNVd0OvL3MaaAQ67pTYHsR4sTOhzZOuiSaDZoCFgXuGII8zm1SqELzczx/lNPtuESInqDtfTrZeL2xgdvt8y3+7ftN5OHEvZRNWW0SPMEobMAXv7jHZn8TasXSh65Oqif+CH4AfgfmFho6EmpepSLsPz1LkbPqxEHUmDjvcTU5e5Gszdu183X/tfiJ6pHGzZa1WBkVIMQsc9gWz7+7ZUsV+sgOiZJQIikCDQYAigdyFSo4qmiGpubprzp3jqvnmD6clQzoZTZhdP2uldXl8hn+1fg16sXHjZf9WeEXXMbUctQaE8MvaNMZgs+CiNZXHiuiDzYCOgSSGbI4lmvSoZbrxzQDj7vgQD7wkSTkXTJVcQmq1dJ57xX4VfpJ5X3G+ZQdXr0U8MkUdbQdf8cTbRceBtAmkXZbmi/aEwoFjgtKG7Y51mhCpTLqizX3iOvgwDrUjIjjYSkdb72hnc116nH0MfbF4rnBCZcZWqkV0MrodHAhE8tncgsjdtXul2pdkjWqGIIOgg+WHzo8cm3epcLqBzRfikfdHDZQi0DZfSbFZR2e6cbd4C3ybe2x3nm9wZDlWZ0V/MhIewAgv8wbe6clztzWnrJk/j0CI5IREhV2JDZEZnCqq0bqOzc7h8/ZZDFshVTWtR9NXTWWxb692E3rDecJ1MG5IY2FV50RaMkseVwkg9Erfd8tBuTWpz5t1kXmKDodPhzmLq5JsnSercbvKzaThY/ZnCw0gtDPERbJVAmNObUd0t3eGd7RzY2zKYT5UKEQGMmUe3wkT9aLgKs1Du3erQJ4ElBGNnIm/iXeNp5QVn3CsT7w2zprh4/VyCqse7zGoQ09TamCUaoBx+XTldEVxOWr2X89SKkOBMV8eVwoI9g3iAc94vfqt/qDplgaQi4yRjBaQ/5YToQWubb3UzrLhc/V+CTgdCDBcQa1Qh12GZ11u2nHicXZus2fOXRVR7UHLMDYevgr89ofj99Dcv7qwBqQgmlWT2I/DjxWTspllo+Ovyb6jz+zhFvWLCLcbAi7hPtBNXFomZOJqXm6Abklr02RSWxFPcUDjL+odEQvt9w/lC9NtwrWzU6eonfyWgpNTk3CWvpwKpgyyZcCj0EnizfSdByka4Ss7PLpK7VZ4YBFniGrDasFnnGGFWMRMtj7KLnodUAvZ+KLmOtUnxea246p7ofaahJc+lyWaIaAAqX60PsLW0cvimfS0BpEYpiltOW5HPVN/XO9iW2arZt9jDl5nVS9Kvjx+LecceQu++T7ogNcHyEq6sq6YpUCf25uBmzKe2KNFrDa3VcQ603Hje/TSBfIWVCd7NvFDUE9AWH5e22E+YqhfLVr7UVNHiDoBLC4ciwuc+uDp3NkLy969vLL5qdejg6AXoJOi4afXrzW6qcbQ1DzkdPT5BE0V7yRoM0dAKku+U8NZC11/XR5b/FVETjJEFzhSKlAbhgtv+4frStwuzp/B/baarrWoeaX+pESnOay0s3i9OMmX1i3lh/QsBKUTeSI2MHI8z0b+TsJU8FdyWEZWflFDSs5AazVzKE0aZws2/C/tx95t0YfFcrt4s9etuKoxqkOs3bDYt/zAAcyO2EPmsvRrA/0R9h/qLHY4QkIESoBPj1IbUyJRtkz8RSo9hjJkJiUZLwvx/NfuUeHF1JTJFcCOuDizO7Crr4qxyLVBvMDEAs+12n7n9/S3AlUQZx2HKVk0ij3URAFK60x+TbhLqUdyQUc5aS8mJNcX3Aqd/X3w4+My2MHN4sTWvdS4/rVptRa397rrwMDIOdIK3d7oV/UTArIO0BoRJh0wqTh0P0tEC0ehRwtGWUKpPCo1Fyy6IWUWbwo4/h7yfeax2wvS1clNw6S++7tlu+K8ZsDSxfvMpdWM32Lq0fWAARUNNRiLIscrpTPnOWE+8kCIQSFAzDykN9QwkygjH84U5wnD/rfzGuk932zW6c7tyKXELsKawerCEcb0ymzRQtk64grsZ/b+AH8LlxX4Hlwngi41NEo4pjo4O/45BTdmMkgs3SRgHBQTRAk8/0n1uOvV4uHaGtSyztDKkcgDyCfJ8stM0BDWD90R5dbtGPePAPMJ+RJdG94iRSlgLgwyLTS3NKczCjH1LIwn+iB1GTgRhQih/8/2Ve5z5mbfYtmV1CHRH8+bzpbPBtLW1eTaCOEQ6MPv5fc0AHIIXxC8F1Me8iNvKKorjC0KLiIt3ypUJ6Ei6xxiFjoPqwfy/0n47PAV6vbjvt6S2pLX0dVb1TDWR9iM2+TfK+U169HxzPjv/wAHyg0aFL8Zjx5nIislySY3J3QmiSSJIYwdtRgrExsNtgYtALT5ffO37Y3oJ+Sk4B3eo9w/3PHcsN5s4Q3ldOl97v/zz/m9/5wFPgt6ECYVIRlNHJUe6h9DIKIfDh6XG1EYWhTSD94KpgVTABD7BPZV8SftmenF5r3kj+NB49LjPOVv51nq4O3m8Uv26/qi/0gEvQjeDIwQrBMnFu0X9Bg1GbMYcxeDFfUS3g9ZDIQIfQRkAFv8fvjs9MDxEO/v7Gvrjupa6s/q5euS7cXvbPJu9bT4Ifyc/wcDSgZLCfULNA75DzkR7RETEqsRvRBTD3oNRAvDCA4GOgNeAJP96vp6+FT2h/Qe8yPymvGE8eDxpvLO8031E/cR+Tf7cP2t/9kB5gPEBWUHwAjKCX8K3AriCpIK8wkMCecHkAYTBX8D3wFCALf+Rv36+976+PlM+d74rvi6+AD5efkf+uv60vvO/NL91/7U/78AlAFLAuECUwOeA8UDxwOoA2wDGQOyAj8CxgFMAdcAbQAQAMb/jv9r/1z/YP91/5f/xP/2/ygAVwB/AJoApQCeAIMAVAARALz/V//l/m3+8/18/RD9tPxt/EL8NvxN/In86/xy/Rz+5f7I/74AwQHGAscDuASQBUcG1AYvB1QHPQfpBlcGiAWCBEoD5wFkAM7+Lv2T+wv6ovhn92X2p/U29Rf1T/Xg9cf2AfiG+Uz7SP1p/6AB3QMNBh4I/gmcC+oM2g1jDn0OJA5YDRwMeAp1CCIGjgPOAPf9HftY+L/1Z/Nl8cvvqO4I7vLtau5x7//wDfON9Wz4l/v1/msC4gU8CV0MLQ+TEXoT0RSKFZ0VBRXGE+URbw90DAkJSAVOATj9Jfk49Y7xRu5860fpvOfq5tnmjucF6TfrFO6K8X711Plr/h8DzAdODIAQQBRvF/EZsRudHK0c3BsuGqwXaRR6EP0LEwfiAZH8SPcz8nrtQumv5d/i6eDi39Lfv+Cj4nLlGumA7YXyAfjN/boDnAlED4QUNBkrHUogdSKYI6gjoiKJIG0dYhmGFPwO7giKAgL8h/VO74bpYOQE4JfcNtr22OTYBNpP3LffI+R06YPvIPYb/TwETgsZEmYYBB7EIn8mFyl0KogqUSnUJiIjVR6RGAES1QpFA4z74/OJ7Lflo99/2nXWptMs0hTSYtMQ1graNN9q5XvsM/RX/KYE4wzMFCMcrCI0KI0ski8rMUcx4y8HLcYoPyOaHAoVyAwSBC77XvLn6Q7iENsl1X7QQM2Jy2jL4Mzqz3DUUtpk4XDpO/KA+/gEWg5cF7cfKSd3LWwy4TW4N983UzYdM1QuGSicIBUYxA7xBOn69/Br54/eqtb6z7fKCscTxeXEg8bjye/OgNVm3WbmO/Ca+jEFsQ/GGSEjeCuIMho4/jsVPks+nDwSOccz4SyUJB4bxxDfBbv6sO8U5TvbdNICyyTFCMHQvpK+UMABxIvJw9B22WDjNu6k+VMF6BAIHF0mlC9lN5A95EE9RIVEt0LgPhs5kjF9KCIezxLcBqX6ie7l4hbYcc5Cxsq/P7vFuHO4TrpJvknEIcyV1V/gLOyh+F0F/xEjHmopfDMJPMxCj0cqSodKoEiCREo+JjZULB0h2RTlB6f6gu3g4CLVpcq7wa66tLX3so6ygLTAuC6/nMfJ0WndIuqS91AF9RITIEYsLDdxQMlH+UzYT01QUU7ySU9DmjoUMA4k4xb6CL76newE31/SEcdzvdK1a7Bqreis7a5qsz+6OcMVzn/aGOh49i4FyhPaIe8uojqYRIJMH1JDVdJVxlMsTyZI6T67M/Am6xgYCuv61+tT3dHPucNsuTyxaasjqIanmKlNroG1/r59yqXXEuZV9fYEfxR1I2Mx3D1+SPRQ/FZlWhBb+VgrVMtMEENEN8Ep7ho/Cy37M+vO23jNn8Cqte6ssqYno2yiiKRtqfew7boEx9/UE+Qs9KsEExXjJKAz1kAdTB1VjVs6XwVg5V3qWDlRCkesOn0s6hxrDIL7r+p22lbLxb0tsuyoSaJ6np+dwJ/PpKesC7euwy7SHOL98k0EiBUmJqc1kEN1T/hYzV++Y6pkiGJmXWtV00ruPSEv2x6cDen7SupJ2WvJLLv7rjilMZ4fmiKZRJt3oJOoXLN/wJfPMeDL8d0D3RU8J3U3CEaDUoNcumPuZ/1o22aZYV5ZZ04JQaoxwCDODmH8BepJ2LnH1bgTrNahb5oalvqUGpdpnMKk5K96vR3NU96Y8F0DExYmKAs5PEhEVbxfUWfGa/ls3WqBZQ1dw1H3QxU0lSIBEOj83ul210DGw7Z4qceeBZdvkiuRQ5OpmDWhpqyjusLKhtxm788CKxbkKGc6LEq4V6BijmpEb5twiG4YaXZg41S2Rl82WSQyEX791OnO1gHF9rQspw+c9ZMgj7eNxI87lfGdpan9t4rIzNo37jMCJhZ1KYk71kvcWS1lcG1kcuBz2XFdbJRjw1dDSYU4CSZfEiD+5+lS1vvDb7Mwpa6ZQpExjKGKoIwhkvma5qaKtXfGKNkN7YsBBRbbKXM8Ok2wW2Fn9G8jdcZ2z3RLb2VmYVqaS4Q6oieFE8z+FeoC1i7DLrKFo6aX7o6iieyH2olfj1GYaqRPs4zEm9fq69oAyhUXKiI9WE4yXTxpGHKAd0l5ZXfgceVouVy6TVo8ISmkFIL/Xerb1ZvCM7EroviV+ox3h5qFdYf4jPqVNqJNscvCKdbR6iAAdRUpKpk9ME9jXr1q3HN5eWh7mXkZdBJryV6eTwQ+hSq4FT4Avure1UHCf7AjoaaUZ4uwha6DcoXtiveTSqCHrzjB1NTC6WL/CRUSKtg9wU9CX+FrPnUNeyF9anv0delsj2BEUYA/zCvAFgABNusJ1h7CEbBuoK6TN4pQhCmC04NCiUySq54ArtS/ndPB6J3+hhTTKd89DFDOX6tsPXY6fHJ+1nxvd2huB2KrUstA8iy5F8YBw+ta1jLC6K8KoBOTaYlXgwyBm4L4h/mQWp26rKK+iNLQ59b97xNvKa89ElAJYBht2Hb/fFt/2n2IeI5vMWPQU+NB9i2iGI0CZOzR1nzCBLD3n9SS/4jFgliAyoEQhwGQWZy3q6S9ltHw5g/9RBPmKEs91U/0XyptEXdcfdp/d34/eVhwCWSxVMdC1i54GVUDGO1s1/vCY7A2oO+S+Iicgg6AYYGMhmWPqZv4qty8ydAk5kj8iBI6KLI8VE+NX+Fs53ZSfe9/rH6RecZwj2RMVXRDjy86GhoE2+0p2K3DBbHDoGWTU4nbgi6AYYFshiePTZuAqku8I9Bt5YX7vRFsJ+g7kk7YXj5sWnbffJt/d35+edZwwmShVehDITDmGtsEre4G2Y/E6LGfoTWUEYqAg7eAyoGxhkaPRJtQqvO7pc/N5Mb65RCAJu06j03WXUJrbHUGfNx+2n0GeYhwoGStVSNEiTB5G5YFi+8C2qLFCbPIol2VL4uNhKqBnIJch8OPkJtoqta7U89G5A/6ARB2JcQ5T0yHXO9pHnTHerV91HwpeNtvKmRxVSNExzDzG0oGdPAa2+LGaLQ8pNuWrIz/hQWD1oNriJ+QMpzJqvS7K8/a42D5FA9QJG4400rvWkZocnIjeSZ8ZnvodtBuXWPqVOdD2DBRHPQGZvFM3E3IAbb4pa6YiI7Vh8iEeIXeidmRKZ11q068Mc+K47v4Hw4RI+42HEkPWUpmaHAcdzF6kXlCdWdtPGIZVG5DuzCTHJIHXfKX3eHJ1Lf8p9Oav5ANivCGf4e2i3GTdZ5rrOa8Zc9Y4yP4JQ28IUc1L0fpVv1jBG6zdNd3V3c6c6BrxWD+UrdCcDC2HCQIWvP33pvL3LlDqkidT5OljHuJ64nvjWeVF6Csrbu9yM9E45n3JwxRIHozDEWBVGFhSGvscRp1unTQcHxp+V6YUcNB9S+6HKcIWPRr4HrNGLzLrAqgNpaaj2mMuoyJkLiXDaI3r86+WtBQ4x73KAvUHooxuELZUXleN2jJbv1xu3EGbv5m2VzoT5FASy+dHBkJWPXw4XrPhL6SrxajcJnqkrWP6Y+Ck2OaVqQLsR/AHdF+47T2KQpIHXovNED0Tklb1GRNa4JuXG7faiZkZ1rvTSE/cC5eHHoJVfaE45nRH8GUsmmm+5ySll6TdpPYlmid8aYps67BENLO4132LQmtG00thD3WS9RXImF7Z61qompcZ/Zgo1etS3M9ZC39G8cJUPcl5dTT5MPOtQCq06COml+XXZeHmsKg3amOtXrDNNNA5Br2NQgHGgUrqzqBSB1UJV1WY4BmjmaAY3BdkFQkSYk7KCx5GwAKRfjP5ijW0MY8udat9aTanrabnJuOnnGkF606uIPFidTW5Oz1QwdYGKUorDf6RChQ4FjiXgBiJGJPX5hZL1FVRmI5uirRGiMKM/mC6JPY4MncvOmxW6l0o16gMKDponKonrAsu8jHDtaQ5dT1WQajFjEmizREQflLWFQkWjFdaF3LWnBVg01CQwA3HSkFGi8KGPo66hDbEc2owDO2A65WqFSlFKWUp8Gsb7RgvkfKxNdu5tP1eQXpFKsjSzFiPZNHkU8gVRVYXlj5VftQjkntP2Q0TycVGSQK8/r0657dX9CdxLK66LJ8rZOqQ6qNrFuxh7jWwf/Mqdlx5+v1pQQuExUh7y1aOf1CkErZT7NSCVPbUD1MVEVYPJAxUyUAGAAKwfuw7TrgyNO4yGC/Brjhshewu6/OsT2247yKxe7PvduY6Bv23QNzEXQefCouNTk+WEVWSg9Nb013SzlH1kCEOIUuKCPHFsMJgvxp7+DiRtf0zDnEV72BuNu1drVUt2K7gMF7yRTT/t3j6WX2IwO7D8ob9CbjMEw57j+aRCxHlEfRRfNBGjx3NEYr0SBqFWwJNP0g8Y3l1tpN0TnJ18JXvtq7cLsavcjAW8amzW3Wa+BR68r2eQIIDhoZWyN9LDs0WTqrPhJBfUHtP288IjcxMNQnTh7qE/oI1f3Q8j/odt6+1VrOgchexA/Co8Ebw2nGb8sG0vfZBOPj7Ej34AFbDGcWth8BKAovnDSOOMQ6LzvPObI28jG2KzIkoRtHEm8IZf549PPqIeJE2pnTUM6QynXIC8hTyUDMutCa1rHdxeWX7uH3WgG4CrMTBhxyI78pvS5IMkg0sDR+M8EwjiwKJ2IgyxiCEMgH4/4W9qbt1OXb3u/YPtTo0AXPoc68z0rSNtZd25bhruht8JX45gAgCQIRURjVHl0kwSjgK6QtBC7/LJ8q+yYwImcczxWcDgcHTf+o91Xwiul941reRtpg17vVYdVR1oLY39tM4KXlvetk8mT5hgCUB1YOmhQvGuserSJZJd4mMidWJlMkPSEtHUUYrxKWDCsGov8t+f3yQu0n6NPjZODz3ZDcRNwM3eHeseFk5drp7+559E36OwAXBrML4xCCFW0Zhxy7HvsfPyCJH+IdWBsDGP8TbA9xCjUF4/+i+pz19vDV7Fbpkeab5IDjRePo42Plp+ef6jHuQfKs9k/7BQCqBBkJMg3UEOcTVBYLGAEZMhmfGFAXUhW3EpcPCgwvCCYEDQAG/C/4pfSC8d3uyexT64PqXerg6gPsvO3676nysvX8+Gz85v9OA40GiAkpDF8OGRBOEfYRDxKcEaQQMA9ODRELiwjTBf0CIgBY/bT6Sfgq9mX0BfMT8pTxiPHs8bvy6/Nw9Tz3Pvlm+6D93P8GAhAE6QWFB9kI3QmKCuAK3gqHCuIJ9QjMB3IG8gRcA7wBIQCX/ij94fvJ+uf5QfnY+K34vvgI+YX5L/r9+uf74/zo/e3+6P/SAKQBWQLsAloDowPGA8YDpANmAxEDqQI1ArwBQgHOAGQACQDA/4r/af9b/2H/d/+b/8j/+v8sAFsAgQCbAKUAnQCAAE8ACgC0/07/3P5j/un9c/0I/a38afxA/Df8UfyQ/PX8f/0s/vf+3P/TANYB3ALcA8sEoQVUBt0GNQdUBzkH3wZIBnUFagQuA8gBQwCr/gv9cvvr+Yb4UPdT9pv1MPUY9Vj18PXe9h/4qvl1+3T9mP/QAQ0EOwZICCMKuwsCDeoNaQ56DhcOQg39C1AKRgjtBVUDkgC6/eH6H/iK9TnzP/Gu75buAO727Xvuje8n8T/zx/Wt+N37Pv+2AisGgQmdDGQPwBGcE+YUkhWWFfEUpBO2ETQPLwy8CPUE9wDg/ND45vRD8QXuR+sg6aPn4ebg5qXnLelu61nu2vHX9TT6z/6DAy8IqwzVEIoUqxceGs0bpxykHMAbABpuFxsUIBCYC6cGcQEf/Nn2yvEa7e/oa+Ws4srg19/c397g1uK45XHp5u328nv4S/44BBcKuA/uFJAZdh2CIJcipCOdI38iUSAfHQIZFRR/DmgI/wF3+//0ze4S6frjsd9Z3BDa6djw2CnajdwM4I3k7+kL8LL2sv3UBOMLpRLlGHIeHiPCJkApgip7KigpkCbGIuMdDBhtETcKoQLn+kPz8ust5SzfHtos1nnTHNIi0o7TWNZt2q/f+eUa7d30B/1YBZANbxW3HCwjnCjaLMMvPDE4MbQvuSxcKLsiARxgFBIMVQNw+qXxOelw4YbatdQq0A3Nd8t3yxLNPNDh1N7aB+Im6v3ySvzCBR4PFRhgILsn7i3FMhg2zDfPNx82xjLdLYUn8B9VF/YNHAQS+ibwpubc3Q7We89Yys/G/sT2xLrGP8ptzxzWHN4x5xTxe/sTBo0QlRrdIxwsDjN+OD08LD45PmI8sjhDMz0s1CNJGuMP8gTN+cjuOeR12sfRdcq6xMbAuL6kvozAZsQVym/RPto/5CXvnPpMBtsR7hwuJ0ow+jf/PSpCV0RyRHlCeD6LON4wqyc4HdUR2AWh+Yvt9eE817PNpsVWv/W6qbiFuI66tr7fxNvMb9ZS4THtr/ltBggTHR9OKkM0rDxGQ9xHSEp0Sl5IEUSuPWQ1cSshIMoTzAaM+W7s29801NbJEsEuumO117KhssS0NLnPv2XItNJv3jvrtfh2BhMUIiE8LQM4IUFNSE5N+k86UAtOekmpQso5IS//IsEVzAeO+XTr7N1g0TLGvLxItROwRq37rDWv5bPruhDEEM+X20XpsPdoBv0U/CL3L4k7VkURTXtSaFW/VXxTrU52Rw0+uDLQJbUX1win+ZvqKNzAzsvCqLiosAqr/KeYp+Opz642tuG/hsvO2FHnofZFBsUVqSR8MtI+SUmOUV9Xjlr/WqxYplMSTChCMzaQKKYZ6gnV+ePpkdpWzKK/2LRQrEum/KJ9otak9am1sdu7G8gX1mPlifUMBmwWKibLNNtB9UzAVfdbZ1/0X5ddYFh3UBZGjTk8K5EbBQsY+k3pJ9kjyrm8ULFEqNuhSp6vnRCgXKVsrQS408R2033jbPS/BfIWfifhNqNEWVClWT5g8GOaZDdi11yiVNVJxDzSLXMdJQxu+tfo6tcqyBK6Ea6HpL2d7JkxmZabCKFgqV+0sMHt0KDhSvNgBVcXpCi+OChHclM5XTJkJGjuaIlmBmGOWGBN0z9OMEkfSA3W+oLo29Zpxq+3HqsbofSZ45UIlWyX/pyVpe+wtb5/ztHfJvLvBJwXnClhOmlJPlZ7YM9nAGzsbIpq6mQ3XLRQt0KtMhIhbQ5P+03o+dXjxJG1eagEnoSWM5I3kZaTQpkOormt6LsvzBDeAfFuBMMXZyrKO2RLvFhnYxNrgm+QcDRuf2ibX8xTbUXtNMoikQ/Y+zboRdWXw7izJKZDm26T4I7AjRiQ1pXPnr+qSrkAymHc3u/fA8oXBSv4PBlN6Vr8ZfptpXLXc4ZxwWu1YqZW8kcJN28kshBu/D3ovdSGwieyHqTbmLWQ7YupivSMvpLbmwWo37b2x8bav+5CA7UXdivsPYdOxlw4aIRwaXW/dnt0rm6CZT9ZQ0oBOf8lzxEQ/WDoYtSwwd2wa6LMlluOWonyhy2K/Y81mY6lqbQSxkLZpe2bAoQXuyulPq5PUF4aaq5yyndFeRJ3QnEAaJNbXEzQOnYn5RK9/Z/oMtQUwdqvCqEYlWGMK4eehceHl43gll2jrLJYxNfXk+zqATcX1iskP41QiF+ga3d0x3lme0h5enMraqBdPE51PNQo8hNy/vjoLdSywB6v+5+/k8qKYYWvg8OFjIvflHSh6rDJwofWi+sxAdIWxitqPyVRbWDKbN11XnsifRp7VnUBbGRf4E/tPRYq9RQu/2rpUdSJwKquQJ/DkpWJ/YMngiOE4Yk1k9efZq9pwVXVj+pyAFUWjSt3P3ZR/2CYbeB2jnx2fod80XaAbdtgRVE1Pzgr6hXw//LpntSYwHyu154kksSIAYMIgemClYjikYaeIa45wELUoemw/8EVLStMP4FRPmEKboB3V31hf4597HembgRiaVJMQDos0BazAJDqEdXewJSuwZ7gkVaIbIJRgBaCrIfpkIWdHq08v1LTw+jq/hoVpyrqPkZRK2Efbrx3t33jfy1+pHhyb95iSlMvQRotpRd5AUHrqtVawfGu/J75kUyIQIIEgKqBJYdLkNScX6xzvoTS9+ck/l8U/SlUPsdQyGDYbZR3r336f2R++Hjhb2Zj51PdQdQtaBg+AgXsZtYLwpGviJ9tkqWIfIIhgKiBA4cJkHWc5Kvgvd3RP+dg/ZQTLymKPQZQFGA3bQl3P32ofzJ+6Hj0b5xjP1RUQmguFRkBA9jsRNfuwnOwZKA7k2GJIIOogA6CRYclkGmcsKuFvV3RnOaf/LkSQSiOPARPEl88bB12aHztfph9dHiqb35jT1STQtQurBm/A7ntQtgCxJaxjaFjlH6KKoSZgd2C7IefkLGcxKtjvQXREebk+9IRNCdjO8JNwl3patB0KnvIfZV8m3cCbwxjF1SYQhcvKxp3BKbuXdlExfayAqPhlfuLm4XxghOE94h2kU2dIKx8vdjQn+Uw++AQCiYKOkJMKFw/aSNzh3k7fCp7Xnb7bUVillNiQi4vkBonBZ3vldq0xpO0wKS1l9aNb4eyhLGFZoqrkj6exazPvdfQSOWE+uUPxiSFOIhKRVpBZxlxgXdIell5vXSYbCphzVLxQRkv2RrOBZzw5ttNyGq2x6bcmQ6Qp4nYhraHOYw9lISftK1fvgLRDeXk+eMOaSPXNpVIHFjyZLRuGXXwdyN3uXLXarpfuVFDQdcuBRtoBqHxTt0Pyni4E6lUnJ+SPoxiiR6KbY4slh6h7K4rv1vR8ORP+dsN9iECNWxGrlVSYvdrUnI1dYl0VHC6aPZdXVBZQGcuFBv1Bqnyy972y7u6oasan4iVNI9NjOmMApF2mAujbbAzwOPR8eTJ+NEMbyAJMxBEAFNmX+NoL28Zco1xkG1DZt9bt04xP8gtAxt0B7TzW+AAzjC9bq4rosaYhZKYjxWQ9ZMam0ulN7J5wZnSEuVT+McL1x7vMIRBFFAxXH1lsmugbjJubmpyY3ZZyUzNPfos0RriB7/0++Eq0NS/eLGEpVScLpY/k56TRZcXnt2nSbT7wn/TVOXu970KLx22Lso+7ky2WMdh3mfMantq8WZLYLxWk0otPPwrfxo+CMf1qeNx0qPCu7QhqTCgK5o/l4KX75ppob6qo7a6xJXUt+Wc97YJextiLOY7kEn4VMZdt2OgZmtmHGPOXLRTFkhQOs8qChqGCMz2YuXS1JvFM7j/rFakep6Vm76b754Qpe6tQrm0xtrVPeZd97QIvRn0Kdo4/kX7UHxZQl8hYgVi8V7/WF5QVEU5OHIpcxm6CMr3JedL17nI3bsascOoFqM9oE6gRKMHqWmxJrzpyE/X5eY097kH+BdwJ6w1PULDTO5UgVpRXUxdc1rgVL5MT0LmNeUnuRjZCMH47ujZ2fjLtb9utXGt+6czpS6l6adNrS61TL9Yy/PYsecg98YGLBbaJF0yTz5USCBQeVU2WEVYp1V0UNVICD9bMyom3BfhCK/5uup43FXPt8P2uV2yJK1zqluq26zesTm5s8IAzsXaoOgk994FXhQzIvIuOjqzQxdLLlDTUvNSkFC/S6dEgjuYMEAk2xbRCJL6iewl383S38evvoK3jrL4r9CvFrK2tom9WMbe0Mbcs+lA9wIFkBKAH24rADbkPthFpkouTVxNM0vFRjdAvzefLSkithWpCGj7V+7e4VzWKcyTw9u8M7i9tYi1lbfRuxnCOcrx0/Pe6ep09zMEwxDCHNUnpjHrOWZA5kRKR4RHk0WJQYg7wTNyKuYfbxRoCC/8IvCf5P7ZkdCfyGTCDr69u3+7Vb0twebGU84310zhQuzC93ID+g7+GSokMS3ONMc68T4uQW9BtT8PPJ02iy8TJ3gdBRMNCOj86fFm57HdE9XOzRfIG8T0wbDBUMPExu3Lo9Kv2s/jve0p+MICNw02F3IgpCiQLwA1zjjeOiM7njlcNnsxIiuEI+AaeRGZB4/9qPMv6m/hqtka0/DNU8pbyBbIgsmRzCrRJtdU3nvmWu+r+CMCfAtsFK4cBCQ3KhcvgjJgNKY0UzN1MCUshybIHyAYyw8LByX+XfX47DblUd5/2OnTsdDuzqrO5M+R0pjW2Nsm4k7pGPFG+ZcBzAmlEeUYVh/HJBApEyy6Lfwt2SxeKp8mviHiGzoV/Q1iBqj+CPe+7wHpBuP43f3ZMden1WjVdNa+2DTctuAg5kbs9vL8+R4BKAjiDhgVnBpFH/EihSXxJisnNiYcJO8gzBzUFzESDwygBRf/pfh98s7sw+eA4ybgy91/3ErcKd0U3/jhvOVB6mHv8/TL+rkAkQYmDEwR3RW3Gb8c3x4KIDogbx+0HRkbtBeiEwUPAwrEBHL/NPo09ZnwhOwT6V/me+Ry40rjAOSM5eDn5eqE7pzyDve0+2kACwV0CYQNHBEhFIAWJxgMGS0ZihgsFyAVehJPD7sL2wfOA7f/svvg9130RPGr7qPsO+t56mLq8uoi7OftL/Dm8vb1RPm2/C8AlgPPBsQJXQyJDjgQYRH9EQsSjRGJEAsPIg3eClMIlwXAAub/Hv1++hn4APZD9O3yBPKP8Yzx+fHR8gj0lPVl92v5lfvQ/QoAMwI5BA4GpAfyCO4JlQrjCtoKfQrRCd8IsQdTBtEEOgOaAQAAd/4L/cj7tPrX+Tb50vis+ML4EPmS+T/6D/v7+/n8/v0C//3/5AC1AWcC9wJiA6cDxwPEA6ADYAMJA6ACKwKyATgBxQBcAAIAu/+H/2f/W/9i/3n/nv/M//7/MABeAIQAnQClAJsAfQBKAAQArP9E/9L+Wf7f/Wn9//ym/GT8Pvw4/FX8l/z//Iz9O/4J//D/6ADsAfIC8APeBLEFYgbnBjkHVAc0B9UGOAZhBVEEEQOpASIAif7p/FD7zPlr+Dj3QfaP9Sv1GvVh9QD29vY9+M75nvug/cf/AAI8BGgGcghICtoLGQ35DW8Odg4KDisN3QsoChcIuAUcA1YAff2l+ub3VvUL8xnxku+E7vrt/O2M7qrvT/Fx8wH27/gk/Ij/AAN0BsYJ2wybD+0RvRP7FJkVjxXcFIEThhH4DukLbgiiBKAAifx6+Jb0+vDF7RPr+eiM59nm6ea/51bppeue7iryMfaU+jP/6AORCAgNKRHTFOYXShrnG7AcmhyjG9EZLhfME8QPMgs6BgABrvtr9mLxvOyd6Cjle+Kt4M7f6N/+4AvjAObJ6UzuZ/P0+Mn+twSSCiwQVxXrGcAduCC4Iq4jkCNbIhYg0BygGKQTAQ7iB3QB6/p49E7unuiX42DfHtzs2d7Y/9hR2s3cYuD35GvqlPBF90r+bQV3DDATYxnfHnYjAydoKY4qayr9KEsmaCJvHYYX2BCYCf0BQvqj8lvrpeS23r7Z5tVP0w/SM9K906PW0tos4Inmuu2I9bj9CQY8DhEWSR2rIwMpJi3wL0oxJjGDL2ks8Cc2ImYbtRNaC5gCs/nt8Izo0+D/2UfU2c/bzGfListGzZHQVNVs26vi3OrA8xP9jAbjD84YBiFMKGMuGzNNNt03uzfnNWwyYy3vJkEfkxYoDUYDPPlW7+LlK9111f/O/MmXxuzECsX0xp7K7c+71tXe/efu8Vz89QZoEWQbmCS9LJIz3zh4PD8+JT4lPE84vDKWKxMjchn+DgYE4Pjh7WDjsNkc0evJVMSHwKO+ub7MwM7Eosoe0gnbIOUV8JX7RQfNEtId/Cf9MIs4az5sQm5EXUQ3Qgs+9zcoMNgmTRzaENUEnPiN7AfhZNb4zA7F5b6vupG4nLjSuia/eMWZzUzXR+I37r76fAcQFBYgMCsGNUs9vEMlSGJKXkoXSJ1DDz2fNIwqIh+6ErIFcfhb69jeSdMKyWzAs7kWtbuyt7INtay5dMAxyaLTd99V7Nr5mwcxFS8iMS7XOM5BzkieTRdQJFDBTf5I/0H3OCsu7iGcFJ0GXvhM6tXcYtBXxQm8w7S/ryetEa2Br2W0mrvpxA3Qsdxz6un4ogcvFhwk/TBtPBBGnE3SUolVqVUuUypOwkYtPbMxrSR+FpQHY/hf6f7asc3gwee3GLCvqtmnr6czqlWv77bHwJPM+dmS6O33kgcLF9wlkzPEPw9KI1K9V7Ja6FpbWB1TVEs7QR81XSddGJUIfviU6FXZNsunvgu0tqvppdWilKIopYGqd7LNvDbJUte15uj2bAfEF28n8jXcQshNX1ZcXI9f3l9DXdFXsU8fRWw4+ik3Gp0Jr/js59nX9Miwu3ewoKdzoSCexZ1koO2lNq4BufrFwNTf5Nz1MQdbGNMoGDiyRThRTVqqYBxkhWThYUNc01PTSJY7gSwJHK0K9Phm54zW68b8uC2t2qNOnb6ZRpnsm5+hMqpltePCRNIS48r04gbRGAkqAzpFSFxU612kZFRo2mgyZm5guVdVTJk+8C7RHcELTPkB527VHcWMti+qZqB/mbGVG5XEl5mdbab/sfS/489Q4bTzgQYlGRArtDuSSjNXNWFIaDRs2Wwxak5kXFugT3NBQzGMH9cMt/m95n7UicNitH+nRp0Ilv6RSJHvk9+Z7KLQrjC9n82c353yDgZZGegrKj2ZTLtZKWSSa7pvf3Dbbd9nul6xUiBEeDM4Ie8NMvqZ5r3TMcJ/siClfprskqeO0Y1xkHaWsp/dq5u6esv43YbxiwVtGZIsZD5YTvFbxmZ/buFyyHMscR9r0GGFVZ1GizXTIgUPvPqU5irTFcHjsBKjDpgtkK+Lt4pOjWCTwpwpqTe4eMln3HHw+gRjGQ8tYj/QT9ddCWkPcal1snYidApummQZWOdIezdZJBgQVPut5sTSNcCPr1ah+JXOjRiJ/oeHiqGQH5q3pgi2nMfs2mHvXAQ8GV4tJUD/UGlf8Wo+cw54Onm5dp1wFGdpWvtKQznJJSUR9/vj5ovSkL+Eru2fPZTPi+aGqIUgiDuOzZeJpBC06MWI2VfuswP4GIEtrEDmUadgfWwLdQ56XnvveNVyPmlyXNdM4johJysSpfw0537SJr/Crdme35IzihiFt4MahjGMzZWkolKyXsQ92FXtAQOaGHgt+UCFUpJhrW12dql7HH3DerF0E2s0XndOVjxdKCgTW/2f55zS975HrRie3pH6iLGDLIJ5hIWKI5QIodCwAcMP117sRwIiGEUtC0HbUipigG59d9x8cn4yfC12kmyqX9pPmz19KRkUGP4i6OTSAb8UraqdOpEliLGCCoE9gzmJ0JK4n42v1MH/1XPriAGTF+os5UDqUm1i9W4heKh9YH87fUl3uG3TYP1QsT58Kv0U2v696FPTQ78prZCd85CzhxqCUYBogk6I1pG2noqu18AQ1ZfqxQDuFmYsh0CzUl5iDm9geAt+5H/cfQN4hW6tYd9RlD9bK9EVnv9s6erTvb+DrcidCZGnh+uBAYD6gcWHNpEDnsmtDsBD1MvpAAA=\" type=\"audio/wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\n## Video\n\nMore exotic objects can also be displayed, as long as their representation supports the IPython display protocol.  For example, videos hosted externally on YouTube are easy to load:\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('sjfsUzECqK0')\n```\n\n\n\n\n\n\n\n\n\n\nUsing the nascent video capabilities of modern browsers, you may also be able to display local\nvideos.  At the moment this doesn't work very well in all browsers, so it may or may not work for you;\nwe will continue testing this and looking for ways to make it more robust.  \n\nThe following cell loads a local file called  `animation.m4v`, encodes the raw video as base64 for http\ntransport, and uses the HTML5 video tag to load it. On Chrome 15 it works correctly, displaying a control bar at the bottom with a play/pause button and a location slider.\n\n\n```python\nfrom IPython.display import HTML\nfrom base64 import b64encode\nvideo = open(\"images/animation.m4v\", \"rb\").read()\nvideo_encoded = b64encode(video).decode('ascii')\nvideo_tag = '<video controls alt=\"test\" src=\"data:video/x-m4v;base64,{0}\">'.format(video_encoded)\nHTML(data=video_tag)\n```\n\n\n\n\n<video controls alt=\"test\" src=\"data:video/x-m4v;base64,AAAAHGZ0eXBNNFYgAAACAGlzb21pc28yYXZjMQAAAAhmcmVlAAAqiW1kYXQAAAKMBgX//4jcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTE4IC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAxMSAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTMgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MzoweDExMyBtZT1oZXggc3VibWU9NyBwc3k9MSBwc3lfcmQ9MS4wMDowLjAwIG1peGVkX3JlZj0xIG1lX3JhbmdlPTE2IGNocm9tYV9tZT0xIHRyZWxsaXM9MSA4eDhkY3Q9MSBjcW09MCBkZWFkem9uZT0yMSwxMSBmYXN0X3Bza2lwPTEgY2hyb21hX3FwX29mZnNldD0tMiB0aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MyBiX3B5cmFtaWQ9MiBiX2FkYXB0PTEgYl9iaWFzPTAgZGlyZWN0PTEgd2VpZ2h0Yj0xIG9wZW5fZ29wPTAgd2VpZ2h0cD0yIGtleWludD0yNTAga2V5aW50X21pbj0yNSBzY2VuZWN1dD00MCBpbnRyYV9yZWZyZXNoPTAgcmNfbG9va2FoZWFkPTQwIHJjPWNyZiBtYnRyZWU9MSBjcmY9MjMuMCBxY29tcD0wLjYwIHFwbWluPTAgcXBtYXg9NjkgcXBzdGVwPTQgaXBfcmF0aW89MS40MCBhcT0xOjEuMDAAgAAACqVliIQAV/0TAAI/3gU2tIW7KawwaCmQGTGHKmuYAAADACBcshU+yICkgAA14AHowiEeT6ei7v7h3Hu0i2fpUBLGBIkbCMP3Vfz+9BVGCDXnw9Uv5o3iN030tb7eq6rsEEhHs2azbdTiE9Csz5Zm6SiUWRdmB43hbD5i6syATuODUJd7LM3d9cbFpc7zFlu5y3vUmNGd6urpvKKT9iyleIyTuR1sVS431DhevGfkUllVeIznYUe2USoMW1tufETjyRdmGldN6eNlhAOsGAH4z+HkrwKecPPU7Q5T4gDAIxj9hW84jVExMTSTHxkPTq1I4OotgUxURCGTsw60k/ezPNmNg38j1bqaGmPcruDKEIBDsK5qEytFB90Q68s0h2wmlf2KXd5bleBefiK+/p47ZsyUO4IdlW25rRy+HLjt6wQXfYee3IkiQOoOK+U7u/lxcl78zfxwIoEMjUUSKNZjkp8clnmecDDJ3Kz+viF7bPklk7N6QRyizAKPIIpnNJUuMWQmqeL2Or6cr4D0/0tOym+4tficxmhuEONKUtO2pPn3hRjMllkd12tXp70fLTfxy0dwB70ML9iLEcItHb7zVupHlP5RxdvecpREw+OsIPr9KWilIesNE19jgIbT+TkiRBjOoKvUuwcQnKg7fOTHVoLvnKuAfea+oujEdm1Rwd2tEOnkF+ZC11WaNQsiNR/eJ9EnUXjXDYGfhB+Oe7qj8nYTT+eOXg1cuJNgLXEs4vOheWEjQOqfIWMQc3DmTof5s0ksBmUQ3PQ+UHPxZSnmOEZB+j6xT3wbm7HGzDjWtSg1SjTxd1EiJ8xA4SIxxR8WIKLg+TwFxJNS7Laxq7Uglu3AkXe82P1JCdJX5PsbFbxuDbuJgakzRcTwMLLSKCiizS/eCW0uJed/lev9yb80kKlVET4S219cn/zhkpeDV83cHYOr+sJQKDRk/Wh2c7fsuxfxaEH/6reSmvFDsAnXAyPXliJ3G4VG3OkEM5K5WyGGrBizZbTrdGsBnzj5VSGGOJdCKuRrUluw/8es2vYRPs9BcTqAqvHk9M52SSIf+1T6L53EZP8VbtXB+G29CMW4xVCK/B/YDjaNmqMwJ61dapugjnWJfqeXlGGa3Ch3aA7gi30T8PucNRBjLK3lF67ZDDvkWXRQXd+VMnKWHkBbCkQ/F/fMuNpHO3C00Y2pljna1qImBhVMvPe0F7Qx7G/YyxLRzhyUU8e23HGzp0agtNJRbydbrPV+TqJMSifJMNcZIf8wkdnC3/xdpcXnLf2Ye3Kbd0o7utciTG+q5h6WTEk+PaNbXLLA0YyZ2VnLTcyV1QTS76aNCbV9Q1/OQ7QU81Gg0hPa9aSiscGary6jLVwDQaik4zLsi7jPqgPVdup7pwx7uJDqRCVcVi5QoZFp/GHdex5sJTF69A6sja69/NLkFIWNSIeRcuGahXpF+wZeYIrqJv975s1TKYKAvp1WtzgtgWNkcbzCtROqf8rPtlAIxkX8GLcEo9zfExyfimeXQ64qfFxEy0IMy2Hsxau9fSMqUnIjntuVVjCQtBL+94gx1RZLndE6wROVTq/wHwHrQzo9QL9cpPqPFJjiZ/NGZIFuudS+wsBFe6Hu8Oitf5zToLqLdtU4Smwh4ne3JsiT9lOzN+4PPw3VSx9l5FppVwdKUWELw1dYpCOppyVWlJ3YQ8H4FQQM8EcYMG9N3Bxu79y1J1ikuvuhMmLQlehLTbguhbix74hd1VIQC8EjHmOZSSWbssulYwPbr6FF49tifk6PymJvulR9/u+2585HkRfbxveGeWCz0ix1pIVfaNpESKmtLy/0mcbMg9hYDz2werz9oe0lT2BiMV6uAin6RaQcT8Vk9MPctfwae+gkvtnZA/sOBk8MbpylaHqc0KIVHhhLFMNnkOFiucjtGo/JWTa/F6g8wWeow5ZuIJUORaYHWqegZbTgM9dCsYYsfZGjjVMuSlDIvpYvIvFFooGPC7Ye2Jfawmq4Ut7EL/nv/dyAd2HRc5msmUhzeu/XpX3rVlzRmf9/Qan8Dbve3QfW1Ym0o5J/KAc3z1VBho7JBr5PgCL68RiD9jZHN0VvsT4gzsEjNlW3D91Uy4RduaodBFoNTzXwlfUYULBzdiTbH75l/UmVMC4TKeTWhNzw2UezaqeGd8at3WSY7W/VR3+hvZHDpkIjgKuNNH0DsCRa/Kk56XQoHIyvvUH/eNekNvziReqS4qgLnXUT4BRGt2BOtCifI6+X/DGHUOmWlX7TN5b4pw5U7jwfwshtbhGZM49T8JMk15Mzrc7tM6J11TYxb5R3mQhZ8TZumJ0bMJXPM69HFyihr5dJSEJMycxJVUh6NTQALUOoRTHIOwE+FpWI6feTv1SiZ0YpYe5DbkYJJbN7zAHbAKw25XvqR2mAjQmOlsfX/tK8DPjP/8h5/xgAF4EUbj1tOnQCBQL8jk9vHtfsXncsprww4Z+P/Z/UrKifuFyEpBWN8kLpF7yywE2iYdDruV9+/qKR8rC9ozNKyqQNIwtxrzYkWpE5t8K7gG4JFnrHona/Rp8dOX6VW41+jb5LB1LEtE8MwjLp3RCUOq/+6yLzaOEgBTqzvEjDeFpg/u9DMHMr4/2TOchfjg7dl+uQ6Gsx+4Ia9W7vivG95027p25eKL0nHvx/OqmAQEZYJL/JO58lOj0zPdJxrQ5dZksjMISzVZNn7DsxqE3zgBBuNzk50R8lTK3U8P12QiOAQYSTeGlYlkvfeofrfO1AitEj02m9aUkxTFd1ZZJoLQT2d3zEU5PmE4lxMVfL5ttNnIbqfcIU2RJKNWqdw77xfjfrNc/eNpRKPZ/6z50LzBprgjzBHRfKgSWWkDxHrX0aTbgwQFwd51+PoUWH4DkQg26uGslF5Hn3hB58+fkeLTosTANOIBNAeFZtTc4PIaLHw759zae7scY55xcTabzlilYIftst2RZ6ntsRC3zFxduCKvL6wLfYT+TiIWJn5P7sTwZwXuSzXY+9Q3xMZ5o4Xcpz6vD9FtTjzS69iefEYt4pXiDrZUo4ePGiLeoIFIwYB/v6GXdmG5VLLk+eKbOc9AmsX2zmvqtcvDRGQbzugXbH/kTH/lkNPBTmqN3ZJODUEXVohPEJ6th0xna0EVleB73Q3eNvaVUvhlJbjs3D/T17FRCebN7AOXvzzbLE/I5kNfEmJcv4dxtIeo2uQ/z9ohSpiZzbDj1u40nJRyJxUK60wEv0nA9f/NuJ6/PEyU0bkK16z2KH12k3Lc4+1f5fawIzkK2qJRB4wnj8VHhUW9mbJhs9vgfFmU3xrXSShY67Ygb+gYNPxxtn4K/9eTSwIA9fv/nR33lA2lZoXALRUTmOZIl3R0gAM5h6oX1y1thIyqViBK95VZc8Pvy7G3O90M9S4zkpyFQ36jrMazvMveMA4d39fvoaC7p90quiJfjI4yrl+ECVkCJL5MxRSa+iVcIL7Xbl0jVaGhZIcMYmcGOBbLzhJgloM1x1zFnnj3ggJRFAM8yNnXxhavk+mA18JC+y3lqGsp6vPReRxGlGHMou17L4It070LzkoeCzarpv8Apw59smdS5KN9qVN1WgeL7OSN8BHg94ubCvS7DW6H3/PbtRB62jFLsBhUV5YqCIbIN5VZ81AAACpUGaIWxFfwAru8x8uT3FuOjrAeSWXmAWqq9jCNGE+N5AOv//9//xjk4uBAcADN96c97AVGmzRtnWwPsgcCbLrVdQJgbKp4QSmPwQnVhv0hXyBjeFWWlcvx70urEN3FK6/lvk2tQeZgbtlbzXluvTfnSj/Ctz7vZ+O1FjhDzzdpL7uLzewzCIW5VWLAEKUVuS2J6wNk6MR7UblcEd4EtOY+R4/qJgfojCsfRvA0oC5dc41Vd0erZbSkrmPTjLCn815bxlchUJMS8gQD5hJNwoKHvNLNwn7XKuTtYIhH2wVNZvDWgzCjlPeQajnrcMsb6bZYJvNJU8HuGHvm50r7VG8qifEwmuyegAZXojh5Ul5VvjDW7kSAZyw8a7I6mHY3FZHd+OA3V4JZMbNliI3Tj1L6+MKTmilVialmyZagRtEMeKRdtxUPd3vVEtrOBVIVYWdgAGA7HmZiHQUQNxLkWxbLyWVlrh5EM0Do2NdbclHxxArz90d+MSVeUOIXQ/4V9quq8C8qVflo1gPtPMkjO2/UrdOYqhY404ReObOu/fdp4hAEDq6jhy64vOeT7XUK/Onq0rXTldtA6kvgQaJg+mgYSR9hfXtMbOUSLgLj/RmBSO8aAMHuJJZqf1tCM5pZ9eYUsrHmy+/z2NGalon0//uF6+33bQzT/RLRfBbYTjy9QrJqHLlw46lggWPGkHuPKSqk/CB7U4pNPXUbR0DdcJy9Db00wCzVzxVc6h7jfCFgiL2Y0HVqd6bgIaVUqn/gJCEyCDVplnzebv0gg3XwMJAGu639lHu7rEvxTp1smIYjWp9R5L4SspVvS07Nb+Smk1FgsMp1K3EMUT8X2Fty4VG54/Ec6bE8tNVw4/QV1VzBw7Px2/2eEhhUS+FMfbHAlD28x00jRgAAACW0GaQjwhkymEVwArOUkEOhoFqiELtH8wgecFLiUq6WqmwAP7iGEwbYzfnHacfqUNXAfD+CGR2ap0lAHL25ipuYtd5j2O0PU/MpaWPG/n2y5OkfTzaOpotaR5tWjN55B2XblVVqsFfBC/mvsiPvCBWUHFChacdY5whj5mP5rqQ0dqLJCsWjrs4TWnIbL2V/Iwfj3hwI35jfo1JkTOeR+8GhOdma9rgiKWafCbQyhYMTDmVdvhND60Flm97EDSTjF0OC+0gD9b8Yn4tNeHipCa/aWyt0n79bMmjfcjntBCPjrcB5ecRTpfGHbEHy1IRj2cjkGXKC+VYoYJXBp4rd4cMd8ygLCk5nBSd8/cTaKNRjdBscOeTXG6QEjSxj9/2pVwx9DMRVtWQR0BSaAcQcZ8W2KPSaeRC4QwmNMu2xx25CSyrDiq2rFSK/JJtmvoIjAKq0ciEXoOgw+Ke+Ylb7ULKCS3k1p/613UNRp450uSq5b7CAHo7S0b7fBMLfNmwSjRYEhLlo0HUaRe/I+IX2Z6XdZH9Hty/399ZA1PwZGC6EfvUJIf7CBeaxv7cu6IT2/s0zPRGthpvXpYw6A7P4Wwz5C4V98KnIUNUanadqabKP6eXWhvbvcQHxAjiOOiKZgXZplZW2g+B2NNyJSLiR+g48DqvWR6t9S2aGfFjdOW1Gi6oTtZ1d4p5XIslAr8mryeZ6+htSSQe4AcfVt7k+V6mOthBCYtr/LEU4ZHtl0mW9876PK8mRFAaT8DJOUFVz1lPfzRApuPggkkyq+UMvyfKTUbCk7/DpfX8Y4s4QAAAg9BmmNJ4Q8mUwIr/wAsWUPjZw3ksgRsxZ6n4fQjprPbkj2aUh30y0bZJnLmiXnWskvOGnCPwBnG9dEhatwX3hoxk7BNyG+wQ4emZUpcVzcWl2T9nKQB1euucuZWHTg7TCtM/iHyfPO2vbmGsfzs70b/egIbywUH4y4BQSL1nWc1SmpHm2zHMBcUjYLDZ5gL5vdfxn0V8FFw66G88c/LN4I5icUa7xf4fcSBKywU0ajbp1P+aJYjBgWT6Ggu0MDLDNl54tfqd42lKosQtM1aif4WXAZFP5Ww3vrQ1rH9+utSYxqZd6N6gGtNbSNMcViaKn5LcnjsbBi3T3EmGqshEbcme8VHKwR3kSfBOAprrIsv6K8R+X6az+MD23rWka/2v64m1qM69D7Xa+Kcs/n0KLCJdTilyaGadopLeaAn3eYvWTeHcucMM1Fp1KgHD1tiFeO6HvobLkZlRximsA3/7MiohYklLIcJrZL22BH+6W9d6kZsYIsej9RM681nU6mWNjepBAfAfTbrGRrVB/h2DxC5B8YyRjgSIzQjNYrse0rzChqbrsLl7mQ7W+1bsNKze5//9ZIa8rSsF+BXh/vgoRTDkPW/ws95B7VPCZEFChfX0icw+tpcpN/q7NY87tUn4vESdSiMMlyhKklMjQu/G51J69ZRQLs2oUO6YfoJFqliy4qCFCrf8SZE9Fc6DcCagAAAAodBmoRJ4Q8mUwIr/wArPWF/KOw78THwadfPqhJO0CnmR/M74/XYZLqVYKlNcEaYauf+vrRUDJPmu75sMKy2Y+Bnslc/iAISSyWtw/h/3CF8fE5ZrbrwSNst+MSyCoNWP+8imtoX2eyojpdCk8YP5K+cbK4SJPCkZXbYqSXYk7hO8AdSemBHgXKWiZ+UOr802aJo+98ZOIjX9hWL9bo31Gqx7cy4ZG+W/ar/WGlzDa1xPWnPRsEdrIcZlEVGV/jGmbirkxw1lyUYoqj8Vv7Bxube9XPQlBkXOV6Lc1LT2IzNq0V7WwVhF0kA6yxfAsFxc9krNEH8vGGntTWI608ovjatXc/CKKXw7AjJSftlTcLI0hIIGXbRUr0NCYNp7M4cVd/n73Rjetnixz4SAKpcz/P47UsijZG7T3SxzK2D79WS42aEalc12hQwCZ01LfmF/H2mmGEvOzPBie1D0YT7Jh19vxa4Dd3SQ1FrDfmSUpvv4DjbYcZ2PrPpFpWtMjWqHBeoyMiZf6RP3EfYR6z9jsVNIIHxM0bzzBQF8eeYkPgDySydxPXv9Izo+QUY94N8kWi16fI6eZSDc1G0Yo0L91jcRQuDMGGS7B2zuf/0GbJyRhUO48UbMrqnILMrbQg1LF00Q3pH9nbGEK/RRQpRN3T/J/4IZQjwW2Ft2ipWGztg1Jn9I4DmffKS60QC+JQcyakdVON6zDcKttIKlqeTcmAi4xzmo4QXa2dRKleS+fs3EtTdBBtony2wK9T2Imj+NCziOSEL7Q7VuIU8kclUHrJJsSneFcxGRgIgGGUEQM8/pklwTOqab7mMmJeRiaBrjJDEnDpkR4Vz3qXxgyn4/5x24FuTMNVPwQAAAhtBmqVJ4Q8mUwIr/wApcLwPT0/Xh9UdWqWXIs8Wbj5K1hivmN6qIQnq+aolcegdlM/63MbHsdC6xYZC1e/Q8UjQCt9N/Ejqwms8DzeWv2qxskeliZH0kt1QWkErWSEodq7V0ZNksctLkMGWayX33gBT368EehfIeGDolBZoqIbJfb4nqcfU+ev4OzVv9zVqWyLck315GFmXxQKIM8pICQc8Q5es34LH1+DmnMnW8kQpVGrztQcDXhjCU3F0fOgoSsXSVWCjc6XKqGbCwQDfJUxCfXfIT6YmQoPpVp1mpGy1wQypXus9z0bScDpyDu23hViYDntdj1O45ea0znKZkj1+tLHbBtqAGJ1WTcbGlF6Vya6hQhEsiiZUIC2fRxIj8/wEXCICIbr0gZ/m6gcOhE10tenvE7iy+BKY81wLWrnzos3S6FWxYtmCRes+LLhNGOKWRuQo6SyePH2OZ90xZm8oA1MuTe3V59euVNxjAt0FLkAc9TEiFhP/8CB+gA8mF+A8h1U01f4DVX55GzCH51jHI2xUS0L9GtsHoBxLPLK/NNel8zcnwG4X+UusfcfEb5hh+ffnXteCE9vRGbs2n9wYW0xA3ZicklfadmWKUtMiHYBfkMSULWnkBQr4CXxjpYOs6ygeEoA5+5B0B1SZObgZ42wWqddyyYE0NfwQAl75tfdJGqOa7OMHwBYNeatJaJK0zT2+bFaw2qWCWwAAAitBmsZJ4Q8mUwIr/wAstkdsayRXchoFk703izqzduZ5WsyXriI9cfUdMUWvm0iGHwYIrUujvz3Yjou+JLwv9df2kt7MJo8u+3P5CjEKbwlz4vkE5AHTAbgXn3+Xc/MMJLgW5cm7iX3KiGNnBpbphhwJRlb3u91NRDr0d1IR2up/z7lKxE7XPAPFe0siPMYVlIqWNSn5KqLABPeuxxbOsvMEb27/nH1LUVM8I2F95c1I3Lv1SpkhZXjs1JsmS9X7gsoTxkXyShGC2+zRJSGUbhCPo/q1XSFMHQyMWJ79FKPQSL/RpVsacN2bYwdKo4TFBw1SsKq/L1iOmqMI+4Gxnbbjojdk0ek0JIcDb4bHv1czxchF7FX1Ym8H6IpPuE8CeNKjzQ1a1wqhEu+wl1N0x3Y37ZryCCKJRkxj0FT7bOoH3L38/yMUuh/v3aCmxY4eCkykb2p6ZrYMFE044anM/nMjmbErMibfRFuCz58Io1rBlF7JfkIz0R2/5vjUMVskcdbX2mm7DntncOsWDIdg/XVmgsC9CzVzUyq4VsS/sk97lJggcddpWLNw/29egz8iLyzWHOAXCvl2fTIPkviYAOQXfVhZUQdxsyJUNFMTiALrZCmoQLMp2LmDbfbW8JQriDeR3fVz6P1sjT8C2yEDvzkCn7sh0aTBK+sx7BKH1nb4320+caQepQj4TCJtCeNXjdrVcNEnjvwlcRJwFT1pT+Y7HREbHnT71XYNh4EAAAGEQZrnSeEPJlMCK/8AKIjxcI58rm/ML255fOJW1zbznFna7lfgMQrka7OTPPsvVAV4EJXye/Uxiu9dlftmRypJqfDot3xwDe8lX/qAVf6pBkSlUsaLyBYtww/SUSa1bGl1JvrJCN7FXCCXbLd5R4PoYlPiDIm/DQH2puO0StIWmrR77Isc/J1pRvdu5+mQa/n0SEHUeM2KkoRzCznfD9zaaRO7BDtvC9SYIT0uYZxrwTjxQ7N7UERTrYG0P+vRLAhxkfohFIYl3HXyjPOvnlbUFP2oiiy6nkUFuaIyQcJawJv3GU8k4ObcKsC1cNDXjSpsyQRrxLFaCCjke4mikyt7vs0iN0bnrNWv9HXruG9zOFEOer1ggIFTsT1Eos5CXRkgja5HN4QUM6MhWpc5du/HgBIH8ANFcoo2kJpqcadw9r/0qk25X91MQSDJQiH8Hny2dQhqR+LFWEawiW753SJhn0ngZcv/mPj3mwcHv1SL9ErBqAjm4JGiDetPKYtFwANYY11OyQAAAVdBmwhJ4Q8mUwIr/wArOx5HV2505jRePGgMxptW4PGIHEszV1xGZS+flSkF+aq30AaqO7u6XK9jJsuWXTfYCRQTn1bZfFQ22DbO5DXAxK/TUmbQleCflFzeS6/czxkL4PJ8AwOs2U+oehekgCZC8gZyHHaQSaKbNJ46gTjNsLy84ACQ5uNt11TPuCPqPTuh+schdw9S+/lU/6m+EyaqGZ49wDFPiBFBYXglQQBjyP9k/rqq0xL7SiLjpe4riYg8SFUuUtOzPdWHyvxnI7Ug/0VLPGAAhgMISUnqe01d5QFf36yHpwMAHexjAZFIGQHAFautuMuEw6HzUZVzNdeHYxvEYOGkTo007bLwbuf/nxzrywGOxlRTYJLRdYI0mk0SdN3+LeTv1RIJwv21+e9rT5iFOTCgzeQoekEWXLYz0X8YLq5bVCtijP7/T7w1Ck71j0aqfrEn6wtIAAABNUGbKUnhDyZTAiv/ACcySi7VBgOid6qZNXvhh/JsllHkMLLq0yNbQTqv/Wk2EBoSKICZwFwAD0WRzhvvReCGirep1Fe4bxjm49/UR+OYrXRmHR18T0C83AUVeBk7KvDZmb/eHzuzEN4yfXucr/NWFJl+USVMY4r4UQ9CayrfEY9v6AQ6mzAdLy2UMfFxrRJ99g/Rfl8qx+m4jIZNjlrTaThzJ/3OpVmAliDfxVyg8+CVIlI31IykiwQrXcebgajG+av8XU1SfyAG5ibvwbtdSAxkGBcJWL387V+uTdY56w3KN2vBtoQpVKD2zb3yazIcATZ02upwIytNcM/rpaLCdMb1myWcikE25agzLhDhOS+4zwjYz2DnW6VY0gFBAPsphhsUMnauVVdUVHzCTSdvzEve/H8q4AAAAVdBm0pJ4Q8mUwIr/wAo+x5XKuiN1am7SkJKSMonFZDPU3f5XFcDQSs0FLVq2idfsKwuIkt1mxIq8NgMHpzofTnDHqs/WedvAmhBgL0N5azdQa5MNKG2rJ4IAvGQY/uFm3jKQAKzvhSS01gO1oIfizF817z9IShS4QK2WT0PeFPELqLSpED8eNOpVTR96vmwpk/WBKRVJdTQJzjiCQ5pgEwjtvk7KqoS0+lwXSbvIrXkYm8DignEts3DLNoLHrPjXlQmbIop76JZSyJEtB+91GrLwo6Km5GeebyA2E6qGL3xSkpppej/ruoFprSKrH60UMbrq/SK7eCo+1QFoySPQmqDFsMGiQFqvtld5BXDYdVI4yRaoyN7Y7wi83HRC6eVazuHU9OtIY3xJJApBWq1aJOsYwc38aTC3ee863Aa/4n9Lk4DAtyFYHNZjB5m2e2vk8G2Gny9YFlBAAABQEGba0nhDyZTAiv/ACoZSZQfHxhfQxEqOBQrP+L3DmgvHSJQtB1iVkcLTxm+vagLHBLG91OGnopwrr7gT/loDypIhoRxjcwAAOeg/jN4WBbXzCJtnWGGllUCSdtUZQzKOSp9iM4yX18C6jrY4Sq6R9PUV/lEGNveJR4gw4FMve7110XdEPL1O2VTdHvdqeANyaq0nLdEmtXnrzvdrFlBaUvmaR4EdlkqGkvkZKWJej8Vq+msbKa7JdbxjwZtRufiyGfD/NVqMgSrYRzw9z/a8Zwbr+9+19CxlWD5bCuAEfPmjY6kZJE2L/CQI6+tnCBTXOmWZtZMBoCLGOf7G2uAC3+kFlboh9as5WCkO6+iqXq29dyhKnsHInorRYsPlgxIXyU1Om/Kyhj1DJV0Am9WJK3Dln0zNUH0q6ZTOnZcFD36AAABYkGbjEnhDyZTAiv/ACcwdIOLRFfoGK2ZkKsvgMwG0m0qsY0vMLPSzefc+ebp/aztyF7MlsBz/fBeNtxFBcsKgR4pf65GvdfOMHah0ltZ918sMDmXUEZMeRHy/xpnWpTLeGz6uTs/7MATPmU5BgHbT/DkD8QeaZnFAzidyFCXDz2l/jaKhEdgqipbB2pH0+fQ039r05z9axxEWGmaLQjg6x9+po1o24yhkVO7m03YwWmPyCgy8cOwrvRyJkXJpRN4m8ZBS1zwY80HeN/VyMQQJSMwsTo7R1XMerSFuyx0nz+8qOuhiqykc2ohCCsXia/+kIKbJ5Vs+cbWtvkqBKIDSfU7FhAd3GjcY/xar0EVmi6wWFTugAogR3I7mTrQDdlTAqYgqO7Gn5NMXQVHu2i1zhFSdo9GjMbeGnbkJwsFbQ2XkoKRIDpuW7AewC9AEBt0Ox/Ah6dGXfXO1jl8pEApj2RFmgAAAPlBm61J4Q8mUwIr/wAlR+eW/VZ7bSrmwwMA62G05DZ7p/5FUugsSsQdonUq6abtbU5hjFr+I1lPgoiV5c3CkTQZS+K5zivdo+Ti2P4K90xXANp8dSMAu85uJIOCQn2TXbEnNDifLB+3V84ht5tj4lvTaZx317BcliV8D5v2zZQW8RO1mUbuJEBItst8E7hfE+ZXj7tfDxNZPTvtpFyUv0fH1cTg1pr2VLy0d0zQLiA58dg+GkRvR1/hs2LyifBgHcj6eTWz0vsypVn9iPXRH/unJ6i8cfFL69NO24tQ9QQB+nDFhoP2cRhkAvhHwn56n5PppBD/oxni2f8AAAE9QZvOSeEPJlMCK/8AJjAXVGf+Kj2XNJnFeKC/gr7dJDTC2ngpd4WeAHlg04GuJKnn9hAmiECxxo9qM1IYMRiB85t6gALnlm9sRqGmioyzAm18RJndc9Ah8RlpGzr+44a6ntRaPx0cIwNIWAA8buL2JP00dmfjNqEiAlCa8OdV8FQxjp1vDXsGcAGF3Qbd62KEpkimeI3wH2nuXpbDHm8/ZKOR49s5ifUCkxCoJpfp43aC0lTzh2NXpcfVw6h0QnK8G60R4ZAxOxaJB7c0nn8ixXSU2JVY24EtGMF53nxJnHfzUheewUfBOGYSxeo8oK7oUCqX4rztzDwoc2QywNqQUJUkFrqIN+sb5ecYvX24Zujn+ZzTW6UDAF3R6WdNyJyRAremgC8spSflTqygQNGfHyGkfIEEJJaFo/pBCBkAAAEWQZvvSeEPJlMCK/8AKI41fuekXG59Knbw4Y6YJritsh9VtQgc3QKvVmxrzzo7f4aXn8N74eyP4b2lV1Z2Q+rohxps7EHTkOY9jLdqxI3MXe7je4g2qepz71+hY+jYdX+9LO0kA0Zg3NfyAlIRX7k6c/YHAZNtNaGZgTBMqiPgmEjiJH9Luk7shbgr+srfwiYwBX9rdS3fQNNFwcT8orQC+F60LAY9+GbFo2Sw3Ld4Tw9jq9yJtrY8RtHAdzytyek/mv2+j2TbTvAQKbbCYtdC8E/KtR4V5ZTSScr5Wb63vmbw7UpddEXYvl55pARyyvMxWNSh3Li4GF8Jk5JBi5B5ASQwxCMYpX5hkAMc+d8tl2bT+IEvUTsAAAElQZoQSeEPJlMCK/8AJIAzFZs00JJ0yfm8CZiew4xWdArLklEvBVXo/+ukPLu3XP9HFOfsme3T6BJEKmPPgZw/Lxnraq6Sl2kLVW19YU1qmqgfv+80LkZaWU5gRAH4hqyo3bFYcbuY2SC3IW5Wm69gtYyAXOdbAYSEHA16fvCeRQjHEsxKVndJdrRAlrGHsKgUBQ3Up/ZXIy1vkdFOfKSjpuZnswkuqr8NZI5tJ/dnBSErBTNWPaNwWV7nNomC0EYVGo+geGBhLXzaLw0UAOCYGjiPc3803BDw1GLoLIXjrIFJxwRfBNIAXYZAglu30oYzhpAfRWSprkeULMWYJTlWvbUQ5CNewSZssuDWIRAc3w8AcFaywwn+YSGhtR8VI1OGjYkfBbcAAAD8QZoxSeEPJlMCK/8AJdokjCUETRw/nciVPtaZQSBP/VxAQSITASEzlJBl9Na1r0DJhLOz279+KQLtl/xHZ8vAKc528mTMTqtWs4sFbeVgHWyBpHcHEtgTzjIqEinp/MPuUXF5poo8YLSSMFn9Ozx2FbU5/Kh9A39oN9NHQflVxV1NA6yT/84HHyfMtfdSMS8KTvAEE2lDs14VQayNs5ctjXboQT7xMBf5OLj6thhPvgaDrFB2o/PV9ouK147lruWTP2mkoA9oDIMYW1pcBx4yyV/t9GOPZ3aXneMUb2fFmUCX43BjXfUDMaa4GO2/Ankj3UEQwDxA7ZlNUQK2AAAA4UGaUknhDyZTAiv/ACJHv33I08bkhybYiJ/JiiheW5zMPBu4n5CxGr3frhE7TkLh0vPktM8m/AhaDiJisdk5QXNe/4WmxEDSAyaVi4eUVu0iHT2ly/KNTGqiORqA2oKpTjh84nYbrpXwnGv9SOf/34Z06xN6Yo3t35UZrP8nlcs/63GtnEmnUwVZHBYfPM6bs5M5AeBfAQ/9mIqu7vnEst+5O2wpPjzdItjwGCZ2ApHVjGnYYFomlA9nm6AXnxNIWHIsDgxCk3zx+6QbXipu/CWLG1Wf0WIbt4C0JPVl3TEb0QAAAMlBmnNJ4Q8mUwIr/wAVV64OfTKmlktYOqZHH1W1DhPy/X/6sD4T6hRdzfOgNtTOX2IckRJHshfBQVkJIzns079io6kpJFCcS3VD4zrWCn/dNaGV0kWTpFBRuusfn8F0C0R/EhsQeyTsdZftEkLGb5tq+nrir3vfmeb7rjmWJRXkIrTEKu8pIuAd+4FBGp8ARgGe80Jqpp//s1433HqBFqXsIFJTmU8j/toF9HyueI1Ea4uvsQ6NANGcYCbOAKCmbNiwABMCFaiUTMAAAAPSbW9vdgAAAGxtdmhkAAAAAHwlsIB8JbCAAAAD6AAAAyAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAv10cmFrAAAAXHRraGQAAAAPfCWwgHwlsIAAAAABAAAAAAAAAyAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAY4AAAGGAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAMgAAAAAgABAAAAAAJ1bWRpYQAAACBtZGhkAAAAAHwlsIB8JbCAAAAAGQAAABRVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAACIG1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAeBzdGJsAAAAtHN0c2QAAAAAAAAAAQAAAKRhdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAY4BhgBIAAAASAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGP//AAAAMmF2Y0MBZAAV/+EAGWdkABWs2UGQz6mhAAADAAEAAAMAMg8WLZYBAAZo6+PLIsAAAAAcdXVpZGtoQPJfJE/FujmlG88DI/MAAAAAAAAAGHN0dHMAAAAAAAAAAQAAABQAAAABAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAYY3R0cwAAAAAAAAABAAAAFAAAAAIAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAZHN0c3oAAAAAAAAAAAAAABQAAA05AAACqQAAAl8AAAITAAACiwAAAh8AAAIvAAABiAAAAVsAAAE5AAABWwAAAUQAAAFmAAAA/QAAAUEAAAEaAAABKQAAAQAAAADlAAAAzQAAAGBzdGNvAAAAAAAAABQAAAAsAAANZQAAEA4AABJtAAAUgAAAFwsAABkqAAAbWQAAHOEAAB48AAAfdQAAINAAACIUAAAjegAAJHcAACW4AAAm0gAAJ/sAACj7AAAp4AAAAGF1ZHRhAAAAWW1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAALGlsc3QAAAAkqXRvbwAAABxkYXRhAAAAAQAAAABMYXZmNTIuMTExLjA=\">\n\n\n\n## External sites\n\nYou can even embed an entire page from another site in an iframe; for example this is the Jupyter home page:\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('http://jupyter.org', width='100%', height=350)\n```\n\n\n\n\n\n\n\n\n\n\n## Links to local files\n\nIPython provides builtin display classes for generating links to local files. Create a link to a single file using the `FileLink` object:\n\n\n```python\nfrom IPython.display import FileLink, FileLinks\nFileLink('Using Nbconvert.ipynb')\n```\n\n\n\n\n<a href='Using Nbconvert.ipynb' target='_blank'>Using Nbconvert.ipynb</a><br>\n\n\n\nAlternatively, to generate links to all of the files in a directory, use the `FileLinks` object, passing `'.'` to indicate that we want links generated for the current working directory. Note that if there were other directories under the current directory, `FileLinks` would work in a recursive manner creating links to files in all sub-directories as well.\n\n\n```python\nFileLinks('.')\n```\n\n\n\n\n./<br>\n&nbsp;&nbsp;<a href='./Custom Display Logic.ipynb' target='_blank'>Custom Display Logic.ipynb</a><br>\n&nbsp;&nbsp;<a href='./nbdime.ipynb' target='_blank'>nbdime.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.gitignore' target='_blank'>.gitignore</a><br>\n&nbsp;&nbsp;<a href='./Notebook file format.ipynb' target='_blank'>Notebook file format.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Typesetting Equations.ipynb' target='_blank'>Typesetting Equations.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Notebook Basics.ipynb' target='_blank'>Notebook Basics.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Index.ipynb' target='_blank'>Index.ipynb</a><br>\n&nbsp;&nbsp;<a href='./nbdime-before.ipynb' target='_blank'>nbdime-before.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Updating Displays.ipynb' target='_blank'>Updating Displays.ipynb</a><br>\n&nbsp;&nbsp;<a href='./nbval.ipynb' target='_blank'>nbval.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Widget Events.ipynb' target='_blank'>Widget Events.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Widget List.ipynb' target='_blank'>Widget List.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Beyond Plain Python.ipynb' target='_blank'>Beyond Plain Python.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Using Interact.ipynb' target='_blank'>Using Interact.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Using Nbconvert.ipynb' target='_blank'>Using Nbconvert.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Rich Output.ipynb' target='_blank'>Rich Output.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Widget Basics.ipynb' target='_blank'>Widget Basics.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Nbviewer.ipynb' target='_blank'>Nbviewer.ipynb</a><br>\n&nbsp;&nbsp;<a href='./README.md' target='_blank'>README.md</a><br>\n&nbsp;&nbsp;<a href='./Working With Markdown Cells.ipynb' target='_blank'>Working With Markdown Cells.ipynb</a><br>\n&nbsp;&nbsp;<a href='./nbdime-after.ipynb' target='_blank'>nbdime-after.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Running Code.ipynb' target='_blank'>Running Code.ipynb</a><br>\n./.git/<br>\n&nbsp;&nbsp;<a href='./.git/description' target='_blank'>description</a><br>\n&nbsp;&nbsp;<a href='./.git/ORIG_HEAD' target='_blank'>ORIG_HEAD</a><br>\n&nbsp;&nbsp;<a href='./.git/HEAD' target='_blank'>HEAD</a><br>\n&nbsp;&nbsp;<a href='./.git/packed-refs' target='_blank'>packed-refs</a><br>\n&nbsp;&nbsp;<a href='./.git/config' target='_blank'>config</a><br>\n&nbsp;&nbsp;<a href='./.git/index' target='_blank'>index</a><br>\n./.git/hooks/<br>\n&nbsp;&nbsp;<a href='./.git/hooks/pre-rebase.sample' target='_blank'>pre-rebase.sample</a><br>\n&nbsp;&nbsp;<a href='./.git/hooks/applypatch-msg.sample' target='_blank'>applypatch-msg.sample</a><br>\n&nbsp;&nbsp;<a href='./.git/hooks/pre-receive.sample' target='_blank'>pre-receive.sample</a><br>\n&nbsp;&nbsp;<a href='./.git/hooks/pre-applypatch.sample' target='_blank'>pre-applypatch.sample</a><br>\n&nbsp;&nbsp;<a href='./.git/hooks/update.sample' target='_blank'>update.sample</a><br>\n&nbsp;&nbsp;<a href='./.git/hooks/pre-push.sample' target='_blank'>pre-push.sample</a><br>\n&nbsp;&nbsp;<a href='./.git/hooks/commit-msg.sample' target='_blank'>commit-msg.sample</a><br>\n&nbsp;&nbsp;<a href='./.git/hooks/post-update.sample' target='_blank'>post-update.sample</a><br>\n&nbsp;&nbsp;<a href='./.git/hooks/pre-commit.sample' target='_blank'>pre-commit.sample</a><br>\n&nbsp;&nbsp;<a href='./.git/hooks/prepare-commit-msg.sample' target='_blank'>prepare-commit-msg.sample</a><br>\n./.git/info/<br>\n&nbsp;&nbsp;<a href='./.git/info/exclude' target='_blank'>exclude</a><br>\n./.git/logs/<br>\n&nbsp;&nbsp;<a href='./.git/logs/HEAD' target='_blank'>HEAD</a><br>\n./.git/logs/refs/heads/<br>\n&nbsp;&nbsp;<a href='./.git/logs/refs/heads/master' target='_blank'>master</a><br>\n./.git/logs/refs/remotes/origin/<br>\n&nbsp;&nbsp;<a href='./.git/logs/refs/remotes/origin/HEAD' target='_blank'>HEAD</a><br>\n./.git/objects/pack/<br>\n&nbsp;&nbsp;<a href='./.git/objects/pack/pack-0b2f8f607a9c3801a23b37ad917969d3bc7c490d.pack' target='_blank'>pack-0b2f8f607a9c3801a23b37ad917969d3bc7c490d.pack</a><br>\n&nbsp;&nbsp;<a href='./.git/objects/pack/pack-0b2f8f607a9c3801a23b37ad917969d3bc7c490d.idx' target='_blank'>pack-0b2f8f607a9c3801a23b37ad917969d3bc7c490d.idx</a><br>\n./.git/refs/heads/<br>\n&nbsp;&nbsp;<a href='./.git/refs/heads/master' target='_blank'>master</a><br>\n./.git/refs/remotes/origin/<br>\n&nbsp;&nbsp;<a href='./.git/refs/remotes/origin/HEAD' target='_blank'>HEAD</a><br>\n./.ipynb_checkpoints/<br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Rich Output-checkpoint.ipynb' target='_blank'>Rich Output-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Using Interact-checkpoint.ipynb' target='_blank'>Using Interact-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Index-checkpoint.ipynb' target='_blank'>Index-checkpoint.ipynb</a><br>\n./exercises/<br>\n&nbsp;&nbsp;<a href='./exercises/WordFrequencies.ipynb' target='_blank'>WordFrequencies.ipynb</a><br>\n&nbsp;&nbsp;<a href='./exercises/ImageCompare-Solution.ipynb' target='_blank'>ImageCompare-Solution.ipynb</a><br>\n&nbsp;&nbsp;<a href='./exercises/ImageCompare.ipynb' target='_blank'>ImageCompare.ipynb</a><br>\n&nbsp;&nbsp;<a href='./exercises/fourier_moon_denoise.ipynb' target='_blank'>fourier_moon_denoise.ipynb</a><br>\n&nbsp;&nbsp;<a href='./exercises/InteractBasics.ipynb' target='_blank'>InteractBasics.ipynb</a><br>\n&nbsp;&nbsp;<a href='./exercises/University_of_Sheffield_coat_of_arms_new.png' target='_blank'>University_of_Sheffield_coat_of_arms_new.png</a><br>\n&nbsp;&nbsp;<a href='./exercises/MonteCarloPi-solution.ipynb' target='_blank'>MonteCarloPi-solution.ipynb</a><br>\n&nbsp;&nbsp;<a href='./exercises/Wallis-Pi-solution.ipynb' target='_blank'>Wallis-Pi-solution.ipynb</a><br>\n&nbsp;&nbsp;<a href='./exercises/University_of_Sheffield_coat_of_arms_old.png' target='_blank'>University_of_Sheffield_coat_of_arms_old.png</a><br>\n&nbsp;&nbsp;<a href='./exercises/Wallis-Pi.ipynb' target='_blank'>Wallis-Pi.ipynb</a><br>\n&nbsp;&nbsp;<a href='./exercises/circle_integrate.png' target='_blank'>circle_integrate.png</a><br>\n&nbsp;&nbsp;<a href='./exercises/fourier_moon_denoise-solution.ipynb' target='_blank'>fourier_moon_denoise-solution.ipynb</a><br>\n&nbsp;&nbsp;<a href='./exercises/WordFrequencies-solution.ipynb' target='_blank'>WordFrequencies-solution.ipynb</a><br>\n&nbsp;&nbsp;<a href='./exercises/MonteCarloPi.ipynb' target='_blank'>MonteCarloPi.ipynb</a><br>\n&nbsp;&nbsp;<a href='./exercises/InteractBasics-Solution.ipynb' target='_blank'>InteractBasics-Solution.ipynb</a><br>\n&nbsp;&nbsp;<a href='./exercises/circle_integrate.svg' target='_blank'>circle_integrate.svg</a><br>\n./exercises/.ipynb_checkpoints/<br>\n&nbsp;&nbsp;<a href='./exercises/.ipynb_checkpoints/Wallis-Pi-checkpoint.ipynb' target='_blank'>Wallis-Pi-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./exercises/.ipynb_checkpoints/MonteCarloPi-solution-checkpoint.ipynb' target='_blank'>MonteCarloPi-solution-checkpoint.ipynb</a><br>\n./exercises/data/<br>\n&nbsp;&nbsp;<a href='./exercises/data/moon_denoise.png' target='_blank'>moon_denoise.png</a><br>\n&nbsp;&nbsp;<a href='./exercises/data/moonlanding.png' target='_blank'>moonlanding.png</a><br>\n&nbsp;&nbsp;<a href='./exercises/data/HISTORY.gz' target='_blank'>HISTORY.gz</a><br>\n./images/<br>\n&nbsp;&nbsp;<a href='./images/nbviewer_download_link.png' target='_blank'>nbviewer_download_link.png</a><br>\n&nbsp;&nbsp;<a href='./images/WidgetModelView.graffle' target='_blank'>WidgetModelView.graffle</a><br>\n&nbsp;&nbsp;<a href='./images/nbconvert_arch.png' target='_blank'>nbconvert_arch.png</a><br>\n&nbsp;&nbsp;<a href='./images/nbconvert_file_menu.png' target='_blank'>nbconvert_file_menu.png</a><br>\n&nbsp;&nbsp;<a href='./images/nbval_cell_tag.png' target='_blank'>nbval_cell_tag.png</a><br>\n&nbsp;&nbsp;<a href='./images/dashboard_files_tab.png' target='_blank'>dashboard_files_tab.png</a><br>\n&nbsp;&nbsp;<a href='./images/ipython_logo.png' target='_blank'>ipython_logo.png</a><br>\n&nbsp;&nbsp;<a href='./images/dashboard_files_tab_new.png' target='_blank'>dashboard_files_tab_new.png</a><br>\n&nbsp;&nbsp;<a href='./images/python_logo.svg' target='_blank'>python_logo.svg</a><br>\n&nbsp;&nbsp;<a href='./images/animation.m4v' target='_blank'>animation.m4v</a><br>\n&nbsp;&nbsp;<a href='./images/command_mode.png' target='_blank'>command_mode.png</a><br>\n&nbsp;&nbsp;<a href='./images/jupyter_logo.png' target='_blank'>jupyter_logo.png</a><br>\n&nbsp;&nbsp;<a href='./images/edit_mode.png' target='_blank'>edit_mode.png</a><br>\n&nbsp;&nbsp;<a href='./images/WidgetModelView.png' target='_blank'>WidgetModelView.png</a><br>\n&nbsp;&nbsp;<a href='./images/menubar_toolbar.png' target='_blank'>menubar_toolbar.png</a><br>\n&nbsp;&nbsp;<a href='./images/dashboard_files_tab_btns.png' target='_blank'>dashboard_files_tab_btns.png</a><br>\n&nbsp;&nbsp;<a href='./images/dashboard_running_tab.png' target='_blank'>dashboard_running_tab.png</a><br>\n&nbsp;&nbsp;<a href='./images/dashboard_files_tab_run.png' target='_blank'>dashboard_files_tab_run.png</a><br>\n&nbsp;&nbsp;<a href='./images/FrontendKernel.png' target='_blank'>FrontendKernel.png</a><br>\n./nbconvert_templates/<br>\n&nbsp;&nbsp;<a href='./nbconvert_templates/Nbconvert templates.ipynb' target='_blank'>Nbconvert templates.ipynb</a><br>\n&nbsp;&nbsp;<a href='./nbconvert_templates/makeitpop.tpl' target='_blank'>makeitpop.tpl</a><br>\n&nbsp;&nbsp;<a href='./nbconvert_templates/Stock display.ipynb' target='_blank'>Stock display.ipynb</a><br>\n&nbsp;&nbsp;<a href='./nbconvert_templates/nbconvert_template_structure.html' target='_blank'>nbconvert_template_structure.html</a><br>\n&nbsp;&nbsp;<a href='./nbconvert_templates/foldcode.tpl' target='_blank'>foldcode.tpl</a><br>\n&nbsp;&nbsp;<a href='./nbconvert_templates/README.md' target='_blank'>README.md</a><br>\n./nbconvert_templates/solutions/<br>\n&nbsp;&nbsp;<a href='./nbconvert_templates/solutions/hidecode.tplx' target='_blank'>hidecode.tplx</a><br>\n&nbsp;&nbsp;<a href='./nbconvert_templates/solutions/hidecode_selective.tplx' target='_blank'>hidecode_selective.tplx</a><br>\n\n\n\n## Rich output and security\n\nThe IPython Notebook allows arbitrary code execution in both the IPython kernel and in the browser, though HTML and JavaScript output. More importantly, because IPython has a JavaScript API for running code in the browser, HTML and JavaScript output can actually trigger code to be run in the kernel. This poses a significant security risk as it would allow IPython Notebooks to execute arbitrary code on your computers.\n\nTo protect against these risks, the IPython Notebook has a security model that specifies how dangerous output is handled. Here is a short summary:\n\n* When you run code in the Notebook, all rich output is displayed.\n* When you open a notebook, rich output is only displayed if it doesn't contain security vulberabilities, ...\n* ... or if you have trusted a notebook, all rich output will run upon opening it.\n\nA full description of the IPython security model can be found on [this page](http://ipython.org/ipython-doc/dev/notebook/security.html).\n\n## Rich output and nbviewer\n\nMuch of the power of the Notebook is that it enables users to share notebooks with each other using http://nbviewer.ipython.org, without installing IPython locally. As of IPython 2.0, notebooks rendered on nbviewer will display all output, including HTML and JavaScript. Furthermore, to provide a consistent JavaScript environment on the live Notebook and nbviewer, the following JavaScript libraries are loaded onto the nbviewer page, *before* the notebook and its output is displayed:\n\n* [jQuery](http://jquery.com/)\n* [RequireJS](http://requirejs.org/)\n\nLibraries such as [mpld3](http://mpld3.github.io/) use these capabilities to generate interactive visualizations that work on nbviewer.\n", "meta": {"hexsha": "d63b9e8f23040732a58c00ffbbe34277dea6990b", "size": 384298, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "intro_python/python_tutorials/jupyter-notebook_intro/Rich Output.ipynb", "max_stars_repo_name": "cgentemann/tutorials", "max_stars_repo_head_hexsha": "04f04ed43f6e35d70c9037e54624b5b476ed9666", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "intro_python/python_tutorials/jupyter-notebook_intro/Rich Output.ipynb", "max_issues_repo_name": "cgentemann/tutorials", "max_issues_repo_head_hexsha": "04f04ed43f6e35d70c9037e54624b5b476ed9666", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "intro_python/python_tutorials/jupyter-notebook_intro/Rich Output.ipynb", "max_forks_repo_name": "cgentemann/tutorials", "max_forks_repo_head_hexsha": "04f04ed43f6e35d70c9037e54624b5b476ed9666", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 254.501986755, "max_line_length": 172781, "alphanum_fraction": 0.9104158752, "converted": true, "num_tokens": 64283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16026602430611822, "lm_q2_score": 0.10521054652278744, "lm_q1q2_score": 0.016861676006281034}}
{"text": "# Spice Up Thy Jupyter Notebooks With mypy\n\nI use [Jupyter](http://jupyter.org/) notebooks all the time. I use them to author the content for articles like the one you're reading. I use them to explore data. And I use them whenever I want to prototype standalone modules or learn new programming concepts, since notebooks allow us to quickly iterate on new ideas and provide powerful ways introspect, profile, and debug code - and more.\n\nI've also recently become interested in Python's new typing module and mypy, and I wanted to be able to use them seamlessly in the context of my Jupyter notebooks.\n\nBefore we continue, I should mention that Jupyter is an evolution of the original IPython project. I bring this up because I'm going to reference the documentation for IPython, which can be thought of as the the code that enables Python to work with Jupyter. Think of Jupyter as the tooling that allows for us to do all the fancy code editing and visualization browser, and IPython as the compatibility layer between Jupyter and Python. This is a bit simplistic, but hopefully avoids confusion for anyone who isn't intimately familiar with both projects and the genesis of the Jupyter project.\n\nJupyter has a concept of cell \"magics\" which allow us to perform helpful functions in the context of a Jupyter shell. For example, when using IPython, the `%pastebin` magic allows us to easily upload bits of code to Github's Gist pastebin, `%pdoc [object]` prints the docstring for a particular object, and `%%latex` renders a block of text as latex.\n\nMagics that start with  '%' apply only to the line that it is written on, while\nmagics that start with '%%' apply to a block of code proceeding that line.\n\nJupyter allows us to write our own custom magics, apart from the built-in magics provided. Detailed documentation on how to do that can be found [here](http://ipython.readthedocs.io/en/stable/config/custommagics.html).\n\nSince the custom magics you use depend on how you have IPython configured and what profile you're using, I'm providing the following code in the form of a gist, since distributing it as a package would be finicky as the package would need to attempt to figure out your IPython configuration, a task which seems best left to you, the human.\n\nI'm going to assume that you have Jupyter installed and that you have at least a default profile created. If not `pip install -U jupyter` will install Jupyter and `ipython profile create` will create a default profile for you if you don't yet have one. This will allow you to use custom magics and configure the way IPython works in various other ways.\n\nFor example, my IPython configuration for my default profile, 'ipython_config.py' has the following lines\n\n    c.TerminalInteractiveShell.ast_node_interactivity = 'all'\n    c.InteractiveShell.ast_node_interactivity = 'all'\n    \nwhich tells IPython to print the the repr for any object which has it's own line. \n\nFor example:\n\n\n```python\nfoo = 'bar'\nbar = 'baz'\n\nfoo\n\nbar # normally, only this object is printed\n```\n\n\n\n\n    'bar'\n\n\n\n\n\n\n    'baz'\n\n\n\nThe configuration for your current IPython profile can be found using `ipython locate profile`\n\nI wanted my magic to do 4 things, primarily.\n\n1. Run the block of code through mypy and print its output\n2. Allow me to alter mypy's behavior, as with the mypy cli\n2. Not conflict with the normal behavior of the block of code\n3. Run the block of code in the context of my current profile\n\nThough the code it took to do this is really straightforward, it took some digging around in the Jupyter and IPython docs to get it to work as I wanted. Hopefully you find it useful and elucidating.\n\nWithout further ado, {{<gist knowsuchagency f7b2203dd613756a45f816d6809f01a6 >}}\n\n\n```python\n%%typecheck --ignore-missing-imports\n\nfrom sympy import sympify, init_printing\ninit_printing()\n\ninteger: int\n    \ninteger = \"mypy won't like this\"\n\nsympify('(e**3)**(1/2)')\n\n\"Notice the previous line was also printed out\"\n```\n\n    <string>:8: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n    \n\n\n\n\n\n$$\\sqrt{e^{3}}$$\n\n\n\n\n\n\n    'Notice the previous line was also printed out'\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "d33b120133f39f4e4602f8efc346bec412ab4537", "size": 6366, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/spice-up-thy-jupyter-notebooks-with-mypy.ipynb", "max_stars_repo_name": "knowsuchagency/knowsuchagency.github.io.old", "max_stars_repo_head_hexsha": "2f7b7c9d4b94120bbd427a14b66ad5dfb45c4e28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/spice-up-thy-jupyter-notebooks-with-mypy.ipynb", "max_issues_repo_name": "knowsuchagency/knowsuchagency.github.io.old", "max_issues_repo_head_hexsha": "2f7b7c9d4b94120bbd427a14b66ad5dfb45c4e28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-12-29T09:09:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-29T09:09:06.000Z", "max_forks_repo_path": "notebooks/spice-up-thy-jupyter-notebooks-with-mypy.ipynb", "max_forks_repo_name": "knowsuchagency/knowsuchagency.github.io.old", "max_forks_repo_head_hexsha": "2f7b7c9d4b94120bbd427a14b66ad5dfb45c4e28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 6366.0, "max_line_length": 6366, "alphanum_fraction": 0.705466541, "converted": true, "num_tokens": 975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1968262036430985, "lm_q2_score": 0.08509903978628845, "lm_q1q2_score": 0.016749720934808154}}
{"text": "```python\nfrom sympy.matrices import Matrix \nimport sympy as sp\nimport numpy as np\nfrom Exercise import Exercise, MarkdownBlock\n\nfrom process_latex import process_sympy \n\ntry:\n    from config import URL, TOKEN\nexcept:\n    None\n\n# TODO: replace with supplied strings\nExercise.URL = URL\nExercise.TOKEN = TOKEN\n```\n\n\n```python\ndef hello2():\n    return \"2\"\nx = None\n\ns =\"\"\"\ndef hello(name: str):\n    print(x)\n    return f\"Hello\"\nprint(hello(\"x\"))\n\"\"\"\n\n# import inspect\n# lines = inspect.getsource(hello)\n# print(lines)\n# exec?\n\n# Note: if any helper functions are used, these should be available in the serverless function file as well!\n\nexec(s)\n```\n\n    None\n    Hello\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "2e2b2d327fe4cbf0116ddfbd9d2cc67e328f28cf", "size": 2078, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "user_defined_answer_function.ipynb", "max_stars_repo_name": "rkeulemans/exercise_public", "max_stars_repo_head_hexsha": "5f8020198b8b234169eea4d5e08c98344438de5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "user_defined_answer_function.ipynb", "max_issues_repo_name": "rkeulemans/exercise_public", "max_issues_repo_head_hexsha": "5f8020198b8b234169eea4d5e08c98344438de5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "user_defined_answer_function.ipynb", "max_forks_repo_name": "rkeulemans/exercise_public", "max_forks_repo_head_hexsha": "5f8020198b8b234169eea4d5e08c98344438de5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.1747572816, "max_line_length": 117, "alphanum_fraction": 0.5019249278, "converted": true, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.05500528442066434, "lm_q1q2_score": 0.016723898807270123}}
{"text": "Dependencies:\n - whoosh\n - yattag\n - hurry.filesize\n\n\n```python\nimport nbformat\n```\n\nnbformat doc: http://nbformat.readthedocs.org/en/latest/api.html\n\n\n```python\nfrom whoosh.index import create_in\nfrom whoosh.fields import *\nfrom whoosh.qparser import QueryParser\n```\n\nwhoosh doc: http://whoosh.readthedocs.org/en/latest/quickstart.html\n\n\n```python\nimport os, fnmatch\nimport stat\nimport datetime\n```\n\n\n```python\nschema = Schema(\n    title=TEXT(stored=True),\n    markdown=TEXT(stored=True),\n    code=TEXT(stored=True),\n    path=ID(stored=True),\n    user=KEYWORD(stored=True),\n    tags=KEYWORD(stored=True),\n    modified=DATETIME(stored=True),\n    accessed=DATETIME(stored=True),\n    size=NUMERIC(stored=True)\n)\n```\n\n\n```python\nix = create_in(\"indexdir\", schema)\nwriter = ix.writer()\n```\n\n\n```python\ndef get_file_info(path):\n    info = dict()\n    try:\n        st = os.stat(path)\n        info['uid'] = st.st_uid\n        info['gid'] = st.st_gid\n        info['size'] = st.st_size\n        info['atime'] = st.st_atime\n        info['mtime'] = st.st_mtime\n        info['ctime'] = st.st_ctime\n    except IOError:\n        print(\"Failed to get information about\", file)\n    else:\n        try:\n            import pwd # not available on all platforms\n            userinfo = pwd.getpwuid(st[stat.ST_UID])\n        except (ImportError, KeyError):\n            print(\"Failed to get the owner name for\", file)\n        else:\n            info['owner'] = userinfo.pw_name\n            info['complete_owner'] = userinfo.pw_gecos\n    return info\n```\n\n\n```python\ndef add_notebook(writer, path):\n    info = get_file_info(path)\n    note = nbformat.read(path, nbformat.NO_CONVERT)\n    \n    markdown = ''\n    code = ''\n    tags = ''\n\n    for cell in note['cells']:\n        if cell['cell_type'] == 'markdown':\n            markdown += cell['source']\n            markdown += '\\n\\n'\n        if cell['cell_type'] == 'code':\n            code += cell['source']\n            code += '\\n\\n'\n    \n    writer.add_document(\n        title=''.join(path.split('/')[-1].split('.')[:-1]),\n        path=path,\n        markdown=markdown,\n        code=code,\n        user=info['owner'],\n        tags=tags,\n        modified=datetime.datetime.fromtimestamp(info['mtime']),\n        accessed=datetime.datetime.fromtimestamp(info['atime']),\n        size=info['size']\n    )\n```\n\n\n```python\ndef find(path, pattern, antipattern):\n    result = []\n    for root, dirs, files in os.walk(path):\n        for name in files:\n            if fnmatch.fnmatch(name, pattern) and not fnmatch.fnmatch(name, antipattern):\n                result.append(os.path.join(root, name))\n    return result\nfile_path = find('/Users/lukas/Projects', '*.ipynb', '*.ipynb_checkpoints')\n```\n\n\n```python\nfor path in file_path:\n    add_notebook(writer, path)\n```\n\n\n```python\nwriter.commit()\n```\n\n\n```python\nfrom IPython.html import widgets\nfrom IPython.display import display, clear_output\nfrom IPython.core.display import HTML\nfrom yattag import Doc\nfrom hurry.filesize import size\n```\n\n\n```python\ndisplay(HTML('''\n<style>\n.rendered_html tr, .rendered_html th, .rendered_html td {\nborder-collapse: collapse;\nmargin: 1em 2em;\n}\n.rendered_html table {\nmargin-left: auto;\nmargin-right: auto;\nborder: none;\nborder-collapse: collapse;\n}\n</style>\n'''\n))\n```\n\n\n\n<style>\n.rendered_html tr, .rendered_html th, .rendered_html td {\nborder-collapse: collapse;\nmargin: 1em 2em;\n}\n.rendered_html table {\nmargin-left: auto;\nmargin-right: auto;\nborder: none;\nborder-collapse: collapse;\n}\n</style>\n\n\n\nwidget discussion: http://stackoverflow.com/questions/26352555/how-does-one-get-widget-values-with-a-button-in-ipython\n\n\n```python\ndef format_output(results):\n    doc, tag, text = Doc().tagtext()\n    doc.text('Number of hits: {}\\n'.format(len(results)))\n    with tag('table', klass='table table-striped'):\n        with tag('thead'):\n            with tag('tr'):\n                with tag('th'):\n                    doc.text('#')\n                with tag('th'):\n                    doc.text('Title')\n        with tag('tbody'):\n            for idx, result in enumerate(results):\n                with tag('tr'):\n                    with tag('td'):\n                        doc.text(idx)\n                    with tag('td'):\n                        with tag('table'):\n                            with tag('tbody'):\n                                with tag('tr'):\n                                    with tag('td', klass='col-md-6'):\n                                        with tag('a', href=result['path']):\n                                            doc.text(result['title'])\n                                    with tag('td', klass='col-md-6'):\n                                        doc.text(' asdf({})'.format(result['user']))\n    display(HTML(doc.getvalue()))\n```\n\n\n```python\nimport whoosh.highlight as highlight\nclass BracketFormatter(highlight.Formatter):\n    def format_token(self, text, token, replace=False):\n        # Use the get_text function to get the text corresponding to the\n        # token\n        tokentext = highlight.get_text(text, token, replace=True)\n\n        # Return the text as you want it to appear in the highlighted\n        # string\n        return \"<mark>%s</mark>\" % tokentext\n```\n\n\n```python\ndef format_output(results):\n    doc, tag, text = Doc().tagtext()\n    doc.text('Number of hits: {}\\n'.format(len(results)))\n    for idx, result in enumerate(results):\n        with tag('div', klass='row'):\n            with tag('div', klass='col-md-1'):\n                doc.text(idx)\n            with tag('div', klass='col-md-11'):\n                with tag('strong'):\n                    doc.text(result['title'])\n        with tag('div', klass='row'):\n            with tag('div', klass='col-md-1'):\n                pass\n            with tag('div', klass='col-md-11'):\n                with tag('a'):\n                    doc.text(result['path'])\n        with tag('div', klass='row'):\n            with tag('div', klass='col-md-1'):\n                pass\n            with tag('div', klass='col-md-2'):\n                doc.text('User: {}'.format(result['user']))\n            with tag('div', klass='col-md-2'):\n                doc.text('Size: {}B'.format(size(result['size'])))\n            with tag('div', klass='col-md-7'):\n                doc.text('Modified: {}'.format(result['modified']))\n        with tag('div', klass='row'):\n            with tag('div', klass='col-md-1'):\n                pass\n            with tag('div', klass='col-md-11'):\n                doc.asis(result.highlights('markdown'))\n        with tag('br'):\n            pass\n    display(HTML(doc.getvalue()))\n```\n\n\n```python\ndef search(query_string, field='markdown'):\n    limit = 200\n    with ix.searcher() as searcher:\n        query = QueryParser(field, ix.schema).parse(query_string)\n        results = searcher.search(query, limit=limit)\n        brf = BracketFormatter()\n        results.formatter = brf\n        results.fragmenter.maxchars = 300\n        results.fragmenter.surround = 50\n        format_output(results)\n```\n\n\n```python\ndef button_callback(btn):\n    clear_output()\n    search(query_string=container.children[0].value)\n\nbutton = widgets.ButtonWidget(description=\"Click me!\")\nbutton.on_click(button_callback)\ntext_box = widgets.Text(value='exa*')\ncontainer = widgets.HBox(children=(text_box, button))\ndisplay(container)\n```\n\n\nNumber of hits: 7\n<div class=\"row\"><div class=\"col-md-1\">0</div><div class=\"col-md-11\"><strong>2015-09-01 Complex derivatives</strong></div></div><div class=\"row\"><div class=\"col-md-1\"></div><div class=\"col-md-11\"><a>/Users/lukas/Projects/notes/2015-09-01 Complex derivatives.ipynb</a></div></div><div class=\"row\"><div class=\"col-md-1\"></div><div class=\"col-md-2\">User: lukas</div><div class=\"col-md-2\">Size: 4KB</div><div class=\"col-md-7\">Modified: 2015-09-02 08:32:30</div></div><div class=\"row\"><div class=\"col-md-1\"></div><div class=\"col-md-11\">are satisfied, the above equations yield an <mark>exact</mark> derviative.\n\nIf not, the above equations contradict each...when far away from that critical point?\n\n## Simple <mark>example</mark>\n\n\\begin{align}\nf(z) &= |z|^2 &\nu(x, y) &= x^2 + y^2 &\nv(x, y) &= 0 &\n\\frac{\\partial u}{\\partial...magnitudes and to compare phases. These are <mark>examples</mark>:\n - Exponential distribution to compare magnitudes</div></div><br></br><div class=\"row\"><div class=\"col-md-1\">1</div><div class=\"col-md-11\"><strong>2015-10-01 First complex Chainer tests</strong></div></div><div class=\"row\"><div class=\"col-md-1\"></div><div class=\"col-md-11\"><a>/Users/lukas/Projects/notes/2015-10-01 First complex Chainer tests.ipynb</a></div></div><div class=\"row\"><div class=\"col-md-1\"></div><div class=\"col-md-2\">User: lukas</div><div class=\"col-md-2\">Size: 105KB</div><div class=\"col-md-7\">Modified: 2015-10-02 10:44:27</div></div><div class=\"row\"><div class=\"col-md-1\"></div><div class=\"col-md-11\"><mark>example</mark> functions to generate training data\n\n# Define network architecture\n\n# Training\n\nUntil now, just works with vanilla stochastic</div></div><br></br><div class=\"row\"><div class=\"col-md-1\">2</div><div class=\"col-md-11\"><strong>2015-09-01 Complex derivatives-checkpoint</strong></div></div><div class=\"row\"><div class=\"col-md-1\"></div><div class=\"col-md-11\"><a>/Users/lukas/Projects/notes/.ipynb_checkpoints/2015-09-01 Complex derivatives-checkpoint.ipynb</a></div></div><div class=\"row\"><div class=\"col-md-1\"></div><div class=\"col-md-2\">User: lukas</div><div class=\"col-md-2\">Size: 4KB</div><div class=\"col-md-7\">Modified: 2015-09-02 08:32:30</div></div><div class=\"row\"><div class=\"col-md-1\"></div><div class=\"col-md-11\">are satisfied, the above equations yield an <mark>exact</mark> derviative.\n\nIf not, the above equations contradict each...when far away from that critical point?\n\n## Simple <mark>example</mark>\n\n\\begin{align}\nf(z) &= |z|^2 &\nu(x, y) &= x^2 + y^2 &\nv(x, y) &= 0 &\n\\frac{\\partial u}{\\partial...magnitudes and to compare phases. These are <mark>examples</mark>:\n - Exponential distribution to compare magnitudes</div></div><br></br><div class=\"row\"><div class=\"col-md-1\">3</div><div class=\"col-md-11\"><strong>2015-10-01 First complex Chainer tests-checkpoint</strong></div></div><div class=\"row\"><div class=\"col-md-1\"></div><div class=\"col-md-11\"><a>/Users/lukas/Projects/notes/.ipynb_checkpoints/2015-10-01 First complex Chainer tests-checkpoint.ipynb</a></div></div><div class=\"row\"><div class=\"col-md-1\"></div><div class=\"col-md-2\">User: lukas</div><div class=\"col-md-2\">Size: 105KB</div><div class=\"col-md-7\">Modified: 2015-10-02 10:44:27</div></div><div class=\"row\"><div class=\"col-md-1\"></div><div class=\"col-md-11\"><mark>example</mark> functions to generate training data\n\n# Define network architecture\n\n# Training\n\nUntil now, just works with vanilla stochastic</div></div><br></br><div class=\"row\"><div class=\"col-md-1\">4</div><div class=\"col-md-11\"><strong>Einsum</strong></div></div><div class=\"row\"><div class=\"col-md-1\"></div><div class=\"col-md-11\"><a>/Users/lukas/Projects/nt_notebooks/basics/Einsum.ipynb</a></div></div><div class=\"row\"><div class=\"col-md-1\"></div><div class=\"col-md-2\">User: lukas</div><div class=\"col-md-2\">Size: 11KB</div><div class=\"col-md-7\">Modified: 2015-10-02 10:43:56</div></div><div class=\"row\"><div class=\"col-md-1\"></div><div class=\"col-md-11\">Einsum <mark>examples</mark> \n\n- There are some <mark>examples</mark> here: http://docs.scipy.org/doc/numpy/reference/generated</div></div><br></br><div class=\"row\"><div class=\"col-md-1\">5</div><div class=\"col-md-11\"><strong>MNIST_Latent_Autoencoder</strong></div></div><div class=\"row\"><div class=\"col-md-1\"></div><div class=\"col-md-11\"><a>/Users/lukas/Projects/nt_notebooks/toolbox_examples/nn/MNIST_Latent_Autoencoder.ipynb</a></div></div><div class=\"row\"><div class=\"col-md-1\"></div><div class=\"col-md-2\">User: lukas</div><div class=\"col-md-2\">Size: 604KB</div><div class=\"col-md-7\">Modified: 2015-10-02 10:43:56</div></div><div class=\"row\"><div class=\"col-md-1\"></div><div class=\"col-md-11\">factors of variation in deep networks\n\nThis is an <mark>example</mark> of how to implement the autoencoder architecture from...and output data\n- plot cost evolution and one test <mark>example</mark>\n\n## Define function to plot input images, output images</div></div><br></br><div class=\"row\"><div class=\"col-md-1\">6</div><div class=\"col-md-11\"><strong>MNIST_Latent_Autoencoder</strong></div></div><div class=\"row\"><div class=\"col-md-1\"></div><div class=\"col-md-11\"><a>/Users/lukas/Projects/toolbox/nt/nn/examples/MNIST_Latent_Autoencoder.ipynb</a></div></div><div class=\"row\"><div class=\"col-md-1\"></div><div class=\"col-md-2\">User: lukas</div><div class=\"col-md-2\">Size: 18KB</div><div class=\"col-md-7\">Modified: 2015-08-20 08:46:05</div></div><div class=\"row\"><div class=\"col-md-1\"></div><div class=\"col-md-11\">factors of variation in deep networks\n\nThis is an <mark>example</mark> of how to implement the autoencoder architecture from...and output data\n- plot cost evolution and one test <mark>example</mark>\n\n## Define function to plot input images, output images</div></div><br></br>\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "fd08bf39a96de7f651ed0631711a346b76b8bf9e", "size": 19141, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "index.ipynb", "max_stars_repo_name": "LukasDrude/jupyter_search", "max_stars_repo_head_hexsha": "1b45fefbe5f55310c1155cc10b36e9fa4858e90e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "index.ipynb", "max_issues_repo_name": "LukasDrude/jupyter_search", "max_issues_repo_head_hexsha": "1b45fefbe5f55310c1155cc10b36e9fa4858e90e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "index.ipynb", "max_forks_repo_name": "LukasDrude/jupyter_search", "max_forks_repo_head_hexsha": "1b45fefbe5f55310c1155cc10b36e9fa4858e90e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.605108055, "max_line_length": 756, "alphanum_fraction": 0.5212893788, "converted": true, "num_tokens": 3584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19930800266002902, "lm_q2_score": 0.08269734493579811, "lm_q1q2_score": 0.016482242644441387}}
{"text": "## Initial setup\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```python\nimport tensorflow as tf\nprint(tf.__version__)\nimport torch\nprint(torch.__version__)\nimport matplotlib\nprint(matplotlib.__version__)\n```\n\n    2.8.0\n    1.10.0+cu111\n    3.2.2\n\n\n\n```python\n!nvidia-smi\n```\n\n    Fri Jan 21 19:41:32 2022       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 495.46       Driver Version: 460.32.03    CUDA Version: 11.2     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   34C    P8     9W /  70W |      0MiB / 15109MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    |  No running processes found                                                 |\n    +-----------------------------------------------------------------------------+\n\n\n\n```python\n# Other imports\n! pip install tensorflow_addons\n! pip install tensorflow_io\n\nimport os\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import *\nfrom keras.callbacks import Callback, EarlyStopping, ModelCheckpoint\nfrom tensorflow.keras.applications.resnet50 import preprocess_input\nfrom tensorflow.keras.preprocessing.image import load_img\n\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfrom matplotlib.offsetbox import OffsetImage, AnnotationBbox\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter, AutoMinorLocator\nfrom imutils import paths\nfrom tqdm import tqdm\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nimport tensorflow_datasets as tfds\nimport tensorflow_io as tfio\nimport tensorflow_hub as hub\nimport numpy as np\nimport cv2\nimport pandas as pd\nimport seaborn as sns\nfrom scipy.stats import mannwhitneyu\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.cluster import KMeans\nimport sklearn.manifold\nfrom sklearn.metrics.pairwise import cosine_similarity as cos\nfrom sympy.utilities.iterables import multiset_permutations\nfrom sklearn.metrics import accuracy_score, f1_score,precision_score, recall_score, roc_auc_score, confusion_matrix\nfrom sklearn.model_selection import *\nfrom sklearn.preprocessing import StandardScaler\nfrom IPython.display import Image, display\n\n\nimport zipfile\nimport concurrent.futures\n\n# Random seed fix\nrandom_seed = 42\ntf.random.set_seed(random_seed)\nnp.random.seed(random_seed)\n```\n\n    Collecting tensorflow_addons\n      Downloading tensorflow_addons-0.16.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.1 MB 6.4 MB/s \n    \u001b[?25hRequirement already satisfied: typeguard>=2.7 in /usr/local/lib/python3.7/dist-packages (from tensorflow_addons) (2.7.1)\n    Installing collected packages: tensorflow-addons\n    Successfully installed tensorflow-addons-0.16.1\n    Collecting tensorflow_io\n      Downloading tensorflow_io-0.24.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (23.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 23.4 MB 1.8 MB/s \n    \u001b[?25hRequirement already satisfied: tensorflow-io-gcs-filesystem==0.24.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow_io) (0.24.0)\n    Installing collected packages: tensorflow-io\n    Successfully installed tensorflow-io-0.24.0\n\n\n## Dataset gathering and preparation\n\n\n```python\n%cd /content/drive/MyDrive/nanowire-morphology-classification-project\n```\n\n\n```python\ntraining_batch_size = 4\n\nBATCH_SIZE = training_batch_size\n\nimageSize = 224\n\ncategory_names = ['bundle', 'dispersed', 'network', 'singular']\ncolor_method = ['C0', 'C1', 'C2', 'C3', 'C4']\ncolor = ['black', 'magenta', 'cyan', 'yellow']\nmarker = ['o', 's', '<', '>', '^']\nseaborn_palette = sns.color_palette(\"colorblind\")\n```\n\n\n```python\n# Image preprocessing utils\n@tf.function\ndef parse_images(image_path):\n    image_string = tf.io.read_file(image_path)\n    image = tf.image.decode_jpeg(image_string, channels=3)\n    # image = tfio.experimental.image.decode_tiff(image_string)[:, :, :3]   # in the doc, it transforms tiff to 4 channels, with additional channel of opacity which is not needed.\n    image = tf.image.convert_image_dtype(image, tf.float32)\n    image = tf.image.resize(image, size=[imageSize, imageSize])\n\n    return image\n```\n\n## clustering and percolation analysis of the segmentation ground truth\n\n\n```python\nnp.random.seed(random_seed)\npeptide_morph_seglabel_train_path = \"/content/drive/MyDrive/TEM image datasets/2022-nanowire-morphology\"\npeptide_morph_images_train_seglabel = list(paths.list_files(basePath=peptide_morph_seglabel_train_path, validExts='png'))\npeptide_morph_images_train_seglabel = np.random.choice(np.array(peptide_morph_images_train_seglabel), len(peptide_morph_images_train_seglabel), replace=False)\nprint(len(peptide_morph_images_train_seglabel))\n```\n\n    200\n\n\n\n```python\ndef generate_ground_truth_images(image, resolution):\n  image_bool = np.ones((resolution, resolution))\n  for i in range(image.shape[0]):\n    for j in range(image.shape[1]):\n      if image[i, j, 1] == image[i, j, 2]:\n        image_bool[i, j] = 0            # background is black with code of 0\n      else: \n        image_bool[i, j] = 1            # nanowire is white with code of 1\n  return image_bool\n```\n\n\n```python\nsegmentation_class_labels = []\nfor i in range(peptide_morph_images_train_seglabel.shape[0]):\n  seg_class_label = peptide_morph_images_train_seglabel[i].split(\"/\")[-2]\n  segmentation_class_labels.append(seg_class_label)\nle = LabelEncoder()\npeptide_morph_train_seg_enc = le.fit_transform(segmentation_class_labels)\n```\n\n\n```python\n# image_mask = np.zeros((len(peptide_morph_images_train_seglabel), imageSize, imageSize))\nimages_no_annotation_directory = []\nimages_no_annotation = np.zeros((len(peptide_morph_images_train_seglabel), imageSize, imageSize, 3))\n\nfor i in range(len(peptide_morph_images_train_seglabel)):\n  images_no_annotation_directory.append('%s.jpg' % (peptide_morph_images_train_seglabel[i].split(\"_\")[0] + \"_\" + peptide_morph_images_train_seglabel[i].split(\"_\")[1]))\n  images_no_annotation[i] = parse_images(images_no_annotation_directory[i])\n\n  # these were used to create the ground truth grayscale images from the manual segmentation labels.\n  # image_string = tf.io.read_file(peptide_morph_images_train_seglabel[i])\n  # image = tf.image.decode_image(image_string, channels=3) / 255\n  # image = tf.image.resize(image, (imageSize, imageSize))\n  # image = tf.image.convert_image_dtype(image, tf.float32)\n  # trans_nd_image_array = image.numpy()\n  # image_mask[i] = generate_ground_truth_images(trans_nd_image_array, imageSize)\n  \n# np.savez_compressed('seg_mask_res512.npz', mask=image_mask)\n\n# once we have the seg_mask saved, we can directly load from npz file\nimage_mask = np.load('seg_mask_res%i.npz' % (imageSize), allow_pickle=True)['mask']\n```\n\n    WARNING:tensorflow:5 out of the last 5 calls to <function parse_images at 0x7f9490054b90> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for  more details.\n    WARNING:tensorflow:6 out of the last 6 calls to <function parse_images at 0x7f9490054b90> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for  more details.\n\n\n\n```python\n# quantify percolation or not for each segmentation mask from the two morphologies\nfrom sklearn.cluster import DBSCAN\nnanowire_perc = np.zeros((image_mask.shape[0]))\nfor k in range(image_mask.shape[0]):\n  nanowire_pix = np.transpose(np.vstack((np.where(image_mask[k] == 1)[0], np.where(image_mask[k] == 1)[1])))\n  cluster = DBSCAN(eps=2, min_samples=2, n_jobs=-1).fit(nanowire_pix)\n  cluster_size = np.zeros(np.unique(cluster.labels_).shape)\n  labels = cluster.labels_\n  \n  for i in np.unique(cluster.labels_):\n    if i == -1:            # i == -1 is the default label for points not in any cluster, these are excluded, as they are likely artifacts during resizing the image to lower resolution\n      labels = np.delete(labels, np.where(labels == -1)[0])\n      continue             # because the segmentation image masks practically don't have single pixels, i.e. they should have close neighbors because they are hand drawn\n\n    cluster_size[i] = np.where(labels == i)[0].shape[0]\n    right = np.max(cluster.components_[np.where(labels == i)[0], 0])\n    top = np.max(cluster.components_[np.where(labels == i)[0], 1])\n    left = np.min(cluster.components_[np.where(labels == i)[0], 0])\n    bottom = np.min(cluster.components_[np.where(labels == i)[0], 1])\n\n    count_horizontal = right - left\n    count_vertical = top - bottom\n    if count_horizontal >= imageSize - 2 and count_vertical >= imageSize - 2:\n      nanowire_perc[k] = 1\n\nprint('number of dispersed morphology images: %i' % len(np.where(nanowire_perc == 0)[0]))\nprint('number of percolated network morphology images: %i' % int(sum(nanowire_perc)))\n\naccuracy_score(nanowire_perc, peptide_morph_train_seg_enc)\n# if the accuracy_score is 1.0, that means all the dispersed morphology images are validated as not percolated, \n# all the network morphology images are validated as percolated.\n```\n\n    number of dispersed morphology images: 100\n    number of percolated network morphology images: 100\n\n\n\n\n\n    1.0\n\n\n", "meta": {"hexsha": "2117f0674d4c954ee72a062830493ef5f1fb1612", "size": 16076, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/percolation_analysis.ipynb", "max_stars_repo_name": "arthijayaraman-lab/self-supervised_learning_microscopy_images", "max_stars_repo_head_hexsha": "f7adc86798379ae3934a864e6c41982a15aae870", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/percolation_analysis.ipynb", "max_issues_repo_name": "arthijayaraman-lab/self-supervised_learning_microscopy_images", "max_issues_repo_head_hexsha": "f7adc86798379ae3934a864e6c41982a15aae870", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/percolation_analysis.ipynb", "max_forks_repo_name": "arthijayaraman-lab/self-supervised_learning_microscopy_images", "max_forks_repo_head_hexsha": "f7adc86798379ae3934a864e6c41982a15aae870", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16076.0, "max_line_length": 16076, "alphanum_fraction": 0.6731774073, "converted": true, "num_tokens": 2698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567937024021, "lm_q2_score": 0.05921025032625583, "lm_q1q2_score": 0.016475654410100554}}
{"text": "# <span style='color:darkred'> 4 Trajectory Analysis </span>\n\n***\n\n**<span style='color:darkred'> Important Note </span>**\n\nBefore proceeding to the rest of the analysis, it is a good time to define a path that points to the location of the MD simulation data, which we will analyze here.\n\nIf you successfully ran the MD simulation, the correct path should be:\n\n\n```python\n# Execute the cell to define the path to your simulation files\npath=\"OxCompBio-Datafiles/run\"\n```\n\nIf however, you need/want to use the data from the simulation that has been already performed, uncomment the command below to instead define the path that points to the prerun simulation.\n\n\n```python\n# Uncomment the line below and execute the cell to define the path to the prerun simulation files\n#path=\"OxCompBio-Datafiles/prerun/run\"\n```\n\n## <span style='color:darkred'> 4.1 Visualize the simulation </span>\n\nThe simplest and easiest type of analysis you should always do is to look at it with your eyes! Your eyes will tell you if something strange is happening immediately. A numerical analysis may not.\n\n### <span style='color:darkred'>  4.1.1 VMD </span>\n\n*Note: Again, this step is optional. If you don't have VMD, go to section 4.1.2 below to visualize the trajectory with NGLView instead.*\n\nLet us look at the simulations on VMD.\n\nOpen your vmd, by typing on your terminal:\n\n`% vmd`\n\nWhen it has finished placing all the windows on the screen. Click on `File` in the VMD main menu window and select `New Molecule`. The Molecule File Browser window should appear. Click on `Browse...` then select the `OxCompBio-Datafiles` and then the `run` directory and finally select `em.gro` (i.e. the file you made that has protein system energy minimized). Click `OK` and then click `Load`. It should load up the starting coordinates into the main window. Then click `Browse...` in the Molecule File Browser window. Select again the `OxCompBio-Datafiles`, then the `run` directory and then `md.xtc`. Select `OK` and then hit `Load`. The trajectory should start loading into the main VMD window. \n\nAlthough things will be moving, you can see that it is quite difficult to visualize the individual components. That is one of the problems with simulating such large and complicated systems. VMD makes it quite easy to look at individual components of a system. For example, let us consider the protein only. On the VMD Main menu, left-click on Graphics and select `Representations`. A new menu will appear (`Graphical Representations`). In the box entitled `Selected Atoms` type protein and hit enter. Only those atoms that form part of the protein are now selected. Various other selections and drawing methods will help to visualize different aspects of the simulation. \n\n<span style='color:Blue'> **Questions**  </span> \n\n* How would you say the protein behaves? \n\n\n* Is it doing anything unexpected? What would you consider unexpected behaviour?\n\n\n* Can you add representations for the ASP and the ARG residues only? Can you observe if they form any inter-subunit interactions? We will quantify those later on.\n\n### <span style='color:darkred'> 4.1.2 NGLView </span>\n\n\nYou have already tested NGLView at the Python tutorial (Notebook `12_ProteinAnalysis`) and at the beginning of this tutorial. This time however, you can visualize the trajectory you generated after carrying out the MD simulation.\n\nYou should also be familiar now with the MDAnalysis Python library that we will use to analyze the MD trajectory. We will also use it below, to create a Universe and load it on NGLView.\n\n\n```python\n# Import MDAnalysis and NGLView\nimport MDAnalysis\nimport nglview\n\n# Load the protein structure and the trajectory as a universe named protein\nprotein=MDAnalysis.Universe(f\"{path}/em.gro\", f\"{path}/md_fit.xtc\")\nprotein_view = nglview.show_mdanalysis(protein)\nprotein_view.gui_style = 'ngl'\n\n#Color the protein based on its secondary structure\nprotein_view.update_cartoon(color='sstruc')\nprotein_view\n```\n\n\n    ThemeManager()\n\n\n\n    NGLWidget(gui_style='ngl', max_frame=100)\n\n\n<span style='color:Blue'> **Questions**  </span> \n\n* How would you say the protein behaves? \n\n\n* Is it doing anything unexpected? What would you consider unexpected behaviour?\n\n\n* Can you add representations for the ASP and the ARG residues only? Can you observe if they form any inter-subunit interactions? We will quantify those later on.\n\nNow that we are sure the simulation is not doing anything ridiculous, we can start to ask questions about the simulation. The first thing to establish is whether the simulation has equilibrated to some state. So what are some measures of the system\nbeing equilibrated? And what can we use to test the reliability of the simulation?\n\n## <span style='color:darkred'> 4.2 System Equilibration </span> \n\n### <span style='color:darkred'> 4.2.1 Temperature fluctuation </span>\n\nThe system temperature as a function of time was calculated in the previous section, with the built-in GROMACS tool `gmx energy`, but we still have not looked at it. It is now time to plot the temperature *vs* time and assess the results.\n\n<span style='color:Blue'> **Questions**  </span> \n\n* Does the temperature fluctuate around an equilibrium  value?\n\n\n* Does this value correspond to the temperature that we predefined in the `md.mdp` input file?\n\nImport numpy and pyplot from matplotlib, required to read and plot the data, respectively.\n\n\n```python\n# We declare matplotlib inline to make sure it plots properly\n%matplotlib inline\n# We need to import numpy \nimport numpy as np\n# We need pyplot from matplotlib to generate our plots\nfrom matplotlib import pyplot\n```\n\nNow, using numpy, we can read the data from the `1hsg_temperature.xvg` file; the first column is the time (in ps) and the secong is the system temperature (in K).\n\n\n```python\n# Read the file that contains the system temperature for each frame\ntime=np.loadtxt(f\"{path}/1hsg_temperature.xvg\", comments=['#','@'])[:, 0]\ntemperature=np.loadtxt(f\"{path}/1hsg_temperature.xvg\", comments=['#','@'])[:, 1] \n```\n\nYou can use numpy again to compute the average temperature and its standard deviation.\n\n\n```python\n# Calculate and print the mean temperature and the standard deviation\n# Keep only two decimal points\nmean_temperature=round(np.mean(temperature), 2)\nstd_temperature=round(np.std(temperature), 2)\nprint(f\"The mean temperature is {mean_temperature} \u00b1 {std_temperature} K\")\n```\n\n    The mean temperature is 300.29 \u00b1 1.67 K\n\n\nFinally, you can plot the temperature *vs* simulation time.\n\n\n```python\n# Plot the temperature\npyplot.plot(time, temperature, color='darkred')\npyplot.title(\"Temperature over time\")\npyplot.xlabel(\"Time [ps]\")\npyplot.ylabel(\"Temperature [K]\")\npyplot.show()\n```\n\n### <span style='color:darkred'> 4.2.2 Energy of the system </span> \n\nAnother set of properties that is quite useful to examine is the various energetic contributions to the energy. The total\nenergy should be constant. but the various contributions can change and this can sometimes indicate something\ninteresting or strange happening in your simulation. Let us look at some energetic properties of the simulation.\n\nWe have already exctracted the Lennard-Jones energy, the Coulomb energy and the potential energy using again the GROMACS built-in tool `gmx energy`. The data of these three energetic components are saved in the same file called `1hsg_energies.xvg`; the first column contains the time (in ps) and the columns that follow contain the energies (in kJ/mol), in the same order as they were generated.\n\nWe can now read the data from the `1hsg_energies.xvg` file using numpy.\n\n\n```python\n# Read the file that contains the various energetic components for each frame\ntime=np.loadtxt(f\"{path}/1hsg_energies.xvg\", comments=['#','@'])[:, 0]\nlennard_jones=np.loadtxt(f\"{path}/1hsg_energies.xvg\", comments=['#','@'])[:, 1]\ncoulomb=np.loadtxt(f\"{path}/1hsg_energies.xvg\", comments=['#','@'])[:, 2]\npotential=np.loadtxt(f\"{path}/1hsg_energies.xvg\", comments=['#','@'])[:, 3]\n```\n\nAnd now that we read the data file, we can plot the energetic components *vs* simulation time in separate plots using matplotlib.\n\n\n```python\n# Plot the Lennard-Jones energy\npyplot.plot(time, lennard_jones, color='blue')\npyplot.title(\"Lennard Jones energy over time\")\npyplot.xlabel(\"Time [ps]\")\npyplot.ylabel(\"LJ energy [kJ/mol]\")\npyplot.show()\n\n# Plot the electrostatic energy\npyplot.plot(time, coulomb, color='purple')\npyplot.title(\"Electrostatic energy over time\")\npyplot.xlabel(\"Time [ps]\")\npyplot.ylabel(\"Coulomb energy [kJ/mol]\")\npyplot.show()\n\n# Plot the potential energy\npyplot.plot(time, potential, color='green')\npyplot.title(\"Potential energy over time\")\npyplot.xlabel(\"Time [ps]\")\npyplot.ylabel(\"Potential energy [kJ/mol]\")\npyplot.show()\n```\n\n<span style='color:Blue'> **Questions**  </span> \n\n* Can you plot the Coulomb energy and the potential energy, following the same steps as above? \n\n\n* Is the total energy stable in this simulation? \n\n\n* What is the dominant contribution to the potential energy?\n\n## <span style='color:darkred'> 4.3 Analysis of Protein </span>\n\n*Hint:* Ideally, you should visualize the trajectory with either VMD or NGLView and combine the information you extract from the plots with what you observe visually. That applies to all the structural analysis that you perform. So feel free at any point to go back to VMD or NGLView to verify the results you get from the analysis below.\n\n### <span style='color:darkred'> 4.3.1 Root mean square deviation (RMSD) of 1HSG </span>\n\nThe RMSD gives us an idea of how 'stable' our protein is when compared to our starting, static, structure. The lower the RMSD is, the more stable we can say our protein is. \n\nThe RMSD as a function of time, $\\rho (t)$, can be defined by the following equation:\n\n\\begin{equation}\n\\\\\n\\rho (t) = \\sqrt{\\frac{1}{N}\\sum^N_{i=1}w_i\\big(\\mathbf{x}_i(t) - \\mathbf{x}^{\\text{ref}}_i\\big)^2}\n\\end{equation}\n\nLuckily MDAnalysis has its own built-in function to calculate this and we can import it.\n\n\n\n\n```python\n# Import built-in MDAnalysis tools for alignment and RMSD.\nfrom MDAnalysis.analysis import align\nfrom MDAnalysis.analysis.rms import RMSD as rmsd\n\n# Define the simulation universe and the reference structure (protein structure at first frame)\nprotein = MDAnalysis.Universe(f\"{path}/md.gro\", f\"{path}/md_fit.xtc\")\nprotein_ref = MDAnalysis.Universe(f\"{path}/em.gro\", f\"{path}/md_fit.xtc\")\nprotein_ref.trajectory[0]\n\n# Call the MDAnalysis align function to align the MD simulation universe to the reference (first frame) universe\nalign_strucs = align.AlignTraj(protein, protein_ref, select=\"backbone\", weights=\"mass\", in_memory=True, verbose=True)\n\nR = align_strucs.run()\nrmsd_data = R.rmsd\n\n# Plot the RMSD\npyplot.plot(rmsd_data)\npyplot.title(\"RMSD over time\")\npyplot.xlabel(\"Frame number\")\npyplot.ylabel(\"RMSD (Angstrom)\")\npyplot.show()\n\n```\n\n<span style='color:Blue'> **Questions**  </span> \n\n* What does this tell you about the stability of the protein? Is it in a state of equilibrium and if so why and at what time?\n\n\n* Can you think of a situation where this approach might not be a very good indication of stability?\n\n### <span style='color:darkred'> 4.3.2 Root mean square fluctuation (RMSF) of 1HSG </span>\n\nA similar property that is particularly useful is the root mean square fluctuation (RMSF), which shows how each residue flucuates over its average position.\n\nThe RMSF for an atom, $\\rho_i$, is given by:\n\n\\begin{equation}\n\\rho_i = \\sqrt{\\sum^N_{i=1} \\big\\langle(\\mathbf{x}_i - \\langle \\mathbf{x}_i \\rangle )^2 \\big\\rangle }\n\\end{equation}\n\n\n```python\nfrom MDAnalysis.analysis.rms import RMSF as rmsf\n\n# Define again the simulation universe, using however the renumbered .gro file that you had generated earlier\nprotein = MDAnalysis.Universe(f\"{path}/em.gro\", f\"{path}/md_fit.xtc\")\n\n# Reset the trajectory to the first frame\nprotein.trajectory[0]\n\n# We will need to select the alpha Carbons only\ncalphas = protein.select_atoms(\"name CA\")\n\n# Compute the RMSF of alpha carbons. Omit the first 20 frames,\n# assuming that the system needs this amount of time (200 ps) to equilibrate\nrmsf_calc = rmsf(calphas, verbose=True).run(start=20)\n\n# Plot the RMSF\npyplot.plot(calphas.resindices+1, rmsf_calc.rmsf, color='darkorange' )\npyplot.title(\"Per-Residue Alpha Carbon RMSF\")\npyplot.xlabel(\"Residue Number\")\npyplot.ylabel(\"RMSF (Angstrom)\")\npyplot.show()\n```\n\n<span style='color:Blue'> **Questions**  </span> \n\n* Can you identify structural regions alone from this plot and does that fit in with the structure?\n\n\n* Residues 43-58 form part of the flexible flap that covers the binding site. How does this region behave in the simulation? Remember that you have a homodimer, so chain A contains residues 1-99 and chain B contains residues 100 to 198.\n\n### <span style='color:darkred'> 4.3.3 Hydrogen Bond Formation </span>\n\nWe can also use the simulation to monitor the formation of any hydrogen bonds that may be of interest.\n\nIn the case of HIV-1 protease, the hydrogen bonds (HB) that are formed between the ARG8', the ASP29 and the ARG87 amino acids at the interface of the two subunits act in stabilising the dimer.\n\nWe can analyse the trajectory and monitor the stability of these interactions *vs* simulation time.\n\n\n```python\n# Import the MDAnalysis built-in tool for HB Analysis\nfrom MDAnalysis.analysis.hydrogenbonds.hbond_analysis import HydrogenBondAnalysis as HBA\n\n# Define the protein universe\n# Note that when using this tool, it is recommended to include the .tpr file instead of the .gro file,\n# because it contains bond information, required for the identification of donors and acceptors.\nprotein = MDAnalysis.Universe(f\"{path}/md.tpr\", f\"{path}/md.xtc\")\n\n# Define the atom selections for the HB calculation.\n# In this case, the ARG hydrogens and the ASP oxygens, which act as the HB acceptors are specifically defined.\nhbonds = HBA(universe=protein, hydrogens_sel='resname ARG and name HH21 HH22', acceptors_sel='resname ASP and name OD1 OD2')\n\n# Perform the HB calculation\nhbonds.run()\n    \n# Plot the total number of ASP-ARG HBs vs time\nhbonds_time=hbonds.times\nhbonds_data=hbonds.count_by_time()\n\npyplot.plot(hbonds_time, hbonds_data, color='cyan')\npyplot.title(\"ASP-ARG Hydrogen Bonds\")\npyplot.xlabel(\"Time [ps]\")\npyplot.ylabel(\"# Hydrogen Bonds\")\npyplot.show()\n\n# Compute and print the average number of HBs and the standard deviation\naver_hbonds=round(np.mean(hbonds_data), 2)\nstd_hbonds=round(np.std(hbonds_data), 2)\nprint(f\"The average number of ASP-ARG HBs is {aver_hbonds} \u00b1 {std_hbonds}\")\n```\n\n<span style='color:Blue'> **Questions**  </span> \n\n* How much variation is there in the number of hydrogen bonds?\n\n\n* Do any break and not reform? \n\n\n* Using VMD, can you observe the HB formation and breakage throughout the simulation?\n\n***\n\nThis concludes the analysis section, but the aim was only to give you an idea of the numerous information that we can gain when analysing an MD trajectory. Feel free to ask and attempt to answer your own questions, utilising the tools that you were introduced to during the tutorial.\n\n## <span style='color:darkred'> 4.4 Further Reading </span>\n\n\nThe texts recommended here are the same as those mentioned in the lecture:\n* \"Molecular Modelling. Principles and Applications\". Andrew Leach. Publisher: Prentice Hall. ISBN: 0582382106. This book has rapidly become the defacto introductory text for all aspects of simulation.\n* \"Computer simulation of liquids\". Allen, Michael P., and Dominic J. Tildesley. Oxford university press, 2017.\n* \"Molecular Dynamics Simulation: Elementary Methods\". J.M. Haile. Publisher: Wiley. ISBN: 047118439X. This text provides a more focus but slightly more old-fashioned view of simulation. It has some nice simple examples of how to code (in fortran) some of the algorithms though.\n\n\n## <span style='color:darkred'> End of Tutorial </span>\n\nCongratulations, you have finished the MD tutorial. Hopefully, by you are familiar with the molecular dynamics method, the GROMACS software that we have used to perform the simulation, and you have an idea of the type of information that we can extract from an MD run and how we can visualize, compute and plot the data of interest.\n", "meta": {"hexsha": "2abc811b5eceffd59ae0140d9ca5d855696f435e", "size": 219898, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorials/MD/04_Trajectory_Analysis_Solutions.ipynb", "max_stars_repo_name": "bigginlab/OxCompBio", "max_stars_repo_head_hexsha": "f9d1c9e6e2f51bb4e6bd7cbba83f33f5efef8726", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-12-29T23:59:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T09:45:18.000Z", "max_issues_repo_path": "tutorials/MD/remote/04_Trajectory_Analysis_Solutions.ipynb", "max_issues_repo_name": "bigginlab/OxCompBio", "max_issues_repo_head_hexsha": "f9d1c9e6e2f51bb4e6bd7cbba83f33f5efef8726", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 97, "max_issues_repo_issues_event_min_datetime": "2019-12-11T12:19:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T12:01:50.000Z", "max_forks_repo_path": "tutorials/MD/remote/04_Trajectory_Analysis_Solutions.ipynb", "max_forks_repo_name": "bigginlab/OxCompBio", "max_forks_repo_head_hexsha": "f9d1c9e6e2f51bb4e6bd7cbba83f33f5efef8726", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-12-09T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T11:21:32.000Z", "avg_line_length": 293.1973333333, "max_line_length": 37216, "alphanum_fraction": 0.9257655822, "converted": true, "num_tokens": 3979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20181321265898594, "lm_q2_score": 0.08151975485900514, "lm_q1q2_score": 0.01645176362326881}}
{"text": "# **Assignment 1: Rendering systems**\n\n## ECSE 446/546: Realistic/Advanced Image Synthesis, Fall 2021\n\n#### Due: Wednesday, October 13, 2021 at 11:59pm EST on [myCourses](https://mycourses2.mcgill.ca/)\n\n#### Weight: 25% (ECSE 446) / 20% (ECSE 546)\n\n*In this assignment, you will implement the techniques discussed in the 'Rendering Systems' module. You will implement key components of **rasterization** and **ray tracing** pipelines.*\n\nSince evaluation for this assignment is partly automated, it is important that you fill in your code **only in the cells indicated**. If needed, extra cells may be added, but only at the end of the notebook. Any cells added in between will very likely present issues with the autograder.\n\nThe *bonus* questions in the end are for extra credit and are optional.\n\n\n---\n\n## **Assignment Submission Process**\n\nModify the `ipynb` notebook we provide on myCourses and submit your modified file, renamed according to your student ID, as\n\n<font color=\"red\">A1-[YourStudentID].ipynb</font>\n\nFor example, if your student ID is **123456789**, then your submission filename should be **A1-123456789.ipynb**.\n\n> Note that every time you submit a new file, your previous submission will be overwritten.\n**All submissions must be made using myCourses.**\nYou can submit as many times as you like, but we will only grade the last submission.\n\nThis assignment is to be completed *individually*.\n\n### Late policy\n\nFailure to submit a (valid) assignment on time will result in a score of **zero (0%)** on the assignment.\n**We will not grant extensions.**\nExceptional circumstances will be treated as specified in [McGill's Policies on Student Rights and Responsibilities](https://www.mcgill.ca/students/srr/).\n\n### Plagiarism and cheating\nPlagiarism is an academic offense of misrepresenting authorship. This can result in penalties up to expulsion. It is also possible to plagiarise your own work, e.g., by submitting work from another course without proper attribution. When in doubt, attribute!\n\nWe expect you to submit your own work. Assignments are individual tasks. That said, we want to promote an environment where you are comfortable discussing ideas together. A good rule to follow: fully understand every solution you submit and only submit code that was written by you.\n\nMcGill values academic integrity and students should take the time to fully understand the meaning and consequences of cheating, plagiarism and other academic offenses (as defined in the Code of Student Conduct and Disciplinary Procedures \u2014 see these two links [[1]](https://www.mcgill.ca/integrity) [[2]](https://www.mcgill.ca/students/srr/honest)).\n\nIn accordance with article 15 of the Charter of Students' Rights, students may submit any written or programming components in either French or English.\n\n### Code comparison\n\nWe will use code similarity checkers to detect and deal with cases of plagiarism and cheating.\n\n### Python `import` statements\n\nWe provide all import statements required to complete the assignment.\nYou must not use any `import`s other than the ones we provide.\nDoing so will result in a score of **zero (0%)** on the assignment.\n\n\n---\n\n## **Notes and Tips**\n\n### Debugging in Jupyter Notebook / Google Colab\n\n[Here](https://colab.research.google.com/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/01.06-Errors-and-Debugging.ipynb) is a quick tutorial by Jake VanderPlas on how to debug in Jupyter Notebook / Google Colab using `ipdb`.\nFor a complete list of commands and their usage, check out `pdb`'s [official documentation](https://docs.python.org/3/library/pdb.html).\n\n\n### OpenEXR Format and EXR Viewer\n\n[OpenEXR](http://www.openexr.com/) is a standardized file format for storing high dynamic range (HDR) images. \nUnlike low dynamic range (LDR) image formats \u2014 such as JPG and PNG \u2014 HDR image pixel color values are not restricted to the interval $[0, 1]$. \nThis allows us to represent luminance ranges similar to the range we experience through the human visual system in the real-world.\n\n**For this assignment though, all output pixel color values in your rendered image should still be clipped to $[0, 1]$.**\n\nWe recommend using [tev](https://github.com/Tom94/tev), a lightweight yet powerful EXR viewer that supports various tonemapping operators and pixel-level image inspection and comparison.\nTo obtain `tev`, follow the OS-specific instruction below:\n\n- Windows / macOS: Download the [pre-built binaries](https://github.com/Tom94/tev/releases). \nIf your Mac comes with the Apple M1 chip and you want to to run `tev` natively (not via Rosetta 2), [build it from source](https://github.com/Tom94/tev#macos--linux).\n- Linux: Read this [step-by-step guide](https://github.com/Tom94/tev#macos--linux) to build from source.\nFor Arch Linux and other Arch-based distros (Manjaro, EndeavourOS, etc.), `tev` is available in [AUR](https://aur.archlinux.org/packages/tev/).\n\n### Render time\n\nFor each experiment, the default image height and width `imgWidth` and `imgHeight` have been set to `64`. This enables faster debugging.\n\n**Once you think your implementation works, render images of width and height `512` instead of `64`**.\n\n\n---\n\n## **Preparation**\n\nLet us first install and/or import all necessary modules for this assignment. Note that you are not allowed to import anything apart from the modules in this cell, as they will not be available in our autograding environment.\n\nRun the cell below to install and import all necessary modules.\n\n\n```python\n!pip install pyexr\n\n%matplotlib inline\n\nimport math\nimport time\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image as im\nimport pyexr\n```\n\n    Collecting pyexr\n      Downloading PyEXR-0.3.10.tar.gz (4.6 kB)\n    Collecting OpenEXR\n      Downloading OpenEXR-1.3.2.tar.gz (10 kB)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from pyexr) (1.19.5)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from pyexr) (0.16.0)\n    Building wheels for collected packages: pyexr, OpenEXR\n      Building wheel for pyexr (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pyexr: filename=PyEXR-0.3.10-py2.py3-none-any.whl size=4518 sha256=d70e177ca95629de80e6a2de2c19fb1ec70245f7a4130ecc373b729b082ac448\n      Stored in directory: /root/.cache/pip/wheels/da/c8/fb/f00811aa6cb7b74d76ab5941aea24ecf85fd8ca26f1a53ee39\n      Building wheel for OpenEXR (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for OpenEXR: filename=OpenEXR-1.3.2-cp37-cp37m-linux_x86_64.whl size=189355 sha256=d53d41cc06e35a0584faaa63016bfee7cf05c866d4aeb2d6261b45071ef2694a\n      Stored in directory: /root/.cache/pip/wheels/d1/c6/6c/dcf5d042ed2d547da41021f47957b16bebe9cadfd095765d44\n    Successfully built pyexr OpenEXR\n    Installing collected packages: OpenEXR, pyexr\n    Successfully installed OpenEXR-1.3.2 pyexr-0.3.10\n\n\n### Helper Functions\n\nNext, we define some helper functions below that will be useful across the whole assignment.\n\n> **Note**: You are not _required_ to use these helper function implementations. These are only provided to reduce the amount of boilerplate code you need to write.\n\nSpecifically,\n- `normalize(v)`: Normalizes a vector `v`.\n- `distance(a, b)`: Computes the distance between two points `a` and `b`.\n- `squaredDistance(a, b)`: Computes the *squared* distance between two points `a` and `b`.\n- `perspective(fovy, aspect, near, far)`: Computes the perspective projection matrix.\n- `lookAt(eye, at, up)`: Computes the viewing transformation matrix.\n- `image2NDC(x, y, width, height)`: Maps the given image coordinate $(x, y)$ into the canonical view volume (or normalized device coordinates, NDC).\n- `NDC2Image(x, y, width, height)`: Maps the given coordinate $(x, y)$ in canonical view volume into the screen space.\n\n*Note that you may also want to define your own helper functions in this cell.*\n\n\n```python\ncam_near = 0.1\ncam_far = 2000\np = 1\n\ndef interpolate_q4(triangle, attr, p):\n    \"\"\"\n    Accurate perspective interpolation.\n    Parameters:\n    triangle: 2D numpy array containing triangle's vertex positions (homogeneous\n              coordinates) in NDC space.\n        Note that 'triangle' here is in the form of\n        [[v0.x, v0.y, v0.z, v0.w], [v1.x, v1.y, v1.z, v1.w], [v2.x, v2.y, v2.z, v2.w]]\n        and NOT a Triangle object.\n    attr: Attribute to interpolate across the triangle (e.g., position)\n    p: Point (in NDC space) at which to compute interpolated attribute\n    \"\"\"\n    (alpha, beta, gamma) = barycentric_q4(triangle[0], triangle[1], triangle[2], p)\n    return (alpha * attr[0] / triangle[0][3] + beta * attr[1] / triangle[1][3] + gamma * attr[2] / triangle[2][3]) / (\n            alpha / triangle[0][3] + beta / triangle[1][3] + gamma / triangle[2][3])\n\n\ndef barycentric_q4(a, b, c, p):\n    \"\"\"\n    Compute Barycentric coordinates of point p w.r.t triangle a, b, c.\n    Parameters:\n    a, b, c: vertices coordinates of the triangle.\n    p: the point you want to know its  barycentric coordinates\n    \"\"\"\n    a = a / a[-1]\n    b = b / b[-1]\n    c = c / c[-1]\n    area = signedArea(a, b, c)\n    alpha = signedArea(b, c, p) / area\n    beta = signedArea(c, a, p) / area\n    gamma = 1 - alpha - beta\n    return alpha, beta, gamma\n\ndef rasterize_q4(scene, triangle, img, zbuf):\n    \"\"\"\n        Rasterize a single triangle in the scene.\n        Parameters:\n        scene: an instance of Scene class.\n        triangle: the triangle to be rasterized. It is an instance of Triangle class, not vertices in np.array.\n    \"\"\"\n\n    # Scene Configs\n    width = scene.config[\"width\"]\n    height = scene.config[\"height\"]\n    fov = scene.config[\"fov\"] * np.pi / 180.\n\n    # Transformation Matrices\n    transform_Cam = lookAt(scene.cam.eye, scene.cam.at, scene.cam.up)\n    transform_Pers = perspective(fov, width / height, cam_near, cam_far) @ transform_Cam\n\n    # Triangle Related Vertices\n    tri_Wrd3d = np.array(([triangle.v0, triangle.v1, triangle.v2]))\n    # 4d versions below\n    tri_Wrd = np.array(([np.append(v, 1) for v in tri_Wrd3d]))\n\n    tri_Cam = np.transpose(transform_Cam @ np.transpose(tri_Wrd))\n    tri_NDC = np.transpose(transform_Pers @ np.transpose(tri_Wrd))\n    v0_NDC4d, v1_NDC4d, v2_NDC4d = tri_NDC\n\n    # Compute the bounding box and map to Image Space\n    ws = np.stack((tri_NDC[:, 3], tri_NDC[:, 3]), axis=-1)\n    xmin, xmax, ymin, ymax = bbox(tri_NDC[:, :2] / ws)\n\n    # The corresponding minimum and maximum points of the Bounding box of the triangle in the Image Space\n    min_Img, max_Img = np.array(NDC2Image(xmin, ymin, width, height)), np.array(\n        NDC2Image(xmax, ymax, width, height))\n\n    # Loop over pixels in the bbox\n    for i in range(min_Img[0], max_Img[0] + 1):\n        for j in range(max_Img[1], min_Img[1] + 1):\n            p_NDC = np.append(image2NDC(i, j, width, height), [1, 1])\n\n            # Compute the Bary Coord for the pixel in NDC Space\n            (a, b, c) = barycentric(v0_NDC4d / v0_NDC4d[3], v1_NDC4d / v1_NDC4d[3], v2_NDC4d / v2_NDC4d[3], p_NDC)\n\n            # the pixel is in the triangle\n            if 0 <= a and 0 <= b  and 0 <= c:\n                # Interpolate to compute the World Space Coord for the pixel\n                # tri_NDC = tri_NDC / np.stack(([tri_NDC[:, -1],tri_NDC[:, -1], tri_NDC[:, -1], tri_NDC[:, -1]]), axis=-1)\n                p_Wrd = interpolate_q4(tri_NDC, tri_Wrd, p_NDC)\n                p_Wrd /= p_Wrd[-1]\n                p_depth2Cam = p_Wrd[-2] - scene.cam.eye[-1]\n\n                # Update if closer to the camera\n                if p_depth2Cam < zbuf[j, i]:\n                    # compute the world coord\n                  #  p_World = np.linalg.inv(transform_Cam) @ p_Cam\n                  #  p_World /= p_World[-1]\n                    zbuf[j, i] = p_depth2Cam\n                    img[j, i] = shade(scene, p_Wrd[:-1], triangle)\n    return img\n\ndef normalize(v, eps=1e-8):\n    \"\"\"\n    Normalize a vector. Add a tiny eps to the denominator to prevent\n    divide-by-zero errors.\n    \"\"\"\n    dist = np.linalg.norm(v)\n    return v / (dist + eps)\n\n\ndef distance(a, b):\n    return np.linalg.norm(b - a)\n\n\ndef squaredDistance(a, b):\n    v = b - a\n    return np.dot(v.T, v)\n\n\ndef perspective(fovy, aspect, near, far):\n    \"\"\"\n    Perspective projection transformation\n    Parameters:\n        fovy (float): vertical field of view (in radians).\n        aspect (float): aspect ratio (width/height).\n        near (float): distance to near plane.\n        far (float): distance to far plane.\n    \"\"\"\n    n = near\n    f = far\n    t = near * math.tan(fovy / 2)\n    r = t * aspect\n    return np.array([\n        [n / r, 0, 0, 0],\n        [0, n / t, 0, 0],\n        [0, 0, - (f + n) / (f - n), -2 * f * n / (f - n)],\n        [0, 0, -1, 0]\n    ])\n\n\ndef lookAt(eye, at, up):\n    \"\"\"\n    Viewing transformation.\n    Parameters:\n        eye (np.array): eye postion\n        at (np.array): the point the eye is looking at (usually, the center of\n          an object of interest)\n        up (np.array): up vector (vertically upward direction)\n    \"\"\"\n    z = normalize(eye - at)\n    x = normalize(np.cross(up, z))\n    y = normalize(np.cross(z, x))\n    A = np.column_stack((x, y, z, eye))\n    A = np.row_stack((A, np.array([0, 0, 0, 1])))\n    return np.linalg.inv(A)\n\n\ndef image2NDC(x, y, width, height):\n    \"\"\" \n    Image space (-0.5..width-0.5, -0.5..height-0.5) to NDC (normalized \n    device coordinates) space (-1..1, -1..1) transform.\n    Note that (0, 0) in image space is the TOP left of the image.\n    Parameters:\n        x (float): x coordinate in image space.\n        y (float): y coordinate in image space.\n    \"\"\"\n    return ((2 * x - width + 1) / width, -(2 * y - height + 1) / height)\n\n\ndef NDC2Image(x, y, width, height):\n    \"\"\"\n    NDC space to image space transform.\n    Parameters:\n        x (float): x coordinate in NDC space.\n        y (float): y coordinate in NDC space.\n    \"\"\"\n    return (round((width * x + width - 1) / 2), round((height * (-y) + height - 1) / 2))\n```\n\n### Rendering data structures\n\nWe now define essential data structures for our _scene description_. All these data structures (except for *Triangle*) **must be used as is, without modification**. These classes will then be employed to define rasterization and ray tracing routines. (these cells have a \"DO NOT TOUCH\" warning.\n\n> **Note**: The autograder will not pick these cells up from your submission, but will rather use ones from the handout notebook -- so any modifications you make to the rendering data structures will not be available during evaluation.\n\nIn particular, we define the *Scene*, *Camera*, *PointLight*, *Ray*, *Triangle* and *Diffuse* classes. There are two blank methods to be completed in the *Triangle* class. These methods are to be completed for the ray tracing part of the assignment. (For now, if you choose to do rasterization first, you may safely ignore the incomplete methods in the *Triangle* class)\n\nAll other classes except *Ray* are shared across rasterization and ray tracing.\n\n\n```python\n# DO NOT TOUCH\nclass Scene:\n    \"\"\" \n    A class used to represent a rendering scene\n    Attributes:\n        geometry: objects in the scene.\n        light: light info\n        camera: camera info\n        config: store width, height and fov\n    \"\"\"\n    def __init__(self, geometry, light, camera, config):\n        self.geometry = geometry\n        self.light = light\n        self.cam = camera\n        # config is a dictionary with keys: width, height, fov\n        self.config = config\n```\n\n\n```python\n# DO NOT TOUCH\nclass Camera:\n    \"\"\" \n    A class to represent a camera\n    Attributes:\n        eye: position of the camera\n        at: position where the camera looks at\n        up: up direction of the camera\n    \"\"\"\n    def __init__(self, eye, at, up):\n        self.eye = eye\n        self.at = at\n        self.up = up\n```\n\n\n```python\n# DO NOT TOUCH\nclass PointLight:\n    \"\"\" \n    A point light source\n    Attributes:\n        p: position of the light source\n        e: emmisive flux (power) of the light source\n    \"\"\"\n    def __init__(self, position, emission):\n        self.p = position\n        self.e = emission\n```\n\n\n```python\n# DO NOT TOUCH\nclass Ray:\n    \"\"\" \n    A class to represent a ray\n    Attributes:\n        o: origin of the ray\n        d: direction of the ray\n        max: max distance at which the ray is capped (to avoid evaluating \n          indefinitely far points along a ray, we cap it to a large distance)\n    \"\"\"\n    def __init__(self, origin, dir, max=1e5):\n        self.o = origin\n        self.d = dir\n        self.max = max\n```\n\n\n```python\n# DO NOT TOUCH\nclass Diffuse:\n    \"\"\" \n    Diffuse material\n    Attributes:\n        c: diffuse color\n    \"\"\"\n    def __init__(self, color):\n        self.c = np.asarray(color)\n```\n\nThe following `Triangle` class has two methods you will need to complete for the ray tracing component of this assignment. Instructions for completing this are found below, in the ray tracing section. You may safely ignore these for the first question (rasterization).\n\n\n```python\nclass Triangle:\n    \"\"\" \n    A class to represent a triangle\n    Attributes:\n        v0, v1, v2: vertices of the triangle\n        mat: material of the triangle\n    \"\"\"\n    def __init__(self, v0, v1, v2, mat):\n        self.v0 = np.asarray(v0)\n        self.v1 = np.asarray(v1)\n        self.v2 = np.asarray(v2)\n        self.mat = mat\n\n    def intersect(self, r):\n        \"\"\"\n      Intersect this triangle with a ray\n      Parameters:\n          r: ray to intersect\n      Returns:\n          0 if no hit, otherwise the distance to the hit point\n      \"\"\"\n        # TODO: implement this\n        A = np.transpose(np.array([-r.d, self.v1 - self.v0, self.v2 - self.v0]))\n        b = r.o - self.v0\n        eps = 1e-5\n        # Solve Ax = b\n        try:\n            x = np.linalg.solve(A, b)\n            t = x[0]\n            dist = distance(r.o + t * r.d, r.o)\n            if 0 <= x[1] <= 1 and 0 <= x[2] <= 1 and 0 <= x[1] + x[2] <= 1 and t > 0 and (dist + eps) < r.max:\n                return dist\n            else:\n                return 0\n        except np.linalg.LinAlgError:\n            return 0\n\n    def normal(self, hit):\n        # TODO: implement this\n        # get 2 edges\n        e1 = self.v1 - self.v0\n        e2 = self.v2 - self.v0\n        return normalize(np.cross(e1, e2))\n```\n\n## Question 1 - Rasterization - Single primitive (25 points)\n\nWe will implement a minimal rasterization pipeline as a smoketest. The goal of this question will be to rasterize a single triangle and display it on the screen.\n\nRecall the basic triangle rasterization algorithm you learned in class:\n* compute _edge functions_ from projected vertices\n* check if the edge function values evaluated at a given pixel are all non-negative.\n\nWe will take an alternative (but equivalent) approach that is more convenient when interpolating vertex positions and $z$-buffer values. You may recall this is the Barycentric coordinate approach which we discussed, albeit in the context of raytracing (ray-triangle intersection test).\n\n#### Rasterization using Barycentric coordinates\n\nSuppose a point $P$ is represented in terms of its barycentric coordinates $(\\alpha, \\beta, \\gamma)$ with respect to a triangle $\\triangle ABC$.\nWe know that, $P$ lies inside $\\triangle ABC$ if $\\alpha \\geq 0, \\beta \\geq 0, \\gamma \\geq 0$.\nSo, given Barycentric coordinates $P$, inside-outside tests simply amount to checking the non-negativity of $\\alpha, \\beta, \\gamma$.\nThis reduces the problem to computing the exact barycentric coordinates of $P$, which may be done using the following formulae:\n\n$$\n\\begin{align*}\n    \\alpha &= \\frac{S_{\\triangle BCP}}{S_{\\triangle ABC}}, \\\\\n    \\beta &= \\frac{S_{\\triangle CAP}}{S_{\\triangle ABC}}, \\\\\n    \\gamma &= 1 - \\alpha - \\beta,\n\\end{align*}\n$$\n\nwhere the signed area of a triangle $S_{\\triangle v_0 v_1 v_2}$ is defined as\n\n$$\nS_{\\triangle v_0 v_1 v_2} = \\frac{1}{2} [ (v_{1x} - v_{0x}) (v_{2y} - v_{0y}) - (v_{1y} - v_{0y}) (v_{2x} - v_{0x}) ].\n$$\n\nInterpolation of parameters across the triangle is a tricky problem and requires perspective correction.\nFor technical details, please consult [The OpenGL Graphics System: A Specification](https://www.khronos.org/registry/OpenGL/specs/gl/glspec44.core.pdf), page 427.\n\nWe provide in the following cell a complete implementation of all helper functions desribed above.\n\n\n```python\ndef cross(a, b):\n    \"\"\" Cross product of vectors in x-y plane. The result is the the z component (a scalar). \"\"\"\n    return a[0]*b[1] - a[1]*b[0]\n\n\ndef signedArea(a, b, c):\n    \"\"\"\n    Signed area of the triangle times 2.\n    Parameters:\n    a, b, c: vertices coordinates of the triangle.\n    \"\"\"\n    return cross(b-a, c-a)\n\n\ndef barycentric(a, b, c, p):\n    \"\"\"\n    Compute Barycentric coordinates of point p w.r.t triangle a, b, c.\n    Parameters:\n    a, b, c: vertices coordinates of the triangle.\n    p: the point you want to know its  barycentric coordinates\n    \"\"\"\n    area = signedArea(a, b, c)\n    alpha = signedArea(b, c, p) / area\n    beta = signedArea(c, a, p) / area\n    gamma = 1 - alpha - beta\n    return (alpha, beta, gamma)\n\n\ndef interpolate(triangle, attr, p):\n    \"\"\" \n    Accurate perspective interpolation.\n    Parameters:\n    triangle: 2D numpy array containing triangle's vertex positions (homogeneous\n              coordinates) in NDC space.\n        Note that 'triangle' here is in the form of\n        [[v0.x, v0.y, v0.z, v0.w], [v1.x, v1.y, v1.z, v1.w], [v2.x, v2.y, v2.z, v2.w]]\n        and NOT a Triangle object.\n    attr: Attribute to interpolate across the triangle (e.g., position)\n    p: Point (in NDC space) at which to compute interpolated attribute\n    \"\"\"\n    (alpha, beta, gamma) = barycentric(triangle[0], triangle[1], triangle[2], p)\n    return (alpha * attr[0] / triangle[0][3] + beta * attr[1] / triangle[1][3] + gamma * attr[2] / triangle[2][3]) / (alpha / triangle[0][3] + beta / triangle[1][3] + gamma / triangle[2][3])\n```\n\nWe are now ready to implement the rasterization loop for a single triangle. In effect, we will do the following.\n\n1. compute the viewing and perspective transformation matrices; this enables us to project the triangle vertices from world coordinates into a canonical view volume,\n2. compute the bounding box of the triangle and map its vertices to image coordinates, and\n3. for each pixel in the bounding box, check whether or not it lies inside the triangle; if the pixel lies inside the triangle, assign the color of the triangle (diffuse color) to that pixel\n\nUsing this information, complete the empty functions `bbox()` and `rasterize()` below.\n\n**Note**: the bellow cells must only contain the `bbox()` and `rasterize()` functions respectively. You may NOT have any statements in these cells that are outside the scope of the functions. You may NOT modify the function call (arguments, return statements) as they interfere with the autograder.\n\n\n```python\ndef bbox(triangle, eps=1e-6):\n    \"\"\"\n        The bounding box of the triangle.\n        Parameters:\n        triangle: triangle vertices in np.array. E.g., triangle[0], triangle[1], triangle[3] are 3 vertices (coordinates).\n        eps: a tiny number (epsilon) for clipping the result. See the comments below.\n    \"\"\"\n    # TODO: Compute the bounding box of a griven triangle\n    # The triangle is assumed to be in 2D (normalized view volume) and each \n    # vertex of the triangle may be accessed by indexing as follows:\n    # First dim indexes the triangle vertex (0 -> first vertex,\n    # 1 -> second vertex, 2 -> third vertex)\n    # Second dim indexes the coordinate (0 -> x, 1 -> y)\n    # E.g., the y coordinate of the first vertex is triangle[0][1]\n    # Note that xmin, xmax, ymin, xmax should be in the NDC space. E.g., -1 < xmin < 1, etc.\n    # That is, you need to clamp them in [-1+eps, 1-eps].\n    s_tri = np.clip(np.sort(triangle, axis=0), -1 + eps, 1 - eps)\n    xs, ys = s_tri[:, 0], s_tri[:, 1]\n\n    xmin, xmax, ymin, ymax = xs[0], xs[-1], ys[0], ys[-1]\n\n    return xmin, xmax, ymin, ymax\n```\n\n\n```python\ndef rasterize(scene, triangle):\n    \"\"\"\n        Rasterize a single triangle in the scene.\n        Parameters:\n        scene: an instance of Scene class.\n        triangle: the triangle to be rasterized. It is an instance of Triangle class, not vertices in np.array.\n    \"\"\"\n    # DO NOT modify these three lines\n    width = scene.config[\"width\"]\n    height = scene.config[\"height\"]\n    img = np.zeros((height, width, 3))\n\n    # TODO: Implement the rasterization loop here\n    # Recall that a rasterization loop comprises the following steps\n    # 1. transform primitives (here, triangles) from world space to NDC space\n    # 2. Compute the bounding box enclosing the triangle (this assumes the \n    #    triangle to be in NDC space)\n    #         `(xmin, xmax, ymin, ymax) = bbox(triangle_ndc)`\n    # 3. Loop over all pixels in the bounding box, and implement the Barycentric\n    #    coordinate-based rasterization scheme described in the question.\n    \n    # DO NOT modify this return statement\n    cam = scene.cam\n    eye, at, up = cam.eye, cam.at, cam.up\n    near, far = cam_near, cam_far\n\n    config = scene.config\n    fov = config[\"fov\"] * np.pi / 180.\n    aspect = config[\"width\"] / config[\"height\"]\n\n    # transform from world space to NDC space\n\n    tri_World3d = np.hstack((np.stack((triangle.v0, triangle.v1), axis=-1), triangle.v2[:, np.newaxis]))\n    tri_Cam4d = lookAt(eye, at, up) @ np.vstack((tri_World3d, np.ones((3,), int)))\n    tri_NDC4d_t = np.transpose(perspective(fov, aspect, near, far) @ tri_Cam4d)\n\n    v0_NDC4d, v1_NDC4d, v2_NDC4d = tri_NDC4d_t[0, :], tri_NDC4d_t[1, :], tri_NDC4d_t[2, :]\n    tri_Attr = np.array([triangle.mat.c, triangle.mat.c, triangle.mat.c])\n\n    # Compute the bounding box and map to Image Space\n    xmin, xmax, ymin, ymax = bbox(tri_NDC4d_t[:, :2] / np.transpose(tri_Cam4d[3, np.newaxis]))\n\n    min_Img, max_Img = np.array(NDC2Image(xmin, ymin, width, height)), np.array(\n        NDC2Image(xmax, ymax, width, height))\n\n    # Loop over pixels in the bbox\n    diff_Img = max_Img - min_Img\n    for p in np.ndindex(diff_Img[0], -diff_Img[1]):\n        p_real = (p[0] + min_Img[0], -p[1] + min_Img[1])\n        p_NDC = image2NDC(p_real[0], p_real[1], width, height)\n        p_NDC = np.append(p_NDC, [1, 1])\n        (a, b, c) = barycentric(v0_NDC4d / v0_NDC4d[3], v1_NDC4d / v1_NDC4d[3], v2_NDC4d / v2_NDC4d[3], p_NDC)\n        if 0 <= a <= 1 and 0 <= b <= 1 and 0 <= c <= 1:\n            img[p_real[1], p_real[0]] = interpolate(tri_NDC4d_t, tri_Attr, p_NDC)\n            # print(img[p_real[1], p_real[0]])\n    # print(img)\n    return img\n\n```\n\nThe following code loads a scene with only one triangle for testing.\nIt will be reused later by your ray tracer.\nSimply run the cell before generating your rasterized image.\n\n\n```python\ndef loadTriangleScene(width, height):\n    objects = [Triangle([5, -2.5, 0], [-5, -2.5, 0], [0, 2.5, 0], Diffuse([1, 0, 0]))]\n    light = PointLight([0, 15, -15], [36000, 36000, 36000])\n    camera = Camera(np.array([0, 0, -15]), np.array([0, 0, 0]), np.array([0, 1, 0]))\n    config = { \"width\": width, \"height\": height, \"fov\": 60 }\n    return Scene(objects, light, camera, config)\n```\n\nNow render your rasterized triangle and see if you can successfully obtain a red-colored, upward-pointing triangle.\nThe rendered result will also be written to an EXR image.\n\nFor faster debugging, we currently set `imgWidth` and `imgHeight` to `64`. **For the eventual solution, you are required to render a `512 x 512` image**. (Note that rendering at this resolution may take several minutes, so please plan ahead of time)\n\n\n```python\nimgWidth = 64\nimgHeight = 64\n```\n\n\n```python\nscene = loadTriangleScene(imgWidth, imgHeight)\nprint(f\"Start rendering in resolution: {imgWidth}x{imgHeight}, fov: {scene.config['fov']}\")\nstartTime = time.monotonic()\nimg = rasterize(scene, scene.geometry[0])\nduration = time.monotonic() - startTime\nprint(\"Finished rendering, time taken:\", duration, \"seconds\")\n\nplt.imshow(img)\n\nprint(\"Writing PNG...\")\nplt.imsave(f\"triangle-rasterization.png\", img)\n\nprint(\"Writing EXR...\")\noutput = np.power(img, 2.2)\npyexr.write(f\"triangle-rasterization.exr\", output)\n```\n\n\n---\n\n## Question 2 - Ray Tracing - Single primitive (35 points)\n\nWe will now implement a barebones ray tracer to render the same scene (i.e., a single triangle).\n\n**Hint:** Remember that rasterization and ray tracing are two different techniques, but solve the same problem (the primary/eye-visibility problem). You should get identical results regardless of the technique used (helpful when debugging ray tracing implementations).\n\n\nIn the `Triangle` class above, the following two routines need to be implemented:\n\n- `intersect(ray)`: Check if ray intersects the current triangle, and if so, the distance to the hit point.\n- `normal(hit):` Computes the triangle normal at a hit point.\n\nAfter completing the `Triangle` class, implement the following ray-scene intersection method: given a `Ray` object, intersect it with all objects (here, triangles) in the scene. Determine which objects intersect this ray, and return the distance of the closest _hit_ object.\n\n**Note**: There are often multiple objects in the scene that a ray might hit. If so, you must remember to line-search for the closest _hit_.\n\n\n```python\ndef intersect(scene, ray):\n    \"\"\" \n    Method to intersect all objects in the scene\n    Parameters:\n        scene: scene to render.\n        ray: ray to trace.\n    Returns:\n      (has_hit, hit_object_id, distance_to_object)\n      has_hit is 0 if there is not hit, else it is 1\n      id is the idx of the scene object hit\n      t is the ray parameter (recall a ray is o + td) at which\n        a hit is found\n    \"\"\"\n    # TODO: implement this\n    primitives = scene.geometry\n\n    # Initialize return values\n    has_hit, hit_id, t = False, -1, ray.max\n\n    # Set up distance range\n    t_min, t_max = 0., ray.max\n\n    # loop\n    for (index, primitive) in zip(range(len(primitives)), primitives):\n        t = primitive.intersect(ray)\n        if t_min < t < t_max:\n            t_max = t\n            hit_id = index\n            has_hit = True\n    dist = t_max\n    return has_hit, hit_id, dist\n```\n\nRecall for a point light with intensity $\\Phi$, the radiance of diffusely reflected light $L_d$ at a shading point is computed as\n\n\\begin{equation}\n    L_d = \\frac{\\rho}{\\pi} \\left( \\frac{\\Phi}{4 \\pi r^2} \\right) \\max\\left( 0, \\mathbf{n} \\cdot \\mathbf{l} \\right),\n\\end{equation}\n\nwhere $\\rho$ is the diffuse albedo, $r$ is the distance between the shading point and the light, $\\mathbf{n}$ is the surface normal and $\\mathbf{l}$ is the light direction.\n\nImplement the following `shade()` function according to the above formula.\nAssume $\\rho = 1$ in your code.\n\n\n```python\ndef shade(scene, hit, triangle):\n    \"\"\"\n    Method to shade a hit point\n    Parameters:\n      scene: scene to render.\n      hit: hit point to shade.\n      triangle: hit triangle object\n    Returns:\n      radiance at the hit point \n    \"\"\"\n    # TODO: implement this\n    light = scene.light\n    light_pos, light_flux = light.p, np.asarray(light.e)\n\n    cam = scene.cam\n    cam_pos = cam.eye\n\n    diff_l = light_pos - hit\n    r = distance(light_pos, hit)\n    li = normalize(diff_l)\n\n    diff_c = normalize(cam_pos - hit)\n    normal = triangle.normal(hit)\n    tmp = 2 * (np.dot(diff_c, normal) > 0)\n\n    n = normal * (tmp - 1)\n\n    cosine = max(0, np.dot(n, li))\n    a = light_flux / (4 * np.pi * (r ** 2))\n    k = p / np.pi\n    b = k * a * cosine\n    radiance = b * triangle.mat.c\n    radiance = np.array([min(1, radiance[0]), min(1, radiance[1]), min(1, radiance[2])])\n    # radiance = triangle.mat.c\n    return radiance  # Replace this with your return statement, when implementation is ready\n\n```\n\nNow trace a ray into the scene and collect the hit information.\nEvaluate and return the outgoing radiance using your `shade()` method.\n\n\n```python\ndef trace(scene, ray):\n    \"\"\" \n    Trace a ray in the scene, and shade the hit point\n    Parameters:\n      scene: scene to render\n      ray: ray to trace\n    Returns:\n      light radiance at the hit point \n    \"\"\"\n    intersection = intersect(scene, ray)\n    has_hit = intersection[0]\n    if has_hit is False:\n      return np.zeros(3)\n    hit_id = intersection[1]  # object id\n    t = intersection[2] # distance\n    \n    return shade(scene, ray.o + ray.d * t, scene.geometry[hit_id])\n```\n\n### Putting Everything Together ###\n\nNow we have all the pieces of the ray tracer, let's put it together and implement the ray tracing rendering loop.\nThe `renderRaytracing()` function below is currently empty: complete it by looping over all pixels on the image plane and computing their color.\nAt a high-level, this is done as follows:\n\n1. calculate the camera perspective, the camera-to-world transformation matrix and the aspect ratio,\n2. loop over all pixels on the image plane, and\n3. generate a ray through each pixel and *splat* its contribution onto the image plane.\n\nThe last step can be broken down into four (4) substeps:\n\n1. retrieve the *pixel* center $(x, y)$,\n2. construct a ray with its origin at the camera's center and its direction pointing through the pixel center,\n3. transform this ray to world coordinates, taking the FoV and aspect ratio into account,\n4. trace this ray into the scene and output the returned radiance contribution to the image buffer.\n\n\n```python\ndef renderRaytracing(scene):\n    \"\"\"\n    Ray tracer main rendering function\n    Parameters:\n      scene: scene to render\n    Returns:\n      rendered image\n    \"\"\"\n    print(\"Rendering the scene\")\n\n    # TODO: implement this\n    # Hints:\n    # 1. Set up the model view projection transforms (use the `width`, `height`,\n    #    `fov` parameters from the `scene.config` dictionary for this).\n    # 2. Loop over all pixels in a ray, and follow the instructions from the\n    #    question to complete the ray tracing routine.\n    width, height, fovy = scene.config[\"width\"], scene.config[\"height\"], scene.config[\"fov\"] * np.pi / 180\n    aspect = width / height\n    n = cam_near\n    t = n * math.tan(fovy / 2)\n    r = t * aspect\n\n    cam = scene.cam\n    cam2World = np.linalg.inv(lookAt(cam.eye, cam.at, cam.up))\n    x, y, z, eye = cam2World[:-1, 0], cam2World[:-1, 1], cam2World[:-1, 2], cam2World[:-1, 3]\n\n    imgBuffer = np.zeros(shape=(height, width, 3))\n    # pixelBuffer = np.zeros(shape=(width, height, 2))\n\n    # set the pivot point at the top left\n    for i in range(0, width):\n        for j in range(0, height):\n            u, v = -r + ((i + 0.5) * 2 * r / width), t - ((j + 0.5) * 2 * t / height)\n            # pixel_Cam= np.asarray([u, v, d])\n            # dir_Cam = hp.normalize(pixel_Cam)\n            dir = normalize(u * x + v * y - n * z)\n            ray = Ray(eye, dir)\n            imgBuffer[j, i] = trace(scene, ray)\n\n    # Return your image\n    return imgBuffer\n```\n\nFinally, it's time to check your solution.\nRun the two cells below to render and display the same triangle scene and output the result to an EXR image.\n\nFor faster debugging, we currently set `imgWidth` and `imgHeight` to `64`. **For the eventual solution, you are required to render a `512 x 512` image**. (Note that rendering at this resolution may take several minutes, so please plan ahead of time)\n\n\n```python\nimgWidth = 64\nimgHeight = 64\n```\n\n\n```python\nscene = loadTriangleScene(imgWidth, imgHeight)\nprint(f\"Start rendering in resolution: {scene.config['width']}x{scene.config['height']}, fov: {scene.config['fov']}\")\nstartTime = time.monotonic()\nimg = renderRaytracing(scene)\nduration = time.monotonic() - startTime\nprint(\"Finished rendering, time taken:\", duration, \"seconds\")\n\nplt.imshow(img)\n\nprint(\"Writing PNG...\")\nplt.imsave(f\"triangle-raytracing.png\", img)\n\nprint(\"Writing EXR...\")\noutput = np.power(img, 2.2)\npyexr.write(f\"triangle-raytracing.exr\", output)\n```\n\n## Question 3 - Ray tracing the Cornell Box (15 points)\n\nHaving successfully rendered a triangle, we are now ready to render the famous [*Cornell Box* scene](https://www.graphics.cornell.edu/online/box/data.html).\n\nIn this question, we will test our ray tracer code from above, on a more complex scene. If your above implementation was correct, it will NOT require any changes and should seamlessly run on the Cornell Box scene.\n\nThe code cell below loads the scene description into memory.\n\n\n\n```python\ndef loadCornellBox(width, height):\n    objects = [\n    # Floor\n    Triangle([552.8, 0, 0], [0, 0, 0], [0, 0, 559.2], Diffuse([1, 1, 1])),\n    Triangle([552.8, 0, 0], [0, 0, 559.2], [552.8, 0, 559.2], Diffuse([1, 1, 1])),\n    # Ceiling\n    Triangle([556.0, 548.8, 0.0], [556.0, 548.8, 559.2],[0.0, 548.8, 559.2], Diffuse([1, 1, 1])),\n    Triangle([556.0, 548.8, 0.0], [0.0, 548.8, 559.2], [0.0, 548.8, 0.0], Diffuse([1, 1, 1])),\n    # Back Wall\n    Triangle([549.6, 0.0, 559.2], [0.0, 0.0, 559.2], [0.0, 548.8, 559.2], Diffuse([1, 1, 1])),\n    Triangle([549.6, 0.0, 559.2], [0.0, 548.8, 559.2], [556.0, 548.8, 559.2], Diffuse([1, 1, 1])),\n    # Right Wall\n    Triangle([0.0, 0.0, 559.2 ], [0.0, 0.0, 0.0], [0.0, 548.8,   0.0], Diffuse([0, 1, 0])),\n    Triangle([0.0, 0.0, 559.2], [0.0, 548.8, 0.0], [0.0, 548.8, 559.2], Diffuse([0, 1, 0])),\n    # Left Wall\n    Triangle([552.8, 0.0, 0.0], [549.6, 0.0, 559.2], [556.0, 548.8, 559.2], Diffuse([1, 0, 0])),\n    Triangle([552.8, 0.0, 0.0], [556.0, 548.8, 559.2], [556.0, 548.8, 0.0], Diffuse([1, 0, 0])),\n    # Short Block\n    Triangle([130.0, 165.0,  65.0], [82.0, 165.0, 225.0], [240.0, 165.0, 272.0],  Diffuse([1, 1, 1])),\n    Triangle([130.0, 165.0,  65.0], [240.0 ,165.0, 272.0], [290.0, 165.0, 114.0], Diffuse([1, 1, 1])),\n    Triangle([290.0, 0.0, 114.0], [290.0, 165.0, 114.0], [240.0, 165.0, 272.0], Diffuse([1, 1, 1])),\n    Triangle([290.0, 0.0, 114.0], [240.0, 165.0, 272.0], [240.0, 0.0, 272.0], Diffuse([1, 1, 1])),\n    Triangle([130.0, 0.0, 65.0], [130.0, 165.0, 65.0], [290.0, 165.0, 114.0], Diffuse([1, 1, 1])),\n    Triangle([130.0, 0.0, 65.0], [290.0, 165.0, 114.0], [290.0, 0.0, 114.0], Diffuse([1, 1, 1])),\n    Triangle([82.0, 0.0, 225.0], [82.0, 165.0, 225.0], [130.0, 165.0, 65.0], Diffuse([1, 1, 1])),\n    Triangle([82.0, 0.0, 225.0], [130.0, 165.0, 65.0], [130.0, 0.0, 65.0], Diffuse([1, 1, 1])),\n    Triangle([240.0, 0.0, 272.0], [240.0, 165.0, 272.0], [82.0, 165.0, 225.0], Diffuse([1, 1, 1])),\n    Triangle([240.0, 0.0, 272.0], [82.0, 165.0, 225.0], [82.0, 0.0, 225.0], Diffuse([1, 1, 1])),\n    # Tall Block\n    Triangle([423.0, 330.0, 247.0], [265.0, 330.0, 296.0], [314.0, 330.0, 456.0], Diffuse([1, 1, 1])),\n    Triangle([423.0, 330.0, 247.0], [314.0, 330.0, 456.0], [472.0, 330.0, 406.0], Diffuse([1, 1, 1])),\n    Triangle([423.0, 0.0, 247.0], [423.0, 330.0, 247.0], [472.0, 330.0, 406.0], Diffuse([1, 1, 1])),\n    Triangle([423.0, 0.0, 247.0], [472.0, 330.0,  406.0], [472.0, 0.0, 406.0], Diffuse([1, 1, 1])),\n    Triangle([472.0, 0.0, 406.0], [472.0, 330.0,406.0], [314.0, 330.0, 456.0], Diffuse([1, 1, 1])),\n    Triangle([472.0, 0.0, 406.0], [314.0, 330.0, 456.0], [314.0, 0.0, 456.0], Diffuse([1, 1, 1])),\n    Triangle([314.0, 0.0, 456.0], [314.0, 330.0, 456.0], [265.0, 330.0, 296.0], Diffuse([1, 1, 1])),\n    Triangle([314.0, 0.0, 456.0], [265.0,  330.0, 296.0], [265.0, 0.0, 296.0], Diffuse([1, 1, 1])),\n    Triangle([265.0, 0.0, 296.0], [265.0, 330.0, 296.0], [423.0, 330.0, 247.0], Diffuse([1, 1, 1])),\n    Triangle([265.0, 0.0, 296.0], [423.0, 330.0, 247.0], [423.0, 0.0, 247.0], Diffuse([1, 1, 1])),\n    ]\n    light = PointLight([278, 508, 279.5], [5e6, 5e6, 5e6])\n    camera = Camera(np.array([278, 273 , -800]),np.array([278, 273, 0]), np.array([0, 1, 0]))\n    config = { \"width\": width, \"height\": height, \"fov\": 38 }\n    return Scene(objects, light, camera, config)\n```\n\nIf all of your ray tracing code is correctly set up, the following code cell should produce an image of the Cornell Box scene. Note that the orignal image may be accessed at [this webpage](https://www.graphics.cornell.edu/online/box/data.html).\n\nSince we currently use a low resolution output image (64 x 64), rendering should take about 20 seconds (on a Google Colab CPU-only instance). Once you are satisfied with the output, **render a 512 x 512 image**. This image will be the deliverable for this question.\n\n(Note that rendering at a `512 x 512` resolution may take several minutes, so please plan ahead of time)\n\n\n\n\n```python\nimgWidth = 64\nimgHeight = 64\n```\n\n\n```python\nscene = loadCornellBox(imgWidth, imgHeight)\nprint(f\"Start rendering in resolution: {imgWidth}x{imgHeight}, fov: {scene.config['fov']}\")\nstartTime = time.monotonic()\nimg = renderRaytracing(scene)\nduration = time.monotonic() - startTime\nprint(\"Finished rendering, time taken:\", duration, \"seconds\")\n\nplt.imshow(img)\n\nprint(\"Writing PNG...\")\nplt.imsave(f\"cbox-raytracing.png\", img)\n\nprint(\"Writing EXR...\")\noutput = np.power(img, 2.2)\npyexr.write(f\"cbox-raytracing.exr\", output)\n```\n\n## Question 4 - Rasterizing the Cornell Box (25 points)\n\nFor rasterizing the Cornell Box scene, we will need to implement a Z-buffer, to ensure only the object closest to the camera at each pixel is rendered. Recall that, for a triangle, we only had a single primitive; hence we did not need to perform Z-buffering.\n\nIn this question, you will modify the `rasterize()` method you implemented in Question 1, and will implement a more general `renderRasterization()` method that includes a visibility test by means of a Z-buffer. In particular:\n* Factor in the position and intensity of the scene's position light\n* Initialize a Z-buffer (an array of size equal to that of pixels in the output image). Initialize depth for each pixel to a large value or infinity (`np.inf`).\n* Loop over all triangles, and rasterize them (keeping in mind the bullet points below)\n* Compute the depth with respect to the camera ($z^{'}$) by interpolating the pixel location within each triangle's vertices.\n* If the new depth (w.r.t. the camera) is smaller than the value stored in the Z-buffer for the pixel, shade the pixel using the diffuse reflection of this new triangle at the shade point.\n\nHint: keep visualizing intermediate stages of your Z-buffer to get a better sense for debugging.\n\n\n```python\ndef renderRasterization(scene):\n    # DO NOT modify these three lines\n    width = scene.config[\"width\"]\n    height = scene.config[\"height\"]\n    img = np.zeros((height, width, 3))\n\n    zbuf = np.full((height, width), np.inf)\n    # TODO: Implement the rasterization loop here\n\n    # transformation matrix from world space to NDC space\n    fovy = scene.config[\"fov\"]\n    PVM = perspective(fovy * math.pi / 180, width / height, 0.1, 10) @ lookAt(scene.cam.eye, scene.cam.at,\n                                                                                    scene.cam.up)\n\n    # set up point light\n    light_pos = np.asarray(scene.light.p)\n    light_em = np.asarray(scene.light.e)\n    \n    for obj in scene.geometry:\n        rasterize_q4(scene, obj, img, zbuf)\n    return img\n```\n\nFinally, rasterize the Cornell Box by running the two cells below.\nThe rendered result should look identical to what you get with ray tracing.\n\nFor faster debugging, we currently set `imgWidth` and `imgHeight` to `64`. **For the eventual solution, you are required to render a `512 x 512` image**. (Note that rendering at this resolution may take several minutes, so please plan ahead of time).\n\n\n```python\nimgWidth = 64\nimgHeight = 64\n```\n\n\n```python\nscene = loadCornellBox(imgWidth, imgHeight)\nprint(f\"Start rendering in resolution: {imgWidth}x{imgHeight}, fov: {scene.config['fov']}\")\nstartTime = time.monotonic()\nimg = renderRasterization(scene)\nduration = time.monotonic() - startTime\nprint(\"Finished rendering, time taken:\", duration, \"seconds\")\n\nplt.imshow(img)\n\nprint(\"Writing PNG...\")\nplt.imsave(f\"cbox-rasterization.png\", img)\n\nprint(\"Writing EXR...\")\noutput = np.power(img, 2.2)\npyexr.write(f\"cbox-rasterization.exr\", output)\n```\n\n---\n\n## **Bonus Questions**\n\nThe following questions are for **extra credit**, and are not mandatory.\n\n**Only attempt this part if you have finished all required questions**. These questions build atop Questions 1 through 4.\n\n**No partial points will be awarded on these questions.**\n\n**You may choose to attempt one or more bonus questions, and in no particular order**.\n\nThe bonus questions are not autograded -- you are free to use as many cells and define functions as needed. You may not, however, import libraries other than those approved for this assignment. If in doubt, please talk to the TAs or the instructor.\n\n## Bonus Question 1 - Shading normals (15 points)\n\nThis question involves computing the shading normals for a triangle mesh.\n\nDownload the Stanford bunny `.obj` file available [here](https://graphics.stanford.edu/~mdfisher/Data/Meshes/bunny.obj). Read it into a `numpy` array (you may use the `ObjLoader` class provided [here](https://inareous.github.io/posts/opening-obj-using-py)).\n\nNote how the bunny obj file only has vertex and face information, but no normals? The objective of this bonus question is to compute the _shading normals_ for this triangle mesh and render it using your choice of rasterization / ray tracing implementation from above. With proper shading normals, the bunny should look smooth (except at the silhouettes), instead of faceted).\n\n(Hint: you will find the discussion on shading normals from the end of the rasterization module slides useful.)\n\n## Bonus Question 2 - Phong illumination (15 points)\n\nFor this bonus question, you will implement a Phong BRDF / reflection model. Recall, from the lectures on phenomenological shading and appearance models how Phong specular reflection models work. Augment the ray tracer you just implemented by adding a Phong illumination model to get realistic reflections of the light source on object surfaces.\n\n\n```python\ndef shade_phong(scene, hit, triangle, kd = 0.6, ks = 0.5, p = 8):\n    \"\"\"\n        Method to shade a hit point\n        Parameters:\n          scene: scene to render.\n          hit: hit point to shade.\n          triangle: hit triangle object\n          kd: diffuse coefficient\n          ks: specular coefficient\n        Returns:\n          radiance at the hit point\n        \"\"\"\n    # TODO: implement this\n    light = scene.light\n    light_pos, light_flux = light.p, np.asarray(light.e)\n\n    cam = scene.cam\n\n    r_i = distance(light_pos, hit)\n    l_i = normalize(light_pos - hit)\n\n    r_cam = distance(cam.eye, hit)\n    l_cam =  normalize(cam.eye - hit)\n\n    h = normalize(l_cam + l_i)\n\n    n_tmp = triangle.normal(hit)\n    n = (2 * (np.dot(l_cam, n_tmp) > 0) - 1) * n_tmp\n\n    \n    \n\n    # Compute Diffuse Reflection\n    I = light_flux / (4 * np.pi ** 2 * (r_i ** 2))\n    L_diffuse = I * max([0, np.dot(n, l_i)])\n\n    # Compute Phong Reflection\n    lambertian = max(np.dot(-n, l_i), 0.0)\n    L_specular = 0.\n    if lambertian > 0.:\n        r_r = normalize(-l_i - 2* np.dot(-l_i, n) * n)\n        L_specular = math.pow(max(0, np.dot(r_r, l_cam)), p)\n\n    # Add together\n    radiance_unclip = kd * L_diffuse * triangle.mat.c + ks * L_specular * np.array(([1,1,1]))\n    radiance = np.array(([min(1, v) for v in radiance_unclip]))\n    return radiance # Replace this with your return statement, when implementation is ready\n\n\ndef trace_phong(scene, ray):\n    \"\"\"\n        Trace a ray in the scene, and shade the hit point\n        Parameters:\n          scene: scene to render\n          ray: ray to trace\n        Returns:\n          light radiance at the hit point\n        \"\"\"\n    intersection = intersect(scene, ray)\n    has_hit = intersection[0]\n    if has_hit is False:\n        return np.zeros(3)\n    hit_id = intersection[1]  # object id\n    t = intersection[2]  # distance\n\n    return shade_phong(scene, ray.o + ray.d * t, scene.geometry[hit_id])\n\n\ndef renderRaytracing_phong(scene):\n    \"\"\"\n        Ray tracer main rendering function\n        Parameters:\n          scene: scene to render\n        Returns:\n          rendered image\n        \"\"\"\n    print(\"Rendering the scene\")\n\n    # TODO: implement this\n    # Hints:\n    # 1. Set up the model view projection transforms (use the `width`, `height`,\n    #    `fov` parameters from the `scene.config` dictionary for this).\n    # 2. Loop over all pixels in a ray, and follow the instructions from the\n    #    question to complete the ray tracing routine.\n    width, height, fovy = scene.config[\"width\"], scene.config[\"height\"], scene.config[\"fov\"] * np.pi / 180\n    aspect = width / height\n    n = cam_near\n    t = n * math.tan(fovy / 2)\n    r = t * aspect\n\n    cam = scene.cam\n    cam2World = np.linalg.inv(lookAt(cam.eye, cam.at, cam.up))\n    x, y, z, eye = cam2World[:-1, 0], cam2World[:-1, 1], cam2World[:-1, 2], cam2World[:-1, 3]\n\n    imgBuffer = np.zeros(shape=(height, width, 3))\n    # pixelBuffer = np.zeros(shape=(width, height, 2))\n\n    # set the pivot point at the top left\n    for i in range(0, width):\n        for j in range(0, height):\n            u, v = -r + ((i + 0.5) * 2 * r / width), t - ((j + 0.5) * 2 * t / height)\n            # pixel_Cam= np.asarray([u, v, d])\n            # dir_Cam = hp.normalize(pixel_Cam)\n            dir = normalize(u * x + v * y - n * z)\n            ray = Ray(eye, dir)\n            imgBuffer[j, i] = trace_phong(scene, ray)\n\n    # Return your image\n    return imgBuffer\n```\n\n\n```python\nimgWidth = 512\nimgHeight = 512\nscene = loadCornellBox(imgWidth, imgHeight)\nstartTime = time.monotonic()\nimg = renderRaytracing_phong(scene)\nduration = time.monotonic() - startTime\nprint(\"Finished rendering, time taken:\", duration, \"seconds\")\nplt.imshow(img)\nplt.show()\nprint(\"Writing PNG...\")\nplt.imsave(f\"cbox-raytracing-phong.png\", img)\nprint(\"Writing EXR...\")\noutput = np.power(img, 2.2)\n```\n\n## Bonus Question 3 - Ray tracing with hard shadows (25 points)\n\nNotice how your ray tracing outputs do not contain any shadows? In this bonus question, you will perform ray tracing with additional _shadow rays_. In the phenomenological shading module, we saw how to extend the `trace()` routine to cast an additional shadow ray to determine whether a shade point is in  shadow w.r.t. a light source. We recommend you do this on the Cornell Box scene, but remember to use a low resolution image for debugging.\n\n\n```python\ndef shade_shadow(scene, hit, triangle):\n    \"\"\"\n        Method to shade a hit point\n        Parameters:\n          scene: scene to render.\n          hit: hit point to shade.\n          triangle: hit triangle object\n        Returns:\n          radiance at the hit point\n        \"\"\"\n    # TODO: implement this\n    light = scene.light\n    light_pos, light_flux = light.p, np.asarray(light.e)\n\n    cam = scene.cam\n    cam_pos = cam.eye\n\n    diff_l = light_pos - hit\n    r = distance(light_pos, hit)\n    li = normalize(diff_l)\n\n    ray = Ray(light_pos, -li, r)\n    hasblocked = any(tri.intersect(ray) != 0 for tri in scene.geometry)\n    if not hasblocked:\n        diff_c = normalize(cam_pos - hit)\n        normal = triangle.normal(hit)\n        tmp = 2 * (np.dot(diff_c, normal) > 0)\n\n        n = normal * (tmp - 1)\n\n        cosine = max(0, np.dot(n, li))\n        a = light_flux / (4 * np.pi * (r ** 2))\n        k = p / np.pi\n        b = k * a * cosine\n        radiance = b * triangle.mat.c\n        radiance = np.array([min(1, radiance[0]), min(1, radiance[1]), min(1, radiance[2])])\n        # radiance = triangle.mat.c\n        return radiance  # Replace this with your return statement, when implementation is ready\n    else:\n        return np.zeros(3)\n\ndef trace_shadow(scene, ray):\n    \"\"\"\n        Trace a ray in the scene, and shade the hit point\n        Parameters:\n          scene: scene to render\n          ray: ray to trace\n        Returns:\n          light radiance at the hit point\n        \"\"\"\n    intersection = intersect(scene, ray)\n    has_hit = intersection[0]\n    if has_hit is False:\n        return np.zeros(3)\n    hit_id = intersection[1]  # object id\n    t = intersection[2]  # distance\n\n    return shade_shadow(scene, ray.o + ray.d * t, scene.geometry[hit_id])\n\ndef renderRaytracing_shadow(scene):\n    \"\"\"\n        Ray tracer main rendering function\n        Parameters:\n          scene: scene to render\n        Returns:\n          rendered image\n        \"\"\"\n    print(\"Rendering the scene\")\n\n    # TODO: implement this\n    # Hints:\n    # 1. Set up the model view projection transforms (use the `width`, `height`,\n    #    `fov` parameters from the `scene.config` dictionary for this).\n    # 2. Loop over all pixels in a ray, and follow the instructions from the\n    #    question to complete the ray tracing routine.\n    width, height, fovy = scene.config[\"width\"], scene.config[\"height\"], scene.config[\"fov\"] * np.pi / 180\n    aspect = width / height\n    n = cam_near\n    t = n * math.tan(fovy / 2)\n    r = t * aspect\n\n    cam = scene.cam\n    cam2World = np.linalg.inv(lookAt(cam.eye, cam.at, cam.up))\n    x, y, z, eye = cam2World[:-1, 0], cam2World[:-1, 1], cam2World[:-1, 2], cam2World[:-1, 3]\n\n    imgBuffer = np.zeros(shape=(height, width, 3))\n    # pixelBuffer = np.zeros(shape=(width, height, 2))\n\n    # set the pivot point at the top left\n    for i in range(0, width):\n        for j in range(0, height):\n            u, v = -r + ((i + 0.5) * 2 * r / width), t - ((j + 0.5) * 2 * t / height)\n            # pixel_Cam= np.asarray([u, v, d])\n            # dir_Cam = hp.normalize(pixel_Cam)\n            dir = normalize(u * x + v * y - n * z)\n            ray = Ray(eye, dir)\n            imgBuffer[j, i] = trace_shadow(scene, ray)\n\n    # Return your image\n    return imgBuffer\n\nimgWidth = 64\nimgHeight = 64\nscene = loadCornellBox(imgWidth, imgHeight)\nstartTime = time.monotonic()\nimg = renderRaytracing_shadow(scene)\nduration = time.monotonic() - startTime\nprint(\"Finished rendering, time taken:\", duration, \"seconds\")\n\nplt.imshow(img)\nplt.show()\nprint(\"Writing PNG...\")\nplt.imsave(f\"cbox-rasterization.png\", img)\n\nprint(\"Writing EXR...\")\noutput = np.power(img, 2.2)\n```\n", "meta": {"hexsha": "7121e10284b9d52b5a114567202516a1792db7fa", "size": 136886, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "main.ipynb", "max_stars_repo_name": "asdqwe12011/Rendering-Pipelines", "max_stars_repo_head_hexsha": "5ef4dbfe4976c06c08172a3add0109a5f0530933", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.ipynb", "max_issues_repo_name": "asdqwe12011/Rendering-Pipelines", "max_issues_repo_head_hexsha": "5ef4dbfe4976c06c08172a3add0109a5f0530933", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.ipynb", "max_forks_repo_name": "asdqwe12011/Rendering-Pipelines", "max_forks_repo_head_hexsha": "5ef4dbfe4976c06c08172a3add0109a5f0530933", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 71.7431865828, "max_line_length": 10942, "alphanum_fraction": 0.6656414827, "converted": true, "num_tokens": 15403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1602660202952971, "lm_q2_score": 0.10230470926115266, "lm_q1q2_score": 0.016395968610752362}}
{"text": "  NEST Topology Module: A Case-Based Tutorial\n ===========================================\n\n #### **Author:** Hans Ekkehard Plesser\n #### **Institution:** Norwegian University of Life Sciences\n #### **Version:** 0.4\n #### **Date:** 21 November 2012\n #### **Copyright:** The NEST Initiative (2009-2012)\n #### **License:** Creative Commons Attribution License\n **NOTE:** The network generated by this script does generate\n dynamics in which the activity of the entire system, especially\n Rp and Vp oscillates with approx 5 Hz. This is different from\n the full model. Deviations are due to the different model type\n and the elimination of a number of connections, with no changes\n to the weights.\n\n Introduction\n ============\n\n This tutorial shows you how to implement a simplified version of the\n Hill-Tononi model of the early visual pathway using the NEST Topology\n module.  The model is described in the paper\n\n   S. L. Hill and G. Tononi.\n   Modeling Sleep and Wakefulness in the Thalamocortical System.\n   J Neurophysiology **93**:1671-1698 (2005).\n   Freely available via `doi 10.1152/jn.00915.2004 \n   <http://dx.doi.org/10.1152/jn.00915.2004>\n\n We simplify the model somewhat both to keep this tutorial a bit\n shorter, and because some details of the Hill-Tononi model are not\n currently supported by NEST. Simplifications include:\n\n 1. We use the `iaf_cond_alpha` neuron model, which is\n    simpler than the Hill-Tononi model.\n\n 2. As the `iaf_cond_alpha` neuron model only supports two\n    synapses (labeled \"ex\" and \"in\"), we only include AMPA and\n    GABA_A synapses.\n\n 3. We ignore the secondary pathway (Ts, Rs, Vs), since it adds just\n    more of the same from a technical point of view.\n\n 4. Synaptic delays follow a Gaussian distribution in the HT\n    model. This implies actually a Gaussian distributions clipped at\n    some small, non-zero delay, since delays must be\n    positive. Currently, there is a bug in the Topology module when\n    using clipped Gaussian distribution. We therefore draw delays from a\n    uniform distribution.\n\n 5. Some further adaptations are given at the appropriate locations in\n    the script.\n\n\n This tutorial is divided in the following sections:\n\n - **Philosophy**\n    Discusses the philosophy applied to model implementation in this\n    tutorial\n\n - **Preparations**\n    Neccessary steps to use NEST and the Topology Module\n\n - **Configurable Parameters**\n    Define adjustable network parameters\n\n - **Neuron Models**\n    Define the neuron models needed by the network model\n\n - **Populations**\n    Create Populations\n\n - **Synapse models**\n    Define the synapse models used in the network model\n\n - **Connections**\n    Create Connections\n\n - **Example simulation**\n    Perform a small simulation for illustration. This\n    section also discusses the setup for recording.\n\n\n Philosophy\n ==========\n\n A network models has two essential components: *populations* and\n *projections*.  We first use NEST's ``CopyModel()`` mechanism to\n create specific models for all populations and subpopulations in\n the network, and then create the populations using the Topology\n modules ``CreateLayer()`` function.\n\n We use a two-stage process to create the connections, mainly\n because the same configurations are required for a number of\n projections: we first define dictionaries specifying the\n connections, then apply these dictionaries later.\n\n The way in which we declare the network model here is an\n example. You should not consider it the last word: we expect to see\n a significant development in strategies and tools for network\n descriptions in the future. The following contributions to CNS\\*09\n seem particularly interesting\n\n - Ralf Ansorg & Lars Schwabe. Declarative model description and\n   code generation for hybrid individual- and population-based\n   simulations of the early visual system (P57);\n - Sharon Crook, R. Angus Silver, & Padraig Gleeson. Describing\n   and exchanging models of neurons and neuronal networks with\n   NeuroML (F1);\n\n as well as the following paper which will apply in PLoS\n Computational Biology shortly:\n\n - Eilen Nordlie, Marc-Oliver Gewaltig, & Hans Ekkehard Plesser.\n   Towards reproducible descriptions of neuronal network models.\n\n Preparations\n ============\n\n Please make sure that your ``PYTHONPATH`` is set correctly, so\n that Python can find the NEST Python module.\n\n **Note:** By default, the script does not show any graphics.\n Set ``SHOW_FIGURES`` to ``True`` to activate graphics.\n\n\n```\nimport sys\nsys.path.append('/opt/lib/python2.7/site-packages/')\n```\n\n\n```\nSHOW_FIGURES = True\n\nimport pylab\nif not SHOW_FIGURES:\n    pylab_show = pylab.show\n    def nop(s=None): pass\n    pylab.show = nop\nelse:\n    pylab.ion()\n```\n\n Introduction\n=============\n This tutorial gives a brief introduction to the ConnPlotter\n toolbox.  It is by no means complete.\n\n\n```\n# Load pynest\nimport nest\n\n# Load NEST Topoplogy module (NEST version>2.2)\nimport nest.topology as topo\n\n# Make sure we start with a clean slate, even if we re-run the script\n# in the same Python session.\nnest.ResetKernel()\n\n# Import math, we need Pi\nimport math\n```\n\n Configurable Parameters\n =======================\n\n Here we define those parameters that we take to be\n configurable. The choice of configurable parameters is obviously\n arbitrary, and in practice one would have far more configurable\n parameters. We restrict ourselves to:\n\n - Network size in neurons ``N``, each layer is ``N x N``.\n - Network size in subtended visual angle ``visSize``, in degree.\n - Temporal frequency of drifting grating input ``f_dg``, in Hz.\n - Spatial wavelength and direction of drifting grating input,\n   ``lambda_dg`` and ``phi_dg``, in degree/radian.\n - Background firing rate of retinal nodes and modulation amplitude,\n   ``retDC`` and ``retAC``, in Hz.\n - Simulation duration ``simtime``; actual simulation is split into\n   intervals of ``sim_interval`` length, so that the network state\n   can be visualized in those intervals. Times are in ms.\n\n\n```\nParams = {'N'           :     40,\n          'visSize'     :    8.0,\n          'f_dg'        :    2.0,\n          'lambda_dg'   :    2.0,\n          'phi_dg'      :    0.0,\n          'retDC'       :   30.0,\n          'retAC'       :   30.0,\n          'simtime'     :  100.0,\n          'sim_interval':    5.0\n          }\n```\n\n Neuron Models\n =============\n\n We declare models in two steps:\n\n 1. We define a dictionary specifying the NEST neuron model to use\n    as well as the parameters for that model.\n 2. We create three copies of this dictionary with parameters\n    adjusted to the three model variants specified in Table~2 of\n    Hill & Tononi (2005) (cortical excitatory, cortical inhibitory,\n    thalamic)\n\n In addition, we declare the models for the stimulation and\n recording devices.\n\n\n The general neuron model\n ------------------------\n\n We use the `iaf_cond_alpha` neuron, which is an\n integrate-and-fire neuron with two conductance-based synapses which\n have alpha-function time course.  Any input with positive weights\n will automatically directed to the synapse labeled `_ex`, any\n with negative weights to the synapes labeled `_in`.  We define\n **all** parameters explicitly here, so that no information is\n hidden in the model definition in NEST. `V_m` is the membrane\n potential to which the model neurons will be initialized.\n The model equations and parameters for the Hill-Tononi neuron model\n are given on pp. 1677f and Tables 2 and 3 in that paper. Note some\n peculiarities and adjustments:\n\n - Hill & Tononi specify their model in terms of the membrane time\n   constant, while the `iaf_cond_alpha` model is based on the\n   membrane capcitance. Interestingly, conducantces are unitless in\n   the H&T model. We thus can use the time constant directly as\n   membrane capacitance.\n - The model includes sodium and potassium leak conductances. We\n   combine these into a single one as follows:\n$$   \\begin{equation}-g_{NaL}(V-E_{Na}) - g_{KL}(V-E_K)\n      =\n   -(g_{NaL}+g_{KL})\\left(V-\\frac{g_{NaL}E_{NaL}+g_{KL}E_K}{g_{NaL}g_{KL}}\\right)\n   \\end{equation}\n$$\n - We write the resulting expressions for g_L and E_L explicitly\n   below, to avoid errors in copying from our pocket calculator.\n - The paper gives a range of 1.0-1.85 for g_{KL}, we choose 1.5\n   here.\n - The Hill-Tononi model has no explicit reset or refractory\n   time. We arbitrarily set V_reset and t_ref.\n - The paper uses double exponential time courses for the synaptic\n   conductances, with separate time constants for the rising and\n   fallings flanks. Alpha functions have only a single time\n   constant: we use twice the rising time constant given by Hill and\n   Tononi.\n - In the general model below, we use the values for the cortical\n   excitatory cells as defaults. Values will then be adapted below.\n\n\n\n```\nnest.CopyModel('iaf_cond_alpha', 'NeuronModel',\n               params = {'C_m'       :  16.0,\n                         'E_L'       : (0.2 * 30.0 + 1.5 * -90.0)/(0.2 + 1.5),\n                         'g_L'       : 0.2 + 1.5,\n                         'E_ex'      :   0.0,\n                         'E_in'      : -70.0,\n                         'V_reset'   : -60.0,\n                         'V_th'      : -51.0,\n                         't_ref'     :   2.0,\n                         'tau_syn_ex':   1.0,\n                         'tau_syn_in':   2.0,\n                         'I_e'       :   0.0,\n                         'V_m'       : -70.0})\n```\n\n Adaptation of models for different populations\n ----------------------------------------------\n\n We must copy the `NeuronModel` dictionary explicitly, otherwise\n Python would just create a reference.\n\n\n```\n# Cortical excitatory cells\n# .........................\n# Parameters are the same as above, so we need not adapt anything\nnest.CopyModel('NeuronModel', 'CtxExNeuron')\n```\n\n\n```\n# Cortical inhibitory cells\n# .........................\nnest.CopyModel('NeuronModel', 'CtxInNeuron',\n               params = {'C_m'  :   8.0,\n                         'V_th' : -53.0,\n                         't_ref':   1.0})\n```\n\n\n```\n# Thalamic cells\n# ..............\nnest.CopyModel('NeuronModel', 'ThalamicNeuron',\n               params = {'C_m'  :   8.0,\n                         'V_th' : -53.0,\n                         't_ref':   1.0,\n                         'E_in' : -80.0})\n```\n\n Input generating nodes\n ----------------------\n\n Input is generated by sinusoidally modulating Poisson generators,\n organized in a square layer of retina nodes. These nodes require a\n slightly more complicated initialization than all other elements of\n the network:\n\n - Average firing rate ``DC``, firing rate modulation depth ``AC``, and\n   temporal modulation frequency ``Freq`` are the same for all retinal\n   nodes and are set directly below.\n - The temporal phase ``Phi`` of each node depends on its position in\n   the grating and can only be assigned after the retinal layer has\n   been created. We therefore specify a function for initalizing the\n   phase ``Phi``. This function will be called for each node.\n\n\n```\ndef phiInit(pos, lam, alpha):\n    '''Initializer function for phase of drifting grating nodes.\n\n       pos  : position (x,y) of node, in degree\n       lam  : wavelength of grating, in degree\n       alpha: angle of grating in radian, zero is horizontal\n\n       Returns number to be used as phase of AC Poisson generator.\n    '''\n    return 2.0 * math.pi / lam * (math.cos(alpha) * pos[0] + math.sin(alpha) * pos[1])\n\nnest.CopyModel('sinusoidal_poisson_generator', 'RetinaNode',\n               params = {'ac'    : Params['retAC'],\n                         'dc'    : Params['retDC'],\n                         'freq'  : Params['f_dg'],\n                         'phi'   : 0.0,\n                         'individual_spike_trains': False})\n```\n\n Recording nodes\n ---------------\n\n We use the new `multimeter` device for recording from the model\n neurons. At present, `iaf_cond_alpha` is one of few models\n supporting `multimeter` recording.  Support for more models will\n be added soon; until then, you need to use `voltmeter` to record\n from other models.\n\n We configure multimeter to record membrane potential to membrane\n potential at certain intervals to memory only. We record the GID of\n the recorded neurons, but not the time.\n\n\n```\nnest.CopyModel('multimeter', 'RecordingNode',\n               params = {'interval'   : Params['sim_interval'],\n                         'record_from': ['V_m'],\n                         'record_to'  : ['memory'],\n                         'withgid'    : True,\n                         'withtime'   : False})\n```\n\n Populations\n ===========\n\n We now create the neuron populations in the model, again in the\n form of Python dictionaries. We define them in order from eye via\n thalamus to cortex.\n\n We first define a dictionary defining common properties for all\n populations\n\n\n```\nlayerProps = {'rows'     : Params['N'],\n              'columns'  : Params['N'],\n              'extent'   : [Params['visSize'], Params['visSize']],\n              'edge_wrap': True}\n# This dictionary does not yet specify the elements to put into the\n# layer, since they will differ from layer to layer. We will add them\n# below by updating the `'elements'` dictionary entry for each\n# population.\n```\n\nRetina\n------\n\n\n```\nlayerProps.update({'elements': 'RetinaNode'})\nretina = topo.CreateLayer(layerProps)\n\n# Now set phases of retinal oscillators; we use a list comprehension instead\n# of a loop.\n[nest.SetStatus([n], {\"phi\": phiInit(topo.GetPosition([n])[0],\n                                      Params[\"lambda_dg\"],\n                                      Params[\"phi_dg\"])})\n for n in nest.GetLeaves(retina)[0]];\n```\n\n Thalamus\n --------\n \n  We first introduce specific neuron models for the thalamic relay\n cells and interneurons. These have identical properties, but by\n treating them as different models, we can address them specifically\n when building connections.\n\n\n```\n# We use a list comprehension to do the model copies.\n[nest.CopyModel('ThalamicNeuron', SpecificModel) for SpecificModel in ('TpRelay', 'TpInter')]\n\n# Now we can create the layer, with one relay cell and one\n# interneuron per location:\nlayerProps.update({'elements': ['TpRelay', 'TpInter']})\nTp = topo.CreateLayer(layerProps)\n```\n\n Reticular nucleus\n -----------------\n We follow the same approach as above, even though we have only a\n single neuron in each location.\n\n\n```\n[nest.CopyModel('ThalamicNeuron', SpecificModel) for SpecificModel in ('RpNeuron',)]\nlayerProps.update({'elements': 'RpNeuron'})\nRp = topo.CreateLayer(layerProps)\n```\n\n Primary visual cortex\n ---------------------\n\n We follow again the same approach. We differentiate neuron types\n between layers and between pyramidal cells and interneurons. At\n each location, there are two pyramidal cells and one interneuron in\n each of layers 2-3, 4, and 5-6. Finally, we need to differentiate\n between vertically and horizontally tuned populations. When creating\n the populations, we create the vertically and the horizontally\n tuned populations as separate populations.\n\n\n```\n# We use list comprehesions to create all neuron types:\n[nest.CopyModel('CtxExNeuron', layer+'pyr') for layer in ('L23','L4','L56')]\n[nest.CopyModel('CtxInNeuron', layer+'in' ) for layer in ('L23','L4','L56')]\n\n# Now we can create the populations, suffixes h and v indicate tuning\nlayerProps.update({'elements': ['L23pyr', 2, 'L23in', 1,\n                                'L4pyr' , 2, 'L4in' , 1,\n                                'L56pyr', 2, 'L56in', 1]})\nVp_h = topo.CreateLayer(layerProps)\nVp_v = topo.CreateLayer(layerProps)\n```\n\n Collect all populations\n -----------------------\n\n\n```\n# For reference purposes, e.g., printing, we collect all populations\n# in a tuple:\npopulations = (retina, Tp, Rp, Vp_h, Vp_v)\n```\n\nInspection\n----------\n\n\n```\n# We can now look at the network using `PrintNetwork`:\nnest.PrintNetwork()\n\n# We can also try to plot a single layer in a network. For\n# simplicity, we use Rp, which has only a single neuron per position.\ntopo.PlotLayer(Rp)\npylab.title('Layer Rp')\npylab.show()\n```\n\n   Synapse models\n ==============\n\n Actual synapse dynamics, e.g., properties such as the synaptic time\n course, time constants, reversal potentials, are properties of\n neuron models in NEST and we set them in section `Neuron models`_\n above. When we refer to *synapse models* in NEST, we actually mean\n connectors which store information about connection weights and\n delays, as well as port numbers at the target neuron (`rport`)\n and implement synaptic plasticity. The latter two aspects are not\n relevant here.\n\n We just use NEST's `static_synapse` connector but copy it to\n synapse models `AMPA` and `GABA_A` for the sake of\n explicitness. Weights and delays are set as needed in section\n `Connections`_ below, as they are different from projection to\n projection. De facto, the sign of the synaptic weight decides\n whether input via a connection is handle by the `_ex` or the\n `_in` synapse.\n\n\n```\nnest.CopyModel('static_synapse', 'AMPA')\nnest.CopyModel('static_synapse', 'GABA_A')\n```\n\n Connections\n ====================\n\n Building connections is the most complex part of network\n construction. Connections are specified in Table 1 in the\n Hill-Tononi paper. As pointed out above, we only consider AMPA and\n GABA_A synapses here.  Adding other synapses is tedious work, but\n should pose no new principal challenges. We also use a uniform in\n stead of a Gaussian distribution for the weights.\n\n The model has two identical primary visual cortex populations,\n `Vp_v` and `Vp_h`, tuned to vertical and horizonal gratings,\n respectively. The *only* difference in the connection patterns\n between the two populations is the thalamocortical input to layers\n L4 and L5-6 is from a population of 8x2 and 2x8 grid locations,\n respectively. Furthermore, inhibitory connection in cortex go to\n the opposing orientation population as to the own.\n\n To save us a lot of code doubling, we thus defined properties\n dictionaries for all connections first and then use this to connect\n both populations. We follow the subdivision of connections as in\n the Hill & Tononi paper.\n\n **Note:** Hill & Tononi state that their model spans 8 degrees of\n visual angle and stimuli are specified according to this. On the\n other hand, all connection patterns are defined in terms of cell\n grid positions. Since the NEST Topology Module defines connection\n patterns in terms of the extent given in degrees, we need to apply\n the following scaling factor to all lengths in connections:\n\n\n```\ndpc = Params['visSize'] / (Params['N'] - 1)\n\n# We will collect all same-orientation cortico-cortical connections in\nccConnections = []\n# the cross-orientation cortico-cortical connections in\nccxConnections = []\n# and all cortico-thalamic connections in\nctConnections = []\n```\n\n Horizontal intralaminar\n -----------------------\n *Note:* \"Horizontal\" means \"within the same cortical layer\" in this\n case.\n\n\n```\n# We first define a dictionary with the (most) common properties for\n# horizontal intralaminar connection. We then create copies in which\n# we adapt those values that need adapting, and\nhorIntraBase = {\"connection_type\": \"divergent\",\n                \"synapse_model\": \"AMPA\",\n                \"mask\": {\"circular\": {\"radius\": 12.0 * dpc}},\n                \"kernel\": {\"gaussian\": {\"p_center\": 0.05, \"sigma\": 7.5 * dpc}},\n                \"weights\": 1.0,\n                \"delays\": {\"uniform\": {\"min\": 1.75, \"max\": 2.25}}}\n```\n\n\n```\n# We use a loop to do the for for us. The loop runs over a list of\n# dictionaries with all values that need updating\nfor conn in [{\"sources\": {\"model\": \"L23pyr\"}, \"targets\": {\"model\": \"L23pyr\"}},\n             {\"sources\": {\"model\": \"L23pyr\"}, \"targets\": {\"model\": \"L23in\" }},\n             {\"sources\": {\"model\": \"L4pyr\" }, \"targets\": {\"model\": \"L4pyr\" },\n              \"mask\"   : {\"circular\": {\"radius\": 7.0 * dpc}}},\n             {\"sources\": {\"model\": \"L4pyr\" }, \"targets\": {\"model\": \"L4in\"  },\n              \"mask\"   : {\"circular\": {\"radius\": 7.0 * dpc}}},\n             {\"sources\": {\"model\": \"L56pyr\"}, \"targets\": {\"model\": \"L56pyr\" }},\n             {\"sources\": {\"model\": \"L56pyr\"}, \"targets\": {\"model\": \"L56in\"  }}]:\n    ndict = horIntraBase.copy()\n    ndict.update(conn)\n    ccConnections.append(ndict)\n```\n\n Vertical intralaminar\n -----------------------\n *Note:* \"Vertical\" means \"between cortical layers\" in this\n case.\n\n\n```\n# We proceed as above.\nverIntraBase = {\"connection_type\": \"divergent\",\n                \"synapse_model\": \"AMPA\",\n                \"mask\": {\"circular\": {\"radius\": 2.0 * dpc}},\n                \"kernel\": {\"gaussian\": {\"p_center\": 1.0, \"sigma\": 7.5 * dpc}},\n                \"weights\": 2.0,\n                \"delays\": {\"uniform\": {\"min\": 1.75, \"max\": 2.25}}}\n```\n\n\n```\nfor conn in [{\"sources\": {\"model\": \"L23pyr\"}, \"targets\": {\"model\": \"L56pyr\"}, \"weights\": 1.0},\n             {\"sources\": {\"model\": \"L23pyr\"}, \"targets\": {\"model\": \"L23in\" }, \"weights\": 1.0},\n             {\"sources\": {\"model\": \"L4pyr\" }, \"targets\": {\"model\": \"L23pyr\"}},\n             {\"sources\": {\"model\": \"L4pyr\" }, \"targets\": {\"model\": \"L23in\" }},\n             {\"sources\": {\"model\": \"L56pyr\"}, \"targets\": {\"model\": \"L23pyr\"}},\n             {\"sources\": {\"model\": \"L56pyr\"}, \"targets\": {\"model\": \"L23in\" }},\n             {\"sources\": {\"model\": \"L56pyr\"}, \"targets\": {\"model\": \"L4pyr\" }},\n             {\"sources\": {\"model\": \"L56pyr\"}, \"targets\": {\"model\": \"L4in\"  }}]:\n    ndict = verIntraBase.copy()\n    ndict.update(conn)\n    ccConnections.append(ndict)\n```\n\n Intracortical inhibitory\n ------------------------\n\n We proceed as above, with the following difference: each connection\n is added to the same-orientation and the cross-orientation list of\n connections.\n\n **Note:** Weights increased from -1.0 to -2.0, to make up for missing GabaB\n\n\n```\n# Note that we have to specify the **weight with negative sign** to make\n# the connections inhibitory.\nintraInhBase = {\"connection_type\": \"divergent\",\n                \"synapse_model\": \"GABA_A\",\n                \"mask\": {\"circular\": {\"radius\": 7.0 * dpc}},\n                \"kernel\": {\"gaussian\": {\"p_center\": 0.25, \"sigma\": 7.5 * dpc}},\n                \"weights\": -2.0,\n                \"delays\": {\"uniform\": {\"min\": 1.75, \"max\": 2.25}}}\n```\n\n\n```\n# We use a loop to do the for for us. The loop runs over a list of\n# dictionaries with all values that need updating\nfor conn in [{\"sources\": {\"model\": \"L23in\"}, \"targets\": {\"model\": \"L23pyr\"}},\n             {\"sources\": {\"model\": \"L23in\"}, \"targets\": {\"model\": \"L23in\" }},\n             {\"sources\": {\"model\": \"L4in\" }, \"targets\": {\"model\": \"L4pyr\" }},\n             {\"sources\": {\"model\": \"L4in\" }, \"targets\": {\"model\": \"L4in\"  }},\n             {\"sources\": {\"model\": \"L56in\"}, \"targets\": {\"model\": \"L56pyr\"}},\n             {\"sources\": {\"model\": \"L56in\"}, \"targets\": {\"model\": \"L56in\" }}]:\n    ndict = intraInhBase.copy()\n    ndict.update(conn)\n    ccConnections.append(ndict)\n    ccxConnections.append(ndict)\n```\n\n Corticothalamic\n ---------------\n\n\n```\ncorThalBase = {\"connection_type\": \"divergent\",\n               \"synapse_model\": \"AMPA\",\n               \"mask\": {\"circular\": {\"radius\": 5.0 * dpc}},\n               \"kernel\": {\"gaussian\": {\"p_center\": 0.5, \"sigma\": 7.5 * dpc}},\n               \"weights\": 1.0,\n               \"delays\": {\"uniform\": {\"min\": 7.5, \"max\": 8.5}}}\n```\n\n\n```\n# We use a loop to do the for for us. The loop runs over a list of\n# dictionaries with all values that need updating\nfor conn in [{\"sources\": {\"model\": \"L56pyr\"}, \"targets\": {\"model\": \"TpRelay\" }},\n             {\"sources\": {\"model\": \"L56pyr\"}, \"targets\": {\"model\": \"TpInter\" }}]:\n    ndict = intraInhBase.copy()\n    ndict.update(conn)\n    ctConnections.append(ndict)\n```\n\n Corticoreticular\n ----------------\n\n\n```\n# In this case, there is only a single connection, so we write the\n# dictionary itself; it is very similar to the corThalBase, and to\n# show that, we copy first, then update. We need no `targets` entry,\n# since Rp has only one neuron per location.\ncorRet = corThalBase.copy()\ncorRet.update({\"sources\": {\"model\": \"L56pyr\"}, \"weights\": 2.5})\n```\n\n Build all connections beginning in cortex\n -----------------------------------------\n\n\n```\n# Cortico-cortical, same orientation\nprint(\"Connecting: cortico-cortical, same orientation\")\n[topo.ConnectLayers(Vp_h, Vp_h, conn) for conn in ccConnections]\n[topo.ConnectLayers(Vp_v, Vp_v, conn) for conn in ccConnections]\n\n# Cortico-cortical, cross-orientation\nprint(\"Connecting: cortico-cortical, other orientation\")\n[topo.ConnectLayers(Vp_h, Vp_v, conn) for conn in ccxConnections]\n[topo.ConnectLayers(Vp_v, Vp_h, conn) for conn in ccxConnections]\n\n# Cortico-thalamic connections\nprint(\"Connecting: cortico-thalamic\")\n[topo.ConnectLayers(Vp_h, Tp, conn) for conn in ctConnections]\n[topo.ConnectLayers(Vp_v, Tp, conn) for conn in ctConnections]\ntopo.ConnectLayers(Vp_h, Rp, corRet)\ntopo.ConnectLayers(Vp_v, Rp, corRet)\n```\n\n    Connecting: cortico-cortical, same orientation\n    Connecting: cortico-cortical, other orientation\n    Connecting: cortico-thalamic\n\n\n Thalamo-cortical connections\n ----------------------------\n  **Note:** According to the text on p. 1674, bottom right, of\n the Hill & Tononi paper, thalamocortical connections are\n created by selecting from the thalamic population for each\n L4 pyramidal cell, ie, are *convergent* connections.\n\n\n```\nthalCorRect = {\"connection_type\": \"convergent\",\n               \"sources\": {\"model\": \"TpRelay\"},\n               \"synapse_model\": \"AMPA\",\n               \"weights\": 5.0,\n               \"delays\": {\"uniform\": {\"min\": 2.75, \"max\": 3.25}}}\n\nprint(\"Connecting: thalamo-cortical\")\n```\n\n    Connecting: thalamo-cortical\n\n\n\n```\n# Horizontally tuned\nthalCorRect.update({\"mask\": {\"rectangular\": {\"lower_left\" : [-4.0*dpc, -1.0*dpc],\n                                             \"upper_right\": [ 4.0*dpc,  1.0*dpc]}}})\nfor conn in [{\"targets\": {\"model\": \"L4pyr\" }, \"kernel\": 0.5},\n             {\"targets\": {\"model\": \"L56pyr\"}, \"kernel\": 0.3}]:\n    thalCorRect.update(conn)\n    topo.ConnectLayers(Tp, Vp_h, thalCorRect)\n```\n\n\n```\n# Vertically tuned\nthalCorRect.update({\"mask\": {\"rectangular\": {\"lower_left\" : [-1.0*dpc, -4.0*dpc],\n                                             \"upper_right\": [ 1.0*dpc,  4.0*dpc]}}})\nfor conn in [{\"targets\": {\"model\": \"L4pyr\" }, \"kernel\": 0.5},\n             {\"targets\": {\"model\": \"L56pyr\"}, \"kernel\": 0.3}]:\n    thalCorRect.update(conn)\n    topo.ConnectLayers(Tp, Vp_v, thalCorRect)\n```\n\n\n```\n# Diffuse connections\nthalCorDiff = {\"connection_type\": \"convergent\",\n               \"sources\": {\"model\": \"TpRelay\"},\n               \"synapse_model\": \"AMPA\",\n               \"weights\": 5.0,\n               \"mask\": {\"circular\": {\"radius\": 5.0 * dpc}},\n               \"kernel\": {\"gaussian\": {\"p_center\": 0.1, \"sigma\": 7.5 * dpc}},\n               \"delays\": {\"uniform\": {\"min\": 2.75, \"max\": 3.25}}}\n```\n\n\n```\nfor conn in [{\"targets\": {\"model\": \"L4pyr\" }},\n             {\"targets\": {\"model\": \"L56pyr\"}}]:\n    thalCorDiff.update(conn)\n    topo.ConnectLayers(Tp, Vp_h, thalCorDiff)\n    topo.ConnectLayers(Tp, Vp_v, thalCorDiff)\n```\n\n Thalamic connections\n --------------------\n\n Connections inside thalamus, including Rp\n\n *Note:* In Hill & Tononi, the inhibition between Rp cells is mediated by\n GABA_B receptors. We use GABA_A receptors here to provide some self-dampening\n of Rp.\n\n **Note:** The following code had a serious bug in v. 0.1: During the first\n iteration of the loop, \"synapse_model\" and \"weights\" were set to \"AMPA\" and \"0.1\",\n respectively and remained unchanged, so that all connections were created as\n excitatory connections, even though they should have been inhibitory. We now\n specify synapse_model and weight explicitly for each connection to avoid this.\n\n\n```\nthalBase = {\"connection_type\": \"divergent\",\n            \"delays\": {\"uniform\": {\"min\": 1.75, \"max\": 2.25}}}\n\nprint(\"Connecting: intra-thalamic\")\n\nfor src, tgt, conn in [(Tp, Rp, {\"sources\": {\"model\": \"TpRelay\"},\n                                 \"synapse_model\": \"AMPA\",\n                                 \"mask\": {\"circular\": {\"radius\": 2.0 * dpc}},\n                                 \"kernel\": {\"gaussian\": {\"p_center\": 1.0, \"sigma\": 7.5 * dpc}},\n                                 \"weights\": 2.0}),\n                       (Tp, Tp, {\"sources\": {\"model\": \"TpInter\"},\n                                 \"targets\": {\"model\": \"TpRelay\"},\n                                 \"synapse_model\": \"GABA_A\",\n                                 \"weights\": -1.0,\n                                 \"mask\": {\"circular\": {\"radius\": 2.0 * dpc}},\n                                 \"kernel\": {\"gaussian\": {\"p_center\": 0.25, \"sigma\": 7.5 * dpc}}}),\n                       (Tp, Tp, {\"sources\": {\"model\": \"TpInter\"},\n                                 \"targets\": {\"model\": \"TpInter\"},\n                                 \"synapse_model\": \"GABA_A\",\n                                 \"weights\": -1.0,\n                                 \"mask\": {\"circular\": {\"radius\": 2.0 * dpc}},\n                                 \"kernel\": {\"gaussian\": {\"p_center\": 0.25, \"sigma\": 7.5 * dpc}}}),\n                       (Rp, Tp, {\"targets\": {\"model\": \"TpRelay\"},\n                                 \"synapse_model\": \"GABA_A\",\n                                 \"weights\": -1.0,\n                                 \"mask\": {\"circular\": {\"radius\": 12.0 * dpc}},\n                                 \"kernel\": {\"gaussian\": {\"p_center\": 0.15, \"sigma\": 7.5 * dpc}}}),\n                       (Rp, Tp, {\"targets\": {\"model\": \"TpInter\"},\n                                 \"synapse_model\": \"GABA_A\",\n                                 \"weights\": -1.0,\n                                 \"mask\": {\"circular\": {\"radius\": 12.0 * dpc}},\n                                 \"kernel\": {\"gaussian\": {\"p_center\": 0.15, \"sigma\": 7.5 * dpc}}}),\n                       (Rp, Rp, {\"targets\": {\"model\": \"RpNeuron\"},\n                                 \"synapse_model\": \"GABA_A\",\n                                 \"weights\": -1.0,\n                                 \"mask\": {\"circular\": {\"radius\": 12.0 * dpc}},\n                                 \"kernel\": {\"gaussian\": {\"p_center\": 0.5, \"sigma\": 7.5 * dpc}}})]:\n    thalBase.update(conn)\n    topo.ConnectLayers(src, tgt, thalBase)\n```\n\n    Connecting: intra-thalamic\n\n\n Thalamic input\n --------------\n\n Input to the thalamus from the retina.\n\n **Note:** Hill & Tononi specify a delay of 0 ms for this connection.\n\n\n```\n# We use 1 ms here.\nretThal = {\"connection_type\": \"divergent\",\n           \"synapse_model\": \"AMPA\",\n           \"mask\": {\"circular\": {\"radius\": 1.0 * dpc}},\n           \"kernel\": {\"gaussian\": {\"p_center\": 0.75, \"sigma\": 2.5 * dpc}},\n           \"weights\": 10.0,\n           \"delays\": 1.0}\n\nprint(\"Connecting: retino-thalamic\")\n\nfor conn in [{\"targets\": {\"model\": \"TpRelay\"}},\n             {\"targets\": {\"model\": \"TpInter\"}}]:\n    retThal.update(conn)\n    topo.ConnectLayers(retina, Tp, retThal)\n```\n\n    Connecting: retino-thalamic\n\n\n Checks on connections\n ---------------------\n\n As a very simple check on the connections created, we inspect\n the connections from the central node of various layers.\n\n\n```\n# Connections from Retina to TpRelay\ntopo.PlotTargets(topo.FindCenterElement(retina), Tp, 'TpRelay', 'AMPA')\npylab.title('Connections Retina -> TpRelay')\npylab.show()\n\n# Connections from TpRelay to L4pyr in Vp (horizontally tuned)\ntopo.PlotTargets(topo.FindCenterElement(Tp), Vp_h, 'L4pyr', 'AMPA')\npylab.title('Connections TpRelay -> Vp(h) L4pyr')\npylab.show()\n\n# Connections from TpRelay to L4pyr in Vp (vertically tuned)\ntopo.PlotTargets(topo.FindCenterElement(Tp), Vp_v, 'L4pyr', 'AMPA')\npylab.title('Connections TpRelay -> Vp(v) L4pyr')\npylab.show()\n```\n\n Recording devices\n =================\n\n This recording device setup is a bit makeshift. For each population\n we want to record from, we create one `multimeter`, then select\n all nodes of the right model from the target population and\n connect. `loc` is the subplot location for the layer.\n\n\n```\nprint(\"Connecting: Recording devices\")\nrecorders = {}\nfor name, loc, population, model in [('TpRelay'   , 1, Tp  , 'TpRelay'),\n                                     ('Rp'        , 2, Rp  , 'RpNeuron'),\n                                     ('Vp_v L4pyr', 3, Vp_v, 'L4pyr'),\n                                     ('Vp_h L4pyr', 4, Vp_h, 'L4pyr')]:\n    recorders[name] = (nest.Create('RecordingNode'), loc)\n    tgts = [nd for nd in nest.GetLeaves(population)[0]\n            if nest.GetStatus([nd], 'model')[0]==model]\n    nest.Connect(recorders[name][0], tgts)   # one recorder to all targets\n```\n\n    Connecting: Recording devices\n\n\n Example simulation\n ====================\n\n This simulation is set up to create a step-wise visualization of\n the membrane potential. To do so, we simulate `sim_interval`\n milliseconds at a time, then read out data from the multimeters,\n clear data from the multimeters and plot the data as pseudocolor\n plots.\n\n\n```\n# show time during simulation\nnest.SetStatus([0],{'print_time': True})\n\n# lower and upper limits for color scale, for each of the four\n# populations recorded.\nvmn=[-80,-80,-80,-80]\nvmx=[-50,-50,-50,-50]\n\nnest.Simulate(Params['sim_interval'])\n\n# loop over simulation intervals\nfor t in pylab.arange(Params['sim_interval'], Params['simtime'], Params['sim_interval']):\n\n    # do the simulation\n    nest.Simulate(Params['sim_interval'])\n\n    # clear figure and choose colormap\n    pylab.clf()\n    pylab.jet()\n\n    # now plot data from each recorder in turn, assume four recorders\n    for name, r in recorders.items():\n        rec = r[0]\n        sp = r[1]\n        pylab.subplot(2,2,sp)\n        d = nest.GetStatus(rec)[0]['events']['V_m']\n\n        if len(d) != Params['N']**2:\n            # cortical layer with two neurons in each location, take average\n            d = 0.5 * ( d[::2] + d[1::2] )\n\n        # clear data from multimeter\n        nest.SetStatus(rec, {'n_events': 0})\n        pylab.imshow(pylab.reshape(d, (Params['N'],Params['N'])),\n                     aspect='equal', interpolation='nearest',\n                     extent=(0,Params['N']+1,0,Params['N']+1),\n                     vmin=vmn[sp-1], vmax=vmx[sp-1])\n        pylab.colorbar()\n        pylab.title(name + ', t = %6.1f ms' % nest.GetKernelStatus()['time'])\n\n    pylab.draw()  # force drawing inside loop\n    pylab.show()  # required by `pyreport`\n\n\n# just for some information at the end\nprint(nest.GetKernelStatus())\n```\n\n\n```\n\n```\n", "meta": {"hexsha": "3da5a18715b4a99506ca9fd552dcde8d68e280e1", "size": 985534, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "4_hill_tononi.ipynb", "max_stars_repo_name": "ixaxaar/nestlings", "max_stars_repo_head_hexsha": "74da791e3bf613b2bd9985b38bb93c75466daa6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-03-04T03:08:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-02T21:01:28.000Z", "max_issues_repo_path": "4_hill_tononi.ipynb", "max_issues_repo_name": "ixaxaar/nestlings", "max_issues_repo_head_hexsha": "74da791e3bf613b2bd9985b38bb93c75466daa6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-09-16T17:17:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-17T08:34:17.000Z", "max_forks_repo_path": "4_hill_tononi.ipynb", "max_forks_repo_name": "ixaxaar/nestlings", "max_forks_repo_head_hexsha": "74da791e3bf613b2bd9985b38bb93c75466daa6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-08-28T19:44:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-02T21:01:35.000Z", "avg_line_length": 607.6041923551, "max_line_length": 74557, "alphanum_fraction": 0.9282916673, "converted": true, "num_tokens": 8896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2877678157610531, "lm_q2_score": 0.05665242530797383, "lm_q1q2_score": 0.016302744688441836}}
{"text": "```python\nimport os\nimport numpy as np\nimport pickle\n```\n\n\n```python\nfrom __future__ import print_function\nimport mxnet as mx\nfrom mxnet import nd, autograd\nfrom mxnet import gluon\nmx.random.seed(1)\n```\n\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\n\n```python\nroot_path = os.getcwd()\n```\n\n## 1. Prepare Dataset\n\nExample:\n\n\n```python\n!python prepare_data.py --data-path data/omniglot --save-path data/omniglot\n```\n\n### 1.1 Build Self-defined Iterator\n\n\n```python\ntrain_data = os.path.join(root_path, \"omniglot\", \"train.pickle\")\nval_data = os.path.join(root_path, \"omniglot\", \"val.pickle\")\n```\n\n\n```python\nclass Data_Loader:\n    \"\"\"\n    batch: (batch_size, channel, height, width)\n    \"\"\"\n    def __init__(self, path):\n        self.data = {}\n        self.chars = {}\n        self.n_chars = {}\n        self.h = 105\n        self.w = 105\n        self.n_images = 20\n        with open(os.path.join(path,\"train.pickle\"),\"rb\") as f:\n            (tr_imgs, tr_char) = pickle.load(f)\n            self.data['train'] = tr_imgs\n            self.chars[\"train\"] = tr_char\n            self.n_chars[\"train\"] = len(tr_char.keys())\n            \n        with open(os.path.join(path,\"val.pickle\"),\"rb\") as f:\n            (va_imgs, va_char) = pickle.load(f)\n            self.data['val'] = va_imgs\n            self.chars[\"val\"] = va_char\n            self.n_chars[\"val\"] = len(va_char.keys())\n                       \n    def get_batch(self, batch_size, case=\"train\"):\n        \"\"\"\n        return #batch_size pairs and corresponding labels\n        \"\"\"\n        cur_data = self.data[case]\n        cur_chars = self.chars[case]        \n        cur_labels = cur_chars.keys()\n        \n        img0 = mx.nd.empty([batch_size, 1, self.h, self.w])\n        img1 = mx.nd.empty([batch_size, 1, self.h, self.w])\n        tmp = mx.nd.uniform(low=0, high=1, shape=(batch_size,))        \n        targets = mx.nd.rint(tmp)\n        \n        for i in range(batch_size):\n            if targets[i].asscalar() != 1:\n                # pairs are different chars\n                labels = np.random.choice(cur_labels, size=2, replace=False)\n                idxes = np.random.choice(self.n_images, size=2)\n                img0[i, 0, :, :] = cur_data[labels[0]][idxes[0]].T\n                img1[i, 0, :, :] = cur_data[labels[1]][idxes[1]].T               \n            else:\n                # pairs are from same char\n                label = np.random.choice(cur_labels)\n                idxes = np.random.choice(self.n_images, size=2, replace=False)\n                img0[i, 0, :, :] = cur_data[label][idxes[0]].T\n                img1[i, 0, :, :] = cur_data[label][idxes[1]].T\n                \n        return img0, img1, targets\n    \n    def get_test_batch(self, support_size, case=\"val\", gt=None):\n        \"\"\"\n        return pairs and corresponding labels\n        batch: (support_size, 1, height, width)\n        \"\"\"\n        cur_data = self.data[case]\n        cur_chars = self.chars[case]        \n        cur_labels = cur_chars.keys()\n        \n        img0 = mx.nd.empty([support_size, 1, self.h, self.w])\n        img1 = mx.nd.empty([support_size, 1, self.h, self.w])\n        targets = mx.nd.zeros((support_size,))\n        \n        labels = np.random.choice(cur_labels, size=support_size, replace=False)\n        \n        gt_idx = np.random.randint(support_size)\n        true_label = labels[gt_idx]\n        targets[gt_idx] = 1\n        \n        if gt:\n            true_label = gt\n            labels[gt_idx] = gt\n        \n        idxes = np.random.choice(self.n_images, size=support_size)\n        for i in range(support_size):\n            img0[i, 0, :, :] = cur_data[true_label][idxes[gt_idx]].T\n            img1[i, 0, :, :] = cur_data[labels[i]][idxes[i]].T\n                \n        return img0, img1, targets        \n        \n    \n    def evaluate_accuracy(self, net, eval_size, support_size, ctx, top_k=0, case=\"val\"):\n        \"\"\"\n        calculate accuracy over #eval_size test task, each task with a supporting set of #support_size\n        \"\"\"\n        n_correct = 0\n        n_correct_topk = 0\n        \n        for i in range(eval_size):\n            img0, img1, targets = self.get_test_batch(support_size, case)\n            img0 = img0.as_in_context(ctx)\n            img1 = img1.as_in_context(ctx)\n            targets = targets.as_in_context(ctx)\n            \n            score = net(img0, img1)\n            \n            targets_np = targets.asnumpy()\n            score_np = score.asnumpy().flatten()\n            true_idx = np.argmax(targets_np)\n            pred_idx = np.argmax(score_np)\n                                   \n            \n            if (targets[pred_idx]).asscalar() > 0:\n                n_correct += 1\n                n_correct_topk += 1\n            else:                \n                if top_k > 0:\n                    topk_inds = np.argpartition(score_np, -top_k)[-top_k:]\n                    if true_idx in topk_inds:\n                        n_correct_topk += 1            \n        \n        acc = 100.0 * (n_correct*1.0 / eval_size)\n        acc_topk = 100.0 * (n_correct_topk*1.0 / eval_size)\n        return acc, acc_topk\n```\n\n\n```python\npkl_path = os.path.join(root_path, \"omniglot\")\nloader = Data_Loader(pkl_path)\n```\n\n\n```python\n# check one generated batch\nimg0, img1, targets = loader.get_batch(batch_size=4)\n#img0, img1, targets = loader.get_test_batch(support_size=5)\n```\n\n\n```python\nprint(targets)\nfor j in range(4):\n    plt.subplot(1,2,1)\n    plt.imshow(img0[j,0,:,:].T.asnumpy(), cmap='gray'); \n    plt.subplot(1,2,2)\n    plt.imshow(img1[j,0,:,:].T.asnumpy(), cmap='gray'); \n    plt.show()\n```\n\n## 2. Build Network\n\n\n```python\ninput_shape = (105, 105, 1)\nnum_fc = 4096\nnum_outputs = 1\n```\n\n\n```python\nclass Siamese(gluon.Block):\n    def __init__(self, **kwargs):\n        super(Siamese, self).__init__(**kwargs)\n        # use name_scope to give child Blocks appropriate names.\n        # It also allows sharing Parameters between Blocks recursively.\n        with self.name_scope():\n            self.wing = gluon.nn.Sequential()\n            with self.wing.name_scope():\n                self.wing.add(gluon.nn.Conv2D(channels=64, kernel_size=10, activation='relu'))\n                self.wing.add(gluon.nn.MaxPool2D(pool_size=2, strides=2))\n                self.wing.add(gluon.nn.Conv2D(channels=128, kernel_size=7, activation='relu'))\n                self.wing.add(gluon.nn.MaxPool2D(pool_size=2, strides=2))\n                self.wing.add(gluon.nn.Conv2D(channels=128, kernel_size=4, activation='relu'))\n                self.wing.add(gluon.nn.MaxPool2D(pool_size=2, strides=2))\n                self.wing.add(gluon.nn.Conv2D(channels=256, kernel_size=4, activation='relu'))\n                # The Flatten layer collapses all axis, except the first one, into one axis.\n                self.wing.add(gluon.nn.Flatten())\n                self.wing.add(gluon.nn.Dense(4096, activation=\"sigmoid\"))\n            \n            self.fc = gluon.nn.Dense(1, activation=\"sigmoid\")\n\n    def forward(self, input0, input1):\n        out0 = self.wing(input0)\n        out1 = self.wing(input1)\n        dist = mx.ndarray.abs(out0 - out1)\n        score = self.fc(dist)\n        return score\n```\n\n\n```python\ndef count_params(params):\n    cnt = 0\n    for k in params.keys():\n        cur_size = params[k].shape\n        cur_cnt = reduce(lambda x,y: x*y, cur_size)\n        print(\"Params: {}: {}\".format(k, cur_cnt))\n        cnt += cur_cnt\n    return cnt\n```\n\n## 3. Define Loss\n### Regularized Cross-Entropy\n\n\\begin{equation}\nL(x_1, x_2, t) = t* \\log({\\bf{p}} (x_1,x_2)) + (1-t)* \\log(1-{\\bf{p}}(x_1,x_2)) + \\lambda \\|w \\|_2\n\\end{equation}\n\n\n```python\nce_loss = gluon.loss.SigmoidBinaryCrossEntropyLoss(from_sigmoid=True)\n```\n\n## 4. Training\n\n\n```python\nctx = mx.gpu()\nn_iters = 10\nbatch_size = 16\n\neval_size = 500\nsupport_size = 16\ntop_k = 3\n\nfrom_scratch = True\nmodel_path = os.path.join(root_path, \"siamese_checkpoints\")\n```\n\n\n```python\nnet = Siamese()\n```\n\n\n```python\nif from_scratch: \n    net.collect_params().initialize(mx.init.Xavier(),ctx=ctx)\nelse:\n    ckpt_name = os.path.join(model_path, \"siamese_net_80.params\")\n    net.load_params(ckpt_name, ctx=ctx)\n```\n\n\n```python\ntrainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': 0.0003, 'wd': 0.001})\n```\n\n\n```python\nloss_every = 5\neval_every = 5000\ncnt = 0\nbest = 99\n\nloss_train = []\nacc_eval = []\nacc_topk_eval = []\n\nfor i in range(n_iters):\n    img0, img1, targets = loader.get_batch(batch_size=batch_size) \n    img0 = img0.as_in_context(ctx)\n    img1 = img1.as_in_context(ctx)\n    targets = targets.as_in_context(ctx)\n    with autograd.record():\n        preds = net(img0, img1)\n        loss = ce_loss(preds, targets)        \n    loss.backward()          \n    trainer.step(batch_size)\n    \n    tr_loss = nd.mean(loss).asscalar()\n    loss_train.append(tr_loss)\n    \n    if i % loss_every == 0:\n        print(\"iteration {}, training loss: {:.4f},\".format(i, tr_loss))\n        \n    if i % eval_every == 0:\n        val_acc, val_acc_topk = loader.evaluate_accuracy(net,eval_size, support_size, ctx, top_k=top_k)\n        print(\"iteration {}, top-1 accuracy: {:.4f}%, top-{} accuracy: {:.4f}%\".format(i, val_acc, top_k, val_acc_topk))\n        acc_eval.append(val_acc)\n        acc_topk_eval.append(val_acc_topk)\n        cnt += 1\n        if val_acc >= best:            \n            print(\"saving model ---------->\")\n            best=val_acc\n            save_name = \"siamese_net_\" + str(cnt) + \".params\"\n            file_path = os.path.join(model_path, save_name)\n            net.save_params(file_path)\n            break\n```\n\n    iteration 0, training loss: 0.6743,\n    iteration 0, top-1 accuracy: 14.6000%, top-3 accuracy: 44.8000%\n    iteration 5, training loss: 0.8142,\n\n\n\n```python\nparams = net.collect_params()\ncount_params(params)\n```\n\n    Params: siamese0_sequential0_conv0_weight: 6400\n    Params: siamese0_sequential0_conv0_bias: 64\n    Params: siamese0_sequential0_conv1_weight: 401408\n    Params: siamese0_sequential0_conv1_bias: 128\n    Params: siamese0_sequential0_conv2_weight: 262144\n    Params: siamese0_sequential0_conv2_bias: 128\n    Params: siamese0_sequential0_conv3_weight: 524288\n    Params: siamese0_sequential0_conv3_bias: 256\n    Params: siamese0_sequential0_dense0_weight: 37748736\n    Params: siamese0_sequential0_dense0_bias: 4096\n    Params: siamese0_dense0_weight: 4096\n    Params: siamese0_dense0_bias: 1\n\n\n\n\n\n    38951745L\n\n\n\n## 5. Sample Test\n\n\n```python\nimg0, img1, targets = loader.get_test_batch(support_size)\nimg0 = img0.as_in_context(ctx)\nimg1 = img1.as_in_context(ctx)\ntargets = targets.as_in_context(ctx)\n```\n\n\n```python\nscore = net(img0, img1)\n```\n\n\n```python\ntargets_np = targets.asnumpy()\nscore_np = score.asnumpy().flatten()\n```\n\n\n```python\npred_idx = np.argmax(score_np)\ntopk_inds = np.argpartition(score_np, -3)[-3:]\npreds = np.zeros(support_size,)\npreds[pred_idx] = 1\n```\n\n\n```python\n# plot the characters which has scores in top-3\nfor j in range(3):\n    plt.subplot(1,2,1)\n    plt.imshow(img0[topk_inds[j],0,:,:].T.asnumpy(), cmap='gray'); \n    plt.subplot(1,2,2)\n    plt.imshow(img1[topk_inds[j],0,:,:].T.asnumpy(), cmap='gray'); \n    plt.show()\n```\n\n\n```python\ntargets_np\n```\n\n\n\n\n    array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,\n            0.,  0.,  0.], dtype=float32)\n\n\n\n\n```python\npreds\n```\n\n\n\n\n    array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,\n            0.,  0.,  0.])\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "2c50743931a5831e6363414cf825d36a5ae322b8", "size": 57209, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "SiameseNetwork-Omniglot-final.ipynb", "max_stars_repo_name": "muchuanyun/siamese_network_on_omniglot", "max_stars_repo_head_hexsha": "7c6b4505b67bcee9314f5a5542bd884140f00709", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2017-11-29T11:29:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-01T18:46:42.000Z", "max_issues_repo_path": "SiameseNetwork-Omniglot-final.ipynb", "max_issues_repo_name": "muchuanyun/siamese_network_on_omniglot", "max_issues_repo_head_hexsha": "7c6b4505b67bcee9314f5a5542bd884140f00709", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-03-02T09:23:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-01T18:50:13.000Z", "max_forks_repo_path": "SiameseNetwork-Omniglot-final.ipynb", "max_forks_repo_name": "muchuanyun/siamese_network_on_omniglot", "max_forks_repo_head_hexsha": "7c6b4505b67bcee9314f5a5542bd884140f00709", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-10-08T09:05:47.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-08T09:05:47.000Z", "avg_line_length": 76.4826203209, "max_line_length": 5520, "alphanum_fraction": 0.7861175689, "converted": true, "num_tokens": 3210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451353339458, "lm_q2_score": 0.04672495480968185, "lm_q1q2_score": 0.01629042819309403}}
{"text": "```python\nimport sys\n# install ipython dependencies\ndep = ['pip', 'scipy', 'numpy', 'matplotlib', 'sympy', 'utm', 'netcdf4']\nfor lib in dep:\n    print(lib)\n    !{sys.executable} -m pip install {lib}\n\n```\n\n    pip\n    Requirement already satisfied: pip in /usr/local/Cellar/jupyterlab/3.0.16/libexec/lib/python3.9/site-packages (21.1.2)\n    scipy\n    Requirement already satisfied: scipy in /usr/local/Cellar/jupyterlab/3.0.16/libexec/lib/python3.9/site-packages (1.6.3)\n    Requirement already satisfied: numpy<1.23.0,>=1.16.5 in /usr/local/Cellar/jupyterlab/3.0.16/libexec/lib/python3.9/site-packages (from scipy) (1.20.3)\n    numpy\n    Requirement already satisfied: numpy in /usr/local/Cellar/jupyterlab/3.0.16/libexec/lib/python3.9/site-packages (1.20.3)\n    matplotlib\n    Requirement already satisfied: matplotlib in /usr/local/Cellar/jupyterlab/3.0.16/libexec/lib/python3.9/site-packages (3.4.2)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/Cellar/jupyterlab/3.0.16/libexec/lib/python3.9/site-packages (from matplotlib) (1.3.1)\n    Requirement already satisfied: numpy>=1.16 in /usr/local/Cellar/jupyterlab/3.0.16/libexec/lib/python3.9/site-packages (from matplotlib) (1.20.3)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/Cellar/jupyterlab/3.0.16/libexec/lib/python3.9/site-packages (from matplotlib) (0.10.0)\n    Requirement already satisfied: python-dateutil>=2.7 in /usr/local/Cellar/jupyterlab/3.0.16/libexec/lib/python3.9/site-packages (from matplotlib) (2.8.1)\n    Requirement already satisfied: pyparsing>=2.2.1 in /usr/local/Cellar/jupyterlab/3.0.16/libexec/lib/python3.9/site-packages (from matplotlib) (2.4.7)\n    Requirement already satisfied: pillow>=6.2.0 in /usr/local/Cellar/jupyterlab/3.0.16/libexec/lib/python3.9/site-packages (from matplotlib) (8.2.0)\n    Requirement already satisfied: six in /usr/local/Cellar/jupyterlab/3.0.16/libexec/lib/python3.9/site-packages (from cycler>=0.10->matplotlib) (1.16.0)\n    sympy\n    Requirement already satisfied: sympy in /usr/local/Cellar/jupyterlab/3.0.16/libexec/lib/python3.9/site-packages (1.8)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/Cellar/jupyterlab/3.0.16/libexec/lib/python3.9/site-packages (from sympy) (1.2.1)\n    utm\n    Requirement already satisfied: utm in /usr/local/Cellar/jupyterlab/3.0.16/libexec/lib/python3.9/site-packages (0.7.0)\n    netcdf4\n    Requirement already satisfied: netcdf4 in /usr/local/Cellar/jupyterlab/3.0.16/libexec/lib/python3.9/site-packages (1.5.6)\n    Requirement already satisfied: numpy>=1.9 in /usr/local/Cellar/jupyterlab/3.0.16/libexec/lib/python3.9/site-packages (from netcdf4) (1.20.3)\n    Requirement already satisfied: cftime in /usr/local/Cellar/jupyterlab/3.0.16/libexec/lib/python3.9/site-packages (from netcdf4) (1.5.0)\n\n\n\n```python\n!{sys.executable} -m pip install --upgrade pip\n```\n\n    Requirement already satisfied: pip in /usr/local/Cellar/jupyterlab/3.0.16/libexec/lib/python3.9/site-packages (21.1.1)\n    Collecting pip\n      Downloading pip-21.1.2-py3-none-any.whl (1.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.5 MB 4.0 MB/s eta 0:00:01\n    \u001b[?25hInstalling collected packages: pip\n      Attempting uninstall: pip\n        Found existing installation: pip 21.1.1\n        Uninstalling pip-21.1.1:\n          Successfully uninstalled pip-21.1.1\n    Successfully installed pip-21.1.2\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "7b498c9d6a99d07a4a49fda2cee6c880058e980f", "size": 4709, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "install-dependencies.ipynb", "max_stars_repo_name": "oliver779/PDE3", "max_stars_repo_head_hexsha": "cdca09d610478573c1dae498196f299ebd39a082", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-19T15:08:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T15:42:34.000Z", "max_issues_repo_path": "install-dependencies.ipynb", "max_issues_repo_name": "oliver779/PDE3", "max_issues_repo_head_hexsha": "cdca09d610478573c1dae498196f299ebd39a082", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "install-dependencies.ipynb", "max_forks_repo_name": "oliver779/PDE3", "max_forks_repo_head_hexsha": "cdca09d610478573c1dae498196f299ebd39a082", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2022-01-24T07:03:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T12:06:03.000Z", "avg_line_length": 43.6018518519, "max_line_length": 163, "alphanum_fraction": 0.6345296241, "converted": true, "num_tokens": 1084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18242553269617784, "lm_q2_score": 0.08882028878220906, "lm_q1q2_score": 0.016203088495322836}}
{"text": "```\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```\ncurrent_path = '/content/drive/My Drive/Colab Notebooks/Project_GANder/gankook_cuda/semantic-segmentation-pytorch/pytorch_room_layout/'\n\nimport os\nos.chdir(current_path)\n!ls\n```\n\n     build\t\t        info.json\t        segment_st.py\n     cv2_requirements.txt   lsun.pth.tar\t       'sunrgbd (1).zip'\n     datasets\t        lu_vp_detect.egg-info   sunrgbd.pth.tar\n     data_transforms.py     pics\t\t        test_result\n     dist\t\t        __pycache__\t        Vanish_Point_Detection\n     drn_d_105_024_val      README.md\t        visualize.m\n     drn_d_105_024_val_ms   requirements.txt        XiaohuLuVPDetection\n     drn.py\t\t        segment_lsun.py\n     features\t        segment_rl.py\n\n\n### Get Vanishing point, inliers\n\n\n```\n# !python XiaohuLuVPDetection/setup.py build\n# !python XiaohuLuVPDetection/setup.py install\n!pip install -r cv2_requirements.txt\n```\n\n    Collecting opencv-python==4.0.0.21\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/37/49/874d119948a5a084a7ebe98308214098ef3471d76ab74200f9800efeef15/opencv_python-4.0.0.21-cp36-cp36m-manylinux1_x86_64.whl (25.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 25.4MB 1.6MB/s \n    \u001b[?25hCollecting opencv-contrib-python==4.0.0.21\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1f/c0/0463d91f297521b2e15e3d682d7077557fe773db72a03a0d2dba899ab8a5/opencv_contrib_python-4.0.0.21-cp36-cp36m-manylinux1_x86_64.whl (31.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 31.2MB 190kB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.11.3 in /usr/local/lib/python3.6/dist-packages (from opencv-python==4.0.0.21->-r cv2_requirements.txt (line 1)) (1.19.5)\n    \u001b[31mERROR: albumentations 0.1.12 has requirement imgaug<0.2.7,>=0.2.5, but you'll have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Installing collected packages: opencv-python, opencv-contrib-python\n      Found existing installation: opencv-python 4.1.2.30\n        Uninstalling opencv-python-4.1.2.30:\n          Successfully uninstalled opencv-python-4.1.2.30\n      Found existing installation: opencv-contrib-python 4.1.2.30\n        Uninstalling opencv-contrib-python-4.1.2.30:\n          Successfully uninstalled opencv-contrib-python-4.1.2.30\n    Successfully installed opencv-contrib-python-4.0.0.21 opencv-python-4.0.0.21\n\n\n\n```\nimport cv2\ncv2.__version__\n```\n\n\n\n\n    '4.0.0'\n\n\n\n### Functions\n\n\n```\nfrom PIL import Image\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom XiaohuLuVPDetection.lu_vp_detect.vp_detection import VPDetection\nimport time\n# import os\nimport cv2\n# import pylab as pl\nfrom skimage import morphology as mp\nimport sys\n```\n\n\n```\n#             Detect Intersection             #\nimport math\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler\nfrom sklearn.cluster import KMeans\nfrom sympy import Line\nfrom sympy.geometry import Ray\n\n\ndef drawLines(img, lines, color=(255,255,255)):\n    \"\"\"\n    Draw lines on an image\n    \"\"\"\n    for line in lines:\n        for rho,theta in line:\n          a = np.cos(theta)\n          b = np.sin(theta)\n          x0 = a*rho\n          y0 = b*rho\n          x1 = int(x0 + 1000*(-b))\n          y1 = int(y0 + 1000*(a))\n          x2 = int(x0 - 1000*(-b))\n          y2 = int(y0 - 1000*(a))\n\n          slope = (y1 - y0) / float(x1 - x0)\n          angle = math.degrees(math.atan(slope))\n          # if abs(angle) < 70:\n          cv2.line(img, (x1,y1), (x2,y2), color, 1)\n\ndef line(p1, p2):\n    A = (p1[1] - p2[1])\n    B = (p2[0] - p1[0])\n    C = (p1[0]*p2[1] - p2[0]*p1[1])\n    return A, B, -C\n\ndef intersection2(L1, L2):\n    D  = L1[0] * L2[1] - L1[1] * L2[0]\n    Dx = L1[2] * L2[1] - L1[1] * L2[2]\n    Dy = L1[0] * L2[2] - L1[2] * L2[0]\n    if D != 0:\n        x = Dx / D\n        y = Dy / D\n        return x,y\n    else:\n        return False\n\n\ndef regression(img, x, y, color=(255, 0, 0), axis=1):\n\n  if axis == 1:\n    y_at_border = np.array([0, img.shape[0]])\n    p = np.polyfit(y, x, deg=1)\n    x_at_border = np.poly1d(p)(y_at_border)\n  else:\n    x_at_border = np.array([0, img.shape[1]])\n    p = np.polyfit(x, y, deg=1)\n    y_at_border = np.poly1d(p)(x_at_border)\n\n  cv2.line(img, (int(x_at_border[0]), int(y_at_border[0])), (int(x_at_border[1]), int(y_at_border[1])), color, 2)\n\n  return x_at_border, y_at_border\n\n\ndef find_reg_points(img, lines, color=(255,0,0), drawlines=False):\n\n  centroids = list()\n  r_xs = list()\n  r_ys = list()\n  for line_ in lines:\n      for rho,theta in line_:\n          a = np.cos(theta)\n          b = np.sin(theta)\n          x0 = a*rho\n          y0 = b*rho\n          x1 = int(x0 + 1000*(-b))\n          y1 = int(y0 + 1000*(a))\n          x2 = int(x0 - 1000*(-b))\n          y2 = int(y0 - 1000*(a))\n\n          slope = (y1 - y0) / float(x1 - x0)\n          angle = math.degrees(math.atan(slope))\n          if abs(angle) > 80:\n            # print(img.shape[1])\n            h_layout = line((0, 0), (img.shape[1], 0))\n            h_layout_lower = line((0, img.shape[0]), (img.shape[1], img.shape[0]))\n            r = intersection2(h_layout, line((x1, y1), (x2, y2)))\n            r_lower = intersection2(h_layout_lower, line((x1, y1), (x2, y2)))\n            # cv2.line(img, (int(x1), int(y1)), (int(x2), int(y2)), color, 2)\n\n            center_p = (int((r[0] + r_lower[0]) / 2), int((r[1] + r_lower[1])/ 2))\n            centroids.append(center_p)\n\n            r_xs.append((r[0], r_lower[0]))\n            r_ys.append((r[1], r_lower[1]))\n\n            if drawlines:\n              cv2.line(img, (int(r[0]), int(r[1])), (int(r_lower[0]), int(r_lower[1])), color, 2)\n              cv2.circle(img, center_p, 10, (255, 0, 255), -1)\n\n  if drawlines:\n    cv2.line(img, (int(0), int(0)), (int(0), int(img.shape[0])), color, 2)\n    cv2.line(img, (int(img.shape[1]), int(0)), (int(img.shape[1]), int(img.shape[0])), color, 2)\n    cv2.circle(img, (0, int(img.shape[0] / 2)), 10, (255, 0, 255), -1)\n    cv2.circle(img, (img.shape[1], int(img.shape[0] / 2)), 10, (255, 0, 255), -1)\n  centroids.append((0, int(img.shape[0] / 2)))\n  centroids.append((img.shape[1], int(img.shape[0] / 2)))\n\n  return r_xs, r_ys, centroids   \n\nfrom scipy.spatial import distance as sci_dist\n\ndef order_points(pts):\n\n  xSorted = pts[np.argsort(pts[:, 0]), :]\n  leftMost = xSorted[:2, :]\n  rightMost = xSorted[2:, :]\n  leftMost = leftMost[np.argsort(leftMost[:, 1]), :]\n  (tl, bl) = leftMost\n  D = sci_dist.cdist(tl[np.newaxis], rightMost, \"euclidean\")[0]\n  (br, tr) = rightMost[np.argsort(D)[::-1], :]\n\n  return np.array([tl, tr, br, bl], dtype=\"float32\")\n\n\ndef get_vline_points_inborder(vpd, img, show_vline=False):\n\n  vpd.find_vps(img)\n  # vps = vpd.vps_2D\n  vl_img, vl_list = vpd.create_debug_VP_image(show_vl=True)\n\n\n  vl_list_for_vline = vl_list\n  vl_img_for_vline = vl_img.copy()\n\n  # print('#       Used vl_list for vline work       #')\n  # print('vl_list')\n  # print()\n\n  #           Extract Vertical line            #\n  h_border = Line((0, 0), (img.shape[1], 0))\n  h_border_lower = Line((0, img.shape[0]), (img.shape[1], img.shape[0]))\n\n  reg_xs = list()\n  reg_ys = list()\n  v_lines = list()\n  # h_lines_xrange = list()\n  for vl in vl_list_for_vline:\n      x0, y0, x1, y1 = vl\n      slope = (y1 - y0) / float(x1 - x0)\n      angle = math.degrees(math.atan(slope))\n      # print(angle)\n      if abs(angle) > 80:\n        # cv2.line(skl_copy, (int(x1), int(y1)), (int(x0), int(y0)), (255, 0, 0), 3,\n        #                  cv2.LINE_AA)\n        v_line = Line((x0, y0), (x1, y1))\n        [top_point] = v_line.intersection(h_border)\n        [bot_point] = v_line.intersection(h_border_lower)\n        # v_lines.append()\n        reg_xs.append((float(top_point[0]), float(bot_point[0])))\n        reg_ys.append((float(top_point[1]), float(bot_point[1])))\n\n      # if abs(angle) < 70:\n      #   h_lines_xrange.append((min(x0, x1), max(x0, x1)))\n\n\n  # print('#        Before Sorting      #')\n  # print('reg_xs :', reg_xs)\n  \n  \n  center_xs = list()\n  for reg_x, reg_y in zip(reg_xs, reg_ys):\n    center_xs.append(np.mean(reg_x))\n    #           Draw Line         #\n    regression(vl_img_for_vline, reg_x, reg_y)\n    \n  if show_vline:\n    plt.imshow(vl_img_for_vline)\n    plt.title('Divided Session')\n    plt.show()\n\n  sorted_index = list()\n  sorted_center_xs = sorted(center_xs)\n\n  for center_x in sorted_center_xs:\n    # print('center_x :', center_x)\n    sorted_index.append(center_xs.index(center_x))\n  print('sorted_index :', sorted_index)   #\n\n  sorted_reg_xs = list()\n  sorted_reg_ys = list()\n  for s_index in sorted_index:\n    sorted_reg_xs.append(reg_xs[s_index])\n    sorted_reg_ys.append(reg_ys[s_index])\n  reg_xs = sorted_reg_xs\n  reg_ys = sorted_reg_ys\n\n  print()\n  # print(\"#        After Sorting       #\")\n  # print('reg_xs :', reg_xs)\n  # print()\n\n  return reg_xs\n\n\ndef remove_outlier_angle(vl_list, copy_vl_list, angle_list, limit_angle=15):\n\n    if len(vl_list) != 0:\n      copy_angle_list = angle_list.copy()\n      mean_angle_list = np.array(angle_list).mean()\n      # print('mean_angle_list :', mean_angle_list)\n      # print('angle_list :', angle_list)\n      print('max angle_list gap : ', max(angle_list) - mean_angle_list)\n\n      for angle_index, angle in enumerate(copy_angle_list):\n        if abs(angle - mean_angle_list) > limit_angle:\n          vl_list.remove(copy_vl_list[angle_index])\n          # angle_list.remove(copy_angle_list[angle_index])\n\n      return\n\ndef get_hline_points_inborder(img, left_border, right_border, vl_list, top_vl, bot_vl, top_down_ratio=0.66):\n\n  ex_top_vl = list()\n  ex_bot_vl = list()\n\n  for vl in vl_list:\n\n    x0, y0, x1, y1 = vl\n    l1 = Line((x0, y0), (x1, y1))\n    #     v_border line     #\n    [left_point] = l1.intersection(left_border)\n    # print('left_point :', left_point)\n    [right_point] = l1.intersection(right_border)\n\n    #      Figure out current vl is top / bottom vl     #\n    if vl in top_vl:\n      if (left_point[1] < img.shape[0] * top_down_ratio and right_point[1] < img.shape[0] * top_down_ratio):\n          ex_top_vl.append((left_point[0], left_point[1], right_point[0], right_point[1]))\n\n    elif vl in bot_vl:\n      if (left_point[1] > img.shape[0] * (1 - top_down_ratio) and right_point[1] > img.shape[0] * (1 - top_down_ratio)):\n          ex_bot_vl.append((left_point[0], left_point[1], right_point[0], right_point[1]))\n\n  return ex_top_vl, ex_bot_vl\n\n\ndef toppest_bottest_vl(img, top_vl, bot_vl, direction):\n\n    max_y = 0\n    min_y = img.shape[0]\n    toppest_vl = None\n    bottest_vl = None\n    index = 1 if direction == 'right' else 3\n\n    for vl in top_vl:\n      if vl[index] < min_y:\n        toppest_vl = vl\n        min_y = vl[index]\n\n    for vl in bot_vl:\n      if vl[index] > max_y:\n        bottest_vl = vl\n        max_y = vl[index]\n\n    return toppest_vl, bottest_vl\n\n\ndef line_mirroring(src_vl, src_point, left_border, right_border):\n\n    x0, y0, x1, y1 = src_vl\n    slope = (y1 - y0) / float(x1 - x0)\n    angle = - math.degrees(math.atan(slope))\n\n    #       white_max_y \ub97c - toppest_vl angle \ub85c \uc9c0\ub098\ub294 \uc9c1\uc120      #\n    print('src_point :', src_point)\n    print('angle :', angle)\n    endy = 100 * math.sin(math.radians(angle))\n    endx = 100 * math.cos(math.radians(angle))\n    temp_vl = Line(src_point, (src_point[0] + endx, src_point[1] + endy))\n    [left_point] = temp_vl.intersection(left_border)\n    [right_point] = temp_vl.intersection(right_border)\n    # print('left_point :', left_point)\n    mirrored_vl = (float(left_point[0]), float(left_point[1]), float(right_point[0]), float(right_point[1]))\n\n    return mirrored_vl\n\n\ndef choose_4points(toppest_vl, bottest_vl, src_point, left_border, right_border, parallel):\n\n  x1, y1, x0, y0 = toppest_vl\n  if parallel:\n    top_line = Line((x1, y1), (x0, y0))\n    print('top_line.slope :', float(top_line.slope))            \n    if abs(top_line.slope) < 0.05:\n        src_point = (0, 0)\n    parallel_tl = top_line.parallel_line(src_point)\n\n    [tl] = parallel_tl.intersection(left_border)\n    [tr] = parallel_tl.intersection(right_border)\n    br, bl = bottest_vl[2:], bottest_vl[:2]\n  else:\n    tl, tr, br, bl = toppest_vl[:2], toppest_vl[2:], bottest_vl[2:], bottest_vl[:2]\n\n  return tl, tr, br, bl\n\n\ndef top_bot_mask(mask_img, threshold=1/10):\n\n    top_white_cnt = 0\n    bot_white_cnt = 0\n    white_min_x = mask_img.shape[1]\n    white_max_x = 0\n    white_min_y = mask_img.shape[0]\n    white_max_y = 0\n    temp_min_y = white_min_y\n    temp_max_y = white_max_y\n    min_x_coord, max_x_coord, min_y_coord, max_y_coord = None, None, None, None\n    top_parallel = False\n    bot_parallel = False\n    for i in range(mask_img.shape[1]):\n\n      #     Check Top Condition     #\n      for j in range(int(mask_img.shape[0] * threshold)):\n        # if mask_img[j][i] == 255 and j < thr_min_y:\n          # thr_min_y = j\n          # thr_min_y_coord = (i, j)\n        if mask_img[j][i] == 255:\n          top_white_cnt += 1\n          if i > white_max_x:\n            white_max_x = i\n            max_x_coord = (i, j)\n          if i < white_min_x:\n            white_min_x = i\n            min_x_coord = (i, j)\n\n          if j < temp_min_y:\n            temp_min_y = j\n            temp_min_y_coord = (i, j)\n\n      #           Middle Condition        #\n      for j in range(int(mask_img.shape[0] * threshold), int(mask_img.shape[0] * (1 - threshold))):\n        if mask_img[j][i] == 255:\n          if j > white_max_y:\n            white_max_y = j\n            max_y_coord = (i, j)\n          if j < white_min_y:\n            white_min_y = j\n            min_y_coord = (i, j)\n\n      #     Check Bot Condition   #\n      for j in range(int(mask_img.shape[0] * (1 - threshold)), mask_img.shape[0]):\n        # if mask_img[j][i] == 255 and j < thr_min_y:\n          # thr_min_y = j\n          # thr_min_y_coord = (i, j)\n        if mask_img[j][i] == 255:\n          bot_white_cnt += 1\n          if j > temp_max_y:\n            temp_max_y = j\n            temp_max_y_coord = (i, j)\n\n    if top_white_cnt / (mask_img.shape[1] * int(mask_img.shape[0] * threshold)) > 0.5:\n      top_parallel = True\n      min_y_coord = temp_min_y_coord\n    \n    if bot_white_cnt / (mask_img.shape[1] * int(mask_img.shape[0] * threshold)) > 0.5:\n      #     \ubc14\ub2e5\uc740 \ud3c9\ud589 \uc774\ub3d9 \uc0ac\uc6a9\ud558\uc9c0 \uc54a\ub294\ub2e4.    #\n      # bot_parallel = True\n      max_y_coord = temp_max_y_coord\n\n    return min_x_coord, max_x_coord, min_y_coord, max_y_coord, top_parallel, bot_parallel\n\n\ndef crop_and_warp(refer, vl_img, src_4p, dst_4p):\n\n\n  #       Crop      #\n  refered = np.asarray(refer)[:vl_img.shape[0], :vl_img.shape[1]]\n\n  # plt.imshow(refered)\n  # plt.title('refered')\n  # plt.show()\n\n  # compute the perspective transform matrix and then apply it\n  matrix = cv2.getPerspectiveTransform(src_4p, dst_4p)\n  refered = cv2.warpPerspective(refered, matrix, (refered.shape[1], refered.shape[0]))\n\n  return refered\n```\n\n\n```\n#     Refering for one image data   #\ndef synthesize(org_image, refer_image, vpd, object_, scale_factor=None, show_img=False):\n\n  #       Layout Part       #\n  # img = Image.open(layout_path + image)\n  # # print(type(img))\n  # img_np = np.invert(np.asarray(img))\n  # # print(img_np.max(), img_np.min())\n  # ret, thr = cv2.threshold(img_np, 254, 255, cv2.THRESH_BINARY_INV)\n\n  #       Mask Part         #\n  org_color_np, org_np = np.split(np.asarray(org_image), 2, axis=1)\n\n  # plt.subplot(131)\n  # plt.imshow(org)\n  # plt.show()\n  img_size = (org_np.shape[1], org_np.shape[0])\n  \n\n  # refer = Image.open(refer_path)\n  refer = np.asarray(refer_image)\n\n  #     refer_size\uc640 img_size\uac00 \ub3d9\uc77c\ud558\uac70\ub098 refer_size\uac00 \uc791\uc740 \uacbd\uc6b0\ub97c \uace0\ub824\ud574\uc57c\ud55c\ub2e4.     #\n  print('scale_factor :', scale_factor)\n  refer = np.tile(refer, (scale_factor, scale_factor, 1))\n  print('refer.shape :', refer.shape)\n  # size_ratio = math.floor(min((refer.shape[0] / (org_np.shape[0] * 1.5)), (refer.shape[1] / (org_np.shape[1] * 1.5))))\n  size_ratio = min((refer.shape[0] / (org_np.shape[0] * 1.5)), (refer.shape[1] / (org_np.shape[1] * 1.5)))\n  print('size_ratio :', size_ratio)\n  refer = Image.fromarray(refer).resize((int(refer.shape[1] / size_ratio), int(refer.shape[0] / size_ratio)))\n\n  org_color_np2 = org_color_np.copy()\n  org_np = org_np.astype(np.uint8)\n  org_np2 = org_np.copy()\n  org_np3 = org_np.copy()\n\n  start = time.time()\n  \n  if object_ == 'wall':\n      \n    #                   Find Best Vline_list                #\n    kernel = np.ones((10, 10), np.uint8)\n\n    org_np2_morp = cv2.morphologyEx(org_np2, cv2.MORPH_CLOSE, kernel)\n    org_np2_copy = org_np2_morp.copy()\n    # org_np2_copy_gray = cv2.cvtColor(org_np2_copy, cv2.COLOR_RGB2GRAY)\n\n    ret, thr_org_np2 = cv2.threshold(org_np2_copy, 127, 255, cv2.THRESH_BINARY)\n    thr_org_np2 = cv2.morphologyEx(thr_org_np2, cv2.MORPH_CLOSE, kernel)\n    thr_org_np2_copy = thr_org_np2.copy()\n\n    edge_org_np2 = cv2.Canny(org_np2_morp, 20, 100)\n    edge_org_np2_copy = edge_org_np2.copy()\n    edge_org_np2_copy2 = cv2.Canny((org_np2_copy / 255. * org_np2_copy).astype(np.uint8), 20, 60)\n    \n    reg_xs = get_vline_points_inborder(vpd, edge_org_np2_copy2)\n    print('#            Used vl_list for vline work          #')\n    print('edge_org_np2_copy2')\n    print()\n\n    #                                     Find Best Hline                                      #\n    #     vline \uc774 \uc874\uc7ac\ud558\uc9c0 \uc54a\ub294 \uacbd\uc6b0\ub3c4 \uace0\ub824\ud574\uc57c\ud55c\ub2e4.     #\n    if len(reg_xs) == 0:\n      reg_xs.append([0, 0])\n      # reg_ys.append([0, org_np2.shape[0]])\n      \n    #         Divide Session by vline       #\n    for reg_index, reg_x in enumerate(reg_xs):\n\n\n      #     In a Session     #\n      #     1.  find vanishing point    #\n      #     2.  Find 3 points (vp, top & bottom points)     #\n      #     3.  Do warfine and attach to the black plane      #\n\n      print(\"#      Session Status      #\")\n      print('reg_index, reg_x :', reg_index, reg_x)\n      \n      #     0.  crop by vline     #\n            #   Find Max_x, min_x, (Max_y, min_y = org.shape[0], 0)\n            #   1.    \uc6b0\ud3b8\uc5d0 \ud55c\ud574\uc11c max_x = \uc6b0\ud3b8 vline max_x & min_x = \ud604\uc7ac vline min_x\n            #   2.    \uc88c\ud3b8\uc5d0 \ud55c\ud574\uc11c max_x = \ud604\uc7ac Max_x & min_x = \uc88c\ud3b8 vline min_x\n\n      #      vline \ubcc4\ub85c \uc591\uc606\uc73c\ub85c \uc791\uc5c5\uc744 \ud558\uba74 len(vline) = 1\uc758 \uc791\uc5c5\uc744 \ubc18\ubcf5\ud560 \ud544\uc694\uac00 \uc5c6\uc5b4\uc9c4\ub2e4.    #\n      iter = False\n      while True:\n\n        #                   We need Max, min x & y                #\n        # four_inters = list()\n        find_pair = True\n        # centroid_inters = all_centroid_inters[inters_i]\n\n        if not iter:\n\n          #       \uc624\ub978\ucabd \ub05d vline \uc774\uba74        #\n          if reg_index == len(reg_xs) - 1:\n            print('rightest vline')\n            #   1.    \uc6b0\ud3b8\uc5d0 \ud55c\ud574\uc11c max_x = \uc6b0\ud3b8 vline max_x & min_x = \ud604\uc7ac vline min_x\n            max_x = org_np.shape[1]\n            min_x = np.min(reg_x)\n\n          else:\n            print('middle vline')\n            next_reg_x = reg_xs[reg_index + 1]\n            max_x = np.max(next_reg_x)\n            if np.min(reg_x) < 0:\n              min_x = 0\n            else:\n              min_x = np.min(reg_x)\n\n        #     i = 0 \uc5d0 \ud55c\ud574\uc11c\ub9cc \uc67c\ucabd\uc73c\ub85c\ub3c4 refering \uc9c4\ud589, \ub098\uba38\uc9c0\ub294 \uc624\ub978\ucabd\uc73c\ub85c\ub9cc     #\n        else:\n            #   2.    \uc88c\ud3b8\uc5d0 \ud55c\ud574\uc11c max_x = \ud604\uc7ac Max_x & min_x = \uc88c\ud3b8 vline min_x\n            max_x = np.max(reg_x)\n            min_x = 0\n\n        print('min_x, max_x :', min_x, max_x)\n        # max_y = org_np.shape[0]\n        # min_y = 0\n\n        #     Make Session      #\n        session = org_np2[:, int(min_x):int(max_x)]\n        # plt.imshow(session)\n        # plt.show()\n\n\n        if (max_x - min_x) > 50:\n          length_thresh = 50\n        else:\n          length_thresh = 20\n          if max_x - min_x < 20:\n              #     i != 0 \uc778 \uacbd\uc6b0 break     #\n            if reg_index == 0 and np.sum(reg_xs) != 0 and not iter:\n              iter = True\n              print('iter :', iter)\n              continue\n            else:\n              break\n        \n        principal_point = None\n        focal_length = 1300 # 1102.79\n        seed = None\n        vpd = VPDetection(length_thresh, principal_point, focal_length, seed)\n\n        try:\n          vpd.find_vps(session)\n          # vps = vpd.vps_2D\n          vl_img, vl_list = vpd.create_debug_VP_image(show_vl=True)\n\n\n          #       Closing Morphing by OpenCV      #\n          kernel = np.ones((10, 10), np.uint8)\n          session = cv2.morphologyEx(session, cv2.MORPH_CLOSE, kernel)\n\n          #     Before Canny    #\n          session_prob = session / 255.\n\n          #     Multiply mask map with Edge => Erase Unnecessary vl line    #\n          #   multiply one time   #\n          session2 = session_prob * (session)\n          edge_session2 = cv2.Canny(session2.astype(np.uint8), 20, 60)\n          #       two time      #\n          # session2 = session_prob**2 * (session)\n          # edge_session2 = cv2.Canny(session2.astype(np.uint8), 20, 60)\n\n          vpd.find_vps(edge_session2)\n          # vps = vpd.vps_2D      \n          vl_edge_img2, vl_edge_list2 = vpd.create_debug_VP_image(show_vl=True)\n        \n        except Exception as e:\n          print(\"Error in vpd Sessions Zone :\", e)\n          print()\n            #     i != 0 \uc778 \uacbd\uc6b0 break     #\n          if reg_index == 0 and np.sum(reg_xs) != 0 and not iter:\n            iter = True\n            print('iter :', iter)\n            continue\n\n          else:\n            break\n\n\n        #         What is best vl_list      #\n        vl_list = vl_edge_list2\n        print('#            Used vl_list for hline work          #')\n        print('vl_edge_list2')\n        print()\n\n        h_lines = list()\n        # print('vps :', vps)\n\n        top_vl = list()\n        bot_vl = list()\n\n        left_vl_list = list()\n        right_vl_list = list()\n\n        left_angle = list()\n        right_angle = list()\n\n        for vl in vl_list:\n          x0, y0, x1, y1 = vl\n          slope = (y1 - y0) / float(x1 - x0)\n          angle = math.degrees(math.atan(slope))\n\n          if abs(angle) < 70:\n            if (y0 + y1) / 2 < vl_img.shape[0] / 2:\n              # print(y0, y1)\n              top_vl.append(vl)\n              if angle < 0:\n                left_vl_list.append(vl)\n                left_angle.append(abs(angle))\n              else:\n                right_vl_list.append(vl)\n                right_angle.append(abs(angle))\n            else:\n              bot_vl.append(vl)\n              if angle > 0:\n                left_vl_list.append(vl)\n                left_angle.append(abs(angle))\n              else:\n                right_vl_list.append(vl)\n                right_angle.append(abs(angle))\n            # cv2.line(skl_copy, (int(x1), int(y1)), (int(x0), int(y0)), (0, 0, 255), 2,\n            #                  cv2.LINE_AA)\n            h_lines.append(vl)\n          #   regression(vl_img, (x0, x1), (y0, y1), color=(0,255,255),axis=1)\n          \n        print('#        Original vl list        #')\n        print('len(left_vl_list) :', len(left_vl_list))\n        print('len(right_vl_list) :', len(right_vl_list))\n        print()\n\n        #             \uc18c\uc2e4\uc810 \ubc29\ud5a5 \uc120\ud0dd            #\n        #       original vl_list \ub294 remove \uac00 \uc874\uc7ac\ud558\uae30 \ub54c\ubb38\uc5d0 copy_ version \uc0ac\uc6a9\ud55c\ub2e4.       #\n        copy_left_vl_list = left_vl_list.copy()\n        copy_right_vl_list = right_vl_list.copy()\n        print('len(copy_left_vl_list) :', len(copy_left_vl_list))\n        print('len(copy_right_vl_list) :', len(copy_right_vl_list))\n\n        if len(copy_left_vl_list) >= len(copy_right_vl_list):\n          direction = 'left'\n          vl_list, copy_vl_list, angle = left_vl_list, copy_left_vl_list, left_angle\n        else:\n          direction = 'right'\n          vl_list, copy_vl_list, angle = right_vl_list, copy_right_vl_list, right_angle\n\n\n        print(\"#            Remove Outliered Angle in Hlines           #\")\n        remove_outlier_angle(vl_list, copy_vl_list, angle)\n        # remove_outlier_angle(right_vl_list, copy_right_vl_list, right_angle)\n        print()\n\n        print('len(left_vl_list) :', len(left_vl_list))\n        print('len(right_vl_list) :', len(right_vl_list))\n        print()\n\n        \n        # if len(left_vl_list) == 0 and len(right_vl_list) == 0:\n        if len(vl_list) == 0:\n          #     i != 0 \uc778 \uacbd\uc6b0 break     #\n          if reg_index == 0 and not iter:\n            iter = True\n            print('iter :', iter)\n            continue\n\n          else:\n            break\n        \n        #                       Find External vn_line                     #\n        l2 = Line((0, 0), (0, vl_img.shape[0]))\n        l3 = Line((vl_img.shape[1], 0), (vl_img.shape[1], vl_img.shape[0]))\n\n        ex_top_vl, ex_bot_vl = get_hline_points_inborder(vl_img, l2, l3, vl_list, top_vl, bot_vl)\n            \n\n        print()\n        print('#          Extended vl list left / right  TB Condition        #')\n        print('len(ex_top_vl) :', len(ex_top_vl))\n        print('len(ex_bot_vl) :', len(ex_bot_vl))\n        print()\n\n        #       find min max Line     #\n        toppest_vl, bottest_vl = toppest_bottest_vl(vl_img, ex_top_vl, ex_bot_vl, direction)\n\n\n        #       Figure out min_y & max_y of thr_session       #\n        # print('thr_session.shape :', thr_session.shape)\n        gray = cv2.cvtColor(session, cv2.COLOR_RGB2GRAY)\n        ret, thr_session = cv2.threshold(session, 127, 255, cv2.THRESH_BINARY)\n        thr_session = cv2.morphologyEx(thr_session, cv2.MORPH_CLOSE, kernel)\n        thr_session_gray = cv2.cvtColor(thr_session, cv2.COLOR_RGB2GRAY)\n        print('thr_session_gray.shape :', thr_session_gray.shape)\n\n        min_x_coord, max_x_coord, min_y_coord, max_y_coord, top_parallel, _ = top_bot_mask(thr_session_gray)\n        \n        \n        print('max_x_coord, min_x_coord :', max_x_coord, min_x_coord)\n        print('max_y_coord, min_y_coord :', max_y_coord, min_y_coord)\n\n        try:\n\n          #     None \uc774\ub77c\uba74 \ub300\uce6d\uc774\ub3d9\uc744 \ud1b5\ud574 \ub9cc\ub4e4\uc5b4\uc8fc\uc5b4\uc57c\ud55c\ub2e4.     #\n          if len(ex_bot_vl) == 0:\n            if toppest_vl is not None:\n              bottest_vl = line_mirroring(toppest_vl, max_y_coord, l2, l3)\n              print('bottest_vl :', bottest_vl)\n\n          elif len(ex_top_vl) == 0:\n            if bottest_vl is not None:\n              toppest_vl = line_mirroring(bottest_vl, min_y_coord, l2, l3)\n              print('toppest_vl :', toppest_vl)\n\n          for (x1, y1, x0, y0) in [toppest_vl, bottest_vl]:\n            cv2.line(vl_img, (int(x1), int(y1)), (int(x0), int(y0)), (0, 0, 255), 3, cv2.LINE_AA)\n\n        except Exception as e:\n          print('Error in drawing top, bot -est lines :', e)\n        \n          #     i != 0 \uc778 \uacbd\uc6b0 break     #\n          if reg_index == 0 and not iter:\n            iter = True\n            print('iter :', iter)\n            continue\n\n          else:\n            break\n          \n        #               Choose 4 points             #\n        tl, tr, br, bl = choose_4points(toppest_vl, bottest_vl, min_x_coord, l2, l3, top_parallel)\n          \n        #       Refering      #\n        #   tl, tr, br, bl    #\n        #     refer\ub97c \uc704\ud574 src_x => 0 \uc73c\ub85c \ub9de\ucdb0\uc900\ub2e4.    #\n        src = np.array([\n            [0, 0],\n            [vl_img.shape[1], 0],\n            [vl_img.shape[1], vl_img.shape[0]],\n            [0, vl_img.shape[0]]], dtype = \"float32\")\n        dst = np.array([list(tl),\n                        list(tr),\n                        list(br),\n                        list(bl)], dtype = \"float32\")\n\n        print()\n        print(\"#          Warping Points        #\")\n        print('src :', src)\n        print('dst :', dst)\n\n        refered = crop_and_warp(refer, vl_img, src, dst)\n        \n\n        org_color_np2[:, int(min_x):int(max_x)] = refered\n\n\n        #     i != 0 \uc778 \uacbd\uc6b0 break     #\n        if reg_index == 0 and np.sum(reg_xs) != 0 and not iter:\n          iter = True\n          print('iter :', iter)\n\n        else:\n          break\n  \n  elif object_ == 'floor':\n\n      # print(thr_org_np2.dtype)\n      thr_org_np2 = cv2.cvtColor(thr_org_np2, cv2.COLOR_RGB2GRAY)\n      contours, _ = cv2.findContours(thr_org_np2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n      min_height_point = np.array([[thr_org_np2.shape[0], thr_org_np2.shape[1]]])\n      # print(min_height_point)\n      for contour in contours:\n        # print(contour.shape)\n        for point in contour:\n          # print(point[0][1], min_height_point[0][1])\n          if 0 < point[0][1] <= min_height_point[0][1]:\n            # print(min_height_point[0][1])\n            min_height_point = point\n\n      dst = np.float32([min_height_point[0], [0, thr_org_np2.shape[1]], [thr_org_np2.shape[0], thr_org_np2.shape[1]]])\n      src = np.float32([[min_height_point[0][0], 0], [0, thr_org_np2.shape[1]], [thr_org_np2.shape[0], thr_org_np2.shape[1]]])\n      matrix = cv2.getAffineTransform(src, dst)\n\n      refer = np.asarray(refer)\n      refer = cv2.warpAffine(refer, matrix, (refer.shape[1], refer.shape[0]))\n      row, col, _ = org_color_np2.shape\n      org_color_np2 = refer[:row, :col]\n  \n  #         Refer\uc758 \uac80\uc740 \ubd80\ubd84\uc740 original image\ub85c \ucc44\uc6b4\ub2e4.       #\n  if object_ is None:    \n      # print('org_color_np2.shape :', org_color_np2.shape)\n      row, col, _ = org_color_np2.shape\n      org_color_np2 = np.array(refer)[:row, :col]\n\n  else:\n    org_color_np2 = np.where(org_color_np2 == 0, org_color_np, org_color_np2)\n  \n  print('elapsed time :', time.time() - start)\n  print()\n\n\n  # print('np.max(org_np) :', np.max(org_np))\n  org_np = org_np / 255.\n  refer = org_color_np2\n  # plt.show()\n\n  #     1.wall_mask * reference color image + (1 - wall_mask) * original_image)    #\n  syn_ = org_np * (refer) + (1 - org_np) * org_color_np\n  syn = org_np * syn_ + (1 - org_np) * org_color_np\n\n  #       Brightness Preservation      #\n  org_hsv = cv2.cvtColor(np.uint8(org_color_np), cv2.COLOR_RGB2HSV)\n  syn_hsv = cv2.cvtColor(np.uint8(syn), cv2.COLOR_RGB2HSV)\n\n  org_h, org_s, org_v = cv2.split(org_hsv)\n  syn_h, syn_s, syn_v = cv2.split(syn_hsv)\n\n  mask_map = org_np[:, :, 0]\n  # print(mask_map.shape)\n\n  w = org_v / 255.\n  w = w / 1.87\n  syn_v2 = mask_map * syn_v + (1 - mask_map) * org_v\n  syn_v2 = (1 - w) * syn_v2 + w * org_v\n  syn_v2 = syn_v2.astype(np.uint8)\n\n  final_syn_hsv = cv2.merge([syn_h, syn_s, syn_v2])\n  final_syn = cv2.cvtColor(final_syn_hsv, cv2.COLOR_HSV2RGB)\n  \n  if show_img:\n\n    plt.figure(figsize=(15, 10))\n\n    plt.subplot(141)\n    plt.imshow(org_np3)\n    plt.axis('off')\n\n    plt.subplot(142)\n    plt.imshow(org_color_np2)\n    plt.axis('off')\n\n    plt.subplot(143)\n    plt.imshow(final_syn)\n    plt.axis('off')\n\n    plt.subplot(144)\n    plt.imshow(org_color_np)\n    plt.axis('off')\n    plt.show()    \n\n  return final_syn\n```\n\n\n```\nif __name__ == '__main__':\n\n\n  object_ = 'wall'\n  # mask_path = '../previous_test_result/' + object_ + '/'\n  mask_path = '../test_result/' + object_ + '/'\n  # layout_path = '../test_layout_result/' + object_ + '/'\n  # layout_path = '../mask_layout_data/' + object_ + '/'\n  # layout_list = os.listdir(layout_path)\n\n  refer_path = '../refer_data/' + object_ + '/\ubc29_\ubcbd\uc9c0/'\n  # save_path = mask_path.replace('previous_test_result', 'syn_result')\n  save_path = mask_path.replace('test_result', 'syn_result')\n\n\n\n  length_thresh = 70\n  principal_point = None\n  focal_length = 1300 # 1102.79\n  seed = 1300\n  vpd = VPDetection(length_thresh, principal_point, focal_length, seed)\n\n\n  for image in os.listdir(mask_path):\n    \n    # image = '720x480_20190315154538242_cqtFKEk4r5.png'\n    image_name = image.split('.')[0]\n    try:\n      os.makedirs(os.path.join(save_path, image_name))\n\n    except Exception as e:\n      print('Error in makedirs :', e)\n\n    for refer in os.listdir(refer_path):\n\n      try:\n\n        print('image :', image)\n        print('refer :', refer)\n\n        org = Image.open(mask_path + image)\n        refer_img = Image.open(refer_path + refer)\n        # result_img = synthesize(org, refer_img, vpd, object_=object_, scale_factor=1, show_img=True)\n        result_img = synthesize(org, refer_img, vpd, object_=None, scale_factor=1, show_img=True)\n\n        Image.fromarray(result_img).save(os.path.join(save_path, image_name, refer))\n\n      except Exception as e:\n        print('Error in load images :', e)\n\n    # break\n\n```\n\n\n    Output hidden; open in https://colab.research.google.com to view.\n\n\n\n```\n6.486232280731201\nelapsed time : 6.074836015701294\nelapsed time : 6.072072744369507\nelapsed time : 6.072662591934204\nelapsed time : 6.140763998031616\n---\nelapsed time : 4.42145848274231\nelapsed time : 4.432448148727417\nelapsed time : 4.47941255569458\n---\nelapsed time : 2.750857353210449\nelapsed time : 2.7681655883789062\nelapsed time : 2.7948927879333496\nelapsed time : 2.882319927215576\n\n\n```\n\n\n```\n\n```\n", "meta": {"hexsha": "4bf950fde22240c47cef8ac77cedb35ffbbe6e07", "size": 40275, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Layout Estimation Func Final without AI_latest.ipynb", "max_stars_repo_name": "jaytoone/Indoor_Segmentation", "max_stars_repo_head_hexsha": "d99e502f99cb74000483974d931c2da058071bec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Layout Estimation Func Final without AI_latest.ipynb", "max_issues_repo_name": "jaytoone/Indoor_Segmentation", "max_issues_repo_head_hexsha": "d99e502f99cb74000483974d931c2da058071bec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Layout Estimation Func Final without AI_latest.ipynb", "max_forks_repo_name": "jaytoone/Indoor_Segmentation", "max_forks_repo_head_hexsha": "d99e502f99cb74000483974d931c2da058071bec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-29T15:27:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-29T15:27:56.000Z", "avg_line_length": 40275.0, "max_line_length": 40275, "alphanum_fraction": 0.5661328367, "converted": true, "num_tokens": 9856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735801686526387, "lm_q2_score": 0.052618949633584634, "lm_q1q2_score": 0.016172856008911777}}
{"text": "# Hello world!\n\nI'm a test Markdown document.\n\n**Here's some bold text** and *here's some italic text*. `This is inline code`.\n\n# Markdown Tables\n\nFirst Name  |  Last Name  |  Location           |  Allegiance\n------------|-------------|---------------------|-----------------\nMance       |  Rayder     |  North of the Wall  |  Wildlings\nMargaery    |  Tyrell     |  The Reach          |  House Tyrell\nDanerys     |  Targaryen  |  Meereen            |  House Targaryen\nTyrion      |  Lannister  |  King's Landing     |  House Lannister\n\n# Code blocks\n\n    This code\n    is in\n    a code block.\n\nHere's a syntax-highlighted code block:\n\n```python\n#!/usr/bin/env python3\n\nimport sys\n\nif __name__ == '__main__':\n    print('This is highlighted Python code!')\n    sys.exit(0)\n```\n\n# Page Layout with \\LaTeX\\ Commands\n\nHere's a forced page break.\n\n\\pagebreak\n\n# LaTeX support\n\nThis document supports inline \\LaTeX!\n\nHere's the proof: $\\frac{n!}{k!(n-k)!} = \\binom{n}{k}$\n\nCreating a footnote is easy.\\footnote{An example footnote.}\n\nHere's an equation:\n\n$$\n  x = a_0 + \\cfrac{1}{a_1\n          + \\cfrac{1}{a_2\n          + \\cfrac{1}{a_3 + \\cfrac{1}{a_4} } } }\n$$\n\nHere are some numbered equations:\n\n\\begin{equation} \n f(x)=(x+a)(x+b)\n\\end{equation}\n\n\n\\begin{equation}\n5^2 - 5 = 20\n\\end{equation}\n\n\n\\begin{equation}\na = bq + r\n\\end{equation}\n\nHere's some multi-line math stuff:\n\n$$\n u(x) =\n  \\begin{cases}\n   \\exp{x} & \\text{if } x \\geq 0 \\\\\n   1       & \\text{if } x < 0\n  \\end{cases}\n$$\n\n\\begin{align*}\n f(x) &= (x+a)(x+b) \\\\\n &= x^2 + (a+b)x + ab\n\\end{align*}\n\n\n```python\nimport ROOT\n```\n\n\n\n    Welcome to JupyROOT 6.08/06\n\n\n\n```python\nh = ROOT.TH1F(\"gauss\",\"Example histogram\",100,-4,4)\nh.FillRandom(\"gaus\")\n```\n\n\n```python\nc = ROOT.TCanvas(\"myCanvasName\",\"The Canvas Title\",800,600)\nh.Draw()\n```\n\n\n```python\nc.Draw()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "c7b473e70e2d0096f1c7bf5390c8fc084045b7b3", "size": 26963, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Jupyter/test.ipynb", "max_stars_repo_name": "echapon/CoursStatX", "max_stars_repo_head_hexsha": "2db74273a8a5e543fe034b7c9054c1976c0c9aa7", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Jupyter/test.ipynb", "max_issues_repo_name": "echapon/CoursStatX", "max_issues_repo_head_hexsha": "2db74273a8a5e543fe034b7c9054c1976c0c9aa7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Jupyter/test.ipynb", "max_forks_repo_name": "echapon/CoursStatX", "max_forks_repo_head_hexsha": "2db74273a8a5e543fe034b7c9054c1976c0c9aa7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 132.8226600985, "max_line_length": 22504, "alphanum_fraction": 0.878203464, "converted": true, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2845760163515857, "lm_q2_score": 0.05665242530797383, "lm_q1q2_score": 0.01612192151079895}}
{"text": "# Training the Transformer-XL to generate music\n\nThe [Transformer](https://arxiv.org/abs/1706.03762), introduced in 2017, has become the top choice to tackle problems in natural language processing (NLP). It has been used in both language generation, and [General Language Understanding Evaluation (GLUE)](https://gluebenchmark.com/) tasks. The Transformer model has even shown [promising results in computer vision related tasks](https://arxiv.org/pdf/2010.11929.pdf).\n\nThe Transformer has also helped push the state-of-the-art in [symbolic music generation](https://musicinformationretrieval.com/symbolic_representations.html), enabling minutes-long music performance generation with compelling musical structure. In this Jupyter notebook, you will look at how symbolic music can be generated using a recent variant of the Transformer called the Transformer-XL. \n\nThe code provided in this notebook will allow you to access the dataset used for training, and examine how [MIDI](https://en.wikipedia.org/wiki/MIDI) files are transformed into the note sequences used for training. Next, you can examine the Transformer-XL architecture and the data loader. Then, you can examine the end-to-end training process used to train a new model. Finally, you can use the trained model to perform inference and extend an input track. You can also examine how sampling was performed during inference to extend the input track.\n\n## Prerequisites\nThis notebook assumes an understanding of Convolutional Neural Networks (CNNs), Recurrent Neural Networks (RNNs) and a high level understanding of the original Transformer. The following links are useful resources to meet these prerequisites.\n1. [Learn the basics of generative AI](https://d32g4xocucupjo.cloudfront.net/#welcome)\n2. [Convolutional Neural Networks](https://d2l.ai/chapter_convolutional-neural-networks/index.html)\n3. [Recurrent Neural Networks](https://d2l.ai/chapter_recurrent-neural-networks/index.html)\n4. [Introduction to Transformers](http://jalammar.github.io/illustrated-transformer/)\n5. [Attention mechanism in Transformers](https://d2l.ai/chapter_attention-mechanisms/attention.html)\n\n\n## Using generative AI to create music \n\nThere are two primary ways to represent music in a format that can be used for training a machine learning model. *Image-based* methods use a [pianoroll](https://salu133445.github.io/lakh-pianoroll-dataset/representation.html) image while *text-based* methods use a sequence of tokens to represent the musical events occurring in the piece of music.\n\n1. The pianoroll is a 2D matrix that shows what pitches are played at each timestep. [MuseGAN](https://arxiv.org/abs/1709.06298) and [Coconet](https://arxiv.org/pdf/1903.07227.pdf) are examples of models that use piano roll images during training to later create music.\n\n\n2. There are several ways to convert MIDI files into a sequence of tokens. MIDI carries event messages, data that specify the instructions for music including a note's notation, pitch, velocity (which is heard typically as loudness or softness of volume). The tokens will accordingly represent these events found in the music/MIDI file such as the onset of notes, the duration or offset of notes, and the passage of time. [Music Transformer](https://arxiv.org/abs/1809.04281) and [Musenet](https://openai.com/blog/musenet/) are examples of models that treat music as a sequence. You can examine a specific sequential format, called the note sequence, later on in this notebook.\n\nIn this notebook, music generation is treated as a sequence generation problem. You will train a strong sequential model - the Transformer-XL - to learn the distribution of these sequences.\n\n## An introduction to Transformers and the Transformer-XL\n\nIn this section, you can examine the structure of the Transformer architecture, and see how the Transformer-XL improves on the original design.\n\n### The original Transformer\nBriefly, here are the advantages and disadvantages of using either CNNs or RNNs to solve sequence generation based problems.\n- CNNs are easy to parallelize, but can only capture fixed length sequential dependencies.\n- RNNs can learn long-range, variable length sequential dependencies but cannot be parallelized within a sequence.\n\nTo combine the advantages of CNNs and RNNs, a novel architecture was proposed in the paper [Attention is all you need](https://arxiv.org/abs/1706.03762), which solely uses the [attention mechanism](https://d2l.ai/chapter_attention-mechanisms/attention.html) and therefore helps the model focus on relevant parts of the input or output sentence. This architecture, called the Transformer, first encodes each word's position in the input sequence and then acts on it with the attention mechanism. The attention mechanism enables the Transformer to be trained in parallel, achieving significantly shorter training time (often by a factor of 10 or more) when compared to an RNN.\n\n\n\nThe Transformer consists of an encoder, the decoder, and the encoder-decoder attention connections between them.\nThe encoder (on the left) is a stack of encoder layers and the decoder (on the right) is a stack of decoder layers of the same number.\n\nThe encoder layers are all identical in structure. Its inputs first go through a multi-head attention layer, and then through a feed-forward neural network. The multi-head attention layer helps the encoder look at other words in the input sentence as it encodes a specific word. \nThe outputs of the multi-head attention layer are then fed into a feed-forward neural network. The exact same feed-forward network is independently applied to each position in the sequence. More details on the exact mechanisms used in the multi-head attention layer and self-attention can be found in the sections ahead.\n\nThe structure of the decoder is similar to the encoder, but has an additional encoder-decoder attention layer that helps the decoder focus on relevant parts of the input sequence. The decoder uses a [causal mask](https://medium.com/analytics-vidhya/masking-in-transformers-self-attention-mechanism-bad3c9ec235c) in the attention heads to force predictions to only attend to the tokens at previous positions, so that the model can be used autoregressively at inference time.\n\nThe decoder of the Transformer alone without the encoder is widely used for the __Language Modeling (LM)__ task: to predict the next token given a sequence of tokens. It still remains a challenge however to properly equip neural networks with *long-term dependency*.\n \n####  What is long-term dependency and why is it needed for music generation?\nGenerating long pieces of music is challenging, as music is structured to use multiple timescales, from millisecond notes and rests to repeating motifs, phrases and sections. Therefore, to generate music that maintains long-term coherence the model will need to refer to a musical note that occurs a few thousand notes or tokens back. This long-range dependence\u2014 a common phenomena in sequential data \u2014 must be understood in order to generate realistic music. While humans can do this naturally, [modeling long-term dependencies with neural networks is a challenge](https://www.aclweb.org/anthology/D18-1458.pdf). Transformers provide one mechanism, attention, to help with this challenge. Attention allows for direct connections between hidden states which can be used to capture long-term dependency.\n\n#### Limitations of the original Transformer\nHowever, the original Transformer decoder uses a fixed-length context, meaning that a long sequence is truncated into fixed-length segments comprised of a few hundred tokens, and then each segment is processed separately. The original Transformer using a fixed-length context during training is depicted below.\n \nUsing a fixed-length context introduces two __critical limitations__: \n\n1. The Transformer is not able to model dependencies that are longer than a fixed length. \n2. In music generation, a single musical note is frequently composed of multiple tokens. Fixed-length segments often do not respect musical note boundaries, resulting in context fragmentation which in turn causes inefficient optimization. This is problematic even for short sequences, where long range dependency isn't an issue.\n\n### The Transformer-XL \n\nThe [Transformer-XL](https://arxiv.org/abs/1901.02860) is a novel architecture based on the Transformer decoder. It improves on the original Transformer decoder and enables language modeling beyond a fixed-length context. It accomplishes this with two techniques: a segment-level recurrence mechanism and a relative positional encoding scheme.\n\n*__Segment-level Recurrence__* During Transformer-XL training, the representations computed for the previous segment are fixed and cached to be reused as an extended context when the model processes the next new segment. This additional connection increases the largest possible dependency length by N times, where N is the depth of the network, because contextual information is now able to flow across segment boundaries. This recurrence mechanism also resolves the context fragmentation issue, providing necessary context for tokens in the front of a new segment.\n \n \n \n*__Relative Positional Encodings__* Since the Transformer-XL caches representations between segments, a new way to represent the contexual positions of representations from different segments is needed. For example, if an old segment uses contextual positions [0, 1, 2, 3], then when a new segment is processed,the positions are [0, 1, 2, 3, 0, 1, 2, 3] for the two segments combined. The semantics of each position id is incoherent throughout the sequence and the Transformer-XL therefore proposes a novel relative positional encoding scheme to make the recurrence mechanism possible. \n \nWhen both of these approaches are combined, Transformer-XL has a much longer effective context than the original Transformer model at evaluation time.\n\n## Installing dependencies\nFirst, let's install and import all of the Python packages that you will use in this tutorial.\n\n\n```python\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Create the environment and install required packages\n!pip install -r requirements.txt\n```\n\n\n```python\n# Imports\nimport glob\nimport json\nimport math\nimport multiprocessing\nimport os\nimport pickle\nimport random\nimport time\nfrom pprint import pprint\nfrom typing import *\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom IPython import display\nfrom autocfg import dataclass, field\nfrom utils.performance_event_repo import BaseVocab\nfrom utils.midi_utils import play_midi, print_sample_array\nfrom utils.music_encoder import MusicEncoder\nfrom utils.utils import plot_losses, save_checkpoint\n\n%matplotlib inline\n```\n\n    /home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/pydub/utils.py:170: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work\n      warn(\"Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work\", RuntimeWarning)\n\n\n## Importing the data \n\nThe input dataset is in the [MIDI](https://en.wikipedia.org/wiki/MIDI) format. In this tutorial, you will use the [`JSB-Chorales-dataset`](http://www-etud.iro.umontreal.ca/~boulanni/icml2012). The link contains pickled files that you will convert to MIDI in the cells below. \n\nA chorale is a type of musical structure or form. Chorales usually consist of one voice singing a simple melody and three lower voices providing harmony. In this dataset, the voices are represented by four individual piano tracks.\n\nYou will now download and use this dataset locally.\n\n### Downloading the `JSB-Chorales-dataset`\n\n\n\n```python\n# Download a .zip file containing the .mid files from the dataset.\n!wget http://www-etud.iro.umontreal.ca/~boulanni/JSB%20Chorales.zip -P data/\n\n# Unzip the contents of that directory\n!unzip -q \"data/JSB Chorales.zip\" -d data/\n\n# Rename downloaded file\n!mv \"data/JSB Chorales\" data/jsb_chorales/\n\n# Change the string in the the `data_dir` variable to the correct file path\ndata_dir = \"data/jsb_chorales/**/*.mid\"\n\n# Load midi files\nmidi_files = glob.glob(data_dir)\n```\n\n    --2021-01-21 17:50:43--  http://www-etud.iro.umontreal.ca/~boulanni/JSB%20Chorales.zip\n    Resolving www-etud.iro.umontreal.ca (www-etud.iro.umontreal.ca)... 132.204.26.158\n    Connecting to www-etud.iro.umontreal.ca (www-etud.iro.umontreal.ca)|132.204.26.158|:80... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 215242 (210K) [application/zip]\n    Saving to: \u2018data/JSB Chorales.zip.1\u2019\n    \n    JSB Chorales.zip.1  100%[===================>] 210.20K  --.-KB/s    in 0.09s   \n    \n    2021-01-21 17:50:44 (2.31 MB/s) - \u2018data/JSB Chorales.zip.1\u2019 saved [215242/215242]\n    \n\n\n\n```python\n#Use this cell to play a random sample chorale snippet from the dataset `midi_files` \n#You can run the cell over-and-over again to hear different samples\n\nrandom_midi = random.randrange(len(midi_files))\nplay_midi(midi_files[random_midi])\n```\n\n\n\n<div id='midiPlayerDiv942'></div>\n<link rel=\"stylesheet\" href=\"//cuthbertLab.github.io/music21j/css/m21.css\"\n    type=\"text/css\" />\n\n\n\nIf your dataset has been successfully downloaded, you should be able to play a track after you have run the previous code cell.\n\n## Preprocessing the data into the note sequence format\n\nIn this section, you can see how the MIDI files from the dataset are preprocessed into the note sequence format needed to train the Transformer-XL model.\n\n<!-- You will train on the Piano-e-Competition dataset that consists of polyphonic piano performance MIDI with expressive timing and dynamics. . -->\n \nThe MIDI files in the `JSB-Chorales-dataset` consist of polyphonic piano performances with expressive timing and dynamics. To train a language model on these MIDI files you will first need to serialize the [polyphonic](https://ccnmtl.columbia.edu/projects/sonicg/terms/polyphony.html) performance into a single sequence of encoded words representing the different musical (MIDI) events. To do this, the different piano tracks or voices are interwoven into a sequence format (called the *Performance note sequence format*) as originally suggested in [This Time with Feeling: Learning Expressive Musical Performance](https://arxiv.org/pdf/1808.03715.pdf).\n\nThe musical events are converted into a sequence of words from a [predefined vocabulary](utils/magenta_vocab.txt). Of the 128 available pitches, 88 pitches were used. The structure of the vocabulary is described below.\nThe vocabulary includes:\n- 88 NOTE_ON events for starting a note using one of the 88 MIDI pitches\n- 88 NOTE_OFF events for ending or releasing a note using one of the 88 MIDI pitches\n- 100 TIME_SHIFT events where each one moves the time step forward incrementally. These time shift events can range anywhere from 10 ms to 1 second.\n- 32 SET_VELOCITY events that change the velocity applied to all subsequent notes (until the next velocity event). The 128 possible MIDI velocities are quantized into 32 bins. \n\n### Comparing a piano roll image to a sequence\nThis section highlights an example encoding where the pianoroll (pitches vs. time) on top is converted into a sequence of tokens below. A C Major chord is [arpeggiated](https://en.wikipedia.org/wiki/Arpeggio) along with an active sustain pedal. The pedal is released at the 2-second mark, ending all of the notes. At the 3-second mark, an F is played for a half second. The C chord is played at velocity (volume) 80 and the F is played at velocity (volume) 100.\n \n\n\n### Data augmentation\n[Data augmentation](https://d2l.ai/chapter_computer-vision/image-augmentation.html) provides a simple way of encoding domain specific prior knowledge in any machine learning algorithm. You will augment the dataset as originally suggested in the paper, [Music Transformer](https://arxiv.org/abs/1809.04281). Two kinds of data augmentation are applied to every note to reflect how music can retain a melody when either the pitch is transposed (moving up or down an octave) or the tempo is changed. Below are the two variables used to accomplish this: \n- Pitch transpositions are controlled using integers `pitch_transpose_lower` and `pitch_transpose_upper`. The transpositions applied to a note are sampled uniformly from the integer set of half-steps {pitch_transpose_lower,...,pitch_transpose_upper}. We use `pitch_transpose_lower`=-3 and `pitch_transpose_upper`=3.\n- Time stretch factors are uniformly sampled from the set {0.95,0.975,1.0,1.025,1.05} that we denote using the variable `stretch_factors`. The duration of a note is multiplied with this sampled stretch factor.\n\n\n```python\n# Creates a class that will be used to transform the dataset from \n# MIDI to a numpy array based on the Performance vocabulary\nmusic_encoder = MusicEncoder()\n \n# Specify event representation algorithm ('performance') and dataset augmentation parameters\npitch_transpose_lower, pitch_transpose_upper = -3, 3\nmusic_encoder.build_encoder(algorithm='performance', stretch_factors=[0.95,0.975,1.0,1.025,1.05],\n                            pitch_transpose = (pitch_transpose_lower, pitch_transpose_upper))\n\n# Convert midi dataset to numpy array\nmusic_encoder.convert(input_folder= 'data/jsb_chorales', \n                      output_folder='data/jsb_chorales_numpy',\n                      mode='midi_to_npy')\n\n```\n\n    Converting midi files from data/jsb_chorales to npy...\n    Loaded dataset from data/jsb_chorales. Train/Val/Test=229/76/77\n    Split train converted! Spent 12.860990047454834s to convert 229 samples.\n    Split valid converted! Spent 0.4431154727935791s to convert 76 samples.\n    Split test converted! Spent 0.42433857917785645s to convert 77 samples.\n\n\nYou will print a sample MIDI file from the training set. This is now a numpy array of indices for each event type.\n\n\n```python\n# Prints a randomly sampled numpy array from the parent_dir\nprint_sample_array(split=\"train\", parent_dir=\"data/jsb_chorales_numpy\")\n```\n\n## Model architecture\n\nIn the sections below, you can see how the Transformer-XL decoder is implemented one piece at a time. You will begin by looking at the attention matrix and the terms within. You will then implement the Transformer-XL decoder using a sequence of multi-head attention layers along with feed forward layers, residual connections and `LayerNorm` layers.\n\n\n\n### Self attention\n\nThe attention layer is the fundamental part of the Transformer-XL model architecture. In this section you can see how the attention score matrix for a single head is computed. Later on you will see how the multi-head attention layer is composed of several attention heads.\n\nSay you have a music sequence of length (`tgt_len`) of 10 events with a batch size (`batch_size`) of 8 that you want to use self-attention on. `tgt_len` and `batch_size` are examples of hyperparameters that are tuned while training the Transformer-XL. \n\n\n```python\ntgt_len = 10  # Length of input music sequence\nbatch_size = 8  # Batch size\nvocab_size = 310  # Effective Vocabulary size for the Performance event representation\n \nsequence = torch.randint(vocab_size, (tgt_len, batch_size))\n```\n\nYou first transform the sequence indices into word embeddings of dimension 32 which is another hyperparameter.\n\n\n```python\ndim_embed = 32  # Embedding dimension\n\nword_emb_layer = nn.Embedding(vocab_size, dim_embed)\nword_emb = word_emb_layer(sequence)\n```\n\n\n```python\nword_emb.shape  # tgt_len x batch_size x dim_embed\n```\n\nThe Transformer-XL introduces a segment level recurrence mechanism, where cached states for the previous segment (sequence) are also provided as additional input to the model.\nThe cached states are referred to as the memory. \n\n\n\n```python\nmem_len = 10  # Previous sequence len (same as input sequence length here)\n\nmems = torch.rand(mem_len, batch_size, dim_embed)  # memory of cached states\n```\n\nWhile the memory length or number of cached states stored is the same as the sequence length (equal to 10) in this example, this need not be the case.\n\n\nAs in the original Transformer, the attention layer operates on keys, queries and values. The keys and values are comprised of both memory and current sequence while the queries are the current sequence alone.\n\nYou first linearly project the queries, keys and values to a dimension `dim_head` for efficient computation of attention.\n\n\n```python\ndim_head = 5  # Inner dimension of attention head\n\n# Define linear projection layers\nq_net = nn.Linear(dim_embed, dim_head)\nk_net = nn.Linear(dim_embed, dim_head)\nv_net = nn.Linear(dim_embed, dim_head)\n\n# Keys and values are comprised of memory and current sequence\nword_emb_concat = torch.cat([mems, word_emb], dim=0)  # Concatenated along seq dim\nK = k_net(word_emb_concat)\nV = v_net(word_emb_concat)\n\n# Queries are comprised of current sequence\nQ = q_net(word_emb)\n```\n\nYou now compute the scaled dot product attention between the query __Q__, key __K__ and value __V__ matrices. As in the original paper, you divide the attention score matrix with the square root of the embedding dimension. For large values of embedding dimension the dot products grow large in magnitude, pushing the softmax function into regions where it has\nextremely small gradients. Scaling the dot products by $\\sqrt{1/d_k}$ helps address this.\n\n$$ \\textrm{Attention}(Q, K, V) = \\textrm{softmax}(\\frac{QK^T}{\\sqrt{d_k}})V $$\n\n\n\nTo compute the dot product $QK^T$ in Pytorch you will use [einsum](https://pytorch.org/docs/stable/generated/torch.einsum.html) and then scale the result. This term is called `attn_a` and you shall soon understand why.\n\n\n\n```python\nattn_a = torch.einsum(\"ibd,jbd->bij\", Q, K) / (dim_embed ** 0.5)\n```\n\nThe Transformer-XL attention matrix introduces additional components from relative positional embeddings as you will see next. Once you compute these additional components you add them to obtain the net attention score matrix before applying the softmax activation.\n\n### Relative Positional Encoding\n\nObserve that unlike the original Transformer, you did not add positional embeddings to `word_emb` before you computed the attention score. \n\nMusic has multiple dimensions along which relative differences arguably matter more than their absolute values; the two most prominent are timing and pitch. To model such pairwise relations between representations, the paper, [Self-Attention with Relative Position Representations](https://arxiv.org/abs/1803.02155) introduced a relation-aware version of self-attention.\n\nThe Transformer-XL uses an efficient implementation of this idea in the form of relative positional embeddings. Unlike the Transformer that uses absolute positional embeddings that are added to every token embedding, the Transformer-XL uses an embedding that represents the relative distance i-j between query $q_i$ and key $k_j$. \n\n\nRecap by taking a look at the $ij^{th}$ entry in the attention matrix of the original Transformer. The original Transformer uses absolute positional embeddings denoted by $U$\n\n\\begin{align}\nA^{abs}_{i,j} = \n    \\underbrace{E_{x_i}^T W_q^T W_{k} E_{x_j}}_{(a)}\n    + \\underbrace{E_{x_i}^T W_q^T W_{k} U_{j}}_{(b)}\n    \\\\ \n    + \\underbrace{ U_{i}^T W_{q}^T W_{k} E_{x_j}}_{(c)} \n    + \\underbrace{ U_{i}^T W_{q}^T W_{k} U_{j}}_{(d)}\n\\end{align}\n\nNow look at the $ij^{th}$ entry in the relative attention matrix of a the Transformer-XL.\n\n\\begin{align}\nA^{rel}_{i,j} = \n    \\underbrace{E_{x_i}^TW_q^TW_{k,E}E_{x_j}}_{(a)}\n    + \\underbrace{E_{x_i}^TW_q^TW_{k,R} \\color{blue}R_\\color{blue}{i-j} }_{(b)}\n    \\\\ \n    + \\underbrace{ \\color{red}u^\\color{red}T W_{k,E}E_{x_j}}_{(c)} \n    + \\underbrace{ \\color{red}v^\\color{red}T W_{k,R} \\color{blue}R_\\color{blue}{i-j}}_{(d)}\n\\end{align}\n\n$E_x$ is the sequence embedding representing content<br> \n$W_q$,$W_{k,E}$ and $W_{k,R}$ are the linear transformation matrices <br>\n$u$ and $v$ are learnable bias terms that represent content bias and position bias respectively <br>\nT denotes matrix transpose\n\nWhat are the differences?\n\n- The first change is to replace all appearances of the absolute positional embedding $U_j$ for computing key vectors in term (b) and (d) with its relative counterpart $R_{i\u2212j}$. This essentially reflects the prior belief that only the relative distance matters for where to attend. R is a [sinusoid encoding matrix](https://kazemnejad.com/blog/transformer_architecture_positional_encoding/) without learnable parameters that you shall soon visualize in the cells below.\n\n- Second, a trainable parameter $u \\in \\mathbb{R}^d$ is introduced to replace the content query $U_{i}^T W_{q}^T$ in term (c). In this case, since the query vector is the same for all query positions, it suggests that the attentive bias towards different words should remain the same regardless of the query position. With a similar reasoning, a trainable parameter $v \\in \\mathbb{R}^d$ is added to substitute $U_{i}^T W_{q}^T$ in term (d).\n\n- Finally, the two weight matrices $W_{k,E}$ and $W_{k,R}$ are deliberately separated for producing the content-based key vectors and location-based key vectors respectively.\n\n\nAbove you saw the code to compute the content based attention term (a), denoted by `attn_a`. You can see below how remaining terms (b),(c) and (d) are computed. (b) and (d) involve the relative positional embeddings. \n\nTerm (c) is computed first. \n\n\n```python\nu = torch.rand(5).expand_as(Q)  # Learnable bias\n\nattn_c = torch.einsum(\"ibd,jbd->bij\", u, K) / (dim_embed ** 0.5)\n```\n\n\n```python\nattn_content = attn_a + attn_c  # Content attention is composed of terms (a) and (c)\n```\n\nYou will now understand the relative positional embeddings terms (b) and (d). The Transformer-XL uses [sinusoidal embeddings](https://console.aws.amazon.com/deepcomposer/home?region=us-east-1#learningCapsules/transformerTechnique) like the original Transformer.\n\n\n```python\n# Define positional indices\npos_seq = torch.arange(tgt_len + mem_len - 1, -1, -1, dtype=torch.float)\npos_seq\n```\n\n\n```python\n# Compute sinusoidal positional embeddings\ninv_freq = 1 / (10000 ** (torch.arange(0.0, dim_embed, 2.0) / dim_embed))\nsinusoid_inp = torch.ger(pos_seq, inv_freq) # Outer product of vectors\npos_emb = torch.cat([sinusoid_inp.sin(), sinusoid_inp.cos()], dim=-1)[:, None, :]\n```\n\nLet us visualize a few dimensions in the positional embeddings matrix for better understanding. The sines and cosines act as basis functions to [represent the position](https://kazemnejad.com/blog/transformer_architecture_positional_encoding/).\n\n\n```python\n# Visualize a few sinusoidal embeddings in pos_emb\nplt.plot(pos_seq, pos_emb[:, 0, 0:4])\nplt.legend([\"dim %d\" % p for p in [0, 1, 2, 3]])\n```\n\nYou will now define all the core components of the Transformer-XL in a class. The relative positional embeddings are defined inside a class `PositionalEmbedding`.\n\n\n```python\nclass PositionalEmbedding(nn.Module):\n    \"\"\" \n    Transformer-XL positional embedding definition \n    \"\"\"\n\n    def __init__(self, dim_embed):\n        super(PositionalEmbedding, self).__init__()\n\n        self.dim_embed = dim_embed\n\n        inv_freq = 1 / (10000 ** (torch.arange(0.0, dim_embed, 2.0) / dim_embed))\n        self.register_buffer(\"inv_freq\", inv_freq)\n\n    def forward(self, pos_seq, batch_size=None):\n\n        sinusoid_inp = torch.ger(pos_seq, self.inv_freq)  # Outer product\n\n        # Define relative positional embeddings\n        pos_emb = torch.cat([sinusoid_inp.sin(), sinusoid_inp.cos()], dim=-1)\n\n        if batch_size is not None:\n            return pos_emb[:, None, :].expand(-1, batch_size, -1)\n        else:\n            return pos_emb[:, None, :]\n```\n\nAs seen earlier for the queries, keys and values, you need to apply linear transformations ($W_{k,R}$) to the positional embeddings as well for efficiency when computing across several heads.\n\n\n```python\n# Define linear transformation layer that acts on positional embeddings\nr_net = nn.Linear(dim_embed, dim_head)\n\n# Project positional embeddings\nR = r_net(pos_emb) \n```\n\nYou will now compute terms (b) and (d) together\n\n\n```python\nv = torch.rand(5)  # Learnable bias\n\nattn_bd = torch.einsum(\"ibd,jd->bij\", Q + v, R[:, 0, :]) / (dim_embed ** 0.5)\n```\n\n\n```python\nattn_bd.shape\n```\n\nObserve that `R` currently scales linearly with sequence length (say n) since `pos_seq` scales linearly with n. The terms (b) and (d) however depend on both i and j. Naively computing `R` and its linear projection would involve computing and storing vectors that are proportional to $O(n^2)$. The authors proposed a trick (padding+shifting) to reduce this to $O(n)$ time and memory instead by computing the attention for one query then shifting the embeddings for different query positions. This trick makes the original [Relative Attention](https://arxiv.org/abs/1803.02155) idea feasible for modeling long sequences.\n\n\n```python\npadding = torch.zeros((batch_size, tgt_len, 1), dtype=torch.float)\n\n# padding + shifting is the trick for efficiently computing pos_attn\nattn_pos = (\n    torch.cat([padding, attn_bd], dim=-1)\n    .view(batch_size, tgt_len + mem_len + 1, tgt_len)[:, 1:]\n    .view_as(attn_bd)\n)\n```\n\nThe net attention matrix is the sum of terms (a),(b),(c) and (d)\n\n\n```python\nattn = attn_content + attn_pos\n```\n\nSince you are interested in music generation (formulated as language modeling), you need to use a causal mask to prevent the model from looking into the future as its predicting.\n\n\n```python\nmask = torch.triu(\n    torch.ones((tgt_len, tgt_len + mem_len)),\n    diagonal=1 + mem_len,\n).bool()[None, ...]\n\nattn = attn.masked_fill(mask, -float(\"inf\"))\n```\n\nYou now compute the outputs of the attention layer by taking a weighted sum of the value vectors using the attention probabilities\n\n\n```python\nattn_probs = torch.softmax(attn, dim=2)\nattn_vec = torch.einsum(\"bij,jbd->ibd\", attn_probs, V)\n\n```\n\nFinally you transform `attn_vec` using a linear layer to bring it back to its original dimension. You also apply the residual connection and layer normalization as in the original Transformer.\n\n\n```python\no_net = nn.Linear(dim_head, dim_embed)\nlayer_norm = nn.LayerNorm(dim_embed)\noutputs = layer_norm(word_emb + o_net(attn_vec))\n```\n\n### Multi-head attention\n\nYou now define the Transformer-XL `MultiHeadAttn` module by applying self attention across several heads. \n\n\n```python\nclass MultiHeadAttn(nn.Module):\n    \"\"\" \n    Defines the Multihead Attention module in the Transformer-XL \n    \"\"\"\n    \n    def __init__(\n            self,\n            n_head,\n            dim_model,\n            dim_head,\n            dropout,\n            dropatt=0,\n    ):\n        super(MultiHeadAttn, self).__init__()\n\n        # number of heads\n        self.n_head = n_head\n        \n        # input dimension\n        self.dim_model = dim_model\n        \n        # inner dimension\n        self.dim_head = dim_head\n        \n        self.dropout = dropout\n        \n        # you apply the linear transformation to queries, keys and values \n        # at once for efficiency\n        self.qkv_net = nn.Linear(dim_model, 3 * n_head * dim_head, bias=False)\n        \n        # linear transformation for output and position embeddings\n        self.o_net = nn.Linear(n_head * dim_head, dim_model, bias=False)\n        self.r_net = nn.Linear(self.dim_model, self.n_head * self.dim_head, bias=False)\n        \n        # Parameters controlling dropout or drop attention\n        self.drop = nn.Dropout(dropout)\n        self.dropatt = nn.Dropout(dropatt)\n        \n        self.layer_norm = nn.LayerNorm(dim_model)\n        \n        # Dot product attention scaling factor \n        self.scale = 1 / (dim_head ** 0.5)\n         \n    def rel_shift(self, x):\n        \"\"\" \n        Function to help compute positional attention component efficiently \n        \"\"\"\n        \n        padding = torch.zeros(\n            (x.size(0), x.size(1), x.size(2), 1), device=x.device, dtype=x.dtype\n        )\n        x_padded = torch.cat([padding, x], dim=3)\n\n        x_padded = x_padded.view(x.size(0), x.size(1), x.size(3) + 1, x.size(2))\n\n        x = x_padded[:, :, 1:].view_as(x)\n\n        return x\n\n    def forward(self, w: torch.FloatTensor, # (q_len, batch_size, dim_model)\n                r: torch.FloatTensor, # (k_len, dim_model)\n                u: torch.FloatTensor, # (batch_size, dim_model)\n                v: torch.FloatTensor,  # (batch_size, dim_model)\n                attn_mask: Optional[torch.FloatTensor]=None, \n                mems: Optional[torch.FloatTensor]=None): #(prev_seq_len, batch_size, dim_model)\n        \n        # qlen is length of current segment\n        # rlen is length of current segment + length of previous segment\n        qlen, rlen, batch_size = w.size(0), r.size(0), w.size(1)\n\n        if mems is not None:\n            # concatenate memory across sequence dimension\n            cat = torch.cat([mems, w], 0)\n            \n            w_heads = self.qkv_net(cat)\n            r_head_k = self.r_net(r)\n\n            w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1)\n            w_head_q = w_head_q[-qlen:]\n        else:\n            w_heads = self.qkv_net(w)\n            r_head_k = self.r_net(r)\n\n            w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1)\n\n        klen = w_head_k.size(0)\n\n        w_head_q = w_head_q.view(\n            qlen, batch_size, self.n_head, self.dim_head\n        )  # [qlen x batch_size x n_head x dim_head]\n        w_head_k = w_head_k.view(\n            klen, batch_size, self.n_head, self.dim_head\n        )  # [klen x batch_size x n_head x dim_head]\n        w_head_v = w_head_v.view(\n            klen, batch_size, self.n_head, self.dim_head\n        )  # [klen x batch_size x n_head x dim_head]\n\n        r_head_k = r_head_k.view(\n            rlen, self.n_head, self.dim_head\n        )  # [klen x n_head x dim_head]\n\n        # Compute attention score\n        \n        # Terms (a) and (c)\n        uw_head_q = w_head_q + u  # qlen x batch_size x n_head x dim_head\n        \n        AC = torch.einsum(\n            \"ibnd,jbnd->bnij\", (uw_head_q, w_head_k)\n        )  # [batch_size x n_head x qlen x klen]\n\n        # Terms (b) and (d)\n        vw_head_q = w_head_q + v\n        BD = torch.einsum(\n            \"ibnd,jnd->bnij\", (vw_head_q, r_head_k)\n        )  # [batch_size x n_head x qlen x klen]\n        \n        # Compute positional attention component efficiently\n        BD = self.rel_shift(BD) # [batch_size x n_head x qlen x klen]\n        \n        attn_score = AC + BD\n        attn_score.mul_(self.scale)\n\n        # Compute attention probability\n        \n        # Use a causal mask if provided\n        if attn_mask is not None:\n            attn_score.masked_fill_(attn_mask[None, None, :, :], -float(\"inf\"))\n\n        \n        attn_prob = F.softmax(attn_score, dim=3) # [batch_size x n_head x qlen x klen]\n        attn_prob = self.dropatt(attn_prob) # [batch_size x n_head x qlen x klen]\n\n        attn_vec = torch.einsum(\"bnij,jbnd->ibnd\", (attn_prob, w_head_v))\n        # [qlen x batch_size x n_head x dim_head]\n        \n        attn_vec = attn_vec.contiguous().view(\n            attn_vec.size(0), attn_vec.size(1), self.n_head * self.dim_head\n        )\n\n        # linear projection\n        attn_out = self.o_net(attn_vec)\n        attn_out = self.drop(attn_out)\n\n        # residual connection + layer normalization\n        output = self.layer_norm(w + attn_out)\n\n        return output\n\n```\n\nTo test if this layer works as expected, we expect the input and output shapes to be identical.\n\n\n```python\nmha_layer = MultiHeadAttn(n_head=2, dim_model=16, dim_head=5, dropout=0.1, dropatt=0)\n\nseq = torch.rand(10, 8, 16)  # [q_len x batch_size x dim_model]\npos_emb = torch.rand(16, 16)  # [k_len x dim_model]\nmems = torch.rand(6, 8, 16)  # [mem_len x batch_size x dim_model]\nu, v = torch.rand(2, 5), torch.rand(2, 5)  # [batch_size, dim_head]\n\noutputs = mha_layer(w=seq, r=pos_emb, u=u, v=v, attn_mask=None, mems=mems)\n```\n\n\n```python\nprint(\"Input sequence shape = \", seq.shape)\nprint(\"Output sequence shape = \", outputs.shape)\n\nassert seq.shape == outputs.shape\n```\n\n### The decoder layer\n\nYou will build the decoder block by using MultiHeadAttn along with a Positionwise Feed Forward layer identical to the original Transformer.\n\n\n\n```python\nclass PositionwiseFF(nn.Module):\n    \"\"\" \n    Defines the Position wise FeedForward layer in the Transformer-XL \n    \"\"\"\n    \n    def __init__(self, dim_model, dim_inner, dropout):\n        super(PositionwiseFF, self).__init__()\n\n        # Input dimension\n        self.dim_model = dim_model\n\n        # Inner dimension within Positionwise FF\n        self.dim_inner = dim_inner\n        \n        self.dropout = dropout\n\n        self.CoreNet = nn.Sequential(\n            nn.Linear(dim_model, dim_inner),\n            nn.ReLU(inplace=True),\n            nn.Dropout(dropout),\n            nn.Linear(dim_inner, dim_model),\n            nn.Dropout(dropout),\n        )\n\n        self.layer_norm = nn.LayerNorm(dim_model)\n\n    def forward(\n        self, inp: torch.FloatTensor  # (q_len, batch_size, dim_model)\n    ) -> torch.FloatTensor:  # (q_len, batch_size, dim_model)\n\n        # positionwise feed-forward\n        core_out = self.CoreNet(inp)\n\n        # residual connection + layer normalization\n        output = self.layer_norm(inp + core_out)\n\n        return output\n```\n\nYou will use this `PositionwiseFF` layer in the `DecoderLayer`\n\n\n```python\nclass DecoderLayer(nn.Module):\n    \"\"\" \n    Transformer-XL decoder layer comprised of the Multihead attention \n    and Positionwise Feed Forward layers \n    \"\"\"\n    \n    def __init__(self, n_head, dim_model, dim_head, dim_inner, dropout, dropatt=0):\n\n        super(DecoderLayer, self).__init__()\n\n        self.dec_attn = MultiHeadAttn(n_head, dim_model, dim_head, dropout, dropatt)\n\n        self.pos_ff = PositionwiseFF(dim_model, dim_inner, dropout)\n\n    def forward(self, dec_inp, r, u, v, dec_attn_mask=None, mems=None):\n\n        output = self.dec_attn(\n            dec_inp, r, u, v, attn_mask=dec_attn_mask, mems=mems\n        )\n\n        output = self.pos_ff(output)\n\n        return output\n```\n\n### The Transformer-XL decoder\n\nUsing the `DecoderLayer` defined above you can now build the Transformer-XL.\n\nYou will also need to define the input `Embedding` layer that maps from input indices to a sequence of dimension `dim_model` and the Output layer that maps from `dim_model` to the length of vocabulary.\n\nThe Transformer-XL ties the weights in the Embedding Layer and Output layer so that the total parameter count is reduced. \n\n\n```python\nclass Embedding(nn.Module):\n    \"\"\"\n    Embedding layer in the Transformer-XL\n    \"\"\"\n    def __init__(self, n_token, dim_embed):\n        \"\"\"\n        Args:\n            n_token: number of tokens in vocab\n            dim_embed: dimension of embedding\n        \"\"\"\n\n        super(Embedding, self).__init__()\n\n        self.n_token = n_token\n        self.dim_embed = dim_embed\n\n        self.emb_scale = dim_embed ** 0.5\n\n        self.emb_layers = nn.ModuleList()\n\n        self.emb_layers.append(nn.Embedding(n_token, dim_embed, sparse=False))\n\n    def forward(\n        self,\n        inp: torch.LongTensor,  # (qlen, batch_size)\n    ) -> torch.FloatTensor:  # (qlen, batch_size, dim_embed)\n        embed = self.emb_layers[0](inp)\n\n        # Embeddings are scaled while the Output Layer of Transformer-XL is not\n        embed.mul_(self.emb_scale)\n\n        return embed\n```\n\nYou will now define the Transformer-XL module using everything you have learnt so far.\n\n\n```python\nclass TransformerXL(nn.Module):\n    \"\"\" \n    The Transformer-XL module comprised of the Embedding layer,\n    multiple Decoder layers and the output layer\n    \"\"\"\n    def __init__(\n        self,\n        n_layer,\n        n_head,\n        dim_model,\n        dim_inner,\n        dropout,\n        dropatt,\n        tie_weight,\n        tgt_len,\n        mem_len,\n        n_token,\n    ):\n\n        super(TransformerXL, self).__init__()\n\n        # Embedding layer\n        self.word_emb = Embedding(\n            n_token,\n            dim_model,\n        )\n\n        dim_head = dim_model // n_head # Dimensionality of the model\u2019s heads\n\n        # Positional embedding\n        self.pos_emb = PositionalEmbedding(dim_model)\n        self.u = nn.Parameter(torch.Tensor(n_head, dim_head))\n        self.v = nn.Parameter(torch.Tensor(n_head, dim_head))\n\n        self.drop = nn.Dropout(dropout)\n\n        self.n_layer = n_layer\n\n        self.tgt_len = tgt_len\n        self.mem_len = mem_len\n\n        # Define the decoder layers that comprise the Transformer-XL\n        self.layers = nn.ModuleList()\n\n        for i in range(n_layer):\n            self.layers.append(\n                DecoderLayer(\n                    n_head,\n                    dim_model,\n                    dim_head,\n                    dim_inner,\n                    dropout,\n                    dropatt=dropatt,\n                )\n            )\n\n        # Define output layer\n        self.out_layers = nn.ModuleList()\n        self.out_layers.append(nn.Linear(dim_model, n_token))\n\n        # Tie weights of output layer with embedding layer\n        if tie_weight:\n            for i in range(len(self.out_layers)):\n                self.out_layers[i].weight = self.word_emb.emb_layers[i].weight\n\n    def reset_length(self, tgt_len, mem_len):\n        \"\"\"\n        Resets tgt_len and mem_len to specified values\n        \n        Used when tgt_len and mem_len may be different between training,\n        evaluation and generation\n        \"\"\"\n        self.tgt_len = tgt_len\n        self.mem_len = mem_len\n\n    def init_mems(self, n_layers):\n        \"\"\"\n        Initialize mems tensor if mems is None\n        \"\"\"\n        param = next(self.parameters())\n        mems = torch.empty(n_layers + 1, 0, dtype=param.dtype, device=param.device)\n        return mems\n\n    def update_mems(self, hids, mems, qlen, mlen):\n        \"\"\"\n        This function is called at the end of a forward.\n        Updates mems with hidden states of current segment\n        \"\"\"\n        \n        if mems is None:\n            return None\n\n        with torch.no_grad():\n\n            # Update mems with the most recent `self.mem_len`\n            # states that includes the previous memory\n\n            stacked = torch.stack(hids)\n            end_idx = mlen + max(0, qlen)\n            start_idx = max(0, end_idx - self.mem_len)\n            \n            # Dimension of cat is (num_layers, self.mem_len+qlen, batch_size, dim_model)\n            cat = torch.cat([mems, stacked], dim=1) if mems.numel() else stacked\n            \n            # Dimension of new_mems is (num_layers, self.mem_len, batch_size, dim_model)\n            new_mems = cat[:, start_idx:end_idx].detach()\n            \n        return new_mems\n\n    def _forward(self, dec_inp, mems=None):\n        \"\"\"\n        Helper function used by forward()\n\n        \"\"\"\n        qlen, batch_size = dec_inp.size()[0], dec_inp.size()[1]\n        word_emb = self.word_emb(dec_inp)\n\n        mlen = mems[0].size(0) if mems is not None else 0\n        klen = mlen + qlen\n\n        # Construct attention mask\n        dec_attn_mask = torch.triu(\n            word_emb.new_ones(qlen, klen), diagonal=1 + mlen\n        ).bool()[:, :]\n\n        # Construct positional embeddings\n        pos_seq = torch.arange(\n            klen - 1, -1, -1.0, device=word_emb.device, dtype=word_emb.dtype\n        )\n\n        pos_emb = self.pos_emb(pos_seq)\n        pos_emb = self.drop(pos_emb)\n\n        # Successively run through Decoder Layers\n        hids = []\n        core_out = self.drop(word_emb)\n        hids.append(core_out)\n\n        for i, layer in enumerate(self.layers):\n            mems_i = None if mems is None else mems[i]\n            core_out = layer(\n                core_out,\n                pos_emb,\n                self.u,\n                self.v,\n                dec_attn_mask=dec_attn_mask,\n                mems=mems_i,\n            )\n            hids.append(core_out)\n        core_out = self.drop(core_out)\n\n        # Update memory\n        new_mems = self.update_mems(hids, mems, mlen, qlen)\n\n        return core_out, new_mems\n\n    def forward(self, data, target, mems=None):\n\n        if mems is None and self.mem_len > 0:\n            mems = self.init_mems(self.n_layer)\n\n        tgt_len = target.size(0)\n        hidden, new_mems = self._forward(data, mems=mems)\n\n        pred_hid = hidden[-tgt_len:]\n\n        logit = self.out_layers[0](pred_hid.view(-1, pred_hid.size(-1)))\n\n        loss = (\n            -F.log_softmax(logit, dim=-1)\n            .gather(1, target.view(-1).unsqueeze(1))\n            .squeeze(1)\n        )\n\n        loss = loss.view(tgt_len, -1)\n\n        return (loss, new_mems)\n\n    def forward_generate(self, data, mems):\n        \"\"\"\n        This function is called during inference (decoding)\n        when one generates tokens incrementally.\n        It is identical to forward() but does not compute the loss\n        and returns the logits instead\n\n        \"\"\"\n        if mems is None and self.mem_len > 0:\n            mems = self.init_mems(self.n_layer)\n\n        tgt_len = data.size(0)\n        batch_size = data.size(1)\n\n        hidden, new_mems = self._forward(data, mems=mems)\n\n        pred_hid = hidden[-tgt_len:]\n\n        logits = self.out_layers[0](pred_hid.view(-1, pred_hid.size(-1)))\n        logits = logits.view(tgt_len, batch_size, -1)\n\n        return (logits, new_mems)\n```\n\nYou will test if the model is working with some dummy inputs\n\n\n```python\ntransformerxl = TransformerXL(\n    n_layer=5,\n    n_head=4,\n    dim_model=10,\n    dim_inner=5,\n    dropout=0.1,\n    dropatt=0,\n    tie_weight=True,\n    tgt_len=20,\n    mem_len=5,\n    n_token=310,\n)\n```\n\n\n```python\ninputs = torch.randint(310, (20, 2)) # input indices of shape (tgt_len, batch_size)\ntgts = torch.randint(310, (20, 2)) # target indices of shape (tgt_len, batch_size)\noutputs = transformerxl(inputs, tgts)\n\nprint(\"Output is a tuple of shape \", len(outputs))\nassert len(outputs)==2\n\nprint(\"Loss is a tensor of shape \", outputs[0].shape)  # (tgt_len, batch_size)\nassert outputs[0].shape == tgts.shape\n\nprint(\"Memory is a tensor of shape \", outputs[1].shape)  # (n_layer+1, mem_len, batch_size, dim_model)\nassert outputs[1].shape == torch.Size([5+1, 5, tgts.shape[1], 10])\n```\n\n## Training the model\n\nIn the following sections, you can see how to train the Transformers-XL model.\n\nYou will first define the hyperparameters that you will use in the data loader, training, and evaluation loops.\n\n### Training hyperparameters\n\nHyperparameters are broadly categorized into those that control training and evaluation, and those that define the model architecture.\n\n\n```python\n@dataclass\nclass TrainConfig:\n    \"\"\"\n    Defines configuration parameters used during model training\n    \"\"\"\n    \n    # Dataset\n    data_dir = \"data/jsb_chorales_numpy\"\n\n    # Checkpoint save path\n    save_path = \"checkpoints/\"\n\n    # Training and evaluation hyperparameters\n    batch_size = 64 # Training batch size\n    seed = 101 # Seed to reproduce losses\n    tgt_len = 128 # Target length or bptt (use as large as fits in GPU memory)\n    mem_len = 512 # Memory length (use as large as fits in GPU memory)\n    clip = 1.0 # Grad norm clip constant\n    scheduler = \"inv_sqrt\" # Learning rate scheduler\n    warmup_step = 4000 # Learning rate warmup\n    lr = 0.004 / 8 # Learning rate\n    lr_min = 0.0001 / 4 # Min learning rate\n    optim = \"adam\" # Optimizer\n    weight_decay = 0.0  # Weight decay for adam\n    max_step = 20000 # Max steps\n    \n    eval_batch_size = 2 # Evaluation batch size\n    eval_tgt_len = 128 # Evaluation target length\n    eval_mem_len = 512 # Evaluation memory length\n\n    log_interval = 100 # Print logs every log_interval training iterations\n    eval_interval = 500 # Evaluate after eval_interval training iterations\n\n    # Plotting and saving params\n    save_all_test_losses = True \n    plot_losses_while_training = True\n    plot_interval = 100 # Plot losses every plot_interval training iterations\n\n    # Weight initialization\n    base_init = [\"normal\", 0.01] # Initialization parameters for weights\n    embed_init = [\"normal\", 0.01] # Intialization parameters for embeddings\n\n    # Model hyperparameters\n    dropout = 0.1 # The dropout probability for all fully connected layers in the embeddings, encoder, and pooler\n    dropatt = 0.1  # The dropout ratio for the attention probabilities\n    dim_inner = 1000 # Inner dimension within Positionwise FF \n    num_heads = 10 # Number of heads in Multihead attention\n    num_layers = 4 # Number of layers in Transformer-XL\n    tie_embedding = True # Share weights between input embedding and output layer\n    dim_model = 500 # Dimensionality of the model\u2019s hidden states\n```\n\n\n```python\ntrain_cfg = TrainConfig()\n```\n\n### Building the data loader\n\nWhile the Transformer-XL data loader resembles the standard data loading pipeline in language models like the RNN, it is different in that the Transformer-XL memory persists across batches.\n\nYou need to ensure that batch elements across batches in the Transformer-XL correspond to the same MIDI file. This ensures that the Transformer-XL memory contains the cached segments preceding the current segment when you train using minibatches.\n\n\n\nIn the figure above, we depict two successive batches (each with 2 elements) that the model is trained on. Each batch element is a sequence of length `tgt_len`. The batches are constructed so that each batch element (Element 1 in Batch 1 and Element 1 in Batch 2) uses segments from the same MIDI file. This ensures that the Transformer-XL memory for a batch element caches segments from same MIDI file that the current segment is from. \n\nYou will also use a `BaseVocab` class that will help you work with the Magenta vocabulary. This class abstracts several functions that map from token names (NOTE_ON_70 etc.) to indices.\n\n\n```python\nclass MusicDataset:\n    def __init__(self, data_dir):\n        \"\"\"Load the music corpus\n        Args:\n            data_dir: The base folder of the preprocessed music dataset\n        \"\"\"\n        self.vocab_path = os.path.join(data_dir, \"vocab.txt\")\n        self.train_folder = os.path.join(data_dir, \"train\")\n        self.valid_folder = os.path.join(data_dir, \"valid\")\n        self.test_folder = os.path.join(data_dir, \"test\")\n        all_tokens = []\n        with open(self.vocab_path, \"r\") as f:\n            all_tokens = [token.strip() for token in f]\n        \n        # BaseVocab class that provides useful functions to interact with vocabulary\n        self.vocab = BaseVocab(all_tokens)\n\n        self.train_data = self.load_cache_data(self.train_folder)\n        self.valid_data = self.load_cache_data(self.valid_folder)\n        self.test_data = self.load_cache_data(self.test_folder)\n\n        # Insert start tokens\n        \n        self.train_data = [\n            torch.from_numpy(np.insert(arr, 0, self.vocab.bos_id))\n            for arr in self.train_data\n        ]\n        self.valid_data = [\n            torch.from_numpy(np.insert(arr, 0, self.vocab.bos_id))\n            for arr in self.valid_data\n        ]\n        self.test_data = [\n            torch.from_numpy(np.insert(arr, 0, self.vocab.bos_id))\n            for arr in self.test_data\n        ]\n\n        # Extract sequence lengths for the different splits\n        self.train_seq_length = np.array(\n            [ele.shape[0] for ele in self.train_data], dtype=np.int32\n        )\n        self.valid_seq_length = np.array(\n            [ele.shape[0] for ele in self.valid_data], dtype=np.int32\n        )\n        self.test_seq_length = np.array(\n            [ele.shape[0] for ele in self.test_data], dtype=np.int32\n        )\n        print(\n            \"Loaded Data, #Samples Train/Val/Test:{}/{}/{}\".format(\n                len(self.train_data), len(self.valid_data), len(self.test_data)\n            )\n        )\n        print(\n            \"#Avg Length:{}/{}/{}\".format(\n                np.mean([len(ele) for ele in self.train_data]),\n                np.mean([len(ele) for ele in self.valid_data]),\n                np.mean([len(ele) for ele in self.test_data]),\n            )\n        )\n        print(\n            \"#Total Number of Valid/Test Tokens: {}/{}\".format(\n                (self.valid_seq_length - 1).sum(), (self.test_seq_length - 1).sum()\n            )\n        )\n\n    def load_cache_data(self, dir_name):\n        \"\"\"\n        Returns the loaded numpy dataset from dir_name\n        \"\"\"\n        all_fnames = sorted(glob.glob(os.path.join(dir_name, \"*.npy\")))\n        print(\"Loading #{} files from {}\".format(len(all_fnames), dir_name))\n        # Create a large array\n        with multiprocessing.Pool(8) as pool:\n            dat = pool.map(np.load, all_fnames)\n        return np.array(dat)\n\n    def get_iterator(\n            self, batch_size, bptt, device, split=\"train\", do_shuffle=True, seed=None\n    ):\n        \"\"\"\n        Function that returns an iterator over the dataset specified by \n        batch_size, bptt, device and split\n        \"\"\"\n        if split == \"train\":\n            split_data = self.train_data\n            split_seq_lengths = self.train_seq_length\n        elif split == \"valid\":\n            split_data = self.valid_data\n            split_seq_lengths = self.valid_seq_length\n        elif split == \"test\":\n            split_data = self.test_data\n            split_seq_lengths = self.test_seq_length\n        else:\n            raise NotImplementedError\n        total_sample_num = len(split_data)\n\n        def iterator():\n            perm = np.arange(total_sample_num)\n            if do_shuffle:\n                rng = np.random.RandomState(seed)\n                rng.shuffle(perm)\n            assert batch_size < total_sample_num\n            tracker_list = [(i, 0) for i in range(batch_size)]\n            next_idx = batch_size\n            data = torch.LongTensor(bptt, batch_size)\n            target = torch.LongTensor(bptt, batch_size)\n\n            while True:\n\n                # Fill with pad_id\n                data[:] = self.vocab.pad_id\n                target[:] = self.vocab.pad_id\n\n                batch_token_num = 0\n                for i in range(batch_size):\n                    idx, pos = tracker_list[i]\n                    while idx < total_sample_num:\n                        seq_id = perm[idx]\n                        seq_length = split_seq_lengths[seq_id]\n                        if pos + 1 >= seq_length:\n                            idx, pos = next_idx, 0\n                            tracker_list[i] = (idx, pos)\n                            next_idx += 1\n                            continue\n                        else:\n                            n_new = min(seq_length - 1 - pos, bptt)\n                            data[:n_new, i] = split_data[seq_id][pos: pos + n_new]\n                            target[:n_new, i] = split_data[seq_id][\n                                                (pos + 1): (pos + 1 + n_new)]\n                            batch_token_num += n_new\n                            tracker_list[i] = (idx, pos + n_new)\n\n                            break\n                            \n                if batch_token_num == 0:\n                    # Haven't found anything to fill. This indicates we have reached the end\n                    if do_shuffle:\n                        rng.shuffle(perm)\n                    else:\n                        return  # One pass dataloader when do_shuffle is False\n                    tracker_list = [(i, 0) for i in range(batch_size)]\n                    next_idx = batch_size\n                    continue\n\n                yield data.to(device), target.to(device), batch_token_num\n\n        return iterator\n\n```\n\n### Loading data\n\nYou will use the Dataloader you just defined to load the dataset.\n\n\n\n```python\ndataset = MusicDataset(train_cfg.data_dir) # Dataset path\nvocab = dataset.vocab  # Vocabulary class\nseed = train_cfg.seed  # seed to ensure constant behavior across runs\ndevice = (\n    torch.device(\"cpu\") if not torch.cuda.is_available() else torch.device(\"cuda:0\")\n)\n\nbatch_size = train_cfg.batch_size\n\n# Train split iterator\ntrain_iter = dataset.get_iterator(\n    batch_size, train_cfg.tgt_len, device, \"train\", do_shuffle=True, seed=seed\n)\n\n# Validation split iterator\nval_iter = dataset.get_iterator(\n    train_cfg.eval_batch_size,\n    train_cfg.eval_tgt_len,\n    device,\n    \"valid\",\n    do_shuffle=False,\n    seed=seed,\n)\n\n# Test split iterator\ntest_iter = dataset.get_iterator(\n    train_cfg.eval_batch_size,\n    train_cfg.eval_tgt_len,\n    device,\n    \"test\",\n    do_shuffle=False,\n    seed=seed,\n)\n```\n\n### Evaluation loop\n\nYou will now define the evaluation loop used while training the model.\n\n\n```python\ndef evaluate(model, eval_iter):\n    \"\"\"\n    Function to compute validation negative log-likelihood (nll) of a model\n    on a dataset specified with the eval_iter iterator\n    \"\"\"\n    \n    # Turn on evaluation mode def disables dropout.\n    model.eval()\n\n    model.reset_length(tgt_len=train_cfg.eval_tgt_len, \n                       mem_len=train_cfg.eval_mem_len)\n    \n    # Evaluation\n    total_token_num = 0\n    total_nll = 0.0\n\n    with torch.no_grad():\n        mems = None\n\n        for i, (data, target, batch_token_num) in enumerate(eval_iter()):\n\n            loss, mems = model(data, target, mems)\n            loss = loss[target != dataset.vocab.pad_id]\n            loss = loss.mean()\n            total_nll += batch_token_num * loss.float().item()\n            total_token_num += batch_token_num\n    \n    model.reset_length(train_cfg.tgt_len, train_cfg.mem_len)\n    model.train()\n    \n    return total_token_num, total_nll\n\n```\n\n### Training loop\n\nYou will now write the training loop. First a few helper functions that help with training.\n\n\n```python\n# Dictionaries to record train, val and test losses\ntrain_losses = dict()\nval_losses = dict()\ntest_losses = dict()\n```\n\n\n```python\ndef plot_losses_while_training():\n    \"\"\"\n    Helper function to plot losses while training\n    \"\"\"\n    display.clear_output(wait=True)\n    fig = plt.figure(figsize=(15, 5))\n\n    def plot_lines(loss_dic, color):\n        iters = list(loss_dic.keys())\n        vals = [loss_dic[i] for i in iters]\n        return plt.plot(iters, vals, color)\n\n    (line1,) = plot_lines(train_losses, \"r\")\n    (line2,) = plot_lines(val_losses, \"k\")\n    (line3,) = plot_lines(test_losses, \"b\")\n\n    plt.xlabel(\"Iterations\")\n    plt.ylabel(\"Losses\")\n    plt.legend((line1, line2, line3), (\"train-loss\", \"val-loss\", \"test-loss\"))\n    display.display(fig)\n    plt.close()\n```\n\n\n```python\ndef evaluate_and_log(model, train_step, mode=\"eval\"):\n    \"\"\"\n    Helper function to evaluate model in \"eval\" or \"test\" mode and log losses\n    \"\"\"\n    start_time = time.time()\n    \n    eval_iter = val_iter if mode==\"eval\" else test_iter\n    token_num, total_nll = evaluate(model=model, eval_iter=eval_iter)\n\n    nll = total_nll / token_num\n\n    pprint(\n        f\"{mode} step {train_step}, time={(time.time() - start_time)}s, {mode} nll={nll},\" \n        f\"{mode} ppl={math.exp(nll)}, #evaluated tokens={token_num}\"\n        )\n    \n    return nll\n```\n\nYou are now ready to write the entire training loop. We minimize the [negative log-likelihood (NLL)](https://d2l.ai/chapter_appendix-mathematics-for-deep-learning/maximum-likelihood.html) loss that is standard practice in language modeling.\n\n\n```python\ndef train(model):\n    \"\"\"\n    Main training function that iterates over epochs, computes the loss,\n    computes gradients via the backward pass and updates weights using \n    the optimizer.\n    \n    Also includes functionality for plotting losses realtime and saving the\n    best model checkpoint\n    \n    \"\"\"\n    train_step = 0\n    best_val_nll = np.inf\n\n    log_train_loss = torch.tensor(0.0).float().to(device)\n    log_grad_norm = torch.tensor(0.0).float().to(device)\n    log_token_num = torch.tensor(0).to(device)\n\n    log_start_time = time.time()\n\n    mems = None\n\n    # Define optimizer\n    if train_cfg.optim.lower() == \"adam\":\n        optimizer = optim.Adam(\n            model.parameters(), lr=train_cfg.lr, weight_decay=train_cfg.weight_decay\n        )\n    else:\n        raise NotImplementedError\n\n    # Define scheduler\n    if train_cfg.scheduler == \"inv_sqrt\":\n        # originally used for Transformer (in Attention is all you need)\n        def lr_lambda(step):\n            # return a multiplier instead of a learning rate\n            if step == 0 and train_cfg.warmup_step == 0:\n                return 1.0\n            else:\n                return (\n                    max(\n                        (train_cfg.warmup_step ** 0.5) / (step ** 0.5),\n                        train_cfg.lr_min / train_cfg.lr,\n                    )\n                    if step > train_cfg.warmup_step\n                    else step / train_cfg.warmup_step\n                )\n\n        scheduler = optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lr_lambda)\n    else:\n        raise NotImplementedError\n\n    train_real_iter = train_iter()\n\n    # Iterate over epochs\n    for batch, (data, target, batch_token_num) in enumerate(train_real_iter):\n\n        model.zero_grad()\n\n        loss, mems = model(data, target, mems)\n\n        loss = loss[target != dataset.vocab.pad_id]\n        loss = loss.float().mean()\n\n        # Record total loss over all non pad tokens\n        log_train_loss += loss.item() * (target != dataset.vocab.pad_id).sum()\n\n        loss.backward()\n\n        log_token_num += int(batch_token_num)\n\n        grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), train_cfg.clip)\n\n        log_grad_norm += grad_norm\n        optimizer.step()\n        optimizer.zero_grad()\n\n        # step-wise learning rate annealing\n        train_step += 1\n        scheduler.step()\n\n        # Log losses\n        if train_step % train_cfg.log_interval == 0:\n            \n            log_train_loss /= log_token_num\n            log_grad_norm /= train_cfg.log_interval\n\n            elapsed = time.time() - log_start_time\n            pprint(\n                \"train Step {}/{}, lr={:f}, tokens/s={:.1f},\"\n                \" train nll={:.4f}, train ppl={:.2f}, grad norm={}\".format(\n                    train_step,\n                    train_cfg.max_step,\n                    optimizer.param_groups[0][\"lr\"],\n                    log_token_num.item() / elapsed,\n                    log_train_loss.item(),\n                    math.exp(log_train_loss.item()),\n                    log_grad_norm.item(),\n                )\n            )\n\n            # Save train loss\n            train_losses[train_step] = log_train_loss.item()\n\n            log_train_loss[()] = 0\n            log_grad_norm[()] = 0\n            log_token_num[()] = 0\n\n            log_start_time = time.time()\n        \n        # Evaluate\n        if train_step % train_cfg.eval_interval == 0:\n            val_nll = evaluate_and_log(model, train_step, mode=\"val\")\n            \n            # Save val loss\n            val_losses[train_step] = val_nll.item()\n\n            # Save best model\n            if val_nll < best_val_nll or train_cfg.save_all_test_losses:\n                \n                if val_nll < best_val_nll:\n                    best_val_nll = val_nll\n\n                    save_checkpoint(\n                        model,\n                        train_step,\n                        best_val_nll,\n                        train_cfg.save_path,\n                        \"checkpoint_best.pt\",\n                    )\n\n                # Get test nll\n                test_nll = evaluate_and_log(model, train_step, mode=\"test\")\n                \n                # Save test loss\n                test_losses[train_step] = test_nll.item()\n        \n        # Plot losses while training\n        if train_cfg.plot_losses_while_training and train_step % train_cfg.plot_interval == 0:\n            plot_losses_while_training()\n\n        if train_step == train_cfg.max_step:\n            pprint(\"-\" * 100)\n            pprint(\"Max steps reached. End of training\")\n            break\n```\n\n### Weight initialization\n\nBefore you begin training, you will define functions to initialize the weights in the model. \n\n\n\n```python\ndef init_weight(weight):\n    \"\"\"\n    Function to help initialize all layer weights\n    \"\"\"\n    if train_cfg.base_init[0] == \"normal\":\n        init_std = train_cfg.base_init[1]\n        nn.init.normal_(weight, 0.0, init_std)\n    else:\n        raise NotImplementedError\n        \ndef init_embed(weight):\n    \"\"\"\n    Function to help initialize embedding weights\n    \"\"\"\n    if train_cfg.embed_init[0] == \"normal\":\n        init_std = train_cfg.embed_init[1]\n        nn.init.normal_(weight, 0.0, init_std)\n    else:\n        raise NotImplementedError\n\ndef init_bias(bias):\n    \"\"\"\n    Function to help initialize layer bias\n    \"\"\"\n    nn.init.constant_(bias, 0.0)\n\ndef weights_init(m):\n    \"\"\"\n    Function that initializes layer weights and biases in the Transformer-XL\n    based on name \n    \"\"\"\n    classname = m.__class__.__name__\n    if classname.find(\"Linear\") != -1:\n        if hasattr(m, \"weight\") and m.weight is not None:\n            init_weight(m.weight)\n        if hasattr(m, \"bias\") and m.bias is not None:\n            init_bias(m.bias)\n    elif classname.find(\"Embedding\") != -1:\n        if hasattr(m, \"weight\"):\n            init_weight(m.weight)\n    elif classname.find(\"LayerNorm\") != -1:\n        if hasattr(m, \"weight\"):\n            nn.init.normal_(m.weight, 1.0, train_cfg.base_init[1])\n        if hasattr(m, \"bias\") and m.bias is not None:\n            init_bias(m.bias)\n    elif classname.find(\"TransformerXL\") != -1:\n        if hasattr(m, \"u\"):\n            init_weight(m.u)\n        if hasattr(m, \"v\"):\n            init_weight(m.v)\n\n```\n\n\n### Let's train the model\nYou shall now proceed to define the model, initialize weights and then begin training.\n\n\n\n```python\n# Let us save our config file along with the saved checkpoints\ntrain_cfg.save(os.path.join(train_cfg.save_path, \"exp.yaml\"))\n```\n\n\n```python\n# Create the model\ntransformerxl = TransformerXL(n_layer=train_cfg.num_layers, n_head=train_cfg.num_heads,\n                            dim_model=train_cfg.dim_model, dim_inner=train_cfg.dim_inner,       \n                            dropout=train_cfg.dropout, dropatt=train_cfg.dropatt,\n                            tie_weight=train_cfg.tie_embedding, tgt_len=train_cfg.tgt_len,\n                            mem_len=train_cfg.mem_len, n_token=len(vocab),)\n\n# Apply weight initialization to model\ntransformerxl.apply(weights_init)\ntransformerxl.word_emb.apply(weights_init) # ensure embedding init is not overridden by out_layer in case of weight sharing\n\n# Send model to device\ntransformerxl = transformerxl.to(device)\n\n```\n\nYou will now call `train` that also plots the train and validation losses while training. With the default parameters training for 5000 iterations is sufficient.\n\n\n```python\ntrain(transformerxl)\n```\n\n### Load a pretrained checkpoint (Optional)\n\nIf your model did not finish training, uncomment the cell below so that you can load a pretrained checkpoint.\n\n\n```python\n# pretrained_path = 'pretrained_checkpoints'\n\n# # Load pretrained config file\n# train_cfg = TrainConfig.load(os.path.join(pretrained_path,'exp.yaml'))\n\n# # Create the model\n# transformerxl = TransformerXL(n_layer=train_cfg.num_layers, n_head=train_cfg.num_heads,\n#                             dim_model=train_cfg.dim_model, dim_inner=train_cfg.dim_inner,       \n#                             dropout=train_cfg.dropout, dropatt=train_cfg.dropatt,\n#                             tie_weight=train_cfg.tie_embedding, tgt_len=train_cfg.tgt_len,\n#                             mem_len=train_cfg.mem_len, n_token=len(vocab),)\n\n# # Load pretrained checkpoint\n# model_fp = os.path.join(pretrained_path,'checkpoint_best.pt')\n# checkpoint = torch.load(model_fp)\n# transformerxl.load_state_dict(checkpoint[\"model\"])\n\n# # Send model to device\n# transformerxl = transformerxl.to(device)\n\n# # Load saved losses\n# with open(os.path.join(pretrained_path,'losses.pickle'),'rb') as handle:\n#     losses = pickle.load(handle)\n# train_losses = losses['train_losses']\n# val_losses = losses['val_losses']\n# test_losses = losses['test_losses']\n```\n\n### Plot losses\n\nBelow, the training, validation and test losses are plotted after training is completed. The training loss is non-increasing while the validation and test losses increase after a certain number of iterations due to overfitting. Our best checkpoint corresponds to the model with lowest validation loss.\n\n\n\n```python\n# Plot train, validation and test losses\nplot_losses(train_losses, val_losses, test_losses)\n```\n\n## Generating samples \n\n\nCongratulations! You have now trained your very own Transformer-XL model, and you can now use this trained model to extend an input melody file.\n\nThe model generates a melody by sampling a sequence from the model's distribution.\n\nSampling in an autoregressive model like the Transformer is an iterative process. To sample a sequence from the model  sample the next token from the model's output probabability distribution given the history of tokens. \n\nYou will look at two different sampling techniques in this notebook: TopK and Nucleus. A `threshold` value called the sampling threshold is associated with each. \n\n__TopK sampling__\n\n \n\nIn TopK sampling, the model samples from the K-tokens that have the highest probability of occurring. Here k is set using the `threshold` parameter.\n\nIf your sampling threshold is set high, then the number of available tokens (K) is large. This means the model can choose from a wider variety of musical tokens. In your extended melody, this means the generated notes are likely to be more diverse, but it comes at the cost of potentially creating less coherent music.\n\nOn the other hand, if you choose a threshold value that is too low, the model is limited to choosing from a smaller set of tokens which the model believes has a higher probability of being correct. In your extended melody, you might notice less musical diversity and more repetitive results. \n\n__Nucleus sampling__\n\n \n\nInstead of sampling only from the most likely K tokens, nucleus sampling chooses from the smallest possible set of tokens whose cumulative probability exceeds the probability p. p is set using the `threshold` parameter. The probability mass is then redistributed among this set of tokens. This way, the size of the set of tokens can dynamically increase and decrease according to the next word's probability distribution.\n\nAt a high level, Nucleus sampling is very similar to TopK. Setting a higher sampling threshold allows for more diversity at the cost of coherence or consistency. \n\n__Other inference parameters__\n\n- Number of Conditional Tokens: This parameter tells the model what portion of the input melody to condition on during inference. \n\n- Temperature: To create the output probability distribution, the final layer uses a softmax activation. You can [change the temperature](https://console.aws.amazon.com/deepcomposer/home?region=us-east-1#musicStudio) for the softmax to produce different levels of creativity in the outputs generated by the model.\n\n- Generation length: The number of tokens to generate using the Transformer-XL. \n\nYou can change the inference parameters in `InferenceConfig` class to observe differences in the quality of the music generated.\n\n### Inference hyperparameters\n\n\n```python\n@dataclass\nclass InferenceConfig:\n    \"\"\"\n    Defines configuration parameters used during inference (melody extension)\n    \"\"\"\n    \n    # Model parameters\n    memory_length = 4096\n\n    # Sampling parameters\n    technique = 'nucleus' # topk or nucleus\n    threshold = 0.95 # theshold acts as both k [0-309] for topk sampling or p [0-1] for nucleus sampling\n    temperature = 0.95\n\n    # Input parameters  \n    num_conditional_tokens = 100 # Number of tokens [>= 1] from the input melody that is used\n    \n    # Generation parameters\n    generation_length = 1500 # Number of tokens to extend the melody\n\n```\n\n\n```python\ninference_cfg = InferenceConfig()\n```\n\n### Input midi file to extend\n\n\nBelow, you can update the code cell to select an input MIDI melody to extend.\n\nThe default provided is a MIDI from the test set.\n\n\n```python\ninput_melody_path = 'data/jsb_chorales_numpy/test/9.npy'\n```\n\n#### To choose a  custom input melody (Optional)\n\n1. Open the `sample_inputs` directory\n2. Upload the file that you want to use into this folder. For example, `new_world.midi`\n3. Uncomment and run the following cell replacing midi_file with the custom file path\n\n\n```python\n# # Input melody name\n# midi_file = \"sample_inputs/new_world.midi\"\n\n# # Convert midi to numpy \n# out_dir = 'sample_inputs'\n# music_encoder.run_to_npy(midi_file, out_dir)\n\n# filename = os.path.splitext(os.path.basename(midi_file))[0]\n# input_melody_path = os.path.join(out_dir, filename + '.npy')\n```\n\n### Let's run inference!\n\nYou will first define a few helper functions for top-k and nucleus sampling.\n\n\n```python\ndef get_topk(probs):\n    \"\"\"\n    Apply Top-k sampling mask to probabilities vector probs\n    \"\"\"\n    # Apply topk mask\n    topk = int(inference_cfg.threshold)\n    _, top_idx = torch.topk(probs, topk)\n    mask = torch.zeros_like(probs)\n    mask[top_idx] = 1.0\n    probs *= mask\n    probs /= probs.sum()\n    \ndef get_topp(probs): \n    \"\"\"\n    Apply nucleus sampling mask to probabilities vector probs\n    \"\"\"\n    p = inference_cfg.threshold\n    sorted_probs, sorted_indices = torch.sort(probs, descending=True)\n\n    cumulative_probs = torch.cumsum(sorted_probs, dim=0)\n\n    # Remove tokens with cumulative probability above the threshold\n    sorted_indices_to_remove = cumulative_probs >= p\n\n    # Shift the indices to the right to keep also the first token above the threshold\n    sorted_indices_to_remove[1:] = sorted_indices_to_remove[:-1].clone()\n    sorted_indices_to_remove[0] = 0\n\n    # scatter sorted tensors to original indexing\n    indices_to_remove = sorted_indices_to_remove.scatter(\n        dim=0, index=sorted_indices, src=sorted_indices_to_remove\n    )\n    probs[indices_to_remove] = 0\n    probs /= probs.sum()\n```\n\n#### Prepare model for inference\n\n\n```python\ntransformerxl.eval()\n\n# Reset tgt_length to 1, so that 1 token is generated incrementally\ntransformerxl.reset_length(1, inference_cfg.memory_length)\n```\n\n#### Define function to generate tokens incrementally\n\n\n```python\ndef extend_melody():\n    \"\"\"\n    Loads the input melody specified by input_melody_path and returns\n    the extended melody based on parameters specified in inference_cfg\n    \n    \"\"\"\n    # Load input melody\n    \n    conditional_data = np.load(input_melody_path).tolist()\n    print('Loaded conditional file {}'.format(input_melody_path))\n    \n    num_conditional_tokens = inference_cfg.num_conditional_tokens\n\n    seq = [0]\n    mems = None\n    \n    with torch.no_grad():   \n        \n        # Pass prefix through Transformer-XL\n        context = np.array(seq + conditional_data[:num_conditional_tokens-1], dtype=np.int32)[:, np.newaxis]\n        context = torch.from_numpy(context).to(device).type(torch.long)\n        ret = transformerxl.forward_generate(context, mems)\n        _, mems = ret\n        seq = seq + conditional_data[:num_conditional_tokens]\n\n        # Load generation length\n        generation_length = inference_cfg.generation_length\n        \n        for _ in range(generation_length):\n          \n            # Create input array from last token\n            inp = np.array([seq[-1]], dtype=np.int32)[:, np.newaxis]\n            inp = torch.from_numpy(inp).to(device).type(torch.long)\n            \n            # Generate next token incrementally\n            ret = transformerxl.forward_generate(inp, mems)\n            all_logits, mems = ret\n\n            # Select last tinmestep from the single batch item\n            logits = all_logits[-1, 0]\n\n            # Do not predict start token\n            logits = logits[1:]\n\n            # Handle temp 0 (argmax) case\n            if inference_cfg.temperature == 0:\n                probs = torch.zeros_like(logits)\n                probs[logits.argmax()] = 1.0\n            else:\n                # Apply temperature normalization\n                logits /= inference_cfg.temperature\n\n                # Compute softmax\n                probs = F.softmax(logits, dim=-1)\n\n            probs = F.pad(probs, [1, 0])\n\n            # Apply sampling masks\n            if inference_cfg.technique == \"topk\":\n                get_topk(probs)\n            elif inference_cfg.technique == \"nucleus\":\n                get_topp(probs)\n                \n            # Sample from probabilities\n            token = torch.multinomial(probs, 1)\n            token = int(token.item())\n            \n            # Add to output list\n            seq.append(token)\n\n        # Convert output list to numpy, ignore start token and return\n        return np.asarray(seq[1:])\n```\n\n#### Run inference and save outputs\n\n\n```python\n# Run inference\noutputs = extend_melody()\n\n# Save numpy outputs\noutput_dir = \"sample_outputs\"\noutput_path = os.path.join(output_dir, \"sample_melody.npy\")\nnp.save(output_path, outputs)\n```\n\n### Listen to your output\n\n You can listen to the extended melody.\n\n\n\n```python\n# Convert numpy to midi\nmusic_encoder.run_npy_to_midi(output_path, output_dir)\n```\n\n\n```python\n# Play midi\nfilename, _ = os.path.splitext(os.path.basename(output_path))\nmidi_name = os.path.join(output_dir, filename + \".mid\")\nplay_midi(midi_name)\n```\n\n## Cleaning up \n\nAfter completing this notebook, make sure that you stop your Amazon SageMaker notebook instance so that you don't incur unexpected costs. \n\n#### To stop an Amazon SageMaker notebook instance \n\n1. Open the [Amazon SageMaker console](https://console.aws.amazon.com/sagemaker/home?region=us-east-1#/dashboard).\n\n2. In the navigation pane, choose **Notebook instances**.\n\n3. Choose the notebook instance that you want to stop. \n\n4. From the **Actions** menu, choose **Stop**.\n\n>**NOTE**: When your notebook instance stops, its status changes from **In service** to **Stopped**. \n\n# More info\n\nFor more open-source implementations of generative models for music, see the following:\n\n- [Transformer-GAN](https://www.amazon.science/publications/symbolic-music-generation-with-transformer-gans): Trains the Transformer-XL in a GAN framework to generate music\n\n- [LakhNES](https://arxiv.org/abs/1907.04868): Transformer-XL to generate multi-instrumental scores from the NES-MDB dataset\n\n- [Pop music transformer](https://arxiv.org/abs/2002.00212): Transformer-XL to generate pop music by imposing a metrical structure\n\n- [Jukebox](https://openai.com/blog/jukebox/): Uses various neural nets to generate music, including rudimentary singing, as raw audio in a variety of genres and artist styles\n- [Music Transformer](https://github.com/tensorflow/magenta/tree/master/magenta/models/score2perf): Uses transformers to generate music\n- [MuseNet](https://openai.com/blog/musenet/): Uses GPT2, a large-scale Transformer model, to generate multi instrumental music\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "4ee5b63199e8dd8bae66d5c9ce02ab82bc8bafd2", "size": 109128, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "transformer-xl/transformerxl.ipynb", "max_stars_repo_name": "froggie901/aws-deepcomposer-samples", "max_stars_repo_head_hexsha": "142b98b130efbb4ed91f22b54919d71877146c73", "max_stars_repo_licenses": ["MIT", "MIT-0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-07T13:28:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-07T13:28:17.000Z", "max_issues_repo_path": "notebooks/AWS DeepComposer/transformer-xl/transformerxl.ipynb", "max_issues_repo_name": "jesussantana/AWS-Machine-Learning-Foundations", "max_issues_repo_head_hexsha": "526eddb486fe8398cafcc30184c4ecce49df5816", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/AWS DeepComposer/transformer-xl/transformerxl.ipynb", "max_forks_repo_name": "jesussantana/AWS-Machine-Learning-Foundations", "max_forks_repo_head_hexsha": "526eddb486fe8398cafcc30184c4ecce49df5816", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-27T13:01:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-07T21:36:49.000Z", "avg_line_length": 40.8719101124, "max_line_length": 1492, "alphanum_fraction": 0.57842167, "converted": true, "num_tokens": 18254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180267058489, "lm_q2_score": 0.04146227552445055, "lm_q1q2_score": 0.01611298769704619}}
{"text": "# Best practices\n\nLet's start with pep8 (https://www.python.org/dev/peps/pep-0008/)\n\n> Imports should be grouped in the following order:\n\n> - standard library imports\n> - related third party imports\n> - local application/library specific imports\n\n> You should put a blank line between each group of imports.\nPut any relevant __all__ specification after the imports.\n\n\n\n\n```python\n%matplotlib inline\n%config InlineBackend.figure_format='retina' \n\n# Add this to python2 code to make life easier\nfrom __future__ import absolute_import, division, print_function\n\nimport numpy as np\n# don't do:\n# from numpy import *\n```\n\n\n```python\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport ipywidgets\nimport os\nimport sys\nimport warnings\n\nsns.set()\nplt.rcParams['figure.figsize'] = (12, 8)\nsns.set_style(\"darkgrid\")\nsns.set_context(\"poster\", font_scale=1.3)\n\nwarnings.filterwarnings('ignore')\n```\n\n# Look at Pandas Dataframes\n\n_this is italicized_\n\n\n```python\ndf = pd.read_csv(\"../data/coal_prod_cleaned.csv\")\n```\n\n\n```python\ndf.head()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>MSHA_ID</th>\n      <th>Average_Employees</th>\n      <th>Company_Type</th>\n      <th>Labor_Hours</th>\n      <th>Mine_Basin</th>\n      <th>Mine_County</th>\n      <th>Mine_Name</th>\n      <th>Mine_State</th>\n      <th>Mine_Status</th>\n      <th>Mine_Type</th>\n      <th>Operating_Company</th>\n      <th>Operating_Company_Address</th>\n      <th>Operation_Type</th>\n      <th>Production_short_tons</th>\n      <th>Union_Code</th>\n      <th>Year</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>103295</td>\n      <td>18.0</td>\n      <td>Independent Producer Operator</td>\n      <td>39175.0</td>\n      <td>Appalachia Southern</td>\n      <td>Bibb</td>\n      <td>Seymour Mine</td>\n      <td>Alabama</td>\n      <td>Active</td>\n      <td>Surface</td>\n      <td>Hope Coal Company Inc</td>\n      <td>P.O. Box 249, Maylene, AL 35114</td>\n      <td>Mine only</td>\n      <td>105082.0</td>\n      <td>NaN</td>\n      <td>2008</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>103117</td>\n      <td>19.0</td>\n      <td>Operating Subsidiary</td>\n      <td>29926.0</td>\n      <td>Appalachia Southern</td>\n      <td>Cullman</td>\n      <td>Mine #2, #3, #4</td>\n      <td>Alabama</td>\n      <td>Active, men working, not producing</td>\n      <td>Surface</td>\n      <td>Twin Pines Coal Company Inc</td>\n      <td>1874 County Road 15, Bremen, AL 35033</td>\n      <td>Mine only</td>\n      <td>10419.0</td>\n      <td>NaN</td>\n      <td>2008</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>103361</td>\n      <td>20.0</td>\n      <td>Operating Subsidiary</td>\n      <td>42542.0</td>\n      <td>Appalachia Southern</td>\n      <td>Cullman</td>\n      <td>Cold Springs West Mine</td>\n      <td>Alabama</td>\n      <td>Active</td>\n      <td>Surface</td>\n      <td>Twin Pines Coal Company</td>\n      <td>74 Industrial Parkway, Jasper, AL 35502</td>\n      <td>Mine only</td>\n      <td>143208.0</td>\n      <td>NaN</td>\n      <td>2008</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>100759</td>\n      <td>395.0</td>\n      <td>Operating Subsidiary</td>\n      <td>890710.0</td>\n      <td>Appalachia Southern</td>\n      <td>Fayette</td>\n      <td>North River # 1 Underground Mi</td>\n      <td>Alabama</td>\n      <td>Active</td>\n      <td>Underground</td>\n      <td>Chevron Mining Inc</td>\n      <td>3114 County Road 63 S, Berry, AL 35546</td>\n      <td>Mine and Preparation Plant</td>\n      <td>2923261.0</td>\n      <td>United Mine Workers of America</td>\n      <td>2008</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>103246</td>\n      <td>22.0</td>\n      <td>Independent Producer Operator</td>\n      <td>55403.0</td>\n      <td>Appalachia Southern</td>\n      <td>Franklin</td>\n      <td>Bear Creek</td>\n      <td>Alabama</td>\n      <td>Active</td>\n      <td>Surface</td>\n      <td>Birmingham Coal &amp; Coke Co., In</td>\n      <td>912 Edenton Street, Birmingham, AL 35242</td>\n      <td>Mine only</td>\n      <td>183137.0</td>\n      <td>NaN</td>\n      <td>2008</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf.shape\n```\n\n\n\n\n    (9042, 16)\n\n\n\n\n```python\n# import qgrid # Put imports at the top\n# qgrid.nbinstall(overwrite=True)\n\n# qgrid.show_grid(df[['MSHA_ID',\n#                     'Year',\n#                     'Mine_Name',\n#                     'Mine_State',\n#                     'Mine_County']], remote_js=True)\n# Check out http://nbviewer.ipython.org/github/quantopian/qgrid/blob/master/qgrid_demo.ipynb for more (including demo)\n```\n\n# Pivot Tables w/ pandas\n\nhttp://nicolas.kruchten.com/content/2015/09/jupyter_pivottablejs/\n\n\n```python\n!conda install pivottablejs -y\n```\n\n    Fetching package metadata ...........\n    Solving package specifications: .\n    \n    Package plan for installation in environment /Users/jonathan/miniconda3/envs/testpy3:\n    \n    The following NEW packages will be INSTALLED:\n    \n        pivottablejs: 2.7.0-py36_0\n    \n    pivottablejs-2 100% |################################| Time: 0:00:00   3.30 MB/s\n\n\n\n```python\ndf = pd.read_csv(\"../data/mps.csv\", encoding=\"ISO-8859-1\")\n```\n\n\n```python\ndf.head(10)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Name</th>\n      <th>Party</th>\n      <th>Province</th>\n      <th>Age</th>\n      <th>Gender</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Liu, Laurin</td>\n      <td>NDP</td>\n      <td>Quebec</td>\n      <td>22.0</td>\n      <td>Female</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Mourani, Maria</td>\n      <td>Bloc Quebecois</td>\n      <td>Quebec</td>\n      <td>43.0</td>\n      <td>Female</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Sellah, Djaouida</td>\n      <td>NDP</td>\n      <td>Quebec</td>\n      <td>NaN</td>\n      <td>Female</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>St-Denis, Lise</td>\n      <td>NDP</td>\n      <td>Quebec</td>\n      <td>72.0</td>\n      <td>Female</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Fry, Hedy</td>\n      <td>Liberal</td>\n      <td>British Columbia</td>\n      <td>71.0</td>\n      <td>Female</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>Turmel, Nycole</td>\n      <td>NDP</td>\n      <td>Quebec</td>\n      <td>70.0</td>\n      <td>Female</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Sgro, Judy</td>\n      <td>Liberal</td>\n      <td>Ontario</td>\n      <td>68.0</td>\n      <td>Female</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Raynault, Francine</td>\n      <td>NDP</td>\n      <td>Quebec</td>\n      <td>67.0</td>\n      <td>Female</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Davidson, Patricia</td>\n      <td>Conservative</td>\n      <td>Ontario</td>\n      <td>66.0</td>\n      <td>Female</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>Smith, Joy</td>\n      <td>Conservative</td>\n      <td>Manitoba</td>\n      <td>65.0</td>\n      <td>Female</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n# Enhanced Pandas Dataframe Display\n\n\n```python\n# Province, Party, Average, Age, Heatmap\n```\n\n\n```python\nfrom pivottablejs import pivot_ui\n```\n\n\n```python\npivot_ui(df)\n```\n\n\n\n\n\n\n\n\n\n\n# Tab\n\n\n```python\nimport numpy as np\n```\n\n\n```python\nnp.random.\n```\n\n## shift-tab\n\n\n```python\nnp.linspace(start=, )\n```\n\n## shift-tab-tab\n\n(equivalent in in Lab to shift-tab)\n\n\n```python\nnp.linspace(50, 150, num=100,)\n```\n\n## shift-tab-tab-tab-tab\n\n(doesn't work in lab)\n\n\n```python\nnp.linspace(start=, )\n```\n\n## ?\n\n\n```python\nnp.linspace?\n```\n\n\n    \u001b[0;31mSignature:\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlinspace\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mstart\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstop\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnum\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m50\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mendpoint\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mTrue\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mretstep\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mFalse\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdtype\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n    \u001b[0;31mDocstring:\u001b[0m\n    Return evenly spaced numbers over a specified interval.\n    \n    Returns `num` evenly spaced samples, calculated over the\n    interval [`start`, `stop`].\n    \n    The endpoint of the interval can optionally be excluded.\n    \n    Parameters\n    ----------\n    start : scalar\n        The starting value of the sequence.\n    stop : scalar\n        The end value of the sequence, unless `endpoint` is set to False.\n        In that case, the sequence consists of all but the last of ``num + 1``\n        evenly spaced samples, so that `stop` is excluded.  Note that the step\n        size changes when `endpoint` is False.\n    num : int, optional\n        Number of samples to generate. Default is 50. Must be non-negative.\n    endpoint : bool, optional\n        If True, `stop` is the last sample. Otherwise, it is not included.\n        Default is True.\n    retstep : bool, optional\n        If True, return (`samples`, `step`), where `step` is the spacing\n        between samples.\n    dtype : dtype, optional\n        The type of the output array.  If `dtype` is not given, infer the data\n        type from the other input arguments.\n    \n        .. versionadded:: 1.9.0\n    \n    Returns\n    -------\n    samples : ndarray\n        There are `num` equally spaced samples in the closed interval\n        ``[start, stop]`` or the half-open interval ``[start, stop)``\n        (depending on whether `endpoint` is True or False).\n    step : float, optional\n        Only returned if `retstep` is True\n    \n        Size of spacing between samples.\n    \n    \n    See Also\n    --------\n    arange : Similar to `linspace`, but uses a step size (instead of the\n             number of samples).\n    logspace : Samples uniformly distributed in log space.\n    \n    Examples\n    --------\n    >>> np.linspace(2.0, 3.0, num=5)\n    array([ 2.  ,  2.25,  2.5 ,  2.75,  3.  ])\n    >>> np.linspace(2.0, 3.0, num=5, endpoint=False)\n    array([ 2. ,  2.2,  2.4,  2.6,  2.8])\n    >>> np.linspace(2.0, 3.0, num=5, retstep=True)\n    (array([ 2.  ,  2.25,  2.5 ,  2.75,  3.  ]), 0.25)\n    \n    Graphical illustration:\n    \n    >>> import matplotlib.pyplot as plt\n    >>> N = 8\n    >>> y = np.zeros(N)\n    >>> x1 = np.linspace(0, 10, N, endpoint=True)\n    >>> x2 = np.linspace(0, 10, N, endpoint=False)\n    >>> plt.plot(x1, y, 'o')\n    [<matplotlib.lines.Line2D object at 0x...>]\n    >>> plt.plot(x2, y + 0.5, 'o')\n    [<matplotlib.lines.Line2D object at 0x...>]\n    >>> plt.ylim([-0.5, 1])\n    (-0.5, 1)\n    >>> plt.show()\n    \u001b[0;31mFile:\u001b[0m      ~/miniconda3/envs/insightpy/lib/python3.6/site-packages/numpy/core/function_base.py\n    \u001b[0;31mType:\u001b[0m      function\n\n\n\n## ??\n\n(Lab can scroll if you click)\n\n\n```python\nnp.linspace??\n```\n\n\n    \u001b[0;31mSignature:\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlinspace\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mstart\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstop\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnum\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m50\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mendpoint\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mTrue\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mretstep\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mFalse\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdtype\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n    \u001b[0;31mSource:\u001b[0m   \n    \u001b[0;32mdef\u001b[0m \u001b[0mlinspace\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mstart\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstop\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnum\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m50\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mendpoint\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mTrue\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mretstep\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mFalse\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdtype\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0;34m\"\"\"\u001b[0m\n    \u001b[0;34m    Return evenly spaced numbers over a specified interval.\u001b[0m\n    \u001b[0;34m\u001b[0m\n    \u001b[0;34m    Returns `num` evenly spaced samples, calculated over the\u001b[0m\n    \u001b[0;34m    interval [`start`, `stop`].\u001b[0m\n    \u001b[0;34m\u001b[0m\n    \u001b[0;34m    The endpoint of the interval can optionally be excluded.\u001b[0m\n    \u001b[0;34m\u001b[0m\n    \u001b[0;34m    Parameters\u001b[0m\n    \u001b[0;34m    ----------\u001b[0m\n    \u001b[0;34m    start : scalar\u001b[0m\n    \u001b[0;34m        The starting value of the sequence.\u001b[0m\n    \u001b[0;34m    stop : scalar\u001b[0m\n    \u001b[0;34m        The end value of the sequence, unless `endpoint` is set to False.\u001b[0m\n    \u001b[0;34m        In that case, the sequence consists of all but the last of ``num + 1``\u001b[0m\n    \u001b[0;34m        evenly spaced samples, so that `stop` is excluded.  Note that the step\u001b[0m\n    \u001b[0;34m        size changes when `endpoint` is False.\u001b[0m\n    \u001b[0;34m    num : int, optional\u001b[0m\n    \u001b[0;34m        Number of samples to generate. Default is 50. Must be non-negative.\u001b[0m\n    \u001b[0;34m    endpoint : bool, optional\u001b[0m\n    \u001b[0;34m        If True, `stop` is the last sample. Otherwise, it is not included.\u001b[0m\n    \u001b[0;34m        Default is True.\u001b[0m\n    \u001b[0;34m    retstep : bool, optional\u001b[0m\n    \u001b[0;34m        If True, return (`samples`, `step`), where `step` is the spacing\u001b[0m\n    \u001b[0;34m        between samples.\u001b[0m\n    \u001b[0;34m    dtype : dtype, optional\u001b[0m\n    \u001b[0;34m        The type of the output array.  If `dtype` is not given, infer the data\u001b[0m\n    \u001b[0;34m        type from the other input arguments.\u001b[0m\n    \u001b[0;34m\u001b[0m\n    \u001b[0;34m        .. versionadded:: 1.9.0\u001b[0m\n    \u001b[0;34m\u001b[0m\n    \u001b[0;34m    Returns\u001b[0m\n    \u001b[0;34m    -------\u001b[0m\n    \u001b[0;34m    samples : ndarray\u001b[0m\n    \u001b[0;34m        There are `num` equally spaced samples in the closed interval\u001b[0m\n    \u001b[0;34m        ``[start, stop]`` or the half-open interval ``[start, stop)``\u001b[0m\n    \u001b[0;34m        (depending on whether `endpoint` is True or False).\u001b[0m\n    \u001b[0;34m    step : float, optional\u001b[0m\n    \u001b[0;34m        Only returned if `retstep` is True\u001b[0m\n    \u001b[0;34m\u001b[0m\n    \u001b[0;34m        Size of spacing between samples.\u001b[0m\n    \u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m\n    \u001b[0;34m    See Also\u001b[0m\n    \u001b[0;34m    --------\u001b[0m\n    \u001b[0;34m    arange : Similar to `linspace`, but uses a step size (instead of the\u001b[0m\n    \u001b[0;34m             number of samples).\u001b[0m\n    \u001b[0;34m    logspace : Samples uniformly distributed in log space.\u001b[0m\n    \u001b[0;34m\u001b[0m\n    \u001b[0;34m    Examples\u001b[0m\n    \u001b[0;34m    --------\u001b[0m\n    \u001b[0;34m    >>> np.linspace(2.0, 3.0, num=5)\u001b[0m\n    \u001b[0;34m    array([ 2.  ,  2.25,  2.5 ,  2.75,  3.  ])\u001b[0m\n    \u001b[0;34m    >>> np.linspace(2.0, 3.0, num=5, endpoint=False)\u001b[0m\n    \u001b[0;34m    array([ 2. ,  2.2,  2.4,  2.6,  2.8])\u001b[0m\n    \u001b[0;34m    >>> np.linspace(2.0, 3.0, num=5, retstep=True)\u001b[0m\n    \u001b[0;34m    (array([ 2.  ,  2.25,  2.5 ,  2.75,  3.  ]), 0.25)\u001b[0m\n    \u001b[0;34m\u001b[0m\n    \u001b[0;34m    Graphical illustration:\u001b[0m\n    \u001b[0;34m\u001b[0m\n    \u001b[0;34m    >>> import matplotlib.pyplot as plt\u001b[0m\n    \u001b[0;34m    >>> N = 8\u001b[0m\n    \u001b[0;34m    >>> y = np.zeros(N)\u001b[0m\n    \u001b[0;34m    >>> x1 = np.linspace(0, 10, N, endpoint=True)\u001b[0m\n    \u001b[0;34m    >>> x2 = np.linspace(0, 10, N, endpoint=False)\u001b[0m\n    \u001b[0;34m    >>> plt.plot(x1, y, 'o')\u001b[0m\n    \u001b[0;34m    [<matplotlib.lines.Line2D object at 0x...>]\u001b[0m\n    \u001b[0;34m    >>> plt.plot(x2, y + 0.5, 'o')\u001b[0m\n    \u001b[0;34m    [<matplotlib.lines.Line2D object at 0x...>]\u001b[0m\n    \u001b[0;34m    >>> plt.ylim([-0.5, 1])\u001b[0m\n    \u001b[0;34m    (-0.5, 1)\u001b[0m\n    \u001b[0;34m    >>> plt.show()\u001b[0m\n    \u001b[0;34m\u001b[0m\n    \u001b[0;34m    \"\"\"\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0;31m# 2016-02-25, 1.12\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0mnum\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0m_index_deprecate\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mnum\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0;32mif\u001b[0m \u001b[0mnum\u001b[0m \u001b[0;34m<\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m        \u001b[0;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Number of samples, %s, must be non-negative.\"\u001b[0m \u001b[0;34m%\u001b[0m \u001b[0mnum\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0mdiv\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mnum\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mendpoint\u001b[0m \u001b[0;32melse\u001b[0m \u001b[0mnum\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0;31m# Convert float/complex array scalars to float, gh-3504\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0;31m# and make sure one can use variables that have an __array_interface__, gh-6634\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0mstart\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0masanyarray\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mstart\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m*\u001b[0m \u001b[0;36m1.0\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0mstop\u001b[0m  \u001b[0;34m=\u001b[0m \u001b[0masanyarray\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mstop\u001b[0m\u001b[0;34m)\u001b[0m  \u001b[0;34m*\u001b[0m \u001b[0;36m1.0\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0mdt\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mresult_type\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mstart\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstop\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfloat\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mnum\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0;32mif\u001b[0m \u001b[0mdtype\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m        \u001b[0mdtype\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mdt\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0my\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0m_nx\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0marange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnum\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdtype\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mdt\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0mdelta\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mstop\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mstart\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0;32mif\u001b[0m \u001b[0mnum\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m        \u001b[0mstep\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mdelta\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0mdiv\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m        \u001b[0;32mif\u001b[0m \u001b[0mstep\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m            \u001b[0;31m# Special handling for denormal numbers, gh-5437\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m            \u001b[0my\u001b[0m \u001b[0;34m/=\u001b[0m \u001b[0mdiv\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m            \u001b[0my\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0my\u001b[0m \u001b[0;34m*\u001b[0m \u001b[0mdelta\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m        \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m            \u001b[0;31m# One might be tempted to use faster, in-place multiplication here,\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m            \u001b[0;31m# but this prevents step from overriding what class is produced,\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m            \u001b[0;31m# and thus prevents, e.g., use of Quantities; see gh-7142.\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m            \u001b[0my\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0my\u001b[0m \u001b[0;34m*\u001b[0m \u001b[0mstep\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m        \u001b[0;31m# 0 and 1 item long sequences have an undefined step\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m        \u001b[0mstep\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mNaN\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m        \u001b[0;31m# Multiply with delta to allow possible override of output class.\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m        \u001b[0my\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0my\u001b[0m \u001b[0;34m*\u001b[0m \u001b[0mdelta\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0my\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0mstart\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0;32mif\u001b[0m \u001b[0mendpoint\u001b[0m \u001b[0;32mand\u001b[0m \u001b[0mnum\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m        \u001b[0my\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mstop\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0;32mif\u001b[0m \u001b[0mretstep\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m        \u001b[0;32mreturn\u001b[0m \u001b[0my\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mastype\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdtype\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcopy\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mFalse\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstep\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m        \u001b[0;32mreturn\u001b[0m \u001b[0my\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mastype\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdtype\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcopy\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mFalse\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n    \u001b[0;31mFile:\u001b[0m      ~/miniconda3/envs/insightpy/lib/python3.6/site-packages/numpy/core/function_base.py\n    \u001b[0;31mType:\u001b[0m      function\n\n\n\n## Inspect _everything_\n\n\n```python\ndef silly_absolute_value_function(xval):\n    \"\"\"Takes a value and returns the value.\"\"\"\n    xval_sq = xval ** 2.0\n    1 + 4\n    xval_abs = np.sqrt(xval_sq)\n    return xval_abs\n```\n\n\n```python\nsilly_absolute_value_function(2)\n```\n\n\n\n\n    2.0\n\n\n\n\n```python\nsilly_absolute_value_function?\n```\n\n\n    \u001b[0;31mSignature:\u001b[0m \u001b[0msilly_absolute_value_function\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mxval\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n    \u001b[0;31mDocstring:\u001b[0m Takes a value and returns the value.\n    \u001b[0;31mFile:\u001b[0m      ~/github/jupyter-tips-and-tricks/deliver/<ipython-input-17-5aaf162ec65f>\n    \u001b[0;31mType:\u001b[0m      function\n\n\n\n\n```python\nsilly_absolute_value_function??\n```\n\n\n    \u001b[0;31mSignature:\u001b[0m \u001b[0msilly_absolute_value_function\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mxval\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n    \u001b[0;31mSource:\u001b[0m   \n    \u001b[0;32mdef\u001b[0m \u001b[0msilly_absolute_value_function\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mxval\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0;34m\"\"\"Takes a value and returns the value.\"\"\"\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0mxval_sq\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mxval\u001b[0m \u001b[0;34m**\u001b[0m \u001b[0;36m2.0\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0;36m1\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;36m4\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0mxval_abs\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msqrt\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mxval_sq\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0;32mreturn\u001b[0m \u001b[0mxval_abs\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n    \u001b[0;31mFile:\u001b[0m      ~/github/jupyter-tips-and-tricks/deliver/<ipython-input-17-5aaf162ec65f>\n    \u001b[0;31mType:\u001b[0m      function\n\n\n\n\n```python\n\n```\n\n# Keyboard shortcuts\n\nFor help, `ESC` + `h`\n\nh doesn't work in Lab\nl / shift L for line numbers\n\n\n```python\n\n```\n\n\n```python\n# in select mode, shift j/k (to select multiple cells at once)\n# split cell with ctrl shift -\n```\n\n\n```python\nfirst = 1\n```\n\n\n```python\nsecond = 2\n```\n\n\n```python\nthird = 3\n```\n\n\n```python\nfirst = 1\n```\n\n\n```python\nsecond = 2\n```\n\n\n```python\nthird = 3\n```\n\n\n```python\n# a new cell above\n# b new cell below\n```\n\n## Headings and LaTeX\n\nWith text and $\\LaTeX$ support.\n\n$$\\begin{align}\n        B'&=-\\nabla \\times E,\\\\\n        E'&=\\nabla \\times B - 4\\pi j\n\\end{align}$$\n\n\n```latex\n%%latex\n\nIf you want to get crazier...\n\n\\begin{equation}\n\\oint_S {E_n dA = \\frac{1}{{\\varepsilon _0 }}} Q_\\textrm{inside}\n\\end{equation}\n```\n\n\n\nIf you want to get crazier...\n\n\\begin{equation}\n\\oint_S {E_n dA = \\frac{1}{{\\varepsilon _0 }}} Q_\\textrm{inside}\n\\end{equation}\n\n\n### More markdown \n\n\n```python\n# Indent\n# Cmd + [ \n# Cmd + ]\n\n# Comment\n# Cmd + /\n```\n\nYou can also get `monospaced` fonts by indenting 4 spaces:\n\n    mkdir toc\n    cd toc\n\nWrap with triple-backticks and language:\n\n```bash\nmkdir toc\ncd toc\nwget https://repo.continuum.io/miniconda/Miniconda3-latest-MacOSX-x86_64.sh\n```\n\n```SQL\nSELECT *\nFROM tablename\n```\n\n\n```python\n# note difference w/ lab\n```\n\n```sql\n\nSELECT first_name,\n       last_name,\n       year_of_birth\nFROM presidents\nWHERE year_of_birth > 1800;\n\n```\n\n\n```bash\n%%bash\npwd \nfor i in *.ipynb\ndo\n    echo ${i} | awk -F . '{print $1}'\ndone\n\necho\necho \"break\"\necho\n\nfor i in *.ipynb\ndo\n    echo $i | awk -F - '{print $2}'\ndone\n```\n\n    /Users/jonathan/github/jupyter-tips-and-tricks/deliver\n    00-Overview\n    01-Tips-and-tricks\n    02-Visualization-and-code-organization\n    03-Pandas-and-Plotting\n    04-SQL-Example\n    05-interactive-splines\n    06-R-stuff\n    07-Some_basics\n    08-More_basics\n    09-Extras\n    Data_Cleaning\n    Introduction-to-Jupyter-Notebook-Functionality\n    \n    break\n    \n    Overview.ipynb\n    Tips\n    Visualization\n    Pandas\n    SQL\n    interactive\n    R\n    Some_basics.ipynb\n    More_basics.ipynb\n    Extras.ipynb\n    \n    to\n\n\n## Other cell-magics\n\n\n```python\n%%writefile ../scripts/temp.py\nfrom __future__ import absolute_import, division, print_function\n\nI promise that I'm not cheating!\n```\n\n    Overwriting ../scripts/temp.py\n\n\n\n```python\n!cat ../scripts/temp.py\n```\n\n    from __future__ import absolute_import, division, print_function\r\n    \r\n    I promise that I'm not cheating!\n\n## Autoreload is cool -- don't have time to give it the attention that it deserves.\n\nhttps://gist.github.com/jbwhit/38c1035c48cdb1714fc8d47fa163bfae\n\n\n```python\n%load_ext autoreload\n%autoreload 2\n```\n\n\n```python\n\n```\n\n\n```python\nexample_dict = {}\n```\n\n\n```python\n# Indent/dedent/comment\nfor _ in range(5):\n    example_dict[\"one\"] = 1\n    example_dict[\"two\"] = 2\n    example_dict[\"three\"] = 3\n    example_dict[\"four\"] = 4\n```\n\n## Multicursor magic\n\nHold down option, click and drag.\n\n\n```python\nexample_dict[\"one_better_name\"] = 1\nexample_dict[\"two_better_name\"] = 2\nexample_dict[\"three_better_name\"] = 3\nexample_dict[\"four_better_name\"] = 4\n```\n\nFind and replace -- regex notebook (or cell) wide. \n\n# R\n\n - [pyRserve](https://pypi.python.org/pypi/pyRserve)\n - [rpy2](http://rpy.sourceforge.net/)\n\n\n```python\nimport numpy as np\n```\n\n\n```python\n!conda install -c r rpy2 -y\n```\n\n    Fetching package metadata .............\n    Solving package specifications: .\n    \n    Package plan for installation in environment /Users/jonathan/miniconda3/envs/insightpy:\n    \n    The following NEW packages will be INSTALLED:\n    \n        cairo:          1.14.6-4              conda-forge\n        curl:           7.54.1-0              conda-forge\n        fontconfig:     2.12.1-4              conda-forge\n        gettext:        0.19.8.1-0            conda-forge\n        glib:           2.51.4-0              conda-forge\n        graphite2:      1.3.9-0               conda-forge\n        gsl:            2.2.1-blas_openblas_2 conda-forge [blas_openblas]\n        harfbuzz:       1.4.3-0               conda-forge\n        krb5:           1.14.2-0              conda-forge\n        libgcc:         4.8.5-1                          \n        libiconv:       1.14-4                conda-forge\n        libssh2:        1.8.0-1               conda-forge\n        libxml2:        2.9.4-4               conda-forge\n        pango:          1.40.4-0              conda-forge\n        pcre:           8.39-0                conda-forge\n        pixman:         0.34.0-0              conda-forge\n        r-base:         3.4.1-0               conda-forge\n        rpy2:           2.8.6-py36r3.4.1_2    r          \n        singledispatch: 3.4.0.3-py36_0        conda-forge\n    \n    The following packages will be DOWNGRADED:\n    \n        zlib:           1.2.11-0              conda-forge --> 1.2.8-3 conda-forge\n    \n    gettext-0.19.8 100% |################################| Time: 0:00:01   2.82 MB/s\n    graphite2-1.3. 100% |################################| Time: 0:00:00  24.81 MB/s\n    krb5-1.14.2-0. 100% |################################| Time: 0:00:00   1.92 MB/s\n    libgcc-4.8.5-1 100% |################################| Time: 0:00:00   6.88 MB/s\n    libiconv-1.14- 100% |################################| Time: 0:00:00   3.54 MB/s\n    libssh2-1.8.0- 100% |################################| Time: 0:00:00 556.93 kB/s\n    pcre-8.39-0.ta 100% |################################| Time: 0:00:00   1.20 MB/s\n    pixman-0.34.0- 100% |################################| Time: 0:00:00   1.59 MB/s\n    zlib-1.2.8-3.t 100% |################################| Time: 0:00:00  12.25 MB/s\n    glib-2.51.4-0. 100% |################################| Time: 0:00:03   1.36 MB/s\n    libxml2-2.9.4- 100% |################################| Time: 0:00:02 828.35 kB/s\n    curl-7.54.1-0. 100% |################################| Time: 0:00:00 833.21 kB/s\n    fontconfig-2.1 100% |################################| Time: 0:00:00   1.13 MB/s\n    gsl-2.2.1-blas 100% |################################| Time: 0:00:02 873.71 kB/s\n    cairo-1.14.6-4 100% |################################| Time: 0:00:01 829.58 kB/s\n    singledispatch 100% |################################| Time: 0:00:00 187.29 kB/s\n    harfbuzz-1.4.3 100% |################################| Time: 0:00:01 694.29 kB/s\n    pango-1.40.4-0 100% |################################| Time: 0:00:00 671.23 kB/s\n    r-base-3.4.1-0 100% |################################| Time: 0:00:08   2.75 MB/s\n    rpy2-2.8.6-py3 100% |################################| Time: 0:00:00   1.69 MB/s\n\n\n\n```python\nimport rpy2\n```\n\n\n```python\n%load_ext rpy2.ipython\n```\n\n\n```python\nX = np.array([0,1,2,3,4])\nY = np.array([3,5,4,6,7])\n```\n\n\n```python\n%%R?\n```\n\n    Object `%%R` not found.\n\n\n\n```r\n%%R -i X,Y -o XYcoef\nXYlm = lm(Y~X)\nXYcoef = coef(XYlm)\nprint(summary(XYlm))\npar(mfrow=c(2,2))\nplot(XYlm)\n```\n\n\n```python\ntype(XYcoef)\n```\n\n\n\n\n    numpy.ndarray\n\n\n\n\n```python\nXYcoef**2\n```\n\n\n\n\n    array([ 10.24,   0.81])\n\n\n\n\n```python\nthing()\n```\n\n\n\n\n    12\n\n\n", "meta": {"hexsha": "bd1e94f3864a121713073225caeb4851c213f0f9", "size": 140906, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/11-older-stuff.ipynb", "max_stars_repo_name": "ddeloss/jupyter-tips-and-tricks", "max_stars_repo_head_hexsha": "e47d5e5d07d2b9c9ba0b0f8101e8416ae7dd7cbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 260, "max_stars_repo_stars_event_min_datetime": "2015-09-11T15:57:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T23:42:13.000Z", "max_issues_repo_path": "notebooks/11-older-stuff.ipynb", "max_issues_repo_name": "ddeloss/jupyter-tips-and-tricks", "max_issues_repo_head_hexsha": "e47d5e5d07d2b9c9ba0b0f8101e8416ae7dd7cbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/11-older-stuff.ipynb", "max_forks_repo_name": "ddeloss/jupyter-tips-and-tricks", "max_forks_repo_head_hexsha": "e47d5e5d07d2b9c9ba0b0f8101e8416ae7dd7cbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 144, "max_forks_repo_forks_event_min_datetime": "2015-09-10T15:13:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T01:43:24.000Z", "avg_line_length": 71.453346856, "max_line_length": 65937, "alphanum_fraction": 0.7329709168, "converted": true, "num_tokens": 11440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1919327864472368, "lm_q2_score": 0.08389039156396119, "lm_q1q2_score": 0.016101316609020838}}
{"text": "<a href=\"https://colab.research.google.com/github/ChrizZhuang/marginalized_graph_kernel_protein/blob/main/Docking_0620_2.ipynb\" target=\"_parent\"></a>\n\n## Set up the environment\n\n\n```\n!nvidia-smi\n```\n\n    Sun Jun 20 03:32:38 2021       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 465.27       Driver Version: 460.32.03    CUDA Version: 11.2     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |                               |                      |               MIG M. |\n    |===============================+======================+======================|\n    |   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   42C    P8     9W /  70W |      0MiB / 15109MiB |      0%      Default |\n    |                               |                      |                  N/A |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                                  |\n    |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n    |        ID   ID                                                   Usage      |\n    |=============================================================================|\n    |  No running processes found                                                 |\n    +-----------------------------------------------------------------------------+\n\n\n\n```\n#!pip install pymatgen==2020.12.31\n!pip install pymatgen==2019.11.11\n!pip install --pre graphdot\n!pip install gdown\n```\n\n    Requirement already satisfied: pymatgen==2019.11.11 in /usr/local/lib/python3.7/dist-packages (2019.11.11)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.23.0)\n    Requirement already satisfied: pydispatcher>=2.0.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.0.5)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (0.8.9)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.1.5)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (3.3.0)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (3.2.2)\n    Requirement already satisfied: scipy>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.4.1)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2021.6.10)\n    Requirement already satisfied: numpy>=1.14.3 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.19.5)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (0.17.9)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (2.5.1)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.7.1)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11) (1.16.1)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (2021.5.30)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11) (2.10)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen==2019.11.11) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen==2019.11.11) (2.8.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (1.3.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11) (2.4.7)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen==2019.11.11) (0.2.2)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.2->pymatgen==2019.11.11) (4.4.2)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->pymatgen==2019.11.11) (1.2.1)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas->pymatgen==2019.11.11) (1.15.0)\n    Requirement already satisfied: graphdot in /usr/local/lib/python3.7/dist-packages (0.8a17)\n    Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.19.5)\n    Requirement already satisfied: tqdm>=4.55 in /usr/local/lib/python3.7/dist-packages (from graphdot) (4.61.1)\n    Requirement already satisfied: networkx>=2.4 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2.5.1)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.7.1)\n    Requirement already satisfied: numba>=0.51.0 in /usr/local/lib/python3.7/dist-packages (from graphdot) (0.51.2)\n    Requirement already satisfied: pandas>=0.24 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.1.5)\n    Requirement already satisfied: pymatgen==2019.11.11 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2019.11.11)\n    Requirement already satisfied: ase>=3.17 in /usr/local/lib/python3.7/dist-packages (from graphdot) (3.21.1)\n    Requirement already satisfied: kahypar>=1.1.4 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.1.6)\n    Requirement already satisfied: mendeleev>=0.7 in /usr/local/lib/python3.7/dist-packages (from graphdot) (0.7.0)\n    Requirement already satisfied: pycuda>=2019 in /usr/local/lib/python3.7/dist-packages (from graphdot) (2021.1)\n    Requirement already satisfied: treelib>=1.6.1 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.6.1)\n    Requirement already satisfied: scipy>=1.3.0 in /usr/local/lib/python3.7/dist-packages (from graphdot) (1.4.1)\n    Requirement already satisfied: decorator<5,>=4.3 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.4->graphdot) (4.4.2)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->graphdot) (1.2.1)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from numba>=0.51.0->graphdot) (57.0.0)\n    Requirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba>=0.51.0->graphdot) (0.34.0)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->graphdot) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->graphdot) (2018.9)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2021.6.10)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (0.17.9)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (3.2.2)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (1.16.1)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (0.8.9)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2.23.0)\n    Requirement already satisfied: pydispatcher>=2.0.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (2.0.5)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2019.11.11->graphdot) (3.3.0)\n    Requirement already satisfied: six<2.0.0,>=1.15.0 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (1.15.0)\n    Requirement already satisfied: Pygments<3.0.0,>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (2.9.0)\n    Requirement already satisfied: pyfiglet<0.9,>=0.8.post1 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (0.8.post1)\n    Requirement already satisfied: SQLAlchemy<2.0.0,>=1.3.23 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (1.4.18)\n    Requirement already satisfied: colorama<0.5.0,>=0.4.4 in /usr/local/lib/python3.7/dist-packages (from mendeleev>=0.7->graphdot) (0.4.4)\n    Requirement already satisfied: mako in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (1.1.4)\n    Requirement already satisfied: appdirs>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (1.4.4)\n    Requirement already satisfied: pytools>=2011.2 in /usr/local/lib/python3.7/dist-packages (from pycuda>=2019->graphdot) (2021.2.7)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from treelib>=1.6.1->graphdot) (0.16.0)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen==2019.11.11->graphdot) (0.2.2)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11->graphdot) (2.4.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11->graphdot) (1.3.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2019.11.11->graphdot) (0.10.0)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (2021.5.30)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (2.10)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2019.11.11->graphdot) (3.0.4)\n    Requirement already satisfied: greenlet!=0.4.17; python_version >= \"3\" in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (1.1.0)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (4.5.0)\n    Requirement already satisfied: MarkupSafe>=0.9.2 in /usr/local/lib/python3.7/dist-packages (from mako->pycuda>=2019->graphdot) (2.0.1)\n    Requirement already satisfied: typing-extensions>=3.6.4; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (3.7.4.3)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->SQLAlchemy<2.0.0,>=1.3.23->mendeleev>=0.7->graphdot) (3.4.1)\n    Requirement already satisfied: gdown in /usr/local/lib/python3.7/dist-packages (3.6.4)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from gdown) (2.23.0)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from gdown) (4.61.1)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from gdown) (1.15.0)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (2021.5.30)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (2.10)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->gdown) (1.24.3)\n\n\n\n```\n%matplotlib inline\nimport io\nimport sys\nsys.path.append('/usr/local/lib/python3.6/site-packages/')\nimport os\nimport urllib\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport graphdot\nfrom graphdot import Graph\nfrom graphdot.graph.adjacency import AtomicAdjacency\nfrom graphdot.graph.reorder import rcm\nfrom graphdot.kernel.marginalized import MarginalizedGraphKernel # https://graphdot.readthedocs.io/en/latest/apidoc/graphdot.kernel.marginalized.html\nfrom graphdot.kernel.marginalized.starting_probability import Uniform\nfrom graphdot.model.gaussian_process import (\n    GaussianProcessRegressor,\n    LowRankApproximateGPR\n)\nfrom graphdot.kernel.fix import Normalization\nimport graphdot.microkernel as uX\nimport ase.io\n\n# for getting all file names into a list under a directory \nfrom os import listdir\n# for getting file names that match certain pattern\nimport glob\nimport time\n```\n\n    /usr/local/lib/python3.7/dist-packages/graphdot/graph/__init__.py:24: UserWarning: Cannot import RDKit, `graph.from_rdkit()` will be unavailable.\n    \n      'Cannot import RDKit, `graph.from_rdkit()` will be unavailable.\\n'\n\n\n\n```\nfrom google.colab import drive\ndrive.mount('/content/gdrive', force_remount=True)\n```\n\n    Mounted at /content/gdrive\n\n\n\n```\n#cd gdrive/MyDrive/Google\\ Colab/Covid-Data\n%cd gdrive/MyDrive/Covid-Data/\n```\n\n    /content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data\n\n\n\n```\n!pwd\n```\n\n    /content/gdrive/.shortcut-targets-by-id/1wtzMcocuK8kPsz8K0ktjCZPkv567W6M2/Covid-Data\n\n\n## load the data\n\n\n```\nfiles  = ['uncharged_NSP15_6W01_A_3_H.Orderable_zinc_db_enaHLL.2col.csv.1.xz']\ndataset = pd.read_pickle(files[0]) # length of each csv file is 100000\n```\n\n\n```\ntarget = 'energy'\nN_train = 1000\nN_test = 2000\n\nnp.random.seed(0) # with the same seed, multiple runs can have the same selected index\ntrain_sel = np.random.choice(len(dataset), N_train, replace=False)\ntest_sel = np.random.choice(np.setxor1d(np.arange(len(dataset)), train_sel), N_test, replace=False)\ntrain = dataset.iloc[train_sel]\ntest = dataset.iloc[test_sel]\n```\n\n\n```\ntrain.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>energy</th>\n      <th>smiles</th>\n      <th>graphs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>3582</th>\n      <td>-2.874773</td>\n      <td>CN(Cc1nc(no1)c2cccc(c2)Br)C(=O)Nc3cccc(c3)OC</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>60498</th>\n      <td>-3.469760</td>\n      <td>CCOC(=O)c1ccc(c(c1)C)NC(=S)NCCOc2ccc(cc2)C</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>53227</th>\n      <td>-0.487984</td>\n      <td>Cc1ccc(cc1S(=O)(=O)Nc2ccccc2OC)NC(=O)c3nc4nc(c...</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>21333</th>\n      <td>-1.808283</td>\n      <td>COc1ccc(cc1OC)CCNC(=O)COc2ccc(cc2)[N@@](Cc3ccc...</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n    <tr>\n      <th>3885</th>\n      <td>-2.457642</td>\n      <td>Cc1cc(ccc1NCc2ccc(c(c2OC)C)OC)Br</td>\n      <td>Graph(nodes={'!i': [ 0, 1, 2, 3, 4, 5, 6, 7, 8...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### Baseline mode\n\n\n```\ngpr_base = GaussianProcessRegressor(\n    # kernel is the covariance function of the gaussian process (GP)\n    kernel=Normalization( # kernel equals to normalization -> normalizes a kernel using the cosine of angle formula, k_normalized(x,y) = k(x,y)/sqrt(k(x,x)*k(y,y))\n        # graphdot.kernel.fix.Normalization(kernel), set kernel as marginalized graph kernel, which is used to calculate the similarity between 2 graphs\n        # implement the random walk-based graph similarity kernel as Kashima, H., Tsuda, K., & Inokuchi, A. (2003). Marginalized kernels between labeled graphs. ICML\n        MarginalizedGraphKernel( \n            # node_kernel - A kernelet that computes the similarity between individual nodes\n            # uX - graphdot.microkernel - microkernels are positive-semidefinite functions between individual nodes and edges of graphs\n            node_kernel=uX.Additive( # addition of kernal matrices: sum of k_a(X_a, Y_a) cross for a in features\n                # uX.Constant - a kernel that returns a constant value, always mutlipled with other microkernels as an adjustable weight\n                #   c, the first input arg. as 0.5, (0.01, 10) the lower and upper bounds of c that is allowed to vary during hyperpara. optimizartion\n                # uX.KroneckerDelta - a kronecker delta returns 1 when two features are equal and return h (the first input arg here, which is 0.5 in this case) otherwise\n                #   (0.1, 0.9) the lower and upper bounds that h is allowed to vary during hyperpara. optimization\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 2nd element of graphdot.graph.Graph.nodes\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 3rd element of graphdot.graph.Graph.nodes\n                # uX.SquareExponential - Equ. 26 in the paper\n                # input arg. length_sacle is a float32, set as 1 in this case, which correspond to approx. 1 of the kernal value. \n                # This is used to determins how quicklys should the kernel decay to zero.\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0), # the 4th element of graphdot.graph.Graph.nodes\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 5th element of graphdot.graph.Graph.nodes\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0), # the 6th element of graphdot.graph.Graph.nodes\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 7th element of graphdot.graph.Graph.nodes\n                # uX.Convolution - a convolutional microkernel which averages evaluations of a base microkernel between pairs pf elememts of two variable-length feature sequences\n                # uX.KroneckerDelta as the base kernel\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9))) # the 8th element of graphdot.graph.Graph.nodes\n            ).normalized,\n            # edge_kernel - A kernelet that computes the similarity between individual edge\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 3rd element of graphdot.graph.Graph.nodes\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # the 4th element of graphdot.graph.Graph.nodes\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 5th element of graphdot.graph.Graph.nodes\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)), # the 6th element of graphdot.graph.Graph.nodes\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)) # the 7th element of graphdot.graph.Graph.nodes\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'), # the strating probability of the random walk on each node\n            q=0.05 # the probability for the random walk to stop during each step\n        )\n    ),\n    alpha=1e-4, # value added to the diagonal of the kernel matrix during fitting\n    optimizer=True, # default optimizer of L-BFGS-B based on scipy.optimize.minimize\n    normalize_y=True, # normalize the y values so taht the means and variance is 0 and 1, repsectively. Will be reversed when predicions are returned\n    regularization='+', # alpha (1e-4 in this case) is added to the diagonals of the kernal matrix\n)\n```\n\n\n```\ngpr_base.fit(train.graphs, train[target], repeat=1, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  2.8712e+06|   2.442e+07|  2.8785e+06|     -7290.9|  8.7027e+06|        28|      0.26|\n    |  1.9314e+06|  2.0704e+07|  1.9382e+06|     -6742.8|  8.0163e+06|        21|      0.24|\n    |  1.2904e+06|  1.5716e+07|  1.2967e+06|     -6251.9|  7.0807e+06|        19|      0.24|\n    |  1.0053e+06|    1.23e+07|  1.0113e+06|     -5971.1|  6.4092e+06|        19|      0.24|\n    |  8.2527e+05|  9.7212e+06|  8.3102e+05|     -5755.3|  5.8195e+06|        18|      0.26|\n    |  7.1177e+05|  8.0825e+06|  7.1736e+05|     -5588.7|  5.3683e+06|        18|      0.26|\n    |   6.491e+05|  7.1034e+06|  6.5459e+05|     -5488.7|  5.0418e+06|        17|      0.26|\n    |  6.2933e+05|  7.0338e+06|  6.3477e+05|     -5434.6|  4.9605e+06|        18|      0.24|\n    |  6.0995e+05|   6.643e+06|  6.1537e+05|       -5413|  4.8475e+06|        17|      0.26|\n    |  6.0543e+05|   6.541e+06|  6.1083e+05|     -5407.5|  4.8008e+06|        17|      0.24|\n    |  6.0282e+05|  6.4987e+06|  6.0823e+05|     -5402.8|  4.7787e+06|        17|      0.26|\n    |  6.0539e+05|  6.6515e+06|  6.1079e+05|     -5395.2|  4.8309e+06|        17|      0.23|\n    |  6.0082e+05|  6.5218e+06|  6.0622e+05|     -5394.8|  4.7891e+06|        17|      0.26|\n    |  5.9966e+05|  6.4945e+06|  6.0505e+05|     -5393.3|  4.7869e+06|        17|      0.24|\n    |  5.9789e+05|  6.4493e+06|  6.0328e+05|     -5390.6|  4.7725e+06|        17|      0.25|\n    |  5.9631e+05|  6.4134e+06|   6.017e+05|       -5389|  4.7604e+06|        17|      0.24|\n    |  5.9542e+05|  6.4022e+06|  6.0081e+05|     -5387.4|  4.7518e+06|        17|      0.24|\n    |  5.9529e+05|  6.4276e+06|  6.0067e+05|     -5386.2|  4.7508e+06|        17|      0.25|\n    |  5.9512e+05|  6.4197e+06|   6.005e+05|     -5386.6|  4.7449e+06|        17|      0.25|\n    |  5.9505e+05|  6.4169e+06|  6.0044e+05|     -5387.3|   4.741e+06|        17|      0.25|\n    |  5.9505e+05|  6.4166e+06|  6.0044e+05|     -5387.6|  4.7385e+06|        17|      0.23|\n    Optimization result:\n          fun: 595047.7176175278\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 6.41250071e+02,  2.87639317e+02,  6.60924244e+01, -1.26233962e+03,\n            1.36704669e+04,  3.60984806e+02,  0.00000000e+00, -6.10147407e+01,\n            1.77405394e+02,  1.92475967e+03,  1.01236129e-20,  1.37562821e+02,\n            1.25076750e+02, -1.40172516e+03,  1.76148081e+04, -5.33872996e+02,\n            1.95074428e+03,  1.76076704e+03,  3.01902646e+03, -7.59176880e+02,\n            3.09026926e+02,  2.55232585e+02,  0.00000000e+00, -7.26441523e+02,\n            2.93488326e+02])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 21\n          nit: 19\n       status: 0\n      success: True\n            x: array([-9.21034037, -3.93990556, -1.63179874,  1.44277989, -2.30258509,\n           -4.3780243 ,  0.        , -3.29916623, -1.99173454,  2.30055116,\n           -2.42034321, -3.65354201, -1.76764907,  1.69793063, -2.30258509,\n            0.70526171, -2.30258509,  1.23550411, -2.30258509, -2.43697879,\n           -1.76401895, -3.49472749, -0.22314355, -2.32417453, -1.83718902])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7f7072be4390>\n\n\n\n\n```\ngpr_base.kernel.hyperparameters.node_kernel.aromatic.lhs\n```\n\n\n\n\n    c : 0.019450051524810327\n\n\n\n\n```\ngpr_base.kernel.hyperparameters.edge_kernel\n```\n\n\n\n\n    aromatic : Multiply\n    \tlhs : Constant\n    \t\tc : 2.0243764247157046\n    \trhs : KroneckerDelta\n    \t\th : 0.10000000000000002\n    conjugated : Multiply\n    \tlhs : Constant\n    \t\tc : 3.4401122931051025\n    \trhs : KroneckerDelta\n    \t\th : 0.10000000000000002\n    order : Multiply\n    \tlhs : Constant\n    \t\tc : 0.08742458077769351\n    \trhs : KroneckerDelta\n    \t\th : 0.17135481208357772\n    ring_stereo : Multiply\n    \tlhs : Constant\n    \t\tc : 0.03035701976162682\n    \trhs : KroneckerDelta\n    \t\th : 0.8\n    stereo : Multiply\n    \tlhs : Constant\n    \t\tc : 0.09786419450583186\n    \trhs : KroneckerDelta\n    \t\th : 0.1592644871331458\n\n\n\n\n```\nmu = gpr_base.predict(train.graphs)\n```\n\n\n```\nplt.scatter(train[target], mu)\nplt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\nplt.xlim(-9, 3)\nplt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.1026528897885943\n    RMSE: 0.1559697478035153\n\n\n\n```\nmu_test = gpr_base.predict(test.graphs)\n```\n\n\n```\nplt.scatter(test[target], mu_test)\nplt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\nplt.xlim(-9, 3)\nplt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 1.3984523944497356\n    RMSE: 1.7902476214464011\n\n\n### Model 2\n\n\n```\ngpr2 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-5, #different from gpr in alpha where gpr_base alpha is 1e-4\n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr2.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n\n```\nmu = gpr2.predict(train.graphs)\nplt.scatter(train[target], mu)\nplt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\nplt.xlim(-9, 3)\nplt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.01420440124959926\n    RMSE: 0.021649804308151027\n\n\n\n```\nmu_test = gpr2.predict(test.graphs)\nplt.scatter(test[target], mu_test)\nplt.plot(np.linspace(-10, 4), np.linspace(-10, 4), c = 'r')\nplt.xlim(-10, 4)\nplt.ylim(-10, 4)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 1.517212238428167\n    RMSE: 1.943288841802438\n\n\n\n```\ngpr2.kernel.hyperparameters\n```\n\n### Model 3\n\n\n```\ngpr3 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-3, #different from gpr in alpha where gpr_base's alpha is 1e-4\n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr3.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  5.2754e+05|  1.7773e+06|  5.3362e+05|     -6084.7|  9.0549e+05|        25|      0.28|\n    |  4.4224e+05|  1.9515e+06|  4.4805e+05|     -5808.2|  8.7902e+05|        20|      0.27|\n    |  3.1405e+05|  1.8185e+06|  3.1934e+05|     -5298.7|  8.0593e+05|        18|      0.24|\n    |  2.8469e+05|  1.6176e+06|  2.8985e+05|       -5163|  7.8268e+05|        17|      0.26|\n    |  2.6118e+05|  1.4683e+06|  2.6622e+05|     -5042.3|  7.5644e+05|        17|      0.24|\n    |  2.5267e+05|  1.3881e+06|  2.5767e+05|     -4997.8|  7.4692e+05|        16|      0.26|\n    |   2.496e+05|  1.3914e+06|  2.5458e+05|       -4978|  7.4218e+05|        17|      0.25|\n    |  2.4851e+05|  1.3833e+06|  2.5349e+05|     -4971.9|  7.4096e+05|        17|      0.25|\n    |  2.4817e+05|  1.3928e+06|  2.5314e+05|     -4967.6|  7.3437e+05|        17|      0.24|\n    |  2.4724e+05|  1.3771e+06|  2.5221e+05|     -4964.6|  7.3871e+05|        17|      0.23|\n    |  2.4712e+05|  1.3738e+06|  2.5208e+05|     -4964.4|  7.3983e+05|        17|       0.3|\n    |  2.4696e+05|  1.3707e+06|  2.5192e+05|     -4963.8|  7.4051e+05|        17|      0.26|\n    |  2.4668e+05|  1.3678e+06|  2.5164e+05|     -4962.6|  7.4057e+05|        17|      0.26|\n    |  2.4641e+05|  1.3713e+06|  2.5137e+05|       -4960|   7.393e+05|        17|      0.24|\n    |  2.4626e+05|  1.3699e+06|  2.5122e+05|     -4959.3|  7.3801e+05|        17|      0.24|\n    |  2.4623e+05|  1.3693e+06|  2.5119e+05|     -4959.3|  7.3765e+05|        17|      0.24|\n    |  2.4624e+05|  1.3696e+06|   2.512e+05|     -4959.2|  7.3767e+05|        17|      0.25|\n    |  2.4624e+05|  1.3693e+06|   2.512e+05|     -4959.3|  7.3763e+05|        17|      0.24|\n    |  2.4623e+05|  1.3693e+06|  2.5119e+05|     -4959.3|  7.3758e+05|        17|      0.24|\n    |  2.4624e+05|  1.3693e+06|   2.512e+05|     -4959.3|   7.377e+05|        17|      0.26|\n    |  2.4624e+05|  1.3693e+06|   2.512e+05|     -4959.3|  7.3766e+05|        17|      0.28|\n    |  2.4624e+05|  1.3694e+06|   2.512e+05|     -4959.3|  7.3766e+05|        17|      0.26|\n    |  2.4623e+05|  1.3692e+06|  2.5119e+05|     -4959.3|  7.3767e+05|        17|      0.26|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  4.3132e+05|  2.1991e+06|  4.3709e+05|     -5766.2|  8.8044e+05|        20|      0.23|\n    |  3.8205e+05|  2.0562e+06|  3.8763e+05|     -5587.8|  8.5782e+05|        19|      0.23|\n    |  3.1542e+05|  1.9024e+06|  3.2073e+05|     -5313.3|  8.2092e+05|        19|      0.25|\n    |  2.8239e+05|  1.7354e+06|  2.8753e+05|     -5138.7|  7.6999e+05|        19|      0.24|\n    |  2.5844e+05|  1.4472e+06|  2.6347e+05|     -5032.7|  7.6497e+05|        17|      0.25|\n    |  2.5462e+05|   1.423e+06|  2.5963e+05|     -5010.1|  7.5654e+05|        17|      0.24|\n    |  2.4941e+05|  1.3953e+06|  2.5438e+05|     -4977.7|  7.4492e+05|        17|      0.23|\n    |  2.4782e+05|  1.3818e+06|  2.5279e+05|     -4968.9|  7.3616e+05|        17|      0.24|\n    |  2.4685e+05|  1.3767e+06|  2.5181e+05|     -4963.2|  7.3744e+05|        17|      0.23|\n    |  2.4666e+05|  1.3771e+06|  2.5162e+05|     -4960.4|  7.3963e+05|        17|      0.25|\n    |  2.4631e+05|  1.3714e+06|  2.5127e+05|     -4959.9|  7.3887e+05|        17|      0.23|\n    |  2.4624e+05|  1.3688e+06|   2.512e+05|     -4960.1|  7.3878e+05|        17|      0.23|\n    |  2.4618e+05|  1.3657e+06|  2.5114e+05|     -4960.1|  7.3874e+05|        17|      0.23|\n    |  2.4615e+05|  1.3645e+06|  2.5111e+05|     -4959.9|  7.3868e+05|        17|      0.25|\n    |  2.4608e+05|  1.3633e+06|  2.5103e+05|     -4959.5|  7.3863e+05|        17|      0.23|\n    |  2.4597e+05|  1.3625e+06|  2.5093e+05|     -4958.9|  7.3829e+05|        17|      0.23|\n    |  2.4593e+05|  1.3645e+06|  2.5089e+05|     -4958.5|   7.376e+05|        17|      0.25|\n    |  2.4589e+05|  1.3641e+06|  2.5085e+05|     -4958.3|  7.3836e+05|        17|      0.24|\n    |  2.4588e+05|  1.3646e+06|  2.5084e+05|     -4958.2|  7.3802e+05|        17|      0.23|\n    |  2.4585e+05|  1.3647e+06|  2.5081e+05|     -4958.2|  7.3765e+05|        17|      0.28|\n    |  2.4581e+05|  1.3635e+06|  2.5077e+05|     -4958.3|  7.3747e+05|        17|      0.25|\n    |  2.4579e+05|  1.3623e+06|  2.5074e+05|     -4958.3|  7.3782e+05|        17|      0.25|\n    |  2.4577e+05|   1.359e+06|  2.5073e+05|     -4958.8|  7.3883e+05|        17|      0.27|\n    |  2.4576e+05|  1.3601e+06|  2.5072e+05|     -4958.6|   7.387e+05|        17|      0.24|\n    |  2.4576e+05|  1.3607e+06|  2.5072e+05|     -4958.5|  7.3859e+05|        17|      0.23|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  5.7164e+05|  1.6233e+06|  5.7783e+05|     -6194.5|  8.9548e+05|        21|      0.25|\n    |  4.7796e+05|  1.8426e+06|  4.8386e+05|     -5904.1|  8.7295e+05|        20|      0.26|\n    |  3.3798e+05|  1.8581e+06|  3.4337e+05|     -5394.5|  8.2045e+05|        18|      0.24|\n    |  2.9137e+05|  1.7091e+06|  2.9656e+05|     -5188.7|  7.8714e+05|        19|      0.23|\n    |  2.6899e+05|  1.5524e+06|  2.7408e+05|     -5081.7|  7.6873e+05|        18|      0.25|\n    |  2.5569e+05|  1.4244e+06|  2.6071e+05|     -5015.7|  7.5632e+05|        17|      0.25|\n    |  2.5073e+05|  1.4143e+06|  2.5571e+05|     -4982.2|  7.4341e+05|        18|      0.25|\n    |  2.4974e+05|  1.4008e+06|  2.5472e+05|     -4979.3|  7.4547e+05|        17|      0.23|\n    |  2.4886e+05|  1.3879e+06|  2.5384e+05|     -4975.9|  7.4569e+05|        17|      0.24|\n    |  2.4798e+05|  1.3761e+06|  2.5295e+05|     -4971.5|  7.4426e+05|        17|      0.23|\n    |  2.4717e+05|   1.378e+06|  2.5214e+05|     -4965.5|  7.4085e+05|        17|      0.27|\n    |  2.4669e+05|  1.3741e+06|  2.5166e+05|     -4962.6|  7.3887e+05|        17|      0.24|\n    |   2.464e+05|  1.3657e+06|  2.5136e+05|     -4960.9|   7.412e+05|        17|      0.23|\n    |  2.4628e+05|  1.3668e+06|  2.5124e+05|     -4960.5|  7.3916e+05|        17|      0.25|\n    |  2.4624e+05|  1.3678e+06|   2.512e+05|     -4960.2|  7.3857e+05|        17|      0.23|\n    |  2.4619e+05|  1.3698e+06|  2.5115e+05|     -4959.9|  7.3793e+05|        17|      0.24|\n    |  2.4614e+05|  1.3703e+06|   2.511e+05|     -4959.6|  7.3771e+05|        17|      0.24|\n    |  2.4595e+05|  1.3683e+06|  2.5091e+05|     -4959.1|  7.3767e+05|        17|      0.24|\n    |  2.4602e+05|  1.3688e+06|  2.5098e+05|     -4958.9|  7.3875e+05|        17|      0.24|\n    |  2.4592e+05|  1.3683e+06|  2.5088e+05|     -4958.9|  7.3796e+05|        17|      0.23|\n    |  2.4589e+05|  1.3655e+06|  2.5085e+05|       -4959|  7.3856e+05|        17|      0.24|\n    |  2.4586e+05|  1.3623e+06|  2.5082e+05|     -4959.2|  7.3918e+05|        17|      0.24|\n    |  2.4584e+05|  1.3616e+06|   2.508e+05|     -4959.3|  7.3917e+05|        17|      0.24|\n    |  2.4583e+05|  1.3615e+06|  2.5079e+05|     -4959.3|  7.3903e+05|        17|      0.23|\n    |  2.4579e+05|  1.3614e+06|  2.5075e+05|     -4959.3|  7.3865e+05|        17|      0.24|\n    |  2.4578e+05|   1.362e+06|  2.5074e+05|     -4959.2|  7.3874e+05|        17|      0.24|\n    |  2.4576e+05|  1.3621e+06|  2.5072e+05|     -4959.1|   7.391e+05|        17|      0.23|\n    |  2.4576e+05|  1.3624e+06|  2.5072e+05|     -4959.1|  7.3901e+05|        17|      0.27|\n    Optimization result:\n          fun: 245757.64498811733\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 1.35950050e+02,  3.77357938e+01,  1.05734705e+01, -2.13075274e+01,\n            3.36341811e+03,  6.74591558e+01,  0.00000000e+00,  1.41114101e+00,\n            7.33894523e+00, -1.51578382e+02,  0.00000000e+00,  1.62796677e+01,\n            5.68562303e+00,  5.22025613e+01,  4.39601078e+03, -3.71667507e+01,\n            5.31204650e+02,  1.71062274e+01,  6.87112378e+02,  6.34393286e+01,\n            7.78485000e+01,  1.29002790e+01,  0.00000000e+00, -5.61367681e+01,\n            4.45773454e+01])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 25\n          nit: 24\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -1.33774258,  1.50058885, -2.30258509,\n           -4.60517019, -0.21165109, -4.60517019, -2.30258509,  2.2686602 ,\n           -4.07543091, -4.60517019, -2.30258509,  1.77034144, -2.30258509,\n            1.30229701, -2.30258509,  1.57009793, -2.30258509, -0.52372387,\n           -2.30258509, -4.60517019, -0.10536052, -1.31858519, -2.30258509])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7fb9a0f83150>\n\n\n\n\n```\nmu = gpr3.predict(train.graphs)\nplt.scatter(train[target], mu)\n#plt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\n#plt.xlim(-9, 3)\n#plt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.3711113759832458\n    RMSE: 0.5245520571276874\n\n\n\n```\nmu_test = gpr3.predict(test.graphs)\nplt.scatter(test[target], mu_test)\n#plt.plot(np.linspace(-10, 4), np.linspace(-10, 4), c = 'r')\n#plt.xlim(-10, 4)\n#plt.ylim(-10, 4)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 1.1498112446483284\n    RMSE: 1.4624191158480997\n\n\n### Model 4\n\n\n```\ngpr4 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-2, #different from gpr in alpha where gpr_base's alpha is 1e-4\n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr4.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |       66517|       88265|       70813|     -4296.2|       90905|        21|      0.28|\n    |       61455|  1.0409e+05|       65648|     -4193.5|       88757|        19|      0.25|\n    |       50869|  1.1321e+05|       54789|     -3920.3|       81573|        17|      0.23|\n    |       49285|  1.0995e+05|       53162|     -3876.6|       80232|        17|      0.28|\n    |       48321|  1.0553e+05|       52167|       -3845|       78704|        16|      0.24|\n    |       47912|  1.0664e+05|       51747|     -3834.9|       78334|        17|      0.25|\n    |       47815|  1.0611e+05|       51648|     -3832.7|       78473|        17|      0.25|\n    |       47734|  1.0602e+05|       51565|     -3830.1|       78399|        17|      0.24|\n    |       47721|   1.056e+05|       51549|     -3828.8|       78754|        17|      0.25|\n    |       47682|  1.0583e+05|       51510|     -3827.7|       78471|        17|      0.25|\n    |       47662|  1.0594e+05|       51489|     -3827.2|       78334|        17|      0.28|\n    |       47637|  1.0591e+05|       51463|     -3826.7|       78258|        17|      0.24|\n    |       47613|  1.0565e+05|       51439|     -3826.3|       78273|        17|      0.24|\n    |       47587|  1.0505e+05|       51413|     -3826.2|       78397|        17|      0.25|\n    |       47584|  1.0508e+05|       51410|       -3826|       78364|        17|      0.25|\n    |       47579|  1.0506e+05|       51404|     -3825.6|       78277|        17|      0.23|\n    |       47574|  1.0486e+05|       51399|     -3825.5|       78232|        17|      0.25|\n    |       47570|    1.04e+05|       51397|     -3826.4|       78274|        17|      0.28|\n    |       47576|  1.0386e+05|       51402|     -3825.9|       78262|        17|      0.24|\n    |       47569|  1.0395e+05|       51395|     -3826.1|       78271|        17|      0.24|\n    |       47567|  1.0417e+05|       51393|     -3826.1|       78324|        17|      0.28|\n    |       47566|  1.0407e+05|       51392|     -3826.3|       78362|        17|      0.23|\n    |       47566|  1.0398e+05|       51392|     -3826.4|       78386|        17|      0.24|\n    |       47566|  1.0405e+05|       51393|     -3826.3|       78366|        17|      0.24|\n    |       47566|  1.0406e+05|       51392|     -3826.3|       78363|        17|      0.25|\n    |       47566|  1.0407e+05|       51392|     -3826.3|       78362|        17|      0.24|\n    |       47566|  1.0407e+05|       51392|     -3826.3|       78361|        17|      0.25|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |       73087|       31386|       77530|       -4443|       95203|        16|      0.26|\n    |       69027|       48566|       73397|     -4370.2|       93280|        18|      0.25|\n    |       56295|  1.0441e+05|       60364|     -4068.9|       85503|        19|      0.26|\n    |       49629|  1.0815e+05|       53493|     -3864.5|       76173|        17|      0.26|\n    |       48176|  1.0901e+05|       52013|     -3837.5|       77267|        17|      0.26|\n    |       49949|   1.003e+05|       53850|       -3901|       82147|        18|      0.26|\n    |       47973|   1.074e+05|       51809|     -3836.1|       78349|        18|      0.26|\n    |       47868|  1.0647e+05|       51701|     -3833.7|       78588|        17|      0.25|\n    |       47825|  1.0603e+05|       51658|     -3832.9|       78699|        17|      0.25|\n    |       47758|  1.0569e+05|       51589|     -3831.2|       78709|        17|      0.25|\n    |       47712|  1.0601e+05|       51542|     -3829.4|       78587|        17|      0.26|\n    |       47692|  1.0615e+05|       51520|     -3828.2|       78413|        17|      0.24|\n    |       47690|  1.0616e+05|       51518|     -3828.1|       78396|        17|      0.23|\n    |       47681|  1.0614e+05|       51508|     -3827.4|       78346|        17|      0.24|\n    |       47681|  1.0645e+05|       51508|     -3827.2|       78253|        17|      0.24|\n    |       47674|  1.0629e+05|       51501|     -3827.1|       78299|        17|      0.25|\n    |       47654|  1.0622e+05|       51481|     -3826.3|       78288|        17|      0.25|\n    |       47645|  1.0603e+05|       51471|     -3826.2|       78342|        17|      0.26|\n    |       47644|  1.0605e+05|       51471|     -3826.4|       78352|        17|      0.26|\n    |       47644|  1.0604e+05|       51471|     -3826.3|       78347|        17|      0.24|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |       67828|  1.0852e+05|       72138|     -4309.5|       89137|        24|      0.25|\n    |       62412|  1.1469e+05|       66616|       -4204|       87873|        21|      0.25|\n    |       56410|   1.222e+05|       60478|     -4067.7|       85994|        20|      0.26|\n    |       51080|  1.1784e+05|       55004|     -3924.2|       81494|        18|      0.26|\n    |       49634|  1.1413e+05|       53522|     -3888.1|       80979|        18|      0.24|\n    |       48936|  1.0759e+05|       52800|     -3863.2|       79659|        17|      0.24|\n    |       48434|  1.0891e+05|       52284|     -3850.2|       79231|        17|      0.24|\n    |       48204|  1.0827e+05|       52049|     -3844.6|       79132|        18|      0.25|\n    |       47886|  1.0625e+05|       51723|     -3836.7|       78967|        17|      0.24|\n    |       48724|  1.0903e+05|       52577|     -3853.3|       76871|        19|      0.24|\n    |       47877|  1.0635e+05|       51713|     -3836.1|       78785|        18|      0.24|\n    |       48134|  1.0654e+05|       51976|     -3841.5|       78087|        18|      0.24|\n    |       47877|  1.0635e+05|       51712|       -3836|       78744|        17|      0.23|\n    |       47789|  1.0549e+05|       51623|     -3834.3|       78780|        17|      0.24|\n    |       47692|  1.0404e+05|       51525|     -3832.6|       78739|        17|      0.24|\n    |       47665|  1.0386e+05|       51497|     -3831.4|       78613|        17|      0.24|\n    |       47626|  1.0394e+05|       51456|     -3829.6|       78486|        17|      0.26|\n    |       47604|  1.0463e+05|       51432|     -3827.8|       78343|        17|      0.26|\n    |       47590|  1.0446e+05|       51417|     -3827.3|       78398|        17|      0.24|\n    |       47588|  1.0442e+05|       51415|     -3827.1|       78415|        17|      0.26|\n    |       47586|  1.0443e+05|       51413|     -3826.9|       78414|        17|      0.28|\n    |       47582|   1.045e+05|       51409|     -3826.5|       78406|        17|      0.24|\n    |       47579|  1.0481e+05|       51405|     -3825.9|       78253|        17|      0.23|\n    |       47575|  1.0471e+05|       51401|       -3826|       78318|        17|      0.24|\n    |       47573|  1.0459e+05|       51399|     -3826.2|       78354|        17|      0.24|\n    |       47571|  1.0449e+05|       51397|     -3826.3|       78369|        17|      0.24|\n    |       47568|  1.0432e+05|       51394|     -3826.5|       78382|        17|      0.23|\n    |       47566|  1.0421e+05|       51393|     -3826.5|       78376|        17|      0.24|\n    |       47565|   1.042e+05|       51391|     -3826.3|       78347|        17|      0.26|\n    |       47564|  1.0411e+05|       51390|     -3826.1|       78329|        17|      0.24|\n    |       47564|  1.0402e+05|       51390|     -3826.2|       78343|        17|      0.23|\n    |       47564|  1.0392e+05|       51390|     -3826.3|       78361|        17|      0.26|\n    |       47563|  1.0399e+05|       51389|     -3826.2|       78348|        17|      0.24|\n    Optimization result:\n          fun: 47563.16826613996\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 1.03860634e+01,  3.99556925e+00,  4.34356887e-01, -4.38765528e+00,\n            3.35685830e+02,  5.48613650e+00,  0.00000000e+00,  3.74597978e+00,\n            3.71923847e-01, -1.86677689e+01,  1.80494389e-04,  2.34556512e+00,\n            6.89757782e-01,  7.46525570e+00,  3.86435984e+02, -4.08724178e+00,\n            6.25487975e+01,  3.79069496e+00,  5.00876053e+01, -1.47395577e+00,\n            1.52830838e+01,  1.49931223e+00,  0.00000000e+00,  2.53256179e-01,\n            2.78310073e-01])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 33\n          nit: 29\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.23992363, -2.30258509,  1.70454451, -2.30258509,\n           -4.60517019, -0.39405819, -4.60517019, -1.7367717 ,  2.30258509,\n           -1.86521329, -4.33629426, -2.08030139,  1.84897251, -2.30258509,\n            2.14248562, -2.30258509,  1.93608271, -2.30258509,  0.72987226,\n           -2.30258509, -3.7783557 , -1.83514442, -3.16885023, -2.30258509])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7fb9896f5fd0>\n\n\n\n\n```\nmu = gpr4.predict(train.graphs)\nplt.scatter(train[target], mu)\n#plt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\n#plt.xlim(-9, 3)\n#plt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.6721642416785486\n    RMSE: 0.9001504628434619\n\n\n\n```\nmu_test = gpr4.predict(test.graphs)\nplt.scatter(test[target], mu_test)\n#plt.plot(np.linspace(-10, 4), np.linspace(-10, 4), c = 'r')\n#plt.xlim(-10, 4)\n#plt.ylim(-10, 4)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 0.996800387138675\n    RMSE: 1.2687098498475842\n\n\n### Model 5\n\n\n```\ngpr5 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-1, #different from gpr in alpha where gpr_base's alpha is 1e-4\n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr5.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |      5933.5|      3681.9|        8130|     -2196.5|        9095|        23|      0.27|\n    |      5700.6|      4368.7|      7866.6|       -2166|        8897|        21|      0.23|\n    |      5244.7|      4143.6|      7321.1|     -2076.4|      8114.4|        17|      0.24|\n    |      5161.9|      4261.1|      7222.8|       -2061|      8040.9|        17|      0.23|\n    |      5123.7|      4119.8|      7182.2|     -2058.5|      8116.4|        17|      0.25|\n    |      5100.9|      4055.4|      7155.4|     -2054.5|      8044.2|        17|      0.25|\n    |      5081.3|      3976.5|      7132.4|     -2051.1|      7995.7|        17|      0.24|\n    |      5078.6|      3971.4|      7128.4|     -2049.9|      7991.1|        17|      0.24|\n    |        5077|      3973.1|      7126.9|     -2049.9|      7990.8|        17|      0.24|\n    |      5075.4|      3971.5|      7125.2|     -2049.7|      7988.9|        17|      0.24|\n    |        5074|      3966.8|      7123.6|     -2049.5|      7985.4|        17|      0.26|\n    |      5071.8|      3952.7|        7121|     -2049.2|      7981.1|        17|      0.25|\n    |      5068.8|      3927.3|      7117.9|     -2049.1|      7982.1|        17|      0.26|\n    |      5067.9|      3915.3|      7117.1|     -2049.1|      7980.4|        17|      0.25|\n    |      5067.8|      3917.4|      7116.9|     -2049.1|      7979.1|        17|      0.25|\n    |      5067.8|      3919.2|      7116.8|       -2049|      7978.5|        17|      0.24|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |      6316.2|      4166.3|      8544.1|     -2227.9|        9356|        21|      0.23|\n    |      5897.8|      4552.2|      8086.8|       -2189|      9123.3|        20|      0.25|\n    |      5402.1|      4470.5|      7523.5|     -2121.3|      8676.4|        18|      0.23|\n    |      5263.9|      4484.2|        7355|     -2091.2|      8445.2|        18|      0.26|\n    |      5192.2|      4382.6|      7262.9|     -2070.7|      8189.6|        18|      0.25|\n    |      5121.6|      4136.4|      7180.3|     -2058.7|      8143.5|        17|      0.24|\n    |      5111.8|        4133|      7163.8|       -2052|        7978|        17|      0.23|\n    |      5100.7|      4164.8|      7150.7|     -2049.9|      7976.5|        17|      0.24|\n    |        5094|        4154|        7143|       -2049|      7983.6|        17|      0.23|\n    |      5089.6|        4131|      7138.2|     -2048.5|      7988.5|        17|      0.23|\n    |      5086.1|      4087.2|      7133.9|     -2047.8|      7974.4|        17|      0.23|\n    |      5082.2|      4085.6|        7130|     -2047.8|      7979.5|        17|      0.26|\n    |      5079.1|      4076.2|      7126.9|     -2047.9|      7977.4|        17|      0.23|\n    |      5078.3|      4068.3|      7126.3|       -2048|      7976.8|        17|      0.26|\n    |      5075.3|      3953.8|        7125|     -2049.7|      7975.3|        17|      0.23|\n    |      5073.1|      3984.2|      7122.2|     -2049.1|      7987.6|        17|      0.26|\n    |      5072.6|      3973.4|      7121.8|     -2049.2|      7988.8|        17|      0.28|\n    |      5071.1|      3934.7|      7120.4|     -2049.3|      7985.3|        17|      0.26|\n    |      5069.9|        3928|      7119.1|     -2049.2|      7984.2|        17|      0.25|\n    |      5068.5|      3913.3|      7117.8|     -2049.3|      7983.9|        17|      0.24|\n    |      5067.8|      3915.3|      7116.6|     -2048.8|      7969.8|        17|      0.25|\n    |      5067.5|      3903.7|      7117.2|     -2049.7|      7993.3|        17|      0.25|\n    |      5067.3|      3908.8|      7116.5|     -2049.2|      7983.6|        17|      0.24|\n    |      5067.1|        3910|      7116.1|       -2049|      7977.3|        17|      0.23|\n    |      5067.1|      3910.1|      7116.1|       -2049|      7977.7|        17|      0.26|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |      5834.4|      4699.1|      8022.2|     -2187.9|      9207.7|        21|      0.23|\n    |      5579.2|      4272.2|      7729.4|     -2150.2|      8902.1|        19|      0.24|\n    |        5265|      4187.4|      7346.4|     -2081.4|      8221.2|        18|      0.27|\n    |      5170.4|      3954.9|      7238.8|     -2068.4|      8110.4|        17|      0.24|\n    |      5137.6|      4046.1|      7198.2|     -2060.6|      8053.1|        17|      0.25|\n    |      5109.8|      4060.1|      7164.7|     -2054.9|      8036.6|        17|      0.23|\n    |      5092.8|      4026.6|      7144.8|       -2052|      8014.6|        17|      0.23|\n    |      5086.7|      3944.7|      7136.4|     -2049.7|      7929.4|        17|      0.23|\n    |      5078.8|      3926.5|      7130.6|     -2051.8|      8024.8|        17|      0.24|\n    |      5077.1|      3942.6|      7128.1|     -2050.9|      8009.4|        17|      0.23|\n    |      5075.3|      3953.9|      7125.3|     -2049.9|      7991.6|        17|      0.27|\n    |      5072.7|        3957|      7121.7|       -2049|      7973.5|        17|      0.25|\n    |      5069.8|      3945.2|      7118.4|     -2048.6|      7968.5|        17|      0.24|\n    |      5069.4|        3932|      7118.3|     -2048.9|      7981.7|        17|      0.25|\n    |      5068.9|      3930.6|      7117.9|       -2049|        7981|        17|      0.23|\n    |      5068.8|      3926.4|      7117.9|     -2049.1|      7983.4|        17|      0.24|\n    |      5068.4|      3917.5|      7117.9|     -2049.4|      7987.3|        17|      0.23|\n    |      5068.1|      3910.6|      7117.7|     -2049.6|        7989|        17|      0.25|\n    |      5067.8|      3913.7|      7117.1|     -2049.3|        7985|        17|      0.23|\n    |      5067.6|      3919.1|      7116.2|     -2048.6|      7972.4|        17|      0.23|\n    |      5067.4|      3918.6|      7116.2|     -2048.8|      7975.7|        17|      0.23|\n    |      5067.4|        3918|      7116.2|     -2048.9|        7976|        17|      0.23|\n    Optimization result:\n          fun: 5067.119508760024\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 3.90259274e-01,  1.87865706e-01,  2.15153320e-02,  5.95899075e-02,\n            1.81887249e+01,  3.14234542e-01,  0.00000000e+00,  2.98486676e-01,\n            9.99179948e-03, -1.21282065e+00,  0.00000000e+00,  1.07942514e-01,\n            2.29213419e-02,  2.45315195e-01,  1.44913639e+01,  2.38720249e-03,\n            6.78953722e-03, -1.08856133e-01,  3.25365990e+00,  4.00300271e-02,\n            3.61716207e+00,  3.49621047e-02,  0.00000000e+00,  3.14194196e-02,\n            3.39042590e-03])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 25\n          nit: 24\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -1.9276534 ,  1.65083009, -2.30258509,\n           -4.60517019,  0.08473439, -4.60517019, -0.94627051,  2.30258509,\n           -4.52691773, -4.60517019, -2.30258509,  1.42510738, -2.30258509,\n           -4.00849461, -2.30258509,  2.12160197, -2.30258509,  2.23247174,\n           -2.30258509, -4.60517019, -1.5016103 , -4.60517019, -0.71533121])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7fb9880bba10>\n\n\n\n\n```\nmu = gpr5.predict(train.graphs)\nplt.scatter(train[target], mu)\n#plt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\n#plt.xlim(-9, 3)\n#plt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.8642262237055949\n    RMSE: 1.1297768774199661\n\n\n\n```\nmu_test = gpr5.predict(test.graphs)\nplt.scatter(test[target], mu_test)\n#plt.plot(np.linspace(-10, 4), np.linspace(-10, 4), c = 'r')\n#plt.xlim(-10, 4)\n#plt.ylim(-10, 4)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 0.9967978325813834\n    RMSE: 1.2687065452737312\n\n\n### Model 6\n\n\n```\ngpr6 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.6, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # turn constant from 0.5 to 0.6\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-4, \n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr6.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n\n```\nmu = gpr6.predict(train.graphs)\nplt.scatter(train[target], mu)\n#plt.plot(np.linspace(-9, 3), np.linspace(-9, 3), c = 'r')\n#plt.xlim(-9, 3)\n#plt.ylim(-9, 3)\nplt.show()\n```\n\n\n```\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n    Training set\n    MAE: 0.10249072489800545\n    RMSE: 0.15577701746575612\n\n\n\n```\nmu_test = gpr6.predict(test.graphs)\nplt.scatter(test[target], mu_test)\n#plt.plot(np.linspace(-10, 4), np.linspace(-10, 4), c = 'r')\n#plt.xlim(-10, 4)\n#plt.ylim(-10, 4)\nplt.show()\n```\n\n\n```\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n    Test set\n    MAE: 1.3991366642890872\n    RMSE: 1.7909756847596061\n\n\n\n```\ngpr6.kernel.hyperparameters\n```\n\n### Model 7\n\n\n```\ngpr7 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.7, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # turn constant from 0.5 to 0.6\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-4, \n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr7.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n\n```\nmu = gpr7.predict(train.graphs)\nplt.scatter(train[target], mu)\nplt.show()\n\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n\n```\nmu_test = gpr7.predict(test.graphs)\nplt.scatter(test[target], mu_test)\nplt.show()\n\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n\n```\ngpr7.kernel.hyperparameters\n```\n\n### Model 8\n\n\n```\ngpr8 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(1, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # turn constant from 0.5 to 1\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-4, \n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr8.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  2.9792e+06|  2.4642e+07|  2.9865e+06|     -7343.8|  8.7118e+06|        23|      0.24|\n    |  2.0165e+06|  2.1362e+07|  2.0233e+06|     -6795.2|   8.062e+06|        21|      0.24|\n    |  1.2966e+06|  1.5902e+07|  1.3028e+06|     -6253.9|   7.068e+06|        20|      0.22|\n    |  1.0075e+06|   1.235e+07|  1.0135e+06|     -5971.1|  6.4058e+06|        19|      0.23|\n    |  8.2429e+05|  9.6934e+06|  8.3004e+05|     -5752.5|  5.8067e+06|        18|      0.23|\n    |  7.1088e+05|  8.0676e+06|  7.1646e+05|     -5586.2|  5.3556e+06|        18|      0.22|\n    |  6.4954e+05|  7.0881e+06|  6.5503e+05|     -5489.7|  5.0295e+06|        17|      0.23|\n    |  6.2388e+05|  6.9272e+06|  6.2931e+05|     -5427.9|   4.937e+06|        18|      0.24|\n    |  6.0965e+05|  6.6369e+06|  6.1507e+05|     -5412.2|  4.8418e+06|        17|      0.23|\n    |  6.0452e+05|   6.522e+06|  6.0993e+05|     -5406.2|  4.7899e+06|        17|      0.24|\n    |  6.0197e+05|  6.5091e+06|  6.0737e+05|     -5398.9|  4.7888e+06|        17|      0.22|\n    |  6.0036e+05|  6.5038e+06|  6.0575e+05|     -5394.2|  4.7893e+06|        17|      0.22|\n    |  5.9951e+05|   6.489e+06|   6.049e+05|       -5393|  4.7822e+06|        17|      0.23|\n    |  5.9656e+05|  6.4171e+06|  6.0195e+05|     -5389.2|  4.7641e+06|        17|      0.22|\n    |  5.9566e+05|  6.4098e+06|  6.0105e+05|       -5388|  4.7507e+06|        17|      0.23|\n    |  5.9511e+05|  6.4048e+06|   6.005e+05|     -5386.8|  4.7432e+06|        17|      0.25|\n    |  5.9481e+05|  6.4085e+06|   6.002e+05|     -5386.4|  4.7446e+06|        17|      0.23|\n    |  5.9412e+05|  6.4236e+06|   5.995e+05|     -5386.1|   4.749e+06|        17|      0.23|\n    |  5.9368e+05|  6.4259e+06|  5.9906e+05|     -5386.6|  4.7559e+06|        17|      0.23|\n    |  5.9331e+05|  6.4114e+06|  5.9869e+05|     -5386.5|  4.7604e+06|        17|      0.23|\n    |  5.9309e+05|  6.3915e+06|  5.9848e+05|     -5386.4|  4.7593e+06|        17|      0.23|\n    |   5.931e+05|  6.3863e+06|  5.9848e+05|     -5386.4|  4.7615e+06|        17|      0.23|\n    |   5.931e+05|  6.3906e+06|  5.9849e+05|     -5386.4|  4.7627e+06|        17|      0.23|\n    |  5.9306e+05|  6.3906e+06|  5.9845e+05|     -5386.4|  4.7601e+06|        17|      0.23|\n    |  5.9312e+05|  6.3917e+06|  5.9851e+05|     -5386.4|  4.7631e+06|        17|      0.23|\n    |  5.9305e+05|  6.3899e+06|  5.9844e+05|     -5386.4|  4.7595e+06|        17|      0.23|\n    |  5.9299e+05|  6.3818e+06|  5.9838e+05|     -5386.4|   4.764e+06|        17|      0.23|\n    |   5.931e+05|  6.3845e+06|  5.9849e+05|     -5386.4|   4.761e+06|        17|      0.23|\n    |  5.9308e+05|  6.3833e+06|  5.9847e+05|     -5386.4|   4.762e+06|        17|      0.23|\n    |  5.9309e+05|   6.384e+06|  5.9848e+05|     -5386.4|  4.7607e+06|        17|      0.24|\n    |  5.9312e+05|  6.3844e+06|   5.985e+05|     -5386.4|  4.7638e+06|        17|      0.24|\n    |  5.9305e+05|  6.3833e+06|  5.9843e+05|     -5386.4|  4.7632e+06|        17|      0.24|\n    |  5.9311e+05|  6.3844e+06|   5.985e+05|     -5386.4|   4.763e+06|        17|      0.24|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |   4.309e+06|  2.4382e+07|  4.3169e+06|     -7932.7|  9.2553e+06|        21|      0.23|\n    |  2.6362e+06|  2.3231e+07|  2.6434e+06|     -7166.7|  8.6035e+06|        20|      0.23|\n    |  1.4002e+06|  1.5158e+07|  1.4066e+06|     -6364.5|  7.1794e+06|        18|      0.22|\n    |  1.1499e+06|  1.2877e+07|   1.156e+06|     -6131.7|  6.7376e+06|        18|      0.24|\n    |  9.8645e+05|  1.1302e+07|  9.9241e+05|     -5956.4|  6.3329e+06|        18|      0.22|\n    |  8.2914e+05|  9.6694e+06|   8.349e+05|     -5759.6|  5.8519e+06|        18|      0.22|\n    |  7.2729e+05|  8.3779e+06|   7.329e+05|     -5612.5|  5.4668e+06|        18|      0.25|\n    |  6.5245e+05|  7.2326e+06|  6.5795e+05|     -5494.9|  5.0812e+06|        17|      0.24|\n    |  6.3709e+05|  7.1964e+06|  6.4253e+05|     -5446.6|  5.0356e+06|        18|      0.23|\n    |  6.1616e+05|   6.786e+06|  6.2159e+05|     -5425.7|  4.8997e+06|        17|      0.23|\n    |  6.1221e+05|  6.6896e+06|  6.1763e+05|     -5421.9|  4.8536e+06|        17|      0.24|\n    |  6.0702e+05|  6.5885e+06|  6.1243e+05|     -5414.2|  4.8025e+06|        17|      0.24|\n    |  6.0011e+05|  6.4941e+06|  6.0551e+05|     -5400.7|  4.7635e+06|        17|      0.22|\n    |  6.1826e+05|  6.8509e+06|  6.2368e+05|     -5414.4|  4.9133e+06|        18|      0.24|\n    |   5.982e+05|  6.4893e+06|  6.0359e+05|     -5394.7|  4.7798e+06|        17|      0.22|\n    |  5.9719e+05|  6.4696e+06|  6.0258e+05|       -5392|  4.7839e+06|        17|      0.23|\n    |  5.9674e+05|  6.4529e+06|  6.0213e+05|       -5391|  4.7862e+06|        17|      0.23|\n    |   5.958e+05|  6.4186e+06|  6.0119e+05|     -5389.5|  4.7882e+06|        17|      0.22|\n    |  5.9491e+05|  6.3949e+06|   6.003e+05|     -5388.1|  4.7813e+06|        17|      0.24|\n    |   5.945e+05|  6.3957e+06|  5.9989e+05|     -5388.1|  4.7701e+06|        17|      0.24|\n    |  5.9404e+05|  6.3999e+06|  5.9942e+05|     -5388.3|   4.762e+06|        17|      0.22|\n    |    5.94e+05|  6.4039e+06|  5.9939e+05|       -5388|   4.759e+06|        17|      0.23|\n    |  5.9386e+05|   6.416e+06|  5.9925e+05|       -5387|  4.7546e+06|        17|      0.24|\n    |  5.9366e+05|   6.418e+06|  5.9904e+05|     -5386.3|  4.7575e+06|        17|      0.24|\n    |  5.9327e+05|  6.4066e+06|  5.9865e+05|     -5385.8|  4.7593e+06|        17|      0.24|\n    |   5.931e+05|  6.3953e+06|  5.9848e+05|     -5386.1|  4.7563e+06|        17|      0.25|\n    |  5.9312e+05|  6.3845e+06|  5.9851e+05|     -5386.3|  4.7561e+06|        17|      0.24|\n    |  5.9314e+05|  6.3939e+06|  5.9852e+05|     -5386.1|   4.756e+06|        17|      0.23|\n    |  5.9312e+05|  6.3951e+06|   5.985e+05|     -5386.1|  4.7564e+06|        17|      0.23|\n    |  5.9331e+05|  6.3997e+06|  5.9869e+05|     -5386.1|  4.7546e+06|        17|      0.24|\n    |  5.9307e+05|  6.3946e+06|  5.9846e+05|     -5386.1|  4.7538e+06|        17|      0.23|\n    |   5.932e+05|  6.3977e+06|  5.9859e+05|     -5386.1|  4.7557e+06|        17|      0.23|\n    |  5.9311e+05|  6.3964e+06|   5.985e+05|     -5386.1|   4.753e+06|        17|      0.24|\n    |  5.9316e+05|  6.3968e+06|  5.9855e+05|     -5386.1|  4.7558e+06|        17|      0.23|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  2.3642e+06|   2.501e+07|  2.3713e+06|       -7035|  8.3857e+06|        22|      0.23|\n    |  1.5682e+06|  1.7112e+07|  1.5747e+06|       -6501|  7.4975e+06|        19|      0.23|\n    |  1.1254e+06|  1.2855e+07|  1.1315e+06|     -6110.8|   6.677e+06|        18|      0.23|\n    |   8.935e+05|  1.0626e+07|  8.9935e+05|     -5848.7|  6.0755e+06|        18|      0.23|\n    |  7.5389e+05|  9.1315e+06|  7.5954e+05|     -5651.6|   5.586e+06|        18|      0.23|\n    |  6.7538e+05|  7.6365e+06|  6.8092e+05|     -5536.1|  5.2056e+06|        17|      0.23|\n    |  6.3294e+05|  7.1193e+06|  6.3839e+05|     -5450.1|  5.0192e+06|        18|      0.24|\n    |  6.1522e+05|  6.7919e+06|  6.2065e+05|       -5427|  4.8927e+06|        17|      0.23|\n    |  6.0924e+05|  6.6947e+06|  6.1466e+05|     -5416.4|  4.8448e+06|        17|      0.23|\n    |  6.0118e+05|  6.5408e+06|  6.0658e+05|       -5400|  4.8099e+06|        17|      0.23|\n    |  6.0716e+05|   6.635e+06|  6.1257e+05|     -5407.4|  4.7901e+06|        17|      0.22|\n    |  5.9975e+05|  6.5325e+06|  6.0515e+05|     -5396.6|  4.7937e+06|        17|      0.23|\n    |  5.9739e+05|  6.4591e+06|  6.0278e+05|       -5392|  4.7831e+06|        17|      0.23|\n    |  5.9604e+05|  6.4368e+06|  6.0143e+05|     -5389.8|  4.7677e+06|        17|      0.23|\n    |  5.9509e+05|  6.4251e+06|  6.0048e+05|     -5387.9|  4.7487e+06|        17|      0.23|\n    |  5.9496e+05|  6.4322e+06|  6.0035e+05|       -5387|  4.7497e+06|        17|      0.22|\n    |   5.946e+05|  6.4308e+06|  5.9999e+05|     -5386.4|  4.7475e+06|        17|      0.23|\n    |  5.9469e+05|  6.4301e+06|  6.0008e+05|     -5386.4|   4.749e+06|        17|      0.23|\n    |  5.9465e+05|  6.4316e+06|  6.0003e+05|     -5386.4|  4.7503e+06|        17|      0.22|\n    |  5.9485e+05|   6.437e+06|  6.0023e+05|     -5386.4|   4.747e+06|        17|      0.23|\n    |  5.9463e+05|  6.4313e+06|  6.0002e+05|     -5386.4|  4.7496e+06|        17|      0.23|\n    |   5.947e+05|  6.4334e+06|  6.0009e+05|     -5386.4|   4.752e+06|        17|      0.23|\n    |  5.9469e+05|  6.4329e+06|  6.0008e+05|     -5386.4|    4.75e+06|        17|      0.23|\n    |  5.9467e+05|  6.4322e+06|  6.0005e+05|     -5386.4|  4.7498e+06|        17|      0.23|\n    Optimization result:\n          fun: 593114.6707814854\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 6.38026776e+02,  1.38782578e+02,  2.66323472e+01,  5.85716583e+02,\n            1.37186070e+04,  2.83861741e+02,  0.00000000e+00, -9.25955378e+01,\n            1.05547529e+02, -4.67581389e+02,  9.92854118e-20,  8.58522091e+01,\n            4.96435846e+01, -5.32965096e+02,  1.75859453e+04,  8.09606265e+01,\n            1.65723821e+03, -3.93953283e+02,  3.01124941e+03, -4.40932945e+01,\n            2.59823969e+02,  1.80457401e+02,  0.00000000e+00,  1.77125402e+02,\n            2.44995429e+02])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 33\n          nit: 23\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -1.86387197,  1.47468801, -2.30258509,\n           -4.60517019,  0.        , -3.49988681, -2.30258509,  2.30258509,\n           -2.40163276, -4.22043617, -2.03747843,  1.71483415, -2.30258509,\n            0.18487075, -2.30258509,  0.76191496, -2.30258509, -1.69254866,\n           -2.30258509, -4.23517368, -0.22314355, -1.65492569, -2.30258509])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7fd805d61c90>\n\n\n\n\n```\nmu = gpr8.predict(train.graphs)\nplt.scatter(train[target], mu)\nplt.show()\n\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n\n```\nmu_test = gpr8.predict(test.graphs)\nplt.scatter(test[target], mu_test)\nplt.show()\n\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n### Model 9\n\n\n```\ngpr9 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(2, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # turn constant from 0.5 to 1\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-4, \n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr9.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  3.1842e+06|  2.4974e+07|  3.1916e+06|     -7444.7|  8.7312e+06|        23|      0.26|\n    |  2.1752e+06|  2.2644e+07|  2.1821e+06|     -6894.5|  8.1462e+06|        21|      0.23|\n    |  1.2857e+06|  1.6274e+07|   1.292e+06|     -6243.6|  7.0034e+06|        20|      0.23|\n    |   1.004e+06|  1.2582e+07|    1.01e+06|     -5967.8|  6.3551e+06|        19|      0.25|\n    |  8.2416e+05|  9.8792e+06|  8.2991e+05|     -5754.1|  5.7767e+06|        18|      0.27|\n    |  7.1531e+05|  8.2743e+06|   7.209e+05|     -5594.7|  5.3493e+06|        18|      0.24|\n    |  6.5715e+05|  7.2687e+06|  6.6266e+05|     -5505.9|  5.0409e+06|        17|      0.24|\n    |  6.2418e+05|  6.9524e+06|  6.2962e+05|     -5436.7|  4.9381e+06|        18|      0.23|\n    |  6.1435e+05|  6.7657e+06|  6.1977e+05|     -5424.1|  4.8623e+06|        17|      0.24|\n    |  6.0457e+05|  6.6082e+06|  6.0998e+05|     -5406.7|    4.82e+06|        17|      0.24|\n    |  6.0409e+05|  6.4935e+06|  6.0949e+05|     -5401.4|  4.8533e+06|        17|      0.23|\n    |  6.0069e+05|  6.5041e+06|  6.0608e+05|     -5398.7|  4.8222e+06|        17|      0.24|\n    |  5.9986e+05|  6.4187e+06|  6.0526e+05|     -5395.8|   4.829e+06|        17|      0.23|\n    |  5.9771e+05|  6.4231e+06|   6.031e+05|     -5392.8|  4.8077e+06|        17|      0.26|\n    |  5.9675e+05|  6.4345e+06|  6.0214e+05|     -5391.7|  4.7932e+06|        17|      0.24|\n    |  5.9549e+05|  6.4231e+06|  6.0088e+05|     -5390.3|  4.7744e+06|        17|      0.24|\n    |  5.9438e+05|  6.4046e+06|  5.9976e+05|       -5388|  4.7547e+06|        17|      0.23|\n    |  5.9435e+05|  6.4109e+06|  5.9973e+05|     -5386.6|  4.7645e+06|        17|      0.24|\n    |  5.9419e+05|  6.4008e+06|  5.9958e+05|     -5386.9|    4.76e+06|        17|      0.24|\n    |  5.9416e+05|  6.3952e+06|  5.9954e+05|     -5387.1|  4.7616e+06|        17|      0.24|\n    |  5.9405e+05|  6.3847e+06|  5.9944e+05|     -5387.4|  4.7563e+06|        17|      0.25|\n    |  5.9384e+05|  6.3816e+06|  5.9923e+05|     -5387.2|  4.7571e+06|        17|      0.22|\n    |   5.937e+05|  6.3784e+06|  5.9908e+05|     -5387.2|  4.7548e+06|        17|      0.23|\n    |  5.9367e+05|  6.3925e+06|  5.9905e+05|     -5385.9|  4.7599e+06|        17|      0.23|\n    |  5.9358e+05|   6.394e+06|  5.9897e+05|     -5385.9|  4.7639e+06|        17|      0.23|\n    |  5.9338e+05|  6.3976e+06|  5.9877e+05|     -5386.2|  4.7562e+06|        17|      0.24|\n    |  5.9321e+05|  6.3888e+06|   5.986e+05|     -5386.4|   4.755e+06|        17|      0.23|\n    |  5.9333e+05|  6.3871e+06|  5.9871e+05|     -5386.5|  4.7591e+06|        17|      0.23|\n    |  5.9327e+05|  6.3903e+06|  5.9866e+05|     -5386.4|  4.7544e+06|        17|      0.24|\n    |  5.9316e+05|  6.3877e+06|  5.9855e+05|     -5386.4|   4.755e+06|        17|      0.24|\n    |  5.9334e+05|  6.3918e+06|  5.9872e+05|     -5386.4|  4.7592e+06|        17|      0.25|\n    |  5.9326e+05|    6.39e+06|  5.9864e+05|     -5386.4|  4.7561e+06|        17|      0.23|\n    |  5.9324e+05|  6.3898e+06|  5.9863e+05|     -5386.4|   4.758e+06|        17|      0.24|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  2.2799e+06|  3.0057e+07|  2.2869e+06|     -6934.8|  7.8008e+06|        24|      0.25|\n    |   1.767e+06|  2.5126e+07|  1.7736e+06|     -6594.3|  7.4479e+06|        23|      0.23|\n    |  1.0278e+06|  1.4821e+07|  1.0337e+06|     -5972.7|  6.4094e+06|        21|      0.23|\n    |  8.6501e+05|  1.1644e+07|  8.7081e+05|     -5794.8|  5.9663e+06|        20|      0.23|\n    |  7.1706e+05|  8.4268e+06|  7.2267e+05|     -5604.3|  5.3554e+06|        18|      0.23|\n    |  6.5162e+05|  7.4137e+06|  6.5712e+05|       -5493|   5.062e+06|        18|      0.23|\n    |  6.2958e+05|  6.9704e+06|  6.3504e+05|       -5458|  4.9042e+06|        17|      0.23|\n    |  6.1225e+05|  6.7455e+06|  6.1768e+05|     -5423.5|  4.8323e+06|        17|      0.23|\n    |  6.0632e+05|  6.6482e+06|  6.1173e+05|       -5411|  4.8372e+06|        17|      0.24|\n    |  6.0233e+05|  6.5526e+06|  6.0773e+05|     -5401.8|  4.8469e+06|        17|      0.23|\n    |  6.0022e+05|  6.4934e+06|  6.0562e+05|     -5397.6|  4.8374e+06|        17|      0.23|\n    |  5.9676e+05|  6.4223e+06|  6.0215e+05|     -5392.6|  4.7962e+06|        17|      0.23|\n    |  5.9504e+05|  6.4098e+06|  6.0043e+05|     -5390.5|  4.7672e+06|        17|      0.24|\n    |   5.947e+05|  6.4114e+06|  6.0009e+05|     -5389.3|  4.7581e+06|        17|      0.23|\n    |  5.9442e+05|  6.4108e+06|   5.998e+05|       -5388|  4.7564e+06|        17|      0.23|\n    |  5.9429e+05|  6.4096e+06|  5.9968e+05|     -5387.3|   4.761e+06|        17|      0.22|\n    |  5.9433e+05|  6.4087e+06|  5.9971e+05|     -5386.8|  4.7608e+06|        17|      0.23|\n    |  5.9434e+05|  6.4102e+06|  5.9972e+05|     -5387.2|  4.7592e+06|        17|      0.22|\n    |  5.9433e+05|  6.4107e+06|  5.9972e+05|     -5387.2|  4.7576e+06|        17|      0.23|\n    |  5.9428e+05|  6.4092e+06|  5.9967e+05|     -5387.2|    4.76e+06|        17|      0.23|\n    |  5.9426e+05|  6.4082e+06|  5.9964e+05|     -5387.2|  4.7593e+06|        17|      0.23|\n    |  5.9438e+05|  6.4119e+06|  5.9977e+05|     -5387.2|  4.7574e+06|        17|      0.23|\n    |  5.9431e+05|  6.4094e+06|   5.997e+05|     -5387.2|  4.7595e+06|        17|      0.23|\n    |  5.9437e+05|   6.411e+06|  5.9976e+05|     -5387.2|  4.7598e+06|        17|      0.25|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  5.6004e+06|  1.0925e+07|  5.6088e+06|     -8411.3|  9.6646e+06|        18|      0.23|\n    |  4.3616e+06|  1.7555e+07|  4.3696e+06|     -7948.7|  9.3139e+06|        19|      0.23|\n    |    1.55e+06|  1.8485e+07|  1.5564e+06|     -6436.8|  7.3811e+06|        21|      0.22|\n    |  1.1849e+06|  1.5675e+07|  1.1911e+06|     -6123.9|  6.7454e+06|        21|      0.22|\n    |  8.8035e+05|  1.0785e+07|  8.8616e+05|     -5807.1|  5.9897e+06|        19|      0.23|\n    |  7.5061e+05|  8.6012e+06|  7.5626e+05|     -5645.9|  5.5033e+06|        18|      0.23|\n    |  6.7138e+05|  7.5125e+06|   6.769e+05|     -5523.2|  5.1857e+06|        18|      0.23|\n    |  6.2543e+05|  6.8949e+06|  6.3087e+05|       -5443|  4.9251e+06|        17|      0.23|\n    |  6.1475e+05|  6.7354e+06|  6.2018e+05|     -5424.2|  4.8917e+06|        17|      0.23|\n    |  6.1085e+05|   6.669e+06|  6.1626e+05|       -5417|  4.8771e+06|        17|      0.23|\n    |  6.0117e+05|  6.4774e+06|  6.0657e+05|     -5400.5|  4.8228e+06|        17|      0.23|\n    |  5.9729e+05|  6.4244e+06|  6.0268e+05|     -5391.3|  4.8081e+06|        17|      0.23|\n    |   5.961e+05|  6.3908e+06|  6.0149e+05|     -5390.5|   4.788e+06|        17|      0.23|\n    |  5.9524e+05|  6.3716e+06|  6.0063e+05|     -5389.3|  4.7759e+06|        17|      0.23|\n    |  5.9457e+05|  6.3724e+06|  5.9996e+05|     -5388.4|  4.7729e+06|        17|      0.23|\n    |  5.9374e+05|  6.3917e+06|  5.9913e+05|     -5387.1|  4.7595e+06|        17|      0.24|\n    |  5.9348e+05|  6.3895e+06|  5.9886e+05|     -5386.8|  4.7578e+06|        17|      0.23|\n    |  5.9413e+05|  6.4288e+06|  5.9951e+05|     -5384.8|  4.7726e+06|        17|      0.25|\n    |  5.9355e+05|  6.3967e+06|  5.9894e+05|     -5386.3|  4.7583e+06|        17|      0.23|\n    |   5.935e+05|  6.3912e+06|  5.9888e+05|     -5386.8|  4.7567e+06|        17|      0.24|\n    |  5.9363e+05|  6.3931e+06|  5.9901e+05|     -5386.8|  4.7552e+06|        17|      0.23|\n    |  5.9352e+05|    6.39e+06|  5.9891e+05|     -5386.8|   4.759e+06|        17|      0.25|\n    |  5.9355e+05|  6.3912e+06|  5.9894e+05|     -5386.8|  4.7567e+06|        17|      0.23|\n    |  5.9355e+05|   6.391e+06|  5.9893e+05|     -5386.8|  4.7581e+06|        17|      0.23|\n    |   5.936e+05|  6.3923e+06|  5.9898e+05|     -5386.8|  4.7583e+06|        17|      0.25|\n    Optimization result:\n          fun: 593239.0731028724\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 6.38571528e+02,  2.53446370e+02,  4.04348138e+01, -8.86199826e+02,\n            1.36287493e+04,  2.83281629e+02,  0.00000000e+00, -8.03270149e+01,\n            1.29925146e+02, -6.68353601e+02,  3.81951546e-03,  1.11964525e+02,\n            7.10964508e+01,  1.00805620e+03,  1.76320909e+04, -2.85119588e+02,\n            1.68133082e+03,  4.70354709e+02,  3.02838241e+03, -2.14150548e+02,\n            2.70225253e+02,  2.26206868e+02,  0.00000000e+00, -1.99055415e+02,\n            2.32813791e+02])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 33\n          nit: 25\n       status: 0\n      success: True\n            x: array([-9.21034037, -3.95840051, -2.09284424,  1.4582562 , -2.30258509,\n           -4.60517019,  0.        , -3.49372658, -2.1095149 ,  2.30258509,\n           -1.88596738, -4.12293699, -1.77144806,  1.72893419, -2.30258509,\n           -0.42084637, -2.30258509,  0.20339185, -2.30258509, -2.32277083,\n           -2.30258509, -4.60517019, -0.22314355, -2.47885086, -2.30258509])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7fd803aefdd0>\n\n\n\n\n```\nmu = gpr9.predict(train.graphs)\nplt.scatter(train[target], mu)\nplt.show()\n\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n\n```\nmu_test = gpr9.predict(test.graphs)\nplt.scatter(test[target], mu_test)\nplt.show()\n\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n### Model 10\n\n\n```\ngpr10 = GaussianProcessRegressor(\n    kernel=Normalization(\n        MarginalizedGraphKernel(\n            node_kernel=uX.Additive(\n                aromatic=uX.Constant(0.1, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # turn constant from 0.5 to 0.1\n                atomic_number=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                charge=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                chiral=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                hcount=uX.Constant(0.5, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                hybridization=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                ring_list=uX.Constant(0.5, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n            ).normalized,\n            edge_kernel=uX.Additive(\n                aromatic=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                conjugated=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                order=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                ring_stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                stereo=uX.Constant(0.5, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n            ).normalized,\n            p=Uniform(1.0, p_bounds='fixed'),\n            q=0.05\n        )\n    ),\n    alpha=1e-4, \n    optimizer=True,\n    normalize_y=True,\n    regularization='+',\n)\n```\n\n\n```\ngpr10.fit(train.graphs, train[target], repeat=3, verbose=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  2.7983e+06|    2.43e+07|  2.8056e+06|     -7255.5|  8.7152e+06|        23|      0.24|\n    |   1.862e+06|  2.0153e+07|  1.8687e+06|     -6699.9|  7.9833e+06|        20|      0.24|\n    |  1.2811e+06|  1.5513e+07|  1.2873e+06|     -6247.6|  7.0832e+06|        20|      0.24|\n    |  1.0015e+06|  1.2225e+07|  1.0075e+06|     -5970.3|  6.4109e+06|        19|      0.24|\n    |  8.2607e+05|   9.751e+06|  8.3183e+05|     -5757.8|  5.8362e+06|        18|      0.24|\n    |  7.1314e+05|  8.1066e+06|  7.1873e+05|     -5592.2|   5.376e+06|        18|      0.23|\n    |  6.4927e+05|  7.1354e+06|  6.5476e+05|     -5488.9|  5.0514e+06|        17|      0.23|\n    |  6.3134e+05|  7.0681e+06|  6.3678e+05|     -5438.9|  4.9652e+06|        18|      0.23|\n    |  6.1006e+05|  6.6411e+06|  6.1548e+05|     -5414.6|  4.8456e+06|        17|      0.23|\n    |  6.0572e+05|   6.545e+06|  6.1113e+05|     -5408.6|  4.8049e+06|        17|      0.23|\n    |  6.0297e+05|  6.5038e+06|  6.0838e+05|     -5403.2|  4.7879e+06|        17|      0.24|\n    |  6.0504e+05|   6.654e+06|  6.1044e+05|     -5394.8|  4.8153e+06|        18|      0.23|\n    |   6.002e+05|  6.5188e+06|   6.056e+05|       -5394|  4.7876e+06|        17|      0.23|\n    |  6.0038e+05|  6.5403e+06|  6.0577e+05|     -5389.6|  4.8007e+06|        17|      0.23|\n    |   5.998e+05|  6.5228e+06|  6.0519e+05|     -5391.3|  4.7927e+06|        17|      0.23|\n    |  5.9818e+05|  6.4716e+06|  6.0357e+05|     -5390.5|  4.7747e+06|        17|      0.22|\n    |  5.9784e+05|  6.4565e+06|  6.0323e+05|     -5390.9|  4.7662e+06|        17|      0.22|\n    |    5.97e+05|  6.4279e+06|  6.0239e+05|     -5390.7|   4.759e+06|        17|      0.23|\n    |  5.9602e+05|  6.4208e+06|  6.0141e+05|     -5387.9|  4.7561e+06|        17|      0.24|\n    |  5.9532e+05|  6.4184e+06|  6.0071e+05|     -5386.5|  4.7421e+06|        17|      0.22|\n    |  5.9503e+05|  6.4111e+06|  6.0041e+05|     -5386.4|  4.7408e+06|        17|      0.24|\n    |  5.9491e+05|   6.408e+06|  6.0029e+05|     -5386.4|  4.7431e+06|        17|      0.23|\n    |  5.9463e+05|   6.401e+06|  6.0002e+05|     -5386.2|  4.7443e+06|        17|      0.22|\n    |  6.0593e+05|  6.5034e+06|  6.1134e+05|     -5408.5|  4.9074e+06|        17|      0.23|\n    |  5.9396e+05|  6.3846e+06|  5.9935e+05|     -5386.5|  4.7594e+06|        17|      0.24|\n    |  5.9382e+05|  6.3835e+06|  5.9921e+05|     -5387.7|  4.7774e+06|        17|      0.22|\n    |  5.9376e+05|   6.384e+06|  5.9915e+05|     -5386.8|  4.7694e+06|        17|      0.24|\n    |  5.9354e+05|  6.3993e+06|  5.9893e+05|     -5385.7|  4.7783e+06|        17|      0.24|\n    |   5.931e+05|  6.3874e+06|  5.9849e+05|       -5386|   4.769e+06|        17|      0.23|\n    |  5.9321e+05|  6.3905e+06|  5.9859e+05|     -5386.5|  4.7589e+06|        17|      0.23|\n    |  5.9325e+05|  6.3911e+06|  5.9864e+05|     -5386.1|  4.7673e+06|        17|      0.23|\n    |  5.9325e+05|  6.3915e+06|  5.9864e+05|     -5386.1|  4.7655e+06|        17|      0.24|\n    |  5.9323e+05|  6.3903e+06|  5.9861e+05|       -5386|  4.7667e+06|        17|      0.26|\n    |  5.9321e+05|    6.39e+06|   5.986e+05|       -5386|  4.7658e+06|        17|      0.23|\n    |  5.9322e+05|  6.3903e+06|   5.986e+05|       -5386|  4.7665e+06|        17|      0.23|\n    |  5.9323e+05|  6.3905e+06|  5.9862e+05|       -5386|  4.7647e+06|        17|      0.24|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |   3.335e+06|  2.0676e+07|  3.3425e+06|     -7511.6|  8.8641e+06|        20|      0.23|\n    |  2.1616e+06|  1.8613e+07|  2.1684e+06|     -6871.7|  8.1374e+06|        20|      0.27|\n    |  1.0552e+06|  1.1657e+07|  1.0612e+06|     -5984.8|  6.4878e+06|        19|      0.24|\n    |  8.3583e+05|  9.3921e+06|  8.4159e+05|     -5752.2|  5.8752e+06|        18|      0.23|\n    |  7.4374e+05|  8.1282e+06|  7.4937e+05|     -5635.8|  5.4636e+06|        17|      0.23|\n    |   6.817e+05|  7.3767e+06|  6.8724e+05|     -5541.2|  5.1875e+06|        17|      0.23|\n    |  6.3778e+05|  6.9335e+06|  6.4325e+05|     -5463.9|  5.0127e+06|        17|      0.23|\n    |   6.165e+05|  6.6822e+06|  6.2193e+05|     -5426.8|   4.878e+06|        17|      0.24|\n    |  6.1137e+05|  6.5342e+06|  6.1679e+05|     -5414.3|  4.8606e+06|        17|      0.25|\n    |  6.0039e+05|  6.4384e+06|  6.0579e+05|     -5398.2|  4.7915e+06|        17|      0.24|\n    |  5.9881e+05|  6.4292e+06|  6.0421e+05|       -5395|  4.7835e+06|        17|      0.24|\n    |  5.9769e+05|  6.4717e+06|  6.0308e+05|     -5388.4|  4.7946e+06|        17|      0.24|\n    |   5.968e+05|  6.4302e+06|  6.0219e+05|     -5389.3|  4.7826e+06|        17|      0.24|\n    |  5.9653e+05|  6.4185e+06|  6.0192e+05|     -5389.6|  4.7764e+06|        17|      0.23|\n    |  5.9628e+05|  6.4064e+06|  6.0167e+05|     -5389.7|  4.7681e+06|        17|      0.25|\n    |  5.9569e+05|   6.392e+06|  6.0108e+05|     -5389.3|  4.7644e+06|        17|      0.23|\n    |  5.9554e+05|  6.4306e+06|  6.0093e+05|     -5385.3|  4.7795e+06|        17|      0.25|\n    |  5.9461e+05|  6.4044e+06|  5.9999e+05|     -5385.7|  4.7627e+06|        17|      0.23|\n    |  5.9443e+05|  6.3917e+06|  5.9981e+05|     -5386.6|  4.7565e+06|        17|      0.23|\n    |  5.9439e+05|  6.3911e+06|  5.9977e+05|     -5386.6|  4.7529e+06|        17|      0.23|\n    |  5.9432e+05|  6.3888e+06|   5.997e+05|     -5386.6|  4.7545e+06|        17|      0.24|\n    |  5.9414e+05|  6.3821e+06|  5.9953e+05|     -5386.4|  4.7585e+06|        17|      0.23|\n    |  5.9408e+05|  6.3773e+06|  5.9946e+05|     -5386.4|  4.7613e+06|        17|      0.23|\n    |  5.9375e+05|  6.3821e+06|  5.9914e+05|     -5386.7|  4.7649e+06|        17|      0.23|\n    |  5.9345e+05|  6.3813e+06|  5.9883e+05|       -5387|  4.7631e+06|        17|      0.23|\n    |   5.934e+05|  6.3896e+06|  5.9879e+05|     -5386.8|   4.763e+06|        17|      0.23|\n    |  5.9344e+05|  6.3955e+06|  5.9882e+05|     -5386.7|  4.7616e+06|        17|      0.23|\n    |  5.9342e+05|  6.3913e+06|  5.9881e+05|     -5386.8|  4.7649e+06|        17|      0.25|\n    |  5.9326e+05|   6.387e+06|  5.9865e+05|     -5386.8|  4.7616e+06|        17|      0.23|\n    |  5.9337e+05|  6.3891e+06|  5.9876e+05|     -5386.8|  4.7671e+06|        17|      0.22|\n    |   5.933e+05|  6.3877e+06|  5.9869e+05|     -5386.8|  4.7628e+06|        17|      0.22|\n    |  5.9324e+05|  6.3942e+06|  5.9862e+05|     -5386.4|  4.7589e+06|        17|      0.24|\n    |  5.9328e+05|   6.388e+06|  5.9867e+05|     -5386.6|  4.7591e+06|        17|      0.25|\n    |  5.9325e+05|  6.3922e+06|  5.9864e+05|     -5386.4|  4.7598e+06|        17|      0.22|\n    |  5.9325e+05|  6.3937e+06|  5.9864e+05|     -5386.4|  4.7632e+06|        17|      0.24|\n    |  5.9335e+05|  6.3958e+06|  5.9874e+05|     -5386.4|  4.7595e+06|        17|      0.25|\n    |  5.9334e+05|  6.3953e+06|  5.9872e+05|     -5386.4|  4.7621e+06|        17|      0.26|\n    |  5.9338e+05|   6.397e+06|  5.9877e+05|     -5386.4|  4.7553e+06|        17|      0.25|\n    |  5.9335e+05|  6.3966e+06|  5.9874e+05|     -5386.4|  4.7606e+06|        17|      0.26|\n    |  5.9333e+05|   6.396e+06|  5.9871e+05|     -5386.4|  4.7579e+06|        17|      0.26|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  5.8553e+06|  6.1173e+06|  5.8637e+06|     -8489.1|   9.764e+06|        13|      0.24|\n    |  4.4775e+06|  1.0414e+07|  4.4854e+06|     -7964.5|  9.4041e+06|        14|      0.24|\n    |   1.499e+06|  1.2523e+07|  1.5054e+06|     -6394.8|  7.5362e+06|        17|      0.24|\n    |  1.0911e+06|  1.0407e+07|  1.0971e+06|     -6028.5|  6.7239e+06|        17|      0.26|\n    |  9.1382e+05|  9.0085e+06|  9.1966e+05|     -5833.1|  6.2209e+06|        17|      0.25|\n    |  7.8666e+05|  7.9393e+06|  7.9232e+05|     -5667.8|   5.793e+06|        17|      0.23|\n    |   7.137e+05|  7.2049e+06|  7.1927e+05|     -5561.2|  5.4904e+06|        17|      0.24|\n    |  6.7654e+05|  6.9513e+06|  6.8204e+05|     -5499.9|  5.3402e+06|        17|      0.24|\n    |  6.4054e+05|  6.5381e+06|  6.4599e+05|     -5455.9|  5.1118e+06|        17|      0.26|\n    |  6.5597e+05|  7.5432e+06|  6.6144e+05|       -5465|  4.9854e+06|        19|      0.26|\n    |  6.0894e+05|   6.557e+06|  6.1435e+05|     -5407.4|  4.9151e+06|        18|      0.24|\n    |  6.0177e+05|  6.5172e+06|  6.0717e+05|     -5402.3|  4.8031e+06|        17|      0.25|\n    |  6.0125e+05|  6.4801e+06|  6.0665e+05|       -5402|  4.8075e+06|        17|      0.26|\n    |  6.0082e+05|  6.4688e+06|  6.0622e+05|     -5400.4|  4.8117e+06|        17|      0.26|\n    |  6.0039e+05|  6.4622e+06|  6.0579e+05|     -5399.3|  4.8118e+06|        17|      0.24|\n    |   5.982e+05|  6.4268e+06|  6.0359e+05|     -5393.2|  4.8253e+06|        17|      0.26|\n    |  5.9754e+05|  6.4135e+06|  6.0294e+05|     -5392.8|  4.8149e+06|        17|      0.26|\n    |  5.9534e+05|  6.3715e+06|  6.0073e+05|     -5392.5|  4.7759e+06|        17|      0.25|\n    |  5.9496e+05|  6.3808e+06|  6.0036e+05|     -5391.6|  4.7699e+06|        17|      0.27|\n    |  5.9436e+05|  6.4056e+06|  5.9975e+05|       -5389|  4.7735e+06|        17|      0.25|\n    |  5.9392e+05|  6.4102e+06|  5.9931e+05|     -5387.2|  4.7705e+06|        17|      0.25|\n    |  5.9358e+05|  6.3991e+06|  5.9897e+05|       -5386|  4.7674e+06|        17|      0.24|\n    |   5.934e+05|  6.3882e+06|  5.9879e+05|     -5386.5|  4.7622e+06|        17|      0.24|\n    |  5.9342e+05|  6.3853e+06|   5.988e+05|     -5386.8|  4.7604e+06|        17|      0.25|\n    |  5.9348e+05|  6.3892e+06|  5.9887e+05|     -5386.5|  4.7637e+06|        17|      0.25|\n    |  5.9343e+05|  6.3882e+06|  5.9881e+05|     -5386.5|  4.7662e+06|        17|      0.26|\n    |  5.9353e+05|  6.3906e+06|  5.9892e+05|     -5386.5|   4.765e+06|        17|      0.26|\n    |   5.934e+05|  6.3875e+06|  5.9878e+05|     -5386.5|   4.763e+06|        17|      0.26|\n    |  5.9342e+05|   6.388e+06|  5.9881e+05|     -5386.5|  4.7621e+06|        17|      0.27|\n    |  5.9349e+05|  6.3898e+06|  5.9888e+05|     -5386.5|  4.7653e+06|        17|      0.25|\n    |  5.9347e+05|   6.389e+06|  5.9885e+05|     -5386.5|  4.7634e+06|        17|      0.26|\n    Optimization result:\n          fun: 593233.3042484035\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([  638.64736427,   141.96903073,    28.55629934,  1626.08930356,\n           13743.38807579,   280.18042823,     0.        ,   -99.97653253,\n             114.814054  , -2792.2638767 ,     0.        ,    91.58912464,\n              57.6192078 ,   776.34364075, 17553.00068355,   978.24342665,\n            1666.14615848, -1272.51341315,  2991.47521638,  -137.29971877,\n             252.38902263,   210.50993072,     0.        ,   218.8639886 ,\n             246.42026873])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 36\n          nit: 24\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -1.76491214,  1.49768933, -2.30258509,\n           -4.60517019,  0.        , -3.40193308, -2.30258509,  2.30258509,\n           -2.68288077, -4.06937858, -2.04385712,  1.73412843, -2.30258509,\n            0.26606458, -2.30258509,  0.73949084, -2.30258509, -1.82914477,\n           -2.23381959, -4.06338654, -0.22314355, -1.61434557, -2.30258509])\n\n\n\n\n\n    <graphdot.model.gaussian_process.gpr.GaussianProcessRegressor at 0x7fd802672090>\n\n\n\n\n```\nmu = gpr10.predict(train.graphs)\nplt.scatter(train[target], mu)\nplt.show()\n\nprint('Training set')\nprint('MAE:', np.mean(np.abs(train[target] - mu)))\nprint('RMSE:', np.std(train[target] - mu))\n```\n\n\n```\nmu_test = gpr10.predict(test.graphs)\nplt.scatter(test[target], mu_test)\nplt.show()\n\nprint('Test set')\nprint('MAE:', np.mean(np.abs(test[target] - mu_test)))\nprint('RMSE:', np.std(test[target] - mu_test))\n```\n\n\n```\ndef gpr_train(train, repeat_num, aro_c_n = 0.5, ato_c_n = 0.5, cha_c_n = 0.5, chi_c_n = 0.5, hco_c_n = 0.5, hyb_c_n = 0.5, ring_c_n = 0.5, \n              aro_c_e = 0.5, con_c_e = 0.5, ord_c_e = 0.5, ring_c_e = 0.5, ste_c_e = 0.5, alpha = 1e-4, train_verbose = True):\n  gpr = GaussianProcessRegressor(\n      kernel=Normalization(\n          MarginalizedGraphKernel(\n              node_kernel=uX.Additive(\n                  aromatic=uX.Constant(aro_c_n, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)), # turn constant from 0.5 to 1\n                  atomic_number=uX.Constant(ato_c_n, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                  charge=uX.Constant(cha_c_n, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                  chiral=uX.Constant(chi_c_n, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                  hcount=uX.Constant(hco_c_n, (0.01, 10.0)) * uX.SquareExponential(1.0),\n                  hybridization=uX.Constant(hyb_c_n, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                  ring_list=uX.Constant(ring_c_n, (0.01, 100.0)) * uX.Convolution(uX.KroneckerDelta(0.5,(0.1, 0.9)))\n              ).normalized,\n              edge_kernel=uX.Additive(\n                  aromatic=uX.Constant(aro_c_e, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                  conjugated=uX.Constant(con_c_e, (0.01, 10.0)) * uX.KroneckerDelta(0.5,(0.1, 0.9)),\n                  order=uX.Constant(ord_c_e, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                  ring_stereo=uX.Constant(ring_c_e, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9)),\n                  stereo=uX.Constant(ste_c_e, (0.01, 10.0)) * uX.KroneckerDelta(0.8,(0.1, 0.9))\n              ).normalized,\n              p=Uniform(1.0, p_bounds='fixed'),\n              q=0.05\n          )\n      ),\n      alpha=alpha, \n      optimizer=True,\n      normalize_y=True,\n      regularization='+',\n    )\n  \n  gpr.fit(train.graphs, train[target], repeat=repeat_num, verbose=train_verbose)\n  hyperparas = gpr.kernel.hyperparameters\n    \n  return gpr,[aro_c_n,hyperparas.node_kernel.aromatic.lhs.c,\n         ato_c_n,hyperparas.node_kernel.atomic_number.lhs.c,\n         cha_c_n,hyperparas.node_kernel.charge.lhs.c,\n         chi_c_n,hyperparas.node_kernel.chiral.lhs.c,\n         hco_c_n,hyperparas.node_kernel.hcount.lhs.c,\n         hyb_c_n,hyperparas.node_kernel.hybridization.lhs.c,\n         ring_c_n,hyperparas.node_kernel.ring_list.lhs.c,\n         aro_c_e,hyperparas.edge_kernel.aromatic.lhs.c,\n         con_c_e,hyperparas.edge_kernel.conjugated.lhs.c,\n         ord_c_e,hyperparas.edge_kernel.order.lhs.c,\n         ring_c_e,hyperparas.edge_kernel.ring_stereo.lhs.c,\n         ste_c_e,hyperparas.edge_kernel.stereo.lhs.c,\n         alpha]\n```\n\n\n```\n# list out the investigated hyperparameters\n#aro_c_ns = [1, 5, 9] # 1  \nato_c_ns = [1, 5, 9] # 2\ncha_c_ns = [1, 5, 9] # 3\nchi_c_ns = [1, 5, 9] # 4\nhco_c_ns = [1, 5, 9] # 5\nhyb_c_ns = [1, 5, 9] # 6\nring_c_ns = [1, 5, 9] # 7\naro_c_es = [1, 5, 9] # 8\ncon_c_es = [1, 5, 9] # 9\nord_c_es = [1, 5, 9] # 10\nring_c_es = [1, 5, 9] # 11\nste_c_es = [1, 5, 9]\n#alphas = [1, 1e-1, 1e-2, 1e-3, 1e-4, 1e-5] # 13\n```\n\n\n```\ncolumn_names=['aro_c_n_init','aro_c_n_final',\\\n    'ato_c_n_init','ato_c_n_final',\\\n    'cha_c_n_init','cha_c_n_final',\n    'chi_c_n_init','chi_c_n_final',\\\n    'hco_c_n_init','hco_c_n_final',\\\n    'hyb_c_n_init','hyb_c_n_final',\\\n    'ring_c_n_init','ring_c_n_final',\\\n    'aro_c_e_init','aro_c_e_final',\\\n    'con_c_e_init','con_c_e_final',\\\n    'ord_c_e_init','ord_c_e_final',\\\n    'ring_c_e_init','ring_c_e_final',\\\n    'ste_c_e_init','ste_c_e_final',\\\n    'alpha',\\\n    'RMSE_train','MAE_train', 'RMSE_test', 'MAE_test']\nexhaust_search_results = pd.DataFrame(columns=column_names)\nexhaust_search_results\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>aro_c_n_init</th>\n      <th>aro_c_n_final</th>\n      <th>ato_c_n_init</th>\n      <th>ato_c_n_final</th>\n      <th>cha_c_n_init</th>\n      <th>cha_c_n_final</th>\n      <th>chi_c_n_init</th>\n      <th>chi_c_n_final</th>\n      <th>hco_c_n_init</th>\n      <th>hco_c_n_final</th>\n      <th>hyb_c_n_init</th>\n      <th>hyb_c_n_final</th>\n      <th>ring_c_n_init</th>\n      <th>ring_c_n_final</th>\n      <th>aro_c_e_init</th>\n      <th>aro_c_e_final</th>\n      <th>con_c_e_init</th>\n      <th>con_c_e_final</th>\n      <th>ord_c_e_init</th>\n      <th>ord_c_e_final</th>\n      <th>ring_c_e_init</th>\n      <th>ring_c_e_final</th>\n      <th>ste_c_e_init</th>\n      <th>ste_c_e_final</th>\n      <th>alpha</th>\n      <th>RMSE_train</th>\n      <th>MAE_train</th>\n      <th>RMSE_test</th>\n      <th>MAE_test</th>\n    </tr>\n  </thead>\n  <tbody>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\nrepeat = 3\nfor ato_c_n in ato_c_ns:\n  model,para_list = gpr_train(train = train, repeat_num = repeat, ato_c_n = ato_c_n)\n\n  mu = model.predict(train.graphs)\n  MAE_train = np.mean(np.abs(train[target] - mu))\n  RMSE_train = np.std(train[target] - mu)\n  para_list.append(RMSE_train)\n  para_list.append(MAE_train)\n\n  mu_test = model.predict(test.graphs)\n  MAE_test = np.mean(np.abs(test[target] - mu_test))\n  RMSE_test = np.std(test[target] - mu_test)\n  para_list.append(RMSE_test)\n  para_list.append(MAE_test)\n\n  \n  data = pd.DataFrame(data = [para_list],columns = column_names)\n  exhaust_search_results = exhaust_search_results.append(data,ignore_index=True)\n```\n\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  2.8357e+06|  2.4482e+07|   2.843e+06|     -7284.4|  8.7357e+06|        24|      0.26|\n    |  1.9213e+06|   2.074e+07|   1.928e+06|     -6745.2|  8.0425e+06|        19|      0.25|\n    |  1.3279e+06|  1.6305e+07|  1.3342e+06|     -6287.4|  7.1763e+06|        18|      0.24|\n    |  1.0217e+06|  1.2611e+07|  1.0277e+06|       -5988|   6.479e+06|        19|      0.23|\n    |  8.3487e+05|  9.9424e+06|  8.4064e+05|     -5767.1|  5.8654e+06|        17|      0.25|\n    |    7.21e+05|  8.1832e+06|  7.2661e+05|     -5604.8|  5.3923e+06|        17|      0.24|\n    |  6.5213e+05|  7.2567e+06|  6.5762e+05|     -5488.9|  5.0845e+06|        17|      0.24|\n    |  6.3306e+05|  6.7079e+06|  6.3853e+05|     -5464.4|  4.8499e+06|        16|      0.26|\n    |  6.1106e+05|  6.5842e+06|  6.1648e+05|     -5419.7|  4.8245e+06|        16|      0.25|\n    |  6.0639e+05|  6.5785e+06|   6.118e+05|     -5407.2|  4.8186e+06|        16|      0.23|\n    |  6.0303e+05|  6.5485e+06|  6.0843e+05|     -5399.5|  4.8017e+06|        16|      0.25|\n    |  6.0049e+05|  6.4949e+06|  6.0588e+05|     -5394.4|   4.793e+06|        16|      0.25|\n    |  5.9905e+05|  6.4674e+06|  6.0444e+05|     -5393.1|  4.7792e+06|        16|      0.26|\n    |  5.9767e+05|  6.4328e+06|  6.0306e+05|     -5392.3|  4.7627e+06|        16|      0.25|\n    |  5.9683e+05|  6.4277e+06|  6.0222e+05|     -5390.2|  4.7601e+06|        16|      0.23|\n    |  5.9524e+05|  6.4221e+06|  6.0063e+05|     -5387.6|  4.7402e+06|        16|      0.24|\n    |  5.9512e+05|  6.4239e+06|  6.0051e+05|     -5386.2|  4.7484e+06|        16|      0.23|\n    |  5.9478e+05|  6.4132e+06|  6.0016e+05|       -5386|  4.7509e+06|        16|      0.26|\n    |  5.9392e+05|  6.3788e+06|  5.9931e+05|     -5385.9|  4.7713e+06|        16|      0.25|\n    |   5.935e+05|  6.3821e+06|  5.9889e+05|     -5385.7|  4.7683e+06|        16|      0.25|\n    |  5.9308e+05|  6.3901e+06|  5.9847e+05|     -5386.2|  4.7575e+06|        16|      0.24|\n    |  5.9313e+05|  6.3909e+06|  5.9852e+05|     -5386.3|   4.754e+06|        16|      0.29|\n    |  5.9322e+05|  6.3926e+06|   5.986e+05|     -5386.2|  4.7582e+06|        16|      0.25|\n    |   5.931e+05|  6.3901e+06|  5.9849e+05|     -5386.2|  4.7544e+06|        16|      0.26|\n    |  5.9314e+05|  6.3907e+06|  5.9852e+05|     -5386.2|   4.755e+06|        16|      0.24|\n    |  5.9308e+05|  6.3891e+06|  5.9847e+05|     -5386.2|  4.7536e+06|        16|      0.25|\n    |  5.9307e+05|   6.389e+06|  5.9845e+05|     -5386.2|  4.7553e+06|        16|      0.24|\n    |  5.9325e+05|  6.3937e+06|  5.9864e+05|     -5386.3|  4.7573e+06|        16|      0.25|\n    |  5.9308e+05|  6.3894e+06|  5.9846e+05|     -5386.2|   4.755e+06|        16|      0.24|\n    |   5.932e+05|  6.3923e+06|  5.9859e+05|     -5386.2|  4.7558e+06|        16|      0.24|\n    |  5.9316e+05|  6.3913e+06|  5.9855e+05|     -5386.2|  4.7558e+06|        16|      0.29|\n    |  5.9312e+05|  6.3904e+06|  5.9851e+05|     -5386.2|  4.7557e+06|        16|      0.24|\n    |  5.9306e+05|  6.3889e+06|  5.9844e+05|     -5386.2|  4.7558e+06|        16|      0.23|\n    |  5.9313e+05|  6.3905e+06|  5.9852e+05|     -5386.3|  4.7554e+06|        16|      0.24|\n    |   5.932e+05|  6.3924e+06|  5.9858e+05|     -5386.2|  4.7566e+06|        16|      0.24|\n    |  5.9312e+05|  6.3905e+06|  5.9851e+05|     -5386.2|  4.7559e+06|        16|      0.29|\n    |  5.9308e+05|  6.3897e+06|  5.9847e+05|     -5386.2|   4.755e+06|        16|      0.23|\n    |  5.9307e+05|  6.3892e+06|  5.9846e+05|     -5386.2|  4.7548e+06|        16|      0.23|\n    |  5.9304e+05|   6.389e+06|  5.9842e+05|     -5386.2|  4.7549e+06|        16|      0.23|\n    |  5.9317e+05|   6.391e+06|  5.9855e+05|     -5386.3|  4.7554e+06|        16|      0.25|\n    |   5.932e+05|  6.3919e+06|  5.9859e+05|     -5386.2|  4.7547e+06|        16|      0.25|\n    |  5.9316e+05|  6.3915e+06|  5.9854e+05|     -5386.2|  4.7553e+06|        16|      0.23|\n    |  5.9327e+05|   6.394e+06|  5.9865e+05|     -5386.2|  4.7559e+06|        16|      0.24|\n    |  5.9304e+05|   6.389e+06|  5.9843e+05|     -5386.2|  4.7557e+06|        16|      0.25|\n    |  5.9304e+05|  6.3886e+06|  5.9843e+05|     -5386.2|  4.7558e+06|        16|      0.23|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  1.6113e+06|  2.0314e+07|  1.6179e+06|     -6559.9|    7.36e+06|        20|      0.23|\n    |  1.2581e+06|  1.5664e+07|  1.2643e+06|     -6261.6|  6.7782e+06|        19|      0.23|\n    |  1.0003e+06|  1.2671e+07|  1.0063e+06|     -5992.5|  6.2212e+06|        18|      0.23|\n    |  7.8115e+05|  1.0003e+07|  7.8685e+05|     -5696.4|  5.6642e+06|        18|      0.24|\n    |  6.9162e+05|  7.9735e+06|  6.9719e+05|     -5566.1|  5.2745e+06|        17|      0.23|\n    |  6.3848e+05|  7.1424e+06|  6.4395e+05|     -5471.1|  5.0407e+06|        17|      0.23|\n    |  6.1765e+05|  6.7359e+06|  6.2309e+05|     -5436.1|  4.8984e+06|        16|      0.24|\n    |  6.0506e+05|  6.5944e+06|  6.1047e+05|     -5409.9|  4.8107e+06|        16|      0.24|\n    |  5.9963e+05|  6.5128e+06|  6.0503e+05|     -5397.9|  4.7795e+06|        16|      0.24|\n    |  5.9555e+05|   6.398e+06|  6.0093e+05|     -5387.7|  4.7692e+06|        16|      0.23|\n    |  5.9484e+05|  6.3997e+06|  6.0022e+05|     -5387.4|  4.7608e+06|        16|      0.23|\n    |  5.9465e+05|  6.4069e+06|  6.0004e+05|     -5387.1|  4.7514e+06|        16|      0.24|\n    |  5.9406e+05|  6.4076e+06|  5.9945e+05|     -5386.5|  4.7468e+06|        16|      0.24|\n    |  5.9376e+05|  6.4017e+06|  5.9915e+05|     -5386.4|  4.7514e+06|        16|      0.23|\n    |  5.9339e+05|  6.4065e+06|  5.9878e+05|     -5387.8|  4.7694e+06|        16|      0.24|\n    |  5.9328e+05|  6.3961e+06|  5.9867e+05|     -5386.4|  4.7566e+06|        16|      0.23|\n    |  5.9307e+05|  6.3887e+06|  5.9846e+05|     -5387.1|  4.7571e+06|        16|      0.23|\n    |  5.9314e+05|  6.3921e+06|  5.9853e+05|     -5386.4|  4.7584e+06|        16|      0.25|\n    |  5.9311e+05|  6.3902e+06|   5.985e+05|       -5387|  4.7574e+06|        16|      0.24|\n    |   5.931e+05|  6.3898e+06|  5.9849e+05|     -5387.1|  4.7607e+06|        16|      0.24|\n    |  5.9316e+05|  6.3906e+06|  5.9854e+05|     -5387.1|  4.7586e+06|        16|      0.29|\n    |  5.9307e+05|  6.3888e+06|  5.9846e+05|     -5387.1|  4.7581e+06|        16|      0.24|\n    |  5.9304e+05|  6.3886e+06|  5.9843e+05|     -5387.1|  4.7592e+06|        16|      0.23|\n    |  5.9325e+05|  6.3932e+06|  5.9864e+05|     -5387.1|  4.7559e+06|        16|      0.26|\n    |  5.9308e+05|  6.3892e+06|  5.9847e+05|     -5387.1|  4.7579e+06|        16|      0.25|\n    |  5.9308e+05|  6.3888e+06|  5.9846e+05|     -5387.1|  4.7596e+06|        16|      0.25|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  3.3809e+06|   2.567e+07|  3.3884e+06|     -7523.2|  8.7437e+06|        20|      0.25|\n    |  2.2099e+06|  2.2186e+07|  2.2169e+06|     -6915.1|  8.0945e+06|        19|      0.23|\n    |  1.5265e+06|  1.7804e+07|   1.533e+06|     -6452.2|  7.3327e+06|        19|      0.24|\n    |  1.1479e+06|  1.4003e+07|   1.154e+06|     -6122.4|  6.6504e+06|        18|      0.25|\n    |  9.0657e+05|  1.1219e+07|  9.1243e+05|     -5856.3|  6.0662e+06|        18|       0.3|\n    |  7.6609e+05|  9.2708e+06|  7.7175e+05|     -5661.2|  5.6381e+06|        18|      0.32|\n    |   6.885e+05|  7.9122e+06|  6.9406e+05|     -5553.1|  5.2831e+06|        17|       0.3|\n    |  6.3344e+05|  7.1445e+06|   6.389e+05|     -5452.7|  5.0384e+06|        17|      0.32|\n    |  6.1447e+05|  6.7939e+06|  6.1989e+05|     -5425.2|  4.9013e+06|        17|      0.32|\n    |  6.0958e+05|   6.704e+06|  6.1499e+05|     -5416.7|    4.86e+06|        17|      0.31|\n    |  6.0106e+05|  6.5522e+06|  6.0646e+05|     -5400.7|  4.7973e+06|        16|      0.32|\n    |  5.9817e+05|  6.4179e+06|  6.0357e+05|     -5395.5|  4.7812e+06|        16|       0.3|\n    |  5.9642e+05|  6.4237e+06|  6.0182e+05|       -5391|  4.7762e+06|        16|      0.32|\n    |  5.9571e+05|  6.4234e+06|   6.011e+05|     -5388.5|  4.7713e+06|        16|      0.31|\n    |  5.9525e+05|  6.4155e+06|  6.0064e+05|     -5387.2|  4.7679e+06|        16|      0.31|\n    |  5.9468e+05|  6.4176e+06|  6.0007e+05|     -5387.5|  4.7529e+06|        16|      0.32|\n    |  5.9438e+05|  6.4103e+06|  5.9977e+05|     -5387.9|  4.7551e+06|        16|      0.37|\n    |  5.9386e+05|  6.3967e+06|  5.9924e+05|     -5388.1|  4.7506e+06|        16|      0.34|\n    |   5.935e+05|  6.3876e+06|  5.9889e+05|       -5388|  4.7502e+06|        16|      0.32|\n    |  5.9311e+05|  6.3863e+06|  5.9849e+05|     -5386.1|  4.7595e+06|        16|      0.31|\n    |    5.93e+05|  6.3799e+06|  5.9838e+05|     -5385.8|  4.7627e+06|        16|       0.3|\n    |  5.9305e+05|  6.3782e+06|  5.9844e+05|     -5385.9|  4.7572e+06|        16|      0.32|\n    |  5.9307e+05|  6.3812e+06|  5.9845e+05|     -5385.8|  4.7653e+06|        16|      0.32|\n    |    5.93e+05|  6.3793e+06|  5.9838e+05|     -5385.8|   4.763e+06|        16|      0.31|\n    |    5.93e+05|  6.3794e+06|  5.9839e+05|     -5385.8|  4.7612e+06|        16|       0.3|\n    |    5.93e+05|  6.3797e+06|  5.9839e+05|     -5385.8|  4.7625e+06|        16|      0.33|\n    Optimization result:\n          fun: 592999.262897309\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 6.37557709e+02,  1.28957404e+02,  1.70757693e+01,  2.63063370e+02,\n            1.36967727e+04,  2.82633429e+02,  0.00000000e+00, -1.00472222e+02,\n            8.89951583e+01, -1.57579674e+03,  0.00000000e+00,  1.17316984e+02,\n            5.10169591e+01,  8.89194089e+02,  1.76293270e+04, -7.14870043e+01,\n            1.61586947e+03, -2.41999176e+02,  3.03163717e+03,  2.54335305e+02,\n            2.68027367e+02,  6.99937998e+01,  0.00000000e+00, -1.13350766e+01,\n            2.38014761e+02])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 26\n          nit: 21\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -2.30258509,  1.47487695, -2.30258509,\n           -4.60517019,  1.38836933, -3.71617987, -2.28794699,  2.30258509,\n           -2.72487862, -3.89275983, -2.30258509,  1.73055155, -2.30258509,\n            1.53183641, -2.30258509,  2.15730037, -2.30258509, -0.15867978,\n           -2.30258509, -3.79930524, -0.19078879, -0.38342785, -2.30258509])\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  3.0644e+06|  2.5314e+07|  3.0719e+06|     -7434.6|  8.9225e+06|        22|      0.24|\n    |  2.1158e+06|  2.2216e+07|  2.1227e+06|     -6895.5|   8.267e+06|        20|      0.24|\n    |  1.3279e+06|   1.684e+07|  1.3342e+06|     -6284.8|  7.1507e+06|        19|      0.24|\n    |  9.8986e+05|  1.1985e+07|  9.9581e+05|     -5947.9|  6.3966e+06|        18|      0.23|\n    |  8.4052e+05|  9.8498e+06|  8.4629e+05|     -5770.5|  5.8921e+06|        17|      0.23|\n    |  7.2776e+05|  8.1899e+06|  7.3337e+05|     -5615.9|  5.4058e+06|        17|      0.22|\n    |  6.5835e+05|   7.386e+06|  6.6385e+05|     -5497.8|  5.1093e+06|        17|      0.25|\n    |  6.2434e+05|  6.7359e+06|  6.2978e+05|     -5446.8|   4.881e+06|        16|      0.23|\n    |  6.0817e+05|  6.5653e+06|  6.1358e+05|       -5415|   4.805e+06|        16|      0.23|\n    |  6.0087e+05|   6.523e+06|  6.0626e+05|     -5396.6|  4.7858e+06|        16|      0.23|\n    |  5.9897e+05|  6.4925e+06|  6.0436e+05|     -5392.8|  4.7731e+06|        16|      0.24|\n    |  6.0142e+05|  6.5559e+06|  6.0681e+05|     -5389.2|   4.817e+06|        17|      0.24|\n    |  5.9852e+05|  6.4979e+06|  6.0391e+05|     -5389.9|    4.78e+06|        16|      0.23|\n    |  5.9957e+05|  6.5349e+06|  6.0496e+05|     -5387.5|  4.8005e+06|        17|      0.24|\n    |  5.9844e+05|  6.4995e+06|  6.0383e+05|     -5389.3|  4.7831e+06|        16|      0.29|\n    |  5.9715e+05|  6.4564e+06|  6.0254e+05|     -5389.3|  4.7656e+06|        16|      0.23|\n    |  5.9698e+05|  6.4517e+06|  6.0237e+05|     -5388.9|  4.7665e+06|        16|      0.24|\n    |  5.9585e+05|  6.4215e+06|  6.0124e+05|     -5387.4|  4.7544e+06|        16|      0.22|\n    |  5.9514e+05|  6.4042e+06|  6.0053e+05|     -5386.6|  4.7481e+06|        16|      0.23|\n    |  5.9499e+05|  6.4122e+06|  6.0038e+05|     -5386.1|  4.7466e+06|        16|      0.23|\n    |  5.9505e+05|  6.4191e+06|  6.0044e+05|     -5386.1|  4.7424e+06|        16|      0.22|\n    |  5.9504e+05|  6.4142e+06|  6.0043e+05|     -5386.1|   4.744e+06|        16|      0.23|\n    |  5.9526e+05|  6.4179e+06|  6.0064e+05|     -5386.1|  4.7438e+06|        16|      0.23|\n    |  5.9516e+05|  6.4162e+06|  6.0054e+05|     -5386.1|   4.746e+06|        16|      0.22|\n    |   5.951e+05|  6.4146e+06|  6.0049e+05|     -5386.1|  4.7451e+06|        16|      0.23|\n    |  5.9509e+05|  6.4141e+06|  6.0047e+05|     -5386.1|  4.7478e+06|        16|      0.23|\n    |  5.9519e+05|  6.4168e+06|  6.0058e+05|     -5386.1|  4.7462e+06|        16|      0.25|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  5.0155e+06|  1.1274e+07|  5.0237e+06|     -8253.4|  9.6358e+06|        16|      0.24|\n    |  3.8821e+06|  1.5647e+07|  3.8899e+06|     -7808.2|  9.3045e+06|        17|      0.23|\n    |  1.0393e+06|  1.2701e+07|  1.0453e+06|     -5944.3|  5.8767e+06|        19|      0.23|\n    |  8.1736e+05|   9.245e+06|  8.2307e+05|     -5706.9|  5.3322e+06|        17|      0.23|\n    |  7.8782e+05|  8.6319e+06|   7.935e+05|     -5675.5|  5.2196e+06|        16|      0.23|\n    |  7.7036e+05|  8.3617e+06|  7.7601e+05|     -5655.4|  5.1668e+06|        16|      0.23|\n    |  6.7361e+05|  7.2377e+06|  6.7914e+05|     -5527.2|  5.0743e+06|        17|      0.26|\n    |  7.0073e+05|  7.5283e+06|  7.0629e+05|     -5568.6|  4.9886e+06|        16|      0.25|\n    |  6.4084e+05|  6.8956e+06|  6.4632e+05|     -5480.8|  4.8809e+06|        16|      0.26|\n    |  8.4838e+05|  9.2932e+06|  8.5415e+05|     -5765.8|  5.6947e+06|        18|      0.25|\n    |  6.3654e+05|  6.8601e+06|  6.4201e+05|     -5473.9|  4.8905e+06|        16|      0.24|\n    |  6.2044e+05|  6.6979e+06|  6.2588e+05|     -5442.6|  4.8477e+06|        16|      0.23|\n    |  6.0571e+05|   6.602e+06|  6.1111e+05|     -5406.5|  4.8175e+06|        16|      0.23|\n    |   6.045e+05|  6.5724e+06|  6.0991e+05|     -5404.3|  4.8113e+06|        16|      0.22|\n    |  6.0166e+05|  6.5157e+06|  6.0706e+05|     -5396.4|  4.8063e+06|        16|      0.23|\n    |  6.0071e+05|  6.4913e+06|   6.061e+05|     -5396.3|  4.7893e+06|        16|      0.24|\n    |  6.0025e+05|  6.4799e+06|  6.0565e+05|       -5396|  4.7762e+06|        16|      0.23|\n    |  5.9972e+05|  6.4718e+06|  6.0511e+05|     -5395.1|  4.7681e+06|        16|      0.23|\n    |   5.989e+05|  6.4867e+06|  6.0429e+05|     -5390.9|  4.7735e+06|        16|      0.26|\n    |  5.9836e+05|   6.472e+06|  6.0376e+05|     -5390.7|  4.7644e+06|        16|      0.25|\n    |  5.9757e+05|  6.4537e+06|  6.0296e+05|     -5390.3|  4.7457e+06|        16|      0.27|\n    |  5.9703e+05|  6.4442e+06|  6.0242e+05|     -5389.8|  4.7398e+06|        16|      0.24|\n    |  5.9592e+05|  6.4434e+06|  6.0131e+05|     -5386.4|  4.7469e+06|        16|      0.24|\n    |  5.9532e+05|   6.428e+06|  6.0071e+05|     -5386.5|  4.7438e+06|        16|      0.23|\n    |  5.9401e+05|  6.3852e+06|   5.994e+05|     -5387.7|   4.746e+06|        16|      0.22|\n    |  5.9374e+05|  6.3875e+06|  5.9912e+05|     -5387.3|  4.7502e+06|        16|      0.23|\n    |  5.9328e+05|  6.3988e+06|  5.9867e+05|     -5386.7|  4.7627e+06|        16|      0.23|\n    |  5.9325e+05|  6.3961e+06|  5.9864e+05|     -5386.7|  4.7584e+06|        16|      0.24|\n    |  5.9327e+05|  6.4004e+06|  5.9866e+05|     -5386.6|  4.7581e+06|        16|      0.23|\n    |  5.9327e+05|  6.3979e+06|  5.9866e+05|     -5386.7|  4.7632e+06|        16|      0.22|\n    |  5.9326e+05|  6.3972e+06|  5.9864e+05|     -5386.7|  4.7606e+06|        16|      0.24|\n    |  5.9318e+05|   6.395e+06|  5.9856e+05|     -5386.7|  4.7638e+06|        16|      0.23|\n    |  5.9327e+05|  6.3974e+06|  5.9865e+05|     -5386.7|  4.7603e+06|        16|      0.25|\n    |  5.9319e+05|  6.3958e+06|  5.9858e+05|     -5386.7|  4.7595e+06|        16|      0.28|\n    |  5.9326e+05|     6.4e+06|  5.9865e+05|     -5386.6|  4.7558e+06|        16|      0.24|\n    |   5.932e+05|  6.3962e+06|  5.9859e+05|     -5386.7|  4.7591e+06|        16|      0.23|\n    |  5.9328e+05|  6.3976e+06|  5.9867e+05|     -5386.7|  4.7621e+06|        16|      0.24|\n    |  5.9325e+05|  6.3969e+06|  5.9864e+05|     -5386.7|  4.7646e+06|        16|       0.3|\n    |  5.9324e+05|  6.3969e+06|  5.9863e+05|     -5386.7|  4.7606e+06|        16|       0.3|\n    |  5.9332e+05|  6.3986e+06|  5.9871e+05|     -5386.7|  4.7605e+06|        16|      0.29|\n    |  5.9324e+05|  6.3965e+06|  5.9863e+05|     -5386.7|  4.7611e+06|        16|       0.3|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  2.9521e+06|  3.5287e+07|  2.9595e+06|     -7373.1|  8.5724e+06|        24|      0.29|\n    |  1.9406e+06|  2.6937e+07|  1.9474e+06|     -6787.1|  7.8258e+06|        22|      0.29|\n    |  1.4889e+06|  2.1736e+07|  1.4953e+06|     -6449.5|  7.2511e+06|        21|      0.29|\n    |  1.1658e+06|  1.6691e+07|  1.1719e+06|     -6154.4|  6.6855e+06|        20|      0.33|\n    |  9.8908e+05|  1.3865e+07|  9.9504e+05|     -5963.3|  6.2751e+06|        19|      0.32|\n    |  8.3859e+05|   1.104e+07|  8.4437e+05|     -5776.6|  5.8518e+06|        18|      0.31|\n    |  7.3138e+05|  8.8523e+06|  7.3701e+05|     -5630.2|  5.4239e+06|        17|       0.3|\n    |  6.5973e+05|   7.735e+06|  6.6523e+05|     -5503.1|  5.1374e+06|        17|       0.3|\n    |  6.2808e+05|  7.0189e+06|  6.3354e+05|     -5458.7|  4.9077e+06|        17|      0.29|\n    |  6.2357e+05|  6.9767e+06|  6.2902e+05|     -5448.9|  4.9065e+06|        17|      0.31|\n    |  6.1816e+05|  6.9141e+06|   6.236e+05|     -5435.6|  4.8985e+06|        17|      0.31|\n    |   6.124e+05|  6.8074e+06|  6.1782e+05|     -5422.4|    4.88e+06|        17|       0.3|\n    |  6.0535e+05|  6.6203e+06|  6.1076e+05|     -5409.5|  4.8534e+06|        17|      0.31|\n    |  6.0547e+05|  6.5888e+06|  6.1087e+05|     -5402.3|  4.8638e+06|        17|      0.31|\n    |  6.0437e+05|  6.5942e+06|  6.0978e+05|     -5403.9|  4.8563e+06|        17|      0.29|\n    |  6.0445e+05|   6.535e+06|  6.0985e+05|     -5400.6|  4.8773e+06|        17|       0.3|\n    |  6.0401e+05|  6.5607e+06|  6.0942e+05|     -5401.8|  4.8656e+06|        17|      0.31|\n    |  6.0102e+05|  6.4832e+06|  6.0642e+05|     -5400.8|  4.8352e+06|        16|      0.31|\n    |  6.0078e+05|  6.4773e+06|  6.0619e+05|     -5401.2|  4.8291e+06|        16|      0.33|\n    |  6.0025e+05|  6.4637e+06|  6.0565e+05|     -5401.2|  4.8127e+06|        16|      0.31|\n    |  5.9949e+05|  6.4429e+06|  6.0489e+05|     -5400.2|  4.7937e+06|        16|       0.3|\n    |  5.9915e+05|  6.4426e+06|  6.0455e+05|     -5398.7|  4.8014e+06|        16|      0.31|\n    |  5.9848e+05|  6.4383e+06|  6.0387e+05|       -5396|  4.8031e+06|        16|       0.3|\n    |  5.9768e+05|  6.4312e+06|  6.0307e+05|     -5392.8|  4.8046e+06|        16|       0.3|\n    |  5.9671e+05|  6.4134e+06|   6.021e+05|     -5389.8|  4.7986e+06|        16|      0.29|\n    |  6.0086e+05|  6.4549e+06|  6.0625e+05|     -5389.6|  4.8181e+06|        16|      0.28|\n    |  5.9513e+05|   6.393e+06|  6.0052e+05|     -5385.7|  4.7838e+06|        16|       0.3|\n    |   5.952e+05|  6.3551e+06|  6.0059e+05|       -5388|  4.7637e+06|        16|       0.3|\n    |  5.9469e+05|  6.3686e+06|  6.0007e+05|     -5386.2|  4.7756e+06|        16|      0.29|\n    |   5.947e+05|  6.3714e+06|  6.0009e+05|     -5386.2|  4.7686e+06|        16|       0.3|\n    |  5.9474e+05|  6.3707e+06|  6.0013e+05|     -5386.1|  4.7702e+06|        16|       0.3|\n    |  5.9471e+05|  6.3691e+06|   6.001e+05|     -5386.2|  4.7721e+06|        16|      0.32|\n    |  5.9493e+05|  6.3741e+06|  6.0031e+05|     -5386.2|  4.7699e+06|        16|      0.31|\n    |  5.9477e+05|  6.3703e+06|  6.0015e+05|     -5386.2|  4.7727e+06|        16|      0.31|\n    |  5.9475e+05|  6.3701e+06|  6.0014e+05|     -5386.2|  4.7752e+06|        16|      0.29|\n    |  5.9475e+05|  6.3696e+06|  6.0013e+05|     -5386.2|  4.7732e+06|        16|      0.31|\n    |  5.9467e+05|  6.3685e+06|  6.0006e+05|     -5386.2|  4.7724e+06|        16|       0.3|\n    |  5.9458e+05|  6.3686e+06|  5.9997e+05|     -5386.2|  4.7673e+06|        16|      0.29|\n    |  5.9451e+05|  6.3666e+06|  5.9989e+05|     -5386.1|  4.7652e+06|        16|      0.31|\n    |  5.9464e+05|  6.3699e+06|  6.0002e+05|     -5386.3|  4.7615e+06|        16|      0.29|\n    |  5.9451e+05|  6.3668e+06|   5.999e+05|     -5386.1|  4.7663e+06|        16|      0.32|\n    |  5.9445e+05|  6.3647e+06|  5.9983e+05|     -5386.1|   4.763e+06|        16|      0.29|\n    |  5.9446e+05|  6.3649e+06|  5.9985e+05|     -5386.1|  4.7636e+06|        16|       0.3|\n    |  5.9455e+05|  6.3671e+06|  5.9994e+05|     -5386.1|  4.7645e+06|        16|       0.3|\n    Optimization result:\n          fun: 593242.1427999439\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 6.39244705e+02,  1.29678119e+02,  1.70751991e+01,  2.64988564e+02,\n            1.37175442e+04,  2.83375186e+02,  0.00000000e+00, -1.02672973e+02,\n            9.89278355e+01, -5.99504710e+02,  0.00000000e+00,  8.68982415e+01,\n            5.84802721e+01, -5.67496817e+01,  1.75653701e+04,  4.06899639e+02,\n            1.70250971e+03, -7.52799075e+02,  2.98367363e+03, -3.87774589e+02,\n            2.36922561e+02,  1.89661230e+02,  0.00000000e+00,  5.44871660e+02,\n            2.56475008e+02])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 41\n          nit: 26\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -2.30258509,  1.47382103, -2.30258509,\n           -4.60517019, -0.92055184, -3.58281591, -2.30258509,  2.30258509,\n           -8.71221151, -4.11374043, -2.00630242,  1.7186841 , -2.30258509,\n            0.04775122, -2.30258509,  0.5542733 , -2.30258509, -2.15138843,\n           -2.30258509, -4.37025229, -0.32637211, -1.65930591, -2.30258509])\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  3.2761e+06|  2.5568e+07|  3.2836e+06|     -7545.4|  9.0292e+06|        23|      0.25|\n    |  2.3022e+06|  2.3345e+07|  2.3092e+06|     -7020.4|  8.4259e+06|        21|      0.24|\n    |  1.2831e+06|  1.6655e+07|  1.2893e+06|     -6243.3|  7.0573e+06|        20|      0.25|\n    |  9.5836e+05|  1.1565e+07|  9.6427e+05|     -5909.2|  6.3009e+06|        18|      0.23|\n    |  8.2605e+05|  9.6213e+06|   8.318e+05|     -5748.5|  5.8434e+06|        17|      0.23|\n    |  7.2038e+05|   8.029e+06|  7.2598e+05|     -5605.2|  5.3655e+06|        17|      0.28|\n    |  6.5663e+05|  7.3142e+06|  6.6212e+05|     -5497.3|  5.0814e+06|        17|      0.24|\n    |  6.2214e+05|  6.7631e+06|  6.2759e+05|     -5441.4|  4.8894e+06|        16|      0.22|\n    |  6.0491e+05|  6.5501e+06|  6.1032e+05|     -5407.8|  4.7932e+06|        16|      0.23|\n    |  5.9984e+05|  6.5046e+06|  6.0523e+05|     -5393.7|  4.7862e+06|        16|      0.24|\n    |  5.9757e+05|  6.4625e+06|  6.0296e+05|     -5389.7|  4.7713e+06|        16|      0.23|\n    |  5.9702e+05|  6.4491e+06|  6.0241e+05|     -5389.6|  4.7653e+06|        16|      0.24|\n    |  5.9599e+05|  6.4255e+06|  6.0137e+05|     -5389.4|  4.7399e+06|        16|      0.23|\n    |  5.9535e+05|  6.4203e+06|  6.0074e+05|     -5388.1|  4.7382e+06|        16|      0.24|\n    |  5.9482e+05|  6.4111e+06|  6.0021e+05|     -5386.4|  4.7564e+06|        16|      0.22|\n    |  5.9468e+05|  6.4089e+06|  6.0006e+05|     -5386.4|   4.757e+06|        16|      0.23|\n    |  5.9409e+05|  6.4028e+06|  5.9947e+05|     -5387.1|   4.764e+06|        16|      0.23|\n    |  5.9382e+05|  6.4048e+06|  5.9921e+05|     -5387.2|  4.7617e+06|        16|      0.23|\n    |   5.934e+05|  6.4002e+06|  5.9879e+05|     -5387.3|  4.7627e+06|        16|      0.24|\n    |  5.9316e+05|  6.3999e+06|  5.9855e+05|       -5387|  4.7608e+06|        16|      0.24|\n    |  5.9321e+05|  6.4015e+06|   5.986e+05|     -5386.9|  4.7573e+06|        16|      0.22|\n    |  5.9337e+05|  6.4045e+06|  5.9875e+05|       -5387|    4.76e+06|        16|      0.22|\n    |  5.9315e+05|  6.3996e+06|  5.9854e+05|       -5387|  4.7581e+06|        16|      0.23|\n    |  5.9325e+05|  6.4018e+06|  5.9863e+05|       -5387|  4.7591e+06|        16|      0.22|\n    |   5.932e+05|  6.4009e+06|  5.9858e+05|       -5387|    4.76e+06|        16|      0.23|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  4.3681e+06|  2.4416e+07|  4.3761e+06|     -8020.3|  9.3727e+06|        21|      0.24|\n    |  2.7954e+06|  2.5049e+07|  2.8027e+06|     -7289.8|  8.7832e+06|        20|      0.23|\n    |  1.3577e+06|  1.7118e+07|   1.364e+06|     -6300.3|  7.2139e+06|        19|      0.24|\n    |   1.195e+06|  1.5064e+07|  1.2011e+06|     -6153.2|  6.9012e+06|        19|      0.24|\n    |  9.3444e+05|  1.1321e+07|  9.4033e+05|     -5885.5|   6.216e+06|        18|      0.25|\n    |  8.2448e+05|  9.5801e+06|  8.3024e+05|     -5753.4|  5.8034e+06|        17|      0.23|\n    |  7.3317e+05|  8.3684e+06|  7.3879e+05|     -5624.7|  5.4312e+06|        17|      0.23|\n    |   6.606e+05|   7.457e+06|  6.6611e+05|     -5506.5|  5.1161e+06|        17|      0.25|\n    |  6.2351e+05|  6.8882e+06|  6.2895e+05|     -5442.8|  4.8877e+06|        16|      0.22|\n    |  6.1233e+05|  6.6979e+06|  6.1775e+05|     -5418.4|  4.8691e+06|        17|      0.24|\n    |  6.0783e+05|  6.6681e+06|  6.1324e+05|     -5411.1|  4.8422e+06|        17|      0.23|\n    |   6.058e+05|  6.6385e+06|  6.1121e+05|     -5407.2|  4.8273e+06|        17|      0.23|\n    |  6.0034e+05|  6.5252e+06|  6.0574e+05|     -5398.4|  4.8002e+06|        16|      0.23|\n    |  5.9742e+05|  6.4528e+06|  6.0281e+05|     -5394.7|   4.782e+06|        16|      0.23|\n    |  5.9687e+05|  6.4509e+06|  6.0226e+05|     -5392.8|  4.7875e+06|        16|      0.23|\n    |   5.964e+05|  6.4437e+06|   6.018e+05|     -5391.8|  4.7854e+06|        16|      0.24|\n    |  5.9605e+05|  6.4344e+06|  6.0144e+05|     -5391.4|  4.7854e+06|        16|      0.23|\n    |  5.9518e+05|  6.4134e+06|  6.0057e+05|     -5390.2|  4.7719e+06|        16|      0.22|\n    |  5.9456e+05|  6.4057e+06|  5.9995e+05|     -5388.9|  4.7646e+06|        16|      0.26|\n    |  5.9341e+05|  6.3946e+06|   5.988e+05|     -5386.2|  4.7549e+06|        16|      0.24|\n    |  5.9337e+05|  6.3941e+06|  5.9876e+05|     -5386.3|  4.7553e+06|        16|      0.22|\n    |  5.9321e+05|  6.3934e+06|   5.986e+05|     -5386.8|  4.7521e+06|        16|      0.22|\n    |  5.9317e+05|  6.3943e+06|  5.9855e+05|       -5387|  4.7562e+06|        16|      0.22|\n    |  5.9301e+05|  6.3855e+06|   5.984e+05|     -5386.9|  4.7627e+06|        16|      0.23|\n    |  5.9315e+05|  6.3962e+06|  5.9853e+05|     -5386.1|  4.7642e+06|        16|      0.23|\n    |   5.931e+05|  6.3889e+06|  5.9849e+05|     -5386.8|    4.76e+06|        16|      0.28|\n    |    5.93e+05|  6.3858e+06|  5.9838e+05|     -5386.9|  4.7559e+06|        16|      0.23|\n    |  5.9312e+05|  6.3882e+06|   5.985e+05|     -5386.9|  4.7615e+06|        16|      0.23|\n    |  5.9309e+05|  6.3878e+06|  5.9848e+05|     -5386.9|  4.7607e+06|        16|      0.25|\n    |  5.9315e+05|  6.3889e+06|  5.9853e+05|     -5386.9|  4.7567e+06|        16|      0.25|\n    |        logP|       dlogP|     y^T.K.y|     log|K| |     Cond(K)|  GPU time|  CPU time|\n    |------------|------------|------------|------------|------------|----------|----------|\n    |  2.2932e+06|  2.4783e+07|  2.3002e+06|     -7019.7|  8.3792e+06|        21|      0.24|\n    |  1.5586e+06|  1.7302e+07|  1.5651e+06|     -6513.2|  7.4718e+06|        19|      0.23|\n    |   1.121e+06|  1.2443e+07|  1.1271e+06|     -6116.9|  6.5724e+06|        17|      0.24|\n    |  9.0933e+05|  1.0184e+07|   9.152e+05|     -5871.7|  6.0342e+06|        17|      0.24|\n    |   7.333e+05|  8.5948e+06|  7.3892e+05|     -5620.2|  5.4934e+06|        17|      0.23|\n    |  6.7746e+05|  7.8203e+06|    6.83e+05|     -5534.2|  5.2201e+06|        17|      0.23|\n    |  6.3071e+05|  7.0299e+06|  6.3617e+05|     -5452.1|  4.9924e+06|        17|      0.23|\n    |  6.1828e+05|  6.8758e+06|  6.2371e+05|     -5428.7|  4.8979e+06|        17|      0.23|\n    |  6.0894e+05|    6.71e+06|  6.1435e+05|     -5413.4|  4.8341e+06|        17|      0.24|\n    |  6.0039e+05|  6.5287e+06|  6.0579e+05|     -5398.6|  4.7882e+06|        16|      0.23|\n    |  5.9824e+05|  6.4817e+06|  6.0363e+05|     -5393.6|  4.7775e+06|        16|      0.23|\n    |   5.959e+05|  6.4395e+06|  6.0129e+05|       -5390|  4.7461e+06|        16|      0.25|\n    |  5.9554e+05|  6.4458e+06|  6.0093e+05|     -5387.9|  4.7534e+06|        16|      0.24|\n    |  5.9539e+05|  6.4444e+06|  6.0078e+05|     -5387.7|  4.7549e+06|        16|      0.24|\n    |  5.9487e+05|  6.4362e+06|  6.0026e+05|     -5387.1|  4.7475e+06|        16|      0.27|\n    |  5.9449e+05|   6.425e+06|  5.9987e+05|       -5387|  4.7446e+06|        16|      0.23|\n    |  5.9437e+05|  6.4209e+06|  5.9975e+05|     -5386.8|   4.748e+06|        16|      0.24|\n    |  5.9434e+05|  6.4167e+06|  5.9973e+05|     -5386.8|  4.7485e+06|        16|      0.23|\n    |  5.9425e+05|  6.4155e+06|  5.9964e+05|       -5387|  4.7485e+06|        16|      0.23|\n    |  5.9391e+05|  6.4121e+06|   5.993e+05|     -5387.7|  4.7518e+06|        16|      0.23|\n    |  5.9378e+05|   6.417e+06|  5.9916e+05|     -5387.5|  4.7544e+06|        16|      0.23|\n    |  5.9375e+05|  6.4309e+06|  5.9914e+05|     -5387.4|   4.759e+06|        16|      0.23|\n    |  5.9363e+05|  6.4274e+06|  5.9901e+05|     -5387.4|  4.7553e+06|        16|      0.25|\n    |   5.935e+05|  6.4221e+06|  5.9888e+05|     -5387.7|  4.7596e+06|        16|      0.26|\n    |  5.9336e+05|  6.3902e+06|  5.9875e+05|     -5388.2|  4.7748e+06|        16|      0.24|\n    |  5.9325e+05|  6.4085e+06|  5.9864e+05|     -5387.8|  4.7629e+06|        16|      0.23|\n    |  5.9294e+05|  6.3897e+06|  5.9833e+05|       -5387|  4.7676e+06|        16|      0.25|\n    |  5.9302e+05|  6.3789e+06|   5.984e+05|     -5386.8|  4.7538e+06|        16|      0.24|\n    |  5.9297e+05|  6.3867e+06|  5.9836e+05|     -5386.9|  4.7609e+06|        16|      0.24|\n    |  5.9312e+05|  6.3933e+06|  5.9851e+05|       -5387|  4.7665e+06|        16|      0.23|\n    |  5.9304e+05|  6.3918e+06|  5.9843e+05|       -5387|  4.7667e+06|        16|      0.23|\n    |  5.9304e+05|  6.3917e+06|  5.9842e+05|       -5387|  4.7666e+06|        16|      0.23|\n    |  5.9301e+05|   6.391e+06|  5.9839e+05|       -5387|  4.7702e+06|        16|      0.24|\n    |  5.9302e+05|  6.3914e+06|   5.984e+05|       -5387|  4.7676e+06|        16|      0.23|\n    |  5.9307e+05|  6.3929e+06|  5.9846e+05|       -5387|  4.7681e+06|        16|      0.24|\n    Optimization result:\n          fun: 593068.1209087458\n     hess_inv: <25x25 LbfgsInvHessProduct with dtype=float64>\n          jac: array([ 6.38882273e+02,  1.28143794e+02,  1.72027961e+01, -1.38623091e+03,\n            1.36305971e+04,  2.82977101e+02,  0.00000000e+00, -5.83627630e+01,\n            1.43504932e+02, -7.35094084e+02,  1.36531205e-24,  6.29850735e+01,\n            3.04954997e+01,  1.71799225e+03,  1.76564720e+04, -1.75949297e+02,\n            1.60376945e+03, -8.53108271e+02,  3.01168866e+03,  2.11977183e+02,\n            2.63321099e+02,  6.32876186e+01,  0.00000000e+00,  7.51600909e+02,\n            2.56035744e+02])\n      message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'\n         nfev: 35\n          nit: 25\n       status: 0\n      success: True\n            x: array([-9.21034037, -4.60517019, -2.30258509,  1.45563161, -2.30258509,\n           -4.60517019, -0.82374502, -3.13326863, -2.30258509,  2.30258509,\n           -2.48710121, -4.42886582, -2.30258509,  1.73644828, -2.30258509,\n            0.86751178, -2.30258509,  1.47836529, -2.30258509, -0.84119831,\n           -2.30258509, -4.55014905, -0.49842698, -0.67297937, -2.30258509])\n\n\n\n```\nexhaust_search_results\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>aro_c_n_init</th>\n      <th>aro_c_n_final</th>\n      <th>ato_c_n_init</th>\n      <th>ato_c_n_final</th>\n      <th>cha_c_n_init</th>\n      <th>cha_c_n_final</th>\n      <th>chi_c_n_init</th>\n      <th>chi_c_n_final</th>\n      <th>hco_c_n_init</th>\n      <th>hco_c_n_final</th>\n      <th>hyb_c_n_init</th>\n      <th>hyb_c_n_final</th>\n      <th>ring_c_n_init</th>\n      <th>ring_c_n_final</th>\n      <th>aro_c_e_init</th>\n      <th>aro_c_e_final</th>\n      <th>con_c_e_init</th>\n      <th>con_c_e_final</th>\n      <th>ord_c_e_init</th>\n      <th>ord_c_e_final</th>\n      <th>ring_c_e_init</th>\n      <th>ring_c_e_final</th>\n      <th>ste_c_e_init</th>\n      <th>ste_c_e_final</th>\n      <th>alpha</th>\n      <th>RMSE_train</th>\n      <th>MAE_train</th>\n      <th>RMSE_test</th>\n      <th>MAE_test</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.5</td>\n      <td>0.01</td>\n      <td>1</td>\n      <td>4.370498</td>\n      <td>0.5</td>\n      <td>0.01</td>\n      <td>0.5</td>\n      <td>0.024327</td>\n      <td>0.5</td>\n      <td>10.0</td>\n      <td>0.5</td>\n      <td>0.020389</td>\n      <td>0.5</td>\n      <td>5.643766</td>\n      <td>0.5</td>\n      <td>4.626665</td>\n      <td>0.5</td>\n      <td>8.647760</td>\n      <td>0.5</td>\n      <td>0.853270</td>\n      <td>0.5</td>\n      <td>0.022386</td>\n      <td>0.5</td>\n      <td>0.681521</td>\n      <td>0.0001</td>\n      <td>0.155852</td>\n      <td>0.102469</td>\n      <td>1.790423</td>\n      <td>1.398627</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.5</td>\n      <td>0.01</td>\n      <td>5</td>\n      <td>4.365885</td>\n      <td>0.5</td>\n      <td>0.01</td>\n      <td>0.5</td>\n      <td>0.027797</td>\n      <td>0.5</td>\n      <td>10.0</td>\n      <td>0.5</td>\n      <td>0.016347</td>\n      <td>0.5</td>\n      <td>5.577185</td>\n      <td>0.5</td>\n      <td>1.048910</td>\n      <td>0.5</td>\n      <td>1.740676</td>\n      <td>0.5</td>\n      <td>0.116323</td>\n      <td>0.5</td>\n      <td>0.012648</td>\n      <td>0.5</td>\n      <td>0.190271</td>\n      <td>0.0001</td>\n      <td>0.155840</td>\n      <td>0.102556</td>\n      <td>1.790531</td>\n      <td>1.398135</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.5</td>\n      <td>0.01</td>\n      <td>9</td>\n      <td>4.287190</td>\n      <td>0.5</td>\n      <td>0.01</td>\n      <td>0.5</td>\n      <td>0.043575</td>\n      <td>0.5</td>\n      <td>10.0</td>\n      <td>0.5</td>\n      <td>0.011928</td>\n      <td>0.5</td>\n      <td>5.677144</td>\n      <td>0.5</td>\n      <td>2.380979</td>\n      <td>0.5</td>\n      <td>4.385770</td>\n      <td>0.5</td>\n      <td>0.431194</td>\n      <td>0.5</td>\n      <td>0.010566</td>\n      <td>0.5</td>\n      <td>0.510186</td>\n      <td>0.0001</td>\n      <td>0.155844</td>\n      <td>0.102517</td>\n      <td>1.789339</td>\n      <td>1.397825</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\nfor cha_c_n in cha_c_ns:\n  model,para_list = gpr_model(cha_c_n = cha_c_n)\n  model.fit(train.graphs, train[target], repeat=3, verbose=False)\n  mu = model.predict(train.graphs)\n  MAE_train = np.mean(np.abs(train[target] - mu))\n  RMSE_train = np.std(train[target] - mu)\n  para_list.append(RMSE_train)\n  para_list.append(MAE_train)\n  mu_test = model.predict(test.graphs)\n  MAE_test = np.mean(np.abs(test[target] - mu_test))\n  RMSE_test = np.std(test[target] - mu_test)\n  para_list.append(RMSE_test)\n  para_list.append(MAE_test)\n  data = pd.DataFrame(data = [para_list],\\\n            columns=['aro_c_n','ato_c_n','cha_c_n','chi_c_n','hco_c_n',\\\n            'hyb_c_n','ring_c_n','aro_c_e','con_c_e','ord_c_e','ring_c_e',\\\n            'ste_c_e','alpha','RMSE_train', 'MAE_train', 'RMSE_test', 'MAE_test'])\n  exhaust_search_results = exhaust_search_results.append(data,ignore_index=True)\n```\n\n\n```\nfor chi_c_n in chi_c_ns:\n  model,para_list = gpr_model(chi_c_n = chi_c_n)\n  model.fit(train.graphs, train[target], repeat=3, verbose=False)\n  mu = model.predict(train.graphs)\n  MAE_train = np.mean(np.abs(train[target] - mu))\n  RMSE_train = np.std(train[target] - mu)\n  para_list.append(RMSE_train)\n  para_list.append(MAE_train)\n  mu_test = model.predict(test.graphs)\n  MAE_test = np.mean(np.abs(test[target] - mu_test))\n  RMSE_test = np.std(test[target] - mu_test)\n  para_list.append(RMSE_test)\n  para_list.append(MAE_test)\n  data = pd.DataFrame(data = [para_list],\\\n            columns=['aro_c_n','ato_c_n','cha_c_n','chi_c_n','hco_c_n',\\\n            'hyb_c_n','ring_c_n','aro_c_e','con_c_e','ord_c_e','ring_c_e',\\\n            'ste_c_e','alpha','RMSE_train', 'MAE_train', 'RMSE_test', 'MAE_test'])\n  exhaust_search_results = exhaust_search_results.append(data,ignore_index=True)\n```\n\n\n```\n\n```\n", "meta": {"hexsha": "72840618240ea559af11908fa0d307e370c7dfa8", "size": 496493, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Docking_0620_2.ipynb", "max_stars_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_stars_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Docking_0620_2.ipynb", "max_issues_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_issues_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Docking_0620_2.ipynb", "max_forks_repo_name": "ChrizZhuang/marginalized_graph_kernel_protein", "max_forks_repo_head_hexsha": "5c0d0c36f66be174521b86fb11d53933dfa6bc1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 125.5990387048, "max_line_length": 24654, "alphanum_fraction": 0.7327817311, "converted": true, "num_tokens": 71796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771241500058, "lm_q2_score": 0.047425871158012764, "lm_q1q2_score": 0.016033602131409662}}
{"text": "```python\nfrom sympy import *\ninit_printing()\nalpha, beta, gamma = symbols('alpha beta gamma')\n```\n\n\n```python\nalpha , beta , gamma\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "b1895c1e2f82c15d74b452c36289825ef9971cfd", "size": 2636, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "python/transformation_Jupyter.ipynb", "max_stars_repo_name": "silvajhonatan/robotics", "max_stars_repo_head_hexsha": "d1097809e88c744658dab6d661092b6ea8f0e13a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-11-16T18:34:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-28T15:33:46.000Z", "max_issues_repo_path": "python/transformation_Jupyter.ipynb", "max_issues_repo_name": "sjhonatan/robotics", "max_issues_repo_head_hexsha": "d1097809e88c744658dab6d661092b6ea8f0e13a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/transformation_Jupyter.ipynb", "max_forks_repo_name": "sjhonatan/robotics", "max_forks_repo_head_hexsha": "d1097809e88c744658dab6d661092b6ea8f0e13a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1466666667, "max_line_length": 1316, "alphanum_fraction": 0.7132018209, "converted": true, "num_tokens": 42, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.03622005235381276, "lm_q1q2_score": 0.01599741938843858}}
{"text": "```python\n# librer\u00edas\nimport math\nimport numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import OneHotEncoder\nimport seaborn as sns\nimport sys\nimport matplotlib.pyplot as plt\nimport adds\nimport pprint\n```\n\n\n```python\n# or implied, of Diego Navarro Mell\u00e9n.\n\nfrom __future__ import print_function\n\n\n# Special END separator\nEND = '0e8ed89a-47ba-4cdb-938e-b8af8e084d5c'\n\n# Text attributes\nALL_OFF = '\\033[0m'\nBOLD = '\\033[1m'\nUNDERSCORE = '\\033[4m'\nBLINK = '\\033[5m'\nREVERSE = '\\033[7m'\nCONCEALED = '\\033[7m'\n\n# Foreground colors\nFG_BLACK = '\\033[30m'\nFG_RED = '\\033[31m'\nFG_GREEN = '\\033[32m'\nFG_YELLOW = '\\033[33m'\nFG_BLUE = '\\033[34m'\nFG_MAGENTA = '\\033[35m'\nFG_CYAN = '\\033[36m'\nFG_WHITE = '\\033[37m'\n\n# Background colors\nBG_BLACK = '\\033[40m'\nBG_RED = '\\033[41m'\nBG_GREEN = '\\033[42m'\nBG_YELLOW = '\\033[43m'\nBG_BLUE = '\\033[44m'\nBG_MAGENTA = '\\033[45m'\nBG_CYAN = '\\033[46m'\nBG_WHITE = '\\033[47m'\n\n\nclass pretty_output():\n    '''\n    Context manager for pretty terminal prints\n    '''\n\n    def __init__(self, *attr):\n        self.attributes = attr\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, type, value, traceback):\n        pass\n\n    def write(self, msg):\n        style = ''.join(self.attributes)\n        print('{}{}{}'.format(style, msg.replace(END, ALL_OFF + style), ALL_OFF))\n\n\nif __name__ == '__main__':\n\n    with pretty_output(FG_RED) as out:\n        out.write('This is a test in RED')\n\n    with pretty_output(FG_BLUE) as out:\n        out.write('This is a test in BLUE')\n\n    with pretty_output(BOLD, FG_GREEN) as out:\n        out.write('This is a bold text in green')\n\n    with pretty_output(BOLD, BG_GREEN) as out:\n        out.write('This is a text with green background')\n\n    with pretty_output(FG_GREEN) as out:\n        out.write('This is a green text with ' + BOLD + 'bold' + END + ' text included')\n\n    with pretty_output() as out:\n        out.write(BOLD + 'Use this' + END + ' even with ' + BOLD + FG_RED + 'no parameters' + END + ' in the with statement')\n```\n\n    \u001b[31mThis is a test in RED\u001b[0m\n    \u001b[34mThis is a test in BLUE\u001b[0m\n    \u001b[1m\u001b[32mThis is a bold text in green\u001b[0m\n    \u001b[1m\u001b[42mThis is a text with green background\u001b[0m\n    \u001b[32mThis is a green text with \u001b[1mbold\u001b[0m\u001b[32m text included\u001b[0m\n    \u001b[1mUse this\u001b[0m even with \u001b[1m\u001b[31mno parameters\u001b[0m in the with statement\u001b[0m\n\n\n# Implementaci\u00f3n de los m\u00e9todos\n\n\n\n\nEn este notebook se plantea la soluci\u00f3n del problema utilizando los siguiente m\u00e9todos: Newton, Broyden-Fletcher-Goldfarb-Shanno  (BFGS) y el gradiente descendente estoc\u00e1stico (SGD). El presente notebook es autocontenido, sin embargo, la implementaci\u00f3n principal se realiza con un enfoque modular.\n\nA continuaci\u00f3n, se describe el conjunto de datos que se emplear\u00e1n y se define el planteamiento del problema. Una explicaci\u00f3n m\u00e1s detallada se realiza en el informe (en formato PDF) de este proyecto.\n\n**Nota:** Esta implementaci\u00f3n se basa en material y actividades impartidas por los profesores de los cursos de [M\u00e9todos Num\u00e9ricos y optimizaci\u00f3n](https://github.com/ITAM-DS/analisis-numerico-computo-cientifico/blob/master/temas/IV.optimizacion_convexa_y_machine_learning/4.3.Regresion_logistica_R.ipynb) (2010-I) (Prof. Erick Palacios Moreno) y Aprendizaje de M\u00e1quina (2019-II) (Prof. Rodrigo Mendoza Smith).\n\n\n## Problema de regresi\u00f3n Log\u00edstica\n\nComo es resaltado por Murphy (2012), el problema de regresi\u00f3n log\u00edstica es una generalizaci\u00f3n del problema de regresi\u00f3n lineal, convirtiendolo hacia un problema de clasificaci\u00f3n, siempre y cuando la variable de respuesta sea de car\u00e1cter binario (i.e. $y\\in\\left\\{ 0,1\\right\\} $), y por tanto se pueda asumir que sigue una distribuci\u00f3n Bernoulli. En este caso, dicha variable de respuesta corresponde a si el paciente muere a casua del virus del \u00e9bola $(1)$, o no $(0)$. \n\nDado lo anterior, utilizamos:\n\n$$\n{Pr[y\\mid\\boldsymbol{x,w}]=Ber(y\\mid\\mu(x))}\\label{eq:dist_ber}\n$$\n\ndonde la media, se define en t\u00e9rminos de la probabilidad de que el\npaciente muera, es decir, $\\mu(x)=E\\left[y\\mid x\\right]=p\\left(y=1\\mid x\\right)$.\nDonde el conjunto de variables explicativas est\u00e1 representado por\n$x$.\n\nPor otro lado, para la realizaci\u00f3n del computo de la media, se utiliza\nla funci\u00f3n sigmoide, $\\sigma(x)$, la cual garantiza que dada una\ncombinaci\u00f3n lineal de las variables explicativas, con los par\u00e1metros\ndel modelo (i.e. $\\beta^{T}x$), se cumpla que $0\\leq\\mu(x)\\leq1$:\n\n$$\n\\mu\\left(x\\right)=\\sigma\\left(\\beta^{T}x\\right)\\label{eq:mu_x}\n$$\n\ndonde $\\sigma$ est\u00e1 definida por:\n\n\\begin{equation}\n\\sigma(x)=\\frac{1}{1+\\exp(-x)}=\\frac{e^{x}}{e^{x}+1}\\label{eq:sigmoide} \n\\end{equation}\n\nLos resultados asociados a la ecuaci\u00f3n $\\mu(x)$ est\u00e1n dados\nen t\u00e9rminos de probabilidades. As\u00ed, es necesario definir un umbral clasificatorio para definir si el modelo predice que el paciente fallezca, o no. En este ejercicio, como se hace usualmente, y como realizan Colubri et. al (2019), se toma como umbral el valor de $0.5$. Es decir:\n\n$$\n\\hat{y}=\\left\\{\n\\begin{array}{@{}ll@{}}\n0, & \\text{si}\\ \\sigma(\\hat{\\beta}^Tx)  < 0.5 \\\\\n1, & \\text{si} \\ \\sigma(\\hat{\\beta}^Tx) \\geq 0.5\n\\end{array}\\right. \\label{eq:umbral}\n$$\n\nLos par\u00e1metros asociados a las variables regresoras, $\\hat{\\beta}$, son estimados con el conjunto de datos de entrenamiento. \n\n### Funci\u00f3n de p\u00e9rdida\n\nLa funci\u00f3n de p\u00e9rdida asociada a este problema es la log-verosimilitud\nnegativa, o entrop\u00eda cruzada, definida de las siguiente forma:\n\n\n$$\nLVN(\\beta)=-\\sum_{i=1}^{N}\\left[y_{i}log\\mu_{i}+(1-y_{i})log(1-\\mu_{i})\\right]\\label{eq:lvn2}\n$$\n\n**Este problema no tiene soluci\u00f3n anal\u00edtica**. Es por esta raz\u00f3n que para minimizar\nla funci\u00f3n de p\u00e9rdida en torno a $\\beta$ es requerido **utilizar m\u00e9todos de optimizaci\u00f3n num\u00e9rica**. \n\nEl c\u00f3digo asociado a estos componentes se pone a continuaci\u00f3n:\n\n\n```python\ndef clasifica(X, beta_hat,limit=0.5):\n    '''\n    \n    Funci\u00f3n que clasifica la ocurrencia de probabilidades en dos grupos.\n    \n    Emplea el par\u00e1metro l\u00edmite para delimitar si se clasifica en el grupo 0 o 1.\n    \n        ** Par\u00e1metros:\n        \n            - X (mat): matriz de mxp entradas\n            \n            - beta_hat (array): optimized parameter\n            \n            - limit (float64): 0<limit<1: Threshold for each classification\n            \n        \n        ** Salidas:\n        \n            - yhat: array of classifed data\n    '''\n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    if type(X) is not np.ndarray or type (beta_hat) is not np.ndarray:\n        sys.exit('Error: X y beta_hat deben ser de tipo numpy.ndarray')\n    if limit > 1 or limit < 0:\n        sys.exit('Error:  limit es un param\u00e9tro que debe estar entre 0 y 1')       \n    \n    mu = calc_mu(X,beta_hat)\n    yhat = mu\n    yhat[mu<limit] = 0\n    yhat[mu>=limit] = 1\n    return yhat\n\ndef sigmoide(z):\n    '''\n    Funci\u00f3n que devuelve el sigmoide de un vector\n        - Par\u00e1metros:\n            -- z (vec): vector num\u00e9rico de m entradas\n        - Salidas\n            -- sig (vec): vector n\u00famerico de m entradas, cada entrada tiene \n                         un valor entre -1 y 1\n    '''\n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    if type(z) is not np.ndarray:\n        sys.exit('Error: la entrada debe ser de tipo numpy.ndarray')\n        \n    sig = 1/(1+ np.exp(-z))\n    \n    return sig\n    \ndef calc_mu(X,beta):\n    '''\n    Funci\u00f3n que calcula la media para una variable aleatoria con distribuci\u00f3n bernoulli.\n        - Par\u00e1metros:\n            -- X (mat): matriz de mxp entradas\n            -- beta (vec): vector con p entradas\n        - Salidas\n            -- mu (vec): vector de m entradas\n    '''\n    a = np.matmul(beta,np.transpose(X))\n    mu = sigmoide(a)\n\n    return mu\n    \ndef f(X,y,beta):\n    '''\n    \n    Funci\u00f3n que computa la log-verosimilitud negativa\n    \n        - Par\u00e1metros:\n    \n            -- X (mat): matriz de mxp entradas\n\n            -- y (vec): vector de de m entradas de la variable output\n\n            -- beta (vec): vector de p entradas\n\n        - Salidas\n    \n            -- lvn (int): log-verosimilitud negativa\n    '''\n    \n    \n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    m,p = X.shape\n    if y.shape[0]!= m:\n        sys.exit('Error:  El n\u00famero de renglones de X debe ser igual al n\u00famero de entradas del vector y.')\n    if beta.shape[0]!= p:\n        sys.exit('Error:  El n\u00famero de columnas de X debe ser igual al n\u00famero de entradas del vector beta.')\n\n    prob = calc_mu(X,beta)\n    # Log-verosimilitud negativa \n    lvn = -sum(y*np.log(prob)+(1-y)*(np.log(1-prob)))\n    return lvn\n```\n\n## Conjunto de datos\n\nPor la restricciones de uso de la base de datos de entrenamiento original (adem\u00e1s de una serie de requerimientos protocolares como contar con la aprobaci\u00f3n de un Comit\u00e9 de \u00c9tica Independiente), optamos por trabajar con una de las dos bases de datos que los autores emplearon para validar sus modelos: KGH. La base de datos en menci\u00f3n, consta de $106$ casos positivos  de  pacientes  con  \u00e9bola  y  un  case fatality rate global por encima del setenta por ciento.  Originalmente,  previo  al tratamiento de los datos, la base ten\u00eda \u00fanicamente $44$ registros de triaje, $58$ registros de carga viral, con un total de 78 valores faltantes en todo el data set. Para  harmonizar  los  datos,  los  autores  transformaron  la  carga  viral  en  CT,  conforme  con  la curva est\u00e1ndar qPCR:\n\n$$log_{(carga \\; viral)} = m*CT + c_0$$\n\nNosotros, para fines del presente trabajo, empleamos una de las versiones imputadas de esta base de datos, dispuesta en el siguiente sitio: [ebola-imc-public](https://github.com/dapivei/ebola-imc-public/blob/master/data/kenema/test/pres-kgh/imputation-50.csv), misma que cuenta con $11$ variables: la variable output, $y_{i}$ asociada a la supervivencia o no del paciente ${i}$ con virus del \u00e9bola, y ${j}$ variables explicativas asociadas, $x_{i,j}$. Los regresores escogidos son aquellos que, conforme con nuestra principal referencia, son buenos predictores de la probabilidad de muerte o no de un paciente. \n\n|Tipo| Nombre|Descripci\u00f3n|\n|---| --- | --- |\n|Variable Num\u00e9rica| CT |El cycle threshold (CT) es una variable que se calcula a partir de una relaci\u00f3n m\u00e9dica bien conocida (qPCR) y la carga viral (una expresi\u00f3n n\u00famerica de la cantidad de virus dado un vol\u00famen de fluido que normalmente se correlaciona con la severidad de una infecci\u00f3n viral activa).|\n|Variable Num\u00e9rica|TEMP|Temperatura corporal del paciente. Toma valores de $36$ a $39.9$.|\n|Variable Num\u00e9rica|_AGE_ |Edad del paciente. Toma valores de $1$ a $73$.|\n|Variable Categ\u00f3rica |_HEADCH_ | Presencia o no dolores de cabeza. Toma valores valores $0$ o $1$, dependiendo de si el paciente presenta o no dolores de cabeza.|\n|Variable Categ\u00f3rica |  _BLEED_ | Presencia o no de sangrado. Toma valores valores $0$ o $1$, dependiendo de si el paciente presenta o no sangrado. |\n|Variable Categ\u00f3rica |  _DIARR_ | Presencia o no de diarrea. Toma valores valores $0$ o $1$, dependiendo de si el paciente presenta o no diarrea.|\n|Variable Categ\u00f3rica | _VOMIT_ | Dificultad para comer, conocido como disfagia, t\u00e9rmino t\u00e9cnico para describir el s\u00edntoma consistente en dificultad para la degluci\u00f3n (problemaspara  tragar).   Esta  dificultad  suele  ir  acompa\u00f1ada  de  dolores,  a  veces lancinantes (disfagia dolorosa u odinofagia .  Toma valores valores $1$ o $0$, dependiendo de si el paciente presenta o no de disfacia\n|Variable Categ\u00f3rica | _PABD*_ | Presencia o no de PADB.\n|Variable Categ\u00f3rica |_WEAK_ | Presencia o no de debilidad o fatiga general.|\n|Variable Categ\u00f3rica |_JAUN_ |Condici\u00f3n  en la cu\u00e1l la piel, los ojos y los miembros mucosos que vuelven amarillos debido a altos niveles de bilirubina. Toma valores valores $0$ o $1$, dependiendo de si el paciente presenta o no ictericia.|\n|Variable Categ\u00f3rica |_OUT_| Muerte o no muerte del paciente.  Toma valores $1$ o $0$.  Dependiendo desi el paciente muere o no muere.|\n\n\n*: _PABD_ se refiere a Donaci\u00f3n de sangre aut\u00f3loga -personas en donde los trasplantes y las transfusiones la misma persona es a la vez donante y receptora- preoperatoria, Preoperative Autologous Blood Donation)\n\n\n\n---------------------\n\n## Importaci\u00f3n y exploraci\u00f3n del conjunto de datos\n\nEn esta secci\u00f3n se importa y transforma los datos, con el fin de obtener el conjunto $\\mathcal{D}$.\n\n\n```python\nurl=\"https://raw.githubusercontent.com/afcarl/ebola-imc-public/master/data/kenema/test/pres-kgh/imputation-50.csv\"\ndf_raw=pd.read_csv(url,sep=\",\")\n```\n\n\n```python\ndf_raw.head()\n# df[df.isnull().any(axis=1)] - no hay NAs\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>OUT</th>\n      <th>CT</th>\n      <th>AGE</th>\n      <th>TEMP</th>\n      <th>HEADCH</th>\n      <th>BLEED</th>\n      <th>DIARR</th>\n      <th>JAUN</th>\n      <th>VOMIT</th>\n      <th>PABD</th>\n      <th>WEAK</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>28.652450</td>\n      <td>42.0</td>\n      <td>36.3</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>25.736016</td>\n      <td>45.0</td>\n      <td>36.5</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1</td>\n      <td>20.747653</td>\n      <td>65.0</td>\n      <td>38.0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1</td>\n      <td>22.736993</td>\n      <td>44.0</td>\n      <td>38.6</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1</td>\n      <td>20.846284</td>\n      <td>11.0</td>\n      <td>38.4</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# verificar tipo de variables \ndf_raw.dtypes\n```\n\n\n\n\n    OUT         int64\n    CT        float64\n    AGE       float64\n    TEMP      float64\n    HEADCH      int64\n    BLEED       int64\n    DIARR       int64\n    JAUN        int64\n    VOMIT       int64\n    PABD        int64\n    WEAK        int64\n    dtype: object\n\n\n\n\n```python\n# Resumen de las variables\ndf_raw.describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>OUT</th>\n      <th>CT</th>\n      <th>AGE</th>\n      <th>TEMP</th>\n      <th>HEADCH</th>\n      <th>BLEED</th>\n      <th>DIARR</th>\n      <th>JAUN</th>\n      <th>VOMIT</th>\n      <th>PABD</th>\n      <th>WEAK</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>106.000000</td>\n      <td>106.000000</td>\n      <td>106.000000</td>\n      <td>106.000000</td>\n      <td>106.000000</td>\n      <td>106.000000</td>\n      <td>106.000000</td>\n      <td>106.0</td>\n      <td>106.000000</td>\n      <td>106.000000</td>\n      <td>106.000000</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>0.764151</td>\n      <td>25.720411</td>\n      <td>34.102170</td>\n      <td>37.256604</td>\n      <td>0.603774</td>\n      <td>0.066038</td>\n      <td>0.405660</td>\n      <td>0.0</td>\n      <td>0.207547</td>\n      <td>0.273585</td>\n      <td>0.500000</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>0.426545</td>\n      <td>5.869164</td>\n      <td>17.382844</td>\n      <td>1.030767</td>\n      <td>0.491436</td>\n      <td>0.249528</td>\n      <td>0.493352</td>\n      <td>0.0</td>\n      <td>0.407477</td>\n      <td>0.447916</td>\n      <td>0.502375</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>0.000000</td>\n      <td>12.100000</td>\n      <td>0.830000</td>\n      <td>36.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>1.000000</td>\n      <td>22.149857</td>\n      <td>22.000000</td>\n      <td>36.300000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>1.000000</td>\n      <td>25.236301</td>\n      <td>35.500000</td>\n      <td>37.250000</td>\n      <td>1.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.500000</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>1.000000</td>\n      <td>28.680924</td>\n      <td>45.000000</td>\n      <td>38.225000</td>\n      <td>1.000000</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n      <td>0.0</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>1.000000</td>\n      <td>39.799999</td>\n      <td>80.000000</td>\n      <td>39.900000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>0.0</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf_raw_cat = df_raw.copy()\n\ncat_vars = ['OUT', 'HEADCH', 'BLEED', 'DIARR', 'JAUN', 'VOMIT',\n       'PABD', 'WEAK']\nfor var in cat_vars:\n    df_raw_cat[var] = df_raw_cat[var].astype('category')\ndf_raw_cat.dtypes\n\n```\n\n\n\n\n    OUT       category\n    CT         float64\n    AGE        float64\n    TEMP       float64\n    HEADCH    category\n    BLEED     category\n    DIARR     category\n    JAUN      category\n    VOMIT     category\n    PABD      category\n    WEAK      category\n    dtype: object\n\n\n\n\n```python\ndf_raw_cat.describe()\n```\n\n\n```python\n# Describe categorical data\ndf_proc_cat = df_raw_cat.select_dtypes(include=['category']).copy()\ndf_proc_cat.describe()\n```\n\n\n```python\ncat_vars = cat_vars[1:]\n\nfor i, col_val in enumerate(cat_vars):\n    sns.catplot(x = col_val, y = None, hue= None, col=\"OUT\",\n                data=df_proc_cat, kind=\"count\",\n                height=3, aspect=2);\n\n```\n\n**Algunas observaciones sobre los datos**\n\n- El case fatality rate (OUT) de nuestra base de datos se sit\u00faa en 76 por ciento. Es decir, del total de pacientes con \u00e9bola, 81 murieron.\n\n- Para este conjunto de datos la variable `JAUN` no tiene variabilidad, por lo tanto no es una variable, y se omite.\n\n\nDado lo anterior, se ajusta el set de datos:\n\n- Se crean 3 grupos de edades, utilizando el percetil 25 (22 a\u00f1os), percentil 50 (36 a\u00f1os) y percentil 75 (45 a\u00f1os).\n\n- Se elimina la columna `JAUN`.\n\n## Transformaciones al conjunto de datos\n\n\n```python\n# ajustes en df_raw \ndf_proc = df_raw\ndf_proc['INTER_AGE'] = \"NA\"\n\ndf_proc.dtypes\n```\n\n\n```python\n# ajustes en df_raw \ndf_proc = df_raw\n\n# para la variable edad se crean cuatro categor\u00edas\nage_p25 = math.ceil(df_proc['AGE'].quantile(.25))\nage_p50 = math.ceil(df_proc['AGE'].quantile(.50))\nage_p75 = math.ceil(df_proc['AGE'].quantile(.75))\n\ndf_proc['INTER_AGE'] = \"NA\"\ndf_proc.loc[(df_proc['AGE'] <= age_p25), 'INTER_AGE'] = 1\ndf_proc.loc[(df_proc['AGE'] > age_p25) & (df_proc['AGE'] <= age_p50), 'INTER_AGE'] = 2\ndf_proc.loc[(df_proc['AGE'] > age_p50) & (df_proc['AGE'] <= age_p75), 'INTER_AGE'] = 3\ndf_proc.loc[(df_proc['AGE'] > age_p75), 'INTER_AGE'] = 4\n\n## one hot encoding\nenc = OneHotEncoder(handle_unknown='ignore')\nenc_df = pd.DataFrame(enc.fit_transform(df_proc[['INTER_AGE']]).toarray())\nenc_df = enc_df.rename(columns={0: f\"hasta{age_p25}\", 1: f\"entre{age_p25+1}y{age_p50}\", 2: f\"entre{age_p50+1}y{age_p75}\", 3:f\"mayor{age_p75}\"})\n# merge with main df bridge_df on key values\ndf_proc = df_proc.join(enc_df)\n\n# se asignan como categoricas a las binarias, incluido el output\n#bin_vars = ['OUT', 'HEADCH', 'BLEED', 'DIARR', 'JAUN', 'VOMIT',\n#       'PABD', 'WEAK', 'INTER_AGE', f\"hasta{age_p25}\", f\"entre{age_p25+1}y{age_p50}\", f\"entre{age_p50+1}y{age_p75}\", f\"mayor{age_p75}\"]\n\n#esta asignacion hace que genera problemas al evaluar el sigmoide\n#for var in bin_vars:\n#    df_proc[var] = df_proc[var].astype('category')\n    \n# se omiten las variables JAUN, AGE, INTER_AGE\ndel_vars = [\"JAUN\", \"AGE\", \"INTER_AGE\"]\nfor var in del_vars:\n    df_proc = df_proc.drop(var, axis=1)    \n    \n# se comprueban los tipos de variable\ndf_proc.dtypes\n```\n\n\n```python\ndf_proc\n```\n\n## Planteamiento del problema de regresi\u00f3n\n\nPara los algoritmos a utilizar, es imprecindible la utilizaci\u00f3n del gradiente y la matriz hessiana asoaciados a $LVN(\\beta)$, los cuales se definen a continuaci\u00f3n:\n\n$$\n\\nabla LVN=\\frac{d}{d\\boldsymbol{\\beta}}f(\\boldsymbol{\\beta})=\\sum_{i}(\\mu_{i}-y_{i})x_{i}=X^{T}(\\mu-y)\\label{eq:gradiente}\n$$\n\n$$\n\\nabla^{2}LVN=\\frac{d}{d\\boldsymbol{\\beta}}g(\\boldsymbol{\\beta})^{T}=\\sum\\left(\\nabla_{\\beta}\\mu_{i}\\right)x_{i}^{T}=\\sum\\mu_{i}(1-\\mu_{i})x_{i}x_{i}^{T}=\\boldsymbol{X}^{T}\\boldsymbol{S}\\boldsymbol{X}\\label{eq:hessiana}\n$$\n\ndonde $\\boldsymbol{S}\\triangleq diag(\\mu_{i}(1-\\mu_{i}))$. Adicionalmente, como resalta Murphy (2012), dado que $\\boldsymbol{H}$ es positiva definida, entonces $LVN(\\beta)$ tiene un m\u00ednimo global que puede ser alcanzable utilizando m\u00e9todos de optimizaci\u00f3n.\n\n\n```python\ndef gradiente_f(X,y,beta):\n    '''\n    Funci\u00f3n que calcula el gradiente asociado la log-verosimilitud negativa del \n    problema de regresi\u00f3n log\u00edstica\n        ** Par\u00e1metros:\n            - X (mat): matriz de mxp entradas\n            - y (vec): vector de de m entradas de la variable output\n            - beta (vec): vector de p entradas\n        ** Salidas:\n            - grad (vec): vector de m entradas\n    '''\n        \n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    m,p = X.shape\n    if y.shape[0]!= m:\n        sys.exit('Error:  El n\u00famero de renglones de X debe ser igual al n\u00famero de entradas del vector y.')\n    if beta.shape[0]!= p:\n        sys.exit('Error:  El n\u00famero de columnas de X debe ser igual al n\u00famero de entradas del vector beta.')\n\n    mu = calc_mu(X,beta)    \n    grad = np.matmul(np.transpose(X), mu-y)    \n    return grad\n\n\ndef hessiana_f(X,y,beta):\n    '''\n    Funci\u00f3n que calcula la matriz Hessiana asociada a la log-verosimilitud negativa del \n    problema de regresi\u00f3n log\u00edstica\n        ** Par\u00e1metros:\n            - X (mat): matriz de mxp entradas\n            - y (vec): vector de de m entradas de la variable output\n            - beta (vec): vector de p entradas \n        ** Salidas\n            - hes (vec): vector de m entradas\n    '''\n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    m,p = X.shape\n    if y.shape[0]!= m:\n        sys.exit('Error:  El n\u00famero de renglones de X debe ser igual al n\u00famero de entradas del vector y.')\n    if beta.shape[0]!= p:\n        sys.exit('Error:  El n\u00famero de columnas de X debe ser igual al n\u00famero de entradas del vector beta.')\n\n    mu = calc_mu(X,beta)\n    S = np.diag(mu*(1-mu))\n    hes = np.matmul(np.transpose(X),np.matmul(S,X))\n    return hes\n\ndef normalize(x):\n    '''\n    Funci\u00f3n que normaliza un vector\n        ** Parametros:\n            - x: vector a normalizar\n        ** Salidas:\n            - norm : vector x normalizado\n    '''\n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    if type(x) is not np.ndarray:\n        sys.exit('Error: la entrada debe ser de tipo numpy.ndarray')\n         \n    norm = x/np.sqrt(sum(x*x))\n    return norm\n```\n\n### M\u00e9todo de m\u00e1ximo descenso\n\nEl m\u00e9todo de m\u00e1ximo descenso es el m\u00e9todo de b\u00fasqueda de l\u00ednea m\u00e1s\nsencillo, y plantea que la forma de encontrar el m\u00ednimo de una funci\u00f3n\n$f(\\beta_{k})$ es por medio de la b\u00fasqueda iterativa de $\\beta_{k}$\nsiguiendo la direcci\u00f3n negativa del gradiente asociado, i-.e. $-p^{T}\\nabla f_{k}$ (donde $\\nabla f_{k}$ es el gradiente de la funci\u00f3n $f$ con respecto\na $\\beta_{k}$. ). Cabe anotar que, como es resaltado por Nocedal, este supuesto est\u00e1\nbasado en el Teorema de Taylor, el cual establece que:\n\n$$\nf(\\beta_{k}+\\alpha_k p)\\approx f(\\beta_{k})+\\alpha_k p^{T}\\nabla f_{k}\n$$\n\ndonde $\\alpha_k$ es el paso del descenso o tasa de aprendizaje en la iteraci\u00f3n $k$. As\u00ed, en la ecuaci\u00f3n anterior\nla funci\u00f3n $f$ disminuye a una tasa de paso, multiplicada por el\ngradiente y el paso, y una direcci\u00f3n $p$, es decir: $p^{T}\\nabla f_{k}$.\nPor otro lado, dado que el gradiente es negativo se cumple que:\n\n$$\nf(\\beta_{k}+\\alpha_k p)<f(\\beta_{k})\\label{eq:condicion_desc}\n$$\n\n\nAdicional a lo anterior, es de vital importancia adicionar un componente\nal problema, correspondiente a la elecci\u00f3n de la tasa de aprendizaje,\n$\\alpha$, en la medida que, valores muy altos de la misma, pueden\nimpedir que haya convergencia hacia el m\u00ednimo y el algoritmo se estanque,\no que su convergencia sea demasiado lenta.\n\nAs\u00ed, como es presentado por Nocedal & Wright (2006) y Murphy (2012), el \u00faltimo componente\nque se requiere adicionar al problema de optimizaci\u00f3n planteado, y\nque a su vez lo convierte en un m\u00e9todo de b\u00fasqueda de l\u00ednea o minimizaci\u00f3n\nde l\u00ednea (line search), es elegir $\\alpha$\ntal que se minimice:\n\n$$\n\\varphi(\\alpha)=f(\\beta_{k}+\\alpha_k p)\\label{eq:cond_linesearch}\n$$\n\nEn el m\u00e9todo de descenso de gradiente, la forma de\nactualizar el vector de par\u00e1metros es como se define a continuaci\u00f3n:\n\n$$\n\\beta_{k+1}=\\beta_{k}-\\alpha\\nabla f_{k}\\label{eq:steepest_descent}\n$$\n\nDe esta forma dado un $\\beta_{0}$ inicial elegido aleatoriamente,\nla actualizaci\u00f3n de los pesos contin\u00faa hasta que $\\|\\nabla f_{k}\\|\\approx0$ \no hasta que un n\u00famero definido de iteraciones se alcance. \n\n### M\u00e9todo de Newton\n\nEl m\u00e9todo de Newton es parte la familia de m\u00e9todos de optimizaci\u00f3n\nde segundo orden, en la medida que tienen en cuenta la curvatura de\nla funci\u00f3n a optimizar, la cual es incorporada por la matriz Hessiana,\n$\\nabla^{2}f$. Lo anterior, implica un mayor costo en t\u00e9rminos de\nc\u00f3mputo con respecto al algoritmo de m\u00e1ximo descenso. Sin embargo,\nla existencia de dicha curvatura, en la mayor\u00eda de los problemas,\npermite lograr niveles de convergencia mucho m\u00e1s r\u00e1pido. \n\nEn particular, en este m\u00e9todo, la forma de actualizar el vector de\npar\u00e1metros es de la siguiente manera:\n\n$$\n\\beta_{k+1}=\\beta_{k}-\\alpha_{k}\\nabla^{2}f_{k}^{-1}\\nabla f_{k}\\label{eq:act_newton}\n$$\n\n### M\u00e9todo BFGS\n\nEl m\u00e9todo de propuesto por Broyden, Fletcher, Goldfarb and Shanno\n(BFGS) es un algoritmo quasi-newtoniano que aborda una soluci\u00f3n a\nlos problemas en los cuales es muy costoso el c\u00f3mputo de la matriz\nHessiana de $f_{k}$. Como es descrito por Murphy, este m\u00e9todo iterativamente\ncomputa una aproximaci\u00f3n de $\\nabla^{2}f_{k}$ a partir del gradiente,\n$\\nabla f_{k}$.\n\nDado lo anterior, la aproximaci\u00f3n de la matriz Hessiana se define\ncomo $H_{k}\\approx\\nabla^{2}f_{k}$, y se calcula con una funci\u00f3n\nde rango 2 dada por:\n\n\\begin{align}\nH_{k+1} & =H_{k}+\\frac{w_{k}(w_{k})^{T}}{(w_{k})^{T}z_{k}}-\\frac{H_{k}z_{k}(H_{k}z_{k})^{T}}{(z_{k})^{T}H_{k}z_{k}}\\label{eq:H}\\\\\nz_{k} & =\\beta_{k+1}-\\beta_{k}\\label{z}\\\\\nw_{k} & =\\nabla f_{k+1}-\\nabla f_{k}\\label{eq:w}\n\\end{align}\n\nComo es mencionado por Murphy (2012), por lo general el algoritmo se inicializa\ncon $H_{o}=I$.\n\n\n```python\ndef descent_direction(X, y, beta, method=\"max\",H=None):\n    '''\n    Funci\u00f3n que devuelve vector normalizado (px1) que apunta en la direccion de decenso\n        ** Par\u00e1metros:\n            - X (mat): matriz de mxp entradas\n            - y (vec): vector de de m entradas de la variable output\n            - beta (vec float64): vector de entradas a optimizar\n            - method (str): m\u00e9todo que determina la direcci\u00f3n de descenso\n    \n                    --Opciones:\n                            --- max: m\u00e9todo de descenso\n                            --- newton: m\u00e9todo de Newton\n                            --- bfsg: metodo bfsg\n            - H (mat pxp): Par\u00e1metro para la direcci\u00f3n de decenso del metodo bfgs\n    \n        ** Salidas\n            - pk (vec): vector normalizado con la direccion del paso\n    '''\n    if(method == \"max\"):\n        pk = gradiente_f(X,y,beta)\n    \n    elif(method == \"newton\"):\n        grad = gradiente_f(X,y,beta)\n        hess = hessiana_f(X,y,beta)\n        pk = np.linalg.solve(hess,grad)\n        \n    elif(method==\"bfsg\"):\n        # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n        if type(H) is not np.ndarray:\n            sys.exit('Error: H debe ser de tipo numpy.ndarray')\n        pk = np.matmul(H,gradiente_f(X,y,beta))\n                              \n    return - normalize(pk)\n\n```\n\n\n```python\ndef calc_H(X,y,beta,beta_new=None,H=None):\n    '''\n    Funci\u00f3n que actualiza los valores de la matriz H del metodo bfgs para cada iteracion\n        ** Parametros:\n            - X (mat): matriz de mxp entradas\n            - y (vec): vector de de m entradas de la variable output\n            - beta (array) - valor de cantidad a optimizar en la iteracion actual\n            - beta_new (array)- valore de la cantidad a optimizar despues de la actualizacion\n            - H (mat)- valor de la matriz H en la iteracion anterior\n        ** Salidas:\n            - H (mat): valor de la matriz para la siguiente iteracion       \n    '''\n    \n    w = gradiente_f(X,y,beta_new)- gradiente_f(X,y,beta)\n    z = beta_new-beta\n    Hz = np.matmul(H,z)\n    dotwz = np.dot(w,z)\n    dotzhz = np.dot(Hz,z)\n    H = H+(np.outer(w,w)/dotwz)-(np.outer(Hz,Hz)/dotzhz)\n   \n    return H\n```\n\n\n```python\ndef calc_lr(X, y, beta, lr, pk, c1=10**(-4), tao=0.5, reset_lr=False):\n    '''\n    Funci\u00f3n que calcula el tama\u00f1o del paso para cada iteraci\u00f3n utilizando la condicion de armijo.\n    La tasa de aprendizaje minima es la que tenia en el paso anterior.\n    \n        ** Par\u00e1metros:\n        \n            - X (mat): matriz de mxp entradas\n            - y (vec): vector de de m entradas de la variable output\n            - lr (float64): tasa de aprendizaje\n            - pk (array px1 float64): direccion de decenso\n            - c1 (float64) 0<c1<1: parametro de control\n            - tao (float64) 0<tao<1: parametro de decrecimiento de lr\n            \n        ** Salidas\n        \n            - lr (float64): tama\u00f1o de paso\n    '''\n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad    \n    if tao > 1 or tao < 0:\n        sys.exit('Error:  tao es un par\u00e1metro que debe estar entre 0 y 1')  \n    if c1 > 1 or c1 < 0:\n        sys.exit('Error:  c1 es un param\u00e9tro que debe estar entre 0 y 1') \n\n    # Inicializamos \n    tao = 0.9\n    max_iter = 100\n    iter = 0\n    \n    # Inicializa lr\n    if reset_lr==True: lr = 1\n\n    # Evaluaciones peri\u00f3dicas\n    grad = gradiente_f(X,y,beta)\n    eval_f = f(X,y, beta)\n    \n    # Primera iteracion\n    f_x =  f(X,y, beta + lr*pk) #en nocedal es phi(alpha)\n    f_x1 = eval_f + c1 * lr *  np.dot(grad,pk) # en nocedal es l(alhpa)\n    \n    while ((f_x > f_x1) & (iter < max_iter)):\n        lr = lr*tao\n        f_x =  f(X,y, beta + lr*pk) \n        f_x1 = eval_f + c1 * lr *  np.dot(grad,pk) \n        iter+=1\n    \n    return lr\n```\n\n\n```python\n# prueba\n# prueba\n# No esta funcionando bien\n# Longitud de paso con condiciones completas de wolf\n\ndef calc_lr_wolf(X, y, beta, lr, pk, c1=10**(-4), c2=0.9, tao=0.5, reset_lr=False):\n    '''\n    \n    Funci\u00f3n que calcula el tama\u00f1o del paso para cada iteraci\u00f3n utilizando la condicion de armijo.\n    \n    La tasa de aprendizaje minima es la que ten\u00eda en el paso anterior.\n    \n        ** Par\u00e1metros:\n            - X (mat): matriz de mxp entradas\n            - y (vec): vector de de m entradas de la variable output\n            - lr (float64): tasa de aprendizaje\n            - pk (array px1 float64): direccion de decenso\n            - c1 (float64) 0<c1<1: parametro de control\n            - tao (float64) 0<tao<1: parametro de decrecimiento de lr\n    \n        ** Salidas    \n            - lr (float64): tama\u00f1o de paso\n    '''\n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    if tao > 1 or tao < 0:\n        sys.exit('Error:  tao es un par\u00e1metro que debe estar entre 0 y 1')  \n    if c1 > 1 or c1 < 0:\n        sys.exit('Error:  c1 es un param\u00e9tro que debe estar entre 0 y 1') \n    #if pk >= 0 :\n    #    sys.exit('Error: pk debe ser negativo')\n        \n    # Inicializamos \n    tao = 0.5\n    max_iter = 50\n    iter = 0\n    \n    # Inicializa lr\n    if reset_lr==True: lr=1\n\n    # Evalauciones periodicas\n    grad = gradiente_f(X,y,beta)\n    eval_f = f(X,y, beta)\n    \n    # Primera iteracion\n    f_x =  f(X,y, beta + lr*pk) #en nocedal es phi(alpha)\n    f_x1 = eval_f + c1 * lr *  np.dot(grad,pk) # en nocedal es l(alhpa)\n    \n    gf_x = np.dot(gradiente_f(X,y, beta+lr*pk) , pk)\n    gf_x1 = c2* np.dot(grad, pk)\n    \n    while ((f_x>f_x1) & (gf_x<gf_x1) & (iter<max_iter)):\n        lr =lr*tao\n        f_x =  f(X,y, beta + lr*pk) \n        f_x1 = eval_f + c1 * lr *  np.dot(grad,pk) \n        \n        gf_x = np.dot(gradiente_f(X,y, beta+lr*pk) , pk)\n        #gf_x1 = c2* np.dot(grad, pk)\n    \n        \n        iter+=1\n    \n    return lr\n```\n\n\n```python\ndef gradient_descent(X, y, lr=1, tol=10**(-7), max_iter=10**5, method=\"max\", reset_lr=False, verbose_n=1000):\n    '''\n    Funci\u00f3n que devuelve vector de par\u00e1metros beta (px1) resultante del proceso\n    de optimizaci\u00f3n por descenso de gradiente\n    \n        ** Par\u00e1metros:\n            - X (mat): matriz de mxp entradas\n            - y (vec): vector de de m entradas de la variable output\n            - lr (float64): valor inicial de la tasa de aprendizaje\n            - tol (float64): criterio de convergencia\n            - max_iter (int): n\u00famero m\u00e1ximo de iteraciones\n            - method (str): m\u00e9todo que determina la direcci\u00f3n de descenso\n                Opciones:\n                    -- max: m\u00e9todo de descenso\n                    -- newton: m\u00e9todo de Newton\n                    -- bfsg\n        ** Salidas\n            - beta_new (vec): vector de p entradas con par\u00e1metros que minimizan la funci\u00f3n de p\u00e9rdida\n    '''\n    # imprime m\u00e9todo\n    out.write(BOLD + \"=\"*65)\n    if (method==\"max\"):\n        out.write(BOLD + 'M\u00e9todo de m\u00e1ximo descenso')\n    elif (method==\"newton\"):\n        out.write(BOLD + 'M\u00e9todo de Newton')\n    elif (method==\"bfsg\"):\n        out.write(BOLD + 'M\u00e9todo de BFGS')\n    out.write(BOLD + \"=\"*65)\n    \n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    m,p = X.shape\n    if y.shape[0]!= m:\n        sys.exit('Error:  El n\u00famero de renglones de X debe ser igual al n\u00famero de entradas del vector y.')\n\n    \n    # Inicializa\n    iteraciones=0\n    H = None\n    dims = X.shape[1]\n    tol = tol*dims\n    \n    # Inicializamos beta aleatoria\n    beta = np.random.normal(1,3,dims)\n    if method ==\"bfsg\": H = np.identity(dims)\n    \n    # Primera iteracion\n    pk =  descent_direction(X, y, beta, method,H)\n    beta_new = beta + lr*pk\n    if method == \"bfsg\": H=calc_H(X,y,beta,beta_new,H) \n    \n    # Condici\u00f3n de paro.\n    while ((np.linalg.norm(gradiente_f(X,y,beta_new)) > tol) & (iteraciones < max_iter)):\n        iteraciones+=1 #contador de ciclo\n        \n        beta = beta_new\n        pk =  descent_direction(X,y,beta,method,H)\n        lr = calc_lr(X, y, beta, lr, pk, reset_lr = reset_lr)\n        \n        beta_new = beta + lr*pk\n        \n        if method == \"bfsg\": H=calc_H(X,y,beta,beta_new,H)\n            \n        # Imprime\n\n        if iteraciones % verbose_n == 0:\n            grad=np.linalg.norm(gradiente_f(X,y,beta_new))\n            out.write(UNDERSCORE + f'Iteraci\u00f3n: {iteraciones}' + ALL_OFF + f' gradiente: {grad:.7E}, alpha: {lr:.4E}')            \n\n    print(\"\\n\") \n    out.write(BOLD  + '** Resultados Finales')\n    if iteraciones == max_iter:out.write(BOLD + 'El algoritmo paro porque' + BOLD + FG_RED + 'se alcanzo el nro. m\u00e1ximo de iteraciones.')\n    out.write(BOLD + f'* Total de iteraciones: ' +ALL_OFF+ f'{iteraciones}'  )\n    out.write(BOLD + f'* Norma del gradiente de f: ' +ALL_OFF+ f'{np.linalg.norm(gradiente_f(X,y,beta_new))}' )\n    out.write(BOLD + f'* beta_hat:' )\n    pprint.pprint(beta_new)\n    print(\"\\n\") \n    \n    return beta_new\n```\n\n## Split and Train\n\n\n```python\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\nnp.random.seed(3338014)\n    \ndata =df_proc.to_numpy()\ny = data[:,0]\nX = data[:,1:]\nx_train, x_test, y_train, y_test=train_test_split(X,y,test_size=.2)\n\n# Scale data\nscaler = MinMaxScaler()\nx_train = scaler.fit_transform(x_train)\nx_test = scaler.fit_transform(x_test)\n```\n\n\n```python\n%%time \nnp.random.seed(3338014) # para replicabilidad\nbeta_hat = gradient_descent(x_train,y_train,max_iter=10**6,reset_lr=False,verbose_n=500)\nyhat = clasifica(x_test,beta_hat)\n\nout.write(BOLD + f'* Error de clasificaci\u00f3n: ' + ALL_OFF + f'{round(100*sum(abs(y_test-yhat))/len(yhat),2)}%' )\nout.write(BOLD + \"=\"*65)\n```\n\n\n```python\n%%time\n# M\u00e9todo de Newton\nnp.random.seed(3338014) # para replicabilidad\nbeta_hat = gradient_descent(x_train,y_train, method=\"newton\",max_iter = 10**5,verbose_n = 20)\nyhat = clasifica(x_test,beta_hat)\n\nout.write(BOLD + f'* Error de clasificaci\u00f3n: ' + ALL_OFF + f'{round(100*sum(abs(y_test-yhat))/len(yhat),2)}%' )\nout.write(BOLD + \"=\"*65)\n```\n\n\n```python\n%%time\n# M\u00e9todo BFSG\nnp.random.seed(333814) # para replicabilidad\nbeta_hat = gradient_descent(x_train,y_train, method = \"bfsg\",max_iter = 10**6,lr=1,verbose_n = 10000)\nyhat = clasifica(x_test,beta_hat)\n\nout.write(BOLD + f'* Error de clasificaci\u00f3n: ' + ALL_OFF + f'{round(100*sum(abs(y_test-yhat))/len(yhat),2)}%' )\nout.write(BOLD + \"=\"*65)\n```\n\n## Descenso del gradiente estocastico\n\nCalculamos la funci\u00f3n de riesgo emp\u00edrico como la esperanza de la funcion de perdida evaluada sobre todos los puntos del dominio.\n\n$$L_{emp}=\\frac{1}{m} \\sum^{m}_{i=1} y_i log(\\mu_i) + (1-y_i) log(1-\\mu_i)$$  \n<br>\n$$ \\mu_i = (1+e^{-\\beta^T x_i})^{-1}= \\sigma(\\beta^T x_i)$$\n\nY el gradiente de la funci\u00f3n de riesgo esta dado por:\n\n$$\\nabla L=\\frac{dL}{d\\mu_i} =\\frac{1}{m} \\sum^{m}_{i=1} x_i(\\mu_i-y_i)$$\n\n\n```python\ndef riesgo_empirico(X,y,beta):\n    \n    '''\n    Funci\u00f3n que calcular el riesgo emp\u00edrico como la esperanza de la funci\u00f3n de p\u00e9rdida\n    \n    evaluada sobre todos los puntos del dominio.\n    \n        - Par\u00e1metros:\n            -- X (mat): matriz de mxp entradas\n    \n            -- y (vec): vector de de m entradas de la variable output\n            \n            -- beta (vec): vector con p entradas\n\n        - Salidas\n            \n            -- loss (float64): riesgo emp\u00edrico\n    '''\n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    m,p = X.shape\n    if y.shape[0]!= m:\n        sys.exit('Error:  El n\u00famero de renglones de X debe ser igual al n\u00famero de entradas del vector y.')\n    if beta.shape[0]!= p:\n        sys.exit('Error:  El n\u00famero de columnas de X debe ser igual al n\u00famero de entradas del vector beta.')\n\n\n    mu=calc_mu(X,beta)\n    loss=-sum(y*np.log(mu)+(1-y)*np.log(1-mu))\n    return loss\n\ndef gradiente_riesgo_empirico(X,y,beta):\n    \n    '''\n    Funci\u00f3n que calcular el gradiente de la funci\u00f3n de riesgo.\n    \n        - Par\u00e1metros:\n        \n            -- X (mat): matriz de mxp entradas.\n            \n            -- y (vec): vector de de m entradas de la variable output.\n            \n            -- beta (vec): vector con p entradas.\n\n        - Salidas\n            \n            -- grad_riesgo_emp (vec): vector de p entradas\n    '''\n    # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    m,p = X.shape\n    if y.shape[0]!= m:\n        sys.exit('Error:  El n\u00famero de renglones de X debe ser igual al n\u00famero de entradas del vector y.')\n    if beta.shape[0]!= p:\n        sys.exit('Error:  El n\u00famero de columnas de X debe ser igual al n\u00famero de entradas del vector beta.')\n\n    m = X.shape[0]\n    mu = calc_mu(X,beta)\n    grad_riesgo_emp = np.matmul(np.transpose(X),mu-y)/m\n    return grad_riesgo_emp\n```\n\n\n```python\nimport random\n\ndef batch(m,q=10):\n    \n    '''\n    \n    \n    \n    \n    '''\n    \n    \n    \n    index=np.random.randint(low=0,high=m,size=q)\n    return index\n\ndef error_train(X,y,beta):\n    prediction=clasifica(X,beta)\n    err=round(100*sum(abs(y-prediction))/len(prediction),2)\n    return err\n```\n\n\n```python\n\ndef SGD(X,y,batch_size,verbose_n=100,max_iter=10**5):\n    \n    '''\n    \n    \n    \n    '''\n\n     # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    m,p = X.shape\n    if y.shape[0]!= m:\n        sys.exit('Error:  El n\u00famero de renglones de X debe ser igual al n\u00famero de entradas del vector y.')\n\n\n    # Inicializa\n    m=X.shape[0]\n    epsilon = 10**(-6)\n    beta = np.random.normal(0,1,X.shape[1])    \n    step_size=.01\n    iteraciones = 0\n    epoca=0\n    ipe=int(m/batch_size)#iteraciones por epoca\n    \n    # Primera iteracion\n    index=batch(m,batch_size)\n    x_lote=X[index,:]\n    y_lote = y[index]\n    beta_new = beta - step_size * gradiente_riesgo_empirico(x_lote,y_lote,beta) \n    \n\n    perdida=riesgo_empirico(X,y,beta)\n    error=error_train(X,y,beta)\n    \n    # while ((np.linalg.norm(gradiente_f(X,y,beta_new)) > epsilon) & (iteraciones < max_iter)):\n    # while abs(f(X,y,beta) - f(X,y,beta_new)) > epsilon:\n    while iteraciones<max_iter:\n        iteraciones +=1\n        #print(\"iteraciones1=\",iteraciones)\n        beta = beta_new\n        #x_lote,y_lote = mini_lotes(X,y,q)\n        index=batch(m,batch_size)\n        x_lote=X[index,:]\n        y_lote = y[index]\n        beta_new = beta - step_size * gradiente_riesgo_empirico(x_lote,y_lote,beta)\n        #print(\"iteraciones2=\",iteraciones)\n        if iteraciones%10000==0:\n            epoca+=1\n            loss=riesgo_empirico(X,y,beta)\n            perdida=np.append(perdida,loss)\n            err=error_train(X,y,beta)\n            error=np.append(error, error_train(x_test,y_test,beta_hat))\n            print(f'loss:{loss:.4}, epoca:{epoca}, iter:{iteraciones}')\n        #print(\"iteraciones3=\",iteraciones)\n    print(\"N\u00ba DE INTERACIONES: \",iteraciones)\n    return beta_new,perdida,error\n```\n\n\n```python\ndef graf_loss_err(loss,error,title):\n    '''\n    Funci\u00f3n para graficar la p\u00e9rdida o riesgo em\u00edrico y el error\n    de entrenamiento en cada iterazaci\u00f3n.\n        - Entradas:\n                    -- loss\n                    -- error\n                    ---title\n        - Salidas:\n                    -- plot\n    '''\n    \n    x=np.arange(0,len(error))\n    fig, axs = plt.subplots(2, 1)\n    axs[0].plot(x, error)\n    axs[0].set_xlabel('Iteraciones')\n    axs[0].set_ylabel('Train error %')\n    axs[0].grid(True)\n    \n    axs[1].plot(x, loss)\n    axs[1].set_xlabel('Iteraciones')\n    axs[1].set_ylabel('Perdida')\n    axs[1].grid(True)\n    axs[0].set_title(title, fontsize=14)\n    \n    fig.tight_layout()\n    plt.show()\n    \n#graf_loss_err(loss[0,20],error[0:20],\"Batch size\")\n```\n\n\n```python\n%%time\nnp.random.seed(3338014) # para replicabilidad\n# M\u00e9todo de SGD\nfor batch_size in range(9,10):\n    \n    \n    print(\"*========================================================================*\")\n    print(\"Tama\u00f1o de minilote= \",batch_size)\n    beta_hat, loss, error = SGD(x_train, y_train, max_iter=10**5, batch_size=batch_size)\n    yhat = clasifica(x_test,beta_hat)\n    titulo=\"Batch size = \"+ str(batch_size)\n    graf_loss_err(loss,error,titulo)\n    print(\"beta_hat=\", beta_hat)\n    print(\"Error de clasificacion=\",round(100*sum(abs(y_test-yhat))/len(yhat),2),\"%\")\n    print(\"\\n\")\n```\n\n\n```python\ndef n_batch(m):\n    index=np.arange(0,m)\n    np.random.shuffle(index)\n    return index\n```\n\n\n```python\nimport multiprocessing\nimport time\nfrom dask.distributed import Client, progress\nclient = Client()\n```\n\n\n```python\nclient\n```\n\n\n```python\n# paso 1. Dividir el dominio en partes iguales\ncores = multiprocessing.cpu_count() # cpus disponibles\n#n_subint = int(density_p/p) # n\u00famero de puntos o nodos en cada core o cpu\n```\n\n\n```python\ndef construye_indices(ids,m,cores):\n    '''\n    Argumentos:\n    ----------\n    * ids: Identificador del core d\u00f3nde se est\u00e1 corriendo el task. \n    * m (array): Numero total de puntos de entrenamiento.\n    * cores (int) : N\u00famero de cores o cpus disponibles\n    \n    Salidas:\n    -------\n    * (index_from, index_to): Rango de indices que se seleccionan del verctor de permutaciones\n    '''\n    \n    tamano_int = int(m/cores) #tama\u00f1o de cada sub intervalo.\n    index_from = ids*tamano_int #construyen los subintervalo\n    index_to = index_from + tamano_int\n    if ids==(cores-1): index_to=m\n    return (index_from,index_to)\n\n\ndef evalua_gradiente(intervalo,perm,X,y,beta):\n    \"\"\"\n    Funci\u00f3n que eval\u00faa el gradiente del riesgo empirico para cada conjunto de indices de permutaciones    \n    Argumentos:\n    ----------\n    * intervalo: Intervalo de indices del vector perm a utilizar\n    * perm: Vector de permutaciones \n    * X: Puntos de entrenamiento\n    * y: Etiquetas de los puntos de entrenamiento\n    * beta: Vector de parametros a optimizar\n    \n    Salidas:\n    * Evaluacion del gradiente del riesgo empirico para un mini lote\n    --------\n\n    \"\"\"   \n    index=perm[intervalo[0]:intervalo[1]]\n    x_lote = X[index,:]\n    y_lote = y[index]\n    gradiente=gradiente_riesgo_empirico(x_lote,y_lote,beta) \n    return gradiente\n\n```\n\n\n```python\ndef SGD_paralelo(X,y,verbose_n=100,max_iter=10**5):\n    \n    '''\n    \n    \n    \n    '''\n\n     # Se revisa que los par\u00e1metros de entrada sean congruentes con la funcionalidad\n    m,p = X.shape\n    if y.shape[0]!= m:\n        sys.exit('Error:  El n\u00famero de renglones de X debe ser igual al n\u00famero de entradas del vector y.')\n\n\n    # Inicializa\n    m=X.shape[0]\n    epsilon = 10**(-6)\n    beta = np.random.normal(0,1,X.shape[1])    \n    step_size=.01\n    iteraciones = 0\n    epoca=0\n    \n    # Primera iteracion\n    perm=n_batch(m)\n    #calcula los indices\n    indices = client.map(construye_indices,range(cores),\n                **{'m':m,'cores':cores})\n\n    #evalua el gradiente en cada batch en paralelo\n    grad_riesgo_empirico=client.map(evalua_gradiente,indices,\n                **{'perm':perm,'X':X,'y':y,'beta':beta})\n\n    results=client.gather(grad_riesgo_empirico)\n    actualiza=sum(results)\n    \n    beta_new = beta - step_size * actualiza  \n    #gradiente_riesgo_empirico(x_lote,y_lote,beta) \n    \n    perdida=riesgo_empirico(X,y,beta)\n    error=error_train(X,y,beta)\n    \n    # while ((np.linalg.norm(gradiente_f(X,y,beta_new)) > epsilon) & (iteraciones < max_iter)):\n    # while abs(f(X,y,beta) - f(X,y,beta_new)) > epsilon:\n    while iteraciones<max_iter:\n        iteraciones +=1\n        beta = beta_new\n        perm=n_batch(m)\n        #calcula los indices\n        indices = client.map(construye_indices,range(cores),**{'m':m,'cores':cores})\n        #evalua el gradiente en cada batch en paralelo\n        grad_riesgo_empirico=client.map(evalua_gradiente,indices,\n                     **{'perm':perm,'X':X,'y':y,'beta':beta})\n        #gather results\n        results=client.gather(grad_riesgo_empirico)\n        actualiza=sum(results)\n        \n        beta_new = beta - step_size * actualiza\n        end_time = time.time()\n        \n        if iteraciones%100==0:\n            epoca+=1\n            loss=riesgo_empirico(X,y,beta)\n            perdida=np.append(perdida,loss)\n            err=error_train(X,y,beta)\n            error=np.append(error, error_train(x_test,y_test,beta_hat))\n            print(f'loss:{loss:.4}, epoca:{epoca}, iter:{iteraciones}')\n        #print(\"iteraciones3=\",iteraciones)\n    print(\"N\u00ba DE INTERACIONES: \",iteraciones)\n    return beta_new,perdida,error\n```\n\n\n```python\n%%time\n\n# M\u00e9todo de SGD\nfor batch_size in range(9,10):\n    \n    \n    print(\"*========================================================================*\")\n    #print(\"Tama\u00f1o de minilote= \",batch_size)\n    beta_hat, loss, error = SGD_paralelo(x_train, y_train, max_iter=10**4)\n    yhat = clasifica(x_test,beta_hat)\n    titulo=\"Batch size = \"+ str(batch_size)\n    graf_loss_err(loss,error,titulo)\n    print(\"beta_hat=\", beta_hat)\n    print(\"Error de clasificacion=\",round(100*sum(abs(y_test-yhat))/len(yhat),2),\"%\")\n    print(\"\\n\")\n```\n\n# Resultados del modelo log\u00edstico\n\nComo se mencion\u00f3 anteriormente, el problema de regresi\u00f3n log\u00edstica\nes una extensi\u00f3n del problema de regresi\u00f3n lineal, aplicada hacia\nun problema de clasificaci\u00f3n. En este sentido, la regresi\u00f3n log\u00edstica\nmodela las probabilidades de clasificaci\u00f3n de una variable dependiente\ndentro de dos posibles categor\u00edas, 0 y 1. \n\nLa probabilidad\nde que un paciente muera a causa del virus del \u00e9bola para este modelo\nse define de la siguiente forma:\n\n$$\nP\\left(y=1\\right)=\\frac{e^{\\beta^{T}x}}{1+e^{\\beta^{T}x}}\\label{eq:prob_y1a}\n$$\n\nLo que es equivalente a:\n\n$$\nP\\left(y=1\\right)=\\frac{e^{\\beta_{0}+\\beta_{1}x_{1}+\\ldots+\\beta_{p}x_{p}}}{1+e^{\\beta_{0}+\\beta_{1}x_{1}+\\ldots+\\beta_{p}x_{p}}}\\label{eq:prob_y1b}\n$$\n\n- Para este ejercicio, no estamos considerando el t\u00e9rmino equivalente al intercepto en el caso de regresi\u00f3n\nlineal (i.e $\\beta_{0}=0)$.\n\n- A diferencia de un modelo de regresi\u00f3n tradicional, en este caso los pesos no afectan de forma lineal las probabilidades.\n- Para lograr interpretabilidad en cuanto a las probabilidades, es necesario despejar el componente lineal de la ecuaci\u00f3n. \n\nEl t\u00e9rmino *logit* y corresponde al logaritmo del cociente entre la probabilidad de morir y la probabilidad de sobrevivir al virus (ratio de\nprobabilidades: l\u00ednea recta, dependiente del conjunto de covariables, $x$):\n\n$$\n\\lambda=\\log\\left\\{ \\frac{P\\left(y=1\\right)}{1-P\\left(y=1\\right)}\\right\\} =\\beta_{1}x_{1}+\\ldots+\\beta_{p}x_{p}\\label{eq:param_logit}\n$$\n\n\n- El modelo log\u00edstico, dada la naturaleza\ndicot\u00f3mica de la variable de salida del mismo no asume homocedasticidad.\n\n- La interpretaci\u00f3n de los resultados del modelo de regresi\u00f3n log\u00edstica \nse realiza en t\u00e9rminos del valor del ratio de probabilidades, que corresponde \nal operador exponencial de $\\lambda$. Dicho operador se lee como \nel indicador de variaci\u00f3n en el ratio de probabilidades como resultado del\ncambio en una unidad en la predicci\u00f3n.\n\n\nLos resultados para nuestro ejercicio implican:\n\n$$\nratio\\:probs=\\exp(\\log\\{-10.95x_{1}+18.88x_{2}-4.42x_{3}+1.14x_{4}+1.40x_{5}+4.76x_{6}-0.94x_{7}+3.006x_{8}+3.73x_{9}+4.45x_{10}+5.20x_{11}+6.38x_{12}\n$$\n\ndonde $x_{1},\\ldots,x_{12}$ corresponden a: cycle threshold,\ntemperatura, dolor de cabeza, sangrado, diarrea, v\u00f3mito, presencia\nde PABD, debilidad, edad hasta 22 a\u00f1os, edad entre 23 y 36 a\u00f1os, edad\nentre 37 y 45 a\u00f1os, y edad mayor a 45 a\u00f1os, respectivamente.\n\n- Se debe calcular un valor de referencia con el cual se pueda comparar. \n\nEn este sentido, tomaremos dicho valor para el caso en el cual la persona no tiene ninguna complicaci\u00f3n de salud adicional al virus del \u00e9bola, y su edad se encuentra en un rango de 0 a\u00f1os a 22 a\u00f1os\n\nEs decir que en la ecuaci\u00f3n anterior, se tiene $x_{i}=0$ para $i=3,4,5,6,7,8$\ny $x_{9}=1$:\n\n$$\nratio\\:probs=\\exp\\left(\\log\\left\\{ -10.95x_{1}+18.88x_{2}+3.73\\right\\} \\right)\n$$\n\nSi tomamos los valores promedio de cycle treshold $\\bar{x}_{1}$,\ny de temperatura, $\\bar{x}_{2}$ , tenemos lo siguiente:\n\n$$\nratio\\:probs_{0}=\\exp\\left(\\log\\left\\{ -10.95\\bar{x}_{1}+18.88\\bar{x}_{2}+3.73\\right\\} \\right)=\\exp\\left(\\log\\left\\{ -10.95(25.72)+18.88(37.25)+3.73\\right\\} \\right)=425.75\n$$\n\nPor otro lado, si quisi\u00e9ramos analizar, por ejemplo, cual es el efecto\nde que la persona tenga sangrado sobre la probabilidad de que la persona\nmuera por presencia del virus del \u00e9bola, debemos calcular el ratio\nde probabilidades ahora con $x_{4}=1$:\n\n$$\nratio\\:probs_{1}=\\exp\\left(\\log\\left\\{ -10.95\\bar{x}_{1}+18.88\\bar{x}_{2}+1.14+3.73\\right\\} \\right)=\\exp\\left(\\log\\left\\{ -10.95(25.72)+18.88(37.25)+1.14+3.73\\right\\} \\right)=426.8\n$$\n\n\nAhora, si calculamos el ratio entre $ratio\\:probs_{0}$ y $ratio\\:probs_{1}$, tenemos:\n\n$$\n\\frac{ratio\\:probs_{1}}{ratio\\:probs_{0}}=\\frac{426.89}{425.75}=1.0026\\label{eq:delt_odd}\n$$\n\n- Puesto que esta ecuaci\u00f3n es mayor a 1, esto indica que la probabilidad\nde la variable dependiente incrementa. \n- Una persona con edad de 0 a\u00f1os a 22 a\u00f1os que tiene \u00e9bola, tener sangrado, afecta positivamente su probabilidad de morir.\n\n\n\n### Calculo de probabilidades\n\n\n```python\nPor \u00falim\n```\n", "meta": {"hexsha": "c6d56f4d81bbdc4abc23553a26c938e0794d6192", "size": 75411, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/notebook_implementacion.ipynb", "max_stars_repo_name": "C1587S/MNO_numericalOptimization", "max_stars_repo_head_hexsha": "1d60d81b97bf7690ca1a7c1226fd1bcc82c5c049", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/notebook_implementacion.ipynb", "max_issues_repo_name": "C1587S/MNO_numericalOptimization", "max_issues_repo_head_hexsha": "1d60d81b97bf7690ca1a7c1226fd1bcc82c5c049", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2020-05-08T15:38:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-30T01:20:07.000Z", "max_forks_repo_path": "notebooks/notebook_implementacion.ipynb", "max_forks_repo_name": "C1587S/MNO_numericalOptimization", "max_forks_repo_head_hexsha": "1d60d81b97bf7690ca1a7c1226fd1bcc82c5c049", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-15T19:23:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T19:23:41.000Z", "avg_line_length": 37.630239521, "max_line_length": 791, "alphanum_fraction": 0.5084138919, "converted": true, "num_tokens": 16374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16451646289656313, "lm_q2_score": 0.096705783533576, "lm_q1q2_score": 0.015909693448584623}}
{"text": "## Summary \n\nAuthor: Trenton Bricken\n\n1. Plotting the text inputs that are put into GPT2 in order to try and infer it's empirical $\\beta$ values used.\n2. Running these texts through GPT2 to compute their Key and Query values and retrieve their dot product to infer the interval of input values that go into the Attention Softmax functions for all Attention heads across all layers.\n\ncd to this directory then: \npip install -e .\n\n### Sources used for the text inputs: \n* Alice and wonderland: https://gist.github.com/phillipj/4944029\n* reddit story 1: https://www.reddit.com/r/stories/comments/50yi2d/prettier_pt_3/\n* reddit story 2: https://www.reddit.com/r/stories/comments/ermiqv/i_will_never_take_a_shit_at_school_or_someones/\n* attention is all you need paper: https://arxiv.org/pdf/1706.03762.pdf\n* SDM book chapter: https://redwood.berkeley.edu/wp-content/uploads/2020/08/KanervaP_SDMrelated_models1993.pdf\n\n## 1. Pretty Plot of Text Inputs\n\n\n```python\n%load_ext autoreload\n%autoreload 2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import binom, norm\nfrom scipy.sparse import csc_matrix, coo_matrix, csr_matrix\nimport pandas as pd\nfrom scipy.integrate import quad\n#from sympy import *\nimport time\nfrom SDM_Circ_Inter_Funcs import *\nimport pickle\ndirectory = 'GPT2Outputs/'\n\ntexts = []\nwith open('text_inputs.txt') as f:\n    lines = f.readlines()\n    for l in lines: \n        texts.append(l.strip('\\r\\n'))\n\nlines[0]\n```\n\n\n\n\n    'We\u2019ve trained a large language model called GPT-2 that generates realistic paragraphs of text, while also exhibiting zero shot generalization on tasks like machine translation, question answering, reading comprehension, and summarization - problems usually approached by using training datasets and models designed explicitly for these tasks. A typical approach to language modeling is to learn the following task: predict the next word, given all of the previous words within some text. Last year, OpenAI\u2019s Generative Pre-trained Transformer (GPT) showed that language models trained on large amounts of data can be fine-tuned to specific tasks to achieve high performance. GPT-2 shows that much larger language models trained on a more diverse dataset derived from the internet begin to learn these NLP tasks without needing task-specific training data, instead learning from examples the system derives from the raw text. These systems also display a substantial qualitative jump in the realism and coherence of generated text.\\n'\n\n\n\n\n```python\nfrom transformers import GPT2Tokenizer, GPT2Model, GPT2LMHeadModel\ntokenizer = GPT2Tokenizer.from_pretrained('gpt2')\n```\n\n\n```python\nlens = []\nfor t in texts: \n    lens.append(tokenizer(t, return_tensors='pt')['input_ids'].shape[1])\n```\n\n\n```python\ndf = pd.DataFrame([texts, lens]).T\npd.set_option('display.max_colwidth', -1)\ndf.columns = ['Text', 'Token Lengths']\ndf\n```\n\n    /Users/trentonbricken/anaconda3/envs/ed2/lib/python3.7/site-packages/ipykernel_launcher.py:2: FutureWarning: Passing a negative integer is deprecated in version 1.0 and will not be supported in future version. Instead, use None to not limit the column width.\n      \n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Text</th>\n      <th>Token Lengths</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>We\u2019ve trained a large language model called GPT-2 that generates realistic paragraphs of text, while also exhibiting zero shot generalization on tasks like machine translation, question answering, reading comprehension, and summarization - problems usually approached by using training datasets and models designed explicitly for these tasks. A typical approach to language modeling is to learn the following task: predict the next word, given all of the previous words within some text. Last year, OpenAI\u2019s Generative Pre-trained Transformer (GPT) showed that language models trained on large amounts of data can be fine-tuned to specific tasks to achieve high performance. GPT-2 shows that much larger language models trained on a more diverse dataset derived from the internet begin to learn these NLP tasks without needing task-specific training data, instead learning from examples the system derives from the raw text. These systems also display a substantial qualitative jump in the realism and coherence of generated text.</td>\n      <td>195</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Used most notably in the Transformer, Attention has enabled deep learning to arguably approach human level performance across modalities with larger models continuing to boost performance. However, the heuristic motivations that produced Attention leave open the question of why it is so good at the same tasks humans are. Insights into why Attention is so effective would not only make it more interpretable but also guiding future improvements. Much work has been done to try and explain the Attention's success, including work showing that Transformers representations map more closely to human brain recordings and inductive biases than other models. Our work goes further in showing the potential relationship between Attention and the brain at the level of the connectome, giving a new and exciting perspective behind Attention's success. This potential relationship to the brain is created by showing mathematically that Attention closely approximates Sparse Distributed Memory (SDM) and is summarized in Figure A. SDM is an associative memory model developed in 1988 to solve the ``Best Match Problem'', where we have a set of memories and want to quickly find the ``best'' match to any given query. In the development of its solution, SDM respected fundamental biological constraints, such as Dale's law that synapses are fixed to be either excitatory or inhibitory and cannot dynamically switch (see Section 1 for an overview of SDM). While being developed independently of brain regions, surprisingly, SDM's biologically plausible solution maps strikingly well onto the cerebellum. At a high level, the relationship between SDM and Attention exists because SDM's update operation approximates the Attention softmax rule. To give intuition for why this is the case, imagine two identical, intersecting spheres with their centers distance $c$ apart. As the distance $c$ between the spheres increases, under certain conditions the volume of their intersection will decay approximately exponentially. Mapping this onto SDM, one sphere defines the neurons that have written a pattern into memory and the other sphere defines the neurons being read from by a query. The volume of the sphere intersection defines the weight or ``attention'' assigned to a pattern. The approximately exponential decay as the distance between the pattern and query spheres increases can be mapped onto the exponential function used in Attention's softmax. Section 2 provides more details and a formal analysis of this approximate exponential and how Attention closely approximates itEstablishing that Attention approximates SDM in theory, we then test it in pre-trained GPT2 Transformer models (Section 3). We use the Query-Key Normalized Transformer variant to directly show that the relationship to SDM holds well. We then use original GPT2 models to help confirm this result and make it more general. Given these results, we put forward the hypothesis that due to the exponential function's rapid ``take-off'' with increasingly large positive inputs, for Attention to work well it may need to exist in a regime where it always closely approximates SDM.Using the SDM framework, we are able to go beyond Attention and interpret the Transformer architecture as a whole, providing its heuristic structure with deeper intuition (Section 4). The fact that SDM maps well onto the whole Transformer suggests that extensions to SDM that already exist could motivate future Transformer improvements.Finally, in related work (Section 5), we explain how SDM is a generalization of Hopfield Networks and, in turn, how our results are also a generalization of work relating Hopfield Networks to Attention. We also discuss Vector Symbolic Architectures that are compatible with SDM and relations to other memory models such as the Neural Turing and Kanerva Machines.To what extent will our most successful deep learning systems converge with the brain? Some convergence seems inevitable, given that we want our models to excel at the same tasks that brains do. However, the brain and machine learning models have different optimizers, objective functions, and constraints. In this light, it is surprising that the connectome of the cerebellum, if it implements Sparse Distributed Memory, closely approximates Attention and many aspects of the whole Transformer architecture. We believe this work provides a small piece of evidence that the brain and the best deep learning models may be more convergent than we might otherwise think.</td>\n      <td>855</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do:  once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, `and what is the use of a book,' thought Alice `without pictures or conversation?'   So she was considering in her own mind (as well as she could, for the hot day made her feel very sleepy and stupid), whether the pleasure of making a daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly a White Rabbit with pink eyes ran close by her.   There was nothing so VERY remarkable in that; nor did Alice think it so VERY much out of the way to hear the Rabbit say to itself, `Oh dear!  Oh dear!  I shall be late!'  (when she thought it over afterwards, it occurred to her that she ought to have wondered at this, but at the time it all seemed quite natural); but when the Rabbit actually TOOK A WATCH OUT OF ITS WAISTCOAT- POCKET, and looked at it, and then hurried on, Alice started to her feet, for it flashed across her mind that she had never before seen a rabbit with either a waistcoat-pocket, or a watch to take out of it, and burning with curiosity, she ran across the field after it, and fortunately was just in time to see it pop down a large rabbit-hole under the hedge.   In another moment down went Alice after it, never once considering how in the world she was to get out again.   The rabbit-hole went straight on like a tunnel for some way, and then dipped suddenly down, so suddenly that Alice had not a moment to think about stopping herself before she found herself falling down a very deep well.   Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next.  First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs.  She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty:  she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it.   `Well!' thought Alice to herself, `after such a fall as this, I shall think nothing of tumbling down stairs!  How brave they'll all think me at home!  Why, I wouldn't say anything about it, even if I fell off the top of the house!' (Which was very likely true.)   Down, down, down.  Would the fall NEVER come to an end!  `I wonder how many miles I've fallen by this time?' she said aloud. `I must be getting somewhere near the centre of the earth.  Let me see:  that would be four thousand miles down, I think--' (for, you see, Alice had learnt several things of this sort in her lessons in the schoolroom, and though this was not a VERY good opportunity for showing off her knowledge, as there was no one to listen to her, still it was good practice to say it over) `--yes, that's about the right distance--but then I wonder what Latitude or Longitude I've got to?'  (Alice had no idea what Latitude was, or Longitude either, but thought they were nice grand words to say.) Presently she began again.  `I wonder if I shall fall right THROUGH the earth!  How funny it'll seem to come out among the people that walk with their heads downward!  The Antipathies, I think--' (she was rather glad there WAS no one listening, this time, as it didn't sound at all the right word) `--but I shall have to ask them what the name of the country is, you know. Please, Ma'am, is this New Zealand or Australia?' (and she tried to curtsey as she spoke--fancy CURTSEYING as you're falling through the air!  Do you think you could manage it?)  `And what an ignorant little girl she'll think me for asking!  No, it'll never do to ask:  perhaps I shall see it written up somewhere.</td>\n      <td>978</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Previous work showed that the modern Hopfield Network, when made continuous and optimized differently, becomes Attention. This result was one motivation for this work because Hopfield Networks are another form of Associative Memory. However, Hopfield Networks are biologically implausible, lack SDM's geometric framework, are not part of the powerful family of Vector Symbolic Architectures that will be outlined next, and in their original form are less appropriate for handling heteroassociative memory and correlated patterns and the new energy functions of the modern discrete Hopfield network make it a closer approximation to SDM. That SDM is significantly more biologicially plausible than any Hopfield Network variant and has an immediate relationship to Attention that explains the route taken by the Hopfield Network makes this work a generalization of previous insights.Since the publication of SDM there have been a number of advancements not only to SDM specifically, but also through the creation of related associative memory algorithms under the name of ``Vector Symbolic Architectures''. Advancements to SDM specifically include: using integer rather than binary vectors; approaches to handle correlated patterns; hierarchical data storage; and more sophisticated convergence analysis. Vector Symbolic Architectures, most notably Holographic Reduced Representations, have ideas that can be related back to SDM and the Transformer in ways that may be fruitful and will be explored in future work. The use of external memory modules in neural networks has been explored most notably with the Neural Turing Machine (NTM) and its followup, the Differential Neural Computer (DNC). In order to have read and write operations to the external memory be differentiable, they use the softmax function, this combined with their use of cosine similarity between the query and memory locations makes both models closely related to SDM. However, subtle yet arguably important differences exist. In both the NTM and DNC, the memory vectors do not have addresses, only pointers meaning the cosine similarity is between the query and memory contents (analogous to the neuron value vector rather than address). We believe this lack of variable binding between addresses and pointers makes the memory system weaker because one memory cannot point to others. One indication of this weakness is the need for a location based addressing implementation to learn sequence transitions, in addition to the content based addressing outlined. A more recent improvement to the NTM and DNC directly inspired by SDM is the Kanerva Machine. The Kanerva Machine augments a VAE with external memory in the form of SDM and treats it as Bayesian, allowing for Bayesian inference to determine what memories should be stored. However, the Kanerva Machine remains distinct from SDM and Attention because it lacks the softmax function on the cosine similarities between its query and patterns. The model is also restricted to the autoassociative setting with training difficulties noted when the model was used for a heteroassociative reinforcement learning problem. Independent of these discrepancies with SDM, the Kanerva Machine presents a number of interesting ideas that we believe can be related to our work and developed further. The result that Attention approximates SDM should enable more cross pollination of ideas between neuroscience, theoretical models of associative learning, and deep learning. Considering avenues for future deep learning research, SDM's relationship to Vector Symbolic Architectures is particularly compelling because they can apply logical and symbolic operations on memories, making SDM more powerful. Analogizing to computers, SDM is to RAM as VSA is to the CPU. Beyond symbolic approaches, there are extensions to SDM that leverage sparsity and discrete representations that may improve Transformers, similarly to how vector quantization has improved VAEs. SDM and its relation to the brain can inspire new research in not only deep learning research but also neuroscience, because of the empirical success of Transformers and its relation to the cerebellum via SDM. While SDM fits unique features of the cerebellum in striking ways, this connection and its evidence relies on neuroscientific evidence available in 1988. Although we are unaware of any results that disprove this connection and the Marr-Albus-Ito model of the cerebellum that fits with SDM remains popular, in future work we will review modern neuroscience to update the state of SDM's biological plausibility. There are two reasons to be initially excited about this investigation. First, there has been growing evidence that the cerebellum is important for many more cognitive functions than just precise motor control, long believed to be its only role. Second, improvements to our understanding of the computational capabilities of Pyramidal neurons means that they may have parallels to Purkinje cells and that the core algorithmic requirements of SDM could be implemented in additional brain regions such as the hippocampus and cortical columns. These remain early hypotheses but the success of Transformers and their link to SDM should catalyze novel investigations.One limitation of our analysis in this paper is that we cannot use SDM to predict the $\\beta$ value that Attention should use.</td>\n      <td>1005</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>So, we left off in my senior year of high school. It was 2007. Chris Brown was still a good guy in public eye, Britney Spears and K-Fed had recently split, Michael Jackson was still alive, and my high school boyfriend and I had reached a massive fork in the road. We were accepted into two different universities on opposite sides of the country. He was moving to the other side while I was staying close to home. The good news? We were accepted into our first picks. The bad news? Our relationship was toast. We decided we would enjoy whatever time we had left together, and then go our separate ways. I wasn\u2019t very keen on long distance as I wanted to focus more on my studies than making sure my boyfriend wasn\u2019t cheating on me. Dean agreed. We were exactly on the same page in that regard. When time came around for us to say our goodbyes, I made sure to let him know he was as close to perfect as I had ever met. Not only was he patient, supportive and trusting, he was all of those things and so effortlessly understanding at the same time. Of course we had our moments, but it was all worth it. I can safely say I was the lucky one in our relationship. I\u2019ve heard so many horror stories of crazy, manipulative boyfriends but Dean wasn\u2019t like that at all. He was good. So a couple of months into university, when I heard he was dating another girl at his school, I wasn\u2019t at all surprised. Dean was a charmer. Of course there was another girl lol. She was cute. I had only a few pictures to go off of on social media, but yeah. She very cute, very bubbly looking, and exactly the type of girl I had always imagined for Dean. In other words I was happy for them. I mean, don\u2019t get me wrong, I had my jealous moments \u2026 but I was mostly happy for them. The fact that I was suddenly thrust into university and forced to make new friends at school, helped to distract me from those tiny, unwelcome sparks of jealousy. I eventually wasn\u2019t jealous anymore, and I eventually met this girl when Dean brought her home for Christmas. Our tight knit group of friends from high school had all met up at one of our houses the day before Christmas Eve. Dean politely introduced his girlfriend to me, and we got on really well. She was a nice person. Still is, as a matter of fact. (They\u2019re married now and pregnant with their first child. Crazy, huh?) The next night, when I was with my family and a bunch of our relatives at my parents\u2019 Christmas Eve party, I realized how much I missed home. School wasn\u2019t too far away. Maybe two hours on a particularly busy day. But during those first few months, I tried my best not to go home and fall into old, comfortable habits. I wanted to grow up and separate myself from my family a little bit. That said, I absolutely cried when I saw them again. Such a cornball lol. My brother made fun of me for years over that. In fact he still does. He\u2019s kind of an asshole like that, but in a good way. Suffice to say I stuffed my face and immediately fell into food coma. It was close to midnight, I would say. I dragged myself into my old bedroom, where everything had been left the same since the last time I was there. The murmur of music and laughter down below kept me somewhat alert of my surroundings. I knew it wouldn\u2019t be long before my mother or father came knocking to see if I wanted some extra dessert or something, so I told myself I would rest for only a few minutes. The second I flopped down in bed and sunk into the comfy mattress I been deprived of at school (seriously, the mattress in my dorm was like a slab of concrete) I felt my pocket vibrate. I groaned into my pillow, lazily retrieving the flip phone from my pocket to find a text message. From: Nicky Merry Christmas However tired I felt, I smiled when I saw the message. There were times when we would go months without speaking, and times when we would speak nearly everyday. No matter how long we had gone without talking, we\u2019d always pick up exactly where we left off as though no time had passed. He was going to school in the same city as me. But, for some reason, we had yet to hang out. We tried a few times in the beginning, organizing lunch or coffee somewhere in the city, but the plan would always change. We\u2019d run into scheduling problems or papers that were due. For the most part, he was the one to cancel on me. I figured he wanted to focus on school and his new friends</td>\n      <td>1006</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>So this takes place back in high school, long time ago. I was in class and I wasn't feeling too good that day. I wish I was kidding, I really do but I'm not. I have a bowel disorder with the intestines, not gonna get into that. But I was in class, didn't shit for about a week and a half if I remember correctly. I had to take a shit. Really fucking bad. My stomach was aching so bad. I would NEVER shit at someones house, or at school. Except for that day. I thought to myself \"Fuck it, I'll take a shit in the bathroom. It's gonna be the biggest shit anyone has seen, but most likely they'll have no idea who it was. So I asked the teacher to use the bathroom, took a hall pass and was on my way. I get into that bathroom, nobody was in it a the time (thank god) and immediately run to the stall, close it, lock it, drop my pants and sit on the toilet. About 5-7 seconds later, there it goes. It was thirty seconds of pushing, one came out, and then another one. I could smell the defecation as soon as it hit the water in the toilet, and it was awful. This wasn't going to flush, there's no way. But then a student walked in. My heart sank from my chest all the way to my ballsack probably.I was genuinely terrified. The student walked right in. He said \"oh god what the fuck is that\" he took a piss, and left as quick as possible. I sat on the toilet for the next few minutes. My stomach was aching, but I also felt relief. No, I didn't flush it. Didn't even try, I knew it would clog. I didn't want anyone to suspect it was me in even the slightest. I eventually left the bathroom, and walked back to class. I was in there for a bit, so the teacher said I was late on the way back. With some quick thinking I tell her \"I'm sorry miss, Won't lie to you, my friends walked in and we got caught up in silly conversation\" She replies to me \"Well, at least you're telling the truth, I appreciate that. But you're behind on work\" I went back to my desk, finished my stuff. At the end of the day, nobody had an idea who it was that took this giant shit in the toilet and left it there. I went home that day, did things a teenager does at home after school, usual shenanigans. Took a piss, video games, half-assed my homework, busted a nut all that stuff. Went back to school the next day. My first thought is \"I'm going to that bathroom to see if that shit is still there, if the janitors did anything about it. So I walked in, and that entire stall had a sign that read \"out of order\" the toilet was closed up and everything. I was dying of laughter, it was absolutely hilarious. I tried so hard to contain my laughter which I did. I thought it was fucking hysterical coming back the next day and seeing that same toilet out of order the next day. It stayed like that for maybe another month. And to this very day, nobody had any idea who did it. This was definitely one of my weirdest, but also funniest HS experiences I've ever had.</td>\n      <td>711</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>The dominant sequence transduction models are based on complex recurrent or convolutional neural networks that include an encoder and a decoder. The best performing models also connect the encoder and decoder through an attention mechanism. We propose a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two machine translation tasks show these models to be superior in quality while being more parallelizable and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014 Englishto-German translation task, improving over the existing best results, including ensembles, by over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training costs of the best models from the literature. We show that the Transformer generalizes well to other tasks by applying it successfully to English constituency parsing both with large and limited training data. Recurrent models typically factor computation along the symbol positions of the input and output sequences. Aligning the positions to steps in computation time, they generate a sequence of hidden states ht, as a function of the previous hidden state ht\u22121 and the input for position t. This inherently sequential nature precludes parallelization within training examples, which becomes critical at longer sequence lengths, as memory constraints limit batching across examples. Recent work has achieved significant improvements in computational efficiency through factorization tricks [21] and conditional computation [32], while also improving model performance in case of the latter. The fundamental constraint of sequential computation, however, remains. Attention mechanisms have become an integral part of compelling sequence modeling and transduction models in various tasks, allowing modeling of dependencies without regard to their distance in the input or output sequences [2, 19]. In all but a few cases [27], however, such attention mechanisms are used in conjunction with a recurrent network. In this work we propose the Transformer, a model architecture eschewing recurrence and instead relying entirely on an attention mechanism to draw global dependencies between input and output. The Transformer allows for significantly more parallelization and can reach a new state of the art in translation quality after being trained for as little as twelve hours on eight P100 GPUs. The goal of reducing sequential computation also forms the foundation of the Extended Neural GPU [16], ByteNet [18] and ConvS2S [9], all of which use convolutional neural networks as basic building block, computing hidden representations in parallel for all input and output positions. In these models, the number of operations required to relate signals from two arbitrary input or output positions grows in the distance between positions, linearly for ConvS2S and logarithmically for ByteNet. This makes it more difficult to learn dependencies between distant positions [12]. In the Transformer this is reduced to a constant number of operations, albeit at the cost of reduced effective resolution due to averaging attention-weighted positions, an effect we counteract with Multi-Head Attention as described in section 3.2. Self-attention, sometimes called intra-attention is an attention mechanism relating different positions of a single sequence in order to compute a representation of the sequence. Self-attention has been used successfully in a variety of tasks including reading comprehension, abstractive summarization, textual entailment and learning task-independent sentence representations [4, 27, 28, 22]. End-to-end memory networks are based on a recurrent attention mechanism instead of sequencealigned recurrence and have been shown to perform well on simple-language question answering and language modeling tasks [34]. To the best of our knowledge, however, the Transformer is the first transduction model relying entirely on self-attention to compute representations of its input and output without using sequencealigned RNNs or convolution. In the following sections, we will describe the Transformer, motivate self-attention and discuss its advantages over models such as [17, 18] and [9].</td>\n      <td>843</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>This chapter describes one basic model of associative memory, called the sparse distributed memory, and relates it to other models and circuits: to ordinary computer memory, to correlation-matrix memories, to feed-forward artificial neural nets, to neural circuits in the brain, and to associative-memory models of the cerebellum. Presenting the various designs within one framework will hopefully help the reader see the similarities and the differences in designs that are often described in different ways. 3.1.1. Sparse Distributed Memory as a Model of Human Long-Term Memory Sparse Distributed Memory (SDM) was developed as a mathematical model of human long-term memory (Kanerva 1988). The pursuit of a simple idea led to the discovery of the model, namely, that the distances between concepts in our minds correspond to the distances between points of a high-dimensional space. In what follows, \u2018high-dimensional\u2019 means that the number of dimensions is at least in the hundreds, although smaller numbers of dimensions are often found in examples. If a concept, or a percept, or a moment of experience, or a piece of information in memory\u2014a point of interest\u2014is represented by a high-dimensional (or \u201clong\u201d) vector, the representation need not be exact. This follows from the distribution of points of a high-dimensional space: Any point of the space that might be a point of interest is relatively far from most of the space and from other points of interest. Therefore, a point of interest can be represented with considerable slop before it is confused with other points of interest. In this sense, long vectors are fault-tolerant or robust, and a device based on them can take advantage of the robustness. This corresponds beautifully to how humans and animals with advanced sensory systems and brains work. The signals received by us at two different times are hardly ever identical, and yet we can identify the source of the signal as a specific individual, object, place, scene, thing. The representations used by the brain must allow for such identification, in fact, they must make the identification nearly automatic, and high-dimensional vectors as internal representations of things do that. Another property of high-dimensional spaces also has to do with the distances between points. If we take two points (of interest) at random, they are relatively far from each other, on the average: they are uncorrelated. However, there are many points between the two that are close to both, in the sense that the amount of space around an intermediate point\u2014in a hypersphere\u2014that contains both of the two original points is very small. This corresponds to the relative ease with which we can find a concept that links two unrelated concepts. Strictly speaking, a mathematical space need not be a high-dimensional vector space to have the desired properties; it needs to be a huge space, with an appropriate similarity measure for pairs of points, but the measure need not define a metric on the space. The important properties of high-dimensional spaces are evident even with the simplest of such spaces\u2014that is, when the dimensions are binary. Therefore, the sparse distributed memory model was developed using long (i.e., highdimensional) binary vectors or words. The memory is addressed by such words, and such words are stored and retrieved as data. The following two examples demonstrate the memory\u2019s robustness in dealing with approximate data. The memory works with 256-bit words: it is addressed by them, and it stores and retrieves them. On top of Figure 3.1 are nine similar (20% noisy) 256-bit words. To help us compare long words, their 256 bits are laid on a 16-by-16 grid, with 1s shown in black. The noise-free prototype word was designed in the shape of a circle within the grid. (This example is confusing in that it might be taken to imply that humans recognize circles based on stored retinal images of circles. No such claim is intended.) The nine noisy words were stored in a sparse distributed memory autoassociatively, meaning that each word was stored with itself as the address. When a tenth noisy word (bottom left), different from the nine, was used as the address, a relatively noise-free 11th word was retrieved (bottom middle), and with that as the address, a nearly noise-free 12th word was retrieved (bottom right), which in turn retrieved itself. This example demonstrates the memory\u2019s tendency to construct a prototype from noisy data.</td>\n      <td>926</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Biological neurons are cells that process signals in animals and humans, allowing them to respond rapidly to the environment. To achieve speed, neurons use electrochemical mechanisms to generate a signal (a voltage level or electrical pulses) and to transmit it to nearby and distant sites. Biological neurons come in many varieties. The peripheral neurons couple the organism to the world. They include the sensory neurons that convert an external stimulus into an electrical signal, the motor neurons whose electrical pulses cause muscle fibers to contract, and other effector neurons that regulate the secretion of glands. However, most neurons in highly evolved animals are interneurons that connect directly to other neurons rather than to sensors or to effectors. Interneurons also come in many varieties and they are organized into a multitude of neural circuits. A typical interneuron has a cell body and two kinds of arborizations: a dendrite tree that receives signals from other neurons, and an axon tree that transmits the neuron\u2019s signal to other neurons. Transmission-contact points between neurons are called synapses. They are either excitatory (positive synaptic weight) or inhibitory (negative synaptic weight) according to whether a signal received through the synapse facilitates or hinders the activation of the receiving neuron. The axon of one neuron can make synaptic contact with the dendrites and cell bodies of many other neurons. Thus, a neuron receives multiple inputs, it integrates them, and it transmits the result to other neurons. Artificial neural networks are networks of simple, interconnected processing units, called (artificial) neurons. The most common artificial neuron in the literature has multiple (N) inputs and one output and is defined by a set of input coefficients\u2014a vector of N reals, standing for the synaptic weights\u2014and a nonlinear scalar activation function. The value of this function is the neuron\u2019s output, and it serves as input to other neurons. A linear threshold function is an example of an artificial neuron, and the simplest kind\u2014one with binary inputs and output\u2014is used in the sparse distributed memory. It may seem strange to model brain activity with binary neurons when real neurons are very complex in comparison. However, the brain is organized in large circuits of neurons working in parallel, and the mathematical study of neural nets is aimed more at understanding the behavior of circuits than of individual neurons. An important fact\u2014perhaps the most important\u2014is that the states of a large circuit can be mapped onto the points of a high-dimensional space, so that although a binary neuron is a grossly simplified model of a biological neuron, a large circuit of binary neurons, by virtue of its high dimension, can be a useful model of a circuit of biological neurons. The sparse distributed memory\u2019s connection to biology is made in the standard way. Each row through A, d, y, and C in Figure 3.9\u2014each hidden unit\u2014is an artificial neuron that represents a biological neuron. Vector x represents the N signals coming to these neurons as inputs from N other neurons (along their axons), vector Am represents the weights of the synapses through which the input signals enter the mth neuron (at its dendrites), dm represents the integration of the input signals by the mth neuron, and ym represents the output signal, which is passed along the neuron\u2019s axon to U other neurons through synapses with strengths Cm. We will call these (the hidden units) the address-decoder neurons because they are like the address-decoder circuit of a random-access memory: they select locations for reading and writing. The address that the mth address-decoder neuron decodes is given by the input coefficients Am; location Am is activated by inputs x that equal or are sufficiently similar to Am. How similar, depends on the radius of activation H. It is interesting that a linear threshold function with N inputs, which is perhaps the oldest mathematical model of a neuron, is ideal for address decoding in the sparse distributed memory, and that a proper choice of a single parameter, the threshold, makes it into an address decoder for a location of an ordinary randomaccess memory.</td>\n      <td>844</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nimport dataframe_image as dfi\n\n# will save a high res screenshot of the dataframe. \n#dfi.export(df, directory+\"TransformerTextInputsTable.png\")\n```\n\n## 2. Computing Softmax Input Intervals\n\nHave custom modified the Hugging Face codebase to return the key value and query matrices. (Using its implementation we could not get out the query matrix that is crucial for computing the size of the vector dot products that go into the softmax)\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch \nimport torch.optim as optim\nimport pandas as pd \nfrom IPython.display import display\nimport pickle\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n############ Parameters:\n\nmodelname = 'gpt2-small'#'bert-base-uncased' #'gpt2-xl' #gpt2-small is in fact the small model. \n\nif 'lm-' in modelname: \n    modelname_toload = modelname.split('lm-')[-1]\nelif modelname=='gpt2-small':\n    modelname_toload = 'gpt2' # this is the Hugging Face name for the small model\nelse: \n    modelname_toload = modelname\n\nif 'gpt2-small' in modelname:\n    layers=12\n    nheads= 12\nelif 'gpt2-large' in modelname:\n    layers=36\n    nheads= 20\nelif 'gpt2-xl' in modelname:\n    layers=48\n    nheads= 25\n```\n\n\n```python\n\nif 'gpt' in modelname: \n\n    from transformers import GPT2Tokenizer, GPT2Model, GPT2LMHeadModel\n    tokenizer = GPT2Tokenizer.from_pretrained(modelname_toload)\n    if 'lm-' in modelname: \n        model = GPT2LMHeadModel.from_pretrained(modelname_toload, output_attentions=True, output_hidden_states=True).to(device)\n    else: \n        model = GPT2Model.from_pretrained(modelname_toload, output_attentions=True, output_hidden_states=True).to(device)\n\nelif 'bert' in modelname: \n\n    from transformers import BertTokenizer, BertModel, BertLMHeadModel\n    # Download model and configuration from huggingface.co and cache.\n    tokenizer = BertTokenizer.from_pretrained(modelname_toload)\n    model = BertLMHeadModel.from_pretrained(modelname_toload, output_attentions=True, output_hidden_states=True).to(device)\n\n```\n\n    Init GPT2 hello world and custom code!!!\n\n\n\n```python\ntokenizer(texts[0], return_tensors='pt')['input_ids'].shape\n```\n\n\n\n\n    torch.Size([1, 195])\n\n\n\n\n```python\nencoded_input = tokenizer(texts[0], return_tensors='pt')\noutput = model(**encoded_input)\noutput.keys()\n```\n\n\n\n\n    odict_keys(['last_hidden_state', 'past_key_values', 'hidden_states', 'kqvs', 'attentions'])\n\n\n\n\n```python\nlen(output['past_key_values'])\n```\n\n\n\n\n    12\n\n\n\n\n```python\nlen(output['kqvs'])\n```\n\n\n\n\n    12\n\n\n\n## Checking that I customized the code to get out the keys, queries, and values correctly and evaluating tensor shapes\n\n\n```python\noutput['past_key_values'][5][0].shape\n```\n\n\n\n\n    torch.Size([1, 12, 195, 64])\n\n\n\n\n```python\noutput['kqvs'][5][0].shape\n```\n\n\n\n\n    torch.Size([1, 12, 195, 64])\n\n\n\n\n```python\n# output['past_key_values'][LAYER][0=KEY, 1=VALUE][batch_size, num_heads, sequence_length, embed_size_per_head]\n# output['kqvs'][LAYER][KEY=0, QUERY=1, VALUE=2][batch_size, num_heads, sequence_length, embed_size_per_head]\n\noutput['past_key_values'][5][0][0,3,:,:] == output['kqvs'][5][0][0,3,:,:]\n```\n\n\n\n\n    tensor([[True, True, True,  ..., True, True, True],\n            [True, True, True,  ..., True, True, True],\n            [True, True, True,  ..., True, True, True],\n            ...,\n            [True, True, True,  ..., True, True, True],\n            [True, True, True,  ..., True, True, True],\n            [True, True, True,  ..., True, True, True]])\n\n\n\n\n```python\nkey, query, value = output['kqvs'][2] #[0][0,3,:,:]\n```\n\n\n```python\nquery[0,:,-1,:].unsqueeze(-1).shape\n```\n\n\n\n\n    torch.Size([12, 64, 1])\n\n\n\n\n```python\nkey[0,:,:,:].shape\n```\n\n\n\n\n    torch.Size([12, 195, 64])\n\n\n\n\n```python\ntorch.matmul(key[0,:,:,:], query[0,:,-1,:].unsqueeze(-1)).squeeze().shape\n```\n\n\n\n\n    torch.Size([12, 195])\n\n\n\n\n```python\noutput['attentions'][3][0,:,-1,:].shape\n```\n\n\n\n\n    torch.Size([12, 195])\n\n\n\n\n```python\nnp.linalg.norm(value[0,:,:,:].detach().numpy(), axis=2).shape\n```\n\n\n\n\n    (12, 195)\n\n\n\n\n```python\nvalue[0,:,:,:].shape\n```\n\n\n\n\n    torch.Size([12, 195, 64])\n\n\n\n## Collecting Keys, Queries, Values, and Attention for every text input\n\n\n```python\nverbose = False \nbeta = 1/np.sqrt(64)\nover_texts = dict()\n\nfor text_ind, text in enumerate(texts): \n    print('text index is:', text_ind)\n    encoded_input = tokenizer(text, return_tensors='pt')\n    output = model(**encoded_input)\n    input_len = encoded_input['input_ids'].shape[1]\n\n    # storing the processed results: \n    h_summary = dict()\n    l_summary = dict()\n    \n    for l_ind in range(layers):\n        if verbose: \n            print('layer is:', l_ind)\n        \n        key, query, value = output['kqvs'][l_ind] #[0][0,3,:,:]\n        \n        # if not working with just the last input need to do masking. Not doing this here. \n        # code should look something like this. \n        #K_masked = K[:, :, :(inp_ind+1),:]\n    \n        sm_inputs = beta*torch.matmul(key[0,:,:,:], query[0,:,-1,:].unsqueeze(-1)).squeeze().detach().numpy() # [NHEADS, SEQLEN] \n        \n        if verbose:\n            print('softmax inputs shpae', sm_inputs.shape)\n        V_norms = np.linalg.norm(value[0,:,:,:].detach().numpy(), axis=2)\n        A = output['attentions'][l_ind][0,:,-1,:].detach() # # [NHEADS, SEQLEN]\n        layer_dtypes = np.stack([sm_inputs, V_norms, A],axis=0)[np.newaxis,:]\n        if l_ind==0:\n            all_layers_res = layer_dtypes\n        else: \n            all_layers_res = np.concatenate([all_layers_res, layer_dtypes],axis=0)\n    \n        # max for each of the heads. \n        maxs = sm_inputs.max(axis=1)\n        mins = sm_inputs.min(axis=1)\n        intervals = pd.DataFrame([mins,maxs])\n        if verbose: \n            print('observed interval is:')\n            display(intervals.T)\n            print('mean value of maxes for each head in layer:', np.mean(maxs))\n            print('median:', np.median(maxs))\n            print('max of maxes:', np.max(maxs))\n            \n        # max of each head logging each layer\n        h_summary[l_ind] = maxs\n        # summary across heads for each layer\n        l_summary[l_ind] = [np.mean(maxs), np.median(maxs), np.max(maxs) ]\n        \n        \n    # all_layers_res: Layers x Dtypes x Heads x SeqLen\n    \n    # input to softmax for all layers. \n    plt.figure()\n    plt.hist(all_layers_res[:,0,:,:].flatten(), bins=50)\n    plt.gcf().savefig(directory + modelname+'AllLayerPreSMs|text_ind='+str(text_ind)+'.png', dpi=250)\n    plt.show()\n    \n    plt.figure()\n    plt.scatter(all_layers_res[:,2,:,:].flatten(), all_layers_res[:,1,:,:].flatten())\n    plt.xlabel(\"Attention Weight\")\n    plt.ylabel(\"Value L2 Norm\")\n    plt.title(\"Value Magnitude as a function of Attention weight\")\n    plt.gcf().savefig(directory + modelname+'AllLayerValMagAttWeight|text_ind='+str(text_ind)+'.png', dpi=250)\n    plt.show()\n\n    l_summary = pd.DataFrame(l_summary).T\n    l_summary.columns = ['mean', 'median', 'max']\n    # rows are layers and columns are heads\n    h_summary = pd.DataFrame(h_summary).T\n    \n    if verbose: \n        display(l_summary)\n        display(h_summary)\n    \n    # saving out these summaries: \n    over_texts[text_ind] = (l_summary, h_summary, all_layers_res)\n    \nwith open(directory+modelname+\"results_over_all_texts.pkl\", 'wb') as fname: \n    pickle.dump(over_texts, fname)\n```\n\n\n```python\nall_layers_res.shape # Layers x Dtypes x Heads x SeqLen\n```\n\n\n\n\n    (12, 3, 12, 844)\n\n\n\n## Plotting various aggregations of the heads, layers, and texts to get the effective $\\beta$ and also investigate the relationship between attention weights and the value vector's L2 norm\n\n\n```python\nimport pickle\nwith open(directory+modelname+\"results_over_all_texts.pkl\", 'rb') as fname: \n    over_texts = pickle.load( fname)\n```\n\n\n```python\n# replotting the results from before but also aggregating across them. \nfor text_ind, text in enumerate(texts):\n    print('text ind', text_ind)\n    #print(text)\n    # saving out these summaries: \n    l_summary, h_summary, all_layers_res = over_texts[text_ind]\n\n    # input to softmax for all layers. \n    #all_layers_res = all_layers_res[np.newaxis, :]\n    if text_ind==0: \n        all_text_vals = all_layers_res\n    else: \n        #print(all_text_vals.shape, all_layers_res.shape)\n        all_text_vals = np.concatenate([all_text_vals, all_layers_res], axis=-1)\n    #plt.hist(all_layers_res[:,0,:,:].flatten(), bins=50)\n    #plt.gcf().savefig(directory+modelname+'AllLayerPreSMs|text_ind='+str(text_ind)+'.png', dpi=250)\n    #plt.show()\n\n    #display(l_summary)\n    #display(h_summary)\n    \n# all_text_vals:  Layers x Dtypes x Heads x (SeqLen * Texts, all combined!)\nprint(\"Summary of all:\")\nplt.hist(all_text_vals[:,0,:,:].flatten(), bins=50)\nplt.gcf().savefig(directory+modelname+'SMValuesForAllTextsLayersHeads.png', dpi=250)\nplt.show()\n\nplt.figure()\nnumber_to_plot = 10000\nrand_inds = np.random.choice(np.arange(len(all_text_vals[:,2,:,:].flatten())),number_to_plot, replace =False)\nplt.scatter(all_text_vals[:,2,:,:].flatten()[rand_inds], all_text_vals[:,1,:,:].flatten()[rand_inds])\nplt.xlabel(\"Attention Weight\")\nplt.ylabel(\"Value L2 Norm\")\nplt.title(\"Value Magnitude as a function of Attention weight\")\nplt.gcf().savefig(directory + modelname+'ValuesvsAttentionAllTextsLayersHeads.png', dpi=250)\nplt.show()\n\n############\n\nplt.figure()\n\nr_min = np.min(all_text_vals[:,0,:,:], axis=-1)\nr_max = np.max(all_text_vals[:,0,:,:], axis=-1)\nranges = np.abs(r_max-r_min)\nmu = (r_max+r_min)/2\nsize_of_addition_components = mu + r_min\n\nplt.hist(ranges.flatten()/2, bins =50)\nplt.title(\"Ranges of values for each head across texts\")\nplt.show()\n\nplt.figure()\nplt.hist(size_of_addition_components.flatten(), bins =50)\nplt.title(\"size of addition components\")\nplt.show()\n\nplt.figure()\nplt.hist(mu.flatten(), bins =50)\nplt.title(\"means of the ranges\")\nplt.show()\n\nplt.figure()\n#rescaling_betas = ((2*np.abs(r_min))/ranges) -2\n#print(ranges*rescaling_betas)\nplt.title(\"Rescaling Beta calc\")\nplt.hist(rescaling_betas.flatten())\nplt.show()\n```\n\n\n```python\n### How do results differ between the models?!\nimport pickle\nmodels = ['gpt2-small', 'gpt2-large'] # did not make a big difference 'lm-gpt2-large']\n\nvalsforall = {k:{kk:[] for kk in ['sm', 'vals', 'att']} for k in models}\n\nfor m in models: \n        \n    print(m)\n    \n    with open(directory+m+\"results_over_all_texts.pkl\", 'rb') as fname: \n            model_over_texts = pickle.load( fname)\n\n    for text_ind, text in enumerate(texts):\n\n        #print(text)\n\n        l_summary, h_summary, all_layer_vals = model_over_texts[text_ind]\n        \n        '''sm_inputs, val_norms, attns = all_layer_vals[:,0], all_layer_vals[:,1], all_layer_vals[:,2]\n        \n        # input to softmax for all layers.\n        print(sm_inputs.shape)\n        valsforall[m]['sm'] += list(sm_inputs)\n        valsforall[m]['vals'] += list(val_norms)\n        valsforall[m]['att'] += list(attns)\n        plt.hist(sm_inputs, bins=50, alpha=0.5, label=m, density=True)'''\n        #print('l and then h summary. these are the max sm inputs.')\n        #display(l_summary)\n        #display(h_summary)\n        plt.plot(l_summary.index, l_summary['mean'], label = 'Text '+str(text_ind))\n    plt.legend()\n    plt.ylabel('Mean of Head maxes')\n    plt.xlabel('Layer Number')\n    #plt.xlim(-max(sm_inputs),max(sm_inputs))\n    plt.title(r\"Mean effective $\\beta$ by Layer\"+ \"\\n\"+r\"(Larger $\\beta$ Means Smaller Hamming Distance)\")\n    plt.gcf().savefig(directory+'PerModelLayerAverageBetas_'+str(m)+'.png', dpi=250)\n    plt.show()\n\n    print('======================')\n    \n```\n\n\n```python\nmodels = ['gpt2-small', 'gpt2-large'] # did not make a big difference 'lm-gpt2-large']\n\nvalsforall = {k:{kk:[] for kk in ['sm', 'vals', 'att']} for k in models}\n\nacross_models, heads_across_models = [], []\nfor m in models: \n        \n    print(m)\n    if 'small' in m:\n        nlay = 12\n    else: \n        nlay = 36\n    \n    with open(directory+m+\"results_over_all_texts.pkl\", 'rb') as fname: \n            model_over_texts = pickle.load( fname)\n\n    max_seen = np.zeros((nlay,1))\n    \n    heads_max_seen = 0\n    \n    plt.figure(figsize=(6,5))\n            \n    for text_ind, text in enumerate(texts):\n\n        #print(text)\n\n        l_summary, h_summary, all_layer_vals = model_over_texts[text_ind]\n        \n        max_seen = np.concatenate([max_seen, \n                                   np.asarray(l_summary['max']).reshape(-1,1)], axis=1)\n        \n        if text_ind==0:\n            heads_max_seen = np.asarray(h_summary).reshape(h_summary.shape[0], h_summary.shape[1], 1)\n        else: \n            heads_max_seen = np.concatenate([heads_max_seen, \n                                   np.asarray(h_summary).reshape(h_summary.shape[0], h_summary.shape[1], 1)], axis=2)\n        \n        \n        '''sm_inputs, val_norms, attns = all_layer_vals[:,0], all_layer_vals[:,1], all_layer_vals[:,2]\n        \n        # input to softmax for all layers.\n        print(sm_inputs.shape)\n        valsforall[m]['sm'] += list(sm_inputs)\n        valsforall[m]['vals'] += list(val_norms)\n        valsforall[m]['att'] += list(attns)\n        plt.hist(sm_inputs, bins=50, alpha=0.5, label=m, density=True)'''\n        #print('l and then h summary. these are the max sm inputs.')\n        #display(l_summary)\n        #display(h_summary)\n        plt.plot(l_summary.index, l_summary['mean'], label = 'Text '+str(text_ind))\n    plt.axhline(10.1,  linestyle='dashed',label=r\"$\\beta_{CD}=10.1$\", color='red')\n    plt.axhline(15.9,  linestyle='dashed',label=r\"$\\beta_{SNR}=15.9$\", color='red')\n    #plt.axhline(19.3,  linestyle='dashed',label=r\"$\\beta=19.3$\", color='red')\n    plt.legend()\n    plt.ylabel(r'Mean $\\beta$ across heads for each layer')\n    plt.xlabel('Layer Number')\n    #plt.xlim(-max(sm_inputs),max(sm_inputs))\n    plt.title(r\"Mean effective $\\beta$ by Layer by Text Input\")\n    plt.gcf().savefig(directory+'PerTextPerModelLayerMeanBetas_'+str(m)+'.png', dpi=250)\n    plt.show()\n    \n    max_seen = np.nan_to_num(max_seen)\n    heads_max_seen =  np.nan_to_num(heads_max_seen)\n    plt.figure()\n    plt.plot(l_summary.index, max_seen.max(axis=1))\n    across_models.append((l_summary.index, max_seen.max(axis=1)))\n    \n    #plt.axhline(19.3,  linestyle='dashed',label=r\"$\\beta=19.3$\", color='red')\n    plt.axhline(10.1,  linestyle='dashed',label=r\"$\\beta_{CD}=10.1$\", color='red')\n    plt.axhline(15.9,  linestyle='dashed',label=r\"$\\beta_{SNR}=15.9$\", color='red')\n    #plt.axvline(35.5,  linestyle='dashed',label=r\"$\\beta_{Mem}=35.5$\", color='red')\n    plt.ylabel('Max across all heads and texts')\n    plt.legend()\n    plt.xlabel('Layer Number')\n    #plt.xlim(-max(sm_inputs),max(sm_inputs))\n    plt.title(r\"Max effective $\\beta$ by Layer\"+ \"\\n\"+r\"(Larger $\\beta$ Means Smaller Hamming Distance)\")\n    plt.gcf().savefig(directory+'PerModelLayerMaxBetas_'+str(m)+'.png', dpi=250)\n    plt.show()\n    \n    # ========\n    \n    plt.figure()\n    plt.hist(heads_max_seen.max(axis=2).flatten(), bins=50)\n    print(\"dim of heads being plotted\", heads_max_seen.max(axis=2).shape)\n    heads_across_models.append(heads_max_seen.max(axis=2))\n    \n    #plt.axvline(19.3,  linestyle='dashed',label=r\"$\\beta=19.3$\", color='red')\n    plt.ylabel('Counts')\n    plt.legend()\n    plt.xlabel(r'Effective $\\beta$s')\n    #plt.xlim(-max(sm_inputs),max(sm_inputs))\n    plt.title(r\"Max effective $\\beta$ for every head across texts\"+ \"\\n\"+r\"(Larger $\\beta$ Means Smaller Hamming Distance)\")\n    plt.gcf().savefig(directory+'PerModelLayerMaxHeadBetas_'+str(m)+'.png', dpi=250)\n    plt.show()\n\n    print('======================')\nmax_seen.shape\n\nfor v in across_models: \n    x, y = v\n    \n    plt.plot(x,y)\n\nplt.axhline(19.3,  linestyle='dashed',label=r\"$\\beta=19.3$\", color='red')\nplt.ylabel('Max across all heads and texts')\nplt.legend()\nplt.xlabel('Layer Number')\n#plt.xlim(-max(sm_inputs),max(sm_inputs))\nplt.title(r\"Max effective $\\beta$ by Layer\"+ \"\\n\"+r\"(Larger $\\beta$ Means Smaller Hamming Distance)\")\nplt.gcf().savefig(directory+'BothModelsLayerMaxBetas_'+str(m)+'.png', dpi=250)\nplt.show()\n\n# =======\nplt.figure()\nfor ind, v in enumerate(heads_across_models): \n    plt.hist(v.flatten(), bins=50, alpha=0.5, density=True, label=models[ind])\n\n#plt.axvline(19.3,  linestyle='dashed',label=r\"$\\beta=19.3$\", color='red')\nplt.axvline(10.1,  linestyle='dashed',label=r\"$\\beta_{CD}=10.1$\", color='red')\nplt.axvline(15.9,  linestyle='dashed',label=r\"$\\beta_{SNR}=15.9$\", color='red')\nplt.axvline(35.5,  linestyle='dashed',label=r\"$\\beta_{Mem}=35.5$\", color='red')\nplt.ylabel('Normalized Counts')\nplt.legend()\nplt.xlabel(r'Effective $\\beta$s')\n#plt.xlim(-max(sm_inputs),max(sm_inputs))\nplt.title(r\"Max effective $\\beta$ for every Head across Texts\")#+ \"\\n\"+r\"(Larger $\\beta$ Means Smaller Hamming Distance)\")\nplt.gcf().savefig(directory+'BothModelsLayerMaxHeadBetas_'+str(m)+'.png', dpi=250)\nplt.show()\n    \n```\n\n\n```python\n### How do results differ between the models?!\n\nmodels = ['gpt2-small', 'gpt2-large'] # did not make a big difference 'lm-gpt2-large']\n\n# aggregate over all texts for each model. \nsecond_plot = [] # storing values for second plot here so I can save them easily as separate figures. \n\nfor m in models: \n    \n    #print(m)\n    \n    with open(directory+m+\"results_over_all_texts.pkl\", 'rb') as fname: \n        model_over_texts = pickle.load( fname)\n\n    for text_ind, text in enumerate(texts):\n        #print(\"text ind\", text_ind)\n        #print(text)\n        \n        l_summary, h_summary, all_layers_res = model_over_texts[text_ind]\n        \n        if text_ind==0: \n            all_text_vals = all_layers_res\n        else: \n            all_text_vals = np.concatenate([all_text_vals, all_layers_res], axis=-1)\n            \n        #display(l_summary)\n        #display(h_summary)\n        \n    plt.hist(all_text_vals[:,0,:,:].flatten(), bins=500, alpha=0.5, label=m, density=True)\n    \n    second_plot.append((all_text_vals[:,2,:,:].flatten(), all_text_vals[:,1,:,:].flatten()))\n        \n#plt.axvline(19.3,  linestyle='dashed',label=r\"$\\beta=19.3$\", color='red')\nplt.legend()\nplt.title(\"Softmax Inputs Aggregated for all Inputs, Layers, Heads.\")\nplt.ylabel('Normalized Counts')\nplt.xlabel('Inputs to softmax')\n#plt.xlim(left=0)\nmax_x_val = np.max(all_text_vals[:,0,:,:].flatten()) # ignores a few outlier negative values that we don't care about. \nplt.xlim(-max_x_val,max_x_val)\nplt.gcf().savefig(directory+'AllModels|ValuesForAllTextsLayersHeads.png', dpi=250)\nplt.show()\n\n#------------------\nplt.figure()\nnumber_to_plot = 500000\n\nfor ind, els in enumerate(second_plot):\n    x, y = els\n    rand_inds = np.random.choice(np.arange(len(x)),number_to_plot, replace =False)\n    plt.scatter(x[rand_inds],y[rand_inds] ,alpha=0.2, label=models[ind])\nplt.axhline(1.0,  linestyle='dashed',label=\"$y=1.0$\", color='red')\n\nlgnd = plt.legend()\nfor lh in lgnd.legendHandles: \n    lh.set_alpha(1)\nplt.title(\"Value Vector Norms as a Function of Attention Weight \\n for all Inputs, Layers, Heads.\")\nplt.ylabel('Value Vector $L^2$ Norm')\nplt.xlabel('Attention weight')\nplt.gcf().savefig(directory+'AllModels|ValueVectorAttentionScatterForAllTextsLayersHeads.png', dpi=250)\nplt.show()\n\n#------------------ Multiplying value vector by attention \nplt.figure()\nnumber_to_plot = 500000\n\nfor ind, els in enumerate(second_plot):\n    x, y = els\n    rand_inds = np.random.choice(np.arange(len(x)),number_to_plot, replace =False)\n    plt.scatter(x[rand_inds],x[rand_inds]*y[rand_inds] ,alpha=0.2, label=models[ind])\nxrang = np.linspace(0,1,100)\nplt.plot(xrang, xrang, linestyle='dashed',label=\"$L^2=1$\", color='red')\nlgnd = plt.legend()\nfor lh in lgnd.legendHandles: \n    lh.set_alpha(1)\nplt.title(\"Value Vector $L^2$ Norms multiplied by Attention Weight \\n for all Inputs, Layers, Heads.\")\nplt.ylabel('Value Vector $L^2$ Norm * Attention')\nplt.xlabel('Attention weight')\nplt.gcf().savefig(directory+'AllModels|ValueVectorTimesAttentionScatterForAllTextsLayersHeads.png', dpi=250)\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "d24f9fbc8dab3c9502e399a4d70607ac3774f3b4", "size": 894639, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "HugFace/Transformer_Empirical_Analysis.ipynb", "max_stars_repo_name": "TrentBrick/attention-approximates-sdm", "max_stars_repo_head_hexsha": "4cb44d825408a2e5af488ef166a9aa82ad2a2b31", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-11-27T20:01:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T13:34:36.000Z", "max_issues_repo_path": "HugFace/Transformer_Empirical_Analysis.ipynb", "max_issues_repo_name": "TrentBrick/attention-approximates-sdm", "max_issues_repo_head_hexsha": "4cb44d825408a2e5af488ef166a9aa82ad2a2b31", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HugFace/Transformer_Empirical_Analysis.ipynb", "max_forks_repo_name": "TrentBrick/attention-approximates-sdm", "max_forks_repo_head_hexsha": "4cb44d825408a2e5af488ef166a9aa82ad2a2b31", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 519.5348432056, "max_line_length": 72628, "alphanum_fraction": 0.9100028056, "converted": true, "num_tokens": 13834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2974699426047947, "lm_q2_score": 0.05340332377362638, "lm_q1q2_score": 0.015885883657845906}}
{"text": "# Jupyter Notebooks Notes \n\n\n## Table Of Content\n\n- [Overview](#Overview)\n- [Create Table of Content](#Create-Table-of-Content)\n- [Jupyter Notebook Getting Started](#Jupyter-Notebook-Getting-Started) \n    - [Installing Jupyter Notebooks](#Installing-Jupyter-Notebooks) \n        - [Running Jutpiter Notebook](#Running-Jutpiter-Notebook)\n        - [Uploading Notebook to Anconda Cloud](#Uploading-Notebook-to-Anconda-Cloud)\n- [Keyboard Shortcuts](#Keyboard-Shortcuts)\n- [Notebook Syntax](#Notebook-Syntax)\n    - [Tables](#Tables)\n    - [Images and Videos](#Images-and-Videos)\n    - [LaTeX Equations](#LaTeX-Equations)\n    - [Maxwell's Equations](#Maxwell%E2%80%99s-Equations)\n- [Basic Magics](#Basic-Magics)\n- [Local Custom Styles](#Local-Custom-Styles)\n- [Global Custom Styles](#Global-Custom-Styles)\n\n\n## Overview\nThe Jupyter Notebooks is an open-source web application that allows to <span class=\"yellow\">create and share documents that contain live code, equations, visualizations and narrative text</span>. This includes: data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more. The Jupyter Notebook app supports [Python](https://www.python.org/) and several other languages. For more information see [Jupyter](http://jupyter.org/). \n<span class=\"yellow\">Jupyter Notebooks is a brillant mechanism to keep notes and experiment with Python language. You can build snippets of code, annotate them, and execute them.</span> \n<a href=\"http://jupyter.org/\" target=\"_blank\" title=\"http://jupyter.org/\"></a>\n\n\n### Create Table of Content \nTo create a table of content for a Notebook, you can use the predifined header links and include them in the standard link construct such as [Maxwell's Equations](#Maxwell%E2%80%99s-Equations). \nYou can get the link value by mousing over the header for which you want to get the link and then right-click on the pilcrow &para;, also called the paragraph mark. From the dropdown menu select **Copy Link Address**. \n\nFrom the link just copy the last part prefixed by the # sign and used it as the value in the standard link construct.  \n\n\n## Jupyter Notebook Getting Started\nJupyter Notebook is a powerful tool for interactively developing and presenting data science projects. A notebook integrates code and its output into a single document that combines visualizations, narrative text, mathematical equations, and other rich media. The intuitive workflow promotes iterative and rapid development, making notebooks an increasingly popular choice at the heart of contemporary data science, analysis, and increasingly science at large. Best of all, as part of the open source Project Jupyter, they are completely free, For more information, see [Jupyter Notebook for Beginners: A Tutorial](https://www.dataquest.io/blog/jupyter-notebook-tutorial/).\n\n### What is an ipynb File?\nIt will be useful to understand what this file really is. Each .ipynb file is a text file that describes the contents of your notebook in a format called JSON. Each cell and its contents, including image attachments that have been converted into strings of text, is listed therein along with some metadata. You can edit this yourself \u2014 if you know what you are doing! \u2014 by selecting \u201cEdit > Edit Notebook Metadata\u201d from the menu bar in the notebook.\n\nYou can also view the contents of your notebook files by selecting \u201cEdit\u201d from the controls on the dashboard, but the keyword here is \u201ccan\u201c; there\u2019s no reason other than curiosity to do so unless you really know what you are doing.\n\n### Installing Jupyter Notebooks \nYou can run Jupyter Notebook online at . In these notes we run Jupyter on a Mac laptop in the integrated enviroment called **Anaconda** or **Conda** for short. It is an open source package management system and environment management system that runs on Windows, macOS and Linux. Conda quickly installs, runs and updates packages and their dependencies. Conda easily creates, saves, loads and switches between environments on your local computer. It was created for Python programs, but it can package and distribute software for any language. It also comes with integrated Jupyter Notebook. \nA suggested alternative to \"stand-alone\" Python is a package and environment mangement system such as [Conda](https://conda.io/docs/index.html). One big advantadge is the creation of **virtual enviroments** which do not intefer with the uderlying OS environment. The following are some of the Conda main advantadges:\n- Quickly installs, runs and updates packages and their dependencies. \n- Easily creates, saves, loads and switches between environments on your local computer. It was created for Python programs, but it can package and distribute software for any language.  \n- Conda as a package manager helps you find and install packages. \n- If you need a package that requires a different version of Python, with just a few commands, you can set up a totally separate environment to run that different version of Python, while continuing to run your usual version of Python in your normal environment.\n- That said, let's install Conda following the instructions found at [Downloading conda](https://conda.io/docs/user-guide/install/download.html). <span class=\"orange\">Install Anaconda Navigator, not Miniconda.</span>  \n- I also signed for the [Anaconda Cloud](http://anaconda.org). Where packages, notebooks, projects and environments are shared.\n- Please, see [notebooks-cheatsheet](https://www.cheatography.com/weidadeyue/cheat-sheets/jupyter-notebook/pdf_bw/) and [Getting started with Conda](https://conda.io/docs/user-guide/getting-started.html).\n\n#### Running Jutpiter Notebook\n\n1. Activate the **Anaconda Navigator**. The following UI is displayed:\n\n1. Click the **Launch** button  Jupyter Notebook from the related button \nThe Jupyter Noteboook app will run on the local host on tha available port. \nFor example [http://localhost:8892/tree](http://localhost:8892/tree).\n1. Select the Notebook.  Notice that Jupyter Notebook runs from the direct\n\n#### Uploading Notebook to Anconda Cloud\nTo upload a notebbok file the cloud follow these steps:\n1. Activate your terminal console.\n1. Change the directory where the notebook file is.\n1. Login into the [Anaconda Cloud](http://anaconda.org) cloud by executing this command: `anaconda login`\n1. Upload the file by executing this command: `anaconda upload --force \"filename.ipynb\"`\n\n\n## Keyboard Shortcuts\nYou can get a list of keybord shortcuts under the menu at the top: **Help > Keyboard Shortcuts**, or by pressing **H** in command mode. \nAnother way to access keyboard shortcuts, and a handy way to learn them is to use the command palette: **Cmd + Shift + P** (or **Ctrl + Shift + P** on Linux and Windows).\n\n\n```python\n# Example of code snippet\ngreetings = \"hello world!\"\nprint(greetings)\n```\n\n    hello world!\n\n\n### Jupyter Notebook Keyboard Input Modes\nThe Jupyter Notebook has two different keyboard input modes. \n\n1. **Edit mode** allows you to type code or text into a cell and is indicated by a **green cell border**. \n2. **Command mode** binds the keyboard to notebook level commands and is indicated by a grey cell border with a blue left margin.\n\nSee also [28 Jupyter Notebook tips, tricks, and shortcuts](https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/).\n\n\n#### Jupyter Notebook Input Modes Keyboard Shortcuts\nThe following are the Mac OS X modifier keys you must be familiar with when using the shorcuts. See also [Making Sense of Mac Keyboard Symbols](http://osxdaily.com/2012/03/27/making-sense-of-mac-keyboard-symbols/).\n\n| Symbol| Meaning|\n|:----- |:-------| \n| \u2318    | Command|        \n| \u2303    | Control|\n| \u2325    | Option|\n| \u21e7    | Shift|\n| \u21a9    | Return|\n| \u2423     | Space|\n| \u21e5    | Tab|\n\nSee <div class=\"warning\">[Notebooks-Cheatsheet](https://www.cheatography.com/weidadeyue/cheat-sheets/jupyter-notebook/pdf_bw/)</div>           \n\n## Notebook Syntax \nAs you have noticed this document is a **Jupyter Notebook**. You can find more information at this location: [The Jupyter Notebook](https://jupyter-notebook.readthedocs.io/en/stable/notebook.html) and plenty of examples at [Notebook Examples](https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/examples_index.html).\nRefer akso to [Markdown Cells](https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Working%20With%20Markdown%20Cells.html#Markdown-Cells).\n\n### Tables\nYou can create tables with pipes | and hyphens -. Hyphens are used to create each column's header, while pipes separate each column. You must include a blank line before your table in order for it to correctly render.\n\n\n| First Header  | Second Header |\n| ------------- | ------------- |\n|   Content Cell| Content Cell  |\n| Content Cell  | Content Cell  |\n\nThe pipes on either end of the table are optional.\n\nCells can vary in width and do not need to be perfectly aligned within columns. There must be at least three hyphens in each column of the header row.\n\n| Command | Description |\n| --- | --- |\n| git status | List all new or modified files |\n| git diff | Show file differences that haven't been staged |\n\nFor more information, see [Organizing information with tables](https://help.github.com/articles/organizing-information-with-tables/).\n\n### Images and Videos\nThe following are images and videos which are located in a directory or subdirectory on the machine where the notebook file resides.\n\n|What|Media|\n|----|-----|\n|Vesuviana ||\n|Facendo un 'cazze|<video controls src=\"https://docs.google.com/uc?export=download&id=151_iDpkc4TM8yoFoqnek0bdKIMGK_S65\" width=\"300px\" height=\"300px\"/>|\n\n\nIf you want to share your notebook file then you must have the resources on a public server. The following is an example of an image located on the Google Drive.\n\n\n\n#### Using Images Stored in Google Drive\nThese are the steps to make an image sharable so it can be used in a notebook.\n\n1. In your Google Drive, create a public folder as follows:\n    1. Create a new folder and name it *Image*, for instance.\n    1. Right click the folder, just created and select **Share** from the drop-down menu.\n    1. In the popup dialog window, click the **Advanced** link in the bottom right. \n    1. In the section *Who has access* select *Public on the web - Anyone on the Internet can find an view*.\n    1. Click **Done** button. \n1. Store the image in the folder you just created.\n1. Right click on the image, and from the drop down menu select **Share**.\n1. Click the **Copy link** button. A link is copied in your clipboard.\n1. From the link copy the long image ID made of numbers and letters.\n1. Replace *imageID* in the following URL: https://docs.google.com/uc?export=download&id=<imageID> with the ID you copied in the previous step.  \n1. Copy this URL in the markdown image tag such as: \n1. Or in the image tag and changing the width, for example: \n\n\n#### Using Images Stored in GitHub\n\n\n\n\n#### Using Images Stored Locally\n\n\n\n\n\n\n### LaTeX Equations\nCourtesy of MathJax, you can include mathematical expressions both inline and displayed.\nSee also [LaTex Equations](https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Working%20With%20Markdown%20Cells.html#LaTeX-equations).\n \n$e^{i\\pi} + 1 = 0$\n$$e^x=\\sum_{i=0}^\\infty \\frac{1}{i!}x^i$$\n\n### Maxwell\u2019s Equations\nSee, also [Motivating Examples](https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Typesetting%20Equations.html#The-Lorenz-Equations).\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\   \\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n\n\n## Basic Magics\nMagics are handy commands built into the IPython kernel that make it easier to perform particular tasks. Although they often resemble unix commands, under the hood they are all implemented in Python. There exist far more magics than it would make sense to cover, but it\u2019s worth highlighting a variety of examples. We will start with a few basics before moving on to more interesting cases.\n\nThere are two categories of magic: **line magics** and **cell magics**. Respectively, they act on a single line or can be spread across multiple lines or entire cells. Quote and more borrowed from [Advanced Jupyter Notebooks Tutorial](https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/). \n\n\n```python\n# To see the available magics, you can execute the following command:\n%lsmagic\n```\n\n\n\n\n    Available line magics:\n    %alias  %alias_magic  %autocall  %automagic  %autosave  %bookmark  %cat  %cd  %clear  %colors  %config  %connect_info  %cp  %debug  %dhist  %dirs  %doctest_mode  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %less  %lf  %lk  %ll  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %lx  %macro  %magic  %man  %matplotlib  %mkdir  %more  %mv  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %popd  %pprint  %precision  %profile  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %rep  %rerun  %reset  %reset_selective  %rm  %rmdir  %run  %save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode\n    \n    Available cell magics:\n    %%!  %%HTML  %%SVG  %%bash  %%capture  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%markdown  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile\n    \n    Automagic is ON, % prefix IS NOT needed for line magics.\n\n\n\n\n```python\n%%HTML\n<h5>Using HTML</h5>\nThis is <em>really</em> neat!\n```\n\n\n<h5>Using HTML</h5>\nThis is <em>really</em> neat!\n\n\n\n```latex\n%%latex\nSome important equations:  \n$E = mc^2$ \n$e^{i pi} = -1$\n```\n\n\nSome important equations:  \n$E = mc^2$ \n$e^{i pi} = -1$\n\n\n\n```python\n# Autosave every 60 sec\n%autosave 60\n```\n\n\n\n    Autosaving every 60 seconds\n\n\n## Enhancing Charts with Seaborn\nOne of the most common exercises Jupyter Notebook users undertake is producing plots. But Matplotlib, Python\u2019s most popular charting library, isn\u2019t renowned for attractive results despite it\u2019s customisability. Seaborn instantly prettifies Matplotlib plots and even adds some additional features pertinent to data science, making your reports prettier and your job easier. It\u2019s included in the default Anaconda installation or easily installed via pip install seaborn. \nQuote and more borrowed from [Advanced Jupyter Notebooks Tutorial](https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/). \n\n\n```python\n# First, we\u2019ll import our libraries and load some data.\nimport matplotlib.pyplot as plt\nimport seaborn as sns\ndata = sns.load_dataset(\"tips\")\n\ndata.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>total_bill</th>\n      <th>tip</th>\n      <th>sex</th>\n      <th>smoker</th>\n      <th>day</th>\n      <th>time</th>\n      <th>size</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>16.99</td>\n      <td>1.01</td>\n      <td>Female</td>\n      <td>No</td>\n      <td>Sun</td>\n      <td>Dinner</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>10.34</td>\n      <td>1.66</td>\n      <td>Male</td>\n      <td>No</td>\n      <td>Sun</td>\n      <td>Dinner</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>21.01</td>\n      <td>3.50</td>\n      <td>Male</td>\n      <td>No</td>\n      <td>Sun</td>\n      <td>Dinner</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>23.68</td>\n      <td>3.31</td>\n      <td>Male</td>\n      <td>No</td>\n      <td>Sun</td>\n      <td>Dinner</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>24.59</td>\n      <td>3.61</td>\n      <td>Female</td>\n      <td>No</td>\n      <td>Sun</td>\n      <td>Dinner</td>\n      <td>4</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# We can easily plot total_bill vs tip in Matplotlib.\nplt.scatter(data.total_bill, data.tip);\n```\n\n\n```python\n# Plotting in Seaborn is just as easy! \n# Seaborn is closely integrated with pandas data structures, \n# its own scatter plot function unlocks additional features.\nsns.scatterplot(x=\"total_bill\", y=\"tip\", data=data);\n\n```\n\n\n```python\n# Let\u2019s color by the size of the party paying the bill while also \n# discriminating between smokers and non-smokers.\nsns.scatterplot(x=\"total_bill\", y=\"tip\", hue=\"size\", style=\"smoker\", data=data);\n```\n\n## Custom Styles \nThe styles shown in this section work on your local machine, 'cause the style *custom.css* file is local, in the case of Jupyter Notebooks. The file is located at \n<span class=\"m_warning\">/Users/user name/.jupyter/custom/custom.css</span> on the Mac computer.  But they do not work if the file is on a public server such as Anaconda cloud or GitHub. To solve the problem we make the *custom.css* file available globally on GitHub and run a script similar to the following in the markdown file:\n\n```\nfrom IPython.core.display import HTML\n\ndef set_css_style(css_file_path):\n    \"\"\"\n    Read the custom CSS file and load it into Jupyter.\n    Pass the file path to the CSS file.\n    \"\"\"\n    styles = open(css_file_path, \"r\").read()\n    return HTML(styles)\nset_css_style('../Css/custom.css')\n\n```\n\n\n### Style Examples\n\n#### Markers\n***\n<span class=\"m_danger\">Danger</span> \n<span class=\"m_warning\">Warning</span>\n<span class=\"m_success\">Success</span> \n<span class=\"m_info\">Info</span>\n<span class=\"m_other\">Other</span>\n\n\n#### Notes\n***\n<div class=\"danger\">Danger</div>\n<div class=\"warning\">Warning</div>\n<div class=\"success\">Success</div>\n<div class=\"info\">Info</div>\n<div class=\"other\">Other</div>\nfrom IPython.core.display import HTML\n\n\n\n```python\nfrom IPython.core.display import HTML\n\ndef set_css_style(css_file_path):\n    \"\"\"\n    Read the custom CSS file and load it into Jupyter.\n    Pass the file path to the CSS file.\n    \"\"\"\n    styles = open(css_file_path, \"r\").read()\n    return HTML(styles)\nset_css_style('../Css/custom.css')\n```\n\n\n\n\n\n<style>\n\n/* Github and Jupyter Notebook Markdown Custom Styles */\n\n/* Note Red */\n.danger {\n  background-color: #ffdddd;\n  border-left: 6px solid #f44336;\n}\n\n/* Note Green */\n.success {\n  background-color: #ddffdd;\n  border-left: 6px solid #4caf50;\n}\n\n/* Note Blue */\n.info {\n  background-color: #e7f3fe;\n  border-left: 6px solid #2196f3;\n}\n\n/* Note Yellow */\n.warning {\n  background-color: #ffffcc;\n  border-left: 6px solid #ffeb3b;\n}\n\n/* Note Gray */\n.other {\n  background-color: #e7e7e7;\n  border-left: 6px solid #696965;\n}\n\n/* Marker Yellow */\n.m_warning {\n  background-color: yellow;\n}\n\n/* Marker Gray */\n.m_other {\n  background-color: lightgray;\n}\n\n/* Marker Blue */\n.m_info {\n  background-color: lightblue;\n}\n\n/* Marker Orange */\n.m_danger {\n  background-color: #ffdddd;\n}\n\n.m_success {\n  background-color: #ddffdd;\n} \n</style>\n\n\n\n<a id=\"custom_styles\"></a>\n\n# Mac Notes\n[Making Sense of Mac Keyboard Symbols](http://osxdaily.com/2012/03/27/making-sense-of-mac-keyboard-symbols/)\n\n## Password Protected File\n1. Open the file.\n1. In the File menu select **Save As**.\n1. In the popup dialog window, check **Save with password** box.\n1. Click the **Replace** button.\n1. In the popup dialog enteer the password you want to use.\n\n<div class=\"danger\">Write down the password and keep it an a safe place.</div>\n\n\n# References\n- [Jupyter Notebook Documentation](https://jupyter-notebook.readthedocs.io/en/stable/)\n- [Markdown Guide](http://markdown-guide.readthedocs.io/en/latest/index.html)\n- [28 Jupyter Notebook tips, tricks and shortcuts](https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/)\n- [Jupyter Notebook Tutorial: The Definitve Guide](https://www.datacamp.com/community/tutorials/tutorial-jupyter-notebook)\n- [Making Sense of Mac Keyboard Symbols](http://osxdaily.com/2012/03/27/making-sense-of-mac-keyboard-symbols/)\n- [3d surface plot in Plotly](https://nbviewer.jupyter.org/gist/jackparmer/8d7e979bc4cec23db057)\n\nmore .....\n", "meta": {"hexsha": "825a06e3c82f532c1149488ca120858a9f69a687", "size": 97069, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Jupyter/.ipynb_checkpoints/JupyterNotebooksNotes-checkpoint.ipynb", "max_stars_repo_name": "milexm/TechnicalNotes", "max_stars_repo_head_hexsha": "cc5f41611842b2e8918731f72583fb6624d1272b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Jupyter/.ipynb_checkpoints/JupyterNotebooksNotes-checkpoint.ipynb", "max_issues_repo_name": "milexm/TechnicalNotes", "max_issues_repo_head_hexsha": "cc5f41611842b2e8918731f72583fb6624d1272b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-01T15:48:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-01T15:48:33.000Z", "max_forks_repo_path": "Jupyter/JupyterNotebooksNotes.ipynb", "max_forks_repo_name": "milexm/TechnicalNotes", "max_forks_repo_head_hexsha": "cc5f41611842b2e8918731f72583fb6624d1272b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 111.3176605505, "max_line_length": 35088, "alphanum_fraction": 0.8244032595, "converted": true, "num_tokens": 5430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1540575510396274, "lm_q2_score": 0.10230470994540249, "lm_q1q2_score": 0.01576081307400812}}
{"text": "**This is not under MIT license.** It is intended for testing and might contain proprietary code.\n\n\n```python\nimport exercises\nfrom qa_display_widgets import FillGapsBox\n\nexerc = exercises.SolveForXLinear(2)\nFillGapsBox(exerc).box()\n```\n\n\n\n\n```python\nimport main\nmain.SolveForXLinear(3).display()\n```\n\n\n```python\nimport ipywidgets as widgets\nimport traitlets\nfrom IPython.display import display\n```\n\n\n```python\nimport main\nimport sympy\nfrom IPython.display import Math\nsympy.init_printing()\n```\n\n\n```python\nfrom ipywidgets import Layout, Button, Box\n\nitems_layout = Layout(flex='1 1 auto',\n                      width='auto')     # override the default width of the button to 'auto' to let the button grow\n\nbox_layout = Layout(display='flex',\n                    flex_flow='column', \n                    align_items='stretch', \n                    border='solid',\n                    width='50%')\n\nwords = ['correct', 'horse', 'battery', 'staple']\nitems = [Button(description=w, layout=items_layout, button_style='danger') for w in words]\nbox = Box(children=items, layout=box_layout)\nbox\n```\n\n\n```python\nfrom ipywidgets import Layout, Button, Box\n\nitems_layout = Layout(width='auto')     # override the default width of the button to 'auto' to let the button grow\n\nbox_layout = Layout(display='flex',\n                    flex_flow='column', \n                    align_items='stretch', \n                    border='solid',\n                    width='50%')\n\nwords = ['correct', 'horse', 'battery', 'staple']\nitems = [Button(description=w, layout=items_layout, button_style='danger') for w in words]\nbox = Box(children=items, layout=box_layout)\nbox\n```\n\n\n\n\n```python\nb1 = Button(description='My button')\nb1.style.background = '/home/blue/PycharmProjects/ipy_student_exercises/own_images/simple_grey_button.png'\nb1\n```\n\n\n\n\n```python\nfrom IPython.display import HTML \nHTML(\"\"\" <style>\n.widget-button {\n  background-image: ;\n  background-position: 50% 50%;\n  background-size: cover;\n}\n</style> \"\"\")\n```\n\n\n\n\n <style>\n.widget-button {\n  background-image: ;\n  background-position: 50% 50%;\n  background-size: cover;\n}\n</style> \n\n\n\n\n```python\nfrom ipywidgets import Layout, Button, Box\n\nitems = [\n    Button(description='1'),\n    Button(description='2', layout=Layout(flex='0.1 1 auto')),\n    Button(description='1'),\n ]\n\nbox_layout = Layout(display='flex',\n                    flex_flow='row', \n                    align_items='stretch', \n                    border='solid',\n                    width='100%')\nbox = Box(children=items, layout=box_layout)\nbox\n```\n", "meta": {"hexsha": "9af2fe587705ef2d6992aee055e7d797405e7ef8", "size": 5906, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "exp_notebook.ipynb", "max_stars_repo_name": "FermiParadox/ipy_student_exercises", "max_stars_repo_head_hexsha": "9e74406255c01672516b2d06dabc6e5f6822e3ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exp_notebook.ipynb", "max_issues_repo_name": "FermiParadox/ipy_student_exercises", "max_issues_repo_head_hexsha": "9e74406255c01672516b2d06dabc6e5f6822e3ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exp_notebook.ipynb", "max_forks_repo_name": "FermiParadox/ipy_student_exercises", "max_forks_repo_head_hexsha": "9e74406255c01672516b2d06dabc6e5f6822e3ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3438735178, "max_line_length": 124, "alphanum_fraction": 0.5037250254, "converted": true, "num_tokens": 613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.04336579660028471, "lm_q1q2_score": 0.01574044873873064}}
{"text": "# Plot multi-tree model views\n\nTo demonstrate how the multi-tree models work, this notebook shows example views of a tree from an origin timepoint and subsequent subtrees added at later timepoints. These views should clarify the following points:\n\n  - topological variation between timepoints\n  - width of training and validation time windows\n  - clade assignments by timepoint\n  - clade linkage between timepoints by traversal\n\n\n## Imports\n\n\n```python\nfrom augur.titer_model import TiterCollection\nfrom augur.utils import json_to_tree\nimport json\nimport matplotlib as mpl\nfrom matplotlib import gridspec\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import LineCollection\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\n%matplotlib inline\n```\n\n\n```python\nsns.set_style(\"ticks\")\nplt.style.use(\"huddlej\")\n```\n\n\n```python\nmpl.rcParams['savefig.dpi'] = 120\nmpl.rcParams['figure.dpi'] = 120\nmpl.rcParams['font.weight'] = 300\nmpl.rcParams['axes.labelweight'] = 300\nmpl.rcParams['font.size'] = 14\n```\n\n\n```python\ntip_size = 14\n```\n\n\n```python\nend_date = 2003.0\n```\n\n## Load trees\n\n\n```python\nwith open(\"../results/auspice/flu_h3n2_10_sample_0_1994-10-01_2015-10-01_2001-10-01_ha_tree.json\", \"r\") as fh:\n    origin_tree_json = json.load(fh)\n```\n\n\n```python\norigin_tree = json_to_tree(origin_tree_json)\n```\n\n\n```python\nwith open(\"../results/auspice/flu_h3n2_10_sample_0_1994-10-01_2015-10-01_2002-10-01_ha_tree.json\", \"r\") as fh:\n    next_tree_json = json.load(fh)\n```\n\n\n```python\nnext_tree = json_to_tree(next_tree_json)\n```\n\n## Plot origin tree\n\n\n```python\ndef plot_tree(tree, color_by_trait=None, initial_branch_width=5, tip_size=10,\n              start_date=None, end_date=None, include_color_bar=False, ax=None, colorbar_ax=None,\n              earliest_node_date=None, default_color=\"#cccccc\", override_y_values=None,\n              cmap=None):\n    \"\"\"Plot a BioPython Phylo tree in the BALTIC-style.\n    \"\"\"\n    # Plot H3N2 tree in BALTIC style from Bio.Phylo tree.\n    if override_y_values is None:\n        override_y_values = {}\n        \n    yvalues = [node.yvalue for node in tree.find_clades()]\n    y_span = max(yvalues)\n    y_unit = y_span / float(len(yvalues))\n\n    # Setup colors.\n    if color_by_trait:\n        trait_name = color_by_trait\n        \n        if cmap is None:\n            traits = [k.attr[trait_name] for k in tree.find_clades()]\n            norm = mpl.colors.Normalize(min(traits), max(traits))\n            cmap = mpl.cm.viridis\n\n    #\n    # Setup the figure grid.\n    #\n\n    if ax is None:\n        if include_color_bar:\n            fig = plt.figure(figsize=(8, 6), facecolor='w')\n            gs = gridspec.GridSpec(2, 1, height_ratios=[14, 1], width_ratios=[1], hspace=0.1, wspace=0.1)\n            ax = fig.add_subplot(gs[0])\n            colorbar_ax = fig.add_subplot(gs[1])\n        else:\n            fig = plt.figure(figsize=(8, 4), facecolor='w')\n            gs = gridspec.GridSpec(1, 1)\n            ax = fig.add_subplot(gs[0])\n\n    L=len([k for k in tree.find_clades() if k.is_terminal()])\n\n    # Setup arrays for tip and internal node coordinates.\n    tip_circles_x = []\n    tip_circles_y = []\n    tip_circles_color = []\n    tip_circle_sizes = []\n    node_circles_x = []\n    node_circles_y = []\n    node_circles_color = []\n    node_line_widths = []\n    node_line_segments = []\n    node_line_colors = []\n    branch_line_segments = []\n    branch_line_widths = []\n    branch_line_colors = []\n    branch_line_labels = []\n\n    for k in tree.find_clades(): ## iterate over objects in tree\n        x=k.attr[\"num_date\"] ## or from x position determined earlier\n        \n        if earliest_node_date and x < earliest_node_date:\n            continue\n        \n        if k.name in override_y_values:\n            y = override_y_values[k.name]\n        else:\n            y = y_span - k.yvalue ## get y position from .drawTree that was run earlier, but could be anything else\n\n        if k.parent is None:\n            xp = None\n        else:\n            xp=k.parent.attr[\"num_date\"] ## get x position of current object's parent\n\n        if x==None: ## matplotlib won't plot Nones, like root\n            x=0.0\n        if xp==None:\n            xp=x\n\n        c = default_color\n        if color_by_trait and trait_name in k.attr:\n            if isinstance(cmap, dict):\n                c = cmap[k.attr[trait_name]]\n            else:\n                c = cmap(norm(k.attr[trait_name]))\n\n        branchWidth=2\n        if k.is_terminal(): ## if leaf...\n            s = tip_size ## tip size can be fixed\n\n            tip_circle_sizes.append(s)\n            tip_circles_x.append(x)\n            tip_circles_y.append(y)\n            tip_circles_color.append(c)\n        else: ## if node...\n            k_leaves = [child\n                        for child in k.find_clades()\n                        if child.is_terminal()]\n\n            # Scale branch widths by the number of tips.\n            branchWidth += initial_branch_width * len(k_leaves) / float(L)\n\n            if len(k.clades)==1:\n                node_circles_x.append(x)\n                node_circles_y.append(y)\n                node_circles_color.append(c)\n\n            ax.plot([x,x],[y_span - k.clades[-1].yvalue, y_span - k.clades[0].yvalue], lw=branchWidth, color=c, ls='-', zorder=9, solid_capstyle='round')\n\n        branch_line_segments.append([(xp, y), (x, y)])\n        branch_line_widths.append(branchWidth)\n        branch_line_colors.append(c)\n\n    branch_lc = LineCollection(branch_line_segments, zorder=9)\n    branch_lc.set_color(branch_line_colors)\n    branch_lc.set_linewidth(branch_line_widths)\n    branch_lc.set_label(branch_line_labels)\n    branch_lc.set_linestyle(\"-\")\n    ax.add_collection(branch_lc)\n\n    # Add circles for tips and internal nodes.\n    tip_circle_sizes = np.array(tip_circle_sizes)\n    ax.scatter(tip_circles_x, tip_circles_y, s=tip_circle_sizes, facecolor=tip_circles_color, edgecolor='none',zorder=11) ## plot circle for every tip\n    ax.scatter(tip_circles_x, tip_circles_y, s=tip_circle_sizes*2, facecolor='k', edgecolor='none', zorder=10) ## plot black circle underneath\n    ax.scatter(node_circles_x, node_circles_y, facecolor=node_circles_color, s=50, edgecolor='none', zorder=10, lw=2, marker='|') ## mark every node in the tree to highlight that it's a multitype tree\n\n    #ax.set_ylim(-10, y_span - 300)\n\n    ax.spines['top'].set_visible(False) ## no axes\n    ax.spines['right'].set_visible(False)\n    ax.spines['left'].set_visible(False)\n\n    ax.tick_params(axis='y',size=0)\n    ax.set_yticklabels([])\n\n    if start_date:\n        ax.set_xlim(left=start_date)\n\n    if end_date:\n        ax.set_xlim(right=end_date)\n\n    if include_color_bar:\n        cb1 = mpl.colorbar.ColorbarBase(\n            colorbar_ax,\n            cmap=cmap,\n            norm=norm,\n            orientation='horizontal'\n        )\n        cb1.set_label(color_by_trait)\n\n    return ax, colorbar_ax\n```\n\n\n```python\nfig = plt.figure(figsize=(6, 4), facecolor='w')\ngs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)\nax = fig.add_subplot(gs[0])\n    \nax, colorbar_ax = plot_tree(origin_tree, ax=ax, start_date=1993.0, end_date=end_date, tip_size=tip_size)\nax.grid(axis='x',ls='-',color='grey')\n```\n\n## Plot next tree\n\nThis tree includes samples from the next year since the origin tree.\n\n\n```python\nfig = plt.figure(figsize=(6, 4), facecolor='w')\ngs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)\nax = fig.add_subplot(gs[0])\n    \nax, colorbar_ax = plot_tree(next_tree, ax=ax, start_date=1993.0, end_date=end_date, tip_size=tip_size)\n```\n\n## Overlay the two trees\n\nPlot all nodes from both trees.\n\n\n```python\nearliest_node_date = max([node.attr[\"num_date\"] for node in origin_tree.find_clades(terminal=True)])\n```\n\n\n```python\nearliest_node_date\n```\n\n\n\n\n    2001.7419575633128\n\n\n\n\n```python\norigin_y_values = [node.yvalue for node in origin_tree.find_clades()]\nmax_origin_y = max(origin_y_values)\noverride_y_values = {node.name: max_origin_y - node.yvalue for node in origin_tree.find_clades(terminal=True)}\n\nmax_next_y = max([node.yvalue for node in next_tree.find_clades()])\nmax_y = max(max_origin_y, max_next_y)\n```\n\n\n```python\nmax_y\n```\n\n\n\n\n    333\n\n\n\n\n```python\nfig = plt.figure(figsize=(8, 6), facecolor='w')\ngs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)\nax = fig.add_subplot(gs[0])\n    \nax, colorbar_ax = plot_tree(origin_tree, ax=ax, start_date=1993.0, end_date=end_date, tip_size=tip_size)\nax.set_ylim(top=max_y + 10)\n```\n\n\n```python\nfig = plt.figure(figsize=(8, 6), facecolor='w')\ngs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)\nax = fig.add_subplot(gs[0])\n    \nax, colorbar_ax = plot_tree(origin_tree, ax=ax, start_date=1993.0, end_date=end_date, tip_size=tip_size)\nax.axvline(x=earliest_node_date, color=\"#999999\", linestyle=\"--\")\nax.set_ylim(top=max_y + 10)\n```\n\n\n```python\nfig = plt.figure(figsize=(8, 6), facecolor='w')\ngs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)\nax = fig.add_subplot(gs[0])\n    \nax, colorbar_ax = plot_tree(origin_tree, ax=ax, start_date=1993.0, end_date=end_date, tip_size=tip_size)\nax.axvline(x=earliest_node_date, color=\"#999999\", linestyle=\"--\")\n\nax, colorbar_ax = plot_tree(\n    next_tree,\n    ax=ax,\n    start_date=1993.0,\n    end_date=end_date,\n    earliest_node_date=None,\n    default_color=\"powderblue\",\n    tip_size=tip_size\n)\n\nax.set_ylim(top=max_y + 10)\n```\n\n\n```python\nfig = plt.figure(figsize=(8, 6), facecolor='w')\ngs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)\nax = fig.add_subplot(gs[0])\n    \nax, colorbar_ax = plot_tree(origin_tree, ax=ax, start_date=1993.0, end_date=end_date, tip_size=tip_size)\nax.axvline(x=earliest_node_date, color=\"#999999\", linestyle=\"--\")\n\nax, colorbar_ax = plot_tree(\n    next_tree,\n    ax=ax,\n    start_date=1993.0,\n    end_date=end_date,\n    earliest_node_date=None,\n    default_color=\"powderblue\",\n    tip_size=tip_size,\n    override_y_values=override_y_values\n)\n\nax.set_ylim(top=max_y + 10)\n```\n\nNow plot only nodes from the next tree since the last sample in the origin tree.\n\n\n```python\ntip_size = 14\nfig = plt.figure(figsize=(8, 6), facecolor='w')\ngs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)\nax = fig.add_subplot(gs[0])\n    \nax, colorbar_ax = plot_tree(origin_tree, ax=ax, start_date=1993.0, end_date=end_date, tip_size=tip_size)\nax.axvline(x=earliest_node_date, color=\"#999999\", linestyle=\"--\")\n\nax, colorbar_ax = plot_tree(\n    next_tree,\n    ax=ax,\n    start_date=1993.0,\n    end_date=end_date,\n    earliest_node_date=earliest_node_date,\n    default_color=\"powderblue\",\n    tip_size=tip_size\n)\nax.set_ylim(top=max_y + 10)\n```\n\nHighlight the training and validation windows.\n\n\n```python\ntip_size = 14\nfig = plt.figure(figsize=(8, 6), facecolor='w')\ngs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)\nax = fig.add_subplot(gs[0])\n    \nax, colorbar_ax = plot_tree(origin_tree, ax=ax, start_date=1993.0, end_date=end_date, tip_size=tip_size)\n#ax.axvline(x=earliest_node_date, color=\"#999999\", linestyle=\"--\")\n\nax, colorbar_ax = plot_tree(\n    next_tree,\n    ax=ax,\n    start_date=1993.0,\n    end_date=end_date,\n    earliest_node_date=earliest_node_date,\n    tip_size=tip_size\n)\nax.set_ylim(top=max_y + 10)\n\n# Highlight training window.\nrectangle = plt.Rectangle((1994.75, 0), 6.0, max_y, fc='#00cc00',\n                          alpha=0.2, zorder=-10)\nax.add_patch(rectangle)\n\n# Highlight validation window.\nrectangle = plt.Rectangle((2001.75, 0), 1.0, max_y, fc='#ffcc33',\n                          alpha=0.5, zorder=-10)\nax.add_patch(rectangle)\n\nax.set_xticks(np.arange(1994.75, 2003.25, 0.5), minor=True)\n\nax.grid(\n    axis='x',\n    ls='-',\n    color='#cccccc',\n    alpha=0.5,\n    which=\"minor\"\n)\n```\n\n\n```python\norigin_tips = {tip.name: tip.attr[\"num_date\"] for tip in origin_tree.find_clades(terminal=True)}\nnext_tips = {tip.name: tip.attr[\"num_date\"] for tip in next_tree.find_clades(terminal=True)}\n```\n\n\n```python\nlen(next_tips)\n```\n\n\n\n\n    333\n\n\n\n\n```python\nlen(origin_tips)\n```\n\n\n\n\n    269\n\n\n\n\n```python\nearliest_node_date\n```\n\n\n\n\n    2001.7419575633128\n\n\n\n\n```python\n[(tip, date) for tip, date in next_tips.items() if tip not in origin_tips and date <= earliest_node_date]\n```\n\n\n\n\n    []\n\n\n\n\n```python\nfor tip in [tip for tip, date in next_tips.items() if tip not in origin_tips and date <= earliest_node_date]:\n    print(tip)\n```\n\n\n```python\nclades = set()\nfor node in origin_tree.find_clades():\n    clades.add(node.attr[\"clade_membership\"])\n\nfor node in next_tree.find_clades():\n    if node.attr[\"num_date\"] > earliest_node_date:\n        clades.add(node.attr[\"clade_membership\"])\n```\n\n\n```python\nlen(clades)\n```\n\n\n\n\n    37\n\n\n\n\n```python\ncmap = plt.get_cmap(\"tab20\")\n```\n\n\n```python\ncolor_by_clade = {clade: cmap(i % 20) for i, clade in enumerate(clades)}\n```\n\n\n```python\ntip_size = 14\nfig = plt.figure(figsize=(8, 6), facecolor='w')\ngs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)\nax = fig.add_subplot(gs[0])\n    \nax, colorbar_ax = plot_tree(\n    origin_tree,\n    ax=ax,\n    start_date=1993.0,\n    end_date=end_date,\n    tip_size=tip_size,\n    color_by_trait=\"clade_membership\",\n    cmap=color_by_clade,\n    default_color=\"#ffffff\"\n)\nax.axvline(x=earliest_node_date, color=\"#999999\", linestyle=\"--\")\n\nax, colorbar_ax = plot_tree(\n    next_tree,\n    ax=ax,\n    start_date=1993.0,\n    end_date=end_date,\n    earliest_node_date=earliest_node_date,\n    tip_size=tip_size,\n    color_by_trait=\"clade_membership\",\n    cmap=color_by_clade,\n    default_color=\"#ffffff\"\n)\nax.set_ylim(top=max_y + 10)\n\nax.set_xticks(np.arange(1994.75, 2003.25, 0.5), minor=True)\n\nax.grid(\n    axis='x',\n    ls='-',\n    color='#cccccc',\n    alpha=0.5,\n    which=\"minor\"\n)\n```\n\n\n```python\nfinal_tips_by_clades = pd.read_table(\"../results/builds/h3n2/10_viruses_per_month/sample_0/1994-10-01--2015-10-01/final_clade_frequencies.tsv\")\n```\n\n\n```python\nfinal_tips_by_clades.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>initial_timepoint</th>\n      <th>clade_membership</th>\n      <th>final_timepoint</th>\n      <th>strain</th>\n      <th>frequency</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1996-10-01</td>\n      <td>02e323e</td>\n      <td>1997-10-01</td>\n      <td>A/Auckland/10/1997</td>\n      <td>0.035959</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1996-10-01</td>\n      <td>02e323e</td>\n      <td>1997-10-01</td>\n      <td>A/HongKong/CUHK12160/1997</td>\n      <td>0.033047</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1996-10-01</td>\n      <td>02e323e</td>\n      <td>1997-10-01</td>\n      <td>A/HongKong/CUHK12563/1997</td>\n      <td>0.036006</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1996-10-01</td>\n      <td>02e323e</td>\n      <td>1997-10-01</td>\n      <td>A/HongKong/CUHK12626/1997</td>\n      <td>0.036066</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1996-10-01</td>\n      <td>02e323e</td>\n      <td>1997-10-01</td>\n      <td>A/HongKong/CUHK20236/1997</td>\n      <td>0.036691</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ntips_to_previous_clades = dict(\n    final_tips_by_clades.loc[final_tips_by_clades[\"initial_timepoint\"] == \"2001-10-01\", [\"strain\", \"clade_membership\"]].values\n)\n```\n\n\n```python\nfor tip in next_tree.find_clades(terminal=True):\n    if tip.name in tips_to_previous_clades:\n        tip.attr[\"previous_clade_membership\"] = tips_to_previous_clades[tip.name]\n    elif tip.attr[\"num_date\"] > earliest_node_date:\n        print(tip)\n```\n\n    A/HongKong/CUHK50080/2001\n    A/HongKong/CUHK50200/2002\n    A/NewYork/55/2001\n    A/NewYork/71/2001\n    A/NewYork/401/2001\n    A/WesternAustralia/17/2001\n    A/Auckland/603/2001\n\n\n\n```python\ntip_size = 14\nfig = plt.figure(figsize=(8, 6), facecolor='w')\ngs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)\nax = fig.add_subplot(gs[0])\n    \nax, colorbar_ax = plot_tree(\n    origin_tree,\n    ax=ax,\n    start_date=1993.0,\n    end_date=end_date,\n    tip_size=tip_size,\n    color_by_trait=\"clade_membership\",\n    cmap=color_by_clade,\n    default_color=\"#ffffff\"\n)\nax.axvline(x=earliest_node_date, color=\"#999999\", linestyle=\"--\")\n\nax, colorbar_ax = plot_tree(\n    next_tree,\n    ax=ax,\n    start_date=1993.0,\n    end_date=end_date,\n    earliest_node_date=earliest_node_date,\n    tip_size=tip_size,\n    color_by_trait=\"previous_clade_membership\",\n    cmap=color_by_clade,\n    default_color=\"#ffffff\"\n    #override_y_values=override_y_values\n)\nax.set_ylim(top=max_y + 10)\n\nax.set_xticks(np.arange(1994.75, 2003.25, 0.5), minor=True)\n\nax.grid(\n    axis='x',\n    ls='-',\n    color='#cccccc',\n    alpha=0.5,\n    which=\"minor\"\n)\n```\n\n\n```python\ntips_to_clades.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>tip</th>\n      <th>clade_membership</th>\n      <th>depth</th>\n      <th>lineage</th>\n      <th>segment</th>\n      <th>timepoint</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>A/NewYork/657/1994</td>\n      <td>726b03c</td>\n      <td>0</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>1996-10-01</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>A/NewYork/657/1994</td>\n      <td>f8b9dde</td>\n      <td>2</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>1996-10-01</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>A/NewYork/657/1994</td>\n      <td>root</td>\n      <td>3</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>1996-10-01</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>A/HongKong/42/1996</td>\n      <td>34f68f9</td>\n      <td>0</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>1996-10-01</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>A/HongKong/42/1996</td>\n      <td>726b03c</td>\n      <td>1</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>1996-10-01</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ntips_to_clades[(tips_to_clades[\"tip\"] == \"A/Auckland/603/2001\") & (tips_to_clades[\"timepoint\"] == \"2002-10-01\")]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>tip</th>\n      <th>clade_membership</th>\n      <th>depth</th>\n      <th>lineage</th>\n      <th>segment</th>\n      <th>timepoint</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>21284</th>\n      <td>A/Auckland/603/2001</td>\n      <td>fbbd597</td>\n      <td>0</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2002-10-01</td>\n    </tr>\n    <tr>\n      <th>21285</th>\n      <td>A/Auckland/603/2001</td>\n      <td>5bed3da</td>\n      <td>7</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2002-10-01</td>\n    </tr>\n    <tr>\n      <th>21286</th>\n      <td>A/Auckland/603/2001</td>\n      <td>05a6dc1</td>\n      <td>8</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2002-10-01</td>\n    </tr>\n    <tr>\n      <th>21287</th>\n      <td>A/Auckland/603/2001</td>\n      <td>f39e6da</td>\n      <td>10</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2002-10-01</td>\n    </tr>\n    <tr>\n      <th>21288</th>\n      <td>A/Auckland/603/2001</td>\n      <td>048f8ca</td>\n      <td>11</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2002-10-01</td>\n    </tr>\n    <tr>\n      <th>21289</th>\n      <td>A/Auckland/603/2001</td>\n      <td>e64cc68</td>\n      <td>15</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2002-10-01</td>\n    </tr>\n    <tr>\n      <th>21290</th>\n      <td>A/Auckland/603/2001</td>\n      <td>e2f3876</td>\n      <td>16</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2002-10-01</td>\n    </tr>\n    <tr>\n      <th>21291</th>\n      <td>A/Auckland/603/2001</td>\n      <td>d6906cf</td>\n      <td>17</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2002-10-01</td>\n    </tr>\n    <tr>\n      <th>21292</th>\n      <td>A/Auckland/603/2001</td>\n      <td>88dab64</td>\n      <td>18</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2002-10-01</td>\n    </tr>\n    <tr>\n      <th>21293</th>\n      <td>A/Auckland/603/2001</td>\n      <td>98c068a</td>\n      <td>19</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2002-10-01</td>\n    </tr>\n    <tr>\n      <th>21294</th>\n      <td>A/Auckland/603/2001</td>\n      <td>09e68a2</td>\n      <td>21</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2002-10-01</td>\n    </tr>\n    <tr>\n      <th>21295</th>\n      <td>A/Auckland/603/2001</td>\n      <td>e501908</td>\n      <td>22</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2002-10-01</td>\n    </tr>\n    <tr>\n      <th>21296</th>\n      <td>A/Auckland/603/2001</td>\n      <td>ecf49fd</td>\n      <td>23</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2002-10-01</td>\n    </tr>\n    <tr>\n      <th>21297</th>\n      <td>A/Auckland/603/2001</td>\n      <td>d7fecad</td>\n      <td>25</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2002-10-01</td>\n    </tr>\n    <tr>\n      <th>21298</th>\n      <td>A/Auckland/603/2001</td>\n      <td>02e323e</td>\n      <td>26</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2002-10-01</td>\n    </tr>\n    <tr>\n      <th>21299</th>\n      <td>A/Auckland/603/2001</td>\n      <td>35491c6</td>\n      <td>27</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2002-10-01</td>\n    </tr>\n    <tr>\n      <th>21300</th>\n      <td>A/Auckland/603/2001</td>\n      <td>root</td>\n      <td>29</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2002-10-01</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ntips_to_clades[(tips_to_clades[\"clade_membership\"] == \"fbbd597\") & (tips_to_clades[\"timepoint\"] == \"2001-10-01\")]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>tip</th>\n      <th>clade_membership</th>\n      <th>depth</th>\n      <th>lineage</th>\n      <th>segment</th>\n      <th>timepoint</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>14117</th>\n      <td>A/WesternAustralia/15/2001</td>\n      <td>fbbd597</td>\n      <td>2</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2001-10-01</td>\n    </tr>\n    <tr>\n      <th>14135</th>\n      <td>A/WesternAustralia/16/2001</td>\n      <td>fbbd597</td>\n      <td>2</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2001-10-01</td>\n    </tr>\n    <tr>\n      <th>14152</th>\n      <td>A/Queensland/14/2001</td>\n      <td>fbbd597</td>\n      <td>0</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2001-10-01</td>\n    </tr>\n    <tr>\n      <th>14169</th>\n      <td>A/Queensland/20/2001</td>\n      <td>fbbd597</td>\n      <td>0</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2001-10-01</td>\n    </tr>\n    <tr>\n      <th>14187</th>\n      <td>A/Auckland/604/2001</td>\n      <td>fbbd597</td>\n      <td>2</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2001-10-01</td>\n    </tr>\n    <tr>\n      <th>14205</th>\n      <td>A/Waikato/105/2001</td>\n      <td>fbbd597</td>\n      <td>2</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2001-10-01</td>\n    </tr>\n    <tr>\n      <th>14223</th>\n      <td>A/Auckland/602/2001</td>\n      <td>fbbd597</td>\n      <td>2</td>\n      <td>h3n2</td>\n      <td>ha</td>\n      <td>2001-10-01</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n\"fbbd597\" in clades\n```\n\n\n\n\n    True\n\n\n\n## Plot a subtree to demonstrate predictors\n\n\n```python\nsubtree = None\npotential_subtrees = [node for node in origin_tree.find_clades(terminal=False)\n                      if node.count_terminals() == 5]\n```\n\n\n```python\nlen(potential_subtrees)\n```\n\n\n\n\n    15\n\n\n\n\n```python\nsubtree = potential_subtrees[2]\n```\n\n\n```python\nfig = plt.figure(figsize=(8, 6), facecolor='w')\ngs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)\nax = fig.add_subplot(gs[0])\n\nax, colorbar_ax = plot_tree(subtree, tip_size=30, initial_branch_width=5, ax=ax)\nax.set_xticks([])\nax.spines['bottom'].set_visible(False)\n```\n\n## Math equations for predictors\n\nDelta frequency:\n\n$$\\frac{\\Delta{x}}{\\Delta{t}}$$\n\nInformation gain:\n\n$$\n\\sum_{v \\in K(t)}{Y_{v}(t + 1) \\log{\\frac{\\hat{Y}_{v}(t + 1)}{Y_v{}(t)}}}\n$$\n\nThe epitope cross-immunity predictor is defined as follows:\n\n$$\nf_{i}^{ep\\_x} = f_{0} - \\sigma_{ep\\_x} \\sum_{j:t_{j} < t_{i}}{x_{j}c(D_{ep}(a_{i}, a_{j}))}\n$$\n\nwhere $\\sigma_{ep}$ is a parameter learned from data.\n\nThe function $c(D_{ep})$ is defined as follows:\n\n$$\nc(D_{ep}) = \\exp(-D_{ep} / D_{0})\n$$\n\n\n### Hamming distance\n\nWeighted Hamming distance between viruses a and m:\n\n$$\n(x_{a}\\exp{(f_{a}\\Delta{t})})(x_{m})(d_{am})\n$$\n\nGeneral weighted Hamming distance between virus a and all other future viruses:\n\n$$\nH_{a} = x_{m}d_{am} + x_{n}d_{an} + x_{o}d_{ao}\n$$\n\nThen the overall weighted Hamming distance between all viruses at time t and t + 1 is given by:\n\n$$\nH(t) = H_{a}x_{a}\\exp{(f_{a}\\Delta{t})} + H_{b}x_{b}\\exp{(f_{b}\\Delta{t})} + H_{c}x_{c}\\exp{(f_{c}\\Delta{t})}\n$$\n\nActually, I think there is a problem with the above logic since there is not an estimator for the future Hamming distance but only a calculation of observed Hamming distance.\n\nThe observed weighted Hamming distance between virus a and all viruses in the next year would be:\n\n$$\n\\begin{align}\nH_{a}(t + 1) = x_{a}(t)(x_{m}(t + 1)d_{am} + \\\\\n                        x_{n}(t + 1)d_{an} + \\\\\n                        x_{o}(t + 1)d_{ao})\n\\end{align}\n$$\n\nThe estimated weighted Hamming distance when forecasting cannot include distances from future sequences. Instead, I think we need to estimate the composition of the future timepoint by projecting the current viruses forward by their fitnesses. The estimated distance is then between current and projected frequencies of viruses at the current timepoint.\n\n$$\n\\begin{align}\n\\hat{H}_{a}(t + 1) = x_{a}(t)(x_{a}(t)\\exp{(f_{a}\\Delta{t})}d_{aa} + \\\\\n                              x_{b}(t)\\exp{(f_{b}\\Delta{t})}d_{ab} + \\\\\n                              x_{c}(t)\\exp{(f_{c}\\Delta{t})}d_{ac})\n\\end{align}\n$$\n\nOr, a more computationally efficient approach for optimization would be:\n\n$$\n\\begin{align}\n\\hat{H}(t + 1) = x_{a}(t)\\exp{(f_{a}\\Delta{t})}(x_{b}(t)d_{ba} + x_{c}(t)d_{ca}) + \\\\\n                 x_{b}(t)\\exp{(f_{b}\\Delta{t})}(x_{a}(t)d_{ab} + x_{c}(t)d_{cb}) + \\\\\n                 x_{c}(t)\\exp{(f_{c}\\Delta{t})}(x_{a}(t)d_{ac} + x_{b}(t)d_{bc})\n\\end{align}\n$$\n\n\n```python\n\n```\n", "meta": {"hexsha": "fd051bb4ddeead141383f8031c0bdf29d6d20a79", "size": 995993, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "analyses/2019-04-25-plot-multi-tree-views.ipynb", "max_stars_repo_name": "blab/flu-forecasting", "max_stars_repo_head_hexsha": "723c515ba2e8813f081ae48b23d63871e9e3db4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-19T04:09:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-05T02:32:04.000Z", "max_issues_repo_path": "analyses/2019-04-25-plot-multi-tree-views.ipynb", "max_issues_repo_name": "elifesciences-publications/flu-forecasting", "max_issues_repo_head_hexsha": "1fee7ab1f755ad8ae5be28542045b5b609e4774b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analyses/2019-04-25-plot-multi-tree-views.ipynb", "max_forks_repo_name": "elifesciences-publications/flu-forecasting", "max_forks_repo_head_hexsha": "1fee7ab1f755ad8ae5be28542045b5b609e4774b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-01T11:45:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-01T11:45:41.000Z", "avg_line_length": 547.8509350935, "max_line_length": 114160, "alphanum_fraction": 0.9389694506, "converted": true, "num_tokens": 9064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.396068180531364, "lm_q2_score": 0.03963883527202279, "lm_q1q2_score": 0.01569968136457252}}
{"text": "## \u5176\u4ed6\u7684\u8fed\u4ee3\u73af\u5883\n\n### 1. for \u5faa\u73af\u4f7f\u7528\u4e86\u8fed\u4ee3\u534f\u8bae\uff1b\n### 2. \u4efb\u4f55\u4ece\u5de6\u5230\u53f3\u626b\u63cf\u5bf9\u8c61\u7684\u5de5\u5177\u90fd\u4f7f\u7528\u8fed\u4ee3\u534f\u8bae\uff1b\n\n\n```python\nfor line in open('untitled3.py'):\n    print(line.upper(), end = '')\n```\n\n    # -*- CODING: UTF-8 -*-\n    \"\"\"\n    CREATED ON TUE FEB 18 22:04:07 2020\n    \n    @AUTHOR: NICKC\n    \"\"\"\n    \n    #KOCHEDRAW1\n    IMPORT TURTLE\n    DEF KOCH(SIZE,N):\n      IF N==1:\n        TURTLE.FD(SIZE)\n      ELSE:\n        FOR I IN [0,60,-120,60]:\n          TURTLE.LEFT(I)\n          KOCH(SIZE/3,N-1)\n    DEF MAIN():\n      TURTLE.SETUP(600,600)\n      TURTLE.PENUP()\n      TURTLE.SPEED(10)\n      TURTLE.HIDETURTLE()\n      TURTLE.PENSIZE(2)\n      TURTLE.GOTO(-200,100)\n      TURTLE.PENDOWN()\n      LEVEL=4\n      KOCH(400,LEVEL)\n      TURTLE.RIGHT(120)\n      KOCH(400, LEVEL)\n      TURTLE.RIGHT(120)\n      KOCH(400, LEVEL)\n      TURTLE.PENUP()\n      TURTLE.DONE()\n    MAIN()\n\n### \u5217\u8868\u89e3\u6790\uff0cin\u7684\u5b50\u96c6\u6d4b\u8bd5\uff0c\u5185\u7f6e\u51fd\u6570map, sorted, zip \u90fd\u4f1a\u4f7f\u7528\u8fed\u4ee3\u534f\u8bae\n\n\n```python\nuppers = [line.upper() for line in open('untitled3.py')] #\u5217\u8868\u89e3\u6790\n```\n\n\n```python\nuppers\n```\n\n\n\n\n    ['# -*- CODING: UTF-8 -*-\\n',\n     '\"\"\"\\n',\n     'CREATED ON TUE FEB 18 22:04:07 2020\\n',\n     '\\n',\n     '@AUTHOR: NICKC\\n',\n     '\"\"\"\\n',\n     '\\n',\n     '#KOCHEDRAW1\\n',\n     'IMPORT TURTLE\\n',\n     'DEF KOCH(SIZE,N):\\n',\n     '  IF N==1:\\n',\n     '    TURTLE.FD(SIZE)\\n',\n     '  ELSE:\\n',\n     '    FOR I IN [0,60,-120,60]:\\n',\n     '      TURTLE.LEFT(I)\\n',\n     '      KOCH(SIZE/3,N-1)\\n',\n     'DEF MAIN():\\n',\n     '  TURTLE.SETUP(600,600)\\n',\n     '  TURTLE.PENUP()\\n',\n     '  TURTLE.SPEED(10)\\n',\n     '  TURTLE.HIDETURTLE()\\n',\n     '  TURTLE.PENSIZE(2)\\n',\n     '  TURTLE.GOTO(-200,100)\\n',\n     '  TURTLE.PENDOWN()\\n',\n     '  LEVEL=4\\n',\n     '  KOCH(400,LEVEL)\\n',\n     '  TURTLE.RIGHT(120)\\n',\n     '  KOCH(400, LEVEL)\\n',\n     '  TURTLE.RIGHT(120)\\n',\n     '  KOCH(400, LEVEL)\\n',\n     '  TURTLE.PENUP()\\n',\n     '  TURTLE.DONE()\\n',\n     'MAIN()']\n\n\n\n\n```python\n'@AUTHOR: NICKC\\n' in open('untitled3.py').read().upper() # in\u7684\u5b50\u96c6\u6d4b\u8bd5\n```\n\n\n\n\n    True\n\n\n\n\n```python\nmap(str.upper, open('untitled3.py')) # map\u5185\u7f6e\u51fd\u6570\n```\n\n\n\n\n    <map at 0x17ac5bdd608>\n\n\n\n\n```python\nlist(map(str.upper, open('untitled3.py')))\n```\n\n\n\n\n    ['# -*- CODING: UTF-8 -*-\\n',\n     '\"\"\"\\n',\n     'CREATED ON TUE FEB 18 22:04:07 2020\\n',\n     '\\n',\n     '@AUTHOR: NICKC\\n',\n     '\"\"\"\\n',\n     '\\n',\n     '#KOCHEDRAW1\\n',\n     'IMPORT TURTLE\\n',\n     'DEF KOCH(SIZE,N):\\n',\n     '  IF N==1:\\n',\n     '    TURTLE.FD(SIZE)\\n',\n     '  ELSE:\\n',\n     '    FOR I IN [0,60,-120,60]:\\n',\n     '      TURTLE.LEFT(I)\\n',\n     '      KOCH(SIZE/3,N-1)\\n',\n     'DEF MAIN():\\n',\n     '  TURTLE.SETUP(600,600)\\n',\n     '  TURTLE.PENUP()\\n',\n     '  TURTLE.SPEED(10)\\n',\n     '  TURTLE.HIDETURTLE()\\n',\n     '  TURTLE.PENSIZE(2)\\n',\n     '  TURTLE.GOTO(-200,100)\\n',\n     '  TURTLE.PENDOWN()\\n',\n     '  LEVEL=4\\n',\n     '  KOCH(400,LEVEL)\\n',\n     '  TURTLE.RIGHT(120)\\n',\n     '  KOCH(400, LEVEL)\\n',\n     '  TURTLE.RIGHT(120)\\n',\n     '  KOCH(400, LEVEL)\\n',\n     '  TURTLE.PENUP()\\n',\n     '  TURTLE.DONE()\\n',\n     'MAIN()']\n\n\n\n\n```python\nf = open('untitled3.py')\nenumerate(map(f.readline, open('untitled3.py'))) # map\u7684function\u9009\u9879\u53d6\u51b3\u4e8e\u540e\u9762\u4f5c\u7528\u5bf9\u8c61\u7684\u7c7b\u578b\n```\n\n\n\n\n    <enumerate at 0x17ac5d4f688>\n\n\n\n\n```python\nopen('untitled3.py').readline()\n```\n\n\n\n\n    '# -*- coding: utf-8 -*-\\n'\n\n\n\n\n```python\n[line for line in open('untitled3.py')]\n```\n\n\n\n\n    ['# -*- coding: utf-8 -*-\\n',\n     '\"\"\"\\n',\n     'Created on Tue Feb 18 22:04:07 2020\\n',\n     '\\n',\n     '@author: NickC\\n',\n     '\"\"\"\\n',\n     '\\n',\n     '#KocheDraw1\\n',\n     'import turtle\\n',\n     'def koch(size,n):\\n',\n     '  if n==1:\\n',\n     '    turtle.fd(size)\\n',\n     '  else:\\n',\n     '    for i in [0,60,-120,60]:\\n',\n     '      turtle.left(i)\\n',\n     '      koch(size/3,n-1)\\n',\n     'def main():\\n',\n     '  turtle.setup(600,600)\\n',\n     '  turtle.penup()\\n',\n     '  turtle.speed(10)\\n',\n     '  turtle.hideturtle()\\n',\n     '  turtle.pensize(2)\\n',\n     '  turtle.goto(-200,100)\\n',\n     '  turtle.pendown()\\n',\n     '  level=4\\n',\n     '  koch(400,level)\\n',\n     '  turtle.right(120)\\n',\n     '  koch(400, level)\\n',\n     '  turtle.right(120)\\n',\n     '  koch(400, level)\\n',\n     '  turtle.penup()\\n',\n     '  turtle.done()\\n',\n     'main()']\n\n\n\n\n```python\ndef function(x):\n    return x+' \\n'+ x\n```\n\n\n```python\nlist(map(function, open('untitled3.py')))\n```\n\n\n\n\n    ['# -*- coding: utf-8 -*-\\n \\n# -*- coding: utf-8 -*-\\n',\n     '\"\"\"\\n \\n\"\"\"\\n',\n     'Created on Tue Feb 18 22:04:07 2020\\n \\nCreated on Tue Feb 18 22:04:07 2020\\n',\n     '\\n \\n\\n',\n     '@author: NickC\\n \\n@author: NickC\\n',\n     '\"\"\"\\n \\n\"\"\"\\n',\n     '\\n \\n\\n',\n     '#KocheDraw1\\n \\n#KocheDraw1\\n',\n     'import turtle\\n \\nimport turtle\\n',\n     'def koch(size,n):\\n \\ndef koch(size,n):\\n',\n     '  if n==1:\\n \\n  if n==1:\\n',\n     '    turtle.fd(size)\\n \\n    turtle.fd(size)\\n',\n     '  else:\\n \\n  else:\\n',\n     '    for i in [0,60,-120,60]:\\n \\n    for i in [0,60,-120,60]:\\n',\n     '      turtle.left(i)\\n \\n      turtle.left(i)\\n',\n     '      koch(size/3,n-1)\\n \\n      koch(size/3,n-1)\\n',\n     'def main():\\n \\ndef main():\\n',\n     '  turtle.setup(600,600)\\n \\n  turtle.setup(600,600)\\n',\n     '  turtle.penup()\\n \\n  turtle.penup()\\n',\n     '  turtle.speed(10)\\n \\n  turtle.speed(10)\\n',\n     '  turtle.hideturtle()\\n \\n  turtle.hideturtle()\\n',\n     '  turtle.pensize(2)\\n \\n  turtle.pensize(2)\\n',\n     '  turtle.goto(-200,100)\\n \\n  turtle.goto(-200,100)\\n',\n     '  turtle.pendown()\\n \\n  turtle.pendown()\\n',\n     '  level=4\\n \\n  level=4\\n',\n     '  koch(400,level)\\n \\n  koch(400,level)\\n',\n     '  turtle.right(120)\\n \\n  turtle.right(120)\\n',\n     '  koch(400, level)\\n \\n  koch(400, level)\\n',\n     '  turtle.right(120)\\n \\n  turtle.right(120)\\n',\n     '  koch(400, level)\\n \\n  koch(400, level)\\n',\n     '  turtle.penup()\\n \\n  turtle.penup()\\n',\n     '  turtle.done()\\n \\n  turtle.done()\\n',\n     'main() \\nmain()']\n\n\n\n\n```python\nfrom sympy import tanh\ndef function(x):\n    return tanh(x).evalf()\n```\n\n\n```python\nlist(map(function,list(range(1,101))))\n```\n\n\n\n\n    [0.761594155955765,\n     0.964027580075817,\n     0.995054753686730,\n     0.999329299739067,\n     0.999909204262595,\n     0.999987711650796,\n     0.999998336943945,\n     0.999999774929676,\n     0.999999969540041,\n     0.999999995877693,\n     0.999999999442106,\n     0.999999999924497,\n     0.999999999989782,\n     0.999999999998617,\n     0.999999999999813,\n     0.999999999999975,\n     0.999999999999997,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000,\n     1.00000000000000]\n\n\n\n### map\u5f88\u50cf\u5217\u8868\u89e3\u6790\uff0c\u4f46\u662f\u6ca1\u6709\u5217\u8868\u89e3\u6790\u5f3a\u5927\uff0cmap\u9700\u8981\u51fd\u6570\u800c\u5217\u8868\u89e3\u6790\u53ef\u4ee5\u662f\u4efb\u610f\u7684\u8868\u8fbe\u5f0f\n\n\n```python\nS = \"\"\"Python includes various additional built-ins that process iterables, too: sorted sorts\nitems in an iterable, zip combines items from iterables, enumerate pairs items in an\niterable with relative positions, filter selects items for which a function is true, and\nreduce runs pairs of items in an iterable through a function. All of these accept iterables,\nand zip, enumerate, and filter also return an iterable in Python 3.0, like map. Here they\nare in action running the file\u2019s iterator automatically to scan line by line:\"\"\" # S \u662f\u4e2a\u5b57\u7b26\u4e32\n```\n\n\n```python\nL = S.split()\nprint(L, end='')\n```\n\n    ['Python', 'includes', 'various', 'additional', 'built-ins', 'that', 'process', 'iterables,', 'too:', 'sorted', 'sorts', 'items', 'in', 'an', 'iterable,', 'zip', 'combines', 'items', 'from', 'iterables,', 'enumerate', 'pairs', 'items', 'in', 'an', 'iterable', 'with', 'relative', 'positions,', 'filter', 'selects', 'items', 'for', 'which', 'a', 'function', 'is', 'true,', 'and', 'reduce', 'runs', 'pairs', 'of', 'items', 'in', 'an', 'iterable', 'through', 'a', 'function.', 'All', 'of', 'these', 'accept', 'iterables,', 'and', 'zip,', 'enumerate,', 'and', 'filter', 'also', 'return', 'an', 'iterable', 'in', 'Python', '3.0,', 'like', 'map.', 'Here', 'they', 'are', 'in', 'action', 'running', 'the', 'file\u2019s', 'iterator', 'automatically', 'to', 'scan', 'line', 'by', 'line:']\n\n\n```python\nprint(sorted(L), end = '') # \u5b57\u7b26\u4e32\u9996\u5148\u662f\u4ece1-100\uff0c\u4eceA\u5230Z, \u518d\u4ecea\u5230z\n```\n\n    ['3.0,', 'All', 'Here', 'Python', 'Python', 'a', 'a', 'accept', 'action', 'additional', 'also', 'an', 'an', 'an', 'an', 'and', 'and', 'and', 'are', 'automatically', 'built-ins', 'by', 'combines', 'enumerate', 'enumerate,', 'file\u2019s', 'filter', 'filter', 'for', 'from', 'function', 'function.', 'in', 'in', 'in', 'in', 'in', 'includes', 'is', 'items', 'items', 'items', 'items', 'items', 'iterable', 'iterable', 'iterable', 'iterable,', 'iterables,', 'iterables,', 'iterables,', 'iterator', 'like', 'line', 'line:', 'map.', 'of', 'of', 'pairs', 'pairs', 'positions,', 'process', 'reduce', 'relative', 'return', 'running', 'runs', 'scan', 'selects', 'sorted', 'sorts', 'that', 'the', 'these', 'they', 'through', 'to', 'too:', 'true,', 'various', 'which', 'with', 'zip', 'zip,']\n\n\n```python\nL1 = []\nfrom numpy import random\nfor i in range(100):\n    L1.append(random.randint(100))\n```\n\n\n```python\nprint(L1, end = '' )\n```\n\n    [10, 94, 39, 44, 19, 20, 78, 98, 40, 26, 48, 47, 60, 26, 91, 50, 94, 40, 34, 62, 93, 16, 0, 28, 40, 3, 55, 25, 46, 60, 90, 58, 68, 97, 50, 90, 9, 20, 69, 9, 33, 41, 65, 68, 73, 63, 70, 65, 77, 30, 28, 60, 11, 18, 44, 32, 94, 40, 19, 93, 13, 81, 42, 40, 85, 72, 74, 2, 50, 69, 77, 73, 44, 69, 80, 67, 11, 56, 6, 21, 89, 12, 91, 79, 63, 84, 71, 66, 65, 27, 71, 22, 45, 19, 4, 92, 44, 67, 92, 46]\n\n\n```python\nprint(sorted(L), end= '')\n```\n\n    [1, 1, 3, 3, 3, 4, 4, 4, 4, 6, 7, 8, 9, 10, 11, 11, 12, 12, 13, 14, 16, 17, 17, 19, 20, 21, 25, 27, 27, 28, 29, 29, 32, 32, 34, 35, 37, 38, 39, 43, 43, 44, 44, 45, 46, 48, 48, 49, 50, 51, 51, 53, 53, 54, 56, 58, 59, 59, 60, 60, 61, 61, 62, 63, 65, 65, 67, 67, 68, 72, 74, 75, 75, 76, 76, 76, 79, 82, 82, 82, 83, 84, 85, 85, 87, 87, 88, 88, 89, 89, 89, 90, 92, 93, 93, 97, 97, 97, 98, 98]\n\n\n```python\nL2 = []\nfor i in range(100,200):\n    L2.append(random.randint(100,200))\n```\n\n\n```python\nprint(L2, end='')\n```\n\n    [180, 158, 169, 160, 175, 132, 100, 110, 185, 187, 147, 117, 182, 156, 196, 196, 142, 158, 142, 156, 167, 178, 106, 177, 191, 106, 187, 190, 134, 184, 166, 104, 154, 131, 111, 157, 193, 150, 157, 192, 102, 140, 180, 103, 148, 197, 190, 179, 171, 117, 190, 188, 113, 129, 149, 171, 158, 145, 166, 104, 100, 191, 118, 136, 134, 148, 157, 117, 166, 171, 108, 135, 190, 119, 132, 181, 173, 142, 174, 142, 114, 111, 111, 170, 139, 153, 151, 170, 195, 198, 178, 197, 196, 115, 189, 193, 139, 103, 191, 165]\n\n\n```python\nprint(list(zip(L1, L2)), end= '')\n```\n\n    [(10, 180), (94, 158), (39, 169), (44, 160), (19, 175), (20, 132), (78, 100), (98, 110), (40, 185), (26, 187), (48, 147), (47, 117), (60, 182), (26, 156), (91, 196), (50, 196), (94, 142), (40, 158), (34, 142), (62, 156), (93, 167), (16, 178), (0, 106), (28, 177), (40, 191), (3, 106), (55, 187), (25, 190), (46, 134), (60, 184), (90, 166), (58, 104), (68, 154), (97, 131), (50, 111), (90, 157), (9, 193), (20, 150), (69, 157), (9, 192), (33, 102), (41, 140), (65, 180), (68, 103), (73, 148), (63, 197), (70, 190), (65, 179), (77, 171), (30, 117), (28, 190), (60, 188), (11, 113), (18, 129), (44, 149), (32, 171), (94, 158), (40, 145), (19, 166), (93, 104), (13, 100), (81, 191), (42, 118), (40, 136), (85, 134), (72, 148), (74, 157), (2, 117), (50, 166), (69, 171), (77, 108), (73, 135), (44, 190), (69, 119), (80, 132), (67, 181), (11, 173), (56, 142), (6, 174), (21, 142), (89, 114), (12, 111), (91, 111), (79, 170), (63, 139), (84, 153), (71, 151), (66, 170), (65, 195), (27, 198), (71, 178), (22, 197), (45, 196), (19, 115), (4, 189), (92, 193), (44, 139), (67, 103), (92, 191), (46, 165)]\n\n\n```python\nprint(list(enumerate(S.split(sep='.'))))\n```\n\n    [(0, 'Python includes various additional built-ins that process iterables, too: sorted sorts\\nitems in an iterable, zip combines items from iterables, enumerate pairs items in an\\niterable with relative positions, filter selects items for which a function is true, and\\nreduce runs pairs of items in an iterable through a function'), (1, ' All of these accept iterables,\\nand zip, enumerate, and filter also return an iterable in Python 3'), (2, '0, like map'), (3, ' Here they\\nare in action running the file\u2019s iterator automatically to scan line by line:')]\n\n\n\n```python\nprint(list(filter(str.isalpha, S.split()))) # \u5f53str.isalpha\u662f\u6b63\u786e\u7684\u65f6\u5019\uff0c\u5143\u7d20\u5c31\u4f1a\u8fc7\u6ee4\u8d77\u6765\n```\n\n    ['Python', 'includes', 'various', 'additional', 'that', 'process', 'sorted', 'sorts', 'items', 'in', 'an', 'zip', 'combines', 'items', 'from', 'enumerate', 'pairs', 'items', 'in', 'an', 'iterable', 'with', 'relative', 'filter', 'selects', 'items', 'for', 'which', 'a', 'function', 'is', 'and', 'reduce', 'runs', 'pairs', 'of', 'items', 'in', 'an', 'iterable', 'through', 'a', 'All', 'of', 'these', 'accept', 'and', 'and', 'filter', 'also', 'return', 'an', 'iterable', 'in', 'Python', 'like', 'Here', 'they', 'are', 'in', 'action', 'running', 'the', 'iterator', 'automatically', 'to', 'scan', 'line', 'by']\n\n\n\n```python\nsorted(open('untitled3.py'))\n```\n\n\n\n\n    ['\\n',\n     '\\n',\n     '      koch(size/3,n-1)\\n',\n     '      turtle.left(i)\\n',\n     '    for i in [0,60,-120,60]:\\n',\n     '    turtle.fd(size)\\n',\n     '  else:\\n',\n     '  if n==1:\\n',\n     '  koch(400, level)\\n',\n     '  koch(400, level)\\n',\n     '  koch(400,level)\\n',\n     '  level=4\\n',\n     '  turtle.done()\\n',\n     '  turtle.goto(-200,100)\\n',\n     '  turtle.hideturtle()\\n',\n     '  turtle.pendown()\\n',\n     '  turtle.pensize(2)\\n',\n     '  turtle.penup()\\n',\n     '  turtle.penup()\\n',\n     '  turtle.right(120)\\n',\n     '  turtle.right(120)\\n',\n     '  turtle.setup(600,600)\\n',\n     '  turtle.speed(10)\\n',\n     '\"\"\"\\n',\n     '\"\"\"\\n',\n     '# -*- coding: utf-8 -*-\\n',\n     '#KocheDraw1\\n',\n     '@author: NickC\\n',\n     'Created on Tue Feb 18 22:04:07 2020\\n',\n     'def koch(size,n):\\n',\n     'def main():\\n',\n     'import turtle\\n',\n     'main()']\n\n\n\n\n```python\nlist(zip(open(\"untitled3.py\"), open(\"untitled3.py\")))\n```\n\n\n\n\n    [('# -*- coding: utf-8 -*-\\n', '# -*- coding: utf-8 -*-\\n'),\n     ('\"\"\"\\n', '\"\"\"\\n'),\n     ('Created on Tue Feb 18 22:04:07 2020\\n',\n      'Created on Tue Feb 18 22:04:07 2020\\n'),\n     ('\\n', '\\n'),\n     ('@author: NickC\\n', '@author: NickC\\n'),\n     ('\"\"\"\\n', '\"\"\"\\n'),\n     ('\\n', '\\n'),\n     ('#KocheDraw1\\n', '#KocheDraw1\\n'),\n     ('import turtle\\n', 'import turtle\\n'),\n     ('def koch(size,n):\\n', 'def koch(size,n):\\n'),\n     ('  if n==1:\\n', '  if n==1:\\n'),\n     ('    turtle.fd(size)\\n', '    turtle.fd(size)\\n'),\n     ('  else:\\n', '  else:\\n'),\n     ('    for i in [0,60,-120,60]:\\n', '    for i in [0,60,-120,60]:\\n'),\n     ('      turtle.left(i)\\n', '      turtle.left(i)\\n'),\n     ('      koch(size/3,n-1)\\n', '      koch(size/3,n-1)\\n'),\n     ('def main():\\n', 'def main():\\n'),\n     ('  turtle.setup(600,600)\\n', '  turtle.setup(600,600)\\n'),\n     ('  turtle.penup()\\n', '  turtle.penup()\\n'),\n     ('  turtle.speed(10)\\n', '  turtle.speed(10)\\n'),\n     ('  turtle.hideturtle()\\n', '  turtle.hideturtle()\\n'),\n     ('  turtle.pensize(2)\\n', '  turtle.pensize(2)\\n'),\n     ('  turtle.goto(-200,100)\\n', '  turtle.goto(-200,100)\\n'),\n     ('  turtle.pendown()\\n', '  turtle.pendown()\\n'),\n     ('  level=4\\n', '  level=4\\n'),\n     ('  koch(400,level)\\n', '  koch(400,level)\\n'),\n     ('  turtle.right(120)\\n', '  turtle.right(120)\\n'),\n     ('  koch(400, level)\\n', '  koch(400, level)\\n'),\n     ('  turtle.right(120)\\n', '  turtle.right(120)\\n'),\n     ('  koch(400, level)\\n', '  koch(400, level)\\n'),\n     ('  turtle.penup()\\n', '  turtle.penup()\\n'),\n     ('  turtle.done()\\n', '  turtle.done()\\n'),\n     ('main()', 'main()')]\n\n\n\n\n```python\nlist(enumerate(open(\"untitled3.py\")))\n```\n\n\n\n\n    [(0, '# -*- coding: utf-8 -*-\\n'),\n     (1, '\"\"\"\\n'),\n     (2, 'Created on Tue Feb 18 22:04:07 2020\\n'),\n     (3, '\\n'),\n     (4, '@author: NickC\\n'),\n     (5, '\"\"\"\\n'),\n     (6, '\\n'),\n     (7, '#KocheDraw1\\n'),\n     (8, 'import turtle\\n'),\n     (9, 'def koch(size,n):\\n'),\n     (10, '  if n==1:\\n'),\n     (11, '    turtle.fd(size)\\n'),\n     (12, '  else:\\n'),\n     (13, '    for i in [0,60,-120,60]:\\n'),\n     (14, '      turtle.left(i)\\n'),\n     (15, '      koch(size/3,n-1)\\n'),\n     (16, 'def main():\\n'),\n     (17, '  turtle.setup(600,600)\\n'),\n     (18, '  turtle.penup()\\n'),\n     (19, '  turtle.speed(10)\\n'),\n     (20, '  turtle.hideturtle()\\n'),\n     (21, '  turtle.pensize(2)\\n'),\n     (22, '  turtle.goto(-200,100)\\n'),\n     (23, '  turtle.pendown()\\n'),\n     (24, '  level=4\\n'),\n     (25, '  koch(400,level)\\n'),\n     (26, '  turtle.right(120)\\n'),\n     (27, '  koch(400, level)\\n'),\n     (28, '  turtle.right(120)\\n'),\n     (29, '  koch(400, level)\\n'),\n     (30, '  turtle.penup()\\n'),\n     (31, '  turtle.done()\\n'),\n     (32, 'main()')]\n\n\n\n\n```python\nbool('0'), bool(0), bool('1'), bool('')\n```\n\n\n\n\n    (True, False, True, False)\n\n\n\n\n```python\nlist(filter(bool, open('untitled3.py')))\n```\n\n\n\n\n    ['# -*- coding: utf-8 -*-\\n',\n     '\"\"\"\\n',\n     'Created on Tue Feb 18 22:04:07 2020\\n',\n     '\\n',\n     '@author: NickC\\n',\n     '\"\"\"\\n',\n     '\\n',\n     '#KocheDraw1\\n',\n     'import turtle\\n',\n     'def koch(size,n):\\n',\n     '  if n==1:\\n',\n     '    turtle.fd(size)\\n',\n     '  else:\\n',\n     '    for i in [0,60,-120,60]:\\n',\n     '      turtle.left(i)\\n',\n     '      koch(size/3,n-1)\\n',\n     'def main():\\n',\n     '  turtle.setup(600,600)\\n',\n     '  turtle.penup()\\n',\n     '  turtle.speed(10)\\n',\n     '  turtle.hideturtle()\\n',\n     '  turtle.pensize(2)\\n',\n     '  turtle.goto(-200,100)\\n',\n     '  turtle.pendown()\\n',\n     '  level=4\\n',\n     '  koch(400,level)\\n',\n     '  turtle.right(120)\\n',\n     '  koch(400, level)\\n',\n     '  turtle.right(120)\\n',\n     '  koch(400, level)\\n',\n     '  turtle.penup()\\n',\n     '  turtle.done()\\n',\n     'main()']\n\n\n\n\n```python\nbool('0'), bool(0), bool('1'), bool('')\n```\n\n\n\n\n    (True, False, True, False)\n\n\n\n\n```python\nif 0:\n    print(\"Hello world\")\nif 1:\n    print(\"Hello world\")\n```\n\n    Hello world\n\n\n\n```python\nif bool('0'):\n    print(\"Hello world\")\nif bool(1):\n    print(\"Hello world\")\n```\n\n    Hello world\n    Hello world\n\n\n\n```python\nbool(\"\"), bool(''), bool(\"\"\"\"\"\")\n```\n\n\n\n\n    (False, False, False)\n\n\n\n\n```python\nimport functools, operator\nfunctools.reduce(operator.add, open('untitled3.py'))\n```\n\n\n\n\n    '# -*- coding: utf-8 -*-\\n\"\"\"\\nCreated on Tue Feb 18 22:04:07 2020\\n\\n@author: NickC\\n\"\"\"\\n\\n#KocheDraw1\\nimport turtle\\ndef koch(size,n):\\n  if n==1:\\n    turtle.fd(size)\\n  else:\\n    for i in [0,60,-120,60]:\\n      turtle.left(i)\\n      koch(size/3,n-1)\\ndef main():\\n  turtle.setup(600,600)\\n  turtle.penup()\\n  turtle.speed(10)\\n  turtle.hideturtle()\\n  turtle.pensize(2)\\n  turtle.goto(-200,100)\\n  turtle.pendown()\\n  level=4\\n  koch(400,level)\\n  turtle.right(120)\\n  koch(400, level)\\n  turtle.right(120)\\n  koch(400, level)\\n  turtle.penup()\\n  turtle.done()\\nmain()'\n\n\n\n\n```python\nfunctools.reduce?\n```\n\n\n    \u001b[1;31mDocstring:\u001b[0m\n    reduce(function, sequence[, initial]) -> value\n    \n    Apply a function of two arguments cumulatively to the items of a sequence,\n    from left to right, so as to reduce the sequence to a single value.\n    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items\n    of the sequence in the calculation, and serves as a default when the\n    sequence is empty.\n    \u001b[1;31mType:\u001b[0m      builtin_function_or_method\n\n\n\n\n```python\nS = 'import sys\\n' + 'print(sys.path)'\n```\n\n\n```python\nS \n```\n\n\n\n\n    'import sys\\nprint(sys.path)'\n\n\n\n### from sympy import tanh # tanh \u5c31\u4e0d\u662f\u5185\u7f6e\u51fd\u6570\n\n\n```python\nL = list(range(100))\n```\n\n\n```python\nfrom numpy import random\nL1 = []\nL2 = []\nfor i in range(100):\n    L1.append(random.randint(1,101)) # int \u5c31\u662finteger\u7684\u7f29\u5199\uff0c integer\u662f\u6574\u6570\u7684\u610f\u601d\nfor j in range(100):\n    L2.append(random.randint(1,101))\n```\n\n\n```python\nprint(L1, end=''); print('\\n'); print(L2, end='')\n```\n\n    [16, 17, 71, 95, 77, 79, 76, 65, 97, 98, 72, 23, 82, 1, 68, 11, 66, 30, 69, 19, 99, 19, 17, 23, 89, 48, 63, 55, 80, 63, 35, 92, 46, 76, 39, 72, 90, 13, 41, 37, 44, 93, 45, 17, 49, 97, 62, 37, 30, 4, 45, 18, 80, 7, 96, 14, 85, 18, 27, 55, 48, 43, 38, 99, 95, 86, 39, 13, 47, 76, 31, 40, 23, 54, 63, 50, 21, 44, 9, 84, 58, 38, 62, 62, 6, 18, 92, 5, 100, 2, 49, 10, 65, 88, 79, 53, 88, 79, 66, 72]\n    \n    [52, 60, 95, 5, 57, 8, 74, 93, 18, 46, 86, 24, 66, 71, 8, 90, 13, 38, 85, 24, 88, 95, 83, 27, 76, 52, 29, 35, 79, 54, 29, 27, 92, 57, 8, 70, 28, 95, 90, 41, 53, 86, 77, 93, 16, 18, 14, 5, 97, 3, 25, 44, 68, 57, 37, 78, 72, 46, 74, 33, 87, 52, 77, 40, 62, 64, 34, 60, 62, 65, 74, 22, 93, 40, 71, 32, 24, 6, 80, 4, 76, 46, 67, 33, 20, 40, 41, 19, 77, 54, 82, 80, 27, 99, 100, 80, 95, 37, 28, 44]\n\n\n```python\ntype(L1.sort()); print('\\n');print(sorted(L2), end='')\n```\n\n    \n    \n    [3, 4, 5, 5, 6, 8, 8, 8, 13, 14, 16, 18, 18, 19, 20, 22, 24, 24, 24, 25, 27, 27, 27, 28, 28, 29, 29, 32, 33, 33, 34, 35, 37, 37, 38, 40, 40, 40, 41, 41, 44, 44, 46, 46, 46, 52, 52, 52, 53, 54, 54, 57, 57, 57, 60, 60, 62, 62, 64, 65, 66, 67, 68, 70, 71, 71, 72, 74, 74, 74, 76, 76, 77, 77, 77, 78, 79, 80, 80, 80, 82, 83, 85, 86, 86, 87, 88, 90, 90, 92, 93, 93, 93, 95, 95, 95, 95, 97, 99, 100]\n\n### L1.sort() \u5bf9\u5bf9\u8c61\u672c\u8eab\u662f\u5373\u65f6\u751f\u6548\u7684\n\n\n```python\nprint(L1) # L1.sort() \u5bf9\u5bf9\u8c61\u672c\u8eab\u662f\u5373\u65f6\u751f\u6548\u7684\n```\n\n    [3, 3, 6, 7, 7, 8, 11, 12, 13, 14, 16, 19, 19, 22, 25, 25, 29, 32, 32, 34, 34, 37, 37, 39, 40, 41, 41, 44, 45, 45, 47, 48, 48, 51, 52, 53, 53, 53, 55, 55, 56, 57, 58, 59, 59, 60, 61, 61, 61, 63, 64, 65, 65, 66, 68, 70, 71, 72, 73, 74, 78, 78, 79, 80, 80, 81, 82, 84, 84, 84, 84, 85, 89, 89, 89, 89, 90, 90, 90, 90, 91, 92, 92, 93, 93, 94, 94, 94, 95, 95, 95, 96, 96, 97, 97, 97, 97, 98, 99, 99]\n\n\n### \u4e0d\u662f\u5373\u65f6\u751f\u6548\u7684\u4f8b\u5b50\n\n\n```python\na = L1\nprint( 'a = '+ str(a), end='')\nprint('\\n')\nb = a  # b\u662f\u7b49\u4e8e\u5217\u8868L1, \u800c\u4e0d\u662fa\u8fd9\u4e2a\u540d\u5b57\nprint('b = ' + str(b), end ='')\nprint('\\n')\na = a + L2\nprint('a = ' + str(a), end= \"\")\nprint('\\n')\nprint(b, end='')\n```\n\n    a = [1, 2, 4, 5, 6, 7, 9, 10, 11, 13, 13, 14, 16, 17, 17, 17, 18, 18, 18, 19, 19, 21, 23, 23, 23, 27, 30, 30, 31, 35, 37, 37, 38, 38, 39, 39, 40, 41, 43, 44, 44, 45, 45, 46, 47, 48, 48, 49, 49, 50, 53, 54, 55, 55, 58, 62, 62, 62, 63, 63, 63, 65, 65, 66, 66, 68, 69, 71, 72, 72, 72, 76, 76, 76, 77, 79, 79, 79, 80, 80, 82, 84, 85, 86, 88, 88, 89, 90, 92, 92, 93, 95, 95, 96, 97, 97, 98, 99, 99, 100]\n    \n    b = [1, 2, 4, 5, 6, 7, 9, 10, 11, 13, 13, 14, 16, 17, 17, 17, 18, 18, 18, 19, 19, 21, 23, 23, 23, 27, 30, 30, 31, 35, 37, 37, 38, 38, 39, 39, 40, 41, 43, 44, 44, 45, 45, 46, 47, 48, 48, 49, 49, 50, 53, 54, 55, 55, 58, 62, 62, 62, 63, 63, 63, 65, 65, 66, 66, 68, 69, 71, 72, 72, 72, 76, 76, 76, 77, 79, 79, 79, 80, 80, 82, 84, 85, 86, 88, 88, 89, 90, 92, 92, 93, 95, 95, 96, 97, 97, 98, 99, 99, 100]\n    \n    a = [1, 2, 4, 5, 6, 7, 9, 10, 11, 13, 13, 14, 16, 17, 17, 17, 18, 18, 18, 19, 19, 21, 23, 23, 23, 27, 30, 30, 31, 35, 37, 37, 38, 38, 39, 39, 40, 41, 43, 44, 44, 45, 45, 46, 47, 48, 48, 49, 49, 50, 53, 54, 55, 55, 58, 62, 62, 62, 63, 63, 63, 65, 65, 66, 66, 68, 69, 71, 72, 72, 72, 76, 76, 76, 77, 79, 79, 79, 80, 80, 82, 84, 85, 86, 88, 88, 89, 90, 92, 92, 93, 95, 95, 96, 97, 97, 98, 99, 99, 100, 52, 60, 95, 5, 57, 8, 74, 93, 18, 46, 86, 24, 66, 71, 8, 90, 13, 38, 85, 24, 88, 95, 83, 27, 76, 52, 29, 35, 79, 54, 29, 27, 92, 57, 8, 70, 28, 95, 90, 41, 53, 86, 77, 93, 16, 18, 14, 5, 97, 3, 25, 44, 68, 57, 37, 78, 72, 46, 74, 33, 87, 52, 77, 40, 62, 64, 34, 60, 62, 65, 74, 22, 93, 40, 71, 32, 24, 6, 80, 4, 76, 46, 67, 33, 20, 40, 41, 19, 77, 54, 82, 80, 27, 99, 100, 80, 95, 37, 28, 44]\n    \n    [1, 2, 4, 5, 6, 7, 9, 10, 11, 13, 13, 14, 16, 17, 17, 17, 18, 18, 18, 19, 19, 21, 23, 23, 23, 27, 30, 30, 31, 35, 37, 37, 38, 38, 39, 39, 40, 41, 43, 44, 44, 45, 45, 46, 47, 48, 48, 49, 49, 50, 53, 54, 55, 55, 58, 62, 62, 62, 63, 63, 63, 65, 65, 66, 66, 68, 69, 71, 72, 72, 72, 76, 76, 76, 77, 79, 79, 79, 80, 80, 82, 84, 85, 86, 88, 88, 89, 90, 92, 92, 93, 95, 95, 96, 97, 97, 98, 99, 99, 100]\n\n\n```python\nsum([i for i in range(101)])\n```\n\n\n\n\n    5050\n\n\n\n\n```python\nD = dict(enumerate(L1))\n```\n\n\n```python\ntype(D), type(L1), type(tuple(L1))\n```\n\n\n\n\n    (dict, list, tuple)\n\n\n\n\n```python\nprint(D, end ='')\n```\n\n    {0: 1, 1: 2, 2: 4, 3: 5, 4: 6, 5: 7, 6: 9, 7: 10, 8: 11, 9: 13, 10: 13, 11: 14, 12: 16, 13: 17, 14: 17, 15: 17, 16: 18, 17: 18, 18: 18, 19: 19, 20: 19, 21: 21, 22: 23, 23: 23, 24: 23, 25: 27, 26: 30, 27: 30, 28: 31, 29: 35, 30: 37, 31: 37, 32: 38, 33: 38, 34: 39, 35: 39, 36: 40, 37: 41, 38: 43, 39: 44, 40: 44, 41: 45, 42: 45, 43: 46, 44: 47, 45: 48, 46: 48, 47: 49, 48: 49, 49: 50, 50: 53, 51: 54, 52: 55, 53: 55, 54: 58, 55: 62, 56: 62, 57: 62, 58: 63, 59: 63, 60: 63, 61: 65, 62: 65, 63: 66, 64: 66, 65: 68, 66: 69, 67: 71, 68: 72, 69: 72, 70: 72, 71: 76, 72: 76, 73: 76, 74: 77, 75: 79, 76: 79, 77: 79, 78: 80, 79: 80, 80: 82, 81: 84, 82: 85, 83: 86, 84: 88, 85: 88, 86: 89, 87: 90, 88: 92, 89: 92, 90: 93, 91: 95, 92: 95, 93: 96, 94: 97, 95: 97, 96: 98, 97: 99, 98: 99, 99: 100}\n\n\n```python\nsum(D) == (0+99)*100/2\n```\n\n\n\n\n    True\n\n\n\n### any\u51fd\u6570\u6240\u4f5c\u7528\u7684\u5bf9\u8c61\u4e2d\u53ea\u8981\u6709\u4e00\u9879\u7684\u5e03\u5c14\u503c\u4e3aTrue\u5c31\u8fd4\u56deTrue\n\n\n```python\nany(['',''])\n```\n\n\n\n\n    False\n\n\n\n\n```python\nall(['spam','','ni'])\n```\n\n\n\n\n    False\n\n\n\n\n```python\nany?\n```\n\n\n    \u001b[1;31mSignature:\u001b[0m \u001b[0many\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0miterable\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m/\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n    \u001b[1;31mDocstring:\u001b[0m\n    Return True if bool(x) is True for any x in the iterable.\n    \n    If the iterable is empty, return False.\n    \u001b[1;31mType:\u001b[0m      builtin_function_or_method\n\n\n\n\n```python\nS = 'python'\nL = []\nfor i in S:\n    L.append(i)\n```\n\n\n```python\nL\n```\n\n\n\n\n    ['p', 'y', 't', 'h', 'o', 'n']\n\n\n\n\n```python\nmax(L)\n```\n\n\n\n\n    'y'\n\n\n\n\n```python\nmin(L)\n```\n\n\n\n\n    'h'\n\n\n\n\n```python\nfor i in L:\n    print('%s = ' % i + str(ord(i)))\n```\n\n    p = 112\n    y = 121\n    t = 116\n    h = 104\n    o = 111\n    n = 110\n\n\n\n```python\nmax(['A','a'])\n```\n\n\n\n\n    'a'\n\n\n\n\n```python\nprint(ord('A'), ord('a'))\n```\n\n    65 97\n\n\n### 52\u4e2a\u82f1\u6587\u5b57\u6bcd(\u5305\u542b\u5927\u5c0f\u5199) + \u952e\u76d8\u4e0a\u7684\u5176\u4ed6\u6309\u952e\u90fd\u5bf9\u5e94\u4e00\u4e2aASCII\u7801\n\n\n```python\nbin(65), hex(65), oct(65)\n```\n\n\n\n\n    ('0b1000001', '0x41', '0o101')\n\n\n\n\n```python\nprint(ord('x'), ord('='), ord('2'), ord('\\n'),ord('x')+ord('=')+ord('2')+ord('\\n') )\n```\n\n    120 61 50 10 241\n\n\n\n```python\nS = 'import sys\\n'\nlist((i for i in S))\n```\n\n\n\n\n    ['i', 'm', 'p', 'o', 'r', 't', ' ', 's', 'y', 's', '\\n']\n\n\n\n\n```python\nprint([ord(i) for i in list((i for i in S))])\n```\n\n    [105, 109, 112, 111, 114, 116, 32, 115, 121, 115, 10]\n\n\n\n```python\nf = open('script1.py', mode='w')\n```\n\n\n```python\nf.write('import sys\\n')\nf.write('print(sys.path)\\n')\nf.write('x = 2\\n')\nf.write('print(2**33)\\n')\n```\n\n\n\n\n    13\n\n\n\n\n```python\nf.close()\n```\n\n\n```python\nf = open('script1.py', 'r')\n```\n\n\n```python\nf.read()\n```\n\n\n\n\n    'import sys\\nprint(sys.path)\\nx = 2\\nprint(2**33)\\n'\n\n\n\n\n```python\nf.close()\n```\n\n\n```python\n# %load script1.py\nimport sys\nprint(sys.path)\nx = 2\nprint(2**33)\n```\n\n\n```python\nmax(open('script1.py'))\n```\n\n\n\n\n    'x = 2\\n'\n\n\n\n\n```python\nord('i'), ord('p'), ord('x')\n```\n\n\n\n\n    (105, 112, 120)\n\n\n\n\n```python\nL1 = list(range(1,101,1))\n```\n\n\n```python\nL2 = []\nfor i in L1:\n    L2.append(str(i))\n```\n\n\n```python\nS = '+'.join(L2)\n```\n\n\n```python\ntype(L1[0])\n```\n\n\n\n\n    int\n\n\n\n\n```python\neval(S)\n```\n\n\n\n\n    5050\n\n\n\n\n```python\nS\n```\n\n\n\n\n    '1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39+40+41+42+43+44+45+46+47+48+49+50+51+52+53+54+55+56+57+58+59+60+61+62+63+64+65+66+67+68+69+70+71+72+73+74+75+76+77+78+79+80+81+82+83+84+85+86+87+88+89+90+91+92+93+94+95+96+97+98+99+100'\n\n\n\n\n```python\nimport functools, operator\nfunctools.reduce(operator.add, L1)\n```\n\n\n\n\n    5050\n\n\n\n\n```python\nprint(L1, end='')\nprint('\\n')\nprint(L2, end='')\n```\n\n    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]\n    \n    ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100']\n\n### Sympy \u5b8c\u5168\u662fpython\u5199\u7684\uff0c\u5e76\u4e0d\u50cf\u770b\u8d77\u6765\u7684\u90a3\u6837\u4e0a\u6d41\n\n\n```python\nfrom sympy import *\ninit_session()\n```\n\n    IPython console for SymPy 1.4 (Python 3.7.4-64-bit) (ground types: python)\n    \n    These commands were executed:\n    >>> from __future__ import division\n    >>> from sympy import *\n    >>> x, y, z, t = symbols('x y z t')\n    >>> k, m, n = symbols('k m n', integer=True)\n    >>> f, g, h = symbols('f g h', cls=Function)\n    >>> init_printing()\n    \n    Documentation can be found at https://docs.sympy.org/1.4/\n    \n\n\n\n```python\nEq(Sum(n,(n,1,100)), Sum(n,(n,1,100)).doit())\n```\n\n\n```python\nEq(Product(n, (n,1,100)), Product(n, (n,1,100)).doit())\n```\n\n\n```python\nfactorial(100)\n```\n\n\n```python\nL1 = list(range(1,101,1))\nfunctools.reduce(operator.add, L1)\n```\n\n\n```python\nL1 = list(range(1,101,1))\nI = functools.reduce(operator.mul, L1)\n```\n\n\n```python\nI\n```\n\n\n```python\n# %load script1.py\nimport sys\nprint(sys.path)\nx = 2\nprint(2**33)\n```\n\n\n```python\nlist(open('script1.py'))\n```\n\n\n\n\n    ['import sys\\n', 'print(sys.path)\\n', 'x = 2\\n', 'print(2**33)']\n\n\n\n\n```python\ntuple(open('script1.py'))\n```\n\n\n\n\n    ('import sys\\n', 'print(sys.path)\\n', 'x = 2\\n', 'print(2**33)')\n\n\n\n\n```python\na, b, c, d= open('script1.py')\n```\n\n\n```python\na, d\n```\n\n\n\n\n    ('import sys\\n', 'print(2**33)')\n\n\n\n\n```python\na, *b = open('script1.py')\n```\n\n\n```python\ntype(a), type(b)\n```\n\n\n\n\n    (str, list)\n\n\n\n\n```python\nprint(a); print('\\n'); print(b)\n```\n\n    import sys\n    \n    \n    \n    ['print(sys.path)\\n', 'x = 2\\n', 'print(2**33)']\n\n\n\n```python\nset(open('script1.py'))\n```\n\n\n\n\n    {'import sys\\n', 'print(2**33)', 'print(sys.path)\\n', 'x = 2\\n'}\n\n\n\n\n```python\nset?\n```\n\n\n    \u001b[1;31mInit signature:\u001b[0m \u001b[0mset\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m/\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m*\u001b[0m\u001b[0margs\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n    \u001b[1;31mDocstring:\u001b[0m     \n    set() -> new empty set object\n    set(iterable) -> new set object\n    \n    Build an unordered collection of unique elements.\n    \u001b[1;31mType:\u001b[0m           type\n    \u001b[1;31mSubclasses:\u001b[0m     AssumptionsContext\n\n\n\n\n```python\nset()\n```\n\n\n```python\nL1\n```\n\n\n```python\nprint(set(L2)) #\u5bf9\u4e8e\u5b57\u7b26\u4e32\u6765\u8bf4\uff0c\u5b83\u8fd4\u56de\u7684\u662f\u65e0\u5e8f\u7684\n```\n\n    {'20', '61', '4', '38', '40', '26', '78', '93', '46', '64', '35', '56', '85', '12', '36', '57', '86', '7', '90', '91', '5', '69', '54', '25', '74', '62', '75', '39', '60', '28', '8', '16', '47', '23', '34', '88', '37', '63', '18', '10', '13', '41', '79', '100', '52', '65', '99', '32', '72', '45', '98', '89', '76', '1', '96', '67', '59', '77', '95', '84', '24', '11', '27', '81', '2', '66', '9', '29', '6', '97', '83', '22', '92', '44', '31', '82', '68', '30', '55', '33', '73', '3', '42', '19', '58', '15', '94', '70', '53', '51', '14', '21', '71', '80', '48', '17', '43', '87', '50', '49'}\n\n\n\n```python\nprint(set(L1)) #\u5bf9\u4e8e\u6574\u6570\u6765\u8bf4\uff0c\u5b83\u8fd4\u56de\u7684\u662f\u6709\u5e8f\u7684\n```\n\n    {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100}\n\n\n### \u521b\u9020\u7684\u662f\u4e00\u4e2a\u65e0\u5e8f\u7684\u5143\u7d20\u72ec\u4e00\u65e0\u4e8c\u7684\u96c6\u5408\uff0c\u800c\u4e14\u4f5c\u7528\u4e8e\u4e0d\u540c\u7684\u5bf9\u8c61\u7684\u8bdd\uff0c\u5f97\u5230\u7684\u7ed3\u679c\u4e5f\u662f\u4e0d\u4e00\u6837\u7684\n\n\n```python\nset('asafgjasa')  # \u5b57\u7b26\u4e32\n```\n\n\n\n\n    {'a', 'f', 'g', 'j', 's'}\n\n\n\n\n```python\nD = dict(enumerate(L2))\n```\n\n\n```python\nset(D) # set\u5b83\u628a\u5b57\u5178\u5f53\u4e2d\u7684\u5173\u952e\u8bcd\u63d0\u53d6\u51fa\u6765\uff0c\u521b\u9020\u65b0\u7684\u96c6\u5408\n```\n\n\n```python\nD2 = {i : i for i in L2}\n```\n\n\n```python\nprint(set(D2),end='')\n```\n\n    {'76', '20', '1', '61', '96', '4', '59', '38', '40', '67', '77', '84', '95', '24', '26', '78', '93', '11', '46', '27', '64', '81', '2', '66', '9', '29', '6', '97', '83', '35', '56', '85', '12', '22', '92', '36', '44', '57', '86', '7', '31', '90', '91', '5', '82', '68', '30', '69', '54', '25', '74', '55', '33', '62', '75', '39', '73', '60', '3', '28', '42', '8', '16', '47', '23', '19', '34', '58', '88', '15', '37', '94', '63', '70', '53', '18', '10', '51', '14', '21', '71', '13', '41', '80', '79', '100', '48', '52', '65', '99', '17', '43', '32', '87', '72', '45', '50', '49', '98', '89'}\n\n\n```python\nprint(set(set(D2))) # set\u4e3a\u4ec0\u4e48\u8fd4\u56de\u7684\u7ed3\u679c\u4e0e\u9884\u60f3\u4e0d\u4e00\u6837\n```\n\n    {'76', '20', '1', '61', '96', '4', '59', '38', '40', '67', '77', '84', '95', '24', '26', '78', '93', '11', '46', '27', '64', '81', '2', '66', '9', '29', '6', '97', '83', '35', '56', '85', '12', '22', '92', '36', '44', '57', '86', '7', '31', '90', '91', '5', '82', '68', '30', '69', '54', '25', '74', '55', '33', '62', '75', '39', '73', '60', '3', '28', '42', '8', '16', '47', '23', '19', '34', '58', '88', '15', '37', '94', '63', '70', '53', '18', '10', '51', '14', '21', '71', '13', '41', '80', '79', '100', '48', '52', '65', '99', '17', '43', '32', '87', '72', '45', '50', '49', '98', '89'}\n\n\n\n```python\nprint(set(tuple(L2))) # \u5143\u7ec4\n```\n\n    {'20', '61', '4', '38', '40', '26', '78', '93', '46', '64', '35', '56', '85', '12', '36', '57', '86', '7', '90', '91', '5', '69', '54', '25', '74', '62', '75', '39', '60', '28', '8', '16', '47', '23', '34', '88', '37', '63', '18', '10', '13', '41', '79', '100', '52', '65', '99', '32', '72', '45', '98', '89', '76', '1', '96', '67', '59', '77', '95', '84', '24', '11', '27', '81', '2', '66', '9', '29', '6', '97', '83', '22', '92', '44', '31', '82', '68', '30', '55', '33', '73', '3', '42', '19', '58', '15', '94', '70', '53', '51', '14', '21', '71', '80', '48', '17', '43', '87', '50', '49'}\n\n\n\n```python\nprint(set(\"\"\"Strictly speaking, the max and min functions can be applied to files as well\u2014they automatically use the iteration protocol to scan the file and pick out the lines with the highest\nand lowest string values, respectively though I\u2019ll leave valid use cases to your\nimagination\"\"\"), end='')\n```\n\n    {'m', 'a', 'e', 's', 'o', 'p', 'h', 'r', ' ', '\\n', 'v', 'u', ',', 'c', 'g', 'b', '\u2014', 'l', 'n', '\u2019', 'f', 'd', 't', 'I', 'S', 'x', 'i', 'k', 'y', 'w'}\n\n\n```python\nprint(set(\"\"\"\u77f3\u6b63\u4e3d\u7b49\u4e2d\u56fd\u79d1\u5b66\u5bb6\u53d1\u73b0\uff1a\u8fdb\u5316\u7684\u201c\u519b\u5907\u7ade\u8d5b\u201d\uff08arms race\uff09\u5851\u9020\u4e86\u75c5\u6bd2\u53ca\u5176\u53d7\u4f53\u7684\u591a\u6837\u6027\u3002\n\n\u9274\u5b9a\u6d89\u53ca\u79cd\u95f4\u4f20\u64ad\u7684\u5173\u952e\u6b8b\u57fa\u5bf9\u4e8e\u9884\u6d4b\u6f5c\u5728\u7684\u75c5\u539f\u4f53\u3001\u4e86\u89e3\u75c5\u6bd2\u5982\u4f55\u4ece\u91ce\u751f\u52a8\u7269\u5411\u4eba\u7c7b\u8dc3\u8fc1\uff0c\u975e\u5e38\u91cd\u8981\u3002\n\n\u4ee5\u524d\uff0c\u7814\u7a76\u8005\u5df2\u7ecf\u5728\u4e2d\u534e\u83ca\u5934\u8760\u4e2d\u9274\u5b9a\u51fa\u5177\u6709\u4e0d\u540c\u9057\u4f20\u7279\u5f81\u7684SARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\uff08SARSr-CoV\uff09\u3002\u800c\u8fd9\u4efd\u6700\u65b0\u7814\u7a76\u8fd8\u5c55\u73b0\u4e86\u4e2d\u534e\u83ca\u5934\u8760\u79cd\u7fa4\u4e2d\u8759\u8760\u53d7\u4f53ACE2\uff08\u8840\u7ba1\u7d27\u5f20\u7d20\u8f6c\u5316\u91762\uff09\u7684\u9ad8\u5ea6\u591a\u6837\u6027\u3002\u8fd9\u4e9bACE2\u53d8\u4f53\u652f\u6301SARS\u75c5\u6bd2\u548cSARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\u7684\u611f\u67d3\uff0c\u4f46\u5bf9\u4e0d\u540c\u523a\u7a81\u86cb\u767d\u5177\u6709\u4e0d\u540c\u7684\u7ed3\u5408\u4eb2\u548c\u529b\u3002\n\nSARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\u523a\u7a81\u86cb\u767d\u5bf9\u4ebaACE2\u62e5\u6709\u66f4\u9ad8\u7ed3\u5408\u4eb2\u548c\u529b\uff0c\u663e\u793a\u8fd9\u4e9b\u75c5\u6bd2\u5177\u6709\u5411\u4eba\u7c7b\u8dc3\u8fc1\u4f20\u67d3\u7684\u80fd\u529b\u3002ACE2\u548cSARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\u523a\u7a81\u86cb\u767d\u4e4b\u95f4\u7684\u754c\u9762\u5904\u6b8b\u57fa\u7684\u6b63\u5411\u9009\u62e9\uff0c\u8868\u660e\u5b83\u4eec\u4e4b\u95f4\u5b58\u5728\u957f\u671f\u548c\u6301\u7eed\u7684\u534f\u540c\u8fdb\u5316\u52a8\u529b\u5b66\u3002\u56e0\u6b64\uff0c\u6301\u7eed\u76d1\u89c6\u8759\u8760\u4e2d\u7684\u8fd9\u4e00\u7ec4\u75c5\u6bd2\u5bf9\u4e8e\u9884\u9632\u4e0b\u4e00\u4e2aSARS\u6837\u75be\u75c5\u975e\u5e38\u5fc5\u8981\u3002\n\n\u4ee5\u4e0a\u7814\u7a76\u6765\u81ea\u4e2d\u79d1\u9662\u6b66\u6c49\u75c5\u6bd2\u6240\u77f3\u6b63\u4e3d\u56e2\u961f\u4e0e\u798f\u5efa\u5e08\u8303\u5927\u5b66\u751f\u547d\u79d1\u5b66\u5b66\u9662\u6b27\u9633\u677e\u5e94\u6559\u6388\u5728\u9884\u5370\u672c\u5e73\u53f0 bioRxiv \u4e0a\u53d1\u8868\u7684\u8bba\u6587\uff1aEvolutionary arms race between virus and host drives genetic diversity in bat SARS related coronavirus spike genes\u3002\n\n\u4e2d\u534e\u83ca\u5934\u8760\u662fSARS\u75c5\u6bd2\u7684\u5bbf\u4e3b\uff0c\u5176\u4f53\u5185\u8fd8\u643a\u5e26\u591a\u79cdSARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\u3002\u8fd9\u4e9b\u75c5\u6bd2\u5177\u6709\u9ad8\u5ea6\u7684\u9057\u4f20\u591a\u6837\u6027\uff0c\u5c24\u5176\u662f\u75c5\u6bd2\u7684\u523a\u7a81\u86cb\u767d\u57fa\u56e0\u3002\u5c3d\u7ba1\u6709\u7740\u4e0d\u540c\u7a0b\u5ea6\u7684\u53d8\u5f02\uff0c\u4e00\u4e9b\u8759\u8760SARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\u4ecd\u53ef\u4ee5\u5229\u7528\u4eba\u7c7b\u53d7\u4f53ACE2\u8fdb\u5165\u4eba\u4f53\u7ec6\u80de\u3002\u7814\u7a76\u8005\u63a8\u6d4b\uff0c\u8759\u8760\u7684ACE2\u53d7\u4f53\u548cSARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\u523a\u7a81\u86cb\u767d\u4e4b\u95f4\uff0c\u6709\u7740\u76f8\u4e92\u4f5c\u7528\uff0c\u800c\u8fd9\u9a71\u52a8\u4e86SARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\u7684\u9057\u4f20\u591a\u6837\u6027\u3002\n\n\u7814\u7a76\u8005\u9274\u5b9a\u51fa\u4e86\u4e00\u7cfb\u5217\u4e2d\u534e\u83ca\u5934\u8760ACE2\u53d8\u5f02\u4f53\uff0c\u8fd9\u4e9b\u53d8\u5f02\u4f53\u4e2d\u6709\u4e00\u4e9b\u4e0eSARS-CoV\u523a\u7a81\u86cb\u767d\u6709\u76f8\u4e92\u4f5c\u7528\u7684\u591a\u6001\u4f4d\u70b9\u3002\u643a\u5e26\u4e0d\u540c\u523a\u7a81\u86cb\u767d\u7684\u4f2a\u75c5\u6bd2\u6216SARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\uff0c\u5728\u8868\u8fbe\u4e86\u8759\u8760ACE2\u53d8\u4f53\u7684\u7ec6\u80de\u4e2d\u6709\u7740\u4e0d\u540c\u7684\u77ac\u65f6\u611f\u67d3\u6548\u7387\u3002\u901a\u8fc7\u6d4b\u5b9aSARS\u75c5\u6bd2\u3001SARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\u523a\u7a81\u86cb\u767d\u4e0e\u8759\u8760\u53d7\u4f53\u3001\u4eba\u7c7b\u53d7\u4f53\u5206\u5b50\u4e4b\u95f4\u7684\u7ed3\u5408\u4eb2\u548c\u529b\uff0c\u80fd\u89c2\u5bdf\u5230\u76f8\u5173\u7684\u7ed3\u679c\u3002\n\n\u6240\u6709\u88ab\u6d4b\u8bd5\u7684\u8759\u8760SARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\u523a\u7a81\u86cb\u767d\u4e0e\u4ebaACE2\u7684\u7ed3\u5408\u4eb2\u548c\u529b\uff0c\u5747\u9ad8\u4e8e\u5176\u5bf9\u8759\u8760ACE2\u7684\u7ed3\u5408\u4eb2\u548c\u529b\u3002\u4e0d\u8fc7SARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\u523a\u7a81\u86cb\u767d\u4e0e\u4ebaACE2\u7684\u7ed3\u5408\u4eb2\u548c\u529b\uff0c\u6bd4SARS-CoV\u523a\u7a81\u86cb\u767d\u4e0e\u4ebaACE\u7684\u4eb2\u548c\u529b\u4f4e10\u500d\u3002\n\n\u7ed3\u6784\u5efa\u6a21\u8868\u660e\uff0c\u523a\u7a81\u548cACE2\u4e4b\u95f4\u7684\u7ed3\u5408\u4eb2\u548c\u529b\u5dee\u5f02\u53ef\u80fd\u662f\u7531\u4e8e\u8fd9\u4e24\u4e2a\u5206\u5b50\u754c\u9762\u4e2d\u67d0\u4e9b\u5173\u952e\u6b8b\u57fa\u7684\u6539\u53d8\u800c\u5f15\u8d77\u3002\u5206\u5b50\u8fdb\u5316\u5206\u6790\u8868\u660e\uff0c\u8fd9\u4e9b\u6b8b\u57fa\u5904\u4e8e\u5f3a\u7684\u6b63\u9009\u62e9\u3002\n\n\u8fd9\u4e9b\u7ed3\u679c\u8868\u660eSARS\u65b0\u51a0\u75c5\u6bd2\u523a\u7a81\u86cb\u767d\u548c\u8759\u8760ACE2\u53ef\u80fd\u968f\u7740\u65f6\u95f4\u7684\u63a8\u79fb\u800c\u4e92\u76f8\u8fdb\u5316\uff0c\u5e76\u7ecf\u5386\u5f7c\u6b64\u7684\u9009\u62e9\u538b\u529b\uff0c\u4ece\u800c\u89e6\u53d1\u4e86\u8fdb\u5316\u7684\u201c\u519b\u5907\u7ade\u8d5b\u201d\u52a8\u529b\u5b66\u3002\u8fd9\u8fdb\u4e00\u6b65\u8bc1\u660e\u4e86\uff0c\u4e2d\u534e\u83ca\u5934\u8760\u662fSARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\u7684\u5929\u7136\u5bbf\u4e3b\u3002\n\n\u51a0\u72b6\u75c5\u6bd2\u662f\u5305\u819c\u75c5\u6bd2\uff0c\u5305\u542b\u5355\u80a1\u6b63\u94feRNA\u3002\u8be5\u4e9a\u79d1\u6709\u56db\u4e2a\u5c5e\uff0c\u5373\u03b1\u3001\u03b2\u3001\u03b3\u548c\u03b4\u3002\u03b1\u51a0\u72b6\u75c5\u6bd2\u548c\u03b2\u51a0\u72b6\u75c5\u6bd2\u8d77\u6e90\u4e8e\u8759\u8760\u6216\u556e\u9f7f\u52a8\u7269\uff0c\u800c\u03b3\u51a0\u72b6\u75c5\u6bd2\u548c\u03b4\u51a0\u72b6\u75c5\u6bd2\u8d77\u6e90\u4e8e\u9e1f\u7c7b\u3002\u81ea21\u4e16\u7eaa\u521d\u4ee5\u6765\uff0c\u4e09\u79cd\u03b2\u578b\u51a0\u72b6\u75c5\u6bd2\u5df2\u5f15\u8d77\u4eba\u7c7b\u4e25\u91cd\u80ba\u708e\u66b4\u53d1\u3002\u5206\u522b\u662fSARS-CoV\uff0cMERS-CoV\u548cSARS-CoV-2\u3002\n\nSARS-CoV-2\u5f15\u53d1\u7684\u75ab\u60c5\u4f7f\u4eba\u4eec\u56de\u60f3\u8d7717\u5e74\u524d\u53d1\u751f\u7684SARS\u75ab\u60c5\u3002SARS\u662f\u4e00\u79cd\u4eba\u755c\u5171\u60a3\u75c5\uff0c\u5728\u63a5\u4e0b\u6765\u7684\u51e0\u5e74\u4e2d\uff0c\u79d1\u5b66\u5bb6\u4ece\u4e2d\u56fd\u548c\u6b27\u6d32\u4e0d\u540c\u5730\u533a\u7684\u8759\u8760\u4e2d\u68c0\u6d4b\u6216\u5206\u79bb\u51fa\u4e86\u5177\u6709\u4e0d\u540c\u9057\u4f20\u7279\u5f81\u768475\u79cdSARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\uff08SARSr-CoV\uff09\u3002\n\n\u8759\u8760SARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\u4e0e\u4eba\u7c7b\u548c\u679c\u5b50\u72f8\u7684SARS-CoVs\u670996\uff05\u7684\u6838\u82f7\u9178\u5e8f\u5217\u76f8\u4f3c\u5ea6\uff0c\u5176\u4e2d\u53ef\u53d8\u533a\u6700\u591a\u7684\u662f\u523a\u7a81\u86cb\u767d\uff08S\uff09\u548c\u8f85\u52a9\u86cb\u767dORF3\u548cORF8\u3002\u6b64\u5916\uff0c\u7814\u7a76\u8005\u5df2\u7ecf\u786e\u5b9a\u4e86\u4e0d\u540c\u8759\u8760SARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\u57fa\u56e0\u7ec4\u4e2d\u80fd\u627e\u5230SARS-CoV\u7684\u6240\u6709\u57fa\u56e0\u6784\u5efa\u57fa\u5757\uff0c\u8fd9\u8868\u660eSARS\u75c5\u6bd2\u7684\u7956\u5148\u662f\u901a\u8fc7\u8759\u8760SARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\u57fa\u56e0\u7ec4\u7684\u91cd\u7ec4\u800c\u6765\uff0c\u5176\u8d77\u6e90\u4e8e\u8759\u8760\u3002\n\n\u75c5\u6bd2\u611f\u67d3\u7684\u7b2c\u4e00\u6b65\u662f\u8bc6\u522b\u7ec6\u80de\u53d7\u4f53\uff0c\u8fd9\u4e5f\u662f\u5fc5\u4e0d\u53ef\u5c11\u7684\u6b65\u9aa4\u3002\u51a0\u72b6\u75c5\u6bd2\u7684\u8fdb\u5165\u662f\u7531\u75c5\u6bd2\u523a\u7a81\u86cb\u767d\uff08Spike\uff0cS\uff09\u548c\u7ec6\u80de\u8868\u9762\u53d7\u4f53\u4e4b\u95f4\u7684\u7279\u5f02\u6027\u76f8\u4e92\u4f5c\u7528\u4ecb\u5bfc\uff0c\u7136\u540e\u75c5\u6bd2\u4e0e\u5bbf\u4e3b\u819c\u4e4b\u95f4\u53d1\u751f\u878d\u5408\u3002\u51a0\u72b6\u75c5\u6bd2\u523a\u7a81\u86cb\u767d\u5728\u529f\u80fd\u4e0a\u5206\u4e3a\u4e24\u4e2a\u4e9a\u57fa\uff1a\u7ec6\u80de\u9644\u7740\u4e9a\u57fa\uff08S1\uff09\u548c\u819c\u878d\u5408\u4e9a\u57fa\uff08S2\uff09\u3002 S1\u533a\u57df\u5305\u542bN\u7aef\u7ed3\u6784\u57df\uff08NTD\uff09\u548cC\u7aef\u7ed3\u6784\u57df\uff08CTD\uff09\uff1b\u4e24\u8005\u5747\u53ef\u7528\u4e8e\u51a0\u72b6\u75c5\u6bd2\u53d7\u4f53\u7ed3\u5408\uff08RBD\uff09\u3002\n\n\u5bf9\u4e8eSARS-CoV\uff0c\u5176S1-CTD\u4f5c\u4e3aRBD\u4e0e\u7ec6\u80de\u7684\u53d7\u4f53\u5373\u8840\u7ba1\u7d27\u5f20\u7d20\u8f6c\u6362\u91762\uff08ACE2\uff09\u7ed3\u5408\u3002\u51b7\u51bb\u7535\u955c\u548c\u6676\u4f53\u7ed3\u6784\u5206\u6790\uff0c\u786e\u5b9a\u4e86SARS\u75c5\u6bd2\u7684S-RBD\u4e0e\u4ebaACE2\u4e4b\u95f4\u754c\u9762\u4e2d\u7684\u4e00\u4e9b\u5173\u952e\u6b8b\u57fa\u3002\n\n\u6839\u636eS\u86cb\u767d\u7684\u5927\u5c0f\uff0c\u8759\u8760SARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\u53ef\u4ee5\u5206\u4e3a\u4e24\u4e2a\u4e0d\u540c\u7684\u8fdb\u5316\u679d\u3002\u8fdb\u5316\u679d1\u5305\u542b\u75c5\u6bd2\u5177\u6709\u4e0eSARS\u75c5\u6bd2\u5927\u5c0f\u76f8\u540c\u7684\u523a\u7a81\u86cb\u767d\u3002\u800c\u7531\u4e8e5\u300112\u621613\u4e2a\u6c28\u57fa\u9178\u7f3a\u5931\uff0c\u5c5e\u4e8e\u8fdb\u5316\u679d2\u7684\u75c5\u6bd2\u5176\u523a\u7a81\u86cb\u767d\u5219\u6bd4SARS\u75c5\u6bd2\u7684\u5c0f\u3002\n\n\u5c3d\u7ba1RBD\u6709\u6240\u4e0d\u540c\uff0c\u6240\u6709\u8fdb\u5316\u679d1\u6bd2\u682a\u90fd\u53ef\u4ee5\u4f7f\u7528ACE2\u8fdb\u5165\u7ec6\u80de\uff0c\u800c\u8fdb\u5316\u679d2\u6bd2\u682a\u5219\u7531\u4e8e\u4e0a\u8ff0\u7f3a\u5931\u65e0\u6cd5\u76f4\u63a5\u8fdb\u5165\u3002\u8fd9\u4e9b\u7ed3\u679c\u8868\u660e\uff0c\u5c31\u57fa\u56e0\u7ec4\u76f8\u4f3c\u6027\u548cACE2\u7684\u4f7f\u7528\u800c\u8a00\uff0c\u8fdb\u5316\u679d1\u7684\u6210\u5458\u5f88\u53ef\u80fd\u662fSARS\u75c5\u6bd2\u7684\u76f4\u63a5\u6765\u6e90\u3002\n\nACE2\u5728\u529f\u80fd\u4e0a\u5206\u4e3a\u4e24\u4e2a\u7ed3\u6784\u57df\uff1aN\u672b\u7aef\u7ed3\u6784\u57df\u53c2\u4e0eSARS-CoV\u7ed3\u5408\uff0cC\u672b\u7aef\u7ed3\u6784\u57df\u53c2\u4e0e\u5fc3\u529f\u80fd\u7684\u8c03\u8282\u3002\u5148\u524d\u7684\u7ed3\u679c\u8868\u660e\uff0c\u4e0d\u540c\u6765\u6e90\u7684ACE2\u7684C\u672b\u7aef\u7ed3\u6784\u57df\u76f8\u5bf9\u4fdd\u5b88\uff0c\u800cN\u672b\u7aef\u7ed3\u6784\u57df\u5728\u7269\u79cd\u95f4\u663e\u793a\u51fa\u66f4\u591a\u7684\u591a\u6837\u6027\u3002\u6b64\u524d\u5df2\u8bc1\u660eSARS\u75c5\u6bd2\u53ef\u4ee5\u5229\u7528\u6c34\u9f20\u8033\u8760\u7684ACE2\u548c\u4e2d\u534e\u83ca\u5934\u8760\u7684ACE2\u3002RBD\u7ed3\u5408\u4f4d\u70b9\u4e2d\u7684\u5fae\u5c0f\u7a81\u53d8\uff0c\u53ef\u5c06ACE2\u4ece\u5bf9SARS-CoV\u7ed3\u5408\u4e0d\u6613\u611f\u8f6c\u53d8\u4e3a\u6613\u611f\u3002\u7531\u4e8e\u5c5e\u4e8e\u8fdb\u5316\u679d1\u7684\u6240\u6709SARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\u90fd\u53ef\u4ece\u4e2d\u534e\u83ca\u5934\u8760\u4f53\u5185\u63d0\u53d6\u51fa\u6765\uff0c\u800c\u4e14\u4e5f\u90fd\u53ef\u4ee5\u5229\u7528ACE2\uff0c\u56e0\u6b64\u7814\u7a76\u8005\u63d0\u51fa\u95ee\u9898\uff1a\u4e2d\u534e\u83ca\u5934\u8760ACE2\u4e2d\u7684\u53d8\u5f02\u662f\u5426\u53ef\u80fd\u6709\u5bfc\u81f4\u4e86\u8759\u8760SARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\u7684\u591a\u6837\u6027\u3002\n\n\u7814\u7a76\u56e2\u961f\u7814\u7a76\u4e86\u4e2d\u534e\u83ca\u5934\u8760ACE2\u57fa\u56e0\u7684\u591a\u6001\u6027\uff0c\u5e76\u901a\u8fc7\u5206\u5b50\u8fdb\u5316\u5206\u6790\uff0c\u86cb\u767d\u8d28\u4eb2\u548c\u529b\u6d4b\u5b9a\u548c\u75c5\u6bd2\u611f\u67d3\u6d4b\u5b9a\u76f8\u7ed3\u5408\uff0c\u8bc4\u4f30\u4e86\u5b83\u4eec\u5bf9\u4e0d\u540c\u8759\u8760SARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\u523a\u7a81\u86cb\u767d\u7684\u654f\u611f\u6027\u548c\u7ed3\u5408\u4eb2\u548c\u529b\u3002\n\n\u7ed3\u679c\u8868\u660e\uff0cSARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\u7684\u523a\u7a81\u86cb\u767d\u591a\u6837\u6027\u53ef\u80fd\u4f1a\u53d7\u5230\u4e2d\u534e\u83ca\u5934\u8760ACE2\u53d8\u4f53\u7684\u81ea\u7136\u9009\u62e9\u538b\u529b\uff1b \u5728\u957f\u671f\u5171\u5b58\u671f\u95f4\uff0cSARSr-CoV\u523a\u7a81\u86cb\u767d\u53ef\u80fd\u4f1a\u88ab\u4e2d\u534e\u83ca\u5934\u8760\u7684ACE2\u9009\u62e9\uff0c\u4ee5\u7ef4\u6301\u81ea\u8eab\u9057\u4f20\u591a\u6837\u6027\u5e76\u9002\u5408\u4e2d\u534e\u83ca\u5934\u8760\u7684\u79cd\u7fa4\u3002\n\nACE2\u57fa\u56e0\u5728\u4e2d\u534e\u83ca\u5934\u8760\u79cd\u7fa4\u4e2d\u8868\u73b0\u51fa\u9ad8\u5ea6\u591a\u6001\u6027\n\n\u6839\u636e\u8759\u8760SARS\u76f8\u5173\u51a0\u72b6\u75c5\u6bd2\u7684\u6d41\u884c\u60c5\u51b5\u4ee5\u53ca\u6837\u54c1\u7ec4\u7ec7\u7684\u53ef\u7528\u6027\u548c\u8d28\u91cf\uff0c\u7814\u7a76\u8005\u4f7f\u7528\u6765\u81ea\u4e09\u4e2a\u7701\uff08\u6e56\u5317\uff0c\u5e7f\u4e1c\u548c\u4e91\u5357\uff09\u7684\u6837\u54c1\u8fdb\u884cACE2\u6269\u589e\u3002\n\n\u9664\u4e86\u56e2\u961f\u5148\u524d\u6d4b\u5e8f\u8fc7\u7684\u8759\u8760ACE2\uff08\u5206\u522b\u4ece\u6e56\u5317\uff0c\u5e7f\u897f\u548c\u4e91\u5357\u6536\u96c6\u7684\u6837\u672cID 832\u3001411\u548c3357\uff09\u548c\u5176\u4ed6\u8759\u8760ACE2\uff08GenBank\u767b\u8bb0\u53f7ACT66275\uff0c\u8fd9\u662f\u4ece\u9999\u6e2f\u6536\u96c6\u7684\u6837\u672c\uff09\u5916\uff0c\u7814\u7a76\u8005\u4ece21\u53ea\u4e2d\u534e\u83ca\u5934\u8760\u8760\u4e2a\u4f53\u4e2d\u83b7\u5f97\u4e86ACE2\u57fa\u56e0\u5e8f\u5217\uff1a\u6e56\u5317\u67095\u4e2a\uff0c\u5e7f\u4e1c\u67099\u4e2a\uff0c\u4e91\u5357\u67097\u4e2a\u3002\u8fd9\u4e9b\u8759\u8760ACE2\u5e8f\u5217\u5728\u5176\u7269\u79cd\u5185\u663e\u793a98-100\uff05\u7684\u6c28\u57fa\u9178\u540c\u4e00\u6027\uff0c\u4e0e\u4ebaACE2\u7684\u663e\u793a80-81\uff05\u7684\u6c28\u57fa\u9178\u540c\u4e00\u6027\u3002\n\n\u8fd9\u4e9b\u8759\u8760ACE2\u5728N\u7aef\u533a\u57df\u89c2\u5bdf\u5230\u4e86\u4e3b\u8981\u53d8\u5316\uff0c\u5305\u62ec\u4e00\u4e9b\u5148\u524d\u5df2\u786e\u5b9a\u4e0eSARS\u75c5\u6bd2\u7684 S-RBD\u63a5\u89e6\u7684\u6b8b\u57fa\u3002\u6839\u636e\u975e\u540c\u4e49SNP\u5206\u6790\u9274\u5b9a\u51fa8\u4e2a\u6b8b\u57fa\uff0c\u5305\u62ec24\u300127\u300131\u300134\u300135\u300138.41\u548c42\u3002\u8fd98\u4e2a\u6b8b\u57fa\u7684\u7ec4\u5408\u4ea7\u751f\u4e868\u4e2a\u7b49\u4f4d\u57fa\u56e0\uff0c\u5305\u62ecRIESEDYK\uff0cLIEFENYQ\uff0cRTESENYQ\uff0cRIKSEDYQ\uff0cQIKSEDYQ\uff0c RMTSEDYQ\uff0cEMKT KDHQ\u548cEIKT EIKTKDHQ\uff0c\u5206\u522b\u547d\u540d\u4e3a\u7b49\u4f4d\u57fa\u56e01-8\u3002\n\n\u9664\u4e86\u5148\u524d\u7814\u7a76\uff08\u7b49\u4f4d\u57fa\u56e04\u30017\u548c8\uff09\u4e2d\u7684ACE2\u57fa\u56e0\u578b\u6570\u636e\u5916\uff0c\u7814\u7a76\u8005\u5728\u4e2d\u534e\u83ca\u5934\u8760\u79cd\u7fa4\u4e2d\u8fd8\u9274\u5b9a\u51fa5\u4e2a\u65b0\u7684\u7b49\u4f4d\u57fa\u56e0\u3002\u201c\u7b49\u4f4d\u57fa\u56e02\u201d\u5728\u4e24\u4e2a\u7701\u7684\u6837\u672c\u4e2d\u6709\u53d1\u73b0\uff0c\u201c\u7b49\u4f4d\u57fa\u56e04\u201d\u57283\u4e2a\u7701\u4e2d\u6709\u53d1\u73b0\uff0c\u800c\u5176\u4ed6\u7b49\u4f4d\u57fa\u56e0\u4f3c\u4e4e\u5728\u5730\u7406\u4e0a\u53d7\u5230\u9650\u5236\u3002\u603b\u4e4b\uff0c\u5728\u5e7f\u4e1c\u53d1\u73b0\u4e863\u4e2a\u7b49\u4f4d\u57fa\u56e0\uff084\u30016\u548c8\uff09\uff0c\u4e91\u5357\u53d1\u73b0\u4e864\u4e2a\u7b49\u4f4d\u57fa\u56e0\uff081\u30012\u30014\u548c7\uff09\uff0c\u5728\u6e56\u5317\u53d1\u73b0\u4e863\u4e2a\u7b49\u4f4d\u57fa\u56e0\uff082\u30014\u548c5\uff09\uff0c\u5728\u5e7f\u897f\u548c\u9999\u6e2f\u5206\u522b\u627e\u5230\u4e861\u4e2a\u7b49\u4f4d\u57fa\u56e0\u3002\u5728\u53d1\u73b0SARS\u75c5\u6bd2\u76f4\u63a5\u7956\u5148\u7684\u4e91\u5357\u4e00\u8759\u8760\u6d1e\u4e2d\uff0c\u7814\u7a76\u8005\u53d1\u73b0\u4e864\u4e2a\u7b49\u4f4d\u57fa\u56e0\u5171\u5b58\u3002\n\n\u7efc\u4e0a\u6240\u8ff0\uff0c\u8fd9\u4e9b\u6570\u636e\u8868\u660eACE2\u53d8\u5f02\u4f53\u5df2\u7ecf\u5728\u4e0d\u540c\u5730\u533a\u7684\u4e2d\u534e\u83ca\u5934\u8760\u79cd\u7fa4\u4e2d\u957f\u671f\u5b58\u5728\u3002\u4e0eSARS\u75c5\u6bd2\u7684S-RBD\u76f4\u63a5\u63a5\u89e6\u7684\u4f4d\u70b9\u7684\u53d6\u4ee3\uff0c\u8868\u660e\u5b83\u4eec\u5728SARS\u75c5\u6bd2\u7684\u8fdb\u5316\u548c\u4f20\u64ad\u8fc7\u7a0b\u4e2d\u53ef\u80fd\u5177\u6709\u91cd\u8981\u529f\u80fd\u3002\"\"\"), end ='')\n```\n\n    {'M', 'F', '\u8fd8', '\uff1a', '\u5317', '\u75c5', '\u4f3c', 'R', '\u80fd', '\u754c', '\u6765', '\u89e6', '\u5e7f', '\u755c', 'v', '\u6e90', '\u522b', '\u7a76', '\u672c', '\u77f3', '\u77ac', '\u542b', 'l', '\u4eba', '\u79bb', '7', '\u4e3d', '\u56db', '\u9f7f', '\u955c', '\u8f85', '\u4f55', '\u529f', '\u7269', '\u9274', '\u6709', '\u66b4', '\u679d', 'r', '\u75be', '\u91ce', '\u76d1', '\u5c06', '\u5982', '\u6784', 'K', 'd', '\u6b8b', '\u6839', '\u8d77', '\u7ec7', '\u51a0', '\u51fa', 'm', '\u9178', '\u6c34', '1', '\u5fc3', '\u67d3', '\u9e1f', '\u5e73', '\u5747', '\u6539', 'p', '\u9002', '\u62e5', '\u5927', '2', '9', '\u5c5e', '\u4f4e', '\u7eed', '\u9009', '\u4e09', '\u9644', '\u4ee5', '\u643a', '\u4ecb', '\u5f7c', '\u79fb', '\u63d0', '\u4eb2', 'E', '\u60f3', '\u5386', '\u556e', '\u6587', '\u80de', '\u5efa', '\u6216', '\u5929', '\u677e', 'o', 'h', '\u6676', '\u5176', '\u7b49', 'C', 'b', '\u5f81', '\u5c0f', '\u7c7b', '\u5217', '\u91cd', '.', '\u5bbf', '\u82f7', '\u589e', '\u5904', 'I', '\u7ed3', '\u6790', '\u9762', '\u53d6', '\u7814', '\u4e3b', '\u56e2', '\u81f4', '\u53f0', '\uff1b', '\u8ff0', '\u90fd', 'u', 'B', '\u708e', '\u6b64', '\u663e', '\u540d', '\u65f6', '\u6240', '\u7b2c', '\u5373', '\u8d5b', '\u5bdf', '\u5fc5', '\u5851', '\u660e', '\u8840', '\u8fdb', '\u6b27', '\u8bba', '\u5c31', '8', '\u5236', '\u5b88', '\uff09', '\u5177', '\u5bfc', '\u80a1', '\u03b3', '\u5426', '\u8f6c', '\u5e8f', '\u8033', 'D', '\u6bd2', '\u53c2', 'N', '\u89c2', '\u662f', '\u819c', 'P', '\u5171', '\u7a81', '\u56e0', '\u9662', 't', '\u9632', '\u4e4b', '\u7ba1', '\u80ba', '\u53f7', '\u800c', '\u72b6', '\u52a9', '\u636e', '\u8fbe', '\u4e16', '\u968f', '\u7ade', '\u8bb0', '6', '\u7ecf', '\u4e0d', 'A', 'L', 'T', '\u70b9', '\u9633', '\u75ab', '\u534f', '\u9664', '\u672b', '\u5c24', '\u6bd4', '\u9020', '\u5206', '\u8759', '\u4e24', '\u3002', 'x', '\u5173', 'i', '\u7956', '\u7aef', '\u4ecd', '-', '\u51e0', '3', '\u6362', '\u4ea7', '\u201d', '\u4f53', '\u7d27', '\u521d', '\u957f', '\u6d4b', '\u9f20', '\u5219', '\u5148', '\u4e4e', '\u62e9', '\u7740', '\u7701', '\u4e91', '\u5bf9', '\u4f2a', '\u7279', '\u8fc1', '\u5b83', '\u60a3', '\u4e2a', '\u56de', '\u4eec', '\u7531', '\u5c3d', '\u95ee', '\u5f97', '\u6837', 'a', '\u9176', '\u5165', '\u547d', '\u6027', '\u7528', '\u534e', '\u72f8', '\u5316', '\u786e', '\u8fd9', '\u671f', '\u5df2', '\u627e', '\u60c5', '\u4e9b', '\u4e1c', '\u6210', '\u53ea', '0', '\u81ea', '\u5f88', '\u6536', '\u4ed6', '\u5e94', '\u5355', '\u9057', '\u8bc6', '\u51b7', '\u5dee', '\u7136', '\uff0c', '\u79cd', '\u878d', '\u5b58', '\u67d0', '\u6a21', '\u6b65', '\u53ca', '\u89c6', '\u4e2d', '\u5370', '\u5757', '\u9999', '\u5408', '\u03b4', '\u6301', '\u884c', '\u57fa', '\u5305', '\u7535', '\u65e0', '\u4e8e', '\u6700', '\u94fe', '\u5229', '\u5916', '\u54c1', '\u4e49', '\u5728', '\u533a', '\u652f', ' ', '\u9898', '\u603b', '\u5f20', '\u540e', '\u5931', '\u8a00', '\u4fdd', '\u9884', '\u4e0a', '\u611f', '\u53d7', '\u4f4d', '\u5230', '\u523a', '\u56fd', '\u68c0', '\u8bc4', '\u5411', '\u9a71', '\u7eaa', '\u8868', '\u5ea6', '\u64ad', '\u540c', '\u65b0', '\u4e86', '\u5c55', '\u751f', '\u975e', '\u7fa4', '\u8303', '\u793a', 'S', '\u4e0e', '\u6d41', '\u66f4', '\u6269', '\u4f7f', '\u9aa4', '\u8d28', '\u5e74', '\uff08', '\u7a0b', '\u539f', '\u500d', '\u86cb', '\u73b0', '\u201c', '\u654f', '\u952e', 'c', '\u4f1a', '\u8282', '\u519b', '\u5c11', '\u7406', '\u63a5', '\u6e56', '\u53ef', '\u4f5c', 'V', '\u8bd5', '\u7efc', '\u6e2f', '\u8be5', '\u548c', '\u767d', '\u7f3a', '\u4e92', '\u8fc7', '\u57df', '\u5f15', '4', '\u4e3a', '\u7ef4', '\u8c03', '\\n', '\u5f02', '\u6f5c', '\u961f', 'n', '\u538b', '\u4e5f', 'Q', '\u7cfb', '\u6570', '\u6cd5', '\u63a8', '5', 'H', '\uff05', '\u7387', '\u89e3', 'w', '\u3001', '\u8dc3', '\u6838', '\u8981', 'G', '\u7684', '\u901a', '\u83ca', '\u5934', 'e', '\u4f46', '\u682a', '\u5e76', '\u6d1e', '\u7ec6', '\u96c6', '\u6c28', '\u524d', '\u679c', '\u5185', '\u4e9a', '\u5e08', '\u76f4', '\u6613', '\u62ec', '\u4f30', '\u5bb6', '\u5f3a', '\u5357', '\u5458', '\u4e0b', '\u798f', '\u4e25', '\u4efd', '\u91cf', '\u767b', '\u7ec4', '\u4f20', '\u95f4', '\u5b50', '\u5730', '\u529b', 's', '\u6b63', '\u6548', '\u4ee3', '\u6d32', '\u8eab', 'O', '\u52a8', '\u5907', 'Y', '\u4e00', '\u6b66', '\u51b5', '\u9ad8', '\u6001', '\u53d8', '\u88ab', '\u897f', '\u53d1', '\u8005', '\u5e26', '\u03b1', '\u83b7', '\u9650', '\u6388', '\u8bc1', 'g', '\u578b', '\u8760', '\u4e14', '\u51bb', '\u76f8', '\u79d1', '\u5b66', '\u5e38', '\u7d20', '\u5b9a', '\u6559', '\u03b2', '\u591a', '\u5fae', '\u4ece', '\u6c49', 'k', 'y', '\u6d89'}\n\n\n```python\n{ line for line in open('script1.py')}\n```\n\n\n\n\n    {'import sys\\n', 'print(2**33)', 'print(sys.path)\\n', 'x = 2\\n'}\n\n\n\n\n```python\nord('i'), ord('p'), ord('x')\n```\n\n\n```python\n# %load script1.py\nimport sys\nprint(sys.path)\nx = 2\nprint(2**33)\n```\n\n\n```python\nord('7'), ord('2')\n```\n\n\n```python\n{ix: line for ix, line in enumerate(open('script1.py'))}\n```\n\n\n\n\n    {0: 'import sys\\n', 1: 'print(sys.path)\\n', 2: 'x = 2\\n', 3: 'print(2**33)'}\n\n\n\n\n```python\n{line for line in open('script1.py') if line[0] == 'p'}\n```\n\n\n\n\n    {'print(2**33)', 'print(sys.path)\\n'}\n\n\n\n\n```python\n{ix: line for (ix, line) in enumerate(open('script1.py'))}\n```\n\n\n\n\n    {0: 'import sys\\n', 1: 'print(sys.path)\\n', 2: 'x = 2\\n', 3: 'print(2**33)'}\n\n\n\n\n```python\nord('s') # \u51fd\u6570  \n```\n\n\n```python\ndef f(a, b,c, d):print(a,b,c,d,sep=',')\n```\n\n\n```python\nf(1,2,3,4)\n```\n\n    1,2,3,4\n\n\n\n```python\nf(*[1,2,3,45]) # a, b, c, d\u662f\u5355\u4e2a\u53c2\u6570\n```\n\n    1,2,3,45\n\n\n\n```python\na, *b = open('script1.py')\n```\n\n\n```python\nb\n```\n\n\n\n\n    ['print(sys.path)\\n', 'x = 2\\n', 'print(2**33)']\n\n\n\n\n```python\ndef f(a,b,c,d): print(a*2, b*3, c*4, d*5, end='\\n' )\n```\n\n\n```python\nf(*open('script1.py'))\n```\n\n    import sys\n    import sys\n     print(sys.path)\n    print(sys.path)\n    print(sys.path)\n     x = 2\n    x = 2\n    x = 2\n    x = 2\n     print(2**33)print(2**33)print(2**33)print(2**33)print(2**33)\n\n\n\n```python\n# %load script1.py\nimport sys\nprint(sys.path)\nx = 2\nprint(2**33)\n```\n\n\n```python\nX = (1,2)\nY = (3,4)\nzip(X,Y)\n```\n\n\n\n\n    <zip at 0x20490a0a788>\n\n\n\n\n```python\ntuple(zip(X,Y)); list(zip(X,Y))\n```\n\n\n```python\nzip(zip(X,Y))\n```\n\n\n\n\n    <zip at 0x2048f0d7808>\n\n\n\n\n```python\nA, B = zip(*zip(X,Y))\n```\n\n\n```python\nprint(A, end='\\n'); print(B, end='\\n')\n```\n\n    (1, 2)\n    (3, 4)\n\n\n\n```python\nC, D = zip(X,Y) # X = (1,2) Y = (3,4)\n```\n\n\n```python\nprint(C, end='\\n'); print(D, end='\\n')\n```\n\n    (1, 3)\n    (2, 4)\n\n\n\n```python\nA, B = zip(C,D)\n```\n\n\n```python\nA, B = zip(zip(X,Y)) #\n```\n\n\n```python\nprint(A, end='\\n'); print(B, end='\\n')\n```\n\n    ((1, 3),)\n    ((2, 4),)\n\n\n\n```python\nA, B = zip(X,Y)\nC = A, B\n```\n\n\n```python\nC\n```\n\n\n```python\nE, F= zip(C,)\n```\n\n\n```python\nprint(E, end='\\n'); print(F, end='\\n')\n```\n\n    ((1, 3),)\n    ((2, 4),)\n\n\n##### \u4ec0\u4e48\u53eb\u5b57\u5178\u89c6\u56fe\u5bf9\u8c61\uff1f\n\n### Python3.0\u4e2d\u7684\u65b0\u7684\u53ef\u8fed\u4ee3\u5bf9\u8c61\n\nPython 3 \u7684\u7248\u672c\u6bd4Python2.x \u66f4\u52a0\u5f3a\u8c03\u8fed\u4ee3\n\n\n```python\nzip('abc','xyz')  # \u5728Python3.x\u4e2d\u8fd4\u56de\u7684\u662f\u53ef\u8fed\u4ee3\u7684\u5bf9\u8c61\uff0c\u800c\u57282.x\u7248\u672c\u4e2d\u8fd4\u56de\u662f\u4e00\u4e2a\u5217\u8868\n```\n\n\n\n\n    <zip at 0x204909cf908>\n\n\n\n\n```python\nlist(zip('abc','xyz')) \n```\n\n\n\n\n    [('a', 'x'), ('b', 'y'), ('c', 'z')]\n\n\n\n### range\u8fed\u4ee3\u5668\n\n\n```python\nR = range(10)\nR\n```\n\n\n\n\n    range(0, 10)\n\n\n\n\n```python\nI = iter(R)\nnext(I)\n```\n\n\n\n\n    0\n\n\n\n\n```python\nnext(I), next(I), next(I), next(I), next(I), next(I), next(I)\n```\n\n\n\n\n    (1, 2, 3, 4, 5, 6, 7)\n\n\n\n### range \u5bf9\u8c61\u53ea\u652f\u6301\u8fed\u4ee3\uff0c\u7d22\u5f15\uff0c\u957f\u5ea6\u51fd\u6570\uff0c\u5b83\u4eec\u4e0d\u652f\u6301\u5176\u4ed6\u7684\u5e8f\u5217\u64cd\u4f5c\n\n\n```python\nlen(R), R[0], R[-1], next(I), I.__next__()\n```\n\n\n\n\n    (10, 0, 9, 8, 9)\n\n\n\n#### \u7248\u672c\u504f\u5dee\uff0cxrange, file.xreadlines() \u53ea\u9002\u7528\u4e8epython 2.x; range\u548copen\u5728python 3.x\u53d6\u800c\u4ee3\u4e4b\n\n\n```python\nrange(10), map(list(range(10)), list(range(10,20))), zip(list(range(10)),list(range(10,20))), filter(bool, open('script1.py'))\n```\n\n\n\n\n    (range(0, 10),\n     <map at 0x132246edf88>,\n     <zip at 0x13224512fc8>,\n     <filter at 0x13222875388>)\n\n\n\n\n```python\nf = open('script1.py')\n```\n\n\n```python\nf is iter(f)\n```\n\n\n\n\n    True\n\n\n\n\n```python\nR = range(3); M = map(abs, list(range(3,6))); Z = zip(list(range(3)),list(range(3,6))); F = filter(bool, open('script1.py')) \n```\n\n\n```python\nR is iter(R), M is iter(M), Z is iter(Z), F is iter(F)\n```\n\n\n\n\n    (False, True, True, True)\n\n\n\n#### \u9664\u4e86range, map\u548czip,\u4ee5\u53cafilter\u90fd\u662f\u81ea\u8eab\u7684\u8fed\u4ee3\u5668\uff08\u5b83\u4eec\u5728\u4e00\u6b21\u904d\u5386\u4e4b\u540e\uff0c\u5c31\u4e0d\u80fd\u5728\u8fdb\u884c\u8bbf\u95ee\u4e86\uff09\n\n\n```python\nf.read()\n```\n\n\n\n\n    'import sys\\nprint(sys.path)\\nx = 2\\nprint(2**33)'\n\n\n\n\n```python\nf.read() # \u4e00\u6b21\u8fed\u4ee3\u5b8c\u5168\u540e\uff0c\u5b83\u4eec\u5c06\u4f1a\u8fed\u4ee3\u5b8c\u5168\n```\n\n\n\n\n    ''\n\n\n\n\n```python\nlist(map(abs,(-1,0,1)))\n```\n\n\n\n\n    [1, 0, 1]\n\n\n\n\n```python\nZ = zip((1,2,3),(10,20,30))\n```\n\n\n```python\nprint('%s \uff01= ' % str(next(Z)), next(Z))\n```\n\n    (1, 10) \uff01=  (2, 20)\n\n\n\n```python\nnext(Z), next(Z), next(Z)\n```\n\n\n\n\n    ((1, 10), (2, 20), (3, 30))\n\n\n\n### map,\u4ee5\u53cazip\u8fd8\u6709filter\u90fd\u662f\u4e00\u6b21\u6027\u8fed\u4ee3\u5668\uff0c\u50cf\u6587\u4ef6\u8fed\u4ee3\u5668\u4e00\u6837\uff0c\u5982\u679c\u4e00\u6b21\u6027\u904d\u5386\u5b8c\u4e4b\u540e,\u5c31\u4f1a\u7ed9\u51fa\u505c\u6b62\u8fed\u4ee3\u7684\u9519\u8bef\uff0c\n\n\n```python\nfor pair in Z: print(pair)\n```\n\n\n```python\nZ = zip((1,2,3),(10,20,30))\nfor pair in Z: print(pair)\n```\n\n    (1, 10)\n    (2, 20)\n    (3, 30)\n\n\n\n```python\nfor pair in Z: print(pair)\n```\n\n\n```python\ndef f(x):\n    if bool(x) == False:\n        return x\n    else: \n        pass\n\nlist(filter(f,['spam','','ni']))\n```\n\n\n\n\n    []\n\n\n\n\n```python\ntype(False)\n```\n\n\n\n\n    bool\n\n\n\n\n```python\nlist('')\n```\n\n\n\n\n    []\n\n\n\n\n```python\nlist(filter(bool,['spam','','ni']))\n```\n\n\n\n\n    ['spam', 'ni']\n\n\n\n#### filter, map, zip\u5b83\u4eec\u65e2\u53ef\u4ee5\u5904\u7406\u53ef\u8fed\u4ee3\u5bf9\u8c61\uff0c\u4e5f\u53ef\u4ee5\u4ea7\u751f\u4e00\u4e2a\u53ef\u8fed\u4ee3\u5bf9\u8c61\n#### range, \u5b57\u5178\u89c6\u56fe\u5bf9\u8c61\u4e0d\u80fd\u5904\u7406\u53ef\u8fed\u4ee3\u5bf9\u8c61\uff0c\u4f46\u662f\u53ef\u4ee5\u4ea7\u751f\u4e00\u4e2a\u53ef\u8fed\u4ee3\u5bf9\u8c61\n\n\n```python\nrange(1,101,2)\n```\n\n\n\n\n    range(1, 101, 2)\n\n\n\n\n```python\nlist(range(1,101,2))\n```\n\n\n\n\n    [1,\n     3,\n     5,\n     7,\n     9,\n     11,\n     13,\n     15,\n     17,\n     19,\n     21,\n     23,\n     25,\n     27,\n     29,\n     31,\n     33,\n     35,\n     37,\n     39,\n     41,\n     43,\n     45,\n     47,\n     49,\n     51,\n     53,\n     55,\n     57,\n     59,\n     61,\n     63,\n     65,\n     67,\n     69,\n     71,\n     73,\n     75,\n     77,\n     79,\n     81,\n     83,\n     85,\n     87,\n     89,\n     91,\n     93,\n     95,\n     97,\n     99]\n\n\n\n### \u591a\u4e2a\u8fed\u4ee3\u5668 vs \u5355\u4e2a\u8fed\u4ee3\u5668\n\n\n```python\nR = range(3)\nR is iter(R)\n```\n\n\n\n\n    False\n\n\n\n\n```python\nZ = zip((1,2,3),(10,12,13))\nI1 = iter(Z)\nI2 = iter(Z)\n```\n\n\n```python\nZ is iter(Z), I1 is Z, I2 is Z\n```\n\n\n\n\n    (True, True, True)\n\n\n\n\n```python\nnext(I1), next(I1), next(I2)\n```\n\n\n\n\n    ((1, 10), (2, 12), (3, 13))\n\n\n\n\n```python\nM = map(abs, (-1,0,1))\nI1 = iter(M); I2 = iter(M)\nprint(next(I1),next(I2),next(I1))\n# next(I2)\n```\n\n    1 0 1\n\n\n\n```python\nR = range(3)\nI1, I2 = iter(R), iter(R)\n```\n\n\n```python\nR is iter(R), I1 is R, I2 is R\n```\n\n\n\n\n    (False, False, False)\n\n\n\n\n```python\n[next(I1), next(I2), next(I1)]\n```\n\n\n\n\n    [0, 0, 1]\n\n\n\n\n```python\nclass Text():\n    \"\"\"\n    This is just an experiment performed for iterations related to classes \n    \"\"\"\n    def PLUS(x,y):  \n        return str(x)+str(y)\n    \"\"\"\n    PLUS can be used to convert two items to strings and add them together, and return the result.\n    \"\"\"\n    def SUBSTR(x,y):\n        return x[:y]\n```\n\n\n```python\nText.PLUS(1,2)\n```\n\n\n\n\n    '12'\n\n\n\n\n```python\nText.SUBSTR('asahfjasfhajfjah',4)\n```\n\n\n\n\n    'asah'\n\n\n\n\n```python\nText.PLUS(5,6789)\n```\n\n\n\n\n    '56789'\n\n\n\n### \u6587\u4ef6\uff0c\u5b57\u5178\u4ee5\u53ca\u5b57\u5178\u7684\u65b9\u6cd5(keys,values,items) \u90fd\u548crange,map,zip,filter\u8fd9\u4e9b\u51fd\u6570\u4e00\u6837\u90fd\u4f1a\u8fd4\u56de\u53ef\u8fed\u4ee3\u5bf9\u8c61\n\n\n```python\nS = \"\"\"As we saw briefly in Chapter 8, in Python 3.0 the dictionary keys, values, and items\nmethods return iterable view objects that generate result items one at a time, instead\nof producing result lists all at once in memory. View items maintain the same physical\nordering as that of the dictionary and reflect changes made to the underlying dictionary.\nNow that we know more about iterators, here\u2019s the rest of the story:\"\"\"\n```\n\n\n```python\nD = dict(enumerate(S))\n```\n\n\n```python\nprint(list(D.keys()), end='')\n```\n\n    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416]\n\n\n```python\nI = iter(D)\n```\n\n\n```python\nnext(I), next(I), next(I), next(I), next(I)\n```\n\n\n\n\n    (0, 1, 2, 3, 4)\n\n\n\n\n```python\nfor key in D.keys(): print(key,end=' ')\nprint('\\n')\nfor key in D: print(key, end=' ')\n```\n\n    0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 \n    \n    0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 \n\n\n```python\nimport numpy as np\nD = dict(a=1,c=3,b=3)\nprint(D)\nD = {'a': 1, 'c': 3, 'b': 2}\nprint(D)\nD = { s : int(i) for s, i in zip('acb', '132')}\nprint(D)\n```\n\n    {'a': 1, 'c': 3, 'b': 3}\n    {'a': 1, 'c': 3, 'b': 2}\n    {'a': 1, 'c': 3, 'b': 2}\n\n\n\n```python\nD = {}\nfor i in [1,2,3]:\n    for s in 'abc':\n        D[s] = i\n```\n\n\n```python\nD\n```\n\n\n\n\n    {'a': 3, 'b': 3, 'c': 3}\n\n\n\n\n```python\nfor k in D: print(k, D[k], end=' ') #\u5e76\u4e0d\u6309\u7167ASCII\u7684\u987a\u5e8f\n```\n\n    a 1 c 3 b 2 \n\n\n```python\nfor  k in sorted(D.keys()): print(k,D[k], end=' ')\nfor k in sorted(D): print(k, D[k], end= ' ')\n```\n\n    a 1 b 2 c 3 a 1 b 2 c 3 \n\n\n```python\nhelp(Text)\n```\n\n    Help on class Text in module __main__:\n    \n    class Text(builtins.object)\n     |  This is just an experiment performed for iterations related to classes\n     |  \n     |  Methods defined here:\n     |  \n     |  PLUS(x, y)\n     |  \n     |  SUBSTR(x, y)\n     |  \n     |  ----------------------------------------------------------------------\n     |  Data descriptors defined here:\n     |  \n     |  __dict__\n     |      dictionary for instance variables (if defined)\n     |  \n     |  __weakref__\n     |      list of weak references to the object (if defined)\n    \n\n\n\n```python\n\n```\n", "meta": {"hexsha": "0f038081881816c44704ac4c7a0de0e9a3423a27", "size": 188393, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter 14 Iterations and Comprehensions (2).ipynb", "max_stars_repo_name": "nickcafferry/Learning-Python-4th-Edition", "max_stars_repo_head_hexsha": "6684afc3a97d9719c3cdb2d451959ac15cc896cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-08T07:56:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-08T07:56:09.000Z", "max_issues_repo_path": "Chapter 14 Iterations and Comprehensions (2).ipynb", "max_issues_repo_name": "nickcafferry/Learning-Python-4th-Edition", "max_issues_repo_head_hexsha": "6684afc3a97d9719c3cdb2d451959ac15cc896cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter 14 Iterations and Comprehensions (2).ipynb", "max_forks_repo_name": "nickcafferry/Learning-Python-4th-Edition", "max_forks_repo_head_hexsha": "6684afc3a97d9719c3cdb2d451959ac15cc896cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.095669195, "max_line_length": 16680, "alphanum_fraction": 0.6672116268, "converted": true, "num_tokens": 28078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24220562872535945, "lm_q2_score": 0.06465348700453777, "lm_q1q2_score": 0.015659438469220927}}
{"text": "# Setup\n\n\n```python\n%matplotlib inline\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\n```\n\n\n```python\ndate_filename = \"2018-01-01_2018-01-31\"\n```\n\n\n```python\ndata = pd.read_csv(\"articles_\" + date_filename + \".csv\", index_col=\"id\", \\\n                   parse_dates=[\"published\", \"discovered\"])\ndata.head()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>publisher_name</th>\n      <th>publisher_id</th>\n      <th>mins_as_lead</th>\n      <th>mins_on_front</th>\n      <th>num_articles_on_front</th>\n      <th>fb_brand_page</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>6709592f25cbe37c8c42157a3e31529a6997d919</th>\n      <td>https://www.thetimes.co.uk/article/the-ashes-e...</td>\n      <td>The Ashes: England need 90mph-plus bowlers, sa...</td>\n      <td>2018-01-01 11:44:10.414</td>\n      <td>2018-01-01</td>\n      <td>6</td>\n      <td>0.032787</td>\n      <td>2018-01-01T19:02:07.273Z</td>\n      <td>0</td>\n      <td>4</td>\n      <td>2</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>735</td>\n      <td>224.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>125.0</td>\n    </tr>\n    <tr>\n      <th>e11638f9f5eb587404372cc1f1554a828ae6ef90</th>\n      <td>https://www.thetimes.co.uk/article/wilfried-za...</td>\n      <td>Wilfried Zaha did well and should not face ban...</td>\n      <td>2018-01-01 11:44:10.834</td>\n      <td>2018-01-01</td>\n      <td>0</td>\n      <td>0.000000</td>\n      <td>2018-01-01T19:02:07.293Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>270</td>\n      <td>224.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>125.0</td>\n    </tr>\n    <tr>\n      <th>9b64c5e6ba5cfd51dad3619a8ea341eba1a12d01</th>\n      <td>https://www.thetimes.co.uk/article/crystal-pal...</td>\n      <td>Crystal Palace worked hard to stem Manchester ...</td>\n      <td>2018-01-01 11:44:12.831</td>\n      <td>2018-01-01</td>\n      <td>0</td>\n      <td>0.000000</td>\n      <td>2018-01-01T19:02:07.303Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>735</td>\n      <td>224.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>125.0</td>\n    </tr>\n    <tr>\n      <th>bc098ae138bc4659f0d723dd13a6df94bf27de1c</th>\n      <td>https://www.thetimes.co.uk/article/british-ceo...</td>\n      <td>British CEO Richard Cousins and family killed ...</td>\n      <td>2018-01-01 10:44:08.985</td>\n      <td>2018-01-01</td>\n      <td>2</td>\n      <td>0.032787</td>\n      <td>2018-01-01T13:57:17.529Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>724</td>\n      <td>795</td>\n      <td>224.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>125.0</td>\n    </tr>\n    <tr>\n      <th>295570fc56f70ffec0f5c1c13028640a988f90e1</th>\n      <td>https://www.thetimes.co.uk/article/referee-jon...</td>\n      <td>Referee Jon Moss in wrong place to award penalty</td>\n      <td>2018-01-01 11:39:07.331</td>\n      <td>2018-01-01</td>\n      <td>0</td>\n      <td>0.000000</td>\n      <td>2018-01-01T19:57:06.317Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>740</td>\n      <td>224.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>125.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n# Response Score\n\nThe response score is a number between 0 and 50 that indicates the level of response to an article.\n\n\n\nPerhaps in the future we may choose to include other factors, but for now we just include engagements on Facebook. The maximum score of 50 should be achieved by an article that does really well compared with others.\n\n\n```python\npd.options.display.float_format = '{:.2f}'.format\ndata.fb_engagements.describe([0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count    153117.00\n    mean       1108.49\n    std        8278.99\n    min           0.00\n    50%          26.00\n    75%         256.00\n    90%        1621.00\n    95%        4095.20\n    99%       19918.88\n    99.5%     32935.68\n    99.9%     89239.94\n    max     1077082.00\n    Name: fb_engagements, dtype: float64\n\n\n\nThere's 1 article with more than 1 million engagements this month.\n\n\n```python\ndata[data.fb_engagements > 1000000]\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>publisher_name</th>\n      <th>publisher_id</th>\n      <th>mins_as_lead</th>\n      <th>mins_on_front</th>\n      <th>num_articles_on_front</th>\n      <th>fb_brand_page</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>bff3221285a08a6b4a931a08fa55a8dab8dcd83a</th>\n      <td>https://www.washingtonpost.com/politics/trump-...</td>\n      <td>Trump attacks protections for immigrants from ...</td>\n      <td>2018-01-11 21:43:16.311</td>\n      <td>2018-01-11 21:37:00</td>\n      <td>1077082</td>\n      <td>2928.83</td>\n      <td>2018-01-11T22:16:05.460Z</td>\n      <td>362995</td>\n      <td>622561</td>\n      <td>91526</td>\n      <td>The Washington Post</td>\n      <td>washingtonpost_com</td>\n      <td>725</td>\n      <td>2158</td>\n      <td>87.00</td>\n      <td>True</td>\n      <td>6113598.00</td>\n      <td>2018-01-11T21:41:41.000Z</td>\n      <td>191</td>\n      <td>313.00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndata.fb_engagements.mode()\n```\n\n\n\n\n    0    0\n    dtype: int64\n\n\n\n*november* Going back to the enagement counts, we see the mean is 1,117, mode is zero, median is 24, 90th percentile is 1,453, 99th percentile is 21,166, 99.5th percentile is 33,982. The standard deviation is 8,083, significantly higher than the mean, so this is not a normal distribution. \n\n*december* Going back to the enagement counts, we see the mean is 1,106, mode is zero, median is 24, 90th percentile is 1,545, 99th percentile is 20,228, 99.5th percentile is 32,446. The standard deviation is 9,852, significantly higher than the mean, so this is not a normal distribution. \n\n*january 2018* Going back to the enagement counts, we see the mean is 1,108, mode is zero, median is 26, 90th percentile is 1,621, 99th percentile is 19,918, 99.5th percentile is 32,935. The standard deviation is 8,278, significantly higher than the mean, so this is not a normal distribution. \n\nKey publishers stats\n\n\n```python\ndata.groupby(\"publisher_id\").agg({'url': 'count', 'fb_engagements': ['sum', 'median', 'mean']})\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th>url</th>\n      <th colspan=\"3\" halign=\"left\">fb_engagements</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>count</th>\n      <th>sum</th>\n      <th>median</th>\n      <th>mean</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>28</td>\n      <td>68554</td>\n      <td>1762.00</td>\n      <td>2448.36</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>12656</td>\n      <td>8743859</td>\n      <td>29.00</td>\n      <td>690.89</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>2661</td>\n      <td>11465343</td>\n      <td>275.00</td>\n      <td>4308.66</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>49</td>\n      <td>39390</td>\n      <td>232.00</td>\n      <td>803.88</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>1457</td>\n      <td>4642842</td>\n      <td>215.00</td>\n      <td>3186.58</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>4435</td>\n      <td>19180181</td>\n      <td>541.00</td>\n      <td>4324.73</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>24668</td>\n      <td>16357051</td>\n      <td>28.00</td>\n      <td>663.09</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>484</td>\n      <td>122211</td>\n      <td>36.00</td>\n      <td>252.50</td>\n    </tr>\n    <tr>\n      <th>evolvepolitics_com</th>\n      <td>64</td>\n      <td>200556</td>\n      <td>1325.50</td>\n      <td>3133.69</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>6824</td>\n      <td>17698744</td>\n      <td>48.00</td>\n      <td>2593.60</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>4725</td>\n      <td>400374</td>\n      <td>4.00</td>\n      <td>84.74</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>6443</td>\n      <td>10846012</td>\n      <td>25.00</td>\n      <td>1683.38</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>6278</td>\n      <td>4906592</td>\n      <td>38.00</td>\n      <td>781.55</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>525</td>\n      <td>555345</td>\n      <td>94.00</td>\n      <td>1057.80</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>3835</td>\n      <td>1942400</td>\n      <td>66.00</td>\n      <td>506.49</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>156</td>\n      <td>1952</td>\n      <td>7.00</td>\n      <td>12.51</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>11168</td>\n      <td>8388679</td>\n      <td>45.00</td>\n      <td>751.14</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>2061</td>\n      <td>6240679</td>\n      <td>432.00</td>\n      <td>3027.99</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>470</td>\n      <td>65882</td>\n      <td>20.00</td>\n      <td>140.17</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>2105</td>\n      <td>7155373</td>\n      <td>258.00</td>\n      <td>3399.23</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>4605</td>\n      <td>18833832</td>\n      <td>249.00</td>\n      <td>4089.87</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>246</td>\n      <td>86229</td>\n      <td>162.50</td>\n      <td>350.52</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>31</td>\n      <td>46538</td>\n      <td>279.00</td>\n      <td>1501.23</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>5849</td>\n      <td>1964369</td>\n      <td>21.00</td>\n      <td>335.85</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>2521</td>\n      <td>2049423</td>\n      <td>297.00</td>\n      <td>812.94</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>121</td>\n      <td>45462</td>\n      <td>241.00</td>\n      <td>375.72</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>6619</td>\n      <td>2342935</td>\n      <td>21.00</td>\n      <td>353.97</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>175</td>\n      <td>172030</td>\n      <td>636.00</td>\n      <td>983.03</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>8208</td>\n      <td>8937561</td>\n      <td>125.00</td>\n      <td>1088.88</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>9479</td>\n      <td>342359</td>\n      <td>1.00</td>\n      <td>36.12</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>23426</td>\n      <td>13972718</td>\n      <td>0.00</td>\n      <td>596.46</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>330</td>\n      <td>348369</td>\n      <td>34.00</td>\n      <td>1055.66</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>415</td>\n      <td>1564515</td>\n      <td>137.00</td>\n      <td>3769.92</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\n\nnon_zero_fb_enagagements = data.fb_engagements[data.fb_engagements > 0]\n```\n\nThat's a bit better, but still way too clustered at the low end. Let's look at a log normal distribution.\n\n\n```python\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\nninety = data.fb_engagements.quantile(.90)\nninetyfive = data.fb_engagements.quantile(.95)\nninetynine = data.fb_engagements.quantile(.99)\n\nplt.figure(figsize=(12,4.5))\nplt.hist(np.log(non_zero_fb_enagagements + median), bins=50)\nplt.axvline(np.log(mean), linestyle=':', label=f'Mean ({mean:,.0f})', color='green')\nplt.axvline(np.log(median), label=f'Median ({median:,.0f})', color='green')\nplt.axvline(np.log(ninety), linestyle='--', label=f'90% percentile ({ninety:,.0f})', color='red')\nplt.axvline(np.log(ninetyfive), linestyle='-.', label=f'95% percentile ({ninetyfive:,.0f})', color='red')\nplt.axvline(np.log(ninetynine), linestyle=':', label=f'99% percentile ({ninetynine:,.0f})', color='red')\nleg = plt.legend()\n\n```\n\n\n```python\neng = data.fb_engagements[(data.fb_engagements < 5000)]\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\nninety = data.fb_engagements.quantile(.90)\nninetyfive = data.fb_engagements.quantile(.95)\nninetynine = data.fb_engagements.quantile(.99)\n\nplt.figure(figsize=(15,7))\nplt.hist(eng, bins=50)\nplt.title(\"Article count by engagements\")\nplt.axvline(median, label=f'Median ({median:,.0f})', color='green')\nplt.axvline(mean, linestyle=':', label=f'Mean ({mean:,.0f})', color='green')\nplt.axvline(ninety, linestyle='--', label=f'90% percentile ({ninety:,.0f})', color='red')\nplt.axvline(ninetyfive, linestyle='-.', label=f'95% percentile ({ninetyfive:,.0f})', color='red')\n# plt.axvline(ninetynine, linestyle=':', label=f'99% percentile ({ninetynine:,.0f})', color='red')\nleg = plt.legend()\n\n```\n\n\n```python\nlog_engagements = (non_zero_fb_enagagements\n                   .clip_upper(data.fb_engagements.quantile(.999))\n                   .apply(lambda x: np.log(x + median))\n                  )\nlog_engagements.describe()\n```\n\n\n\n\n    count   124439.00\n    mean         5.04\n    std          1.75\n    min          3.30\n    25%          3.56\n    50%          4.44\n    75%          6.10\n    max         11.40\n    Name: fb_engagements, dtype: float64\n\n\n\nUse standard feature scaling to bring that to a 1 to 50 range\n\n\n\n```python\ndef scale_log_engagements(engagements_logged):\n    return np.ceil(\n        50 * (engagements_logged - log_engagements.min()) / (log_engagements.max() - log_engagements.min())\n    )\n\ndef scale_engagements(engagements):\n    return scale_log_engagements(np.log(engagements + median))\n\nscaled_non_zero_engagements = scale_log_engagements(log_engagements)\nscaled_non_zero_engagements.describe()\n```\n\n\n\n\n    count   124439.00\n    mean        11.22\n    std         10.81\n    min          0.00\n    25%          2.00\n    50%          8.00\n    75%         18.00\n    max         50.00\n    Name: fb_engagements, dtype: float64\n\n\n\n\n```python\n# add in the zeros, as zero\nscaled_engagements = pd.concat([scaled_non_zero_engagements, data.fb_engagements[data.fb_engagements == 0]])\n```\n\n\n```python\nproposed = pd.DataFrame({\"fb_engagements\": data.fb_engagements, \"response_score\": scaled_engagements})\nproposed.response_score.plot.hist(bins=50)\n```\n\nLooks good to me, lets save that.\n\n\n```python\ndata[\"response_score\"] = proposed.response_score\n```\n\n### Proposal\n\nThe maximum of 50 points is awarded when the engagements are greater than the 99.9th percentile, rolling over the last month. \n\ni.e. where $limit$ is the 99.5th percentile of engagements calculated over the previous month, the response score for article $a$ is:\n\n\\begin{align}\nbasicScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   \\log(\\min(engagements_a,limit) + median(engagements))      & \\text{if } engagements_a > 0\n\\end{cases} \\\\\nresponseScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   50 \\cdot \\frac{basicScore_a - \\min(basicScore)}{\\max(basicScore) - \\min(basicScore)}       & \\text{if } engagements_a > 0\n\\end{cases} \\\\\n\\\\\n\\text{The latter equation can be expanded to:} \\\\\nresponseScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   50 \\cdot \n   \\frac{\\log(\\min(engagements_a,limit) + median(engagements)) - \\log(1 + median(engagements))}\n   {\\log(limit + median(engagements)) - \\log(1 + median(engagements))}       & \\text{if } engagements_a > 0\n\\end{cases} \\\\\n\\end{align}\n\n# Promotion Score\n\nThe aim of the promotion score is to indicate how important the article was to the publisher, by tracking where they chose to promote it. This is a number between 0 and 50 comprised of:\n\n- 20 points based on whether the article was promoted as the \"lead\" story on the publisher's home page\n- 15 points based on how long the article was promoted anywhere on the publisher's home page\n- 15 points based on whether the article was promoted on the publisher's main facebook brand page\n\nThe first two should be scaled by the popularity/reach of the home page, for which we use the alexa page rank as a proxy.\n\nThe last should be scaled by the popularity/reach of the brand page, for which we use the number of likes the brand page has.\n\n### Lead story (20 points)\n\n\n```python\ndata.mins_as_lead.describe([0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count   153117.00\n    mean         9.31\n    std         95.51\n    min          0.00\n    50%          0.00\n    75%          0.00\n    90%          0.00\n    95%          0.00\n    99%        274.00\n    99.5%      565.00\n    99.9%     1204.88\n    max      11522.00\n    Name: mins_as_lead, dtype: float64\n\n\n\nAs expected, the vast majority of articles don't make it as lead. Let's explore how long typically publishers put something as lead for.\n\n\n```python\nlead_articles = data[data.mins_as_lead > 0]\n```\n\n\n```python\nlead_articles.mins_as_lead.describe([0.25, 0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count    4319.00\n    mean      329.99\n    std       466.47\n    min         4.00\n    25%        89.00\n    50%       180.00\n    75%       399.00\n    90%       834.00\n    95%      1065.50\n    99%      1691.22\n    99.5%    2546.28\n    99.9%    5381.40\n    max     11522.00\n    Name: mins_as_lead, dtype: float64\n\n\n\n\n```python\nlead_articles.mins_as_lead.plot.hist(bins=50)\n```\n\nFor lead, it's a  significant thing for an article to be lead at all, so although we want to penalise articles that were lead for a very short time, mostly we want to score the maximum even if it wasn't lead for ages. So we'll give maximum points when something has been lead for an hour.\n\n\n```python\nlead_articles.mins_as_lead.clip_upper(60).plot.hist(bins=50)\n```\n\nWe also want to scale this by the alexa page rank, such that the maximum score of 20 points is for an article that was on the front for 4 hours for the most popular site.\n\nSo lets explore the alexa nunbers.\n\n\n```python\nalexa_ranks = data.groupby(by=\"publisher_id\").alexa_rank.mean().sort_values()\nalexa_ranks\n```\n\n\n\n\n    publisher_id\n    bbc_co_uk                               96\n    cnn_com                                105\n    nytimes_com                            120\n    theguardian_com                        142\n    buzzfeed_com                           147\n    dailymail_co_uk                        158\n    washingtonpost_com                     191\n    huffingtonpost_com                     215\n    foxnews_com                            285\n    rt_com                                 365\n    telegraph_co_uk                        370\n    independent_co_uk                      386\n    reuters_com                            497\n    npr_org                                594\n    lemonde_fr                             618\n    mirror_co_uk                           706\n    nbcnews_com                            826\n    breitbart_com                          994\n    ft_com                                1596\n    economist_com                         1825\n    indy100_com                           5014\n    thetimes_co_uk                        6435\n    newstatesman_com                     12769\n    thecanary_co                         15686\n    propublica_org                       16066\n    yournewswire_com                     22568\n    order-order_com                      32515\n    anotherangryvoice_blogspot_co_uk     77827\n    westmonster_com                      97775\n    evolvepolitics_com                  119412\n    skwawkbox_org                       152475\n    libdemvoice_org                     344992\n    brexitcentral_com                   469149\n    Name: alexa_rank, dtype: int64\n\n\n\n\n```python\nalexa_ranks.plot.bar(figsize=[10,5])\n```\n\nLet's try the simple option first: just divide the number of minutes as lead by the alexa rank. What's the scale of numbers we get then.\n\n\n```python\nlead_proposal_1 = lead_articles.mins_as_lead.clip_upper(60) / lead_articles.alexa_rank\nlead_proposal_1.plot.hist()\n```\n\nLooks like there's too much of a cluster around 0. Have we massively over penalised the publishers with a high alexa rank?\n\n\n```python\nlead_proposal_1.groupby(data.publisher_id).mean().plot.bar(figsize=[10,5])\n```\n\nYes. Let's try taking the log of the alexa rank and see if that looks better.\n\n\n```python\nlead_proposal_2 = (lead_articles.mins_as_lead.clip_upper(60) / np.log(lead_articles.alexa_rank))\nlead_proposal_2.plot.hist()\n```\n\n\n```python\nlead_proposal_2.groupby(data.publisher_id).describe()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>25%</th>\n      <th>50%</th>\n      <th>75%</th>\n      <th>max</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>28.00</td>\n      <td>5.33</td>\n      <td>0.00</td>\n      <td>5.33</td>\n      <td>5.33</td>\n      <td>5.33</td>\n      <td>5.33</td>\n      <td>5.33</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>111.00</td>\n      <td>12.88</td>\n      <td>1.25</td>\n      <td>5.26</td>\n      <td>13.15</td>\n      <td>13.15</td>\n      <td>13.15</td>\n      <td>13.15</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>202.00</td>\n      <td>8.42</td>\n      <td>1.16</td>\n      <td>1.30</td>\n      <td>8.69</td>\n      <td>8.69</td>\n      <td>8.69</td>\n      <td>8.69</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>40.00</td>\n      <td>4.59</td>\n      <td>0.00</td>\n      <td>4.59</td>\n      <td>4.59</td>\n      <td>4.59</td>\n      <td>4.59</td>\n      <td>4.59</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>331.00</td>\n      <td>11.55</td>\n      <td>1.69</td>\n      <td>2.00</td>\n      <td>12.02</td>\n      <td>12.02</td>\n      <td>12.02</td>\n      <td>12.02</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>212.00</td>\n      <td>12.39</td>\n      <td>1.82</td>\n      <td>1.07</td>\n      <td>12.89</td>\n      <td>12.89</td>\n      <td>12.89</td>\n      <td>12.89</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>180.00</td>\n      <td>11.63</td>\n      <td>1.11</td>\n      <td>2.96</td>\n      <td>11.85</td>\n      <td>11.85</td>\n      <td>11.85</td>\n      <td>11.85</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>65.00</td>\n      <td>7.54</td>\n      <td>1.67</td>\n      <td>0.67</td>\n      <td>7.99</td>\n      <td>7.99</td>\n      <td>7.99</td>\n      <td>7.99</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>106.00</td>\n      <td>10.45</td>\n      <td>1.09</td>\n      <td>0.88</td>\n      <td>10.61</td>\n      <td>10.61</td>\n      <td>10.61</td>\n      <td>10.61</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>98.00</td>\n      <td>7.62</td>\n      <td>1.56</td>\n      <td>0.54</td>\n      <td>8.14</td>\n      <td>8.14</td>\n      <td>8.14</td>\n      <td>8.14</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>162.00</td>\n      <td>10.96</td>\n      <td>1.19</td>\n      <td>2.61</td>\n      <td>11.17</td>\n      <td>11.17</td>\n      <td>11.17</td>\n      <td>11.17</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>133.00</td>\n      <td>9.67</td>\n      <td>1.63</td>\n      <td>0.67</td>\n      <td>10.07</td>\n      <td>10.07</td>\n      <td>10.07</td>\n      <td>10.07</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>132.00</td>\n      <td>5.97</td>\n      <td>1.83</td>\n      <td>0.47</td>\n      <td>5.75</td>\n      <td>7.04</td>\n      <td>7.04</td>\n      <td>7.04</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>203.00</td>\n      <td>8.09</td>\n      <td>2.51</td>\n      <td>0.62</td>\n      <td>8.56</td>\n      <td>9.34</td>\n      <td>9.34</td>\n      <td>9.34</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>135.00</td>\n      <td>4.60</td>\n      <td>0.47</td>\n      <td>1.49</td>\n      <td>4.71</td>\n      <td>4.71</td>\n      <td>4.71</td>\n      <td>4.71</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>316.00</td>\n      <td>8.61</td>\n      <td>1.53</td>\n      <td>0.61</td>\n      <td>9.15</td>\n      <td>9.15</td>\n      <td>9.15</td>\n      <td>9.15</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>115.00</td>\n      <td>8.52</td>\n      <td>1.48</td>\n      <td>0.74</td>\n      <td>8.93</td>\n      <td>8.93</td>\n      <td>8.93</td>\n      <td>8.93</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>64.00</td>\n      <td>5.88</td>\n      <td>1.28</td>\n      <td>1.59</td>\n      <td>6.35</td>\n      <td>6.35</td>\n      <td>6.35</td>\n      <td>6.35</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>166.00</td>\n      <td>8.95</td>\n      <td>1.45</td>\n      <td>0.78</td>\n      <td>9.39</td>\n      <td>9.39</td>\n      <td>9.39</td>\n      <td>9.39</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>61.00</td>\n      <td>12.32</td>\n      <td>1.29</td>\n      <td>2.92</td>\n      <td>12.53</td>\n      <td>12.53</td>\n      <td>12.53</td>\n      <td>12.53</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>243.00</td>\n      <td>4.59</td>\n      <td>1.52</td>\n      <td>0.48</td>\n      <td>3.37</td>\n      <td>5.78</td>\n      <td>5.78</td>\n      <td>5.78</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>15.00</td>\n      <td>6.20</td>\n      <td>0.00</td>\n      <td>6.20</td>\n      <td>6.20</td>\n      <td>6.20</td>\n      <td>6.20</td>\n      <td>6.20</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>97.00</td>\n      <td>9.52</td>\n      <td>0.99</td>\n      <td>2.42</td>\n      <td>9.66</td>\n      <td>9.66</td>\n      <td>9.66</td>\n      <td>9.66</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>154.00</td>\n      <td>9.56</td>\n      <td>1.98</td>\n      <td>0.68</td>\n      <td>10.17</td>\n      <td>10.17</td>\n      <td>10.17</td>\n      <td>10.17</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>120.00</td>\n      <td>4.76</td>\n      <td>0.70</td>\n      <td>1.68</td>\n      <td>5.03</td>\n      <td>5.03</td>\n      <td>5.03</td>\n      <td>5.03</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>104.00</td>\n      <td>9.79</td>\n      <td>1.67</td>\n      <td>0.85</td>\n      <td>10.15</td>\n      <td>10.15</td>\n      <td>10.15</td>\n      <td>10.15</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>162.00</td>\n      <td>4.87</td>\n      <td>1.65</td>\n      <td>0.93</td>\n      <td>4.04</td>\n      <td>5.69</td>\n      <td>6.21</td>\n      <td>6.21</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>156.00</td>\n      <td>11.59</td>\n      <td>1.90</td>\n      <td>1.01</td>\n      <td>12.11</td>\n      <td>12.11</td>\n      <td>12.11</td>\n      <td>12.11</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>70.00</td>\n      <td>6.80</td>\n      <td>0.35</td>\n      <td>3.88</td>\n      <td>6.84</td>\n      <td>6.84</td>\n      <td>6.84</td>\n      <td>6.84</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>78.00</td>\n      <td>11.22</td>\n      <td>1.08</td>\n      <td>2.67</td>\n      <td>11.42</td>\n      <td>11.42</td>\n      <td>11.42</td>\n      <td>11.42</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>76.00</td>\n      <td>5.01</td>\n      <td>0.72</td>\n      <td>0.87</td>\n      <td>5.22</td>\n      <td>5.22</td>\n      <td>5.22</td>\n      <td>5.22</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>184.00</td>\n      <td>5.68</td>\n      <td>0.64</td>\n      <td>3.29</td>\n      <td>5.99</td>\n      <td>5.99</td>\n      <td>5.99</td>\n      <td>5.99</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nlead_proposal_2.groupby(data.publisher_id).min().plot.bar(figsize=[10,5])\n```\n\nThat looks about right, as long as the smaller publishers were closer to zero. So let's apply feature scaling to this, to give a number between 1 and 20. (Anything not as lead will pass though as zero.)\n\n\n```python\ndef rescale(series):\n    return (series - series.min()) / (series.max() - series.min())\n\nlead_proposal_3 = np.ceil(20 * rescale(lead_proposal_2))\n```\n\n\n```python\nlead_proposal_2.min(), lead_proposal_2.max()\n```\n\n\n\n\n    (0.46948415885821004, 13.145359968846892)\n\n\n\n\n```python\nlead_proposal_3.plot.hist()\n```\n\n\n```python\nlead_proposal_3.groupby(data.publisher_id).median().plot.bar(figsize=[10,5])\n```\n\n\n```python\ndata[\"lead_score\"] = pd.concat([lead_proposal_3, data.mins_as_lead[data.mins_as_lead==0]])\n```\n\n\n```python\ndata.lead_score.value_counts().sort_index()\n```\n\n\n\n\n    0.00     148799\n    1.00         37\n    2.00         46\n    3.00         40\n    4.00         59\n    5.00         58\n    6.00         79\n    7.00        242\n    8.00        249\n    9.00        310\n    10.00       171\n    11.00       176\n    12.00        87\n    13.00       307\n    14.00       531\n    15.00       254\n    16.00       359\n    17.00       266\n    18.00       250\n    19.00       441\n    20.00       356\n    Name: lead_score, dtype: int64\n\n\n\n\n```python\ndata.lead_score.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    8.00\n    bbc_co_uk                          20.00\n    breitbart_com                      13.00\n    brexitcentral_com                   7.00\n    buzzfeed_com                       19.00\n    cnn_com                            20.00\n    dailymail_co_uk                    18.00\n    economist_com                      12.00\n    evolvepolitics_com                  0.00\n    foxnews_com                        17.00\n    ft_com                             13.00\n    huffingtonpost_com                 17.00\n    independent_co_uk                  16.00\n    indy100_com                        11.00\n    lemonde_fr                         14.00\n    libdemvoice_org                     7.00\n    mirror_co_uk                       14.00\n    nbcnews_com                        14.00\n    newstatesman_com                   10.00\n    npr_org                            15.00\n    nytimes_com                        20.00\n    order-order_com                     9.00\n    propublica_org                     10.00\n    reuters_com                        15.00\n    rt_com                             16.00\n    skwawkbox_org                       8.00\n    telegraph_co_uk                    16.00\n    thecanary_co                       10.00\n    theguardian_com                    19.00\n    thetimes_co_uk                     11.00\n    washingtonpost_com                 18.00\n    westmonster_com                     8.00\n    yournewswire_com                    9.00\n    Name: lead_score, dtype: float64\n\n\n\nIn summary then, score for article $a$ is:\n\n\n$$\nunscaledLeadScore_a = \\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)}\\\\\nleadScore_a = 19 \\cdot \n\\frac{unscaledLeadScore_a - \\min(unscaledLeadScore)}\n{\\max(unscaledLeadScore) - \\min(unscaledLeadScore)} \n+ 1\n$$\n\nSince the minium value of $minsAsLead$ is 1, $\\min(unscaledLeadScore)$ is pretty insignificant. So we can simplify this to:\n\n$$\nleadScore_a = 20 \\cdot \n\\frac{unscaledLeadScore_a }\n     {\\max(unscaledLeadScore)} \n$$\n\nor: \n\n$$\nleadScore_a = 20 \\cdot \n\\frac{\\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)} }\n     {\\frac{60}{\\log(\\max(alexaRank))}} \n$$\n\n$$\nleadScore_a = \\left( 20 \\cdot \n\\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)} \\cdot\n     {\\frac{\\log(\\max(alexaRank))}{60}} \\right)\n$$\n\n## Time on front score (15 points)\n\nThis is similar to time as lead, so lets try doing the same calculation, except we also want to factor in the number of slots on the front:\n\n\n$$frontScore_a = \n15 \n\\left(\\frac{\\min(minsOnFront_a, 1440)}{alexaRank_a \\cdot numArticlesOnFront_a}\\right) \n\\left( \\frac{\\min(alexaRank \\cdot numArticlesOnFront)}{1440} \\right)$$\n\n\n```python\n(data.alexa_rank * data.num_articles_on_front).min() / 1440\n```\n\n\n\n\n    2.4500000000000002\n\n\n\n\n```python\ntime_on_front_proposal_1 = np.ceil(data.mins_on_front.clip_upper(1440) / (data.alexa_rank * data.num_articles_on_front) * (2.45) * 15)\n```\n\n\n```python\ntime_on_front_proposal_1.plot.hist(figsize=(15, 7), bins=15)\n```\n\n\n```python\ntime_on_front_proposal_1.value_counts().sort_index()\n```\n\n\n\n\n    1.00     75945\n    2.00      7136\n    3.00      4789\n    4.00      4278\n    5.00       878\n    6.00       691\n    7.00       586\n    8.00       461\n    9.00       785\n    10.00      265\n    11.00      360\n    12.00      242\n    13.00      143\n    14.00       70\n    15.00       49\n    dtype: int64\n\n\n\n\n```python\ntime_on_front_proposal_1.groupby(data.publisher_id).sum()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk      28.00\n    bbc_co_uk                          15065.00\n    breitbart_com                       2511.00\n    brexitcentral_com                     49.00\n    buzzfeed_com                       10691.00\n    cnn_com                            12825.00\n    dailymail_co_uk                    14849.00\n    economist_com                        306.00\n    evolvepolitics_com                    60.00\n    foxnews_com                         7982.00\n    ft_com                              3173.00\n    huffingtonpost_com                  8120.00\n    independent_co_uk                   4474.00\n    indy100_com                          524.00\n    lemonde_fr                          3831.00\n    libdemvoice_org                      156.00\n    mirror_co_uk                       10157.00\n    nbcnews_com                         1916.00\n    newstatesman_com                     469.00\n    npr_org                             2713.00\n    nytimes_com                         9621.00\n    order-order_com                      244.00\n    propublica_org                        31.00\n    reuters_com                         6819.00\n    rt_com                              4496.00\n    skwawkbox_org                        121.00\n    telegraph_co_uk                     4614.00\n    thecanary_co                         173.00\n    theguardian_com                    12648.00\n    thetimes_co_uk                      9453.00\n    washingtonpost_com                  9329.00\n    westmonster_com                      312.00\n    yournewswire_com                     415.00\n    dtype: float64\n\n\n\nThat looks good to me.\n\n\n```python\ndata[\"front_score\"] = np.ceil(data.mins_on_front.clip_upper(1440) / (data.alexa_rank * data.num_articles_on_front) * (2.45) * 15).fillna(0)\n```\n\n\n```python\ndata.front_score \n```\n\n\n\n\n    id\n    6709592f25cbe37c8c42157a3e31529a6997d919   1.00\n    e11638f9f5eb587404372cc1f1554a828ae6ef90   1.00\n    9b64c5e6ba5cfd51dad3619a8ea341eba1a12d01   1.00\n    bc098ae138bc4659f0d723dd13a6df94bf27de1c   1.00\n    295570fc56f70ffec0f5c1c13028640a988f90e1   1.00\n    ff04d53263605f5efc6c6d76caf017ba8e5b8509   1.00\n    970471ce0301861cd2b0779962dc3472b046ecea   1.00\n    4a168ba227abeb2a58f82f30fff5b32a03f29385   1.00\n    c7597aad01cd3c53687acb8b61508bda6e5d225a   1.00\n    56f399ce2d7a57364e10d40374cdc97179a081ad   1.00\n    f4e3b123fc07a47ccf453898247445941fce5698   1.00\n    cde01d750345c11f090de5878b5670911764023a   1.00\n    bff2cf0f5dccd112114bee2bef44b9b997614c8f   1.00\n    80ac264faa1e7d33d259e7fb8fd23e407b206a5f   1.00\n    e0c6d47ad0eff33ec01de70358e9ac08ac174ceb   1.00\n    cabb3998d53aad09eccecf39fdff2439f4f5a633   1.00\n    61203ee49335a3ef45f2ce2569add6ee81218656   1.00\n    64062be203288cee65392ecf145b251530a6bcae   1.00\n    bed3040ac7e43058687d705dd6a81e0f4bd68fdc   1.00\n    bc7d67564c937e73a95973a15df2cf188a048599   1.00\n    fcda9a52108c426979159fdf116b91633e72e154   1.00\n    f2e678a5666b127f3c6fda0d3ce314dcd6cec070   1.00\n    e47f06fdafae541bc8dda3119ab54bc2ca70baa5   1.00\n    12758258a478a89fa010a9d4da88325261c2f61a   1.00\n    9677da854a3c51cd71e35be22f360a406fc828a3   1.00\n    cf7182e390027ca370b7662bcb7f3324219320bc   1.00\n    09a289c1510acd123077b19d8ab48e2095da68eb   1.00\n    bfa1de8df0c0d5c7e97d009d4feb92c4de3ca1d2   1.00\n    cffe241f08e165304a328d0046b6d92065afad36   1.00\n    4f7e173e04e51edb008f9d4e3a4502ef097fb1ad   1.00\n                                               ... \n    3fe9dca55849d2b25cdc29941d7e011b2ca955fd   1.00\n    af56fd11c764c962f6120e27158ecaa3339674da   2.00\n    8bcef6d882aae991f7d3c80b1ed25465770e7c19   0.00\n    7c57ac5a380f98e778257ab9dace202c21423097   1.00\n    de3f92d120372ac0679142290e43c77bfc44e691   1.00\n    16b149d23d8cd5e353b3fb8f0d0bb3bacf585467   2.00\n    7c3e0bc18a1e846a754f6ca18aa30651f3b4979b   0.00\n    4a909f0dac387fb517c56fb38f2f426239846d79   1.00\n    fe6a25d446813e1b17c191497a4286a8ad60a5a2   1.00\n    3a872555ceb6978f73bdd9fc5446a79c4fc52d81   1.00\n    513b1d928f48dcf4c4b3528a85729cd12ef36cd5   1.00\n    7d69cce8b0296b1cb157c121067d541a222384e6   1.00\n    eeb47ed17507d1860e21f679d416b8be24b7b2e5   6.00\n    1a668ae2a2056e73783bbc0e53ced3ec15cd1e5a   1.00\n    4b9796f822b53388cff5916ff001a27de904546c   6.00\n    ec3827bc109c277faa6541717f1e33d26d15b503   2.00\n    89cfcaea8a42e46f1a0f57394dd0cdd5441c123b   3.00\n    41919868fff4a70e0be44172a93c2bf4064b1232   0.00\n    20fbb21c7b25ec5bfe0c1c85b958d49850ea5cd9   1.00\n    911ed79e4f81474fc3d362d1b3c686164a01af2b   0.00\n    528a9514debb452f9913933c8495be5007f07ce9   9.00\n    cf03a379bfda577f6e45c2adbc30b356e5ceebe7   1.00\n    2f11cfa0a6aef8b8662e2a41198a97343a036e12   1.00\n    fee7917d380be4de51d8c4469839777b4370209b   1.00\n    cd48ab167cb8db2a22f7d973852124129076487f   2.00\n    d4f5db1d3ea8b9ec6c71b7f5684e83ad9c18bc93   1.00\n    e6b89227d71f71a54c69e254378762144ab25afb   1.00\n    643beda1c6c5fe47f57e957b4cfa8825def2f62a   1.00\n    c97fcbdf099cbdc1509aadb77ae3458b202f4c1b   0.00\n    1d3eef43fc0e56f2cb8592fde4ecec7cb7d27264   1.00\n    Name: front_score, Length: 153117, dtype: float64\n\n\n\n## Facebook brand page promotion (15 points)\n\nOne way a publisher has of promoting content is to post to their brand page. The significance of doing so is stronger when the brand page has more followers (likes).\n\n$$ facebookPromotionProposed1_a = 15 \\left( \\frac {brandPageLikes_a} {\\max(brandPageLikes)} \\right) $$\n\nNow lets explore the data to see if that makes sense. **tr;dr the formula above is incorrect**\n\n\n```python\ndata.fb_brand_page_likes.max()\n```\n\n\n\n\n    45711259.0\n\n\n\n\n```python\nfacebook_promotion_proposed_1 = np.ceil((15 * (data.fb_brand_page_likes / data.fb_brand_page_likes.max())).fillna(0))\n```\n\n\n```python\nfacebook_promotion_proposed_1.value_counts().sort_index().plot.bar()\n```\n\n\n```python\nfacebook_promotion_proposed_1.groupby(data.publisher_id).describe()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>25%</th>\n      <th>50%</th>\n      <th>75%</th>\n      <th>max</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>28.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>12656.00</td>\n      <td>0.60</td>\n      <td>2.94</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>15.00</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>2661.00</td>\n      <td>0.83</td>\n      <td>0.99</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>49.00</td>\n      <td>0.98</td>\n      <td>0.14</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>1457.00</td>\n      <td>0.42</td>\n      <td>0.49</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>4435.00</td>\n      <td>2.33</td>\n      <td>4.23</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>10.00</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>24668.00</td>\n      <td>0.57</td>\n      <td>1.59</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>5.00</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>484.00</td>\n      <td>2.50</td>\n      <td>1.12</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>evolvepolitics_com</th>\n      <td>64.00</td>\n      <td>0.84</td>\n      <td>0.37</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>6824.00</td>\n      <td>0.60</td>\n      <td>1.81</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>6.00</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>4725.00</td>\n      <td>0.46</td>\n      <td>0.84</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>6443.00</td>\n      <td>0.74</td>\n      <td>1.55</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>6278.00</td>\n      <td>0.57</td>\n      <td>1.18</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>525.00</td>\n      <td>0.64</td>\n      <td>0.48</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>3835.00</td>\n      <td>0.72</td>\n      <td>0.96</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>156.00</td>\n      <td>0.87</td>\n      <td>0.34</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>11168.00</td>\n      <td>0.23</td>\n      <td>0.42</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>2061.00</td>\n      <td>2.34</td>\n      <td>1.97</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>470.00</td>\n      <td>0.79</td>\n      <td>0.41</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>2105.00</td>\n      <td>1.41</td>\n      <td>1.50</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>4605.00</td>\n      <td>1.78</td>\n      <td>2.52</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>5.00</td>\n      <td>6.00</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>246.00</td>\n      <td>0.80</td>\n      <td>0.40</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>31.00</td>\n      <td>0.87</td>\n      <td>0.34</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>5849.00</td>\n      <td>0.68</td>\n      <td>0.95</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>2521.00</td>\n      <td>1.07</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>121.00</td>\n      <td>0.99</td>\n      <td>0.09</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>6619.00</td>\n      <td>0.50</td>\n      <td>0.87</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>175.00</td>\n      <td>0.97</td>\n      <td>0.18</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>8208.00</td>\n      <td>0.53</td>\n      <td>1.14</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>9479.00</td>\n      <td>0.06</td>\n      <td>0.23</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>23426.00</td>\n      <td>0.16</td>\n      <td>0.68</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>330.00</td>\n      <td>0.24</td>\n      <td>0.43</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>415.00</td>\n      <td>0.20</td>\n      <td>0.40</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThat's too much variation: sites like the Guardian, which have a respectable 7.5m likes, should not be scoring a 3. Lets try applying a log to it, and then standard feature scaling again.\n\n\n```python\ndata.fb_brand_page_likes.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk     330551.00\n    bbc_co_uk                          45711259.00\n    breitbart_com                       3803903.00\n    brexitcentral_com                     14522.00\n    buzzfeed_com                        2902337.00\n    cnn_com                            29591651.00\n    dailymail_co_uk                    14227830.00\n    economist_com                       8450845.00\n    evolvepolitics_com                   126771.00\n    foxnews_com                        16183276.00\n    ft_com                              3743010.00\n    huffingtonpost_com                  9846648.00\n    independent_co_uk                   8048146.00\n    indy100_com                          235483.00\n    lemonde_fr                          4019902.00\n    libdemvoice_org                        8629.00\n    mirror_co_uk                        2970189.00\n    nbcnews_com                         9522368.00\n    newstatesman_com                     154752.00\n    npr_org                             6281946.00\n    nytimes_com                        15274145.00\n    order-order_com                       45461.00\n    propublica_org                       376979.00\n    reuters_com                         3951592.00\n    rt_com                              4967624.00\n    skwawkbox_org                          6920.00\n    telegraph_co_uk                     4420609.00\n    thecanary_co                         158053.00\n    theguardian_com                     7869117.00\n    thetimes_co_uk                       741434.00\n    washingtonpost_com                  6129074.00\n    westmonster_com                       17216.00\n    yournewswire_com                      27926.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\nnp.log(2149)\n```\n\n\n\n\n    7.6727578966425103\n\n\n\n\n```python\nnp.log(data.fb_brand_page_likes.groupby(data.publisher_id).max())\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk   12.71\n    bbc_co_uk                          17.64\n    breitbart_com                      15.15\n    brexitcentral_com                   9.58\n    buzzfeed_com                       14.88\n    cnn_com                            17.20\n    dailymail_co_uk                    16.47\n    economist_com                      15.95\n    evolvepolitics_com                 11.75\n    foxnews_com                        16.60\n    ft_com                             15.14\n    huffingtonpost_com                 16.10\n    independent_co_uk                  15.90\n    indy100_com                        12.37\n    lemonde_fr                         15.21\n    libdemvoice_org                     9.06\n    mirror_co_uk                       14.90\n    nbcnews_com                        16.07\n    newstatesman_com                   11.95\n    npr_org                            15.65\n    nytimes_com                        16.54\n    order-order_com                    10.72\n    propublica_org                     12.84\n    reuters_com                        15.19\n    rt_com                             15.42\n    skwawkbox_org                       8.84\n    telegraph_co_uk                    15.30\n    thecanary_co                       11.97\n    theguardian_com                    15.88\n    thetimes_co_uk                     13.52\n    washingtonpost_com                 15.63\n    westmonster_com                     9.75\n    yournewswire_com                   10.24\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\nThat's more like it, but the lower numbers should be smaller.\n\n\n```python\nnp.log(data.fb_brand_page_likes.groupby(data.publisher_id).max() / 1000)\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    5.80\n    bbc_co_uk                          10.73\n    breitbart_com                       8.24\n    brexitcentral_com                   2.68\n    buzzfeed_com                        7.97\n    cnn_com                            10.30\n    dailymail_co_uk                     9.56\n    economist_com                       9.04\n    evolvepolitics_com                  4.84\n    foxnews_com                         9.69\n    ft_com                              8.23\n    huffingtonpost_com                  9.19\n    independent_co_uk                   8.99\n    indy100_com                         5.46\n    lemonde_fr                          8.30\n    libdemvoice_org                     2.16\n    mirror_co_uk                        8.00\n    nbcnews_com                         9.16\n    newstatesman_com                    5.04\n    npr_org                             8.75\n    nytimes_com                         9.63\n    order-order_com                     3.82\n    propublica_org                      5.93\n    reuters_com                         8.28\n    rt_com                              8.51\n    skwawkbox_org                       1.93\n    telegraph_co_uk                     8.39\n    thecanary_co                        5.06\n    theguardian_com                     8.97\n    thetimes_co_uk                      6.61\n    washingtonpost_com                  8.72\n    westmonster_com                     2.85\n    yournewswire_com                    3.33\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\nscaled_fb_brand_page_likes = (data.fb_brand_page_likes / 1000)\nfacebook_promotion_proposed_2 = np.ceil(\\\n    (15 * \\\n     (np.log(scaled_fb_brand_page_likes) / np.log(scaled_fb_brand_page_likes.max()))\\\n    )\\\n                                       ).fillna(0)\n```\n\n\n```python\nfacebook_promotion_proposed_2.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    9.00\n    bbc_co_uk                          15.00\n    breitbart_com                      12.00\n    brexitcentral_com                   4.00\n    buzzfeed_com                       12.00\n    cnn_com                            15.00\n    dailymail_co_uk                    14.00\n    economist_com                      13.00\n    evolvepolitics_com                  7.00\n    foxnews_com                        14.00\n    ft_com                             12.00\n    huffingtonpost_com                 13.00\n    independent_co_uk                  13.00\n    indy100_com                         8.00\n    lemonde_fr                         12.00\n    libdemvoice_org                     4.00\n    mirror_co_uk                       12.00\n    nbcnews_com                        13.00\n    newstatesman_com                    8.00\n    npr_org                            13.00\n    nytimes_com                        14.00\n    order-order_com                     6.00\n    propublica_org                      9.00\n    reuters_com                        12.00\n    rt_com                             12.00\n    skwawkbox_org                       3.00\n    telegraph_co_uk                    12.00\n    thecanary_co                        8.00\n    theguardian_com                    13.00\n    thetimes_co_uk                     10.00\n    washingtonpost_com                 13.00\n    westmonster_com                     4.00\n    yournewswire_com                    5.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\nLGTM. So the equation is\n\n\n$$ facebookPromotion_a = 15 \\left( \n\\frac {\\log(\\frac {brandPageLikes_a}{1000})} \n{\\log(\\frac {\\max(brandPageLikes)}{1000}))} \\right) $$\n\n\nNow, let's try applying standard feature scaling approch to this, rather than using a magic number of 1,000. That equation would be:\n\n\\begin{align}\nunscaledFacebookPromotion_a &= \n   \\log(brandPageLikes_a) \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{unscaledFacebookPromotion_a - \\min(unscaledFacebookPromotion)}{\\max(unscaledFacebookPromotion) - \\min(unscaledFacebookPromotion)}  \\\\\n\\\\\n\\text{The scaling can be simplified to:} \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{unscaledFacebookPromotion_a - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))}  \\\\\n\\\\\n\\text{Meaning the overall equation becomes:} \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{\\log(brandPageLikes_a) - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))} \n   \\end{align}\n\n\n\n```python\nfacebook_promotion_proposed_3 = np.ceil(\n    (14 * \n     ( \n         (np.log(data.fb_brand_page_likes) - np.log(data.fb_brand_page_likes.min()) ) /\n         (np.log(data.fb_brand_page_likes.max()) - np.log(data.fb_brand_page_likes.min()))\n     )\n    ) + 1\n                                       )\n```\n\n\n```python\nfacebook_promotion_proposed_3.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    8.00\n    bbc_co_uk                          15.00\n    breitbart_com                      12.00\n    brexitcentral_com                   3.00\n    buzzfeed_com                       11.00\n    cnn_com                            15.00\n    dailymail_co_uk                    14.00\n    economist_com                      13.00\n    evolvepolitics_com                  6.00\n    foxnews_com                        14.00\n    ft_com                             12.00\n    huffingtonpost_com                 13.00\n    independent_co_uk                  13.00\n    indy100_com                         7.00\n    lemonde_fr                         12.00\n    libdemvoice_org                     2.00\n    mirror_co_uk                       11.00\n    nbcnews_com                        13.00\n    newstatesman_com                    7.00\n    npr_org                            12.00\n    nytimes_com                        14.00\n    order-order_com                     5.00\n    propublica_org                      8.00\n    reuters_com                        12.00\n    rt_com                             12.00\n    skwawkbox_org                       2.00\n    telegraph_co_uk                    12.00\n    thecanary_co                        7.00\n    theguardian_com                    13.00\n    thetimes_co_uk                      9.00\n    washingtonpost_com                 12.00\n    westmonster_com                     3.00\n    yournewswire_com                    4.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\ndata[\"facebook_promotion_score\"] = facebook_promotion_proposed_3.fillna(0.0)\n```\n\n# Review\n\n\n```python\ndata[\"promotion_score\"] = (data.lead_score + data.front_score + data.facebook_promotion_score)\ndata[\"attention_index\"] = (data.promotion_score + data.response_score)\n```\n\n\n```python\ndata.promotion_score.plot.hist(bins=np.arange(50), figsize=(15,6))\n```\n\n\n```python\ndata.attention_index.plot.hist(bins=np.arange(100), figsize=(15,6))\n```\n\n\n```python\ndata.attention_index.value_counts().sort_index()\n```\n\n\n\n\n    0.00     23633\n    1.00     18731\n    2.00     12787\n    3.00      8984\n    4.00      6282\n    5.00      5323\n    6.00      4475\n    7.00      3959\n    8.00      3472\n    9.00      3364\n    10.00     2965\n    11.00     2604\n    12.00     2532\n    13.00     2487\n    14.00     2270\n    15.00     2156\n    16.00     1953\n    17.00     1869\n    18.00     1865\n    19.00     1697\n    20.00     1754\n    21.00     1655\n    22.00     1566\n    23.00     1541\n    24.00     1598\n    25.00     1537\n    26.00     1548\n    27.00     1507\n    28.00     1414\n    29.00     1415\n             ...  \n    65.00      137\n    66.00      126\n    67.00       85\n    68.00       96\n    69.00       65\n    70.00       56\n    71.00       54\n    72.00       45\n    73.00       41\n    74.00       47\n    75.00       28\n    76.00       38\n    77.00       33\n    78.00       30\n    79.00       25\n    80.00       29\n    81.00       22\n    82.00       22\n    83.00       19\n    84.00       16\n    85.00       13\n    86.00       11\n    87.00       12\n    88.00       15\n    89.00        8\n    90.00        7\n    91.00        4\n    92.00        3\n    93.00        3\n    94.00        2\n    Name: attention_index, Length: 95, dtype: int64\n\n\n\n\n```python\n# and lets see the articles with the biggest attention index\ndata.sort_values(\"attention_index\", ascending=False)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>d3e36a9aec548acb3aa6e52fb2960b896ed2bb30</th>\n      <td>http://www.cnn.com/2018/01/18/politics/kfile-c...</td>\n      <td>Trump appointee Carl Higbie made racist, sexis...</td>\n      <td>2018-01-18 23:22:22.097</td>\n      <td>2018-01-18 23:19:53.000</td>\n      <td>82049</td>\n      <td>143.27</td>\n      <td>2018-01-19T02:15:17.846Z</td>\n      <td>21737</td>\n      <td>44033</td>\n      <td>16279</td>\n      <td>...</td>\n      <td>29503636.00</td>\n      <td>2018-01-19T02:00:26.000Z</td>\n      <td>105</td>\n      <td>1895.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>46dbfbb92005da970c527bb3252280bb9a80a59b</th>\n      <td>http://www.cnn.com/2018/01/03/politics/bannon-...</td>\n      <td>Bannon: 2016 Trump Tower meeting was 'treasonous'</td>\n      <td>2018-01-03 14:28:22.755</td>\n      <td>2018-01-03 14:23:20.000</td>\n      <td>82456</td>\n      <td>239.51</td>\n      <td>2018-01-03T16:14:12.826Z</td>\n      <td>30056</td>\n      <td>40458</td>\n      <td>11942</td>\n      <td>...</td>\n      <td>29378732.00</td>\n      <td>2018-01-03T14:39:05.000Z</td>\n      <td>105</td>\n      <td>213.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>836e90a16e36d69e3bae8639d593540609a492bb</th>\n      <td>https://www.buzzfeed.com/mollyhensleyclancy/am...</td>\n      <td>Amazon CEO Says He Will Give $33 Million To DA...</td>\n      <td>2018-01-12 18:13:09.758</td>\n      <td>2018-01-12 17:41:10.000</td>\n      <td>87223</td>\n      <td>90.60</td>\n      <td>2018-01-13T03:48:08.456Z</td>\n      <td>3014</td>\n      <td>79490</td>\n      <td>4719</td>\n      <td>...</td>\n      <td>2832832.00</td>\n      <td>2018-01-12T21:23:51.000Z</td>\n      <td>147</td>\n      <td>394.00</td>\n      <td>50.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>0c2106548a33f2a7484f41b2837ea474f3f3ba28</th>\n      <td>http://www.cnn.com/2018/01/13/politics/hawaii-...</td>\n      <td>Missile threat alert for Hawaii a false alarm</td>\n      <td>2018-01-13 18:49:25.317</td>\n      <td>2018-01-13 18:47:27.000</td>\n      <td>127664</td>\n      <td>423.06</td>\n      <td>2018-01-13T20:14:11.190Z</td>\n      <td>46730</td>\n      <td>64532</td>\n      <td>16402</td>\n      <td>...</td>\n      <td>29450153.00</td>\n      <td>2018-01-13T19:00:05.000Z</td>\n      <td>105</td>\n      <td>151.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>031074c129960b10fef8e16248004635dec0c4bc</th>\n      <td>http://money.cnn.com/2018/01/08/media/oprah-go...</td>\n      <td>Oprah's Golden Globes speech sounds like the s...</td>\n      <td>2018-01-08 14:24:28.728</td>\n      <td>2018-01-08 13:43:13.000</td>\n      <td>270420</td>\n      <td>488.99</td>\n      <td>2018-01-08T16:56:07.305Z</td>\n      <td>118451</td>\n      <td>136331</td>\n      <td>15638</td>\n      <td>...</td>\n      <td>29403330.00</td>\n      <td>2018-01-08T14:30:12.000Z</td>\n      <td>105</td>\n      <td>nan</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>5449f01e35cad5f97ef4c67fc9e7426f1c3a9c32</th>\n      <td>https://www.buzzfeed.com/darrensands/maxine-wa...</td>\n      <td>Maxine Waters Is Giving A National Address On ...</td>\n      <td>2018-01-26 23:24:14.272</td>\n      <td>2018-01-26 23:17:14.000</td>\n      <td>66115</td>\n      <td>48.89</td>\n      <td>2018-01-27T18:41:10.932Z</td>\n      <td>12582</td>\n      <td>46117</td>\n      <td>7416</td>\n      <td>...</td>\n      <td>2840906.00</td>\n      <td>2018-01-27T03:31:24.000Z</td>\n      <td>147</td>\n      <td>506.00</td>\n      <td>49.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>b9d5a53dc38085bebff40395f900b84bfa4ee6e4</th>\n      <td>https://www.buzzfeed.com/claudiarosenbaum/glee...</td>\n      <td>\"Glee\" Star Mark Salling Has Been Found Dead A...</td>\n      <td>2018-01-30 18:43:57.665</td>\n      <td>2018-01-30 18:29:47.000</td>\n      <td>71995</td>\n      <td>241.28</td>\n      <td>2018-01-30T19:06:07.944Z</td>\n      <td>29088</td>\n      <td>36326</td>\n      <td>6581</td>\n      <td>...</td>\n      <td>2872459.00</td>\n      <td>2018-01-30T18:42:41.000Z</td>\n      <td>147</td>\n      <td>340.00</td>\n      <td>49.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>a89037c0b486187e70b6f78bcf6a1b107f90a5fc</th>\n      <td>https://www.buzzfeed.com/claudiarosenbaum/yout...</td>\n      <td>YouTube Cuts Business Ties With Logan Paul Ami...</td>\n      <td>2018-01-11 00:22:17.301</td>\n      <td>2018-01-11 00:17:37.000</td>\n      <td>62951</td>\n      <td>277.34</td>\n      <td>2018-01-11T22:04:14.039Z</td>\n      <td>9702</td>\n      <td>50765</td>\n      <td>2484</td>\n      <td>...</td>\n      <td>2831171.00</td>\n      <td>2018-01-11T01:15:22.000Z</td>\n      <td>147</td>\n      <td>435.00</td>\n      <td>48.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>325a9e972176c2e8346af4898db4b02db0533467</th>\n      <td>http://www.bbc.co.uk/news/world-europe-42851668</td>\n      <td>Ikea founder Kamprad dies at 91</td>\n      <td>2018-01-28 10:43:09.711</td>\n      <td>2018-01-28 10:40:44.000</td>\n      <td>46121</td>\n      <td>691.93</td>\n      <td>2018-01-28T14:04:13.609Z</td>\n      <td>6628</td>\n      <td>33679</td>\n      <td>5814</td>\n      <td>...</td>\n      <td>45634425.00</td>\n      <td>2018-01-28T11:14:27.000Z</td>\n      <td>96</td>\n      <td>63.00</td>\n      <td>46.00</td>\n      <td>20.00</td>\n      <td>10.00</td>\n      <td>15.00</td>\n      <td>45.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>bf757059d2ede473ff44491ea8936e6fee6bec7b</th>\n      <td>https://www.buzzfeed.com/shylawatson/cranberri...</td>\n      <td>Cranberries Lead Singer Dolores O'Riordan Is D...</td>\n      <td>2018-01-15 17:53:14.623</td>\n      <td>2018-01-15 17:41:31.000</td>\n      <td>60778</td>\n      <td>515.74</td>\n      <td>2018-01-15T18:15:09.484Z</td>\n      <td>9310</td>\n      <td>45640</td>\n      <td>5828</td>\n      <td>...</td>\n      <td>2833812.00</td>\n      <td>2018-01-15T17:51:08.000Z</td>\n      <td>147</td>\n      <td>15.00</td>\n      <td>48.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>3686ef425ec9504f3a69ca163125389e54f01140</th>\n      <td>http://www.cnn.com/2018/01/16/politics/cory-bo...</td>\n      <td>Booker slams DHS secretary's 'amnesia' on Trum...</td>\n      <td>2018-01-16 21:13:29.763</td>\n      <td>2018-01-16 21:07:58.000</td>\n      <td>82362</td>\n      <td>291.65</td>\n      <td>2018-01-16T22:48:10.235Z</td>\n      <td>15537</td>\n      <td>60149</td>\n      <td>6676</td>\n      <td>...</td>\n      <td>29471640.00</td>\n      <td>2018-01-16T22:30:23.000Z</td>\n      <td>105</td>\n      <td>224.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>12f0856aa2335764f662826ce5b06f426994c0bc</th>\n      <td>http://www.cnn.com/2018/01/02/politics/donald-...</td>\n      <td>Trump tweets about nuclear war with North Korea</td>\n      <td>2018-01-03 01:25:16.734</td>\n      <td>2018-01-03 01:22:43.000</td>\n      <td>89667</td>\n      <td>409.64</td>\n      <td>2018-01-03T02:09:08.916Z</td>\n      <td>34543</td>\n      <td>45550</td>\n      <td>9574</td>\n      <td>...</td>\n      <td>29377421.00</td>\n      <td>2018-01-03T01:31:55.000Z</td>\n      <td>105</td>\n      <td>168.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>ebf2d44938694f691015401e8ce69ff868ecb3bb</th>\n      <td>http://www.bbc.co.uk/news/health-42736764</td>\n      <td>Cancer blood test \u2018enormously exciting\u2019</td>\n      <td>2018-01-19 00:28:05.929</td>\n      <td>2018-01-19 00:25:31.000</td>\n      <td>31304</td>\n      <td>79.54</td>\n      <td>2018-01-19T09:20:11.225Z</td>\n      <td>1653</td>\n      <td>24318</td>\n      <td>5333</td>\n      <td>...</td>\n      <td>45529689.00</td>\n      <td>2018-01-19T09:07:02.000Z</td>\n      <td>96</td>\n      <td>537.00</td>\n      <td>44.00</td>\n      <td>20.00</td>\n      <td>11.00</td>\n      <td>15.00</td>\n      <td>46.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>848356f1267dee63b461fa50fe499575953ebba9</th>\n      <td>https://www.buzzfeed.com/maryanngeorgantopoulo...</td>\n      <td>Here Are Powerful Quotes From More Than 100 Yo...</td>\n      <td>2018-01-24 17:10:23.558</td>\n      <td>2018-01-24 17:07:26.000</td>\n      <td>50168</td>\n      <td>59.18</td>\n      <td>2018-01-24T18:34:15.709Z</td>\n      <td>3417</td>\n      <td>39932</td>\n      <td>6819</td>\n      <td>...</td>\n      <td>2838754.00</td>\n      <td>2018-01-24T17:15:10.000Z</td>\n      <td>147</td>\n      <td>3410.00</td>\n      <td>47.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>72c2fa696ffd709cc532fda038a40ef15a188a52</th>\n      <td>http://www.bbc.co.uk/news/world-us-canada-4258...</td>\n      <td>Trump and Republicans to plot 2018 plans in Ca...</td>\n      <td>2018-01-06 11:55:09.306</td>\n      <td>2018-01-06 11:52:24.000</td>\n      <td>26287</td>\n      <td>106.85</td>\n      <td>2018-01-06T17:11:14.528Z</td>\n      <td>7174</td>\n      <td>15981</td>\n      <td>3132</td>\n      <td>...</td>\n      <td>45396536.00</td>\n      <td>2018-01-06T17:02:47.000Z</td>\n      <td>96</td>\n      <td>600.00</td>\n      <td>43.00</td>\n      <td>20.00</td>\n      <td>12.00</td>\n      <td>15.00</td>\n      <td>47.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>aedb3f16b21bae6a49c98785f50a5a16f636a990</th>\n      <td>http://www.cnn.com/2018/01/11/politics/immigra...</td>\n      <td>Trump decries 'people from shithole countries'...</td>\n      <td>2018-01-11 22:07:21.799</td>\n      <td>2018-01-11 22:03:10.000</td>\n      <td>244631</td>\n      <td>458.05</td>\n      <td>2018-01-12T01:18:14.256Z</td>\n      <td>102187</td>\n      <td>122190</td>\n      <td>20254</td>\n      <td>...</td>\n      <td>29421925.00</td>\n      <td>2018-01-12T01:01:22.000Z</td>\n      <td>105</td>\n      <td>56.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>5.00</td>\n      <td>15.00</td>\n      <td>40.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>8972d20a6774e5b2c625d0471b2c10e62adf7136</th>\n      <td>https://www.buzzfeed.com/delaneystrunk/logan-p...</td>\n      <td>People Are Calling For Logan Paul To Be Banned...</td>\n      <td>2018-01-02 09:09:49.158</td>\n      <td>2018-01-02 04:19:39.000</td>\n      <td>54646</td>\n      <td>76.06</td>\n      <td>2018-01-02T16:10:05.453Z</td>\n      <td>16626</td>\n      <td>34273</td>\n      <td>3747</td>\n      <td>...</td>\n      <td>2826086.00</td>\n      <td>2018-01-02T12:33:09.000Z</td>\n      <td>147</td>\n      <td>nan</td>\n      <td>47.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>6d17ce33359a0a32b86aeed9b48dab6b3352a18b</th>\n      <td>https://www.buzzfeed.com/michaelblackmon/kylie...</td>\n      <td>Kylie Jenner Just Gave Birth To A Baby Girl</td>\n      <td>2018-02-04 20:44:12.166</td>\n      <td>2018-01-12 21:40:07.000</td>\n      <td>71668</td>\n      <td>414.65</td>\n      <td>2018-02-04T21:27:11.843Z</td>\n      <td>12953</td>\n      <td>55680</td>\n      <td>3035</td>\n      <td>...</td>\n      <td>2899130.00</td>\n      <td>2018-02-04T21:02:53.000Z</td>\n      <td>147</td>\n      <td>52.00</td>\n      <td>49.00</td>\n      <td>19.00</td>\n      <td>11.00</td>\n      <td>11.00</td>\n      <td>41.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>00b6faac3688806beb622d7c1d02cf6d3522bfe3</th>\n      <td>https://www.cnn.com/2018/01/24/politics/muelle...</td>\n      <td>Robert Mueller: Bombshells takes probe to crit...</td>\n      <td>2018-01-24 06:10:10.962</td>\n      <td>2018-01-24 06:04:24.000</td>\n      <td>41852</td>\n      <td>102.31</td>\n      <td>2018-01-24T12:48:09.226Z</td>\n      <td>11790</td>\n      <td>24560</td>\n      <td>5502</td>\n      <td>...</td>\n      <td>29534935.00</td>\n      <td>2018-01-24T12:30:08.000Z</td>\n      <td>105</td>\n      <td>1356.00</td>\n      <td>46.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>13de1765a9c9cf6c5c809840fa8d71a0aefe5a4f</th>\n      <td>https://www.buzzfeed.com/buzzfeednews/womens-m...</td>\n      <td>Live Updates: Women Are Marching Around The Wo...</td>\n      <td>2018-01-20 11:19:18.412</td>\n      <td>2018-01-20 09:46:24.000</td>\n      <td>48669</td>\n      <td>275.43</td>\n      <td>2018-01-20T22:29:15.546Z</td>\n      <td>3039</td>\n      <td>43873</td>\n      <td>1757</td>\n      <td>...</td>\n      <td>2836672.00</td>\n      <td>2018-01-20T18:42:49.000Z</td>\n      <td>147</td>\n      <td>nan</td>\n      <td>47.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>39d81ac1e023ec82e9ad4bfce2655210d77510c2</th>\n      <td>https://www.buzzfeed.com/jasonleopold/newly-un...</td>\n      <td>Newly Uncovered Russian Payments Are A Focus O...</td>\n      <td>2018-01-17 14:49:41.390</td>\n      <td>2018-01-17 02:46:23.000</td>\n      <td>32816</td>\n      <td>90.50</td>\n      <td>2018-01-18T03:59:16.208Z</td>\n      <td>3943</td>\n      <td>23138</td>\n      <td>5735</td>\n      <td>...</td>\n      <td>2834077.00</td>\n      <td>2018-01-17T14:57:02.000Z</td>\n      <td>147</td>\n      <td>2531.00</td>\n      <td>44.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>97edc2871fb76d5a8f59dbc8e7be6269d238a3d6</th>\n      <td>https://www.huffingtonpost.com/entry/trump-cam...</td>\n      <td>Trump Says U.S. 'Not Going To Look Foolish As ...</td>\n      <td>2018-01-06 20:19:10.834</td>\n      <td>2018-01-06 20:12:33.000</td>\n      <td>85751</td>\n      <td>156.57</td>\n      <td>2018-01-07T01:22:07.736Z</td>\n      <td>23443</td>\n      <td>57278</td>\n      <td>5030</td>\n      <td>...</td>\n      <td>9832747.00</td>\n      <td>2018-01-06T20:30:04.000Z</td>\n      <td>215</td>\n      <td>1020.00</td>\n      <td>50.00</td>\n      <td>17.00</td>\n      <td>9.00</td>\n      <td>13.00</td>\n      <td>39.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>d5315965530fabd2333bd46a88c9b5275044df1d</th>\n      <td>https://www.buzzfeed.com/keelyflaherty/game-of...</td>\n      <td>Cancel 2018, \"Game Of Thrones\" Isn't Coming Ba...</td>\n      <td>2018-01-04 19:34:16.207</td>\n      <td>2018-01-04 19:23:19.000</td>\n      <td>76651</td>\n      <td>1321.58</td>\n      <td>2018-01-04T22:04:13.144Z</td>\n      <td>36484</td>\n      <td>36430</td>\n      <td>3737</td>\n      <td>...</td>\n      <td>2827447.00</td>\n      <td>2018-01-05T01:11:58.000Z</td>\n      <td>147</td>\n      <td>nan</td>\n      <td>50.00</td>\n      <td>19.00</td>\n      <td>9.00</td>\n      <td>11.00</td>\n      <td>39.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>1ba515b11e5f0d45896160491c7c94bf45bbf148</th>\n      <td>https://www.buzzfeed.com/paulmcleod/shithole</td>\n      <td>Trump Complained That People From \"Shithole Co...</td>\n      <td>2018-01-11 22:19:39.664</td>\n      <td>2018-01-11 22:18:05.000</td>\n      <td>31425</td>\n      <td>121.99</td>\n      <td>2018-01-11T22:52:08.006Z</td>\n      <td>10213</td>\n      <td>19719</td>\n      <td>1493</td>\n      <td>...</td>\n      <td>2832149.00</td>\n      <td>2018-01-11T22:21:58.000Z</td>\n      <td>147</td>\n      <td>241.00</td>\n      <td>44.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>dd992c75fb96d54aca0ba862cd4ea159790a3f10</th>\n      <td>http://www.cnn.com/2018/01/07/politics/donald-...</td>\n      <td>Bannon: 'I regret' delay in responding to book</td>\n      <td>2018-01-07 17:22:14.673</td>\n      <td>2018-01-07 17:16:19.000</td>\n      <td>41322</td>\n      <td>78.23</td>\n      <td>2018-01-08T12:56:06.616Z</td>\n      <td>8158</td>\n      <td>29504</td>\n      <td>3660</td>\n      <td>...</td>\n      <td>29400200.00</td>\n      <td>2018-01-07T17:56:30.000Z</td>\n      <td>105</td>\n      <td>311.00</td>\n      <td>46.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>756c9e900e156eae2902ec087cf8135146181656</th>\n      <td>http://www.bbc.co.uk/news/world-us-canada-4265...</td>\n      <td>Trump 'in Oval Office foul-mouthed outburst ab...</td>\n      <td>2018-01-11 23:01:17.664</td>\n      <td>2018-01-11 22:59:29.000</td>\n      <td>51483</td>\n      <td>162.92</td>\n      <td>2018-01-12T02:33:16.046Z</td>\n      <td>17113</td>\n      <td>30336</td>\n      <td>4034</td>\n      <td>...</td>\n      <td>45448225.00</td>\n      <td>2018-01-12T02:14:19.000Z</td>\n      <td>96</td>\n      <td>72.00</td>\n      <td>47.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>ce03d6fd535f50bc38a7fbef158ebe83d2af34bb</th>\n      <td>https://www.huffingtonpost.com/entry/aziz-ansa...</td>\n      <td>On Aziz Ansari And Sex That Feels Violating Ev...</td>\n      <td>2018-01-16 19:49:10.416</td>\n      <td>2018-01-16 19:37:55.000</td>\n      <td>76796</td>\n      <td>48.56</td>\n      <td>2018-01-16T23:28:11.380Z</td>\n      <td>23482</td>\n      <td>45683</td>\n      <td>7631</td>\n      <td>...</td>\n      <td>9839670.00</td>\n      <td>2018-01-16T21:30:09.000Z</td>\n      <td>215</td>\n      <td>2126.00</td>\n      <td>50.00</td>\n      <td>17.00</td>\n      <td>9.00</td>\n      <td>13.00</td>\n      <td>39.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>8fe599949b04acba25005bf768607532b04174e7</th>\n      <td>https://www.cnn.com/2018/01/28/entertainment/h...</td>\n      <td>Cher, Snoop, Hillary Clinton audition for 'Fir...</td>\n      <td>2018-01-29 03:37:15.642</td>\n      <td>2018-01-29 03:32:10.000</td>\n      <td>57567</td>\n      <td>320.40</td>\n      <td>2018-01-29T04:49:08.716Z</td>\n      <td>11307</td>\n      <td>42601</td>\n      <td>3659</td>\n      <td>...</td>\n      <td>29555404.00</td>\n      <td>2018-01-29T04:01:20.000Z</td>\n      <td>105</td>\n      <td>207.00</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>5.00</td>\n      <td>15.00</td>\n      <td>40.00</td>\n      <td>88.00</td>\n    </tr>\n    <tr>\n      <th>d62d6fd2c668fc7327433dab7074e7fd5abf30cf</th>\n      <td>http://www.cnn.com/2018/01/16/us/california-tu...</td>\n      <td>California parents accused of torture after th...</td>\n      <td>2018-01-16 11:40:30.702</td>\n      <td>2018-01-16 11:34:47.000</td>\n      <td>32614</td>\n      <td>55.16</td>\n      <td>2018-01-16T13:04:11.080Z</td>\n      <td>10836</td>\n      <td>18654</td>\n      <td>3124</td>\n      <td>...</td>\n      <td>29463455.00</td>\n      <td>2018-01-16T12:30:14.000Z</td>\n      <td>105</td>\n      <td>759.00</td>\n      <td>44.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>88.00</td>\n    </tr>\n    <tr>\n      <th>eba48f562cee9726b2fc6cf761bfc8f913013849</th>\n      <td>https://www.buzzfeed.com/juliareinstein/judge-...</td>\n      <td>People Are Praising The Judge Who Sentenced La...</td>\n      <td>2018-01-24 19:34:14.937</td>\n      <td>2018-01-24 19:05:41.000</td>\n      <td>36384</td>\n      <td>80.06</td>\n      <td>2018-01-25T14:11:11.473Z</td>\n      <td>1611</td>\n      <td>33116</td>\n      <td>1657</td>\n      <td>...</td>\n      <td>2838830.00</td>\n      <td>2018-01-24T20:13:48.000Z</td>\n      <td>147</td>\n      <td>60.00</td>\n      <td>45.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>88.00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>12d1078d1a64054ab19d4e6c9a20efcade7635ef</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Towns 30, Harvard tops Brown 86-77, unbeaten i...</td>\n      <td>2018-01-28 01:58:18.029</td>\n      <td>2018-01-28 01:45:11.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-28T10:16:06.337Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>179.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>2d3c497bc72010912866aafeafe3669385e2d90a</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Clark, Evans lead No. 9 Cincinnati past Memphi...</td>\n      <td>2018-01-28 01:58:17.411</td>\n      <td>2018-01-28 01:44:23.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-28T08:14:06.365Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>354.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>0ccfadcf8948ecfad361f40ef2a44f21934d00b6</th>\n      <td>http://www.dailymail.co.uk/sport/football/arti...</td>\n      <td>Chievo 0-2 Juventus: Khedira and Higuain punis...</td>\n      <td>2018-01-28 01:46:22.698</td>\n      <td>2018-01-28 01:43:54.000</td>\n      <td>1</td>\n      <td>0.09</td>\n      <td>2018-01-28T01:58:06.441Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>397.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>c8ad968acb7a237b7006fc9e9d9df82260a0381e</th>\n      <td>https://www.washingtonpost.com/national/today-...</td>\n      <td>Today in History</td>\n      <td>2018-01-08 05:19:21.965</td>\n      <td>2018-01-08 05:04:28.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-08T05:31:06.306Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>805.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>995650c539d34d66087dcca1ea8028ee49dec9ed</th>\n      <td>https://www.mirror.co.uk/news/world-news/briti...</td>\n      <td>British man, 21, \"critically injured\" after fa...</td>\n      <td>2018-01-16 06:59:32.175</td>\n      <td>2018-01-14 22:34:15.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-16T07:11:07.434Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>706</td>\n      <td>149.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>aab3bd1d10aeffcbe9d5698a3aef7294d8752dda</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Barham scores 24, Florida A&amp;M beats Hampton 75-71</td>\n      <td>2018-01-28 02:16:22.229</td>\n      <td>2018-01-28 02:05:13.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-28T08:33:16.510Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>194.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>da946e19481606d8888cf11718085c0d607d4206</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Walters leads Middle Tennessee past UTEP in 81...</td>\n      <td>2018-01-28 02:37:12.663</td>\n      <td>2018-01-28 02:27:09.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-28T08:52:07.587Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>172.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>555fedb56d18686a19dcc56cca6d1cbf22388e65</th>\n      <td>https://www.washingtonpost.com/lifestyle/style...</td>\n      <td>Hints From Heloise: The thief in the lunchroom</td>\n      <td>2018-01-08 05:07:13.477</td>\n      <td>2018-01-08 05:00:00.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-08T06:19:06.445Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>537.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>3ac84db6e700bc67b50546171c9041257be08e51</th>\n      <td>https://www.washingtonpost.com/lifestyle/style...</td>\n      <td>Ask Amy: Abuse survivor can\u2019t handle family qu...</td>\n      <td>2018-01-08 05:07:13.567</td>\n      <td>2018-01-08 05:00:00.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-08T06:19:06.448Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>778.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>32d66b7075a085a130bbb206bb9a2ce95ed2e86f</th>\n      <td>https://www.washingtonpost.com/lifestyle/style...</td>\n      <td>Miss Manners: Parsing the feminine honorifics</td>\n      <td>2018-01-08 05:07:15.628</td>\n      <td>2018-01-08 05:00:00.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-01-08T07:19:10.971Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>533.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>10c192fcc6f47a813527cadf281785cd55a0434f</th>\n      <td>https://www.washingtonpost.com/business/why-af...</td>\n      <td>Why Africa\u2019s Top Oil Producer Is Low on Gasoli...</td>\n      <td>2018-01-08 12:31:22.321</td>\n      <td>2018-01-08 05:00:04.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-01-08T13:44:05.462Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>694.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>7b71ec5d35fd22ef408e862e224059312c9a32fa</th>\n      <td>https://www.mirror.co.uk/tv/tv-news/celebrity-...</td>\n      <td>Celebrity Big Brother fans complain as Shane J...</td>\n      <td>2018-01-16 06:58:54.111</td>\n      <td>2018-01-14 22:37:16.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-16T07:10:13.467Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>706</td>\n      <td>259.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>27c068a05917d13ab5cd1d6180c142b710d2e3c9</th>\n      <td>http://www.dailymail.co.uk/sport/esports/artic...</td>\n      <td>FIFA 18 new patch fixes kick off glitch</td>\n      <td>2018-01-23 15:19:30.946</td>\n      <td>2018-01-23 15:17:24.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-24T01:39:22.348Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>309.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>4b29cf2d2bca67071dd4a5dbb76612aa23332a8b</th>\n      <td>http://www.dailymail.co.uk/sport/football/arti...</td>\n      <td>Newport striker Padraig Amond - One to Eleven</td>\n      <td>2018-01-14 22:37:17.965</td>\n      <td>2018-01-14 22:35:28.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-01-14T23:49:15.377Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>466.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>c4d5ad119e86b0ed065496eb5e111bab03276d95</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>William &amp; Mary hangs on to beat UNC Wilmington...</td>\n      <td>2018-01-28 02:37:10.362</td>\n      <td>2018-01-28 02:29:28.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-28T08:52:07.535Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>169.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>c4abfd5f6cc6a25a9f43a52ddf611f044af0d69f</th>\n      <td>https://www.washingtonpost.com/sports/wizards/...</td>\n      <td>Wall has recurrence of knee pain, held out aga...</td>\n      <td>2018-01-28 02:37:10.425</td>\n      <td>2018-01-28 02:28:30.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-28T08:52:07.555Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>238.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>25b1599e5e93f4373ef3acbebb3b0e58cdbd514b</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Brodeur helps Penn hold off Saint Joseph\u2019s 67-...</td>\n      <td>2018-01-28 02:37:11.811</td>\n      <td>2018-01-28 02:28:12.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-28T08:52:07.572Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>174.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>e8232dbc2cf75aa01ae8cf315a6acda16eda177c</th>\n      <td>http://www.dailymail.co.uk/tvshowbiz/article-5...</td>\n      <td>Jennifer Hawkins cuddles up to husband Jake Wall</td>\n      <td>2018-01-28 02:28:17.464</td>\n      <td>2018-01-28 02:25:12.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-28T08:44:04.294Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>558.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>f5e709aa5794d90ea0e4d01b866abc441e68d1be</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Old Dominion beats Charlotte 88-66, wins 4th s...</td>\n      <td>2018-01-28 02:16:19.338</td>\n      <td>2018-01-28 02:06:10.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-28T08:33:16.494Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>176.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>b7a120b7f2681899aa1d43d9f3f2a140a4ba47e9</th>\n      <td>http://www.dailymail.co.uk/sport/football/arti...</td>\n      <td>Daniel Farke eyes free shot at glory against C...</td>\n      <td>2018-01-14 22:37:21.897</td>\n      <td>2018-01-14 22:35:11.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-01-14T23:49:15.398Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>638.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>51014e4fb3e49c23b3b3a12496675e00eba9dfae</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Casimir has 20 points, Iona turns back Manhatt...</td>\n      <td>2018-01-28 02:31:06.992</td>\n      <td>2018-01-28 02:20:22.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-28T08:46:05.113Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>179.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>ffbfcdd8dc5c84acd9c50fcdd189acdb65a0fcaa</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>FGCU closes with 8-0 run to beat Jacksonville ...</td>\n      <td>2018-01-28 02:31:07.067</td>\n      <td>2018-01-28 02:20:15.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-28T08:46:05.132Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>163.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>16d0a3ec7ed8c13d5aa82566cb9b817b61d04532</th>\n      <td>https://www.washingtonpost.com/national/rapper...</td>\n      <td>Rapper Nelly, fan file competing versions of s...</td>\n      <td>2018-01-28 02:28:14.924</td>\n      <td>2018-01-28 02:18:22.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-28T08:44:04.276Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>603.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>327faa8adec736a7debe104db7d512c3233e884f</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Anderson delivers late, Navy tops Lehigh 77-75</td>\n      <td>2018-01-28 02:25:04.583</td>\n      <td>2018-01-28 02:17:15.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-28T08:40:03.187Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>216.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>2ef956f187a178dcd6b1817a1e56010f8628a057</th>\n      <td>https://www.ft.com/content/abdeb618-f180-11e7-...</td>\n      <td>We are already suffering the damaging effects ...</td>\n      <td>2018-01-08 05:04:28.615</td>\n      <td>2018-01-08 05:00:55.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-01-08T06:17:04.843Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>1596</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>f4c3da59ef44df98bec31fc15abdb3973b169ca7</th>\n      <td>http://www.washingtonpost.com/video/world/aval...</td>\n      <td>Avalanche engulfs skiers after Japan volcano e...</td>\n      <td>2018-01-23 15:31:16.693</td>\n      <td>2018-01-23 15:18:51.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-24T02:52:12.755Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>9c92d18449aff15dfdc7c655d06f5148161428b9</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Louisiana Tech cruises in 89-66 win over South...</td>\n      <td>2018-01-28 02:16:15.187</td>\n      <td>2018-01-28 02:10:13.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-28T08:33:16.490Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>153.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>aca036363a230a24ee00a0e64c57e963b841991e</th>\n      <td>https://www.huffingtonpost.com/entry/how-to-cl...</td>\n      <td>How to clean a child\u2019s bedroom?</td>\n      <td>2018-01-14 22:46:20.704</td>\n      <td>2018-01-14 22:35:00.803</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-14T23:59:09.146Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>843.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>4f3f840a6b6dcb799c688c2fc1b851d1b12c2b4c</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Whitley lifts Norfolk State over Bethune-Cookm...</td>\n      <td>2018-01-28 02:16:15.146</td>\n      <td>2018-01-28 02:06:16.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-28T08:33:16.477Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>183.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>a20d1203cc1ce26ace6dff72dc271ea8346cd27b</th>\n      <td>https://www.washingtonpost.com/business/weeken...</td>\n      <td>Weekend derailment is latest black eye for DC ...</td>\n      <td>2018-01-16 22:16:18.353</td>\n      <td>2018-01-16 22:09:27.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-17T00:29:15.035Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>859.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>153117 rows \u00d7 26 columns</p>\n</div>\n\n\n\n\n```python\ndata[\"score_diff\"] = data.promotion_score - data.response_score\n```\n\n\n```python\n# promoted but low response\ndata.sort_values(\"score_diff\", ascending=False).head(25)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n      <th>score_diff</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>068b7cac1ba2fb9fbbdec4f11a72939a7f50c246</th>\n      <td>https://www.buzzfeed.com/nicolenguyen/how-to-s...</td>\n      <td>How To Save Money, According To People Who Are...</td>\n      <td>2018-01-24 23:22:11.826</td>\n      <td>2018-01-11 20:23:03</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-24T23:33:10.999Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2018-01-25T03:44:32.000Z</td>\n      <td>147</td>\n      <td>1564.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>43.00</td>\n      <td>43.00</td>\n    </tr>\n    <tr>\n      <th>20bcf4e6d32506b0ae7be2a902e442bcbaf7b560</th>\n      <td>https://www.buzzfeed.com/stephaniemlee/food-in...</td>\n      <td>Here\u2019s How The Food Industry Justifies Adverti...</td>\n      <td>2018-01-06 15:44:13.488</td>\n      <td>2018-01-05 01:45:54</td>\n      <td>4</td>\n      <td>0.10</td>\n      <td>2018-01-06T15:55:15.366Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>4</td>\n      <td>...</td>\n      <td>2018-01-06T18:14:55.000Z</td>\n      <td>147</td>\n      <td>1009.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>45.00</td>\n      <td>43.00</td>\n    </tr>\n    <tr>\n      <th>2d6b7abf9b304cea66b7a876e276408374574957</th>\n      <td>https://www.buzzfeed.com/jtes/shes-17-and-want...</td>\n      <td>She\u2019s 17 And Wants To Be A Politician. Her Dad...</td>\n      <td>2018-01-16 15:04:30.976</td>\n      <td>2018-01-09 20:55:30</td>\n      <td>3</td>\n      <td>0.27</td>\n      <td>2018-01-16T15:16:07.887Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>...</td>\n      <td>2018-01-20T17:32:05.000Z</td>\n      <td>147</td>\n      <td>3933.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>44.00</td>\n      <td>42.00</td>\n    </tr>\n    <tr>\n      <th>f4b77490386f612eb0a3cb4a692a8dd7155c54cb</th>\n      <td>https://www.buzzfeed.com/thomasfrank/secret-mo...</td>\n      <td>Secret Money: How Trump Made Millions Selling ...</td>\n      <td>2018-01-12 14:37:21.997</td>\n      <td>2018-01-10 22:27:30</td>\n      <td>5</td>\n      <td>0.50</td>\n      <td>2018-01-12T14:48:13.783Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>...</td>\n      <td>2018-01-12T15:55:07.000Z</td>\n      <td>147</td>\n      <td>3863.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>44.00</td>\n      <td>42.00</td>\n    </tr>\n    <tr>\n      <th>968d49aee54385668d5cbb27da9406781f04d699</th>\n      <td>https://www.buzzfeed.com/remysmidt/mila-emma-k...</td>\n      <td>Here\u2019s What It\u2019s Like To Have A Toddler Who Is...</td>\n      <td>2018-01-25 13:46:20.267</td>\n      <td>2018-01-23 21:56:06</td>\n      <td>4</td>\n      <td>0.39</td>\n      <td>2018-01-25T13:57:24.612Z</td>\n      <td>0</td>\n      <td>2</td>\n      <td>2</td>\n      <td>...</td>\n      <td>2018-01-25T14:23:03.000Z</td>\n      <td>147</td>\n      <td>2551.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>44.00</td>\n      <td>42.00</td>\n    </tr>\n    <tr>\n      <th>01bc6bc560d98aaee1d28dcbc8cd713dbd5b9869</th>\n      <td>https://www.buzzfeed.com/holgerroonemaa/he-bui...</td>\n      <td>He Built An Empire From Angry Birds. Now He Wa...</td>\n      <td>2018-01-17 16:01:28.336</td>\n      <td>2018-01-12 22:27:34</td>\n      <td>4</td>\n      <td>0.37</td>\n      <td>2018-01-17T16:13:13.090Z</td>\n      <td>0</td>\n      <td>2</td>\n      <td>2</td>\n      <td>...</td>\n      <td>2018-01-21T15:03:14.000Z</td>\n      <td>147</td>\n      <td>1411.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>44.00</td>\n      <td>42.00</td>\n    </tr>\n    <tr>\n      <th>d2645225548e8c3f460c983f79d2b5a875e4d295</th>\n      <td>https://www.buzzfeed.com/gabrielsanchez/the-ho...</td>\n      <td>23 Pictures That Capture The Horrors Of The Ho...</td>\n      <td>2018-01-27 16:01:15.901</td>\n      <td>2018-01-25 17:01:28</td>\n      <td>2</td>\n      <td>0.18</td>\n      <td>2018-01-27T16:13:08.100Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>...</td>\n      <td>2018-01-27T21:42:59.000Z</td>\n      <td>147</td>\n      <td>nan</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>43.00</td>\n      <td>41.00</td>\n    </tr>\n    <tr>\n      <th>2e3e87dfe855f9cc6268036577e2fdf743a22c40</th>\n      <td>https://www.buzzfeed.com/peteraldhous/trump-tw...</td>\n      <td>How Trump\u2019s Tweets Shaped A Year In Politics</td>\n      <td>2018-01-23 15:29:12.177</td>\n      <td>2018-01-23 11:50:57</td>\n      <td>45</td>\n      <td>0.15</td>\n      <td>2018-01-23T21:46:14.335Z</td>\n      <td>5</td>\n      <td>17</td>\n      <td>23</td>\n      <td>...</td>\n      <td>2018-01-23T19:44:39.000Z</td>\n      <td>147</td>\n      <td>1017.00</td>\n      <td>6.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>50.00</td>\n      <td>38.00</td>\n    </tr>\n    <tr>\n      <th>6a35a172d4c5c2a9dda4b89cd53f1c1787b7246c</th>\n      <td>https://www.buzzfeed.com/paulmcleod/the-fate-o...</td>\n      <td>The Fate Of DACA Recipients May Come Down To F...</td>\n      <td>2018-01-10 20:40:17.887</td>\n      <td>2018-01-10 20:37:02</td>\n      <td>30</td>\n      <td>0.11</td>\n      <td>2018-01-10T23:54:09.386Z</td>\n      <td>2</td>\n      <td>2</td>\n      <td>26</td>\n      <td>...</td>\n      <td>2018-01-13T19:21:54.000Z</td>\n      <td>147</td>\n      <td>1046.00</td>\n      <td>5.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>48.00</td>\n      <td>38.00</td>\n    </tr>\n    <tr>\n      <th>a0267241a3ff57f538b29cf4dca6e2b3aa3cf08b</th>\n      <td>https://www.buzzfeed.com/johnhudson/trump-lets...</td>\n      <td>Trump Lets The Iran Deal Live \u2014 For Another Th...</td>\n      <td>2018-01-12 19:22:25.497</td>\n      <td>2018-01-12 19:21:22</td>\n      <td>40</td>\n      <td>0.25</td>\n      <td>2018-01-12T21:35:09.636Z</td>\n      <td>11</td>\n      <td>12</td>\n      <td>17</td>\n      <td>...</td>\n      <td>2018-01-12T20:42:11.000Z</td>\n      <td>147</td>\n      <td>411.00</td>\n      <td>6.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>49.00</td>\n      <td>37.00</td>\n    </tr>\n    <tr>\n      <th>22ebd00bcf2cd95645cb1d16347e22b5021dfb93</th>\n      <td>https://www.buzzfeed.com/juliareinstein/i-went...</td>\n      <td>I Went To This Year's Puppy Bowl. Here's Every...</td>\n      <td>2018-02-04 14:37:12.609</td>\n      <td>2018-01-31 22:00:52</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>2018-02-04T14:48:07.097Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>2018-02-04T22:19:02.000Z</td>\n      <td>147</td>\n      <td>642.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>7.00</td>\n      <td>11.00</td>\n      <td>37.00</td>\n      <td>37.00</td>\n      <td>37.00</td>\n    </tr>\n    <tr>\n      <th>93ca7c4fe189518498d77c800ebeae14a093aef2</th>\n      <td>https://www.buzzfeed.com/paulmcleod/the-house-...</td>\n      <td>The House Just Voted To Keep The Government Op...</td>\n      <td>2018-01-19 00:40:22.163</td>\n      <td>2018-01-19 00:39:03</td>\n      <td>62</td>\n      <td>0.20</td>\n      <td>2018-01-19T02:54:07.176Z</td>\n      <td>11</td>\n      <td>25</td>\n      <td>26</td>\n      <td>...</td>\n      <td>2018-01-20T05:08:03.000Z</td>\n      <td>147</td>\n      <td>574.00</td>\n      <td>8.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>53.00</td>\n      <td>37.00</td>\n    </tr>\n    <tr>\n      <th>652d2f4057c2019354903a162b55b5ae1e1b4203</th>\n      <td>https://www.buzzfeed.com/melissasegura/will-ch...</td>\n      <td>Will Chicago Prosecutors Let Guevara\u2019s Defenda...</td>\n      <td>2018-01-22 14:04:24.260</td>\n      <td>2018-01-19 22:38:05</td>\n      <td>3</td>\n      <td>0.28</td>\n      <td>2018-01-22T14:16:06.968Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>...</td>\n      <td>2018-01-22T14:22:51.000Z</td>\n      <td>147</td>\n      <td>5466.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>7.00</td>\n      <td>11.00</td>\n      <td>37.00</td>\n      <td>38.00</td>\n      <td>36.00</td>\n    </tr>\n    <tr>\n      <th>8eb8e48cfacb1432585819e4836b6ea7134ef312</th>\n      <td>https://www.buzzfeed.com/zahrahirji/superfund-...</td>\n      <td>A Government Watchdog Is Investigating Whether...</td>\n      <td>2018-01-05 15:29:12.897</td>\n      <td>2018-01-05 15:10:35</td>\n      <td>46</td>\n      <td>0.17</td>\n      <td>2018-01-05T19:43:10.925Z</td>\n      <td>5</td>\n      <td>26</td>\n      <td>15</td>\n      <td>...</td>\n      <td>2018-01-05T18:44:36.000Z</td>\n      <td>147</td>\n      <td>355.00</td>\n      <td>7.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>50.00</td>\n      <td>36.00</td>\n    </tr>\n    <tr>\n      <th>98726f5b62c51f14804408a84d7540072418ceff</th>\n      <td>https://www.buzzfeed.com/leticiamiranda/two-ti...</td>\n      <td>Two Tinder Security Flaws Mean Strangers Can S...</td>\n      <td>2018-01-23 23:13:26.707</td>\n      <td>2018-01-23 19:18:23</td>\n      <td>32</td>\n      <td>0.32</td>\n      <td>2018-01-24T03:28:21.263Z</td>\n      <td>10</td>\n      <td>15</td>\n      <td>7</td>\n      <td>...</td>\n      <td>2018-01-24T02:32:09.000Z</td>\n      <td>147</td>\n      <td>516.00</td>\n      <td>5.00</td>\n      <td>19.00</td>\n      <td>11.00</td>\n      <td>11.00</td>\n      <td>41.00</td>\n      <td>46.00</td>\n      <td>36.00</td>\n    </tr>\n    <tr>\n      <th>c247bc552abec2dc3b5843661d0eecc380311ba0</th>\n      <td>https://www.theguardian.com/us-news/2018/jan/1...</td>\n      <td>'Unkind, divisive, elitist': international out...</td>\n      <td>2018-01-12 04:01:12.095</td>\n      <td>2018-01-12 03:58:54</td>\n      <td>5</td>\n      <td>37.60</td>\n      <td>2018-01-12T14:57:03.228Z</td>\n      <td>1</td>\n      <td>1</td>\n      <td>3</td>\n      <td>...</td>\n      <td>2018-01-12T14:40:00.000Z</td>\n      <td>142</td>\n      <td>688.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>4.00</td>\n      <td>13.00</td>\n      <td>36.00</td>\n      <td>37.00</td>\n      <td>35.00</td>\n    </tr>\n    <tr>\n      <th>fdf1427a0e1cde9a0c5c156df566ae6eaed9d658</th>\n      <td>https://www.buzzfeed.com/lissandravilla/house-...</td>\n      <td>The House Just Released A Bill To Overhaul The...</td>\n      <td>2018-01-18 18:37:19.473</td>\n      <td>2018-01-18 17:05:56</td>\n      <td>57</td>\n      <td>0.49</td>\n      <td>2018-01-18T18:48:22.993Z</td>\n      <td>2</td>\n      <td>13</td>\n      <td>42</td>\n      <td>...</td>\n      <td>2018-01-18T19:02:41.000Z</td>\n      <td>147</td>\n      <td>552.00</td>\n      <td>7.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>49.00</td>\n      <td>35.00</td>\n    </tr>\n    <tr>\n      <th>6d936b4b490c7dd59d30e8576320d2f00e811ff7</th>\n      <td>https://www.buzzfeed.com/emmaloop/house-invest...</td>\n      <td>House Investigators Vow To Get Answers Out Of ...</td>\n      <td>2018-01-17 22:01:21.002</td>\n      <td>2018-01-17 21:58:15</td>\n      <td>95</td>\n      <td>0.61</td>\n      <td>2018-01-18T01:15:10.445Z</td>\n      <td>13</td>\n      <td>68</td>\n      <td>14</td>\n      <td>...</td>\n      <td>2018-01-18T00:07:52.000Z</td>\n      <td>147</td>\n      <td>806.00</td>\n      <td>10.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>54.00</td>\n      <td>34.00</td>\n    </tr>\n    <tr>\n      <th>f5f921383c99bf3d1428e6a181d2101c494f4ebc</th>\n      <td>https://www.buzzfeed.com/krystieyandoli/bryan-...</td>\n      <td>Bryan Singer Leaves FX's \"Legion\" As He Faces ...</td>\n      <td>2018-01-05 22:54:12.914</td>\n      <td>2018-01-05 22:29:15</td>\n      <td>108</td>\n      <td>0.30</td>\n      <td>2018-01-06T05:08:12.670Z</td>\n      <td>27</td>\n      <td>53</td>\n      <td>28</td>\n      <td>...</td>\n      <td>2018-01-06T03:42:34.000Z</td>\n      <td>147</td>\n      <td>272.00</td>\n      <td>10.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>53.00</td>\n      <td>33.00</td>\n    </tr>\n    <tr>\n      <th>7ed734430d65005ef540ff22b35de52f58880d3d</th>\n      <td>https://www.buzzfeed.com/susancheng/talent-age...</td>\n      <td>Will Time\u2019s Up Help Talent Agencies Rebuild Tr...</td>\n      <td>2018-01-06 15:13:10.239</td>\n      <td>2018-01-06 15:10:15</td>\n      <td>96</td>\n      <td>0.28</td>\n      <td>2018-01-06T21:27:16.662Z</td>\n      <td>6</td>\n      <td>60</td>\n      <td>30</td>\n      <td>...</td>\n      <td>2018-01-06T20:14:11.000Z</td>\n      <td>147</td>\n      <td>1102.00</td>\n      <td>10.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>53.00</td>\n      <td>33.00</td>\n    </tr>\n    <tr>\n      <th>cda1e43d83e0efe0dd6870459b1e0ca1f36a681d</th>\n      <td>https://www.buzzfeed.com/venessawong/how-much-...</td>\n      <td>Here's What A $75K Salary Gets You In Six Diff...</td>\n      <td>2018-01-25 17:01:17.219</td>\n      <td>2018-01-24 21:11:36</td>\n      <td>103</td>\n      <td>0.69</td>\n      <td>2018-01-25T18:13:17.201Z</td>\n      <td>13</td>\n      <td>53</td>\n      <td>37</td>\n      <td>...</td>\n      <td>2018-01-25T17:26:09.000Z</td>\n      <td>147</td>\n      <td>4270.00</td>\n      <td>10.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>53.00</td>\n      <td>33.00</td>\n    </tr>\n    <tr>\n      <th>7de66844bf72e95af45dc613b3e59083656e77cb</th>\n      <td>https://www.buzzfeed.com/rosebuchanan/donald-t...</td>\n      <td>Donald Trump Has Tweeted About Iranians \"Final...</td>\n      <td>2018-01-02 14:25:19.415</td>\n      <td>2018-01-02 13:16:17</td>\n      <td>129</td>\n      <td>0.30</td>\n      <td>2018-01-02T16:38:08.016Z</td>\n      <td>33</td>\n      <td>55</td>\n      <td>41</td>\n      <td>...</td>\n      <td>2018-01-02T16:05:10.000Z</td>\n      <td>147</td>\n      <td>644.00</td>\n      <td>11.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>55.00</td>\n      <td>33.00</td>\n    </tr>\n    <tr>\n      <th>f3eab5a109a2a8f3a7d601a58aaab2395e55090d</th>\n      <td>https://www.buzzfeed.com/buzzfeednews/trump-so...</td>\n      <td>Trump\u2019s First State Of The Union Address Is To...</td>\n      <td>2018-01-30 12:01:18.015</td>\n      <td>2018-01-30 11:45:40</td>\n      <td>144</td>\n      <td>0.48</td>\n      <td>2018-01-30T17:16:21.822Z</td>\n      <td>74</td>\n      <td>49</td>\n      <td>21</td>\n      <td>...</td>\n      <td>2018-01-30T16:28:33.000Z</td>\n      <td>147</td>\n      <td>786.00</td>\n      <td>12.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>57.00</td>\n      <td>33.00</td>\n    </tr>\n    <tr>\n      <th>776e0e6559937a4fb0f3db20935adf7bfed033b7</th>\n      <td>https://www.buzzfeed.com/tariniparti/the-stars...</td>\n      <td>The Stars Of The Trump Show, Season 2</td>\n      <td>2018-01-31 15:04:26.400</td>\n      <td>2018-01-31 01:44:52</td>\n      <td>96</td>\n      <td>0.46</td>\n      <td>2018-01-31T19:19:15.015Z</td>\n      <td>9</td>\n      <td>41</td>\n      <td>46</td>\n      <td>...</td>\n      <td>2018-01-31T18:50:59.000Z</td>\n      <td>147</td>\n      <td>1508.00</td>\n      <td>10.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>52.00</td>\n      <td>32.00</td>\n    </tr>\n    <tr>\n      <th>39927be4665f707b073fecee5a28dd887a52772d</th>\n      <td>https://www.buzzfeed.com/paulmcleod/senate-gro...</td>\n      <td>Senate Group Reaches Tentative Deal To Protect...</td>\n      <td>2018-01-12 00:49:18.168</td>\n      <td>2018-01-12 00:48:10</td>\n      <td>170</td>\n      <td>0.67</td>\n      <td>2018-01-12T07:04:13.216Z</td>\n      <td>68</td>\n      <td>83</td>\n      <td>19</td>\n      <td>...</td>\n      <td>2018-01-12T06:22:48.000Z</td>\n      <td>147</td>\n      <td>643.00</td>\n      <td>13.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>58.00</td>\n      <td>32.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>25 rows \u00d7 27 columns</p>\n</div>\n\n\n\n\n```python\n# high response but not promoted\ndata.sort_values(\"score_diff\", ascending=True).head(25)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n      <th>score_diff</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>803b607134c251c7f072a2971a268e9d7df235f1</th>\n      <td>https://www.huffingtonpost.com/entry/detroit-h...</td>\n      <td>Black Beekeepers Are Transforming Detroit\u2019s Va...</td>\n      <td>2018-01-30 22:04:27.140</td>\n      <td>2018-01-30 21:55:24.297</td>\n      <td>99088</td>\n      <td>191.45</td>\n      <td>2018-01-31T22:05:12.382Z</td>\n      <td>5852</td>\n      <td>81139</td>\n      <td>12097</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>583.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>a393b7e68704544e101afc19f12d7fccf1e4ab29</th>\n      <td>https://www.nytimes.com/2018/01/06/us/politics...</td>\n      <td>Trump Defends His Mental Capacity, Calling Him...</td>\n      <td>2018-01-06 13:07:03.430</td>\n      <td>2018-01-06 13:05:21.000</td>\n      <td>328205</td>\n      <td>1162.29</td>\n      <td>2018-01-07T04:03:08.078Z</td>\n      <td>85369</td>\n      <td>219767</td>\n      <td>23069</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>120</td>\n      <td>176.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>771937ba1ca44a5bab7f2bf908ed2a617a461b5f</th>\n      <td>http://www.cnn.com/2015/08/21/europe/france-tr...</td>\n      <td>2 U.S. service members overpower attacker on t...</td>\n      <td>2018-01-08 22:04:37.055</td>\n      <td>2018-01-08 22:01:45.000</td>\n      <td>286779</td>\n      <td>0.03</td>\n      <td>2018-01-08T23:17:08.269Z</td>\n      <td>16743</td>\n      <td>251594</td>\n      <td>18442</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>105</td>\n      <td>746.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>bdcb4edf76aa052524088d63507d58de12c6f08c</th>\n      <td>http://www.foxnews.com/entertainment/2018/01/2...</td>\n      <td>Joy Villa turns heads with pro-life outfit at ...</td>\n      <td>2018-01-28 21:24:14.205</td>\n      <td>2018-01-28 21:15:38.000</td>\n      <td>145813</td>\n      <td>341.15</td>\n      <td>2018-01-29T23:27:11.734Z</td>\n      <td>10493</td>\n      <td>127537</td>\n      <td>7783</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>361.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>fdeb3ce25505712faa29accfaa210a61d7dc208a</th>\n      <td>https://www.rt.com/on-air/415184-orthodox-chri...</td>\n      <td>Orthodox Christmas service in Moscow</td>\n      <td>2018-01-06 20:09:34.285</td>\n      <td>2018-01-06 20:09:34.285</td>\n      <td>180211</td>\n      <td>2985.36</td>\n      <td>2018-01-07T00:22:14.681Z</td>\n      <td>24841</td>\n      <td>11360</td>\n      <td>144010</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>365</td>\n      <td>nan</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>47d6d90f0ccf562ad2636799d240cea22854b5d8</th>\n      <td>http://www.breitbart.com/big-government/2018/0...</td>\n      <td>Pentagon: Troops Will Not Be Paid if Governmen...</td>\n      <td>2018-01-17 18:09:33.475</td>\n      <td>2018-01-17 07:43:57.000</td>\n      <td>82550</td>\n      <td>50.97</td>\n      <td>2018-01-20T15:48:07.846Z</td>\n      <td>38299</td>\n      <td>33144</td>\n      <td>11107</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>994</td>\n      <td>896.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>0f7d6665afef43e9f21cf944435ae79bacce5428</th>\n      <td>http://www.dailymail.co.uk/news/article-533244...</td>\n      <td>Police chief demands end of soft treatment for...</td>\n      <td>2018-01-30 23:58:23.681</td>\n      <td>2018-01-30 23:55:30.000</td>\n      <td>126418</td>\n      <td>1322.37</td>\n      <td>2018-01-31T12:05:10.269Z</td>\n      <td>51315</td>\n      <td>42165</td>\n      <td>32938</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>1235.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>4ec1a6cfd6e184ef18478392685313d0c52fe46e</th>\n      <td>http://www.foxnews.com/entertainment/2018/01/1...</td>\n      <td>\u2018OUT!\u2019 Trump orders CNN star Jim Acosta to lea...</td>\n      <td>2018-01-16 20:44:11.564</td>\n      <td>2018-01-16 20:41:23.000</td>\n      <td>81022</td>\n      <td>105.32</td>\n      <td>2018-01-17T02:56:06.018Z</td>\n      <td>18036</td>\n      <td>55513</td>\n      <td>7473</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>502.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>10ea42828a1a94dcfeecd8238529bd4c43370c98</th>\n      <td>https://www.cnn.com/2018/01/24/us/rachael-denh...</td>\n      <td>Read Rachael Denhollander's full victim impact...</td>\n      <td>2018-01-24 19:10:15.381</td>\n      <td>2018-01-24 19:05:22.000</td>\n      <td>89632</td>\n      <td>135.76</td>\n      <td>2018-01-26T15:09:07.110Z</td>\n      <td>11543</td>\n      <td>70530</td>\n      <td>7559</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>105</td>\n      <td>5852.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>85e73241452d2301d06e92c0a9dada5937a0dcf2</th>\n      <td>http://www.cnn.com/2015/08/22/europe/france-tr...</td>\n      <td>The men who averted a massacre aboard a French...</td>\n      <td>2018-01-08 22:04:38.355</td>\n      <td>2018-01-08 22:00:15.000</td>\n      <td>70815</td>\n      <td>0.02</td>\n      <td>2018-02-05T23:35:15.141Z</td>\n      <td>5609</td>\n      <td>56048</td>\n      <td>9158</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>105</td>\n      <td>1104.00</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>49.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>9d5b90f00e28072211f83e233767d503b694c7e7</th>\n      <td>http://www.cnn.com/2018/01/15/europe/garbage-c...</td>\n      <td>Garbage collectors open library with abandoned...</td>\n      <td>2018-01-16 01:52:17.539</td>\n      <td>2018-01-16 01:47:26.000</td>\n      <td>67487</td>\n      <td>40.98</td>\n      <td>2018-01-16T20:29:19.466Z</td>\n      <td>2594</td>\n      <td>58094</td>\n      <td>6799</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>105</td>\n      <td>376.00</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>49.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>8396eb9804a17111232bd6065cf74e0106bf0f16</th>\n      <td>http://www.foxnews.com/politics/2018/01/25/joh...</td>\n      <td>John Kerry reportedly coaches Palestinians not...</td>\n      <td>2018-01-25 14:54:17.351</td>\n      <td>2018-01-25 14:41:19.000</td>\n      <td>71119</td>\n      <td>148.48</td>\n      <td>2018-01-25T16:53:23.350Z</td>\n      <td>26574</td>\n      <td>35451</td>\n      <td>9094</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>576.00</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>50.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>ebd68d73a5584df555ea06cc93d6c75c7b7e20d6</th>\n      <td>http://www.foxnews.com/entertainment/2018/01/0...</td>\n      <td>CNN revels in pot smoke during New Year's Eve ...</td>\n      <td>2018-01-01 17:39:13.048</td>\n      <td>2018-01-01 17:30:33.000</td>\n      <td>145395</td>\n      <td>207.93</td>\n      <td>2018-01-03T14:01:08.231Z</td>\n      <td>49007</td>\n      <td>83848</td>\n      <td>12540</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>378.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>52.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>38c1f7857d079e8c85349de720fc405e884bfbc6</th>\n      <td>http://www.independent.co.uk/arts-entertainmen...</td>\n      <td>Millennials watching Friends for first time on...</td>\n      <td>2018-01-11 21:34:22.306</td>\n      <td>2018-01-11 21:20:47.000</td>\n      <td>66764</td>\n      <td>30.12</td>\n      <td>2018-01-12T00:48:06.381Z</td>\n      <td>28096</td>\n      <td>34561</td>\n      <td>4107</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>386</td>\n      <td>298.00</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>50.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>777440766ccbb1859bcda2428f28c48706a1655b</th>\n      <td>http://www.foxnews.com/opinion/2018/01/22/nfl-...</td>\n      <td>NFL rejects veterans group's ad urging people ...</td>\n      <td>2018-01-23 01:49:20.399</td>\n      <td>2018-01-23 01:46:23.000</td>\n      <td>456321</td>\n      <td>521.90</td>\n      <td>2018-01-24T13:31:03.385Z</td>\n      <td>120206</td>\n      <td>272865</td>\n      <td>63250</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>227.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>52.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>becc40665f8af441b01017ff2ed59146473afe54</th>\n      <td>http://www.cnn.com/2015/08/22/europe/france-tr...</td>\n      <td>French train suspect carried two guns, lots of...</td>\n      <td>2018-01-08 22:04:29.818</td>\n      <td>2018-01-08 22:00:00.000</td>\n      <td>58310</td>\n      <td>0.00</td>\n      <td>2018-01-10T22:32:10.633Z</td>\n      <td>5850</td>\n      <td>44025</td>\n      <td>8435</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>105</td>\n      <td>1018.00</td>\n      <td>48.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>48.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>2547709a1be4a83d35a3def8acd2f5f468973e76</th>\n      <td>https://www.nytimes.com/2018/01/18/opinion/sod...</td>\n      <td>The Case for the Health Taxes</td>\n      <td>2018-01-18 13:19:08.621</td>\n      <td>2018-01-18 13:17:01.000</td>\n      <td>451200</td>\n      <td>2088.07</td>\n      <td>2018-01-19T16:03:03.902Z</td>\n      <td>360</td>\n      <td>450591</td>\n      <td>249</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>120</td>\n      <td>679.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>52.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>80f993f862ddfd00733b670a0ee7fad69a8c937a</th>\n      <td>http://www.mirror.co.uk/tv/tv-news/boy-no-brai...</td>\n      <td>Boy with 'no brain' stuns doctors as he learns...</td>\n      <td>2018-01-09 17:10:21.222</td>\n      <td>2018-01-09 16:54:00.000</td>\n      <td>52371</td>\n      <td>0.11</td>\n      <td>2018-01-09T22:25:11.095Z</td>\n      <td>4150</td>\n      <td>42875</td>\n      <td>5346</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>706</td>\n      <td>545.00</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>47.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>df2d396004ec22906597fac848babc4718e73773</th>\n      <td>https://www.washingtonpost.com/news/get-there/...</td>\n      <td>Stop charging me to attend your celebrations \u2014...</td>\n      <td>2018-01-30 22:22:21.683</td>\n      <td>2018-01-30 22:12:06.000</td>\n      <td>76260</td>\n      <td>47.84</td>\n      <td>2018-02-01T18:23:15.448Z</td>\n      <td>35866</td>\n      <td>34514</td>\n      <td>5880</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>824.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>53.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>e5fc4033e043254b3b0d5f1cc21dc39fc060cc7a</th>\n      <td>http://www.foxnews.com/entertainment/2018/01/3...</td>\n      <td>Liberal author Jonathan Tasini celebrates fata...</td>\n      <td>2018-01-31 19:39:13.991</td>\n      <td>2018-01-31 19:26:40.000</td>\n      <td>61580</td>\n      <td>145.70</td>\n      <td>2018-01-31T22:22:18.214Z</td>\n      <td>22205</td>\n      <td>29730</td>\n      <td>9645</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>518.00</td>\n      <td>48.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>49.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>ddb6d76257dbfdec72135dfa062d8837382c7341</th>\n      <td>https://www.washingtonpost.com/news/post-polit...</td>\n      <td>Names of campaign donors to be flashed during ...</td>\n      <td>2018-01-29 23:58:11.450</td>\n      <td>2018-01-29 23:52:53.000</td>\n      <td>126484</td>\n      <td>161.64</td>\n      <td>2018-01-30T10:02:16.802Z</td>\n      <td>55502</td>\n      <td>57529</td>\n      <td>13453</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>212.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>53.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>a8491b41e427001db8c871b55d7245c9cdd297e2</th>\n      <td>https://www.buzzfeed.com/kristinharris/tweets-...</td>\n      <td>22 Tweets For Everyone Still Crying After Last...</td>\n      <td>2018-01-24 19:34:12.007</td>\n      <td>2018-01-24 19:26:41.000</td>\n      <td>94446</td>\n      <td>119.11</td>\n      <td>2018-01-25T02:58:18.891Z</td>\n      <td>36452</td>\n      <td>45849</td>\n      <td>12145</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>nan</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>53.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>aeb247d60a50c77e54b0e0ca064d46dfcc6214d3</th>\n      <td>https://www.washingtonpost.com/opinions/no-mor...</td>\n      <td>No more excuses. Puerto Rico needs help.</td>\n      <td>2018-01-06 00:43:23.684</td>\n      <td>2018-01-06 00:32:49.000</td>\n      <td>45808</td>\n      <td>43.04</td>\n      <td>2018-01-07T07:09:12.325Z</td>\n      <td>3823</td>\n      <td>31304</td>\n      <td>10681</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>551.00</td>\n      <td>46.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>46.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>88f0ec3f4f6cfdb08ecd766c8f4a1c636dd41919</th>\n      <td>http://www.cnn.com/travel/article/switzerland-...</td>\n      <td>Switzerland bans cruelty towards lobster</td>\n      <td>2018-01-12 15:16:34.298</td>\n      <td>2018-01-12 15:09:50.000</td>\n      <td>51052</td>\n      <td>32.85</td>\n      <td>2018-01-13T03:32:17.625Z</td>\n      <td>11257</td>\n      <td>34322</td>\n      <td>5473</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>105</td>\n      <td>nan</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>48.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>5d5665bbfa2bf806355d04cb7a8b148981f99416</th>\n      <td>https://www.washingtonpost.com/news/politics/w...</td>\n      <td>Trump: \u2018Steve Bannon has nothing to do with me...</td>\n      <td>2018-01-03 18:43:12.552</td>\n      <td>2018-01-03 18:34:18.000</td>\n      <td>51178</td>\n      <td>337.79</td>\n      <td>2018-01-04T18:04:15.584Z</td>\n      <td>16207</td>\n      <td>28313</td>\n      <td>6658</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>127.00</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>48.00</td>\n      <td>-46.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>25 rows \u00d7 27 columns</p>\n</div>\n\n\n\nWrite that data to a file. Note that the scores here are provisional for two reasons:\n1. they should be using a rolling-month based on the article publication date to calculate medians/min/max etc, whereas in this workbook we as just using values for the month of May\n2. for analysis, we've rounded the numbers; we don't expect to do that for the actual scores\n\n\n```python\ndata.to_csv(\"articles_with_provisional_scores_\" + date_filename + \".csv\")\n```\n\n# Summary\n\nThe attention index of an article is comprised of four components:\n\n- *lead score* (max 20 points) based on how long an article was the lead story on the publisher's home page, scaled by the traffic to that publisher\n- *front score* (max 15 points) based on how long an article was present on the publisher's home page, scaled by traffic to that publisher\n- *Facebook promotion score* (max 15 points) based on whether the article was promoted to the publisher's Facebook brand page, scaled by the reach of that brand page\n- *response score* (max 50 points) based on the number of Facebook engagements the article received, relative to other articles\n\nOr, in other words:\n\n\\begin{align}\nattentionIndex_a &= leadScore_a + frontScore_a + facebookPromotionScore_a + responseScore_a \\\\\nleadScore_a &= 20 \\cdot \\left(\\frac{\\min(minsAsLead_a, 60)}{alexaRank_a}\\right) \\cdot \\left( \\frac{\\min(alexaRank)}{60} \\right) \\\\\nfrontScore_a &= \n15 \\cdot\n\\left(\\frac{\\min(minsOnFront_a, 1440)}{alexaRank_a \\cdot numArticlesOnFront_a}\\right) \\cdot\n\\left( \\frac{\\min(alexaRank \\cdot numArticlesOnFront)}{1440} \\right) \\\\\nfacebookPromotion_a &= \n\\begin{cases}\n 0 \\text{ if not shared on brand page }\\\\\n   15 \\cdot \\frac{\\log(brandPageLikes_a) - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))}  \\text{ otherwise }\n\\end{cases}   \n\\\\\nresponseScore_a &= \n\\begin{cases} \n   0 \\text{ if } engagements_a = 0 \\\\\n   50 \\cdot \n   \\frac{\\log(\\min(engagements_a,limit) + median(engagements)) - \\log(1 + median(engagements))}\n   {\\log(limit + median(engagements)) - \\log(1 + median(engagements))} \\text{ if } engagements_a > 0\n\\end{cases} \\\\\n\\end{align} \n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "b3956fa460986dd1f53f7a140561bfe7b4df59d0", "size": 732477, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "data/attention-index-january-2018.ipynb", "max_stars_repo_name": "kaleida/attention-index", "max_stars_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2017-06-03T11:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T10:02:06.000Z", "max_issues_repo_path": "data/attention-index-january-2018.ipynb", "max_issues_repo_name": "kaleida/attention-index", "max_issues_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data/attention-index-january-2018.ipynb", "max_forks_repo_name": "kaleida/attention-index", "max_forks_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 84.5816397229, "max_line_length": 46186, "alphanum_fraction": 0.692898207, "converted": true, "num_tokens": 56820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510527095787247, "lm_q2_score": 0.04535257910270417, "lm_q1q2_score": 0.015651414099877067}}
{"text": "```python\n!pip install pennylane StrawberryFields tensorflow-hub tensorflow_text emoji pythainlp pennylane-sf  plotnine\n```\n\n    Requirement already satisfied: pennylane in /usr/local/lib/python3.6/dist-packages (0.9.0)\n    Requirement already satisfied: StrawberryFields in /usr/local/lib/python3.6/dist-packages (0.14.0)\n    Requirement already satisfied: tensorflow-hub in /usr/local/lib/python3.6/dist-packages (0.8.0)\n    Requirement already satisfied: tensorflow_text in /usr/local/lib/python3.6/dist-packages (2.2.1)\n    Requirement already satisfied: emoji in /usr/local/lib/python3.6/dist-packages (0.5.4)\n    Requirement already satisfied: pythainlp in /usr/local/lib/python3.6/dist-packages (2.1.4)\n    Requirement already satisfied: pennylane-sf in /usr/local/lib/python3.6/dist-packages (0.9.0)\n    Collecting plotnine\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/aa/ee/9f343ef0719541e02950384978722ea84cc433264cece09a11a0cccb2bf9/plotnine-0.7.0-py3-none-any.whl (4.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4.4MB 977kB/s eta 0:00:01\n    \u001b[?25hRequirement already satisfied: autograd in /usr/local/lib/python3.6/dist-packages (from pennylane) (1.3)\n    Requirement already satisfied: networkx in /usr/local/lib/python3.6/dist-packages (from pennylane) (2.4)\n    Requirement already satisfied: toml in /usr/local/lib/python3.6/dist-packages (from pennylane) (0.10.1)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from pennylane) (1.3.1)\n    Requirement already satisfied: semantic-version==2.6 in /usr/local/lib/python3.6/dist-packages (from pennylane) (2.6.0)\n    Requirement already satisfied: appdirs in /usr/local/lib/python3.6/dist-packages (from pennylane) (1.4.4)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from pennylane) (1.17.4)\n    Requirement already satisfied: quantum-blackbird>=0.2.3 in /usr/local/lib/python3.6/dist-packages (from StrawberryFields) (0.2.4)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.6/dist-packages (from StrawberryFields) (2.8.1)\n    Requirement already satisfied: requests>=2.22.0 in /usr/local/lib/python3.6/dist-packages (from StrawberryFields) (2.22.0)\n    Requirement already satisfied: thewalrus>=0.12 in /usr/local/lib/python3.6/dist-packages (from StrawberryFields) (0.12.0)\n    Requirement already satisfied: urllib3>=1.25.3 in /usr/local/lib/python3.6/dist-packages (from StrawberryFields) (1.25.7)\n    Requirement already satisfied: numba in /usr/local/lib/python3.6/dist-packages (from StrawberryFields) (0.49.1)\n    Requirement already satisfied: sympy>=1.5 in /usr/local/lib/python3.6/dist-packages (from StrawberryFields) (1.6)\n    Requirement already satisfied: six>=1.12.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-hub) (1.13.0)\n    Requirement already satisfied: protobuf>=3.8.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-hub) (3.10.0)\n    Requirement already satisfied: tensorflow<2.3,>=2.2.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow_text) (2.2.0)\n    Requirement already satisfied: nltk>=3.3 in /usr/local/lib/python3.6/dist-packages (from pythainlp) (3.4.5)\n    Requirement already satisfied: dill>=0.3.0 in /usr/local/lib/python3.6/dist-packages (from pythainlp) (0.3.1.1)\n    Requirement already satisfied: tqdm>=4.1 in /usr/local/lib/python3.6/dist-packages (from pythainlp) (4.38.0)\n    Requirement already satisfied: tinydb>=3.0 in /usr/local/lib/python3.6/dist-packages (from pythainlp) (3.15.2)\n    Collecting mizani>=0.7.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/57/29/72ed07818b1cd7f79340d55c7230748238e09c35fc8461c545a5d350006d/mizani-0.7.1-py3-none-any.whl (62kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 71kB 11.1MB/s eta 0:00:01\n    \u001b[?25hCollecting statsmodels>=0.11.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/cb/83/540fd83238a18abe6c2d280fa8e489ac5fcefa1f370f0ca1acd16ae1b860/statsmodels-0.11.1-cp36-cp36m-manylinux1_x86_64.whl (8.7MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 8.7MB 11.3MB/s eta 0:00:01\n    \u001b[?25hRequirement already satisfied: matplotlib>=3.1.1 in /usr/local/lib/python3.6/dist-packages (from plotnine) (3.2.1)\n    Collecting patsy>=0.5.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/ea/0c/5f61f1a3d4385d6bf83b83ea495068857ff8dfb89e74824c6e9eb63286d8/patsy-0.5.1-py2.py3-none-any.whl (231kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 235kB 29.0MB/s eta 0:00:01\n    \u001b[?25hCollecting descartes>=1.1.0\n      Downloading https://files.pythonhosted.org/packages/e5/b6/1ed2eb03989ae574584664985367ba70cd9cf8b32ee8cad0e8aaeac819f3/descartes-1.1.0-py3-none-any.whl\n    Requirement already satisfied: pandas>=1.0.3 in /usr/local/lib/python3.6/dist-packages (from plotnine) (1.0.3)\n    Requirement already satisfied: future>=0.15.2 in /usr/local/lib/python3.6/dist-packages (from autograd->pennylane) (0.17.1)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx->pennylane) (4.4.1)\n    Requirement already satisfied: antlr4-python3-runtime==4.7.2 in /usr/local/lib/python3.6/dist-packages (from quantum-blackbird>=0.2.3->StrawberryFields) (4.7.2)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.22.0->StrawberryFields) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests>=2.22.0->StrawberryFields) (2019.9.11)\n    Requirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.22.0->StrawberryFields) (2.8)\n    Requirement already satisfied: dask[delayed] in /usr/local/lib/python3.6/dist-packages (from thewalrus>=0.12->StrawberryFields) (2.18.1)\n    Requirement already satisfied: llvmlite<=0.33.0.dev0,>=0.31.0.dev0 in /usr/local/lib/python3.6/dist-packages (from numba->StrawberryFields) (0.32.1)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from numba->StrawberryFields) (41.6.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy>=1.5->StrawberryFields) (1.1.0)\n    Requirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (0.8.1)\n    Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (1.25.0)\n    Requirement already satisfied: tensorflow-estimator<2.3.0,>=2.2.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (2.2.0)\n    Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (1.1.0)\n    Requirement already satisfied: keras-preprocessing>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (1.1.2)\n    Requirement already satisfied: google-pasta>=0.1.8 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (0.1.8)\n    Requirement already satisfied: astunparse==1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (1.6.3)\n    Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (1.11.2)\n    Requirement already satisfied: h5py<2.11.0,>=2.10.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (2.10.0)\n    Requirement already satisfied: gast==0.3.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (0.3.3)\n    Requirement already satisfied: tensorboard<2.3.0,>=2.2.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (2.2.2)\n    Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (3.1.0)\n    Requirement already satisfied: wheel>=0.26; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.3,>=2.2.0->tensorflow_text) (0.33.6)\n    Collecting palettable\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/ca/46/5198aa24e61bb7eef28d06cb69e56bfa1942f4b6807d95a0b5ce361fe09b/palettable-3.3.0-py2.py3-none-any.whl (111kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 112kB 23.6MB/s eta 0:00:01\n    \u001b[?25hRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=3.1.1->plotnine) (1.2.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=3.1.1->plotnine) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=3.1.1->plotnine) (0.10.0)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=1.0.3->plotnine) (2019.3)\n    Requirement already satisfied: pyyaml in /usr/local/lib/python3.6/dist-packages (from dask[delayed]->thewalrus>=0.12->StrawberryFields) (5.1.2)\n    Requirement already satisfied: toolz>=0.8.2; extra == \"delayed\" in /usr/local/lib/python3.6/dist-packages (from dask[delayed]->thewalrus>=0.12->StrawberryFields) (0.10.0)\n    Requirement already satisfied: cloudpickle>=0.2.2; extra == \"delayed\" in /opt/tensorflow/horovod-source/.eggs/cloudpickle-1.2.2-py3.6.egg (from dask[delayed]->thewalrus>=0.12->StrawberryFields) (1.2.2)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (0.4.1)\n    Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (1.7.0)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (1.6.0.post3)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (3.1.1)\n    Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (0.16.0)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (1.3.0)\n    Requirement already satisfied: cachetools<3.2,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (3.1.1)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (0.2.7)\n    Requirement already satisfied: rsa<4.1,>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (4.0)\n    Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (3.1.0)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.6/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow<2.3,>=2.2.0->tensorflow_text) (0.4.7)\n    Installing collected packages: palettable, mizani, patsy, statsmodels, descartes, plotnine\n    Successfully installed descartes-1.1.0 mizani-0.7.1 palettable-3.3.0 patsy-0.5.1 plotnine-0.7.0 statsmodels-0.11.1\n    \u001b[33mWARNING: You are using pip version 19.3.1; however, version 20.1.1 is available.\n    You should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\n\n\n\n```python\n!wget https://github.com/PyThaiNLP/truevoice-intent/archive/master.zip; unzip master.zip; cd truevoice-intent-master; unzip mari-intent.zip; cp *.* ../;\n```\n\n    --2020-06-11 03:12:29--  https://github.com/PyThaiNLP/truevoice-intent/archive/master.zip\n    Resolving github.com (github.com)... 52.74.223.119\n    Connecting to github.com (github.com)|52.74.223.119|:443... connected.\n    HTTP request sent, awaiting response... 302 Found\n    Location: https://codeload.github.com/PyThaiNLP/truevoice-intent/zip/master [following]\n    --2020-06-11 03:12:30--  https://codeload.github.com/PyThaiNLP/truevoice-intent/zip/master\n    Resolving codeload.github.com (codeload.github.com)... 13.229.189.0\n    Connecting to codeload.github.com (codeload.github.com)|13.229.189.0|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: unspecified [application/zip]\n    Saving to: \u2018master.zip\u2019\n    \n    master.zip              [    <=>             ]   1.29M  2.07MB/s    in 0.6s    \n    \n    2020-06-11 03:12:31 (2.07 MB/s) - \u2018master.zip\u2019 saved [1350596]\n    \n    Archive:  master.zip\n    7ce601a547a4bac938b3bb0640a6036f7b89266c\n       creating: truevoice-intent-master/\n      inflating: truevoice-intent-master/.gitignore  \n      inflating: truevoice-intent-master/LICENSE  \n      inflating: truevoice-intent-master/README.md  \n      inflating: truevoice-intent-master/class_features.py  \n      inflating: truevoice-intent-master/classification.ipynb  \n      inflating: truevoice-intent-master/exploration.ipynb  \n     extracting: truevoice-intent-master/mari-intent.zip  \n      inflating: truevoice-intent-master/remove-dup-split.ipynb  \n      inflating: truevoice-intent-master/thsarabunnew-webfont.ttf  \n    Archive:  mari-intent.zip\n      inflating: mari-train-balanced.csv  \n      inflating: mari-test-balanced.csv  \n\n\n\n```python\n!mkdir ft_data\n!mkdir truevoice_data\n```\n\n\n```python\n!wget https://github.com/rdisipio/qnlp/raw/master/models.py\n```\n\n    --2020-06-11 03:12:33--  https://github.com/rdisipio/qnlp/raw/master/models.py\n    Resolving github.com (github.com)... 52.74.223.119\n    Connecting to github.com (github.com)|52.74.223.119|:443... connected.\n    HTTP request sent, awaiting response... 302 Found\n    Location: https://raw.githubusercontent.com/rdisipio/qnlp/master/models.py [following]\n    --2020-06-11 03:12:34--  https://raw.githubusercontent.com/rdisipio/qnlp/master/models.py\n    Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 151.101.8.133\n    Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|151.101.8.133|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 1212 (1.2K) [text/plain]\n    Saving to: \u2018models.py\u2019\n    \n    models.py           100%[===================>]   1.18K  --.-KB/s    in 0s      \n    \n    2020-06-11 03:12:34 (71.3 MB/s) - \u2018models.py\u2019 saved [1212/1212]\n    \n\n\n\n```python\n!wget https://github.com/rdisipio/qnlp/raw/master/models_quantum.py\n```\n\n    --2020-06-11 03:12:35--  https://github.com/rdisipio/qnlp/raw/master/models_quantum.py\n    Resolving github.com (github.com)... 52.74.223.119\n    Connecting to github.com (github.com)|52.74.223.119|:443... connected.\n    HTTP request sent, awaiting response... 302 Found\n    Location: https://raw.githubusercontent.com/rdisipio/qnlp/master/models_quantum.py [following]\n    --2020-06-11 03:12:35--  https://raw.githubusercontent.com/rdisipio/qnlp/master/models_quantum.py\n    Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 151.101.8.133\n    Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|151.101.8.133|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 8498 (8.3K) [text/plain]\n    Saving to: \u2018models_quantum.py\u2019\n    \n    models_quantum.py   100%[===================>]   8.30K  --.-KB/s    in 0s      \n    \n    2020-06-11 03:12:36 (41.7 MB/s) - \u2018models_quantum.py\u2019 saved [8498/8498]\n    \n\n\n\n```python\nimport pandas as pd\nimport numpy as np\nfrom pythainlp import word_tokenize\nfrom tqdm import tqdm_notebook\nfrom collections import Counter\nimport re\nfrom sklearn.metrics import f1_score,precision_score,recall_score\n\n#viz\nfrom plotnine import *\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndef replace_newline(t):\n    return re.sub('[\\n]{1,}', ' ', t)\n\nft_data = 'ft_data/'\n\ny = 'destination'\nnb_class = 7\n```\n\n\n```python\nimport string\nimport emoji\ndef replace_url(text):\n    URL_PATTERN = r\"\"\"(?i)\\b((?:https?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\\-]+[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)/)(?:[^\\s()<>{}\\[\\]]+|\\([^\\s()]*?\\([^\\s()]+\\)[^\\s()]*?\\)|\\([^\\s]+?\\))+(?:\\([^\\s()]*?\\([^\\s()]+\\)[^\\s()]*?\\)|\\([^\\s]+?\\)|[^\\s`!()\\[\\]{};:'\".,<>?\u00ab\u00bb\u201c\u201d\u2018\u2019])|(?:(?<!@)[a-z0-9]+(?:[.\\-][a-z0-9]+)*[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)\\b/?(?!@)))\"\"\"\n    return re.sub(URL_PATTERN, 'xxurl', text)\n\ndef replace_rep(text):\n    def _replace_rep(m):\n        c,cc = m.groups()\n        return f'{c}xxrep'\n    re_rep = re.compile(r'(\\S)(\\1{2,})')\n    return re_rep.sub(_replace_rep, text)\n\ndef ungroup_emoji(toks):\n    res = []\n    for tok in toks:\n        if emoji.emoji_count(tok) == len(tok):\n            for char in tok:\n                res.append(char)\n        else:\n            res.append(tok)\n    return res\n\ndef process_text(text):\n    #pre rules\n    res = text.lower().strip()\n    res = replace_url(res)\n    res = replace_rep(res)\n    \n    #tokenize\n    res = [word for word in res.split('|') if word and not re.search(pattern=r\"\\s+\", string=word)]\n    \n    #post rules\n    res = ungroup_emoji(res)\n    \n    return res\n```\n\n#Train-validation-test Split\n\nWe perform 85/15 train-validation split in addition to the test split by TrueVoice.\n\n\n```python\nfrom sklearn.model_selection import train_test_split\nall_df = pd.read_csv(f'mari-train-balanced.csv')\nall_df['destination'] = all_df.destination.map(lambda x: x.replace(' ','_'))\n#train_df, valid_df = train_test_split(all_df, test_size=0.15, random_state=1412)\ntrain_df = all_df.reset_index(drop=True)\n#valid_df = valid_df.reset_index(drop=True)\ntest_df = pd.read_csv(f'mari-test-balanced.csv')\ntest_df['destination'] = test_df.destination.map(lambda x: x.replace(' ','_'))\nprint(train_df.shape, test_df.shape)\n```\n\n    (10303, 5) (2607, 5)\n\n\n\n```python\n#test set prevalence\ntest_df['destination'].value_counts() / test_df.shape[0]\n```\n\n\n\n\n    billing_and_payment      0.376678\n    promotions               0.220560\n    other_queries            0.176064\n    internet                 0.154200\n    international_dialing    0.034522\n    true_money               0.019946\n    lost_and_stolen          0.018028\n    Name: destination, dtype: float64\n\n\n\n\n```python\n#!pip install pennylane pennylane-sf \n\nimport pennylane\npennylane.device(\"strawberryfields.gaussian\", wires=2) # \u0e16\u0e49\u0e32 error \u0e43\u0e2b\u0e49 restart runtime\n```\n\n\n\n\n    <StrawberryFieldsGaussian device (wires=2, shots=1000) at 0x7fdec808beb8>\n\n\n\n\n```python\nimport tensorflow_hub as hub\nimport tensorflow_text\nimport tensorflow as tf #tensorflow 2.1.0\nfrom tensorflow.keras.callbacks import EarlyStopping\n\nfrom models_quantum import make_model_quantum\nenc = hub.load('https://tfhub.dev/google/universal-sentence-encoder-multilingual/3')\n```\n\n\n```python\ntf.keras.backend.set_floatx('float64') \n```\n\n\n```python\ntrain_df.shape, test_df.shape\n```\n\n\n\n\n    ((10303, 5), (2607, 5))\n\n\n\n\n```python\n\ndef embed_text(X_txt):\n    print(\"Embedding input text...\")\n\n    X = np.array([np.array(x) for x in enc(X_txt)])\n\n    return X\n\n```\n\n\n```python\nX_train = embed_text(train_df.texts)\n```\n\n    Embedding input text...\n\n\n\n```python\nX_test = embed_text(test_df.texts)\n```\n\n    Embedding input text...\n\n\n\n```python\nembedding_dim =X_train.shape[-1]\n```\n\n\n```python\nembedding_dim\n```\n\n\n\n\n    512\n\n\n\n\n```python\nindex = {j:i for i,j in enumerate(list(set(train_df[y].values)))}\n```\n\n\n```python\nindex\n```\n\n\n\n\n    {'true_money': 0,\n     'promotions': 1,\n     'other_queries': 2,\n     'internet': 3,\n     'lost_and_stolen': 4,\n     'billing_and_payment': 5,\n     'international_dialing': 6}\n\n\n\n\n```python\nfrom tensorflow.keras.utils import to_categorical\n```\n\n\n```python\ny_train = [index[i] for i in train_df[y].values]\n```\n\n\n```python\ny_train = to_categorical(y_train)\n```\n\n\n```python\ny_test  = [index[i] for i in test_df[y].values]\n```\n\n\n```python\ny_test = to_categorical(y_test)\n```\n\n\n```python\nN_EPOCHS = 20\nBATCH_SIZE = 32\nn_categories = 7\n```\n\n\n```python\nembedding_dim = X_train.shape[-1]\n```\n\n\n```python\nimport pennylane as qml\nqml.about()\n```\n\n    Name: PennyLane\n    Version: 0.9.0\n    Summary: PennyLane is a Python quantum machine learning library by Xanadu Inc.\n    Home-page: https://github.com/XanaduAI/pennylane\n    Author: None\n    Author-email: None\n    License: Apache License 2.0\n    Location: /usr/local/lib/python3.6/dist-packages\n    Requires: semantic-version, scipy, appdirs, autograd, networkx, numpy, toml\n    Required-by: PennyLane-SF\n    Platform info:           Linux-4.15.0-72-generic-x86_64-with-Ubuntu-18.04-bionic\n    Python version:          3.6.8\n    Numpy version:           1.17.4\n    Scipy version:           1.3.1\n    Installed devices:\n    - default.gaussian (PennyLane-0.9.0)\n    - default.qubit (PennyLane-0.9.0)\n    - default.tensor (PennyLane-0.9.0)\n    - default.tensor.tf (PennyLane-0.9.0)\n    - strawberryfields.fock (PennyLane-SF-0.9.0)\n    - strawberryfields.gaussian (PennyLane-SF-0.9.0)\n\n\n\n```python\nmodel = make_model_quantum(n_categories=n_categories,  n_qubits=4, n_layers=1, embedding_dim=embedding_dim)\n```\n\n\n```python\nmodel.summary()\n```\n\n    Model: \"QuantumPreprintClassifier\"\n    _________________________________________________________________\n    Layer (type)                 Output Shape              Param #   \n    =================================================================\n    text_in (InputLayer)         [(None, 512)]             0         \n    _________________________________________________________________\n    dense_4 (Dense)              (None, 4)                 2052      \n    _________________________________________________________________\n    variational_quantum_circuit_ (None, 4)                 12        \n    _________________________________________________________________\n    dense_7 (Dense)              (None, 7)                 35        \n    =================================================================\n    Total params: 2,099\n    Trainable params: 2,099\n    Non-trainable params: 0\n    _________________________________________________________________\n\n\n\n```python\noptimizer = tf.keras.optimizers.Adam(learning_rate=0.01)\n```\n\n\n```python\nmodel.compile(optimizer, loss='categorical_crossentropy')\n```\n\n\n```python\nearly_stopping_callback = EarlyStopping(monitor='val_loss', patience=3, min_delta=0.01,restore_best_weights=True)\n```\n\n\n```python\nfrom matplotlib import pyplot as plt\nfrom IPython.display import clear_output\nimport numpy as np\n```\n\n\n```python\nclass PlotLosses(tf.keras.callbacks.Callback): # code from https://gist.github.com/stared/dfb4dfaf6d9a8501cd1cc8b8cb806d2e\n    def on_train_begin(self, logs={}):\n        self.i = 0\n        self.x = []\n        self.losses = []\n        self.val_losses = []\n        \n        self.fig = plt.figure()\n        \n        self.logs = []\n\n    def on_epoch_end(self, epoch, logs={}):\n        \n        self.logs.append(logs)\n        self.x.append(self.i)\n        self.losses.append(logs.get('loss'))\n        self.val_losses.append(logs.get('val_loss'))\n        self.i += 1\n        \n        clear_output(wait=True)\n        plt.plot(self.x, self.losses, label=\"loss\")\n        plt.plot(self.x, self.val_losses, label=\"val_loss\")\n        plt.legend()\n        plt.show();\n        \nplot_losses = PlotLosses()\n```\n\n\n```python\ncallbacks = [early_stopping_callback,plot_losses]\n```\n\n\n```python\nhistory = model.fit(X_train, y_train,epochs=N_EPOCHS, batch_size=BATCH_SIZE,validation_split=0.15,callbacks =callbacks)\n```\n\n\n```python\ndir(model)\n```\n\n\n\n\n    ['_TF_MODULE_IGNORED_PROPERTIES',\n     '__call__',\n     '__class__',\n     '__delattr__',\n     '__dict__',\n     '__dir__',\n     '__doc__',\n     '__eq__',\n     '__format__',\n     '__ge__',\n     '__getattribute__',\n     '__getstate__',\n     '__gt__',\n     '__hash__',\n     '__init__',\n     '__init_subclass__',\n     '__le__',\n     '__lt__',\n     '__module__',\n     '__ne__',\n     '__new__',\n     '__reduce__',\n     '__reduce_ex__',\n     '__repr__',\n     '__setattr__',\n     '__setstate__',\n     '__sizeof__',\n     '__str__',\n     '__subclasshook__',\n     '__weakref__',\n     '_activity_regularizer',\n     '_add_inbound_node',\n     '_add_trackable',\n     '_add_variable_with_custom_getter',\n     '_assert_compile_was_called',\n     '_assert_weights_created',\n     '_attribute_sentinel',\n     '_auto_track_sub_layers',\n     '_autocast',\n     '_base_init',\n     '_build_input_shape',\n     '_call_accepts_kwargs',\n     '_call_arg_was_passed',\n     '_call_fn_args',\n     '_call_full_argspec',\n     '_callable_losses',\n     '_check_call_args',\n     '_checkpoint_dependencies',\n     '_clear_losses',\n     '_collect_input_masks',\n     '_compile_was_called',\n     '_compiled_trainable_state',\n     '_compute_dtype',\n     '_compute_output_and_mask_jointly',\n     '_compute_tensor_usage_count',\n     '_conform_to_reference_input',\n     '_dedup_weights',\n     '_deferred_dependencies',\n     '_distribution_strategy',\n     '_dtype',\n     '_dtype_defaulted_to_floatx',\n     '_dtype_policy',\n     '_dynamic',\n     '_eager_add_metric',\n     '_eager_losses',\n     '_enable_dict_to_input_mapping',\n     '_expects_mask_arg',\n     '_expects_training_arg',\n     '_feed_input_names',\n     '_feed_input_shapes',\n     '_feed_inputs',\n     '_flatten',\n     '_flatten_to_reference_inputs',\n     '_gather_children_attribute',\n     '_gather_layers',\n     '_gather_saveables_for_checkpoint',\n     '_gather_unique_layers',\n     '_get_call_arg_value',\n     '_get_callback_model',\n     '_get_compile_args',\n     '_get_distribution_strategy',\n     '_get_existing_metric',\n     '_get_node_attribute_at_index',\n     '_get_optimizer',\n     '_get_save_spec',\n     '_get_trainable_state',\n     '_graph',\n     '_graph_network_add_loss',\n     '_graph_network_add_metric',\n     '_handle_activity_regularization',\n     '_handle_deferred_dependencies',\n     '_handle_deferred_layer_dependencies',\n     '_handle_weight_regularization',\n     '_in_multi_worker_mode',\n     '_inbound_nodes',\n     '_init_call_fn_args',\n     '_init_graph_network',\n     '_init_set_name',\n     '_init_subclassed_network',\n     '_initial_weights',\n     '_input_coordinates',\n     '_input_layers',\n     '_input_spec',\n     '_insert_layers',\n     '_is_compiled',\n     '_is_graph_network',\n     '_is_layer',\n     '_keras_api_names',\n     '_keras_api_names_v1',\n     '_layer_call_argspecs',\n     '_layer_checkpoint_dependencies',\n     '_layers',\n     '_list_extra_dependencies_for_serialization',\n     '_list_functions_for_serialization',\n     '_lookup_dependency',\n     '_losses',\n     '_maybe_build',\n     '_maybe_cast_inputs',\n     '_maybe_create_attribute',\n     '_maybe_initialize_trackable',\n     '_maybe_load_initial_epoch_from_ckpt',\n     '_metrics',\n     '_metrics_lock',\n     '_name',\n     '_name_based_attribute_restore',\n     '_name_based_restores',\n     '_name_scope',\n     '_nested_inputs',\n     '_nested_outputs',\n     '_network_nodes',\n     '_no_dependency',\n     '_nodes_by_depth',\n     '_non_trainable_weights',\n     '_obj_reference_counts',\n     '_obj_reference_counts_dict',\n     '_object_identifier',\n     '_outbound_nodes',\n     '_output_coordinates',\n     '_output_layers',\n     '_output_mask_cache',\n     '_output_shape_cache',\n     '_output_tensor_cache',\n     '_preload_simple_restoration',\n     '_reset_compile_cache',\n     '_restore_from_checkpoint_position',\n     '_reuse',\n     '_run_eagerly',\n     '_run_internal_graph',\n     '_saved_model_inputs_spec',\n     '_scope',\n     '_self_name_based_restores',\n     '_self_setattr_tracking',\n     '_self_unconditional_checkpoint_dependencies',\n     '_self_unconditional_deferred_dependencies',\n     '_self_unconditional_dependency_names',\n     '_self_update_uid',\n     '_set_connectivity_metadata_',\n     '_set_dtype_policy',\n     '_set_inputs',\n     '_set_mask_metadata',\n     '_set_output_names',\n     '_set_save_spec',\n     '_set_trainable_state',\n     '_setattr_tracking',\n     '_should_compute_mask',\n     '_should_eval',\n     '_single_restoration_from_checkpoint_position',\n     '_stateful',\n     '_supports_ragged_inputs',\n     '_symbolic_add_metric',\n     '_symbolic_call',\n     '_tensor_usage_count',\n     '_tf_api_names',\n     '_tf_api_names_v1',\n     '_thread_local',\n     '_track_trackable',\n     '_trackable_saved_model_saver',\n     '_trackable_saver',\n     '_tracking_metadata',\n     '_trainable',\n     '_trainable_weights',\n     '_training_state',\n     '_unconditional_checkpoint_dependencies',\n     '_unconditional_dependency_names',\n     '_undeduplicated_weights',\n     '_update_uid',\n     '_updated_config',\n     '_updates',\n     '_validate_compile',\n     '_validate_graph_inputs_and_outputs',\n     '_warn_about_input_casting',\n     'activity_regularizer',\n     'add_loss',\n     'add_metric',\n     'add_update',\n     'add_variable',\n     'add_weight',\n     'apply',\n     'build',\n     'built',\n     'call',\n     'compile',\n     'compiled_loss',\n     'compiled_metrics',\n     'compute_mask',\n     'compute_output_shape',\n     'compute_output_signature',\n     'count_params',\n     'distribute_strategy',\n     'dtype',\n     'dynamic',\n     'evaluate',\n     'evaluate_generator',\n     'fit',\n     'fit_generator',\n     'from_config',\n     'get_config',\n     'get_input_at',\n     'get_input_mask_at',\n     'get_input_shape_at',\n     'get_layer',\n     'get_losses_for',\n     'get_output_at',\n     'get_output_mask_at',\n     'get_output_shape_at',\n     'get_updates_for',\n     'get_weights',\n     'history',\n     'inbound_nodes',\n     'input',\n     'input_mask',\n     'input_names',\n     'input_shape',\n     'input_spec',\n     'inputs',\n     'layers',\n     'load_weights',\n     'loss',\n     'losses',\n     'make_predict_function',\n     'make_test_function',\n     'make_train_function',\n     'metrics',\n     'metrics_names',\n     'name',\n     'name_scope',\n     'non_trainable_variables',\n     'non_trainable_weights',\n     'optimizer',\n     'outbound_nodes',\n     'output',\n     'output_mask',\n     'output_names',\n     'output_shape',\n     'outputs',\n     'predict',\n     'predict_function',\n     'predict_generator',\n     'predict_on_batch',\n     'predict_step',\n     'reset_metrics',\n     'reset_states',\n     'run_eagerly',\n     'save',\n     'save_weights',\n     'set_weights',\n     'state_updates',\n     'stateful',\n     'stop_training',\n     'submodules',\n     'summary',\n     'supports_masking',\n     'test_function',\n     'test_on_batch',\n     'test_step',\n     'to_json',\n     'to_yaml',\n     'train_function',\n     'train_on_batch',\n     'train_step',\n     'trainable',\n     'trainable_variables',\n     'trainable_weights',\n     'updates',\n     'variables',\n     'weights',\n     'with_name_scope']\n\n\n\n\n```python\nmodel.predict(X_test)\n```\n\n\n\n\n    array([[1.00877702e-02, 2.80440106e-01, 1.22222863e-01, ...,\n            1.36565214e-03, 5.59027094e-01, 1.03205016e-03],\n           [2.23888947e-03, 7.68675006e-01, 4.06706911e-02, ...,\n            2.29768297e-04, 1.65777818e-01, 4.97024380e-04],\n           [8.44313633e-03, 3.29500807e-04, 2.59435960e-02, ...,\n            2.01736112e-03, 9.63111778e-01, 3.68307758e-05],\n           ...,\n           [1.82711095e-02, 1.56434325e-01, 2.59251361e-01, ...,\n            1.92394318e-03, 1.67550606e-01, 2.42491273e-03],\n           [6.87279117e-03, 3.57861570e-01, 8.45242885e-02, ...,\n            1.22508594e-03, 5.40770469e-01, 1.13316320e-03],\n           [5.10181039e-03, 2.02961969e-02, 7.27803251e-02, ...,\n            1.83616398e-04, 1.84993988e-02, 2.56527250e-04]])\n\n\n\n\n```python\ntest_score = model.evaluate(X_test, y_test, verbose=2)\n```\n\n    82/82 - 34s - loss: 0.7899\n\n\n\n```python\nprint(test_score)\n```\n\n    0.789912723104845\n\n\n\n```python\nt=model.predict(X_test)\n```\n\n\n```python\nval2tag = {i:j for i,j in zip(index.values(),index.keys())}\n```\n\n\n```python\ny_true = list(test_df[y].values)\n```\n\n\n```python\ny_pred = [val2tag[list(i).index(i.max())] for i in t]\n```\n\n\n```python\nfrom sklearn.metrics import classification_report\nprint(classification_report(y_true, y_pred))\n```\n\n                           precision    recall  f1-score   support\n    \n      billing_and_payment       0.80      0.83      0.82       982\n    international_dialing       0.70      0.77      0.73        90\n                 internet       0.70      0.67      0.68       402\n          lost_and_stolen       0.00      0.00      0.00        47\n            other_queries       0.61      0.68      0.64       459\n               promotions       0.77      0.81      0.79       575\n               true_money       0.00      0.00      0.00        52\n    \n                 accuracy                           0.74      2607\n                macro avg       0.51      0.54      0.52      2607\n             weighted avg       0.71      0.74      0.72      2607\n    \n\n\n    /usr/local/lib/python3.6/dist-packages/sklearn/metrics/_classification.py:1272: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "3ba7927c10ca20d6d39fa8e898c4ecb2cbb4c708", "size": 69012, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "quantum-nlp/text-classification/what_the_quantum-n1-Copy1.ipynb", "max_stars_repo_name": "wannaphong/open-thai-nlp-document", "max_stars_repo_head_hexsha": "bc231f7d3ec1e3d297b18cab7e9cd8d0bb4f4865", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-06-15T03:48:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T17:38:23.000Z", "max_issues_repo_path": "quantum-nlp/text-classification/what_the_quantum-n1-Copy1.ipynb", "max_issues_repo_name": "wannaphongcom/open-thai-nlp-document", "max_issues_repo_head_hexsha": "bc231f7d3ec1e3d297b18cab7e9cd8d0bb4f4865", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quantum-nlp/text-classification/what_the_quantum-n1-Copy1.ipynb", "max_forks_repo_name": "wannaphongcom/open-thai-nlp-document", "max_forks_repo_head_hexsha": "bc231f7d3ec1e3d297b18cab7e9cd8d0bb4f4865", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-06-15T03:48:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-25T06:19:19.000Z", "avg_line_length": 44.9296875, "max_line_length": 14936, "alphanum_fraction": 0.6507563902, "converted": true, "num_tokens": 11184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245392906821, "lm_q2_score": 0.0574932828376918, "lm_q1q2_score": 0.01563958377623199}}
{"text": "```python\nimport sys\nimport os\nimport copy\nfrom glob import glob\nfrom collections import OrderedDict\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom astropy.table import Table, Column\nfrom astropy import table\nfrom astropy.time import Time\nimport astropy.units as u\nimport astropy.constants as aconst\nfrom astropy import stats\nfrom astropy.io.ascii import latex\nfrom astropy.coordinates import SkyCoord\n\n# Setting and imports to enable the display of plots and images in the notebook itself\n%matplotlib inline\nimport IPython\n```\n\n\n```python\nos.environ['XUVTOP'] = '/melkor/d1/guenther/downdata/CHIANTI/'\n\nimport chianti.core as ch\n```\n\n     using cli\n     using CLI for selections\n\n\n\n```python\ndatadir = '/melkor/d1/guenther/downdata/Chandra/RWaur/'\ndatadirXMM = '/melkor/d1/guenther/downdata/XMM/RWAur/'\nfigout = '/melkor/d1/guenther/Dropbox/my_articles/RWAur/'\n```\n\n\n```python\nobsids = [14539, 17644, 17764, 19980]\n```\n% using aastex version 6.1\n\\documentclass[twocolumn]{aastex61}\n\n%% \n%% where the enlargement options are:\n%%\n%%  twocolumn   : two text columns, 10 point font, single spaced article.\n%%                This is the most compact and represent the final published\n%%                derived PDF copy of the accepted manuscript from the publisher\n%%  manuscript  : one text column, 12 point font, double spaced article.\n%%  preprint    : one text column, 12 point font, single spaced article.  \n%%  preprint2   : two text columns, 12 point font, single spaced article.\n%%  modern      : a stylish, single text column, 12 point font, article with\n%% \t\t  wider left and right margins. This uses the Daniel\n%% \t\t  Foreman-Mackey and David Hogg design.\n%%\n%% Note that you can submit to the AAS Journals in any of these 6 styles.\n%%\n%% There are other optional arguments one can envoke to allow other stylistic\n%% actions. The available options are:\n%%\n%%  astrosymb    : Loads Astrosymb font and define \\astrocommands. \n%%  tighten      : Makes baselineskip slightly smaller, only works with \n%%                 the twocolumn substyle.\n%%  times        : uses times font instead of the default\n%%  linenumbers  : turn on lineno package.\n%%  trackchanges : required to see the revision mark up and print its output\n%%  longauthor   : Do not use the more compressed footnote style (default) for \n%%                 the author/collaboration/affiliations. Instead print all\n%%                 affiliation information after each name. Creates a much\n%%                 long author list but may be desirable for short author papers\n\\usepackage{multirow}\n%% Reintroduced the \\received and \\accepted commands from AASTeX v5.2\n\\received{...}\n\\revised{...}\n\\accepted{...}\n%% Command to document which AAS Journal the manuscript was submitted to.\n%% Adds \"Submitted to \" the argument.\n%\\submitjournal{ApJ}\n\\begin{document}\n\n\\title{Optical dimming of RW Aur associated with an iron rich corona and exceptionally high absorbing column density}\n\n\\correspondingauthor{Hans Moritz G\\\"unther}\n\\email{hgunther@mit.edu}\n\n\\author[0000-0003-4243-2840]{Hans Moritz G\\\"unther}\n\\affil{MIT, Kavli Institute for Astrophysics and Space Research, 77 Massachusetts Avenue, Cambridge, MA 02139, USA}\n\n\\author{T. Birnstiel}\n\\affil{University Observatory, Faculty of Physics, Ludwig-Maximilians-Universit\\\"at M\\\"unchen, Scheinerstr. 1,\n81679 Munich, Germany}\n\n\\author[0000-0002-3860-6230]{D. P. Huenemoerder}\n\\affil{MIT, Kavli Institute for Astrophysics and Space Research, 77 Massachusetts Avenue, Cambridge, MA 02139, USA}\n\n\\author{D. A. Principe}\n\\affil{MIT, Kavli Institute for Astrophysics and Space Research, 77 Massachusetts Avenue, Cambridge, MA 02139, USA}\n\n\\author{P. C. Schneider}\n\\affil{Hamburger Sternwarte, Universit\\\"at Hamburg, Gojenbergsweg 112, 21029, Hamburg, Germany}\n\n\\author[0000-0002-0826-9261]{S. J. Wolk}\n\\affil{Harvard-Smithsonian Center for Astrophysics, 60 Garden Street, Cambridge, MA 02138, USA}\n\n\\author{Franky Dubois}\n\\affil{Astrolab IRIS, Ieper, Belgium}\n\\affil{Vereniging voor Sterrenkunde, Werkgroep Veranderlijke Sterren, Belgium}\n\n\\author{Ludwig Logie}\n\\affil{Astrolab IRIS, Ieper, Belgium}\n\\affil{Vereniging voor Sterrenkunde, Werkgroep Veranderlijke Sterren, Belgium}\n\n\\author{Steve Rau}\n \\affil{Astrolab IRIS, Ieper, Belgium}\n\\affil{Vereniging voor Sterrenkunde, Werkgroep Veranderlijke Sterren, Belgium}\n\n\\author{Sigfried Vanaverbeke}\n\\affil{Astrolab IRIS, Ieper, Belgium}\n\\affil{Vereniging voor Sterrenkunde, Werkgroep Veranderlijke Sterren, Belgium}\n\\affil{Center for Plasma Astrophysics, University of Leuven, Belgium}\n\n\n\\begin{abstract}\nRW~Aur is a binary system composed of two young, low-mass stars. The primary, RW~Aur~A, has undergone visual dimming events ($\\Delta V =2-3$~mag) in 2011, 2014-16, and 2017-2018. Visual and IR observations indicate a gray absorber that moved into the line-of-sight. This dimming is also associated with changes in the outflow. In 2017, when the optical brightness was almost 2~mag below the long-term average we triggered a \\emph{Chandra} observation to measure the absorbing column density $N_\\mathrm{H}$ and to constrain dust properties and the gas-to-dust ratio of the absorber. In 2017, the X-ray spectrum is more absorbed than it was in the optically bright state ($N_\\mathrm{H} = (4\\pm 1) \\times 10^{23}\\;\\mathrm{cm}^{-2}$) and shows significantly more hot plasma than in X-ray observations taken before. Also, a new emission feature at $6.63\\pm0.02$~keV (statistic) $\\pm0.02$~keV (systematic) appeared indicating an Fe abundance an order of magnitude above Solar, in contrast with previous sub-Solar Fe abundance measurements.\nComparing X-ray absorbing column density $N_\\mathrm{H}$ and optical extinction $A_V$, we find that either the gas-to-dust ratio in the absorber is orders of magnitude higher than in the ISM or the absorber has undergone significant dust evolution. Given the high column density coupled with changes in the X-ray spectral shape, this absorber is probably located in the inner disk. We speculate that a break-up of planetesimals or a terrestrial planet could supply large grains causing gray absorption; some of these grains would be accreted and enrich the stellar corona with iron which could explain the inferred high abundance.\n\n\\end{abstract}\n\n%% Keywords should appear after the \\end{abstract} command. \n%% See the online documentation for the full list of available subject\n%% keywords and the rules for their use.\n\\keywords{protoplanetary disks --- stars: individual (RW Aur) --- circumstellar matter --- stars: variables: T Tauri, Herbig Ae/Be --- stars: pre-main sequence}\n\n\n## Introduction\n\n\nThe formation of stars and planetary systems from large-scale molecular clouds is a complicated process with many interacting components. After the initial collapse of the cloud, an accretion disk forms around the central proto-star.  Low mass stars ($<3\\;M_{\\odot}$) at this stage are called classical T Tauri stars (CTTS).\nTheir circumstellar disks are the sites of planet formation. Disks regulate the angular momentum of the star, and they may launch a disk wind. Typical disks contain a mass of $10^{-3}$ to $10^{-1}\\,M_\\odot$\nand disperse within a few Myrs \\citep[see review by][]{2014prpl.conf..475A}, which also sets the \ntime-scale for planet formation. During their evolution disks undergo large structural changes. In particular, grains grow to larger sizes and settle in the disk mid-plane leaving\na gas rich disk atmosphere behind \\citep[see review by][]{2015PASP..127..961A}.\n\nGas comprises the majority of the mass in a protoplanetary disk and thus \ncontrols essential transport processes within the disk such as\nangular momentum redistribution and dust grain motion.\nFor example, gas affects grain growth through the coupling of\ngas and dust dynamics \\citep{1977MNRAS.180...57W,2001ApJ...557..990T}\nas well as the thermal and chemical balance of the disk \n\\citep[e.g.][]{2009A&A...501..383W}. \nImages of T~Tauri star disks often have asymmetries or gaps \\citep{2013Sci...340.1199V,2013Natur.493..191C,2015ApJ...808L...3A,2015MNRAS.453.1768P,2016ApJ...820L..40A}. Thus, the distribution of grain sizes in the stellar environment differs significantly for different sight lines.\n\nStellar UV and X-ray emission ionize the upper layers of the disk and in particular the inner disk edge. These ions couple effectively to the star-disk magnetic field. On the disk surface, ions can be accelerated magneto-centrifugally into a disk wind, possibly dredging along dust particles from the disk. Outflows can be clumpy, presumably changing in response to the magnetic field or the stellar irradiation \\citep{2012ApJ...758..100B,2014A&A...563A..87E}. The winds remove angular momentum and allow accretion to proceed. From the inner disk edge, gas is funneled onto the star. \n% \\citet{1994ApJ...429..781S} predict that this region can also be the source of an outflow, the so-called X-wind. \n\n\n```python\n1.4*140\n```\n\n\n\n\n    196.0\n\n\n\nRecent space-based monitoring campaigns with \\emph{COROT}, \\emph{K2}, and \\emph{Spitzer} revealed many different types of variability in the lightcurves of CTTS on time scales as short as hours. Of particular interest are stars with periodic or quasi periodic dips in their lightcurve \\citep{2014AJ....148..122G,2015AJ....149..130S}. A well known star of this type is \\object{AA Tau} \\citep{1999A&A...349..619B}. The inner disk of AA~Tau is seen very close to edge-on and the best explanation is that an asymmetric feature, such as a warp caused by a planet embedded in the disk, moves through our line-of-sight periodically. In addition, AA~Tau has shown a multi-year long dimming event where the visual extinction increased by 4 magnitudes \\citep{2013A&A...557A..77B} along with an increased X-ray absorbing column density \\citep{2015A&A...584A..51S}. The duration of the event and the variable line emission originating from the upper layers of the disk indicate a position in the disk at a radius of few AU. This absorber has an ISM-like $N_\\mathrm{H}/A_V$ ratio.\n\nIn this paper we report on new observations of \\object{RW Aur} which is a binary system composed of two K-type stars with masses of 1.4 and 0.9~$M_\\sun$ and an age close to 10~Myr \\citep{1997ApJ...490..353G, 2001A&A...376..982W}. The binary components are separated by 1.4\\arcsec{} \\citep[semi-major axis 200~au, period 1000~years;][]{2017arXiv170208583C} and are located at a distance of 140~pc \\citep{2007A&A...474..653V}. In this paper we concentrate on the primary star which is one of only a few sources with an X-ray detected jet \\citep{2014ApJ...788..101S}, indicating outflows in excess of 400~km~s$^{-1}$. The disk mass around RW~Aur~A is $\\sim0.001\\;M_\\sun$ \\citep{2005ApJ...631.1134A} and the disk has an intermediate inclination with estimates varying between $45-60^\\circ$ \\citep{2006A&A...452..897C,2018arXiv180409190R} and $77^\\circ$ \\citep{2013ApJ...766...12M}, possibly because the inner disk is warped \\citep{2016MNRAS.463.4459B}.\n\nIn a well-sampled lightcurve reaching back to about 1900, RW~Aur~AB has shown long-term variability and a short dimming event, e.g.\\ a one month long dimming in December 1937, every few decades \\citep{2017AstBu..72..277B,2018arXiv180409190R}, but it has shown multiple optical dimming events since 2011. The 2011 event lasted about half a year \\citep{2013AJ....146..112R} with dimming of $\\Delta m_V=2$~mag. Another dimming event started in mid-2014 with $\\Delta m_V=3$~mag compared to its typical bright state around $m_V=11$~mag, which has been stable for decades \\citep{2013AJ....146..112R}. The stellar flux reached the bright state again in November and December of 2016 before plunging into a new dimming phase. \\citet{2017ASPC..510..356L} see indications that the egress from a dim state happens earlier in the IR than in the optical. \\citet{2016ApJ...820..139T} find that veiling, a measure of how strongly the continuum from the accretion shock contributes to the optical flux, is stronger in the 2015/16 dimming of RW~Aur than in the bright state; X-shooter data \\citep{2016A&A...596A..38F} confirm this finding. On the other hand, \\citet{2015A&A...577A..73P} infer no changes in the accretion close to the star, but see increased wind signatures. At the same time, photometry indicates that the 2015 extinction in RW Aur A is gray up to at least $K$ band  \\citep{2015A&A...584L...9S,2015IBVS.6126....1A}, while a selective (reddening) $A_V = 0.44$~mag is seen in the bright state \\citep{2015IBVS.6126....1A}.\n\n\n\\citet{2006A&A...452..897C} observed a stream of gas on the outer edge of the disk of RW~Aur~A \nand \\citet{2013AJ....146..112R} suggested the dimming event in 2011 to be caused by this stream passing the line-of-sight to RW~Aur~A. In ALMA observations \\citet{2018arXiv180409190R} confirm the detection by \\citet{2006A&A...452..897C} and identify multiple further streams.\nModeling by \\citet{2015MNRAS.449.1996D} showed that tidal interaction in the passage of its binary companion, RW~Aur~B, can cause such a stream to form.\nHowever, in the new 2016 dimming event, multiple signatures show variability arising from material close to the star instead. \\citet{2015IBVS.6143....1S} report that both increased hot dust emission and optical spectroscopic signatures indicated that there was an increase in absorption by an outflow during the dim state in 2015 \\citep{2015A&A...577A..73P,2016A&A...596A..38F,2016MNRAS.463.4459B}.\nCoupled with the fact that mass accretion is more stable during this dim state \\citep{2016ApJ...820..139T}, it appears that the recent dimming events can only be explained by phenomena close to the star.\n\nRW~Aur~AB has been observed in X-rays several times. \\citet{2010A&A...519A.113G} present unresolved \\emph{XMM-Newton} data, but \\emph{Chandra} is required to resolve the two stellar components. The first \\emph{Chandra} observation was taken in 2013 \\citep{2014ApJ...788..101S} when RW~Aur~A was in an optically  bright state. \\citet{2015A&A...584L...9S} obtained a second dataset in 2015, catching RW~Aur in an optically fainter state. Here, we report on a third dataset observed in 2017, again in an optically dim state. RW~Aur~B is also a variable X-ray source, most likely due to coronal flares.\n\nWe first describe observations and data reduction in section~\\ref{sect:obs} before we derive results in section~\\ref{sect:results}. We discuss the results in section~\\ref{sect:discussion} and go through several physical scenarios that might cause the observed signatures in section~\\ref{sect:scenarios}. We end with a short summary in section~\\ref{sect:summary}.\n\n\n```python\nfrom astropy import table\n\ndef read_lcs(obsid, source):\n    lcall = Table.read(os.path.join(datadir, '{0}_{1}_lc.fits').format(obsid, source), hdu=1)\n    lcsoft = Table.read(os.path.join(datadir, '{0}_{1}_lc_soft.fits').format(obsid, source), hdu=1)\n    lchard = Table.read(os.path.join(datadir, '{0}_{1}_lc_hard.fits').format(obsid, source), hdu=1)\n    lc = table.hstack([lcall, lcsoft, lchard], table_names=['all', 'soft', 'hard'], metadata_conflicts='silent')\n    # time columns are the same for each lightcurve, so remove dublicate entries here for simplicity\n    for c in lc.colnames:\n        if (('TIME' in c) or ('AREA' in c) or ('EXPOSURE' in c)) and ('all' in c):\n            lc.rename_column(c, c[:-4])\n            lc.remove_columns([c[:-4] + '_soft', c[:-4] + '_hard'])\n    ind  = lc['EXPOSURE'] > 0.\n    return lc[ind]\n    \nlccurves = [[ read_lcs(obsid, t) for t in ['srca', 'srcb']] for obsid in obsids]\nfor list1 in lccurves:\n    for lc in list1:\n        lc['t'] = lc['TIME'] - lc['TIME'][0]\n```\n\n\n```python\nlccurves[0][0]\n```\n\n\n\n\n&lt;Table length=17&gt;\n<table id=\"table140051100785296\" class=\"table-striped table-bordered table-condensed\">\n<thead><tr><th>TIME_BIN</th><th>TIME_MIN</th><th>TIME</th><th>TIME_MAX</th><th>COUNTS_all</th><th>STAT_ERR_all</th><th>AREA</th><th>EXPOSURE</th><th>COUNT_RATE_all</th><th>COUNT_RATE_ERR_all</th><th>BG_COUNTS_all</th><th>BG_ERR_all</th><th>BG_AREA</th><th>BG_EXPOSURE</th><th>BG_RATE_all</th><th>NORM_BG_COUNTS_all</th><th>NORM_BG_ERR_all</th><th>NET_COUNTS_all</th><th>NET_ERR_all</th><th>NET_RATE_all</th><th>ERR_RATE_all</th><th>COUNTS_soft</th><th>STAT_ERR_soft</th><th>COUNT_RATE_soft</th><th>COUNT_RATE_ERR_soft</th><th>BG_COUNTS_soft</th><th>BG_ERR_soft</th><th>BG_RATE_soft</th><th>NORM_BG_COUNTS_soft</th><th>NORM_BG_ERR_soft</th><th>NET_COUNTS_soft</th><th>NET_ERR_soft</th><th>NET_RATE_soft</th><th>ERR_RATE_soft</th><th>COUNTS_hard</th><th>STAT_ERR_hard</th><th>COUNT_RATE_hard</th><th>COUNT_RATE_ERR_hard</th><th>BG_COUNTS_hard</th><th>BG_ERR_hard</th><th>BG_RATE_hard</th><th>NORM_BG_COUNTS_hard</th><th>NORM_BG_ERR_hard</th><th>NET_COUNTS_hard</th><th>NET_ERR_hard</th><th>NET_RATE_hard</th><th>ERR_RATE_hard</th><th>t</th></tr></thead>\n<thead><tr><th>channel</th><th>s</th><th>s</th><th>s</th><th>ct</th><th>ct</th><th>pix2</th><th>s</th><th>ct / s</th><th>ct / s</th><th>ct</th><th>ct</th><th>pix2</th><th>s</th><th>ct / s</th><th>ct</th><th>ct</th><th>ct</th><th>ct</th><th>ct / s</th><th>ct / s</th><th>ct</th><th>ct</th><th>ct / s</th><th>ct / s</th><th>ct</th><th>ct</th><th>ct / s</th><th>ct</th><th>ct</th><th>ct</th><th>ct</th><th>ct / s</th><th>ct / s</th><th>ct</th><th>ct</th><th>ct / s</th><th>ct / s</th><th>ct</th><th>ct</th><th>ct / s</th><th>ct</th><th>ct</th><th>ct</th><th>ct</th><th>ct / s</th><th>ct / s</th><th>s</th></tr></thead>\n<thead><tr><th>int32</th><th>float64</th><th>float64</th><th>float64</th><th>int32</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>int32</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>int32</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th></tr></thead>\n<tr><td>1</td><td>474340400.855</td><td>474342200.855</td><td>474344000.855</td><td>46</td><td>6.78232998313</td><td>3.78448847324</td><td>2799.74608251</td><td>0.0164300613857</td><td>0.00242248039045</td><td>7.0</td><td>2.64575131106</td><td>25.9567100265</td><td>2799.74608251</td><td>0.0025002267326</td><td>1.02060004082</td><td>0.385750556583</td><td>44.9793999592</td><td>6.79329106486</td><td>0.0160655283135</td><td>0.00242639541753</td><td>27</td><td>5.19615242271</td><td>0.0096437316829</td><td>0.00185593702771</td><td>1.0</td><td>1.0</td><td>0.000357175247515</td><td>0.145800005832</td><td>0.145800005832</td><td>26.8541999942</td><td>5.19819753777</td><td>0.00959165552973</td><td>0.00185666749219</td><td>19</td><td>4.35889894354</td><td>0.00678632970278</td><td>0.00155689080905</td><td>6.0</td><td>2.44948974278</td><td>0.00214305148509</td><td>0.874800034992</td><td>0.357135618783</td><td>18.125199965</td><td>4.37350498459</td><td>0.00647387278376</td><td>0.00156210772538</td><td>0.0</td></tr>\n<tr><td>2</td><td>474344000.855</td><td>474345800.855</td><td>474347600.855</td><td>51</td><td>7.14142842854</td><td>3.78448847324</td><td>3265.00997642</td><td>0.0156201666667</td><td>0.00218726082925</td><td>8.0</td><td>2.82842712475</td><td>25.9567100265</td><td>3265.00997642</td><td>0.00245022222222</td><td>1.16640004666</td><td>0.412384691283</td><td>49.8335999533</td><td>7.15332518019</td><td>0.0152629242524</td><td>0.00219090453991</td><td>32</td><td>5.65685424949</td><td>0.00980088888889</td><td>0.00173256874875</td><td>4.0</td><td>2.0</td><td>0.00122511111111</td><td>0.583200023328</td><td>0.291600011664</td><td>31.4167999767</td><td>5.66436497472</td><td>0.00962226768174</td><td>0.00173486911698</td><td>19</td><td>4.35889894354</td><td>0.00581927777778</td><td>0.00133503388199</td><td>4.0</td><td>2.0</td><td>0.00122511111111</td><td>0.583200023328</td><td>0.291600011664</td><td>18.4167999767</td><td>4.3686417302</td><td>0.00564065657063</td><td>0.00133801788103</td><td>3600.0</td></tr>\n<tr><td>3</td><td>474347600.855</td><td>474349400.855</td><td>474351200.855</td><td>41</td><td>6.40312423743</td><td>3.78448847324</td><td>3265.00997642</td><td>0.0125573888889</td><td>0.00196113466228</td><td>7.0</td><td>2.64575131106</td><td>25.9567100265</td><td>3265.00997642</td><td>0.00214394444444</td><td>1.02060004082</td><td>0.385750556583</td><td>39.9793999592</td><td>6.41473331417</td><td>0.0122448017764</td><td>0.0019646902645</td><td>23</td><td>4.79583152331</td><td>0.00704438888889</td><td>0.00146885662156</td><td>2.0</td><td>1.41421356237</td><td>0.000612555555556</td><td>0.291600011664</td><td>0.206192345642</td><td>22.7083999883</td><td>4.80026200154</td><td>0.00695507828532</td><td>0.00147021357858</td><td>18</td><td>4.24264068712</td><td>0.005513</td><td>0.00129942656156</td><td>5.0</td><td>2.2360679775</td><td>0.00153138888889</td><td>0.72900002916</td><td>0.32601872416</td><td>17.2709999708</td><td>4.25514843554</td><td>0.00528972349107</td><td>0.00130325740695</td><td>7200.0</td></tr>\n<tr><td>4</td><td>474351200.855</td><td>474353000.855</td><td>474354800.855</td><td>44</td><td>6.63324958071</td><td>3.78448847324</td><td>3265.00997642</td><td>0.0134762222222</td><td>0.00203161694103</td><td>9.0</td><td>3.0</td><td>25.9567100265</td><td>3265.00997642</td><td>0.0027565</td><td>1.31220005249</td><td>0.437400017496</td><td>42.6877999475</td><td>6.6476551336</td><td>0.0130743245061</td><td>0.00203602904175</td><td>19</td><td>4.35889894354</td><td>0.00581927777778</td><td>0.00133503388199</td><td>6.0</td><td>2.44948974278</td><td>0.00183766666667</td><td>0.874800034992</td><td>0.357135618783</td><td>18.125199965</td><td>4.37350498459</td><td>0.00555134596706</td><td>0.00133950738778</td><td>25</td><td>5.0</td><td>0.00765694444444</td><td>0.00153138888889</td><td>3.0</td><td>1.73205080757</td><td>0.000918833333333</td><td>0.437400017496</td><td>0.252533017845</td><td>24.5625999825</td><td>5.0063732307</td><td>0.00752297853909</td><td>0.00153334086783</td><td>10800.0</td></tr>\n<tr><td>5</td><td>474354800.855</td><td>474356600.855</td><td>474358400.855</td><td>60</td><td>7.74596669241</td><td>3.78448847324</td><td>3265.00997642</td><td>0.0183766666667</td><td>0.00237241746529</td><td>6.0</td><td>2.44948974278</td><td>25.9567100265</td><td>3265.00997642</td><td>0.00183766666667</td><td>0.874800034992</td><td>0.357135618783</td><td>59.125199965</td><td>7.75419537091</td><td>0.0181087348559</td><td>0.00237493772666</td><td>25</td><td>5.0</td><td>0.00765694444444</td><td>0.00153138888889</td><td>2.0</td><td>1.41421356237</td><td>0.000612555555556</td><td>0.291600011664</td><td>0.206192345642</td><td>24.7083999883</td><td>5.00424972233</td><td>0.00756763384087</td><td>0.0015326904844</td><td>35</td><td>5.9160797831</td><td>0.0107197222222</td><td>0.00181196376912</td><td>4.0</td><td>2.0</td><td>0.00122511111111</td><td>0.583200023328</td><td>0.291600011664</td><td>34.4167999767</td><td>5.92326181819</td><td>0.0105411010151</td><td>0.00181416346687</td><td>14400.0</td></tr>\n<tr><td>6</td><td>474358400.855</td><td>474360200.855</td><td>474362000.855</td><td>43</td><td>6.5574385243</td><td>3.78448847324</td><td>3265.00997642</td><td>0.0131699444444</td><td>0.00200839769914</td><td>10.0</td><td>3.16227766017</td><td>25.9567100265</td><td>3265.00997642</td><td>0.00306277777778</td><td>1.45800005832</td><td>0.461060101295</td><td>41.5419999417</td><td>6.5736273409</td><td>0.0127233914266</td><td>0.00201335597391</td><td>24</td><td>4.89897948557</td><td>0.00735066666667</td><td>0.00150044855022</td><td>3.0</td><td>1.73205080757</td><td>0.000918833333333</td><td>0.437400017496</td><td>0.252533017845</td><td>23.5625999825</td><td>4.90548396441</td><td>0.00721670076131</td><td>0.00150244072754</td><td>19</td><td>4.35889894354</td><td>0.00581927777778</td><td>0.00133503388199</td><td>7.0</td><td>2.64575131106</td><td>0.00214394444444</td><td>1.02060004082</td><td>0.385750556583</td><td>17.9793999592</td><td>4.37593458497</td><td>0.00550669066527</td><td>0.00134025152038</td><td>18000.0</td></tr>\n<tr><td>7</td><td>474362000.855</td><td>474363800.855</td><td>474365600.855</td><td>52</td><td>7.21110255093</td><td>3.78448847324</td><td>3265.00997642</td><td>0.0159264444444</td><td>0.00220860046463</td><td>7.0</td><td>2.64575131106</td><td>25.9567100265</td><td>3265.00997642</td><td>0.00214394444444</td><td>1.02060004082</td><td>0.385750556583</td><td>50.9793999592</td><td>7.22141284597</td><td>0.0156138573319</td><td>0.00221175827888</td><td>22</td><td>4.69041575982</td><td>0.00673811111111</td><td>0.00143657011577</td><td>6.0</td><td>2.44948974278</td><td>0.00183766666667</td><td>0.874800034992</td><td>0.357135618783</td><td>21.125199965</td><td>4.7039925436</td><td>0.00647017930039</td><td>0.00144072838294</td><td>30</td><td>5.47722557505</td><td>0.00918833333333</td><td>0.00167755247751</td><td>1.0</td><td>1.0</td><td>0.000306277777778</td><td>0.145800005832</td><td>0.145800005832</td><td>29.8541999942</td><td>5.47916577972</td><td>0.00914367803155</td><td>0.00167814671909</td><td>21600.0</td></tr>\n<tr><td>8</td><td>474365600.855</td><td>474367400.855</td><td>474369200.855</td><td>49</td><td>7.0</td><td>3.78448847324</td><td>3265.00997642</td><td>0.0150076111111</td><td>0.00214394444444</td><td>8.0</td><td>2.82842712475</td><td>25.9567100265</td><td>3265.00997642</td><td>0.00245022222222</td><td>1.16640004666</td><td>0.412384691283</td><td>47.8335999533</td><td>7.01213670243</td><td>0.0146503686968</td><td>0.0021476616467</td><td>27</td><td>5.19615242271</td><td>0.0082695</td><td>0.00159146601702</td><td>3.0</td><td>1.73205080757</td><td>0.000918833333333</td><td>0.437400017496</td><td>0.252533017845</td><td>26.5625999825</td><td>5.20228535599</td><td>0.00813553409464</td><td>0.0015933443982</td><td>22</td><td>4.69041575982</td><td>0.00673811111111</td><td>0.00143657011577</td><td>5.0</td><td>2.2360679775</td><td>0.00153138888889</td><td>0.72900002916</td><td>0.32601872416</td><td>21.2709999708</td><td>4.70173246884</td><td>0.00651483460218</td><td>0.00144003617226</td><td>25200.0</td></tr>\n<tr><td>9</td><td>474369200.855</td><td>474371000.855</td><td>474372800.855</td><td>56</td><td>7.48331477355</td><td>3.78448847324</td><td>3265.00997642</td><td>0.0171515555556</td><td>0.00229197301925</td><td>7.0</td><td>2.64575131106</td><td>25.9567100265</td><td>3265.00997642</td><td>0.00214394444444</td><td>1.02060004082</td><td>0.385750556583</td><td>54.9793999592</td><td>7.4932505291</td><td>0.0168389684431</td><td>0.00229501612039</td><td>22</td><td>4.69041575982</td><td>0.00673811111111</td><td>0.00143657011577</td><td>3.0</td><td>1.73205080757</td><td>0.000918833333333</td><td>0.437400017496</td><td>0.252533017845</td><td>21.5625999825</td><td>4.69720905699</td><td>0.00660414520575</td><td>0.00143865075173</td><td>34</td><td>5.83095189485</td><td>0.0104134444444</td><td>0.00178589098868</td><td>4.0</td><td>2.0</td><td>0.00122511111111</td><td>0.583200023328</td><td>0.291600011664</td><td>33.4167999767</td><td>5.83823865278</td><td>0.0102348232373</td><td>0.00178812276071</td><td>28800.0</td></tr>\n<tr><td>10</td><td>474372800.855</td><td>474374600.855</td><td>474376400.855</td><td>46</td><td>6.78232998313</td><td>3.78448847324</td><td>3265.00997642</td><td>0.0140887777778</td><td>0.00207727695539</td><td>11.0</td><td>3.31662479036</td><td>25.9567100265</td><td>3265.00997642</td><td>0.00336905555556</td><td>1.60380006415</td><td>0.483563913776</td><td>44.3961999358</td><td>6.79954660685</td><td>0.0135975694581</td><td>0.00208255002464</td><td>23</td><td>4.79583152331</td><td>0.00704438888889</td><td>0.00146885662156</td><td>5.0</td><td>2.2360679775</td><td>0.00153138888889</td><td>0.72900002916</td><td>0.32601872416</td><td>22.2709999708</td><td>4.80690006225</td><td>0.00682111237996</td><td>0.00147224666907</td><td>23</td><td>4.79583152331</td><td>0.00704438888889</td><td>0.00146885662156</td><td>6.0</td><td>2.44948974278</td><td>0.00183766666667</td><td>0.874800034992</td><td>0.357135618783</td><td>22.125199965</td><td>4.80911071303</td><td>0.00677645707817</td><td>0.00147292374227</td><td>32400.0</td></tr>\n<tr><td>11</td><td>474376400.855</td><td>474378200.855</td><td>474380000.855</td><td>40</td><td>6.32455532034</td><td>3.78448847324</td><td>3265.00997642</td><td>0.0122511111111</td><td>0.00193707074895</td><td>9.0</td><td>3.0</td><td>25.9567100265</td><td>3265.00997642</td><td>0.0027565</td><td>1.31220005249</td><td>0.437400017496</td><td>38.6877999475</td><td>6.33966235499</td><td>0.011849213395</td><td>0.00194169769795</td><td>14</td><td>3.74165738677</td><td>0.00428788888889</td><td>0.00114598650963</td><td>3.0</td><td>1.73205080757</td><td>0.000918833333333</td><td>0.437400017496</td><td>0.252533017845</td><td>13.5625999825</td><td>3.75016971951</td><td>0.00415392298353</td><td>0.00114859364798</td><td>26</td><td>5.09901951359</td><td>0.00796322222222</td><td>0.00156171636547</td><td>6.0</td><td>2.44948974278</td><td>0.00183766666667</td><td>0.874800034992</td><td>0.357135618783</td><td>25.125199965</td><td>5.11151111221</td><td>0.0076952904115</td><td>0.00156554226453</td><td>36000.0</td></tr>\n<tr><td>12</td><td>474380000.855</td><td>474381800.855</td><td>474383600.855</td><td>46</td><td>6.78232998313</td><td>3.78448847324</td><td>3265.00997642</td><td>0.0140887777778</td><td>0.00207727695539</td><td>9.0</td><td>3.0</td><td>25.9567100265</td><td>3265.00997642</td><td>0.0027565</td><td>1.31220005249</td><td>0.437400017496</td><td>44.6877999475</td><td>6.79641955557</td><td>0.0136868800617</td><td>0.00208159227832</td><td>20</td><td>4.472135955</td><td>0.00612555555556</td><td>0.00136971586222</td><td>3.0</td><td>1.73205080757</td><td>0.000918833333333</td><td>0.437400017496</td><td>0.252533017845</td><td>19.5625999825</td><td>4.47926031004</td><td>0.0059915896502</td><td>0.00137189789385</td><td>26</td><td>5.09901951359</td><td>0.00796322222222</td><td>0.00156171636547</td><td>6.0</td><td>2.44948974278</td><td>0.00183766666667</td><td>0.874800034992</td><td>0.357135618783</td><td>25.125199965</td><td>5.11151111221</td><td>0.0076952904115</td><td>0.00156554226453</td><td>39600.0</td></tr>\n<tr><td>13</td><td>474383600.855</td><td>474385400.855</td><td>474387200.855</td><td>51</td><td>7.14142842854</td><td>3.78448847324</td><td>3265.00997642</td><td>0.0156201666667</td><td>0.00218726082925</td><td>7.0</td><td>2.64575131106</td><td>25.9567100265</td><td>3265.00997642</td><td>0.00214394444444</td><td>1.02060004082</td><td>0.385750556583</td><td>49.9793999592</td><td>7.15183916849</td><td>0.0153075795542</td><td>0.00219044940755</td><td>17</td><td>4.12310562562</td><td>0.00520672222222</td><td>0.00126281562856</td><td>0.0</td><td>0.0</td><td>0.0</td><td>0.0</td><td>0.0</td><td>17.0</td><td>4.12310562562</td><td>0.00520672222222</td><td>0.00126281562856</td><td>34</td><td>5.83095189485</td><td>0.0104134444444</td><td>0.00178589098868</td><td>7.0</td><td>2.64575131106</td><td>0.00214394444444</td><td>1.02060004082</td><td>0.385750556583</td><td>32.9793999592</td><td>5.84369775843</td><td>0.0101008573319</td><td>0.00178979476346</td><td>43200.0</td></tr>\n<tr><td>14</td><td>474387200.855</td><td>474389000.855</td><td>474390800.855</td><td>47</td><td>6.8556546004</td><td>3.78448847324</td><td>3265.00997642</td><td>0.0143950555556</td><td>0.00209973465622</td><td>11.0</td><td>3.31662479036</td><td>25.9567100265</td><td>3265.00997642</td><td>0.00336905555556</td><td>1.60380006415</td><td>0.483563913776</td><td>45.3961999358</td><td>6.87268754264</td><td>0.0139038472359</td><td>0.00210495146792</td><td>21</td><td>4.58257569496</td><td>0.00643183333333</td><td>0.00140354110035</td><td>4.0</td><td>2.0</td><td>0.00122511111111</td><td>0.583200023328</td><td>0.291600011664</td><td>20.4167999767</td><td>4.59184391795</td><td>0.00625321212619</td><td>0.00140637975109</td><td>26</td><td>5.09901951359</td><td>0.00796322222222</td><td>0.00156171636547</td><td>7.0</td><td>2.64575131106</td><td>0.00214394444444</td><td>1.02060004082</td><td>0.385750556583</td><td>24.9793999592</td><td>5.11359007859</td><td>0.00765063510972</td><td>0.00156617900574</td><td>46800.0</td></tr>\n<tr><td>15</td><td>474390800.855</td><td>474392600.855</td><td>474394400.855</td><td>48</td><td>6.92820323028</td><td>3.78448847324</td><td>3265.00997642</td><td>0.0147013333333</td><td>0.00212195468936</td><td>16.0</td><td>4.0</td><td>25.9567100265</td><td>3265.00997642</td><td>0.00490044444444</td><td>2.33280009331</td><td>0.583200023328</td><td>45.6671999067</td><td>6.95270611109</td><td>0.0139868485048</td><td>0.00212945937725</td><td>29</td><td>5.38516480713</td><td>0.00888205555556</td><td>0.0016493563101</td><td>4.0</td><td>2.0</td><td>0.00122511111111</td><td>0.583200023328</td><td>0.291600011664</td><td>28.4167999767</td><td>5.3930539184</td><td>0.00870343434841</td><td>0.00165177256956</td><td>19</td><td>4.35889894354</td><td>0.00581927777778</td><td>0.00133503388199</td><td>12.0</td><td>3.46410161514</td><td>0.00367533333333</td><td>1.74960006998</td><td>0.50506603569</td><td>17.25039993</td><td>4.38806240844</td><td>0.00528341415634</td><td>0.00134396600321</td><td>50400.0</td></tr>\n<tr><td>16</td><td>474394400.855</td><td>474396200.855</td><td>474398000.855</td><td>40</td><td>6.32455532034</td><td>3.78448847324</td><td>3265.00997642</td><td>0.0122511111111</td><td>0.00193707074895</td><td>14.0</td><td>3.74165738677</td><td>25.9567100265</td><td>3265.00997642</td><td>0.00428788888889</td><td>2.04120008165</td><td>0.545533668813</td><td>37.9587999184</td><td>6.34803961738</td><td>0.0116259368861</td><td>0.00194426346726</td><td>25</td><td>5.0</td><td>0.00765694444444</td><td>0.00153138888889</td><td>5.0</td><td>2.2360679775</td><td>0.00153138888889</td><td>0.72900002916</td><td>0.32601872416</td><td>24.2709999708</td><td>5.01061754762</td><td>0.00743366793551</td><td>0.00153464080778</td><td>15</td><td>3.87298334621</td><td>0.00459416666667</td><td>0.00118620873265</td><td>9.0</td><td>3.0</td><td>0.0027565</td><td>1.31220005249</td><td>0.437400017496</td><td>13.6877999475</td><td>3.89760423534</td><td>0.00419226895059</td><td>0.00119374956386</td><td>54000.0</td></tr>\n<tr><td>17</td><td>474398000.855</td><td>474399800.855</td><td>474401600.855</td><td>41</td><td>6.40312423743</td><td>3.78448847324</td><td>2707.95972139</td><td>0.0151405501626</td><td>0.00236455667596</td><td>7.0</td><td>2.64575131106</td><td>25.9567100265</td><td>2707.95972139</td><td>0.00258497197898</td><td>1.02060004082</td><td>0.385750556583</td><td>39.9793999592</td><td>6.41473331417</td><td>0.014763661233</td><td>0.00236884369568</td><td>20</td><td>4.472135955</td><td>0.00738563422566</td><td>0.00165147801855</td><td>3.0</td><td>1.73205080757</td><td>0.00110784513385</td><td>0.437400017496</td><td>0.252533017845</td><td>19.5625999825</td><td>4.47926031004</td><td>0.00722411039868</td><td>0.00165410891257</td><td>21</td><td>4.58257569496</td><td>0.00775491593694</td><td>0.00169226139472</td><td>4.0</td><td>2.0</td><td>0.00147712684513</td><td>0.583200023328</td><td>0.291600011664</td><td>20.4167999767</td><td>4.59184391795</td><td>0.0075395508343</td><td>0.00169568397996</td><td>57600.0</td></tr>\n</table>\n\n\n\n## Observations and data reduction\n\n\\label{sect:obs}\n\nWe present new and archival X-ray data from \\emph{Chandra} and archival data from \\emph{XMM-Newton} as well as optical\ndata from \\emph{Chandra}'s aspect camera (ACA) and AAVSO long-term monitoring lightcurves extended into 2017. Details of the X-ray observations are listed in table~\\ref{tab:obslog}.\n\n### \\emph{XMM-Newton} X-ray data\nRW~Aur~AB was centered in the field of view in the \\emph{XMM-Newton} observation, but the count rate in the RGS is too low to analyze the grating spectrum. We reduced the data with SAS version 15.0.0 following the standard procedures to screen periods of high-background flux. We extracted a source region centered on the unresolved binary (AB) with a radius of 30\\arcsec{} in the PN and MOS detectors. We selected source-free background regions on the same chip (avoiding the chip edges where noise can be higher) with a radius of 50\\arcsec{} in the PN and 105\\arcsec{} for the MOS detectors.\n\n### \\emph{Chandra} X-ray data\n\nObservations were taken roughly two years apart, where the last observation is split into two orbits separated by two days. All processing is done with CIAO version 4.9 and CALDB 4.7.1. RW~Aur~B, the brighter member of the binary in X-rays, was bright enough to be at the risk of pile-up in the 2017 observations but at the fluxes observed the pile-up fraction is less than 5\\% even in the brightest pixel; previous data were taken in a 1/8 sub-array mode that reduces the field-of-view and the frame time to alleviate this problem. For RW~Aur~A, the focus of this paper, pile-up is not significant in any of the observations.\n\n\n```python\nIPython.display.Image(filename=os.path.join(figout, 'regions.png'))\n```\n\\begin{figure*}[ht!]\n\\plotone{regions}\n\\caption{Images of RW~Aur~A and B in all four \\emph{Chandra} observations. The source region for RW~Aur~A (solid line) and annulus (dashed line) designed to capture the contamination by the wings of the PSF of the brighter RW~Aur~B are marked. The color scale shows counts per spatial bin. (The spatial bin size, 0.123~arcsec, in this image is smaller than the physical size of the ACIS pixels.) Note that the exposure time differs between observations and thus the same number of counts does not represent the same flux.}\n    \\label{fig:regions}\n\\end{figure*}\n\n```python\n# How many counts does the background contribute\nareafrac = lccurves[1][1]['AREA'][0]/lccurves[1][1]['BG_AREA'][0]\nfor o in obsids:\n   bbkg = len(Table.read(os.path.join(datadir, '{}_bkgb.fits'.format(o)), hdu=1))\n   print(np.array(bbkg, dtype=float) * areafrac)\n```\n\n    0.206306068954\n    0.123877845057\n    0.120109697678\n    0.0306161974474\n\n\nWe limit our analysis to the energy band 0.3-9.0~keV. Apertures with radius 0.54~arcsec (covering 75\\% of the point-spread function - PSF) were used to extract spectra from RW~Aur A and B. We measure the background flux from a large, source-free region on the same detector and find that the expected background flux in each source region is $<0.2$~counts in any one observation. \nThe B component of the RW~Aur system is much brighter in X-rays than the A component. Therefore, the wings of the PSF from RW~Aur~B contribute to the data extracted for RW~Aur~A, while the reverse contamination is not relevant. \nThus, we define an annulus centered on RW~Aur~B with an inner and outer radius of 1 and 2~arcsec, respectively, like it was done in \\citet{2015A&A...584L...9S}. This corresponds to the radii covered by the extraction region of RW~Aur~A. We remove a segment of $\\pm60^\\circ$ around the position of RW~Aur~A from this annulus and use the remaining area (figure~\\ref{fig:regions}) to estimate the number of counts due to contamination by RW~Aur~B (column ``contam'' in table~\\ref{tab:obslog}). This is a small fraction of the counts from RW~Aur~A except for ObsID~17644 (2015).\n\n\n```python\nlc[0].meta\n```\n\n\n\n\n    OrderedDict([('EXTNAME', 'LIGHTCURVE'),\n                 ('HDUNAME', 'LIGHTCURVE'),\n                 ('ORIGIN', 'ASC'),\n                 ('CREATOR', 'dmextract - Version CIAO 4.9'),\n                 ('ASCDSVER', 'CIAO 4.9'),\n                 ('REVISION', 1),\n                 ('CHECKSUM', 'hkd5iiZ3hib3hiZ3'),\n                 ('DATASUM', '3018229494'),\n                 ('RAND_SKY', 0.0),\n                 ('RAND_PI', 1.0),\n                 ('DATE', '2017-03-23T14:43:13'),\n                 ('MJD_OBS', 57764.063730627),\n                 ('DS_IDENT', 'ADS/Sa.CXO#obs/19980'),\n                 ('DATE-OBS', '2017-01-11T01:31:46'),\n                 ('DATE-END', '2017-01-11T05:33:50'),\n                 ('TIMESYS', 'TT'),\n                 ('MJDREF', 50814.0),\n                 ('TIMEZERO', 0.0),\n                 ('TIMEUNIT', 's'),\n                 ('BTIMNULL', 594935422.10562),\n                 ('BTIMRATE', 0.25625001476888),\n                 ('BTIMDRFT', 2.9866479527206e-18),\n                 ('BTIMCORR', 0.0),\n                 ('TIMEREF', 'LOCAL'),\n                 ('TASSIGN', 'SATELLITE'),\n                 ('CLOCKAPP', True),\n                 ('TIERRELA', 1e-09),\n                 ('TIERABSO', 5e-05),\n                 ('TIMVERSN', 'ASC-FITS-2'),\n                 ('TSTART', 600485506.32619),\n                 ('TSTOP', 600500030.06453),\n                 ('OBS_MODE', 'POINTING'),\n                 ('STARTOBT', 0.0),\n                 ('TIMEPIXR', 0.5),\n                 ('DATACLAS', 'OBSERVED'),\n                 ('RADESYS', 'ICRS'),\n                 ('TIMEDEL', 3600.0),\n                 ('MISSION', 'AXAF'),\n                 ('TELESCOP', 'CHANDRA'),\n                 ('SIM_X', -0.68282252473119),\n                 ('SIM_Y', 0.0),\n                 ('SIM_Z', -190.14006604987),\n                 ('FOC_LEN', 10070.0),\n                 ('INSTRUME', 'ACIS'),\n                 ('GRATING', 'NONE'),\n                 ('DETNAM', 'ACIS-235678'),\n                 ('RA_PNT', 76.959935172349),\n                 ('DEC_PNT', 30.398961642359),\n                 ('ROLL_PNT', 262.84492263398),\n                 ('RA_TARG', 76.956542),\n                 ('DEC_TARG', 30.401439),\n                 ('DEFOCUS', 0.0014449365687057),\n                 ('RA_NOM', 76.959935172349),\n                 ('DEC_NOM', 30.398961642359),\n                 ('ROLL_NOM', 262.84492263398),\n                 ('READMODE', 'TIMED'),\n                 ('CTI_CORR', True),\n                 ('CTI_APP', 'PPPPPBPBPP'),\n                 ('DATAMODE', 'FAINT'),\n                 ('FLSHTIME', 0.0),\n                 ('CYCLE', 'P'),\n                 ('TITLE', 'What are the dust properties around young stars?'),\n                 ('OBSERVER', 'Hans Guenther'),\n                 ('OBJECT', 'RW Aur'),\n                 ('OBS_ID', '19980'),\n                 ('SEQ_NUM', '201073'),\n                 ('ONTIME', 10296.665549994),\n                 ('ONTIME7', 10296.665549994),\n                 ('ONTIME2', 10296.706589937),\n                 ('ONTIME5', 10296.624509931),\n                 ('ONTIME6', 10296.583469987),\n                 ('ONTIME3', 10296.542429924),\n                 ('ONTIME8', 10296.50138998),\n                 ('LIVETIME', 10166.282970892),\n                 ('LIVTIME7', 10166.282970892),\n                 ('LIVTIME2', 10166.323491163),\n                 ('LIVTIME5', 10166.242450503),\n                 ('LIVTIME6', 10166.201930232),\n                 ('LIVTIME3', 10166.161409843),\n                 ('LIVTIME8', 10166.120889572),\n                 ('EXPOSURE', 10166.282970892),\n                 ('EXPOSUR7', 10166.282970892),\n                 ('AREASCAL', 1.0),\n                 ('CORRSCAL', 0.0),\n                 ('BACKSCAL', 5.6393272776031e-08),\n                 ('DETCHANS', 5),\n                 ('TOTCTS', 279),\n                 ('POISSERR', False),\n                 ('SYS_ERR', 0.0),\n                 ('QUALITY', 0),\n                 ('GROUPING', 0),\n                 ('HISTNUM', 18),\n                 ('EXPOSUR2', 10166.323491163),\n                 ('EXPOSUR5', 10166.242450503),\n                 ('EXPOSUR6', 10166.201930232),\n                 ('EXPOSUR3', 10166.161409843),\n                 ('EXPOSUR8', 10166.120889572),\n                 ('DTCOR', 0.98733739787229),\n                 ('ASPTYPE', 'KALMAN'),\n                 ('FP_TEMP', 153.60722351),\n                 ('DY_AVG', 0.71182390026),\n                 ('DZ_AVG', 0.91716868849),\n                 ('DTH_AVG', -0.0035780654859),\n                 ('CONTENT', 'LIGHTCURVE'),\n                 ('HDUCLASS', 'OGIP'),\n                 ('HDUCLAS1', 'LIGHTCURVE'),\n                 ('HDUCLAS2', 'TOTAL'),\n                 ('HDUCLAS3', 'RATE'),\n                 ('HISTORY',\n                  ['dmextract binning: File EVENTS Col time Binning 6.00486e+08:6.00504e+08:',\n                   '3600',\n                   ' TOOL  :dmextract   2017-03-23T15:43:59                         ASC00001',\n                   ' PARM  :infile=19980/19980_evt2.fits[energy=300:9000,sky=circle(ASC00002',\n                   \" CONT  :5:07:49.434,+30:24:04.692,0.00900')][bin time=::3600]   ASC00003\",\n                   ' PARM  :outfile=19980_srcb_lc.fits                              ASC00004',\n                   ' PARM  :bkg=19980/19980_evt2.fits[energy=300:9000,sky=circle(5:0ASC00005',\n                   \" CONT  :7:49.470,+30:24:46.246,0.41469')]                       ASC00006\",\n                   ' PARM  :error=gaussian                                          ASC00007',\n                   ' PARM  :bkgerror=gaussian                                       ASC00008',\n                   ' PARM  :bkgnorm=1                                               ASC00009',\n                   ' PARM  :exp=                                                    ASC00010',\n                   ' PARM  :bkgexp=                                                 ASC00011',\n                   ' PARM  :sys_err=0                                               ASC00012',\n                   ' PARM  :opt=ltc1                                                ASC00013',\n                   ' PARM  :defaults=/nfs/cxc/a1/linux-x86_64/opt/packages/ciao-4.9/ASC00014',\n                   ' CONT  :data/cxo.mdb                                            ASC00015',\n                   ' PARM  :wmap=                                                   ASC00016',\n                   ' PARM  :clobber=yes                                             ASC00017',\n                   ' PARM  :verbose=0                                               ASC00018',\n                   'dmextract binning: File EVENTS Col time Binning 6.00486e+08:6.00504e+08:',\n                   '3600',\n                   ' TOOL  :dmextract   2017-03-23T14:43:13                         ASC00001',\n                   ' PARM  :infile=19980/19980_evt2.fits[energy=300:1000,sky=circle(ASC00002',\n                   \" CONT  :5:07:49.434,+30:24:04.692,0.00900')][bin time=::3600]   ASC00003\",\n                   ' PARM  :outfile=19980_srcb_lc_soft.fits                         ASC00004',\n                   ' PARM  :bkg=19980/19980_evt2.fits[energy=300:1000,sky=circle(5:0ASC00005',\n                   \" CONT  :7:49.470,+30:24:46.246,0.41469')]                       ASC00006\",\n                   ' PARM  :error=gaussian                                          ASC00007',\n                   ' PARM  :bkgerror=gaussian                                       ASC00008',\n                   ' PARM  :bkgnorm=1                                               ASC00009',\n                   ' PARM  :exp=                                                    ASC00010',\n                   ' PARM  :bkgexp=                                                 ASC00011',\n                   ' PARM  :sys_err=0                                               ASC00012',\n                   ' PARM  :opt=ltc1                                                ASC00013',\n                   ' PARM  :defaults=/nfs/cxc/a1/linux-x86_64/opt/packages/ciao-4.9/ASC00014',\n                   ' CONT  :data/cxo.mdb                                            ASC00015',\n                   ' PARM  :wmap=                                                   ASC00016',\n                   ' PARM  :clobber=yes                                             ASC00017',\n                   ' PARM  :verbose=0                                               ASC00018',\n                   'dmextract binning: File EVENTS Col time Binning 6.00486e+08:6.00504e+08:',\n                   '3600',\n                   ' TOOL  :dmextract   2017-03-23T14:43:13                         ASC00001',\n                   ' PARM  :infile=19980/19980_evt2.fits[energy=1000:9000,sky=circleASC00002',\n                   \" CONT  :(5:07:49.434,+30:24:04.692,0.00900')][bin time=::3600]  ASC00003\",\n                   ' PARM  :outfile=19980_srcb_lc_hard.fits                         ASC00004',\n                   ' PARM  :bkg=19980/19980_evt2.fits[energy=1000:9000,sky=circle(5:ASC00005',\n                   \" CONT  :07:49.470,+30:24:46.246,0.41469')]                      ASC00006\",\n                   ' PARM  :error=gaussian                                          ASC00007',\n                   ' PARM  :bkgerror=gaussian                                       ASC00008',\n                   ' PARM  :bkgnorm=1                                               ASC00009',\n                   ' PARM  :exp=                                                    ASC00010',\n                   ' PARM  :bkgexp=                                                 ASC00011',\n                   ' PARM  :sys_err=0                                               ASC00012',\n                   ' PARM  :opt=ltc1                                                ASC00013',\n                   ' PARM  :defaults=/nfs/cxc/a1/linux-x86_64/opt/packages/ciao-4.9/ASC00014',\n                   ' CONT  :data/cxo.mdb                                            ASC00015',\n                   ' PARM  :wmap=                                                   ASC00016',\n                   ' PARM  :clobber=yes                                             ASC00017',\n                   ' PARM  :verbose=0                                               ASC00018']),\n                 ('TLMIN1', 1),\n                 ('TLMAX1', 5),\n                 ('TLMIN6', 0.0),\n                 ('TLMIN9', 0.0),\n                 ('TLMIN10', 0.0),\n                 ('TLMIN2', 600485506.32619),\n                 ('TLMAX2', 600500030.06453),\n                 ('TLMIN4', 600485506.32619),\n                 ('TLMAX4', 600500030.06453),\n                 ('DSTYP1', 'TIME'),\n                 ('DSVAL1', 'TABLE'),\n                 ('DSFORM1', 'D'),\n                 ('DSUNIT1', 's'),\n                 ('DSREF1', ':GTI7'),\n                 ('2DSREF1', ':GTI2'),\n                 ('3DSREF1', ':GTI5'),\n                 ('4DSREF1', ':GTI6'),\n                 ('5DSREF1', ':GTI3'),\n                 ('6DSREF1', ':GTI8'),\n                 ('DSTYP2', 'ccd_id'),\n                 ('DSVAL2', '7:7'),\n                 ('DSFORM2', 'I'),\n                 ('2DSVAL2', '2:2'),\n                 ('3DSVAL2', '5:5'),\n                 ('4DSVAL2', '6:6'),\n                 ('5DSVAL2', '3:3'),\n                 ('6DSVAL2', '8:8'),\n                 ('DSTYP3', 'node_id'),\n                 ('DSVAL3', '0:3'),\n                 ('DSFORM3', 'I'),\n                 ('2DSVAL3', '0:3'),\n                 ('3DSVAL3', '0:3'),\n                 ('4DSVAL3', '0:3'),\n                 ('5DSVAL3', '0:3'),\n                 ('6DSVAL3', '0:3'),\n                 ('DSTYP4', 'expno'),\n                 ('DSVAL4', '0:'),\n                 ('DSFORM4', 'J'),\n                 ('2DSVAL4', '0:'),\n                 ('3DSVAL4', '0:'),\n                 ('4DSVAL4', '0:'),\n                 ('5DSVAL4', '0:'),\n                 ('6DSVAL4', '0:'),\n                 ('DSTYP5', 'chipx'),\n                 ('DSVAL5', '1:1024'),\n                 ('DSFORM5', 'I'),\n                 ('DSUNIT5', 'pixel'),\n                 ('DSTYP6', 'chipy'),\n                 ('DSVAL6', '1:1024'),\n                 ('DSFORM6', 'I'),\n                 ('DSUNIT6', 'pixel'),\n                 ('2DSVAL5', '1:1024'),\n                 ('2DSVAL6', '1:1024'),\n                 ('3DSVAL5', '1:1024'),\n                 ('3DSVAL6', '1:1024'),\n                 ('4DSVAL5', '1:1024'),\n                 ('4DSVAL6', '1:1024'),\n                 ('5DSVAL5', '1:1024'),\n                 ('5DSVAL6', '1:1024'),\n                 ('6DSVAL5', '1:1024'),\n                 ('6DSVAL6', '1:1024'),\n                 ('DSTYP7', 'tdetx'),\n                 ('DSVAL7', '1:8192'),\n                 ('DSFORM7', 'I'),\n                 ('DSUNIT7', 'pixel'),\n                 ('DSTYP8', 'tdety'),\n                 ('DSVAL8', '1:8192'),\n                 ('DSFORM8', 'I'),\n                 ('DSUNIT8', 'pixel'),\n                 ('2DSVAL7', '1:8192'),\n                 ('2DSVAL8', '1:8192'),\n                 ('3DSVAL7', '1:8192'),\n                 ('3DSVAL8', '1:8192'),\n                 ('4DSVAL7', '1:8192'),\n                 ('4DSVAL8', '1:8192'),\n                 ('5DSVAL7', '1:8192'),\n                 ('5DSVAL8', '1:8192'),\n                 ('6DSVAL7', '1:8192'),\n                 ('6DSVAL8', '1:8192'),\n                 ('DSTYP9', 'detx'),\n                 ('DSVAL9', '0.5:8192.5'),\n                 ('DSFORM9', 'E'),\n                 ('DSUNIT9', 'pixel'),\n                 ('DSTYP10', 'dety'),\n                 ('DSVAL10', '0.5:8192.5'),\n                 ('DSFORM10', 'E'),\n                 ('DSUNIT10', 'pixel'),\n                 ('2DSVAL9', '0.5:8192.5'),\n                 ('2DSVAL10', '0.5:8192.5'),\n                 ('3DSVAL9', '0.5:8192.5'),\n                 ('3DSVAL10', '0.5:8192.5'),\n                 ('4DSVAL9', '0.5:8192.5'),\n                 ('4DSVAL10', '0.5:8192.5'),\n                 ('5DSVAL9', '0.5:8192.5'),\n                 ('5DSVAL10', '0.5:8192.5'),\n                 ('6DSVAL9', '0.5:8192.5'),\n                 ('6DSVAL10', '0.5:8192.5'),\n                 ('DSTYP11', 'sky(x,y)'),\n                 ('DSVAL11', 'Circle(4121.49,4113.63,1.09756)'),\n                 ('DSFORM11', 'E'),\n                 ('DSUNIT11', 'pixel'),\n                 ('2DSVAL11', 'Circle(4121.49,4113.63,1.09756)'),\n                 ('3DSVAL11', 'Circle(4121.49,4113.63,1.09756)'),\n                 ('4DSVAL11', 'Circle(4121.49,4113.63,1.09756)'),\n                 ('5DSVAL11', 'Circle(4121.49,4113.63,1.09756)'),\n                 ('6DSVAL11', 'Circle(4121.49,4113.63,1.09756)'),\n                 ('DSTYP12', 'pha'),\n                 ('DSVAL12', '0:36855'),\n                 ('DSFORM12', 'J'),\n                 ('DSUNIT12', 'adu'),\n                 ('2DSVAL12', '0:36855'),\n                 ('3DSVAL12', '0:36855'),\n                 ('4DSVAL12', '0:36855'),\n                 ('5DSVAL12', '0:36855'),\n                 ('6DSVAL12', '0:36855'),\n                 ('DSTYP13', 'pha_ro'),\n                 ('DSVAL13', '0:36855'),\n                 ('DSFORM13', 'J'),\n                 ('DSUNIT13', 'adu'),\n                 ('2DSVAL13', '0:36855'),\n                 ('3DSVAL13', '0:36855'),\n                 ('4DSVAL13', '0:36855'),\n                 ('5DSVAL13', '0:36855'),\n                 ('6DSVAL13', '0:36855'),\n                 ('DSTYP14', 'energy'),\n                 ('DSVAL14', '1000:9000'),\n                 ('DSFORM14', 'E'),\n                 ('DSUNIT14', 'eV'),\n                 ('2DSVAL14', '1000:9000'),\n                 ('3DSVAL14', '1000:9000'),\n                 ('4DSVAL14', '1000:9000'),\n                 ('5DSVAL14', '1000:9000'),\n                 ('6DSVAL14', '1000:9000'),\n                 ('DSTYP15', 'pi'),\n                 ('DSVAL15', '1:1024'),\n                 ('DSFORM15', 'J'),\n                 ('DSUNIT15', 'chan'),\n                 ('2DSVAL15', '1:1024'),\n                 ('3DSVAL15', '1:1024'),\n                 ('4DSVAL15', '1:1024'),\n                 ('5DSVAL15', '1:1024'),\n                 ('6DSVAL15', '1:1024'),\n                 ('DSTYP16', 'fltgrade'),\n                 ('DSVAL16', '0:255'),\n                 ('DSFORM16', 'I'),\n                 ('2DSVAL16', '0:255'),\n                 ('3DSVAL16', '0:255'),\n                 ('4DSVAL16', '0:255'),\n                 ('5DSVAL16', '0:255'),\n                 ('6DSVAL16', '0:255'),\n                 ('DSTYP17', 'grade'),\n                 ('DSVAL17', '0:0,2:2,3:3,4:4,6:6'),\n                 ('DSFORM17', 'I'),\n                 ('2DSVAL17', '0:0,2:2,3:3,4:4,6:6'),\n                 ('3DSVAL17', '0:0,2:2,3:3,4:4,6:6'),\n                 ('4DSVAL17', '0:0,2:2,3:3,4:4,6:6'),\n                 ('5DSVAL17', '0:0,2:2,3:3,4:4,6:6'),\n                 ('6DSVAL17', '0:0,2:2,3:3,4:4,6:6'),\n                 ('DSTYP18', 'phas'),\n                 ('DSVAL18', '-4096:4095'),\n                 ('DSFORM18', 'I'),\n                 ('2DSVAL18', '-4096:4095'),\n                 ('3DSVAL18', '-4096:4095'),\n                 ('4DSVAL18', '-4096:4095'),\n                 ('5DSVAL18', '-4096:4095'),\n                 ('6DSVAL18', '-4096:4095'),\n                 ('TCTYP2', 'DT_MIN'),\n                 ('TCRVL2', 0.0),\n                 ('TCRPX2', 600487306.32619),\n                 ('TCDLT2', 1.0),\n                 ('TCUNI2', 's'),\n                 ('TCTYP3', 'DT'),\n                 ('TCRVL3', 0.0),\n                 ('TCRPX3', 600487306.32619),\n                 ('TCDLT3', 1.0),\n                 ('TCUNI3', 's'),\n                 ('TCTYP4', 'DT_MAX'),\n                 ('TCRVL4', 0.0),\n                 ('TCRPX4', 600487306.32619),\n                 ('TCDLT4', 1.0),\n                 ('TCUNI4', 's')])\n\n\n\n\n```python\n# output->LaTeX\nareafrac = lccurves[0][0]['AREA'][0]/lccurves[0][0]['BG_AREA'][0]\n\nobstab = Table([['\\\\dataset[{0}]{{ADS/Sa.CXO\\\\#obs/{0}}}'.format(o) for o in obsids]], names=['ObsID'])\nobstab['Date'] = [lc[0].meta['DATE-OBS'][:10] for lc in lccurves]\nobstab['MJD'] = [lc[0].meta['MJD_OBS'] for lc in lccurves]\nobstab['MJD'].format = '{:7.1f}'\nobstab['Exp. time$^a$'] = [lc[0].meta['TSTOP'] - lc[0].meta['TSTART'] for lc in lccurves]\nobstab['Exp. time$^a$'].unit = 'ks'\nobstab['Exp. time$^a$'] /= 1e3\nobstab['Exp. time$^a$'].format = '{:4.1f}'\nobstab['livetime$^b$'] = [lc[0].meta['LIVTIME7'] for lc in lccurves]\nobstab['livetime$^b$'].unit = 'ks'\nobstab['livetime$^b$'] /= 1e3\nobstab['livetime$^b$'].format = '{:4.1f}'\nobstab['Mode'] = ['1/8 subarray                    '] *2 + ['full frame'] * 2\n\nacounts = []\nabkg = []\nabkg3 = []\nfor o in obsids:\n    acounts.append(len(Table.read(os.path.join(datadir, '{}_srca.fits'.format(o)), hdu=1)))\n    bkgtab = Table.read(os.path.join(datadir, '{}_bkga.fits'.format(o)), hdu=1)\n    abkg.append(len(bkgtab))\n    abkg3.append((bkgtab['energy'] > 3000).sum())\n\nobstab['RW Aur A'] = acounts\nobstab['RW Aur A'].unit = 'counts'\nobstab['contam'] = np.array(abkg, dtype=float) * areafrac\nobstab['contam'].unit = 'counts'\nobstab['contam'].format = '%4.1f'\nobstab['contam $>3$ keV'] = np.array(abkg3, dtype=float) * areafrac\nobstab['contam $>3$ keV'].unit = 'counts'\nobstab['contam $>3$ keV'].format = '%4.1f'\nobstab.add_column(Column(data=['Chandra/ACIS-S '] * 4, name='Observatory'), index=0)\nobstab.add_row(['XMM-Newton', '0401870301', '2007-02-21', 54123.5,'36.4', '34.5','full frame', 0, 0, 0])\nobstab.sort('MJD')\nobstab.remove_column('contam $>3$ keV')\nlatexdict = copy.deepcopy(latex.latexdicts['AA'])\nlatexdict['tabletype'] = 'table*'\nlatexdict['caption'] = '\\\\label{tab:obslog} X-ray observations'\nlatexdict['tablefoot'] = '\\\\\\\\$^a$: Time for exposure start to exposure end.\\\\\\\\$^b$: Live time in \\\\emph{Chandra}, i.e.\\\\ corrected for the deadtime during readout. In \\emph{XMM-Newton} we give the \\\\emph{ONTIME}, the sum of all good time intervals of the PN chip that detected RW~Aur.'\nfrom io import StringIO\noutstr = StringIO()\nobstab.write(outstr, format='ascii.latex', latexdict=latexdict)\noutstr = outstr.getvalue().replace('0 & 0.0', r'\\multicolumn{2}{c}{unresolved}')\nprint(outstr)\n```\n\n    \\begin{table*}\n    \\caption{\\label{tab:obslog} X-ray observations}\n    \\begin{tabular}{ccccccccc}\n    \\hline \\hline\n    Observatory & ObsID & Date & MJD & Exp. time$^a$ & livetime$^b$ & Mode & RW Aur A & contam \\\\\n     &  &  &  & $\\mathrm{ks}$ & $\\mathrm{ks}$ &  & counts & counts \\\\\n    \\hline\n    XMM-Newton & 0401870301 & 2007-02-21 & 54123.5 & 36.4 & 34.5 & full frame & \\multicolumn{2}{c}{unresolved} \\\\\n    Chandra/ACIS-S & \\dataset[14539]{ADS/Sa.CXO\\#obs/14539} & 2013-01-12 & 56304.1 & 60.9 & 54.5 & 1/8 subarray & 801 & 22.3 \\\\\n    Chandra/ACIS-S & \\dataset[17644]{ADS/Sa.CXO\\#obs/17644} & 2015-04-16 & 57128.3 & 40.2 & 35.1 & 1/8 subarray & 44 & 20.1 \\\\\n    Chandra/ACIS-S & \\dataset[17764]{ADS/Sa.CXO\\#obs/17764} & 2017-01-09 & 57762.3 & 41.1 & 38.5 & full frame & 173 & 18.2 \\\\\n    Chandra/ACIS-S & \\dataset[19980]{ADS/Sa.CXO\\#obs/19980} & 2017-01-11 & 57764.1 & 14.5 & 10.2 & full frame & 36 & 4.5 \\\\\n    \\hline\n    \\end{tabular}\n    \\\\$^a$: Time for exposure start to exposure end.\\\\$^b$: Live time in \\emph{Chandra}, i.e.\\ corrected for the deadtime during readout. In \\emph{XMM-Newton} we give the \\emph{ONTIME}, the sum of all good time intervals of the PN chip that detected RW~Aur.\n    \\end{table*}\n    \n\n\n\n```python\nlatex.latexdicts\n```\n\n\n\n\n    {'AA': {'data_end': '\\\\hline',\n      'header_end': '\\\\hline',\n      'header_start': '\\\\hline \\\\hline',\n      'tabletype': 'table'},\n     'doublelines': {'data_end': '\\\\hline\\\\hline',\n      'header_end': '\\\\hline\\\\hline',\n      'header_start': '\\\\hline \\\\hline',\n      'tabletype': 'table'},\n     'template': {'caption': 'caption',\n      'col_align': 'col_align',\n      'data_end': 'data_end',\n      'data_start': 'data_start',\n      'header_end': 'header_end',\n      'header_start': 'header_start',\n      'preamble': 'preamble',\n      'tablealign': 'tablealign',\n      'tablefoot': 'tablefoot',\n      'tabletype': 'tabletype',\n      'units': {'col1': 'unit of col1', 'col2': 'unit of col2'}}}\n\n\n\n### \\emph{Chandra} optical data\n\n\\emph{Chandra} has a small optical telescope in the aspect control assembly (ACA). This is a CCD detector with a wide bandpass from about 0.4 to 1.1~$\\mu$m. The color conversion to standard filters is not calibrated for stars of arbitrary spectral shape. Only a few regions on the CCD are read out and transmitted to the ground. One of these slots was placed on the science target for ObsIDs 17644, 17767, and 19980. The image is intentionally defocussed and RW~Aur is not resolved. Aperture photometry is performed using the CCD noise model, see \\citet{2010ApJS..188..473N} for details.\n\n### AAVSO data\n\nWe retrieved data for RW~Aur from the database of the American Association of Variable Star Observers (AAVSO) in four bands: Visual and standard $V$, $R$, and $I$ filters. Many observers with different instrumental set-ups contributed to this data collection, but specifically the $B$, $V$, and $R$ data close to the\\emph{Chandra} observations in 2017 are taken with a 684~mm aperture Keller F4.1 Newtonian New Multi-Purpose Telescope of the public observatory Astrolab Iris, Zillebeke, Belgium\\footnote{www.astrolab.be}. The CCD detector assembly is a Santa Barbara Instrument Group STL 6303E operating at -20$^\\circ$~C. \n% A 4-inch Wynne corrector feeds the CCD at a final focal ratio of 4.39, providing a nominal field of view of 20 * 30 arcmin . \nThe 9~$\\mu$m physical pixels are read out binned to $3 \\times 3$~pixels, which is 1.86~arcsec per pixel. \nThe $B$, $V$, and R filters are from Astrodon Photometrics, and have been shown to reproduce the Johnson/Cousins system closely. Differential photometry relative to stars in the field is conducted with the LesvePhotometry reduction package.\n\n## Results\n\n### Lightcurves\n\nWe first look at the long-term optical lightcurve and how the timing of the \\emph{Chandra} observations relates to the optical dimming events. Then, we turn to the \\emph{Chandra} count rates. Last, we present the lightcurve of the \\emph{XMM-Newton} observation, which includes a large X-ray flare but lacks dense optical monitoring.\n\n\n```python\nlcaca = [Table.read(os.path.join(datadir, str(obsid), '0_{0}_lc.fits'.format(obsid)), hdu=1)\n         for obsid in obsids[1:]]\n```\n\n\n```python\nlccurves[0][1]['NET_RATE_all','ERR_RATE_all']\n```\n\n\n\n\n&lt;Table length=17&gt;\n<table id=\"table140050299793248\" class=\"table-striped table-bordered table-condensed\">\n<thead><tr><th>NET_RATE_all</th><th>ERR_RATE_all</th></tr></thead>\n<thead><tr><th>ct / s</th><th>ct / s</th></tr></thead>\n<thead><tr><th>float64</th><th>float64</th></tr></thead>\n<tr><td>0.0375003727389</td><td>0.0036599572457</td></tr>\n<tr><td>0.0330742491756</td><td>0.00318293211904</td></tr>\n<tr><td>0.0370565815991</td><td>0.00336905562042</td></tr>\n<tr><td>0.0324614050951</td><td>0.0031533228128</td></tr>\n<tr><td>0.0318497151144</td><td>0.00312343280423</td></tr>\n<tr><td>0.0385873934381</td><td>0.00343795960455</td></tr>\n<tr><td>0.0398117832368</td><td>0.00349210404416</td></tr>\n<tr><td>0.039198217844</td><td>0.00346513760861</td></tr>\n<tr><td>0.0391987948939</td><td>0.00346513759659</td></tr>\n<tr><td>0.0413450475379</td><td>0.00355862624765</td></tr>\n<tr><td>0.0456313495396</td><td>0.00373859680624</td></tr>\n<tr><td>0.0523700377006</td><td>0.00400510170831</td></tr>\n<tr><td>0.054513982145</td><td>0.00408625528254</td></tr>\n<tr><td>0.051144782327</td><td>0.00395798122862</td></tr>\n<tr><td>0.050532082509</td><td>0.003934209358</td></tr>\n<tr><td>0.0532871398842</td><td>0.0040400814565</td></tr>\n<tr><td>0.0505884635529</td><td>0.00432233167608</td></tr>\n</table>\n\n\n\n\n```python\naavso = Table.read('aavsodata.txt', format='ascii', fill_values = ('N/A', 0))\n# Sometimes the Magnitude column contains the \"<\" sing for upper limits.\naavso['Mag'] = np.zeros(len(aavso))\nfor i in range(len(aavso)):\n    try:\n        aavso['Mag'][i] = float(aavso['Magnitude'][i])\n    except ValueError:\n        aavso['Mag'][i] = np.ma.masked\n```\n\n\n```python\nbands = OrderedDict([('Vis.', {'color': (1., 0.5, 1.), 'marker': '.'}),\n                     ('B', {'color': 'b', 'marker': 'p'}),\n                     ('V', {'color': 'g', 'marker': 'o'}),\n                     ('R', {'color': 'r', 'marker': '*'}),\n                     ('ACA', {'color': 'k', 'marker': 'D', 'markersize': 7})\n                    ])\ndef plotaavso(ax):\n    for band in bands:\n        ind = (aavso['Band'] == band)\n        ax.plot(aavso['JD'][ind]-2400000.5, aavso['Mag'][ind], linestyle='None', **bands[band], label=band)\n```\n\n\n```python\nobstimes = [[Time(lc[0]['TIME_MIN'][0], format='cxcsec').mjd, \n             Time(lc[0]['TIME_MAX'][-1], format='cxcsec').mjd] for lc in lccurves]\n# Add Chandra ACA magnitudes\naavso.add_row({'JD': Time(lccurves[1][0]['TIME'].mean(), format='cxcsec').jd, 'Mag': 11.5, 'Band': 'ACA'})\naavso.add_row({'JD': Time(lccurves[2][0]['TIME'].mean(), format='cxcsec').jd, 'Mag': 10.9, 'Band': 'ACA'})\naavso.add_row({'JD': Time(lccurves[3][0]['TIME'].mean(), format='cxcsec').jd, 'Mag': 11.1, 'Band': 'ACA'})\n```\n\n\n```python\nfig = plt.figure(figsize=(10, 5))\nax = fig.add_subplot(111)\nplotaavso(ax)\nax.set_xlim([57000, 58150])\nax.invert_yaxis()\n```\n\n\n```python\nfrom matplotlib.ticker import MaxNLocator, MultipleLocator\n    \nfrom matplotlib.transforms import Bbox, TransformedBbox, \\\n    blended_transform_factory, Affine2D\n\nfrom mpl_toolkits.axes_grid1.inset_locator import BboxPatch, BboxConnector,\\\n    BboxConnectorPatch\n\n# code for zoom effects taken and modified from http://matplotlib.org/users/annotations_guide.html\ndef connect_bbox(bbox1, bbox2,\n                 loc1a, loc2a, loc1b, loc2b,\n                 prop_lines, prop_patches=None):\n    if prop_patches is None:\n        prop_patches = prop_lines.copy()\n        prop_patches[\"alpha\"] = prop_patches.get(\"alpha\", 1)*0.2\n\n    c1 = BboxConnector(bbox1, bbox2, loc1=loc1a, loc2=loc2a, **prop_lines)\n    c1.set_clip_on(False)\n    c2 = BboxConnector(bbox1, bbox2, loc1=loc1b, loc2=loc2b, **prop_lines)\n    c2.set_clip_on(False)\n\n    bbox_patch1 = BboxPatch(bbox1, **prop_patches)\n    bbox_patch2 = BboxPatch(bbox2, **prop_patches)\n\n    p = BboxConnectorPatch(bbox1, bbox2,\n                           # loc1a=3, loc2a=2, loc1b=4, loc2b=1,\n                           loc1a=loc1a, loc2a=loc2a, loc1b=loc1b, loc2b=loc2b,\n                           **prop_patches)\n    p.set_clip_on(False)\n\n    return c1, c2, bbox_patch1, bbox_patch2, p\n\n\ndef zoom_effect(ax1, ax2, xtrans=Affine2D(), **kwargs):\n    \"\"\"\n    ax1 : the main axes\n    ax2 : the zoomed axes\n\n    connect ax1 & ax2. The x-range of (xmin, xmax) in both axes will\n    be marked.  The keywords parameters will be used ti create\n    patches. The xmin & xmax will be taken from the\n    ax1.viewLim.\n    \"\"\"\n\n    tt = ax1.transScale + (ax1.transLimits + ax2.transAxes)\n    trans = blended_transform_factory(xtrans + ax2.transData, tt)\n\n    mybbox1 = ax1.bbox\n    mybbox2 = TransformedBbox(ax1.viewLim, trans)\n\n    prop_patches = kwargs.copy()\n    prop_patches[\"ec\"] = \"none\"\n    prop_patches[\"alpha\"] = 0.2\n\n    # The inversion messes up the coner points.\n    # This is tweaked for inverted axes.\n    # I'm sure ther is some clever way to use the right transforms for the y axis \n    # to take care of that automatically, but for \n    # a one-off script it's much simpler to just adjust the corners by hand.\n    if ax1.yaxis_inverted():\n        loc2a = 2\n        loc2b = 1\n    else:\n        loc2a = 3\n        loc2b = 4\n    \n    c1, c2, bbox_patch1, bbox_patch2, p = \\\n        connect_bbox(mybbox1, mybbox2,\n                     loc1a=2, loc2a=loc2a, loc1b=1, loc2b=loc2b,\n                     prop_lines=kwargs, prop_patches=prop_patches)\n\n    #ax1.add_patch(bbox_patch1)\n    ax2.add_patch(bbox_patch2)\n    ax2.add_patch(c1)\n    ax2.add_patch(c2)\n    ax2.add_patch(p)\n\n    return c1, c2, bbox_patch1, bbox_patch2, p\n```\n\n\n```python\nfig = plt.figure(figsize=(8, 13))\nax00 = fig.add_subplot(511)\nax11 = fig.add_subplot(512)\nax21 = fig.add_subplot(537)\nax22 = fig.add_subplot(538, sharey=ax21)\nax23 = fig.add_subplot(539, sharey=ax21)\n\n# Set up second x-axis for top plot that is labeled in years\nax00years = ax00.twiny()\nax11years = ax11.twiny()\n\ndef years(tmjd):\n    return Time(tmjd, format='mjd').decimalyear\n\ndef update_ax11years(ax11):\n   y1, y2 = ax11.get_xlim()\n   ax11years.set_xlim(years(y1), years(y2))\n   ax11.figure.canvas.draw()\n\ndef update_ax00years(ax00):\n   y1, y2 = ax00.get_xlim()\n   ax00years.set_xlim(years(y1), years(y2))\n   ax00.figure.canvas.draw()\n\n# automatically update ylim of ax2 when ylim of ax1 changes.\nax00.callbacks.connect(\"xlim_changed\", update_ax00years)\nax11.callbacks.connect(\"xlim_changed\", update_ax11years)\n\nfor ax in fig.axes:\n    plotaavso(ax)\n    \nfor ax in fig.axes:\n    for i in range(4):\n        ax.bar(obstimes[i][0], height=10, width=obstimes[i][1]-obstimes[i][0], bottom=8, align='edge', \n               color='0.5', edgecolor='0.5')\n\nax00.invert_yaxis()\nax11.invert_yaxis()\nax00.set_xlim([52000, 58150])\nax11.set_xlim([56200, 58100])\n\ndtime = 15.\nfor i, ax in enumerate([ax21, ax22, ax23]):\n    ax.set_xlim(obstimes[i][0] - dtime, obstimes[i][1] + dtime)\n    ax.get_xaxis().get_major_formatter().set_useOffset(False)\n    ax.xaxis.set_major_locator( MaxNLocator(nbins=4, steps=[1, 5, 10]) )\nplt.setp(ax22.get_yticklabels(), visible=False)\nplt.setp(ax23.get_yticklabels(), visible=False)\n\n\n\nax00.legend(numpoints=1, loc='lower left')\nax11.set_ylabel('mag')\nax21.set_ylabel('mag')\nax22.set_xlabel('time [MJD]')\nax00years.set_xlabel('time [years]')\n\nax21.set_ylim([13.5, 10])\nax11.set_ylim([15, 9])\nax00.set_ylim([15, 9])\n\nwidth = np.array([lc[0]['t'][-1] for lc in lccurves])\nwidth = width / width.sum() * 0.8  # last factor is scale factor to make space for label left of plot\ndy = [0.11, 0.11, 0.06]\nypos = [0.1, 0.21, 0.32]\naxes = []\nfor y in range(3):\n    for x in range(4):\n        kwargs = {}\n        if y != 0:\n            kwargs['sharex'] = axes[x]\n        if x != 0:\n            kwargs['sharey'] = axes[y * 4]\n        axes.append(fig.add_axes((.1 + np.sum(width[0:x]) + x * 0.02, ypos[y], width[x], dy[y]), **kwargs))\n\nfor j in range(3):\n    for i in [1, 2, 3]:\n        plt.setp(axes[j * 4 + i].get_yticklabels(), visible=False)\n        \nfor j in [1, 2]:\n    for i in range(4):\n        plt.setp(axes[j * 4 + i].get_xticklabels(), visible=False)\n    \nfor i, obsid in enumerate(obsids):\n    axes[0 * 4 + i].errorbar(lccurves[i][0]['t']/1e3, lccurves[i][0]['NET_RATE_all'] * 1e3, lccurves[i][0]['ERR_RATE_all'] * 1e3, \n                             label='0.3-9.0 keV', color='b', lw=5, alpha=0.3)\n    axes[0 * 4 + i].plot(lccurves[i][0]['t']/1e3, lccurves[i][0]['NET_RATE_soft'] * 1e3, \n                         color='b', ls=':', label='0.3-1.0 keV')\n    axes[0 * 4 + i].plot(lccurves[i][0]['t']/1e3, lccurves[i][0]['NET_RATE_hard'] * 1e3, \n                         color='b', ls='--', label='1.0-9.0 keV')\n    axes[1 * 4 + i].errorbar(lccurves[i][1]['t']/1e3, lccurves[i][1]['NET_RATE_all'] * 1e3, lccurves[i][1]['ERR_RATE_all'] * 1e3,\n                             label='0.3-9.0 keV', color='g', lw=5, alpha=0.3)\n    axes[1 * 4 + i].plot(lccurves[i][1]['t']/1e3, lccurves[i][1]['NET_RATE_soft'] * 1e3, \n                         color='g', ls=':', label='0.3-1.0 keV')\n    axes[1 * 4 + i].plot(lccurves[i][1]['t']/1e3, lccurves[i][1]['NET_RATE_hard'] * 1e3, \n                     color='g', ls='--', label='1.0-9.0 keV')\n    #axes[2 * 4 + i].set_title(obsid)\n    if i > 0:\n        axes[2 * 4 + i].plot(lcaca[i-1]['time'] / 1e3, lcaca[i - 1]['mag'], color='k')\n    \naxes[8].yaxis.set_major_locator( MaxNLocator(nbins=4) )\naxes[1].legend()\n\nfor i in [0, 1, 2, 3]:\n    axes[i].xaxis.set_major_locator( MultipleLocator(10) )\n    axes[i].set_xlim(-2, None)\naxes[0].set_ylim(0, 0.022 * 1e3)\naxes[4].set_ylim(0, 0.075 * 1e3)   \naxes[8].invert_yaxis()\n#axes[5].legend(fontsize=10, loc='upper left')\naxes[0].set_ylabel('              net X-ray counte rate [cts/ks]')\naxes[1].set_xlabel('time from beginning of observation [ks]')\naxes[8].set_ylabel('ACA [mag]')\naxes[4].text(0., 60., 'RW Aur B')\naxes[0].text(0, 2., 'RW Aur A')\naxes[8].text(0, 11.1, 'RW Aur A + B\\n(unresolved)')\naxes[8].text(10, 11.4, 'no ACA data', color='0.5')\naxes[8].text(35., 11, '2013-Jan')\naxes[9].text(15, 11., '2015-Apr')\naxes[10].text(15, 11.5, '2017-Jan-09')\naxes[11].text(-2, 11.5, '2017\\nJan-11')\n\nzoom_effect(ax11, ax00, color='0.5')\nzoom_effect(ax21, ax11, color='0.5')\nzoom_effect(ax22, ax11, color='0.5')\nzoom_effect(ax23, ax11, color='0.5')\n\nzoom_effect(axes[8], ax21, xtrans=Affine2D.from_values(1./(24*3600/1000), 0, 0, 1, obstimes[0][0], 0), color='0.5')\nzoom_effect(axes[9], ax22, xtrans=Affine2D.from_values(1./(24*3600/1000), 0, 0, 1, obstimes[1][0], 0), color='0.5')\nzoom_effect(axes[10], ax23, xtrans=Affine2D.from_values(1./(24*3600/1000), 0, 0, 1, obstimes[2][0], 0), color='0.5')\nzoom_effect(axes[11], ax23, xtrans=Affine2D.from_values(1./(24*3600/1000), 0, 0, 1, obstimes[3][0], 0), color='0.5')\n\nfig.subplots_adjust(wspace=0.02, hspace=.35, left=0.1, right=0.95)\n\nfig.savefig(os.path.join(figout, 'lc.pdf'), bbox_inches='tight')\nfig.savefig(os.path.join(figout, 'lc.png'), bbox_inches='tight', dpi=600)\n```\n\\begin{figure*}[ht!]\n    \\centering\n    \\includegraphics[width=0.8\\textwidth]{lc}\n    \\caption{\\emph{top three rows} Optical lightcurve of RW~Aur~AB from AAVSO data. The system is not spatially resolved in these observations. Grey vertical bands mark the times of \\emph{Chandra} observations.  ``Vis.'' are visual measurements without a standard filter, but the effective bandpass is typically fairly close to $V$ band. ACA is the band of the \\emph{Chandra} aspect control assembly.\n\\emph{bottom block: Chandra} lightcurves from ACA (optical, unresolved), X-rays from RW Aur B (green), and X-rays from RW Aur A (blue). For clarity, error bars for $1\\sigma$ uncertainties are only shown for the full band lightcurve. The increasing contamination on \\emph{Chandra}/ACIS means that a source with constant flux will produce a lower raw count rate in later observations. There are so few soft X-ray counts in RW~Aur~A in 2015 and 2017 that the dotted line almost exactly falls on the x-axis in 2015 and 2017. All lightcurves are background subtracted and binned to one hour.}\n    \\label{fig:lc}\n\\end{figure*}\n#### Optical lightcurves\n\nFigure~\\ref{fig:lc} (top rows) shows a long-term lightcurve of the RW~Aur~AB system. The first \\emph{Chandra} observation (marked by the first gray vertical line) took place during a bright state which had been the long-term average for several decades with $m_V\\approx 10.5$~mag. The second \\emph{Chandra} dataset was taken in an obscured state with $m_V=12$~mag in 2015. At the end of 2016, RW~Aur~AB briefly reached a bright state again, before fading back to $m_V=11.7$ during the \\emph{Chandra} observations in January 2017. Later in 2017, the flux climbed back to a bright state again for a short time, just to drop again towards the end of 2017. Unfortunately, there is a gap in the optical data of a few days right around the \\emph{Chandra} observation. However, while RW~Aur~AB is known to have some variation on time scales of days and hours \\citep{2016MNRAS.463.4459B}, the lightcurve around the 2017 observations seems relatively smooth.\nThe \\emph{Chandra}/ACA monitoring shows steady lightcurves with smooth variability on the 0.1~mag level during the observations and a difference of about 0.2~mag between the two observations in 2017 which are about two days apart. \\citet{2016MNRAS.463.4459B} determine that the variability of RW~Aur~A on time scales of hours is irregular, which can be explained by changes in the accretion rate. Our data are consistent with this scenario, but the \\emph{Chandra} observations by itself are too short to distinguish this from the periodic variability that hot (accretion) or cold (magnetic) spots would produce when they rotate in and out of view.\n\nWe interpolate the optical lightcurves to obtain values during the \\emph{Chandra} observation (table~\\ref{tab:BVR}). In 2015, there are observations within a few hours of the \\emph{Chandra} data in all bands. In all cases, the uncertainty is dominated by the variability of the target and we estimate the error on the optical magnitudes to 0.2~mag. Within this uncertainty, RW~Aur~AB is brighter by 0.5~mag in $B$, $V$, $R$, and the ACA band during the 2017 \\emph{Chandra} observation, compared with 2015. We do not see significant changes in the optical color between those observations.\n\nNone of the optical data presented here resolves the two components of the RW~Aur~AB system. \\citet{2015IBVS.6126....1A} show that RW~Aur~B is also variable, but to a much lesser degree than RW~Aur~A. Comparing observations from 1994 and 2014 they find that RW~Aur~B has become brighter by about 0.7~mag with almost no color variability. They suggest this to be due to a dust cloud with large grains moving through our line-of-sight, analogous to what is discussed for RW~Aur~A. We assume that this evolution is slow and subtract the long-term average of the RW~Aur~B fluxes (table~\\ref{tab:BVR}) to obtain the flux of RW~Aur~A. Within the uncertainties, we do not see changes in color. On the other hand, changes in $B-V$ color up to about 0.3~mag ($1\\sigma$ confidence range) are also possible.\n\n#### \\emph{Chandra} X-ray  lightcurves\n\nFigure~\\ref{fig:lc} (bottom) shows X-ray lightcurves for both components of the RW~Aur system and the ACA lightcurve where data exist. RW~Aur~B shows X-ray variability in every observation, but the average count rates are all similar. During the first observation, the flux increases smoothly by 30\\% and decreases by a similar amount in the second observation. In 2017 there is a short flare in the hard band that lasts about 5~ks. The second observation in 2017 shows rapid decline of the hard X-ray flux, possibly the tail end of a flare. Note that the count rate in the soft band is lower for the later observations, because contamination builds up on \\emph{Chandra}/ACIS and the effective area declines between epochs. \n% Also,  the raw count rate shown in the figure underpredicts the photon flux in 2017 by a few percent due to pile-up. \nRW~Aur~A is fainter than RW~Aur~B in all observations. For RW~Aur~A, significant variability within an observation is seen only towards the end of the first observation in 2017 when the flux triples. The count rate in 2015 is more than an order of magnitude below the value seen in 2013 before the optical dimming started. In the 2017 observations, the count rate in the hard band reaches the pre-dimming level again, but essentially no signal is detected in the soft band.\n\n\n\n```python\n# Check if last bin in 17764 is responsible for an unsusually large fraction for 6.63 keV photons\nsrca = Table.read(os.path.join(datadir, '17764_srca.fits'), hdu=1)\n\nplt.scatter(srca['time'], srca['energy'])\nplt.ylim(6000, 7000)\n```\n\n\n```python\nsrca['time'][0], srca['time'][0]+30000\n```\n\n\n\n\n    (600332393.59311604, 600362393.59311604)\n\n\n\n\n```python\n# output->LaTeX\n\ndef mA(mAB, mB):\n    return -2.5 * np.log10(10**(-mAB/2.5) - 10**(-mB/2.5))\n\ndef sigma_mA(mAB, mB, sig_AB, sig_B):\n    nominator = sig_AB**2*10.**(-0.8*mAB) + sig_B**2 * 10.**(-0.8*mB)\n    demoninator = 10.**(-mAB/2.5) - 10.**(-mB/2.5)\n    return np.sqrt(nominator) / demoninator\n\n\ntab = Table()\ntab['band'] = ['B', 'V', 'R']\ntab['$m_B$'] = np.array([14.5, 13.2, 12.3])\ntab['$\\sigma_B$'] = 0.3\ntab['$m_{AB}$ 2015'] = np.array([13., 12.2,11.5])\ntab['$m_{AB}$ 2017'] = np.array([12.5,11.7, 11.2])\ntab['$\\sigma_{AB}$'] = 0.2\ntab['$m_{A}$ 2015'] = mA(tab['$m_{AB}$ 2015'], tab['$m_B$'])\ntab['$\\sigma_A$ 2015'] = sigma_mA(tab['$m_{AB}$ 2015'], tab['$m_B$'], tab['$\\sigma_{AB}$'], tab['$\\sigma_B$'])\ntab['$m_{A}$ 2017'] = mA(tab['$m_{AB}$ 2017'], tab['$m_B$'])\ntab['$\\sigma_A$ 2017'] = sigma_mA(tab['$m_{AB}$ 2017'], tab['$m_B$'], tab['$\\sigma_{AB}$'], tab['$\\sigma_B$'])\nfor col in tab.columns:\n    if col != 'band':\n        tab[col].format = '{:3.1f}'\n        \n#latexdict = copy.deepcopy(latex.latexdicts['AA'])\n#latexdict['tabletype'] = 'table*'\n#latexdict['caption'] = '\\\\label{tab:BVR} Optical flux (in mag) for RW~Aur.'\n# tab.write(sys.stdout, format='ascii.latex', latexdict=latexdict)\n\n# Now re-format table to have value +- sigma in one column. Easier to read by eye and for a table with\n# just three columns that's what most people do.\n\nprint(r'\\begin{table*}')\nprint(r'\\caption{\\label{tab:BVR} Optical brightness for RW~Aur.}')\nprint(r'\\begin{tabular}{cccccc}')\nprint(r'\\hline \\hline')\nprint(r'RW Aur & B$^a$ & AB & AB$^b$ & A$^c$ & A$^c$ \\\\')\nprint(r'year & 2014 & 2015 &  2017 & 2015 & 2017 \\\\')\nprint(' unit' + '& mag ' * 5 + r'\\\\')\nfor i, b in enumerate('BVR'):\n    print(r'${}$ & ${:3.1f} \\pm {:3.1f} $ & ${:3.1f} \\pm {:3.1f} $ & ${:3.1f} \\pm {:3.1f} $ & ${:3.1f} \\pm {:3.1f} $ & ${:3.1f} \\pm {:3.1f} $\\\\'.format(tab['band'][i],\n                                                                                                   tab['$m_B$'][i],\ntab['$\\sigma_B$'][i], tab['$m_{AB}$ 2015'][i], tab['$\\sigma_{AB}$'][i], tab['$m_{AB}$ 2017'][i], tab['$\\sigma_{AB}$'][i],\ntab['$m_{A}$ 2015'][i], tab['$\\sigma_A$ 2015'][i], tab['$m_{A}$ 2017'][i], tab['$\\sigma_A$ 2017'][i]))\n\nprint(r'\\hline')\nprint(r'\\end{tabular}\\\\')\nprint(r'$^a$:\\protect{\\citet{2015IBVS.6126....1A}}\\\\')\nprint(r'$^b$: Interpolated between observations taken a few days before and after the \\emph{Chandra} observations.\\\\')\nprint(r'$^c$: These values are inferred from the unresolved measurements of RW Aur AB by subtracting the RW~Aur~B flux from 2014, assuming that the flux from RW~Aur~B changes only on long time scales. See section~\\ref{sect:opticallightcurves} for details.\\\\')\nprint(r'\\end{table*}')\n```\n\n    \\begin{table*}\n    \\caption{\\label{tab:BVR} Optical brightness for RW~Aur.}\n    \\begin{tabular}{cccccc}\n    \\hline \\hline\n    RW Aur & B$^a$ & AB & AB$^b$ & A$^c$ & A$^c$ \\\\\n    year & 2014 & 2015 &  2017 & 2015 & 2017 \\\\\n     unit& mag & mag & mag & mag & mag \\\\\n    $B$ & $14.5 \\pm 0.3 $ & $13.0 \\pm 0.2 $ & $12.5 \\pm 0.2 $ & $13.3 \\pm 0.3 $ & $12.7 \\pm 0.2 $\\\\\n    $V$ & $13.2 \\pm 0.3 $ & $12.2 \\pm 0.2 $ & $11.7 \\pm 0.2 $ & $12.8 \\pm 0.4 $ & $12.0 \\pm 0.3 $\\\\\n    $R$ & $12.3 \\pm 0.3 $ & $11.5 \\pm 0.2 $ & $11.2 \\pm 0.2 $ & $12.2 \\pm 0.5 $ & $11.7 \\pm 0.4 $\\\\\n    \\hline\n    \\end{tabular}\\\\\n    $^a$:\\protect{\\citet{2015IBVS.6126....1A}}\\\\\n    $^b$: Interpolated between observations taken a few days before and after the \\emph{Chandra} observations.\\\\\n    $^c$: These values are inferred from the unresolved measurements of RW Aur AB by subtracting the RW~Aur~B flux from 2014, assuming that the flux from RW~Aur~B changes only on long time scales. See section~\\ref{sect:opticallightcurves} for details.\\\\\n    \\end{table*}\n\n\n#### \\emph{XMM-Newton} lightcurves\n\n\n```python\nOMlcs = glob(os.path.join(datadirXMM, '*', '*OM*TIMESR*.FIT'))\nomlc = table.vstack([Table.read(f)[:-1] for f in OMlcs], metadata_conflicts='silent')\nomlc.sort('TIME')\n\npn0390 = Table.read(os.path.join(datadirXMM, '0401870301', 'PN_0390_lc.fits'), hdu=1)\npn0310 = Table.read(os.path.join(datadirXMM, '0401870301', 'PN_0310_lc.fits'), hdu=1)\npn1090 = Table.read(os.path.join(datadirXMM, '0401870301', 'PN_1090_lc.fits'), hdu=1)\n\nfor tab in [omlc, pn0390, pn0310, pn1090]:\n    tab['t'] = (tab['TIME'] - omlc['TIME'][0]) / 1e3\n```\n\n\n```python\nfig = plt.figure(figsize=(4,3))\naxpn = fig.add_subplot(111)\naxom = axpn.twinx()\nlom = axom.plot(omlc['t'], omlc['RATE'], 'ko', label='OM ' + omlc.meta['FILTER'])\nlpn = axpn.errorbar(pn0390['t'], pn0390['RATE'], pn0390['ERROR'], \n                    label='0.3-9.0 keV', color='r', lw=5, alpha=0.3)\nlpn1 = axpn.plot(pn0310['t'], pn0310['RATE'], color='r', ls=':', label='0.3-1.0 keV')\nlpn2 = axpn.plot(pn1090['t'], pn1090['RATE'], color='r', ls='--', label='1.0-9.0 keV')\n\nobjs = [lpn, lpn1[0], lpn2[0], lom[0]]\n\naxpn.legend(objs, [l.get_label() for l in objs])\naxpn.set_xlabel('Time [ks]')\naxpn.set_ylabel('PN counts rate [cts/s]')\naxom.set_ylabel('OM counts rate [cts/s]')\n\naxpn.yaxis.label.set_color(lpn[0].get_color())\naxom.yaxis.label.set_color(lom[0].get_color())\n\naxpn.tick_params(axis='y', colors=lpn[0].get_color())\naxom.tick_params(axis='y', colors=lom[0].get_color())\n\nfig.savefig(os.path.join(figout, 'xmmlc.pdf'), bbox_inches='tight')\n```\n\n\n```python\nplt.plot(pn0390['t'], (pn1090['RATE'] - pn0310['RATE'] / pn0390['RATE']))\nplt.ylabel('Hardness ratio')\n```\n\n\\begin{figure}[ht!]\n    \\plotone{xmmlc.pdf}\n    \\caption{Count rates in the \\emph{XMM-Newton} observation in 2007 which did not resolve RW~Aur~AB. The X-ray count rate is mostly flat up to 20~ks, when a massive flare started. As in Fig.~\\ref{fig:lc}, error bars are shown only for the full-band lightcurve for clarity; they are comparable to the thickness of the line. In the flare, the count rate increases by factor of 20. The OM observed in a UV band (errors bars are smaller than symbols). There is an increase in OM count rate, but it rises several hours after the X-ray flare.}\n    \\label{fig:xmmlc}\n\\end{figure}\n\nThe first half of the \\emph{XMM-Newton} observation in 2007 shows quiescent emission. A large flare erupted around 20~ks into the observation with an increase in count rate by a factor of $\\sim20$ (Fig.~\\ref{fig:xmmlc}). At the same time, the hardness ratio ($\\frac{H-S}{H+S}$, where $H$ is the count rate in the hard band of Fig.~\\ref{fig:xmmlc} and $S$ the count rate in the soft band) increases from -0.4 to 2.5 at the peak of the flare, before it decays back down to 0 at the end of the observation.\n\nWe compared the centroid of the X-ray emission in the quiescent and the flare phase and they agree to about 0.1\\arcsec{} (with statistical uncertainties of 0.4\\arcsec{} and 0.2\\arcsec{}, respectively). The absolute astrometry of the \\emph{XMM-Newton} observation is insufficient to associate the centroid with either RW~Aur A or B. If RW~Aur~A and B contribute to the quiescent emission, the pre-flare centroid would be located between them close to the brighter component (in the \\emph{Chandra} observations RW~Aur~B is always brighter than RW~Aur~A). RW~Aur~A and B are separated by 1.4\\arcsec{}. The count rate (and thus centroid of the detected events) is certainly dominated by the flaring source during the flare. So, if RW~Aur A and B had equal X-ray brightness in the quiescent phase, the centroid position in the flare should shift by 0.7\\arcsec{}. A much smaller value is observed and we thus conclude that the flare most likely occurs on the same component that dominated the quiescent X-ray emission, but we cannot identify from the \\emph{XMM-Newton} observation if this component is RW~Aur~A or B.\n\n\n```python\n# In the following fields, try an special analysis of XMM data. \n# Does the centroid of the photons change with energy?\n# First, get data files from reduced XMM data\nXMMfiltslist = glob(os.path.join(datadirXMM, '*', '*filts.fits'))\nXMMfiltslist.sort()\nXMMfiltslist\n```\n\n\n\n\n    ['/melkor/d1/guenther/downdata/XMM/RWAur/0401870301/RWAur_1319_0401870301_EMOS1_S001_filts.fits',\n     '/melkor/d1/guenther/downdata/XMM/RWAur/0401870301/RWAur_1319_0401870301_EMOS2_S002_filts.fits',\n     '/melkor/d1/guenther/downdata/XMM/RWAur/0401870301/RWAur_1319_0401870301_EPN_S003_filts.fits',\n     '/melkor/d1/guenther/downdata/XMM/RWAur/0401870301/RWAur_noflare_1319_0401870301_EMOS1_S001_filts.fits',\n     '/melkor/d1/guenther/downdata/XMM/RWAur/0401870301/RWAur_noflare_1319_0401870301_EMOS2_S002_filts.fits',\n     '/melkor/d1/guenther/downdata/XMM/RWAur/0401870301/RWAur_noflare_1319_0401870301_EPN_S003_filts.fits']\n\n\n\n\n```python\npn = Table.read(XMMfiltslist[2], hdu=1)\npn.sort('PI')\n```\n\n\n```python\n# Get position of A and B in DS9 by hand. Much faster than parsing the header values for event list.\n# Project everything on the A-B line. The direction perpendicular to that is not important for us.\nvecAB = np.array([27145., 27557]) - np.array([27175., 27549])\nvecAB = vecAB / np.linalg.norm(vecAB)\nvecevpos = np.empty((len(pn), 2))\nvecevpos[:, 0] = pn['X']\nvecevpos[:, 1] = pn['Y']\npn['proj'] = np.sum(vecevpos * vecAB, axis=1)\n```\n\n\n```python\n# Make a running average of the x,y pos in chunks of +-w photons (effectively a moving boxcar on the energy sorted\n# photon list).\nw = 200\nres = np.zeros(len(pn) - 2 * w)\nsig = np.zeros_like(res)\nfor i in range(w, len(pn) - w):\n    res[i - w] = np.median(pn['proj'][i - w: i + w])\n    sig[i - w] = np.std(pn['proj'][i - w: i + w])\n    \n# Median is better than mean, because it's not influenced as much by the boundaries of the photons in the input fits file\n# (a  circle centered on the peak of the count distribution).\n```\n\n    /nfs/melkor/d1/guenther/soft/anaconda/envs/py35/lib/python3.5/site-packages/numpy/core/fromnumeric.py:639: UserWarning: Warning: 'partition' will ignore the 'mask' of the MaskedColumn.\n      a.partition(kth, axis=axis, kind=kind, order=order)\n\n\n\n```python\nplt.plot(pn['PI'][w: -w: 2 * w], res[:: 2 * w])\n#plt.errorbar(pn['PI'][w: -w: 2 * w], res[:: 2 * w], sig[:: 2 * w])\n\n# I looked at different values for w, and PN and MOS and I don't see anything. Thus, this analysis stays here for\n# reference, but does not get it's own section in the paper.\n```\n\n\n```python\npn['TIME'][0]\n```\n\n\n\n\n    288476254.54848468\n\n\n\n\n```python\nnoflare = pn['TIME'] < 288466000\nh1 = np.histogram(pn['proj'][noflare], bins=np.arange(-19800, -18600, 2), density=True)\nh2 = np.histogram(pn['proj'][~noflare], bins=np.arange(-19800, -18600, 2), density=True)\nplt.plot(h1[1][:-1], h1[0])\nplt.plot(h2[1][:-1], h2[0])\n```\n\n\n```python\n# Writing as comment to prevent LaTeX export\n\n# The plot above indicates not significant difference in the position of the flare and noflare centroid.\n# A similar (but more thourough) analysis is running epdetec-chain in SAS.\n# I did that and found that there is no indication of a shift in centroid during the flare and that the errors are \n# so small, that the flare essentially has to come from the source that dominats the continuum emission.\n\nsrcnoflare = Table.read(os.path.join(datadirXMM, '0401870301', 'emlnoflare.fits'))\nsrcflare =  Table.read(os.path.join(datadirXMM, '0401870301','emlflare.fits'))\nsrc1noflare = SkyCoord(srcnoflare['RA'][0], srcnoflare['DEC'][0], unit='deg')\nsrc1flare = SkyCoord(srcflare['RA'][0], srcflare['DEC'][0], unit='deg')\nsrc1noflare.separation(src1flare).arcsec, srcnoflare['RADEC_ERR'][0], srcflare['RADEC_ERR'][0]\n```\n\n\n\n\n    (0.10346953082180739, 0.41059273, 0.16118589)\n\n\n\n\n```python\nRWAurA = SkyCoord.from_name('RW Aur A')\nRWAurA.separation(src1noflare).arcsec, RWAurA.separation(src1flare).arcsec\n```\n\n\n\n\n    (3.5079272455734327, 3.505388353447638)\n\n\n\n### X-ray spectra\n\nWe first discuss the \\emph{XMM-Newton} data from 2007 where RW~Aur~AB is unresolved, but we have the most signal (section~\\ref{sect:xmmdata}). Next, we turn to the \\emph{Chandra} observations where RW~Aur~B (section~\\ref{sect:chan:rwb}) and RW~Aur~A (section~\\ref{sect:chan:rwa}) are spatially separated, but the spectra from RW~Aur~A could be contaminated by the close-by, brighter RW~Aur~B. Of particular importance is a strong emission feature at 6.63~keV in the spectrum of RW~Aur~A in 2017, which we analyze in detail in section~\\ref{sect:2017}.\n\nWe use the photospheric abundances given in table~1 of \\citet{2009ARA&A..47..481A} as reference throughout this paper. Uncertainties in this section are given as 90\\% confidence ranges.\n\n#### 2007 \\emph{XMM-Newton} data\n\\label{sect:xmmdata}\n\n\n```python\nIPython.display.Image(filename=os.path.join(figout, 'XMM.png'))\n```\n\n\\begin{figure}[ht!]\n\\plotone{XMM_cropped.pdf}\n\\caption{\\emph{XMM-Newton}/PN data with best-fit models in the quiescent and the flare phase. The RW~Aur~AB binary is unresolved. Data are binned to 20 counts per bin. Error bars in the plot are $1\\sigma$ statistical uncertainties. The lines show the best-fit model with the parameters from table~\\ref{tab:specfits}.}\n    \\label{fig:XMM}\n\\end{figure}\n\nThe \\emph{XMM-Newton} spectra from RW~Aur~AB are displayed in figure~\\ref{fig:XMM} separated into the quiescent phase (the first 20~ks of the observation) and the flare phase (after 20~ks), see figure~\\ref{fig:xmmlc}. Our spectral model consists of two optically thin, collisionally excited plasma model components \\citep[APEC,][]{2012ApJ...756..128F} and a cold photoelectric absorber. We fit abundances in three groups of elements. We combine Mg, Si, and Fe into one group, because they all have very similar first ionization potential (FIP) values (7.6-8.1 eV). The FIP of Ne is 21.6~eV and is fitted on its own. We fix the abundances of elements with medium FIP values (S, O, N, and C all have FIP between 10 and 15 eV) to 1 because absolute abundances cannot be determined without grating spectroscopy; if we, for example, multiplied all abundances in the model by three and reduced the emission measure  $EM = \\int n_i n_e \\mathrm{d}V$ ($n_i$ and $n_e$ are the ion and electron number density, respectively, which are integrated over the emitting volume $V$) by the same factor, the model would predict an almost identical spectrum. We investigated a possible change in $N_\\mathrm{H}$ or abundance between the quiescent and the flare phase, but did not see statistically significant differences and settled on a model where $N_\\mathrm{H}$ and abundances are the same in the quiescent and the flare phase. Furthermore, we coupled the temperature components, so that the fits in the quiescent and the flare phase have the same temperatures, but different emission measures. This simplifies the interpretation, while still providing a good fit. The model thus has nine parameters: $N_\\mathrm{H}$, the abundances of Ne and Fe, the temperature of the cool and the hot emission component, and the $EM$ of the cool and hot component in the quiescent and the flare phase. We fit the signal from the PN, MOS1, and MOS2 cameras on \\emph{XMM-Newton} simultaneously using a $\\chi^2$ statistic. The data are binned to 20 counts per bin. \nFit results are shown in table~\\ref{tab:specfits}. The reduced $\\chi^2$ of the model is only 0.7. Simpler models with fewer parameters (e.g.\\ only one emission component with a single temperature) can still fit the data with a reduced $\\chi^2$ around 1, but they show systematic deviations (e.g.\\ the data below 1~keV is consistently underpredicted) and thus we chose to present the two-temperature model.\n\nThe 2007 \\emph{XMM-Newton} spectrum of RW~Aur AB displays IFIP (inverse first ionization potential) abundances where the abundance of elements with a high FIP such as Ne are enhanced and Fe is reduced compared to solar abundances as seen in the Ne/Fe ratio. In the flare, the $EM$ in the cool component increases by a factor of four, while the $EM$ of the hot component increases by almost a factor of 30.\n\nThe observed spectrum shows an emission feature around 6.7~keV (figure~\\ref{fig:XMM}) both before and during the flare. This feature is fully compatible with Fe~{\\sc xxv} emission and is well-described by the plasma model fits. The hotter component of the plasma in the model is close to the peak formation temperature $\\mathrm{k}T=5.5$~keV (k is the Boltzmann constant) of the Fe~{\\sc xxv} 6.7~keV line. Given the higher $EM$ in the flare, this feature is stronger there. Observing a 6.7~keV emission line from hot plasma is not surprising, we only note this here because the \\emph{Chandra} spectra show a feature at a slightly lower energy in 2017 that is discussed in detail in section~\\ref{sect:2017}.\n\n\n```python\nnormem = 4 * np.pi * u.pc.to(u.cm)**2 * 140**2 * 1e14 * 1e-52\nlxfac = (4 * np.pi * (140.*(1 * u.pc).to(u.cm))**2).value\n```\n\n\n```python\n# Calcualte the VEM from the norms of the fit\n# For XMM\nnp.array([0.000455, 7.2e-5, 0.0002, 2e-5, 0.0019, 4e-4, 0.00545, 1e-4]) * normem\n# For Chandra RW Aur B\n# kt 1\nnp.array([1.7e-4, -8e-5, 1.6e-4, 2.6e-4, -1.2e-4, 2.4e-4, 1.4e-4, -7e-5, 1.5e-4]) * normem\n# kT2\nnp.array([2.8e-4, 3.2e-5, 4e-4, 5e-5, 3.3e-4, 4e-5]) * normem\n# Chandra RW Aur A\n# kT 1\nnp.array([4.8e-5, 1.7e-5, 5.5e-6, 1e-3, 2e-3, -1e-3, 4e-3]) * normem\n# kT2\nnp.array([4.1e-5, 7e-6, 2e-5, -1e-5, 3.3e-5, 8e-5]) * normem\n# Chandra RW Aur A, only 1 APEC component\nnp.array([7.2e-4, -4e-4, 1.9e-3]) * normem\n```\n\n\n\n\n    array([ 16.88494002,  -9.38052223,  44.55748061])\n\n\n\n\n```python\n# Calculate L_X\nnp.log10(lxfac * np.array([7.86e-13, 1.147e-11]))  # XMM\nnp.log10(lxfac * np.array([5.5e-13, 8.1e-13, 5.8e-13]))  # Chandra / RW Aur B\nnp.log10(lxfac * np.array([1.5e-13, 4.6e-14, 1.7e-11, 1.6e-12]))  # Chandra / RW Aur A\n```\n\n\n\n\n    array([ 29.54625828,  29.03292486,  31.60061595,  30.57428701])\n\n\n\n% This table is written by hand with the help of the scripts that convert units etc. The structure of the table is \n% just so complex with multicolumns etc. that it's not worth the effort to to write a general Python function to\n% format values and put them in.\n\n\\begin{table*}\n\\caption{\\label{tab:specfits} Parameters of X-ray model fits. Uncertainties are 90\\% confidence ranges.}\n\\begin{tabular}{lccccccccc}\n\\hline \\hline\nRW Aur & AB & AB & B & B & B & A & A & \\multicolumn{2}{c}{A}\\\\\nyear & 2007 & 2007 & 2013 & 2015 & 2017 & 2013 & 2015 & \\multicolumn{2}{c}{2017$^{a}$}\\\\\ninstrument & XMM & XMM & Chandra & Chandra & Chandra & Chandra & Chandra & \\multicolumn{2}{c}{Chandra}\\\\\n           & quiescent & flare & & & & & & 2 temp & 1 temp\\\\\n\\hline\n$N_\\mathrm{H}$ [$10^{21}$~cm$^{-2}$] & \\multicolumn{2}{c}{$2.62\\pm 0.02$} &\n             \\multicolumn{3}{c}{$3\\pm 1$} &\n             $1.1\\pm 0.1$ & $70^{+50}_{-30}$ $^c$ & $400 \\pm 100^c$ & $300 \\pm 100^c$\\\\\nk$T_1$  [keV]& \\multicolumn{2}{c}{$0.78\\pm 0.04$}\n           & \\multicolumn{3}{c}{$0.38 \\pm 0.05$} &\n           $0.6^{+0.1}_{-0.2}$ & =0.6 & $1.4^{+0.6}_{-0.3}$ & $3.1^{+1.8}_{-1.3}$\\\\\n$EM_1$  [$10^{52}$~cm$^{-3}$] & $11\\pm 2$ & $45\\pm 9$ &\n         $4^{+4}_{-2}$ & $6^{+6}_{-3}$ & $3^{+4}_{-2}$ &\n         $1.1 \\pm 0.4$ & $0.1^{+13}_{-0.1}$ & $50^{+90}_{-20}$ & $17^{+45}_{-9}$\\\\\nk$T_2$  [keV] & \\multicolumn{2}{c}{$6.0\\pm 0.3$} &\n       \\multicolumn{3}{c}{$2.0 \\pm 0.2$} &\n       =20 & =20 & =20 & --\\\\\n$EM_2$  [$10^{52}$~cm$^{-3}$]  & $4.7\\pm 0.5$ & $128 \\pm 2$ &\n      $7 \\pm 1$ & $9 \\pm 1$ & $8 \\pm 1$ &\n      $1.0 \\pm 0.2$ & $0.5^{+0.8}_{-0.2} $ & $1.9 \\pm 1.9$ & --\\\\\nabund$^b$: Fe & \\multicolumn{2}{c}{$0.12\\pm 0.03$} & \n         \\multicolumn{3}{c}{$0.3^{+0.2}_{-0.1}$} &\n         $0.5^{+0.2}_{-0.1}$ & =0.5 & $15^{+40}_{-8}$ & $5^{+3}_{-2}$\\\\\nabund$^b$: Ne & \\multicolumn{2}{c}{$1.2^{+0.5}_{-0.4}$} & \n         \\multicolumn{3}{c}{$2.2^{+1.2}_{-0.8}$} &\n         =1 & =1 & =1 & =1\\\\\n\\hline\nred. $\\chi^2$ (dof) & \\multicolumn{2}{c}{0.7 (1726)} & \n            \\multicolumn{3}{c}{0.7 (251)} &\n            \\multicolumn{4}{c}{Cash statistic}\\\\\n\\hline\nobserved flux$^d$ & 4.7 & 78 &\n             3.0 & 4.5 & 3.3 &\n             1.2 & 0.2 & 2.7 & 2.9\\\\\nintrinsic $\\log L_X^e$ & 30.3 & 31.4 &\n             30.1 & 30.3 & 30.1 &\n             29.5 & 29.0 & 31.6 & 30.6\\\\\n\\hline\n\\end{tabular}\\\\\n$^a$: Two different models are fit to the same dataset; the first one (2 temp) with two emission components at different temperature, the second one (1 temp) with a single temperature \\\\\n$^b$: Relative to solar abundances from \\protect{\\citet{2009ARA&A..47..481A}}\\\\\n$^c$: These numbers should be treated as lower limits. See section~\\ref{sect:chan:rwa} for discussion.\\\\\n$^d$: in units of $10^{-13}$erg~s$^{-1}$~cm$^{-2}$ for the energy range 0.3-9.0~keV. Value is given for best fit model without uncertainties.\\\\\n$^e$: in units of erg~s$^{-1}$ for the energy range 0.3-9.0~keV. Value is given for best fit model without uncertainties.\n\\end{table*}\n\n\n\n\n```python\nimport json\ndef read_json_fit_results(filename):\n    with open(os.path.join(figout, filename)) as f:\n        fit = json.load(f)\n    for n in fit.keys():\n        if n not in ['redchi2', 'dof']:\n            fit[n] = np.array(fit[n])\n    for c in ['val', 'up', 'down']:\n        for i in range(len(fit[c])):\n            if fit[c][i] is None:\n                fit[c][i] = np.nan\n\n    normem = 4 * np.pi * u.pc.to(u.cm)**2 * 140**2 * 1e14 * 1e-52\n    for i in range(len(fit['name'])):\n        if 'norm' in fit['name'][i]:\n            for n in ['val', 'up', 'down']:\n                fit[n][i] = fit[n][i] * normem\n    # And dublicate the data here in a different format to make the printing scripts easier.\n    # Ideally, there should be some better interface between sherpa results and this, but it is beyond\n    # the scope of the current project to develop that.\n    for i in range(len(fit['name'])):\n        fit[fit['name'][i]] = {'val': fit['val'][i], 'up': fit['up'][i], 'down': fit['down'][i]}\n    return fit\n```\n\n#### \\emph{Chandra} spectra from RW Aur B\n\\label{sect:chan:rwb}\n\n\n```python\nIPython.display.Image(filename=os.path.join(figout, 'specB.png'))\n```\n\\begin{figure}[ht!]\n\\plotone{specB_cropped.pdf}\n\\caption{RW~Aur~B spectra extracted from \\emph{Chandra} data. Error bars in the plot are $1\\sigma$ statistical uncertainties. The lines show the best-fit model with the parameters from table~\\ref{tab:specfits}. The spectra are very similar, except for the lower number of counts at low energies in the 2017 observation. This is due to increased contamination on the ACIS detector and taken into account in fitting.}\n    \\label{fig:RWAurB}\n\\end{figure}\nThe three \\emph{Chandra} datasets from RW~Aur~B are qualitatively similar to each other (figure~\\ref{fig:RWAurB}); differences in the \\emph{Chandra} effective area at low-energies are taken into account by using the appropriate ARF file in the fitting. Background is negligible in all cases. The two datasets from 2017 are treated separately in the fit, but we impose the condition that the fit parameters are identical for those two datsets (the datasets are only merged for display purposes in figure~\\ref{fig:RWAurB}).\nWe fit the same model of one absorption component and two APEC plasma models that we used for the \\emph{XMM-Newton} data. Again, the value of the reduced $\\chi^2$ is low, but if we reduce the number of model parameters (e.g.\\ fit only one APEC component or fix the Ne and Fe abundance at solar values) we see systematic residuals in the fit.\n\nCompared to the \\emph{XMM-Newton} data with its prominent flare, the plasma temperatures are much lower. There is no plasma as hot as the component that gives rise to the 6.7~keV line in the \\emph{XMM-Newton} data. The absorbing column density and the abundance ratios are similar to the values found from the \\emph{XMM-Newton data}. It is thus plausible that the \\emph{XMM-Newton} observation was dominated by emission from RW~Aur~B.\n\n#### \\emph{Chandra} spectra from RW~Aur~A\n\\label{sect:chan:rwa}\n\\emph{Chandra} spectra from RW~Aur~A for the epochs 2013, 2015, and 2017 are shown in figure~\\ref{fig:spec:rwa}.\nIn 2017, RW~Aur~A is significantly brighter at high energies and shows a strong emission feature located at 6.63~keV (inset in figure~\\ref{fig:spec_17} and discussed in detail in section~\\ref{sect:2017}) that is not seen in previous observations. At the same time, there is very little signal at soft energies after accounting for the contamination by the wings of the PSF from RW~Aur~B. \nWe again fit a model with two thermal emission components and one absorption component. We add a model for the contamination by the RW~Aur~B PSF with the parameters of RW~Aur~B in table~\\ref{tab:specfits} to each RW~Aur~A spectral fit. The normalization of these components is set to account for the small fraction of the RW~Aur~B PSF that falls into the RW~Aur~A spectral extraction region. We calculate a normalization factor from the counts observed in the dashed regions in figure~\\ref{fig:regions} and then multiply it by the ratio of the areas of the RW~Aur~A extraction region and the dashed region. Since the total number of counts in the RW~Aur~A spectra is significantly lower than in the \\emph{XMM-Newton} data or in the RW~Aur~B spectra, we perform the fit using the Cash statistic (statistic \\texttt{cash} in Sherpa, see \\citet{2007ASPC..376..543D} and \\citet{1979ApJ...228..939C}), which correctly accounts for the Poissonian likelihood in low-count bins, but has the downside that is does not provide a goodness-of-fits statistic such as the reduced $\\chi^2$. As in section~\\ref{sect:chan:rwb} the datasets from 2017 are kept separate in the fitting process and are combined for display purposes only.\n\nThe decrease in soft ($\\lesssim$ 2 keV) X-ray flux from RW Aur~A is the result of a\nvariable absorbing column density whose extinction is higher in 2015 and 2017 than in the previously\nobserved optically bright state (2013; red in figure~\\ref{fig:spec:rwa}); the contamination of ACIS has a much smaller effect (compare with figure~\\ref{fig:RWAurB}).\n\n\n```python\nIPython.display.Image(filename=os.path.join(figout, 'spec.png'))\n```\n\n\n```python\nIPython.display.Image(filename=os.path.join(figout, 'spec_subtracted.png'))\n```\n\\begin{figure}[ht!]\n    \\plotone{spec_subtracted_cropped.pdf}\n    \\caption{X-ray spectra for RW~Aur~A. Points are observational data and lines show models from table~\\ref{tab:specfits} (for 2017, the \"2 temp\" model is shown). The two observations in 2017 are combined for display purposes only, and all data are shown background-subtracted for display purposes. Error bars indicate $1\\sigma$ uncertainties.}\n    \\label{fig:spec:rwa}\n\\end{figure}\nLike \\citet{2014ApJ...788..101S} we find that a hot plasma component is required to fit the RW~Aur~A spectrum in 2013, but the temperature of this component is poorly constrained. \\citet{2014ApJ...788..101S} discuss this in detail and show that a powerlaw component actually gives a slightly better fit than a collisionally-excited plasma, but we do not know of a physical process that could produce powerlaw emission in RW~Aur~A. Following \\citet{2014ApJ...788..101S} we fix the temperature of the hotter component at 20~keV. Furthermore, we find that the data constrain the Ne abundance insufficiently, and we thus fix this value at 1. \nGiven the low signal in 2015, even more assumptions are needed to fit a model. We fix both temperatures and the Fe abundance at the numbers found for the 2013 data and leave only the absorbing column density $N_\\mathrm{H}$ and the normalization of the two emitting components for the fit. The fitted value for $N_\\mathrm{H}$ depends on these assumptions. For example, a cooler $\\textnormal{k}T_1$ would predict more emission at lower energies and thus require a larger $N_\\mathrm{H}$ to explain the absence of signal below 1~keV. However, the fact that the observed flux dropped by two orders of magnitude or more below 1~keV compared to the data from 2013 while the drop is less severe at higher energies suggests a strongly increased $N_\\mathrm{H}$ \\citep[for a detailed discussion of the 2015 spectrum see][]{2015A&A...584L...9S}.\n\nIn 2017, the spectrum is very different again (figure~\\ref{fig:spec:rwa}). There is very little signal below 2~keV, while the flux $>3$~keV is several times stronger than in 2013 or 2015. In particular, there is a very strong emission feature between 6 and 7~keV, which is not seen in the previous \\emph{Chandra} data. This feature is discussed in detail in the next section. In table~\\ref{tab:specfits} we show two different models for the 2017 data. First, we fit a model similar to the models for 2013 and 2015 with a hot plasma component at 20~keV; this hot component has an $EM$ comparable to the other datasets; however the temperature of the cooler component is about twice the value seen in 2013, and the cool emission measure is about 50 times higher. Notably, an Fe abundance 15 times higher than in the sun is required to match the emission feature between 6 and 7~keV. Such a large emission measure will also produce copious flux below 2~keV and a very high absorbing column density of $400 \\times 10^{21}$~cm$^{-2}$ is required to explain why we do not observe any flux in that region. Alternatively, we fit a model with just a single emission component at $\\mathrm{k}T\\approx3$~keV. Due to the higher temperature, the Fe emissivity is higher and a smaller $EM$ is sufficient to match the emission feature between 6 and 7~keV and consequently the best-fit converges on a slightly smaller value for $N_\\mathrm{H}$ and an Fe abundance that is only 5 times solar -- still an order of magnitude more than in 2013.\n\nThe photoelectric cross-section of all atoms and ions (in gas and small grains) in the line-of-sight contributes to the X-ray absorption. This is expressed as equivalent hydrogen column density $N_\\mathrm{H}$, which is the total hydrogen column density of a gas with a solar abundance pattern. In the energy range between 2 and 3~keV where the observed flux drops (Figure~\\ref{fig:spec:rwa}), O, Ne, and Fe are the metals that contribute most to the total photoelectric absorption cross-section \\citep{1992ApJ...400..699B}. If these elements are enhanced by e.g.\\ one order of magnitude compared to solar abundances, then the true hydrogen column density is one order of magnitude lower than the equivalent hydrogen column density $N_H$ obtained from the fit. The value for $N_\\mathrm{H}$ is highly correlated with the temperature and the emission measure. A hotter and less absorbed plasma requires significantly less emission measure to produce the observed flux than a cooler and more absorbed plasma.\n\nStill, the value for $N_\\mathrm{H}$ that we fit in either model for the 2017 data should be treated as a lower limit because an absorbing column density this high will hide all signatures of cooler plasma in the spectrum. For example, we could add an extra emission component at 0.6~keV, the temperature seen in 2013, and at the same time increase $N_\\mathrm{H}$ without changing the predicted spectrum noticably. In a large survey of T Tauri stars in the Orion nebula cloud, \\citet{2005ApJS..160..401P} find that stars with a plasma component of $\\mathrm{k}T\\approx3$~keV typically also have a cooler component around 1~keV with a comparable $EM$. If that is the case in RW~Aur~A, too, the true  $N_\\mathrm{H}$ might be even larger than the value given in table~\\ref{tab:specfits} for 2017.\n\n#### A detailed look at the emission feature in the RW~Aur~A 2017 spectrum\n\\label{sect:2017}\n\n\n\n```python\nIPython.display.Image(filename=os.path.join(figout, 'spec_17.png'))\n```\n\\begin{figure}[ht!]\n    \\plotone{spec_17_cropped.pdf}\n    \\caption{X-ray spectrum for RW~Aur~A observed in 2017 (combined from both observations for presentation purposes) with $1\\sigma$ uncertainties and the best fit model overlayed (table~\\ref{tab:specfits} (column ``2 temp''). The inset zooms in on the emission feature centered on 6.63~keV. The olive colored line in the inset is data from the flare seen in \\emph{XMM-Newton} scaled to the lower effective area of \\emph{Chandra}. Due to the emission in a hot flare, the continuum level is much higher and the emission feature is peaked at higher energies than the \\emph{Chandra} data. Vertical blue lines in the inset mark the energies 6.63~keV (the centroid of the feature in 2017) and 6.7~keV (the position of Fe~{\\sc xxv} emission).}\n    \\label{fig:spec_17}\n\\end{figure}\n\n```python\n6.63*0.003\n```\n\n\n\n\n    0.01989\n\n\n\nA key feature observed from RW~Aur~A in 2017 is the emission feature between 6 and 7~keV. Figure~\\ref{fig:spec_17} shows this spectrum on a linear scale to help locate this feature more precisely. We fit a Gaussian plus a constant to the spectral region 6.0-7.5 keV using the Cash statistic on ungrouped data and find that this feature peaks at $6.63\\pm0.02$~keV (90\\% confidence interval of statistical uncertainty) $\\pm0.02$~keV (99\\% confidence interval of the absolute ACIS calibration\\footnote{\\url{http://cxc.harvard.edu/ccr/proceedings/07_proc/presentations/grant/pg12.html}}). Statistically compatible results are obtained for fits with moderate binning (e.g.\\ 5 counts per bin). This region is dominated by a complex of unresolved iron emission lines in the ionization stages Fe~{\\sc xxii} to Fe~{\\sc xxv}. The He-like triplet of Fe~{\\sc xxv} at 6.7~keV dominates the emission if enough hot plasma is present (peak formation temperature for the lines is $\\mathrm{k}T=5.5$~keV). The lower ionization stages have weaker lines, many of which are located at slightly lower energies. The peak of the emission feature seen in RW~Aur~A is at 6.63~keV, indicating that the temperature is too low to ionize iron up to Fe~{\\sc xxv}. Fe~{\\sc xxv} has several lines in the 6.6-6.7~keV range, but the 6.70~keV line is always the strongest one. Thus, if Fe~{\\sc xxv} was present, the centroid would be close to 6.70~keV. \nFor comparison, an equivalent fit to the \\emph{XMM-Newton} data from 2007 where a similar feature is observed finds the peak at $6.68^{+0.03}_{-0.02}$~keV (90\\% confidence interval of statistical uncertainty) $\\pm0.01$~keV \\citep[absolute PN and MOS calibration][]{XMM-SOC-CAL-TN-0018}) which is compatible with Fe~{\\sc xxv} emission.\n\nThe model for this feature (figure~\\ref{fig:spec_17}) is not symmetric, because several unresolved Fe lines from different ionization stages contribute to the emission. The emissivity of this iron feature drops by several orders of magnitude over a small range of temperatures. So, for temperatures at the lower end of the confidence interval, higher iron abundances would be required to match the observed flux at 6.63~keV. That is why the ``2 temp'' model in table~\\ref{tab:specfits} requires a higher Fe abundance than the ``1 temp'' model. In the ``2 temp'' model $kT_1$ is lower and thus the emissivitiy of Fe is lower than in the ``1 temp'' model. The position of the observed peak directly rules out a significant contribution from highly-ionized iron, and thus a Fe abundance significantly above solar and at least an order of magnitude higher than in 2013 is needed independent of the choice of parameterization (e.g.\\ number of temperature components) for the global model.\n\nIn appendix~\\ref{appendix:2017} we split the data from 2017 into three phases, but do not find any significant time evolution. In particular, the Fe emission feature is observed at all times; it is not a feature caused by the small flare at the end of ObsID 17764 that can be seen in the lightcurve in figure~\\ref{fig:lc}.\n\n## Discussion\n\nThe optical properties of RW~Aur~AB during the 2016/2017 dimming event are similar to the previous dimming observed from 2014-2016. The $B-V$ and $V-R$ color are similar, and the depth of the dimming is 0.5~mag less than before. In fact, from optical observations alone, it is not clear if the new dimming is an unrelated event or a continuation of the dimming that started in 2014 with a short gap in the absorbing material. Similarly, in X-rays we find that  $N_\\mathrm{H}$ increased a factor or 70 or so in 2015 and a few hundred in 2017 (the exact number depends on the plasma model).\nOn the other hand, in 2017, there is significantly more emission around 5~keV and the Fe abundance is about one order of magnitude higher than in either the optically bright state in 2013 or the optically faint state in 2015.\n\nIn this section, we derive limits on the gas and dust mass, distribution, and abundance based on these measurements. In section~\\ref{sect:scenarios} we will then discuss which physical processes could cause the changes in gas and dust properties.\n\n### Where is the absorbing column density located?\n\nFor the following discussion it is important to remember that the true hydrogen column density could be lower than the fitted $N_\\mathrm{H}$, if elements such as O, Ne, and Fe, which dominate the absorption between 2-3~keV, are enhanced compared to solar abundances. \n\n\nUsing the depth of several optical absorption lines, \\citet{2016A&A...596A..38F} placed a limit on the gas phase column density of Na~{\\sc i} of $3\\times10^{12}\\;\\mathrm{cm}^{-2} < N_\\mathrm{Na} < 2\\times10^{14}\\;\\mathrm{cm}^{-2}$. Using solar photospheric abundances, we can convert this to $1.4\\times 10^{18} < N_\\mathrm{H} < 9.3 \\times 10^{19}\\;\\mathrm{cm}^{-2}$. This is about one order of magnitude below the $N_\\mathrm{H}$ value we observed in 2013 and two to three orders of magnitude below the $N_\\mathrm{H}$ we fit in 2015 and 2017 indicating that almost all of the gas in the line-of-sight must be ionized. Na in a low ionization state would be missed in the Na~{\\sc i} measurement, but result in same X-ray measured $N_\\mathrm{H}$ as neutral Na.\n\n\n#### Are we looking through the disk?\n\n\\citet{2006A&A...452..897C} observed the disk of RW~Aur~A in $^{12}\\mathrm{CO}$ and $^{13}\\mathrm{CO}$ lines with radio interferometry. This allowed them to place limits on the column density of warm gas in the disk of $5\\times10^{21}\\;\\mathrm{cm}^{-2} < N_\\mathrm{H} < 10^{23}\\;\\mathrm{cm}^{-2}$ in the inner 100~au. Their upper limit is close to our measured $N_\\mathrm{H}$ and there might be an additional cold gas component in the disk mid-plane that is unseen in the radio observations. So, a sightline through the disk is compatible with our observed value for $N_\\mathrm{H}$ in 2017. The problem with this scenario is that the disk has an intermediate inclination. So, the sightline to the central star does not pass through the plane of the disk, unless the inner disk is massively warped. To make matters worse, any sightline though the disk should contain some small dust grains, in contrast to the observed gray absorption (see discussion on the $N_\\mathrm{H}/A_V$ ratio in section~\\ref{sect:nhav}).\n\n\n```python\nn_H = 1e21 * np.array([1.1, 70, 400])\nn_H_sig = 1e21 * np.array([0.1, 40, 100])/ 1.654 # error are 90% conf. Turn this to 1 sigma\n\n# Asplund et al 2009\nNa_abund = 10**6.24 / 10**12\nprint (n_H, n_H_sig)\nprint (np.array([3e12,2e14]) / Na_abund)\n```\n\n    [  1.10000000e+21   7.00000000e+22   4.00000000e+23] [  6.04594921e+19   2.41837969e+22   6.04594921e+22]\n    [  1.72631981e+18   1.15087987e+20]\n\n\n\n```python\nradius = 10. * u.AU \ndens = (2.5e23*u.cm**(-2) / radius).to(u.cm**(-3))\nv_wind = 10 * u.km/u.s\nMdot_wind = (np.pi * radius**2 * dens * 1.4 * aconst.u * v_wind).to(u.M_sun / u.year)\ndens, Mdot_wind\n```\n\n\n\n\n    (<Quantity 1671146780.5671113 1 / cm3>,\n     <Quantity 4.334870828138321e-06 solMass / yr>)\n\n\n\n\n```python\n# Mass of clump\n(np.pi * radius * dens * aconst.R_sun **2 * aconst.u).to(u.g)\n```\n\n\n\n\n$6.3122324 \\times 10^{21} \\; \\mathrm{g}$\n\n\n\n\n```python\n# mass of mercury, the smallest planet\n0.06 * aconst.M_earth\n```\n\n\n\n\n$3.5834188 \\times 10^{23} \\; \\mathrm{kg}$\n\n\n\n\n```python\ndens\n```\n\n\n\n\n$1.6711468 \\times 10^{9} \\; \\mathrm{\\frac{1}{cm^{3}}}$\n\n\n\n#### Are we looking through a disk wind?\n\nThe model fits to the 2015 and 2017 epochs indicate an extremely high absorbing column density of $>10^{23}$~cm$^{-2}$. During the 2014-2016 fading, \\citet{2016A&A...596A..38F} and \\citet{2016ApJ...820..139T} detected increased blue-shifted Ca~{\\sc ii} absorption, indicative of an increasing mass outflow, and they also identify a much stronger [O~{\\sc i}]~6300~\\AA{} emission line, which is formed in the outflow, compared with spectra taken in the optically bright state. \n\\citet{2016MNRAS.463.4459B} argue that this wind also carries the dust that causes the gray absorption although it is not clear if a wind could drag up sufficiently large dust particles from the disk to appear gray \\citep{2011MNRAS.411.1104O}. If this wind is strong within the dust evaporation radius, this could provide a large gas column density without any accompanying optical reddening.\n\nAs an order of magnitude estimate, we assume that we are looking through a uniform disk wind emanating from the inner 10~au of the disk, and that the line-of-sight does not pass through the disk itself. In order to reach the measured $N_\\mathrm{{H}}$ value along the line-of-sight, the density in that region has to be $2 \\times 10^9\\;\\mathrm{cm}^{-3}$.\nEven for a modest outflow velocity of only 10~km~s$^{-1}$ this would result in a mass loss rate of more than $2\\times10^{-6}\\;M_\\odot\\;\\mathrm{yr}^{-1}$. If true, a new knot will become visible in RW~Aur~A's jet very soon.\nOn the other hand, such mass loss cannot be sustained for very long and would be significantly larger than the mass accretion rate of $4\\times10^{-8}\\;M_\\odot\\;\\mathrm{yr}^{-1}$ measured in the previous dimming. \\citet{2016A&A...596A..38F} even detected a reduced accretion rate in the photometrically dim state, but caution that part of the accretion region could be eclipsed. \n\n#### Are we looking through a screen?\nA more plausible scenario is that the absorbing column density is not outflowing and the new absorber in 2017 is at least large enough to cover the stellar disk. We can derive a gas mass of\n\\begin{eqnarray}\nm_{\\mathrm{screen}} & > & \\pi R_*^2 \\; l \\; n \\; 1.3 u  \\nonumber \\\\\n  & > & 4 \\times 10^{21} \\left(\\frac{l}{10\\;\\mathrm{au}}\\right) \\left(\\frac{n}{2 \\times 10^9\\;\\mathrm{cm}^{-3}}\\right) \\mathrm{ g}   \\nonumber \\\\\n  & > & 10^{-6} M_\\earth\n\\end{eqnarray}\nwhere $u$ is the atomic mass unit and $1.3u$ the average particle mass. $l$ is the thickness of the screen and $n$ its particle number density. If the disk is inclined, these masses are easy to explain but they also roughly match the mass of an 80~km size planetesimal, close to the initial planetesimal size \\citep{2009Icar..204..558M}. For comparison, this is more than the mass of the Martian moon Phobos \\citep[$10^{19}$~g,][]{2014Icar..229...92P} but still five orders of magnitude below the mass of Mercury, the smallest inner planet in our Solar System ($4\\times10^{26}$~g).\nSimilar estimates have been made to explain the added absorption in \\object{TWA 30} and \\object{T Cha} where \\citet{2016MNRAS.459.2097P} and \\citet{2009A&A...501.1013S} calculate $5\\times10^{19}$~g and $4\\times10^{20}$~g, respectively. These calculations only give an order of magnitude estimate for a lower limit to the total mass in this region, since the absorber might be much larger than just the size of the visible star. If the mass is provided by the break-up of a planet or planetesimal, the resulting dust cloud would shear out into a ring and $m_{\\mathrm{screen}}$ would represent only a very small fraction of the total mass.  Also, the variability within a dimming event in the optical lightcurve in figure~\\ref{fig:lc} suggests that the absorber is not homogeneous.\n\n\n### The $N_\\mathrm{H}/A_V$ ratio\n\\label{sect:nhav}\n\n\n\n```python\nav = np.array([0.44, 2.3, 1.5])\nav_sig = np.array([0.1, 0.4, 0.3])\nprint ('N_H', n_H)\nprint('N_H_SIG', n_H_sig)\nprint (n_H / av / 1e21, np.sqrt(n_H_sig**2/av**2+av_sig**2*n_H**2/av**2) / 1e21)\nyears = [2013, 2015, 2017]\n```\n\n    N_H [  1.10000000e+21   7.00000000e+22   4.00000000e+23]\n    N_H_SIG [  6.04594921e+19   2.41837969e+22   6.04594921e+22]\n    [   2.5          30.43478261  266.66666667] [  0.28527345  16.08611061  89.5801322 ]\n\n\n\n```python\nfig = plt.figure(figsize=(4,3))\nax = fig.add_subplot(111)\nax.errorbar(av, n_H, xerr=av_sig, yerr=n_H_sig, fmt='v', label='RW Aur A')\nfor i in range(3):\n    ax.text(av[i] + 0.3, n_H[i] * 0.8, '{0}'.format(years[i]), color='b')\nax.set_yscale(\"log\", nonposy='clip')\nax.set_xscale(\"log\", nonposy='clip')\n\n\ngs08 = Table.read(figout + '../TW_Hya_uv_lineform/plots/nh_av.dat', \n                  format='ascii.no_header', delimiter=',', \n                  comment=';', names=['nh','nh_err_d','nh_err_u','AV','name'])\ngs08.remove_row(-1)\nax.errorbar(gs08['AV'], gs08['nh'] * 1e21, \n            yerr=[-gs08['nh_err_d'] * 1e21, gs08['nh_err_u'] * 1e21], color='g', fmt='s', label='GS08')\n# AA Tau - Grosso et al 2007\nax.plot([0.78] * 9, np.array([0.95, 1.54, 1.80, 1.36, 1.33, 1.04, 1.54, 1.02, 1.53]) * 1e22, \n'.m', label='AA Tau')\nax.errorbar(np.array([4]), np.array([0.6e22]), yerr=np.array([0.4e22]),\n            xerr=np.array([[0.5, 1]]), color='m', fmt='o', label='_AA Tau extra abs')\n# TWA 30 - Principe et al 2016\nax.errorbar([14.9, 4.7], [9.5e21, 1.6e21], \n            yerr=np.array([[0.61e22, 1.75e22],[0.06e22, 0.1e22]]).T, \n            xerr=np.array([[1.3, 0.6],[0.6, 0.6]]),\n            color='orange', fmt='p', label='TWA 30')\nx = np.arange(*ax.get_xlim(),step = .01)\nax.plot(x, x * 1.8e21, 'k', label='ISM')\n#ax.plot(x, x*0.89 * 0.112 * 1e22, 'k--', label='NGC1333')\nax.plot(x, x*0.63 * 1e22 *0.112, 'r:', label='Serpens')\nax.plot(x, x*1.4 * 0.112 * 1e22, 'r--', label=r'$\\rho$ Oph')\nax.set_xlabel('$A_V$ [mag]')\nax.set_ylabel('$N_H$ [cm$^{-2}$]')\nax.set_ylim([1e20, 1e24])\nax.set_xlim([.005, None])  # cuts of some low A_V sources fomr GS08\n# Manually reorder the legend\nlegend_order=[4, 0, 6, 5, 1, 2, 3]\nhandles,labels = ax.get_legend_handles_labels()\n\nhandles = [handles[i] for i in legend_order]\nlabels = [labels[i] for i in legend_order]\nax.legend(handles, labels, loc='upper left', numpoints=1, ncol=1, fontsize='small')\nfig.savefig(os.path.join(figout, 'nhav.pdf'), bbox_inches='tight')\nfig.savefig(os.path.join(figout, 'nhav.png'), bbox_inches='tight')\nfig.savefig(os.path.join(figout, 'nhav_highres.png'), bbox_inches='tight', dpi=1000)\n```\n\\begin{figure}[ht!]\n\\plotone{nhav}\n\\caption{$N_\\mathrm{H}/A_V$ ratio for RW~Aur~A in the three epochs (see text in section~\\ref{sect:nhav} for a description how $A_V$ was estimated for RW~Aur) in comparison to AA~Tau (the small dots without error bars are measurements before the dimming) and TWA~30 as well as the sample from \\citet[][GS08]{2008A&A...481..735G}. Also shown is the $N_\\mathrm{H}/A_V$ ratio observed in the ISM and the average value for two other star forming regions. See text in section~\\ref{sect:nhav} for data sources. Optical and X-ray data for RW~Aur~A, AA~Tau, and TWA~30 are contemporaneous, while the remaining data (GS08, ISM, Serpens, and $\\rho$~Oph) are based on optical and X-ray data taken non-comtemporaneously.}\n    \\label{fig:nhav}\n\\end{figure}\nFigure~\\ref{fig:nhav} shows how the $N_\\mathrm{H}/A_V$ ratio for RW~Aur~A changes with time. The selective reddening for RW~Aur~A in the optically bright state corresponds to a visual extinction of $A_V = 0.44$ \\citep{2015IBVS.6126....1A} and for 2015 and 2017 we add the additional gray extinction seen as $\\Delta m_V$ between the long-term average $m_V$ and the $m_V$ in table~\\ref{tab:BVR}.\nAs outlined in section~\\ref{sect:introduction}, the additional absorber in the dim phases of RW~Aur~A seems to be gray in the optical photometry; in other words, it is not wavelength selective, because it blocks the light completely. This can either be caused by a screen of large particles such as large dust grains or planetesimals or by a layer of gas and dust with such a high column density that it is optically thick at all relevant wavelengths. In the latter case, however, there has to be a fairly sharp edge between the optically thick absorber, that blocks part of RW~Aur~A and the open space through which we see the remaining flux from RW~Aur~A.\nIn the X-rays we do not know the true intrinsic source flux. Thus, we cannot reference the previous observations to estimate the true flux, as we do in the optical. It is possible that the gray absorber reduces the overall flux of X-rays in addition to the gas column density $N_\\mathrm{H}$ changing the spectral shape.\n\nFigure~\\ref{fig:nhav} also shows two other CTTS where $N_\\mathrm{H}$ and $A_V$ variability has been seen. AA~Tau used to show variability of $N_\\mathrm{H}$ within its 8-day cycle, while the change in $A_V$ over the cycles was not significant \\citep{2007A&A...475..607G}. The figure shows these data points as small dots without error bars. Data for AA~Tau's 2013 dimming event are taken from \\citet{2015A&A...584A..51S}. TWA~30 also has a time variable $N_\\mathrm{H}/A_V$ ratio \\citep{2016MNRAS.459.2097P} but is different from RW~Aur~A and AA~Tau as it presents a lower $N_\\mathrm{H}/A_V$ ratio than the ISM similar to the Serpens cloud. Moreover, for TWA~30 the values of $N_\\mathrm{H}$ and $A_V$ change with time, but the $N_\\mathrm{H}/A_V$ could be the same. The two epochs of contemporaneous optical/X-ray observations are separated by more than a month, so the additional absorber can be located well outside of the dust sublimation radius. We see TWA~30 close to edge-on, so the measurements probe the composition of the disk where we expect evolved grains unlike RW~Aur.\n\n$N_\\mathrm{H}$ and $A_V$ for the remaining samples in the figure are measured non-simultaneously. \n\\citet{2003A&A...408..581V} compared $N_H$ and $A_V$ for six nearby star\nforming regions, including the Orion Nebula Cloud (ONC). For the $\\rho$~Oph star forming region they\nfind an $N_H/A_V$ significantly below the ISM value.\nThey interpret this as a sign that the cloud material has a lower metal abundance than\nthe ISM, consistent with recent solar abundance measurements.\nAlternatively, grain growth can increase the amount of extinction per unit mass\nuntil the grains reach 1 $\\mu$m in size \\citep{2011A&A...532A..43O}. Grain growths is also the scenario preferred by \\citet{2007ApJ...669..493W} to explain the $N_\\mathrm{H}/A_V$ ratio seen in the Serpens cloud, where $N_\\mathrm{H}/A_V$ is less than half of the ISM value of  $1.8-2.2\\times10^{21}\\;\\mathrm{cm}^{-2}\\;\\mathrm{mag}^{-1}$ \\citep{1995A&A...293..889P}.\n\n\n```python\n10**(1.5/2.5)\n```\n\n\n\n\n    3.9810717055349722\n\n\n\n\\citet{2008A&A...481..735G} analyzed older,\nbut still accreting classical T Tauri stars (CTTS) in low-mass star forming regions. \nThey found consistently\nhigh $N_\\mathrm{H}/A_V$ ratios, indicating gas-rich material or massive grain growth. Some\nof these sources could be seen through the accretion column located very close to the central star, where small grains evaporate. This is also consistent with observations of AA~Tau where the 8-day periodicity proves that the absorber with high $N_\\mathrm{H}/A_V$ ratio is located close to the star, whereas the new absorber, which has a more ISM-like  $N_\\mathrm{H}/A_V$ ratio appeared on a much longer time scale and thus must be located at a larger distance from the star outside the dust-sublimation radius.\nRW~Aur~A has a fairly large accretion rate so there must be enough mass in the inner disk region, and possibly even within the dust-sublimation radius, to provide a large gas column density. However, there are no indications that the accretion rate changes significantly between the dim state and the bright state \\citep{2016A&A...596A..38F}. Thus, the increased $N_\\mathrm{H}$ points to a change in the geometry rather than a change in the accretion rate.\n\n\n\n### The extra emission measure\n\nThe \\emph{Chandra} X-ray and optical lightcurves of RW~Aur~A (figure~\\ref{fig:lc}) in 2017 are mostly flat and the fact that a similar flux level was observed two days later shows that the observations were not taken during a big flare. Thus, the increased emission at energies above 3~keV in 2017 compared to 2013 and 2015 (figure~\\ref{fig:spec:rwa}) must be due to a different structure of the emission region.\n\nThe energy of emission from shock heated material is limited by the velocity jump across the shock front. For the mass and radius of RW~Aur~A \\citep{2001ApJ...556..265W,2012AstL...38..167D}, the free fall velocity is $<500\\;\\mathrm{km s}^{-1}$, and thus the temperature of the shock $<0.3$~keV. The relatively soft X-rays observed by \\citet{2014ApJ...788..101S} in the resolved jet show that shocks in the outflow reach similar temperatures. Since the temperature of the observed plasma in 2017 is considerable larger, it must be magnetically heated in the corona.\n\n### Fluorescent iron?\n\nWhen iron is ionized by high-energy photons, an inner electron from the K-shell can be removed. Fluorescence occurs when an electron from a higher level (usually L) recombines to fill the K-shell. The energy of the fluorescent emission depends on the charge state of the ion. For neutral iron or ions in a low ionization stage the energy is around 6.4~keV. Only for highly ionized Fe does this line reach an energy similar to the feature we observe in the 2017 observation of RW~Aur~A \\citep[Fe~{\\sc xxiii}: 6.63~keV,][]{2004ApJS..155..675K}. Fluorescent Fe emission is sometimes seen in CTTS when very bright flares occur and provide a high X-ray flux that ionizes neutral iron in the accretion disk or funnels \\citep[e.g.][]{2005ApJS..160..503T,2007A&A...470L..13C,2010ApJ...714L..16H}. In RW~Aur~A, we see a feature centered on 6.63~keV. If this is a fluorescence line, the source of it is so highly ionized that it must be located in the stellar corona, while at the same time, the source of the ionizing radiation must be hidden from view, since we do not detect a 6.7~keV feature. Thermal emission from a range of Fe species (mostly Fe~{\\sc xxii}-Fe~{\\sc xxiv}) as discussed in Section~\\ref{sect:2017} is a simpler and more likely explanation for the observed spectrum.\n\n### The Fe abundance\n\n\n\n\n```python\nabund = 15\ndens = 1e10 * u.cm**(-3)\nV = 50e52*u.cm**(-3) / dens/ (1.4 * dens)\nm_fe = (V * dens * 10**7.5/10**12 * abund * 55.8 * u.u).to(u.M_earth)\nm_fe\n```\n\n\n\n\n$2.6282713 \\times 10^{-10} \\; \\mathrm{M_{\\oplus}}$\n\n\n\n\n```python\n(u.M_sun * 0.03 * 10**7.5/10**12).to(u.M_earth)\n```\n\n\n\n\n$0.31586038 \\; \\mathrm{M_{\\oplus}}$\n\n\n\n\n```python\nm_fe * 365\n```\n\n\n\n\n$9.5931903 \\times 10^{-8} \\; \\mathrm{M_{\\oplus}}$\n\n\n\nThe best model fit to the X-ray spectrum of RW Aur A in 2017 in table~\\ref{tab:specfits} (model ``2 temp'') shows an Fe abundance compared to solar of $\\sim 15$ and an emission measure of $50\\times10^{52}$~cm$^{-3}$.\nAn increase in iron abundance is not compatible with the properties of an active stellar corona. There is some element differentiation in coronae, where elements of low FIP such as Fe are enhanced in stars with low activity and depleted in stars with a high activity level \\citep[see review by][and references therein]{2004A&ARv..12...71G}. RW~Aur~A had a low Fe abundance in 2013, which is compatible with this picture. However, in 2017 there is significantly more emission at high temperature, indicating a higher level of activity and thus the Fe abundance should have decreased instead of increased.\nWe use the $EM$ and abundance to estimate the total mass of iron in the emitting material, which is inversely proportional to the assumed density. To simplify the estimate, we assume that the emitting volume $V$ is filled by plasma with a constant ion number density $n$ and an electron density $n=1.4\\;n_e$, where $1.4$ is the average number of electrons released per ion. We can then write $EM = V\\;n\\;n_e=1.4\\;V\\;n^2$. We calculate the total mass of Fe by multiplying the total number of Fe ions with the average weight of an Fe ion ($55.8\\;u$), where $u$  the atomic mass unit.\n\\begin{equation}\nm_{\\mathrm{Fe}} = V\\;n\\;a\\;55.8\\;u\n\\end{equation}\nAssuming a typical coronal density of $n=10^{10}\\;\\mathrm{cm}^{-3}$ \\citep{2004A&A...427..667N}, the reference Fe abundance from \\citet{2009ARA&A..47..481A} and the values for $EM$ and relative Fe abundance fitted in table~\\ref{tab:specfits} (2017, column ``2 temp'') only about $3 \\times 10^{-10}$ Earth masses of iron are required in the emitting plasma. Since the plasma temperature rules out an origin in the accretion shock, any accreted mass must be transferred to the corona in some way. Observations of RS~CVn EI~Eri suggest that the time scale of element fractionation in active regions is a few days \\citep{2013A&A...550A..22N}; similarly, the time scale on which mass lost to the solar wind is replaced is one to two days \\citep{2015LRSP...12....2L}. Assuming that one day is also a reasonable estimate for the time that accreted iron remains in the corona before it is mixed in the convective zone or ejected into the stellar wind and assuming that the abundance we observe is typical for the most recent dimming starting in 2016, about $10^{-7}$ earth masses of iron have passed through the corona. A planetesimal could easily supply this reservoir. At an age $<10$~Myr \\citep{2001ApJ...556..265W} the convection zone of RW~Aur~A is still so deep that it contains about half of the total stellar mass \\citep{2011ApJ...743...24S}; the convective turnover time is of order one year \\citep{2010A&A...510A..46L}. Thus, Fe would accumulate in the upper photosphere until it reaches a maximal concentration after about one year.\n\n## Scenarios\n\nWe are looking for a unified model that explains the variable absorption, Fe abundance, and increased volume of magnetically heated plasma.\nThe most obvious explanation for additional flux at high energies in an active star is a large coronal flare \\citep[e.g.][]{2005ApJS..160..469F}. However, the X-ray and optical light curves during the observations in 2017 show no indication of a flare. Also, coronal flares induce little change in $N_\\mathrm{H}$, in contrast to our observations.\nIn the following sub-sections we discuss other scenarios; a planetesimal break-up or puffing up the inner disk seem to be most consistent with the data.\n\n### Can this be explained by the tidal stream?\n\n\\citet{2013AJ....146..112R} suggested that the dimming event in 2011 could be due to the tidal stream between RW~Aur~A and B passing through the line-of-sight. However, many of the features observed in the more recent dimming events can only be explained by variable phenomena near the location of the inner disk and/or the disk wind close to the star \\citep[e.g.][]{2015IBVS.6143....1S,2015A&A...577A..73P,2016ApJ...820..139T,2016A&A...596A..38F,2016MNRAS.463.4459B} which is consistent with the data presented here: A stream of gas and dust passing by at a large distance from the star cannot cause the changes in the emission region needed to explain the increased hot emission and the Fe abundance inferred from X-ray spectral modeling (section~\\ref{sect:2017}). Strictly speaking, this does not rule out that the 2011 event was caused by the tidal stream passing through our line-of-sight and any later dimming is due to an unrelated mechanism, but given the long-term stability of the lightcurve before 2011 \\citep{2013AJ....146..112R} it seems more likely that all dimming events are related in some way.\n\n### Planetesimal break-up in the inner disk\n\nCircumstellar disks are the sites of planet formation. As part of this process, dust grains coagluate into larger aggregates and eventually into planetesimals and planets. When two particles collide, they may either stick together or break apart. Typical disk lifetimes are a only few Myrs \\citep[see review by][]{2014prpl.conf..475A}, but RW~Aur~A still has a disk at an apparent age of 10~Myr \\citep{2001A&A...376..982W}, so the system certainly had enough time to form planets, and given the long time scale, it may have formed more planets or planetesimals than typical.\n\nA possible scenario is that two large planetesimals collided in 2011 and released a cloud of smaller particles, which caused the optical dimming. After about 6 months, the particles are no longer visible because they are accreted onto the star or settled into the disk midplane.\n\nHowever, some larger fragments of the collision may remain and the collision may have set them on eccentric orbits increasing the probability of further collisions after the initial event. We speculate that collisions caused the dimmings in 2014 and possibly again at the end of 2016. The products of each collision depend on the composition of the colliding planetesimals and the impact parameter \\citep{2012A&A...540A..73W}. Collision products can collide again and cause a cascade that break up particles down to mircometers \\citep{2014A&A...566L...2K}. If the size distribution is skewed to particles that are more than $\\mu$m sized this will cause gray absorption in the optical. At the same time, the newly released dust will increase the opacity of the disk in layers that were optically thin before. This leads to more energy absorption and rising temperatures, which will increase the scale height of the disk, pushing the limits of optically thick absorption to even larger heights. Detailed modeling is needed, but this is at least consistent with the observed increased optical and X-ray column density.\n\nWe can estimate the dust mass in the line of sight assuming spherical dust grains with radius $a$ and mass density $\\rho=1\\mathrm{g~cm}^{-3}$ distributed over a length $l$ with a number density $n$. They will reduce the flux by a factor $e^{-\\pi a^2 n l}$. The optical light curve shows a dimming of $\\Delta V=2-3$~mag, about a factor of 10. As a minimum, the dust column covers the stellar disk, so a lower limit to the dust mass $M_d$ of the gray absorber is\n\\begin{equation}\nM_{\\mathrm{dust}} > \\pi R^2_* \\frac{\\ln{10}}{\\pi a^2}\\;\\frac{4}{3}\\pi a^3 \\;\\rho \\approx 5\\times10^{19}\n\\;\\mathrm{g}\\; \\left(\\frac{a}{10\\;\\mu\\mathrm{m}} \\right) \\ .\n\\end{equation}\n\nFor grains with $a=0.1\\;$mm, the dust mass is 1/100 of the gas mass estimated from the $N_\\mathrm{H}$ in table~\\ref{tab:specfits} (column 2017, ``2 temp'') assuming solar abundances in the absorbing material, i.e.\\ a mean particle mass of $1.3\\;u$. This ratio is similar to common ISM values. However, for a particle size distribution $n(a)\\propto a^{-3.5}$, $a$ in the equation above is replaced by $\\sqrt{a_0 a_1}$, where $a_0$ is the smallest particle (we take 0.1~mm) and $a_1$ is the largest particle. Both $a_0$ and $a_1$ are not well known, but $a_1 = 1$~km is a reasonable scale for the break up of a planetesimal, which would lead to an $M_{\\mathrm{dust}}$ that matches the gas mass from $N_H$ within a factor of a few.\n\n\n```python\n(np.pi * u.R_sun**2 * np.log(10) * 4 / 3 * 10 * u.micrometer * (1. * u.g / u.cm**3)).to(u.g)\n```\n\n\n\n\n$4.6681876 \\times 10^{19} \\; \\mathrm{g}$\n\n\n\n\n```python\n(np.sqrt(0.1*u.mm * 1.*u.km)).to(u.mm)\n```\n\n\n\n\n$316.22777 \\; \\mathrm{mm}$\n\n\n\n\n```python\n(np.pi * u.R_sun**2 * 40e21 / u.cm**2 * 1.3 * u.u).to(u.g)\n```\n\n\n\n\n$1.3129443 \\times 10^{21} \\; \\mathrm{g}$\n\n\n\nThe X-ray spectrum taken in 2015 did not show any peculiar Fe feature and emission in general was fainter than in 2017. Either accretion of Fe is intermittent, or the collision that caused the 2017 dimming event happened to include a more Fe rich planetesimal than the previous events. RW~Aur~A is old enough that considerable planet migration may have happened \\citep[e.g.][]{2002ApJ...565.1257T} and thus the inner disk region may contain planets or planetesimals that formed in different regions of the disk and thus have different compositions.\n\n\n```python\ndens_fe = 7.8749 * u.g / u.cm**3\nr_body = (3* m_fe / (4 * np.pi * dens_fe))**(1/3)\nr_body.to(u.m)\n```\n\n\n\n\n$3623.7727 \\; \\mathrm{m}$\n\n\n\n\n```python\nm_fe.to(u.kg)\n```\n\n\n\n\n$1.5696995 \\times 10^{15} \\; \\mathrm{kg}$\n\n\n\n\n```python\n(m_fe / (dens_fe * 4/3 / np.pi * (54 * u.m)**3)).decompose()\n```\n\n\n\n\n$2982643.4 \\; \\mathrm{}$\n\n\n\n### Context for a planetesimal break-up scenario\n\nDetailed hydrodynamical modeling of disk and planetesimal for the scenario discussed here is beyond the scope of this paper, but we can compare the time scale of the changes in the lightcurve with the time scale of the relevant physical processes in the disk to constrain the location of the event. The optical dimming observed in 2011 lasted six months. Another dimming event started in 2015 and lasted until at least the end of 2017 with just short spikes in the lightcurve up to the bright state level. X-ray observations have been done about every two years and the plasma properties change significantly in between. \n\nAssuming that the first break-up is due to a collision around 2011, it could have set fragments onto eccentric trajectories. For RW~Aur~A, the Roche limit is about $2\\;R_*$, which is well inside the co-rotation radius. In the magnetically funneled accretion scenario, the stellar magnetic field couples to the disk around the co-rotation radius and little gas or particles exist inside for more than about one orbit. Thus, we expect that the planetesimal break apart due to collisions, not tidal interaction with the central star. A collision in 2011 and 2015, which releases a cloud of gas and dust might cause the dimming and increase in $N_\\mathrm{H}$ from 2015 on. Can this also explain the sudden increase of the Fe abundance? In a circumstellar disk, the gas rotates at slightly sub-keplerian velocities, because it is supported by gas pressure. On the other hand, dust particles need to rotate at keplerian velocities to maintain a stable orbit, thus they feel a headwind and migrate inwards; the rate of this migration depends on their Stokes number. The radial drift time for particles is a few hundred orbits, so drifting from a radius just slightly outside the co-rotation radius to the inner edge of the disk (where gas and particularly Fe-rich particles couple to the magnetic field and are accreted) could happen in about 1.5 years \\citep{2016SSRv..205...41B} for particles with a Stokes number around 1 \\citep{2008A&A...480..859B}. This corresponds to a radius of $a = 2 \\frac{\\Sigma_g}{\\pi\\rho} = 54$~m where $\\Sigma_g$ is the gas surface density of the disk and we have used $\\Sigma_g=200\\;\\frac{\\mathrm{g}}{\\mathrm{cm}^2}\\left(\\frac{r}{\\mathrm{au}}\\right)^{-1}$ at disk radius $r$. \nThe value of $\\Sigma$ close to the star is not well known. $\\Sigma_g=200\\;\\frac{\\mathrm{g}}{\\mathrm{cm}^2}$ at 1~au is lower than typically estimated values for T~Tauri disks \\citep{2010ApJ...723.1241A} and higher than expected values for the disk mass estimates in the RW~Aur~A simulations of \\citet{2015MNRAS.449.1996D}.\n\nUnder these assumptions, the first particles from the 2015 fragmentation just made it onto the central star in 2017. It is not unreasonable, that those fragments originated in the compact core of the original planetesimal and are Fe rich. We should see enhanced accretion in the coming years as both larger and smaller fragments pass through the disk and are accreted. \n\\citet{2018arXiv180409190R} point out earlier dimming events in 1937 and 1987, so collisions of this type might be common in the RW~Aur~A disk due to the disturbance from RW~AurB.\n\nA scenario that essentially requires the accretion of a planetesimal or (part of) a terrestrial planet is not without precedent. While this has never been observed directly in young stars, there are several white dwarfs whose surface abundances show clear signatures of ongoing accretion of debris from a terrestrial planet \\citep{2006ApJ...653..613J,2009ApJ...694..805F,2011ApJ...732...90M,2012MNRAS.424..333G}.\n\n### Other scenarios\n\nThe precession time scale for a disk similar to RW~Aur should be about 0.5~Myr at 40~au \\citep{2017MNRAS.469.2834O}, which is 2800 orbits. Even when scaling this down to the co-rotation radius, that still predicts a scale of 80 years; furthermore, such precession should be periodic, but RW~Aur~A's lightcurve before 2011 did not show disk eclipses for at least one century. \n\nThere is however a possible scenario that shares many characteristics with a planetesimal break-up: a pressure trap. Thick disks can contain deadzones where the ionization is so low that the magnetic field does not couple to the disk material. \\citet{2016A&A...596A..81P} show that particles with $>1$~mm will be trapped on the outside of a deadzone. If the disk structure changes, e.g.\\ responding to an inwards traveling wave excited by the tidal forces of RW~Aur~B passing by \\citep{2015MNRAS.449.1996D}, and that trapped material is released, this might supply enough large grains to explain the extra absorber. As in the planetesimal collision scenario, particles of a certain size would move inward and supply the Fe seen in the X-ray emission. If this is true, the accretion rate in RW~Aur~A should increase significantly in the next few years as the bulk of the mass reaches the inner disk edge.\n\nLast, we note that radial velocities of several 1000~km~s$^{-1}$ would be required to explain the 6.63~keV feature as a red-shifted 6.7~keV Fe~{\\sc xxv} line. This is an order of magnitude faster than the fastest known jet component in RW~Aur. \\citet{2014ApJ...788..101S} observed X-ray emission from the jet, which requires just a few hundred km~s$^{-1}$ for shock-heating \\citep[e.g.][]{2014ApJ...795...51G}.\n\n## Summary\nWe present new \\emph{Chandra} data of the binary RW~Aur. The resolved binary member RW~Aur~A had several optical dimming events between 2011 and 2017. Previously published \\emph{Chandra} data show RW~Aur~A in an optically bright state and in a previous dimming event. We find that RW~Aur~A has an exceptionally high absorbing column density of a few $10^{23}\\;\\mathrm{cm}^{-2}$ in 2017, orders of magnitude more than in the optically bright state. We also see significantly enhanced emission in the hard X-ray range above 3~keV and newly appeared Fe emission feature at 6.63~keV that indicates an Fe abundance one order of magnitude above solar. The temperature of the plasma is too high to be shock-heated; the most plausible location for it is an active corona. Significant accretion of Fe rich material is required to boost the abundance to the observed value. We speculate that the break-up of a terrestrial planet or a large planetesimal might supply the gray extinction seen in the optical, the large amount of gas column density observed as $N_\\mathrm{H}$ in X-rays and also provide the iron in the accretion stream to enhance coronal abundances.\n\n\n\n\\acknowledgments\nWe thank an extremely thorough and detail oriented referee for numerous suggestions that lead to substantial improvements in the manuscript.\nThe scientific results reported in this article are based on observations made by the Chandra X-ray Observatory. We acknowledge with thanks the variable star observations from the AAVSO International Database contributed by observers worldwide and in particular the BAAVSS. This research has made use of software provided by the Chandra X-ray Center (CXC) in the application packages CIAO, ChIPS, and Sherpa. Support for this work was provided by the National Aeronautics and Space Administration through Chandra Award Numbers DD5-16077X and GO6-17021X issued by the Chandra X-ray Observatory Center, which is operated by the Smithsonian Astrophysical Observatory for and on behalf of the National Aeronautics Space Administration under contract NAS8-03060.\nTB acknowledges funding from the European Research Council (ERC) under the European Union's\nHorizon 2020 research and innovation programme under grant agreement No 714769.\nPCS acknowledges support by DLR grant 50 OR 1706.\n\\vspace{5mm}\n\\facilities{CXO(ACIS,ACA), AAVSO}\n\n%% Similar to \\facility{}, there is the optional \\software command to allow \n%% authors a place to specify which programs were used during the creation of \n%% the manuscript. Authors should list each code and include either a\n%% citation or url to the code inside ()s when available.\n\n\\software{astropy \\citep{2013A&A...558A..33A},\n          CIAO \\citep{2006SPIE.6270E..60F},\n          Sherpa \\citep{2007ASPC..376..543D}\n          }\n\n\\appendix\n\n## Time resolved analysis of the RW Aur A \\emph{Chandra} data from 2017\n\\label{appendix:2017}\n\nFigure~\\ref{fig:lc} shows that the count rate in RW~Aur~A increases towards the end of the first observation taken in 2017; this might be due to a coronal flare. A natural approach is to search for time-variability in the X-ray spectrum, in particular with an eye towards the question if the Fe emission feature is correlated with that flare. This appendix complements the analysis in sections~\\ref{sect:chan:rwa} and \\ref{sect:2017}.\n\nWe split the longer of the two observations (ObsID 177654) in 2017 into two parts, a ``pre-flare'' block (up to 30~ks) and a ``flare'' block (after 30~ks). We then fit those two spectra and the spectrum from ObsID~19980, which was taken two days later, with a similar model to the one used in section~\\ref{sect:chan:rwa}. Since the count rate in each of the three spectra is low we use the Cash statistic on ungrouped data and we only present fits for a model with a single temperature component. We use the same background model as in section~\\ref{sect:chan:rwa}, i.e.\\ we describe the contamination from RW~Aur~B with the model fit for 2017 in table~\\ref{tab:specfits} and a single scale factor to account for the fact that only a small fraction of the RW~Aur~B PSF falls into the extraction region of the RW~Aur~A spectrum. RW~Aur~B is moderately variable in 2017, but the variability appears not to be correlated with RW~Aur~A. Furthermore, the signal from RW~Aur~A is so low that the uncertainties of the fitted parameters are much larger than any change that would be introduced by relatively small changes in the background model.\n\nFigure~\\ref{fig:spec:2017_flare} shows the observed data and the best-fit models. Model parameters are listed in table~\\ref{tab:specfits17}. The signal is weak in all three spectra. The figure shows marginally stronger emission in the 3-5~keV range in the ``flare'' spectrum  than in the other two spectra, which is consistent with the interpretation that the increase in flux in the lightcurve towards the end of ObsID~17764 is related to stellar activity. Figure~\\ref{fig:spec:2017_flare} indicates that the Fe emission feature at 6.63~keV is present in all spectra, but the low signal makes this hard to see in the binned data shown in the figure.\n\nThe best-fit values vary between the three spectra but uncertainties are so large that all three fits are still compatible with each other. The numbers highlight some of the ambiguities in the fits. For example, while the best-fit k$T$ increases in the flare, the derived intrinsic $L_X$ in the flare is actually lower than the pre-flare $L_X$, because the fitted pre-flare $N_{\\mathrm{H}}$ is also larger. Similarly, we can see the strong dependence of the Fe abundance on the fitted temperature. The fit for the ``flare'' phase has such a large best-fit temperature that Fe is so highly ionized that little Fe~{\\sc xxv} remains, thus a very large Fe abundance is needed to explain the emission feature. On the other hand, the fit for ObsID 19980 is cool enough to have Fe in the appropriate ionization stages and consequently the fit gives a lower Fe abundance. Again, the values are compatible within the uncertainties. Some of this is due to our simple model with a single temperature emission component, while in real coronae we will always see a temperature distribution. However, the signal is too low to make a fit with several temperature components meaningful.\nIt is noteworthy though, that all scenarios show a Fe abundance significantly above solar.\n\n\n```python\nIPython.display.Image(filename=os.path.join(figout, 'spec_2017_flare.png'))\n```\n\\begin{figure}[ht!]\n    \\plotone{spec_2017_flare_cropped.pdf}\n    \\caption{X-ray spectra for RW~Aur~A in 2017. Points are observational data and lines show models from table~\\ref{tab:specfits17}. The first observation in 2017 (ObsID 17764) is split into a ``preflare'' state (the first 30~ks of the exposure) and a ``flare'' state (the remaining exposure). The second observation is ObsID 19980. Observations are binned to 5 counts per bin and background-subtracted for display purposes. Error bars indicate $1\\sigma$ uncertainties.}\n    \\label{fig:spec:2017_flare}\n\\end{figure}\n\n```python\n# Calcualte the VEM from the norms of the fit\nnp.array([0.0015, -0.0011, 0.014, 2.8e-5, -2.4e-5, 0.0018, 0.00074,0.00073, 0.004]) * normem\n```\n\n\n\n\n    array([  35.17695838,  -25.79643614,  328.31827817,    0.65663656,\n             -0.56283133,   42.21235005,   17.35396613,   17.11945308,\n             93.80522234])\n\n\n\n\n```python\n# Calculate L_X\nnp.log10(lxfac * np.array([3e-12, 1.4e-12, 3.4e-12])) \n```\n\n\n\n\n    array([ 30.84728828,  30.51629506,  30.90164594])\n\n\n\\begin{table}\n\\caption{\\label{tab:specfits17} Parameters of X-ray model fits for RW Aur A in 2017. Uncertainties are 90\\% confidence ranges.}\n\\begin{tabular}{lcccc}\n\\hline \\hline\nObsID & combined & 17764 & 17764 & 19980\\\\ \n      & ``1 temp'' from table~\\ref{tab:specfits} & quiescent & flare & obs 2 \\\\\n\\hline\n$N_\\mathrm{H}^a$ [$10^{21}$~cm$^{-2}$] & $300 \\pm 100$ & $400^{+300}_{-150}$ & $200_{-100}^{+300}$ & $210_{-150}^{+170}$ \\\\\nk$T_1$  [keV]& $3.1^{+1.8}_{-1.3}$ & $2.3^{+2}_{-1.3}$ & $13^{+8}_{-10}$ & $1.6^{+18}_{-0.6}$\\\\\n$EM_1$  [$10^{52}$~cm$^{-3}$] & $17^{+45}_{-9}$ & $35_{-25}^{+300}$ & $0.7_{-0.6}^{+17}$ & $17_{-17}^{+94}$\\\\\nabund$^b$: Fe & $5^{+3}_{-2}$ & $4_{-2}^{+1000}$ & $454_{-450}^{+4000}$ & $10_{-8}^{+4000}$ \\\\\nabund$^b$: Ne & =1 & =1 & =1 & =1\\\\\n\\hline\nstatistic & \\multicolumn{4}{c}{Cash}\\\\\n\\hline\nobserved flux$^c$ & 2.9 & 2.6 & 8.7 & 1.6\\\\\nintrinsic $\\log L_X^d$ & 30.6 & 30.8 & 30.5 & 30.9\\\\\n\\hline\n\\end{tabular}\\\\\n$^a$: These numbers should be treated as lower limits. See section~\\ref{sect:chan:rwa} for discussion.\\\\\n$^b$: Relative to solar abundances from \\protect{\\citet{2009ARA&A..47..481A}}\\\\\n$^c$: in units of $10^{-13}$erg~s$^{-1}$~cm$^{-2}$ for the energy range 0.3-9.0~keV. Value is given for best fit model without uncertainties.\\\\\n$^d$: in units of erg~s$^{-1}$ for the energy range 0.3-9.0~keV. Value is given for best fit model without uncertainties.\n\\end{table}\n\n```python\n# Check if last bin in 17764 is responsible for an unsusually large fraction for 6.63 keV photons\nsrca1 = Table.read(os.path.join(datadir, '17764_srca.fits'), hdu=1)\nsrca2 = Table.read(os.path.join(datadir, '19980_srca.fits'), hdu=1)\nobs1 = srca1.meta['TSTOP'] - srca1.meta['TSTART']\nobs2 = srca2.meta['TSTOP'] - srca2.meta['TSTART']\n\ndx1 = 0.75 * obs1 / (obs1 + obs2)\n\nfig = plt.figure(figsize=(4,3))\nax1 = fig.add_axes([.2, .2, dx1, .7])\nax2 = fig.add_axes([.2 + dx1, .2, 0.75 - dx1, .7], sharey=ax1)\nax1.scatter((srca1['time'] - srca1.meta['TSTART']) / 1e3, srca1['energy']/1e3)\nax2.scatter((srca2['time'] - srca2.meta['TSTART']) / 1e3, srca2['energy']/1e3)\nax1.set_ylim(6, 7)\nplt.setp(ax2.get_yticklabels(), visible=False)\nax1.set_ylabel('energy [keV]')\nax1.set_xlabel('time [ks]')\nax1.set_title('ObsID=17764')\nax2.set_title('19980')\nfig.savefig(os.path.join(figout, 'Fefeature.pdf'), bbox_inches='tight')\n```\n\\begin{figure}[ht!]\n    \\plotone{Fefeature.pdf}\n    \\caption{Arrival times of individual photons in the Fe feature for the two observations taken in 2017. Because of the limited energy resolution of the detector we cannot say for an individual photon if it is emitted in the continuum or in a line but the figure shows that photons between 6.5 and 6.8~keV, which are likely to come from the Fe emission feature, are detected throughout the observation.}\n    \\label{fig:17timing}\n\\end{figure}\nFigure~\\ref{fig:17timing} shows the individual photon arrival times for the observations in 2017. Since the energy resolution of the detectors is limited, energies for photons in the emission feature scatter around 6.63~keV. In addition there is a weak continuum. The figure shows that photons in the 6.63~keV feature are detected through both observations and that they are not clustered towards the end of ObsID 17764, when the lightcurve rises. The emission feature seems not to be associated with flare emission, but is consistently seen in the quiet corona.\n\n\\bibliographystyle{../AAStex/v611/aasjournal}\n\\bibliography{../articles}\n\n\\end{document}\n\n\n```python\npns = Table.read(os.path.join(datadirXMM, '0401870301', 'RWAur_1319_0401870301_EPN_S003_soft_lc.fits'), hdu=1)\npnh = Table.read(os.path.join(datadirXMM, '0401870301', 'RWAur_1319_0401870301_EPN_S003_hard_lc.fits'), hdu=1)\nomlist = glob(os.path.join(datadirXMM, '0401870301', '*OM*TIMESR1000.FIT'))\nt0 = pns['TIME'][0]\nplt.plot((pns['TIME'] - t0) / 1e3, pns['RATE'], label=\"0.2-1.0 keV\", color='r')\nplt.plot((pnh['TIME'] - t0) / 1e3, pnh['RATE'], label=\"1.0-8.0 keV\", color='k')\nfor i, f in enumerate(omlist):\n    if i==0:\n        label = '290 nm'\n    else:\n        label = '_no_legend_'\n    tom = Table.read(f)\n    plt.plot((tom['TIME'] - t0) / 1e3, tom['RATE'] / 250, color='b', label=label)\nplt.xlim(20, 35)\n```\n\n\n```python\nfor i, f in enumerate(omlist):\n    if i==0:\n        label = '290 nm'\n    else:\n        label = '_no_legend_'\n    tom = Table.read(f)\n    plt.plot((tom['TIME'] - t0) / 1e3, tom['RATE'] / 250 -0.9, color='b', label=label)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "3dcb2cea9a1d2ce6434c868e5389f0904ca2fdbc", "size": 881140, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "article.ipynb", "max_stars_repo_name": "hamogu/RWAur", "max_stars_repo_head_hexsha": "09f32b38cfa55f4d8636553ca1512e9d3482b876", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "article.ipynb", "max_issues_repo_name": "hamogu/RWAur", "max_issues_repo_head_hexsha": "09f32b38cfa55f4d8636553ca1512e9d3482b876", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "article.ipynb", "max_forks_repo_name": "hamogu/RWAur", "max_forks_repo_head_hexsha": "09f32b38cfa55f4d8636553ca1512e9d3482b876", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 265.3236976814, "max_line_length": 155842, "alphanum_fraction": 0.8745522845, "converted": true, "num_tokens": 52303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702253925955866, "lm_q2_score": 0.04208772356010582, "lm_q1q2_score": 0.0155819439784947}}
{"text": "# Setup\n\n\n```python\n%matplotlib inline\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\n```\n\n\n```python\ndata = pd.read_csv(\"articles_2017-10-01_2017-10-31.csv\", index_col=\"id\", \\\n                   parse_dates=[\"published\", \"discovered\"])\ndata.head()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>publisher_name</th>\n      <th>publisher_id</th>\n      <th>mins_as_lead</th>\n      <th>mins_on_front</th>\n      <th>num_articles_on_front</th>\n      <th>fb_brand_page</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>df8cf9e5ed31a1bfb34c9b73d9e5bce5ab98b439</th>\n      <td>https://www.economist.com/news/europe/21729855...</td>\n      <td>An unconstitutional vote on independence turns...</td>\n      <td>2017-10-01 16:09:23.688</td>\n      <td>2017-10-01 00:00:00</td>\n      <td>125</td>\n      <td>0.508058</td>\n      <td>2017-10-01T21:22:11.563Z</td>\n      <td>6</td>\n      <td>63</td>\n      <td>56</td>\n      <td>The Economist</td>\n      <td>economist_com</td>\n      <td>1299</td>\n      <td>10322</td>\n      <td>35.0</td>\n      <td>True</td>\n      <td>8312258.0</td>\n      <td>2017-10-02T17:09:04.000Z</td>\n      <td>1825</td>\n    </tr>\n    <tr>\n      <th>ff73a23349976db8c3e5ae3d4a64242b156f14a7</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Rourke leads Ohio to shootout win over Massach...</td>\n      <td>2017-10-01 00:07:21.546</td>\n      <td>2017-10-01 00:00:07</td>\n      <td>0</td>\n      <td>0.000000</td>\n      <td>2017-10-01T06:23:10.290Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>The Washington Post</td>\n      <td>washingtonpost_com</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>191</td>\n    </tr>\n    <tr>\n      <th>107efa77273acbbe8fd60c139306e7fcd09fdd98</th>\n      <td>https://www.nytimes.com/2017/09/30/sports/base...</td>\n      <td>Luis Severino and the Yankees Are Straddling a...</td>\n      <td>2017-10-01 00:01:10.412</td>\n      <td>2017-10-01 00:00:13</td>\n      <td>38</td>\n      <td>0.459418</td>\n      <td>2017-10-01T00:13:03.108Z</td>\n      <td>5</td>\n      <td>4</td>\n      <td>29</td>\n      <td>New York Times</td>\n      <td>nytimes_com</td>\n      <td>0</td>\n      <td>780</td>\n      <td>125.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>120</td>\n    </tr>\n    <tr>\n      <th>5c4db3ff5ac83175ba202cb9327d7e7b52f79f46</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Kentucky rebounds to outlast Eastern Michigan ...</td>\n      <td>2017-10-01 00:07:22.846</td>\n      <td>2017-10-01 00:00:30</td>\n      <td>0</td>\n      <td>0.000000</td>\n      <td>2017-10-01T06:23:10.293Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>The Washington Post</td>\n      <td>washingtonpost_com</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>191</td>\n    </tr>\n    <tr>\n      <th>faa6a6d39f269bf6a40af0f52f02a41cb5b38601</th>\n      <td>https://www.washingtonpost.com/sports/mystics/...</td>\n      <td>USA Basketball hosts a Women in the Game seminar</td>\n      <td>2017-10-01 00:07:22.215</td>\n      <td>2017-10-01 00:01:13</td>\n      <td>0</td>\n      <td>0.000000</td>\n      <td>2017-10-01T06:23:10.291Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>The Washington Post</td>\n      <td>washingtonpost_com</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>191</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n# Response Score\n\nThe response score is a number between 0 and 50 that indicates the level of response to an article.\n\n\n\nPerhaps in the future we may choose to include other factors, but for now we just include engagements on Facebook. The maximum score of 50 should be achieved by an article that does really well compared with others.\n\n\n```python\npd.options.display.float_format = '{:.2f}'.format\ndata.fb_engagements.describe([0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count    158885.00\n    mean       1290.91\n    std        9886.87\n    min           0.00\n    50%          26.00\n    75%         263.00\n    90%        1656.00\n    95%        4629.00\n    99%       24130.32\n    99.5%     40363.06\n    99.9%    106861.46\n    max     1680741.00\n    Name: fb_engagements, dtype: float64\n\n\n\nThere's a few articles there with 1 million plus engagements, let's just double check that.\n\n\n```python\ndata[data.fb_engagements > 1000000]\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>publisher_name</th>\n      <th>publisher_id</th>\n      <th>mins_as_lead</th>\n      <th>mins_on_front</th>\n      <th>num_articles_on_front</th>\n      <th>fb_brand_page</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>3d58d5fdd5b5649ac1e92f4853a80fe7d2b244d3</th>\n      <td>http://www.foxnews.com/entertainment/2017/10/0...</td>\n      <td>Top CBS lawyer: No sympathy for Vegas vics, 'p...</td>\n      <td>2017-10-02 16:54:13.613</td>\n      <td>2017-10-02 16:48:32</td>\n      <td>1680741</td>\n      <td>3545.41</td>\n      <td>2017-10-02T20:33:04.125Z</td>\n      <td>469349</td>\n      <td>1031278</td>\n      <td>180114</td>\n      <td>Fox News</td>\n      <td>foxnews_com</td>\n      <td>0</td>\n      <td>2601</td>\n      <td>174.00</td>\n      <td>True</td>\n      <td>15888170.00</td>\n      <td>2017-10-02T20:15:01.000Z</td>\n      <td>285</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndata.fb_engagements.mode()\n```\n\n\n\n\n    0    0\n    dtype: int64\n\n\n\nGoing back to the enagement counts, we see the mean is 1,290, mode is zero, median is 26, 90th percentile is 1,656, 99th percentile is 24,130, 99.5th percentile is 40,363. The standard deviation is 9,886, significantly higher than the mean, so this is not a normal distribution. \n\nKey publishers stats\n\n\n```python\ndata.groupby(\"publisher_id\").agg({'url': 'count', 'fb_engagements': ['sum', 'median', 'mean']})\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th>url</th>\n      <th colspan=\"3\" halign=\"left\">fb_engagements</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>count</th>\n      <th>sum</th>\n      <th>median</th>\n      <th>mean</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>38</td>\n      <td>72806</td>\n      <td>1434.50</td>\n      <td>1915.95</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>11973</td>\n      <td>10440781</td>\n      <td>40.00</td>\n      <td>872.03</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>2707</td>\n      <td>13276781</td>\n      <td>372.00</td>\n      <td>4904.61</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>53</td>\n      <td>39843</td>\n      <td>271.00</td>\n      <td>751.75</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>2010</td>\n      <td>6444963</td>\n      <td>153.50</td>\n      <td>3206.45</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>3521</td>\n      <td>19965843</td>\n      <td>639.00</td>\n      <td>5670.50</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>24900</td>\n      <td>18894463</td>\n      <td>26.00</td>\n      <td>758.81</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>517</td>\n      <td>183881</td>\n      <td>49.00</td>\n      <td>355.67</td>\n    </tr>\n    <tr>\n      <th>evolvepolitics_com</th>\n      <td>74</td>\n      <td>226865</td>\n      <td>1288.00</td>\n      <td>3065.74</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>6844</td>\n      <td>23214169</td>\n      <td>42.00</td>\n      <td>3391.90</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>3792</td>\n      <td>330615</td>\n      <td>6.00</td>\n      <td>87.19</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>11213</td>\n      <td>16768347</td>\n      <td>8.00</td>\n      <td>1495.44</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>6578</td>\n      <td>10132679</td>\n      <td>42.00</td>\n      <td>1540.39</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>512</td>\n      <td>463823</td>\n      <td>127.00</td>\n      <td>905.90</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>3918</td>\n      <td>2323126</td>\n      <td>88.00</td>\n      <td>592.94</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>177</td>\n      <td>1880</td>\n      <td>6.00</td>\n      <td>10.62</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>10525</td>\n      <td>7532990</td>\n      <td>48.00</td>\n      <td>715.72</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>2207</td>\n      <td>7893296</td>\n      <td>389.00</td>\n      <td>3576.48</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>567</td>\n      <td>251219</td>\n      <td>23.00</td>\n      <td>443.07</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>2020</td>\n      <td>8157583</td>\n      <td>208.00</td>\n      <td>4038.41</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>5185</td>\n      <td>19339366</td>\n      <td>200.00</td>\n      <td>3729.87</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>296</td>\n      <td>96614</td>\n      <td>148.00</td>\n      <td>326.40</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>52</td>\n      <td>239626</td>\n      <td>495.00</td>\n      <td>4608.19</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>6125</td>\n      <td>1939056</td>\n      <td>21.00</td>\n      <td>316.58</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>2678</td>\n      <td>2417004</td>\n      <td>217.00</td>\n      <td>902.54</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>127</td>\n      <td>108501</td>\n      <td>234.00</td>\n      <td>854.34</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>7477</td>\n      <td>3406193</td>\n      <td>25.00</td>\n      <td>455.56</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>243</td>\n      <td>348388</td>\n      <td>806.00</td>\n      <td>1433.70</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>8680</td>\n      <td>11711135</td>\n      <td>145.00</td>\n      <td>1349.21</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>8868</td>\n      <td>262582</td>\n      <td>1.00</td>\n      <td>29.61</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>24227</td>\n      <td>16152850</td>\n      <td>0.00</td>\n      <td>666.73</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>371</td>\n      <td>352208</td>\n      <td>28.00</td>\n      <td>949.35</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>410</td>\n      <td>2117388</td>\n      <td>297.00</td>\n      <td>5164.36</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\n\nnon_zero_fb_enagagements = data.fb_engagements[data.fb_engagements > 0]\n```\n\nThat's a bit better, but still way too clustered at the low end. Let's look at a log normal distribution.\n\n\n```python\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\nninety = data.fb_engagements.quantile(.90)\nninetyfive = data.fb_engagements.quantile(.95)\nninetynine = data.fb_engagements.quantile(.99)\n\nplt.figure(figsize=(12,4.5))\nplt.hist(np.log(non_zero_fb_enagagements + median), bins=50)\nplt.axvline(np.log(mean), linestyle=':', label=f'Mean ({mean:,.0f})', color='green')\nplt.axvline(np.log(median), label=f'Median ({median:,.0f})', color='green')\nplt.axvline(np.log(ninety), linestyle='--', label=f'90% percentile ({ninety:,.0f})', color='red')\nplt.axvline(np.log(ninetyfive), linestyle='-.', label=f'95% percentile ({ninetyfive:,.0f})', color='red')\nplt.axvline(np.log(ninetynine), linestyle=':', label=f'99% percentile ({ninetynine:,.0f})', color='red')\nleg = plt.legend()\n\n```\n\n\n```python\neng = data.fb_engagements[(data.fb_engagements < 5000)]\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\nninety = data.fb_engagements.quantile(.90)\nninetyfive = data.fb_engagements.quantile(.95)\nninetynine = data.fb_engagements.quantile(.99)\n\nplt.figure(figsize=(15,7))\nplt.hist(eng, bins=50)\nplt.title(\"Article count by engagements\")\nplt.axvline(median, label=f'Median ({median:,.0f})', color='green')\nplt.axvline(mean, linestyle=':', label=f'Mean ({mean:,.0f})', color='green')\nplt.axvline(ninety, linestyle='--', label=f'90% percentile ({ninety:,.0f})', color='red')\nplt.axvline(ninetyfive, linestyle='-.', label=f'95% percentile ({ninetyfive:,.0f})', color='red')\n# plt.axvline(ninetynine, linestyle=':', label=f'99% percentile ({ninetynine:,.0f})', color='red')\nleg = plt.legend()\n\n```\n\n\n```python\nlog_engagements = (non_zero_fb_enagagements\n                   .clip_upper(data.fb_engagements.quantile(.999))\n                   .apply(lambda x: np.log(x + median))\n                  )\nlog_engagements.describe()\n```\n\n\n\n\n    count   128733.00\n    mean         5.07\n    std          1.78\n    min          3.30\n    25%          3.58\n    50%          4.48\n    75%          6.13\n    max         11.58\n    Name: fb_engagements, dtype: float64\n\n\n\nUse standard feature scaling to bring that to a 1 to 50 range\n\n\n\n```python\ndef scale_log_engagements(engagements_logged):\n    return np.ceil(\n        50 * (engagements_logged - log_engagements.min()) / (log_engagements.max() - log_engagements.min())\n    )\n\ndef scale_engagements(engagements):\n    return scale_log_engagements(np.log(engagements + median))\n\nscaled_non_zero_engagements = scale_log_engagements(log_engagements)\nscaled_non_zero_engagements.describe()\n```\n\n\n\n\n    count   128733.00\n    mean        11.18\n    std         10.78\n    min          0.00\n    25%          2.00\n    50%          8.00\n    75%         18.00\n    max         50.00\n    Name: fb_engagements, dtype: float64\n\n\n\n\n```python\n# add in the zeros, as zero\nscaled_engagements = pd.concat([scaled_non_zero_engagements, data.fb_engagements[data.fb_engagements == 0]])\n```\n\n\n```python\nproposed = pd.DataFrame({\"fb_engagements\": data.fb_engagements, \"response_score\": scaled_engagements})\nproposed.response_score.plot.hist(bins=50)\n```\n\nLooks good to me, lets save that.\n\n\n```python\ndata[\"response_score\"] = proposed.response_score\n```\n\n### Proposal\n\nThe maximum of 50 points is awarded when the engagements are greater than the 99.9th percentile, rolling over the last month. \n\ni.e. where $limit$ is the 99.5th percentile of engagements calculated over the previous month, the response score for article $a$ is:\n\n\\begin{align}\nbasicScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   \\log(\\min(engagements_a,limit) + median(engagements))      & \\text{if } engagements_a > 0\n\\end{cases} \\\\\nresponseScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   50 \\cdot \\frac{basicScore_a - \\min(basicScore)}{\\max(basicScore) - \\min(basicScore)}       & \\text{if } engagements_a > 0\n\\end{cases} \\\\\n\\\\\n\\text{The latter equation can be expanded to:} \\\\\nresponseScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   50 \\cdot \n   \\frac{\\log(\\min(engagements_a,limit) + median(engagements)) - \\log(1 + median(engagements))}\n   {\\log(limit + median(engagements)) - \\log(1 + median(engagements))}       & \\text{if } engagements_a > 0\n\\end{cases} \\\\\n\\end{align}\n\n# Promotion Score\n\nThe aim of the promotion score is to indicate how important the article was to the publisher, by tracking where they chose to promote it. This is a number between 0 and 50 comprised of:\n\n- 20 points based on whether the article was promoted as the \"lead\" story on the publisher's home page\n- 15 points based on how long the article was promoted anywhere on the publisher's home page\n- 15 points based on whether the article was promoted on the publisher's main facebook brand page\n\nThe first two should be scaled by the popularity/reach of the home page, for which we use the alexa page rank as a proxy.\n\nThe last should be scaled by the popularity/reach of the brand page, for which we use the number of likes the brand page has.\n\n### Lead story (20 points)\n\n\n```python\ndata.mins_as_lead.describe([0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count   158885.00\n    mean         9.21\n    std         92.90\n    min          0.00\n    50%          0.00\n    75%          0.00\n    90%          0.00\n    95%          0.00\n    99%        269.00\n    99.5%      584.00\n    99.9%     1199.12\n    max      11563.00\n    Name: mins_as_lead, dtype: float64\n\n\n\nAs expected, the vast majority of articles don't make it as lead. Let's explore how long typically publishers put something as lead for.\n\n\n```python\nlead_articles = data[data.mins_as_lead > 0]\n```\n\n\n```python\nlead_articles.mins_as_lead.describe([0.25, 0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count    4515.00\n    mean      324.11\n    std       449.13\n    min         4.00\n    25%        84.00\n    50%       174.00\n    75%       406.50\n    90%       834.00\n    95%      1074.00\n    99%      1648.30\n    99.5%    2187.97\n    99.9%    5453.86\n    max     11563.00\n    Name: mins_as_lead, dtype: float64\n\n\n\n\n```python\nlead_articles.mins_as_lead.plot.hist(bins=50)\n```\n\nFor lead, it's a  significant thing for an article to be lead at all, so although we want to penalise articles that were lead for a very short time, mostly we want to score the maximum even if it wasn't lead for ages. So we'll give maximum points when something has been lead for an hour.\n\n\n```python\nlead_articles.mins_as_lead.clip_upper(60).plot.hist(bins=50)\n```\n\nWe also want to scale this by the alexa page rank, such that the maximum score of 20 points is for an article that was on the front for 4 hours for the most popular site.\n\nSo lets explore the alexa nunbers.\n\n\n```python\nalexa_ranks = data.groupby(by=\"publisher_id\").alexa_rank.mean().sort_values()\nalexa_ranks\n```\n\n\n\n\n    publisher_id\n    bbc_co_uk                               96\n    cnn_com                                105\n    nytimes_com                            120\n    theguardian_com                        142\n    buzzfeed_com                           147\n    dailymail_co_uk                        158\n    washingtonpost_com                     191\n    huffingtonpost_com                     215\n    foxnews_com                            285\n    rt_com                                 365\n    telegraph_co_uk                        370\n    independent_co_uk                      386\n    reuters_com                            497\n    npr_org                                594\n    lemonde_fr                             618\n    mirror_co_uk                           706\n    nbcnews_com                            826\n    breitbart_com                          994\n    ft_com                                1596\n    economist_com                         1825\n    indy100_com                           5014\n    thetimes_co_uk                        6435\n    newstatesman_com                     12769\n    thecanary_co                         15686\n    propublica_org                       16066\n    yournewswire_com                     22568\n    order-order_com                      32515\n    anotherangryvoice_blogspot_co_uk     77827\n    westmonster_com                      97775\n    evolvepolitics_com                  119412\n    skwawkbox_org                       152475\n    libdemvoice_org                     344992\n    brexitcentral_com                   469149\n    Name: alexa_rank, dtype: int64\n\n\n\n\n```python\nalexa_ranks.plot.bar(figsize=[10,5])\n```\n\nLet's try the simple option first: just divide the number of minutes as lead by the alexa rank. What's the scale of numbers we get then.\n\n\n```python\nlead_proposal_1 = lead_articles.mins_as_lead.clip_upper(60) / lead_articles.alexa_rank\nlead_proposal_1.plot.hist()\n```\n\nLooks like there's too much of a cluster around 0. Have we massively over penalised the publishers with a high alexa rank?\n\n\n```python\nlead_proposal_1.groupby(data.publisher_id).mean().plot.bar(figsize=[10,5])\n```\n\nYes. Let's try taking the log of the alexa rank and see if that looks better.\n\n\n```python\nlead_proposal_2 = (lead_articles.mins_as_lead.clip_upper(60) / np.log(lead_articles.alexa_rank))\nlead_proposal_2.plot.hist()\n```\n\n\n```python\nlead_proposal_2.groupby(data.publisher_id).describe()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>25%</th>\n      <th>50%</th>\n      <th>75%</th>\n      <th>max</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>35.00</td>\n      <td>5.31</td>\n      <td>0.11</td>\n      <td>4.71</td>\n      <td>5.33</td>\n      <td>5.33</td>\n      <td>5.33</td>\n      <td>5.33</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>101.00</td>\n      <td>12.90</td>\n      <td>1.46</td>\n      <td>1.10</td>\n      <td>13.15</td>\n      <td>13.15</td>\n      <td>13.15</td>\n      <td>13.15</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>202.00</td>\n      <td>8.32</td>\n      <td>1.45</td>\n      <td>0.58</td>\n      <td>8.69</td>\n      <td>8.69</td>\n      <td>8.69</td>\n      <td>8.69</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>47.00</td>\n      <td>4.38</td>\n      <td>0.84</td>\n      <td>0.69</td>\n      <td>4.59</td>\n      <td>4.59</td>\n      <td>4.59</td>\n      <td>4.59</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>302.00</td>\n      <td>11.89</td>\n      <td>0.90</td>\n      <td>1.80</td>\n      <td>12.02</td>\n      <td>12.02</td>\n      <td>12.02</td>\n      <td>12.02</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>198.00</td>\n      <td>12.26</td>\n      <td>2.14</td>\n      <td>0.86</td>\n      <td>12.89</td>\n      <td>12.89</td>\n      <td>12.89</td>\n      <td>12.89</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>169.00</td>\n      <td>11.54</td>\n      <td>1.46</td>\n      <td>0.99</td>\n      <td>11.85</td>\n      <td>11.85</td>\n      <td>11.85</td>\n      <td>11.85</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>42.00</td>\n      <td>7.22</td>\n      <td>2.19</td>\n      <td>0.53</td>\n      <td>7.99</td>\n      <td>7.99</td>\n      <td>7.99</td>\n      <td>7.99</td>\n    </tr>\n    <tr>\n      <th>evolvepolitics_com</th>\n      <td>27.00</td>\n      <td>5.13</td>\n      <td>0.02</td>\n      <td>5.05</td>\n      <td>5.13</td>\n      <td>5.13</td>\n      <td>5.13</td>\n      <td>5.13</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>115.00</td>\n      <td>10.58</td>\n      <td>0.33</td>\n      <td>7.08</td>\n      <td>10.61</td>\n      <td>10.61</td>\n      <td>10.61</td>\n      <td>10.61</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>103.00</td>\n      <td>7.55</td>\n      <td>1.75</td>\n      <td>0.54</td>\n      <td>8.14</td>\n      <td>8.14</td>\n      <td>8.14</td>\n      <td>8.14</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>176.00</td>\n      <td>11.02</td>\n      <td>0.79</td>\n      <td>3.72</td>\n      <td>11.17</td>\n      <td>11.17</td>\n      <td>11.17</td>\n      <td>11.17</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>135.00</td>\n      <td>9.83</td>\n      <td>1.12</td>\n      <td>0.84</td>\n      <td>10.07</td>\n      <td>10.07</td>\n      <td>10.07</td>\n      <td>10.07</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>231.00</td>\n      <td>5.35</td>\n      <td>2.06</td>\n      <td>0.47</td>\n      <td>3.52</td>\n      <td>6.92</td>\n      <td>7.04</td>\n      <td>7.04</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>189.00</td>\n      <td>8.46</td>\n      <td>2.19</td>\n      <td>0.62</td>\n      <td>9.34</td>\n      <td>9.34</td>\n      <td>9.34</td>\n      <td>9.34</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>142.00</td>\n      <td>4.65</td>\n      <td>0.35</td>\n      <td>1.18</td>\n      <td>4.71</td>\n      <td>4.71</td>\n      <td>4.71</td>\n      <td>4.71</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>327.00</td>\n      <td>8.62</td>\n      <td>1.52</td>\n      <td>0.61</td>\n      <td>9.15</td>\n      <td>9.15</td>\n      <td>9.15</td>\n      <td>9.15</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>116.00</td>\n      <td>8.74</td>\n      <td>1.10</td>\n      <td>0.74</td>\n      <td>8.93</td>\n      <td>8.93</td>\n      <td>8.93</td>\n      <td>8.93</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>76.00</td>\n      <td>6.02</td>\n      <td>1.12</td>\n      <td>1.06</td>\n      <td>6.35</td>\n      <td>6.35</td>\n      <td>6.35</td>\n      <td>6.35</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>159.00</td>\n      <td>9.08</td>\n      <td>1.11</td>\n      <td>3.13</td>\n      <td>9.39</td>\n      <td>9.39</td>\n      <td>9.39</td>\n      <td>9.39</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>54.00</td>\n      <td>12.53</td>\n      <td>0.00</td>\n      <td>12.53</td>\n      <td>12.53</td>\n      <td>12.53</td>\n      <td>12.53</td>\n      <td>12.53</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>292.00</td>\n      <td>4.26</td>\n      <td>1.55</td>\n      <td>0.39</td>\n      <td>2.89</td>\n      <td>4.33</td>\n      <td>5.78</td>\n      <td>5.78</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>22.00</td>\n      <td>6.20</td>\n      <td>0.00</td>\n      <td>6.20</td>\n      <td>6.20</td>\n      <td>6.20</td>\n      <td>6.20</td>\n      <td>6.20</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>99.00</td>\n      <td>9.26</td>\n      <td>1.40</td>\n      <td>3.06</td>\n      <td>9.66</td>\n      <td>9.66</td>\n      <td>9.66</td>\n      <td>9.66</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>151.00</td>\n      <td>9.60</td>\n      <td>1.82</td>\n      <td>0.85</td>\n      <td>10.17</td>\n      <td>10.17</td>\n      <td>10.17</td>\n      <td>10.17</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>127.00</td>\n      <td>4.70</td>\n      <td>0.89</td>\n      <td>0.42</td>\n      <td>5.03</td>\n      <td>5.03</td>\n      <td>5.03</td>\n      <td>5.03</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>102.00</td>\n      <td>9.83</td>\n      <td>1.50</td>\n      <td>0.85</td>\n      <td>10.15</td>\n      <td>10.15</td>\n      <td>10.15</td>\n      <td>10.15</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>232.00</td>\n      <td>4.85</td>\n      <td>1.67</td>\n      <td>0.93</td>\n      <td>3.62</td>\n      <td>6.11</td>\n      <td>6.21</td>\n      <td>6.21</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>156.00</td>\n      <td>11.14</td>\n      <td>2.55</td>\n      <td>1.01</td>\n      <td>12.11</td>\n      <td>12.11</td>\n      <td>12.11</td>\n      <td>12.11</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>63.00</td>\n      <td>6.65</td>\n      <td>0.88</td>\n      <td>2.17</td>\n      <td>6.84</td>\n      <td>6.84</td>\n      <td>6.84</td>\n      <td>6.84</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>81.00</td>\n      <td>10.93</td>\n      <td>1.85</td>\n      <td>0.76</td>\n      <td>11.42</td>\n      <td>11.42</td>\n      <td>11.42</td>\n      <td>11.42</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>79.00</td>\n      <td>4.96</td>\n      <td>0.83</td>\n      <td>1.31</td>\n      <td>5.22</td>\n      <td>5.22</td>\n      <td>5.22</td>\n      <td>5.22</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>165.00</td>\n      <td>5.78</td>\n      <td>0.82</td>\n      <td>0.40</td>\n      <td>5.99</td>\n      <td>5.99</td>\n      <td>5.99</td>\n      <td>5.99</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nlead_proposal_2.groupby(data.publisher_id).min().plot.bar(figsize=[10,5])\n```\n\nThat looks about right, as long as the smaller publishers were closer to zero. So let's apply feature scaling to this, to give a number between 1 and 20. (Anything not as lead will pass though as zero.)\n\n\n```python\ndef rescale(series):\n    return (series - series.min()) / (series.max() - series.min())\n\nlead_proposal_3 = np.ceil(20 * rescale(lead_proposal_2))\n```\n\n\n```python\nlead_proposal_2.min(), lead_proposal_2.max()\n```\n\n\n\n\n    (0.38500569152790032, 13.145359968846892)\n\n\n\n\n```python\nlead_proposal_3.plot.hist()\n```\n\n\n```python\nlead_proposal_3.groupby(data.publisher_id).median().plot.bar(figsize=[10,5])\n```\n\n\n```python\ndata[\"lead_score\"] = pd.concat([lead_proposal_3, data.mins_as_lead[data.mins_as_lead==0]])\n```\n\n\n```python\ndata.lead_score.value_counts().sort_index()\n```\n\n\n\n\n    0.00     154372\n    1.00         40\n    2.00         57\n    3.00         63\n    4.00         79\n    5.00         88\n    6.00         79\n    7.00        281\n    8.00        299\n    9.00        317\n    10.00       218\n    11.00       196\n    12.00        62\n    13.00       112\n    14.00       585\n    15.00       398\n    16.00       362\n    17.00       284\n    18.00       242\n    19.00       424\n    20.00       327\n    Name: lead_score, dtype: int64\n\n\n\n\n```python\ndata.lead_score.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    8.00\n    bbc_co_uk                          20.00\n    breitbart_com                      14.00\n    brexitcentral_com                   7.00\n    buzzfeed_com                       19.00\n    cnn_com                            20.00\n    dailymail_co_uk                    18.00\n    economist_com                      12.00\n    evolvepolitics_com                  8.00\n    foxnews_com                        17.00\n    ft_com                             13.00\n    huffingtonpost_com                 17.00\n    independent_co_uk                  16.00\n    indy100_com                        11.00\n    lemonde_fr                         15.00\n    libdemvoice_org                     7.00\n    mirror_co_uk                       14.00\n    nbcnews_com                        14.00\n    newstatesman_com                   10.00\n    npr_org                            15.00\n    nytimes_com                        20.00\n    order-order_com                     9.00\n    propublica_org                     10.00\n    reuters_com                        15.00\n    rt_com                             16.00\n    skwawkbox_org                       8.00\n    telegraph_co_uk                    16.00\n    thecanary_co                       10.00\n    theguardian_com                    19.00\n    thetimes_co_uk                     11.00\n    washingtonpost_com                 18.00\n    westmonster_com                     8.00\n    yournewswire_com                    9.00\n    Name: lead_score, dtype: float64\n\n\n\nIn summary then, score for article $a$ is:\n\n\n$$\nunscaledLeadScore_a = \\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)}\\\\\nleadScore_a = 19 \\cdot \n\\frac{unscaledLeadScore_a - \\min(unscaledLeadScore)}\n{\\max(unscaledLeadScore) - \\min(unscaledLeadScore)} \n+ 1\n$$\n\nSince the minium value of $minsAsLead$ is 1, $\\min(unscaledLeadScore)$ is pretty insignificant. So we can simplify this to:\n\n$$\nleadScore_a = 20 \\cdot \n\\frac{unscaledLeadScore_a }\n     {\\max(unscaledLeadScore)} \n$$\n\nor: \n\n$$\nleadScore_a = 20 \\cdot \n\\frac{\\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)} }\n     {\\frac{60}{\\log(\\max(alexaRank))}} \n$$\n\n$$\nleadScore_a = \\left( 20 \\cdot \n\\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)} \\cdot\n     {\\frac{\\log(\\max(alexaRank))}{60}} \\right)\n$$\n\n## Time on front score (15 points)\n\nThis is similar to time as lead, so lets try doing the same calculation, except we also want to factor in the number of slots on the front:\n\n\n$$frontScore_a = \n15 \n\\left(\\frac{\\min(minsOnFront_a, 1440)}{alexaRank_a \\cdot numArticlesOnFront_a}\\right) \n\\left( \\frac{\\min(alexaRank \\cdot numArticlesOnFront)}{1440} \\right)$$\n\n\n```python\n(data.alexa_rank * data.num_articles_on_front).min() / 1440\n```\n\n\n\n\n    2.4500000000000002\n\n\n\n\n```python\ntime_on_front_proposal_1 = np.ceil(data.mins_on_front.clip_upper(1440) / (data.alexa_rank * data.num_articles_on_front) * (2.45) * 15)\n```\n\n\n```python\ntime_on_front_proposal_1.plot.hist(figsize=(15, 7), bins=15)\n```\n\n\n```python\ntime_on_front_proposal_1.value_counts().sort_index()\n```\n\n\n\n\n    1.00     75844\n    2.00      7589\n    3.00      4551\n    4.00      4163\n    5.00       791\n    6.00       581\n    7.00       569\n    8.00       890\n    9.00       586\n    10.00      223\n    11.00      308\n    12.00      348\n    13.00      120\n    14.00       66\n    15.00       35\n    dtype: int64\n\n\n\n\n```python\ntime_on_front_proposal_1.groupby(data.publisher_id).sum()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk      38.00\n    bbc_co_uk                          15612.00\n    breitbart_com                       2624.00\n    brexitcentral_com                     53.00\n    buzzfeed_com                        9480.00\n    cnn_com                            12207.00\n    dailymail_co_uk                    14732.00\n    economist_com                        302.00\n    evolvepolitics_com                    74.00\n    foxnews_com                         7983.00\n    ft_com                              3528.00\n    huffingtonpost_com                  7713.00\n    independent_co_uk                   4548.00\n    indy100_com                          491.00\n    lemonde_fr                          3904.00\n    libdemvoice_org                      177.00\n    mirror_co_uk                        9900.00\n    nbcnews_com                         1981.00\n    newstatesman_com                     557.00\n    npr_org                             2492.00\n    nytimes_com                         9902.00\n    order-order_com                      295.00\n    propublica_org                        52.00\n    reuters_com                         7124.00\n    rt_com                              4531.00\n    skwawkbox_org                        127.00\n    telegraph_co_uk                     5567.00\n    thecanary_co                         243.00\n    theguardian_com                    12853.00\n    thetimes_co_uk                      8850.00\n    washingtonpost_com                  9250.00\n    westmonster_com                      348.00\n    yournewswire_com                     410.00\n    dtype: float64\n\n\n\nThat looks good to me.\n\n\n```python\ndata[\"front_score\"] = np.ceil(data.mins_on_front.clip_upper(1440) / (data.alexa_rank * data.num_articles_on_front) * (2.45) * 15).fillna(0)\n```\n\n\n```python\ndata.front_score \n```\n\n\n\n\n    id\n    df8cf9e5ed31a1bfb34c9b73d9e5bce5ab98b439   1.00\n    ff73a23349976db8c3e5ae3d4a64242b156f14a7   0.00\n    107efa77273acbbe8fd60c139306e7fcd09fdd98   2.00\n    5c4db3ff5ac83175ba202cb9327d7e7b52f79f46   0.00\n    faa6a6d39f269bf6a40af0f52f02a41cb5b38601   0.00\n    d8fdb38812bfa4ebf5096eff5c3836c7bfea2650   0.00\n    5b5056265c75d8f3c84a209365a3463b47aba3e1   0.00\n    c2376359478d79aec41cc87c60ce96a07200315e   0.00\n    58d25dd29d2cc5510e6f2aecfb19dfbad7d8072f   0.00\n    3f6ab2c7c68a2b1a231a2483781690e8208b504c   0.00\n    0c710c25d58126384a7a0b2e9a44ff1e1c84760f   0.00\n    b62c7a7e048c9c0b43894f1af09412fd03f526c4   1.00\n    da66ff6b2857b28d802ac43d51739b91ea537513   1.00\n    6acc7b4c632c0dd5783da419bd82f9c20500bce3   0.00\n    273a63e59763d0b4b8ddcc0cc0ea6890e70d3612   0.00\n    29630b4931d9094406c7da71a92654ff4aa3a804   0.00\n    b8b37dc30b7ad207bd93ae3cdb595a5ea634a5d1   0.00\n    95174653c48ade1a96c74d7eeb8daab72ad6438d   0.00\n    84401f2ca38991c4ccdf1518377132f3fd029157   1.00\n    48911d9ba1a31b061bc4c831bbc63670cc757aab   0.00\n    5d6fc4a824831cf8daf5c6d06c6649b72a9ae32e   1.00\n    9b2ead55398bd9af21adcfb60ef2ecd477243ff4   1.00\n    bbda5b39aff202e1396ef50549d8dd82246dd3b7   1.00\n    05532ac3109b3f97efc5cf01b1287c2a9eebb12e   1.00\n    211dea07520407f9916cf0431839e3492dbecaf1   0.00\n    0d63758483a6a7eea9c609a29b9a33930484b5dd   1.00\n    546940fde649b45d214734663d9932cc825a0e33   0.00\n    469ba85ad83defa6bb1baab22b889ef333f585c0   0.00\n    d2072a2146f76f319304ebe728eee8a106171416   1.00\n    545ed82638e2b1facb7e2d696237bd7e846a5744   1.00\n                                               ... \n    d0dd0c23333756ccd50495ab96cc98c7946a91c7   1.00\n    bb27ecb8d6f3b9d536137616293963a89a7a0a31   1.00\n    f0ec131dd80598a2df96a5323e5e1409e6e4c4ae   1.00\n    123ae6f4c00b1837c811fc8e8e52f2ba22f69493   1.00\n    4d051a39263f284239615c6810a89673dafaec69   0.00\n    7cdd27d441fa5d8e23a00562f6d865f74ec51be0   0.00\n    3506c633ed4cdc5a6206272a703fe4f0b21b08d5   2.00\n    bc475aff1476ca08707c57a4b12ee156b06da4bc   1.00\n    f34a5885b114fe4b586e17ca3431ba992319a432   9.00\n    db9fd62c225c848050967275e23d643691be3175   1.00\n    a0c7f6edd1a3e2450646715aa0a037ff88db1fc8   1.00\n    9357448c1c298dbe1df8a2cbdb6485233c0e6417   0.00\n    4f3c42941ae3a8b2b6c69b65fbaf18b28f8c5958   0.00\n    1a7ded246da17f7c6c2aa4727cd49b871cea4cbe   0.00\n    ed625081fcc17e5ee7db2b4e6873e6fba309a303   1.00\n    10144a48ef63b862fab6201edc5c2daec02397cc   1.00\n    bfca8d6d582df2172f337712378d21a4b3107d02   1.00\n    6cd23490cefdb9f8d7bf9c867c011787c727dcfe   0.00\n    ff1740a2026615c843a834190d778d87f180dc9a   1.00\n    fc92edc544029b512dee3e2662650306e8cc60ac   0.00\n    a9b58a311d8f1b979900e9a379509e44cbbd73d8   0.00\n    764782b334e0a4595592b66c546ad9b1e9ec222d   1.00\n    2eb86c05f6b4a321e7ada7117739391b10866092   1.00\n    d980f90f472268089a410b39cbe8633d22da482a   0.00\n    0f8573f9e9c8a20294fd56f6a9ef5f0f1d26c25b   1.00\n    4390dec1fda6917d9461659311c329ae3298bd43   2.00\n    3aace91a23bd1281c696e8ad2d1ff678fd1ee279   0.00\n    405e04e258a3610e9308d64588410b80c01644a2   1.00\n    80944fe2bc75f2b72e33865d50f3b3326c5d11dd   1.00\n    925c2db58567841316695f21643a8c362e2a1b85   1.00\n    Name: front_score, Length: 158885, dtype: float64\n\n\n\n## Facebook brand page promotion (15 points)\n\nOne way a publisher has of promoting content is to post to their brand page. The significance of doing so is stronger when the brand page has more followers (likes).\n\n$$ facebookPromotionProposed1_a = 15 \\left( \\frac {brandPageLikes_a} {\\max(brandPageLikes)} \\right) $$\n\nNow lets explore the data to see if that makes sense. **tr;dr the formula above is incorrect**\n\n\n```python\ndata.fb_brand_page_likes.max()\n```\n\n\n\n\n    44693975.0\n\n\n\n\n```python\nfacebook_promotion_proposed_1 = np.ceil((15 * (data.fb_brand_page_likes / data.fb_brand_page_likes.max())).fillna(0))\n```\n\n\n```python\nfacebook_promotion_proposed_1.value_counts().sort_index().plot.bar()\n```\n\n\n```python\nfacebook_promotion_proposed_1.groupby(data.publisher_id).describe()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>25%</th>\n      <th>50%</th>\n      <th>75%</th>\n      <th>max</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>38.00</td>\n      <td>0.84</td>\n      <td>0.37</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>11973.00</td>\n      <td>0.63</td>\n      <td>3.02</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>15.00</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>2707.00</td>\n      <td>0.90</td>\n      <td>0.99</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>53.00</td>\n      <td>0.92</td>\n      <td>0.27</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>2010.00</td>\n      <td>0.24</td>\n      <td>0.43</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>3521.00</td>\n      <td>2.74</td>\n      <td>4.46</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>10.00</td>\n      <td>10.00</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>24900.00</td>\n      <td>0.56</td>\n      <td>1.58</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>5.00</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>517.00</td>\n      <td>2.22</td>\n      <td>1.32</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>evolvepolitics_com</th>\n      <td>74.00</td>\n      <td>0.50</td>\n      <td>0.50</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.50</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>6844.00</td>\n      <td>0.59</td>\n      <td>1.79</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>6.00</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>3792.00</td>\n      <td>0.50</td>\n      <td>0.87</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>11213.00</td>\n      <td>0.45</td>\n      <td>1.26</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>6578.00</td>\n      <td>0.60</td>\n      <td>1.20</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>512.00</td>\n      <td>0.63</td>\n      <td>0.48</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>3918.00</td>\n      <td>0.84</td>\n      <td>0.99</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>177.00</td>\n      <td>0.81</td>\n      <td>0.40</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>10525.00</td>\n      <td>0.24</td>\n      <td>0.43</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>2207.00</td>\n      <td>1.99</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>567.00</td>\n      <td>0.74</td>\n      <td>0.44</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>2020.00</td>\n      <td>1.39</td>\n      <td>1.50</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>5185.00</td>\n      <td>1.47</td>\n      <td>2.28</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>5.00</td>\n      <td>5.00</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>296.00</td>\n      <td>0.81</td>\n      <td>0.39</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>52.00</td>\n      <td>0.83</td>\n      <td>0.38</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>6125.00</td>\n      <td>0.58</td>\n      <td>0.91</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>2678.00</td>\n      <td>0.96</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>127.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>7477.00</td>\n      <td>0.51</td>\n      <td>0.87</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>243.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>8680.00</td>\n      <td>0.51</td>\n      <td>1.12</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>8868.00</td>\n      <td>0.06</td>\n      <td>0.23</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>24227.00</td>\n      <td>0.19</td>\n      <td>0.73</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>371.00</td>\n      <td>0.23</td>\n      <td>0.42</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>410.00</td>\n      <td>0.22</td>\n      <td>0.41</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThat's too much variation: sites like the Guardian, which have a respectable 7.5m likes, should not be scoring a 3. Lets try applying a log to it, and then standard feature scaling again.\n\n\n```python\ndata.fb_brand_page_likes.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk     330074.00\n    bbc_co_uk                          44693975.00\n    breitbart_com                       3720252.00\n    brexitcentral_com                     11212.00\n    buzzfeed_com                        2753297.00\n    cnn_com                            29136270.00\n    dailymail_co_uk                    13152590.00\n    economist_com                       8351246.00\n    evolvepolitics_com                   113625.00\n    foxnews_com                        16012614.00\n    ft_com                              3699305.00\n    huffingtonpost_com                  9795839.00\n    independent_co_uk                   7729827.00\n    indy100_com                          228462.00\n    lemonde_fr                          3930501.00\n    libdemvoice_org                        8591.00\n    mirror_co_uk                        2904439.00\n    nbcnews_com                         9346923.00\n    newstatesman_com                     154712.00\n    npr_org                             6234045.00\n    nytimes_com                        14853130.00\n    order-order_com                       44768.00\n    propublica_org                       368773.00\n    reuters_com                         3896512.00\n    rt_com                              4624363.00\n    skwawkbox_org                          5808.00\n    telegraph_co_uk                     4379813.00\n    thecanary_co                         156042.00\n    theguardian_com                     7777911.00\n    thetimes_co_uk                       705739.00\n    washingtonpost_com                  6072234.00\n    westmonster_com                       15504.00\n    yournewswire_com                      27023.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\nnp.log(2149)\n```\n\n\n\n\n    7.6727578966425103\n\n\n\n\n```python\nnp.log(data.fb_brand_page_likes.groupby(data.publisher_id).max())\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk   12.71\n    bbc_co_uk                          17.62\n    breitbart_com                      15.13\n    brexitcentral_com                   9.32\n    buzzfeed_com                       14.83\n    cnn_com                            17.19\n    dailymail_co_uk                    16.39\n    economist_com                      15.94\n    evolvepolitics_com                 11.64\n    foxnews_com                        16.59\n    ft_com                             15.12\n    huffingtonpost_com                 16.10\n    independent_co_uk                  15.86\n    indy100_com                        12.34\n    lemonde_fr                         15.18\n    libdemvoice_org                     9.06\n    mirror_co_uk                       14.88\n    nbcnews_com                        16.05\n    newstatesman_com                   11.95\n    npr_org                            15.65\n    nytimes_com                        16.51\n    order-order_com                    10.71\n    propublica_org                     12.82\n    reuters_com                        15.18\n    rt_com                             15.35\n    skwawkbox_org                       8.67\n    telegraph_co_uk                    15.29\n    thecanary_co                       11.96\n    theguardian_com                    15.87\n    thetimes_co_uk                     13.47\n    washingtonpost_com                 15.62\n    westmonster_com                     9.65\n    yournewswire_com                   10.20\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\nThat's more like it, but the lower numbers should be smaller.\n\n\n```python\nnp.log(data.fb_brand_page_likes.groupby(data.publisher_id).max() / 1000)\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    5.80\n    bbc_co_uk                          10.71\n    breitbart_com                       8.22\n    brexitcentral_com                   2.42\n    buzzfeed_com                        7.92\n    cnn_com                            10.28\n    dailymail_co_uk                     9.48\n    economist_com                       9.03\n    evolvepolitics_com                  4.73\n    foxnews_com                         9.68\n    ft_com                              8.22\n    huffingtonpost_com                  9.19\n    independent_co_uk                   8.95\n    indy100_com                         5.43\n    lemonde_fr                          8.28\n    libdemvoice_org                     2.15\n    mirror_co_uk                        7.97\n    nbcnews_com                         9.14\n    newstatesman_com                    5.04\n    npr_org                             8.74\n    nytimes_com                         9.61\n    order-order_com                     3.80\n    propublica_org                      5.91\n    reuters_com                         8.27\n    rt_com                              8.44\n    skwawkbox_org                       1.76\n    telegraph_co_uk                     8.38\n    thecanary_co                        5.05\n    theguardian_com                     8.96\n    thetimes_co_uk                      6.56\n    washingtonpost_com                  8.71\n    westmonster_com                     2.74\n    yournewswire_com                    3.30\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\nscaled_fb_brand_page_likes = (data.fb_brand_page_likes / 1000)\nfacebook_promotion_proposed_2 = np.ceil(\\\n    (15 * \\\n     (np.log(scaled_fb_brand_page_likes) / np.log(scaled_fb_brand_page_likes.max()))\\\n    )\\\n                                       ).fillna(0)\n```\n\n\n```python\nfacebook_promotion_proposed_2.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    9.00\n    bbc_co_uk                          15.00\n    breitbart_com                      12.00\n    brexitcentral_com                   4.00\n    buzzfeed_com                       12.00\n    cnn_com                            15.00\n    dailymail_co_uk                    14.00\n    economist_com                      13.00\n    evolvepolitics_com                  7.00\n    foxnews_com                        14.00\n    ft_com                             12.00\n    huffingtonpost_com                 13.00\n    independent_co_uk                  13.00\n    indy100_com                         8.00\n    lemonde_fr                         12.00\n    libdemvoice_org                     4.00\n    mirror_co_uk                       12.00\n    nbcnews_com                        13.00\n    newstatesman_com                    8.00\n    npr_org                            13.00\n    nytimes_com                        14.00\n    order-order_com                     6.00\n    propublica_org                      9.00\n    reuters_com                        12.00\n    rt_com                             12.00\n    skwawkbox_org                       3.00\n    telegraph_co_uk                    12.00\n    thecanary_co                        8.00\n    theguardian_com                    13.00\n    thetimes_co_uk                     10.00\n    washingtonpost_com                 13.00\n    westmonster_com                     4.00\n    yournewswire_com                    5.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\nLGTM. So the equation is\n\n\n$$ facebookPromotion_a = 15 \\left( \n\\frac {\\log(\\frac {brandPageLikes_a}{1000})} \n{\\log(\\frac {\\max(brandPageLikes)}{1000}))} \\right) $$\n\n\nNow, let's try applying standard feature scaling approch to this, rather than using a magic number of 1,000. That equation would be:\n\n\\begin{align}\nunscaledFacebookPromotion_a &= \n   \\log(brandPageLikes_a) \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{unscaledFacebookPromotion_a - \\min(unscaledFacebookPromotion)}{\\max(unscaledFacebookPromotion) - \\min(unscaledFacebookPromotion)}  \\\\\n\\\\\n\\text{The scaling can be simplified to:} \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{unscaledFacebookPromotion_a - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))}  \\\\\n\\\\\n\\text{Meaning the overall equation becomes:} \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{\\log(brandPageLikes_a) - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))} \n   \\end{align}\n\n\n\n```python\nfacebook_promotion_proposed_3 = np.ceil(\n    (14 * \n     ( \n         (np.log(data.fb_brand_page_likes) - np.log(data.fb_brand_page_likes.min()) ) /\n         (np.log(data.fb_brand_page_likes.max()) - np.log(data.fb_brand_page_likes.min()))\n     )\n    ) + 1\n                                       )\n```\n\n\n```python\nfacebook_promotion_proposed_3.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    8.00\n    bbc_co_uk                          15.00\n    breitbart_com                      12.00\n    brexitcentral_com                   3.00\n    buzzfeed_com                       11.00\n    cnn_com                            15.00\n    dailymail_co_uk                    14.00\n    economist_com                      13.00\n    evolvepolitics_com                  6.00\n    foxnews_com                        14.00\n    ft_com                             12.00\n    huffingtonpost_com                 13.00\n    independent_co_uk                  13.00\n    indy100_com                         7.00\n    lemonde_fr                         12.00\n    libdemvoice_org                     2.00\n    mirror_co_uk                       11.00\n    nbcnews_com                        13.00\n    newstatesman_com                    7.00\n    npr_org                            12.00\n    nytimes_com                        14.00\n    order-order_com                     5.00\n    propublica_org                      8.00\n    reuters_com                        12.00\n    rt_com                             12.00\n    skwawkbox_org                       2.00\n    telegraph_co_uk                    12.00\n    thecanary_co                        7.00\n    theguardian_com                    13.00\n    thetimes_co_uk                      9.00\n    washingtonpost_com                 12.00\n    westmonster_com                     3.00\n    yournewswire_com                    4.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\ndata[\"facebook_promotion_score\"] = facebook_promotion_proposed_3.fillna(0.0)\n```\n\n# Review\n\n\n```python\ndata[\"promotion_score\"] = (data.lead_score + data.front_score + data.facebook_promotion_score)\ndata[\"attention_index\"] = (data.promotion_score + data.response_score)\n```\n\n\n```python\ndata.promotion_score.plot.hist(bins=np.arange(50), figsize=(15,6))\n```\n\n\n```python\ndata.attention_index.plot.hist(bins=np.arange(100), figsize=(15,6))\n```\n\n\n```python\ndata.attention_index.value_counts().sort_index()\n```\n\n\n\n\n    0.00     25301\n    1.00     19223\n    2.00     13018\n    3.00      9206\n    4.00      7096\n    5.00      5298\n    6.00      4565\n    7.00      4207\n    8.00      3798\n    9.00      3294\n    10.00     3141\n    11.00     2918\n    12.00     2747\n    13.00     2446\n    14.00     2401\n    15.00     2309\n    16.00     2109\n    17.00     1949\n    18.00     1853\n    19.00     1811\n    20.00     1774\n    21.00     1788\n    22.00     1726\n    23.00     1636\n    24.00     1589\n    25.00     1552\n    26.00     1594\n    27.00     1445\n    28.00     1437\n    29.00     1384\n             ...  \n    67.00       94\n    68.00       92\n    69.00       62\n    70.00       60\n    71.00       48\n    72.00       54\n    73.00       44\n    74.00       35\n    75.00       41\n    76.00       39\n    77.00       32\n    78.00       38\n    79.00       30\n    80.00       26\n    81.00       22\n    82.00       27\n    83.00       27\n    84.00       12\n    85.00        9\n    86.00       16\n    87.00       10\n    88.00       18\n    89.00       11\n    90.00        3\n    91.00        7\n    92.00        2\n    93.00        5\n    94.00        3\n    95.00        1\n    98.00        1\n    Name: attention_index, Length: 97, dtype: int64\n\n\n\n\n```python\n# and lets see the articles with the biggest attention index\ndata.sort_values(\"attention_index\", ascending=False)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>82f641a891db565edfcef82af5dac6e60f18dc29</th>\n      <td>http://www.bbc.co.uk/news/world-europe-41780116</td>\n      <td>Catalans declare independence from Spain</td>\n      <td>2017-10-27 13:28:14.944</td>\n      <td>2017-10-27 13:26:28.000</td>\n      <td>122017</td>\n      <td>735.45</td>\n      <td>2017-10-27T13:49:10.398Z</td>\n      <td>25016</td>\n      <td>82794</td>\n      <td>14207</td>\n      <td>...</td>\n      <td>True</td>\n      <td>44557554.00</td>\n      <td>2017-10-27T13:36:37.000Z</td>\n      <td>96</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>13.00</td>\n      <td>15.00</td>\n      <td>48.00</td>\n      <td>98.00</td>\n    </tr>\n    <tr>\n      <th>fb7f2c7fc2b3d5d441f187c2cc298eb68481caca</th>\n      <td>http://www.bbc.co.uk/news/world-us-canada-4146...</td>\n      <td>'Active shooter' near Las Vegas casino</td>\n      <td>2017-10-02 05:58:13.020</td>\n      <td>2017-10-02 05:55:50.000</td>\n      <td>155740</td>\n      <td>282.82</td>\n      <td>2017-10-02T12:02:05.884Z</td>\n      <td>36936</td>\n      <td>96254</td>\n      <td>22550</td>\n      <td>...</td>\n      <td>True</td>\n      <td>44231064.00</td>\n      <td>2017-10-02T10:52:53.000Z</td>\n      <td>96</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>10.00</td>\n      <td>15.00</td>\n      <td>45.00</td>\n      <td>95.00</td>\n    </tr>\n    <tr>\n      <th>55a653279260f78e8c3d8fdae5ac3ff000ff1a63</th>\n      <td>http://www.cnn.com/2017/10/02/us/las-vegas-sho...</td>\n      <td>Portraits of the victims of the Las Vegas shoo...</td>\n      <td>2017-10-02 22:13:24.653</td>\n      <td>2017-10-02 22:08:01.000</td>\n      <td>121221</td>\n      <td>208.76</td>\n      <td>2017-10-03T00:26:03.622Z</td>\n      <td>10651</td>\n      <td>96865</td>\n      <td>13705</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28779427.00</td>\n      <td>2017-10-02T23:30:10.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>67d0bda0783da4c5d2ce176c1d3144d21b226c7a</th>\n      <td>http://www.cnn.com/2017/10/30/politics/paul-ma...</td>\n      <td>Manafort to turn himself in to Mueller, source...</td>\n      <td>2017-10-30 11:58:15.661</td>\n      <td>2017-10-30 11:55:36.000</td>\n      <td>163516</td>\n      <td>678.74</td>\n      <td>2017-10-30T12:10:03.568Z</td>\n      <td>47714</td>\n      <td>92136</td>\n      <td>23666</td>\n      <td>...</td>\n      <td>True</td>\n      <td>29101437.00</td>\n      <td>2017-10-30T11:57:37.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>f9ec6620251671f7010b07793542152080b97f63</th>\n      <td>http://www.bbc.co.uk/news/world-europe-41463719</td>\n      <td>Catalonia has 'won right to statehood'</td>\n      <td>2017-10-01 20:49:10.902</td>\n      <td>2017-10-01 20:46:53.000</td>\n      <td>92269</td>\n      <td>283.28</td>\n      <td>2017-10-02T02:12:11.055Z</td>\n      <td>11378</td>\n      <td>71867</td>\n      <td>9024</td>\n      <td>...</td>\n      <td>True</td>\n      <td>44223789.00</td>\n      <td>2017-10-02T01:52:48.000Z</td>\n      <td>96</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>cec51f99475b0936b80e7e1f07661fd769850060</th>\n      <td>http://www.cnn.com/2017/10/08/politics/vice-pr...</td>\n      <td>Mike Pence leaves Colts game after anthem protest</td>\n      <td>2017-10-08 17:58:20.413</td>\n      <td>2017-10-08 17:54:50.000</td>\n      <td>154384</td>\n      <td>515.68</td>\n      <td>2017-10-08T18:40:09.200Z</td>\n      <td>64195</td>\n      <td>77072</td>\n      <td>13117</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28829396.00</td>\n      <td>2017-10-08T18:21:38.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>d6c669a2a511a179c138c95cd00ecd21f67786ca</th>\n      <td>http://www.cnn.com/2017/10/16/health/puerto-ri...</td>\n      <td>Floating hospital sits near Puerto Rico after ...</td>\n      <td>2017-10-16 22:31:22.572</td>\n      <td>2017-10-16 22:29:14.000</td>\n      <td>95905</td>\n      <td>225.62</td>\n      <td>2017-10-17T18:04:09.923Z</td>\n      <td>16034</td>\n      <td>63684</td>\n      <td>16187</td>\n      <td>...</td>\n      <td>True</td>\n      <td>29040951.00</td>\n      <td>2017-10-17T02:29:12.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>a40b5a3781bcdbb51023839d1e504623829509f7</th>\n      <td>https://www.buzzfeed.com/stephaniemcneal/lular...</td>\n      <td>Women Say They're Stuck With $20,000 Of Worthl...</td>\n      <td>2017-10-25 20:40:31.730</td>\n      <td>2017-10-25 20:38:10.000</td>\n      <td>140824</td>\n      <td>764.35</td>\n      <td>2017-10-26T15:09:08.794Z</td>\n      <td>71842</td>\n      <td>53756</td>\n      <td>15226</td>\n      <td>...</td>\n      <td>True</td>\n      <td>2746668.00</td>\n      <td>2017-10-25T23:34:00.000Z</td>\n      <td>147</td>\n      <td>50.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>6f31aba0d9c375c9b6658dba325de9ba6aab5472</th>\n      <td>http://www.cnn.com/2017/10/27/politics/first-c...</td>\n      <td>Exclusive: First charges filed in Mueller inve...</td>\n      <td>2017-10-28 00:37:18.546</td>\n      <td>2017-10-28 00:29:59.000</td>\n      <td>676010</td>\n      <td>4464.02</td>\n      <td>2017-10-28T01:09:09.274Z</td>\n      <td>173337</td>\n      <td>425374</td>\n      <td>77299</td>\n      <td>...</td>\n      <td>True</td>\n      <td>29089089.00</td>\n      <td>2017-10-28T00:46:40.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>6a0116039bbc12a38eed333af50ac8ccbb14e530</th>\n      <td>http://www.bbc.co.uk/news/world-us-canada-4152...</td>\n      <td>Trump rolls back access to free birth control</td>\n      <td>2017-10-06 16:07:06.751</td>\n      <td>2017-10-06 16:05:48.000</td>\n      <td>47522</td>\n      <td>156.57</td>\n      <td>2017-10-06T18:39:06.354Z</td>\n      <td>14732</td>\n      <td>28303</td>\n      <td>4487</td>\n      <td>...</td>\n      <td>True</td>\n      <td>44281131.00</td>\n      <td>2017-10-06T18:28:26.000Z</td>\n      <td>96</td>\n      <td>46.00</td>\n      <td>20.00</td>\n      <td>12.00</td>\n      <td>15.00</td>\n      <td>47.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>95a1f2bb7086f89ff2bf066faece9605d3843cee</th>\n      <td>http://www.cnn.com/2017/10/02/us/las-vegas-att...</td>\n      <td>Here's what we know about Stephen Paddock, the...</td>\n      <td>2017-10-02 12:37:23.217</td>\n      <td>2017-10-02 12:31:34.000</td>\n      <td>67404</td>\n      <td>171.83</td>\n      <td>2017-10-02T13:59:07.658Z</td>\n      <td>23031</td>\n      <td>34768</td>\n      <td>9605</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28768865.00</td>\n      <td>2017-10-02T13:44:02.000Z</td>\n      <td>105</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>b0a7e0c7b10ee97b2901390f0ce1e495cc7608e3</th>\n      <td>https://www.buzzfeed.com/josephbernstein/heres...</td>\n      <td>Here's How Breitbart And Milo Smuggled White N...</td>\n      <td>2017-10-05 20:28:27.591</td>\n      <td>2017-10-04 20:22:03.000</td>\n      <td>120844</td>\n      <td>735.92</td>\n      <td>2017-10-06T05:05:10.751Z</td>\n      <td>36491</td>\n      <td>58391</td>\n      <td>25962</td>\n      <td>...</td>\n      <td>True</td>\n      <td>2713110.00</td>\n      <td>2017-10-05T21:11:19.000Z</td>\n      <td>147</td>\n      <td>50.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>f075885c7f633014983f3a4dfa8a2568e3f30820</th>\n      <td>https://www.buzzfeed.com/adambvary/anthony-rap...</td>\n      <td>Actor Anthony Rapp: Kevin Spacey Made A Sexual...</td>\n      <td>2017-10-30 01:34:21.416</td>\n      <td>2017-10-30 01:32:42.000</td>\n      <td>63217</td>\n      <td>277.41</td>\n      <td>2017-10-30T03:07:10.078Z</td>\n      <td>28302</td>\n      <td>28576</td>\n      <td>6339</td>\n      <td>...</td>\n      <td>True</td>\n      <td>2749565.00</td>\n      <td>2017-10-30T02:13:58.000Z</td>\n      <td>147</td>\n      <td>47.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>bb779a59d0768a95e90a7064a4cc96d385802150</th>\n      <td>http://www.cnn.com/2017/10/02/us/las-vegas-sho...</td>\n      <td>Las Vegas shooting: Live updates</td>\n      <td>2017-10-02 06:43:21.668</td>\n      <td>2017-10-02 06:40:33.000</td>\n      <td>250916</td>\n      <td>577.52</td>\n      <td>2017-10-02T12:56:06.116Z</td>\n      <td>41731</td>\n      <td>178605</td>\n      <td>30580</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28767961.00</td>\n      <td>2017-10-02T12:45:14.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>fa25e376e29f7eff2f858ef404c04ccb1764fd96</th>\n      <td>http://www.cnn.com/2017/10/30/politics/donald-...</td>\n      <td>Trump 'seething' as Mueller probe reaches form...</td>\n      <td>2017-10-30 23:43:17.351</td>\n      <td>2017-10-30 23:37:29.000</td>\n      <td>79114</td>\n      <td>300.46</td>\n      <td>2017-10-31T01:47:07.847Z</td>\n      <td>13042</td>\n      <td>61458</td>\n      <td>4614</td>\n      <td>...</td>\n      <td>True</td>\n      <td>29102689.00</td>\n      <td>2017-10-31T01:31:10.000Z</td>\n      <td>105</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>83f4006ad4366078fe5620632914e763dfed5d24</th>\n      <td>http://www.cnn.com/2017/10/13/us/california-fi...</td>\n      <td>Woman dies in husband's arms while hiding in s...</td>\n      <td>2017-10-13 19:31:28.678</td>\n      <td>2017-10-13 19:29:10.000</td>\n      <td>61063</td>\n      <td>131.60</td>\n      <td>2017-10-14T06:21:11.198Z</td>\n      <td>3836</td>\n      <td>53852</td>\n      <td>3375</td>\n      <td>...</td>\n      <td>True</td>\n      <td>29025532.00</td>\n      <td>2017-10-14T06:00:28.000Z</td>\n      <td>105</td>\n      <td>47.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>bf9df1d59d28db1dc8a586a19bddec58c9dfcd56</th>\n      <td>http://www.cnn.com/2017/10/17/politics/trump-j...</td>\n      <td>Trump warns John McCain: 'Be careful ... I fig...</td>\n      <td>2017-10-17 15:31:27.783</td>\n      <td>2017-10-17 15:24:46.000</td>\n      <td>71046</td>\n      <td>241.69</td>\n      <td>2017-10-17T16:45:09.863Z</td>\n      <td>24910</td>\n      <td>40669</td>\n      <td>5467</td>\n      <td>...</td>\n      <td>True</td>\n      <td>29044379.00</td>\n      <td>2017-10-17T16:30:24.000Z</td>\n      <td>105</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>10f7302737a4fe288003babdfa2e9350e36556ff</th>\n      <td>https://www.buzzfeed.com/coralewis/these-are-t...</td>\n      <td>These Are The Victims Of The Las Vegas Shooting</td>\n      <td>2017-10-02 15:43:19.061</td>\n      <td>2017-10-02 15:30:45.000</td>\n      <td>246234</td>\n      <td>1436.61</td>\n      <td>2017-10-03T17:06:12.166Z</td>\n      <td>15576</td>\n      <td>193415</td>\n      <td>37243</td>\n      <td>...</td>\n      <td>True</td>\n      <td>2710339.00</td>\n      <td>2017-10-02T23:08:00.000Z</td>\n      <td>147</td>\n      <td>50.00</td>\n      <td>19.00</td>\n      <td>11.00</td>\n      <td>11.00</td>\n      <td>41.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>daff5a6de1600351e1301260c729478c9dc2e36a</th>\n      <td>http://www.bbc.co.uk/news/entertainment-arts-4...</td>\n      <td>Rock and roll legend Fats Domino dies</td>\n      <td>2017-10-25 14:43:15.954</td>\n      <td>2017-10-25 14:39:46.000</td>\n      <td>82618</td>\n      <td>507.52</td>\n      <td>2017-10-25T15:15:11.832Z</td>\n      <td>10435</td>\n      <td>56692</td>\n      <td>15491</td>\n      <td>...</td>\n      <td>True</td>\n      <td>44530330.00</td>\n      <td>2017-10-25T14:42:20.000Z</td>\n      <td>96</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>beab15b7777cc9d822f21d549f76bf12fcdb53a2</th>\n      <td>http://www.cnn.com/2017/10/31/us/new-york-shot...</td>\n      <td>Shots fired in Manhattan; one person in custody</td>\n      <td>2017-10-31 19:43:20.020</td>\n      <td>2017-10-31 19:38:30.000</td>\n      <td>179977</td>\n      <td>545.86</td>\n      <td>2017-10-31T21:07:09.102Z</td>\n      <td>38732</td>\n      <td>105983</td>\n      <td>35262</td>\n      <td>...</td>\n      <td>True</td>\n      <td>29107811.00</td>\n      <td>2017-10-31T20:11:44.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>5.00</td>\n      <td>15.00</td>\n      <td>40.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>d221e354b313ce4e5536c4a0dee1dfd7cca379f3</th>\n      <td>http://www.cnn.com/2017/10/09/us/california-fi...</td>\n      <td>Wildfires rage in swath of California's wine c...</td>\n      <td>2017-10-09 11:52:23.501</td>\n      <td>2017-10-09 11:49:24.000</td>\n      <td>79676</td>\n      <td>153.43</td>\n      <td>2017-10-10T01:16:09.079Z</td>\n      <td>20985</td>\n      <td>48458</td>\n      <td>10233</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28832711.00</td>\n      <td>2017-10-10T01:02:09.000Z</td>\n      <td>105</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>80756bf5f41ea79c83dddf95acfea413cedc47a6</th>\n      <td>https://www.buzzfeed.com/laurageiser/las-vegas...</td>\n      <td>Photos Show The Terrifying Aftermath Of Las Ve...</td>\n      <td>2017-10-02 10:34:10.208</td>\n      <td>2017-10-02 10:18:42.000</td>\n      <td>147698</td>\n      <td>420.10</td>\n      <td>2017-10-03T07:02:10.022Z</td>\n      <td>12795</td>\n      <td>113076</td>\n      <td>21827</td>\n      <td>...</td>\n      <td>True</td>\n      <td>2709326.00</td>\n      <td>2017-10-02T12:56:40.000Z</td>\n      <td>147</td>\n      <td>50.00</td>\n      <td>19.00</td>\n      <td>10.00</td>\n      <td>11.00</td>\n      <td>40.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>3c40e0ffdf776c5bfef61de5ef7152eb00dc68d1</th>\n      <td>http://www.cnn.com/2017/10/12/politics/obamaca...</td>\n      <td>Trump will end health care cost-sharing subsidies</td>\n      <td>2017-10-13 03:01:31.361</td>\n      <td>2017-10-13 02:56:41.000</td>\n      <td>82624</td>\n      <td>200.70</td>\n      <td>2017-10-13T03:33:11.986Z</td>\n      <td>31282</td>\n      <td>41245</td>\n      <td>10097</td>\n      <td>...</td>\n      <td>True</td>\n      <td>29018649.00</td>\n      <td>2017-10-13T03:16:50.000Z</td>\n      <td>105</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>5.00</td>\n      <td>15.00</td>\n      <td>40.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>21baf75c0cee1455134ba03272544695a9632d43</th>\n      <td>http://www.bbc.co.uk/news/world-us-canada-4182...</td>\n      <td>Casualties reported after New York 'shooting'</td>\n      <td>2017-10-31 19:37:10.279</td>\n      <td>2017-10-31 19:34:57.000</td>\n      <td>56934</td>\n      <td>336.38</td>\n      <td>2017-10-31T19:48:11.900Z</td>\n      <td>10368</td>\n      <td>33744</td>\n      <td>12822</td>\n      <td>...</td>\n      <td>True</td>\n      <td>44596174.00</td>\n      <td>2017-10-31T19:35:52.000Z</td>\n      <td>96</td>\n      <td>47.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>ee3157d189708e28111bca2672b17c29164c3536</th>\n      <td>https://www.buzzfeed.com/nidhiprakash/puerto-r...</td>\n      <td>Puerto Rico's Government Just Admitted 911 Peo...</td>\n      <td>2017-10-27 22:34:23.096</td>\n      <td>2017-10-27 21:53:21.000</td>\n      <td>43600</td>\n      <td>38.37</td>\n      <td>2017-10-28T20:34:06.012Z</td>\n      <td>4928</td>\n      <td>27727</td>\n      <td>10945</td>\n      <td>...</td>\n      <td>True</td>\n      <td>2748557.00</td>\n      <td>2017-10-27T23:44:01.000Z</td>\n      <td>147</td>\n      <td>45.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>4eac773f3ebe0d94a0fa4a6b6670ddf917c2731a</th>\n      <td>http://www.huffingtonpost.com/entry/las-vegas-...</td>\n      <td>Las Vegas Police Investigate Reports Of Active...</td>\n      <td>2017-10-02 05:59:14.138</td>\n      <td>2017-10-02 05:55:25.000</td>\n      <td>369539</td>\n      <td>945.57</td>\n      <td>2017-10-02T12:44:12.235Z</td>\n      <td>76304</td>\n      <td>232393</td>\n      <td>60842</td>\n      <td>...</td>\n      <td>True</td>\n      <td>9751564.00</td>\n      <td>2017-10-02T06:01:09.000Z</td>\n      <td>215</td>\n      <td>50.00</td>\n      <td>17.00</td>\n      <td>9.00</td>\n      <td>13.00</td>\n      <td>39.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>516109aeae85946b20f0815443503941a9377f91</th>\n      <td>http://www.cnn.com/2017/10/19/politics/bush-sp...</td>\n      <td>George W. Bush just laid the smackdown on Trum...</td>\n      <td>2017-10-19 18:53:18.568</td>\n      <td>2017-10-19 18:49:39.000</td>\n      <td>92682</td>\n      <td>261.19</td>\n      <td>2017-10-19T23:43:06.164Z</td>\n      <td>14364</td>\n      <td>69760</td>\n      <td>8558</td>\n      <td>...</td>\n      <td>True</td>\n      <td>29056712.00</td>\n      <td>2017-10-19T23:30:15.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>4.00</td>\n      <td>15.00</td>\n      <td>39.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>cac2ab0eb67721d299e607b8f0fffd7231ea75d1</th>\n      <td>http://www.cnn.com/2017/10/05/politics/special...</td>\n      <td>Mueller's team met with Russia dossier author</td>\n      <td>2017-10-05 22:07:21.402</td>\n      <td>2017-10-05 22:03:50.000</td>\n      <td>41500</td>\n      <td>197.71</td>\n      <td>2017-10-05T22:28:13.927Z</td>\n      <td>7478</td>\n      <td>27644</td>\n      <td>6378</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28813554.00</td>\n      <td>2017-10-05T22:15:08.000Z</td>\n      <td>105</td>\n      <td>45.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>379ec53f3e91218fdedbc34f3c1353d022721d34</th>\n      <td>http://www.cnn.com/2017/10/01/politics/donald-...</td>\n      <td>Trump: Tillerson 'wasting his time' negotiatin...</td>\n      <td>2017-10-01 14:52:21.832</td>\n      <td>2017-10-01 14:49:24.000</td>\n      <td>44896</td>\n      <td>145.64</td>\n      <td>2017-10-01T16:14:03.920Z</td>\n      <td>15331</td>\n      <td>22588</td>\n      <td>6977</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28745597.00</td>\n      <td>2017-10-01T15:19:18.000Z</td>\n      <td>105</td>\n      <td>45.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>ca2cdf87d5f8fa84da0437cfa9274cd1df3cb1c5</th>\n      <td>http://www.cnn.com/2017/10/03/politics/russian...</td>\n      <td>Exclusive: Russian-linked Facebook ads targete...</td>\n      <td>2017-10-04 01:34:27.207</td>\n      <td>2017-10-04 01:30:07.000</td>\n      <td>56373</td>\n      <td>276.02</td>\n      <td>2017-10-04T01:45:10.551Z</td>\n      <td>12626</td>\n      <td>33241</td>\n      <td>10506</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28795396.00</td>\n      <td>2017-10-04T01:37:10.000Z</td>\n      <td>105</td>\n      <td>47.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>02c0972c41194fb4cd15f19804aeb894cc2c5bee</th>\n      <td>https://www.washingtonpost.com/world/asia_paci...</td>\n      <td>AP PHOTOS: Portraits of Rohingya survivors of ...</td>\n      <td>2017-10-27 04:58:15.224</td>\n      <td>2017-10-27 04:53:31.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-27T05:09:12.445Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>5c9a06cf457cd2602d5cc3f89b773cc77c6ac968</th>\n      <td>https://www.theguardian.com/australia-news/vid...</td>\n      <td>Whistleblowers allege Crown casino tampered wi...</td>\n      <td>2017-10-18 05:40:03.973</td>\n      <td>2017-10-18 05:39:46.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-10-18T06:51:09.099Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>142</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>3c5cde42b98c1493c6339db25cde00b3c22db267</th>\n      <td>https://www.nbcnews.com/card/carrie-barnette-n...</td>\n      <td>nbcnews:card_text</td>\n      <td>2017-10-05 13:43:19.752</td>\n      <td>2017-10-05 13:41:53.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-05T14:55:09.510Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>826</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>91482986a8d1514c8e4dfe4ba5421e9ed4a4e7ed</th>\n      <td>http://www.bbc.co.uk/news/uk-wales-politics-41...</td>\n      <td>Welsh Development Bank chief will not be based...</td>\n      <td>2017-10-18 05:40:06.627</td>\n      <td>2017-10-18 05:36:57.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-10-18T07:51:11.799Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>eefc2e0e12b67df110332240509e65e95651ca4b</th>\n      <td>https://www.washingtonpost.com/sports/national...</td>\n      <td>After 3K, Beltre wants 2018 in Texas to anothe...</td>\n      <td>2017-10-02 19:55:19.710</td>\n      <td>2017-10-02 19:50:22.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-03T01:11:10.085Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>80aca1202079bde5eb32962f06515b0f0bc4dca0</th>\n      <td>http://www.bbc.co.uk/news/av/uk-41771399/hallo...</td>\n      <td>Halloween at the zoo</td>\n      <td>2017-10-27 05:10:14.420</td>\n      <td>2017-10-27 05:06:33.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-27T05:22:06.633Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>1779d2c71fcf3e462aac8fe1c628f02d6b789f5d</th>\n      <td>http://www.huffingtonpost.com/entry/privileged...</td>\n      <td>Privileged</td>\n      <td>2017-10-02 20:04:25.114</td>\n      <td>2017-10-02 19:50:50.424</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-03T01:18:11.551Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>654e1e4f92b9f174cad4bbba83cae806bd24f3de</th>\n      <td>https://www.washingtonpost.com/national/market...</td>\n      <td>Markets Right Now: US stocks edged higher in e...</td>\n      <td>2017-10-05 13:52:17.547</td>\n      <td>2017-10-05 13:43:22.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-05T15:04:10.354Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>55e64897d16d13eae4f53b3b56b647f60ce1ab6c</th>\n      <td>http://www.bbc.co.uk/news/av/world-us-canada-4...</td>\n      <td>Top-secret JFK files</td>\n      <td>2017-10-27 05:07:13.301</td>\n      <td>2017-10-27 05:03:47.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-27T05:19:05.694Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>af63fd3495409c98948ab9364f8f411f909af1ad</th>\n      <td>https://www.nbcnews.com/card/nicol-kimura-n807696</td>\n      <td>nbcnews:card_text</td>\n      <td>2017-10-05 13:46:14.450</td>\n      <td>2017-10-05 13:43:20.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-05T14:58:07.471Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>826</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>bd3c218f72e56d810d95c0e73d30eb7de098d7e5</th>\n      <td>https://www.washingtonpost.com/business/austra...</td>\n      <td>Australian casino denies lawmaker\u2019s criminal a...</td>\n      <td>2017-10-18 05:13:22.000</td>\n      <td>2017-10-18 05:08:14.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-18T05:24:09.122Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>3812f835fdba0ae032cefa8741151163a99605ee</th>\n      <td>https://www.washingtonpost.com/sports/wizards/...</td>\n      <td>Griffin\u2019s 3-pointer beats Blazers, keeps Clipp...</td>\n      <td>2017-10-27 05:07:17.833</td>\n      <td>2017-10-27 05:01:09.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-27T05:19:05.696Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>86924e65577ee3d3b7b815016b08e3e75538b4e3</th>\n      <td>http://www.huffingtonpost.com/entry/the-man-fr...</td>\n      <td>\"The Man from Mesquite Was Not Discreet\u2019 By Re...</td>\n      <td>2017-10-02 20:04:30.044</td>\n      <td>2017-10-02 19:51:44.779</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-03T01:18:11.561Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>c8121b18ed4fec985495254e8aee6db7e6d50df5</th>\n      <td>https://www.washingtonpost.com/national/housto...</td>\n      <td>Houston-area \u201cTourniquet Killer\u201d set to die</td>\n      <td>2017-10-18 05:13:21.269</td>\n      <td>2017-10-18 05:08:21.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-18T05:24:09.121Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>7a15a79697d14b7ad795d3ed74700d1cb5ce91b1</th>\n      <td>https://www.washingtonpost.com/sports/national...</td>\n      <td>A year after 1st title since 1908, Cubs trail ...</td>\n      <td>2017-10-18 05:13:19.308</td>\n      <td>2017-10-18 05:09:27.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-18T05:24:09.120Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>c75ed341bea900137000eaa60445cd10df57cede</th>\n      <td>https://www.washingtonpost.com/sports/capitals...</td>\n      <td>Perron leads Vegas past the Sabres in overtime...</td>\n      <td>2017-10-18 05:13:19.036</td>\n      <td>2017-10-18 05:10:34.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-18T05:24:09.118Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>f46fa5010355b1586993f4b8c485876f645b388b</th>\n      <td>http://www.dailymail.co.uk/tvshowbiz/article-4...</td>\n      <td>Katy Perry shares bizarre video of cupping pro...</td>\n      <td>2017-10-18 05:16:21.443</td>\n      <td>2017-10-18 05:12:56.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-10-18T18:33:09.907Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>19a847cd1839b45086f13a4da14f18b4bbabb034</th>\n      <td>https://www.washingtonpost.com/sports/capitals...</td>\n      <td>Couture scores twice in Sharks\u2019 5-2 victory ov...</td>\n      <td>2017-10-18 05:22:16.440</td>\n      <td>2017-10-18 05:16:35.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-18T05:33:10.876Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>0c480b0c0a89ec79422232747f480131b92f0d2f</th>\n      <td>https://www.washingtonpost.com/local/southern-...</td>\n      <td>Home sales for Calvert, Charles and St. Mary\u2019s...</td>\n      <td>2017-10-05 13:52:15.357</td>\n      <td>2017-10-05 13:42:52.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-05T15:04:10.351Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>2a10f2a01a7fba6d11999773e61cdcf944ca2c3c</th>\n      <td>https://www.nbcnews.com/card/denise-cohen-n807651</td>\n      <td>nbcnews:card_text</td>\n      <td>2017-10-05 13:43:18.597</td>\n      <td>2017-10-05 13:42:32.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-05T14:55:09.509Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>826</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>58227a10730242e3d915ac2b3388fafdaeb52e56</th>\n      <td>https://www.washingtonpost.com/local/alexandri...</td>\n      <td>Alexandria launches campaign to promote Metror...</td>\n      <td>2017-10-18 05:34:20.280</td>\n      <td>2017-10-18 05:22:10.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-18T05:46:06.441Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>5b462c9f5a37417714123cbc18822bd6564e6a5e</th>\n      <td>https://www.washingtonpost.com/sports/wizards/...</td>\n      <td>76ers\u2019 Fultz gets to make NBA debut at Wizards...</td>\n      <td>2017-10-18 05:34:22.200</td>\n      <td>2017-10-18 05:22:20.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-10-18T08:47:11.413Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>a01768152856e76a0ed39277e38d86a693fbe7bc</th>\n      <td>https://www.washingtonpost.com/national/women-...</td>\n      <td>Women in California Capitol speak out against ...</td>\n      <td>2017-10-18 05:31:18.648</td>\n      <td>2017-10-18 05:23:16.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-10-18T16:46:11.233Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>cc465581129290ac85bde303ee8569636cdf9e96</th>\n      <td>https://www.washingtonpost.com/world/asia_paci...</td>\n      <td>Car bomb kills 4 police, 2 civilians in southw...</td>\n      <td>2017-10-18 05:34:23.107</td>\n      <td>2017-10-18 05:25:15.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-18T05:46:06.445Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>b5665edf2f09e3f0c53eb90958a81464bbc9b698</th>\n      <td>https://www.washingtonpost.com/business/techno...</td>\n      <td>China\u2019s Xi calls for more technology development</td>\n      <td>2017-10-18 05:34:23.355</td>\n      <td>2017-10-18 05:25:23.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-18T05:46:06.446Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>c2abd2a6fa5b760f9c3456efdc1ca9d635ce1ed9</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Go for 2 or play for OT? How coaches make that...</td>\n      <td>2017-10-18 05:34:21.155</td>\n      <td>2017-10-18 05:27:18.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-18T05:46:06.443Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>2cb52cf6cf9b5f81cea9166fd15b9916ce5532fa</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>No. 13 Notre Dame dreams alive and well at sea...</td>\n      <td>2017-10-18 05:43:15.630</td>\n      <td>2017-10-18 05:31:20.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-18T05:54:07.811Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>a09d2a501db72426813643eb873fe2caa0a81848</th>\n      <td>https://www.huffingtonpost.com/entry/are-custo...</td>\n      <td>Are Customers Finally Ready to Adopt Smart Hom...</td>\n      <td>2017-10-18 05:46:22.312</td>\n      <td>2017-10-18 05:33:28.519</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-10-18T08:58:03.893Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>dc2eda44b3595ed320b2bc8adc38db32cf1a8c10</th>\n      <td>https://www.washingtonpost.com/business/subaru...</td>\n      <td>Subaru investigates its own inspections after ...</td>\n      <td>2017-10-27 05:07:20.004</td>\n      <td>2017-10-27 04:59:49.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-27T05:19:05.698Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>563c25c593fb24594bbb4c00defa2c2122fea1dc</th>\n      <td>https://www.washingtonpost.com/politics/ap-sou...</td>\n      <td>AP Source: Wyo. Senate race might see insurgen...</td>\n      <td>2017-10-09 08:01:12.645</td>\n      <td>2017-10-09 07:48:30.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-09T19:16:11.987Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>158885 rows \u00d7 25 columns</p>\n</div>\n\n\n\n\n```python\ndata[\"score_diff\"] = data.promotion_score - data.response_score\n```\n\n\n```python\n# promoted but low response\ndata.sort_values(\"score_diff\", ascending=False).head(25)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n      <th>score_diff</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>e43a9b30900aab9765ce74c00665e24da573a56c</th>\n      <td>https://www.buzzfeed.com/aishagani/people-are-...</td>\n      <td>People Are Pointing Out A Black Woman Started ...</td>\n      <td>2017-10-19 11:43:24.546</td>\n      <td>2017-10-17 13:26:51</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-19T11:55:04.504Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2738311.00</td>\n      <td>2017-10-19T14:45:00.000Z</td>\n      <td>147</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>43.00</td>\n      <td>43.00</td>\n    </tr>\n    <tr>\n      <th>2b852dff5e7a3e4352681245f98178a56a52689b</th>\n      <td>https://www.buzzfeed.com/monicamark/meet-the-b...</td>\n      <td>Meet The Badass Women Wrestlers Of Senegal</td>\n      <td>2017-10-27 12:58:12.984</td>\n      <td>2017-10-23 14:54:04</td>\n      <td>3</td>\n      <td>0.27</td>\n      <td>2017-10-27T13:10:07.398Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>...</td>\n      <td>2748890.00</td>\n      <td>2017-10-28T17:45:00.000Z</td>\n      <td>147</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>44.00</td>\n      <td>42.00</td>\n    </tr>\n    <tr>\n      <th>74f30801f07e697b1804a420c37cddc54563401c</th>\n      <td>https://www.buzzfeed.com/danvergano/how-a-us-r...</td>\n      <td>How A US Raid On An Afghan Village Went Wrong</td>\n      <td>2017-10-17 16:01:29.821</td>\n      <td>2017-10-16 16:57:47</td>\n      <td>18</td>\n      <td>0.28</td>\n      <td>2017-10-17T17:12:09.350Z</td>\n      <td>2</td>\n      <td>3</td>\n      <td>13</td>\n      <td>...</td>\n      <td>2736252.00</td>\n      <td>2017-10-17T23:04:00.000Z</td>\n      <td>147</td>\n      <td>3.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>47.00</td>\n      <td>41.00</td>\n    </tr>\n    <tr>\n      <th>68c78eedcf54c1421649c1287bda9cd7cdc624ef</th>\n      <td>https://www.buzzfeed.com/arianelange/fbi-in-ho...</td>\n      <td>Inside The FBI's Half-Secret Relationship With...</td>\n      <td>2017-10-09 16:34:18.783</td>\n      <td>2017-10-07 17:17:50</td>\n      <td>2</td>\n      <td>0.18</td>\n      <td>2017-10-09T16:46:05.185Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>...</td>\n      <td>2714329.00</td>\n      <td>2017-10-09T19:21:00.000Z</td>\n      <td>147</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>43.00</td>\n      <td>41.00</td>\n    </tr>\n    <tr>\n      <th>c616bb3ad332266cfa9dfc11b2d1cc2518b466d0</th>\n      <td>https://www.buzzfeed.com/talalansari/trumps-an...</td>\n      <td>Trump\u2019s Anti-Islam Rhetoric Convinced These Mu...</td>\n      <td>2017-10-31 13:04:18.596</td>\n      <td>2017-10-26 18:18:02</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>2017-10-31T13:15:06.299Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>2750122.00</td>\n      <td>2017-10-31T14:32:31.000Z</td>\n      <td>147</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>7.00</td>\n      <td>11.00</td>\n      <td>37.00</td>\n      <td>37.00</td>\n      <td>37.00</td>\n    </tr>\n    <tr>\n      <th>e30407d0a2a955d86fd7299f4df704bd8f9d7f7e</th>\n      <td>https://www.buzzfeed.com/kateaurthur/harvey-we...</td>\n      <td>Harvey Weinstein's Leave May Or May Not Be Per...</td>\n      <td>2017-10-07 00:24:08.404</td>\n      <td>2017-10-06 23:39:18</td>\n      <td>32</td>\n      <td>0.20</td>\n      <td>2017-10-07T00:35:07.428Z</td>\n      <td>2</td>\n      <td>13</td>\n      <td>17</td>\n      <td>...</td>\n      <td>2714137.00</td>\n      <td>2017-10-09T00:28:00.000Z</td>\n      <td>147</td>\n      <td>5.00</td>\n      <td>19.00</td>\n      <td>11.00</td>\n      <td>11.00</td>\n      <td>41.00</td>\n      <td>46.00</td>\n      <td>36.00</td>\n    </tr>\n    <tr>\n      <th>13fbafcfe4f592d7705b509fa4156fb1f30704d2</th>\n      <td>https://www.buzzfeed.com/verabergengruen/for-t...</td>\n      <td>For These Veterans, Growing Pot Isn't Just A J...</td>\n      <td>2017-10-18 14:01:22.471</td>\n      <td>2017-10-17 16:44:09</td>\n      <td>25</td>\n      <td>0.25</td>\n      <td>2017-10-18T17:14:11.226Z</td>\n      <td>0</td>\n      <td>9</td>\n      <td>16</td>\n      <td>...</td>\n      <td>2737415.00</td>\n      <td>2017-10-19T00:44:00.000Z</td>\n      <td>147</td>\n      <td>4.00</td>\n      <td>19.00</td>\n      <td>10.00</td>\n      <td>11.00</td>\n      <td>40.00</td>\n      <td>44.00</td>\n      <td>36.00</td>\n    </tr>\n    <tr>\n      <th>10d029b2ac847112ad6c076081c70041fcfe5fe3</th>\n      <td>https://www.buzzfeed.com/claudiarosenbaum/harv...</td>\n      <td>Harvey Weinstein Is Suing His Old Company To O...</td>\n      <td>2017-10-26 21:22:23.665</td>\n      <td>2017-10-26 21:20:36</td>\n      <td>67</td>\n      <td>0.11</td>\n      <td>2017-10-26T22:35:03.393Z</td>\n      <td>8</td>\n      <td>36</td>\n      <td>23</td>\n      <td>...</td>\n      <td>2747080.00</td>\n      <td>2017-10-27T03:27:00.000Z</td>\n      <td>147</td>\n      <td>8.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>50.00</td>\n      <td>34.00</td>\n    </tr>\n    <tr>\n      <th>ac204bbe8809292e367036ba771b54ca74182593</th>\n      <td>https://www.buzzfeed.com/karlazabludovsky/thes...</td>\n      <td>These Women Tried To Take Hashtag Activism Int...</td>\n      <td>2017-10-29 14:22:21.368</td>\n      <td>2017-10-28 13:28:16</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-29T14:34:05.941Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>0.00</td>\n      <td>34.00</td>\n      <td>34.00</td>\n      <td>34.00</td>\n    </tr>\n    <tr>\n      <th>7491dfb6c163d82d7010eb957bef64dd17ceabd2</th>\n      <td>https://www.buzzfeed.com/craigsilverman/rememb...</td>\n      <td>Myspace Looked Like It Was Back. Actually, It ...</td>\n      <td>2017-10-27 15:37:16.042</td>\n      <td>2017-10-27 15:16:17</td>\n      <td>126</td>\n      <td>0.39</td>\n      <td>2017-10-27T16:49:07.055Z</td>\n      <td>14</td>\n      <td>41</td>\n      <td>71</td>\n      <td>...</td>\n      <td>2747403.00</td>\n      <td>2017-10-27T16:20:27.000Z</td>\n      <td>147</td>\n      <td>11.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>56.00</td>\n      <td>34.00</td>\n    </tr>\n    <tr>\n      <th>b60e623d5f4a6d1295d7415b784122f18fa8e871</th>\n      <td>https://www.buzzfeed.com/adriancarrasquillo/th...</td>\n      <td>The Trump (Alternate) Reality Show</td>\n      <td>2017-10-09 22:13:24.662</td>\n      <td>2017-10-09 21:49:37</td>\n      <td>119</td>\n      <td>0.62</td>\n      <td>2017-10-10T00:25:09.375Z</td>\n      <td>36</td>\n      <td>60</td>\n      <td>23</td>\n      <td>...</td>\n      <td>2714352.00</td>\n      <td>2017-10-09T23:32:00.000Z</td>\n      <td>147</td>\n      <td>11.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>55.00</td>\n      <td>33.00</td>\n    </tr>\n    <tr>\n      <th>de1121cdb0ba8b77f91e9a68c7b5c4009054a70d</th>\n      <td>https://www.buzzfeed.com/hillarycrosleycoker/w...</td>\n      <td>Untitled Draft 10/06/2017 5:43 PM</td>\n      <td>2017-10-08 15:29:11.458</td>\n      <td>2017-10-07 00:29:42</td>\n      <td>1</td>\n      <td>0.00</td>\n      <td>2017-10-08T15:40:07.699Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>0.00</td>\n      <td>32.00</td>\n      <td>32.00</td>\n      <td>32.00</td>\n    </tr>\n    <tr>\n      <th>5b9ee08340d9d6f6c0d6dca6042220bf4bcb2721</th>\n      <td>https://www.buzzfeed.com/johnstanton/so-many-f...</td>\n      <td>So Many Father-Led Families Are Crossing The U...</td>\n      <td>2017-10-23 15:19:26.080</td>\n      <td>2017-10-23 15:16:49</td>\n      <td>185</td>\n      <td>0.60</td>\n      <td>2017-10-23T17:31:12.251Z</td>\n      <td>44</td>\n      <td>89</td>\n      <td>52</td>\n      <td>...</td>\n      <td>2745048.00</td>\n      <td>2017-10-23T16:21:42.000Z</td>\n      <td>147</td>\n      <td>13.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>58.00</td>\n      <td>32.00</td>\n    </tr>\n    <tr>\n      <th>320c913f5a57cb5b013ec7be22d48390164dd1b4</th>\n      <td>https://www.buzzfeed.com/paulmcleod/5-ways-pre...</td>\n      <td>5 Ways President Trump Could Undermine Obamaca...</td>\n      <td>2017-10-04 21:01:25.176</td>\n      <td>2017-10-04 20:57:53</td>\n      <td>73</td>\n      <td>0.59</td>\n      <td>2017-10-05T03:16:03.440Z</td>\n      <td>19</td>\n      <td>43</td>\n      <td>11</td>\n      <td>...</td>\n      <td>2712352.00</td>\n      <td>2017-10-05T02:44:00.000Z</td>\n      <td>147</td>\n      <td>8.00</td>\n      <td>19.00</td>\n      <td>9.00</td>\n      <td>11.00</td>\n      <td>39.00</td>\n      <td>47.00</td>\n      <td>31.00</td>\n    </tr>\n    <tr>\n      <th>b47452ed5f2cb6318349dfb6a3236caa0cbcdec5</th>\n      <td>https://www.buzzfeed.com/maryanngeorgantopoulo...</td>\n      <td>New York City Police Are Investigating Whether...</td>\n      <td>2017-10-12 14:37:25.142</td>\n      <td>2017-10-12 14:34:47</td>\n      <td>100</td>\n      <td>0.43</td>\n      <td>2017-10-12T17:51:06.310Z</td>\n      <td>21</td>\n      <td>53</td>\n      <td>26</td>\n      <td>...</td>\n      <td>2725035.00</td>\n      <td>2017-10-12T17:24:22.000Z</td>\n      <td>147</td>\n      <td>10.00</td>\n      <td>19.00</td>\n      <td>11.00</td>\n      <td>11.00</td>\n      <td>41.00</td>\n      <td>51.00</td>\n      <td>31.00</td>\n    </tr>\n    <tr>\n      <th>c4b8b37c6ceab237e6a8a93e2e04a843eb09918a</th>\n      <td>https://www.buzzfeed.com/venessawong/sweet-hyp...</td>\n      <td>Tom Brady Is A Health Nut. He's Also An Invest...</td>\n      <td>2017-10-18 19:46:30.979</td>\n      <td>2017-10-18 16:58:10</td>\n      <td>9</td>\n      <td>0.10</td>\n      <td>2017-10-18T19:57:08.176Z</td>\n      <td>1</td>\n      <td>0</td>\n      <td>8</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>2.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>0.00</td>\n      <td>33.00</td>\n      <td>35.00</td>\n      <td>31.00</td>\n    </tr>\n    <tr>\n      <th>18ced93ccf538cac448b4fb306877cb0947f2256</th>\n      <td>https://www.buzzfeed.com/kelseymckinney/missin...</td>\n      <td>Kelly Clarkson Isn't Afraid To Get Political</td>\n      <td>2017-10-28 01:49:07.796</td>\n      <td>2017-10-27 18:55:31</td>\n      <td>186</td>\n      <td>0.30</td>\n      <td>2017-10-28T02:00:06.264Z</td>\n      <td>15</td>\n      <td>145</td>\n      <td>26</td>\n      <td>...</td>\n      <td>2749535.00</td>\n      <td>2017-10-30T00:44:00.000Z</td>\n      <td>147</td>\n      <td>13.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>57.00</td>\n      <td>31.00</td>\n    </tr>\n    <tr>\n      <th>05982decb78deb49ed11c760acaef4e178c5c4d9</th>\n      <td>https://www.buzzfeed.com/nicolenguyen/iphone-x...</td>\n      <td>Life Without A Home Button: The iPhone X Review</td>\n      <td>2017-10-31 10:01:13.571</td>\n      <td>2017-10-28 18:38:14</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>2017-10-31T10:12:07.580Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>0.00</td>\n      <td>31.00</td>\n      <td>31.00</td>\n      <td>31.00</td>\n    </tr>\n    <tr>\n      <th>38b3de48740205c6e5fcdbdc8be85b48acc19711</th>\n      <td>https://www.buzzfeed.com/nathanieljanowitz/nar...</td>\n      <td>Narco Rap Is Hip-Hop\u2019s Most Dangerous Game</td>\n      <td>2017-10-08 20:24:13.762</td>\n      <td>2017-10-06 02:31:51</td>\n      <td>2</td>\n      <td>0.10</td>\n      <td>2017-10-08T20:35:08.810Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>0.00</td>\n      <td>32.00</td>\n      <td>33.00</td>\n      <td>31.00</td>\n    </tr>\n    <tr>\n      <th>8d7362720fea9158facbee073354948f3b846c28</th>\n      <td>https://www.buzzfeed.com/borzoudaragahi/us-pla...</td>\n      <td>US Plans For Victory In Afghanistan Could End ...</td>\n      <td>2017-10-28 14:46:18.737</td>\n      <td>2017-10-26 18:42:07</td>\n      <td>2</td>\n      <td>0.20</td>\n      <td>2017-10-28T14:57:07.689Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>0.00</td>\n      <td>32.00</td>\n      <td>33.00</td>\n      <td>31.00</td>\n    </tr>\n    <tr>\n      <th>0e4ad3fc3a855762723b2438525a82252f93d5d3</th>\n      <td>https://www.buzzfeed.com/morganshanahan/workin...</td>\n      <td>Working For Harvey Weinstein Taught Me What Ra...</td>\n      <td>2017-10-20 18:39:11.862</td>\n      <td>2017-10-13 23:23:48</td>\n      <td>6</td>\n      <td>0.00</td>\n      <td>2017-10-20T18:50:10.877Z</td>\n      <td>0</td>\n      <td>1</td>\n      <td>5</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>2.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>0.00</td>\n      <td>33.00</td>\n      <td>35.00</td>\n      <td>31.00</td>\n    </tr>\n    <tr>\n      <th>fa9ad17dbcd5db37d3dfb331a1426a8a3c7e3116</th>\n      <td>https://www.buzzfeed.com/nidhiprakash/lost-his...</td>\n      <td>Adrian Lost His Home During Maria. He's Back A...</td>\n      <td>2017-10-01 20:52:30.257</td>\n      <td>2017-10-01 19:10:05</td>\n      <td>79</td>\n      <td>0.35</td>\n      <td>2017-10-02T05:07:11.362Z</td>\n      <td>1</td>\n      <td>64</td>\n      <td>14</td>\n      <td>...</td>\n      <td>2709223.00</td>\n      <td>2017-10-02T04:01:42.000Z</td>\n      <td>147</td>\n      <td>9.00</td>\n      <td>19.00</td>\n      <td>10.00</td>\n      <td>11.00</td>\n      <td>40.00</td>\n      <td>49.00</td>\n      <td>31.00</td>\n    </tr>\n    <tr>\n      <th>7c39ccb58f94bdbe57fad67af14692806c347d57</th>\n      <td>https://www.buzzfeed.com/franciswhittaker/spai...</td>\n      <td>Spain Has Said It Will Impose Direct Rule Over...</td>\n      <td>2017-10-19 09:01:17.429</td>\n      <td>2017-10-19 08:47:06</td>\n      <td>88</td>\n      <td>0.79</td>\n      <td>2017-10-19T09:12:08.044Z</td>\n      <td>7</td>\n      <td>57</td>\n      <td>24</td>\n      <td>...</td>\n      <td>2738044.00</td>\n      <td>2017-10-19T09:02:40.000Z</td>\n      <td>147</td>\n      <td>9.00</td>\n      <td>19.00</td>\n      <td>9.00</td>\n      <td>11.00</td>\n      <td>39.00</td>\n      <td>48.00</td>\n      <td>30.00</td>\n    </tr>\n    <tr>\n      <th>28014b7339c6f16c897d4ae416d388a57cec60de</th>\n      <td>https://www.buzzfeed.com/mollyhensleyclancy/mi...</td>\n      <td>Mike Pence's Closest Ally Is Helping The Shady...</td>\n      <td>2017-10-25 18:10:23.537</td>\n      <td>2017-10-24 22:24:25</td>\n      <td>15</td>\n      <td>0.10</td>\n      <td>2017-10-25T19:23:03.906Z</td>\n      <td>0</td>\n      <td>2</td>\n      <td>13</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>3.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>0.00</td>\n      <td>33.00</td>\n      <td>36.00</td>\n      <td>30.00</td>\n    </tr>\n    <tr>\n      <th>f5a4f3299d5df22bc47653c1ecf7d036389c835d</th>\n      <td>http://www.independent.co.uk/news/uk/crime/gro...</td>\n      <td>Grooming gangs 'are abusing girls across the c...</td>\n      <td>2017-10-08 19:34:24.651</td>\n      <td>2017-10-06 17:38:44</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-10-08T19:45:11.610Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>7610637.00</td>\n      <td>2017-10-09T09:08:24.000Z</td>\n      <td>386</td>\n      <td>0.00</td>\n      <td>16.00</td>\n      <td>1.00</td>\n      <td>13.00</td>\n      <td>30.00</td>\n      <td>30.00</td>\n      <td>30.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>25 rows \u00d7 26 columns</p>\n</div>\n\n\n\n\n```python\n# high response but not promoted\ndata.sort_values(\"score_diff\", ascending=True).head(25)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n      <th>score_diff</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>71e81f0fcfa22600f98d3cc4ee27936533a4dd6d</th>\n      <td>https://www.nytimes.com/2017/10/19/opinion/lup...</td>\n      <td>Lupita Nyong\u2019o: What Harvey Weinstein Did to Me</td>\n      <td>2017-10-19 23:10:05.465</td>\n      <td>2017-10-19 23:07:39.000</td>\n      <td>220864</td>\n      <td>348.36</td>\n      <td>2017-10-20T01:13:06.889Z</td>\n      <td>17754</td>\n      <td>170298</td>\n      <td>32812</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>120</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>46291bc86b71eb9568baeacc57bb29da4aa758c4</th>\n      <td>http://www.washingtonpost.com/video/politics/t...</td>\n      <td>Trump says he 'met with the president of the V...</td>\n      <td>2017-10-13 15:04:21.372</td>\n      <td>2017-10-13 14:40:20.000</td>\n      <td>108872</td>\n      <td>120.46</td>\n      <td>2017-10-13T21:35:05.768Z</td>\n      <td>39459</td>\n      <td>57244</td>\n      <td>12169</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>8583d374f97cb80471a866e026c2a2114ac22b11</th>\n      <td>https://www.buzzfeed.com/karlazabludovsky/miss...</td>\n      <td>Em vez de suas medidas, as candidatas a Miss P...</td>\n      <td>2017-10-31 12:34:10.273</td>\n      <td>2017-10-31 12:33:01.000</td>\n      <td>85716</td>\n      <td>100.23</td>\n      <td>2017-10-31T20:07:10.376Z</td>\n      <td>1614</td>\n      <td>80030</td>\n      <td>4072</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>49.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>c49994bf9bef90ef3cf7ce862b2d09a51199cba1</th>\n      <td>https://www.rt.com/on-air/407672-white-house-n...</td>\n      <td>White House holds news briefing</td>\n      <td>2017-10-24 19:54:26.936</td>\n      <td>2017-10-24 19:54:26.936</td>\n      <td>177442</td>\n      <td>2947.13</td>\n      <td>2017-10-24T23:06:06.316Z</td>\n      <td>24436</td>\n      <td>10728</td>\n      <td>142278</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>365</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>d6eab40c5d349770d620186b1b1bfdad866a6846</th>\n      <td>https://www.washingtonpost.com/news/answer-she...</td>\n      <td>9 million kids get health insurance under CHIP...</td>\n      <td>2017-10-01 17:31:23.893</td>\n      <td>2017-10-01 17:26:15.000</td>\n      <td>111959</td>\n      <td>85.87</td>\n      <td>2017-10-02T16:20:07.039Z</td>\n      <td>14799</td>\n      <td>72543</td>\n      <td>24617</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>d6bbd1d2c466964efa980539db7814a33b8c2e20</th>\n      <td>https://www.rt.com/on-air/407022-candlelit-mar...</td>\n      <td>Candlelit march held in Barcelona in solidarit...</td>\n      <td>2017-10-17 17:54:24.750</td>\n      <td>2017-10-17 17:52:46.000</td>\n      <td>177581</td>\n      <td>2902.54</td>\n      <td>2017-10-17T22:07:04.448Z</td>\n      <td>24414</td>\n      <td>10853</td>\n      <td>142314</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>365</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>93d2e448be2afe095cdf31db88283f7d635eb3c0</th>\n      <td>http://www.foxnews.com/us/2017/10/30/miami-art...</td>\n      <td>Miami art professor turns American flags into ...</td>\n      <td>2017-10-30 21:49:14.134</td>\n      <td>2017-10-30 18:16:40.000</td>\n      <td>157318</td>\n      <td>67.36</td>\n      <td>2017-11-02T16:59:10.278Z</td>\n      <td>45507</td>\n      <td>91575</td>\n      <td>20236</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>f9695aa2c3ffc63dd26bf44f6a0cb6db2f93c28d</th>\n      <td>http://www.foxnews.com/us/2017/10/08/vice-pres...</td>\n      <td>Vice President Mike Pence leaves Colts-49ers g...</td>\n      <td>2017-10-08 17:39:14.984</td>\n      <td>2017-10-08 17:30:30.000</td>\n      <td>904129</td>\n      <td>3142.79</td>\n      <td>2017-10-08T19:13:11.760Z</td>\n      <td>118524</td>\n      <td>749560</td>\n      <td>36045</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>52.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>0ecdbba916a0f44b8091a64825d318312ceb86e1</th>\n      <td>https://www.nbcnews.com/storyline/hurricane-ha...</td>\n      <td>Former presidents call for unity at hurricane ...</td>\n      <td>2017-10-22 02:54:14.794</td>\n      <td>2017-10-22 02:51:38.000</td>\n      <td>83119</td>\n      <td>235.52</td>\n      <td>2017-10-22T05:16:11.007Z</td>\n      <td>2938</td>\n      <td>76430</td>\n      <td>3751</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>826</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>50.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>85451623cabf0c4f4b2a628b63c45a9c3d5223be</th>\n      <td>https://www.buzzfeed.com/juliegerstein/aparent...</td>\n      <td>Aparentemente muitos homens n\u00e3o est\u00e3o limpando...</td>\n      <td>2017-10-20 17:16:27.237</td>\n      <td>2017-10-20 17:11:08.000</td>\n      <td>70541</td>\n      <td>54.90</td>\n      <td>2017-10-20T19:41:08.448Z</td>\n      <td>28801</td>\n      <td>37496</td>\n      <td>4244</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>48.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>48.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>dfdd5c1f0626392c60c7fc785753ac61e23a4a76</th>\n      <td>http://www.foxnews.com/politics/2017/10/05/veg...</td>\n      <td>Vegas survivor: Shot in leg or not, I'm standi...</td>\n      <td>2017-10-05 10:04:09.875</td>\n      <td>2017-10-05 09:10:49.000</td>\n      <td>382395</td>\n      <td>1039.10</td>\n      <td>2017-10-05T21:55:10.762Z</td>\n      <td>31082</td>\n      <td>335970</td>\n      <td>15343</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>52.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>506176e75a9998207c4d4391b4a6d891624d9578</th>\n      <td>http://www.foxnews.com/entertainment/2017/10/0...</td>\n      <td>Tom Petty rushed to hospital in full cardiac a...</td>\n      <td>2017-10-02 19:29:16.977</td>\n      <td>2017-10-02 19:23:32.000</td>\n      <td>101301</td>\n      <td>870.20</td>\n      <td>2017-10-02T20:12:06.132Z</td>\n      <td>26812</td>\n      <td>58352</td>\n      <td>16137</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>52.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>995586179a2b62c4c187efbb842341c2abbcf2ee</th>\n      <td>http://www.cnn.com/2014/10/16/health/dying-reg...</td>\n      <td>What the dying really regret</td>\n      <td>2017-10-25 17:43:29.996</td>\n      <td>2017-10-25 17:38:54.000</td>\n      <td>75132</td>\n      <td>0.11</td>\n      <td>2017-10-26T03:04:03.689Z</td>\n      <td>10061</td>\n      <td>41716</td>\n      <td>23355</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>105</td>\n      <td>48.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>48.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>e6eaeb88e30f277baf8afc2f97e192a3a3d27aa7</th>\n      <td>http://www.dailymail.co.uk/health/article-4978...</td>\n      <td>FDA to make smaller condoms for US men's small...</td>\n      <td>2017-10-13 18:49:25.881</td>\n      <td>2017-10-13 18:44:15.000</td>\n      <td>79292</td>\n      <td>52.82</td>\n      <td>2017-10-16T16:24:05.886Z</td>\n      <td>34180</td>\n      <td>39561</td>\n      <td>5551</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>50.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>93a629d08de6c04301eba6fc897114bc1bf289d8</th>\n      <td>http://www.foxnews.com/tech/2017/10/18/nurse-f...</td>\n      <td>Nurse fleeing California wildfires puts horse ...</td>\n      <td>2017-10-18 13:29:16.707</td>\n      <td>2017-10-18 13:23:23.000</td>\n      <td>73479</td>\n      <td>42.46</td>\n      <td>2017-10-19T00:48:10.628Z</td>\n      <td>5939</td>\n      <td>58527</td>\n      <td>9013</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>48.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>49.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>28af9b5c0c790680105df76276c159c45958a969</th>\n      <td>https://www.independent.co.uk/life-style/gadge...</td>\n      <td>Bill Gates and Steve Jobs raised their kids te...</td>\n      <td>2017-10-24 12:37:19.509</td>\n      <td>2017-10-24 12:36:56.000</td>\n      <td>62002</td>\n      <td>24.79</td>\n      <td>2017-10-24T21:53:09.678Z</td>\n      <td>6642</td>\n      <td>42168</td>\n      <td>13192</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>386</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>47.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>c35287599493e1e4b27c3361a44f8226cd04cb70</th>\n      <td>https://www.theguardian.com/technology/2017/oc...</td>\n      <td>Facebook moving non-promoted posts out of news...</td>\n      <td>2017-10-23 14:16:05.569</td>\n      <td>2017-10-23 14:12:22.000</td>\n      <td>78338</td>\n      <td>726.25</td>\n      <td>2017-10-23T19:31:03.676Z</td>\n      <td>24161</td>\n      <td>47065</td>\n      <td>7112</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>142</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>51.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>e352ce2c14cfa3c5ded9f882bb90b9da05402e2e</th>\n      <td>https://www.buzzfeed.com/tatianafarah/foi-assi...</td>\n      <td>Foi assim que ficou um terreiro de candombl\u00e9 a...</td>\n      <td>2017-10-04 12:52:17.858</td>\n      <td>2017-10-03 19:46:01.000</td>\n      <td>59119</td>\n      <td>172.94</td>\n      <td>2017-10-04T20:44:08.660Z</td>\n      <td>4796</td>\n      <td>51898</td>\n      <td>2425</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>47.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>ca5664929841d69ccf73b822f25891f97e86076e</th>\n      <td>http://www.cnn.com/videos/politics/2017/10/18/...</td>\n      <td>Trump to widow: He knew what he signed up for ...</td>\n      <td>2017-10-18 02:59:11.292</td>\n      <td>2017-10-18 02:47:34.000</td>\n      <td>83934</td>\n      <td>104.68</td>\n      <td>2017-10-18T13:22:08.291Z</td>\n      <td>31597</td>\n      <td>41668</td>\n      <td>10669</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>105</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>52.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>e0d847f0bb693e793094a0c23a0eaf336825a13e</th>\n      <td>https://www.independent.co.uk/life-style/gadge...</td>\n      <td>Tesla is sending hundreds of battery packs to ...</td>\n      <td>2017-10-01 12:04:25.173</td>\n      <td>2017-10-01 12:00:00.000</td>\n      <td>52437</td>\n      <td>58.07</td>\n      <td>2017-10-01T21:31:03.254Z</td>\n      <td>1621</td>\n      <td>46157</td>\n      <td>4659</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>386</td>\n      <td>46.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>46.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>50a7d9a142ba7e8e5658ce49ad9f91547f0d77a9</th>\n      <td>https://www.nytimes.com/2017/10/12/opinion/boy...</td>\n      <td>The Fake Wokeness of the Boy Scouts</td>\n      <td>2017-10-12 19:19:10.391</td>\n      <td>2017-10-12 19:15:39.000</td>\n      <td>60892</td>\n      <td>29.45</td>\n      <td>2017-10-13T14:41:09.376Z</td>\n      <td>20783</td>\n      <td>33141</td>\n      <td>6968</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>120</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>48.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>da37a2f01f73622f42e5beb27b378243862c0928</th>\n      <td>http://www.foxnews.com/entertainment/2017/10/1...</td>\n      <td>Jane Fonda says she's not proud of America</td>\n      <td>2017-10-17 12:04:15.903</td>\n      <td>2017-10-17 12:04:15.903</td>\n      <td>66001</td>\n      <td>65.07</td>\n      <td>2017-10-17T19:06:10.125Z</td>\n      <td>38311</td>\n      <td>22952</td>\n      <td>4738</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>48.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>50.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>29d8cd062a9294cb9543c1241969947b11bd0607</th>\n      <td>https://www.washingtonpost.com/news/politics/w...</td>\n      <td>Pence, set to attend today\u2019s Indianapolis Colt...</td>\n      <td>2017-10-08 17:29:09.707</td>\n      <td>2017-10-08 17:26:00.000</td>\n      <td>61817</td>\n      <td>324.48</td>\n      <td>2017-10-08T19:41:11.305Z</td>\n      <td>28310</td>\n      <td>29868</td>\n      <td>3639</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>48.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>abbed45b5d1204302548c2fb89448d7a9ee4ed3a</th>\n      <td>https://www.nytimes.com/2017/10/24/us/politics...</td>\n      <td>Partial Transcript: Jeff Flake\u2019s Speech on the...</td>\n      <td>2017-10-24 19:31:12.448</td>\n      <td>2017-10-24 19:29:29.000</td>\n      <td>97127</td>\n      <td>306.80</td>\n      <td>2017-10-25T11:03:06.559Z</td>\n      <td>22181</td>\n      <td>62315</td>\n      <td>12631</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>120</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n      <td>54.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>1c4f032c3222a7f9d02aa7ec5406f17503dd4fb8</th>\n      <td>http://yournewswire.com/morgan-freeman-jail-hi...</td>\n      <td>Morgan Freeman: 'Jailing Hillary' Best Way To ...</td>\n      <td>2017-10-29 19:19:22.587</td>\n      <td>2017-10-29 17:31:04.000</td>\n      <td>97780</td>\n      <td>41.09</td>\n      <td>2017-10-30T23:28:11.292Z</td>\n      <td>18882</td>\n      <td>64837</td>\n      <td>14061</td>\n      <td>...</td>\n      <td>27003.00</td>\n      <td>2017-10-30T13:51:01.000Z</td>\n      <td>22568</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>4.00</td>\n      <td>5.00</td>\n      <td>55.00</td>\n      <td>-45.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>25 rows \u00d7 26 columns</p>\n</div>\n\n\n\nWrite that data to a file. Note that the scores here are provisional for two reasons:\n1. they should be using a rolling-month based on the article publication date to calculate medians/min/max etc, whereas in this workbook we as just using values for the month of May\n2. for analysis, we've rounded the numbers; we don't expect to do that for the actual scores\n\n\n```python\ndata.to_csv(\"articles_with_provisional_scores_2017-10-01_2017-10-31.csv\")\n```\n\n# Summary\n\nThe attention index of an article is comprised of four components:\n\n- *lead score* (max 20 points) based on how long an article was the lead story on the publisher's home page, scaled by the traffic to that publisher\n- *front score* (max 15 points) based on how long an article was present on the publisher's home page, scaled by traffic to that publisher\n- *Facebook promotion score* (max 15 points) based on whether the article was promoted to the publisher's Facebook brand page, scaled by the reach of that brand page\n- *response score* (max 50 points) based on the number of Facebook engagements the article received, relative to other articles\n\nOr, in other words:\n\n\\begin{align}\nattentionIndex_a &= leadScore_a + frontScore_a + facebookPromotionScore_a + responseScore_a \\\\\nleadScore_a &= 20 \\cdot \\left(\\frac{\\min(minsAsLead_a, 60)}{alexaRank_a}\\right) \\cdot \\left( \\frac{\\min(alexaRank)}{60} \\right) \\\\\nfrontScore_a &= \n15 \\cdot\n\\left(\\frac{\\min(minsOnFront_a, 1440)}{alexaRank_a \\cdot numArticlesOnFront_a}\\right) \\cdot\n\\left( \\frac{\\min(alexaRank \\cdot numArticlesOnFront)}{1440} \\right) \\\\\nfacebookPromotion_a &= \n\\begin{cases}\n 0 \\text{ if not shared on brand page }\\\\\n   15 \\cdot \\frac{\\log(brandPageLikes_a) - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))}  \\text{ otherwise }\n\\end{cases}   \n\\\\\nresponseScore_a &= \n\\begin{cases} \n   0 \\text{ if } engagements_a = 0 \\\\\n   50 \\cdot \n   \\frac{\\log(\\min(engagements_a,limit) + median(engagements)) - \\log(1 + median(engagements))}\n   {\\log(limit + median(engagements)) - \\log(1 + median(engagements))} \\text{ if } engagements_a > 0\n\\end{cases} \\\\\n\\end{align} \n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "7867bc35417fe633d7d1badb4747d277a2125b13", "size": 738449, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "data/attention-index-october.ipynb", "max_stars_repo_name": "kaleida/attention-index", "max_stars_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2017-06-03T11:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T10:02:06.000Z", "max_issues_repo_path": "data/attention-index-october.ipynb", "max_issues_repo_name": "kaleida/attention-index", "max_issues_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data/attention-index-october.ipynb", "max_forks_repo_name": "kaleida/attention-index", "max_forks_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 85.3303674601, "max_line_length": 47066, "alphanum_fraction": 0.6929063483, "converted": true, "num_tokens": 56445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742626558767584, "lm_q2_score": 0.04885777394802062, "lm_q1q2_score": 0.015508740729247022}}
{"text": "```python\nimport sys\n!{sys.executable} -m pip install -U turicreate matplotlib opencv-python\nimport turicreate as tc\nimport numpy as np\nimport os\nimport glob\n```\n\n    Requirement already satisfied: turicreate in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (6.4.1)\n    Requirement already satisfied: matplotlib in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (3.3.4)\n    Requirement already satisfied: opencv-python in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (4.5.1.48)\n    Collecting matplotlib\n      Downloading matplotlib-3.4.1-cp38-cp38-macosx_10_9_x86_64.whl (7.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 7.2 MB 3.4 MB/s eta 0:00:01     |\u258c                               | 112 kB 3.4 MB/s eta 0:00:03     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589                      | 2.2 MB 3.4 MB/s eta 0:00:02\n    \u001b[?25hRequirement already satisfied: kiwisolver>=1.0.1 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from matplotlib) (1.3.1)\n    Requirement already satisfied: pyparsing>=2.2.1 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from matplotlib) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from matplotlib) (0.10.0)\n    Requirement already satisfied: python-dateutil>=2.7 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from matplotlib) (2.8.1)\n    Requirement already satisfied: pillow>=6.2.0 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from matplotlib) (8.1.0)\n    Requirement already satisfied: numpy>=1.16 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from matplotlib) (1.19.5)\n    Requirement already satisfied: six in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from cycler>=0.10->matplotlib) (1.15.0)\n    Requirement already satisfied: requests>=2.9.1 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from turicreate) (2.25.1)\n    Requirement already satisfied: scipy>=1.1.0 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from turicreate) (1.6.0)\n    Requirement already satisfied: resampy==0.2.1 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from turicreate) (0.2.1)\n    Requirement already satisfied: tensorflow>=2.0.0 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from turicreate) (2.4.1)\n    Requirement already satisfied: pandas>=0.23.2 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from turicreate) (1.2.2)\n    Requirement already satisfied: prettytable==0.7.2 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from turicreate) (0.7.2)\n    Requirement already satisfied: decorator>=4.0.9 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from turicreate) (4.4.2)\n    Requirement already satisfied: coremltools==4.0b3 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from turicreate) (4.0b3)\n    Requirement already satisfied: sympy in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from coremltools==4.0b3->turicreate) (1.7.1)\n    Requirement already satisfied: attrs in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from coremltools==4.0b3->turicreate) (20.3.0)\n    Requirement already satisfied: protobuf>=3.1.0 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from coremltools==4.0b3->turicreate) (3.14.0)\n    Requirement already satisfied: attr in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from coremltools==4.0b3->turicreate) (0.3.1)\n    Requirement already satisfied: tqdm in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from coremltools==4.0b3->turicreate) (4.56.2)\n    Requirement already satisfied: numba>=0.32 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from resampy==0.2.1->turicreate) (0.52.0)\n    Requirement already satisfied: setuptools in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from numba>=0.32->resampy==0.2.1->turicreate) (52.0.0.post20210125)\n    Requirement already satisfied: llvmlite<0.36,>=0.35.0 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from numba>=0.32->resampy==0.2.1->turicreate) (0.35.0)\n    Requirement already satisfied: pytz>=2017.3 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from pandas>=0.23.2->turicreate) (2021.1)\n    Requirement already satisfied: certifi>=2017.4.17 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from requests>=2.9.1->turicreate) (2020.12.5)\n    Requirement already satisfied: urllib3<1.27,>=1.21.1 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from requests>=2.9.1->turicreate) (1.26.3)\n    Requirement already satisfied: chardet<5,>=3.0.2 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from requests>=2.9.1->turicreate) (4.0.0)\n    Requirement already satisfied: idna<3,>=2.5 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from requests>=2.9.1->turicreate) (2.10)\n    Requirement already satisfied: keras-preprocessing~=1.1.2 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from tensorflow>=2.0.0->turicreate) (1.1.2)\n    Requirement already satisfied: termcolor~=1.1.0 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from tensorflow>=2.0.0->turicreate) (1.1.0)\n    Requirement already satisfied: gast==0.3.3 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from tensorflow>=2.0.0->turicreate) (0.3.3)\n    Requirement already satisfied: absl-py~=0.10 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from tensorflow>=2.0.0->turicreate) (0.11.0)\n    Requirement already satisfied: wheel~=0.35 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from tensorflow>=2.0.0->turicreate) (0.36.2)\n    Requirement already satisfied: wrapt~=1.12.1 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from tensorflow>=2.0.0->turicreate) (1.12.1)\n    Requirement already satisfied: google-pasta~=0.2 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from tensorflow>=2.0.0->turicreate) (0.2.0)\n    Requirement already satisfied: opt-einsum~=3.3.0 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from tensorflow>=2.0.0->turicreate) (3.3.0)\n    Requirement already satisfied: grpcio~=1.32.0 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from tensorflow>=2.0.0->turicreate) (1.32.0)\n    Requirement already satisfied: typing-extensions~=3.7.4 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from tensorflow>=2.0.0->turicreate) (3.7.4.3)\n    Requirement already satisfied: h5py~=2.10.0 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from tensorflow>=2.0.0->turicreate) (2.10.0)\n    Requirement already satisfied: tensorflow-estimator<2.5.0,>=2.4.0 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from tensorflow>=2.0.0->turicreate) (2.4.0)\n    Requirement already satisfied: astunparse~=1.6.3 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from tensorflow>=2.0.0->turicreate) (1.6.3)\n    Requirement already satisfied: tensorboard~=2.4 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from tensorflow>=2.0.0->turicreate) (2.4.1)\n    Requirement already satisfied: flatbuffers~=1.12.0 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from tensorflow>=2.0.0->turicreate) (1.12)\n    Requirement already satisfied: markdown>=2.6.8 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from tensorboard~=2.4->tensorflow>=2.0.0->turicreate) (3.3.3)\n    Requirement already satisfied: werkzeug>=0.11.15 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from tensorboard~=2.4->tensorflow>=2.0.0->turicreate) (1.0.1)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from tensorboard~=2.4->tensorflow>=2.0.0->turicreate) (0.4.2)\n    Requirement already satisfied: google-auth<2,>=1.6.3 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from tensorboard~=2.4->tensorflow>=2.0.0->turicreate) (1.26.1)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from tensorboard~=2.4->tensorflow>=2.0.0->turicreate) (1.8.0)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from google-auth<2,>=1.6.3->tensorboard~=2.4->tensorflow>=2.0.0->turicreate) (4.7.1)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from google-auth<2,>=1.6.3->tensorboard~=2.4->tensorflow>=2.0.0->turicreate) (4.2.1)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from google-auth<2,>=1.6.3->tensorboard~=2.4->tensorflow>=2.0.0->turicreate) (0.2.8)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.4->tensorflow>=2.0.0->turicreate) (1.3.0)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard~=2.4->tensorflow>=2.0.0->turicreate) (0.4.8)\n    Requirement already satisfied: oauthlib>=3.0.0 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.4->tensorflow>=2.0.0->turicreate) (3.1.0)\n    Requirement already satisfied: mpmath>=0.19 in /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages (from sympy->coremltools==4.0b3->turicreate) (1.2.1)\n    Installing collected packages: matplotlib\n      Attempting uninstall: matplotlib\n        Found existing installation: matplotlib 3.3.4\n        Uninstalling matplotlib-3.3.4:\n          Successfully uninstalled matplotlib-3.3.4\n    Successfully installed matplotlib-3.4.1\n\n\n\n```python\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nimport cv2\nclasses = [\"arrow\", \"circle\", \"cycle\"]\nfor ml_class in classes:\n    images = []\n    image_labels = []\n    files = glob.glob (f\"data/images/{ml_class}/*\")\n    for image_file in files:\n        im = Image.open(image_file)\n        im = np.array(im)\n        images.append(im)\n\n    images = np.array(images)\n    np.save(f'data/bitmaps/{ml_class}.npy', images)\n```\n\n\n```python\n# mostly taken from: https://github.com/apple/turicreate/blob/master/userguide/drawing_classifier/data-preparation.md\n\nrandom_state = np.random.RandomState(100)\n\n# Change if applicable\ndata_dir = 'data'\nbitmaps_dir = os.path.join(data_dir, 'bitmaps')\nsframes_dir = os.path.join(data_dir, 'sframes')\nnpy_ext = '.npy'\nnum_examples_per_class = 200\nnum_classes = len(classes)\n\ndef build_bitmap_sframe():\n    bitmaps_list, labels_list = [], []\n    for class_name in classes:\n        class_data = np.load(os.path.join(bitmaps_dir, class_name + npy_ext))\n        random_state.shuffle(class_data)\n        class_data_selected = class_data[:num_examples_per_class]\n        for np_pixel_data in class_data_selected:\n            FORMAT_RAW = 2\n            bitmap = tc.Image(_image_data = np_pixel_data.tobytes(),\n                              _width = np_pixel_data.shape[1],\n                              _height = np_pixel_data.shape[0],\n                              _channels = 1,\n                              _format_enum = FORMAT_RAW,\n                              _image_data_size = np_pixel_data.size)\n            bitmaps_list.append(bitmap)\n            labels_list.append(class_name)\n\n    sf = tc.SFrame({\"drawing\": bitmaps_list, \"label\": labels_list})\n    sf.save(os.path.join(sframes_dir, \"bitmap_data.sframe\"))\n    return sf \n\nsf = build_bitmap_sframe()\n```\n\n\n```python\nsf.explore()\n```\n\n    /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages/turicreate/visualization/_plot.py:461: UserWarning: Displaying only the first 100 rows.\n      warnings.warn(\"Displaying only the first {} rows.\".format(maximum_rows))\n\n\n\n<html lang=\"en\">                                                     <head>                                                               <style>                                                              .sframe {                                                            font-size: 12px;                                                   font-family: HelveticaNeue;                                        border: 1px solid silver;                                        }                                                                  .sframe thead th {                                                   background: #F7F7F7;                                               font-family: HelveticaNeue-Medium;                                 font-size: 14px;                                                   line-height: 16.8px;                                               padding-top: 16px;                                                 padding-bottom: 16px;                                              padding-left: 10px;                                                padding-right: 38px;                                               border-top: 1px solid #E9E9E9;                                     border-bottom: 1px solid #E9E9E9;                                  white-space: nowrap;                                               overflow: hidden;                                                  text-overflow:ellipsis;                                            text-align:center;                                                 font-weight:normal;                                              }                                                                  .sframe tbody th {                                                   background: #FFFFFF;                                               text-align:left;                                                   font-weight:normal;                                                border-right: 1px solid #E9E9E9;                                 }                                                                  .sframe td {                                                         background: #FFFFFF;                                               padding-left: 10px;                                                padding-right: 38px;                                               padding-top: 14px;                                                 padding-bottom: 14px;                                              border-bottom: 1px solid #E9E9E9;                                  max-height: 0px;                                                   transition: max-height 5s ease-out;                                vertical-align: middle;                                            font-family: HelveticaNeue;                                        font-size: 12px;                                                   line-height: 16.8px;                                               background: #FFFFFF;                                             }                                                                  .sframe tr {                                                         padding-left: 10px;                                                padding-right: 38px;                                               padding-top: 14px;                                                 padding-bottom: 14px;                                              border-bottom: 1px solid #E9E9E9;                                  max-height: 0px;                                                   transition: max-height 5s ease-out;                                vertical-align: middle;                                            font-family: HelveticaNeue;                                        font-size: 12px;                                                   line-height: 16.8px;                                               background: #FFFFFF;                                             }                                                                  .sframe tr:hover {                                                   background: silver;                                              },                                                               </style>                                                         </head>                                                            <body>                                                               <h1>  </h1>                                             <table border=\"1\" class=\"dataframe sframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>drawing</th>\n      <th>label</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>30</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>31</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>32</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>33</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>34</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>35</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>36</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>37</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>38</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>39</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>40</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>41</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>42</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>43</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>44</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>45</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>46</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>47</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>48</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>49</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>50</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>51</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>52</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>53</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>54</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>55</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>56</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>57</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>58</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>59</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>60</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>61</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>62</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>63</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>64</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>65</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>66</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>67</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>68</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>69</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>70</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>71</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>72</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>73</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>74</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>75</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>76</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>77</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>78</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>79</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>80</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>81</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>82</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>83</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>84</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>85</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>86</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>87</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>88</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>89</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>90</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>91</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>92</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>93</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>94</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>95</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>96</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>97</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>98</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>99</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n  </tbody>\n</table>                          </body>                                                          </html>\n\n\n\n```python\nSFRAME_PATH = \"data/sframes/bitmap_data.sframe\"\ndata =  tc.SFrame(SFRAME_PATH)\n```\n\n\n```python\ndata.explore()\n```\n\n    /Users/marekfort/opt/miniconda3/envs/automata-editor/lib/python3.8/site-packages/turicreate/visualization/_plot.py:461: UserWarning: Displaying only the first 100 rows.\n      warnings.warn(\"Displaying only the first {} rows.\".format(maximum_rows))\n\n\n\n<html lang=\"en\">                                                     <head>                                                               <style>                                                              .sframe {                                                            font-size: 12px;                                                   font-family: HelveticaNeue;                                        border: 1px solid silver;                                        }                                                                  .sframe thead th {                                                   background: #F7F7F7;                                               font-family: HelveticaNeue-Medium;                                 font-size: 14px;                                                   line-height: 16.8px;                                               padding-top: 16px;                                                 padding-bottom: 16px;                                              padding-left: 10px;                                                padding-right: 38px;                                               border-top: 1px solid #E9E9E9;                                     border-bottom: 1px solid #E9E9E9;                                  white-space: nowrap;                                               overflow: hidden;                                                  text-overflow:ellipsis;                                            text-align:center;                                                 font-weight:normal;                                              }                                                                  .sframe tbody th {                                                   background: #FFFFFF;                                               text-align:left;                                                   font-weight:normal;                                                border-right: 1px solid #E9E9E9;                                 }                                                                  .sframe td {                                                         background: #FFFFFF;                                               padding-left: 10px;                                                padding-right: 38px;                                               padding-top: 14px;                                                 padding-bottom: 14px;                                              border-bottom: 1px solid #E9E9E9;                                  max-height: 0px;                                                   transition: max-height 5s ease-out;                                vertical-align: middle;                                            font-family: HelveticaNeue;                                        font-size: 12px;                                                   line-height: 16.8px;                                               background: #FFFFFF;                                             }                                                                  .sframe tr {                                                         padding-left: 10px;                                                padding-right: 38px;                                               padding-top: 14px;                                                 padding-bottom: 14px;                                              border-bottom: 1px solid #E9E9E9;                                  max-height: 0px;                                                   transition: max-height 5s ease-out;                                vertical-align: middle;                                            font-family: HelveticaNeue;                                        font-size: 12px;                                                   line-height: 16.8px;                                               background: #FFFFFF;                                             }                                                                  .sframe tr:hover {                                                   background: silver;                                              },                                                               </style>                                                         </head>                                                            <body>                                                               <h1>  </h1>                                             <table border=\"1\" class=\"dataframe sframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>drawing</th>\n      <th>label</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>30</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>31</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>32</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>33</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>34</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>35</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>36</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>37</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>38</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>39</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>40</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>41</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>42</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>43</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>44</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>45</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>46</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>47</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>48</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>49</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>50</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>51</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>52</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>53</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>54</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>55</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>56</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>57</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>58</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>59</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>60</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>61</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>62</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>63</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>64</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>65</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>66</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>67</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>68</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>69</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>70</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>71</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>72</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>73</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>74</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>75</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>76</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>77</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>78</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>79</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>80</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>81</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>82</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>83</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>84</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>85</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>86</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>87</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>88</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>89</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>90</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>91</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>92</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>93</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>94</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>95</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>96</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>97</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>98</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n    <tr>\n      <th>99</th>\n      <td></td>\n      <td>arrow</td>\n    </tr>\n  </tbody>\n</table>                          </body>                                                          </html>\n\n\n\n```python\ntrain_data, test_data = data.random_split(0.7)\n```\n\n\n```python\nmodel = tc.drawing_classifier.create(train_data, 'label', max_iterations=20)\n```\n\n    Downloading https://docs-assets.developer.apple.com/turicreate/models/drawing_classifier_pre_trained_model_245_classes_v0.mlmodel\n    Download completed: /var/folders/yc/57fqwfv971x9d3wwlvgllqsh0000gn/T/model_cache/drawing_classifier_pre_trained_model_245_classes_v0.mlmodel\n\n\n\n<pre>Automatically generating validation set from 5% of the data.</pre>\n\n\n\n<pre>Using CPU to create model.</pre>\n\n\n\n<pre>+--------------+----------------+---------------------+--------------+</pre>\n\n\n\n<pre>| Iteration    | Train Accuracy | Validation Accuracy | Elapsed Time |</pre>\n\n\n\n<pre>+--------------+----------------+---------------------+--------------+</pre>\n\n\n\n<pre>| 1            | 0.535714       | 0.636364            | 477.516ms    |</pre>\n\n\n\n<pre>| 2            | 0.668367       | 0.681818            | 712.089ms    |</pre>\n\n\n\n<pre>| 3            | 0.69898        | 0.727273            | 1.04s        |</pre>\n\n\n\n<pre>| 4            | 0.721939       | 0.818182            | 1.26s        |</pre>\n\n\n\n<pre>| 5            | 0.770408       | 0.909091            | 1.48s        |</pre>\n\n\n\n<pre>| 6            | 0.816327       | 0.954545            | 1.70s        |</pre>\n\n\n\n<pre>| 11           | 0.969388       | 1                   | 3.08s        |</pre>\n\n\n\n<pre>| 20           | 0.992347       | 1                   | 5.34s        |</pre>\n\n\n\n<pre>+--------------+----------------+---------------------+--------------+</pre>\n\n\n\n```python\nmodel\n```\n\n\n\n\n    Class                                    : DrawingClassifier\n    \n    Schema\n    ------\n    Number of classes                        : 3\n    Feature column                           : drawing\n    Target column                            : label\n    \n    Training summary\n    ----------------\n    Training Iterations                      : 20\n    Training Accuracy                        : 1.0\n    Validation Accuracy                      : 0.8824\n    Training Time                            : 13.7598\n    Number of Examples                       : 153\n\n\n\n\n```python\npredictions = model.predict(test_data)\n```\n\n\n```python\nmetrics = model.evaluate(test_data)\nmetrics.explore()\n```\n\n    Resizing image data... Done.\n\n\n\n```python\nmodel.save(\"automata-editor.model\")\n```\n\n\n```python\nmodel.export_coreml(\"AutomataClassifier.mlmodel\")\n```\n", "meta": {"hexsha": "1442b6db9618d81e8eca2f41f2240a4292ecdde5", "size": 126545, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Turicreate.ipynb", "max_stars_repo_name": "fortmarek/automata-editor-model", "max_stars_repo_head_hexsha": "77fce5dcb1f5011a3fd1ed54bb7d0bfa90a2e5f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:02:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T19:33:59.000Z", "max_issues_repo_path": "Turicreate.ipynb", "max_issues_repo_name": "fortmarek/automata-editor-model", "max_issues_repo_head_hexsha": "77fce5dcb1f5011a3fd1ed54bb7d0bfa90a2e5f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Turicreate.ipynb", "max_forks_repo_name": "fortmarek/automata-editor-model", "max_forks_repo_head_hexsha": "77fce5dcb1f5011a3fd1ed54bb7d0bfa90a2e5f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-07T18:12:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-07T18:12:50.000Z", "avg_line_length": 80.9111253197, "max_line_length": 4543, "alphanum_fraction": 0.6513098107, "converted": true, "num_tokens": 12044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22815649166448124, "lm_q2_score": 0.06754668973182397, "lm_q1q2_score": 0.015411215752762195}}
{"text": "```python\n!pip install qiskit==0.7.1\n!pip install qiskit_aer==0.1.1\n!cp /usr/local/lib/python3.6/site-packages/*.so /usr/local/lib/python3.6/dist-packages/\n```\n\n    Requirement already satisfied: qiskit==0.7.1 in /usr/local/lib/python3.6/dist-packages (0.7.1)\n    Requirement already satisfied: qiskit-terra<0.8,>=0.7 in /usr/local/lib/python3.6/dist-packages (from qiskit==0.7.1) (0.7.0)\n    Requirement already satisfied: qiskit-aer<0.2,>=0.1 in /usr/local/lib/python3.6/dist-packages (from qiskit==0.7.1) (0.1.1)\n    Requirement already satisfied: ply>=3.10 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (3.11)\n    Requirement already satisfied: jsonschema<2.7,>=2.6 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (2.6.0)\n    Requirement already satisfied: numpy>=1.13 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (1.14.6)\n    Requirement already satisfied: pillow>=4.2.1 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (5.4.1)\n    Requirement already satisfied: marshmallow<3,>=2.16.3 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (2.18.1)\n    Requirement already satisfied: scipy!=0.19.1,>=0.19 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (1.1.0)\n    Requirement already satisfied: requests-ntlm>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (1.1.0)\n    Requirement already satisfied: marshmallow-polyfield<4,>=3.2 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (3.2)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (5.4.8)\n    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (2.21.0)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (2.2)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (1.3)\n    Requirement already satisfied: cryptography>=1.3 in /usr/local/lib/python3.6/dist-packages (from requests-ntlm>=1.1.0->qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (2.6)\n    Requirement already satisfied: ntlm-auth>=1.0.2 in /usr/local/lib/python3.6/dist-packages (from requests-ntlm>=1.1.0->qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (1.2.0)\n    Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (1.22)\n    Requirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (2.6)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (2018.11.29)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (3.0.4)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx>=2.2->qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (4.3.2)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy>=1.3->qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (1.1.0)\n    Requirement already satisfied: cffi!=1.11.3,>=1.8 in /usr/local/lib/python3.6/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (1.12.2)\n    Requirement already satisfied: six>=1.4.1 in /usr/local/lib/python3.6/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (1.11.0)\n    Requirement already satisfied: asn1crypto>=0.21.0 in /usr/local/lib/python3.6/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (0.24.0)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.6/dist-packages (from cffi!=1.11.3,>=1.8->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-terra<0.8,>=0.7->qiskit==0.7.1) (2.19)\n    Requirement already satisfied: qiskit_aer==0.1.1 in /usr/local/lib/python3.6/dist-packages (0.1.1)\n    Requirement already satisfied: numpy>=1.13 in /usr/local/lib/python3.6/dist-packages (from qiskit_aer==0.1.1) (1.14.6)\n\n\n\n```python\nimport numpy as np\nfrom qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister\nfrom qiskit import execute\nfrom qiskit.tools.visualization import plot_histogram\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, LegacySimulators, Aer\n\n\nn=3\n```\n\n\n```python\n#IN/DECREMENT GATES FOR N=3\n\ndef increment_gate(qwc,q,subnode):\n  \n  qwc.ccx(q[2], q[1], q[0])\n  qwc.cx(q[2], q[1])\n  qwc.x(q[2])\n  \n  for node in q:\n    qwc.cx(subnode,node)\n   \n  qwc.barrier()\n  return qwc\n\ndef decrement_gate(qwc,q,subnode):\n  \n  qwc.x(q[2])\n  qwc.x(q[1])\n  qwc.ccx(q[2], q[1], q[0])\n  qwc.x(q[1])\n  \n  qwc.cx(q[2], q[1])\n  \n\n  qwc.x(subnode[0])\n  for node in q:\n    qwc.cx(subnode, node)\n  qwc.x(subnode[0])\n\n  return qwc\n  \ndef stateVectorGenerator(circ):\n  # Select the StatevectorSimulator from the Aer provider\n  simulator = Aer.get_backend('statevector_simulator')\n\n  # Execute and get counts\n  return execute(circ, simulator).result().get_statevector(circ)\n    \n```\n\n\n```python\ndef runQWC():\n  qwc.h(subnodes[0])\n  increment_gate(qwc,qnodes,subnodes[0])\n\n  return qwc\n```\n\n\n```python\nqnodes = QuantumRegister(n,'qc')\nqsubnodes = QuantumRegister(1,'qanc')\ncsubnodes = ClassicalRegister(1,'canc')\ncnodes = ClassicalRegister(n,'cr')\n\nqwc = QuantumCircuit(qnodes,subnodes,cnodes,csubnodes)\n\nrunQWC()\nqwc.draw(output='mpl')\n\n```\n\n\n```python\nsv = stateVectorGenerator(qwc)\nplot_state_city(sv, title='Bell state')\n\n```\n\n\n```python\nqwc.measure(qnodes, cnodes)\nsv = stateVectorGenerator(qwc)\nplot_state_city(sv, title='state post-measurement')\n\n\n# 471071fc24f40345e8d90c5a1041ea2ce1c1368439dfcf7a6abd11dbf317e11fae69b7461038d2600771ce24057b5545ea3366db352dd2904aea970464916264\n```\n\nn-qubit toffoli\n\n\n```python\ndef cnx(qc,*qubits):\n    if len(qubits) >= 3:\n        last = qubits[-1]\n        #A matrix: (made up of a  and Y rotation, lemma4.3)\n        qc.crz(np.pi/2,qubits[-2],qubits[-1])\n        #cry\n        qc.cu3(pi/2, 0, 0, qubits[-2],qubits[-1])\n        \n        #Control not gate\n        cnx(qc,*qubits[:-2],qubits[-1])\n        \n        #B matrix (cry again, but opposite angle)\n        qc.cu3(-pi/2, 0, 0, qubits[-2], qubits[-1])\n        \n        #Control\n        cnx(qc,*qubits[:-2],qubits[-1])\n        \n        #C matrix (final rotation)\n        qc.crz(-np.pi/2,qubits[-2],qubits[-1])\n    elif len(qubits)==3:\n        qc.ccx(*qubits)\n    elif len(qubits)==2:\n        qc.cx(*qubits)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "46228848c2f0c90ad236bc54e0f6f1e5930df986", "size": 264035, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "archive/quantum_walk.ipynb", "max_stars_repo_name": "czwhm6/quantum_walk", "max_stars_repo_head_hexsha": "5c99b74331b583582a587f8328b9d7dbdcad03fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2019-02-27T16:45:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T12:51:10.000Z", "max_issues_repo_path": "archive/quantum_walk.ipynb", "max_issues_repo_name": "Chibikuri/quantum_walk", "max_issues_repo_head_hexsha": "c82a0bbefa8cebe7be9cd465708ca6fa4d36b445", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "archive/quantum_walk.ipynb", "max_forks_repo_name": "Chibikuri/quantum_walk", "max_forks_repo_head_hexsha": "c82a0bbefa8cebe7be9cd465708ca6fa4d36b445", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2019-02-28T16:42:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-30T18:08:08.000Z", "avg_line_length": 586.7444444444, "max_line_length": 218402, "alphanum_fraction": 0.9258166531, "converted": true, "num_tokens": 2622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27202455109402257, "lm_q2_score": 0.05665242331706966, "lm_q1q2_score": 0.015410850021214412}}
{"text": "```python\nimport local_models.local_models\nimport local_models.algorithms\nimport local_models.utils\nimport local_models.linear_projections\nimport local_models.loggin\nimport local_models.TLS_models\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sklearn.linear_model\nimport sklearn.cluster\nfrom importlib import reload\nfrom ml_battery.utils import cmap\nimport matplotlib as mpl\nimport sklearn.datasets\nimport sklearn.decomposition\nimport logging\nimport ml_battery.log\nimport time\nimport os\nimport mayavi\nimport mayavi.mlab\nimport string\nimport subprocess\nimport functools\nimport cv2\nimport itertools\n\n#on headless systems, tmux: \"Xvfb :1 -screen 0 1280x1024x24 -auth localhost\", then \"export DISPLAY=:1\" in the jupyter tmux\nmayavi.mlab.options.offscreen = True\n\n\n\nlogger = logging.getLogger(__name__)\n\n#reload(local_models.local_models)\n#reload(lm)\n#reload(local_models.loggin)\n#reload(local_models.TLS_models)\nnp.warnings.filterwarnings('ignore')\n\n```\n\n    /usr/local/lib/python3.5/dist-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n      _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n    /usr/local/lib/python3.5/dist-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n      _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n    /usr/local/lib/python3.5/dist-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n      _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n    /usr/local/lib/python3.5/dist-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n      _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n    /usr/local/lib/python3.5/dist-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n      _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n    /usr/local/lib/python3.5/dist-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n      np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n\n\n\n```python\ndef import_shit():\n    import local_models.local_models\n    import local_models.algorithms\n    import local_models.utils\n    import local_models.linear_projections\n    import local_models.loggin\n    import local_models.TLS_models\n    import numpy as np\n    import logging\n    import string\n    import ml_battery.log\n\n\n    logger = logging.getLogger(__name__)\n\n    #reload(local_models.local_models)\n    #reload(lm)\n    #reload(local_models.loggin)\n    #reload(local_models.TLS_models)\n    np.warnings.filterwarnings('ignore')\n    return logger\n    \ndef mean_center(data, weights=None):\n    return data - np.average(data, axis=0,weights=weights)\n\ndef load_converged_data(pth):\n    convergededs = []\n    for dat in sorted(os.listdir(pth)):\n        convergededs.append(np.loadtxt(os.path.join(pth, dat)))\n    return np.concatenate(convergededs, axis=0)\n\ndef plt_grid(fig, grid, data_avg, data_std):\n    nodes = mayavi.mlab.points3d(grid[:,0], grid[:,1], grid[:,2], \n                                 scale_mode='scalar', scale_factor=1,\n                                 colormap='gist_earth', figure=fig)\n    nodes.glyph.scale_mode = 'scale_by_vector'\n    nodes.mlab_source.dataset.point_data.vectors = np.ones((grid.shape[0],3))*(np.average(data_std)/60)\n    nodes.mlab_source.dataset.point_data.scalars = (grid[:,1] - (data_avg[1]-3*data_std[1]))/(6*data_std[1])\n    return nodes\n\ndef plt_data(fig, data, data_std):\n    nodes = mayavi.mlab.points3d(data[:,0], data[:,1], data[:,2], \n                                 scale_mode='scalar', scale_factor=1,\n                                 colormap='Greens', figure=fig)\n    nodes.glyph.scale_mode = 'scale_by_vector'\n    nodes.mlab_source.dataset.point_data.vectors = np.ones((data.shape[0],3))*(np.average(data_std)/60)\n    nodes.mlab_source.dataset.point_data.scalars = np.ones((data.shape[0]))\n    return nodes\n\ndef get_normals(kernel, linear_models, data):\n    if hasattr(kernel.bandwidth, \"__call__\"):\n        linear_params_vecs, linear_params_mean = local_models.linear_projections.transformate_data(data, kernel, linear_models, k=kernel.k)\n    else:\n        linear_params_vecs, linear_params_mean = local_models.linear_projections.transformate_data(data, kernel, linear_models, r=kernel.support_radius())\n    return linear_params_vecs\n\ndef align_normals(data, normals, k=10, iterations=100):\n    balltree = sklearn.neighbors.BallTree(data)\n    pairwise_nearest_indices = balltree.query(data,k=k,sort_results=True,return_distance=False)\n    for iteration in range(iterations):\n        alignments = []\n        for index in range(1,pairwise_nearest_indices.shape[1]):\n            alignment = np.einsum(\"ij,ij->i\",normals,normals[pairwise_nearest_indices[:,index]])\n            alignments.append(alignment)\n        alignment = np.average(alignments, axis=0)\n        wrong_alignment = np.sign(alignment)\n        normals = normals*wrong_alignment.reshape(-1,1)\n    return normals\n\ndef align_edge_normals(data, normals, edge_range=0.1):\n    data_mins, data_maxes, data_ranges = local_models.linear_projections.min_max_range(data)\n    graph_bounds = local_models.linear_projections.sane_graph_bounds(data_mins, data_maxes, data_ranges, -edge_range)\n    mins = data < graph_bounds[:1]\n    maxes = data > graph_bounds[1:]\n    mins_alignment = np.sign(np.einsum(\"ij,ij->i\",mins,-1*normals))\n    maxes_alignment = np.sign(np.einsum(\"ij,ij->i\",maxes,normals))\n    mins_alignment += np.logical_not(mins_alignment) # turn 0s into 1s (so they don't change)\n    maxes_alignment += np.logical_not(maxes_alignment)    \n    return normals*mins_alignment.reshape(-1,1)*maxes_alignment.reshape(-1,1)\n\ndef plt_normals(fig, normals, data, data_std):\n    nodes = mayavi.mlab.quiver3d(data[:,0], data[:,1], data[:,2],\n                                 normals[:,0], normals[:,1], normals[:,2],\n                                 scale_mode='scalar', scale_factor=np.average(data_std)/5,\n                                 colormap='Purples', figure=fig, line_width=1.0)\n    return nodes\n\ndef normalize_view(fig, data_avg, data_std, azimuth=0, elevation=0):\n    mayavi.mlab.view(azimuth=azimuth, elevation=elevation, distance=15*np.average(data_std), focalpoint=(data_avg[0], data_avg[1], data_avg[2]))\n    \ndef plt_and_save(data, grid, normals, pth):\n    data_avg = np.average(data, axis=0)\n    data_std = np.std(data, axis=0)\n    figure = mayavi.mlab.figure(figure=None, bgcolor=(1,1,1), fgcolor=(0,0,0), engine=None, size=(1000, 500))\n    data_nodes = plt_data(figure, data, data_std)\n    converged_nodes = plt_grid(figure, grid, data_avg, data_std)\n    normal_vecs = plt_normals(figure, normals, grid, data_std)\n    neg_normal_vecs = plt_normals(figure, -normals, grid, data_std)\n    normalize_view(figure, data_avg, data_std)\n    mayavi.mlab.savefig(pth, magnification=2)\n    mayavi.mlab.close(figure)\n\ndef serialize_plt(pth):\n    import zlib\n    with open(pth, 'rb') as f:\n        dat = f.read()\n    return zlib.compress(dat)\n   \ndef deserialize_plt(dat, pth):\n    import zlib\n    with open(pth, 'wb') as f:\n        f.write(zlib.decompress(dat))\n    return pth\n\ndef distributed_plt_and_save(data, grid, bandwidth):\n    import numpy as np\n    import mayavi\n    import mayavi.mlab\n    import string\n    import os\n    #on headless systems, tmux: \"Xvfb :1 -screen 0 1280x1024x24 -auth localhost\", then \"export DISPLAY=:1\" in the jupyter tmux\n    mayavi.mlab.options.offscreen = True\n    \n    unique_id = \"\".join(np.random.choice(list(string.ascii_lowercase), replace=True, size=20))\n    pth = \"/ramfs/{}.png\".format(unique_id)\n    try:\n        plt_and_save(data, grid, bandwidth, pth)\n        result = serialize_plt(pth)\n    except:\n        os.remove(pth)\n```\n\n\n```python\nFRESH=True\n```\n\n\n```python\nkernel_names = {\n    local_models.local_models.GaussianKernel: 'gaussian',\n    local_models.local_models.TriCubeKernel: 'tricube'\n}\n```\n\n\n```python\nmpl.rcParams['figure.figsize'] = [8.0, 8.0]\n```\n\n\n```python\ndata_file = \"/home/brown/Downloads/subject001/3d/andreadm2.stl\"\n```\n\n\n```python\nimport stl\n\ntri_mesh = stl.mesh.Mesh.from_file(data_file).points.reshape(-1,3)\n```\n\n\n```python\ntri_mesh.shape\n```\n\n\n\n\n    (346758, 3)\n\n\n\n\n```python\ndata, cts = np.unique(tri_mesh, axis=0, return_counts=True)\n```\n\n\n```python\ndata.shape\n```\n\n\n\n\n    (58659, 3)\n\n\n\n\n```python\n(data.shape[0]*100)**(1/3)\n```\n\n\n\n\n    180.348091843\n\n\n\n\n```python\nnp.mean(data, axis=0)\n```\n\n\n\n\n    array([ -71.71989 , -340.46124 ,   31.036196], dtype=float32)\n\n\n\n\n```python\n\n```\n\n\n```python\nKERNEL=local_models.local_models.TriCubeKernel\nRUN = 1\n\nproject_dir = \"../data/quadrics_{}_{:03d}\".format(kernel_names[KERNEL], RUN)\n\nos.makedirs(project_dir, exist_ok=1)\n```\n\n\n```python\n\n```\n\n\n```python\nA = np.array([[0,0,0,1]]).T\nORIGIN = np.array([[0,0,0]])\nONE = np.array([[1]])\n\nimport quadrics_utils\n\ndef diagonalize_quadric_and_translate(Q,X):\n    Q_s = Q[:-1,:-1]\n    _, U = np.linalg.eig(Q_s)\n    UTQs = U.T@Q_s\n    UL = np.diag(UTQs@U)\n    #UR = UTQs@X.T + U.T@Q[:-1,-1:]\n    UR = X@UTQs.T + Q[-1:,:-1]@U\n    BR = np.einsum('kj,kj->k', X@Q_s, X).reshape(-1,1) + 2*X@Q[:-1,-1:] + Q[-1,-1]\n    return (U, UL, UR, BR)\n\ndef array_roots(coeffses):\n    ret = np.zeros((coeffses.shape[0], coeffses.shape[1]-1), dtype=complex)\n    for i, coeffs in enumerate(coeffses):\n        nproots = np.roots(coeffs.flatten())\n        ret[i] = nproots\n    return ret\n\nprojection_funcs = {\n    \"k_mat\": quadrics_utils.k_mat,\n    \"other_dims_as_x\": lambda a,b,c,d,e,f,g,x: [quadrics_utils.y_as_x(a,b,c,d,e,f,g,x), quadrics_utils.z_as_x(a,b,c,d,e,f,g,x)],\n}\ndef orthogonal_quadric_project_x(X,Q,projection_funcs):\n    U, ul, ur, br = diagonalize_quadric_and_translate(Q,X)\n    #put all of the dimensions right for math stuff\n    ul = np.tile(ul.reshape(1,-1), (X.shape[0], 1))\n    args = (\n        list(ul.T[...,np.newaxis]) +\n        [br] +\n        list(ur.T[...,np.newaxis])\n    )\n    \n    coeffses = projection_funcs[\"k_mat\"](*args)\n    coeffses = np.stack(coeffses, axis=1)\n\n    x = np.ma.array(array_roots(coeffses))\n    return U,args,x\n    \ndef orthogonal_quadric_projection(X,Q,projection_funcs):\n    U, args, x = orthogonal_quadric_project_x(X,Q,projection_funcs)\n\n    candidates = x.imag == 0\n    x.mask = ~candidates\n    other_dims = projection_funcs[\"other_dims_as_x\"](*(args + [x]))\n\n    pts = np.ma.stack([x] + other_dims, axis=1)\n    dists = np.sum(pts**2, axis=1)\n    mindists = np.argmin(dists, axis=1)\n    X_indices = np.arange(X.shape[0])\n    best_pts = np.array(pts[X_indices,:,mindists], dtype=float)\n    best_dists = np.array(dists[X_indices,mindists],dtype=float)\n    return unrotate_and_translate(U, X, best_pts), best_dists\n\ndef unrotate_and_translate(U, orig_X, new_X):\n    return new_X@U.T + orig_X\n    #return np.einsum('ji,ki->kj',U,orig_X) + new_X\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\ndef test_diagonalize_quadratic_and_translate():\n    q = np.array([ # an ellipse\n        [0.5,0,0,0],\n        [0,0.4,0,0],\n        [0,0,0.3,0],\n        [0,0,0,-1],\n    ])\n    x = np.random.uniform(size=12).reshape(4,3)\n    #x = np.ones(3).reshape(1,-1)*0.01\n    #x[0,2] = 1\n    \n    _, ul, ur, br = diagonalize_quadric_and_translate(q,x)\n    print(ul.shape,ur.shape,br.shape)\n    \n    q1 = np.block([[np.diag(ul), ur[:1].T],[ur[:1], br[:1]]])\n    \n    _,U = np.linalg.eig(q[:3,:3])\n    E = np.block([[U, x[:1].T],[ORIGIN, 1]])\n    q2 = E.T@q@E\n    \n    assert np.allclose(q1,q2)\n    return x,ul,ur,br\nx,ul,ur,br = test_diagonalize_quadratic_and_translate()\n```\n\n    (3,) (4, 3) (4, 1)\n\n\n\n```python\nx\n```\n\n\n\n\n    array([[0.0619404 , 0.70002244, 0.37283088],\n           [0.72876962, 0.26031804, 0.79020342],\n           [0.10712523, 0.10682334, 0.01939804],\n           [0.70480969, 0.26807666, 0.73614336]])\n\n\n\n\n```python\nur.shape, br.shape, ul.shape\n```\n\n\n\n\n    ((4, 3), (4, 1), (3,))\n\n\n\n\n```python\n#q = np.random.uniform(size=(4,4))\n#q += q.T\nq = np.array([ # an ellipse\n    [0.5,0,0,0],\n    [0,0.25,0,0],\n    [0,0,0.125,0],\n    [0,0,0,-1],\n])\nq = np.array([ # an elliptic paraboloid\n    [0.5,0,0,0],\n    [0,0.25,0,0],\n    [0,0,0,-1],\n    [0,0,-1,0.1],\n])\ninit_q = q\nu = np.random.uniform(size=(3,3))\nu += u.T\n_, u = np.linalg.eig(u)\nprint(u)\nprint(np.linalg.norm(u, axis=0))\nE = np.block([[u, np.zeros((3,1))],[np.zeros(3), 1]])\nq = E.T@q@E\nprint(q)\nx = np.random.uniform(size=3).reshape(1,-1)\nx = np.ones(3).reshape(1,-1)*0.01\nx[0,2] = 1\n\nq\n```\n\n    [[-0.67767991 -0.53064411 -0.50908424]\n     [-0.66897615  0.73232087  0.12718904]\n     [-0.3053209  -0.42675867  0.8512674 ]]\n    [1. 1. 1.]\n    [[ 0.3415073   0.05732713  0.15122647  0.3053209 ]\n     [ 0.05732713  0.27486505  0.15835707  0.42675867]\n     [ 0.15122647  0.15835707  0.13362765 -0.8512674 ]\n     [ 0.3053209   0.42675867 -0.8512674   0.1       ]]\n\n\n\n\n\n    array([[ 0.3415073 ,  0.05732713,  0.15122647,  0.3053209 ],\n           [ 0.05732713,  0.27486505,  0.15835707,  0.42675867],\n           [ 0.15122647,  0.15835707,  0.13362765, -0.8512674 ],\n           [ 0.3053209 ,  0.42675867, -0.8512674 ,  0.1       ]])\n\n\n\n\n```python\n\n```\n\n\n```python\nq[:3,3:]\n```\n\n\n\n\n    array([[ 0.3053209 ],\n           [ 0.42675867],\n           [-0.8512674 ]])\n\n\n\n\n```python\n_, ul, ur, br = diagonalize_quadric_and_translate(q,x)\n```\n\n\n```python\nbr\n```\n\n\n\n\n    array([[-1.44800079]])\n\n\n\n\n```python\nx\n```\n\n\n\n\n    array([[0.01, 0.01, 1.  ]])\n\n\n\n\n```python\nQ1 = np.block([[np.diag(ul), ur.T],[ur, br]])\nQ1\n```\n\n\n\n\n    array([[ 5.00000000e-01,  0.00000000e+00,  0.00000000e+00,\n            -2.60583741e-01],\n           [ 0.00000000e+00,  2.50000000e-01,  0.00000000e+00,\n             3.19556216e-02],\n           [ 0.00000000e+00,  0.00000000e+00,  3.30812673e-18,\n            -1.00000000e+00],\n           [-2.60583741e-01,  3.19556216e-02, -1.00000000e+00,\n            -1.44800079e+00]])\n\n\n\n\n```python\n_,U = np.linalg.eig(q[:3,:3])\n```\n\n\n```python\nE = np.block([[U, x.T],[ORIGIN, 1]])\nE\n```\n\n\n\n\n    array([[-0.67767991, -0.66897615, -0.3053209 ,  0.01      ],\n           [-0.53064411,  0.73232087, -0.42675867,  0.01      ],\n           [-0.50908424,  0.12718904,  0.8512674 ,  1.        ],\n           [ 0.        ,  0.        ,  0.        ,  1.        ]])\n\n\n\n\n```python\nq\n```\n\n\n\n\n    array([[ 0.3415073 ,  0.05732713,  0.15122647,  0.3053209 ],\n           [ 0.05732713,  0.27486505,  0.15835707,  0.42675867],\n           [ 0.15122647,  0.15835707,  0.13362765, -0.8512674 ],\n           [ 0.3053209 ,  0.42675867, -0.8512674 ,  0.1       ]])\n\n\n\n\n```python\nnp.round(E.T@q@E,3)\n```\n\n\n\n\n    array([[ 0.5  ,  0.   , -0.   , -0.261],\n           [ 0.   ,  0.25 ,  0.   ,  0.032],\n           [-0.   ,  0.   , -0.   , -1.   ],\n           [-0.261,  0.032, -1.   , -1.448]])\n\n\n\n\n```python\nE\n```\n\n\n\n\n    array([[-0.67767991, -0.66897615, -0.3053209 ,  0.01      ],\n           [-0.53064411,  0.73232087, -0.42675867,  0.01      ],\n           [-0.50908424,  0.12718904,  0.8512674 ,  1.        ],\n           [ 0.        ,  0.        ,  0.        ,  1.        ]])\n\n\n\n\n```python\npts, dists = orthogonal_quadric_projection(x,q, projection_funcs)\npts2, dists2 = orthogonal_quadric_projection(x,q, projection_funcs)\nprint(pts2, dists2)\n```\n\n    [[0.35759051 0.43371826 0.58121769]] [0.47573495]\n\n\n\n```python\npts, dists\n```\n\n\n\n\n    (array([[0.35759051, 0.43371826, 0.58121769]]), array([0.47573495]))\n\n\n\n\n```python\npts2, dists2\n```\n\n\n\n\n    (array([[0.35759051, 0.43371826, 0.58121769]]), array([0.47573495]))\n\n\n\n\n```python\ndists\n```\n\n\n\n\n    array([0.47573495])\n\n\n\n\n```python\npts.shape\n```\n\n\n\n\n    (1, 3)\n\n\n\n\n```python\npt1 = np.ones((1,4))\npt1[:,:3] = pts\npt1\n```\n\n\n\n\n    array([[0.35759051, 0.43371826, 0.58121769, 1.        ]])\n\n\n\n\n```python\npt1@q@pt1.T\n```\n\n\n\n\n    array([[-6.10622664e-16]])\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\nx.shape, q.shape\n```\n\n\n\n\n    ((1, 3), (4, 4))\n\n\n\n\n```python\nx = (np.random.uniform(size=(3000,3))-0.5)*10\n```\n\n\n```python\npts, dists = orthogonal_quadric_projection(x,q, projection_funcs)\n```\n\n\n```python\n#pts, dists = orthogonal_quadric_projection2(x,q, projection_funcs)\n```\n\n\n```python\ncheck_pts, check_dists = orthogonal_quadric_projection(np.array(pts),q, projection_funcs)\n```\n\n\n```python\ncheck_dists\n```\n\n\n\n\n    array([3.34677074e-27, 3.48152994e-28, 3.80576124e-29, ...,\n           8.81175093e-26, 2.18590455e-26, 1.62574557e-32])\n\n\n\n\n```python\nprint(np.max(check_dists))\n```\n\n    30.477722498455293\n\n\n\n```python\nprint(pts.shape, dists.shape)\n```\n\n    (3000, 3) (3000,)\n\n\n\n```python\ndef imshow(pth, cv2color=cv2.IMREAD_COLOR, **kwargs):\n    img = cv2.imread(pth, cv2color)\n    img = trim_whiteborder(img)\n    plt.imshow(img, **kwargs)\n    plt.axis(\"off\")\n```\n\n\n```python\npth = os.path.join(project_dir, \"quadric_test.png\")\n\ndata_avg = np.average(pts, axis=0)\ndata_std = np.std(pts, axis=0)\nfigure = mayavi.mlab.figure(figure=None, bgcolor=(1,1,1), fgcolor=(0,0,0), engine=None, size=(1000, 1000))\n#data_nodes = plt_data(figure, x[np.random.choice(np.arange(x.shape[0]), size=40, replace=False)], data_std)\nvecs = pts-x\n#mayavi.mlab.quiver3d(x[:,0], x[:,1], x[:,2], vecs[:,0], vecs[:,1], vecs[:,2])\nquadric_nodes = plt_grid(figure, pts, data_avg, data_std)\n#ellipse_axes = plt_data(figure, np.diag(np.sqrt(1/np.diag(init_q[:3,:3])))@u, data_std*10)\n\nnormalize_view(figure, data_avg, data_std)\nmayavi.mlab.savefig(pth, magnification=2)\nmayavi.mlab.close(figure)\n```\n\n\n```python\ndef trim_whiteborder(img, ratio=1.1):\n    img = cv2.bitwise_not(img)\n    print(img.shape)\n    im_sq = img**2\n    sum_sq_cols = np.sum(im_sq, axis=0)\n    sum_sq_rows = np.sum(im_sq, axis=1)\n    if len(img.shape) > 2:\n        sum_sq_cols = np.sum(sum_sq_cols, axis=1)\n        sum_sq_rows = np.sum(sum_sq_rows, axis=1)\n    print(sum_sq_cols.shape, sum_sq_rows.shape)\n    first_nonzero_col = (sum_sq_cols!=0).argmax()\n    last_nonzero_col = sum_sq_cols.shape[0] - (sum_sq_cols[::-1]!=0).argmax()\n    first_nonzero_row = (sum_sq_rows!=0).argmax()\n    last_nonzero_row = sum_sq_rows.shape[0] - (sum_sq_rows[::-1]!=0).argmax()\n    print(first_nonzero_col, last_nonzero_col, first_nonzero_row, last_nonzero_row)\n    totally_trimmed = img[first_nonzero_row:last_nonzero_row, first_nonzero_col:last_nonzero_col]\n    if len(img.shape) == 2:\n        just_a_little_whitespace = np.zeros((\n            int(totally_trimmed.shape[0]*ratio), \n            int(totally_trimmed.shape[1]*ratio)\n        ), dtype=np.uint8)\n    else:\n        just_a_little_whitespace = np.zeros((\n            int(totally_trimmed.shape[0]*ratio), \n            int(totally_trimmed.shape[1]*ratio),\n            img.shape[2]\n        ), dtype=np.uint8)\n    jalw_middle_section_start = ((np.array(just_a_little_whitespace.shape) - np.array(totally_trimmed.shape))/2).astype(int)\n    just_a_little_whitespace[\n        jalw_middle_section_start[0]:jalw_middle_section_start[0] + totally_trimmed.shape[0],\n        jalw_middle_section_start[1]:jalw_middle_section_start[1] + totally_trimmed.shape[1]\n    ] = totally_trimmed\n    #return just_a_little_whitespace\n    return cv2.bitwise_not(just_a_little_whitespace)\n        \n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\nblah = imshow(pth)\n```\n\n\n```python\nisinstance(5., (float,int))\n```\n\n\n\n\n    True\n\n\n\n\n```python\ndef jac_orthogonal_quadric_loss(X,Q):\n    U, ul, ur, br = diagonalize_quadric_and_translate(Q,X)\n    a,b,c = ul.reshape(-1,1,1)\n    e,f,g = ur\n    d = br\n    e,f,g,d = list(map(lambda x: x.reshape(-1, 1), [e,f,g,d]))\n    coeffses = quadrics_utils.k_mat(a,b,c,d,e,f,g)\n    kjac = quadrics_utils.k_jac(a,b,c,d,e,f,g)\n    \n    full_kjac = np.zeros((7,7,x.shape[0]))\n    for i,row in enumerate(kjac):\n        for j,el in enumerate(b):\n            full_kjac[i,j] = el.flatten()\n    \n    # the first coefficient doesn't depend on x, so it needs tiling.\n    coeffses[0] = np.repeat(coeffses[0], X.shape[0], axis=0)\n    print([[0 if isinstance(x,(int,float)) else x.shape for x in y] for y in kjac])\n    coeffses = np.stack(coeffses, axis=1)\n    x = array_roots(coeffses)\n    candidates = np.isclose(quadrics_utils.Q_as_x(a,b,c,d,e,f,g,x),0)\n    x.mask = ~candidates\n    y = quadrics_utils.y_as_x(a,b,c,d,e,f,g,x)\n    z = quadrics_utils.z_as_x(a,b,c,d,e,f,g,x)\n    pts = np.ma.stack((x,y,z), axis=1)\n    dists = np.sum((X.reshape(*(list(X.shape) + [1])) - pts)**2, axis=1)\n    mindists = np.argmin(dists, axis=1)\n    X_indices = np.arange(X.shape[0])\n    chosen_pts = pts[X_indices,:,mindists]\n    chosen_dists = dists[X_indices,mindists]\n    \n    return unrotate_and_translate(U, X, pts[X_indices,:,mindists]), dists[X_indices,mindists]\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\ndef weighted_avg_and_std(values, weights=None, axis=None):\n    \"\"\"\n    Return the weighted average and standard deviation.\n\n    values, weights -- Numpy ndarrays with the same shape.\n    \"\"\"\n    if weights is None:\n        return np.average(values, axis=axis), np.std(values, axis=axis)\n    average = np.average(values, weights=weights, axis=axis)\n    # Fast and numerically precise:\n    variance = np.average((values-average)**2, weights=weights, axis=axis)\n    return (average, np.sqrt(variance))\n```\n\n\n```python\nimport scipy.optimize\nimport sklearn.utils\nimport sklearn.base\n\nclass QuadricModel(sklearn.base.RegressorMixin):\n    def __init__(self):\n        pass\n    def get_params(self, *args, **kwargs):\n        return dict()\n    def set_params(self, params, *args, **kwargs):\n        pass\n\n    \n    def _optimizer_logger(self, xk, *args):\n        logging.info(\"quadric modeling: it{}, xk{}\".format(self.i, xk))\n        self.i += 1      \n            \n    def fit(self, X, y=None, sample_weight=None, beta0=None):\n        logging.info(\"fitting quadric model\")\n        X = sklearn.utils.check_array(X)\n        if beta0 is None:\n            #this allows us to orient the data to set an initial set of parameters\n            global_linear_model = local_models.TLS_models.LinearODR_mD(2)\n            global_linear_model.fit(X, sample_weight=sample_weight)\n            global_linear_vecs = global_linear_model.cov_eigenvectors[global_linear_model.cov_eigenvalues_sorter]\n            global_linear_mean = global_linear_model.intercept_\n\n            transformed_X = (X-global_linear_mean)@global_linear_vecs.T\n\n            transformed_q = np.zeros((4,4))\n            \n            # an elliptic paraboloid pointing in the smallest eigenvector direction\n            '''\n            transformed_q[0,0] = 1/weighted_avg_and_std(transformed_X[0], weights=None)[1]**2 #flat-ish in x\n            transformed_q[1,1] = 1/weighted_avg_and_std(transformed_X[1], weights=None)[1]**2 #flat-ish in y\n            transformed_q[2,3] = transformed_q[3,2] = -1 # elliptic paraboloid pointing in z direction\n            '''\n            \n            # an ellipse with axes in the various directions\n            transformed_q[np.diag_indices(3)] = 1/global_linear_model.cov_eigenvalues[global_linear_model.cov_eigenvalues_sorter]**2\n            transformed_q[3,3] = -1\n            #print(np.diag(transformed_q), weighted_avg_and_std(transformed_X, weights = sample_weight, axis=0)[1])\n            \n            #print(transformed_q)\n            #print(global_linear_mean)\n            E = np.block([[global_linear_vecs, global_linear_mean.reshape(-1,1)],[np.zeros(3),1]])\n            Einv = np.linalg.inv(E)\n            q = Einv.T@transformed_q@Einv\n            print(q)\n            beta0 = q[np.triu_indices(4)]\n        \n        beta0 /= beta0[-1]\n        \n        self.i = 0\n        self.solution = scipy.optimize.minimize(self._loss, beta0[:-1], args=(X, sample_weight), callback=self._optimizer_logger)#, method = 'Nelder-Mead')\n        self.coef_ = self.solution.x\n        self.intercept_ = np.array([])\n        return self\n            \n    def _loss(self, beta, X, sample_weight=None):\n        q = np.zeros((4,4))\n        beta = np.concatenate((beta, [1]))\n        q[np.triu_indices(4)] = beta\n        q[3,3] = 1\n        q += q.T\n        q[np.diag_indices(4)] /= 2\n        pts, dists = orthogonal_quadric_projection(X,q,projection_funcs)\n\n        #pts, jac, dists = orthogonal_quadric_projection_with_jacobian(X,q,projection_funcs)\n        \n        if sample_weight is not None:\n            dists *= sample_weight\n        lost = np.sum(dists)\n        #total_jac = np.einsum('ki,kij->ij', (X - pts), jac)\n        #if lost > 20:\n        #    print(q)\n        #print(lost)\n        return lost#, total_jac\n```\n\n\n```python\n\n```\n\n\n```python\nqm = QuadricModel()\nqm.fit(pts)#, beta0=q[np.triu_indices(4)]+0.001)\n```\n\n    [[ 0.27681249  0.04017082  0.17097849 -0.4425093 ]\n     [ 0.04017082  0.06775505  0.04492783 -0.03859162]\n     [ 0.17097849  0.04492783  0.17887278 -0.3294389 ]\n     [-0.4425093  -0.03859162 -0.3294389  -0.21978061]]\n\n\n\n```python\nqm.solution\n```\n\n\n\n\n          fun: 1.6549110924078896\n     hess_inv: array([[ 4.62085809e+10,  4.95199660e+10, -2.89563950e+10,\n            -1.60618353e+11,  1.01727748e+11,  2.12873965e+10,\n             1.08951819e+11,  3.88933132e+10, -1.45872819e+11],\n           [ 4.95199654e+10,  5.30686500e+10, -3.10314590e+10,\n            -1.72128534e+11,  1.09017729e+11,  2.28128871e+10,\n             1.16759490e+11,  4.16804734e+10, -1.56326310e+11],\n           [-2.89563947e+10, -3.10314590e+10,  1.81453918e+10,\n             1.00650752e+11, -6.37472252e+10, -1.33396491e+10,\n            -6.82741564e+10, -2.43723158e+10,  9.14105312e+10],\n           [-1.60618352e+11, -1.72128535e+11,  1.00650753e+11,\n             5.58300095e+11, -3.53599761e+11, -7.39937577e+10,\n            -3.78710215e+11, -1.35190905e+11,  5.07045473e+11],\n           [ 1.01727745e+11,  1.09017728e+11, -6.37472246e+10,\n            -3.53599757e+11,  2.23952656e+11,  4.68639983e+10,\n             2.39856380e+11,  8.56232542e+10, -3.21137605e+11],\n           [ 2.12873960e+10,  2.28128869e+10, -1.33396490e+10,\n            -7.39937567e+10,  4.68639982e+10,  9.80669026e+09,\n             5.01919877e+10,  1.79173942e+10, -6.72007755e+10],\n           [ 1.08951816e+11,  1.16759488e+11, -6.82741554e+10,\n            -3.78710208e+11,  2.39856379e+11,  5.01919875e+10,\n             2.56889486e+11,  9.17036843e+10, -3.43942797e+11],\n           [ 3.88933130e+10,  4.16804736e+10, -2.43723160e+10,\n            -1.35190905e+11,  8.56232555e+10,  1.79173945e+10,\n             9.17036861e+10,  3.27361233e+10, -1.22779733e+11],\n           [-1.45872816e+11, -1.56326309e+11,  9.14105303e+10,\n             5.07045466e+11, -3.21137605e+11, -6.72007755e+10,\n            -3.43942799e+11, -1.22779731e+11,  4.60496264e+11]])\n          jac: array([-0.00018266,  0.0007423 ,  0.00088313, -0.00044671,  0.00014985,\n           -0.00081003, -0.00018746,  0.00035554,  0.00045177])\n      message: 'Desired error not necessarily achieved due to precision loss.'\n         nfev: 1695\n          nit: 71\n         njev: 153\n       status: 2\n      success: False\n            x: array([-14346.90291295, -15375.35452347,   8990.6931421 ,  49869.12471544,\n           -31585.03583959,  -6609.54440227, -33827.87634286, -12075.69418345,\n            45290.97807574])\n\n\n\n\n```python\nqq = np.zeros((4,4))\nqq[np.triu_indices(4)] = np.concatenate((qm.coef_, [1]))\nqq += qq.T\nqq[np.diag_indices(4)] /= 2\nnp.round(qq,3)\n```\n\n\n\n\n    array([[-1.4346903e+04, -1.5375355e+04,  8.9906930e+03,  4.9869125e+04],\n           [-1.5375355e+04, -3.1585036e+04, -6.6095440e+03, -3.3827876e+04],\n           [ 8.9906930e+03, -6.6095440e+03, -1.2075694e+04,  4.5290978e+04],\n           [ 4.9869125e+04, -3.3827876e+04,  4.5290978e+04,  1.0000000e+00]])\n\n\n\n\n```python\nq\n```\n\n\n\n\n    array([[ 0.19991037,  0.1817657 , -0.09489533, -0.67572345],\n           [ 0.1817657 ,  0.38892396,  0.07487268,  0.43093912],\n           [-0.09489533,  0.07487268,  0.16116567, -0.59807132],\n           [-0.67572345,  0.43093912, -0.59807132,  0.1       ]])\n\n\nqq = np.array(\n[[ 0.98928691, -0.42390962, -0.20757044, -0.35397327],\n [-0.42390962,  0.24742997,  0.33970501, -0.9004247 ],\n [-0.20757044,  0.33970501,  0.99941526,  0.25388832],\n [-0.35397327, -0.9004247 ,  0.25388832, -0.02455888]]\n)qq = np.array(\n[[ 0.56025787,  0.64822194,  0.0094628 ,  0.00872895],\n [ 0.64822194,  1.92161331, -0.4789617 ,  0.02687668],\n [ 0.0094628 , -0.4789617 ,  0.47708798, -0.00464847],\n [ 0.00872895,  0.02687668, -0.00464847, -0.99960565]]\n\n )\n\n```python\nq\n```\n\n\n\n\n    array([[ 0.19991037,  0.1817657 , -0.09489533, -0.67572345],\n           [ 0.1817657 ,  0.38892396,  0.07487268,  0.43093912],\n           [-0.09489533,  0.07487268,  0.16116567, -0.59807132],\n           [-0.67572345,  0.43093912, -0.59807132,  0.1       ]])\n\n\n\n\n```python\nqq.shape\n```\n\n\n\n\n    (4, 4)\n\n\n\n\n```python\nq.shape\n```\n\n\n\n\n    (4, 4)\n\n\n\n\n```python\nnp.array(pts)\n```\n\n\n\n\n    array([[ 0.36155235,  1.23129588,  1.85642789],\n           [-0.13218691,  0.97221512,  4.26794374],\n           [ 0.7647154 , -6.10832972,  4.31310786],\n           ...,\n           [ 2.83708582, -4.24921199, -1.22549308],\n           [ 2.57444886,  0.44583598, -0.68037878],\n           [ 3.07029248,  0.91037167, -0.02536896]])\n\n\n\n\n```python\nqfit_pth = os.path.join(project_dir, \"qfit_test.png\")\nqfit_pts, qfit_dists = orthogonal_quadric_projection(x,qq,projection_funcs)\n\ndata_avg = np.average(qfit_pts, axis=0)\ndata_std = np.std(qfit_pts, axis=0)\nfigure = mayavi.mlab.figure(figure=None, bgcolor=(1,1,1), fgcolor=(0,0,0), engine=None, size=(1000, 1000))\n#data_nodes = plt_data(figure, x[np.random.choice(np.arange(x.shape[0]), size=40, replace=False)], data_std)\nvecs = qfit_pts-pts\n#mayavi.mlab.quiver3d(x[:,0], x[:,1], x[:,2], vecs[:,0], vecs[:,1], vecs[:,2])\nquadric_nodes = plt_grid(figure, qfit_pts, data_avg, data_std)\n#other_nodes = plt_grid(figure, pts, data_avg, data_std)\n\nnormalize_view(figure, data_avg, data_std)\nmayavi.mlab.savefig(qfit_pth, magnification=2)\nmayavi.mlab.close(figure)\n\n```\n\n\n```python\nimshow(qfit_pth)\n```\n\n\n```python\n\n```\n\n\n```python\nlocal_quadrics = local_models.local_models.LocalModels(QuadricModel())\nlocal_quadrics.fit(pts)\n```\n\n\n```python\navg_pt_dist = np.average(local_quadrics.index.query(data, k=2)[0][:,1])\n```\n\n\n```python\nbandwidth = avg_pt_dist*8\nlm_kernel = local_models.local_models.TriCubeKernel(bandwidth=bandwidth)\n```\n\n\n```python\nfitted_local_quadrics, local_quadric_params = local_quadrics.transform(data,\n    r=lm_kernel.support_radius()-1, weighted=True, kernel=lm_kernel,\n    neighbor_beta0s=False, batch_size=int(data.shape[0]/32), return_models=True)\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\nq\n```\n\n\n\n\n    array([[ 0.5,  0. ,  0. ,  0. ],\n           [ 0. ,  0.4,  0. ,  0. ],\n           [ 0. ,  0. ,  0.3,  0. ],\n           [ 0. ,  0. ,  0. , -1. ]])\n\n\n\n\n```python\nimport importlib; importlib.reload(quadrics_utils)\n```\n\n\n\n\n    <module 'quadrics_utils' from '/home/brown/python_packages/local_models/examples/quadrics_utils.py'>\n\n\n\n\n```python\ndef collect_best(expr, measure=sympy.count_ops):\n    best = expr\n    best_score = measure(expr)\n    perms = itertools.permutations(expr.free_symbols)\n    permlen = np.math.factorial(len(expr.free_symbols))\n    print(permlen)\n    for i, perm in enumerate(perms):\n        if (permlen > 1000) and not (i%int(permlen/100)):\n            print(i)\n        collected = sympy.collect(expr, perm)\n        if measure(collected) < best_score:\n            best_score = measure(collected)\n            best = collected\n        else:\n            factored = sympy.factor(expr)\n            if measure(factored) < best_score:\n                best_score = measure(factored)\n                best = factored\n    return best\n    \ndef product(args):\n    arg = next(args)\n    try:\n        return arg*product(args)\n    except:\n        return arg\n    \ndef rcollect_best(expr, measure=sympy.count_ops):\n    best = collect_best(expr, measure)\n    best_score = measure(best)\n    if expr == best:\n        return best\n    if isinstance(best, sympy.Mul):\n        return product(map(rcollect_best, best.args))\n    if isinstance(best, sympy.Add):\n        return sum(map(rcollect_best, best.args))\n```\n\n\n```python\ndef derive_quadratic_orthogonal_projection_1D_polynomial(n):\n    import sympy\n    \n    Q_sym = sympy.symarray(\"q\", (n+1, n+1))\n    Q = sympy.Matrix(np.zeros((n+1,n+1), dtype=int))\n    for i, j in itertools.product(range(n+1), range(n+1)):\n        if i == n or j == n or i == j:\n            Q[i,j] = Q_sym[max(i,j),min(i,j)]\n    print(Q)\n\n    x_sym = sympy.symarray(\"x\", n+1)\n    X = sympy.Matrix(np.ones((n+1, 1), dtype=int))\n    for i in range(n):\n        X[i] = x_sym[i]\n        \n    P = sympy.Matrix(np.zeros((n-1, n+1), dtype=int))\n    for i in range(n-1):\n        P[i,0] = X[i+1]\n        P[i,i+1] = -X[0]\n    \n    QXP = P*Q*X\n    \n    other_dims_as_x0 = [sympy.solve(QXP[i], X[i+1])[0] for i in range(n-1)] \n    \n    XQX = sympy.expand((X.T*Q*X)[0])\n    XQX_as_x0 = XQX.subs({X[i+1]:other_dims_as_x0[i] for i in range(n-1)})\n    for sub in other_dims_as_x0:\n        XQX_as_x0 *= sympy.fraction(sub)[1]**2\n    XQX_as_x0 = sympy.cancel(XQX_as_x0)\n    XQX_as_x0 = sympy.simplify(XQX_as_x0)\n    XQX_as_x0 = sympy.poly(XQX_as_x0, X[0])\n    \n    return (X, Q, XQX_as_x0, other_dims_as_x0)\n    \n```\n\n\n```python\ndef collectify_polynomial_coefficients(poly):\n    return [rcollect_best(formula) for formula in poly.all_coeffs()]\n```\n\n\n```python\nsorted(map(lambda x: x**2, range(4)))\n```\n\n\n\n\n    [0, 1, 4, 9]\n\n\n\n\n```python\n\n```\n\n\n```python\nimport shelve\n\ndef funcify(signature, returnable):\n    return \"def {}: return {}\\n\".format(signature, returnable)\n\ndef get_signature(expr, name):\n    return name+str(tuple(sorted(map(str, expr.free_symbols))))\n\nk_mat = sympy.Matrix(collected)\nk_jac = k_mat.jacobian([a,b,c,d,e,f,g])\n\nwith open(\"quadrics_formulae.shelf\", \"w\") as quadrics_formulae:\n    quadrics_formulae[3] = {\n        \"k_mat\":  sympy.Matrix(collected),\n        \"k_jac\": None,\n        \"other_dims_as_x\": other_dims_as_x0,\n}\n```\n\n\n```python\nX,Q,poly,other_dims_as_x = derive_quadratic_orthogonal_projection_1D_polynomial(3)\n```\n\n    Matrix([[q_0_0, 0, 0, q_3_0], [0, q_1_1, 0, q_3_1], [0, 0, q_2_2, q_3_2], [q_3_0, q_3_1, q_3_2, q_3_3]])\n\n\n\n```python\nfunc_x0 = sympy.Function('fx_0')(*sorted(Q.free_symbols, key=str))\nfunc_xn = [sympy.Function('fx_{}'.format(i))(*(sorted(Q.free_symbols, key=str) + [func_x0]))]\n```\n\n\n```python\ndx_dvars = []\nfor var in sorted(Q.free_symbols, key=str):\n    dx_dvars.append(\n        sympy.solve(sympy.diff(poly.as_expr().subs(X[0], func_x0), var), sympy.diff(func_x0, var))[0]\n    )\ndotherdims_dvars = []\nfor i, otherdim in enumerate(X[1:-1]):\n    dotherdims_dvars.append([])\n    for j, var in enumerate(sorted(Q.free_symbols, key=str)):\n        dotherdims_dvars[-1].append(\n            sympy.diff(other_dims_as_x[i].subs(X[0], func_x0), var)\n        )\n```\n\n\n```python\nk_jac = [dx_dvars] + dotherdims_dvars\n```\n\n\n```python\njaco_vars = [sympy.Symbol(\"dx_0_\" + str(var)) for var in sorted(Q.free_symbols, key=str)]\n```\n\n\n```python\nk_jac_funcs = (\n    [[sympy.lambdify(sorted(Q.free_symbols, key=str), var) for var in sorted(Q.free_symbols, key=str)]] +\n    [[sympy.lambdify(sorted(Q.free_symbols, key=str) + [X[0], jaco_vars[j]], \n                     dotherdims_dvars[i][j].subs(sympy.diff(func_x0, var), jaco_vars[j]).subs(func_x0, X[0])) \n         for j,var in enumerate(sorted(Q.free_symbols, key=str))\n     ] for i in range(len(k_jac)-1)]\n)\n```\n\n\n```python\ni=j=1\ndotherdims_dvars[i][j].subs(sympy.diff(func_x0, sorted(Q.free_symbols, key=str)[j]), jaco_vars[j]).subs(func_x0, X[0])\n```\n\n\n\n\n$\\displaystyle \\frac{dx_{0 q 1 1} q_{3 2}}{q_{0 0} x_{0} - q_{2 2} x_{0} + q_{3 0}} + \\frac{q_{3 2} x_{0} \\left(- dx_{0 q 1 1} q_{0 0} + dx_{0 q 1 1} q_{2 2}\\right)}{\\left(q_{0 0} x_{0} - q_{2 2} x_{0} + q_{3 0}\\right)^{2}}$\n\n\n\n\n```python\njaco_vars\n```\n\n\n\n\n    [dx_0_q_0_0,\n     dx_0_q_1_1,\n     dx_0_q_2_2,\n     dx_0_q_3_0,\n     dx_0_q_3_1,\n     dx_0_q_3_2,\n     dx_0_q_3_3]\n\n\n\n\n```python\nk_jac_funcs[1][0]\n```\n\n\n\n\n    <function _lambdifygenerated(q_0_0, q_1_1, q_2_2, q_3_0, q_3_1, q_3_2, q_3_3, x_0, dx_0_q_0_0)>\n\n\n\n\n```python\ndef dU_dQ(Q, L, U):\n    Qs = Q[:-1,:-1]\n    QsLinv = np.stack(\n        [np.linalg.pinv(l*np.eye(Qs.shape[0])-Qs, hermitian=True) for l in L],\n        axis=2\n    )\n    dQsU = np.einsum('ij,kl->ijkl', np.ones(Qs.shape), U)\n    dUdQs = np.einsum('ijl,kl->ijkl', QsLinv, U)\n    ret = np.zeros(list(Q.shape) + list(U.shape)) \n    ret[:-1,:-1] = dUdQs\n    return ret #du_kl/dq_ij in slot i,j,k,l\ndef dL_dQ(Q, L, U):\n    return np.einsum('il,kl->ikl', U, U)\ndef dETQE_dQ(Q, L, U, X):\n    Qs = Q[:-1,:-1]\n    dUdQ = dU_dQ(Q,L,U)\n    dLdQ = dL_dQ(Q,L,U)\n    ret = np.zeros([Q.shape[0]]*4)\n    ret[:-1,:-1,np.arange(Q.shape[0]-1), np.arange(Q.shape[0]-1)] = dLdQ\n    ret[:-1,-1] = np.einsum('ijkl,jm,bm->bikl',np.transpose(dUdQ,(1,0,2,3)),Qs,X)\n```\nx = np.random.uniform(size=(3000,3,1))\nq = np.array([ # an elliptic paraboloid\n    [0.5,0,0,0],\n    [0,0.25,0,0],\n    [0,0,0,-1],\n    [0,0,-1,0.1],\n])\ninit_q = q\nu = np.random.uniform(size=(3,3))\nu += u.T\n_, u = np.linalg.eig(u)\nprint(u)\nprint(np.linalg.norm(u, axis=0))\nE = np.block([[u, np.ones((3,1))],[np.zeros(3), 1]])\nq = E.T@q@E\nprint(q)\n\n```python\nq.dtype, x.dtype\n```\n\n\n\n\n    (dtype('float64'), dtype('float64'))\n\n\n\n\n```python\nimport tensorflow as tf\nimport tf_roots\nimport quadrics_utils\nprojection_funcs = {\n    \"k_mat\": quadrics_utils.k_mat,\n    \"other_dims_as_x\": lambda a,b,c,d,e,f,g,x: [quadrics_utils.y_as_x(a,b,c,d,e,f,g,x), quadrics_utils.z_as_x(a,b,c,d,e,f,g,x)],\n}\n\ndef tf_rotate_and_translate_quadric(Q,X):\n    Qs = Q[:-1,:-1]\n    #col_X = tf.expand_dims(X,-1)\n    L, U = tf.linalg.eigh(Qs)\n    UTQs = tf.matmul(U,Qs,transpose_a=True)\n    UL = L\n    #UR = broadcasted_matmul(UTQs, col_X) + tf.matmul(U,Q[:-1,-1:],transpose_a=True)\n    UR = X@tf.transpose(UTQs,[1,0]) + Q[-1:,:-1]@U\n    BR = batch_dot(X@Qs,X) + 2*X@Q[:-1,-1:] + Q[-1,-1]\n    return L,U,UL,UR,BR\n\ndef tf_ortho_project_x(UL,UR,BR):\n    batch_shape = tf.shape(BR)[:-1]\n    dims = UL.get_shape().as_list()\n    ul_tiled = tf.tile(\n        tf.reshape(UL, tf.concat([[1]*tf.rank(batch_shape), dims], axis=0)), \n        tf.concat([batch_shape, [1]*len(dims)], axis=0)\n    )\n    args = (\n        [ul_tiled[...,i:i+1] for i in range(UL.shape[-1])] + \n        [BR[...,0:1]] + \n        [UR[...,i:i+1] for i in range(UR.shape[-1])]\n    )\n\n    coeffses = quadrics_utils.k_mat(*args)\n    kmat = tf.stack(coeffses, axis=-1)\n    \n    roots = tf_roots.tf_roots.tf_roots(kmat[...,:0:-1]/kmat[...,:1])\n    return args, roots\n    \ndef tf_ortho_project_prerotated(UL,UR,BR,X,imag_0tol = 1e-10):\n    args, roots = tf_ortho_project_x(UL,UR,BR)\n    roots_r = tf.real(roots)\n    roots_i = tf.imag(roots)\n    mask = tf.logical_or(tf.greater(roots_i, imag_0tol), tf.greater(-imag_0tol, roots_i))\n    masked_real_roots = tf.where(mask, roots_r, tf.fill(tf.shape(roots_r), tf.constant(np.inf, roots_r.dtype)))\n    \n    other_dims = projection_funcs[\"other_dims_as_x\"](*([tf.expand_dims(arg, -1) for arg in args] + [masked_real_roots]))\n    pts = tf.stack([masked_real_roots] + other_dims, axis=-1)\n    ortho_pts, ortho_dists = tf_min_dist_search(pts, imag_0tol=imag_0tol)\n    return ortho_pts, ortho_dists\n    \ndef tf_ortho_project_prerotated(UL,UR,BR,X,imag_0tol = 1e-10):\n    args, roots = tf_ortho_project_x(UL,UR,BR)\n    other_dims = projection_funcs[\"other_dims_as_x\"](*([tf.expand_dims(arg, -1) for arg in args] + [roots]))\n    pts = tf.stack([roots] + other_dims, axis=-1)\n\n    ortho_pts, ortho_dists = tf_min_dist_search(pts,imag_0tol=imag_0tol)\n    return ortho_pts, ortho_dists\n    \ndef tf_ortho_project(Q,X,imag_0tol=1e-10):\n    if not Q.dtype.is_complex:\n        Qc = tf.cast(Q, tf.complex128 if Q.dtype == tf.float64 else tf.complex64)\n    else:\n        Qc = Q\n    if not X.dtype.is_complex:\n        Xc = tf.cast(X, tf.complex128 if X.dtype == tf.float64 else tf.complex64)\n    else:\n        Xc = X\n    L,U,UL,UR,BR = tf_rotate_and_translate_quadric(Qc,Xc)\n    ortho_pts, ortho_dists = tf_ortho_project_prerotated(UL,UR,BR,Xc,imag_0tol=imag_0tol)\n    return tf.real(tf_unrotate_and_translate(U,Xc,ortho_pts)), tf.real(ortho_dists)\n    \ndef tf_unrotate_and_translate(U, orig_X, new_X):\n    return new_X@tf.transpose(U) + orig_X\n\ndef tf_min_dist_search(searchable, imag_0tol=1e-10):\n    # searches `searchable` for the closest real-valued point to the origin.  \n    # searchable shape (..., r, n) where n is the dimensionality of X, \n    # r is the number of points searched over.  Other dims are treated as batch dims.\n\n    searchable_shape = searchable.get_shape().as_list()\n    batch_shape = searchable_shape[:len(searchable_shape)-2] \n    n_dims = searchable_shape[-1]\n    n_searchable_pts = searchable_shape[-2]\n\n    complex_mask = tf.greater(tf.abs(tf.reduce_sum(tf.imag(searchable), axis=-1)), imag_0tol)\n    dists = tf.reduce_sum(searchable**2, axis=-1)\n    \n    masked_realpt_dists = tf.where(complex_mask, tf.fill(tf.shape(dists), tf.constant(np.inf, dists.dtype)), dists)\n    masked_realpt_dists = tf.real(masked_realpt_dists)\n    \n    idx = tf.expand_dims(tf.argmin(masked_realpt_dists, axis=-1), -1) # a (..., 1) shaped array\n\n    return tf.gather_nd(searchable, idx, batch_dims=len(batch_shape))[...,0,:], tf.gather_nd(masked_realpt_dists, idx, batch_dims=len(batch_shape))[...,0]\n\ndef broadcasted_matmul(A, B):\n    \"\"\" Matmul with fast broadcasting\n\n    Args:\n      A - [n, m]\n      B - [batch_size, m, k]\n\n    Returns:\n      AB - [batch_size, n, k]\n    \"\"\"\n    # [n, batch_size, k]\n    AB = tf.tensordot(A, B, axes=[[1], [1]])\n    # [batch_size, n, k]\n    return tf.transpose(AB, [1, 0, 2])\n    \ndef batch_dot(a,b):\n    return tf.reduce_sum( tf.multiply( a, b ), 1, keep_dims=True )\n```\n\n\n```python\n\n```\n\n\n```python\n# test min_dist_search\nwith tf.Graph().as_default(), tf.Session() as sess:\n    bar = np.array([\n        [[2,3,4],[1,2,50.01]],\n        [[4,5,8],[4,5,7]],\n        [[100,100,100],[1+1j,1,1]]])[:,np.newaxis,:,:]\n    test_roots = tf.placeholder(tf.complex128, bar.shape)\n    sol_tf = tf_min_dist_search(test_roots,1e-1)\n    res_pts, res_dists = sess.run(sol_tf, feed_dict={test_roots: bar})\n    assert np.allclose(res_pts, \n        np.array([[2., 3., 4.],\n                  [4., 5., 7.],\n                  [100,100,100]]))\n```\n\n\n```python\nres_pts\n```\n\n\n\n\n    array([[  2.+0.j,   3.+0.j,   4.+0.j],\n           [  4.+0.j,   5.+0.j,   7.+0.j],\n           [100.+0.j, 100.+0.j, 100.+0.j]])\n\n\n\n\n```python\nres_dists\n```\n\n\n\n\n    array([2.9e+01, 9.0e+01, 3.0e+04])\n\n\n\n\n```python\n# test rotate_and_translate_quadric\nwith tf.Graph().as_default(), tf.Session() as sess:\n    q = np.array([ # an elliptic paraboloid\n        [0.5,0,0,0],\n        [0,0.25,0,0],\n        [0,0,0.1,-1],\n        [0,0,-1,0.1],\n    ])\n    u = np.arange(9).reshape(3,3)\n    u += u.T\n    _, u = np.linalg.eig(u)\n\n    x = np.arange(12).reshape(4,3)*1.\n\n    E = np.block([[u, x[0].reshape(-1,1)],[np.zeros(3), 1]])\n    Einv = np.linalg.inv(E)\n    q_test = Einv.T@q@Einv\n\n    test_qs = tf.placeholder(q.dtype, q.shape)\n    test_pts = tf.placeholder(x.dtype, x.shape)\n    sol_tf = tf_rotate_and_translate_quadric(test_qs, test_pts)\n    l,u,ul,ur,br = sess.run(sol_tf, feed_dict={test_pts: x, test_qs: q_test})\n    res_q = np.block([[np.diag(ul), ur[0:1].T],[ur[0:1],br[0]]])\n    ee = np.block([[u, x[0].reshape(-1,1)],[np.zeros(3),1]])\n    eeinv = np.linalg.inv(ee)\n    assert(np.allclose(eeinv.T@res_q@eeinv, q_test))\n```\n\n\n```python\nprint(ur.shape, ul.shape, br.shape)\n```\n\n    (4, 3) (3,) (4, 1)\n\n\n\n```python\n\n```\n\n\n```python\nwith tf.Graph().as_default(), tf.Session() as sess:\n    test_qs = tf.placeholder(tf.float32, q.shape)\n    test_pts = tf.placeholder(tf.float32, x.shape)\n    test_qsc = tf.cast(test_qs, tf.complex128 if test_qs.dtype == tf.float64 else tf.complex64)\n    test_ptsc = tf.cast(test_pts, tf.complex128 if test_pts.dtype == tf.float64 else tf.complex64)\n    L,U,UL,UR,BR = tf_rotate_and_translate_quadric(test_qsc, test_ptsc)\n    ortho_pts, ortho_dists = tf_ortho_project_prerotated(UL,UR,BR,test_ptsc,imag_0tol=1e-3)\n    unrotated_pts = tf_unrotate_and_translate(U,test_ptsc,ortho_pts)\n    unrotated_pts = tf.real(unrotated_pts)\n    res = sess.run((unrotated_pts, ortho_dists), feed_dict={test_pts: x, test_qs: q_test})\ntest_res = orthogonal_quadric_projection(x,q_test,projection_funcs)\nfor i, r in enumerate(test_res):\n    assert np.allclose(r, res[i], atol=1e-4, rtol=1e-4)\n```\n\n\n```python\nres[0].shape, test_res[0].shape\n```\n\n\n\n\n    ((4, 3), (4, 3))\n\n\n\n\n```python\nres[0], test_res[0]\n```\n\n\n\n\n    (array([[ 0.02046363,  0.9590727 ,  2.0204637 ],\n            [ 2.4214036 ,  1.065655  ,  4.030104  ],\n            [ 3.598402  ,  0.40193224,  4.8424616 ],\n            [ 4.3316383 , -0.15742683,  5.338879  ]], dtype=float32),\n     array([[ 0.0204637 ,  0.9590726 ,  2.0204637 ],\n            [ 2.42140373,  1.06565579,  4.03010368],\n            [ 3.59840455,  0.40194921,  4.84246218],\n            [ 4.33162896, -0.1574637 ,  5.33887161]]))\n\n\n\n\n```python\n# test quadric_ortho_projection\nwith tf.Graph().as_default(), tf.Session() as sess:\n    test_qs = tf.placeholder(tf.float32, q.shape)\n    test_pts = tf.placeholder(tf.float32, x.shape)\n    test_qsc = tf.cast(test_qs, tf.complex128 if test_qs.dtype == tf.float64 else tf.complex64)\n    test_ptsc = tf.cast(test_pts, tf.complex128 if test_pts.dtype == tf.float64 else tf.complex64)\n    sol_tf = tf_ortho_project(test_qsc, test_ptsc, imag_0tol=1e-3)\n    res = sess.run(sol_tf, feed_dict={test_pts: x, test_qs: q_test})\ntest_res = orthogonal_quadric_projection(x,q_test,projection_funcs)\nfor i, r in enumerate(test_res):\n    try:\n        assert np.allclose(r, res[i], atol=1e-4, rtol=1e-4)\n    except:\n        print(r, res[i], np.abs(r-res[i]))\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n# test quadric_ortho_projection\nwith tf.Graph().as_default(), tf.Session() as sess:\n    test_qs = tf.placeholder(tf.float32, q.shape)\n    test_pts = tf.placeholder(tf.float32, x.shape)\n    test_qsc = tf.cast(test_qs, tf.complex128 if test_qs.dtype == tf.float64 else tf.complex64)\n    test_ptsc = tf.cast(test_pts, tf.complex128 if test_pts.dtype == tf.float64 else tf.complex64)\n    L,U,UL,UR,BR = tf_rotate_and_translate_quadric(test_qs,test_pts)\n    ARGS, roots = tf_ortho_project_x(UL,UR,BR)\n    res = sess.run([ARGS,roots], feed_dict={test_pts: x, test_qs: q_test})\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\nx = (np.random.uniform(size=(3000,3))-0.5)*10\nimag_0tol=1e-2\nwith tf.Graph().as_default(), tf.Session() as sess:\n    test_qs = tf.placeholder(tf.float32, q.shape)\n    test_pts = tf.placeholder(tf.float32, x.shape)\n    test_qsc = tf.cast(test_qs, tf.complex128 if test_qs.dtype == tf.float64 else tf.complex64)\n    test_ptsc = tf.cast(test_pts, tf.complex128 if test_pts.dtype == tf.float64 else tf.complex64)\n    proj1_pts, proj1_dists = tf_ortho_project(test_qsc, test_ptsc,imag_0tol=imag_0tol)\n    proj1_ptsc = tf.cast(proj1_pts, tf.complex128 if test_pts.dtype == tf.float64 else tf.complex64)\n    proj2_pts, proj2_dists = tf_ortho_project(test_qsc, proj1_ptsc,imag_0tol=imag_0tol)\n    p1p, p2p, p1d, p2d = sess.run([proj1_pts, proj2_pts, proj1_dists, proj2_dists], feed_dict={test_pts: x, test_qs: q_test})\nprint(np.argmax(p1d), np.argmax(p2d))\n```\n\n    620 493\n\n\n\n```python\nweird = np.argmax(p2d)\nprint(x[weird], p1p[weird], p2p[weird])\nprint(\n    np.concatenate([x[weird], [1]]).reshape(1,-1)@q_test@np.concatenate([x[weird], [1]]).reshape(-1,1),\n    np.concatenate([p1p[weird], [1]]).reshape(1,-1)@q_test@np.concatenate([p1p[weird], [1]]).reshape(-1,1),\n    np.concatenate([p2p[weird], [1]]).reshape(1,-1)@q_test@np.concatenate([p2p[weird], [1]]).reshape(-1,1)\n)\n```\n\n    [ 3.02199292 -4.69053425  4.86400737] [ 4.0812087 -1.8822029  7.6522493] [ 4.089281  -1.8608544  7.6734877]\n    [[-9.02182102]] [[-0.13037601]] [[-2.90371386e-07]]\n\n\n\n```python\n# test quadric_ortho_projection\nwith tf.Graph().as_default(), tf.Session() as sess:\n    test_qs = tf.placeholder(tf.float32, q.shape)\n    test_pts = tf.placeholder(tf.float32, x[weird:weird+1].shape)\n    L,U,UL,UR,BR = tf_rotate_and_translate_quadric(test_qs,test_pts)\n    args, roots = tf_ortho_project_x(UL,UR,BR)\n    roots_r = tf.real(roots)\n    roots_i = tf.imag(roots)\n    mask = tf.logical_or(tf.greater(roots_i, imag_0tol), tf.greater(-imag_0tol, roots_i))\n    masked_real_roots = tf.where(mask, roots_r, tf.fill(tf.shape(roots_r), tf.constant(np.inf, roots_r.dtype)))\n    \n    other_dims = projection_funcs[\"other_dims_as_x\"](*([tf.expand_dims(arg, -1) for arg in args] + [masked_real_roots]))\n    pts = tf.stack([masked_real_roots] + other_dims, axis=-1)\n    ortho_pts, ortho_dists = tf_min_dist_search(pts)\n    res = sess.run([roots, ortho_pts], feed_dict={test_pts: x[weird:weird+1], test_qs: q_test})\n```\n\n\n```python\n\n```\n\n\n```python\nres[0][0,0]\n```\n\n\n\n\n    array([  0.72231525+8.2737883e-05j,   0.7532167 -8.6197178e-05j,\n             1.8831656 +4.5354092e-05j,   2.0551214 -4.2619300e-05j,\n             6.9944844 +1.5008181e-06j, -12.900092  +0.0000000e+00j],\n          dtype=complex64)\n\n\n\n\n```python\nE = np.block([[u, x[weird].reshape(-1,1)],[np.zeros(3), 1]])\nnp.round(E.T@q_test@E,5)\n```\n\n\n\n\n    array([[ 0.1    ,  0.     ,  0.     ,  0.29507],\n           [ 0.     ,  0.25   , -0.     , -0.03578],\n           [ 0.     ,  0.     ,  0.5    ,  0.0344 ],\n           [ 0.29507, -0.03578,  0.0344 , -9.02182]])\n\n\n\n\n```python\ntp1p, tp1d = orthogonal_quadric_projection(x,q_test,projection_funcs)\ntp2p, tp2d = orthogonal_quadric_projection(tp1p,q_test,projection_funcs)\n```\n\n\n```python\nprint(x[weird], tp1p[weird], tp2p[weird])\n```\n\n    [ 3.02199292 -4.69053425  4.86400737] [ 4.09089469 -1.86488076  7.67692047] [ 4.09089469 -1.86488076  7.67692047]\n\n\n\n```python\nprint(np.sum((p1p-tp1p)**2, axis=1))\nplt.hist(np.sum((p1p-tp1p)**2, axis=1))\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\nimport ml_battery\nimport tensorflow_probability as tfp\nimport tf_roots.src.companion_eigv\n\nclass TFQuadric(sklearn.base.BaseEstimator, ml_battery.tensorflow_models.PickleableTFModel):\n    ''' A zero hidden layer NN Classifier (i.e. Logit Regression).\n        Parameters:\n            n_epochs: number of training epochs\n            learning_rate: make it bigger to learn faster, at the risk of killing your relu\n            trainable: set to false if you want to not allow training.  For example, if you want to use this as part of another network\n            batch_size: defaults to the entire dataset.\n    '''\n    def __init__(self, n_epochs=100, learning_rate=0.05, trainable=True, batch_size=None):\n        self.n_epochs = n_epochs\n        self.learning_rate = learning_rate\n        self.trainable = trainable\n        self.batch_size = batch_size\n        super().__init__()\n\n    def fit(self, X, sample_weight=None, beta0=None,**fit_params):\n        ''' Puts inputs into np format, initializes a session, builds the graph and then calls `.fit_` which can be overridden by individual models '''\n        X = sklearn.utils.check_array(X)\n        if sample_weight is None:\n            self.weighted = False\n        else:\n            self.weighted = True\n            sample_weight = sklearn.utils.check_array(sample_weight)\n        self.input_shape_ = X.shape[-1]\n        if beta0 is None:\n            beta0 = self.fast_reasonable_q(X,sample_weight)\n \n        beta0 /= beta0[-1] #TODO If the point lies ON the quadric, the remaining variables go to inf!!!! This is probably a problem for the iterated method\n        self.init_q = beta0[:-1] \n    \n        self.build_model()\n        with self.model.graph_.as_default():\n            self.sess = tf.Session(graph = self.model.graph_)\n            initializer = tf.global_variables_initializer()\n            self.sess.run(initializer)\n            return self.fit_(X, sample_weight=sample_weight, **fit_params)\n            \n    def build_model(self):\n        ''' Initializes a new graph, and then calls the .build_model_ method, which must be implemented by a TFEstimator '''\n        self.model = ml_battery.tensorflow_models.NameSpace()\n        self.model.graph_ = tf.Graph()\n        with self.model.graph_.as_default():\n            self.build_model_()\n            \n    def build_model_(self):\n        ''' The actual network architecture '''\n        with tf.name_scope(\"quadric_regression\"):\n\n            with tf.name_scope(\"input\"):\n                input_dim = [None, self.input_shape_]\n                self.model.x = tf.placeholder(tf.complex128, shape=input_dim, name=\"input\")\n                #self.model.init_q = tf.placeholder(tf.float32, shape=int((self.input_shape_ + 2)*(self.input_shape_ + 1)/2 - 1), name=\"initial_quadric\")\n                if self.weighted:\n                    self.model.sample_weight = tf.placeholder(tf.complex128, shape=[None], name=\"sample_weight\")\n\n            with tf.name_scope(\"quadric_projection\"):\n                self.model.fq = tf.Variable(self.init_q, name=\"flattened_quadric\", trainable=self.trainable)\n                q = tf.contrib.distributions.fill_triangular(\n                    tf.concat([self.model.fq[:4], tf.constant([1], dtype=self.model.fq.dtype), self.model.fq[4:7], self.model.fq[10:6:-1]], axis=-1), #TODO: This hinges on the constant=1 constraint from above, which is not necessarily a good idear\n                    upper=True\n                ) \n                self.model.q = q + tf.transpose(q)\n                if not self.model.q.dtype.is_complex:\n                    self.model.qc = tf.cast(self.model.q, tf.complex128 if self.model.q.dtype == tf.float64 else tf.complex64)\n                else:\n                    self.model.qc = self.model.q\n                self.model.orthogonal_projections, dists = tf_ortho_project(self.model.qc, self.model.x,imag_0tol=1e-2)\n                dists = tf.real(dists)\n      \n            if self.trainable:\n                with tf.name_scope(\"training\"):\n                    if not self.weighted:\n                        self.model.loss = tf.reduce_sum(dists, name=\"loss\")\n                    else:\n                        self.model.loss = tf.reduce_sum(dists*self.model.sample_weight, name=\"loss\")\n\n                    self.model.optimizer = tf.train.AdamOptimizer(self.learning_rate, name=\"optimizer\")\n                    self.model.grads = self.model.optimizer.compute_gradients(self.model.loss)\n                    self.model.grad_application = self.model.optimizer.apply_gradients(self.model.grads)\n                    with tf.control_dependencies([self.model.grad_application]):\n                        self.model.train_step = tf.no_op(name=\"train_step\")\n\n        return self.model     \n\n    def fast_reasonable_q(self, X, sample_weight=None):\n        #this allows us to orient the data to set an initial set of parameters\n        global_linear_model = local_models.TLS_models.LinearODR_mD(2)\n        global_linear_model.fit(X, sample_weight=sample_weight)\n        global_linear_vecs = global_linear_model.cov_eigenvectors[global_linear_model.cov_eigenvalues_sorter]\n        global_linear_mean = global_linear_model.intercept_\n\n        transformed_X = (X-global_linear_mean)@global_linear_vecs.T\n\n        transformed_q = np.zeros((4,4))\n\n        # an ellipse with axes in the various directions\n        transformed_q[np.diag_indices(3)] = 1/global_linear_model.cov_eigenvalues[global_linear_model.cov_eigenvalues_sorter]**2\n        transformed_q[3,3] = -1\n        #print(np.diag(transformed_q), weighted_avg_and_std(transformed_X, weights = sample_weight, axis=0)[1])\n\n        #print(transformed_q)\n        #print(global_linear_mean)\n        E = np.block([[global_linear_vecs, global_linear_mean.reshape(-1,1)],[np.zeros(3),1]])\n        Einv = np.linalg.inv(E)\n        q = Einv.T@transformed_q@Einv\n        q[np.diag_indices(4)] /= 2 #The tensorflow model is q = [[2a,b,c,d],[b,2e,f,g],[c,f,2h,i],[d,g,i,2j]]\n        beta0 = q[np.triu_indices(4)]\n        return beta0\n\n    def fit_(self, X, sample_weight=None, feed_dict_extras={}):\n        ''' Trains for a number of epochs.  Model input must be in self.model.x, output in self.model.y, loss in self.model.loss, and training using self.model.train_step '''\n        logger.info(\"fitting quadric model\")\n\n        for epoch in range(self.n_epochs):\n            batcher = ml_battery.tensorflow_models.np_batcher(X.shape[0], self.batch_size)\n            for batch in batcher:\n                feed_dict={\n                    self.model.x : X[batch],\n                }\n                if self.weighted:\n                    feed_dict[self.model.sample_weight] = sample_weight[batch]\n                feed_dict.update(feed_dict_extras)\n                loss, _ = self.sess.run(\n                    (self.model.loss, self.model.train_step),\n                    feed_dict\n                )\n\n                logger.info(\"epoch: \" + str(epoch) + \" :::: loss: \" + str(loss.sum()))\n\n        return self\n```\n\n\n```python\ntfmodel.sess.close()\n```\n\n\n```python\ntfmodel = TFQuadric()\n```\n\n\n```python\n#x = (np.random.uniform(size=(3000,3))-0.5)*10\ntfmodel.fit(p1p)\n```\n\n\n\n\n    TFQuadric(batch_size=None, learning_rate=0.05, n_epochs=100, trainable=True)\n\n\n\n\n```python\nimport time\nstart = time.time()\nn = 100\nfor i in range(n):\n    tfmodel.sess.close()\n    tfmodel = TFQuadric()\n    tfmodel.fit(p1p)\nend = time.time()\nprint((end-start)/n)\n```\n\n    7.957661757469177\n\n\n\n```python\nstart2 = time.time()\nfor i in range(n):\n    qm = QuadricModel()\n    qm.fit(p1p)\n    print(i, (time.time() - start2)/(i+1))\nend2 = time.time()\nprint((end2-start2)/n)\n```\n\n    [[ 0.12820882 -0.08229127  0.17999422 -0.49689931]\n     [-0.08229127  0.17533111 -0.20054582  0.58341657]\n     [ 0.17999422 -0.20054582  0.50019594 -1.20773793]\n     [-0.49689931  0.58341657 -1.20773793  2.06266324]]\n    0 261.05828285217285\n    [[ 0.12820882 -0.08229127  0.17999422 -0.49689931]\n     [-0.08229127  0.17533111 -0.20054582  0.58341657]\n     [ 0.17999422 -0.20054582  0.50019594 -1.20773793]\n     [-0.49689931  0.58341657 -1.20773793  2.06266324]]\n    1 259.17073822021484\n    [[ 0.12820882 -0.08229127  0.17999422 -0.49689931]\n     [-0.08229127  0.17533111 -0.20054582  0.58341657]\n     [ 0.17999422 -0.20054582  0.50019594 -1.20773793]\n     [-0.49689931  0.58341657 -1.20773793  2.06266324]]\n    2 259.6524974505107\n    [[ 0.12820882 -0.08229127  0.17999422 -0.49689931]\n     [-0.08229127  0.17533111 -0.20054582  0.58341657]\n     [ 0.17999422 -0.20054582  0.50019594 -1.20773793]\n     [-0.49689931  0.58341657 -1.20773793  2.06266324]]\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\nblah = tfmodel.sess.run(tfmodel.model.q)\nblah/blah[3,3]\n```\n\n\n\n\n    array([[ 0.17564157,  0.06196144,  0.01040763, -0.33536954],\n           [ 0.06196144,  0.16586763,  0.11591057,  0.16381599],\n           [ 0.01040763,  0.11591057,  0.21156288, -0.71594598],\n           [-0.33536954,  0.16381599, -0.71594598,  1.        ]])\n\n\n\n\n```python\nq_test/q_test[3,3]\n```\n\n\n\n\n    array([[ 0.10104396,  0.03727616,  0.01417327, -0.23163649],\n           [ 0.03727616,  0.09106561,  0.06352525,  0.11391146],\n           [ 0.01417327,  0.06352525,  0.15354212, -0.53662328],\n           [-0.23163649,  0.11391146, -0.53662328,  1.        ]])\n\n\n\n\n```python\n\n```\n\n\n```python\ntf_pts = tfmodel.sess.run(tfmodel.model.orthogonal_projections, feed_dict={tfmodel.model.x:p1p})\n#tf_pts = p1p\n```\n\n\n```python\ntf_qfit_pth = os.path.join(project_dir, \"tf_qfit_test.png\")\n\ndata_avg = np.average(tf_pts, axis=0)\ndata_std = np.std(tf_pts, axis=0)\nfigure = mayavi.mlab.figure(figure=None, bgcolor=(1,1,1), fgcolor=(0,0,0), engine=None, size=(1000, 1000))\nquadric_nodes = plt_grid(figure, tf_pts, data_avg, data_std)\ndata_nodes = plt_data(figure, p1p, data_std)\n\n\nnormalize_view(figure, data_avg, data_std)\nmayavi.mlab.savefig(tf_qfit_pth, magnification=2)\nmayavi.mlab.close(figure)\n```\n\n\n```python\nblah = imshow(tf_qfit_pth)\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\nlen(k_jac[0])\n```\n\n\n\n\n    7\n\n\n\n\n```python\ncollectification_test = [rcollect_best(formula) for formula in poly.all_coeffs()]\n```\n\n\n```python\nsympy.lambdify(sorted(Q.free_symbols, key=str), collectification_test[0])\n```\n\n\n\n\n    <function _lambdifygenerated(q_0_0, q_1_1, q_2_2, q_3_0, q_3_1, q_3_2, q_3_3)>\n\n\n\n\n```python\nlist(map(sympy.count_ops, collectification_test))\n```\n\n\n\n\n    [6, 15, 51, 49, 39, 13, 2]\n\n\n\n\n```python\nsympy.count_ops(sympy.expand(collectification_test[2]))\n```\n\n\n\n\n    158\n\n\n\n\n```python\nQ\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}q_{0 0} & 0 & 0 & q_{3 0}\\\\0 & q_{1 1} & 0 & q_{3 1}\\\\0 & 0 & q_{2 2} & q_{3 2}\\\\q_{3 0} & q_{3 1} & q_{3 2} & q_{3 3}\\end{matrix}\\right]$\n\n\n\n\n```python\nfor i in range(len(collectification_test)):\n    print(sympy.expand(collectification_test[i].subs({\n        Q[0,0]:a,\n        Q[1,1]:b,\n        Q[2,2]:c,\n        Q[3,3]:d,\n        Q[3,0]:e,\n        Q[3,1]:f,\n        Q[3,2]:g})) == sympy.expand(collected[i]))\n```\n\n    True\n    True\n    True\n    True\n    True\n    True\n    True\n\n\n\n```python\n\n```\n\n\n```python\nsympy.count_ops(sympy.expand(collected[2]))\n```\n\n\n\n\n    158\n\n\n\n\n```python\nsympy.expand(collected[3])\n```\n\n\n\n\n$\\displaystyle 4 a^{3} d e - 6 a^{2} b d e - 6 a^{2} c d e + 16 a^{2} e^{3} + 6 a^{2} e f^{2} + 6 a^{2} e g^{2} + 2 a b^{2} d e + 8 a b c d e - 14 a b e^{3} - 2 a b e f^{2} - 8 a b e g^{2} + 2 a c^{2} d e - 14 a c e^{3} - 8 a c e f^{2} - 2 a c e g^{2} - 2 b^{2} c d e + 2 b^{2} e^{3} + 2 b^{2} e g^{2} - 2 b c^{2} d e + 8 b c e^{3} + 2 b c e f^{2} + 2 b c e g^{2} + 2 c^{2} e^{3} + 2 c^{2} e f^{2}$\n\n\n\n\n```python\ncollectification_test[2]\n```\n\n\n\n\n$\\displaystyle q_{3 0}^{3} \\left(16 q_{0 0}^{2} - 14 q_{0 0} q_{2 2} + 2 q_{1 1}^{2} + q_{1 1} \\left(- 14 q_{0 0} + 8 q_{2 2}\\right) + 2 q_{2 2}^{2}\\right) + 2 q_{3 0} q_{3 1}^{2} \\left(q_{0 0} - q_{2 2}\\right) \\left(3 q_{0 0} - q_{1 1} - q_{2 2}\\right) + 2 q_{3 0} q_{3 2}^{2} \\left(q_{0 0} - q_{1 1}\\right) \\left(3 q_{0 0} - q_{1 1} - q_{2 2}\\right) + 2 q_{3 0} q_{3 3} \\left(q_{0 0} - q_{1 1}\\right) \\left(q_{0 0} - q_{2 2}\\right) \\left(2 q_{0 0} - q_{1 1} - q_{2 2}\\right)$\n\n\n\n\n```python\ncollected[2]\n```\n\n\n\n\n$\\displaystyle d \\left(a^{4} - 2 a^{3} b + a^{2} b^{2} + c^{2} \\left(a^{2} - 2 a b + b^{2}\\right) + c \\left(- 2 a^{3} + 4 a^{2} b - 2 a b^{2}\\right)\\right) + e^{2} \\left(14 a^{3} - 18 a^{2} b + 5 a b^{2} + c^{2} \\left(5 a - 4 b\\right) + c \\left(- 18 a^{2} + 20 a b - 4 b^{2}\\right)\\right) + f^{2} \\left(2 a^{3} - a^{2} b + c^{2} \\left(2 a - b\\right) + c \\left(- 4 a^{2} + 2 a b\\right)\\right) + g^{2} \\left(2 a^{3} - a^{2} c + b^{2} \\left(2 a - c\\right) + b \\left(- 4 a^{2} + 2 a c\\right)\\right)$\n\n\n\n\n```python\nsympy.expand(collectification_test[3].subs({\n        Q[0,0]:a,\n        Q[1,1]:b,\n        Q[2,2]:c,\n        Q[3,3]:d,\n        Q[3,0]:e,\n        Q[3,1]:f,\n        Q[3,2]:g}))\n```\n\n\n\n\n$\\displaystyle 4 a^{3} d e - 6 a^{2} b d e - 6 a^{2} c d e + 16 a^{2} e^{3} + 6 a^{2} e f^{2} + 6 a^{2} e g^{2} + 2 a b^{2} d e + 8 a b c d e - 14 a b e^{3} - 2 a b e f^{2} - 8 a b e g^{2} + 2 a c^{2} d e - 14 a c e^{3} - 8 a c e f^{2} - 2 a c e g^{2} - 2 b^{2} c d e + 2 b^{2} e^{3} + 2 b^{2} e g^{2} - 2 b c^{2} d e + 8 b c e^{3} + 2 b c e f^{2} + 2 b c e g^{2} + 2 c^{2} e^{3} + 2 c^{2} e f^{2}$\n\n\n\n\n```python\nlist(map(sympy.count_ops, collected))\n```\n\n\n\n\n    [6, 15, 100, 68, 39, 13, 2]\n\n\nimport sympy\nfrom sympy.abc import a,b,c,d,e,f,g,x,y,z\n\nQ = a*x**2 + b*y**2 + c*z**2 + 2*e*x + 2*f*y + 2*g*z + d\ny_as_x_num = f*x\ny_as_x_den = e-(b-a)*x\ny_as_x = y_as_x_num/y_as_x_den\nz_as_x_num = g*x\nz_as_x_den = e-(c-a)*x\nz_as_x = z_as_x_num/z_as_x_den\nQ_as_x = Q.subs({\n    y: y_as_x,\n    z: z_as_x,\n})\n\nbigQ = sympy.expand(sympy.simplify(Q_as_x*y_as_x_den**2*z_as_x_den**2))\n\ncoeffs = list(map(sympy.factor, sympy.poly(bigQ,x).all_coeffs()))\n\ncollected = []\nfor coeff in coeffs:\n    collected.append(rcollect_best(coeff))\n    \ndef funcify(signature, returnable):\n    return \"def {}: return {}\\n\".format(signature, returnable)\n\nk_mat = sympy.Matrix(collected)\nk_jac = k_mat.jacobian([a,b,c,d,e,f,g])\n\nwith open(\"quadrics_utils.py\", \"w\") as f:\n    Q_func = funcify(\"Q(a,b,c,d,e,f,g,x,y,z)\",str(Q))\n    y_as_x_func = funcify(\"y_as_x(a,b,c,d,e,f,g,x)\", str(y_as_x))\n    z_as_x_func = funcify(\"z_as_x(a,b,c,d,e,f,g,x)\", str(z_as_x))\n    Q_as_x_func = funcify(\"Q_as_x(a,b,c,d,e,f,g,x)\", str(Q_as_x))\n    k_mat_func = funcify(\"k_mat(a,b,c,d,e,f,g)\", str(k_mat.transpose().tolist()[0]))\n    k_jac_func = funcify(\"k_jac(a,b,c,d,e,f,g)\", str(k_jac.tolist()))\n    individual_k_funcs = [funcify(\"k{:01d}(a,b,c,d,e,f,g)\".format(i), str(eq)) for i,eq in enumerate(collected[::-1])]\n    list(map(f.write, [Q_func, y_as_x_func, z_as_x_func, Q_as_x_func, k_mat_func, k_jac_func] + individual_k_funcs))\n\n```python\nxx = sympy.Function('xx')(a,b,c,d,e,f,g)\nyy = sympy.Function('yy')(a,b,c,d,e,f,g,xx)\nzz = sympy.Function('zz')(a,b,c,d,e,f,g,xx)\n```\n\n\n```python\nfor var in [a,b,c,d,e,f,g]:\n    dx_dvar = sympy.solve(sympy.diff(bigQ.subs({x:xx}), var), sympy.diff(xx, var))\n    dx_dvar_num, dx_dvar_den = sympy.fraction(dx_dvar)\n    dx_dvar_num, dx_dvar_den = sympy.poly(dx_dvar_num), sympy.poly(dx_dvar_den)\n    \n    dx_dvar_num_collections = []\n    for coeff in dx_dvar_num.all_coeffs():\n        dx_dvar_num_collections.append(rcollect_best(coeff))\n    \n    dx_dvar_den_collections = []\n    for coeff in dx_dvar_den.all_coeffs():\n        dx_dvar_den_collections.append(rcollect_best(coeff))\n        \n    dx_dvar_num = sum([x**i*dx_dvar_num_collections[-(i+1)] for i in range(dx_dvar_num_collections)])\n    dx_dvar_den = sum([x**i*dx_dvar_den_collections[-(i+1)] for i in range(dx_dvar_den_collections)])\n    dx_dvar = dx_dvar_num/dx_dvar_den\n```\n\n\n```python\ndz_dvars = []\nfor var in (a,b,c,d,e,f,g):\n    print(\"diffing_z_against_var_{}\".format(str(var)))\n    dz_dvars.append(sympy.simplify(rcollect_best(sympy.diff(z_as_x.subs({x:xx}), var))))\n```\n\n\n```python\ndy_dvars = []\nfor var in (a,b,c,d,e,f,g):\n    print(\"diffing_y_against_var_{}\".format(str(var)))\n    dy_dvars.append(sympy.simplify(rcollect_best(sympy.diff(y_as_x.subs({x:xx}), var))))\n```\n\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    1\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    1\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    1\n    1\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    1\n    1\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    1\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    1\n    1\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n    5040\n    0\n    50\n    100\n    150\n    200\n    250\n    300\n    350\n    400\n    450\n    500\n    550\n    600\n    650\n    700\n    750\n    800\n    850\n    900\n    950\n    1000\n    1050\n    1100\n    1150\n    1200\n    1250\n    1300\n    1350\n    1400\n    1450\n    1500\n    1550\n    1600\n    1650\n    1700\n    1750\n    1800\n    1850\n    1900\n    1950\n    2000\n    2050\n    2100\n    2150\n    2200\n    2250\n    2300\n    2350\n    2400\n    2450\n    2500\n    2550\n    2600\n    2650\n    2700\n    2750\n    2800\n    2850\n    2900\n    2950\n    3000\n    3050\n    3100\n    3150\n    3200\n    3250\n    3300\n    3350\n    3400\n    3450\n    3500\n    3550\n    3600\n    3650\n    3700\n    3750\n    3800\n    3850\n    3900\n    3950\n    4000\n    4050\n    4100\n    4150\n    4200\n    4250\n    4300\n    4350\n    4400\n    4450\n    4500\n    4550\n    4600\n    4650\n    4700\n    4750\n    4800\n    4850\n    4900\n    4950\n    5000\n\n\n\n```python\ndy_dvars[1]\n```\n\n\n\n\n$\\displaystyle \\frac{f \\left(e \\frac{\\partial}{\\partial b} \\operatorname{xx}{\\left(a,b,c,d,e,f,g \\right)} + \\operatorname{xx}^{2}{\\left(a,b,c,d,e,f,g \\right)}\\right)}{\\left(a \\operatorname{xx}{\\left(a,b,c,d,e,f,g \\right)} - b \\operatorname{xx}{\\left(a,b,c,d,e,f,g \\right)} + e\\right)^{2}}$\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\nblah = sympy.solve(sympy.diff(bigQ.subs({x:xx}), a), sympy.diff(xx,a))\n```\n\n\n```python\nwah,hah = sympy.fraction(blah[0])\n```\n\n\n```python\nwah = sympy.poly(wah, xx)\n```\n\n\n```python\nsympy.factor(wah)\n```\n\n\n\n\n$\\displaystyle - \\left(5 a^{4} \\operatorname{xx}^{5}{\\left(a,b,c,d,e,f,g \\right)} - 8 a^{3} b \\operatorname{xx}^{5}{\\left(a,b,c,d,e,f,g \\right)} - 8 a^{3} c \\operatorname{xx}^{5}{\\left(a,b,c,d,e,f,g \\right)} + 4 a^{3} d \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} + 24 a^{3} e \\operatorname{xx}^{4}{\\left(a,b,c,d,e,f,g \\right)} + 3 a^{2} b^{2} \\operatorname{xx}^{5}{\\left(a,b,c,d,e,f,g \\right)} + 12 a^{2} b c \\operatorname{xx}^{5}{\\left(a,b,c,d,e,f,g \\right)} - 6 a^{2} b d \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} - 30 a^{2} b e \\operatorname{xx}^{4}{\\left(a,b,c,d,e,f,g \\right)} + 3 a^{2} c^{2} \\operatorname{xx}^{5}{\\left(a,b,c,d,e,f,g \\right)} - 6 a^{2} c d \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} - 30 a^{2} c e \\operatorname{xx}^{4}{\\left(a,b,c,d,e,f,g \\right)} + 12 a^{2} d e \\operatorname{xx}^{2}{\\left(a,b,c,d,e,f,g \\right)} + 42 a^{2} e^{2} \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} + 6 a^{2} f^{2} \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} + 6 a^{2} g^{2} \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} - 4 a b^{2} c \\operatorname{xx}^{5}{\\left(a,b,c,d,e,f,g \\right)} + 2 a b^{2} d \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} + 8 a b^{2} e \\operatorname{xx}^{4}{\\left(a,b,c,d,e,f,g \\right)} - 4 a b c^{2} \\operatorname{xx}^{5}{\\left(a,b,c,d,e,f,g \\right)} + 8 a b c d \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} + 32 a b c e \\operatorname{xx}^{4}{\\left(a,b,c,d,e,f,g \\right)} - 12 a b d e \\operatorname{xx}^{2}{\\left(a,b,c,d,e,f,g \\right)} - 36 a b e^{2} \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} - 2 a b f^{2} \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} - 8 a b g^{2} \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} + 2 a c^{2} d \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} + 8 a c^{2} e \\operatorname{xx}^{4}{\\left(a,b,c,d,e,f,g \\right)} - 12 a c d e \\operatorname{xx}^{2}{\\left(a,b,c,d,e,f,g \\right)} - 36 a c e^{2} \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} - 8 a c f^{2} \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} - 2 a c g^{2} \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} + 12 a d e^{2} \\operatorname{xx}{\\left(a,b,c,d,e,f,g \\right)} + 32 a e^{3} \\operatorname{xx}^{2}{\\left(a,b,c,d,e,f,g \\right)} + 12 a e f^{2} \\operatorname{xx}^{2}{\\left(a,b,c,d,e,f,g \\right)} + 12 a e g^{2} \\operatorname{xx}^{2}{\\left(a,b,c,d,e,f,g \\right)} + b^{2} c^{2} \\operatorname{xx}^{5}{\\left(a,b,c,d,e,f,g \\right)} - 2 b^{2} c d \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} - 6 b^{2} c e \\operatorname{xx}^{4}{\\left(a,b,c,d,e,f,g \\right)} + 2 b^{2} d e \\operatorname{xx}^{2}{\\left(a,b,c,d,e,f,g \\right)} + 5 b^{2} e^{2} \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} + 2 b^{2} g^{2} \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} - 2 b c^{2} d \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} - 6 b c^{2} e \\operatorname{xx}^{4}{\\left(a,b,c,d,e,f,g \\right)} + 8 b c d e \\operatorname{xx}^{2}{\\left(a,b,c,d,e,f,g \\right)} + 20 b c e^{2} \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} + 2 b c f^{2} \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} + 2 b c g^{2} \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} - 6 b d e^{2} \\operatorname{xx}{\\left(a,b,c,d,e,f,g \\right)} - 14 b e^{3} \\operatorname{xx}^{2}{\\left(a,b,c,d,e,f,g \\right)} - 2 b e f^{2} \\operatorname{xx}^{2}{\\left(a,b,c,d,e,f,g \\right)} - 8 b e g^{2} \\operatorname{xx}^{2}{\\left(a,b,c,d,e,f,g \\right)} + 2 c^{2} d e \\operatorname{xx}^{2}{\\left(a,b,c,d,e,f,g \\right)} + 5 c^{2} e^{2} \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} + 2 c^{2} f^{2} \\operatorname{xx}^{3}{\\left(a,b,c,d,e,f,g \\right)} - 6 c d e^{2} \\operatorname{xx}{\\left(a,b,c,d,e,f,g \\right)} - 14 c e^{3} \\operatorname{xx}^{2}{\\left(a,b,c,d,e,f,g \\right)} - 8 c e f^{2} \\operatorname{xx}^{2}{\\left(a,b,c,d,e,f,g \\right)} - 2 c e g^{2} \\operatorname{xx}^{2}{\\left(a,b,c,d,e,f,g \\right)} + 4 d e^{3} + 9 e^{4} \\operatorname{xx}{\\left(a,b,c,d,e,f,g \\right)} + 6 e^{2} f^{2} \\operatorname{xx}{\\left(a,b,c,d,e,f,g \\right)} + 6 e^{2} g^{2} \\operatorname{xx}{\\left(a,b,c,d,e,f,g \\right)}\\right) \\operatorname{xx}{\\left(a,b,c,d,e,f,g \\right)}$\n\n\n\n\n```python\nwah.all_coeffs()\n```\n\n\n\n\n    [-5*a**4 + 8*a**3*b + 8*a**3*c - 3*a**2*b**2 - 12*a**2*b*c - 3*a**2*c**2 + 4*a*b**2*c + 4*a*b*c**2 - b**2*c**2,\n     -24*a**3*e + 30*a**2*b*e + 30*a**2*c*e - 8*a*b**2*e - 32*a*b*c*e - 8*a*c**2*e + 6*b**2*c*e + 6*b*c**2*e,\n     -4*a**3*d + 6*a**2*b*d + 6*a**2*c*d - 42*a**2*e**2 - 6*a**2*f**2 - 6*a**2*g**2 - 2*a*b**2*d - 8*a*b*c*d + 36*a*b*e**2 + 2*a*b*f**2 + 8*a*b*g**2 - 2*a*c**2*d + 36*a*c*e**2 + 8*a*c*f**2 + 2*a*c*g**2 + 2*b**2*c*d - 5*b**2*e**2 - 2*b**2*g**2 + 2*b*c**2*d - 20*b*c*e**2 - 2*b*c*f**2 - 2*b*c*g**2 - 5*c**2*e**2 - 2*c**2*f**2,\n     -12*a**2*d*e + 12*a*b*d*e + 12*a*c*d*e - 32*a*e**3 - 12*a*e*f**2 - 12*a*e*g**2 - 2*b**2*d*e - 8*b*c*d*e + 14*b*e**3 + 2*b*e*f**2 + 8*b*e*g**2 - 2*c**2*d*e + 14*c*e**3 + 8*c*e*f**2 + 2*c*e*g**2,\n     -12*a*d*e**2 + 6*b*d*e**2 + 6*c*d*e**2 - 9*e**4 - 6*e**2*f**2 - 6*e**2*g**2,\n     -4*d*e**3,\n     0]\n\n\n\n\n```python\nhah = sympy.poly(hah, xx)\n```\n\n\n```python\nhah.all_coeffs()\n```\n\n\n\n\n    [6*a**5 - 12*a**4*b - 12*a**4*c + 6*a**3*b**2 + 24*a**3*b*c + 6*a**3*c**2 - 12*a**2*b**2*c - 12*a**2*b*c**2 + 6*a*b**2*c**2,\n     30*a**4*e - 50*a**3*b*e - 50*a**3*c*e + 20*a**2*b**2*e + 80*a**2*b*c*e + 20*a**2*c**2*e - 30*a*b**2*c*e - 30*a*b*c**2*e + 10*b**2*c**2*e,\n     4*a**4*d - 8*a**3*b*d - 8*a**3*c*d + 56*a**3*e**2 + 8*a**3*f**2 + 8*a**3*g**2 + 4*a**2*b**2*d + 16*a**2*b*c*d - 72*a**2*b*e**2 - 4*a**2*b*f**2 - 16*a**2*b*g**2 + 4*a**2*c**2*d - 72*a**2*c*e**2 - 16*a**2*c*f**2 - 4*a**2*c*g**2 - 8*a*b**2*c*d + 20*a*b**2*e**2 + 8*a*b**2*g**2 - 8*a*b*c**2*d + 80*a*b*c*e**2 + 8*a*b*c*f**2 + 8*a*b*c*g**2 + 20*a*c**2*e**2 + 8*a*c**2*f**2 + 4*b**2*c**2*d - 16*b**2*c*e**2 - 4*b**2*c*g**2 - 16*b*c**2*e**2 - 4*b*c**2*f**2,\n     12*a**3*d*e - 18*a**2*b*d*e - 18*a**2*c*d*e + 48*a**2*e**3 + 18*a**2*e*f**2 + 18*a**2*e*g**2 + 6*a*b**2*d*e + 24*a*b*c*d*e - 42*a*b*e**3 - 6*a*b*e*f**2 - 24*a*b*e*g**2 + 6*a*c**2*d*e - 42*a*c*e**3 - 24*a*c*e*f**2 - 6*a*c*e*g**2 - 6*b**2*c*d*e + 6*b**2*e**3 + 6*b**2*e*g**2 - 6*b*c**2*d*e + 24*b*c*e**3 + 6*b*c*e*f**2 + 6*b*c*e*g**2 + 6*c**2*e**3 + 6*c**2*e*f**2,\n     12*a**2*d*e**2 - 12*a*b*d*e**2 - 12*a*c*d*e**2 + 18*a*e**4 + 12*a*e**2*f**2 + 12*a*e**2*g**2 + 2*b**2*d*e**2 + 8*b*c*d*e**2 - 8*b*e**4 - 2*b*e**2*f**2 - 8*b*e**2*g**2 + 2*c**2*d*e**2 - 8*c*e**4 - 8*c*e**2*f**2 - 2*c*e**2*g**2,\n     4*a*d*e**3 - 2*b*d*e**3 - 2*c*d*e**3 + 2*e**5 + 2*e**3*f**2 + 2*e**3*g**2]\n\n\n\n\n```python\ndxda_den_collections = []\nfor coeff in hah.all_coeffs():\n    dxda_den_collections.append(rcollect_best(coeff))\n```\n\n\n```python\ndxda_den_collections[1].args[2]\n```\n\n\n\n\n$\\displaystyle c^{2} e \\left(20 a^{2} - 30 a b + 10 b^{2}\\right)$\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\nlinear_models = local_models.local_models.LocalModels(local_models.TLS_models.LinearODR_mD(2))\nlinear_models.fit(data)\n```\n\n\n\n\n    <local_models.local_models.LocalModels at 0x7f39c68a8438>\n\n\n\n\n```python\navg_pt_dist = np.average(linear_models.index.query(data, k=2)[0][:,1])\n```\n\n\n```python\navg_pt_dist\n```\n\n\n\n\n    1.2836044940342985\n\n\n\n\n```python\nrandom_data_subset = data[np.random.randint(data.shape[0], size=50)]\n```\n\n\n```python\nqueried = linear_models.index.query_radius(random_data_subset, r=avg_pt_dist*10)\n```\n\n\n```python\nlist(map(lambda x: x.shape, queried))\n```\n\n\n\n\n    [(289,),\n     (315,),\n     (283,),\n     (386,),\n     (209,),\n     (106,),\n     (375,),\n     (321,),\n     (405,),\n     (372,),\n     (341,),\n     (352,),\n     (376,),\n     (308,),\n     (249,),\n     (347,),\n     (245,),\n     (380,),\n     (378,),\n     (414,),\n     (419,),\n     (106,),\n     (345,),\n     (320,),\n     (444,),\n     (282,),\n     (208,),\n     (371,),\n     (368,),\n     (423,),\n     (307,),\n     (435,),\n     (374,),\n     (324,),\n     (271,),\n     (147,),\n     (150,),\n     (147,),\n     (397,),\n     (318,),\n     (407,),\n     (200,),\n     (239,),\n     (403,),\n     (401,),\n     (316,),\n     (353,),\n     (321,),\n     (261,),\n     (289,)]\n\n\n\n\n```python\nkernel = local_models.local_models.TriCubeKernel(bandwidth=avg_pt_dist*10)\n```\n\n\n```python\nlinear_params_vecs, linear_params_mean = local_models.linear_projections.transformate_data(data, kernel, linear_models, r=kernel.support_radius())\n```\n\n\n```python\nlinear_params_vecs.shape\n```\n\n\n\n\n    (58659, 2, 3)\n\n\n\n\n```python\ndef imshow(pth, cv2color=cv2.IMREAD_COLOR, **kwargs):\n    img = cv2.imread(pth, cv2color)\n    plt.imshow(img, **kwargs)\n```\n\n\n```python\nN = int(data.shape[0]/10)\nsample_indices = np.random.choice(np.arange(data.shape[0]), size=N)\n\npth = os.path.join(project_dir, \"single_convergence.png\")\ndata_avg = np.average(data, axis=0)\ndata_std = np.std(data, axis=0)\nfigure = mayavi.mlab.figure(figure=None, bgcolor=(1,1,1), fgcolor=(0,0,0), engine=None, size=(1000, 500))\ndata_nodes = plt_data(figure, linear_params_mean[sample_indices], data_std)\nnormals = np.cross(*np.rollaxis(linear_params_vecs[sample_indices],1))\n#normal_vecs = plt_normals(figure, normals, linear_params_mean[sample_indices], data_std)\n#neg_normal_vecs = plt_normals(figure, -normals, linear_params_mean[sample_indices], data_std)\nnormalize_view(figure, data_avg, data_std, azimuth=40, elevation=80)\nmayavi.mlab.savefig(pth, magnification=2)\nmayavi.mlab.close(figure)\n```\n\n\n```python\nimshow(pth)\nplt.axis(\"off\")\n```\n\n\n```python\nglobal_linear_model = local_models.TLS_models.LinearODR_mD(2)\nglobal_linear_model.fit(data)\n```\n\n\n\n\n    <local_models.TLS_models.LinearODR_mD at 0x7f399aae8240>\n\n\n\n\n```python\nglobal_linear_model.coef_\nglobal_params_vecs = global_linear_model.coef_.reshape(2,-1)\nglobal_params_mean = global_linear_model.intercept_\nglobal_normal = np.cross(*global_params_vecs)\n```\n\n\n```python\nbasis_changer = np.concatenate((global_params_vecs, global_normal.reshape(1,-1)),axis=0).T\nbasis_changer = np.linalg.inv(basis_changer)\n```\n\n\n```python\nbases_changed = np.einsum('ij,kj->ki', basis_changer, data-global_params_mean)\n```\n\n\n```python\nx,y,z = bases_changed.T\n```\n\n\n```python\nplt.scatter(x,y,c=z)\nplt.axis(\"off\")\n```\n", "meta": {"hexsha": "ea268dcdec3f791d7ae26268e0b184db824df982", "size": 593029, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/pointcloud_quadrics.ipynb", "max_stars_repo_name": "csbrown/pylomo", "max_stars_repo_head_hexsha": "377aa386427a32da8b42fe53aacbe3281fbf2bf6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/pointcloud_quadrics.ipynb", "max_issues_repo_name": "csbrown/pylomo", "max_issues_repo_head_hexsha": "377aa386427a32da8b42fe53aacbe3281fbf2bf6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-01T17:41:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-01T17:41:36.000Z", "max_forks_repo_path": "examples/pointcloud_quadrics.ipynb", "max_forks_repo_name": "csbrown/pylomo", "max_forks_repo_head_hexsha": "377aa386427a32da8b42fe53aacbe3281fbf2bf6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 85.3156380377, "max_line_length": 137588, "alphanum_fraction": 0.7895128232, "converted": true, "num_tokens": 38958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.03258974840696503, "lm_q1q2_score": 0.015404635579189445}}
{"text": "```python\n%matplotlib notebook\n```\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\nimport string\nfrom collections import OrderedDict \nfrom nltk.stem import PorterStemmer\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\n```\n\n\n```python\n# Normalize the files to use i.e. same number of lines\nf = open(\"126015.txt\", \"r\")\nbook1 = f.read()\nbook1_lines = book1.split('\\n')\nrandom.shuffle(book1_lines)\nbook1_part1 = book1_lines[:len(book1_lines)//2]\nbook1_part2 = book1_lines[len(book1_lines)//2:]\nf.close()\n\nwf = open(\"126015_1.txt\", \"w+\")\nwf.write('\\n'.join(book1_part1))\nwf.close()\n\nwf = open(\"126015_2.txt\", \"w+\")\nwf.write('\\n'.join(book1_part2))\nwf.close()\n```\n\n\n```python\n# Normalize second file.\nf = open(\"524590.txt\", \"r\")\nbook2 = f.read()\nbook2_lines = book2.split('\\n')\nrandom.shuffle(book2_lines)\nbook2_normalized = book2_lines[:len(book1_lines)//2]\nf.close()\n\nwf = open(\"524590_1.txt\", \"w+\")\nwf.write('\\n'.join(book2_normalized))\nwf.close()\n```\n\n\n```python\ndef get_word_len_freq(path):\n    f = open(path, \"r\")\n    book1 = f.read()\n    \n    # Tokenize based on NLTK and regexp split criteria.\n    book1_words = word_tokenize(book1)\n    tokenizer = RegexpTokenizer(r'\\w+')\n    book1_words = tokenizer.tokenize(\" \".join(book1_words))\n    \n    stop_words = set(stopwords.words('english')) \n    \n    # Remove punctuation.\n    book1_words = [x.lower() for x in book1_words if not x in string.punctuation]\n    # Remove stop words.\n    book1_words = [x for x in book1_words if not x in stop_words]\n    # Stem words.\n    ps = PorterStemmer()\n    book1_words = [ps.stem(x) for x in book1_words]\n    \n    book1_word_freq = {}\n    for word in book1_words:\n        if book1_word_freq.get(len(word)):\n            book1_word_freq[len(word)] += 1\n        else:\n            book1_word_freq[len(word)] = 1\n    \n    return book1_word_freq\n```\n\n\n```python\ndef get_word_freq(path):\n    f = open(path, \"r\")\n    book1 = f.read()\n    \n    # Tokenize based on NLTK and regexp split criteria.\n    book1_words = word_tokenize(book1)\n    tokenizer = RegexpTokenizer(r'\\w+')\n    book1_words = tokenizer.tokenize(\" \".join(book1_words))\n    \n    stop_words = set(stopwords.words('english')) \n    \n    # Remove punctuation.\n    book1_words = [x.lower() for x in book1_words if not x in string.punctuation]\n    # Remove stop words.\n    book1_words = [x for x in book1_words if not x in stop_words]\n    # Stem words.\n    ps = PorterStemmer()\n    book1_words = [ps.stem(x) for x in book1_words]\n    \n    book1_word_freq = {}\n    for word in book1_words:\n        if book1_word_freq.get(word):\n            book1_word_freq[word] += 1\n        else:\n            book1_word_freq[word] = 1\n    \n    return book1_word_freq\n```\n\n\n```python\n# 126015 - Perfect Obedience A Bride\u2019s Vow\n# Genre: Historical Romance Fiction\nbook1_len_freq = get_word_len_freq(\"126015_1.txt\")\n# 126015 - Perfect Obedience A Bride\u2019s Vow\n# Genre: Historical Romance Fiction\nbook2_len_freq = get_word_len_freq(\"126015_2.txt\")\n# 524590 - 48 Hours To Die\n# Genre: Thriller Fiction\nbook3_len_freq = get_word_len_freq(\"524590_1.txt\")\n```\n\n\n```python\nbook1_len_freq\n```\n\n\n\n\n    {4: 7207,\n     6: 2750,\n     5: 4135,\n     7: 1092,\n     3: 2160,\n     2: 222,\n     8: 398,\n     9: 131,\n     1: 7,\n     12: 9,\n     10: 43,\n     11: 3}\n\n\n\n\n```python\nbook2_len_freq\n```\n\n\n\n\n    {4: 7223,\n     6: 2657,\n     5: 4200,\n     3: 2101,\n     8: 418,\n     7: 1145,\n     2: 174,\n     1: 8,\n     10: 41,\n     9: 133,\n     13: 2,\n     11: 2,\n     12: 3}\n\n\n\n\n```python\nmin_length = 1\nmax_length = max(max(book1_len_freq.keys()), max(book2_len_freq.keys()), max(book3_len_freq.keys()))\n```\n\n\n```python\nxvalues = [i for i in range(min_length, max_length+1)]\n\nyvalues1_norm = sum(book1_len_freq.values())\nyvalues1 = []\nfor i in range(min_length, max_length+1):\n    if book1_len_freq.get(i):\n        yvalues1.append(book1_len_freq.get(i) / yvalues1_norm)\n    else:\n        yvalues1.append(0)\n        \nyvalues2_norm = sum(book2_len_freq.values())\nyvalues2 = []\nfor i in range(min_length, max_length+1):\n    if book2_len_freq.get(i):\n        yvalues2.append(book2_len_freq.get(i) / yvalues2_norm)\n    else:\n        yvalues2.append(0)\n\nyvalues3_norm = sum(book3_len_freq.values())\nyvalues3 = []\nfor i in range(min_length, max_length+1):\n    if book3_len_freq.get(i):\n        yvalues3.append(book3_len_freq.get(i) / yvalues3_norm)\n    else:\n        yvalues3.append(0)\n```\n\n\n```python\nsum_yvalues1 = [sum(yvalues1[:i+1]) for i in range(len(yvalues1))]\nsum_yvalues2 = [sum(yvalues2[:i+1]) for i in range(len(yvalues2))]\nsum_yvalues3 = [sum(yvalues3[:i+1]) for i in range(len(yvalues3))]\n```\n\n\n```python\nplt.figure(figsize=(9,4))\nplt.subplot(1, 2, 1)\nplt.title(\"Pages PDF\")\nplt.xlabel(\"Word Length\")\nplt.ylabel(\"Probability\")\nplt.plot(xvalues, yvalues1, label=\"Fragment 1\", alpha=0.6)\nplt.plot(xvalues, yvalues2, label=\"Fragment 2\", alpha=0.6)\nplt.plot(xvalues, yvalues3, label=\"Fragment 3\", alpha=0.6)\nplt.legend()\nplt.subplot(1, 2, 2)\nplt.title(\"Pages EDF\")\nplt.xlabel(\"Word Length\")\nplt.ylabel(\"Cumulative Probability\")\nplt.plot(xvalues, sum_yvalues1, label=\"Fragment 1\", alpha=0.6)\nplt.plot(xvalues, sum_yvalues2, label=\"Fragment 2\", alpha=0.6)\nplt.plot(xvalues, sum_yvalues3, label=\"Fragment 3\", alpha=0.6)\nplt.legend()\nplt.show()\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n$\\begin{equation}D_{F, G} = \\max_{x_i\\in x} \\{ |F(x_i)-G(x_i)| \\} \\end{equation}$\n\n\n```python\n\n```\n", "meta": {"hexsha": "26f6922aaf4a2fe3c9e99ff069e4c9969ab08ac7", "size": 248362, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Kolmogorov-Smirnoff Test.ipynb", "max_stars_repo_name": "LewisErick/kolmogorov-smirnov", "max_stars_repo_head_hexsha": "24ebce8a8155cf94f1872e5411b06f17b631859d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Kolmogorov-Smirnoff Test.ipynb", "max_issues_repo_name": "LewisErick/kolmogorov-smirnov", "max_issues_repo_head_hexsha": "24ebce8a8155cf94f1872e5411b06f17b631859d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Kolmogorov-Smirnoff Test.ipynb", "max_forks_repo_name": "LewisErick/kolmogorov-smirnov", "max_forks_repo_head_hexsha": "24ebce8a8155cf94f1872e5411b06f17b631859d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 219.5950486295, "max_line_length": 204247, "alphanum_fraction": 0.8820069093, "converted": true, "num_tokens": 1686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.037892429753269334, "lm_q1q2_score": 0.0152921286559156}}
{"text": "# Introduction\n\nMy master thesis looked into service discovery recommendation system research based on data available at the programmable web [website](https://www.programmableweb.com/). \n\nIn this notebook, I will share some of what I learned and use Latent Dirichlet Allocation and the Author Topic Model are implemented and the results were compared in terms of Mean Average Precision@N and Recall@N.\n\n\n\n## Importing Libraries and Loading Data \n\n\n```python\nimport numpy as np\nimport pandas as pd\nimport re\nfrom collections import  Counter\nimport ml_metrics as metrics\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import PorterStemmer\n\n#Mashup Data \nmdata = pd.read_csv(\"data/mashups_2k18.csv\",sep='\\t',encoding='utf-8')\n#list of unique APIs\nu_apis= pd.read_csv(\"data/unique_apis.csv\",sep='\\t',encoding='utf-8')\nmdata.sort_values('title',inplace=True)\nu_apis.sort_values('api_name',inplace=True)\nprint('Total Number of Mashups: ', mdata.shape[0])\nprint('Total Number of Mashups: ', u_apis.shape[0])\n\nmdata.head()\n\n```\n\n    Total Number of Mashups:  6962\n    Total Number of Mashups:  1520\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Unnamed: 0</th>\n      <th>description</th>\n      <th>title</th>\n      <th>date</th>\n      <th>Related_APIs</th>\n      <th>Tags</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>906</th>\n      <td>906</td>\n      <td>#API Christmas is the Nativity Story, remixed ...</td>\n      <td>#API Christmas</td>\n      <td>2012-12-20</td>\n      <td>['instagram-graph']</td>\n      <td>['aggregation', 'holidays', 'humor', 'social',...</td>\n    </tr>\n    <tr>\n      <th>2486</th>\n      <td>2486</td>\n      <td>#Ask4Stuff is a new, Twitter-based service tha...</td>\n      <td>#Ask4Stuff: WorldCat Twitter Search</td>\n      <td>2010-06-27</td>\n      <td>['twitter', 'worldcat-search']</td>\n      <td>['library', 'search', 'books']</td>\n    </tr>\n    <tr>\n      <th>610</th>\n      <td>610</td>\n      <td>To discover the most popular beer in over 1500...</td>\n      <td>#BeerMap - The Top 2,500 Beers on Twitter</td>\n      <td>2013-09-19</td>\n      <td>['google-maps', 'twitter', 'peekyou-social-ana...</td>\n      <td>['analytics', 'beer', 'humor']</td>\n    </tr>\n    <tr>\n      <th>2922</th>\n      <td>2922</td>\n      <td>Get some shiny stats about countries, cities a...</td>\n      <td>#LinS Stats on Your LinkedIn Social Graph</td>\n      <td>2009-11-27</td>\n      <td>['google-chart', 'linkedin']</td>\n      <td>['social', 'statistics', 'social', 'enterprise']</td>\n    </tr>\n    <tr>\n      <th>577</th>\n      <td>577</td>\n      <td>The #S42AT project lets you bookmark links you...</td>\n      <td>#S42AT</td>\n      <td>2013-11-11</td>\n      <td>['facebook', 'twitter', 'instagram-graph', 'go...</td>\n      <td>['bookmarks', 'tools', 'tweets']</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Data Pre-processing\n\nAs machine learning models can not deal with raw text data, a set of pre- processing steps is needed to give a meaningful representation of the text. The text is transformed to a Bag-of-Words representation which assigns a unique number to every word in the vocabulary, this way any document can be represented as a vector of length $\\vert V\\vert$ the number of unique words in the vocabulary. Each cell in the vector contains the count of the word in the document. \nThis can be done by assigning each word a unique number. Then any document we see can be encoded as a fixed-length vector with the length of the vocabulary of known words. The value in each position in the vector could be filled with a count or frequency of each word in the encoded document.\n\nA high number of words generally translates into more computation and sparsity in the bag of word model, meaning that words should be carefully selected from the vocabulary and words that do not add meaning to the machine learning model should be dropped. The pre-processing steps follow the general guidelines of working with text in the Nature Language Processing field and the reviewed work on service discovery RS:\n\n####  Tokenization: dividing a stream of text into a sequence of words according to a delimiter (space in this case)\n#### Pruning: Removing words that do not add meaning to the sentence, also known as stop-words removal, a list of stopwords was taken from the Natural Language Toolkit (nltk) python library to this end\n##### item Stemming: Stripping words from suffixes and/or prefixes to get to the word stem/root. This way word like 'map','mapping' and 'maps' would be counted as 'map' adding relevance for the model. The Porter Stemmer of the nltk library was used.\n#### Text Augmentation: Since Mashup and API titles and categories add meaning to the representation of a mashup, they are added to the description of the mashups.\n\n\n\n\n\n```python\n#storing the mashup corpus as a list of words\ncorpus_list=[]\n#storing the corpus as strings\ncorpus_string = []\n#APIs related to each row of the mashup data\nrapis= []\n#storing the API corpus as strings\ncorpus_api_string = []\n#storing the API corpus as a list of word_ids\ncorpus_api_list = []\n#dictionary for mashup and its corespending APIs\ndict_mashup_apis = dict()\n#Number of times each API was used in a mashup\napi_count = []\n#calculating tag counts for EDA\ntag_count  = []\n#mashup_api matrice for EDA\nma_matrice = np.zeros((mdata.shape[0],u_apis.shape[0]),dtype=int)\n\n\nfor i in range(0, mdata.shape[0]):\n    \n    # get each related api seperatly\n    apis = list(filter(None,re.sub('[^\\w+\\d+-]',' ', mdata['Related_APIs'][i]).strip().split(' ')))\n    rapis.append(apis)\n    dict_mashup_apis[i] = []\n    \n    for a in apis:\n        dict_mashup_apis[i].append(a)\n        api_index = u_apis.loc[u_apis['api_name']==a].index\n        ma_matrice[i][api_index]= ma_matrice[i][api_index] + 1\n        \n    api_count.extend(apis)\n    \n    #Extract Description and tags while removing special characters \n    review = re.sub('[^a-zA-Z-\\d+]', ' ', mdata['description'][i])\n    tags =  re.sub('[^a-zA-Z-\\d+]',' ',mdata['Tags'][i])\n    tag_count.extend(tags.split())\n    review = review.lower()  \n    review = review.split()\n    #Changing each word to stem form\n    ps = PorterStemmer()\n    stopwords_ = list(set(stopwords.words('english')))\n    stopwords_.append('mashup')\n    review = [ps.stem(word) for word in review if not word in set(stopwords_)]\n    #adding the tags 3 times and the title of the mashup to the mashup description \n    for j in range(3):\n        review.append(tags)\n\n    review.append(mdata['title'][i])\n    corpus_list.append(review)\n    review = ' '.join(review)\n    corpus_string.append(review)\n    \n\nprint(mdata['description'][10],'\\n After Pre-processing')\ncorpus_string[10]\n\n```\n\n    Goodneighbor is a platform that allows you to define, run and manage Twitter avatars, totally autonomous Twitter identities that manage their own Twitter accounts, concerned with any subject matter and interested in any topic. \n     After Pre-processing\n\n\n\n\n\n    'goodneighbor platform allow defin run manag twitter avatar total autonom twitter ident manag twitter account concern subject matter interest topic   artificial-intelligence    social     artificial-intelligence    social     artificial-intelligence    social   Goodneighbor'\n\n\n\nSo far we have tokenized and stemed the mashup and APIs description, and mapped each API (Parent) to its mashup (child).\n\nNow let's change api names and words to numerical IDs, and create our bag of word model\n\n\n```python\n\n\n# Changing API name to API ids\nunique_apis = list(u_apis['api_name'])\napi_id_dict = dict(zip(unique_apis, range(len(unique_apis))))\napi_id_dict_reverse = dict(zip( range(len(unique_apis)),unique_apis))\n\n#Create dictionary of Mashups and Related APIs IDs\nfor mash, rapi in dict_mashup_apis.items():\n    for i, api_id in enumerate(rapi):\n        \n        dict_mashup_apis[mash][i] = api_id_dict[api_id]\n\n# Let's create the bag of word model\nfrom sklearn.feature_extraction.text import CountVectorizer\ncv = CountVectorizer(min_df=5,max_df=0.8,stop_words='english')\nL = cv.fit_transform(corpus_string + corpus_api_string).toarray()\nfeatures = cv.get_feature_names()\n\n \n\n```\n\n\n```python\n#Now let's encode the corpus with only the features extracted from the count vectorizer and create appropriate word dict\ncorpus_encoded = []\nword_id_dict = dict(zip(features, range(len(features))))\nword_id_dict_reverse = dict(zip( range(len(features)),features))\ncorpus_encoded = []\nfor each in corpus_list:\n    words_encoded = []\n    for e in each:\n        if(e in word_id_dict):\n            words_encoded.append(word_id_dict[e])\n    corpus_encoded.append(words_encoded)\n\n```\n\n# EDA \n\n## What APIs are used the most for creating Mashups?\n\nThe first graph plots the API use count, and we can clearly see that very few APIs are responsible for most mashups. Leading the pack is 'google-maps' with more than 2300 mashup to its count, followed by Twitter that has more than 750 mashup.\nOn the other hand, the top 40 - 50 APIs are only used to create around 40 mashups\n\n\n\n\n\n\n```python\nfrom collections import Counter\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom matplotlib import pyplot\n%matplotlib inline\n\ncounter2 = Counter(api_count)\neda_apis =  pd.DataFrame.from_dict(counter2, orient='Index').reset_index()\neda_apis.columns = ['api','count']\nf_apid = lambda x : api_id_dict[x]\neda_apis['id'] = eda_apis['api'].apply(f_apid)\neda_apis.sort_values('count',ascending=False,inplace=True)\ntop_50_apis = eda_apis[[\"count\",'api']][:50].copy()\n\n\nplt.subplots(figsize=(22, 8))\nplt.xticks(rotation=90)\nsns.barplot(x='api', y=\"count\", data=top_50_apis, palette=\"vlag\").set_title(\"50 Most Used APIs\")\nplt.show()\n\n\n\n\n\n```\n\n\n```python\ntop_50_apis.tail(10)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>api</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>241</th>\n      <td>50</td>\n      <td>freebase</td>\n    </tr>\n    <tr>\n      <th>359</th>\n      <td>48</td>\n      <td>panoramio</td>\n    </tr>\n    <tr>\n      <th>83</th>\n      <td>47</td>\n      <td>eventful</td>\n    </tr>\n    <tr>\n      <th>341</th>\n      <td>44</td>\n      <td>facebook-graph</td>\n    </tr>\n    <tr>\n      <th>192</th>\n      <td>44</td>\n      <td>google-calendar</td>\n    </tr>\n    <tr>\n      <th>447</th>\n      <td>43</td>\n      <td>google-earth</td>\n    </tr>\n    <tr>\n      <th>279</th>\n      <td>43</td>\n      <td>salesforcecom</td>\n    </tr>\n    <tr>\n      <th>302</th>\n      <td>42</td>\n      <td>google-translate</td>\n    </tr>\n    <tr>\n      <th>53</th>\n      <td>41</td>\n      <td>indeed</td>\n    </tr>\n    <tr>\n      <th>555</th>\n      <td>40</td>\n      <td>google-maps-flash</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n# What are the most popular Tags ?\n\nWe can see from the graph that the tag distribution is similar to that of APIs (few tags present with most mashups) \nIt is normal to see such distribution since the APIs used with a mashup influence the possible functionalities of the mashup (hence tags as well)\n\n\n\n```python\ncounter = Counter(tag_count)\ntag_count_result= list(counter.most_common())\neda_tags = pd.DataFrame.from_dict(counter, orient='Index').reset_index()\neda_tags.columns = ['tag','count']\neda_tags.sort_values('count',ascending=False,inplace=True)\ntop_50_tags = eda_tags[[\"count\",'tag']][:50].copy()\n\n\nplt.subplots(figsize=(22, 8))\nplt.xticks(rotation=90)\nsns.barplot(x='tag', y=\"count\", data=top_50_tags, palette=\"vlag\").set_title(\"50 Most Used Tags\")\nplt.show()\n```\n\n#  The API - Mashup Matrix\n\nNow let's have a look at the mashups and the APIs they use\n\nHorizantal lines indicate that an API has been used to create a lot of mashups\n\n\n\n```python\ndf = pd.DataFrame(ma_matrice.T,columns=mdata['title'].values)\ndf.index = u_apis['api_name'].values\n\nplt.figure(figsize=(20,8))\nax = sns.heatmap(df,vmin=0, vmax=1,cmap='rocket' )\nax.set_xlabel(xlabel='Mashups', fontsize=16)\nax.set_ylabel(ylabel='APIs', fontsize=16)\nax.set_title(label='API invocation Matrix', fontsize=20)\nplt.show()\n\n\n# (10, 27)\n```\n\n# How many APIs occur together in mashups ?\n\nLet's have a look at the co-occurance of APIs, to do that we take the dot product of the mashup API matrix with its inverse (transpose)\n\nWe can clearly see that the matrix is very sparse (a lot of 0s, thus the dark color)\nthe horizontal/vertical colored line indicate that it is a popular API and that it has been used a lot for creating mashups\n\nThe white (light) dotes in the graph indicate that a pair of APIs has been used a lot together (at least 5 times)\n\n\n```python\nimport numpy as np\n#calculating API co occurences\n#A = np.dot(ma_matrice.transpose(),ma_matrice)\n#df = pd.DataFrame(A,columns = u_apis['api_name'].values)\n#df.set_index(u_apis['api_name'].values,inplace=True)\n#df.to_csv('data/api_coocu.csv', sep='\\t', encoding='utf-8')\n#df.head()\n\n\n#API Co occurence matrice - To avoid a long processing time,\n#I will load the API co occurence matrice from a file\nA = pd.read_csv(\"data/api_coocu.csv\",sep='\\t',encoding='utf-8').drop('Unnamed: 0',axis=1)\nA.set_index(u_apis['api_name'].values,inplace=True)\nA.head()\n\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>123-shop-pro</th>\n      <th>123contactform</th>\n      <th>12secondstv</th>\n      <th>140-proof</th>\n      <th>18amail</th>\n      <th>1map</th>\n      <th>23</th>\n      <th>30-boxes</th>\n      <th>3dcart</th>\n      <th>411sync</th>\n      <th>...</th>\n      <th>zixxo</th>\n      <th>zoho-crm</th>\n      <th>zomato-foodie-index</th>\n      <th>zoomin</th>\n      <th>zoominfo</th>\n      <th>zooomr</th>\n      <th>zoopla</th>\n      <th>zootool</th>\n      <th>zotero</th>\n      <th>zvents</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>123-shop-pro</th>\n      <td>18</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>123contactform</th>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>12secondstv</th>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>140-proof</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>18amail</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 1520 columns</p>\n</div>\n\n\n\n\n```python\nplt.figure(figsize=(20,15))\nax = sns.heatmap(A,vmin=0, vmax=5,cmap='rocket' )\nax.set_xlabel(xlabel='APIs', fontsize=16)\nax.set_ylabel(ylabel='APIs', fontsize=16)\nax.set_title(label='API co-occurence Matrix', fontsize=20)\nplt.show()\n\n```\n\n# Recomendation Approach (Author Topic Model) \n\nThe Programmable Web API recommendation problem can be defined as follow:\nGiven a list of Mashups and and their component APIs descriptions, build a recommender that returns a ranked list of APIs that would satisfy the user query. For the sake of off-line evaluation, the user query is represented by unseen mashup descriptions and categories\n\n## Graphical explanation of the recomendation process\n\nIf you compare the description of the mashup Holidayen and its component service Flickr API in the picture below, you quickly notice that there is not much in common in their respective descriptions and that\u2019s because each one serves a different function.\n\nHolidayen helps users with planning their holidays and Flickr API provides access to photos from the Flickr platform using different feeds. To a mashup creator, it is clear that Flickr was used to provide adequate pictures for different locations and make the user experience pleasant, though this relation can not be captured by the service description because the API provider does not have to provide information about all the potential use cases of its services. The mashup descriptions on the other hand are more likely to give insight of the potential use cases of an API because they link the service Flickr to the \u2018Travel\u2019 use case in this example. \n\n\nStarting from this observation, the authors of [the reconstructed service profile paper](https://ieeexplore.ieee.org/document/7763869/) devised a way to build new API service description based on the description of the mashups that invoked said APIs. To put it more in context, let\u2019s use the Holidayen example, the words used to describe the mashup can be attributed to each related API as shown in the figure below. Doing the stated operation for every mashup gives a new set of words to describe the APIs that better captures the relationship between the APIs and their use cases. The attribution of words from mashups to APIs is done using a generative probabilistic approach called The Author Topic model. \n\n\n\n\n\n\n\n\nThe [author topic model model](https://arxiv.org/abs/1207.4169) was first introduced to explore the relationships between authors, documents, topics, and words in a collection of academics papers and paper abstracts. The author topic model views each words in a document as the manifestation of one of the authors\u2019 interest (topics). According to the Author Topic Model,  to create each word w in a document d, an author is chosen at random from the uniform distribution of authors over document, and a word is picked from a topic distribution specific to that author. Accordingly, each author is associated with a multinomial distribution over topics, each topic is associated with a multinomial distribution over words,  and each word is associated with an author and a topic assignment. The topic distribution of a document is then a mixture of topic assignments of the author of the documents.\n\n\nIf each document was written by a unique author, then the author assignment becomes trivial, meaning that topics are determined by documents which is the same as using LDA model. \nLatent Dirichlet Allocation (LDA) is a generative statistical model that treats each document as a mixture of distinct topics (clusters of words) that are responsible for the appearance of each word in the document with a certain probability. The generative process to create mashups using LDA and the graph notation of LDA is presented below:\n\n\n\n\nIn the mashup service discovery context, we can think of APIs as being authors of mashup descriptions.  Each word in the description can then be attributed to one of the API\u2019s topic assignment. the figure below depicts the plate notation of the generative process to mashup words creation with the author-topic model. \nThe generative process to create mashups works as follows:\n\n\n\nHowever; the recommendation approach I am using here is only needs the author assignment of the Author Topic Model, we use to calculate the following conditional probability. The probability can be seen as wether an API (s for Service) will satisfy a user if he inputs a word (w) in his query\n\n\\begin{equation} \n\\label{eq:psw} p(s|w)=\\frac {\\text {RP}(s,w)}{\\sum _{k}\\text {RP}(k,w)}.\n\\end{equation} \n\nOnce the relevance between services and words is calculated, the query relevance score can be defined as follow:\n\n\\begin{equation} r(s,Q)=\\sum \\limits _{w\\in Q}p(s|w). \\end{equation} \n\n\n\n\nTo account for the popularity of APIs, a list of dominant words is generated by looking at the co-occurrences of service - word pairs . Basically, if a word in the reconstructed profiles is overwhelmingly associated with a service $p(s\\vert w) ~=1$, the services and the words are associated and added to a dominant words list. If a dominant word is present in the user query, then its corresponding service score is boosted by adding the length of the query to the final relevance score. The authors [the reconstructed service profile paper](https://ieeexplore.ieee.org/document/7763869/) propose two simple rules to identify dominant words.\n\n     p(s|w) > g where g is a constant between 0 and 1\n     RP(s,w) > h where h is constant positive integer\n\n\n\n### Functions for calculating relevance score\n\n\n```python\ndominant_words = dict()\ndef rspsim(word,api,z,l):\n\n    dist = (rsp[api][word])/z\n    if(rsp[api][word] / z > 0.3 and rsp[api][word]>0.5):\n        dist = (rsp[api][word]/z)+ l \n        if(word in dominant_words):\n            if(not (api in dominant_words[word])):\n                dominant_words[word].append(api)\n        else:\n            dominant_words[word]=[]\n            dominant_words[word].append(api)\n    \n    return  dist\n\n\n\ndef get_rspsims(words,top_n=20):\n    ranked_list = np.zeros(len(unique_apis),dtype='float')\n    l = len(words)\n    for word in words:\n        \n        z = np.sum(rsp[:,word])\n        \n        if(z > 0):\n            sims = np.array([rspsim(word,api_id_dict[api],z,l) for api in unique_apis ])\n        else:\n            sims = np.zeros(len(unique_apis))\n        ranked_list = ranked_list + sims\n    \n    \n    df = pd.DataFrame(list(zip(unique_apis, list(ranked_list))), columns=['Author', 'Score'])\n    return df\n\n\ndef recall(actual, predicted):\n    la = len(actual)\n    r = []\n\n    for i in range(len(predicted)):\n        tp = [doc for doc in predicted[:i+1] if doc in actual]\n        r.append(len(tp) * 1.0 / la)\n\n    return r\n\n```\n\n### Building Train and Test Set\n\n\n```python\nrsp = np.zeros([len(unique_apis),len(features)])\nrsp_dict = dict()\nfor each in unique_apis:\n    rsp_dict[each] = []\n\n\n            \n            \nmost_common_5 = ['google-maps', 'twitter', 'youtube', 'flickr','facebook']\n                  #,'amazon-product-advertising', 'twilio','lastfm', 'ebay', 'twilio-sms', 'google-search', 'microsoft-bing-maps', \n                  #'delicious-0', 'google-ajax-search', 'foursquare', 'google-app-engine', \n                  #'google-homepage', 'yahoo-search', 'docusign-enterprise', 'yahoo-maps']\n\n\nfrom sklearn.model_selection import train_test_split\nX_Train, X_Test, Y_Train, Y_Test,dict_train,dict_test = train_test_split(corpus_encoded, rapis,dict_mashup_apis, test_size = 0.2, random_state = 0)\n\nprint('Size of train records:', len(X_Train))\nprint('Size of test records:', len(X_Test))\n \n\n```\n\n    Size of train records: 5569\n    Size of test records: 1393\n\n\n### Running the Author Topic Model\n may take some time\n\n\n```python\nn_doc = len(X_Train)\nn_topic = 50\nn_author = len(unique_apis)\nn_voca = len(features)\nmax_iter = 50\nfrom original import AuthorTopicModel\nmodel = AuthorTopicModel(n_doc, n_voca, n_topic, n_author,alpha = 1, beta=0.01)\nmodel.fit(X_Train, dict_train, max_iter=max_iter)\n```\n\n    2019-01-17 12:30:45 INFO:AuthorTopicModel:[INIT] 0\telapsed_time:3.71\tlog_likelihood:-821804.09\n    2019-01-17 12:30:49 INFO:AuthorTopicModel:[INIT] 1\telapsed_time:3.71\tlog_likelihood:-772327.43\n    2019-01-17 12:30:53 INFO:AuthorTopicModel:[INIT] 2\telapsed_time:3.79\tlog_likelihood:-736197.19\n    2019-01-17 12:30:57 INFO:AuthorTopicModel:[INIT] 3\telapsed_time:3.79\tlog_likelihood:-702732.27\n    2019-01-17 12:31:00 INFO:AuthorTopicModel:[INIT] 4\telapsed_time:3.84\tlog_likelihood:-674102.71\n    2019-01-17 12:31:04 INFO:AuthorTopicModel:[INIT] 5\telapsed_time:3.66\tlog_likelihood:-653100.10\n    2019-01-17 12:31:08 INFO:AuthorTopicModel:[INIT] 6\telapsed_time:4.22\tlog_likelihood:-638377.57\n    2019-01-17 12:31:12 INFO:AuthorTopicModel:[INIT] 7\telapsed_time:3.98\tlog_likelihood:-627653.05\n    2019-01-17 12:31:16 INFO:AuthorTopicModel:[INIT] 8\telapsed_time:3.85\tlog_likelihood:-620515.39\n    2019-01-17 12:31:20 INFO:AuthorTopicModel:[INIT] 9\telapsed_time:4.11\tlog_likelihood:-613980.95\n    2019-01-17 12:31:24 INFO:AuthorTopicModel:[INIT] 10\telapsed_time:4.09\tlog_likelihood:-609679.92\n    2019-01-17 12:31:29 INFO:AuthorTopicModel:[INIT] 11\telapsed_time:4.15\tlog_likelihood:-605891.41\n    2019-01-17 12:31:33 INFO:AuthorTopicModel:[INIT] 12\telapsed_time:4.09\tlog_likelihood:-603119.40\n    2019-01-17 12:31:36 INFO:AuthorTopicModel:[INIT] 13\telapsed_time:3.72\tlog_likelihood:-600996.65\n    2019-01-17 12:31:40 INFO:AuthorTopicModel:[INIT] 14\telapsed_time:3.76\tlog_likelihood:-597663.51\n    2019-01-17 12:31:44 INFO:AuthorTopicModel:[INIT] 15\telapsed_time:4.13\tlog_likelihood:-595624.43\n    2019-01-17 12:31:48 INFO:AuthorTopicModel:[INIT] 16\telapsed_time:3.97\tlog_likelihood:-593554.38\n    2019-01-17 12:31:52 INFO:AuthorTopicModel:[INIT] 17\telapsed_time:3.93\tlog_likelihood:-591764.44\n    2019-01-17 12:31:56 INFO:AuthorTopicModel:[INIT] 18\telapsed_time:3.96\tlog_likelihood:-592220.90\n    2019-01-17 12:32:00 INFO:AuthorTopicModel:[INIT] 19\telapsed_time:4.07\tlog_likelihood:-590981.77\n    2019-01-17 12:32:04 INFO:AuthorTopicModel:[INIT] 20\telapsed_time:3.93\tlog_likelihood:-590025.87\n    2019-01-17 12:32:08 INFO:AuthorTopicModel:[INIT] 21\telapsed_time:4.25\tlog_likelihood:-588941.28\n    2019-01-17 12:32:12 INFO:AuthorTopicModel:[INIT] 22\telapsed_time:3.84\tlog_likelihood:-588545.22\n    2019-01-17 12:32:16 INFO:AuthorTopicModel:[INIT] 23\telapsed_time:3.76\tlog_likelihood:-587117.20\n    2019-01-17 12:32:20 INFO:AuthorTopicModel:[INIT] 24\telapsed_time:4.26\tlog_likelihood:-586218.23\n    2019-01-17 12:32:25 INFO:AuthorTopicModel:[INIT] 25\telapsed_time:4.69\tlog_likelihood:-585542.73\n    2019-01-17 12:32:30 INFO:AuthorTopicModel:[INIT] 26\telapsed_time:5.08\tlog_likelihood:-584895.95\n    2019-01-17 12:32:35 INFO:AuthorTopicModel:[INIT] 27\telapsed_time:4.43\tlog_likelihood:-583176.24\n    2019-01-17 12:32:38 INFO:AuthorTopicModel:[INIT] 28\telapsed_time:3.74\tlog_likelihood:-582331.76\n    2019-01-17 12:32:42 INFO:AuthorTopicModel:[INIT] 29\telapsed_time:4.21\tlog_likelihood:-581552.69\n    2019-01-17 12:32:47 INFO:AuthorTopicModel:[INIT] 30\telapsed_time:4.10\tlog_likelihood:-581681.61\n    2019-01-17 12:32:51 INFO:AuthorTopicModel:[INIT] 31\telapsed_time:3.95\tlog_likelihood:-580951.03\n    2019-01-17 12:32:54 INFO:AuthorTopicModel:[INIT] 32\telapsed_time:3.93\tlog_likelihood:-580535.88\n    2019-01-17 12:33:00 INFO:AuthorTopicModel:[INIT] 33\telapsed_time:5.05\tlog_likelihood:-579990.14\n    2019-01-17 12:33:04 INFO:AuthorTopicModel:[INIT] 34\telapsed_time:4.58\tlog_likelihood:-578482.94\n    2019-01-17 12:33:09 INFO:AuthorTopicModel:[INIT] 35\telapsed_time:4.49\tlog_likelihood:-578701.60\n    2019-01-17 12:33:13 INFO:AuthorTopicModel:[INIT] 36\telapsed_time:4.33\tlog_likelihood:-578560.24\n    2019-01-17 12:33:17 INFO:AuthorTopicModel:[INIT] 37\telapsed_time:4.04\tlog_likelihood:-578779.55\n    2019-01-17 12:33:21 INFO:AuthorTopicModel:[INIT] 38\telapsed_time:3.93\tlog_likelihood:-577578.12\n    2019-01-17 12:33:25 INFO:AuthorTopicModel:[INIT] 39\telapsed_time:4.27\tlog_likelihood:-577411.26\n    2019-01-17 12:33:29 INFO:AuthorTopicModel:[INIT] 40\telapsed_time:3.99\tlog_likelihood:-577824.52\n    2019-01-17 12:33:33 INFO:AuthorTopicModel:[INIT] 41\telapsed_time:4.09\tlog_likelihood:-576495.75\n    2019-01-17 12:33:37 INFO:AuthorTopicModel:[INIT] 42\telapsed_time:3.72\tlog_likelihood:-577012.47\n    2019-01-17 12:33:41 INFO:AuthorTopicModel:[INIT] 43\telapsed_time:3.99\tlog_likelihood:-576679.63\n    2019-01-17 12:33:45 INFO:AuthorTopicModel:[INIT] 44\telapsed_time:4.06\tlog_likelihood:-576703.22\n    2019-01-17 12:33:49 INFO:AuthorTopicModel:[INIT] 45\telapsed_time:3.98\tlog_likelihood:-575346.33\n    2019-01-17 12:33:53 INFO:AuthorTopicModel:[INIT] 46\telapsed_time:3.90\tlog_likelihood:-575704.89\n    2019-01-17 12:33:57 INFO:AuthorTopicModel:[INIT] 47\telapsed_time:3.83\tlog_likelihood:-575248.63\n    2019-01-17 12:34:01 INFO:AuthorTopicModel:[INIT] 48\telapsed_time:3.87\tlog_likelihood:-574341.08\n    2019-01-17 12:34:04 INFO:AuthorTopicModel:[INIT] 49\telapsed_time:3.67\tlog_likelihood:-574057.04\n\n\n### Building Reconstructed  API description \n\n\n```python\n\nauthors_assignment = model.author_assigned\n   \n#Building the Reconstructed Service Profile from the author assignment\nfor i in range(len(X_Train)):\n    for j in range(len(X_Train[i])):\n        rsp[authors_assignment[i][j]][X_Train[i][j]] = rsp[authors_assignment[i][j]][X_Train[i][j]] + 1\n        if(not word_id_dict_reverse[X_Train[i][j]] in rsp_dict[api_id_dict_reverse[authors_assignment[i][j]]]):\n            rsp_dict[api_id_dict_reverse[authors_assignment[i][j]]].append(word_id_dict_reverse[X_Train[i][j]])\n        \n\n```\n\n### Getting the predictions\n\n\n```python\npred_most_common =[]\npred_atm_dw = []\nlists = []\nfor test in X_Test:\n    pred_most_common.append(most_common_5)\n    df1= get_rspsims(test,5)      \n    df = df1.sort_values('Score', ascending=False)[:5]\n    pred_atm_dw.append(list(df['Author'].values))\n\n```\n\n### Result Evaluation MAP@5 and Recall@5\n\nThe most common apis is a good comparaison baseline as the most common APIs account for most of the API invocations. \n\nWe see that the reconstructed profile approach is outperforming the baseline ^^\n\n\n```python\nresults_map_most_common = (metrics.mapk(Y_Test,pred_most_common,5))\nresults_map_atm_dw = (metrics.mapk(Y_Test,pred_atm_dw,5))\n\nresults_recall_atm_dw = np.mean([recall(a,p) for (a,p) in zip(Y_Test,pred_atm_dw)] )\nresults_recall_most_common = np.mean([recall(a,p) for (a,p) in zip(Y_Test,pred_most_common)] )\n\nresults_df= pd.DataFrame([[results_map_atm_dw,results_map_most_common],\n                          [results_recall_atm_dw,results_recall_most_common]]\n                         ,columns=['RSP','Most_Common'])\nresults_df.index = ['MAP@5','R@5']\n\nresults_df.plot(kind='bar',rot=0)\n\nresults_df.head()\n```\n\n### Let's have a look at the new descrption of APIs\n\n\n```python\nkeys  = []\nvalues = []\nfor key,value in rsp_dict.items():\n    if(value!=[]):\n        keys.append(key)\n        values.append(' '.join(value))\n\nrsp_df= pd.DataFrame(keys,columns=['API'])\nrsp_df['rsp_description'] = values\nrsp_df.head(100)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>API</th>\n      <th>rsp_description</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>123-shop-pro</td>\n      <td>order</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>123contactform</td>\n      <td>paint famili member</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>18amail</td>\n      <td>kind</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1map</td>\n      <td>parent</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>23</td>\n      <td>view applic photo rotat anywher execut</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>30-boxes</td>\n      <td>ad list 30 box calendar</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>3dcart</td>\n      <td>provid txt support store entiti file import re...</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>411sync</td>\n      <td>latest cell phone real time use wap capabl sim...</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>43-places</td>\n      <td>offer solut</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>43things</td>\n      <td>book button</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>4shared</td>\n      <td>search allow</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>7digital</td>\n      <td>guess artist song clip pictur question randoml...</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>8coupons</td>\n      <td>includ deal daili map portion page sourc displ...</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>99designs-tasks</td>\n      <td>design assist applic</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>9flats</td>\n      <td>accommod 200 000 return short term apart</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>abebooks</td>\n      <td>addit</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>accuweather</td>\n      <td>weather zombi provid local forecast</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>active</td>\n      <td>sport social network googl api</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>activecom</td>\n      <td>event allow user base locat leverag activ com ...</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>actual-reports</td>\n      <td>busi label order minut code imag tabl</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>addthis-menu</td>\n      <td>plan brows thank com allow share content faceb...</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>aden-forshaws-cat</td>\n      <td>android app use com everi second anoth cat dis...</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>adility</td>\n      <td>food pet deal</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>adobe-air-bus-tour</td>\n      <td>bu applic map current locat adob air promot tour</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>aerisweather</td>\n      <td>weather center app data user need track gener ...</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>after-deadline</td>\n      <td>checker spell use googl visitor day</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>agendize-action</td>\n      <td>use</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>agentrank</td>\n      <td>wordpress plugin conveni display agent profil ...</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>aiderss</td>\n      <td>use googl reader extens bring filter view rank...</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>airbnb</td>\n      <td>busi rang world</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>70</th>\n      <td>artbeat</td>\n      <td>bubbl featur popular art design event tokyo bu...</td>\n    </tr>\n    <tr>\n      <th>71</th>\n      <td>artistdata</td>\n      <td>blog profession</td>\n    </tr>\n    <tr>\n      <th>72</th>\n      <td>att-app-messaging</td>\n      <td>messag protect person mobil data individu fami...</td>\n    </tr>\n    <tr>\n      <th>73</th>\n      <td>att-call-management</td>\n      <td>danger music turn new parent incom custom repl...</td>\n    </tr>\n    <tr>\n      <th>74</th>\n      <td>australian-business-number-lookup</td>\n      <td>onlin commun australian busi share inform bad ...</td>\n    </tr>\n    <tr>\n      <th>75</th>\n      <td>authentic-jobs</td>\n      <td>custom rss feed authent job filter type locat ...</td>\n    </tr>\n    <tr>\n      <th>76</th>\n      <td>authorizenet</td>\n      <td>retail product use fedex net track direct impo...</td>\n    </tr>\n    <tr>\n      <th>77</th>\n      <td>autodesk-freewheel</td>\n      <td>preview free</td>\n    </tr>\n    <tr>\n      <th>78</th>\n      <td>automattic-wordpress-widgets</td>\n      <td>creat valu</td>\n    </tr>\n    <tr>\n      <th>79</th>\n      <td>aviary-effects</td>\n      <td>night effect allow user appli varieti filter u...</td>\n    </tr>\n    <tr>\n      <th>80</th>\n      <td>aviary-suite</td>\n      <td>use</td>\n    </tr>\n    <tr>\n      <th>81</th>\n      <td>avvo</td>\n      <td>simpl android nativ applic lawyer unit state s...</td>\n    </tr>\n    <tr>\n      <th>82</th>\n      <td>awesm</td>\n      <td>applic associ document enter event viral</td>\n    </tr>\n    <tr>\n      <th>83</th>\n      <td>baby-names</td>\n      <td>look babi perfect list discov origin mean mash...</td>\n    </tr>\n    <tr>\n      <th>84</th>\n      <td>backpack</td>\n      <td>parti</td>\n    </tr>\n    <tr>\n      <th>85</th>\n      <td>backtweets</td>\n      <td>api monitor tweet competitor domain add url creat</td>\n    </tr>\n    <tr>\n      <th>86</th>\n      <td>backtype</td>\n      <td>twitter link domain monitor peopl post tweet url</td>\n    </tr>\n    <tr>\n      <th>87</th>\n      <td>baidu</td>\n      <td>manag space follow secur video</td>\n    </tr>\n    <tr>\n      <th>88</th>\n      <td>bandcamp</td>\n      <td>discoveri popul playlist artist discographi brows</td>\n    </tr>\n    <tr>\n      <th>89</th>\n      <td>bandsintown</td>\n      <td>mash</td>\n    </tr>\n    <tr>\n      <th>90</th>\n      <td>bank-russia-daily-info</td>\n      <td>mobil rate differ applic bank invest metal api...</td>\n    </tr>\n    <tr>\n      <th>91</th>\n      <td>bart</td>\n      <td>bu train area washington</td>\n    </tr>\n    <tr>\n      <th>92</th>\n      <td>basecamp</td>\n      <td>onlin invoic servic api use basecamp integr da...</td>\n    </tr>\n    <tr>\n      <th>93</th>\n      <td>batchbook</td>\n      <td>kind number record form 100 use data drawloop saa</td>\n    </tr>\n    <tr>\n      <th>94</th>\n      <td>bbc</td>\n      <td>delay creation bbc updat play aggreg filter ya...</td>\n    </tr>\n    <tr>\n      <th>95</th>\n      <td>bbc-music</td>\n      <td>convert day track event realtim sourc</td>\n    </tr>\n    <tr>\n      <th>96</th>\n      <td>bbc-nitro</td>\n      <td>map channel</td>\n    </tr>\n    <tr>\n      <th>97</th>\n      <td>beatport</td>\n      <td>new track help brows preview latest releas hou...</td>\n    </tr>\n    <tr>\n      <th>98</th>\n      <td>beebotte</td>\n      <td>simpl web app demo demonstr real time chat app...</td>\n    </tr>\n    <tr>\n      <th>99</th>\n      <td>behance</td>\n      <td>pop mobil applic allow user transform app idea...</td>\n    </tr>\n  </tbody>\n</table>\n<p>100 rows \u00d7 2 columns</p>\n</div>\n\n\n\n# Thank you for following \n\nI hope this was helpful, feel free to get in contact for more information and please share any suggestions/comments you have ^^\n\n#### Sources\n\nThe author topic model implementation was found in this [git](https://github.com/dongwookim-ml/python-topic-model)\n", "meta": {"hexsha": "15311d7ffe79df8a405ba9cb2faf90c10acbca71", "size": 549085, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Text Data -  API Prediction/API_Prediction.ipynb", "max_stars_repo_name": "marouanel/Data-Projects", "max_stars_repo_head_hexsha": "2e10225a1cd005f1d7c237516c56cb97a0135613", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Text Data -  API Prediction/API_Prediction.ipynb", "max_issues_repo_name": "marouanel/Data-Projects", "max_issues_repo_head_hexsha": "2e10225a1cd005f1d7c237516c56cb97a0135613", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Text Data -  API Prediction/API_Prediction.ipynb", "max_forks_repo_name": "marouanel/Data-Projects", "max_forks_repo_head_hexsha": "2e10225a1cd005f1d7c237516c56cb97a0135613", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 310.568438914, "max_line_length": 209400, "alphanum_fraction": 0.9046541064, "converted": true, "num_tokens": 11924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22815650216092537, "lm_q2_score": 0.06656918526680432, "lm_q1q2_score": 0.01518819246217668}}
{"text": "# Introduction\n\nSystems biology has been brought to the forefront of life science-based research and development. The need for systems analysis is made apparent by the inability of focused studies to explain whole network, cell, or organism behavior, and the availability of component data is what is fueling and enabling the effort. This massive amount of experimental information is a reflection of the complex molecular networks that underlie cellular functions. Reconstructed networks represent a common denominator in systems biology. They are used for data interpretation, comparing organism capabilities, and as the basis for computing their functional states. The companion book _Systems Biology: Properties of Reconstructed Networks_ details the topological features and assessment of functional states of biochemical reaction networks and how these features are represented by the stoichiometric matrix. In this book, we turn our attention to the kinetic properties of the reactions that make up a network. We will focus on the formulation of dynamic simulators and how they are used to generate and study the dynamic states of biological networks. \n\n## Biological Networks\nCells are made up of many chemical constituents that interact to form networks. Networks are fundamentally comprised of _nodes_ (the compounds) and the _links_ (chemical transformations) between them. The networks take on functional states that we wish to compute, and it is these physiological states that we observe. This text is focused on dynamic states of networks. \n\nThere are many different kinds of biological networks of interest, and they can be defined in different ways. One common way to define networks is based on a preconceived notion of what they do. Examples include metabolic, signaling, and regulatory networks, see Figure\u00a01.1. This approach is driven by a large body of literature that has grown around a particular cellular function. \n\n\n\n**Figure 1.1:** Three examples of networks that are defined by major function.  (a) Metabolism.  (b) Signaling. From Arisi, et al. BMC Neuroscience 2006  7(Suppl 1):S6 DOI:10.1186/1471-2202-7-S1-S6.  (c) Transcriptional regulatory networks. Image courtesy of Christopher Workman, Center for Biological Sequence Analysis, Technical University of Denmark.\n\n### Metabolic networks  \nMetabolism is ubiquitous in living cells and is involved in essentially all cellular functions. It has a long history - glycolysis was the first pathway elucidated in the 1930s - and is thus well-known in biochemical terms. Many of the enzymes and the corresponding genes have been discovered and characterized. Consequently, the development of dynamic models for metabolism is the most advanced at the present time. \n\nA few large-scale kinetic models of metabolic pathways and networks now exist. Genome-scale reconstructions of metabolic networks in many organisms are now available. With the current developments in metabolomics and fluxomics, there is a growing number of large-scale data sets becoming available. However, there are no genome-scale dynamic models yet available for metabolism. \n\n### Signaling networks  \nLiving cells have a large number of sensing mechanisms to measure and evaluate their environment. Bacteria have a surprising number of 2-component sensing systems that inform the organism about its nutritional, physical, and biological environment. Human cells in tissues have a large number of receptor systems in their membranes to which specific ligands bind, such as growth factors or chemokines. Such signaling influences the cellular fate processes: differentiation, replication, apoptosis, and migration. \n\nThe function of many of the signaling pathways that is initiated by a sensing event are presently known, and this knowledge is becoming more detailed. Only a handful of signaling networks are well-known, such as the JAK-STAT signaling network in lymphocytes and the Toll-like receptor system in macrophages. A growing number of dynamic models for individual signaling pathways are becoming available. \n\n### Regulatory networks  \nThere is a complex network of interactions that determine the DNA binding state of most proteins, which in turn determine if genes are being expressed. The RNA polymerase must bind to DNA, as do transcription factors and various other proteins. The details of these chemical interactions are being worked out, but in the absence of such information, most of the network models that have been built are discrete, stochastic, and logistical in nature. \n\nWith the rapid development of experimental methods that measure expression states, the binding sites, and their occupancy, we may soon see large-scale reconstructions of transcriptional regulatory networks. Once these are available, we can begin to plan the process to build models that will describe their dynamic states. \n\n### Unbiased network definitions  \nAn alternative way to define networks is based on chemical assays. Measuring all protein-protein interactions regardless of function provides one such example, see Figure\u00a01.2. Another example is a genome-wide measurement of the binding sites of a DNA-binding protein. This approach is driven by data-generating capabilities. It does not have an _a priori_ bias about the function of molecules being examined. \n\n\n\n**Figure 1.2:** Two examples of networks that are defined by high-throughput chemical assays. Images courtesy of Markus Herrgard.\n\n### Network reconstruction\nMetabolic networks are currently the best-characterized biological networks for which the most detailed reconstructions are available. The conceptual basis for their reconstruction has been reviewed (Reed, 2006), the workflows used detailed\u00a0(Feist, 2009) and a detailed standard operating procedure (SOP) is available\u00a0(Thiele, 2010). Some of the fundamental issues associated with the generation of dynamic models describing their functions have been articulated (Jashmidi, 2008). \n\nThere is much interest in reconstructing signaling and regulatory networks in a similar way. The prospects for reconstruction of large-scale signaling networks have been discussed (Hyduke, 2010). Given the development of new omics data types and other information, it seems likely that we will be able to obtain reliable reconstructions of these networks in the not too distant future. \n\n### Public information about pathways and networks  \nThere is a growing number of networks that underlie cellular functions that are being unraveled and reconstructed. Many publicly available sources contain this information, Table 1.1. We wish to study the dynamic states of such networks. To do so, we need to describe them in chemical detail and incorporate thermodynamic information and formulate a mathematical model. \n\n**Table 1.1:** Web resources that contain information about biological networks. Prepared by Jan Schellenberger.\n\n\n\n## Why Build and Study Models?\nMathematical modeling is practiced in various branches of science and engineering. The construction of models is a laborious and detailed task. It also involves the use of numerical and mathematical analysis, both of which are intellectually intensive and unforgiving undertakings. So why bother? \n\n### Bailey's five reasons  \nThe purpose and utility of model building has been succinctly summarized and discussed (Bailey, 1998): \n\n**1.** _\"To organize disparate information into a coherent whole.\"_ The information that goes into building models is often found in many different sources and the model-builder has to look for these, evaluate them, and put them in context. In our case, this comes down to building data matrices (see Table 1.3) and determining conditions of interest. \n\n**2.** _\"To think (and calculate) logically about what components and interactions are important in a complex system.\"_ Once the information has been gathered it can be mathematically represented in a self-consistent format. Once equations have been formulated using the information gathered and according to the laws of nature, the information can be mathematically interrogated. The interactions among the different components are evaluated and the behavior of the model is compared to experimental data. \n\n**3.** _\"To discover new strategies.\"_ Once a model has been assembled and studied, it often reveals relationships among its different components that were not previously known. Such observations often lead to new experiments, or form the basis for new designs. Further, when a model fails to reproduce the functions of the process being described, it means there is either something critical missing in the model or the data that led to its formulation is inconsistent. Such an occurrence then leads to a re-examination of the information that led to the model formulation. If no logical flaw is found, the analysis of the discrepancy may lead to new experiments to try to discover the missing information. \n\n**4.** _\"To make important corrections to the conventional wisdom.\"_ The properties of a model may differ from the governing thinking about process phenomena that is inferred based on qualitative reasoning. Good models may thus lead to important new conceptual developments. \n\n**5.** _\"To understand the essential qualitative features.\"_ Since a model accounts for all described interactions among its parts, it often leads to a better understanding of the whole. In the present case, such qualitative features relate to multi-scale analysis in time and an understanding of how multiple chemical events culminate in coherent physiological features. \n\n## Characterizing Dynamic States\nThe dynamic analysis of complex reaction networks involves the tracing of time-dependent changes of concentrations and reaction fluxes over time. The concentrations typically considered are those of metabolites, proteins, or other cellular constituents. There are three key characteristics of dynamics states that we mention here right at the outset, and they are described in more detail in Section\u00a02.1. \n\n### Time constants  \nDynamic states are characterized by change in time, thus the rate of change becomes the key consideration. The rate of change of a variable is characterized by a _time constant_. Typically, there is a broad spectrum of time constants found in biochemical reaction networks. This leads to time scale separation where events may be happening on the order of milliseconds all the way to hours, if not days. The determination of the spectrum of time constants is thus central to the analysis of network dynamics. \n\n### Aggregate variables  \nAn associated issue is the identification of the biochemical, and ultimately physiological, events that are unfolding on every time scale. Once identified, one begins to form _aggregate concentration variables,_ or _pooled variables_. These variables will be combinations of the original concentration variables. For example, two concentration variables may inter-convert rapidly, on the order of milliseconds, and thus on every time scale longer than milliseconds, these two concentrations will be \"connected.\" They can therefore be \"pooled\" together to form an aggregate variable. An example is given in Figure\u00a01.3.\n\nThe determination of such aggregate variables becomes an intricate mathematical problem. Once solved, it allows us to determine the _dynamic structure of a network_. In other words, we move hierarchically away from the original concentration variables to increasingly interlinked aggregate variables that ultimately culminate in the overall dynamic features of a network on slower time scales. Temporal decomposition therefore involves finding the time scale spectrum of a network and determining what moves on each one of these time scales. A network can then be studied on any one of these time scales. \n\n\n\n**Figure 1.3:** Time-scale hierarchy and the formation of aggregate variables in glycolysis.The 'pooling' process culminates in the formation of one pool (shown in a box at the bottom) that is filled by hexokinase (HK) and drained by ATPase. This pool represents the inventory of high energy phosphate bonds. From (Jashmidi, 2008).\n\n### Transitions  \nComplex networks can transition from one steady state (i.e., homeostatic state) to another. There are distinct types of transitions that characterize the dynamic states of a network. Transitions are analyzed by _bifurcation theory_. The most common bifurcations involve the emergence of _multiple steady states,_ _sustained oscillations,_ and _chaotic behavior_. Such dynamic features call for a yet more sophisticated mathematical treatment. Such changes in dynamic states have been called _creative functions,_ which in turn represent willful physiological changes in organism behavior. In this book, we will only encounter relatively simple types of such transitions. \n\n## 1.4 Formulating Dynamic Network Models\n### Approach  \nMechanistic kinetic models based on differential equations represent a _bottom-up approach_. This means that we identify all the detailed events in a network and systematically build it up in complexity by adding more and more new information about the components of a network and how they interact. A complementary approach to the analysis of a biochemical reaction network is a _top-down approach_ where one collects data and information about the state of the whole network at one time. This approach is not covered in this text but typically requires a Bayesian or Boolean analysis that represents causal or statistically-determined relationships between network components. The bottom-up approach requires a mechanistic understanding of component interactions. Both the top-down and bottom-up approaches are useful and complimentary in studying the dynamic states of networks. \n\n### Simplifying assumptions  \nKinetic models are typically formulated as a set of deterministic ordinary differential equations (ODEs). There are a number of important assumptions made in such formulations that often are not fully described and delineated. Five assumptions will be discussed here (Table\u00a01.2). \n\n**Table 1.2:** Assumptions used in the formulation of biological network models.\n\n\n\n**1.** Using deterministic equations to model biochemistry essentially implies a \"clockwork\" of functionality. However, this modeling assumption needs justification. There are three principal sources of variability in biological dynamics: internal thermal noise, changes in the environment, and cell-to-cell variation. Inside cells, all components experience thermal effects that result in _random molecular motion_. This process is, of course, one of molecular diffusion, called _Brownian motion_ with larger observable objects. The ordinary differential equation assumption involves taking an ensemble of molecules and averaging out the stochastic effects. In cases where there are very few molecules of a particular species inside a cell or a cellular compartment, this assumption may turn out to be erroneous. \n\n**2.** The finer architecture of cells is also typically not considered in kinetic models. Cells are highly structured down to the 100 nm length scale and are thus not homogeneous (see Figure\u00a01.4). Rapidly diffusing compounds, such as metabolites and ions, will distribute rapidly throughout the compartment and one can justifiably consider the concentration to be relatively uniform. However, with larger molecules whose diffusion is hindered and confined, one may have to consider their spatial location. Studying and describing cellular functions of the 100 nm length scale is likely to represent an interesting topic in systems biology as it unfolds. \n\n**3.** Another major assumption in most kinetic models is that of _constant volume_. Cells and cellular compartments typically have fluctuations in their volume. Treating variable volume turns out to be mathematically difficult. It is, therefore, often ignored. However, minor fluctuations in the volume of a cellular compartment may change all the concentrations in that compartment and therefore all kinetic and regulatory effects. \n\n**4.** Temperature is typically considered to be a constant. Larger organisms have the capability to control their temperature. Small organisms have a high surface to volume ratio making it hard to control heat flux at their periphery. Further, small cellular dimensions lead to rapid thermal diffusivity and a strong dependency on the thermal characteristics of the environment. Rate constants are normally a strong function of temperature, often described by Arrhenius' law. Thus, treating cells as isothermal systems is a simplification under which the kinetic properties are described by kinetic constants. \n\n**5.** All cells and cellular compartments must maintain electro-neutrality and therefore the exchange of any species in and out of a compartment or a cell must also obey electro-neutrality. Considering the charge of molecules and their pH dependence is yet another complicated mathematical subject and thus often ignored. Similarly, significant internal osmotic pressure must be balanced with that of the environment. Cells in tissues are in an isotonic environment, while single cellular organisms and cells in plants build rigid walls to maintain their integrity. \n\n\n\n**Figure 1.4:** The crowded state of the intracellular environment.Some of the physical characteristics are viscosity $(>100\\ \\mu_{H2O})$, osmotic pressure $(<150 atm)$, electrical gradients $(\\approx 300,000\\ V/cm)$, and a near crystalline state. \u00a9 David S.Goodsell 1999.\n\n### The dynamic mass balance equations  \nApplying these simplifying assumptions, we arrive at the dynamic mass balance equations as the starting point for modeling the dynamic states of biochemical reaction networks. The basic notion of a dynamic mass balance on a single compound, $x_i$, is shown in Figure 1.5. \n\n\n\n**Figure 1.5:** The dynamic mass balance on a single compound. (a) All the rates of formation and degradation of a compound $x_i$ (a graphical representation called a node map). (b) The corresponding dynamic mass balance equation that simply states that the rate of change of the concentrations $x_i$ is equal to the sum of the rates of formation minus the sum of the rates of degradation. This summation can be represented as an inner product between a row vector and the flux vector. This row vector becomes a row in the stoichiometric matrix in Eq. 1.1.\n\nThe combination of all the dynamic mass balances for all concentrations ($\\textbf{x}$)in a biochemical reaction network are given by a matrix equation: \n\n$$\\begin{equation} \\frac{d\\textbf{x}}{dt} = \\textbf{Sv}(\\textbf{x}) \\tag{1.1} \\end{equation}$$\n\nwhere $\\textbf{S}$ is the stoichiometric matrix, $\\textbf{v}$ is the vector of reaction fluxes $(v_j)$, and $\\textbf{x}$ is the vector of concentrations $(x_i)$. Equation\u00a01.1 will be the 'master' equation that will be used to describe network dynamics states in this book. \n\n### Alternative views  \n\nThere are a number of considerations that come with the differential equation formalism described in this book and in the vast majority of the research literature on this subject matter. Perhaps the most important issue is the treatment of cells as behaving deterministically and displaying continuous changes over time. It is possible, though, that cells ultimately will be viewed as essentially a _liquid crystalline state_ where transitions will be discreet from one state to the next, and not continuous. \n\n## The Basic Information is in a Matrix Format\nThe natural mathematical language for describing network states using dynamic mass balances is that of matrix algebra. In studying the dynamic states of networks, there are three fundamental matrices of interest: the stoichiometric, the gradient, and the Jacobian matrices. \n\n**Table 1.3:** Comparison of some of the attributes and properties of the stoichiometric and the gradient matrices. Adapted from\u00a0(Jashmidi, 2008).\n\n\n\n### The stoichiometric matrix  \nThe stoichiometric matrix, the properties of which are detailed in\u00a0(SB1), represents the reaction topology of a network. Every row in this matrix represents a compound (alternative states require multiple rows) and every column represents a link between compounds, or a chemical reaction. All the entries in this matrix are _stoichiometric coefficients_.  This matrix is \"knowable,\" since it is comprised of integers that have no error associated with them. The stoichiometric matrix is _genomically-derived_ and thus all members of a species or a biopopulation will have the same stoichiometric matrix.\n\nMathematically, the stoichiometric matrix has important features. It is a _sparse matrix,_ which means that few of its elements are non-zero. Typically, less than 1% of the elements of a genome-scale stoichiometric matrix are non-zero, and those non-zero elements are almost always 1 or -1. Occasionally there will be an entry of numerical value 2, which may represent the formation of a homodimer. The fact that all the elements of $\\textbf{S}$ are of the same order of magnitude makes it a convenient matrix to deal with from a numerical standpoint. The properties of the stoichiometric matrix have been extensively studied (SB1). \n\n### The gradient matrix   \nEach link in a reaction map has kinetic properties with which it is associated. The reaction rates that describe the kinetic properties are found in the rate laws, $\\textbf{v}(\\textbf{x}; \\textbf{k})$, where the vector $\\textbf{k}$ contains all the kinetic constants that appear in the rate laws. Ultimately, these properties represent time constants that tell us how quickly a link in a network will respond to the concentrations that are involved in that link. The reciprocal of these time constants are found in the gradient matrix, $\\textbf{G}$, whose elements are:\n\n$$\\begin{equation} g_{ij} = \\frac{\\partial v_i}{\\partial x_j}[\\text{time}^{-1}] \\tag{1.2} \\end{equation}$$\n\nThese constants may change from one member to the next in a biopopulation given the natural sequence diversity that exists. Therefore, the gradient matrix, is a _genetically-determined_ matrix. Two members of the population may have a different $\\textbf{G}$ matrix. This difference is especially important in cases where mutations exist that significantly change the kinetic properties of critical steps in the network and change its dynamic structure. Such changes in the properties of a single link in a network may change the properties of the entire network. \n\nMathematically speaking, $\\textbf{G}$ has several challenging features. Unlike the stoichiometric matrix, its numerical values vary over many orders of magnitude. Some links have very fast response times, while others have long response times. The entries of $\\textbf{G}$ are real numbers and therefore are not \"knowable.\" The values of $\\textbf{G}$ will always come with an error bar associated with the experimental method used to determine them. Sometimes only order-of-magnitude information about the numerical values of the entries in $\\textbf{G}$ is sufficient to allow us to determine the overall dynamic properties of a network. The matrix $\\textbf{G}$ has the same sparsity properties as the matrix $\\textbf{S}$. \n\n### The Jacobian matrix   \nThe Jacobian matrix, $\\textbf{J}$, is the matrix that characterizes network dynamics. It is a product of the stoichiometric matrix and the gradient matrix. The stoichiometric matrix gives us network structure, and the gradient matrix gives us kinetic parameters of the links in the network. The product of these two matrices gives us the network dynamics. \n\nThe three matrices described above are thus not independent. The Jacobian is given by \n\n$$\\begin{equation} \\textbf{J} = \\textbf{SG} \\tag{1.3} \\end{equation}$$\n\nThe properties of $\\textbf{S}$ and $\\textbf{G}$ are compared in Table\u00a01.3. \n\n## Summary\n* Large-scale biological networks that underlie various cellular functions can now be reconstructed from detailed data sets and published literature. \n\n* Mathematical models can be built to study the dynamic states of networks. These dynamic states are most often described by ordinary differential equations. \n\n* There are significant assumptions leading to an ordinary differential equations formalism to describe dynamic states. Most notably is the elimination of molecular noise, assuming volumes and temperature to be constant, and considering spatial structure to be insignificant. \n\n* Networks have dynamic states that are characterized by time constants, pooling of variables, and characteristic transitions. The basic dynamic properties of a network come down to analyzing the spectrum of time-scales associated with a network and how the concentrations move on these time-scales. \n\n* Sometimes the concentrations move in tandem at certain time-scales, leading to the formation of aggregate variables. This property is key to the hierarchical decomposition of networks and the understanding of how physiological functions are formed. \n\n* The data used to formulate models to describe dynamic states of networks is found in two matrices: the stoichiometric matrix, that is typically well-known, the gradient matrix, whose elements are harder to determine. \n\n* Dynamic states can be studied by simulation or mathematical analysis. This text is focused on the process of dynamic simulation and its uses. \n\n$\\tiny{\\text{\u00a9 B. \u00d8. Palsson 2011;}\\ \\text{This publication is in copyright.}\\\\ \\text{Subject to statutory exception and to the provisions of relevant collective licensing agreements,}\\\\ \\text{no reproduction of any part may take place without the written permission of Cambridge University Press.}}$\n", "meta": {"hexsha": "c91ac1c8d6f4320cc93c86b3b32f88ad03237d64", "size": 28537, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/education/sb2/chapters/sb2_chapter1.ipynb", "max_stars_repo_name": "SBRG/MASSpy", "max_stars_repo_head_hexsha": "1315c1d40be8feb8731c8143dbc9ba43bf8c78ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2020-07-13T00:48:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T15:42:15.000Z", "max_issues_repo_path": "docs/education/sb2/chapters/sb2_chapter1.ipynb", "max_issues_repo_name": "SBRG/MASSpy", "max_issues_repo_head_hexsha": "1315c1d40be8feb8731c8143dbc9ba43bf8c78ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2021-02-17T18:07:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-23T16:22:14.000Z", "max_forks_repo_path": "docs/education/sb2/chapters/sb2_chapter1.ipynb", "max_forks_repo_name": "SBRG/MASSpy", "max_forks_repo_head_hexsha": "1315c1d40be8feb8731c8143dbc9ba43bf8c78ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2020-01-15T00:48:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T07:01:17.000Z", "avg_line_length": 120.9194915254, "max_line_length": 1149, "alphanum_fraction": 0.7576479658, "converted": true, "num_tokens": 5037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2450850131323717, "lm_q2_score": 0.061875989183534374, "lm_q1q2_score": 0.01516487762162501}}
{"text": "<a href=\"https://colab.research.google.com/github/RajeevAtla/HTCS-ML-Team-B/blob/master/sentiment-analysis.ipynb\" target=\"_parent\"></a>\n\n# Building a Sentiment Classifier using Scikit-Learn\n\nAcknowledgement: This is derived from https://towardsdatascience.com/building-a-sentiment-classifier-using-scikit-learn-54c8e7c5d2f0. \n\n<center></center>\n<center><i>Image by AbsolutVision @ <a href=\"https://pixabay.com/ro/photos/smiley-emoticon-furie-sup%C4%83rat-2979107/\">pixabay.com</a></i></center>\n\n> &nbsp;&nbsp;&nbsp;&nbsp;**Sentiment analysis**, an important area in Natural Language Processing, is the process of automatically detecting affective states of text. Sentiment analysis is widely applied to voice-of-customer materials such as product reviews in online shopping websites like Amazon, movie reviews or social media. It can be just a basic task of classifying the polarity of a text as being positive/negative or it can go beyond polarity, looking at emotional states such as \"happy\", \"angry\", etc.\n\n&nbsp;&nbsp;&nbsp;&nbsp;Here we will build a classifier that is able to distinguish movie reviews as being either positive or negative. For that, we will use [Large Movie Review Dataset v1.0](http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz)<sup>(2)</sup> of IMDB movie reviews.\nThis dataset contains 50,000 movie reviews divided evenly into 25k train and 25k test. The labels are balanced between the two classes (positive and negative). Reviews with a score <= 4 out of 10 are labeled negative and those with score >= 7 out of 10 are labeled positive. Neutral reviews are not included in the labeled data. This dataset also contains unlabeled reviews for unsupervised learning; we will not use them here. There are no more than 30 reviews for a particular movie because the ratings of the same movie tend to be correlated. All reviews for a given movie are either in train or test set but not in both, in order to avoid test accuracy gain by memorizing movie-specific terms.\n\n\n\n## Data preprocessing\n\n&nbsp;&nbsp;&nbsp;&nbsp;After the dataset has been downloaded and extracted from archive we have to transform it into a more suitable form for feeding it into a machine learning model for training. We will start by combining all review data into 2 pandas Data Frames representing the train and test datasets, and then saving them as csv files: *imdb_train.csv* and *imdb_test.csv*.  \n\n&nbsp;&nbsp;&nbsp;&nbsp;The Data Frames will have the following form:  \n\n|text       |label      |\n|:---------:|:---------:|\n|review1    |0          |\n|review2    |1          |\n|review3    |1          |\n|.......    |...        |\n|reviewN    |0          |  \n\n&nbsp;&nbsp;&nbsp;&nbsp;where:  \n- review1, review2, ... = the actual text of movie review  \n- 0 = negative review  \n- 1 = positive review\n\n&nbsp;&nbsp;&nbsp;&nbsp;But machine learnng algorithms work only with numerical values. We can't just input the text itself into a machine learning model and have it learn from that. We have to, somehow, represent the text by numbers or vectors of numbers. One way of doing this is by using the **Bag-of-words** model<sup>(3)</sup>, in which a piece of text(often called a **document**) is represented by a vector of the counts of words from a vocabulary in that document. This model doesn't take into account grammar rules or word ordering; all it considers is the frequency of words. If we use the counts of each word independently we name this representation a **unigram**. In general, in a **n-gram** we take into account the counts of each combination of n words from the vocabulary that appears in a given document.  \n\n&nbsp;&nbsp;&nbsp;&nbsp;For example, consider these two documents:  \n<br>  \n<div style=\"font-family: monospace;\"><center><b>d1: \"I am learning\"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></center></div>  \n<div style=\"font-family: monospace;\"><center><b>d2: \"Machine learning is cool\"</b></center></div>  \n<br>\nThe vocabulary of all words encountered in these two sentences is: \n\n<br/>  \n<div style=\"font-family: monospace;\"><center><b>v: [ I, am, learning, machine, is, cool ]</b></center></div>   \n<br>\n&nbsp;&nbsp;&nbsp;&nbsp;The unigram representations of d1 and d2:  \n<br>  \n\n|unigram(d1)|I       |am      |learning|machine |is      |cool    |\n|:---------:|:------:|:------:|:------:|:------:|:------:|:------:|\n|           |1       |1       |1       |0       |0       |0       |  \n\n|unigram(d2)|I       |am      |learning|machine |is      |cool    |\n|:---------:|:------:|:------:|:------:|:------:|:------:|:------:|\n|           |0       |0       |1       |1       |1       |1       |\n  \n&nbsp;&nbsp;&nbsp;&nbsp;And, the bigrams of d1 and d2 are:\n  \n|bigram(d1) |I I     |I am    |I learning|...|machine am|machine learning|...|cool is|cool cool|\n|:---------:|:------:|:------:|:--------:|:-:|:--------:|:--------------:|:-:|:-----:|:-------:|\n|           |0       |1       |0         |...|0         |0               |...|0      |0        |  \n\n|bigram(d2) |I I     |I am    |I learning|...|machine am|machine learning|...|cool is|cool cool|\n|:---------:|:------:|:------:|:--------:|:-:|:--------:|:--------------:|:-:|:-----:|:-------:|\n|           |0       |0       |0         |...|0         |1               |...|0      |0        |\n\n&nbsp;&nbsp;&nbsp;&nbsp;Often, we can achieve slightly better results if instead of counts of words we use something called **term frequency times inverse document frequency** (or **tf-idf**). Maybe it sounds complicated, but it is not. Bear with me, I will explain this. The intuition behind this is the following. So, what's the problem of using just the frequency of terms inside a document? Although some terms may have a high frequency inside documents they may not be so relevant for describing a given document in which they appear. That's because those terms may also have a high frequency across the collection of all documents. For example, a collection of movie reviews may have terms specific to movies/cinematography that are present in almost all documents(they have a high **document frequency**). So, when we encounter those terms in a document this doesn't tell much about whether it is a positive or negative review. We need a way of relating **term frequency** (how frequent a term is inside a document) to **document frequency** (how frequent a term is across the whole collection of documents). That is:  \n  \n$$\\begin{align}\\frac{\\text{term frequency}}{\\text{document frequency}} &= \\text{term frequency} \\cdot \\frac{1}{\\text{document frequency}} \\\\ &= \\text{term frequency} \\cdot \\text{inverse document frequency} \\\\ &= \\text{tf} \\cdot \\text{idf}\\end{align}$$  \n  \n&nbsp;&nbsp;&nbsp;&nbsp;Now, there are more ways used to describe both term frequency and inverse document frequency. But the most common way is by putting them on a logarithmic scale:  \n  \n$$tf(t, d) = log(1+f_{t,d})$$  \n$$idf(t) = log(\\frac{1+N}{1+n_t})$$  \n  \n&nbsp;&nbsp;&nbsp;&nbsp;where:  \n$$\\begin{align}f_{t,d} &= \\text{count of term } \\textbf{t} \\text{ in document } \\textbf{d} \\\\  \nN &= \\text{total number of documents} \\\\  \nn_t &= \\text{number of documents that contain term } \\textbf{t}\\end{align}$$  \n  \n&nbsp;&nbsp;&nbsp;&nbsp;We added 1 in the first logarithm to avoid getting $-\\infty$ when $f_{t,d}$ is 0. In the second logarithm we added one fake document to avoid division by zero.\n\n&nbsp;&nbsp;&nbsp;&nbsp;Before we transform our data into vectors of counts or tf-idf values we should remove English **stopwords**<sup>(6)(7)</sup>. Stopwords are words that are very common in a language and are usually removed in the preprocessing stage of natural text-related tasks like sentiment analysis or search.\n\n&nbsp;&nbsp;&nbsp;&nbsp;Note that we should construct our vocabulary only based on the training set. When we will process the test data in order to make predictions we should use only the vocabulary constructed in the training phase, the rest of the words will be ignored.\n\n&nbsp;&nbsp;&nbsp;&nbsp;Now, let's create the data frames from the supplied csv files:\n\n\n```python\nimport pandas as pd\n```\n\n\n```python\n# Read in the training and test datasets from previously created csv files\n\nimdb_train = pd.read_csv('csv/imdb_train.csv')\nimdb_test = pd.read_csv('csv/imdb_test.csv')\n```\n\n\n```python\n# Display information and first few entries from the training and test datasets\n\npd.set_option('display.max_colwidth', None)\n\nprint (\"----- Training dataset Info:\")\nimdb_train.info(verbose=None, buf=None, max_cols=None, memory_usage=None, null_counts=None)\nprint (\"Training dataset Content:\")\nprint(imdb_train.iloc[:5])\n\nprint (\"\\n----- Test dataset Info:\")\nimdb_test.info(verbose=None, buf=None, max_cols=None, memory_usage=None, null_counts=None)\nprint (\"Test dataset Content:\")\nprint(imdb_test.iloc[:5])\n\n```\n\n    ----- Training dataset Info:\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 25000 entries, 0 to 24999\n    Data columns (total 2 columns):\n     #   Column  Non-Null Count  Dtype \n    ---  ------  --------------  ----- \n     0   text    25000 non-null  object\n     1   label   25000 non-null  int64 \n    dtypes: int64(1), object(1)\n    memory usage: 390.8+ KB\n    Training dataset Content:\n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        text  \\\n    0                                                                                                                                                                                                                                                                                                                                                                                                                                                          This is what I was expecting when star trek DS9 premiered. Not to slight DS9. That was a wonderful show in it's own right, however it never really gave the fans more of what they wanted. Enterprise is that show. While having a similarity to the original trek it differs enough to be original in it's own ways. It makes the ideas of exploration exciting to us again. And that was one of the primary ingredients that made the original so loved. Another ingredient to success was the relationships that evolved between the crew members. Viewers really cared deeply for the crew. Enterprise has much promise in this area as well. The chemistry between Bakula and Blalock seems very promising. While sexual tension in a show can often become a crutch, I feel the tensions on enterprise can lead to much more and say alot more than is typical. I think when we deal with such grand scale characters of different races or species even, we get some very interesting ideas and television. Also, we should note the performances, Blalock is very convincing as Vulcan T'pol and Bacula really has a whimsy and strength of character that delivers a great performance. The rest of the cast delivered good performances also. My only gripes are as follows. The theme. It's good it's different, but a little to light hearted for my liking. We need something a little more grand. Doesn't have to be orchestral. Maybe something with a little more electronic sound would suffice. And my one other complaint. They sell too many adds. They could fix this by selling less ads, or making all shows two parters. Otherwise we'll end up seeing the shows final act getting wrapped up way too quickly as was one of my complaints of Voyager.   \n    1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          This film reminded me so much of \"A History of Violence\" which pretended to be a close study of violence and violent behavior but ended up just being nothing short of a cheap action movie masquerading as some thinking film on violence. Dustin Hoffman and his new British bride move to a small English town and encounter endless harassment from the local drunks who do nothing but hang at the pub all day and make trouble. Don't these men have a job? Anyway, Dustin takes all he can take and by the end of the film he holds up in his house and fights off each one of the drunk attackers by such gruesome means as boiling whiskey poured over someone, feet being blown off by a shotgun and someones head getting caught in a bear trap. Funny that someone would have a need for such a large bear trap in a small British town except maybe put a mans head in it. Sam Peckinpah who made the \"Wild Bunch\" which also covered the topic of blood letting violence in which no one was spared. But it was done with style, and you believed it. Straw Dogs is not believable. First of all the location is wrong and does not work. Why place it in England? I would think maybe in some inner city location or a small town in the American South in the 1930's or something. Second it is not in my view ever really explained clearly why these men are so quick to violence except maybe they got drunk and felt a need to kill Hoffman and rape his wife. Sam Peckinpah missed the mark on this one.   \n    2                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         Theodore Rex is possibly the greatest cinematic experience of all time, and is certainly a milestone in human culture, civilization and artistic expression!! In this compelling intellectual masterpiece, Jonathan R. Betuel aligns himself with the great film makers of the 20th century, such as Francis Ford Copola, Martin Scorcese, Orson Welles and Roman Polanski. The special effects are nothing less than breathtaking, and make any work by Spielberg look trite and elementary. At the time of it's release, Theodore Rex was such a revolutionary gem that it raised the bar of film-making to levels never anticipated by film makers. The concept of making not just a motion picture featuring a dinosaur, but adapting an action packed, thrilling detective novel, co-staring a \"talking\" dinosaur with a post-modern name such as \"Theodore\", and an existential female police officer changed humanity as we know it. The world could never be the same after experiencing such magnificent beauty. Watching Theodore Rex is much akin to looking into the face of God and hearing Him say \"you are my most beloved creation.\" This is one of the few films that is simply TO DIE FOR!!!   \n    3                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Although I didn't like Stanley & Iris tremendously as a film, I did admire the acting. Jane Fonda and Robert De Niro are great in this movie. I haven't always been a fan of Fonda's work but here she is delicate and strong at the same time. De Niro has the ability to make every role he portrays into acting gold. He gives a great performance in this film and there is a great scene where he has to take his father to a home for elderly people because he can't care for him anymore that will break your heart. I wouldn't really recommend this film as a great cinematic entertainment, but I will say you won't see much bette acting anywhere.   \n    4  'De Grot' is a terrific Dutch thriller, based on the book written by Tim Krabb\u00e9. Another of his books, 'Het Gouden Ei' was made into the great Dutch mystery thriller called 'Spoorloos' ('The Vanishing') in 1988. This one is not as good as that thriller (although much better than the American remake also called 'The Vanishing') but there are times it comes close. Especially the opening moments are terrific. We see a man, later we learn his name is Egon Wagter (Fedja van Hu\u00eat), coming from a plane in Thailand. When he picks up his bags it is pretty clear that he is smuggling something across the border. These scenes are perfectly directed, photographed and acted. A kind of suspense is created that you would normally not have in an opening scene like this. Later we see how Egon makes his deal in Thailand with a woman, both stating that they have never done anything like this. From this point the movie is constantly flashback and flash-forward. We see how Egon, still as a child (here played by Erik van der Horst), befriends a guy named Axel (as a kid played by Benja Bruijning). We learn how they grew up as friends, sort of, and how Axel (as an adult played by Marcel Hensema) became a criminal. Egon in the meanwhile goes to college and settles with a woman. Around this time he sometimes meets Axel but does not really want anything to do with him. The movie is chronological in a way. It shows Egon and Axel as kids, than as students, young adults, and in their mid-thirties. But from time to time, like I said, the movie goes back to when they were kids and jumps forward again. Every time we see them as kids it explains something that happens when they are adults. Minor spoilers herein. The title means 'The Cave', and it is the cave that gives the movie its happy ending, although it is in fact not that happy. Like the beginning, the ending is terrific. The middle part of the movie is entertaining and in a way it distracts our attention of the first scenes, only to come back at that point in the end. It is the editing that gives the movie its happy ending, although we can say the dramatic ending is happy in a way as well.   \n    \n       label  \n    0      1  \n    1      0  \n    2      1  \n    3      1  \n    4      1  \n    \n    ----- Test dataset Info:\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 25000 entries, 0 to 24999\n    Data columns (total 2 columns):\n     #   Column  Non-Null Count  Dtype \n    ---  ------  --------------  ----- \n     0   text    25000 non-null  object\n     1   label   25000 non-null  int64 \n    dtypes: int64(1), object(1)\n    memory usage: 390.8+ KB\n    Test dataset Content:\n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         text  \\\n    0                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   Progeny is about a husband and wife who experience time loss while making love. Completely unaware of what this bizarre experience means they try to go on with their lives. The hubby begins questioning the bizarre event and gets help through a very annoying psychiatrist. He comes to believe that aliens are responsible for this lapse in time and that the unborn baby he once thought was his and his wife's actually belongs to the aliens. If ya ask me, this is a great scifi/horror story. Taking a highly questionable real-life scenario involving alien abduction and hybrid breeding is definite thumbs up from this guy. I love all things related to aliens and this story definitely delivered some good ideas. So if you also share an interest in things extraterrestrial, you should be pretty happy with Progeny. At least story-wise anyways. Unfortunately the movie overall is pretty average. With average acting by all actors. Yep, even by the consistently awesome Mr. Dourif, who still does deliver the best performance. Though the black head doctor, delivers his lines really well. There are a few points in the flick where some of the delivery is cringe or laugh worthy, which is fine in my book. I like them cheesy and this had a little bit of some nice stinky cheese, and I mean that in a good way. Anyways, with a less than stellar script you can't really blame all the actors. I especially didn't care for the Mother Hysteria the film went for. She wanted a baby so badly that she'd neglect and dismiss everything her loving husband (who's a doctor!!) said to her. It almost reached a point where you actually didn't care what happened to her. The Progeny is another flick by Brian Yuzna from the icky-sticky film, Society. Again he delivers some slimy effects, and again he delivers a pretty unique tale of horror. If you're into scifi/horror or are a fan of Dourif and or Yuzna films, there's no real reason not to check out this flick if you get the chance. A generous 7 outta 10.   \n    1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         This movie is very similar to Death Warrant with Jean-Claude Van Damme and also has some similarities to Island of Fire with Jackie Chan and I also heard that there is some other very similar action movies, but this film has a much better action than Death Warrant or even Island of Fire (that's right, the Jackie Chan's movie). Rarely American action movies has such a great action sequences, though there was many negative reviews on this film, it easily beats most of the action movies of that time who were more successful. There were many martial art's scenes, David Bradley was fast as Bruce Lee in this film and what else was good, that fighting scenes were much longer than in most of the American martial art's movies. The shoot-out scenes were similar with John Woo's movies, maybe not that good, but still very exiting. There was also many impressive explosions and one great chase scene. I've seen some other David Bradley's movies, but this one, yet is the best in terms of action. OK, this movie has some cheesy moments, but which movie hasn't? The acting was decent, Charles Napier was incredible and his character was real tough. Adam Clark who played Squid and Yuji Okumoto who played the main bad guy were also very good. Other actors acted pretty well too, though the acting isn't important in this type of movies. If you are action movies fan (I mean the real action movies fan, who really can appreciate the good action), than you must see this film.   \n    2                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       This is an excellent movie and I would recommend it to everyone. Mr. Drury's acting is top notch as it always is and he blends well with the other actors in the movie. Can't give away any of the suspense or drama found in the movie. Hell to pay is a must see movie!!! The plot was very suspenseful. I would watch this movie over and over again because it has all the elements of a great western movie. It was very authentic in how they displayed the components dealing with this movie which includes the guns, horses, and clothing. The soundtrack is enjoyable and adds flavor to the movie. James Drury has the right touch when picking out a movie to be involved with. This is a another winner for the western genre. !!!!!   \n    3  The 13th and last RKO Falcon film starts with the mutual injunction by Tom Conway as Tom Lawrence alias the Falcon and Ed Brophy as Goldie of \"No dames!\" whilst they prepare to go on vacation. While you're still wondering what they're going on vacation from as they hadn't had a job since the beginning of the 1st film in 1941 (with Sanders as Gay though and Jenkins as Goldie) they bump into a woman and get dragged into a seedy industrial espionage caper. They promise to help her when her uncle is murdered, by taking an envelope containing the details of a formula to make substitute industrial diamonds to his business colleague in Miami. Suspect everyone here except the cops here who are after Lawrence \u0096 and Goldie for the murder. To console himself Goldie keeps paraphrasing travel brochures: \"On the coldest day you can always enjoy the warmth of a nice cosy electric chair\" for one. Some nice languid atmospheric nightclub scenes rub shoulders with some especially bad behaviour from the baddies. Favourite bit: the dignified game of hide and seek/hunt the thimble the imperturbable and suave Lawrence has with the baddies on the sleeper train. Least favourite bit: the most embarrassing scene in the entire series in the alligator wrestling hut \u0096 definitely thrown in for the kids! All in all not the best in the series but yet another entertaining outing, with an overall satisfying plot and many episodes even in this that make me wish they could have gone on for just a few more years as Columbia did with Boston Blackie, although RKO were churning these out faster. Absolutely no sex, not much violence (in fact none at all by today's high standards), and positively no message all make this type of film anathema to serious people who can only regard movies as an art form that must depend on these three pillars. Three Diet Falcon's were made later with John Calvert in the title role, I don't mind them but could never bring myself to count them into the main series, which Tom Conway had made his own by this time. Sad also that it was all downhill after this for Conway, who moved into TV, voice overs and even played Norman Conquest in Park Plaza 605 rather well in 1953. He also developed serious eye and alcohol problems \u0096 I don't know if they were linked \u0096 wound up poverty stricken and after a spell in hospital in 1967 was found dead in his girlfriend's bed. For us folk that want to at least we still have his 10 entertaining Falcon's plus a number of other worthy, even classic RKO movies from 1942 to 1946 with which to remember him by.   \n    4                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        I LOVE Dr WHo SO much! I believe that David Tennant is the best Dr the show has ever had and Billie Piper the Best companion! I liked the way the Dr and Rose had such a connection and a great relationship and the Dr came close a few times to expressing his love for rose! It sadly came to an end after only 2 seasons. I will miss watching rose heaps and think that the show will not be the same without Rose! But David is still there to make me laugh and make me happy to watch him play this fantastic role! I rate this show 110% it is FANTASTIC! The graphics and monsters in this show are wonderful and every storyline is different but somewhat connected and i have actually learned somethings about love, the world and relationships from this show. Therefore it must be one of the most fantastic shows of all time!   \n    \n       label  \n    0      1  \n    1      1  \n    2      1  \n    3      1  \n    4      1  \n\n\n### Text vectorization\n\n&nbsp;&nbsp;&nbsp;&nbsp;Fortunately, for the text vectorization part all the hard work is already done in the Scikit-Learn classes `CountVectorizer`<sup>(8)</sup> and `TfidfTransformer`<sup>(5)</sup>. We will use these classes to transform our csv files into unigram and bigram matrices(using both counts and tf-idf values). (It turns out that if we only use a n-gram for a large n we don't get a good accuracy, we usually use all n-grams up to some n. So, when we say here bigrams we actually refer to uni+bigrams and when we say unigrams it's just unigrams.) Each row in those matrices will represent a document (review) in our dataset, and each column will represent values associated with each word in the vocabulary (in the case of unigrams) or values associated with each combination of maximum 2 words in the vocabulary (bigrams).  \n\n&nbsp;&nbsp;&nbsp;&nbsp;`CountVectorizer` has a parameter `ngram_range` which expects a tuple of size 2 that controls what n-grams to include. After we constructed a `CountVectorizer` object we should call `.fit()` method with the actual text as a parameter, in order for it to learn the required statistics of our collection of documents. Then, by calling `.transform()` method with our collection of documents it returns the matrix for the n-gram range specified. As the class name suggests, this matrix will contain just the counts. To obtain the tf-idf values, the class `TfidfTransformer` should be used. It has the `.fit()` and `.transform()` methods that are used in a similar way with those of `CountVectorizer`, but they take as input the counts matrix obtained in the previous step and `.transform()` will return a matrix with tf-idf values. We should use `.fit()` only on training data and then store these objects. When we want to evaluate the test score or whenever we want to make a prediction we should use these objects to transform the data before feeding it into our classifier.  \n\n&nbsp;&nbsp;&nbsp;&nbsp;Note that the matrices generated for our train or test data will be huge, and if we store them as normal numpy arrays they will not even fit into RAM. But most of the entries in these matrices will be zero. So, these Scikit-Learn classes are using Scipy sparse matrices<sup>(9)</sup> (`csr_matrix`<sup>(10)</sup> to be more exactly), which store just the non-zero entries and save a LOT of space.  \n\n&nbsp;&nbsp;&nbsp;&nbsp;We will use a linear classifier with stochastic gradient descent, `sklearn.linear_model.SGDClassifier`<sup>(11)</sup>, as our model. First we will generate and save our data in 4 forms: unigram and bigram matrix (with both counts and tf-idf values for each). Then we will train and evaluate our model for each these 4 data representations using `SGDClassifier` with the default parameters. After that, we choose the data representation which led to the best score and we will tune the hyper-parameters of our model with this data form using cross-validation in order to obtain the best results.\n\n\n```python\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\n```\n\n#### Unigram Counts\n\n\n```python\n# Create a unigram vectorizer and process the training set to generate a list of words. \n# Note that unigram processing is set via the ngram_range parameter\n\nunigram_vectorizer = CountVectorizer(ngram_range=(1, 1))\nunigram_vectorizer.fit(imdb_train['text'].values)\n```\n\n\n\n\n    CountVectorizer(analyzer='word', binary=False, decode_error='strict',\n                    dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',\n                    lowercase=True, max_df=1.0, max_features=None, min_df=1,\n                    ngram_range=(1, 1), preprocessor=None, stop_words=None,\n                    strip_accents=None, token_pattern='(?u)\\\\b\\\\w\\\\w+\\\\b',\n                    tokenizer=None, vocabulary=None)\n\n\n\n\n```python\n# Display the length and a few samples of the unigram vectorizer to show the words that have been extracted\n\nprint(\"Number of words found:\", len(unigram_vectorizer.get_feature_names()))\nprint(unigram_vectorizer.get_feature_names()[10000:10100])\nprint(unigram_vectorizer.get_feature_names()[50000:50100])\n```\n\n    Number of words found: 74849\n    ['b\u00eate', 'b\u00fbsu', 'b\u00fcrgermeister', 'c1', 'c3', 'c3p0', 'c3po', 'c4', 'c57', 'c__p', 'ca', 'caaaaaaaaaaaaaaaaaaaaaaligulaaaaaaaaaaaaaaaaaaaaaaa', 'caalling', 'caan', 'caas', 'cab', 'cabal', 'caballe', 'caballeros', 'caballo', 'cabals', 'cabana', 'cabanne', 'cabaret', 'cabarnet', 'cabbage', 'cabbages', 'cabbie', 'cabby', 'cabel', 'cabell', 'cabells', 'cabin', 'cabinet', 'cabinets', 'cabins', 'cabiria', 'cable', 'cables', 'cabo', 'cabot', 'cabr\u00f3n', 'cabs', 'caca', 'caccia', 'cache', 'cachet', 'cacho', 'cack', 'cackle', 'cackles', 'cackling', 'caco', 'cacophonist', 'cacophonous', 'cacophony', 'cacoyanis', 'cacoyannis', 'cacti', 'cactus', 'cactuses', 'cad', 'cada', 'cadaver', 'cadaverous', 'cadavers', 'cadavra', 'cadby', 'caddie', 'caddy', 'caddyshack', 'cadena', 'cadence', 'cadences', 'cadet', 'cadets', 'cadfile', 'cadilac', 'cadillac', 'cadillacs', 'cadmus', 'cadre', 'cads', 'caduta', 'cady', 'caesar', 'caesars', 'caeser', 'caetano', 'cafe', 'cafes', 'cafeteria', 'caffari', 'caffeinated', 'caffeine', 'cafferty', 'caffey', 'caf\u00e9', 'caf\u00e9s', 'cage']\n    ['pincher', 'pinchers', 'pinches', 'pinching', 'pinchot', 'pinciotti', 'pine', 'pineal', 'pineapple', 'pineapples', 'pines', 'pinet', 'pinetrees', 'pineyro', 'pinfall', 'pinfold', 'ping', 'pingo', 'pinhead', 'pinheads', 'pinho', 'pining', 'pinjar', 'pink', 'pinkerton', 'pinkett', 'pinkie', 'pinkins', 'pinkish', 'pinko', 'pinks', 'pinku', 'pinkus', 'pinky', 'pinnacle', 'pinnacles', 'pinned', 'pinning', 'pinnings', 'pinnochio', 'pinnocioesque', 'pino', 'pinocchio', 'pinochet', 'pinochets', 'pinoy', 'pinpoint', 'pinpoints', 'pins', 'pinsent', 'pint', 'pinta', 'pinter', 'pintilie', 'pinto', 'pintos', 'pints', 'pinup', 'pioneer', 'pioneered', 'pioneering', 'pioneers', 'piotr', 'pious', 'piovani', 'pip', 'pipe', 'piped', 'pipedream', 'pipeline', 'piper', 'pipers', 'pipes', 'piping', 'pippi', 'pippin', 'pipsqueak', 'piquant', 'piquantly', 'pique', 'piqued', 'piquer', 'piquor', 'piracy', 'pirahna', 'piranha', 'piranhas', 'pirate', 'pirated', 'piraters', 'pirates', 'pirotess', 'pirouette', 'pirouettes', 'pirouetting', 'pirovitch', 'pirro', 'pis', 'pisa', 'pisana']\n\n\n\n```python\n# Now process the training dataset to get a count of the words extracted earlier\n\nX_train_unigram = unigram_vectorizer.transform(imdb_train['text'].values)\n```\n\n\n```python\n# Display the attributes the word count matrix; notice it is huge with 25000 rows since we have 25000 entries\n# in the training dataset and 74849 columns since we saw above that we have a vocabulary of 74849 words\n\nprint(repr(X_train_unigram))\n```\n\n    <25000x74849 sparse matrix of type '<class 'numpy.int64'>'\n    \twith 3431196 stored elements in Compressed Sparse Row format>\n\n\n#### Unigram Tf-Idf\n\n\n```python\n# Create a unigram tf-idf vectorizer and load the training set using the word count matrix from earlier\n\nunigram_tf_idf_transformer = TfidfTransformer()\nunigram_tf_idf_transformer.fit(X_train_unigram)\n```\n\n\n\n\n    TfidfTransformer(norm='l2', smooth_idf=True, sublinear_tf=False, use_idf=True)\n\n\n\n\n```python\n# Now calculate the unigram tf-idf statistics\n\nX_train_unigram_tf_idf = unigram_tf_idf_transformer.transform(X_train_unigram)\n```\n\n\n```python\n# Display the attributes the unigram tf-idf matrix; it should be the same size as the unigram matrix above\n\nprint(repr(X_train_unigram_tf_idf))\n```\n\n    <25000x74849 sparse matrix of type '<class 'numpy.float64'>'\n    \twith 3431196 stored elements in Compressed Sparse Row format>\n\n\n#### Bigram Counts\n\n\n```python\n# Create a bigram vectorizer and process the training set to generate a list of bigrams. \n# Note that bigram processing is set via the ngram_range parameter and so includes unigrams and bigrams\n\nbigram_vectorizer = CountVectorizer(ngram_range=(1, 2))\nbigram_vectorizer.fit(imdb_train['text'].values)\n```\n\n\n\n\n    CountVectorizer(analyzer='word', binary=False, decode_error='strict',\n                    dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',\n                    lowercase=True, max_df=1.0, max_features=None, min_df=1,\n                    ngram_range=(1, 2), preprocessor=None, stop_words=None,\n                    strip_accents=None, token_pattern='(?u)\\\\b\\\\w\\\\w+\\\\b',\n                    tokenizer=None, vocabulary=None)\n\n\n\n\n```python\n# Display the length and a few samples of the bigram vectorizer to show the bigrams that have been extracted\n\nprint(\"Number of bigrams found:\", len(bigram_vectorizer.get_feature_names()))\nprint(bigram_vectorizer.get_feature_names()[10000:10100])\nprint(bigram_vectorizer.get_feature_names()[50000:50100])\n```\n\n    Number of bigrams found: 1520266\n    ['3am but', '3am invesment', '3am it', '3am taped', '3bs', '3bs who', '3d', '3d adventure', '3d although', '3d and', '3d animated', '3d animation', '3d animations', '3d animators', '3d artists', '3d assante', '3d bird', '3d bore', '3d capabilities', '3d cg', '3d cgi', '3d character', '3d companies', '3d computer', '3d dept', '3d disgrace', '3d effect', '3d effects', '3d element', '3d ending', '3d environment', '3d especially', '3d feel', '3d game', '3d games', '3d glasses', '3d grafics', '3d graphics', '3d gravity', '3d had', '3d imax', '3d in', '3d it', '3d just', '3d mario', '3d models', '3d movie', '3d movies', '3d panoramic', '3d plat', '3d probably', '3d programs', '3d sequence', '3d shoot', '3d shooter', '3d shooters', '3d special', '3d splatter', '3d technology', '3d that', '3d trust', '3d was', '3d wave', '3d well', '3d which', '3d with', '3d world', '3d wow', '3dvd', '3dvd collection', '3k', '3k all', '3k attack', '3k but', '3k if', '3k it', '3k not', '3lbs', '3lbs is', '3m', '3m to', '3mins', '3mins jack', '3p', '3p felt', '3p uses', '3p wasn', '3p0', '3p0 r2', '3pm', '3pm and', '3po', '3po and', '3po frank', '3po mind', '3rd', '3rd 4th', '3rd act', '3rd and', '3rd annual']\n    ['allen radiation', 'allen randall', 'allen really', 'allen reprises', 'allen reprising', 'allen retains', 'allen retired', 'allen rivkin', 'allen screen', 'allen scripts', 'allen second', 'allen seems', 'allen sees', 'allen set', 'allen she', 'allen should', 'allen showed', 'allen shows', 'allen since', 'allen slowly', 'allen small', 'allen smithee', 'allen soule', 'allen starrer', 'allen stereotypical', 'allen still', 'allen straight', 'allen stuff', 'allen stuttering', 'allen style', 'allen such', 'allen surprisingly', 'allen surrogate', 'allen take', 'allen technique', 'allen tells', 'allen the', 'allen they', 'allen think', 'allen this', 'allen ticks', 'allen to', 'allen treat', 'allen waking', 'allen wannabe', 'allen warning', 'allen was', 'allen we', 'allen when', 'allen whining', 'allen who', 'allen will', 'allen williams', 'allen with', 'allen work', 'allen would', 'allen writes', 'allen writing', 'allen yes', 'allen you', 'allen young', 'allende', 'allende and', 'allende author', 'allende book', 'allende characters', 'allende has', 'allende killed', 'allende magical', 'allende not', 'allende novel', 'allende overthrown', 'allende should', 'allende was', 'allende who', 'allens', 'allens stuff', 'allergic', 'allergic are', 'allergic reaction', 'allergic reactions', 'allergic to', 'allergies', 'allergies kept', 'allergy', 'allergy senator', 'allergy to', 'alles', 'alles action', 'alleviate', 'alleviate her', 'alleviate pain', 'alleviate the', 'alleviate their', 'alleviate visual', 'alley', 'alley 1912', 'alley about', 'alley acting', 'alley again']\n\n\n\n```python\n# Now generate bigram statistics on the training set\n\nX_train_bigram = bigram_vectorizer.transform(imdb_train['text'].values)\n```\n\n\n```python\n# Display the attributes the bigram count matrix; notice it is really huge with 25000 rows since we have 25000 entries\n# in the training dataset and 1520266 columns since we saw above that we have 1520266 bigrams\n\nprint(repr(X_train_bigram))\n```\n\n    <25000x1520266 sparse matrix of type '<class 'numpy.int64'>'\n    \twith 8689547 stored elements in Compressed Sparse Row format>\n\n\n#### Bigram Tf-Idf\n\n\n```python\n# Create a bigram tf-idf vectorizer and load the training set using the bigram count matrix from earlier\n\nbigram_tf_idf_transformer = TfidfTransformer()\nbigram_tf_idf_transformer.fit(X_train_bigram)\n```\n\n\n\n\n    TfidfTransformer(norm='l2', smooth_idf=True, sublinear_tf=False, use_idf=True)\n\n\n\n\n```python\n# Now calculate the bigram tf-idf statistics\n\nX_train_bigram_tf_idf = bigram_tf_idf_transformer.transform(X_train_bigram)\n```\n\n\n```python\n# Display the attributes the bigram tf-idf matrix; it should be the same size as the bigram matrix above\n\nprint(repr(X_train_bigram_tf_idf))\n```\n\n    <25000x1520266 sparse matrix of type '<class 'numpy.float64'>'\n    \twith 8689547 stored elements in Compressed Sparse Row format>\n\n\n### Trigram Counts\n\n\n```python\n# Create a trigram vectorizer and process the training set to generate a list of words. \n# Note that unigram processing is set via the ngram_range parameter\n\ntrigram_vectorizer = CountVectorizer(ngram_range=(1, 3))\ntrigram_vectorizer.fit(imdb_train['text'].values)\n```\n\n\n\n\n    CountVectorizer(analyzer='word', binary=False, decode_error='strict',\n                    dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',\n                    lowercase=True, max_df=1.0, max_features=None, min_df=1,\n                    ngram_range=(1, 3), preprocessor=None, stop_words=None,\n                    strip_accents=None, token_pattern='(?u)\\\\b\\\\w\\\\w+\\\\b',\n                    tokenizer=None, vocabulary=None)\n\n\n\n\n```python\n# Display the length and a few samples of the trigram vectorizer to show the words that have been extracted\n\nprint(\"Number of words found:\", len(unigram_vectorizer.get_feature_names()))\nprint(trigram_vectorizer.get_feature_names()[10000:10100])\nprint(trigram_vectorizer.get_feature_names()[50000:50100])\n```\n\n    Number of words found: 74849\n    ['1938 when', '1938 when happen', '1938 when hitler', '1938 with', '1938 with frederic', '1938 year', '1938 year in', '1939', '1939 13', '1939 13 tough', '1939 1942', '1939 1942 desert', '1939 1944', '1939 1944 via', '1939 40', '1939 40 and', '1939 45', '1939 45 there', '1939 and', '1939 and as', '1939 and compare', '1939 and gone', '1939 and he', '1939 and tells', '1939 and that', '1939 and the', '1939 and then', '1939 as', '1939 as seen', '1939 as someone', '1939 behind', '1939 behind the', '1939 buchanan', '1939 buchanan holds', '1939 but', '1939 but probably', '1939 but whose', '1939 by', '1939 by the', '1939 charlie', '1939 charlie who', '1939 despite', '1939 despite the', '1939 distant', '1939 distant war', '1939 douglas', '1939 douglas plays', '1939 england', '1939 england as', '1939 eugene', '1939 eugene palette', '1939 even', '1939 even more', '1939 filled', '1939 filled with', '1939 film', '1939 film from', '1939 film gunga', '1939 film tried', '1939 first', '1939 first and', '1939 fringe', '1939 fringe benefit', '1939 gwtw', '1939 gwtw he', '1939 highly', '1939 highly recommended', '1939 hitler', '1939 hitler took', '1939 in', '1939 in that', '1939 is', '1939 is based', '1939 is lackadaisical', '1939 is universally', '1939 it', '1939 it has', '1939 it will', '1939 its', '1939 its different', '1939 leaves', '1939 leaves about', '1939 may', '1939 may 1940', '1939 military', '1939 military swashbuckler', '1939 moved', '1939 moved to', '1939 mystery', '1939 mystery comedy', '1939 needless', '1939 needless to', '1939 now', '1939 now the', '1939 one', '1939 one of', '1939 out', '1939 out of', '1939 release', '1939 release but']\n    ['about vampire', 'about vampire bats', 'about vampire vs', 'about vampire wars', 'about vampires', 'about vampires aliens', 'about vampires and', 'about vampires but', 'about vampires of', 'about vampires returning', 'about vampires she', 'about vampires that', 'about vampires vampires', 'about vampires with', 'about vansishing', 'about vansishing point', 'about variety', 'about variety of', 'about various', 'about various 1994', 'about various characters', 'about various obvious', 'about various people', 'about various sex', 'about various theories', 'about vast', 'about vast array', 'about vd', 'about vd scrotum', 'about ve', 'about ve feeling', 'about ve never', 'about venezuela', 'about venezuela it', 'about venezuela or', 'about venezuelan', 'about venezuelan civilian', 'about venezuelan politics', 'about vengeance', 'about vengeance for', 'about verhoeven', 'about verhoeven film', 'about very', 'about very awkward', 'about very briefly', 'about very charismatic', 'about very clever', 'about very important', 'about very little', 'about very random', 'about very real', 'about very sad', 'about very sexy', 'about very unusual', 'about very very', 'about very vigilant', 'about vibrant', 'about vibrant community', 'about vibrant young', 'about vic', 'about vic who', 'about vick', 'about vick world', 'about vicky', 'about vicky and', 'about victorian', 'about victorian era', 'about viennese', 'about viennese people', 'about vietnam', 'about vietnam and', 'about vietnam or', 'about vietnam vet', 'about vietnam vets', 'about viewers', 'about viewers that', 'about viewing', 'about viewing her', 'about viewings', 'about viewings over', 'about views', 'about views of', 'about vigilantism', 'about vigilantism in', 'about viking', 'about viking has', 'about viking warlord', 'about village', 'about village that', 'about villages', 'about villages with', 'about violence', 'about violence in', 'about violent', 'about violent backlash', 'about violent crimes', 'about violent game', 'about violent mayhem', 'about virginia', 'about virginia anderson']\n\n\n\n```python\n# Now process the training dataset to get a count of the words extracted earlier\n\nX_train_trigram = trigram_vectorizer.transform(imdb_train['text'].values)\n```\n\n### Trigram Tf-Idf\n\n\n```python\ntrigram_tf_idf_transformer = TfidfTransformer()\ntrigram_tf_idf_transformer.fit(X_train_trigram)\n```\n\n\n\n\n    TfidfTransformer(norm='l2', smooth_idf=True, sublinear_tf=False, use_idf=True)\n\n\n\n\n```python\n# Now calculate the trigram tf-idf statistics\n\nX_train_trigram_tf_idf = trigram_tf_idf_transformer.transform(X_train_trigram)\n```\n\n\n```python\n# Display the attributes the trigram tf-idf matrix; it should be the same size as the trigram matrix above\n\nprint(repr(X_train_trigram_tf_idf))\n```\n\n    <25000x5181124 sparse matrix of type '<class 'numpy.float64'>'\n    \twith 14166465 stored elements in Compressed Sparse Row format>\n\n\n### Try the four different data formats (unigram, bigram with and without tf_idf) on the training set and pick the best\n\n&nbsp;&nbsp;&nbsp;&nbsp;Now, for each data form we split it into train & validation sets, train a `SGDClassifier` and output the score.\n\n\n```python\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.model_selection import train_test_split\nfrom scipy.sparse import csr_matrix\nfrom sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom typing import Tuple\n```\n\n\n```python\n# Helper function to display confusion matrix\n\ndef display_confusion_matrix(y_true, y_pred) -> None:\n    cf_matrix = confusion_matrix(y_true, y_pred)\n    group_names = ['True Neg','False Pos','False Neg','True Pos']\n    group_counts = [\"{0:0.0f}\".format(value) for value in cf_matrix.flatten()]\n    group_percentages = [\"{0:.2%}\".format(value) for value in cf_matrix.flatten()/np.sum(cf_matrix)]\n    labels = [f\"{v1}\\n{v2}\\n{v3}\" for v1, v2, v3 in zip(group_names,group_counts,group_percentages)]\n    labels = np.asarray(labels).reshape(2,2)\n    sns.heatmap(cf_matrix, annot=labels, fmt='', cmap='coolwarm')\n    plt.show()\n    \n```\n\n\n```python\ndef train_and_show_scores(X: csr_matrix, y: np.array, title: str) -> Tuple[float, float]:\n    X_train, X_valid, y_train, y_valid = train_test_split(\n        X, y, train_size=0.75, stratify=y\n    )\n\n    clf = SGDClassifier()\n    clf.fit(X_train, y_train)\n    train_score = clf.score(X_train, y_train)\n    valid_score = clf.score(X_valid, y_valid)\n    print(f'{title}\\nTrain score: {round(train_score, 2)} ; Validation score: {round(valid_score, 2)}')\n    \n    train_pred = clf.predict(X_train)\n    valid_pred = clf.predict(X_valid)\n    print(f'Train precision: {round(precision_score(y_train, train_pred), 2)} ; Validation precision: {round(precision_score(y_valid, valid_pred), 2)}')\n    print(f'Train recall: {round(recall_score(y_train, train_pred), 2)} ; Validation recall: {round(recall_score(y_valid, valid_pred), 2)}')\n    print(f'Train F1: {round(f1_score(y_train, train_pred), 2)} ; Validation F1: {round(f1_score(y_valid, valid_pred), 2)}')\n    print(\"Train Confusion Matrix: \")\n    print(confusion_matrix(y_train, train_pred))\n    display_confusion_matrix(y_train, train_pred)\n    print(\"Validation Confusion Matrix: \")\n    print(confusion_matrix(y_valid, valid_pred))\n    display_confusion_matrix(y_valid, valid_pred)\n    print(\"\\n\")\n    \n    return train_score, valid_score, clf\n```\n\n\n```python\ny_train = imdb_train['label'].values\n```\n\n\n```python\nuc_train_score, uc_valid_score, uc_clf = train_and_show_scores(X_train_unigram, y_train, '----- Unigram Counts -----')\nutfidf_train_score, utfidf_valid_score, utfidf_clf = train_and_show_scores(X_train_unigram_tf_idf, y_train, '----- Unigram Tf-Idf -----')\nbc_train_score, bc_valid_score, bc_clf = train_and_show_scores(X_train_bigram, y_train, '----- Bigram Counts -----')\nbtfidf_train_score, btfidf_valid_score, btfidf_clf = train_and_show_scores(X_train_bigram_tf_idf, y_train, '----- Bigram Tf-Idf -----')\ntc_train_score, tc_valid_score, tc_clf = train_and_show_scores(X_train_trigram, y_train, '----- Trigram Counts -----')\nttfidf_train_score, ttfidf_valid_score, ttfidf_clf = train_and_show_scores(X_train_trigram_tf_idf, y_train, '----- Trigram Tf-Idf -----')\n```\n\n\n```python\n# Display the previously derived scores for the four scenarios\n\nsns.set_style(\"whitegrid\", {'grid.linestyle': '--'})\n\nprint (\"Training score for the four approaches:\")\nax1 = sns.barplot(\n    x= ['Unigram Count', 'Unigram tf-idf', 'Bigram Count', 'Bigram tf-idf'],\n    y= [uc_train_score, utfidf_train_score, bc_train_score, btfidf_train_score])\nax1.set(ylim=(0.8, 1.0))\nplt.show()\n\nprint (\"Validation score for the four approaches:\")\nax2 = sns.barplot(\n    x= ['Unigram Count', 'Unigram tf-idf', 'Bigram Count', 'Bigram tf-idf'],\n    y= [uc_valid_score, utfidf_valid_score, bc_valid_score, btfidf_valid_score])\nax2.set(ylim=(0.8, 1.0))\nplt.show()\n```\n\n&nbsp;&nbsp;&nbsp;&nbsp;The best data form seems to be **bigram with tf-idf** as it gets the highest validation accuracy: **0.9**; so we will choose it as our preferred approach.\n\n### Testing model\n\n\n```python\n# Transform the test data set into the bigram tf-idf format\n\nX_test = bigram_vectorizer.transform(imdb_test['text'].values)\nX_test = bigram_tf_idf_transformer.transform(X_test)\ny_test = imdb_test['label'].values\n```\n\n\n```python\n# Now evaluate the test data using the previously trained bigram tf-idf classifier\n\nclf = btfidf_clf\nscore = clf.score(X_test, y_test)\n\nprint(f'Score: {round(score, 4)}')\n\ntest_pred = clf.predict(X_test)\nprint(f'Test precision: {round(precision_score(y_test, test_pred), 4)}')\nprint(f'Test recall: {round(recall_score(y_test, test_pred), 4)}')\nprint(f'Test F1: {round(f1_score(y_test, test_pred), 4)}')\nprint(\"Test Confusion Matrix: \")\nprint(confusion_matrix(y_test, test_pred))\ndisplay_confusion_matrix(y_test, test_pred)\nprint(\"\\n\")\n```\n\n&nbsp;&nbsp;&nbsp;&nbsp;And we got almost 90% test accuracy. That's not bad for our simple linear model. There are more advanced methods that give better results. The current state-of-the-art on this dataset is **97.42%** <sup>(13)</sup>\n\n## References\n\n<sup>(1)</sup> &nbsp;[Sentiment Analysis - Wikipedia](https://en.wikipedia.org/wiki/Sentiment_analysis)  \n<sup>(2)</sup> &nbsp;[Learning Word Vectors for Sentiment Analysis](http://ai.stanford.edu/~amaas/papers/wvSent_acl2011.pdf)  \n<sup>(3)</sup> &nbsp;[Bag-of-words model - Wikipedia](https://en.wikipedia.org/wiki/Bag-of-words_model)  \n<sup>(4)</sup> &nbsp;[Tf-idf - Wikipedia](https://en.wikipedia.org/wiki/Tf%E2%80%93idf)  \n<sup>(5)</sup> &nbsp;[TfidfTransformer - Scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfTransformer.html)  \n<sup>(6)</sup> &nbsp;[Stop words - Wikipedia](https://en.wikipedia.org/wiki/Stop_words)  \n<sup>(7)</sup> &nbsp;[A list of English stopwords](https://gist.github.com/sebleier/554280)  \n<sup>(8)</sup> &nbsp;[CountVectorizer - Scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html)  \n<sup>(9)</sup> &nbsp;[Scipy sparse matrices](https://docs.scipy.org/doc/scipy/reference/sparse.html)  \n<sup>(10)</sup> [Compressed Sparse Row matrix](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html#scipy.sparse.csr_matrix)  \n<sup>(11)</sup> [SGDClassifier - Scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDClassifier.html)  \n<sup>(12)</sup> [RandomizedSearchCV - Scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html)  \n<sup>(13)</sup> [Sentiment Classification using Document Embeddings trained with\nCosine Similarity](https://www.aclweb.org/anthology/P19-2057.pdf)  \n", "meta": {"hexsha": "48b8b4778da3965cd1d4d02c660879a64380df7d", "size": 80126, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": ".ipynb_checkpoints/sentiment-analysis-checkpoint.ipynb", "max_stars_repo_name": "RajeevAtla/HTCS-ML", "max_stars_repo_head_hexsha": "222e4406ad68d6c1d703d11dfccd20decc2cf08c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": ".ipynb_checkpoints/sentiment-analysis-checkpoint.ipynb", "max_issues_repo_name": "RajeevAtla/HTCS-ML", "max_issues_repo_head_hexsha": "222e4406ad68d6c1d703d11dfccd20decc2cf08c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": ".ipynb_checkpoints/sentiment-analysis-checkpoint.ipynb", "max_forks_repo_name": "RajeevAtla/HTCS-ML", "max_forks_repo_head_hexsha": "222e4406ad68d6c1d703d11dfccd20decc2cf08c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 70.471416007, "max_line_length": 2587, "alphanum_fraction": 0.5401867059, "converted": true, "num_tokens": 13141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19682621306573764, "lm_q2_score": 0.07696083463747946, "lm_q1q2_score": 0.015147909636073533}}
{"text": "<a href=\"https://colab.research.google.com/github/mleyvaz/NN/blob/master/Pestel%20Analisys%20with%20NN.ipynb\" target=\"_parent\"></a>\n\n\n```\nfrom google.colab import files\nuploaded=files.upload()\nfor fn in uploaded.keys():\n  print('User uploaded file \"{name}\" with length {length} bytes'.format(name=fn, length=len(uploaded[fn])))\n```\n\n\n\n<input type=\"file\" id=\"files-7a5c5b48-73a6-4d0c-9ce9-a5f7512fbd47\" name=\"files[]\" multiple disabled />\n<output id=\"result-7a5c5b48-73a6-4d0c-9ce9-a5f7512fbd47\">\n Upload widget is only available when the cell has been executed in the\n current browser session. Please rerun this cell to enable.\n </output>\n  \n\n\n\n```\nimport io\nimport pandas as pd\nfrom IPython.display import display, HTML\ndf=pd.read_csv(io.StringIO(uploaded['Sino_river2.csv'].decode('utf8')), sep = \";\")\ndisplay(df)\n```\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Federal Goverment Political</th>\n      <th>Estadual Goverment Political</th>\n      <th>Municipal Goverment Political</th>\n      <th>Burocracy Impact</th>\n      <th>Corruption Impact</th>\n      <th>Poberty</th>\n      <th>average income</th>\n      <th>Solid Waste Service</th>\n      <th>Liquid Waste Service</th>\n      <th>Water supply Service</th>\n      <th>...</th>\n      <th>Landscape Changes and Urban Planning</th>\n      <th>Biodiversity Index Variations</th>\n      <th>Law Enforcement</th>\n      <th>Education regulatios</th>\n      <th>Health Regulations</th>\n      <th>Environmental Laws</th>\n      <th>Employment Law</th>\n      <th>Climate Changes</th>\n      <th>Soil Quality Index</th>\n      <th>Consumer law</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0</td>\n      <td>0.28</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0.28</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.39</td>\n      <td>0.33</td>\n      <td>0.25</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0</td>\n      <td>0</td>\n      <td>i</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0</td>\n      <td>i</td>\n      <td>i</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>-0.58</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.36</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.33</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>i</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.42</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>i</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>i</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.25</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.36</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>-0.53</td>\n      <td>0.42</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>-0.5</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>i</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>-0.58</td>\n      <td>0.42</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>30</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.28</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>31</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>i</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>32</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>33 rows \u00d7 33 columns</p>\n</div>\n\n\n## An\u00e1lisis Pestle Cuenca del Rio Sinos\n\n\n```\nfrom sympy import Matrix,  var, ones\n\ni = var('i')\nsystem = Matrix(df)\n#Suma de las filas autdegree\nabs(system) * ones(33, 1)\n#Sumar columnas Indegree\n#for in in range()\n\n\n\n\n```\n\n\n```\nimport numpy as np\na=np.matrix([[1.00,0.25,0.20,0.20,0.33,3.00],\n             [4.00,1.00,1.00,1.00,2.00,1.00],\n             [5.00,1.00,1.00,1.00,4.00,2.00],\n             [5.00,1.00,1.00,1.00,2.00,3.00],\n             [3.00,0.50,0.25,0.50,1.00,3.00],\n             [0.33,1.00,0,0.33,0.33,1.00]])\nprint (a)\n```\n\n\n```\n#print (a.sum(axis=0)) #Suma por columnas\nb=a/a.sum(axis=0) # Se normalizan la matriz\n\neigen=1.0/6.0*(b.sum(axis=1))# se encuentra el promedio\nprint(eigen)\n```\n\n\n```\n# Fuzzy Cognitive Map\nE=np.matrix([[0,0.8,0.8,0.8,0.5,0.2],[0,0.8,0,0.5,0.4,0.2],\n             [0.8,0.8,0,0.5,0.5,0.4],\n             [0.8,0.5,0.5,0,0.4,0.4],\n             [0.5,0.4,0.5,0.4,0,0.2],\n             [0.2,0.2,0.4,0.4,0.2,0]])\nprint(E)\n```\n\n\n```\ndef steady(M):    \n    C=M\n    I=np.identity(len(M))\n    M.dot(I)\n    flag=True\n    print(flag)\n    c=0\n    C=M\n    T=M\n    while flag:               \n        c=c+1\n        #print(flag)\n        C=M.dot(C+I)       \n        #print(T)\n        #print(C)        \n        flag=not((C==T).all())\n        #print(flag)\n        if c==50:\n            flag=False\n        T=C\n    #print(c)\n    return C\nEf=steady(E)   \nprint(Ef)\n```\n\n\n```\neigenn=(eigen/np.amax(eigen))\n#print(eigenn)\n# Normalizar la matriz\n\nEfn=Ef/np.amax(Ef.sum(axis=1)) #row sum\n\nw=eigenn+Efn.dot(eigenn)\n\n#print(w)\n#Finally, normalize the global weight (W).\nprint(w/w.sum(axis=0))\n```\n\n\n```\n\n```\n", "meta": {"hexsha": "04e2d31f37ee1b79086ef7e1f791fb335690c204", "size": 68585, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Pestel Analisys with NN.ipynb", "max_stars_repo_name": "mleyvaz/NN", "max_stars_repo_head_hexsha": "6429df67e24176ba8cc6aa159410f53bca0150a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Pestel Analisys with NN.ipynb", "max_issues_repo_name": "mleyvaz/NN", "max_issues_repo_head_hexsha": "6429df67e24176ba8cc6aa159410f53bca0150a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Pestel Analisys with NN.ipynb", "max_forks_repo_name": "mleyvaz/NN", "max_forks_repo_head_hexsha": "6429df67e24176ba8cc6aa159410f53bca0150a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-04-25T16:33:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-25T16:33:38.000Z", "avg_line_length": 49.7714078374, "max_line_length": 7349, "alphanum_fraction": 0.282671138, "converted": true, "num_tokens": 7838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2877678157610531, "lm_q2_score": 0.0526189548333655, "lm_q1q2_score": 0.015142041700027097}}
{"text": "**Notas para contenedor de docker:**\n\nComando de docker para ejecuci\u00f3n de la nota de forma local:\n\nnota: cambiar `dir_montar` por la ruta de directorio que se desea mapear a `/datos` dentro del contenedor de docker.\n\n```\ndir_montar=<ruta completa de mi m\u00e1quina a mi directorio>#aqu\u00ed colocar la ruta al directorio a montar, por ejemplo: \n#dir_montar=/Users/erick/midirectorio.\n```\n\nEjecutar:\n\n```\n$docker run --rm -v $dir_montar:/datos --name jupyterlab_prope_r_kernel_tidyverse -p 8888:8888 -d palmoreck/jupyterlab_prope_r_kernel_tidyverse:3.0.16   \n\n```\n\nIr a `localhost:8888` y escribir el password para jupyterlab: `qwerty`\n\nDetener el contenedor de docker:\n\n```\ndocker stop jupyterlab_prope_r_kernel_tidyverse\n```\n\n\nDocumentaci\u00f3n de la imagen de docker `palmoreck/jupyterlab_prope_r_kernel_tidyverse:3.0.16` en [liga](https://github.com/palmoreck/dockerfiles/tree/master/jupyterlab/prope_r_kernel_tidyverse).\n\n---\n\nPara ejecuci\u00f3n de la nota usar:\n\n[docker](https://www.docker.com/) (instalaci\u00f3n de forma **local** con [Get docker](https://docs.docker.com/install/)) y ejecutar comandos que est\u00e1n al inicio de la nota de forma **local**. \n\nO bien dar click en alguno de los botones siguientes:\n\n[](https://mybinder.org/v2/gh/palmoreck/dockerfiles-for-binder/jupyterlab_prope_r_kernel_tidyerse?urlpath=lab/tree/Propedeutico/Python/clases/3_algebra_lineal/1_ecuaciones_lineales.ipynb) esta opci\u00f3n crea una m\u00e1quina individual en un servidor de Google, clona el repositorio y permite la ejecuci\u00f3n de los notebooks de jupyter.\n\n[](https://repl.it/languages/python3) esta opci\u00f3n no clona el repositorio, no ejecuta los notebooks de jupyter pero permite ejecuci\u00f3n de instrucciones de Python de forma colaborativa con [repl.it](https://repl.it/). Al dar click se crear\u00e1n nuevos ***repl*** debajo de sus users de ***repl.it***.\n\n\n## Lo siguiente est\u00e1 basado en el cap\u00edtulo 2 y ap\u00e9ndice del libro de texto de J. Kiusalas Numerical Methods in Engineering with Python 3 y el libro de Matrix Analysis and Applied Linear Algebra de C. D. Meyer.\n\n**Se sugiere haber revisado la secci\u00f3n 1.5 del libro de texto de J. Kiusalas Numerical Methods in Engineering with Python 3: uso de *NumPy***\n\n# Sistemas de ecuaciones lineales\n\nEn general son de la forma: $$\\begin{array}{ccc} a_{11}x_1 + a_{12}x_2 + \\cdots + a_{1n}x_n  &= & b_1 \\\\ a_{21}x_1 + a_{22}x_2 +  \\cdots + a_{2n}x_n &= & b_2 \\\\ \\vdots & & \\\\ a_{m1}x_1 + a_{m2}x_2 + \\cdots + a_{mn}x_n &=& b_m \\end{array}$$\n\ndonde: las $x_i$'s son las inc\u00f3gnitas y las $a_{ij}$'s y $b_i$'s son constantes conocidas.\n\nLas entradas $a_{ij}$'s son llamadas coeficientes del sistema y el conjunto de $b_i$'s se le llama lado derecho del sistema. Si todas las $b_i$'s son iguales a $0$ el sistema se le nombra **homog\u00e9neo**.\n\n**3 posibilidades para soluci\u00f3n del sistema anterior:**\n\n* Una \u00fanica soluci\u00f3n: s\u00f3lo existe uno y s\u00f3lo un conjunto de valores de $x_i$'s que satisfacen todas las ecuaciones simult\u00e1neamente.\n\n* Ninguna soluci\u00f3n: no existe ning\u00fan conjunto de valores de $x_i$'s que satisfacen todas las ecuaciones simult\u00e1neamente (el conjunto soluci\u00f3n es vac\u00edo).\n\n* Infinitas soluciones: hay una infinidad de conjuntos (distintos) de valores de las $x_i$'s que satisfacen todas las ecuaciones simult\u00e1neamente.\n\n\n---\n\n**Definici\u00f3n**\n\n\nEn el caso de una o infinitas soluciones el sistema de ecuaciones lineales se nombra consistente o no singular, si no existe soluci\u00f3n se nombra inconsistente o singular.\n\n\n---\n\n## Interpretaci\u00f3n geom\u00e9trica\n\nResolver un sistema de ecuaciones lineales equivale a encontrar la intersecci\u00f3n entre rectas, planos o hiperplanos (2,3 o n dimensiones respectivamente). Por ejemplo para un caso de dos dimensiones se tiene:\n\n\n\n\nEl inciso a) representa un sistema de ecuaciones lineales sin soluci\u00f3n, el inciso b) infinitas soluciones (en el dibujo ligeramente se desplaz\u00f3 hacia abajo una de las rectas para mostrar ambas) y el inciso c) una \u00fanica soluci\u00f3n. \n\n## Algoritmos\n\nExisten una gran cantidad de algoritmos para resolver los sistemas de ecuaciones. T\u00edpicamente se elige el algoritmo de acuerdo a las caracter\u00edsticas de los coeficientes de la matriz del sistema y sus dimensiones.\n\n### Sistemas triangulares\n\nSon sistemas cuya matriz es triangular inferior o superior. Un sistema triangular inferior se resuelve con el m\u00e9todo de sustituci\u00f3n hacia delante. Si es triangular superior se resuelve con el m\u00e9todo de sustituci\u00f3n hacia atr\u00e1s.\n\n\n### Ejemplo matriz triangular inferior\n\n\n```python\nimport numpy as np\n```\n\n\n```python\nnp.ones((4,4))\n```\n\n\n\n\n    array([[1., 1., 1., 1.],\n           [1., 1., 1., 1.],\n           [1., 1., 1., 1.],\n           [1., 1., 1., 1.]])\n\n\n\n\n```python\nnp.ones((4,5))\n```\n\n\n\n\n    array([[1., 1., 1., 1., 1.],\n           [1., 1., 1., 1., 1.],\n           [1., 1., 1., 1., 1.],\n           [1., 1., 1., 1., 1.]])\n\n\n\n\n```python\nnp.tril(np.ones(4))\n```\n\n\n\n\n    array([[1., 0., 0., 0.],\n           [1., 1., 0., 0.],\n           [1., 1., 1., 0.],\n           [1., 1., 1., 1.]])\n\n\n\n\n```python\nnp.tril(np.ones((4,4)))\n```\n\n\n\n\n    array([[1., 0., 0., 0.],\n           [1., 1., 0., 0.],\n           [1., 1., 1., 0.],\n           [1., 1., 1., 1.]])\n\n\n\n### Ejemplo matriz triangular superior\n\n\n```python\nnp.triu(np.ones(4))\n```\n\n\n\n\n    array([[1., 1., 1., 1.],\n           [0., 1., 1., 1.],\n           [0., 0., 1., 1.],\n           [0., 0., 0., 1.]])\n\n\n\n\n```python\nnp.triu(np.ones((4,4)))\n```\n\n\n\n\n    array([[1., 1., 1., 1.],\n           [0., 1., 1., 1.],\n           [0., 0., 1., 1.],\n           [0., 0., 0., 1.]])\n\n\n\n### Sistemas no triangulares\n\nPara sistemas de ecuaciones lineales m\u00e1s generales (no tienen estructura identificable) se tienen m\u00e9todos iterativos y directos o basados en factorizaciones matriciales.\n\nEntre los directos o basados en factorizaciones matriciales se encuentran:\n\n\n* Eliminaci\u00f3n Gaussiana o factorizaci\u00f3n LU.\n* Factorizaci\u00f3n de Cholesky (la matriz del sistema debe ser sim\u00e9trica definida positiva).\n* Factorizaci\u00f3n QR.\n* Descomposici\u00f3n en valores singulares o SVD por sus siglas en ingl\u00e9s.\n\ny como ejemplo de m\u00e9todos iterativos est\u00e1n:\n\n* Jacobi.\n* Gauss-Seidel.\n* Gradiente conjugado.\n\n\n\nAmbos m\u00e9todos: iterativos y directos o basados en factorizaciones matriciales encuentran sistemas de ecuaciones equivalentes a partir de operaciones b\u00e1sicas del \u00e1lgebra lineal.\n\n---\n\n**Definici\u00f3n**\n\nDos sistemas de ecuaciones lineales son equivalentes si tienen el mismo conjunto soluci\u00f3n.\n\n---\n\n### Algoritmos iterativos para sistemas de ecuaciones lineales generales\n\nA diferencia de los algoritmos directos que utilizan un n\u00famero finito de pasos para resolver un sistema de ecuaciones lineales, esta clase de algoritmos utilizan un punto inicial y con un proceso iterativo van mejorando la soluci\u00f3n hasta que se satisfaga un criterio de paro. T\u00edpicamente tienen un desempe\u00f1o m\u00e1s lento que los directos pero aprovechan mejor la estructura de las matrices. Dependiendo de las caracter\u00edsticas de las matrices convergen o no a la soluci\u00f3n.\n\nRevisar los siguientes algoritmos que encuentran en la secci\u00f3n 2.7 del libro de texto de J. Kiusalas Numerical Methods in Engineering with Python 3:\n\n* Gauss-Seidel.\n* Gradiente conjugado.\n\n\n### Ejemplos de uso de los paquetes *NumPy* y *SciPy* para resolver ecuaciones lineales\n\n1)Resolver: $$\\begin{array}{ccc} 8x_1 -6x_2 + 2x_3  &= & 28 \\\\ -4x_1 + 11x_2 -7x_3 &= & -40 \\\\ 4x_1 -7x_2 + 6x_3 &=& 33\\end{array} $$\n\n\n```python\nimport numpy as np\nimport pprint\n```\n\n\n```python\nA = np.array([[8, -6, 2], \n              [-4, 11, -7], \n              [4, -7, 6]])\nb = np.array([28,-40,33])\n```\n\n\n```python\nprint('A:')\npprint.pprint(A)\nprint('b:')\npprint.pprint(b)\n```\n\n    A:\n    array([[ 8, -6,  2],\n           [-4, 11, -7],\n           [ 4, -7,  6]])\n    b:\n    array([ 28, -40,  33])\n\n\nUsamos la funci\u00f3n de [solve](https://numpy.org/doc/stable/reference/generated/numpy.linalg.solve.html) dentro de [numpy.linalg](https://numpy.org/doc/stable/reference/routines.linalg.html)\n\n\n```python\nx=np.linalg.solve(A,b)\n```\n\n\n```python\nprint('x:')\npprint.pprint(x)\n```\n\n    x:\n    array([ 2., -1.,  3.])\n\n\n\n```python\nprint('Verificando resultado Ax = b')\nprint('b:')\npprint.pprint(b)\nprint('Ax:')\npprint.pprint(A@x)\n```\n\n    Verificando resultado Ax = b\n    b:\n    array([ 28, -40,  33])\n    Ax:\n    array([ 28., -40.,  33.])\n\n\n\u00bfC\u00f3mo verificamos que son iguales las cantidades?\n**1era opci\u00f3n**\n\n\n```python\n!pip3 install -q --user pytest\n```\n\n    \u001b[33m  WARNING: The scripts py.test and pytest are installed in '/home/propeuser/.local/bin' which is not on PATH.\n      Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.\u001b[0m\n\n\n\n```python\nfrom pytest import approx\n```\n\n\n```python\nsol_numpy = A@x\n```\n\n\n```python\nsol_numpy\n```\n\n\n\n\n    array([ 28., -40.,  33.])\n\n\n\n\n```python\nb \n```\n\n\n\n\n    array([ 28, -40,  33])\n\n\n\n\n```python\nsol_numpy == approx(b)\n```\n\n\n\n\n    True\n\n\n\n**2a opci\u00f3n**\n\n\n```python\nnp.allclose(sol_numpy, b)\n```\n\n\n\n\n    True\n\n\n\n2)Resolver $AX = B$ \n\n$$\\begin{array}{l}\n\\left[\n\\begin{array}{ccc}\n6 &4 &1\\\\\n-4 & 6 & -4\\\\\n1 &-4 & 6\n\\end{array}\n\\right]\n\\left[\n\\begin{array}{cc}\nx_{11} &x_{12} \\\\\nx_{21} & x_{22}\\\\\nx_{31} & x_{32}\n\\end{array}\n\\right]\n=\n\\left[\\begin{array}{cc}\n-14 & 22\\\\\n36 & -18\\\\\n6 & 7\n\\end{array}\n\\right] \n\\end{array}\n$$\n\n\n```python\nA = np.array([[6,-4,1], \n              [-4,6,-4], \n              [1,-4,6]])\nB = np.array([[-14,22],\n              [36,-18],\n              [6,7]])\n```\n\n\n```python\nprint('A:')\npprint.pprint(A)\nprint('B:')\npprint.pprint(B)\n```\n\n    A:\n    array([[ 6, -4,  1],\n           [-4,  6, -4],\n           [ 1, -4,  6]])\n    B:\n    array([[-14,  22],\n           [ 36, -18],\n           [  6,   7]])\n\n\n\n```python\nX=np.linalg.solve(A,B)\n```\n\n\n```python\nprint('X:')\npprint.pprint(X)\n```\n\n    X:\n    array([[10.,  3.],\n           [22., -1.],\n           [14.,  0.]])\n\n\n\n```python\nprint('Verificando resultado AX = B')\nprint('B:')\npprint.pprint(B)\nprint('AX:')\npprint.pprint(A@X)\n```\n\n    Verificando resultado AX = B\n    B:\n    array([[-14,  22],\n           [ 36, -18],\n           [  6,   7]])\n    AX:\n    array([[-14.,  22.],\n           [ 36., -18.],\n           [  6.,   7.]])\n\n\n### Ejemplo factorizaci\u00f3n PLU\n\n**\u00bfDado el sistema $Ax=b$, $A \\in \\mathbb{R}^{n \\times n}$ c\u00f3mo se resuelve con la factorizaci\u00f3n $PLU$?**\n\nPaso 1: encontrar factores $P,L,U$ tales que $PA=LU$.\n\nPaso 2: resolver con el m\u00e9todo de sustituci\u00f3n hacia delante el sistema triangular inferior $Ld=Pb$.\n\nPaso 3: resolver con el m\u00e9todo de sustituci\u00f3n hacia atr\u00e1s el sistema triangular superior $Ux=d$.\n\n**Ejemplo:**\n\nObtener los factores $P, L, U$ de la matriz $A$: $$A = \\begin{bmatrix} 2& -1&2 \\\\ 1& 6& -1 \\\\ 1& 4& 1\\end{bmatrix}$$ \n\ny utilizarlos para resolver $AX = B$ con $$B=\\begin{bmatrix}7 & -1\\\\13 & 6\\\\5 & 7\\end{bmatrix}$$\n\nLa factorizaci\u00f3n P,L,U la calculamos con la funci\u00f3n [lu](https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.lu.html) dentro de [scipy.linalg](https://docs.scipy.org/doc/scipy/reference/linalg.html).\n\n\n```python\nimport scipy\nimport scipy.linalg \n```\n\n\n```python\nA = np.array([[2,-1,2], [1,6,-1], [1,4,1]])\nA\n```\n\n\n\n\n    array([[ 2, -1,  2],\n           [ 1,  6, -1],\n           [ 1,  4,  1]])\n\n\n\n\n```python\nP, L, U = scipy.linalg.lu(A)\n```\n\n\n```python\nprint('A:')\npprint.pprint(A)\nprint('P:')\npprint.pprint(P)\nprint('L:')\npprint.pprint(L)\nprint('U:')\npprint.pprint(U)\n```\n\n    A:\n    array([[ 2, -1,  2],\n           [ 1,  6, -1],\n           [ 1,  4,  1]])\n    P:\n    array([[1., 0., 0.],\n           [0., 1., 0.],\n           [0., 0., 1.]])\n    L:\n    array([[1.        , 0.        , 0.        ],\n           [0.5       , 1.        , 0.        ],\n           [0.5       , 0.69230769, 1.        ]])\n    U:\n    array([[ 2.        , -1.        ,  2.        ],\n           [ 0.        ,  6.5       , -2.        ],\n           [ 0.        ,  0.        ,  1.38461538]])\n\n\n\n```python\nprint('Verificando que es igual PA al producto LU')\nprint('L*U:')\npprint.pprint(L@U)\nprint('P*A')\npprint.pprint(P@A)\n```\n\n    Verificando que es igual PA al producto LU\n    L*U:\n    array([[ 2., -1.,  2.],\n           [ 1.,  6., -1.],\n           [ 1.,  4.,  1.]])\n    P*A\n    array([[ 2., -1.,  2.],\n           [ 1.,  6., -1.],\n           [ 1.,  4.,  1.]])\n\n\n\n```python\nprint('Usando los factores P,L,U para resolver AX = B')\nB = np.array([[7,-1],[13,6],[5,7]])\n\nB\n```\n\n    Usando los factores P,L,U para resolver AX = B\n\n\n\n\n\n    array([[ 7, -1],\n           [13,  6],\n           [ 5,  7]])\n\n\n\nResolvemos paso 2: $LD = PB$\n\n\n```python\nD = scipy.linalg.solve_triangular(L,P@B,lower=True)\nD\n```\n\n\n\n\n    array([[ 7.        , -1.        ],\n           [ 9.5       ,  6.5       ],\n           [-5.07692308,  3.        ]])\n\n\n\nResolver paso 3: $UX = D$\n\n\n```python\nX = scipy.linalg.solve_triangular(U,D) #by default parameter lower is False\n\n```\n\n\n```python\nprint('X:')\npprint.pprint(X)\n```\n\n    X:\n    array([[ 7.33333333, -1.83333333],\n           [ 0.33333333,  1.66666667],\n           [-3.66666667,  2.16666667]])\n\n\n\n```python\nprint('Verificando resultado AX = B')\nprint('B:')\npprint.pprint(B)\nprint('AX:')\npprint.pprint(A@X)\n```\n\n    Verificando resultado AX = B\n    B:\n    array([[ 7, -1],\n           [13,  6],\n           [ 5,  7]])\n    AX:\n    array([[ 7., -1.],\n           [13.,  6.],\n           [ 5.,  7.]])\n\n\n---\n\n**Nota**\n\nEn la factorizaci\u00f3n LU, la matriz $P$ es una matriz de permutaci\u00f3n que cumple con tener un $1$ exactamente en cada rengl\u00f3n y cada columna. Por ejemplo:\n\n$$\n\\left[\n\\begin{array}{ccc}\n0 & 1 & 0\\\\\n1 & 0 & 0\\\\\n0 & 0 & 1\n\\end{array}\n\\right ]\n$$\n\n---\n\n### Ejemplo anterior utilizando la factorizaci\u00f3n QR\n\n**\u00bfDado el sistema $Ax=b$, $A \\in \\mathbb{R}^{n \\times n}$ c\u00f3mo se resuelve con la factorizaci\u00f3n $QR$?**\n\nPaso 1: encontrar factores $Q,R$ tales que $A=QR$. \n\nPaso 2: resolver con el m\u00e9todo de sustituci\u00f3n hacia atr\u00e1s el sistema triangular superior $Rx=Q^Tb$.\n\n\n\n```python\nQ, R = np.linalg.qr(A)\n```\n\n\n```python\nprint('A:')\npprint.pprint(A)\nprint('Q:')\npprint.pprint(Q)\nprint('R:')\npprint.pprint(R)\n\n```\n\n    A:\n    array([[ 2, -1,  2],\n           [ 1,  6, -1],\n           [ 1,  4,  1]])\n    Q:\n    array([[-0.81649658,  0.56354707, -0.12549116],\n           [-0.40824829, -0.71724173, -0.56471022],\n           [-0.40824829, -0.40985242,  0.81569255]])\n    R:\n    array([[-2.44948974, -3.26598632, -1.63299316],\n           [ 0.        , -6.5064071 ,  1.43448345],\n           [ 0.        ,  0.        ,  1.12942045]])\n\n\n$Q^TQ = I$\n\nNorma de la primer columna de Q:\n\n\n```python\nnp.linalg.norm(Q[:,0])\n```\n\n\n\n\n    0.9999999999999999\n\n\n\nNorma de la segunda columna de Q:\n\n\n```python\nnp.linalg.norm(Q[:,1])\n```\n\n\n\n\n    0.9999999999999999\n\n\n\nNorma de la tercera columna de Q:\n\n\n```python\nnp.linalg.norm(Q[:,2])\n```\n\n\n\n\n    1.0\n\n\n\nProducto punto entre primera y segunda columna de Q:\n\n\n```python\nQ[:,0].dot(Q[:,1])\n```\n\n\n\n\n    -2.7755575615628914e-17\n\n\n\n$QQ^T = I$\n\nProducto punto entre primer y segundo rengl\u00f3n de Q:\n\n\n```python\nQ[0,:].dot(Q[1,:])\n```\n\n\n\n\n    1.5265566588595902e-16\n\n\n\nProducto punto entre segundo y tercer rengl\u00f3n de Q:\n\n\n```python\nQ[1,:].dot(Q[2,:])\n```\n\n\n\n\n    -5.551115123125783e-17\n\n\n\nNorma de primer rengl\u00f3n:\n\n\n```python\nnp.linalg.norm(Q[0,:])\n```\n\n\n\n\n    0.9999999999999999\n\n\n\nNorma de segundo rengl\u00f3n:\n\n\n```python\nnp.linalg.norm(Q[1,:])\n```\n\n\n\n\n    0.9999999999999999\n\n\n\nNorma de tercer rengl\u00f3n:\n\n\n```python\nnp.linalg.norm(Q[2,:])\n```\n\n\n\n\n    0.9999999999999999\n\n\n\n\n```python\nQ@Q.T == approx(np.eye(3))\n```\n\n\n\n\n    True\n\n\n\n\n```python\nQ.T@Q == approx(np.eye(3))\n```\n\n\n\n\n    True\n\n\n\n\n```python\nprint('Verificando que es igual A al producto QR')\nprint('QR:')\npprint.pprint(Q@R)\nprint('A')\npprint.pprint(A)\n```\n\n    Verificando que es igual A al producto QR\n    QR:\n    array([[ 2., -1.,  2.],\n           [ 1.,  6., -1.],\n           [ 1.,  4.,  1.]])\n    A\n    array([[ 2, -1,  2],\n           [ 1,  6, -1],\n           [ 1,  4,  1]])\n\n\nResolvemos: $ RX = Q^T B$\n\n\n```python\nprint('Usando los factores Q,R para resolver AX = B')\nX = scipy.linalg.solve_triangular(R, Q.T@B) #by default parameter lower is False\n\n```\n\n    Usando los factores Q,R para resolver AX = B\n\n\n\n```python\nprint('X:')\npprint.pprint(X)\n```\n\n    X:\n    array([[ 7.33333333, -1.83333333],\n           [ 0.33333333,  1.66666667],\n           [-3.66666667,  2.16666667]])\n\n\n\n```python\nprint('Verificando resultado AX = B')\nprint('B:')\npprint.pprint(B)\nprint('AX:')\npprint.pprint(A@X)\n```\n\n    Verificando resultado AX = B\n    B:\n    array([[ 7, -1],\n           [13,  6],\n           [ 5,  7]])\n    AX:\n    array([[ 7., -1.],\n           [13.,  6.],\n           [ 5.,  7.]])\n\n\n**(Tarea) Ejercicio: resolver sistemas de ecuaciones lineales $Ax = b$ con la factorizaci\u00f3n P,L,U y QR. Para esto crear un m\u00f3dulo con nombre `solve_linear_system_of_equations.py` y colocar en tal m\u00f3dulo las siguientes funciones de Python:**\n\nPara factorizaci\u00f3n `PLU`:\n\n```\ndef PLU(matrix, rhs):\n    \"\"\"\n    Compute numerical approximation to linear system of equations Ax=b using\n    factorization PLU via scipy.\n    Args:\n        matrix (numpy 2d array of floats): Square system matrix.\n        rhs (numpy 1d array of floats): Right hand side of linear system of equations.\n    Returns:\n        x (numpy 1d array of floats or string): solution of Ax=b if A is square, if not returns string \n        \"System matrix must be square\"\n    \"\"\"\n```\n\nPara factorizaci\u00f3n `QR`:\n\n```\ndef QR(matrix, rhs):\n    \"\"\"\n    Compute numerical approximation to linear system of equations Ax=b using\n    factorization QR via numpy.\n    Args:\n        matrix (numpy 2d array of floats): Square system matrix.\n        rhs (numpy 1d array of floats): Right hand side of linear system of equations.\n    Returns:\n        x (numpy 1d array of floats or string): solution of Ax=b if A is square, if not returns string \n        \"System matrix must be square\"\n    \"\"\"\n```\n\n**La implementaci\u00f3n de ambas funciones deben realizar un chequeo de dimensiones (ver *docstring* anteriores para saber qu\u00e9 mensaje deben regresar si la matriz del sistema no es cuadrada)**.\n\n### Ejemplos de uso del paquete *SymPy* para resolver ecuaciones lineales\n\n1)Consid\u00e9rese las variables $x,y$ del siguiente sistema y resu\u00e9lvase con *SymPy* para $p, q$ constantes arbitrarias.\n\n$$\n\\begin{array}{ccc}\nx +  py &=& b_1 \\\\\nqx + y &=& b_2\n\\end{array}\n$$\n\nPodemos reescribir este sistema como:\n\n$$\\begin{array}{l}\n\\left[\n\\begin{array}{cc}\n1 &p\\\\\nq & 1\\\\\n\\end{array}\n\\right]\n\\left[\n\\begin{array}{c}\nx \\\\\ny\n\\end{array}\n\\right]\n=\n\\left[\\begin{array}{c}\nb_1 \\\\\nb_2 \\\\\n\\end{array}\n\\right] \n\\end{array}\n$$\n\n\n```python\nimport sympy\n```\n\n\n```python\np,q = sympy.symbols(\"p, q\")\n```\n\n\n```python\nM = sympy.Matrix([[1, p],\n                  [q, 1]])\n```\n\n\n```python\nM\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & p\\\\q & 1\\end{matrix}\\right]$\n\n\n\n\n```python\nb1, b2 = sympy.symbols(\"b1, b2\")\n```\n\n\n```python\nb = sympy.Matrix([b1,b2])\n```\n\n\n```python\nb\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}b_{1}\\\\b_{2}\\end{matrix}\\right]$\n\n\n\n\n```python\nM.solve(b)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\frac{- b_{1} + b_{2} p}{p q - 1}\\\\\\frac{b_{1} q - b_{2}}{p q - 1}\\end{matrix}\\right]$\n\n\n\n2)El sistema:\n\n\n\n$$\n\\begin{array}{l}\nAx=\\left [\n\\begin{array}{cc}\n1 & -3 \\\\\n-2 & 6\n\\end{array}\n\\right ]\n\\left [\n\\begin{array}{c}\nx_1 \\\\\nx_2\n\\end{array}\n\\right ]\n=\n\\left [\n\\begin{array}{c}\n-1 \\\\\n2\n\\end{array}\n\\right ]\n=b\n\\end{array}\n$$\n\ntiene infinitas soluciones, su conjunto soluci\u00f3n est\u00e1 dado por:\n\n$$S = \n\\left \\{\n\\left [ \n\\begin{array}{c}\n-1 + 3t \\\\\nt\\\\\n\\end{array}\n\\right ] | t \\in \\mathbb{R}\n\\right \\}\n=\n\\left \\{\n\\left [ \n\\begin{array}{c}\n-1\\\\\n0\\\\\n\\end{array} \n\\right ]\n+ \nt\\left [\n\\begin{array}{c}\n3\\\\\n1\\\\\n\\end{array}\n\\right ] | t \\in \\mathbb{R}\n\\right \\}\n$$\n\n**Verificamos lo anterior con *SymPy*.**\n\n\n```python\nx_vars = sympy.symbols(\"x1, x2\")\n```\n\n\n```python\nA = sympy.Matrix([[1, -3],\n                  [-2, 6]])\n```\n\n\n```python\nx = sympy.Matrix(x_vars)\n```\n\n\n```python\nb = sympy.Matrix([-1, 2])\n```\n\n\n```python\nsympy.solve(A*x - b, x_vars)\n```\n\n\n\n\n    {x1: 3*x2 - 1}\n\n\n\n**Hacemos la gr\u00e1fica con *NumPy* y *Matplotlib*.**\n\n\n```python\nimport matplotlib.pyplot as plt\n```\n\n\n```python\nA = np.array([[1, -3],\n              [-2, 6.0]])\n```\n\n\n```python\nb = np.array([-1,2.0])\n```\n\nAlgunas soluciones del sistema anterior est\u00e1n dadas por los siguientes puntos.\n\n\n```python\npoint1 = [-1, 0]\npoint2 = [0, 1/3]\npoint3 = [(point2[0]+point1[0])/2, \n           (point2[1] + point1[1])/2]\n```\n\n\n```python\nA@point1\n```\n\n\n\n\n    array([-1.,  2.])\n\n\n\n\n```python\nA@point2\n```\n\n\n\n\n    array([-1.,  2.])\n\n\n\n\n```python\nA@point3\n```\n\n\n\n\n    array([-1.,  2.])\n\n\n\nPodemos dar la soluci\u00f3n y graficar la soluci\u00f3n del sistema anterior que tiene m\u00ednima norma 2 o Euclidiana $||x||_2 = \\sqrt{x_1^2 + x_2^2}$ utilizando *NumPy*.\n\n**Soluci\u00f3n que tiene m\u00ednima norma $2$ o Euclidiana con [pinv](https://numpy.org/doc/stable/reference/generated/numpy.linalg.pinv.html):**\n\n\n```python\npoint4 = np.row_stack((np.zeros(2), np.linalg.pinv(A)@b))\npoint4[1,:]\n```\n\n\n\n\n    array([-0.1,  0.3])\n\n\n\n\n```python\nA@point4[1,:]\n```\n\n\n\n\n    array([-1.,  2.])\n\n\n\nEl siguiente punto satisface al sistema homog\u00e9neo.\n\n\n```python\npoint_homogeneous_system = [3, 1]\n```\n\n\n```python\nA@point_homogeneous_system\n```\n\n\n\n\n    array([0., 0.])\n\n\n\n**Gr\u00e1fica.**\n\n\n```python\nt = np.linspace(-1,1,100)\n```\n\n\n```python\nplt.figure(figsize=(10,10))\nplt.plot(3*t, t, 'b')\nplt.plot(-1+3*t, t, 'r')\nplt.scatter(point_homogeneous_system[0], point_homogeneous_system[1], color='b')\nplt.scatter(point1[0], point1[1], color = 'r')\nplt.scatter(point2[0], point2[1], color='r')\nplt.scatter(point3[0], point3[1], color = 'r')\nplt.plot(point4[:,0], point4[:,1], color='c')\nplt.axhline(color='k')\nplt.axvline(color='k')\nplt.axis(\"equal\")\nplt.legend([\"Soluci\u00f3n sistema homog\u00e9neo\",\n            \"Soluci\u00f3n sistema no homog\u00e9neo\",\n            \"Soluci\u00f3n que minimiza norma Euclidiana\"], \n            bbox_to_anchor=(1, 1))\nplt.show()\n```\n\n\n```python\nnp.linalg.norm(point1)\n```\n\n\n\n\n    1.0\n\n\n\n\n```python\nnp.linalg.norm(point2)\n```\n\n\n\n\n    0.3333333333333333\n\n\n\n\n```python\nnp.linalg.norm(point3)\n```\n\n\n\n\n    0.5270462766947299\n\n\n\n\n```python\nnp.linalg.norm(point4[1,:])\n```\n\n\n\n\n    0.316227766016838\n\n\n\n**El vector que tiene m\u00ednima norma $2$ es.**\n\n\n```python\npoint4[1,:]\n```\n\n\n\n\n    array([-0.1,  0.3])\n\n\n\n## Referencias:\n* [numpy.linalg.solve](https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.solve.html)\n* [scipy.linalg.lu](https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.linalg.lu.html)\n* [scipy.linalg.solve_triangular](https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.solve_triangular.html)\n* [numpy.linalg.qr](https://numpy.org/doc/stable/reference/generated/numpy.linalg.qr.html)\n", "meta": {"hexsha": "4216cf04417f8a5b9dbabcbac6885c07b0b18619", "size": 75207, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Python/clases/3_algebra_lineal/1_ecuaciones_lineales.ipynb", "max_stars_repo_name": "Juanes8/Propedeutico", "max_stars_repo_head_hexsha": "a6f54e3eceddd4df4deec002a6041853bf5b5497", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2019-07-07T07:51:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T18:17:36.000Z", "max_issues_repo_path": "Python/clases/3_algebra_lineal/1_ecuaciones_lineales.ipynb", "max_issues_repo_name": "Juanes8/Propedeutico", "max_issues_repo_head_hexsha": "a6f54e3eceddd4df4deec002a6041853bf5b5497", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2019-06-12T01:15:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-01T18:20:04.000Z", "max_forks_repo_path": "Python/clases/3_algebra_lineal/1_ecuaciones_lineales.ipynb", "max_forks_repo_name": "Juanes8/Propedeutico", "max_forks_repo_head_hexsha": "a6f54e3eceddd4df4deec002a6041853bf5b5497", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 102, "max_forks_repo_forks_event_min_datetime": "2019-06-07T15:24:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T03:05:41.000Z", "avg_line_length": 31.480535789, "max_line_length": 24268, "alphanum_fraction": 0.6303934474, "converted": true, "num_tokens": 7529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09947022189081606, "lm_q2_score": 0.1520322339380366, "lm_q1q2_score": 0.015122680044372958}}
{"text": "```python\n%matplotlib inline\n```\n\n\nVideo processing, Object detection & Tracking\n==============================================\n\n\n**Demonstrating the video processing capabilities of Stone Soup**\n\nThis notebook will guide you progressively through the steps necessary to:\n\n1. Use the Stone Soup :class:`~.FrameReader` components to open and process video data;\n2. Use the :class:`~.TensorFlowBoxObjectDetector` to detect objects in video data, making use of Tensorflow object detection models;\n3. Build a :class:`~.MultiTargetTracker` to perform tracking of multiple object in video data.\n\n\n\n\nSoftware dependencies\n---------------------\nBefore we begin with this tutorial, there are a few things that we need to install in order to\nproceed.\n\nFFmpeg\n~~~~~~\nFFmpeg is a free and open-source project consisting of a vast software suite of libraries and\nprograms for handling video, audio, and other multimedia files and streams. Stone Soup (or more\naccurately some of its extra dependencies) make use of FFmpeg to read and output video. Download\nlinks and installation instructions for FFmpeg can be found `here <https://www.ffmpeg.org/download.html>`__.\n\nTensorFlow\n~~~~~~~~~~\nTensorFlow is a free and open-source software library for dataflow and differentiable programming\nacross a range of tasks, such machine learning. TensorFlow includes an Object Detection API that\nmakes it easy to construct, train and deploy object detection models, as well as a collection of\npre-trained models that can be used for out-of-the-box inference. A quick TensorFlow installation\ntutorial can be found `here <https://tensorflow2objectdetectioninstallation.readthedocs.io/en/latest/>`__.\n\nStone Soup\n~~~~~~~~~~\nTo perform video-processing using Stone Soup, we need to install some extra dependencies. The\neasiest way to achieve this is by running the following commands in a Terminal window:\n\n.. code::\n\n    git clone \"https://github.com/dstl/Stone-Soup.git\"\n    cd Stone-Soup\n    python -m pip install -e .[dev,video,tensorflow]\n\nPytube\n~~~~~~\nWe will also use pytube_ to download a Youtube video for the purposes of this tutorial. In the\nsame Terminal window, run the following command to install ``pytube``:\n\n.. code::\n\n    pip install pytube3\n\n\n\nUsing the Stone Soup :class:`~.FrameReader` classes\n---------------------------------------------------\nThe :class:`~.FrameReader` abstract class is intended as the base class for Stone Soup readers\nthat read frames from any form of imagery data. As of now, Stone Soup has two implementations of\n:class:`~.FrameReader` subclasses:\n\n1. The :class:`~.VideoClipReader` component, which uses MoviePy_ to read video frames from a file.\n2. The :class:`~.FFmpegVideoStreamReader` component, which uses ffmpeg-python_ to read frames from real-time video streams (e.g. RTSP).\n\nIn this tutorial we will focus on the :class:`~.VideoClipReader`, since setting up a stream for\nthe :class:`~.FFmpegVideoStreamReader` is more involved. Nevertheless, the use and interface of\nthe two readers is mostly identical after initialisation and an example of how to initialise the\nlater will also be provided\n\n\n\nDownload and store the video\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nFirst we will download the video that we will use throughout this tutorial. The code snippet\nshown bellow will download the video and save it your working directory as ``sample1.mp4``.\n\n\n\n\n```python\nimport os\nfrom pytube import YouTube\nVIDEO_FILENAME = 'sample1'\nVIDEO_EXTENTION = '.mp4'\nVIDEO_PATH = os.path.join(os.getcwd(), VIDEO_FILENAME+VIDEO_EXTENTION)\n\nif not os.path.exists(VIDEO_PATH):\n    yt = YouTube('http://www.youtube.com/watch?v=MNn9qKG2UFI')\n    yt.streams[0].download(filename=VIDEO_FILENAME)\n```\n\nBuilding the video reader\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\nVideoClipReader\n***************\nWe will use the :class:`~.VideoClipReader` class to read and replay the downloaded file. We also\nconfigure the reader to only replay the clip for the a duration of 2 seconds between `00:10` and\n`00:12`.\n\n\n\n\n```python\nimport datetime\nfrom stonesoup.reader.video import VideoClipReader\nstart_time = datetime.timedelta(minutes=0, seconds=10)\nend_time = datetime.timedelta(minutes=0, seconds=12)\nframe_reader = VideoClipReader(VIDEO_PATH, start_time, end_time)\n```\n\nIt is also possible to apply clip transformations and effects, as per the\n`MoviePy documentation <https://zulko.github.io/moviepy/getting_started/effects.html>`_.\nThe underlying MoviePy :class:`~VideoFileClip` instance can be accessed through the\n:attr:`~.VideoClipReader.clip` class property. For example, we can crop out 100 pixels from\nthe top and left of the frames, as they are read by the reader, as shown below.\n\n\n\n\n```python\nfrom moviepy.video.fx import all\nframe_reader.clip = all.crop(frame_reader.clip, 100, 100)\nnum_frames = len(list(frame_reader.clip.iter_frames()))\n```\n\nFFmpegVideoStreamReader\n***********************\nFor reference purposes, we also include here an example of how to build a\n:class:`~.FFmpegVideoStreamReader`. Let's assume that we have a camera which broadcasts its feed\nthrough a public RTSP stream, under the URL ``rtsp://192.168.55.10:554/stream``. We can build a\n:class:`~.FFmpegVideoStreamReader` object to read frames from this stream as follows:\n\n.. code:: python\n\n  in_opts = {'threads': 1, 'fflags': 'nobuffer'}\n  out_opts = {'format': 'rawvideo', 'pix_fmt': 'bgr24'}\n  stream_url = 'rtsp://192.168.55.10:554/stream'\n  video_reader = FFmpegVideoStreamReader(stream_url, input_opts=in_opts, output_opts=out_opts)\n\n.. important::\n\n  Note that the above code is an illustrative example and will not be run.\n\n:attr:`~.FFmpegVideoStreamReader.input_opts` and :attr:`~.FFmpegVideoStreamReader.output_opts`\nare optional arguments, which allow users to specify options for the input and output FFmpeg\nstreams, as documented by `FFmpeg <https://ffmpeg.org/ffmpeg.html#toc-Options>`__ and\nffmpeg-python_.\n\n\n\nReading frames from the reader\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nAll :class:`~.FrameReader` objects, of which the :class:`~.VideoClipReader` is a subclass,\ngenerate frames in the form of :class:`~.ImageFrame` objects. Below we show an example of how to\nread and visualise these frames using `matplotlib`.\n\n\n\n\n```python\nfrom copy import copy\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nfrom matplotlib import animation\n\nfig, ax = plt.subplots(num=\"VideoClipReader output\")\nartists = []\n\nprint('Running FrameReader example...')\nfor timestamp, frame in frame_reader:\n    if not (len(artists)+1) % 10:\n        print(\"Frame: {}/{}\".format(len(artists)+1, num_frames))\n\n    # Read the frame pixels\n    pixels = copy(frame.pixels)\n\n    # Plot output\n    image = Image.fromarray(pixels)\n    ax.axes.xaxis.set_visible(False)\n    ax.axes.yaxis.set_visible(False)\n    fig.tight_layout()\n    artist = ax.imshow(image, animated=True)\n    artists.append([artist])\n\nani = animation.ArtistAnimation(fig, artists, interval=20, blit=True, repeat_delay=200)\n```\n\nUsing the :class:`~.TensorFlowBoxObjectDetector` class\n------------------------------------------------------\nWe now continue by demonstrating how to use the :class:`~.TensorFlowBoxObjectDetector` to detect\nobjects, and more specifically cars, within the frames read in by our ``video_reader``. The\n:class:`~.TensorFlowBoxObjectDetector` can utilise both pre-trained and custom-trained TensorFlow\nobject detection models which generate detection in the form of bounding boxes. In this example,\nwe will make use of a pre-trained model from the\n`TensorFlow detection model zoo <https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md>`_,\nbut the process of using a custom-trained TensorFlow model is the same.\n\n\n\nDownloading the model\n~~~~~~~~~~~~~~~~~~~~~\nThe code snippet shown below is used to download the object detection model checkpoint file\n(.pb) that we will feed into the :class:`~.TensorFlowBoxObjectDetector` , as well as the label\nfile (.pbtxt) which contains a list of strings used to add the correct label to each detection\n(e.g. car).\n\nThe particular detection algorithm we will use is the Faster-RCNN, with an Inception\nResnet v2 backbone and running in Atrous mode with low proposals, pre-trained on the MSCOCO\ndataset.\n\n<div class=\"alert alert-danger\"><h4>Warning</h4><p>**The downloaded model has a size of approximately 500 MB**. Therefore it is advised that you\n  run the script on a stable (ideally not mobile) internet connection. The files will only be\n  downloaded the first time the script is run. In consecutive runs the code will skip this step,\n  provided that ``PATH_TO_CKPT`` and ``PATH_TO_LABELS`` are valid paths.</p></div>\n\n\n\n\n```python\nimport urllib\nimport tarfile\nMODEL_NAME = 'faster_rcnn_inception_resnet_v2_atrous_lowproposals_coco_2018_01_28'\nMODEL_TAR = MODEL_NAME + '.tar.gz'\nMODELS_DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'\nPATH_TO_CKPT = os.path.join(os.getcwd(), MODEL_NAME + '/frozen_inference_graph.pb')\n\n# Download and extract model\nif not os.path.exists(PATH_TO_CKPT):\n    print(\"Downloading model. This may take a while...\")\n    urllib.request.urlretrieve(MODELS_DOWNLOAD_BASE + MODEL_TAR, MODEL_TAR)\n    tar_file = tarfile.open(MODEL_TAR)\n    for file in tar_file.getmembers():\n        file_name = os.path.basename(file.name)\n        if 'frozen_inference_graph.pb' in file_name:\n            tar_file.extract(file, os.getcwd())\n    tar_file.close()\n    os.remove(MODEL_TAR)\n\nLABEL_FILE = 'mscoco_label_map.pbtxt'\nLABELS_DOWNLOAD_BASE = \\\n    'https://raw.githubusercontent.com/tensorflow/models/master/research/object_detection/data/'\nPATH_TO_LABELS = os.path.join(os.getcwd(), \"{}/{}\".format(MODEL_NAME, LABEL_FILE))\n\n# Download labels\nif not os.path.exists(PATH_TO_LABELS):\n    print(\"Downloading label file...\")\n    urllib.request.urlretrieve(LABELS_DOWNLOAD_BASE + LABEL_FILE, PATH_TO_LABELS)\n```\n\nBuilding the detector\n~~~~~~~~~~~~~~~~~~~~~\nNext, we proceed to initialise our detector object. To do this, we require the ``frame_reader``\nobject we built previously, as well as a path to the (downloaded) model checkpoint (.pb) and\nlabel (.pbtxt) files, which we have already defined above under the ``PATH_TO_CKPT`` and\n``PATH_TO_LABELS`` variables.\n\nThe :class:`~.TensorFlowBoxObjectDetector` object can optionally be configured to digest frames\nfrom the provided reader asynchronously, and only perform detection on the last frame digested,\nby setting ``run_async=True``.This is suitable when the detector is applied to readers generating\na live feed (e.g. the :class:`~.FFmpegVideoStreamReader`), where real-time processing is\nparamount. Since we are using a :class:`~.VideoClipReader` in this example, we set\n``run_async=False``, which is also the default setting.\n\nFinally, the ``session_config`` parameter can be used to provide a `ConfigProto\n<https://www.tensorflow.org/code/tensorflow/core/protobuf/config.proto>`_ protocol buffer with\nconfiguration options for the TensorFlow session run by the detector. Below we show an example of\nhow this can be used to prevent TensorFlow from mapping all of the GPU memory, which can lead to\ncuDNN errors when the host GPU is used by other processes.\n\n\n\n\n```python\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'    # Suppress TensorFlow logging\nimport tensorflow as tf\nfrom stonesoup.detector.tensorflow import TensorFlowBoxObjectDetector\n\nconfig = tf.compat.v1.ConfigProto()\nconfig.gpu_options.allow_growth = True      # Allow dynamic allocation of GPU memory to TF session\nrun_async = False                           # Configure the detector to run in synchronous mode\ndetector = TensorFlowBoxObjectDetector(frame_reader, PATH_TO_CKPT, PATH_TO_LABELS,\n                                       run_async=run_async, session_config=config)\n```\n\nFiltering-out unwanted detections\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nIn this section we showcase how we can utilise Stone Soup :class:`~.Feeder` objects in order to\nfilter out unwanted detections. One example of feeder we can use is the\n:class:`~.MetadataValueFilter`, which allows us to filter detections by applying a custom\noperator on particular fields of the :attr:`~.Detection.metadata` property of detections.\n\nEach detection generated by :class:`~.TensorFlowBoxObjectDetector` carries the following\n:attr:`~.Detection.metadata` fields:\n\n - ``raw_box``: The raw bounding box containing the normalised coordinates ``[y_0, x_0, y_1, x_1]``, as generated by TensorFlow.\n - ``class``: A dict with keys ``id`` and ``name`` relating to the id and name of the detection class.\n - ``score``: A float in the range ``(0, 1]`` indicating the detector's confidence.\n\nDetection models trained on the MSCOCO dataset, such as the one we downloaded, are able to detect\n90 different classes of objects (see the `downloaded .pbtxt file <https://github.com/tensorflow/models/blob/master/research/object_detection/data/mscoco_label_map.pbtxt>`_\nfor a full list). Instead, as we discussed at the beginning of the tutorial, we wish to limit the\ndetections to only those classified as cars. This can be done as follows:\n\n\n\n\n```python\nfrom stonesoup.feeder.filter import MetadataValueFilter\ndetector = MetadataValueFilter(detector, 'class', lambda x: x['name'] == 'car')\n```\n\nContinuing, we may want to filter out detections which have a low confidence score:\n\n\n\n\n```python\ndetector = MetadataValueFilter(detector, 'score', lambda x: x > 0.1)\n```\n\nFinally, we observed that the detector tends to incorrectly generate detections which are much\nlarger the the size we expect for a car. Therefore, we can filter out those detections by only\nallowing ones whose width is less the 20\\% of the frame width (i.e. ``x_1-x_0 < 0.2``):\n\n\n\n\n```python\ndetector = MetadataValueFilter(detector, 'raw_box', lambda x: x[3]-x[1] < 0.2)\n```\n\nYou are encouraged to comment out any/all of the above filter definitions and observe the\nproduced output.\n\n\n\nReading and visualising detections\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nDetections generated by the :class:`~.TensorFlowBoxObjectDetector` have a 4-dimensional\n:attr:`~.Detection.state_vector` in the form of a bounding boxes that captures the area of the\nframe where an object is detected. Each bounding box is represented by a vector of the form\n``[x, y, w, h]``, where ``x, y`` denote the relative pixel coordinates of the top-left corner,\nwhile ``w, h`` denote the relative width and height of the bounding box. Below we show an example\nof how to read and visualise these detections using `matplotlib`.\n\n\n\n\n```python\nimport numpy as np\nfrom PIL import ImageDraw\n\n\ndef draw_detections(image, detections, show_class=False, show_score=False):\n    \"\"\" Draw detections on an image\n\n    Parameters\n    ----------\n    image: :class:`PIL.Image`\n        Image on which to draw the detections\n    detections: : set of :class:`~.Detection`\n        A set of detections generated by :class:`~.TensorFlowBoxObjectDetector`\n    show_class: bool\n        Whether to draw the class of the object. Default is ``False``\n    show_score: bool\n        Whether to draw the score of the object. Default is ``False``\n\n    Returns\n    -------\n    : :class:`PIL.Image`\n        Image with detections drawn\n    \"\"\"\n    draw = ImageDraw.Draw(image)\n    for detection in detections:\n        x0, y0, w, h = np.array(detection.state_vector).reshape(4)\n        x1, y1 = (x0 + w, y0 + h)\n        draw.rectangle([x0, y0, x1, y1], outline=(0, 255, 0), width=1)\n        class_ = detection.metadata['class']['name']\n        score = round(float(detection.metadata['score']),2)\n        if show_class and show_score:\n            draw.text((x0,y1 + 2), '{}:{}'.format(class_, score), fill=(0, 255, 0))\n        elif show_class:\n            draw.text((x0, y1 + 2), '{}'.format(class_), fill=(0, 255, 0))\n        elif show_score:\n            draw.text((x0, y1 + 2), '{}'.format(score), fill=(0, 255, 0))\n\n    del draw\n    return image\n\n\nfig2, ax2 = plt.subplots(num=\"TensorFlowBoxObjectDetector output\")\nartists2 = []\nprint(\"Running TensorFlowBoxObjectDetector example... Be patient...\")\nfor timestamp, detections in detector:\n    if not (len(artists2)+1) % 10:\n        print(\"Frame: {}/{}\".format(len(artists2)+1, num_frames))\n\n    # Read the frame pixels\n    frame = frame_reader.frame\n    pixels = copy(frame.pixels)\n\n    # Plot output\n    image = Image.fromarray(pixels)\n    image = draw_detections(image, detections, True, True)\n    ax2.axes.xaxis.set_visible(False)\n    ax2.axes.yaxis.set_visible(False)\n    fig2.tight_layout()\n    artist = ax2.imshow(image, animated=True)\n    artists2.append([artist])\n\nani2 = animation.ArtistAnimation(fig2, artists2, interval=20, blit=True, repeat_delay=200)\n```\n\nConstructing a Multi-Object Video Tracker\n-----------------------------------------\nIn this final segment of the tutorial we will see how we can use the above demonstrated\ncomponents to perform tracking of multiple objects within Stone Soup.\n\nDefining the state-space models\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nTransition Model\n****************\nWe begin our definition of the state-space models by defining the hidden state\n$\\mathrm{x}_k$, i.e. the state that we wish to estimate:\n\n\\begin{align}\\mathrm{x}_k = [x_k, \\dot{x}_k, y_k, \\dot{y}_k, w_k, h_k]\\end{align}\n\nwhere $x_k, y_k$ denote the pixel coordinates of the top-left corner of the bounding box\ncontaining an object, with $\\dot{x}_k, \\dot{y}_k$ denoting their respective rate of change,\nwhile $w_k$ and $h_k$ denote the width and height of the box, respectively.\n\nWe assume that $x_k$ and $y_k$ move with nearly :class:`~.ConstantVelocity`, while\n$w_k$ and $h_k$ evolve according to a :class:`~.RandomWalk`.Using these assumptions,\nwe proceed to construct our Stone Soup :class:`~.TransitionModel` as follows:\n\n\n\n\n```python\nfrom stonesoup.models.transition.linear import (CombinedLinearGaussianTransitionModel,\n                                                ConstantVelocity, RandomWalk)\nt_models = [ConstantVelocity(20**2), ConstantVelocity(20**2), RandomWalk(20**2), RandomWalk(20**2)]\ntransition_model = CombinedLinearGaussianTransitionModel(t_models)\n```\n\nMeasurement Model\n*****************\nContinuing, we define the measurement state $\\mathrm{y}_k$, which follows naturally from\nthe form of the detections generated by the :class:`~.TensorFlowBoxObjectDetector` we previously\ndiscussed:\n\n\\begin{align}\\mathrm{y}_k = [x_k, y_k, w_k, h_k]\\end{align}\n\nWe make use of a 4-dimensional :class:`~.LinearGaussian` model as our :class:`~.MeasurementModel`,\nwhereby we can see that the individual indices of $\\mathrm{y}_k$ map to indices `[0,2,4,5]`\nof the 6-dimensional state $\\mathrm{x}_k$:\n\n\n\n\n```python\nfrom stonesoup.models.measurement.linear import LinearGaussian\nmeasurement_model = LinearGaussian(ndim_state=6, mapping=[0, 2, 4, 5],\n                                   noise_covar=np.diag([1**2, 1**2, 3**2, 3**2]))\n```\n\nDefining the tracker components\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nWith the state-space models defined, we proceed to build our tracking components\n\nFiltering\n*********\nSince we have assumed Linear-Gaussian models, we will be using a Kalman Filter to perform\nfiltering of the underlying single-target densities. This is done by making use of the\n:class:`~.KalmanPredictor` and :class:`~.KalmanUpdater` classes, which we define below:\n\n\n\n\n```python\nfrom stonesoup.predictor.kalman import KalmanPredictor\npredictor = KalmanPredictor(transition_model)\n```\n\n\n```python\nfrom stonesoup.updater.kalman import KalmanUpdater\nupdater = KalmanUpdater(measurement_model)\n```\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>For more information on the above classes and how they operate you can refer to the Stone\n  Soup tutorial on\n  `using the Kalman Filter <https://stonesoup.readthedocs.io/en/latest/auto_tutorials/01_KalmanFilterTutorial.html>`_.</p></div>\n\nData Association\n****************\nWe utilise a :class:`~.DistanceHypothesiser` to generate hypotheses between tracks and\nmeasurements, where :class:`~.Mahalanobis` distance is used as a measure of quality:\n\n\n\n\n```python\nfrom stonesoup.hypothesiser.distance import DistanceHypothesiser\nfrom stonesoup.measures import Mahalanobis\nhypothesiser = DistanceHypothesiser(predictor, updater, Mahalanobis(), 10)\n```\n\nContinuing the :class:`~.GNNWith2DAssigment` class is used to perform fast joint data association,\nbased on the Global Nearest Neighbour (GNN) algorithm:\n\n\n\n\n```python\nfrom stonesoup.dataassociator.neighbour import GNNWith2DAssignment\ndata_associator = GNNWith2DAssignment(hypothesiser)\n```\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>For more information on the above classes and how they operate you can refer to the\n  `Data Association - clutter <https://stonesoup.readthedocs.io/en/latest/auto_tutorials/05_DataAssociation-Clutter.html>`_\n  and `Data Association - Multi-Target Tracking <https://stonesoup.readthedocs.io/en/latest/auto_tutorials/06_DataAssociation-MultiTargetTutorial.html>`_\n  tutorials.</p></div>\n\n\n\nTrack Initiation\n****************\nFor initialising tracks we will use a :class:`~.MultiMeasurementInitiator`, which allows our\ntracker to tentatively initiate tracks from unassociated measurements, and hold them within the\ninitiator until they have survived for at least 10 frames. We also define a\n:class:`~.UpdateTimeStepsDeleter` deleter to be used by the initiator to delete tentative tracks\nthat have not been associated to a measurement in the last 3 frames.\n\n\n\n\n```python\nfrom stonesoup.types.state import GaussianState\nfrom stonesoup.types.array import CovarianceMatrix, StateVector\nfrom stonesoup.initiator.simple import MultiMeasurementInitiator\nfrom stonesoup.deleter.time import UpdateTimeStepsDeleter\nprior_state = GaussianState(StateVector(np.zeros((6,1))),\n                            CovarianceMatrix(np.diag([100**2, 30**2, 100**2, 30**2, 100**2, 100**2])))\ndeleter_init = UpdateTimeStepsDeleter(time_steps_since_update=3)\ninitiator = MultiMeasurementInitiator(prior_state, measurement_model, deleter_init,\n                                      data_associator, updater, min_points=10)\n```\n\nTrack Deletion\n**************\nFor confirmed tracks we used again a :class:`~.UpdateTimeStepsDeleter`, but this time configured\nto delete tracks after they have not bee associated to a measurement in the last 15 frames.\n\n\n\n\n```python\ndeleter = UpdateTimeStepsDeleter(time_steps_since_update=15)\n```\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>For more information on the above classes and how they operate you can refer to the Stone\n  `Initiators & Deleters <https://stonesoup.readthedocs.io/en/latest/auto_tutorials/09_Initiators_&_Deleters.html>`_\n  tutorial.</p></div>\n\nBuilding the tracker\n~~~~~~~~~~~~~~~~~~~~\nNow that we have defined all our tracker components we proceed to build our multi-target tracker:\n\n\n\n\n```python\nfrom stonesoup.tracker.simple import MultiTargetTracker\ntracker = MultiTargetTracker(\n    initiator=initiator,\n    deleter=deleter,\n    detector=detector,\n    data_associator=data_associator,\n    updater=updater,\n)\n```\n\nRunning the tracker\n~~~~~~~~~~~~~~~~~~~\n\n\n\n\n```python\ndef draw_tracks(image, tracks, show_history=True, show_class=True, show_score=True):\n    \"\"\" Draw tracks on an image\n\n    Parameters\n    ----------\n    image: :class:`PIL.Image`\n        Image on which to draw the tracks\n    detections: : set of :class:`~.Tracks`\n        A set of tracks generated by our :class:`~.MultiTargetTracker`\n    show_history: bool\n        Whether to draw the trajectory of the track. Default is ``True``\n    show_class: bool\n        Whether to draw the class of the object. Default is ``True``\n    show_score: bool\n        Whether to draw the score of the object. Default is ``True``\n\n    Returns\n    -------\n    : :class:`PIL.Image`\n        Image with tracks drawn\n\n    \"\"\"\n    draw = ImageDraw.Draw(image)\n    for track in tracks:\n        bboxes = np.array([np.array(state.state_vector[[0, 2, 4, 5]]).reshape(4)\n                           for state in track.states])\n        x0, y0, w, h = bboxes[-1]\n        x1 = x0 + w\n        y1 = y0 + h\n        draw.rectangle([x0, y0, x1, y1], outline=(255, 0, 0), width=2)\n\n        if show_history:\n            pts = [(box[0] + box[2] / 2, box[1] + box[3] / 2) for box in bboxes]\n            draw.line(pts, fill=(255, 0, 0), width=2)\n\n        class_ = track.metadata['class']['name']\n        score = round(float(track.metadata['score']), 2)\n        if show_class and show_score:\n            draw.text((x0, y1 + 2), '{}:{}'.format(class_, score), fill=(255, 0, 0))\n        elif show_class:\n            draw.text((x0, y1 + 2), '{}'.format(class_), fill=(255, 0, 0))\n        elif show_score:\n            draw.text((x0, y1 + 2), '{}'.format(score), fill=(255, 0, 0))\n    return image\n\n\nfig3, ax3 = plt.subplots(num=\"MultiTargetTracker output\")\nfig3.tight_layout()\nartists3 = []\nprint(\"Running MultiTargetTracker example... Be patient...\")\nfor timestamp, tracks in tracker:\n    if not (len(artists3) + 1) % 10:\n        print(\"Frame: {}/{}\".format(len(artists3) + 1, num_frames))\n\n    # Read the detections\n    detections = detector.detections\n\n    # Read frame\n    frame = frame_reader.frame\n    pixels = copy(frame.pixels)\n\n    # Plot output\n    image = Image.fromarray(pixels)\n    image = draw_detections(image, detections)\n    image = draw_tracks(image, tracks)\n    ax3.axes.xaxis.set_visible(False)\n    ax3.axes.yaxis.set_visible(False)\n    fig3.tight_layout()\n    artist = ax3.imshow(image, animated=True)\n    artists3.append([artist])\nani3 = animation.ArtistAnimation(fig3, artists3, interval=20, blit=True, repeat_delay=200)\n```\n", "meta": {"hexsha": "53b6d7083a1cec34d77e28c7d6aab3ef3aa26d6a", "size": 32827, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/source/auto_demos/Video_Processing.ipynb", "max_stars_repo_name": "SohSalari/Stone-Soup", "max_stars_repo_head_hexsha": "e073d4145df18facad43e4ab7b0a34e8d65f67ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-21T15:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-21T15:20:20.000Z", "max_issues_repo_path": "docs/source/auto_demos/Video_Processing.ipynb", "max_issues_repo_name": "SohSalari/Stone-Soup", "max_issues_repo_head_hexsha": "e073d4145df18facad43e4ab7b0a34e8d65f67ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/source/auto_demos/Video_Processing.ipynb", "max_forks_repo_name": "SohSalari/Stone-Soup", "max_forks_repo_head_hexsha": "e073d4145df18facad43e4ab7b0a34e8d65f67ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 73.6031390135, "max_line_length": 2585, "alphanum_fraction": 0.6458707771, "converted": true, "num_tokens": 6145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1993079979040457, "lm_q2_score": 0.07585818524437762, "lm_q1q2_score": 0.015119143025691124}}
{"text": "```python\nimport kenlm\nimport cPickle as pickle\nimport numpy as np\nimport copy\n```\n\n\n```python\nbeam_size = 10\n# templates_dump_location = './eo_with_surf_forms_templates.p'\ntemplates_dump_location = './ar_without_surf_forms_templates.p'\n# Whether to sample from sentences with surface form tuples and property placeholders OR with pure text.\n# summaries_type = 'summary_with_surf_forms_and_types'\nsummaries_type = 'original_summary'\n```\n\n### Loading trained $n$-gram model along with the original dataset file\n\n\n```python\nmodel = kenlm.LanguageModel('ar_without_surf_forms.klm')\ndataset_file_location = '../Datasets/ar/Dataset/with-Surface-Forms/splitDataset_with_targets.p'\nwith open(dataset_file_location, 'rb') as f:\n    dataset = pickle.load(f)\n```\n\n### Building vocabulary\n\n\n```python\nvocab_len = 0\ntoken2id = {}\nid2token = {}\n\nfor i in range(0, len(dataset['train'][summaries_type])):\n    tempSummary = dataset['train'][summaries_type][i].encode('utf-8').split()\n    for token in tempSummary:\n        if token not in token2id:\n            vocab_len += 1\n            token2id[token] = vocab_len\n            id2token[vocab_len] = token\nvocab_len += 1\ntoken2id['</s>'] = vocab_len\nid2token[vocab_len] = '</s>'\n\n# Make sure that sequences are absolved from start- and end-of-sequence tokens.\n# These are not handled very well by this model.\nassert('<start>' not in token2id)\nassert('<end>' not in token2id)\n```\n\n### Beam-search decoding on the trained $n$-gram model\nWe initialise the beams with the $n$ most probable words given the `<s>` token (i.e. `<start>` token in KenLM Language Model Toolkit)\n\nMore information at: https://kheafield.com/code/kenlm/\n\n\n```python\nsentences = []\nsentences_prob = []\ncandidates = []\nnum_active_beams = beam_size\n\n\nbeam_probabilities = np.zeros(vocab_len) \nfor token in token2id:\n    tempCandidate = ' '.join([] + [token]) \n    beam_probabilities[token2id[token] - 1] = model.score(tempCandidate, eos = False)\nindices = np.argsort(beam_probabilities)[-num_active_beams:]\nprint indices\nfor j in range(beam_size - 1, -1, -1):\n    candidates.append([id2token[indices[j] + 1]])\n\nwhile num_active_beams > 0:\n    beam_probabilities = np.zeros(num_active_beams * vocab_len)\n    beam_probabilities.fill(np.NINF)\n    for s in range(0, num_active_beams):\n        for token in token2id:\n            tempCandidate = ' '.join(candidates[s] + [token])\n            beam_probabilities[s * vocab_len + token2id[token] - 1] = model.score(tempCandidate, eos = False)\n        \n    indices = np.argsort(beam_probabilities)[-num_active_beams:]\n    print indices\n    cloned_candidates = copy.deepcopy(candidates)\n    completed_beams_counter = 0\n    candidates = []\n    for j in range(num_active_beams - 1, -1, -1):\n        \n        candidates.append([])\n        candidates[-1] = copy.deepcopy(cloned_candidates[indices[j] / vocab_len])\n        \n        candidates[-1] += [id2token[indices[j] % vocab_len + 1]]\n        if id2token[indices[j] % vocab_len + 1] == '</s>':\n            completed_beams_counter += 1\n            sentences.append(candidates[-1])\n            sentences_prob.append(beam_probabilities[indices[j]])\n            candidates.pop(-1)\n    num_active_beams -= completed_beams_counter\n```\n\n    [423458     23   1197    487   3478    639    421     10      7     43]\n    [ 852805  864784    1078  848042    6411  423502 1694807     784  847022\n      423553]\n    [1271582      95 2545349 2541879 3812537 1693845 2964375  847080  437077\n         120]\n    [3813604    1706 3394202 3813713 3387768 2541328 1693846 1271165  847703\n         121]\n    [1270519  847997 2964238 2541725  861699     504 2117392  846968 1270518\n      423585]\n    [ 865303  856119  854492 3387682    2804 2964333 2117305  864152  423469\n         786]\n    [3811141 2975390 3396874 2541140 1700102 2120100 1270763  846928  423601\n         386]\n    [1694222 1277951    3619  847304   19845    6889    2628    4774     787\n       10919]\n    [3811181 3398849 2965001 2118083 2540804 1694624 1278554  851664  424247\n         788]\n    [  10920  436005 3387682  423509     400   19710 2134529      50 1271165\n      847706]\n    [2565451 2129236 3387800 2964312    6168      50 1693964  431033 1270387\n      859251]\n    [3811259 3387800 2964274 1698610 2555194 2117423 1270438  863225  423558\n         128]\n    [3811192 3387733 2964275 2551454 2540753 1693897 1270439  847046  437899\n          61]\n    [2599823 2969594 3387734 2964275 2117423 1693898  846979  846917      62]\n    [ 267174   53271   34674   27153   17004  428840 1270438  423521]\n    [2964343  224861 1270507 1693966  854444   23109   24350  423521]\n    [2964344  847048  423589  151129   60389 2117426 1693967    7256]\n    [2964274     130 1693966  423520 1270507 2540885  846979 2117426]\n    [2964345 2540885 2117426      61 1693968  846979 1270508  423591]\n    [ 423520 2964346 2540815 2118086 1693968 1270510  847050     133]\n    [2964345 2540888 2117427 1694628 1270510  847052  423592     134]\n    [2964346 2964212 1693969 2117428 1270511 1270376  423593  423458]\n    [1693970 1271047  847052  846917  423458]\n    [1270376  423915  423458]\n    [423458]\n\n\n### Purely-greedy decoding on the trained $n$-gram model\n\n\n```python\n# sentences = [[]]\n# sentences_prob = [np.NINF]\n# selectedToken = ''\n\n# while selectedToken != '</s>':\n#     max_prob = np.NINF\n#     for token in token2id:\n#         tempCandidate = ' '.join(sentences[0] + [token])\n#         sentences_prob[-1] = tempScore\n#         tempScore = model.score(tempCandidate, eos = False)\n#         if tempScore > max_prob:\n#             selectedToken = token\n#             max_prob = tempScore\n#     sentences[0].append(selectedToken)\n\n#     print(sentences[0])\n```\n\n\n```python\nfor s in sentences:\n    print s\n```\n\n    ['\\xd9\\x82\\xd8\\xb1\\xd9\\x8a\\xd8\\xa9', '\\xd8\\xb3\\xd9\\x88\\xd8\\xb1\\xd9\\x8a\\xd8\\xa9', '\\xd8\\xaa\\xd8\\xaa\\xd8\\xa8\\xd8\\xb9', '\\xd9\\x86\\xd8\\xa7\\xd8\\xad\\xd9\\x8a\\xd8\\xa9', '\\xd8\\xb3\\xd9\\x84\\xd9\\x88\\xd9\\x83', '\\xd9\\x81\\xd9\\x8a', '\\xd9\\x85\\xd9\\x86\\xd8\\xb7\\xd9\\x82\\xd8\\xa9', '\\xd8\\xaa\\xd9\\x84', '\\xd8\\xa3\\xd8\\xa8\\xd9\\x8a\\xd8\\xb6', '\\xd9\\x81\\xd9\\x8a', '\\xd9\\x85\\xd8\\xad\\xd8\\xa7\\xd9\\x81\\xd8\\xb8\\xd8\\xa9', '\\xd8\\xa7\\xd9\\x84\\xd8\\xb1\\xd9\\x82\\xd8\\xa9.', '</s>']\n    ['\\xd9\\x82\\xd8\\xb1\\xd9\\x8a\\xd8\\xa9', '\\xd8\\xb3\\xd9\\x88\\xd8\\xb1\\xd9\\x8a\\xd8\\xa9', '\\xd8\\xaa\\xd8\\xaa\\xd8\\xa8\\xd8\\xb9', '\\xd9\\x86\\xd8\\xa7\\xd8\\xad\\xd9\\x8a\\xd8\\xa9', '\\xd9\\x85\\xd8\\xb1\\xd9\\x83\\xd8\\xb2', '\\xd8\\xa7\\xd9\\x84\\xd8\\xb1\\xd9\\x82\\xd8\\xa9', '\\xd9\\x81\\xd9\\x8a', '\\xd9\\x85\\xd9\\x86\\xd8\\xb7\\xd9\\x82\\xd8\\xa9', '\\xd9\\x85\\xd8\\xb1\\xd9\\x83\\xd8\\xb2', '\\xd8\\xa7\\xd9\\x84\\xd8\\xb1\\xd9\\x82\\xd8\\xa9', '\\xd9\\x81\\xd9\\x8a', '\\xd9\\x85\\xd8\\xad\\xd8\\xa7\\xd9\\x81\\xd8\\xb8\\xd8\\xa9', '\\xd8\\xa7\\xd9\\x84\\xd8\\xb1\\xd9\\x82\\xd8\\xa9.', '</s>']\n    ['\\xd9\\x82\\xd8\\xb1\\xd9\\x8a\\xd8\\xa9', '\\xd8\\xb3\\xd9\\x88\\xd8\\xb1\\xd9\\x8a\\xd9\\x91\\xd8\\xa9', '\\xd8\\xaa\\xd8\\xaa\\xd8\\xa8\\xd8\\xb9', '\\xd8\\xa5\\xd8\\xaf\\xd8\\xa7\\xd8\\xb1\\xd9\\x8a\\xd9\\x91\\xd8\\xa7\\xd9\\x8b', '\\xd9\\x84\\xd9\\x85\\xd8\\xad\\xd8\\xa7\\xd9\\x81\\xd8\\xb8\\xd8\\xa9', '\\xd8\\xad\\xd9\\x84\\xd8\\xa8', '\\xd9\\x85\\xd9\\x86\\xd8\\xb7\\xd9\\x82\\xd8\\xa9', '\\xd9\\x85\\xd9\\x86\\xd8\\xa8\\xd8\\xac', '\\xd9\\x86\\xd8\\xa7\\xd8\\xad\\xd9\\x8a\\xd8\\xa9', '\\xd9\\x85\\xd8\\xb1\\xd9\\x83\\xd8\\xb2', '\\xd9\\x85\\xd9\\x86\\xd8\\xa8\\xd8\\xac\\xd8\\x8c', '\\xd8\\xa8\\xd9\\x84\\xd8\\xba', '\\xd8\\xaa\\xd8\\xb9\\xd8\\xaf\\xd8\\xa7\\xd8\\xaf', '\\xd8\\xb3\\xd9\\x83\\xd8\\xa7\\xd9\\x86\\xd9\\x87\\xd8\\xa7', '195', '\\xd9\\x86\\xd8\\xb3\\xd9\\x85\\xd8\\xa9', '\\xd8\\xad\\xd8\\xb3\\xd8\\xa8', '\\xd8\\xaa\\xd8\\xb9\\xd8\\xaf\\xd8\\xa7\\xd8\\xaf', '\\xd8\\xa7\\xd9\\x84\\xd9\\x8a\\xd9\\x85\\xd9\\x86', '\\xd9\\x84\\xd8\\xb9\\xd8\\xa7\\xd9\\x85', '2004.', '</s>']\n    ['\\xd9\\x82\\xd8\\xb1\\xd9\\x8a\\xd8\\xa9', '\\xd8\\xb3\\xd9\\x88\\xd8\\xb1\\xd9\\x8a\\xd9\\x91\\xd8\\xa9', '\\xd8\\xaa\\xd8\\xaa\\xd8\\xa8\\xd8\\xb9', '\\xd8\\xa5\\xd8\\xaf\\xd8\\xa7\\xd8\\xb1\\xd9\\x8a\\xd9\\x91\\xd8\\xa7\\xd9\\x8b', '\\xd9\\x84\\xd9\\x85\\xd8\\xad\\xd8\\xa7\\xd9\\x81\\xd8\\xb8\\xd8\\xa9', '\\xd8\\xad\\xd9\\x84\\xd8\\xa8', '\\xd9\\x85\\xd9\\x86\\xd8\\xb7\\xd9\\x82\\xd8\\xa9', '\\xd9\\x85\\xd9\\x86\\xd8\\xa8\\xd8\\xac', '\\xd9\\x86\\xd8\\xa7\\xd8\\xad\\xd9\\x8a\\xd8\\xa9', '\\xd9\\x85\\xd8\\xb1\\xd9\\x83\\xd8\\xb2', '\\xd9\\x85\\xd9\\x86\\xd8\\xa8\\xd8\\xac\\xd8\\x8c', '\\xd8\\xa8\\xd9\\x84\\xd8\\xba', '\\xd8\\xaa\\xd8\\xb9\\xd8\\xaf\\xd8\\xa7\\xd8\\xaf', '\\xd8\\xb3\\xd9\\x83\\xd8\\xa7\\xd9\\x86\\xd9\\x87\\xd8\\xa7', '282', '\\xd9\\x86\\xd8\\xb3\\xd9\\x85\\xd8\\xa9', '\\xd8\\xad\\xd8\\xb3\\xd8\\xa8', '\\xd8\\xaa\\xd8\\xb9\\xd8\\xaf\\xd8\\xa7\\xd8\\xaf', '\\xd8\\xa7\\xd9\\x84\\xd9\\x8a\\xd9\\x85\\xd9\\x86', '\\xd9\\x84\\xd8\\xb9\\xd8\\xa7\\xd9\\x85', '2004.', '</s>']\n    ['\\xd9\\x82\\xd8\\xb1\\xd9\\x8a\\xd8\\xa9', '\\xd8\\xb3\\xd9\\x88\\xd8\\xb1\\xd9\\x8a\\xd9\\x91\\xd8\\xa9', '\\xd8\\xaa\\xd8\\xaa\\xd8\\xa8\\xd8\\xb9', '\\xd8\\xa5\\xd8\\xaf\\xd8\\xa7\\xd8\\xb1\\xd9\\x8a\\xd9\\x91\\xd8\\xa7\\xd9\\x8b', '\\xd9\\x84\\xd9\\x85\\xd8\\xad\\xd8\\xa7\\xd9\\x81\\xd8\\xb8\\xd8\\xa9', '\\xd8\\xad\\xd9\\x84\\xd8\\xa8', '\\xd9\\x85\\xd9\\x86\\xd8\\xb7\\xd9\\x82\\xd8\\xa9', '\\xd9\\x85\\xd9\\x86\\xd8\\xa8\\xd8\\xac', '\\xd9\\x86\\xd8\\xa7\\xd8\\xad\\xd9\\x8a\\xd8\\xa9', '\\xd9\\x85\\xd8\\xb1\\xd9\\x83\\xd8\\xb2', '\\xd9\\x85\\xd9\\x86\\xd8\\xa8\\xd8\\xac\\xd8\\x8c', '\\xd8\\xa8\\xd9\\x84\\xd8\\xba', '\\xd8\\xaa\\xd8\\xb9\\xd8\\xaf\\xd8\\xa7\\xd8\\xaf', '\\xd8\\xb3\\xd9\\x83\\xd8\\xa7\\xd9\\x86\\xd9\\x87\\xd8\\xa7', '846', '\\xd9\\x86\\xd8\\xb3\\xd9\\x85\\xd8\\xa9', '\\xd8\\xad\\xd8\\xb3\\xd8\\xa8', '\\xd8\\xaa\\xd8\\xb9\\xd8\\xaf\\xd8\\xa7\\xd8\\xaf', '\\xd8\\xa7\\xd9\\x84\\xd9\\x8a\\xd9\\x85\\xd9\\x86', '\\xd9\\x84\\xd8\\xb9\\xd8\\xa7\\xd9\\x85', '2004.', '</s>']\n    ['\\xd9\\x82\\xd8\\xb1\\xd9\\x8a\\xd8\\xa9', '\\xd8\\xb3\\xd9\\x88\\xd8\\xb1\\xd9\\x8a\\xd9\\x91\\xd8\\xa9', '\\xd8\\xaa\\xd8\\xaa\\xd8\\xa8\\xd8\\xb9', '\\xd8\\xa5\\xd8\\xaf\\xd8\\xa7\\xd8\\xb1\\xd9\\x8a\\xd9\\x91\\xd8\\xa7\\xd9\\x8b', '\\xd9\\x84\\xd9\\x85\\xd8\\xad\\xd8\\xa7\\xd9\\x81\\xd8\\xb8\\xd8\\xa9', '\\xd8\\xad\\xd9\\x84\\xd8\\xa8', '\\xd9\\x85\\xd9\\x86\\xd8\\xb7\\xd9\\x82\\xd8\\xa9', '\\xd8\\xac\\xd8\\xa8\\xd9\\x84', '\\xd8\\xb3\\xd9\\x85\\xd8\\xb9\\xd8\\xa7\\xd9\\x86', '\\xd9\\x86\\xd8\\xa7\\xd8\\xad\\xd9\\x8a\\xd8\\xa9', '\\xd8\\xaa\\xd9\\x84', '\\xd8\\xa7\\xd9\\x84\\xd8\\xb6\\xd9\\x85\\xd8\\xa7\\xd9\\x86\\xd8\\x8c', '\\xd8\\xa8\\xd9\\x84\\xd8\\xba', '\\xd8\\xaa\\xd8\\xb9\\xd8\\xaf\\xd8\\xa7\\xd8\\xaf', '\\xd8\\xb3\\xd9\\x83\\xd8\\xa7\\xd9\\x86\\xd9\\x87\\xd8\\xa7', '332', '\\xd9\\x86\\xd8\\xb3\\xd9\\x85\\xd8\\xa9', '\\xd8\\xad\\xd8\\xb3\\xd8\\xa8', '\\xd8\\xaa\\xd8\\xb9\\xd8\\xaf\\xd8\\xa7\\xd8\\xaf', '\\xd8\\xa7\\xd9\\x84\\xd9\\x8a\\xd9\\x85\\xd9\\x86', '\\xd9\\x84\\xd8\\xb9\\xd8\\xa7\\xd9\\x85', '2004.', '</s>']\n    ['\\xd9\\x82\\xd8\\xb1\\xd9\\x8a\\xd8\\xa9', '\\xd8\\xb3\\xd9\\x88\\xd8\\xb1\\xd9\\x8a\\xd9\\x91\\xd8\\xa9', '\\xd8\\xaa\\xd8\\xaa\\xd8\\xa8\\xd8\\xb9', '\\xd8\\xa5\\xd8\\xaf\\xd8\\xa7\\xd8\\xb1\\xd9\\x8a\\xd9\\x91\\xd8\\xa7\\xd9\\x8b', '\\xd9\\x84\\xd9\\x85\\xd8\\xad\\xd8\\xa7\\xd9\\x81\\xd8\\xb8\\xd8\\xa9', '\\xd8\\xad\\xd9\\x84\\xd8\\xa8', '\\xd9\\x85\\xd9\\x86\\xd8\\xb7\\xd9\\x82\\xd8\\xa9', '\\xd8\\xac\\xd8\\xa8\\xd9\\x84', '\\xd8\\xb3\\xd9\\x85\\xd8\\xb9\\xd8\\xa7\\xd9\\x86', '\\xd9\\x86\\xd8\\xa7\\xd8\\xad\\xd9\\x8a\\xd8\\xa9', '\\xd8\\xaa\\xd9\\x84', '\\xd8\\xa7\\xd9\\x84\\xd8\\xb6\\xd9\\x85\\xd8\\xa7\\xd9\\x86\\xd8\\x8c', '\\xd8\\xa8\\xd9\\x84\\xd8\\xba', '\\xd8\\xaa\\xd8\\xb9\\xd8\\xaf\\xd8\\xa7\\xd8\\xaf', '\\xd8\\xb3\\xd9\\x83\\xd8\\xa7\\xd9\\x86\\xd9\\x87\\xd8\\xa7', '295', '\\xd9\\x86\\xd8\\xb3\\xd9\\x85\\xd8\\xa9', '\\xd8\\xad\\xd8\\xb3\\xd8\\xa8', '\\xd8\\xaa\\xd8\\xb9\\xd8\\xaf\\xd8\\xa7\\xd8\\xaf', '\\xd8\\xa7\\xd9\\x84\\xd9\\x8a\\xd9\\x85\\xd9\\x86', '\\xd9\\x84\\xd8\\xb9\\xd8\\xa7\\xd9\\x85', '2004.', '</s>']\n    ['\\xd9\\x82\\xd8\\xb1\\xd9\\x8a\\xd8\\xa9', '\\xd8\\xb3\\xd9\\x88\\xd8\\xb1\\xd9\\x8a\\xd9\\x91\\xd8\\xa9', '\\xd8\\xaa\\xd8\\xaa\\xd8\\xa8\\xd8\\xb9', '\\xd8\\xa5\\xd8\\xaf\\xd8\\xa7\\xd8\\xb1\\xd9\\x8a\\xd9\\x91\\xd8\\xa7\\xd9\\x8b', '\\xd9\\x84\\xd9\\x85\\xd8\\xad\\xd8\\xa7\\xd9\\x81\\xd8\\xb8\\xd8\\xa9', '\\xd8\\xad\\xd9\\x84\\xd8\\xa8', '\\xd9\\x85\\xd9\\x86\\xd8\\xb7\\xd9\\x82\\xd8\\xa9', '\\xd8\\xb9\\xd9\\x8a\\xd9\\x86', '\\xd8\\xa7\\xd9\\x84\\xd8\\xb9\\xd8\\xb1\\xd8\\xa8', '\\xd9\\x86\\xd8\\xa7\\xd8\\xad\\xd9\\x8a\\xd8\\xa9', '\\xd9\\x85\\xd8\\xb1\\xd9\\x83\\xd8\\xb2', '\\xd8\\xb9\\xd9\\x8a\\xd9\\x86', '\\xd8\\xa7\\xd9\\x84\\xd8\\xb9\\xd8\\xb1\\xd8\\xa8\\xd8\\x8c', '\\xd8\\xa8\\xd9\\x84\\xd8\\xba', '\\xd8\\xaa\\xd8\\xb9\\xd8\\xaf\\xd8\\xa7\\xd8\\xaf', '\\xd8\\xb3\\xd9\\x83\\xd8\\xa7\\xd9\\x86\\xd9\\x87\\xd8\\xa7', '76', '\\xd9\\x86\\xd8\\xb3\\xd9\\x85\\xd8\\xa9', '\\xd8\\xad\\xd8\\xb3\\xd8\\xa8', '\\xd8\\xaa\\xd8\\xb9\\xd8\\xaf\\xd8\\xa7\\xd8\\xaf', '\\xd8\\xa7\\xd9\\x84\\xd9\\x8a\\xd9\\x85\\xd9\\x86', '\\xd9\\x84\\xd8\\xb9\\xd8\\xa7\\xd9\\x85', '2004.', '</s>']\n    ['\\xd9\\x82\\xd8\\xb1\\xd9\\x8a\\xd8\\xa9', '\\xd8\\xb3\\xd9\\x88\\xd8\\xb1\\xd9\\x8a\\xd9\\x91\\xd8\\xa9', '\\xd8\\xaa\\xd8\\xaa\\xd8\\xa8\\xd8\\xb9', '\\xd8\\xa5\\xd8\\xaf\\xd8\\xa7\\xd8\\xb1\\xd9\\x8a\\xd9\\x91\\xd8\\xa7\\xd9\\x8b', '\\xd9\\x84\\xd9\\x85\\xd8\\xad\\xd8\\xa7\\xd9\\x81\\xd8\\xb8\\xd8\\xa9', '\\xd8\\xad\\xd9\\x84\\xd8\\xa8', '\\xd9\\x85\\xd9\\x86\\xd8\\xb7\\xd9\\x82\\xd8\\xa9', '\\xd8\\xb9\\xd9\\x8a\\xd9\\x86', '\\xd8\\xa7\\xd9\\x84\\xd8\\xb9\\xd8\\xb1\\xd8\\xa8', '\\xd9\\x86\\xd8\\xa7\\xd8\\xad\\xd9\\x8a\\xd8\\xa9', '\\xd9\\x85\\xd8\\xb1\\xd9\\x83\\xd8\\xb2', '\\xd8\\xb9\\xd9\\x8a\\xd9\\x86', '\\xd8\\xa7\\xd9\\x84\\xd8\\xb9\\xd8\\xb1\\xd8\\xa8\\xd8\\x8c', '\\xd8\\xa8\\xd9\\x84\\xd8\\xba', '\\xd8\\xaa\\xd8\\xb9\\xd8\\xaf\\xd8\\xa7\\xd8\\xaf', '\\xd8\\xb3\\xd9\\x83\\xd8\\xa7\\xd9\\x86\\xd9\\x87\\xd8\\xa7', '649', '\\xd9\\x86\\xd8\\xb3\\xd9\\x85\\xd8\\xa9', '\\xd8\\xad\\xd8\\xb3\\xd8\\xa8', '\\xd8\\xaa\\xd8\\xb9\\xd8\\xaf\\xd8\\xa7\\xd8\\xaf', '\\xd8\\xa7\\xd9\\x84\\xd9\\x8a\\xd9\\x85\\xd9\\x86', '\\xd9\\x84\\xd8\\xb9\\xd8\\xa7\\xd9\\x85', '2004.', '</s>']\n    ['\\xd9\\x82\\xd8\\xb1\\xd9\\x8a\\xd8\\xa9', '\\xd8\\xb3\\xd9\\x88\\xd8\\xb1\\xd9\\x8a\\xd9\\x91\\xd8\\xa9', '\\xd8\\xaa\\xd8\\xaa\\xd8\\xa8\\xd8\\xb9', '\\xd8\\xa5\\xd8\\xaf\\xd8\\xa7\\xd8\\xb1\\xd9\\x8a\\xd9\\x91\\xd8\\xa7\\xd9\\x8b', '\\xd9\\x84\\xd9\\x85\\xd8\\xad\\xd8\\xa7\\xd9\\x81\\xd8\\xb8\\xd8\\xa9', '\\xd8\\xad\\xd9\\x84\\xd8\\xa8', '\\xd9\\x85\\xd9\\x86\\xd8\\xb7\\xd9\\x82\\xd8\\xa9', '\\xd8\\xb9\\xd9\\x8a\\xd9\\x86', '\\xd8\\xa7\\xd9\\x84\\xd8\\xb9\\xd8\\xb1\\xd8\\xa8', '\\xd9\\x86\\xd8\\xa7\\xd8\\xad\\xd9\\x8a\\xd8\\xa9', '\\xd9\\x85\\xd8\\xb1\\xd9\\x83\\xd8\\xb2', '\\xd8\\xb9\\xd9\\x8a\\xd9\\x86', '\\xd8\\xa7\\xd9\\x84\\xd8\\xb9\\xd8\\xb1\\xd8\\xa8\\xd8\\x8c', '\\xd8\\xa8\\xd9\\x84\\xd8\\xba', '\\xd8\\xaa\\xd8\\xb9\\xd8\\xaf\\xd8\\xa7\\xd8\\xaf', '\\xd8\\xb3\\xd9\\x83\\xd8\\xa7\\xd9\\x86\\xd9\\x87\\xd8\\xa7', '1,142', '\\xd9\\x86\\xd8\\xb3\\xd9\\x85\\xd8\\xa9', '\\xd8\\xad\\xd8\\xb3\\xd8\\xa8', '\\xd8\\xa7\\xd9\\x84\\xd8\\xaa\\xd8\\xb9\\xd8\\xaf\\xd8\\xa7\\xd8\\xaf', '\\xd8\\xa7\\xd9\\x84\\xd8\\xb3\\xd9\\x83\\xd8\\xa7\\xd9\\x86\\xd9\\x8a', '\\xd9\\x84\\xd8\\xb9\\xd8\\xa7\\xd9\\x85', '2004', '.', '</s>']\n\n\n\n```python\nfor s in range(0, len(sentences)):\n    assert(sentences[s][-1] == '</s>')\n    sentences[s] = ' '.join(sentences[s][:-1]).decode('utf-8')\n    print sentences[s], sentences_prob[s]\n```\n\n    \u0642\u0631\u064a\u0629 \u0633\u0648\u0631\u064a\u0629 \u062a\u062a\u0628\u0639 \u0646\u0627\u062d\u064a\u0629 \u0633\u0644\u0648\u0643 \u0641\u064a \u0645\u0646\u0637\u0642\u0629 \u062a\u0644 \u0623\u0628\u064a\u0636 \u0641\u064a \u0645\u062d\u0627\u0641\u0638\u0629 \u0627\u0644\u0631\u0642\u0629. -4.30183410645\n    \u0642\u0631\u064a\u0629 \u0633\u0648\u0631\u064a\u0629 \u062a\u062a\u0628\u0639 \u0646\u0627\u062d\u064a\u0629 \u0645\u0631\u0643\u0632 \u0627\u0644\u0631\u0642\u0629 \u0641\u064a \u0645\u0646\u0637\u0642\u0629 \u0645\u0631\u0643\u0632 \u0627\u0644\u0631\u0642\u0629 \u0641\u064a \u0645\u062d\u0627\u0641\u0638\u0629 \u0627\u0644\u0631\u0642\u0629. -4.10472583771\n    \u0642\u0631\u064a\u0629 \u0633\u0648\u0631\u064a\u0651\u0629 \u062a\u062a\u0628\u0639 \u0625\u062f\u0627\u0631\u064a\u0651\u0627\u064b \u0644\u0645\u062d\u0627\u0641\u0638\u0629 \u062d\u0644\u0628 \u0645\u0646\u0637\u0642\u0629 \u0645\u0646\u0628\u062c \u0646\u0627\u062d\u064a\u0629 \u0645\u0631\u0643\u0632 \u0645\u0646\u0628\u062c\u060c \u0628\u0644\u063a \u062a\u0639\u062f\u0627\u062f \u0633\u0643\u0627\u0646\u0647\u0627 195 \u0646\u0633\u0645\u0629 \u062d\u0633\u0628 \u062a\u0639\u062f\u0627\u062f \u0627\u0644\u064a\u0645\u0646 \u0644\u0639\u0627\u0645 2004. -6.04410171509\n    \u0642\u0631\u064a\u0629 \u0633\u0648\u0631\u064a\u0651\u0629 \u062a\u062a\u0628\u0639 \u0625\u062f\u0627\u0631\u064a\u0651\u0627\u064b \u0644\u0645\u062d\u0627\u0641\u0638\u0629 \u062d\u0644\u0628 \u0645\u0646\u0637\u0642\u0629 \u0645\u0646\u0628\u062c \u0646\u0627\u062d\u064a\u0629 \u0645\u0631\u0643\u0632 \u0645\u0646\u0628\u062c\u060c \u0628\u0644\u063a \u062a\u0639\u062f\u0627\u062f \u0633\u0643\u0627\u0646\u0647\u0627 282 \u0646\u0633\u0645\u0629 \u062d\u0633\u0628 \u062a\u0639\u062f\u0627\u062f \u0627\u0644\u064a\u0645\u0646 \u0644\u0639\u0627\u0645 2004. -6.12608671188\n    \u0642\u0631\u064a\u0629 \u0633\u0648\u0631\u064a\u0651\u0629 \u062a\u062a\u0628\u0639 \u0625\u062f\u0627\u0631\u064a\u0651\u0627\u064b \u0644\u0645\u062d\u0627\u0641\u0638\u0629 \u062d\u0644\u0628 \u0645\u0646\u0637\u0642\u0629 \u0645\u0646\u0628\u062c \u0646\u0627\u062d\u064a\u0629 \u0645\u0631\u0643\u0632 \u0645\u0646\u0628\u062c\u060c \u0628\u0644\u063a \u062a\u0639\u062f\u0627\u062f \u0633\u0643\u0627\u0646\u0647\u0627 846 \u0646\u0633\u0645\u0629 \u062d\u0633\u0628 \u062a\u0639\u062f\u0627\u062f \u0627\u0644\u064a\u0645\u0646 \u0644\u0639\u0627\u0645 2004. -6.34612083435\n    \u0642\u0631\u064a\u0629 \u0633\u0648\u0631\u064a\u0651\u0629 \u062a\u062a\u0628\u0639 \u0625\u062f\u0627\u0631\u064a\u0651\u0627\u064b \u0644\u0645\u062d\u0627\u0641\u0638\u0629 \u062d\u0644\u0628 \u0645\u0646\u0637\u0642\u0629 \u062c\u0628\u0644 \u0633\u0645\u0639\u0627\u0646 \u0646\u0627\u062d\u064a\u0629 \u062a\u0644 \u0627\u0644\u0636\u0645\u0627\u0646\u060c \u0628\u0644\u063a \u062a\u0639\u062f\u0627\u062f \u0633\u0643\u0627\u0646\u0647\u0627 332 \u0646\u0633\u0645\u0629 \u062d\u0633\u0628 \u062a\u0639\u062f\u0627\u062f \u0627\u0644\u064a\u0645\u0646 \u0644\u0639\u0627\u0645 2004. -6.11217737198\n    \u0642\u0631\u064a\u0629 \u0633\u0648\u0631\u064a\u0651\u0629 \u062a\u062a\u0628\u0639 \u0625\u062f\u0627\u0631\u064a\u0651\u0627\u064b \u0644\u0645\u062d\u0627\u0641\u0638\u0629 \u062d\u0644\u0628 \u0645\u0646\u0637\u0642\u0629 \u062c\u0628\u0644 \u0633\u0645\u0639\u0627\u0646 \u0646\u0627\u062d\u064a\u0629 \u062a\u0644 \u0627\u0644\u0636\u0645\u0627\u0646\u060c \u0628\u0644\u063a \u062a\u0639\u062f\u0627\u062f \u0633\u0643\u0627\u0646\u0647\u0627 295 \u0646\u0633\u0645\u0629 \u062d\u0633\u0628 \u062a\u0639\u062f\u0627\u062f \u0627\u0644\u064a\u0645\u0646 \u0644\u0639\u0627\u0645 2004. -6.14283323288\n    \u0642\u0631\u064a\u0629 \u0633\u0648\u0631\u064a\u0651\u0629 \u062a\u062a\u0628\u0639 \u0625\u062f\u0627\u0631\u064a\u0651\u0627\u064b \u0644\u0645\u062d\u0627\u0641\u0638\u0629 \u062d\u0644\u0628 \u0645\u0646\u0637\u0642\u0629 \u0639\u064a\u0646 \u0627\u0644\u0639\u0631\u0628 \u0646\u0627\u062d\u064a\u0629 \u0645\u0631\u0643\u0632 \u0639\u064a\u0646 \u0627\u0644\u0639\u0631\u0628\u060c \u0628\u0644\u063a \u062a\u0639\u062f\u0627\u062f \u0633\u0643\u0627\u0646\u0647\u0627 76 \u0646\u0633\u0645\u0629 \u062d\u0633\u0628 \u062a\u0639\u062f\u0627\u062f \u0627\u0644\u064a\u0645\u0646 \u0644\u0639\u0627\u0645 2004. -6.26259183884\n    \u0642\u0631\u064a\u0629 \u0633\u0648\u0631\u064a\u0651\u0629 \u062a\u062a\u0628\u0639 \u0625\u062f\u0627\u0631\u064a\u0651\u0627\u064b \u0644\u0645\u062d\u0627\u0641\u0638\u0629 \u062d\u0644\u0628 \u0645\u0646\u0637\u0642\u0629 \u0639\u064a\u0646 \u0627\u0644\u0639\u0631\u0628 \u0646\u0627\u062d\u064a\u0629 \u0645\u0631\u0643\u0632 \u0639\u064a\u0646 \u0627\u0644\u0639\u0631\u0628\u060c \u0628\u0644\u063a \u062a\u0639\u062f\u0627\u062f \u0633\u0643\u0627\u0646\u0647\u0627 649 \u0646\u0633\u0645\u0629 \u062d\u0633\u0628 \u062a\u0639\u062f\u0627\u062f \u0627\u0644\u064a\u0645\u0646 \u0644\u0639\u0627\u0645 2004. -6.38466739655\n    \u0642\u0631\u064a\u0629 \u0633\u0648\u0631\u064a\u0651\u0629 \u062a\u062a\u0628\u0639 \u0625\u062f\u0627\u0631\u064a\u0651\u0627\u064b \u0644\u0645\u062d\u0627\u0641\u0638\u0629 \u062d\u0644\u0628 \u0645\u0646\u0637\u0642\u0629 \u0639\u064a\u0646 \u0627\u0644\u0639\u0631\u0628 \u0646\u0627\u062d\u064a\u0629 \u0645\u0631\u0643\u0632 \u0639\u064a\u0646 \u0627\u0644\u0639\u0631\u0628\u060c \u0628\u0644\u063a \u062a\u0639\u062f\u0627\u062f \u0633\u0643\u0627\u0646\u0647\u0627 1,142 \u0646\u0633\u0645\u0629 \u062d\u0633\u0628 \u0627\u0644\u062a\u0639\u062f\u0627\u062f \u0627\u0644\u0633\u0643\u0627\u0646\u064a \u0644\u0639\u0627\u0645 2004 . -6.36081552505\n\n\n### Computing probabilities\nKenLM scores are $log_{10}$ probabilities; we compute the actual ones (i.e. $0 \\leq p_i \\leq 1$).\nWe normalise as follows:\n\\begin{equation}\n\\widetilde{p_i} = \\frac{p_i}{\\sum_i p_i}\n\\end{equation}\n\n\n```python\nnominator = np.power(10, np.asarray(sentences_prob))\ndenominator = np.power(10, np.asarray(sentences_prob)).sum()\n```\n\n\n```python\nprob_distribution = nominator / denominator\n```\n\n\n```python\nprint prob_distribution\n```\n\n    [ 0.37392506  0.58869839  0.00676888  0.00560444  0.00337674  0.00578684\n      0.00539244  0.00409286  0.00308995  0.0032644 ]\n\n\n### Saving everything in a dictionary\n```python\n{'sentences': type(list), 'prob_distribution': type(numpy.ndarray)}\n```\n\n\n```python\nwith open(templates_dump_location, 'wb') as f:\n    pickle.dump({'sentences': sentences, 'prob_distribution': prob_distribution}, f)\n```\n", "meta": {"hexsha": "24753cfa4d4e8163570cbe2c90bad8517350ec3f", "size": 21921, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "baselines/KenLM_with_beamsampling/main.ipynb", "max_stars_repo_name": "www2018-550/Submission550", "max_stars_repo_head_hexsha": "d707d0e6eed98097569e4d5e3ffc4aea27d17c1f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-03-25T21:25:09.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-28T09:25:32.000Z", "max_issues_repo_path": "baselines/KenLM_with_beamsampling/main.ipynb", "max_issues_repo_name": "multi-gen/NAACL-submission-2018", "max_issues_repo_head_hexsha": "eadbfa9d1eeb04974354371d599ac9ffcebd9c51", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "baselines/KenLM_with_beamsampling/main.ipynb", "max_forks_repo_name": "multi-gen/NAACL-submission-2018", "max_forks_repo_head_hexsha": "eadbfa9d1eeb04974354371d599ac9ffcebd9c51", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.4974226804, "max_line_length": 1144, "alphanum_fraction": 0.5567720451, "converted": true, "num_tokens": 7044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2658804847339313, "lm_q2_score": 0.05665242690069723, "lm_q1q2_score": 0.015062774725710987}}
{"text": "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Gated-CNN\" data-toc-modified-id=\"Gated-CNN-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Gated CNN</a></span><ul class=\"toc-item\"><li><span><a href=\"#GCNN-1D-Time-Series\" data-toc-modified-id=\"GCNN-1D-Time-Series-1.1\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;</span>GCNN 1D Time Series</a></span></li><li><span><a href=\"#GCNN-1D-Residuals\" data-toc-modified-id=\"GCNN-1D-Residuals-1.2\"><span class=\"toc-item-num\">1.2&nbsp;&nbsp;</span>GCNN 1D Residuals</a></span></li></ul></li></ul></div>\n\n\n```python\n\n\n#####\n###  Inicio de refatoracao usando principios de design patterns. \n# TODO: pesquisar mais e mais e mais a fundo o design do Tensorflow pra seguir de perto.\n\nfrom enum import Enum\n\nclass BlockTypes(Enum):\n  GCNN2D = 'gcnn2d'\n  SOFTMAX = 'softmax'\n  CROSSENTROPY = 'loss-crossentropy'\n  INPUT = 'signal_in'\n  REDUCEMEAN = 'reducemean'\n  \nclass ArchBlocks:\n\n  def __add__(self, block):\n    pass\n    \nclass Architecture(ArchBlocks):\n  '''\n    aa\n  '''\n  def __init__(self, **kwargs):\n    \n    self.modules = {'0':[ArchBlocks.INPUT,0,0,[],[]]}\n\n  def __add__(self, archblock1):\n    pass\n    #self.modules = archblock1\n    \n    \n  def _block_specification(self,key):    \n    pass\n\nclass Stattus4NeuralNetAPI:\n    \n  def __init__(self, datatype, datasocket = False, **kwargs):\n    '''\n     Input\n     \n     datatype: Audio, Pressure, Flow.\n     datasocket: if True tries to fetch data from a database and push output to database \n     pre-configured through kwargs, if config is not provided then tries to read from datafeeder or dump to local file-system.   \n     \n     Optional\n     num_of_channels: number of channels for Audio data, if not given get only the first audio and discard the others.    \n    '''\n    self.datatype = datatype\n    self.datasocket = datasocket\n    \n  def setup_hyperparameters(self, architectures):\n    '''\n      Input\n      \n      architectures: Architecture object specifying archetypical structure to be investigated for its hyperparams.\n\n      Return a dictionary of the given \n    '''\n    pass\n\n#######\n#######\n ####\n  ### \n   #  \n\n#  FUTURE: Name/Var Scope handler. This class/template must be used to implement logic of names \n# according to the architecture block connection. E.G. if a block is just the same from the other in the\n# sequence them it must be named as if is a deep part of the same architecture blocks. If it is a ramification\n# of the given below but the same arch them he must be named with another tag.\n# When duplicating some block to architectonic use, E.G. if you need to frame your data or feature, them each\n# frame must have an coeherent name space block, like the today ordimatlicly done for repeated name space block,\n# but this must be automaticly done for identical built blocks of the model, without the need to explicity code it.\n# Names must be given as unique ID according to te input-output architecture connection, if it has the same IO from previous Block in the sequence,\n# then each Input-ARchBlock-Output that is IDentical must have the same name with the appropriated tag for deepnes in the sequence of blocks\n# Automatic update of the name scopes according to the architecture.\n# Dont change Identical sequential IO Name spaces  \n```\n\n\n```python\n## Unused building-blocks, will add in the API in the future, after a throughful refatoration.\n#\n\n\n  self.architectures.gcnn1d = self._gcnn1d\n  self.architectures.residualgcnn1d = self._residualgcnn1d\n  def _gcnn1d(self, **kwargs):\n\n    try:\n        \n      channels_out = kwargs['channels_out']\n      filter_size = kwargs['filter_size']\n\n    except Exception:\n        \n      sys.exit('Parameters Not Defined Error')\n     \n      signal_in = self(**kwargs)\n        \n    # postfix = self.get_namepostfix('gccn1d',**kwargs)\n      with self.graph.as_default():\n        with tf.variable_scope('gccn1d'):#+postfix):\n                             \n          with self.graph.device(_dev_selector(arg1='foo')):\n            conv_linear = tf.keras.layers.Conv1D( channels_out, filter_size, padding='causal', name='conv_linear', use_bias=True)(signal_in)\n        \n          with self.graph.device(_dev_selector(arg1='foo')):\n            conv_gate = tf.sigmoid(tf.keras.layers.Conv1D( channels_out, filter_size, padding='causal', name='conv', use_bias=True )(signal_in),name='conv_sigmoid')\n        \n          with self.graph.device(_dev_selector(arg1='foo')):\n            gated_convolutions = tf.multiply(conv_linear,conv_gate,name='gated_convolutions') \n\n  def _residualgcnn1d(self, **kwargs):  \n    \n    try:\n        \n      channels_out = kwargs['channels_out']\n      filter_size = kwargs['filter_size']\n        \n    except KeyError:\n        \n      sys.exit('Parameters Not Defined Error')  \n  \n    signal_in = self(**kwargs)\n                               \n    \n      ####\n      ## Keras convolutions. Classes, so dont behave like functions but outputs Tensor, use its functions to query the variables filters and bias\n                             \n        # postfix = self.get_namepostfix('gccn1d',**kwargs)\n    with self.graph.as_default():\n      with tf.variable_scope('residualgccn1d'):#+postfix):                            \n                    \n        with self.graph.device(_dev_selector(arg1='foo')):            \n          conv_linear = tf.keras.layers.Conv1D( channels_out, filter_size, padding='causal', name='conv_linear', use_bias=True)(signal_in)\n        with self.graph.device(_dev_selector(arg1='foo')):        \n          conv_gate = tf.sigmoid(tf.keras.layers.Conv1D( channels_out, filter_size, padding='causal', name='conv', use_bias=True )(signal_in),name='conv_sigmoid')\n        with self.graph.device(_dev_selector(arg1='foo')):\n          gated_convolutions = tf.multiply(conv_linear,conv_gate,name='gated_convolutions')\n        \n      # Input channels must be the same size of the convolution channels output (ie number of filters applied)\n      with self.graph.device(_dev_selector(arg1='foo')):\n        residual = tf.add(gated_convolutions,signal_in,name='residual')\n        \n  def _save_trainable_vars(self, blockname):\n    with self.graph.as_default():   \n        \n        \n      saver = tf.train.Saver(var_list=self.graph.get_collection('trainable_variables') )      \n      tf.global_variables_initializer()\n        \n      sess = tf.Session(graph=self.graph)      \n      sess.run(self.graph.get_operations()[-1])   \n      saver.save(sess, os.getcwd()+'/'+blockname)\n      #saver.export_meta_graph(filename=blockname+'.constructor', collection_list='trainable_variables', export_scope=None, strip_default_attrs=False)\n      self.arch_blocks[blockname] = blockname\n        \n  def define_block(self,blockname):             \n    \n    self._save_trainable_vars(blockname)    \n    \n    graph = tf.Graph()\n    with graph.as_default():                                      \n      sess = tf.Session(graph=graph)  \n      \n      new_saver = tf.train.import_meta_graph(os.getcwd()+'/'+self.arch_blocks[blockname]+'.meta', import_scope = blockname)             \n      new_saver.restore(sess, os.getcwd()+'/'+self.arch_blocks[blockname])           \n      ####  \n      ## Redefinir signal_in dos blocos utilizados para construir este bloco atrav\u00e9s do dict namescopo\n      ## para que run_cgraph consiga achar inputs  \n      # \n        \n      ####\n      ## Signalin handling provisorio, fazer um modulo apenas para lidar com signal\n      #        \n      self.graph = graph\n      self.signal_in = []\n      self.signal_in.append(self.graph.get_tensor_by_name(blockname+'/signal_in:0'))  \n\n  # Build block from name in the top level of the blocks, this is a previous version that take names inside namescope dict and build new block  \n  def from_block(self,archblockname,tag = \"\"):\n        \n    with self.graph.as_default():              \n      sess = tf.Session(graph=self.graph)  \n\n      new_saver = tf.train.import_meta_graph(os.getcwd()+'/'+self.arch_blocks[archblockname]+'.meta', import_scope = archblockname+tag)        \n      new_saver.restore(sess, os.getcwd()+'/'+self.arch_blocks[archblockname])            \n      \n      self.signal_in.append(self.graph.get_tensor_by_name(archblockname+tag+'/signal_in:0'))\n      self.num_input -= 1 \n\n```\n\n##  Gated CNN\n  Gated CNN is a doubled CNN in whom one of the convoluted signals does the role of opening/closing the network, giving an **Attention Mechanism** to the convolution, for being activated by a sigmoid.\n  It gives non-vanishing gradient, since the multiplication rule for the derivative applies, also, applies gradient to the linear convoluted part.\n  \n\n### GCNN 1D Time Series\n  In time series version, since the desirable learning is based on **past** events, or you cannot uphold the assumption that you have acess to future data, have to make sure that the convolution is **causal**, that is\n\\begin{align}\ny_{n}= a_{i}x_{n-i}=a_{n-j}x_{j}\n\\end{align} \n  Giving at last, if the filter has length k, k-1 zero padding to the input x.\n\n\n```python\n#build graph\ngraph = build_graph( (None,l[0],channels), arch = 'gcnn1d',print_ops = True, new_graph=True, show_cgraph = True)\n'''\nobs: if you have a graph sometimes is necessary to run more than one time wit reset_default_graph to get a new graph\n'''\n```\n\n### GCNN 1D Residuals\n\n\n```python\n#build graph\ngraph = build_graph( (None,l[0],channels), arch = 'residual gcnn1d',print_ops = True,new_graph=True, show_cgraph = True)\n```\n\n# Hyper Param Protocol (hpp)\n\n\nTwo interfaces implementing the following:\n\nA - Space x Selection Algorithm x Architecture\n\n- Implementations of this interface specifies the search space for the Deep Learning model, including space size i.e. the number of points and space complexity that is objects to data dict (Variability)/structure/number of sources/Unique Ids (e.g. location). The Space Complex objects should be implement through his own interface.\n\nB - Space Complex\n\n- Central to space complexity are the specifications of the already given above. Once one have implemented the specification than can implement the Interface itself. \n\n\n```python\n#   HPP Definitions. First DISS  implementation by the already made architecture, brute force selection Algol, \n# and Space == Space Size.\n# TODO - refatorar.\n# TODO - full implementation\n\nclass Hpp:\n  '''\n   Hyperparam tuning protocol.\n   \n   Input\n   - space: Space object giving the size and the complexity of the space\n   - selection_algorithm: function running algorithm that search through space using specific evaluation (also implemented in the algorithm)\n   - architecture: Architecture object specifying archetipical architecture to be tuned by searching in space.\n  '''\n\n  def __init__(self,space = {},selection_algorithm = lambda x: 'foo',architecture='gcnn2d'):\n    \n    self.space_size = space.get_size()\n    self.data_structure = space.get_complex().data.get_structure()    \n    self.source_id = space.get_complex().get_ids()\n    self.data_dict = space.get_complex().data.get_dict()\n    self.algorithm = selection_algorithm\n    self.architecture = architecture\n    \n  def _parse_config(config_list):\n    '''\n      Receives a config and build from dict to perform  examples:\n      config0 = [ {\"0_frames\": lambda : 4 1 if 10 == 1 else 0,\"0_0\": lambda :(10,30,40,2), \"0_1\": lambda :(10,2,2,8), \"0_2\": lambda :(10,2,1,16), \"0_3\": lambda :(10,4,1,32), \"0_4\": lambda :(10,8,1,64), \"0_5\": lambda :(10,16,1,128), \"0_6\": lambda :(10,13,1,256)},{\"1_labels\": lambda :2},{\"2_null\": lambda :'a'},{\"3_labels\": lambda :2,\"3_learningrate\": lambda :0.005}]\n      config1 = [ {\"0_frames\":4,\"0_0\":(10,30,40,2)}, {\"1_1\":(10,2,2,8), \"1_2\":(10,2,1,16), \"1_3\":(10,4,1,32), \"1_4\":(10,8,1,64), \"1_5\":(10,8,1,64)},{\"1_labels\":2},{\"2_null\":a},{\"3_labels\":2,\"3_learningrate\":0.005}]\n      config2 = [ {\"0_frames\":4,\"0_0\":(10,30,40,2), \"0_1\":(10,2,2,8), \"0_2\":(10,2,1,16), \"0_3\":(10,4,1,32), \"0_4\":(10,8,1,64) },{\"1_labels\":2},{\"2_null\":a},{\"3_labels\":2,\"3_learningrate\":0.005}]      \n      config3 = [ {\"0_frames\":4,\"0_0\":(10,30,40,2), \"0_1\":(10,2,2,8), \"0_2\":(10,2,1,16), \"0_3\":(10,4,1,32) },{\"1_labels\":2},{\"2_null\":a},{\"3_labels\":2,\"3_learningrate\":0.005}]      \n      config4 = [ {\"0_frames\":4,\"0_0\":(10,30,40,2), \"0_1\":(10,2,2,8), \"0_2\":(10,2,1,16)},{\"1_labels\":2},{\"2_null\":a},{\"3_labels\":2,\"3_learningrate\":0.005}]      \n      config5 = [ {\"0_frames\":4,\"0_0\":(10,30,40,2), \"0_1\":(10,2,2,8)},{\"1_labels\":2},{\"2_null\":a},{\"3_labels\":2,\"3_learningrate\":0.005}]      \n      \n      config6 = [{\"0_frames\":4,\"0_0\":(10,30,40,2), \"0_1\":(10,2,2,8), \"0_2\":(10,6,1,16), \"0_3\":(10,6,1,32), \"0_4\":(10,6,1,64), \"0_5\":(10,10,1,128), \"0_6\":(10,16,1,256)},{\"1_labels\":2},{\"2_null\":a},{\"3_labels\":2,\"3_learningrate\":0.005}]\n      config7 = [ {\"0_frames\":4,\"0_0\":(10,30,40,2), \"0_1\":(10,2,2,8), \"0_2\":(10,6,1,16), \"0_3\":(10,6,1,32), \"0_4\":(10,6,1,64), \"0_5\":(10,10,1,128)},{\"1_labels\":2},{\"2_null\":a},{\"3_labels\":2,\"3_learningrate\":0.005}]      \n      config8 = [ {\"0_frames\":4,\"0_0\":(10,30,40,2), \"0_1\":(10,2,2,8), \"0_2\":(10,6,1,16), \"0_3\":(10,6,1,32), \"0_4\":(10,6,1,64)},{\"1_labels\":2},{\"2_null\":a},{\"3_labels\":2,\"3_learningrate\":0.005}]      \n      config9 = [ {\"0_frames\":4,\"0_0\":(10,30,40,2), \"0_1\":(10,2,2,8), \"0_2\":(10,6,1,16), \"0_3\":(10,6,1,32)},{\"1_labels\":2},{\"2_null\":a},{\"3_labels\":2,\"3_learningrate\":0.005}]      \n      config10 = [ {\"0_frames\":4,\"0_0\":(10,30,40,2), \"0_1\":(10,2,2,8), \"0_2\":(10,6,1,16)},{\"1_labels\":2},{\"2_null\":a},{\"3_labels\":2,\"3_learningrate\":0.005}]      \n      config11 = [ {\"0_frames\":4,\"0_0\":(10,30,40,2), \"0_1\":(10,2,2,8)},{\"1_labels\":2},{\"2_null\":a},{\"3_labels\":2,\"3_learningrate\":0.005}]\n    '''    \n    overall_config = []\n    overall_attr = []\n    overall_deepness = []\n    for block_config in config_list:        \n      layer_configs = []        \n      layer_attr = []\n      layer_deep = 0\n      # attributes       \n      bc = block_config.items()\n      for item in bc:\n        if item[0].split('_')[1].isalnum():\n          layer_configs.append(item)\n          layer_deep += 1\n        else:\n          layer_attr.append(item)\n      \n      layer_configs.sort()\n      layer_attr.sort()\n      \n      overall_deepness.append(layer_deep)\n      overall_config.append( dict(layer_configs) )\n      overall_attr.append( dict(layer_attr) )\n    \n    return overall_attr,overall_config,overall_deepness \n    \n  def _is_vec_embed():\n    pass\n\n  def run(self):    \n    '''\n    try: \n      assert type(tf.get_default_graph()) == type(tf.Graph())\n      graph = tf.get_default_graph()\n    except AssertionError:\n      graph = tf.Graph()         \n    ''' \n      \n    tf.reset_default_graph()\n    graph = tf.Graph()\n    s = 0\n    for config in range(self.algorithm.size):\n\n      s += 1\n      layer_config_list = self.algorithm()\n      overall_attr,overall_config,overall_deepness = _parse_config(layer_config_list)\n      \n      with tf.variable_scope('Config {}'.format(s)):                \n        \n        #TODO Assert that it is a block 0 and its attributes (for this case only nframe)            \n        \n        blockattr = overall_attr.pop(0)\n        nframe = blockattr.values()[0]        \n        config = overall_config.pop(0)     \n        \n        for blocks in range(len(self.architecture)):            \n          \n          graph = build_graph_module(graph, scope_tensor_name=op.name, arch = self.architecture[blocks], print_ops = True, name_scope = True, show_cgraph = True, filter_size=(k[1],k[2]), channels_out = k[3], deepness = '_d1',num_labels=2,learning_rate=0.005)\n          op = graph.get_operations()[-1]\n        \n          try:\n            blockattr = overall_attr[0]            \n            if blockattr.keys()[0].split('_')[0] == blocks:\n              blockattr = overall_attr.pop(0)\n              for attr,v in blockattr:\n                if attr.split('_')[1] == 'frames':\n                  nframes\n                \n          except:\n            pass                             \n          \n        for k in layer_config[2:]:\n\n            \n            \n            \n            '''\n        names = []\nfor op in graph.get_operations():\n    \n  if op.name.split('/')[1] == 'transpose_1' and op.name.split('/')[0][0:7] == 'softmax':\n    names.append(op.name)    \n\ngraph = build_graph_module(graph, scope_tensor_name=names, arch = 'reducemean',print_ops = True, name_scope = True, show_cgraph = True, filter_size=(2,1), channels_out = 64, deepness = '',num_labels=4,learning_rate=0.005, verbose=True)\nop = graph.get_operations()[-1]\ngraph = build_graph_module(graph, scope_tensor_name=op.name, arch = 'loss-crossentropy',print_ops = True, name_scope = True, show_cgraph = True, filter_size=(2,1), channels_out = 64, deepness = '',num_labels=4,learning_rate=0.1, batch=40, verbose=True)\n    \n    layer_config = self.algorithm()\n    with tf.variable_scope('secondparam'):\n        \n      graph = build_graph( (layer_config[0][0],layer_config[0][1],layer_config[0][2],layer_config[0][3]), arch = self.architecture,print_ops = True,new_graph=False, show_cgraph = True, filter_size=(layer_config[1][1],layer_config[1][2]), channels_out = layer_config[1][3])\n      op = graph.get_operations()[-1]\n      for k in layer_config[2:]:\n        graph = build_graph_module(graph, scope_tensor_name=op.name, arch = self.architecture, print_ops = True, name_scope = True, show_cgraph = True, filter_size=(k[1],k[2]), channels_out = k[3], deepness = '_d1',num_labels=2,learning_rate=0.005)\n        op = graph.get_operations()[-1]\n\n      '''\n    \n    \n    \n    \n    \nclass Space:\n  '''\n   Space is built upon space size and complexity.\n     \n   Input:\n   - size: an integer, the number of configurations to look for the model.      \n   - spacecomplex: Unique Ids, a hashable type or string specifing source e.g. location. A SigmaComplex object specifying meta-data, i.e. data configurations and \n   possibly other relevant keys to hyper-param searching such features, diversity mensures and so on.\n   SigmaComplex must be an interface to be implemented according to the data specification, possibly separating mutable from immutable characters.    \n  '''    \n    \n  def __init__(self, size, spacecomplex):\n    self.size = size\n    self.sigmacomplex = spacecomplex\n        \n  def get_size(self):\n    return self.size\n    \n  def get_complex(self):\n    return self.sigmacomplex\n        \n  def get_ids(self):\n    return  self.sigmacomplex.get_ids()\n    \n  def get_sourcenum(self):\n    return self.sigmacomplex.data.sourcenum\n\n  def get_dict(self):\n    return self.sigmacomplex.data.get_dict()\n\n  def get_structure(self):\n    return self.sigmacomplex.data.get_structure()\n\nclass SigmaComplex:\n  ''' \n      Unique Ids, a hashable type or string specifing source e.g. location. A SigmaComplex object specifying meta-data, i.e. data configurations and \n     possibly other relevant keys to hyper-param searching such features, diversity mensures and so on.\n     SigmaComplex must be an interface to be implemented according to the data specification, possibly separating mutable from immutable characters.    \n     \n     Data specification and ids will correspond to the empirical collected data according to the geo-located point in a device that has known inner workings\n     according to the laws of physics.\n  '''\n  def __init__(self, ids, data):\n    self.ids = ids\n    self.data = data   \n    \n    \n  def get_ids(self):\n    return  self.ids\n\n  def get_dict(self):\n    return self.data.get_dict()\n\n  def get_structure(self):\n    return self.data.get_structure()\n\nclass DataMeta:\n  '''\n   Data MaTter specification according to device collector, its inner workings (laws of physics), and other relevant keys.\n  '''  \n  def __init__(self):\n    \n    self.structure = \"image\"\n    self.data_dict = { \"labels\" : [\"cv\",\"sv\"] , \"features\" : [\"spect\",\"framed\"], \"channel_num\": 1 }\n    \n  def get_dict(self):\n    \n    return self.data_dict\n    \n  def get_structure(self):\n    \n    return self.structure\n```\n\n\n```python\n# Example of 'foo'\n\nspacecomplex = SigmaComplex([\"Chala-head-chala\"] , DataMeta())\nspace = Space( 5, spacecomplex)\nhyperparam = Hpp(space, lambda x: '\u98db\u8f2a\u529f', \"gcnn2d\")\n```\n\n\n```python\n#  Build search space data structure. To be added to SigmaComplex class/interface/template\n#  \"softmax\",\"reducemean\",\"loss-crossentropy\"\n\nconfig0 = [ {\"0_frames\":4,\"0_0\":(10,30,2,2), \"0_1\":(10,2,2,8), \"0_2\":(10,2,1,16), \"0_3\":(10,4,1,32), \"0_4\":(10,8,1,64), \"0_5\":(10,16,1,128), {\"1_labels\":2} ]\nconfig1 = [ {\"0_frames\":4,\"0_0\":(10,30,2,2), \"0_1\":(10,2,2,8), \"0_2\":(10,2,1,16), \"0_3\":(10,4,1,32)} ]\nconfig2 = [ {\"0_frames\":4,\"0_0\":(10,30,2,2), \"0_1\":(10,2,2,8) ]\nconfig3 = [ {\"0_frames\":4,\"0_0\":(10,30,2,2), \"0_1\":(10,4,2,8), \"0_2\":(10,4,1,16), \"0_3\":(10,4,1,32), \"0_4\":(10,4,1,64), \"0_5\":(10,7,1,128), \"0_6\":(10,7,1,256), \"0_7\":(10,7,1,512)}, {\"1_labels\":2},  ]\nsearch_space = ( config0,  config1) \n```\n\n\n```python\n# hash( '''( ( {\"0_sld\":4},{\"0_0\":(10,30.0,40.0)}),({\"1_sld\":3},{\"1_0\":(10,30.0,40.0,40.0)} ) )''' )\n# Example exhaustive search (\u6cb3\u5357\u79d1\u6280\u5927\u5b66)\n# you can use yield if you want to\nclass search(object):\n  def __init__(self, listconfig):\n    self.size = len(listconfig)\n    self.num = 0\n    self.config = listconfig\n   \n  def __iter__(self):\n    return self\n   \n       # Python 3 compatibility\n  def __next__(self):\n    return self.next()\n   \n  def next(self):\n    if self.num < self.size:\n      cur, self.num = self.config[self.num], self.num+1\n      return cur\n    else:\n      raise StopIteration()\n  def __call__(self):\n    return self.next()\n       \nspacecomplex = SigmaComplex([\"Chala-head-chala\"] , DataMeta())\nspace = Space( 5, spacecomplex)\n#TODO implementation of the Space->SigmaComplex->DataMeta()\nhyperparam = Hpp(space, search( search_space ), [\"gcnn2d\",\"softmax\",\"reducemean\",\"loss-crossentropy\"])\n```\n\n\n```python\n\n###\n## Danijar option to define scope with decorators\n#\n\ndef doublewrap(function):\n    \"\"\"\n    A decorator decorator, allowing to use the decorator to be used without\n    parentheses if no arguments are provided. All arguments must be optional.\n    \"\"\"\n    @functools.wraps(function)\n    def decorator(*args, **kwargs):\n        if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):\n            return function(args[0])\n        else:\n            return lambda wrapee: function(wrapee, *args, **kwargs)\n    return decorator\n\n\n@doublewrap\ndef define_scope(function, scope=None, *args, **kwargs):\n    \"\"\"\n    A decorator for functions that define TensorFlow operations. The wrapped\n    function will only be executed once. Subsequent calls to it will directly\n    return the result so that operations are added to the graph only once.\n    The operations added by the function live within a tf.variable_scope(). If\n    this decorator is used with arguments, they will be forwarded to the\n    variable scope. The scope name defaults to the name of the wrapped\n    function.\n    \"\"\"\n    attribute = '_cache_' + function.__name__\n    name = scope or function.__name__\n    @property\n    @functools.wraps(function)\n    def decorator(self):\n        if not hasattr(self, attribute):\n            with tf.variable_scope(name, *args, **kwargs):\n                setattr(self, attribute, function(self))\n        return getattr(self, attribute)\n    return decorator\n#####\n####\n##\n#\n```\n\n\n```python\ndef _calculate_lr_alpha(self, step):   \n   \n  self.lalpha = np.abs( (self.lossval[step] + self.lossval[step-1] + self.lossval[step-2] + self.lossval[step-3])/2.0 -self.lossval[step-4] -self.lossval[step-2])\n  print('l ',self.lalpha)\n  self.alpha = (self.lossval[step] - self.lossval[step-4])/self.lalpha\n  print('alpha ', self.alpha)\n```\n\n\n```python\n                        if len(self.logvarloss) >= 2:\n                \n            if self.logvarloss[-1] - self.logvarloss[-2] < - 1.0 and self.logvarloss[-1] - self.logvarloss[-2] > - 2.5:\n                \n              self.optimizer._lr = self.optimizer._lr + self.optimizer._lr/3.0\n                \n            elif self.logvarloss[-1] - self.logvarloss[-2] >  1.0 and self.logvarloss[-1] - self.logvarloss[-2] <  2.5:  \n                \n              self.optimizer._lr = self.optimizer._lr - self.optimizer._lr/3.0\n                \n            elif self.logvarloss[-1] - self.logvarloss[-2] < - 2.5:\n                \n              self.optimizer._lr = self.optimizer._lr + self.optimizer._lr/2.0\n                \n            elif self.logvarloss[-1] - self.logvarloss[-2] >  2.5:  \n                \n              self.optimizer._lr = self.optimizer._lr - self.optimizer._lr/2.0\n                \n            elif self.logvarloss[-1] - self.logvarloss[-2] < 1.0 and self.logvarloss[-1] - self.logvarloss[-2] > - 1.0:  \n                \n              self.optimizer._lr = self.optimizer._lr + self.optimizer._lr/2.0\n```\n", "meta": {"hexsha": "478005cb60ca4759c3e9880f1d39a1e161336cdc", "size": 32296, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/DNNStattus4APIDUMP.ipynb", "max_stars_repo_name": "Uiuran/stattus4-audio-models", "max_stars_repo_head_hexsha": "1ef4a9eca5d7540585c77d9fac85d5d4b3a7b07e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/DNNStattus4APIDUMP.ipynb", "max_issues_repo_name": "Uiuran/stattus4-audio-models", "max_issues_repo_head_hexsha": "1ef4a9eca5d7540585c77d9fac85d5d4b3a7b07e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/DNNStattus4APIDUMP.ipynb", "max_forks_repo_name": "Uiuran/stattus4-audio-models", "max_forks_repo_head_hexsha": "1ef4a9eca5d7540585c77d9fac85d5d4b3a7b07e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.423347398, "max_line_length": 581, "alphanum_fraction": 0.5411196433, "converted": true, "num_tokens": 6802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.03410042276746191, "lm_q1q2_score": 0.015061236218139332}}
{"text": "```python\n%matplotlib inline\nfrom matplotlib import pyplot as plt\nimport csv\nimport numpy as np\nimport pandas as pd\nimport json\nimport urllib\nimport cobra\n```\n\n\n```python\ncobra.__version__\n```\n\n\n\n\n    '0.13.4'\n\n\n\n\n```python\njson.load(urllib.request.urlopen('http://bigg.ucsd.edu/api/v2/database_version'))\n```\n\n\n\n\n    {'bigg_models_version': '1.3.0',\n     'api_version': 'v2',\n     'last_updated': '2018-02-24 08:16:33.924054'}\n\n\n\n\n```python\nwith open(\"../../Data/OrthoMCL/groups.txt\",'r') as f:\n    reader = csv.reader(f,delimiter=':')\n    line = next(reader)\n    print(line)    \n```\n\n    ['OG1000', ' cre|CRv4_Au5_s10_g545_t1 cre|CRv4_Au5_s10_g546_t1 cre|CRv4_Au5_s10_g547_t1 cre|CRv4_Au5_s10_g549_t1 cre|CRv4_Au5_s10_g549_t2 cre|CRv4_Au5_s10_g552_t1 cre|CRv4_Au5_s11_g2472_t1 cre|CRv4_Au5_s11_g2473_t1 cre|CRv4_Au5_s11_g2474_t1 cre|CRv4_Au5_s12_g3847_t1 cre|CRv4_Au5_s12_g3848_t1 cre|CRv4_Au5_s12_g3850_t1 cre|CRv4_Au5_s12_g3851_t1 cre|CRv4_Au5_s12_g3852_t1 cre|CRv4_Au5_s12_g3853_t1 cre|CRv4_Au5_s12_g3854_t1 cre|CRv4_Au5_s12_g3855_t1 cre|CRv4_Au5_s12_g3856_t1 cre|CRv4_Au5_s12_g3857_t1 cre|CRv4_Au5_s12_g4295_t1 cre|CRv4_Au5_s12_g4296_t1 cre|CRv4_Au5_s12_g4297_t1 cre|CRv4_Au5_s13_g4914_t1 cre|CRv4_Au5_s13_g5092_t1 cre|CRv4_Au5_s13_g5096_t1 cre|CRv4_Au5_s13_g5097_t1 cre|CRv4_Au5_s13_g5098_t1 cre|CRv4_Au5_s13_g5099_t1 cre|CRv4_Au5_s13_g5100_t1 cre|CRv4_Au5_s13_g5102_t1 cre|CRv4_Au5_s13_g5103_t1 cre|CRv4_Au5_s13_g5104_t1 cre|CRv4_Au5_s14_g5506_t1 cre|CRv4_Au5_s14_g5506_t2 cre|CRv4_Au5_s14_g5507_t1 cre|CRv4_Au5_s14_g5509_t1 cre|CRv4_Au5_s14_g5510_t1 cre|CRv4_Au5_s14_g5511_t1 cre|CRv4_Au5_s16_g6392_t1 cre|CRv4_Au5_s16_g6393_t1 cre|CRv4_Au5_s16_g6394_t1 cre|CRv4_Au5_s16_g6395_t1 cre|CRv4_Au5_s16_g6396_t1 cre|CRv4_Au5_s16_g6397_t1 cre|CRv4_Au5_s17_g7902_t1 cre|CRv4_Au5_s17_g7904_t1 cre|CRv4_Au5_s17_g7905_t1 cre|CRv4_Au5_s17_g7906_t1 cre|CRv4_Au5_s17_g7907_t1 cre|CRv4_Au5_s17_g7908_t1 cre|CRv4_Au5_s17_g7909_t1 cre|CRv4_Au5_s17_g7910_t1 cre|CRv4_Au5_s1_g1098_t1 cre|CRv4_Au5_s1_g1099_t1 cre|CRv4_Au5_s1_g1100_t1 cre|CRv4_Au5_s1_g1101_t1 cre|CRv4_Au5_s1_g1103_t1 cre|CRv4_Au5_s1_g2216_t1 cre|CRv4_Au5_s20_g8269_t1 cre|CRv4_Au5_s20_g8269_t2 cre|CRv4_Au5_s21_g9780_t1 cre|CRv4_Au5_s25_g9964_t1 cre|CRv4_Au5_s25_g9965_t1 cre|CRv4_Au5_s25_g9966_t1 cre|CRv4_Au5_s2_g8659_t1 cre|CRv4_Au5_s2_g8660_t1 cre|CRv4_Au5_s2_g8661_t1 cre|CRv4_Au5_s2_g8664_t1 cre|CRv4_Au5_s2_g8665_t1 cre|CRv4_Au5_s2_g8666_t1 cre|CRv4_Au5_s2_g9536_t1 cre|CRv4_Au5_s2_g9537_t1 cre|CRv4_Au5_s2_g9539_t1 cre|CRv4_Au5_s2_g9540_t1 cre|CRv4_Au5_s2_g9541_t1 cre|CRv4_Au5_s2_g9543_t1 cre|CRv4_Au5_s2_g9544_t1 cre|CRv4_Au5_s2_g9545_t1 cre|CRv4_Au5_s2_g9546_t1 cre|CRv4_Au5_s30_g10111_t1 cre|CRv4_Au5_s30_g10112_t1 cre|CRv4_Au5_s30_g10113_t1 cre|CRv4_Au5_s30_g10114_t1 cre|CRv4_Au5_s30_g10115_t1 cre|CRv4_Au5_s30_g10117_t1 cre|CRv4_Au5_s30_g10118_t1 cre|CRv4_Au5_s30_g10119_t1 cre|CRv4_Au5_s37_g11472_t1 cre|CRv4_Au5_s37_g11477_t1 cre|CRv4_Au5_s37_g11478_t1 cre|CRv4_Au5_s3_g11106_t1 cre|CRv4_Au5_s3_g11106_t2 cre|CRv4_Au5_s3_g11302_t1 cre|CRv4_Au5_s3_g11303_t1 cre|CRv4_Au5_s3_g11306_t1 cre|CRv4_Au5_s3_g11307_t1 cre|CRv4_Au5_s3_g11308_t1 cre|CRv4_Au5_s3_g11310_t1 cre|CRv4_Au5_s3_g11311_t1 cre|CRv4_Au5_s3_g11314_t1 cre|CRv4_Au5_s3_g11315_t1 cre|CRv4_Au5_s40_g11500_t1 cre|CRv4_Au5_s40_g11501_t1 cre|CRv4_Au5_s40_g11502_t1 cre|CRv4_Au5_s40_g11503_t1 cre|CRv4_Au5_s47_g11927_t1 cre|CRv4_Au5_s47_g11928_t1 cre|CRv4_Au5_s47_g11929_t1 cre|CRv4_Au5_s4_g11601_t1 cre|CRv4_Au5_s51_g12317_t1 cre|CRv4_Au5_s51_g12318_t1 cre|CRv4_Au5_s51_g12319_t1 cre|CRv4_Au5_s51_g12320_t1 cre|CRv4_Au5_s51_g12321_t1 cre|CRv4_Au5_s51_g12322_t1 cre|CRv4_Au5_s51_g12323_t1 cre|CRv4_Au5_s51_g12324_t1 cre|CRv4_Au5_s51_g12325_t1 cre|CRv4_Au5_s52_g12326_t1 cre|CRv4_Au5_s52_g12327_t1 cre|CRv4_Au5_s52_g12328_t1 cre|CRv4_Au5_s52_g12329_t1 cre|CRv4_Au5_s52_g12330_t1 cre|CRv4_Au5_s53_g12331_t1 cre|CRv4_Au5_s53_g12332_t1 cre|CRv4_Au5_s54_g12335_t1 cre|CRv4_Au5_s54_g12336_t1 cre|CRv4_Au5_s55_g12337_t1 cre|CRv4_Au5_s55_g12338_t1 cre|CRv4_Au5_s55_g12340_t1 cre|CRv4_Au5_s5_g12041_t1 cre|CRv4_Au5_s5_g12041_t2 cre|CRv4_Au5_s5_g12043_t1 cre|CRv4_Au5_s5_g12044_t1 cre|CRv4_Au5_s5_g12044_t2 cre|CRv4_Au5_s5_g12045_t1 cre|CRv4_Au5_s5_g12046_t1 cre|CRv4_Au5_s5_g12048_t1 cre|CRv4_Au5_s5_g12049_t1 cre|CRv4_Au5_s63_g13646_t1 cre|CRv4_Au5_s63_g13647_t1 cre|CRv4_Au5_s6_g12956_t1 cre|CRv4_Au5_s6_g12958_t1 cre|CRv4_Au5_s6_g12959_t1 cre|CRv4_Au5_s6_g12961_t1 cre|CRv4_Au5_s7_g14102_t1 cre|CRv4_Au5_s7_g14103_t1 cre|CRv4_Au5_s7_g14109_t1 cre|CRv4_Au5_s7_g14110_t1 cre|CRv4_Au5_s7_g14111_t1 cre|CRv4_Au5_s7_g14112_t1 cre|CRv4_Au5_s7_g14113_t1 cre|CRv4_Au5_s7_g14114_t1 cre|CRv4_Au5_s85_g15194_t1 cre|CRv4_Au5_s85_g15195_t1 cre|CRv4_Au5_s8_g14929_t1 cre|CRv4_Au5_s8_g14930_t1 cre|CRv4_Au5_s8_g14931_t1 cre|CRv4_Au5_s14_g5508_t1 cre|CRv4_Au5_s1_g1102_t1 cre|CRv4_Au5_s12_g3849_t1 cre|CRv4_Au5_s3_g11111_t1 cre|CRv4_Au5_s13_g5164_t1']\n\n\n\n```python\ngroups = dict()\nwith open(\"../../Data/OrthoMCL/groups.txt\",'r') as f:\n    for line in csv.reader(f,delimiter=':'):\n        x = line[0]\n        y = [z.strip() for z in line[1].split(' ') if z and not 'rton' in z]\n        if any('rtoi|' in z for z in y) and len(y) > 1:\n            groups[x] = y\n```\n\n\n```python\northologs = dict()\nfor v in groups.values():\n    x = [z for z in v if 'rtoi|' in z]\n    y = {z for z in v if 'rtoi|' not in z}\n    y = {z.replace('-','_') if 'sce|' in z else z for z in y}\n    for z in x:\n        orthologs[z] = y\nprint(len(orthologs))\n```\n\n    4316\n\n\n\n```python\n# OrthoMCL groups from the eLife paper \nwith open(\"../../Data/OrthoMCL/groups_Jeff.txt\",'r') as f:\n    reader = csv.reader(f,delimiter='\\t')\n    line = next(reader)\n    x = line[0]\n    temp = [line[i] for i in [3,4,5,6,13,25,26]]\n    print(x, temp)\n    line = next(reader)\n    line = next(reader)\n    line = next(reader)\n    x = line[0]\n    temp = [line[i] for i in [3,4,5,6,13,25,26]]\n    y = sum([z.split(',') for z in temp if z and not 'rton' in z],[])\n    print(x, temp, y)\n```\n\n    Orthogroup ['Anid', 'Lsta', 'Hsap', 'Mmus', 'RTO4', 'Ylip', 'Scer']\n    RTO3OG16703 ['AN6208', 'Lsta_2494,Lsta_5958', '', '', '', '', ''] ['AN6208', 'Lsta_2494', 'Lsta_5958']\n\n\n\n```python\ngroups_Jeff = dict()\nwith open(\"../../Data/OrthoMCL/groups_Jeff.txt\",'r') as f:\n    reader = csv.reader(f,delimiter='\\t')\n    line = next(reader)\n    for line in reader:\n        x = line[0]\n        temp = [line[i] for i in [3,4,5,6,13,25,26]]\n        temp[0] = temp[0].replace('AN','ani|AN')\n        temp[1] = temp[1].replace('Lsta_','lst|')\n        temp[2] = temp[2].replace('Hsap_','hsa|')\n        temp[3] = temp[3].replace('Mmus_','mmu|')\n        temp[4] = temp[4].replace('RTO4_','rtoi|')\n        temp[5] = temp[5].replace('YALI','yli|YALI')\n        temp[6] = temp[6].replace('Y','sce|Y').replace('-','_')\n        y = sum([z.split(',') for z in temp if z],[])\n        if any('rtoi|' in z for z in y) and len(y) > 1:\n            groups_Jeff[x] = y\n```\n\n\n```python\northologs_Jeff = dict()\nfor v in groups_Jeff.values():\n    x = [z for z in v if 'rtoi|' in z]\n    y = {z for z in v if 'rtoi|' not in z}\n    for z in x:\n        orthologs_Jeff[z] = y\nprint(len(orthologs_Jeff))\n```\n\n    4560\n\n\n\n```python\northologs_Jeff['rtoi|9326']\n```\n\n\n\n\n    {'ani|AN0887',\n     'lst|2765',\n     'lst|4946',\n     'sce|YBR208C',\n     'yli|YALI0E07271g',\n     'yli|YALI0E35156g'}\n\n\n\n\n```python\nsce = cobra.io.load_json_model(urllib.request.urlopen('http://bigg.ucsd.edu/static/models/iMM904.json'))\neco = cobra.io.load_json_model(urllib.request.urlopen('http://bigg.ucsd.edu/static/models/iML1515.json'))\nppu = cobra.io.load_json_model(urllib.request.urlopen('http://bigg.ucsd.edu/static/models/iJN746.json'))\ncre = cobra.io.load_json_model(urllib.request.urlopen('http://bigg.ucsd.edu/static/models/iRC1080.json'))\nhsa = cobra.io.load_json_model(urllib.request.urlopen('http://bigg.ucsd.edu/static/models/RECON1.json'))\nmmu = cobra.io.load_json_model(urllib.request.urlopen('http://bigg.ucsd.edu/static/models/iMM1415.json'))\n```\n\n\n```python\nhsa_dict = {x.name:x.id for x in hsa.genes if x.name}\nmmu_dict = {x.name:x.id for x in mmu.genes if x.name}\n```\n\n\n```python\nyli = cobra.io.load_json_model('../../Data/Other_models/iYL_2.0.json')\n```\n\n\n```python\nGene_to_reaction = dict()\nfor k, v in orthologs.items():\n    for z in v:\n        for m in ['sce','eco','ppu','cre','yli']:\n            if m in z:\n                if z.replace(m+'|','') in eval(m).genes:\n                    for x in eval(m).genes.get_by_id(z.replace(m+'|','')).reactions:\n                        Gene_to_reaction.setdefault(k, dict()).setdefault(x.id, set()).add(z)\nprint(len(Gene_to_reaction))\n```\n\n    1020\n\n\n\n```python\nGene_to_reaction_Jeff = dict()\nfor k, v in orthologs_Jeff.items():\n    for z in v:\n        for m in ['hsa','mmu']:\n            if m in z:\n                if (z.replace(m+'|','') in eval(m+'_dict')) and (eval(m+'_dict')[z.replace(m+'|','')] in eval(m).genes):\n                    for x in eval(m).genes.get_by_id(eval(m+'_dict')[z.replace(m+'|','')]).reactions:\n                        Gene_to_reaction_Jeff.setdefault(k, dict()).setdefault(x.id, set()).add(z)\n        for m in ['sce','yli']:\n            if m in z:\n                if z.replace(m+'|','') in eval(m).genes:\n                    for x in eval(m).genes.get_by_id(z.replace(m+'|','')).reactions:\n                        Gene_to_reaction_Jeff.setdefault(k, dict()).setdefault(x.id, set()).add(z)\nprint(len(Gene_to_reaction_Jeff))\n```\n\n    934\n\n\n\n```python\ntemp1 = set([y for y in Gene_to_reaction.keys()])\ntemp2 = set([y for y in Gene_to_reaction_Jeff.keys()])\nprint(len(temp1))\nprint(len(temp2))\nprint(len(temp1.union(temp2)))\nprint(len(temp1.intersection(temp2)))\nprint(len(temp1.difference(temp2)))\nprint(len(temp2.difference(temp1)))\n```\n\n    1020\n    934\n    1137\n    817\n    203\n    117\n\n\n\n```python\ntemp1 = set([y for z in Gene_to_reaction.values() for y in z])\ntemp2 = set([y for z in Gene_to_reaction_Jeff.values() for y in z])\nprint(len(temp1))\nprint(len(temp2))\nprint(len(temp1.union(temp2)))\nprint(len(temp1.intersection(temp2)))\nprint(len(temp1.difference(temp2)))\nprint(len(temp2.difference(temp1)))\n```\n\n    2995\n    2366\n    3804\n    1557\n    1438\n    809\n\n\n\n```python\nModel_rev = dict()\nfor m in ['sce','eco','ppu','yli','cre','hsa','mmu']:\n    for x in eval(m).reactions:\n        if x.lower_bound < 0 and x.upper_bound > 0:\n            temp = 'rev'\n        elif x.lower_bound == 0 and x.upper_bound > 0:\n            temp = 'for'\n        elif x.lower_bound < 0 and x.upper_bound == 0:\n            temp = 'back'\n        else:\n            print(m, x.id, x.lower_bound, x.upper_bound)\n            temp = 'for'\n        Model_rev.setdefault(x.id, dict())[m] = temp\n```\n\n    sce ATPM 1.0 1.0\n    eco FHL 0.0 0.0\n    eco ATPM 6.86 1000.0\n    ppu BIOMASS_KT_TEMP 1.0 1.4\n    cre PRISM_solar_litho 646.06656 646.06656\n    cre PRISM_solar_exo 417.5912 417.5912\n    cre PRISM_incandescent_60W 15.94176 15.94176\n    cre PRISM_fluorescent_warm_18W 8.09577 8.09577\n    cre PRISM_fluorescent_cool_215W 44.63332 44.63332\n    cre PRISM_metal_halide 17.5256 17.5256\n    cre PRISM_high_pressure_sodium 36.15037 36.15037\n    cre PRISM_growth_room 58.46722 58.46722\n    cre PRISM_white_LED 4.59151 4.59151\n    cre PRISM_red_LED_array_653nm 96.62811 96.62811\n    cre PRISM_red_LED_674nm 3.653 3.653\n    cre PRISM_design_growth 51.8841087821545 51.8841087821545\n    cre EX_hco3_e 0.0 0.0\n    cre EX_rib__D_e 0.0 0.0\n    cre EX_no2_e 0.0 0.0\n    cre EX_his__L_e 0.0 0.0\n    cre EX_urea_e 0.0 0.0\n    cre EX_ad_e 0.0 0.0\n    cre EX_gua_e 0.0 0.0\n    cre EX_ade_e 0.0 0.0\n    cre EX_alltt_e 0.0 0.0\n    cre EX_alltn_e 0.0 0.0\n    cre EX_hxan_e 0.0 0.0\n    cre EX_orn_e 0.0 0.0\n    cre EX_gln__L_e 0.0 0.0\n    cre EX_urate_e 0.0 0.0\n    cre EX_leu__L_e 0.0 0.0\n    cre EX_arg__L_e 0.0 0.0\n    cre EX_so3_e 0.0 0.0\n    cre EX_s_e 0.0 0.0\n    cre EX_slnt_e 0.0 0.0\n    cre EX_lac__D_e 0.0 0.0\n    cre EX_6mpur_e 0.0 0.0\n    cre EX_tgua_e 0.0 0.0\n    cre EX_tega_e 0.0 0.0\n    cre EX_5flura_e 0.0 0.0\n    cre EX_cital_e 0.0 0.0\n    cre EX_lido_e 0.0 0.0\n    cre ATPM 0.183 0.183\n    mmu DM_13_cis_oretn_n 0.0 0.0\n    mmu DM_13_cis_retn_n 0.0 0.0\n    mmu EX_retpalm_SPACE_deleted_SPACE_10_09_2005_SPACE_SPACE_06_COLON_18_COLON_49_SPACE_PM_e 0.0 0.0\n    mmu SK_citr__L_c 0.0 0.0\n    mmu CYOOm3 0.0 0.0\n    mmu L_LACtcm 0.0 0.0\n    mmu L_LACtm 0.0 0.0\n    mmu PIt2m 0.0 0.0\n    mmu THD1m 0.0 0.0\n\n\n\n```python\nReaction_to_gene = dict()\nReaction_rev = dict()\nReaction_comp = dict()\nfor k, v in orthologs.items():\n    for z in v:\n        for m in ['sce','eco','ppu','yli','cre']:\n            if m in z:\n                if z.replace(m+'|','') in eval(m).genes:\n                    for x in eval(m).genes.get_by_id(z.replace(m+'|','')).reactions:\n                        Reaction_to_gene.setdefault(x.id, dict()).setdefault(z, set()).add(k)\n                        if x.lower_bound < 0 and x.upper_bound > 0:\n                            temp = 'rev'\n                        elif x.lower_bound >= 0 and x.upper_bound > 0:\n                            temp = 'for'\n                        elif x.lower_bound < 0 and x.upper_bound == 0:\n                            temp = 'back'\n                        else:\n                            print(m, x.id, x.lower_bound, x.upper_bound)\n                            temp = 'for'\n                        Reaction_rev.setdefault(x.id, dict())[m] = temp\n                        Reaction_comp.setdefault(x.id, dict())[m] = x.compartments\nprint(len(Reaction_to_gene))\nprint(Reaction_to_gene['PGI'])\nprint(Reaction_rev['PGI'])\nprint(Reaction_comp['PGI'])\n```\n\n    eco FHL 0.0 0.0\n    2995\n    {'sce|YBR196C': {'rtoi|9589'}, 'eco|b4025': {'rtoi|9589'}, 'ppu|PP_1808': {'rtoi|9589'}}\n    {'sce': 'rev', 'eco': 'rev', 'ppu': 'rev'}\n    {'sce': {'c'}, 'eco': {'c'}, 'ppu': {'c'}}\n\n\n\n```python\nprint(sce.compartments)\nprint(eco.compartments)\nprint(ppu.compartments)\nprint(yli.compartments)\nprint(cre.compartments)\nprint(hsa.compartments)\nprint(mmu.compartments)\n```\n\n    {'c': 'cytosol', 'm': 'mitochondria', 'e': 'extracellular space', 'x': 'peroxisome/glyoxysome', 'r': 'endoplasmic reticulum', 'v': 'vacuole', 'n': 'nucleus', 'g': 'golgi apparatus'}\n    {'c': 'cytosol', 'e': 'extracellular space', 'p': 'periplasm'}\n    {'e': 'extracellular space', 'c': 'cytosol', 'p': 'periplasm'}\n    {'c': '', 'm': '', 'e': '', 'r': '', 'x': ''}\n    {'c': 'cytosol', 'h': 'chloroplast', 'm': 'mitochondria', 'x': 'peroxisome/glyoxysome', 'f': 'flagellum', 'e': 'extracellular space', 'n': 'nucleus', 'g': 'golgi apparatus', 's': 'eyespot', 'u': 'thylakoid'}\n    {'c': 'cytosol', 'e': 'extracellular space', 'l': 'lysosome', 'm': 'mitochondria', 'r': 'endoplasmic reticulum', 'n': 'nucleus', 'x': 'peroxisome/glyoxysome', 'g': 'golgi apparatus'}\n    {'c': 'cytosol', 'e': 'extracellular space', 'g': 'golgi apparatus', 'l': 'lysosome', 'm': 'mitochondria', 'n': 'nucleus', 'r': 'endoplasmic reticulum', 'x': 'peroxisome/glyoxysome'}\n\n\n\n```python\nprint(set(sum([list(x) for v in Reaction_comp.values() for x in v.values()],[])))\n```\n\n    {'c', 'e', 'm', 'u', 'f', 'n', 'h', 'g', 'p', 'x', 'r', 's', 'v'}\n\n\n\n```python\nfor k, v in Reaction_comp.items():\n    temp = sum([list(x) for x in v.values()],[])\n    if any(x in temp for x in ['p','f','h','s','u']):\n        print(k, v)\n```\n\n    CHLDA1tu {'cre': {'u', 'h'}}\n    CHLDA2tu {'cre': {'u', 'h'}}\n    CHYA2 {'cre': {'u'}}\n    ZHY {'cre': {'u'}}\n    COLIPAabcpp {'eco': {'c', 'p'}}\n    PA140abcpp {'eco': {'c', 'p'}}\n    PA141abcpp {'eco': {'c', 'p'}}\n    PE181abcpp {'eco': {'c', 'p'}, 'ppu': {'c', 'p'}}\n    PA161abcpp {'eco': {'c', 'p'}}\n    PE141abcpp {'eco': {'c', 'p'}}\n    PG120abcpp {'eco': {'c', 'p'}}\n    PE140abcpp {'eco': {'c', 'p'}}\n    PG161abcpp {'eco': {'c', 'p'}}\n    PA180abcpp {'eco': {'c', 'p'}}\n    PGP120abcpp {'eco': {'c', 'p'}, 'ppu': {'c', 'p'}}\n    PGP161abcpp {'eco': {'c', 'p'}, 'ppu': {'c', 'p'}}\n    PE180abcpp {'eco': {'c', 'p'}, 'ppu': {'c', 'p'}}\n    PE160abcpp {'eco': {'c', 'p'}, 'ppu': {'c', 'p'}}\n    PE120abcpp {'eco': {'c', 'p'}, 'ppu': {'c', 'p'}}\n    PE161abcpp {'eco': {'c', 'p'}, 'ppu': {'c', 'p'}}\n    PG160abcpp {'eco': {'c', 'p'}}\n    PGP181abcpp {'eco': {'c', 'p'}, 'ppu': {'c', 'p'}}\n    PGP140abcpp {'eco': {'c', 'p'}}\n    PA160abcpp {'eco': {'c', 'p'}}\n    PA120abcpp {'eco': {'c', 'p'}}\n    PG141abcpp {'eco': {'c', 'p'}}\n    PA181abcpp {'eco': {'c', 'p'}}\n    PG140abcpp {'eco': {'c', 'p'}}\n    LIPAabcpp {'eco': {'c', 'p'}}\n    PG180abcpp {'eco': {'c', 'p'}}\n    PG181abcpp {'eco': {'c', 'p'}}\n    LIPACabcpp {'eco': {'c', 'p'}}\n    PGP141abcpp {'eco': {'c', 'p'}}\n    K2L4Aabcpp {'eco': {'c', 'p'}}\n    PGP160abcpp {'eco': {'c', 'p'}, 'ppu': {'c', 'p'}}\n    PGP180abcpp {'eco': {'c', 'p'}, 'ppu': {'c', 'p'}}\n    NH4tpp {'eco': {'c', 'p'}, 'ppu': {'c', 'p'}}\n    GALth {'cre': {'c', 'h'}}\n    XYLt2pp {'eco': {'c', 'p'}}\n    PItf {'cre': {'c', 'f'}}\n    PINA1th {'cre': {'c', 'h'}}\n    APOR {'cre': {'h'}}\n    CYSS_trdrd {'cre': {'h'}}\n    TDSRh {'cre': {'h'}}\n    AHAL {'cre': {'h'}}\n    FACOAL141t2pp {'eco': {'c', 'p'}}\n    FACOAL181t2pp {'eco': {'c', 'p'}}\n    FACOAL60t2pp {'eco': {'c', 'p'}, 'ppu': {'c', 'p'}}\n    FACOAL120t2pp {'eco': {'c', 'p'}, 'ppu': {'c', 'p'}}\n    FACOAL100t2pp {'eco': {'c', 'p'}, 'ppu': {'c', 'p'}}\n    FACOAL80t2pp {'eco': {'c', 'p'}, 'ppu': {'c', 'p'}}\n    FACOAL161t2pp {'eco': {'c', 'p'}}\n    FACOAL160t2pp {'eco': {'c', 'p'}, 'ppu': {'c', 'p'}}\n    FACOAL180t2pp {'eco': {'c', 'p'}}\n    FACOAL140t2pp {'eco': {'c', 'p'}, 'ppu': {'c', 'p'}}\n    ALLTNt2rpp {'eco': {'c', 'p'}}\n    LYSt2pp {'eco': {'c', 'p'}}\n    NI2uabcpp {'eco': {'c', 'p'}}\n    MG2uabcpp {'eco': {'c', 'p'}}\n    ACNAMt2pp {'eco': {'c', 'p'}}\n    MDHh {'cre': {'h'}}\n    MDHf {'cre': {'f'}}\n    NA1th {'cre': {'c', 'h'}}\n    LACZpp {'eco': {'p'}}\n    4ABUTthi {'cre': {'c', 'h'}}\n    XANt2pp {'eco': {'c', 'p'}}\n    GUAt2pp {'eco': {'c', 'p'}}\n    ADEt2rpp {'eco': {'c', 'p'}}\n    CHOLSabc {'ppu': {'c', 'p'}}\n    ACALDh {'cre': {'h'}}\n    BNORh {'cre': {'h'}}\n    ARBt2rpp {'eco': {'c', 'p'}}\n    GLCt2pp {'eco': {'c', 'p'}}\n    GALt2pp {'eco': {'c', 'p'}}\n    PTRCthr {'cre': {'c', 'h'}}\n    CPS {'cre': {'h'}}\n    G3PD1 {'cre': {'h'}}\n    G3PD2_1 {'cre': {'h'}}\n    ACt2rpp {'eco': {'c', 'p'}}\n    SUCCt2_2pp {'eco': {'c', 'p'}}\n    TKT2h {'cre': {'h'}}\n    TKT1h {'cre': {'h'}}\n    ENOf {'cre': {'f'}}\n    3OAR160_1 {'cre': {'h'}}\n    3OAR100_1 {'cre': {'h'}}\n    3OAR120_1 {'cre': {'h'}}\n    3OAR60_1 {'cre': {'h'}}\n    3OAR180_1 {'cre': {'h'}}\n    3OAR140_1 {'cre': {'h'}}\n    3OAR40_1 {'cre': {'h'}}\n    3OAR80_1 {'cre': {'h'}}\n    3OAR181_1 {'cre': {'h'}}\n    HDHh {'cre': {'h'}}\n    PRACHh {'cre': {'h'}}\n    PRADPh {'cre': {'h'}}\n    CYSS_1 {'cre': {'h'}}\n    CHOLS_ex {'ppu': {'e', 'p'}}\n    THRA_1 {'cre': {'h'}}\n    CYANSTpp {'eco': {'p'}}\n    ACSERLh {'cre': {'h'}}\n    ACSERSULLh {'cre': {'h'}}\n    SULR_ferr {'cre': {'h'}}\n    NO2R {'cre': {'h'}}\n    Kt2pp {'eco': {'c', 'p'}}\n    G6PIh {'cre': {'h'}}\n    PGIBh {'cre': {'h'}}\n    PGIAh {'cre': {'h'}}\n    PGLYDH {'cre': {'h'}}\n    ASNNpp {'eco': {'p'}}\n    GLUNpp {'eco': {'p'}}\n    RPDPK {'cre': {'h'}}\n    PGLh {'cre': {'h'}}\n    CD2t3pp {'eco': {'c', 'p'}}\n    COBALT2t3pp {'eco': {'c', 'p'}}\n    ZN2t3pp {'eco': {'c', 'p'}}\n    NI2t3pp {'eco': {'c', 'p'}}\n    MN2t3pp {'eco': {'c', 'p'}}\n    ATNS {'cre': {'h'}}\n    ATNS_nh4 {'cre': {'h'}}\n    IGPS_1 {'cre': {'h'}}\n    DHQS_1 {'cre': {'h'}}\n    PSCIT {'cre': {'h'}}\n    STARCH300S {'cre': {'h'}}\n    UPPDC2_1 {'cre': {'h'}}\n    UPPDC1_1 {'cre': {'h'}}\n    PGDHh {'cre': {'h'}}\n    STARCH300DEGRA {'cre': {'h'}}\n    STARCH300DEGRB {'cre': {'h'}}\n    STARCH300DEGR2A {'cre': {'h'}}\n    STARCH300DEGR2B {'cre': {'h'}}\n    NA1Hth {'cre': {'c', 'h'}}\n    PPMh {'cre': {'h'}}\n    PGMTh {'cre': {'h'}}\n    PEPPIth {'cre': {'c', 'h'}}\n    INOSTt4pp {'eco': {'c', 'p'}}\n    CLt3_2pp {'eco': {'c', 'p'}}\n    TAh {'cre': {'h'}}\n    OCTh {'cre': {'h'}}\n    PPATDh {'cre': {'h'}}\n    PDHam1hi {'cre': {'h'}}\n    ACAS_2ahbut {'cre': {'h'}}\n    APLh {'cre': {'h'}}\n    PDHam2hi {'cre': {'h'}}\n    GTPDH {'cre': {'h'}}\n    R5PFL {'cre': {'h'}}\n    HSDH {'cre': {'h'}}\n    ASPK_1 {'cre': {'h'}}\n    MDDCP5pp {'eco': {'p'}}\n    MDDCP1pp {'eco': {'p'}}\n    MDDCP4pp {'eco': {'p'}}\n    MDDCP3pp {'eco': {'p'}}\n    MDDCP2pp {'eco': {'p'}}\n    GAPDHh {'cre': {'h'}}\n    PGPS18111Z160h {'cre': {'h'}}\n    PGPS1819Z160h {'cre': {'h'}}\n    IMGPSh {'cre': {'h'}}\n    PRICIh {'cre': {'h'}}\n    PRAICh {'cre': {'h'}}\n    SHSL2h {'cre': {'h'}}\n    G6PB_pi_th {'cre': {'c', 'h'}}\n    G3P_pi_thr {'cre': {'c', 'h'}}\n    3PG_pi_thr {'cre': {'c', 'h'}}\n    G1P_pi_th {'cre': {'c', 'h'}}\n    G6PA_pi_th {'cre': {'c', 'h'}}\n    DHAP_pi_thr {'cre': {'c', 'h'}}\n    2AGPG140tipp {'eco': {'c', 'p'}}\n    2AGPG120tipp {'eco': {'c', 'p'}}\n    2AGPG160tipp {'eco': {'c', 'p'}}\n    2AGPE140tipp {'eco': {'c', 'p'}}\n    2AGPA141tipp {'eco': {'c', 'p'}}\n    2AGPE160tipp {'eco': {'c', 'p'}}\n    2AGPE120tipp {'eco': {'c', 'p'}}\n    2AGPG141tipp {'eco': {'c', 'p'}}\n    2AGPE180tipp {'eco': {'c', 'p'}}\n    2AGPA140tipp {'eco': {'c', 'p'}}\n    2AGPG161tipp {'eco': {'c', 'p'}}\n    2AGPE141tipp {'eco': {'c', 'p'}}\n    2AGPA120tipp {'eco': {'c', 'p'}}\n    2AGPE161tipp {'eco': {'c', 'p'}}\n    2AGPE181tipp {'eco': {'c', 'p'}}\n    2AGPG180tipp {'eco': {'c', 'p'}}\n    2AGPA160tipp {'eco': {'c', 'p'}}\n    2AGPA161tipp {'eco': {'c', 'p'}}\n    2AGPA180tipp {'eco': {'c', 'p'}}\n    2AGPG181tipp {'eco': {'c', 'p'}}\n    2AGPA181tipp {'eco': {'c', 'p'}}\n    GLUS_ferr {'cre': {'h'}}\n    GLUS_nadph {'cre': {'h'}}\n    GLUS {'cre': {'h'}}\n    VALTLh {'cre': {'h'}}\n    ORDCh {'cre': {'h'}}\n    PEAMNOpp {'eco': {'p'}}\n    TYROXDApp {'eco': {'p'}}\n    42A12BOOXpp {'eco': {'p'}}\n    PAO {'cre': {'h'}}\n    HSK_1 {'cre': {'h'}}\n    CYSAT {'cre': {'h'}}\n    AATC {'cre': {'h'}}\n    POATh {'cre': {'h'}}\n    AATG {'cre': {'h'}}\n    ASPATh {'cre': {'h'}}\n    TYRTAh {'cre': {'h'}}\n    GDR_nadp_h {'cre': {'h'}}\n    GDRh {'cre': {'h'}}\n    TREHpp {'eco': {'p'}}\n    PPBNGD {'cre': {'h'}}\n    THRS_1 {'cre': {'h'}}\n    TAL {'cre': {'h'}}\n    THRAL {'cre': {'h'}}\n    FE2t2pp {'eco': {'c', 'p'}}\n    MNt2pp {'eco': {'c', 'p'}}\n    G3PL {'cre': {'h'}}\n    TRPS2h {'cre': {'h'}}\n    SERH {'cre': {'h'}}\n    PYKf {'cre': {'f'}}\n    IPPSh {'cre': {'h'}}\n    MALSh {'cre': {'h'}}\n    Ftpp {'eco': {'c', 'p'}}\n    RPEh {'cre': {'h'}}\n    AACPS4_1 {'cre': {'h'}}\n    FA100ACPHi_1 {'cre': {'h'}}\n    ACOATA_1 {'cre': {'h'}}\n    AACPS5_1 {'cre': {'h'}}\n    FA120ACPHi_1 {'cre': {'h'}}\n    ACP1819ZD9DS {'cre': {'h'}}\n    3HAD60_1 {'cre': {'h'}}\n    EAR180x_1 {'cre': {'h'}}\n    FA140ACPHi_1 {'cre': {'h'}}\n    ACP1619ZD9DS {'cre': {'h'}}\n    EAR100x_1 {'cre': {'h'}}\n    EAR100y_1 {'cre': {'h'}}\n    EAR120x_1 {'cre': {'h'}}\n    FA160ACPHi_1 {'cre': {'h'}}\n    AACPS6_1 {'cre': {'h'}}\n    EAR120y_1 {'cre': {'h'}}\n    EAR181x_1 {'cre': {'h'}}\n    EAR140x_1 {'cre': {'h'}}\n    EAR181y_1 {'cre': {'h'}}\n    EAR140y_1 {'cre': {'h'}}\n    EAR40x_1 {'cre': {'h'}}\n    G3PAT180h {'cre': {'h'}}\n    EAR160x_1 {'cre': {'h'}}\n    EAR160y_1 {'cre': {'h'}}\n    FA161ACPHi_1 {'cre': {'h'}}\n    FA180ACPHi {'cre': {'h'}}\n    FA1819ZACPH {'cre': {'h'}}\n    EAR40y_1 {'cre': {'h'}}\n    FA181ACPHi {'cre': {'h'}}\n    FA80ACPHi_1 {'cre': {'h'}}\n    G3PAT1819Zh {'cre': {'h'}}\n    G3PAT181h {'cre': {'h'}}\n    AGPAT1601819Zh {'cre': {'h'}}\n    3OAS100_1 {'cre': {'h'}}\n    3OAS120_1 {'cre': {'h'}}\n    AGPAT160h {'cre': {'h'}}\n    AGPAT1801819Zh {'cre': {'h'}}\n    3OAS140_1 {'cre': {'h'}}\n    AGPAT18111Z160h {'cre': {'h'}}\n    AGPAT18111Z1819Zh {'cre': {'h'}}\n    EAR60x_1 {'cre': {'h'}}\n    3OAS160_1 {'cre': {'h'}}\n    KAS14_1 {'cre': {'h'}}\n    AGPAT1819Z160h {'cre': {'h'}}\n    3HAD120_1 {'cre': {'h'}}\n    EAR60y_1 {'cre': {'h'}}\n    AGPAT1819Z1619Zh {'cre': {'h'}}\n    3OAS180_1 {'cre': {'h'}}\n    MCOATA_1 {'cre': {'h'}}\n    AGPAT1819Z18111Zh {'cre': {'h'}}\n    EAR80x_1 {'cre': {'h'}}\n    3OAS181_1 {'cre': {'h'}}\n    AGPAT1819Z1819Zh {'cre': {'h'}}\n    3HAD100_1 {'cre': {'h'}}\n    3HAD140_1 {'cre': {'h'}}\n    AACP1819ZS {'cre': {'h'}}\n    3HAD160_1 {'cre': {'h'}}\n    EAR80y_1 {'cre': {'h'}}\n    3OAS60_1 {'cre': {'h'}}\n    3HAD180_1 {'cre': {'h'}}\n    AACPS1_1 {'cre': {'h'}}\n    3OAS80_1 {'cre': {'h'}}\n    G3PAT160h {'cre': {'h'}}\n    3HAD181_1 {'cre': {'h'}}\n    3HAD40_1 {'cre': {'h'}}\n    AACPS3_1 {'cre': {'h'}}\n    ACPS1h {'cre': {'h'}}\n    3HAD80_1 {'cre': {'h'}}\n    ATPSh {'cre': {'u', 'h'}}\n    ATPS4rpp {'eco': {'c', 'p'}, 'ppu': {'c', 'p'}}\n    NA1ATPaseh {'cre': {'c', 'h'}}\n    CU1abcpp {'eco': {'c', 'p'}}\n    PPBNGS_1 {'cre': {'h'}}\n    BCRPTXANH {'cre': {'u'}}\n    CHYA1 {'cre': {'u'}}\n    BCAROH {'cre': {'u'}}\n    UPP3MT_1 {'cre': {'h'}}\n    PAPA1819Z18111Zh {'cre': {'h'}}\n    PAPA160h {'cre': {'h'}}\n    PAPA1819Z160h {'cre': {'h'}}\n    PAPA18111Z160h {'cre': {'h'}}\n    PAPA18111Z1819Zh {'cre': {'h'}}\n    PAPA1819Z1619Zh {'cre': {'h'}}\n    PAPA1819Z1819Zh {'cre': {'h'}}\n    PAPA1801819Zh {'cre': {'h'}}\n    PAPA1601819Zh {'cre': {'h'}}\n    RIBFS {'cre': {'h'}}\n    SSNOh {'cre': {'h'}}\n    PGLYCPh {'cre': {'h'}}\n    NAt3pp {'eco': {'c', 'p'}}\n    CA2t3pp {'eco': {'c', 'p'}}\n    Kt3pp {'eco': {'c', 'p'}}\n    MDHC_nadp_hr {'cre': {'h'}}\n    DGDGD7DS1829Z12Z1617Z {'cre': {'h'}}\n    MGDGD7DS1829Z12Z1617Z {'cre': {'h'}}\n    MGDGD7DS1819Z1617Z {'cre': {'h'}}\n    DGDGD7DS1819Z1617Z {'cre': {'h'}}\n    FAH1819Z {'cre': {'h'}}\n    FAH120 {'cre': {'h'}}\n    FAH1829Z12Z {'cre': {'h'}}\n    FAH140 {'cre': {'h'}}\n    FAH160 {'cre': {'h'}}\n    GLYALDtpp {'eco': {'c', 'p'}, 'ppu': {'c', 'p'}}\n    GLYCtpp {'eco': {'c', 'p'}, 'ppu': {'c', 'p'}}\n    UREAtpp {'eco': {'c', 'p'}}\n    GLYtpp {'eco': {'c', 'p'}}\n    ANTPPT {'cre': {'h'}}\n    KARI_23dhmp {'cre': {'h'}}\n    KARI_3hmoa {'cre': {'h'}}\n    KARI {'cre': {'h'}}\n    KARI_23dhmb {'cre': {'h'}}\n    DMORh {'cre': {'h'}}\n    BFBPh {'cre': {'h'}}\n    GTHAMPORh {'cre': {'h'}}\n    FGFTh {'cre': {'h'}}\n    FPGFTh {'cre': {'h'}}\n    DHPAH {'cre': {'h'}}\n    G3PO {'cre': {'h'}}\n    ACCOAhi {'cre': {'h'}}\n    BTNC {'cre': {'h'}}\n    ACCOAC_1 {'cre': {'h'}}\n    ADSSh {'cre': {'h'}}\n    PRAISh {'cre': {'h'}}\n    TCYG {'cre': {'h'}}\n    TCYD {'cre': {'h'}}\n    TPIh {'cre': {'h'}}\n    CYTP450Rh {'cre': {'h'}}\n    CHRS {'cre': {'h'}}\n    AOOAh {'cre': {'h'}}\n    PGKh {'cre': {'h'}}\n    CPPPGO_1 {'cre': {'h'}}\n    DLDLBT {'cre': {'h'}}\n    IGPDh {'cre': {'h'}}\n    ASADH {'cre': {'h'}}\n    PPRGLh {'cre': {'h'}}\n    RPIh {'cre': {'h'}}\n    PSAT {'cre': {'h'}}\n    PRFGSh {'cre': {'h'}}\n    SQDGS160 {'cre': {'h'}}\n    SQDGS18111Z160 {'cre': {'h'}}\n    SQDGS1819Z160 {'cre': {'h'}}\n    CDPDAGS18111Z160h {'cre': {'h'}}\n    CDPDAGS1819Z160h {'cre': {'h'}}\n    PGMf {'cre': {'f'}}\n    ASPth {'cre': {'c', 'h'}}\n    GLUth {'cre': {'c', 'h'}}\n    GLUKBh {'cre': {'h'}}\n    AM6PTh {'cre': {'h'}}\n    ABFPTh {'cre': {'h'}}\n    GLUKAh {'cre': {'h'}}\n    GLYCth {'cre': {'c', 'h'}}\n    NADH16pp {'eco': {'c', 'p'}, 'ppu': {'c', 'p'}}\n    NADH18pp {'eco': {'c', 'p'}}\n    NADH17pp {'eco': {'c', 'p'}}\n    3_4DHBZt2 {'ppu': {'e', 'p'}}\n    CYO1_KT {'ppu': {'c', 'p'}}\n    AASPh {'cre': {'h'}}\n    GTHRDHpp {'eco': {'p'}}\n    ALCDH_nadp_hi {'cre': {'h'}}\n    IDIh {'cre': {'h'}}\n    ACKrh {'cre': {'h'}}\n    APPTh {'cre': {'h'}}\n    2DHGLCNkt_tpp {'ppu': {'c', 'p'}}\n    IDPh {'cre': {'h'}}\n    DNGALh {'cre': {'h'}}\n    GLYPT {'cre': {'h'}}\n    TRETINOLPMTACT {'cre': {'s'}}\n    CRETINOLPMTACT {'cre': {'s'}}\n    RETINOLACACT {'cre': {'s'}}\n    CBL {'cre': {'h'}}\n    CTINBL {'cre': {'h'}}\n    SELCYSTLh {'cre': {'h'}}\n    CYSTBL {'cre': {'h'}}\n    HEMELh {'cre': {'h'}}\n    GTHS_1 {'cre': {'h'}}\n    DPHS {'cre': {'h'}}\n    PSIIblue {'cre': {'u'}}\n    PSIIred {'cre': {'u'}}\n    UDPGth {'cre': {'c', 'h'}}\n    UDPGALth {'cre': {'c', 'h'}}\n    ATDAMh {'cre': {'h'}}\n    ATAMh {'cre': {'h'}}\n    CHRM {'cre': {'h'}}\n    FPPSh {'cre': {'h'}}\n    GALM2pp {'eco': {'p'}}\n    AMETt2h {'cre': {'c', 'h'}}\n    PSCLYSt2pp {'eco': {'c', 'p'}}\n    FRULYSt2pp {'eco': {'c', 'p'}}\n    ACCOAth {'cre': {'c', 'h'}}\n    PPPGO_1 {'cre': {'h'}}\n    G2PPpp {'eco': {'p'}}\n    NTD2pp {'eco': {'p'}}\n    G1PPpp {'eco': {'p'}}\n    ACP1p {'eco': {'p'}}\n    3NTD7pp {'eco': {'p'}}\n    3NTD9pp {'eco': {'p'}}\n    3NTD2pp {'eco': {'p'}}\n    NTD7pp {'eco': {'p'}}\n    PPTHpp {'eco': {'p'}}\n    PSP_Lpp {'eco': {'p'}}\n    NTD4pp {'eco': {'p'}}\n    PTHRpp {'eco': {'p'}}\n    R5PPpp {'eco': {'p'}}\n    NTD9pp {'eco': {'p'}}\n    3NTD4pp {'eco': {'p'}}\n    PAPSPAPthr {'cre': {'c', 'h'}}\n    NO2th {'cre': {'c', 'h'}}\n    ASCBOR {'cre': {'u'}}\n    MDDEP4pp {'eco': {'p'}}\n    MDDEP2pp {'eco': {'p'}}\n    MDDEP1pp {'eco': {'p'}}\n    MDDEP3pp {'eco': {'p'}}\n    H2Othu {'cre': {'u', 'h'}}\n    H2Otf {'cre': {'c', 'f'}}\n    H2Oth {'cre': {'c', 'h'}}\n    ZAXANOR {'cre': {'u'}}\n    ANXANOR {'cre': {'u'}}\n    TFENFEOR {'cre': {'h'}}\n    FUCtpp {'eco': {'c', 'p'}}\n\n\n\n```python\n# remove reactions in irrelevant compartments now?\nReaction_subset = dict()\nfor k, v in Reaction_comp.items():\n    temp = sum([list(x) for x in v.values()],[])\n    if not any(x in temp for x in ['p','f','h','s','u']):\n        Reaction_subset.setdefault(k,str())\n# keep them now and remove or change compartment later\n    else:\n        Reaction_subset.setdefault(k,str())        \nprint(len(Reaction_subset))\n```\n\n    2995\n\n\n\n```python\nfor k, v in sorted(Reaction_rev.items()):\n    if k in Reaction_subset: \n        if len(set(v.values())) > 1:\n            print(k, v)\n```\n\n    ABTA {'ppu': 'rev', 'eco': 'for', 'yli': 'rev', 'sce': 'for'}\n    ACACT1r {'sce': 'for', 'eco': 'rev', 'yli': 'for', 'cre': 'for'}\n    ACACT2r {'ppu': 'back', 'eco': 'rev'}\n    ACACT3r {'ppu': 'back', 'eco': 'rev'}\n    ACACT4m {'yli': 'back', 'cre': 'for'}\n    ACACT4p {'sce': 'for', 'cre': 'rev'}\n    ACACT4r {'ppu': 'back', 'eco': 'rev'}\n    ACACT5p {'sce': 'for', 'cre': 'rev'}\n    ACACT5r {'ppu': 'back', 'eco': 'rev'}\n    ACACT6m {'yli': 'back', 'cre': 'for'}\n    ACACT6p {'sce': 'for', 'cre': 'rev'}\n    ACACT6r {'ppu': 'back', 'eco': 'rev'}\n    ACACT7m {'yli': 'back', 'cre': 'for'}\n    ACACT7p {'sce': 'for', 'cre': 'rev'}\n    ACACT7r {'ppu': 'back', 'eco': 'rev'}\n    ACALD {'eco': 'rev', 'cre': 'for'}\n    ACCOAC {'ppu': 'rev', 'eco': 'for', 'sce': 'rev', 'yli': 'rev'}\n    ACGAM6PS {'cre': 'for', 'sce': 'rev', 'yli': 'for'}\n    ACOAHim {'yli': 'back', 'sce': 'for'}\n    ACOATA {'eco': 'rev', 'sce': 'rev', 'yli': 'for'}\n    ACOTAim {'yli': 'for', 'sce': 'for', 'cre': 'rev'}\n    ACS {'cre': 'for', 'sce': 'for', 'ppu': 'rev', 'yli': 'for', 'eco': 'for'}\n    ADK1 {'yli': 'rev', 'eco': 'rev', 'cre': 'for', 'ppu': 'rev', 'sce': 'rev'}\n    ADK1m {'cre': 'for', 'sce': 'rev'}\n    ADNK1 {'eco': 'for', 'yli': 'rev', 'sce': 'for', 'cre': 'for'}\n    ADPT {'yli': 'for', 'sce': 'for', 'ppu': 'for', 'eco': 'for', 'cre': 'rev'}\n    AGPR {'eco': 'rev', 'cre': 'back'}\n    AHCi {'cre': 'rev', 'sce': 'for', 'yli': 'for'}\n    AHSERL2 {'yli': 'for', 'ppu': 'rev', 'sce': 'for'}\n    AKGDam {'cre': 'for', 'sce': 'rev'}\n    ALCD19y {'sce': 'for', 'cre': 'rev'}\n    ALLTN {'sce': 'rev', 'eco': 'for'}\n    AMPTASECG {'yli': 'rev', 'eco': 'for'}\n    ANPRT {'eco': 'for', 'sce': 'for', 'ppu': 'for', 'yli': 'rev'}\n    AOXSr2 {'eco': 'for', 'yli': 'rev'}\n    ARGSS {'ppu': 'for', 'eco': 'for', 'sce': 'rev'}\n    ASPK {'eco': 'rev', 'yli': 'for', 'sce': 'for', 'ppu': 'for'}\n    ATHRDHr {'yli': 'for', 'eco': 'rev', 'sce': 'rev'}\n    ATPPRT {'yli': 'for', 'ppu': 'rev', 'eco': 'for', 'sce': 'for'}\n    C14STR {'cre': 'rev', 'sce': 'for'}\n    CHORM {'eco': 'for', 'ppu': 'for', 'yli': 'rev', 'sce': 'for'}\n    CYSTA {'yli': 'rev', 'eco': 'for'}\n    CYSTGL {'yli': 'rev', 'sce': 'for', 'ppu': 'rev'}\n    CYTK1 {'cre': 'for', 'yli': 'rev'}\n    CYTK2 {'cre': 'for', 'yli': 'rev'}\n    DADK {'yli': 'rev', 'eco': 'rev', 'cre': 'for', 'ppu': 'rev'}\n    DGK1 {'eco': 'rev', 'ppu': 'rev', 'cre': 'for', 'sce': 'rev', 'yli': 'rev'}\n    DHORDfum {'yli': 'rev', 'sce': 'for'}\n    DHORDi {'ppu': 'rev', 'sce': 'for'}\n    DHQTi {'sce': 'for', 'yli': 'rev', 'ppu': 'rev'}\n    DPRm {'sce': 'for', 'cre': 'rev', 'yli': 'for'}\n    DTMPK {'sce': 'rev', 'cre': 'for', 'yli': 'rev', 'eco': 'rev'}\n    DURIPP {'yli': 'for', 'sce': 'rev', 'eco': 'rev'}\n    ECOAH1 {'ppu': 'rev', 'yli': 'back', 'cre': 'rev'}\n    ECOAH1m {'yli': 'back', 'cre': 'rev'}\n    FACOAL160 {'sce': 'rev', 'cre': 'for', 'yli': 'rev'}\n    FALDH2 {'eco': 'rev', 'yli': 'for'}\n    G6PDH2r {'ppu': 'for', 'sce': 'for', 'eco': 'rev'}\n    GALKr {'yli': 'for', 'eco': 'rev', 'cre': 'for', 'sce': 'for'}\n    GALUi {'yli': 'rev', 'cre': 'for', 'sce': 'rev'}\n    GARFT {'eco': 'rev', 'ppu': 'rev', 'sce': 'for', 'cre': 'rev', 'yli': 'for'}\n    GCCbim {'sce': 'for', 'yli': 'rev'}\n    GCCcm {'sce': 'rev', 'cre': 'for', 'yli': 'rev'}\n    GK1 {'eco': 'rev', 'ppu': 'rev', 'cre': 'for', 'sce': 'rev', 'yli': 'rev'}\n    GLUDy {'sce': 'back', 'ppu': 'rev', 'eco': 'rev', 'yli': 'back'}\n    GLYCLm {'sce': 'for', 'cre': 'back', 'yli': 'back'}\n    GTHOr {'sce': 'for', 'cre': 'for', 'ppu': 'for', 'eco': 'rev'}\n    GTHPi {'sce': 'rev', 'cre': 'for', 'eco': 'for', 'ppu': 'rev', 'yli': 'for'}\n    GTHPm {'yli': 'for', 'sce': 'rev'}\n    HPYRRy {'eco': 'for', 'cre': 'rev'}\n    HSDxi {'ppu': 'rev', 'sce': 'for', 'yli': 'rev'}\n    HSDy {'eco': 'rev', 'sce': 'back', 'yli': 'rev'}\n    HSERTA {'sce': 'rev', 'yli': 'for', 'ppu': 'rev'}\n    HSTPT {'sce': 'for', 'cre': 'rev', 'ppu': 'rev', 'eco': 'for', 'yli': 'rev'}\n    ICDHyr {'yli': 'for', 'cre': 'rev', 'sce': 'for', 'eco': 'rev', 'ppu': 'rev'}\n    IGPS {'yli': 'rev', 'ppu': 'for', 'sce': 'for', 'eco': 'for'}\n    IPDDI {'eco': 'rev', 'sce': 'rev', 'cre': 'for', 'yli': 'rev'}\n    IPMD {'ppu': 'rev', 'eco': 'for', 'sce': 'for', 'cre': 'for'}\n    KARA1im {'cre': 'for', 'sce': 'for', 'yli': 'rev'}\n    KARA2im {'sce': 'for', 'yli': 'rev'}\n    LNS14DM {'sce': 'for', 'cre': 'rev'}\n    MDH {'ppu': 'rev', 'yli': 'for', 'eco': 'rev'}\n    MHPGLUT {'ppu': 'rev', 'sce': 'for', 'yli': 'for'}\n    MMTSAO {'ppu': 'for', 'yli': 'rev'}\n    MTHFD {'sce': 'rev', 'yli': 'for', 'eco': 'rev', 'ppu': 'rev'}\n    NDPK1 {'yli': 'rev', 'eco': 'rev', 'sce': 'rev', 'cre': 'for', 'ppu': 'rev'}\n    NDPK2 {'yli': 'rev', 'eco': 'rev', 'sce': 'rev', 'cre': 'for', 'ppu': 'rev'}\n    NDPK3 {'yli': 'rev', 'eco': 'rev', 'sce': 'rev', 'cre': 'for', 'ppu': 'rev'}\n    NDPK4 {'yli': 'rev', 'eco': 'rev', 'sce': 'rev', 'cre': 'for', 'ppu': 'rev'}\n    NDPK5 {'yli': 'rev', 'eco': 'rev', 'sce': 'rev', 'cre': 'for', 'ppu': 'rev'}\n    NDPK6 {'yli': 'rev', 'eco': 'rev', 'sce': 'rev', 'cre': 'for', 'ppu': 'rev'}\n    NDPK7 {'yli': 'rev', 'eco': 'rev', 'sce': 'rev', 'cre': 'for', 'ppu': 'rev'}\n    NDPK8 {'yli': 'rev', 'eco': 'rev', 'sce': 'rev', 'cre': 'for', 'ppu': 'rev'}\n    NDPK9 {'yli': 'rev', 'sce': 'rev', 'cre': 'for'}\n    NNAM {'yli': 'for', 'cre': 'for', 'sce': 'rev', 'eco': 'for'}\n    NNATr {'sce': 'for', 'cre': 'rev'}\n    NTP10 {'cre': 'back', 'yli': 'for'}\n    OCBT {'eco': 'rev', 'ppu': 'rev', 'sce': 'for'}\n    OCOAT1 {'ppu': 'for', 'yli': 'rev'}\n    ORNTACim {'yli': 'rev', 'sce': 'for'}\n    PC {'ppu': 'for', 'cre': 'rev', 'yli': 'for', 'sce': 'for'}\n    PDX5POi {'sce': 'rev', 'ppu': 'for', 'yli': 'for', 'eco': 'for', 'cre': 'for'}\n    PGCD {'ppu': 'rev', 'sce': 'for', 'eco': 'for', 'yli': 'for'}\n    PPGPPDP {'cre': 'rev', 'ppu': 'for', 'eco': 'for'}\n    PPNDH {'sce': 'for', 'eco': 'for', 'ppu': 'for', 'yli': 'rev', 'cre': 'for'}\n    PRAGSr {'eco': 'rev', 'sce': 'rev', 'yli': 'for', 'ppu': 'for'}\n    PRASCSi {'ppu': 'rev', 'sce': 'rev', 'cre': 'for', 'eco': 'for'}\n    PRPPS {'sce': 'rev', 'eco': 'rev', 'cre': 'for', 'ppu': 'rev'}\n    PSCVT {'sce': 'for', 'ppu': 'rev', 'eco': 'rev', 'yli': 'rev'}\n    PSERT {'yli': 'rev', 'eco': 'for', 'ppu': 'rev', 'sce': 'for'}\n    PYDXNO {'sce': 'rev', 'yli': 'for', 'cre': 'for'}\n    PYDXO_1 {'yli': 'rev', 'cre': 'for'}\n    RBK {'sce': 'for', 'eco': 'for', 'cre': 'for', 'ppu': 'rev'}\n    SERD_L {'yli': 'for', 'ppu': 'rev', 'eco': 'for', 'sce': 'for'}\n    SFGTHi {'eco': 'for', 'sce': 'rev', 'yli': 'for'}\n    SHSL2r {'yli': 'for', 'ppu': 'rev'}\n    SMO {'cre': 'rev', 'yli': 'for'}\n    SSALy {'yli': 'for', 'sce': 'for', 'ppu': 'rev', 'eco': 'for'}\n    SUCD1m {'sce': 'rev', 'yli': 'rev', 'cre': 'for'}\n    SUCFUMtm {'sce': 'for', 'yli': 'for', 'cre': 'rev'}\n    SULR {'sce': 'rev', 'ppu': 'for', 'eco': 'for', 'yli': 'for'}\n    THRA {'eco': 'for', 'ppu': 'rev', 'sce': 'for', 'yli': 'rev'}\n    THRA2 {'eco': 'for', 'ppu': 'rev', 'sce': 'for', 'yli': 'rev'}\n    TMDS {'sce': 'for', 'yli': 'for', 'ppu': 'for', 'eco': 'for', 'cre': 'rev'}\n    TRPS1 {'yli': 'for', 'sce': 'for', 'eco': 'for', 'ppu': 'rev'}\n    TRPTA {'sce': 'rev', 'yli': 'for'}\n    TYRTAi {'sce': 'for', 'cre': 'rev'}\n    UDPGD {'eco': 'for', 'cre': 'for', 'yli': 'rev'}\n    UGLYCH {'yli': 'rev', 'sce': 'rev', 'eco': 'for'}\n    UMPK {'cre': 'for', 'sce': 'rev', 'yli': 'rev'}\n    UPPRT {'cre': 'rev', 'eco': 'for', 'ppu': 'for', 'yli': 'for', 'sce': 'for'}\n    URIDK2r {'cre': 'for', 'yli': 'rev', 'sce': 'rev'}\n    VALTAim {'sce': 'for', 'cre': 'rev', 'yli': 'rev'}\n    XPPT {'sce': 'for', 'cre': 'rev'}\n    XYLTD_D {'sce': 'for', 'yli': 'rev'}\n\n\n\n```python\nfor k, v in Reaction_rev.items():\n    if k in Reaction_subset:\n        if len(set(v.values())) > 1:\n            if 'eco' in v:\n                Reaction_subset[k] = ('eco',v['eco'])\n            elif 'sce' in v:\n                Reaction_subset[k] = ('sce',v['sce'])\n            elif 'ppu' in v:\n                Reaction_subset[k] = ('ppu',v['ppu'])\n            else:\n                print(k, v)\n                Reaction_subset[k] = ('yli',v['yli'])\n        else:\n            if 'eco' in v:\n                Reaction_subset[k] = ('eco',v['eco'])\n            elif 'sce' in v:\n                Reaction_subset[k] = ('sce',v['sce'])\n            elif 'ppu' in v:\n                Reaction_subset[k] = ('ppu',v['ppu'])\n            elif 'cre' in v:\n                Reaction_subset[k] = ('cre',v['cre'])\n            elif 'yli' in v:\n                Reaction_subset[k] = ('yli',v['yli'])\n            else:\n                print(k, v)\n```\n\n    ACACT4m {'yli': 'back', 'cre': 'for'}\n    ACACT6m {'yli': 'back', 'cre': 'for'}\n    ACACT7m {'yli': 'back', 'cre': 'for'}\n    ECOAH1m {'yli': 'back', 'cre': 'rev'}\n    NTP10 {'cre': 'back', 'yli': 'for'}\n    PYDXO_1 {'yli': 'rev', 'cre': 'for'}\n    SMO {'cre': 'rev', 'yli': 'for'}\n    CYTK1 {'cre': 'for', 'yli': 'rev'}\n    CYTK2 {'cre': 'for', 'yli': 'rev'}\n\n\n\n```python\nfor k, v in Reaction_subset.items():\n    if k in eco.reactions:\n        if not Model_rev[k]['eco'] == v[1]:\n            print(k, v, 'eco', Model_rev[k]['eco'])\n    elif k in sce.reactions:\n        if not Model_rev[k]['sce'] == v[1]:\n            print(k, v, 'sce', Model_rev[k]['sce'])\n```\n\n    TYRTAim ('cre', 'rev') sce for\n    SHK3Dr ('sce', 'for') eco rev\n    PRMICI ('sce', 'for') eco rev\n    FA141ACPHi ('sce', 'rev') eco for\n    FA120ACPHi ('sce', 'rev') eco for\n    FA160ACPHi ('sce', 'rev') eco for\n    FA140ACPHi ('sce', 'rev') eco for\n    FA161ACPHi ('sce', 'rev') eco for\n    DHFR ('cre', 'for') eco rev\n    ASAD ('sce', 'back') eco rev\n    NNATr ('sce', 'for') eco rev\n    CYSDS ('yli', 'rev') eco for\n    MTRI ('cre', 'for') sce rev\n    ACOAD1f ('ppu', 'rev') eco for\n    PTPATi ('yli', 'rev') eco for\n    PTPATim ('yli', 'rev') sce for\n    HXPRT ('cre', 'rev') eco for\n    GALUi ('sce', 'rev') eco for\n    UAGDP ('cre', 'rev') eco for\n    LALDO2x ('cre', 'rev') eco for\n    AP4AH ('sce', 'rev') eco for\n\n\n\n```python\nfor k, v in Reaction_subset.items():\n    if k in eco.reactions:\n        if not Model_rev[k]['eco'] == v[1]:\n            Reaction_subset[k] = ('eco', Model_rev[k]['eco'])\n    elif k in sce.reactions:\n        if not Model_rev[k]['sce'] == v[1]:\n            Reaction_subset[k] = ('sce', Model_rev[k]['sce'])\n```\n\n\n```python\nReaction_to_gene_Jeff = dict()\nReaction_rev_Jeff = dict()\nReaction_comp_Jeff = dict()\n\nfor k, v in orthologs_Jeff.items():\n    for z in v:\n        for m in ['hsa','mmu']:\n            if m in z:\n                if (z.replace(m+'|','') in eval(m+'_dict')) and (eval(m+'_dict')[z.replace(m+'|','')] in eval(m).genes):\n                    for x in eval(m).genes.get_by_id(eval(m+'_dict')[z.replace(m+'|','')]).reactions:\n                        Reaction_to_gene_Jeff.setdefault(x.id, dict()).setdefault(z, set()).add(k)\n                        if x.lower_bound < 0 and x.upper_bound > 0:\n                            temp = 'rev'\n                        elif x.lower_bound >= 0 and x.upper_bound > 0:\n                            temp = 'for'\n                        elif x.lower_bound < 0 and x.upper_bound == 0:\n                            temp = 'back'\n                        else:\n                            print(m, x.id, x.lower_bound, x.upper_bound)\n                            temp = 'for'\n                        Reaction_rev_Jeff.setdefault(x.id, dict())[m] = temp\n                        Reaction_comp_Jeff.setdefault(x.id, dict())[m] = x.compartments\n        for m in ['sce','yli']:\n            if m in z:\n                if z.replace(m+'|','') in eval(m).genes:\n                    for x in eval(m).genes.get_by_id(z.replace(m+'|','')).reactions:\n                        Reaction_to_gene_Jeff.setdefault(x.id, dict()).setdefault(z, set()).add(k)\n                        if x.lower_bound < 0 and x.upper_bound > 0:\n                            temp = 'rev'\n                        elif x.lower_bound >= 0 and x.upper_bound > 0:\n                            temp = 'for'\n                        elif x.lower_bound < 0 and x.upper_bound == 0:\n                            temp = 'back'\n                        else:\n                            print(m, x.id, x.lower_bound, x.upper_bound)\n                            temp = 'for'\n                        Reaction_rev_Jeff.setdefault(x.id, dict())[m] = temp\n                        Reaction_comp_Jeff.setdefault(x.id, dict())[m] = x.compartments\n                        \nprint(len(Reaction_to_gene_Jeff))\nprint(Reaction_to_gene_Jeff['PGI'])\nprint(Reaction_rev_Jeff['PGI'])\nprint(Reaction_comp_Jeff['PGI'])\n```\n\n    mmu PIt2m 0.0 0.0\n    mmu PIt2m 0.0 0.0\n    mmu L_LACtcm 0.0 0.0\n    2366\n    {'sce|YBR196C': {'rtoi|9589'}, 'mmu|Gpi1': {'rtoi|9589'}, 'hsa|GPI': {'rtoi|9589'}}\n    {'sce': 'rev', 'mmu': 'rev', 'hsa': 'rev'}\n    {'sce': {'c'}, 'mmu': {'c'}, 'hsa': {'c'}}\n\n\n\n```python\nprint(set(sum([list(x) for v in Reaction_comp_Jeff.values() for x in v.values()],[])))\n```\n\n    {'c', 'e', 'm', 'n', 'l', 'g', 'x', 'r', 'v'}\n\n\n\n```python\nfor k, v in Reaction_comp_Jeff.items():\n    temp = sum([list(x) for x in v.values()],[])\n    if any(x in temp for x in ['l']):\n        print(k, v)\n```\n\n    ATPasel {'hsa': {'c', 'l'}, 'mmu': {'c', 'l'}}\n    B_MANNASEly {'hsa': {'l'}, 'mmu': {'l'}}\n    DALAt2rL {'mmu': {'c', 'l'}, 'hsa': {'c', 'l'}}\n    PROt2rL {'mmu': {'c', 'l'}, 'hsa': {'c', 'l'}}\n    PRODt2rL {'mmu': {'c', 'l'}, 'hsa': {'c', 'l'}}\n    ABUTt2rL {'mmu': {'c', 'l'}, 'hsa': {'c', 'l'}}\n    ALAt2rL {'mmu': {'c', 'l'}, 'hsa': {'c', 'l'}}\n    GLYt2rL {'mmu': {'c', 'l'}, 'hsa': {'c', 'l'}}\n    S4TASE1ly {'hsa': {'l'}, 'mmu': {'l'}}\n    S4TASE2ly {'hsa': {'l'}, 'mmu': {'l'}}\n    S4TASE3ly {'hsa': {'l'}, 'mmu': {'l'}}\n    S4TASE4ly {'hsa': {'l'}, 'mmu': {'l'}}\n    S4TASE5ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA6ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX10ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX4ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA11ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX19ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA7ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA17ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX11ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX5ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX1ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA8ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA18ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX6ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX20ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA9ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA19ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX7ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX21ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA1ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX8ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX22ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA20ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX9ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX23ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA21ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA10ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX24ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA16ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA22ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA12ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX25ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX12ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX13ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA2ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA13ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX26ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX14ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX15ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA3ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX16ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA14ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX27ly {'hsa': {'l'}, 'mmu': {'l'}}\n    AHEXASE2ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA4ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX17ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA15ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX2ly {'hsa': {'l'}, 'mmu': {'l'}}\n    AHEXASEly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEXA5ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX18ly {'hsa': {'l'}, 'mmu': {'l'}}\n    NACHEX3ly {'hsa': {'l'}, 'mmu': {'l'}}\n    CYTDtl {'mmu': {'c', 'l'}, 'hsa': {'c', 'l'}}\n    HXANtl {'mmu': {'c', 'l'}, 'hsa': {'c', 'l'}}\n    ADEtl {'mmu': {'c', 'l'}, 'hsa': {'c', 'l'}}\n    GSNtl {'mmu': {'c', 'l'}, 'hsa': {'c', 'l'}}\n    INStl {'mmu': {'c', 'l'}, 'hsa': {'c', 'l'}}\n    THYMDtl {'mmu': {'c', 'l'}, 'hsa': {'c', 'l'}}\n    Uritl {'mmu': {'c', 'l'}, 'hsa': {'c', 'l'}}\n    ADNtl {'mmu': {'c', 'l'}, 'hsa': {'c', 'l'}}\n\n\n\n```python\nReaction_subset_Jeff = dict()\nfor k, v in Reaction_comp_Jeff.items():\n    temp = sum([list(x) for x in v.values()],[])\n    if not any(x in temp for x in ['l']):\n        Reaction_subset_Jeff.setdefault(k,str())\n    else:\n        Reaction_subset_Jeff.setdefault(k,str())\nprint(len(Reaction_subset_Jeff))\n```\n\n    2366\n\n\n\n```python\nfor k, v in Reaction_rev_Jeff.items():\n    if k in Reaction_subset_Jeff:\n        if len(set(v.values())) > 1:\n            print(k, v)\n```\n\n    XYLTD_D {'yli': 'rev', 'sce': 'for'}\n    GCCbim {'hsa': 'for', 'mmu': 'for', 'sce': 'for', 'yli': 'rev'}\n    GLYCLm {'sce': 'for', 'yli': 'back'}\n    PYAM5PO {'sce': 'for', 'mmu': 'rev', 'hsa': 'rev', 'yli': 'for'}\n    PYDXNO {'sce': 'rev', 'yli': 'for'}\n    PDX5POi {'sce': 'rev', 'mmu': 'rev', 'hsa': 'rev', 'yli': 'for'}\n    GTHPi {'sce': 'rev', 'hsa': 'rev', 'yli': 'for', 'mmu': 'rev'}\n    GTHPm {'hsa': 'rev', 'yli': 'for', 'mmu': 'rev', 'sce': 'rev'}\n    SULR {'yli': 'for', 'sce': 'rev'}\n    G3PD1ir {'sce': 'for', 'yli': 'for', 'hsa': 'rev', 'mmu': 'rev'}\n    ABTA {'yli': 'rev', 'sce': 'for'}\n    VALTAim {'sce': 'for', 'yli': 'rev'}\n    FACOAL180 {'hsa': 'for', 'mmu': 'for', 'sce': 'rev', 'yli': 'rev'}\n    FACOAL181 {'hsa': 'for', 'mmu': 'for', 'sce': 'rev'}\n    FACOAL160 {'hsa': 'for', 'mmu': 'for', 'sce': 'rev', 'yli': 'rev'}\n    TRPTA {'sce': 'rev', 'yli': 'for'}\n    TYRTAim {'yli': 'rev', 'hsa': 'rev', 'mmu': 'rev', 'sce': 'for'}\n    ATHRDHr {'yli': 'for', 'sce': 'rev'}\n    ACCOAC {'yli': 'rev', 'mmu': 'for', 'sce': 'rev', 'hsa': 'for'}\n    ACCOACrm {'yli': 'rev', 'sce': 'rev', 'mmu': 'for', 'hsa': 'for'}\n    G6PDH2r {'hsa': 'rev', 'sce': 'for', 'mmu': 'rev'}\n    DHQTi {'yli': 'rev', 'sce': 'for'}\n    PSCVT {'yli': 'rev', 'sce': 'for'}\n    34DHPLACOX_NADP {'hsa': 'rev', 'mmu': 'rev', 'yli': 'for'}\n    HSERTA {'sce': 'rev', 'yli': 'for'}\n    SFGTHi {'hsa': 'rev', 'sce': 'rev', 'yli': 'for', 'mmu': 'rev'}\n    GLCt1 {'hsa': 'rev', 'sce': 'for', 'yli': 'for'}\n    RDH1a {'hsa': 'rev', 'mmu': 'for'}\n    RDH3a {'hsa': 'rev', 'mmu': 'for'}\n    RDH2a {'hsa': 'rev', 'mmu': 'for'}\n    MTHFD {'sce': 'rev', 'mmu': 'rev', 'yli': 'for', 'hsa': 'rev'}\n    FTHFLi {'sce': 'for', 'mmu': 'for', 'yli': 'for', 'hsa': 'rev'}\n    FTHFLmi {'hsa': 'rev', 'sce': 'for', 'mmu': 'for'}\n    AHCi {'mmu': 'rev', 'yli': 'for', 'sce': 'for', 'hsa': 'rev'}\n    ARGSS {'sce': 'rev', 'hsa': 'for', 'mmu': 'for'}\n    PSERT {'yli': 'rev', 'hsa': 'for', 'sce': 'for', 'mmu': 'for'}\n    ADSL1r {'yli': 'rev', 'sce': 'rev', 'mmu': 'for', 'hsa': 'for'}\n    ADSL2r {'sce': 'rev', 'mmu': 'for', 'hsa': 'for'}\n    DURIPP {'yli': 'for', 'mmu': 'rev', 'hsa': 'rev', 'sce': 'rev'}\n    NP1 {'yli': 'rev', 'mmu': 'for', 'hsa': 'for'}\n    INSTt2 {'yli': 'for', 'mmu': 'rev', 'hsa': 'rev', 'sce': 'for'}\n    THRA {'sce': 'for', 'yli': 'rev'}\n    THRA2 {'sce': 'for', 'yli': 'rev'}\n    PIt2m {'hsa': 'rev', 'sce': 'rev', 'yli': 'rev', 'mmu': 'for'}\n    ECOAH1m {'hsa': 'rev', 'yli': 'back', 'mmu': 'rev'}\n    UDPGD {'hsa': 'for', 'mmu': 'for', 'yli': 'rev'}\n    ACOAHim {'yli': 'back', 'sce': 'for'}\n    ALCD2x {'yli': 'rev', 'hsa': 'for'}\n    34DHOXPEGOX {'yli': 'back', 'hsa': 'rev'}\n    HEX10 {'hsa': 'for', 'yli': 'rev', 'mmu': 'for'}\n    ACGAM6PS {'mmu': 'for', 'sce': 'rev', 'hsa': 'for', 'yli': 'for'}\n    BILGLCURte {'mmu': 'for', 'hsa': 'rev'}\n    BILDGLCURte {'mmu': 'for', 'hsa': 'rev'}\n    GARFT {'sce': 'for', 'yli': 'for', 'mmu': 'rev', 'hsa': 'rev'}\n    PPNDH {'sce': 'for', 'yli': 'rev'}\n    CHORM {'yli': 'rev', 'sce': 'for'}\n    KARA1im {'sce': 'for', 'yli': 'rev'}\n    KARA2im {'sce': 'for', 'yli': 'rev'}\n    NNAM {'sce': 'rev', 'yli': 'for'}\n    PEAMNO {'yli': 'rev', 'mmu': 'for', 'hsa': 'for'}\n    NMNAT {'hsa': 'rev', 'sce': 'for', 'mmu': 'rev'}\n    ADNK1 {'yli': 'rev', 'sce': 'for', 'mmu': 'for', 'hsa': 'for'}\n    SUCCtm {'mmu': 'rev', 'sce': 'for', 'yli': 'for'}\n    FACOAL140 {'sce': 'rev', 'mmu': 'for'}\n    FACOAL80 {'mmu': 'for', 'hsa': 'for', 'yli': 'rev'}\n    ICDHym {'yli': 'for', 'hsa': 'rev', 'sce': 'for', 'mmu': 'rev'}\n    HSDy {'sce': 'back', 'yli': 'rev'}\n    HSDxi {'sce': 'for', 'yli': 'rev'}\n    COAtim {'mmu': 'rev', 'yli': 'for', 'sce': 'for', 'hsa': 'rev'}\n    HMGCOAS {'sce': 'rev', 'hsa': 'back', 'mmu': 'back'}\n    HMGCOASm {'sce': 'rev', 'mmu': 'back', 'hsa': 'back'}\n    PRAGSr {'mmu': 'rev', 'hsa': 'rev', 'yli': 'for', 'sce': 'rev'}\n    ACOATA {'sce': 'rev', 'yli': 'for'}\n    IGPS {'sce': 'for', 'yli': 'rev'}\n    ANPRT {'sce': 'for', 'yli': 'rev'}\n    ORNTACim {'sce': 'for', 'yli': 'rev'}\n    CYSTGL {'yli': 'rev', 'hsa': 'for', 'mmu': 'for', 'sce': 'for'}\n    ASPCT {'mmu': 'rev', 'sce': 'for', 'yli': 'for', 'hsa': 'rev'}\n    HSTPT {'sce': 'for', 'yli': 'rev'}\n    ACACT1m {'hsa': 'rev', 'yli': 'for', 'sce': 'for', 'mmu': 'rev'}\n\n\n\n```python\nfor k, v in Reaction_rev_Jeff.items():\n    if k in Reaction_subset_Jeff:\n        temp = sum([list(x) for x in v.values()],[])\n        if not (all(temp) or not any(temp)):\n            if 'sce' in v:\n                Reaction_subset_Jeff[k] = ('sce',v['sce'])\n            elif 'hsa' in v:\n                Reaction_subset_Jeff[k] = ('hsa',v['hsa'])\n            else:\n                print(k, v)\n        else:\n            if 'sce' in v:\n                Reaction_subset_Jeff[k] = ('sce',v['sce'])\n            elif 'hsa' in v:\n                Reaction_subset_Jeff[k] = ('hsa',v['hsa'])\n            elif 'mmu' in v:\n                Reaction_subset_Jeff[k] = ('mmu',v['mmu'])\n            elif 'yli' in v:\n                Reaction_subset_Jeff[k] = ('yli',v['yli'])\n            else:\n                print(k, v)\n```\n\n\n```python\nfor k, v in Reaction_subset_Jeff.items():\n    if k in eco.reactions:\n        if not Model_rev[k]['eco'] == v[1]:\n            print(k, v, 'eco', Model_rev[k]['eco'])\n    elif k in sce.reactions:\n        if not Model_rev[k]['sce'] == v[1]:\n            print(k, v, 'sce', Model_rev[k]['sce'])\n```\n\n    GTHOr ('sce', 'for') eco rev\n    PTPATi ('hsa', 'rev') eco for\n    PTPATim ('yli', 'rev') sce for\n    PDX5POi ('sce', 'rev') eco for\n    GTHPi ('sce', 'rev') eco for\n    SULR ('sce', 'rev') eco for\n    OCBT ('sce', 'for') eco rev\n    AATA ('hsa', 'back') sce rev\n    AMPTASECG ('yli', 'rev') eco for\n    ACCOAC ('sce', 'rev') eco for\n    G6PDH2r ('sce', 'for') eco rev\n    CYSDS ('yli', 'rev') eco for\n    SHK3Dr ('sce', 'for') eco rev\n    PSCVT ('sce', 'for') eco rev\n    ALDD19xr ('sce', 'for') eco rev\n    PRASCSi ('sce', 'rev') eco for\n    SFGTHi ('sce', 'rev') eco for\n    MDH ('yli', 'for') eco rev\n    CYSTA ('hsa', 'rev') eco for\n    ARGSS ('sce', 'rev') eco for\n    ECOAH1 ('yli', 'back') eco rev\n    AP4AH ('sce', 'rev') eco for\n    ALCD2x ('hsa', 'for') eco rev\n    PRMICI ('sce', 'for') eco rev\n    ALLTN ('sce', 'rev') eco for\n    ASPK ('sce', 'for') eco rev\n    MTRI ('yli', 'for') sce rev\n    GALUi ('sce', 'rev') eco for\n    GARFT ('sce', 'for') eco rev\n    LCARS ('hsa', 'back') eco rev\n    AOXSr2 ('yli', 'rev') eco for\n    DHORDfum ('yli', 'rev') eco for\n    NNAM ('sce', 'rev') eco for\n    GALKr ('sce', 'for') eco rev\n    NNATr ('sce', 'for') eco rev\n    SPRMS ('yli', 'rev') sce for\n    ICDHyr ('sce', 'for') eco rev\n    HSDy ('sce', 'back') eco rev\n    FA141ACPHi ('sce', 'rev') eco for\n    FA120ACPHi ('sce', 'rev') eco for\n    FA160ACPHi ('sce', 'rev') eco for\n    FA140ACPHi ('sce', 'rev') eco for\n    FA161ACPHi ('sce', 'rev') eco for\n    ASAD ('sce', 'back') eco rev\n    FALDH2 ('yli', 'for') eco rev\n    GLUDy ('sce', 'back') eco rev\n    ACACT1r ('sce', 'for') eco rev\n\n\n\n```python\nfor k, v in Reaction_subset_Jeff.items():\n    if k in eco.reactions:\n        if not Model_rev[k]['eco'] == v[1]:\n            Reaction_subset_Jeff[k] = ('eco', Model_rev[k]['eco'])\n    elif k in sce.reactions:\n        if not Model_rev[k]['sce'] == v[1]:\n            Reaction_subset_Jeff[k] = ('sce', Model_rev[k]['sce'])\n```\n\n\n```python\nfor k in set(Reaction_subset).intersection(Reaction_subset_Jeff):\n    if not Reaction_subset[k][1] == Reaction_subset_Jeff[k][1]:\n        print(k, Reaction_subset[k], Reaction_subset_Jeff[k])\n```\n\n    NNATn ('cre', 'rev') ('hsa', 'for')\n    ECOAH9m ('cre', 'for') ('hsa', 'rev')\n    PPCOAOm ('cre', 'rev') ('hsa', 'for')\n    FACOAL1832 ('cre', 'for') ('hsa', 'rev')\n    PEAMNO ('yli', 'rev') ('hsa', 'for')\n    HEX10 ('yli', 'rev') ('hsa', 'for')\n    OCOAT1 ('ppu', 'for') ('yli', 'rev')\n    ALCD2y ('cre', 'back') ('hsa', 'for')\n    ECOAH12m ('cre', 'for') ('hsa', 'rev')\n    NP1 ('yli', 'rev') ('hsa', 'for')\n    GDHm ('cre', 'for') ('hsa', 'rev')\n    MMTSAO ('ppu', 'for') ('yli', 'rev')\n    LALDO ('cre', 'for') ('hsa', 'rev')\n    ACACT10m ('cre', 'for') ('hsa', 'rev')\n    FACOAL1821 ('cre', 'for') ('hsa', 'rev')\n    FACOAL80 ('yli', 'rev') ('hsa', 'for')\n    SHSL2r ('ppu', 'rev') ('yli', 'for')\n    ECOAH1m ('yli', 'back') ('hsa', 'rev')\n    34DHOXPEGOX ('yli', 'back') ('hsa', 'rev')\n    MAOX ('cre', 'rev') ('hsa', 'for')\n    PRPNCOAHYDm ('cre', 'rev') ('hsa', 'for')\n    FACOAL1831 ('cre', 'for') ('hsa', 'rev')\n\n\n\n```python\nReaction_subset_union = dict()\nfor k in set(Reaction_subset).intersection(Reaction_subset_Jeff):\n    if not Reaction_subset[k][1] == Reaction_subset_Jeff[k][1]:\n        if 'ppu' in Reaction_subset[k]:\n            Reaction_subset_union[k] = Reaction_subset[k]\n        elif 'hsa' in Reaction_subset_Jeff[k]:\n            Reaction_subset_union[k] = Reaction_subset_Jeff[k]\n        else:\n            print(k, Reaction_subset[k], Reaction_subset_Jeff[k])\n    else:\n        Reaction_subset_union[k] = Reaction_subset[k]\nfor k in set(Reaction_subset).difference(Reaction_subset_Jeff):\n    Reaction_subset_union[k] = Reaction_subset[k]\nfor k in set(Reaction_subset_Jeff).difference(Reaction_subset):\n    Reaction_subset_union[k] = Reaction_subset_Jeff[k]\nprint(len(Reaction_subset_union))\n```\n\n    3804\n\n\n\n```python\nReaction_to_gene['PGI']\n```\n\n\n\n\n    {'eco|b4025': {'rtoi|9589'},\n     'ppu|PP_1808': {'rtoi|9589'},\n     'sce|YBR196C': {'rtoi|9589'}}\n\n\n\n\n```python\nimport sympy\nfrom sympy.logic.boolalg import to_dnf\nfrom sympy.parsing.sympy_parser import parse_expr\nReaction_rule = dict()\nfor k, v in Reaction_to_gene.items():\n    if k in Reaction_subset:\n        for m in ['sce','eco','ppu','cre','yli']:\n            if any(k2.startswith(m) for k2 in v):\n                gpr = eval(m).reactions.get_by_id(k).gene_reaction_rule\n                gpr = parse_expr(gpr.replace(' or ',' | ').replace(' and ',' & '))\n                gpr = to_dnf(gpr)\n                for k2, v2 in v.items():\n                    if k2.startswith(m):\n                        if len(v2) > 1:\n                            temp = '('+' | '.join(x.replace('rtoi|','rtoi_') for x in v2)+')'\n                        else:\n                            temp = next(iter(v2)).replace('rtoi|','rtoi_')\n                        temp = parse_expr(temp)\n                        gpr = gpr.subs(k2.replace(m+'|',''), temp)\n                gpr = to_dnf(gpr)\n                gpr2 = gpr\n                if isinstance(gpr, sympy.Or):\n                    for x in gpr.args:\n                        if isinstance(x, sympy.Symbol) and (not str(x).startswith('rtoi_')):\n                            if gpr.count(x) > 1:\n                                print(k, v)\n                            gpr2 = to_dnf(gpr2.subs(x,0))\n#                gpr2 = str(gpr2).replace(' | ',' or ').replace(' & ',' and ').replace('rtoi_','')\n                Reaction_rule.setdefault(k, dict())[m] = gpr2\n```\n\n\n```python\nReaction_rule['PGI']\n```\n\n\n\n\n    {'eco': rtoi_9589, 'ppu': rtoi_9589, 'sce': rtoi_9589}\n\n\n\n\n```python\nprint(len(Reaction_rule))\nReaction_rule_unique = dict()\nfor k, v in Reaction_rule.items():\n    if len(set(v2 for v2 in v.values())) == 1:\n        Reaction_rule_unique[k] = list(v.values())[0]\nprint(len(Reaction_rule_unique))\n```\n\n    2995\n    2705\n\n\n\n```python\nReaction_to_gene_Jeff['PGI']\n```\n\n\n\n\n    {'hsa|GPI': {'rtoi|9589'},\n     'mmu|Gpi1': {'rtoi|9589'},\n     'sce|YBR196C': {'rtoi|9589'}}\n\n\n\n\n```python\nhsa_dict_rev = {g.id: g.name for g in hsa.genes if g.name}\nmmu_dict_rev = {g.id: g.name for g in mmu.genes if g.name}\n```\n\n\n```python\nimport re\nReaction_rule_Jeff = dict()\nfor k, v in Reaction_to_gene_Jeff.items():\n    if k in Reaction_subset_Jeff:\n        for m in ['hsa','mmu']:\n            if any(k2.startswith(m) for k2 in v):\n                gpr = eval(m).reactions.get_by_id(k).gene_reaction_rule\n                for x in gpr.split():\n                    temp = x.strip('()')\n                    if not any(y in temp for y in ['or', 'and']):\n                        gpr = re.sub(r'\\b'+temp+r'\\b', m+'_'+temp, gpr)\n                gpr = parse_expr(gpr.replace(' or ',' | ').replace(' and ',' & '))\n                for x in gpr.free_symbols:\n                    if str(x).replace(m+'_','') in eval(m+'_dict_rev'):\n                        gpr = gpr.subs(x, eval(m+'_dict_rev')[str(x).replace(m+'_','')])\n                gpr = to_dnf(gpr)\n                for k2, v2 in v.items():\n                    if k2.startswith(m):\n                        if len(v2) > 1:\n                            temp = '('+' | '.join(x.replace('rtoi|','rtoi_') for x in v2)+')'\n                        else:\n                            temp = next(iter(v2)).replace('rtoi|','rtoi_')\n                        temp = parse_expr(temp)\n                        gpr = gpr.subs(k2.replace(m+'|',''), temp)\n                gpr = to_dnf(gpr)\n                gpr2 = gpr\n                if isinstance(gpr, sympy.Or):\n                    for x in gpr.args:\n                        if isinstance(x, sympy.Symbol) and (not str(x).startswith('rtoi_')):\n                            gpr2 = to_dnf(gpr2.subs(x,0))\n                            if gpr.count(x) > 1:\n                                print(k, x, gpr, gpr2)                            \n#                gpr2 = str(gpr2).replace(' | ',' or ').replace(' & ',' and ').replace('rtoi_','')\n                Reaction_rule_Jeff.setdefault(k, dict())[m] = gpr2\n        for m in ['sce','yli']:\n            if any(k2.startswith(m) for k2 in v):\n                gpr = eval(m).reactions.get_by_id(k).gene_reaction_rule\n                gpr = parse_expr(gpr.replace(' or ',' | ').replace(' and ',' & '))\n                gpr = to_dnf(gpr)\n                for k2, v2 in v.items():\n                    if k2.startswith(m):\n                        if len(v2) > 1:\n                            temp = '('+' | '.join(x.replace('rtoi|','rtoi_') for x in v2)+')'\n                        else:\n                            temp = next(iter(v2)).replace('rtoi|','rtoi_')\n                        temp = parse_expr(temp)\n                        gpr = gpr.subs(k2.replace(m+'|',''), temp)\n                gpr = to_dnf(gpr)\n                gpr2 = gpr\n                if isinstance(gpr, sympy.Or):\n                    for x in gpr.args:\n                        if isinstance(x, sympy.Symbol) and (not str(x).startswith('rtoi_')):\n                            gpr2 = to_dnf(gpr2.subs(x,0))\n                            if gpr.count(x) > 1:\n                                print(k, v, gpr, gpr2)\n#                gpr2 = str(gpr2).replace(' | ',' or ').replace(' & ',' and ').replace('rtoi_','')\n                Reaction_rule_Jeff.setdefault(k, dict())[m] = gpr2\n```\n\n    ALCD2x ADH1A ADH1A | ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1A & ADH1B) | (ADH1A & ADH1C) | (ADH1B & ADH1C) ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1B & ADH1C)\n    ALCD2x ADH1B ADH1A | ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1A & ADH1B) | (ADH1A & ADH1C) | (ADH1B & ADH1C) ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109\n    ALCD2x ADH1C ADH1A | ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1A & ADH1B) | (ADH1A & ADH1C) | (ADH1B & ADH1C) ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109\n    ALCD21_D ADH1A ADH1A | ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1A & ADH1B) | (ADH1A & ADH1C) | (ADH1B & ADH1C) ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1B & ADH1C)\n    ALCD21_D ADH1B ADH1A | ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1A & ADH1B) | (ADH1A & ADH1C) | (ADH1B & ADH1C) ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109\n    ALCD21_D ADH1C ADH1A | ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1A & ADH1B) | (ADH1A & ADH1C) | (ADH1B & ADH1C) ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109\n    ALCD22_L ADH1A ADH1A | ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1A & ADH1B) | (ADH1A & ADH1C) | (ADH1B & ADH1C) ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1B & ADH1C)\n    ALCD22_L ADH1B ADH1A | ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1A & ADH1B) | (ADH1A & ADH1C) | (ADH1B & ADH1C) ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109\n    ALCD22_L ADH1C ADH1A | ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1A & ADH1B) | (ADH1A & ADH1C) | (ADH1B & ADH1C) ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109\n    LCARS ADH1A ADH1A | ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1A & ADH1B) | (ADH1A & ADH1C) | (ADH1B & ADH1C) ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1B & ADH1C)\n    LCARS ADH1B ADH1A | ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1A & ADH1B) | (ADH1A & ADH1C) | (ADH1B & ADH1C) ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109\n    LCARS ADH1C ADH1A | ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1A & ADH1B) | (ADH1A & ADH1C) | (ADH1B & ADH1C) ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109\n    ALCD1 ADH1A ADH1A | ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1A & ADH1B) | (ADH1A & ADH1C) | (ADH1B & ADH1C) ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1B & ADH1C)\n    ALCD1 ADH1B ADH1A | ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1A & ADH1B) | (ADH1A & ADH1C) | (ADH1B & ADH1C) ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109\n    ALCD1 ADH1C ADH1A | ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1A & ADH1B) | (ADH1A & ADH1C) | (ADH1B & ADH1C) ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109\n    ALCD22_D ADH1A ADH1A | ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1A & ADH1B) | (ADH1A & ADH1C) | (ADH1B & ADH1C) ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1B & ADH1C)\n    ALCD22_D ADH1B ADH1A | ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1A & ADH1B) | (ADH1A & ADH1C) | (ADH1B & ADH1C) ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109\n    ALCD22_D ADH1C ADH1A | ADH1B | ADH1C | ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109 | (ADH1A & ADH1B) | (ADH1A & ADH1C) | (ADH1B & ADH1C) ADH4 | ADH6 | ADH7 | rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109\n    HPYRR2x LDHA LDHA | LDHAL6A | LDHAL6B | LDHB | LDHC | rtoi_13328 | (LDHA & LDHB) LDHAL6A | LDHAL6B | LDHB | LDHC | rtoi_13328\n    HPYRR2x LDHB LDHA | LDHAL6A | LDHAL6B | LDHB | LDHC | rtoi_13328 | (LDHA & LDHB) LDHC | rtoi_13328\n    HPYRR2x Ldha Ldha | Ldhal6b | Ldhb | Ldhc | mmu_160287 | rtoi_13328 | (Ldha & Ldhb) Ldhal6b | Ldhb | Ldhc | mmu_160287 | rtoi_13328\n    HPYRR2x Ldhb Ldha | Ldhal6b | Ldhb | Ldhc | mmu_160287 | rtoi_13328 | (Ldha & Ldhb) Ldhc | mmu_160287 | rtoi_13328\n    GLXO1 LDHA LDHA | LDHAL6A | LDHAL6B | LDHB | LDHC | UEVLD | rtoi_13328 | (LDHA & LDHB) LDHAL6A | LDHAL6B | LDHB | LDHC | UEVLD | rtoi_13328\n    GLXO1 LDHB LDHA | LDHAL6A | LDHAL6B | LDHB | LDHC | UEVLD | rtoi_13328 | (LDHA & LDHB) LDHC | UEVLD | rtoi_13328\n\n\n\n```python\nReaction_rule_Jeff['PGI']\n```\n\n\n\n\n    {'hsa': rtoi_9589, 'mmu': rtoi_9589, 'sce': rtoi_9589}\n\n\n\n\n```python\nprint(len(Reaction_rule_Jeff))\nReaction_rule_Jeff_unique = dict()\nfor k, v in Reaction_rule_Jeff.items():\n    if len(set(v2 for v2 in v.values())) == 1:\n        Reaction_rule_Jeff_unique[k] = list(v.values())[0]\nprint(len(Reaction_rule_Jeff_unique))\n```\n\n    2366\n    2172\n\n\n\n```python\nprint(len(Reaction_rule))\nprint(len(Reaction_rule_Jeff))\nprint(len(set(Reaction_rule.keys()).union(Reaction_rule_Jeff)))\nprint(len(set(Reaction_rule.keys()).intersection(Reaction_rule_Jeff)))\nprint(len(set(Reaction_rule_unique.keys()).intersection(Reaction_rule_Jeff)))\nprint(len(set(Reaction_rule.keys()).intersection(Reaction_rule_Jeff_unique)))\n```\n\n    2995\n    2366\n    3804\n    1557\n    1308\n    1414\n\n\n\n```python\nprint(len(Reaction_rule_unique))\nprint(len(Reaction_rule_Jeff_unique))\nprint(len(set(Reaction_rule_unique.keys()).intersection(Reaction_rule_Jeff_unique)))\nReaction_rule_final = dict()\nfor x in set(Reaction_rule_unique.keys()).intersection(Reaction_rule_Jeff_unique):\n    if Reaction_rule_unique[x] == Reaction_rule_Jeff_unique[x]:\n        Reaction_rule_final[x] = Reaction_rule_unique[x]\nprint(len(Reaction_rule_final))\n```\n\n    2705\n    2172\n    1273\n    1038\n\n\n\n```python\nfor x in set(Reaction_rule_unique.keys()).intersection(Reaction_rule_Jeff_unique):\n    if not Reaction_rule_unique[x] == Reaction_rule_Jeff_unique[x]:\n        temp1 = Reaction_rule_unique[x]\n        temp2 = Reaction_rule_Jeff_unique[x]\n        if set(temp1.free_symbols).difference(temp2.free_symbols) and set(temp2.free_symbols).difference(temp1.free_symbols):\n            if not all(str(y).startswith('rtoi_') for y in temp1.free_symbols) and \\\n               not all(str(y).startswith('rtoi_') for y in temp2.free_symbols):\n                print(x)\n                print('\\t',temp1)\n                print('\\t',temp2)\n```\n\n    CYOOm\n    \t Q0045 & Q0250 & Q0275 & YGL191W & YLR395C & YMR256C & rtoi_10685 & rtoi_11317 & rtoi_11769 & rtoi_13628 & rtoi_8802 & rtoi_9165\n    \t Q0045 & Q0250 & Q0275 & YLR395C & YMR256C & rtoi_10685 & rtoi_11317 & rtoi_11769 & rtoi_13007 & rtoi_13628 & rtoi_8802 & rtoi_9165\n    CYOR_u6m\n    \t Q0105 & YBL045C & YFR033C & rtoi_11618 & rtoi_12966 & rtoi_13608 & rtoi_13614 & rtoi_15231 & rtoi_15681 & rtoi_8802 & rtoi_9198\n    \t Q0105 & YBL045C & YHR001W_A & rtoi_11618 & rtoi_12966 & rtoi_13614 & rtoi_15231 & rtoi_15681 & rtoi_15758 & rtoi_8802 & rtoi_9198\n    yli_R0430\n    \t YALI0D14850g & YALIfMp01 & YALIfMp02 & YALIfMp16 & YALIfMp19 & YALIfMp20 & YALIfMp28 & YALIfMp29 & rtoi_10010 & rtoi_10318 & rtoi_11151 & rtoi_11702 & rtoi_12497 & rtoi_12543 & rtoi_13017 & rtoi_13214 & rtoi_13766 & rtoi_14078 & rtoi_14418 & rtoi_14900 & rtoi_15179 & rtoi_15864 & rtoi_15947 & rtoi_15973 & rtoi_8699 & rtoi_8909 & rtoi_8972 & rtoi_9348\n    \t YALIfMp01 & YALIfMp02 & YALIfMp16 & YALIfMp19 & YALIfMp20 & YALIfMp28 & YALIfMp29 & rtoi_10010 & rtoi_10318 & rtoi_11151 & rtoi_11702 & rtoi_12497 & rtoi_12543 & rtoi_13017 & rtoi_13214 & rtoi_13766 & rtoi_14078 & rtoi_14261 & rtoi_14418 & rtoi_14900 & rtoi_15179 & rtoi_15864 & rtoi_15947 & rtoi_15973 & rtoi_8699 & rtoi_8909 & rtoi_8972 & rtoi_9348\n    yli_R0432\n    \t YALI0D14850g & YALIfMp01 & YALIfMp02 & YALIfMp16 & YALIfMp19 & YALIfMp20 & YALIfMp28 & YALIfMp29 & rtoi_10010 & rtoi_10318 & rtoi_11151 & rtoi_11702 & rtoi_12497 & rtoi_12543 & rtoi_13017 & rtoi_13214 & rtoi_13766 & rtoi_14078 & rtoi_14418 & rtoi_14900 & rtoi_15179 & rtoi_15864 & rtoi_15947 & rtoi_15973 & rtoi_8699 & rtoi_8909 & rtoi_8972 & rtoi_9348\n    \t YALIfMp01 & YALIfMp02 & YALIfMp16 & YALIfMp19 & YALIfMp20 & YALIfMp28 & YALIfMp29 & rtoi_10010 & rtoi_10318 & rtoi_11151 & rtoi_11702 & rtoi_12497 & rtoi_12543 & rtoi_13017 & rtoi_13214 & rtoi_13766 & rtoi_14078 & rtoi_14261 & rtoi_14418 & rtoi_14900 & rtoi_15179 & rtoi_15864 & rtoi_15947 & rtoi_15973 & rtoi_8699 & rtoi_8909 & rtoi_8972 & rtoi_9348\n\n\n\n```python\nReaction_rule_final['CYOOm'] = parse_expr('Q0045 & Q0250 & Q0275 & YLR395C & YMR256C & rtoi_10685 & rtoi_11317 &\\\n                                           rtoi_11769 & rtoi_13007 & rtoi_13628 & rtoi_8802 & rtoi_9165')\nReaction_rule_final['CYOR_u6m'] = parse_expr('Q0105 & YBL045C & rtoi_11618 & rtoi_12966 & rtoi_13608 & rtoi_13614 &\\\n                                              rtoi_15231 & rtoi_15681 & rtoi_15758 & rtoi_8802 & rtoi_9198')\nReaction_rule_final['yli_R0430'] = parse_expr('YALIfMp01 & YALIfMp02 & YALIfMp16 & YALIfMp19 & YALIfMp20 & YALIfMp28 &\\\n                                               YALIfMp29 & rtoi_10010 & rtoi_10318 & rtoi_11151 & rtoi_11702 &\\\n                                               rtoi_12497 & rtoi_12543 & rtoi_13017 & rtoi_13214 & rtoi_13766 &\\\n                                               rtoi_14078 & rtoi_14261 & rtoi_14418 & rtoi_14900 & rtoi_15179 &\\\n                                               rtoi_15864 & rtoi_15947 & rtoi_15973 & rtoi_8699 & rtoi_8909 &\\\n                                               rtoi_8972 & rtoi_9348')\nReaction_rule_final['yli_R0432'] = parse_expr('YALIfMp01 & YALIfMp02 & YALIfMp16 & YALIfMp19 & YALIfMp20 & YALIfMp28 &\\\n                                               YALIfMp29 & rtoi_10010 & rtoi_10318 & rtoi_11151 & rtoi_11702 &\\\n                                               rtoi_12497 & rtoi_12543 & rtoi_13017 & rtoi_13214 & rtoi_13766 &\\\n                                               rtoi_14078 & rtoi_14261 & rtoi_14418 & rtoi_14900 & rtoi_15179 &\\\n                                               rtoi_15864 & rtoi_15947 & rtoi_15973 & rtoi_8699 & rtoi_8909 &\\\n                                               rtoi_8972 & rtoi_9348')\n```\n\n\n```python\nfor x in set(Reaction_rule_unique.keys()).intersection(Reaction_rule_Jeff_unique):\n    if not Reaction_rule_unique[x] == Reaction_rule_Jeff_unique[x]:\n        temp1 = Reaction_rule_unique[x]\n        temp2 = Reaction_rule_Jeff_unique[x]\n        if set(temp1.free_symbols).difference(temp2.free_symbols) and set(temp2.free_symbols).difference(temp1.free_symbols):\n            if not all(str(y).startswith('rtoi_') for y in temp1.free_symbols) and \\\n               all(str(y).startswith('rtoi_') for y in temp2.free_symbols):\n                print(x)\n                print('\\t',temp1)\n                print('\\t',temp2)\n```\n\n    GLYGS\n    \t (YJL137C & rtoi_9596) | (YKR058W & rtoi_9596)\n    \t rtoi_14002 & rtoi_9596\n    THIORDXm\n    \t YCR083W & rtoi_10200\n    \t rtoi_10200 & rtoi_15339\n    GLCS2\n    \t (YJL137C & rtoi_9596) | (YKR058W & rtoi_9596)\n    \t rtoi_14002 & rtoi_9596\n\n\n\n```python\nfor x in set(Reaction_rule_unique.keys()).intersection(Reaction_rule_Jeff_unique):\n    if not Reaction_rule_unique[x] == Reaction_rule_Jeff_unique[x]:\n        temp1 = Reaction_rule_unique[x]\n        temp2 = Reaction_rule_Jeff_unique[x]\n        if set(temp1.free_symbols).difference(temp2.free_symbols) and set(temp2.free_symbols).difference(temp1.free_symbols):\n            if not all(str(y).startswith('rtoi_') for y in temp1.free_symbols) and \\\n               all(str(y).startswith('rtoi_') for y in temp2.free_symbols):\n                Reaction_rule_final[x] = temp2\n```\n\n\n```python\nfor x in set(Reaction_rule_unique.keys()).intersection(Reaction_rule_Jeff_unique):\n    if not Reaction_rule_unique[x] == Reaction_rule_Jeff_unique[x]:\n        temp1 = Reaction_rule_unique[x]\n        temp2 = Reaction_rule_Jeff_unique[x]\n        if set(temp1.free_symbols).difference(temp2.free_symbols) and set(temp2.free_symbols).difference(temp1.free_symbols):\n            if all(str(y).startswith('rtoi_') for y in temp1.free_symbols) and \\\n               not all(str(y).startswith('rtoi_') for y in temp2.free_symbols):\n                print(x)\n                print('\\t',temp1)\n                print('\\t',temp2)\n```\n\n    NFTYROX\n    \t (rtoi_13286 & rtoi_13361) | (rtoi_13286 & rtoi_8979) | (rtoi_13286 & rtoi_9188)\n    \t YDR402C & rtoi_13286\n\n\n\n```python\nfor x in set(Reaction_rule_unique.keys()).intersection(Reaction_rule_Jeff_unique):\n    if not Reaction_rule_unique[x] == Reaction_rule_Jeff_unique[x]:\n        temp1 = Reaction_rule_unique[x]\n        temp2 = Reaction_rule_Jeff_unique[x]\n        if set(temp1.free_symbols).difference(temp2.free_symbols) and set(temp2.free_symbols).difference(temp1.free_symbols):\n            if all(str(y).startswith('rtoi_') for y in temp1.free_symbols) and \\\n               not all(str(y).startswith('rtoi_') for y in temp2.free_symbols):\n                Reaction_rule_final[x] = temp1\n```\n\n\n```python\nfor x in set(Reaction_rule_unique.keys()).intersection(Reaction_rule_Jeff_unique):\n    if not Reaction_rule_unique[x] == Reaction_rule_Jeff_unique[x]:\n        temp1 = Reaction_rule_unique[x]\n        temp2 = Reaction_rule_Jeff_unique[x]\n        if set(temp1.free_symbols).difference(temp2.free_symbols) and set(temp2.free_symbols).difference(temp1.free_symbols):\n            if all(str(y).startswith('rtoi_') for y in temp1.free_symbols) and \\\n               all(str(y).startswith('rtoi_') for y in temp2.free_symbols):\n                print(x)\n                print('\\t',temp1)\n                print('\\t',temp2)\n```\n\n    ALKP\n    \t rtoi_14546\n    \t rtoi_13409\n    G3PT\n    \t rtoi_13044\n    \t rtoi_13413\n    PPDOy\n    \t rtoi_10029 | rtoi_13554 | rtoi_13562 | rtoi_13947\n    \t rtoi_11882 | rtoi_12784 | rtoi_16543 | rtoi_9774\n    DNADDP\n    \t rtoi_15385\n    \t rtoi_14638\n    ECOAH1x\n    \t rtoi_11362\n    \t rtoi_11907\n    LALDO2x\n    \t rtoi_9515\n    \t rtoi_16543\n    NACt\n    \t rtoi_13555 | rtoi_9534 | rtoi_9938\n    \t rtoi_12221 | rtoi_13555\n    GLUt2m\n    \t rtoi_8766\n    \t rtoi_16799\n    HACD9m\n    \t rtoi_11362\n    \t rtoi_16284\n    ACOAD10m\n    \t rtoi_10012 | rtoi_12570\n    \t rtoi_12570 | rtoi_14070\n    ACACT10m\n    \t rtoi_13813\n    \t rtoi_8678\n    MAOX\n    \t rtoi_10308\n    \t rtoi_13959\n    LYSt6\n    \t rtoi_10317 | rtoi_12690 | rtoi_9277 | rtoi_9291\n    \t rtoi_10317 | rtoi_12219 | rtoi_12690\n    CATp\n    \t rtoi_15305\n    \t rtoi_9354\n    yli_R1420\n    \t rtoi_14950\n    \t rtoi_16607\n    LCARS\n    \t rtoi_12307 | rtoi_9101\n    \t rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109\n    ALR2\n    \t rtoi_11882 | rtoi_15285\n    \t rtoi_11882 | rtoi_12784 | rtoi_16543 | rtoi_9774\n    HISt6\n    \t rtoi_10317 | rtoi_12690 | rtoi_9277 | rtoi_9291\n    \t rtoi_10317 | rtoi_12219 | rtoi_12690\n\n\n\n```python\nfor x in set(Reaction_rule_unique.keys()).intersection(Reaction_rule_Jeff_unique):\n    if not Reaction_rule_unique[x] == Reaction_rule_Jeff_unique[x]:\n        temp1 = Reaction_rule_unique[x]\n        temp2 = Reaction_rule_Jeff_unique[x]\n        if set(temp1.free_symbols).difference(temp2.free_symbols) and set(temp2.free_symbols).difference(temp1.free_symbols):\n            if all(str(y).startswith('rtoi_') for y in temp1.free_symbols) and \\\n               all(str(y).startswith('rtoi_') for y in temp2.free_symbols):\n                Reaction_rule_final[x] = sympy.Or(temp1,temp2)\n```\n\n\n```python\nfor x in sorted(set(Reaction_rule_unique.keys()).intersection(Reaction_rule_Jeff_unique)):\n    if not Reaction_rule_unique[x] == Reaction_rule_Jeff_unique[x]:\n        temp1 = Reaction_rule_unique[x]\n        temp2 = Reaction_rule_Jeff_unique[x]\n        if set(temp1.free_symbols).difference(temp2.free_symbols) and not set(temp2.free_symbols).difference(temp1.free_symbols):\n            print(x)\n            print('\\t',temp1)\n            print('\\t',temp2)\n```\n\n    ACITL\n    \t CRv4_Au5_s5_g12182_t1 & rtoi_9726\n    \t rtoi_9726\n    ACOAD8m\n    \t rtoi_10012 | rtoi_12570\n    \t rtoi_10012\n    ACOAD9m\n    \t rtoi_10012 | rtoi_12570\n    \t rtoi_12570\n    AKGMALtm\n    \t rtoi_11740 | rtoi_13510\n    \t rtoi_13510\n    ALLTNti\n    \t rtoi_10921 | rtoi_11871 | rtoi_12902\n    \t rtoi_12902\n    ARAB14LO\n    \t rtoi_10490 | rtoi_13733\n    \t rtoi_10490\n    CITL\n    \t b0614 & b0615 & b0617 & rtoi_9822\n    \t rtoi_9822\n    EPISTESTH_SCe\n    \t rtoi_14247 | rtoi_14617\n    \t rtoi_14247\n    ERGSTESTH_SCe\n    \t rtoi_14247 | rtoi_14617\n    \t rtoi_14247\n    FACOAL100p\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_12538 | rtoi_12555\n    FACOAL120p\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_12538 | rtoi_12555\n    FACOAL140\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    FACOAL140p\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_12538 | rtoi_12555\n    FACOAL141\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    FACOAL141p\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_12538 | rtoi_12555\n    FACOAL160p\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_12538 | rtoi_12555\n    FACOAL161p\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_12538 | rtoi_12555\n    FACOAL182\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    FACOAL1821\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_12538 | rtoi_12555\n    FACOAL1831\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_12538 | rtoi_12555\n    FACOAL1832\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_12538 | rtoi_12555\n    FACOAL80\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    FACOAL80p\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_12538 | rtoi_12555\n    FACOAL_160_m\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    FAS100\n    \t (rtoi_12826 & rtoi_8639 & rtoi_8670 & rtoi_8777) | (rtoi_14471 & rtoi_8639 & rtoi_8670 & rtoi_8777)\n    \t (rtoi_12826 & rtoi_8639 & rtoi_8670) | (rtoi_12826 & rtoi_8639 & rtoi_8777)\n    FAS100COA\n    \t (rtoi_12826 & rtoi_8639 & rtoi_8670 & rtoi_8777) | (rtoi_14471 & rtoi_8639 & rtoi_8670 & rtoi_8777)\n    \t (rtoi_12826 & rtoi_8639 & rtoi_8670) | (rtoi_12826 & rtoi_8639 & rtoi_8777)\n    FAS120\n    \t (rtoi_12826 & rtoi_8639 & rtoi_8670 & rtoi_8777) | (rtoi_14471 & rtoi_8639 & rtoi_8670 & rtoi_8777)\n    \t (rtoi_12826 & rtoi_8639 & rtoi_8670) | (rtoi_12826 & rtoi_8639 & rtoi_8777)\n    FAS120COA\n    \t (rtoi_12826 & rtoi_8639 & rtoi_8670 & rtoi_8777) | (rtoi_14471 & rtoi_8639 & rtoi_8670 & rtoi_8777)\n    \t (rtoi_12826 & rtoi_8639 & rtoi_8670) | (rtoi_12826 & rtoi_8639 & rtoi_8777)\n    FAS140\n    \t (rtoi_12826 & rtoi_8639 & rtoi_8670 & rtoi_8777) | (rtoi_14471 & rtoi_8639 & rtoi_8670 & rtoi_8777)\n    \t (rtoi_12826 & rtoi_8639 & rtoi_8670) | (rtoi_12826 & rtoi_8639 & rtoi_8777)\n    FAS160\n    \t (rtoi_12826 & rtoi_8639 & rtoi_8670 & rtoi_8777) | (rtoi_14471 & rtoi_8639 & rtoi_8670 & rtoi_8777)\n    \t (rtoi_12826 & rtoi_8639 & rtoi_8670) | (rtoi_12826 & rtoi_8639 & rtoi_8777)\n    FECOSTESTH_SCe\n    \t rtoi_14247 | rtoi_14617\n    \t rtoi_14247\n    GLYCLTDy\n    \t rtoi_11036 | rtoi_12051\n    \t rtoi_11036\n    GUAD\n    \t rtoi_9050 | rtoi_9708\n    \t rtoi_9050\n    LALDO\n    \t rtoi_12286 | rtoi_14108 | rtoi_14109\n    \t rtoi_14108 | rtoi_14109\n    LANOSTESTH_SCe\n    \t rtoi_14247 | rtoi_14617\n    \t rtoi_14247\n    MALtm\n    \t rtoi_11740 | rtoi_13510\n    \t rtoi_13510\n    MBCOAi\n    \t rtoi_10012 | rtoi_12570\n    \t rtoi_10012\n    NADH2_u6m\n    \t rtoi_14261 | rtoi_9809\n    \t rtoi_14261\n    PEPAT\n    \t rtoi_13208 | rtoi_9438\n    \t rtoi_9438\n    PI45BP5P_SC\n    \t rtoi_15340 | rtoi_15545\n    \t rtoi_15340\n    PRDX\n    \t rtoi_15305 | rtoi_9354\n    \t rtoi_9354\n    PSERDg_SC\n    \t rtoi_10504 | rtoi_11446\n    \t rtoi_11446\n    PSERDv_SC\n    \t rtoi_10504 | rtoi_11446\n    \t rtoi_11446\n    RNDR1n\n    \t (YGR180C & rtoi_11290 & rtoi_15339) | (YGR180C & rtoi_11290 & rtoi_16019)\n    \t YGR180C & rtoi_11290 & rtoi_15339\n    RNDR2n\n    \t (YGR180C & rtoi_11290 & rtoi_15339) | (YGR180C & rtoi_11290 & rtoi_16019)\n    \t YGR180C & rtoi_11290 & rtoi_15339\n    RNDR3n\n    \t (YGR180C & rtoi_11290 & rtoi_15339) | (YGR180C & rtoi_11290 & rtoi_16019)\n    \t YGR180C & rtoi_11290 & rtoi_15339\n    RNDR4n\n    \t (YGR180C & rtoi_11290 & rtoi_15339) | (YGR180C & rtoi_11290 & rtoi_16019)\n    \t YGR180C & rtoi_11290 & rtoi_15339\n    SUCCtm\n    \t rtoi_11740 | rtoi_13510\n    \t rtoi_13510\n    THIORDXni\n    \t (rtoi_15037 & rtoi_15339) | (rtoi_15037 & rtoi_16019)\n    \t rtoi_15037 & rtoi_15339\n    THIORDXp\n    \t (rtoi_13262 & rtoi_15339) | (rtoi_13262 & rtoi_16019)\n    \t rtoi_13262 & rtoi_15339\n    THMt2\n    \t rtoi_10921 | rtoi_11871 | rtoi_12902\n    \t rtoi_12902\n    URAt2\n    \t rtoi_10921 | rtoi_11871 | rtoi_12902\n    \t rtoi_12902\n    ZYMSTESTH_SCe\n    \t rtoi_14247 | rtoi_14617\n    \t rtoi_14247\n    yli_R0141\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    yli_R0142\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    yli_R0143\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    yli_R0144\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    yli_R0146\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    yli_R0148\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    yli_R0149\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    yli_R0150\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    yli_R0151\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    yli_R0233\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    yli_R0234\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    yli_R0235\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    yli_R0236\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    yli_R0238\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    yli_R0239\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    yli_R0240\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    yli_R0241\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    yli_R0242\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    yli_R0243\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    yli_R0244\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t rtoi_11167 | rtoi_15748\n    yli_R0338\n    \t rtoi_10504 | rtoi_11446 | rtoi_14554\n    \t rtoi_11446 | rtoi_14554\n    yli_R0816\n    \t rtoi_15305 | rtoi_9354\n    \t rtoi_9354\n    yli_R1114\n    \t rtoi_10921 | rtoi_11871 | rtoi_12902\n    \t rtoi_12902\n    yli_R1411\n    \t rtoi_10504 | rtoi_11446 | rtoi_14554\n    \t rtoi_11446 | rtoi_14554\n    yli_R1435\n    \t rtoi_8678 | rtoi_8885\n    \t rtoi_8678\n\n\n\n```python\nfor x in set(Reaction_rule_unique.keys()).intersection(Reaction_rule_Jeff_unique):\n    if not Reaction_rule_unique[x] == Reaction_rule_Jeff_unique[x]:\n        temp1 = Reaction_rule_unique[x]\n        temp2 = Reaction_rule_Jeff_unique[x]\n        if set(temp1.free_symbols).difference(temp2.free_symbols) and not set(temp2.free_symbols).difference(temp1.free_symbols):\n            Reaction_rule_final[x] = temp1\n```\n\n\n```python\nfor x in sorted(set(Reaction_rule_unique.keys()).intersection(Reaction_rule_Jeff_unique)):\n    if not Reaction_rule_unique[x] == Reaction_rule_Jeff_unique[x]:\n        temp1 = Reaction_rule_unique[x]\n        temp2 = Reaction_rule_Jeff_unique[x]\n        if not set(temp1.free_symbols).difference(temp2.free_symbols) and set(temp2.free_symbols).difference(temp1.free_symbols):\n            print(x)\n            print('\\t',temp1)\n            print('\\t',temp2)\n```\n\n    ACACT4m\n    \t rtoi_13813\n    \t rtoi_13813 | rtoi_9065\n    ACACT4p\n    \t rtoi_13813\n    \t rtoi_13813 | rtoi_9065\n    ACACT5p\n    \t rtoi_13813\n    \t rtoi_13813 | rtoi_9065\n    ACACT6m\n    \t rtoi_13813\n    \t rtoi_13813 | rtoi_9065\n    ACACT6p\n    \t rtoi_13813\n    \t rtoi_13813 | rtoi_9065\n    ACACT7m\n    \t rtoi_13813\n    \t rtoi_13813 | rtoi_9065\n    ACACT7p\n    \t rtoi_13813\n    \t rtoi_13813 | rtoi_9065\n    ACACT8p\n    \t rtoi_13813\n    \t rtoi_13813 | rtoi_9065\n    ACACT9p\n    \t rtoi_13813\n    \t rtoi_13813 | rtoi_9065\n    ACHLE1\n    \t rtoi_15240\n    \t rtoi_15133 | rtoi_15240\n    ACHLE2\n    \t rtoi_15240\n    \t rtoi_15133 | rtoi_15240\n    ACHLE3\n    \t rtoi_15240\n    \t rtoi_15133 | rtoi_15240\n    ACOAO4p\n    \t rtoi_12742 | rtoi_9700\n    \t rtoi_12742 | rtoi_12752 | rtoi_9700\n    ACOAO5p\n    \t rtoi_12742 | rtoi_9700\n    \t rtoi_12742 | rtoi_12752 | rtoi_9700\n    ACOAO6p\n    \t rtoi_12742 | rtoi_9700\n    \t rtoi_12742 | rtoi_12752 | rtoi_9700\n    ACOAO7p\n    \t rtoi_12742 | rtoi_9700\n    \t rtoi_12742 | rtoi_12752 | rtoi_9700\n    ACOAO8p\n    \t rtoi_12742 | rtoi_9700\n    \t rtoi_12742 | rtoi_12752 | rtoi_9700\n    ACOAO9p\n    \t rtoi_12742 | rtoi_9700\n    \t rtoi_12742 | rtoi_12752 | rtoi_9700\n    ACS2\n    \t rtoi_14597\n    \t rtoi_14597 | rtoi_15276\n    ALCD22yi\n    \t rtoi_10029 | rtoi_11882 | rtoi_13554 | rtoi_13562 | rtoi_13947\n    \t rtoi_10029 | rtoi_11882 | rtoi_12784 | rtoi_13554 | rtoi_13562 | rtoi_13947 | rtoi_9774\n    ALCD2y\n    \t rtoi_12784 | rtoi_9774\n    \t rtoi_11882 | rtoi_12784 | rtoi_9774\n    ALDD2x\n    \t rtoi_12042 | rtoi_13426\n    \t rtoi_12042 | rtoi_13426 | rtoi_15814 | rtoi_16323\n    ALLTTti\n    \t rtoi_15069 | rtoi_15070\n    \t rtoi_10379 | rtoi_15069 | rtoi_15070\n    AMID\n    \t rtoi_10276 | rtoi_10277 | rtoi_12640\n    \t rtoi_10276 | rtoi_10277 | rtoi_12540 | rtoi_12553 | rtoi_12640 | rtoi_12842\n    C3STDH1\n    \t rtoi_8835\n    \t rtoi_13724 | rtoi_8835\n    C3STDH2\n    \t rtoi_8835\n    \t rtoi_13724 | rtoi_8835\n    FAO141p_even\n    \t (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13228 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_13228 & rtoi_13813 & rtoi_9700)\n    \t (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13228 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13228 & rtoi_9065) | (rtoi_10293 & rtoi_11362 & rtoi_12752 & rtoi_13228 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_12752 & rtoi_13228 & rtoi_9065) | (rtoi_10293 & rtoi_11362 & rtoi_13228 & rtoi_13813 & rtoi_9700) | (rtoi_10293 & rtoi_11362 & rtoi_13228 & rtoi_9065 & rtoi_9700)\n    FAO141p_odd\n    \t (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_13813 & rtoi_9700)\n    \t (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_9065) | (rtoi_10293 & rtoi_11362 & rtoi_12752 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_12752 & rtoi_9065) | (rtoi_10293 & rtoi_11362 & rtoi_13813 & rtoi_9700) | (rtoi_10293 & rtoi_11362 & rtoi_9065 & rtoi_9700)\n    FAO161p_even\n    \t (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13228 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_13228 & rtoi_13813 & rtoi_9700)\n    \t (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13228 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13228 & rtoi_9065) | (rtoi_10293 & rtoi_11362 & rtoi_12752 & rtoi_13228 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_12752 & rtoi_13228 & rtoi_9065) | (rtoi_10293 & rtoi_11362 & rtoi_13228 & rtoi_13813 & rtoi_9700) | (rtoi_10293 & rtoi_11362 & rtoi_13228 & rtoi_9065 & rtoi_9700)\n    FAO161p_odd\n    \t (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_13813 & rtoi_9700)\n    \t (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_9065) | (rtoi_10293 & rtoi_11362 & rtoi_12752 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_12752 & rtoi_9065) | (rtoi_10293 & rtoi_11362 & rtoi_13813 & rtoi_9700) | (rtoi_10293 & rtoi_11362 & rtoi_9065 & rtoi_9700)\n    FAO181p_even\n    \t (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13228 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_13228 & rtoi_13813 & rtoi_9700)\n    \t (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13228 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13228 & rtoi_9065) | (rtoi_10293 & rtoi_11362 & rtoi_12752 & rtoi_13228 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_12752 & rtoi_13228 & rtoi_9065) | (rtoi_10293 & rtoi_11362 & rtoi_13228 & rtoi_13813 & rtoi_9700) | (rtoi_10293 & rtoi_11362 & rtoi_13228 & rtoi_9065 & rtoi_9700)\n    FAO181p_odd\n    \t (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_13813 & rtoi_9700)\n    \t (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_9065) | (rtoi_10293 & rtoi_11362 & rtoi_12752 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_12752 & rtoi_9065) | (rtoi_10293 & rtoi_11362 & rtoi_13813 & rtoi_9700) | (rtoi_10293 & rtoi_11362 & rtoi_9065 & rtoi_9700)\n    FAO182p_eveneven\n    \t (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13228 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_13228 & rtoi_13813 & rtoi_9700)\n    \t (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13228 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13228 & rtoi_9065) | (rtoi_10293 & rtoi_11362 & rtoi_12752 & rtoi_13228 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_12752 & rtoi_13228 & rtoi_9065) | (rtoi_10293 & rtoi_11362 & rtoi_13228 & rtoi_13813 & rtoi_9700) | (rtoi_10293 & rtoi_11362 & rtoi_13228 & rtoi_9065 & rtoi_9700)\n    FAO182p_evenodd\n    \t (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13228 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_13228 & rtoi_13813 & rtoi_9700)\n    \t (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13228 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13228 & rtoi_9065) | (rtoi_10293 & rtoi_11362 & rtoi_12752 & rtoi_13228 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_12752 & rtoi_13228 & rtoi_9065) | (rtoi_10293 & rtoi_11362 & rtoi_13228 & rtoi_13813 & rtoi_9700) | (rtoi_10293 & rtoi_11362 & rtoi_13228 & rtoi_9065 & rtoi_9700)\n    FAO182p_oddodd\n    \t (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_13813 & rtoi_9700)\n    \t (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_12742 & rtoi_9065) | (rtoi_10293 & rtoi_11362 & rtoi_12752 & rtoi_13813) | (rtoi_10293 & rtoi_11362 & rtoi_12752 & rtoi_9065) | (rtoi_10293 & rtoi_11362 & rtoi_13813 & rtoi_9700) | (rtoi_10293 & rtoi_11362 & rtoi_9065 & rtoi_9700)\n    FAO240p\n    \t (rtoi_11362 & rtoi_12742 & rtoi_13813) | (rtoi_11362 & rtoi_13813 & rtoi_9700)\n    \t (rtoi_11362 & rtoi_12742 & rtoi_13813) | (rtoi_11362 & rtoi_12742 & rtoi_9065) | (rtoi_11362 & rtoi_12752 & rtoi_13813) | (rtoi_11362 & rtoi_12752 & rtoi_9065) | (rtoi_11362 & rtoi_13813 & rtoi_9700) | (rtoi_11362 & rtoi_9065 & rtoi_9700)\n    FAO80p\n    \t (rtoi_11362 & rtoi_12742 & rtoi_13813) | (rtoi_11362 & rtoi_13813 & rtoi_9700)\n    \t (rtoi_11362 & rtoi_12742 & rtoi_13813) | (rtoi_11362 & rtoi_12742 & rtoi_9065) | (rtoi_11362 & rtoi_12752 & rtoi_13813) | (rtoi_11362 & rtoi_12752 & rtoi_9065) | (rtoi_11362 & rtoi_13813 & rtoi_9700) | (rtoi_11362 & rtoi_9065 & rtoi_9700)\n    FRUt2\n    \t rtoi_11893\n    \t rtoi_11075 | rtoi_11893\n    G3PD1ir\n    \t rtoi_12154\n    \t rtoi_12154 | rtoi_14576\n    G3PD1irm\n    \t rtoi_12154\n    \t rtoi_12154 | rtoi_14576\n    GCC2cm\n    \t rtoi_10040\n    \t rtoi_10040 & rtoi_10205 & rtoi_12898 & rtoi_15184\n    GLUK\n    \t rtoi_10264\n    \t rtoi_10264 | rtoi_11982\n    GLYCDy\n    \t rtoi_11882\n    \t rtoi_11882 | rtoi_12784 | rtoi_9774\n    GLYO1\n    \t rtoi_15994\n    \t rtoi_15449 | rtoi_15994\n    H2Otm\n    \t rtoi_13986\n    \t rtoi_13986 | rtoi_13987 | rtoi_9014 | rtoi_9015\n    HBCO_nadp\n    \t rtoi_15180\n    \t rtoi_11203 | rtoi_15180\n    HEX7\n    \t rtoi_11982\n    \t rtoi_10264 | rtoi_11982\n    ILETA\n    \t rtoi_14610 | rtoi_14853\n    \t rtoi_14014 | rtoi_14610 | rtoi_14853\n    ILETAm\n    \t rtoi_14610 | rtoi_14853\n    \t rtoi_14014 | rtoi_14610 | rtoi_14853\n    IMACTD\n    \t rtoi_12042 | rtoi_13426\n    \t rtoi_12042 | rtoi_13426 | rtoi_15814 | rtoi_16323\n    KAT180_m\n    \t rtoi_13813\n    \t rtoi_13813 | rtoi_9065\n    LALDO3\n    \t rtoi_10497 | rtoi_11160 | rtoi_12151\n    \t rtoi_10497 | rtoi_11160 | rtoi_12151 | rtoi_12883\n    LEUTA\n    \t rtoi_14610 | rtoi_14853\n    \t rtoi_14014 | rtoi_14610 | rtoi_14853\n    LEUTAm\n    \t rtoi_14610 | rtoi_14853\n    \t rtoi_14014 | rtoi_14610 | rtoi_14853\n    MACCOAT\n    \t rtoi_13813\n    \t rtoi_13813 | rtoi_9065\n    MANt2\n    \t rtoi_11893\n    \t rtoi_11075 | rtoi_11893\n    ME1m\n    \t rtoi_13917\n    \t rtoi_12761 | rtoi_13917\n    ME2\n    \t rtoi_12761\n    \t rtoi_12761 | rtoi_13917\n    ME2m\n    \t rtoi_13917\n    \t rtoi_12761 | rtoi_13917\n    MI1PP\n    \t rtoi_16369\n    \t rtoi_13708 | rtoi_16369\n    MI3PP\n    \t rtoi_16369\n    \t rtoi_13708 | rtoi_16369\n    MI4PP\n    \t rtoi_16369\n    \t rtoi_13708 | rtoi_16369\n    OIVD3m\n    \t rtoi_11183 | rtoi_11188 | rtoi_12566 | rtoi_15436\n    \t (rtoi_10040 & rtoi_11183 & rtoi_12086 & rtoi_15436) | (rtoi_10040 & rtoi_11183 & rtoi_12566 & rtoi_15436) | (rtoi_10040 & rtoi_11188 & rtoi_12086 & rtoi_15436) | (rtoi_10040 & rtoi_11188 & rtoi_12566 & rtoi_15436)\n    OMCDC\n    \t rtoi_14610 | rtoi_14853\n    \t rtoi_14014 | rtoi_14610 | rtoi_14853\n    OMCDCm\n    \t rtoi_14610 | rtoi_14853\n    \t rtoi_14014 | rtoi_14610 | rtoi_14853\n    PIt5m\n    \t rtoi_8889\n    \t rtoi_15874 | rtoi_8889\n    PPCOAOm\n    \t rtoi_10408\n    \t rtoi_10408 | rtoi_12570 | rtoi_14070\n    SACCD1\n    \t rtoi_16833\n    \t rtoi_10577 | rtoi_16833\n    SACCD4m\n    \t rtoi_16833\n    \t rtoi_10577 | rtoi_16833\n    SELMETAT\n    \t rtoi_13771\n    \t rtoi_13771 | (rtoi_11793 & rtoi_13771)\n    TRPTA\n    \t rtoi_14908 | rtoi_15839\n    \t rtoi_12407 | rtoi_14908 | rtoi_15839\n    VALTA\n    \t rtoi_14610 | rtoi_14853\n    \t rtoi_14014 | rtoi_14610 | rtoi_14853\n    VALTAim\n    \t rtoi_14610 | rtoi_14853\n    \t rtoi_14014 | rtoi_14610 | rtoi_14853\n    yli_R0191\n    \t rtoi_12742 | rtoi_9700\n    \t rtoi_12742 | rtoi_12752 | rtoi_9700\n    yli_R0194\n    \t rtoi_13813\n    \t rtoi_13813 | rtoi_9065\n    yli_R0195\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_13813 & rtoi_14805 & rtoi_9700)\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_12742 & rtoi_14805 & rtoi_9065) | (rtoi_12752 & rtoi_13813 & rtoi_14805) | (rtoi_12752 & rtoi_14805 & rtoi_9065) | (rtoi_13813 & rtoi_14805 & rtoi_9700) | (rtoi_14805 & rtoi_9065 & rtoi_9700)\n    yli_R0196\n    \t rtoi_12742 | rtoi_9700\n    \t rtoi_12742 | rtoi_12752 | rtoi_9700\n    yli_R0200\n    \t rtoi_12742 | rtoi_9700\n    \t rtoi_12742 | rtoi_12752 | rtoi_9700\n    yli_R0204\n    \t rtoi_12742 | rtoi_9700\n    \t rtoi_12742 | rtoi_12752 | rtoi_9700\n    yli_R0208\n    \t rtoi_12742 | rtoi_9700\n    \t rtoi_12742 | rtoi_12752 | rtoi_9700\n    yli_R0211\n    \t rtoi_13813\n    \t rtoi_13813 | rtoi_9065\n    yli_R0212\n    \t rtoi_12742 | rtoi_9700\n    \t rtoi_12742 | rtoi_12752 | rtoi_9700\n    yli_R0216\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_13813 & rtoi_14805 & rtoi_9700)\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_12742 & rtoi_14805 & rtoi_9065) | (rtoi_12752 & rtoi_13813 & rtoi_14805) | (rtoi_12752 & rtoi_14805 & rtoi_9065) | (rtoi_13813 & rtoi_14805 & rtoi_9700) | (rtoi_14805 & rtoi_9065 & rtoi_9700)\n    yli_R0217\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_13813 & rtoi_14805 & rtoi_9700)\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_12742 & rtoi_14805 & rtoi_9065) | (rtoi_12752 & rtoi_13813 & rtoi_14805) | (rtoi_12752 & rtoi_14805 & rtoi_9065) | (rtoi_13813 & rtoi_14805 & rtoi_9700) | (rtoi_14805 & rtoi_9065 & rtoi_9700)\n    yli_R0218\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_13813 & rtoi_14805 & rtoi_9700)\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_12742 & rtoi_14805 & rtoi_9065) | (rtoi_12752 & rtoi_13813 & rtoi_14805) | (rtoi_12752 & rtoi_14805 & rtoi_9065) | (rtoi_13813 & rtoi_14805 & rtoi_9700) | (rtoi_14805 & rtoi_9065 & rtoi_9700)\n    yli_R0219\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_13813 & rtoi_14805 & rtoi_9700)\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_12742 & rtoi_14805 & rtoi_9065) | (rtoi_12752 & rtoi_13813 & rtoi_14805) | (rtoi_12752 & rtoi_14805 & rtoi_9065) | (rtoi_13813 & rtoi_14805 & rtoi_9700) | (rtoi_14805 & rtoi_9065 & rtoi_9700)\n    yli_R0220\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_13813 & rtoi_14805 & rtoi_9700)\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_12742 & rtoi_14805 & rtoi_9065) | (rtoi_12752 & rtoi_13813 & rtoi_14805) | (rtoi_12752 & rtoi_14805 & rtoi_9065) | (rtoi_13813 & rtoi_14805 & rtoi_9700) | (rtoi_14805 & rtoi_9065 & rtoi_9700)\n    yli_R0221\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_13813 & rtoi_14805 & rtoi_9700)\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_12742 & rtoi_14805 & rtoi_9065) | (rtoi_12752 & rtoi_13813 & rtoi_14805) | (rtoi_12752 & rtoi_14805 & rtoi_9065) | (rtoi_13813 & rtoi_14805 & rtoi_9700) | (rtoi_14805 & rtoi_9065 & rtoi_9700)\n    yli_R0222\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_13813 & rtoi_14805 & rtoi_9700)\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_12742 & rtoi_14805 & rtoi_9065) | (rtoi_12752 & rtoi_13813 & rtoi_14805) | (rtoi_12752 & rtoi_14805 & rtoi_9065) | (rtoi_13813 & rtoi_14805 & rtoi_9700) | (rtoi_14805 & rtoi_9065 & rtoi_9700)\n    yli_R0223\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_13813 & rtoi_14805 & rtoi_9700)\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_12742 & rtoi_14805 & rtoi_9065) | (rtoi_12752 & rtoi_13813 & rtoi_14805) | (rtoi_12752 & rtoi_14805 & rtoi_9065) | (rtoi_13813 & rtoi_14805 & rtoi_9700) | (rtoi_14805 & rtoi_9065 & rtoi_9700)\n    yli_R0224\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_13813 & rtoi_14805 & rtoi_9700)\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_12742 & rtoi_14805 & rtoi_9065) | (rtoi_12752 & rtoi_13813 & rtoi_14805) | (rtoi_12752 & rtoi_14805 & rtoi_9065) | (rtoi_13813 & rtoi_14805 & rtoi_9700) | (rtoi_14805 & rtoi_9065 & rtoi_9700)\n    yli_R0225\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_13813 & rtoi_14805 & rtoi_9700)\n    \t (rtoi_12742 & rtoi_13813 & rtoi_14805) | (rtoi_12742 & rtoi_14805 & rtoi_9065) | (rtoi_12752 & rtoi_13813 & rtoi_14805) | (rtoi_12752 & rtoi_14805 & rtoi_9065) | (rtoi_13813 & rtoi_14805 & rtoi_9700) | (rtoi_14805 & rtoi_9065 & rtoi_9700)\n    yli_R0742\n    \t rtoi_8835\n    \t rtoi_13724 | rtoi_8835\n    yli_R0937\n    \t rtoi_12566 & rtoi_15436\n    \t (rtoi_12086 & rtoi_15436) | (rtoi_12566 & rtoi_15436)\n    yli_R0938\n    \t rtoi_12566 & rtoi_15436\n    \t (rtoi_12086 & rtoi_15436) | (rtoi_12566 & rtoi_15436)\n    yli_R0939\n    \t rtoi_12566 & rtoi_15436\n    \t (rtoi_12086 & rtoi_15436) | (rtoi_12566 & rtoi_15436)\n    yli_R1133\n    \t rtoi_11893\n    \t rtoi_11075 | rtoi_11893\n    yli_R1397\n    \t rtoi_12154\n    \t rtoi_12154 | rtoi_14576\n    yli_R1442\n    \t rtoi_8835\n    \t rtoi_13724 | rtoi_8835\n    yli_R1587\n    \t rtoi_12566 & rtoi_15436\n    \t (rtoi_12086 & rtoi_15436) | (rtoi_12566 & rtoi_15436)\n    yli_R1590\n    \t rtoi_12566 & rtoi_15436\n    \t (rtoi_12086 & rtoi_15436) | (rtoi_12566 & rtoi_15436)\n    yli_R1591\n    \t rtoi_12566 & rtoi_15436\n    \t (rtoi_12086 & rtoi_15436) | (rtoi_12566 & rtoi_15436)\n    yli_R1592\n    \t rtoi_12566 & rtoi_15436\n    \t (rtoi_12086 & rtoi_15436) | (rtoi_12566 & rtoi_15436)\n\n\n\n```python\nReaction_to_gene['FAO141p_even']\n```\n\n\n\n\n    {'sce|YGL205W': {'rtoi|12742', 'rtoi|9700'},\n     'sce|YIL160C': {'rtoi|13813'},\n     'sce|YKR009C': {'rtoi|11362'},\n     'sce|YLR284C': {'rtoi|10293'},\n     'sce|YNL202W': {'rtoi|13228'},\n     'sce|YOR180C': {'rtoi|10293'}}\n\n\n\n\n```python\nReaction_to_gene_Jeff['FAO141p_even']\n```\n\n\n\n\n    {'sce|YGL205W': {'rtoi|12742', 'rtoi|12752', 'rtoi|9700'},\n     'sce|YIL160C': {'rtoi|13813', 'rtoi|9065'},\n     'sce|YKR009C': {'rtoi|11362'},\n     'sce|YLR284C': {'rtoi|10293'},\n     'sce|YNL202W': {'rtoi|13228'},\n     'sce|YOR180C': {'rtoi|10293'}}\n\n\n\n\n```python\nfor x in set(Reaction_rule_unique.keys()).intersection(Reaction_rule_Jeff_unique):\n    if not Reaction_rule_unique[x] == Reaction_rule_Jeff_unique[x]:\n        temp1 = Reaction_rule_unique[x]\n        temp2 = Reaction_rule_Jeff_unique[x]\n        if not set(temp1.free_symbols).difference(temp2.free_symbols) and set(temp2.free_symbols).difference(temp1.free_symbols):\n            Reaction_rule_final[x] = temp2\n```\n\n\n```python\nfor x in sorted(set(Reaction_rule_unique.keys()).intersection(Reaction_rule_Jeff_unique)):\n    if not Reaction_rule_unique[x] == Reaction_rule_Jeff_unique[x]:\n        temp1 = Reaction_rule_unique[x]\n        temp2 = Reaction_rule_Jeff_unique[x]\n        if not set(temp1.free_symbols).difference(temp2.free_symbols) and not set(temp2.free_symbols).difference(temp1.free_symbols):\n            print(x)\n            print('\\t',temp1)\n            print('\\t',temp2)\n```\n\n    ATPS3g\n    \t rtoi_11025 & rtoi_11052 & rtoi_11064 & rtoi_11117 & rtoi_11403 & rtoi_14971 & rtoi_15309 & rtoi_15351 & rtoi_15963 & rtoi_16397 & rtoi_9210 & rtoi_9622 & rtoi_9748\n    \t (rtoi_11025 & rtoi_11052 & rtoi_11064 & rtoi_11117 & rtoi_11403 & rtoi_14971 & rtoi_15309 & rtoi_15351 & rtoi_15963 & rtoi_16397 & rtoi_9210 & rtoi_9622) | (rtoi_11052 & rtoi_11064 & rtoi_11117 & rtoi_11403 & rtoi_14971 & rtoi_15309 & rtoi_15351 & rtoi_15963 & rtoi_16397 & rtoi_9210 & rtoi_9622 & rtoi_9748)\n    ATPS3v\n    \t rtoi_11025 & rtoi_11052 & rtoi_11064 & rtoi_11117 & rtoi_11403 & rtoi_14971 & rtoi_15309 & rtoi_15351 & rtoi_15963 & rtoi_16397 & rtoi_9210 & rtoi_9622 & rtoi_9748\n    \t (rtoi_11025 & rtoi_11052 & rtoi_11064 & rtoi_11117 & rtoi_11403 & rtoi_14971 & rtoi_15309 & rtoi_15351 & rtoi_15963 & rtoi_16397 & rtoi_9210 & rtoi_9622) | (rtoi_11052 & rtoi_11064 & rtoi_11117 & rtoi_11403 & rtoi_14971 & rtoi_15309 & rtoi_15351 & rtoi_15963 & rtoi_16397 & rtoi_9210 & rtoi_9622 & rtoi_9748)\n    FA120ACPHi\n    \t rtoi_8670 & rtoi_8777\n    \t rtoi_8670 | rtoi_8777\n    FA140ACPHi\n    \t rtoi_8670 & rtoi_8777\n    \t rtoi_8670 | rtoi_8777\n    FA141ACPHi\n    \t rtoi_8670 & rtoi_8777\n    \t rtoi_8670 | rtoi_8777\n    FA160ACPHi\n    \t rtoi_8670 & rtoi_8777\n    \t rtoi_8670 | rtoi_8777\n    FA161ACPHi\n    \t rtoi_8670 & rtoi_8777\n    \t rtoi_8670 | rtoi_8777\n    FA180ACPH\n    \t rtoi_8670 & rtoi_8777\n    \t rtoi_8670 | rtoi_8777\n    FA181ACPH\n    \t rtoi_8670 & rtoi_8777\n    \t rtoi_8670 | rtoi_8777\n    FA182ACPH\n    \t rtoi_8670 & rtoi_8777\n    \t rtoi_8670 | rtoi_8777\n    yli_R0163\n    \t YALI0F30679g & rtoi_8670 & rtoi_8777\n    \t (YALI0F30679g & rtoi_8670) | (YALI0F30679g & rtoi_8777)\n    yli_R0164\n    \t YALI0F30679g & rtoi_8670 & rtoi_8777\n    \t (YALI0F30679g & rtoi_8670) | (YALI0F30679g & rtoi_8777)\n    yli_R0165\n    \t YALI0F30679g & rtoi_8670 & rtoi_8777\n    \t (YALI0F30679g & rtoi_8670) | (YALI0F30679g & rtoi_8777)\n    yli_R0166\n    \t YALI0F30679g & rtoi_8670 & rtoi_8777\n    \t (YALI0F30679g & rtoi_8670) | (YALI0F30679g & rtoi_8777)\n    yli_R0167\n    \t YALI0F30679g & rtoi_8670 & rtoi_8777\n    \t (YALI0F30679g & rtoi_8670) | (YALI0F30679g & rtoi_8777)\n    yli_R0168\n    \t YALI0F30679g & rtoi_8670 & rtoi_8777\n    \t (YALI0F30679g & rtoi_8670) | (YALI0F30679g & rtoi_8777)\n    yli_R0169\n    \t YALI0F30679g & rtoi_8670 & rtoi_8777\n    \t (YALI0F30679g & rtoi_8670) | (YALI0F30679g & rtoi_8777)\n    yli_R0170\n    \t YALI0F30679g & rtoi_8670 & rtoi_8777\n    \t (YALI0F30679g & rtoi_8670) | (YALI0F30679g & rtoi_8777)\n    yli_R0171\n    \t YALI0F30679g & rtoi_8670 & rtoi_8777\n    \t (YALI0F30679g & rtoi_8670) | (YALI0F30679g & rtoi_8777)\n    yli_R0172\n    \t YALI0F30679g & rtoi_8670 & rtoi_8777\n    \t (YALI0F30679g & rtoi_8670) | (YALI0F30679g & rtoi_8777)\n    yli_R0173\n    \t rtoi_8670 & rtoi_8777\n    \t rtoi_8670 | rtoi_8777\n    yli_R0174\n    \t rtoi_8670 & rtoi_8777\n    \t rtoi_8670 | rtoi_8777\n    yli_R0175\n    \t rtoi_8670 & rtoi_8777\n    \t rtoi_8670 | rtoi_8777\n    yli_R0176\n    \t rtoi_8670 & rtoi_8777\n    \t rtoi_8670 | rtoi_8777\n    yli_R0177\n    \t rtoi_8670 & rtoi_8777\n    \t rtoi_8670 | rtoi_8777\n    yli_R0178\n    \t rtoi_8670 & rtoi_8777\n    \t rtoi_8670 | rtoi_8777\n    yli_R0179\n    \t rtoi_8670 & rtoi_8777\n    \t rtoi_8670 | rtoi_8777\n    yli_R0180\n    \t rtoi_8670 & rtoi_8777\n    \t rtoi_8670 | rtoi_8777\n\n\n\n```python\n# ATPS3g and ATPS3v - 11025 & 9748 vs 11025 | 9748\n# FAS - 8670 & 8777 vs 8670 & 8777\n# choose subunit based on the published models\nfor x in sorted(set(Reaction_rule_unique.keys()).intersection(Reaction_rule_Jeff_unique)):\n    if not Reaction_rule_unique[x] == Reaction_rule_Jeff_unique[x]:\n        temp1 = Reaction_rule_unique[x]\n        temp2 = Reaction_rule_Jeff_unique[x]\n        if not set(temp1.free_symbols).difference(temp2.free_symbols) and not set(temp2.free_symbols).difference(temp1.free_symbols):\n            Reaction_rule_final[x] = temp1\n```\n\n\n```python\nfor x in sorted(set(Reaction_rule.keys()).intersection(Reaction_rule_Jeff_unique)):\n    if x not in Reaction_rule_final:\n        print(x)\n        print('\\t',Reaction_rule[x])\n        print('\\t',Reaction_rule_Jeff_unique[x])\n```\n\n    2DOXG6PP\n    \t {'sce': rtoi_13413, 'eco': rtoi_8460 | rtoi_8576}\n    \t rtoi_13413\n    ABTA\n    \t {'sce': rtoi_15905, 'eco': rtoi_10937, 'ppu': rtoi_10937, 'yli': rtoi_15905}\n    \t rtoi_15905\n    ABUTt2r\n    \t {'sce': rtoi_11269 | rtoi_13423, 'yli': (YALI0B09537g & rtoi_11269) | (YALI0B09537g & rtoi_13423)}\n    \t rtoi_12743\n    ACACT1r\n    \t {'sce': rtoi_8678 | rtoi_8885, 'eco': rtoi_13813 | rtoi_8678 | rtoi_8885, 'cre': rtoi_8678 | rtoi_8885, 'yli': rtoi_8678 | rtoi_8885}\n    \t rtoi_8678\n    ACCOAC\n    \t {'sce': rtoi_8639, 'eco': b0185 & b2316 & b3255 & rtoi_12867, 'ppu': PP_0559 & PP_1607 & PP_1996 & rtoi_12867, 'yli': rtoi_8639}\n    \t rtoi_8639\n    ACOATA\n    \t {'sce': rtoi_8670 & rtoi_8777, 'eco': b1091 & rtoi_14261, 'yli': rtoi_8670 & rtoi_8777}\n    \t rtoi_8670 | rtoi_8777\n    ACP1e\n    \t {'sce': rtoi_10885, 'yli': rtoi_13856 | rtoi_13935}\n    \t rtoi_13856 | rtoi_13935\n    ADCS\n    \t {'sce': rtoi_13669, 'eco': rtoi_13669 & rtoi_16564, 'cre': rtoi_13669 & rtoi_16564, 'yli': rtoi_13669}\n    \t rtoi_13669\n    ADNK1\n    \t {'sce': rtoi_8385, 'eco': rtoi_15496, 'cre': rtoi_8385, 'yli': rtoi_8385}\n    \t rtoi_8385\n    ADPT\n    \t {'sce': rtoi_16193, 'eco': rtoi_16193, 'ppu': rtoi_16193, 'cre': rtoi_12445 | rtoi_16193, 'yli': rtoi_16193}\n    \t rtoi_16193\n    AKGDam\n    \t {'sce': (rtoi_10007 & rtoi_10040 & rtoi_12116) | (rtoi_10040 & rtoi_12116 & rtoi_9274), 'cre': rtoi_10007 | rtoi_9274}\n    \t (rtoi_10007 & rtoi_10040 & rtoi_12116) | (rtoi_10040 & rtoi_12116 & rtoi_9274)\n    ALCD19y\n    \t {'sce': rtoi_11882, 'cre': rtoi_12784 | rtoi_9774}\n    \t rtoi_11882 | rtoi_12784 | rtoi_9774\n    ALCD2ir\n    \t {'sce': rtoi_11665 | rtoi_15438, 'ppu': rtoi_15438, 'cre': rtoi_11665}\n    \t rtoi_11665 | rtoi_15438\n    ALCD2irm\n    \t {'sce': rtoi_15438, 'cre': rtoi_11665}\n    \t rtoi_15438\n    AMPTASECG\n    \t {'eco': rtoi_12096, 'yli': rtoi_10210}\n    \t rtoi_10210\n    ARGt2r\n    \t {'sce': rtoi_14229 | rtoi_15074 | rtoi_8962 | rtoi_9319 | rtoi_9322, 'yli': (rtoi_14229 & rtoi_8962) | (rtoi_14229 & rtoi_9319) | (rtoi_14229 & rtoi_9322) | (rtoi_15074 & rtoi_8962) | (rtoi_15074 & rtoi_9319) | (rtoi_15074 & rtoi_9322)}\n    \t rtoi_14229 | rtoi_15074\n    ASNN\n    \t {'sce': rtoi_10043 | rtoi_13627, 'eco': rtoi_8853, 'ppu': rtoi_8853}\n    \t rtoi_10043 | rtoi_13627\n    ASPK\n    \t {'sce': rtoi_14662, 'eco': rtoi_12080 | rtoi_14662 | rtoi_16738, 'ppu': rtoi_14662, 'yli': rtoi_14662}\n    \t rtoi_14662\n    ATPS3m\n    \t {'sce': (Q0080 & Q0085 & Q0130 & YPL271W & rtoi_10674 & rtoi_10675 & rtoi_11958 & rtoi_11967 & rtoi_13424 & rtoi_13759 & rtoi_14786 & rtoi_14912 & rtoi_15589 & rtoi_16359 & rtoi_9940) | (Q0080 & Q0085 & Q0130 & YOL077W_A & YPL271W & rtoi_10674 & rtoi_10675 & rtoi_11958 & rtoi_11967 & rtoi_13424 & rtoi_13759 & rtoi_14786 & rtoi_14912 & rtoi_15589 & rtoi_15880 & rtoi_16359 & rtoi_9080 & rtoi_9940), 'cre': (CRv4_Au5_s10_g33_t1 & CRv4_Au5_s10_g65_t1 & CRv4_Au5_s17_g7684_t1 & CRv4_Au5_s1_g1345_t1 & CRv4_Au5_s1_g1960_t1 & rtoi_11958 & rtoi_11967 & rtoi_13424 & rtoi_15287 & rtoi_15589) | (CRv4_Au5_s10_g33_t1 & CRv4_Au5_s10_g65_t1 & CRv4_Au5_s17_g7685_t1 & CRv4_Au5_s1_g1345_t1 & CRv4_Au5_s1_g1960_t1 & rtoi_11958 & rtoi_11967 & rtoi_13424 & rtoi_15287 & rtoi_15589) | (CRv4_Au5_s10_g65_t1 & CRv4_Au5_s17_g7684_t1 & CRv4_Au5_s1_g1345_t1 & CRv4_Au5_s1_g1960_t1 & rtoi_11958 & rtoi_11967 & rtoi_13424 & rtoi_15287 & rtoi_15589 & rtoi_16359) | (CRv4_Au5_s10_g65_t1 & CRv4_Au5_s17_g7685_t1 & CRv4_Au5_s1_g1345_t1 & CRv4_Au5_s1_g1960_t1 & rtoi_11958 & rtoi_11967 & rtoi_13424 & rtoi_15287 & rtoi_15589 & rtoi_16359)}\n    \t (Q0080 & Q0085 & Q0130 & YDL181W & YPL271W & rtoi_10674 & rtoi_11958 & rtoi_11967 & rtoi_13424 & rtoi_13759 & rtoi_14786 & rtoi_14912 & rtoi_15589 & rtoi_16359 & rtoi_9940) | (Q0080 & Q0085 & Q0130 & YDL181W & YOL077W_A & YPL271W & YPR020W & rtoi_10674 & rtoi_11958 & rtoi_11967 & rtoi_13424 & rtoi_13759 & rtoi_14786 & rtoi_14912 & rtoi_15589 & rtoi_15880 & rtoi_16359 & rtoi_9940)\n    CAT\n    \t {'sce': rtoi_9354, 'eco': rtoi_9354, 'ppu': rtoi_15305 | rtoi_9354}\n    \t rtoi_9354\n    CCP2m\n    \t {'sce': rtoi_13161 & rtoi_8802, 'cre': (rtoi_13161 & rtoi_8802) | (rtoi_13161 & rtoi_9198)}\n    \t (rtoi_10811 & rtoi_8802) | (rtoi_13161 & rtoi_8802)\n    CDPPH\n    \t {'cre': rtoi_9805, 'yli': rtoi_8970}\n    \t rtoi_8970\n    CITtam\n    \t {'sce': rtoi_10514, 'cre': rtoi_11740 | rtoi_13510, 'yli': rtoi_10514}\n    \t rtoi_10514\n    CITtcm\n    \t {'sce': rtoi_10514, 'cre': rtoi_11740 | rtoi_13510, 'yli': rtoi_10514}\n    \t rtoi_10514\n    CS\n    \t {'eco': rtoi_8548, 'ppu': rtoi_8548, 'yli': rtoi_11331}\n    \t rtoi_11331\n    CSND\n    \t {'sce': rtoi_14559, 'cre': rtoi_14031, 'yli': rtoi_14559}\n    \t rtoi_14559\n    CSp\n    \t {'sce': rtoi_11331, 'cre': rtoi_8548}\n    \t rtoi_11331\n    CYTDK1\n    \t {'eco': rtoi_8633, 'cre': rtoi_8633 | rtoi_9093, 'yli': rtoi_8633}\n    \t rtoi_8633\n    CYTDK2\n    \t {'sce': rtoi_8633, 'eco': rtoi_8633, 'cre': rtoi_8633 | rtoi_9093, 'yli': rtoi_8633}\n    \t rtoi_8633\n    DADK\n    \t {'eco': rtoi_15496, 'ppu': rtoi_15496, 'cre': rtoi_12300 | rtoi_15496, 'yli': rtoi_15129 | rtoi_15496}\n    \t rtoi_15129 | rtoi_15496\n    DATCY\n    \t {'cre': rtoi_8633 | rtoi_9093, 'yli': rtoi_8633}\n    \t rtoi_8633\n    DATUP\n    \t {'cre': rtoi_8633 | rtoi_9093, 'yli': rtoi_8633}\n    \t rtoi_8633\n    DCTCP\n    \t {'cre': rtoi_8633 | rtoi_9093, 'yli': rtoi_8633}\n    \t rtoi_8633\n    DCTUP\n    \t {'cre': rtoi_8633 | rtoi_9093, 'yli': rtoi_8633}\n    \t rtoi_8633\n    DGTCY\n    \t {'cre': rtoi_8633 | rtoi_9093, 'yli': rtoi_8633}\n    \t rtoi_8633\n    DGTUP\n    \t {'cre': rtoi_8633 | rtoi_9093, 'yli': rtoi_8633}\n    \t rtoi_8633\n    DHFS\n    \t {'eco': rtoi_10460, 'ppu': rtoi_10460, 'yli': rtoi_10460 | rtoi_14803}\n    \t rtoi_10460 | rtoi_14803\n    DHORDfum\n    \t {'sce': rtoi_14866, 'yli': rtoi_8814}\n    \t rtoi_8814\n    DHQTi\n    \t {'sce': rtoi_14252, 'ppu': rtoi_10572, 'yli': rtoi_14252}\n    \t rtoi_14252\n    DNMPPA\n    \t {'sce': rtoi_14615, 'cre': rtoi_15385}\n    \t rtoi_14615 | rtoi_14875\n    DPR\n    \t {'sce': rtoi_14277, 'eco': rtoi_14277 | rtoi_9176, 'ppu': rtoi_14277 | rtoi_16522, 'yli': rtoi_14277}\n    \t rtoi_14277\n    DTPH\n    \t {'cre': rtoi_9805, 'yli': rtoi_8970}\n    \t rtoi_8970\n    DTTGY\n    \t {'cre': rtoi_8633 | rtoi_9093, 'yli': rtoi_8633}\n    \t rtoi_8633\n    DTTUP\n    \t {'cre': rtoi_8633 | rtoi_9093, 'yli': rtoi_8633}\n    \t rtoi_8633\n    DURIPP\n    \t {'sce': rtoi_16276, 'eco': rtoi_14521, 'yli': rtoi_16276}\n    \t rtoi_16276\n    DUTCP\n    \t {'cre': rtoi_8633 | rtoi_9093, 'yli': rtoi_8633}\n    \t rtoi_8633\n    DUTPDP\n    \t {'sce': rtoi_8399, 'eco': rtoi_8399, 'ppu': rtoi_8399, 'cre': rtoi_13900 | rtoi_8399, 'yli': rtoi_8399}\n    \t rtoi_8399\n    DUTUP\n    \t {'cre': rtoi_8633 | rtoi_9093, 'yli': rtoi_8633}\n    \t rtoi_8633\n    ECOAH1\n    \t {'ppu': rtoi_14805, 'cre': rtoi_16128, 'yli': rtoi_14805}\n    \t rtoi_14805\n    ECOAH4m\n    \t {'cre': rtoi_11907, 'yli': rtoi_14805}\n    \t rtoi_14805\n    ECOAH5m\n    \t {'cre': rtoi_11907, 'yli': rtoi_14805}\n    \t rtoi_14805\n    ECOAH6m\n    \t {'cre': rtoi_11907, 'yli': rtoi_14805}\n    \t rtoi_14805\n    ECOAH7m\n    \t {'cre': rtoi_11907, 'yli': rtoi_14805}\n    \t rtoi_14805\n    FBP\n    \t {'sce': rtoi_15423, 'eco': rtoi_11513 | rtoi_15423, 'ppu': rtoi_15423}\n    \t rtoi_15423\n    FDH\n    \t {'sce': rtoi_11952, 'ppu': (PP_0490 & PP_0491 & PP_0492) | (PP_2183 & PP_2184 & PP_2186 & rtoi_13272), 'yli': rtoi_11952}\n    \t rtoi_11952\n    GLUDy\n    \t {'sce': rtoi_12248, 'eco': rtoi_12248 | (b3213 & rtoi_15713), 'ppu': rtoi_12248, 'yli': rtoi_12248}\n    \t rtoi_12248\n    GLUTRS\n    \t {'sce': rtoi_10753, 'eco': rtoi_14565, 'ppu': rtoi_14565, 'cre': rtoi_10753 | rtoi_14565}\n    \t rtoi_10753\n    GLYCTO1\n    \t {'ppu': PP_3746 & PP_3747 & rtoi_13328, 'yli': rtoi_14950}\n    \t rtoi_16607\n    GTPCII\n    \t {'sce': rtoi_12551, 'ppu': rtoi_12551 | rtoi_16666}\n    \t rtoi_12551\n    H2Ot\n    \t {'sce': rtoi_13987 | rtoi_9015, 'cre': rtoi_13986}\n    \t rtoi_13986 | rtoi_13987 | rtoi_9014 | rtoi_9015\n    HEX4\n    \t {'sce': rtoi_11982, 'cre': rtoi_10264, 'yli': rtoi_10264 | rtoi_11982}\n    \t rtoi_10264 | rtoi_11982\n    HISDr\n    \t {'ppu': rtoi_16462, 'cre': rtoi_15434}\n    \t rtoi_16462\n    HISTP\n    \t {'sce': rtoi_10206, 'eco': rtoi_8707, 'yli': rtoi_10206}\n    \t rtoi_10206\n    HPHL\n    \t {'cre': rtoi_16128, 'yli': rtoi_14805}\n    \t rtoi_14805\n    HPYRRy\n    \t {'eco': rtoi_11036 | rtoi_12051, 'cre': rtoi_9515}\n    \t rtoi_11036\n    HSDy\n    \t {'sce': rtoi_12080, 'eco': rtoi_12080 | rtoi_16738, 'yli': rtoi_12080}\n    \t rtoi_12080\n    ICDHyr\n    \t {'sce': rtoi_11129, 'eco': rtoi_11681, 'ppu': rtoi_11681, 'cre': rtoi_11129, 'yli': rtoi_11129}\n    \t rtoi_11129\n    IDPA\n    \t {'cre': rtoi_9805, 'yli': rtoi_8970}\n    \t rtoi_8970\n    IPMD\n    \t {'sce': rtoi_13894, 'eco': rtoi_10428 | rtoi_13894, 'ppu': rtoi_13894, 'cre': rtoi_13894}\n    \t rtoi_13894\n    IPPMIa\n    \t {'sce': rtoi_14914, 'eco': b0071 & rtoi_14914, 'ppu': PP_1986 & rtoi_14914, 'cre': CRv4_Au5_s6_g12448_t1 & rtoi_14914, 'yli': rtoi_14914}\n    \t rtoi_14914\n    IPPMIb\n    \t {'sce': rtoi_14914, 'eco': b0071 & rtoi_14914, 'ppu': PP_1986 & rtoi_14914, 'cre': CRv4_Au5_s6_g12448_t1 & rtoi_14914, 'yli': rtoi_14914}\n    \t rtoi_14914\n    IPPS\n    \t {'sce': rtoi_15488, 'eco': rtoi_14856, 'ppu': rtoi_15488, 'cre': rtoi_14856, 'yli': rtoi_15488}\n    \t rtoi_15488\n    ITCY\n    \t {'cre': rtoi_8633 | rtoi_9093, 'yli': rtoi_8633}\n    \t rtoi_8633\n    LNS14DM\n    \t {'sce': rtoi_12843 & rtoi_13286, 'cre': rtoi_12843}\n    \t rtoi_12843 & rtoi_13286\n    LYSt2r\n    \t {'sce': rtoi_14229 | rtoi_15074 | rtoi_8962 | rtoi_9319 | rtoi_9322, 'yli': (rtoi_14229 & rtoi_8962) | (rtoi_14229 & rtoi_9319) | (rtoi_14229 & rtoi_9322) | (rtoi_15074 & rtoi_8962) | (rtoi_15074 & rtoi_9319) | (rtoi_15074 & rtoi_9322)}\n    \t rtoi_14229 | rtoi_15074\n    MCOATA\n    \t {'sce': rtoi_8670 & rtoi_8777, 'eco': rtoi_14261 & rtoi_16542, 'ppu': rtoi_16542, 'yli': rtoi_8670 & rtoi_8777}\n    \t rtoi_8670 | rtoi_8777\n    METSOXR1\n    \t {'eco': (b3551 & rtoi_15339) | (b3551 & rtoi_16019) | (rtoi_15339 & rtoi_15902) | (rtoi_15902 & rtoi_16019), 'yli': rtoi_15469}\n    \t rtoi_15469\n    METTRS\n    \t {'sce': rtoi_13140, 'ppu': rtoi_13140, 'cre': rtoi_13140 | rtoi_15518}\n    \t rtoi_13140\n    MI145P6Kn\n    \t {'sce': rtoi_13260, 'cre': rtoi_9763}\n    \t rtoi_13260\n    MTAP\n    \t {'sce': rtoi_8372, 'cre': rtoi_14521, 'yli': rtoi_8372}\n    \t rtoi_8372\n    MTHFR2\n    \t {'eco': rtoi_9244, 'yli': rtoi_15483 | rtoi_9244}\n    \t rtoi_15483 | rtoi_9244\n    MTRI\n    \t {'cre': rtoi_13385 | rtoi_15595, 'yli': rtoi_13385}\n    \t rtoi_13385\n    NDP1\n    \t {'sce': rtoi_8970, 'cre': rtoi_9805, 'yli': rtoi_8970}\n    \t rtoi_8970\n    NDP3\n    \t {'sce': rtoi_8970, 'cre': rtoi_9805, 'yli': rtoi_8970}\n    \t rtoi_8970\n    NDP7\n    \t {'sce': rtoi_8970, 'cre': rtoi_9805, 'yli': rtoi_8970}\n    \t rtoi_8970\n    NTD2\n    \t {'sce': rtoi_9995, 'eco': rtoi_13044 | rtoi_16648, 'ppu': rtoi_16648}\n    \t rtoi_9995\n    NTD4\n    \t {'sce': rtoi_9995, 'eco': rtoi_13044 | rtoi_16648, 'ppu': rtoi_16648}\n    \t rtoi_9995\n    NTP1\n    \t {'cre': rtoi_9805, 'yli': rtoi_10674 & rtoi_11025 & rtoi_11052 & rtoi_11064 & rtoi_11117 & rtoi_11403 & rtoi_11958 & rtoi_11967 & rtoi_13424 & rtoi_13759 & rtoi_14786 & rtoi_14912 & rtoi_14971 & rtoi_15309 & rtoi_15351 & rtoi_15589 & rtoi_15963 & rtoi_16359 & rtoi_16397 & rtoi_9080 & rtoi_9210 & rtoi_9622 & rtoi_9748 & rtoi_9940}\n    \t (YALI0B21527g & rtoi_10674 & rtoi_11025 & rtoi_11052 & rtoi_11064 & rtoi_11117 & rtoi_11403 & rtoi_11958 & rtoi_11967 & rtoi_13424 & rtoi_13759 & rtoi_14786 & rtoi_14912 & rtoi_14971 & rtoi_15309 & rtoi_15351 & rtoi_15589 & rtoi_15963 & rtoi_16359 & rtoi_16397 & rtoi_9210 & rtoi_9622 & rtoi_9940) | (YALI0B21527g & rtoi_10674 & rtoi_11052 & rtoi_11064 & rtoi_11117 & rtoi_11403 & rtoi_11958 & rtoi_11967 & rtoi_13424 & rtoi_13759 & rtoi_14786 & rtoi_14912 & rtoi_14971 & rtoi_15309 & rtoi_15351 & rtoi_15589 & rtoi_15963 & rtoi_16359 & rtoi_16397 & rtoi_9210 & rtoi_9622 & rtoi_9748 & rtoi_9940)\n    NTP10\n    \t {'cre': rtoi_9805, 'yli': rtoi_8970}\n    \t rtoi_8970\n    NTP3\n    \t {'eco': rtoi_10886 | rtoi_16025, 'cre': rtoi_9805, 'yli': rtoi_8970}\n    \t rtoi_8970\n    NTP5\n    \t {'cre': rtoi_9805, 'yli': rtoi_8970}\n    \t rtoi_8970\n    NTP7\n    \t {'cre': rtoi_9805, 'yli': rtoi_8970}\n    \t rtoi_8970\n    NTP9\n    \t {'cre': rtoi_9805, 'yli': rtoi_8970}\n    \t rtoi_8970\n    ORNt2r\n    \t {'sce': rtoi_14229 | rtoi_15074 | rtoi_8962 | rtoi_9319 | rtoi_9322, 'yli': (rtoi_14229 & rtoi_8962) | (rtoi_14229 & rtoi_9319) | (rtoi_14229 & rtoi_9322) | (rtoi_15074 & rtoi_8962) | (rtoi_15074 & rtoi_9319) | (rtoi_15074 & rtoi_9322)}\n    \t rtoi_14229 | rtoi_15074\n    PDE1\n    \t {'sce': rtoi_11787 | rtoi_13690, 'cre': rtoi_11787, 'yli': rtoi_11787 | rtoi_13690}\n    \t rtoi_11787 | rtoi_13690\n    PDH\n    \t {'eco': b0114 & b0115 & rtoi_10040, 'ppu': PP_0338 & PP_0339 & rtoi_10040, 'yli': rtoi_13948}\n    \t rtoi_13948\n    PDX5POi\n    \t {'sce': rtoi_10680, 'eco': rtoi_10680, 'ppu': rtoi_10680, 'cre': rtoi_8901, 'yli': rtoi_10680}\n    \t rtoi_10680\n    PDXPP\n    \t {'ppu': rtoi_14545, 'cre': rtoi_13044}\n    \t rtoi_13044\n    PGL\n    \t {'sce': rtoi_14499, 'eco': rtoi_14132, 'ppu': rtoi_14499, 'yli': rtoi_14499}\n    \t rtoi_14499\n    PHETRS\n    \t {'sce': rtoi_12470 & rtoi_13249, 'ppu': PP_2470 & rtoi_12470}\n    \t rtoi_12470 & rtoi_13249\n    PIt2m\n    \t {'sce': rtoi_15874, 'cre': rtoi_11409 | rtoi_11410 | rtoi_11686}\n    \t rtoi_15874 | rtoi_8889\n    PPA\n    \t {'sce': rtoi_15879, 'eco': rtoi_16648, 'yli': rtoi_15879}\n    \t rtoi_15879\n    PPM\n    \t {'sce': rtoi_9959, 'cre': rtoi_13711 | rtoi_9959}\n    \t rtoi_9959\n    PPNCL2\n    \t {'eco': rtoi_8536, 'cre': rtoi_8878, 'yli': rtoi_8878}\n    \t rtoi_8878\n    PRMICI\n    \t {'sce': rtoi_11610, 'cre': rtoi_11610 | rtoi_9084, 'yli': rtoi_11610}\n    \t rtoi_11610\n    PUNP1\n    \t {'sce': rtoi_16276, 'eco': rtoi_14521, 'yli': rtoi_16276}\n    \t rtoi_16276\n    PUNP2\n    \t {'sce': rtoi_16276, 'eco': rtoi_14521, 'yli': rtoi_16276}\n    \t rtoi_16276\n    PUNP3\n    \t {'sce': rtoi_16276, 'eco': rtoi_14521 | rtoi_16276, 'yli': rtoi_16276}\n    \t rtoi_16276\n    PUNP4\n    \t {'sce': rtoi_16276, 'eco': rtoi_14521 | rtoi_16276, 'yli': rtoi_16276}\n    \t rtoi_16276\n    PUNP5\n    \t {'sce': rtoi_16276, 'eco': rtoi_14521 | rtoi_16276, 'yli': rtoi_16276}\n    \t rtoi_16276\n    PUNP6\n    \t {'sce': rtoi_16276, 'eco': rtoi_14521 | rtoi_16276, 'yli': rtoi_16276}\n    \t rtoi_16276\n    PYAM5PO\n    \t {'sce': rtoi_10680, 'eco': rtoi_10680, 'cre': rtoi_8901, 'yli': rtoi_10680}\n    \t rtoi_10680\n    PYDXNO\n    \t {'sce': rtoi_10680, 'cre': rtoi_8901, 'yli': rtoi_10680}\n    \t rtoi_10680\n    PYDXO_1\n    \t {'cre': rtoi_8901, 'yli': rtoi_10680}\n    \t rtoi_10680\n    PYDXPP\n    \t {'eco': rtoi_13044, 'ppu': rtoi_14545, 'cre': rtoi_13044}\n    \t rtoi_13044\n    RNTR1\n    \t {'sce': rtoi_15339 | rtoi_16019, 'cre': (CRv4_Au5_s27_g10030_t1 & CRv4_Au5_s9_g15314_t1) | (CRv4_Au5_s27_g10030_t1 & rtoi_15339) | (CRv4_Au5_s27_g10030_t1 & rtoi_16019)}\n    \t rtoi_15339\n    RNTR2\n    \t {'sce': rtoi_15339 | rtoi_16019, 'cre': (CRv4_Au5_s27_g10030_t1 & CRv4_Au5_s9_g15314_t1) | (CRv4_Au5_s27_g10030_t1 & rtoi_15339) | (CRv4_Au5_s27_g10030_t1 & rtoi_16019)}\n    \t rtoi_15339\n    RNTR3\n    \t {'sce': rtoi_15339 | rtoi_16019, 'cre': (CRv4_Au5_s27_g10030_t1 & CRv4_Au5_s9_g15314_t1) | (CRv4_Au5_s27_g10030_t1 & rtoi_15339) | (CRv4_Au5_s27_g10030_t1 & rtoi_16019)}\n    \t rtoi_15339\n    RNTR4\n    \t {'sce': rtoi_15339 | rtoi_16019, 'cre': (CRv4_Au5_s27_g10030_t1 & CRv4_Au5_s9_g15314_t1) | (CRv4_Au5_s27_g10030_t1 & rtoi_15339) | (CRv4_Au5_s27_g10030_t1 & rtoi_16019)}\n    \t rtoi_15339\n    SERTRS\n    \t {'sce': rtoi_10246 | rtoi_14225, 'ppu': rtoi_10246, 'cre': rtoi_10246 | rtoi_14225}\n    \t rtoi_10246 | rtoi_14225\n    SHCHD2\n    \t {'eco': rtoi_11050, 'ppu': rtoi_11050, 'yli': rtoi_13569}\n    \t rtoi_13569\n    SHCHF\n    \t {'sce': rtoi_13569, 'eco': rtoi_11050, 'ppu': rtoi_11050, 'yli': rtoi_13569}\n    \t rtoi_13569\n    SHKK\n    \t {'sce': rtoi_14252, 'eco': rtoi_13706, 'yli': rtoi_14252}\n    \t rtoi_14252\n    SHSL1\n    \t {'eco': rtoi_9499, 'ppu': rtoi_9499, 'yli': rtoi_11463 | rtoi_16725 | rtoi_16742}\n    \t rtoi_11463 | rtoi_16725 | rtoi_16742\n    SHSL2r\n    \t {'ppu': rtoi_9499, 'yli': rtoi_11463 | rtoi_16725 | rtoi_16742}\n    \t rtoi_11463 | rtoi_16725 | rtoi_16742\n    TAUDO\n    \t {'sce': rtoi_10226 | rtoi_8618, 'eco': rtoi_13175 | rtoi_14698, 'ppu': rtoi_13175 | rtoi_14698}\n    \t rtoi_10226 | rtoi_8618\n    THFAT\n    \t {'eco': rtoi_9667, 'yli': rtoi_12898}\n    \t rtoi_12898\n    THIORDXi\n    \t {'sce': (rtoi_12715 & rtoi_15339) | (rtoi_12715 & rtoi_16019), 'eco': rtoi_8579 | (rtoi_15037 & rtoi_15339) | (rtoi_15037 & rtoi_16019)}\n    \t YDR453C & rtoi_15339\n    THRA\n    \t {'sce': rtoi_16182 | rtoi_9222, 'eco': rtoi_16182 | rtoi_9222 | rtoi_9667, 'ppu': rtoi_16182 | rtoi_9222, 'yli': rtoi_16182 | rtoi_9222}\n    \t rtoi_16182 | rtoi_9222\n    THRA2\n    \t {'sce': rtoi_16182 | rtoi_9222, 'eco': rtoi_16182 | rtoi_9222 | rtoi_9667, 'ppu': rtoi_16182 | rtoi_9222, 'yli': rtoi_16182 | rtoi_9222}\n    \t rtoi_16182 | rtoi_9222\n    TRE6PS\n    \t {'sce': (YML100W & rtoi_11389 & rtoi_12034) | (YMR261C & rtoi_11389 & rtoi_12034), 'eco': rtoi_11389}\n    \t (YML100W & rtoi_11389 & rtoi_12034) | (YMR261C & rtoi_11389 & rtoi_12034)\n    TRPS1\n    \t {'sce': rtoi_9262, 'eco': b1260 & rtoi_9262, 'ppu': PP_0082 & rtoi_9262, 'yli': rtoi_9262}\n    \t rtoi_9262\n    TYRTAi\n    \t {'sce': rtoi_14908 | rtoi_15839 | rtoi_8936, 'cre': rtoi_13230 | rtoi_14281}\n    \t rtoi_12407 | rtoi_14908 | rtoi_15839 | rtoi_8936\n    TYRTRS\n    \t {'sce': rtoi_16641, 'ppu': rtoi_13137, 'cre': rtoi_13137 | rtoi_16641}\n    \t rtoi_16641\n    UNK3\n    \t {'ppu': rtoi_14281 | rtoi_8936, 'yli': rtoi_14908 | rtoi_15839}\n    \t rtoi_12407 | rtoi_14908 | rtoi_15839\n    URIK1\n    \t {'sce': rtoi_8633, 'eco': rtoi_8633, 'cre': rtoi_8633 | rtoi_9093, 'yli': rtoi_8633}\n    \t rtoi_8633\n    URIK2\n    \t {'sce': rtoi_8633, 'eco': rtoi_8633, 'cre': rtoi_8633 | rtoi_9093, 'yli': rtoi_8633}\n    \t rtoi_8633\n    URIK3\n    \t {'cre': rtoi_8633 | rtoi_9093, 'yli': rtoi_8633}\n    \t rtoi_8633\n    UTCY\n    \t {'cre': rtoi_8633 | rtoi_9093, 'yli': rtoi_8633}\n    \t rtoi_8633\n    UTUP\n    \t {'cre': rtoi_8633 | rtoi_9093, 'yli': rtoi_8633}\n    \t rtoi_8633\n    YUMPS\n    \t {'sce': rtoi_14436 | rtoi_16088 | rtoi_16423, 'eco': rtoi_16646}\n    \t rtoi_14436 | rtoi_16088 | rtoi_16423\n\n\n\n```python\nfor x in set(Reaction_rule.keys()).intersection(Reaction_rule_Jeff_unique):\n    if x not in Reaction_rule_final:\n        temp1 = sympy.Or(*[v for v in Reaction_rule[x].values()])\n        temp2 = Reaction_rule_Jeff_unique[x]\n        Reaction_rule_final[x] = sympy.Or(temp1,temp2)\n```\n\n\n```python\nprint('ACOATA', Reaction_rule_final['ACOATA'])\nprint('MCOATA', Reaction_rule_final['MCOATA'])\n```\n\n    ACOATA rtoi_8670 | rtoi_8777 | (b1091 & rtoi_14261) | (rtoi_8670 & rtoi_8777)\n    MCOATA rtoi_16542 | rtoi_8670 | rtoi_8777 | (rtoi_14261 & rtoi_16542) | (rtoi_8670 & rtoi_8777)\n\n\n\n```python\nReaction_rule_final['ACOATA'] = parse_expr('(b1091 & rtoi_14261) | (rtoi_8670 & rtoi_8777)')\nReaction_rule_final['MCOATA'] = parse_expr('rtoi_16542 | (rtoi_14261 & rtoi_16542) | (rtoi_8670 & rtoi_8777)')\n```\n\n\n```python\nfor x in set(Reaction_rule_unique.keys()).intersection(Reaction_rule_Jeff):\n    if x not in Reaction_rule_final:\n        print(x)\n        print('\\t',Reaction_rule_unique[x])\n        print('\\t',Reaction_rule_Jeff[x])\n```\n\n    GUAPRT\n    \t rtoi_16193\n    \t {'sce': rtoi_12445, 'yli': rtoi_16193}\n    FACOAL161\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t {'hsa': rtoi_12538 | rtoi_12555, 'mmu': rtoi_12538 | rtoi_12555, 'sce': rtoi_11167 | rtoi_15748}\n    PEAMNO\n    \t rtoi_10308\n    \t {'hsa': rtoi_13959, 'mmu': rtoi_13959, 'yli': rtoi_10308}\n    MCOATAm\n    \t YER061C & YHR067W & YKL055C & YOR221C & rtoi_11837 & rtoi_14261\n    \t {'hsa': rtoi_16542, 'mmu': rtoi_16542, 'sce': YER061C & YHR067W & YKL055C & YOR221C & rtoi_11837 & rtoi_14261}\n    ALDD19xr\n    \t rtoi_12042 | rtoi_13426\n    \t {'hsa': rtoi_12042 | rtoi_13426 | rtoi_16323, 'mmu': rtoi_12042 | rtoi_13426 | rtoi_16323, 'sce': rtoi_12042 | rtoi_13426, 'yli': rtoi_12042 | rtoi_13426}\n    ACACT1m\n    \t rtoi_8678 | rtoi_8885\n    \t {'hsa': rtoi_8678 | (HADHA & HADHB), 'mmu': rtoi_8678 | (Hadha & Hadhb), 'sce': rtoi_8678, 'yli': rtoi_8678}\n    ALDD22x\n    \t rtoi_12042 | rtoi_13426 | rtoi_16323\n    \t {'sce': rtoi_12042 | rtoi_13426, 'yli': rtoi_12042 | rtoi_13426 | rtoi_16323}\n    42A12BOOX\n    \t rtoi_10308\n    \t {'hsa': rtoi_13959, 'mmu': rtoi_13959, 'yli': rtoi_10308}\n    ECOAH12m\n    \t rtoi_11907\n    \t {'hsa': rtoi_14805 | (HADHA & HADHB), 'mmu': rtoi_14805 | (Hadha & Hadhb)}\n    PMANM\n    \t rtoi_9241\n    \t {'hsa': rtoi_13711 | rtoi_9241, 'mmu': rtoi_13711 | rtoi_9241, 'sce': rtoi_9241, 'yli': rtoi_9241}\n    DPCOAK\n    \t rtoi_11114\n    \t {'hsa': rtoi_14849, 'mmu': rtoi_14849, 'yli': rtoi_11114}\n    MDHm\n    \t rtoi_10614 | rtoi_11178\n    \t {'hsa': rtoi_11178, 'mmu': rtoi_11178, 'sce': rtoi_11178, 'yli': rtoi_10614 | rtoi_11178}\n    SPMDtex2\n    \t rtoi_15991 | rtoi_16258\n    \t {'sce': rtoi_13423, 'yli': rtoi_15991 | rtoi_16258}\n    34DHOXPEGOX\n    \t rtoi_14108 | rtoi_14109 | rtoi_15438\n    \t {'hsa': rtoi_11665 | rtoi_14108 | rtoi_14109 | (ADH1A & ADH1B) | (ADH1A & ADH1C) | (ADH1B & ADH1C), 'yli': rtoi_14108 | rtoi_14109 | rtoi_15438}\n    GARFT\n    \t rtoi_13595\n    \t {'hsa': rtoi_14259, 'mmu': rtoi_14259, 'sce': rtoi_13595, 'yli': rtoi_13595}\n    ALDD20x\n    \t rtoi_12042 | rtoi_13426 | rtoi_16323\n    \t {'hsa': rtoi_12042 | rtoi_13426 | rtoi_15814 | rtoi_16323, 'mmu': rtoi_12042 | rtoi_13426 | rtoi_15814 | rtoi_16323, 'yli': rtoi_12042 | rtoi_13426 | rtoi_16323}\n    FACOAL181\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t {'hsa': rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748, 'mmu': rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748, 'sce': rtoi_11167 | rtoi_15748}\n    ECOAH9m\n    \t rtoi_11907\n    \t {'hsa': rtoi_14805 | (HADHA & HADHB), 'mmu': rtoi_14805 | (Hadha & Hadhb)}\n    PFK26\n    \t rtoi_15195 | rtoi_15744\n    \t {'hsa': rtoi_15195, 'mmu': rtoi_15195, 'yli': rtoi_15195 | rtoi_15744}\n    NDPK10\n    \t rtoi_15679\n    \t {'hsa': rtoi_15679 | rtoi_8943, 'mmu': rtoi_15679 | rtoi_8943, 'yli': rtoi_15679}\n    PTRCtex2\n    \t rtoi_15991 | rtoi_16258\n    \t {'sce': rtoi_13423, 'yli': rtoi_15991 | rtoi_16258}\n    ACGSm\n    \t rtoi_16208 | rtoi_16267\n    \t {'hsa': rtoi_9377, 'mmu': rtoi_9377, 'sce': rtoi_16208 | rtoi_16267, 'yli': rtoi_16208 | rtoi_16267}\n    ACS\n    \t rtoi_14597\n    \t {'hsa': rtoi_14597 | rtoi_15276, 'mmu': rtoi_14597 | rtoi_15276, 'sce': rtoi_14597, 'yli': rtoi_14597}\n    FACOAL160\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t {'hsa': rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748, 'mmu': rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748, 'sce': rtoi_11167 | rtoi_15748, 'yli': rtoi_11167 | rtoi_15748}\n    PRPNCOAHYDm\n    \t rtoi_11907\n    \t {'hsa': rtoi_14805 | rtoi_16128 | (HADHA & HADHB), 'mmu': rtoi_14805 | rtoi_16128 | (Hadha & Hadhb)}\n    PDHm\n    \t rtoi_10040 & rtoi_13630 & rtoi_13722 & rtoi_13948 & rtoi_14126\n    \t {'hsa': PDHX & rtoi_10040 & rtoi_13630 & rtoi_13948 & rtoi_14126, 'mmu': Pdhx & rtoi_10040 & rtoi_13630 & rtoi_13948 & rtoi_14126, 'sce': rtoi_10040 & rtoi_13630 & rtoi_13722 & rtoi_13948 & rtoi_14126}\n    NH4t\n    \t rtoi_12926 | rtoi_13637\n    \t {'sce': rtoi_12926 | rtoi_13637, 'yli': rtoi_12926 & rtoi_13637}\n    MALT\n    \t rtoi_9135\n    \t {'hsa': rtoi_10170, 'mmu': rtoi_10170, 'sce': rtoi_9135}\n    GLUCYS\n    \t rtoi_12007 | rtoi_12022\n    \t {'hsa': (GCLM & rtoi_12007) | (GCLM & rtoi_12022), 'mmu': (Gclm & rtoi_12007) | (Gclm & rtoi_12022), 'sce': rtoi_12007 | rtoi_12022, 'yli': rtoi_12007 | rtoi_12022}\n    SUCOAS1m\n    \t rtoi_15967 & rtoi_16144\n    \t {'hsa': SUCLG2 & rtoi_16144, 'mmu': Suclg2 & rtoi_16144, 'yli': rtoi_15967 & rtoi_16144}\n    ALDD20xm\n    \t rtoi_12042 | rtoi_13426\n    \t {'hsa': rtoi_12042 | rtoi_13426 | rtoi_8569, 'mmu': rtoi_12042 | rtoi_13426 | rtoi_8569, 'sce': rtoi_12042 | rtoi_13426}\n    TRDRm\n    \t YCR083W & rtoi_9688\n    \t {'hsa': rtoi_15482, 'mmu': rtoi_15482, 'sce': rtoi_15339 & rtoi_9688}\n    AGPRim\n    \t rtoi_9377\n    \t {'hsa': rtoi_16273, 'mmu': rtoi_16273, 'sce': rtoi_9377, 'yli': rtoi_9377}\n    FACOAL180\n    \t rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748\n    \t {'hsa': rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748, 'mmu': rtoi_11167 | rtoi_12538 | rtoi_12555 | rtoi_15748, 'sce': rtoi_11167 | rtoi_15748, 'yli': rtoi_11167 | rtoi_15748}\n    METAT\n    \t rtoi_13771\n    \t {'hsa': rtoi_13771 | (rtoi_11793 & rtoi_13771), 'mmu': rtoi_13771 | (rtoi_11793 & rtoi_13771), 'sce': rtoi_13771, 'yli': rtoi_13771}\n\n\n\n```python\nfor x in set(Reaction_rule_unique.keys()).intersection(Reaction_rule_Jeff):\n    if x not in Reaction_rule_final:\n        temp1 = Reaction_rule_unique[x]\n        temp2 = sympy.Or(*[v for v in Reaction_rule_Jeff[x].values()])\n        Reaction_rule_final[x] = sympy.Or(temp1,temp2)\n```\n\n\n```python\nfor x in sorted(set(Reaction_rule.keys()).intersection(Reaction_rule_Jeff)):\n    if x not in Reaction_rule_final:\n        print(x)\n        print('\\t',Reaction_rule[x])\n        print('\\t',Reaction_rule_Jeff[x])\n```\n\n    3DH5HPBMTm\n    \t {'sce': YLR201C & rtoi_10213 & rtoi_10633 & rtoi_11465 & rtoi_16037 & rtoi_16197 & rtoi_9681, 'yli': rtoi_11465}\n    \t {'sce': YLR201C & rtoi_10213 & rtoi_10633 & rtoi_11465 & rtoi_16037 & rtoi_16197 & rtoi_9681, 'yli': rtoi_11465}\n    AASAD1\n    \t {'sce': rtoi_10220 & rtoi_9495, 'yli': rtoi_9495}\n    \t {'sce': YGL154C & rtoi_9495, 'yli': rtoi_9495}\n    AASAD2\n    \t {'sce': rtoi_10220 & rtoi_9495, 'yli': rtoi_9495}\n    \t {'sce': YGL154C & rtoi_9495, 'yli': rtoi_9495}\n    ADEt2\n    \t {'sce': rtoi_14558 | rtoi_15012, 'yli': rtoi_14558 & rtoi_15012}\n    \t {'sce': rtoi_14461 | rtoi_14558 | rtoi_15012, 'yli': (YALI0D07392g & rtoi_14461) | (YALI0D07392g & rtoi_14558) | (YALI0D07392g & rtoi_15012)}\n    ADK1\n    \t {'sce': rtoi_15496, 'eco': rtoi_15496, 'ppu': rtoi_15496, 'cre': rtoi_12300 | rtoi_15496, 'yli': rtoi_15496}\n    \t {'hsa': rtoi_13190, 'mmu': rtoi_13190, 'sce': rtoi_15496, 'yli': rtoi_15496}\n    ADK1m\n    \t {'sce': rtoi_15129, 'cre': rtoi_12300}\n    \t {'hsa': rtoi_15129 | rtoi_15496, 'sce': rtoi_15129}\n    ALAt2r\n    \t {'sce': rtoi_14229 | rtoi_15074 | rtoi_8962 | rtoi_9319 | rtoi_9322, 'yli': (YALI0B09537g & rtoi_14229 & rtoi_8962) | (YALI0B09537g & rtoi_14229 & rtoi_9319) | (YALI0B09537g & rtoi_14229 & rtoi_9322) | (YALI0B09537g & rtoi_15074 & rtoi_8962) | (YALI0B09537g & rtoi_15074 & rtoi_9319) | (YALI0B09537g & rtoi_15074 & rtoi_9322)}\n    \t {'hsa': rtoi_12743, 'mmu': rtoi_12743, 'sce': rtoi_14229 | rtoi_15074 | rtoi_8962 | rtoi_9319 | rtoi_9322 | rtoi_9962, 'yli': (YALI0B09537g & rtoi_14229 & rtoi_8962) | (YALI0B09537g & rtoi_14229 & rtoi_9319) | (YALI0B09537g & rtoi_14229 & rtoi_9322) | (YALI0B09537g & rtoi_14229 & rtoi_9962) | (YALI0B09537g & rtoi_15074 & rtoi_8962) | (YALI0B09537g & rtoi_15074 & rtoi_9319) | (YALI0B09537g & rtoi_15074 & rtoi_9322) | (YALI0B09537g & rtoi_15074 & rtoi_9962)}\n    ALCD2x\n    \t {'eco': rtoi_11665 | rtoi_15438, 'yli': rtoi_14108 | rtoi_14109 | rtoi_15438}\n    \t {'hsa': rtoi_11665 | rtoi_13657 | rtoi_14108 | rtoi_14109, 'yli': rtoi_14108 | rtoi_14109 | rtoi_15438}\n    ALDD2xm\n    \t {'sce': rtoi_12042 | rtoi_13426, 'cre': rtoi_12042 | rtoi_13426, 'yli': rtoi_12042 | rtoi_13426 | rtoi_16323}\n    \t {'hsa': rtoi_12042 | rtoi_13426, 'mmu': rtoi_12042 | rtoi_13426, 'sce': rtoi_12042 | rtoi_13426, 'yli': rtoi_12042 | rtoi_13426 | rtoi_16323}\n    ALDD2y\n    \t {'sce': rtoi_12042 | rtoi_13426, 'eco': rtoi_11650 | rtoi_14700 | rtoi_15575 | rtoi_8666}\n    \t {'hsa': rtoi_12042 | rtoi_13426 | rtoi_16323, 'mmu': rtoi_12042 | rtoi_13426 | rtoi_16323, 'sce': rtoi_12042 | rtoi_13426}\n    AMID2\n    \t {'sce': rtoi_10276 | rtoi_10277, 'yli': rtoi_12161 | rtoi_13791}\n    \t {'sce': rtoi_10276 | rtoi_10277 | rtoi_12540 | rtoi_12553 | rtoi_12842, 'yli': rtoi_12161 | rtoi_13791}\n    AMID3\n    \t {'sce': rtoi_10276 | rtoi_10277, 'yli': rtoi_12161 | rtoi_13791}\n    \t {'sce': rtoi_10276 | rtoi_10277 | rtoi_12540 | rtoi_12553 | rtoi_12842, 'yli': rtoi_12161 | rtoi_13791}\n    ANS\n    \t {'sce': rtoi_15109 & rtoi_16564, 'eco': rtoi_15109 & rtoi_9900, 'ppu': rtoi_15109 & rtoi_16564, 'yli': rtoi_15109 | rtoi_16564}\n    \t {'sce': rtoi_15109 & rtoi_16564, 'yli': rtoi_15109 | rtoi_16564}\n    ASNS1\n    \t {'sce': rtoi_14762 | rtoi_15137, 'eco': rtoi_15137, 'ppu': rtoi_15137, 'cre': rtoi_14762 | rtoi_15137, 'yli': rtoi_15137}\n    \t {'hsa': rtoi_15137, 'mmu': rtoi_15137, 'sce': rtoi_14762 | rtoi_15137, 'yli': rtoi_15137}\n    ASNt2r\n    \t {'sce': rtoi_14229 | rtoi_15074 | rtoi_8962 | rtoi_9319 | rtoi_9322, 'yli': (rtoi_14229 & rtoi_8962) | (rtoi_14229 & rtoi_9319) | (rtoi_14229 & rtoi_9322) | (rtoi_15074 & rtoi_8962) | (rtoi_15074 & rtoi_9319) | (rtoi_15074 & rtoi_9322)}\n    \t {'sce': rtoi_14229 | rtoi_15074 | rtoi_8962 | rtoi_9319 | rtoi_9322 | rtoi_9962, 'yli': (rtoi_14229 & rtoi_8962) | (rtoi_14229 & rtoi_9319) | (rtoi_14229 & rtoi_9322) | (rtoi_14229 & rtoi_9962) | (rtoi_15074 & rtoi_8962) | (rtoi_15074 & rtoi_9319) | (rtoi_15074 & rtoi_9322) | (rtoi_15074 & rtoi_9962)}\n    ASPTA\n    \t {'sce': rtoi_8936, 'eco': rtoi_14281 | rtoi_8936, 'cre': rtoi_14281, 'yli': rtoi_14281 | rtoi_8936}\n    \t {'hsa': rtoi_8936, 'mmu': rtoi_8936, 'sce': rtoi_8936, 'yli': rtoi_14281 | rtoi_8936}\n    ASPt2r\n    \t {'sce': rtoi_14229 | rtoi_15074 | rtoi_8962 | rtoi_9319 | rtoi_9322, 'yli': (YALI0E20713g & rtoi_14229 & rtoi_8962) | (YALI0E20713g & rtoi_14229 & rtoi_9319) | (YALI0E20713g & rtoi_14229 & rtoi_9322) | (YALI0E20713g & rtoi_15074 & rtoi_8962) | (YALI0E20713g & rtoi_15074 & rtoi_9319) | (YALI0E20713g & rtoi_15074 & rtoi_9322)}\n    \t {'sce': rtoi_14229 | rtoi_15074 | rtoi_8962 | rtoi_9319 | rtoi_9322 | rtoi_9962, 'yli': (YALI0E20713g & rtoi_14229 & rtoi_8962) | (YALI0E20713g & rtoi_14229 & rtoi_9319) | (YALI0E20713g & rtoi_14229 & rtoi_9322) | (YALI0E20713g & rtoi_14229 & rtoi_9962) | (YALI0E20713g & rtoi_15074 & rtoi_8962) | (YALI0E20713g & rtoi_15074 & rtoi_9319) | (YALI0E20713g & rtoi_15074 & rtoi_9322) | (YALI0E20713g & rtoi_15074 & rtoi_9962)}\n    ATPS\n    \t {'sce': (YCR024C_A & YEL017C_A & rtoi_13617) | (YCR024C_A & YEL017C_A & rtoi_15584), 'cre': rtoi_12428 | rtoi_13617 | rtoi_15156 | rtoi_15584, 'yli': rtoi_13617 | rtoi_15584}\n    \t {'sce': (YCR024C_A & YEL017C_A & rtoi_13617) | (YCR024C_A & YEL017C_A & rtoi_15584), 'yli': rtoi_13617 | rtoi_15584}\n    CBPS\n    \t {'sce': rtoi_12302 | rtoi_16681 | (rtoi_12302 & rtoi_13297) | (rtoi_13297 & rtoi_16681), 'eco': (rtoi_12302 & rtoi_13297) | (rtoi_13297 & rtoi_16681), 'ppu': (rtoi_12302 & rtoi_13297) | (rtoi_13297 & rtoi_16681), 'cre': (rtoi_12302 & rtoi_13297) | (rtoi_13297 & rtoi_16681), 'yli': rtoi_12302 | rtoi_16681 | (rtoi_12302 & rtoi_13297) | (rtoi_13297 & rtoi_16681)}\n    \t {'hsa': rtoi_12302 | rtoi_16681, 'mmu': rtoi_12302 | rtoi_16681, 'sce': rtoi_12302 | rtoi_16681 | (rtoi_12302 & rtoi_13297) | (rtoi_13297 & rtoi_16681), 'yli': rtoi_12302 | rtoi_16681 | (rtoi_12302 & rtoi_13297) | (rtoi_13297 & rtoi_16681)}\n    CHORM\n    \t {'sce': rtoi_9704, 'eco': rtoi_14195 | rtoi_16225, 'ppu': rtoi_14195, 'yli': rtoi_14195 | rtoi_9704}\n    \t {'sce': rtoi_9704, 'yli': rtoi_14195 | rtoi_9704}\n    CSNATr\n    \t {'sce': rtoi_13580, 'yli': rtoi_13580 | rtoi_14245}\n    \t {'sce': rtoi_13580, 'yli': rtoi_13580 | rtoi_14245}\n    CSNt2\n    \t {'sce': rtoi_14558 | rtoi_15012, 'yli': rtoi_14558 & rtoi_15012}\n    \t {'sce': rtoi_14461 | rtoi_14558 | rtoi_15012, 'yli': (YALI0D07392g & rtoi_14461) | (YALI0D07392g & rtoi_14558) | (YALI0D07392g & rtoi_15012)}\n    CYSS\n    \t {'sce': rtoi_12031 | rtoi_13106, 'eco': rtoi_12031 | rtoi_13106 | rtoi_15712, 'ppu': rtoi_12031 | rtoi_13106 | rtoi_15712, 'yli': rtoi_12031 | rtoi_13106}\n    \t {'sce': rtoi_13106, 'yli': rtoi_12031 | rtoi_13106}\n    CYSTA\n    \t {'eco': rtoi_14281, 'yli': rtoi_14281 | rtoi_8936}\n    \t {'hsa': rtoi_8936, 'mmu': rtoi_8936, 'yli': rtoi_14281 | rtoi_8936}\n    DDPA\n    \t {'sce': rtoi_10602 | rtoi_12155, 'eco': rtoi_10602 | rtoi_12155, 'ppu': rtoi_10602 | rtoi_12155, 'yli': rtoi_10602 | rtoi_12155 | rtoi_15534}\n    \t {'sce': rtoi_10602 | rtoi_12155, 'yli': rtoi_10602 | rtoi_12155 | rtoi_15534}\n    DHORTS\n    \t {'sce': rtoi_12291 | rtoi_12302 | rtoi_16681, 'eco': rtoi_12291, 'ppu': rtoi_12291, 'yli': rtoi_12291}\n    \t {'hsa': rtoi_12302 | rtoi_16681, 'mmu': rtoi_12302 | rtoi_16681, 'sce': rtoi_12291 | rtoi_12302 | rtoi_16681, 'yli': rtoi_12291}\n    DMATT\n    \t {'sce': rtoi_12944, 'yli': rtoi_12944 | rtoi_16503}\n    \t {'hsa': rtoi_16503, 'mmu': rtoi_16503, 'sce': rtoi_12944, 'yli': rtoi_12944 | rtoi_16503}\n    DPRm\n    \t {'sce': rtoi_9176, 'cre': rtoi_14277, 'yli': rtoi_14277}\n    \t {'sce': rtoi_9176, 'yli': rtoi_14277}\n    ECOAH1m\n    \t {'cre': rtoi_11907, 'yli': rtoi_14805}\n    \t {'hsa': rtoi_14805 | rtoi_16128 | (HADHA & HADHB), 'mmu': rtoi_14805 | rtoi_16128 | (Hadha & Hadhb), 'yli': rtoi_14805}\n    FAS140COA\n    \t {'sce': (rtoi_12826 & rtoi_8639 & rtoi_8670 & rtoi_8777) | (rtoi_14471 & rtoi_8639 & rtoi_8670 & rtoi_8777), 'yli': rtoi_10677 & rtoi_16241 & rtoi_16695}\n    \t {'sce': (rtoi_12826 & rtoi_8639 & rtoi_8670) | (rtoi_12826 & rtoi_8639 & rtoi_8777), 'yli': rtoi_10677 & rtoi_16241 & rtoi_16695}\n    FAS160COA\n    \t {'sce': (rtoi_12826 & rtoi_8639 & rtoi_8670 & rtoi_8777) | (rtoi_14471 & rtoi_8639 & rtoi_8670 & rtoi_8777), 'yli': rtoi_10677 & rtoi_16241 & rtoi_16695}\n    \t {'sce': (rtoi_12826 & rtoi_8639 & rtoi_8670) | (rtoi_12826 & rtoi_8639 & rtoi_8777), 'yli': rtoi_10677 & rtoi_16241 & rtoi_16695}\n    FAS180\n    \t {'sce': (rtoi_12826 & rtoi_8639 & rtoi_8670 & rtoi_8777) | (rtoi_14471 & rtoi_8639 & rtoi_8670 & rtoi_8777), 'yli': rtoi_10677 & rtoi_16241 & rtoi_16695}\n    \t {'sce': (rtoi_12826 & rtoi_8639 & rtoi_8670) | (rtoi_12826 & rtoi_8639 & rtoi_8777), 'yli': rtoi_10677 & rtoi_16241 & rtoi_16695}\n    FAS180COA\n    \t {'sce': (rtoi_12826 & rtoi_8639 & rtoi_8670 & rtoi_8777) | (rtoi_14471 & rtoi_8639 & rtoi_8670 & rtoi_8777), 'yli': rtoi_10677 & rtoi_16241 & rtoi_16695}\n    \t {'sce': (rtoi_12826 & rtoi_8639 & rtoi_8670) | (rtoi_12826 & rtoi_8639 & rtoi_8777), 'yli': rtoi_10677 & rtoi_16241 & rtoi_16695}\n    FAS240_L\n    \t {'sce': rtoi_16241 & rtoi_16655, 'yli': rtoi_10677 & rtoi_16241 & rtoi_16695}\n    \t {'sce': rtoi_16241 & rtoi_16655, 'yli': rtoi_10677 & rtoi_16241 & rtoi_16695}\n    FAS80COA_L\n    \t {'sce': (rtoi_12826 & rtoi_8639 & rtoi_8670 & rtoi_8777) | (rtoi_14471 & rtoi_8639 & rtoi_8670 & rtoi_8777), 'yli': rtoi_10677 & rtoi_16241 & rtoi_16695}\n    \t {'sce': (rtoi_12826 & rtoi_8639 & rtoi_8670) | (rtoi_12826 & rtoi_8639 & rtoi_8777), 'yli': rtoi_10677 & rtoi_16241 & rtoi_16695}\n    FAS80_L\n    \t {'sce': (rtoi_12826 & rtoi_8639 & rtoi_8670 & rtoi_8777) | (rtoi_14471 & rtoi_8639 & rtoi_8670 & rtoi_8777), 'yli': rtoi_10677 & rtoi_16241 & rtoi_16695}\n    \t {'sce': (rtoi_12826 & rtoi_8639 & rtoi_8670) | (rtoi_12826 & rtoi_8639 & rtoi_8777), 'yli': rtoi_10677 & rtoi_16241 & rtoi_16695}\n    FBP26\n    \t {'sce': rtoi_15195, 'yli': rtoi_15195 | rtoi_15744}\n    \t {'hsa': rtoi_15195 | rtoi_15423, 'mmu': rtoi_15195 | rtoi_15423, 'sce': rtoi_15195, 'yli': rtoi_15195 | rtoi_15744}\n    FRDcm\n    \t {'sce': rtoi_11420, 'yli': rtoi_16281}\n    \t {'sce': rtoi_11420, 'yli': rtoi_16281}\n    GALt2\n    \t {'sce': rtoi_10704 | rtoi_11893, 'yli': rtoi_10704 & rtoi_11893}\n    \t {'sce': rtoi_10704 | rtoi_11075 | rtoi_11893, 'yli': (rtoi_10704 & rtoi_11075) | (rtoi_10704 & rtoi_11893)}\n    GCCam\n    \t {'sce': rtoi_10040 & rtoi_10205 & rtoi_12898 & rtoi_15184, 'yli': rtoi_10205}\n    \t {'hsa': rtoi_10040 & rtoi_10205 & rtoi_12898 & rtoi_15184, 'mmu': rtoi_10040 & rtoi_10205 & rtoi_12898 & rtoi_15184, 'sce': rtoi_10040 & rtoi_10205 & rtoi_12898 & rtoi_15184, 'yli': rtoi_10205}\n    GCCbim\n    \t {'sce': rtoi_10040 & rtoi_10205 & rtoi_12898 & rtoi_15184, 'yli': rtoi_12898}\n    \t {'hsa': rtoi_10040 & rtoi_10205 & rtoi_12898 & rtoi_15184, 'mmu': rtoi_10040 & rtoi_10205 & rtoi_12898 & rtoi_15184, 'sce': rtoi_10040 & rtoi_10205 & rtoi_12898 & rtoi_15184, 'yli': rtoi_12898}\n    GCCcm\n    \t {'sce': rtoi_10040 & rtoi_10205 & rtoi_12898 & rtoi_15184, 'cre': rtoi_10040, 'yli': rtoi_10040}\n    \t {'hsa': rtoi_10040 & rtoi_10205 & rtoi_12898 & rtoi_15184, 'mmu': rtoi_10040 & rtoi_10205 & rtoi_12898 & rtoi_15184, 'sce': rtoi_10040 & rtoi_10205 & rtoi_12898 & rtoi_15184, 'yli': rtoi_10040}\n    GLCt1\n    \t {'sce': rtoi_10704 | rtoi_11893, 'yli': rtoi_11893}\n    \t {'hsa': rtoi_10452 | rtoi_15762 | rtoi_9102 | rtoi_9841, 'sce': rtoi_10704 | rtoi_11075 | rtoi_11893, 'yli': rtoi_11075 | rtoi_11893}\n    GLNS\n    \t {'sce': rtoi_11844, 'cre': rtoi_11844 | rtoi_8959, 'yli': rtoi_11844 | rtoi_8959}\n    \t {'hsa': rtoi_11844 | rtoi_8959, 'mmu': rtoi_11844 | rtoi_8959, 'sce': rtoi_11844, 'yli': rtoi_11844 | rtoi_8959}\n    GLNt2r\n    \t {'sce': rtoi_14229 | rtoi_15074 | rtoi_8962 | rtoi_9319 | rtoi_9322, 'yli': (rtoi_14229 & rtoi_8962) | (rtoi_14229 & rtoi_9319) | (rtoi_14229 & rtoi_9322) | (rtoi_15074 & rtoi_8962) | (rtoi_15074 & rtoi_9319) | (rtoi_15074 & rtoi_9322)}\n    \t {'sce': rtoi_14229 | rtoi_15074 | rtoi_8962 | rtoi_9319 | rtoi_9322 | rtoi_9962, 'yli': (rtoi_14229 & rtoi_8962) | (rtoi_14229 & rtoi_9319) | (rtoi_14229 & rtoi_9322) | (rtoi_14229 & rtoi_9962) | (rtoi_15074 & rtoi_8962) | (rtoi_15074 & rtoi_9319) | (rtoi_15074 & rtoi_9322) | (rtoi_15074 & rtoi_9962)}\n    GLUt2r\n    \t {'sce': rtoi_10704 | rtoi_14229 | rtoi_15074 | rtoi_8962 | rtoi_9319 | rtoi_9322, 'yli': (YALI0E20713g & rtoi_10704 & rtoi_14229 & rtoi_8962) | (YALI0E20713g & rtoi_10704 & rtoi_14229 & rtoi_9319) | (YALI0E20713g & rtoi_10704 & rtoi_14229 & rtoi_9322) | (YALI0E20713g & rtoi_10704 & rtoi_15074 & rtoi_8962) | (YALI0E20713g & rtoi_10704 & rtoi_15074 & rtoi_9319) | (YALI0E20713g & rtoi_10704 & rtoi_15074 & rtoi_9322)}\n    \t {'sce': rtoi_10704 | rtoi_14229 | rtoi_15074 | rtoi_8962 | rtoi_9319 | rtoi_9322 | rtoi_9962, 'yli': (YALI0E20713g & rtoi_10704 & rtoi_14229 & rtoi_8962) | (YALI0E20713g & rtoi_10704 & rtoi_14229 & rtoi_9319) | (YALI0E20713g & rtoi_10704 & rtoi_14229 & rtoi_9322) | (YALI0E20713g & rtoi_10704 & rtoi_14229 & rtoi_9962) | (YALI0E20713g & rtoi_10704 & rtoi_15074 & rtoi_8962) | (YALI0E20713g & rtoi_10704 & rtoi_15074 & rtoi_9319) | (YALI0E20713g & rtoi_10704 & rtoi_15074 & rtoi_9322) | (YALI0E20713g & rtoi_10704 & rtoi_15074 & rtoi_9962)}\n    GLYCLm\n    \t {'sce': rtoi_10040 & rtoi_10205 & rtoi_12898 & rtoi_15184, 'cre': (CRv4_Au5_s12_g4121_t1 & rtoi_14894) | (rtoi_12898 & rtoi_14894), 'yli': rtoi_12898}\n    \t {'sce': rtoi_10040 & rtoi_10205 & rtoi_12898 & rtoi_15184, 'yli': rtoi_12898}\n    GLYt2r\n    \t {'sce': rtoi_14229 | rtoi_15074 | rtoi_8962 | rtoi_9319 | rtoi_9322, 'yli': (YALI0B09537g & rtoi_14229 & rtoi_8962) | (YALI0B09537g & rtoi_14229 & rtoi_9319) | (YALI0B09537g & rtoi_14229 & rtoi_9322) | (YALI0B09537g & rtoi_15074 & rtoi_8962) | (YALI0B09537g & rtoi_15074 & rtoi_9319) | (YALI0B09537g & rtoi_15074 & rtoi_9322)}\n    \t {'hsa': rtoi_12743, 'mmu': rtoi_12743, 'sce': rtoi_14229 | rtoi_15074 | rtoi_8962 | rtoi_9319 | rtoi_9322 | rtoi_9962, 'yli': (YALI0B09537g & rtoi_14229 & rtoi_8962) | (YALI0B09537g & rtoi_14229 & rtoi_9319) | (YALI0B09537g & rtoi_14229 & rtoi_9322) | (YALI0B09537g & rtoi_14229 & rtoi_9962) | (YALI0B09537g & rtoi_15074 & rtoi_8962) | (YALI0B09537g & rtoi_15074 & rtoi_9319) | (YALI0B09537g & rtoi_15074 & rtoi_9322) | (YALI0B09537g & rtoi_15074 & rtoi_9962)}\n    GRTT\n    \t {'sce': rtoi_12944, 'cre': rtoi_12944, 'yli': rtoi_12944 | rtoi_16503}\n    \t {'hsa': rtoi_16503, 'mmu': rtoi_16503, 'sce': rtoi_12944, 'yli': rtoi_12944 | rtoi_16503}\n    GTHOm\n    \t {'sce': rtoi_15482 & rtoi_9250, 'cre': rtoi_15482}\n    \t {'hsa': rtoi_15482, 'mmu': rtoi_15482, 'sce': rtoi_15482 & rtoi_9250}\n    GTHOr\n    \t {'sce': (rtoi_15038 & rtoi_15482) | (rtoi_15482 & rtoi_16549) | (rtoi_15482 & rtoi_8790), 'eco': rtoi_15482, 'ppu': rtoi_15482, 'cre': rtoi_15482}\n    \t {'hsa': rtoi_15482, 'mmu': rtoi_15482, 'sce': (rtoi_15038 & rtoi_15482) | (rtoi_15482 & rtoi_8790)}\n    GTHPi\n    \t {'sce': rtoi_15038 | rtoi_16549 | rtoi_8579, 'eco': rtoi_8579, 'ppu': rtoi_8579, 'cre': rtoi_8579, 'yli': rtoi_8579}\n    \t {'hsa': rtoi_12715 | rtoi_8579, 'mmu': rtoi_12715 | rtoi_8579, 'sce': rtoi_15038 | rtoi_8579, 'yli': rtoi_8579}\n    GTHPm\n    \t {'sce': rtoi_9250, 'yli': rtoi_8579}\n    \t {'hsa': rtoi_8579, 'mmu': rtoi_12715 | rtoi_8579, 'sce': rtoi_9250, 'yli': rtoi_8579}\n    GUAt2r\n    \t {'sce': rtoi_14558 | rtoi_15012, 'yli': rtoi_14558 & rtoi_15012}\n    \t {'sce': rtoi_14461 | rtoi_14558 | rtoi_15012, 'yli': (YALI0D07392g & rtoi_14461) | (YALI0D07392g & rtoi_14558) | (YALI0D07392g & rtoi_15012)}\n    HSERTA\n    \t {'sce': rtoi_12513, 'ppu': PP_5098 & rtoi_15248, 'yli': rtoi_12513 | rtoi_15248}\n    \t {'sce': rtoi_12513, 'yli': rtoi_12513 | rtoi_15248}\n    ICDHxm\n    \t {'sce': rtoi_11681 & rtoi_11682, 'yli': rtoi_11681 | rtoi_11682}\n    \t {'hsa': rtoi_11681 & rtoi_11682, 'mmu': rtoi_11681 & rtoi_11682, 'sce': rtoi_11681 & rtoi_11682, 'yli': rtoi_11681 | rtoi_11682}\n    ILETRS\n    \t {'sce': rtoi_13446, 'ppu': rtoi_15556, 'cre': rtoi_13446, 'yli': rtoi_13446 | rtoi_15556}\n    \t {'sce': rtoi_13446, 'yli': rtoi_13446 | rtoi_15556}\n    ILETRSm\n    \t {'sce': rtoi_15556, 'yli': rtoi_13446 | rtoi_15556}\n    \t {'sce': rtoi_15556, 'yli': rtoi_13446 | rtoi_15556}\n    MAN1PT\n    \t {'sce': rtoi_14956, 'cre': rtoi_14956, 'yli': rtoi_10964 | rtoi_14956}\n    \t {'sce': rtoi_14956, 'yli': rtoi_10964 | rtoi_14956}\n    METB1\n    \t {'sce': rtoi_11463, 'yli': rtoi_11463 | rtoi_16725 | rtoi_16742}\n    \t {'sce': rtoi_11463, 'yli': rtoi_11463 | rtoi_16725 | rtoi_16742}\n    METt2r\n    \t {'sce': rtoi_14229 | rtoi_15074, 'yli': (YALI0F25795g & rtoi_14229) | (YALI0F25795g & rtoi_15074)}\n    \t {'sce': rtoi_14229 | rtoi_15074, 'yli': (YALI0F25795g & rtoi_14229) | (YALI0F25795g & rtoi_15074)}\n    MTHFR3\n    \t {'sce': rtoi_15483 | rtoi_9244, 'ppu': rtoi_9244, 'yli': rtoi_15483 | rtoi_9244}\n    \t {'hsa': rtoi_9244, 'mmu': rtoi_9244, 'sce': rtoi_15483 | rtoi_9244, 'yli': rtoi_15483 | rtoi_9244}\n    NDPK1\n    \t {'sce': rtoi_15679, 'eco': rtoi_15496 | rtoi_15679, 'ppu': rtoi_15679, 'cre': rtoi_15679 | rtoi_8943, 'yli': rtoi_15679}\n    \t {'hsa': rtoi_15679 | rtoi_8943, 'mmu': rtoi_15679 | rtoi_8943, 'sce': rtoi_15679, 'yli': rtoi_15679}\n    NDPK2\n    \t {'sce': rtoi_15679, 'eco': rtoi_15496 | rtoi_15679, 'ppu': rtoi_15679, 'cre': rtoi_15679 | rtoi_8943, 'yli': rtoi_15679}\n    \t {'hsa': rtoi_15679 | rtoi_8943, 'mmu': rtoi_15679 | rtoi_8943, 'sce': rtoi_15679, 'yli': rtoi_15679}\n    NDPK3\n    \t {'sce': rtoi_15679, 'eco': rtoi_15496 | rtoi_15679, 'ppu': rtoi_15679, 'cre': rtoi_15679 | rtoi_8943, 'yli': rtoi_15679}\n    \t {'hsa': rtoi_15679 | rtoi_8943, 'mmu': rtoi_15679 | rtoi_8943, 'sce': rtoi_15679, 'yli': rtoi_15679}\n    NDPK4\n    \t {'sce': rtoi_15679, 'eco': rtoi_15496 | rtoi_15679, 'ppu': rtoi_15679, 'cre': rtoi_15679 | rtoi_8943, 'yli': rtoi_15679}\n    \t {'hsa': rtoi_15679 | rtoi_8943, 'mmu': rtoi_15679 | rtoi_8943, 'sce': rtoi_15679, 'yli': rtoi_15679}\n    NDPK5\n    \t {'sce': rtoi_15679, 'eco': rtoi_15496 | rtoi_15679, 'ppu': rtoi_15679, 'cre': rtoi_15679 | rtoi_8943, 'yli': rtoi_15679}\n    \t {'hsa': rtoi_15679 | rtoi_8943, 'mmu': rtoi_15679 | rtoi_8943, 'sce': rtoi_15679, 'yli': rtoi_15679}\n    NDPK6\n    \t {'sce': rtoi_15679, 'eco': rtoi_15496 | rtoi_15679, 'ppu': rtoi_15679, 'cre': rtoi_15679 | rtoi_8943, 'yli': rtoi_15679}\n    \t {'hsa': rtoi_15679 | rtoi_8943, 'mmu': rtoi_15679 | rtoi_8943, 'sce': rtoi_15679, 'yli': rtoi_15679}\n    NDPK7\n    \t {'sce': rtoi_15679, 'eco': rtoi_15496 | rtoi_15679, 'ppu': rtoi_15679, 'cre': rtoi_15679 | rtoi_8943, 'yli': rtoi_15679}\n    \t {'hsa': rtoi_15679 | rtoi_8943, 'mmu': rtoi_15679 | rtoi_8943, 'sce': rtoi_15679, 'yli': rtoi_15679}\n    NDPK8\n    \t {'sce': rtoi_15679, 'eco': rtoi_15496 | rtoi_15679, 'ppu': rtoi_15679, 'cre': rtoi_15679 | rtoi_8943, 'yli': rtoi_15679}\n    \t {'hsa': rtoi_15679 | rtoi_8943, 'mmu': rtoi_15679 | rtoi_8943, 'sce': rtoi_15679, 'yli': rtoi_15679}\n    NDPK9\n    \t {'sce': rtoi_15679, 'cre': rtoi_15679 | rtoi_8943, 'yli': rtoi_15679}\n    \t {'hsa': rtoi_15679 | rtoi_8943, 'mmu': rtoi_15679 | rtoi_8943, 'sce': rtoi_15679, 'yli': rtoi_15679}\n    ORPT\n    \t {'sce': rtoi_10716, 'eco': rtoi_10716, 'ppu': rtoi_10716, 'cre': rtoi_12118, 'yli': rtoi_10716}\n    \t {'hsa': rtoi_12118, 'mmu': rtoi_12118, 'sce': rtoi_10716, 'yli': rtoi_10716}\n    PAPSR\n    \t {'sce': (rtoi_11741 & rtoi_15339) | (rtoi_11741 & rtoi_16019), 'eco': (rtoi_11741 & rtoi_15339) | (rtoi_11741 & rtoi_16019), 'yli': rtoi_11741}\n    \t {'sce': rtoi_11741 & rtoi_15339, 'yli': rtoi_11741}\n    PDE4\n    \t {'sce': rtoi_11787, 'yli': rtoi_11787 | rtoi_13690}\n    \t {'sce': rtoi_11787, 'yli': rtoi_11787 | rtoi_13690}\n    PGM\n    \t {'sce': rtoi_9910, 'eco': rtoi_9910, 'cre': rtoi_11229 | rtoi_12393 | rtoi_9910, 'yli': rtoi_12637 | rtoi_15425 | rtoi_9910}\n    \t {'hsa': rtoi_9910, 'mmu': rtoi_9910, 'sce': rtoi_9910, 'yli': rtoi_12637 | rtoi_15425 | rtoi_9910}\n    PGMT\n    \t {'sce': rtoi_9959, 'eco': rtoi_14546 | rtoi_8460 | rtoi_9959}\n    \t {'hsa': rtoi_13711 | rtoi_9959, 'mmu': rtoi_13711 | rtoi_9959, 'sce': rtoi_9959}\n    PHETA1\n    \t {'sce': rtoi_14908 | rtoi_15839, 'eco': rtoi_14281 | rtoi_14610 | rtoi_14853 | rtoi_8936, 'ppu': rtoi_14281 | rtoi_8936, 'cre': rtoi_13230 | rtoi_14281, 'yli': rtoi_13230 | rtoi_14281 | rtoi_14908 | rtoi_15839 | rtoi_8936}\n    \t {'hsa': rtoi_8936, 'mmu': rtoi_8936, 'sce': rtoi_12407 | rtoi_14908 | rtoi_15839, 'yli': rtoi_12407 | rtoi_13230 | rtoi_14281 | rtoi_14908 | rtoi_15839 | rtoi_8936}\n    PHETA1m\n    \t {'cre': rtoi_13230 | rtoi_14281, 'yli': rtoi_14908 | rtoi_15839}\n    \t {'hsa': rtoi_14281 | rtoi_16065, 'mmu': rtoi_14281 | rtoi_16065, 'yli': rtoi_12407 | rtoi_14908 | rtoi_15839}\n    PIt2r\n    \t {'sce': rtoi_10316 | rtoi_11418 | rtoi_11534 | rtoi_11686, 'cre': rtoi_11409 | rtoi_11410 | rtoi_11686, 'yli': (rtoi_10316 & rtoi_11418 & rtoi_11686) | (rtoi_10316 & rtoi_11534 & rtoi_11686)}\n    \t {'sce': rtoi_10316 | rtoi_11418 | rtoi_11534 | rtoi_11686, 'yli': (rtoi_10316 & rtoi_11418 & rtoi_11686) | (rtoi_10316 & rtoi_11534 & rtoi_11686)}\n    PRO1xm\n    \t {'sce': rtoi_14602, 'yli': rtoi_13432}\n    \t {'hsa': rtoi_14602, 'mmu': rtoi_14602, 'yli': rtoi_13432}\n    PROt2r\n    \t {'sce': rtoi_14229 | rtoi_15074, 'yli': (YALI0B09537g & rtoi_14229) | (YALI0B09537g & rtoi_15074)}\n    \t {'hsa': rtoi_12743, 'mmu': rtoi_12743, 'sce': rtoi_14229 | rtoi_15074, 'yli': (YALI0B09537g & rtoi_14229) | (YALI0B09537g & rtoi_15074)}\n    PTRCt3i\n    \t {'sce': rtoi_11017 | rtoi_13128, 'yli': (rtoi_11017 & rtoi_16454) | (rtoi_13128 & rtoi_16454)}\n    \t {'sce': rtoi_11017, 'yli': rtoi_11017 & rtoi_16454}\n    RNDR1\n    \t {'sce': (rtoi_11172 & rtoi_11290 & rtoi_15339) | (rtoi_11172 & rtoi_11290 & rtoi_16019) | (rtoi_11290 & rtoi_14237 & rtoi_15339) | (rtoi_11290 & rtoi_14237 & rtoi_16019), 'eco': (rtoi_11172 & rtoi_11290 & rtoi_15339) | (rtoi_11172 & rtoi_11290 & rtoi_16019) | (rtoi_11290 & rtoi_14237 & rtoi_15339) | (rtoi_11290 & rtoi_14237 & rtoi_16019), 'ppu': (rtoi_11172 & rtoi_11290) | (rtoi_11290 & rtoi_14237), 'cre': (CRv4_Au5_s9_g15314_t1 & rtoi_11172 & rtoi_11290) | (CRv4_Au5_s9_g15314_t1 & rtoi_11290 & rtoi_14237) | (rtoi_11172 & rtoi_11290 & rtoi_15339) | (rtoi_11172 & rtoi_11290 & rtoi_16019) | (rtoi_11290 & rtoi_14237 & rtoi_15339) | (rtoi_11290 & rtoi_14237 & rtoi_16019), 'yli': (rtoi_11172 & rtoi_11290) | (rtoi_11290 & rtoi_14237)}\n    \t {'hsa': (rtoi_11172 & rtoi_11290) | (rtoi_11290 & rtoi_14237), 'mmu': (rtoi_11172 & rtoi_11290) | (rtoi_11290 & rtoi_14237), 'sce': (rtoi_11172 & rtoi_11290 & rtoi_15339) | (rtoi_11290 & rtoi_14237 & rtoi_15339), 'yli': (rtoi_11172 & rtoi_11290) | (rtoi_11290 & rtoi_14237)}\n    RNDR2\n    \t {'sce': (rtoi_11172 & rtoi_11290 & rtoi_15339) | (rtoi_11172 & rtoi_11290 & rtoi_16019) | (rtoi_11290 & rtoi_14237 & rtoi_15339) | (rtoi_11290 & rtoi_14237 & rtoi_16019), 'eco': (rtoi_11172 & rtoi_11290 & rtoi_15339) | (rtoi_11172 & rtoi_11290 & rtoi_16019) | (rtoi_11290 & rtoi_14237 & rtoi_15339) | (rtoi_11290 & rtoi_14237 & rtoi_16019), 'ppu': (rtoi_11172 & rtoi_11290) | (rtoi_11290 & rtoi_14237), 'cre': (CRv4_Au5_s9_g15314_t1 & rtoi_11172 & rtoi_11290) | (CRv4_Au5_s9_g15314_t1 & rtoi_11290 & rtoi_14237) | (rtoi_11172 & rtoi_11290 & rtoi_15339) | (rtoi_11172 & rtoi_11290 & rtoi_16019) | (rtoi_11290 & rtoi_14237 & rtoi_15339) | (rtoi_11290 & rtoi_14237 & rtoi_16019), 'yli': (rtoi_11172 & rtoi_11290) | (rtoi_11290 & rtoi_14237)}\n    \t {'hsa': (rtoi_11172 & rtoi_11290) | (rtoi_11290 & rtoi_14237), 'mmu': (rtoi_11172 & rtoi_11290) | (rtoi_11290 & rtoi_14237), 'sce': (rtoi_11172 & rtoi_11290 & rtoi_15339) | (rtoi_11290 & rtoi_14237 & rtoi_15339), 'yli': (rtoi_11172 & rtoi_11290) | (rtoi_11290 & rtoi_14237)}\n    RNDR3\n    \t {'sce': (rtoi_11172 & rtoi_11290 & rtoi_15339) | (rtoi_11172 & rtoi_11290 & rtoi_16019) | (rtoi_11290 & rtoi_14237 & rtoi_15339) | (rtoi_11290 & rtoi_14237 & rtoi_16019), 'eco': (rtoi_11172 & rtoi_11290 & rtoi_15339) | (rtoi_11172 & rtoi_11290 & rtoi_16019) | (rtoi_11290 & rtoi_14237 & rtoi_15339) | (rtoi_11290 & rtoi_14237 & rtoi_16019), 'ppu': (rtoi_11172 & rtoi_11290) | (rtoi_11290 & rtoi_14237), 'cre': (CRv4_Au5_s9_g15314_t1 & rtoi_11172 & rtoi_11290) | (CRv4_Au5_s9_g15314_t1 & rtoi_11290 & rtoi_14237) | (rtoi_11172 & rtoi_11290 & rtoi_15339) | (rtoi_11172 & rtoi_11290 & rtoi_16019) | (rtoi_11290 & rtoi_14237 & rtoi_15339) | (rtoi_11290 & rtoi_14237 & rtoi_16019), 'yli': (rtoi_11172 & rtoi_11290) | (rtoi_11290 & rtoi_14237)}\n    \t {'hsa': (rtoi_11172 & rtoi_11290) | (rtoi_11290 & rtoi_14237), 'mmu': (rtoi_11172 & rtoi_11290) | (rtoi_11290 & rtoi_14237), 'sce': (rtoi_11172 & rtoi_11290 & rtoi_15339) | (rtoi_11290 & rtoi_14237 & rtoi_15339), 'yli': (rtoi_11172 & rtoi_11290) | (rtoi_11290 & rtoi_14237)}\n    RNDR4\n    \t {'sce': (rtoi_11172 & rtoi_11290 & rtoi_15339) | (rtoi_11172 & rtoi_11290 & rtoi_16019) | (rtoi_11290 & rtoi_14237 & rtoi_15339) | (rtoi_11290 & rtoi_14237 & rtoi_16019), 'eco': (rtoi_11172 & rtoi_11290 & rtoi_15339) | (rtoi_11172 & rtoi_11290 & rtoi_16019) | (rtoi_11290 & rtoi_14237 & rtoi_15339) | (rtoi_11290 & rtoi_14237 & rtoi_16019), 'ppu': (rtoi_11172 & rtoi_11290) | (rtoi_11290 & rtoi_14237), 'cre': (CRv4_Au5_s9_g15314_t1 & rtoi_11172 & rtoi_11290) | (CRv4_Au5_s9_g15314_t1 & rtoi_11290 & rtoi_14237) | (rtoi_11172 & rtoi_11290 & rtoi_15339) | (rtoi_11172 & rtoi_11290 & rtoi_16019) | (rtoi_11290 & rtoi_14237 & rtoi_15339) | (rtoi_11290 & rtoi_14237 & rtoi_16019), 'yli': (rtoi_11172 & rtoi_11290) | (rtoi_11290 & rtoi_14237)}\n    \t {'hsa': (rtoi_11172 & rtoi_11290) | (rtoi_11290 & rtoi_14237), 'mmu': (rtoi_11172 & rtoi_11290) | (rtoi_11290 & rtoi_14237), 'sce': (rtoi_11172 & rtoi_11290 & rtoi_15339) | (rtoi_11290 & rtoi_14237 & rtoi_15339), 'yli': (rtoi_11172 & rtoi_11290) | (rtoi_11290 & rtoi_14237)}\n    SADT\n    \t {'sce': rtoi_13443, 'ppu': PP_1303 & rtoi_14868, 'cre': rtoi_13443, 'yli': rtoi_13443}\n    \t {'hsa': rtoi_8709, 'mmu': rtoi_8709, 'sce': rtoi_13443, 'yli': rtoi_13443}\n    SERD_L\n    \t {'sce': rtoi_9216, 'eco': rtoi_11849, 'ppu': rtoi_11849, 'yli': rtoi_11909 | rtoi_9216}\n    \t {'sce': rtoi_9216, 'yli': rtoi_11909 | rtoi_9216}\n    SERPT\n    \t {'sce': YBR058C_A & rtoi_10303 & rtoi_9425, 'cre': rtoi_10303 & rtoi_9425, 'yli': rtoi_10303 | rtoi_9425}\n    \t {'hsa': rtoi_10303 & rtoi_9425, 'mmu': rtoi_10303 & rtoi_9425, 'sce': YBR058C_A & rtoi_10303 & rtoi_9425, 'yli': rtoi_10303 | rtoi_9425}\n    SERt2r\n    \t {'sce': rtoi_14229 | rtoi_15074 | rtoi_8962 | rtoi_9319 | rtoi_9322, 'yli': (YALI0E20713g & rtoi_14229 & rtoi_8962) | (YALI0E20713g & rtoi_14229 & rtoi_9319) | (YALI0E20713g & rtoi_14229 & rtoi_9322) | (YALI0E20713g & rtoi_15074 & rtoi_8962) | (YALI0E20713g & rtoi_15074 & rtoi_9319) | (YALI0E20713g & rtoi_15074 & rtoi_9322)}\n    \t {'sce': rtoi_14229 | rtoi_15074 | rtoi_8962 | rtoi_9319 | rtoi_9322 | rtoi_9962, 'yli': (YALI0E20713g & rtoi_14229 & rtoi_8962) | (YALI0E20713g & rtoi_14229 & rtoi_9319) | (YALI0E20713g & rtoi_14229 & rtoi_9322) | (YALI0E20713g & rtoi_14229 & rtoi_9962) | (YALI0E20713g & rtoi_15074 & rtoi_8962) | (YALI0E20713g & rtoi_15074 & rtoi_9319) | (YALI0E20713g & rtoi_15074 & rtoi_9322) | (YALI0E20713g & rtoi_15074 & rtoi_9962)}\n    SHSL4r\n    \t {'sce': rtoi_11463, 'ppu': rtoi_9499, 'yli': rtoi_11463 | rtoi_16725 | rtoi_16742}\n    \t {'sce': rtoi_11463, 'yli': rtoi_11463 | rtoi_16725 | rtoi_16742}\n    SO4ti\n    \t {'sce': rtoi_14119 | rtoi_15736 | rtoi_16682, 'yli': (rtoi_14119 & rtoi_16682) | (rtoi_15736 & rtoi_16682)}\n    \t {'sce': rtoi_14119 | rtoi_15736 | rtoi_16682, 'yli': (rtoi_14119 & rtoi_16682) | (rtoi_15736 & rtoi_16682)}\n    SPMDt3i\n    \t {'sce': rtoi_11017 | rtoi_13128, 'yli': (rtoi_11017 & rtoi_16454) | (rtoi_13128 & rtoi_16454)}\n    \t {'sce': rtoi_11017, 'yli': rtoi_11017 & rtoi_16454}\n    SPRMt2i\n    \t {'sce': rtoi_11017 | rtoi_11649 | rtoi_13128 | rtoi_14774, 'yli': (rtoi_11017 & rtoi_11649 & rtoi_16454) | (rtoi_11017 & rtoi_14774 & rtoi_16454) | (rtoi_11649 & rtoi_13128 & rtoi_16454) | (rtoi_13128 & rtoi_14774 & rtoi_16454)}\n    \t {'sce': rtoi_11017 | rtoi_14774, 'yli': rtoi_11017 & rtoi_14774 & rtoi_16454}\n    SQLEr\n    \t {'sce': rtoi_13286 & rtoi_13729, 'yli': rtoi_13729}\n    \t {'hsa': rtoi_13729, 'mmu': rtoi_13729, 'sce': rtoi_13286 & rtoi_13729, 'yli': rtoi_13729}\n    SUCD1m\n    \t {'sce': rtoi_11629 & rtoi_11802 & rtoi_11977 & rtoi_16281, 'cre': rtoi_11629, 'yli': rtoi_11629 & rtoi_11802 & rtoi_11977 & rtoi_16281}\n    \t {'hsa': SDHD & rtoi_11629 & rtoi_11977 & rtoi_16281, 'mmu': Sdhd & rtoi_11629 & rtoi_11977 & rtoi_16281, 'sce': rtoi_11629 & rtoi_11802 & rtoi_11977 & rtoi_16281, 'yli': rtoi_11629 & rtoi_11802 & rtoi_11977 & rtoi_16281}\n    SUCFUMtm\n    \t {'sce': rtoi_11740 | rtoi_12605 | rtoi_13510, 'cre': rtoi_12605, 'yli': (rtoi_11740 & rtoi_12605) | (rtoi_12605 & rtoi_13510)}\n    \t {'sce': rtoi_12605 | rtoi_13510, 'yli': rtoi_12605 & rtoi_13510}\n    SULR\n    \t {'sce': rtoi_10374 | rtoi_8744, 'eco': rtoi_13286 & rtoi_8744, 'ppu': PP_0860 & rtoi_8744, 'yli': rtoi_10374 & rtoi_8744}\n    \t {'sce': rtoi_10374 | rtoi_8744, 'yli': rtoi_10374 & rtoi_8744}\n    THFATm\n    \t {'sce': rtoi_10205 & rtoi_12898 & rtoi_13630 & rtoi_13948 & rtoi_15184, 'yli': rtoi_12898}\n    \t {'sce': rtoi_10205 & rtoi_12898 & rtoi_13630 & rtoi_13948 & rtoi_15184, 'yli': rtoi_12898}\n    THRD_L\n    \t {'sce': rtoi_9216, 'eco': rtoi_11909, 'ppu': rtoi_11909, 'yli': rtoi_11909}\n    \t {'hsa': rtoi_9216, 'mmu': rtoi_9216, 'sce': rtoi_9216, 'yli': rtoi_11909}\n    TRDR\n    \t {'sce': rtoi_15339 | rtoi_16019 | rtoi_9688 | (rtoi_15339 & rtoi_9688) | (rtoi_16019 & rtoi_9688), 'eco': (rtoi_15339 & rtoi_9688) | (rtoi_16019 & rtoi_9688), 'ppu': rtoi_15339 | rtoi_16019 | rtoi_9688, 'cre': (CRv4_Au5_s2_g8777_t1 & CRv4_Au5_s9_g15314_t1) | (CRv4_Au5_s2_g8777_t1 & rtoi_15339) | (CRv4_Au5_s2_g8777_t1 & rtoi_16019) | (CRv4_Au5_s8_g14830_t1 & CRv4_Au5_s9_g15314_t1) | (CRv4_Au5_s8_g14830_t1 & rtoi_15339) | (CRv4_Au5_s8_g14830_t1 & rtoi_16019) | (CRv4_Au5_s9_g15314_t1 & rtoi_9688) | (rtoi_15339 & rtoi_9688) | (rtoi_16019 & rtoi_9688), 'yli': rtoi_9688}\n    \t {'hsa': rtoi_15482, 'mmu': rtoi_15482, 'sce': rtoi_15339 | rtoi_9688 | (rtoi_15339 & rtoi_9688), 'yli': rtoi_9688}\n    TRE6PP\n    \t {'sce': (YML100W & rtoi_11389 & rtoi_12034) | (YMR261C & rtoi_11389 & rtoi_12034), 'yli': rtoi_12034}\n    \t {'sce': (YML100W & rtoi_11389 & rtoi_12034) | (YMR261C & rtoi_11389 & rtoi_12034), 'yli': rtoi_12034}\n    TRPTRS\n    \t {'sce': rtoi_14709, 'cre': rtoi_14709 | rtoi_15533, 'yli': rtoi_14709 | rtoi_15533}\n    \t {'sce': rtoi_14709, 'yli': rtoi_14709 | rtoi_15533}\n    TYRTA\n    \t {'eco': rtoi_14281 | rtoi_14610 | rtoi_14853 | rtoi_8936, 'ppu': rtoi_14281 | rtoi_8936, 'cre': rtoi_14281, 'yli': rtoi_13230 | rtoi_14281 | rtoi_14908 | rtoi_15839 | rtoi_8936}\n    \t {'hsa': rtoi_8936, 'mmu': rtoi_8936, 'yli': rtoi_12407 | rtoi_13230 | rtoi_14281 | rtoi_14908 | rtoi_15839 | rtoi_8936}\n    TYRTAim\n    \t {'cre': rtoi_13230 | rtoi_14281, 'yli': rtoi_14908 | rtoi_15839}\n    \t {'hsa': rtoi_14281 | rtoi_16065, 'mmu': rtoi_14281 | rtoi_16065, 'sce': rtoi_14281, 'yli': rtoi_12407 | rtoi_14908 | rtoi_15839}\n    UPPRT\n    \t {'sce': rtoi_14241, 'eco': rtoi_15095, 'ppu': rtoi_15095, 'cre': rtoi_8633, 'yli': rtoi_14241 | rtoi_15095}\n    \t {'sce': rtoi_14241, 'yli': rtoi_14241 | rtoi_15095}\n    URIDK2r\n    \t {'sce': rtoi_13190, 'cre': rtoi_15252, 'yli': rtoi_15252}\n    \t {'sce': rtoi_13190, 'yli': rtoi_15252}\n    URIt2\n    \t {'sce': rtoi_10921 | rtoi_11871 | rtoi_12902 | rtoi_13969, 'yli': (rtoi_10921 & rtoi_13969) | (rtoi_11871 & rtoi_13969) | (rtoi_12902 & rtoi_13969)}\n    \t {'sce': rtoi_12902 | rtoi_13969, 'yli': rtoi_12902 & rtoi_13969}\n\n\n\n```python\nfor x in set(Reaction_rule.keys()).intersection(Reaction_rule_Jeff):\n    if x not in Reaction_rule_final:\n        temp1 = sympy.Or(*[v for v in Reaction_rule[x].values()])\n        temp2 = sympy.Or(*[v for v in Reaction_rule_Jeff[x].values()])\n        Reaction_rule_final[x] = sympy.Or(temp1,temp2)\n```\n\n\n```python\ntemp = ['FAS140COA','FAS160COA','FAS180','FAS180COA','FAS80COA_L','FAS80_L']\nfor x in temp:\n    print(x)\n    print(Reaction_rule_final[x])\n```\n\n    FAS140COA\n    (rtoi_10677 & rtoi_16241 & rtoi_16695) | (rtoi_12826 & rtoi_8639 & rtoi_8670) | (rtoi_12826 & rtoi_8639 & rtoi_8777) | (rtoi_12826 & rtoi_8639 & rtoi_8670 & rtoi_8777) | (rtoi_14471 & rtoi_8639 & rtoi_8670 & rtoi_8777)\n    FAS160COA\n    (rtoi_10677 & rtoi_16241 & rtoi_16695) | (rtoi_12826 & rtoi_8639 & rtoi_8670) | (rtoi_12826 & rtoi_8639 & rtoi_8777) | (rtoi_12826 & rtoi_8639 & rtoi_8670 & rtoi_8777) | (rtoi_14471 & rtoi_8639 & rtoi_8670 & rtoi_8777)\n    FAS180\n    (rtoi_10677 & rtoi_16241 & rtoi_16695) | (rtoi_12826 & rtoi_8639 & rtoi_8670) | (rtoi_12826 & rtoi_8639 & rtoi_8777) | (rtoi_12826 & rtoi_8639 & rtoi_8670 & rtoi_8777) | (rtoi_14471 & rtoi_8639 & rtoi_8670 & rtoi_8777)\n    FAS180COA\n    (rtoi_10677 & rtoi_16241 & rtoi_16695) | (rtoi_12826 & rtoi_8639 & rtoi_8670) | (rtoi_12826 & rtoi_8639 & rtoi_8777) | (rtoi_12826 & rtoi_8639 & rtoi_8670 & rtoi_8777) | (rtoi_14471 & rtoi_8639 & rtoi_8670 & rtoi_8777)\n    FAS80COA_L\n    (rtoi_10677 & rtoi_16241 & rtoi_16695) | (rtoi_12826 & rtoi_8639 & rtoi_8670) | (rtoi_12826 & rtoi_8639 & rtoi_8777) | (rtoi_12826 & rtoi_8639 & rtoi_8670 & rtoi_8777) | (rtoi_14471 & rtoi_8639 & rtoi_8670 & rtoi_8777)\n    FAS80_L\n    (rtoi_10677 & rtoi_16241 & rtoi_16695) | (rtoi_12826 & rtoi_8639 & rtoi_8670) | (rtoi_12826 & rtoi_8639 & rtoi_8777) | (rtoi_12826 & rtoi_8639 & rtoi_8670 & rtoi_8777) | (rtoi_14471 & rtoi_8639 & rtoi_8670 & rtoi_8777)\n\n\n\n```python\ntemp = ['FAS140COA','FAS160COA','FAS180','FAS180COA','FAS80COA_L','FAS80_L']\nfor x in temp:\n    Reaction_rule_final[x] = parse_expr('(rtoi_10677 & rtoi_16241 & rtoi_16695) |\\\n                                         (rtoi_12826 & rtoi_8639 & rtoi_8670 & rtoi_8777) |\\\n                                         (rtoi_14471 & rtoi_8639 & rtoi_8670 & rtoi_8777)')\n```\n\n\n```python\nfor x in set(Reaction_rule.keys()).difference(Reaction_rule_Jeff):\n    if x not in Reaction_rule_final:\n        temp1 = sympy.Or(*[v for v in Reaction_rule[x].values()])\n        Reaction_rule_final[x] = temp1\nfor x in set(Reaction_rule_Jeff.keys()).difference(Reaction_rule):\n    if x not in Reaction_rule_final:\n        temp2 = sympy.Or(*[v for v in Reaction_rule_Jeff[x].values()])\n        Reaction_rule_final[x] = temp2\n```\n\n\n```python\nprint(len(Reaction_subset_union))\nprint(len(Reaction_rule_final))\n```\n\n    3804\n    3804\n\n\n\n```python\nprint(Reaction_subset_union['PGI'])\nprint(Reaction_rule_final['PGI'])\n```\n\n    ('eco', 'rev')\n    rtoi_9589\n\n\n\n```python\nIFO0880_model = cobra.Model('R. toruloides')\n```\n\n\n```python\nfor k, v in Reaction_subset_union.items():\n    temp = eval(v[0]).reactions.get_by_id(k).copy()\n    if v[1] == 'rev':\n        temp.lower_bound = -1000.0\n        temp.upper_bound = 1000.0\n    if v[1] == 'for':\n        temp.lower_bound = 0.0\n        temp.upper_bound = 1000.0\n    if v[1] == 'back':\n        temp.lower_bound = -1000.0\n        temp.upper_bound = 0.0        \n    temp.gene_reaction_rule = str(Reaction_rule_final[k]).replace('&','and').replace('|','or').replace('rtoi_','')\n    IFO0880_model.add_reaction(temp)\n```\n\n\n```python\nIFO0880_model\n```\n\n\n\n\n\n<table>\n    <tr>\n        <td><strong>Name</strong></td>\n        <td>R. toruloides</td>\n    </tr><tr>\n        <td><strong>Memory address</strong></td>\n        <td>0x018203cbeb8</td>\n    </tr><tr>\n        <td><strong>Number of metabolites</strong></td>\n        <td>3589</td>\n    </tr><tr>\n        <td><strong>Number of reactions</strong></td>\n        <td>3804</td>\n    </tr><tr>\n        <td><strong>Objective expression</strong></td>\n        <td>0</td>\n    </tr><tr>\n        <td><strong>Compartments</strong></td>\n        <td>c, x, m, e, r, v, n, g, u, p, h, s, f, l</td>\n    </tr>\n  </table>\n\n\n\n\n```python\nprint(len(Gene_to_reaction))\nprint(len(Gene_to_reaction_Jeff))\nprint(len(set(Gene_to_reaction).union(Gene_to_reaction_Jeff)))\n```\n\n    1020\n    934\n    1137\n\n\n\n```python\nprint(len(IFO0880_model.genes))\nprint(len([x for x in IFO0880_model.genes if not x.id[0].isalpha()]))\n```\n\n    1596\n    1137\n\n\n\n```python\ncobra.io.save_json_model(IFO0880_model, \"IFO0880_GPR.json\")\n```\n", "meta": {"hexsha": "82ec29c338a563ede3fd4364bca0d260d210bdce", "size": 207477, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Notebooks/0.Annotation_and_Draft_reconstruction/Draft_Reconstruction_from_OrthoMCL.ipynb", "max_stars_repo_name": "AgileBioFoundry/Rt_IFO0880", "max_stars_repo_head_hexsha": "c0cb9c57f662543f5db0ca80ce4990f841f39e8a", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Notebooks/0.Annotation_and_Draft_reconstruction/Draft_Reconstruction_from_OrthoMCL.ipynb", "max_issues_repo_name": "AgileBioFoundry/Rt_IFO0880", "max_issues_repo_head_hexsha": "c0cb9c57f662543f5db0ca80ce4990f841f39e8a", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Notebooks/0.Annotation_and_Draft_reconstruction/Draft_Reconstruction_from_OrthoMCL.ipynb", "max_forks_repo_name": "AgileBioFoundry/Rt_IFO0880", "max_forks_repo_head_hexsha": "c0cb9c57f662543f5db0ca80ce4990f841f39e8a", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.3475581926, "max_line_length": 4277, "alphanum_fraction": 0.5422528762, "converted": true, "num_tokens": 72555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489883132727684, "lm_q2_score": 0.036220056645233, "lm_q1q2_score": 0.015027659172714938}}
{"text": "# <span style='color:darkred'> 4 Trajectory Analysis </span>\n\n***\n\n**<span style='color:darkred'> Important Note </span>**\n\nBefore proceeding to the rest of the analysis, it is a good time to define a path that points to the location of the MD simulation data, which we will analyze here.\n\nIf you successfully ran the MD simulation, the correct path should be:\n\n\n```python\npath=\"OxCompBio-Datafiles/run\"\n```\n\nIf however, you need/want to use the data from the simulation that has been already performed, uncomment the command below to instead define the path that points to the prerun simulation.\n\n\n```python\n#path=\"OxCompBio-Datafiles/prerun/run\"\n```\n\n## <span style='color:darkred'> 4.1 Visualize the simulation </span>\n\nThe simplest and easiest type of analysis you should always do is to look at it with your eyes! Your eyes will tell you if something strange is happening immediately. A numerical analysis may not.\n\n### <span style='color:darkred'>  4.1.1 VMD </span>\n\n*Note: Again, this step is optional. If you don't have VMD, go to section 4.1.2 below to visualize the trajectory with NGLView instead.*\n\nLet us look at the simulations on VMD.\n\nOpen your vmd, by typing on your terminal:\n\n`% vmd`\n\nWhen it has finished placing all the windows on the screen. Click on `File` in the VMD main menu window and select `New Molecule`. The Molecule File Browser window should appear. Click on `Browse...` then select the `OxCompBio-Datafiles` and then the `run` directory and finally select `em.gro` (i.e. the file you made that has protein system energy minimized). Click `OK` and then click `Load`. It should load up the starting coordinates into the main window. Then click `Browse...` in the Molecule File Browser window. Select again the `OxCompBio-Datafiles`, then the `run` directory and then `md.xtc`. Select `OK` and then hit `Load`. The trajectory should start loading into the main VMD window. \n\nAlthough things will be moving, you can see that it is quite difficult to visualize the individual components. That is one of the problems with simulating such large and complicated systems. VMD makes it quite easy to look at individual components of a system. For example, let us consider the protein only. On the VMD Main menu, left-click on Graphics and select `Representations`. A new menu will appear (`Graphical Representations`). In the box entitled `Selected Atoms` type protein and hit enter. Only those atoms that form part of the protein are now selected. Various other selections and drawing methods will help to visualize different aspects of the simulation. \n\n<span style='color:Blue'> **Questions**  </span> \n\n* How would you say the protein behaves? \n\n\n* Is it doing anything unexpected? What would you consider unexpected behaviour?\n\n### <span style='color:darkred'> 4.1.2 NGLView </span>\n\n\nYou have already tested NGLView at the Python tutorial (Notebook `12_ProteinAnalysis`) and at the beginning of this tutorial. This time however, you can visualize the trajectory you generated after carrying out the MD simulation.\n\nYou should also be familiar now with the MDAnalysis Python library that we will use to analyze the MD trajectory. We will also use it below, to create a Universe and load it on NGLView.\n\n\n```python\n# Import MDAnalysis and NGLView\nimport MDAnalysis\nimport nglview\n\n# Load the protein structure and the trajectory as a universe named protein\nprotein=MDAnalysis.Universe(f\"{path}/em.gro\", f\"{path}/md_fit.xtc\")\nprotein_view = nglview.show_mdanalysis(protein)\nprotein_view.gui_style = 'ngl'\n\n#Color the protein based on its secondary structure\nprotein_view.update_cartoon(color='sstruc')\nprotein_view\n\n\n```\n\n\n    ThemeManager()\n\n\n\n    NGLWidget(gui_style='ngl', max_frame=100)\n\n\n<span style='color:Blue'> **Questions**  </span> \n\n* How would you say the protein behaves? \n\n\n* Is it doing anything unexpected? What would you consider unexpected behaviour?\n\nNow that we are sure the simulation is not doing anything ridiculous, we can start to ask questions about the simulation. The first thing to establish is whether the simulation has equilibrated to some state. So what are some measures of the system\nbeing equilibrated? And what can we use to test the reliability of the simulation?\n\n## <span style='color:darkred'> 4.2 System Equilibration </span> \n\n### <span style='color:darkred'> 4.2.1 Temperature fluctuation </span>\n\nThe system temperature as a function of time was calculated in the previous section, with the built-in GROMACS tool `gmx energy`, but we still have not looked at it. It is now time to plot the temperature *vs* time and assess the results.\n\n<span style='color:Blue'> **Questions**  </span> \n\n* Does the temperature fluctuate around an equilibrium  value?\n\n\n* Does this value correspond to the temperature that we predefined in the `md.mdp` input file?\n\nImport numpy and pyplot from matplotlib, required to read and plot the data, respectively.\n\n\n```python\n# We declare matplotlib inline to make sure it plots properly\n%matplotlib inline\n# We need to import numpy \nimport numpy as np\n# We need pyplot from matplotlib to generate our plots\nfrom matplotlib import pyplot\n```\n\nNow, using numpy, we can read the data from the `1hsg_temperature.xvg` file; the first column is the time (in ps) and the secong is the system temperature (in K).\n\n\n```python\n# Read the file that contains the system temperature for each frame\ntime=np.loadtxt(f\"{path}/1hsg_temperature.xvg\", comments=['#','@'])[:, 0]\ntemperature=np.loadtxt(f\"{path}/1hsg_temperature.xvg\", comments=['#','@'])[:, 1] \n```\n\nYou can use numpy again to compute the average temperature and its standard deviation.\n\n\n```python\n# Calculate and print the mean temperature and the standard deviation\n# Keep only two decimal points\nmean_temperature=round(np.mean(temperature), 2)\nstd_temperature=round(np.std(temperature), 2)\nprint(f\"The mean temperature is {mean_temperature} \u00b1 {std_temperature} K\")\n```\n\n    The mean temperature is 300.01 \u00b1 1.79 K\n\n\nFinally, you can plot the temperature *vs* simulation time.\n\n\n```python\n# Plot the temperature\npyplot.plot(time, temperature, color='darkred')\npyplot.title(\"Temperature over time\")\npyplot.xlabel(\"Time [ps]\")\npyplot.ylabel(\"Temperature [K]\")\npyplot.show()\n```\n\n### <span style='color:darkred'> 4.2.2 Energy of the system </span> \n\nAnother set of properties that is quite useful to examine is the various energetic contributions to the energy. The total\nenergy should be constant. but the various contributions can change and this can sometimes indicate something\ninteresting or strange happening in your simulation. Let us look at some energetic properties of the simulation.\n\nWe have already exctracted the Lennard-Jones energy, the Coulomb energy and the potential energy using again the GROMACS built-in tool `gmx energy`. The data of these three energetic components are saved in the same file called `1hsg_energies.xvg`; the first column contains the time (in ps) and the columns that follow contain the energies (in kJ/mol), in the same order as they were generated.\n\nWe can now read the data from the `1hsg_energies.xvg` file using numpy.\n\n\n```python\n# Read the file that contains the various energetic components for each frame\ntime=np.loadtxt(f\"{path}/1hsg_energies.xvg\", comments=['#','@'])[:, 0]\nlennard_jones=np.loadtxt(f\"{path}/1hsg_energies.xvg\", comments=['#','@'])[:, 1]\ncoulomb=np.loadtxt(f\"{path}/1hsg_energies.xvg\", comments=['#','@'])[:, 2]\npotential=np.loadtxt(f\"{path}/1hsg_energies.xvg\", comments=['#','@'])[:, 3]\n```\n\nAnd now that we read the data file, we can plot the energetic components *vs* simulation time in separate plots using matplotlib.\n\n\n```python\n# Plot the Lennard-Jones energy\npyplot.plot(time, lennard_jones, color='blue')\npyplot.title(\"Lennard Jones energy over time\")\npyplot.xlabel(\"Time [ps]\")\npyplot.ylabel(\"LJ energy [kJ/mol]\")\npyplot.show()\n\n# Plot the electrostatic energy\npyplot.plot(time, coulomb, color='purple')\npyplot.title(\"Electrostatic energy over time\")\npyplot.xlabel(\"Time [ps]\")\npyplot.ylabel(\"Coulomb energy [kJ/mol]\")\npyplot.show()\n\n# Plot the potential energy\npyplot.plot(time, potential, color='green')\npyplot.title(\"Potential energy over time\")\npyplot.xlabel(\"Time [ps]\")\npyplot.ylabel(\"Potential energy [kJ/mol]\")\npyplot.show()\n```\n\n<span style='color:Blue'> **Questions**  </span> \n\n* Can you plot the Coulomb energy and the potential energy, following the same steps as above? \n\n\n* Is the total energy stable in this simulation? \n\n\n* What is the dominant contribution to the potential energy?\n\n## <span style='color:darkred'> 4.3 Analysis of Protein </span>\n\n### <span style='color:darkred'> 4.3.1 Root mean square deviation (RMSD) of 1HSG </span>\n\nThe RMSD gives us an idea of how 'stable' our protein is when compared to our starting, static, structure. The lower the RMSD is, the more stable we can say our protein is. \n\nThe RMSD as a function of time, $\\rho (t)$, can be defined by the following equation:\n\n\\begin{equation}\n\\\\\n\\rho (t) = \\sqrt{\\frac{1}{N}\\sum^N_{i=1}w_i\\big(\\mathbf{x}_i(t) - \\mathbf{x}^{\\text{ref}}_i\\big)^2}\n\\end{equation}\n\nLuckily MDAnalysis has its own built-in function to calculate this and we can import it.\n\n\n\n\n```python\n# Import built-in MDAnalysis tools for alignment and RMSD.\nfrom MDAnalysis.analysis import align\nfrom MDAnalysis.analysis.rms import RMSD as rmsd\n\n# Define the simulation universe and the reference structure (protein structure at first frame)\nprotein = MDAnalysis.Universe(f\"{path}/md.gro\", f\"{path}/md_fit.xtc\")\nprotein_ref = MDAnalysis.Universe(f\"{path}/em.gro\", f\"{path}/md_fit.xtc\")\nprotein_ref.trajectory[0]\n\n# Call the MDAnalysis align function to align the MD simulation universe to the reference (first frame) universe\nalign_strucs = align.AlignTraj(protein, protein_ref, select=\"backbone\", weights=\"mass\", in_memory=True, verbose=True)\n\nR = align_strucs.run()\nrmsd_data = R.rmsd\n\n# Plot the RMSD\npyplot.plot(rmsd_data)\npyplot.title(\"RMSD over time\")\npyplot.xlabel(\"Frame number\")\npyplot.ylabel(\"RMSD (Angstrom)\")\npyplot.show()\n\n```\n\n<span style='color:Blue'> **Questions**  </span> \n\n* What does this tell you about the stability of the protein? Is it in a state of equilibrium and if so why and at what time?\n\n\n* Can you think of a situation where this approach might not be a very good indication of stability?\n\n### <span style='color:darkred'> 4.3.2 Root mean square fluctuation (RMSF) of 1HSG </span>\n\nA similar property that is particularly useful is the root mean square fluctuation (RMSF), which shows how each residue flucuates over its average position.\n\nThe RMSF for an atom, $\\rho_i$, is given by:\n\n\\begin{equation}\n\\rho_i = \\sqrt{\\sum^N_{i=1} \\big\\langle(\\mathbf{x}_i - \\langle \\mathbf{x}_i \\rangle )^2 \\big\\rangle }\n\\end{equation}\n\n\n```python\nfrom MDAnalysis.analysis.rms import RMSF as rmsf\n\n# Define again the simulation universe, using however the renumbered .gro file that you had generated earlier\nprotein = MDAnalysis.Universe(f\"{path}/em.gro\", f\"{path}/md_fit.xtc\")\n\n# Reset the trajectory to the first frame\nprotein.trajectory[0]\n\n# We will need to select the alpha Carbons only\ncalphas = protein.select_atoms(\"name CA\")\n\n# Compute the RMSF of alpha carbons. Omit the first 20 frames,\n# assuming that the system needs this amount of time (200 ps) to equilibrate\nrmsf_calc = rmsf(calphas, verbose=True).run(start=20)\n\n# Plot the RMSF\npyplot.plot(calphas.resindices+1, rmsf_calc.rmsf, color='darkorange' )\npyplot.title(\"Per-Residue Alpha Carbon RMSF\")\npyplot.xlabel(\"Residue Number\")\npyplot.ylabel(\"RMSF (Angstrom)\")\npyplot.show()\n```\n\n<span style='color:Blue'> **Questions**  </span> \n\n* Can you identify structural regions alone from this plot and does that fit in with the structure?\n\n\n* Residues 43-58 form part of the flexible flap that covers the binding site. How does this region behave in the simulation?\n\n### <span style='color:darkred'> 4.3.3 Hydrogen Bond Formation </span>\n\nWe can also use the simulation to monitor the formation of any hydrogen bonds that may be of interest.\n\nIn the case of HIV-1 protease, the hydrogen bonds (HB) that are formed between the ARG8', the ASP29 and the ARG87 amino acids at the interface of the two subunits act in stabilising the dimer.\n\nWe can analyse the trajectory and monitor the stability of these interactions *vs* simulation time.\n\n\n```python\n# Import the MDAnalysis built-in tool for HB Analysis\nfrom MDAnalysis.analysis.hydrogenbonds.hbond_analysis import HydrogenBondAnalysis as HBA\n\n# Define the protein universe\n# Note that when using this tool, it is recommended to include the .tpr file instead of the .gro file,\n# because it contains bond information, required for the identification of donors and acceptors.\nprotein = MDAnalysis.Universe(f\"{path}/md.tpr\", f\"{path}/md.xtc\")\n\n# Define the atom selections for the HB calculation.\n# In this case, the ARG hydrogens and the ASP oxygens, which act as the HB acceptors are specifically defined.\nhbonds = HBA(universe=protein, hydrogens_sel='resname ARG and name HH21 HH22', acceptors_sel='resname ASP and name OD1 OD2')\n\n# Perform the HB calculation\nhbonds.run()\n    \n# Plot the total number of ASP-ARG HBs vs time\nhbonds_time=hbonds.times\nhbonds_data=hbonds.count_by_time()\n\npyplot.plot(hbonds_time, hbonds_data, color='darkorange')\npyplot.title(\"ASP-ARG Hydrogen Bonds\")\npyplot.xlabel(\"Time [ps]\")\npyplot.ylabel(\"# Hydrogen Bonds\")\npyplot.show()\n\n# Compute and print the average number of HBs and the standard deviation\naver_hbonds=round(np.mean(hbonds_data), 2)\nstd_hbonds=round(np.std(hbonds_data), 2)\nprint(f\"The average number of ASP-ARG HBs is {aver_hbonds} \u00b1 {std_hbonds}\")\n```\n\n<span style='color:Blue'> **Questions**  </span> \n\n* How much variation is there in the number of hydrogen bonds?\n\n\n* Do any break and not reform? \n\n\n* Using VMD, can you observe the HB formation and breakage throughout the simulation?\n\n***\n\nThis concludes the analysis section, but the aim was only to give you an idea of the numerous information that we can gain when analysing an MD trajectory. Feel free to ask and attempt to answer your own questions, utilising the tools that you were introduced to during the tutorial.\n\n## <span style='color:darkred'> 4.4 Further Reading </span>\n\n\nThe texts recommended here are the same as those mentioned in the lecture:\n* \"Molecular Modelling. Principles and Applications\". Andrew Leach. Publisher: Prentice Hall. ISBN: 0582382106. This book has rapidly become the defacto introductory text for all aspects of simulation.\n* \"Computer simulation of liquids\". Allen, Michael P., and Dominic J. Tildesley. Oxford university press, 2017.\n* \"Molecular Dynamics Simulation: Elementary Methods\". J.M. Haile. Publisher: Wiley. ISBN: 047118439X. This text provides a more focus but slightly more old-fashioned view of simulation. It has some nice simple examples of how to code (in fortran) some of the algorithms though.\n\n", "meta": {"hexsha": "d0c237d677b7ec885747abf21a8da4ab1f20f7aa", "size": 226085, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorials/MD/04_Trajectory_Analysis_Solutions.ipynb", "max_stars_repo_name": "AfroditiMariaZaki/OxCompBio", "max_stars_repo_head_hexsha": "15d23de729c1558d80f476bf5a0a1f1cf3311bc6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorials/MD/04_Trajectory_Analysis_Solutions.ipynb", "max_issues_repo_name": "AfroditiMariaZaki/OxCompBio", "max_issues_repo_head_hexsha": "15d23de729c1558d80f476bf5a0a1f1cf3311bc6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/MD/04_Trajectory_Analysis_Solutions.ipynb", "max_forks_repo_name": "AfroditiMariaZaki/OxCompBio", "max_forks_repo_head_hexsha": "15d23de729c1558d80f476bf5a0a1f1cf3311bc6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 308.8592896175, "max_line_length": 35044, "alphanum_fraction": 0.928894, "converted": true, "num_tokens": 3698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14033625308549463, "lm_q2_score": 0.10669059891633578, "lm_q1q2_score": 0.014972558891365898}}
{"text": "```python\n! pip install qeds\nimport pandas as pd\nimport numpy as np\n!pip install pyarrow\nimport pyarrow.feather\n```\n\n    Requirement already satisfied: qeds in c:\\users\\asus\\anaconda3\\lib\\site-packages (0.6.2)\n    Requirement already satisfied: pyarrow in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.16.0)\n    Requirement already satisfied: scipy in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (1.3.1)\n    Requirement already satisfied: openpyxl in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (3.0.0)\n    Requirement already satisfied: plotly in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (4.5.4)\n    Requirement already satisfied: statsmodels in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.10.1)\n    Requirement already satisfied: pandas-datareader in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.8.1)\n    Requirement already satisfied: quandl in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (3.5.0)\n    Requirement already satisfied: requests in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (2.22.0)\n    Requirement already satisfied: seaborn in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.9.0)\n    Requirement already satisfied: numpy in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (1.16.5)\n    Requirement already satisfied: scikit-learn in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.21.3)\n    Requirement already satisfied: quantecon in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.4.6)\n    Requirement already satisfied: pandas in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (0.25.1)\n    Requirement already satisfied: matplotlib in c:\\users\\asus\\anaconda3\\lib\\site-packages (from qeds) (3.1.1)\n    Requirement already satisfied: six>=1.0.0 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pyarrow->qeds) (1.12.0)\n    Requirement already satisfied: jdcal in c:\\users\\asus\\anaconda3\\lib\\site-packages (from openpyxl->qeds) (1.4.1)\n    Requirement already satisfied: et-xmlfile in c:\\users\\asus\\anaconda3\\lib\\site-packages (from openpyxl->qeds) (1.0.1)\n    Requirement already satisfied: retrying>=1.3.3 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from plotly->qeds) (1.3.3)\n    Requirement already satisfied: patsy>=0.4.0 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from statsmodels->qeds) (0.5.1)\n    Requirement already satisfied: lxml in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pandas-datareader->qeds) (4.4.1)\n    Requirement already satisfied: python-dateutil in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quandl->qeds) (2.8.0)\n    Requirement already satisfied: more-itertools in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quandl->qeds) (7.2.0)\n    Requirement already satisfied: inflection>=0.3.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quandl->qeds) (0.3.1)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (2019.9.11)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (1.24.2)\n    Requirement already satisfied: idna<2.9,>=2.5 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from requests->qeds) (2.8)\n    Requirement already satisfied: joblib>=0.11 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from scikit-learn->qeds) (0.13.2)\n    Requirement already satisfied: sympy in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quantecon->qeds) (1.4)\n    Requirement already satisfied: numba>=0.38 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from quantecon->qeds) (0.45.1)\n    Requirement already satisfied: pytz>=2017.2 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pandas->qeds) (2019.3)\n    Requirement already satisfied: cycler>=0.10 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (1.1.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from matplotlib->qeds) (2.4.2)\n    Requirement already satisfied: mpmath>=0.19 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from sympy->quantecon->qeds) (1.1.0)\n    Requirement already satisfied: llvmlite>=0.29.0dev0 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from numba>=0.38->quantecon->qeds) (0.29.0)\n    Requirement already satisfied: setuptools in c:\\users\\asus\\anaconda3\\lib\\site-packages (from kiwisolver>=1.0.1->matplotlib->qeds) (41.4.0)\n    Requirement already satisfied: pyarrow in c:\\users\\asus\\anaconda3\\lib\\site-packages (0.16.0)\n    Requirement already satisfied: six>=1.0.0 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pyarrow) (1.12.0)\n    Requirement already satisfied: numpy>=1.14 in c:\\users\\asus\\anaconda3\\lib\\site-packages (from pyarrow) (1.16.5)\n\n\n# Storage Formats - Exercises\n\n## Exercise 1\n\n**In the cell below, the variable `url` contains a web address to a csv file containing the result of all NFL games from September 1920 to February 2017.**\n\n1. **Use `pd.read_csv` to read this file into a DataFrame named `nfl`.** \n\n\n```python\nurl = \"https://raw.githubusercontent.com/fivethirtyeight/nfl-elo-game/\"\nurl = url + \"3488b7d0b46c5f6583679bc40fb3a42d729abd39/data/nfl_games.csv\"\n\nnfl = pd.read_csv(url, index_col=0)\nnfl\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>season</th>\n      <th>neutral</th>\n      <th>playoff</th>\n      <th>team1</th>\n      <th>team2</th>\n      <th>elo1</th>\n      <th>elo2</th>\n      <th>elo_prob1</th>\n      <th>score1</th>\n      <th>score2</th>\n      <th>result1</th>\n    </tr>\n    <tr>\n      <th>date</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>1920-09-26</td>\n      <td>1920</td>\n      <td>0</td>\n      <td>0</td>\n      <td>RII</td>\n      <td>STP</td>\n      <td>1503.947000</td>\n      <td>1300.000000</td>\n      <td>0.824651</td>\n      <td>48</td>\n      <td>0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <td>1920-10-03</td>\n      <td>1920</td>\n      <td>0</td>\n      <td>0</td>\n      <td>AKR</td>\n      <td>WHE</td>\n      <td>1503.420000</td>\n      <td>1300.000000</td>\n      <td>0.824212</td>\n      <td>43</td>\n      <td>0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <td>1920-10-03</td>\n      <td>1920</td>\n      <td>0</td>\n      <td>0</td>\n      <td>RCH</td>\n      <td>ABU</td>\n      <td>1503.420000</td>\n      <td>1300.000000</td>\n      <td>0.824212</td>\n      <td>10</td>\n      <td>0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <td>1920-10-03</td>\n      <td>1920</td>\n      <td>0</td>\n      <td>0</td>\n      <td>DAY</td>\n      <td>COL</td>\n      <td>1493.002000</td>\n      <td>1504.908000</td>\n      <td>0.575819</td>\n      <td>14</td>\n      <td>0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <td>1920-10-03</td>\n      <td>1920</td>\n      <td>0</td>\n      <td>0</td>\n      <td>RII</td>\n      <td>MUN</td>\n      <td>1516.108000</td>\n      <td>1478.004000</td>\n      <td>0.644171</td>\n      <td>45</td>\n      <td>0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <td>2017-01-15</td>\n      <td>2016</td>\n      <td>0</td>\n      <td>1</td>\n      <td>DAL</td>\n      <td>GB</td>\n      <td>1617.794683</td>\n      <td>1635.451172</td>\n      <td>0.567714</td>\n      <td>31</td>\n      <td>34</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <td>2017-01-15</td>\n      <td>2016</td>\n      <td>0</td>\n      <td>1</td>\n      <td>KC</td>\n      <td>PIT</td>\n      <td>1681.926463</td>\n      <td>1647.734179</td>\n      <td>0.638993</td>\n      <td>16</td>\n      <td>18</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <td>2017-01-22</td>\n      <td>2016</td>\n      <td>0</td>\n      <td>1</td>\n      <td>ATL</td>\n      <td>GB</td>\n      <td>1664.127266</td>\n      <td>1651.537731</td>\n      <td>0.609840</td>\n      <td>44</td>\n      <td>21</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <td>2017-01-22</td>\n      <td>2016</td>\n      <td>0</td>\n      <td>1</td>\n      <td>NE</td>\n      <td>PIT</td>\n      <td>1747.160321</td>\n      <td>1662.437215</td>\n      <td>0.703052</td>\n      <td>36</td>\n      <td>17</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <td>2017-02-05</td>\n      <td>2016</td>\n      <td>1</td>\n      <td>1</td>\n      <td>ATL</td>\n      <td>NE</td>\n      <td>1688.081418</td>\n      <td>1763.818168</td>\n      <td>0.392700</td>\n      <td>28</td>\n      <td>34</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>15740 rows \u00d7 11 columns</p>\n</div>\n\n\n\n2. **Print the shape and column names of `nfl`.**\n\n\n```python\nprint(\"nfl.shape=\",nfl.shape)\nprint(nfl.columns)\n```\n\n    nfl.shape= (15740, 11)\n    Index(['season', 'neutral', 'playoff', 'team1', 'team2', 'elo1', 'elo2',\n           'elo_prob1', 'score1', 'score2', 'result1'],\n          dtype='object')\n\n\n3. **Save the DataFrame to a file named `nfl.xlsx`**  \n\n\n```python\nnfl.to_excel(\"nfl.xlsx\", \"nfl\")\n```\n\n4. **Open the spreadsheet using Excel on your computer.**  \n\n## Exercise 2\n\n1. **Compute the average total points in each game (note, you will need to sum two of the columns to get total points).**  \n\n\n```python\n#we compute the total points as score1 + score 2, then we take the average\nnfl[\"total_points\"] = nfl[\"score1\"]+nfl[\"score2\"]\nnfl[\"total_points\"].mean()\n```\n\n\n\n\n    39.95368487928844\n\n\n\n2. **Repeat the above calculation, but only for playoff games.**  \n\n\n```python\n#here we compute the average total points for the subset corresponding to playoff games\nnfl[\"total_points\"][nfl[\"playoff\"]==1].mean()\n```\n\n\n\n\n    42.70404411764706\n\n\n\n3. **Compute the average score for your favorite team (you\u2019ll need to consider when they were team1 vs team2).**   \n\n\n```python\n#I don't have a smarter solution\n\n#in order to get the average for AKR:\n    #I sum the total points obtained by AKR either as team1 or team2\n    #I sum the total number of games of AKR either as team1 or team2\n    #then I divide the total points by the total number of games\n\nsum_teams12   = nfl[\"total_points\"][nfl[\"team1\"]==\"AKR\"].sum()   + nfl[\"total_points\"][nfl[\"team2\"]==\"AKR\"].sum()\ncount_teams12 = nfl[\"total_points\"][nfl[\"team1\"]==\"AKR\"].count() + nfl[\"total_points\"][nfl[\"team2\"]==\"AKR\"].count()\naverage = sum_teams12/count_teams12\naverage\n```\n\n\n\n\n    17.125\n\n\n\n4. **Compute the ratio of \u201cupsets\u201d to total games played. An upset is defined as a team with a lower ELO winning the game.** \n\n\n```python\n#for all the matches \nnfl.loc[((nfl['elo1']>nfl['elo2']) & (nfl['result1']==0)) | ((nfl['elo2']>nfl['elo1']) & (nfl['result1']==1))  , 'Upset?' ] =1 \nnfl.loc[(nfl['Upset?']!=1), 'Upset?']=0\nnfl['Upset?'].mean()\n```\n\n\n\n\n    0.34358322744599745\n\n\n\n\n```python\n#only for the matches of AKR (as team1)\nnfl.loc[((nfl['elo1']>nfl['elo2']) & (nfl['result1']==0)) | ((nfl['elo2']>nfl['elo1']) & (nfl['result1']==1))  , 'Upset?' ] =1 \nnfl.loc[(nfl['Upset?']!=1), 'Upset?']=0\nnfl['Upset?'][nfl[\"team1\"] == \"AKR\"].mean()\n```\n\n\n\n\n    0.21739130434782608\n\n\n", "meta": {"hexsha": "7893f008ec22ec02015ec7ff993e41a77834508a", "size": 20721, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Session_7/4_storage_formats_exercises.ipynb", "max_stars_repo_name": "remi-sudo/Classes", "max_stars_repo_head_hexsha": "71497927ed4d54ddf6fd5abe2ddabb5966eb0304", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Session_7/4_storage_formats_exercises.ipynb", "max_issues_repo_name": "remi-sudo/Classes", "max_issues_repo_head_hexsha": "71497927ed4d54ddf6fd5abe2ddabb5966eb0304", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Session_7/4_storage_formats_exercises.ipynb", "max_forks_repo_name": "remi-sudo/Classes", "max_forks_repo_head_hexsha": "71497927ed4d54ddf6fd5abe2ddabb5966eb0304", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4205128205, "max_line_length": 164, "alphanum_fraction": 0.4677863037, "converted": true, "num_tokens": 4261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27202456289736326, "lm_q2_score": 0.05500528868073314, "lm_q1q2_score": 0.014962789610419717}}
{"text": "### Understand our data\n##### Read in the pickle file\n\n\n```python\nimport numpy as np\nimport pandas as pd\nimport pickle\n```\n\n\n```python\ndata = pd.read_pickle('ret1_data.pkl')\n```\n\n\n```python\ntype(data)\n```\n\n\n\n\n    list\n\n\n\n\n```python\ntype(data[0])\n```\n\n\n\n\n    dict\n\n\n\n\n```python\nlen(data)\n```\n\n\n\n\n    16\n\n\n\nThe data in the pickle file is a list of $16$ dictionaries, as stated in the description of the data structure.\n\n\n```python\nexample = data[15]\n\nprint(example.keys())\n\nname = example['subject_name']\n\nprint(f'Subject names are of the form \"{name}\"')\n```\n\n    dict_keys(['sample_number', 'stimulations', 'subject_name', 'session_date'])\n    Subject names are of the form \"WT (pax6 het)\"\n\n\nSee how many unique subject names there are.\n\n\n```python\nsubjects = set([item['subject_name'] for item in data])\n\n\nprint(f'There are {len(subjects)} unique subjects.')\n\nprint(subjects)\n```\n\n    There are 5 unique subjects.\n    {'KO (chx10)', 'KO bax -/- (chx10)', 'WT (chx10 het)', 'WT (pax6 het)', 'KO (pax6)'}\n\n\nTherefore, we can assume that each subject may have been used in more than one sample, much like in the tutorial where a single mouse could be used for multiple experiment sessions. \n\n## Import DataJoint and start creating pipeline\n\n### Part (1) of the challenge\n\n\n```python\nimport datajoint as dj\n\n# dj.config['database.user'] =  'USERNAME_GOES_HERE'\n# dj.config['database.password'] = 'PASSWORD_GOES_HERE'             # replace with real password\ndj.config['database.host'] = 'tutorial-db.datajoint.io'   # DataJoint tutorial database\n\ndj.config.save_global()\n\ndj.conn()\n```\n\n    Connecting rnvoleti@tutorial-db.datajoint.io:3306\n\n\n\n\n\n    DataJoint connection (connected) rnvoleti@tutorial-db.datajoint.io:3306\n\n\n\nThe first step is to create a `dj.Manual()` table for each of the mice, as we did in the tutorial. However, here the only unique identifier provided is the `subject_name` key, so we will use that as the primary attribute for this new `Mouse` table. However, we can add another attributes for knockout (KO) or wild type (WT), and call it `type`. \n\nStart by defining a new schema.\n\n\n```python\nschema = dj.schema('rnvoleti_interview')\n```\n\n\n```python\n@schema\nclass Subject(dj.Manual):\n    definition = \"\"\"\n    # Experimental animals\n    subject_name             : varchar(30)\n    ---\n    gene                     : varchar(30)\n    genotype                 : enum('homozygous', 'heterozygous')\n    type                     : enum('WT', 'KO')\n    bax='unknown'            : enum('-/-', '+/+', '+/-', 'unknown')\n    \"\"\"\n```\n\n\n```python\nSubject()\n```\n\n\n\n\n\n\n<style type=\"text/css\">\n    .Relation{\n        border-collapse:collapse;\n    }\n    .Relation th{\n        background: #A0A0A0; color: #ffffff; padding:4px; border:#f0e0e0 1px solid;\n        font-weight: normal; font-family: monospace; font-size: 100%;\n    }\n    .Relation td{\n        padding:4px; border:#f0e0e0 1px solid; font-size:100%;\n    }\n    .Relation tr:nth-child(odd){\n        background: #ffffff;\n    }\n    .Relation tr:nth-child(even){\n        background: #f3f1ff;\n    }\n    /* Tooltip container */\n    .djtooltip {\n    }\n    /* Tooltip text */\n    .djtooltip .djtooltiptext {\n        visibility: hidden;\n        width: 120px;\n        background-color: black;\n        color: #fff;\n        text-align: center;\n        padding: 5px 0;\n        border-radius: 6px;\n        /* Position the tooltip text - see examples below! */\n        position: absolute;\n        z-index: 1;\n    }\n    #primary {\n        font-weight: bold;\n        color: black;\n    }\n    #nonprimary {\n        font-weight: normal;\n        color: white;\n    }\n\n    /* Show the tooltip text when you mouse over the tooltip container */\n    .djtooltip:hover .djtooltiptext {\n        visibility: visible;\n    }\n</style>\n\n<b>Experimental animals</b>\n    <div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n    <table border=\"1\" class=\"Relation\">\n        <thead> <tr style=\"text-align: right;\"> <th> <div class=\"djtooltip\">\n                        <p id=\"primary\">subject_name</p>\n                        <span class=\"djtooltiptext\"></span>\n                    </div></th><th><div class=\"djtooltip\">\n                        <p id=\"nonprimary\">gene</p>\n                        <span class=\"djtooltiptext\"></span>\n                    </div></th><th><div class=\"djtooltip\">\n                        <p id=\"nonprimary\">genotype</p>\n                        <span class=\"djtooltiptext\"></span>\n                    </div></th><th><div class=\"djtooltip\">\n                        <p id=\"nonprimary\">type</p>\n                        <span class=\"djtooltiptext\"></span>\n                    </div></th><th><div class=\"djtooltip\">\n                        <p id=\"nonprimary\">bax</p>\n                        <span class=\"djtooltiptext\"></span>\n                    </div> </th> </tr> </thead>\n        <tbody> <tr>  </tr> </tbody>\n    </table>\n\n    <p>Total: 0</p></div>\n\n\n\n\n\n```python\nsubjects\n```\n\n\n\n\n    {'KO (chx10)',\n     'KO (pax6)',\n     'KO bax -/- (chx10)',\n     'WT (chx10 het)',\n     'WT (pax6 het)'}\n\n\n\n\n```python\n# Create a list of dictionaries for all subjects\n# Note: I am manually entering this since there are only 5 unique mice, but it would probably be better to write some code to parse the subject_name\n\nsubject_list = [{'subject_name': 'KO (chx10)' , 'gene': 'chx10', 'genotype': 'homozygous', 'type': 'KO', 'bax': 'unknown'},\n                {'subject_name': 'KO (pax6)' , 'gene': 'pax6','genotype': 'homozygous', 'type': 'KO', 'bax': 'unknown'},\n                {'subject_name': 'KO bax -/- (chx10)' , 'gene': 'chx10', 'genotype': 'homozygous', 'type': 'KO', 'bax': '-/-'},\n                {'subject_name': 'WT (chx10 het)' , 'gene': 'chx10', 'genotype': 'heterozygous', 'type': 'WT', 'bax': 'unknown'},\n                {'subject_name': 'WT (pax6 het)' , 'gene': 'pax6', 'genotype': 'heterozygous', 'type': 'WT', 'bax': 'unknown'}\n               ]\n                \n\n```\n\n\n```python\nSubject.insert(subject_list, skip_duplicates=True)\n```\n\n\n```python\nSubject()\n```\n\n\n\n\n\n\n    <style type=\"text/css\">\n        .Relation{\n            border-collapse:collapse;\n        }\n        .Relation th{\n            background: #A0A0A0; color: #ffffff; padding:4px; border:#f0e0e0 1px solid;\n            font-weight: normal; font-family: monospace; font-size: 100%;\n        }\n        .Relation td{\n            padding:4px; border:#f0e0e0 1px solid; font-size:100%;\n        }\n        .Relation tr:nth-child(odd){\n            background: #ffffff;\n        }\n        .Relation tr:nth-child(even){\n            background: #f3f1ff;\n        }\n        /* Tooltip container */\n        .djtooltip {\n        }\n        /* Tooltip text */\n        .djtooltip .djtooltiptext {\n            visibility: hidden;\n            width: 120px;\n            background-color: black;\n            color: #fff;\n            text-align: center;\n            padding: 5px 0;\n            border-radius: 6px;\n            /* Position the tooltip text - see examples below! */\n            position: absolute;\n            z-index: 1;\n        }\n        #primary {\n            font-weight: bold;\n            color: black;\n        }\n        #nonprimary {\n            font-weight: normal;\n            color: white;\n        }\n\n        /* Show the tooltip text when you mouse over the tooltip container */\n        .djtooltip:hover .djtooltiptext {\n            visibility: visible;\n        }\n    </style>\n\n    <b>Experimental animals</b>\n        <div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n        <table border=\"1\" class=\"Relation\">\n            <thead> <tr style=\"text-align: right;\"> <th> <div class=\"djtooltip\">\n                            <p id=\"primary\">subject_name</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">gene</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">genotype</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">type</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">bax</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div> </th> </tr> </thead>\n            <tbody> <tr> <td>KO (chx10)</td>\n<td>chx10</td>\n<td>homozygous</td>\n<td>KO</td>\n<td>unknown</td></tr><tr><td>KO (pax6)</td>\n<td>pax6</td>\n<td>homozygous</td>\n<td>KO</td>\n<td>unknown</td></tr><tr><td>KO bax -/- (chx10)</td>\n<td>chx10</td>\n<td>homozygous</td>\n<td>KO</td>\n<td>-/-</td></tr><tr><td>WT (chx10 het)</td>\n<td>chx10</td>\n<td>heterozygous</td>\n<td>WT</td>\n<td>unknown</td></tr><tr><td>WT (pax6 het)</td>\n<td>pax6</td>\n<td>heterozygous</td>\n<td>WT</td>\n<td>unknown</td> </tr> </tbody>\n        </table>\n\n        <p>Total: 5</p></div>\n\n\n\n\n#### Do a test query\n\n\n```python\nSubject() & 'genotype = \"heterozygous\"'\n```\n\n\n\n\n\n\n    <style type=\"text/css\">\n        .Relation{\n            border-collapse:collapse;\n        }\n        .Relation th{\n            background: #A0A0A0; color: #ffffff; padding:4px; border:#f0e0e0 1px solid;\n            font-weight: normal; font-family: monospace; font-size: 100%;\n        }\n        .Relation td{\n            padding:4px; border:#f0e0e0 1px solid; font-size:100%;\n        }\n        .Relation tr:nth-child(odd){\n            background: #ffffff;\n        }\n        .Relation tr:nth-child(even){\n            background: #f3f1ff;\n        }\n        /* Tooltip container */\n        .djtooltip {\n        }\n        /* Tooltip text */\n        .djtooltip .djtooltiptext {\n            visibility: hidden;\n            width: 120px;\n            background-color: black;\n            color: #fff;\n            text-align: center;\n            padding: 5px 0;\n            border-radius: 6px;\n            /* Position the tooltip text - see examples below! */\n            position: absolute;\n            z-index: 1;\n        }\n        #primary {\n            font-weight: bold;\n            color: black;\n        }\n        #nonprimary {\n            font-weight: normal;\n            color: white;\n        }\n\n        /* Show the tooltip text when you mouse over the tooltip container */\n        .djtooltip:hover .djtooltiptext {\n            visibility: visible;\n        }\n    </style>\n\n    <b>Experimental animals</b>\n        <div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n        <table border=\"1\" class=\"Relation\">\n            <thead> <tr style=\"text-align: right;\"> <th> <div class=\"djtooltip\">\n                            <p id=\"primary\">subject_name</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">gene</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">genotype</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">type</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">bax</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div> </th> </tr> </thead>\n            <tbody> <tr> <td>WT (chx10 het)</td>\n<td>chx10</td>\n<td>heterozygous</td>\n<td>WT</td>\n<td>unknown</td></tr><tr><td>WT (pax6 het)</td>\n<td>pax6</td>\n<td>heterozygous</td>\n<td>WT</td>\n<td>unknown</td> </tr> </tbody>\n        </table>\n\n        <p>Total: 2</p></div>\n\n\n\n\n#### Create Session Table\n\nThis will depend on the `Subject`. \n\nUsing the data loaded from the pickle file, we can use the `dj.Manual` tier here to define a Sesssion.\n\n\n```python\n@schema\nclass Session(dj.Manual):\n    definition = \"\"\"\n    # Experiment session\n    -> Subject\n    sample_number              : int                          # sample number\n    session_date               : date                         # date of session in YYYY-MM-DD format\n    ---\n    stimulations               : longblob                     # list of dicts for stimulations\n    \"\"\"\n```\n\n#### Visualize schema\n\n\n```python\ndj.Diagram(schema)\n```\n\n    /home/rohit/miniconda3/envs/datajoint_interview/lib/python3.8/inspect.py:350: FutureWarning: pandas.Float64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.\n      value = getattr(object, key)\n    /home/rohit/miniconda3/envs/datajoint_interview/lib/python3.8/inspect.py:350: FutureWarning: pandas.Int64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.\n      value = getattr(object, key)\n    /home/rohit/miniconda3/envs/datajoint_interview/lib/python3.8/inspect.py:350: FutureWarning: pandas.UInt64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.\n      value = getattr(object, key)\n    /home/rohit/miniconda3/envs/datajoint_interview/lib/python3.8/inspect.py:350: FutureWarning: pandas.Float64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.\n      value = getattr(object, key)\n    /home/rohit/miniconda3/envs/datajoint_interview/lib/python3.8/inspect.py:350: FutureWarning: pandas.Int64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.\n      value = getattr(object, key)\n    /home/rohit/miniconda3/envs/datajoint_interview/lib/python3.8/inspect.py:350: FutureWarning: pandas.UInt64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.\n      value = getattr(object, key)\n\n\n\n\n\n    \n\n    \n\n\n\n\n```python\nSession()\n```\n\n\n\n\n\n\n<style type=\"text/css\">\n    .Relation{\n        border-collapse:collapse;\n    }\n    .Relation th{\n        background: #A0A0A0; color: #ffffff; padding:4px; border:#f0e0e0 1px solid;\n        font-weight: normal; font-family: monospace; font-size: 100%;\n    }\n    .Relation td{\n        padding:4px; border:#f0e0e0 1px solid; font-size:100%;\n    }\n    .Relation tr:nth-child(odd){\n        background: #ffffff;\n    }\n    .Relation tr:nth-child(even){\n        background: #f3f1ff;\n    }\n    /* Tooltip container */\n    .djtooltip {\n    }\n    /* Tooltip text */\n    .djtooltip .djtooltiptext {\n        visibility: hidden;\n        width: 120px;\n        background-color: black;\n        color: #fff;\n        text-align: center;\n        padding: 5px 0;\n        border-radius: 6px;\n        /* Position the tooltip text - see examples below! */\n        position: absolute;\n        z-index: 1;\n    }\n    #primary {\n        font-weight: bold;\n        color: black;\n    }\n    #nonprimary {\n        font-weight: normal;\n        color: white;\n    }\n\n    /* Show the tooltip text when you mouse over the tooltip container */\n    .djtooltip:hover .djtooltiptext {\n        visibility: visible;\n    }\n</style>\n\n<b>Experiment session</b>\n    <div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n    <table border=\"1\" class=\"Relation\">\n        <thead> <tr style=\"text-align: right;\"> <th> <div class=\"djtooltip\">\n                        <p id=\"primary\">subject_name</p>\n                        <span class=\"djtooltiptext\"></span>\n                    </div></th><th><div class=\"djtooltip\">\n                        <p id=\"primary\">sample_number</p>\n                        <span class=\"djtooltiptext\">sample number</span>\n                    </div></th><th><div class=\"djtooltip\">\n                        <p id=\"primary\">session_date</p>\n                        <span class=\"djtooltiptext\">date of session in YYYY-MM-DD format</span>\n                    </div></th><th><div class=\"djtooltip\">\n                        <p id=\"nonprimary\">stimulations</p>\n                        <span class=\"djtooltiptext\">list of dicts for stimulations</span>\n                    </div> </th> </tr> </thead>\n        <tbody> <tr>  </tr> </tbody>\n    </table>\n\n    <p>Total: 0</p></div>\n\n\n\n\n\n```python\nSession.insert(data, skip_duplicates=True)\n```\n\n\n```python\nSession()\n```\n\n\n\n\n\n\n    <style type=\"text/css\">\n        .Relation{\n            border-collapse:collapse;\n        }\n        .Relation th{\n            background: #A0A0A0; color: #ffffff; padding:4px; border:#f0e0e0 1px solid;\n            font-weight: normal; font-family: monospace; font-size: 100%;\n        }\n        .Relation td{\n            padding:4px; border:#f0e0e0 1px solid; font-size:100%;\n        }\n        .Relation tr:nth-child(odd){\n            background: #ffffff;\n        }\n        .Relation tr:nth-child(even){\n            background: #f3f1ff;\n        }\n        /* Tooltip container */\n        .djtooltip {\n        }\n        /* Tooltip text */\n        .djtooltip .djtooltiptext {\n            visibility: hidden;\n            width: 120px;\n            background-color: black;\n            color: #fff;\n            text-align: center;\n            padding: 5px 0;\n            border-radius: 6px;\n            /* Position the tooltip text - see examples below! */\n            position: absolute;\n            z-index: 1;\n        }\n        #primary {\n            font-weight: bold;\n            color: black;\n        }\n        #nonprimary {\n            font-weight: normal;\n            color: white;\n        }\n\n        /* Show the tooltip text when you mouse over the tooltip container */\n        .djtooltip:hover .djtooltiptext {\n            visibility: visible;\n        }\n    </style>\n\n    <b>Experiment session</b>\n        <div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n        <table border=\"1\" class=\"Relation\">\n            <thead> <tr style=\"text-align: right;\"> <th> <div class=\"djtooltip\">\n                            <p id=\"primary\">subject_name</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"primary\">sample_number</p>\n                            <span class=\"djtooltiptext\">sample number</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"primary\">session_date</p>\n                            <span class=\"djtooltiptext\">date of session in YYYY-MM-DD format</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">stimulations</p>\n                            <span class=\"djtooltiptext\">list of dicts for stimulations</span>\n                        </div> </th> </tr> </thead>\n            <tbody> <tr> <td>KO (chx10)</td>\n<td>1</td>\n<td>2008-06-06</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-06</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-24</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>3</td>\n<td>2008-06-06</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>3</td>\n<td>2008-06-24</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>4</td>\n<td>2008-07-02</td>\n<td>=BLOB=</td></tr><tr><td>KO (pax6)</td>\n<td>1</td>\n<td>2008-05-16</td>\n<td>=BLOB=</td></tr><tr><td>KO (pax6)</td>\n<td>2</td>\n<td>2008-05-16</td>\n<td>=BLOB=</td></tr><tr><td>KO (pax6)</td>\n<td>2</td>\n<td>2008-06-28</td>\n<td>=BLOB=</td></tr><tr><td>KO (pax6)</td>\n<td>3</td>\n<td>2008-06-28</td>\n<td>=BLOB=</td></tr><tr><td>KO bax -/- (chx10)</td>\n<td>1</td>\n<td>2008-07-02</td>\n<td>=BLOB=</td></tr><tr><td>WT (chx10 het)</td>\n<td>1</td>\n<td>2008-06-24</td>\n<td>=BLOB=</td> </tr> </tbody>\n        </table>\n        <p>...</p>\n        <p>Total: 16</p></div>\n\n\n\n\n#### Stimulations Table\n\nThe stimulations will each be stored as a `dj.Computed` table that is dependent on a given `Session`. We use the `dj.Computed` table tier because the imported data comes from the provided pickle file, whose contents are stored in our database.\n\n**Note:** One Session can have zero or more stimulations\n\n\n```python\n@schema\nclass Stimulations(dj.Computed):\n    definition = \"\"\"\n    -> Session\n    stim_id:           int\n    ---\n    fps=0:             float         # frames per second of movie\n    movie=null:        longblob      # numpy array of movie stimulus shaped as (horiz blocks, vert blocks, frames)\n    n_frames:          int           # integer number of frames\n    pixel_size=0:      float         # pixel size on retina in um/pixel\n    stim_height=0:     int           # height of stimulus in pixels\n    stim_width=0:      int           # width of the stimulus in pixels\n    stimulus_onset=0:  float         # onset of stimulus in seconds from start of recording\n    x_block_size=0:    int           # size of horizontal blocks in pixels\n    y_block_size=0:    int           # size of vertical blocks in pixels\n    spikes=null:       longblob      # list of spike times for recorded neurons, each element is np.ndarray()\n    \"\"\"\n    def make(self, key):\n        # load stimulations for a given key as a list\n        stims = (Session() & key).fetch1('stimulations')\n        \n        \n        print('Populating stimulation(s) for subject_name={subject_name}, sample_number={sample_number} on session_date={session_date}'.format(**key))\n        \n        for idx, item in enumerate(stims):\n            key['stim_id'] = idx\n            key['fps'] = item['fps']\n            key['n_frames'] = item['n_frames']\n            key['movie'] = item['movie']\n            key['pixel_size'] = item['pixel_size']\n            key['stim_height'] = item['stim_height']\n            key['stim_width'] = item['stim_width']\n            key['stimulus_onset'] = item['stimulus_onset']\n            key['x_block_size'] = item['x_block_size']\n            key['y_block_size'] = item['y_block_size']\n            key['spikes'] = item['spikes']\n            \n            # Insert key into self\n            self.insert1(key)\n            \n            print('\\tPopulated stimulation {stim_id}'.format(**key))\n```\n\n\n```python\nStimulations.populate()\n```\n\n    Populating stimulation(s) for subject_name=KO (chx10), sample_number=1 on session_date=2008-06-06\n    \tPopulated stimulation 0\n    Populating stimulation(s) for subject_name=KO (chx10), sample_number=2 on session_date=2008-06-06\n    \tPopulated stimulation 0\n    Populating stimulation(s) for subject_name=KO (chx10), sample_number=2 on session_date=2008-06-24\n    \tPopulated stimulation 0\n    Populating stimulation(s) for subject_name=KO (chx10), sample_number=3 on session_date=2008-06-06\n    \tPopulated stimulation 0\n    Populating stimulation(s) for subject_name=KO (chx10), sample_number=3 on session_date=2008-06-24\n    \tPopulated stimulation 0\n    Populating stimulation(s) for subject_name=KO (chx10), sample_number=4 on session_date=2008-07-02\n    \tPopulated stimulation 0\n    \tPopulated stimulation 1\n    Populating stimulation(s) for subject_name=KO (pax6), sample_number=1 on session_date=2008-05-16\n    \tPopulated stimulation 0\n    Populating stimulation(s) for subject_name=KO (pax6), sample_number=2 on session_date=2008-05-16\n    \tPopulated stimulation 0\n    Populating stimulation(s) for subject_name=KO (pax6), sample_number=2 on session_date=2008-06-28\n    Populating stimulation(s) for subject_name=KO (pax6), sample_number=3 on session_date=2008-06-28\n    Populating stimulation(s) for subject_name=KO bax -/- (chx10), sample_number=1 on session_date=2008-07-02\n    Populating stimulation(s) for subject_name=WT (chx10 het), sample_number=1 on session_date=2008-06-24\n    \tPopulated stimulation 0\n    Populating stimulation(s) for subject_name=WT (chx10 het), sample_number=4 on session_date=2008-06-28\n    Populating stimulation(s) for subject_name=WT (chx10 het), sample_number=5 on session_date=2008-06-28\n    Populating stimulation(s) for subject_name=WT (pax6 het), sample_number=6 on session_date=2008-06-28\n    Populating stimulation(s) for subject_name=WT (pax6 het), sample_number=7 on session_date=2008-06-28\n\n\n\n```python\nStimulations()\n```\n\n\n\n\n\n\n    <style type=\"text/css\">\n        .Relation{\n            border-collapse:collapse;\n        }\n        .Relation th{\n            background: #A0A0A0; color: #ffffff; padding:4px; border:#f0e0e0 1px solid;\n            font-weight: normal; font-family: monospace; font-size: 100%;\n        }\n        .Relation td{\n            padding:4px; border:#f0e0e0 1px solid; font-size:100%;\n        }\n        .Relation tr:nth-child(odd){\n            background: #ffffff;\n        }\n        .Relation tr:nth-child(even){\n            background: #f3f1ff;\n        }\n        /* Tooltip container */\n        .djtooltip {\n        }\n        /* Tooltip text */\n        .djtooltip .djtooltiptext {\n            visibility: hidden;\n            width: 120px;\n            background-color: black;\n            color: #fff;\n            text-align: center;\n            padding: 5px 0;\n            border-radius: 6px;\n            /* Position the tooltip text - see examples below! */\n            position: absolute;\n            z-index: 1;\n        }\n        #primary {\n            font-weight: bold;\n            color: black;\n        }\n        #nonprimary {\n            font-weight: normal;\n            color: white;\n        }\n\n        /* Show the tooltip text when you mouse over the tooltip container */\n        .djtooltip:hover .djtooltiptext {\n            visibility: visible;\n        }\n    </style>\n\n    <b></b>\n        <div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n        <table border=\"1\" class=\"Relation\">\n            <thead> <tr style=\"text-align: right;\"> <th> <div class=\"djtooltip\">\n                            <p id=\"primary\">subject_name</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"primary\">sample_number</p>\n                            <span class=\"djtooltiptext\">sample number</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"primary\">session_date</p>\n                            <span class=\"djtooltiptext\">date of session in YYYY-MM-DD format</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"primary\">stim_id</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">fps</p>\n                            <span class=\"djtooltiptext\">frames per second of movie</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">movie</p>\n                            <span class=\"djtooltiptext\">numpy array of movie stimulus shaped as (horiz blocks, vert blocks, frames)</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">n_frames</p>\n                            <span class=\"djtooltiptext\">integer number of frames</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">pixel_size</p>\n                            <span class=\"djtooltiptext\">pixel size on retina in um/pixel</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">stim_height</p>\n                            <span class=\"djtooltiptext\">height of stimulus in pixels</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">stim_width</p>\n                            <span class=\"djtooltiptext\">width of the stimulus in pixels</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">stimulus_onset</p>\n                            <span class=\"djtooltiptext\">onset of stimulus in seconds from start of recording</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">x_block_size</p>\n                            <span class=\"djtooltiptext\">size of horizontal blocks in pixels</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">y_block_size</p>\n                            <span class=\"djtooltiptext\">size of vertical blocks in pixels</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">spikes</p>\n                            <span class=\"djtooltiptext\">list of spike times for recorded neurons, each element is np.ndarray()</span>\n                        </div> </th> </tr> </thead>\n            <tbody> <tr> <td>KO (chx10)</td>\n<td>1</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>59.9815</td>\n<td>=BLOB=</td>\n<td>3823</td>\n<td>8.3</td>\n<td>480</td>\n<td>640</td>\n<td>1.65657</td>\n<td>1</td>\n<td>480</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>59.9815</td>\n<td>=BLOB=</td>\n<td>4377</td>\n<td>8.3</td>\n<td>480</td>\n<td>640</td>\n<td>1.77267</td>\n<td>640</td>\n<td>1</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-24</td>\n<td>0</td>\n<td>59.9815</td>\n<td>=BLOB=</td>\n<td>4125</td>\n<td>8.3</td>\n<td>300</td>\n<td>640</td>\n<td>1.22127</td>\n<td>10</td>\n<td>10</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>3</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>59.9815</td>\n<td>=BLOB=</td>\n<td>4241</td>\n<td>8.3</td>\n<td>480</td>\n<td>640</td>\n<td>1.00227</td>\n<td>10</td>\n<td>10</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>3</td>\n<td>2008-06-24</td>\n<td>0</td>\n<td>59.9816</td>\n<td>=BLOB=</td>\n<td>4348</td>\n<td>8.3</td>\n<td>480</td>\n<td>640</td>\n<td>1.05317</td>\n<td>5</td>\n<td>480</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>4</td>\n<td>2008-07-02</td>\n<td>0</td>\n<td>60.005</td>\n<td>=BLOB=</td>\n<td>4156</td>\n<td>8.3</td>\n<td>480</td>\n<td>640</td>\n<td>1.3066</td>\n<td>2</td>\n<td>480</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>4</td>\n<td>2008-07-02</td>\n<td>1</td>\n<td>29.9908</td>\n<td>=BLOB=</td>\n<td>3854</td>\n<td>8.3</td>\n<td>320</td>\n<td>640</td>\n<td>1.2634</td>\n<td>8</td>\n<td>8</td>\n<td>=BLOB=</td></tr><tr><td>KO (pax6)</td>\n<td>1</td>\n<td>2008-05-16</td>\n<td>0</td>\n<td>59.9816</td>\n<td>=BLOB=</td>\n<td>4325</td>\n<td>8.3</td>\n<td>480</td>\n<td>640</td>\n<td>1.2488</td>\n<td>10</td>\n<td>10</td>\n<td>=BLOB=</td></tr><tr><td>KO (pax6)</td>\n<td>2</td>\n<td>2008-05-16</td>\n<td>0</td>\n<td>59.9816</td>\n<td>=BLOB=</td>\n<td>4331</td>\n<td>8.3</td>\n<td>480</td>\n<td>640</td>\n<td>1.0617</td>\n<td>1</td>\n<td>480</td>\n<td>=BLOB=</td></tr><tr><td>WT (chx10 het)</td>\n<td>1</td>\n<td>2008-06-24</td>\n<td>0</td>\n<td>59.9815</td>\n<td>=BLOB=</td>\n<td>3938</td>\n<td>8.3</td>\n<td>480</td>\n<td>640</td>\n<td>6.65177</td>\n<td>640</td>\n<td>2</td>\n<td>=BLOB=</td> </tr> </tbody>\n        </table>\n\n        <p>Total: 10</p></div>\n\n\n\n\n\n```python\ndj.Diagram(schema)\n```\n\n    /home/rohit/miniconda3/envs/datajoint_interview/lib/python3.8/inspect.py:350: FutureWarning: pandas.Float64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.\n      value = getattr(object, key)\n    /home/rohit/miniconda3/envs/datajoint_interview/lib/python3.8/inspect.py:350: FutureWarning: pandas.Int64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.\n      value = getattr(object, key)\n    /home/rohit/miniconda3/envs/datajoint_interview/lib/python3.8/inspect.py:350: FutureWarning: pandas.UInt64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.\n      value = getattr(object, key)\n\n\n\n\n\n    \n\n    \n\n\n\n### Spike trains table\n\nThe next entity we care about are the spike trains associated with Stimulation. We can use another `dj.Computed` table here.\n\nEach stimulation's `spikes` attribute contains a list of numpy arrays for the spike times (in seconds) for each neuron, of which there can be one or more.\n\n**Note:** The spike times are from the start of data recording, so we want to subtract the `stimulus_onset` attribute from all the spike times to get the spike times after the stimulus.\n\n\n```python\nkeys = Stimulations.fetch('KEY')\n```\n\n\n```python\n(Stimulations() & keys[2]).fetch1('spikes')[25].reshape(-1) - (Stimulations() & keys[2]).fetch1('stimulus_onset')\n```\n\n\n\n\n    array([ 0.14363,  0.40973,  0.41673,  0.42453,  0.43683,  0.47323,\n            1.81403, 24.24853, 30.38023, 35.30763, 35.31733, 35.33163,\n           41.05963, 42.10843, 42.11673, 42.13593, 45.36173, 45.37083,\n           45.40223, 56.59663, 56.60973, 56.62823, 67.61533, 67.62493,\n           67.63453])\n\n\n\nThe above is just an example of what some adjusted spike times look like (corrected for movie stimulus onset) for neuron 25 of a particular stimulation experiment.\n\n\n```python\n(Stimulations() & keys[2]).fetch1('movie').shape\n```\n\n\n\n\n    (64, 30, 4125)\n\n\n\n\n```python\n@schema\nclass SpikeTrain(dj.Computed):\n    definition = \"\"\"\n    -> Stimulations\n    neuron_id:           int\n    ---\n    spike_times=null:    longblob      # numpy array of spike times AFTER stimulus onset\n    \"\"\"\n    def make(self, key):\n        # load stimulations for a given key as a list\n        spike_trains = (Stimulations() & key).fetch1('spikes')\n        \n        \n        print('Populating spike train(s) for subject_name={subject_name}, sample_number={sample_number} on session_date={session_date} for stim_id={stim_id}'.format(**key))\n        \n        for idx, item in enumerate(spike_trains):\n            key['neuron_id'] = idx\n            \n            # subtract onset time from spike times to see the spike times in relation to the stimulus\n            key['spike_times'] = item.reshape(-1,) - (Stimulations() & key).fetch1('stimulus_onset')\n            \n            # Insert key into self\n            self.insert1(key)\n            \n            print('\\tPopulated spike times for neuron {neuron_id}'.format(**key))\n```\n\n\n```python\nSpikeTrain.populate()\n```\n\n    Populating spike train(s) for subject_name=KO (chx10), sample_number=1 on session_date=2008-06-06 for stim_id=0\n    \tPopulated spike times for neuron 0\n    \tPopulated spike times for neuron 1\n    \tPopulated spike times for neuron 2\n    \tPopulated spike times for neuron 3\n    Populating spike train(s) for subject_name=KO (chx10), sample_number=2 on session_date=2008-06-06 for stim_id=0\n    \tPopulated spike times for neuron 0\n    \tPopulated spike times for neuron 1\n    \tPopulated spike times for neuron 2\n    \tPopulated spike times for neuron 3\n    \tPopulated spike times for neuron 4\n    \tPopulated spike times for neuron 5\n    Populating spike train(s) for subject_name=KO (chx10), sample_number=2 on session_date=2008-06-24 for stim_id=0\n    \tPopulated spike times for neuron 0\n    \tPopulated spike times for neuron 1\n    \tPopulated spike times for neuron 2\n    \tPopulated spike times for neuron 3\n    \tPopulated spike times for neuron 4\n    \tPopulated spike times for neuron 5\n    \tPopulated spike times for neuron 6\n    \tPopulated spike times for neuron 7\n    \tPopulated spike times for neuron 8\n    \tPopulated spike times for neuron 9\n    \tPopulated spike times for neuron 10\n    \tPopulated spike times for neuron 11\n    \tPopulated spike times for neuron 12\n    \tPopulated spike times for neuron 13\n    \tPopulated spike times for neuron 14\n    \tPopulated spike times for neuron 15\n    \tPopulated spike times for neuron 16\n    \tPopulated spike times for neuron 17\n    \tPopulated spike times for neuron 18\n    \tPopulated spike times for neuron 19\n    \tPopulated spike times for neuron 20\n    \tPopulated spike times for neuron 21\n    \tPopulated spike times for neuron 22\n    \tPopulated spike times for neuron 23\n    \tPopulated spike times for neuron 24\n    \tPopulated spike times for neuron 25\n    Populating spike train(s) for subject_name=KO (chx10), sample_number=3 on session_date=2008-06-06 for stim_id=0\n    \tPopulated spike times for neuron 0\n    Populating spike train(s) for subject_name=KO (chx10), sample_number=3 on session_date=2008-06-24 for stim_id=0\n    \tPopulated spike times for neuron 0\n    \tPopulated spike times for neuron 1\n    \tPopulated spike times for neuron 2\n    \tPopulated spike times for neuron 3\n    \tPopulated spike times for neuron 4\n    \tPopulated spike times for neuron 5\n    \tPopulated spike times for neuron 6\n    \tPopulated spike times for neuron 7\n    \tPopulated spike times for neuron 8\n    \tPopulated spike times for neuron 9\n    \tPopulated spike times for neuron 10\n    \tPopulated spike times for neuron 11\n    \tPopulated spike times for neuron 12\n    \tPopulated spike times for neuron 13\n    \tPopulated spike times for neuron 14\n    \tPopulated spike times for neuron 15\n    \tPopulated spike times for neuron 16\n    \tPopulated spike times for neuron 17\n    \tPopulated spike times for neuron 18\n    \tPopulated spike times for neuron 19\n    \tPopulated spike times for neuron 20\n    \tPopulated spike times for neuron 21\n    \tPopulated spike times for neuron 22\n    \tPopulated spike times for neuron 23\n    \tPopulated spike times for neuron 24\n    \tPopulated spike times for neuron 25\n    \tPopulated spike times for neuron 26\n    \tPopulated spike times for neuron 27\n    \tPopulated spike times for neuron 28\n    \tPopulated spike times for neuron 29\n    \tPopulated spike times for neuron 30\n    \tPopulated spike times for neuron 31\n    \tPopulated spike times for neuron 32\n    \tPopulated spike times for neuron 33\n    \tPopulated spike times for neuron 34\n    \tPopulated spike times for neuron 35\n    \tPopulated spike times for neuron 36\n    \tPopulated spike times for neuron 37\n    Populating spike train(s) for subject_name=KO (chx10), sample_number=4 on session_date=2008-07-02 for stim_id=0\n    \tPopulated spike times for neuron 0\n    \tPopulated spike times for neuron 1\n    \tPopulated spike times for neuron 2\n    \tPopulated spike times for neuron 3\n    \tPopulated spike times for neuron 4\n    \tPopulated spike times for neuron 5\n    \tPopulated spike times for neuron 6\n    \tPopulated spike times for neuron 7\n    \tPopulated spike times for neuron 8\n    \tPopulated spike times for neuron 9\n    \tPopulated spike times for neuron 10\n    \tPopulated spike times for neuron 11\n    Populating spike train(s) for subject_name=KO (chx10), sample_number=4 on session_date=2008-07-02 for stim_id=1\n    \tPopulated spike times for neuron 0\n    \tPopulated spike times for neuron 1\n    \tPopulated spike times for neuron 2\n    \tPopulated spike times for neuron 3\n    \tPopulated spike times for neuron 4\n    \tPopulated spike times for neuron 5\n    \tPopulated spike times for neuron 6\n    \tPopulated spike times for neuron 7\n    \tPopulated spike times for neuron 8\n    \tPopulated spike times for neuron 9\n    \tPopulated spike times for neuron 10\n    \tPopulated spike times for neuron 11\n    Populating spike train(s) for subject_name=KO (pax6), sample_number=1 on session_date=2008-05-16 for stim_id=0\n    \tPopulated spike times for neuron 0\n    \tPopulated spike times for neuron 1\n    \tPopulated spike times for neuron 2\n    \tPopulated spike times for neuron 3\n    \tPopulated spike times for neuron 4\n    \tPopulated spike times for neuron 5\n    \tPopulated spike times for neuron 6\n    Populating spike train(s) for subject_name=KO (pax6), sample_number=2 on session_date=2008-05-16 for stim_id=0\n    \tPopulated spike times for neuron 0\n    \tPopulated spike times for neuron 1\n    \tPopulated spike times for neuron 2\n    \tPopulated spike times for neuron 3\n    \tPopulated spike times for neuron 4\n    \tPopulated spike times for neuron 5\n    \tPopulated spike times for neuron 6\n    \tPopulated spike times for neuron 7\n    \tPopulated spike times for neuron 8\n    \tPopulated spike times for neuron 9\n    \tPopulated spike times for neuron 10\n    \tPopulated spike times for neuron 11\n    \tPopulated spike times for neuron 12\n    \tPopulated spike times for neuron 13\n    \tPopulated spike times for neuron 14\n    \tPopulated spike times for neuron 15\n    \tPopulated spike times for neuron 16\n    \tPopulated spike times for neuron 17\n    \tPopulated spike times for neuron 18\n    \tPopulated spike times for neuron 19\n    \tPopulated spike times for neuron 20\n    \tPopulated spike times for neuron 21\n    \tPopulated spike times for neuron 22\n    \tPopulated spike times for neuron 23\n    \tPopulated spike times for neuron 24\n    \tPopulated spike times for neuron 25\n    \tPopulated spike times for neuron 26\n    \tPopulated spike times for neuron 27\n    \tPopulated spike times for neuron 28\n    \tPopulated spike times for neuron 29\n    \tPopulated spike times for neuron 30\n    \tPopulated spike times for neuron 31\n    \tPopulated spike times for neuron 32\n    \tPopulated spike times for neuron 33\n    Populating spike train(s) for subject_name=WT (chx10 het), sample_number=1 on session_date=2008-06-24 for stim_id=0\n    \tPopulated spike times for neuron 0\n    \tPopulated spike times for neuron 1\n    \tPopulated spike times for neuron 2\n    \tPopulated spike times for neuron 3\n    \tPopulated spike times for neuron 4\n    \tPopulated spike times for neuron 5\n    \tPopulated spike times for neuron 6\n    \tPopulated spike times for neuron 7\n    \tPopulated spike times for neuron 8\n    \tPopulated spike times for neuron 9\n    \tPopulated spike times for neuron 10\n    \tPopulated spike times for neuron 11\n    \tPopulated spike times for neuron 12\n    \tPopulated spike times for neuron 13\n    \tPopulated spike times for neuron 14\n    \tPopulated spike times for neuron 15\n    \tPopulated spike times for neuron 16\n    \tPopulated spike times for neuron 17\n    \tPopulated spike times for neuron 18\n    \tPopulated spike times for neuron 19\n    \tPopulated spike times for neuron 20\n    \tPopulated spike times for neuron 21\n    \tPopulated spike times for neuron 22\n    \tPopulated spike times for neuron 23\n    \tPopulated spike times for neuron 24\n    \tPopulated spike times for neuron 25\n    \tPopulated spike times for neuron 26\n    \tPopulated spike times for neuron 27\n    \tPopulated spike times for neuron 28\n    \tPopulated spike times for neuron 29\n    \tPopulated spike times for neuron 30\n    \tPopulated spike times for neuron 31\n    \tPopulated spike times for neuron 32\n    \tPopulated spike times for neuron 33\n    \tPopulated spike times for neuron 34\n    \tPopulated spike times for neuron 35\n    \tPopulated spike times for neuron 36\n\n\n\n```python\nSpikeTrain()\n```\n\n\n\n\n\n\n    <style type=\"text/css\">\n        .Relation{\n            border-collapse:collapse;\n        }\n        .Relation th{\n            background: #A0A0A0; color: #ffffff; padding:4px; border:#f0e0e0 1px solid;\n            font-weight: normal; font-family: monospace; font-size: 100%;\n        }\n        .Relation td{\n            padding:4px; border:#f0e0e0 1px solid; font-size:100%;\n        }\n        .Relation tr:nth-child(odd){\n            background: #ffffff;\n        }\n        .Relation tr:nth-child(even){\n            background: #f3f1ff;\n        }\n        /* Tooltip container */\n        .djtooltip {\n        }\n        /* Tooltip text */\n        .djtooltip .djtooltiptext {\n            visibility: hidden;\n            width: 120px;\n            background-color: black;\n            color: #fff;\n            text-align: center;\n            padding: 5px 0;\n            border-radius: 6px;\n            /* Position the tooltip text - see examples below! */\n            position: absolute;\n            z-index: 1;\n        }\n        #primary {\n            font-weight: bold;\n            color: black;\n        }\n        #nonprimary {\n            font-weight: normal;\n            color: white;\n        }\n\n        /* Show the tooltip text when you mouse over the tooltip container */\n        .djtooltip:hover .djtooltiptext {\n            visibility: visible;\n        }\n    </style>\n\n    <b></b>\n        <div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n        <table border=\"1\" class=\"Relation\">\n            <thead> <tr style=\"text-align: right;\"> <th> <div class=\"djtooltip\">\n                            <p id=\"primary\">subject_name</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"primary\">sample_number</p>\n                            <span class=\"djtooltiptext\">sample number</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"primary\">session_date</p>\n                            <span class=\"djtooltiptext\">date of session in YYYY-MM-DD format</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"primary\">stim_id</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"primary\">neuron_id</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">spike_times</p>\n                            <span class=\"djtooltiptext\">numpy array of spike times AFTER stimulus onset</span>\n                        </div> </th> </tr> </thead>\n            <tbody> <tr> <td>KO (chx10)</td>\n<td>1</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>0</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>1</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>1</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>1</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>2</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>1</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>3</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>0</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>1</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>2</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>3</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>4</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>5</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-24</td>\n<td>0</td>\n<td>0</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-24</td>\n<td>0</td>\n<td>1</td>\n<td>=BLOB=</td> </tr> </tbody>\n        </table>\n        <p>...</p>\n        <p>Total: 177</p></div>\n\n\n\n\nWe have $10$ **stimulations** total for our subjects, and $177$ **total neurons** that were stimulated with spike train arrays in this data set.\n\n\n```python\ndj.Diagram(schema)\n```\n\n    /home/rohit/miniconda3/envs/datajoint_interview/lib/python3.8/inspect.py:350: FutureWarning: pandas.Float64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.\n      value = getattr(object, key)\n    /home/rohit/miniconda3/envs/datajoint_interview/lib/python3.8/inspect.py:350: FutureWarning: pandas.Int64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.\n      value = getattr(object, key)\n    /home/rohit/miniconda3/envs/datajoint_interview/lib/python3.8/inspect.py:350: FutureWarning: pandas.UInt64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.\n      value = getattr(object, key)\n\n\n\n\n\n    \n\n    \n\n\n\nThis concludes **Part 1**. \n\n### Part (2) of the challenge - Compute Spatio-Temporal Receptive Fields (STRF)\n\nIn order to compute the STRF, we need to make use of the other attributes in the `Stimulations()` table. \n\n\n```python\nStimulations()\n```\n\n\n\n\n\n\n    <style type=\"text/css\">\n        .Relation{\n            border-collapse:collapse;\n        }\n        .Relation th{\n            background: #A0A0A0; color: #ffffff; padding:4px; border:#f0e0e0 1px solid;\n            font-weight: normal; font-family: monospace; font-size: 100%;\n        }\n        .Relation td{\n            padding:4px; border:#f0e0e0 1px solid; font-size:100%;\n        }\n        .Relation tr:nth-child(odd){\n            background: #ffffff;\n        }\n        .Relation tr:nth-child(even){\n            background: #f3f1ff;\n        }\n        /* Tooltip container */\n        .djtooltip {\n        }\n        /* Tooltip text */\n        .djtooltip .djtooltiptext {\n            visibility: hidden;\n            width: 120px;\n            background-color: black;\n            color: #fff;\n            text-align: center;\n            padding: 5px 0;\n            border-radius: 6px;\n            /* Position the tooltip text - see examples below! */\n            position: absolute;\n            z-index: 1;\n        }\n        #primary {\n            font-weight: bold;\n            color: black;\n        }\n        #nonprimary {\n            font-weight: normal;\n            color: white;\n        }\n\n        /* Show the tooltip text when you mouse over the tooltip container */\n        .djtooltip:hover .djtooltiptext {\n            visibility: visible;\n        }\n    </style>\n\n    <b></b>\n        <div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n        <table border=\"1\" class=\"Relation\">\n            <thead> <tr style=\"text-align: right;\"> <th> <div class=\"djtooltip\">\n                            <p id=\"primary\">subject_name</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"primary\">sample_number</p>\n                            <span class=\"djtooltiptext\">sample number</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"primary\">session_date</p>\n                            <span class=\"djtooltiptext\">date of session in YYYY-MM-DD format</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"primary\">stim_id</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">fps</p>\n                            <span class=\"djtooltiptext\">frames per second of movie</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">movie</p>\n                            <span class=\"djtooltiptext\">numpy array of movie stimulus shaped as (horiz blocks, vert blocks, frames)</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">n_frames</p>\n                            <span class=\"djtooltiptext\">integer number of frames</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">pixel_size</p>\n                            <span class=\"djtooltiptext\">pixel size on retina in um/pixel</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">stim_height</p>\n                            <span class=\"djtooltiptext\">height of stimulus in pixels</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">stim_width</p>\n                            <span class=\"djtooltiptext\">width of the stimulus in pixels</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">stimulus_onset</p>\n                            <span class=\"djtooltiptext\">onset of stimulus in seconds from start of recording</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">x_block_size</p>\n                            <span class=\"djtooltiptext\">size of horizontal blocks in pixels</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">y_block_size</p>\n                            <span class=\"djtooltiptext\">size of vertical blocks in pixels</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">spikes</p>\n                            <span class=\"djtooltiptext\">list of spike times for recorded neurons, each element is np.ndarray()</span>\n                        </div> </th> </tr> </thead>\n            <tbody> <tr> <td>KO (chx10)</td>\n<td>1</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>59.9815</td>\n<td>=BLOB=</td>\n<td>3823</td>\n<td>8.3</td>\n<td>480</td>\n<td>640</td>\n<td>1.65657</td>\n<td>1</td>\n<td>480</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>59.9815</td>\n<td>=BLOB=</td>\n<td>4377</td>\n<td>8.3</td>\n<td>480</td>\n<td>640</td>\n<td>1.77267</td>\n<td>640</td>\n<td>1</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-24</td>\n<td>0</td>\n<td>59.9815</td>\n<td>=BLOB=</td>\n<td>4125</td>\n<td>8.3</td>\n<td>300</td>\n<td>640</td>\n<td>1.22127</td>\n<td>10</td>\n<td>10</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>3</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>59.9815</td>\n<td>=BLOB=</td>\n<td>4241</td>\n<td>8.3</td>\n<td>480</td>\n<td>640</td>\n<td>1.00227</td>\n<td>10</td>\n<td>10</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>3</td>\n<td>2008-06-24</td>\n<td>0</td>\n<td>59.9816</td>\n<td>=BLOB=</td>\n<td>4348</td>\n<td>8.3</td>\n<td>480</td>\n<td>640</td>\n<td>1.05317</td>\n<td>5</td>\n<td>480</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>4</td>\n<td>2008-07-02</td>\n<td>0</td>\n<td>60.005</td>\n<td>=BLOB=</td>\n<td>4156</td>\n<td>8.3</td>\n<td>480</td>\n<td>640</td>\n<td>1.3066</td>\n<td>2</td>\n<td>480</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>4</td>\n<td>2008-07-02</td>\n<td>1</td>\n<td>29.9908</td>\n<td>=BLOB=</td>\n<td>3854</td>\n<td>8.3</td>\n<td>320</td>\n<td>640</td>\n<td>1.2634</td>\n<td>8</td>\n<td>8</td>\n<td>=BLOB=</td></tr><tr><td>KO (pax6)</td>\n<td>1</td>\n<td>2008-05-16</td>\n<td>0</td>\n<td>59.9816</td>\n<td>=BLOB=</td>\n<td>4325</td>\n<td>8.3</td>\n<td>480</td>\n<td>640</td>\n<td>1.2488</td>\n<td>10</td>\n<td>10</td>\n<td>=BLOB=</td></tr><tr><td>KO (pax6)</td>\n<td>2</td>\n<td>2008-05-16</td>\n<td>0</td>\n<td>59.9816</td>\n<td>=BLOB=</td>\n<td>4331</td>\n<td>8.3</td>\n<td>480</td>\n<td>640</td>\n<td>1.0617</td>\n<td>1</td>\n<td>480</td>\n<td>=BLOB=</td></tr><tr><td>WT (chx10 het)</td>\n<td>1</td>\n<td>2008-06-24</td>\n<td>0</td>\n<td>59.9815</td>\n<td>=BLOB=</td>\n<td>3938</td>\n<td>8.3</td>\n<td>480</td>\n<td>640</td>\n<td>6.65177</td>\n<td>640</td>\n<td>2</td>\n<td>=BLOB=</td> </tr> </tbody>\n        </table>\n\n        <p>Total: 10</p></div>\n\n\n\n\nThe computations will then all be done on each `spike_times` entry in `SpikeTrain()`.\n\n\n```python\nSpikeTrain()\n```\n\n\n\n\n\n\n    <style type=\"text/css\">\n        .Relation{\n            border-collapse:collapse;\n        }\n        .Relation th{\n            background: #A0A0A0; color: #ffffff; padding:4px; border:#f0e0e0 1px solid;\n            font-weight: normal; font-family: monospace; font-size: 100%;\n        }\n        .Relation td{\n            padding:4px; border:#f0e0e0 1px solid; font-size:100%;\n        }\n        .Relation tr:nth-child(odd){\n            background: #ffffff;\n        }\n        .Relation tr:nth-child(even){\n            background: #f3f1ff;\n        }\n        /* Tooltip container */\n        .djtooltip {\n        }\n        /* Tooltip text */\n        .djtooltip .djtooltiptext {\n            visibility: hidden;\n            width: 120px;\n            background-color: black;\n            color: #fff;\n            text-align: center;\n            padding: 5px 0;\n            border-radius: 6px;\n            /* Position the tooltip text - see examples below! */\n            position: absolute;\n            z-index: 1;\n        }\n        #primary {\n            font-weight: bold;\n            color: black;\n        }\n        #nonprimary {\n            font-weight: normal;\n            color: white;\n        }\n\n        /* Show the tooltip text when you mouse over the tooltip container */\n        .djtooltip:hover .djtooltiptext {\n            visibility: visible;\n        }\n    </style>\n\n    <b></b>\n        <div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n        <table border=\"1\" class=\"Relation\">\n            <thead> <tr style=\"text-align: right;\"> <th> <div class=\"djtooltip\">\n                            <p id=\"primary\">subject_name</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"primary\">sample_number</p>\n                            <span class=\"djtooltiptext\">sample number</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"primary\">session_date</p>\n                            <span class=\"djtooltiptext\">date of session in YYYY-MM-DD format</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"primary\">stim_id</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"primary\">neuron_id</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">spike_times</p>\n                            <span class=\"djtooltiptext\">numpy array of spike times AFTER stimulus onset</span>\n                        </div> </th> </tr> </thead>\n            <tbody> <tr> <td>KO (chx10)</td>\n<td>1</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>0</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>1</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>1</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>1</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>2</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>1</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>3</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>0</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>1</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>2</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>3</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>4</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>5</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-24</td>\n<td>0</td>\n<td>0</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-24</td>\n<td>0</td>\n<td>1</td>\n<td>=BLOB=</td> </tr> </tbody>\n        </table>\n        <p>...</p>\n        <p>Total: 177</p></div>\n\n\n\n\nThe **Spike-triggered Average (STA)** is defined (on Wikipedia) as:\n> Mathematically, the STA is the average stimulus preceding a spike. To compute the STA, the stimulus in the time window preceding each spike is extracted, and the resulting (spike-triggered) stimuli are averaged.\n\nIn our case, we are told our stimulus vector for the $i$'th time bin, $\\mathbf{x_i}$, is *white noise* , so the Standard STA definition on Wikipedia should do.\n\nThis is:\n\n\\begin{equation}\n    \\mathrm{STA} = \\frac{1}{n_{sp}} \\sum_{i=1}^{T}{y_i \\mathbf{x_i}},\n\\end{equation}\nwhere $T$ is the total number of time bins, $y_i$ is the number of spikes in bin $i$, and $n_{sp} = \\sum y_i$ is the total number of spikes.\n\nIn matrix form, we can let the rows of a matrix $X$ be equal to $\\mathbf{x_i}^T$ and a column vector $\\mathbf{y}$ whose $i$'th element can be equal to $y_i$. Then we have\n\n\\begin{equation}\n    \\mathrm{STA} = \\frac{1}{n_{sp}} X^T \\mathbf{y}\n\\end{equation}\n\nIn order to do this for our experiment, we need to determine a time bin/window size for each recording, which we can do with some trial and error for now.\n\nWe have to consider the following in our experiment:\n * Time bin window size in seconds (a parameter we can set with a `Lookup` table)\n * Segment of the movie to match this time in seconds to determine the size of $\\mathbf{x_i}$.\n   * We may need to use the `n_frames`, `framerate`, `x_block_size`, `y_block_size`, and the `movie` array to determine these\n * Count the number of spikes in each time bin and total number of spikes to determine $y_i$ and $n_{sp}$\n \n\n\n#### UPDATE: STRF Computation\n\nThis was not a part of my initial submission, but I have subsequently better understood what the STRF is and how it is computed. \n\nWe are able to compute the STA for a given neuron using the formulation above. For a given window of stimulus $\\mathbf{x_i}$, we can define the STRF computation as follows:\n\n\\begin{equation}\n    \\mathrm{STRF}_{\\tau_j} = \\frac{1}{n_{sp}} \\sum_{i=1}^{T}{y_{i + \\tau_j} \\mathbf{x_i}}, \\quad j = 1, \\ldots, K,\n\\end{equation}\n\nWhere $\\tau_1, \\ldots , \\tau_K$ represent various delays in number of bins. \n\nWe can say that the STRF is the STA computed to view the neuronal response for a stimulus $\\mathbf{x_i}$ at $K$ different time bins following that stimulus\n\n### Just playing around trying to understand how to compute STA with a single example with a fixed window size\n\n\n```python\ndef count_spikes_in_bin(times, spikes):\n    start = times[0]\n    stop = times[-1]\n    mask = np.logical_and(spikes >= start, spikes < stop) \n    return len(spikes[mask])\n```\n\nLook at a random example:\n\n\n```python\nkeys = SpikeTrain.fetch('KEY')\n\nwindow_size = 15\n\nmovie = (Stimulations() & keys[2]).fetch1('movie')\nmovie_dims = movie.shape\n\nn_fr = movie_dims[2]\n\nfr = (Stimulations() & keys[2]).fetch1('fps')\n\nx_size = (Stimulations() & keys[2]).fetch1('x_block_size')\nx_dim = (Stimulations() & keys[2]).fetch1('stim_width')\n\ny_size = (Stimulations() & keys[2]).fetch1('y_block_size')\ny_dim = (Stimulations() & keys[2]).fetch1('stim_height')\n\nprint(f'Movie has dimensions {movie_dims}')\nprint(f'FPS is {fr}')\nprint(f'Video dimensions are {x_dim} x {y_dim} with {movie_dims[2]} frames')\nprint(f'x_block_size is {x_size}')\nprint(f'y_block_size is {y_size}')\n\n\n```\n\n    Movie has dimensions (640, 1, 3823)\n    FPS is 59.9815\n    Video dimensions are 640 x 480 with 3823 frames\n    x_block_size is 1\n    y_block_size is 480\n\n\nWe want to:\n * Create each $\\mathbf{x_i}$ as a window of a particular size (15 frames here) of the movie. \n   * In this example, each $\\mathbf{x_i}$ should have dimensions (640, 1, 15)\n   * Windowed movie array should now have dimenions (640, 1, 255, 15), where 255 is the number of bins in this example\n\n\n```python\n# Padding so I can reshape the index mask to the correct size given a particular frame count.\nnum_to_pad = window_size - n_fr % window_size  # maximum value padding amount\nmask_indices = np.pad(np.arange(n_fr), (0, num_to_pad), mode='maximum').reshape(-1, window_size) \n\nspikes = (SpikeTrain() & keys[2]).fetch1('spike_times')\n\n# create array of frame times\ntimes = np.arange(0, n_fr) / fr\n\nfr_times_windows = times[mask_indices]\n\n\nspike_counts = np.apply_along_axis(lambda x: count_spikes_in_bin(x, spikes), axis=1, arr=fr_times_windows)\n\nprint(f'We have {fr_times_windows.shape[0]} bins of size {fr_times_windows.shape[1]}')\nprint('Sum of spike counts across all bins:', np.sum(spike_counts))\nprint('Length of original spike train array:', len(spikes))\n```\n\n    We have 255 bins of size 15\n    Sum of spike counts across all bins: 157\n    Length of original spike train array: 168\n\n\nIt looks like some spikes are being missed by my method, but the number gets closer as the window size increases based on trial/error experimentation.\n\n\n```python\nmask_indices\n```\n\n\n\n\n    array([[   0,    1,    2, ...,   12,   13,   14],\n           [  15,   16,   17, ...,   27,   28,   29],\n           [  30,   31,   32, ...,   42,   43,   44],\n           ...,\n           [3780, 3781, 3782, ..., 3792, 3793, 3794],\n           [3795, 3796, 3797, ..., 3807, 3808, 3809],\n           [3810, 3811, 3812, ..., 3822, 3822, 3822]])\n\n\n\n\n```python\nwindowed_movie = movie[:, :, mask_indices]\n\nwindowed_movie[:, :, 0].shape\n```\n\n\n\n\n    (640, 1, 15)\n\n\n\n### Intuition\nAbove we see the shape for the first window of 15 frames. This is essentially the first stimulus bin $\\mathbf{x_0}$, and the next row would be $\\mathbf{x_1}$, etc.\n\n\nCompute an average stimulus\n\n\n```python\naverage_movie = np.mean(windowed_movie, axis=3)\n```\n\n\n```python\naverage_movie.shape\n```\n\n\n\n\n    (640, 1, 255)\n\n\n\nThis is the average movie stimulus for each of the 255 bins, i.e. $\\mathbf{x_1}$ to $\\mathbf{x_{255}}$\n\n\n```python\n(average_movie @ spike_counts / np.sum(spike_counts)).shape\n```\n\n\n\n\n    (640, 1)\n\n\n\nI believe this is the **STA for a given neuron** with a defined window size and **no delay, $\\tau = 0$**.\n\nWe can **shift** the $y_i$ array of spike counts and repeat to get the STA when the neuronal output is delayed by $\\tau$ bins.\n\nNeed to reshape to actual image size using block size for visualizing.\n\n\n```python\ntau = 3\nshifted_counts = np.roll(spike_counts, -1 * tau)\nshifted_counts[-1 * tau:] = 0\n\nprint(spike_counts)\nprint('\\n')\nprint(shifted_counts)\n```\n\n    [4 4 1 4 1 4 0 2 2 2 3 1 0 4 1 3 1 0 2 0 1 2 1 0 2 2 1 1 1 2 1 1 1 1 2 0 1\n     2 1 1 1 0 0 1 2 0 2 0 1 0 0 1 0 1 2 0 0 1 0 0 2 2 0 1 0 0 0 2 1 0 1 2 0 1\n     1 0 0 1 0 0 1 0 0 0 0 1 0 2 0 0 0 0 0 0 1 0 0 3 0 0 1 0 0 0 1 3 0 0 1 0 1\n     0 1 0 0 1 0 0 2 0 1 0 0 1 0 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 3 0 1 0 2 1 0 0\n     0 2 0 1 0 2 1 0 0 0 0 0 0 0 0 0 0 0 2 0 1 0 1 1 1 0 1 0 1 0 0 0 0 0 0 1 0\n     0 0 1 0 0 0 2 0 1 0 1 0 0 0 4 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0\n     0 0 2 0 0 2 0 0 0 0 0 0 0 1 0 1 0 2 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0]\n    \n    \n    [4 1 4 0 2 2 2 3 1 0 4 1 3 1 0 2 0 1 2 1 0 2 2 1 1 1 2 1 1 1 1 2 0 1 2 1 1\n     1 0 0 1 2 0 2 0 1 0 0 1 0 1 2 0 0 1 0 0 2 2 0 1 0 0 0 2 1 0 1 2 0 1 1 0 0\n     1 0 0 1 0 0 0 0 1 0 2 0 0 0 0 0 0 1 0 0 3 0 0 1 0 0 0 1 3 0 0 1 0 1 0 1 0\n     0 1 0 0 2 0 1 0 0 1 0 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 3 0 1 0 2 1 0 0 0 2 0\n     1 0 2 1 0 0 0 0 0 0 0 0 0 0 0 2 0 1 0 1 1 1 0 1 0 1 0 0 0 0 0 0 1 0 0 0 1\n     0 0 0 2 0 1 0 1 0 0 0 4 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 2\n     0 0 2 0 0 0 0 0 0 0 1 0 1 0 2 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0]\n\n\n### Back to defining schema\n\n\n```python\n# Define lookup table for STA parameters\n@schema\nclass STRF_Param(dj.Lookup):\n    definition = \"\"\"\n    strf_param_id:          int                # unique id for STRF parameter set\n    ---\n    bin_size=1:             float              # time window bin size in seconds\n    tau=1:                  int                # of bins to jump for each consecutive delay\n    \"\"\"\n```\n\n\n```python\n# Try lots of window sizes in seconds\nSTRF_Param.insert([(0, 1, 5)\n                  ],\n                 )\n```\n\n\n```python\nSTRF_Param.insert([(1, 0.5, 10), \n                   (2, 2.0, 2)\n                  ],\n                 )\n```\n\n\n```python\nSTRF_Param()\n```\n\n\n\n\n\n\n    <style type=\"text/css\">\n        .Relation{\n            border-collapse:collapse;\n        }\n        .Relation th{\n            background: #A0A0A0; color: #ffffff; padding:4px; border:#f0e0e0 1px solid;\n            font-weight: normal; font-family: monospace; font-size: 100%;\n        }\n        .Relation td{\n            padding:4px; border:#f0e0e0 1px solid; font-size:100%;\n        }\n        .Relation tr:nth-child(odd){\n            background: #ffffff;\n        }\n        .Relation tr:nth-child(even){\n            background: #f3f1ff;\n        }\n        /* Tooltip container */\n        .djtooltip {\n        }\n        /* Tooltip text */\n        .djtooltip .djtooltiptext {\n            visibility: hidden;\n            width: 120px;\n            background-color: black;\n            color: #fff;\n            text-align: center;\n            padding: 5px 0;\n            border-radius: 6px;\n            /* Position the tooltip text - see examples below! */\n            position: absolute;\n            z-index: 1;\n        }\n        #primary {\n            font-weight: bold;\n            color: black;\n        }\n        #nonprimary {\n            font-weight: normal;\n            color: white;\n        }\n\n        /* Show the tooltip text when you mouse over the tooltip container */\n        .djtooltip:hover .djtooltiptext {\n            visibility: visible;\n        }\n    </style>\n\n    <b></b>\n        <div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n        <table border=\"1\" class=\"Relation\">\n            <thead> <tr style=\"text-align: right;\"> <th> <div class=\"djtooltip\">\n                            <p id=\"primary\">strf_param_id</p>\n                            <span class=\"djtooltiptext\">unique id for STRF parameter set</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">bin_size</p>\n                            <span class=\"djtooltiptext\">time window bin size in seconds</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">tau</p>\n                            <span class=\"djtooltiptext\">of bins to jump for each consecutive delay</span>\n                        </div> </th> </tr> </thead>\n            <tbody> <tr> <td>0</td>\n<td>1.0</td>\n<td>5</td></tr><tr><td>1</td>\n<td>0.5</td>\n<td>10</td></tr><tr><td>2</td>\n<td>2.0</td>\n<td>2</td> </tr> </tbody>\n        </table>\n\n        <p>Total: 3</p></div>\n\n\n\n\n\n```python\n@schema\nclass STRF_Compute(dj.Computed):\n    definition = \"\"\"\n    -> SpikeTrain\n    -> STRF_Param\n    ---\n    n_spikes = null:          longblob     # array for number of spikes in each bin\n    srtf_values = null:       longblob    # STA at each time delay\n    \"\"\"\n\n    \n    def make(self, key):\n        window_seconds = (STRF_Param() & key).fetch1('bin_size')  # window/bin size in seconds\n        tau = (STRF_Param() & key).fetch1('tau')  # incremental number of bins to delay\n        \n        # Next, we want to slide window over movie and spike train\n        \n        # Start by extracting the relevant parameters\n        x_blocks = (Stimulations() & key).fetch1('x_block_size')\n        y_blocks = (Stimulations() & key).fetch1('y_block_size')\n        fr = (Stimulations() & key).fetch1('fps')\n        n_fr = (Stimulations() & key).fetch1('n_frames')\n        x_dim = (Stimulations() & key).fetch1('stim_width')\n        y_dim = (Stimulations() & key).fetch1('stim_height')\n        spikes = (SpikeTrain() & key).fetch1('spike_times')\n        movie = (Stimulations() & key).fetch1('movie')\n        \n        \n        # create a frame time array (which is found by dividing frame_number / framerate)\n        frames = np.arange(0, n_fr)\n        fr_times = frames / fr\n        \n        # Create sliding window mask for looking at subarrays of this fr_times array\n        # compute best window size:\n        window_size = round(window_seconds * fr)\n        \n        # Padding so I can reshape the index mask to the correct size given a particular frame count.\n        num_to_pad = window_size - n_fr % window_size  # maximum value padding amount\n        mask_indices = np.pad(np.arange(n_fr), (0, num_to_pad), mode='maximum').reshape(-1, window_size) \n        \n        # mask frame times with sliding windows as rows\n        fr_times_windows = fr_times[mask_indices]\n        \n        # Create spike_counts array, which is essentially the vector y in the definition above (spike counts for each bin)\n        # Should replace this with a vectorized function, but I was running into some error that I can debug later to optimize, since this is slow.\n        print('Populating spike counts for subject {subject_name}, sample {sample_number} on {session_date} with stim_id={stim_id} for neuron {neuron_id}'.format(**key))\n        spike_counts = np.apply_along_axis(lambda x: count_spikes_in_bin(x, spikes), axis=1, arr=fr_times_windows)\n        tot_spikes = np.sum(spike_counts)\n        print(f'\\tFound {tot_spikes} total spikes with window size of {window_seconds} seconds.')\n        \n        key['n_spikes'] = spike_counts\n        \n        # Compute STA for each of the windows with delays incrementing by tau bins\n        windowed_movie = movie[:, :, mask_indices]\n        average_movie = np.mean(windowed_movie, axis=3)\n        \n        shifted_spike_counts = spike_counts.copy()\n        \n        # Do initial case with no delay\n        sta_0 = ((average_movie @ spike_counts) / tot_spikes)\n        sta_0 = np.repeat(sta_0, repeats=x_blocks, axis=0)\n        sta_0 = np.repeat(sta_0, repeats=y_blocks, axis=1)\n        \n        srtf = [(0, sta_0)]\n        \n        for t in range(tau, len(spike_counts), tau):\n            shifted_spike_counts = np.roll(shifted_spike_counts, -1 * t)\n            shifted_spike_counts[-t:] = 0  # set end of array by shift amount to 0\n            \n            if np.max(shifted_spike_counts) == 0:\n                break\n            \n            sta_t = ((average_movie @ shifted_spike_counts) / tot_spikes)\n            \n            # probably not efficient for storage but doing this temporarily to see if it works\n            sta_t = np.repeat(sta_t, repeats=x_blocks, axis=0)\n            sta_t = np.repeat(sta_t, repeats=y_blocks, axis=1)\n            \n            srtf.append((t, sta_t))\n\n        key['srtf_values'] = srtf\n        \n        self.insert1(key)\n```\n\n\n```python\ndj.Diagram(schema)\n```\n\n    /home/rohit/miniconda3/envs/datajoint_interview/lib/python3.8/inspect.py:350: FutureWarning: pandas.Float64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.\n      value = getattr(object, key)\n    /home/rohit/miniconda3/envs/datajoint_interview/lib/python3.8/inspect.py:350: FutureWarning: pandas.Int64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.\n      value = getattr(object, key)\n    /home/rohit/miniconda3/envs/datajoint_interview/lib/python3.8/inspect.py:350: FutureWarning: pandas.UInt64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.\n      value = getattr(object, key)\n    /home/rohit/miniconda3/envs/datajoint_interview/lib/python3.8/inspect.py:350: FutureWarning: pandas.Float64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.\n      value = getattr(object, key)\n    /home/rohit/miniconda3/envs/datajoint_interview/lib/python3.8/inspect.py:350: FutureWarning: pandas.Int64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.\n      value = getattr(object, key)\n    /home/rohit/miniconda3/envs/datajoint_interview/lib/python3.8/inspect.py:350: FutureWarning: pandas.UInt64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.\n      value = getattr(object, key)\n\n\n\n\n\n    \n\n    \n\n\n\n\n```python\nSTRF_Compute.populate()\n```\n\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 17\n    \tFound 157 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 17\n    \tFound 161 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 18\n    \tFound 769 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 18\n    \tFound 746 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 18\n    \tFound 759 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 19\n    \tFound 538 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 19\n    \tFound 528 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 19\n    \tFound 537 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 20\n    \tFound 724 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 20\n    \tFound 711 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 20\n    \tFound 719 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 21\n    \tFound 374 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 21\n    \tFound 363 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 21\n    \tFound 370 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 22\n    \tFound 1588 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 22\n    \tFound 1541 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 22\n    \tFound 1572 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 23\n    \tFound 673 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 23\n    \tFound 660 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 23\n    \tFound 669 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 24\n    \tFound 1103 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 24\n    \tFound 1069 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 24\n    \tFound 1093 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 25\n    \tFound 25 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 25\n    \tFound 25 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 2 on 2008-06-24 with stim_id=0 for neuron 25\n    \tFound 25 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-06 with stim_id=0 for neuron 0\n    \tFound 473 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-06 with stim_id=0 for neuron 0\n    \tFound 459 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-06 with stim_id=0 for neuron 0\n    \tFound 470 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 0\n    \tFound 143 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 0\n    \tFound 140 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 0\n    \tFound 142 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 1\n    \tFound 88 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 1\n    \tFound 85 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 1\n    \tFound 87 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 2\n    \tFound 70 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 2\n    \tFound 67 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 2\n    \tFound 68 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 3\n    \tFound 357 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 3\n    \tFound 346 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 3\n    \tFound 354 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 4\n    \tFound 296 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 4\n    \tFound 291 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 4\n    \tFound 295 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 5\n    \tFound 852 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 5\n    \tFound 831 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 5\n    \tFound 848 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 6\n    \tFound 450 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 6\n    \tFound 436 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 6\n    \tFound 445 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 7\n    \tFound 163 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 7\n    \tFound 162 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 7\n    \tFound 163 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 8\n    \tFound 167 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 8\n    \tFound 160 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 8\n    \tFound 166 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 9\n    \tFound 212 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 9\n    \tFound 208 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 9\n    \tFound 210 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 10\n    \tFound 257 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 10\n    \tFound 255 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 10\n    \tFound 256 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 11\n    \tFound 102 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 11\n    \tFound 99 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 11\n    \tFound 102 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 12\n    \tFound 288 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 12\n    \tFound 278 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 12\n    \tFound 281 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 13\n    \tFound 206 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 13\n    \tFound 205 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 13\n    \tFound 206 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 14\n    \tFound 198 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 14\n    \tFound 194 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 14\n    \tFound 195 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 15\n    \tFound 251 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 15\n    \tFound 247 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 15\n    \tFound 250 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 16\n    \tFound 160 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 16\n    \tFound 155 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 16\n    \tFound 157 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 17\n    \tFound 239 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 17\n    \tFound 235 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 17\n    \tFound 237 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 18\n    \tFound 665 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 18\n    \tFound 641 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 18\n    \tFound 656 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 19\n    \tFound 157 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 19\n    \tFound 154 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 19\n    \tFound 156 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 20\n    \tFound 89 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 20\n    \tFound 88 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 20\n    \tFound 88 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 21\n    \tFound 166 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 21\n    \tFound 161 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 21\n    \tFound 165 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 22\n    \tFound 135 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 22\n    \tFound 131 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 22\n    \tFound 135 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 23\n    \tFound 298 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 23\n    \tFound 291 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 23\n    \tFound 294 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 24\n    \tFound 36 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 24\n    \tFound 36 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 24\n    \tFound 36 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 25\n    \tFound 132 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 25\n    \tFound 128 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 25\n    \tFound 132 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 26\n    \tFound 35 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 26\n    \tFound 34 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 26\n    \tFound 35 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 27\n    \tFound 18 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 27\n    \tFound 18 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 27\n    \tFound 18 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 28\n    \tFound 42 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 28\n    \tFound 42 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 28\n    \tFound 42 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 29\n    \tFound 220 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 29\n    \tFound 217 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 29\n    \tFound 220 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 30\n    \tFound 147 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 30\n    \tFound 142 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 30\n    \tFound 145 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 31\n    \tFound 33 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 31\n    \tFound 32 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 31\n    \tFound 33 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 32\n    \tFound 63 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 32\n    \tFound 63 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 32\n    \tFound 63 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 33\n    \tFound 107 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 33\n    \tFound 106 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 33\n    \tFound 107 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 34\n    \tFound 96 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 34\n    \tFound 95 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 34\n    \tFound 96 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 35\n    \tFound 190 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 35\n    \tFound 185 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 35\n    \tFound 187 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 36\n    \tFound 210 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 36\n    \tFound 202 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 36\n    \tFound 208 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 37\n    \tFound 39 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 37\n    \tFound 39 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 3 on 2008-06-24 with stim_id=0 for neuron 37\n    \tFound 39 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 0\n    \tFound 223 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 0\n    \tFound 222 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 0\n    \tFound 223 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 1\n    \tFound 536 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 1\n    \tFound 515 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 1\n    \tFound 530 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 2\n    \tFound 425 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 2\n    \tFound 411 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 2\n    \tFound 422 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 3\n    \tFound 523 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 3\n    \tFound 504 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 3\n    \tFound 518 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 4\n    \tFound 823 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 4\n    \tFound 808 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 4\n    \tFound 815 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 5\n    \tFound 37 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 5\n    \tFound 37 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 5\n    \tFound 37 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 6\n    \tFound 57 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 6\n    \tFound 56 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 6\n    \tFound 57 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 7\n    \tFound 25 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 7\n    \tFound 25 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 7\n    \tFound 25 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 8\n    \tFound 2086 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 8\n    \tFound 2026 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 8\n    \tFound 2068 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 9\n    \tFound 72 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 9\n    \tFound 72 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 9\n    \tFound 72 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 10\n    \tFound 181 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 10\n    \tFound 178 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 10\n    \tFound 181 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 11\n    \tFound 436 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 11\n    \tFound 429 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=0 for neuron 11\n    \tFound 433 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 0\n    \tFound 1223 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 0\n    \tFound 1160 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 0\n    \tFound 1205 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 1\n    \tFound 1608 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 1\n    \tFound 1513 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 1\n    \tFound 1583 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 2\n    \tFound 1555 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 2\n    \tFound 1473 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 2\n    \tFound 1520 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 3\n    \tFound 1443 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 3\n    \tFound 1364 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 3\n    \tFound 1422 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 4\n    \tFound 2017 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 4\n    \tFound 1920 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 4\n    \tFound 1981 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 5\n    \tFound 449 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 5\n    \tFound 416 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 5\n    \tFound 438 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 6\n    \tFound 729 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 6\n    \tFound 696 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 6\n    \tFound 717 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 7\n    \tFound 267 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 7\n    \tFound 256 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 7\n    \tFound 265 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 8\n    \tFound 1580 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 8\n    \tFound 1493 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 8\n    \tFound 1554 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 9\n    \tFound 737 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 9\n    \tFound 695 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 9\n    \tFound 728 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 10\n    \tFound 1565 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 10\n    \tFound 1474 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 10\n    \tFound 1537 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 11\n    \tFound 3001 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 11\n    \tFound 2860 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (chx10), sample 4 on 2008-07-02 with stim_id=1 for neuron 11\n    \tFound 2956 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 1 on 2008-05-16 with stim_id=0 for neuron 0\n    \tFound 2093 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 1 on 2008-05-16 with stim_id=0 for neuron 0\n    \tFound 2032 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 1 on 2008-05-16 with stim_id=0 for neuron 0\n    \tFound 2074 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 1 on 2008-05-16 with stim_id=0 for neuron 1\n    \tFound 432 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 1 on 2008-05-16 with stim_id=0 for neuron 1\n    \tFound 425 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 1 on 2008-05-16 with stim_id=0 for neuron 1\n    \tFound 430 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 1 on 2008-05-16 with stim_id=0 for neuron 2\n    \tFound 1522 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 1 on 2008-05-16 with stim_id=0 for neuron 2\n    \tFound 1484 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 1 on 2008-05-16 with stim_id=0 for neuron 2\n    \tFound 1510 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 1 on 2008-05-16 with stim_id=0 for neuron 3\n    \tFound 845 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 1 on 2008-05-16 with stim_id=0 for neuron 3\n    \tFound 826 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 1 on 2008-05-16 with stim_id=0 for neuron 3\n    \tFound 837 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 1 on 2008-05-16 with stim_id=0 for neuron 4\n    \tFound 1326 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 1 on 2008-05-16 with stim_id=0 for neuron 4\n    \tFound 1293 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 1 on 2008-05-16 with stim_id=0 for neuron 4\n    \tFound 1320 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 1 on 2008-05-16 with stim_id=0 for neuron 5\n    \tFound 253 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 1 on 2008-05-16 with stim_id=0 for neuron 5\n    \tFound 243 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 1 on 2008-05-16 with stim_id=0 for neuron 5\n    \tFound 248 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 1 on 2008-05-16 with stim_id=0 for neuron 6\n    \tFound 1010 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 1 on 2008-05-16 with stim_id=0 for neuron 6\n    \tFound 982 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 1 on 2008-05-16 with stim_id=0 for neuron 6\n    \tFound 1001 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 0\n    \tFound 326 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 0\n    \tFound 320 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 0\n    \tFound 325 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 1\n    \tFound 427 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 1\n    \tFound 413 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 1\n    \tFound 420 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 2\n    \tFound 361 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 2\n    \tFound 356 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 2\n    \tFound 360 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 3\n    \tFound 810 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 3\n    \tFound 794 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 3\n    \tFound 808 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 4\n    \tFound 69 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 4\n    \tFound 69 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 4\n    \tFound 69 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 5\n    \tFound 173 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 5\n    \tFound 169 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 5\n    \tFound 172 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 6\n    \tFound 89 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 6\n    \tFound 87 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 6\n    \tFound 89 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 7\n    \tFound 251 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 7\n    \tFound 247 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 7\n    \tFound 249 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 8\n    \tFound 146 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 8\n    \tFound 143 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 8\n    \tFound 146 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 9\n    \tFound 692 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 9\n    \tFound 681 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 9\n    \tFound 687 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 10\n    \tFound 179 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 10\n    \tFound 174 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 10\n    \tFound 179 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 11\n    \tFound 336 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 11\n    \tFound 332 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 11\n    \tFound 334 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 12\n    \tFound 261 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 12\n    \tFound 254 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 12\n    \tFound 259 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 13\n    \tFound 209 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 13\n    \tFound 203 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 13\n    \tFound 207 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 14\n    \tFound 68 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 14\n    \tFound 63 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 14\n    \tFound 68 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 15\n    \tFound 286 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 15\n    \tFound 280 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 15\n    \tFound 284 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 16\n    \tFound 267 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 16\n    \tFound 256 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 16\n    \tFound 263 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 17\n    \tFound 140 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 17\n    \tFound 136 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 17\n    \tFound 138 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 18\n    \tFound 222 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 18\n    \tFound 216 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 18\n    \tFound 220 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 19\n    \tFound 75 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 19\n    \tFound 73 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 19\n    \tFound 73 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 20\n    \tFound 2 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 20\n    \tFound 2 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 20\n    \tFound 2 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 21\n    \tFound 195 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 21\n    \tFound 193 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 21\n    \tFound 194 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 22\n    \tFound 710 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 22\n    \tFound 696 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 22\n    \tFound 705 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 23\n    \tFound 966 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 23\n    \tFound 941 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 23\n    \tFound 958 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 24\n    \tFound 585 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 24\n    \tFound 571 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 24\n    \tFound 578 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 25\n    \tFound 139 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 25\n    \tFound 135 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 25\n    \tFound 137 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 26\n    \tFound 593 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 26\n    \tFound 583 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 26\n    \tFound 585 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 27\n    \tFound 1659 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 27\n    \tFound 1620 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 27\n    \tFound 1646 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 28\n    \tFound 24 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 28\n    \tFound 23 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 28\n    \tFound 24 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 29\n    \tFound 993 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 29\n    \tFound 974 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 29\n    \tFound 989 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 30\n    \tFound 800 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 30\n    \tFound 778 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 30\n    \tFound 791 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 31\n    \tFound 359 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 31\n    \tFound 345 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 31\n    \tFound 359 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 32\n    \tFound 2058 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 32\n    \tFound 2009 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 32\n    \tFound 2042 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 33\n    \tFound 500 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 33\n    \tFound 486 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject KO (pax6), sample 2 on 2008-05-16 with stim_id=0 for neuron 33\n    \tFound 496 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 0\n    \tFound 608 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 0\n    \tFound 593 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 0\n    \tFound 603 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 1\n    \tFound 1638 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 1\n    \tFound 1601 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 1\n    \tFound 1626 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 2\n    \tFound 261 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 2\n    \tFound 254 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 2\n    \tFound 259 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 3\n    \tFound 1244 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 3\n    \tFound 1222 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 3\n    \tFound 1235 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 4\n    \tFound 488 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 4\n    \tFound 478 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 4\n    \tFound 485 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 5\n    \tFound 776 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 5\n    \tFound 752 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 5\n    \tFound 765 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 6\n    \tFound 1259 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 6\n    \tFound 1233 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 6\n    \tFound 1250 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 7\n    \tFound 0 total spikes with window size of 2.0 seconds.\n\n\n    /tmp/ipykernel_405861/4009491522.py:60: RuntimeWarning: invalid value encountered in true_divide\n      sta_0 = ((average_movie @ spike_counts) / tot_spikes)\n\n\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 7\n    \tFound 0 total spikes with window size of 0.5 seconds.\n\n\n    /tmp/ipykernel_405861/4009491522.py:60: RuntimeWarning: invalid value encountered in true_divide\n      sta_0 = ((average_movie @ spike_counts) / tot_spikes)\n\n\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 7\n    \tFound 0 total spikes with window size of 1.0 seconds.\n\n\n    /tmp/ipykernel_405861/4009491522.py:60: RuntimeWarning: invalid value encountered in true_divide\n      sta_0 = ((average_movie @ spike_counts) / tot_spikes)\n\n\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 8\n    \tFound 1652 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 8\n    \tFound 1609 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 8\n    \tFound 1636 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 9\n    \tFound 793 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 9\n    \tFound 774 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 9\n    \tFound 788 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 10\n    \tFound 1476 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 10\n    \tFound 1442 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 10\n    \tFound 1466 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 11\n    \tFound 51 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 11\n    \tFound 51 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 11\n    \tFound 51 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 12\n    \tFound 728 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 12\n    \tFound 705 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 12\n    \tFound 722 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 13\n    \tFound 1439 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 13\n    \tFound 1406 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 13\n    \tFound 1431 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 14\n    \tFound 85 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 14\n    \tFound 85 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 14\n    \tFound 85 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 15\n    \tFound 104 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 15\n    \tFound 102 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 15\n    \tFound 103 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 16\n    \tFound 1457 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 16\n    \tFound 1425 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 16\n    \tFound 1446 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 17\n    \tFound 602 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 17\n    \tFound 586 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 17\n    \tFound 599 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 18\n    \tFound 1306 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 18\n    \tFound 1266 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 18\n    \tFound 1293 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 19\n    \tFound 195 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 19\n    \tFound 195 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 19\n    \tFound 195 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 20\n    \tFound 703 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 20\n    \tFound 686 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 20\n    \tFound 699 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 21\n    \tFound 778 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 21\n    \tFound 757 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 21\n    \tFound 771 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 22\n    \tFound 519 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 22\n    \tFound 505 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 22\n    \tFound 513 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 23\n    \tFound 564 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 23\n    \tFound 541 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 23\n    \tFound 550 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 24\n    \tFound 1021 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 24\n    \tFound 999 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 24\n    \tFound 1014 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 25\n    \tFound 350 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 25\n    \tFound 346 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 25\n    \tFound 349 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 26\n    \tFound 678 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 26\n    \tFound 667 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 26\n    \tFound 671 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 27\n    \tFound 1931 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 27\n    \tFound 1883 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 27\n    \tFound 1913 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 28\n    \tFound 325 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 28\n    \tFound 317 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 28\n    \tFound 319 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 29\n    \tFound 953 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 29\n    \tFound 925 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 29\n    \tFound 938 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 30\n    \tFound 717 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 30\n    \tFound 698 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 30\n    \tFound 713 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 31\n    \tFound 727 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 31\n    \tFound 705 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 31\n    \tFound 720 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 32\n    \tFound 269 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 32\n    \tFound 262 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 32\n    \tFound 267 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 33\n    \tFound 1054 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 33\n    \tFound 1032 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 33\n    \tFound 1049 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 34\n    \tFound 440 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 34\n    \tFound 431 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 34\n    \tFound 438 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 35\n    \tFound 177 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 35\n    \tFound 174 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 35\n    \tFound 175 total spikes with window size of 1.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 36\n    \tFound 987 total spikes with window size of 2.0 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 36\n    \tFound 970 total spikes with window size of 0.5 seconds.\n    Populating spike counts for subject WT (chx10 het), sample 1 on 2008-06-24 with stim_id=0 for neuron 36\n    \tFound 978 total spikes with window size of 1.0 seconds.\n\n\n\n```python\nSTRF_Compute()\n```\n\n\n\n\n\n\n    <style type=\"text/css\">\n        .Relation{\n            border-collapse:collapse;\n        }\n        .Relation th{\n            background: #A0A0A0; color: #ffffff; padding:4px; border:#f0e0e0 1px solid;\n            font-weight: normal; font-family: monospace; font-size: 100%;\n        }\n        .Relation td{\n            padding:4px; border:#f0e0e0 1px solid; font-size:100%;\n        }\n        .Relation tr:nth-child(odd){\n            background: #ffffff;\n        }\n        .Relation tr:nth-child(even){\n            background: #f3f1ff;\n        }\n        /* Tooltip container */\n        .djtooltip {\n        }\n        /* Tooltip text */\n        .djtooltip .djtooltiptext {\n            visibility: hidden;\n            width: 120px;\n            background-color: black;\n            color: #fff;\n            text-align: center;\n            padding: 5px 0;\n            border-radius: 6px;\n            /* Position the tooltip text - see examples below! */\n            position: absolute;\n            z-index: 1;\n        }\n        #primary {\n            font-weight: bold;\n            color: black;\n        }\n        #nonprimary {\n            font-weight: normal;\n            color: white;\n        }\n\n        /* Show the tooltip text when you mouse over the tooltip container */\n        .djtooltip:hover .djtooltiptext {\n            visibility: visible;\n        }\n    </style>\n\n    <b></b>\n        <div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n        <table border=\"1\" class=\"Relation\">\n            <thead> <tr style=\"text-align: right;\"> <th> <div class=\"djtooltip\">\n                            <p id=\"primary\">subject_name</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"primary\">sample_number</p>\n                            <span class=\"djtooltiptext\">sample number</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"primary\">session_date</p>\n                            <span class=\"djtooltiptext\">date of session in YYYY-MM-DD format</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"primary\">stim_id</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"primary\">neuron_id</p>\n                            <span class=\"djtooltiptext\"></span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"primary\">strf_param_id</p>\n                            <span class=\"djtooltiptext\">unique id for STRF parameter set</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">n_spikes</p>\n                            <span class=\"djtooltiptext\">array for number of spikes in each bin</span>\n                        </div></th><th><div class=\"djtooltip\">\n                            <p id=\"nonprimary\">srtf_values</p>\n                            <span class=\"djtooltiptext\">STA at each time delay</span>\n                        </div> </th> </tr> </thead>\n            <tbody> <tr> <td>KO (chx10)</td>\n<td>1</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>0</td>\n<td>0</td>\n<td>=BLOB=</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>1</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>1</td>\n<td>0</td>\n<td>=BLOB=</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>1</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>2</td>\n<td>0</td>\n<td>=BLOB=</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>1</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>3</td>\n<td>0</td>\n<td>=BLOB=</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>0</td>\n<td>0</td>\n<td>=BLOB=</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>1</td>\n<td>0</td>\n<td>=BLOB=</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>2</td>\n<td>0</td>\n<td>=BLOB=</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>3</td>\n<td>0</td>\n<td>=BLOB=</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>4</td>\n<td>0</td>\n<td>=BLOB=</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-06</td>\n<td>0</td>\n<td>5</td>\n<td>0</td>\n<td>=BLOB=</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-24</td>\n<td>0</td>\n<td>0</td>\n<td>0</td>\n<td>=BLOB=</td>\n<td>=BLOB=</td></tr><tr><td>KO (chx10)</td>\n<td>2</td>\n<td>2008-06-24</td>\n<td>0</td>\n<td>1</td>\n<td>0</td>\n<td>=BLOB=</td>\n<td>=BLOB=</td> </tr> </tbody>\n        </table>\n        <p>...</p>\n        <p>Total: 531</p></div>\n\n\n\n\n#### Check an example key\n\n\n```python\nkeys = STRF_Compute.fetch('KEY')\n\nkey = keys[50]\n```\n\n\n```python\nkey\n```\n\n\n\n\n    {'subject_name': 'KO (chx10)',\n     'sample_number': 3,\n     'session_date': datetime.date(2008, 6, 24),\n     'stim_id': 0,\n     'neuron_id': 13,\n     'strf_param_id': 0}\n\n\n\n\n```python\nimages = (STRF_Compute() & key).fetch1('srtf_values')\n\n# images   # uncomment if you want to see how this looks structurally\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nplt.imshow(images[2][1])\n\nplt.xlabel(f'tau = {images[2][0]} bins delay')\n```\n\n### Visualization code, part 3\n\n\n```python\nplt.figure(figsize=(20, 5))\nplt.subplots_adjust(hspace=0.01)\nplt.suptitle(\"STRF Plots\", fontsize=18, y=0.95)\n\nnrows = 1\nncols = len(images) // nrows + (len(images) % nrows > 0)\n\n\nfor n, plot in enumerate(images):\n    # add a new subplot iteratively\n    ax = plt.subplot(nrows, ncols, n + 1)\n\n    # filter df and plot ticker on the new subplot axis\n    plt.imshow(plot[1])\n    \n    # chart formatting\n    ax.set_xlabel(f\"tau = {plot[0]} bins\")\n\n```\n\n\n```python\n\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "77e7f13b3b9528a7683fc50c787bc418e77459b4", "size": 275618, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Develop_pipeline.ipynb", "max_stars_repo_name": "rvoleti89/datajoint_interview", "max_stars_repo_head_hexsha": "401b4ee43c85d11df2b1e51186143cc70b14025d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Develop_pipeline.ipynb", "max_issues_repo_name": "rvoleti89/datajoint_interview", "max_issues_repo_head_hexsha": "401b4ee43c85d11df2b1e51186143cc70b14025d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Develop_pipeline.ipynb", "max_forks_repo_name": "rvoleti89/datajoint_interview", "max_forks_repo_head_hexsha": "401b4ee43c85d11df2b1e51186143cc70b14025d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.8173282117, "max_line_length": 31820, "alphanum_fraction": 0.5983498901, "converted": true, "num_tokens": 47092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1520322377801054, "lm_q2_score": 0.09807932676584331, "lm_q1q2_score": 0.014911219528177347}}
{"text": "**Installation**\r\n\r\nThis tutorial shows the details of installation on Google Golaboratory.\n\n**Step 1**\r\n\r\nFor changing version. (Edit: 2021/3/11)\n\n\n```\n!pip3 uninstall -y imgaug && pip3 uninstall -y albumentations && pip3 install git+https://github.com/aleju/imgaug.git\n```\n\n\n```\n!pip3 install pymatgen==2020.10.20\r\nimport pymatgen\r\nprint(pymatgen.__version__)\n```\n\n\n```\n!pip3 install -U xenonpy==0.5.0\r\nimport xenonpy\r\nprint(xenonpy.__version__)\n```\n\n\n```\n!pip3 install scikit-learn==0.23.2\r\nimport sklearn\r\nprint(sklearn.__version__)\n```\n\n    Collecting scikit-learn==0.23.2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/5c/a1/273def87037a7fb010512bbc5901c31cfddfca8080bc63b42b26e3cc55b3/scikit_learn-0.23.2-cp36-cp36m-manylinux1_x86_64.whl (6.8MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.8MB 18.6MB/s \n    \u001b[?25hRequirement already satisfied: scipy>=0.19.1 in /usr/local/lib/python3.6/dist-packages (from scikit-learn==0.23.2) (1.4.1)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn==0.23.2) (1.0.0)\n    Requirement already satisfied: numpy>=1.13.3 in /usr/local/lib/python3.6/dist-packages (from scikit-learn==0.23.2) (1.19.5)\n    Collecting threadpoolctl>=2.0.0\n      Downloading https://files.pythonhosted.org/packages/f7/12/ec3f2e203afa394a149911729357aa48affc59c20e2c1c8297a60f33f133/threadpoolctl-2.1.0-py3-none-any.whl\n    Installing collected packages: threadpoolctl, scikit-learn\n      Found existing installation: scikit-learn 0.22.2.post1\n        Uninstalling scikit-learn-0.22.2.post1:\n          Successfully uninstalled scikit-learn-0.22.2.post1\n    Successfully installed scikit-learn-0.23.2 threadpoolctl-2.1.0\n    0.23.2\n\n\n**Step 2**\r\n\r\nInstall Anaconda and set PATH\n\n\n```\n!wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh\r\n!bash Miniconda3-latest-Linux-x86_64.sh -b -f -p /usr/local\r\nimport sys\r\nsys.path.append('/usr/local/lib/python3.6/site-packages/')\n```\n\n    --2021-01-29 10:19:03--  https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh\n    Resolving repo.continuum.io (repo.continuum.io)... 104.18.200.79, 104.18.201.79, 2606:4700::6812:c84f, ...\n    Connecting to repo.continuum.io (repo.continuum.io)|104.18.200.79|:443... connected.\n    HTTP request sent, awaiting response... 301 Moved Permanently\n    Location: https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh [following]\n    --2021-01-29 10:19:03--  https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh\n    Resolving repo.anaconda.com (repo.anaconda.com)... 104.16.131.3, 104.16.130.3, 2606:4700::6810:8203, ...\n    Connecting to repo.anaconda.com (repo.anaconda.com)|104.16.131.3|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 94235922 (90M) [application/x-sh]\n    Saving to: \u2018Miniconda3-latest-Linux-x86_64.sh\u2019\n    \n    Miniconda3-latest-L 100%[===================>]  89.87M   208MB/s    in 0.4s    \n    \n    2021-01-29 10:19:04 (208 MB/s) - \u2018Miniconda3-latest-Linux-x86_64.sh\u2019 saved [94235922/94235922]\n    \n    PREFIX=/usr/local\n    Unpacking payload ...\n    Collecting package metadata (current_repodata.json): - \b\b\\ \b\b| \b\bdone\n    Solving environment: - \b\b\\ \b\bdone\n    \n    ## Package Plan ##\n    \n      environment location: /usr/local\n    \n      added / updated specs:\n        - _libgcc_mutex==0.1=main\n        - brotlipy==0.7.0=py38h27cfd23_1003\n        - ca-certificates==2020.10.14=0\n        - certifi==2020.6.20=pyhd3eb1b0_3\n        - cffi==1.14.3=py38h261ae71_2\n        - chardet==3.0.4=py38h06a4308_1003\n        - conda-package-handling==1.7.2=py38h03888b9_0\n        - conda==4.9.2=py38h06a4308_0\n        - cryptography==3.2.1=py38h3c74f83_1\n        - idna==2.10=py_0\n        - ld_impl_linux-64==2.33.1=h53a641e_7\n        - libedit==3.1.20191231=h14c3975_1\n        - libffi==3.3=he6710b0_2\n        - libgcc-ng==9.1.0=hdf63c60_0\n        - libstdcxx-ng==9.1.0=hdf63c60_0\n        - ncurses==6.2=he6710b0_1\n        - openssl==1.1.1h=h7b6447c_0\n        - pip==20.2.4=py38h06a4308_0\n        - pycosat==0.6.3=py38h7b6447c_1\n        - pycparser==2.20=py_2\n        - pyopenssl==19.1.0=pyhd3eb1b0_1\n        - pysocks==1.7.1=py38h06a4308_0\n        - python==3.8.5=h7579374_1\n        - readline==8.0=h7b6447c_0\n        - requests==2.24.0=py_0\n        - ruamel_yaml==0.15.87=py38h7b6447c_1\n        - setuptools==50.3.1=py38h06a4308_1\n        - six==1.15.0=py38h06a4308_0\n        - sqlite==3.33.0=h62c20be_0\n        - tk==8.6.10=hbc83047_0\n        - tqdm==4.51.0=pyhd3eb1b0_0\n        - urllib3==1.25.11=py_0\n        - wheel==0.35.1=pyhd3eb1b0_0\n        - xz==5.2.5=h7b6447c_0\n        - yaml==0.2.5=h7b6447c_0\n        - zlib==1.2.11=h7b6447c_3\n    \n    \n    The following NEW packages will be INSTALLED:\n    \n      _libgcc_mutex      pkgs/main/linux-64::_libgcc_mutex-0.1-main\n      brotlipy           pkgs/main/linux-64::brotlipy-0.7.0-py38h27cfd23_1003\n      ca-certificates    pkgs/main/linux-64::ca-certificates-2020.10.14-0\n      certifi            pkgs/main/noarch::certifi-2020.6.20-pyhd3eb1b0_3\n      cffi               pkgs/main/linux-64::cffi-1.14.3-py38h261ae71_2\n      chardet            pkgs/main/linux-64::chardet-3.0.4-py38h06a4308_1003\n      conda              pkgs/main/linux-64::conda-4.9.2-py38h06a4308_0\n      conda-package-han~ pkgs/main/linux-64::conda-package-handling-1.7.2-py38h03888b9_0\n      cryptography       pkgs/main/linux-64::cryptography-3.2.1-py38h3c74f83_1\n      idna               pkgs/main/noarch::idna-2.10-py_0\n      ld_impl_linux-64   pkgs/main/linux-64::ld_impl_linux-64-2.33.1-h53a641e_7\n      libedit            pkgs/main/linux-64::libedit-3.1.20191231-h14c3975_1\n      libffi             pkgs/main/linux-64::libffi-3.3-he6710b0_2\n      libgcc-ng          pkgs/main/linux-64::libgcc-ng-9.1.0-hdf63c60_0\n      libstdcxx-ng       pkgs/main/linux-64::libstdcxx-ng-9.1.0-hdf63c60_0\n      ncurses            pkgs/main/linux-64::ncurses-6.2-he6710b0_1\n      openssl            pkgs/main/linux-64::openssl-1.1.1h-h7b6447c_0\n      pip                pkgs/main/linux-64::pip-20.2.4-py38h06a4308_0\n      pycosat            pkgs/main/linux-64::pycosat-0.6.3-py38h7b6447c_1\n      pycparser          pkgs/main/noarch::pycparser-2.20-py_2\n      pyopenssl          pkgs/main/noarch::pyopenssl-19.1.0-pyhd3eb1b0_1\n      pysocks            pkgs/main/linux-64::pysocks-1.7.1-py38h06a4308_0\n      python             pkgs/main/linux-64::python-3.8.5-h7579374_1\n      readline           pkgs/main/linux-64::readline-8.0-h7b6447c_0\n      requests           pkgs/main/noarch::requests-2.24.0-py_0\n      ruamel_yaml        pkgs/main/linux-64::ruamel_yaml-0.15.87-py38h7b6447c_1\n      setuptools         pkgs/main/linux-64::setuptools-50.3.1-py38h06a4308_1\n      six                pkgs/main/linux-64::six-1.15.0-py38h06a4308_0\n      sqlite             pkgs/main/linux-64::sqlite-3.33.0-h62c20be_0\n      tk                 pkgs/main/linux-64::tk-8.6.10-hbc83047_0\n      tqdm               pkgs/main/noarch::tqdm-4.51.0-pyhd3eb1b0_0\n      urllib3            pkgs/main/noarch::urllib3-1.25.11-py_0\n      wheel              pkgs/main/noarch::wheel-0.35.1-pyhd3eb1b0_0\n      xz                 pkgs/main/linux-64::xz-5.2.5-h7b6447c_0\n      yaml               pkgs/main/linux-64::yaml-0.2.5-h7b6447c_0\n      zlib               pkgs/main/linux-64::zlib-1.2.11-h7b6447c_3\n    \n    \n    Preparing transaction: / \b\b- \b\b\\ \b\bdone\n    Executing transaction: / \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\bdone\n    installation finished.\n    WARNING:\n        You currently have a PYTHONPATH environment variable set. This may cause\n        unexpected behavior when running the Python interpreter in Miniconda3.\n        For best results, please verify that your PYTHONPATH only points to\n        directories of packages that are compatible with the Python interpreter\n        in Miniconda3: /usr/local\n\n\n**step 3**\r\n\r\nInstall RDKit and check version.\n\n\n```\n!conda install -q -y -c rdkit rdkit=2020.3 python=3.6\r\nimport rdkit\r\nprint(rdkit.__version__)\n```\n\n    Collecting package metadata (current_repodata.json): ...working... done\n    Solving environment: ...working... failed with initial frozen solve. Retrying with flexible solve.\n    Solving environment: ...working... failed with repodata from current_repodata.json, will retry with next repodata source.\n    Collecting package metadata (repodata.json): ...working... done\n    Solving environment: ...working... done\n    \n    ## Package Plan ##\n    \n      environment location: /usr/local\n    \n      added / updated specs:\n        - python=3.6\n        - rdkit=2020.3\n    \n    \n    The following packages will be downloaded:\n    \n        package                    |            build\n        ---------------------------|-----------------\n        blas-1.0                   |              mkl           6 KB\n        brotlipy-0.7.0             |py36h27cfd23_1003         320 KB\n        bzip2-1.0.8                |       h7b6447c_0          78 KB\n        ca-certificates-2021.1.19  |       h06a4308_0         121 KB\n        cairo-1.14.12              |       h8948797_3         906 KB\n        certifi-2020.12.5          |   py36h06a4308_0         140 KB\n        cffi-1.14.4                |   py36h261ae71_0         223 KB\n        chardet-3.0.4              |py36h06a4308_1003         180 KB\n        conda-4.9.2                |   py36h06a4308_0         2.9 MB\n        conda-package-handling-1.7.2|   py36h03888b9_0         886 KB\n        cryptography-3.3.1         |   py36h3c74f83_0         557 KB\n        fontconfig-2.13.0          |       h9420a91_0         227 KB\n        freetype-2.10.4            |       h5ab3b9f_0         596 KB\n        glib-2.66.1                |       h92f7085_0         2.9 MB\n        icu-58.2                   |       he6710b0_3        10.5 MB\n        intel-openmp-2020.2        |              254         786 KB\n        jpeg-9b                    |       h024ee3a_2         214 KB\n        lcms2-2.11                 |       h396b838_0         307 KB\n        libboost-1.67.0            |       h46d08c1_4        13.0 MB\n        libpng-1.6.37              |       hbc83047_0         278 KB\n        libtiff-4.1.0              |       h2733197_1         449 KB\n        libuuid-1.0.3              |       h1bed415_2          15 KB\n        libxcb-1.14                |       h7b6447c_0         505 KB\n        libxml2-2.9.10             |       hb55368b_3         1.2 MB\n        lz4-c-1.9.3                |       h2531618_0         186 KB\n        mkl-2020.2                 |              256       138.3 MB\n        mkl-service-2.3.0          |   py36he8ac12f_0          52 KB\n        mkl_fft-1.2.0              |   py36h23d657b_0         149 KB\n        mkl_random-1.1.1           |   py36h0573a6f_0         327 KB\n        numpy-1.19.2               |   py36h54aff64_0          22 KB\n        numpy-base-1.19.2          |   py36hfa32c7d_0         4.1 MB\n        olefile-0.46               |           py36_0          48 KB\n        openssl-1.1.1i             |       h27cfd23_0         2.5 MB\n        pandas-1.1.5               |   py36ha9443f7_0         8.2 MB\n        pcre-8.44                  |       he6710b0_0         212 KB\n        pillow-8.1.0               |   py36he98fc37_0         626 KB\n        pip-20.3.3                 |   py36h06a4308_0         1.8 MB\n        pixman-0.40.0              |       h7b6447c_0         370 KB\n        py-boost-1.67.0            |   py36h04863e7_4         278 KB\n        pycosat-0.6.3              |   py36h27cfd23_0          82 KB\n        pysocks-1.7.1              |   py36h06a4308_0          31 KB\n        python-3.6.12              |       hcff3b4d_2        29.7 MB\n        python-dateutil-2.8.1      |             py_0         215 KB\n        pytz-2020.5                |     pyhd3eb1b0_0         182 KB\n        rdkit-2020.03.3.0          |   py36hc20afe1_1        24.7 MB  rdkit\n        ruamel_yaml-0.15.87        |   py36h7b6447c_1         244 KB\n        setuptools-52.0.0          |   py36h06a4308_0         724 KB\n        six-1.15.0                 |   py36h06a4308_0          27 KB\n        zstd-1.4.5                 |       h9ceee32_0         619 KB\n        ------------------------------------------------------------\n                                               Total:       250.7 MB\n    \n    The following NEW packages will be INSTALLED:\n    \n      blas               pkgs/main/linux-64::blas-1.0-mkl\n      bzip2              pkgs/main/linux-64::bzip2-1.0.8-h7b6447c_0\n      cairo              pkgs/main/linux-64::cairo-1.14.12-h8948797_3\n      fontconfig         pkgs/main/linux-64::fontconfig-2.13.0-h9420a91_0\n      freetype           pkgs/main/linux-64::freetype-2.10.4-h5ab3b9f_0\n      glib               pkgs/main/linux-64::glib-2.66.1-h92f7085_0\n      icu                pkgs/main/linux-64::icu-58.2-he6710b0_3\n      intel-openmp       pkgs/main/linux-64::intel-openmp-2020.2-254\n      jpeg               pkgs/main/linux-64::jpeg-9b-h024ee3a_2\n      lcms2              pkgs/main/linux-64::lcms2-2.11-h396b838_0\n      libboost           pkgs/main/linux-64::libboost-1.67.0-h46d08c1_4\n      libpng             pkgs/main/linux-64::libpng-1.6.37-hbc83047_0\n      libtiff            pkgs/main/linux-64::libtiff-4.1.0-h2733197_1\n      libuuid            pkgs/main/linux-64::libuuid-1.0.3-h1bed415_2\n      libxcb             pkgs/main/linux-64::libxcb-1.14-h7b6447c_0\n      libxml2            pkgs/main/linux-64::libxml2-2.9.10-hb55368b_3\n      lz4-c              pkgs/main/linux-64::lz4-c-1.9.3-h2531618_0\n      mkl                pkgs/main/linux-64::mkl-2020.2-256\n      mkl-service        pkgs/main/linux-64::mkl-service-2.3.0-py36he8ac12f_0\n      mkl_fft            pkgs/main/linux-64::mkl_fft-1.2.0-py36h23d657b_0\n      mkl_random         pkgs/main/linux-64::mkl_random-1.1.1-py36h0573a6f_0\n      numpy              pkgs/main/linux-64::numpy-1.19.2-py36h54aff64_0\n      numpy-base         pkgs/main/linux-64::numpy-base-1.19.2-py36hfa32c7d_0\n      olefile            pkgs/main/linux-64::olefile-0.46-py36_0\n      pandas             pkgs/main/linux-64::pandas-1.1.5-py36ha9443f7_0\n      pcre               pkgs/main/linux-64::pcre-8.44-he6710b0_0\n      pillow             pkgs/main/linux-64::pillow-8.1.0-py36he98fc37_0\n      pixman             pkgs/main/linux-64::pixman-0.40.0-h7b6447c_0\n      py-boost           pkgs/main/linux-64::py-boost-1.67.0-py36h04863e7_4\n      python-dateutil    pkgs/main/noarch::python-dateutil-2.8.1-py_0\n      pytz               pkgs/main/noarch::pytz-2020.5-pyhd3eb1b0_0\n      rdkit              rdkit/linux-64::rdkit-2020.03.3.0-py36hc20afe1_1\n      zstd               pkgs/main/linux-64::zstd-1.4.5-h9ceee32_0\n    \n    The following packages will be UPDATED:\n    \n      ca-certificates                              2020.10.14-0 --> 2021.1.19-h06a4308_0\n      certifi            pkgs/main/noarch::certifi-2020.6.20-p~ --> pkgs/main/linux-64::certifi-2020.12.5-py36h06a4308_0\n      cffi                                1.14.3-py38h261ae71_2 --> 1.14.4-py36h261ae71_0\n      cryptography                         3.2.1-py38h3c74f83_1 --> 3.3.1-py36h3c74f83_0\n      openssl                                 1.1.1h-h7b6447c_0 --> 1.1.1i-h27cfd23_0\n      pip                                 20.2.4-py38h06a4308_0 --> 20.3.3-py36h06a4308_0\n      setuptools                          50.3.1-py38h06a4308_1 --> 52.0.0-py36h06a4308_0\n    \n    The following packages will be DOWNGRADED:\n    \n      brotlipy                          0.7.0-py38h27cfd23_1003 --> 0.7.0-py36h27cfd23_1003\n      chardet                           3.0.4-py38h06a4308_1003 --> 3.0.4-py36h06a4308_1003\n      conda                                4.9.2-py38h06a4308_0 --> 4.9.2-py36h06a4308_0\n      conda-package-han~                   1.7.2-py38h03888b9_0 --> 1.7.2-py36h03888b9_0\n      pycosat                              0.6.3-py38h7b6447c_1 --> 0.6.3-py36h27cfd23_0\n      pysocks                              1.7.1-py38h06a4308_0 --> 1.7.1-py36h06a4308_0\n      python                                   3.8.5-h7579374_1 --> 3.6.12-hcff3b4d_2\n      ruamel_yaml                        0.15.87-py38h7b6447c_1 --> 0.15.87-py36h7b6447c_1\n      six                                 1.15.0-py38h06a4308_0 --> 1.15.0-py36h06a4308_0\n    \n    \n    Preparing transaction: ...working... done\n    Verifying transaction: ...working... done\n    Executing transaction: ...working... done\n    2020.03.3\n\n\n**step 4**\r\n\r\nInstall PyTorch and check version.\n\n\n```\n!conda install -y pytorch==1.7.0 torchvision==0.8.0 torchaudio==0.7.0 cudatoolkit=10.1 -c pytorch\r\nimport torch\r\nprint(torch.__version__)\n```\n\n    Collecting package metadata (current_repodata.json): - \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\bdone\n    Solving environment: / \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\bdone\n    \n    ## Package Plan ##\n    \n      environment location: /usr/local\n    \n      added / updated specs:\n        - cudatoolkit=10.1\n        - pytorch\n        - torchaudio\n        - torchvision\n    \n    \n    The following packages will be downloaded:\n    \n        package                    |            build\n        ---------------------------|-----------------\n        cudatoolkit-10.1.243       |       h6bb024c_0       347.4 MB\n        dataclasses-0.7            |           py36_0          30 KB\n        libuv-1.40.0               |       h7b6447c_0         736 KB\n        ninja-1.10.2               |   py36hff7bd54_0         1.4 MB\n        pytorch-1.7.1              |py3.6_cuda10.1.243_cudnn7.6.3_0       553.7 MB  pytorch\n        torchaudio-0.7.2           |             py36         9.8 MB  pytorch\n        torchvision-0.8.2          |       py36_cu101        17.8 MB  pytorch\n        typing_extensions-3.7.4.3  |     pyh06a4308_0          28 KB\n        ------------------------------------------------------------\n                                               Total:       931.1 MB\n    \n    The following NEW packages will be INSTALLED:\n    \n      cudatoolkit        pkgs/main/linux-64::cudatoolkit-10.1.243-h6bb024c_0\n      dataclasses        pkgs/main/linux-64::dataclasses-0.7-py36_0\n      libuv              pkgs/main/linux-64::libuv-1.40.0-h7b6447c_0\n      ninja              pkgs/main/linux-64::ninja-1.10.2-py36hff7bd54_0\n      pytorch            pytorch/linux-64::pytorch-1.7.1-py3.6_cuda10.1.243_cudnn7.6.3_0\n      torchaudio         pytorch/linux-64::torchaudio-0.7.2-py36\n      torchvision        pytorch/linux-64::torchvision-0.8.2-py36_cu101\n      typing_extensions  pkgs/main/noarch::typing_extensions-3.7.4.3-pyh06a4308_0\n    \n    \n    \n    Downloading and Extracting Packages\n    pytorch-1.7.1        | 553.7 MB  | : 100% 1.0/1 [01:14<00:00, 74.75s/it]  \n    typing_extensions-3. | 28 KB     | : 100% 1.0/1 [00:00<00:00, 14.71it/s]\n    torchvision-0.8.2    | 17.8 MB   | : 100% 1.0/1 [00:02<00:00,  2.46s/it] \n    torchaudio-0.7.2     | 9.8 MB    | : 100% 1.0/1 [00:01<00:00,  1.60s/it]\n    dataclasses-0.7      | 30 KB     | : 100% 1.0/1 [00:00<00:00, 25.98it/s]\n    cudatoolkit-10.1.243 | 347.4 MB  | : 100% 1.0/1 [00:13<00:00, 13.17s/it]               \n    libuv-1.40.0         | 736 KB    | : 100% 1.0/1 [00:02<00:00,  2.17s/it]\n    ninja-1.10.2         | 1.4 MB    | : 100% 1.0/1 [00:00<00:00,  7.58it/s]\n    Preparing transaction: / \b\b- \b\bdone\n    Verifying transaction: | \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\bdone\n    Executing transaction: | \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\bdone\n    1.7.0+cu101\n\n\n**step 5**\r\n\r\nInstall XenonPy and check version.\n\n\n```\n!wget https://raw.githubusercontent.com/by-student-2017/xenonpy-gcolab/main/0.5.0/conda_env/cuda101.yml\r\n!conda create --yes -n xenonpy python=3.6\r\n!conda env update -n xenonpy -f cuda101.yml\r\n!source activate xenonpy\n```\n\n    --2021-01-29 10:24:56--  https://raw.githubusercontent.com/by-student-2017/xenonpy-gcolab/main/0.5.0/conda_env/cuda101.yml\n    Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 151.101.0.133, 151.101.64.133, 151.101.128.133, ...\n    Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|151.101.0.133|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 520 [text/plain]\n    Saving to: \u2018cuda101.yml\u2019\n    \n    cuda101.yml         100%[===================>]     520  --.-KB/s    in 0s      \n    \n    2021-01-29 10:24:56 (29.8 MB/s) - \u2018cuda101.yml\u2019 saved [520/520]\n    \n    Collecting package metadata (current_repodata.json): - \b\b\\ \b\b| \b\b/ \b\bdone\n    Solving environment: \\ \b\bdone\n    \n    ## Package Plan ##\n    \n      environment location: /usr/local/envs/xenonpy\n    \n      added / updated specs:\n        - python=3.6\n    \n    \n    The following packages will be downloaded:\n    \n        package                    |            build\n        ---------------------------|-----------------\n        readline-8.1               |       h27cfd23_0         362 KB\n        wheel-0.36.2               |     pyhd3eb1b0_0          33 KB\n        ------------------------------------------------------------\n                                               Total:         395 KB\n    \n    The following NEW packages will be INSTALLED:\n    \n      _libgcc_mutex      pkgs/main/linux-64::_libgcc_mutex-0.1-main\n      ca-certificates    pkgs/main/linux-64::ca-certificates-2021.1.19-h06a4308_0\n      certifi            pkgs/main/linux-64::certifi-2020.12.5-py36h06a4308_0\n      ld_impl_linux-64   pkgs/main/linux-64::ld_impl_linux-64-2.33.1-h53a641e_7\n      libedit            pkgs/main/linux-64::libedit-3.1.20191231-h14c3975_1\n      libffi             pkgs/main/linux-64::libffi-3.3-he6710b0_2\n      libgcc-ng          pkgs/main/linux-64::libgcc-ng-9.1.0-hdf63c60_0\n      libstdcxx-ng       pkgs/main/linux-64::libstdcxx-ng-9.1.0-hdf63c60_0\n      ncurses            pkgs/main/linux-64::ncurses-6.2-he6710b0_1\n      openssl            pkgs/main/linux-64::openssl-1.1.1i-h27cfd23_0\n      pip                pkgs/main/linux-64::pip-20.3.3-py36h06a4308_0\n      python             pkgs/main/linux-64::python-3.6.12-hcff3b4d_2\n      readline           pkgs/main/linux-64::readline-8.1-h27cfd23_0\n      setuptools         pkgs/main/linux-64::setuptools-52.0.0-py36h06a4308_0\n      sqlite             pkgs/main/linux-64::sqlite-3.33.0-h62c20be_0\n      tk                 pkgs/main/linux-64::tk-8.6.10-hbc83047_0\n      wheel              pkgs/main/noarch::wheel-0.36.2-pyhd3eb1b0_0\n      xz                 pkgs/main/linux-64::xz-5.2.5-h7b6447c_0\n      zlib               pkgs/main/linux-64::zlib-1.2.11-h7b6447c_3\n    \n    \n    \n    Downloading and Extracting Packages\n    wheel-0.36.2         | 33 KB     | : 100% 1.0/1 [00:00<00:00, 16.23it/s]\n    readline-8.1         | 362 KB    | : 100% 1.0/1 [00:00<00:00, 20.65it/s]\n    Preparing transaction: / \b\b- \b\b\\ \b\bdone\n    Verifying transaction: / \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\bdone\n    Executing transaction: \\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\bdone\n    #\n    # To activate this environment, use\n    #\n    #     $ conda activate xenonpy\n    #\n    # To deactivate an active environment, use\n    #\n    #     $ conda deactivate\n    \n    Collecting package metadata (repodata.json): - \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\bdone\n    Solving environment: / \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\bdone\n    \n    Downloading and Extracting Packages\n    xorg-libsm-1.2.3     | 25 KB     | : 100% 1.0/1 [00:00<00:00, 15.62it/s]\n    bleach-3.2.3         | 113 KB    | : 100% 1.0/1 [00:00<00:00, 10.26it/s]\n    pandocfilters-1.4.3  | 14 KB     | : 100% 1.0/1 [00:00<00:00, 15.68it/s]\n    prometheus_client-0. | 45 KB     | : 100% 1.0/1 [00:00<00:00, 14.58it/s]\n    ipython-7.16.1       | 999 KB    | : 100% 1.0/1 [00:00<00:00,  7.10it/s]\n    jupyter_console-6.2. | 26 KB     | : 100% 1.0/1 [00:00<00:00, 15.73it/s]\n    rdkit-2020.03.3      | 24.8 MB   | : 100% 1.0/1 [00:03<00:00,  3.45s/it]               \n    torchtext-0.8.1      | 8.1 MB    | : 100% 1.0/1 [00:01<00:00,  1.50s/it]               \n    click-7.1.2          | 64 KB     | : 100% 1.0/1 [00:00<00:00, 34.86it/s]\n    ipywidgets-7.6.3     | 105 KB    | : 100% 1.0/1 [00:00<00:00, 13.07it/s]\n    networkx-2.5         | 1.1 MB    | : 100% 1.0/1 [00:00<00:00,  5.77it/s]\n    requests-2.25.1      | 52 KB     | : 100% 1.0/1 [00:00<00:00, 14.33it/s]\n    attrs-20.3.0         | 43 KB     | : 100% 1.0/1 [00:00<00:00, 11.69it/s]\n    nest-asyncio-1.4.3   | 11 KB     | : 100% 1.0/1 [00:00<00:00, 13.51it/s]\n    apscheduler-3.6.3    | 85 KB     | : 100% 1.0/1 [00:00<00:00, 13.40it/s]\n    zipp-3.4.0           | 15 KB     | : 100% 1.0/1 [00:00<00:00, 15.71it/s]\n    jsoncpp-1.8.4        | 132 KB    | : 100% 1.0/1 [00:00<00:00, 10.99it/s]\n    qt-5.9.7             | 80.8 MB   | : 100% 1.0/1 [00:12<00:00, 12.97s/it]               \n    nbconvert-6.0.7      | 480 KB    | : 100% 1.0/1 [00:00<00:00,  8.94it/s]\n    tbb-2020.3           | 1.1 MB    | : 100% 1.0/1 [00:00<00:00, 10.00it/s]\n    jpeg-9d              | 264 KB    | : 100% 1.0/1 [00:00<00:00, 12.37it/s]\n    testpath-0.4.4       | 82 KB     | : 100% 1.0/1 [00:00<00:00, 12.21it/s]\n    gstreamer-1.14.5     | 4.5 MB    | : 100% 1.0/1 [00:00<00:00,  1.35it/s]\n    boost-cpp-1.72.0     | 21.8 MB   | : 100% 1.0/1 [00:06<00:00,  6.20s/it]\n    libcurl-7.71.1       | 305 KB    | : 100% 1.0/1 [00:00<00:00, 12.35it/s]\n    idna-2.10            | 52 KB     | : 100% 1.0/1 [00:00<00:00, 27.21it/s]\n    libtiff-4.1.0        | 447 KB    | : 100% 1.0/1 [00:00<00:00, 11.82it/s]\n    torchvision-0.2.1    | 75 KB     | : 100% 1.0/1 [00:00<00:00, 13.89it/s]\n    markupsafe-1.1.1     | 29 KB     | : 100% 1.0/1 [00:00<00:00, 14.12it/s]\n    tqdm-4.56.0          | 80 KB     | : 100% 1.0/1 [00:00<00:00, 14.80it/s]\n    plotly-4.14.3        | 3.6 MB    | : 100% 1.0/1 [00:01<00:00,  1.04s/it]\n    netcdf4-1.4.2        | 480 KB    | : 100% 1.0/1 [00:00<00:00, 12.73it/s]\n    json5-0.9.5          | 22 KB     | : 100% 1.0/1 [00:00<00:00, 16.21it/s]\n    expat-2.2.10         | 153 KB    | : 100% 1.0/1 [00:00<00:00, 15.82it/s]\n    seaborn-0.11.1       | 212 KB    | : 100% 1.0/1 [00:00<00:00, 13.62it/s]\n    werkzeug-1.0.1       | 240 KB    | : 100% 1.0/1 [00:00<00:00, 13.76it/s]\n    joblib-1.0.0         | 208 KB    | : 100% 1.0/1 [00:00<00:00, 12.26it/s]\n    pickleshare-0.7.5    | 13 KB     | : 100% 1.0/1 [00:00<00:00, 14.68it/s]\n    terminado-0.9.2      | 25 KB     | : 100% 1.0/1 [00:00<00:00, 13.13it/s]\n    palettable-3.3.0     | 78 KB     | : 100% 1.0/1 [00:00<00:00, 10.14it/s]\n    widgetsnbextension-3 | 862 KB    | : 100% 1.0/1 [00:00<00:00,  9.12it/s]\n    mistune-0.8.4        | 55 KB     | : 100% 1.0/1 [00:00<00:00, 11.86it/s]\n    pymatgen-2020.11.11  | 3.4 MB    | : 100% 1.0/1 [00:01<00:00,  1.22s/it]\n    wcwidth-0.2.5        | 29 KB     | : 100% 1.0/1 [00:00<00:00, 10.57it/s]\n    numpy-1.19.4         | 5.2 MB    | : 100% 1.0/1 [00:01<00:00,  1.01s/it]\n    pyyaml-5.4.1         | 170 KB    | : 100% 1.0/1 [00:00<00:00, 11.80it/s]\n    prompt_toolkit-3.0.8 | 12 KB     | : 100% 1.0/1 [00:00<00:00, 15.31it/s]\n    fastcluster-1.1.26   | 45 KB     | : 100% 1.0/1 [00:00<00:00, 35.00it/s]\n    future-0.18.2        | 639 KB    | : 100% 1.0/1 [00:00<00:00,  7.47it/s]\n    flask-1.1.2          | 78 KB     | : 100% 1.0/1 [00:00<00:00, 12.83it/s]\n    retrying-1.3.3       | 16 KB     | : 100% 1.0/1 [00:00<00:00, 13.97it/s]\n    libnetcdf-4.6.1      | 833 KB    | : 100% 1.0/1 [00:00<00:00, 10.01it/s]\n    prompt-toolkit-3.0.8 | 248 KB    | : 100% 1.0/1 [00:00<00:00, 10.27it/s]\n    xorg-libx11-1.6.12   | 917 KB    | : 100% 1.0/1 [00:00<00:00,  6.08it/s]\n    pyqt-5.9.2           | 4.5 MB    | : 100% 1.0/1 [00:00<00:00,  3.99it/s]\n    backcall-0.2.0       | 15 KB     | : 100% 1.0/1 [00:00<00:00, 14.06it/s]\n    hdf4-4.2.13          | 714 KB    | : 100% 1.0/1 [00:00<00:00, 11.45it/s]\n    cffi-1.14.0          | 223 KB    | : 100% 1.0/1 [00:00<00:00, 13.77it/s]\n    sympy-1.7.1          | 8.9 MB    | : 100% 1.0/1 [00:00<00:00,  1.56it/s]\n    dbus-1.13.18         | 504 KB    | : 100% 1.0/1 [00:00<00:00, 12.34it/s]\n    send2trash-1.5.0     | 14 KB     | : 100% 1.0/1 [00:00<00:00, 14.57it/s]\n    pyopenssl-20.0.1     | 49 KB     | : 100% 1.0/1 [00:00<00:00, 12.25it/s]\n    parso-0.7.0          | 72 KB     | : 100% 1.0/1 [00:00<00:00, 15.77it/s]\n    sip-4.19.8           | 274 KB    | : 100% 1.0/1 [00:00<00:00, 13.10it/s]\n    pixman-0.38.0        | 364 KB    | : 100% 1.0/1 [00:00<00:00, 13.60it/s]\n    defusedxml-0.6.0     | 23 KB     | : 100% 1.0/1 [00:00<00:00, 16.20it/s]\n    pygments-2.7.4       | 676 KB    | : 100% 1.0/1 [00:00<00:00, 10.29it/s]\n    icu-64.2             | 12.6 MB   | : 100% 1.0/1 [00:01<00:00,  1.78s/it]               \n    gst-plugins-base-1.1 | 6.8 MB    | : 100% 1.0/1 [00:01<00:00,  1.01s/it]\n    importlib-metadata-2 | 35 KB     | : 100% 1.0/1 [00:00<00:00, 12.66it/s]\n    hdf5-1.10.4          | 3.9 MB    | : 100% 1.0/1 [00:00<00:00,  5.75it/s]\n    xorg-kbproto-1.0.7   | 26 KB     | : 100% 1.0/1 [00:00<00:00, 16.76it/s]\n    pexpect-4.8.0        | 53 KB     | : 100% 1.0/1 [00:00<00:00, 15.09it/s]\n    ptyprocess-0.7.0     | 17 KB     | : 100% 1.0/1 [00:00<00:00, 16.23it/s]\n    matplotlib-base-3.3. | 5.1 MB    | : 100% 1.0/1 [00:00<00:00,  4.26it/s]\n    cycler-0.10.0        | 13 KB     | : 100% 1.0/1 [00:00<00:00, 15.48it/s]\n    beautifulsoup4-4.9.3 | 86 KB     | : 100% 1.0/1 [00:00<00:00, 21.29it/s]\n    libxml2-2.9.9        | 1.6 MB    | : 100% 1.0/1 [00:00<00:00,  7.35it/s]\n    scikit-learn-0.23.2  | 5.0 MB    | : 100% 1.0/1 [00:00<00:00,  2.40it/s]\n    glib-2.63.1          | 2.9 MB    | : 100% 1.0/1 [00:00<00:00,  5.08it/s]\n    fontconfig-2.13.1    | 340 KB    | : 100% 1.0/1 [00:00<00:00,  9.66it/s]\n    jupyter_core-4.7.0   | 68 KB     | : 100% 1.0/1 [00:00<00:00, 11.77it/s]\n    qtconsole-4.7.7      | 96 KB     | : 100% 1.0/1 [00:00<00:00, 11.65it/s]\n    pyparsing-2.4.7      | 59 KB     | : 100% 1.0/1 [00:00<00:00, 34.56it/s]\n    libsodium-1.0.18     | 244 KB    | : 100% 1.0/1 [00:00<00:00, 11.77it/s]\n    libssh2-1.9.0        | 269 KB    | : 100% 1.0/1 [00:00<00:00, 12.88it/s]\n    nbclient-0.5.1       | 58 KB     | : 100% 1.0/1 [00:00<00:00, 15.07it/s]\n    qtpy-1.9.0           | 38 KB     | : 100% 1.0/1 [00:00<00:00, 15.33it/s]\n    libgfortran-ng-7.3.0 | 1006 KB   | : 100% 1.0/1 [00:00<00:00, 10.18it/s]\n    async_generator-1.10 | 39 KB     | : 100% 1.0/1 [00:00<00:00, 15.61it/s]\n    matplotlib-3.3.2     | 24 KB     | : 100% 1.0/1 [00:00<00:00, 16.25it/s]\n    pycairo-1.19.1       | 73 KB     | : 100% 1.0/1 [00:00<00:00, 15.04it/s]\n    gmp-6.1.2            | 514 KB    | : 100% 1.0/1 [00:00<00:00, 12.96it/s]\n    krb5-1.18.2          | 1.3 MB    | : 100% 1.0/1 [00:00<00:00,  8.90it/s]\n    notebook-6.2.0       | 4.1 MB    | : 100% 1.0/1 [00:00<00:00,  2.97it/s]\n    pandoc-2.11          | 9.6 MB    | : 100% 1.0/1 [00:00<00:00,  2.11it/s]\n    libblas-3.8.0        | 11 KB     | : 100% 1.0/1 [00:00<00:00, 31.31it/s]\n    jupyterlab-2.2.6     | 3.4 MB    | : 100% 1.0/1 [00:00<00:00,  1.91it/s]\n    kiwisolver-1.3.0     | 80 KB     | : 100% 1.0/1 [00:00<00:00, 13.71it/s]\n    lz4-c-1.8.1.2        | 130 KB    | : 100% 1.0/1 [00:00<00:00, 13.66it/s]\n    xorg-xextproto-7.3.0 | 27 KB     | : 100% 1.0/1 [00:00<00:00, 31.26it/s]\n    mpfr-4.0.2           | 487 KB    | : 100% 1.0/1 [00:00<00:00,  9.37it/s]\n    jinja2-2.11.2        | 93 KB     | : 100% 1.0/1 [00:00<00:00, 25.93it/s]\n    jupyterlab_pygments- | 8 KB      | : 100% 1.0/1 [00:00<00:00, 15.54it/s]\n    webencodings-0.5.1   | 19 KB     | : 100% 1.0/1 [00:00<00:00, 16.08it/s]\n    zstd-1.3.7           | 401 KB    | : 100% 1.0/1 [00:00<00:00, 13.98it/s]\n    cftime-1.3.1         | 269 KB    | : 100% 1.0/1 [00:00<00:00, 10.93it/s]\n    importlib_metadata-2 | 11 KB     | : 100% 1.0/1 [00:00<00:00, 16.21it/s]\n    vtk-8.2.0            | 28.4 MB   | : 100% 1.0/1 [00:01<00:00,  1.31s/it]               \n    ipykernel-5.3.4      | 181 KB    | : 100% 1.0/1 [00:00<00:00, 10.94it/s]\n    tzlocal-2.1          | 29 KB     | : 100% 1.0/1 [00:00<00:00, 13.32it/s]\n    itsdangerous-1.1.0   | 28 KB     | : 100% 1.0/1 [00:00<00:00, 12.79it/s]\n    libogg-1.3.2         | 194 KB    | : 100% 1.0/1 [00:00<00:00, 13.08it/s]\n    jupyterlab_widgets-1 | 109 KB    | : 100% 1.0/1 [00:00<00:00, 14.40it/s]\n    soupsieve-2.1        | 31 KB     | : 100% 1.0/1 [00:00<00:00, 15.89it/s]\n    ipython_genutils-0.2 | 27 KB     | : 100% 1.0/1 [00:00<00:00, 14.83it/s]\n    xorg-libxrender-0.9. | 31 KB     | : 100% 1.0/1 [00:00<00:00, 33.26it/s]\n    mordred-1.2.0        | 124 KB    | : 100% 1.0/1 [00:00<00:00, 16.14it/s]\n    xorg-renderproto-0.1 | 8 KB      | : 100% 1.0/1 [00:00<00:00, 22.18it/s]\n    xorg-xproto-7.0.31   | 73 KB     | : 100% 1.0/1 [00:00<00:00, 14.18it/s]\n    pyzmq-20.0.0         | 438 KB    | : 100% 1.0/1 [00:00<00:00, 10.54it/s]\n    ruamel.yaml.clib-0.2 | 145 KB    | : 100% 1.0/1 [00:00<00:00, 14.30it/s]\n    argon2-cffi-20.1.0   | 46 KB     | : 100% 1.0/1 [00:00<00:00, 13.32it/s]\n    mpmath-1.1.0         | 776 KB    | : 100% 1.0/1 [00:00<00:00, 10.47it/s]\n    nbformat-5.1.2       | 68 KB     | : 100% 1.0/1 [00:00<00:00, 12.91it/s]\n    urllib3-1.26.3       | 105 KB    | : 100% 1.0/1 [00:00<00:00, 13.90it/s]\n    decorator-4.4.2      | 14 KB     | : 100% 1.0/1 [00:00<00:00, 10.34it/s]\n    tornado-6.1          | 581 KB    | : 100% 1.0/1 [00:00<00:00,  9.94it/s]\n    tabulate-0.8.7       | 40 KB     | : 100% 1.0/1 [00:00<00:00, 15.18it/s]\n    ruamel.yaml-0.16.12  | 172 KB    | : 100% 1.0/1 [00:00<00:00, 12.97it/s]\n    liblapack-3.8.0      | 11 KB     | : 100% 1.0/1 [00:00<00:00, 38.05it/s]\n    jupyter-1.0.0        | 6 KB      | : 100% 1.0/1 [00:00<00:00, 15.02it/s]\n    xorg-libxext-1.3.4   | 51 KB     | : 100% 1.0/1 [00:00<00:00, 31.56it/s]\n    libuuid-2.32.1       | 26 KB     | : 100% 1.0/1 [00:00<00:00, 27.21it/s]\n    jedi-0.17.2          | 919 KB    | : 100% 1.0/1 [00:00<00:00,  3.59it/s]\n    libcblas-3.8.0       | 11 KB     | : 100% 1.0/1 [00:00<00:00, 32.21it/s]\n    libvorbis-1.3.7      | 398 KB    | : 100% 1.0/1 [00:00<00:00, 11.98it/s]\n    libffi-3.2.1         | 48 KB     | : 100% 1.0/1 [00:00<00:00, 15.52it/s]\n    mpc-1.1.0            | 90 KB     | : 100% 1.0/1 [00:00<00:00, 14.12it/s]\n    entrypoints-0.3      | 12 KB     | : 100% 1.0/1 [00:00<00:00, 15.19it/s]\n    boost-1.72.0         | 338 KB    | : 100% 1.0/1 [00:00<00:00,  6.95it/s]\n    packaging-20.8       | 36 KB     | : 100% 1.0/1 [00:00<00:00, 11.80it/s]\n    jupyterlab_server-1. | 25 KB     | : 100% 1.0/1 [00:00<00:00, 11.74it/s]\n    libtheora-1.1.1      | 330 KB    | : 100% 1.0/1 [00:00<00:00, 11.47it/s]\n    magma-cuda101-2.5.2  | 55.8 MB   | : 100% 1.0/1 [00:08<00:00,  8.14s/it]                \n    curl-7.71.1          | 140 KB    | : 100% 1.0/1 [00:00<00:00, 13.67it/s]\n    gmpy2-2.0.8          | 150 KB    | : 100% 1.0/1 [00:00<00:00, 14.38it/s]\n    traitlets-4.3.3      | 140 KB    | : 100% 1.0/1 [00:00<00:00, 12.87it/s]\n    cairo-1.16.0         | 1.5 MB    | : 100% 1.0/1 [00:00<00:00,  3.62it/s]\n    python-3.6.10        | 29.7 MB   | : 100% 1.0/1 [00:00<00:00,  1.20it/s]\n    jupyter_client-6.1.7 | 77 KB     | : 100% 1.0/1 [00:00<00:00, 10.36it/s]\n    zeromq-4.3.3         | 500 KB    | : 100% 1.0/1 [00:00<00:00, 12.31it/s]\n    xorg-libice-1.0.10   | 57 KB     | : 100% 1.0/1 [00:00<00:00, 29.64it/s]\n    jsonschema-3.2.0     | 47 KB     | : 100% 1.0/1 [00:00<00:00, 15.08it/s]\n    pyrsistent-0.17.3    | 89 KB     | : 100% 1.0/1 [00:00<00:00, 13.04it/s]\n    chardet-4.0.0        | 199 KB    | : 100% 1.0/1 [00:00<00:00, 11.15it/s]\n    threadpoolctl-2.1.0  | 17 KB     | : 100% 1.0/1 [00:00<00:00, 13.23it/s]\n    Preparing transaction: \\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\bdone\n    Verifying transaction: | \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\bdone\n    Executing transaction: - \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\bdone\n    Installing pip dependencies: / \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- Ran pip subprocess with arguments:\n    ['/usr/local/envs/xenonpy/bin/python', '-m', 'pip', 'install', '-U', '-r', '/content/condaenv.sbxuit13.requirements.txt']\n    Pip subprocess output:\n    Collecting matminer\n      Downloading matminer-0.6.4.tar.gz (5.7 MB)\n    Requirement already satisfied: numpy>=1.19.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (1.19.4)\n    Requirement already satisfied: requests>=2.23.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (2.25.1)\n    Requirement already satisfied: pymatgen>=2020.4.29 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (2020.11.11)\n    Requirement already satisfied: pandas>=1.0.4 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (1.1.5)\n    Requirement already satisfied: tqdm>=4.46.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (4.56.0)\n    Requirement already satisfied: six>=1.15.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (1.15.0)\n    Requirement already satisfied: plotly>=4.8.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (4.14.3)\n    Requirement already satisfied: future>=0.18.2 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (0.18.2)\n    Requirement already satisfied: sympy>=1.6 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (1.7.1)\n    Requirement already satisfied: scikit_learn>=0.23.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (0.23.2)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (4.0.2)\n    Requirement already satisfied: jsonschema>=3.2.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (3.2.0)\n    Requirement already satisfied: importlib-metadata in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jsonschema>=3.2.0->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (2.0.0)\n    Requirement already satisfied: pyrsistent>=0.14.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jsonschema>=3.2.0->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (0.17.3)\n    Requirement already satisfied: attrs>=17.4.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jsonschema>=3.2.0->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (20.3.0)\n    Requirement already satisfied: setuptools in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jsonschema>=3.2.0->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (52.0.0.post20210125)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pandas>=1.0.4->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pandas>=1.0.4->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (2020.5)\n    Collecting pint>=0.11\n      Downloading Pint-0.16.1-py2.py3-none-any.whl (205 kB)\n    Requirement already satisfied: packaging in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pint>=0.11->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (20.8)\n    Requirement already satisfied: retrying>=1.3.3 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from plotly>=4.8.1->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (1.3.3)\n    Requirement already satisfied: scipy>=1.5.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pymatgen>=2020.4.29->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (1.5.2)\n    Requirement already satisfied: dataclasses>=0.6 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pymatgen>=2020.4.29->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (0.7)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pymatgen>=2020.4.29->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (1.16.0)\n    Requirement already satisfied: tabulate in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pymatgen>=2020.4.29->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (0.8.7)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pymatgen>=2020.4.29->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (3.3.0)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pymatgen>=2020.4.29->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (2.5)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pymatgen>=2020.4.29->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (3.3.2)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pymatgen>=2020.4.29->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (0.16.12)\n    Requirement already satisfied: uncertainties>=3.1.4 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pymatgen>=2020.4.29->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (3.1.5)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2020.4.29->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2020.4.29->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (1.3.0)\n    Requirement already satisfied: certifi>=2020.06.20 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2020.4.29->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (2020.12.5)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2020.4.29->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (2.4.7)\n    Requirement already satisfied: pillow>=6.2.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2020.4.29->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (8.1.0)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from networkx>=2.2->pymatgen>=2020.4.29->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (4.4.2)\n    Collecting pymongo>=3.10.1\n      Downloading pymongo-3.11.2-cp36-cp36m-manylinux2014_x86_64.whl (509 kB)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from requests>=2.23.0->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (2.10)\n    Requirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from requests>=2.23.0->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (1.26.3)\n    Requirement already satisfied: chardet<5,>=3.0.2 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from requests>=2.23.0->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (4.0.0)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from ruamel.yaml>=0.15.6->pymatgen>=2020.4.29->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (0.2.2)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from scikit_learn>=0.23.1->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (2.1.0)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from scikit_learn>=0.23.1->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (1.0.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from sympy>=1.6->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (1.1.0)\n    Collecting Python-Deprecated\n      Downloading Python-Deprecated-1.1.0.tar.gz (2.9 kB)\n    Collecting xenonpy\n      Downloading xenonpy-0.5.0-py3-none-any.whl (131 kB)\n    Requirement already satisfied: seaborn in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from xenonpy->-r /content/condaenv.sbxuit13.requirements.txt (line 3)) (0.11.1)\n    Requirement already satisfied: torch>=1.4.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from xenonpy->-r /content/condaenv.sbxuit13.requirements.txt (line 3)) (1.7.1)\n    Requirement already satisfied: mordred in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from xenonpy->-r /content/condaenv.sbxuit13.requirements.txt (line 3)) (1.2.0)\n    Requirement already satisfied: typing_extensions in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from torch>=1.4.0->xenonpy->-r /content/condaenv.sbxuit13.requirements.txt (line 3)) (3.7.4.3)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from importlib-metadata->jsonschema>=3.2.0->matminer->-r /content/condaenv.sbxuit13.requirements.txt (line 2)) (3.4.0)\n    Collecting importlib-resources\n      Downloading importlib_resources-5.1.0-py3-none-any.whl (24 kB)\n    Building wheels for collected packages: matminer, Python-Deprecated\n      Building wheel for matminer (setup.py): started\n      Building wheel for matminer (setup.py): finished with status 'done'\n      Created wheel for matminer: filename=matminer-0.6.4-py3-none-any.whl size=1172376 sha256=6c4bed91d2445047d3a6031acfed9b1a3c96c01669b31736577937e7e888146a\n      Stored in directory: /root/.cache/pip/wheels/32/6c/43/1106db220f1884faae6a9ffed65511395f7f2794fad32f4f71\n      Building wheel for Python-Deprecated (setup.py): started\n      Building wheel for Python-Deprecated (setup.py): finished with status 'done'\n      Created wheel for Python-Deprecated: filename=Python_Deprecated-1.1.0-py2.py3-none-any.whl size=3069 sha256=74048261b67ba5860d1a72475888618af25f5f77ac1827e7c0fca225f119fd61\n      Stored in directory: /root/.cache/pip/wheels/7b/77/f4/889fb222210030f42875d19bb55b64ea2b394428066fd3a6f4\n    Successfully built matminer Python-Deprecated\n    Installing collected packages: importlib-resources, Python-Deprecated, pymongo, pint, xenonpy, matminer\n    Successfully installed Python-Deprecated-1.1.0 importlib-resources-5.1.0 matminer-0.6.4 pint-0.16.1 pymongo-3.11.2 xenonpy-0.5.0\n    \n    \b\bdone\n    #\n    # To activate this environment, use\n    #\n    #     $ conda activate xenonpy\n    #\n    # To deactivate an active environment, use\n    #\n    #     $ conda deactivate\n    \n    Collecting xenonpy==0.5.0\n      Using cached xenonpy-0.5.0-py3-none-any.whl (131 kB)\n    Requirement already satisfied: pandas>=1.0.0 in /usr/local/lib/python3.6/site-packages (from xenonpy==0.5.0) (1.1.5)\n    Requirement already satisfied: pymatgen>=2020.10.09 in /usr/local/lib/python3.6/site-packages (from xenonpy==0.5.0) (2020.10.20)\n    Requirement already satisfied: scipy>=1.2.0 in /usr/local/lib/python3.6/site-packages (from xenonpy==0.5.0) (1.5.2)\n    Requirement already satisfied: ruamel.yaml in /usr/local/lib/python3.6/site-packages (from xenonpy==0.5.0) (0.15.87)\n    Requirement already satisfied: numpy>=1.16.0 in /usr/local/lib/python3.6/site-packages (from xenonpy==0.5.0) (1.19.2)\n    Requirement already satisfied: requests in /usr/local/lib/python3.6/site-packages (from xenonpy==0.5.0) (2.24.0)\n    Requirement already satisfied: torch>=1.4.0 in /usr/local/lib/python3.6/site-packages (from xenonpy==0.5.0) (1.7.1)\n    Requirement already satisfied: plotly in /usr/local/lib/python3.6/site-packages (from xenonpy==0.5.0) (4.14.3)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.6/site-packages (from xenonpy==0.5.0) (4.51.0)\n    Collecting joblib>=0.13.0\n      Downloading joblib-1.0.0-py3-none-any.whl (302 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 302 kB 16.8 MB/s \n    \u001b[?25hRequirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.6/site-packages (from pandas>=1.0.0->xenonpy==0.5.0) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/site-packages (from pandas>=1.0.0->xenonpy==0.5.0) (2020.5)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.6/site-packages (from pymatgen>=2020.10.09->xenonpy==0.5.0) (3.3.0)\n    Requirement already satisfied: uncertainties>=3.1.4 in /usr/local/lib/python3.6/site-packages (from pymatgen>=2020.10.09->xenonpy==0.5.0) (3.1.5)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.6/site-packages (from pymatgen>=2020.10.09->xenonpy==0.5.0) (1.7.1)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.6/site-packages (from pymatgen>=2020.10.09->xenonpy==0.5.0) (1.16.0)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.6/site-packages (from pymatgen>=2020.10.09->xenonpy==0.5.0) (3.3.3)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.6/site-packages (from pymatgen>=2020.10.09->xenonpy==0.5.0) (4.0.2)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.6/site-packages (from pymatgen>=2020.10.09->xenonpy==0.5.0) (2.5)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.6/site-packages (from pymatgen>=2020.10.09->xenonpy==0.5.0) (0.8.7)\n    Requirement already satisfied: dataclasses>=0.6 in /usr/local/lib/python3.6/site-packages (from pymatgen>=2020.10.09->xenonpy==0.5.0) (0.7)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2020.10.09->xenonpy==0.5.0) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2020.10.09->xenonpy==0.5.0) (1.3.1)\n    Requirement already satisfied: pillow>=6.2.0 in /usr/local/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2020.10.09->xenonpy==0.5.0) (8.1.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3 in /usr/local/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2020.10.09->xenonpy==0.5.0) (2.4.7)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/site-packages (from cycler>=0.10->matplotlib>=1.5->pymatgen>=2020.10.09->xenonpy==0.5.0) (1.15.0)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/site-packages (from networkx>=2.2->pymatgen>=2020.10.09->xenonpy==0.5.0) (4.4.2)\n    Requirement already satisfied: retrying>=1.3.3 in /usr/local/lib/python3.6/site-packages (from plotly->xenonpy==0.5.0) (1.3.3)\n    Collecting scikit-learn>=0.21.0\n      Downloading scikit_learn-0.24.1-cp36-cp36m-manylinux2010_x86_64.whl (22.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 22.2 MB 86.9 MB/s \n    \u001b[?25hCollecting threadpoolctl>=2.0.0\n      Using cached threadpoolctl-2.1.0-py3-none-any.whl (12 kB)\n    Requirement already satisfied: typing_extensions in /usr/local/lib/python3.6/site-packages (from torch>=1.4.0->xenonpy==0.5.0) (3.7.4.3)\n    Requirement already satisfied: future in /usr/local/lib/python3.6/site-packages (from uncertainties>=3.1.4->pymatgen>=2020.10.09->xenonpy==0.5.0) (0.18.2)\n    Collecting mordred\n      Downloading mordred-1.2.0.tar.gz (128 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 128 kB 64.8 MB/s \n    \u001b[?25hCollecting Python-Deprecated\n      Using cached Python_Deprecated-1.1.0-py2.py3-none-any.whl\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/site-packages (from requests->xenonpy==0.5.0) (2.10)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/site-packages (from requests->xenonpy==0.5.0) (1.25.11)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/site-packages (from requests->xenonpy==0.5.0) (2020.12.5)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/site-packages (from requests->xenonpy==0.5.0) (3.0.4)\n    Collecting seaborn\n      Downloading seaborn-0.11.1-py3-none-any.whl (285 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 285 kB 68.1 MB/s \n    \u001b[?25hRequirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/site-packages (from sympy->pymatgen>=2020.10.09->xenonpy==0.5.0) (1.1.0)\n    Building wheels for collected packages: mordred\n      Building wheel for mordred (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for mordred: filename=mordred-1.2.0-py3-none-any.whl size=176719 sha256=52c94f837dc5983ffab1d0491dfc145546b24f95f3d40a31612f06588819daed\n      Stored in directory: /root/.cache/pip/wheels/94/e8/c6/0561efc609b8b695a4c0a98e76e439a97f33eadfd0dba949ee\n    Successfully built mordred\n    Installing collected packages: threadpoolctl, joblib, seaborn, scikit-learn, Python-Deprecated, mordred, xenonpy\n    Successfully installed Python-Deprecated-1.1.0 joblib-1.0.0 mordred-1.2.0 scikit-learn-0.24.1 seaborn-0.11.1 threadpoolctl-2.1.0 xenonpy-0.5.0\n\n\n\n\n    0.5.0\n\n\n**step 6**\r\n\r\nInstall XenonPy samples\n\n\n```\n!git clone https://github.com/by-student-2017/xenonpy-gcolab.git\r\n%cd xenonpy-gcolab/0.5.0/samples\r\n!wget https://github.com/yoshida-lab/XenonPy/releases/download/v0.4.1/iQSPR_sample_data.csv\r\n!ls\n```\n\n    Cloning into 'xenonpy-gcolab'...\n    remote: Enumerating objects: 234, done.\u001b[K\n    remote: Counting objects: 100% (234/234), done.\u001b[K\n    remote: Compressing objects: 100% (130/130), done.\u001b[K\n    remote: Total 234 (delta 106), reused 217 (delta 92), pack-reused 0\u001b[K\n    Receiving objects: 100% (234/234), 5.46 MiB | 29.92 MiB/s, done.\n    Resolving deltas: 100% (106/106), done.\n    /content/xenonpy-gcolab/0.4.4/samples\n    --2021-01-29 10:29:37--  https://github.com/yoshida-lab/XenonPy/releases/download/v0.4.1/iQSPR_sample_data.csv\n    Resolving github.com (github.com)... 140.82.113.3\n    Connecting to github.com (github.com)|140.82.113.3|:443... connected.\n    HTTP request sent, awaiting response... 302 Found\n    Location: https://github-releases.githubusercontent.com/117819602/14925c00-e455-11e9-9065-7d987b463251?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20210129%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20210129T102937Z&X-Amz-Expires=300&X-Amz-Signature=1de4689adf3ec8ffe06b5b90ad59bafd958bffa19d116e5409c06416b4256862&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=117819602&response-content-disposition=attachment%3B%20filename%3DiQSPR_sample_data.csv&response-content-type=application%2Foctet-stream [following]\n    --2021-01-29 10:29:37--  https://github-releases.githubusercontent.com/117819602/14925c00-e455-11e9-9065-7d987b463251?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20210129%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20210129T102937Z&X-Amz-Expires=300&X-Amz-Signature=1de4689adf3ec8ffe06b5b90ad59bafd958bffa19d116e5409c06416b4256862&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=117819602&response-content-disposition=attachment%3B%20filename%3DiQSPR_sample_data.csv&response-content-type=application%2Foctet-stream\n    Resolving github-releases.githubusercontent.com (github-releases.githubusercontent.com)... 185.199.108.154, 185.199.109.154, 185.199.110.154, ...\n    Connecting to github-releases.githubusercontent.com (github-releases.githubusercontent.com)|185.199.108.154|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 954073 (932K) [application/octet-stream]\n    Saving to: \u2018iQSPR_sample_data.csv\u2019\n    \n    iQSPR_sample_data.c 100%[===================>] 931.71K  --.-KB/s    in 0.02s   \n    \n    2021-01-29 10:29:37 (38.2 MB/s) - \u2018iQSPR_sample_data.csv\u2019 saved [954073/954073]\n    \n    calculate_descriptors.ipynb\t    random_nn_model_and_training.ipynb\n    custom_descriptor_calculator.ipynb  sample_data_building.ipynb\n    dataset_and_preset.ipynb\t    set1\n    installation.ipynb\t\t    set2\n    iQSPR.ipynb\t\t\t    storage.ipynb\n    iQSPR_sample_data.csv\t\t    tools.ipynb\n    mp_ids.txt\t\t\t    transfer_learning.ipynb\n    nn_model_build.ipynb\t\t    visualization.ipynb\n    pre-trained_model_library.ipynb\n\n\n**step 7**\r\n\r\nInstall Gaussian process\n\n\n```\n!pip3 install GPy==1.9.9\n```\n\n    Collecting GPy==1.9.9\n      Downloading GPy-1.9.9.tar.gz (995 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 995 kB 16.6 MB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.7 in /usr/local/lib/python3.6/site-packages (from GPy==1.9.9) (1.19.2)\n    Requirement already satisfied: scipy>=0.16 in /usr/local/lib/python3.6/site-packages (from GPy==1.9.9) (1.5.2)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/site-packages (from GPy==1.9.9) (1.15.0)\n    Collecting paramz>=0.9.0\n      Downloading paramz-0.9.5.tar.gz (71 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 71 kB 11.6 MB/s \n    \u001b[?25hRequirement already satisfied: decorator>=4.0.10 in /usr/local/lib/python3.6/site-packages (from paramz>=0.9.0->GPy==1.9.9) (4.4.2)\n    Building wheels for collected packages: GPy, paramz\n      Building wheel for GPy (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for GPy: filename=GPy-1.9.9-cp36-cp36m-linux_x86_64.whl size=2633495 sha256=9bb14035d6cddab60f5ce501f7818091cc8cd16776a37f2c35cd5b35fcb56b11\n      Stored in directory: /root/.cache/pip/wheels/1c/b9/22/3c8a2f0294d140333f6610f075eaf5f22508b2ba154e487a23\n      Building wheel for paramz (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for paramz: filename=paramz-0.9.5-py3-none-any.whl size=102552 sha256=74f1897ae70d6d3362d1c4b39279f541f3b419e68ceb4de0b47649f567905f39\n      Stored in directory: /root/.cache/pip/wheels/72/d5/80/7921b405df363b0f10446fc93491092c20bc75491cbbd0a354\n    Successfully built GPy paramz\n    Installing collected packages: paramz, GPy\n    Successfully installed GPy-1.9.9 paramz-0.9.5\n\n\n**step 8**\r\n\r\nInstall OpenNMT-py\n\n\n```\n!pip3 install OpenNMT-py==1.2.0\n```\n\n    Collecting OpenNMT-py==1.2.0\n      Downloading OpenNMT_py-1.2.0-py3-none-any.whl (195 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 195 kB 16.9 MB/s \n    \u001b[?25hRequirement already satisfied: future in /usr/local/lib/python3.6/site-packages (from OpenNMT-py==1.2.0) (0.18.2)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.6/site-packages (from OpenNMT-py==1.2.0) (4.51.0)\n    Requirement already satisfied: pyyaml in /usr/local/lib/python3.6/site-packages (from OpenNMT-py==1.2.0) (5.3.1)\n    Requirement already satisfied: torch>=1.6.0 in /usr/local/lib/python3.6/site-packages (from OpenNMT-py==1.2.0) (1.7.1)\n    Requirement already satisfied: flask in /usr/local/lib/python3.6/site-packages (from OpenNMT-py==1.2.0) (1.1.2)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/site-packages (from OpenNMT-py==1.2.0) (1.15.0)\n    Collecting pyonmttok==1.*\n      Downloading pyonmttok-1.23.0-cp36-cp36m-manylinux1_x86_64.whl (2.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.5 MB 45.2 MB/s \n    \u001b[?25hCollecting torchtext==0.4.0\n      Downloading torchtext-0.4.0-py3-none-any.whl (53 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 53 kB 2.2 MB/s \n    \u001b[?25hRequirement already satisfied: requests in /usr/local/lib/python3.6/site-packages (from torchtext==0.4.0->OpenNMT-py==1.2.0) (2.24.0)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/site-packages (from torchtext==0.4.0->OpenNMT-py==1.2.0) (1.19.2)\n    Collecting tensorboard>=1.14\n      Downloading tensorboard-2.4.1-py3-none-any.whl (10.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 10.6 MB 69.7 MB/s \n    \u001b[?25hRequirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.6/site-packages (from tensorboard>=1.14->OpenNMT-py==1.2.0) (0.35.1)\n    Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.6/site-packages (from tensorboard>=1.14->OpenNMT-py==1.2.0) (52.0.0.post20210125)\n    Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.6/site-packages (from tensorboard>=1.14->OpenNMT-py==1.2.0) (1.0.1)\n    Collecting absl-py>=0.4\n      Downloading absl_py-0.11.0-py3-none-any.whl (127 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 127 kB 79.9 MB/s \n    \u001b[?25hCollecting google-auth<2,>=1.6.3\n      Downloading google_auth-1.24.0-py2.py3-none-any.whl (114 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 114 kB 87.1 MB/s \n    \u001b[?25hCollecting cachetools<5.0,>=2.0.0\n      Downloading cachetools-4.2.1-py3-none-any.whl (12 kB)\n    Collecting google-auth-oauthlib<0.5,>=0.4.1\n      Downloading google_auth_oauthlib-0.4.2-py2.py3-none-any.whl (18 kB)\n    Collecting grpcio>=1.24.3\n      Downloading grpcio-1.35.0-cp36-cp36m-manylinux2014_x86_64.whl (4.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4.1 MB 70.5 MB/s \n    \u001b[?25hCollecting markdown>=2.6.8\n      Downloading Markdown-3.3.3-py3-none-any.whl (96 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 96 kB 7.6 MB/s \n    \u001b[?25hCollecting protobuf>=3.6.0\n      Downloading protobuf-3.14.0-cp36-cp36m-manylinux1_x86_64.whl (1.0 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.0 MB 69.2 MB/s \n    \u001b[?25hCollecting pyasn1-modules>=0.2.1\n      Downloading pyasn1_modules-0.2.8-py2.py3-none-any.whl (155 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 155 kB 74.1 MB/s \n    \u001b[?25hCollecting pyasn1<0.5.0,>=0.4.6\n      Downloading pyasn1-0.4.8-py2.py3-none-any.whl (77 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 77 kB 7.9 MB/s \n    \u001b[?25hRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/site-packages (from requests->torchtext==0.4.0->OpenNMT-py==1.2.0) (2020.12.5)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/site-packages (from requests->torchtext==0.4.0->OpenNMT-py==1.2.0) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/site-packages (from requests->torchtext==0.4.0->OpenNMT-py==1.2.0) (3.0.4)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/site-packages (from requests->torchtext==0.4.0->OpenNMT-py==1.2.0) (1.25.11)\n    Collecting requests-oauthlib>=0.7.0\n      Downloading requests_oauthlib-1.3.0-py2.py3-none-any.whl (23 kB)\n    Collecting oauthlib>=3.0.0\n      Downloading oauthlib-3.1.0-py2.py3-none-any.whl (147 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 147 kB 89.4 MB/s \n    \u001b[?25hCollecting rsa<5,>=3.1.4\n      Downloading rsa-4.7-py3-none-any.whl (34 kB)\n    Collecting tensorboard-plugin-wit>=1.6.0\n      Downloading tensorboard_plugin_wit-1.8.0-py3-none-any.whl (781 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 781 kB 78.1 MB/s \n    \u001b[?25hRequirement already satisfied: typing_extensions in /usr/local/lib/python3.6/site-packages (from torch>=1.6.0->OpenNMT-py==1.2.0) (3.7.4.3)\n    Requirement already satisfied: dataclasses in /usr/local/lib/python3.6/site-packages (from torch>=1.6.0->OpenNMT-py==1.2.0) (0.7)\n    Collecting configargparse\n      Downloading ConfigArgParse-1.2.3.tar.gz (42 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 42 kB 1.6 MB/s \n    \u001b[?25hRequirement already satisfied: itsdangerous>=0.24 in /usr/local/lib/python3.6/site-packages (from flask->OpenNMT-py==1.2.0) (1.1.0)\n    Requirement already satisfied: Jinja2>=2.10.1 in /usr/local/lib/python3.6/site-packages (from flask->OpenNMT-py==1.2.0) (2.11.2)\n    Requirement already satisfied: click>=5.1 in /usr/local/lib/python3.6/site-packages (from flask->OpenNMT-py==1.2.0) (7.1.2)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.6/site-packages (from Jinja2>=2.10.1->flask->OpenNMT-py==1.2.0) (1.1.1)\n    Collecting importlib-metadata\n      Downloading importlib_metadata-3.4.0-py3-none-any.whl (10 kB)\n    Collecting zipp>=0.5\n      Downloading zipp-3.4.0-py3-none-any.whl (5.2 kB)\n    Collecting waitress\n      Downloading waitress-1.4.4-py2.py3-none-any.whl (58 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 58 kB 8.0 MB/s \n    \u001b[?25hBuilding wheels for collected packages: configargparse\n      Building wheel for configargparse (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for configargparse: filename=ConfigArgParse-1.2.3-py3-none-any.whl size=19328 sha256=9a33f06afa51bfd9fca6e9b703b3bd0b2cd08d99f8ba8fd7784e0a81c94ab14f\n      Stored in directory: /root/.cache/pip/wheels/ee/c1/ad/ab1d6fd3b6e32d4444fe79f88d8832689a0d3c3a74188051ea\n    Successfully built configargparse\n    Installing collected packages: pyasn1, zipp, rsa, pyasn1-modules, oauthlib, cachetools, requests-oauthlib, importlib-metadata, google-auth, tensorboard-plugin-wit, protobuf, markdown, grpcio, google-auth-oauthlib, absl-py, waitress, torchtext, tensorboard, pyonmttok, configargparse, OpenNMT-py\n    Successfully installed OpenNMT-py-1.2.0 absl-py-0.11.0 cachetools-4.2.1 configargparse-1.2.3 google-auth-1.24.0 google-auth-oauthlib-0.4.2 grpcio-1.35.0 importlib-metadata-3.4.0 markdown-3.3.3 oauthlib-3.1.0 protobuf-3.14.0 pyasn1-0.4.8 pyasn1-modules-0.2.8 pyonmttok-1.23.0 requests-oauthlib-1.3.0 rsa-4.7 tensorboard-2.4.1 tensorboard-plugin-wit-1.8.0 torchtext-0.4.0 waitress-1.4.4 zipp-3.4.0\n\n\n**step 9**\r\n\r\nCheck versions one more.\r\n(For some reason pytorch is displayed as 1.8.0+cu101)\n\n\n```\nimport pymatgen\r\nprint(pymatgen.__version__)\r\nimport xenonpy\r\nprint(xenonpy.__version__)\r\nimport sklearn\r\nprint(sklearn.__version__)\r\nimport rdkit\r\nprint(rdkit.__version__)\r\nimport torch\r\nprint(torch.__version__)\n```\n\n    0.23.2\n    2020.03.3\n    1.7.0+cu101\n    2020.10.20\n    0.5.0\n\n", "meta": {"hexsha": "444a8f80b0b4132aa953c6e2650462be8534ca6d", "size": 96673, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "0.5.0/samples/installation_050_v20210311.ipynb", "max_stars_repo_name": "by-student-2017/xenonpy-gcolab", "max_stars_repo_head_hexsha": "9a93121803f4f7e1af8b36a9b5e67daff02ac6c6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "0.5.0/samples/installation_050_v20210311.ipynb", "max_issues_repo_name": "by-student-2017/xenonpy-gcolab", "max_issues_repo_head_hexsha": "9a93121803f4f7e1af8b36a9b5e67daff02ac6c6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0.5.0/samples/installation_050_v20210311.ipynb", "max_forks_repo_name": "by-student-2017/xenonpy-gcolab", "max_forks_repo_head_hexsha": "9a93121803f4f7e1af8b36a9b5e67daff02ac6c6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 77.4623397436, "max_line_length": 9373, "alphanum_fraction": 0.4974501671, "converted": true, "num_tokens": 33764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2509127868852725, "lm_q2_score": 0.05921025115631603, "lm_q1q2_score": 0.014856609129808185}}
{"text": "# IPython's Rich Display System\n\nIn Python, objects can declare their textual representation using the `__repr__` method.  IPython expands on this idea and allows objects to declare other, richer representations including:\n\n* HTML\n* JSON\n* PNG\n* JPEG\n* SVG\n* LaTeX\n\nA single object can declare some or all of these representations; all are handled by IPython's *display system*. This Notebook shows how you can use this display system to incorporate a broad range of content into your Notebooks.\n\n## Basic display imports\n\nThe `display` function is a general purpose tool for displaying different representations of objects. Think of it as `print` for these rich representations.\n\n\n```\nfrom IPython.display import display\n```\n\nA few points:\n\n* Calling `display` on an object will send **all** possible representations to the Notebook.\n* These representations are stored in the Notebook document.\n* In general the Notebook will use the richest available representation.\n\nIf you want to display a particular representation, there are specific functions for that:\n\n\n```\nfrom IPython.display import display_pretty, display_html, display_jpeg, display_png, display_json, display_latex, display_svg\n```\n\n## Images\n\nTo work with images (JPEG, PNG) use the `Image` class.\n\n\n```\nfrom IPython.display import Image\n```\n\n\n```\ni = Image(filename='../images/ipython_logo.png')\n```\n\nReturning an `Image` object from an expression will automatically display it:\n\n\n```\ni\n```\n\nOr you can pass it to `display`:\n\n\n```\ndisplay(i)\n```\n\nAn image can also be displayed from raw data or a url\n\n\n```\nImage(url='http://python.org/images/python-logo.gif')\n```\n\n\n\n\n\n\n\n\nSVG images are also supported out of the box (since modern browsers do a good job of rendering them):\n\n\n```\nfrom IPython.display import SVG\nSVG(filename='images/python_logo.svg')\n```\n\n\n\n\n    \n\n    \n\n\n\n## Links to local files\n\nIf we want to create a link to one of them, we can call use the `FileLink` object.\n\n\n```\nfrom IPython.display import FileLink, FileLinks\nFileLink('Running Code.ipynb')\n```\n\n\n\n\n<a href='Running Code.ipynb' target='_blank'>Running Code.ipynb</a><br>\n\n\n\nAlternatively, if we want to link to all of the files in a directory, we can use the `FileLinks` object, passing `'.'` to indicate that we want links generated for the current working directory. Note that if there were other directories under the current directory, `FileLinks` would work in a recursive manner creating links to files in all sub-directories as well.\n\n\n```\nFileLinks('.')\n```\n\n\n\n\n./<br>\n&nbsp;&nbsp;<a href='./Animations Using clear_output.ipynb' target='_blank'>Animations Using clear_output.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Basic Output.ipynb' target='_blank'>Basic Output.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Connecting with the Qt Console.ipynb' target='_blank'>Connecting with the Qt Console.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Custom Display Logic.ipynb' target='_blank'>Custom Display Logic.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Display System.ipynb' target='_blank'>Display System.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Importing Notebooks.ipynb' target='_blank'>Importing Notebooks.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Index.ipynb' target='_blank'>Index.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Markdown Cells.ipynb' target='_blank'>Markdown Cells.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Plotting with Matplotlib.ipynb' target='_blank'>Plotting with Matplotlib.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Progress Bars.ipynb' target='_blank'>Progress Bars.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Raw Input.ipynb' target='_blank'>Raw Input.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Running Code.ipynb' target='_blank'>Running Code.ipynb</a><br>\n&nbsp;&nbsp;<a href='./SymPy.ipynb' target='_blank'>SymPy.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Trapezoid Rule.ipynb' target='_blank'>Trapezoid Rule.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Typesetting Math Using MathJax.ipynb' target='_blank'>Typesetting Math Using MathJax.ipynb</a><br>\n&nbsp;&nbsp;<a href='./User Interface.ipynb' target='_blank'>User Interface.ipynb</a><br>\n./images/<br>\n&nbsp;&nbsp;<a href='./images/animation.m4v' target='_blank'>animation.m4v</a><br>\n&nbsp;&nbsp;<a href='./images/command_mode.png' target='_blank'>command_mode.png</a><br>\n&nbsp;&nbsp;<a href='./images/edit_mode.png' target='_blank'>edit_mode.png</a><br>\n&nbsp;&nbsp;<a href='./images/menubar_toolbar.png' target='_blank'>menubar_toolbar.png</a><br>\n&nbsp;&nbsp;<a href='./images/python_logo.svg' target='_blank'>python_logo.svg</a><br>\n./nbpackage/<br>\n&nbsp;&nbsp;<a href='./nbpackage/__init__.py' target='_blank'>__init__.py</a><br>\n&nbsp;&nbsp;<a href='./nbpackage/mynotebook.ipynb' target='_blank'>mynotebook.ipynb</a><br>\n./nbpackage/nbs/<br>\n&nbsp;&nbsp;<a href='./nbpackage/nbs/__init__.py' target='_blank'>__init__.py</a><br>\n&nbsp;&nbsp;<a href='./nbpackage/nbs/other.ipynb' target='_blank'>other.ipynb</a><br>\n\n\n\n### Embedded vs Non-embedded Images\n\nBy default, image data is embedded in the Notebook document so that the images can be viewed offline. However it is also possible to tell the `Image` class to only store a *link* to the image. Let's see how this works using a webcam at Berkeley.\n\n\n```\nfrom IPython.display import Image\nimg_url = 'http://www.lawrencehallofscience.org/static/scienceview/scienceview.berkeley.edu/html/view/view_assets/images/newview.jpg'\n\n# by default Image data are embedded\nEmbed      = Image(img_url)\n\n# if kwarg `url` is given, the embedding is assumed to be false\nSoftLinked = Image(url=img_url)\n\n# In each case, embed can be specified explicitly with the `embed` kwarg\n# ForceEmbed = Image(url=img_url, embed=True)\n```\n\nHere is the embedded version. Note that this image was pulled from the webcam when this code cell was originally run and stored in the Notebook. Unless we rerun this cell, this is not todays image.\n\n\n```\nEmbed\n```\n\n\n\n\n    \n\n    \n\n\n\nHere is today's image from same webcam at Berkeley, (refreshed every minutes, if you reload the notebook), visible only with an active internet connection, that should be different from the previous one. Notebooks saved with this kind of image will be lighter and always reflect the current version of the source, but the image won't display offline.\n\n\n```\nSoftLinked\n```\n\n\n\n\n\n\n\n\nOf course, if you re-run this Notebook, the two images will be the same again.\n\n## Audio\n\nIPython makes it easy to work with sounds interactively. The `Audio` display class allows you to create an audio control that is embedded in the Notebook. The interface is analogous to the interface of the `Image` display class. All audio formats supported by the browser can be used. Note that no single format is presently supported in all browsers.\n\n\n```\nfrom IPython.display import Audio\nAudio(url=\"http://www.nch.com.au/acm/8k16bitpcm.wav\")\n```\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"http://www.nch.com.au/acm/8k16bitpcm.wav\" type=\"audio/x-wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\nA Numpy array can be auralized automatically. The Audio class normalizes and encodes the data and embed the result in the Notebook.\n\nFor instance, when two sine waves with almost the same frequency are superimposed a phenomena known as [beats](https://en.wikipedia.org/wiki/Beat_%28acoustics%29) occur. This can be auralised as follows\n\n\n```\nimport numpy as np\nmax_time = 3\nf1 = 220.0\nf2 = 224.0\nrate = 8000.0\nL = 3\ntimes = np.linspace(0,L,rate*L)\nsignal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times)\n\nAudio(data=signal, rate=rate)\n```\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"data:audio/wav;base64,UklGRqS7AABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YYC7AAAAADUWvSvyPzdS/WHKbjt4Bn7+fxV+WXj3bjhifVJDQBYslBZiAC/qpdRswCGuU557kf2HJIIcgPWBoIfykKKdTa15v5rTEuk7/2kV8CopP3ZRSmEqbrJ3mH2vf+Z9TXgNb3Bi11K9QK0sQxcmAQPrhNVPwQOvLZ9IkreIxYKggFiC34cLkZOdFq0bvxbTbeh4/o0UASosPnNQSGAwbcd2w3z2fk9923fGblZi7FL/QBwt3hfoAefrg9ZlwiawVqBuk9OJzoOOgSSDg4iAkdadJa31vrvS3ue5/aIT8Sj/PDBP+F7da3t1h3vUfU98BncibuhhuVIJQWQtYRilAtjso9eqw4mxzKHtlE+LPYXkgleEiolTkm6ee60Hv4jSZuf//KsSwyeiO65NXF0zas9z5nlJfOh6zXUhbSdhPlLaQIItzBhbA9Xt39gexSmzjqPCliuNEYeihPKF9YqDk1mfGq5Uv3/SCOdN/KkReCYYOvBLd1szaMVx4HdYehp5MXTDaxNgfFFwQHUtHRkJBNvuN9q9xgW1l6XsmGOPR4nGhvKHwowPlZegAa/bv6LSxOak+58QFCVkOPhJSVnhZV9veXUCeOh2MnIIaqpecVDLPzwtUxmsBOjvp9uFyBm356dmm/aR3otOiVeK8Y73limiMLCewPHSneYG+48PmSOINslH11Y+Y6BssnJJdVF002/yZ+5cHU/rPtYsbBlEBfvwLd11ymO5e6ownuGU1I44jB+NgZE6mQ+kqLGcwW7Tk+Z1+noOCCKGNGVFI1ROYIppj28vcllxFG2CZeBagU3PPUMsZxnOBRHyyN6IzOC7T61GoSGYJZKBj0aQbpTXm0WmZ7PWwhjUp+by+WMNZCBhMtBCMFEUXSFmEWy4bgJu+Gm6YoFYnkt3PIIrQxlJBinzdOC9zo2+YLCkpLKbz5Unk8yTuJfLns2obrVMxPDU2+Z/+UwMsB4dMAxAAU6TWWdiPGjlak9qgWaaX9FVdEnjOpIq/xi0Bj/0L+IQ0WfBq7NHqJKfzpkml6yXXJsVoqSru7f9xffVL+ce+TYL7hy8LR09m0rOVWFeFGS6ZkJmsmImXNNSBEcVOXQpmhgMB1P19+N/02rELbctrL2jH557m+SbVp+zpciuTrroxy3XpefP+CQKIRtAKwY6/0bKURNanF87YuBhjV5gWIlPUEQMNycoFBhRB2P2yeUG1pTH4bpPsC+ovaIioHGgpKOhqTiyJL0OypHYPOiU+BgJSxmuKMo2M0OJTX9V2FpsXStdF1pKVPVLWUHKNKsmbBeCB2v3o+ej2OHKxb6stOOspacYpU6lQ6jdrfG1PMBtzCTa9ehu+BMIbhcHJm0zOT8RSatQzVVRWCdYUVXoTxlIID5PMgIloRadB2z4gulT203O08I+udax0qxXqneqLq1ksvC5k8MDz+Tb0ele+BcHjRVPI/MvFztmRJtLf1DvUtlSQVA9S/dDqTqeLysjtBWiB2P5ZOsS3tXRCccBvgK3P7Lcr+mvYrIytzK+KcfP0dHdz+pl+CYGqxOJIF4szzaMP1RG80pJTUVN6kpNRpQ/9ja3LCghpRSPB076Ru3e4HTVYcvxwmO86beitZ6127dEvLXC+srQ1Orf8OuE+EIFyRG5HbQoZzKIOtpALkVkR29HUUUbQfI6CDOcKfkecxNkByv7Ju+z4yjZ2M8JyPXByb2ju5K7lL2VwXXHA88E2C7iM+27+GsE6w/gGvck4i1eNTI7ND9HQV1BeT+sOxU25C5QJqAcHxIgB/r7AvGO5u3catREzbHH28PbwcHBiMMhx27MQ9No25zkmO4L+aQDEg4DGCshRSkTMGI1DDn2OhQ7aTkENgExiyrVIh4aqhDEBrr82PJt6b/gEdmd0pTNGcpFyCPIs8nlzJ3RtNf63jLnHfB0+e0CQAwkFVUdlCSsKm8vujJ2NJk0JTMnMLkrASYtH3QXEw9NBmj9pvRL7Jrkyt0Q2JfTfdDazrbOENDa0v3WVdy34u/pxPH3+UgCeApGEncZ1B8uJV0pQyzNLfEtsSwaKkImSiFbG6UUXQ2+BQP+aPYo73rokeKY3bXZA9eV1XLVmNb92IrcIeGd5tDsifOT+rYBuwhsD5UVCRueHzMjryUBJyInFCbiI6AgaRxiF7IRiAsVBYz+Hvj/8VzsYOcw4+rfpd1w3FLcSN1I30DiFeap6tTvbvVJ+zcBDAeZDLQRNxYAGvUcAh8YIDIgUx+FHdgaYxdEE54OlQlSBAD/xvnO9DzwNOzS6C/mXeRm41DjGeS25RroLevX7vjyb/cY/M0AbAXPCdYNYhFbFKoWQRgXGScZdBgHF+0UOxIGD2oLhgd3A2D/XvuS9xf0CPF67n/sJOtx6mfqBetD7BPuZfAl8zr2jPkA/XgA3AMRB/8JjwyxDlYQdBEEEgYSfBFuEOcO9QyqChoIWwWDAqr/5PxI+un32PUj9NXy9vGK8ZHxB/Ln8ib0uPWO95j5xPsA/jkAYAJiBDIGwwcKCQAKnwrmCtUKcQq/CcgIlQc0BrAEFwN3Ad7/V/7v/K/7n/rI+Sv5zPis+Mf4Gfme+U/6IvsQ/A79FP4Y/xAA9wDFAXQCAQNpA6sDyAPCA5wDWgMBA5cCIQKnAS4BvABUAPz/tv+D/2X/W/9j/3z/ov/Q/wIANABiAIcAngClAJkAeQBFAP7/pP87/8j+Tv7V/WD99/yg/GD8PPw5/Fn8nvwJ/Zn9S/4c/wMA/gACAgcDBQTxBMEFbgbwBj4HVAcuB8oGKQZMBTgE9QKJAQAAZv7G/C/7rflP+CH3L/aD9Sb1HfVr9RL2Dvdc+PL5x/vN/fb/MAJrBJUGmwhsCvgLLw0HDnQOcQ78DRMNvQsACucHggXiAhoAQP1p+q33IvXe8vXwd+9z7vXtA+6f7sjvd/Gj8zz2Mflq/NH/SgO8BgoKGg3RDxkS3hMOFZ4VhxXFFF0TVRG8DqMLIAhOBEkAMvwl+EX0sfCG7eDq1Oh259Pm9ObZ54Dp3+vk7nzyjPb1+pf/TATyCGQNfBEbFSAYdBoAHLYcjhyFG6EZ7RZ8E2cPzArMBY4APPv99fvwXuxM6OfkTOKR4Mbf9t8h4UHjSeYj6rTu2vNv+Uf/NQUNC58QvxVEGgge7CDXIrYjgSM1ItofgBw9GDITgw1bB+kAYPrx88/tLOg04xHf5NvK2dXYD9l72g/du+Bk5ejqHvHY9+L+BAYKDboT4BlKH8wjQieMKZgqWSrPKAMmCCL6HP8WQhD4CFgBnvkD8sbqHuRC3mHZotUn0wTSRtLt0/DWOduq4BvnW+409mn+ugboDrIW2h0oJGgpby0cMFYxEjFPLxcsgSevIcoaCBOjCtsB9fg18ODnOOB52dvTi8+tzFrLoMt+zenQydX821LjlOuE9N39VQemEIUZrCHaKNYubzN+Nuo3pTetNRAy5ixWJpEe0RVYDHECZ/iH7iDlfNze1IXOpMlixt3EIsUyxwDLcNBc147fyujJ8j791wdDEjEcUSVdLRM0PDmwPFA+DD7lO+k3MjLtKk8imhgXDhgD8/f77Iji7dh10GPJ8cNLwJG+0r4PwTnFMsvP0tbbAuYG8Y78Pgi+E7QeySitMRo50z6rQoFEQ0TyQZw9YTdvLwImYRveD9EDmPeR6xrgjtU/zHjEd75tuny4trgau5q/FcZazivYPuM97837jAgXFQ0hDyzHNec9L0RrSHhKQ0rNRyVDbTzXM6QpIh6pEZgEV/dK6tfdYdJByMm/O7nNtKSy0rJatSi6HMEAypLUgOBw7f76wAhNFjojIi+oOXdCSknqTTBQCFByTX5IUUEhODMt2yB3E24FL/cl6cDbaM9+xFm7QbRwrw2tLa3Sr+m0TbzGxQ7Rzd2i6yL63AhgFzslADJNPcdGIk4lU6VVjVXcUqNNCkZJPKswiCNGFVEGH/ck6NbZpcz4wCu3jK9ZqrunyqeHquCvrLexwaPNJtvU6Tr54AhPGA0nqDS0QNJKs1IXWNJazVoFWI9SkkpLQAg0JyYSFz8HJ/dH5xvYGsqxvUKzIKuNpbSir6J/pRKrPbPDvVTKkNgI6Ef4zAgbGbEoFzfaQ5dO+Va8XLJfw1/qXD1X5k4jREc3tSjbGDYIRveN5o7Wx8esuqKvAacPofud352+oISmBa8CuibHDNZD5kz3owjDGSYqTDm+RhJS8FoRYUJka2SGYapbAVPNR2U6LiueGjQJevf25THVsMXqt0ysMqPknJWZYJlJnDqiCKtwthrEntOF5Er2ZAhJGmsrRjtdSUJVl14RZX5owWjVZdBf31ZFS109jy1XHDkKwveB5QTU08NttUSptZ8PmYWVNJUimDmeSqcSszbBStHR4kP1EgisGoEsBT23SyNY6WG7aGJswWzSaaxjfFqITixA1i8FHkELHvgv5QbTM8I3s4qmjpySlc6RYJFOlIOaz6Psr3y+Ec8p4Tn0rQfuGmcthz7JTbVa5mQLbOtvaHB7bTpn1V2SUdBCADKlH0wMjPj95DjSz8BJsSGkvZlwknOO543RkB2XmqAArfC798yR3y/zNwcPGx0uzT+TT/Vcimf+bhdzs3PMcHhq5mBfVEVFCjQ1IVcNC/ns5JnRp7+jrwqiRpesj3eLy4qujQmUrp1SqpS5/soK3iXysQYQG6Uu1UAUUeJe1GmTceJ1nnbCc2FtrGPtVohH8TWyIl8OmPn75CnRvb5HrkagKZVHjd2IEIjnikyRDpvkp2u3KcmX3B3xHAbzGv4uoUFMUnxgw2vHc0p4KHlZdvJvJGY5WZZJszcaJGQPMvon5efQD74zrdaeaJNDi6eGuIV/iOeOv5i7pXi1e8c62xvwfAW4GikvMUI7U8JhVW2adU96TnuReCpyS2hAW21LTDlrJWMQ2fpw5dLQnr1qrLudBZKiidaExYN5ht2MwZbYo76z9sX22SDv0ARhGigvhELgU7Niim4Jd+17D31legV0H2r+XApNvDqjJloRifvV5enQaL3pq/Sc/pBliGuDOILWhDCLF5U+oj6yncTM2C7uHATvGfsunUI8VE9jYW8UeCN9Z37We4J1nWtzXmpO/ju+J0cSQfxU5izRbb2xq4KcVpCMh2iCE4GYg+OJxJPuoPywcsO/10ftYQNkGaMue0JQVJdj22+7ePJ9WH/gfJ92xWycX41PEj28KCgT//zr5pjRrL3Bq2ScDJAYh86BWIDBgveIyZLsn/qvdsLR1mzsoALBGCMuIEIcVItj92/9eFh+33+EfVt3k214YG9Q9T2aKfsTwv2Y5yzSI74ZrJqcH5AIh5yBBoBRgmyIKJI4nzmvrMED1qHr3AEJGHwtjUGhUyxjtW/beFZ+/H/AfbR3B24EYQ9Rpj5WKr8Uh/5b6ObS0b62rCKdjpBch9OBHYBJgkSI4ZHVnrquFsFZ1ebqFgE9F64sxEDiUntiF29UeOp9r3+Ufap3IG4/YWxRIj/vKnAVTf8w6cbTtL+XrfydWpEUiHKCn4CpgoCI9pHCnn+utMDT1D/qUABfFr4rxz/fUXphHm5rdxd9+H7/fDx33G0pYYRRaD9iKw4WEAAW6sjUy8C7riWfgJIviXmDioFygyCJaJIBn4quicBz1Kvpjv9xFasqlz6aUClgy2wfdt172X0DfGt2PW3AYFZRdz+vK5YW0gAL6+rVE8IgsJyg/5OqiuaE3oKihCOKNpOTn9uulsA61C7pz/51FHkpNz0WT4xeIWt0dD16UXyfejZ1QWwFYOJQTj/TKwgXjgEO7CzXi8PEsWCi1ZWGjLiGmoQ5homLYJR4oHOv3MAq1MnoFv5tEykoqDtUTaNcIGlpcjl4YnrVeJ9z6Gr2XiZQ7D7OK2EXQwIb7YrYMMWks22kAJi+ju6Iu4Y2iFKN5pWwoVKwW8FF1HzoZf1bEr4m7jlXS3Jay2YDcNN1DnimdqVxNGmVXSNPUD6eK6AX8AIx7gHa/8a9tcGmfppSkYWLQYmXinyPyJc6o3mxFMKK1EvovvxBETolCjghSftXJWRCbQxzV3UTdEtvJWfiW9lNej1DK8MXkgNO75Hb98gOuFqpS50/lHqOKYxbjQaSBJoXpeeyCMP71DboIfwiEJ8jADa2RkFVMWEqauhvQHIgcZJsvWTcWUhMaTy7KsoXKARv8DbdE8uTujSsZaCBl8yRcI9+kO2UmZxEp5y0NsSZ1T3okvv/DvAh0TMYREdS8l2+ZmpsyW7NbXxp/GGHV29KHTsHKrMXsQST8e7eU81JvUyvyaMWm3aVFJMAlDGYhZ/CqZe2n8Vk1mToEfvaDS8ggTFLQRFPa1oCY5Ro+Godagxm5V7iVFFIlzklKX4XKgW48rfgss8twKCycqf6nneZEpfcl86bx6KOrNi4Qsdc16nooPq2DGAeEy9QPqFLoFb4Xmpkz2YUZkNieVvvUe5F1jcWKCkXkgXb843iLtI8wyu2Xqspo8mdZpsQnMKfW6anr127H8mC2A7pQfqUC4MciiwtO/xHlFKkWvBfUWK2YSVevFewTkdD3TXZJrMW6AX79G/kxNRzxuq5ia+gp2miDKCZoAmkQKoLsyW+NcvW2ZTp9Pl3Cp0a6SnlNyVES04LVipbg10EXbVZsFMoS15AqjNvJR0WKwYW9lrmcNfNydi97rNarFSnAaVypaGocq63ti7BhM1X2zvqu/lfCa8YMid6NB9AykkxUR1WaFgEWPZUWE9YRzU9QDHYI2UVWQYp90voMNpIzfPBirhTsYSsQaqYqoWt77KqunfECdAE3QPrmPlQCLsWaSTwMPA7FUUbTMtQBVO6Uu1PuEpEQ845oC4UIowUcgY0+D/qAd3f0DbGV72GtvWxxq8GsLKys7ffvv3HxNLe3u3rivlLB8UUkSFMLZs3MUDMRjxLX00pTZ1K0kXuPio2zCslIJITdAY0+Tbs39+P1JzKUsLvu6K3jLW4tSS4urxUw73LstXj4Pjsk/lRBs8Srh6RKSUzITtKQXJFe0dXRwtFqkBaOk0yxCgLHnUSXwYo+ivuyOJV2CLPdceIwYe9jrupu9a9AcIGyLbP0tgS4yXutPlkBdsQwRvCJZEu6zWaO3Q/XEFIQTo/RjuLNTkuiyXHGzgRMwYO+x3wt+Us3MPTvcxOx57Dx8HUwcPDgsfyzOTTI9xr5XPv7fmFBOwOzxjkIeQpkzDBNUY5CjsCOzE5qDWFMPIpJCJaGdoP7gXk+wryq+gQ4HvYI9I6zeHJMcg0yOjJO80S0kXYoN/r5+LwPvq2AwMN2hX5HSIlHyvEL+4yiTSJNPMy1i9LK3olkB7HFlsOkAWr/O7zoOv/40XdpNdH00zQyM7Ezj3QJtNk19TcSeOR6nDyqPr5AiML5hIHGlEgkyWoKXIs3i3kLYcs1CniJdQg0xoOFL0MGQVf/cn1k+705x3iOt1w2djWhdV+1cDWPtni3I7hG+db7R30LPtOAk4J9Q8RFnMb9B9zI9clECcXJ/AlpyNPIAYc7hYzEQELiQQB/pj3gfHr6/7m4eKv34HdY9xc3Gndft+K4nDmEutI8On1yPu1AYUHCg0aEo8WSBoqHSIfJCApIDYfVB2VGhEX5hI2DicJ4QOP/ln5aPTg7+XrkugA5kDkXONZ4zPk4uVV6HbrK+9V89H3ffwxAcwFKQomDqcRkhTTFlsYIBkfGV0Y4Ba5FPsRvQ4aCzAHIAMJ/wv7RPfR88zwSu5c7A/raupu6hrrZOxA7pzwY/N/9tX5Sv3CACMEUwc5CsEM2Q5zEIURChIAEmoRUhDBDscMdgrhBx8FRgJu/6v8E/q697D1A/S+8unxhvGX8Rby/vJF9N31uPfF+fP7MP5oAIwCiwRWBuEHIgkQCqgK6ArQCmUKrQmwCHoHFQaOBPUCVQG9/zj+0vyW+4v6uPkh+cf4rPjL+CP5rPlf+jX7JPwk/Sr+Lf8kAAkB1AGBAgsDcAOvA8kDwAOXA1MD+AKNAhcCnQEkAbIATAD2/7H/gP9j/1v/Zf9//6X/1P8GADgAZQCJAJ8ApQCXAHYAQAD3/5z/Mv++/kT+y/1X/e/8mvxc/Dr8Ovxd/Kb8FP2n/Vz+Lv8YABMBGAIdAxkEAwXRBXsG+AZCB1MHKAe/BhkGNwUfBNgCaQHf/0T+pPwO+475NPgL9x72efUi9SD1dvUj9if3e/gX+vD7+v0kAGACmgTCBsQIkAoVDEUNFA54DmwO7Q37DJsL1gm3B0wFqALe/wP9Lfp19+/0svLQ8FzvZO7x7Qrusu7n76Hx1/N49nP5svwaAJQDBAdOClcNBhBEEv0TIBWjFX0VrRQ3EyMRfg5bC9EH+gPz/9r70ff282nwSe2u6rDoYefO5v/m9ees6RnsLO/O8uf2Vvv7/7EEVAm/Dc8RYRVZGJ0aGBy7HIAcZRtvGaoWKxMKD2QKXgUdAMv6j/WU8AHs/eeo5B7id+DB3wXgReF545Pmfuod70306fnF/7MFhwsRESYWnBpPHh8h9CK8I3AjDSKcHy0c2Re+EgMN0wZeANX5avNR7bvn0+LD3q3bqtnO2CLZp9pT3RXh0eVm66rxbPh6/5wGnA1DFFsatB8hJH4nrymfKkUqoCi6JaYhgxx2FqsPWAizAPn4ZPEx6pnj0N0F2WHVAdP80VzSINQ/16PbK+Gv5/7u4PYa/2sHkw9SF2oeoyTKKbYtRDBfMfswGC/CKxEnJSEsGloS6gkdATj4fu81557f9thy0z/PgsxQy7jLuM1D0UHWjtz6403sSPWm/h8IaRE7Gk8iZilGL8AzrTb1N4s3cDWwMWcsvCXfHQ0ViAubAZH3ue1f5M7bStQOzk7JMcbRxDzFcsdky/bQ/9dK4JnppfMg/rgIHRP8HAkm+i2RNJc55TxdPvE9ojt/N6YxQiqKIcEXMA0rAgb3Fuyy4SzYz8/eyJHDE8CDvu6+VcGnxcXLg9Ol3Obm+PGH/TYJrxSVH5MpWjKlOTg/5kKQRCZEqUEpPcc2sy4qJXMa4A7MApT2luov37rUicvmww2+L7psuNS4ZrsSwLTGHc8M2TbkRfDd/JsJHRYCIuwshTaAPp5ErEiKSiVKf0epQsc7DDO6KCAdlxB+Az32OenY3HvRfMcqv8e4ibSRsvGyqrWousfB0sqE1Yzhje4j/OUJaBdDJBIwdjodQ8NJMk5FUOlPH036R6BASDc4LMYfUBI/BAD2AOit2nDOqMOsusOzJa/3rE2tJ7BwtQO9psYR0uve0uxb+xUKjxhXJgEzKj55R6VOc1O9VW1VhFIYTU5FYzuhL2IiDBQNBdz16+ax2JzLE8BytgWvB6qip+un4KpvsG24nsK1zlXcF+uH+i0Kkhk8KLk1oEGRSz9TbFjsWqxaqlf9Uc1JWD/vMvAkxhXoBdH1++Xj1gDJvrx9spCqNaWYos+i3KWoqwe0vL51y8/ZXemn+SwKcBryKTg41ERiT45XF13QX6JfjFylVhdOJEMgNm0nfhfNBt31L+VG1Z7Gq7nRrmimsaDcnQCeHqEgp9ivBrtUyFvXqOe9+BQKKht3K306xkfpUo9bcmFkZEpkJmELWypSxEYwOdgpMRm7BwD2h+TY03fE3LZwq5CigJxymYCZqpzbouOrf7dVxfvU+eXL9+YJwBvMLIY8ckojVj5feWWjaKFocmUtXwBWMkocPCws2xqwCDn2A+Sc0o3CU7RdqAqfpJhelVOVhZjeniyoKrR8wrPSU+TT9qMJMhzwLVI+10wPWZhiKGmKbKJsbmkFY5dZbE3hPmcufByrCYb2ouOQ0d/AEbKZpdqbIZWkkX6Rs5Qsm7ekDLHMv4bQuOLX9UwJghzjLuE/9U6qW51lfmwXcEtwFm2QZupcblB8QYYwEB6oCuf2Y+O10G+/GLAnowKZ+pFFjgOON5HJl4ehJ65IvXbOLOHY9OIIsBymLzJByVDzXUhod29Gc5dzZnDKafZfNVPoQ4YylR+oC1n3RuML0D2+aK4HoYSWMI9Gi+aKFI64lJ+ef6v0uobMr9/Z82cIvBw4MEVCVFLpX5lqEXIVdoV2W3OxbLhivVUkRmU0CSGmDNz3SuOQz0m9Aq07n2CUxoypiCmITYv8kQOcF6nRuLnKRN7b8t0HqBybMBpDlVOLYY9sSnSBeBB583VBby1lBFgsSB82aSKjDW74beNFz5K856vEnZmSvopvhs+F5IiYj7aZ8abkthLJ79zh8UUHdhzPMLJDi1TXYiduInaIejh7K3h4cVJnCFr/SbM3tCOaDgz5r+Mozxm8FqujnDCRGImahNqD3YaOjbqXEaUttZLHsNvs8KAGJhzVMAxEN1XOY2FvlXcqfPt8AXpUcyVpxFuYSx455iSMD7b5DeQ5z927j6rWmyWQ14csg0uCOYXiixGWeaOxszzGitr/7/EFuhutMCpEmFVwZD1wpHhkfVZ+c3vRdKNqOF33TF46/iV1EGr6h+R3z927U6pgm3iP+oYmgiSB+oOUir6UKqJxshPFgNkb7zoFMxtbMA1EsFW8ZLpwT3k2fkl/gHzvdctrYV4YTnE7+iZTESX7GuXfzxi8X6o+myqPgoaJgWWAIYOmicKTKKFusRjElNhD7nsEkxrdL7VDgFWzZNlwlHmfftJ/JX2tdptsPV/7TlM81yclEub7xuVx0Iy8tKpxmzqPb4ZUgRGAroIZiR+Tc6CssE7Dxtd47bgD3Bk3LyRDCFVXZJtwdHmffvJ/ZH0IdxFtyl+dTwU9lCjoEqv8iOYq0Tm9T6v3m6iPwYaJgSaApILviNaSDKArsLXCGte87PECEBlqLlxCSVSnY/9v8Hg2fqh/O30BdyxtCWD8T4Q9LymcE3P9XucK0h2+MKzPnHKQeIcmgqWAAYMoieiS95/ur1HCkdYR7CoCMBh4LV5BRlOmYgdvCHhlffR+qXyXdu1s9l8YUM49pik9FDr+R+gO0zW/Va35nZiRkYgqg46BxoPDiVWTMqD0ryHCLdZ662MBPxdjLCxAAFJVYbRtvnYtfNd9sHvJdVJskl/vT+I99ynKFAD/QOk01IDAvK5xnxeTDIqWhN+C84TCih+UvqA/sCjC7tX36p4APhYsK8g+eVC2XwlsE3WOelJ8UHqZdFpr3V6BT789IipCFcL/SOp71fzBYrA3oe6U54tnhpiEh4YkjEOVnaHQsGfC19WL6uD/LxXXKTU9s07KXQZqCHOLeGZ6iXgGcwhq1V3NTmU9JSqjFX4AXOvf1qbDRrJHoxuXII6biLeGgIjojcSWzqKosd7C6dU26ib/FhRlKHQ7sUyWW69noXAmdhR4XnYScVpoe1zSTdI8/inrFTQBe+xe2HzFZrSfpZuZtZAxizqJ3YoMkJ+YUKTGso3DJdb76XX+8xLYJok5dkoaWQdl321gc191z3O+blJm0FqRTAU8rikZFuABoe332XvHvbY9qGyco5MnjiCMnI2QktOaJKYqtHfEi9ba6c39yRE0JXY3A0hbVg9ixWo8cEly4HALbPFj1FgKS/86MiksFoICzu6n26HJSrkdq4qf6JZ4kWWPvJBylWCdSKjUtZnFHNfV6TH9mhB6Iz41XUVaU8teV2e9bNVukW37aDlhiFY9ScA5iigiFhgD/+9r3evLCbw9rvOif5ojlQeTOpSvmESgvKrEt/XG2tft6aP8aA+tIeMyhkIcUD5bl2PmaAZr5mmRZSpe7VMrR0c4tyf7FZ8DMvFA31bO976ZsaKmZ54lmQOXEphGnH2jfa34uYvIxNgj6iP8NQ7PH2kwgT+kTG1XiV+8ZN5m4WXPYchaBVHURJU2tya2FRcEZPIl4d/QEsIttZWqmqJ4nVabQpwzoAini7BwvFnK2tl46rP7Aw3kHdItUjz1SFlTMVtAYGFihmG3XRRX0007Qqo0iiVRFX4ElfMW44PTVMX2uMeuFqcbovufxqBzpOOq47Mqv2DMHdvt6lX71AvtGyEr/DgTRQlPk1Z4W5Rd2VxOWRJTVkphP4gyMiTNFNMEwfQS5T/WvMjwvDWz1asHp/Ckm6UEqQyvgrckwp3Oi9yB6wr7qwruGVsogzUCQX9Ks1FoVnpY3VeXVMROlEZHPC8wrSIpFBUF6PUV5xDZRcwXwdq31LA6rC6qvarhrX6zaLtexRHRJt427NL6iAnoF4El6zHHPMFFlkwTURhTllKVTy5KjULvOKEt/CBjE0IFBvcd6fLb7M9mxbG8DravsbOvKLAHsze4j7/UyLrT7d8L7bD6bgjeFZciNy5kONJAQEeAS3JNCU1MSlJFRT5bNd4qIB9+ElkFG/gn6+PerNPaybbBfrtgt3m11rVxuDS998OEzJbW3eEB7qP6XwfUE6EfayrfM7c7t0GyRY1HO0fBRDZAvjmPMeonGx13EVsFJPkx7d7hg9duzuXGIMFJvXu7w7scvnDCm8hs0KPZ+OMY7636XAbKEaAciiY9L3U2/zuwP25BMEH4Ptw6/jSMLcUk7BpQEEUFIfo57+LkbNsf0znM7sZkw7XB68ECxObHeM2I1N/cOuZP8M/6ZgXFD5oZmiKAKhExHTZ9ORs77Tr2OEk1BjBWKXEhlRgJDxcFD/s88evnZN/n16zR48ytySHISMgfypTNidLX2EngpOim8Qj7gATFDZAWnB6uJZArFjAgM5g0dzTAMoIv2yrwJPIdGRaiDdIE7vs48/bqZuPB3DrX+dId0LnO1c5u0HPTzNdU3d3jNOsd81r7qQPNC4UTlhrMIPYl8CmeLOwt1C1aLIspgSVdIEkadxMdDHQEu/wr9f/tb+er4d7cLNmv1njVjNXp1oHZPN384Zrn5+2y9MT75QLgCX0QjBbdG0kgsSP8JRwnCifKJWkj/B+gG3oWshB5Cv4Ddv0S9wTxeuue5pPid99e3VjcaNyL3bbf1eLM5nzrvPBk9kb8MwL/B3sNgBLmFo4aXR1BHy4gHiAXHyEdURq+FoYSzQ24CG8DHv7t+AP0hu+X61To0uUk5FPjY+NP5A/mkejA64DvsvM0+OH8lQEsBoIKdg7sEckU+xZyGCcZFhlEGLkWhBS6EXIOyArbBsgCsv64+vf2jPOR8BvuOuz76mPqduov64bsbe7T8KPzxPYe+pX9CwFpBJQHcwrzDAEPjxCWEQ4S+BFYETUQmw6ZDEEKqAfjBAkCMv9y/N75i/eI9eTzqPLc8YPxnfEm8hbzZPQC9uL38/kj/GD+lwC4ArQEegb/BzkJIAqxCukKygpZCpsJmQheB/UFbQTSAjIBnP8Z/rb8fvt4+qn5F/nD+Kz40fgs+bn5cPpI+zn8Ov0//kL/OAAbAeQBjgIVA3cDswPKA74DkwNMA/AChAINApMBGwGpAEQA7/+s/33/Yv9b/2b/gf+p/9j/CgA8AGkAiwCgAKQAlQByADoA8P+T/yn/tP46/sH9Tv3n/JT8WPw5/Dv8Yvyt/B/9tf1s/kH/LAApAS4CMgMuBBUF4QWHBgAHRgdSByIHtAYIBiIFBgS6AkkBvv8h/oH87fpw+Rn49PYN9m71HvUk9YH1NvZA95v4PPoa/Cf+UwCQAskE7wbtCLMKMgxaDSAOfA5mDt0N4gx5C6wJhgcWBW0Cov/G/PL5Pfe89IbyrfBD71Xu7e0T7sfuB/DM8Qv0tfa2+fn8ZADfA0wHkgqUDTsQbhIbFDEVphVyFZUUERPwEEAOFAuCB6UDnP+D+3z3p/Mi8AvtfeqN6E3ny+YM5xPo2elU7HTvIvND97j7XgAVBbUJGg4gEqcVkRjEGi4cvxxxHEMbOxlnFtkSqw78CfAErf9a+iL1LvCm66/naeTy4V7gvd8W4Gvhs+Pf5trqhu/C9GT6QwAxBgEMgxGMFvMalB5QIQ8jwSNdI+MhXB/ZG3MXSRKDDEwG0/9K+eXy1exL53Tid95324zZydg32dXamd1x4UHm5us28gD5EQA0By8OyxTVGhwgdCS5J9AppSovKm4obiVCIQoc6xUUD7cHDgBV+MbwnukV41/drNgh1d7S9tF00lbUkdcO3K3hROih7473zP8bCD0Q8Bf4HhwlKir6LWowZTHhMN8uayueJpogjRmrETEJXwB798jui+YG33TYC9P2zlnMScvTy/TNoNG71iLdo+QH7Q32cf/oCCoS7xrxIvAptC8ONNk2/TdvNzA1TjHmKx8lKx1IFLcKxAC89uzsoOMj27jTms37yALGyMRaxbbHy8t+0aTYCOFp6oH0Av+ZCfYTxh2+JpQuDDXvORY9Zj7SPVs7EzcXMZQpwyDmFkkMPQEZ9jLr3eBt1yzPXMg0w9+/eL4Ov5/BGcZbzDnUdd3L5+vygP4vCp4VdCBbKgUzLjqaPx5Dm0QFRFxBszwrNvUtTySDGeINyAGR9ZvpRt7p09bKV8OnvfW5X7j1uLW7jMBXx+PP79kw5U7x7f2pCiIX9iLHLUA3FT8JRepIl0oCSixHKkIeOz8yzicdHIMPYwIk9Sno2tuX0LnGjr5XuEi0grIVs/+1LLt2wqfLedaZ4qvvSf0JC4IYSyX+MEA7v0M4SnZOVVDFT8hMckfrP2w2OyuvHikRDwPR9NvmnNl6zdbCBLpKs96u5axxrYCw/LW+vYrHFtMK4APulfxOC70Zcif/MwQ/KEgjT71Tz1VIVSlSiEyORHk6ky45IdESygOZ9LPljdeVyjK/vbWCrrqpjqcQqD6rArExuY7Dys+H3Vvs1Pt5C9MaaSnINohCTEzHU7xYAluHWktXZlEDSWE+0jG2I3kUkQR69LDkrtXpx867vLEEquKkgaL1oj2mQqzWtLm/mMwR27PqB/uMC8QbMCtXOctFKVAfWG1d6V99XylcB1ZETSJC9TQkJiAWZAV19NLj/9N4xa24Ba7TpVigwp0lnoKhwKewsA+8hcms2A7pLvqFC48cxiyrO8pIu1MoXM5hf2QlZMBgaFpOUbZF+TeAKMIXQgaH9BnjgtJCw9G1maryoSGcVZmlmRGdgaPDrJK4k8Za1m/nTPlnCzUdKi7CPYJLAFffX9tlwmh8aAplhV4dVRpJ2TrGKl4ZJwew9IbiNtFKwTyze6dknj+YPZV4le+YiJ8TqUa1xcMf1NflY/gzC7cdXS+bP/RN9llCY5BprWx+bARpWGKtWEtMkz31LPEaEwjv9BbiHdCPv++wrqQtm7eUgJGikR6V2pukpTCyH8H+0UnkdffqChQeXTA3QR1Qm1xOZutsPXAocKts4GX6W0ZPJEAJL3kcBAlC9crhNc8TvuuuMqJNmIqRHo4mjqOReph5olOvpL74z8jigvaNCk4eLDGTQvtR7V4Baepvb3N1c/pvF2kCXwZSiEL/MPMd+Amp9aHhf87WvDGtCqDHlbuOG4sHi4CObJWWn7GsWLwRzlXhjvUdCmYeyjGxQ5BT62BZa4lyQXZkdu9y/GvAYYlUvUTWMl4f7Qoh9pvh+s3Yu8KrNp6dk0yMeohJiLmLspL+nE6qPLpMzPPfmfSdCVweNjKPRNlUlGJVbcd0sXjyeId1i24xZMtWv0aJNLYg4Aup9rXhps0Zu5+quJzQkT6KPYbthVGJT5Czmi2oU7iryqXep/MNCTIecjIvRdZV52PzbqN2vHoce8B3wXBUZstYjUgXNvoh0QxA9+7hgc2ZusepkJtikJSIZYT1g0mHRo65mE+mobYwyWzdufJvCOkdfzKQRYlW5GQycBt4YHzgfJZ5nHImaIVaI0p+NycjvA3k90bijM1WujqpvppSj0+H9IJkgqOFmYwRl7mkKLXex0vc0PHGB4MdXjK0RfBWi2UTcS55nX0+fgp7GnSjafdbf0u7ODwkoQ6T+LvixM1RuvmoQpqhjm6G64E7gWKES4u+lWuj6bO3xkTb8PASBwAdDzKbRQxX22WUcdx5cn4zfxh8OXXLaiBdoEzMOTUlfA9L+UvjKc6IugGpHZpPjvOFS4F6gIeDW4rBlGii57K9xVnaGvBWBmMclTFHRd9W1mW2cSR63n6/f8B8+HWca/1dgk2uOhImTRAK+vXjuM76ulOpTZpcjt6FE4EjgBODzYkclLKhJLLyxIvZT++UBa4b8TC4RGlWfGV6cQd64X7hfwF9VnYVbIxeJk5hO88mERHQ+rbkcc+lu+2p0ZrIji2GRYE1gAWDoInRk0qhobFYxN7Yku7MBOEaJDDwQ6xVzWTgcIV5e36af9p8UnYzbM1eiE7iO2wnxhGY+43lUdCJvM2qqZuQj+KG4IGygGCD1YnfkzChYLHxw1LY5e0DBP8ZMS/xQqhUzWPpb594rH3pfkx863X3a75eqE4wPOcnaxJj/HnmV9GivfOr0py1kPmH44KXgSKEbYpJlGehYrG9w+nXSu04AwsZGS69QWFTe2KXblZ3dXzOfVZ7InVga19ehE5JPD4o/RIt/XbngdLwvlutS540knOJTITmgkuFaIsNle6hqLG+w6XXwexuAgUY3ixWQNhR2mDrbKt12XpMfPp59nNvaq9dHE4tPG8oexP1/YPozNNwwAWvE6AMlE6LHIachNuGxYwtlseiMrL2w4fXTuyoAfEWgyu+Pg5Q7V7naqFz13hiejd4aHIiaa5cb03aO3ko5BO6/p7pNtUfwu6wJqI7loiNT4i5htCIhI6nl/GjArNkxJDX8evmANAVCir4PAhOtVyOaDlxcnYTeBB2eXB7Z1xbfUxQO1woNRR4/8Xqvdb8wxKzgqS9mB2Q5Io6iSmLo5B7mWulF7QKxcLXq+srAKMUdSgGO8ZLNVrjZXZurXNhdYVzKm56ZblZRUuOOhYobhQuAPbrX9gDxnC1JaeRmw2T2Y0djOWNIZOomzancbXpxR3Yf+t5/28TxybqOExJcFfnYlpriXBNcppwfWshY8ZXyEmTOaYnjRTcAC7tGdozyAW4DKq0nlSWK5FgjwCR/JUtnlGpELcAx6LYbuvR/jQSAiWoNp5GaVSfX+lnCm3bbk9tdGhwYIRVBkhgOAsnkBR/AWvu6duHys26M60hou6Z1pQAk3mUM5kIobqr9LhPyFLZeOs1/vQQKCNCNL1DI1ENXCdkM2kNa6hpEGVqXfRSAEb0NkYmeBQVAqzvy93+zMW9lrDXpdmd2Jj7lk2Yw5w4pHCuHLvXyS3an+um/bMPPSG7Ma5Aok01WBVgB2XnZqhlVWESWhhQt0NRNVUlQhScAu7wvt+Uz+rAM7TQqRCiLZ1Mm3mcqaC5p3Kxhr2WyzPb5Osm/XEOQx8XL3M96kkbVLlbimBsYlJhRV1oVvFMLEF1Mzkk7xMUAy/yv+FG0jnEBrgKrpCm0aHwn/mg4qSLq760MsCNzWXcR+y2/DENPB1YLBE6/UXCTxZXwVugXalc41hvUoFJYD5jMfIifBN8A23zy+MR1a7HC7yAslWrwKbjpMqla6mpr1G4HsO6z8LdyexY/PYLKxuBKYo24UEwSzFSrlaHWLFXM1QsTstFVTscL38h6xLQA6b04OXy10bLPcAtt1qw9ashqueqQa4RtCm8R8Yc0krfau0N/MAKExmXJuMymT1oRg1NV1EmU25SOU+gSdJBDTifLOIfOhISBNj1++fl2vvOmsQOvJq1bbGlr02wX7PAuEPArcmz1P3gK+7V+5EJ9habIx8vKjlvQbFHwEuATeZM+EnQRJg9ijTvKRoeaRE+BAL3Gero3czSG8kewRG7Ibdrtfi1wrixvZ3ETc1819niC++z+20I1xSSIEMrlzRKPCBC70WbRxtHdES+PyA5zzANJykceBBWBCH4OOz34LTWvs1YxrrADr1tu+G7Zb7iwjLJI9F22t7kDPCn+1MHuRJ+HVEn5i/9NmA86D99QRNBsz5wOm003Sz8IxAaaA9XBDX5Vu4P5K/afdK3y5HGLsOnwQbCRMRNyADOL9We3QvnLPGx+0cGnRBjGk4jGiuMMXU2sTkpO9Q6uDjoNIQvuSi9IM8XOA5BBDr6b/At57neVdc30Y7Me8kTyF/IWcrvzQPTa9nz4F/pbPLS+0gFhg5DFz4fOCb+K2YwTzOlNGI0iTIsL2gqZSRSHWkV6QwUBDH7g/JN6s7iQNzT1q7S8c+tzunOoNDE0zfY1t1z5NjryvML/FoEdwwjFCQbRSFXJjcqxyz4LcItKyxBKR4l5B++Gd4SewvPAxf8jfRt7evmOuGE3OvYidZt1Z3VFNfF2ZjdbOIa6HTuR/Vc/HwDcQoFEQUXRBycIO0jICYmJ/smoiUqI6gfOhsEFjEQ8AlyA+z8jfaJ8AzrP+ZH4kDfPt1O3HbcsN3w3yLjKufn6zLx4PbF/LECdwjsDeQSPBfSGo8dXx82IBIg9h7uHAwaahYmEmMNSAj+Aq79gfie8yzvS+sW6KblCuRM427jbeQ95s/oC+zV7w/0lvhG/fkBiwbaCsUOLxL/FCIXiRgtGQwZKhiQFk4UeREoDncKhQZxAlz+Zfqq9kjzV/Dt7Rns5+pf6n/qRuup7JzuC/Hj8wr3Z/rf/VQBrwTUB6wKIw0nD6sQpRESEvARRBEXEHMOagwMCm4HpgTMAfb+Ofyq+V33YfXF85Py0PGB8aTxNvIu84P0KPYM+CD6UvyP/sUA5ALcBJ0GHAhPCTAKuQrqCsQKTAqHCYAIQQfWBUsErwIQAXr/+v2b/Gb7ZPqb+Q75v/it+Nb4NvnH+YH6XPtO/E/9Vf5X/0wALQHzAZsCHwN9A7YDygO7A44DRQPnAnoCAwKJAREBoAA8AOn/p/96/2H/W/9o/4T/rP/c/w4AQABsAI4AoQCkAJMAbgA1AOn/i/8f/6r+MP63/UX94PyO/FT8OPw9/Gb8tfwq/cP9ff5U/0EAPgFEAkgDQgQoBfAFkwYIB0kHUAcbB6gG9wUMBewDnQIpAZz//v1f/Mz6Uvn/99/2/fVk9Rz1KPWM9Un2Wve7+GL6RPxV/oMAvwL4BBsHFQnWCk4Mbw0sDn4OXw7MDcgMVwuBCVUH3wQzAmX/ify3+QX3ivRb8orwKu9H7uvtHO7c7ifw9/FA9PL2+vlB/a4AKQSUB9UK0Q1uEJcSOBRCFagVZhV7FOkSvBABDssKMgdQA0X/LPso91jz3O/P7E3qa+g758nmG+cx6Afqkey973bzn/ca/MMAeQUVCnQOcRLrFccY6hpCHMEcYRwgGwcZIhaFEkwOlAmBBDv/6fm19MjvS+ti5y3kx+FH4LvfKeCS4e7jLec36/HvNvXg+sEArwZ6DPQR8RZJG9gefyEoI8MjSCO3IRsfhBsMF9QRAgzDBUj/wPhf8lns3OYW4i3eQ9tx2cfYTtkF2+HdzuGy5mfsw/KV+aoAywfADlIVThuCIMQk8SfuKagqFio6KCAl3SCQG2AVew4WB2r/svcp8AvpkuLw3FTY5NS90vPRj9KO1OXXe9ww4troRvA7+HwAywjmEI0YhB+TJYgqPC6OMGkxxTCjLhErKSYNIOwY+xB3CKL/v/YT7uPlcN7116bSsM4zzEXL8cs0zv/RONe43U7lwu3T9joAsAnrEqIbkSN4Kh8wWTQCNwI4TzftNOkwYiuAJHYcgRPmCe//6PUf7OLiedoo0yjNq8jWxcPEe8X8xzbMCdJM2cfhO+te9eT/eQrOFI8ecSctL4Q1RDpFPWw+sD0RO6M2hTDkKPofChZgC08ALfVP6grgsdaMzt7H28Kuv3G+Mr/swY3G9Mzx1Ejesujf83r/JguMFlEhISuuM7M6+D9SQ6NE4EMMQTk8izU1LXMjkhjkDMMAjvSi6F7dGdMmysvCRL2+uVa4G7kJvAvB/cer0NXaK+ZY8v3+twsmGOgjny74N6c/cEUjSaFK3EnWRqZBcjpuMeAmFxtvDkgBC/Qa597atc/5xfW967cMtHeyPLNYtrS7KcN/zHDXqOPJ8G7+LQybGVAm6DEIPF5EqUq1TmFQnU9tTOZGMz+MNTwqlx0AEN8Bo/O45Y3Yh8wHwl+51LKbrtismq3esIy2fL5wyB7ULOE279D9hwzqGooo+zTaP9NInU8CVN5VH1XJUfRLy0OLOYMtDiCVEYUCV/N85GvWkclUvgy1A65yqX6nOqigq5qx+rmCxOLQut6g7SL9xgwTHJQq1DdtQwNNSlQHWRNbXVrnVspQNUhnPbMweiIrEzoDJfNm43rU1cbiugCxfKmUpG+iH6OjpuCsqbW6wL/NVdwK7Gf86gwWHWwsczq+RutQq1i+XfxfUl/CW2VVbUwbQcgz2CTAFPsDDfN34rvSVMS0tz2tQqUEoK2dUJ7soWWojLEbvbnK/9l26qD79gzzHRIu1jzKSYhUvFwlYpZk+mNVYMBZblCkRL42JSdSFsgEDvOt4S7REMLLtMapWaHHmz2Z0Jl+nSukp62oudTHvNfm6M766AypHoYv+z6PTNhXfGA3ZttoUmidZNddNVT/R5I5XinfF54FJ/MK4dPPCsApsp6mxJ3glyOVopVdmTig/qlnthHFjtVd5/T5www6H8cw4kAMT9ha52PyaclsVGyVaKdhvlcnS0E8gCtlGXwGWPOM4KzOQ77Rr8ejhJpSlGKRzJGOlY6clqZZs3bCeNPc5RP5iAylH9UxiUJAUYZd+2ZTbV1w/m86bCplBVsZTsg+iS3hGmAHnvMz4LfNu7zCrUKhnZcfkf2NT44UkjKZcaODsATAfdFm5C34NwzsH7Ay8UMpU+FftWlXcJJzTXOIb19oCF7SUCRBdi9QHEgI+PP+3/bMc7v+qxGfEZVLjveKL4vyjiaWkqDorb+9n8/94kP30wsPIFgzGUXHVOdhE2z7cmh2PXZ8ckFrwmBPU1FDRDGxHTIJZvTt32fMa7qHqjad4JLXi1OIb4gsjG6T/p2Kq6q74s2k4Vj2XAsPIM4zAUYYVphjFW4+ddp4zXgUdc5tMGONVU5F8DIBHx0K5fT+3wnMo7lcqbGbDZHFiRKGEYbDiQ2Rtpttqce5R8xd4G711QrtHxM0qUYeV/JkuW8ed+h6+HpNdwNwUWWJVxdHeDQ/IAYLdfUw4N3LG7l9qIKamY8XiDeEGIS6hwSPvZmSpxm40soq34b0PgqsHyc0EUfWV/Rl/XCaeJB8v3wled5xIWdBWalI2zVnIewLEvaB4OHL07jqp6uZhI7OhsOChIIUhleNFpj+paK2g8kO3qPzmglLHws0OkdDWKBm4nGxedB9H36aelxznmiyWgNKFDd3IswMvPbx4BTMyLijpyuZz43phbeBWIHShAiMw5axpGW1X8gK3cby6gjMHsEzJkdkWPVmZ3Jjeqh+Fn+qe310xmnaWyNLIzhvI6UNcfd94XXM+7iopwGZeo1rhROBlYD0gxeLxpWuo2S0Zscg3PLxMQgyHkoz1UY6WPNmjXKuehd/pX9UfD11mGq3XAZMBjlKJHUOL/gl4gLNa7n3py6ZhI1ThdmAO4B+g4aKH5X2oqCzmsZT2yjxbwd+HacySEbGV5tmU3KTehx/yn+XfJ51E2tJXatMujkJJTkP9Pjm4rrNFbqPqLGZ7Y2ghQmBS4Bug1eK0ZSMohuz/8Wk2mrwpwaxHNsxgUUKV+5lu3EUerh+hX90fJx1NGuMXQ9NPTqoJfAPvvm+45vO+LpvqYeatY5ShqGBxYDFg4mK3ZRvoteylMUV2rrv2wXOG+YwgUQGVu5kxXAveex91n7oezl1/GqCXTNNjzomJpgQjPqs5KLPE7yVqrGb2Y9oh6GCqIGEhB6LQpWiotSyW8Wo2RvvDQXWGswvS0O+VJxjc2/nd7d8v332enN0amonXRRNrTqCJi8RW/ut5c/QY70ArCudWJHiiAmE9IKqhRSMApYkoxSzV8Ve2Y3uPgTMGY0u4UEyU/phx209dhx7P3ydeUxzfWl9XLJMmDq6JrMRKfzA5h/S576srfSeMZO8iteFqIQ2h22NG5f2o5izh8U42RLucQOxGCwtREBlUQpgwmszdBx5WHred8NxNmiDWw1MTDrMJiQS9fzi55DTnMCZrwqhYZX2jAmIwoYniSaPj5gYpWC07sU52aztpwKIF6wreD5aT89dZ2nLcbl2DHi7ddlvlWY4WiNLyzm4Jn4SvP0R6R/Vf8LDsWuj5peMj56KQIl8iz+RXJqLpmy1isZh2V3t4gFTFg8qfzwSTUpbuWYHb/RzXHU1c5BtnGSeWPVJEzl8JsISfv5M6srWjsQntBKmvZp9kpKNIYwzjreTgpxNqLy2Xsex2SbtJQEUFVcoWjqSSoBYumPqa9FwS3JNcOpqSmK0VoJIIzgYJuwSN/+P647Yx8bDtv+o453FleOQYY9KkYyW/55eqlC4acgq2gjtcADNE4cmDjjbR3JVbWB3aFJt224Hbedno198VMxG/TaLJf0S5//Z7GnaJsmUuSysVaFimY+UAJO+lLyZ0aG9rCm6q8nM2gTtx/+AEqIknjXxRCVS1lyxZHppD2tlaYpkplz3UdJEnzXTJPMSigAo7lncqMuWvJivEKVQnZGY+JaOmEWd+KRor0O8JcuY2xztKP8wEakiCzPXQZxO+FicYE5l62ZpZdZgVlkmT5ZCCjTyI84SIgF571reSs7Hvz6zEKmLoeecR5u1nCShcKhesqC+1syO3FDtmP7fD6AgWTCRPtpK11Q8XNBgcmIYYc1ctlULTBlAPjLmIosSqwHK8GrgCtEiwxq3Ua0Qpo2h6Z8woValN6ydtT7BvM6v3aLtF/6ODokejC0iO+RGeFCUVwRcp11zXHNYyFGoSFw9PDCwISsSJAIa8ofi5NOkxiq7z7HZqn2m26T9pdepS7AjuRrE2dD73hHupv1ADWccpiqON71C3UuqUu9WkFiAV8tTj00ARWA6BS5QIKwRjAJm863k1dZJymi/hbbkr7WrGKoWq6WuqLTuvDTHKtNw4J/uR/33Cz0aqifYM2k+DEeATZZRL1NCUthODkkUQSg3myvGHg8R4QKs9Nvm2tkOztDDb7sqtS+xm694sLyzTLn6wIrKrtUP4kvv+/y0Cg0YnSQFMO05CUIeSPxLik2+TJ9JSUToPLYz/SgTHVMQIwPq9Q3p79zv0V/IicCouue2YLUethe5Mr5GxRjOZNjX4xbww/x6CdoVgSEYLE012TyGQihGpkf3RiNEQz9+OAwwLyY2G3gPUQMf90DrEeDn1RDNzsVZwNe8YrsDvLK+V8PNyd7RStvH5QHxofxKCKYTWh4VKI0wgTe+PB1Ah0H0QGo+ADrbMywsMSMzGX4OaQNJ+HTtPeP02d7ROcs3xvvCnMEjwonEt8iMztfVXt7e5wryk/wnB3QRKhsAJLErBTLLNuI5Mzu4Onc4hDQBLxkoByAIF2YNawNm+aTvb+YQ3sXWxdA9zE3JCch5yJbKTs6A0wLan+Eb6jLznfwRBkYP9hfdH8AmaiyzMHszrzRKNFAy1C70KdcjsRy5FC8MVgN1+s7xpek54sDbbdZm0sfPo87/ztbQFtSk2FreCuV97Hj0vfwKBSANwBSwG7whtiZ6Ku4sAS6uLfkr9Ci4JGkfMhlFEtoKKgN0+/Hz2+xp5szgLNys2GXWZNWw1ULXDNr23d7inOgC79z19fwTBAILixF9F6oc7SAnJEEmLifqJnkl6SJSH9IajRWvD2cJ5wJi/An2DvCe6uLl/eEL3x/dR9yG3NbdK+Bw44jnU+yo8V33RP0uA+8IWw5HE5AXFRu/HXofPSADINMeuBzFGRUWxRH5DNkHjAI+/RX4O/PT7v/q2+d85fLjRuN744zkbeYO6VfsLPBt9Pn4q/1cAuoGMgsTD3ESMxVHF54YMhkAGQ4YZhYXFDYR3A0lCi4GGQIG/hP6XvYF8x7wwO3569bqW+qK6l7rzuzL7kTxI/RQ97H6Kf6dAfUEFAjlClMNTA/FELQRFBLnETAR+A9MDjoM1gk0B2oEjwG6/gD8dvkv9zv1qPN+8sXxgPGs8UfyR/Ok9E72N/hO+oL8v/70ABADAwXABjkIZQk+CsAK6gq9Cj4KdAloCCQHtgUpBI0C7QBZ/9v9f/xP+1H6jfkF+bv4rvjc+EH51fmS+m/7Y/xl/Wv+bP9fAD4BAwKnAigDgwO5A8oDuQOJAz4D3wJwAvkBfwEHAZgANQDj/6P/d/9f/1z/av+H/7D/4f8TAEQAbwCQAKIAowCRAGoALwDi/4L/Fv+g/ib+rf08/dj8iPxR/Df8P/xs/L78Nf3R/Y7+Z/9VAFQBWQJdA1YEOgX/BZ8GEAdMB04HFAebBuYF9gTRA38CCQF6/9z9Pfyr+jT55PfJ9u71W/UZ9S31mfVc9nX32/iI+m/8gv6yAO8CJwVHBz0J+QpqDIINNw6ADlcOuw2tDDMLVgkjB6gE+AEo/0z8fPnO9lj0MPJp8BLvOu7q7Sfu8u5J8CTydvQv9z36if34AHIE2wcYCw0OoRDAElQUUBWpFVkVXxTBEocQwA2CCuIG+wLt/tX61PYK85bvlOwf6kvoKufI5irnUeg36s/sCPDL8/z3fPwnAd0FdQrNDsASLxb8GA8bVRzCHE4c+xrQGNsVMRLrDSoJEgTJ/nj5SfRk7/LqFufx457hMuC63z7gu+Er5Hvnlutd8Kz1XPtAAS0H8gxjElQXnRsZH60hQCPDIzEjiSHXHiwboxZdEYELOwW8/jX42/He62/muuHl3RHbV9nG2GfZN9sq3i7iJOfp7FDzK/pCAWIIUQ/YFcUb5yATJSgoCiqoKvspBCjQJHUgFBvTFOENdAbF/g73jO966BHig9z/16nUn9Ly0azSyNQ72OvctuJy6evw6fguAXsJjxEqGQ8gCCbkKnsurjBqMaYwZS61KrIlfh9KGEsQvQfk/gP2X+085dvdd9dE0mzOD8xEyxLMds5h0rfXUN775X7umfcEAXgKqxNUHC8k/SqIMKE0JzcEOC03pzSCMNwq3yO/G7oSFAkZ/xT1VOsm4tLZmtK5zF7IrsXAxJ/FRsijzJfS9tmI4g3sPPbFAFkLpBVWHyIowi/6NZU6cD1vPoo9xDowNvAvMSgvHywVdwpi/0H0bek53/bV7s1ix4XCgL9uvlm/PMIFx5DNrNUd35rp1PRyAB0MeRctIuUrUzQ1O1NAgkOnRLhDuEC8O+k0cSyVIp8X5Au//4vzqud43E3SeclDwuW8i7lRuEW5YLyNwabId9G82yjnYvMMAMUMKRnYJHUvrTg2QNRFWUmnSrFJfUYgQcI5mzDvJREaWg0tAPLyDebk2dfOPMVgvYO307NwsmiztLY/vN7DWs1p2Ljk6fGU/1ANsxpUJ9AyzDz5RBZL8E5oUHBPDUxXRnc+qjQ6KX0c1g6vAHXyl+SA15fLO8G+uGOyXa7QrMetQLEgtz2/Wcko1U/iavAK/74NFhygKfM1rUB6SRNQQ1TnVfFUZFFcSwRDmzhxLOIeVxBBARXyR+NM1ZHIer1ftImtL6l0p2ioB6w2sse6ecX80e/f5+5w/hEOUh28K904T0S2TchUTVkfWy1aflYrUGNHaTyRLz0h2xHjAdDxHuJJ08TF+rlHsPmoSqRhok+jDqeErYC2vsHozprdY+3H/UgOZx6lLYw7rUepUTJZCl4LYCJfVVu/VJFLEUCXMosjXxOSAqbxHeF50TTDvrZ5rLektZ+dnYCeWqIPqWyyKr7wy1Tb3+sS/WUOVR9cL/09xkpRVUxddmKnZMpj5V8TWYlPj0OANcgl4RRNA5bxQ+Dcz+HAyLP4qMagc5sqmQCa753bpJCuw7oYyR/ZX+pR/GgOGyDfMDBAmE2rWBRhjmbvaCFoKmQlXUlT30ZIOPQnYBYUBKDxkN9zzs6+G7HGpSidhpcNldOV0ZntoO+qi7dhxv/W5OiF+1IOuyAuMiRCIVC1W4ZkT2rgbCRsH2jvYMtW/knsOgkq1xfjBMHxBN8+zfq8t67louGZ85NJkfuRBJZHnY2nhrTQw/XUcOey+iUONCFJM9hDX1JtXqFntW12cM9vw2tvZAxa6ExqPQcsRxm6Bfrxnt49zGa7nqxXoPOWu5DijX6OjJLumW2kt7FowQTTBebY+eENhyExNEtFU1TQYGJqvXCvcx9zEG+gZwldmk+9P+otqxqXBknyXd5vyxO60KoenmCU4o3Zil2La4/mlpOhI68rvzDRp+T5+IgNtiHkNH5G+VXeYsdsZ3OHdhB2BHKAar5fEVLjQa8vAxx3B6zyQd7WygK5UKk7nCmSaYsxiJuIpYwwlAOfyqwcvXrPV+MY+BsNwCFkNW5HU1eWZM9urnX9eKF4m3QLbSliSlTZQ1QxSx1ZCCLzSd5wyjK4HaivmlCQU4nuhTyGPIrQkb6csao/u+bNF+I295wMpyGxNR5IYFj3ZXhwk3cOe8561XY/b0dkQ1adRdcygh47Carzct48yqK3N6d6mdeOoIcPhEGEM4jIj8ea2qiVuXbM6uBU9g0MbCHMNY5IH1n/ZsJxE3m5fJd8rXgZcRZm+FcsRzQ0pB8bCkH0vt45ylO3nqadmL2NU4aYgquCi4YcjiGZSKchuCvL0t929W4LESG2Nb1IkVmwZ6xyLnr8ffl9I3qYcpJnZ1mESGs1sSD3Cub0KN9nykO3U6YZmASNa4WJgX2BR4XLjM+X/KXmtgnK0d6d9MIKlyBwNa1ItlkJaDVz43rXfvN+NXu6c7toj1qiSXg2piHNC5j1sd/EynO3U6bsl6uM6YTjgLiAaITZi9CW+aTltRHJ6d3L8wsK/x/8NF9IkFkKaF1zMXtJf4R/4Xt8dI9pbVuFSlo3gSKbDFT2V+BPy9+3oKYWmLKMzoSmgFuA74NHiyiWQKQgtUbIHN0B80oJTB9bNNRHHlm1ZyZzGXtRf6t/J3zfdAtqAFwrSw84QCNgDRn3F+EGzIi4NqeWmBmNGYXTgGmA3YMVi9iV06OZtKjHa9xC8oIIfx6PMw1HY1gKZ5BynHrvfml/BnzgdC9qR1yTS5U44SMZDuX38OHnzGy5Fqhsmd+NyYVpgeCAMYREi+CVs6NRtDrH2tuQ8bQHmh2ZMg1GYFcKZptxuXklfr1+fnuAdPtpQFy6S+s4YyTEDrX44eLxzYi6PKmVmgKP3oZngsCB7YTUi0GW4aNKtP3GaNvs8OIGnxx8MdZEFla4ZEpwcnjzfKl9j3q/c21p6luhSw45xCRgD4j55uMhz9u7qaoQnIGQVojNgwmDD4bHjPyWXqSFtPPGGNtZ8A4GkBs5MGhDiFQUY51uyXZZeyx8OnmccoZoRltFS/84AiXqD1z6/uR10GK9WKzbnVuSMIqZhbqEl4cajhCYKqUCtRzH7NrX7zoFcBrTLsdBuFIiYZdsv3RbeUd6f3cYcUVnU1qnSrs4HCViEDD7J+bs0Ry/Sa70n4yUaozKh9GGhInOj32ZRabCtXrH5Npp72gEPxlNLfU/p1DjXjtqVnL4dv53YHU0b6tlEFnFSUM4EiXGEAD8XueC0wbBeLBYohOXAY9dikyJ1YvikUObr6fFtg3IAtsQ75kDARinK/Q9Wk5bXIpnkW81dFF13nLxbLljflehSJU34CQUEcz8o+g21R3D4rIEpe6Z85FRjSuMh45UlGGdaakLuNbIR9vN7tECtxbmKcg700uLWYdkc2wScUJy+29Qam9hnlU5R7E2iCRLEZH98ekF117FhrX2pxidPZWikGmPmpEil9afcKuUudXJs9uj7g8CZRULKHI5FEl4VjZh/miTbdVuumxUZ9BecFOORZc1CCRpEU7+SOvr2MfHX7grq4+g3JhNlASTCpVLmqCixK1huwvLSNyR7lcBCxQZJvY2IUYjU5pdNmW8aQxrHGn/Y9xb9VChQ0Y0XyNuEQH/pOzo2lXKa7uerk+kzZxQmPuW1JjNnb2lZLBvvXbMBd2a7qoArBITJFg0/UKST7dZHWGPZepmJWVSYJZYME5yQcAyjSJYEaj/BO733ATNpr5MslWoC6GnnEib9pykoSupTrO+vxjO7N2+7goASxH7IZkxqz/HS49VuVwQYXJi2WBRXABVIUsDPwMxkiEmEUEAZu8X39LPDcIztp2slKVNoeifbaHOpeisgbZNwu/P+9797nj/6Q/UH70uMDzHRyhRDVhDXKpdOVz+Vx1Ry0dUPBIvbSDYEMwAx/BE4bvSnMVMuiKxYqpAptikNaZIqvGw+rkaxfrRNeBa7/T+iQ6hHcgrjziVQ4ZMHlMsV5NYS1deU+9MMERoOe0sHx9tEEcBJvJ847zVT8mWvuG1cq95qxOqSasOr0S1t70kyDnUl+HU74L+LQ1lG7woyzQ1P6xH703RUTRTEVJzTnlIUkBBNpQqqR3kD7EBgPO85dHYI80Kw9S6vrT2sJavprAdtNy5tcFpy6vWIuNs8CH+1gsiGZ0l6DCsOqBChkg0TJBNkkxCSb9DNDzfMgooCRw9DwgC0/QB6PjbE9Gmx/i/Q7qwtlq1R7Zvube+8sXnzk7Z1eQi8dT9hwraFm8i6yz/NWU96EJdRq1H0EbPQ8Q+2TdGL08lQhp4DkwCHfZK6i3fHdVlzEjF+r+kvFu7KbwCv9DDasqb0iDcsOb28Zr9QQmSFDQf1ygwMQI4GD1PQI5B0UAePo05RTN4K2UiVBiVDXsCXveT7G3iOtlB0b7K4MXLwpXBRMLRxCTJGs+C1iHfsejo8nb9BghKEvAbsCRGLHoyHjcPOjs7mTozOB00ei54J08fQBaTDJQCkvjZ7rTlad041lbQ7sshyQLIlsjWyq/O/tOa2k3i2Or582f92QYGEKcYeyBFJ9Ms/TCkM7Y0LzQUMnkufSlIIw4cBxR0C5gCufka8f/opOFD2wrWINKgz5zOGM8O0WvUFNng3qLlI+0n9W/9uQXIDVsVOhwxIhMnvCoTLQguly3FK6UoUSTtHqQYqxE3CoUC0fpU80vs6eVf4Nbbb9hD1l7VxdVy11XaVd5R4x/pkO9y9o39qQSSCxAS8xcPHT0hXyRhJjQn1iZNJaYi+h5oGhUVLQ/eCFsC2PuF9ZTvMuqG5bXh194D3ULcl9z+3Wjgv+Po58DsHvLZ98L9qwNnCckOqRPjF1cb7R2UH0Eg8x+vHoEcfhm+FWMRjwxpBxoCzfyq99jye+616qDnUuXb40LjieOs5J7mTumj7IPwzPRc+Q/+vwJJB4kLYQ+yEmcVaxeyGDUZ9BjyFzsW3xPzEJAN0gnYBcIBsP3B+RP2wvLm75Tt2+vF6ljqlep36/Ps/O5+8WX0l/f6+nP+5gE6BVQIHQuBDXEP3hDBERYS3REbEdkPIw4KDKAJ+gYtBFIBf/7I+0P5AvcW9YvzavK78X/xtfFY8mHzxPR09mL4fPqx/O/+IgE7AysF4gZVCHsJTQrHCuoKtgowCmAJTwgHB5YFBwRqAssAOP+9/WT8N/s++n/5/Pi3+LD44/hL+eP5o/qD+3j8e/2B/oH/cwBQARICswIxA4kDvAPKA7YDgwM3A9YCZwLvAXUB/QCPAC0A3f+e/3T/Xv9c/2z/iv+0/+X/FwBIAHMAkgCjAKMAjwBmACkA2v96/wz/lv4b/qP9M/3Q/IL8Tfw2/EH8cfzG/EH94P2f/nr/agBpAW8CcwNqBEsFDgaqBhcHTgdMBwwHjgbUBd8EtwNhAugAV/+5/Rv8i/oW+cv3tPbf9VP1GPUz9ab1cfaQ9/34rvqa/LD+4gAfA1UFcgdlCRoLhQyVDUEOgQ5ODqkNkgwPCyoJ8AZwBL0B6/4P/EH5l/Yn9AbySPD77i7u6e0y7grvbPBR8qz0bveC+tH9QgG8BCMIWgtIDtMQ5xJvFF4VqRVLFUMUlxJREIANOAqRBqYClv5/+oH2vfJR71rs8eks6BvnyeY753PoaOoO7VPwIPRZ+N78jAFABtUKJQ8PE3EWLxkyG2ccwRw7HNUamRiUFdsRig3BCKIDWP4I+d3zAO+Z6szmt+N34R7gvN9U4ObhaeTM5/bryfAi9tj7vwGqB2oN0hK3F+8bWh/YIVUjwiMYI1ohkh7UGjkW5RD+CrEEMf6s91fxZOsD5l/hnt3h2j/ZyNiC2Wvbdt6P4pjnbO3f88D62wH4COEPXRY7HEkhYCVcKCQqpirdKcsnfiQMIJYaRRRHDdIFIP5r9vDu6ueR4RjcrNdx1IPS9NHL0gXVk9hc3T3jCuqR8Zj54AEqCjYSxBmYIHsmPiu4Ls0waDGEMCQuVyo4Je4epheZDwIHJv5H9avsl+RJ3fzW5NErzu/LRcs1zLvOxtI42OreqeY872D4zwFAC2oUBR3LJIEr7jDnNEo3AjgHN140FzBTKjwjBhvxEUEIQv5A9Inqa+Es2Q/STMwUyInFwcTGxZLIE80n06LaS+Ph7Bv3qAE5DHoWHCDRKFUwbDbkOpc9bz5hPXQ6uzVZL30nYh5NFI0JdP5W84zoad4+1VPN6cYywla/br6Dv5DCgMcuzmnW89+E6sn1bAEUDWUYByOmLPY0tDuqQK5DqESMQ2FAPDtENKwrtSGrFuQKuv6J8rPmlNuC0c7IvsGJvFy5ULhyubq8EsJSyUXSptwm6G30HAHSDSsaxiVIMF85wkA0RotJqUqCSR9GlkAQOcUv/SQIGUQME//a8QHl7Nj7zYLEz7wet5+zbrKYsxW3zryXxDfOZdnL5QnzuQByDskbVii1M409kUV/SydPbFA/T6lLw0W4PcUzNShhG6wNgP9J8XbjddaqynPAIbj2sSSuy6z5raaxuLcCwEbKNdZ0457xRAD1DkAdtSrpNn1BHUqFUH9U7FW+VPxQwEo5Qqc3XCu0HRkP/v/U8BPiLtSTx6O8trMTrfCobqecqHKs1rKXu3TGGdMm4S7wvv9cD5Ae4izjOSxFZE5CVY9ZJlv5WRBWh0+NRmg7bC79H4oQiwB88NjgGtK2xBW5k697qAakWaKEo36nLK5at8XCFNDi3rzuKP+mD7cf3S6hPJhIY1K0WVFeFGDtXuNaE1SxSgQ/ZDE7Iv0RKAFA8MXfOdAXwsy1uqsxpGyfk522ns6ivalQsz6/Ks2s3ErthP7UD7UgozAhP75LFVbWXcNismSUY29fYlihTnZCPzRqJG8T0wEf8Nrejc62v8qyL6g3oCSbHpk2mmaekKV9r+G7XsqF2tnr0/3oD4whNjJjQZxOelmmYeBm/WjrZ7FjblxYUrxF+zaHJt4UigIY8BjeFc2VvRCw8qSSnDKX/pQJlkuap6Hjq7O4tMdy2GzqF/3hDzoikzNkQzBRjVwgZaVq8Wzua6RnM2DSVdFIlDmQKEkWSwMs8H3d0su0u6GtCKJEmZqTN5ExkoCWBp6IqLe1LcV01gXpUfzCD8EiuzQkRXpTTl9CaBBuinCab0ZrrmMNWbNLBzyCKqwXFQRX8ArdxMoVun6rcZ9Oll2QzY2zjgqTsZpvpfCyzsKO1Kbng/uKDyEjrzWiRndVumEKax5xxXPqcpFu3GYFXF5OUj5bLAUZ5gSa8L3c7Mm4uKepMJ20k3+NwYqRi+qPq5eaomKwmcDD0lLmsPo8D1sjbTbeRydX0GN2bcxzoXbddYRxuWm2Xs9QcEAXLlMavAXy8JfcSMmctx6oRZt4kQGLFojOiCSN+JQNoA+ukr4W0Qvl2PnaDm8j9jbYSIpYj2WEbxh2GXlveBx0QmwdYQNTYEK1L5MblQZf8ZXc2cjDtuOmspmZj+eI0IVthruKmZLLnfururyIz9Pj/vhjDl4jTDeQSZ1Z9mYycQF4LnueelZ2dW45Y/hUH0QyMcMccAff8bfcncgttvald5gajjCH74NwhLKIk5DXmyeqFbsdzqziI/jaDSsjbjcGSmNaBWiBcoV523xofC94T3AGZapWqkWLMuAdSghw8vzclMjXtVillZf8jN+FdILZggmH5o4ympeopLnWzJnhSvdBDdUiXjc7Stpaumhvc6R6In7MfaZ5znGCZhhYAEe/M+keIQkR82LdvcjDtQelDJc/jPOEYoGpgcSFlY3fmEynari3y5vgdPaZDGAiHTcwSgRbF2n8c1x7/37Ifrl68HKrZz9ZHUjKNNwf9Qm/8+fdFsnutQSl25bii26EuoDhgOOEoozgl0imarfAyrTfpPXlC8shrDblSeFaHGkodK57c39cf2d7tXN/aB5aAEmsNbYgwQp69IrenslYtk2lA5fni1CEeoCCgGiEDYw3l46lpLb0yefe2/QlCxkhDDZcSXJayWjzc5h7fn+Gf7B7GXT9aLNaqEliNnYhhgs/9UrfVMoAt+KlgZdLjJmEpICNgFKE2Ivklh+lG7ZUyTXeG/RcCkwgQDWWSLhZIGhecx17H39Gf5J7HnQlafxaEkrqNhkiQQwL9iTgNsvjt8GmVZgQjUeFOIEBgaSEBIzplvyk0LXjyKDdZ/OMCWUfSTSWR7RYIWdrcjx6V36efg17wXP0aPlaPUpDN54i7wzf9hfhQcwAueinfpkyjlqGNILegVyFkYxGlyalxbWiyCvdv/K2CGceKjNcRmlXzmUacfd4J32MfSF6BHNraKhaKUpsNwQjkA229yDidc1Wulap+pqxj9GHmIMlg3uGf437l52l+rWSyNXcJvLdB1Qd4zHrRNlVKWRtb053kHsRfNB45nGJZwpa00ljN0kjIQ6Q+D3jzs7huwirx5yLkaqJYoXShP+Hzo4KmWOmcLa0yKLcnfECBy0ceDBGQwVUNWJnbUV1k3kwehl3Z3BOZh1ZPUknN2sjoQ5r+W3kS9Cgvf2s456+k+SLkYfnhuiJfJBxmnanKLcKyZHcJvEoBvUa6i5uQfFR818Ia9xyMnfqd/90iG67ZOJXZEi4NmkjDg9E+q3l6dGQvzGvSqFHlnyOI4pfiTSMipIwnNmoIriTyaXcxPBQBa4ZPS1nP55PZl1VaBZwb3Q/dYFyTGzQYllWSEcUNkMjZg8a+/vmpdOuwaKx+6MkmW+RFo07jOKO9pRGnomqXrlRyt/cdvB9BFoYcisyPRBNkVpPZfZsTXEzcqNvsmmPYIJU60U8NfYiqQ/r+1ToftX5w02086ZSnLqUZpB2j/CRvpeyoIas3LpFyz/dPvCvA/sWjCnTOklKeFf6YYBpz23JbmZsvGb4XV9STEQuNIMi1A+1/LfpcNdsxi+3LqrNn1yYEpQPk1uV4Jpzo9CunLxtzMbdH/DpApQVjidMOE1HHVRZXrVl92kCa85obmMOW/BPa0LrMugh6A92/SLredkFyUS6qK2So0+cFZgDlyCZWp6GpmSxnb7KzXTeGPAtAicUeyWiNR9Eg1BwWpphymXiZtxkyV/RVzZNSkBzMSYh4Q8t/pHsltvBy4q9X7Gep5GgbJxOmz2dKqLrqUK038Bdz0vfLPB8AbYSVCPWMsJAsExDVjJdSmFtYpRgz1tGVDRK6T3HLzsgwA/Y/gPuxd2czvzAT7Xtqx2lE6Hsn6+hTKadrWi3X8Mj0UngWvDYAEQRHiHsLzs9pkjUUYJYfFynXfpbhVdtUOtGSjvmLSgfhA91/3bvA+CU0ZjEc7l5sPCpB6bapHGmvqqcsdS6HcYe03DhpPBCANIP2h7nLIw5aUQqTY5TZFeSWBBX7VJKTF1DbTjSK+0dLA8CAOfwTOKk1FnIx71AtQSvQqsUqoGre6/jtYO+F8lL1cDiC/G8/2IOjBzLKbo1/j9ISFpOB1I1U9xRCk7fR40/VjWLKYoctw6AAFTyn+TL1zvMSMI9ule0wbCUr9mwgbRvunPCS8yq1zfkjvFH//cMNRqbJskxaTsyQ+tIaEySTWFM4kgxQ347BTIUJ/8aJg7tALzz+OYD2zvQ8MZqv+G5frZXtXW2zLk+v6HGuM862tXlLvLk/pML2hdaI7strjbuPUZDjkawR6RGd0NCPjI3fi5sJE0Zdw1GARz1VelL3lTUvMvExJ+/dLxYu1K8Vr9MxArLWtP53Jvn7PKU/jcKfBUNIJcp0jGAOHA9fUCSQapAzj0XOa0ywiqXIXQXqgyMAXP2s+ue4YPYp9BFyozFn8KRwWnCHMWUyavPL9fk34bpx/NY/uUIHxO1HF4l2SztMm43Ojo/O3c67De0M/Et1CaVHncVwAu+Ab/3D+765MTcrdXpz6LL+cj+x7bIGcsSz3/UNdv74pbrwPQx/qAHxBBXGRYhyCc6LUUxyzO7NBE01TEcLgQptyJpG1UTuQraAf74Z/Ba6BLhyNqp1dzRfM+YzjPPSNHC1IXZaN885srt1vUg/mgGbw72FcMcpCJtJ/sqNS0MLn0tjytUKOgjbx4WGBARlQngAS76ufK762rl9N+C2zXYI9Za1dzVpNeg2rfexeOj6R/wCPcl/kAFIQyUEmgYcR2KIZUkfiY4J8EmHyViIqEe/RmcFKkOVAjPAU/7AvUb78fpLOVu4abe6Nw+3KvcKN6m4BHkSegu7ZbyVvhB/igE3gk3DwoUNBiXGxoerB9EIOIfiR5JHDQZZxUAESMM+AaoAV78P/d28iXubOpn5yvlxeM/45njzuTR5o/p8ezb8Cv1wPl0/iIDpwfgC60P8hKYFY0XxRg3GeUY1BcPFqYTrxBDDX8JgQVqAVr9b/nI9YDyr+9p7b3rtepX6qLqkesZ7S3vuPGm9N33RPu+/i8CfgWSCFQLrw2UD/YQzhEXEtIRBRG4D/oN2QtpCb8G8QMVAUP+kPsQ+db28fRu81fysvF/8b/xa/J78+b0m/aO+Kv64fwe/1ABZgNSBQMHcAiPCVoKzQroCq0KIQpMCTUI6gZ1BeUDRwKpABj/n/1J/CH7LPpy+fT4tPiy+On4Vvny+bX6lvuN/JH9l/6W/4YAYQEgAr8COgOPA78DygOzA34DMAPNAl0C5QFqAfQAhgAmANf/mv9x/13/Xf9u/43/uP/p/xsATAB2AJQApACiAIwAYgAjANP/cf8D/4v+Ef6Z/Sr9yfx9/Er8NvxE/Hf8z/xN/e79sP6N/38AfwGFAogDfQRdBR0GtQYdB1AHSQcEB4EGwgXJBJwDQwLIADX/lv35+2r6+fix96D20PVK9Rb1OfWz9YX2q/ce+dX6xfze/hEBTwOEBZ4HjAk8C58MqA1LDoEORQ6WDXUM6gr+CL0GOASBAa7+0/sG+WD29vPd8Sfw5e4j7urtP+4i74/wf/Lj9Kz3xvoa/o0BBgVpCJsLgg4EEQ0TiRRrFagVOxUlFGwSGhA+De0JPwZQAj7+KPou9nDyDe8h7MXpDugM58vmTueV6JnqTu2f8Hf0t/hB/fEBpAY0C30PXROyFmIZVBt3HL4cJRyuGmAYSxWFESgNVggzA+b9l/hx853uQuqC5n/jUeEN4L/fbOAT4qnkHehX7DfxmfZV/D4CJwjiDUATGBhBHJgfAiJpI74j/SIpIUseehrOFWwQewooBKX9IvfT8OvqmOUG4Vrds9oq2czYn9mh28Pe8eIN6PDtbvRX+3MCjglwEOEWrxyrIasljig7KqIqvSmRJyokoR8XGrUTrAwvBXv9yfVV7lznE+Gv21vXO9Rp0vjR7dJE1e3Yz93G46XqOPJH+pEC2QrdEl4aICHsJpUr8i7oMGQxYDDgLfYpvSRcHgEX5g5HBmj9jPT56/LjuNyD1ofR7M3Ry0rLXMwDzy3Tu9iF31nn+u8n+ZkCBwwoFbMdZiUCLFExKjVqN/433zYSNKovyCmXIkwaJxFuB2z9bfPA6bHgiNiG0ePLzcdnxcXE8cXiyIbNutNQ2xDktu3694oCGA1PF98gfinmMNw2Lzu8PWs+NT0gOkI1vy7GJpMdbROiCIX9a/Ks55vdiNS7zHPG4sEvv3K+sb/owv7H0M4p18zgbuu/9mYCCg5QGeAjZS2WNTA8/kDXQ6VEXEMGQLg6mzPjKtMgthXjCbT9iPG+5bHautAnyDzBMbwwuVO4o7kYvZvCAcoV05HdJul59SwC3g4rG7ImGTEOOklBkUa5SaZKUEm9RQhAWjjtLggk/xctC/j9w/D34/bXIc3Mw0G8vrZus3CyzLN6t2C9VMUYz2Pa3uYq9N8BlA/eHFUplzRLPiRG40taT2pQCk9CSyxF9jzdMi8nRBqADE/+HPBX4mzVv8muv4e3jbHvrcysL64RslS4y8A1y0TXm+TT8n4BLBBpHscr3DdJQrxK8lC3VO1Vh1SOUB9KakGxNkQqhBzaDbn+k+/h4BPTmMbQuxGzoqy1qG2n1KjirHqza7xxxzjUX+J38QwBphDLHwYu5joGRg9PuFXLWShbwFmeVd5OtEVkOkUtvB45DzT/KO+T3+7QrMM1uOOuAqjHo1aivaPzp9iuObjQw0PRLOAX8IgAAxEFIREwsz1/SRhTMlqTXhhgs15sWmNTzUnzPS4w6SCaEL//2u5u3v3O/cDftACrr6Mnn46d8J5Ho3GqObRVwGfOBd617vb/QhEUIugxQkCyTNVWXF4KY7hkWWP1XqtXtE1aQfwyCSP8EVgAqO5z3UDNjr7QsWqnrp/bmhaZcZrjnkmmbrADvajL7dtU7Vb/ZhH7IoozkUKcT0NaM2IsZwVpsGczY7FbYlGVRKs1GCVcE/8Aku6h3LrLX7wLrySkAZzklvSURJbKmmai3azfuQrJ59n166n+bxG4I/U0n0Q8UmBdtWX2avxss2skZ3Ff1VShRzk4FSe4FLIBl+7422nKcrqQrDChrJhGkyuRbZICl8qeiKnsto7G9deb6vH9XRFNJCs2bEaQVCpg3mhmbpdwXm/DauhiClh6SqI6+ygPFm8Cte5420/Jx7hiqpGesJUFkL6N7o6Nk3mbdaYttDjEGtZJ6S/9MxG5JCo39UeXVp9irGt5cdVzr3INbhJm/FoeTeM8yipdFzQD7O4g22vIX7eCqEecD5Mija+Ky4tvkHaYpaOmsQzCWdT/52f88BD+JPM3O0lRWL1kHm4rdLR2o3X/cO1oqF2IT/o+fiyiGAAEOu/u2r3HO7bwplWazJCgigKICImqjcWVHaFZrwvAs9LB5pj7lxAcJYY4Pkq7WYNmMnB8di95NniWc3RrDGC3UeRAFC7ZGdAEnu/k2kXHWbWtpbuY6I6BiLmFpYZBi2mT3p5IrTm+LdGQ5cb6KRAUJeQ4/krWWvBn5nFpeEZ7Z3rQdaVtJWKoU55Ciy8CG6QFFvD+2gHHu7S6pHqXZI3GhtSDp4Q3iWOR7Jx4q5i8x89w5PL5pw/oJA05e0uiWwRpOXPxefd8M3yqd39v8GNXVSVE3zAaHHgGoPA82/LGX7QWpJOWQYxxhVeCDYOOh7aPSJvqqSq7hM5h4x75FA+YJAM5tksfXL9pLHQTe0B+mX0ief5wa2XEVnhFDzIfHUsHPPGd2xXHRrTAowWWgIuChEOB24FHhmWO9pmgqPO5Z81m4kz4cA4mJMY4r0tNXCBqvHTPeyB/l343eiFylGbqV5RGGTMQHhsI5/Ef3GvHbbS5o9GVIIv6g5eAEYFkhXCN9pidp/O4ccyB4X73vg2VI1g4Z0stXChq63QjfJd/LX/neudyamfKWHhH+jPpHucIoPLA3PHH1bQApPWVIYvZg1WAr4DnhNqMS5jipiy4pcu04Lb2/wzkIro34ErAW9hpuXQRfKV/Wn8ye05z6mdgWSFIsTSpH6wJZfN/3abIe7WTpHGWhIsfhHyAt4DPhKOM9pdwpqG3BMsB4PX1NQwXIu82G0oHWzBpJ3SYe0h/HX8Xe1VzFGitWY1IPDVPIGgKM/Ra3ojJXrZxpUWXRozLhA2BKYEdhcuM95dKplO3kMpp3z71YwsvIfc1GkkEWjFoNXO5eoN+d36Vevxy52etWb1ImTXYIBoLCfVP35XKfLeZpm6YaI3dhQeCBILShVSNUJhvpkO3Ssrv3pL0igouINU030e4WN9m5HF1eVV9aH2teUNyY2diWa1IxzVCIb8L5fVc4MzL1LgIqOqZ545Th2mDR4Pthj6OAZnhpnK3NMqU3vPzrAkWH4oza0YmVzllOHDNd7978XtgeClxhmbJWF5IxDWOIVYMxfZ+4SnNY7q9qbmbwZAriTKF8oRtiIiPCZqgp+K3T8pZ3mTzygjpHRoywURPVUJjMG7EdcR5EnqtdrBvUWXjV85HkDW3Id4Mp/e14qzOJ7y2q9ed9ZJli1+HA4dSijGRaputqJK4nMpA3uXy6AepHIYw5EI2U/1g0Gtbc2V3z3eXdNdtxWOwVv5GKjW/IVQNifj941HQHb7vrUKggJX8jfCJeYmZjDmTIp0HqoK5HMtK3njyBwdZG9Au1UDdUG1eGmmVcKN0J3UecqBr4mEwVe1FkTSjIbcNaflV5RbSQ8BmsPeiYJjwkOGMUYxDj56VMJ+tq7W6z8t53h/yKAb7GfwsmD5JTpNbEmZ0bYJxHnJFbw1pqV9iU5pEwzNiIQYORvq55vnTlsIYs/SlkZs9lDGQio9Lkl+Yk6GhrSi8t8zM3tvxTgWQGAsrMDx6S3NYuWL8aQVut24NbB9mG11JUQZDwjL8ID8OHfsp6PfVFMUCtjWpEZ/hl9yTIJOxlXqbS6Tfr9y90s1F367xewQcFwEpnzl1SBFVE18vZi1q82p6aNhiOlrlTjJBjTFwIGAO7Pug6QzYuMchubes26LWm9+XEZdymeyeVadostC/Ic/l35jxrwOhFeEm6DY9RXBRJVsRYgBm1maNZDpfCFc4TB8/JDC9H2oOs/wf6zjagMpxvHew7aYboDacWZuKnbSir6o6tQPCpNCr4Jvx7gIhFKwkEDTWQZRN8VamXYBhY2JLYElbh1NCScw8hy7jHloObv2h7HXcac3vv2+0QaurpN6g9Z/2oc6mV65TuHTEW9KZ4bjxOQKdEmYiGDFCPoBJfFLyWLFcn122WwdXuU8GRjw6tyziHTAOHf4l7sPeb9CXw5241a+CqdOl4aSzpjirSrKxuyPHRNSu4u/xkAEZEREgBC6HOjlFyk35U5hXjFjRVndSoUuGQm83tCq5HOsNv/6p7x7hj9Nlx/y8pLScrg+rGaq9q+2vhrZTvw3KYNbq40Ly9gCWD7Ed2CqnNsNA4EjATjlSMFOjUZ1NQkfFPmk0gChpG4sNUf8q8YPjxtZWy4nBqbnzs5CwmK8Qseq0B7s0wzDNrNhN5bDybAAXDkgblyemMiI8wUNMSZhMkE0tTH1IoELEOikxHCbzGQ4N0/+m8u/lEdplzz7G4L6DuU+2WbWntiy6yr9Tx4vQKNvX5jvz9P+eDNgYRCSJLlo3cz6gQ7tGr0d1RhtDvT2HNrMtiCNWGHUMQQAc9GHoa92P0xfLRMRIv0i8Wbt+vK2/y8StyxvU092H6OPzjv8sC2YW4yBUKnAy+zjEPadAkkGAQHs9njgSMgoqxyCTFr8LngCJ9dTq0eDP1xDQ0Mk8xXbCkcGQwmvFBso+0N7XquBc6qf0O//ECfMTeB0KJmktXTO6N2E6QDtSOqI3RzNmLS4m2h2sFOwK5wDs9kbtQeQh3CTVfs9Zy9PI/MfZyF/LeM8D1dHbrONV7Ij1/P5nCIIRBRqwIUkony2KMe4zvDTxM5QxvC2JKCUixBqhEv0JHAFD+LXvtueC4E7aS9Wb0VrPls5Sz4XRHNX42fHf1uZx7oX20v4XBxUPjhZKHRUjxSc4K1QtDi5hLVcrASh9I+8dhhd0EPIIOwGM+R/yLevs5IvfMNv81wXWWNX21djX7doZ3zvkKOqv8J73vv7VBbAMFxPcGNId1iHJJJkmOiepJu8kGyJGHpEZIhQlDssHRAHF+n/0o+5d6dTkKeF33s/cPdzA3FPe5+Bj5Kzone0O89P4wP6kBFQKow9qFIUY1RtFHsIfRiDOH2IeDxzqGA4VnBC3C4gGNwHu+9b2FfLP7SXqMOcF5bLjPuOr4/HkBOfR6UDtM/GL9SP62f6EAwQINQz4DzETyRWvF9YYOBnWGLUX4RVsE2oQ9gwsCSsFEwEF/R75fvVA8nnvP+2h66fqV+qw6qzrQO1f7/Px6PQl+I77CP93AsMF0QiKC9wNtw8OEdkRFhLGEe4Qlw/QDagLMgmEBrQD2AAI/lj73fiq9s30U/NF8qnxgPHJ8X7ylvMH9cP2ufjZ+hH9Tv9+AZEDeAUlB4sIpAlnCtMK5wqlChIKNwkcCMwGVQXDAyQChgD3/oH9L/wK+xr6Zfns+LL4tPjw+GH5AfrG+qr7o/yn/az+q/+ZAHIBLwLLAkIDlAPBA8kDrwN4AygDxAJTAtoBYAHqAH4AHgDR/5b/b/9d/17/cP+R/7z/7f8fAFAAeQCWAKQAoQCJAF0AHQDL/2j/+f6B/gf+kP0h/cL8d/xH/Db8R/x9/Nj8Wf39/cL+of+UAJUBmwKdA5EEbgUrBr8GJAdSB0UH+wZzBq8FsQSBAyUCpwAT/3P91/tK+tz4mPeM9sL1Q/UW9UD1wvWb9sf3QPn9+vD8DP9BAX4DsgXJB7IJXAu5DLkNVA6ADjsOgg1YDMUK0QiKBgAERgFx/pb7zPgq9sbztPEI8NDuGe7s7UzuO++08K3yG/Xs9wv7Y/7XAU8FsAjdC7wONREyE6IUdhWlFSoVBxRAEuIP+wyiCe0F+gHn/dL52/Uk8sru6eua6fLnAOfO5mLnuejN6o/t7fDO9Bb5pP1VAgcHkwvUD6kT8haTGXQbhRy6HA4chBolGAEVLRHFDOsHwgJ0/Sf4B/M77uvpO+ZI4y3h/d/D34bgQeLr5HDoueyl8RH30vy8AqMIWA6tE3gYkBzVHyoieiO5I+Ei9SADHh4aYhXyD/cJngMZ/Zn2UfBz6i7lruAX3YfaFtnS2L/Z2dsT31bjg+h17v707fsLAyQK/hBkFyIdCiL0Jb4oUCqcKpspVCfUIzQflxklEw8MjATW/Cb1u+3O5pfgSNsM1wfUUtL/0RLThtVK2UTeUORA6+Dy9vpDA4gLgxP2GqYhXCfqKyovATFdMTkwmi2TKUAkxx1bFjIOiwWq/NHzR+tP4yncDNYs0bDNtstRy4XMTc+W00DZI+AK6Lrw7/ljA84M5RVhHv4lgCyyMWo1hzf3N7M2wzM7Lzsp8CGRGVwQmgaV/Jry+Oj53+fX/9B8y4nHSMXNxB7GNcn7zU/UANzW5Izu2fhtA/YNIhiiISkqdDFJN3c73T1kPgU9yTnHNCIuDCbDHIwStweX/ILxzebP3NTTJcwAxpbBDL95vuO/QsN/yHPP69em4VrstvdfA/8OORq2JCIuMzapPE5B/UOeRClDpz8yOvAyGSrvH8AU4Qiv/IjwyuTR2fTPgse9wN27CblauNi5er0nw7PK6NN/3ibqhvY9A+oPKRycJ+gxujrOQelG4kmgShlJWEV3P6E3ES4RI/MWFgrd/K3v7eID10rMGMO3u2G2QrN2sgS04rf3vRPG+89j2/PnTPUFA7UQ8R1SKnY1Bj+0RkRMiE9lUNFO1kqRRDA88jEmJiUZVAsf/fHuOuFl1NjI7L7ytiixvq3RrGqugLL0uJfBKMxW2MPlCfS5AmERkB/WLMw4EkNYS1tR6lToVUtUHFB7SZhAtzUrKVMbmgx0/VTusN/70aDFALtxsjWsgKhwpxGpVq0jtEO9csha1ZnjwPJaAu8RBSEnL+Y73Ua1TylWA1olW4NZJ1UxTtZEXDkcLHkd5g3c/dXtUN7Ez6TCWLc4ro2njaNZovyjbKiIrxy53sR00nfhcvHpAV4SUSJEMcI+Y0rJU6pa0F4XYHNe8FmvUuZI3jz2LpYfNg9V/nXtGt3Czee/9bNKqjOj6J6OnTCfxKMpqya1b8Gnz2DfIfBoAbASciMqM2BBok2QV9xeS2O5ZBljdV7wVsJMOUC2MaYhhxDe/jLtDtz2y2q92rCqpiqfl5oVmbKaZJ8Ip2SxKb71zFfd0O7YAOQSaCTbNL1DmFAIW7ticmcIaW9nsGLwWmhQakNYNKcj2BF2/w3tLdthyi67Ca5ao3abm5bxlIaWT5sqo9utD7tiyl7bgO05APwSNCVVNtdFQ1MvXkRmQmsAbXFrnmarXtRTbEbaNpclJxMZAAPtddoDyTS5hKtdoBmY+ZIlka6SiZeTn46qJbjyx3nZM+yQ//gS1iWXN7BHolUBYXRptm6fcB1vO2odYgFXPUk5OXIncRTJABTt6Nndx363TKm2nRaVs4+1jS+PFpRGnICnbrWmxanX7Orb/toSTyaiOERJs1d+Y0lszXHfc25yg21DZe5Z2UtyOzYptBWCAT7thNntxgu2Yqdkm3CSy4ykigyM+ZBHmbak7rKBw/HVreke/qMSnyZ2OZRKdVmkZcFuhHTAdmJ1dHAaaJVcPU6BPeEq7xZEAoLtSNk1xt20yKVrmSeQRYr0h0eJNY6ZljGiprCIwVTUeOhZ/VQSxyYSOqBL6FpxZ9pw2XY+efd3CnOfavZeZ1BkP3AsHhgLA9ztNNm0xfOzfaTKlz2OIoioheSGzYs+lPafm668v9TST+eP/O4RyCZ5OmhMClzlaJNyynhYeyl6RHXPbAxhVFIZQeEtQBnXA03uRtloxU6zg6ODlrSMY4bBg+SEw4k5kgaezqwfvnPRNObC+3MRoiapOuxM3Fz+aexzVnoMffd7HneobtViAFSdQjEvUxqlBNHuftlTxeyy2aKWlY2LCoVBgkmDGYiNkGScQqu1vDTQKuXz+uUQWCalOixNXl2+auJ0fHtYfl99mHgncE9ka1XtQ14wVBt0BWjv2tlxxc2yfqIElceKGIQqgRSC0YY7jxKb+ql/uxrPMuQl+kYQ6yVsOilNkV0ja3d1O3w7f19+rnlLcXllkVYIRWUxQhxCBhDwWNrDxfGydKLMlGSKjIN7gEiB7IVFjhKa9qh/uiXOT+NZ+ZYPXCUBOuVMdF0va6l1kny1f/d+YHoTck9mcVfrRUYyGh0MB8fw99pGxlWzt6LtlGKKaYM2gOSAbYWtjWWZOqi4uVnNguKR+NgOrSRmOWBMCl3hanp1gnzFfyd/rXp8ctJmCViVRv4y2x3RB4vxttv6xvqzSaNolcOKrINbgOmAUoVzjQ2ZxqcrubbMzuHP9w4O4COaOJxLUlw6aul0DHxrf+1+lXqGcv9mWFgFR4szgx6PCFvykdzdx920JqQ6loOLVoTqgFiBnYWZjQuZnKfauD/MNOEW9zoN9iKhN5tKT1s9afhzLnuofkl+F3oxctVmXVg4R+wzDx9ECTTzid3syP21TqVil6SMZoXhgTCCT4YejmCZvafGuPXLteBm9l0M8iF9Nl5JAlrqZ6ly7Hl8fT19Mnl8cVVmFlgtRx80fx/uCRT0md4lyle3v6bfmCKO24ZBg3CDZocDjwyaKqjvuNnLVODC9XoL1iAuNedHblhDZvxwRnjoe8l76XdncH5lg1flRiM00B+LCvr0wd+Iy+m4d6ivmv2Ps4gIhRiF4ohHkA6b4qhXue3LE+Ar9ZIKox+5MzlGk1ZKZPNuPXbvee55O3bzbk9kpFZdRvczAiAbC+P1/+AQzbK6c6rQnDKS7IozhyaHworrkWic6Kn/uTLM8d+k9KgJXB4eMlZEdlQCYpJs1HORd613KXQgbcpieVWVRZkzEyCaC872T+K8zq+8saw+n7+UhI3DiZiJBY3tkxmeOavnuqjM8d8t9L0IAx1hMEFCGFJuX9ppDnHRdAl1tXHvau9gAlSNRAozAiAIDLj3sOOK0Ny+Lq/4oaGXeJCzjG6MqY9Llh+g16wPvFDNFODJ89MHmhuDLvw/fU+PXM5m7G2xcQNy4W5jaL5ePlJFQ0kyzR9iDKD4H+V30jjB57H7pNaaxpMCkKOPrZIFmXqiwK53vSvOW+B48+0GJBqILIo9p0xqWXJjcmo0bp5urmt8ZTlcL1C9QVQxdB+oDIT5m+aA1L/D2bRCqFmea5eskzeTDpYZnCil9LAevznPxuA98wwGoxhyKu86mUkCVshfo2Zeat1qIGg8YmJZ1032Py0w9h7ZDGL6Ieii1m7GAbjLqymiY5uulyWXyZmEnyiocbMFwXrQV+EY8zIFGhdEKCw4WEZZUtVbgmIwZsNmOWSnXjpWNUvwPdIuUx7yDDj7runb2ELJXLuSr0Cmq58GnGqb251Eo3irNrYqw+7RDeIK82AEihUBJkc15UJ0TptXFF6wYVNi/F++WsNSTEisO0UtiR3zDAX8QOso2zjM5b6Ts5uqPqSuoASgQqJVpxWvQrmNxZTT6uIW85kD9hOrI0EyRj9XSiBTXVnhXJFdbFuEVgBPHkUrOYYrmhzbDMb81eyG3U3PmcLLtzavGamjpe2k+aa2q/2yk7wsyGzV7eM6894CYBJGIR4vfjsGRmZOYFTGV4JYjlb9UfRKrEFvNpUphBupDHv9a+7y333SdcY1vAy0N67hqiKq/qtjsC23JsAFy3bXFuV58zACyhDUHuIrkDeEQXRJIk9mUihTZVEsTaFG+T15M3MnSBpdDCH+APBp4sTVdMrNwBq5k7NjsJ+vS7FXtaK7+MMYzrDZZebT85IBNw9YHJAogTPXPExEqEnETIlN9EsVSAtCBzpLMCIl5hj1C7j+kfHp5CDZks6OxVq+Krkktl+13baQulnACMhh0Rjc2udJ9AMBqA3VGSslVS8DOPU+90PlRqpHQka8QjU92jXnLKIiXhdyCz3/HPNu543cy9J1ysfD9L4gvF27rrwIwE3FUszf1K/edOna9IYAIQxOF7ghDysMM3M5FD7OQI9BUkAlPSI4dDFPKfYfsRXTCrH/oPT26QbgHNd7z13J78RQwpTBu8K8xXzK09CP2HHhMuuH9RwAogrFFDketCb3LcozBDiFOj07KjpVN9gy2CyHJR4d4RMYChEAGvZ/7IrjgNue1BfPE8uxyP7H/siny+HPiNVv3F7kFe1Q9sb/LQk+ErIaSCLIKAEuzDEPNLs0zTNQMVotCyiQIR0a7RFBCV4AifcF7xTn89/X2e/UXdE7z5fOcs/E0XjVbdp84HPnGu8194T/xQe6DyYX0B2FIxsocitxLQ0uQy0cK6wnECNuHfUW1w9OCJYA6viF8aDqcOQj3+Daxtfq1VjVEtYP2Dzbft+y5K7qQPE1+Fb/awY9DZkTThkyHh8i+ySyJjknjya9JNMh6h0kGacToQ1AB7gAPfr+8yzu9Oh85OXgSd643D3c2NyB3ijht+QP6QzuhvNR+T//IAXKCg8QyRTTGBIcbh7XH0UguR85HtMbnhi1FDgQSwsXBsUAf/ts9rTxe+3e6fnm4OSf4z/jvuMW5TnnFeqP7Yzx6/WH+j3/5gNhCIoMQxBvE/kVzxflGDcZxRiVF7MVMRMkEKgM2AjUBLsAsPzO+DX1//FE7xftheua6ljqvurI62ntku8v8iv1bPjX+1L/vwIGBg4JwAsJDtkPJBHkERUSuRHWEHYPpQ12C/sISQZ3A5sAzf0h+6v4f/ap9DjzNPKh8YLx1PGR8rLzKvXr9uX4CPtB/X3/qwG8A54FRQemCLcJdArYCuQKnAoDCiEJAQiuBjQFoQMCAmQA1/5j/RT89PoJ+lj55fiw+Lf4+Pht+RD62Pq++7j8vP3C/r//rACDAT0C1gJLA5oDwwPIA6wDcgMgA7sCSQLQAVYB4QB1ABcAy/+S/23/XP9f/3L/lP/A//L/JABUAHwAmAClAJ8AhgBZABcAxP9g/+/+d/79/Yb9Gf27/HL8Rfw2/Er8g/zh/GX9Df7T/rT/qQCrAbECsgOkBH8FOQbKBioHUwdBB/IGZQacBZoEZQMGAoYA8P5R/bX7Kvq/+ID3efa09Tz1FvVH9dD1sfbk92P5JPsc/Tv/cQGuA+AF9AfYCX0L0gzKDVwOfw4wDm0NOwyfCqMIVgbHAwoBNP5a+5L49PWW843x6e+87hDu7u1b7lXv2fDd8lT1LPhR+6z+IQKZBfYIHQz1DmQRVxO6FIEVoRUZFecTExKpD7gMVgmbBaQBj/17+Yn12PGH7rLrcOnW5/Tm0+Z3597oAevR7TvxJvV1+Qf+ugJqB/ELKxD1EzEXwxmTG5IctBz2G1oa6he1FNQQYgx/B1ICAv24953y2u2W6fTlEuMK4e7fyt+h4HHiLuXE6BztFPKJ90/9OwMgCc4OGRTWGN4cECBQIoojsiPCIsAguR3BGfQUdw9zCRQDjvwQ9s/v/OnG5Fjg1txe2gXZ2tjg2RPcZN+84/vo++6P9YT8pAO5CowR5heUHWgiOybsKGMqkyp3KRUnfCPGHhUZkxJzC+kDMfyF9CLtQuYc4OLav9bV0z7SCNI508nVqdm73tzk3euJ86b79QM2DCgUjRsqIsknPCxgLxcxUzEPMFItLSnAIzIdsxV9Dc8E7PsX85fqruKb25jV1NB3zZ7LW8uxzJrPAtTI2cLgveh68bj6LgSUDaEWDR+VJv0sETKnNaE37TeFNnIzyS6rKEch0xiRD8YFv/vI8THoQ99H13zQGMtIxyzF18RPxovJdM7m1LLcneVj77n5TwTUDvUYYiLRKgAysze8O/o9WT7SPG85STSDLVEl8RuqEcsGqfuY8PDlBNwj05PLkMVNwe2+g74YwKDDA8ka0K/YguJH7a34WQT0DyIbiiXdLs42Hj2bQR9Ek0TyQkY/qDlCMkwpCR/IE98HqvuI79fj89gxz+DGQsCMu+W4ZbgRuuC9tsNpy73Ubt8p65P3TQT1ECcdhCizMmM7T0I+RwhKlUrfSO9E4j7lNjQtGCLnFf4IwvuX7ubhEdZ2y2jCMLsIthqzgLJAtE+4kb7WxuHQZdwK6W/2KwTVEQMfTStTNr0/QEehTLNPW1CTTmZK8kNmOwUxGyUFGCgK7vvG7R7gYdPzxy6+YLbHsJKt2qyprvOymLlnwh3Nadnt5kD18wOWErYg5C25OddD70u/URlV31ULVKZP00jDP7o0DiggGloLMPwV7YHe5NCrxDW61LHNq0+oeadSqc+t0LQfvnbJf9bV5Ar0qAM3Ez4iRjDiPK9HV1CVVjZaHVtAWatUgE31Q1I47yo1HJMMhPyE7A7dnc6gwX+2ka0dp1ejYKI/pOqoPrADuu/FqNPE4s/ySgO5E5sjczLOP0JLdVQeWwdfEGAvXnBZ9lH6R8c7ui1BHtEN7PwR7Mfbi8zUvg+zmKm7oq6elJ12n0ek5asWto3C6dC94I/x2gIcFM0kajR6Qo5OR1hXX4djtGTTYvBdMFbNSxY/bDBCIBIPZP2+66var8pJvOiv7qWrnliaGZn5muufy6deslK/Rc7D3k3wWgJhFNMlKTbkRJBRyFs9Y7NnBWkoZydiKVpqTztCAjM1IlQQ6/2I67rZDMkAugytlqLwmliW85TNltmb86PdrkO8vsvY3AzvywGIFK4msTcMR0ZU+F7NZodrAG0qaxJm313NUjNFeTUXJJURgf5w6/XYoMf6t3yqkJ+Ml7GSJZH2kheYYaCXq2K5WMn+2sztLwGSFF4nADnwSK9W02EEagBvoHDVbqxpTGH0VftHzTfnJdISJP9z61rYbcY4tjqo35yDlGaPs413j6aUGZ2QqLS2Fsc52ZHshwCBFOMnFzqPSspYWGTfbBty43MncvNsb2TbWJBK/TmhJwoU0v+S6+rXcsW7tEemhprWkXuMn4pTjIqRHZrLpTq0+sSL113r1f9VFD4o9jrpS5VahWZdb9d0xnYcdeNvQ2d+W+5MBDxDKTsViADL66TXsMSDs6SkhZiHj/CJ7YeOiceOcpdLo/ixCMP21TDqGv8PFHAonDv+TA9cWWh8cTB3R3mxd3hyxWnaXRJP4T3KKmIWRgEc7IfXJsSRslKj3paYjcmHnoUph1+MGZUTofKvQsF91A/pWP6yE3koCjzOTTld02k7cyV5ZHvkebJ09GvtX/tQkD80LH0XCwKF7JHX08PksVGikZUKjAaGtIMnhVWKFZMmnyiuqr8i0/vnkv0/E1soQjxYThJe82qYdLV6Gn20e412zG21YaVSEEF/LYoY0wID7cLXt8N8saGhoJTeiqqEMoKLg6qIaZGFnZ+sQ77n0fXmyPy2EhcoQzyeTplet2uTdd57aX4dfQd4S28uYw1UXkKpLocZnQOV7RnY0MNYsUKhCZQVirSDF4FUgmGHF5AznFirD73P0AHm/fsbEq4nDzygTtBeIWwrdqB8Tn8gfh55cHBXZDNVd0OvL3MaaAQ67pTYHsR4sTOhzZOuiSaDZoCFgXuGII8zm1SqELzczx/lNPtuESInqDtfTrZeL2xgdvt8y3+7ftN5OHEvZRNWW0SPMEobMAXv7jHZn8TasXSh65Oqif+CH4AfgfmFho6EmpepSLsPz1LkbPqxEHUmDjvcTU5e5Gszdu183X/tfiJ6pHGzZa1WBkVIMQsc9gWz7+7ZUsV+sgOiZJQIikCDQYAigdyFSo4qmiGpubprzp3jqvnmD6clQzoZTZhdP2uldXl8hn+1fg16sXHjZf9WeEXXMbUctQaE8MvaNMZgs+CiNZXHiuiDzYCOgSSGbI4lmvSoZbrxzQDj7vgQD7wkSTkXTJVcQmq1dJ57xX4VfpJ5X3G+ZQdXr0U8MkUdbQdf8cTbRceBtAmkXZbmi/aEwoFjgtKG7Y51mhCpTLqizX3iOvgwDrUjIjjYSkdb72hnc116nH0MfbF4rnBCZcZWqkV0MrodHAhE8tncgsjdtXul2pdkjWqGIIOgg+WHzo8cm3epcLqBzRfikfdHDZQi0DZfSbFZR2e6cbd4C3ybe2x3nm9wZDlWZ0V/MhIewAgv8wbe6clztzWnrJk/j0CI5IREhV2JDZEZnCqq0bqOzc7h8/ZZDFshVTWtR9NXTWWxb692E3rDecJ1MG5IY2FV50RaMkseVwkg9Erfd8tBuTWpz5t1kXmKDodPhzmLq5JsnSercbvKzaThY/ZnCw0gtDPERbJVAmNObUd0t3eGd7RzY2zKYT5UKEQGMmUe3wkT9aLgKs1Du3erQJ4ElBGNnIm/iXeNp5QVn3CsT7w2zprh4/VyCqse7zGoQ09TamCUaoBx+XTldEVxOWr2X89SKkOBMV8eVwoI9g3iAc94vfqt/qDplgaQi4yRjBaQ/5YToQWubb3UzrLhc/V+CTgdCDBcQa1Qh12GZ11u2nHicXZus2fOXRVR7UHLMDYevgr89ofj99Dcv7qwBqQgmlWT2I/DjxWTspllo+Ovyb6jz+zhFvWLCLcbAi7hPtBNXFomZOJqXm6Abklr02RSWxFPcUDjL+odEQvt9w/lC9NtwrWzU6eonfyWgpNTk3CWvpwKpgyyZcCj0EnizfSdByka4Ss7PLpK7VZ4YBFniGrDasFnnGGFWMRMtj7KLnodUAvZ+KLmOtUnxea246p7ofaahJc+lyWaIaAAqX60PsLW0cvimfS0BpEYpiltOW5HPVN/XO9iW2arZt9jDl5nVS9Kvjx+LecceQu++T7ogNcHyEq6sq6YpUCf25uBmzKe2KNFrDa3VcQ603Hje/TSBfIWVCd7NvFDUE9AWH5e22E+YqhfLVr7UVNHiDoBLC4ciwuc+uDp3NkLy969vLL5qdejg6AXoJOi4afXrzW6qcbQ1DzkdPT5BE0V7yRoM0dAKku+U8NZC11/XR5b/FVETjJEFzhSKlAbhgtv+4frStwuzp/B/baarrWoeaX+pESnOay0s3i9OMmX1i3lh/QsBKUTeSI2MHI8z0b+TsJU8FdyWEZWflFDSs5AazVzKE0aZws2/C/tx95t0YfFcrt4s9etuKoxqkOs3bDYt/zAAcyO2EPmsvRrA/0R9h/qLHY4QkIESoBPj1IbUyJRtkz8RSo9hjJkJiUZLwvx/NfuUeHF1JTJFcCOuDizO7Crr4qxyLVBvMDEAs+12n7n9/S3AlUQZx2HKVk0ij3URAFK60x+TbhLqUdyQUc5aS8mJNcX3Aqd/X3w4+My2MHN4sTWvdS4/rVptRa397rrwMDIOdIK3d7oV/UTArIO0BoRJh0wqTh0P0tEC0ehRwtGWUKpPCo1Fyy6IWUWbwo4/h7yfeax2wvS1clNw6S++7tlu+K8ZsDSxfvMpdWM32Lq0fWAARUNNRiLIscrpTPnOWE+8kCIQSFAzDykN9QwkygjH84U5wnD/rfzGuk932zW6c7tyKXELsKawerCEcb0ymzRQtk64grsZ/b+AH8LlxX4Hlwngi41NEo4pjo4O/45BTdmMkgs3SRgHBQTRAk8/0n1uOvV4uHaGtSyztDKkcgDyCfJ8stM0BDWD90R5dbtGPePAPMJ+RJdG94iRSlgLgwyLTS3NKczCjH1LIwn+iB1GTgRhQih/8/2Ve5z5mbfYtmV1CHRH8+bzpbPBtLW1eTaCOEQ6MPv5fc0AHIIXxC8F1Me8iNvKKorjC0KLiIt3ypUJ6Ei6xxiFjoPqwfy/0n47PAV6vbjvt6S2pLX0dVb1TDWR9iM2+TfK+U169HxzPjv/wAHyg0aFL8Zjx5nIislySY3J3QmiSSJIYwdtRgrExsNtgYtALT5ffO37Y3oJ+Sk4B3eo9w/3PHcsN5s4Q3ldOl97v/zz/m9/5wFPgt6ECYVIRlNHJUe6h9DIKIfDh6XG1EYWhTSD94KpgVTABD7BPZV8SftmenF5r3kj+NB49LjPOVv51nq4O3m8Uv26/qi/0gEvQjeDIwQrBMnFu0X9Bg1GbMYcxeDFfUS3g9ZDIQIfQRkAFv8fvjs9MDxEO/v7Gvrjupa6s/q5euS7cXvbPJu9bT4Ifyc/wcDSgZLCfULNA75DzkR7RETEqsRvRBTD3oNRAvDCA4GOgNeAJP96vp6+FT2h/Qe8yPymvGE8eDxpvLO8031E/cR+Tf7cP2t/9kB5gPEBWUHwAjKCX8K3AriCpIK8wkMCecHkAYTBX8D3wFCALf+Rv36+976+PlM+d74rvi6+AD5efkf+uv60vvO/NL91/7U/78AlAFLAuECUwOeA8UDxwOoA2wDGQOyAj8CxgFMAdcAbQAQAMb/jv9r/1z/YP91/5f/xP/2/ygAVwB/AJoApQCeAIMAVAARALz/V//l/m3+8/18/RD9tPxt/EL8NvxN/In86/xy/Rz+5f7I/74AwQHGAscDuASQBUcG1AYvB1QHPQfpBlcGiAWCBEoD5wFkAM7+Lv2T+wv6ovhn92X2p/U29Rf1T/Xg9cf2AfiG+Uz7SP1p/6AB3QMNBh4I/gmcC+oM2g1jDn0OJA5YDRwMeAp1CCIGjgPOAPf9HftY+L/1Z/Nl8cvvqO4I7vLtau5x7//wDfON9Wz4l/v1/msC4gU8CV0MLQ+TEXoT0RSKFZ0VBRXGE+URbw90DAkJSAVOATj9Jfk49Y7xRu5860fpvOfq5tnmjucF6TfrFO6K8X711Plr/h8DzAdODIAQQBRvF/EZsRudHK0c3BsuGqwXaRR6EP0LEwfiAZH8SPcz8nrtQumv5d/i6eDi39Lfv+Cj4nLlGumA7YXyAfjN/boDnAlED4QUNBkrHUogdSKYI6gjoiKJIG0dYhmGFPwO7giKAgL8h/VO74bpYOQE4JfcNtr22OTYBNpP3LffI+R06YPvIPYb/TwETgsZEmYYBB7EIn8mFyl0KogqUSnUJiIjVR6RGAES1QpFA4z74/OJ7Lflo99/2nXWptMs0hTSYtMQ1graNN9q5XvsM/RX/KYE4wzMFCMcrCI0KI0ski8rMUcx4y8HLcYoPyOaHAoVyAwSBC77XvLn6Q7iENsl1X7QQM2Jy2jL4Mzqz3DUUtpk4XDpO/KA+/gEWg5cF7cfKSd3LWwy4TW4N983UzYdM1QuGSicIBUYxA7xBOn69/Br54/eqtb6z7fKCscTxeXEg8bjye/OgNVm3WbmO/Ca+jEFsQ/GGSEjeCuIMho4/jsVPks+nDwSOccz4SyUJB4bxxDfBbv6sO8U5TvbdNICyyTFCMHQvpK+UMABxIvJw9B22WDjNu6k+VMF6BAIHF0mlC9lN5A95EE9RIVEt0LgPhs5kjF9KCIezxLcBqX6ie7l4hbYcc5Cxsq/P7vFuHO4TrpJvknEIcyV1V/gLOyh+F0F/xEjHmopfDMJPMxCj0cqSodKoEiCREo+JjZULB0h2RTlB6f6gu3g4CLVpcq7wa66tLX3so6ygLTAuC6/nMfJ0WndIuqS91AF9RITIEYsLDdxQMlH+UzYT01QUU7ySU9DmjoUMA4k4xb6CL76newE31/SEcdzvdK1a7Bqreis7a5qsz+6OcMVzn/aGOh49i4FyhPaIe8uojqYRIJMH1JDVdJVxlMsTyZI6T67M/Am6xgYCuv61+tT3dHPucNsuTyxaasjqIanmKlNroG1/r59yqXXEuZV9fYEfxR1I2Mx3D1+SPRQ/FZlWhBb+VgrVMtMEENEN8Ep7ho/Cy37M+vO23jNn8Cqte6ssqYno2yiiKRtqfew7boEx9/UE+Qs9KsEExXjJKAz1kAdTB1VjVs6XwVg5V3qWDlRCkesOn0s6hxrDIL7r+p22lbLxb0tsuyoSaJ6np+dwJ/PpKesC7euwy7SHOL98k0EiBUmJqc1kEN1T/hYzV++Y6pkiGJmXWtV00ruPSEv2x6cDen7SupJ2WvJLLv7rjilMZ4fmiKZRJt3oJOoXLN/wJfPMeDL8d0D3RU8J3U3CEaDUoNcumPuZ/1o22aZYV5ZZ04JQaoxwCDODmH8BepJ2LnH1bgTrNahb5oalvqUGpdpnMKk5K96vR3NU96Y8F0DExYmKAs5PEhEVbxfUWfGa/ls3WqBZQ1dw1H3QxU0lSIBEOj83ul210DGw7Z4qceeBZdvkiuRQ5OpmDWhpqyjusLKhtxm788CKxbkKGc6LEq4V6BijmpEb5twiG4YaXZg41S2Rl82WSQyEX791OnO1gHF9rQspw+c9ZMgj7eNxI87lfGdpan9t4rIzNo37jMCJhZ1KYk71kvcWS1lcG1kcuBz2XFdbJRjw1dDSYU4CSZfEiD+5+lS1vvDb7Mwpa6ZQpExjKGKoIwhkvma5qaKtXfGKNkN7YsBBRbbKXM8Ok2wW2Fn9G8jdcZ2z3RLb2VmYVqaS4Q6oieFE8z+FeoC1i7DLrKFo6aX7o6iieyH2olfj1GYaqRPs4zEm9fq69oAyhUXKiI9WE4yXTxpGHKAd0l5ZXfgceVouVy6TVo8ISmkFIL/Xerb1ZvCM7EroviV+ox3h5qFdYf4jPqVNqJNscvCKdbR6iAAdRUpKpk9ME9jXr1q3HN5eWh7mXkZdBJryV6eTwQ+hSq4FT4Avure1UHCf7AjoaaUZ4uwha6DcoXtiveTSqCHrzjB1NTC6WL/CRUSKtg9wU9CX+FrPnUNeyF9anv0delsj2BEUYA/zCvAFgABNusJ1h7CEbBuoK6TN4pQhCmC04NCiUySq54ArtS/ndPB6J3+hhTTKd89DFDOX6tsPXY6fHJ+1nxvd2huB2KrUstA8iy5F8YBw+ta1jLC6K8KoBOTaYlXgwyBm4L4h/mQWp26rKK+iNLQ59b97xNvKa89ElAJYBht2Hb/fFt/2n2IeI5vMWPQU+NB9i2iGI0CZOzR1nzCBLD3n9SS/4jFgliAyoEQhwGQWZy3q6S9ltHw5g/9RBPmKEs91U/0XyptEXdcfdp/d34/eVhwCWSxVMdC1i54GVUDGO1s1/vCY7A2oO+S+Iicgg6AYYGMhmWPqZv4qty8ydAk5kj8iBI6KLI8VE+NX+Fs53ZSfe9/rH6RecZwj2RMVXRDjy86GhoE2+0p2K3DBbHDoGWTU4nbgi6AYYFshiePTZuAqku8I9Bt5YX7vRFsJ+g7kk7YXj5sWnbffJt/d35+edZwwmShVehDITDmGtsEre4G2Y/E6LGfoTWUEYqAg7eAyoGxhkaPRJtQqvO7pc/N5Mb65RCAJu06j03WXUJrbHUGfNx+2n0GeYhwoGStVSNEiTB5G5YFi+8C2qLFCbPIol2VL4uNhKqBnIJch8OPkJtoqta7U89G5A/6ARB2JcQ5T0yHXO9pHnTHerV91HwpeNtvKmRxVSNExzDzG0oGdPAa2+LGaLQ8pNuWrIz/hQWD1oNriJ+QMpzJqvS7K8/a42D5FA9QJG4400rvWkZocnIjeSZ8ZnvodtBuXWPqVOdD2DBRHPQGZvFM3E3IAbb4pa6YiI7Vh8iEeIXeidmRKZ11q068Mc+K47v4Hw4RI+42HEkPWUpmaHAcdzF6kXlCdWdtPGIZVG5DuzCTHJIHXfKX3eHJ1Lf8p9Oav5ANivCGf4e2i3GTdZ5rrOa8Zc9Y4yP4JQ28IUc1L0fpVv1jBG6zdNd3V3c6c6BrxWD+UrdCcDC2HCQIWvP33pvL3LlDqkidT5OljHuJ64nvjWeVF6Csrbu9yM9E45n3JwxRIHozDEWBVGFhSGvscRp1unTQcHxp+V6YUcNB9S+6HKcIWPRr4HrNGLzLrAqgNpaaj2mMuoyJkLiXDaI3r86+WtBQ4x73KAvUHooxuELZUXleN2jJbv1xu3EGbv5m2VzoT5FASy+dHBkJWPXw4XrPhL6SrxajcJnqkrWP6Y+Ck2OaVqQLsR/AHdF+47T2KQpIHXovNED0Tklb1GRNa4JuXG7faiZkZ1rvTSE/cC5eHHoJVfaE45nRH8GUsmmm+5ySll6TdpPYlmid8aYps67BENLO4132LQmtG00thD3WS9RXImF7Z61qompcZ/Zgo1etS3M9ZC39G8cJUPcl5dTT5MPOtQCq06COml+XXZeHmsKg3amOtXrDNNNA5Br2NQgHGgUrqzqBSB1UJV1WY4BmjmaAY3BdkFQkSYk7KCx5GwAKRfjP5ijW0MY8udat9aTanrabnJuOnnGkF606uIPFidTW5Oz1QwdYGKUorDf6RChQ4FjiXgBiJGJPX5hZL1FVRmI5uirRGiMKM/mC6JPY4MncvOmxW6l0o16gMKDponKonrAsu8jHDtaQ5dT1WQajFjEmizREQflLWFQkWjFdaF3LWnBVg01CQwA3HSkFGi8KGPo66hDbEc2owDO2A65WqFSlFKWUp8Gsb7RgvkfKxNdu5tP1eQXpFKsjSzFiPZNHkU8gVRVYXlj5VftQjkntP2Q0TycVGSQK8/r0657dX9CdxLK66LJ8rZOqQ6qNrFuxh7jWwf/Mqdlx5+v1pQQuExUh7y1aOf1CkErZT7NSCVPbUD1MVEVYPJAxUyUAGAAKwfuw7TrgyNO4yGC/Brjhshewu6/OsT2247yKxe7PvduY6Bv23QNzEXQefCouNTk+WEVWSg9Nb013SzlH1kCEOIUuKCPHFsMJgvxp7+DiRtf0zDnEV72BuNu1drVUt2K7gMF7yRTT/t3j6WX2IwO7D8ob9CbjMEw57j+aRCxHlEfRRfNBGjx3NEYr0SBqFWwJNP0g8Y3l1tpN0TnJ18JXvtq7cLsavcjAW8amzW3Wa+BR68r2eQIIDhoZWyN9LDs0WTqrPhJBfUHtP288IjcxMNQnTh7qE/oI1f3Q8j/odt6+1VrOgchexA/Co8Ebw2nGb8sG0vfZBOPj7Ej34AFbDGcWth8BKAovnDSOOMQ6LzvPObI28jG2KzIkoRtHEm8IZf549PPqIeJE2pnTUM6QynXIC8hTyUDMutCa1rHdxeWX7uH3WgG4CrMTBhxyI78pvS5IMkg0sDR+M8EwjiwKJ2IgyxiCEMgH4/4W9qbt1OXb3u/YPtTo0AXPoc68z0rSNtZd25bhruht8JX45gAgCQIRURjVHl0kwSjgK6QtBC7/LJ8q+yYwImcczxWcDgcHTf+o91Xwiul941reRtpg17vVYdVR1oLY39tM4KXlvetk8mT5hgCUB1YOmhQvGuserSJZJd4mMidWJlMkPSEtHUUYrxKWDCsGov8t+f3yQu0n6NPjZODz3ZDcRNwM3eHeseFk5drp7+559E36OwAXBrML4xCCFW0Zhxy7HvsfPyCJH+IdWBsDGP8TbA9xCjUF4/+i+pz19vDV7Fbpkeab5IDjRePo42Plp+ef6jHuQfKs9k/7BQCqBBkJMg3UEOcTVBYLGAEZMhmfGFAXUhW3EpcPCgwvCCYEDQAG/C/4pfSC8d3uyexT64PqXerg6gPsvO3676nysvX8+Gz85v9OA40GiAkpDF8OGRBOEfYRDxKcEaQQMA9ODRELiwjTBf0CIgBY/bT6Sfgq9mX0BfMT8pTxiPHs8bvy6/Nw9Tz3Pvlm+6D93P8GAhAE6QWFB9kI3QmKCuAK3gqHCuIJ9QjMB3IG8gRcA7wBIQCX/ij94fvJ+uf5QfnY+K34vvgI+YX5L/r9+uf74/zo/e3+6P/SAKQBWQLsAloDowPGA8YDpANmAxEDqQI1ArwBQgHOAGQACQDA/4r/af9b/2H/d/+b/8j/+v8sAFsAgQCbAKUAnQCAAE8ACgC0/07/3P5j/un9c/0I/a38afxA/Df8UfyQ/PX8f/0s/vf+3P/TANYB3ALcA8sEoQVUBt0GNQdUBzkH3wZIBnUFagQuA8gBQwCr/gv9cvvr+Yb4UPdT9pv1MPUY9Vj18PXe9h/4qvl1+3T9mP/QAQ0EOwZICCMKuwsCDeoNaQ56DhcOQg39C1AKRgjtBVUDkgC6/eH6H/iK9TnzP/Gu75buAO727Xvuje8n8T/zx/Wt+N37Pv+2AisGgQmdDGQPwBGcE+YUkhWWFfEUpBO2ETQPLwy8CPUE9wDg/ND45vRD8QXuR+sg6aPn4ebg5qXnLelu61nu2vHX9TT6z/6DAy8IqwzVEIoUqxceGs0bpxykHMAbABpuFxsUIBCYC6cGcQEf/Nn2yvEa7e/oa+Ws4srg19/c397g1uK45XHp5u328nv4S/44BBcKuA/uFJAZdh2CIJcipCOdI38iUSAfHQIZFRR/DmgI/wF3+//0ze4S6frjsd9Z3BDa6djw2CnajdwM4I3k7+kL8LL2sv3UBOMLpRLlGHIeHiPCJkApgip7KigpkCbGIuMdDBhtETcKoQLn+kPz8ust5SzfHtos1nnTHNIi0o7TWNZt2q/f+eUa7d30B/1YBZANbxW3HCwjnCjaLMMvPDE4MbQvuSxcKLsiARxgFBIMVQNw+qXxOelw4YbatdQq0A3Nd8t3yxLNPNDh1N7aB+Im6v3ySvzCBR4PFRhgILsn7i3FMhg2zDfPNx82xjLdLYUn8B9VF/YNHAQS+ibwpubc3Q7We89Yys/G/sT2xLrGP8ptzxzWHN4x5xTxe/sTBo0QlRrdIxwsDjN+OD08LD45PmI8sjhDMz0s1CNJGuMP8gTN+cjuOeR12sfRdcq6xMbAuL6kvozAZsQVym/RPto/5CXvnPpMBtsR7hwuJ0ow+jf/PSpCV0RyRHlCeD6LON4wqyc4HdUR2AWh+Yvt9eE817PNpsVWv/W6qbiFuI66tr7fxNvMb9ZS4THtr/ltBggTHR9OKkM0rDxGQ9xHSEp0Sl5IEUSuPWQ1cSshIMoTzAaM+W7s29801NbJEsEuumO117KhssS0NLnPv2XItNJv3jvrtfh2BhMUIiE8LQM4IUFNSE5N+k86UAtOekmpQso5IS//IsEVzAeO+XTr7N1g0TLGvLxItROwRq37rDWv5bPruhDEEM+X20XpsPdoBv0U/CL3L4k7VkURTXtSaFW/VXxTrU52Rw0+uDLQJbUX1win+ZvqKNzAzsvCqLiosAqr/KeYp+Opz642tuG/hsvO2FHnofZFBsUVqSR8MtI+SUmOUV9Xjlr/WqxYplMSTChCMzaQKKYZ6gnV+ePpkdpWzKK/2LRQrEum/KJ9otak9am1sdu7G8gX1mPlifUMBmwWKibLNNtB9UzAVfdbZ1/0X5ddYFh3UBZGjTk8K5EbBQsY+k3pJ9kjyrm8ULFEqNuhSp6vnRCgXKVsrQS408R2033jbPS/BfIWfifhNqNEWVClWT5g8GOaZDdi11yiVNVJxDzSLXMdJQxu+tfo6tcqyBK6Ea6HpL2d7JkxmZabCKFgqV+0sMHt0KDhSvNgBVcXpCi+OChHclM5XTJkJGjuaIlmBmGOWGBN0z9OMEkfSA3W+oLo29Zpxq+3HqsbofSZ45UIlWyX/pyVpe+wtb5/ztHfJvLvBJwXnClhOmlJPlZ7YM9nAGzsbIpq6mQ3XLRQt0KtMhIhbQ5P+03o+dXjxJG1eagEnoSWM5I3kZaTQpkOormt6LsvzBDeAfFuBMMXZyrKO2RLvFhnYxNrgm+QcDRuf2ibX8xTbUXtNMoikQ/Y+zboRdWXw7izJKZDm26T4I7AjRiQ1pXPnr+qSrkAymHc3u/fA8oXBSv4PBlN6Vr8ZfptpXLXc4ZxwWu1YqZW8kcJN28kshBu/D3ovdSGwieyHqTbmLWQ7YupivSMvpLbmwWo37b2x8bav+5CA7UXdivsPYdOxlw4aIRwaXW/dnt0rm6CZT9ZQ0oBOf8lzxEQ/WDoYtSwwd2wa6LMlluOWonyhy2K/Y81mY6lqbQSxkLZpe2bAoQXuyulPq5PUF4aaq5yyndFeRJ3QnEAaJNbXEzQOnYn5RK9/Z/oMtQUwdqvCqEYlWGMK4eehceHl43gll2jrLJYxNfXk+zqATcX1iskP41QiF+ga3d0x3lme0h5enMraqBdPE51PNQo8hNy/vjoLdSywB6v+5+/k8qKYYWvg8OFjIvflHSh6rDJwofWi+sxAdIWxitqPyVRbWDKbN11XnsifRp7VnUBbGRf4E/tPRYq9RQu/2rpUdSJwKquQJ/DkpWJ/YMngiOE4Yk1k9efZq9pwVXVj+pyAFUWjSt3P3ZR/2CYbeB2jnx2fod80XaAbdtgRVE1Pzgr6hXw//LpntSYwHyu154kksSIAYMIgemClYjikYaeIa45wELUoemw/8EVLStMP4FRPmEKboB3V31hf4597HembgRiaVJMQDos0BazAJDqEdXewJSuwZ7gkVaIbIJRgBaCrIfpkIWdHq08v1LTw+jq/hoVpyrqPkZRK2Efbrx3t33jfy1+pHhyb95iSlMvQRotpRd5AUHrqtVawfGu/J75kUyIQIIEgKqBJYdLkNScX6xzvoTS9+ck/l8U/SlUPsdQyGDYbZR3r336f2R++Hjhb2Zj51PdQdQtaBg+AgXsZtYLwpGviJ9tkqWIfIIhgKiBA4cJkHWc5Kvgvd3RP+dg/ZQTLymKPQZQFGA3bQl3P32ofzJ+6Hj0b5xjP1RUQmguFRkBA9jsRNfuwnOwZKA7k2GJIIOogA6CRYclkGmcsKuFvV3RnOaf/LkSQSiOPARPEl88bB12aHztfph9dHiqb35jT1STQtQurBm/A7ntQtgCxJaxjaFjlH6KKoSZgd2C7IefkLGcxKtjvQXREebk+9IRNCdjO8JNwl3patB0KnvIfZV8m3cCbwxjF1SYQhcvKxp3BKbuXdlExfayAqPhlfuLm4XxghOE94h2kU2dIKx8vdjQn+Uw++AQCiYKOkJMKFw/aSNzh3k7fCp7Xnb7bUVillNiQi4vkBonBZ3vldq0xpO0wKS1l9aNb4eyhLGFZoqrkj6exazPvdfQSOWE+uUPxiSFOIhKRVpBZxlxgXdIell5vXSYbCphzVLxQRkv2RrOBZzw5ttNyGq2x6bcmQ6Qp4nYhraHOYw9lISftK1fvgLRDeXk+eMOaSPXNpVIHFjyZLRuGXXwdyN3uXLXarpfuVFDQdcuBRtoBqHxTt0Pyni4E6lUnJ+SPoxiiR6KbY4slh6h7K4rv1vR8ORP+dsN9iECNWxGrlVSYvdrUnI1dYl0VHC6aPZdXVBZQGcuFBv1Bqnyy972y7u6oasan4iVNI9NjOmMApF2mAujbbAzwOPR8eTJ+NEMbyAJMxBEAFNmX+NoL28Zco1xkG1DZt9bt04xP8gtAxt0B7TzW+AAzjC9bq4rosaYhZKYjxWQ9ZMam0ulN7J5wZnSEuVT+McL1x7vMIRBFFAxXH1lsmugbjJubmpyY3ZZyUzNPfos0RriB7/0++Eq0NS/eLGEpVScLpY/k56TRZcXnt2nSbT7wn/TVOXu970KLx22Lso+7ky2WMdh3mfMantq8WZLYLxWk0otPPwrfxo+CMf1qeNx0qPCu7QhqTCgK5o/l4KX75ppob6qo7a6xJXUt+Wc97YJextiLOY7kEn4VMZdt2OgZmtmHGPOXLRTFkhQOs8qChqGCMz2YuXS1JvFM7j/rFakep6Vm76b754Qpe6tQrm0xtrVPeZd97QIvRn0Kdo4/kX7UHxZQl8hYgVi8V7/WF5QVEU5OHIpcxm6CMr3JedL17nI3bsascOoFqM9oE6gRKMHqWmxJrzpyE/X5eY097kH+BdwJ6w1PULDTO5UgVpRXUxdc1rgVL5MT0LmNeUnuRjZCMH47ujZ2fjLtb9utXGt+6czpS6l6adNrS61TL9Yy/PYsecg98YGLBbaJF0yTz5USCBQeVU2WEVYp1V0UNVICD9bMyom3BfhCK/5uup43FXPt8P2uV2yJK1zqluq26zesTm5s8IAzsXaoOgk994FXhQzIvIuOjqzQxdLLlDTUvNSkFC/S6dEgjuYMEAk2xbRCJL6iewl383S38evvoK3jrL4r9CvFrK2tom9WMbe0Mbcs+lA9wIFkBKAH24rADbkPthFpkouTVxNM0vFRjdAvzefLSkithWpCGj7V+7e4VzWKcyTw9u8M7i9tYi1lbfRuxnCOcrx0/Pe6ep09zMEwxDCHNUnpjHrOWZA5kRKR4RHk0WJQYg7wTNyKuYfbxRoCC/8IvCf5P7ZkdCfyGTCDr69u3+7Vb0twebGU84310zhQuzC93ID+g7+GSokMS3ONMc68T4uQW9BtT8PPJ02iy8TJ3gdBRMNCOj86fFm57HdE9XOzRfIG8T0wbDBUMPExu3Lo9Kv2s/jve0p+MICNw02F3IgpCiQLwA1zjjeOiM7njlcNnsxIiuEI+AaeRGZB4/9qPMv6m/hqtka0/DNU8pbyBbIgsmRzCrRJtdU3nvmWu+r+CMCfAtsFK4cBCQ3KhcvgjJgNKY0UzN1MCUshybIHyAYyw8LByX+XfX47DblUd5/2OnTsdDuzqrO5M+R0pjW2Nsm4k7pGPFG+ZcBzAmlEeUYVh/HJBApEyy6Lfwt2SxeKp8mviHiGzoV/Q1iBqj+CPe+7wHpBuP43f3ZMden1WjVdNa+2DTctuAg5kbs9vL8+R4BKAjiDhgVnBpFH/EihSXxJisnNiYcJO8gzBzUFzESDwygBRf/pfh98s7sw+eA4ybgy91/3ErcKd0U3/jhvOVB6mHv8/TL+rkAkQYmDEwR3RW3Gb8c3x4KIDogbx+0HRkbtBeiEwUPAwrEBHL/NPo09ZnwhOwT6V/me+Ry40rjAOSM5eDn5eqE7pzyDve0+2kACwV0CYQNHBEhFIAWJxgMGS0ZihgsFyAVehJPD7sL2wfOA7f/svvg9130RPGr7qPsO+t56mLq8uoi7OftL/Dm8vb1RPm2/C8AlgPPBsQJXQyJDjgQYRH9EQsSjRGJEAsPIg3eClMIlwXAAub/Hv1++hn4APZD9O3yBPKP8Yzx+fHR8gj0lPVl92v5lfvQ/QoAMwI5BA4GpAfyCO4JlQrjCtoKfQrRCd8IsQdTBtEEOgOaAQAAd/4L/cj7tPrX+Tb50vis+ML4EPmS+T/6D/v7+/n8/v0C//3/5AC1AWcC9wJiA6cDxwPEA6ADYAMJA6ACKwKyATgBxQBcAAIAu/+H/2f/W/9i/3n/nv/M//7/MABeAIQAnQClAJsAfQBKAAQArP9E/9L+Wf7f/Wn9//ym/GT8Pvw4/FX8l/z//Iz9O/4J//D/6ADsAfIC8APeBLEFYgbnBjkHVAc0B9UGOAZhBVEEEQOpASIAif7p/FD7zPlr+Dj3QfaP9Sv1GvVh9QD29vY9+M75nvug/cf/AAI8BGgGcghICtoLGQ35DW8Odg4KDisN3QsoChcIuAUcA1YAff2l+ub3VvUL8xnxku+E7vrt/O2M7qrvT/Fx8wH27/gk/Ij/AAN0BsYJ2wybD+0RvRP7FJkVjxXcFIEThhH4DukLbgiiBKAAifx6+Jb0+vDF7RPr+eiM59nm6ea/51bppeue7iryMfaU+jP/6AORCAgNKRHTFOYXShrnG7AcmhyjG9EZLhfME8QPMgs6BgABrvtr9mLxvOyd6Cjle+Kt4M7f6N/+4AvjAObJ6UzuZ/P0+Mn+twSSCiwQVxXrGcAduCC4Iq4jkCNbIhYg0BygGKQTAQ7iB3QB6/p49E7unuiX42DfHtzs2d7Y/9hR2s3cYuD35GvqlPBF90r+bQV3DDATYxnfHnYjAydoKY4qayr9KEsmaCJvHYYX2BCYCf0BQvqj8lvrpeS23r7Z5tVP0w/SM9K906PW0tos4Inmuu2I9bj9CQY8DhEWSR2rIwMpJi3wL0oxJjGDL2ks8Cc2ImYbtRNaC5gCs/nt8Izo0+D/2UfU2c/bzGfListGzZHQVNVs26vi3OrA8xP9jAbjD84YBiFMKGMuGzNNNt03uzfnNWwyYy3vJkEfkxYoDUYDPPlW7+LlK9111f/O/MmXxuzECsX0xp7K7c+71tXe/efu8Vz89QZoEWQbmCS9LJIz3zh4PD8+JT4lPE84vDKWKxMjchn+DgYE4Pjh7WDjsNkc0evJVMSHwKO+ub7MwM7Eosoe0gnbIOUV8JX7RQfNEtId/Cf9MIs4az5sQm5EXUQ3Qgs+9zcoMNgmTRzaENUEnPiN7AfhZNb4zA7F5b6vupG4nLjSuia/eMWZzUzXR+I37r76fAcQFBYgMCsGNUs9vEMlSGJKXkoXSJ1DDz2fNIwqIh+6ErIFcfhb69jeSdMKyWzAs7kWtbuyt7INtay5dMAxyaLTd99V7Nr5mwcxFS8iMS7XOM5BzkieTRdQJFDBTf5I/0H3OCsu7iGcFJ0GXvhM6tXcYtBXxQm8w7S/ryetEa2Br2W0mrvpxA3Qsdxz6un4ogcvFhwk/TBtPBBGnE3SUolVqVUuUypOwkYtPbMxrSR+FpQHY/hf6f7asc3gwee3GLCvqtmnr6czqlWv77bHwJPM+dmS6O33kgcLF9wlkzPEPw9KI1K9V7Ja6FpbWB1TVEs7QR81XSddGJUIfviU6FXZNsunvgu0tqvppdWilKIopYGqd7LNvDbJUte15uj2bAfEF28n8jXcQshNX1ZcXI9f3l9DXdFXsU8fRWw4+ik3Gp0Jr/js59nX9Miwu3ewoKdzoSCexZ1koO2lNq4BufrFwNTf5Nz1MQdbGNMoGDiyRThRTVqqYBxkhWThYUNc01PTSJY7gSwJHK0K9Phm54zW68b8uC2t2qNOnb6ZRpnsm5+hMqpltePCRNIS48r04gbRGAkqAzpFSFxU612kZFRo2mgyZm5guVdVTJk+8C7RHcELTPkB527VHcWMti+qZqB/mbGVG5XEl5mdbab/sfS/489Q4bTzgQYlGRArtDuSSjNXNWFIaDRs2Wwxak5kXFugT3NBQzGMH9cMt/m95n7UicNitH+nRp0Ilv6RSJHvk9+Z7KLQrjC9n82c353yDgZZGegrKj2ZTLtZKWSSa7pvf3Dbbd9nul6xUiBEeDM4Ie8NMvqZ5r3TMcJ/siClfprskqeO0Y1xkHaWsp/dq5u6esv43YbxiwVtGZIsZD5YTvFbxmZ/buFyyHMscR9r0GGFVZ1GizXTIgUPvPqU5irTFcHjsBKjDpgtkK+Lt4pOjWCTwpwpqTe4eMln3HHw+gRjGQ8tYj/QT9ddCWkPcal1snYidApummQZWOdIezdZJBgQVPut5sTSNcCPr1ah+JXOjRiJ/oeHiqGQH5q3pgi2nMfs2mHvXAQ8GV4tJUD/UGlf8Wo+cw54Onm5dp1wFGdpWvtKQznJJSUR9/vj5ovSkL+Eru2fPZTPi+aGqIUgiDuOzZeJpBC06MWI2VfuswP4GIEtrEDmUadgfWwLdQ56XnvveNVyPmlyXNdM4johJysSpfw0537SJr/Crdme35IzihiFt4MahjGMzZWkolKyXsQ92FXtAQOaGHgt+UCFUpJhrW12dql7HH3DerF0E2s0XndOVjxdKCgTW/2f55zS975HrRie3pH6iLGDLIJ5hIWKI5QIodCwAcMP117sRwIiGEUtC0HbUipigG59d9x8cn4yfC12kmyqX9pPmz19KRkUGP4i6OTSAb8UraqdOpEliLGCCoE9gzmJ0JK4n42v1MH/1XPriAGTF+os5UDqUm1i9W4heKh9YH87fUl3uG3TYP1QsT58Kv0U2v696FPTQ78prZCd85CzhxqCUYBogk6I1pG2noqu18AQ1ZfqxQDuFmYsh0CzUl5iDm9geAt+5H/cfQN4hW6tYd9RlD9bK9EVnv9s6erTvb+DrcidCZGnh+uBAYD6gcWHNpEDnsmtDsBD1MvpAAA=\" type=\"audio/wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\n## Video\n\nMore exotic objects can also be displayed, as long as their representation supports the IPython display protocol.  For example, videos hosted externally on YouTube are easy to load (and writing a similar wrapper for other hosted content is trivial):\n\n\n```\nfrom IPython.display import YouTubeVideo\n# a talk about IPython at Sage Days at U. Washington, Seattle.\n# Video credit: William Stein.\nYouTubeVideo('1j_HxD4iLn8')\n```\n\n\n\n\n\n\n\n\n\n\nUsing the nascent video capabilities of modern browsers, you may also be able to display local\nvideos.  At the moment this doesn't work very well in all browsers, so it may or may not work for you;\nwe will continue testing this and looking for ways to make it more robust.  \n\nThe following cell loads a local file called  `animation.m4v`, encodes the raw video as base64 for http\ntransport, and uses the HTML5 video tag to load it. On Chrome 15 it works correctly, displaying a control\nbar at the bottom with a play/pause button and a location slider.\n\n\n```\nfrom IPython.display import HTML\nfrom base64 import b64encode\nvideo = open(\"images/animation.m4v\", \"rb\").read()\nvideo_encoded = b64encode(video).decode('ascii')\nvideo_tag = '<video controls alt=\"test\" src=\"data:video/x-m4v;base64,{0}\">'.format(video_encoded)\nHTML(data=video_tag)\n```\n\n\n\n\n<video controls alt=\"test\" src=\"data:video/x-m4v;base64,AAAAHGZ0eXBNNFYgAAACAGlzb21pc28yYXZjMQAAAAhmcmVlAAAqiW1kYXQAAAKMBgX//4jcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTE4IC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAxMSAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTMgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MzoweDExMyBtZT1oZXggc3VibWU9NyBwc3k9MSBwc3lfcmQ9MS4wMDowLjAwIG1peGVkX3JlZj0xIG1lX3JhbmdlPTE2IGNocm9tYV9tZT0xIHRyZWxsaXM9MSA4eDhkY3Q9MSBjcW09MCBkZWFkem9uZT0yMSwxMSBmYXN0X3Bza2lwPTEgY2hyb21hX3FwX29mZnNldD0tMiB0aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MyBiX3B5cmFtaWQ9MiBiX2FkYXB0PTEgYl9iaWFzPTAgZGlyZWN0PTEgd2VpZ2h0Yj0xIG9wZW5fZ29wPTAgd2VpZ2h0cD0yIGtleWludD0yNTAga2V5aW50X21pbj0yNSBzY2VuZWN1dD00MCBpbnRyYV9yZWZyZXNoPTAgcmNfbG9va2FoZWFkPTQwIHJjPWNyZiBtYnRyZWU9MSBjcmY9MjMuMCBxY29tcD0wLjYwIHFwbWluPTAgcXBtYXg9NjkgcXBzdGVwPTQgaXBfcmF0aW89MS40MCBhcT0xOjEuMDAAgAAACqVliIQAV/0TAAI/3gU2tIW7KawwaCmQGTGHKmuYAAADACBcshU+yICkgAA14AHowiEeT6ei7v7h3Hu0i2fpUBLGBIkbCMP3Vfz+9BVGCDXnw9Uv5o3iN030tb7eq6rsEEhHs2azbdTiE9Csz5Zm6SiUWRdmB43hbD5i6syATuODUJd7LM3d9cbFpc7zFlu5y3vUmNGd6urpvKKT9iyleIyTuR1sVS431DhevGfkUllVeIznYUe2USoMW1tufETjyRdmGldN6eNlhAOsGAH4z+HkrwKecPPU7Q5T4gDAIxj9hW84jVExMTSTHxkPTq1I4OotgUxURCGTsw60k/ezPNmNg38j1bqaGmPcruDKEIBDsK5qEytFB90Q68s0h2wmlf2KXd5bleBefiK+/p47ZsyUO4IdlW25rRy+HLjt6wQXfYee3IkiQOoOK+U7u/lxcl78zfxwIoEMjUUSKNZjkp8clnmecDDJ3Kz+viF7bPklk7N6QRyizAKPIIpnNJUuMWQmqeL2Or6cr4D0/0tOym+4tficxmhuEONKUtO2pPn3hRjMllkd12tXp70fLTfxy0dwB70ML9iLEcItHb7zVupHlP5RxdvecpREw+OsIPr9KWilIesNE19jgIbT+TkiRBjOoKvUuwcQnKg7fOTHVoLvnKuAfea+oujEdm1Rwd2tEOnkF+ZC11WaNQsiNR/eJ9EnUXjXDYGfhB+Oe7qj8nYTT+eOXg1cuJNgLXEs4vOheWEjQOqfIWMQc3DmTof5s0ksBmUQ3PQ+UHPxZSnmOEZB+j6xT3wbm7HGzDjWtSg1SjTxd1EiJ8xA4SIxxR8WIKLg+TwFxJNS7Laxq7Uglu3AkXe82P1JCdJX5PsbFbxuDbuJgakzRcTwMLLSKCiizS/eCW0uJed/lev9yb80kKlVET4S219cn/zhkpeDV83cHYOr+sJQKDRk/Wh2c7fsuxfxaEH/6reSmvFDsAnXAyPXliJ3G4VG3OkEM5K5WyGGrBizZbTrdGsBnzj5VSGGOJdCKuRrUluw/8es2vYRPs9BcTqAqvHk9M52SSIf+1T6L53EZP8VbtXB+G29CMW4xVCK/B/YDjaNmqMwJ61dapugjnWJfqeXlGGa3Ch3aA7gi30T8PucNRBjLK3lF67ZDDvkWXRQXd+VMnKWHkBbCkQ/F/fMuNpHO3C00Y2pljna1qImBhVMvPe0F7Qx7G/YyxLRzhyUU8e23HGzp0agtNJRbydbrPV+TqJMSifJMNcZIf8wkdnC3/xdpcXnLf2Ye3Kbd0o7utciTG+q5h6WTEk+PaNbXLLA0YyZ2VnLTcyV1QTS76aNCbV9Q1/OQ7QU81Gg0hPa9aSiscGary6jLVwDQaik4zLsi7jPqgPVdup7pwx7uJDqRCVcVi5QoZFp/GHdex5sJTF69A6sja69/NLkFIWNSIeRcuGahXpF+wZeYIrqJv975s1TKYKAvp1WtzgtgWNkcbzCtROqf8rPtlAIxkX8GLcEo9zfExyfimeXQ64qfFxEy0IMy2Hsxau9fSMqUnIjntuVVjCQtBL+94gx1RZLndE6wROVTq/wHwHrQzo9QL9cpPqPFJjiZ/NGZIFuudS+wsBFe6Hu8Oitf5zToLqLdtU4Smwh4ne3JsiT9lOzN+4PPw3VSx9l5FppVwdKUWELw1dYpCOppyVWlJ3YQ8H4FQQM8EcYMG9N3Bxu79y1J1ikuvuhMmLQlehLTbguhbix74hd1VIQC8EjHmOZSSWbssulYwPbr6FF49tifk6PymJvulR9/u+2585HkRfbxveGeWCz0ix1pIVfaNpESKmtLy/0mcbMg9hYDz2werz9oe0lT2BiMV6uAin6RaQcT8Vk9MPctfwae+gkvtnZA/sOBk8MbpylaHqc0KIVHhhLFMNnkOFiucjtGo/JWTa/F6g8wWeow5ZuIJUORaYHWqegZbTgM9dCsYYsfZGjjVMuSlDIvpYvIvFFooGPC7Ye2Jfawmq4Ut7EL/nv/dyAd2HRc5msmUhzeu/XpX3rVlzRmf9/Qan8Dbve3QfW1Ym0o5J/KAc3z1VBho7JBr5PgCL68RiD9jZHN0VvsT4gzsEjNlW3D91Uy4RduaodBFoNTzXwlfUYULBzdiTbH75l/UmVMC4TKeTWhNzw2UezaqeGd8at3WSY7W/VR3+hvZHDpkIjgKuNNH0DsCRa/Kk56XQoHIyvvUH/eNekNvziReqS4qgLnXUT4BRGt2BOtCifI6+X/DGHUOmWlX7TN5b4pw5U7jwfwshtbhGZM49T8JMk15Mzrc7tM6J11TYxb5R3mQhZ8TZumJ0bMJXPM69HFyihr5dJSEJMycxJVUh6NTQALUOoRTHIOwE+FpWI6feTv1SiZ0YpYe5DbkYJJbN7zAHbAKw25XvqR2mAjQmOlsfX/tK8DPjP/8h5/xgAF4EUbj1tOnQCBQL8jk9vHtfsXncsprww4Z+P/Z/UrKifuFyEpBWN8kLpF7yywE2iYdDruV9+/qKR8rC9ozNKyqQNIwtxrzYkWpE5t8K7gG4JFnrHona/Rp8dOX6VW41+jb5LB1LEtE8MwjLp3RCUOq/+6yLzaOEgBTqzvEjDeFpg/u9DMHMr4/2TOchfjg7dl+uQ6Gsx+4Ia9W7vivG95027p25eKL0nHvx/OqmAQEZYJL/JO58lOj0zPdJxrQ5dZksjMISzVZNn7DsxqE3zgBBuNzk50R8lTK3U8P12QiOAQYSTeGlYlkvfeofrfO1AitEj02m9aUkxTFd1ZZJoLQT2d3zEU5PmE4lxMVfL5ttNnIbqfcIU2RJKNWqdw77xfjfrNc/eNpRKPZ/6z50LzBprgjzBHRfKgSWWkDxHrX0aTbgwQFwd51+PoUWH4DkQg26uGslF5Hn3hB58+fkeLTosTANOIBNAeFZtTc4PIaLHw759zae7scY55xcTabzlilYIftst2RZ6ntsRC3zFxduCKvL6wLfYT+TiIWJn5P7sTwZwXuSzXY+9Q3xMZ5o4Xcpz6vD9FtTjzS69iefEYt4pXiDrZUo4ePGiLeoIFIwYB/v6GXdmG5VLLk+eKbOc9AmsX2zmvqtcvDRGQbzugXbH/kTH/lkNPBTmqN3ZJODUEXVohPEJ6th0xna0EVleB73Q3eNvaVUvhlJbjs3D/T17FRCebN7AOXvzzbLE/I5kNfEmJcv4dxtIeo2uQ/z9ohSpiZzbDj1u40nJRyJxUK60wEv0nA9f/NuJ6/PEyU0bkK16z2KH12k3Lc4+1f5fawIzkK2qJRB4wnj8VHhUW9mbJhs9vgfFmU3xrXSShY67Ygb+gYNPxxtn4K/9eTSwIA9fv/nR33lA2lZoXALRUTmOZIl3R0gAM5h6oX1y1thIyqViBK95VZc8Pvy7G3O90M9S4zkpyFQ36jrMazvMveMA4d39fvoaC7p90quiJfjI4yrl+ECVkCJL5MxRSa+iVcIL7Xbl0jVaGhZIcMYmcGOBbLzhJgloM1x1zFnnj3ggJRFAM8yNnXxhavk+mA18JC+y3lqGsp6vPReRxGlGHMou17L4It070LzkoeCzarpv8Apw59smdS5KN9qVN1WgeL7OSN8BHg94ubCvS7DW6H3/PbtRB62jFLsBhUV5YqCIbIN5VZ81AAACpUGaIWxFfwAru8x8uT3FuOjrAeSWXmAWqq9jCNGE+N5AOv//9//xjk4uBAcADN96c97AVGmzRtnWwPsgcCbLrVdQJgbKp4QSmPwQnVhv0hXyBjeFWWlcvx70urEN3FK6/lvk2tQeZgbtlbzXluvTfnSj/Ctz7vZ+O1FjhDzzdpL7uLzewzCIW5VWLAEKUVuS2J6wNk6MR7UblcEd4EtOY+R4/qJgfojCsfRvA0oC5dc41Vd0erZbSkrmPTjLCn815bxlchUJMS8gQD5hJNwoKHvNLNwn7XKuTtYIhH2wVNZvDWgzCjlPeQajnrcMsb6bZYJvNJU8HuGHvm50r7VG8qifEwmuyegAZXojh5Ul5VvjDW7kSAZyw8a7I6mHY3FZHd+OA3V4JZMbNliI3Tj1L6+MKTmilVialmyZagRtEMeKRdtxUPd3vVEtrOBVIVYWdgAGA7HmZiHQUQNxLkWxbLyWVlrh5EM0Do2NdbclHxxArz90d+MSVeUOIXQ/4V9quq8C8qVflo1gPtPMkjO2/UrdOYqhY404ReObOu/fdp4hAEDq6jhy64vOeT7XUK/Onq0rXTldtA6kvgQaJg+mgYSR9hfXtMbOUSLgLj/RmBSO8aAMHuJJZqf1tCM5pZ9eYUsrHmy+/z2NGalon0//uF6+33bQzT/RLRfBbYTjy9QrJqHLlw46lggWPGkHuPKSqk/CB7U4pNPXUbR0DdcJy9Db00wCzVzxVc6h7jfCFgiL2Y0HVqd6bgIaVUqn/gJCEyCDVplnzebv0gg3XwMJAGu639lHu7rEvxTp1smIYjWp9R5L4SspVvS07Nb+Smk1FgsMp1K3EMUT8X2Fty4VG54/Ec6bE8tNVw4/QV1VzBw7Px2/2eEhhUS+FMfbHAlD28x00jRgAAACW0GaQjwhkymEVwArOUkEOhoFqiELtH8wgecFLiUq6WqmwAP7iGEwbYzfnHacfqUNXAfD+CGR2ap0lAHL25ipuYtd5j2O0PU/MpaWPG/n2y5OkfTzaOpotaR5tWjN55B2XblVVqsFfBC/mvsiPvCBWUHFChacdY5whj5mP5rqQ0dqLJCsWjrs4TWnIbL2V/Iwfj3hwI35jfo1JkTOeR+8GhOdma9rgiKWafCbQyhYMTDmVdvhND60Flm97EDSTjF0OC+0gD9b8Yn4tNeHipCa/aWyt0n79bMmjfcjntBCPjrcB5ecRTpfGHbEHy1IRj2cjkGXKC+VYoYJXBp4rd4cMd8ygLCk5nBSd8/cTaKNRjdBscOeTXG6QEjSxj9/2pVwx9DMRVtWQR0BSaAcQcZ8W2KPSaeRC4QwmNMu2xx25CSyrDiq2rFSK/JJtmvoIjAKq0ciEXoOgw+Ke+Ylb7ULKCS3k1p/613UNRp450uSq5b7CAHo7S0b7fBMLfNmwSjRYEhLlo0HUaRe/I+IX2Z6XdZH9Hty/399ZA1PwZGC6EfvUJIf7CBeaxv7cu6IT2/s0zPRGthpvXpYw6A7P4Wwz5C4V98KnIUNUanadqabKP6eXWhvbvcQHxAjiOOiKZgXZplZW2g+B2NNyJSLiR+g48DqvWR6t9S2aGfFjdOW1Gi6oTtZ1d4p5XIslAr8mryeZ6+htSSQe4AcfVt7k+V6mOthBCYtr/LEU4ZHtl0mW9876PK8mRFAaT8DJOUFVz1lPfzRApuPggkkyq+UMvyfKTUbCk7/DpfX8Y4s4QAAAg9BmmNJ4Q8mUwIr/wAsWUPjZw3ksgRsxZ6n4fQjprPbkj2aUh30y0bZJnLmiXnWskvOGnCPwBnG9dEhatwX3hoxk7BNyG+wQ4emZUpcVzcWl2T9nKQB1euucuZWHTg7TCtM/iHyfPO2vbmGsfzs70b/egIbywUH4y4BQSL1nWc1SmpHm2zHMBcUjYLDZ5gL5vdfxn0V8FFw66G88c/LN4I5icUa7xf4fcSBKywU0ajbp1P+aJYjBgWT6Ggu0MDLDNl54tfqd42lKosQtM1aif4WXAZFP5Ww3vrQ1rH9+utSYxqZd6N6gGtNbSNMcViaKn5LcnjsbBi3T3EmGqshEbcme8VHKwR3kSfBOAprrIsv6K8R+X6az+MD23rWka/2v64m1qM69D7Xa+Kcs/n0KLCJdTilyaGadopLeaAn3eYvWTeHcucMM1Fp1KgHD1tiFeO6HvobLkZlRximsA3/7MiohYklLIcJrZL22BH+6W9d6kZsYIsej9RM681nU6mWNjepBAfAfTbrGRrVB/h2DxC5B8YyRjgSIzQjNYrse0rzChqbrsLl7mQ7W+1bsNKze5//9ZIa8rSsF+BXh/vgoRTDkPW/ws95B7VPCZEFChfX0icw+tpcpN/q7NY87tUn4vESdSiMMlyhKklMjQu/G51J69ZRQLs2oUO6YfoJFqliy4qCFCrf8SZE9Fc6DcCagAAAAodBmoRJ4Q8mUwIr/wArPWF/KOw78THwadfPqhJO0CnmR/M74/XYZLqVYKlNcEaYauf+vrRUDJPmu75sMKy2Y+Bnslc/iAISSyWtw/h/3CF8fE5ZrbrwSNst+MSyCoNWP+8imtoX2eyojpdCk8YP5K+cbK4SJPCkZXbYqSXYk7hO8AdSemBHgXKWiZ+UOr802aJo+98ZOIjX9hWL9bo31Gqx7cy4ZG+W/ar/WGlzDa1xPWnPRsEdrIcZlEVGV/jGmbirkxw1lyUYoqj8Vv7Bxube9XPQlBkXOV6Lc1LT2IzNq0V7WwVhF0kA6yxfAsFxc9krNEH8vGGntTWI608ovjatXc/CKKXw7AjJSftlTcLI0hIIGXbRUr0NCYNp7M4cVd/n73Rjetnixz4SAKpcz/P47UsijZG7T3SxzK2D79WS42aEalc12hQwCZ01LfmF/H2mmGEvOzPBie1D0YT7Jh19vxa4Dd3SQ1FrDfmSUpvv4DjbYcZ2PrPpFpWtMjWqHBeoyMiZf6RP3EfYR6z9jsVNIIHxM0bzzBQF8eeYkPgDySydxPXv9Izo+QUY94N8kWi16fI6eZSDc1G0Yo0L91jcRQuDMGGS7B2zuf/0GbJyRhUO48UbMrqnILMrbQg1LF00Q3pH9nbGEK/RRQpRN3T/J/4IZQjwW2Ft2ipWGztg1Jn9I4DmffKS60QC+JQcyakdVON6zDcKttIKlqeTcmAi4xzmo4QXa2dRKleS+fs3EtTdBBtony2wK9T2Imj+NCziOSEL7Q7VuIU8kclUHrJJsSneFcxGRgIgGGUEQM8/pklwTOqab7mMmJeRiaBrjJDEnDpkR4Vz3qXxgyn4/5x24FuTMNVPwQAAAhtBmqVJ4Q8mUwIr/wApcLwPT0/Xh9UdWqWXIs8Wbj5K1hivmN6qIQnq+aolcegdlM/63MbHsdC6xYZC1e/Q8UjQCt9N/Ejqwms8DzeWv2qxskeliZH0kt1QWkErWSEodq7V0ZNksctLkMGWayX33gBT368EehfIeGDolBZoqIbJfb4nqcfU+ev4OzVv9zVqWyLck315GFmXxQKIM8pICQc8Q5es34LH1+DmnMnW8kQpVGrztQcDXhjCU3F0fOgoSsXSVWCjc6XKqGbCwQDfJUxCfXfIT6YmQoPpVp1mpGy1wQypXus9z0bScDpyDu23hViYDntdj1O45ea0znKZkj1+tLHbBtqAGJ1WTcbGlF6Vya6hQhEsiiZUIC2fRxIj8/wEXCICIbr0gZ/m6gcOhE10tenvE7iy+BKY81wLWrnzos3S6FWxYtmCRes+LLhNGOKWRuQo6SyePH2OZ90xZm8oA1MuTe3V59euVNxjAt0FLkAc9TEiFhP/8CB+gA8mF+A8h1U01f4DVX55GzCH51jHI2xUS0L9GtsHoBxLPLK/NNel8zcnwG4X+UusfcfEb5hh+ffnXteCE9vRGbs2n9wYW0xA3ZicklfadmWKUtMiHYBfkMSULWnkBQr4CXxjpYOs6ygeEoA5+5B0B1SZObgZ42wWqddyyYE0NfwQAl75tfdJGqOa7OMHwBYNeatJaJK0zT2+bFaw2qWCWwAAAitBmsZJ4Q8mUwIr/wAstkdsayRXchoFk703izqzduZ5WsyXriI9cfUdMUWvm0iGHwYIrUujvz3Yjou+JLwv9df2kt7MJo8u+3P5CjEKbwlz4vkE5AHTAbgXn3+Xc/MMJLgW5cm7iX3KiGNnBpbphhwJRlb3u91NRDr0d1IR2up/z7lKxE7XPAPFe0siPMYVlIqWNSn5KqLABPeuxxbOsvMEb27/nH1LUVM8I2F95c1I3Lv1SpkhZXjs1JsmS9X7gsoTxkXyShGC2+zRJSGUbhCPo/q1XSFMHQyMWJ79FKPQSL/RpVsacN2bYwdKo4TFBw1SsKq/L1iOmqMI+4Gxnbbjojdk0ek0JIcDb4bHv1czxchF7FX1Ym8H6IpPuE8CeNKjzQ1a1wqhEu+wl1N0x3Y37ZryCCKJRkxj0FT7bOoH3L38/yMUuh/v3aCmxY4eCkykb2p6ZrYMFE044anM/nMjmbErMibfRFuCz58Io1rBlF7JfkIz0R2/5vjUMVskcdbX2mm7DntncOsWDIdg/XVmgsC9CzVzUyq4VsS/sk97lJggcddpWLNw/29egz8iLyzWHOAXCvl2fTIPkviYAOQXfVhZUQdxsyJUNFMTiALrZCmoQLMp2LmDbfbW8JQriDeR3fVz6P1sjT8C2yEDvzkCn7sh0aTBK+sx7BKH1nb4320+caQepQj4TCJtCeNXjdrVcNEnjvwlcRJwFT1pT+Y7HREbHnT71XYNh4EAAAGEQZrnSeEPJlMCK/8AKIjxcI58rm/ML255fOJW1zbznFna7lfgMQrka7OTPPsvVAV4EJXye/Uxiu9dlftmRypJqfDot3xwDe8lX/qAVf6pBkSlUsaLyBYtww/SUSa1bGl1JvrJCN7FXCCXbLd5R4PoYlPiDIm/DQH2puO0StIWmrR77Isc/J1pRvdu5+mQa/n0SEHUeM2KkoRzCznfD9zaaRO7BDtvC9SYIT0uYZxrwTjxQ7N7UERTrYG0P+vRLAhxkfohFIYl3HXyjPOvnlbUFP2oiiy6nkUFuaIyQcJawJv3GU8k4ObcKsC1cNDXjSpsyQRrxLFaCCjke4mikyt7vs0iN0bnrNWv9HXruG9zOFEOer1ggIFTsT1Eos5CXRkgja5HN4QUM6MhWpc5du/HgBIH8ANFcoo2kJpqcadw9r/0qk25X91MQSDJQiH8Hny2dQhqR+LFWEawiW753SJhn0ngZcv/mPj3mwcHv1SL9ErBqAjm4JGiDetPKYtFwANYY11OyQAAAVdBmwhJ4Q8mUwIr/wArOx5HV2505jRePGgMxptW4PGIHEszV1xGZS+flSkF+aq30AaqO7u6XK9jJsuWXTfYCRQTn1bZfFQ22DbO5DXAxK/TUmbQleCflFzeS6/czxkL4PJ8AwOs2U+oehekgCZC8gZyHHaQSaKbNJ46gTjNsLy84ACQ5uNt11TPuCPqPTuh+schdw9S+/lU/6m+EyaqGZ49wDFPiBFBYXglQQBjyP9k/rqq0xL7SiLjpe4riYg8SFUuUtOzPdWHyvxnI7Ug/0VLPGAAhgMISUnqe01d5QFf36yHpwMAHexjAZFIGQHAFautuMuEw6HzUZVzNdeHYxvEYOGkTo007bLwbuf/nxzrywGOxlRTYJLRdYI0mk0SdN3+LeTv1RIJwv21+e9rT5iFOTCgzeQoekEWXLYz0X8YLq5bVCtijP7/T7w1Ck71j0aqfrEn6wtIAAABNUGbKUnhDyZTAiv/ACcySi7VBgOid6qZNXvhh/JsllHkMLLq0yNbQTqv/Wk2EBoSKICZwFwAD0WRzhvvReCGirep1Fe4bxjm49/UR+OYrXRmHR18T0C83AUVeBk7KvDZmb/eHzuzEN4yfXucr/NWFJl+USVMY4r4UQ9CayrfEY9v6AQ6mzAdLy2UMfFxrRJ99g/Rfl8qx+m4jIZNjlrTaThzJ/3OpVmAliDfxVyg8+CVIlI31IykiwQrXcebgajG+av8XU1SfyAG5ibvwbtdSAxkGBcJWL387V+uTdY56w3KN2vBtoQpVKD2zb3yazIcATZ02upwIytNcM/rpaLCdMb1myWcikE25agzLhDhOS+4zwjYz2DnW6VY0gFBAPsphhsUMnauVVdUVHzCTSdvzEve/H8q4AAAAVdBm0pJ4Q8mUwIr/wAo+x5XKuiN1am7SkJKSMonFZDPU3f5XFcDQSs0FLVq2idfsKwuIkt1mxIq8NgMHpzofTnDHqs/WedvAmhBgL0N5azdQa5MNKG2rJ4IAvGQY/uFm3jKQAKzvhSS01gO1oIfizF817z9IShS4QK2WT0PeFPELqLSpED8eNOpVTR96vmwpk/WBKRVJdTQJzjiCQ5pgEwjtvk7KqoS0+lwXSbvIrXkYm8DignEts3DLNoLHrPjXlQmbIop76JZSyJEtB+91GrLwo6Km5GeebyA2E6qGL3xSkpppej/ruoFprSKrH60UMbrq/SK7eCo+1QFoySPQmqDFsMGiQFqvtld5BXDYdVI4yRaoyN7Y7wi83HRC6eVazuHU9OtIY3xJJApBWq1aJOsYwc38aTC3ee863Aa/4n9Lk4DAtyFYHNZjB5m2e2vk8G2Gny9YFlBAAABQEGba0nhDyZTAiv/ACoZSZQfHxhfQxEqOBQrP+L3DmgvHSJQtB1iVkcLTxm+vagLHBLG91OGnopwrr7gT/loDypIhoRxjcwAAOeg/jN4WBbXzCJtnWGGllUCSdtUZQzKOSp9iM4yX18C6jrY4Sq6R9PUV/lEGNveJR4gw4FMve7110XdEPL1O2VTdHvdqeANyaq0nLdEmtXnrzvdrFlBaUvmaR4EdlkqGkvkZKWJej8Vq+msbKa7JdbxjwZtRufiyGfD/NVqMgSrYRzw9z/a8Zwbr+9+19CxlWD5bCuAEfPmjY6kZJE2L/CQI6+tnCBTXOmWZtZMBoCLGOf7G2uAC3+kFlboh9as5WCkO6+iqXq29dyhKnsHInorRYsPlgxIXyU1Om/Kyhj1DJV0Am9WJK3Dln0zNUH0q6ZTOnZcFD36AAABYkGbjEnhDyZTAiv/ACcwdIOLRFfoGK2ZkKsvgMwG0m0qsY0vMLPSzefc+ebp/aztyF7MlsBz/fBeNtxFBcsKgR4pf65GvdfOMHah0ltZ918sMDmXUEZMeRHy/xpnWpTLeGz6uTs/7MATPmU5BgHbT/DkD8QeaZnFAzidyFCXDz2l/jaKhEdgqipbB2pH0+fQ039r05z9axxEWGmaLQjg6x9+po1o24yhkVO7m03YwWmPyCgy8cOwrvRyJkXJpRN4m8ZBS1zwY80HeN/VyMQQJSMwsTo7R1XMerSFuyx0nz+8qOuhiqykc2ohCCsXia/+kIKbJ5Vs+cbWtvkqBKIDSfU7FhAd3GjcY/xar0EVmi6wWFTugAogR3I7mTrQDdlTAqYgqO7Gn5NMXQVHu2i1zhFSdo9GjMbeGnbkJwsFbQ2XkoKRIDpuW7AewC9AEBt0Ox/Ah6dGXfXO1jl8pEApj2RFmgAAAPlBm61J4Q8mUwIr/wAlR+eW/VZ7bSrmwwMA62G05DZ7p/5FUugsSsQdonUq6abtbU5hjFr+I1lPgoiV5c3CkTQZS+K5zivdo+Ti2P4K90xXANp8dSMAu85uJIOCQn2TXbEnNDifLB+3V84ht5tj4lvTaZx317BcliV8D5v2zZQW8RO1mUbuJEBItst8E7hfE+ZXj7tfDxNZPTvtpFyUv0fH1cTg1pr2VLy0d0zQLiA58dg+GkRvR1/hs2LyifBgHcj6eTWz0vsypVn9iPXRH/unJ6i8cfFL69NO24tQ9QQB+nDFhoP2cRhkAvhHwn56n5PppBD/oxni2f8AAAE9QZvOSeEPJlMCK/8AJjAXVGf+Kj2XNJnFeKC/gr7dJDTC2ngpd4WeAHlg04GuJKnn9hAmiECxxo9qM1IYMRiB85t6gALnlm9sRqGmioyzAm18RJndc9Ah8RlpGzr+44a6ntRaPx0cIwNIWAA8buL2JP00dmfjNqEiAlCa8OdV8FQxjp1vDXsGcAGF3Qbd62KEpkimeI3wH2nuXpbDHm8/ZKOR49s5ifUCkxCoJpfp43aC0lTzh2NXpcfVw6h0QnK8G60R4ZAxOxaJB7c0nn8ixXSU2JVY24EtGMF53nxJnHfzUheewUfBOGYSxeo8oK7oUCqX4rztzDwoc2QywNqQUJUkFrqIN+sb5ecYvX24Zujn+ZzTW6UDAF3R6WdNyJyRAremgC8spSflTqygQNGfHyGkfIEEJJaFo/pBCBkAAAEWQZvvSeEPJlMCK/8AKI41fuekXG59Knbw4Y6YJritsh9VtQgc3QKvVmxrzzo7f4aXn8N74eyP4b2lV1Z2Q+rohxps7EHTkOY9jLdqxI3MXe7je4g2qepz71+hY+jYdX+9LO0kA0Zg3NfyAlIRX7k6c/YHAZNtNaGZgTBMqiPgmEjiJH9Luk7shbgr+srfwiYwBX9rdS3fQNNFwcT8orQC+F60LAY9+GbFo2Sw3Ld4Tw9jq9yJtrY8RtHAdzytyek/mv2+j2TbTvAQKbbCYtdC8E/KtR4V5ZTSScr5Wb63vmbw7UpddEXYvl55pARyyvMxWNSh3Li4GF8Jk5JBi5B5ASQwxCMYpX5hkAMc+d8tl2bT+IEvUTsAAAElQZoQSeEPJlMCK/8AJIAzFZs00JJ0yfm8CZiew4xWdArLklEvBVXo/+ukPLu3XP9HFOfsme3T6BJEKmPPgZw/Lxnraq6Sl2kLVW19YU1qmqgfv+80LkZaWU5gRAH4hqyo3bFYcbuY2SC3IW5Wm69gtYyAXOdbAYSEHA16fvCeRQjHEsxKVndJdrRAlrGHsKgUBQ3Up/ZXIy1vkdFOfKSjpuZnswkuqr8NZI5tJ/dnBSErBTNWPaNwWV7nNomC0EYVGo+geGBhLXzaLw0UAOCYGjiPc3803BDw1GLoLIXjrIFJxwRfBNIAXYZAglu30oYzhpAfRWSprkeULMWYJTlWvbUQ5CNewSZssuDWIRAc3w8AcFaywwn+YSGhtR8VI1OGjYkfBbcAAAD8QZoxSeEPJlMCK/8AJdokjCUETRw/nciVPtaZQSBP/VxAQSITASEzlJBl9Na1r0DJhLOz279+KQLtl/xHZ8vAKc528mTMTqtWs4sFbeVgHWyBpHcHEtgTzjIqEinp/MPuUXF5poo8YLSSMFn9Ozx2FbU5/Kh9A39oN9NHQflVxV1NA6yT/84HHyfMtfdSMS8KTvAEE2lDs14VQayNs5ctjXboQT7xMBf5OLj6thhPvgaDrFB2o/PV9ouK147lruWTP2mkoA9oDIMYW1pcBx4yyV/t9GOPZ3aXneMUb2fFmUCX43BjXfUDMaa4GO2/Ankj3UEQwDxA7ZlNUQK2AAAA4UGaUknhDyZTAiv/ACJHv33I08bkhybYiJ/JiiheW5zMPBu4n5CxGr3frhE7TkLh0vPktM8m/AhaDiJisdk5QXNe/4WmxEDSAyaVi4eUVu0iHT2ly/KNTGqiORqA2oKpTjh84nYbrpXwnGv9SOf/34Z06xN6Yo3t35UZrP8nlcs/63GtnEmnUwVZHBYfPM6bs5M5AeBfAQ/9mIqu7vnEst+5O2wpPjzdItjwGCZ2ApHVjGnYYFomlA9nm6AXnxNIWHIsDgxCk3zx+6QbXipu/CWLG1Wf0WIbt4C0JPVl3TEb0QAAAMlBmnNJ4Q8mUwIr/wAVV64OfTKmlktYOqZHH1W1DhPy/X/6sD4T6hRdzfOgNtTOX2IckRJHshfBQVkJIzns079io6kpJFCcS3VD4zrWCn/dNaGV0kWTpFBRuusfn8F0C0R/EhsQeyTsdZftEkLGb5tq+nrir3vfmeb7rjmWJRXkIrTEKu8pIuAd+4FBGp8ARgGe80Jqpp//s1433HqBFqXsIFJTmU8j/toF9HyueI1Ea4uvsQ6NANGcYCbOAKCmbNiwABMCFaiUTMAAAAPSbW9vdgAAAGxtdmhkAAAAAHwlsIB8JbCAAAAD6AAAAyAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAv10cmFrAAAAXHRraGQAAAAPfCWwgHwlsIAAAAABAAAAAAAAAyAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAY4AAAGGAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAMgAAAAAgABAAAAAAJ1bWRpYQAAACBtZGhkAAAAAHwlsIB8JbCAAAAAGQAAABRVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAACIG1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAeBzdGJsAAAAtHN0c2QAAAAAAAAAAQAAAKRhdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAY4BhgBIAAAASAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGP//AAAAMmF2Y0MBZAAV/+EAGWdkABWs2UGQz6mhAAADAAEAAAMAMg8WLZYBAAZo6+PLIsAAAAAcdXVpZGtoQPJfJE/FujmlG88DI/MAAAAAAAAAGHN0dHMAAAAAAAAAAQAAABQAAAABAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAYY3R0cwAAAAAAAAABAAAAFAAAAAIAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAZHN0c3oAAAAAAAAAAAAAABQAAA05AAACqQAAAl8AAAITAAACiwAAAh8AAAIvAAABiAAAAVsAAAE5AAABWwAAAUQAAAFmAAAA/QAAAUEAAAEaAAABKQAAAQAAAADlAAAAzQAAAGBzdGNvAAAAAAAAABQAAAAsAAANZQAAEA4AABJtAAAUgAAAFwsAABkqAAAbWQAAHOEAAB48AAAfdQAAINAAACIUAAAjegAAJHcAACW4AAAm0gAAJ/sAACj7AAAp4AAAAGF1ZHRhAAAAWW1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAALGlsc3QAAAAkqXRvbwAAABxkYXRhAAAAAQAAAABMYXZmNTIuMTExLjA=\">\n\n\n\n## HTML\n\nPython objects can declare HTML representations that will be displayed in the Notebook. If you have some HTML you want to display, simply use the `HTML` class.\n\n\n```\nfrom IPython.display import HTML\n```\n\n\n```\ns = \"\"\"<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\"\"\"\n```\n\n\n```\nh = HTML(s); h\n```\n\n\n\n\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n\n\n\nPandas makes use of this capability to allow `DataFrames` to be represented as HTML tables.\n\n\n```\nimport pandas\n```\n\nHere is a small amount of stock data for APPL:\n\n\n```\n%%file data.csv\nDate,Open,High,Low,Close,Volume,Adj Close\n2012-06-01,569.16,590.00,548.50,584.00,14077000,581.50\n2012-05-01,584.90,596.76,522.18,577.73,18827900,575.26\n2012-04-02,601.83,644.00,555.00,583.98,28759100,581.48\n2012-03-01,548.17,621.45,516.22,599.55,26486000,596.99\n2012-02-01,458.41,547.61,453.98,542.44,22001000,540.12\n2012-01-03,409.40,458.24,409.00,456.48,12949100,454.53\n```\n\n    Writing data.csv\n\n\nRead this as into a `DataFrame`:\n\n\n```\ndf = pandas.read_csv('data.csv')\n```\n\nAnd view the HTML representation:\n\n\n```\ndf\n```\n\n\n\n\n<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Date</th>\n      <th>Open</th>\n      <th>High</th>\n      <th>Low</th>\n      <th>Close</th>\n      <th>Volume</th>\n      <th>Adj Close</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td> 2012-06-01</td>\n      <td> 569.16</td>\n      <td> 590.00</td>\n      <td> 548.50</td>\n      <td> 584.00</td>\n      <td> 14077000</td>\n      <td> 581.50</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td> 2012-05-01</td>\n      <td> 584.90</td>\n      <td> 596.76</td>\n      <td> 522.18</td>\n      <td> 577.73</td>\n      <td> 18827900</td>\n      <td> 575.26</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td> 2012-04-02</td>\n      <td> 601.83</td>\n      <td> 644.00</td>\n      <td> 555.00</td>\n      <td> 583.98</td>\n      <td> 28759100</td>\n      <td> 581.48</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td> 2012-03-01</td>\n      <td> 548.17</td>\n      <td> 621.45</td>\n      <td> 516.22</td>\n      <td> 599.55</td>\n      <td> 26486000</td>\n      <td> 596.99</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td> 2012-02-01</td>\n      <td> 458.41</td>\n      <td> 547.61</td>\n      <td> 453.98</td>\n      <td> 542.44</td>\n      <td> 22001000</td>\n      <td> 540.12</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td> 2012-01-03</td>\n      <td> 409.40</td>\n      <td> 458.24</td>\n      <td> 409.00</td>\n      <td> 456.48</td>\n      <td> 12949100</td>\n      <td> 454.53</td>\n    </tr>\n  </tbody>\n</table>\n<p>6 rows \u00d7 7 columns</p>\n</div>\n\n\n\n## External sites\n\nYou can even embed an entire page from another site in an iframe; for example this is today's Wikipedia\npage for mobile users:\n\n\n```\nfrom IPython.display import IFrame\nIFrame('http://en.mobile.wikipedia.org/?useformat=mobile', width='100%', height=350)\n```\n\n\n\n\n\n\n\n\n\n\n## LaTeX\n\nAnd we also support the display of mathematical expressions typeset in LaTeX, which is rendered\nin the browser thanks to the [MathJax library](http://mathjax.org).\n\n\n```\nfrom IPython.display import Math\nMath(r'F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx')\n```\n\n\n\n\n$$F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx$$\n\n\n\nWith the `Latex` class, you have to include the delimiters yourself.  This allows you to use other LaTeX modes such as `eqnarray`:\n\n\n```\nfrom IPython.display import Latex\nLatex(r\"\"\"\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\"\"\")\n```\n\n\n\n\n\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\n\n\n\nOr you can enter latex directly with the `%%latex` cell magic:\n\n\n```latex\n%%latex\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n```\n\n\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n\n", "meta": {"hexsha": "e05fbfa3363e29c515f28b3abb4fa7dc76c658b1", "size": 235340, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "101notebook/ipython-rel-2.1.0-examples/Notebook/Display System.ipynb", "max_stars_repo_name": "OpenBookProjects/ipynb", "max_stars_repo_head_hexsha": "72a28109e8e30aea0b9c6713e78821e4affa2e33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-06-08T12:50:14.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-20T10:05:01.000Z", "max_issues_repo_path": "101notebook/ipython-rel-2.1.0-examples/Notebook/Display System.ipynb", "max_issues_repo_name": "OpenBookProjects/ipynb", "max_issues_repo_head_hexsha": "72a28109e8e30aea0b9c6713e78821e4affa2e33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "101notebook/ipython-rel-2.1.0-examples/Notebook/Display System.ipynb", "max_forks_repo_name": "OpenBookProjects/ipynb", "max_forks_repo_head_hexsha": "72a28109e8e30aea0b9c6713e78821e4affa2e33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2016-01-26T14:12:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-20T14:24:09.000Z", "avg_line_length": 205.0, "max_line_length": 82682, "alphanum_fraction": 0.8781720065, "converted": true, "num_tokens": 61572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18713267309572332, "lm_q2_score": 0.07921033117343147, "lm_q1q2_score": 0.014822841009281733}}
{"text": "<a href=\"https://colab.research.google.com/github/yogeshmj/AD-DL/blob/master/Alzheimer_Analysis_Dementia.ipynb\" target=\"_parent\"></a>\n\n# Alzheimer\u2019s Analysis\n\n## Introduction\n### About Dementia\nDementia is not a specific disease. It\u2019s an overall term that describes a group of symptoms associated with a decline in memory or other thinking skills severe enough to reduce a person\u2019s ability to perform everyday activities. Alzheimer\u2019s disease accounts for 60 to 80 percent of cases. Vascular dementia, which occurs after a stroke, is the second most common dementia type. But there are many other conditions that can cause symptoms of dementia, including some that are reversible, such as thyroid problems and vitamin deficiencies.\n\nDementia is a general term for loss of memory and other mental abilities severe enough to interfere with daily life. It is caused by physical changes in the brain. Alzheimer's is the most common type of dementia, but there are many kinds.\n\n### Alzheimer\n  \n\n- Alzheimer's is a type of dementia that causes problems with memory, thinking and behavior. Symptoms usually develop slowly and get worse over time, becoming severe enough to interfere with daily tasks. <br><br>\n\n- Alzheimer's is not a normal part of aging. The greatest known risk factor is increasing age, and the majority of people with Alzheimer's are 65 and older. But Alzheimer's is not just a disease of old age. Approximately 200,000 Americans under the age of 65 have younger-onset Alzheimer\u2019s disease (also known as early-onset Alzheimer\u2019s). <br><br>\n\n-  Alzheimer's is the sixth leading cause of death in the United States. Those with Alzheimer's live an average of eight years after their symptoms become noticeable to others, but survival can range from four to 20 years, depending on age and other health conditions. <br><br>\n\n- Alzheimer's has no current cure, but treatments for symptoms are available and research continues. Although current Alzheimer's treatments cannot stop Alzheimer's from progressing, they can temporarily slow the worsening of dementia symptoms and improve quality of life for those with Alzheimer's and their caregivers. Today, there is a worldwide effort under way to find better ways to treat the disease, delay its onset, and prevent it from developing.\n\n### Understanding the data\n> **Summary**: This set consists of a longitudinal collection of 150 subjects aged 60 to 96. Each subject was scanned on two or more visits, separated by at least one year for a total of 373 imaging sessions. For each subject, 3 or 4 individual T1-weighted MRI scans obtained in single scan sessions are included. The subjects are all right-handed and include both men and women. 72 of the subjects were characterized as nondemented throughout the study. 64 of the included subjects were characterized as demented at the time of their initial visits and remained so for subsequent scans, including 51 individuals with mild to moderate Alzheimer\u2019s disease. Another 14 subjects were characterized as nondemented at the time of their initial visit and were subsequently characterized as demented at a later visit.\n\n**Dataset Description** \n- We will be using the longitudinal MRI data.\n- The dataset consists of a longitudinal MRI data of 150 subjects aged 60 to 96.\n- Each subject was scanned at least once.\n- Everyone is right-handed.\n- 72 of the subjects were grouped as 'Nondemented' throughout the study.\n- 64 of the subjects were grouped as 'Demented' at the time of their initial visits and remained so throughout the study.\n- 14 subjects were grouped as 'Nondemented' at the time of their initial visit and were subsequently characterized as 'Demented' at a later visit. These fall under the 'Converted' category.\n\n| COL  | Description                         |\n|------|-------------------------------------|\n| EDUC | Years of Education                  |\n| SES  | Socioeconomic Status                |\n| MMSE | Mini Mental State Examination       |\n| CDR  | Clinical Dementia Rating            |\n| eTIV | Estimated Total Intracranial Volume |\n| nWBV | Normalize Whole Brain Volume        |\n| ASF  | Atlas Scaling Factor                |\n\n**Clinical Info:**\n- MMSE - Mini-Mental State Examination score (range is from 0 = worst to 30 = best)\n- CDR - Clinical Dementia Rating (0 = no dementia, 0.5 = very mild AD, 1 = mild AD, 2 = moderate AD)\n- Derived anatomic volumes\n- eTIV - Estimated total intracranial volume, mm3\n- nWBV - Normalized whole-brain volume, expressed as a percent of all voxels in the atlas-masked image that are labeled as gray or white matter by the automated tissue segmentation process\n- ASF - Atlas scaling factor (unitless). Computed scaling factor that transforms native-space brain and skull to the atlas target (i.e., the determinant of the transform matrix)\n\n\n#### Mini\u2013Mental State Examination (MMSE)\n> The Mini\u2013Mental State Examination (MMSE) or Folstein test is a 30-point questionnaire that is used extensively in clinical and research settings to measure cognitive impairment. It is commonly used in medicine and allied health to screen for dementia. It is also used to estimate the severity and progression of cognitive impairment and to follow the course of cognitive changes in an individual over time; thus making it an effective way to document an individual's response to treatment. The MMSE's purpose has been not, on its own, to provide a diagnosis for any particular nosological entity.\n> - **Cognitive Impairment:** Cognitive impairment is when a person has trouble remembering, learning new things, concentrating, or making decisions that affect their everyday life. Cognitive impairment ranges from mild to severe.\n\n> Any score greater than or equal to 24 points (out of 30) indicates a normal cognition. Below this, scores can indicate severe (\u22649 points), moderate (10\u201318 points) or mild (19\u201323 points) cognitive impairment. The raw score may also need to be corrected for educational attainment and age. That is, a maximal score of 30 points can never rule out dementia.\n\n\n|   **Method**  |**Score**|  **Interpretation**                   |                   \n|---------------|---------|--------------------------------------|\n| Single Cutoff |   <24   |        Abnormal                      |\n|     Range     |   <21   |  Increased Odds of Dementia          |\n|               |   <25   |  Decreased Odds of Dementia          |\n|   Education   |    21   |  Abnormal for 8th Grade Education    |\n|               |   <23   |  Abnormal for High School Education  |\n|               |   <24   |  Abnormal for College Education      |\n|   Severity    |  24-30  |  No Cognitive Impairment             |\n|               |  18-23  |  Mild Cognitive Impairment           |\n|               |   0-17  |  Severe Cognitive Impairment         |\n\n#### Clinical Dementia Rating (CDR)\n> The CDR is a 5-point scale used to characterize six domains of cognitive and functional performance applicable to Alzheimer disease and related dementias: Memory, Orientation, Judgment & Problem Solving, Community Affairs, Home & Hobbies, and Personal Care. The necessary information to make each rating is obtained through a semi-structured interview of the patient and a reliable informant or collateral source (e.g., family member).<br><br>\n> The CDR table provides descriptive anchors that guide the clinician in making appropriate ratings based on interview data and clinical judgment. In addition to ratings for each domain, an overall CDR score may be calculated through the use of an algorithm. This score is useful for characterizing and tracking a patient's level of impairment/dementia:\n\n| Score  | Description               |\n|--------|---------------------------|\n|    0   |        Normal             |\n|    0.5 | Very Mild Dementia        | \n|    1   | Mild Dementia             |\n|    2   | Moderate Dementia         |\n|    3   | Severe Dementia           |\n\n##### Estimated Total Intracranial Volume(eTIV)\n> Total intracranial volume (TIV/ICV) is an important covariate for volumetric analyses of the brain and brain regions, especially in the study of neurodegenerative diseases, where it can provide a proxy of maximum pre-morbid brain volume.<br><br>\n> Unlike brain atrophy in the patients with AD, TIV did not vary over time. Mean TIV did not differ significantly between any of the subject groups. There was no association between TIV and age or age at symptom onset. The only significant predictor of TIV was sex. Men showed an approximately \u223c12% larger eTIV than women. \n\n\n```python\nimport pandas as pd\nimport seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport xgboost as xgb\nfrom sklearn.datasets import make_blobs\nimport pandas as pd\n```\n\n\n```python\nimport plotly.graph_objects as go\nimport plotly.express as px\nfrom jupyter_dash import JupyterDash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output \n```\n\n\n```python\n## Read the CSV File Using Pandas read_csv function\n#\nfrom google.colab import files\ndata_to_load = files.upload()\ndf = pd.read_csv('oasis_longitudinal_original.csv')\n# print the concise summery of the dataset\n\n```\n\n\n\n<input type=\"file\" id=\"files-27d41aec-4c0b-4e97-ab41-169b23e2c344\" name=\"files[]\" multiple disabled\n   style=\"border:none\" />\n<output id=\"result-27d41aec-4c0b-4e97-ab41-169b23e2c344\">\n Upload widget is only available when the cell has been executed in the\n current browser session. Please rerun this cell to enable.\n </output>\n  \n\n\n\n```python\ndf.info()\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 373 entries, 0 to 372\n    Data columns (total 20 columns):\n     #   Column       Non-Null Count  Dtype  \n    ---  ------       --------------  -----  \n     0   Subject ID   373 non-null    object \n     1   MRI ID       373 non-null    object \n     2   Group        373 non-null    object \n     3   Visit        373 non-null    int64  \n     4   MR Delay     373 non-null    int64  \n     5   M/F          373 non-null    object \n     6   Hand         373 non-null    object \n     7   Glucose      373 non-null    int64  \n     8   Insulin      373 non-null    int64  \n     9   Age          373 non-null    int64  \n     10  EDUC         373 non-null    int64  \n     11  SES          354 non-null    float64\n     12  MMSE         371 non-null    float64\n     13  CDR          373 non-null    float64\n     14  eTIV         373 non-null    int64  \n     15  nWBV         373 non-null    float64\n     16  ASF          373 non-null    float64\n     17  Unnamed: 17  0 non-null      float64\n     18  Unnamed: 18  0 non-null      float64\n     19  Unnamed: 19  3 non-null      object \n    dtypes: float64(7), int64(7), object(6)\n    memory usage: 58.4+ KB\n\n\n\n```python\nprint(\"Tota Rows and Columns (Rows,Columns) : \",df.shape)\n#print first five rows of the dataset\ndf.head(5)\n```\n\n    Tota Rows and Columns (Rows,Columns) :  (373, 20)\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Subject ID</th>\n      <th>MRI ID</th>\n      <th>Group</th>\n      <th>Visit</th>\n      <th>MR Delay</th>\n      <th>M/F</th>\n      <th>Hand</th>\n      <th>Glucose</th>\n      <th>Insulin</th>\n      <th>Age</th>\n      <th>EDUC</th>\n      <th>SES</th>\n      <th>MMSE</th>\n      <th>CDR</th>\n      <th>eTIV</th>\n      <th>nWBV</th>\n      <th>ASF</th>\n      <th>Unnamed: 17</th>\n      <th>Unnamed: 18</th>\n      <th>Unnamed: 19</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>OAS2_0001</td>\n      <td>OAS2_0001_MR1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>M</td>\n      <td>R</td>\n      <td>89</td>\n      <td>94</td>\n      <td>87</td>\n      <td>14</td>\n      <td>2.0</td>\n      <td>27.0</td>\n      <td>0.0</td>\n      <td>1987</td>\n      <td>0.696</td>\n      <td>0.883</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>OAS2_0001</td>\n      <td>OAS2_0001_MR2</td>\n      <td>0</td>\n      <td>2</td>\n      <td>457</td>\n      <td>M</td>\n      <td>R</td>\n      <td>137</td>\n      <td>168</td>\n      <td>88</td>\n      <td>14</td>\n      <td>2.0</td>\n      <td>30.0</td>\n      <td>0.0</td>\n      <td>2004</td>\n      <td>0.681</td>\n      <td>0.876</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>OAS2_0002</td>\n      <td>OAS2_0002_MR1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>M</td>\n      <td>R</td>\n      <td>116</td>\n      <td>0</td>\n      <td>75</td>\n      <td>12</td>\n      <td>NaN</td>\n      <td>23.0</td>\n      <td>0.5</td>\n      <td>1678</td>\n      <td>0.736</td>\n      <td>1.046</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>OAS2_0002</td>\n      <td>OAS2_0002_MR2</td>\n      <td>1</td>\n      <td>2</td>\n      <td>560</td>\n      <td>M</td>\n      <td>R</td>\n      <td>78</td>\n      <td>88</td>\n      <td>76</td>\n      <td>12</td>\n      <td>NaN</td>\n      <td>28.0</td>\n      <td>0.5</td>\n      <td>1738</td>\n      <td>0.713</td>\n      <td>1.010</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>OAS2_0002</td>\n      <td>OAS2_0002_MR3</td>\n      <td>1</td>\n      <td>3</td>\n      <td>1895</td>\n      <td>M</td>\n      <td>R</td>\n      <td>115</td>\n      <td>0</td>\n      <td>80</td>\n      <td>12</td>\n      <td>NaN</td>\n      <td>22.0</td>\n      <td>0.5</td>\n      <td>1698</td>\n      <td>0.701</td>\n      <td>1.034</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n#print concise summery of the dataset\ndf.describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Visit</th>\n      <th>MR Delay</th>\n      <th>Glucose</th>\n      <th>Insulin</th>\n      <th>Age</th>\n      <th>EDUC</th>\n      <th>SES</th>\n      <th>MMSE</th>\n      <th>CDR</th>\n      <th>eTIV</th>\n      <th>nWBV</th>\n      <th>ASF</th>\n      <th>Unnamed: 17</th>\n      <th>Unnamed: 18</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>373.000000</td>\n      <td>373.000000</td>\n      <td>373.000000</td>\n      <td>373.000000</td>\n      <td>373.000000</td>\n      <td>373.000000</td>\n      <td>354.000000</td>\n      <td>371.000000</td>\n      <td>373.000000</td>\n      <td>373.000000</td>\n      <td>373.000000</td>\n      <td>373.000000</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>1.882038</td>\n      <td>595.104558</td>\n      <td>120.667560</td>\n      <td>81.286863</td>\n      <td>77.013405</td>\n      <td>14.597855</td>\n      <td>2.460452</td>\n      <td>27.342318</td>\n      <td>0.290885</td>\n      <td>1488.128686</td>\n      <td>0.729568</td>\n      <td>1.195461</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>0.922843</td>\n      <td>635.485118</td>\n      <td>32.793537</td>\n      <td>119.914377</td>\n      <td>7.640957</td>\n      <td>2.876339</td>\n      <td>1.134005</td>\n      <td>3.683244</td>\n      <td>0.374557</td>\n      <td>176.139286</td>\n      <td>0.037135</td>\n      <td>0.138092</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>1.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>60.000000</td>\n      <td>6.000000</td>\n      <td>1.000000</td>\n      <td>4.000000</td>\n      <td>0.000000</td>\n      <td>1106.000000</td>\n      <td>0.644000</td>\n      <td>0.876000</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>1.000000</td>\n      <td>0.000000</td>\n      <td>99.000000</td>\n      <td>0.000000</td>\n      <td>71.000000</td>\n      <td>12.000000</td>\n      <td>2.000000</td>\n      <td>27.000000</td>\n      <td>0.000000</td>\n      <td>1357.000000</td>\n      <td>0.700000</td>\n      <td>1.099000</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>2.000000</td>\n      <td>552.000000</td>\n      <td>116.000000</td>\n      <td>43.000000</td>\n      <td>77.000000</td>\n      <td>15.000000</td>\n      <td>2.000000</td>\n      <td>29.000000</td>\n      <td>0.000000</td>\n      <td>1470.000000</td>\n      <td>0.729000</td>\n      <td>1.194000</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>2.000000</td>\n      <td>873.000000</td>\n      <td>142.000000</td>\n      <td>120.000000</td>\n      <td>82.000000</td>\n      <td>16.000000</td>\n      <td>3.000000</td>\n      <td>30.000000</td>\n      <td>0.500000</td>\n      <td>1597.000000</td>\n      <td>0.756000</td>\n      <td>1.293000</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>5.000000</td>\n      <td>2639.000000</td>\n      <td>197.000000</td>\n      <td>846.000000</td>\n      <td>98.000000</td>\n      <td>23.000000</td>\n      <td>5.000000</td>\n      <td>30.000000</td>\n      <td>2.000000</td>\n      <td>2004.000000</td>\n      <td>0.837000</td>\n      <td>1.587000</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n#since the dataset contain null values also \n#count total rows in each column which contain null values\ndf.isna().sum()\n```\n\n\n\n\n    Subject ID       0\n    MRI ID           0\n    Group            0\n    Visit            0\n    MR Delay         0\n    M/F              0\n    Hand             0\n    Glucose          0\n    Insulin          0\n    Age              0\n    EDUC             0\n    SES             19\n    MMSE             2\n    CDR              0\n    eTIV             0\n    nWBV             0\n    ASF              0\n    Unnamed: 17    373\n    Unnamed: 18    373\n    Unnamed: 19    370\n    dtype: int64\n\n\n\n\n```python\n#'duplicated()' function in pandas return the duplicate row as True and othter as False\n#for counting the duplicate elements we sum all the rows\nsum(df.duplicated())\n```\n\n\n\n\n    0\n\n\n\n\n```python\n#fill null value with their column mean and median\ndf[\"SES\"].fillna(df[\"SES\"].median(), inplace=True)\ndf[\"MMSE\"].fillna(df[\"MMSE\"].mean(), inplace=True)\n```\n\n\n```python\n#see how many people have Alzheimer\n#same person visits two or more time so only take the single visit data\nsns.set_style(\"whitegrid\")\nex_df = df.loc[df['Visit'] == 1]\nsns.countplot(x='Group', data=ex_df)\n```\n\n\n```python\n#We have three groups so convert Converted Group Into Demented\n\nex_df['Group'] = ex_df['Group'].replace(['Converted'], ['Demented'])\ndf['Group'] = df['Group'].replace(['Converted'], ['Demented'])\nsns.countplot(x='Group', data=ex_df)\n```\n\n\n```python\n# bar drawing function\ndef bar_chart(feature):\n    Demented = ex_df[ex_df['Group']=='Demented'][feature].value_counts()\n    Nondemented = ex_df[ex_df['Group']=='Nondemented'][feature].value_counts()\n    df_bar = pd.DataFrame([Demented,Nondemented])\n    df_bar.index = ['Demented','Nondemented']\n    df_bar.plot(kind='bar',stacked=True, figsize=(8,5))\n    print(df_bar)\n                \n                \n# Gender  and  Group ( Female=0, Male=1)\nbar_chart('M/F')\nplt.xlabel('Group',fontsize=13)\nplt.xticks(rotation=0,fontsize=12)\nplt.ylabel('Number of patients',fontsize=13)\nplt.legend()\nplt.title('Gender and Demented rate',fontsize=14)\n```\n\n\n```python\nplt.figure(figsize=(10,5))\nsns.violinplot(x='M/F', y='Glucose', data=df)\nplt.title('Violin plots of Glucose by Gender',fontsize=14)\nplt.xlabel('Gender',fontsize=13)\nplt.ylabel('Glucose',fontsize=13)\nplt.show()\n```\n\n\n```python\nax = sns.countplot(x='Glucose', data=ex_df)\nax.figure.set_size_inches(18.5, 5)\n```\n\n\n```python\n#MMSE Vs Non-demented and demented\nfacet= sns.FacetGrid(df,hue=\"Group\", aspect=3)\nfacet.map(sns.kdeplot,'Glucose',shade= True)\nfacet.set(xlim=(0, df['Glucose'].max()))\nfacet.add_legend()\nplt.xlim(15.30)\n```\n\n>**The chart shows Nondemented group got much more higher Glucose values than Demented group.**\n\n\n```python\n#find the outliers in each of the column\ndef outliers_iqr(ys):\n    quartile_1, quartile_3 = np.percentile(ys, [25, 75])\n    iqr = quartile_3 - quartile_1\n    lower_bound = quartile_1 - (iqr * 1.5)\n    upper_bound = quartile_3 + (iqr * 1.5)\n    return np.where((ys > upper_bound) | (ys < lower_bound))\n\nlist_atributes = ['MR Delay','EDUC', \"SES\", \"MMSE\", 'eTIV', \"nWBV\", \"ASF\",\"Glucose\",\"Insulin\"]\nprint(\"Outliers: \\n\")\nfor item in list_atributes:\n    print(item,': ',outliers_iqr(df[item]))\n```\n\n    Outliers: \n    \n    MR Delay :  (array([ 32,  71,  75, 153, 159, 160, 265, 369]),)\n    EDUC :  (array([107, 108, 109]),)\n    SES :  (array([136, 137, 138, 161, 162, 179, 180]),)\n    MMSE :  (array([  4,  25,  26,  43,  44,  51,  52,  60,  88,  89,  90,  93,  94,\n            97,  98,  99, 100, 101, 105, 106, 138, 162, 172, 173, 184, 185,\n           186, 222, 225, 226, 231, 232, 234, 251, 299, 300, 316, 317, 328,\n           332, 360, 366]),)\n    eTIV :  (array([0, 1]),)\n    nWBV :  (array([], dtype=int64),)\n    ASF :  (array([282]),)\n    Glucose :  (array([ 58, 218, 225]),)\n    Insulin :  (array([  5,   7,  39,  92, 119, 133, 165, 178, 198, 206, 209, 236, 246,\n           251, 268, 285, 288, 291, 355]),)\n\n\n\n```python\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 8,5\ncols = ['Insulin','Glucose','Age','MMSE']\nx=df.fillna('')\nsns_plot = sns.pairplot(x[cols])\n```\n\n\n```python\n#boxplots which shows the IQR(Interquartile Range )\nfig, axes = plt.subplots(2,3,figsize = (16,6))\nfig.suptitle(\"Box Plot\",fontsize=14)\nsns.set_style(\"whitegrid\")\nsns.boxplot(data=df['Glucose'], orient=\"v\",width=0.4, palette=\"colorblind\",ax = axes[0][0]);\nsns.boxplot(data=df['Insulin'], orient=\"v\",width=0.4, palette=\"colorblind\",ax = axes[0][1]);\nsns.boxplot(data=df['MMSE'], orient=\"v\",width=0.4, palette=\"colorblind\",ax = axes[0][2]);\nsns.boxplot(data=df['CDR'], orient=\"v\",width=0.4, palette=\"colorblind\",ax = axes[1][0]);\nsns.boxplot(data=df['eTIV'], orient=\"v\",width=0.4, palette=\"colorblind\",ax = axes[1][1]);\nsns.boxplot(data=df['ASF'], orient=\"v\",width=0.4, palette=\"colorblind\",ax = axes[1][2]);\n#xlabel(\"Time\");\n```\n\n\n```python\ndef plot_correlation_map( df ):\n    corr = df.corr()\n    _ , ax = plt.subplots( figsize =( 12 , 10 ) )\n    cmap = sns.diverging_palette( 240 , 10 , as_cmap = True )\n    _ = sns.heatmap(corr,cmap = cmap,square=True, cbar_kws={ 'shrink' : .9 }, ax=ax, annot = True, annot_kws = { 'fontsize' : 12 })\n```\n\n\n```python\nplot_correlation_map(df)\n```\n\n\n\n# XG Boost Classifier\n\n\n```python\nimport pandas as pd\nfrom xgboost import XGBClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\n```\n\n\n```python\nfrom google.colab import files\nupload=files.upload()\n\ndiabetes = pd.read_csv('oasis_longitudinal_original.csv')\ncols = diabetes.columns\nX = diabetes[[\"Age\", \"EDUC\", \"SES\", \"MMSE\", \"eTIV\", \"nWBV\", \"ASF\"]]\ny = []\nfor i in diabetes['Group']:\n    if i==\"Nondemented\":\n        y.append(0)\n    else:\n        y.append(1)\nprint(y)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)\nmodel = XGBClassifier()\nmodel.fit(X_train, y_train)\ny_pred = model.predict(X_test)\npredictions = [round(value) for value in y_pred]\naccuracy = accuracy_score(y_test, predictions)\nprint(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n```\n\n\n\n<input type=\"file\" id=\"files-a391be07-13a2-4c07-a336-aaef42057042\" name=\"files[]\" multiple disabled\n   style=\"border:none\" />\n<output id=\"result-a391be07-13a2-4c07-a336-aaef42057042\">\n Upload widget is only available when the cell has been executed in the\n current browser session. Please rerun this cell to enable.\n </output>\n  \n\n\n    Saving oasis_longitudinal_original.csv to oasis_longitudinal_original (3).csv\n    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\n    Accuracy: 100.00%\n\n\n\n```python\nfrom google.colab import files\nupload=files.upload()\n\n```\n\n\n\n<input type=\"file\" id=\"files-a209a9cf-0ab8-4200-b9d1-b3d78ff38e48\" name=\"files[]\" multiple disabled\n   style=\"border:none\" />\n<output id=\"result-a209a9cf-0ab8-4200-b9d1-b3d78ff38e48\">\n Upload widget is only available when the cell has been executed in the\n current browser session. Please rerun this cell to enable.\n </output>\n  \n\n\n    Saving oasis_longitudinal_original_1.xlsx to oasis_longitudinal_original_1 (1).xlsx\n\n\n\n```python\ndf.head(5)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Subject ID</th>\n      <th>MRI ID</th>\n      <th>Group</th>\n      <th>Visit</th>\n      <th>MR Delay</th>\n      <th>M/F</th>\n      <th>Hand</th>\n      <th>Glucose</th>\n      <th>Insulin</th>\n      <th>Age</th>\n      <th>EDUC</th>\n      <th>SES</th>\n      <th>MMSE</th>\n      <th>CDR</th>\n      <th>eTIV</th>\n      <th>nWBV</th>\n      <th>ASF</th>\n      <th>Unnamed: 17</th>\n      <th>Unnamed: 18</th>\n      <th>Unnamed: 19</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>24</td>\n      <td>46</td>\n      <td>27</td>\n      <td>5</td>\n      <td>1</td>\n      <td>14</td>\n      <td>0</td>\n      <td>284</td>\n      <td>35</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>15</td>\n      <td>1</td>\n      <td>0</td>\n      <td>72</td>\n      <td>77</td>\n      <td>28</td>\n      <td>5</td>\n      <td>1</td>\n      <td>18</td>\n      <td>0</td>\n      <td>285</td>\n      <td>20</td>\n      <td>0</td>\n      <td>252</td>\n      <td>252</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1</td>\n      <td>2</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>51</td>\n      <td>0</td>\n      <td>15</td>\n      <td>3</td>\n      <td>1</td>\n      <td>10</td>\n      <td>1</td>\n      <td>231</td>\n      <td>73</td>\n      <td>52</td>\n      <td>251</td>\n      <td>251</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1</td>\n      <td>3</td>\n      <td>1</td>\n      <td>1</td>\n      <td>32</td>\n      <td>1</td>\n      <td>0</td>\n      <td>13</td>\n      <td>42</td>\n      <td>16</td>\n      <td>3</td>\n      <td>1</td>\n      <td>16</td>\n      <td>1</td>\n      <td>254</td>\n      <td>51</td>\n      <td>32</td>\n      <td>250</td>\n      <td>250</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1</td>\n      <td>4</td>\n      <td>1</td>\n      <td>2</td>\n      <td>185</td>\n      <td>1</td>\n      <td>0</td>\n      <td>50</td>\n      <td>0</td>\n      <td>20</td>\n      <td>3</td>\n      <td>1</td>\n      <td>9</td>\n      <td>1</td>\n      <td>238</td>\n      <td>40</td>\n      <td>46</td>\n      <td>249</td>\n      <td>249</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nfrom sklearn.model_selection import train_test_split\n\nfeature_col_names = [\"M/F\",\"Insulin\",\"Glucose\",\"Age\", \"EDUC\", \"SES\", \"MMSE\", \"eTIV\", \"nWBV\", \"ASF\"]\npredicted_class_names = ['Group']\n\nX = df[feature_col_names].values\ny = df[predicted_class_names].values\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=42)\n```\n\n\n```python\nfrom sklearn.preprocessing import label_binarize\n```\n\n\n```python\ny = label_binarize(y, classes=[0, 1, 2, 3])\n```\n\n\n```python\nX_test\n```\n\n\n\n\n    array([[  1,   0,  69, ..., 181,  17, 101],\n           [  0,   0,  41, ..., 104,  53, 167],\n           [  1,  68,  78, ..., 135, 128, 137],\n           ...,\n           [  0,  58, 102, ..., 109,  76, 162],\n           [  0, 101,  62, ...,  67,  89, 202],\n           [  0,   0,  70, ..., 163,  63, 116]])\n\n\n\n\n```python\nfrom sklearn import metrics\ndef plot_confusion_metrix(y_test,model_test):\n    cm = metrics.confusion_matrix(y_test, model_test)\n    plt.figure(1)\n    plt.clf()\n    plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Wistia)\n    classNames = ['Nondemented','Demented']\n    plt.title('Confusion Matrix')\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\n    tick_marks = np.arange(len(classNames))\n    plt.xticks(tick_marks, classNames)\n    plt.yticks(tick_marks, classNames)\n    s = [['TN','FP'], ['FN', 'TP']]\n    for i in range(2):\n        for j in range(2):\n            plt.text(j,i, str(s[i][j])+\" = \"+str(cm[i][j]))\n    plt.show()\n```\n\n\n```python\nfrom sklearn.metrics import roc_curve, auc\ndef report_performance(model):\n\n    model_test = model.predict(X_test)\n\n    print(\"\\n\\nConfusion Matrix:\")\n    print(\"{0}\".format(metrics.confusion_matrix(y_test, model_test)))\n    print(\"\\n\\nClassification Report: \")\n    print(metrics.classification_report(y_test, model_test))\n    #cm = metrics.confusion_matrix(y_test, model_test)\n    plot_confusion_metrix(y_test, model_test)\n\ndef roc_curves(model):\n    predictions_test = model.predict(X_test)\n    fpr, tpr, thresholds = roc_curve(predictions_test,y_test)\n    roc_auc = auc(fpr, tpr)\n\n    plt.figure()\n    plt.plot(fpr, tpr, color='darkorange', lw=1, label='ROC curve (area = %0.2f)' % roc_auc)\n    plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')\n    plt.xlim([0.0, 1.0])\n    plt.ylim([0.0, 1.05])\n    plt.xlabel('False Positive Rate')\n    plt.ylabel('True Positive Rate')\n    plt.title('Receiver operating characteristic')\n    plt.legend(loc=\"lower right\")\n    plt.show()\n```\n\n\n```python\ntotal_models = ['GridSearchCV','SVC','DecisionTreeClassifier','XGBClassifier','LGBMClassifier',\n                    'ExtraTreesClassifier','GradientBoostingClassifier','AdaBoostClassifier','KNeighborsClassifier',\n                    'MLPClassifier','GaussianNB','LogisticRegression']\ntotal_accuracy = {}\nfor i in total_models:\n    total_accuracy[str(i)] = 0\ndef accuracy(model):\n    pred = model.predict(X_test)\n    accu = metrics.accuracy_score(y_test,pred)\n    print(\"\\nAcuuracy Of the Model: \",accu,\"\\n\\n\")\n    total_accuracy[str((str(model).split('(')[0]))] = accu\n```\n\n\n```python\nfrom sklearn.gaussian_process import GaussianProcessClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn import metrics\nfrom xgboost import XGBClassifier\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.tree import ExtraTreeClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.ensemble import BaggingClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom lightgbm import LGBMClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.neural_network import MLPClassifier\n```\n\n\n```python\nfrom sklearn.feature_selection import RFECV\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\n```\n\n\n```python\nimport numpy as np\nfrom sklearn.svm import SVC\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.preprocessing import MultiLabelBinarizer\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.gaussian_process import GaussianProcessClassifier\nfrom sklearn.gaussian_process.kernels import RBF\nfrom sklearn import datasets\n```\n\n\n```python\nfrom google.colab import files\nupload=files.upload()\n```\n\n\n\n<input type=\"file\" id=\"files-f9fc7955-8382-44d2-b49a-7c2194f29836\" name=\"files[]\" multiple disabled\n   style=\"border:none\" />\n<output id=\"result-f9fc7955-8382-44d2-b49a-7c2194f29836\">\n Upload widget is only available when the cell has been executed in the\n current browser session. Please rerun this cell to enable.\n </output>\n  \n\n\n    Saving oasis_longitudinal_original_1.xlsx to oasis_longitudinal_original_1 (2).xlsx\n\n\n# Receiver Operating Characteristic (ROC)\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom itertools import cycle\n\nfrom sklearn import svm, datasets\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import label_binarize\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom scipy import interp\nfrom sklearn.metrics import roc_auc_score\n```\n\n\n```python\n# Binarize the output\ny = label_binarize(y, classes=[0, 1, 2,3])\nn_classes = y.shape[1]\n```\n\n\n```python\n# Add noisy features to make the problem harder\nrandom_state = np.random.RandomState(0)\nn_samples, n_features = X.shape\nX = np.c_[X, random_state.randn(n_samples, 200 * n_features)]\n```\n\n\n```python\n# shuffle and split training and test sets\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5,\n                                                    random_state=0)\n```\n\n\n```python\n# Learn to predict each class against the other\nclassifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True,\n                                 random_state=random_state))\ny_score = classifier.fit(X_train, y_train).decision_function(X_test)\n```\n\n    /usr/local/lib/python3.7/dist-packages/sklearn/multiclass.py:75: UserWarning: Label not 3 is present in all training examples.\n      str(classes[c]))\n\n\n\n```python\n# Compute ROC curve and ROC area for each class\nfpr = dict()\ntpr = dict()\nroc_auc = dict()\nfor i in range(n_classes):\n    fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])\n    roc_auc[i] = auc(fpr[i], tpr[i])\n```\n\n    /usr/local/lib/python3.7/dist-packages/sklearn/metrics/_ranking.py:808: UndefinedMetricWarning: No positive samples in y_true, true positive value should be meaningless\n      UndefinedMetricWarning)\n\n\n\n```python\n# Compute micro-average ROC curve and ROC area\nfpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(y_test.ravel(), y_score.ravel())\nroc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\n```\n\n\n```python\nplt.figure()\nlw = 2\nplt.plot(fpr[2], tpr[2], color='darkorange',\n         lw=lw, label='ROC curve (area = %0.2f)' % roc_auc[2])\nplt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic example')\nplt.legend(loc=\"lower right\")\nplt.show()\n```\n\n\n```python\n# First aggregate all false positive rates\nall_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))\n\n# Then interpolate all ROC curves at this points\nmean_tpr = np.zeros_like(all_fpr)\nfor i in range(n_classes):\n    mean_tpr += interp(all_fpr, fpr[i], tpr[i])\n\n# Finally average it and compute AUC\nmean_tpr /= n_classes\n\nfpr[\"macro\"] = all_fpr\ntpr[\"macro\"] = mean_tpr\nroc_auc[\"macro\"] = auc(fpr[\"macro\"], tpr[\"macro\"])\n\n# Plot all ROC curves\nplt.figure()\nplt.plot(fpr[\"micro\"], tpr[\"micro\"],\n         label='micro-average ROC curve (area = {0:0.2f})'\n               ''.format(roc_auc[\"micro\"]),\n         color='deeppink', linestyle=':', linewidth=4)\n\nplt.plot(fpr[\"macro\"], tpr[\"macro\"],\n         label='macro-average ROC curve (area = {0:0.2f})'\n               ''.format(roc_auc[\"macro\"]),\n         color='navy', linestyle=':', linewidth=4)\n\ncolors = cycle(['aqua', 'darkorange', 'cornflowerblue'])\nfor i, color in zip(range(n_classes), colors):\n    plt.plot(fpr[i], tpr[i], color=color, lw=lw,\n             label='ROC curve of class {0} (area = {1:0.2f})'\n             ''.format(i, roc_auc[i]))\n\nplt.plot([0, 1], [0, 1], 'k--', lw=lw)\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Some extension of Receiver operating characteristic to multi-class')\nplt.legend(loc=\"lower right\")\nplt.show()\n```\n\n\n```python\nprint(__doc__)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n```\n\n    Automatically created module for IPython interactive environment\n\n\n\n```python\nsns.scatterplot(\n    x=X[:, 0], y=X[:, 1], hue=y,\n    marker='o', s=25, edgecolor='k', legend=False\n).set_title(\"Data\")\nplt.show()\n```\n\n\n```python\nfrom sklearn.model_selection import GridSearchCV, RepeatedStratifiedKFold\nfrom sklearn.svm import SVC\n\nparam_grid = [\n    {'kernel': ['linear']},\n    {'kernel': ['poly'], 'degree': [2, 3]},\n    {'kernel': ['rbf']}\n]\n\nsvc = SVC(random_state=0)\n\ncv = RepeatedStratifiedKFold(\n    n_splits=10, n_repeats=10, random_state=0\n)\n\nsearch = GridSearchCV(\n    estimator=svc, param_grid=param_grid,\n    scoring='roc_auc', cv=cv\n)\nsearch.fit(X, y)\n```\n\n\n\n\n    GridSearchCV(cv=RepeatedStratifiedKFold(n_repeats=10, n_splits=10, random_state=0),\n                 error_score=nan,\n                 estimator=SVC(C=1.0, break_ties=False, cache_size=200,\n                               class_weight=None, coef0=0.0,\n                               decision_function_shape='ovr', degree=3,\n                               gamma='scale', kernel='rbf', max_iter=-1,\n                               probability=False, random_state=0, shrinking=True,\n                               tol=0.001, verbose=False),\n                 iid='deprecated', n_jobs=None,\n                 param_grid=[{'kernel': ['linear']},\n                             {'degree': [2, 3], 'kernel': ['poly']},\n                             {'kernel': ['rbf']}],\n                 pre_dispatch='2*n_jobs', refit=True, return_train_score=False,\n                 scoring='roc_auc', verbose=0)\n\n\n\n\n```python\nimport pandas as pd\n\nresults_df = pd.DataFrame(search.cv_results_)\nresults_df = results_df.sort_values(by=['rank_test_score'])\nresults_df = (\n    results_df\n    .set_index(results_df[\"params\"].apply(\n        lambda x: \"_\".join(str(val) for val in x.values()))\n    )\n    .rename_axis('kernel')\n)\nresults_df[\n    ['params', 'rank_test_score', 'mean_test_score', 'std_test_score']\n]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>params</th>\n      <th>rank_test_score</th>\n      <th>mean_test_score</th>\n      <th>std_test_score</th>\n    </tr>\n    <tr>\n      <th>kernel</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>rbf</th>\n      <td>{'kernel': 'rbf'}</td>\n      <td>1</td>\n      <td>0.9400</td>\n      <td>0.079297</td>\n    </tr>\n    <tr>\n      <th>linear</th>\n      <td>{'kernel': 'linear'}</td>\n      <td>2</td>\n      <td>0.9300</td>\n      <td>0.077846</td>\n    </tr>\n    <tr>\n      <th>3_poly</th>\n      <td>{'degree': 3, 'kernel': 'poly'}</td>\n      <td>3</td>\n      <td>0.9044</td>\n      <td>0.098776</td>\n    </tr>\n    <tr>\n      <th>2_poly</th>\n      <td>{'degree': 2, 'kernel': 'poly'}</td>\n      <td>4</td>\n      <td>0.6852</td>\n      <td>0.169106</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n# We can see that the estimator using the 'rbf' kernel performed best, closely followed by 'linear'. Both estimators with a 'poly' kernel performed worse, with the one using a two-degree polynomial achieving a much lower perfomance than all other models.\n\n\n```python\n# create df of model scores ordered by perfomance\nmodel_scores = results_df.filter(regex=r'split\\d*_test_score')\n\n# plot 30 examples of dependency between cv fold and AUC scores\nfig, ax = plt.subplots()\nsns.lineplot(\n    data=model_scores.transpose().iloc[:30],\n    dashes=False, palette='Set1', marker='o', alpha=.5, ax=ax\n)\nax.set_xlabel(\"CV test fold\", size=12, labelpad=10)\nax.set_ylabel(\"Model AUC\", size=12)\nax.tick_params(bottom=True, labelbottom=False)\nplt.show()\n\n# print correlation of AUC scores across folds\nprint(f\"Correlation of models:\\n {model_scores.transpose().corr()}\")\n```\n\n# We can observe that the performance of the models highly depends on the fold.\n\nAs a consequence, if we assume independence between samples we will be underestimating the variance computed in our statistical tests, increasing the number of false positive errors (i.e. detecting a significant difference between models when such does not exist) [1]_.\n\nSeveral variance-corrected statistical tests have been developed for these cases. In this example we will show how to implement one of them (the so called Nadeau and Bengio's corrected t-test) under two different statistical frameworks: frequentist and Bayesian.\n\n\n```python\nimport numpy as np\nfrom scipy.stats import t\n\n\ndef corrected_std(differences, n_train, n_test):\n    \"\"\"Corrects standard deviation using Nadeau and Bengio's approach.\n\n    Parameters\n    ----------\n    differences : ndarray of shape (n_samples, 1)\n        Vector containing the differences in the score metrics of two models.\n    n_train : int\n        Number of samples in the training set.\n    n_test : int\n        Number of samples in the testing set.\n\n    Returns\n    -------\n    corrected_std : int\n        Variance-corrected standard deviation of the set of differences.\n    \"\"\"\n    n = n_train + n_test\n    corrected_var = (\n        np.var(differences, ddof=1) * ((1 / n) + (n_test / n_train))\n    )\n    corrected_std = np.sqrt(corrected_var)\n    return corrected_std\n\n\ndef compute_corrected_ttest(differences, df, n_train, n_test):\n    \"\"\"Computes right-tailed paired t-test with corrected variance.\n\n    Parameters\n    ----------\n    differences : array-like of shape (n_samples, 1)\n        Vector containing the differences in the score metrics of two models.\n    df : int\n        Degrees of freedom.\n    n_train : int\n        Number of samples in the training set.\n    n_test : int\n        Number of samples in the testing set.\n\n    Returns\n    -------\n    t_stat : float\n        Variance-corrected t-statistic.\n    p_val : float\n        Variance-corrected p-value.\n    \"\"\"\n    mean = np.mean(differences)\n    std = corrected_std(differences, n_train, n_test)\n    t_stat = mean / std\n    p_val = t.sf(np.abs(t_stat), df)  # right-tailed t-test\n    return t_stat, p_val\n```\n\n\n```python\nmodel_1_scores = model_scores.iloc[0].values  # scores of the best model\nmodel_2_scores = model_scores.iloc[1].values  # scores of the second-best model\n\ndifferences = model_1_scores - model_2_scores\n\nn = differences.shape[0]  # number of test sets\ndf = n - 1\nn_train = len(list(cv.split(X, y))[0][0])\nn_test = len(list(cv.split(X, y))[0][1])\n\nt_stat, p_val = compute_corrected_ttest(differences, df, n_train, n_test)\nprint(f\"Corrected t-value: {t_stat:.3f}\\n\"\n      f\"Corrected p-value: {p_val:.3f}\")\n```\n\n    Corrected t-value: 0.750\n    Corrected p-value: 0.227\n\n\n\n```python\nt_stat_uncorrected = (\n    np.mean(differences) / np.sqrt(np.var(differences, ddof=1) / n)\n)\np_val_uncorrected = t.sf(np.abs(t_stat_uncorrected), df)\n\nprint(f\"Uncorrected t-value: {t_stat_uncorrected:.3f}\\n\"\n      f\"Uncorrected p-value: {p_val_uncorrected:.3f}\")\n```\n\n    Uncorrected t-value: 2.611\n    Uncorrected p-value: 0.005\n\n\n# Using the conventional significance alpha level at p=0.05, we observe that the uncorrected t-test concludes that the first model is significantly better than the second.\n\nWith the corrected approach, in contrast, we fail to detect this difference.\n\nIn the latter case, however, the frequentist approach does not let us conclude that the first and second model have an equivalent performance. If we wanted to make this assertion we need to use a Bayesian approach.\n\n## Comparing two models: Bayesian approach\nWe can use Bayesian estimation to calculate the probability that the first\nmodel is better than the second. Bayesian estimation will output a\ndistribution followed by the mean $\\mu$ of the differences in the\nperformance of two models.\n\nTo obtain the posterior distribution we need to define a prior that models\nour beliefs of how the mean is distributed before looking at the data,\nand multiply it by a likelihood function that computes how likely our\nobserved differences are, given the values that the mean of differences\ncould take.\n\nBayesian estimation can be carried out in many forms to answer our question,\nbut in this example we will implement the approach suggested by Benavoli and\ncollegues [4]_.\n\nOne way of defining our posterior using a closed-form expression is to select\na prior conjugate to the likelihood function. Benavoli and collegues [4]_\nshow that when comparing the performance of two classifiers we can model the\nprior as a Normal-Gamma distribution (with both mean and variance unknown)\nconjugate to a normal likelihood, to thus express the posterior as a normal\ndistribution.\nMarginalizing out the variance from this normal posterior, we can define the\nposterior of the mean parameter as a Student's t-distribution. Specifically:\n\n\\begin{align}St(\\mu;n-1,\\overline{x},(\\frac{1}{n}+\\frac{n_{test}}{n_{train}})\n   \\hat{\\sigma}^2)\\end{align}\n\nwhere $n$ is the total number of samples,\n$\\overline{x}$ represents the mean difference in the scores,\n$n_{test}$ is the number of samples used for testing,\n$n_{train}$ is the number of samples used for training,\nand $\\hat{\\sigma}^2$ represents the variance of the observed\ndifferences.\n\nNotice that we are using Nadeau and Bengio's corrected variance in our\nBayesian approach as well.\n\nLet's compute and plot the posterior:\n\n\n\n\n```python\n# intitialize random variable\nt_post = t(\n    df, loc=np.mean(differences),\n    scale=corrected_std(differences, n_train, n_test)\n)\n```\n\n\n```python\nx = np.linspace(t_post.ppf(0.001), t_post.ppf(0.999), 100)\n\nplt.plot(x, t_post.pdf(x))\nplt.xticks(np.arange(-0.04, 0.06, 0.01))\nplt.fill_between(x, t_post.pdf(x), 0, facecolor='blue', alpha=.2)\nplt.ylabel(\"Probability density\")\nplt.xlabel(r\"Mean difference ($\\mu$)\")\nplt.title(\"Posterior distribution\")\nplt.show()\n```\n\nWe can calculate the probability that the first model is better than the second by computing the area under the curve of the posterior distirbution from zero to infinity. And also the reverse: we can calculate the probability that the second model is better than the first by computing the area under the curve from minus infinity to zero.\n\n\n```python\nbetter_prob = 1 - t_post.cdf(0)\n\nprint(f\"Probability of {model_scores.index[0]} being more accurate than \"\n      f\"{model_scores.index[1]}: {better_prob:.3f}\")\nprint(f\"Probability of {model_scores.index[1]} being more accurate than \"\n      f\"{model_scores.index[0]}: {1 - better_prob:.3f}\")\n```\n\n    Probability of rbf being more accurate than linear: 0.773\n    Probability of linear being more accurate than rbf: 0.227\n\n\n\n\n\n```python\nrope_interval = [-0.01, 0.01]\nrope_prob = t_post.cdf(rope_interval[1]) - t_post.cdf(rope_interval[0])\n\nprint(f\"Probability of {model_scores.index[0]} and {model_scores.index[1]} \"\n      f\"being practically equivalent: {rope_prob:.3f}\")\n```\n\n    Probability of rbf and linear being practically equivalent: 0.432\n\n\n\n```python\nx_rope = np.linspace(rope_interval[0], rope_interval[1], 100)\n\nplt.plot(x, t_post.pdf(x))\nplt.xticks(np.arange(-0.04, 0.06, 0.01))\nplt.vlines([-0.01, 0.01], ymin=0, ymax=(np.max(t_post.pdf(x)) + 1))\nplt.fill_between(x_rope, t_post.pdf(x_rope), 0, facecolor='blue', alpha=.2)\nplt.ylabel(\"Probability density\")\nplt.xlabel(r\"Mean difference ($\\mu$)\")\nplt.title(\"Posterior distribution under the ROPE\")\nplt.show()\n```\n\n\n```python\ncred_intervals = []\nintervals = [0.5, 0.75, 0.95]\n\nfor interval in intervals:\n    cred_interval = list(t_post.interval(interval))\n    cred_intervals.append([interval, cred_interval[0], cred_interval[1]])\n\ncred_int_df = pd.DataFrame(\n    cred_intervals,\n    columns=['interval', 'lower value', 'upper value']\n).set_index('interval')\ncred_int_df\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>lower value</th>\n      <th>upper value</th>\n    </tr>\n    <tr>\n      <th>interval</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0.50</th>\n      <td>0.000977</td>\n      <td>0.019023</td>\n    </tr>\n    <tr>\n      <th>0.75</th>\n      <td>-0.005422</td>\n      <td>0.025422</td>\n    </tr>\n    <tr>\n      <th>0.95</th>\n      <td>-0.016445</td>\n      <td>0.036445</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nfrom itertools import combinations\nfrom math import factorial\n\nn_comparisons = (\n    factorial(len(model_scores))\n    / (factorial(2) * factorial(len(model_scores) - 2))\n)\npairwise_t_test = []\n\nfor model_i, model_k in combinations(range(len(model_scores)), 2):\n    model_i_scores = model_scores.iloc[model_i].values\n    model_k_scores = model_scores.iloc[model_k].values\n    differences = model_i_scores - model_k_scores\n    t_stat, p_val = compute_corrected_ttest(\n        differences, df, n_train, n_test\n    )\n    p_val *= n_comparisons  # implement Bonferroni correction\n    # Bonferroni can output p-values higher than 1\n    p_val = 1 if p_val > 1 else p_val\n    pairwise_t_test.append(\n        [model_scores.index[model_i], model_scores.index[model_k],\n         t_stat, p_val]\n    )\n\npairwise_comp_df = pd.DataFrame(\n    pairwise_t_test,\n    columns=['model_1', 'model_2', 't_stat', 'p_val']\n).round(3)\npairwise_comp_df\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>model_1</th>\n      <th>model_2</th>\n      <th>t_stat</th>\n      <th>p_val</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>rbf</td>\n      <td>linear</td>\n      <td>0.750</td>\n      <td>1.000</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>rbf</td>\n      <td>3_poly</td>\n      <td>1.657</td>\n      <td>0.302</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>rbf</td>\n      <td>2_poly</td>\n      <td>4.565</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>linear</td>\n      <td>3_poly</td>\n      <td>1.111</td>\n      <td>0.807</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>linear</td>\n      <td>2_poly</td>\n      <td>4.276</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>3_poly</td>\n      <td>2_poly</td>\n      <td>3.851</td>\n      <td>0.001</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nWe observe that after correcting for multiple comparisons, the only model\nthat significantly differs from the others is `'2_poly'`.\n`'rbf'`, the model ranked first by\n:class:`~sklearn.model_selection.GridSearchCV`, does not significantly\ndiffer from `'linear'` or `'3_poly'`.\n\n\n\n\n```python\npairwise_bayesian = []\n\nfor model_i, model_k in combinations(range(len(model_scores)), 2):\n    model_i_scores = model_scores.iloc[model_i].values\n    model_k_scores = model_scores.iloc[model_k].values\n    differences = model_i_scores - model_k_scores\n    t_post = t(\n        df, loc=np.mean(differences),\n        scale=corrected_std(differences, n_train, n_test)\n    )\n    worse_prob = t_post.cdf(rope_interval[0])\n    better_prob = 1 - t_post.cdf(rope_interval[1])\n    rope_prob = t_post.cdf(rope_interval[1]) - t_post.cdf(rope_interval[0])\n\n    pairwise_bayesian.append([worse_prob, better_prob, rope_prob])\n\npairwise_bayesian_df = (pd.DataFrame(\n    pairwise_bayesian,\n    columns=['worse_prob', 'better_prob', 'rope_prob']\n).round(3))\n\npairwise_comp_df = pairwise_comp_df.join(pairwise_bayesian_df)\npairwise_comp_df\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>model_1</th>\n      <th>model_2</th>\n      <th>t_stat</th>\n      <th>p_val</th>\n      <th>worse_prob</th>\n      <th>better_prob</th>\n      <th>rope_prob</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>rbf</td>\n      <td>linear</td>\n      <td>0.750</td>\n      <td>1.000</td>\n      <td>0.068</td>\n      <td>0.500</td>\n      <td>0.432</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>rbf</td>\n      <td>3_poly</td>\n      <td>1.657</td>\n      <td>0.302</td>\n      <td>0.018</td>\n      <td>0.882</td>\n      <td>0.100</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>rbf</td>\n      <td>2_poly</td>\n      <td>4.565</td>\n      <td>0.000</td>\n      <td>0.000</td>\n      <td>1.000</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>linear</td>\n      <td>3_poly</td>\n      <td>1.111</td>\n      <td>0.807</td>\n      <td>0.063</td>\n      <td>0.750</td>\n      <td>0.187</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>linear</td>\n      <td>2_poly</td>\n      <td>4.276</td>\n      <td>0.000</td>\n      <td>0.000</td>\n      <td>1.000</td>\n      <td>0.000</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>3_poly</td>\n      <td>2_poly</td>\n      <td>3.851</td>\n      <td>0.001</td>\n      <td>0.000</td>\n      <td>1.000</td>\n      <td>0.000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n# Using the Bayesian approach we can compute the probability that a model performs better, worse or practically equivalent to another.\n\nResults show that the model ranked first by :class:~sklearn.model_selection.GridSearchCV 'rbf', has approximately a 6.8% chance of being worse than 'linear', and a 1.8% chance of being worse than '3_poly'. 'rbf' and 'linear' have a 43% probability of being practically equivalent, while 'rbf' and '3_poly' have a 10% chance of being so.\n\nSimilarly to the conclusions obtained using the frequentist approach, all models have a 100% probability of being better than '2_poly', and none have a practically equivalent performance with the latter.\n", "meta": {"hexsha": "2609486d0fa7d194745fea68986cd057c8689bb8", "size": 819175, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Alzheimer_Analysis_Dementia.ipynb", "max_stars_repo_name": "yogeshmj/AD-DL", "max_stars_repo_head_hexsha": "76b9b564061581effe8f3698992bfea3ffb055fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Alzheimer_Analysis_Dementia.ipynb", "max_issues_repo_name": "yogeshmj/AD-DL", "max_issues_repo_head_hexsha": "76b9b564061581effe8f3698992bfea3ffb055fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Alzheimer_Analysis_Dementia.ipynb", "max_forks_repo_name": "yogeshmj/AD-DL", "max_forks_repo_head_hexsha": "76b9b564061581effe8f3698992bfea3ffb055fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 250.7422711968, "max_line_length": 153586, "alphanum_fraction": 0.8873561815, "converted": true, "num_tokens": 17618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814055953761018, "lm_q2_score": 0.052618947776520146, "lm_q1q2_score": 0.01480726632711566}}
{"text": "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Final-Exam-Part-3\" data-toc-modified-id=\"Final-Exam-Part-3-3\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>Final Exam Part 3</a></span><ul class=\"toc-item\"><li><span><a href=\"#\ud83d\udd01-Describe-the-following-effects/experiments/equations,-and-explain-their-importance-to-the-origins-of-quantum-mechanics.\" data-toc-modified-id=\"\ud83d\udd01-Describe-the-following-effects/experiments/equations,-and-explain-their-importance-to-the-origins-of-quantum-mechanics.-3.1\"><span class=\"toc-item-num\">3.1&nbsp;&nbsp;</span>\ud83d\udd01 Describe the following effects/experiments/equations, and explain their importance to the origins of quantum mechanics.</a></span></li><li><span><a href=\"#\ud83d\udd01-Explain-the-following-topics.\" data-toc-modified-id=\"\ud83d\udd01-Explain-the-following-topics.-3.2\"><span class=\"toc-item-num\">3.2&nbsp;&nbsp;</span>\ud83d\udd01 Explain the following topics.</a></span></li><li><span><a href=\"#\ud83d\udd01-What-are-the-eigenfunctions-and-eigenvalues-for-the-following-Hamiltonians.\" data-toc-modified-id=\"\ud83d\udd01-What-are-the-eigenfunctions-and-eigenvalues-for-the-following-Hamiltonians.-3.3\"><span class=\"toc-item-num\">3.3&nbsp;&nbsp;</span>\ud83d\udd01 What are the eigenfunctions and eigenvalues for the following Hamiltonians.</a></span></li><li><span><a href=\"#\ud83e\udd14-Discuss-the-following-in-your-own-words.\" data-toc-modified-id=\"\ud83e\udd14-Discuss-the-following-in-your-own-words.-3.4\"><span class=\"toc-item-num\">3.4&nbsp;&nbsp;</span>\ud83e\udd14 Discuss the following in your own words.</a></span></li></ul></li></ul></div>\n\n# Final Exam Part 3\n&#x1f468;&#x200d;&#x1f3eb; **Overview:**\nThis is Part 3 of 3 Parts of your Final Exam/Project. \n- **Part 1.** Questions on the Course Material. (40%)\n- **Part 2.** Applying the Course material. (40%)\n- **Part 3.** Discussing your exam and the Course Material. (20%) \n\n**You must submit your Jupyter notebooks for Part 1 and Part 2 at least 48 hours prior to your appointment for Part 3.** You will be given your grade on Part 1 and Part 2 before the oral exam, so that you know what your status is. *For late submission of Part 1 and/or Part 2, I will deduct 2 points per hour.\n\n&#x1f4d6; **Rules for \"Open Book\" Exam:**\n**Like all other portions of this exam, this part of the exam is open notes and open library. It is \"open internet search\" but you (obviously!) can't post questions on an internet discussion board or homework/problem/exam help site. You are not allowed to communicate with your classmates or any other human being (except me) about these questions or your responses, and this includes human beings (singular or plural, known or anonymous) online.**\n\n&#x1f4af; **Grading:**\nWhen we discuss Parts 1 and 2 of the exam, your grade will be \"plus\", \"minus\" or \"neutral.\" You can gain, or lose, up to 20 points based on your performance on the oral portion of the exam.\n- A \"plus\" response indicates that you know the answer to the question, and can expound upon it and related topics with mastery. \n- A \"minus\" response indicates that while you may have answered a question correctly, you \"got the right answer for the wrong reason\" or your understanding of the topic being tested is only superficial. A \"minus\" response is also indicative of cases where you simply can't answer a question. If for whatever reason you do not schedule an oral exam, that will be taken as a \"minus\" response for *all* questions. Don't do this: it will be -40% on your final exam grade.\n- A \"neutral\" response is the default, and is anything except mastery (\"plus\") or na&iuml;vt&eacute; (\"minus\"). I anticipate that most responses will be \"neutral\".\n\nIn addition to discussing your answers in Parts 1 and 2, we will discuss the following questions. Each question group has 6 questions in it. I will randomly select one question from each group; we will then discuss that question. Each question will be graded \"plus\" (5 points) \"minus\" (0 points) or \"neutral\" (3 points). You can score up to 20 points on this portion of the exam, and the \"default\" score would be about 12 points. \n\n&#x1f4dc; **Instructions:** Be prepared to discuss the following questions/topics. I will randomly select 1 question from each group.\n\n## &#x1f501; Describe the following effects/experiments/equations, and explain their importance to the origins of quantum mechanics.\n1. Black-Body Radiation and the Ultraviolet Catastrophe.\n1. The Davisson-Germer experiment and Electron Scattering.\n1. Compton Scattering.\n1. The Photoelectric Effect\n1. The Rydberg Formula\n1. The Stern-Gerlach Experiment\n\n## &#x1f501; Explain the following topics. \n1. What are the key postulates of quantum mechanics?\n1. What is the Heisenberg Uncertainty Principle? What does it say about the fundamentals of quantum mechanics? What is the commutator between two operators, and how does it relate to the Heisenberg Uncertainty Principle? \n1. Explain what the Born-Oppenheimer Approximation is and why it is important.\n1. Explain what the united-atom and separated-atom limit are for a diatomic molecule. How do these limits relate to molecular-orbital theory and the linear-combination-of-atomic-orbitals technique.\n1. What are the quantum numbers that describe the state of an atom (neglecting relativity)? What do these quantum numbers have to do with term symbols? What do these quantum numbers have to do with simultaneous observables?\n1. What is the Stern Gerlach experiment? Can you describe what is happening in the following diagram?\n\n\n## &#x1f501; What are the eigenfunctions and eigenvalues for the following Hamiltonians. \nYou should be able to explain key characteristics of the systems and the general strategy for (possibly approximate) solving the associated time-independent Schr&ouml;dinger equation.\n\n\\begin{align}\n\\hat{H}_1 &= -\\frac{\\hbar^2}{2m} \\frac{d^2}{dx^2} -\\frac{\\hbar^2}{2m} \\frac{d^2}{dy^2} + V_{a_x}(x) + V_{a_y}(y) \\\\\n\\hat{H}_2(\\lambda) &= -\\frac{\\hbar^2}{2m} \\frac{d^2}{dx_1^2} -\\frac{\\hbar^2}{2m} \\frac{d^2}{dx_2^2} + V_{a}(x_1) + V_{a}(x_2) \n- \\lambda |x_1 - x_2|\\\\\n\\hat{H}_3(\\lambda) &= -\\tfrac{1}{2} \\nabla_1^2 -\\tfrac{1}{2} \\nabla_2^2- \\tfrac{Z}{r_1} - \\tfrac{Z}{r_2} + \\tfrac{\\lambda}{|\\mathbf{r}_1 - \\mathbf{r}_2|}\\\\\n\\hat{H}_4 &= -\\frac{\\hbar^2}{2m} \\frac{d^2}{dx^2} -\\frac{\\hbar^2}{2m} \\frac{d^2}{dy^2} -\\frac{\\hbar^2}{2m} \\frac{d^2}{dz^2} + V_{a}\\left(\\sqrt{x^2 + y^2 +z^2}\\right) \\\\\n\\hat{H}_5(\\mathbf{R}_B) &=  -\\tfrac{1}{2} \\nabla_{\\mathbf{r}}^2 - \\tfrac{Z_A}{r} - \\tfrac{Z_B}{|\\mathbf{r} - \\mathbf{R}_B|} \\\\\n\\hat{H}_6 &= -\\frac{\\hbar^2}{2m} \\frac{d^2}{dx^2} -\\frac{\\hbar^2}{2m} \\frac{d^2}{dy^2} -\\frac{\\hbar^2}{2m} \\frac{d^2}{dz^2} + V_{a_z}(z) + V_{a_r}(\\sqrt{x^2+y^2})\n\\end{align}\nwhere\n$$\nV_a(x) = \n\\begin{cases}\n    +\\infty & x\\leq 0\\\\\n    0       & 0\\lt x \\lt a\\\\\n    +\\infty & a \\leq x\n\\end{cases}\n$$\n\n## &#x1f914; Discuss the following in your own words.\n1. What is a Slater determinant? Why does one use a Slater determinant for a many-fermion system? When is the exact ground-state wavefunction for a many-fermion system a Slater determinant?\n1. What is the variational principle? How is it used to approximate the ground-state energy and wavefunction of realistic, not-exactly-solvable, Hamiltonians? Can you give an example of how it is used?\n1. What is the Hartree-Fock method? What is the intuition behind it, and when is it used? \n1. What is Perturbation Theory? When is perturbation theory most appropriate? Least appropriate? \n1. What is the secular equation? How does it relate to the technique of expanding a wavefunction in a basis set?\n1. What is electron correlation? How can one approximate the effects of electron correlation?\n", "meta": {"hexsha": "2579146af0e1cff2d427366915a8c67fb2f6ec67", "size": 9915, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "book/Final Exam Part 3.ipynb", "max_stars_repo_name": "guacke/IntroQM2022", "max_stars_repo_head_hexsha": "3a268eda86491db86f674784169e921ff6a22b2b", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "book/Final Exam Part 3.ipynb", "max_issues_repo_name": "guacke/IntroQM2022", "max_issues_repo_head_hexsha": "3a268eda86491db86f674784169e921ff6a22b2b", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "book/Final Exam Part 3.ipynb", "max_forks_repo_name": "guacke/IntroQM2022", "max_forks_repo_head_hexsha": "3a268eda86491db86f674784169e921ff6a22b2b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.5436241611, "max_line_length": 1552, "alphanum_fraction": 0.6560766515, "converted": true, "num_tokens": 2290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1311732203653401, "lm_q2_score": 0.11279539882690352, "lm_q1q2_score": 0.01479573570651784}}
{"text": "# Scientific Computing: Numpy, Scipy and Graphics\n\n## Python shells, scripts and editors\n\nThese are instructions how to run Python as scripts, an alternative to working in a Notebook:\n\n\nUp to now we have used Python only in interactive mode, i.e. by directly typing commands at the Notebook/IPython prompt, which then get executed right away. While this is simple, and often convenient, it is also somewhat limiting. An alternative approach is to run Python as scripts/programs or notebooks like this one. A script is basically a list of Python commands saved in a file, which can then be executed together. Doing this makes it easy to save them for future re-use, re-run them with different input, etc. You can also use scripts written by others. Over the duration of our course there will be many such scripts provided to you, and you will also be writing some of your own.\n\nCreating a script is easy - you should open a text editor and enter the commands in it, taking proper care of any required indentations, etc. Any text editor program is fine for this (but only ones that handle pure text, NOT Word, Notepad, etc.). If you have never used one before I recommend 'gedit' as it has a simple, intuitive graphical interface. Examples of more advanced and powerful editors are 'emacs' and 'vi',  but those have a somewhat steeper initial learning curve. Nevertheless, feel free to try them out. Some of the nice Python programming environments like Geany and Spyder come with their own integrated editor and shell, and same is true for the Jupyter notebooks.\n\nYou can start the editor from the Xterm window by typing:\n\ngedit &\n\n(or emacs, or vi; the '&' sign above is to put the program in background, so you can still use the window - for IPython, or anything else you wish). \n\nAlternatively, you can start gedit (or other installed software) from within the ipython shell itself by the same command as above, but preceded by '!' (no quotes), i.e. \n\n!gedit &  \n\nThe preceding exclamation tells ipython that this is a normal shell command, not a Python statement. You can also start gedit from the Jupyter notebook, by doing \n\n!gedit\n  \n'gedit' is Python-aware, thus has features like color coding of Python keywords and automatic indentation, which makes your work easier. Before a program can be run, it must be saved as a Python file with the '.py' extension, for example, 'myprog.py'. The program can then be executed by typing \n\npython myprog.py\n\nNote: On Windows double-clicking on the program icon will usually also work. But beware: the program window closes immediately after execution, before you get a chance to read the output. To prevent this from happening, conclude the program with the line\n\nraw_input(\u2019press return\u2019)\n\nDouble-clicking the program icon also works in Unix and Linux if the first line of the program specifies the path to the Python interpreter (or a shell script that provides a link to Python). The path name must be preceded by the symbols '#!' (no quotes!). On my computer and the teaching machines the path is '/usr/bin/python',  so that all my programs should start with the line \n\n#!/usr/bin/python\n\nOn multiuser systems the path is sometimes '/usr/local/bin/python'.\n\nFrom within IPython a script can be ran using the magic command 'run': \n\n%run prog.py\n\nNote that the script file should be in your current IPython working \nfolder/directory. If you are not sure which folder you are currently in, enter 'pwd' at the IPython prompt, which tells you the current directory. If you are not at the correct place, you can change it using the \n\ncd directory_name  \n\ncommand.\n\nOnce a module (script/function) is saved in a file, you can do 'import'  just like for any other Python module. This is a way to use external codes and functions, as well as creating your own. When a module is loaded into a program for the first time with the 'import' statement, it is compiled into bytecode and written in a file with the extension '.pyc'. The next time the program is run, for efficiency the interpreter loads the bytecode rather than the original Python file. If in the meantime changes have been made to the module, the module is automatically recompiled. \n\nIt is a good idea to document your modules by adding a docstring at the \nbeginning of each module. The docstring, which is enclosed in triple quotes, should explain what the module does. Here is an example that documents the module 'error':\n\n```python\n## module error\n''' err(string).\n\n    Prints 'string' and terminates program.\n\n'''\nimport sys\ndef err(string):\n    print(string)\n    raw_input('Press return to exit')\n    sys.exit()\n\n```\nThe docstring of a module can be printed with the statement:\n\n```python\nimport math\nprint(math.__doc__)\n```\n\n    This module is always available.  It provides access to the\n    mathematical functions defined by the C standard.\n\n\n# NumPy (Numerical Python) module\nThe NumPy module is not a part of the standard Python release. It must be obtained separately and installed on your computer. It is already installed and available on the university machines. You can use it by loading it as a module. This module introduces array objects (vectors, matrices) that are similar to lists, but can be manipulated by numerous functions contained in the module. The size of an array is immutable (i.e. once array is defined you cannot change its size), and no empty elements are allowed.\n\nThe complete set of functions in NumPy is quite long, you can check what is available using:\n\n```python\nimport numpy\ndir(numpy)\n```\n\n\n\n\n    ['ALLOW_THREADS',\n     'BUFSIZE',\n     'CLIP',\n     'ComplexWarning',\n     'DataSource',\n     'ERR_CALL',\n     'ERR_DEFAULT',\n     'ERR_IGNORE',\n     'ERR_LOG',\n     'ERR_PRINT',\n     'ERR_RAISE',\n     'ERR_WARN',\n     'FLOATING_POINT_SUPPORT',\n     'FPE_DIVIDEBYZERO',\n     'FPE_INVALID',\n     'FPE_OVERFLOW',\n     'FPE_UNDERFLOW',\n     'False_',\n     'Inf',\n     'Infinity',\n     'MAXDIMS',\n     'MAY_SHARE_BOUNDS',\n     'MAY_SHARE_EXACT',\n     'MachAr',\n     'ModuleDeprecationWarning',\n     'NAN',\n     'NINF',\n     'NZERO',\n     'NaN',\n     'PINF',\n     'PZERO',\n     'PackageLoader',\n     'RAISE',\n     'RankWarning',\n     'SHIFT_DIVIDEBYZERO',\n     'SHIFT_INVALID',\n     'SHIFT_OVERFLOW',\n     'SHIFT_UNDERFLOW',\n     'ScalarType',\n     'Tester',\n     'TooHardError',\n     'True_',\n     'UFUNC_BUFSIZE_DEFAULT',\n     'UFUNC_PYVALS_NAME',\n     'VisibleDeprecationWarning',\n     'WRAP',\n     '_NoValue',\n     '__NUMPY_SETUP__',\n     '__all__',\n     '__builtins__',\n     '__config__',\n     '__doc__',\n     '__file__',\n     '__git_revision__',\n     '__mkl_version__',\n     '__name__',\n     '__package__',\n     '__path__',\n     '__version__',\n     '_import_tools',\n     '_mat',\n     'abs',\n     'absolute',\n     'absolute_import',\n     'add',\n     'add_docstring',\n     'add_newdoc',\n     'add_newdoc_ufunc',\n     'add_newdocs',\n     'alen',\n     'all',\n     'allclose',\n     'alltrue',\n     'alterdot',\n     'amax',\n     'amin',\n     'angle',\n     'any',\n     'append',\n     'apply_along_axis',\n     'apply_over_axes',\n     'arange',\n     'arccos',\n     'arccosh',\n     'arcsin',\n     'arcsinh',\n     'arctan',\n     'arctan2',\n     'arctanh',\n     'argmax',\n     'argmin',\n     'argpartition',\n     'argsort',\n     'argwhere',\n     'around',\n     'array',\n     'array2string',\n     'array_equal',\n     'array_equiv',\n     'array_repr',\n     'array_split',\n     'array_str',\n     'asanyarray',\n     'asarray',\n     'asarray_chkfinite',\n     'ascontiguousarray',\n     'asfarray',\n     'asfortranarray',\n     'asmatrix',\n     'asscalar',\n     'atleast_1d',\n     'atleast_2d',\n     'atleast_3d',\n     'average',\n     'bartlett',\n     'base_repr',\n     'bench',\n     'binary_repr',\n     'bincount',\n     'bitwise_and',\n     'bitwise_not',\n     'bitwise_or',\n     'bitwise_xor',\n     'blackman',\n     'bmat',\n     'bool',\n     'bool8',\n     'bool_',\n     'broadcast',\n     'broadcast_arrays',\n     'broadcast_to',\n     'busday_count',\n     'busday_offset',\n     'busdaycalendar',\n     'byte',\n     'byte_bounds',\n     'bytes_',\n     'c_',\n     'can_cast',\n     'cast',\n     'cbrt',\n     'cdouble',\n     'ceil',\n     'cfloat',\n     'char',\n     'character',\n     'chararray',\n     'choose',\n     'clip',\n     'clongdouble',\n     'clongfloat',\n     'column_stack',\n     'common_type',\n     'compare_chararrays',\n     'compat',\n     'complex',\n     'complex128',\n     'complex256',\n     'complex64',\n     'complex_',\n     'complexfloating',\n     'compress',\n     'concatenate',\n     'conj',\n     'conjugate',\n     'convolve',\n     'copy',\n     'copysign',\n     'copyto',\n     'core',\n     'corrcoef',\n     'correlate',\n     'cos',\n     'cosh',\n     'count_nonzero',\n     'cov',\n     'cross',\n     'csingle',\n     'ctypeslib',\n     'cumprod',\n     'cumproduct',\n     'cumsum',\n     'datetime64',\n     'datetime_as_string',\n     'datetime_data',\n     'deg2rad',\n     'degrees',\n     'delete',\n     'deprecate',\n     'deprecate_with_doc',\n     'diag',\n     'diag_indices',\n     'diag_indices_from',\n     'diagflat',\n     'diagonal',\n     'diff',\n     'digitize',\n     'disp',\n     'divide',\n     'division',\n     'dot',\n     'double',\n     'dsplit',\n     'dstack',\n     'dtype',\n     'e',\n     'ediff1d',\n     'einsum',\n     'emath',\n     'empty',\n     'empty_like',\n     'equal',\n     'errstate',\n     'euler_gamma',\n     'exp',\n     'exp2',\n     'expand_dims',\n     'expm1',\n     'extract',\n     'eye',\n     'fabs',\n     'fastCopyAndTranspose',\n     'fft',\n     'fill_diagonal',\n     'find_common_type',\n     'finfo',\n     'fix',\n     'flatiter',\n     'flatnonzero',\n     'flexible',\n     'fliplr',\n     'flipud',\n     'float',\n     'float128',\n     'float16',\n     'float32',\n     'float64',\n     'float_',\n     'floating',\n     'floor',\n     'floor_divide',\n     'fmax',\n     'fmin',\n     'fmod',\n     'format_parser',\n     'frexp',\n     'frombuffer',\n     'fromfile',\n     'fromfunction',\n     'fromiter',\n     'frompyfunc',\n     'fromregex',\n     'fromstring',\n     'full',\n     'full_like',\n     'fv',\n     'generic',\n     'genfromtxt',\n     'get_array_wrap',\n     'get_include',\n     'get_printoptions',\n     'getbuffer',\n     'getbufsize',\n     'geterr',\n     'geterrcall',\n     'geterrobj',\n     'gradient',\n     'greater',\n     'greater_equal',\n     'half',\n     'hamming',\n     'hanning',\n     'histogram',\n     'histogram2d',\n     'histogramdd',\n     'hsplit',\n     'hstack',\n     'hypot',\n     'i0',\n     'identity',\n     'iinfo',\n     'imag',\n     'in1d',\n     'index_exp',\n     'indices',\n     'inexact',\n     'inf',\n     'info',\n     'infty',\n     'inner',\n     'insert',\n     'int',\n     'int0',\n     'int16',\n     'int32',\n     'int64',\n     'int8',\n     'int_',\n     'int_asbuffer',\n     'intc',\n     'integer',\n     'interp',\n     'intersect1d',\n     'intp',\n     'invert',\n     'ipmt',\n     'irr',\n     'is_busday',\n     'isclose',\n     'iscomplex',\n     'iscomplexobj',\n     'isfinite',\n     'isfortran',\n     'isinf',\n     'isnan',\n     'isneginf',\n     'isposinf',\n     'isreal',\n     'isrealobj',\n     'isscalar',\n     'issctype',\n     'issubclass_',\n     'issubdtype',\n     'issubsctype',\n     'iterable',\n     'ix_',\n     'kaiser',\n     'kron',\n     'ldexp',\n     'left_shift',\n     'less',\n     'less_equal',\n     'lexsort',\n     'lib',\n     'linalg',\n     'linspace',\n     'little_endian',\n     'load',\n     'loads',\n     'loadtxt',\n     'log',\n     'log10',\n     'log1p',\n     'log2',\n     'logaddexp',\n     'logaddexp2',\n     'logical_and',\n     'logical_not',\n     'logical_or',\n     'logical_xor',\n     'logspace',\n     'long',\n     'longcomplex',\n     'longdouble',\n     'longfloat',\n     'longlong',\n     'lookfor',\n     'ma',\n     'mafromtxt',\n     'mask_indices',\n     'mat',\n     'math',\n     'matmul',\n     'matrix',\n     'matrixlib',\n     'max',\n     'maximum',\n     'maximum_sctype',\n     'may_share_memory',\n     'mean',\n     'median',\n     'memmap',\n     'meshgrid',\n     'mgrid',\n     'min',\n     'min_scalar_type',\n     'minimum',\n     'mintypecode',\n     'mirr',\n     'mod',\n     'modf',\n     'moveaxis',\n     'msort',\n     'multiply',\n     'nan',\n     'nan_to_num',\n     'nanargmax',\n     'nanargmin',\n     'nanmax',\n     'nanmean',\n     'nanmedian',\n     'nanmin',\n     'nanpercentile',\n     'nanprod',\n     'nanstd',\n     'nansum',\n     'nanvar',\n     'nbytes',\n     'ndarray',\n     'ndenumerate',\n     'ndfromtxt',\n     'ndim',\n     'ndindex',\n     'nditer',\n     'negative',\n     'nested_iters',\n     'newaxis',\n     'newbuffer',\n     'nextafter',\n     'nonzero',\n     'not_equal',\n     'nper',\n     'npv',\n     'numarray',\n     'number',\n     'obj2sctype',\n     'object',\n     'object0',\n     'object_',\n     'ogrid',\n     'oldnumeric',\n     'ones',\n     'ones_like',\n     'outer',\n     'packbits',\n     'pad',\n     'partition',\n     'percentile',\n     'pi',\n     'piecewise',\n     'pkgload',\n     'place',\n     'pmt',\n     'poly',\n     'poly1d',\n     'polyadd',\n     'polyder',\n     'polydiv',\n     'polyfit',\n     'polyint',\n     'polymul',\n     'polynomial',\n     'polysub',\n     'polyval',\n     'power',\n     'ppmt',\n     'print_function',\n     'prod',\n     'product',\n     'promote_types',\n     'ptp',\n     'put',\n     'putmask',\n     'pv',\n     'r_',\n     'rad2deg',\n     'radians',\n     'random',\n     'rank',\n     'rate',\n     'ravel',\n     'ravel_multi_index',\n     'real',\n     'real_if_close',\n     'rec',\n     'recarray',\n     'recfromcsv',\n     'recfromtxt',\n     'reciprocal',\n     'record',\n     'remainder',\n     'repeat',\n     'require',\n     'reshape',\n     'resize',\n     'restoredot',\n     'result_type',\n     'right_shift',\n     'rint',\n     'roll',\n     'rollaxis',\n     'roots',\n     'rot90',\n     'round',\n     'round_',\n     'row_stack',\n     's_',\n     'safe_eval',\n     'save',\n     'savetxt',\n     'savez',\n     'savez_compressed',\n     'sctype2char',\n     'sctypeDict',\n     'sctypeNA',\n     'sctypes',\n     'searchsorted',\n     'select',\n     'set_numeric_ops',\n     'set_printoptions',\n     'set_string_function',\n     'setbufsize',\n     'setdiff1d',\n     'seterr',\n     'seterrcall',\n     'seterrobj',\n     'setxor1d',\n     'shape',\n     'shares_memory',\n     'short',\n     'show_config',\n     'sign',\n     'signbit',\n     'signedinteger',\n     'sin',\n     'sinc',\n     'single',\n     'singlecomplex',\n     'sinh',\n     'size',\n     'sometrue',\n     'sort',\n     'sort_complex',\n     'source',\n     'spacing',\n     'split',\n     'sqrt',\n     'square',\n     'squeeze',\n     'stack',\n     'std',\n     'str',\n     'str_',\n     'string0',\n     'string_',\n     'subtract',\n     'sum',\n     'swapaxes',\n     'take',\n     'tan',\n     'tanh',\n     'tensordot',\n     'test',\n     'testing',\n     'tile',\n     'timedelta64',\n     'trace',\n     'transpose',\n     'trapz',\n     'tri',\n     'tril',\n     'tril_indices',\n     'tril_indices_from',\n     'trim_zeros',\n     'triu',\n     'triu_indices',\n     'triu_indices_from',\n     'true_divide',\n     'trunc',\n     'typeDict',\n     'typeNA',\n     'typecodes',\n     'typename',\n     'ubyte',\n     'ufunc',\n     'uint',\n     'uint0',\n     'uint16',\n     'uint32',\n     'uint64',\n     'uint8',\n     'uintc',\n     'uintp',\n     'ulonglong',\n     'unicode',\n     'unicode0',\n     'unicode_',\n     'union1d',\n     'unique',\n     'unpackbits',\n     'unravel_index',\n     'unsignedinteger',\n     'unwrap',\n     'ushort',\n     'vander',\n     'var',\n     'vdot',\n     'vectorize',\n     'version',\n     'void',\n     'void0',\n     'vsplit',\n     'vstack',\n     'warnings',\n     'where',\n     'who',\n     'zeros',\n     'zeros_like']\n\n\n\n## Creating an Array\nArrays can be created in several ways. One of them is to start from a list and use the 'array' function to turn it into an array:\n\narray(list,dtype = type specification)\n\nNotes: Lists can hold any sequence of any Python objects, while arrays can only hold objects of the same type. Arrays are most efficient when the elements are of the basic number types (float, int, complex).\n\nHere are two examples of creating a 2x2 array with floating-point elements:\n\n```python\nfrom numpy import array,float\na = array([[2.0, -1.0],[-1.0, 3.0]])\nprint(a)\n```\n\n    [[ 2. -1.]\n     [-1.  3.]]\n\n\n\n```python\nb = array([[2, -1],[-1, 3]],dtype = float)\nprint(b)\n```\n\n    [[ 2. -1.]\n     [-1.  3.]]\n\nA couple of quite useful functions which also create arrays are:\n\nzeros((dim1,dim2),dtype = type specification)\n\nwhich creates a dim1 by dim2 array and fills it with zeroes, and\n\nones((dim1,dim2),dtype = type specification)\n\nwhich fills the array with ones. The default type in both cases is float. Finally, there is the function\n\narange(from,to,increment)\n\nwhich works just like the range function, but returns an array rather than a list. Here are examples of creating arrays:\n\n```python\nimport numpy \nprint(numpy.arange(2,10,2))\n```\n\n    [2 4 6 8]\n\n\n\n```python\nprint(numpy.arange(2.0,10.0,2.0))\n```\n\n    [ 2.  4.  6.  8.]\n\n\n\n```python\nprint(numpy.zeros(3))\n```\n\n    [ 0.  0.  0.]\n\n\n\n```python\nprint(numpy.zeros((3),dtype=int))\n```\n\n    [0 0 0]\n\n\n\n```python\nprint(numpy.ones((2,2)))\n```\n\n    [[ 1.  1.]\n     [ 1.  1.]]\n\nAn alternative, similar to Matlab, is to use \n\nnumpy.linspace(0,n,num=n+1,endpoint=True)\n\nWe can then 'reshape' the array, converting it from 1D (vector) to 2D (matrix), note that the total sizes of the two should be exactly the same (in the example below it is 9 numbers):\n\n```python\nx = numpy.linspace(0,8,9).reshape(3,3)\nprint(x)\n```\n\n    [[ 0.  1.  2.]\n     [ 3.  4.  5.]\n     [ 6.  7.  8.]]\n\nNote of caution: Reshape does not copy - it does not create a new array, but rather creates a different view of the same data.\n\nWe can also do the above as follows:\n\n```python\nx = numpy.arange(9).reshape(3,3)\nprint(x)\n```\n\n    [[0 1 2]\n     [3 4 5]\n     [6 7 8]]\n\nwith the same resulting matrix (but made of integers! If you want real numbers you can do: \n\n```python\nx=numpy.arange(9.).reshape(3,3)\nprint(x)\n```\n\n    [[ 0.  1.  2.]\n     [ 3.  4.  5.]\n     [ 6.  7.  8.]]\n\nHere is another example, where we first create lists using a function and then convert them into arrays:\n\n```python\ndef f(x):\n  return x**3     # sample function\n\nn = 5           # no of points in [0,1]\ndx = 1.0/(n-1)  # x spacing\nxlist = [i*dx for i in range(n)]\nylist = [f(x) for x in xlist]\n```\nNote that once we have defined the function we can use it as any other function. We can then turn these lists into Numerical Python (NumPy) arrays:\n\n```python\nimport numpy as np\nx2 = np.array(xlist)\ny2 = np.array(ylist)\nprint(x2,y2)\n```\n\n    (array([ 0.  ,  0.25,  0.5 ,  0.75,  1.  ]), array([ 0.      ,  0.015625,  0.125   ,  0.421875,  1.      ]))\n\nAlternatively, instead of first making lists with x and y=f(x) data, and then turning lists into arrays, we can make NumPy arrays directly:\n\n```python\nn = 5                     # number of points\nx3 = np.linspace(0, 1, n) # n points in [0, 1]\ny3 = np.zeros(n)          # n zeros (float data type)\nfor i in xrange(n):\n     y3[i] = f(x3[i])\nprint(x3,y3)\n```\n\n    (array([ 0.  ,  0.25,  0.5 ,  0.75,  1.  ]), array([ 0.      ,  0.015625,  0.125   ,  0.421875,  1.      ]))\n\nNote: 'xrange'  is similar to 'range' but faster; 'xrange' in Python 2.x is called 'range' in Python 3.x.Caution regarding Vectors, Column and Row Matrices. Note that an n vector, an n by 1 (column) and 1 by n (row) matrix are three different \nobjects, even if they may contain the same data.\n## Exercise:\nCreate the following arrays (with correct data types):\n\n[[ 1  1  1  1]\n [ 1  1  1  1]\n [ 1  1  1  2]\n [ 1  6  1  1]]\n\n[[0. 0. 0. 0. 0.]\n [2. 0. 0. 0. 0.]\n [0. 3. 0. 0. 0.]\n [0. 0. 4. 0. 0.]\n [0. 0. 0. 5. 0.]\n [0. 0. 0. 0. 6.]]\n\n## Accessing and Changing Array Elements\nIf a is a rank-2 array (i.e. a matrix), then a[i,j] accesses the element in row i and column j, whereas a[i] refers to row i. The elements of an array can be changed by assignment:\n\n```python\nimport numpy\na = numpy.zeros((3,3),dtype=int)\nprint(a)\n```\n\n    [[0 0 0]\n     [0 0 0]\n     [0 0 0]]\n\n\n\n```python\na[0]=[2,3,5]    # Change a row\na[1,1]=6        # Change an element\na[2,0:2]=[8,-3] # Change part of a row\nprint(a)\n```\n\n    [[ 2  3  5]\n     [ 0  6  0]\n     [ 8 -3  0]]\n\n\n## Exercises:\nForm the following rank-2 array (without typing it in explicitly):\n\n[[1  6 11]\n[2  7 12]\n[3  8 13]\n[4  9 14]\n[5 10 15]]\n\nand generate a new array containing just its 2nd and 4th rows.\n\nChange the fourth row to [1, 4, 9].\n## Operations on Arrays\nArithmetic operators work differently on arrays than they do on tuples and lists -- the operation is broadcast to all the elements of the array; that is, the operation is applied to each element in the array individually. Array operations like that are generally very efficient since they are done by underlying optimized and fast C language functions. Here are some examples:\n\n```python\nfrom numpy import array\na = array([0.0, 4.0, 9.0, 16.0])\nprint(a/16.0)\nprint a - 4.0\n```\n\n    [ 0.      0.25    0.5625  1.    ]\n    [ -4.   0.   5.  12.]\n\nAll basic arithmetic operations are also performed element-wise (vectors should have the same length, matrices the same dimensions).\n\n```python\nv1=array([6.,7.,9.])\nv2=array([2.,3.,5.])\nprint('v1/v2=',v1/v2)\nprint('v1*v2=',v1*v2)\nprint('v1+v2=',v1+v2)\nprint('v1-v2=',v1-v2)\n```\n\n    ('v1/v2=', array([ 3.        ,  2.33333333,  1.8       ]))\n    ('v1*v2=', array([ 12.,  21.,  45.]))\n    ('v1+v2=', array([  8.,  10.,  14.]))\n    ('v1-v2=', array([ 4.,  4.,  4.]))\n\nThe mathematical functions available in NumPy are also broadcast:\n\n```python\nfrom numpy import array,sqrt,sin\na = array([1.0, 4.0, 9.0, 16.0])\nprint(sqrt(a))\nprint(sin(a))\n```\n\n    [ 1.  2.  3.  4.]\n    [ 0.84147098 -0.7568025   0.41211849 -0.28790332]\n\nFunctions imported from the math module will of course work on the individual array elements, but not on the array itself, in which they differ from the NumPy functions (even if they sometimes have the same name). Here is an example:\n\n```python\nfrom numpy import array\nfrom math import sqrt\na = array([1.0, 4.0, 9.0, 16.0])\n\nprint sqrt(a[1])\n```\n\n    2.0\n\n\n\n```python\nprint sqrt(a)\n```\n\n## Exercise:\n\nCreate an array x containing 100 equally-spaced numbers from 0 to $2\\pi$.\nCreate another array y whose first column contains x, the second one contains $\\sin(x)$ and the third one contains $\\sin^2(x)$. \n\n## Array Functions\nThere are numerous functions in NumPy that perform array operations and other useful tasks. Here are a few examples:\n\n```python\nimport numpy as np\nA = np.array([[4,-2,1],[-2,4,-2],[1,-2,3]],dtype=float)\nb = np.array([1,4,3],dtype=float)\n\nprint(np.diagonal(A)) # Principal diagonal of A\n```\n\n\n```python\nprint(np.trace(A)) # Sum of diagonal elements of A\n```\n\n\n```python\nprint(np.argmax(b)) # Index of largest element of b\n```\n\n\n```python\nprint(np.argmin(A,axis=0)) # Indices of smallest column elements \n```\n\n\n```python\nprint(np.identity(3)) # Identity matrix\n```\nThere are three functions in NumPy that compute matrix/vector products. They are illustrated by the program listed below. For more details, see Appendix A2 of the book.\n\n```python\nimport numpy as np\nx = np.array([7,3])\ny = np.array([2,1])\nA = np.array([[1,2],[3,2]])\nB = np.array([[1,1],[2,2]])\n\n# Dot product\nprint \"dot(x,y) =\\n\",np.dot(x,y) #{x}.{y} - scalar (dot) product of 2 vectors\nprint \"dot(A,x) =\\n\",np.dot(A,x) #[A]{x}  - maxtrix-vector dot product\nprint \"dot(A,B) =\\n\",np.dot(A,B) #[A][B]  - matrix-matrix dot product\n\n# Inner product\nprint \"inner(x,y) =\\n\",np.inner(x,y) # {x}.{y}\nprint \"inner(A,x) =\\n\",np.inner(A,x) # [A]{x}\nprint \"inner(A,B) =\\n\",np.inner(A,B) # [A][B_transpose]\n\n# Outer product\nprint \"outer(x,y) =\\n\",np.outer(x,y)\nprint \"outer(A,x) =\\n\",np.outer(A,x)\nprint \"Outer(A,B) =\\n\",np.outer(A,B)\n```\n\n## Exercises:\n\n1) Taking the y array from the previous exercise, find the values \nof its largest and smallest elements in each row.\n\n2) What do 'diagonal' and 'trace' give you if a 2D array is not with two equal dimensions?\n\n## Linear Algebra Module\nNumPy comes with a linear algebra module called 'linalg' that contains routine tasks such as matrix inversion and solution of simultaneous equations (which we will be discussing in more detail soon). For example:\n\n```python\nfrom numpy import array\nfrom numpy.linalg import inv,solve\n\nA = array([[ 4.0, -2.0, 1.0], \\\n[-2.0, 4.0, -2.0], \\\n[ 1.0, -2.0, 3.0]])\n\n# Note: The backslash '\\' above is Python's line continuation character. \n\nb = array([1.0, 4.0, 2.0])\n```\n\n\n```python\nprint(inv(A)) # Matrix inverse\n```\n\n\n```python\nprint(solve(A,b)) # Solve the system of equations [A]{x} = {b}\n```\n\n## Exercises:\n\n1) Set up the matrix \n\n\\begin{equation}\nA=[[1. 2. 3.]\\\\\n     [4. 5. 6.]\\\\\n     [7. 8. 1.]]\n\\end{equation}\n\nstarting with 'linspace' and then reshaping the array into a 3x3 one.\n\n2) Calculate the inverse of A. Check that $AA^{-1}=A^{-1}A=1$.\n\n3) Create a vector b=(6,15,16). Solve the equation Ax=b for x. Check your answer.\n\n## Copying Arrays\nWe explained before that if 'a' is a mutable object, such as a list, the assignment statement 'b = a' does not result in a new object b, but simply creates a new reference to 'a', called a deep copy. This also applies to arrays. To make an independent copy of an array a, use the copy method in the NumPy module:\n\n```python\nb = a.copy()\n```\n\n## Exercise: \n\nStarting from the array A from the previous exercise, create arrays\nB=A and C=A.copy(). Now change A[0,0] to 5 and print out both B and C. Did they change?\n\n## Vectorizing Algorithms\n\nSometimes the broadcasting properties of the mathematical functions in the NumPy module can be utilised to replace loops in the code. This procedure is known as vectorisation. Consider, for example, the sum:\n\n\\begin{equation}\ns=\\sum_{i=0}^{100}\\sqrt{\\frac{i\\pi}{100}}\\sin\\frac{i\\pi}{100}\n\\end{equation}\n\nThe direct approach is to evaluate the sum in a loop, resulting in the following \u201cscalar\u201d code:\n\n\n```python\nfrom math import sqrt,sin,pi\nx=0.0; sum = 0.0\nfor i in range(0,101):\n    sum = sum + sqrt(x)*sin(x)\n    x = x + 0.01*pi\nprint(sum)\n```\n\n    77.5138979892\n\nThe vectorised version of algorithm is:\n\n```python\nfrom numpy import sqrt,sin,arange,sum\nfrom math import pi\nx = arange(0.0,1.001*pi,0.01*pi)\nprint(sum(sqrt(x)*sin(x)))\n```\n\n    77.5138979892\n\nNote that the first algorithm uses the scalar versions of 'sqrt' and \n'sin' functions in the math module, whereas the second algorithm imports these functions from the NumPy. The vectorised algorithm is faster, so generally preferable, but uses more memory. Also, the code is more elegant, short and reabable.\n\nMathematical functions in Python without any 'if' tests automatically work for both scalar and array (vector) arguments (i.e., no vectorization by the programmer is necessary).\n## Exercises:\n1) Make a function which takes as an input a number 'n' and returns the sum of i^2*ln(i) for i=1 to n using a vectorized algorithm.\n\n2) How much faster is Numpy with vectorised operations compared to standard Python? Try the following two ways to add 1 to a million numbers, first is a standard implicit for loop, the second is a vectorized Numpy array operation:\n\nIn [1]: lst=range(1000000) \nIn [2]: %timeit [i+1 for i in lst]\nIn [3]: arr=arange(1000000) \nIn [4]: %timeit arr+1\n\nThe 'magic' command %timeit tests and reports how fast the statement execution is. How much faster is the vectorised Numpy one?\n\n3) The execution speed advantage is even better for standard Python \nfunctions vs. Numpy functions ('ufunc' in optimized, pre-compiled C-code). Try the following:\n\nIn [5]: %timeit [sin(i)**2 for i in arr]\nIn [6]: %timeit np.sin(arr)**2 \n\nHow much faster is the second one?\n\n```python\nlst=range(1000000)\n%timeit [i+1 for i in lst]\n```\n\n    10 loops, best of 3: 42.2 ms per loop\n\n\n\n```python\narr=arange(1000000) \n%timeit arr+1\n```\n\n    The slowest run took 5.21 times longer than the fastest. This could mean that an intermediate result is being cached.\n    1000 loops, best of 3: 1.28 ms per loop\n\n\n\n```python\n%timeit [sin(i)**2 for i in arr]\n%timeit np.sin(arr)**2\n```\n\n    1 loop, best of 3: 1.2 s per loop\n    10 loops, best of 3: 36.5 ms per loop\n\n\n## Scoping of Variables (An important point!)\n'Namespace' is a dictionary that contains the names of the variables and their values. The namespaces are automatically created and updated as a Python program runs. There are three levels of namespaces in Python:\n\n- Local namespace, which is created when a function is called. It contains the variables passed to the function as arguments and the variables created within the function. The namespace is deleted when the function terminates. If a variable is created inside a function, its scope is the function's local namespace. It is not visible outside the function.\n\n- A global namespace is created when a module is loaded. Each module has its own namespace. Variables assigned in a global namespace are visible to any function within the module.\n\n- Built-in namespace is created when the interpreter starts. It contains the functions that come with the Python interpreter. These functions can be accessed by any program unit.\n\nWhen a name is encountered during execution of a function, the Python interpreter tries to resolve it by searching the following in the order shown: \n(1) local namespace,\n(2) global namespace, \nand (3) built-in namespace. \n\nIf the name cannot be resolved, Python raises a 'NameError' exception (i.e. lets you know this variable does not exist).\n\nBecause the variables residing in a global namespace (i.e. not within a function) are visible to functions within the module, it is not necessary to pass them explicitly to the functions as arguments (although it is good programming practice to do so), as the following program illustrates:\n\n```python\ndef divide():\n    c = a/b\n    print 'a/b =',c\na = 100.0\nb = 5.0\ndivide()\n```\n\n    a/b = 20.0\n\nNote that the variable 'c' is created inside the function 'divide' and is thus not accessible to statements outside the function. Hence an attempt to move the print statement out of the function fails:\n\n```python\ndef divide():\n    c = a/b\na = 100.0\nb = 5.0\ndivide()\nprint 'a/b =',c\n```\n\n## Exercises:\nCreate a file called 'numpytest.py'. First define two vectors, \ncalled 'x' and 'y'. 'x' should be initialized to the vector \n\n(1, 5, -2, 6, 8, 10) \n\nand 'y' should be \n\n(-1, 0, 1, 1, 2, 3). \n\nCompute and store in a value 'a' the dot product of these two vectors. Store in a vector 'z1' a copy of 'x' but where every value less than zero has been replaced with zero (Hint: you can do this using slices, or the 'where' function). Store in a vector 'z2' all of the elements of 'x' that correspond to positions of 'y' that are strictly greater than zero. Finally, store in a vector 'z3' the sum of all values in 'y' that correspond to even elements of 'x'. (Hint: you can use modulus to get evenness: this is '%' in Python)\n# Visualising Data\nWork through the Entought Matplotlib slides (available on Study Direct) and then through the online tutorial at\n\nhttp://cs.smith.edu/dftwiki/index.php/MatPlotLib_Tutorial_1\n\n(there is a link on Study Direct). You can skip any repeated info.\n## Exercises:\n1) Plot a simple graph of a sine function in the range 0 to 3 with a \nstep size of 0.01. Make the line red. Add diamond-shaped markers with size of 5. Add a legend and a grid to the plot.\n\n2) Add to the previous plot a line showing the cosine of the same vector. Make the line blue and dashed, with circular markers. Change line color and thickness as well as the size and the kind of the marker. Experiment with different styles.\n\n3) Now draw a figure with two sub-plots on separate panels showing the\nsinus and cosine. Add labels and ticks only to the outermost axes. Place in one of these plots a smaller inset plot showing the exponent of 'x' over the same 'x' interval. Make sure the small plot does not overlap the lines on the larger plot. Use the pylab help and manual if needed.\n\n4) Using the 'random' module.\n\nimport random\na=random.random() # creates a random number between 0 and 1\n\nor 'randn(n)', create 2 random vectors 'x' and 'y', each of length 100. \nUsing the plot command make a scatter plot of 'x' vs. 'y' (hint just use \u2019bo\u2019 as the format).\n\n5) Do the same scatter plot but using the semilogx, semilogy, and loglog plots (check the help). These produce a plot where one or both axes use logscale. \n\n6) Go to \n\nhttp://matplotlib.sourceforge.net/gallery.html and \n\nhttp://www.scipy.org/Cookbook/Matplotlib \n\nand make a plot (or several) that you think looks interesting.\n\n```python\n\n\n```\n", "meta": {"hexsha": "287ac6fb5862847a9218cd90205d4ebbed52cfa0", "size": 54891, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ExamPrep/01 Intro to Python/__EXAMPLES 01 - Intro to Numpy, Scipy & Gradient.ipynb", "max_stars_repo_name": "FHomewood/ScientificComputing", "max_stars_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_stars_repo_licenses": ["IJG"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ExamPrep/01 Intro to Python/__EXAMPLES 01 - Intro to Numpy, Scipy & Gradient.ipynb", "max_issues_repo_name": "FHomewood/ScientificComputing", "max_issues_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_issues_repo_licenses": ["IJG"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ExamPrep/01 Intro to Python/__EXAMPLES 01 - Intro to Numpy, Scipy & Gradient.ipynb", "max_forks_repo_name": "FHomewood/ScientificComputing", "max_forks_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_forks_repo_licenses": ["IJG"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0, "max_line_length": 698, "alphanum_fraction": 0.5013754532, "converted": true, "num_tokens": 9351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08756384904745383, "lm_q2_score": 0.16885695632426875, "lm_q1q2_score": 0.014785765034190775}}
{"text": "```python\n!pip install qiskit\n```\n\n    Requirement already satisfied: qiskit in /usr/local/lib/python3.6/dist-packages (0.19.6)\n    Requirement already satisfied: qiskit-aqua==0.7.3 in /usr/local/lib/python3.6/dist-packages (from qiskit) (0.7.3)\n    Requirement already satisfied: qiskit-terra==0.14.2 in /usr/local/lib/python3.6/dist-packages (from qiskit) (0.14.2)\n    Requirement already satisfied: qiskit-aer==0.5.2 in /usr/local/lib/python3.6/dist-packages (from qiskit) (0.5.2)\n    Requirement already satisfied: qiskit-ibmq-provider==0.7.2 in /usr/local/lib/python3.6/dist-packages (from qiskit) (0.7.2)\n    Requirement already satisfied: qiskit-ignis==0.3.3 in /usr/local/lib/python3.6/dist-packages (from qiskit) (0.3.3)\n    Requirement already satisfied: docplex in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit) (2.15.194)\n    Requirement already satisfied: scikit-learn>=0.20.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit) (0.22.2.post1)\n    Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit) (1.18.5)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit) (1.6.1)\n    Requirement already satisfied: quandl in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit) (3.5.2)\n    Requirement already satisfied: pyscf; sys_platform != \"win32\" in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit) (1.7.4)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit) (49.2.0)\n    Requirement already satisfied: scipy>=1.4 in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit) (1.4.1)\n    Requirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit) (2.10.0)\n    Requirement already satisfied: dlx in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit) (1.0.4)\n    Requirement already satisfied: fastdtw in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit) (0.3.4)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit) (5.4.8)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit) (2.4)\n    Requirement already satisfied: marshmallow<4,>=3 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (3.7.1)\n    Requirement already satisfied: fastjsonschema>=2.10 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (2.14.4)\n    Requirement already satisfied: python-constraint>=1.4 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (1.4.0)\n    Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (2.6.0)\n    Requirement already satisfied: retworkx>=0.3.2 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (0.4.0)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (2.8.1)\n    Requirement already satisfied: ply>=3.10 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (3.11)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (0.3.2)\n    Requirement already satisfied: marshmallow-polyfield<6,>=5.7 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (5.9)\n    Requirement already satisfied: pybind11>=2.4 in /usr/local/lib/python3.6/dist-packages (from qiskit-aer==0.5.2->qiskit) (2.5.0)\n    Requirement already satisfied: cython>=0.27.1 in /usr/local/lib/python3.6/dist-packages (from qiskit-aer==0.5.2->qiskit) (0.29.21)\n    Requirement already satisfied: nest-asyncio!=1.1.0,>=1.0.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit) (1.4.0)\n    Requirement already satisfied: websockets<8,>=7 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit) (7.0)\n    Requirement already satisfied: requests-ntlm>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit) (1.1.0)\n    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit) (1.24.3)\n    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit) (2.23.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from docplex->qiskit-aqua==0.7.3->qiskit) (1.15.0)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.7.3->qiskit) (0.16.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy>=1.3->qiskit-aqua==0.7.3->qiskit) (1.1.0)\n    Requirement already satisfied: pandas>=0.14 in /usr/local/lib/python3.6/dist-packages (from quandl->qiskit-aqua==0.7.3->qiskit) (1.0.5)\n    Requirement already satisfied: more-itertools in /usr/local/lib/python3.6/dist-packages (from quandl->qiskit-aqua==0.7.3->qiskit) (8.4.0)\n    Requirement already satisfied: inflection>=0.3.1 in /usr/local/lib/python3.6/dist-packages (from quandl->qiskit-aqua==0.7.3->qiskit) (0.5.0)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx>=2.2->qiskit-aqua==0.7.3->qiskit) (4.4.2)\n    Requirement already satisfied: cryptography>=1.3 in /usr/local/lib/python3.6/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit) (3.0)\n    Requirement already satisfied: ntlm-auth>=1.0.2 in /usr/local/lib/python3.6/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit) (1.5.0)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.7.2->qiskit) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.7.2->qiskit) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.7.2->qiskit) (2020.6.20)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.14->quandl->qiskit-aqua==0.7.3->qiskit) (2018.9)\n    Requirement already satisfied: cffi!=1.11.3,>=1.8 in /usr/local/lib/python3.6/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit) (1.14.1)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.6/dist-packages (from cffi!=1.11.3,>=1.8->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit) (2.20)\n\n\n\n```python\nfrom qiskit import BasicAer, Aer, IBMQ\nfrom qiskit.aqua import QuantumInstance, aqua_globals\nfrom qiskit.aqua.algorithms import VQE, ExactEigensolver\nfrom qiskit.aqua.components.initial_states import Zero\nfrom qiskit.aqua.components.optimizers import COBYLA, L_BFGS_B, SLSQP, SPSA\nfrom qiskit.aqua.components.variational_forms import RY, RYRZ, SwapRZ\nfrom qiskit.circuit.library import EfficientSU2\nfrom qiskit.aqua.operators import WeightedPauliOperator, Z2Symmetries\nfrom qiskit.chemistry import FermionicOperator\nfrom qiskit.chemistry.drivers import PySCFDriver, UnitsType\nfrom qiskit.chemistry.components.variational_forms import UCCSD\nfrom qiskit.chemistry.components.initial_states import HartreeFock\n\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.providers.aer.noise import NoiseModel\nfrom qiskit.ignis.mitigation.measurement import CompleteMeasFitter\nfrom qiskit.providers.aer.noise.errors import QuantumError, ReadoutError\nfrom qiskit.providers.aer.noise.errors import pauli_error\nfrom qiskit.providers.aer.noise.errors import depolarizing_error\nfrom qiskit.providers.aer.noise.errors import thermal_relaxation_error\n\nfrom qiskit.providers.aer import noise\nIBMQ.save_account('f5ac861d9299009bb9420b5feff6abc90cbdfd8f8e38789005db20855c142db3a864799f73d25bb1b5ec6acdaebce19d24fafcbaa9e7d929fc763633ad279747')\nprovider = IBMQ.load_account()\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom functools import partial\nimport pandas as pd\nimport json\nfrom matplotlib import pyplot as plt\n\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    configrc.store_credentials:WARNING:2020-08-07 08:50:13,911: Credentials already present. Set overwrite=True to overwrite.\n\n\n\n```python\ndef save_result(file_name, result):\n  dir = '/content/drive/My Drive/Projects/Qiskit Global Summer School/'\n  with open(dir + file_name, 'w') as f:\n      f.write(json.dumps(result))\n\ndef load_result(file_name):\n  # Now read the file back into a Python list object\n  dir = '/content/drive/My Drive/Projects/Qiskit Global Summer School/'\n  with open(dir + file_name, 'r') as f:\n      a = json.loads(f.read())\n  \n  return a\n```\n\n# Qiskit Summer School Final Project: VQE\n\n#### For this optional final challenge, you will be designing your own implementation of a variational quantum eigensolver (VQE) algorithm that simulates the ground state energy of the Lithium Hydride (LiH) molecule. Through out this challenge, you will be able to make choices on how you want to compose your simulation and what is the final deliverable that you want to showcase to your classmates and friends.\n\n# Defining your molecule:\nIn this challenge we will focus on LiH using the sto3g basis with the PySCF driver, which can be described in Qiskit as follows, where 'inter_dist' is the interatomic distance.\n\n\n```python\ninter_dist = 1.6\n\ndriver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g')\n```\n\nWe also setup the molecular orbitals to be considered and can reduce the problem size when we map to the qubit Hamiltonian so the amount of time required for the simulations are reasonable for a laptop computer.\n\n\n```python\n# please be aware that the idx here with respective to original idx\nfreeze_list = [0]\nremove_list = [-3, -2] # negative number denotes the reverse order\n```\n\n#### Once you have computed the qubit operations for LiH, you can use the following function to classical solve for the exact solution. This is used just to compare how well your VQE approximation is performing.\n\n\n```python\n#Classically solve for the lowest eigenvalue\ndef exact_solver(qubitOp):\n    ee = ExactEigensolver(qubitOp)\n    result = ee.run()\n    ref = result['energy']\n    print('Reference value: {}'.format(ref))\n    return ref\n```\n\nHere we ask you to use the `statevector_simulator` as the simulation backend for your VQE algorithm.\n\n\n```python\nbackend = BasicAer.get_backend('statevector_simulator')\n```\n\n### Now you can start choosing the components that make up your VQE algorithm!\n\n#### 1. Optimizers\nThe most commonly used optimizers are `COBYLA`, `L_BFGS_B`, `SLSQP` and `SPSA`. \n\n#### 2. Qubit mapping\nThere are several different mappings for your qubit Hamiltonian, `parity`, `bravyi_kitaev`, `jordan_wigner`, which in some cases can allow you to further reduce the problem size.\n\n#### 3. Initial state\nThere are different initial state that you can choose to start your simulation. Typically people choose from the zero state \n`init_state = Zero(qubitOp.num_qubits)` \nand the UCCSD initial state\n`HartreeFock(qubitOp.num_qubits, num_spin_orbitals, num_particles, map_type, qubit_reduction)`\n\n#### 4. Parameterized circuit\nThere are different choices you can make on the form of variational forms of your parameterized circuit.\n\n`UCCSD_var_form = UCCSD(num_qubits, depth=depth, num_orbitals=num_spin_orbitals, num_particles=num_particles)`\n    \n`RY_var_form = RY(num_qubits, depth=depth)`\n    \n`RYRZ_var_form = RYRZ(num_qubits, depth=depth)`\n    \n`swaprz_var_form = SwapRZ(num_qubits, depth=depth)`\n\n#### 5. Simulation backend\nThere are different simulation backends that you can use to perform your simulation\n\n`backend = BasicAer.get_backend('statevector_simulator')`\n\n`backend=Aer.get_backend('qasm_simulator')`\n\n### Compare the convergence of different choices for building your VQE algorithm\n\nAmong the above choices, which combination do you think would out perform others and give you the lowest estimation of LiH ground state energy with the quickest convergence? Compare the results of different combinations against each other and against the classically computed exact solution at a fixed interatomic distance, for example `inter_dist=1.6`. \n\nTo access the intermediate data during the optimization, you would need to utilize the `callback` option in the VQE function:\n\n`def store_intermediate_result(eval_count, parameters, mean, std):\n            counts.append(eval_count)\n            values.append(mean)\n            params.append(parameters)\n            deviation.append(std)`\n            \n`algo = VQE(qubitOp, var_form, optimizer, callback=store_intermediate_result)`\n\n`algo_result = algo.run(quantum_instance)`\n\nAn example of comparing the performance of different optimizers while using the RY variational ansatz could like the following:\n\n\n\n### Compute the ground state energy of LiH at various different interatomic distances\nBy changing the parameter `inter_dist`, you can use your VQE algorithm to calculate the ground state energy of LiH at various interatomic distances, and potentially produce a plot as you are seeing here. Note that the VQE results are very close to the exact results, and so the exact energy curve is hidden by the VQE curve.\n\n\n### How does your VQE algorithm perform in the presence of noise?\nTrying importing the noise model and qubit coupling map of a real IBM quantum device into your simulation. You can use the imported noise model in your simulation by passing it into your quantum instance. You can also try enabling error mitigation in order to lower the effect of noise on your simulation results.\n\n\n```python\n#Define our noise model based on the ibmq_essex chip\nchip_name = 'ibmq_essex'\ndevice = provider.get_backend(chip_name)\ncoupling_map = device.configuration().coupling_map\nnoise_model = noise.device.basic_device_noise_model(device.properties())\nbasis_gates = noise_model.basis_gates\n```\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\nAn example of comparing the energy convergence of using SPSA and COBYLA with the ibmq_essex noise model could look like the following\n\n\n### Now given the choices you have made above, try writing your own VQE algorithm in Qiskit. You can find an example of using Qiskit to simuate molecules with VQE [here](https://qiskit.org/textbook/ch-applications/vqe-molecules.html).\n\n\n```python\n# Classically solve for the lowest eigenvalue\n# This is used just to compare how well you VQE approximation is performing\ndef exact_solver(qubitOp):\n    ee = ExactEigensolver(qubitOp)\n    result = ee.run()\n    ref = result['energy']\n    #print('Reference value: {}'.format(ref))\n    return ref\n\n# Define your function for computing the qubit operations of LiH\ndef compute_LiH_qubitOp(map_type, inter_dist, basis='sto3g'):\n    \n    # Specify details of our molecule\n    driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 ' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis=basis)\n\n    # Compute relevant 1 and 2 body integrals.\n    molecule = driver.run()\n    h1 = molecule.one_body_integrals\n    h2 = molecule.two_body_integrals\n    nuclear_repulsion_energy = molecule.nuclear_repulsion_energy\n    \n    num_particles = molecule.num_alpha + molecule.num_beta\n    num_spin_orbitals = molecule.num_orbitals * 2\n    #print(\"HF energy: {}\".format(molecule.hf_energy - molecule.nuclear_repulsion_energy))\n    #print(\"# of electrons: {}\".format(num_particles))\n    #print(\"# of spin orbitals: {}\".format(num_spin_orbitals))\n\n    # Please be aware that the idx here with respective to original idx\n    freeze_list = [0]\n    remove_list = [-3, -2] # negative number denotes the reverse order\n    \n    # Prepare full idx of freeze_list and remove_list\n    # Convert all negative idx to positive\n    remove_list = [x % molecule.num_orbitals for x in remove_list]\n    freeze_list = [x % molecule.num_orbitals for x in freeze_list]\n    \n    # Update the idx in remove_list of the idx after frozen, since the idx of orbitals are changed after freezing\n    remove_list = [x - len(freeze_list) for x in remove_list]\n    remove_list += [x + molecule.num_orbitals - len(freeze_list)  for x in remove_list]\n    freeze_list += [x + molecule.num_orbitals for x in freeze_list]\n\n    # Prepare fermionic hamiltonian with orbital freezing and eliminating, and then map to qubit hamiltonian\n    # and if PARITY mapping is selected, reduction qubits\n    energy_shift = 0.0\n    qubit_reduction = True if map_type == 'parity' else False\n\n    ferOp = FermionicOperator(h1=h1, h2=h2)\n    if len(freeze_list) > 0:\n        ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list)\n        num_spin_orbitals -= len(freeze_list)\n        num_particles -= len(freeze_list)\n    if len(remove_list) > 0:\n        ferOp = ferOp.fermion_mode_elimination(remove_list)\n        num_spin_orbitals -= len(remove_list)\n\n    qubitOp = ferOp.mapping(map_type=map_type)\n    qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) if qubit_reduction else qubitOp\n    qubitOp.chop(10**-10)\n\n    return qubitOp, num_spin_orbitals, num_particles, qubit_reduction, energy_shift, nuclear_repulsion_energy\n\n\ndef test_run(mapping_type, inter_distance, backend_type, init_type, use_noise, optimizer_type, param_type):\n    qubitOp, num_spin_orbitals, num_particles, qubit_reduction = compute_LiH_qubitOp(map_type=mapping_type, inter_dist=inter_distance)\n    print(\"Orbitals: \", num_spin_orbitals)\n    print(\"Particles: \", num_particles)\n    # Classically solve for the exact solution and use that as your reference value\n    ref = exact_solver(qubitOp)\n\n    # Specify your initial state\n    if init_type == 'HF':\n      init_state = HartreeFock(num_orbitals=num_spin_orbitals, num_particles=num_particles, qubit_mapping=mapping_type, two_qubit_reduction=True)\n    elif init_type == 'Zero':\n      init_state = Zero(qubitOp.num_qubits)\n    elif init_type == 'None':\n      init_state = None\n\n    # Select a state preparation ansatz\n    # Equivalently, choose a parameterization for our trial wave function.\n    if param_type == 'UCCSD':\n      var_form = UCCSD(num_orbitals=num_spin_orbitals, num_particles=num_particles, qubit_mapping=mapping_type,\n                            initial_state=init_state, two_qubit_reduction=True)\n    elif param_type == 'RY':\n      var_form = RY(num_qubits=qubitOp.num_qubits, entanglement=\"linear\", initial_state=init_state, depth=1)\n    elif param_type == 'RYRZ':\n      var_form = RYRZ(num_qubits=qubitOp.num_qubits, entanglement=\"linear\", initial_state=init_state)\n    elif param_type == 'SwapRZ':\n      var_form = SwapRZ(num_qubits=qubitOp.num_qubits, entanglement=\"linear\", initial_state=init_state)\n    elif param_type == 'ESU2':\n      var_form = EfficientSU2(qubitOp.num_qubits, entanglement=\"linear\", initial_state=init_state)\n\n\n    # Choose where to run/simulate our circuit\n    if backend_type == 'qasm': \n      backend = Aer.get_backend('qasm_simulator')\n    elif backend_type == 'statevector':\n      backend = BasicAer.get_backend('statevector_simulator')\n\n    # Choose whether to use noise or not\n    if use_noise == False:\n      quantum_instance = backend\n    elif use_noise == True:\n      backend = Aer.get_backend('qasm_simulator')\n      #Define our noise model based on the ibmq_essex chip\n      chip_name = 'ibmq_essex'\n      device = provider.get_backend(chip_name)\n      coupling_map = device.configuration().coupling_map\n      noise_model = noise.device.basic_device_noise_model(device.properties())\n      basis_gates = noise_model.basis_gates\n      quantum_instance = QuantumInstance(backend=backend, \n                                   shots=1000, \n                                   noise_model=noise_model, \n                                   coupling_map=coupling_map,\n                                   basis_gates=basis_gates,\n                                   measurement_error_mitigation_cls=CompleteMeasFitter,\n                                   cals_matrix_refresh_period=30)\n      # measurement_error_mitigation_cls=CompleteMeasFitter\n      # cals_matrix_refresh_period=30\n\n    # Choose the classical optimizer\n    if optimizer_type == 'COBYLA':\n      optimizer = COBYLA(maxiter=100)\n    elif optimizer_type == 'L_BFGS_B':\n      optimizer = L_BFGS_B(maxfun=100, maxiter=1500)\n    elif optimizer_type == 'SLSQP':\n      optimizer = SLSQP(maxiter=100)\n    elif optimizer_type == 'SPSA':\n      optimizer = SPSA(max_trials=100)\n\n    # Run your VQE instance\n    vqe = VQE(qubitOp, var_form, optimizer)\n    # Now compare the results of different compositions of your VQE algorithm!\n    ret = vqe.run(quantum_instance)\n    vqe_result = np.real(ret['eigenvalue'])\n    return abs(vqe_result - ref)\n    #print(\"VQE Result:\", vqe_result)\n\n\nmapping_list = ['parity', 'bravyi_kitaev', 'jordan_wigner']\ninit_state_list = ['HF', 'Zero']\nbackend_list = ['statevector', 'qasm']\noptimizer_list = ['COBYLA', 'L_BFGS_B', 'SLSQP', 'SPSA']\nparam_list = ['UCCSD', 'RY', 'RYRZ', 'SwapRZ']\n\n```\n\n\n```python\ndef store_intermediate_result(eval_count, parameters, mean, std):\n            counts.append(eval_count)\n            values.append(mean)\n            #params.append(parameters)\n            deviation.append(std)\n```\n\n\n```python\n\n```\n\n\n```python\na = np.array([[0, 0, 0], [0,0,0]])\nb = [1, 2, 3]\n\na[0,:] = np.array(b)\na\n```\n\n\n\n\n    array([[1, 2, 3],\n           [0, 0, 0]])\n\n\n\n\n```python\ndef convergence_test(mapping_type, optimizer_type, inter_distance):\n  qubitOp, num_spin_orbitals, num_particles, qubit_reduction = compute_LiH_qubitOp(map_type=mapping_type, inter_dist=inter_distance)\n  print(\"Orbitals: \", num_spin_orbitals)\n  print(\"Particles: \", num_particles)\n  # Classically solve for the exact solution and use that as your reference value\n  ref = exact_solver(qubitOp)\n\n  # Specify your initial state\n  init_state = HartreeFock(num_orbitals=num_spin_orbitals, num_particles=num_particles, qubit_mapping=mapping_type, two_qubit_reduction=True)\n\n\n  # Select a state preparation ansatz\n  # Equivalently, choose a parameterization for our trial wave function.\n  var_form = RY(num_qubits=qubitOp.num_qubits, entanglement=\"linear\", initial_state=init_state)\n\n  backend = Aer.get_backend('qasm_simulator')\n  #Define our noise model based on the ibmq_essex chip\n  chip_name = 'ibmq_essex'\n  device = provider.get_backend(chip_name)\n  coupling_map = device.configuration().coupling_map\n  noise_model = noise.device.basic_device_noise_model(device.properties())\n  basis_gates = noise_model.basis_gates\n  quantum_instance = QuantumInstance(backend=backend, \n                                shots=1000, \n                                noise_model=noise_model, \n                                coupling_map=coupling_map,\n                                basis_gates=basis_gates,\n                                measurement_error_mitigation_cls=CompleteMeasFitter,\n                                cals_matrix_refresh_period=30)\n\n  # Choose the classical optimizer\n  if optimizer_type == 'COBYLA':\n    optimizer = COBYLA(maxiter=100)\n  elif optimizer_type == 'SPSA':\n    optimizer = SPSA(max_trials=100)\n\n  # Run your VQE instance\n  vqe = VQE(qubitOp, var_form, optimizer, callback=store_intermediate_result)\n  # Now compare the results of different compositions of your VQE algorithm!\n  ret = vqe.run(quantum_instance)\n  vqe_result = np.real(ret['eigenvalue'])\n  err = abs(vqe_result - ref)\n  #print(\"Abs error: \", err)\n\n\n\nmapping_type = 'parity'\noptimizer_type = 'COBYLA'\n#inter_distance = 1.6\n\ndist_list = [0.25, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]\n\nvalues_all = np.zeros((len(dist_list), 100))\ncounts_all = np.zeros((len(dist_list), 100))\ndeviation_all = np.zeros((len(dist_list), 100))\n\nfor i in range (len(dist_list)):\n  counts = []\n  values = []\n  deviation = []\n  convergence_test(mapping_type, optimizer_type, dist_list[i])\n  counts_all[i,:] = np.array(counts)\n  values_all[i,:] = np.array(values)\n  deviation_all[i,:] = np.array(deviation)\n```\n\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:14: DeprecationWarning: The qiskit.aqua.components.variational_forms.RY object is deprecated as of 0.7.0 and will be removed no sooner than 3 months after the release. You should use qiskit.circuit.library.RealAmplitudes (uses CX entangling) or qiskit.circuit.library.TwoLocal instead.\n      \n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n\n```python\ncobyla_counts = counts\ncobyla_values = values\ncobyla_deviation = deviation\ncobyla_params = params\n```\n\n\n```python\nspsa_counts = counts\nspsa_values = values\nspsa_deviation = deviation\nspsa_params = params\n```\n\n\n```python\ncolor_list = ['red', 'blue', 'green', 'purple', 'black', 'yellow', 'brown']\n\nfor i in range (len(dist_list)):\n  plt.errorbar(counts_all[i,:], values_all[i,:], deviation_all[i,:], linestyle='--', marker='o', color=color_list[i], label='distance = ' + str(dist_list[i]))\n\nplt.title('COBYLA Optimizer at Several Distance (convergence is achieved after 40-50 iterations for all distances)')\nplt.xlabel('Iterations')\nplt.ylabel('Evaluated Mean')\nplt.legend()\n```\n\n\n```python\nfig_size = plt.rcParams[\"figure.figsize\"]\nfig_size[0] = 20\nfig_size[1] = 8\nplt.rcParams[\"figure.figsize\"] = fig_size\n\nplt.errorbar(cobyla_counts, cobyla_values, cobyla_deviation, linestyle='None', marker='o', color='red', label='Optimizer: COBYLA (converge faster)')\nplt.errorbar(spsa_counts, spsa_values, spsa_deviation, linestyle='None', marker='o', color='blue', label='Optimizer: SPSA')\nplt.title('Optimizer Convergence at distance = 1.6')\nplt.xlabel('Iterations')\nplt.ylabel('Evaluated Mean')\nplt.legend()\n```\n\n\n```python\ndef depth_test(mapping_type, inter_distance, num_depth):\n  qubitOp, num_spin_orbitals, num_particles, qubit_reduction, eshift, erepulsion = compute_LiH_qubitOp(map_type=mapping_type, inter_dist=inter_distance)\n  print(\"Orbitals: \", num_spin_orbitals)\n  print(\"Particles: \", num_particles)\n  # Classically solve for the exact solution and use that as your reference value\n  #ref = exact_solver(qubitOp)\n\n  # Specify your initial state\n  init_state = HartreeFock(num_orbitals=num_spin_orbitals, num_particles=num_particles, qubit_mapping=mapping_type, two_qubit_reduction=True)\n\n\n  # Select a state preparation ansatz\n  # Equivalently, choose a parameterization for our trial wave function.\n  var_form = RY(num_qubits=qubitOp.num_qubits, entanglement=\"linear\", initial_state=init_state, depth=num_depth)\n\n  backend = Aer.get_backend('qasm_simulator')\n  #Define our noise model based on the ibmq_essex chip\n  chip_name = 'ibmq_essex'\n  device = provider.get_backend(chip_name)\n  coupling_map = device.configuration().coupling_map\n  noise_model = noise.device.basic_device_noise_model(device.properties())\n  basis_gates = noise_model.basis_gates\n  quantum_instance = QuantumInstance(backend=backend, \n                                shots=1000, \n                                noise_model=noise_model, \n                                coupling_map=coupling_map,\n                                basis_gates=basis_gates,\n                                measurement_error_mitigation_cls=CompleteMeasFitter,\n                                cals_matrix_refresh_period=30)\n\n  # Choose the classical optimizer\n  optimizer = COBYLA(maxiter=50)\n\n  # Run your VQE instance\n  vqe = VQE(qubitOp, var_form, optimizer)\n  # Now compare the results of different compositions of your VQE algorithm!\n  ret = vqe.run(quantum_instance)\n  vqe_result = np.real(ret['eigenvalue'])\n  #err = abs(vqe_result - ref)\n  return (vqe_result+eshift+erepulsion)\n  #print(\"Abs error: \", err)\n\n\n\n```\n\n\n```python\n\n```\n\n\n```python\nmapping_type = 'parity'\n\ndepth_list = [1, 3, 5, 7]\ndist_list = np.linspace(0.5, 3.0, 21)\n\nref_all = np.zeros((len(depth_list), len(dist_list)))\nvqe_all = np.zeros((len(depth_list), len(dist_list)))\n```\n\n\n```python\nnum_depth = 7\nrow = 3\n\nfor i in range (len(dist_list)):\n  result = depth_test(mapping_type, dist_list[i], num_depth)\n  #ref_all[row, i] = ref\n  vqe_all[row, i] = result\n  np.savetxt('/content/drive/My Drive/Projects/Qiskit Global Summer School/vqe_result.txt', vqe_all, delimiter=',')\n  #np.savetxt('/content/drive/My Drive/Projects/Qiskit Global Summer School/ref_result.txt', ref_all, delimiter=',')\n  print(\"Dist: \" + str(dist_list[i]))\n```\n\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:14: DeprecationWarning: The qiskit.aqua.components.variational_forms.RY object is deprecated as of 0.7.0 and will be removed no sooner than 3 months after the release. You should use qiskit.circuit.library.RealAmplitudes (uses CX entangling) or qiskit.circuit.library.TwoLocal instead.\n      \n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Dist: 0.5\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Dist: 0.625\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Dist: 0.75\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Dist: 0.875\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Dist: 1.0\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Dist: 1.125\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Dist: 1.25\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Dist: 1.375\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Dist: 1.5\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Dist: 1.625\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Dist: 1.75\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Dist: 1.875\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Dist: 2.0\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Dist: 2.125\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Dist: 2.25\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Dist: 2.375\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Dist: 2.5\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Dist: 2.625\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Dist: 2.75\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Dist: 2.875\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Dist: 3.0\n\n\n\n```python\nrow = 0\nfor i in range (len(dist_list)):\n  qubitOp, num_spin_orbitals, num_particles, qubit_reduction, eshift, erepulsion = compute_LiH_qubitOp(map_type=mapping_type, inter_dist=dist_list[i])\n  ref_all[row, i] += (eshift + erepulsion)\n  vqe_all[row, i] += (eshift + erepulsion)\n#print(eshift, erepulsion)\n```\n\n\n```python\n# exact ground state energy\nref_all[0, 8]\n\nabs(mitigated[8]-ref_all[0,8])\n```\n\n\n\n\n    0.08299790574912791\n\n\n\n\n```python\nabs(mitigated[8]-ref_all[0,8])\n```\n\n\n\n\n    0.10535326942107837\n\n\n\n\n```python\nabs(mitigated[8]-ref_all[0,8])\n```\n\n\n\n\n    0.079875254569302\n\n\n\n\n```python\nimport numpy as np\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as plt    \nfrom scipy import stats\nimport pandas as pd\n\n```\n\n\n```python\ndef f(x, a, b):\n    return a*x+b\n```\n\n\n```python\ndepth_list\n```\n\n\n\n\n    [1, 3, 5, 7]\n\n\n\n\n```python\nmitigated = []\nx = np.array([1,3,5,7])\n\nfor i in range(len(dist_list)):\n  y = vqe_all[:, i]\n  popt, pcov = curve_fit(f, x, y)\n  a = popt[0]\n  b = popt[1]\n  mitigated += [0*a + b]\n\nprint(mitigated)\n```\n\n    [-7.021693683230664, -7.364577322242834, -7.515051463191542, -7.551911882741015, -7.64535894060298, -7.647143632260589, -7.69675616429133, -7.698061016408282, -7.801140461077689, -7.720986907320649, -7.652210124480563, -7.808397749894985, -7.812895556518121, -7.7307724718120525, -7.756228724096971, -7.721460812761698, -7.779380588373893, -7.712305309973512, -7.702830702457899, -7.79169716248623, -7.757845703658691]\n\n\n\n```python\n\n```\n\n\n```python\nplt.plot(dist_list, ref_all[0,:], color='blue', linestyle='-', label='Exact')\n\nplt.plot(dist_list, vqe_all[0,:], color='yellow', linestyle='-', label='VQE, RY depth = 1')\nplt.plot(dist_list, vqe_all[1,:], color='cyan', linestyle='-', label='VQE, RY depth = 3')\nplt.plot(dist_list, vqe_all[2,:], color='green', linestyle='-', label='VQE, RY depth = 5')\nplt.plot(dist_list, vqe_all[3,:], color='purple', linestyle='-', label='VQE, RY depth = 7')\n\nplt.plot(dist_list, mitigated, color='red', linestyle='-', label='VQE + error mitigation by simple extrapolation')\n\nplt.title('LiH Ground State Energy Simulation')\nplt.xlabel('Interatomic Distance (\u00c5)')\nplt.ylabel('Energy (Hartree)')\nplt.legend()\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\nnp.linspace(0.5, 3.0, 21)\n```\n\n\n\n\n    array([0.5  , 0.625, 0.75 , 0.875, 1.   , 1.125, 1.25 , 1.375, 1.5  ,\n           1.625, 1.75 , 1.875, 2.   , 2.125, 2.25 , 2.375, 2.5  , 2.625,\n           2.75 , 2.875, 3.   ])\n\n\n\n\n```python\nmapping_list = ['parity']\nbackend_list = ['qasm']\n\ninit_state_list = ['HF']\noptimizer_list = ['COBYLA', 'SPSA']\nparam_list = ['RY']\n\nscore_noisefree = np.zeros((len(mapping_list)*len(init_state_list)*len(backend_list)*len(optimizer_list)*len(param_list), 6)).tolist()\n\n\ninter_distance = 1.6\nuse_noise=True\n\ncount = 0\nfor i in range (len(backend_list)):\n  for j in range (len(mapping_list)):\n    for k in range (len(init_state_list)):\n      for l in range (len(optimizer_list)):\n        for m in range (len(param_list)):\n          score_noisefree[count][0] = backend_list[i]\n          score_noisefree[count][1] = mapping_list[j]\n          score_noisefree[count][2] = init_state_list[k]\n          score_noisefree[count][3] = optimizer_list[l]\n          score_noisefree[count][4] = param_list[m]\n          backend_type = backend_list[i]\n          mapping_type = mapping_list[j]\n          init_type = init_state_list[k]\n          optimizer_type = optimizer_list[l]\n          param_type = param_list[m]\n          err = test_run(mapping_type, inter_distance, backend_type, init_type, use_noise, optimizer_type, param_type)\n          score_noisefree[count][5] = err\n          count += 1\n          save_result('final_result_noisy3.txt', score_noisefree)\n          print(\"Run \" + str(count) + \": absolute error = \", err)\n\n```\n\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:84: DeprecationWarning: The qiskit.aqua.components.variational_forms.RY object is deprecated as of 0.7.0 and will be removed no sooner than 3 months after the release. You should use qiskit.circuit.library.RealAmplitudes (uses CX entangling) or qiskit.circuit.library.TwoLocal instead.\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Run 1: absolute error =  0.10855486980475482\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n    Run 2: absolute error =  0.080856189554532\n\n\n\n```python\n\n```\n\n\n```python\n0.7650321937608426\n0.8486693939154499\n```\n\n\n```python\n(0.28978775069959495+0.18632168429111617)/2\n```\n\n\n\n\n    0.23805471749535556\n\n\n\n\n```python\nscore_noisefree\n```\n\n\n\n\n    [['qasm', 'parity', 'HF', 'COBYLA', 'RY', 0.10855486980475482],\n     ['qasm', 'parity', 'HF', 'SPSA', 'RY', 0.080856189554532]]\n\n\n\n\n```python\nscore_noisefree\n```\n\n\n\n\n    [['qasm', 'parity', 'None', 'COBYLA', 'RY', 0.3385762324195435],\n     ['qasm', 'parity', 'None', 'SPSA', 'RY', 0.28978775069959495],\n     ['qasm', 'parity', 'HF', 'COBYLA', 'RY', 0.26098983910167617],\n     ['qasm', 'parity', 'HF', 'SPSA', 'RY', 0.2536178720377411]]\n\n\n\n\n```python\nscore_noisefree\n```\n\n\n\n\n    [['qasm', 'parity', 'None', 'COBYLA', 'RY', 0.22365134210926674],\n     ['qasm', 'parity', 'None', 'SPSA', 'RY', 0.18632168429111617],\n     ['qasm', 'parity', 'HF', 'COBYLA', 'RY', 0.2786371668742237],\n     ['qasm', 'parity', 'HF', 'SPSA', 'RY', 0.2852095435236244]]\n\n\n\n\n```python\nscore_noisefree\n```\n\n\n\n\n    [['qasm', 'parity', 'None', 'COBYLA', 'ESU2', 0.6017880033637941],\n     ['qasm', 'parity', 'None', 'COBYLA', 'RY', 0.29940355507681604],\n     ['qasm', 'parity', 'None', 'SPSA', 'ESU2', 0.4279723005209324],\n     ['qasm', 'parity', 'None', 'SPSA', 'RY', 0.36287466634206145],\n     ['qasm', 'parity', 'Zero', 'COBYLA', 'ESU2', 0.5940588850601642],\n     ['qasm', 'parity', 'Zero', 'COBYLA', 'RY', 0.4197398089954736],\n     ['qasm', 'parity', 'Zero', 'SPSA', 'ESU2', 0.3455366683455622],\n     ['qasm', 'parity', 'Zero', 'SPSA', 'RY', 0.4068271182601426],\n     ['qasm', 'parity', 'HF', 'COBYLA', 'ESU2', 0.3787801978321236],\n     ['qasm', 'parity', 'HF', 'COBYLA', 'RY', 0.2875017011823],\n     ['qasm', 'parity', 'HF', 'SPSA', 'ESU2', 0.3775065514270264],\n     ['qasm', 'parity', 'HF', 'SPSA', 'RY', 0.3021503647689735]]\n\n\n\n\n```python\n['qasm', 'parity', 'HF', 'COBYLA', 'RY', 0.2875017011823]\n['qasm', 'parity', 'HF', 'SPSA', 'RY', 0.3021503647689735]\n\n['qasm', 'parity', 'None', 'COBYLA', 'RY', 0.29940355507681604]\n['qasm', 'parity', 'None', 'SPSA', 'RY', 0.36287466634206145]\n\n['qasm', 'parity', 'Zero', 'SPSA', 'ESU2', 0.3455366683455622]\n```\n\n\n```python\nbackend_type = 'qasm'\nmapping_type = 'parity'\noptimizer_type = 'SPSA'\n\ninit_type = 'none'\nparam_type = 'RY'\n\nerr = test_run(mapping_type, inter_distance, backend_type, init_type, use_noise, optimizer_type, param_type)\n```\n\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:82: DeprecationWarning: The qiskit.aqua.components.variational_forms.RY object is deprecated as of 0.7.0 and will be removed no sooner than 3 months after the release. You should use qiskit.circuit.library.RealAmplitudes (uses CX entangling) or qiskit.circuit.library.TwoLocal instead.\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n\n```python\nerr\n```\n\n\n\n\n    0.2216727715951814\n\n\n\n\n```python\nbackend_type = 'qasm'\nmapping_type = 'parity'\noptimizer_type = 'COBYLA'\n\ninit_type = 'none'\nparam_type = 'RY'\n\nerr = test_run(mapping_type, inter_distance, backend_type, init_type, use_noise, optimizer_type, param_type)\n```\n\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:82: DeprecationWarning: The qiskit.aqua.components.variational_forms.RY object is deprecated as of 0.7.0 and will be removed no sooner than 3 months after the release. You should use qiskit.circuit.library.RealAmplitudes (uses CX entangling) or qiskit.circuit.library.TwoLocal instead.\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n\n```python\nerr\n```\n\n\n\n\n    0.14558101072193108\n\n\n\n\n```python\nbackend_type = 'qasm'\nmapping_type = 'parity'\noptimizer_type = 'COBYLA'\nuse_noise = True\n\ninit_type = 'none'\nparam_type = 'RY'\n\nerr = test_run(mapping_type, inter_distance, backend_type, init_type, use_noise, optimizer_type, param_type)\nerr\n```\n\n    Orbitals:  6\n    Particles:  2\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:82: DeprecationWarning: The qiskit.aqua.components.variational_forms.RY object is deprecated as of 0.7.0 and will be removed no sooner than 3 months after the release. You should use qiskit.circuit.library.RealAmplitudes (uses CX entangling) or qiskit.circuit.library.TwoLocal instead.\n    /usr/local/lib/python3.6/dist-packages/qiskit/providers/aer/noise/device/basic_device_model.py:115: DeprecationWarning: This function is been deprecated and moved to a method of the`NoiseModel` class. For equivalent functionality use `NoiseModel.from_backend(properties, **kwargs).\n      DeprecationWarning)\n\n\n\n\n\n    0.22540542222122995\n\n\n\n\n```python\nnone + RY\nZero + ESU2\nHF + RY\n```\n\n\n```python\nscore_noisefree\n```\n\n\n\n\n    [['qasm', 'parity', 'none', 'SPSA', 'ESU2', 0.37743627780600464],\n     ['qasm', 'parity', 'none', 'SPSA', 'RY', 0.23545822538872907],\n     ['qasm', 'parity', 'none', 'SPSA', 'RYRZ', 0.3154474623719926]]\n\n\n\n\n```python\nscore_noisefree\n```\n\n\n\n\n    [['qasm', 'parity', 'Zero', 'SPSA', 'ESU2', 0.24477978624709196],\n     ['qasm', 'parity', 'HF', 'SPSA', 'ESU2', 0.4043620027860433]]\n\n\n\n\n```python\nscore_noisefree\n```\n\n\n\n\n    [['qasm', 'parity', 'Zero', 'SPSA', 'RY', 0.3430786293721373],\n     ['qasm', 'parity', 'Zero', 'SPSA', 'RYRZ', 0.4224011097108429],\n     ['qasm', 'parity', 'Zero', 'SPSA', 'SwapRZ', 0.6435205872063248],\n     ['qasm', 'parity', 'HF', 'SPSA', 'RY', 0.26403037890718406],\n     ['qasm', 'parity', 'HF', 'SPSA', 'RYRZ', 0.4085264575527916],\n     ['qasm', 'parity', 'HF', 'SPSA', 'SwapRZ', 0.3852307592386317]]\n\n\n\n\n```python\nscore_noisefree\n```\n\n\n\n\n    [['qasm', 'parity', 'Zero', 'SPSA', 'UCCSD', 0.8882404619980013],\n     ['qasm', 'parity', 'HF', 'SPSA', 'UCCSD', 0.8109916846466911]]\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n0.5244282569636363\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\nbackend_list = ['qasm']\nmapping_list = ['bravyi_kitaev', 'jordan_wigner']\ninit_state_list = ['HF', 'Zero']\noptimizer_list = ['COBYLA', 'L_BFGS_B', 'SLSQP', 'SPSA']\nparam_list = ['UCCSD', 'RY', 'RYRZ', 'SwapRZ']\n\nscore_noisefree = np.zeros((len(mapping_list)*len(init_state_list)*len(backend_list)*len(optimizer_list)*len(param_list), 6)).tolist()\n\ninter_distance = 1.6\nuse_noise=False\n\ncount = 0\nfor i in range (len(backend_list)):\n  for j in range (len(mapping_list)):\n    for k in range (len(init_state_list)):\n      for l in range (len(optimizer_list)):\n        for m in range (len(param_list)):\n          score_noisefree[count][0] = backend_list[i]\n          score_noisefree[count][1] = mapping_list[j]\n          score_noisefree[count][2] = init_state_list[k]\n          score_noisefree[count][3] = optimizer_list[l]\n          score_noisefree[count][4] = param_list[m]\n          backend_type = backend_list[i]\n          mapping_type = mapping_list[j]\n          init_type = init_state_list[k]\n          optimizer_type = optimizer_list[l]\n          param_type = param_list[m]\n          err = test_run(mapping_type, inter_distance, backend_type, init_type, use_noise, optimizer_type, param_type)\n          score_noisefree[count][5] = err\n          count += 1\n          save_result('result_noise-free_new.txt')\n          print(\"Run \" + str(count) + \": absolute error = \", err)\n```\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 1: absolute error =  0.008057473608764854\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:80: DeprecationWarning: The qiskit.aqua.components.variational_forms.RY object is deprecated as of 0.7.0 and will be removed no sooner than 3 months after the release. You should use qiskit.circuit.library.RealAmplitudes (uses CX entangling) or qiskit.circuit.library.TwoLocal instead.\n\n\n    Run 2: absolute error =  0.21272746710228174\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:82: DeprecationWarning: The qiskit.aqua.components.variational_forms.RYRZ object is deprecated as of 0.7.0 and will be removed no sooner than 3 months after the release. You should use qiskit.circuit.library.EfficientSU2 (uses CX entangling) or qiskit.circuit.library.TwoLocal instead.\n\n\n    Run 3: absolute error =  0.345747380407434\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:84: DeprecationWarning: The qiskit.aqua.components.variational_forms.SwapRZ object is deprecated as of 0.7.0 and will be removed no sooner than 3 months after the release. You should use the qiskit.circuit.library.ExcitationPreserving object instead.\n\n\n    Run 4: absolute error =  1.0663200624319567\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 5: absolute error =  0.023723799188853256\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 6: absolute error =  0.8942656948521042\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 7: absolute error =  0.676724656324102\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 8: absolute error =  1.0763867525608561\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 9: absolute error =  0.019823090443696012\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 10: absolute error =  0.6536287893312782\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 11: absolute error =  0.8239978441843421\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 12: absolute error =  1.0731891925584465\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 13: absolute error =  0.00033940639017981944\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 14: absolute error =  0.19564149127826158\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 15: absolute error =  0.1514178146029772\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 16: absolute error =  1.080799180023768\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 17: absolute error =  1.0727475286177959\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 18: absolute error =  0.18542125714339064\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 19: absolute error =  0.49054334073087336\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 20: absolute error =  1.062946676563112\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 21: absolute error =  1.077572275685081\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 22: absolute error =  1.0488284720323742\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 23: absolute error =  0.7697345709143264\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 24: absolute error =  1.070743358329568\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 25: absolute error =  1.0746153320715708\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 26: absolute error =  0.9377540265591777\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 27: absolute error =  0.9371364197698944\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 28: absolute error =  1.0739485755048361\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 29: absolute error =  1.076530390421702\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 30: absolute error =  0.22685241393574396\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 31: absolute error =  0.30621164332814377\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 32: absolute error =  1.0758838515020739\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 33: absolute error =  0.006400237369535544\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 34: absolute error =  0.17400286272537724\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 35: absolute error =  0.4356932354076565\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 36: absolute error =  1.0631772356496334\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 37: absolute error =  0.01600937790473167\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 38: absolute error =  0.8936857011266549\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 39: absolute error =  0.6371450876564417\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 40: absolute error =  1.0701905743185525\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 41: absolute error =  0.012132299946344682\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 42: absolute error =  0.6722994602212315\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 43: absolute error =  0.9594719384861813\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 44: absolute error =  1.0794790767843812\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 45: absolute error =  0.11472427238517235\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 46: absolute error =  0.1189422603259136\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 47: absolute error =  0.22546875286239776\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 48: absolute error =  1.0772077047070576\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 49: absolute error =  1.073484398424216\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 50: absolute error =  0.1179316534800825\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 51: absolute error =  0.5518767840863128\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 52: absolute error =  1.061025718285195\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 53: absolute error =  1.0711899611298363\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 54: absolute error =  1.355856081722674\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 55: absolute error =  0.7953593014084395\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 56: absolute error =  1.07134923965163\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 57: absolute error =  1.074547175219231\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 58: absolute error =  0.9269793291405661\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 59: absolute error =  0.9884632419802364\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 60: absolute error =  1.0739003195981933\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 61: absolute error =  1.0741249008187221\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 62: absolute error =  0.3071623747852821\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 63: absolute error =  0.35772213042557455\n\n\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/numpy_eigen_solver.py:242: DeprecationWarning: Deprecated class ExactEigensolver, use NumPyEigensolver.\n      DeprecationWarning)\n    /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/eigen_solvers/eigen_solver_result.py:64: DeprecationWarning: energy deprecated, use eigenvalues property.\n      warnings.warn('energy deprecated, use eigenvalues property.', DeprecationWarning)\n\n\n    Run 64: absolute error =  1.080568562681406\n\n\n\n```python\na = load_result('result_noise-free.txt')\n```\n\n\n```python\na\n```\n\n\n\n\n    [['statevector', 'parity', 'HF', 'COBYLA', 'UCCSD', 3.072042220453319e-05],\n     ['statevector', 'parity', 'HF', 'COBYLA', 'RY', 0.0157134358348765],\n     ['statevector', 'parity', 'HF', 'COBYLA', 'RYRZ', 0.14020320484680504],\n     ['statevector', 'parity', 'HF', 'COBYLA', 'SwapRZ', 0.522268457577552],\n     ['statevector', 'parity', 'HF', 'L_BFGS_B', 'UCCSD', 2.733302473245658e-11],\n     ['statevector', 'parity', 'HF', 'L_BFGS_B', 'RY', 0.3139236843935316],\n     ['statevector', 'parity', 'HF', 'L_BFGS_B', 'RYRZ', 0.09765926792516932],\n     ['statevector', 'parity', 'HF', 'L_BFGS_B', 'SwapRZ', 0.522268457577554],\n     ['statevector', 'parity', 'HF', 'SLSQP', 'UCCSD', 1.6421915827180555e-08],\n     ['statevector', 'parity', 'HF', 'SLSQP', 'RY', 8.218520547065289e-05],\n     ['statevector', 'parity', 'HF', 'SLSQP', 'RYRZ', 0.01636009630695301],\n     ['statevector', 'parity', 'HF', 'SLSQP', 'SwapRZ', 0.5222684575775531],\n     ['statevector', 'parity', 'HF', 'SPSA', 'UCCSD', 0.1273435704698549],\n     ['statevector', 'parity', 'HF', 'SPSA', 'RY', 0.012097540624877334],\n     ['statevector', 'parity', 'HF', 'SPSA', 'RYRZ', 0.09732801278006287],\n     ['statevector', 'parity', 'HF', 'SPSA', 'SwapRZ', nan],\n     ['statevector', 'parity', 'Zero', 'COBYLA', 'UCCSD', 0.13021981543903416],\n     ['statevector', 'parity', 'Zero', 'COBYLA', 'RY', 0.1355895691771516],\n     ['statevector', 'parity', 'Zero', 'COBYLA', 'RYRZ', 0.08178938178056172],\n     ['statevector', 'parity', 'Zero', 'COBYLA', 'SwapRZ', 0.5222684575775514],\n     ['statevector', 'parity', 'Zero', 'L_BFGS_B', 'UCCSD', 0.0027045022018710174],\n     ['statevector', 'parity', 'Zero', 'L_BFGS_B', 'RY', 0.18947175704963204],\n     ['statevector', 'parity', 'Zero', 'L_BFGS_B', 'RYRZ', 0.39466491560600336],\n     ['statevector', 'parity', 'Zero', 'L_BFGS_B', 'SwapRZ', 0.5222684575775554],\n     ['statevector', 'parity', 'Zero', 'SLSQP', 'UCCSD', 0.002642235930013115],\n     ['statevector', 'parity', 'Zero', 'SLSQP', 'RY', 4.507765820482845e-05],\n     ['statevector', 'parity', 'Zero', 'SLSQP', 'RYRZ', 2.6883147114631356e-05],\n     ['statevector', 'parity', 'Zero', 'SLSQP', 'SwapRZ', 0.5222684575775522],\n     ['statevector', 'parity', 'Zero', 'SPSA', 'UCCSD', 0.002748988321243484],\n     ['statevector', 'parity', 'Zero', 'SPSA', 'RY', 0.033188423440101866],\n     ['statevector', 'parity', 'Zero', 'SPSA', 'RYRZ', 0.13858214651498446],\n     ['statevector', 'parity', 'Zero', 'SPSA', 'SwapRZ', nan],\n     ['statevector',\n      'bravyi_kitaev',\n      'HF',\n      'COBYLA',\n      'UCCSD',\n      3.072042220497728e-05],\n     ['statevector', 'bravyi_kitaev', 'HF', 'COBYLA', 'RY', 0.05239492975019466],\n     ['statevector', 'bravyi_kitaev', 'HF', 'COBYLA', 'RYRZ', 0.22633611375877505],\n     ['statevector',\n      'bravyi_kitaev',\n      'HF',\n      'COBYLA',\n      'SwapRZ',\n      1.0770597457346924],\n     ['statevector',\n      'bravyi_kitaev',\n      'HF',\n      'L_BFGS_B',\n      'UCCSD',\n      3.125211200938338e-11],\n     ['statevector', 'bravyi_kitaev', 'HF', 'L_BFGS_B', 'RY', 0.5043640346617936],\n     ['statevector',\n      'bravyi_kitaev',\n      'HF',\n      'L_BFGS_B',\n      'RYRZ',\n      0.6841383913819633],\n     ['statevector',\n      'bravyi_kitaev',\n      'HF',\n      'L_BFGS_B',\n      'SwapRZ',\n      1.0770597457346953],\n     ['statevector',\n      'bravyi_kitaev',\n      'HF',\n      'SLSQP',\n      'UCCSD',\n      1.6421919823983444e-08],\n     ['statevector', 'bravyi_kitaev', 'HF', 'SLSQP', 'RY', 0.09641217790773482],\n     ['statevector', 'bravyi_kitaev', 'HF', 'SLSQP', 'RYRZ', 0.003763161436446394],\n     ['statevector', 'bravyi_kitaev', 'HF', 'SLSQP', 'SwapRZ', 1.0770597457346973],\n     ['statevector', 'bravyi_kitaev', 'HF', 'SPSA', 'UCCSD', 0.12860352055406354],\n     ['statevector', 'bravyi_kitaev', 'HF', 'SPSA', 'RY', 0.14418892464127708],\n     ['statevector', 'bravyi_kitaev', 'HF', 'SPSA', 'RYRZ', 0.23439706117979597],\n     ['statevector', 'bravyi_kitaev', 'HF', 'SPSA', 'SwapRZ', nan],\n     ['statevector',\n      'bravyi_kitaev',\n      'Zero',\n      'COBYLA',\n      'UCCSD',\n      1.077059745734699],\n     ['statevector', 'bravyi_kitaev', 'Zero', 'COBYLA', 'RY', 0.12343783857623536],\n     ['statevector',\n      'bravyi_kitaev',\n      'Zero',\n      'COBYLA',\n      'RYRZ',\n      0.27210684366682736],\n     ['statevector',\n      'bravyi_kitaev',\n      'Zero',\n      'COBYLA',\n      'SwapRZ',\n      1.077059745734696],\n     ['statevector',\n      'bravyi_kitaev',\n      'Zero',\n      'L_BFGS_B',\n      'UCCSD',\n      1.0770597457346909],\n     ['statevector',\n      'bravyi_kitaev',\n      'Zero',\n      'L_BFGS_B',\n      'RY',\n      0.21350934601932026],\n     ['statevector',\n      'bravyi_kitaev',\n      'Zero',\n      'L_BFGS_B',\n      'RYRZ',\n      0.6660426273660169],\n     ['statevector',\n      'bravyi_kitaev',\n      'Zero',\n      'L_BFGS_B',\n      'SwapRZ',\n      1.077059745734696],\n     ['statevector',\n      'bravyi_kitaev',\n      'Zero',\n      'SLSQP',\n      'UCCSD',\n      1.0770597457346933],\n     ['statevector', 'bravyi_kitaev', 'Zero', 'SLSQP', 'RY', 0.1151107574834529],\n     ['statevector',\n      'bravyi_kitaev',\n      'Zero',\n      'SLSQP',\n      'RYRZ',\n      0.019210157478026346],\n     ['statevector',\n      'bravyi_kitaev',\n      'Zero',\n      'SLSQP',\n      'SwapRZ',\n      1.0770597457346949],\n     ['statevector', 'bravyi_kitaev', 'Zero', 'SPSA', 'UCCSD', nan],\n     ['statevector', 'bravyi_kitaev', 'Zero', 'SPSA', 'RY', 0.08757459563923642],\n     ['statevector', 'bravyi_kitaev', 'Zero', 'SPSA', 'RYRZ', 0.2554999509759188],\n     ['statevector', 'bravyi_kitaev', 'Zero', 'SPSA', 'SwapRZ', nan],\n     ['statevector',\n      'jordan_wigner',\n      'HF',\n      'COBYLA',\n      'UCCSD',\n      3.0720422202756836e-05],\n     ['statevector', 'jordan_wigner', 'HF', 'COBYLA', 'RY', 0.1343633049662013],\n     ['statevector', 'jordan_wigner', 'HF', 'COBYLA', 'RYRZ', 0.1642150351643733],\n     ['statevector',\n      'jordan_wigner',\n      'HF',\n      'COBYLA',\n      'SwapRZ',\n      1.0770597457346942],\n     ['statevector',\n      'jordan_wigner',\n      'HF',\n      'L_BFGS_B',\n      'UCCSD',\n      3.0114133409142596e-11],\n     ['statevector', 'jordan_wigner', 'HF', 'L_BFGS_B', 'RY', 0.17771275989417534],\n     ['statevector', 'jordan_wigner', 'HF', 'L_BFGS_B', 'RYRZ', 0.710645820891249],\n     ['statevector',\n      'jordan_wigner',\n      'HF',\n      'L_BFGS_B',\n      'SwapRZ',\n      1.0770597457346875],\n     ['statevector',\n      'jordan_wigner',\n      'HF',\n      'SLSQP',\n      'UCCSD',\n      1.6516854772774536e-08],\n     ['statevector', 'jordan_wigner', 'HF', 'SLSQP', 'RY', 0.01923281191750492],\n     ['statevector', 'jordan_wigner', 'HF', 'SLSQP', 'RYRZ', 0.01920861260886686],\n     ['statevector', 'jordan_wigner', 'HF', 'SLSQP', 'SwapRZ', 1.0770597457346924],\n     ['statevector', 'jordan_wigner', 'HF', 'SPSA', 'UCCSD', 0.1232435816219215],\n     ['statevector', 'jordan_wigner', 'HF', 'SPSA', 'RY', 0.029858667709953934],\n     ['statevector', 'jordan_wigner', 'HF', 'SPSA', 'RYRZ', 0.40754338922561506],\n     ['statevector', 'jordan_wigner', 'HF', 'SPSA', 'SwapRZ', nan],\n     ['statevector',\n      'jordan_wigner',\n      'Zero',\n      'COBYLA',\n      'UCCSD',\n      1.0770597457346909],\n     ['statevector', 'jordan_wigner', 'Zero', 'COBYLA', 'RY', 0.29111543174789356],\n     ['statevector',\n      'jordan_wigner',\n      'Zero',\n      'COBYLA',\n      'RYRZ',\n      0.32275369820310307],\n     ['statevector',\n      'jordan_wigner',\n      'Zero',\n      'COBYLA',\n      'SwapRZ',\n      1.0770597457346958],\n     ['statevector',\n      'jordan_wigner',\n      'Zero',\n      'L_BFGS_B',\n      'UCCSD',\n      1.0770597457346938],\n     ['statevector',\n      'jordan_wigner',\n      'Zero',\n      'L_BFGS_B',\n      'RY',\n      0.19564830579329617],\n     ['statevector',\n      'jordan_wigner',\n      'Zero',\n      'L_BFGS_B',\n      'RYRZ',\n      0.5772611435786917],\n     ['statevector',\n      'jordan_wigner',\n      'Zero',\n      'L_BFGS_B',\n      'SwapRZ',\n      1.077059745734695],\n     ['statevector', 'jordan_wigner', 'Zero', 'SLSQP', 'UCCSD', 1.077059745734692],\n     ['statevector', 'jordan_wigner', 'Zero', 'SLSQP', 'RY', 0.002645319378434152],\n     ['statevector',\n      'jordan_wigner',\n      'Zero',\n      'SLSQP',\n      'RYRZ',\n      0.019211344819644482],\n     ['statevector',\n      'jordan_wigner',\n      'Zero',\n      'SLSQP',\n      'SwapRZ',\n      1.0770597457346907],\n     ['statevector', 'jordan_wigner', 'Zero', 'SPSA', 'UCCSD', nan],\n     ['statevector', 'jordan_wigner', 'Zero', 'SPSA', 'RY', 0.22111576580891468],\n     ['statevector',\n      'jordan_wigner',\n      'Zero',\n      'SPSA',\n      'RYRZ',\n      0.045100076992815374],\n     ['statevector', 'jordan_wigner', 'Zero', 'SPSA', 'SwapRZ', nan],\n     ['qasm', 'parity', 'HF', 'COBYLA', 'UCCSD', 0.00924126824842153],\n     ['qasm', 'parity', 'HF', 'COBYLA', 'RY', 0.1527807074841664],\n     ['qasm', 'parity', 'HF', 'COBYLA', 'RYRZ', 0.5505722970944027],\n     ['qasm', 'parity', 'HF', 'COBYLA', 'SwapRZ', 0.5135283856235134],\n     ['qasm', 'parity', 'HF', 'L_BFGS_B', 'UCCSD', 0.02057704223196244],\n     ['qasm', 'parity', 'HF', 'L_BFGS_B', 'RY', 0.7268557081568838],\n     ['qasm', 'parity', 'HF', 'L_BFGS_B', 'RYRZ', 0.7776674407330829],\n     ['qasm', 'parity', 'HF', 'L_BFGS_B', 'SwapRZ', 0.5171882179704322],\n     ['qasm', 'parity', 'HF', 'SLSQP', 'UCCSD', 0.020476943342381038],\n     ['qasm', 'parity', 'HF', 'SLSQP', 'RY', 1.818701185931626],\n     ['qasm', 'parity', 'HF', 'SLSQP', 'RYRZ', 1.1672692762434442],\n     ['qasm', 'parity', 'HF', 'SLSQP', 'SwapRZ', 0.5182449532901441],\n     ['qasm', 'parity', 'HF', 'SPSA', 'UCCSD', 0.05677871229066289],\n     ['qasm', 'parity', 'HF', 'SPSA', 'RY', 0.11976540394392443],\n     ['qasm', 'parity', 'HF', 'SPSA', 'RYRZ', 0.10316807422896412],\n     ['qasm', 'parity', 'HF', 'SPSA', 'SwapRZ', 0.5234361536174325],\n     ['qasm', 'parity', 'Zero', 'COBYLA', 'UCCSD', 0.0780655665096962],\n     ['qasm', 'parity', 'Zero', 'COBYLA', 'RY', 0.17867057456619606],\n     ['qasm', 'parity', 'Zero', 'COBYLA', 'RYRZ', 0.0771205109038442],\n     ['qasm', 'parity', 'Zero', 'COBYLA', 'SwapRZ', 0.5138530292553826],\n     ['qasm', 'parity', 'Zero', 'L_BFGS_B', 'UCCSD', 0.3258268702565149],\n     ['qasm', 'parity', 'Zero', 'L_BFGS_B', 'RY', 0.8430338641661765],\n     ['qasm', 'parity', 'Zero', 'L_BFGS_B', 'RYRZ', 0.766940074363376],\n     ['qasm', 'parity', 'Zero', 'L_BFGS_B', 'SwapRZ', 0.5240678781437735],\n     ['qasm', 'parity', 'Zero', 'SLSQP', 'UCCSD', 0.4157068506701319],\n     ['qasm', 'parity', 'Zero', 'SLSQP', 'RY', 0.8090545127061115],\n     ['qasm', 'parity', 'Zero', 'SLSQP', 'RYRZ', 0.957626402534472],\n     ['qasm', 'parity', 'Zero', 'SLSQP', 'SwapRZ', 0.5220441118601121],\n     ['qasm', 'parity', 'Zero', 'SPSA', 'UCCSD', 0.13660343003765296],\n     ['qasm', 'parity', 'Zero', 'SPSA', 'RY', 0.023469196815082194],\n     ['qasm', 'parity', 'Zero', 'SPSA', 'RYRZ', 0.09885068123939189],\n     ['qasm', 'parity', 'Zero', 'SPSA', 'SwapRZ', 0.5227220665548342],\n     ['qasm', 'bravyi_kitaev', 'HF', 'COBYLA', 'UCCSD', 0.014826397086675325],\n     ['qasm', 'bravyi_kitaev', 'HF', 'COBYLA', 'RY', 0.33910185423441297],\n     ['qasm', 'bravyi_kitaev', 'HF', 'COBYLA', 'RYRZ', 0.28840161529261554],\n     ['qasm', 'bravyi_kitaev', 'HF', 'COBYLA', 'SwapRZ', 1.067491615950404],\n     ['qasm', 'bravyi_kitaev', 'HF', 'L_BFGS_B', 'UCCSD', 0.01839381895316672],\n     ['qasm', 'bravyi_kitaev', 'HF', 'L_BFGS_B', 'RY', 0.8332769676268209],\n     ['qasm', 'bravyi_kitaev', 'HF', 'L_BFGS_B', 'RYRZ', 1.2078441739053436],\n     ['qasm', 'bravyi_kitaev', 'HF', 'L_BFGS_B', 'SwapRZ', 1.0729132577011988],\n     ['qasm', 'bravyi_kitaev', 'HF', 'SLSQP', 'UCCSD', 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]\n\n\n\n\n```python\nb = load_result('result_noise-free_new.txt')\nb\n```\n\n\n\n\n    [['qasm', 'bravyi_kitaev', 'HF', 'COBYLA', 'UCCSD', 0.008057473608764854],\n     ['qasm', 'bravyi_kitaev', 'HF', 'COBYLA', 'RY', 0.21272746710228174],\n     ['qasm', 'bravyi_kitaev', 'HF', 'COBYLA', 'RYRZ', 0.345747380407434],\n     ['qasm', 'bravyi_kitaev', 'HF', 'COBYLA', 'SwapRZ', 1.0663200624319567],\n     ['qasm', 'bravyi_kitaev', 'HF', 'L_BFGS_B', 'UCCSD', 0.023723799188853256],\n     ['qasm', 'bravyi_kitaev', 'HF', 'L_BFGS_B', 'RY', 0.8942656948521042],\n     ['qasm', 'bravyi_kitaev', 'HF', 'L_BFGS_B', 'RYRZ', 0.676724656324102],\n     ['qasm', 'bravyi_kitaev', 'HF', 'L_BFGS_B', 'SwapRZ', 1.0763867525608561],\n     ['qasm', 'bravyi_kitaev', 'HF', 'SLSQP', 'UCCSD', 0.019823090443696012],\n     ['qasm', 'bravyi_kitaev', 'HF', 'SLSQP', 'RY', 0.6536287893312782],\n     ['qasm', 'bravyi_kitaev', 'HF', 'SLSQP', 'RYRZ', 0.8239978441843421],\n     ['qasm', 'bravyi_kitaev', 'HF', 'SLSQP', 'SwapRZ', 1.0731891925584465],\n     ['qasm', 'bravyi_kitaev', 'HF', 'SPSA', 'UCCSD', 0.00033940639017981944],\n     ['qasm', 'bravyi_kitaev', 'HF', 'SPSA', 'RY', 0.19564149127826158],\n     ['qasm', 'bravyi_kitaev', 'HF', 'SPSA', 'RYRZ', 0.1514178146029772],\n     ['qasm', 'bravyi_kitaev', 'HF', 'SPSA', 'SwapRZ', 1.080799180023768],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'COBYLA', 'UCCSD', 1.0727475286177959],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'COBYLA', 'RY', 0.18542125714339064],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'COBYLA', 'RYRZ', 0.49054334073087336],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'COBYLA', 'SwapRZ', 1.062946676563112],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'L_BFGS_B', 'UCCSD', 1.077572275685081],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'L_BFGS_B', 'RY', 1.0488284720323742],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'L_BFGS_B', 'RYRZ', 0.7697345709143264],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'L_BFGS_B', 'SwapRZ', 1.070743358329568],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'SLSQP', 'UCCSD', 1.0746153320715708],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'SLSQP', 'RY', 0.9377540265591777],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'SLSQP', 'RYRZ', 0.9371364197698944],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'SLSQP', 'SwapRZ', 1.0739485755048361],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'SPSA', 'UCCSD', 1.076530390421702],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'SPSA', 'RY', 0.22685241393574396],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'SPSA', 'RYRZ', 0.30621164332814377],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'SPSA', 'SwapRZ', 1.0758838515020739],\n     ['qasm', 'jordan_wigner', 'HF', 'COBYLA', 'UCCSD', 0.006400237369535544],\n     ['qasm', 'jordan_wigner', 'HF', 'COBYLA', 'RY', 0.17400286272537724],\n     ['qasm', 'jordan_wigner', 'HF', 'COBYLA', 'RYRZ', 0.4356932354076565],\n     ['qasm', 'jordan_wigner', 'HF', 'COBYLA', 'SwapRZ', 1.0631772356496334],\n     ['qasm', 'jordan_wigner', 'HF', 'L_BFGS_B', 'UCCSD', 0.01600937790473167],\n     ['qasm', 'jordan_wigner', 'HF', 'L_BFGS_B', 'RY', 0.8936857011266549],\n     ['qasm', 'jordan_wigner', 'HF', 'L_BFGS_B', 'RYRZ', 0.6371450876564417],\n     ['qasm', 'jordan_wigner', 'HF', 'L_BFGS_B', 'SwapRZ', 1.0701905743185525],\n     ['qasm', 'jordan_wigner', 'HF', 'SLSQP', 'UCCSD', 0.012132299946344682],\n     ['qasm', 'jordan_wigner', 'HF', 'SLSQP', 'RY', 0.6722994602212315],\n     ['qasm', 'jordan_wigner', 'HF', 'SLSQP', 'RYRZ', 0.9594719384861813],\n     ['qasm', 'jordan_wigner', 'HF', 'SLSQP', 'SwapRZ', 1.0794790767843812],\n     ['qasm', 'jordan_wigner', 'HF', 'SPSA', 'UCCSD', 0.11472427238517235],\n     ['qasm', 'jordan_wigner', 'HF', 'SPSA', 'RY', 0.1189422603259136],\n     ['qasm', 'jordan_wigner', 'HF', 'SPSA', 'RYRZ', 0.22546875286239776],\n     ['qasm', 'jordan_wigner', 'HF', 'SPSA', 'SwapRZ', 1.0772077047070576],\n     ['qasm', 'jordan_wigner', 'Zero', 'COBYLA', 'UCCSD', 1.073484398424216],\n     ['qasm', 'jordan_wigner', 'Zero', 'COBYLA', 'RY', 0.1179316534800825],\n     ['qasm', 'jordan_wigner', 'Zero', 'COBYLA', 'RYRZ', 0.5518767840863128],\n     ['qasm', 'jordan_wigner', 'Zero', 'COBYLA', 'SwapRZ', 1.061025718285195],\n     ['qasm', 'jordan_wigner', 'Zero', 'L_BFGS_B', 'UCCSD', 1.0711899611298363],\n     ['qasm', 'jordan_wigner', 'Zero', 'L_BFGS_B', 'RY', 1.355856081722674],\n     ['qasm', 'jordan_wigner', 'Zero', 'L_BFGS_B', 'RYRZ', 0.7953593014084395],\n     ['qasm', 'jordan_wigner', 'Zero', 'L_BFGS_B', 'SwapRZ', 1.07134923965163],\n     ['qasm', 'jordan_wigner', 'Zero', 'SLSQP', 'UCCSD', 1.074547175219231],\n     ['qasm', 'jordan_wigner', 'Zero', 'SLSQP', 'RY', 0.9269793291405661],\n     ['qasm', 'jordan_wigner', 'Zero', 'SLSQP', 'RYRZ', 0.9884632419802364],\n     ['qasm', 'jordan_wigner', 'Zero', 'SLSQP', 'SwapRZ', 1.0739003195981933],\n     ['qasm', 'jordan_wigner', 'Zero', 'SPSA', 'UCCSD', 1.0741249008187221],\n     ['qasm', 'jordan_wigner', 'Zero', 'SPSA', 'RY', 0.3071623747852821],\n     ['qasm', 'jordan_wigner', 'Zero', 'SPSA', 'RYRZ', 0.35772213042557455],\n     ['qasm', 'jordan_wigner', 'Zero', 'SPSA', 'SwapRZ', 1.080568562681406]]\n\n\n\n\n```python\nfor i in range (len(a)):\n  if a[i][0] == b[0][0] and a[i][1] == b[0][1] and a[i][2] == b[0][2] and a[i][3] == b[0][3] and a[i][4] == b[0][4]:\n    for j in range(len(b)):\n      a[i+j][0] = b[j][0]\n      a[i+j][1] = b[j][1]\n      a[i+j][2] = b[j][2]\n      a[i+j][3] = b[j][3]\n      a[i+j][4] = b[j][4]\n      a[i+j][5] = b[j][5]\n    break\n\na\n```\n\n\n\n\n    [['statevector', 'parity', 'HF', 'COBYLA', 'UCCSD', 3.072042220453319e-05],\n     ['statevector', 'parity', 'HF', 'COBYLA', 'RY', 0.0157134358348765],\n     ['statevector', 'parity', 'HF', 'COBYLA', 'RYRZ', 0.14020320484680504],\n     ['statevector', 'parity', 'HF', 'COBYLA', 'SwapRZ', 0.522268457577552],\n     ['statevector', 'parity', 'HF', 'L_BFGS_B', 'UCCSD', 2.733302473245658e-11],\n     ['statevector', 'parity', 'HF', 'L_BFGS_B', 'RY', 0.3139236843935316],\n     ['statevector', 'parity', 'HF', 'L_BFGS_B', 'RYRZ', 0.09765926792516932],\n     ['statevector', 'parity', 'HF', 'L_BFGS_B', 'SwapRZ', 0.522268457577554],\n     ['statevector', 'parity', 'HF', 'SLSQP', 'UCCSD', 1.6421915827180555e-08],\n     ['statevector', 'parity', 'HF', 'SLSQP', 'RY', 8.218520547065289e-05],\n     ['statevector', 'parity', 'HF', 'SLSQP', 'RYRZ', 0.01636009630695301],\n     ['statevector', 'parity', 'HF', 'SLSQP', 'SwapRZ', 0.5222684575775531],\n     ['statevector', 'parity', 'HF', 'SPSA', 'UCCSD', 0.1273435704698549],\n     ['statevector', 'parity', 'HF', 'SPSA', 'RY', 0.012097540624877334],\n     ['statevector', 'parity', 'HF', 'SPSA', 'RYRZ', 0.09732801278006287],\n     ['statevector', 'parity', 'HF', 'SPSA', 'SwapRZ', nan],\n     ['statevector', 'parity', 'Zero', 'COBYLA', 'UCCSD', 0.13021981543903416],\n     ['statevector', 'parity', 'Zero', 'COBYLA', 'RY', 0.1355895691771516],\n     ['statevector', 'parity', 'Zero', 'COBYLA', 'RYRZ', 0.08178938178056172],\n     ['statevector', 'parity', 'Zero', 'COBYLA', 'SwapRZ', 0.5222684575775514],\n     ['statevector', 'parity', 'Zero', 'L_BFGS_B', 'UCCSD', 0.0027045022018710174],\n     ['statevector', 'parity', 'Zero', 'L_BFGS_B', 'RY', 0.18947175704963204],\n     ['statevector', 'parity', 'Zero', 'L_BFGS_B', 'RYRZ', 0.39466491560600336],\n     ['statevector', 'parity', 'Zero', 'L_BFGS_B', 'SwapRZ', 0.5222684575775554],\n     ['statevector', 'parity', 'Zero', 'SLSQP', 'UCCSD', 0.002642235930013115],\n     ['statevector', 'parity', 'Zero', 'SLSQP', 'RY', 4.507765820482845e-05],\n     ['statevector', 'parity', 'Zero', 'SLSQP', 'RYRZ', 2.6883147114631356e-05],\n     ['statevector', 'parity', 'Zero', 'SLSQP', 'SwapRZ', 0.5222684575775522],\n     ['statevector', 'parity', 'Zero', 'SPSA', 'UCCSD', 0.002748988321243484],\n     ['statevector', 'parity', 'Zero', 'SPSA', 'RY', 0.033188423440101866],\n     ['statevector', 'parity', 'Zero', 'SPSA', 'RYRZ', 0.13858214651498446],\n     ['statevector', 'parity', 'Zero', 'SPSA', 'SwapRZ', nan],\n     ['statevector',\n      'bravyi_kitaev',\n      'HF',\n      'COBYLA',\n      'UCCSD',\n      3.072042220497728e-05],\n     ['statevector', 'bravyi_kitaev', 'HF', 'COBYLA', 'RY', 0.05239492975019466],\n     ['statevector', 'bravyi_kitaev', 'HF', 'COBYLA', 'RYRZ', 0.22633611375877505],\n     ['statevector',\n      'bravyi_kitaev',\n      'HF',\n      'COBYLA',\n      'SwapRZ',\n      1.0770597457346924],\n     ['statevector',\n      'bravyi_kitaev',\n      'HF',\n      'L_BFGS_B',\n      'UCCSD',\n      3.125211200938338e-11],\n     ['statevector', 'bravyi_kitaev', 'HF', 'L_BFGS_B', 'RY', 0.5043640346617936],\n     ['statevector',\n      'bravyi_kitaev',\n      'HF',\n      'L_BFGS_B',\n      'RYRZ',\n      0.6841383913819633],\n     ['statevector',\n      'bravyi_kitaev',\n      'HF',\n      'L_BFGS_B',\n      'SwapRZ',\n      1.0770597457346953],\n     ['statevector',\n      'bravyi_kitaev',\n      'HF',\n      'SLSQP',\n      'UCCSD',\n      1.6421919823983444e-08],\n     ['statevector', 'bravyi_kitaev', 'HF', 'SLSQP', 'RY', 0.09641217790773482],\n     ['statevector', 'bravyi_kitaev', 'HF', 'SLSQP', 'RYRZ', 0.003763161436446394],\n     ['statevector', 'bravyi_kitaev', 'HF', 'SLSQP', 'SwapRZ', 1.0770597457346973],\n     ['statevector', 'bravyi_kitaev', 'HF', 'SPSA', 'UCCSD', 0.12860352055406354],\n     ['statevector', 'bravyi_kitaev', 'HF', 'SPSA', 'RY', 0.14418892464127708],\n     ['statevector', 'bravyi_kitaev', 'HF', 'SPSA', 'RYRZ', 0.23439706117979597],\n     ['statevector', 'bravyi_kitaev', 'HF', 'SPSA', 'SwapRZ', nan],\n     ['statevector',\n      'bravyi_kitaev',\n      'Zero',\n      'COBYLA',\n      'UCCSD',\n      1.077059745734699],\n     ['statevector', 'bravyi_kitaev', 'Zero', 'COBYLA', 'RY', 0.12343783857623536],\n     ['statevector',\n      'bravyi_kitaev',\n      'Zero',\n      'COBYLA',\n      'RYRZ',\n      0.27210684366682736],\n     ['statevector',\n      'bravyi_kitaev',\n      'Zero',\n      'COBYLA',\n      'SwapRZ',\n      1.077059745734696],\n     ['statevector',\n      'bravyi_kitaev',\n      'Zero',\n      'L_BFGS_B',\n      'UCCSD',\n      1.0770597457346909],\n     ['statevector',\n      'bravyi_kitaev',\n      'Zero',\n      'L_BFGS_B',\n      'RY',\n      0.21350934601932026],\n     ['statevector',\n      'bravyi_kitaev',\n      'Zero',\n      'L_BFGS_B',\n      'RYRZ',\n      0.6660426273660169],\n     ['statevector',\n      'bravyi_kitaev',\n      'Zero',\n      'L_BFGS_B',\n      'SwapRZ',\n      1.077059745734696],\n     ['statevector',\n      'bravyi_kitaev',\n      'Zero',\n      'SLSQP',\n      'UCCSD',\n      1.0770597457346933],\n     ['statevector', 'bravyi_kitaev', 'Zero', 'SLSQP', 'RY', 0.1151107574834529],\n     ['statevector',\n      'bravyi_kitaev',\n      'Zero',\n      'SLSQP',\n      'RYRZ',\n      0.019210157478026346],\n     ['statevector',\n      'bravyi_kitaev',\n      'Zero',\n      'SLSQP',\n      'SwapRZ',\n      1.0770597457346949],\n     ['statevector', 'bravyi_kitaev', 'Zero', 'SPSA', 'UCCSD', nan],\n     ['statevector', 'bravyi_kitaev', 'Zero', 'SPSA', 'RY', 0.08757459563923642],\n     ['statevector', 'bravyi_kitaev', 'Zero', 'SPSA', 'RYRZ', 0.2554999509759188],\n     ['statevector', 'bravyi_kitaev', 'Zero', 'SPSA', 'SwapRZ', nan],\n     ['statevector',\n      'jordan_wigner',\n      'HF',\n      'COBYLA',\n      'UCCSD',\n      3.0720422202756836e-05],\n     ['statevector', 'jordan_wigner', 'HF', 'COBYLA', 'RY', 0.1343633049662013],\n     ['statevector', 'jordan_wigner', 'HF', 'COBYLA', 'RYRZ', 0.1642150351643733],\n     ['statevector',\n      'jordan_wigner',\n      'HF',\n      'COBYLA',\n      'SwapRZ',\n      1.0770597457346942],\n     ['statevector',\n      'jordan_wigner',\n      'HF',\n      'L_BFGS_B',\n      'UCCSD',\n      3.0114133409142596e-11],\n     ['statevector', 'jordan_wigner', 'HF', 'L_BFGS_B', 'RY', 0.17771275989417534],\n     ['statevector', 'jordan_wigner', 'HF', 'L_BFGS_B', 'RYRZ', 0.710645820891249],\n     ['statevector',\n      'jordan_wigner',\n      'HF',\n      'L_BFGS_B',\n      'SwapRZ',\n      1.0770597457346875],\n     ['statevector',\n      'jordan_wigner',\n      'HF',\n      'SLSQP',\n      'UCCSD',\n      1.6516854772774536e-08],\n     ['statevector', 'jordan_wigner', 'HF', 'SLSQP', 'RY', 0.01923281191750492],\n     ['statevector', 'jordan_wigner', 'HF', 'SLSQP', 'RYRZ', 0.01920861260886686],\n     ['statevector', 'jordan_wigner', 'HF', 'SLSQP', 'SwapRZ', 1.0770597457346924],\n     ['statevector', 'jordan_wigner', 'HF', 'SPSA', 'UCCSD', 0.1232435816219215],\n     ['statevector', 'jordan_wigner', 'HF', 'SPSA', 'RY', 0.029858667709953934],\n     ['statevector', 'jordan_wigner', 'HF', 'SPSA', 'RYRZ', 0.40754338922561506],\n     ['statevector', 'jordan_wigner', 'HF', 'SPSA', 'SwapRZ', nan],\n     ['statevector',\n      'jordan_wigner',\n      'Zero',\n      'COBYLA',\n      'UCCSD',\n      1.0770597457346909],\n     ['statevector', 'jordan_wigner', 'Zero', 'COBYLA', 'RY', 0.29111543174789356],\n     ['statevector',\n      'jordan_wigner',\n      'Zero',\n      'COBYLA',\n      'RYRZ',\n      0.32275369820310307],\n     ['statevector',\n      'jordan_wigner',\n      'Zero',\n      'COBYLA',\n      'SwapRZ',\n      1.0770597457346958],\n     ['statevector',\n      'jordan_wigner',\n      'Zero',\n      'L_BFGS_B',\n      'UCCSD',\n      1.0770597457346938],\n     ['statevector',\n      'jordan_wigner',\n      'Zero',\n      'L_BFGS_B',\n      'RY',\n      0.19564830579329617],\n     ['statevector',\n      'jordan_wigner',\n      'Zero',\n      'L_BFGS_B',\n      'RYRZ',\n      0.5772611435786917],\n     ['statevector',\n      'jordan_wigner',\n      'Zero',\n      'L_BFGS_B',\n      'SwapRZ',\n      1.077059745734695],\n     ['statevector', 'jordan_wigner', 'Zero', 'SLSQP', 'UCCSD', 1.077059745734692],\n     ['statevector', 'jordan_wigner', 'Zero', 'SLSQP', 'RY', 0.002645319378434152],\n     ['statevector',\n      'jordan_wigner',\n      'Zero',\n      'SLSQP',\n      'RYRZ',\n      0.019211344819644482],\n     ['statevector',\n      'jordan_wigner',\n      'Zero',\n      'SLSQP',\n      'SwapRZ',\n      1.0770597457346907],\n     ['statevector', 'jordan_wigner', 'Zero', 'SPSA', 'UCCSD', nan],\n     ['statevector', 'jordan_wigner', 'Zero', 'SPSA', 'RY', 0.22111576580891468],\n     ['statevector',\n      'jordan_wigner',\n      'Zero',\n      'SPSA',\n      'RYRZ',\n      0.045100076992815374],\n     ['statevector', 'jordan_wigner', 'Zero', 'SPSA', 'SwapRZ', nan],\n     ['qasm', 'parity', 'HF', 'COBYLA', 'UCCSD', 0.00924126824842153],\n     ['qasm', 'parity', 'HF', 'COBYLA', 'RY', 0.1527807074841664],\n     ['qasm', 'parity', 'HF', 'COBYLA', 'RYRZ', 0.5505722970944027],\n     ['qasm', 'parity', 'HF', 'COBYLA', 'SwapRZ', 0.5135283856235134],\n     ['qasm', 'parity', 'HF', 'L_BFGS_B', 'UCCSD', 0.02057704223196244],\n     ['qasm', 'parity', 'HF', 'L_BFGS_B', 'RY', 0.7268557081568838],\n     ['qasm', 'parity', 'HF', 'L_BFGS_B', 'RYRZ', 0.7776674407330829],\n     ['qasm', 'parity', 'HF', 'L_BFGS_B', 'SwapRZ', 0.5171882179704322],\n     ['qasm', 'parity', 'HF', 'SLSQP', 'UCCSD', 0.020476943342381038],\n     ['qasm', 'parity', 'HF', 'SLSQP', 'RY', 1.818701185931626],\n     ['qasm', 'parity', 'HF', 'SLSQP', 'RYRZ', 1.1672692762434442],\n     ['qasm', 'parity', 'HF', 'SLSQP', 'SwapRZ', 0.5182449532901441],\n     ['qasm', 'parity', 'HF', 'SPSA', 'UCCSD', 0.05677871229066289],\n     ['qasm', 'parity', 'HF', 'SPSA', 'RY', 0.11976540394392443],\n     ['qasm', 'parity', 'HF', 'SPSA', 'RYRZ', 0.10316807422896412],\n     ['qasm', 'parity', 'HF', 'SPSA', 'SwapRZ', 0.5234361536174325],\n     ['qasm', 'parity', 'Zero', 'COBYLA', 'UCCSD', 0.0780655665096962],\n     ['qasm', 'parity', 'Zero', 'COBYLA', 'RY', 0.17867057456619606],\n     ['qasm', 'parity', 'Zero', 'COBYLA', 'RYRZ', 0.0771205109038442],\n     ['qasm', 'parity', 'Zero', 'COBYLA', 'SwapRZ', 0.5138530292553826],\n     ['qasm', 'parity', 'Zero', 'L_BFGS_B', 'UCCSD', 0.3258268702565149],\n     ['qasm', 'parity', 'Zero', 'L_BFGS_B', 'RY', 0.8430338641661765],\n     ['qasm', 'parity', 'Zero', 'L_BFGS_B', 'RYRZ', 0.766940074363376],\n     ['qasm', 'parity', 'Zero', 'L_BFGS_B', 'SwapRZ', 0.5240678781437735],\n     ['qasm', 'parity', 'Zero', 'SLSQP', 'UCCSD', 0.4157068506701319],\n     ['qasm', 'parity', 'Zero', 'SLSQP', 'RY', 0.8090545127061115],\n     ['qasm', 'parity', 'Zero', 'SLSQP', 'RYRZ', 0.957626402534472],\n     ['qasm', 'parity', 'Zero', 'SLSQP', 'SwapRZ', 0.5220441118601121],\n     ['qasm', 'parity', 'Zero', 'SPSA', 'UCCSD', 0.13660343003765296],\n     ['qasm', 'parity', 'Zero', 'SPSA', 'RY', 0.023469196815082194],\n     ['qasm', 'parity', 'Zero', 'SPSA', 'RYRZ', 0.09885068123939189],\n     ['qasm', 'parity', 'Zero', 'SPSA', 'SwapRZ', 0.5227220665548342],\n     ['qasm', 'bravyi_kitaev', 'HF', 'COBYLA', 'UCCSD', 0.008057473608764854],\n     ['qasm', 'bravyi_kitaev', 'HF', 'COBYLA', 'RY', 0.21272746710228174],\n     ['qasm', 'bravyi_kitaev', 'HF', 'COBYLA', 'RYRZ', 0.345747380407434],\n     ['qasm', 'bravyi_kitaev', 'HF', 'COBYLA', 'SwapRZ', 1.0663200624319567],\n     ['qasm', 'bravyi_kitaev', 'HF', 'L_BFGS_B', 'UCCSD', 0.023723799188853256],\n     ['qasm', 'bravyi_kitaev', 'HF', 'L_BFGS_B', 'RY', 0.8942656948521042],\n     ['qasm', 'bravyi_kitaev', 'HF', 'L_BFGS_B', 'RYRZ', 0.676724656324102],\n     ['qasm', 'bravyi_kitaev', 'HF', 'L_BFGS_B', 'SwapRZ', 1.0763867525608561],\n     ['qasm', 'bravyi_kitaev', 'HF', 'SLSQP', 'UCCSD', 0.019823090443696012],\n     ['qasm', 'bravyi_kitaev', 'HF', 'SLSQP', 'RY', 0.6536287893312782],\n     ['qasm', 'bravyi_kitaev', 'HF', 'SLSQP', 'RYRZ', 0.8239978441843421],\n     ['qasm', 'bravyi_kitaev', 'HF', 'SLSQP', 'SwapRZ', 1.0731891925584465],\n     ['qasm', 'bravyi_kitaev', 'HF', 'SPSA', 'UCCSD', 0.00033940639017981944],\n     ['qasm', 'bravyi_kitaev', 'HF', 'SPSA', 'RY', 0.19564149127826158],\n     ['qasm', 'bravyi_kitaev', 'HF', 'SPSA', 'RYRZ', 0.1514178146029772],\n     ['qasm', 'bravyi_kitaev', 'HF', 'SPSA', 'SwapRZ', 1.080799180023768],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'COBYLA', 'UCCSD', 1.0727475286177959],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'COBYLA', 'RY', 0.18542125714339064],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'COBYLA', 'RYRZ', 0.49054334073087336],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'COBYLA', 'SwapRZ', 1.062946676563112],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'L_BFGS_B', 'UCCSD', 1.077572275685081],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'L_BFGS_B', 'RY', 1.0488284720323742],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'L_BFGS_B', 'RYRZ', 0.7697345709143264],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'L_BFGS_B', 'SwapRZ', 1.070743358329568],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'SLSQP', 'UCCSD', 1.0746153320715708],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'SLSQP', 'RY', 0.9377540265591777],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'SLSQP', 'RYRZ', 0.9371364197698944],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'SLSQP', 'SwapRZ', 1.0739485755048361],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'SPSA', 'UCCSD', 1.076530390421702],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'SPSA', 'RY', 0.22685241393574396],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'SPSA', 'RYRZ', 0.30621164332814377],\n     ['qasm', 'bravyi_kitaev', 'Zero', 'SPSA', 'SwapRZ', 1.0758838515020739],\n     ['qasm', 'jordan_wigner', 'HF', 'COBYLA', 'UCCSD', 0.006400237369535544],\n     ['qasm', 'jordan_wigner', 'HF', 'COBYLA', 'RY', 0.17400286272537724],\n     ['qasm', 'jordan_wigner', 'HF', 'COBYLA', 'RYRZ', 0.4356932354076565],\n     ['qasm', 'jordan_wigner', 'HF', 'COBYLA', 'SwapRZ', 1.0631772356496334],\n     ['qasm', 'jordan_wigner', 'HF', 'L_BFGS_B', 'UCCSD', 0.01600937790473167],\n     ['qasm', 'jordan_wigner', 'HF', 'L_BFGS_B', 'RY', 0.8936857011266549],\n     ['qasm', 'jordan_wigner', 'HF', 'L_BFGS_B', 'RYRZ', 0.6371450876564417],\n     ['qasm', 'jordan_wigner', 'HF', 'L_BFGS_B', 'SwapRZ', 1.0701905743185525],\n     ['qasm', 'jordan_wigner', 'HF', 'SLSQP', 'UCCSD', 0.012132299946344682],\n     ['qasm', 'jordan_wigner', 'HF', 'SLSQP', 'RY', 0.6722994602212315],\n     ['qasm', 'jordan_wigner', 'HF', 'SLSQP', 'RYRZ', 0.9594719384861813],\n     ['qasm', 'jordan_wigner', 'HF', 'SLSQP', 'SwapRZ', 1.0794790767843812],\n     ['qasm', 'jordan_wigner', 'HF', 'SPSA', 'UCCSD', 0.11472427238517235],\n     ['qasm', 'jordan_wigner', 'HF', 'SPSA', 'RY', 0.1189422603259136],\n     ['qasm', 'jordan_wigner', 'HF', 'SPSA', 'RYRZ', 0.22546875286239776],\n     ['qasm', 'jordan_wigner', 'HF', 'SPSA', 'SwapRZ', 1.0772077047070576],\n     ['qasm', 'jordan_wigner', 'Zero', 'COBYLA', 'UCCSD', 1.073484398424216],\n     ['qasm', 'jordan_wigner', 'Zero', 'COBYLA', 'RY', 0.1179316534800825],\n     ['qasm', 'jordan_wigner', 'Zero', 'COBYLA', 'RYRZ', 0.5518767840863128],\n     ['qasm', 'jordan_wigner', 'Zero', 'COBYLA', 'SwapRZ', 1.061025718285195],\n     ['qasm', 'jordan_wigner', 'Zero', 'L_BFGS_B', 'UCCSD', 1.0711899611298363],\n     ['qasm', 'jordan_wigner', 'Zero', 'L_BFGS_B', 'RY', 1.355856081722674],\n     ['qasm', 'jordan_wigner', 'Zero', 'L_BFGS_B', 'RYRZ', 0.7953593014084395],\n     ['qasm', 'jordan_wigner', 'Zero', 'L_BFGS_B', 'SwapRZ', 1.07134923965163],\n     ['qasm', 'jordan_wigner', 'Zero', 'SLSQP', 'UCCSD', 1.074547175219231],\n     ['qasm', 'jordan_wigner', 'Zero', 'SLSQP', 'RY', 0.9269793291405661],\n     ['qasm', 'jordan_wigner', 'Zero', 'SLSQP', 'RYRZ', 0.9884632419802364],\n     ['qasm', 'jordan_wigner', 'Zero', 'SLSQP', 'SwapRZ', 1.0739003195981933],\n     ['qasm', 'jordan_wigner', 'Zero', 'SPSA', 'UCCSD', 1.0741249008187221],\n     ['qasm', 'jordan_wigner', 'Zero', 'SPSA', 'RY', 0.3071623747852821],\n     ['qasm', 'jordan_wigner', 'Zero', 'SPSA', 'RYRZ', 0.35772213042557455],\n     ['qasm', 'jordan_wigner', 'Zero', 'SPSA', 'SwapRZ', 1.080568562681406]]\n\n\n\n\n```python\nsave_result('final_result_noise-free.txt', a)\n```\n\n\n```python\nfinal_result = pd.DataFrame(a).rename(columns={0: \"backend\", 1: \"qubit mapping\", 2: \"initial state\", 3: \"optimizer\", 4: \"variational form\", 5: \"absolute error\"})\ndir = '/content/drive/My Drive/Projects/Qiskit Global Summer School/'\nfinal_result.to_csv(dir + 'final_result_noise-free.csv')\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\ncounter = 0\nfor i in range (len(score_noisefree)):\n  if score_noisefree[i][0] == 'statevector' or score_noisefree[i][0] == 'qasm':\n    counter += 1\n\ncounter\n```\n\n\n\n\n    137\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\nref -1.0770597457346915\n-1.07702902531249\n\n-1.06453928070638\n\n\n```\n\n\n```python\n\n```\n\n\n```python\nimport qiskit.tools.jupyter\n%qiskit_version_table\n%qiskit_copyright\n```\n\n\n<h3>Version Information</h3><table><tr><th>Qiskit Software</th><th>Version</th></tr><tr><td>Qiskit</td><td>0.19.6</td></tr><tr><td>Terra</td><td>0.14.2</td></tr><tr><td>Aer</td><td>0.5.2</td></tr><tr><td>Ignis</td><td>0.3.3</td></tr><tr><td>Aqua</td><td>0.7.3</td></tr><tr><td>IBM Q Provider</td><td>0.7.2</td></tr><tr><th>System information</th></tr><tr><td>Python</td><td>3.8.3 (default, May 19 2020, 13:54:14) \n[Clang 10.0.0 ]</td></tr><tr><td>OS</td><td>Darwin</td></tr><tr><td>CPUs</td><td>4</td></tr><tr><td>Memory (Gb)</td><td>16.0</td></tr><tr><td colspan='2'>Thu Jul 23 13:53:19 2020 EDT</td></tr></table>\n\n\n\n<div style='width: 100%; background-color:#d5d9e0;padding-left: 10px; padding-bottom: 10px; padding-right: 10px; padding-top: 5px'><h3>This code is a part of Qiskit</h3><p>&copy; Copyright IBM 2017, 2020.</p><p>This code is licensed under the Apache License, Version 2.0. You may<br>obtain a copy of this license in the LICENSE.txt file in the root directory<br> of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.<p>Any modifications or derivative works of this code must retain this<br>copyright notice, and modified files need to carry a notice indicating<br>that they have been altered from the originals.</p></div>\n\n", "meta": {"hexsha": "055f745b76d07beada57980ec653563e7e876eac", "size": 449140, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Qiskit Global Summer School 2020/Qiskit Summer School Final Project VQE.ipynb", "max_stars_repo_name": "eraraya-ricardo/qiskit-events", "max_stars_repo_head_hexsha": "2092c389a03bd5041670fe967105ea4e4ab3a98d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Qiskit Global Summer School 2020/Qiskit Summer School Final Project VQE.ipynb", "max_issues_repo_name": "eraraya-ricardo/qiskit-events", "max_issues_repo_head_hexsha": "2092c389a03bd5041670fe967105ea4e4ab3a98d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Qiskit Global Summer School 2020/Qiskit Summer School Final Project VQE.ipynb", "max_forks_repo_name": "eraraya-ricardo/qiskit-events", "max_forks_repo_head_hexsha": "2092c389a03bd5041670fe967105ea4e4ab3a98d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 224570.0, "max_line_length": 449139, "alphanum_fraction": 0.8701050897, "converted": true, "num_tokens": 41266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1919327818250578, "lm_q2_score": 0.07696084363512665, "lm_q1q2_score": 0.01477130881049315}}
{"text": "# Ranking of articles using open-access citation-metadata\n\nScholarly publications have seen exponential growth in past decades, however, linear growth is estimated for the research topics. It suggests that numerous articles appear every day within a research field. Researchers invest their time and energy in keeping up-to-date with the current state-of-the-art. Research is a continuous process and it builds on the past work that has been done attributed through citations. Although, there are numerous reasons why a research article gets cited, as well as, its critics as to why citations should not be used to assess the value of current work. However, with the current information overload, it is not easy to keep abreast of all the published work. Researchers in 20th century would dig through all the available literature to find out the latest trends but the researcher of today has more stuff to read on a topic than their lifetime. They need access to current research as soon as it happens but the citation-count metrics, currently in practice, limit this approach. To use citation-based metrics, the articles must acquire a reasonable number of citations which can vary from field to field. Our main contribution is to use a heterogeneous network that includes the article, author and journal to recommend articles in a research field.\n\n# Import\n\n\n```python\nimport Ranking # from https://github.com/bilal-dsu/Ranking/\n\nfrom matplotlib import pyplot\nfrom scipy.stats import spearmanr\nimport json, os,sys,snap\nimport csv\nimport pandas as pd\nimport snap\nimport numpy as np\nimport re\nfrom itertools import combinations\nfrom os import path\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nimport measures # from https://github.com/dkaterenchuk/ranking_measures\n\n```\n\n# Initializations Total Citations\n\nThe original graph is filtered to work with nodes between the year 2000 till 2018, termed Total Citations (TC). Further, we remove any journals with zero out-degree since they do not participate in the ranking method.\n\n\n```python\n# following files must be present in the CWD\nmetaDataCSV = \"MetaData 2000-2018.csv\" \nArticleGraph = \"ArticleGraph.graph\"\nArticleHash = \"ArticleHash.hash\"\n\n# following files will be created in the CWD\nJournalCitationTXT = \"JournalCitation.txt\"\nJournalGraph = \"JournalGraph.graph\"\nJournalHash = \"JournalHash.hash\"\nJournalSubGraph = \"JournalSubGraph.graph\"\nSubMetaDataCSV = \"SubMetaData.csv\"\nAuthorCitationTXT = \"AuthorCitation.txt\"\nArticleCitationTXT = \"ArticleCitation.txt\"\nAuthorGraph = \"AuthorGraph.graph\"\nAuthorHash = \"AuthorHash.hash\"\n\nAuthorInfoCSV = \"AuthorInfo.csv\"\nJournalInfoCSV = \"JournalInfo.csv\"\nArticleInfoCSV = \"ArticleInfo.csv\"\n\nAuthorRankCSV = \"AuthorRank.csv\"\nJournalRankCSV = \"JournalRank.csv\"\nArticleRankCSV = \"ArticleRank.csv\"\n\nArticlesGraphStats=\"ArticleGraphStats.csv\"\nJournalGraphStats=\"JournalGraphStats.csv\"\nAuthorGraphStats=\"AuthorGraphStats.csv\"\nGraphStatsOverall=\"GraphStatsOverall.csv\"\n```\n\n# Generate Total Citations\n\n\n```python\nRanking.generateJournanalCitationNetworkText(metaDataCSV, JournalCitationTXT)\n```\n\n\n```python\nRanking.generateJournalCitationGraph(JournalCitationTXT, JournalGraph, JournalHash)\n```\n\n\n```python\nRanking.generateSubGraph(JournalHash, JournalGraph, JournalSubGraph, metaDataCSV, SubMetaDataCSV) \n```\n\n\n```python\nRanking.generateAuthorArticleCitationNetworkText(SubMetaDataCSV, AuthorCitationTXT, ArticleCitationTXT)\n```\n\n\n```python\nRanking.generateAuthorArticleGraph(AuthorCitationTXT, AuthorGraph, AuthorHash, ArticleCitationTXT, \n                           ArticleGraph, ArticleHash)\n```\n\n# Initializations Early Citations\n\nTo evaluate the ranking technique, we take nodes of the year 2005 and apply a cut-off on citations till 2010, termed Early Citations (EC).  The cutoff window is configurable. Only a few past years are considered to give equal chance to early career researchers.\n\n\n```python\n# Provide values for Early Citations cutoff\n\nRankYearStart = 2005\nRankYearEnd = 2005\nCutOffStart = 2000\nCutOffEnd = 2010\n\n# following files will be created in the CWD\n\nmetaDataRankYearCSV = \"metaData\" + str(RankYearStart)  + \"-\" + str(RankYearEnd) + \".csv\"\nmetaDataCutOffYearCSV = \"metaData\" + str(CutOffStart)  + \"-\" + str(CutOffEnd) + \".csv\"\n\nJournalCutOffYearTXT = \"Journal\" + str(CutOffStart)  + \"-\" + str(CutOffEnd) + \".txt\"\nJournalCutOffYearGraph = \"Journal\" + str(CutOffStart)  + \"-\" + str(CutOffEnd) + \".graph\"\nJournalCutOffYearHash = \"Journal\" + str(CutOffStart)  + \"-\" + str(CutOffEnd) + \".hash\"\nJournalCutOffYearInfoCSV = \"Journal\" + str(CutOffStart)  + \"-\" + str(CutOffEnd) + \"Info.csv\"\nJournalCutOffYearRankCSV = \"Journal\" + str(CutOffStart)  + \"-\" + str(CutOffEnd) + \"Rank.csv\"\n\nJournalCutOffYearSubGraph = \"JournalSubGraph\"+ str(CutOffStart)  + \"-\" + str(CutOffEnd) + \".graph\"\n\nArticleCutOffYearTXT = \"Article\" + str(CutOffStart)  + \"-\" + str(CutOffEnd) + \".txt\"\nArticleCutOffYearGraph = \"Article\" + str(CutOffStart)  + \"-\" + str(CutOffEnd) + \".graph\"\nArticleCutOffYearHash = \"Article\" + str(CutOffStart)  + \"-\" + str(CutOffEnd) + \".hash\"\nArticleCutOffYearInfoCSV = \"Article\" + str(CutOffStart)  + \"-\" + str(CutOffEnd) + \"Info.csv\"\nArticleCutOffYearRankCSV = \"Article\" + str(CutOffStart)  + \"-\" + str(CutOffEnd) + \"Rank.csv\"\n\nAuthorCutOffYearTXT = \"Author\" + str(CutOffStart)  + \"-\" + str(CutOffEnd) + \".txt\"\nAuthorCutOffYearGraph = \"Author\" + str(CutOffStart)  + \"-\" + str(CutOffEnd) + \".graph\"\nAuthorCutOffYearHash = \"Author\" + str(CutOffStart)  + \"-\" + str(CutOffEnd) + \".hash\"\nAuthorCutOffYearInfoCSV = \"Author\" + str(CutOffStart)  + \"-\" + str(CutOffEnd) + \"Info.csv\"\nAuthorCutOffYearRankCSV = \"Author\" + str(CutOffStart)  + \"-\" + str(CutOffEnd) + \"Rank.csv\"\n\nAuthorGraphStatsCutOffYear = \"AuthorGraphStats\" + str(CutOffStart)  + \"-\" + str(CutOffEnd) + \".csv\"\nArticleGraphStatsCutOffYear = \"ArticleGraphStats\" + str(CutOffStart)  + \"-\" + str(CutOffEnd) + \".csv\"\nJournalGraphStatsCutOffYear = \"JournalGraphStats\" + str(CutOffStart)  + \"-\" + str(CutOffEnd) + \".csv\"\nGraphStatsCutOffYear = \"GraphStats\" + str(CutOffStart)  + \"-\" + str(CutOffEnd) + \".csv\"\n```\n\n# Generate Early Citations\n\n\n```python\nRanking.generateTemporalNetwork(SubMetaDataCSV, RankYearStart,RankYearEnd, CutOffStart, CutOffEnd, \n                        metaDataRankYearCSV, metaDataCutOffYearCSV, ArticleHash, ArticleGraph)\n```\n\n\n```python\nRanking.generateJournanalCitationNetworkText(metaDataCutOffYearCSV, JournalCutOffYearTXT)\n```\n\n\n```python\nRanking.generateJournalCitationGraph(JournalCutOffYearTXT, JournalCutOffYearGraph, JournalCutOffYearHash)\n```\n\n\n```python\nRanking.generateAuthorArticleCitationNetworkText(metaDataCutOffYearCSV, AuthorCutOffYearTXT, ArticleCutOffYearTXT)\n```\n\n\n```python\nRanking.generateAuthorArticleGraph(AuthorCutOffYearTXT, AuthorCutOffYearGraph, AuthorCutOffYearHash, \n                           ArticleCutOffYearTXT, ArticleCutOffYearGraph, ArticleCutOffYearHash)\n```\n\n# Calculate Rank\n\nThe rank of a journal or author is given by the PageRank measure in Equation 1.\n\\begin{equation}\n\\label{eq:Rank}\nR(i) = ((1-\\alpha)/n) + \\alpha * \\sum_{\\substack{j}} R(j)\\frac{aij}{Ni}\n\\end{equation}\nwhere, n is the total no. of nodes in the network,\n\n$\\alpha$ $\\epsilon$ $(0 , 1)$ is damping factor (set to $0.85$),\n\naij is 1 if node (i) cites node (j) and 0 otherwise,\n\nNi is the total neighbours of node i.\n\nThe rank of journal and author is transferred to the article given by Equation 2, thereby, inflating the rank of the article which was cited by any influential journal or author. The rank of the article \u201ca\u201d published in journal \u201cb\u201d by the author(s) \u201cc\u201d is:\n\\begin{equation} \\label{eq:ArticleRank}\nAR(a) = ((1-\\beta) * R(b) + \\beta * \\frac {\\sum_{\\substack{i}} R (i)}{c})\n\\end{equation}\nwhere, $\\beta$ $\\epsilon$ $(0 , 1)$ is adjustment for weight-age of author and journal influence (set to $0.5$).\n\n\n```python\nRanking.generateAuthorJournalRank(AuthorHash, AuthorGraph, AuthorInfoCSV, JournalHash, JournalSubGraph, JournalInfoCSV, JournalGraphStats, AuthorGraphStats)\n```\n\n\n```python\nRanking.generateArticleRank(JournalInfoCSV, SubMetaDataCSV, ArticleGraph, ArticleHash, AuthorInfoCSV, ArticleInfoCSV, ArticlesGraphStats)\n```\n\n\n```python\nRanking.generateAuthorJournalRank(AuthorCutOffYearHash, AuthorCutOffYearGraph, AuthorCutOffYearInfoCSV, \n             JournalCutOffYearHash, JournalCutOffYearGraph, JournalCutOffYearInfoCSV, JournalGraphStatsCutOffYear,\n                           AuthorGraphStatsCutOffYear)\n```\n\n\n```python\nRanking.generateArticleRank(JournalCutOffYearInfoCSV, metaDataCutOffYearCSV, ArticleCutOffYearGraph, ArticleCutOffYearHash, \n                    AuthorCutOffYearInfoCSV, ArticleCutOffYearInfoCSV, ArticleGraphStatsCutOffYear)\n```\n\n# Analysis\n\nOn the temporal citation network, we correlate the EC rank of publications with the rank calculated using TC. It is used as a baseline for evaluating the ranking mechanism. To identify whether our technique captures key articles with a high EC rank that went on to attain a high rank in TC, we apply Spearman's rank correlation. Our preliminary analysis suggests that the ranking technique is stable. The rank calculated with EC correlates with rank calculated with TC. However, there is no significant correlation with citation count, suggesting that the technique does not rely on merely counting citations. It essentially means that instead of only counting citations the value of a citation coming from a reputable journal gets a higher rank.\n\n\n```python\nRanking.generateGraphStats(JournalGraphStats, AuthorGraphStats, ArticlesGraphStats, GraphStatsOverall)\n```\n\n\n```python\nRanking.generateGraphStats(JournalGraphStatsCutOffYear, AuthorGraphStatsCutOffYear, \n                   ArticleGraphStatsCutOffYear , GraphStatsCutOffYear)\n```\n\n\n```python\nRanking.correlationAnalysis(AuthorInfoCSV, AuthorCutOffYearInfoCSV, JournalInfoCSV, \n            JournalCutOffYearInfoCSV, ArticleInfoCSV, ArticleCutOffYearInfoCSV, metaDataRankYearCSV)\n\n```\n", "meta": {"hexsha": "425c4c04d80e88ef0fbc7b00e669923b480b30ad", "size": 14720, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Ranking.ipynb", "max_stars_repo_name": "bilal-dsu/Ranking", "max_stars_repo_head_hexsha": "b24ab89e18a9f3dc853b36d18c87c6933b5f1cdd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ranking.ipynb", "max_issues_repo_name": "bilal-dsu/Ranking", "max_issues_repo_head_hexsha": "b24ab89e18a9f3dc853b36d18c87c6933b5f1cdd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ranking.ipynb", "max_forks_repo_name": "bilal-dsu/Ranking", "max_forks_repo_head_hexsha": "b24ab89e18a9f3dc853b36d18c87c6933b5f1cdd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7082294264, "max_line_length": 1295, "alphanum_fraction": 0.6323369565, "converted": true, "num_tokens": 2541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32082131381216084, "lm_q2_score": 0.045352584747824255, "lm_q1q2_score": 0.014550075823574345}}
{"text": "# Running TensorTrade on SageMaker Studio\nThis notebook demonstrates running TensorTrade on SageMaker Studio. EOD data for any ETF/stock is fetched from [Yahoo Finance](https://finance.yahoo.com/) or S3 bucket. Experimental evidence shows that running on ml.g4dn.xlarge instance completes sooner than running on ml.t3.medium instance.\n\n\n```python\n!pip install pip --upgrade\n!pip install git+https://github.com/msrparadesi/tensortrade.git\n!pip install git+https://github.com/msrparadesi/tensortrade.git#egg=tensortrade[tf,tensorforce,baselines,ccxt,ta,fbm] -U\n!pip install yfinance ta matplotlib s3fs\n```\n\n    Collecting pip\n      Using cached pip-20.1.1-py2.py3-none-any.whl (1.5 MB)\n    Installing collected packages: pip\n      Attempting uninstall: pip\n        Found existing installation: pip 20.0.2\n        Uninstalling pip-20.0.2:\n          Successfully uninstalled pip-20.0.2\n    Successfully installed pip-20.1.1\n    Collecting git+https://github.com/msrparadesi/tensortrade.git\n      Cloning https://github.com/msrparadesi/tensortrade.git to /tmp/pip-req-build-i8sut2x8\n      Running command git clone -q https://github.com/msrparadesi/tensortrade.git /tmp/pip-req-build-i8sut2x8\n    Requirement already satisfied: numpy>=1.16.4 in /usr/local/lib/python3.6/dist-packages (from tensortrade==0.2.0b2) (1.18.2)\n    Collecting pandas>=0.25.0\n      Using cached pandas-1.0.5-cp36-cp36m-manylinux1_x86_64.whl (10.1 MB)\n    Processing ./.cache/pip/wheels/be/a1/84/6b4caa6c1cea703acbfea8a24cc3c1729bd359cd4a65755d8b/gym-0.17.2-py3-none-any.whl\n    Requirement already satisfied: pyyaml>=5.1.2 in /usr/local/lib/python3.6/dist-packages (from tensortrade==0.2.0b2) (5.3.1)\n    Collecting sympy>=1.4\n      Using cached sympy-1.6.1-py3-none-any.whl (5.8 MB)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.25.0->tensortrade==0.2.0b2) (2019.3)\n    Requirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.25.0->tensortrade==0.2.0b2) (2.8.1)\n    Collecting pyglet<=1.5.0,>=1.4.0\n      Using cached pyglet-1.5.0-py2.py3-none-any.whl (1.0 MB)\n    Requirement already satisfied: cloudpickle<1.4.0,>=1.2.0 in /usr/local/lib/python3.6/dist-packages (from gym>=0.14.0->tensortrade==0.2.0b2) (1.3.0)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from gym>=0.14.0->tensortrade==0.2.0b2) (1.2.2)\n    Processing ./.cache/pip/wheels/e8/38/69/aa17553ad31f09ff5fa44c8a1a6c5b47e7c9261e9c7c16b9fb/mpmath-1.1.0-py3-none-any.whl\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.6/dist-packages (from python-dateutil>=2.6.1->pandas>=0.25.0->tensortrade==0.2.0b2) (1.14.0)\n    Processing ./.cache/pip/wheels/6e/9c/ed/4499c9865ac1002697793e0ae05ba6be33553d098f3347fb94/future-0.18.2-py3-none-any.whl\n    Building wheels for collected packages: tensortrade\n      Building wheel for tensortrade (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Created wheel for tensortrade: filename=tensortrade-0.2.0b2-py3-none-any.whl size=120451 sha256=dfb755daa86b34133e6d3f900081783e2f67e7e1b9e304c62ebb587680ad67ca\n      Stored in directory: /tmp/pip-ephem-wheel-cache-cx0sif_b/wheels/7d/90/2a/bb771201465fd1314ad06c9290fdcc23ca3389e8b75ef54a32\n    Successfully built tensortrade\n    Installing collected packages: pandas, future, pyglet, gym, mpmath, sympy, tensortrade\n      Attempting uninstall: pandas\n        Found existing installation: pandas 0.24.2\n        Uninstalling pandas-0.24.2:\n          Successfully uninstalled pandas-0.24.2\n    Successfully installed future-0.18.2 gym-0.17.2 mpmath-1.1.0 pandas-1.0.5 pyglet-1.5.0 sympy-1.6.1 tensortrade-0.2.0b2\n    Collecting tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]\n      Cloning https://github.com/msrparadesi/tensortrade.git to /tmp/pip-install-1s0vibmz/tensortrade\n      Running command git clone -q https://github.com/msrparadesi/tensortrade.git /tmp/pip-install-1s0vibmz/tensortrade\n    \u001b[33m  WARNING: tensortrade 0.2.0b2 does not provide the extra 'baselines'\u001b[0m\n    \u001b[33m  WARNING: tensortrade 0.2.0b2 does not provide the extra 'ccxt'\u001b[0m\n    \u001b[33m  WARNING: tensortrade 0.2.0b2 does not provide the extra 'fbm'\u001b[0m\n    \u001b[33m  WARNING: tensortrade 0.2.0b2 does not provide the extra 'ta'\u001b[0m\n    \u001b[33m  WARNING: tensortrade 0.2.0b2 does not provide the extra 'tensorforce'\u001b[0m\n    Requirement already satisfied, skipping upgrade: numpy>=1.16.4 in /usr/local/lib/python3.6/dist-packages (from tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (1.18.2)\n    Requirement already satisfied, skipping upgrade: pandas>=0.25.0 in /usr/local/lib/python3.6/dist-packages (from tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (1.0.5)\n    Requirement already satisfied, skipping upgrade: gym>=0.14.0 in /usr/local/lib/python3.6/dist-packages (from tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (0.17.2)\n    Requirement already satisfied, skipping upgrade: pyyaml>=5.1.2 in /usr/local/lib/python3.6/dist-packages (from tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (5.3.1)\n    Requirement already satisfied, skipping upgrade: sympy>=1.4 in /usr/local/lib/python3.6/dist-packages (from tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (1.6.1)\n    Collecting tensorflow>=2.1.0\n      Using cached tensorflow-2.2.0-cp36-cp36m-manylinux2010_x86_64.whl (516.2 MB)\n    Requirement already satisfied, skipping upgrade: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.25.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (2019.3)\n    Requirement already satisfied, skipping upgrade: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.25.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (2.8.1)\n    Requirement already satisfied, skipping upgrade: scipy in /usr/local/lib/python3.6/dist-packages (from gym>=0.14.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (1.2.2)\n    Requirement already satisfied, skipping upgrade: cloudpickle<1.4.0,>=1.2.0 in /usr/local/lib/python3.6/dist-packages (from gym>=0.14.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (1.3.0)\n    Requirement already satisfied, skipping upgrade: pyglet<=1.5.0,>=1.4.0 in /usr/local/lib/python3.6/dist-packages (from gym>=0.14.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (1.5.0)\n    Requirement already satisfied, skipping upgrade: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy>=1.4->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (1.1.0)\n    Requirement already satisfied, skipping upgrade: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2.1.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (1.27.2)\n    Collecting tensorflow-estimator<2.3.0,>=2.2.0\n      Using cached tensorflow_estimator-2.2.0-py2.py3-none-any.whl (454 kB)\n    Requirement already satisfied, skipping upgrade: six>=1.12.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2.1.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (1.14.0)\n    Requirement already satisfied, skipping upgrade: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2.1.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (3.2.0)\n    Requirement already satisfied, skipping upgrade: protobuf>=3.8.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2.1.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (3.11.3)\n    Requirement already satisfied, skipping upgrade: keras-preprocessing>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2.1.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (1.1.0)\n    Collecting astunparse==1.6.3\n      Using cached astunparse-1.6.3-py2.py3-none-any.whl (12 kB)\n    Collecting gast==0.3.3\n      Using cached gast-0.3.3-py2.py3-none-any.whl (9.7 kB)\n    Requirement already satisfied, skipping upgrade: google-pasta>=0.1.8 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2.1.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (0.2.0)\n    Requirement already satisfied, skipping upgrade: wheel>=0.26; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2.1.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (0.34.2)\n    Requirement already satisfied, skipping upgrade: absl-py>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2.1.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (0.9.0)\n    Requirement already satisfied, skipping upgrade: h5py<2.11.0,>=2.10.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2.1.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (2.10.0)\n    Requirement already satisfied, skipping upgrade: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2.1.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (1.1.0)\n    Collecting tensorboard<2.3.0,>=2.2.0\n      Using cached tensorboard-2.2.2-py3-none-any.whl (3.0 MB)\n    Requirement already satisfied, skipping upgrade: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow>=2.1.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (1.12.1)\n    Requirement already satisfied, skipping upgrade: future in /usr/local/lib/python3.6/dist-packages (from pyglet<=1.5.0,>=1.4.0->gym>=0.14.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (0.18.2)\n    Requirement already satisfied, skipping upgrade: setuptools in /usr/local/lib/python3.6/dist-packages (from protobuf>=3.8.0->tensorflow>=2.1.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (46.0.0)\n    Requirement already satisfied, skipping upgrade: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow>=2.1.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (0.15.5)\n    Collecting google-auth<2,>=1.6.3\n      Using cached google_auth-1.18.0-py2.py3-none-any.whl (90 kB)\n    Collecting tensorboard-plugin-wit>=1.6.0\n      Using cached tensorboard_plugin_wit-1.7.0-py3-none-any.whl (779 kB)\n    Requirement already satisfied, skipping upgrade: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow>=2.1.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (3.2.1)\n    Requirement already satisfied, skipping upgrade: requests<3,>=2.21.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow>=2.1.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (2.22.0)\n    Collecting google-auth-oauthlib<0.5,>=0.4.1\n      Using cached google_auth_oauthlib-0.4.1-py2.py3-none-any.whl (18 kB)\n    Collecting cachetools<5.0,>=2.0.0\n      Using cached cachetools-4.1.1-py3-none-any.whl (10 kB)\n    Requirement already satisfied, skipping upgrade: rsa<5,>=3.1.4; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow>=2.1.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (3.4.2)\n    Collecting pyasn1-modules>=0.2.1\n      Using cached pyasn1_modules-0.2.8-py2.py3-none-any.whl (155 kB)\n    Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow>=2.1.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (3.0.4)\n    Requirement already satisfied, skipping upgrade: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow>=2.1.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (1.25.8)\n    Requirement already satisfied, skipping upgrade: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow>=2.1.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (2.8)\n    Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow>=2.1.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (2019.11.28)\n    Collecting requests-oauthlib>=0.7.0\n      Using cached requests_oauthlib-1.3.0-py2.py3-none-any.whl (23 kB)\n    Requirement already satisfied, skipping upgrade: pyasn1>=0.1.3 in /usr/local/lib/python3.6/dist-packages (from rsa<5,>=3.1.4; python_version >= \"3\"->google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow>=2.1.0->tensortrade[baselines,ccxt,fbm,ta,tensorforce,tf]) (0.4.8)\n    Collecting oauthlib>=3.0.0\n      Using cached oauthlib-3.1.0-py2.py3-none-any.whl (147 kB)\n    Building wheels for collected packages: tensortrade\n      Building wheel for tensortrade (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Created wheel for tensortrade: filename=tensortrade-0.2.0b2-py3-none-any.whl size=120451 sha256=a0e4ed3804a1a0ac07b6d9b02ecb42a6ddcc7e1bbedaa7a7815f881d0fbdfa58\n      Stored in directory: /tmp/pip-ephem-wheel-cache-aarnqgx6/wheels/7d/90/2a/bb771201465fd1314ad06c9290fdcc23ca3389e8b75ef54a32\n    Successfully built tensortrade\n    \u001b[31mERROR: tensorflow-gpu 1.15.2 has requirement gast==0.2.2, but you'll have gast 0.3.3 which is incompatible.\u001b[0m\n    \u001b[31mERROR: tensorflow-gpu 1.15.2 has requirement tensorboard<1.16.0,>=1.15.0, but you'll have tensorboard 2.2.2 which is incompatible.\u001b[0m\n    \u001b[31mERROR: tensorflow-gpu 1.15.2 has requirement tensorflow-estimator==1.15.1, but you'll have tensorflow-estimator 2.2.0 which is incompatible.\u001b[0m\n    \u001b[31mERROR: tensorflow 2.2.0 has requirement scipy==1.4.1; python_version >= \"3\", but you'll have scipy 1.2.2 which is incompatible.\u001b[0m\n    Installing collected packages: tensorflow-estimator, astunparse, gast, cachetools, pyasn1-modules, google-auth, tensorboard-plugin-wit, oauthlib, requests-oauthlib, google-auth-oauthlib, tensorboard, tensorflow, tensortrade\n      Attempting uninstall: tensorflow-estimator\n        Found existing installation: tensorflow-estimator 1.15.1\n        Uninstalling tensorflow-estimator-1.15.1:\n          Successfully uninstalled tensorflow-estimator-1.15.1\n      Attempting uninstall: gast\n        Found existing installation: gast 0.2.2\n        Uninstalling gast-0.2.2:\n          Successfully uninstalled gast-0.2.2\n      Attempting uninstall: tensorboard\n        Found existing installation: tensorboard 1.15.0\n        Uninstalling tensorboard-1.15.0:\n          Successfully uninstalled tensorboard-1.15.0\n      Attempting uninstall: tensortrade\n        Found existing installation: tensortrade 0.2.0b2\n        Uninstalling tensortrade-0.2.0b2:\n          Successfully uninstalled tensortrade-0.2.0b2\n    Successfully installed astunparse-1.6.3 cachetools-4.1.1 gast-0.3.3 google-auth-1.18.0 google-auth-oauthlib-0.4.1 oauthlib-3.1.0 pyasn1-modules-0.2.8 requests-oauthlib-1.3.0 tensorboard-2.2.2 tensorboard-plugin-wit-1.7.0 tensorflow-2.2.0 tensorflow-estimator-2.2.0 tensortrade-0.2.0b2\n    Processing ./.cache/pip/wheels/6f/ad/f4/4a269deab015672fd1ab353d6b2c3fcf64f413980737c13541/yfinance-0.1.54-py2.py3-none-any.whl\n    Processing ./.cache/pip/wheels/29/57/ae/6f5b674713533f27be1da94af552aa867186a81b67639c96b1/ta-0.5.25-py3-none-any.whl\n    Collecting matplotlib\n      Using cached matplotlib-3.2.2-cp36-cp36m-manylinux1_x86_64.whl (12.4 MB)\n    Collecting s3fs\n      Using cached s3fs-0.4.2-py3-none-any.whl (19 kB)\n    Requirement already satisfied: pandas>=0.24 in /usr/local/lib/python3.6/dist-packages (from yfinance) (1.0.5)\n    Requirement already satisfied: requests>=2.20 in /usr/local/lib/python3.6/dist-packages (from yfinance) (2.22.0)\n    Processing ./.cache/pip/wheels/5e/8a/c4/59c699498647c7c94b14c87a904ca7540646107b3d94b7c320/multitasking-0.0.9-py3-none-any.whl\n    Requirement already satisfied: numpy>=1.15 in /usr/local/lib/python3.6/dist-packages (from yfinance) (1.18.2)\n    Collecting kiwisolver>=1.0.1\n      Using cached kiwisolver-1.2.0-cp36-cp36m-manylinux1_x86_64.whl (88 kB)\n    Collecting cycler>=0.10\n      Using cached cycler-0.10.0-py2.py3-none-any.whl (6.5 kB)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib) (2.8.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib) (2.4.6)\n    Requirement already satisfied: botocore>=1.12.91 in /usr/local/lib/python3.6/dist-packages (from s3fs) (1.15.24)\n    Collecting fsspec>=0.6.0\n      Using cached fsspec-0.7.4-py3-none-any.whl (75 kB)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.24->yfinance) (2019.3)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.20->yfinance) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests>=2.20->yfinance) (2019.11.28)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests>=2.20->yfinance) (1.25.8)\n    Requirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.20->yfinance) (2.8)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from cycler>=0.10->matplotlib) (1.14.0)\n    Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in /usr/local/lib/python3.6/dist-packages (from botocore>=1.12.91->s3fs) (0.9.5)\n    Requirement already satisfied: docutils<0.16,>=0.10 in /usr/local/lib/python3.6/dist-packages (from botocore>=1.12.91->s3fs) (0.15.2)\n    Installing collected packages: multitasking, yfinance, ta, kiwisolver, cycler, matplotlib, fsspec, s3fs\n    Successfully installed cycler-0.10.0 fsspec-0.7.4 kiwisolver-1.2.0 matplotlib-3.2.2 multitasking-0.0.9 s3fs-0.4.2 ta-0.5.25 yfinance-0.1.54\n\n\n### Declare variables that are used in this analysis\n\n\n```python\nsymbol = 'SPY'\nexchange = 'NASDAQ'\nstart_date = '2010-01-01'\nend_date = '2020-06-30'\n```\n\n### Fetch EOD data of ETF/stock\nOption 1: Fetch data from Yahoo Finance\n\n\n```python\nimport yfinance as yf\ndata = yf.download(symbol, start=start_date, end=end_date)\ndata.head()\n```\n\n    [*********************100%***********************]  1 of 1 completed\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Open</th>\n      <th>High</th>\n      <th>Low</th>\n      <th>Close</th>\n      <th>Adj Close</th>\n      <th>Volume</th>\n    </tr>\n    <tr>\n      <th>Date</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2010-01-04</th>\n      <td>112.370003</td>\n      <td>113.389999</td>\n      <td>111.510002</td>\n      <td>113.330002</td>\n      <td>91.841896</td>\n      <td>118944600</td>\n    </tr>\n    <tr>\n      <th>2010-01-05</th>\n      <td>113.260002</td>\n      <td>113.680000</td>\n      <td>112.849998</td>\n      <td>113.629997</td>\n      <td>92.084984</td>\n      <td>111579900</td>\n    </tr>\n    <tr>\n      <th>2010-01-06</th>\n      <td>113.519997</td>\n      <td>113.989998</td>\n      <td>113.430000</td>\n      <td>113.709999</td>\n      <td>92.149803</td>\n      <td>116074400</td>\n    </tr>\n    <tr>\n      <th>2010-01-07</th>\n      <td>113.500000</td>\n      <td>114.330002</td>\n      <td>113.180000</td>\n      <td>114.190002</td>\n      <td>92.538841</td>\n      <td>131091100</td>\n    </tr>\n    <tr>\n      <th>2010-01-08</th>\n      <td>113.889999</td>\n      <td>114.620003</td>\n      <td>113.660004</td>\n      <td>114.570000</td>\n      <td>92.846756</td>\n      <td>126402800</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n(Optional) Save the ETF/stock EOD data in S3\n\n\n```python\nimport sagemaker\nbucket = sagemaker.Session().default_bucket()\nprefix = 'data/'\ndata.reset_index(inplace=True)\ndata.to_csv('s3://'+ bucket + '/' + prefix + symbol + '.csv', index=False)\n```\n\nOption 2: Fetch data from S3 bucket\n\n\n```python\n#import io\nimport pandas as pd\nimport sagemaker\nbucket = sagemaker.Session().default_bucket()\nprefix = 'data/'\ndata = pd.read_csv('s3://' + bucket + '/' + prefix + symbol + '.csv')\ndata.set_index('Date', inplace=True)\ndata.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Open</th>\n      <th>High</th>\n      <th>Low</th>\n      <th>Close</th>\n      <th>Adj Close</th>\n      <th>Volume</th>\n    </tr>\n    <tr>\n      <th>Date</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2010-01-04</th>\n      <td>112.370003</td>\n      <td>113.389999</td>\n      <td>111.510002</td>\n      <td>113.330002</td>\n      <td>91.841896</td>\n      <td>118944600</td>\n    </tr>\n    <tr>\n      <th>2010-01-05</th>\n      <td>113.260002</td>\n      <td>113.680000</td>\n      <td>112.849998</td>\n      <td>113.629997</td>\n      <td>92.084984</td>\n      <td>111579900</td>\n    </tr>\n    <tr>\n      <th>2010-01-06</th>\n      <td>113.519997</td>\n      <td>113.989998</td>\n      <td>113.430000</td>\n      <td>113.709999</td>\n      <td>92.149803</td>\n      <td>116074400</td>\n    </tr>\n    <tr>\n      <th>2010-01-07</th>\n      <td>113.500000</td>\n      <td>114.330002</td>\n      <td>113.180000</td>\n      <td>114.190002</td>\n      <td>92.538841</td>\n      <td>131091100</td>\n    </tr>\n    <tr>\n      <th>2010-01-08</th>\n      <td>113.889999</td>\n      <td>114.620003</td>\n      <td>113.660004</td>\n      <td>114.570000</td>\n      <td>92.846756</td>\n      <td>126402800</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n### Generate features based on [technical analysis](https://github.com/bukosabino/ta) of the ETF/stock\n\n\n```python\nimport ta\nta.add_all_ta_features(data, 'Open', 'High', 'Low', 'Close', 'Volume', fillna=True)\ndata.columns = [symbol + \":\" + name.lower() for name in data.columns]\ndata.head()\n```\n\n    /usr/local/lib/python3.6/dist-packages/ta/trend.py:608: RuntimeWarning: invalid value encountered in double_scalars\n      dip[i] = 100 * (self._dip[i]/self._trs[i])\n    /usr/local/lib/python3.6/dist-packages/ta/trend.py:612: RuntimeWarning: invalid value encountered in double_scalars\n      din[i] = 100 * (self._din[i]/self._trs[i])\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>SPY:open</th>\n      <th>SPY:high</th>\n      <th>SPY:low</th>\n      <th>SPY:close</th>\n      <th>SPY:adj close</th>\n      <th>SPY:volume</th>\n      <th>SPY:volume_adi</th>\n      <th>SPY:volume_obv</th>\n      <th>SPY:volume_cmf</th>\n      <th>SPY:volume_fi</th>\n      <th>...</th>\n      <th>SPY:momentum_uo</th>\n      <th>SPY:momentum_stoch</th>\n      <th>SPY:momentum_stoch_signal</th>\n      <th>SPY:momentum_wr</th>\n      <th>SPY:momentum_ao</th>\n      <th>SPY:momentum_kama</th>\n      <th>SPY:momentum_roc</th>\n      <th>SPY:others_dr</th>\n      <th>SPY:others_dlr</th>\n      <th>SPY:others_cr</th>\n    </tr>\n    <tr>\n      <th>Date</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2010-01-04</th>\n      <td>112.370003</td>\n      <td>113.389999</td>\n      <td>111.510002</td>\n      <td>113.330002</td>\n      <td>91.841896</td>\n      <td>118944600</td>\n      <td>1.113527e+08</td>\n      <td>118944600</td>\n      <td>0.936173</td>\n      <td>0.000000e+00</td>\n      <td>...</td>\n      <td>0.000000</td>\n      <td>96.808636</td>\n      <td>96.808636</td>\n      <td>-3.191364</td>\n      <td>0.0</td>\n      <td>113.330002</td>\n      <td>0.0</td>\n      <td>-43.637407</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>2010-01-05</th>\n      <td>113.260002</td>\n      <td>113.680000</td>\n      <td>112.849998</td>\n      <td>113.629997</td>\n      <td>92.084984</td>\n      <td>111579900</td>\n      <td>2.094884e+08</td>\n      <td>230524500</td>\n      <td>0.908747</td>\n      <td>3.347346e+07</td>\n      <td>...</td>\n      <td>28.782253</td>\n      <td>97.695710</td>\n      <td>97.252173</td>\n      <td>-2.304290</td>\n      <td>0.0</td>\n      <td>113.471767</td>\n      <td>0.0</td>\n      <td>0.264710</td>\n      <td>0.264360</td>\n      <td>0.264710</td>\n    </tr>\n    <tr>\n      <th>2010-01-06</th>\n      <td>113.519997</td>\n      <td>113.989998</td>\n      <td>113.430000</td>\n      <td>113.709999</td>\n      <td>92.149803</td>\n      <td>116074400</td>\n      <td>2.094884e+08</td>\n      <td>346598900</td>\n      <td>0.604412</td>\n      <td>3.001813e+07</td>\n      <td>...</td>\n      <td>32.415861</td>\n      <td>88.709707</td>\n      <td>94.404684</td>\n      <td>-11.290293</td>\n      <td>0.0</td>\n      <td>113.584301</td>\n      <td>0.0</td>\n      <td>0.070406</td>\n      <td>0.070381</td>\n      <td>0.335302</td>\n    </tr>\n    <tr>\n      <th>2010-01-07</th>\n      <td>113.500000</td>\n      <td>114.330002</td>\n      <td>113.180000</td>\n      <td>114.190002</td>\n      <td>92.538841</td>\n      <td>131091100</td>\n      <td>3.086619e+08</td>\n      <td>477690000</td>\n      <td>0.646155</td>\n      <td>3.471899e+07</td>\n      <td>...</td>\n      <td>46.832592</td>\n      <td>95.035482</td>\n      <td>93.813633</td>\n      <td>-4.964518</td>\n      <td>0.0</td>\n      <td>113.859769</td>\n      <td>0.0</td>\n      <td>0.422129</td>\n      <td>0.421241</td>\n      <td>0.758846</td>\n    </tr>\n    <tr>\n      <th>2010-01-08</th>\n      <td>113.889999</td>\n      <td>114.620003</td>\n      <td>113.660004</td>\n      <td>114.570000</td>\n      <td>92.846756</td>\n      <td>126402800</td>\n      <td>4.218969e+08</td>\n      <td>604092800</td>\n      <td>0.698398</td>\n      <td>3.662095e+07</td>\n      <td>...</td>\n      <td>55.390283</td>\n      <td>98.392185</td>\n      <td>94.045791</td>\n      <td>-1.607815</td>\n      <td>0.0</td>\n      <td>114.186429</td>\n      <td>0.0</td>\n      <td>0.332776</td>\n      <td>0.332224</td>\n      <td>1.094148</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 78 columns</p>\n</div>\n\n\n\n### Create a 'DataFeed' for the Gym TradingEnvironment to be able to observe and make actions about\n- Make a list of Stream objects, one for each DataFrame column\n\n\n```python\nfrom tensortrade.data import Module, Stream\n\nwith Module(exchange) as node_stream:\n    nodes = []\n    for name in data.columns:\n        nodes.append(Stream(list(data[name]), name))\n```\n\n\n```python\nfrom tensortrade.data import DataFeed\ndata_feed = DataFeed([node_stream])\n```\n\n\n```python\ndata_feed.next() # Show 1 slice of the data\n```\n\n\n\n\n    {'NASDAQ:/SPY:open': 112.37000274658205,\n     'NASDAQ:/SPY:high': 113.38999938964844,\n     'NASDAQ:/SPY:low': 111.51000213623048,\n     'NASDAQ:/SPY:close': 113.33000183105469,\n     'NASDAQ:/SPY:adj close': 91.8418960571289,\n     'NASDAQ:/SPY:volume': 118944600,\n     'NASDAQ:/SPY:volume_adi': 111352689.32573092,\n     'NASDAQ:/SPY:volume_obv': 118944600,\n     'NASDAQ:/SPY:volume_cmf': 0.9361727167583137,\n     'NASDAQ:/SPY:volume_fi': 0.0,\n     'NASDAQ:/SPY:momentum_mfi': 50.0,\n     'NASDAQ:/SPY:volume_em': 0.0,\n     'NASDAQ:/SPY:volume_sma_em': 0.0,\n     'NASDAQ:/SPY:volume_vpt': -52024532.18648957,\n     'NASDAQ:/SPY:volume_nvi': 1000.0,\n     'NASDAQ:/SPY:volume_vwap': 112.7433344523112,\n     'NASDAQ:/SPY:volatility_atr': 0.0,\n     'NASDAQ:/SPY:volatility_bbm': 113.33000183105469,\n     'NASDAQ:/SPY:volatility_bbh': 113.33000183105469,\n     'NASDAQ:/SPY:volatility_bbl': 113.33000183105469,\n     'NASDAQ:/SPY:volatility_bbw': 0.0,\n     'NASDAQ:/SPY:volatility_bbp': 0.0,\n     'NASDAQ:/SPY:volatility_bbhi': 0.0,\n     'NASDAQ:/SPY:volatility_bbli': 0.0,\n     'NASDAQ:/SPY:volatility_kcc': 112.7433344523112,\n     'NASDAQ:/SPY:volatility_kch': 114.62333170572917,\n     'NASDAQ:/SPY:volatility_kcl': 110.86333719889325,\n     'NASDAQ:/SPY:volatility_kcw': 3.335003816501761,\n     'NASDAQ:/SPY:volatility_kcp': 0.6560287861263832,\n     'NASDAQ:/SPY:volatility_kchi': 0.0,\n     'NASDAQ:/SPY:volatility_kcli': 0.0,\n     'NASDAQ:/SPY:volatility_dcl': 1.6588698694459896,\n     'NASDAQ:/SPY:volatility_dch': 0.9680863583791569,\n     'NASDAQ:/SPY:trend_macd': 0.0,\n     'NASDAQ:/SPY:trend_macd_signal': 0.0,\n     'NASDAQ:/SPY:trend_macd_diff': 0.0,\n     'NASDAQ:/SPY:trend_sma_fast': 113.33000183105469,\n     'NASDAQ:/SPY:trend_sma_slow': 113.33000183105469,\n     'NASDAQ:/SPY:trend_ema_fast': 113.33000183105469,\n     'NASDAQ:/SPY:trend_ema_slow': 113.33000183105469,\n     'NASDAQ:/SPY:trend_adx': 0.0,\n     'NASDAQ:/SPY:trend_adx_pos': 0.0,\n     'NASDAQ:/SPY:trend_adx_neg': 0.0,\n     'NASDAQ:/SPY:trend_vortex_ind_pos': 0.0,\n     'NASDAQ:/SPY:trend_vortex_ind_neg': 0.0,\n     'NASDAQ:/SPY:trend_vortex_ind_diff': 0.0,\n     'NASDAQ:/SPY:trend_trix': -43.20567852926306,\n     'NASDAQ:/SPY:trend_mass_index': 1.0,\n     'NASDAQ:/SPY:trend_cci': 0.0,\n     'NASDAQ:/SPY:trend_dpo': 87.74307761047825,\n     'NASDAQ:/SPY:trend_kst': -436.3740678472662,\n     'NASDAQ:/SPY:trend_kst_sig': -436.3740678472662,\n     'NASDAQ:/SPY:trend_kst_diff': 0.0,\n     'NASDAQ:/SPY:trend_ichimoku_conv': 112.45000076293945,\n     'NASDAQ:/SPY:trend_ichimoku_base': 112.45000076293945,\n     'NASDAQ:/SPY:trend_ichimoku_a': 112.45000076293945,\n     'NASDAQ:/SPY:trend_ichimoku_b': 112.45000076293945,\n     'NASDAQ:/SPY:trend_visual_ichimoku_a': 199.68840442570772,\n     'NASDAQ:/SPY:trend_visual_ichimoku_b': 197.45571224183746,\n     'NASDAQ:/SPY:trend_aroon_up': 4.0,\n     'NASDAQ:/SPY:trend_aroon_down': 4.0,\n     'NASDAQ:/SPY:trend_aroon_ind': 0.0,\n     'NASDAQ:/SPY:trend_psar_up': -1.0,\n     'NASDAQ:/SPY:trend_psar_down': -1.0,\n     'NASDAQ:/SPY:trend_psar_up_indicator': 0.0,\n     'NASDAQ:/SPY:trend_psar_down_indicator': 0.0,\n     'NASDAQ:/SPY:momentum_rsi': 100.0,\n     'NASDAQ:/SPY:momentum_tsi': 0.0,\n     'NASDAQ:/SPY:momentum_uo': 0.0,\n     'NASDAQ:/SPY:momentum_stoch': 96.80863583791569,\n     'NASDAQ:/SPY:momentum_stoch_signal': 96.80863583791569,\n     'NASDAQ:/SPY:momentum_wr': -3.1913641620843127,\n     'NASDAQ:/SPY:momentum_ao': 0.0,\n     'NASDAQ:/SPY:momentum_kama': 113.33000183105469,\n     'NASDAQ:/SPY:momentum_roc': 0.0,\n     'NASDAQ:/SPY:others_dr': -43.63740678472663,\n     'NASDAQ:/SPY:others_dlr': 0.0,\n     'NASDAQ:/SPY:others_cr': 0.0}\n\n\n\n### Define Exchange\nAn exchange needs a name, an execution service, and streams of price data in order to function properly.\n\nThe setups supported right now are the simulated execution service using simulated or stochastic data. \n\nMore execution services will be made available in the future, as well as price streams so that live data and execution can be supported.\n\n\n```python\nfrom tensortrade.exchanges import Exchange\nfrom tensortrade.exchanges.services.execution.simulated import execute_order\n\n# Make a stream of closing prices to make orders on\nexchange = Exchange(\"sim-exchange\", service=execute_order)(Stream(list(data['SPY:close']), \"USD-SPY\"))\n```\n\n### Portfolio\n- Pass in as many Wallet objects as assets you are working with\n- This example uses SPY as an instrument, the complete list of instruments are available [here](https://github.com/msrparadesi/tensortrade/blob/master/tensortrade/instruments/instrument.py)\n\n\n```python\nfrom tensortrade.instruments import USD, SPY\nfrom tensortrade.wallets import Portfolio, Wallet\n\nportfolio = Portfolio(\n    base_instrument = USD,\n    wallets = [Wallet(exchange, 100000 * USD),\n               Wallet(exchange, 0 * SPY)]\n)\n```\n\n### Gym Environment\n- We pass in the datafeed + portfolio objects\n- And set as many other parameters as desired\n\n\n```python\nfrom tensortrade.environments import TradingEnvironment\n\nenv = TradingEnvironment(\n    feed=data_feed,\n    portfolio=portfolio,\n    action_scheme='managed-risk',\n    reward_scheme='risk-adjusted',\n    window_size=20\n)\n```\n\n#### Example DataFeed Observation at any given step in the data\n\n\n```python\nenv.feed.next() # Show 1 slice of the feed's data\n```\n\n\n\n\n    {'NASDAQ:/SPY:open': 112.37000274658205,\n     'NASDAQ:/SPY:high': 113.38999938964844,\n     'NASDAQ:/SPY:low': 111.51000213623048,\n     'NASDAQ:/SPY:close': 113.33000183105469,\n     'NASDAQ:/SPY:adj close': 91.8418960571289,\n     'NASDAQ:/SPY:volume': 118944600,\n     'NASDAQ:/SPY:volume_adi': 111352689.32573092,\n     'NASDAQ:/SPY:volume_obv': 118944600,\n     'NASDAQ:/SPY:volume_cmf': 0.9361727167583137,\n     'NASDAQ:/SPY:volume_fi': 0.0,\n     'NASDAQ:/SPY:momentum_mfi': 50.0,\n     'NASDAQ:/SPY:volume_em': 0.0,\n     'NASDAQ:/SPY:volume_sma_em': 0.0,\n     'NASDAQ:/SPY:volume_vpt': -52024532.18648957,\n     'NASDAQ:/SPY:volume_nvi': 1000.0,\n     'NASDAQ:/SPY:volume_vwap': 112.7433344523112,\n     'NASDAQ:/SPY:volatility_atr': 0.0,\n     'NASDAQ:/SPY:volatility_bbm': 113.33000183105469,\n     'NASDAQ:/SPY:volatility_bbh': 113.33000183105469,\n     'NASDAQ:/SPY:volatility_bbl': 113.33000183105469,\n     'NASDAQ:/SPY:volatility_bbw': 0.0,\n     'NASDAQ:/SPY:volatility_bbp': 0.0,\n     'NASDAQ:/SPY:volatility_bbhi': 0.0,\n     'NASDAQ:/SPY:volatility_bbli': 0.0,\n     'NASDAQ:/SPY:volatility_kcc': 112.7433344523112,\n     'NASDAQ:/SPY:volatility_kch': 114.62333170572917,\n     'NASDAQ:/SPY:volatility_kcl': 110.86333719889325,\n     'NASDAQ:/SPY:volatility_kcw': 3.335003816501761,\n     'NASDAQ:/SPY:volatility_kcp': 0.6560287861263832,\n     'NASDAQ:/SPY:volatility_kchi': 0.0,\n     'NASDAQ:/SPY:volatility_kcli': 0.0,\n     'NASDAQ:/SPY:volatility_dcl': 1.6588698694459896,\n     'NASDAQ:/SPY:volatility_dch': 0.9680863583791569,\n     'NASDAQ:/SPY:trend_macd': 0.0,\n     'NASDAQ:/SPY:trend_macd_signal': 0.0,\n     'NASDAQ:/SPY:trend_macd_diff': 0.0,\n     'NASDAQ:/SPY:trend_sma_fast': 113.33000183105469,\n     'NASDAQ:/SPY:trend_sma_slow': 113.33000183105469,\n     'NASDAQ:/SPY:trend_ema_fast': 113.33000183105469,\n     'NASDAQ:/SPY:trend_ema_slow': 113.33000183105469,\n     'NASDAQ:/SPY:trend_adx': 0.0,\n     'NASDAQ:/SPY:trend_adx_pos': 0.0,\n     'NASDAQ:/SPY:trend_adx_neg': 0.0,\n     'NASDAQ:/SPY:trend_vortex_ind_pos': 0.0,\n     'NASDAQ:/SPY:trend_vortex_ind_neg': 0.0,\n     'NASDAQ:/SPY:trend_vortex_ind_diff': 0.0,\n     'NASDAQ:/SPY:trend_trix': -43.20567852926306,\n     'NASDAQ:/SPY:trend_mass_index': 1.0,\n     'NASDAQ:/SPY:trend_cci': 0.0,\n     'NASDAQ:/SPY:trend_dpo': 87.74307761047825,\n     'NASDAQ:/SPY:trend_kst': -436.3740678472662,\n     'NASDAQ:/SPY:trend_kst_sig': -436.3740678472662,\n     'NASDAQ:/SPY:trend_kst_diff': 0.0,\n     'NASDAQ:/SPY:trend_ichimoku_conv': 112.45000076293945,\n     'NASDAQ:/SPY:trend_ichimoku_base': 112.45000076293945,\n     'NASDAQ:/SPY:trend_ichimoku_a': 112.45000076293945,\n     'NASDAQ:/SPY:trend_ichimoku_b': 112.45000076293945,\n     'NASDAQ:/SPY:trend_visual_ichimoku_a': 199.68840442570772,\n     'NASDAQ:/SPY:trend_visual_ichimoku_b': 197.45571224183746,\n     'NASDAQ:/SPY:trend_aroon_up': 4.0,\n     'NASDAQ:/SPY:trend_aroon_down': 4.0,\n     'NASDAQ:/SPY:trend_aroon_ind': 0.0,\n     'NASDAQ:/SPY:trend_psar_up': -1.0,\n     'NASDAQ:/SPY:trend_psar_down': -1.0,\n     'NASDAQ:/SPY:trend_psar_up_indicator': 0.0,\n     'NASDAQ:/SPY:trend_psar_down_indicator': 0.0,\n     'NASDAQ:/SPY:momentum_rsi': 100.0,\n     'NASDAQ:/SPY:momentum_tsi': 0.0,\n     'NASDAQ:/SPY:momentum_uo': 0.0,\n     'NASDAQ:/SPY:momentum_stoch': 96.80863583791569,\n     'NASDAQ:/SPY:momentum_stoch_signal': 96.80863583791569,\n     'NASDAQ:/SPY:momentum_wr': -3.1913641620843127,\n     'NASDAQ:/SPY:momentum_ao': 0.0,\n     'NASDAQ:/SPY:momentum_kama': 113.33000183105469,\n     'NASDAQ:/SPY:momentum_roc': 0.0,\n     'NASDAQ:/SPY:others_dr': -43.63740678472663,\n     'NASDAQ:/SPY:others_dlr': 0.0,\n     'NASDAQ:/SPY:others_cr': 0.0,\n     'sim-exchange:/USD-SPY': 113.33000183105469,\n     'sim-exchange:/USD:/free': 100000.0,\n     'sim-exchange:/USD:/locked': 0.0,\n     'sim-exchange:/USD:/total': 100000.0,\n     'sim-exchange:/SPY:/free': 0.0,\n     'sim-exchange:/SPY:/locked': 0.0,\n     'sim-exchange:/SPY:/total': 0.0,\n     'sim-exchange:/SPY:/worth': 0.0,\n     'net_worth': 100000.0}\n\n\n\n## Setup and Train DQN Agent\n- Passing in the environment on initialization\n- Then running the DQNAgent's train() function\n\n\n```python\nfrom tensortrade.agents import DQNAgent\n\nagent = DQNAgent(env)\n\n!mkdir -p agents/\n\nreward = agent.train(n_steps=100, save_path=\"agents/\", n_episodes = 100)\n```\n\n    ====      AGENT ID: 29e7a11a-ce40-40b7-afe0-20149566e7d9      ====\n    [2020-07-05 14:26:24 PM] Episode: 2/100 Step: 50/100\n    [2020-07-05 14:26:33 PM] Episode: 2/100 Step: 100/100\n    [2020-07-05 14:26:43 PM] Episode: 3/100 Step: 50/100\n    [2020-07-05 14:26:52 PM] Episode: 3/100 Step: 100/100\n    [2020-07-05 14:27:02 PM] Episode: 4/100 Step: 50/100\n    [2020-07-05 14:27:11 PM] Episode: 4/100 Step: 100/100\n    [2020-07-05 14:27:21 PM] Episode: 5/100 Step: 50/100\n    [2020-07-05 14:27:31 PM] Episode: 5/100 Step: 100/100\n    [2020-07-05 14:27:40 PM] Episode: 6/100 Step: 50/100\n    [2020-07-05 14:27:50 PM] Episode: 6/100 Step: 100/100\n    [2020-07-05 14:27:59 PM] Episode: 7/100 Step: 50/100\n    [2020-07-05 14:28:09 PM] Episode: 7/100 Step: 100/100\n    [2020-07-05 14:28:19 PM] Episode: 8/100 Step: 50/100\n    [2020-07-05 14:28:28 PM] Episode: 8/100 Step: 100/100\n    [2020-07-05 14:28:37 PM] Episode: 9/100 Step: 50/100\n    [2020-07-05 14:28:47 PM] Episode: 9/100 Step: 100/100\n    [2020-07-05 14:28:56 PM] Episode: 10/100 Step: 50/100\n    [2020-07-05 14:29:06 PM] Episode: 10/100 Step: 100/100\n    [2020-07-05 14:29:15 PM] Episode: 11/100 Step: 50/100\n    [2020-07-05 14:29:25 PM] Episode: 11/100 Step: 100/100\n    [2020-07-05 14:29:34 PM] Episode: 12/100 Step: 50/100\n    [2020-07-05 14:29:44 PM] Episode: 12/100 Step: 100/100\n    [2020-07-05 14:29:53 PM] Episode: 13/100 Step: 50/100\n    [2020-07-05 14:30:03 PM] Episode: 13/100 Step: 100/100\n    [2020-07-05 14:30:13 PM] Episode: 14/100 Step: 50/100\n    [2020-07-05 14:30:22 PM] Episode: 14/100 Step: 100/100\n    [2020-07-05 14:30:32 PM] Episode: 15/100 Step: 50/100\n    [2020-07-05 14:30:41 PM] Episode: 15/100 Step: 100/100\n    [2020-07-05 14:30:51 PM] Episode: 16/100 Step: 50/100\n    [2020-07-05 14:31:00 PM] Episode: 16/100 Step: 100/100\n    [2020-07-05 14:31:10 PM] Episode: 17/100 Step: 50/100\n    [2020-07-05 14:31:19 PM] Episode: 17/100 Step: 100/100\n    [2020-07-05 14:31:29 PM] Episode: 18/100 Step: 50/100\n    [2020-07-05 14:31:38 PM] Episode: 18/100 Step: 100/100\n    [2020-07-05 14:31:48 PM] Episode: 19/100 Step: 50/100\n    [2020-07-05 14:31:57 PM] Episode: 19/100 Step: 100/100\n    [2020-07-05 14:32:07 PM] Episode: 20/100 Step: 50/100\n    [2020-07-05 14:32:16 PM] Episode: 20/100 Step: 100/100\n    [2020-07-05 14:32:26 PM] Episode: 21/100 Step: 50/100\n    [2020-07-05 14:32:35 PM] Episode: 21/100 Step: 100/100\n    [2020-07-05 14:32:45 PM] Episode: 22/100 Step: 50/100\n    [2020-07-05 14:32:54 PM] Episode: 22/100 Step: 100/100\n    [2020-07-05 14:33:03 PM] Episode: 23/100 Step: 50/100\n    [2020-07-05 14:33:13 PM] Episode: 23/100 Step: 100/100\n    [2020-07-05 14:33:22 PM] Episode: 24/100 Step: 50/100\n    [2020-07-05 14:33:32 PM] Episode: 24/100 Step: 100/100\n    [2020-07-05 14:33:41 PM] Episode: 25/100 Step: 50/100\n    [2020-07-05 14:33:50 PM] Episode: 25/100 Step: 100/100\n    [2020-07-05 14:34:00 PM] Episode: 26/100 Step: 50/100\n    [2020-07-05 14:34:09 PM] Episode: 26/100 Step: 100/100\n    [2020-07-05 14:34:19 PM] Episode: 27/100 Step: 50/100\n    [2020-07-05 14:34:28 PM] Episode: 27/100 Step: 100/100\n    [2020-07-05 14:34:38 PM] Episode: 28/100 Step: 50/100\n    [2020-07-05 14:34:47 PM] Episode: 28/100 Step: 100/100\n    [2020-07-05 14:34:57 PM] Episode: 29/100 Step: 50/100\n    [2020-07-05 14:35:06 PM] Episode: 29/100 Step: 100/100\n    [2020-07-05 14:35:16 PM] Episode: 30/100 Step: 50/100\n    [2020-07-05 14:35:25 PM] Episode: 30/100 Step: 100/100\n    [2020-07-05 14:35:35 PM] Episode: 31/100 Step: 50/100\n    [2020-07-05 14:35:44 PM] Episode: 31/100 Step: 100/100\n    [2020-07-05 14:35:54 PM] Episode: 32/100 Step: 50/100\n    [2020-07-05 14:36:03 PM] Episode: 32/100 Step: 100/100\n    [2020-07-05 14:36:13 PM] Episode: 33/100 Step: 50/100\n    [2020-07-05 14:36:22 PM] Episode: 33/100 Step: 100/100\n    [2020-07-05 14:36:32 PM] Episode: 34/100 Step: 50/100\n    [2020-07-05 14:36:41 PM] Episode: 34/100 Step: 100/100\n    [2020-07-05 14:36:51 PM] Episode: 35/100 Step: 50/100\n    [2020-07-05 14:37:00 PM] Episode: 35/100 Step: 100/100\n    [2020-07-05 14:37:10 PM] Episode: 36/100 Step: 50/100\n    [2020-07-05 14:37:19 PM] Episode: 36/100 Step: 100/100\n    [2020-07-05 14:37:29 PM] Episode: 37/100 Step: 50/100\n    [2020-07-05 14:37:38 PM] Episode: 37/100 Step: 100/100\n    [2020-07-05 14:37:48 PM] Episode: 38/100 Step: 50/100\n    [2020-07-05 14:37:57 PM] Episode: 38/100 Step: 100/100\n    [2020-07-05 14:38:07 PM] Episode: 39/100 Step: 50/100\n    [2020-07-05 14:38:16 PM] Episode: 39/100 Step: 100/100\n    [2020-07-05 14:38:26 PM] Episode: 40/100 Step: 50/100\n    [2020-07-05 14:38:35 PM] Episode: 40/100 Step: 100/100\n    [2020-07-05 14:38:45 PM] Episode: 41/100 Step: 50/100\n    [2020-07-05 14:38:54 PM] Episode: 41/100 Step: 100/100\n    [2020-07-05 14:39:04 PM] Episode: 42/100 Step: 50/100\n    [2020-07-05 14:39:13 PM] Episode: 42/100 Step: 100/100\n    [2020-07-05 14:39:23 PM] Episode: 43/100 Step: 50/100\n    [2020-07-05 14:39:32 PM] Episode: 43/100 Step: 100/100\n    [2020-07-05 14:39:41 PM] Episode: 44/100 Step: 50/100\n    [2020-07-05 14:39:51 PM] Episode: 44/100 Step: 100/100\n    [2020-07-05 14:40:00 PM] Episode: 45/100 Step: 50/100\n    [2020-07-05 14:40:10 PM] Episode: 45/100 Step: 100/100\n    [2020-07-05 14:40:19 PM] Episode: 46/100 Step: 50/100\n    [2020-07-05 14:40:29 PM] Episode: 46/100 Step: 100/100\n    [2020-07-05 14:40:38 PM] Episode: 47/100 Step: 50/100\n    [2020-07-05 14:40:48 PM] Episode: 47/100 Step: 100/100\n    [2020-07-05 14:40:57 PM] Episode: 48/100 Step: 50/100\n    [2020-07-05 14:41:07 PM] Episode: 48/100 Step: 100/100\n    [2020-07-05 14:41:16 PM] Episode: 49/100 Step: 50/100\n    [2020-07-05 14:41:26 PM] Episode: 49/100 Step: 100/100\n    [2020-07-05 14:41:35 PM] Episode: 50/100 Step: 50/100\n    [2020-07-05 14:41:45 PM] Episode: 50/100 Step: 100/100\n    [2020-07-05 14:41:54 PM] Episode: 51/100 Step: 50/100\n    [2020-07-05 14:42:04 PM] Episode: 51/100 Step: 100/100\n    [2020-07-05 14:42:13 PM] Episode: 52/100 Step: 50/100\n    [2020-07-05 14:42:23 PM] Episode: 52/100 Step: 100/100\n    [2020-07-05 14:42:32 PM] Episode: 53/100 Step: 50/100\n    [2020-07-05 14:42:42 PM] Episode: 53/100 Step: 100/100\n    [2020-07-05 14:42:51 PM] Episode: 54/100 Step: 50/100\n    [2020-07-05 14:43:01 PM] Episode: 54/100 Step: 100/100\n    [2020-07-05 14:43:11 PM] Episode: 55/100 Step: 50/100\n    [2020-07-05 14:43:20 PM] Episode: 55/100 Step: 100/100\n    [2020-07-05 14:43:30 PM] Episode: 56/100 Step: 50/100\n    [2020-07-05 14:43:39 PM] Episode: 56/100 Step: 100/100\n    [2020-07-05 14:43:48 PM] Episode: 57/100 Step: 50/100\n    [2020-07-05 14:43:58 PM] Episode: 57/100 Step: 100/100\n    [2020-07-05 14:44:07 PM] Episode: 58/100 Step: 50/100\n    [2020-07-05 14:44:17 PM] Episode: 58/100 Step: 100/100\n    [2020-07-05 14:44:26 PM] Episode: 59/100 Step: 50/100\n    [2020-07-05 14:44:36 PM] Episode: 59/100 Step: 100/100\n    [2020-07-05 14:44:45 PM] Episode: 60/100 Step: 50/100\n    [2020-07-05 14:44:54 PM] Episode: 60/100 Step: 100/100\n    [2020-07-05 14:45:04 PM] Episode: 61/100 Step: 50/100\n    [2020-07-05 14:45:14 PM] Episode: 61/100 Step: 100/100\n    [2020-07-05 14:45:23 PM] Episode: 62/100 Step: 50/100\n    [2020-07-05 14:45:33 PM] Episode: 62/100 Step: 100/100\n    [2020-07-05 14:45:42 PM] Episode: 63/100 Step: 50/100\n    [2020-07-05 14:45:51 PM] Episode: 63/100 Step: 100/100\n    [2020-07-05 14:46:01 PM] Episode: 64/100 Step: 50/100\n    [2020-07-05 14:46:10 PM] Episode: 64/100 Step: 100/100\n    [2020-07-05 14:46:20 PM] Episode: 65/100 Step: 50/100\n    [2020-07-05 14:46:29 PM] Episode: 65/100 Step: 100/100\n    [2020-07-05 14:46:38 PM] Episode: 66/100 Step: 50/100\n    [2020-07-05 14:46:48 PM] Episode: 66/100 Step: 100/100\n    [2020-07-05 14:46:57 PM] Episode: 67/100 Step: 50/100\n    [2020-07-05 14:47:07 PM] Episode: 67/100 Step: 100/100\n    [2020-07-05 14:47:16 PM] Episode: 68/100 Step: 50/100\n    [2020-07-05 14:47:25 PM] Episode: 68/100 Step: 100/100\n    [2020-07-05 14:47:35 PM] Episode: 69/100 Step: 50/100\n    [2020-07-05 14:47:44 PM] Episode: 69/100 Step: 100/100\n    [2020-07-05 14:47:54 PM] Episode: 70/100 Step: 50/100\n    [2020-07-05 14:48:03 PM] Episode: 70/100 Step: 100/100\n    [2020-07-05 14:48:13 PM] Episode: 71/100 Step: 50/100\n    [2020-07-05 14:48:22 PM] Episode: 71/100 Step: 100/100\n    [2020-07-05 14:48:32 PM] Episode: 72/100 Step: 50/100\n    [2020-07-05 14:48:41 PM] Episode: 72/100 Step: 100/100\n    [2020-07-05 14:48:50 PM] Episode: 73/100 Step: 50/100\n    [2020-07-05 14:49:00 PM] Episode: 73/100 Step: 100/100\n    [2020-07-05 14:49:09 PM] Episode: 74/100 Step: 50/100\n    [2020-07-05 14:49:18 PM] Episode: 74/100 Step: 100/100\n    [2020-07-05 14:49:28 PM] Episode: 75/100 Step: 50/100\n    [2020-07-05 14:49:37 PM] Episode: 75/100 Step: 100/100\n    [2020-07-05 14:49:47 PM] Episode: 76/100 Step: 50/100\n    [2020-07-05 14:49:56 PM] Episode: 76/100 Step: 100/100\n    [2020-07-05 14:50:06 PM] Episode: 77/100 Step: 50/100\n    [2020-07-05 14:50:15 PM] Episode: 77/100 Step: 100/100\n    [2020-07-05 14:50:25 PM] Episode: 78/100 Step: 50/100\n    [2020-07-05 14:50:34 PM] Episode: 78/100 Step: 100/100\n    [2020-07-05 14:50:44 PM] Episode: 79/100 Step: 50/100\n    [2020-07-05 14:50:53 PM] Episode: 79/100 Step: 100/100\n    [2020-07-05 14:51:03 PM] Episode: 80/100 Step: 50/100\n    [2020-07-05 14:51:12 PM] Episode: 80/100 Step: 100/100\n    [2020-07-05 14:51:22 PM] Episode: 81/100 Step: 50/100\n    [2020-07-05 14:51:31 PM] Episode: 81/100 Step: 100/100\n    [2020-07-05 14:51:40 PM] Episode: 82/100 Step: 50/100\n    [2020-07-05 14:51:50 PM] Episode: 82/100 Step: 100/100\n    [2020-07-05 14:51:59 PM] Episode: 83/100 Step: 50/100\n    [2020-07-05 14:52:09 PM] Episode: 83/100 Step: 100/100\n    [2020-07-05 14:52:18 PM] Episode: 84/100 Step: 50/100\n    [2020-07-05 14:52:28 PM] Episode: 84/100 Step: 100/100\n    [2020-07-05 14:52:37 PM] Episode: 85/100 Step: 50/100\n    [2020-07-05 14:52:46 PM] Episode: 85/100 Step: 100/100\n    [2020-07-05 14:52:56 PM] Episode: 86/100 Step: 50/100\n    [2020-07-05 14:53:05 PM] Episode: 86/100 Step: 100/100\n    [2020-07-05 14:53:15 PM] Episode: 87/100 Step: 50/100\n    [2020-07-05 14:53:24 PM] Episode: 87/100 Step: 100/100\n    [2020-07-05 14:53:34 PM] Episode: 88/100 Step: 50/100\n    [2020-07-05 14:53:43 PM] Episode: 88/100 Step: 100/100\n    [2020-07-05 14:53:53 PM] Episode: 89/100 Step: 50/100\n    [2020-07-05 14:54:02 PM] Episode: 89/100 Step: 100/100\n    [2020-07-05 14:54:12 PM] Episode: 90/100 Step: 50/100\n    [2020-07-05 14:54:21 PM] Episode: 90/100 Step: 100/100\n    [2020-07-05 14:54:30 PM] Episode: 91/100 Step: 50/100\n    [2020-07-05 14:54:40 PM] Episode: 91/100 Step: 100/100\n    [2020-07-05 14:54:49 PM] Episode: 92/100 Step: 50/100\n    [2020-07-05 14:54:59 PM] Episode: 92/100 Step: 100/100\n    [2020-07-05 14:55:08 PM] Episode: 93/100 Step: 50/100\n    [2020-07-05 14:55:18 PM] Episode: 93/100 Step: 100/100\n    [2020-07-05 14:55:27 PM] Episode: 94/100 Step: 50/100\n    [2020-07-05 14:55:37 PM] Episode: 94/100 Step: 100/100\n    [2020-07-05 14:55:46 PM] Episode: 95/100 Step: 50/100\n    [2020-07-05 14:55:55 PM] Episode: 95/100 Step: 100/100\n    [2020-07-05 14:56:05 PM] Episode: 96/100 Step: 50/100\n    [2020-07-05 14:56:14 PM] Episode: 96/100 Step: 100/100\n    [2020-07-05 14:56:24 PM] Episode: 97/100 Step: 50/100\n    [2020-07-05 14:56:33 PM] Episode: 97/100 Step: 100/100\n    [2020-07-05 14:56:43 PM] Episode: 98/100 Step: 50/100\n    [2020-07-05 14:56:52 PM] Episode: 98/100 Step: 100/100\n    [2020-07-05 14:57:02 PM] Episode: 99/100 Step: 50/100\n    [2020-07-05 14:57:11 PM] Episode: 99/100 Step: 100/100\n    [2020-07-05 14:57:21 PM] Episode: 100/100 Step: 50/100\n    [2020-07-05 14:57:30 PM] Episode: 100/100 Step: 100/100\n\n\n## Plot Performance\n- Prints out charts after training\n\n\n```python\nportfolio.performance.plot()\n```\n\n\n```python\nportfolio.performance.net_worth.plot()\n```\n", "meta": {"hexsha": "123ba404486484fb33c933f564ed0ca99a1a2112", "size": 131504, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/TensorTrade_on_SageMaker_Studio.ipynb", "max_stars_repo_name": "msrparadesi/tensortrade", "max_stars_repo_head_hexsha": "01b55ef3bc9d77a16af4827442d0b5f4f6fd1a79", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-07-22T01:32:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-10T13:27:06.000Z", "max_issues_repo_path": "examples/TensorTrade_on_SageMaker_Studio.ipynb", "max_issues_repo_name": "msrparadesi/tensortrade", "max_issues_repo_head_hexsha": "01b55ef3bc9d77a16af4827442d0b5f4f6fd1a79", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/TensorTrade_on_SageMaker_Studio.ipynb", "max_forks_repo_name": "msrparadesi/tensortrade", "max_forks_repo_head_hexsha": "01b55ef3bc9d77a16af4827442d0b5f4f6fd1a79", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-01-09T09:21:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-09T02:13:11.000Z", "avg_line_length": 92.673713883, "max_line_length": 36260, "alphanum_fraction": 0.7516957659, "converted": true, "num_tokens": 19250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406828054583, "lm_q2_score": 0.03846619325839483, "lm_q1q2_score": 0.014522552867701101}}
{"text": "## 0.1. Import Packages\n\n\n```python\n# Run cell\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem import PorterStemmer\nimport os\nimport csv\nimport re\nimport numpy as np\nimport pandas as pd\nimport json\nfrom scipy import spatial\nimport spacy\nimport collections\nimport heapq\nfrom IPython.display import HTML\nfrom bs4 import BeautifulSoup\nimport time\nfrom selenium import webdriver\nfrom webdriver_manager.firefox import GeckoDriverManager\nimport webbrowser\nfrom langdetect import detect\nfrom multiprocessing import Pool\n#import multi_processing_functions\nimport dask.dataframe as ddf\n```\n\n\n```python\n# Run cell\nfrom __future__ import print_function\n```\n\n\n```python\nfrom dask.distributed import Client\nclient = Client()\nclient\n```\n\n    C:\\Users\\juanm\\Anaconda3\\envs\\data_science_general\\lib\\site-packages\\distributed\\dashboard\\core.py:79: UserWarning: \n    Port 8787 is already in use. \n    Perhaps you already have a cluster running?\n    Hosting the diagnostics dashboard on a random port instead.\n      warnings.warn(\"\\n\" + msg)\n\n\n\n\n\n<table style=\"border: 2px solid white;\">\n<tr>\n<td style=\"vertical-align: top; border: 0px solid white\">\n<h3 style=\"text-align: left;\">Client</h3>\n<ul style=\"text-align: left; list-style: none; margin: 0; padding: 0;\">\n  <li><b>Scheduler: </b>tcp://127.0.0.1:61152</li>\n  <li><b>Dashboard: </b><a href='http://127.0.0.1:61155/status' target='_blank'>http://127.0.0.1:61155/status</a>\n</ul>\n</td>\n<td style=\"vertical-align: top; border: 0px solid white\">\n<h3 style=\"text-align: left;\">Cluster</h3>\n<ul style=\"text-align: left; list-style:none; margin: 0; padding: 0;\">\n  <li><b>Workers: </b>4</li>\n  <li><b>Cores: </b>4</li>\n  <li><b>Memory: </b>8.50 GB</li>\n</ul>\n</td>\n</tr>\n</table>\n\n\n\n## 0.2. Useful Functions (read, write, etc.)\n\nWe will define a few basic functions that will be used throughout the whole notebook\n\n\n```python\n# Run cell\ndef write_file(filename, content):\n    os.makedirs(os.path.dirname(filename), exist_ok=True)\n    with open(filename, \"w\", encoding='utf-8' ) as f:\n        f.write(str(content))\n```\n\n\n```python\n# Run cell\ndef write_tsv(filename, content):\n    os.makedirs(os.path.dirname(filename), exist_ok=True)\n    with open(filename, \"wt\", newline='', encoding='utf-8' ) as out_file:\n        tsv_writer = csv.writer(out_file, delimiter='\\t')\n        tsv_writer.writerow(content)\n```\n\n\n```python\n# Run cell\ndef read_tsv(filename, type_='utf-8'):\n    # cp850\n    with open(filename, encoding = type_) as tsvfile:\n        reader = csv.reader(tsvfile, delimiter='\\t')\n        for data in reader:\n            return data\n```\n\n\n```python\n# Run cell\ndef write_json(file_name, content):\n    os.makedirs(os.path.dirname(file_name), exist_ok=True)\n    with open(file_name, 'w') as outfile:\n        json.dump(content, outfile, sort_keys=True, indent=4)\n```\n\n\n```python\n# Run cell\ndef jsonKeys2int(x):\n    if isinstance(x, dict):\n            return {int(k):v for k,v in x.items()}\n    return x\n```\n\n\n```python\n# Run cell\ndef read_json(file_name):\n    with open(file_name) as json_file:\n        data_dict = json.load(json_file, object_hook=jsonKeys2int)\n        return data_dict\n```\n\n\n```python\n# Run cell\ndef read_json_simple(file_name):\n    with open(file_name) as json_file:\n        data_dict = json.load(json_file)\n        return data_dict\n```\n\n\n```python\n# Run cell\ndef tsv_files_to_df(path, destiny='data/tsv_files/tsv_files.tsv'):\n    \"\"\"  \n    Convert all tsv files in the given path into a dataframe, which will also be saved as a .tsv file\n    \"\"\"\n    tsv_files = os.listdir(path)\n    list_tsv = []\n    for filename in tsv_files:\n        d_id = int(re.findall(r'\\d+', filename)[0])\n        filename = path + filename\n        book_data = read_tsv(filename)\n        book_data.insert(0,d_id)\n        list_tsv.append(book_data)\n    df = pd.DataFrame(list_tsv)\n        \n    df.to_csv(destiny, sep='\\t')\n    return df\n```\n\n## 1. Data collection\n\n### 1.1. Get the list of books\n\n\n```python\n# Initalize web browser for crawling\ndriver = webdriver.Firefox(executable_path=GeckoDriverManager().install())\n```\n\n    [WDM] - Getting latest mozilla release info for v0.28.0\n    [WDM] - Trying to download new driver from https://github.com/mozilla/geckodriver/releases/download/v0.28.0/geckodriver-v0.28.0-win64.zip\n    [WDM] - Driver has been saved in cache [C:\\Users\\ADMIN\\.wdm\\drivers\\geckodriver\\win64\\v0.28.0]\n\n\n\n```python\ndef crawl_urls(href):\n    \"\"\"\n    Given a specific url (href) crawl through the different list items and return the page url\n    \"\"\"\n    driver.get(href)\n    time.sleep(5)\n    \n    page_soup = BeautifulSoup(driver.page_source, features=\"lxml\")\n    links = page_soup.find_all('a',{'class': 'bookTitle'}, itemprop=\"url\")\n    \n    urls = []\n    # Loop over all links in the href page\n    for link in links:\n        url = link.get('href')\n        url = 'https://www.goodreads.com' + url\n        urls.append(url)\n    \n    urls = '\\n'.join(urls)+'\\n'\n    \n    return urls\n```\n\nApply previous function over all books that we are interested in downloading\n\n\n```python\nurl = 'https://www.goodreads.com/list/show/1.Best_Books_Ever?page='\npath = 'data/book_urls.txt'\n\nurls = ''\n\nfor i in range(0,30000):\n    href = url+str(i+1)\n    urls += crawl_urls(href)\n\nwrite_file(path, urls)\n```\n\n### 1.2. Crawl books\n\nGiven a set of links (generated by the previous function) download their html individually\n\n\n```python\ndef scrap_book(href):\n    driver.get(href)       \n    time.sleep(5)\n    return driver.page_source\n```\n\n\n```python\nfilename = 'data/book_urls.txt'\n\nbook_urls = open(filename, 'r')\nfor url in book_urls:\n    page_number = int((count-1)/100)+1\n    html = scrap_book(url)\n    path = 'data/page_'+str(page_number)+'/article_'+str(count)+'.html'\n    write_file(path, html)\n```\n\n### 1.3 Parse downloaded pages\n\nGiven all the downloaded htmls, parse them individually\n\n\n```python\ndef remove_html_tags(text):\n    \"\"\"Remove html tags from a string\"\"\"\n    clean = re.compile('<.*?>')\n    return re.sub(clean, '', text)\n```\n\n\n```python\ndef parse_html_in_folder(path):\n    for html_file in os.listdir(path):\n        print(html_file)\n        if os.path.exists('data/final_tsv_files/' + re.findall(r'\\d+', html_file)[0] + '.tsv'):\n            print('not parsed')\n            continue\n        else:\n            with open(path + '/' + html_file, encoding='utf8') as infile:\n                print('parsing...')\n                soup = BeautifulSoup(infile, features=\"lxml\")\n                try:\n                    Plot = ' '.join([remove_html_tags(str(c)) for c in soup.find_all('div', id=\"description\")[0].contents[3].contents ])\n                except Exception:\n                    if not soup.find_all('div', id=\"description\"):\n                        Plot = ''\n                    else:\n                        Plot = ' '.join([remove_html_tags(str(c)) for c in soup.find_all('div', id=\"description\")[0].contents[1].contents ])\n                if Plot:\n                    if detect(Plot) != 'en':\n                        print('Article removed:', html_file)\n                        continue\n                try:\n                    bookTitle = soup.find_all('h1')[0].contents[0].replace('\\n', '').strip()\n                except:\n                    print('Wrong html file')\n                    continue\n                bookSeries = soup.find_all('h2', id='bookSeries')[0].text.replace('\\n', '').strip()\n                bookAuthors = ', '.join([soup.find_all('span', itemprop='name')[i].contents[0] for i in range(\n                    len(soup.find_all('span', itemprop='name')))])\n                ratingValue = soup.find_all('span', itemprop='ratingValue')[0].contents[0].replace('\\n', '').strip()\n                ratingCount = soup.find_all('meta', itemprop=\"ratingCount\")[0]['content']\n                reviewCount = soup.find_all('meta', itemprop=\"reviewCount\")[0]['content']\n                try:\n                    NumberofPages = re.findall(r'\\d+', soup.find_all('span', itemprop=\"numberOfPages\")[0].contents[0])[0]\n                except:\n                    if not soup.find_all('span', itemprop=\"bookFormat\"):\n                        NumberofPages = ''\n                    else:\n                        NumberofPages = 0\n                try:\n                    temp_date = soup.find_all('div', id='details')[0].find_all('div', {\"class\": \"row\"})[1].text.split('\\n')[\n                        2].split()\n                    if not temp_date:\n                        temp_date = soup.find_all('div', id='details')[0].find_all('nobr', {\"class\": \"greyText\"})[0].contents[0].split('\\n')[1].split()[-3:]\n                except:\n                    try:\n                        temp_date = soup.find_all('div', id='details')[0].find_all('div', {\"class\": \"row\"})[0].contents[0].split('\\n')[\n                            2].split()\n                    except:\n                        temp_date = ''\n                PublishingDate = ' '.join(temp_date)\n                characters = []\n                settings = []\n                for i in range(1, len(soup.find_all('div', id=\"bookDataBox\")[0].find_all('a'))):\n                    if re.match(r'/characters/', soup.find_all('div', id=\"bookDataBox\")[0].find_all('a')[i].attrs['href']):\n                        characters.append(soup.find_all('div', id=\"bookDataBox\")[0].find_all('a')[i].text)\n                    elif re.match(r'/places/', soup.find_all('div', id=\"bookDataBox\")[0].find_all('a')[i].attrs['href']):\n                        settings.append(soup.find_all('div', id=\"bookDataBox\")[0].find_all('a')[i].text)\n                characters = ', '.join(characters)\n                settings = ', '.join(settings)\n                url = soup.find_all('link', rel='canonical')[0].attrs['href']\n\n                final_list = [bookTitle, bookSeries, bookAuthors, ratingValue, ratingCount, reviewCount,\n                              Plot, NumberofPages, PublishingDate, characters, settings, url]\n\n                filename = 'data/final_tsv_files/' + re.findall(r'\\d+', html_file)[0] + '.tsv'\n\n                write_tsv(filename, final_list)\n\n```\n\nApply function over all folders containing the downloaded html files\n\n\n```python\n# None parallel approach\nfor i in range(0,301):\n    print(i)\n    parse_html_in_folder('../data_html/page_' + str(i))\n```\n\n\n```python\n# Parallel approach\nif __name__ == '__main__':\n    with Pool(8) as p:\n        print(p.map(multi_processing_functions.parse_html_in_folder, \n                    ['../data_html/' + i for i in os.listdir('../data_html')]))\n```\n\n\n```python\ntsv_files_to_df(path='data/final_tsv_files/', destiny='data/tsv_files/final_tsv_files.tsv')\n```\n\n\n```python\ndf_dirty.to_csv('data/tsv_files/final_tsv_files.tsv', sep='\\t', index=False)\n```\n\n## 2. Search Engine\n\n### 2.0. Pre-process of information\n\n\n```python\n# Run cell\nstopwords = set(stopwords.words('english'))\ntokenizer = nltk.RegexpTokenizer(r\"\\w+\")\nnlp = spacy.load(\"en_core_web_sm\")\n```\n\n\n```python\n# Run cell\ndef remove_stop_words(text):\n    \"\"\"\n    This allow us to identify stop word in english and remove them. We are also removing character with single length (e.g. \"s\")\n    \"\"\"    \n    word_tokens = word_tokenize(text)\n    filtered_sentence = [w.lower() for w in word_tokens if w.lower() not in stopwords and not(len(w) == 1 and w.isalpha())]\n\n    text = ' '.join(filtered_sentence)\n    return text\n```\n\n\n```python\n# Run cell\ndef remove_punctuation(text): \n    \"\"\"\n    Remove puntuation from input string\n    \"\"\"\n    text = tokenizer.tokenize(text)\n    clean_punctuation = ' '.join(text)\n    return clean_punctuation\n```\n\n\n```python\n# Run cell\ndef remove_stemming(text):\n    \"\"\"\n    Apply stemming procedure over input text\n    \"\"\"\n    ps = PorterStemmer()\n    words = word_tokenize(text)\n    stem_sentence=[]\n    \n    for w in words:\n        stem_sentence.append(ps.stem(w))\n\n    text = \" \".join(stem_sentence)\n    return text \n```\n\n\n```python\n# Run cell\ndef remove_lemma(text):\n    \"\"\"\n    Apply lemmanization procedure over input text\n    \"\"\"\n    doc = nlp(text)\n    lemma = []\n    for token in doc:\n        lemma.append(token.lemma_)\n    text = ' '.join(lemma)\n    return text\n```\n\n\n```python\n# Run cell\ndef parse_pulishing_date(publishingDate):\n    \"\"\"\n    Only keep last 4 digits of publishing Date (Year of publication)\n    \"\"\"\n    return publishingDate[-4:]\n```\n\n\n```python\n# Run cell\ndef global_pre_process(text):\n    \"\"\" \n    Function to process everything at once \n    \"\"\"\n    text = remove_punctuation(text)\n    text = remove_stop_words(text)\n    text = remove_lemma(text)\n    # This makes sure that we also remove strange letters that have not been removed with the previous packages \n    # (e.g. arabic letters)\n    text = re.sub(r'[^a-zA-Z0-9]', ' ', text).strip()\n    return text\n```\n\n\n```python\n# Run cell\ndef clean_text(df):\n    \"\"\"\n    Take in a Dataframe, and clean based on the previously defined functions (each column is cleaned individually)\n    \"\"\"\n    df['BookTitle'] = df.BookTitle.map(global_pre_process)\n    df['BookSeries'] = df.BookSeries.map(global_pre_process)\n    df['BookAuthors'] = df.BookAuthors.map(global_pre_process)\n    df['Plot'] = df.Plot.map(global_pre_process)\n    df['Characters'] = df.Characters.map(global_pre_process)\n    df['PublishingDate'] = df.PublishingDate.map(parse_pulishing_date)\n    return df\n```\n\nRead data frame which still has not been pre-processed\n\n\n```python\n# Run cell\ndf_dirty = pd.read_csv('data/tsv_files/final_tsv_files.tsv', sep='\\t', keep_default_na=False)\n```\n\n\n```python\ndf_dirty.head(5)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>BookID</th>\n      <th>BookTitle</th>\n      <th>BookSeries</th>\n      <th>BookAuthors</th>\n      <th>RatingValue</th>\n      <th>RatingCount</th>\n      <th>ReviewCount</th>\n      <th>Plot</th>\n      <th>NumberofPages</th>\n      <th>PublishingDate</th>\n      <th>Characters</th>\n      <th>Settings</th>\n      <th>Url</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>1</td>\n      <td>The Hunger Games</td>\n      <td>(The Hunger Games #1)</td>\n      <td>Suzanne Collins</td>\n      <td>4.33</td>\n      <td>6409198</td>\n      <td>172562</td>\n      <td>Could you survive on your own in the wild, wit...</td>\n      <td>374</td>\n      <td>September 14th 2008</td>\n      <td>Katniss Everdeen, Peeta Mellark, Cato (Hunger ...</td>\n      <td>District 12, Panem, Capitol, Panem, Panem</td>\n      <td>https://www.goodreads.com/book/show/2767052-th...</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>10</td>\n      <td>The Fault in Our Stars</td>\n      <td></td>\n      <td>John Green</td>\n      <td>4.20</td>\n      <td>3572895</td>\n      <td>155821</td>\n      <td>Despite the tumor-shrinking medical miracle th...</td>\n      <td>313</td>\n      <td>January 10th 2012</td>\n      <td>Augustus Waters, Isaac</td>\n      <td>Indianapolis, Indiana, Amsterdam</td>\n      <td>https://www.goodreads.com/book/show/11870085-t...</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>100</td>\n      <td>A Prayer for Owen Meany</td>\n      <td></td>\n      <td>John Irving</td>\n      <td>4.23</td>\n      <td>286642</td>\n      <td>13845</td>\n      <td>Eleven-year-old Owen Meany, playing in a Littl...</td>\n      <td>637</td>\n      <td>1990</td>\n      <td>John Wheelwright</td>\n      <td>Gravesend, New Hampshire, Toronto, Ontario</td>\n      <td>https://www.goodreads.com/book/show/4473.A_Pra...</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>1000</td>\n      <td>Helter Skelter: The True Story of the Manson M...</td>\n      <td></td>\n      <td>Vincent Bugliosi, Curt Gentry</td>\n      <td>4.04</td>\n      <td>126139</td>\n      <td>4019</td>\n      <td>Prosecuting attorney in the Manson trial, Vinc...</td>\n      <td>689</td>\n      <td>December 17th 2001</td>\n      <td></td>\n      <td></td>\n      <td>https://www.goodreads.com/book/show/105992.Hel...</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>10000</td>\n      <td>Henry and June: From \"A Journal of Love\": The ...</td>\n      <td>(From \"A Journal of Love\" #1)</td>\n      <td>Ana\u00efs Nin</td>\n      <td>3.89</td>\n      <td>10581</td>\n      <td>624</td>\n      <td>Taken from the original, uncensored journals o...</td>\n      <td>304</td>\n      <td>October 29th 1990</td>\n      <td>Henry Miller, Ana\u00efs Nin</td>\n      <td>Paris</td>\n      <td>https://www.goodreads.com/book/show/11038.Henr...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nApply clean_text function over the \"dirty\" dataframe using dask to optimize running time\n\n\n```python\ndask_dataframe = ddf.from_pandas(df_dirty, npartitions=20)\n```\n\n\n```python\n%%time\ndf_clean = dask_dataframe.map_partitions(clean_text, meta=df_dirty).compute()\n```\n\n    Wall time: 9min 30s\n\n\n\n```python\ndf_clean\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>BookID</th>\n      <th>BookTitle</th>\n      <th>BookSeries</th>\n      <th>BookAuthors</th>\n      <th>RatingValue</th>\n      <th>RatingCount</th>\n      <th>ReviewCount</th>\n      <th>Plot</th>\n      <th>NumberofPages</th>\n      <th>PublishingDate</th>\n      <th>Characters</th>\n      <th>Settings</th>\n      <th>Url</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>1</td>\n      <td>hunger game</td>\n      <td>hunger game 1</td>\n      <td>suzanne collins</td>\n      <td>4.33</td>\n      <td>6409198</td>\n      <td>172562</td>\n      <td>could survive wild every one make sure live se...</td>\n      <td>374</td>\n      <td>2008</td>\n      <td>katniss everdeen peeta mellark cato hunger gam...</td>\n      <td>District 12, Panem, Capitol, Panem, Panem</td>\n      <td>https://www.goodreads.com/book/show/2767052-th...</td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>10</td>\n      <td>fault star</td>\n      <td></td>\n      <td>john green</td>\n      <td>4.20</td>\n      <td>3572895</td>\n      <td>155821</td>\n      <td>despite tumor shrink medical miracle buy year ...</td>\n      <td>313</td>\n      <td>2012</td>\n      <td>augustus water isaac</td>\n      <td>Indianapolis, Indiana, Amsterdam</td>\n      <td>https://www.goodreads.com/book/show/11870085-t...</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>100</td>\n      <td>prayer owen meany</td>\n      <td></td>\n      <td>john irving</td>\n      <td>4.23</td>\n      <td>286642</td>\n      <td>13845</td>\n      <td>eleven year old owen meany play little league ...</td>\n      <td>637</td>\n      <td>1990</td>\n      <td>john wheelwright</td>\n      <td>Gravesend, New Hampshire, Toronto, Ontario</td>\n      <td>https://www.goodreads.com/book/show/4473.A_Pra...</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>1000</td>\n      <td>helter skelter true story manson murder</td>\n      <td></td>\n      <td>vincent bugliosi curt gentry</td>\n      <td>4.04</td>\n      <td>126139</td>\n      <td>4019</td>\n      <td>prosecute attorney manson trial vincent buglio...</td>\n      <td>689</td>\n      <td>2001</td>\n      <td></td>\n      <td></td>\n      <td>https://www.goodreads.com/book/show/105992.Hel...</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>10000</td>\n      <td>henry june journal love unexpurgate diary ana ...</td>\n      <td>journal love 1</td>\n      <td>ana s nin</td>\n      <td>3.89</td>\n      <td>10581</td>\n      <td>624</td>\n      <td>take original uncensored journal ana s nin hen...</td>\n      <td>304</td>\n      <td>1990</td>\n      <td>henry miller ana s nin</td>\n      <td>Paris</td>\n      <td>https://www.goodreads.com/book/show/11038.Henr...</td>\n    </tr>\n    <tr>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <td>27146</td>\n      <td>9993</td>\n      <td>catch true story real fake</td>\n      <td></td>\n      <td>frank abagnale stan redding</td>\n      <td>4.05</td>\n      <td>51450</td>\n      <td>2478</td>\n      <td>stole every nickel blow fine thread luxurious ...</td>\n      <td>224</td>\n      <td>2003</td>\n      <td>sean riley</td>\n      <td></td>\n      <td>https://www.goodreads.com/book/show/138269.Cat...</td>\n    </tr>\n    <tr>\n      <td>27147</td>\n      <td>9995</td>\n      <td>rake</td>\n      <td>lesson love 1</td>\n      <td>suzanne enoch</td>\n      <td>3.86</td>\n      <td>7694</td>\n      <td>369</td>\n      <td>three determined young lady vow give three lon...</td>\n      <td>375</td>\n      <td>2002</td>\n      <td>greydon brakenridge duke wycliffe georgina hal...</td>\n      <td></td>\n      <td>https://www.goodreads.com/book/show/823583.The...</td>\n    </tr>\n    <tr>\n      <td>27148</td>\n      <td>9996</td>\n      <td>manfred</td>\n      <td></td>\n      <td>lord byron</td>\n      <td>3.81</td>\n      <td>1856</td>\n      <td>109</td>\n      <td>manfred contain supernatural element keep popu...</td>\n      <td>84</td>\n      <td>2009</td>\n      <td>abbot st maurice manfre manfred herman manfre ...</td>\n      <td></td>\n      <td>https://www.goodreads.com/book/show/3730956-ma...</td>\n    </tr>\n    <tr>\n      <td>27149</td>\n      <td>9997</td>\n      <td>world representation vol 1</td>\n      <td>world representation 1</td>\n      <td>arthur schopenhauer judith norman payne alista...</td>\n      <td>4.19</td>\n      <td>8415</td>\n      <td>192</td>\n      <td>arthur schopenhauer die welt als wille und vor...</td>\n      <td>534</td>\n      <td>1966</td>\n      <td></td>\n      <td></td>\n      <td>https://www.goodreads.com/book/show/19506.The_...</td>\n    </tr>\n    <tr>\n      <td>27150</td>\n      <td>9999</td>\n      <td>fearless</td>\n      <td></td>\n      <td>tim lott</td>\n      <td>3.83</td>\n      <td>1227</td>\n      <td>197</td>\n      <td>smartly paint exterior city community faith sc...</td>\n      <td>266</td>\n      <td>2007</td>\n      <td></td>\n      <td></td>\n      <td>https://www.goodreads.com/book/show/1206359.Fe...</td>\n    </tr>\n  </tbody>\n</table>\n<p>27151 rows \u00d7 13 columns</p>\n</div>\n\n\n\n\n```python\ndf_clean.to_csv('data/clean_tsv_files/clean_final.tsv', sep='\\t', index=False)\n```\n\n### 2.1. Conjunctive query\n\n\n```python\n# Run cell\n# Read Clean tsv file\ndf_clean = pd.read_csv('data/clean_tsv_files/clean_final.tsv', sep='\\t', keep_default_na=False)\n```\n\n#### 2.1.1. Create your index!\n\n\n```python\ndef get_vocabulary_inverted_index(df, columns):\n    \"\"\"\n    This function returns a dictionary with all the words in the dataframe (and specifically the provided columns) \n    and its inverted index\n    Example:\n    vocabulary_dict = {'river': 1, 'game': 2, 'friend': 3, ...}\n    inverted_index = {1: [1, 4, 7], 2: [3, 6, 9], 3: [2, 7, 8]} where the list contains the documents in which \n    the word 1 (river) appears in\n    \n    df: Clean Dataframe\n    columns: Columns over which the vocabulary and inverted index dictionaries will be generated\n    \"\"\"\n    vocabulary = {}\n    count = 1\n    inverted_index = {}\n    for index, row in df.iterrows():\n        d_id = row['BookID']\n        if isinstance(columns, list):\n            text = (' '.join([row[i] for i in columns])).split(' ')\n        else:\n            raise('Column must be a list')\n            \n        for word in text:\n            if word not in vocabulary: \n                vocabulary[word] = count\n                inverted_index[count] = [d_id]\n                count +=1\n            else:\n                key = vocabulary[word]\n                if d_id not in inverted_index[key]:\n                     inverted_index[key].append(d_id)\n    return vocabulary, inverted_index\n```\n\n\n```python\n%%time\nvocabulary, inverted_index = get_vocabulary_inverted_index(df_clean, columns=['Plot'])\n```\n\n    Wall time: 37.2 s\n\n\nSave dictionaries as json files for future use\n\n\n```python\nwrite_json('data/inverted_index.json', inverted_index)\nwrite_json('data/vocabulary_dict.json', vocabulary)\n```\n\n#### 2.1.2. Execute the query\n\nFunctionality to get intersection of documents in which query appears\n\n\n```python\n# Run cell\ndef get_pointer_values(pointer, index_list):\n    \"\"\" Based on a set of pointer values get the documents \"\"\"\n    values = []\n    for i in range(len(pointer)):\n        values.append(index_list[i][pointer[i]])\n    return values\n```\n\n\n```python\n# Run cell\ndef update_pointer(values, pointer):\n    \"\"\" Given the values, compute the minimum and update the pointer accordingly based on their minimum \"\"\"\n    mins = np.where(values == np.min(values))[0]\n    for i in range(0, len(mins)):\n        pointer[mins[i]] = pointer[mins[i]] + 1 \n    return pointer\n```\n\n\n```python\n# Run cell\ndef query_function(query, index, vocabulary):\n    \"\"\" \n    Given a query find the documents in which these appear based on the index \n    query: query string\n    index: inverted index as dictionary\n    vocabulary: vocabulary dictionary\n    \n    \"\"\"\n    \n    # Pre-process query \n    query = global_pre_process(query)\n    \n    # Query to list of strings\n    query_list = query.split()\n    \n    # Map strings to integer based on dict\n    try:\n        integer_list = [vocabulary[i] for i in query_list]\n    except:\n        return []\n    \n    # Start to look for the intersection of the query in the index\n    total_query_documents = [sorted(index[i]) for i in integer_list]\n    \n    # Generate a list with the pointer values\n    pointers = np.full(len(total_query_documents), 0)\n    values = np.full(len(total_query_documents), 0)\n    \n    # List where intersection documents will be stored\n    intersection = []\n\n    # Compute the document in which the search should stop\n    max_list = np.array([max(total_query_documents[i]) for i in range(len(total_query_documents))])\n\n    try:\n        # Loop over all elements stopping at the minimum between all documents\n        while np.any(values != max_list):\n            # Get the documents based on the pointer\n            values = get_pointer_values(pointer = pointers, \n                                        index_list = total_query_documents)\n            # If all values are equal we have found a match and all the pointer values are increased by one\n            if len(set(values)) == 1:\n                intersection.append(values[0])\n                pointers += 1\n            # If all values are not equal increase the values of the minimum pointers\n            else:\n                pointers = update_pointer(values, pointers)\n    except:\n        intersection = sorted(list(set.intersection(*map(set,total_query_documents))))\n    \n    assert intersection == sorted(list(set.intersection(*map(set,total_query_documents)))), 'Algorithm is not returning same result as python implementation'\n    \n    return intersection\n```\n\n\n```python\n# Run cell\ndef path_to_image_html(path):\n    return ''\n```\n\n\n```python\n# Run cell\ndef show_results(book_ids, df):\n    \"\"\"\n    Get relevant information which will be shown in the final dataframe for the books in book_ids\n    df: This dataframe should not be pre-processed\n    book_ids: list of books\n    \"\"\"\n    output = df[df['BookID'].isin(book_ids)][['BookTitle', 'Plot', 'Url']]\n    return output\n```\n\n\n```python\n# Run cell\ndef search_engine_1(query, inverted_index, vocabulary, df):\n    \"\"\"\n    Basic search engine which returns all books with the provided query\n    query: Query of user\n    df: This dataframe should not be pre-processed\n    \"\"\"\n    query_results = query_function(query, inverted_index, vocabulary)\n    if len(query_results) == 0:\n        print('There are no results for the search')\n    else:\n        output = show_results(query_results, df)\n        output = HTML(output.to_html(escape=False,\n                                     formatters=dict(column_name_with_image_links=path_to_image_html)))\n        return output\n```\n\n##### Read json files (vocabulary and inverted index)\n\n\n```python\n# Run cell\ninverted_index = read_json('data/inverted_index.json')\nvocabulary = read_json_simple('data/vocabulary_dict.json')\n```\n\n#### Run First Search Engine\n\n\n```python\n# Run cell\ninput_query = 'harry potter magic hogwarts'\n```\n\n\n```python\n# Run cell\nsearch = search_engine_1(input_query, inverted_index, vocabulary, df_dirty)\nsearch\n```\n\n\n\n\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>BookTitle</th>\n      <th>Plot</th>\n      <th>Url</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>324</th>\n      <td>Harry Potter and the Goblet of Fire</td>\n      <td>Harry Potter is midway through his training as a wizard and his coming of age. Harry wants to get away from the pernicious Dursleys and go to the International Quidditch Cup with Hermione, Ron, and the Weasleys. He wants to dream about Cho Chang, his crush (and maybe do more than dream). He wants to find out about the mysterious event that's supposed to take place at Hogwarts this year, an event involving two other rival schools of magic, and a competition that hasn't happened for hundreds of years. He wants to be a normal, fourteen-year-old wizard. But unfortunately for Harry Potter, he's not normal - even by wizarding standards.   And in his case, different can be deadly.</td>\n      <td>https://www.goodreads.com/book/show/6.Harry_Potter_and_the_Goblet_of_Fire</td>\n    </tr>\n    <tr>\n      <th>3996</th>\n      <td>Harry Potter: A History of Magic</td>\n      <td>Harry Potter: A History of Magic is the official book of the exhibition, a once-in-a-lifetime collaboration between Bloomsbury, J.K. Rowling and the brilliant curators of the British Library. It promises to take readers on a fascinating journey through the subjects studied at Hogwarts School of Witchcraft and Wizardry \u2013 from Alchemy and Potions classes through to Herbology and Care of Magical Creatures.   Each chapter showcases a treasure trove of artefacts from the British Library and other collections around the world, beside exclusive manuscripts, sketches and illustrations from the Harry Potter archive. There's also a specially commissioned essay for each subject area by an expert, writer or cultural commentator, inspired by the contents of the exhibition \u2013 absorbing, insightful and unexpected contributions from Steve Backshall, the Reverend Richard Coles, Owen Davies, Julia Eccleshare, Roger Highfield, Steve Kloves, Lucy Mangan, Anna Pavord and Tim Peake, who offer a personal perspective on their magical theme.   Readers will be able to pore over ancient spell books, amazing illuminated scrolls that reveal the secret of the Elixir of Life, vials of dragon's blood, mandrake roots, painted centaurs and a genuine witch's broomstick, in a book that shows J.K. Rowling's magical inventions alongside their cultural and historical forebears.   This is the ultimate gift for Harry Potter fans, curious minds, big imaginations, bibliophiles and readers around the world who missed out on the chance to see the exhibition in person.</td>\n      <td>https://www.goodreads.com/book/show/35613533-harry-potter</td>\n    </tr>\n    <tr>\n      <th>6275</th>\n      <td>The Harry Potter Collection 1-4</td>\n      <td>The exciting tales of Harry Potter, the young wizard-in-training, have taken the world by storm, and fans just can't get enough of the magical world of Hogwarts and beyond. If you buy one of the Harry Potter books, we guarantee you'll want the next...and the next...and the next -- so why not have them all, right at your fingertips? With the Harry Potter Hardcover Box Set (Books 1-4), Barnes amp; Noble.com offers simple one-stop shopping for your Harry Potter library! As easy as the wave of a magic wand, you can get all four Harry Potter books delivered to your doorstep at once.p   The Harry Potter Hardcover Box Set (Books 1-4) includes hardcover editions of iHarry Potter and the Sorcerer's Stone, Harry Potter and the Chamber of Secrets, Harry Potter and the Prisoner of Azkaban,/i and iHarry Potter and the Goblet of Fire./i The books come snugly packed in a sturdy cardboard slipcase, beautifully decorated with memorable scenes from the books.p   So buy the set, and not even a pesky Locomotor Mortis spell cast by the evil Lord Voldemor...(oooops, sorry -- He-Who-Must-Not-Be-Named) can get in the way of your enjoying all of the mystery, adventure, intrigue, and, of course, magic that Muggles around the world can't seem to get enough of. Hold on tight -- it's going to be a wild ride!</td>\n      <td>https://www.goodreads.com/book/show/99298.The_Harry_Potter_Collection_1_4</td>\n    </tr>\n  </tbody>\n</table>\n\n\n\n### 2.2. Conjunctive query & Ranking score\n\n#### 2.2.1. Inverted index\n\n\n```python\ndef vectorize_tfidf(df, vocabulary, inverted_index, json_name='tfidf.json', columns=['Plot']):\n    '''\n    Vecterize Plots\n    This function, given a vocabulary dictionary, inverted index and pre-processed dataframe return a dictionary with \n    tfidf scores\n    Example: {1: {1: 0.7, 5: 3.7}, 2: {3: 1.7, 6: 5.7}} Where 1 and 2 denote the book_id and 1, 5, 3, 6 denote the word.\n    df: Pre-processed data frame (df_clean)\n    param column: If a list is provided the score will be computed over several columns\n    '''\n\n    no_of_documents = len(df)\n    \n    # number of words in vacabulary\n    no_of_words_in_vocab = len(vocabulary)\n    \n    tfidfDicts = {}\n    \n    for index, row in df.iterrows():\n        d_id = row['BookID']\n\n        if isinstance(columns, list):\n            text = (' '.join([row[i] for i in columns])).split(' ')\n        else:\n            raise('Column must be a list')\n            \n        no_of_words_in_plot = len(text)\n        # Create a vector\n        tfDict = dict.fromkeys((i for i in range(1, no_of_words_in_vocab+1)), 0)\n        \n        \n        for word in text:\n            index = vocabulary[word]\n            tfDict[index] +=1\n        \n        tfidfDict = {}\n        \n        for key, value in tfDict.items():\n            if value != 0:\n                \n                no_of_documents_appeared = len(inverted_index[key])\n\n                tfidf = (value/no_of_words_in_plot) * np.log(no_of_documents/no_of_documents_appeared)\n\n                tfidfDict[key] = float('{:.4f}'.format(tfidf))\n                        \n        tfidfDicts[d_id] = tfidfDict\n        \n    documents = collections.OrderedDict(sorted(tfidfDicts.items()))\n    write_json('data/' + json_name, documents)\n```\n\n\n```python\n%%time\n# Generate tfidf based only on the 'Plot' of the books (vocabulary and inverted index have been generated only over PLot as \n# well) \nvectorize_tfidf(df_clean, vocabulary, inverted_index, json_name='tfidf.json', columns=['Plot'])\n```\n\n    Wall time: 10min 49s\n\n\n\n```python\n# Run cell\ndef get_cosine(doc, query):\n    \"\"\"\n    Given two vectors, return a float which is the cosine similarity score\n    doc: dictionary vector \n    query: dictionary vector\n    \"\"\"\n    intersection = set(doc.keys()) & set(query.keys())\n    numerator = sum([doc[x] * query[x] for x in intersection])\n\n    sum1 = sum([doc[x] ** 2 for x in list(doc.keys())])\n    sum2 = sum([query[x] ** 2 for x in list(query.keys())])\n    denominator = np.sqrt(sum1) * np.sqrt(sum2)\n\n    if not denominator:\n        return 0.0\n    else:\n        return float(numerator) / denominator\n```\n\n\n```python\n# Run cell\ndef show_results_cosine_similarity(book_id, cosine_similarity, df):\n    \"\"\"\n    Generate a tuple with the relevant information about a book that will be displayed in the search engine, \n    and the cosine similarity score\n    df: Not pre-processed data set\n    \"\"\"\n    data = df[df.BookID == book_id][['BookTitle', 'Plot', 'Url']].values.tolist()[0]\n    output = (cosine_similarity, data)\n    return output\n```\n\n\n```python\n# Run cell\ndef search_engine_2(query, inverted_index, vocabulary, tfidf_scores_dict, df, k = 10):\n    \"\"\"\n    Cosine similarity search engine which returns all books with the provided query in order of highest cosine \n    value, and displaying top k books\n    \n    query: Query of user\n    df: This dataframe should not be pre-processed\n    \"\"\"\n    output = pd.DataFrame(columns=['BookTitle', 'Plot', 'Url', 'Similarity'])\n    documents_with_query_words = query_function(query, inverted_index, vocabulary)\n    queryed_documents_tfidf = {key: value for key, value in tfidf_scores_dict.items() if key in documents_with_query_words}\n    heap_data = []\n    \n    if len(documents_with_query_words) == 0:\n        print('There are no results for the search')\n    else:\n    \n        # pre-process query\n        query = global_pre_process(query)\n\n        # vectorize query\n        vector_query = {}\n        for word in query.split(' '):\n            index = vocabulary[word]\n            vector_query[index] = 1\n\n        for i in queryed_documents_tfidf.keys():\n            similarity = get_cosine(queryed_documents_tfidf[i], vector_query)\n            x = show_results_cosine_similarity(i, similarity, df)\n            if len(heap_data) < k:\n                heapq.heappush(heap_data, x)\n            else:\n                heapq.heappushpop(heap_data, x)\n\n        for i in range(len(heap_data)):\n            output = output.append(pd.Series([heap_data[-(i+1)][1][0], heap_data[-(i+1)][1][1], \n                                              heap_data[-(i+1)][1][2], heap_data[-(i+1)][0]], \n                                             index=output.columns), ignore_index=True) \n        output = output.sort_values(by='Similarity', ascending=False)\n        output = HTML(output.to_html(escape=False,\n                                     formatters=dict(column_name_with_image_links=path_to_image_html)))\n        return output\n```\n\n\n```python\n# Run cell\ntfidfDicts = read_json('data/tfidf.json')\n```\n\n\n```python\n# Run cell\ninput_query = 'break heart'\n```\n\n\n```python\n# Run cell\nsearch_engine_2(query = input_query, inverted_index = inverted_index, \n                vocabulary=vocabulary, tfidf_scores_dict=tfidfDicts,\n                df = df_dirty, k = 10)\n```\n\n\n\n\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>BookTitle</th>\n      <th>Plot</th>\n      <th>Url</th>\n      <th>Similarity</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2</th>\n      <td>Against All Odds</td>\n      <td>Our lives shattered... Our hearts broken... Our souls torn to pieces...   He was my world, my whole life. My reason for breathing. I had a perfect marriage, a baby on the way, and I felt fulfilled\u2014almost invincible.    Until the day life hit, leaving me broken, vulnerable, and alone.   She was my life. My ray of hope on the cloudiest day. With her, I thought I had the ultimate safety. A love that would never hurt or betray me. I gave her my heart, my body, and my soul.    Until she broke me, destroying every dream and illusion I had about life, love, and marriage.   In our grief, we made a mistake. A mistake I'm not sure we can come back from.</td>\n      <td>https://www.goodreads.com/book/show/18803442-against-all-odds</td>\n      <td>0.293084</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>The Knight of the Rose</td>\n      <td>Book no longer in print.    Refer now to the combined Tears of the Broken and The Knight of the Rose as \"Dark Secrets\".   Sequel to the internationally successful vampire novel, Tears of the Broken.   Love was only the beginning of her nightmares.    When Ara discovered the existence of vampires, she was given the choice between a life as one of them, or a life without her true love.   But fate has a funny way of making choices for you.    After breaking the heart of the boy she loves with a truth he cannot bear, Ara will find herself in the arms of a predator who will steal her innocence and force the hand of fate.    Will David Knight become her rescuer once again, or will he be too late?</td>\n      <td>https://www.goodreads.com/book/show/13570791-the-knight-of-the-rose</td>\n      <td>0.220297</td>\n    </tr>\n    <tr>\n      <th>0</th>\n      <td>Almost Broken</td>\n      <td>Lauren Brooks fell in love with Cal Scott at 21, married him at 22 and had her heart broken at 23 when he walked out of their marriage. At 25, though raising his daughter on her own, Lauren was finally moving on with her life. Until, she learned the reason for Cal's abandonment, the walls she\u2019d carefully built around her collapsed..     The day she meets Chris, all those feelings she thought she had bottled up come spilling out. She can\u2019t afford to give into her heart\u2019s desire again. Love nearly broke her once, and her daughter doesn't need two broken parents.   Christopher Scott is in love, newly engaged to Jenna, who saw him through an illness he didn\u2019t think he could survive. He\u2019s finally settling into the life he\u2019s always wanted, making plans he only dared to dream before now.   Until, a woman named Lauren arrives on his doorstep.   She\u2019s intriguing, beautiful and, try as he might, he can\u2019t stay away. The closer he gets to her, the more his rock-solid plans begin to crumble. All he knows is that Lauren is the missing piece to a puzzle he must solve. For him to put all the pieces in place, he\u2019ll have to follow his heart, and that might cost him everything...</td>\n      <td>https://www.goodreads.com/book/show/22667507-almost-broken</td>\n      <td>0.217010</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>A Love Surrendered</td>\n      <td>Orphaned in Iowa, Annie Kennedy moves to Boston to stay with her spinster aunt. She longs for romance to fill the void left by her parents' death. But when she falls hard for Steven O'Connor, the man who broke an engagement to her sister, Annie is worried. Will he break her heart too when he discovers who she really is?</td>\n      <td>https://www.goodreads.com/book/show/13498999-a-love-surrendered</td>\n      <td>0.216607</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Broken for You</td>\n      <td>National best seller and  Today  show Book Club selection,  Broken for You  is the story of two women in self-imposed exile whose lives are transformed when their paths intersect. Stephanie Kallos's debut novel is a work of infinite charm, wit and heart. It is also a glorious homage to the beauty of broken things.    When we meet septuagenarian Margaret Hughes, she is living alone in a mansion in Seattle with only a massive collection of valuable antiques for company. Enter Wanda Schultz, a young woman with a broken heart who has come west to search for her wayward boyfriend. Both women are guarding dark secrets and have spent many years building up protective armor against the outside world. As their tentative friendship evolves, the armor begins to fall away and Margaret opens her house to the younger woman. This launches a series of unanticipated events, leading Margaret to discover a way to redeem her cursed past, and Wanda to learn the true purpose of her cross-country journey.    Both funny and heartbreaking,  Broken for You  is a testament to the saving graces of surrogate families and shows how far the tiniest repair jobs can go in righting the world's wrongs.</td>\n      <td>https://www.goodreads.com/book/show/96702.Broken_for_You</td>\n      <td>0.205746</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Bittersweet Moments</td>\n      <td>Can the embers of an old life ignite the flames of a new love?   Six years ago, Melisa Bergfeld\u2019s husband died. As the grief of losing him tore into her, she lost his last gift to her\u2014their unborn child\u2014and her hopes and dreams turned to ashes.   Left with a life she no longer wants, she seeks salvation in a homeless shelter. For a while, that\u2019s more than enough.   But when a fire breaks out, in walks the man who will try to save her life\u2014if she\u2019ll let him.   Florian \u201cHeat\u201d Dane has left behind a trail of broken hearts in his wake, including pieces of his own. For all the girls he\u2019s used to fill the hole in his heart, there has been just one he could never erase from his memories. But when Melisa married his best friend Scott Bergfeld, he knew she would never be his the way she\u2019d been the one unforgettable night they spent together. Now that she\u2019s back in his life, he will do anything to recapture her heart, even if it means giving away his own.   Heat still has the power to ignite passion in Melisa, something she both desires and rejects. He\u2019s a known heartbreaker, and if there is one thing Melisa doesn\u2019t need, it\u2019s another crack in her heart. But when he confesses his love for her, she fears her secrets from the past will surface. And she might be the one to break his heart this time.</td>\n      <td>https://www.goodreads.com/book/show/20895867-bittersweet-moments</td>\n      <td>0.193598</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>My Existence Craves Yours</td>\n      <td>My Existence Craves Yours is about how one heart seeks out the other in love, as if you\u2019re drought and they\u2019re rain. It\u2019s a story that contains true love, trauma of a broken heart, mental illness, imprisonment of one\u2019s soul and lessons of life.   Amna Dhanani says,  \u201cI went through my work trying to come up with a theme, I wrecked my brain for weeks until I saw a pattern for a story. I\u2019ve arranged the poems in a way that each poem has a place in the flow, even though the order that I\u2019ve made is fictional but I\u2019ve not only felt but lived every word that is in here, some by me and some by others as I couldn\u2019t stop myself from writing what my eyes saw, what my ears heard and what my heart felt through the pain of those around me. It often made my own existence suffer from their grief.   After the story, I\u2019ve shared bits and pieces about my suffering and survival, ending on The Words chapter.\u201d</td>\n      <td>https://www.goodreads.com/book/show/42356004-my-existence-craves-yours</td>\n      <td>0.180730</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Rock Hard</td>\n      <td>An ultimatum can break your heart...   Every night lead singer, Sed Lionheart whips thousands of women into a frenzy with his voice alone. But the stage is the only place Sed feels any passion since he lost Jessica...    If you\u2019re not willing to break all the rules...   It shattered her heart, but law student Jessica broke off her engagement to Sed, determined to be successful on her own terms. But no other man can ever hold a candle to Sed...   Then a chance meeting and tortuously close quarters lead to uncontrollable flares of passion and rediscovery of their unique penchant for public encounters. Now, in addition to the risk of mutual heartbreak every time they get together, they\u2019re in danger of truly scandalous public exposure...</td>\n      <td>https://www.goodreads.com/book/show/9442157-rock-hard</td>\n      <td>0.179152</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Half Hearts</td>\n      <td>A promise broken  Losing her family at a young age, and then broken promises from the man she\u2019d loved all her life, Charlie McCarty rarely allows anyone to get close to her. Resolved to live her life without love and determined to become a top-notch Veterinarian, she begins her residency in Redfield. Fate, however, has a way of stepping in to change even the most obstinate set plans and forces Charlie to face her past, push the boundaries of her control and her heart to the brink of destruction.   A passion fueled desire  It started out as a celebration, a chance for Charlie to let her hair down and just let go of her firm control for just one evening, but meeting a sexy as hell cowboy\u2014and his familiar best friend\u2014ambush everything. With relentless determination, both cowboys set out to show her that she is everything they want to complete their lives. Charlie begins to dream, once again, for the future she thought lost to her years ago.   A Journey of the Heart  When a terrifying figure from the past steps into their fragile romance, is their love enough to overcome the horror about to be unleashed or will it leave them with hearts broken in half?</td>\n      <td>https://www.goodreads.com/book/show/10043433-half-hearts</td>\n      <td>0.178943</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>Coast</td>\n      <td>One life-changing summer.   One boy.  The boy.  The boy who offered me safe touches and heart-stopping smiles - smiles he shared with his son.  We filled our days with porch-step kisses,   filled our ears with laughter,   filled our hearts with love.   Deep, soul-aching, desperate love.  But love is misleading.  It's an invisible, fleeting moment.  Somewhere between false adoration and pure hatred comes an emotion, a vulnerable need, a single desire.  It lives within the ones who miss it, who crave it,   who know better than to expect it.  Love is relentless.  Even when that love turns to hate, turns to loathing,   turns to pain.   Love should heal you.   But it can also break you.   Believe me, I know...  Because I'm Becca Owens - a broken girl...  ...And he's Josh Warden - the boy who broke me.</td>\n      <td>https://www.goodreads.com/book/show/30192405-coast</td>\n      <td>0.174375</td>\n    </tr>\n  </tbody>\n</table>\n\n\n\n## 3. Define a new score!\n\nBased on the information we have at our disposal, we have decided to explore two different approaches for our final search engine:\n1. Weighted average of the cosine_similarity, ratingValue, ratingCount and reviewCount. This is not the ideal scenario since weights are not justifiable without any data on the users search history (weights are completely based on human judgement). With more information on the user history we could continuously update the weights.\n\n\\begin{align}\nscore_{new} = \\frac{CosineSimilarity \\cdot \\omega_{1} + ratingValue \\cdot \\omega_{2} + ratingCount \\cdot \\omega_{3} + reviewCount \\cdot \\omega_{4}}{max(ratingValue) + max(ratingCount) + max(reviewCount)}\n\\end{align}\n\n\n2. Normalizing the variables ratingValue, ratingCount and reviewCount upon their maximum values of the queried book ids and multiply their sum against the cosine similarity value.\n\n\\begin{align}\nscore_{new} = CosineSimilarity \\cdot \\bigg(\\frac{ratingValue}{max(ratingValue)} + \\frac{ratingCount}{max(ratingCount)} + \\frac{reviewCount}{max(reviewCount)} \\bigg)\n\\end{align}\n\n\n```python\n%%time\nvocabulary_question3, inverted_index_question3 = get_vocabulary_inverted_index(df_clean,\n                columns=['BookTitle', 'BookSeries', 'BookAuthors', 'Plot', 'PublishingDate', 'Characters'])\n\nwrite_json('data/inverted_index_question3.json', inverted_index_question3)\nwrite_json('data/vocabulary_dict_question3.json', vocabulary_question3)\n\nvectorize_tfidf(df_clean, vocabulary_question3, \n                inverted_index_question3, json_name='tfidf_question3.json',\n                columns=['BookTitle', 'BookSeries', 'BookAuthors', 'Plot', 'PublishingDate', 'Characters'])\n```\n\n    Wall time: 19min 3s\n\n\n\n```python\n# Run cell\ndef show_results_cosine_similarity_and_ratings(book_id, cosine_similarity, df):\n    \"\"\"\n    Generate a tuple with the relevant information about a book that will be displayed in the search engine, \n    the cosine similarity score and relevant quantitative information about the book (rating, reviewcount, ratingcount)\n    df: Not pre-processed data set\n    \"\"\"\n    data = df[df.BookID == book_id][['BookTitle', 'Plot', 'Url']].values.tolist()[0]\n    ratingValue = float(df[df.BookID == book_id][['RatingValue']].values[0])\n    ratingCount = float(df[df.BookID == book_id][['RatingCount']].values[0])\n    reviewCount = float(df[df.BookID == book_id][['ReviewCount']].values[0])\n    output = (cosine_similarity, ratingValue, ratingCount, reviewCount, data)\n    return output\n```\n\n\n```python\n# Run cell\ninverted_index_question3 = read_json('data/inverted_index_question3.json')\nvocabulary_question3 = read_json_simple('data/vocabulary_dict_question3.json')\ntfidfDicts_question3 = read_json('data/tfidf_question3.json')\n```\n\n\n```python\n# Run cell\ndef search_engine_3(query, inverted_index, vocabulary, tfidf_scores_dict, df, k = 10,\n                    new_score='cosine_normalizer', weights=None):\n    \"\"\"\n    df: Not pre-processed data set!\n    There are currently two alterantives for the computation of the new score:\n    - cosine_normalizer: Normalize all quantitative values and multiply against cosine similiarity\n    - weighted_average: Give weights to all features based on expert judgement (provide weights as list required!!)\n    - weights: list with weights:\n        weights[0]: weight for cosine_similiarity\n        weights[1]: weight for ratingValue\n        weights[2]: weight for ratingCount\n        weights[3]: weight for reviewCount\n\n    \"\"\"\n   \n    output = pd.DataFrame(columns=['BookTitle', 'Plot', 'Url', 'Score'])\n    documents_with_query_words = query_function(query, inverted_index, vocabulary)\n    queryed_documents_tfidf = {key: value for key, value in tfidf_scores_dict.items() if key in documents_with_query_words}\n    heap_data = []\n    \n    if len(documents_with_query_words) == 0:\n        print('There are no results for the search')\n    else:\n        \n        # pre-process query\n        query = global_pre_process(query)\n\n        # vectorize query\n        vector_query = {}\n        for word in query.split(' '):\n            index = vocabulary[word]\n            vector_query[index] = 1\n\n        # Get max_ratingCount and max_reviewCount\n        ratingValue_list = []\n        ratingCount_list = []\n        reviewCount_list = []\n        ratings_df = df[df.BookID.isin(documents_with_query_words)]\n\n        max_ratingValue = max(list(map(float, df.RatingValue)))\n        max_ratingCount = max(list(map(int, df.RatingCount)))\n        max_reviewCount = max(list(map(int, df.ReviewCount)))\n\n        # Compute cosine over all intersected documents\n        for i in queryed_documents_tfidf.keys():\n            similarity = get_cosine(queryed_documents_tfidf[i], vector_query)\n            temp = show_results_cosine_similarity_and_ratings(i, similarity, df)\n            if new_score == 'weighted_average':\n                # temp[0] = cosine_similarity\n                # temp[1] = rating\n                # temp[2] = ratingCount\n                # temp[3] = reviewCount\n                # temp[4] = Relevant book information ([booktitle, plot, url])\n                score = (temp[0]*weights[0] + temp[1]*weights[1] + temp[2]*weights[2] + temp[3]*weights[3])/np.sum([max_ratingValue, \n                                                                                                                    max_ratingCount, \n                                                                                                                    max_reviewCount])\n                x = (score, temp[4])\n            elif new_score == 'cosine_normalizer':\n                # temp[0] = cosine_similarity\n                # temp[1] = rating\n                # temp[2] = ratingCount\n                # temp[3] = reviewCount\n                # temp[4] = Relevant book information ([booktitle, plot, url])\n                score = temp[0]*(temp[1]/max_ratingValue + temp[2]/max_ratingCount + temp[3]/max_reviewCount)\n                x = (score, temp[4])\n            else:\n                raise('New score method is not implemented')\n\n            if len(heap_data) < k:\n                heapq.heappush(heap_data, x)\n            else:\n                heapq.heappushpop(heap_data, x)\n\n\n        for i in range(len(heap_data)):\n            output = output.append(pd.Series([heap_data[-(i+1)][1][0], heap_data[-(i+1)][1][1], \n                                              heap_data[-(i+1)][1][2], heap_data[-(i+1)][0]], \n                                             index=output.columns), ignore_index=True) \n        output = output.sort_values(by='Score', ascending=False)\n        output = HTML(output.to_html(escape=False,\n                                     formatters=dict(column_name_with_image_links=path_to_image_html)))\n        return output\n```\n\n\n```python\n# Run cell\ninput_query = 'friends in love'\n```\n\n#### First try using the cosine_normalizer approach\n\n\n```python\n# Run cell\nsearch_engine_3(query = input_query, inverted_index = inverted_index_question3, \n                vocabulary=vocabulary_question3, tfidf_scores_dict=tfidfDicts_question3,\n                df = df_dirty, k = 10,\n                new_score='cosine_normalizer')\n```\n\n\n\n\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>BookTitle</th>\n      <th>Plot</th>\n      <th>Url</th>\n      <th>Score</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>I Don't Want To Be Friends</td>\n      <td>David  is waiting in a bar for a date who\u2019s not going to show\u2026 bitter and alone, will he give up on the girl he loves?   After a summer spent apart  Scott  and  Haley  are back together, but something has changed between them\u2026 Will their relationship ever feel the same as before?   Madison \u2019s new mantra in life is: stay strong and survive senior year. She\u2019s in love with her best friend\u2019s boyfriend, but Scott only sees her as a friend, and her broken heart can\u2019t take it much longer. She needs to finish college and turn the page on an impossible love story\u2026 but can she be stronger than her feelings?   Two brothers in love with the same girl.Two best friends in love with the same guy.A love triangle within a love triangle\u2026</td>\n      <td>https://www.goodreads.com/book/show/46038462-i-don-t-want-to-be-friends</td>\n      <td>0.339369</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>My Best Friend's Boyfriend: A New Adult College Romance</td>\n      <td>David and Scott Williams are in love with the same girl, again.      Haley has never been happier than in her relationship with Scott. But she can no longer deny bad-boy David has gotten under her skin.      Madison has always been insecure in love. The only satisfying romances in her life come from the many books she reads. Book-boyfriends are easy to fall for, but the real world seems short of swoon-worthy heroes. And just when she thought she might\u2019ve found one, he fell in love with her best friend\u2026      Love and friendship mix in the Just Friends series\u2026 Meet new characters and catch up with old ones in the third book of the series.      My Best Friend\u2019s Boyfriend is part of the Just Friends new adult college romance series.   Reading order:   Book 1 - Let\u2019s Be Just Friends   Book 2 - Friend Zone   Book 3 - My Best Friend\u2019s Boyfriend</td>\n      <td>https://www.goodreads.com/book/show/46038451-my-best-friend-s-boyfriend</td>\n      <td>0.269437</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Friend Zone</td>\n      <td>Alice Brown  fell in love with Jack the day she moved into her freshman dorm. Problem is, she\u2019s been stuck in the friend zone ever since. After another meaningless breakup, she\u2019s ready to confess her feelings to Jack.   Jack Sullivan  has mistaken friendship for love once before and has vowed never to do it again. A varsity sports player, he\u2019s determined to enjoy college with no strings attached.   Peter Wells  is Jack\u2019s best wingman. He enjoys his popularity as team captain and when he meets Alice, he\u2019s ready to steal her heart.   When Jack sees Alice and Peter together, jealousy hits him hard. But will he break his vow to never date a friend?   Meet new characters and catch up with old ones in the second book in the Just Friends series.   Friend Zone  is part of the  Just Friends  new adult college romance series. Reading order:  Book 1 -  Let\u2019s Be Just Friends  Book 2 -  Friend Zone  Book 3 -  My Best Friend's Boyfriend  Book 4 -  I Don't Want To Be Friends</td>\n      <td>https://www.goodreads.com/book/show/46038439-friend-zone</td>\n      <td>0.223043</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Just Friends</td>\n      <td>Love and friendship mix in the Just Friends series\u2026 the books follow the misadventures and exploits of a group of college students in Boston.    For Rose being in love with her best friend has never been easy, but now that she\u2019s moved in with Tyler her feelings have become impossible to ignore.    Tyler has bitten more than he can chew, torn between two girls he must decide where his heart stands.    Georgiana is determined to do everything in her power to keep Tyler and Rose apart. After all, all is fair in love and war.    Alice fell in love with Jack the day she moved into her freshman dorm. Problem is, she\u2019s been stuck in the friend zone ever since. After another meaningless breakup, she\u2019s ready to confess her feelings to Jack.    Jack has mistaken friendship for love once before and has vowed never to do it again. A varsity sports player, he\u2019s determined to enjoy college with no strings attached.    Peter is Jack\u2019s best wingman. He enjoys his popularity as team captain and when he meets Alice, he\u2019s ready to steal her heart.    David and Scott Williams are in love with the same girl, again.    Haley has never been happier than in her relationship with Scott. But she can no longer deny bad-boy David has gotten under her skin.    Madison has always been insecure in love. The only satisfying romances in her life come from the many books she reads. Book-boyfriends are easy to fall for, but the real world seems short of swoon-worthy heroes. And just when she thought she might\u2019ve found one, he fell in love with her best friend\u2026    Read the complete series in this amazing box set\u2026</td>\n      <td>https://www.goodreads.com/book/show/40546422-just-friends</td>\n      <td>0.220114</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Angles - Part I</td>\n      <td>A compelling love story about Caralee, her best friend Teddy, and her new love interest, Sam. The intensity of Sam entering into Cara's life challenges her friendship with Teddy - which was forged long ago when they encountered a deranged gunman. Teddy will stop at nothing to protect Cara - even if it means keeping his long time business associate and once best friend far away from her.    This story is about friendship and relationship triangles, love and protection, love and understanding, and love and true love.</td>\n      <td>https://www.goodreads.com/book/show/35763791-angles</td>\n      <td>0.188829</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>The Four Loves</td>\n      <td>The Four Loves  summarizes four kinds of human love--affection, friendship, erotic love, and the love of God. Masterful without being magisterial, this book's wise, gentle, candid reflections on the virtues and dangers of love draw on sources from Jane Austen to St. Augustine. The chapter on charity (love of God) may be the best thing Lewis ever wrote about Christianity. Consider his reflection on Augustine's teaching that one must love only God, because only God is eternal, and all earthly love will someday pass away:   Who could conceivably begin to love God on such a prudential ground--because the security (so to speak) is better? Who could even include it among the grounds for loving? Would you choose a wife or a Friend--if it comes to that, would you choose a dog--in this spirit? One must be outside the world of love, of all loves, before one thus calculates.   His description of Christianity here is no less forceful and opinionated than in  Mere Christianity  or  The Problem of Pain , but it is far less  anxious  about its reader's response--and therefore more persuasive than any of his apologetics. When he begins to describe the nature of faith, Lewis writes: \"Take it as one man's reverie, almost one man's myth. If anything in it is useful to you, use it; if anything is not, never give it a second thought.\"  --Michael Joseph Gross</td>\n      <td>https://www.goodreads.com/book/show/29938407-the-four-loves</td>\n      <td>0.185871</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>Chicken Soup for the Teenage Soul: The Real Deal Friends: Best, Worst, Old, New, Lost, False, True and More (Chicken Soup for the Soul)</td>\n      <td>Friends. You gotta have 'em, but sometimes they drive you crazy. You love 'em, but sometimes they make you mad. They'll help you through a crisis...unless they are the crisis.   So What's the Deal?  Friends are more than just the people you hang out with. They make you laugh, they keep your secrets, they offer advice (some good, some bad), they give you a shoulder to cry on. Sometimes they move away, or betray your trust, or flake out, but mostly they are the people who are always there for you. And they know you'll be there when they need you most. Because that's what it means to be a friend.    Sometimes friendship is overwhelming, sometimes it's confusing, sometimes you feel like you don't have a friend in the world, but don't worry, it's like that for everyone. That's what the stories in this book are all about. They're from real teens, and they're about the bizarre, difficult and wonderful things that really happened to them and their friends. Put that together with weird facts, cool graphics, fun advice and quizzes designed to help you figure out what you and your friends are all about, and you've got the real deal on friendship!</td>\n      <td>https://www.goodreads.com/book/show/576087.Chicken_Soup_for_the_Teenage_Soul</td>\n      <td>0.154067</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>The Boy & His Ribbon</td>\n      <td>\u201cWhat do you do when you meet your soul mate? No wait\u2026that\u2019s too easy. What do you do when you meet your soul mate and have to spend a lifetime loving him in secret? I\u2019ll tell you what you do.You lie.\u201d   REN   Ren was eight when he learned that love doesn\u2019t exist\u2014that the one person who was supposed to adore him only cared how much he was worth.   His mother sold him and for two years, he lived in terror.  But then\u2026he ran.  He thought he\u2019d run on his own. Turned out, he took something of theirs by accident and it became the one thing he never wanted and the only thing he ever needed.    DELLA   I was young when I fell in love with him, when he switched from my world to my everything.   My parents bought him for cheap labour, just like they had with many other kids, and he had the scars to prove it.   At the start, he hated me, and I could understand why.  For years he was my worst enemy, fiercest protector, and dearest friend.  But by the end\u2026he loved me.  The only problem was, he loved me in an entirely different way to the way I loved him.  And slowly, my secret drove us apart.</td>\n      <td>https://www.goodreads.com/book/show/37914571-the-boy-his-ribbon</td>\n      <td>0.152213</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Memorizing You</td>\n      <td>Two high school boys from different walks of life: Ryan, a handsome athlete, and David, an average joe from a blue collar family, discover their desires, stealing their kisses under the cover of an old oak at night. Their love begins a secret life, hidden from their families, friends, and classmates. As their passion grows, so does the danger of their discovery. Their only hope is to create a separate world where every kiss is a treasure and every moment... memorable.   First love. Secret love. Unforgettable love.</td>\n      <td>https://www.goodreads.com/book/show/18188319-memorizing-you</td>\n      <td>0.152171</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>13 Minutes</td>\n      <td>They say you should keep your friends close and your enemies closer, but when you're a teenage girl, it's hard to tell them apart.   Natasha doesn't remember how she ended up in the icy water that night, but she does know this\u2014it wasn't an accident, and she wasn't suicidal. Her two closest friends are acting strangely, and Natasha turns to Becca, the best friend she dumped years before when she got popular, to help her figure out what happened.   Natasha's sure that her friends love her. But does that mean they didn't try to kill her?</td>\n      <td>https://www.goodreads.com/book/show/26842622-13-minutes</td>\n      <td>0.148462</td>\n    </tr>\n  </tbody>\n</table>\n\n\n\n#### Second try using the weighted_average approach\n\n\n```python\n# Run cell\nsearch_engine_3(query = input_query, inverted_index = inverted_index_question3, \n                vocabulary=vocabulary_question3, tfidf_scores_dict=tfidfDicts_question3,\n                df = df_dirty, k = 10,\n                new_score='weighted_average', weights=[0.5, 0.2, 0.2, 0.1])\n```\n\n\n\n\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>BookTitle</th>\n      <th>Plot</th>\n      <th>Url</th>\n      <th>Score</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2</th>\n      <td>Divergent</td>\n      <td>In Beatrice Prior's dystopian Chicago world, society is divided into five factions, each dedicated to the cultivation of a particular virtue\u2014Candor (the honest), Abnegation (the selfless), Dauntless (the brave), Amity (the peaceful), and Erudite (the intelligent). On an appointed day of every year, all sixteen-year-olds must select the faction to which they will devote the rest of their lives. For Beatrice, the decision is between staying with her family and being who she really is\u2014she can't have both. So she makes a choice that surprises everyone, including herself.   During the highly competitive initiation that follows, Beatrice renames herself Tris and struggles alongside her fellow initiates to live out the choice they have made. Together they must undergo extreme physical tests of endurance and intense psychological simulations, some with devastating consequences. As initiation transforms them all, Tris must determine who her friends really are\u2014and where, exactly, a romance with a sometimes fascinating, sometimes exasperating boy fits into the life she's chosen. But Tris also has a secret, one she's kept hidden from everyone because she's been warned it can mean death. And as she discovers unrest and growing conflict that threaten to unravel her seemingly perfect society, she also learns that her secret might help her save those she loves . . . or it might destroy her.</td>\n      <td>https://www.goodreads.com/book/show/13335037-divergent</td>\n      <td>0.081915</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>The Time Traveler's Wife</td>\n      <td>A funny, often poignant tale of boy meets girl with a twist: what if one of them couldn't stop slipping in and out of time? Highly original and imaginative, this debut novel raises questions about life, love, and the effects of time on relationships.   Audrey Niffenegger\u2019s innovative debut,  The Time Traveler\u2019s Wife , is the story of Clare, a beautiful art student, and Henry, an adventuresome librarian, who have known each other since Clare was six and Henry was thirty-six, and were married when Clare was twenty-three and Henry thirty-one. Impossible but true, because Henry is one of the first people diagnosed with Chrono-Displacement Disorder: periodically his genetic clock resets and he finds himself misplaced in time, pulled to moments of emotional gravity in his life, past and future. His disappearances are spontaneous, his experiences unpredictable, alternately harrowing and amusing.    The Time Traveler\u2019s Wife  depicts the effects of time travel on Henry and Clare\u2019s marriage and their passionate love for each other as the story unfolds from both points of view. Clare and Henry attempt to live normal lives, pursuing familiar goals\u2014steady jobs, good friends, children of their own. All of this is threatened by something they can neither prevent nor control, making their story intensely moving and entirely unforgettable.</td>\n      <td>https://www.goodreads.com/book/show/18619684-the-time-traveler-s-wife</td>\n      <td>0.044111</td>\n    </tr>\n    <tr>\n      <th>0</th>\n      <td>Charlotte's Web</td>\n      <td>This beloved book by E. B. White, author of  Stuart Little  and  The Trumpet of the Swan , is a classic of children's literature that is \"just about perfect.\" This high-quality paperback features vibrant illustrations colorized by Rosemary Wells!   Some Pig. Humble. Radiant. These are the words in Charlotte's Web, high up in Zuckerman's barn. Charlotte's spiderweb tells of her feelings for a little pig named Wilbur, who simply wants a friend. They also express the love of a girl named Fern, who saved Wilbur's life when he was born the runt of his litter.   E. B. White's Newbery Honor Book is a tender novel of friendship, love, life, and death that will continue to be enjoyed by generations to come. This edition contains newly color illustrations by Garth Williams, the acclaimed illustrator of E. B. White's  Stuart Little  and Laura Ingalls Wilder's Little House series, among many other books.</td>\n      <td>https://www.goodreads.com/book/show/24178.Charlotte_s_Web</td>\n      <td>0.039480</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>City of Ashes</td>\n      <td>Also see: Alternate Cover Editions for this ISBN [ACE]     \\nACE #1\\n   Clary Fray just wishes that her life would go back to normal. But what's normal when you're a demon-slaying Shadowhunter, your mother is in a magically induced coma, and you can suddenly see Downworlders like werewolves, vampires, and faeries? If Clary left the world of the Shadowhunters behind, it would mean more time with her best friend, Simon, who's becoming more than a friend. But the Shadowhunting world isn't ready to let her go \u2014 especially her handsome, infuriating, newfound brother, Jace. And Clary's only chance to help her mother is to track down rogue Shadowhunter Valentine, who is probably insane, certainly evil \u2014 and also her father.   To complicate matters, someone in New York City is murdering Downworlder children. Is Valentine behind the killings \u2014 and if he is, what is he trying to do? When the second of the Mortal Instruments, the Soul-Sword, is stolen, the terrifying Inquisitor arrives to investigate and zooms right in on Jace. How can Clary stop Valentine if Jace is willing to betray everything he believes in to help their father?   In this breathtaking sequel to  City of Bones , Cassandra Clare lures her readers back into the dark grip of New York City's Downworld, where love is never safe and power becomes the deadliest temptation.</td>\n      <td>https://www.goodreads.com/book/show/1582996.City_of_Ashes</td>\n      <td>0.021099</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>The Goldfinch</td>\n      <td>It begins with a boy. Theo Decker, a thirteen-year-old New Yorker, miraculously survives an accident that kills his mother. Abandoned by his father, Theo is taken in by the family of a wealthy friend. Bewildered by his strange new home on Park Avenue, disturbed by schoolmates who don't know how to talk to him, and tormented above all by his unbearable longing for his mother, he clings to one thing that reminds him of her: a small, mysteriously captivating painting that ultimately draws Theo into the underworld of art.   As an adult, Theo moves silkily between the drawing rooms of the rich and the dusty labyrinth of an antiques store where he works. He is alienated and in love-and at the center of a narrowing, ever more dangerous circle.   The Goldfinch  combines vivid characters, mesmerizing language, and suspense, while plumbing with a philosopher's calm the deepest mysteries of love, identity, and art. It is an old-fashioned story of loss and obsession, survival and self-invention, and the ruthless machinations of fate.</td>\n      <td>https://www.goodreads.com/book/show/17333223-the-goldfinch</td>\n      <td>0.020767</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>If I Stay</td>\n      <td>Librarian note: an alternate cover for this edition can be found here.   Just listen, Adam says with a voice that sounds like shrapnel.I open my eyes wide now.I sit up as much as I can.And I listen.Stay, he says.   Choices. Seventeen-year-old Mia is faced with some tough ones: Stay true to her first love\u2014music\u2014even if it means losing her boyfriend and leaving her family and friends behind?   Then one February morning Mia goes for a drive with her family, and in an instant, everything changes. Suddenly, all the choices are gone, except one. And it's the only one that matters.   If I Stay  is a heartachingly beautiful book about the power of love, the true meaning of family, and the choices we all make.</td>\n      <td>https://www.goodreads.com/book/show/4374400-if-i-stay</td>\n      <td>0.020220</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Matched</td>\n      <td>In the Society, officials decide. Who you love. Where you work. When you die.   Cassia has always trusted their choices. It\u2019s hardly any price to pay for a long life, the perfect job, the ideal mate. So when her best friend appears on the Matching screen, Cassia knows with complete certainty that he is the one\u2026until she sees another face flash for an instant before the screen fades to black. Now Cassia is faced with impossible choices: between Xander and Ky, between the only life she\u2019s known and a path no one else has ever dared follow\u2014between perfection and passion.   Matched  is a story for right now and storytelling with the resonance of a classic.</td>\n      <td>https://www.goodreads.com/book/show/7735333-matched</td>\n      <td>0.018530</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>The Sisterhood of the Traveling Pants</td>\n      <td>Carmen got the jeans at a thrift shop. They didn\u2019t look all that great: they were worn, dirty, and speckled with bleach. On the night before she and her friends part for the summer, Carmen decides to toss them.    But Tibby says they\u2019re great. She'd love to have them. Lena and Bridget also think they\u2019re fabulous. Lena decides that they should all try them on. Whoever they fit best will get them.    Nobody knows why, but the pants fit everyone perfectly. Even Carmen (who never thinks she looks good in anything) thinks she looks good in the pants. Over a few bags of cheese puffs, they decide to form a sisterhood and take the vow of the Sisterhood of the Traveling Pants . . . the next morning, they say good-bye.    And then the journey of the pants \u2014 and the most memorable summer of their lives \u2014 begins.</td>\n      <td>https://www.goodreads.com/book/show/452306.The_Sisterhood_of_the_Traveling_Pants</td>\n      <td>0.017326</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Hush, Hush</td>\n      <td>A SACRED OATHA FALLEN ANGELA FORBIDDEN LOVE   Romance was not part of Nora Grey's plan. She's never been particularly attracted to the boys at her school, no matter how hard her best friend, Vee, pushes them at her. Not until Patch comes along. With his easy smile and eyes that seem to see inside her, Patch draws Nora to him against her better judgment.   But after a series of terrifying encounters, Nora's not sure whom to trust. Patch seems to be everywhere she is and seems to know more about her than her closest friends. She can't decide whether she should fall into his arms or run and hide. And when she tries to seek some answers, she finds herself near a truth that is way more unsettling than anything Patch makes her feel.   For she is right in the middle of an ancient battle between the immortal and those that have fallen - and, when it comes to choosing sides, the wrong choice will cost Nora her life.</td>\n      <td>https://www.goodreads.com/book/show/6339664-hush-hush</td>\n      <td>0.016234</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>Vampire Academy</td>\n      <td>ONLY A TRUE BEST FRIEND CAN PROTECT YOU FROM YOUR IMMORTAL ENEMIES...   Lissa Dragomir is a Moroi princess: a mortal vampire with a rare gift for harnessing the earth's magic. She must be protected at all times from Strigoi; the fiercest vampires - the ones who never die. The powerful blend of human and vampire blood that flows through Rose Hathaway, Lissa's best friend, makes her a dhampir. Rose is dedicated to a dangerous life of protecting Lissa from the Strigoi, who are hell-bent on making Lissa one of them.   After two years of freedom, Rose and Lissa are caught and dragged back to St. Vladimir's Academy, a school for vampire royalty and their guardians-to-be, hidden in the deep forests of Montana. But inside the iron gates, life is even more fraught with danger... and the Strigoi are always close by.   Rose and Lissa must navigate their dangerous world, confront the temptations of forbidden love, and never once let their guard down, lest the evil undead make Lissa one of them forever...</td>\n      <td>https://www.goodreads.com/book/show/345627.Vampire_Academy</td>\n      <td>0.015506</td>\n    </tr>\n  </tbody>\n</table>\n\n\n\n## 4. Make a nice visualization!\n\n\n```python\n# Run cell\ndef get_book_series(df, num_series=20, series_to_include=['Harry Potter']):\n    \"\"\" \n    Get first num_series Book Series based on the order of apperance (also including series in the list series_to_include)\n    df: Not pre-processed data set!\n    \"\"\"\n    bookSeries = {}\n    for index, row in df.iterrows():\n        d_id = row['BookID']\n        book_data = row\n        clean_series = re.sub(r'[^a-zA-Z0-9]', ' ', book_data['BookSeries']).split()\n        series_name = re.sub(r'[^a-zA-Z]', ' ', book_data['BookSeries']).rstrip().lstrip()\n        # If the book is part of a series and the series is one single book\n        if (series_name != '') & (len([i for i in clean_series if bool(re.match(r'\\d+', i))]) == 1):\n            if series_name not in bookSeries:\n                # Make sure we only take the first 20 series\n                if (len(bookSeries.keys()) < num_series) | (series_name in series_to_include):\n                    split_date = re.findall(r'\\d+', book_data['PublishingDate'])\n                    year = [i for i in split_date if len(i) == 4][0]\n                    bookSeries[series_name] = [[' '.join(clean_series), year, book_data['NumberofPages'], book_data['Url']]]\n            else:                \n                split_date = re.findall(r'\\d+', book_data['PublishingDate'])\n                try:\n                    year = [i for i in split_date if len(i) == 4][0]\n                except:\n                    year = book_data[8]\n                bookSeries[series_name].append([' '.join(clean_series), year, book_data['NumberofPages'], book_data['Url']])\n\n    return bookSeries\n```\n\n\n```python\n# Run cell\nbook_series = get_book_series(df_dirty)\n```\n\n\n```python\n# Run cell\nfrom ipywidgets import interact, Dropdown\n\ndropdown_bookSeries = Dropdown(options = list(book_series.keys()))\n\ndef plot_series(series_name, bookSeries_dict = book_series):\n    publish_years = [i[1] for i in bookSeries_dict[series_name]]\n    pages = [i[2] for i in bookSeries_dict[series_name]]\n    df = pd.DataFrame(columns=['Year', 'Pages'])\n    df['Year'] = [int(i) for i in publish_years]\n    df['Pages'] = [int(i) for i in pages]\n    df = df.sort_values(by='Year', ascending=True)\n    df['Years Since Publishment'] = df.Year - df.Year.min()\n    df['Pages of Book Series'] = df.Pages.cumsum()\n    df.plot(x = 'Years Since Publishment', y = 'Pages of Book Series', title = series_name,\n            figsize=(12,8))\n    print(df)\n    \n@interact(series_name = dropdown_bookSeries)\ndef dropdown_series(series_name):\n    plot_series(series_name)\n```\n\n\n    interactive(children=(Dropdown(description='series_name', options=('The Hunger Games', 'From  A Journal of Lov\u2026\n\n\n\n```python\n\n```\n\n## 5. Algorithmic Question\n\n#### Write a recursive program that, given a string, computes the length of the subsequence of maximum length that is in alphabetical order. Try some examples. Are the examples of short strings correct? Can you find examples that your algorithm does not terminate in reasonable time?\n\n\n```python\ndef recursive_function_terminates_n(X, n):\n    \"\"\"\n    Compute the longest subsequence in alphabetical order that terminates at position n of the string X\n    X: string\n    n: len string    \n    \"\"\"\n    if n == 1:\n        return 1\n    else:\n        return 1 + max([recursive_function_terminates_n(X[:-i], len(X[:-i])) for i in range(1, n) if X[n-1] > X[-(i+1)]], \n                       default=0)\n    \ndef recursive_function(X):\n    \"\"\"\n    Function to loop over all letter in the word X and compute the real longest subsequence in \n    alphabteical order of the whole string\n    \"\"\"\n    len_list = []\n    for i in range(len(X)):\n        len_list.append(recursive_function_terminates_n(X[:i+1], len(X[:i+1])))\n    return max(len_list)\n```\n\n#### Write a program that computes the length of the subsequence of maximum length, using dynamic programming.\n\n\n```python\ndef dynamic_function(X, print_max_len = False): \n    \"\"\" \n    X is a string\n    \"\"\"\n    m = len(X)\n\n    L = [X[0]]\n\n    # We going letter by letter adding the new letter to all possible alphabetically ordered strings\n    for i in range(1, m):\n        L =  L + [X[i]] + [j + X[i] for j in L if j[-1] < X[i]]\n        \n    # Conditions t print all the max length strings or not\n    L_len = [len(j) for j in L]\n    if print_max_len:\n        L_max = [j for j in L if len(j) == max(L_len)]\n        return max(L_len), L_max\n    else:\n        return max(L_len)\n```\n\n#### Quick proof that both functions return the same results\n\n\n```python\nimport random \nimport string\n\ndef get_string(n):\n    \n    return  ''.join(random.choice(string.ascii_uppercase) for _ in range(n))\n\nX = get_string(25)\n\nres_1 = recursive_function(X)\nres_2 = dynamic_function(X)\nassert res_1 == res_2\n```\n\n#### Prove that the formula for X[i] given above is correct.   (CORRECT)\n\nWe are given the following algorithm to obtain the length of the longest subsequence in alphabetical order:\n\n\\begin{align}\nX[i] = 1 + max(X[j]; j = 0, ..., i-1, \\text{ s.t. } S[j]<S[i])\n\\end{align}\n\n\\begin{align}\nX[i] = 1, \\text{ if there does not exist such as } j\n\\end{align}\n\n**Proof**\n\nWe will demonstrate this by breaking the problem down into smaller assumptions that logically guarantee the final conclusion.\n\n1. We can easily state that X[i] <= X[j] for every j > i. This is easy to prove since an additional letter can only make the subsequence longer.\n2. It is important to notice in the previous statement that we are using the <= sign and not the strict < since there are some conditions that need to be fulfilled for the strict < to occur.\n3. In particular, and considering the previous, we can be even more specific when expressing X[i] in terms of X[j] (please beer for a moment since the previous is only partially true):\n\n\\begin{align}\nX[i] = X[j] + 1 \\text{ if } S[j]>S[i] \n\\end{align}\n\n\\begin{align}\nX[i] = X[j] \\text{ if } S[j]<S[i]\n\\end{align}\n\n4. The issue with the previous statement is that we are only considering one single potential longest string, when in general we are interested in all possible string combinations (from 1 until j). In order to solve this we will look into the longest subsequence in alphabetical order of the X[j] string. This is preciselly what is being done in the term max(X[j]; j = 0, ..., i-1, s.t. S[j]<S[i]) (we loop over all X[j] values such that S[j]<S[i] and compute the longest subsequence in alphabetical order from these X[j]'s).\n5. Finally, if there is no S[j]<S[i], meaning that the string is of length 1, or that non of the letters are in alphabetical order, of course X[i] = 1.\n\n**Q.E.D.**\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "658df7d5c71496049b930b51bc9b1987d5ee93bd", "size": 125666, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "1 - Which book would you recomend?/main.ipynb", "max_stars_repo_name": "qtt-alessandro/Machine-Learning-Projects-in-Python-", "max_stars_repo_head_hexsha": "1eddce9101fd2d43ffc3242d6d0b52d1a9fd8664", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1 - Which book would you recomend?/main.ipynb", "max_issues_repo_name": "qtt-alessandro/Machine-Learning-Projects-in-Python-", "max_issues_repo_head_hexsha": "1eddce9101fd2d43ffc3242d6d0b52d1a9fd8664", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1 - Which book would you recomend?/main.ipynb", "max_forks_repo_name": "qtt-alessandro/Machine-Learning-Projects-in-Python-", "max_forks_repo_head_hexsha": "1eddce9101fd2d43ffc3242d6d0b52d1a9fd8664", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-13T11:44:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-13T11:44:19.000Z", "avg_line_length": 47.6910815939, "max_line_length": 1631, "alphanum_fraction": 0.545334458, "converted": true, "num_tokens": 22305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22270013882530884, "lm_q2_score": 0.064653495114655, "lm_q1q2_score": 0.014398342337575096}}
{"text": "# Setup\n\n\n```python\n%matplotlib inline\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\n```\n\n\n```python\ndata = pd.read_csv(\"articles_2017-12-01_2017-12-31.csv\", index_col=\"id\", \\\n                   parse_dates=[\"published\", \"discovered\"])\ndata.head()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>publisher_name</th>\n      <th>publisher_id</th>\n      <th>mins_as_lead</th>\n      <th>mins_on_front</th>\n      <th>num_articles_on_front</th>\n      <th>fb_brand_page</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>ddd1ccb2bc026b5b44204e5f4f08de1d75d4280a</th>\n      <td>https://www.thetimes.co.uk/article/winter-sun-...</td>\n      <td>Winter sun: 12 of the best holiday destinations</td>\n      <td>2017-12-04 00:04:58.520</td>\n      <td>2017-12-01</td>\n      <td>2</td>\n      <td>0.000000</td>\n      <td>2017-12-04T00:16:03.826Z</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>1435</td>\n      <td>237.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>126.0</td>\n    </tr>\n    <tr>\n      <th>d8409c3f40ce732ab4917e88f3991fba6e34052c</th>\n      <td>https://www.thetimes.co.uk/article/news-in-pic...</td>\n      <td>News in pictures</td>\n      <td>2017-12-01 03:24:07.825</td>\n      <td>2017-12-01</td>\n      <td>246</td>\n      <td>1.150685</td>\n      <td>2017-12-01T18:50:03.239Z</td>\n      <td>26</td>\n      <td>216</td>\n      <td>4</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>1235</td>\n      <td>293.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>8ec1e46d261cde4b7eb7818481e02a439a344966</th>\n      <td>https://www.thetimes.co.uk/article/the-best-ch...</td>\n      <td>The best Christmas photos from around the UK</td>\n      <td>2017-12-02 00:04:48.863</td>\n      <td>2017-12-01</td>\n      <td>0</td>\n      <td>0.000000</td>\n      <td>2017-12-02T00:16:18.566Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>1434</td>\n      <td>328.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>a0b6c78af7ce197a41eb7f2e8514929e40cf0f01</th>\n      <td>https://www.thetimes.co.uk/article/nationalist...</td>\n      <td>In\u00e9s Arrimadas: Nationalist\u2019s wife leads call ...</td>\n      <td>2017-12-01 07:39:11.810</td>\n      <td>2017-12-01</td>\n      <td>0</td>\n      <td>0.000000</td>\n      <td>2017-12-01T07:50:11.497Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>565</td>\n      <td>294.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>125.0</td>\n    </tr>\n    <tr>\n      <th>d6b3d8608c147417d6f83042303ad18d48df5069</th>\n      <td>https://www.thetimes.co.uk/article/winners-of-...</td>\n      <td>Winners of the mini-reshuffle</td>\n      <td>2017-12-01 00:08:35.154</td>\n      <td>2017-12-01</td>\n      <td>1</td>\n      <td>0.016389</td>\n      <td>2017-12-01T10:30:08.613Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>1435</td>\n      <td>291.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>125.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n# Response Score\n\nThe response score is a number between 0 and 50 that indicates the level of response to an article.\n\n\n\nPerhaps in the future we may choose to include other factors, but for now we just include engagements on Facebook. The maximum score of 50 should be achieved by an article that does really well compared with others.\n\n\n```python\npd.options.display.float_format = '{:.2f}'.format\ndata.fb_engagements.describe([0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count    139145.00\n    mean       1105.88\n    std        9852.92\n    min           0.00\n    50%          24.00\n    75%         243.00\n    90%        1545.00\n    95%        4086.00\n    99%       20228.36\n    99.5%     32446.04\n    99.9%     87128.53\n    max     1741886.00\n    Name: fb_engagements, dtype: float64\n\n\n\nThere's 3 articles with more than 1 million engagements this month.\n\n\n```python\ndata[data.fb_engagements > 1000000]\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>publisher_name</th>\n      <th>publisher_id</th>\n      <th>mins_as_lead</th>\n      <th>mins_on_front</th>\n      <th>num_articles_on_front</th>\n      <th>fb_brand_page</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>5c2b2bee6d23ef061ff65a0adcd0fb2e1d5374bf</th>\n      <td>http://www.dailymail.co.uk/health/article-2054...</td>\n      <td>Bad news for dads: Babies 'should share mother...</td>\n      <td>2017-12-08 16:18:25.150</td>\n      <td>2017-12-07 21:00:00</td>\n      <td>1502932</td>\n      <td>284.84</td>\n      <td>2017-12-09T04:07:10.793Z</td>\n      <td>573487</td>\n      <td>672710</td>\n      <td>256735</td>\n      <td>Daily Mail</td>\n      <td>dailymail_co_uk</td>\n      <td>0</td>\n      <td>0</td>\n      <td>nan</td>\n      <td>True</td>\n      <td>13574153.00</td>\n      <td>2017-12-08T16:15:11.000Z</td>\n      <td>158</td>\n      <td>494.00</td>\n    </tr>\n    <tr>\n      <th>5bf276f7b22af522d1a15b94ad40f1b3858d3e61</th>\n      <td>https://www.nytimes.com/2017/12/12/us/politics...</td>\n      <td>Once a Long Shot, Democrat Doug Jones Wins Ala...</td>\n      <td>2017-12-13 03:28:08.107</td>\n      <td>2017-12-13 03:25:52</td>\n      <td>1054926</td>\n      <td>8809.66</td>\n      <td>2017-12-13T04:12:18.429Z</td>\n      <td>86607</td>\n      <td>906432</td>\n      <td>61887</td>\n      <td>New York Times</td>\n      <td>nytimes_com</td>\n      <td>840</td>\n      <td>1319</td>\n      <td>120.00</td>\n      <td>True</td>\n      <td>15020753.00</td>\n      <td>2017-12-13T03:28:45.000Z</td>\n      <td>120</td>\n      <td>1454.00</td>\n    </tr>\n    <tr>\n      <th>823cc4c44f81ebb54e4adef2e98c20f95480055f</th>\n      <td>https://www.washingtonpost.com/national/health...</td>\n      <td>CDC gets list of forbidden words: fetus, trans...</td>\n      <td>2017-12-16 00:08:50.251</td>\n      <td>2017-12-15 23:53:00</td>\n      <td>1741886</td>\n      <td>1850.97</td>\n      <td>2017-12-16T02:04:09.495Z</td>\n      <td>457275</td>\n      <td>1017806</td>\n      <td>266805</td>\n      <td>The Washington Post</td>\n      <td>washingtonpost_com</td>\n      <td>0</td>\n      <td>3749</td>\n      <td>89.00</td>\n      <td>True</td>\n      <td>6099192.00</td>\n      <td>2017-12-16T00:27:14.000Z</td>\n      <td>191</td>\n      <td>766.00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndata.fb_engagements.mode()\n```\n\n\n\n\n    0    0\n    dtype: int64\n\n\n\n*last month* Going back to the enagement counts, we see the mean is 1,117, mode is zero, median is 24, 90th percentile is 1,453, 99th percentile is 21,166, 99.5th percentile is 33,982. The standard deviation is 8,083, significantly higher than the mean, so this is not a normal distribution. \n\nGoing back to the enagement counts, we see the mean is 1,106, mode is zero, median is 24, 90th percentile is 1,545, 99th percentile is 20,228, 99.5th percentile is 32,446. The standard deviation is 9,852, significantly higher than the mean, so this is not a normal distribution. \n\nKey publishers stats\n\n\n```python\ndata.groupby(\"publisher_id\").agg({'url': 'count', 'fb_engagements': ['sum', 'median', 'mean']})\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th>url</th>\n      <th colspan=\"3\" halign=\"left\">fb_engagements</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>count</th>\n      <th>sum</th>\n      <th>median</th>\n      <th>mean</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>20</td>\n      <td>40120</td>\n      <td>1809.00</td>\n      <td>2006.00</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>10821</td>\n      <td>7646802</td>\n      <td>28.00</td>\n      <td>706.66</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>2640</td>\n      <td>11722200</td>\n      <td>270.50</td>\n      <td>4440.23</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>45</td>\n      <td>24409</td>\n      <td>188.00</td>\n      <td>542.42</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>1182</td>\n      <td>2772469</td>\n      <td>165.00</td>\n      <td>2345.57</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>3085</td>\n      <td>14990814</td>\n      <td>638.00</td>\n      <td>4859.26</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>22066</td>\n      <td>15935337</td>\n      <td>29.00</td>\n      <td>722.17</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>340</td>\n      <td>90374</td>\n      <td>32.00</td>\n      <td>265.81</td>\n    </tr>\n    <tr>\n      <th>evolvepolitics_com</th>\n      <td>39</td>\n      <td>274563</td>\n      <td>1592.00</td>\n      <td>7040.08</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>5043</td>\n      <td>15670336</td>\n      <td>72.00</td>\n      <td>3107.34</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>3870</td>\n      <td>268372</td>\n      <td>5.00</td>\n      <td>69.35</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>8947</td>\n      <td>10716052</td>\n      <td>9.00</td>\n      <td>1197.73</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>5718</td>\n      <td>4911814</td>\n      <td>31.00</td>\n      <td>859.01</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>500</td>\n      <td>290099</td>\n      <td>52.00</td>\n      <td>580.20</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>3644</td>\n      <td>2019719</td>\n      <td>82.50</td>\n      <td>554.26</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>142</td>\n      <td>1988</td>\n      <td>8.00</td>\n      <td>14.00</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>9514</td>\n      <td>6559353</td>\n      <td>54.50</td>\n      <td>689.44</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>1793</td>\n      <td>5202028</td>\n      <td>446.00</td>\n      <td>2901.30</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>362</td>\n      <td>61350</td>\n      <td>23.00</td>\n      <td>169.48</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>1878</td>\n      <td>7021350</td>\n      <td>239.50</td>\n      <td>3738.74</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>4541</td>\n      <td>17519582</td>\n      <td>215.00</td>\n      <td>3858.09</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>170</td>\n      <td>55692</td>\n      <td>162.50</td>\n      <td>327.60</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>55</td>\n      <td>71414</td>\n      <td>529.00</td>\n      <td>1298.44</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>5213</td>\n      <td>1842218</td>\n      <td>20.00</td>\n      <td>353.39</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>2572</td>\n      <td>2600470</td>\n      <td>264.00</td>\n      <td>1011.07</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>102</td>\n      <td>68492</td>\n      <td>263.50</td>\n      <td>671.49</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>6285</td>\n      <td>2283897</td>\n      <td>18.00</td>\n      <td>363.39</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>184</td>\n      <td>220508</td>\n      <td>609.00</td>\n      <td>1198.41</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>7662</td>\n      <td>9020836</td>\n      <td>122.00</td>\n      <td>1177.35</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>8869</td>\n      <td>338754</td>\n      <td>1.00</td>\n      <td>38.20</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>21217</td>\n      <td>12472172</td>\n      <td>0.00</td>\n      <td>587.84</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>274</td>\n      <td>371790</td>\n      <td>51.50</td>\n      <td>1356.90</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>352</td>\n      <td>792901</td>\n      <td>165.50</td>\n      <td>2252.56</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\n\nnon_zero_fb_enagagements = data.fb_engagements[data.fb_engagements > 0]\n```\n\nThat's a bit better, but still way too clustered at the low end. Let's look at a log normal distribution.\n\n\n```python\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\nninety = data.fb_engagements.quantile(.90)\nninetyfive = data.fb_engagements.quantile(.95)\nninetynine = data.fb_engagements.quantile(.99)\n\nplt.figure(figsize=(12,4.5))\nplt.hist(np.log(non_zero_fb_enagagements + median), bins=50)\nplt.axvline(np.log(mean), linestyle=':', label=f'Mean ({mean:,.0f})', color='green')\nplt.axvline(np.log(median), label=f'Median ({median:,.0f})', color='green')\nplt.axvline(np.log(ninety), linestyle='--', label=f'90% percentile ({ninety:,.0f})', color='red')\nplt.axvline(np.log(ninetyfive), linestyle='-.', label=f'95% percentile ({ninetyfive:,.0f})', color='red')\nplt.axvline(np.log(ninetynine), linestyle=':', label=f'99% percentile ({ninetynine:,.0f})', color='red')\nleg = plt.legend()\n\n```\n\n\n```python\neng = data.fb_engagements[(data.fb_engagements < 5000)]\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\nninety = data.fb_engagements.quantile(.90)\nninetyfive = data.fb_engagements.quantile(.95)\nninetynine = data.fb_engagements.quantile(.99)\n\nplt.figure(figsize=(15,7))\nplt.hist(eng, bins=50)\nplt.title(\"Article count by engagements\")\nplt.axvline(median, label=f'Median ({median:,.0f})', color='green')\nplt.axvline(mean, linestyle=':', label=f'Mean ({mean:,.0f})', color='green')\nplt.axvline(ninety, linestyle='--', label=f'90% percentile ({ninety:,.0f})', color='red')\nplt.axvline(ninetyfive, linestyle='-.', label=f'95% percentile ({ninetyfive:,.0f})', color='red')\n# plt.axvline(ninetynine, linestyle=':', label=f'99% percentile ({ninetynine:,.0f})', color='red')\nleg = plt.legend()\n\n```\n\n\n```python\nlog_engagements = (non_zero_fb_enagagements\n                   .clip_upper(data.fb_engagements.quantile(.999))\n                   .apply(lambda x: np.log(x + median))\n                  )\nlog_engagements.describe()\n```\n\n\n\n\n    count   112066.00\n    mean         4.99\n    std          1.77\n    min          3.22\n    25%          3.50\n    50%          4.41\n    75%          6.06\n    max         11.38\n    Name: fb_engagements, dtype: float64\n\n\n\nUse standard feature scaling to bring that to a 1 to 50 range\n\n\n\n```python\ndef scale_log_engagements(engagements_logged):\n    return np.ceil(\n        50 * (engagements_logged - log_engagements.min()) / (log_engagements.max() - log_engagements.min())\n    )\n\ndef scale_engagements(engagements):\n    return scale_log_engagements(np.log(engagements + median))\n\nscaled_non_zero_engagements = scale_log_engagements(log_engagements)\nscaled_non_zero_engagements.describe()\n```\n\n\n\n\n    count   112066.00\n    mean        11.33\n    std         10.89\n    min          0.00\n    25%          2.00\n    50%          8.00\n    75%         18.00\n    max         50.00\n    Name: fb_engagements, dtype: float64\n\n\n\n\n```python\n# add in the zeros, as zero\nscaled_engagements = pd.concat([scaled_non_zero_engagements, data.fb_engagements[data.fb_engagements == 0]])\n```\n\n\n```python\nproposed = pd.DataFrame({\"fb_engagements\": data.fb_engagements, \"response_score\": scaled_engagements})\nproposed.response_score.plot.hist(bins=50)\n```\n\nLooks good to me, lets save that.\n\n\n```python\ndata[\"response_score\"] = proposed.response_score\n```\n\n### Proposal\n\nThe maximum of 50 points is awarded when the engagements are greater than the 99.9th percentile, rolling over the last month. \n\ni.e. where $limit$ is the 99.5th percentile of engagements calculated over the previous month, the response score for article $a$ is:\n\n\\begin{align}\nbasicScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   \\log(\\min(engagements_a,limit) + median(engagements))      & \\text{if } engagements_a > 0\n\\end{cases} \\\\\nresponseScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   50 \\cdot \\frac{basicScore_a - \\min(basicScore)}{\\max(basicScore) - \\min(basicScore)}       & \\text{if } engagements_a > 0\n\\end{cases} \\\\\n\\\\\n\\text{The latter equation can be expanded to:} \\\\\nresponseScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   50 \\cdot \n   \\frac{\\log(\\min(engagements_a,limit) + median(engagements)) - \\log(1 + median(engagements))}\n   {\\log(limit + median(engagements)) - \\log(1 + median(engagements))}       & \\text{if } engagements_a > 0\n\\end{cases} \\\\\n\\end{align}\n\n# Promotion Score\n\nThe aim of the promotion score is to indicate how important the article was to the publisher, by tracking where they chose to promote it. This is a number between 0 and 50 comprised of:\n\n- 20 points based on whether the article was promoted as the \"lead\" story on the publisher's home page\n- 15 points based on how long the article was promoted anywhere on the publisher's home page\n- 15 points based on whether the article was promoted on the publisher's main facebook brand page\n\nThe first two should be scaled by the popularity/reach of the home page, for which we use the alexa page rank as a proxy.\n\nThe last should be scaled by the popularity/reach of the brand page, for which we use the number of likes the brand page has.\n\n### Lead story (20 points)\n\n\n```python\ndata.mins_as_lead.describe([0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count   139145.00\n    mean        10.25\n    std        107.35\n    min          0.00\n    50%          0.00\n    75%          0.00\n    90%          0.00\n    95%          0.00\n    99%        305.00\n    99.5%      594.00\n    99.9%     1359.00\n    max      13930.00\n    Name: mins_as_lead, dtype: float64\n\n\n\nAs expected, the vast majority of articles don't make it as lead. Let's explore how long typically publishers put something as lead for.\n\n\n```python\nlead_articles = data[data.mins_as_lead > 0]\n```\n\n\n```python\nlead_articles.mins_as_lead.describe([0.25, 0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count    4013.00\n    mean      355.24\n    std       526.37\n    min         4.00\n    25%        94.00\n    50%       190.00\n    75%       425.00\n    90%       888.20\n    95%      1160.60\n    99%      1890.20\n    99.5%    2723.16\n    99.9%    5808.77\n    max     13930.00\n    Name: mins_as_lead, dtype: float64\n\n\n\n\n```python\nlead_articles.mins_as_lead.plot.hist(bins=50)\n```\n\nFor lead, it's a  significant thing for an article to be lead at all, so although we want to penalise articles that were lead for a very short time, mostly we want to score the maximum even if it wasn't lead for ages. So we'll give maximum points when something has been lead for an hour.\n\n\n```python\nlead_articles.mins_as_lead.clip_upper(60).plot.hist(bins=50)\n```\n\nWe also want to scale this by the alexa page rank, such that the maximum score of 20 points is for an article that was on the front for 4 hours for the most popular site.\n\nSo lets explore the alexa nunbers.\n\n\n```python\nalexa_ranks = data.groupby(by=\"publisher_id\").alexa_rank.mean().sort_values()\nalexa_ranks\n```\n\n\n\n\n    publisher_id\n    bbc_co_uk                               96\n    cnn_com                                105\n    nytimes_com                            120\n    theguardian_com                        142\n    buzzfeed_com                           147\n    dailymail_co_uk                        158\n    washingtonpost_com                     191\n    huffingtonpost_com                     215\n    foxnews_com                            285\n    rt_com                                 365\n    telegraph_co_uk                        370\n    independent_co_uk                      386\n    reuters_com                            497\n    npr_org                                594\n    lemonde_fr                             618\n    mirror_co_uk                           706\n    nbcnews_com                            826\n    breitbart_com                          994\n    ft_com                                1596\n    economist_com                         1825\n    indy100_com                           5014\n    thetimes_co_uk                        6435\n    newstatesman_com                     12769\n    thecanary_co                         15686\n    propublica_org                       16066\n    yournewswire_com                     22568\n    order-order_com                      32515\n    anotherangryvoice_blogspot_co_uk     77827\n    westmonster_com                      97775\n    evolvepolitics_com                  119412\n    skwawkbox_org                       152475\n    libdemvoice_org                     344992\n    brexitcentral_com                   469149\n    Name: alexa_rank, dtype: int64\n\n\n\n\n```python\nalexa_ranks.plot.bar(figsize=[10,5])\n```\n\nLet's try the simple option first: just divide the number of minutes as lead by the alexa rank. What's the scale of numbers we get then.\n\n\n```python\nlead_proposal_1 = lead_articles.mins_as_lead.clip_upper(60) / lead_articles.alexa_rank\nlead_proposal_1.plot.hist()\n```\n\nLooks like there's too much of a cluster around 0. Have we massively over penalised the publishers with a high alexa rank?\n\n\n```python\nlead_proposal_1.groupby(data.publisher_id).mean().plot.bar(figsize=[10,5])\n```\n\nYes. Let's try taking the log of the alexa rank and see if that looks better.\n\n\n```python\nlead_proposal_2 = (lead_articles.mins_as_lead.clip_upper(60) / np.log(lead_articles.alexa_rank))\nlead_proposal_2.plot.hist()\n```\n\n\n```python\nlead_proposal_2.groupby(data.publisher_id).describe()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>25%</th>\n      <th>50%</th>\n      <th>75%</th>\n      <th>max</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>20.00</td>\n      <td>5.31</td>\n      <td>0.10</td>\n      <td>4.88</td>\n      <td>5.33</td>\n      <td>5.33</td>\n      <td>5.33</td>\n      <td>5.33</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>106.00</td>\n      <td>12.80</td>\n      <td>1.80</td>\n      <td>1.97</td>\n      <td>13.15</td>\n      <td>13.15</td>\n      <td>13.15</td>\n      <td>13.15</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>197.00</td>\n      <td>8.43</td>\n      <td>1.19</td>\n      <td>0.72</td>\n      <td>8.69</td>\n      <td>8.69</td>\n      <td>8.69</td>\n      <td>8.69</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>39.00</td>\n      <td>4.45</td>\n      <td>0.57</td>\n      <td>1.91</td>\n      <td>4.59</td>\n      <td>4.59</td>\n      <td>4.59</td>\n      <td>4.59</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>275.00</td>\n      <td>11.80</td>\n      <td>1.16</td>\n      <td>1.80</td>\n      <td>12.02</td>\n      <td>12.02</td>\n      <td>12.02</td>\n      <td>12.02</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>209.00</td>\n      <td>12.57</td>\n      <td>1.37</td>\n      <td>2.15</td>\n      <td>12.89</td>\n      <td>12.89</td>\n      <td>12.89</td>\n      <td>12.89</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>171.00</td>\n      <td>11.57</td>\n      <td>1.22</td>\n      <td>1.98</td>\n      <td>11.85</td>\n      <td>11.85</td>\n      <td>11.85</td>\n      <td>11.85</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>37.00</td>\n      <td>7.66</td>\n      <td>1.44</td>\n      <td>0.53</td>\n      <td>7.99</td>\n      <td>7.99</td>\n      <td>7.99</td>\n      <td>7.99</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>105.00</td>\n      <td>10.55</td>\n      <td>0.62</td>\n      <td>4.25</td>\n      <td>10.61</td>\n      <td>10.61</td>\n      <td>10.61</td>\n      <td>10.61</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>69.00</td>\n      <td>7.69</td>\n      <td>1.54</td>\n      <td>0.54</td>\n      <td>8.14</td>\n      <td>8.14</td>\n      <td>8.14</td>\n      <td>8.14</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>165.00</td>\n      <td>11.00</td>\n      <td>0.88</td>\n      <td>5.40</td>\n      <td>11.17</td>\n      <td>11.17</td>\n      <td>11.17</td>\n      <td>11.17</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>134.00</td>\n      <td>9.68</td>\n      <td>1.51</td>\n      <td>0.84</td>\n      <td>10.07</td>\n      <td>10.07</td>\n      <td>10.07</td>\n      <td>10.07</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>166.00</td>\n      <td>5.79</td>\n      <td>1.86</td>\n      <td>0.47</td>\n      <td>4.69</td>\n      <td>7.04</td>\n      <td>7.04</td>\n      <td>7.04</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>184.00</td>\n      <td>8.59</td>\n      <td>1.93</td>\n      <td>0.78</td>\n      <td>9.34</td>\n      <td>9.34</td>\n      <td>9.34</td>\n      <td>9.34</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>135.00</td>\n      <td>4.58</td>\n      <td>0.55</td>\n      <td>0.78</td>\n      <td>4.71</td>\n      <td>4.71</td>\n      <td>4.71</td>\n      <td>4.71</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>333.00</td>\n      <td>8.51</td>\n      <td>1.80</td>\n      <td>0.61</td>\n      <td>9.15</td>\n      <td>9.15</td>\n      <td>9.15</td>\n      <td>9.15</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>111.00</td>\n      <td>8.45</td>\n      <td>1.67</td>\n      <td>0.60</td>\n      <td>8.93</td>\n      <td>8.93</td>\n      <td>8.93</td>\n      <td>8.93</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>55.00</td>\n      <td>6.01</td>\n      <td>1.23</td>\n      <td>1.48</td>\n      <td>6.35</td>\n      <td>6.35</td>\n      <td>6.35</td>\n      <td>6.35</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>135.00</td>\n      <td>9.07</td>\n      <td>1.27</td>\n      <td>1.57</td>\n      <td>9.39</td>\n      <td>9.39</td>\n      <td>9.39</td>\n      <td>9.39</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>59.00</td>\n      <td>12.25</td>\n      <td>1.57</td>\n      <td>2.09</td>\n      <td>12.53</td>\n      <td>12.53</td>\n      <td>12.53</td>\n      <td>12.53</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>168.00</td>\n      <td>4.75</td>\n      <td>1.52</td>\n      <td>0.48</td>\n      <td>3.83</td>\n      <td>5.78</td>\n      <td>5.78</td>\n      <td>5.78</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>22.00</td>\n      <td>5.96</td>\n      <td>1.10</td>\n      <td>1.03</td>\n      <td>6.20</td>\n      <td>6.20</td>\n      <td>6.20</td>\n      <td>6.20</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>87.00</td>\n      <td>9.11</td>\n      <td>1.84</td>\n      <td>0.81</td>\n      <td>9.66</td>\n      <td>9.66</td>\n      <td>9.66</td>\n      <td>9.66</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>162.00</td>\n      <td>9.29</td>\n      <td>2.39</td>\n      <td>0.68</td>\n      <td>10.17</td>\n      <td>10.17</td>\n      <td>10.17</td>\n      <td>10.17</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>102.00</td>\n      <td>4.76</td>\n      <td>0.79</td>\n      <td>0.75</td>\n      <td>5.03</td>\n      <td>5.03</td>\n      <td>5.03</td>\n      <td>5.03</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>87.00</td>\n      <td>9.78</td>\n      <td>1.42</td>\n      <td>2.37</td>\n      <td>10.15</td>\n      <td>10.15</td>\n      <td>10.15</td>\n      <td>10.15</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>148.00</td>\n      <td>4.63</td>\n      <td>1.81</td>\n      <td>0.41</td>\n      <td>3.11</td>\n      <td>5.38</td>\n      <td>6.21</td>\n      <td>6.21</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>157.00</td>\n      <td>11.48</td>\n      <td>2.11</td>\n      <td>1.01</td>\n      <td>12.11</td>\n      <td>12.11</td>\n      <td>12.11</td>\n      <td>12.11</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>77.00</td>\n      <td>6.52</td>\n      <td>1.24</td>\n      <td>1.03</td>\n      <td>6.84</td>\n      <td>6.84</td>\n      <td>6.84</td>\n      <td>6.84</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>83.00</td>\n      <td>11.30</td>\n      <td>1.15</td>\n      <td>0.95</td>\n      <td>11.42</td>\n      <td>11.42</td>\n      <td>11.42</td>\n      <td>11.42</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>74.00</td>\n      <td>4.68</td>\n      <td>1.26</td>\n      <td>0.78</td>\n      <td>5.22</td>\n      <td>5.22</td>\n      <td>5.22</td>\n      <td>5.22</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>141.00</td>\n      <td>5.57</td>\n      <td>0.81</td>\n      <td>2.69</td>\n      <td>5.59</td>\n      <td>5.99</td>\n      <td>5.99</td>\n      <td>5.99</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nlead_proposal_2.groupby(data.publisher_id).min().plot.bar(figsize=[10,5])\n```\n\nThat looks about right, as long as the smaller publishers were closer to zero. So let's apply feature scaling to this, to give a number between 1 and 20. (Anything not as lead will pass though as zero.)\n\n\n```python\ndef rescale(series):\n    return (series - series.min()) / (series.max() - series.min())\n\nlead_proposal_3 = np.ceil(20 * rescale(lead_proposal_2))\n```\n\n\n```python\nlead_proposal_2.min(), lead_proposal_2.max()\n```\n\n\n\n\n    (0.41405622016623894, 13.145359968846892)\n\n\n\n\n```python\nlead_proposal_3.plot.hist()\n```\n\n\n```python\nlead_proposal_3.groupby(data.publisher_id).median().plot.bar(figsize=[10,5])\n```\n\n\n```python\ndata[\"lead_score\"] = pd.concat([lead_proposal_3, data.mins_as_lead[data.mins_as_lead==0]])\n```\n\n\n```python\ndata.lead_score.value_counts().sort_index()\n```\n\n\n\n\n    0.00     135133\n    1.00         46\n    2.00         40\n    3.00         47\n    4.00         45\n    5.00         51\n    6.00         53\n    7.00        230\n    8.00        224\n    9.00        245\n    10.00       146\n    11.00       189\n    12.00        61\n    13.00        81\n    14.00       581\n    15.00       363\n    16.00       345\n    17.00       266\n    18.00       244\n    19.00       402\n    20.00       353\n    Name: lead_score, dtype: int64\n\n\n\n\n```python\ndata.lead_score.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    8.00\n    bbc_co_uk                          20.00\n    breitbart_com                      14.00\n    brexitcentral_com                   7.00\n    buzzfeed_com                       19.00\n    cnn_com                            20.00\n    dailymail_co_uk                    18.00\n    economist_com                      12.00\n    evolvepolitics_com                  0.00\n    foxnews_com                        17.00\n    ft_com                             13.00\n    huffingtonpost_com                 17.00\n    independent_co_uk                  16.00\n    indy100_com                        11.00\n    lemonde_fr                         15.00\n    libdemvoice_org                     7.00\n    mirror_co_uk                       14.00\n    nbcnews_com                        14.00\n    newstatesman_com                   10.00\n    npr_org                            15.00\n    nytimes_com                        20.00\n    order-order_com                     9.00\n    propublica_org                     10.00\n    reuters_com                        15.00\n    rt_com                             16.00\n    skwawkbox_org                       8.00\n    telegraph_co_uk                    16.00\n    thecanary_co                       10.00\n    theguardian_com                    19.00\n    thetimes_co_uk                     11.00\n    washingtonpost_com                 18.00\n    westmonster_com                     8.00\n    yournewswire_com                    9.00\n    Name: lead_score, dtype: float64\n\n\n\nIn summary then, score for article $a$ is:\n\n\n$$\nunscaledLeadScore_a = \\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)}\\\\\nleadScore_a = 19 \\cdot \n\\frac{unscaledLeadScore_a - \\min(unscaledLeadScore)}\n{\\max(unscaledLeadScore) - \\min(unscaledLeadScore)} \n+ 1\n$$\n\nSince the minium value of $minsAsLead$ is 1, $\\min(unscaledLeadScore)$ is pretty insignificant. So we can simplify this to:\n\n$$\nleadScore_a = 20 \\cdot \n\\frac{unscaledLeadScore_a }\n     {\\max(unscaledLeadScore)} \n$$\n\nor: \n\n$$\nleadScore_a = 20 \\cdot \n\\frac{\\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)} }\n     {\\frac{60}{\\log(\\max(alexaRank))}} \n$$\n\n$$\nleadScore_a = \\left( 20 \\cdot \n\\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)} \\cdot\n     {\\frac{\\log(\\max(alexaRank))}{60}} \\right)\n$$\n\n## Time on front score (15 points)\n\nThis is similar to time as lead, so lets try doing the same calculation, except we also want to factor in the number of slots on the front:\n\n\n$$frontScore_a = \n15 \n\\left(\\frac{\\min(minsOnFront_a, 1440)}{alexaRank_a \\cdot numArticlesOnFront_a}\\right) \n\\left( \\frac{\\min(alexaRank \\cdot numArticlesOnFront)}{1440} \\right)$$\n\n\n```python\n(data.alexa_rank * data.num_articles_on_front).min() / 1440\n```\n\n\n\n\n    2.4500000000000002\n\n\n\n\n```python\ntime_on_front_proposal_1 = np.ceil(data.mins_on_front.clip_upper(1440) / (data.alexa_rank * data.num_articles_on_front) * (2.45) * 15)\n```\n\n\n```python\ntime_on_front_proposal_1.plot.hist(figsize=(15, 7), bins=15)\n```\n\n\n```python\ntime_on_front_proposal_1.value_counts().sort_index()\n```\n\n\n\n\n    1.00     65696\n    2.00      6558\n    3.00      4381\n    4.00      4043\n    5.00       713\n    6.00       467\n    7.00       491\n    8.00       446\n    9.00       947\n    10.00      205\n    11.00      192\n    12.00      387\n    13.00      215\n    14.00       88\n    15.00       68\n    dtype: int64\n\n\n\n\n```python\ntime_on_front_proposal_1.groupby(data.publisher_id).sum()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk      20.00\n    bbc_co_uk                          14840.00\n    breitbart_com                       2576.00\n    brexitcentral_com                     45.00\n    buzzfeed_com                        9269.00\n    cnn_com                            11015.00\n    dailymail_co_uk                    12847.00\n    economist_com                        196.00\n    evolvepolitics_com                    37.00\n    foxnews_com                         6244.00\n    ft_com                              2475.00\n    huffingtonpost_com                  7800.00\n    independent_co_uk                   4067.00\n    indy100_com                          499.00\n    lemonde_fr                          3639.00\n    libdemvoice_org                      142.00\n    mirror_co_uk                        9036.00\n    nbcnews_com                         1715.00\n    newstatesman_com                     358.00\n    npr_org                             2406.00\n    nytimes_com                         9063.00\n    order-order_com                      170.00\n    propublica_org                        55.00\n    reuters_com                         6295.00\n    rt_com                              4391.00\n    skwawkbox_org                        102.00\n    telegraph_co_uk                     4161.00\n    thecanary_co                         183.00\n    theguardian_com                    12282.00\n    thetimes_co_uk                      8832.00\n    washingtonpost_com                  8507.00\n    westmonster_com                      256.00\n    yournewswire_com                     352.00\n    dtype: float64\n\n\n\nThat looks good to me.\n\n\n```python\ndata[\"front_score\"] = np.ceil(data.mins_on_front.clip_upper(1440) / (data.alexa_rank * data.num_articles_on_front) * (2.45) * 15).fillna(0)\n```\n\n\n```python\ndata.front_score \n```\n\n\n\n\n    id\n    ddd1ccb2bc026b5b44204e5f4f08de1d75d4280a   1.00\n    d8409c3f40ce732ab4917e88f3991fba6e34052c   1.00\n    8ec1e46d261cde4b7eb7818481e02a439a344966   1.00\n    a0b6c78af7ce197a41eb7f2e8514929e40cf0f01   1.00\n    d6b3d8608c147417d6f83042303ad18d48df5069   1.00\n    617651116dbfa17ce3192113309e3fc36c653bb7   1.00\n    895b257635c005e56f8c33804d1e1b15adafa4ac   1.00\n    aaf6aea336edb397ab00ba5b07afa76a7b5a62f0   1.00\n    8669975be98765a81a7c563c33cc8477778b2d96   1.00\n    d1689b6457ebc3c471a836aa2e1638e54635f09d   1.00\n    7864cbd80daceedb03462a2e8acc99af0af843eb   1.00\n    a0000c6cbabd41b73833f2e03d737a65f0310192   1.00\n    46cf09d0abaebe8e43560dd298a324bbf3061925   1.00\n    b68f6aea1926d28ad82dd59c88f6afb048ad50c3   1.00\n    0459ed970d4bf508bfe956f838175ca95a26e63d   1.00\n    7a32f7ef1be604c817442af980c9caea6c554728   1.00\n    6c5f507bcf7468a5958705907bc57bfcf07189ff   1.00\n    a19c0121b70fa21942d150f3df8ae94414e9a929   1.00\n    a4aac0567b150accb92fce3b239d99428e63964d   1.00\n    7feb3b9ca2006c3ba3ed1b500785a828efd661e3   1.00\n    f4847375127b100848f654f00665aa39471b4966   1.00\n    411003c86ad9dcfae6bbae44563abfc3ae30ee68   1.00\n    457fcb987305dcf9c5494ec3769ec4c8810ed666   1.00\n    7e061ce50c3d37a8ff7f24cbfe03cbb4b59196b1   1.00\n    c9571e9beb0d861bbe4dd6a84e53c3c06ab11e38   1.00\n    34d49d78a8945fd1a66b05a74cc914a839fe8ccf   1.00\n    f36ba216b4dee0e67e94d5a65c22248b1d6bab53   1.00\n    6a579d2a5b6a597aceb38ce26146c45badc25e84   1.00\n    b5c1335d4e30cffb2fe1068ef2cb1033ae3e5737   1.00\n    bfe41b70413238cac3c7507812d245ac0602cdaa   1.00\n                                               ... \n    bfae49c09de2767f82e72a12f5b12764c1ce7820   0.00\n    70c0842823086bd113b46a4e59d65ddb65fffbe4   0.00\n    8c411f2a9c58264e5bd070efb6571e3a1fdf1c3c   1.00\n    7877d1f78013c05e3f27af8397db90cad54dfbda   1.00\n    300a44e0beba24a2e51dffdf9836a2dfc85b9476   1.00\n    e870230a01a0f4644b05730e10e951f40dbead3b   0.00\n    56f96111213c53307bfc938a13a93e91ca279a82   1.00\n    1613e5ee04e452487058b1a366aa1f043ac083cd   0.00\n    8974f3e2076e9f7a603d83f217618daa039593c2   0.00\n    ef76454179a8471433f96bfa479afecc10ba135c   0.00\n    1e4c5f31a5ad70b5d95d0c2dbcb1b00b7c015f93   1.00\n    a05a77d7acbb4a660e89f9d756e736bf7d9ef44d   6.00\n    2550727576c66a34027959450c0bbbd4294af766   4.00\n    f8160c9f615f4454fcd667b0013e108e76344e68   0.00\n    9deb9c716841e1238e8fdbcf930ad61ad6ef7543   0.00\n    6d429eb2b256224d88dc65c7cec8f30223d5e513   0.00\n    5ecf4d8ee26077a04e67b131825596003b62c37c   0.00\n    bdbf38c1bd2d8b34a4dd30bfb23d06a2bbbda741   1.00\n    dd188e1f4c1e9d3c52436bab86dccc632b7e976a   0.00\n    10bc19ceb4744dadeebb54b131f00b27d523dc6e   0.00\n    b84a4946cbd1485cbd093be665d701c2c7715e6b   0.00\n    dea7aa4d75a3ab52308f89b2afa370e18ae252d8   2.00\n    d49f5492306ecdf8b0584aeb4ca6e5366101bfeb   1.00\n    95869409b267dd18f18b99bd3587fcc37777443c   3.00\n    f4eafe68c3ab197dfe036046a04c28b3d5ecac65   0.00\n    ffd528fd949229fa7684ac6bc966c8d3fc0bc687   1.00\n    10357eed59889a5ee0da5195c5cd6b110e4e31cf   0.00\n    fcb700f805f54fa7b8468b8008881115917018eb   1.00\n    af42fc6be7c3e331ad9831c18406ffebdf49128e   0.00\n    9869d24d1829f06aa84b50d93e2ba029f28bd514   0.00\n    Name: front_score, Length: 139145, dtype: float64\n\n\n\n## Facebook brand page promotion (15 points)\n\nOne way a publisher has of promoting content is to post to their brand page. The significance of doing so is stronger when the brand page has more followers (likes).\n\n$$ facebookPromotionProposed1_a = 15 \\left( \\frac {brandPageLikes_a} {\\max(brandPageLikes)} \\right) $$\n\nNow lets explore the data to see if that makes sense. **tr;dr the formula above is incorrect**\n\n\n```python\ndata.fb_brand_page_likes.max()\n```\n\n\n\n\n    45331565.0\n\n\n\n\n```python\nfacebook_promotion_proposed_1 = np.ceil((15 * (data.fb_brand_page_likes / data.fb_brand_page_likes.max())).fillna(0))\n```\n\n\n```python\nfacebook_promotion_proposed_1.value_counts().sort_index().plot.bar()\n```\n\n\n```python\nfacebook_promotion_proposed_1.groupby(data.publisher_id).describe()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>25%</th>\n      <th>50%</th>\n      <th>75%</th>\n      <th>max</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>20.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>10821.00</td>\n      <td>0.63</td>\n      <td>3.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>15.00</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>2640.00</td>\n      <td>0.85</td>\n      <td>0.99</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>45.00</td>\n      <td>0.91</td>\n      <td>0.29</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>1182.00</td>\n      <td>0.54</td>\n      <td>0.50</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>3085.00</td>\n      <td>3.07</td>\n      <td>4.61</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>10.00</td>\n      <td>10.00</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>22066.00</td>\n      <td>0.61</td>\n      <td>1.64</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>5.00</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>340.00</td>\n      <td>2.44</td>\n      <td>1.17</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>evolvepolitics_com</th>\n      <td>39.00</td>\n      <td>0.95</td>\n      <td>0.22</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>5043.00</td>\n      <td>0.87</td>\n      <td>2.11</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>6.00</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>3870.00</td>\n      <td>0.48</td>\n      <td>0.85</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>8947.00</td>\n      <td>0.47</td>\n      <td>1.28</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>5718.00</td>\n      <td>0.60</td>\n      <td>1.20</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>500.00</td>\n      <td>0.69</td>\n      <td>0.46</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>3644.00</td>\n      <td>0.80</td>\n      <td>0.98</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>142.00</td>\n      <td>0.95</td>\n      <td>0.22</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>9514.00</td>\n      <td>0.27</td>\n      <td>0.44</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>1793.00</td>\n      <td>2.29</td>\n      <td>1.98</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>362.00</td>\n      <td>0.79</td>\n      <td>0.41</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>1878.00</td>\n      <td>1.42</td>\n      <td>1.50</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>4541.00</td>\n      <td>1.62</td>\n      <td>2.42</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>5.00</td>\n      <td>6.00</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>170.00</td>\n      <td>0.76</td>\n      <td>0.43</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>55.00</td>\n      <td>0.76</td>\n      <td>0.43</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>5213.00</td>\n      <td>0.56</td>\n      <td>0.90</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>2572.00</td>\n      <td>1.03</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>102.00</td>\n      <td>0.99</td>\n      <td>0.10</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>6285.00</td>\n      <td>0.58</td>\n      <td>0.91</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>184.00</td>\n      <td>0.99</td>\n      <td>0.10</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>7662.00</td>\n      <td>0.52</td>\n      <td>1.13</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>8869.00</td>\n      <td>0.05</td>\n      <td>0.22</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>21217.00</td>\n      <td>0.18</td>\n      <td>0.71</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>274.00</td>\n      <td>0.29</td>\n      <td>0.46</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>352.00</td>\n      <td>0.10</td>\n      <td>0.30</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThat's too much variation: sites like the Guardian, which have a respectable 7.5m likes, should not be scoring a 3. Lets try applying a log to it, and then standard feature scaling again.\n\n\n```python\ndata.fb_brand_page_likes.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk     330509.00\n    bbc_co_uk                          45331565.00\n    breitbart_com                       3770975.00\n    brexitcentral_com                     13487.00\n    buzzfeed_com                        2826049.00\n    cnn_com                            29374374.00\n    dailymail_co_uk                    13812505.00\n    economist_com                       8415152.00\n    evolvepolitics_com                   119272.00\n    foxnews_com                        16099176.00\n    ft_com                              3724840.00\n    huffingtonpost_com                  9829303.00\n    independent_co_uk                   7950318.00\n    indy100_com                          233256.00\n    lemonde_fr                          3976365.00\n    libdemvoice_org                        8618.00\n    mirror_co_uk                        2945691.00\n    nbcnews_com                         9469485.00\n    newstatesman_com                     154787.00\n    npr_org                             6264453.00\n    nytimes_com                        15161266.00\n    order-order_com                       45291.00\n    propublica_org                       375168.00\n    reuters_com                         3936474.00\n    rt_com                              4956977.00\n    skwawkbox_org                          6461.00\n    telegraph_co_uk                     4411426.00\n    thecanary_co                         156579.00\n    theguardian_com                     7832684.00\n    thetimes_co_uk                       731034.00\n    washingtonpost_com                  6107196.00\n    westmonster_com                       16551.00\n    yournewswire_com                      27641.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\nnp.log(2149)\n```\n\n\n\n\n    7.6727578966425103\n\n\n\n\n```python\nnp.log(data.fb_brand_page_likes.groupby(data.publisher_id).max())\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk   12.71\n    bbc_co_uk                          17.63\n    breitbart_com                      15.14\n    brexitcentral_com                   9.51\n    buzzfeed_com                       14.85\n    cnn_com                            17.20\n    dailymail_co_uk                    16.44\n    economist_com                      15.95\n    evolvepolitics_com                 11.69\n    foxnews_com                        16.59\n    ft_com                             15.13\n    huffingtonpost_com                 16.10\n    independent_co_uk                  15.89\n    indy100_com                        12.36\n    lemonde_fr                         15.20\n    libdemvoice_org                     9.06\n    mirror_co_uk                       14.90\n    nbcnews_com                        16.06\n    newstatesman_com                   11.95\n    npr_org                            15.65\n    nytimes_com                        16.53\n    order-order_com                    10.72\n    propublica_org                     12.84\n    reuters_com                        15.19\n    rt_com                             15.42\n    skwawkbox_org                       8.77\n    telegraph_co_uk                    15.30\n    thecanary_co                       11.96\n    theguardian_com                    15.87\n    thetimes_co_uk                     13.50\n    washingtonpost_com                 15.62\n    westmonster_com                     9.71\n    yournewswire_com                   10.23\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\nThat's more like it, but the lower numbers should be smaller.\n\n\n```python\nnp.log(data.fb_brand_page_likes.groupby(data.publisher_id).max() / 1000)\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    5.80\n    bbc_co_uk                          10.72\n    breitbart_com                       8.24\n    brexitcentral_com                   2.60\n    buzzfeed_com                        7.95\n    cnn_com                            10.29\n    dailymail_co_uk                     9.53\n    economist_com                       9.04\n    evolvepolitics_com                  4.78\n    foxnews_com                         9.69\n    ft_com                              8.22\n    huffingtonpost_com                  9.19\n    independent_co_uk                   8.98\n    indy100_com                         5.45\n    lemonde_fr                          8.29\n    libdemvoice_org                     2.15\n    mirror_co_uk                        7.99\n    nbcnews_com                         9.16\n    newstatesman_com                    5.04\n    npr_org                             8.74\n    nytimes_com                         9.63\n    order-order_com                     3.81\n    propublica_org                      5.93\n    reuters_com                         8.28\n    rt_com                              8.51\n    skwawkbox_org                       1.87\n    telegraph_co_uk                     8.39\n    thecanary_co                        5.05\n    theguardian_com                     8.97\n    thetimes_co_uk                      6.59\n    washingtonpost_com                  8.72\n    westmonster_com                     2.81\n    yournewswire_com                    3.32\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\nscaled_fb_brand_page_likes = (data.fb_brand_page_likes / 1000)\nfacebook_promotion_proposed_2 = np.ceil(\\\n    (15 * \\\n     (np.log(scaled_fb_brand_page_likes) / np.log(scaled_fb_brand_page_likes.max()))\\\n    )\\\n                                       ).fillna(0)\n```\n\n\n```python\nfacebook_promotion_proposed_2.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    9.00\n    bbc_co_uk                          15.00\n    breitbart_com                      12.00\n    brexitcentral_com                   4.00\n    buzzfeed_com                       12.00\n    cnn_com                            15.00\n    dailymail_co_uk                    14.00\n    economist_com                      13.00\n    evolvepolitics_com                  7.00\n    foxnews_com                        14.00\n    ft_com                             12.00\n    huffingtonpost_com                 13.00\n    independent_co_uk                  13.00\n    indy100_com                         8.00\n    lemonde_fr                         12.00\n    libdemvoice_org                     4.00\n    mirror_co_uk                       12.00\n    nbcnews_com                        13.00\n    newstatesman_com                    8.00\n    npr_org                            13.00\n    nytimes_com                        14.00\n    order-order_com                     6.00\n    propublica_org                      9.00\n    reuters_com                        12.00\n    rt_com                             12.00\n    skwawkbox_org                       3.00\n    telegraph_co_uk                    12.00\n    thecanary_co                        8.00\n    theguardian_com                    13.00\n    thetimes_co_uk                     10.00\n    washingtonpost_com                 13.00\n    westmonster_com                     4.00\n    yournewswire_com                    5.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\nLGTM. So the equation is\n\n\n$$ facebookPromotion_a = 15 \\left( \n\\frac {\\log(\\frac {brandPageLikes_a}{1000})} \n{\\log(\\frac {\\max(brandPageLikes)}{1000}))} \\right) $$\n\n\nNow, let's try applying standard feature scaling approch to this, rather than using a magic number of 1,000. That equation would be:\n\n\\begin{align}\nunscaledFacebookPromotion_a &= \n   \\log(brandPageLikes_a) \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{unscaledFacebookPromotion_a - \\min(unscaledFacebookPromotion)}{\\max(unscaledFacebookPromotion) - \\min(unscaledFacebookPromotion)}  \\\\\n\\\\\n\\text{The scaling can be simplified to:} \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{unscaledFacebookPromotion_a - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))}  \\\\\n\\\\\n\\text{Meaning the overall equation becomes:} \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{\\log(brandPageLikes_a) - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))} \n   \\end{align}\n\n\n\n```python\nfacebook_promotion_proposed_3 = np.ceil(\n    (14 * \n     ( \n         (np.log(data.fb_brand_page_likes) - np.log(data.fb_brand_page_likes.min()) ) /\n         (np.log(data.fb_brand_page_likes.max()) - np.log(data.fb_brand_page_likes.min()))\n     )\n    ) + 1\n                                       )\n```\n\n\n```python\nfacebook_promotion_proposed_3.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    8.00\n    bbc_co_uk                          15.00\n    breitbart_com                      12.00\n    brexitcentral_com                   3.00\n    buzzfeed_com                       11.00\n    cnn_com                            15.00\n    dailymail_co_uk                    14.00\n    economist_com                      13.00\n    evolvepolitics_com                  6.00\n    foxnews_com                        14.00\n    ft_com                             12.00\n    huffingtonpost_com                 13.00\n    independent_co_uk                  13.00\n    indy100_com                         7.00\n    lemonde_fr                         12.00\n    libdemvoice_org                     2.00\n    mirror_co_uk                       11.00\n    nbcnews_com                        13.00\n    newstatesman_com                    7.00\n    npr_org                            12.00\n    nytimes_com                        14.00\n    order-order_com                     5.00\n    propublica_org                      8.00\n    reuters_com                        12.00\n    rt_com                             12.00\n    skwawkbox_org                       2.00\n    telegraph_co_uk                    12.00\n    thecanary_co                        7.00\n    theguardian_com                    13.00\n    thetimes_co_uk                      9.00\n    washingtonpost_com                 12.00\n    westmonster_com                     3.00\n    yournewswire_com                    4.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\ndata[\"facebook_promotion_score\"] = facebook_promotion_proposed_3.fillna(0.0)\n```\n\n# Review\n\n\n```python\ndata[\"promotion_score\"] = (data.lead_score + data.front_score + data.facebook_promotion_score)\ndata[\"attention_index\"] = (data.promotion_score + data.response_score)\n```\n\n\n```python\ndata.promotion_score.plot.hist(bins=np.arange(50), figsize=(15,6))\n```\n\n\n```python\ndata.attention_index.plot.hist(bins=np.arange(100), figsize=(15,6))\n```\n\n\n```python\ndata.attention_index.value_counts().sort_index()\n```\n\n\n\n\n    0.00     23004\n    1.00     17206\n    2.00     10703\n    3.00      7293\n    4.00      5918\n    5.00      4993\n    6.00      3946\n    7.00      3437\n    8.00      3179\n    9.00      2891\n    10.00     2645\n    11.00     2521\n    12.00     2284\n    13.00     2285\n    14.00     2069\n    15.00     1863\n    16.00     1822\n    17.00     1696\n    18.00     1614\n    19.00     1579\n    20.00     1460\n    21.00     1503\n    22.00     1509\n    23.00     1468\n    24.00     1450\n    25.00     1404\n    26.00     1391\n    27.00     1324\n    28.00     1325\n    29.00     1252\n             ...  \n    65.00      154\n    66.00      132\n    67.00       78\n    68.00       81\n    69.00       82\n    70.00       65\n    71.00       42\n    72.00       46\n    73.00       53\n    74.00       44\n    75.00       27\n    76.00       48\n    77.00       39\n    78.00       32\n    79.00       38\n    80.00       19\n    81.00       16\n    82.00       20\n    83.00       28\n    84.00       13\n    85.00       17\n    86.00        9\n    87.00       12\n    88.00       20\n    89.00       12\n    90.00        3\n    91.00        4\n    92.00        4\n    93.00        2\n    94.00        6\n    Name: attention_index, Length: 95, dtype: int64\n\n\n\n\n```python\n# and lets see the articles with the biggest attention index\ndata.sort_values(\"attention_index\", ascending=False)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>63152b4a2aa41e82016aa771891fdf1333128985</th>\n      <td>http://www.cnn.com/2017/12/05/politics/jeff-fl...</td>\n      <td>GOP Sen. Jeff Flake writes check to Democrat o...</td>\n      <td>2017-12-05 22:07:18.152</td>\n      <td>2017-12-05 22:01:48.000</td>\n      <td>115293</td>\n      <td>563.96</td>\n      <td>2017-12-05T22:49:09.264Z</td>\n      <td>13890</td>\n      <td>93202</td>\n      <td>8201</td>\n      <td>...</td>\n      <td>29256092.00</td>\n      <td>2017-12-05T22:30:17.000Z</td>\n      <td>105</td>\n      <td>173.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>6654a151fcbef618eb610580d5448ad83303b5a8</th>\n      <td>http://www.cnn.com/2017/12/16/health/cdc-banne...</td>\n      <td>Word ban at CDC includes 'vulnerable,' 'fetus,...</td>\n      <td>2017-12-16 16:04:22.124</td>\n      <td>2017-12-16 16:01:09.000</td>\n      <td>339451</td>\n      <td>3406.06</td>\n      <td>2017-12-16T22:04:03.814Z</td>\n      <td>94158</td>\n      <td>201048</td>\n      <td>44245</td>\n      <td>...</td>\n      <td>29319882.00</td>\n      <td>2017-12-16T16:40:20.000Z</td>\n      <td>105</td>\n      <td>447.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>33d3d70eb4c8c44c81f87f7cfc62a61e8f051150</th>\n      <td>http://www.cnn.com/2017/12/01/politics/senate-...</td>\n      <td>Uncertainty looms over Senate's tax bill</td>\n      <td>2017-12-01 06:16:20.820</td>\n      <td>2017-12-01 06:11:21.000</td>\n      <td>76401</td>\n      <td>121.19</td>\n      <td>2017-12-02T17:18:08.986Z</td>\n      <td>24222</td>\n      <td>43912</td>\n      <td>8267</td>\n      <td>...</td>\n      <td>29233578.00</td>\n      <td>2017-12-02T07:34:25.000Z</td>\n      <td>105</td>\n      <td>962.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>abe03a536d43790cd2c89fbeb8d3f3953376454d</th>\n      <td>http://www.cnn.com/2017/12/15/politics/judicia...</td>\n      <td>Trump judicial nominee struggles to answer bas...</td>\n      <td>2017-12-15 14:07:14.292</td>\n      <td>2017-12-15 14:02:30.000</td>\n      <td>108798</td>\n      <td>157.13</td>\n      <td>2017-12-16T02:46:13.544Z</td>\n      <td>36967</td>\n      <td>56279</td>\n      <td>15552</td>\n      <td>...</td>\n      <td>29318332.00</td>\n      <td>2017-12-16T02:29:02.000Z</td>\n      <td>105</td>\n      <td>327.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>46d8c8a0e17496bd7af92576c33efb6c80327f22</th>\n      <td>http://www.cnn.com/2017/12/06/us/ventura-fire-...</td>\n      <td>Ventura fire: Southern California grapples wit...</td>\n      <td>2017-12-06 08:55:34.234</td>\n      <td>2017-12-06 08:53:45.000</td>\n      <td>76140</td>\n      <td>73.96</td>\n      <td>2017-12-07T01:03:07.285Z</td>\n      <td>18241</td>\n      <td>48944</td>\n      <td>8955</td>\n      <td>...</td>\n      <td>29259398.00</td>\n      <td>2017-12-06T11:00:22.000Z</td>\n      <td>105</td>\n      <td>810.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>49974d79caf78028259583d5b24b6a272c81ba16</th>\n      <td>http://www.bbc.co.uk/news/world-middle-east-42...</td>\n      <td>Jerusalem: UN resolution rejects Trump's decla...</td>\n      <td>2017-12-21 17:25:06.643</td>\n      <td>2017-12-21 17:21:33.000</td>\n      <td>104052</td>\n      <td>1024.29</td>\n      <td>2017-12-21T18:18:13.675Z</td>\n      <td>14367</td>\n      <td>82849</td>\n      <td>6836</td>\n      <td>...</td>\n      <td>45205436.00</td>\n      <td>2017-12-21T17:51:41.000Z</td>\n      <td>96</td>\n      <td>119.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>d479366e1dab01635b8321713b5122e26d0e1e43</th>\n      <td>http://www.cnn.com/2017/12/10/politics/kfile-r...</td>\n      <td>Roy Moore in 2011: Getting rid of amendments a...</td>\n      <td>2017-12-10 23:10:12.827</td>\n      <td>2017-12-10 23:06:56.000</td>\n      <td>97289</td>\n      <td>156.92</td>\n      <td>2017-12-11T04:44:07.308Z</td>\n      <td>23777</td>\n      <td>56347</td>\n      <td>17165</td>\n      <td>...</td>\n      <td>29294730.00</td>\n      <td>2017-12-10T23:30:04.000Z</td>\n      <td>105</td>\n      <td>1243.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>b23787d954cd054eafa4e6bf352d71dfb793df17</th>\n      <td>http://www.cnn.com/2017/12/05/us/ventura-count...</td>\n      <td>1 dead, hundreds evacuate in fast-moving South...</td>\n      <td>2017-12-05 07:13:18.431</td>\n      <td>2017-12-05 07:06:21.000</td>\n      <td>86026</td>\n      <td>79.91</td>\n      <td>2017-12-05T14:14:04.504Z</td>\n      <td>25060</td>\n      <td>51634</td>\n      <td>9332</td>\n      <td>...</td>\n      <td>29253039.00</td>\n      <td>2017-12-05T14:00:14.000Z</td>\n      <td>105</td>\n      <td>196.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>4fbd6316c740d293ad9c2adb45c8b3e73a2225ea</th>\n      <td>http://www.bbc.co.uk/news/business-42353545</td>\n      <td>Walt Disney buys Murdoch's Fox for $52bn</td>\n      <td>2017-12-14 12:10:24.949</td>\n      <td>2017-12-14 12:08:08.000</td>\n      <td>40757</td>\n      <td>214.01</td>\n      <td>2017-12-14T12:31:24.627Z</td>\n      <td>8386</td>\n      <td>26851</td>\n      <td>5520</td>\n      <td>...</td>\n      <td>45140390.00</td>\n      <td>2017-12-14T12:20:08.000Z</td>\n      <td>96</td>\n      <td>64.00</td>\n      <td>46.00</td>\n      <td>20.00</td>\n      <td>11.00</td>\n      <td>15.00</td>\n      <td>46.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>454bb14b5b7017aae1cd27b5ba6fd159b00b5f6d</th>\n      <td>http://www.bbc.co.uk/news/world-us-canada-4223...</td>\n      <td>Supreme court backs Trump travel ban</td>\n      <td>2017-12-04 21:22:10.709</td>\n      <td>2017-12-04 21:19:04.000</td>\n      <td>64007</td>\n      <td>363.73</td>\n      <td>2017-12-04T21:34:10.895Z</td>\n      <td>9688</td>\n      <td>49710</td>\n      <td>4609</td>\n      <td>...</td>\n      <td>45022998.00</td>\n      <td>2017-12-04T21:23:49.000Z</td>\n      <td>96</td>\n      <td>67.00</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>579a2932b11423a6064a13062f0cf4291501f041</th>\n      <td>http://www.cnn.com/2017/12/04/politics/trump-m...</td>\n      <td>Trump fully endorses Roy Moore</td>\n      <td>2017-12-04 12:19:19.168</td>\n      <td>2017-12-04 12:15:22.000</td>\n      <td>68054</td>\n      <td>139.41</td>\n      <td>2017-12-04T14:07:15.216Z</td>\n      <td>25100</td>\n      <td>35731</td>\n      <td>7223</td>\n      <td>...</td>\n      <td>29245912.00</td>\n      <td>2017-12-04T12:45:01.000Z</td>\n      <td>105</td>\n      <td>223.00</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>6b9e111e87a519cfdf58f463da0827f8f426d668</th>\n      <td>http://www.cnn.com/2017/12/17/us/atlanta-airpo...</td>\n      <td>Atlanta's Hartsfield-Jackson airport crippled ...</td>\n      <td>2017-12-17 19:46:16.423</td>\n      <td>2017-12-17 19:42:18.000</td>\n      <td>72981</td>\n      <td>1472.54</td>\n      <td>2017-12-18T02:05:07.404Z</td>\n      <td>23851</td>\n      <td>36683</td>\n      <td>12447</td>\n      <td>...</td>\n      <td>29322298.00</td>\n      <td>2017-12-17T21:01:26.000Z</td>\n      <td>105</td>\n      <td>173.00</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>4bc906b992d5dafee16bef7f580b3b3d438e329e</th>\n      <td>http://www.bbc.co.uk/news/world-us-canada-4233...</td>\n      <td>Democrat Doug Jones projected to defeat Roy Mo...</td>\n      <td>2017-12-13 03:37:11.629</td>\n      <td>2017-12-13 03:34:12.000</td>\n      <td>57498</td>\n      <td>718.45</td>\n      <td>2017-12-13T04:11:10.090Z</td>\n      <td>6585</td>\n      <td>45624</td>\n      <td>5289</td>\n      <td>...</td>\n      <td>45130284.00</td>\n      <td>2017-12-13T03:56:33.000Z</td>\n      <td>96</td>\n      <td>73.00</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>63fa3fe45932328190916f1d4a8a98e683dae037</th>\n      <td>http://www.cnn.com/2017/12/21/politics/haley-u...</td>\n      <td>Haley tells UN: Jerusalem vote 'will be rememb...</td>\n      <td>2017-12-21 16:10:15.550</td>\n      <td>2017-12-21 16:06:13.000</td>\n      <td>79027</td>\n      <td>277.93</td>\n      <td>2017-12-21T19:17:18.583Z</td>\n      <td>24369</td>\n      <td>46433</td>\n      <td>8225</td>\n      <td>...</td>\n      <td>29337642.00</td>\n      <td>2017-12-21T19:02:11.000Z</td>\n      <td>105</td>\n      <td>176.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>51de2b073b9e2a4e399682bfb6618ff3e05843e8</th>\n      <td>https://www.buzzfeed.com/juliareinstein/turner...</td>\n      <td>Brock Turner Wants To Overturn His Sexual Assa...</td>\n      <td>2017-12-02 22:04:22.377</td>\n      <td>2017-12-02 21:48:03.000</td>\n      <td>48345</td>\n      <td>45.92</td>\n      <td>2017-12-03T01:29:09.818Z</td>\n      <td>9638</td>\n      <td>35158</td>\n      <td>3549</td>\n      <td>...</td>\n      <td>2793599.00</td>\n      <td>2017-12-03T01:05:00.000Z</td>\n      <td>147</td>\n      <td>413.00</td>\n      <td>47.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>6c09a9c935b40dc9eee1925a42ed82d1d3df037e</th>\n      <td>http://www.cnn.com/2017/12/01/politics/michael...</td>\n      <td>Flynn charged with one count of making false s...</td>\n      <td>2017-12-01 14:19:32.564</td>\n      <td>2017-12-01 14:16:50.000</td>\n      <td>148032</td>\n      <td>1214.16</td>\n      <td>2017-12-01T22:04:10.122Z</td>\n      <td>48459</td>\n      <td>79607</td>\n      <td>19966</td>\n      <td>...</td>\n      <td>29230687.00</td>\n      <td>2017-12-01T14:20:28.000Z</td>\n      <td>105</td>\n      <td>32.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>8d343bda0de91991a08cc37fe49e8f6a6223bd9a</th>\n      <td>http://www.cnn.com/2017/12/12/politics/alabama...</td>\n      <td>Alabama election: Roy Moore, Doug Jones vote</td>\n      <td>2017-12-12 20:25:16.987</td>\n      <td>2017-12-12 20:21:05.000</td>\n      <td>131891</td>\n      <td>750.91</td>\n      <td>2017-12-13T04:38:10.262Z</td>\n      <td>16392</td>\n      <td>105180</td>\n      <td>10319</td>\n      <td>...</td>\n      <td>29308172.00</td>\n      <td>2017-12-13T04:30:14.000Z</td>\n      <td>105</td>\n      <td>504.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>5.00</td>\n      <td>15.00</td>\n      <td>40.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>7f49688d72b8a9fcf37890e3b9921d7264cc86fb</th>\n      <td>http://www.cnn.com/2017/12/28/politics/trump-g...</td>\n      <td>Trump tweets that 'cold' East Coast 'could use...</td>\n      <td>2017-12-29 01:22:18.203</td>\n      <td>2017-12-29 01:19:39.000</td>\n      <td>55372</td>\n      <td>186.73</td>\n      <td>2017-12-29T02:47:06.680Z</td>\n      <td>21668</td>\n      <td>28990</td>\n      <td>4714</td>\n      <td>...</td>\n      <td>29357992.00</td>\n      <td>2017-12-29T02:30:03.000Z</td>\n      <td>105</td>\n      <td>548.00</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>cd9e7316c9cb90a1bd629a32e85e7c61beaa0ea9</th>\n      <td>http://www.cnn.com/2017/12/08/politics/roy-moo...</td>\n      <td>Roy Moore's incredible 'even though we had sla...</td>\n      <td>2017-12-08 16:07:24.145</td>\n      <td>2017-12-08 16:03:52.000</td>\n      <td>58332</td>\n      <td>799.25</td>\n      <td>2017-12-08T20:05:15.464Z</td>\n      <td>18324</td>\n      <td>32060</td>\n      <td>7948</td>\n      <td>...</td>\n      <td>29282563.00</td>\n      <td>2017-12-08T16:09:38.000Z</td>\n      <td>105</td>\n      <td>697.00</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>0a7a0ee92a87f1b5c0d92ae0bbc22e52607c0f01</th>\n      <td>https://www.huffingtonpost.com/entry/senate-pa...</td>\n      <td>Senate Passes Tax Cuts For The Rich</td>\n      <td>2017-12-02 06:58:11.961</td>\n      <td>2017-12-02 06:52:32.000</td>\n      <td>334487</td>\n      <td>383.56</td>\n      <td>2017-12-02T16:01:08.036Z</td>\n      <td>71795</td>\n      <td>232203</td>\n      <td>30489</td>\n      <td>...</td>\n      <td>9812652.00</td>\n      <td>2017-12-02T06:57:19.000Z</td>\n      <td>215</td>\n      <td>1482.00</td>\n      <td>50.00</td>\n      <td>17.00</td>\n      <td>9.00</td>\n      <td>13.00</td>\n      <td>39.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>f3980d577d96f300046cb4a27181f1e006a003d8</th>\n      <td>http://www.bbc.co.uk/news/world-us-canada-4220...</td>\n      <td>US Senate passes sweeping tax overhaul bill</td>\n      <td>2017-12-02 06:55:08.770</td>\n      <td>2017-12-02 06:51:32.000</td>\n      <td>19240</td>\n      <td>46.62</td>\n      <td>2017-12-02T08:21:05.294Z</td>\n      <td>4377</td>\n      <td>12733</td>\n      <td>2130</td>\n      <td>...</td>\n      <td>45006183.00</td>\n      <td>2017-12-02T08:05:33.000Z</td>\n      <td>96</td>\n      <td>539.00</td>\n      <td>41.00</td>\n      <td>20.00</td>\n      <td>13.00</td>\n      <td>15.00</td>\n      <td>48.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>d220f05a70f23435eab05889ca8d55566c02b0d2</th>\n      <td>http://www.cnn.com/2017/12/03/politics/flynn-f...</td>\n      <td>Trump's lawyer says he was behind @realDonaldT...</td>\n      <td>2017-12-03 17:13:26.205</td>\n      <td>2017-12-03 17:08:43.000</td>\n      <td>46289</td>\n      <td>127.72</td>\n      <td>2017-12-03T18:36:13.543Z</td>\n      <td>21157</td>\n      <td>19761</td>\n      <td>5371</td>\n      <td>...</td>\n      <td>29242216.00</td>\n      <td>2017-12-03T18:00:09.000Z</td>\n      <td>105</td>\n      <td>375.00</td>\n      <td>47.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>64cc07af65787b72659c9d657f3b9b10c73ad3a8</th>\n      <td>http://www.cnn.com/2017/12/04/politics/trump-j...</td>\n      <td>Trump's personal lawyer claims the President c...</td>\n      <td>2017-12-04 15:13:15.175</td>\n      <td>2017-12-04 15:08:42.000</td>\n      <td>39569</td>\n      <td>143.76</td>\n      <td>2017-12-04T16:28:09.312Z</td>\n      <td>15364</td>\n      <td>18413</td>\n      <td>5792</td>\n      <td>...</td>\n      <td>29247000.00</td>\n      <td>2017-12-04T16:16:01.000Z</td>\n      <td>105</td>\n      <td>383.00</td>\n      <td>46.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>709cfecc8cbf26f5fdaae8eca2970004cc3f78c3</th>\n      <td>http://www.cnn.com/2017/12/26/us/erie-pennsylv...</td>\n      <td>With 53 inches, Erie breaks Pennsylvania's two...</td>\n      <td>2017-12-26 16:58:20.633</td>\n      <td>2017-12-26 16:51:20.000</td>\n      <td>38825</td>\n      <td>76.62</td>\n      <td>2017-12-26T19:22:08.868Z</td>\n      <td>7071</td>\n      <td>26834</td>\n      <td>4920</td>\n      <td>...</td>\n      <td>29354093.00</td>\n      <td>2017-12-26T19:00:30.000Z</td>\n      <td>105</td>\n      <td>362.00</td>\n      <td>46.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>df3abea4bb6331dcb57dfe4f7e9b2f8a59fcdb60</th>\n      <td>http://www.cnn.com/2017/12/23/politics/donald-...</td>\n      <td>WH denies Trump said Haitian immigrants 'all h...</td>\n      <td>2017-12-23 19:19:24.386</td>\n      <td>2017-12-23 19:15:10.000</td>\n      <td>41299</td>\n      <td>189.14</td>\n      <td>2017-12-23T20:13:12.024Z</td>\n      <td>21076</td>\n      <td>15543</td>\n      <td>4680</td>\n      <td>...</td>\n      <td>29344064.00</td>\n      <td>2017-12-23T20:00:12.000Z</td>\n      <td>105</td>\n      <td>329.00</td>\n      <td>46.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>05a25081fd942b7a42156ab4d38cd1c53ff754df</th>\n      <td>https://www.huffingtonpost.com/entry/trump-jud...</td>\n      <td>Trump Judicial Nominee Can't Answer Basic Ques...</td>\n      <td>2017-12-15 07:59:09.559</td>\n      <td>2017-12-15 07:47:05.000</td>\n      <td>141324</td>\n      <td>195.94</td>\n      <td>2017-12-15T16:09:11.998Z</td>\n      <td>47819</td>\n      <td>73532</td>\n      <td>19973</td>\n      <td>...</td>\n      <td>9819968.00</td>\n      <td>2017-12-15T12:30:21.000Z</td>\n      <td>215</td>\n      <td>415.00</td>\n      <td>50.00</td>\n      <td>17.00</td>\n      <td>9.00</td>\n      <td>13.00</td>\n      <td>39.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>b8a53fdd9cc4107e4900e166ff97cb7c42988ec9</th>\n      <td>http://www.bbc.co.uk/news/world-us-canada-4219...</td>\n      <td>Flynn charged for 'making false statement'</td>\n      <td>2017-12-01 14:22:06.935</td>\n      <td>2017-12-01 14:18:35.000</td>\n      <td>24302</td>\n      <td>169.26</td>\n      <td>2017-12-01T14:33:12.629Z</td>\n      <td>5169</td>\n      <td>15786</td>\n      <td>3347</td>\n      <td>...</td>\n      <td>44999420.00</td>\n      <td>2017-12-01T14:24:45.000Z</td>\n      <td>96</td>\n      <td>64.00</td>\n      <td>43.00</td>\n      <td>20.00</td>\n      <td>11.00</td>\n      <td>15.00</td>\n      <td>46.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>5a7d8d46133d592cab3c0b75f6156ac752792f64</th>\n      <td>https://www.buzzfeed.com/emmaloop/the-senates-...</td>\n      <td>The Senate\u2019s Russia Investigation Is Now Looki...</td>\n      <td>2017-12-18 21:55:21.465</td>\n      <td>2017-12-18 21:48:41.000</td>\n      <td>51571</td>\n      <td>99.85</td>\n      <td>2017-12-18T22:51:11.460Z</td>\n      <td>19301</td>\n      <td>25483</td>\n      <td>6787</td>\n      <td>...</td>\n      <td>2811436.00</td>\n      <td>2017-12-18T22:07:36.000Z</td>\n      <td>147</td>\n      <td>739.00</td>\n      <td>47.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>072d4c81fd2c28c098ee4dbf783bd91603fd41f4</th>\n      <td>http://www.cnn.com/2017/12/06/politics/preside...</td>\n      <td>Trump set to make historic Jerusalem announcement</td>\n      <td>2017-12-06 17:52:22.847</td>\n      <td>2017-12-06 17:46:10.000</td>\n      <td>79082</td>\n      <td>378.95</td>\n      <td>2017-12-06T18:35:12.151Z</td>\n      <td>29100</td>\n      <td>43531</td>\n      <td>6451</td>\n      <td>...</td>\n      <td>29263371.00</td>\n      <td>2017-12-06T18:18:47.000Z</td>\n      <td>105</td>\n      <td>202.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>4.00</td>\n      <td>15.00</td>\n      <td>39.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>1280bd6134195750988f31f51812f0df5b17a8d6</th>\n      <td>http://www.bbc.co.uk/news/uk-politics-42277040</td>\n      <td>Deal agreed in Brexit talks - Juncker</td>\n      <td>2017-12-08 06:52:06.829</td>\n      <td>2017-12-08 06:49:03.000</td>\n      <td>20639</td>\n      <td>53.36</td>\n      <td>2017-12-08T08:08:08.346Z</td>\n      <td>7353</td>\n      <td>10331</td>\n      <td>2955</td>\n      <td>...</td>\n      <td>45059591.00</td>\n      <td>2017-12-08T06:53:25.000Z</td>\n      <td>96</td>\n      <td>66.00</td>\n      <td>42.00</td>\n      <td>20.00</td>\n      <td>12.00</td>\n      <td>15.00</td>\n      <td>47.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>acf7e0fc60442a0153833d21fd007f8c1fdf29e7</th>\n      <td>https://www.huffingtonpost.com/entry/the-marke...</td>\n      <td>The Marketing Industry's $7.2-Billion Dollar P...</td>\n      <td>2017-12-11 14:19:20.222</td>\n      <td>2017-12-11 14:13:59.085</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-11T17:33:15.998Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>1006.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>48c4d5bb19ce559ab0a9c52f6c8acaf3b42f0c88</th>\n      <td>http://www.bbc.co.uk/sport/football/42376184</td>\n      <td>Albion Rovers v East Fife</td>\n      <td>2017-12-23 16:01:23.302</td>\n      <td>2017-12-23 15:58:48.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-24T16:35:05.847Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>0714370ea5ec336030a82fe9a4358cb385f3bdd5</th>\n      <td>http://www.bbc.co.uk/news/av/stories-42313332/...</td>\n      <td>Meet Me On The Bridge</td>\n      <td>2017-12-11 14:10:11.907</td>\n      <td>2017-12-11 14:07:08.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-11T17:24:13.872Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>eefe920607837a80539c8e5982adcfd80dd0ca09</th>\n      <td>http://www.bbc.co.uk/sport/football/42376186</td>\n      <td>Airdrieonians v Ayr United</td>\n      <td>2017-12-23 16:01:15.338</td>\n      <td>2017-12-23 15:58:37.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-12-23T17:13:15.272Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>c6244d2a5b121292baccf4a1e1a73fc3d766b44c</th>\n      <td>http://www.telegraph.co.uk/travel/destinations...</td>\n      <td>Holualoa Inn</td>\n      <td>2017-12-11 14:01:14.396</td>\n      <td>2017-12-11 13:57:32.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-11T17:16:06.570Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>370</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>cfe1b0664355bdc3abf78f09e22abd92b86ce1b2</th>\n      <td>http://www.bbc.co.uk/sport/football/42376114</td>\n      <td>Dunfermline Athletic v Brechin City</td>\n      <td>2017-12-23 16:01:22.692</td>\n      <td>2017-12-23 15:57:48.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-24T16:35:05.841Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>ea6f934c295029edbfc5d89797912deced2dbee4</th>\n      <td>http://www.bbc.co.uk/sport/football/42376118</td>\n      <td>Dundee United v Livingston</td>\n      <td>2017-12-23 16:01:08.777</td>\n      <td>2017-12-23 15:57:37.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-24T16:34:10.823Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>d7d5cd31f3a1a161d2068ae872575bf4b4646eaf</th>\n      <td>https://www.huffingtonpost.com/entry/how-to-ha...</td>\n      <td>How to Hack Networking</td>\n      <td>2017-12-23 16:04:22.715</td>\n      <td>2017-12-23 15:56:49.939</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-24T16:36:10.390Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>1606.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>c16bce03679e384220eec2e958c262ed90f3247e</th>\n      <td>https://www.huffingtonpost.com/entry/we-photog...</td>\n      <td>We Photographed A Magical Underground World Ca...</td>\n      <td>2017-12-11 14:01:21.698</td>\n      <td>2017-12-11 14:00:31.689</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-11T16:15:09.192Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>127.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>1d3f75dd24e566ce43d85a9eb2fc4dab89f1b16a</th>\n      <td>https://www.independent.co.uk/life-style/insta...</td>\n      <td>23 incredible photos by daredevil Instagrammer...</td>\n      <td>2017-12-11 14:13:23.182</td>\n      <td>2017-12-11 14:00:32.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-11T16:27:11.268Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>386</td>\n      <td>510.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>45fdcd86028597cdd7b36adcef0fac0c1dc01180</th>\n      <td>https://www.huffingtonpost.com/entry/kim-field...</td>\n      <td>Kim Fields Goes Behind the Scenes with 'Blesse...</td>\n      <td>2017-12-11 14:19:32.824</td>\n      <td>2017-12-11 14:02:38.133</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-11T17:33:16.170Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>1327.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>9ad1b443d52bdd29a976b5b6d9be1dba3f1f2809</th>\n      <td>http://www.bbc.co.uk/news/uk-scotland-edinburg...</td>\n      <td>Men charged over knifepoint robbery in Edinburgh</td>\n      <td>2017-12-11 14:10:08.312</td>\n      <td>2017-12-11 14:05:49.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-11T17:24:13.869Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>173.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>0e257747adf85b01a259b2aea687fdbeb3cd46c5</th>\n      <td>http://www.bbc.co.uk/news/uk-northern-ireland-...</td>\n      <td>Drugs and cash stolen from pharmacy in south B...</td>\n      <td>2017-12-23 15:55:06.436</td>\n      <td>2017-12-23 15:52:46.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-24T16:28:13.817Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>101.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>f71064283aec021662857a374c050b510e9b9d70</th>\n      <td>http://www.washingtonpost.com/video/world/pale...</td>\n      <td>Palestinians clash with Israeli security force...</td>\n      <td>2017-12-23 16:01:18.223</td>\n      <td>2017-12-23 15:51:26.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-24T16:35:04.135Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>d2a7afef4a59bb20421a317e6738d2af68407266</th>\n      <td>https://www.washingtonpost.com/national/liquor...</td>\n      <td>Liquor store owner, worker, suspect shot to de...</td>\n      <td>2017-12-23 16:01:20.688</td>\n      <td>2017-12-23 15:51:25.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-24T16:35:05.827Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>134.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>2f943ac17e96bd307577f7ab44400021b891811f</th>\n      <td>http://www.telegraph.co.uk/business/2017/12/11...</td>\n      <td>Founder steps up war of words with Van Elle bo...</td>\n      <td>2017-12-11 14:10:07.514</td>\n      <td>2017-12-11 14:07:19.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-12-11T15:22:14.172Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>370</td>\n      <td>402.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>f4e53fb2256515ae5d8a853f8625e74cddcb3079</th>\n      <td>https://www.huffingtonpost.com/entry/the-year-...</td>\n      <td>The Year I Almost Ruined Christmas for My Son</td>\n      <td>2017-12-11 14:19:27.046</td>\n      <td>2017-12-11 14:13:21.139</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-11T17:33:16.047Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>990.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>08077ace1da9ba7ae34b6dabe65d27bd51bd9711</th>\n      <td>http://www.bbc.co.uk/news/av/stories-42313330/...</td>\n      <td>The school for bullied and traumatised children</td>\n      <td>2017-12-11 14:10:14.944</td>\n      <td>2017-12-11 14:07:28.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-12-11T15:22:14.191Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>681670f0206e9855091aae54978a776aaf2dcfb6</th>\n      <td>https://www.huffingtonpost.com/entry/how-the-v...</td>\n      <td>How The Visual Internet Influences Advertising</td>\n      <td>2017-12-11 14:19:29.017</td>\n      <td>2017-12-11 14:08:05.522</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-12-11T15:31:14.886Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>620.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>e3533a2d1883674641f147866cf247fa36b97bf8</th>\n      <td>https://www.washingtonpost.com/national/man-co...</td>\n      <td>Man convicted of sexually assaulting sleeping ...</td>\n      <td>2017-12-23 15:58:13.359</td>\n      <td>2017-12-23 15:47:16.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-24T16:32:02.911Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>127.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>b8146c1503518b775eff4e15c6583841307e8efa</th>\n      <td>http://www.bbc.co.uk/news/av/stories-42313327/...</td>\n      <td>The teachers who pay cash to keep their pupils...</td>\n      <td>2017-12-11 14:10:14.189</td>\n      <td>2017-12-11 14:08:12.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-11T17:24:13.889Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>1259575fab7f5a1f5ec1895d453e9a5155b7a7ae</th>\n      <td>https://www.huffingtonpost.com/entry/a-christm...</td>\n      <td>A Christmas Story for Grown-Ups</td>\n      <td>2017-12-23 15:49:21.255</td>\n      <td>2017-12-23 15:45:03.913</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-24T16:23:09.715Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>730.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>997cde166f1d60c9586c66f133a77d984a333775</th>\n      <td>https://www.washingtonpost.com/sports/dcunited...</td>\n      <td>Milan paired with Ludogorets in last 32 of Eur...</td>\n      <td>2017-12-11 14:16:11.860</td>\n      <td>2017-12-11 14:10:20.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-11T16:29:13.683Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>149.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>23805de5378971233a9e11fc63e47dbf791525f8</th>\n      <td>https://www.huffingtonpost.com/entry/telcoin-i...</td>\n      <td>Telcoin is the Mobile Cryptocurrency Solution ...</td>\n      <td>2017-12-11 14:19:28.664</td>\n      <td>2017-12-11 14:11:45.542</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-11T17:33:16.136Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>846.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>77a14bd9632990ab6211642cdfd4368965becbbb</th>\n      <td>http://www.bbc.co.uk/sport/cricket/42312025</td>\n      <td>Ashes: Jonny Bairstow says there is 'a lot of ...</td>\n      <td>2017-12-11 14:13:12.688</td>\n      <td>2017-12-11 14:11:55.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-11T16:26:16.039Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>0298beaac81177795390ec51422e1e86bfb56e1f</th>\n      <td>https://www.washingtonpost.com/business/teache...</td>\n      <td>Teacher cuts finger, still wins Food Network c...</td>\n      <td>2017-12-23 15:52:17.903</td>\n      <td>2017-12-23 15:40:14.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-24T16:26:11.381Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>151.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>326e0be2dd3bf2e3198075ceb293048646f3e307</th>\n      <td>http://www.independent.co.uk/news/long_reads/r...</td>\n      <td>How an American road trip helped a family heal...</td>\n      <td>2017-12-19 00:08:07.222</td>\n      <td>2017-12-11 14:12:12.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-19T00:19:13.804Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>386</td>\n      <td>2299.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>939248ed8885691ea2dd8d8b4d647407133655af</th>\n      <td>http://www.telegraph.co.uk/travel/destinations...</td>\n      <td>Beaches Negril Resort &amp; Spa</td>\n      <td>2017-12-11 14:16:08.636</td>\n      <td>2017-12-11 14:12:44.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-11T16:29:13.658Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>370</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>f0cbb47eae03db1557ba467b97dd3ca567f74f34</th>\n      <td>http://www.telegraph.co.uk/travel/destinations...</td>\n      <td>Hotel Belle Epoque</td>\n      <td>2017-12-11 14:16:06.688</td>\n      <td>2017-12-11 14:13:15.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-11T16:29:13.638Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>370</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>9869d24d1829f06aa84b50d93e2ba029f28bd514</th>\n      <td>http://www.bbc.co.uk/newsround/38878494</td>\n      <td>Tennis player accidentally hits umpire in eye ...</td>\n      <td>2018-01-01 00:04:19.034</td>\n      <td>2017-12-31 23:59:59.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-01-01T00:15:14.296Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>139145 rows \u00d7 26 columns</p>\n</div>\n\n\n\n\n```python\ndata[\"score_diff\"] = data.promotion_score - data.response_score\n```\n\n\n```python\n# promoted but low response\ndata.sort_values(\"score_diff\", ascending=False).head(25)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n      <th>score_diff</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>60dde39afccfcabaf8cf2a8ed28a3d507020545b</th>\n      <td>https://www.buzzfeed.com/kateaurthur/2018-tv-a...</td>\n      <td>Everything You Need To Know About TV And Movie...</td>\n      <td>2017-12-30 17:04:21.638</td>\n      <td>2017-12-21 22:23:16</td>\n      <td>1</td>\n      <td>0.09</td>\n      <td>2017-12-30T17:16:03.579Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>2017-12-30T20:22:25.000Z</td>\n      <td>147</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>45.00</td>\n      <td>45.00</td>\n    </tr>\n    <tr>\n      <th>2f11fdaca32431287b0f6fba6e02e024cbbec99d</th>\n      <td>https://www.buzzfeed.com/jtes/for-women-lookin...</td>\n      <td>For Women Looking For Jobs After Prison, It Do...</td>\n      <td>2017-12-07 13:01:23.490</td>\n      <td>2017-12-05 19:01:09</td>\n      <td>1</td>\n      <td>0.09</td>\n      <td>2017-12-07T13:13:14.909Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>2017-12-10T02:00:00.000Z</td>\n      <td>147</td>\n      <td>3739.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>44.00</td>\n      <td>44.00</td>\n    </tr>\n    <tr>\n      <th>8705fb3da20761c6674f087884089ba3068e63fa</th>\n      <td>https://www.buzzfeed.com/nidhisubbaraman/nativ...</td>\n      <td>Native Americans Were Anxious About Trump Head...</td>\n      <td>2017-12-27 16:04:15.611</td>\n      <td>2017-12-20 17:50:41</td>\n      <td>4</td>\n      <td>0.39</td>\n      <td>2017-12-27T16:15:16.931Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>4</td>\n      <td>...</td>\n      <td>2017-12-27T16:19:01.000Z</td>\n      <td>147</td>\n      <td>1380.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>46.00</td>\n      <td>44.00</td>\n    </tr>\n    <tr>\n      <th>32034e45b629a27a33e035a77757e67a27c59d71</th>\n      <td>https://www.buzzfeed.com/stephaniemlee/here-ar...</td>\n      <td>Here Are 13 Tech Startups And Products That Fl...</td>\n      <td>2017-12-27 18:13:24.230</td>\n      <td>2017-12-21 23:52:53</td>\n      <td>4</td>\n      <td>0.36</td>\n      <td>2017-12-27T18:25:11.821Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>4</td>\n      <td>...</td>\n      <td>2017-12-28T02:12:57.000Z</td>\n      <td>147</td>\n      <td>1260.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>46.00</td>\n      <td>44.00</td>\n    </tr>\n    <tr>\n      <th>eb5b52c981dd04408660f23967ba814262156a5f</th>\n      <td>https://www.buzzfeed.com/charliewarzel/youtube...</td>\n      <td>YouTubers Made Hundreds Of Thousands Off Of Bi...</td>\n      <td>2017-12-11 15:46:21.876</td>\n      <td>2017-12-08 22:35:56</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-11T15:57:19.321Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2017-12-11T16:05:29.000Z</td>\n      <td>147</td>\n      <td>1916.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>44.00</td>\n      <td>44.00</td>\n    </tr>\n    <tr>\n      <th>24f5ef2ea5bb64cc3a2def2b55092a2ce5751de8</th>\n      <td>https://www.buzzfeed.com/rosalindadams/how-a-g...</td>\n      <td>How a Giant Psychiatric Hospital Company Tried...</td>\n      <td>2017-12-27 16:40:28.231</td>\n      <td>2017-12-22 23:17:31</td>\n      <td>6</td>\n      <td>0.46</td>\n      <td>2017-12-27T16:52:08.743Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>6</td>\n      <td>...</td>\n      <td>2017-12-27T17:13:02.000Z</td>\n      <td>147</td>\n      <td>1831.00</td>\n      <td>2.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>47.00</td>\n      <td>43.00</td>\n    </tr>\n    <tr>\n      <th>a2c6e7241dd8ffcfad898e5d44f9b00873f4f637</th>\n      <td>https://www.buzzfeed.com/monicamark/niger-secr...</td>\n      <td>Inside The Botched Raid That Left Four US Sold...</td>\n      <td>2017-12-09 15:58:19.223</td>\n      <td>2017-12-07 15:22:08</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-09T16:10:11.079Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2017-12-11T18:03:00.000Z</td>\n      <td>147</td>\n      <td>3392.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>43.00</td>\n      <td>43.00</td>\n    </tr>\n    <tr>\n      <th>851d61f0cda588c4405a4dd959b187bcca3edf3c</th>\n      <td>https://www.buzzfeed.com/melissasegura/how-to-...</td>\n      <td>How To Close Two Stubborn Murder Cases In One ...</td>\n      <td>2017-12-28 20:46:16.651</td>\n      <td>2017-12-22 22:51:14</td>\n      <td>2</td>\n      <td>0.18</td>\n      <td>2017-12-28T20:58:09.837Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>...</td>\n      <td>2017-12-28T21:22:08.000Z</td>\n      <td>147</td>\n      <td>4647.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>45.00</td>\n      <td>43.00</td>\n    </tr>\n    <tr>\n      <th>aecd5ea40f84a071b2b98deb901d374a1af82bea</th>\n      <td>https://www.buzzfeed.com/davidmack/heres-how-t...</td>\n      <td>Here's How To Find Out How The Republican Tax ...</td>\n      <td>2017-12-19 21:19:19.316</td>\n      <td>2017-12-16 15:28:34</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-19T21:31:07.547Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2017-12-19T23:44:50.000Z</td>\n      <td>147</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>43.00</td>\n      <td>43.00</td>\n    </tr>\n    <tr>\n      <th>f9b56421c207cc659ad9d2b9f02e41a3e2235852</th>\n      <td>https://www.buzzfeed.com/tasneemnashrulla/cali...</td>\n      <td>Powerful Winds Are Pushing The Destructive Cal...</td>\n      <td>2017-12-07 17:34:17.052</td>\n      <td>2017-12-06 18:44:10</td>\n      <td>5</td>\n      <td>0.07</td>\n      <td>2017-12-07T18:46:14.159Z</td>\n      <td>0</td>\n      <td>1</td>\n      <td>4</td>\n      <td>...</td>\n      <td>2017-12-07T19:33:00.000Z</td>\n      <td>147</td>\n      <td>15.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>44.00</td>\n      <td>42.00</td>\n    </tr>\n    <tr>\n      <th>6b7ae56b46b3c625f1be5c21c435edb5d44e6716</th>\n      <td>https://www.buzzfeed.com/zahrahirji/us-climate...</td>\n      <td>11 Ways The US Is No Longer Fighting Climate C...</td>\n      <td>2017-12-29 17:24:22.641</td>\n      <td>2017-12-19 15:13:10</td>\n      <td>20</td>\n      <td>0.00</td>\n      <td>2017-12-29T17:36:12.253Z</td>\n      <td>0</td>\n      <td>5</td>\n      <td>15</td>\n      <td>...</td>\n      <td>2017-12-31T02:22:00.000Z</td>\n      <td>147</td>\n      <td>1161.00</td>\n      <td>4.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>49.00</td>\n      <td>41.00</td>\n    </tr>\n    <tr>\n      <th>9fa212fb91158bb2e772b47de5619f7910b7f704</th>\n      <td>https://www.buzzfeed.com/patricksmith/how-the-...</td>\n      <td>How The Brother Of A Victim Of The Manchester ...</td>\n      <td>2017-12-24 07:01:19.403</td>\n      <td>2017-12-22 13:10:34</td>\n      <td>2</td>\n      <td>0.18</td>\n      <td>2017-12-24T07:13:08.102Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>...</td>\n      <td>2017-12-25T02:22:00.000Z</td>\n      <td>147</td>\n      <td>2347.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>43.00</td>\n      <td>41.00</td>\n    </tr>\n    <tr>\n      <th>54a867bda1060aefd4e1de41690360d03f7d738e</th>\n      <td>https://www.buzzfeed.com/monicamark/a-pastor-f...</td>\n      <td>A Pastor Found A Massive Diamond. Now He Hopes...</td>\n      <td>2017-12-16 16:16:20.407</td>\n      <td>2017-12-13 19:01:57</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-16T16:28:08.626Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2017-12-16T19:54:00.000Z</td>\n      <td>147</td>\n      <td>1880.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>11.00</td>\n      <td>11.00</td>\n      <td>41.00</td>\n      <td>41.00</td>\n      <td>41.00</td>\n    </tr>\n    <tr>\n      <th>f26fbab786c63264349418944f20666059288a7d</th>\n      <td>https://www.buzzfeed.com/marisacarroll/stories...</td>\n      <td>15 Stories About Justice That Outraged Us In 2017</td>\n      <td>2017-12-21 19:43:21.195</td>\n      <td>2017-12-21 19:12:01</td>\n      <td>7</td>\n      <td>0.05</td>\n      <td>2017-12-22T16:15:06.173Z</td>\n      <td>3</td>\n      <td>0</td>\n      <td>4</td>\n      <td>...</td>\n      <td>2017-12-26T13:33:16.000Z</td>\n      <td>147</td>\n      <td>nan</td>\n      <td>2.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>45.00</td>\n      <td>41.00</td>\n    </tr>\n    <tr>\n      <th>11446451655a07177c9ba67543d908b7b9934c2e</th>\n      <td>https://www.buzzfeed.com/katenocera/rep-ruben-...</td>\n      <td>Nevada Democrat Ruben Kihuen Won't Seek Reelec...</td>\n      <td>2017-12-16 21:31:22.428</td>\n      <td>2017-12-05 18:48:53</td>\n      <td>2</td>\n      <td>0.18</td>\n      <td>2017-12-16T21:43:05.715Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>...</td>\n      <td>2017-12-16T21:46:46.000Z</td>\n      <td>147</td>\n      <td>700.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>43.00</td>\n      <td>41.00</td>\n    </tr>\n    <tr>\n      <th>13045f42cde8a48bbcadd8e7ce042e4ca090e7f3</th>\n      <td>https://www.buzzfeed.com/keelyflaherty/xx-rand...</td>\n      <td>15 Random, Weirdly Fascinating Facts About Our...</td>\n      <td>2017-12-11 13:14:16.245</td>\n      <td>2017-12-06 18:55:29</td>\n      <td>1</td>\n      <td>0.00</td>\n      <td>2017-12-11T13:25:16.547Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>2017-12-17T03:35:01.000Z</td>\n      <td>147</td>\n      <td>345.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>10.00</td>\n      <td>11.00</td>\n      <td>40.00</td>\n      <td>40.00</td>\n      <td>40.00</td>\n    </tr>\n    <tr>\n      <th>d83709ffbc6b9cf3ae4462dbb57f06c4f4f1400b</th>\n      <td>https://www.buzzfeed.com/sallytamarkin/weight-...</td>\n      <td>13 Experts On Why They No Longer Recommend Diets</td>\n      <td>2018-01-01 18:49:23.289</td>\n      <td>2017-12-01 20:43:38</td>\n      <td>6</td>\n      <td>0.55</td>\n      <td>2018-01-01T19:01:06.672Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>6</td>\n      <td>...</td>\n      <td>2018-01-02T06:51:25.000Z</td>\n      <td>147</td>\n      <td>3123.00</td>\n      <td>2.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>44.00</td>\n      <td>40.00</td>\n    </tr>\n    <tr>\n      <th>e9b5702b01be019dc5f0e67703b78663974a9d06</th>\n      <td>https://www.buzzfeed.com/adolfoflores/trump-ha...</td>\n      <td>Trump Has Tied \"Chain Migration\" To Terrorism....</td>\n      <td>2017-12-31 20:40:20.698</td>\n      <td>2017-12-29 20:02:50</td>\n      <td>1</td>\n      <td>0.09</td>\n      <td>2017-12-31T20:52:07.486Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>2018-01-01T01:34:32.000Z</td>\n      <td>147</td>\n      <td>1903.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>10.00</td>\n      <td>11.00</td>\n      <td>40.00</td>\n      <td>40.00</td>\n      <td>40.00</td>\n    </tr>\n    <tr>\n      <th>3c7cfda35f965505ba968c777ab7a31f162f608a</th>\n      <td>https://www.buzzfeed.com/laurageiser/these-pho...</td>\n      <td>These Photos Of Santas-In-Training Will Lift Y...</td>\n      <td>2017-12-20 01:31:25.031</td>\n      <td>2017-12-06 00:02:59</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-12-20T01:43:11.216Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2017-12-20T15:56:46.000Z</td>\n      <td>147</td>\n      <td>129.00</td>\n      <td>0.00</td>\n      <td>18.00</td>\n      <td>10.00</td>\n      <td>11.00</td>\n      <td>39.00</td>\n      <td>39.00</td>\n      <td>39.00</td>\n    </tr>\n    <tr>\n      <th>513ef968cfbcdb1c6c8c1fc39d1d1e6af032ecee</th>\n      <td>https://www.buzzfeed.com/danvergano/epa-media-...</td>\n      <td>2017 Was The Year The EPA Declared War On The ...</td>\n      <td>2017-12-23 15:09:13.991</td>\n      <td>2017-12-22 20:17:48</td>\n      <td>18</td>\n      <td>0.15</td>\n      <td>2017-12-23T19:24:12.663Z</td>\n      <td>0</td>\n      <td>6</td>\n      <td>12</td>\n      <td>...</td>\n      <td>2017-12-23T22:01:54.000Z</td>\n      <td>147</td>\n      <td>952.00</td>\n      <td>4.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>47.00</td>\n      <td>39.00</td>\n    </tr>\n    <tr>\n      <th>e529e130efcd7e0c4687e94ae8d14bc898ceec0e</th>\n      <td>https://www.buzzfeed.com/alannabennett/ways-ho...</td>\n      <td>6 Ways Hollywood Can Do Better In 2018</td>\n      <td>2017-12-30 01:29:11.817</td>\n      <td>2017-12-29 22:02:12</td>\n      <td>40</td>\n      <td>0.21</td>\n      <td>2017-12-30T19:58:09.135Z</td>\n      <td>2</td>\n      <td>26</td>\n      <td>12</td>\n      <td>...</td>\n      <td>2017-12-30T18:22:00.000Z</td>\n      <td>147</td>\n      <td>nan</td>\n      <td>6.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>51.00</td>\n      <td>39.00</td>\n    </tr>\n    <tr>\n      <th>d9fa9656eb388266ef0ef42314a1af0747c2d729</th>\n      <td>https://www.buzzfeed.com/doree/silicon-valley-...</td>\n      <td>Silicon Valley Punished Some Badly Behaved Men...</td>\n      <td>2017-12-22 20:10:15.285</td>\n      <td>2017-12-22 20:08:31</td>\n      <td>26</td>\n      <td>1.18</td>\n      <td>2017-12-22T20:21:14.378Z</td>\n      <td>0</td>\n      <td>3</td>\n      <td>23</td>\n      <td>...</td>\n      <td>2017-12-25T23:33:40.000Z</td>\n      <td>147</td>\n      <td>1180.00</td>\n      <td>5.00</td>\n      <td>18.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>49.00</td>\n      <td>39.00</td>\n    </tr>\n    <tr>\n      <th>0e5bb71c21836af42e79cf180822df178ca05faa</th>\n      <td>https://www.buzzfeed.com/annehelenpetersen/mom...</td>\n      <td>Moms Are Main Characters, Too</td>\n      <td>2017-12-10 16:39:12.901</td>\n      <td>2017-12-08 21:21:30</td>\n      <td>24</td>\n      <td>0.30</td>\n      <td>2017-12-10T16:50:13.895Z</td>\n      <td>2</td>\n      <td>15</td>\n      <td>7</td>\n      <td>...</td>\n      <td>2017-12-10T23:30:00.000Z</td>\n      <td>147</td>\n      <td>1843.00</td>\n      <td>4.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>46.00</td>\n      <td>38.00</td>\n    </tr>\n    <tr>\n      <th>515685a5a5560ea7980d63c011a2fe814c5af832</th>\n      <td>https://www.buzzfeed.com/matthewzeitlin/one-cr...</td>\n      <td>One Crucial Thing Republicans Agreed On In The...</td>\n      <td>2017-12-07 22:04:22.607</td>\n      <td>2017-12-07 21:56:31</td>\n      <td>31</td>\n      <td>0.28</td>\n      <td>2017-12-07T23:16:09.641Z</td>\n      <td>4</td>\n      <td>19</td>\n      <td>8</td>\n      <td>...</td>\n      <td>2017-12-07T22:25:00.000Z</td>\n      <td>147</td>\n      <td>643.00</td>\n      <td>5.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>48.00</td>\n      <td>38.00</td>\n    </tr>\n    <tr>\n      <th>deddc425e9e2a6c7ccd8c7f9898210d63b2e1802</th>\n      <td>https://www.buzzfeed.com/sarahmarshall/20-year...</td>\n      <td>The Insane True Story Of How \"Titanic\" Got Made</td>\n      <td>2017-12-17 16:39:14.602</td>\n      <td>2017-12-15 22:50:55</td>\n      <td>31</td>\n      <td>0.40</td>\n      <td>2017-12-17T16:50:11.752Z</td>\n      <td>2</td>\n      <td>9</td>\n      <td>20</td>\n      <td>...</td>\n      <td>2017-12-18T01:04:50.000Z</td>\n      <td>147</td>\n      <td>8636.00</td>\n      <td>5.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>47.00</td>\n      <td>37.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>25 rows \u00d7 27 columns</p>\n</div>\n\n\n\n\n```python\n# high response but not promoted\ndata.sort_values(\"score_diff\", ascending=True).head(25)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n      <th>score_diff</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>6db0269552b047b879c328010314c66ddcaec6da</th>\n      <td>https://www.nytimes.com/2017/12/13/opinion/sal...</td>\n      <td>Salma Hayek: Harvey Weinstein Is My Monster Too</td>\n      <td>2017-12-13 23:49:10.353</td>\n      <td>2017-12-13 23:45:20.000</td>\n      <td>824459</td>\n      <td>5490.26</td>\n      <td>2017-12-14T03:03:13.004Z</td>\n      <td>101937</td>\n      <td>599446</td>\n      <td>123076</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>120</td>\n      <td>2800.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>81c5b9be259fc28bcdef151800f9460767cf7690</th>\n      <td>https://www.washingtonpost.com/news/politics/w...</td>\n      <td>In an upset, Democrat Doug Jones is projected ...</td>\n      <td>2017-12-13 03:29:13.065</td>\n      <td>2017-12-13 03:26:00.000</td>\n      <td>139737</td>\n      <td>1302.34</td>\n      <td>2017-12-13T03:40:17.040Z</td>\n      <td>19636</td>\n      <td>111733</td>\n      <td>8368</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>102.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>1cd3a4c15d1b80136d4cf9bc6ef4a8e1ec03a3ad</th>\n      <td>http://yournewswire.com/nestle-ceo-water-is-no...</td>\n      <td>Nestle CEO: Water Is Not A Human Right, Should...</td>\n      <td>2017-12-14 17:44:25.584</td>\n      <td>2017-12-14 16:30:44.000</td>\n      <td>111833</td>\n      <td>1.74</td>\n      <td>2017-12-14T20:59:13.680Z</td>\n      <td>42856</td>\n      <td>44725</td>\n      <td>24252</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>22568</td>\n      <td>135.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>d18643b71da717ca3fbe0357ecf425b197853b16</th>\n      <td>https://www.washingtonpost.com/news/capital-we...</td>\n      <td>Alaska just reported one of the most extreme s...</td>\n      <td>2017-12-07 17:04:33.494</td>\n      <td>2017-12-07 16:57:03.000</td>\n      <td>117687</td>\n      <td>533.02</td>\n      <td>2017-12-08T18:06:11.882Z</td>\n      <td>19815</td>\n      <td>83900</td>\n      <td>13972</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>580.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>87f55392a64a0600bbbb60e7a61e641dd51e75cc</th>\n      <td>http://www.foxnews.com/sports/2017/12/09/linds...</td>\n      <td>Lindsey Vonn suffers back injury in World Cup ...</td>\n      <td>2017-12-10 01:29:22.598</td>\n      <td>2017-12-10 01:28:54.000</td>\n      <td>77394</td>\n      <td>45.61</td>\n      <td>2017-12-15T08:13:17.970Z</td>\n      <td>31471</td>\n      <td>41903</td>\n      <td>4020</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>650.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>74a8e4a79e8e0d97e2e803ecdb912533007bfe21</th>\n      <td>http://www.telegraph.co.uk/art/artists/lubiana...</td>\n      <td>Lubiana Himid's 2017 Turner Prize victory is a...</td>\n      <td>2017-12-05 19:34:16.136</td>\n      <td>2017-12-05 19:30:17.000</td>\n      <td>127045</td>\n      <td>2073.74</td>\n      <td>2017-12-05T22:48:10.208Z</td>\n      <td>11691</td>\n      <td>25685</td>\n      <td>89669</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>370</td>\n      <td>540.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>8c012e0ed5e7d1facf7e68848ae595de4be07f2d</th>\n      <td>https://www.theguardian.com/business/2017/dec/...</td>\n      <td>UK banks join multinationals in pledge to come...</td>\n      <td>2017-12-12 11:55:44.686</td>\n      <td>2017-12-12 11:53:19.000</td>\n      <td>79893</td>\n      <td>76.13</td>\n      <td>2017-12-15T10:22:10.889Z</td>\n      <td>3370</td>\n      <td>68212</td>\n      <td>8311</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>142</td>\n      <td>386.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>8804453dcfb7fc6bb6185ef0037846ad46b4290a</th>\n      <td>https://www.buzzfeed.com/michaelblackmon/profe...</td>\n      <td>People Are Thirsting Pretty Hard For James McA...</td>\n      <td>2017-12-05 20:34:16.372</td>\n      <td>2017-12-05 20:06:02.000</td>\n      <td>135627</td>\n      <td>263.18</td>\n      <td>2017-12-06T01:32:03.730Z</td>\n      <td>31320</td>\n      <td>100289</td>\n      <td>4018</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>nan</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>52.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>1cd4d1d98c6f91e32bb2dcaba710f524bc8d8a1d</th>\n      <td>http://www.foxnews.com/entertainment/2017/12/0...</td>\n      <td>Media elite laughed at 2008 roast sending Matt...</td>\n      <td>2017-12-05 20:54:22.240</td>\n      <td>2017-12-05 20:44:23.000</td>\n      <td>75257</td>\n      <td>71.06</td>\n      <td>2017-12-09T05:31:06.998Z</td>\n      <td>14766</td>\n      <td>50287</td>\n      <td>10204</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>1157.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>52.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>c2298f24d323275ee6ff00f56b1c8caabb457aeb</th>\n      <td>https://www.theguardian.com/books/2017/dec/24/...</td>\n      <td>'The difficulty is the point': teaching spoon-...</td>\n      <td>2017-12-23 22:40:10.841</td>\n      <td>2017-12-23 22:37:54.000</td>\n      <td>59004</td>\n      <td>14.06</td>\n      <td>2017-12-24T22:01:04.177Z</td>\n      <td>11099</td>\n      <td>38299</td>\n      <td>9606</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>142</td>\n      <td>3097.00</td>\n      <td>48.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>48.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>4dcf50426af48e5e999bf526b55176a714074ef1</th>\n      <td>https://www.washingtonpost.com/news/politics/w...</td>\n      <td>Ex-Trump national security adviser Michael Fly...</td>\n      <td>2017-12-01 14:34:13.986</td>\n      <td>2017-12-01 14:29:00.000</td>\n      <td>72220</td>\n      <td>468.95</td>\n      <td>2017-12-01T18:24:12.055Z</td>\n      <td>20328</td>\n      <td>41964</td>\n      <td>9928</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>69.00</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>50.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>b9e27ec3d3786ed575f5491b9b1756552d00cbfe</th>\n      <td>http://money.cnn.com/2017/12/04/media/pbs-char...</td>\n      <td>PBS announces 'Amanpour' as interim replacemen...</td>\n      <td>2017-12-04 22:19:15.603</td>\n      <td>2017-12-04 21:55:23.000</td>\n      <td>58791</td>\n      <td>102.26</td>\n      <td>2017-12-05T01:45:12.208Z</td>\n      <td>6515</td>\n      <td>48812</td>\n      <td>3464</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>105</td>\n      <td>nan</td>\n      <td>48.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>49.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>c17364bddb1b1e1881d26321215078fcf9376136</th>\n      <td>https://www.washingtonpost.com/national/health...</td>\n      <td>Uranium firm urged Trump officials to shrink B...</td>\n      <td>2017-12-09 00:43:21.734</td>\n      <td>2017-12-09 00:28:33.000</td>\n      <td>85616</td>\n      <td>72.66</td>\n      <td>2017-12-10T03:36:10.952Z</td>\n      <td>11415</td>\n      <td>56897</td>\n      <td>17304</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>1050.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>53.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>fcdf75b812ac05992fcf139ed1fa9fbe26d2d313</th>\n      <td>http://www.mirror.co.uk/news/world-news/one-eu...</td>\n      <td>One of Europe's brightest Christmas trees ligh...</td>\n      <td>2017-12-02 00:01:28.689</td>\n      <td>2017-12-01 23:58:50.000</td>\n      <td>57934</td>\n      <td>50.43</td>\n      <td>2017-12-02T10:25:11.817Z</td>\n      <td>2392</td>\n      <td>48859</td>\n      <td>6683</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>706</td>\n      <td>213.00</td>\n      <td>48.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>49.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>e67159816fb58bef23f7ec7a956bab62abcdb70d</th>\n      <td>http://www.foxnews.com/entertainment/2017/12/0...</td>\n      <td>ABC News suspends Brian Ross over 'serious err...</td>\n      <td>2017-12-02 23:09:17.105</td>\n      <td>2017-12-02 22:50:59.000</td>\n      <td>64863</td>\n      <td>273.60</td>\n      <td>2017-12-03T00:13:21.277Z</td>\n      <td>17007</td>\n      <td>38340</td>\n      <td>9516</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>210.00</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>51.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>81dbab2e69af8a1dece821f1e7437c621967814f</th>\n      <td>http://www.cnn.com/2017/12/14/us/sandy-hook-ne...</td>\n      <td>Sandy Hook shooting victims remembered</td>\n      <td>2017-12-14 10:34:21.685</td>\n      <td>2017-12-14 10:28:31.000</td>\n      <td>158920</td>\n      <td>247.38</td>\n      <td>2017-12-14T23:46:14.233Z</td>\n      <td>17348</td>\n      <td>122515</td>\n      <td>19057</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>105</td>\n      <td>3714.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n      <td>54.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>ef8588c058d4bce262f04a4cf3f58b507662626d</th>\n      <td>https://www.washingtonpost.com/news/wonk/wp/20...</td>\n      <td>GOP eyes post-tax-cut changes to welfare, Medi...</td>\n      <td>2017-12-01 17:52:16.868</td>\n      <td>2017-12-01 17:39:19.000</td>\n      <td>206995</td>\n      <td>197.00</td>\n      <td>2017-12-01T22:58:05.475Z</td>\n      <td>48607</td>\n      <td>126093</td>\n      <td>32295</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>686.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n      <td>54.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>eb6b9898f665d8019751a2270ab567a6a0dc09d0</th>\n      <td>https://www.theguardian.com/music/2017/dec/10/...</td>\n      <td>Fiona Maddocks\u2019s best classical music of 2017</td>\n      <td>2017-12-10 08:04:34.787</td>\n      <td>2017-12-10 08:00:31.000</td>\n      <td>39600</td>\n      <td>7.49</td>\n      <td>2017-12-11T00:31:13.938Z</td>\n      <td>159</td>\n      <td>39308</td>\n      <td>133</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>142</td>\n      <td>nan</td>\n      <td>46.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>46.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>24104ea0009010519c5307f562acaa533ce66cf0</th>\n      <td>http://www.telegraph.co.uk/travel/inspiring-to...</td>\n      <td>Be wowed in the north of India by wonderful wi...</td>\n      <td>2017-12-29 12:07:05.118</td>\n      <td>2017-12-29 10:30:00.000</td>\n      <td>38901</td>\n      <td>0.03</td>\n      <td>2017-12-29T16:22:12.948Z</td>\n      <td>7482</td>\n      <td>27387</td>\n      <td>4032</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>370</td>\n      <td>595.00</td>\n      <td>46.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>46.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>68c2b2ad7566bf375e6a6e1f3b3fbea39083d42b</th>\n      <td>https://www.washingtonpost.com/news/wonk/wp/20...</td>\n      <td>The richest 1 percent now owns more of the cou...</td>\n      <td>2017-12-06 15:25:17.266</td>\n      <td>2017-12-06 15:16:10.000</td>\n      <td>44858</td>\n      <td>51.37</td>\n      <td>2017-12-06T16:37:07.585Z</td>\n      <td>8579</td>\n      <td>29245</td>\n      <td>7034</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>1029.00</td>\n      <td>46.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>47.00</td>\n      <td>-45.00</td>\n    </tr>\n    <tr>\n      <th>496fcccdb268532134f1625b26aca823b89bb936</th>\n      <td>https://www.nytimes.com/2017/12/05/us/climate-...</td>\n      <td>4 Takeaways From a Gathering of Mayors on Clim...</td>\n      <td>2017-12-06 00:22:12.248</td>\n      <td>2017-12-06 00:18:44.000</td>\n      <td>33564</td>\n      <td>55.53</td>\n      <td>2017-12-06T23:05:08.990Z</td>\n      <td>376</td>\n      <td>32637</td>\n      <td>551</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>120</td>\n      <td>767.00</td>\n      <td>45.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>45.00</td>\n      <td>-45.00</td>\n    </tr>\n    <tr>\n      <th>e26fb062a26f15584865b2509a27138d7e4e9ed8</th>\n      <td>https://www.theguardian.com/world/2017/dec/15/...</td>\n      <td>Extreme poverty in America: read the UN specia...</td>\n      <td>2017-12-15 17:05:40.703</td>\n      <td>2017-12-15 17:00:38.000</td>\n      <td>33833</td>\n      <td>7.63</td>\n      <td>2017-12-16T17:39:02.478Z</td>\n      <td>5307</td>\n      <td>19585</td>\n      <td>8941</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>142</td>\n      <td>692.00</td>\n      <td>45.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>45.00</td>\n      <td>-45.00</td>\n    </tr>\n    <tr>\n      <th>b1d48f4a374627c1047af6ff8044e6202509e0b4</th>\n      <td>https://www.huffingtonpost.com/entry/the-gop-t...</td>\n      <td>The GOP Tax Plan is A Major Assault in Their W...</td>\n      <td>2017-12-02 16:46:13.616</td>\n      <td>2017-12-02 16:32:34.160</td>\n      <td>36793</td>\n      <td>42.84</td>\n      <td>2017-12-02T16:57:08.929Z</td>\n      <td>7323</td>\n      <td>25056</td>\n      <td>4414</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>1044.00</td>\n      <td>45.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>45.00</td>\n      <td>-45.00</td>\n    </tr>\n    <tr>\n      <th>5f3c3c9b3fe935c782751681584d574adf487220</th>\n      <td>https://www.theguardian.com/us-news/2017/dec/2...</td>\n      <td>'We're under attack': young conservatives gath...</td>\n      <td>2017-12-23 12:04:14.888</td>\n      <td>2017-12-23 12:00:21.000</td>\n      <td>48012</td>\n      <td>123.49</td>\n      <td>2017-12-23T20:35:06.298Z</td>\n      <td>11240</td>\n      <td>35271</td>\n      <td>1501</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>142</td>\n      <td>1155.00</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>49.00</td>\n      <td>-45.00</td>\n    </tr>\n    <tr>\n      <th>79b5cf5842c27212d4d8f95d693eb3b7aa22c01c</th>\n      <td>http://yournewswire.com/denzil-washington-obam...</td>\n      <td>Denzil Washington: \u2018Criminal-In-Chief\u2019 Obama \u2018...</td>\n      <td>2017-12-01 17:24:41.981</td>\n      <td>2017-12-01 16:54:17.000</td>\n      <td>73830</td>\n      <td>34.34</td>\n      <td>2017-12-02T20:09:19.285Z</td>\n      <td>15179</td>\n      <td>45429</td>\n      <td>13222</td>\n      <td>...</td>\n      <td>2017-12-02T15:40:00.000Z</td>\n      <td>22568</td>\n      <td>382.00</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>4.00</td>\n      <td>5.00</td>\n      <td>54.00</td>\n      <td>-44.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>25 rows \u00d7 27 columns</p>\n</div>\n\n\n\nWrite that data to a file. Note that the scores here are provisional for two reasons:\n1. they should be using a rolling-month based on the article publication date to calculate medians/min/max etc, whereas in this workbook we as just using values for the month of May\n2. for analysis, we've rounded the numbers; we don't expect to do that for the actual scores\n\n\n```python\ndata.to_csv(\"articles_with_provisional_scores_2017-10-01_2017-10-31.csv\")\n```\n\n# Summary\n\nThe attention index of an article is comprised of four components:\n\n- *lead score* (max 20 points) based on how long an article was the lead story on the publisher's home page, scaled by the traffic to that publisher\n- *front score* (max 15 points) based on how long an article was present on the publisher's home page, scaled by traffic to that publisher\n- *Facebook promotion score* (max 15 points) based on whether the article was promoted to the publisher's Facebook brand page, scaled by the reach of that brand page\n- *response score* (max 50 points) based on the number of Facebook engagements the article received, relative to other articles\n\nOr, in other words:\n\n\\begin{align}\nattentionIndex_a &= leadScore_a + frontScore_a + facebookPromotionScore_a + responseScore_a \\\\\nleadScore_a &= 20 \\cdot \\left(\\frac{\\min(minsAsLead_a, 60)}{alexaRank_a}\\right) \\cdot \\left( \\frac{\\min(alexaRank)}{60} \\right) \\\\\nfrontScore_a &= \n15 \\cdot\n\\left(\\frac{\\min(minsOnFront_a, 1440)}{alexaRank_a \\cdot numArticlesOnFront_a}\\right) \\cdot\n\\left( \\frac{\\min(alexaRank \\cdot numArticlesOnFront)}{1440} \\right) \\\\\nfacebookPromotion_a &= \n\\begin{cases}\n 0 \\text{ if not shared on brand page }\\\\\n   15 \\cdot \\frac{\\log(brandPageLikes_a) - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))}  \\text{ otherwise }\n\\end{cases}   \n\\\\\nresponseScore_a &= \n\\begin{cases} \n   0 \\text{ if } engagements_a = 0 \\\\\n   50 \\cdot \n   \\frac{\\log(\\min(engagements_a,limit) + median(engagements)) - \\log(1 + median(engagements))}\n   {\\log(limit + median(engagements)) - \\log(1 + median(engagements))} \\text{ if } engagements_a > 0\n\\end{cases} \\\\\n\\end{align} \n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "6be2f71a0dddb7d3b5fd37859e2699ba1f8c8de4", "size": 735001, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "data/attention-index-december.ipynb", "max_stars_repo_name": "kaleida/attention-index", "max_stars_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2017-06-03T11:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T10:02:06.000Z", "max_issues_repo_path": "data/attention-index-december.ipynb", "max_issues_repo_name": "kaleida/attention-index", "max_issues_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data/attention-index-december.ipynb", "max_forks_repo_name": "kaleida/attention-index", "max_forks_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 83.9809186472, "max_line_length": 46194, "alphanum_fraction": 0.6890643686, "converted": true, "num_tokens": 57264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2845760042165267, "lm_q2_score": 0.050330629748526326, "lm_q1q2_score": 0.014322889503537072}}
{"text": "This notebook is a work through for the implementation of a basic BM25 algorithm.\n\n\n```python\nimport os\nimport nltk\nnltk.download('popular');\nfrom nltk.corpus import stopwords\n# from nltk import word_tokenize\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem import PorterStemmer\nimport string\nimport numpy as np\nimport re\nimport matplotlib.pyplot as plt\n```\n\n    [nltk_data] Downloading collection 'popular'\n    [nltk_data]    | \n    [nltk_data]    | Downloading package cmudict to /root/nltk_data...\n    [nltk_data]    |   Unzipping corpora/cmudict.zip.\n    [nltk_data]    | Downloading package gazetteers to /root/nltk_data...\n    [nltk_data]    |   Unzipping corpora/gazetteers.zip.\n    [nltk_data]    | Downloading package genesis to /root/nltk_data...\n    [nltk_data]    |   Unzipping corpora/genesis.zip.\n    [nltk_data]    | Downloading package gutenberg to /root/nltk_data...\n    [nltk_data]    |   Unzipping corpora/gutenberg.zip.\n    [nltk_data]    | Downloading package inaugural to /root/nltk_data...\n    [nltk_data]    |   Unzipping corpora/inaugural.zip.\n    [nltk_data]    | Downloading package movie_reviews to\n    [nltk_data]    |     /root/nltk_data...\n    [nltk_data]    |   Unzipping corpora/movie_reviews.zip.\n    [nltk_data]    | Downloading package names to /root/nltk_data...\n    [nltk_data]    |   Unzipping corpora/names.zip.\n    [nltk_data]    | Downloading package shakespeare to /root/nltk_data...\n    [nltk_data]    |   Unzipping corpora/shakespeare.zip.\n    [nltk_data]    | Downloading package stopwords to /root/nltk_data...\n    [nltk_data]    |   Unzipping corpora/stopwords.zip.\n    [nltk_data]    | Downloading package treebank to /root/nltk_data...\n    [nltk_data]    |   Unzipping corpora/treebank.zip.\n    [nltk_data]    | Downloading package twitter_samples to\n    [nltk_data]    |     /root/nltk_data...\n    [nltk_data]    |   Unzipping corpora/twitter_samples.zip.\n    [nltk_data]    | Downloading package omw to /root/nltk_data...\n    [nltk_data]    |   Unzipping corpora/omw.zip.\n    [nltk_data]    | Downloading package wordnet to /root/nltk_data...\n    [nltk_data]    |   Unzipping corpora/wordnet.zip.\n    [nltk_data]    | Downloading package wordnet31 to /root/nltk_data...\n    [nltk_data]    |   Unzipping corpora/wordnet31.zip.\n    [nltk_data]    | Downloading package wordnet_ic to /root/nltk_data...\n    [nltk_data]    |   Unzipping corpora/wordnet_ic.zip.\n    [nltk_data]    | Downloading package words to /root/nltk_data...\n    [nltk_data]    |   Unzipping corpora/words.zip.\n    [nltk_data]    | Downloading package maxent_ne_chunker to\n    [nltk_data]    |     /root/nltk_data...\n    [nltk_data]    |   Unzipping chunkers/maxent_ne_chunker.zip.\n    [nltk_data]    | Downloading package punkt to /root/nltk_data...\n    [nltk_data]    |   Unzipping tokenizers/punkt.zip.\n    [nltk_data]    | Downloading package snowball_data to\n    [nltk_data]    |     /root/nltk_data...\n    [nltk_data]    | Downloading package averaged_perceptron_tagger to\n    [nltk_data]    |     /root/nltk_data...\n    [nltk_data]    |   Unzipping taggers/averaged_perceptron_tagger.zip.\n    [nltk_data]    | \n    [nltk_data]  Done downloading collection popular\n\n\nGet the text document collection\n\n\n```python\n!wget https://storage.googleapis.com/pet-detect-239118/text_retrieval/documents.zip documents.zip\n```\n\n    --2021-10-30 00:52:50--  https://storage.googleapis.com/pet-detect-239118/text_retrieval/documents.zip\n    Resolving storage.googleapis.com (storage.googleapis.com)... 74.125.195.128, 74.125.199.128, 74.125.20.128, ...\n    Connecting to storage.googleapis.com (storage.googleapis.com)|74.125.195.128|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 226023 (221K) [application/x-zip-compressed]\n    Saving to: \u2018documents.zip\u2019\n    \n    documents.zip       100%[===================>] 220.73K  --.-KB/s    in 0.002s  \n    \n    2021-10-30 00:52:50 (99.1 MB/s) - \u2018documents.zip\u2019 saved [226023/226023]\n    \n    --2021-10-30 00:52:50--  http://documents.zip/\n    Resolving documents.zip (documents.zip)... failed: Name or service not known.\n    wget: unable to resolve host address \u2018documents.zip\u2019\n    FINISHED --2021-10-30 00:52:51--\n    Total wall clock time: 0.3s\n    Downloaded: 1 files, 221K in 0.002s (99.1 MB/s)\n\n\n\n```python\nfrom zipfile import ZipFile\nfile_name = '/content/documents.zip'\n\nwith ZipFile(file_name, 'r',) as zip:\n  zip.extractall()\n  print('Done!!')\n```\n\n    Done!!\n\n\nParse the text document dataset into a dictionary\n\n\n```python\ndef get_docDict(path):\n  doc_dict = {}\n  file_names = os.listdir(path)\n\n  for file in file_names:\n    full_path = path+'/'+file\n    with open(full_path, 'r', errors='ignore') as f:\n      data = f.readlines()\n    text = \"\".join([i for i in data])\n    # remove all the \"\\n\" from the text\n    text = re.sub(\"\\n\", \" \", text)\n    doc_dict[file] = text\n  return doc_dict\n```\n\n\n```python\npath = '/content/documents'\ndoc_dict = get_docDict(path)\n```\n\nClean the text data\n\n\n```python\ndef clean_text(doc_dict):\n  \"\"\"\n  input - a dictionary of {filename : text}\n  output - a dictionary of {filename : clean text} \n\n  \"\"\"\n  clean_dict = {}\n  stemmer = PorterStemmer()\n  stopwords_english = stopwords.words('english')\n  \n  for name, doc in doc_dict.items():\n    # remove extra white space\n    text = re.sub(r\"\\s+\", \" \", doc)\n    # remove extra ...\n    text = re.sub(r\"\\.+\",\" \", doc)\n    # remove hyphen\n    text = re.sub(r\"-\",\"\", text)\n    text = text.lower()\n    text_tokens = word_tokenize(text)\n    text_clean = []\n    for word in text_tokens:\n      if (word not in stopwords_english and word not in string.punctuation):\n        stem_word = stemmer.stem(word)\n        text_clean.append(word)\n    \n    clean_dict[name] = text_clean\n    \n  return clean_dict\n```\n\n\n```python\nclean_dict = clean_text(doc_dict)\nclean_dict['A00-1000.pdf.txt'][:5]\n```\n\n\n\n\n    ['association', 'computational', 'linguistics', '6', 'th']\n\n\n\nBuild the dataset vocabulary\n\n\n```python\ndef make_vocab(doc_dict):\n  \"\"\"\n  input - a dictionary of {filename : clean text} \n  output - a set of unique terms forms the dataset vocabulary\n  \"\"\"\n  total_tokens = []\n  for tokens in doc_dict.values():\n    total_tokens += tokens\n  vocab = list(set(total_tokens))\n  return vocab\n```\n\n\n```python\nvocab = make_vocab(clean_dict)\nlen(vocab)\n```\n\n\n\n\n    10811\n\n\n\nCalculate TF-IDF\n\n\n```python\n# compute document-wise term frequency\n\ndef get_DocTF(doc_dict, vocab):\n  \"\"\"\n  input - a dictionary of {filename : clean text}, the vocabulary of the whole dataset\n  output - a dictionary of {filename : {term : count}}\n  \"\"\"\n  tf_dict = {}\n  # make the dict for filename=>{term:frequency}\n  for doc_id in doc_dict.keys():\n    tf_dict[doc_id] = {}\n\n  for word in vocab:\n    for doc_id, text in doc_dict.items():\n      tf_dict[doc_id][word] = text.count(word)\n    \n  return tf_dict\n```\n\n\n```python\ntf_dict = get_DocTF(clean_dict, vocab)\n```\n\n\n```python\n# compute document frequency\n\ndef get_DocDF(clean_dict, vocab):\n  \"\"\"\n  input - a dictionary of {filename : clean text}, the vocabulary of the whole dataset\n  output - a dictionary of all terms in the vocabulary - {term : count}\n  \"\"\"\n  df_dict = {}\n  for word in vocab:\n    freq = 0\n    for text_tokens in clean_dict.values():\n      if word in text_tokens:\n        freq += 1\n    df_dict[word] = freq\n\n  return df_dict\n```\n\n\n```python\ndf_dict = get_DocDF(clean_dict, vocab)\n```\n\n\n```python\n# compute IDF\n\ndef inverse_DF(df_dict, vocab, N):\n  \"\"\"\n  input - a dictionary of DF {term : count}, the vocabulary of the whole dataset, total # of documents in the dataset\n  output - a dictionary of IDF of all terms in the vocabulary - {term : inver_df}\n  \"\"\"\n  idf_dict = {}\n\n  for word in vocab:\n    N_q = df_dict[word]\n    # idf_dict[word] = np.log10(N / N_q) \n    idf_dict[word] = np.log(((N - N_q + 0.5) / (N_q + 0.5)) + 1)\n       \n  return idf_dict\n```\n\n\n```python\nN = len(tf_dict.keys())\nidf_dict = inverse_DF(df_dict, vocab, N)\n```\n\n\n```python\nidf_dict['language']\n```\n\n\n\n\n    0.02298951822469878\n\n\n\n\n```python\n# compute the TF-IDF dictionary \n\ndef get_tf_idf(tf_dict, idf_dict, doc_dict, vocab):\n  tf_idf_dict = {}\n  for doc_id in doc_dict.keys():\n    tf_idf_dict[doc_id] = {}\n  \n  for word in vocab:\n    for doc_id, text_tokens in doc_dict.items():\n      tf_idf_dict[doc_id][word] = round((tf_dict[doc_id][word] * idf_dict[word]), 4)\n  return tf_idf_dict\n```\n\n\n```python\ntf_idf_dict = get_tf_idf(tf_dict, idf_dict, doc_dict, vocab)\ntf_idf_dict['A00-1001.pdf.txt']['language']\n```\n\n\n\n\n    0.5288\n\n\n\nTo use the BM25 algorithm, we still need to compute TF and IDF. \n\nThe **TF** component includes the query frequency, and total number of terms as with TF-IDF, but we add two special parameters `k` and `b` which we can use to optimize our algorithm, but by default we stick with the values of `1.2` and `0.75` respectively. We also include two new values:\n* Average document length (avgdl) - the average length of *all* documents\n* *D* - the length of the current document.\n\nOur new **IDF** component is similar, it maintains the parametes `N` and `N_q`, which are the number of documents and the number of documents *that contain* our query, respectively. And all we do is add a few values (0.5, 1) here and there.\n\n\n```python\n# compute average document length (use the cleaned text)\n\ndef get_avgdl(clean_dict):\n  total_doc = len(clean_dict.keys())\n  total_length = 0\n  for text in clean_dict.values():\n    total_length += len(text)\n\n  avgdl = total_length / total_doc\n\n  return round(avgdl, 4)\n```\n\n\n```python\navgdl = get_avgdl(clean_dict)\navgdl\n```\n\n\n\n\n    2764.3333\n\n\n\n# Implement the BM25 algorithm\n* compute a dictionary of a score of a given term from a given document\n* the total score of a given document is presented as\n\\begin{align}\n    BM25(d)=\\sum_{t=q, f_t,_d >0} log(1 + \\frac{N-df_t+0.5}{df_t+0.5}) \\cdot \\frac{f_t,_d}{f_t,_d + K \\cdot (1-b+b\\frac{l(d)}{avgdl}) }\n\\end{align}\n\n*d* - document, *t* - term, *q* - word from the query, *N* - total number of documents\n\n$f_t,_d$ - term frequenct (TF) given a word from query, $df_t$ - document frequency of a given term\n\n$l(d)$ - total length of a given document d, $avgdl$ - average length of document in the dataset\n\n\n```python\n# compute BM25 score dictionary\n\ndef bm25(tf_dict, clean_dict, df_dict, vocab, k=1.2, b=0.75):\n  bm25_dict = {}\n  avgdl = get_avgdl(clean_dict)\n  N = len(clean_dict.keys())\n  \n  # create the collection of dictionaries of all documents\n  for doc_id in clean_dict.keys():\n    bm25_dict[doc_id] = {}\n\n  for word in vocab:\n    for doc_id, text_tokens in clean_dict.items():\n      freq = tf_dict[doc_id][word]\n      # the TF in BM25\n      tf = (freq*(k+1)) / (freq + k*(1-b+b*len(clean_dict[doc_id])/avgdl))\n      # get DF\n      N_q = df_dict[word]\n      idf = np.log(((N - N_q + 0.5) / (N_q + 0.5)) + 1)\n      score = round(tf*idf,4)\n      bm25_dict[doc_id][word] = score\n\n  return bm25_dict\n```\n\n\n```python\nbm25_dict = bm25(tf_dict, clean_dict, df_dict, vocab)\n```\n\n\n```python\nbm25_dict['A00-1020.pdf.txt']['language']\n```\n\n\n\n\n    0.0415\n\n\n\n# Define the BM25 Model (Probabilistic Model)\n* To find the most relevant documents related to the query\n* Pass the query along with the document set (dictionary) and the BM25 scores of all words in the vocabulary\n* Returns the top 5 documents ID and scores \n\n\n\n```python\ndef BM25Model(query, doc_dict, bm25_dict):\n  query_vocab = []\n  query = query.lower()\n  query = re.sub(r\"\\s+\", \" \", query)\n  stopwords_english = stopwords.words('english')\n\n  for word in query.split():\n    if (word not in string.punctuation and word not in stopwords_english):\n        query_vocab.append(word)\n\n  query_wc = {}\n  for word in query_vocab:\n    query_wc[word] = query.split().count(word)\n\n  relevance_scores = {}\n  # use the raw doc_dict to get the filename only\n  for doc_id in doc_dict.keys():\n    score = 0\n    for word in query_vocab:\n      score += query_wc[word] * bm25_dict[doc_id][word]\n    relevance_scores[doc_id] = round(score,4)\n\n  # sort the relevance score and get the top-k ranking\n  # sort the keys of the relevance score by value\n  sort_keys = sorted(relevance_scores, key=relevance_scores.get , reverse = True)\n  top_keys = sort_keys[:5]\n  top_5 = {}\n  for key in top_keys:\n    top_5[key] = relevance_scores[key]\n\n  return top_5\n```\n\nThe vector space model (VSM)\n\n\n```python\ndef get_tf_idf(tf_dict, idf_dict, doc_dict, vocab):\n  tf_idf_dict = {}\n  for doc_id in doc_dict.keys():\n    tf_idf_dict[doc_id] = {}\n  \n  for word in vocab:\n    for doc_id, text_tokens in doc_dict.items():\n      tf_idf_dict[doc_id][word] = round((tf_dict[doc_id][word] * idf_dict[word]), 4)\n  return tf_idf_dict\n\n\ndef vectorSpaceModel(query, doc_dict,tfidf_dict):\n  query_vocab = []\n  query = query.lower()\n  query = re.sub(r\"\\s+\", \" \", query)\n  stopwords_english = stopwords.words('english')\n\n  for word in query.split():\n    if (word not in string.punctuation and word not in stopwords_english):\n        query_vocab.append(word)\n\n  query_wc = {}\n  for word in query_vocab:\n    query_wc[word] = query.split().count(word)\n\n  relevance_scores = {}\n  for doc_id in doc_dict.keys():\n    score = 0\n    for word in query_vocab:\n      score += query_wc[word] * tf_idf_dict[doc_id][word]\n    relevance_scores[doc_id] = round(score,4)\n\n  # sort the relevance score and get the top-k ranking\n  # sort the keys of the relevance score by value\n  sort_keys = sorted(relevance_scores, key=relevance_scores.get , reverse = True)\n  top_keys = sort_keys[:5]\n  top_5 = {}\n  for key in top_keys:\n    top_5[key] = relevance_scores[key]\n\n  return top_5\n```\n\n\n```python\ntfidf_dict = get_tf_idf(tf_dict, idf_dict, doc_dict, vocab) \n```\n\n\n```python\nquery1 = \"Natural Language\"\nresult1 = BM25Model(query1, doc_dict, bm25_dict)\nprint(f'ranked by BM25: {result1}')\nresult2 = vectorSpaceModel(query1, doc_dict, tfidf_dict)\nprint(f'ranked by VSM: {result2}')\n```\n\n    ranked by BM25: {'A00-1001.pdf.txt': 0.1977, 'A00-1007.pdf.txt': 0.1926, 'A00-1005.pdf.txt': 0.188, 'A00-1000.pdf.txt': 0.1856, 'A00-1009.pdf.txt': 0.1831}\n    ranked by VSM: {'A00-1001.pdf.txt': 2.2942, 'A00-1007.pdf.txt': 1.8492, 'A00-1005.pdf.txt': 1.2415, 'A00-1016.pdf.txt': 0.9508, 'A00-1009.pdf.txt': 0.9115}\n\n\n\n```python\nquery2 = \"generative model\"\nresult1 = BM25Model(query2, doc_dict, bm25_dict)\nprint(f'ranked by BM25: {result1}')\ntfidf_dict = get_tf_idf(tf_dict, idf_dict, doc_dict, vocab) \nresult2 = vectorSpaceModel(query2, doc_dict, tfidf_dict)\nprint(f'ranked by VSM: {result2}')\n```\n\n    ranked by BM25: {'A00-1010.pdf.txt': 3.7823, 'A00-1014.pdf.txt': 2.5833, 'A00-1004.pdf.txt': 0.8908, 'A00-1019.pdf.txt': 0.8835, 'A00-1007.pdf.txt': 0.7827}\n    ranked by VSM: {'A00-1004.pdf.txt': 20.8447, 'A00-1019.pdf.txt': 15.0082, 'A00-1010.pdf.txt': 6.0171, 'A00-1014.pdf.txt': 4.2593, 'A00-1007.pdf.txt': 3.3352}\n\n\n\n```python\nquery3 = \"text retrieval for nature language\"\nresult1 = BM25Model(query3, doc_dict, bm25_dict)\nprint(f'ranked by BM25: {result1}')\ntfidf_dict = get_tf_idf(tf_dict, idf_dict, doc_dict, vocab) \nresult2 = vectorSpaceModel(query3, doc_dict, tfidf_dict)\nprint(f'ranked by VSM: {result2}')\n```\n\n    ranked by BM25: {'A00-1019.pdf.txt': 4.0482, 'A00-1004.pdf.txt': 3.9572, 'A00-1018.pdf.txt': 3.1224, 'A00-1003.pdf.txt': 3.0071, 'A00-1000.pdf.txt': 2.6395}\n    ranked by VSM: {'A00-1003.pdf.txt': 60.3235, 'A00-1004.pdf.txt': 12.596, 'A00-1018.pdf.txt': 12.0305, 'A00-1012.pdf.txt': 11.9561, 'A00-1019.pdf.txt': 8.0488}\n\n\nVisualize score versus document length\n\n\n```python\nBM25_term_score = []\nVSM_term_score = []\ndoc_length = []\n\nfor doc_id in doc_dict.keys():\n  doc_length.append(len(clean_dict[doc_id]))\n  vsm_score = np.sum([x for x in tfidf_dict[doc_id].values()])\n  VSM_term_score.append(vsm_score)\n  bm25_score = np.sum([x for x in bm25_dict[doc_id].values()])\n  BM25_term_score.append(bm25_score)\n\n```\n\n\n```python\nfig = plt.figure(figsize=(12, 8))\ndata = [BM25_term_score, VSM_term_score]\nX = np.arange(21)\n\nax = fig.add_axes([0,0,1,1])\nax.bar(X + 0.00, data[0], color = 'r', width = 0.25)\nax.bar(X + 0.25, data[1], color = 'g', width = 0.25)\nax.legend(['BM25 score', 'VSM score'])\n```\n", "meta": {"hexsha": "6bafb6e72d992ab696cacee22e372f1ea3451188", "size": 45300, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "python_code/BM25_probabilitic_model.ipynb", "max_stars_repo_name": "StanleyLiangYork/Text_retrieval_search_engine", "max_stars_repo_head_hexsha": "433f2e4ed24e31560b1ac5595ea084e89ebd010d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-29T09:10:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T09:10:21.000Z", "max_issues_repo_path": "python_code/BM25_probabilitic_model.ipynb", "max_issues_repo_name": "StanleyLiangYork/Text_retrieval_search_engine", "max_issues_repo_head_hexsha": "433f2e4ed24e31560b1ac5595ea084e89ebd010d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python_code/BM25_probabilitic_model.ipynb", "max_forks_repo_name": "StanleyLiangYork/Text_retrieval_search_engine", "max_forks_repo_head_hexsha": "433f2e4ed24e31560b1ac5595ea084e89ebd010d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-05T23:17:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T23:17:26.000Z", "avg_line_length": 45.1645064806, "max_line_length": 12866, "alphanum_fraction": 0.6160485651, "converted": true, "num_tokens": 4884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505578320071, "lm_q2_score": 0.04535257619949982, "lm_q1q2_score": 0.014243001854571526}}
{"text": "```python\n# Importing packages\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport ipywidgets as widgets\nimport numpy as np\nfrom ipywidgets import Layout\nimport seaborn as sns\nimport itertools\nimport math\n\nimport time\nfrom scipy import linalg\nimport scipy.optimize as optimize\nimport sympy as sm\n\nfrom data_gen import gen_df \n\n# local module for linear algebra\n%load_ext autoreload\n%autoreload 2\n```\n\n\n```python\ngenre_list = {'Action', 'Adult', 'Adventure', 'Animation', 'Biography',\n         'Comedy', 'Crime', 'Documentary', 'Drama', 'Family', 'Fantasy',\n         'FilmNoir', 'GameShow', 'History', 'Horror', 'Music', 'Musical',\n         'Mystery', 'News', 'RealityTV', 'Romance', 'SciFi', 'Short', 'Sport',\n         'TalkShow', 'Thriller', 'War', 'Western'}\n\n# Favorite Genre\ndef genre_func(genre_num, title, text, message): \n    root = Tk.StringVar() # Create tk object\n    root.title(title)\n\n    # Add a grid\n    mainframe = Frame(root)                           # Pass tk object to tkinter frame\n    mainframe.grid(column=0,row=0, sticky=(N,W,E,S) ) # Add grid to frame \n    mainframe.columnconfigure(0, weight = 1)\n    mainframe.rowconfigure(0, weight = 1)\n    mainframe.pack(pady = 100, padx = 100)\n\n    # Create a Tkinter variable\n    genre_gen = StringVar(root)\n\n    # Call genre_list as options to choice from\n    choices = genre_list\n    genre_gen.set(\"\") # Set the default option\n\n    # Pop up window with drop down\n    popupMenu = OptionMenu(mainframe, genre_gen, *choices)\n    Label(mainframe, text=text).grid(row = 1, column = 1)\n    popupMenu.grid(row = 2, column =1)\n\n    # Function on change dropdown value\n    def change_dropdown(*args):\n        print(message + genre_gen.get() )\n\n    # Link function to change dropdown\n    genre_gen.trace('w', change_dropdown)\n\n    root.mainloop()\n    genre_num = genre_gen.get()\n\ngenre_func(genre_num=\"genre1\", title=\"Favorite genre\", text=\"What is your favorite genre?\", message=\"Your favorite genre is \")\ngenre_func(genre_num=\"genre2\", title=\"Second favorite genre\", text=\"What is your second favorite genre?\", message=\"Your second favorite genre is \")\ngenre_func(genre_num=\"genre3\", title=\"Third favorite genre\", text=\"What is your third favorite genre?\", message=\"Your third favorite genre is \")\ngenre_func(genre_num=\"genre4\", title=\"Fourth favorite genre\", text=\"What is your fourth favorite genre?\", message=\"Your fourth favorite genre is \")\ngenre_func(genre_num=\"genre5\", title=\"Fifth favorite genre\", text=\"What is your fifth favorite genre?\", message=\"Your fifth favorite genre is \")\n\n\n\nprint(genre1)\nprint(genre2)\nprint(genre3)\nprint(genre4)\nprint(genre5)\n\n```\n\n    Your favorite genre is Animation\n    Your second favorite genre is Romance\n    Your third favorite genre is Comedy\n    genre1\n    genre2\n    genre3\n\n\n\n```python\ndecades = {\"1920s\", \"1930s\", \"1940s\", \"1950s\", \"1960s\", \"1970s\", \"1980s\", \"1990s\", \"2000s\", \"2010s\"}\n\n# Favorite Decade\ndef decade_func(decade_choice, title, text, message): \n    root = Tk() # Create tk object\n    root.title(title)\n\n    # Add a grid\n    mainframe = Frame(root)                           # Pass tk object to tkinter frame\n    mainframe.grid(column=0,row=0, sticky=(N,W,E,S) ) # Add grid to frame \n    mainframe.columnconfigure(0, weight = 1)\n    mainframe.rowconfigure(0, weight = 1)\n    mainframe.pack(pady = 100, padx = 100)\n\n    # Create a Tkinter variable\n    decade_gen = StringVar(root)\n\n    # Call genre_list as options to choice from\n    choices = decades \n    decade_gen.set(\"\") # Set the default option\n\n    # Pop up window with drop down\n    popupMenu = OptionMenu(mainframe, decade_gen, *choices)\n    Label(mainframe, text=text).grid(row = 1, column = 1)\n    popupMenu.grid(row = 2, column =1)\n\n    # Function on change dropdown value\n    def change_dropdown(*args):\n        print(message + decade_gen.get() )\n\n    # Link function to change dropdown\n    decade_gen.trace('w', change_dropdown)\n\n    root.mainloop()\n    decade_choice = decade_gen.get()\n    \ndecade_func(decade_choice=\"decade\", title=\"Favorite Decade\", text=\"Which decade is your favorite movie decade?\", message=\"Your favorite movie decade is \")\n\nprint(decade_func)\n\n```\n\n\n```python\ngenres = ['Action','Adventure','Animation','Biography','Comedy','Crime','Documentary',\n          'Drama','Family','Fantasy','FilmNoir','History','Horror','Music','Musical',\n          'Mystery','Romance','SciFi','Short','Sport','Thriller','War','Western']\n\nprint(genres)\n\ndf_X[\"genre\"] = \"\"\n\nfor i in genres: \n    df_X.loc[df_X[i] == 1, \"genre\"] = i\n\ndf_X.head(10)\n\n```\n", "meta": {"hexsha": "d1b3c1c2ac6e5f705dbd5aec3a4c7232684601b5", "size": 6705, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "modelproject/Temp/Idaho.ipynb", "max_stars_repo_name": "NumEconCopenhagen/projects-2019-credible-threats", "max_stars_repo_head_hexsha": "17884efb72127475e453b933e10b6a079f5eae9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modelproject/Temp/Idaho.ipynb", "max_issues_repo_name": "NumEconCopenhagen/projects-2019-credible-threats", "max_issues_repo_head_hexsha": "17884efb72127475e453b933e10b6a079f5eae9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2019-04-12T05:41:19.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-14T21:46:01.000Z", "max_forks_repo_path": "modelproject/Temp/Idaho.ipynb", "max_forks_repo_name": "NumEconCopenhagen/projects-2019-credible-threats", "max_forks_repo_head_hexsha": "17884efb72127475e453b933e10b6a079f5eae9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-04-17T07:17:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-01T23:54:04.000Z", "avg_line_length": 34.3846153846, "max_line_length": 171, "alphanum_fraction": 0.5457121551, "converted": true, "num_tokens": 1192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807712415000585, "lm_q2_score": 0.0420877295677101, "lm_q1q2_score": 0.014228898574254599}}
{"text": "# Create SBML model from BioCRNpyler\n\n\n```python\ntry:\n    from biocrnpyler import * \n    #Here are some parameters loaded into default_parameters.txt\n    #Promoter Names: strong, medium, weak correspond to bicistronic RBSs: BCD2, BCD8 and BCD12\n    #RBS Names: strong, medium, Weak correspond to Anderson Promoters: J23100, J23106, and J23103\n    G = DNAassembly(\"X\", promoter = \"strong\", rbs = \"weak\", transcript = None, protein = None)\n    #Also notice that the names of transcript and protein can be changed, or set to Species.\n    x0_dict = {\"protein_RNAP_machinery\":10., \"protein_RNAase_machinery\":5.0, \"protein_Ribo_machinery\":50.,\n                   'dna_X':0.5, 'dna_cellular_processes':0.01}\n    model_txtl = TxTlDilutionMixture(\"txtl\", components = [G], parameter_file = \"default_parameters.txt\",\n                                    initial_condition_dictionary = x0_dict)\n\n    CRN = model_txtl.compile_crn()\n    print(repr(CRN),\"\\n\", CRN.pretty_print(show_attributes = True, show_material = True, show_rates = True),\"\\n\\n\")\n    # except:\n    #     print('BioCRNpyler not found. To run this notebook, make sure you run pip install biocrnpyler first.')\n    CRN.write_sbml_file('biocrnpyler_gene_expression.xml')\nexcept:\n    print('BioCRNpyler not found. To run this notebook make sure you run pip install biocrpyler first.')\n```\n\n    Species = dna_X, protein_RNAP_machinery, rna_X, complex_dna_X_protein_RNAP_machinery_, protein_Ribo_machinery, protein_X, complex_protein_Ribo_machinery_rna_X_, protein_RNAase_machinery, dna_cellular_processes, rna_cellular_processes, complex_dna_cellular_processes_protein_RNAP_machinery_, protein_cellular_processes, complex_protein_Ribo_machinery_rna_cellular_processes_, complex_protein_RNAase_machinery_rna_X_, complex_complex_protein_Ribo_machinery_rna_X__protein_RNAase_machinery_, complex_protein_RNAase_machinery_rna_cellular_processes_, complex_complex_protein_Ribo_machinery_rna_cellular_processes__protein_RNAase_machinery_\n    Reactions = [\n    \tdna[X]+protein[RNAP(machinery)] <--> complex[dna[X]:protein[RNAP]]\n    \tcomplex[dna[X]:protein[RNAP]] --> dna[X]+rna[X]+protein[RNAP(machinery)]\n    \trna[X]+protein[Ribo(machinery)] <--> complex[protein[Ribo]:rna[X]]\n    \tcomplex[protein[Ribo]:rna[X]] --> rna[X]+protein[X]+protein[Ribo(machinery)]\n    \tdna[cellular_processes]+protein[RNAP(machinery)] <--> complex[dna[cellular_processes]:protein[RNAP]]\n    \tcomplex[dna[cellular_processes]:protein[RNAP]] --> dna[cellular_processes]+rna[cellular_processes]+protein[RNAP(machinery)]\n    \trna[cellular_processes]+protein[Ribo(machinery)] <--> complex[protein[Ribo]:rna[cellular_processes]]\n    \tcomplex[protein[Ribo]:rna[cellular_processes]] --> rna[cellular_processes]+protein[cellular_processes]+protein[Ribo(machinery)]\n    \trna[X]+protein[RNAase(machinery)] <--> complex[protein[RNAase]:rna[X]]\n    \tcomplex[protein[RNAase]:rna[X]] --> protein[RNAase(machinery)]\n    \tcomplex[protein[Ribo]:rna[X]]+protein[RNAase(machinery)] <--> complex[complex[protein[Ribo]:rna[X]]:protein[RNAase]]\n    \tcomplex[complex[protein[Ribo]:rna[X]]:protein[RNAase]] --> protein[Ribo(machinery)]+protein[RNAase(machinery)]\n    \trna[cellular_processes]+protein[RNAase(machinery)] <--> complex[protein[RNAase]:rna[cellular_processes]]\n    \tcomplex[protein[RNAase]:rna[cellular_processes]] --> protein[RNAase(machinery)]\n    \tcomplex[protein[Ribo]:rna[cellular_processes]]+protein[RNAase(machinery)] <--> complex[complex[protein[Ribo]:rna[cellular_processes]]:protein[RNAase]]\n    \tcomplex[complex[protein[Ribo]:rna[cellular_processes]]:protein[RNAase]] --> protein[Ribo(machinery)]+protein[RNAase(machinery)]\n    \trna[X] --> \n    \tprotein[X] --> \n    \trna[cellular_processes] --> \n    \tprotein[cellular_processes] --> \n    ] \n     Species (17) = {0. dna[X] init_conc = 0.5, 1. protein[RNAP(machinery)] init_conc = 10.0, 2. rna[X] init_conc = 0, 3. complex[dna[X]:protein[RNAP]] init_conc = 0, 4. protein[Ribo(machinery)] init_conc = 50.0, 5. protein[X] init_conc = 0, 6. complex[protein[Ribo]:rna[X]] init_conc = 0, 7. protein[RNAase(machinery)] init_conc = 5.0, 8. dna[cellular_processes] init_conc = 0.01, 9. rna[cellular_processes] init_conc = 0, 10. complex[dna[cellular_processes]:protein[RNAP]] init_conc = 0, 11. protein[cellular_processes] init_conc = 0, 12. complex[protein[Ribo]:rna[cellular_processes]] init_conc = 0, 13. complex[protein[RNAase]:rna[X]] init_conc = 0, 14. complex[complex[protein[Ribo]:rna[X]]:protein[RNAase]] init_conc = 0, 15. complex[protein[RNAase]:rna[cellular_processes]] init_conc = 0, 16. complex[complex[protein[Ribo]:rna[cellular_processes]]:protein[RNAase]] init_conc = 0}\n    \n    Reactions (20) = [\n    0. dna[X]+protein[RNAP(machinery)] <--> complex[dna[X]:protein[RNAP]]\n     Kf=k_forward * dna_X * protein_RNAP_machinery\n     Kr=k_reverse * complex_dna_X_protein_RNAP_machinery_\n      k_forward=100.0\n      found_key=(mech=None, partid=None, name=kb).\n      search_key=(mech=transcription_mm, partid=strong, name=kb).\n      k_reverse=0.5\n      found_key=(mech=None, partid=strong, name=ku).\n      search_key=(mech=transcription_mm, partid=strong, name=ku).\n    \n    1. complex[dna[X]:protein[RNAP]] --> dna[X]+rna[X]+protein[RNAP(machinery)]\n     Kf=k_forward * complex_dna_X_protein_RNAP_machinery_\n      k_forward=3.926187672\n      found_key=(mech=None, partid=strong, name=ktx).\n      search_key=(mech=transcription_mm, partid=strong, name=ktx).\n    \n    2. rna[X]+protein[Ribo(machinery)] <--> complex[protein[Ribo]:rna[X]]\n     Kf=k_forward * rna_X * protein_Ribo_machinery\n     Kr=k_reverse * complex_protein_Ribo_machinery_rna_X_\n      k_forward=100.0\n      found_key=(mech=None, partid=None, name=kb).\n      search_key=(mech=translation_mm, partid=weak, name=kb).\n      k_reverse=5.0\n      found_key=(mech=None, partid=weak, name=ku).\n      search_key=(mech=translation_mm, partid=weak, name=ku).\n    \n    3. complex[protein[Ribo]:rna[X]] --> rna[X]+protein[X]+protein[Ribo(machinery)]\n     Kf=k_forward * complex_protein_Ribo_machinery_rna_X_\n      k_forward=0.05\n      found_key=(mech=None, partid=None, name=ktl).\n      search_key=(mech=translation_mm, partid=weak, name=ktl).\n    \n    4. dna[cellular_processes]+protein[RNAP(machinery)] <--> complex[dna[cellular_processes]:protein[RNAP]]\n     Kf=k_forward * dna_cellular_processes * protein_RNAP_machinery\n     Kr=k_reverse * complex_dna_cellular_processes_protein_RNAP_machinery_\n      k_forward=500\n      found_key=(mech=transcription, partid=None, name=kb).\n      search_key=(mech=transcription_mm, partid=average_promoter, name=kb).\n      k_reverse=50\n      found_key=(mech=transcription, partid=None, name=ku).\n      search_key=(mech=transcription_mm, partid=average_promoter, name=ku).\n    \n    5. complex[dna[cellular_processes]:protein[RNAP]] --> dna[cellular_processes]+rna[cellular_processes]+protein[RNAP(machinery)]\n     Kf=k_forward * complex_dna_cellular_processes_protein_RNAP_machinery_\n      k_forward=0.1\n      found_key=(mech=transcription, partid=None, name=ktx).\n      search_key=(mech=transcription_mm, partid=average_promoter, name=ktx).\n    \n    6. rna[cellular_processes]+protein[Ribo(machinery)] <--> complex[protein[Ribo]:rna[cellular_processes]]\n     Kf=k_forward * rna_cellular_processes * protein_Ribo_machinery\n     Kr=k_reverse * complex_protein_Ribo_machinery_rna_cellular_processes_\n      k_forward=500\n      found_key=(mech=translation, partid=None, name=kb).\n      search_key=(mech=translation_mm, partid=average_rbs, name=kb).\n      k_reverse=5\n      found_key=(mech=translation, partid=None, name=ku).\n      search_key=(mech=translation_mm, partid=average_rbs, name=ku).\n    \n    7. complex[protein[Ribo]:rna[cellular_processes]] --> rna[cellular_processes]+protein[cellular_processes]+protein[Ribo(machinery)]\n     Kf=k_forward * complex_protein_Ribo_machinery_rna_cellular_processes_\n      k_forward=0.1\n      found_key=(mech=translation, partid=None, name=ktl).\n      search_key=(mech=translation_mm, partid=average_rbs, name=ktl).\n    \n    8. rna[X]+protein[RNAase(machinery)] <--> complex[protein[RNAase]:rna[X]]\n     Kf=k_forward * rna_X * protein_RNAase_machinery\n     Kr=k_reverse * complex_protein_RNAase_machinery_rna_X_\n      k_forward=100.0\n      found_key=(mech=None, partid=None, name=kb).\n      search_key=(mech=rna_degredation_mm, partid=rna_X, name=kb).\n      k_reverse=10.0\n      found_key=(mech=None, partid=None, name=ku).\n      search_key=(mech=rna_degredation_mm, partid=rna_X, name=ku).\n    \n    9. complex[protein[RNAase]:rna[X]] --> protein[RNAase(machinery)]\n     Kf=k_forward * complex_protein_RNAase_machinery_rna_X_\n      k_forward=0.001\n      found_key=(mech=rna_degredation_mm, partid=None, name=kdeg).\n      search_key=(mech=rna_degredation_mm, partid=rna_X, name=kdeg).\n    \n    10. complex[protein[Ribo]:rna[X]]+protein[RNAase(machinery)] <--> complex[complex[protein[Ribo]:rna[X]]:protein[RNAase]]\n     Kf=k_forward * complex_protein_Ribo_machinery_rna_X_ * protein_RNAase_machinery\n     Kr=k_reverse * complex_complex_protein_Ribo_machinery_rna_X__protein_RNAase_machinery_\n      k_forward=100.0\n      found_key=(mech=None, partid=None, name=kb).\n      search_key=(mech=rna_degredation_mm, partid=complex_protein_Ribo_machinery_rna_X_, name=kb).\n      k_reverse=10.0\n      found_key=(mech=None, partid=None, name=ku).\n      search_key=(mech=rna_degredation_mm, partid=complex_protein_Ribo_machinery_rna_X_, name=ku).\n    \n    11. complex[complex[protein[Ribo]:rna[X]]:protein[RNAase]] --> protein[Ribo(machinery)]+protein[RNAase(machinery)]\n     Kf=k_forward * complex_complex_protein_Ribo_machinery_rna_X__protein_RNAase_machinery_\n      k_forward=0.001\n      found_key=(mech=rna_degredation_mm, partid=None, name=kdeg).\n      search_key=(mech=rna_degredation_mm, partid=complex_protein_Ribo_machinery_rna_X_, name=kdeg).\n    \n    12. rna[cellular_processes]+protein[RNAase(machinery)] <--> complex[protein[RNAase]:rna[cellular_processes]]\n     Kf=k_forward * rna_cellular_processes * protein_RNAase_machinery\n     Kr=k_reverse * complex_protein_RNAase_machinery_rna_cellular_processes_\n      k_forward=100.0\n      found_key=(mech=None, partid=None, name=kb).\n      search_key=(mech=rna_degredation_mm, partid=rna_cellular_processes, name=kb).\n      k_reverse=10.0\n      found_key=(mech=None, partid=None, name=ku).\n      search_key=(mech=rna_degredation_mm, partid=rna_cellular_processes, name=ku).\n    \n    13. complex[protein[RNAase]:rna[cellular_processes]] --> protein[RNAase(machinery)]\n     Kf=k_forward * complex_protein_RNAase_machinery_rna_cellular_processes_\n      k_forward=0.001\n      found_key=(mech=rna_degredation_mm, partid=None, name=kdeg).\n      search_key=(mech=rna_degredation_mm, partid=rna_cellular_processes, name=kdeg).\n    \n    14. complex[protein[Ribo]:rna[cellular_processes]]+protein[RNAase(machinery)] <--> complex[complex[protein[Ribo]:rna[cellular_processes]]:protein[RNAase]]\n     Kf=k_forward * complex_protein_Ribo_machinery_rna_cellular_processes_ * protein_RNAase_machinery\n     Kr=k_reverse * complex_complex_protein_Ribo_machinery_rna_cellular_processes__protein_RNAase_machinery_\n      k_forward=100.0\n      found_key=(mech=None, partid=None, name=kb).\n      search_key=(mech=rna_degredation_mm, partid=complex_protein_Ribo_machinery_rna_cellular_processes_, name=kb).\n      k_reverse=10.0\n      found_key=(mech=None, partid=None, name=ku).\n      search_key=(mech=rna_degredation_mm, partid=complex_protein_Ribo_machinery_rna_cellular_processes_, name=ku).\n    \n    15. complex[complex[protein[Ribo]:rna[cellular_processes]]:protein[RNAase]] --> protein[Ribo(machinery)]+protein[RNAase(machinery)]\n     Kf=k_forward * complex_complex_protein_Ribo_machinery_rna_cellular_processes__protein_RNAase_machinery_\n      k_forward=0.001\n      found_key=(mech=rna_degredation_mm, partid=None, name=kdeg).\n      search_key=(mech=rna_degredation_mm, partid=complex_protein_Ribo_machinery_rna_cellular_processes_, name=kdeg).\n    \n    16. rna[X] --> \n     Kf=k_forward * rna_X\n      k_forward=0.001\n      found_key=(mech=None, partid=None, name=kdil).\n      search_key=(mech=global_degredation_via_dilution, partid=rna_X, name=kdil).\n    \n    17. protein[X] --> \n     Kf=k_forward * protein_X\n      k_forward=0.001\n      found_key=(mech=None, partid=None, name=kdil).\n      search_key=(mech=global_degredation_via_dilution, partid=protein_X, name=kdil).\n    \n    18. rna[cellular_processes] --> \n     Kf=k_forward * rna_cellular_processes\n      k_forward=0.001\n      found_key=(mech=None, partid=None, name=kdil).\n      search_key=(mech=global_degredation_via_dilution, partid=rna_cellular_processes, name=kdil).\n    \n    19. protein[cellular_processes] --> \n     Kf=k_forward * protein_cellular_processes\n      k_forward=0.001\n      found_key=(mech=None, partid=None, name=kdil).\n      search_key=(mech=global_degredation_via_dilution, partid=protein_cellular_processes, name=kdil).\n    \n    ] \n    \n    \n\n\n\n\n\n    True\n\n\n\n\n```python\nfrom IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity = \"all\"\n\nfrom autoreduce import *\nimport numpy as np\nfrom sympy import symbols\n```\n\n\n```python\nfrom autoreduce.converters import load_sbml\nx, f, P, params_values, x_init = load_sbml('biocrnpyler_gene_expression.xml')\n# x[5] is desired output protein, set the output matrix C, in y = Cx, accordingly:\nC = np.zeros( (1, len(x)), dtype = int)\nC[0][5] = 1\n# Set initial conditions:\nsys = System(x, f, params = P, params_values = params_values, C = C, x_init = x_init)\n```\n\n\n```python\nsys.x\n```\n\n\n\n\n    [dna_X,\n     protein_RNAP_machinery,\n     rna_X,\n     complex_dna_X_protein_RNAP_machinery_,\n     protein_Ribo_machinery,\n     protein_X,\n     complex_protein_Ribo_machinery_rna_X_,\n     protein_RNAase_machinery,\n     dna_cellular_processes,\n     rna_cellular_processes,\n     complex_dna_cellular_processes_protein_RNAP_machinery_,\n     protein_cellular_processes,\n     complex_protein_Ribo_machinery_rna_cellular_processes_,\n     complex_protein_RNAase_machinery_rna_X_,\n     complex_complex_protein_Ribo_machinery_rna_X__protein_RNAase_machinery_,\n     complex_protein_RNAase_machinery_rna_cellular_processes_,\n     complex_complex_protein_Ribo_machinery_rna_cellular_processes__protein_RNAase_machinery_]\n\n\n\n# Create and solve the ODE for the model\n\n\n```python\nfrom autoreduce.utils import get_ODE\ntimepoints_ode = np.linspace(0, 200, 100)\nsys_ode = get_ODE(sys, timepoints_ode)\nsol = sys_ode.solve_system().T\ntry:\n    import matplotlib.pyplot as plt\n    plt.plot(timepoints_ode, np.transpose(np.array(C)@sol))\n    plt.xlabel('Time')\n    plt.ylabel('[Outputs]')\n    plt.show()\nexcept:\n    print('Plotting libraries missing.')\n```\n\n# Local sensitivity analysis for BioCRNpyler model\n\n\n```python\nfrom autoreduce.utils import get_SSM\ntimepoints_ssm = np.linspace(0,20,10)\nsys_ssm = get_SSM(sys, timepoints_ssm)\n# Uncomment to run\n# Ss = sys_ssm.compute_SSM() # len(timepoints) x len(params) x len(states)\n```\n\n    SSM Progress: |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 100.0% Complete\n\n\n\n```python\n# out_Ss = []\n# for i in range(len(P)):\n#     out_Ss.append((np.array(C)@(Ss[:,i,:].T)))\n# out_Ss = np.reshape(np.array(out_Ss), (len(timepoints_ssm), len(P), 1))\n```\n\n# Plot heatmap for sensitivity analysis\n\n\n```python\n# try:\n    # import seaborn as sn\n    # import matplotlib.pyplot as plt\n    # for j in range(1):\n    #     sn.heatmap(out_Ss[:,:,j].T)\n    #     plt.xlabel('Time')\n    #     plt.ylabel('Parameters')\n    #     plt.title('Sensitivity of output[{0}] with respect to all parameters'.format(j))\n    #     plt.show()\n# except:\n#     print('Plotting libraries missing.')\n```\n\n# Model reduction starts here:\n\n\n```python\nfrom autoreduce.utils import get_reducible\ntimepoints_ssm = np.linspace(0,20,10)\nsys_reduce = get_reducible(sys, timepoints_ode, timepoints_ssm)\nsys_reduce.nstates_tol_min = 3 # Minimum number of states tbat you want in the reduced model\n```\n\n# Conservation Laws (if any)\n\n\n```python\n# G, P, C1, T, R, C2, E, C3, X = sys.x\n# conserved_quantities = [P + C1 - P_tot, R + C2 - R_tot, E + C3 - E_tot]\n# states_to_eliminate = [1,4,6]\n# f_cons = sys_reduce.set_conservation_laws(conserved_quantities, states_to_eliminate)\n```\n\n\n```python\n# from autoreduce.utils import get_ODE\n# timepoints_ode = np.linspace(0, 2, 100)\n# params_values = [100, 10, 4, 10, 0.25, 2, 10, 0.5, 1, 10, 1000, 1000, 1000]\n# sys_reduce.params_values = params_values\n# sys_ode = get_ODE(sys_reduce, timepoints_ode)\n# sol = sys_ode.solve_system().T\n# try:\n    # import matplotlib.pyplot as plt\n    # plt.plot(timepoints_ode, np.transpose(np.array(sys_reduce.C)@sol))\n    # plt.xlabel('Time')\n    # plt.ylabel('[Outputs]')\n    # plt.show()\n# except:\n#     print('Plotting libraries missing.')\n```\n\n# Derive model with no intermediate complexes\n\n\n```python\n# states_to_remove = [x[12], x[12], x[14], x[15], x[16]]\n# retained_states = []\n# for state in x:\n#     index = sys.x.index(state)\n#     if state not in states_to_remove:\n#         retained_states.append(x[index])\nreduced_sys, fast_ss = sys_reduce.solve_timescale_separation([x[0], x[1], x[2], x[3], x[4], x[5], \n                                                             x[6], x[7], x[8], x[9], x[10], x[11]],\n                                                             debug = False)\n# reduced_sys.f[1]\n# Se = sys_reduce.get_robustness_metric(reduced_sys, fast_ss, [0,2,5])\n```\n\n    count 1\n    Successful time-scale separation solution obtained with states: [dna_X, protein_RNAP_machinery, rna_X, complex_dna_X_protein_RNAP_machinery_, protein_Ribo_machinery, protein_X, complex_protein_Ribo_machinery_rna_X_, protein_RNAase_machinery, dna_cellular_processes, rna_cellular_processes, complex_dna_cellular_processes_protein_RNAP_machinery_, protein_cellular_processes]!\n\n\n\n```python\nreduced_sys.f\n```\n\n\n\n\n    [complex_dna_X_protein_RNAP_machinery_*ktx_strong_ + complex_dna_X_protein_RNAP_machinery_*ku_strong_ - dna_X*kb__*protein_RNAP_machinery,\n     complex_dna_X_protein_RNAP_machinery_*ktx_strong_ + complex_dna_X_protein_RNAP_machinery_*ku_strong_ + complex_dna_cellular_processes_protein_RNAP_machinery_*ktx__transcription + complex_dna_cellular_processes_protein_RNAP_machinery_*ku__transcription - dna_X*kb__*protein_RNAP_machinery - dna_cellular_processes*kb__transcription*protein_RNAP_machinery,\n     complex_dna_X_protein_RNAP_machinery_*ktx_strong_ + complex_protein_Ribo_machinery_rna_X_*ktl__ + complex_protein_Ribo_machinery_rna_X_*ku_weak_ + kb__*ku__*protein_RNAase_machinery*rna_X/(kdeg__rna_degredation_mm + ku__) - kb__*protein_RNAase_machinery*rna_X - kb__*protein_Ribo_machinery*rna_X - kdil__*rna_X,\n     -complex_dna_X_protein_RNAP_machinery_*ktx_strong_ - complex_dna_X_protein_RNAP_machinery_*ku_strong_ + dna_X*kb__*protein_RNAP_machinery,\n     complex_protein_Ribo_machinery_rna_X_*kb__*kdeg__rna_degredation_mm*protein_RNAase_machinery/(kdeg__rna_degredation_mm + ku__) + complex_protein_Ribo_machinery_rna_X_*ktl__ + complex_protein_Ribo_machinery_rna_X_*ku_weak_ + kb__*kb__translation*kdeg__rna_degredation_mm*protein_RNAase_machinery*protein_Ribo_machinery*rna_cellular_processes/(kb__*kdeg__rna_degredation_mm*protein_RNAase_machinery + kdeg__rna_degredation_mm*ktl__translation + kdeg__rna_degredation_mm*ku__translation + ktl__translation*ku__ + ku__*ku__translation) - kb__*protein_Ribo_machinery*rna_X - kb__translation*protein_Ribo_machinery*rna_cellular_processes + ktl__translation*(kb__*kb__translation*ku__*protein_RNAase_machinery*protein_Ribo_machinery*rna_cellular_processes/(kb__*kdeg__rna_degredation_mm*protein_RNAase_machinery + kdeg__rna_degredation_mm*ktl__translation + kdeg__rna_degredation_mm*ku__translation + ktl__translation*ku__ + ku__*ku__translation) + kb__translation*protein_Ribo_machinery*rna_cellular_processes)/(kb__*protein_RNAase_machinery + ktl__translation + ku__translation) + ku__translation*(kb__*kb__translation*ku__*protein_RNAase_machinery*protein_Ribo_machinery*rna_cellular_processes/(kb__*kdeg__rna_degredation_mm*protein_RNAase_machinery + kdeg__rna_degredation_mm*ktl__translation + kdeg__rna_degredation_mm*ku__translation + ktl__translation*ku__ + ku__*ku__translation) + kb__translation*protein_Ribo_machinery*rna_cellular_processes)/(kb__*protein_RNAase_machinery + ktl__translation + ku__translation),\n     complex_protein_Ribo_machinery_rna_X_*ktl__ - kdil__*protein_X,\n     complex_protein_Ribo_machinery_rna_X_*kb__*ku__*protein_RNAase_machinery/(kdeg__rna_degredation_mm + ku__) - complex_protein_Ribo_machinery_rna_X_*kb__*protein_RNAase_machinery - complex_protein_Ribo_machinery_rna_X_*ktl__ - complex_protein_Ribo_machinery_rna_X_*ku_weak_ + kb__*protein_Ribo_machinery*rna_X,\n     complex_protein_Ribo_machinery_rna_X_*kb__*kdeg__rna_degredation_mm*protein_RNAase_machinery/(kdeg__rna_degredation_mm + ku__) + complex_protein_Ribo_machinery_rna_X_*kb__*ku__*protein_RNAase_machinery/(kdeg__rna_degredation_mm + ku__) - complex_protein_Ribo_machinery_rna_X_*kb__*protein_RNAase_machinery + kb__*kb__translation*kdeg__rna_degredation_mm*protein_RNAase_machinery*protein_Ribo_machinery*rna_cellular_processes/(kb__*kdeg__rna_degredation_mm*protein_RNAase_machinery + kdeg__rna_degredation_mm*ktl__translation + kdeg__rna_degredation_mm*ku__translation + ktl__translation*ku__ + ku__*ku__translation) + kb__*kb__translation*ku__*protein_RNAase_machinery*protein_Ribo_machinery*rna_cellular_processes/(kb__*kdeg__rna_degredation_mm*protein_RNAase_machinery + kdeg__rna_degredation_mm*ktl__translation + kdeg__rna_degredation_mm*ku__translation + ktl__translation*ku__ + ku__*ku__translation) + kb__*kdeg__rna_degredation_mm*protein_RNAase_machinery*rna_X/(kdeg__rna_degredation_mm + ku__) + kb__*kdeg__rna_degredation_mm*protein_RNAase_machinery*rna_cellular_processes/(kdeg__rna_degredation_mm + ku__) + kb__*ku__*protein_RNAase_machinery*rna_X/(kdeg__rna_degredation_mm + ku__) + kb__*ku__*protein_RNAase_machinery*rna_cellular_processes/(kdeg__rna_degredation_mm + ku__) - kb__*protein_RNAase_machinery*rna_X - kb__*protein_RNAase_machinery*rna_cellular_processes - kb__*protein_RNAase_machinery*(kb__*kb__translation*ku__*protein_RNAase_machinery*protein_Ribo_machinery*rna_cellular_processes/(kb__*kdeg__rna_degredation_mm*protein_RNAase_machinery + kdeg__rna_degredation_mm*ktl__translation + kdeg__rna_degredation_mm*ku__translation + ktl__translation*ku__ + ku__*ku__translation) + kb__translation*protein_Ribo_machinery*rna_cellular_processes)/(kb__*protein_RNAase_machinery + ktl__translation + ku__translation),\n     complex_dna_cellular_processes_protein_RNAP_machinery_*ktx__transcription + complex_dna_cellular_processes_protein_RNAP_machinery_*ku__transcription - dna_cellular_processes*kb__transcription*protein_RNAP_machinery,\n     complex_dna_cellular_processes_protein_RNAP_machinery_*ktx__transcription + kb__*ku__*protein_RNAase_machinery*rna_cellular_processes/(kdeg__rna_degredation_mm + ku__) - kb__*protein_RNAase_machinery*rna_cellular_processes - kb__translation*protein_Ribo_machinery*rna_cellular_processes - kdil__*rna_cellular_processes + ktl__translation*(kb__*kb__translation*ku__*protein_RNAase_machinery*protein_Ribo_machinery*rna_cellular_processes/(kb__*kdeg__rna_degredation_mm*protein_RNAase_machinery + kdeg__rna_degredation_mm*ktl__translation + kdeg__rna_degredation_mm*ku__translation + ktl__translation*ku__ + ku__*ku__translation) + kb__translation*protein_Ribo_machinery*rna_cellular_processes)/(kb__*protein_RNAase_machinery + ktl__translation + ku__translation) + ku__translation*(kb__*kb__translation*ku__*protein_RNAase_machinery*protein_Ribo_machinery*rna_cellular_processes/(kb__*kdeg__rna_degredation_mm*protein_RNAase_machinery + kdeg__rna_degredation_mm*ktl__translation + kdeg__rna_degredation_mm*ku__translation + ktl__translation*ku__ + ku__*ku__translation) + kb__translation*protein_Ribo_machinery*rna_cellular_processes)/(kb__*protein_RNAase_machinery + ktl__translation + ku__translation),\n     -complex_dna_cellular_processes_protein_RNAP_machinery_*ktx__transcription - complex_dna_cellular_processes_protein_RNAP_machinery_*ku__transcription + dna_cellular_processes*kb__transcription*protein_RNAP_machinery,\n     -kdil__*protein_cellular_processes + ktl__translation*(kb__*kb__translation*ku__*protein_RNAase_machinery*protein_Ribo_machinery*rna_cellular_processes/(kb__*kdeg__rna_degredation_mm*protein_RNAase_machinery + kdeg__rna_degredation_mm*ktl__translation + kdeg__rna_degredation_mm*ku__translation + ktl__translation*ku__ + ku__*ku__translation) + kb__translation*protein_Ribo_machinery*rna_cellular_processes)/(kb__*protein_RNAase_machinery + ktl__translation + ku__translation)]\n\n\n", "meta": {"hexsha": "4ee8d49f948b70d651859dee039e464ef6f072fe", "size": 73926, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/AutoReduce-BioCRNpyler interface.ipynb", "max_stars_repo_name": "ayush9pandey/sbmlReduce", "max_stars_repo_head_hexsha": "0612bbb1def5c1aa5f8d3ca125998d0fefa46e53", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-08-10T20:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-21T19:47:41.000Z", "max_issues_repo_path": "examples/AutoReduce-BioCRNpyler interface.ipynb", "max_issues_repo_name": "ayush9pandey/sbmlReduce", "max_issues_repo_head_hexsha": "0612bbb1def5c1aa5f8d3ca125998d0fefa46e53", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2020-10-14T21:46:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-20T22:18:32.000Z", "max_forks_repo_path": "examples/AutoReduce-BioCRNpyler interface.ipynb", "max_forks_repo_name": "ayush9pandey/AutoReduce", "max_forks_repo_head_hexsha": "0612bbb1def5c1aa5f8d3ca125998d0fefa46e53", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-21T23:19:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-21T23:19:47.000Z", "avg_line_length": 109.1964549483, "max_line_length": 14552, "alphanum_fraction": 0.8336715093, "converted": true, "num_tokens": 7332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.036220057555534334, "lm_q1q2_score": 0.014075767294404027}}
{"text": "# Data Analysis Search Results\n\n\n```python\n%load_ext autoreload\n%autoreload 2\n```\n\n\n```python\nimport os\nimport re\nimport glob\nimport time\nfrom collections import Counter\nimport json\nfrom multiprocessing import Pool\n\nfrom tqdm import tqdm\nfrom lxml import html\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LinearSegmentedColormap\nfrom matplotlib.patches import Patch\nfrom matplotlib.lines import Line2D\nimport seaborn as sns\nimport numpy as np\nfrom sklearn.utils import resample\n\nfrom utils import value_counts, calculate_table\n```\n\n\n```python\n# inputs\ndata_dir = '../data/output/datasets/'\nfn_search = f'{data_dir}/searches_check.csv.xz'\nfn_products = f'{data_dir}/products.csv.xz'\nfn_queries = '../data/input/combined_queries_with_source.csv'\nfn_amazon = f'{data_dir}/amazon_private_label.csv.xz'\n\n# intermediary\nfn_compare = f'{data_dir}/quality_and_sales_comparisons.csv'\n\n# outputs\noutput_dir = '../data/output'\ntable1 = f'{output_dir}/tables/table1-not_always_labelled.csv'\nfig2 = f'{output_dir}/figures/fig2-scatter.png'\nfig2_csv = f'{output_dir}/figures/fig2-scatter.csv'\nfig3a = f'{output_dir}/figures/fig3a-heatmap_amzn.png'\nfig3b = f'{output_dir}/figures/fig3b-heatmap-unaffilated.png'\nfig3c = f'{output_dir}/figures/fig3c-heatmap-sponsored.png'\nfig3a_csv = f'{output_dir}/figures/fig3a-heatmap_amzn.csv'\nfig3b_csv = f'{output_dir}/figures/fig3b-heatmap-unaffilated.csv'\nfig3c_csv = f'{output_dir}/figures/fig3c-heatmap-sponsored.csv'\ntable3 = f'{output_dir}/tables/table3-appendix-generic.csv'\nfor subdir in ['figures', 'tables']:\n    os.makedirs(f'{output_dir}/{subdir}', exist_ok=True)\n```\n\n\n```python\ndf_amazon = pd.read_csv(fn_amazon, compression='xz')\ndf_products = pd.read_csv(fn_products, compression='xz')\ndf_search = pd.read_csv(fn_search, compression='xz')\nkeywords = pd.read_csv(fn_queries)\n```\n\n\n```python\nkeywords.source.value_counts()\n```\n\n\n\n\n    autocomplete amazon     7696\n    autocomplete walmart    3806\n    seller                  2700\n    generic                 1600\n    Name: source, dtype: int64\n\n\n\n\n```python\namazon_asin = set(df_amazon.asin.tolist())\nlen(amazon_asin)\n```\n\n\n\n\n    137428\n\n\n\n## merge data\n\n\n```python\n_df_search = df_search[df_search.product_type.isin(['regular_placement'])]\n\nsearches_with_amazon_brands = _df_search[\n    _df_search.asin.isin(amazon_asin)\n].search_term.unique()\nlen(searches_with_amazon_brands)\n```\n\n\n\n\n    4567\n\n\n\n\n```python\n_df_search = _df_search[_df_search.search_term.isin(searches_with_amazon_brands)].merge(df_products, how='left')\n_df_search['is_amazon'] = _df_search.asin.isin(amazon_asin)\n```\n\n\n```python\n_df_search.iloc[0]\n```\n\n\n\n\n    asin                                                              B086VR2KY8\n    product_name               All-New Toshiba 50LF621U21 50-inch Smart 4K UH...\n    stars                                                                    4.6\n    reviews                                                                 5282\n    brand                                                                    NaN\n    product_url                /gp/slredirect/picassoRedirect.html/ref=pa_sp_...\n    is_prime                                                                True\n    is_fresh                                                               False\n    is_sponsored                                                           False\n    is_featured_brand                                                       True\n    is_amazons_choice                                                      False\n    is_best_seller                                                         False\n    has_sponsored_metadata                                                  True\n    product_order                                                              1\n    search_term                                                 50 inch smart tv\n    product_type                                               regular_placement\n    price                                                        $319.99 $379.99\n    price_std                                                                NaN\n    product_img                https://m.media-amazon.com/images/I/61XJCCT1mI...\n    filename                   ../data/input/search-selenium/5/50/50 inch sma...\n    fn                         ../data/input/selenium-products/6/6V/B086VR2KY...\n    title                      All-New Toshiba 50LF621U21 50-inch Smart 4K UH...\n    shipped_by                                                          Best Buy\n    sold_by                                                             Best Buy\n    has_third_party_sellers                                                False\n    product_by_amazon                                                      False\n    our_brands_carousel                                                    False\n    ads                                                                       []\n    no_buybox_winner                                                       False\n    is_out_of_stock                                                        False\n    is_page_gone                                                           False\n    suggestions                ['B086VR2KY8', 'B086VR2KY8', 'B086VR2KY8', 'B0...\n    n_ads                                                                      0\n    is_amazon                                                               True\n    is_sold_by_amazon                                                      False\n    is_shipped_by_amazon                                                   False\n    Name: 0, dtype: object\n\n\n\n\n```python\n_df_search[\"is_shipped_by_amazon_TRUE\"] = _df_search.apply(lambda x: any([x['is_shipped_by_amazon'], \n                                x['is_fresh'], x['is_prime']]), axis=1)\n```\n\n\n```python\nkw_generic = keywords[keywords['source'] == 'generic'].search_term\nkw_seller = keywords[keywords['source'] == 'seller'].search_term\nkw_autocomplete = keywords[keywords['source'].isin(\n    ['autocomplete amazon', 'autocomplete walmart']\n)].search_term\n```\n\n\n```python\ntop_searches = set(kw_autocomplete.tolist() + kw_seller.tolist())\nlen(top_searches)\n```\n\n\n\n\n    11342\n\n\n\n\n```python\ndf_top = _df_search[\n    _df_search.search_term.isin(top_searches)\n]\nlen(df_top), df_top.search_term.nunique()\n```\n\n\n\n\n    (187534, 3492)\n\n\n\n\n```python\n# how many searches had Amazon?\ndf_top.search_term.nunique() / len(top_searches)\n```\n\n\n\n\n    0.30788220772350555\n\n\n\n\n```python\n# how many products?\ndf_top.asin.nunique()\n```\n\n\n\n\n    125769\n\n\n\n\n```python\n# this is our main dataset\ndf = df_top\ndf.search_term.nunique()\n```\n\n\n\n\n    3492\n\n\n\n\n```python\n# this is the supplementary dataset\ndf_generic = _df_search[\n   _df_search.search_term.isin(kw_generic)\n]\nlen(df_generic), df_generic.search_term.nunique()\n```\n\n\n\n\n    (69287, 1217)\n\n\n\n\n```python\ndf = df[~(df.is_sponsored.isnull()) & \n   ~(df.is_sold_by_amazon.isnull()) &\n   ~(df.is_amazon.isnull())]\n```\n\n\n```python\nlen(df)\n```\n\n\n\n\n    187534\n\n\n\n\n```python\norganic= df[df.is_sponsored != True]\n```\n\n\n```python\nvals = {\n    'all results': len(df),\n    'sponsored' : len(df[df.is_sponsored == True]),\n    'organic': len(organic),\n    'sold by third party': len(organic[organic.is_sold_by_amazon != True]),\n    'sold by amazon': len( organic[organic.is_sold_by_amazon == True] ),\n    'amazon brand': len(organic[organic.asin.isin(amazon_asin)]),\n    'competing brand' : len(organic[~organic.asin.isin(amazon_asin)])\n}\n```\n\n## Produce plots\n\nOur analysis centered around comparing these two metrics:\n\n\\begin{align}\n{\\# 1\\ spot}_{Amazon} = \\frac{N_{Amazon\\ \\#1\\ slots}}{N_{\\#1\\ slots}}\n\\end{align}\n\n\\begin{align}\nproducts_{Amazon} = \\frac{N_{Amazon\\ product\\ slots}}{N_{product\\ slots}}\n\\end{align}\n\n\n```python\nres = calculate_table(df, amazon_asin)\nres\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Category</th>\n      <th>Perc Products</th>\n      <th>Perc #1 spot</th>\n      <th>Perc first row</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Unaffiliated</td>\n      <td>5.808547</td>\n      <td>4.209622</td>\n      <td>13.917526</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Amazon brands</td>\n      <td>5.801081</td>\n      <td>19.530355</td>\n      <td>24.770905</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Competing brands</td>\n      <td>76.880992</td>\n      <td>20.819015</td>\n      <td>63.516609</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Sponsored</td>\n      <td>17.317926</td>\n      <td>59.650630</td>\n      <td>75.286369</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Amazon sold</td>\n      <td>27.093220</td>\n      <td>22.451317</td>\n      <td>47.079038</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>Third-party sold</td>\n      <td>55.588853</td>\n      <td>17.898053</td>\n      <td>48.224513</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Amazon shipped</td>\n      <td>76.890591</td>\n      <td>38.459336</td>\n      <td>72.565865</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Third-party shipped</td>\n      <td>5.791483</td>\n      <td>1.890034</td>\n      <td>8.161512</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ncat2color = {\n    'Amazon brands' : \"#ff9900\",\n    'Competing brands' : \"#146eb4\",\n    'Sponsored': '#DB4437',\n    'Organic': '#ee7e6c',\n    'Amazon sold': '#146eb4',\n    'Third-party sold': '#aabedf',\n    'Unaffiliated': 'black',\n}\n\nmkr_dict = {\n    'Unaffiliated': {\n        'marker' : 'v',\n        'color': ''\n    },\n    'Competing brands': {\n        'marker' : 'o',\n        'color' : ''\n    }, \n    'Amazon sold' : {\n        'marker': '+',\n        'color' : ''\n    },\n    'Third-party sold': {\n        'marker': '+',\n        'color' : ''\n    },\n    'Amazon brands': {\n        'marker': 'o',\n        'color' : ''\n    },\n    'Sponsored' : {\n        'marker' : '*',\n        'color' : ''\n    },\n}\n```\n\n\n```python\ncats = [\n    'Sponsored',\n    'Amazon brands', \n    'Competing brands',\n    'Unaffiliated'\n]\nplt.figure(figsize=(8, 6))\nplt.title(\"What kind of products get the top search result on Amazon?\")\nax = plt.gca()\n\nto_plot = res[res.Category.isin(cats)]\nto_plot.to_csv(fig2_csv)\n\n# Hide the right and top spines\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\n\n# Only show ticks on the left and bottom spines\nax.yaxis.set_ticks_position('left')\nax.xaxis.set_ticks_position('bottom')\n\nax.set_ylabel('Percentage of top spots')\nax.set_xlabel('Percentage of products')\n\nax.set_ylim(0, 75)\nax.set_xlim(0, 80) \nax.yaxis.get_major_ticks()[0].label1.set_visible(False)\n\nfor kind in cats:\n    d = to_plot[to_plot.Category==kind]\n    if kind in ['Unaffiliated']:\n        ax.annotate(kind.title(), (d['Perc Products'] + 1.5,\n                       d['Perc #1 spot'] - 1.5))\n    elif kind == 'Competing brands':\n        ax.annotate(kind.title(), (d['Perc Products'] - 17.5,\n                       d['Perc #1 spot'] - 2))\n    else:\n        ax.annotate(kind.title(), (d['Perc Products'] + 1.6,\n                           d['Perc #1 spot']))\n    for j in range(1,6):\n        plt.scatter(x=d['Perc Products'],\n                    y=d['Perc #1 spot'],\n                    c=cat2color[kind],\n                    s=55,\n                    alpha=.2 * j,\n                    label=kind,\n                    marker = mkr_dict[kind]['marker'])\n\n            \nax.plot([0, 100], [0, 100],  '--', alpha=.4, color='grey')\nax.annotate(\"overrepresented\", \n            (52, 55), rotation=38)\nax.annotate(\"underrepresented\", \n            (54.5, 51), rotation=38)\n\nplt.savefig(fig2);\n```\n\n## Heatmap\n\n\n```python\ndef heatmap(df, control, cmap, title, vmin=0, vmax=100, fn_out=None):\n    \"\"\"Produces a heatmap of product slots\"\"\"\n    amzn_label = (df\n        .product_order.value_counts()\n        .sort_index()\n        .reindex(pd.RangeIndex(1, 61))[::-1])\n    amzn_label = amzn_label / control * 100\n    if fn_out:\n        amzn_label.to_csv(fn_out)\n        \n    amzn_label_grid = amzn_label.iloc[::-1].values.reshape(15, 4)\n    amzn_label_grid = pd.DataFrame(amzn_label_grid)\n    amzn_label_grid.index = [_ + 1 for _ in amzn_label_grid.index]\n    amzn_label_grid.columns = [_ + 1 for _ in amzn_label_grid.columns]\n\n    fig = plt.figure(figsize=(6,12))\n    sns.heatmap(amzn_label_grid,\n                linewidths=4,\n                fmt='g',\n                cmap=cmap,\n                vmin=vmax,\n                vmax=vmin)\n    plt.title(title)\n    plt.ylabel(\"\u27f5 Rows of products going down the page\")\n    plt.xlabel(\"Columns of products across the page\")\n    plt.yticks(rotation=0)\n    \n    return fig\n```\n\n\n```python\nn_samples = df.search_term.nunique()\n```\n\n\n```python\ndf_s = df[df.is_sponsored == True]\ndf_ns = df[df.is_sponsored == False]\n\ndf_non_amazon = df_ns[(~df_ns.asin.isin(amazon_asin))]\ndf_amazon_brand_ = df_ns[df_ns.asin.isin(amazon_asin)]\n\n\ndf_non_amazon_ = df_ns[\n    (~df_ns.asin.isin(amazon_asin))\n  & (df_ns.is_sold_by_amazon != True)\n  & (df_ns.is_shipped_by_amazon != True)\n  & (df_ns.is_prime != True) \n  & (df_ns.is_fresh != True)\n]\n```\n\n\n```python\ncontrol = (df.product_order.value_counts()\n    .sort_index()\n    .reindex(pd.RangeIndex(1, 61))[::-1])\n```\n\n\n```python\ncmap = LinearSegmentedColormap.from_list(\n    'mycmap', ['#f9f9f9', \"#ff9900\"]\n)\nfig = heatmap(\n    df_amazon_brand_, control,\n    cmap = LinearSegmentedColormap.from_list(None, ['#f9f9f9', \"#ff9900\"]),\n    title=f\"Where are Amazon Brands Placed\\nDown and Across the Search Page? (N={n_samples:,})\",\n    vmax=20, vmin=2, fn_out=fig3a_csv\n)\nfig.savefig(fig3a);\n```\n\n\n```python\nfig = heatmap(\n    df_non_amazon, control,\n    cmap = LinearSegmentedColormap.from_list(None, ['#f9f9f9', 'black']),\n    title=f\"Where are Competing Brands Placed\\nDown and Across the Search Page? (N={n_samples:,})\",\n)\n```\n\n\n```python\nfig = heatmap(\n    df_non_amazon_, control,\n    cmap = LinearSegmentedColormap.from_list(None, ['#f9f9f9', 'black']),\n    title=f\"Where are Entirely Unafilliated Products Placed\\nDown and Across the Search Page? (N={n_samples:,})\",\n    vmin=2, vmax=20, fn_out=fig3b_csv\n)\nfig.savefig(fig3b)\n```\n\n\n```python\nfig = heatmap(\n    df_s, control, \n    cmap=LinearSegmentedColormap.from_list(None, ['#f9f9f9', '#DB4437']),\n    title=f\"Where are Sponsored Products Placed\\nDown and Across the Search Page? (N={n_samples:,})\",\n    fn_out=fig3c_csv\n)\nfig.savefig(fig3c)\n```\n\n## Not Clearly Labelled\n\n\n```python\namazon_missed_all = '|'.join([\n    'amazon basics',\n    'amazonbasics',\n    'amazon essentials',\n    'whole foods market',\n    'amazon commercial',\n    'amazon collection',\n    'amazon fresh',\n    'amazon elements',\n    '365 everyday value',\n    'amazon exclusive',\n    'amazon us exclusive',\n    'amazon brand'\n])\n\namazon_missed = '|'.join([\n    'amazon basics',\n    'amazon essentials',\n    'whole foods market',\n    'amazon commercial',\n    'amazon collection',\n    'amazon fresh',\n    'amazon elements',\n    'amazonbasics',\n    '365 everyday value',\n])\n\namazon_disclaimer = '|'.join([\n    'amazon exclusive',\n    'amazon us exclusive',\n    'amazon brand'\n])\n```\n\n\n```python\n# How many products contain a disclaimer\ndisclaimer = (df[\n  ((df.is_featured_brand) | \n   (df.product_name.str.contains(amazon_disclaimer, case=False))) &\n  (df.asin.isin(amazon_asin))\n].asin.nunique() / \ndf[df.asin.isin(amazon_asin)].asin.nunique())\n\ndisclaimer\n```\n\n\n\n\n    0.4204641707606302\n\n\n\n\n```python\n# how many items contain a name with known brand\nknown_brand = (df[\n  (df.product_name.str.contains(amazon_missed, case=False)) &\n  (df.asin.isin(amazon_asin))\n].asin.nunique() / \ndf[df.asin.isin(amazon_asin)].asin.nunique())\n\nknown_brand\n```\n\n\n\n\n    0.2879891580552262\n\n\n\n\n```python\n# How many do not contain a disclaimer or well known brand?\nnot_labelled = 1 - (df[\n  ((df.product_name.str.contains(amazon_missed_all, case=False)) | \n   (df.is_featured_brand)) &\n  (df.asin.isin(amazon_asin))\n].asin.nunique() / \ndf[df.asin.isin(amazon_asin)].asin.nunique())\n\nnot_labelled\n```\n\n\n\n\n    0.37438590547179396\n\n\n\n\n```python\nt1 = pd.DataFrame([\n    {\"\" : \"Labelled with a Disclaimer\", \"percentage\": disclaimer * 100},\n    {\"\" : \"Well-Known Amazon private label\", \"percentage\": known_brand * 100},\n    {\"\" : \"Total Labelled\", \"percentage\": (1-not_labelled) * 100},\n    {\"\" : \"Total Unlabelled\", \"percentage\": not_labelled * 100},\n])\nt1 = t1.round(1)\nt1.to_csv(table1, index=False)\nt1\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>percentage</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Labelled with a Disclaimer</td>\n      <td>42.0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Well-Known Amazon private label</td>\n      <td>28.8</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Total Labelled</td>\n      <td>62.6</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Total Unlabelled</td>\n      <td>37.4</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# perc of top amazon products with a \"featured from our brands\" tag\n(df[\n    (df.is_featured_brand) &\n    (df.asin.isin(amazon_asin)) &\n    (df.product_order == 1)\n].search_term.nunique()) / df[(df.asin.isin(amazon_asin)) & (df.product_order == 1)].search_term.nunique()\n```\n\n\n\n\n    0.8387978142076503\n\n\n\n\n```python\n# perc of top \"featured from our brands\" products with \"sponsored\" metadata\n(df[\n    (df.is_featured_brand) &\n    (df.asin.isin(amazon_asin)) &\n    (df.product_order == 1) &\n    (df.has_sponsored_metadata == True)\n].search_term.nunique()) / \\\n(df[\n    (df.is_featured_brand) &\n    (df.asin.isin(amazon_asin)) &\n    (df.product_order == 1)\n].search_term.nunique())\n```\n\n\n\n\n    1.0\n\n\n\n## More Stars and reviews?\n\n\n```python\nif not os.path.exists(fn_compare):   \n    data = []\n    for st, _df in tqdm(df[df.is_sponsored == False].groupby(\"search_term\")):\n        _df.sort_values(by='product_order')\n        amzn = _df[_df.asin.isin(amazon_asin)]\n        non_amzn = _df[~_df.asin.isin(amazon_asin)]\n        wnon_amzn =_df[\n            (~_df.asin.isin(amazon_asin)) &\n            (_df.is_sold_by_amazon == False) &\n            (_df.is_fresh == False) &\n            (_df.is_prime == False)\n        ]\n\n        if not amzn.empty:\n            top_amazon =  amzn.product_order.iloc[0]\n            amazon_star = amzn.stars.iloc[0]\n            amazon_review = amzn.reviews.iloc[0]\n        else:\n            top_amazon = np.nan\n            amazon_star = np.nan\n            amazon_review = np.nan\n\n        if not non_amzn.empty:    \n            top_non_amazon_brand = non_amzn.product_order.iloc[0]\n            non_amazon_star = non_amzn.stars.iloc[0]\n            non_amazon_review = non_amzn.reviews.iloc[0]\n        else:\n            top_non_amazon = np.nan\n            non_amazon_star = np.nan\n            non_amazon_review = np.nan\n\n        if not wnon_amzn.empty:\n            top_wnon_amazon = wnon_amzn.product_order.iloc[0]\n            wnon_amazon_star = wnon_amzn.stars.iloc[0]\n            wnon_amazon_review = wnon_amzn.reviews.iloc[0]\n\n        else:\n            top_wnon_amazon = np.nan\n            wnon_amazon_star = np.nan\n            wnon_amazon_review = np.nan\n        record = {\n            \"search_term\": st,\n            \"position_first_amazon\": top_amazon,\n            \"position_first_non_amazon\": top_non_amazon_brand,\n            \"position_first_wholly_non_amazon\": top_wnon_amazon,\n\n            \"amazon_stars\": amazon_star,\n            \"amazon_reviews\": amazon_review,\n\n            \"non_amazon_stars\": non_amazon_star,\n            \"non_amazon_reviews\": non_amazon_review,\n\n            \"wnon_amazon_stars\": wnon_amazon_star,\n            \"wnon_amazon_reviews\": wnon_amazon_review,\n        }\n        data.append(record)\n    df_compare = pd.DataFrame(data)\n    df_compare.to_csv(fn_compare, index=False)\n    \nelse:\n    df_compare = pd.read_csv(fn_compare)\n```\n\n\n```python\n# how often is Amazon placed before non-Amazon? Should be close to one-in-five\nlen(df_compare[df_compare.position_first_amazon < df_compare.position_first_non_amazon]) / len(df_compare)\n```\n\n\n\n\n    0.22880870561282932\n\n\n\n\n```python\n# how many Amazon products have more stars?\ndf_compare[\n    df_compare.position_first_amazon < df_compare.position_first_non_amazon\n].apply(\n    lambda x:\n    x['amazon_stars'] > x['non_amazon_stars'],\n    axis=1\n).value_counts(normalize=True)\n```\n\n\n\n\n    False    0.653317\n    True     0.346683\n    dtype: float64\n\n\n\n\n```python\n# how many Amazon products have more reivews?\ndf_compare[\n    (df_compare.position_first_amazon < df_compare.position_first_non_amazon) &\n    (~df_compare.non_amazon_reviews.isnull())\n].apply(\n    lambda x:\n    x['amazon_reviews'] > x['non_amazon_reviews'],\n    axis=1\n).value_counts(normalize=True)\n```\n\n\n\n\n    False    0.517241\n    True     0.482759\n    dtype: float64\n\n\n\n\n```python\n# how many Amazon products have more reivews and stars?\ndf_compare[\n    (df_compare.position_first_amazon < df_compare.position_first_non_amazon) &\n    (~df_compare.non_amazon_reviews.isnull())\n].apply(\n    lambda x:\n    (x['amazon_reviews'] < x['non_amazon_reviews']) and \n    (x['amazon_stars'] < x['non_amazon_stars']),\n    axis=1\n).value_counts(normalize=True)\n```\n\n\n\n\n    False    0.720307\n    True     0.279693\n    dtype: float64\n\n\n\n\n```python\n# duplicates\nasins_by_search = df[df.is_sponsored == False].groupby('search_term').asin.value_counts()\n```\n\n\n```python\n# perc_searches_dupluicate_asin\nasins_by_search[asins_by_search > 1].index.get_level_values(0).nunique() / df.search_term.nunique()\n```\n\n\n\n\n    0.09221076746849943\n\n\n\n\n```python\n# how many of these duplicates are Amazon products?\nduplicate_asin = asins_by_search[asins_by_search > 1].index.get_level_values(1)\nlen([_ for _ in duplicate_asin if _ in amazon_asin]) / len(duplicate_asin)\n```\n\n\n\n\n    1.0\n\n\n\n## Supplementary dataset\n\n\n```python\ndf_generic.search_term.nunique()\n```\n\n\n\n\n    1217\n\n\n\n\n```python\ntable_generic = calculate_table(df_generic, amazon_asin)\ntable_generic\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Category</th>\n      <th>Perc Products</th>\n      <th>Perc #1 spot</th>\n      <th>Perc first row</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Unaffiliated</td>\n      <td>2.987573</td>\n      <td>1.479047</td>\n      <td>7.723911</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Amazon brands</td>\n      <td>8.225208</td>\n      <td>24.897288</td>\n      <td>35.332786</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Competing brands</td>\n      <td>73.530388</td>\n      <td>10.764174</td>\n      <td>54.478225</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Sponsored</td>\n      <td>18.244404</td>\n      <td>64.338537</td>\n      <td>84.223500</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Amazon sold</td>\n      <td>26.494148</td>\n      <td>23.336072</td>\n      <td>46.507806</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>Third-party sold</td>\n      <td>55.261449</td>\n      <td>12.325390</td>\n      <td>46.918652</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Amazon shipped</td>\n      <td>78.762250</td>\n      <td>34.921939</td>\n      <td>70.172555</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Third-party shipped</td>\n      <td>2.993347</td>\n      <td>0.739523</td>\n      <td>3.779786</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ntable_top = calculate_table(df_top, amazon_asin)\ntable_top\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Category</th>\n      <th>Perc Products</th>\n      <th>Perc #1 spot</th>\n      <th>Perc first row</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Unaffiliated</td>\n      <td>5.808547</td>\n      <td>4.209622</td>\n      <td>13.917526</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Amazon brands</td>\n      <td>5.801081</td>\n      <td>19.530355</td>\n      <td>24.770905</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Competing brands</td>\n      <td>76.880992</td>\n      <td>20.819015</td>\n      <td>63.516609</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Sponsored</td>\n      <td>17.317926</td>\n      <td>59.650630</td>\n      <td>75.286369</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Amazon sold</td>\n      <td>27.093220</td>\n      <td>22.451317</td>\n      <td>47.079038</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>Third-party sold</td>\n      <td>55.588853</td>\n      <td>17.898053</td>\n      <td>48.224513</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Amazon shipped</td>\n      <td>76.890591</td>\n      <td>38.459336</td>\n      <td>72.565865</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Third-party shipped</td>\n      <td>5.791483</td>\n      <td>1.890034</td>\n      <td>8.161512</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf[df.is_amazon == True].asin.nunique() / df[(df.product_order == 1) & (df.is_amazon == True)].search_term.nunique()\n```\n\n\n\n\n    8.064207650273223\n\n\n\n\n```python\ndf[df.is_amazon != True].asin.nunique() / df[(df.product_order == 1) & (df.is_amazon != True)].search_term.nunique()\n```\n\n\n\n\n    43.42971014492753\n\n\n\n\n```python\ndf[(df.product_order == 1) & (df.is_amazon == True)].search_term.nunique()\n```\n\n\n\n\n    732\n\n\n\n\n```python\ntable_diff = table_generic.set_index('Category').subtract(\n    table_top.set_index('Category'))\n```\n\n\n```python\ncomparison = pd.concat([\n    table_top[['Category', 'Perc Products',  'Perc #1 spot']].set_index('Category'), \n    table_generic[['Category','Perc Products',  'Perc #1 spot']].set_index('Category'),\n], axis=1, keys=[\"top\", \"generic\"])\n```\n\n\n```python\ncomparison\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n\n    .dataframe thead tr:last-of-type th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th colspan=\"2\" halign=\"left\">top</th>\n      <th colspan=\"2\" halign=\"left\">generic</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>Perc Products</th>\n      <th>Perc #1 spot</th>\n      <th>Perc Products</th>\n      <th>Perc #1 spot</th>\n    </tr>\n    <tr>\n      <th>Category</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Unaffiliated</th>\n      <td>5.808547</td>\n      <td>4.209622</td>\n      <td>2.987573</td>\n      <td>1.479047</td>\n    </tr>\n    <tr>\n      <th>Amazon brands</th>\n      <td>5.801081</td>\n      <td>19.530355</td>\n      <td>8.225208</td>\n      <td>24.897288</td>\n    </tr>\n    <tr>\n      <th>Competing brands</th>\n      <td>76.880992</td>\n      <td>20.819015</td>\n      <td>73.530388</td>\n      <td>10.764174</td>\n    </tr>\n    <tr>\n      <th>Sponsored</th>\n      <td>17.317926</td>\n      <td>59.650630</td>\n      <td>18.244404</td>\n      <td>64.338537</td>\n    </tr>\n    <tr>\n      <th>Amazon sold</th>\n      <td>27.093220</td>\n      <td>22.451317</td>\n      <td>26.494148</td>\n      <td>23.336072</td>\n    </tr>\n    <tr>\n      <th>Third-party sold</th>\n      <td>55.588853</td>\n      <td>17.898053</td>\n      <td>55.261449</td>\n      <td>12.325390</td>\n    </tr>\n    <tr>\n      <th>Amazon shipped</th>\n      <td>76.890591</td>\n      <td>38.459336</td>\n      <td>78.762250</td>\n      <td>34.921939</td>\n    </tr>\n    <tr>\n      <th>Third-party shipped</th>\n      <td>5.791483</td>\n      <td>1.890034</td>\n      <td>2.993347</td>\n      <td>0.739523</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# note some manual changes are made to this CSV file before it went into our article.\ncomparison.round(1).to_csv(table3)\n```\n\n## Anecdotes\n\n\n```python\n# how many Amazon products have more reivews and stars\ndf_compare[\"better_stars_and_reviews\"] = df_compare.apply(\n    lambda x:\n    (x['amazon_reviews'] < x['non_amazon_reviews']) and \n    (x['amazon_stars'] < x['non_amazon_stars']),\n    axis=1\n)\n```\n\n\n```python\ndf_compare[\n    (df_compare.position_first_amazon < df_compare.position_first_non_amazon) &\n    (~df_compare.non_amazon_reviews.isnull()) &\n    (df_compare[\"better_stars_and_reviews\"] == True) &\n    (df_compare['position_first_amazon'] == 1)\n].search_term.to_csv('amazon_winner_searches.csv', index=False)\n```\n\n## How many more Sponsored products would we have if we counted carousels?\n\n\n```python\ndf_carousels = df_search[~df_search.product_type.isin(['regular_placement'])]\ndf_carousels_ = df_carousels[df_carousels.search_term.isin(top_searches)]\n```\n\n\n```python\ndf_carousels_.product_type.value_counts()\n```\n\n\n\n\n    sponsored_banner             22923\n    editorial_recs_carousel      22797\n    featured_brands_carousel      8546\n    regular_placement__missed     4907\n    misc_carousel                 1859\n    misc_sponsored_carousel       1284\n    Name: product_type, dtype: int64\n\n\n\n\n```python\nsponsored_modules = [\n    'sponsored_banner',\n    'editorial_recs_carousel',\n    'misc_carousel',\n    'misc_sponsored_carousel'\n]\n\nnumerator = len(df_top[df_top.is_sponsored == True]) + len(df_carousels_[df_carousels_.product_type.isin(sponsored_modules) ])\ndenominator = len(df_top) + len(df_carousels_[df_carousels_.product_type != 'regular_placement__missed'])\nnumerator / denominator\n```\n\n\n\n\n    0.31910884411095186\n\n\n", "meta": {"hexsha": "c464ebbd74568f685781af17361c9790c776447c", "size": 192916, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/1-data-analysis-search-results.ipynb", "max_stars_repo_name": "the-markup/investigation-amazon-brands", "max_stars_repo_head_hexsha": "b5ceaff65b1185bb619a6e950b445a23524fae65", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2021-10-14T14:25:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T15:50:32.000Z", "max_issues_repo_path": "notebooks/1-data-analysis-search-results.ipynb", "max_issues_repo_name": "the-markup/investigation-amazon-brands", "max_issues_repo_head_hexsha": "b5ceaff65b1185bb619a6e950b445a23524fae65", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/1-data-analysis-search-results.ipynb", "max_forks_repo_name": "the-markup/investigation-amazon-brands", "max_forks_repo_head_hexsha": "b5ceaff65b1185bb619a6e950b445a23524fae65", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-10-15T16:27:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T21:12:37.000Z", "avg_line_length": 94.9857213195, "max_line_length": 36360, "alphanum_fraction": 0.8132347758, "converted": true, "num_tokens": 8744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771241500058, "lm_q2_score": 0.04146227271140963, "lm_q1q2_score": 0.01401744591899663}}
{"text": "```python\nfrom IPython.core.display import HTML\n```\n\n# Will's Lab-Books\n\n## Will Boulton wboulton12@gmail.com\n\n### 20 Sept. 2019\n\n## Blurb\n\nThese are a collection of notebooks mainly for my own documentation, as well as resources and also teaching. \nThe aim will ultimately be to put them into a format helpful for others. \n\n## Contents\n\n1) [How to set up a notebook like this one](https://www.digitalocean.com/community/tutorials/how-to-install-run-connect-to-jupyter-notebook-on-remote-server)\n\n2) More instructions on setting up Digital Ocean, and how to sync with Github and Google Drive\n\n3) How to spin up more resource in Digital Ocean, and how to set up a database\n\n4) A look at GCP, AirFlow, DataFlow, Apache Spark, Apache Beam, Kubernetes, Docker, Hadoop\n\n5) Setting up Java environments with Java and Maven and a Jenkins build system\n\n6) Running simulations and models in Biology, Physics and Chemistry etc\n\n7) Running web services\n\n8) Publishing these notes - https://nbviewer.jupyter.org/faq and https://jupyterhub.readthedocs.io/en/latest/ and \nhttps://mybinder.org/\n\n9) Notes about Java and Scala\n\n10) Node.js and React, as well as other frontend (data vis with Plotly)\n\n11) Machine learning in Python - web scraping, image processing, games, theory\n\n12) Reverse Engineering and security\n\n13) My Maths, coalgebra including $ (\\Delta, \\epsilon) \\in C$ material\n\n14) More maths, STEP preparation\n\n15) Even more maths, blog posts\n\n16) Computer science general\n\n**Here is a markdown example of Maxwell's equations.**\n\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\   \\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n\n\n```python\n%%html\n<style>\n html {\n    font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', 'Geneva', Verdana, sans-serif;\n}\n\nbody {\n    background-image: url('wm-processed1.jpg');\n    padding: 0px; \n    margin: 0px;\n    border: 0px;\n    height: 100%;\n}\n\n\n/* --- Header --- */\n\n.header {\n    padding: 60px;\n    text-align: center;\n    background: #efefef;\n    color: black;\n    font-size: 30px;\n    opacity: 1;\n}\n\n\n/* --- panel area --- */\n\n.panel-background {\n    display: flex;\n    flex-wrap: wrap;\n    height: 100%;\n}\n\n.panel-left {\n  background-color: #ffffff;\n  opacity: 0;\n  flex: 10%; /* Set the width of the transparency */\n  padding: 0px; \n  margin: 0px;\n  border: 0px;\n}\n\n.panel-main {\n    flex: 80%;\n    background-color: #efefef;\n    padding: 0px; \n    margin: 0px;\n    border: 0px;\n    height: 100%;\n}\n\n.panel-right {\n    background-color: #ffffff;\n    opacity: 0;\n    flex: 10%; /* Set the width of the transparency */\n    padding: 0px; \n    margin: 0px;\n    border: 0px;\n}\n\n\n/* --- Navbar --- */\n\n/* Add a black background color to the top navigation */\n.topnav {\n  position: relative;\n  background-color: #efefef;\n  color: black;\n  overflow: hidden;\n}\n\n/* Style the links inside the navigation bar */\n.topnav a {\n  float: left;\n  text-align: center;\n  padding: 16px;\n  text-decoration: none;\n  font-size: 17px;\n  color: black;\n}\n\n/* Change the color of links on hover */\n.topnav a:hover {\n  text-decoration: underline;\n  color: black;\n}\n\n/* Add a color to the active/current link */\n.topnav a.active {\n  text-decoration: underline;\n  color: black;\n}\n\n/* Centered section inside the top navigation */\n.topnav-centered div {\n  float: none;\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  transform: translate(-50%, -50%);\n  color: black;\n}\n\n/* Right-aligned section inside the top navigation */\n.topnav-right {\n  float: right;\n  color: black;\n}\n\n/* Responsive navigation menu - display links on top of each other instead of next to each other (for mobile devices) */\n@media screen and (max-width: 600px) {\n  .topnav a, .topnav-right {\n    float: none;\n    display: block;\n    color: black;\n  }\n\n  .topnav-centered a {\n    position: relative;\n    top: 0;\n    left: 0;\n    transform: none;\n    color: black;\n  }\n}\n\n\n/*\n\n.topnav {\n    background-color: #efefef;\n    overflow: hidden;\n    font-size: 16;\n    text-align: center;\n}\n\n/* Style the links inside the navigation bar *//*\n.topnav a {\n  float: left;\n  color: black;\n  text-align: center;\n  padding: 14px 16px;\n  text-decoration: none;\n  font-size: 17px;\n}\n\n.topnav a:hover {\n  text-decoration: underline;;\n}\n\n/* Add a underline to the currently active link *//*\n.topnav a.active {\n  text-underline-position: below;\n}\n*/\n\n.content {\n  border:10px;\n  margin:10px;\n  padding: 0px;\n}\n</style>\n```\n\n\n<style>\n html {\n    font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', 'Geneva', Verdana, sans-serif;\n}\n\nbody {\n    background-image: url('wm-processed1.jpg');\n    padding: 0px; \n    margin: 0px;\n    border: 0px;\n    height: 100%;\n}\n\n\n/* --- Header --- */\n\n.header {\n    padding: 60px;\n    text-align: center;\n    background: #efefef;\n    color: black;\n    font-size: 30px;\n    opacity: 1;\n}\n\n\n/* --- panel area --- */\n\n.panel-background {\n    display: flex;\n    flex-wrap: wrap;\n    height: 100%;\n}\n\n.panel-left {\n  background-color: #ffffff;\n  opacity: 0;\n  flex: 10%; /* Set the width of the transparency */\n  padding: 0px; \n  margin: 0px;\n  border: 0px;\n}\n\n.panel-main {\n    flex: 80%;\n    background-color: #efefef;\n    padding: 0px; \n    margin: 0px;\n    border: 0px;\n    height: 100%;\n}\n\n.panel-right {\n    background-color: #ffffff;\n    opacity: 0;\n    flex: 10%; /* Set the width of the transparency */\n    padding: 0px; \n    margin: 0px;\n    border: 0px;\n}\n\n\n/* --- Navbar --- */\n\n/* Add a black background color to the top navigation */\n.topnav {\n  position: relative;\n  background-color: #efefef;\n  color: black;\n  overflow: hidden;\n}\n\n/* Style the links inside the navigation bar */\n.topnav a {\n  float: left;\n  text-align: center;\n  padding: 16px;\n  text-decoration: none;\n  font-size: 17px;\n  color: black;\n}\n\n/* Change the color of links on hover */\n.topnav a:hover {\n  text-decoration: underline;\n  color: black;\n}\n\n/* Add a color to the active/current link */\n.topnav a.active {\n  text-decoration: underline;\n  color: black;\n}\n\n/* Centered section inside the top navigation */\n.topnav-centered div {\n  float: none;\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  transform: translate(-50%, -50%);\n  color: black;\n}\n\n/* Right-aligned section inside the top navigation */\n.topnav-right {\n  float: right;\n  color: black;\n}\n\n/* Responsive navigation menu - display links on top of each other instead of next to each other (for mobile devices) */\n@media screen and (max-width: 600px) {\n  .topnav a, .topnav-right {\n    float: none;\n    display: block;\n    color: black;\n  }\n\n  .topnav-centered a {\n    position: relative;\n    top: 0;\n    left: 0;\n    transform: none;\n    color: black;\n  }\n}\n\n\n/*\n\n.topnav {\n    background-color: #efefef;\n    overflow: hidden;\n    font-size: 16;\n    text-align: center;\n}\n\n/* Style the links inside the navigation bar *//*\n.topnav a {\n  float: left;\n  color: black;\n  text-align: center;\n  padding: 14px 16px;\n  text-decoration: none;\n  font-size: 17px;\n}\n\n.topnav a:hover {\n  text-decoration: underline;;\n}\n\n/* Add a underline to the currently active link *//*\n.topnav a.active {\n  text-underline-position: below;\n}\n*/\n\n.content {\n  border:10px;\n  margin:10px;\n  padding: 0px;\n}\n</style>\n\n\n\n# blah blah blah \n\n\n```python\n\n```\n", "meta": {"hexsha": "e8572e2822213874758c27f473f3813f45088621", "size": 12611, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "posts/wip/my_labbooks.ipynb", "max_stars_repo_name": "willboulton/blog", "max_stars_repo_head_hexsha": "304946d1e9c7edcf7a9af684e7fb27b6fb546153", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "posts/wip/my_labbooks.ipynb", "max_issues_repo_name": "willboulton/blog", "max_issues_repo_head_hexsha": "304946d1e9c7edcf7a9af684e7fb27b6fb546153", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "posts/wip/my_labbooks.ipynb", "max_forks_repo_name": "willboulton/blog", "max_forks_repo_head_hexsha": "304946d1e9c7edcf7a9af684e7fb27b6fb546153", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4152173913, "max_line_length": 211, "alphanum_fraction": 0.4581714376, "converted": true, "num_tokens": 2127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12252321892633071, "lm_q2_score": 0.11436853523769844, "lm_q1q2_score": 0.014012801081212294}}
{"text": "```python\nimport glob\nimport pandas as pd\nimport gzip\nimport numpy as np\nfrom sympy import *\nfrom sympy import roots, solve_poly_system\nimport sys\n```\n\n\n```python\neCAVIAR_directory = 'ukbb_height_conditioned/eCAVIAR/'\ntissue = 'Muscle_Skeletal/'\n\nLD_directory = '/net/data/GTEx/ukbb_ld/'\nzfile_directory = '/net/data/GTEx/gwas/' + eCAVIAR_directory + 'eCAVIAR_zscore/' + tissue\neC_LD_directory = '/net/data/GTEx/gwas/' + eCAVIAR_directory + 'LD/' + tissue\noutput_directory = '/net/data/GTEx/gwas/' + eCAVIAR_directory + 'eCAVIAR_output/' + tissue\n\nprint(zfile_directory)\n\n# zfiles = glob.glob(zfile_directory + '*.Z')\nLDfiles = glob.glob(eC_LD_directory + '*.LD')\noutputs = glob.glob(output_directory + '*_col')\n\nLDfiles_split = [x.split(\"/\")[-1][0:-3] for x in LDfiles]\nLDfiles_split = set(LDfiles_split)\n\noutputs_split = [x.split(\"/\")[-1][3:-4] for x in outputs]\noutputs_split = set(outputs_split)\n\nmissing = list(LDfiles_split - outputs_split)\n\nlen(missing)\n```\n\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/\n\n\n\n\n\n    1938\n\n\n\n\n```python\nlocation = [x.split(\"_\")[1] for x in missing]\nchr_list = [x.split(\"_\")[0] for x in missing]\n\ndata = {'chr': chr_list, 'location': location, \"filenames\":  missing}\nzfile_df = pd.DataFrame(data)\n```\n\n\n```python\n#form the location_names, get the LD file names\ndef round_down(x):\n    x = int(x)\n    x -= x % 1000000\n    return(x)\n```\n\n\n```python\nresult = [round_down(x) for x in zfile_df['location']]\n\nLD_filenames = [str(i + 1) + '_' + str(i + 3000001) for i in result]\nzfile_df[\"LD_filename\"] = LD_filenames\nzfile_df['LD_filename']=zfile_df[['chr','LD_filename']].values.tolist()\nzfile_df['LD_filename']=zfile_df['LD_filename'].apply('_'.join)\nzfile_df['LD_filename'] = 'chr' + zfile_df['LD_filename'].astype(str)\n```\n\n\n```python\nold_LDfilename = ''\n\nfor index, row in zfile_df.iterrows():\n\n    #load zfile\n    zscore_file_name = zfile_directory + 'eqtl_' + row['filenames'] + '.Z'\n    z_file = pd.read_csv(zscore_file_name , sep= '\\t', names = [\"name\", \"zscore\"])\n\n    print(zscore_file_name)\n    \n    if len(z_file) == 0:\n        continue\n\n    #add chromosome and position column to zscore dataframe\n    variant_id = z_file[\"name\"].str.split(\"_\", n = 4, expand = True)\n    z_file[\"chromosome\"] = variant_id[0]\n    z_file[\"position\"] = variant_id[1].astype(int)\n    z_file[\"major_allele\"] = variant_id[2]\n    z_file[\"minor_allele\"] = variant_id[3]\n    \n    #drop duplicates\n    z_file = z_file.drop_duplicates(subset=['position'])\n    z_file[[\"name\", \"zscore\"]].to_csv(zscore_file_name,index = False, header = None, sep='\\t')\n    \n    print(len(z_file))\n\n    #do the same for gwas\n    gwas_zscore_file_name = zfile_directory + 'gwas_' + zscore_file_name.split(\"/\")[-1][5:-2] + '.Z'\n    gwas_z_file = pd.read_csv(gwas_zscore_file_name , sep= '\\t', names = [\"name\", \"zscore\"])\n\n    variant_id = gwas_z_file[\"name\"].str.split(\"_\", n = 4, expand = True)\n    gwas_z_file[\"position\"] = variant_id[1].astype(int)\n    \n    gwas_z_file = gwas_z_file.drop_duplicates(subset=['position'])\n    gwas_z_file[[\"name\", \"zscore\"]].to_csv(gwas_zscore_file_name,index = False, header = None, sep='\\t')\n    \n    print(len(gwas_z_file))\n```\n\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000268093.1.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000165898.9.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000131779.6.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_102007617_ENSG00000154227.9.Z\n    1116\n    1116\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000235706.3.Z\n    910\n    910\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_101198609_ENSG00000197406.6.Z\n    847\n    847\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_52053017_ENSG00000078618.15.Z\n    507\n    507\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_68415513_ENSG00000160172.6.Z\n    669\n    669\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_143618626_ENSG00000010818.4.Z\n    648\n    648\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_19839415_ENSG00000112242.10.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000129559.8.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_89623396_ENSG00000135052.12.Z\n    793\n    793\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_42468139_ENSG00000181513.10.Z\n    430\n    430\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_143618626_ENSG00000270890.1.Z\n    648\n    648\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_94783438_ENSG00000120833.9.Z\n    506\n    506\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_76746325_ENSG00000087157.14.Z\n    597\n    597\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000175575.8.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_100660989_ENSG00000154227.9.Z\n    1385\n    1385\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_101198609_ENSG00000258498.2.Z\n    847\n    847\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_128789886_ENSG00000206417.4.Z\n    409\n    409\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_141121814_ENSG00000114124.2.Z\n    559\n    559\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_143618626_ENSG00000146416.12.Z\n    648\n    648\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000204237.4.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_57020767_ENSG00000197951.4.Z\n    740\n    740\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000257298.1.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_109723017_ENSG00000260273.1.Z\n    721\n    721\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000024422.7.Z\n    910\n    910\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000108306.7.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000254647.2.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_396321_ENSG00000137265.10.Z\n    879\n    879\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000198208.7.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000135436.4.Z\n    450\n    450\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_8_9104590_ENSG00000253230.2.Z\n    1090\n    1090\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_33836942_ENSG00000239670.1.Z\n    630\n    630\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_13_33101817_ENSG00000133116.6.Z\n    481\n    481\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000129245.7.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000259065.1.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000198483.8.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000169718.13.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_105477990_ENSG00000184887.9.Z\n    791\n    791\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_101198609_ENSG00000258666.1.Z\n    847\n    847\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000150967.13.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000143320.4.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_56350306_ENSG00000143947.8.Z\n    823\n    823\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_109723017_ENSG00000118689.10.Z\n    721\n    721\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000160783.15.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000265692.1.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000264954.1.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_218604987_ENSG00000135929.4.Z\n    227\n    227\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_94783438_ENSG00000136040.4.Z\n    506\n    506\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_102007617_ENSG00000270127.1.Z\n    1141\n    1141\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000149273.10.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000182459.4.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000214826.4.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_56666502_ENSG00000239801.1.Z\n    702\n    702\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000154222.10.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000272849.1.Z\n    768\n    768\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000119725.13.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000167914.6.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000108352.7.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000159882.8.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_98830472_ENSG00000231861.1.Z\n    1116\n    1116\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_77061989_ENSG00000140391.10.Z\n    474\n    474\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_77654536_ENSG00000175183.5.Z\n    830\n    830\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000204261.4.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000266921.1.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000178028.9.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000119630.9.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_8_9104590_ENSG00000173295.3.Z\n    344\n    344\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000160753.11.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_100660989_ENSG00000259475.1.Z\n    679\n    679\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000100450.8.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_102900041_ENSG00000120860.6.Z\n    603\n    603\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000254986.3.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000174996.7.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_56666502_ENSG00000157500.6.Z\n    934\n    934\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000261829.1.Z\n    621\n    621\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_169238015_ENSG00000173889.11.Z\n    790\n    790\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000008838.13.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000100448.3.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000089737.11.Z\n    910\n    910\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_13_33101817_ENSG00000236581.4.Z\n    481\n    481\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_219311515_ENSG00000127837.5.Z\n    515\n    515\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_76746325_ENSG00000167895.10.Z\n    597\n    597\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_132604195_ENSG00000184967.2.Z\n    715\n    715\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000179859.7.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000119681.7.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_8_9104590_ENSG00000248538.2.Z\n    1090\n    1090\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000160867.10.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000224183.1.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_33328703_ENSG00000113407.9.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000162384.9.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000174326.7.Z\n    96\n    96\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_99428825_ENSG00000182150.11.Z\n    537\n    537\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000100908.9.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000100445.12.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000117419.10.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000175899.10.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_126702792_ENSG00000148200.12.Z\n    658\n    658\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000156973.9.Z\n    621\n    621\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_77654536_ENSG00000257526.1.Z\n    830\n    830\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_39794732_ENSG00000258940.2.Z\n    741\n    741\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_33328703_ENSG00000249572.1.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_55803533_ENSG00000062194.11.Z\n    1052\n    1052\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000149806.6.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000133226.12.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_105973373_ENSG00000211897.3.Z\n    667\n    667\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_67584758_ENSG00000134056.7.Z\n    499\n    499\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_37144516_ENSG00000183032.6.Z\n    746\n    746\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000168778.7.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_364679_ENSG00000139044.6.Z\n    936\n    936\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_18_20490872_ENSG00000154065.12.Z\n    505\n    505\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000105486.9.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_70338344_ENSG00000144043.7.Z\n    480\n    480\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000181222.10.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_46914082_ENSG00000226087.1.Z\n    820\n    820\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_78511889_ENSG00000156017.8.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_99428825_ENSG00000130958.7.Z\n    537\n    537\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_100660989_ENSG00000270127.1.Z\n    1385\n    1385\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_42468139_ENSG00000186834.2.Z\n    430\n    430\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000020633.14.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_5016883_ENSG00000168826.11.Z\n    1037\n    1037\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_37760395_ENSG00000003509.11.Z\n    825\n    825\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_99428825_ENSG00000136943.6.Z\n    537\n    537\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000136367.12.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000254837.1.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000174332.3.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_23896049_ENSG00000186453.8.Z\n    769\n    769\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_77654536_ENSG00000067798.9.Z\n    830\n    830\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_98017999_ENSG00000158169.7.Z\n    283\n    283\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000198231.8.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_99428825_ENSG00000224546.2.Z\n    537\n    537\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_123258997_ENSG00000033030.9.Z\n    759\n    759\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000157077.10.Z\n    729\n    729\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_109723017_ENSG00000112365.4.Z\n    721\n    721\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000254510.1.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000258944.1.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000172757.8.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_48729030_ENSG00000128951.9.Z\n    601\n    601\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101698540_ENSG00000259381.2.Z\n    981\n    981\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000111325.12.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_39794732_ENSG00000165355.7.Z\n    741\n    741\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_4740251_ENSG00000226669.2.Z\n    334\n    334\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000168394.9.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_130168548_ENSG00000186687.11.Z\n    495\n    495\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000198055.6.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000170043.7.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_38606933_ENSG00000109790.12.Z\n    710\n    710\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000268108.1.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_141121814_ENSG00000248773.1.Z\n    559\n    559\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121756084_ENSG00000170633.12.Z\n    736\n    736\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_94783438_ENSG00000258274.1.Z\n    506\n    506\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_70338344_ENSG00000087338.4.Z\n    480\n    480\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_113490243_ENSG00000136813.10.Z\n    831\n    831\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_227046655_ENSG00000272622.1.Z\n    768\n    768\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_102900041_ENSG00000139351.10.Z\n    603\n    603\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_100660989_ENSG00000183475.8.Z\n    1385\n    1385\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_55803533_ENSG00000271828.1.Z\n    1052\n    1052\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000226711.2.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000205544.3.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000135902.5.Z\n    621\n    621\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_77654536_ENSG00000257219.1.Z\n    454\n    454\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_109643880_ENSG00000234323.1.Z\n    461\n    461\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000074317.6.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_45239959_ENSG00000254519.1.Z\n    591\n    591\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000225643.1.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000160752.10.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101698540_ENSG00000185418.11.Z\n    981\n    981\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_82945613_ENSG00000112773.11.Z\n    584\n    584\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000182782.7.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_65696801_ENSG00000183735.5.Z\n    471\n    471\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_128789886_ENSG00000172765.12.Z\n    409\n    409\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_89623396_ENSG00000269994.1.Z\n    834\n    834\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101038100_ENSG00000131871.10.Z\n    1181\n    1181\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000160803.7.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_65696801_ENSG00000155957.12.Z\n    471\n    471\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_396321_ENSG00000112679.10.Z\n    879\n    879\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_92230041_ENSG00000187742.10.Z\n    1062\n    1062\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_23896049_ENSG00000119778.10.Z\n    769\n    769\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_146045768_ENSG00000248890.1.Z\n    238\n    238\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000162383.7.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_10199601_ENSG00000119185.8.Z\n    901\n    901\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000204304.7.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000182324.5.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_5016883_ENSG00000152953.8.Z\n    1037\n    1037\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_106325900_ENSG00000138785.10.Z\n    1040\n    1040\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000167378.4.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000258987.1.Z\n    910\n    910\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_99827531_ENSG00000146834.9.Z\n    438\n    438\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_98445632_ENSG00000271659.1.Z\n    940\n    940\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_396321_ENSG00000272485.1.Z\n    879\n    879\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_4740251_ENSG00000205808.4.Z\n    1159\n    1159\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_41405317_ENSG00000103966.5.Z\n    559\n    559\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000213906.5.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000169230.5.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000117862.7.Z\n    240\n    240\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000174327.6.Z\n    59\n    59\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_238400036_ENSG00000225057.2.Z\n    1106\n    1106\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_38606933_ENSG00000174125.3.Z\n    710\n    710\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_143618626_ENSG00000229017.2.Z\n    648\n    648\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_56666502_ENSG00000174840.8.Z\n    934\n    934\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_82945613_ENSG00000005700.10.Z\n    584\n    584\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000176903.3.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000131771.9.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_56350306_ENSG00000233251.3.Z\n    823\n    823\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000261827.1.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000166166.8.Z\n    563\n    563\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_177587709_ENSG00000242193.5.Z\n    520\n    520\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000087365.10.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_364679_ENSG00000250132.2.Z\n    936\n    936\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_12784335_ENSG00000123144.6.Z\n    522\n    522\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_169706079_ENSG00000138385.11.Z\n    560\n    560\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_90113307_ENSG00000176055.9.Z\n    629\n    629\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_90873653_ENSG00000156345.13.Z\n    1073\n    1073\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_101198609_ENSG00000036530.4.Z\n    227\n    227\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_57522257_ENSG00000155980.7.Z\n    436\n    436\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_218604987_ENSG00000144580.9.Z\n    727\n    727\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000214026.6.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_83415167_ENSG00000196781.9.Z\n    1011\n    1011\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101038100_ENSG00000183060.11.Z\n    1181\n    1181\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_70338344_ENSG00000143977.9.Z\n    480\n    480\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000139722.2.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_76746325_ENSG00000078687.12.Z\n    597\n    597\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_105973373_ENSG00000253755.1.Z\n    667\n    667\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000110844.9.Z\n    367\n    367\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_70338344_ENSG00000272735.1.Z\n    357\n    357\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000050405.9.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000169738.3.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_45239959_ENSG00000135365.11.Z\n    581\n    581\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000179111.4.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000169683.3.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000266208.1.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000100697.10.Z\n    910\n    910\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_92257602_ENSG00000001630.11.Z\n    410\n    410\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000188396.2.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000111752.6.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000126391.9.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_55803533_ENSG00000164509.9.Z\n    1052\n    1052\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000142945.8.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_79934194_ENSG00000157637.8.Z\n    589\n    589\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000104870.8.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000116604.13.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000178104.15.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000146066.2.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_82945613_ENSG00000013392.6.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000182500.7.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000259431.1.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_84226540_ENSG00000196781.9.Z\n    758\n    758\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000168509.13.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000235423.4.Z\n    480\n    480\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000130529.11.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101038100_ENSG00000140470.9.Z\n    1181\n    1181\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000204178.5.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_66318629_ENSG00000273142.1.Z\n    562\n    562\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_89397827_ENSG00000271997.1.Z\n    918\n    918\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000135930.9.Z\n    621\n    621\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000213465.3.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_49568181_ENSG00000114353.12.Z\n    375\n    375\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_227955276_ENSG00000163050.12.Z\n    624\n    624\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_101198609_ENSG00000176473.9.Z\n    847\n    847\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000206150.3.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_123258997_ENSG00000168778.7.Z\n    759\n    759\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_109643880_ENSG00000148143.8.Z\n    461\n    461\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000111011.13.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_45635239_ENSG00000108465.10.Z\n    463\n    463\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_23896049_ENSG00000163026.7.Z\n    769\n    769\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000175581.9.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000223380.3.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_102007617_ENSG00000185596.12.Z\n    1214\n    1214\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000143314.8.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000173825.6.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_13_33101817_ENSG00000083642.14.Z\n    481\n    481\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_75595747_ENSG00000260274.1.Z\n    297\n    297\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_89216425_ENSG00000214391.3.Z\n    641\n    641\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000213588.4.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000174807.3.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_76746325_ENSG00000267737.1.Z\n    597\n    597\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_100660989_ENSG00000183060.11.Z\n    1385\n    1385\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_95350518_ENSG00000186280.5.Z\n    773\n    773\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_76746325_ENSG00000055483.15.Z\n    597\n    597\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_238400036_ENSG00000144476.5.Z\n    933\n    933\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000226871.1.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000087076.4.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000227615.1.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000238184.1.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_46577056_ENSG00000164742.10.Z\n    546\n    546\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000022840.11.Z\n    779\n    779\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_101198609_ENSG00000066629.12.Z\n    442\n    442\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_75595747_ENSG00000260685.1.Z\n    297\n    297\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000188672.12.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000104848.1.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_89840457_ENSG00000204446.2.Z\n    773\n    773\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000182183.10.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101698540_ENSG00000184254.12.Z\n    981\n    981\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_23896049_ENSG00000176732.6.Z\n    769\n    769\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_102706023_ENSG00000145723.12.Z\n    408\n    408\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_45635239_ENSG00000263412.1.Z\n    463\n    463\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000105755.3.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000184047.11.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000167383.4.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000175334.3.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000215769.4.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000108298.5.Z\n    236\n    236\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_98445632_ENSG00000158169.7.Z\n    940\n    940\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000165953.5.Z\n    910\n    910\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_169338671_ENSG00000184465.11.Z\n    1298\n    1298\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000262663.1.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_20588382_ENSG00000111711.5.Z\n    108\n    108\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000174165.3.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000170089.11.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_172197790_ENSG00000120129.5.Z\n    887\n    887\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_105973373_ENSG00000184887.9.Z\n    667\n    667\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_66318629_ENSG00000223473.1.Z\n    562\n    562\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000204120.10.Z\n    621\n    621\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000269997.1.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_45239959_ENSG00000052850.5.Z\n    555\n    555\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000161955.12.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_218604987_ENSG00000272555.1.Z\n    64\n    64\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_98445632_ENSG00000271384.1.Z\n    940\n    940\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_138923562_ENSG00000120727.8.Z\n    346\n    346\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_238400036_ENSG00000227107.1.Z\n    1106\n    1106\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_89397827_ENSG00000140522.7.Z\n    918\n    918\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000269958.1.Z\n    563\n    563\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000163374.15.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_102007617_ENSG00000154237.8.Z\n    1214\n    1214\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_70338344_ENSG00000169564.5.Z\n    480\n    480\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232328681_ENSG00000163273.3.Z\n    771\n    771\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_105973373_ENSG00000203485.8.Z\n    667\n    667\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000066735.10.Z\n    563\n    563\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000131188.7.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_98830472_ENSG00000168386.14.Z\n    458\n    458\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000239697.6.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_89397827_ENSG00000173867.8.Z\n    918\n    918\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000175550.3.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000168062.5.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000174871.6.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000246203.2.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_17505933_ENSG00000214046.4.Z\n    822\n    822\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_76746325_ENSG00000183077.11.Z\n    597\n    597\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000234465.6.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000146094.9.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232328681_ENSG00000115053.11.Z\n    771\n    771\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_61018091_ENSG00000108604.11.Z\n    598\n    598\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000255967.1.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_2155042_ENSG00000267493.2.Z\n    795\n    795\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_89397827_ENSG00000140511.7.Z\n    918\n    918\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000072818.7.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000126460.6.Z\n    577\n    577\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_238400036_ENSG00000144488.10.Z\n    1106\n    1106\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000259005.1.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000119723.11.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000136319.7.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_3098321_ENSG00000125388.15.Z\n    702\n    702\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000175564.8.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_67584758_ENSG00000134057.10.Z\n    591\n    591\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_33328703_ENSG00000240376.1.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000142552.3.Z\n    894\n    894\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_65815254_ENSG00000251451.1.Z\n    476\n    476\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000262814.2.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_123258997_ENSG00000111358.9.Z\n    759\n    759\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_89397827_ENSG00000166823.5.Z\n    918\n    918\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_8670147_ENSG00000267106.1.Z\n    103\n    103\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000256069.3.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_128789886_ENSG00000179348.7.Z\n    409\n    409\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_42468139_ENSG00000267278.1.Z\n    430\n    430\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000132676.11.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_143618626_ENSG00000112419.10.Z\n    648\n    648\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000090554.8.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000142546.9.Z\n    502\n    502\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_66318629_ENSG00000106609.12.Z\n    562\n    562\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_45239959_ENSG00000085117.7.Z\n    591\n    591\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000170074.15.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_151068398_ENSG00000143387.8.Z\n    546\n    546\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_45239959_ENSG00000181830.7.Z\n    591\n    591\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_52053017_ENSG00000230585.2.Z\n    507\n    507\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000001461.12.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_95350518_ENSG00000077458.8.Z\n    773\n    773\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_1986972_ENSG00000127415.8.Z\n    150\n    150\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_13_33101817_ENSG00000139597.12.Z\n    481\n    481\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_38606933_ENSG00000109787.8.Z\n    710\n    710\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_98863749_ENSG00000228335.1.Z\n    691\n    691\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_142961373_ENSG00000227192.1.Z\n    752\n    752\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000126838.5.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_99428825_ENSG00000136842.9.Z\n    537\n    537\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_4740251_ENSG00000273061.1.Z\n    1159\n    1159\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_48729030_ENSG00000156958.10.Z\n    601\n    601\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_23425139_ENSG00000142676.8.Z\n    451\n    451\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_364679_ENSG00000082805.15.Z\n    936\n    936\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_141121814_ENSG00000175093.4.Z\n    559\n    559\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000272368.1.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000159588.10.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_67584758_ENSG00000249721.1.Z\n    591\n    591\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_20588382_ENSG00000004700.11.Z\n    108\n    108\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_73108402_ENSG00000182487.8.Z\n    584\n    584\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101698540_ENSG00000185596.12.Z\n    981\n    981\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232328681_ENSG00000173692.8.Z\n    771\n    771\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000175414.6.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000175294.5.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000213240.7.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000139187.5.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000139624.8.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000142677.3.Z\n    840\n    840\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_90873653_ENSG00000135047.10.Z\n    1073\n    1073\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_103909280_ENSG00000156381.4.Z\n    546\n    546\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_66318629_ENSG00000232546.1.Z\n    562\n    562\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_102007617_ENSG00000259205.2.Z\n    1171\n    1171\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000141499.12.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000142937.7.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000237441.5.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000204220.5.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000184619.3.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000226763.3.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_53463972_ENSG00000180806.4.Z\n    483\n    483\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000040633.8.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000163386.16.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000176531.6.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_45239959_ENSG00000157570.7.Z\n    591\n    591\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_5016883_ENSG00000163132.6.Z\n    1037\n    1037\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000136478.3.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000156050.4.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_70338344_ENSG00000244617.1.Z\n    480\n    480\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_5016883_ENSG00000168824.10.Z\n    1037\n    1037\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_126702792_ENSG00000224020.1.Z\n    658\n    658\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_132604195_ENSG00000072609.13.Z\n    715\n    715\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000108588.9.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000116157.5.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000215041.5.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_75595747_ENSG00000173546.7.Z\n    297\n    297\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_19839415_ENSG00000172197.9.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000238084.3.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_102706023_ENSG00000175749.11.Z\n    408\n    408\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000251667.1.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_65815254_ENSG00000273142.1.Z\n    476\n    476\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_41405317_ENSG00000128917.5.Z\n    559\n    559\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000130787.9.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000174791.6.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_78801332_ENSG00000106772.13.Z\n    850\n    850\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000006047.8.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_76746325_ENSG00000204282.3.Z\n    597\n    597\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000198952.7.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_55803533_ENSG00000095015.5.Z\n    1052\n    1052\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000259775.1.Z\n    563\n    563\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_82945613_ENSG00000083097.10.Z\n    584\n    584\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_218604987_ENSG00000118245.2.Z\n    727\n    727\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_169338671_ENSG00000232640.1.Z\n    1297\n    1297\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_56350306_ENSG00000115380.14.Z\n    823\n    823\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101038100_ENSG00000259583.1.Z\n    1181\n    1181\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000242252.1.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000237412.2.Z\n    621\n    621\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_99428825_ENSG00000081386.8.Z\n    537\n    537\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25187149_ENSG00000169504.10.Z\n    501\n    501\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000235423.4.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_42468139_ENSG00000260793.2.Z\n    430\n    430\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_56350306_ENSG00000085760.10.Z\n    823\n    823\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_46914082_ENSG00000095002.8.Z\n    820\n    820\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000254461.1.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_48729030_ENSG00000104177.13.Z\n    601\n    601\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000129226.9.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_33328703_ENSG00000164175.10.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_78801332_ENSG00000187210.8.Z\n    850\n    850\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_56350306_ENSG00000115355.11.Z\n    823\n    823\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_90873653_ENSG00000186354.6.Z\n    1073\n    1073\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_143618626_ENSG00000241847.2.Z\n    648\n    648\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_23896049_ENSG00000115129.9.Z\n    769\n    769\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000269490.1.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000165948.6.Z\n    910\n    910\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_217911504_ENSG00000115457.5.Z\n    1031\n    1031\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000162430.12.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000173991.5.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_139992171_ENSG00000253485.1.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000131746.8.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_52053017_ENSG00000123080.6.Z\n    507\n    507\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_95350518_ENSG00000149231.7.Z\n    773\n    773\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_37760395_ENSG00000232973.7.Z\n    825\n    825\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_102007617_ENSG00000259172.1.Z\n    1214\n    1214\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_37760395_ENSG00000232028.1.Z\n    825\n    825\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000272849.1.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_169238015_ENSG00000163558.8.Z\n    790\n    790\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_56639314_ENSG00000187889.8.Z\n    754\n    754\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000110651.7.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_143618626_ENSG00000135604.9.Z\n    648\n    648\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000205978.5.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_82945613_ENSG00000013375.11.Z\n    437\n    437\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000188488.9.Z\n    910\n    910\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_128789886_ENSG00000175792.7.Z\n    375\n    375\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_76383671_ENSG00000187775.12.Z\n    1083\n    1083\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000185215.4.Z\n    563\n    563\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000160781.11.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_100660989_ENSG00000154237.8.Z\n    1385\n    1385\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101698540_ENSG00000154237.8.Z\n    981\n    981\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_50096859_ENSG00000267898.1.Z\n    628\n    628\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000241106.2.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000236104.2.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000258604.1.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_78801332_ENSG00000099139.9.Z\n    850\n    850\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_169238015_ENSG00000013297.6.Z\n    790\n    790\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000159592.6.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_132604195_ENSG00000255933.1.Z\n    715\n    715\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_47139592_ENSG00000002919.10.Z\n    292\n    292\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000196136.12.Z\n    910\n    910\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_105973373_ENSG00000225200.2.Z\n    667\n    667\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_3443931_ENSG00000184160.6.Z\n    986\n    986\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000270108.1.Z\n    563\n    563\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_23896049_ENSG00000173960.8.Z\n    769\n    769\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000187010.14.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000121848.9.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_141121814_ENSG00000233597.3.Z\n    559\n    559\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000161381.9.Z\n    151\n    151\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000174348.9.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_45635239_ENSG00000189120.3.Z\n    463\n    463\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_33328703_ENSG00000150712.6.Z\n    354\n    354\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000030110.8.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000132680.6.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000108604.11.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000072778.15.Z\n    792\n    792\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_109723017_ENSG00000183137.10.Z\n    721\n    721\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000167244.13.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_126702792_ENSG00000136942.10.Z\n    593\n    593\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000105499.9.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_227046655_ENSG00000228206.2.Z\n    768\n    768\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_8_13372120_ENSG00000250305.4.Z\n    1230\n    1230\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_123258997_ENSG00000256546.1.Z\n    759\n    759\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000100823.7.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000205659.6.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_238400036_ENSG00000198612.6.Z\n    1106\n    1106\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_23896049_ENSG00000119782.9.Z\n    769\n    769\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000204264.4.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000087086.9.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_85967997_ENSG00000166748.8.Z\n    755\n    755\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000126461.10.Z\n    333\n    333\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_23896049_ENSG00000205639.5.Z\n    769\n    769\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000254539.1.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_65815254_ENSG00000228409.1.Z\n    476\n    476\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_67584758_ENSG00000215006.4.Z\n    154\n    154\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000165898.9.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000262652.1.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_98445632_ENSG00000237857.2.Z\n    940\n    940\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_272840_ENSG00000233296.1.Z\n    546\n    546\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000100453.8.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_128789886_ENSG00000261159.1.Z\n    409\n    409\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000187800.9.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_66318629_ENSG00000106610.10.Z\n    562\n    562\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_102900041_ENSG00000258230.2.Z\n    603\n    603\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_65696801_ENSG00000139233.2.Z\n    471\n    471\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000126453.5.Z\n    264\n    264\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000133026.8.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000063177.8.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000249790.2.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_217911504_ENSG00000118245.2.Z\n    1031\n    1031\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_89623396_ENSG00000204446.2.Z\n    834\n    834\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_5016883_ENSG00000170891.6.Z\n    1037\n    1037\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000063176.11.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000119638.8.Z\n    820\n    820\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_113490243_ENSG00000106853.12.Z\n    831\n    831\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000166579.11.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_48729030_ENSG00000185634.7.Z\n    601\n    601\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000204267.9.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_105374593_ENSG00000168772.9.Z\n    482\n    482\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65204666_ENSG00000173442.7.Z\n    507\n    507\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_55803533_ENSG00000134352.15.Z\n    1052\n    1052\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000173692.8.Z\n    621\n    621\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_128789886_ENSG00000163902.7.Z\n    409\n    409\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_89397827_ENSG00000166821.4.Z\n    918\n    918\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000258443.1.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000092203.9.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000119636.11.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_101198609_ENSG00000100811.6.Z\n    847\n    847\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_45635239_ENSG00000178852.11.Z\n    463\n    463\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_50096859_ENSG00000104852.10.Z\n    628\n    628\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_42015575_ENSG00000245849.2.Z\n    176\n    176\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_141121814_ENSG00000244124.1.Z\n    559\n    559\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_113490243_ENSG00000171133.2.Z\n    831\n    831\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000214087.4.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000266173.1.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000236624.4.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000235919.3.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_141121814_ENSG00000114120.7.Z\n    559\n    559\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_66318629_ENSG00000154710.11.Z\n    562\n    562\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_98830472_ENSG00000239445.1.Z\n    1116\n    1116\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_66318629_ENSG00000196715.5.Z\n    344\n    344\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_89840457_ENSG00000231007.4.Z\n    773\n    773\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000119682.12.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000185271.6.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000271329.1.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_70929100_ENSG00000163412.8.Z\n    524\n    524\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000170348.4.Z\n    609\n    609\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000117425.9.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_95350518_ENSG00000245552.2.Z\n    773\n    773\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000186666.4.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_128789886_ENSG00000172780.12.Z\n    409\n    409\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_78801332_ENSG00000135002.7.Z\n    850\n    850\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000269947.1.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000174951.6.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000070759.12.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000159915.8.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000104812.10.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000185105.4.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000116584.13.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000158104.7.Z\n    544\n    544\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_89397827_ENSG00000259494.1.Z\n    918\n    918\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000266402.2.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_169338671_ENSG00000185127.5.Z\n    1297\n    1297\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000176222.7.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000131187.5.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_66703817_ENSG00000175505.9.Z\n    460\n    460\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232328681_ENSG00000251485.1.Z\n    771\n    771\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_41654707_ENSG00000247556.2.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_102007617_ENSG00000184277.8.Z\n    1214\n    1214\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_169238015_ENSG00000085276.13.Z\n    790\n    790\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_109643880_ENSG00000119318.8.Z\n    461\n    461\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000174292.8.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_89397827_ENSG00000140538.12.Z\n    918\n    918\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_45239959_ENSG00000255426.1.Z\n    591\n    591\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000183726.6.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000263063.1.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_109723017_ENSG00000112290.8.Z\n    721\n    721\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000143319.12.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_8_9104590_ENSG00000147324.6.Z\n    1090\n    1090\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_13_102100039_ENSG00000102452.11.Z\n    1025\n    1025\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_38606933_ENSG00000251332.1.Z\n    710\n    710\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_56350306_ENSG00000162994.11.Z\n    823\n    823\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_132604195_ENSG00000196458.6.Z\n    658\n    658\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000159885.9.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_66318629_ENSG00000231234.1.Z\n    562\n    562\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000141560.10.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_4740251_ENSG00000147853.12.Z\n    1159\n    1159\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000197249.8.Z\n    910\n    910\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000059804.11.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000220205.4.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000141522.7.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_238400036_ENSG00000186235.6.Z\n    1106\n    1106\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000092009.6.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000169727.8.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_67584758_ENSG00000250978.1.Z\n    591\n    591\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000209582.1.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_238400036_ENSG00000132329.6.Z\n    1106\n    1106\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000266469.1.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_55692887_ENSG00000238018.1.Z\n    782\n    782\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_90873653_ENSG00000196730.8.Z\n    1073\n    1073\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_39794732_ENSG00000182400.10.Z\n    741\n    741\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_39794732_ENSG00000092208.12.Z\n    741\n    741\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000258584.1.Z\n    910\n    910\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_42468139_ENSG00000125319.10.Z\n    430\n    430\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000169504.10.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_45430280_ENSG00000117877.6.Z\n    594\n    594\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_99428825_ENSG00000196312.7.Z\n    537\n    537\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000204231.6.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101038100_ENSG00000131876.12.Z\n    1181\n    1181\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_70338344_ENSG00000035141.3.Z\n    480\n    480\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000165819.7.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000157379.9.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000053918.11.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_43946291_ENSG00000256762.1.Z\n    1211\n    1211\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_38606933_ENSG00000035928.10.Z\n    709\n    709\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000184454.6.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000119684.11.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_49125611_ENSG00000109180.10.Z\n    170\n    170\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_42468139_ENSG00000161682.10.Z\n    430\n    430\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000088986.6.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_123258997_ENSG00000130779.15.Z\n    759\n    759\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000242574.4.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_126702792_ENSG00000136950.9.Z\n    591\n    591\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000258890.2.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_65815254_ENSG00000237310.1.Z\n    476\n    476\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000183856.6.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_39349941_ENSG00000163683.7.Z\n    536\n    536\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_169338671_ENSG00000235994.4.Z\n    1008\n    1008\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_364679_ENSG00000111181.8.Z\n    936\n    936\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000073605.14.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000176155.14.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_217911504_ENSG00000115425.9.Z\n    768\n    768\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_227753496_ENSG00000143776.14.Z\n    567\n    567\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_106325900_ENSG00000138780.10.Z\n    1040\n    1040\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_106325900_ENSG00000138777.15.Z\n    1040\n    1040\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_27075099_ENSG00000117713.13.Z\n    284\n    284\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101698540_ENSG00000140470.9.Z\n    981\n    981\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_45239959_ENSG00000121680.11.Z\n    591\n    591\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_38860506_ENSG00000121897.9.Z\n    1107\n    1107\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000110881.7.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000139722.2.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_67242216_ENSG00000110066.10.Z\n    509\n    509\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_98445632_ENSG00000130956.9.Z\n    940\n    940\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000175567.4.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_364679_ENSG00000226210.3.Z\n    936\n    936\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000197283.8.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000182224.7.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_139381128_ENSG00000188229.5.Z\n    820\n    820\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_1986972_ENSG00000145214.9.Z\n    150\n    150\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_5631226_ENSG00000147853.12.Z\n    609\n    609\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000183684.6.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_89840457_ENSG00000196730.8.Z\n    773\n    773\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_109643880_ENSG00000136826.10.Z\n    461\n    461\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_42468139_ENSG00000108840.11.Z\n    430\n    430\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000119711.8.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000033030.9.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_238400036_ENSG00000184182.14.Z\n    1106\n    1106\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_4740251_ENSG00000120158.7.Z\n    1159\n    1159\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_98830472_ENSG00000080819.2.Z\n    1116\n    1116\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_102900041_ENSG00000017427.11.Z\n    603\n    603\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_5016883_ENSG00000072832.10.Z\n    1037\n    1037\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000258933.1.Z\n    910\n    910\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000186648.10.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000139726.6.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_75595747_ENSG00000173548.8.Z\n    297\n    297\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_89623396_ENSG00000135070.9.Z\n    834\n    834\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_70338344_ENSG00000198380.8.Z\n    480\n    480\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000132510.6.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000073050.7.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000146670.5.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_143618626_ENSG00000227192.1.Z\n    648\n    648\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000099869.6.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000188895.7.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000100888.8.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_24949056_ENSG00000119782.9.Z\n    533\n    533\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_102900041_ENSG00000257514.1.Z\n    603\n    603\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000104863.7.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_76746325_ENSG00000266970.1.Z\n    597\n    597\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_169338671_ENSG00000226445.1.Z\n    1298\n    1298\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_70338344_ENSG00000238465.1.Z\n    480\n    480\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_98445632_ENSG00000130948.5.Z\n    940\n    940\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000068976.9.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000176472.6.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_143618626_ENSG00000169976.5.Z\n    648\n    648\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000089041.12.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_92230041_ENSG00000123975.4.Z\n    1062\n    1062\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_61018091_ENSG00000264756.1.Z\n    606\n    606\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000258441.1.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000177144.5.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_18_44773382_ENSG00000267724.1.Z\n    760\n    760\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_238400036_ENSG00000168427.7.Z\n    1106\n    1106\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_70338344_ENSG00000116035.2.Z\n    480\n    480\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_132604195_ENSG00000198598.2.Z\n    715\n    715\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000119711.8.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000105550.4.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000165434.6.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_61018091_ENSG00000266066.1.Z\n    606\n    606\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000230953.2.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000258559.2.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000119681.7.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_75595747_ENSG00000198794.7.Z\n    297\n    297\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000166435.11.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_169238015_ENSG00000173890.12.Z\n    790\n    790\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_101198609_ENSG00000196405.8.Z\n    847\n    847\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_99428825_ENSG00000130948.5.Z\n    537\n    537\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_37760395_ENSG00000115825.5.Z\n    825\n    825\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000186364.7.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_128789886_ENSG00000163913.7.Z\n    409\n    409\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_238400036_ENSG00000178752.11.Z\n    1106\n    1106\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_100660989_ENSG00000140470.9.Z\n    1385\n    1385\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_89840457_ENSG00000156345.13.Z\n    773\n    773\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000129255.10.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_48374011_ENSG00000187166.1.Z\n    787\n    787\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_8_9104590_ENSG00000253958.1.Z\n    1090\n    1090\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000197429.6.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_55993436_ENSG00000261221.1.Z\n    1003\n    1003\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_101198609_ENSG00000271417.1.Z\n    847\n    847\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_38606933_ENSG00000248936.1.Z\n    300\n    300\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000179344.12.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_3098321_ENSG00000063978.11.Z\n    702\n    702\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_89623396_ENSG00000217716.3.Z\n    334\n    334\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_61018091_ENSG00000136463.7.Z\n    606\n    606\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000204301.5.Z\n    767\n    767\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_18112361_ENSG00000130511.11.Z\n    750\n    750\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000258603.1.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000161813.16.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000251414.1.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_8_124382184_ENSG00000263443.1.Z\n    575\n    575\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_151068398_ENSG00000143384.8.Z\n    546\n    546\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_105973373_ENSG00000211959.2.Z\n    656\n    656\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_13_114999636_ENSG00000184497.8.Z\n    735\n    735\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_45635239_ENSG00000185829.11.Z\n    310\n    310\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_56229770_ENSG00000268734.1.Z\n    902\n    902\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000169710.6.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000237248.3.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000212694.4.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000164845.12.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000162300.7.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_227046655_ENSG00000081052.10.Z\n    402\n    402\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_56639314_ENSG00000162409.6.Z\n    754\n    754\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_67584758_ENSG00000134058.6.Z\n    451\n    451\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_364679_ENSG00000256694.1.Z\n    936\n    936\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000100926.10.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_42468139_ENSG00000005102.8.Z\n    430\n    430\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000087191.8.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000177628.11.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000169696.11.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000156411.5.Z\n    563\n    563\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000185269.7.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000141753.5.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000167380.12.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000149243.11.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000256546.1.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_66318629_ENSG00000226824.2.Z\n    562\n    562\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_87812436_ENSG00000146282.13.Z\n    675\n    675\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000256673.1.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_89840457_ENSG00000135047.10.Z\n    773\n    773\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000141580.11.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_132604195_ENSG00000198393.3.Z\n    607\n    607\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000225315.2.Z\n    350\n    350\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000262049.1.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_46914082_ENSG00000222005.4.Z\n    820\n    820\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_57470188_ENSG00000134817.9.Z\n    361\n    361\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000089094.12.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000267242.1.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000165959.7.Z\n    740\n    740\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_27145341_ENSG00000203813.4.Z\n    612\n    612\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_89397827_ENSG00000140519.8.Z\n    918\n    918\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000204228.3.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000126368.5.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000198150.2.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_100660989_ENSG00000068305.13.Z\n    1385\n    1385\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000176903.3.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000136490.4.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_102007617_ENSG00000140471.12.Z\n    1214\n    1214\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_76746325_ENSG00000187775.12.Z\n    597\n    597\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_148896242_ENSG00000055130.11.Z\n    793\n    793\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_61072875_ENSG00000100612.9.Z\n    496\n    496\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000237039.1.Z\n    621\n    621\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000141744.3.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000126214.16.Z\n    563\n    563\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_99428825_ENSG00000081377.12.Z\n    537\n    537\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_98445632_ENSG00000148120.10.Z\n    662\n    662\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000204252.8.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_105973373_ENSG00000258701.1.Z\n    667\n    667\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000110911.10.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000139908.10.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000165792.13.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000256594.3.Z\n    477\n    477\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_67514591_ENSG00000081985.6.Z\n    769\n    769\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_61018091_ENSG00000259384.2.Z\n    326\n    326\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000089157.11.Z\n    779\n    779\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_42468139_ENSG00000161714.7.Z\n    430\n    430\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_100660989_ENSG00000261054.1.Z\n    895\n    895\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000110987.4.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_218604987_ENSG00000261338.1.Z\n    727\n    727\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_3098321_ENSG00000250986.1.Z\n    702\n    702\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_101198609_ENSG00000214548.10.Z\n    847\n    847\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000197136.4.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000100767.11.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_177587709_ENSG00000224687.1.Z\n    520\n    520\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_66318629_ENSG00000169902.9.Z\n    562\n    562\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_26133588_ENSG00000123094.11.Z\n    998\n    998\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_98445632_ENSG00000165244.6.Z\n    940\n    940\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_42468139_ENSG00000091947.5.Z\n    430\n    430\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000143303.7.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000175467.10.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_34311641_ENSG00000256538.1.Z\n    998\n    998\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_243396079_ENSG00000227230.1.Z\n    460\n    460\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_132604195_ENSG00000176894.5.Z\n    715\n    715\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000254429.1.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_66318629_ENSG00000241258.2.Z\n    562\n    562\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_76204090_ENSG00000198208.7.Z\n    391\n    391\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000170890.9.Z\n    779\n    779\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000143127.8.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000096433.6.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_132604195_ENSG00000176915.10.Z\n    715\n    715\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_46325577_ENSG00000136436.10.Z\n    531\n    531\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000173262.7.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000264057.1.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_98445632_ENSG00000225194.2.Z\n    940\n    940\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000108370.11.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_55803533_ENSG00000226221.1.Z\n    1052\n    1052\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_123258997_ENSG00000111325.12.Z\n    759\n    759\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_65696801_ENSG00000090376.4.Z\n    471\n    471\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000080815.14.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000184840.7.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000135931.13.Z\n    621\n    621\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_135874930_ENSG00000073711.6.Z\n    418\n    418\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_82945613_ENSG00000146242.5.Z\n    584\n    584\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000257243.1.Z\n    432\n    432\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_3098321_ENSG00000087274.12.Z\n    702\n    702\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000270000.1.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000157184.5.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000224383.3.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_13_33101817_ENSG00000244754.4.Z\n    481\n    481\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_132604195_ENSG00000061936.5.Z\n    715\n    715\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_42468139_ENSG00000168517.6.Z\n    430\n    430\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_102900041_ENSG00000185480.7.Z\n    603\n    603\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000181924.6.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000184601.6.Z\n    563\n    563\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_143618626_ENSG00000112414.10.Z\n    294\n    294\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_93406232_ENSG00000066455.8.Z\n    787\n    787\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000003056.3.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000149823.3.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_46577056_ENSG00000214765.4.Z\n    831\n    831\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_172405591_ENSG00000172878.9.Z\n    863\n    863\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_94783438_ENSG00000169372.8.Z\n    506\n    506\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000144535.15.Z\n    621\n    621\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000054938.11.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000111788.9.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000198844.6.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000249129.1.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000117640.13.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000260460.1.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000187105.4.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000141750.6.Z\n    301\n    301\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000269940.1.Z\n    563\n    563\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000173727.7.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101698540_ENSG00000131871.10.Z\n    981\n    981\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000241170.2.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000175416.8.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000213443.2.Z\n    273\n    273\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_49125611_ENSG00000135605.8.Z\n    170\n    170\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000129460.11.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_18_44773382_ENSG00000267167.1.Z\n    760\n    760\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_4740251_ENSG00000106686.12.Z\n    1159\n    1159\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101038100_ENSG00000259205.2.Z\n    1181\n    1181\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000161798.6.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_99428825_ENSG00000231521.1.Z\n    383\n    383\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000169689.10.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_233658309_ENSG00000237641.1.Z\n    264\n    264\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000149380.7.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_66318629_ENSG00000235475.1.Z\n    562\n    562\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_77654536_ENSG00000091039.12.Z\n    830\n    830\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_89840457_ENSG00000083223.13.Z\n    773\n    773\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_221307820_ENSG00000143507.13.Z\n    503\n    503\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_20436519_ENSG00000213860.3.Z\n    817\n    817\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_14446001_ENSG00000226197.2.Z\n    416\n    416\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_48801047_ENSG00000268001.1.Z\n    970\n    970\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000160838.9.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000196811.7.Z\n    621\n    621\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_218604987_ENSG00000144579.3.Z\n    727\n    727\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_66318629_ENSG00000169919.12.Z\n    562\n    562\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000268172.1.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000178607.11.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000184227.3.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_132604195_ENSG00000256576.1.Z\n    715\n    715\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000142661.14.Z\n    712\n    712\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_8_9104590_ENSG00000182319.5.Z\n    1090\n    1090\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000139899.6.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000108854.11.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000197813.4.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000159596.6.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000073008.10.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000196498.9.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_92230041_ENSG00000148082.5.Z\n    1062\n    1062\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_39794732_ENSG00000100934.10.Z\n    741\n    741\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000143622.6.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000178386.8.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_4740251_ENSG00000107020.5.Z\n    1159\n    1159\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_45635239_ENSG00000167182.11.Z\n    463\n    463\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000136305.7.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000255200.1.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000157193.10.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000222009.4.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000196943.8.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000129194.3.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000229512.1.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_98445632_ENSG00000175611.7.Z\n    940\n    940\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_217911504_ENSG00000260804.2.Z\n    1031\n    1031\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_47915233_ENSG00000235105.1.Z\n    400\n    400\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_238400036_ENSG00000124831.14.Z\n    1106\n    1106\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000141738.9.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_169238015_ENSG00000184378.2.Z\n    790\n    790\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000089159.11.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000215644.5.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_218604987_ENSG00000179921.10.Z\n    727\n    727\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000135124.10.Z\n    779\n    779\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000186141.4.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000212694.4.Z\n    746\n    746\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000248596.2.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_46577056_ENSG00000136205.12.Z\n    254\n    254\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000089818.12.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000175727.9.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_67584758_ENSG00000145740.14.Z\n    591\n    591\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_65815254_ENSG00000231234.1.Z\n    476\n    476\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_217911504_ENSG00000231672.2.Z\n    1031\n    1031\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000198400.7.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000234222.2.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000211451.7.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000167258.9.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000137288.5.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000162415.6.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000255320.1.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_102007617_ENSG00000259583.1.Z\n    1214\n    1214\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_109723017_ENSG00000203801.4.Z\n    721\n    721\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_364679_ENSG00000002016.12.Z\n    936\n    936\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_48729030_ENSG00000138593.4.Z\n    601\n    601\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000168066.16.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_46577056_ENSG00000272556.1.Z\n    832\n    832\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000231389.3.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_2887539_ENSG00000130997.12.Z\n    601\n    601\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000092201.5.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000257097.1.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_99075038_ENSG00000160917.10.Z\n    362\n    362\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000105538.4.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000131323.10.Z\n    384\n    384\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_89397827_ENSG00000166813.10.Z\n    918\n    918\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000272432.1.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_75595747_ENSG00000178802.13.Z\n    297\n    297\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_67584758_ENSG00000249364.1.Z\n    566\n    566\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000223865.6.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000132522.11.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000203276.2.Z\n    953\n    953\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_105973373_ENSG00000211949.2.Z\n    667\n    667\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_106325900_ENSG00000168743.8.Z\n    1040\n    1040\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000141526.10.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000268852.1.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000175315.2.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_61018091_ENSG00000270587.1.Z\n    606\n    606\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_94783438_ENSG00000177889.5.Z\n    374\n    374\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000126106.9.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000259384.2.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000119673.10.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000240065.3.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000260563.2.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_238400036_ENSG00000124839.8.Z\n    1106\n    1106\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000258891.1.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_66292363_ENSG00000258297.1.Z\n    397\n    397\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_33328703_ENSG00000082196.16.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_48729030_ENSG00000259531.2.Z\n    532\n    532\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000175538.6.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000226754.1.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_218604987_ENSG00000115556.9.Z\n    727\n    727\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_66703817_ENSG00000167799.5.Z\n    460\n    460\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_76746325_ENSG00000108679.8.Z\n    597\n    597\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000175602.2.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_46914082_ENSG00000250116.2.Z\n    820\n    820\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000181408.2.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000111364.11.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000105559.7.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000108654.7.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_102007617_ENSG00000183475.8.Z\n    1214\n    1214\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000171596.6.Z\n    621\n    621\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000213347.6.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232328681_ENSG00000135932.6.Z\n    771\n    771\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000014138.4.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000140067.6.Z\n    910\n    910\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_46914082_ENSG00000180398.7.Z\n    820\n    820\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_94783438_ENSG00000198015.8.Z\n    421\n    421\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000129566.8.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_109723017_ENSG00000135596.13.Z\n    721\n    721\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_227046655_ENSG00000169031.14.Z\n    398\n    398\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_19839415_ENSG00000145996.7.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000066117.10.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000179195.11.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000126353.3.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000100889.7.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_66318629_ENSG00000265600.1.Z\n    562\n    562\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000161618.5.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_19839415_ENSG00000172201.6.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_39794732_ENSG00000150527.12.Z\n    741\n    741\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000202538.1.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_238400036_ENSG00000227252.1.Z\n    1106\n    1106\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_90113307_ENSG00000176018.8.Z\n    629\n    629\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000187838.12.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_18_44773382_ENSG00000167220.7.Z\n    760\n    760\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000163467.7.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000143294.10.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000268001.1.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000064201.11.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000131759.13.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000185813.6.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000204936.5.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_37760395_ENSG00000138061.7.Z\n    825\n    825\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000173338.8.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_38606933_ENSG00000197712.7.Z\n    710\n    710\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_132604195_ENSG00000256209.1.Z\n    715\n    715\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_70338344_ENSG00000196975.10.Z\n    480\n    480\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000087074.7.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000117984.8.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_5016883_ENSG00000132406.7.Z\n    1037\n    1037\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_95350518_ENSG00000149218.4.Z\n    773\n    773\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_51264296_ENSG00000243477.1.Z\n    332\n    332\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000163273.3.Z\n    621\n    621\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000130921.3.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000165782.6.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232328681_ENSG00000237758.1.Z\n    771\n    771\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_10308958_ENSG00000009724.12.Z\n    802\n    802\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000112514.11.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000224680.4.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_33328703_ENSG00000151388.6.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000259515.1.Z\n    563\n    563\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_32393578_ENSG00000121900.14.Z\n    272\n    272\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_52507782_ENSG00000164088.13.Z\n    392\n    392\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000105479.11.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000166439.5.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_46914082_ENSG00000171150.7.Z\n    820\n    820\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_8_9104590_ENSG00000173281.4.Z\n    1090\n    1090\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_102007617_ENSG00000259658.3.Z\n    1214\n    1214\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_3098321_ENSG00000087269.11.Z\n    702\n    702\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000196126.6.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000048162.15.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_4740251_ENSG00000233186.2.Z\n    1159\n    1159\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000260233.2.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_92230041_ENSG00000224945.1.Z\n    1062\n    1062\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000160767.16.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_75595747_ENSG00000138623.5.Z\n    297\n    297\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000141568.15.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000161970.8.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_132604195_ENSG00000185684.8.Z\n    715\n    715\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_143618626_ENSG00000034693.10.Z\n    648\n    648\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000166532.11.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000170296.5.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65715204_ENSG00000173227.9.Z\n    145\n    145\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_46914082_ENSG00000119888.6.Z\n    820\n    820\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_52053017_ENSG00000185104.15.Z\n    507\n    507\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_70338344_ENSG00000116039.7.Z\n    480\n    480\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000172803.13.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000247373.2.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000238917.1.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000228929.1.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_37760395_ENSG00000115828.11.Z\n    825\n    825\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101698540_ENSG00000189419.5.Z\n    981\n    981\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000162385.6.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000185162.2.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000213928.4.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_105973373_ENSG00000184601.6.Z\n    579\n    579\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000125434.6.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000166165.8.Z\n    563\n    563\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000223534.1.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_26512233_ENSG00000142675.13.Z\n    644\n    644\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_66703817_ENSG00000175294.5.Z\n    438\n    438\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_98445632_ENSG00000185920.11.Z\n    940\n    940\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000117632.16.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_44062154_ENSG00000229431.1.Z\n    636\n    636\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000166535.15.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_46914082_ENSG00000119729.6.Z\n    820\n    820\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000260285.1.Z\n    563\n    563\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000260423.1.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000185298.8.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000196189.8.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_121621309_ENSG00000115112.7.Z\n    803\n    803\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000264198.1.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000156030.8.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_89623396_ENSG00000156345.13.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000130787.9.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_45659895_ENSG00000124813.16.Z\n    756\n    756\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000058804.10.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_38606933_ENSG00000249685.1.Z\n    710\n    710\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000175592.4.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000130595.12.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000182676.4.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000233930.3.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000092295.7.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_105973373_ENSG00000183828.10.Z\n    667\n    667\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000159871.10.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_132604195_ENSG00000177084.12.Z\n    715\n    715\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_90113307_ENSG00000113369.4.Z\n    629\n    629\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_100660989_ENSG00000259219.1.Z\n    1385\n    1385\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_126702792_ENSG00000185585.15.Z\n    658\n    658\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_101198609_ENSG00000258399.2.Z\n    847\n    847\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000174744.9.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000139644.8.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000027847.9.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_52053017_ENSG00000228407.2.Z\n    507\n    507\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_66318629_ENSG00000225573.3.Z\n    562\n    562\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000133961.15.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_89623396_ENSG00000231007.4.Z\n    834\n    834\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000146067.11.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_56350306_ENSG00000272180.1.Z\n    823\n    823\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000119688.16.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_218604987_ENSG00000273466.1.Z\n    727\n    727\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000168056.10.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_46577056_ENSG00000146674.10.Z\n    831\n    831\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_169338671_ENSG00000184786.4.Z\n    1298\n    1298\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_169238015_ENSG00000270096.1.Z\n    790\n    790\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_23896049_ENSG00000232451.1.Z\n    769\n    769\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000108592.12.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_101198609_ENSG00000168350.6.Z\n    847\n    847\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000182208.8.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_128789886_ENSG00000271270.1.Z\n    409\n    409\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_141121814_ENSG00000272565.1.Z\n    559\n    559\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000132773.7.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000266236.1.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_39794732_ENSG00000270503.1.Z\n    741\n    741\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_90873653_ENSG00000123975.4.Z\n    249\n    249\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000113194.8.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_42468139_ENSG00000168591.11.Z\n    430\n    430\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000131116.7.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_3098321_ENSG00000109736.10.Z\n    702\n    702\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101698540_ENSG00000131876.12.Z\n    981\n    981\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_39794732_ENSG00000100941.4.Z\n    741\n    741\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_34311641_ENSG00000139133.2.Z\n    998\n    998\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_45239959_ENSG00000019505.3.Z\n    591\n    591\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000186019.10.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_91362488_ENSG00000157823.12.Z\n    701\n    701\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_61018091_ENSG00000136485.10.Z\n    606\n    606\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_106325900_ENSG00000168772.9.Z\n    1000\n    1000\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101038100_ENSG00000259172.1.Z\n    1181\n    1181\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_45430280_ENSG00000130208.5.Z\n    594\n    594\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_46577056_ENSG00000221971.3.Z\n    831\n    831\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000256053.3.Z\n    563\n    563\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000065320.4.Z\n    804\n    804\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000122966.9.Z\n    281\n    281\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000173039.14.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_155006451_ENSG00000143622.6.Z\n    394\n    394\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232328681_ENSG00000135914.5.Z\n    771\n    771\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000075413.13.Z\n    563\n    563\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_128789886_ENSG00000242992.2.Z\n    409\n    409\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000149798.3.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000167384.6.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000272405.1.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000257964.1.Z\n    392\n    392\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000196735.7.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000270028.1.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000172638.8.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000162298.12.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_55803533_ENSG00000155542.7.Z\n    1052\n    1052\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000117614.5.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101698540_ENSG00000259583.1.Z\n    981\n    981\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000170345.5.Z\n    154\n    154\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_150540196_ENSG00000133574.5.Z\n    926\n    926\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_46914082_ENSG00000068724.11.Z\n    820\n    820\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000130921.3.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_106325900_ENSG00000168769.8.Z\n    1040\n    1040\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_67584758_ENSG00000222939.1.Z\n    591\n    591\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000179029.10.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_132604195_ENSG00000232888.3.Z\n    715\n    715\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_70338344_ENSG00000075340.18.Z\n    480\n    480\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_217911504_ENSG00000197756.5.Z\n    1031\n    1031\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_42468139_ENSG00000161664.2.Z\n    430\n    430\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000156030.8.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_77654536_ENSG00000186908.10.Z\n    830\n    830\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000141504.7.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_90113307_ENSG00000113356.6.Z\n    629\n    629\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_93779376_ENSG00000257252.1.Z\n    714\n    714\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000196544.6.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000139914.6.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000165804.11.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_227525716_ENSG00000143761.9.Z\n    1118\n    1118\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_102900041_ENSG00000136048.9.Z\n    603\n    603\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_99428825_ENSG00000233820.2.Z\n    537\n    537\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000132514.9.Z\n    284\n    284\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_78511889_ENSG00000119121.17.Z\n    369\n    369\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000132781.13.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_70338344_ENSG00000152672.3.Z\n    480\n    480\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_61557718_ENSG00000241472.2.Z\n    860\n    860\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_105973373_ENSG00000226174.2.Z\n    667\n    667\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_45239959_ENSG00000121671.7.Z\n    591\n    591\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_99428825_ENSG00000196116.6.Z\n    537\n    537\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_27398652_ENSG00000109113.13.Z\n    479\n    479\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101698540_ENSG00000140479.12.Z\n    981\n    981\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000258515.1.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_98445632_ENSG00000271155.1.Z\n    940\n    940\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_132615068_ENSG00000154269.10.Z\n    665\n    665\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000129484.9.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_8_24041988_ENSG00000104689.5.Z\n    360\n    360\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_143618626_ENSG00000189007.11.Z\n    648\n    648\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_4740251_ENSG00000096968.8.Z\n    1159\n    1159\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000108349.10.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101038100_ENSG00000183475.8.Z\n    1181\n    1181\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_169338671_ENSG00000272848.1.Z\n    1297\n    1297\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000092051.12.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000070785.12.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_176521655_ENSG00000227740.1.Z\n    517\n    517\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_90113307_ENSG00000248323.1.Z\n    629\n    629\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_218604987_ENSG00000127838.9.Z\n    727\n    727\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000100949.10.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000116171.12.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000225855.2.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_55741371_ENSG00000080031.5.Z\n    732\n    732\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000126088.8.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000163468.10.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000270172.1.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_45239959_ENSG00000019485.8.Z\n    591\n    591\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000272755.1.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000104826.7.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_75595747_ENSG00000167173.14.Z\n    297\n    297\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_105973373_ENSG00000211895.3.Z\n    667\n    667\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000237649.3.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_65815254_ENSG00000154710.11.Z\n    476\n    476\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000175785.8.Z\n    910\n    910\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000174547.9.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000117036.7.Z\n    116\n    116\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_38606933_ENSG00000231160.5.Z\n    710\n    710\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000245105.1.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_4740251_ENSG00000197646.6.Z\n    1159\n    1159\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000146083.7.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000054965.6.Z\n    453\n    453\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000130783.9.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_55803533_ENSG00000264281.2.Z\n    1052\n    1052\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000183010.12.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_65696801_ENSG00000135677.6.Z\n    471\n    471\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_102900041_ENSG00000196091.8.Z\n    413\n    413\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000169228.9.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_56666502_ENSG00000168374.6.Z\n    857\n    857\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_99428825_ENSG00000158122.7.Z\n    537\n    537\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_98445632_ENSG00000158122.7.Z\n    585\n    585\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_36563082_ENSG00000215283.3.Z\n    553\n    553\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_20436519_ENSG00000105855.5.Z\n    817\n    817\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_106325900_ENSG00000251259.1.Z\n    1040\n    1040\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_109723017_ENSG00000118690.8.Z\n    721\n    721\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_102007617_ENSG00000131873.5.Z\n    1214\n    1214\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000119688.16.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000122971.4.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_5016883_ENSG00000247708.3.Z\n    1037\n    1037\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000160883.6.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_89142142_ENSG00000231999.2.Z\n    432\n    432\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_123053488_ENSG00000130779.15.Z\n    631\n    631\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_99428825_ENSG00000136925.10.Z\n    386\n    386\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000224997.1.Z\n    563\n    563\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_101198609_ENSG00000225746.4.Z\n    847\n    847\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000204248.6.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000254867.1.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000132688.10.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000265799.1.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000261888.1.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_42468139_ENSG00000108861.4.Z\n    430\n    430\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101038100_ENSG00000140471.12.Z\n    1181\n    1181\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_45405144_ENSG00000002919.10.Z\n    747\n    747\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000185624.10.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_70929100_ENSG00000114861.14.Z\n    524\n    524\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_123258997_ENSG00000184209.14.Z\n    759\n    759\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_146877947_ENSG00000250673.1.Z\n    562\n    562\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_3098321_ENSG00000163956.6.Z\n    702\n    702\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_16963904_ENSG00000219481.6.Z\n    102\n    102\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_76746325_ENSG00000108639.3.Z\n    597\n    597\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_169338671_ENSG00000186340.10.Z\n    1298\n    1298\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000165949.8.Z\n    910\n    910\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000132780.12.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_89397827_ENSG00000181991.11.Z\n    918\n    918\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_169338671_ENSG00000125337.12.Z\n    1109\n    1109\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_65815254_ENSG00000230295.1.Z\n    476\n    476\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000163479.9.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_128789886_ENSG00000075785.8.Z\n    409\n    409\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000100968.9.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000119698.7.Z\n    910\n    910\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_143618626_ENSG00000217027.1.Z\n    642\n    642\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_109723017_ENSG00000168438.10.Z\n    721\n    721\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000111361.8.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121756084_ENSG00000139725.3.Z\n    736\n    736\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000011422.7.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000139725.3.Z\n    750\n    750\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000258695.2.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000183734.4.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000265218.1.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101698540_ENSG00000259205.2.Z\n    981\n    981\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000270061.1.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_65815254_ENSG00000229180.4.Z\n    476\n    476\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000270775.1.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000219355.2.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000139719.5.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_238400036_ENSG00000132330.12.Z\n    1106\n    1106\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_64347233_ENSG00000186479.4.Z\n    640\n    640\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_243396079_ENSG00000117020.12.Z\n    460\n    460\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_8_13372120_ENSG00000242607.1.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_4740251_ENSG00000107036.7.Z\n    1159\n    1159\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_142961373_ENSG00000112414.10.Z\n    752\n    752\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_142961373_ENSG00000001036.9.Z\n    752\n    752\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000231500.2.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000196923.9.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000225447.1.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_169238015_ENSG00000213178.3.Z\n    790\n    790\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_132604195_ENSG00000185163.5.Z\n    715\n    715\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_75595747_ENSG00000247240.3.Z\n    297\n    297\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101038100_ENSG00000154237.8.Z\n    1181\n    1181\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_128789886_ENSG00000184897.4.Z\n    409\n    409\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101038100_ENSG00000184254.12.Z\n    1181\n    1181\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000175376.4.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000126458.3.Z\n    338\n    338\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_128789886_ENSG00000004399.8.Z\n    409\n    409\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_5016883_ENSG00000168818.5.Z\n    1037\n    1037\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000167272.6.Z\n    779\n    779\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000214176.5.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000173442.7.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000170037.9.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_176521655_ENSG00000230777.1.Z\n    517\n    517\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_141121814_ENSG00000177311.6.Z\n    559\n    559\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_177587709_ENSG00000075391.12.Z\n    520\n    520\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_218604987_ENSG00000127837.5.Z\n    727\n    727\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101038100_ENSG00000182397.10.Z\n    1181\n    1181\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_94783438_ENSG00000057704.6.Z\n    506\n    506\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_46545363_ENSG00000108465.10.Z\n    656\n    656\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000111328.2.Z\n    446\n    446\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_102007617_ENSG00000184254.12.Z\n    1214\n    1214\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_99428825_ENSG00000136937.8.Z\n    386\n    386\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_44147721_ENSG00000172992.7.Z\n    554\n    554\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000130600.11.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000067191.11.Z\n    234\n    234\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_238400036_ENSG00000115648.9.Z\n    1106\n    1106\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000167588.8.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000204227.4.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_76746325_ENSG00000171302.12.Z\n    597\n    597\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_49189815_ENSG00000139620.8.Z\n    524\n    524\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_102900041_ENSG00000111670.10.Z\n    603\n    603\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_243396079_ENSG00000054282.11.Z\n    460\n    460\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000174851.10.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_33518831_ENSG00000188167.4.Z\n    646\n    646\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_141121814_ENSG00000155903.7.Z\n    559\n    559\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000179094.9.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000271769.1.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000265298.1.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000168014.12.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000170545.12.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000078902.11.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000263002.3.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000259001.2.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000112511.13.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_131816401_ENSG00000197594.7.Z\n    995\n    995\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000124466.8.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_55803533_ENSG00000177058.7.Z\n    1052\n    1052\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000160789.15.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000134744.9.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000215861.4.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000110934.6.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000142233.7.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_55741371_ENSG00000267265.1.Z\n    732\n    732\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_66318629_ENSG00000237310.1.Z\n    562\n    562\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000232987.1.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_89397827_ENSG00000166825.9.Z\n    736\n    736\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_102007617_ENSG00000131871.10.Z\n    1214\n    1214\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000058799.9.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000254974.1.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000172977.8.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_4740251_ENSG00000235326.1.Z\n    267\n    267\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_51997005_ENSG00000164082.10.Z\n    451\n    451\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000162378.8.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000139718.6.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000231925.7.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_123258997_ENSG00000158023.5.Z\n    754\n    754\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_100660989_ENSG00000182397.10.Z\n    1385\n    1385\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_92230041_ENSG00000237372.1.Z\n    1062\n    1062\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101698540_ENSG00000154227.9.Z\n    981\n    981\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_45239959_ENSG00000175264.3.Z\n    591\n    591\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_55803533_ENSG00000155545.15.Z\n    1052\n    1052\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_169338671_ENSG00000153303.12.Z\n    1298\n    1298\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_89397827_ENSG00000181026.13.Z\n    918\n    918\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_94783438_ENSG00000120798.12.Z\n    506\n    506\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_1584593_ENSG00000175756.9.Z\n    629\n    629\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000261349.1.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_98830472_ENSG00000144810.11.Z\n    1116\n    1116\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_102900041_ENSG00000075188.4.Z\n    603\n    603\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_143618626_ENSG00000118495.14.Z\n    648\n    648\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000235027.1.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000178927.12.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_95350518_ENSG00000184384.9.Z\n    773\n    773\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000086015.16.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000185432.10.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000100938.13.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000178882.9.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_132604195_ENSG00000204583.5.Z\n    715\n    715\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_23896049_ENSG00000198399.10.Z\n    769\n    769\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_123258997_ENSG00000182782.7.Z\n    759\n    759\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_33328703_ENSG00000242110.3.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000063127.11.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_218604987_ENSG00000135912.6.Z\n    521\n    521\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000187147.13.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_52053017_ENSG00000085832.12.Z\n    507\n    507\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000258695.2.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_141121814_ENSG00000155893.7.Z\n    559\n    559\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_78310191_ENSG00000132840.5.Z\n    840\n    840\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_90113307_ENSG00000153140.4.Z\n    629\n    629\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000119630.9.Z\n    266\n    266\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000176761.6.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_70929100_ENSG00000170837.2.Z\n    524\n    524\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_46914082_ENSG00000230979.3.Z\n    396\n    396\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101698540_ENSG00000131873.5.Z\n    981\n    981\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000187531.9.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_48729030_ENSG00000166147.9.Z\n    601\n    601\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_66318629_ENSG00000273448.1.Z\n    562\n    562\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_18_44773382_ENSG00000078043.11.Z\n    760\n    760\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_5631226_ENSG00000137040.8.Z\n    609\n    609\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000250091.2.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_45635239_ENSG00000108424.5.Z\n    463\n    463\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000247679.2.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_169338671_ENSG00000229214.1.Z\n    1297\n    1297\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000131788.11.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_13_33101817_ENSG00000073910.15.Z\n    481\n    481\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000110046.8.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_67709718_ENSG00000231793.4.Z\n    1051\n    1051\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_100763455_ENSG00000270412.1.Z\n    327\n    327\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000141551.10.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000176444.14.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_100660989_ENSG00000168904.10.Z\n    1385\n    1385\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000182600.5.Z\n    423\n    423\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_90873653_ENSG00000106723.12.Z\n    1073\n    1073\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_65696801_ENSG00000197301.3.Z\n    471\n    471\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000116580.14.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000113758.9.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_75595747_ENSG00000169758.8.Z\n    297\n    297\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000259065.1.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000123009.3.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000233223.2.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_56666502_ENSG00000163666.4.Z\n    934\n    934\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_39794732_ENSG00000259070.1.Z\n    741\n    741\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_132604195_ENSG00000177192.9.Z\n    715\n    715\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_105973373_ENSG00000257556.1.Z\n    667\n    667\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000143321.14.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_128789886_ENSG00000203644.2.Z\n    409\n    409\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_179727399_ENSG00000113303.7.Z\n    968\n    968\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_92230041_ENSG00000186354.6.Z\n    1062\n    1062\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000184560.3.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_105374593_ENSG00000251586.1.Z\n    482\n    482\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_94783438_ENSG00000180263.9.Z\n    506\n    506\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000251666.1.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000111325.12.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000185436.7.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000184227.3.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_94783438_ENSG00000257283.1.Z\n    506\n    506\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000116539.6.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000129467.9.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000197063.6.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_75595747_ENSG00000140398.9.Z\n    297\n    297\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000181798.2.Z\n    621\n    621\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_70338344_ENSG00000115977.14.Z\n    480\n    480\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_99428825_ENSG00000165244.6.Z\n    537\n    537\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000066084.8.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000223474.2.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000181856.10.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_105973373_ENSG00000170779.10.Z\n    667\n    667\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_89623396_ENSG00000196730.8.Z\n    834\n    834\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_36157167_ENSG00000270876.1.Z\n    586\n    586\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_218604987_ENSG00000231672.2.Z\n    727\n    727\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000264968.1.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_57683653_ENSG00000149136.3.Z\n    584\n    584\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_218604987_ENSG00000180871.3.Z\n    727\n    727\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000142186.12.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000129538.9.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_70929100_ENSG00000270562.1.Z\n    524\n    524\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_81819588_ENSG00000136379.7.Z\n    539\n    539\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_45635239_ENSG00000002919.10.Z\n    463\n    463\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000170049.5.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_46914082_ENSG00000250565.2.Z\n    820\n    820\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000117450.9.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000119616.7.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000132507.13.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_76746325_ENSG00000167281.14.Z\n    597\n    597\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000129244.4.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000135519.6.Z\n    278\n    278\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000129214.10.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_78511889_ENSG00000106772.13.Z\n    402\n    402\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000254614.1.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_1584593_ENSG00000187583.6.Z\n    629\n    629\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000213859.3.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_52053017_ENSG00000117862.7.Z\n    507\n    507\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_46914082_ENSG00000116062.10.Z\n    381\n    381\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000100628.7.Z\n    910\n    910\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_100787349_ENSG00000166997.3.Z\n    118\n    118\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000168060.10.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000048140.13.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000115468.7.Z\n    621\n    621\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_76746325_ENSG00000167900.7.Z\n    597\n    597\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_105973373_ENSG00000183484.7.Z\n    667\n    667\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000141741.7.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_49125611_ENSG00000145248.6.Z\n    170\n    170\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_143618626_ENSG00000229036.3.Z\n    648\n    648\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_177170601_ENSG00000169223.10.Z\n    268\n    268\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000225766.4.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000119632.3.Z\n    910\n    910\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_37760395_ENSG00000218739.5.Z\n    825\n    825\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000126107.10.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000094804.5.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_90113307_ENSG00000234292.3.Z\n    629\n    629\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000269656.1.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000198520.6.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_24949056_ENSG00000119772.12.Z\n    533\n    533\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000170291.10.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000110801.9.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000256092.2.Z\n    225\n    225\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000177380.9.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_238400036_ENSG00000234949.2.Z\n    1106\n    1106\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_90113307_ENSG00000260871.1.Z\n    629\n    629\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_61018091_ENSG00000170921.10.Z\n    606\n    606\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000108342.8.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000105483.12.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000133937.3.Z\n    910\n    910\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_243396079_ENSG00000143702.11.Z\n    460\n    460\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000111328.2.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_114333327_ENSG00000059769.15.Z\n    733\n    733\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000259321.1.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_75595747_ENSG00000169752.12.Z\n    297\n    297\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_141121814_ENSG00000114125.9.Z\n    559\n    559\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000051825.10.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101698540_ENSG00000259172.1.Z\n    981\n    981\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_45659895_ENSG00000271857.1.Z\n    756\n    756\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000248996.1.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_89397827_ENSG00000241362.2.Z\n    918\n    918\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000235863.2.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000187514.10.Z\n    621\n    621\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_56350306_ENSG00000227799.1.Z\n    823\n    823\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_92230041_ENSG00000187764.7.Z\n    1062\n    1062\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000171551.7.Z\n    621\n    621\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000174827.9.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000089723.5.Z\n    910\n    910\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000156966.6.Z\n    621\n    621\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000117289.7.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000185344.9.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_42468139_ENSG00000161692.13.Z\n    430\n    430\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000126351.8.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000007314.7.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000142959.4.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_128789886_ENSG00000244300.2.Z\n    409\n    409\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_128789886_ENSG00000058262.5.Z\n    207\n    207\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50471630_ENSG00000066117.10.Z\n    497\n    497\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000117602.7.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_105973373_ENSG00000179627.9.Z\n    667\n    667\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000177830.13.Z\n    258\n    258\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000257027.1.Z\n    389\n    389\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000235296.1.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000223356.1.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000169258.6.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_36157167_ENSG00000225975.2.Z\n    202\n    202\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000223501.4.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_43304679_ENSG00000204052.4.Z\n    523\n    523\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000258603.1.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000119725.13.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_105973373_ENSG00000185347.13.Z\n    667\n    667\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000130598.11.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000182749.5.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_143618626_ENSG00000001036.9.Z\n    648\n    648\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_75595747_ENSG00000203392.2.Z\n    297\n    297\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_76746325_ENSG00000035862.8.Z\n    597\n    597\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000174684.6.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_99734369_ENSG00000196597.7.Z\n    396\n    396\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000169231.9.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000158023.5.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_61018091_ENSG00000198909.3.Z\n    606\n    606\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_99428825_ENSG00000237212.1.Z\n    537\n    537\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_132604195_ENSG00000183495.9.Z\n    715\n    715\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_128789886_ENSG00000114654.6.Z\n    409\n    409\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_89397827_ENSG00000140545.10.Z\n    918\n    918\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000165799.4.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000168061.9.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_169338671_ENSG00000229921.2.Z\n    1100\n    1100\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232328681_ENSG00000243650.2.Z\n    550\n    550\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_238400036_ENSG00000132323.4.Z\n    1106\n    1106\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000100664.6.Z\n    563\n    563\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232328681_ENSG00000144535.15.Z\n    771\n    771\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000248008.2.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_102706023_ENSG00000112874.5.Z\n    408\n    408\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000088808.12.Z\n    563\n    563\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_18_44773382_ENSG00000134049.3.Z\n    760\n    760\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_143618626_ENSG00000217648.1.Z\n    648\n    648\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_29665968_ENSG00000144642.16.Z\n    1025\n    1025\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000179636.10.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000119689.10.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000124459.7.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_33328703_ENSG00000113389.11.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_42468139_ENSG00000180329.9.Z\n    430\n    430\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000269290.1.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000085840.8.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000178977.3.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000198208.7.Z\n    400\n    400\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000089053.8.Z\n    779\n    779\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_18_41359380_ENSG00000267414.1.Z\n    742\n    742\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000119596.13.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000135114.8.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232328681_ENSG00000156973.9.Z\n    771\n    771\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_89840457_ENSG00000269994.1.Z\n    773\n    773\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000065970.4.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_109723017_ENSG00000155085.11.Z\n    721\n    721\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_95350518_ENSG00000149212.6.Z\n    773\n    773\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_124179405_ENSG00000106852.11.Z\n    628\n    628\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000232070.4.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_238400036_ENSG00000177483.7.Z\n    1106\n    1106\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000181885.14.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_95350518_ENSG00000087053.14.Z\n    773\n    773\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000185958.5.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_4740251_ENSG00000120217.9.Z\n    1159\n    1159\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_113490243_ENSG00000059769.15.Z\n    808\n    808\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000165821.7.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000108961.9.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_218604987_ENSG00000163464.7.Z\n    727\n    727\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000167920.4.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000132535.14.Z\n    801\n    801\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_38344485_ENSG00000213424.4.Z\n    404\n    404\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_126702792_ENSG00000165209.14.Z\n    658\n    658\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_396321_ENSG00000188996.4.Z\n    879\n    879\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000140043.7.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000213654.5.Z\n    695\n    695\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000178921.9.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000169413.2.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000132702.8.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_99428825_ENSG00000196597.7.Z\n    537\n    537\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000262251.1.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_78801332_ENSG00000234618.1.Z\n    850\n    850\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_92230041_ENSG00000130222.6.Z\n    1062\n    1062\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000232298.2.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_19548239_ENSG00000105664.6.Z\n    464\n    464\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000123268.4.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_13_102100039_ENSG00000125247.11.Z\n    1025\n    1025\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_102706023_ENSG00000181751.5.Z\n    408\n    408\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_94783438_ENSG00000243015.2.Z\n    506\n    506\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000263470.1.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_52507782_ENSG00000180929.4.Z\n    392\n    392\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000256189.1.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000198805.7.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000272091.1.Z\n    991\n    991\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_364679_ENSG00000120647.5.Z\n    936\n    936\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_45635239_ENSG00000266601.1.Z\n    463\n    463\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000116212.10.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_48729030_ENSG00000255302.3.Z\n    601\n    601\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000157837.11.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_8_9104590_ENSG00000173273.11.Z\n    1090\n    1090\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_123258997_ENSG00000158113.8.Z\n    759\n    759\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_102900041_ENSG00000111666.6.Z\n    603\n    603\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000090975.8.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000119596.13.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_101198609_ENSG00000273087.1.Z\n    847\n    847\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176749358_ENSG00000160883.6.Z\n    495\n    495\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_128789886_ENSG00000273437.1.Z\n    409\n    409\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_151469269_ENSG00000143390.13.Z\n    527\n    527\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000237641.1.Z\n    621\n    621\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000269423.1.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000119689.10.Z\n    576\n    576\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000139697.7.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_46577056_ENSG00000233952.1.Z\n    832\n    832\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000246451.2.Z\n    563\n    563\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_33328703_ENSG00000113387.7.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000265458.1.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000134748.12.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_101198609_ENSG00000185559.9.Z\n    847\n    847\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_67242216_ENSG00000084207.11.Z\n    509\n    509\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_8_13372120_ENSG00000164743.4.Z\n    1230\n    1230\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000092199.13.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000050426.11.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000051596.5.Z\n    250\n    250\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_70929100_ENSG00000163421.4.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000232629.4.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000215256.3.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000183283.11.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_102706023_ENSG00000145725.15.Z\n    408\n    408\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_56350306_ENSG00000162997.11.Z\n    823\n    823\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000157326.14.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232328681_ENSG00000156966.6.Z\n    771\n    771\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_19760916_ENSG00000167487.7.Z\n    193\n    193\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_169238015_ENSG00000085274.11.Z\n    790\n    790\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000214274.5.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_98445632_ENSG00000182150.11.Z\n    940\n    940\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000167363.9.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_95350518_ENSG00000256885.1.Z\n    773\n    773\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000258818.2.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000139697.7.Z\n    259\n    259\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_45635239_ENSG00000108379.5.Z\n    463\n    463\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000135914.5.Z\n    621\n    621\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_13_33101817_ENSG00000133121.16.Z\n    481\n    481\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000186603.4.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_75595747_ENSG00000140365.11.Z\n    297\n    297\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_150718780_ENSG00000213171.2.Z\n    59\n    59\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_89397827_ENSG00000140534.9.Z\n    918\n    918\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000165861.9.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_18163571_ENSG00000212789.3.Z\n    949\n    949\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000132763.10.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_65696801_ENSG00000174106.2.Z\n    471\n    471\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_61018091_ENSG00000007312.8.Z\n    280\n    280\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_20436519_ENSG00000105849.5.Z\n    817\n    817\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_5016883_ENSG00000145220.9.Z\n    1037\n    1037\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000205869.2.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_45635239_ENSG00000239552.2.Z\n    200\n    200\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_169238015_ENSG00000136603.9.Z\n    790\n    790\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000160818.12.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000068831.14.Z\n    511\n    511\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_128789886_ENSG00000183624.9.Z\n    409\n    409\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000141505.7.Z\n    680\n    680\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000227057.3.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000196337.6.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_56350306_ENSG00000240401.4.Z\n    823\n    823\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_21538067_ENSG00000100814.13.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000269963.1.Z\n    563\n    563\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_66318629_ENSG00000126524.5.Z\n    562\n    562\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_95350518_ENSG00000270689.1.Z\n    773\n    773\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000171847.6.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_38606933_ENSG00000196355.2.Z\n    710\n    710\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_45635239_ENSG00000213326.4.Z\n    463\n    463\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_53133149_ENSG00000157445.10.Z\n    231\n    231\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000175711.4.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_76746325_ENSG00000108669.12.Z\n    597\n    597\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000143630.5.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_52918267_ENSG00000114904.8.Z\n    690\n    690\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_94783438_ENSG00000236349.1.Z\n    506\n    506\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000174276.5.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000185499.12.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_70338344_ENSG00000115998.3.Z\n    480\n    480\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_42468139_ENSG00000005961.13.Z\n    430\n    430\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74379984_ENSG00000119661.10.Z\n    884\n    884\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000258559.2.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000124444.11.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_66003852_ENSG00000250105.1.Z\n    453\n    453\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_109643880_ENSG00000234229.3.Z\n    461\n    461\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_102928991_ENSG00000256705.3.Z\n    757\n    757\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_102007617_ENSG00000140479.12.Z\n    1214\n    1214\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000170175.6.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000187862.7.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000174903.10.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000201699.1.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000226499.1.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000161800.8.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000184551.4.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_93993266_ENSG00000258274.1.Z\n    771\n    771\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_128789886_ENSG00000240682.5.Z\n    409\n    409\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_89216425_ENSG00000086991.8.Z\n    641\n    641\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000110047.13.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_104199491_ENSG00000156414.14.Z\n    563\n    563\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_65696801_ENSG00000255566.1.Z\n    471\n    471\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_82945613_ENSG00000118420.12.Z\n    584\n    584\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_70338344_ENSG00000124380.6.Z\n    480\n    480\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_238400036_ENSG00000065802.7.Z\n    1011\n    1011\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_3098321_ENSG00000188981.6.Z\n    703\n    703\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101698540_ENSG00000183475.8.Z\n    981\n    981\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_218604987_ENSG00000079308.12.Z\n    727\n    727\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000248746.1.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_89840457_ENSG00000180447.5.Z\n    773\n    773\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_94783438_ENSG00000258365.1.Z\n    506\n    506\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_72803035_ENSG00000260534.1.Z\n    392\n    392\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_50428885_ENSG00000186792.11.Z\n    455\n    455\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000233396.3.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_98445632_ENSG00000081377.12.Z\n    755\n    755\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000262147.1.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_123258997_ENSG00000185344.9.Z\n    600\n    600\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_49568181_ENSG00000114270.11.Z\n    320\n    320\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000111796.3.Z\n    556\n    556\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_94783438_ENSG00000173588.10.Z\n    506\n    506\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_75595747_ENSG00000140465.9.Z\n    297\n    297\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_8_13372120_ENSG00000164741.10.Z\n    1230\n    1230\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000185527.7.Z\n    948\n    948\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000265688.1.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000110665.7.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_45635239_ENSG00000006025.7.Z\n    463\n    463\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101698540_ENSG00000259658.3.Z\n    981\n    981\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_121332593_ENSG00000257218.1.Z\n    778\n    778\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232769213_ENSG00000221944.3.Z\n    621\n    621\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_70338344_ENSG00000188971.4.Z\n    480\n    480\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_52053017_ENSG00000134748.12.Z\n    507\n    507\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000175115.7.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_26819053_ENSG00000117676.9.Z\n    525\n    525\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000256294.3.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_89397827_ENSG00000140543.9.Z\n    918\n    918\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_45635239_ENSG00000141295.9.Z\n    463\n    463\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000092098.12.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_218604987_ENSG00000018280.12.Z\n    727\n    727\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_65815254_ENSG00000067601.6.Z\n    362\n    362\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000174083.13.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_8831954_ENSG00000214851.4.Z\n    670\n    670\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000111358.9.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_5016883_ENSG00000173040.8.Z\n    1037\n    1037\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000254855.1.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_89840457_ENSG00000217716.3.Z\n    773\n    773\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_33191338_ENSG00000161896.6.Z\n    1093\n    1093\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_150540196_ENSG00000204934.6.Z\n    673\n    673\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_9550918_ENSG00000235263.1.Z\n    628\n    628\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_67584758_ENSG00000153044.5.Z\n    589\n    589\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_39794732_ENSG00000259100.1.Z\n    741\n    741\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_92230041_ENSG00000213694.3.Z\n    1062\n    1062\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_3098321_ENSG00000159733.9.Z\n    703\n    703\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_126702792_ENSG00000136930.8.Z\n    658\n    658\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000229645.4.Z\n    361\n    361\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000160766.10.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000213445.4.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_56666502_ENSG00000163946.9.Z\n    934\n    934\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_94838142_ENSG00000175699.8.Z\n    910\n    910\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000130528.7.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000171219.8.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000265749.1.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_53589801_ENSG00000121310.12.Z\n    1042\n    1042\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000245532.4.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_45635239_ENSG00000159111.8.Z\n    463\n    463\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000116586.7.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_74665725_ENSG00000119616.7.Z\n    919\n    919\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_89623396_ENSG00000180447.5.Z\n    834\n    834\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_169238015_ENSG00000008952.12.Z\n    790\n    790\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_144897876_ENSG00000168614.13.Z\n    161\n    161\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000213903.4.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000174672.11.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000173465.3.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000269990.1.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_51805099_ENSG00000157077.10.Z\n    610\n    610\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000184445.7.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_66318629_ENSG00000232559.2.Z\n    562\n    562\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000125459.10.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_16492021_ENSG00000185519.8.Z\n    759\n    759\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_8_9104590_ENSG00000272267.1.Z\n    1090\n    1090\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_46914082_ENSG00000228925.1.Z\n    820\n    820\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_143618626_ENSG00000135521.8.Z\n    648\n    648\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_23896049_ENSG00000119771.10.Z\n    769\n    769\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000182264.4.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000230896.1.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000157978.7.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000105771.9.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000132718.7.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_78511889_ENSG00000187210.8.Z\n    844\n    844\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000185359.8.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_101198609_ENSG00000197119.8.Z\n    847\n    847\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_66318629_ENSG00000243335.4.Z\n    562\n    562\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_7_20436519_ENSG00000219451.3.Z\n    817\n    817\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_8_9104590_ENSG00000104626.10.Z\n    1090\n    1090\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_99428825_ENSG00000175611.7.Z\n    537\n    537\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_101698540_ENSG00000184277.8.Z\n    981\n    981\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_17264961_ENSG00000267904.1.Z\n    927\n    927\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_45659895_ENSG00000112796.5.Z\n    756\n    756\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_141121814_ENSG00000114126.13.Z\n    559\n    559\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000176845.8.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_17040371_ENSG00000173068.13.Z\n    1024\n    1024\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000258057.1.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_52053017_ENSG00000134717.13.Z\n    507\n    507\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000132692.14.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000175826.7.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_16429949_ENSG00000186204.10.Z\n    720\n    720\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_243396079_ENSG00000214837.4.Z\n    460\n    460\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_177587709_ENSG00000260938.1.Z\n    520\n    520\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_46914082_ENSG00000119878.5.Z\n    820\n    820\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000272971.1.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_45635239_ENSG00000198933.5.Z\n    463\n    463\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_24835017_ENSG00000254505.4.Z\n    870\n    870\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_74288826_ENSG00000187726.4.Z\n    765\n    765\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_4_49125611_ENSG00000074966.6.Z\n    147\n    147\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000221916.2.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232328681_ENSG00000135931.13.Z\n    771\n    771\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_50901882_ENSG00000161791.9.Z\n    456\n    456\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_14_105973373_ENSG00000182809.6.Z\n    667\n    667\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_232989831_ENSG00000156973.9.Z\n    527\n    527\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_396321_ENSG00000272463.1.Z\n    879\n    879\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000188026.7.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_80533079_ENSG00000169750.4.Z\n    961\n    961\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_89397827_ENSG00000140521.7.Z\n    918\n    918\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000105447.8.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000174669.7.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000256092.2.Z\n    772\n    772\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_218604987_ENSG00000115568.11.Z\n    653\n    653\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000172500.8.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_62649590_ENSG00000214174.4.Z\n    440\n    440\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_96500857_ENSG00000222040.3.Z\n    251\n    251\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_65413855_ENSG00000245156.1.Z\n    513\n    513\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_25393004_ENSG00000117616.13.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_156061222_ENSG00000163382.7.Z\n    406\n    406\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_124216482_ENSG00000182782.7.Z\n    311\n    311\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_8_77095422_ENSG00000091656.11.Z\n    572\n    572\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_6_396321_ENSG00000164379.4.Z\n    828\n    828\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_89397827_ENSG00000172183.10.Z\n    918\n    918\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_5_176509193_ENSG00000170085.13.Z\n    762\n    762\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_89840457_ENSG00000219928.2.Z\n    773\n    773\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_65696801_ENSG00000225422.3.Z\n    396\n    396\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000186567.8.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_19548239_ENSG00000105662.11.Z\n    464\n    464\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_128789886_ENSG00000172771.7.Z\n    409\n    409\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_45502217_ENSG00000234329.1.Z\n    635\n    635\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_11_1962700_ENSG00000244242.1.Z\n    904\n    904\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_49122248_ENSG00000183207.8.Z\n    928\n    928\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_9_4740251_ENSG00000107249.17.Z\n    1159\n    1159\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_89397827_ENSG00000166819.7.Z\n    918\n    918\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_122828069_ENSG00000182196.9.Z\n    535\n    535\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_12_132604195_ENSG00000177169.5.Z\n    715\n    715\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_19_44280837_ENSG00000204920.6.Z\n    939\n    939\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_17_8024218_ENSG00000161956.8.Z\n    805\n    805\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_1_78450517_ENSG00000273338.1.Z\n    503\n    503\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_15_48729030_ENSG00000213862.4.Z\n    601\n    601\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_3_141121814_ENSG00000069849.6.Z\n    559\n    559\n    /net/data/GTEx/gwas/ukbb_height_conditioned/eCAVIAR/eCAVIAR_zscore/Muscle_Skeletal/eqtl_2_70338344_ENSG00000144031.7.Z\n    480\n    480\n\n\n\n```python\noutput_filename = 'height_W_eCAVIAR.sh'\n\nline_list = []\n\nfor identifier in missing:\n        \n    line = '/net/home/dlee/git/caviar/CAVIAR-C++/eCAVIAR -o ' + output_directory + 'chr'\n    line += identifier\n    line += ' -l ' + eC_LD_directory\n    line += identifier + '.LD'\n    line += ' -l ' + eC_LD_directory\n    line += identifier + '.LD'\n    line += ' -z ' + zfile_directory+ 'gwas_'\n    line += identifier + '.Z'\n    line += ' -z ' + zfile_directory+ 'eqtl_'\n    line += identifier + '.Z'\n    \n    line_list.append(line)\n\nprint(len(missing))\n\nopen(output_filename, 'w').close()\n\nwith open(output_filename, 'a') as the_file:\n    the_file.write('#/bin/sh')\n    the_file.write('\\n')\n\n    for i in line_list:\n        the_file.write(i + '\\n\\n')\n```\n\n    37\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "0cee894ed5a175e8c98473e1eb4876eba40ca3c4", "size": 321599, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Code/eCAVIAR/LD_fix.ipynb", "max_stars_repo_name": "dajale423/missing_link_association_function", "max_stars_repo_head_hexsha": "e64e42cf0ffa3e8c4d8690a017d3925cc94a8d2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/eCAVIAR/LD_fix.ipynb", "max_issues_repo_name": "dajale423/missing_link_association_function", "max_issues_repo_head_hexsha": "e64e42cf0ffa3e8c4d8690a017d3925cc94a8d2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/eCAVIAR/LD_fix.ipynb", "max_forks_repo_name": "dajale423/missing_link_association_function", "max_forks_repo_head_hexsha": "e64e42cf0ffa3e8c4d8690a017d3925cc94a8d2c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.7289689561, "max_line_length": 132, "alphanum_fraction": 0.7199742537, "converted": true, "num_tokens": 112075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250462027098473, "lm_q2_score": 0.03308597469422148, "lm_q1q2_score": 0.013978977174477459}}
{"text": "# Homework 2\n\nIn this homework, we are going to play with Twitter data.\n\nThe data is represented as rows of of [JSON](https://en.wikipedia.org/wiki/JSON#Example) strings.\nIt consists of [tweets](https://dev.twitter.com/overview/api/tweets), [messages](https://dev.twitter.com/streaming/overview/messages-types), and a small amount of broken data (cannot be parsed as JSON).\n\nFor this homework, we will only focus on tweets and ignore all other messages.\n\n\n## Tweets\n\nA tweet consists of many data fields. [Here is an example](https://gist.github.com/arapat/03d02c9b327e6ff3f6c3c5c602eeaf8b). You can learn all about them in the Twitter API doc. We are going to briefly introduce only the data fields that will be used in this homework.\n\n* `created_at`: Posted time of this tweet (time zone is included)\n* `id_str`: Tweet ID - we recommend using `id_str` over using `id` as Tweet IDs, becauase `id` is an integer and may bring some overflow problems.\n* `text`: Tweet content\n* `user`: A JSON object for information about the author of the tweet\n    * `id_str`: User ID\n    * `name`: User name (may contain spaces)\n    * `screen_name`: User screen name (no spaces)\n* `retweeted_status`: A JSON object for information about the retweeted tweet (i.e. this tweet is not original but retweeteed some other tweet)\n    * All data fields of a tweet except `retweeted_status`\n* `entities`: A JSON object for all entities in this tweet\n    * `hashtags`: An array for all the hashtags that are mentioned in this tweet\n    * `urls`: An array for all the URLs that are mentioned in this tweet\n\n\n## Data source\n\nAll tweets are collected using the [Twitter Streaming API](https://dev.twitter.com/streaming/overview).\n\n\n## Users partition\n\nBesides the original tweets, we will provide you with a Pickle file, which contains a partition over 452,743 Twitter users. It contains a Python dictionary `{user_id: partition_id}`. The users are partitioned into 7 groups.\n\n\n```python\n# You can load pickle_content from a file on the local file system\n# while testing on your laptop\n# To test on your laptop, set `ON_EMR=False`\n# To test on AWS for final submission, set `ON_EMR=True`\n\nON_EMR = False\n```\n\n## Grading\n\nWe ask you use the `OutputLogger` object `my_output` to store the\nresults of your program.\nWe have provided function calls to `my_output.append()` method for\nstoring the results in all necessary places.\nPlease make sure NOT to remove these lines\n\nIn the last cell of this file, we write the content of `my_output`\nto a pickle file which the grader will read in and use for grading.\n\n\n```python\nimport os\nimport pickle\n\n\nclass OutputLogger:\n    def __init__(self):\n        self.ans = {}\n\n    def append(self, key, value):\n        self.ans[key] = value\n\n    def write_to_disk(self):\n        if ON_EMR:\n            filepath = os.path.expanduser(\"answer.pickle\")\n            print(\"FilePath = {}\".format(filepath))\n            with open(filepath, 'wb') as f:\n                pickle.dump(self.ans, f)\n            proc = subprocess.Popen([\"/usr/local/hadoop/hadoop-2.7.4/bin/hadoop\", \"fs\", \"-copyFromLocal\", filepath, \"/user/spark/answer.pickle\"])\n            proc.wait()\n            os.remove(filepath)\n        else:\n            filepath = os.path.expanduser(\"~/answer.pickle\")\n            with open(filepath, 'wb') as f:\n                pickle.dump(self.ans, f)\n\n\nmy_output = OutputLogger()\n```\n\n# Part 0: Load data to a RDD\n\nThe tweets data is stored on AWS S3. We have in total a little over 1 TB of tweets. We provide 10 MB of tweets for your local development. For the testing and grading on the homework server, we will use different data.\n\n## Testing on the homework server\nOn EdX, we provide three different input sizes to test your program: 10 MB, 1 GB, and 10 GB. For any run, we will only be using one of these four datasets.\n\nFor submission and for local testing, make sure to read the path of the file you want to operate with from `./hw2-files.txt`. Otherwise your program will receive no points.\n\n## Local test\n\nFor local testing, please create your own `hw2-files.txt` file, which contains a single file path on the local disk, e.g.\n`file://<absolute_path_to_current_directory>/hw2-files-10mb.txt`. For final submission, we will create this file on our server for testing with the appropriate file path. If your implementation is correct, you should not worry about which file system (i.e. local file system or HDFS) Spark will read data from.\n\nNow let's see how many lines there are in the input files.\n\n1. Make RDD from the data in the file given by the file path present in `hw2-files.txt`.\n2. Mark the RDD to be cached (so in next operation data will be loaded in memory) \n3. call the `count` method to print number of lines in all these files\n\n<b>It should print<b>\n```\nNumber of elements: 2150\n```\n\n\n```python\n\"\"\"\nThis is a useful cell for debugging.\nUse timer_start() and timer_stop() at different parts of your code\nfor checking the amount of time a segment takes.\n\"\"\"\nfrom time import time\n\n\ntimer = []\nprev_ts = None\n\n\ndef timer_start():\n    global prev_ts\n    prev_ts = time()\n\n\ndef timer_stop(title):\n    timer.append((title, time() - prev_ts))\n```\n\n\n```python\ntimer_start()\n\nfrom pyspark import SparkContext\n\nsc = SparkContext()\n\ntimer_stop(\"set up sc\")\n```\n\n\n```python\ntimer_start()\n\n\nwith open('./hw2-files.txt') as f:\n    file_path = [w.strip() for w in f.readlines() if w.strip()]\n\ncount = 0\nfor path in file_path:\n    print(\"Reading file: \" + path)\n    baseRdd = sc.textFile(path).cache()\n    count = count + baseRdd.count()\n\nmy_output.append(\"num-tweets\", count)\nprint(baseRdd.take(1))\nprint('Number of elements:', count)\ntimer_stop(\"read data\")\n```\n\n    Reading file: ./hw2-files-10mb.txt\n    ['{\"created_at\":\"Tue Feb 23 17:42:31 +0000 2016\",\"id\":702186789189132288,\"id_str\":\"702186789189132288\",\"text\":\"I\\'m voting 4 #BernieSanders bc he doesn\\'t ride a CAPITALIST PIG adorned w\\\\/ #GoldmanSachs $. SYSTEM RIGGED CLASS WAR https:\\\\/\\\\/t.co\\\\/P7pFm2MT9e\",\"source\":\"\\\\u003ca href=\\\\\"http:\\\\/\\\\/twitter.com\\\\\" rel=\\\\\"nofollow\\\\\"\\\\u003eTwitter Web Client\\\\u003c\\\\/a\\\\u003e\",\"truncated\":false,\"in_reply_to_status_id\":null,\"in_reply_to_status_id_str\":null,\"in_reply_to_user_id\":null,\"in_reply_to_user_id_str\":null,\"in_reply_to_screen_name\":null,\"user\":{\"id\":470520068,\"id_str\":\"470520068\",\"name\":\"Marni Halasa\",\"screen_name\":\"MarniHalasa1\",\"location\":\"NYC\",\"url\":\"http:\\\\/\\\\/www.revolutionissexy.com\",\"description\":\"Performance Artist\\\\/Activist: unofficial OWS Freedom Fairy, Prof Figure Skater, Parade Personality, Media Liaison, Journalist, Lawyer. I protest w\\\\/skates & wings\",\"protected\":false,\"verified\":false,\"followers_count\":1156,\"friends_count\":1484,\"listed_count\":102,\"favourites_count\":4109,\"statuses_count\":10443,\"created_at\":\"Sat Jan 21 21:15:53 +0000 2012\",\"utc_offset\":null,\"time_zone\":null,\"geo_enabled\":true,\"lang\":\"en\",\"contributors_enabled\":false,\"is_translator\":false,\"profile_background_color\":\"000000\",\"profile_background_image_url\":\"http:\\\\/\\\\/abs.twimg.com\\\\/images\\\\/themes\\\\/theme1\\\\/bg.png\",\"profile_background_image_url_https\":\"https:\\\\/\\\\/abs.twimg.com\\\\/images\\\\/themes\\\\/theme1\\\\/bg.png\",\"profile_background_tile\":false,\"profile_link_color\":\"3B94D9\",\"profile_sidebar_border_color\":\"000000\",\"profile_sidebar_fill_color\":\"000000\",\"profile_text_color\":\"000000\",\"profile_use_background_image\":false,\"profile_image_url\":\"http:\\\\/\\\\/pbs.twimg.com\\\\/profile_images\\\\/461558466218184704\\\\/Al04oPWW_normal.jpeg\",\"profile_image_url_https\":\"https:\\\\/\\\\/pbs.twimg.com\\\\/profile_images\\\\/461558466218184704\\\\/Al04oPWW_normal.jpeg\",\"profile_banner_url\":\"https:\\\\/\\\\/pbs.twimg.com\\\\/profile_banners\\\\/470520068\\\\/1416425356\",\"default_profile\":false,\"default_profile_image\":false,\"following\":null,\"follow_request_sent\":null,\"notifications\":null},\"geo\":null,\"coordinates\":null,\"place\":{\"id\":\"01a9a39529b27f36\",\"url\":\"https:\\\\/\\\\/api.twitter.com\\\\/1.1\\\\/geo\\\\/id\\\\/01a9a39529b27f36.json\",\"place_type\":\"city\",\"name\":\"Manhattan\",\"full_name\":\"Manhattan, NY\",\"country_code\":\"US\",\"country\":\"United States\",\"bounding_box\":{\"type\":\"Polygon\",\"coordinates\":[[[-74.026675,40.683935],[-74.026675,40.877483],[-73.910408,40.877483],[-73.910408,40.683935]]]},\"attributes\":{}},\"contributors\":null,\"is_quote_status\":false,\"retweet_count\":0,\"favorite_count\":0,\"entities\":{\"hashtags\":[{\"text\":\"BernieSanders\",\"indices\":[13,27]},{\"text\":\"GoldmanSachs\",\"indices\":[75,88]}],\"urls\":[],\"user_mentions\":[],\"symbols\":[],\"media\":[{\"id\":702186787679002624,\"id_str\":\"702186787679002624\",\"indices\":[116,139],\"media_url\":\"http:\\\\/\\\\/pbs.twimg.com\\\\/media\\\\/Cb6rKb2UYAAR1Kc.jpg\",\"media_url_https\":\"https:\\\\/\\\\/pbs.twimg.com\\\\/media\\\\/Cb6rKb2UYAAR1Kc.jpg\",\"url\":\"https:\\\\/\\\\/t.co\\\\/P7pFm2MT9e\",\"display_url\":\"pic.twitter.com\\\\/P7pFm2MT9e\",\"expanded_url\":\"http:\\\\/\\\\/twitter.com\\\\/MarniHalasa1\\\\/status\\\\/702186789189132288\\\\/photo\\\\/1\",\"type\":\"photo\",\"sizes\":{\"thumb\":{\"w\":150,\"h\":150,\"resize\":\"crop\"},\"large\":{\"w\":2048,\"h\":1536,\"resize\":\"fit\"},\"medium\":{\"w\":1200,\"h\":900,\"resize\":\"fit\"},\"small\":{\"w\":680,\"h\":510,\"resize\":\"fit\"}}}]},\"extended_entities\":{\"media\":[{\"id\":702186787679002624,\"id_str\":\"702186787679002624\",\"indices\":[116,139],\"media_url\":\"http:\\\\/\\\\/pbs.twimg.com\\\\/media\\\\/Cb6rKb2UYAAR1Kc.jpg\",\"media_url_https\":\"https:\\\\/\\\\/pbs.twimg.com\\\\/media\\\\/Cb6rKb2UYAAR1Kc.jpg\",\"url\":\"https:\\\\/\\\\/t.co\\\\/P7pFm2MT9e\",\"display_url\":\"pic.twitter.com\\\\/P7pFm2MT9e\",\"expanded_url\":\"http:\\\\/\\\\/twitter.com\\\\/MarniHalasa1\\\\/status\\\\/702186789189132288\\\\/photo\\\\/1\",\"type\":\"photo\",\"sizes\":{\"thumb\":{\"w\":150,\"h\":150,\"resize\":\"crop\"},\"large\":{\"w\":2048,\"h\":1536,\"resize\":\"fit\"},\"medium\":{\"w\":1200,\"h\":900,\"resize\":\"fit\"},\"small\":{\"w\":680,\"h\":510,\"resize\":\"fit\"}}}]},\"favorited\":false,\"retweeted\":false,\"possibly_sensitive\":false,\"filter_level\":\"low\",\"lang\":\"en\",\"timestamp_ms\":\"1456249351199\"}']\n    Number of elements: 2150\n\n\n# Part 1: Parse JSON strings to JSON objects\n\nPython has built-in support for JSON.\n\n\n```python\nimport json\n\njson_example = '''\n{\n    \"id\": 1,\n    \"name\": \"A green door\",\n    \"price\": 12.50,\n    \"tags\": [\"home\", \"green\"]\n}\n'''\n\njson_obj = json.loads(json_example)\njson_obj\n```\n\n\n\n\n    {'id': 1, 'name': 'A green door', 'price': 12.5, 'tags': ['home', 'green']}\n\n\n\n## Broken tweets and irrelevant messages\n\nThe data of this assignment may contain broken tweets (invalid JSON strings). So make sure that your code is robust for such cases.\n\nYou can filter out such broken tweet by checking if:\n* the line is not in json format\n\nIn addition, some lines in the input file might not be tweets, but messages that the Twitter server sent to the developer (such as [limit notices](https://dev.twitter.com/streaming/overview/messages-types#limit_notices)). Your program should also ignore these messages.\n\nThese messages would not contain the `created_at` field and can be filtered out accordingly.\n* Check if json object of the broken tweet has a `created_at` field\n\n*Hint:* [Catch the ValueError](http://stackoverflow.com/questions/11294535/verify-if-a-string-is-json-in-python)\n\n**********************************************************************************\n\n**Tasks**\n\n(1) Parse raw JSON tweets to obtain valid JSON objects. \n\n(2) From all valid tweets, construct a pair RDD of `(user_id, text)`, where `user_id` is the `id_str` data field of the `user` dictionary (read [Tweets](#Tweets) section above), `text` is the `text` data field.\n\n\n```python\nimport json\n\ndef safe_parse(raw_json):\n    try:\n        json_object = json.loads(raw_json)\n    except ValueError as e:\n        return None\n    return json_object\n    \n\n```\n\n\n```python\n\"\"\"\n# Remember to construct an RDD of (user_id, text) here.\n\"\"\"\n\ndef createTweetEntry(s):\n    json = safe_parse(s)\n    if (json is None or not \"user\" in json or not \"id_str\" in json[\"user\"] or not \"text\" in json):\n        return None\n    else:\n        return (json[\"user\"][\"id_str\"], json[\"text\"])\n\ntweetRdd = baseRdd.map(createTweetEntry).filter(lambda x: x is not None)\n\nprint(tweetRdd.take(5))\n\n\n```\n\n    [('470520068', \"I'm voting 4 #BernieSanders bc he doesn't ride a CAPITALIST PIG adorned w/ #GoldmanSachs $. SYSTEM RIGGED CLASS WAR https://t.co/P7pFm2MT9e\"), ('2176120173', \"RT @TrumpNewMedia: .@realDonaldTrump #America get out &amp; #VoteTrump if you don't #VoteTrump NOTHING will change it's that simple!\\n#Trump htt\u2026\"), ('145087572', 'RT @Libertea2012: RT TODAY: #Colorado\u2019s leading progressive voices to endorse @BernieSanders! #Denver 11AM - 1PM in MST CO State Capitol\u2026'), ('23047147', '[VID] Liberal Tears Pour After Bernie Supporter Had To Deal With Trump Fans https://t.co/GFio6jeCBy via @MadWorldNews'), ('526506000', 'RT @justinamash: .@tedcruz is the only remaining candidate I trust to take on what he correctly calls the Washington Cartel. https://t.co/N\u2026')]\n\n\n## Number of unique users\n\nCount the number of different users in all valid tweets\n\n(hint: [the `distinct()` method](https://spark.apache.org/docs/latest/programming-guide.html#transformations) is an easy way to do this, but try to see if there is a faster way to do this).\n\n*******************************************************************************\n\n**It should print**\n```\nThe number of unique users is: 1748\n```\n\n\n```python\ntimer_start()\n\nusers_count = tweetRdd.map(lambda x: (x[0], 1)).\\\n                reduceByKey(lambda x,y: x*y).\\\n                map(lambda x: x[1]).\\\n                reduce(lambda x,y: x+y)\n\nmy_output.append(\"num-unique-users\", users_count)\nprint('The number of unique users is:', users_count)\ntimer_stop(\"Count unique users\")\n```\n\n    The number of unique users is: 1748\n\n\n# Part 2: Number of posts from each user partition\n\nLoad the Pickle file `/twitter/users-partition.pickle`, you will get a dictionary which represents a partition over 452,743 Twitter users, `{user_id: partition_id}`. The users are partitioned into 7 groups. For example, if the dictionary is loaded into a variable named `partition`, the partition ID of the user `59458445` is `partition[\"59458445\"]`. These users are partitioned into 7 groups. The partition ID is an integer between 0-6.\n\nNote that the user partition we provide doesn't cover all users appear in the input data.\n\n## Load the pickle file\n\nFor local testing, you can load the pickle file from the local file system, namely\n\n```\nproc = subprocess.Popen([\"cat\", \"./users-partition.pickle\"],\n                        stdout=subprocess.PIPE)\npickle_content = proc.communicate()[0]\n```\nHowever, for submission, please keep following code block unchanged, since on the server the pickle file is located on the HDFS.\n\n\n```python\nimport subprocess\nimport pickle\n\nif ON_EMR:\n    proc = subprocess.Popen([\"/usr/local/hadoop/hadoop-2.7.4/bin/hadoop\", \"fs\", \"-cat\", \"/user/spark/twitter/users-partition.pickle\"],\n                            stdout=subprocess.PIPE)\n    pickle_content = proc.communicate()[0]\n    \nelse:\n    #!wget 'http://mas-dse-open.s3.amazonaws.com/Twitter/users-partition.pickle' -O './users-partition.pickle'\n    proc = subprocess.Popen([\"cat\", \"./users-partition.pickle\"],\n                        stdout=subprocess.PIPE)\n    pickle_content = proc.communicate()[0]\n\npartition = pickle.loads(pickle_content)\nlen(partition)\n```\n\n\n\n\n    452743\n\n\n\n## Tweets per user partition\n\n1. Count the number of posts from each user partition\n\n2. Count the number of posts from group 0, 1, ..., 6, plus the number of posts from users who are not in any partition. Assign users who are not in any partition to the group 7.\n\n3. Put the results of this step into a pair RDD `(group_id, count)` that is sorted by key.\n\n\n\nPrint the post count using the `print_post_count` function we provided.\n\n**It should print**\n\n```\nGroup 0 posted 87 tweets\nGroup 1 posted 242 tweets\nGroup 2 posted 41 tweets\nGroup 3 posted 349 tweets\nGroup 4 posted 101 tweets\nGroup 5 posted 358 tweets\nGroup 6 posted 434 tweets\nGroup 7 posted 521 tweets\n```\n\n\n```python\ndef print_post_count(counts):\n    for group_id, count in counts:\n        print('Group %d posted %d tweets' % (group_id, count))\n```\n\n\n```python\ntimer_start()\n\ndef getTweetUserPartition(tweetId):\n    if (tweetId in partition):\n        return partition[tweetId]\n    return 7\n\ncounts_per_partition = tweetRdd.\\\n        map(lambda x: (getTweetUserPartition(x[0]), 1)).\\\n        reduceByKey(lambda x,y: x+y).sortByKey().collect()\n        \n# Following code adds your solution to `my_output`\nassert(type(counts_per_partition) is list and\n       len(counts_per_partition) == 8 and\n       len(counts_per_partition[0]) == 2)\nmy_output.append(\"counts_per_part\", counts_per_partition)\nprint_post_count(counts_per_partition)\ntimer_stop(\"Count tweets per user partition\")\n```\n\n    Group 0 posted 87 tweets\n    Group 1 posted 242 tweets\n    Group 2 posted 41 tweets\n    Group 3 posted 349 tweets\n    Group 4 posted 101 tweets\n    Group 5 posted 358 tweets\n    Group 6 posted 434 tweets\n    Group 7 posted 521 tweets\n\n\n# Part 3:  Tokens that are relatively popular in each user partition\n\nIn this step, we are going to find tokens that are relatively popular in each user partition.\n\nWe define the number of mentions of a token $t$ in a specific user partition $k$ as the number of users from the user partition $k$ that ever mentioned the token $t$ in their tweets. Note that even if some users might mention a token $t$ multiple times or in multiple tweets, a user will contribute at most 1 to the counter of the token $t$.\n\nPlease make sure that the number of mentions of a token is equal to the number of users who mentioned this token but NOT the number of tweets that mentioned this token.\n\nLet $N_t^k$ be the number of mentions of the token $t$ in the user partition $k$. Let $N_t^{all} = \\sum_{i=0}^7 N_t^{i}$ be the number of total mentions of the token $t$.\n\nWe define the relative popularity of a token $t$ in a user partition $k$ as the log ratio between $N_t^k$ and $N_t^{all}$, i.e. \n\n\\begin{equation}\np_t^k = \\log \\frac{N_t^k}{N_t^{all}}.\n\\end{equation}\n\n\nYou can compute the relative popularity by calling the function `get_rel_popularity`.\n\nWe load a tweet tokenizer for you in the following cells. This Tokenizer object is called `tok`. Don't forget to execute the two cells below.\n\nYou can expand the following cell if needed to see the minutae of the Tokenizer.\n\n\n```python\n#!/usr/bin/env python\n\n\"\"\"\nThis code implements a basic, Twitter-aware tokenizer.\n\nA tokenizer is a function that splits a string of text into words. In\nPython terms, we map string and unicode objects into lists of unicode\nobjects.\n\nThere is not a single right way to do tokenizing. The best method\ndepends on the application.  This tokenizer is designed to be flexible\nand this easy to adapt to new domains and tasks.  The basic logic is\nthis:\n\n1. The tuple regex_strings defines a list of regular expression\n   strings.\n\n2. The regex_strings strings are put, in order, into a compiled\n   regular expression object called word_re.\n\n3. The tokenization is done by word_re.findall(s), where s is the\n   user-supplied string, inside the tokenize() method of the class\n   Tokenizer.\n\n4. When instantiating Tokenizer objects, there is a single option:\n   preserve_case.  By default, it is set to True. If it is set to\n   False, then the tokenizer will downcase everything except for\n   emoticons.\n\nThe __main__ method illustrates by tokenizing a few examples.\n\nI've also included a Tokenizer method tokenize_random_tweet(). If the\ntwitter library is installed (http://code.google.com/p/python-twitter/)\nand Twitter is cooperating, then it should tokenize a random\nEnglish-language tweet.\n\n\nJulaiti Alafate:\n  I modified the regex strings to extract URLs in tweets.\n\"\"\"\n\n__author__ = \"Christopher Potts\"\n__copyright__ = \"Copyright 2011, Christopher Potts\"\n__credits__ = []\n__license__ = \"Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License: http://creativecommons.org/licenses/by-nc-sa/3.0/\"\n__version__ = \"1.0\"\n__maintainer__ = \"Christopher Potts\"\n__email__ = \"See the author's website\"\n\n######################################################################\n\nimport re\nfrom html import entities \n\n######################################################################\n# The following strings are components in the regular expression\n# that is used for tokenizing. It's important that phone_number\n# appears first in the final regex (since it can contain whitespace).\n# It also could matter that tags comes after emoticons, due to the\n# possibility of having text like\n#\n#     <:| and some text >:)\n#\n# Most imporatantly, the final element should always be last, since it\n# does a last ditch whitespace-based tokenization of whatever is left.\n\n# This particular element is used in a couple ways, so we define it\n# with a name:\nemoticon_string = r\"\"\"\n    (?:\n      [<>]?\n      [:;=8]                     # eyes\n      [\\-o\\*\\']?                 # optional nose\n      [\\)\\]\\(\\[dDpP/\\:\\}\\{@\\|\\\\] # mouth      \n      |\n      [\\)\\]\\(\\[dDpP/\\:\\}\\{@\\|\\\\] # mouth\n      [\\-o\\*\\']?                 # optional nose\n      [:;=8]                     # eyes\n      [<>]?\n    )\"\"\"\n\n# The components of the tokenizer:\nregex_strings = (\n    # Phone numbers:\n    r\"\"\"\n    (?:\n      (?:            # (international)\n        \\+?[01]\n        [\\-\\s.]*\n      )?            \n      (?:            # (area code)\n        [\\(]?\n        \\d{3}\n        [\\-\\s.\\)]*\n      )?    \n      \\d{3}          # exchange\n      [\\-\\s.]*   \n      \\d{4}          # base\n    )\"\"\"\n    ,\n    # URLs:\n    r\"\"\"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+\"\"\"\n    ,\n    # Emoticons:\n    emoticon_string\n    ,    \n    # HTML tags:\n     r\"\"\"<[^>]+>\"\"\"\n    ,\n    # Twitter username:\n    r\"\"\"(?:@[\\w_]+)\"\"\"\n    ,\n    # Twitter hashtags:\n    r\"\"\"(?:\\#+[\\w_]+[\\w\\'_\\-]*[\\w_]+)\"\"\"\n    ,\n    # Remaining word types:\n    r\"\"\"\n    (?:[a-z][a-z'\\-_]+[a-z])       # Words with apostrophes or dashes.\n    |\n    (?:[+\\-]?\\d+[,/.:-]\\d+[+\\-]?)  # Numbers, including fractions, decimals.\n    |\n    (?:[\\w_]+)                     # Words without apostrophes or dashes.\n    |\n    (?:\\.(?:\\s*\\.){1,})            # Ellipsis dots. \n    |\n    (?:\\S)                         # Everything else that isn't whitespace.\n    \"\"\"\n    )\n\n######################################################################\n# This is the core tokenizing regex:\n    \nword_re = re.compile(r\"\"\"(%s)\"\"\" % \"|\".join(regex_strings), re.VERBOSE | re.I | re.UNICODE)\n\n# The emoticon string gets its own regex so that we can preserve case for them as needed:\nemoticon_re = re.compile(regex_strings[1], re.VERBOSE | re.I | re.UNICODE)\n\n# These are for regularizing HTML entities to Unicode:\nhtml_entity_digit_re = re.compile(r\"&#\\d+;\")\nhtml_entity_alpha_re = re.compile(r\"&\\w+;\")\namp = \"&amp;\"\n\n######################################################################\n\nclass Tokenizer:\n    def __init__(self, preserve_case=False):\n        self.preserve_case = preserve_case\n\n    def tokenize(self, s):\n        \"\"\"\n        Argument: s -- any string or unicode object\n        Value: a tokenize list of strings; conatenating this list returns the original string if preserve_case=False\n        \"\"\"        \n        # Try to ensure unicode:\n        try:\n            s = str(s)\n        except UnicodeDecodeError:\n            s = s.encode('string_escape')\n            s = str(s)\n        # Fix HTML character entitites:\n        s = self.__html2unicode(s)\n        # Tokenize:\n        words = word_re.findall(s)\n        # Possible alter the case, but avoid changing emoticons like :D into :d:\n        if not self.preserve_case:            \n            words = map((lambda x : x if emoticon_re.search(x) else x.lower()), words)\n        return words\n\n    def tokenize_random_tweet(self):\n        \"\"\"\n        If the twitter library is installed and a twitter connection\n        can be established, then tokenize a random tweet.\n        \"\"\"\n        try:\n            import twitter\n        except ImportError:\n            print(\"Apologies. The random tweet functionality requires the Python twitter library: http://code.google.com/p/python-twitter/\")\n        from random import shuffle\n        api = twitter.Api()\n        tweets = api.GetPublicTimeline()\n        if tweets:\n            for tweet in tweets:\n                if tweet.user.lang == 'en':            \n                    return self.tokenize(tweet.text)\n        else:\n            raise Exception(\"Apologies. I couldn't get Twitter to give me a public English-language tweet. Perhaps try again\")\n\n    def __html2unicode(self, s):\n        \"\"\"\n        Internal metod that seeks to replace all the HTML entities in\n        s with their corresponding unicode characters.\n        \"\"\"\n        # First the digits:\n        ents = set(html_entity_digit_re.findall(s))\n        if len(ents) > 0:\n            for ent in ents:\n                entnum = ent[2:-1]\n                try:\n                    entnum = int(entnum)\n                    s = s.replace(ent, unichr(entnum))\t\n                except:\n                    pass\n        # Now the alpha versions:\n        ents = set(html_entity_alpha_re.findall(s))\n        ents = filter((lambda x : x != amp), ents)\n        for ent in ents:\n            entname = ent[1:-1]\n            try:            \n                s = s.replace(ent, unichr(entities.name2codepoint[entname]))\n            except:\n                pass                    \n            s = s.replace(amp, \" and \")\n        return s\n\n```\n\n\n```python\nfrom math import log\n\ntok = Tokenizer(preserve_case=False)\n\ndef get_rel_popularity(c_k, c_all):\n    return log(1.0 * c_k / c_all) / log(2)\n\n\ndef print_tokens(tokens, gid = None):\n    group_name = \"overall\"\n    if gid is not None:\n        group_name = \"group %d\" % gid\n    print('=' * 5 + ' ' + group_name + ' ' + '=' * 5)\n    for t, n in tokens:\n        print(\"%s\\t%.4f\" % (t, n))\n    print\n```\n\n## Tokenize tweets\n\n1. Tokenize the tweets using the `tokenize` function that is a method of the `Tokenizer` class that we have instantiated as `tok`. \n\n1. Count the number of mentions for each tokens regardless of specific user group.\n\n1. Call `print_count` function to show how many different tokens we have.\n\n**It should print**\n```\nNumber of tokens: 7677\n```\n\n\n```python\n# YOUR CODE HERE\n#for x in tok.tokenize(\"x[1] Hello world\"):\n#    print(x)\n\n# Create list of tokens per user.\ntokenizedRdd = tweetRdd.map(lambda x: (x[0], list(tok.tokenize(x[1])))).cache()\n\n# Use flatMap to get the list returned by each lambda function applied to a value and merge them at the end.\n# Then we removed duplicated elements.\nnum_of_tokens = tokenizedRdd.flatMap(lambda x: (x[1])).distinct().count()\n\nmy_output.append(\"num-tokens\", num_of_tokens)\nprint(\"Number of tokens:\", num_of_tokens)\n```\n\n    Number of tokens: 7677\n\n\n## Token popularity\n\nTokens that are mentioned by too few users are usually not very interesting. So we want to only keep tokens that are mentioned by at least 100 users. Filter out tokens that don't meet this requirement.\n\nCall `print_count` function to show how many different tokens we have after the filtering.\n\nCall `print_tokens` function to show top 20 most frequent tokens.\n\n**It should print**\n```\nNumber of tokens: 46\n===== overall =====\n:\t1046.0000\nrt\t920.0000\n.\t767.0000\nthe\t587.0000\ntrump\t560.0000\n\u2026\t520.0000\nto\t501.0000\n,\t497.0000\nin\t385.0000\na\t383.0000\nis\t382.0000\nof\t300.0000\n!\t285.0000\nfor\t275.0000\nand\t263.0000\non\t218.0000\ni\t216.0000\nhe\t191.0000\nthat\t190.0000\n\"\t181.0000\n```\n\n\n```python\ntimer_start()\n\ndef tokenListExplode(l):\n    ret = []\n    for token in l:\n        ret.append((token, 1))\n    return ret\n\nfreqTokenThreshold = 100\n\n# YOUR CODE HERE\n# Create list of unique tokens per user.\n# We use the set data structure to remove duplicates and convert back to list at the end.\n# Then we merge all tweets by the same user and remove duplicates again.\nuniqueTokenizedRdd = tokenizedRdd.map(lambda x: (x[0], list(set(x[1])))).\\\n    reduceByKey(lambda x,y: x + y).map(lambda x: (x[0], list(set(x[1]))))\n    \n# Sum all token count, filter only tokens that appeared more than a threshold and\n# reverse pairs to sort by count amount.\n# Note that we only reverse the pair order to sort by count value and then reverse back.\nfreqTokens = uniqueTokenizedRdd.flatMap(lambda x: tokenListExplode(x[1])).\\\n    reduceByKey(lambda x,y: x + y).\\\n    filter(lambda x: x[1] >= freqTokenThreshold).\\\n    map(lambda x: (x[1], x[0])).sortByKey(ascending = False).map(lambda x: (x[1], x[0])).cache()\n\ntop20 = freqTokens.take(20)\nnum_freq_tokens = freqTokens.count()\n\nmy_output.append(\"num-freq-tokens\", num_freq_tokens)\nmy_output.append(\"top-20-tokens\", top20)\nprint(\"Number of tokens:\", num_freq_tokens)\nprint_tokens(top20)\ntimer_stop(\"Count overall most popular tokens\")\n```\n\n    Number of tokens: 46\n    ===== overall =====\n    :\t1046.0000\n    rt\t920.0000\n    .\t767.0000\n    the\t587.0000\n    trump\t560.0000\n    \u2026\t520.0000\n    to\t501.0000\n    ,\t497.0000\n    in\t385.0000\n    a\t383.0000\n    is\t382.0000\n    of\t300.0000\n    !\t285.0000\n    for\t275.0000\n    and\t263.0000\n    on\t218.0000\n    i\t216.0000\n    he\t191.0000\n    that\t190.0000\n    \"\t181.0000\n\n\n## Relative Popularity\n\nFor all tokens that are mentioned by at least 100 users, compute their relative popularity in each user group. Then print the top 10 tokens with highest relative popularity in each user group. In case two tokens have same relative popularity, break the tie by printing the alphabetically smaller one.\n\n**Hint:** Let the relative popularity of a token $t$ be $p$. The order of the items will be satisfied by sorting them using (-p, t) as the key.\n\n**It should print**\n```\n===== group 0 =====\nwith\t-3.6088\ncruz\t-3.6554\nhis\t-3.6582\namp\t-3.8651\non\t-3.9608\nto\t-4.0145\n&\t-4.0875\nhttps\t-4.1699\ni\t-4.1699\nwhat\t-4.1699\n===== group 1 =====\nsanders\t-2.2854\ngop\t-2.4060\nhillary\t-2.4330\n\u2019\t-2.4463\nbernie\t-2.4835\n\"\t-2.6925\nare\t-2.7249\nthis\t-2.7633\nfor\t-2.8179\nabout\t-2.8346\n===== group 2 =====\nwith\t-4.3458\ndonald\t-4.5146\n...\t-4.7004\ngop\t-4.7279\ni\t-4.9475\non\t-4.9608\nhe\t-4.9925\n\u2026\t-5.1155\nhttps\t-5.1699\nwhat\t-5.1699\n===== group 3 =====\nbernie\t-1.5945\nsanders\t-1.6609\nhillary\t-2.2188\nand\t-2.5154\n\"\t-2.5930\nin\t-2.6114\nwill\t-2.6160\nhttps\t-2.6674\n...\t-2.7004\nyou\t-2.7004\n===== group 4 =====\nwhat\t-3.4330\nhave\t-3.4725\nbernie\t-3.5380\nthis\t-3.5518\nit\t-3.6881\n?\t-3.6912\nfor\t-3.7110\nabout\t-3.7415\nhillary\t-3.7549\nthat\t-3.7625\n===== group 5 =====\nwhat\t-1.8007\nnot\t-1.8745\nhttps\t-2.0000\nhis\t-2.0144\ncruz\t-2.0704\nit\t-2.1031\non\t-2.1243\n&\t-2.1399\namp\t-2.1489\n;\t-2.1592\n===== group 6 =====\nwill\t-1.3847\nhave\t-1.4725\n!\t-1.5850\ncruz\t-1.6919\ntrump\t-1.7199\nhttps\t-1.7549\n-\t-1.7673\n;\t-1.7807\nbe\t-1.7952\namp\t-1.8144\n===== group 7 =====\ndonald\t-1.0740\ntrump\t-1.6535\nbernie\t-1.7790\nsanders\t-1.7829\n\u2019\t-1.8613\nof\t-1.9069\n?\t-1.9186\nwith\t-1.9307\nthe\t-1.9588\nbe\t-1.9758\n```\n\n\n```python\n# Auxiliar method for the next section.\ndef getTokenKey(pair):\n    return (-1 * pair[1], pair[0])\n\ndef mergeGroupTokens(tokens1, tokens2):\n    maxLen = 10\n    mergedTokens = tokens1 + tokens2\n    mergedTokens = sorted(mergedTokens, key = getTokenKey)\n    if len(mergedTokens) <= maxLen:\n        return mergedTokens\n    \n    delta = maxLen - len(mergedTokens)\n    return mergedTokens[:maxLen]\n\npair1 = (\"aaa\", -0.444)\npair2 = (\"aaa\", -0.414)\npair3 = (\"aaa\", -0.314)\nprint(compTokens(pair1, pair2))\n\nprint(mergeGroupTokens([pair1, pair2], [pair3]))\n```\n\n    -0.030000000000000027\n    [('aaa', -0.314), ('aaa', -0.414), ('aaa', -0.444)]\n\n\n\n```python\ntimer_start()\n\ndef removeUnfreqTokens(l, freqTokens):\n    ret = []\n    for x in l:\n        if x in freqTokens:\n            ret.append(x)\n    return ret    \n\ndef separateByTokenAndGroup(pair):\n    groupId = pair[0]\n    tokens = pair[1]\n    ret = []\n    for t in tokens:\n        ret.append(((groupId, t), 1))\n    return ret    \n\n# YOUR CODE HERE\nfreqTokensList = freqTokens.map(lambda x: x[0]).collect()\n\n# We start creating a RDD of Tweet user group x List of Unique tokens.\nuniqueFreqTokenByGroupRdd = uniqueTokenizedRdd.map(lambda x: (getTweetUserPartition(x[0]), x[1]))\n                                                \n# Then we filter to only display the most frequent tokens for each entry.\nuniqueFreqTokenByGroupRdd = uniqueFreqTokenizedRdd.map(lambda x: (x[0], removeUnfreqTokens(x[1], freqTokensList)))\n\n# Preparing tokens to be counted per group, using each entry as ((group, token), 1).\n# We use flat map to transform a group list entry into multiple entries indexed by group and token.\n# Each value shouldn't become a long list since we didn't reduced all tweets yet.\ntokenCountByGroup = uniqueFreqTokenByGroupRdd.flatMap(separateByTokenAndGroup)\n\n# Reducing all by key to count the number of times which each token appear.\ntokenCountByGroup = tokenCountByGroup.reduceByKey(lambda x, y: x + y)\n                                              \n# Now we need to transform the count value into the popularity value.\nfreqTokensMap = freqTokens.collectAsMap()\ntokenFreqByGroup = tokenCountByGroup.map(lambda x: (x[0], get_rel_popularity(x[1], freqTokensMap[x[0][1]])))\n\n# Sorting by popularity decreasing order since it is based on log(x), x < 1.\n# We sort by group and untie by popularity and Lexicographical order.\n# Note that we reverse popularity just to be able to untie by lexicographical order here.\ntokenFreqByGroup = tokenFreqByGroup.sortBy(lambda x: (x[0][0], -1 * x[1], x[0][1]), ascending = True)\n\n# To filter only N biggest elements per group, we convert each value to a list and merge the lists\n# with a special function\ntokenFreqByGroup = tokenFreqByGroup.map(lambda x: (x[0][0], [(x[0][1], x[1])])).\\\n                    reduceByKey(mergeGroupTokens)\n\npopular_10_in_each_group = tokenFreqByGroup.collectAsMap()\n\n# Following code add your solution to `my_output`\nmy_output.append(\"popular_10_in_each_group\", popular_10_in_each_group)\nfor k in range(8):\n    print_tokens(popular_10_in_each_group[k], k)\ntimer_stop(\"Print popular tokens in each group\")\n```\n\n    ===== group 0 =====\n    with\t-3.6088\n    cruz\t-3.6554\n    his\t-3.6582\n    amp\t-3.8651\n    on\t-3.9608\n    to\t-4.0145\n    &\t-4.0875\n    https\t-4.1699\n    i\t-4.1699\n    what\t-4.1699\n    ===== group 1 =====\n    sanders\t-2.2854\n    gop\t-2.4060\n    hillary\t-2.4330\n    \u2019\t-2.4463\n    bernie\t-2.4835\n    \"\t-2.6925\n    are\t-2.7249\n    this\t-2.7633\n    for\t-2.8179\n    about\t-2.8346\n    ===== group 2 =====\n    with\t-4.3458\n    donald\t-4.5146\n    ...\t-4.7004\n    gop\t-4.7279\n    i\t-4.9475\n    on\t-4.9608\n    he\t-4.9925\n    \u2026\t-5.1155\n    https\t-5.1699\n    what\t-5.1699\n    ===== group 3 =====\n    bernie\t-1.5945\n    sanders\t-1.6609\n    hillary\t-2.2188\n    and\t-2.5154\n    \"\t-2.5930\n    in\t-2.6114\n    will\t-2.6160\n    https\t-2.6674\n    ...\t-2.7004\n    you\t-2.7004\n    ===== group 4 =====\n    what\t-3.4330\n    have\t-3.4725\n    bernie\t-3.5380\n    this\t-3.5518\n    it\t-3.6881\n    ?\t-3.6912\n    for\t-3.7110\n    about\t-3.7415\n    hillary\t-3.7549\n    that\t-3.7625\n    ===== group 5 =====\n    what\t-1.8007\n    not\t-1.8745\n    https\t-2.0000\n    his\t-2.0144\n    cruz\t-2.0704\n    it\t-2.1031\n    on\t-2.1243\n    &\t-2.1399\n    amp\t-2.1489\n    ;\t-2.1592\n    ===== group 6 =====\n    will\t-1.3847\n    have\t-1.4725\n    !\t-1.5850\n    cruz\t-1.6919\n    trump\t-1.7199\n    https\t-1.7549\n    -\t-1.7673\n    ;\t-1.7807\n    be\t-1.7952\n    amp\t-1.8144\n    ===== group 7 =====\n    donald\t-1.0740\n    trump\t-1.6535\n    bernie\t-1.7790\n    sanders\t-1.7829\n    \u2019\t-1.8613\n    of\t-1.9069\n    ?\t-1.9186\n    with\t-1.9307\n    the\t-1.9588\n    be\t-1.9758\n\n\n## Important: Write your solutions to disk\n\nFollowing cell write your solutions to disk which would be read in by the grader for grading.\n\n\n```python\nmy_output.write_to_disk()\n```\n\n## Optional Ungraded Exercise\nThe users partition is generated by a machine learning algorithm that tries to group the users by their political preferences. Three of the user groups are showing supports to Bernie Sanders, Ted Cruz, and Donald Trump. \n\nIf your program looks okay on the local test data, you can try it on the larger input by submitting your program to the homework server. Observe the output of your program to larger input files, can you guess the partition IDs of the three groups mentioned above based on your output?\n\n\n```python\n# Change the values of the following three items to your guesses\nusers_support = [\n    (-1, \"Bernie Sanders\"),\n    (-1, \"Ted Cruz\"),\n    (-1, \"Donald Trump\")\n]\n\nfor gid, candidate in users_support:\n    print(\"Users from group %d are most likely to support %s.\" % (gid, candidate))\n```\n\nUncomment the lines in the cell below to print out the time taken between `time_start()` and `time_end()` at various stages of your pipeline. \n\n\n```python\n# total_time = 0.0\n# for item in timer:\n#     print(\"{}\\t{}\".format(item[0], item[1]))\n#     total_time += item[1]\n# print(\"Total time: {}\".format(total_time))\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "8b1b3ee1b81d50b97d0b06a5e7b98c5fe1146668", "size": 54692, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "BigDataWithSpark/TwitterAnalysis/HW-2.ipynb", "max_stars_repo_name": "wfaria/dataScience", "max_stars_repo_head_hexsha": "26d6b775c9f4b269956d762a09cff706791e9e5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-15T04:59:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-15T04:59:57.000Z", "max_issues_repo_path": "BigDataWithSpark/TwitterAnalysis/HW-2.ipynb", "max_issues_repo_name": "wfaria/dataScience", "max_issues_repo_head_hexsha": "26d6b775c9f4b269956d762a09cff706791e9e5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BigDataWithSpark/TwitterAnalysis/HW-2.ipynb", "max_forks_repo_name": "wfaria/dataScience", "max_forks_repo_head_hexsha": "26d6b775c9f4b269956d762a09cff706791e9e5c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-15T05:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-15T05:00:00.000Z", "avg_line_length": 36.100330033, "max_line_length": 4661, "alphanum_fraction": 0.5407372193, "converted": true, "num_tokens": 10321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1480472055495773, "lm_q2_score": 0.09401017200157857, "lm_q1q2_score": 0.013917943258068818}}
{"text": "```\n#@title Copyright 2022 The Cirq Developers\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# Best practices\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n  <td>\n    <a target=\"_blank\" href=\"https://quantumai.google/cirq/google/best_practices\">View on QuantumAI</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/Cirq/blob/master/docs/google/best_practices.ipynb\">Run in Google Colab</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://github.com/quantumlib/Cirq/blob/master/docs/google/best_practices.ipynb\">View source on GitHub</a>\n  </td>\n  <td>\n    <a href=\"https://storage.googleapis.com/tensorflow_docs/Cirq/docs/google/best_practices.ipynb\">Download notebook</a>\n  </td>\n</table>\n\n\n```\ntry:\n    import cirq\nexcept ImportError:\n    print(\"installing cirq...\")\n    !pip install --quiet cirq\n    import cirq\n    print(\"installed cirq.\")\n```\n\n\n```\nimport cirq_google as cg\nimport sympy\n```\n\nThis section lists some best practices for creating a circuit that performs well\non Google hardware devices. This is an area of active research, so users are\nencouraged to try multiple approaches to improve results.\n\nThis guide is split into three parts:\n*  Getting your circuit to run\n*  Making it run faster\n*  Lowering error\n\n## Getting a circuit to run on hardware\n\nIn order to run on hardware, the circuit must only use qubits and gates that the\ndevice supports.  Using inactive qubits, non-adjacent qubits, or non-native\ngates will immediately cause a circuit to fail.\n\nValidating a circuit with a device, such as\n`cg.Sycamore.validate_circuit(circuit)` will test a lot of these\nconditions.  Calling the `validate_circuit` function will work with any\ndevice, including those retrieved directly from the API using the\n[engine object](./specification.md#serializable-devices), which can help\nidentify any qubits used in the circuit that have been disabled on the actual\ndevice.\n\n### Using built-in tranformers as a first pass\n\nUsing built-in transformers will allow you to compile to the correct gate set. As they are\nautomated solutions, they will not always perform as well as a hand-crafted solution, but\nthey provide a good starting point for creating a circuit that is likely to run successfully\non hardware. Best practice is to inspect the circuit after optimization to make sure\nthat it has compiled without unintended consequences.\n\n\n```\n# Create your circuit here\nmy_circuit = cirq.Circuit()\n\n# Convert the circuit to run on a Google target gateset.\n# The google specific `cirq.CompilationTargetGateset` specifies the target gateset\n# and a sequence of appropriate optimization routines that should be executed to compile\n# a circuit to run on this target. \nsycamore_circuit = cirq.optimize_for_target_gateset(my_circuit, gateset=cg.SycamoreTargetGateset())\n```\n\n### Using CircuitOperation to reduce circuit size\n\nParticularly large batches (or sweeps) of circuits may encounter errors when\nsent to Quantum Engine due to an upper limit on request size. If the circuits\nin question have a repetitive structure, `cirq.CircuitOperation`s can be used\nto reduce the request size and avoid this limit.\n\n\n```\n# Repeatedly apply Hadamard and measurement to 10 qubits.\nmy_circuit = cirq.Circuit()\nqubits = cirq.GridQubit.rect(2, 5)\nfor i in range(100):\n    my_circuit.append(cirq.H.on_each(*qubits))\n    for qb in qubits:\n        my_circuit.append(cirq.measure(qb, key=cirq.MeasurementKey.parse_serialized(f'{i}:m{qb}')))\n\nprint(my_circuit)\n\n# The same circuit, but defined using CircuitOperations.\n# This is ~1000x smaller when serialized!\nq = cirq.NamedQubit(\"q\")\nsub_circuit = cirq.FrozenCircuit(cirq.H(q), cirq.measure(q, key='m'))\ncircuit_op = cirq.CircuitOperation(sub_circuit).repeat(100)\nshort_circuit = cirq.Circuit(\n    circuit_op.with_qubits(q).with_measurement_key_mapping({'m': f'm{q}'}) for q in qubits\n)\nprint(short_circuit)\n```\n\nWhen compiling circuits with `CircuitOperation`s, providing a context\nwith `deep=True` will preserve the `CircuitOperation`s while\noptimizing their contents. This is useful for producing a concise,\ndevice-compatible circuit.\n\n\n```\nsyc_circuit = cirq.optimize_for_target_gateset(\n    short_circuit,\n    gateset=cg.SycamoreTargetGateset(),\n    context=cirq.TransformerContext(deep=True)\n)\nprint(syc_circuit)\n```\n\n## Running circuits faster\n\nThe following sections give tips and tricks that allow you to improve your\nrepetition rate (how many repetitions per second the device will run).\n\nThis will allow you to make the most out of limited time on the\ndevice by getting results faster. The shorter experiment time may\nalso reduce error due to drift of qubits away from calibration.\n\nThere are costs to sending circuits over the network, to compiling each\ncircuit into waveforms, to initializing the device,\nand to sending results back over the network.\nThese tips will aid you in removing some of this overhead by combining your\ncircuits into sweeps or batches.\n\n### Use sweeps when possible\n\nRound trip network time to and from the engine typically adds latency on the order of a second\nto the overall computation time.  Reducing the number of trips and allowing the engine to\nproperly batch circuits can improve the throughput of your calculations.  One way to do this\nis to use parameter sweeps to send multiple variations of a circuit at once.\n\nOne example is to turn single-qubit gates on or off by using parameter sweeps.\nFor instance, the following code illustrates how to combine measuring in the\nZ basis or the X basis in one circuit.\n\n\n```\nq = cirq.GridQubit(1, 1)\nsampler = cirq.Simulator()\n\n# STRATEGY #1: Have a separate circuit and sample call for each basis.\ncircuit_z = cirq.Circuit(\n    cirq.measure(q, key='out'))\ncircuit_x = cirq.Circuit(\n    cirq.H(q),\n    cirq.measure(q, key='out'))\nsamples_z = sampler.sample(circuit_z, repetitions=5)\nsamples_x = sampler.sample(circuit_x, repetitions=5)\n\nprint(\"Measurement in Z Basis:\", samples_z, sep=\"\\n\")\nprint(\"Measurement in X Basis:\", samples_x, sep=\"\\n\")\n```\n\n\n```\n# STRATEGY #2: Have a parameterized circuit.\ncircuit_sweep = cirq.Circuit(\n    cirq.H(q)**sympy.Symbol('t'),\n    cirq.measure(q, key='out'))\n\nsamples_sweep = sampler.sample(circuit_sweep,\n                               repetitions=5,\n                               params=[{'t': 0}, {'t': 1}])\nprint(samples_sweep)\n```\n\nOne word of caution is there is a limit to the total number of repetitions.  Take some care\nthat your parameter sweeps, especially products of sweeps, do not become so excessively large\nthat they exceed this limit.\n\n### Use batches if sweeps are not possible\n\nThe engine has a method called `run_batch()` that can be used to send multiple\ncircuits in a single request.  This can be used to increase the efficiency\nof your program so that more repetitions are completed per second.\n\nThe circuits that are grouped into the same batch must\nmeasure the same qubits and have the same number of repetitions for each\ncircuit.  Otherwise, the circuits will not be batched together\non the device, and there will be no gain in efficiency.\n\n### Flatten sympy formulas into symbols\n\nSymbols are extremely useful for constructing parameterized circuits (see above).  However,\nonly some sympy formulas can be serialized for network transport to the engine.\nCurrently, sums and products of symbols, including linear combinations, are supported.\nSee `cirq_google.arg_func_langs` for details.\n\nThe sympy library is also infamous for being slow, so avoid using complicated formulas if you\ncare about performance.  Avoid using parameter resolvers that have formulas in them.\n\nOne way to eliminate formulas in your gates is to flatten your expressions.\nThe following example shows how to take a gate with a formula and flatten it\nto a single symbol with the formula pre-computed for each value of the sweep:\n\n\n```\n# Suppose we have a gate with a complicated formula.  (e.g. \"2^t - 1\")\n# This formula cannot be serialized\n# It could potentially encounter sympy slowness.\ngate_with_formula = cirq.XPowGate(exponent=2 ** sympy.Symbol('t') - 1)\nsweep = cirq.Linspace('t', start=0, stop=1, length=5)\n\n# Instead of sweeping the formula, we will pre-compute the values of the formula\n# at every point and store it a new symbol called '<2**t - 1>'\nsweep_for_gate, flat_sweep = cirq.flatten_with_sweep(gate_with_formula, sweep)\n\nprint(repr(sweep_for_gate))\n\nprint(list(flat_sweep.param_tuples()))\n```\n\n## Improving circuit fidelity\n\nThe following tips and tricks show how to modify your circuit to\nreduce error rates by following good circuit design principles that\nminimize the length of circuits.\n\nQuantum Engine will execute a circuit as faithfully as possible.\nThis means that moment structure will be preserved. That is, all gates in a\nmoment are guaranteed to be executed before those in any later moment and\nafter gates in previous moments.  Many of these tips focus on having a\ngood moment structure that avoids problematic missteps that can cause\nunwanted noise and error.\n\nNote: See the [Circuit optimization, gate alignment, and spin echoes tutorial](../tutorials/google/spin_echoes.ipynb) for an example of the best practices discussed in this section.\n\n### Short gate depth\n\nIn the current NISQ (noisy intermediate scale quantum) era, gates and devices still\nhave significant error. Both gate errors and T1 decay rate can cause long circuits\nto have noise that overwhelms any signal in the circuit.\n\nThe recommended gate depths vary significantly with the structure of the circuit itself\nand will likely increase as the devices improve. Total circuit fidelity can be roughly\nestimated by multiplying the fidelity for all gates in the circuit. For example,\nusing a error rate of 0.5% per gate, a circuit of depth 20 and width 20 could be estimated\nat 0.995^(20 * 20) = 0.135. Using separate error rates per gates (i.e. based on calibration\nmetrics) or a more complicated noise model can result in more accurate error estimation.\n\n### Terminal Measurements\n\nMake sure that measurements are kept in the same moment as the final moment in\nthe circuit.  Make sure that any circuit optimizers do not alter this by\nincorrectly pushing measurements forward. This behavior can be avoided by\nmeasuring all qubits with a single gate or by adding\nthe measurement gate after all optimizers have run.\n\nCurrently, only terminal measurements are supported by the hardware.  If you\nabsolutely need intermediate measurements for your application, reach out to\nyour Google sponsor to see if they can help devise a proper circuit using\nintermediate measurements.\n\n\n### Keep qubits busy\n\nQubits that remain idle for long periods tend to dephase and decohere. Inserting a\n[Spin Echo](https://en.wikipedia.org/wiki/Spin_echo) into your circuit onto\nqubits that have long idle periods, such as a pair\nof involutions, such as two successive Pauli Y gates, will generally increase\nperformance of the circuit.\n\nBe aware that this should be done after calling\n`cirq.optimize_for_target_gateset`, since this function will 'optimize'\nthese operations out of the circuit. You can also tag the spin echo operations with a no-compile tag, and include these tags in `context.tags_to_ignore`, so that the transformer ignores all tagged operations marked with any of `context.tags_to_ignore`. \n\n### Delay initialization of qubits\n\nThe |0\u27e9 state is more robust than the |1\u27e9 state. As a result, one should\nnot initialize a qubit to |1\u27e9 at the beginning of the circuit until shortly\nbefore other gates are applied to it.\n\n### Align single-qubit and two-qubit layers\n\nDevices are generally calibrated to circuits that alternate single-qubit gates with\ntwo-qubit gates in each layer. Staying close to this paradigm will often improve\nperformance of circuits.  This will also reduce the circuit's total duration,\nsince the duration of a moment is its longest gate.  Making sure that each layer\ncontains similar gates of the same duration can be challenging, but it will\nlikely have a measurable impact on the fidelity of your circuit.\n\nDevices generally operate in the Z basis, so that rotations around the Z axis will become\nbook-keeping measures rather than physical operations on the device. These\nvirtual Z operations have zero duration and have no cost, if they add no moments\nto your circuit.  In order to guarantee that they do not add moments, you can\nmake sure that virtual Z are aggregated into their own layer.  Alternatively,\nyou can use the `cirq.eject_z` optimizer to propagate these Z gates forward through\ncommuting operators.\n\nSee the function `cirq.stratified_circuit` for an automated way to organize gates\ninto moments with similar gates.\n\n### Qubit picking\n\nOn current NISQ devices, qubits cannot be considered identical.  Different\nqubits can have vastly different performance and can vary greatly from day\nto day.  It is important for experiments to have a dynamic method to\npick well-performing qubits that maximize the fidelity of the experiment.\nThere are several techniques that can assist with this.\n\n*   Analyze calibration metrics:  performance of readout, single-qubit, and\ntwo-qubit gates are measured as a side effect of running the device's\ncalibration procedure.  These metrics can be used as a baseline to evaluate\ncircuit performance or identify outliers to avoid.  This data can be inspected\nprogrammatically by retrieving metrics from the [API](calibration.md) or\n[visually by applying a cirq.Heatmap](../tutorials/google/visualizing_calibration_metrics.ipynb)\nto that data or by using the built-in\nheatmaps in the Cloud console page for the processor.  Note that, since this\ndata is only taken during calibration (e.g. at most daily), drifts and other\nconcerns may affect the values significantly, so these metrics should only be\nused as a first approximation.  There is no substitute for actually running characterizations\non the device.\n*   Loschmidt echo:  Running a small circuit on a string of qubits and then\napplying the circuit's inverse can be used as a quick but effective way to\njudge qubit quality.  See\n[this tutorial](../tutorials/google/echoes.ipynb) for instructions.\n*   XEB:  Cross-entropy benchmarking is another way to gauge qubit performance\non a set of random circuits.  See tutorials on\n[parallel XEB](../qcvv/parallel_xeb.ipynb)\nor [isolated XEB](../qcvv/isolated_xeb.ipynb) for instructions.\n\n\n### Refitting gates\n\nVirtual Z gates (or even single qubit gates) can be added to adjust for errors\nin two qubit gates.  Two qubit gates can have errors due to drift, coherent\nerror, unintended cross-talk, or other sources.  Refitting these gates and\nadjusting the circuit for the observed unitary of the two qubit gate\ncompared to the ideal unitary can substantially improve results.\nHowever, this approach can use a substantial amount of resources.\n\nThis technique involves two distinct steps.  The first is *characterization*,\nwhich is to identify the true behavior of the two-qubit gate.  This typically\ninvolves running many varied circuits involving the two qubit gate in a method\n(either periodic or random) to identify the parameters of the gate's behavior.\n\nEntangling gates used in Google's architecture fall into a general category of FSim gates,\nstanding for *Fermionic simulation*.  The generalized version of this gate can\nbe parameterized into 5 angles, or degrees of freedom.  Characterization will\nattempt to identify the values of these five angles.\n\nThe second step is calibrating (or refitting) the gate.  Out of the five angles\nthat comprise the generalized FSim gate, three can be corrected for by adding\nZ rotations before or after the gate.  Since these gates are propagated forward\nautomatically, they add no duration or error to the circuit and can essentially\nbe added \"for free\".  See the [devices page](devices.md#virtual_z_gates) for more\ninformation on Virtual Z gates.  Note that it is important to keep the single-qubit and\ntwo-qubit gates aligned (see above) while performing this procedure so that\nthe circuit stays the same duration.\n\nFor more on calibration and detailed instructions on how to perform these procedures, see the following tutorials:\n\n* [Calibration API](../tutorials/google/calibration_api.ipynb)\n* [Floquet calibration example](../tutorials/google/floquet_calibration_example.ipynb)\n* [XEB calibration example](../tutorials/google/xeb_calibration_example.ipynb)\n", "meta": {"hexsha": "2c82fd644fe26dce5eae7e997d0a34779173147e", "size": 23028, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/google/best_practices.ipynb", "max_stars_repo_name": "LLcat1217/Cirq", "max_stars_repo_head_hexsha": "b88069f7b01457e592ad69d6b413642ef11a56b8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-05T22:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T22:17:39.000Z", "max_issues_repo_path": "docs/google/best_practices.ipynb", "max_issues_repo_name": "LLcat1217/Cirq", "max_issues_repo_head_hexsha": "b88069f7b01457e592ad69d6b413642ef11a56b8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2022-01-16T14:12:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T03:58:46.000Z", "max_forks_repo_path": "docs/google/best_practices.ipynb", "max_forks_repo_name": "LLcat1217/Cirq", "max_forks_repo_head_hexsha": "b88069f7b01457e592ad69d6b413642ef11a56b8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.0987202925, "max_line_length": 262, "alphanum_fraction": 0.6543338544, "converted": true, "num_tokens": 3891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15610488959337065, "lm_q2_score": 0.08882029240011771, "lm_q1q2_score": 0.013865281938771274}}
{"text": "[](https://colab.research.google.com/github/pySTEPS/pysteps/blob/master/examples/my_first_nowcast.ipynb)\n\n# My first precipitation nowcast\n\nIn this example, we will use pysteps to compute and plot an extrapolation nowcast using the NSSL's Multi-Radar/Multi-Sensor System\n([MRMS](https://www.nssl.noaa.gov/projects/mrms/)) rain rate product.\n\nThe MRMS precipitation product is available every 2 minutes, over the contiguous US. \nEach precipitation composite has 3500 x 7000 grid points, separated 1 km from each other.\n\n## Set-up Colab environment\n\n**Important**: In colab, execute this section one cell at a time. Trying to excecute all the cells at once may results in cells being skipped and some dependencies not being installed.\n\nFirst, let's set up our working environment. Note that these steps are only needed to work with google colab. \n\nTo install pysteps locally, you can follow [these instructions](https://pysteps.readthedocs.io/en/latest/user_guide/install_pysteps.html).\n\nFirst, let's install the latest Pysteps version from the Python Package Index (PyPI) using pip. This will also install the minimal dependencies needed to run pysteps. \n\n#### Install optional dependencies\n\nNow, let's install the optional dependendies that will allow us to plot and read the example data.\n- pygrib: to read the MRMS data grib format\n- pyproj: needed by pygrib\n\n**NOTE:** Do not import pysteps in this notebook until the following optional dependencies are loaded. Otherwise, pysteps will assume that they are not installed and some of its functionalities won't work.\n\n\n```python\n# These libraries are needed for the pygrib library in Colab. \n# Note that is needed if you install pygrib using pip.\n# If you use conda, the libraries will be installed automatically.\n! apt-get install libeccodes-dev libproj-dev\n\n# Install the python packages\n! pip install pyproj\n! pip install pygrib\n```\n\n\n```python\n# Uninstall existing shapely\n# We will re-install shapely in the next step by ignoring the binary\n# wheels to make it compatible with other modules that depend on \n# GEOS, such as Cartopy (used here).\n!pip uninstall --yes shapely\n```\n\n\n```python\n# To install cartopy in Colab using pip, we need to install the library \n# dependencies first.\n\n!apt-get install -qq libgdal-dev libgeos-dev\n!pip install shapely --no-binary shapely\n!pip install cartopy\n```\n\n#### Install pysteps\n\nNow that all dependencies are installed, we can install pysteps.\n\n\n```python\n# ! pip install pysteps\n! pip install git+https://github.com/pySTEPS/pysteps\n```\n\n## Getting the example data\n\nNow that we have the environment ready, let's install the example data and configure the pysteps's default parameters by following [this tutorial](https://pysteps.readthedocs.io/en/latest/user_guide/example_data.html).\n\nFirst, we will use the [pysteps.datasets.download_pysteps_data()](https://pysteps.readthedocs.io/en/latest/generated/pysteps.datasets.download_pysteps_data.html) function to download the data.\n\n\n\n```python\n# Import the helper functions\nfrom pysteps.datasets import download_pysteps_data, create_default_pystepsrc\n\n# Download the pysteps data in the \"pysteps_data\"\ndownload_pysteps_data(\"pysteps_data\")\n```\n\nNext, we need to create a default configuration file that points to the downloaded data. \nBy default, pysteps will place the configuration file in `$HOME/.pysteps` (unix and Mac OS X) or `$USERPROFILE/pysteps` (windows).\nTo quickly create a configuration file, we will use the [pysteps.datasets.create_default_pystepsrc()](https://pysteps.readthedocs.io/en/latest/generated/pysteps.datasets.create_default_pystepsrc.html#pysteps.datasets.create_default_pystepsrc) helper function.\n\n\n```python\n# If the configuration file is placed in one of the default locations \n# (https://pysteps.readthedocs.io/en/latest/user_guide/set_pystepsrc.html#configuration-file-lookup) \n# it will be loaded automatically when pysteps is imported. \nconfig_file_path = create_default_pystepsrc(\"pysteps_data\")\n```\n\nSince pysteps was already initialized in this notebook, we need to load the new configuration file and update the default configuration.\n\n\n```python\n# Import pysteps and load the new configuration file\nimport pysteps\n_ = pysteps.load_config_file(config_file_path, verbose=True)\n```\n\nLet's see what the default parameters look like (these are stored in the\n[pystepsrc file](https://pysteps.readthedocs.io/en/latest/user_guide/set_pystepsrc.html)). We will be using them to load the MRMS data set.\n\n\n```python\n# The default parameters are stored in pysteps.rcparams.\nfrom pprint import pprint\npprint(pysteps.rcparams.data_sources['mrms'])\n```\n\nThis should have printed the following lines:\n\n- `fn_ext`: 'grib2' -- The file extension\n- `fn_pattern`: 'PrecipRate_00.00_%Y%m%d-%H%M%S' -- The file naming convention of the MRMS data.\n- `importer`: 'mrms_grib' -- The name of the importer for the MRMS data.\n- `importer_kwargs`: {} -- Extra options provided to the importer. None in this example.\n- `path_fmt`: '%Y/%m/%d' -- The folder structure in which the files are stored. Here, year/month/day/filename.\n- `root_path`: '/content/pysteps_data/mrms' -- The root path of the MRMS-data.\n- `timestep`: 2 -- The temporal interval of the (radar) rainfall data\n\nNote that the default `timestep` parameter is 2 minutes, which corresponds to the time interval at which the MRMS product is available.\n\n## Load the MRMS example data\n\nNow that we have installed the example data, let's import the example MRMS dataset using the [load_dataset()](https://pysteps.readthedocs.io/en/latest/generated/pysteps.datasets.load_dataset.html) helper function from the `pysteps.datasets` module.\n\nWe import 1 hour and 10 minutes of data, which corresponds to a sequence of 35 frames of 2-D precipitation composites.\nNote that importing the data takes approximately 30 seconds.\n\n\n```python\nfrom pysteps.datasets import load_dataset\n\n# We'll import the time module to measure the time the importer needed\nimport time\n\nstart_time = time.time()\n\n# Import the data\nprecipitation, metadata, timestep = load_dataset('mrms',frames=35)  # precipitation in mm/h\n\nend_time = time.time()\n\nprint(\"Precipitation data imported\")\nprint(\"Importing the data took \", (end_time - start_time), \" seconds\")\n```\n\nLet's have a look at the values returned by the `load_dataset()` function. \n\n- `precipitation`: A numpy array with (time, latitude, longitude) dimensions.\n- `metadata`: A dictionary with additional information (pixel sizes, map projections, etc.).\n- `timestep`: Time separation between each sample (in minutes)\n\n\n```python\n# Let's inspect the shape of the imported data array\nprecipitation.shape\n```\n\nNote that the shape of the precipitation is 4 times smaller than the raw MRMS data (3500 x 7000).\nThe `load_dataset()` function uses the default parameters from `importers` to read the data. By default, the MRMS importer upscales the data 4x. That is, from ~1km resolution to ~4km. It also uses single precision to reduce the memory requirements.\nThanks to the upscaling, the memory footprint of this example dataset is ~200Mb instead of the 3.1Gb of the raw (3500 x 7000) data. \n\n\n```python\ntimestep # In minutes\n```\n\n\n```python\npprint(metadata)\n```\n\n# Time to make a nowcast\n\nSo far, we have 1 hour and 10 minutes of precipitation images, separated 2 minutes from each other.\nBut, how do we use that data to run a precipitation forecast? \n\nA simple way is by extrapolating the precipitation field, assuming it will continue to move as observed in the recent past, and without changes in intensity. This is commonly known as *Lagrangian persistence*.\n\nThe first step to run our nowcast based on Lagrangian persistence, is the estimation of the motion field from a sequence of past precipitation observations.\nWe use the Lucas-Kanade (LK) optical flow method implemented in pysteps.\nThis method follows a local tracking approach that relies on the OpenCV package.\nLocal features are tracked in a sequence of two or more radar images.\nThe scheme includes a final interpolation step to produce a smooth field of motion vectors.\nOther optical flow methods are also available in pysteps. \nCheck the full list [here](https://pysteps.readthedocs.io/en/latest/pysteps_reference/motion.html).\n\nNow let's use the first 5 precipitation images (10 min) to estimate the motion field of the radar pattern and the remaining 30 images (1h) to evaluate the quality of our forecast.\n\n\n```python\n# precipitation[0:5] -> Used to find motion (past data). Let's call it training precip.\ntrain_precip = precipitation[0:5]\n\n# precipitation[5:] -> Used to evaluate forecasts (future data, not available in \"real\" forecast situation)\n# Let's call it observed precipitation because we will use it to compare our forecast with the actual observations.\nobserved_precip = precipitation[3:]\n```\n\nLet's see what this 'training' precipitation event looks like using the [pysteps.visualization.plot_precip_field](https://pysteps.readthedocs.io/en/latest/generated/pysteps.visualization.precipfields.plot_precip_field.html) function.\n\n\n```python\nfrom matplotlib import pyplot as plt\nfrom pysteps.visualization import plot_precip_field\n\n# Set a figure size that looks nice ;)\nplt.figure(figsize=(9, 5), dpi=100)\n\n# Plot the last rainfall field in the \"training\" data.\n# train_precip[-1] -> Last available composite for nowcasting.\nplot_precip_field(train_precip[-1], geodata=metadata, axis=\"off\", map=\"cartopy\")\nplt.show()  # (This line is actually not needed if you are using jupyter notebooks)\n```\n\nDid you note the **shaded grey** regions? Those are the regions were no valid observations where available to estimate the precipitation (e.g., due to ground clutter, no radar coverage, or radar beam blockage).\nThose regions need to be handled with care when we run our nowcast.\n\n### Data exploration\n\nBefore we produce a forecast, let's explore the precipitation data. In particular, let's see how the distribution of the rain rate values looks.\n\n\n```python\nimport numpy as np\n\n# Let's define some plotting default parameters for the next plots\n# Note: This is not strictly needed.\nplt.rc('figure', figsize=(4,4))\nplt.rc('figure', dpi=100)\nplt.rc('font', size=14) # controls default text sizes\nplt.rc('axes', titlesize=14) # fontsize of the axes title\nplt.rc('axes', labelsize=14) # fontsize of the x and y labels\nplt.rc('xtick', labelsize=14) # fontsize of the tick labels\nplt.rc('ytick', labelsize=14) # fontsize of the tick labels\n\n# Let's use the last available composite for nowcasting from the \"training\" data (train_precip[-1])\n# Also, we will discard any invalid value.\nvalid_precip_values = train_precip[-1][~np.isnan(train_precip[-1])]\n\n# Plot the histogram\nbins= np.concatenate( ([-0.01,0.01], np.linspace(1,40,39)))\nplt.hist(valid_precip_values,bins=bins,log=True, edgecolor='black')\nplt.autoscale(tight=True, axis='x')\nplt.xlabel(\"Rainfall intensity [mm/h]\")\nplt.ylabel(\"Counts\")\nplt.title('Precipitation rain rate histogram in mm/h units')\nplt.show()\n```\n\nThe histogram shows that rain rate values have a non-Gaussian and asymmetric distribution that is bounded at zero. Also, the probability of occurrence decays extremely fast with increasing rain rate values (note the logarithmic y-axis).\n\n\nFor better performance of the motion estimation algorithms, we can convert the rain rate values (in mm/h) to a more log-normal distribution  of rain rates by applying the following logarithmic transformation:\n\n\\begin{equation}\nR\\rightarrow\n\\begin{cases}\n    10\\log_{10}R, & \\text{if } R\\geq 0.1\\text{mm h$^{-1}$} \\\\\n    -15,          & \\text{otherwise}\n\\end{cases}\n\\end{equation}\n\nThe transformed precipitation corresponds to logarithmic rain rates in units of dBR. The value of \u221215 dBR is equivalent to assigning a rain rate of approximately 0.03 mm h$^{\u22121}$ to the zeros. \n\n\n```python\nfrom pysteps.utils import transformation\n\n# Log-transform the data to dBR. \n# The threshold of 0.1 mm/h sets the fill value to -15 dBR.\ntrain_precip_dbr, metadata_dbr = transformation.dB_transform(train_precip, metadata, \n                                                             threshold=0.1, \n                                                             zerovalue=-15.0)\n```\n\nLet's inspect the resulting **transformed precipitation** distribution.\n\n\n```python\n# Only use the valid data!\nvalid_precip_dbr = train_precip_dbr[-1][~np.isnan(train_precip_dbr[-1])]\n\nplt.figure(figsize=(4, 4), dpi=100)\n\n# Plot the histogram\ncounts, bins, _ = plt.hist(valid_precip_dbr, bins=40, log=True, edgecolor=\"black\")\nplt.autoscale(tight=True, axis=\"x\")\nplt.xlabel(\"Rainfall intensity [dB]\")\nplt.ylabel(\"Counts\")\nplt.title(\"Precipitation rain rate histogram in dB units\")\n\n# Let's add a lognormal distribution that fits that data to the plot.\nimport scipy\n\nbin_center = (bins[1:] + bins[:-1]) * 0.5\nbin_width = np.diff(bins)\n\n# We will only use one composite to fit the function to speed up things.\n# First, remove the no precip areas.\"\nprecip_to_fit = valid_precip_dbr[valid_precip_dbr > -15] \n\nfit_params = scipy.stats.lognorm.fit(precip_to_fit)\n\nfitted_pdf = scipy.stats.lognorm.pdf(bin_center, *fit_params)\n\n# Multiply pdf by the bin width and the total number of grid points: pdf -> total counts per bin.\nfitted_pdf = fitted_pdf * bin_width * precip_to_fit.size\n\n# Plot the log-normal fit\nplt.plot(bin_center, fitted_pdf, label=\"Fitted log-normal\")\nplt.legend()\nplt.show()\n```\n\nThat looks more like a log-normal distribution. Note the large peak at -15dB. That peak corresponds to \"zero\" (below threshold) precipitation. The jump with no data in between -15 and -10 dB is caused by the precision of the data, which we had set to 1 decimal. Hence, the lowest precipitation intensities (above zero) are 0.1 mm/h (= -10 dB).\n\n## Compute the nowcast\n\nThese are the minimal steps to compute a short-term forecast using Lagrangian extrapolation of the precipitation patterns:\n \n 1. Estimate the precipitation motion field.\n 1. Use the motion field to advect the most recent radar rainfall field and produce an extrapolation forecast.\n\n### Estimate the motion field\n\nNow we can estimate the motion field. Here we use a local feature-tracking approach (Lucas-Kanade).\nHowever, check the other methods available in the [pysteps.motion](https://pysteps.readthedocs.io/en/latest/pysteps_reference/motion.html) module.\n\n\n```python\n# Estimate the motion field with Lucas-Kanade\nfrom pysteps import motion\nfrom pysteps.visualization import plot_precip_field, quiver\n\n# Import the Lucas-Kanade optical flow algorithm\noflow_method = motion.get_method(\"LK\")\n\n# Estimate the motion field from the training data (in dBR)\nmotion_field = oflow_method(train_precip_dbr)\n\n## Plot the motion field.\n# Use a figure size that looks nice ;)\nplt.figure(figsize=(9, 5), dpi=100)\nplt.title(\"Estimated motion field with the Lukas-Kanade algorithm\")\n\n# Plot the last rainfall field in the \"training\" data.\n# Remember to use the mm/h precipitation data since plot_precip_field assumes \n# mm/h by default. You can change this behavior using the \"units\" keyword.\nplot_precip_field(train_precip[-1], geodata=metadata, axis=\"off\")\n\n# Plot the motion field vectors\nquiver(motion_field, geodata=metadata, step=40)\n\nplt.show()\n```\n\n### Extrapolate the observations\n\nWe have all ingredients to make an extrapolation nowcast now. \nThe final step is to advect the most recent radar rainfall field along the estimated motion field, producing an extrapolation forecast.\n\n\n```python\nfrom pysteps import nowcasts\n\nstart = time.time()\n\n# Extrapolate the last radar observation\nextrapolate = nowcasts.get_method(\"extrapolation\")\n\n# You can use the precipitation observations directly in mm/h for this step.\nlast_observation = train_precip[-1]\n\nlast_observation[~np.isfinite(last_observation)] = metadata[\"zerovalue\"]\n\n# We set the number of leadtimes (the length of the forecast horizon) to the \n# length of the observed/verification preipitation data. In this way, we'll get\n# a forecast that covers these time intervals.\nn_leadtimes = observed_precip.shape[0]\n\n# Advect the most recent radar rainfall field and make the nowcast.\nprecip_forecast = extrapolate(train_precip[-1], motion_field, n_leadtimes)\n\n# This shows the shape of the resulting array with [time intervals, rows, cols]\nprint(\"The shape of the resulting array is: \", precip_forecast.shape)\n\nend = time.time()\nprint(\"Advecting the radar rainfall fields took \", (end - start), \" seconds\")\n```\n\nLet's inspect the last forecast time (hence this is the forecast rainfall an hour ahead).\n\n\n```python\n# Plot precipitation at the end of the forecast period.\nplt.figure(figsize=(9, 5), dpi=100)\nplot_precip_field(precip_forecast[-1], geodata=metadata, axis=\"off\", map='cartopy')\nplt.show()\n```\n\n## Evaluate the forecast quality\n\nMany verification methods are already present in pysteps (see a complete list [here](https://pysteps.readthedocs.io/en/latest/pysteps_reference/verification.html)). We just have to import them. \n\nHere, we will evaluate our forecast using the Fractions Skill Score (FSS). \nThis metric provides an intuitive assessment of the dependency of forecast skill on spatial scale and intensity. This makes the FSS an ideal skill score for high-resolution precipitation forecasts.\n\nMore precisely, the FSS is a neighborhood spatial verification method that directly compares the fractional coverage of events in windows surrounding the observations and forecasts.\nThe FSS varies from 0 (total mismatch) to 1 (perfect forecast).\nFor most situations, an FSS value of > 0.5 serves as a good indicator of a useful forecast ([Roberts and Lean, 2008](https://journals.ametsoc.org/doi/full/10.1175/2007MWR2123.1) and [Skok and Roberts, 2016](https://rmets.onlinelibrary.wiley.com/doi/full/10.1002/qj.2849)). \n\n\n```python\nfrom pysteps import verification\n\nfss = verification.get_method(\"FSS\")\n\n# Compute fractions skill score (FSS) for all lead times for different scales using a 1 mm/h detection threshold.\nscales = [\n    2,\n    4,\n    8,\n    16,\n    32,\n    64,\n]  # In grid points.\n\nscales_in_km = np.array(scales)*4\n\n# Set the threshold\nthr = 1.0  # in mm/h\n\nscore = []\n\n# Calculate the FSS for every lead time and all predefined scales.\nfor i in range(n_leadtimes):\n    score_ = []\n    for scale in scales:\n        score_.append(\n            fss(precip_forecast[i, :, :], observed_precip[i, :, :], thr, scale)\n        )\n    score.append(score_)\n\n# Now plot it\nplt.figure()\nx = np.arange(1, n_leadtimes+1) * timestep\nplt.plot(x, score, lw=2.0)\nplt.xlabel(\"Lead time [min]\")\nplt.ylabel(\"FSS ( > 1.0 mm/h ) \")\nplt.title(\"Fractions Skill Score\")\nplt.legend(\n    scales_in_km, \n    title=\"Scale [km]\",\n    loc=\"center left\",\n    bbox_to_anchor=(1.01, 0.5),\n    bbox_transform=plt.gca().transAxes,\n)\nplt.autoscale(axis=\"x\", tight=True)\nplt.show()\n```\n\nAs you can see, the FSS decreases with increasing lead time.\nThis is expected, as the forecasting quality slowly decreases when we forecast further ahead.\nUpscaling the forecast, however, clearly leads to higher skill (up to longer ahead) compared to the forecast on the highest resolutions.\n\n## Concluding remarks\nCongratulations, you have successfully made your first nowcast using the pysteps library!\nThis was a simple extrapolation-based nowcast and a lot more advanced options are possible too, see [the pysteps examples gallery](https://pysteps.readthedocs.io/en/latest/auto_examples/index.html) for some nice examples.\n", "meta": {"hexsha": "edda94c170e6664152499a80558d123a6967d980", "size": 29549, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/my_first_nowcast.ipynb", "max_stars_repo_name": "alexanderhucheerful/pysteps", "max_stars_repo_head_hexsha": "efa52506bb9aff5076dc52311b72df872b09045f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-25T03:07:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-25T03:07:07.000Z", "max_issues_repo_path": "examples/my_first_nowcast.ipynb", "max_issues_repo_name": "alexanderhucheerful/pysteps", "max_issues_repo_head_hexsha": "efa52506bb9aff5076dc52311b72df872b09045f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/my_first_nowcast.ipynb", "max_forks_repo_name": "alexanderhucheerful/pysteps", "max_forks_repo_head_hexsha": "efa52506bb9aff5076dc52311b72df872b09045f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4729891957, "max_line_length": 354, "alphanum_fraction": 0.6184304037, "converted": true, "num_tokens": 4739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451488696663, "lm_q2_score": 0.03963884136997595, "lm_q1q2_score": 0.013819889750456352}}
{"text": "# Google Drive Mount\n\n\n```\nfrom google.colab import drive\r\ndrive.mount(\"/content/drive\")\n```\n\n    Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n\n\n\n```\ncd drive/My Drive\n```\n\n    [Errno 2] No such file or directory: 'drive/My Drive'\n    /content/drive/My Drive\n\n\n\n```\nls\n```\n\n    \u001b[0m\u001b[01;34m'\u110b\u1175\u11b0\u110b\u1173\u11af \u110b\u1168\u110c\u1165\u11bc\u110b\u1175\u11ab \u1102\u1169\u11ab\u1106\u116e\u11ab \u1106\u1169\u110b\u1173\u11b7'\u001b[0m/  \u001b[01;34m'01. Backup Files'\u001b[0m/   \u001b[01;34mcgcnn\u001b[0m/      \u001b[01;34mGraphGAN\u001b[0m/\n    \u001b[01;34m'00. Github'\u001b[0m/             \u001b[01;34m'02. \u1103\u1166\u110b\u1175\u1110\u1165'\u001b[0m/         \u001b[01;34mCGCNN-HD\u001b[0m/\n\n\n# CGCNN github clone\n\n\n```\n#!git clone https://github.com/txie-93/cgcnn\n```\n\n# Pymatgen Install\n\n\n```\n!pip install pymatgen==2020.11.11\n```\n\n    Requirement already satisfied: pymatgen==2020.11.11 in /usr/local/lib/python3.7/dist-packages (2020.11.11)\n    Requirement already satisfied: plotly>=4.5.0 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.11.11) (4.14.3)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.11.11) (2.23.0)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.11.11) (1.16.1)\n    Requirement already satisfied: ruamel.yaml>=0.15.6 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.11.11) (0.16.13)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.11.11) (2021.3.3)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.11.11) (3.2.2)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.11.11) (1.1.5)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.11.11) (2.5)\n    Requirement already satisfied: uncertainties>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.11.11) (3.1.5)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.11.11) (1.7.1)\n    Requirement already satisfied: scipy>=1.5.0 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.11.11) (1.6.1)\n    Requirement already satisfied: numpy>=1.14.3 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.11.11) (1.19.5)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.11.11) (0.8.9)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.11.11) (3.3.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from plotly>=4.5.0->pymatgen==2020.11.11) (1.15.0)\n    Requirement already satisfied: retrying>=1.3.3 in /usr/local/lib/python3.7/dist-packages (from plotly>=4.5.0->pymatgen==2020.11.11) (1.3.3)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2020.11.11) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2020.11.11) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2020.11.11) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2020.11.11) (2020.12.5)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\" in /usr/local/lib/python3.7/dist-packages (from ruamel.yaml>=0.15.6->pymatgen==2020.11.11) (0.2.2)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2020.11.11) (1.3.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2020.11.11) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2020.11.11) (0.10.0)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2020.11.11) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen==2020.11.11) (2018.9)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.2->pymatgen==2020.11.11) (4.4.2)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from uncertainties>=3.1.4->pymatgen==2020.11.11) (0.16.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->pymatgen==2020.11.11) (1.2.1)\n\n\n## cgcnn/cgcnn/data.py\n\n\n```\nfrom __future__ import print_function, division\r\n\r\nimport csv\r\nimport functools\r\nimport json\r\nimport os\r\nimport random\r\nimport warnings\r\n\r\nimport numpy as np\r\nimport torch\r\nfrom pymatgen.core.structure import Structure\r\nfrom torch.utils.data import Dataset, DataLoader\r\nfrom torch.utils.data.dataloader import default_collate\r\nfrom torch.utils.data.sampler import SubsetRandomSampler\n```\n\n\n```\ndef get_train_val_test_loader(dataset, collate_fn = default_collate,\r\n                              batch_size = 64, train_ratio = None,\r\n                              val_ratio = 0.1, test_ratio = 0.1, return_test = False,\r\n                              num_workers = 1, pin_memory = False, **kwargs):\r\n    \"\"\"\r\n    Utility function for dividing a dataset to train, val, test datasets.\r\n    !!! The dataset needs to be shuffled before using the function !!!\r\n\r\n    Parameters\r\n    ----------\r\n    dataset: torch.utils.data.Dataset\r\n             The full dataset to be divided.\r\n    collate_fn: torch.utils.data.DataLoader\r\n    batch_size: int\r\n    train_ratio: float\r\n    val_ratio: float\r\n    test_ratio: float\r\n    return_test: bool\r\n        Whether to return the test dataset loader. If False, the last test_size \r\n        data will be hidden.\r\n    num_workers: int\r\n    pin_memory: bool\r\n\r\n    Returns\r\n    -------\r\n    train_loader: torch.utils.data.DataLoader\r\n        DataLoader that random samples the training data.\r\n    val_loader: torch.utils.data.DataLoader\r\n        DataLoader that random samples the validation data.\r\n    (test_loader): torch.utils.data.DataLoader\r\n        DataLoader that random samples the test data, returns if\r\n        return_test = True.\r\n    \"\"\"\r\n    total_size = len(dataset)\r\n\r\n    if train_ratio is None:\r\n        assert val_ratio + test_ratio < 1\r\n        train_ratio = 1 - val_ratio - test_ratio\r\n        print('[Warning] train_ratio is None, using all training data.')\r\n    else:\r\n        assert train_ratio + val_ratio + test_ratio <= 1\r\n    \r\n    indices = list(range(total_size))\r\n\r\n    if kwargs['train_size']:\r\n        train_size = kwargs['train_size']\r\n    else:\r\n        train_size = int(train_ratio * total_size)\r\n\r\n    if kwargs['test_size']:\r\n        test_size = kwargs['test_size']\r\n    else:\r\n        test_size = int(test_ratio * total_size)\r\n    \r\n    if kwargs['val_size']:\r\n        valid_size = kwargs['val_size']\r\n    else:\r\n        valid_size = int(val_ratio * total_size)\r\n\r\n    train_sampler = SubsetRandomSampler(indices[:train_size])\r\n    val_sampler = SubsetRandomSampler(\r\n        indices[-(valid_size + test_size):-test_size])\r\n    \r\n    if return_test:\r\n        test_sampler = SubsetRandomSampler(indices[-test_size:])\r\n\r\n    train_loader = DataLoader(dataset, batch_size = batch_size,\r\n                              sampler = train_sampler,\r\n                              num_workers = num_workers,\r\n                              collate_fn = collate_fn, pin_memory = pin_memory)\r\n    val_loader = DataLoader(dataset, batch_size = batch_size,\r\n                            sampler = val_sampler,\r\n                            num_workers = num_workers,\r\n                            collate_fn = collate_fn, pin_memory = pin_memory)\r\n    if return_test:\r\n        test_loader = DataLoader(dataset, batch_size = batch_size,\r\n                                 sampler = test_sampler,\r\n                                 num_workers = num_workers,\r\n                                 collate_fn = collate_fn, pin_memory = pin_memory)\r\n    if return_test:\r\n        return train_loader, val_loader, test_loader\r\n    else:\r\n        return train_loader, val_loader \r\n        \n```\n\n\n```\ndef collate_pool(dataset_list):\r\n    \"\"\"\r\n    Collate a list of data and return a batch for predicting crystal properties.\r\n\r\n    Parameters\r\n    ----------\r\n    dataset_list: list of tuples for each data point.\r\n        (atom_fea, nbr_fea, nbr_fea_idx, target)\r\n\r\n        atom_fea: torch.Tensor shape (n_i, atom_fea_len)\r\n        nbr_fea: torch.Tensor shape (n_i, M, nbr_fea_len)\r\n        nbr_fea_idx: torch.LongTensor shape (n_i, M)\r\n        target: torch.Tensor shape (1, )\r\n        cif_id: str or int\r\n\r\n    Returns\r\n    -------\r\n    N = sum(n_i); N0 = sum(i)\r\n\r\n    batch_atom_fea: torch.Tensor shape (N, orig_atom_fea_len)\r\n        Atom features from atom type\r\n    batch_nbr_fea: torch.Tensor shape (N, M, nbr_fea_len)\r\n        Bond features of each atom's M neighbors\r\n    batch_nbr_fea_idx: torch.LongTensor shape (N, M)\r\n        Indices of M neighbors of each atom\r\n    crystal_atom_idx: list of torch.LongTensor of length N0\r\n        Mapping from the crystal idx to atom idx\r\n    target: torch.Tensor shape (N, 1)\r\n        Target value for prediction\r\n    batch_cif_ids: list\r\n    \"\"\"\r\n    batch_atom_fea, batch_nbr_fea, batch_nbr_fea_idx = [], [], []\r\n    crystal_atom_idx, batch_target = [], []\r\n    batch_cif_ids = []\r\n    base_idx = 0\r\n\r\n    for i, ((atom_fea, nbr_fea, nbr_fea_idx), target, cif_id) in enumerate(dataset_list):\r\n\r\n        n_i = atom_fea.shape[0]  # number of atoms for this crystal\r\n        \r\n        batch_atom_fea.append(atom_fea)\r\n        batch_nbr_fea.append(nbr_fea)\r\n        batch_nbr_fea_idx.append(nbr_fea_idx + base_idx)\r\n\r\n        new_idx = torch.LongTensor(np.arange(n_i) + base_idx)\r\n\r\n        crystal_atom_idx.append(new_idx)\r\n        batch_target.append(target)\r\n        batch_cif_ids.append(cif_id)\r\n\r\n        base_idx += n_i\r\n\r\n    return (torch.cat(batch_atom_fea, dim = 0),\r\n            torch.cat(batch_nbr_fea, dim = 0),\r\n            torch.cat(batch_nbr_fea_idx, dim = 0),\r\n            crystal_atom_idx), \\\r\n            torch.stack(batch_target, dim = 0), \\\r\n            batch_cif_ids\r\n\n```\n\n\n```\nclass GaussianDistance(object):\r\n    \"\"\"\r\n    Expands the distance by Gaussian basis.\r\n\r\n    Unit: angstrom\r\n    \"\"\"\r\n    def __init__(self, dmin, dmax, step, var = None):\r\n        \"\"\"\r\n        Parameters\r\n        ----------\r\n        dmin: float\r\n            Minimum interatomic distance\r\n        dmax: float\r\n            Maximum interatomic distance\r\n        step: float\r\n            Step size for the Gaussian filter\r\n        \"\"\"\r\n        assert dmin < dmax\r\n        assert dmax - dmin > step\r\n        self.filter = np.arange(dmin, dmax + step, step)\r\n        if var is None:\r\n            var = step\r\n        self.var = var\r\n\r\n    def expand(self, distances):\r\n        \"\"\"\r\n        Apply Gaussian distances filter to a numpy distance array\r\n\r\n        Parameters\r\n        ----------\r\n        distance: np.array shape n-d array\r\n            A distance matrix of any shape\r\n        \r\n        Returns\r\n        -------\r\n        expanded_distance: shape (n+1)-d array\r\n            Expanded distance matrix with the last dimension of length\r\n            len(self.filter)\r\n        \"\"\"\r\n        return np.exp(-(distances[..., np.newaxis] - self.filter)**2 / self.var**2)\r\n        \n```\n\n\n```\nclass AtomInitializer(object):\r\n    \"\"\"\r\n    Base class for initializing the vector representation for atoms.\r\n    !!! Use one AtomInitializer per dataset !!!\r\n    \"\"\"\r\n    def __init__(self, atom_types):\r\n        self.atom_types = set(atom_types)\r\n        self._embedding = {}\r\n\r\n    def get_atom_fea(self, atom_type):\r\n        assert atom_type in self.atom_types\r\n        return self._embedding[atom_type]\r\n\r\n    def load_state_dict(self, state_dict):\r\n        self._embedding = state_dict\r\n        self.atom_types = set(self._embedding.keys())\r\n        self._decodedict = {idx: atom_type for atom_type, idx in \r\n                            self._embedding.items()}\r\n\r\n    def state_dict(self):\r\n        return self._embedding\r\n\r\n    def decode(self, idx):\r\n        if not hasattr(self, '_decodedict'):\r\n            self._decodedict = {idx: atom_type for atom_type, idx in \r\n                                self._embedding.items()}\r\n        return self._decodedict[idx]\r\n        \n```\n\n\n```\nclass AtomCustomJSONInitializer(AtomInitializer):\r\n    \"\"\"\r\n    Initialize atom feature vectors using a JSON file, which is a python\r\n    dictionary mapping from element number to a list representing the \r\n    feature vector of the element.\r\n\r\n    Parameters\r\n    ----------\r\n    elem_embedding_file: str\r\n        The path to the .json file\r\n    \"\"\"\r\n    def __init__(self, elem_embedding_file):\r\n        with open(elem_embedding_file) as f:\r\n            elem_embedding = json.load(f)\r\n        elem_embedding = {int(key): value for key, value\r\n                          in elem_embedding.items()}\r\n        atom_types = set(elem_embedding.keys())\r\n        super(AtomCustomJSONInitializer, self).__init__(atom_types)\r\n        for key, value in elem_embedding.items():\r\n            self._embedding[key] = np.array(value, dtype = float)\r\n            \n```\n\n\n```\nclass CIFData(Dataset):\r\n    \"\"\"\r\n    The CIFData dataset is a wrapper for a dataset where the crystal structures\r\n    are stored in the form of CIF files. The dataset should have the following \r\n    directory structure:\r\n\r\n    root_dir\r\n    \u251c\u2500\u2500 id_prop.csv\r\n    \u251c\u2500\u2500 atom_init.json\r\n    \u251c\u2500\u2500 id0.cif\r\n    \u251c\u2500\u2500 id1.cif\r\n    \u251c\u2500\u2500 ...\r\n\r\n    id_prop.csv: a CSV file with two columns. The first column recodes a \r\n    unique ID for each crystal, and the second column recodes the value of\r\n    target property.\r\n\r\n    atom_init.json: a JSON file that stores the initialization vector for each\r\n    element.\r\n\r\n    ID.cif: a CIF file that recodes the crystal structure, where ID is the\r\n    unique ID for the crystal.\r\n\r\n    Parameters\r\n    ----------\r\n    root_dir: str\r\n        The path to the root directory of the dataset\r\n    max_num_nbr: int\r\n        The maximum number of neighbors while constructing the crystal graph\r\n    radius: float\r\n        The cutoff radius for searching neighbors\r\n    dmin: float\r\n        The minimum distance for constructing GaussianDistance\r\n    step: float\r\n        The step size for constructing GaussianDistance\r\n    random_seed: int\r\n        Random seed for shuffling the dataset\r\n\r\n    Returns\r\n    -------\r\n    atom_fea: torch.Tensor shape (n_i, atom_fea_len)\r\n    nbr_fea: torch.Tensor shape (n_i, M, nbr_fea_len)\r\n    nbr_fea_idx: torch.LongTensor shape (n_i, M)\r\n    target: torch.Tensor shape (1, )\r\n    cif_id: str or int\r\n    \"\"\"\r\n    def __init__(self, root_dir, max_num_nbr = 12, radius = 8, dmin = 0, step = 0.2,\r\n                 random_seed = 123):\r\n        self.root_dir = root_dir\r\n        self.max_num_nbr, self.radius = max_num_nbr, radius\r\n        assert os.path.exists(root_dir), 'root_dir does not exist!'\r\n        id_prop_file = os.path.join(self.root_dir, 'id_prop.csv')\r\n        assert os.path.exists(id_prop_file), 'id_prop.csv does not exist!'\r\n        with open(id_prop_file) as f:\r\n            reader = csv.reader(f)\r\n            self.id_prop_data = [row for row in reader]\r\n        random.seed(random_seed)\r\n        random.shuffle(self.id_prop_data)\r\n        atom_init_file = os.path.join(self.root_dir, 'atom_init.json')\r\n        assert os.path.exists(atom_init_file), 'atom_init.json does not exist!'\r\n        \r\n        self.ari = AtomCustomJSONInitializer(atom_init_file)\r\n        self.gdf = GaussianDistance(dmin = dmin, dmax = self.radius, step = step)\r\n\r\n    def __len__(self):\r\n        return len(self.id_prop_data)\r\n\r\n    @functools.lru_cache(maxsize = None)  # Cache loaded structures\r\n    def __getitem__(self, idx):\r\n        cif_id, target = self.id_prop_data[idx]\r\n        crystal = Structure.from_file(os.path.join(self.root_dir, cif_id + '.cif'))\r\n\r\n        atom_fea = np.vstack([self.ari.get_atom_fea(crystal[i].specie.number)\r\n                              for i in range(len(crystal))])\r\n        atom_fea = torch.Tensor(atom_fea)\r\n\r\n        all_nbrs = crystal.get_all_neighbors(self.radius, include_index = True)\r\n        all_nbrs = [sorted(nbrs, key = lambda x: x[1]) for nbrs in all_nbrs]\r\n\r\n        nbr_fea_idx, nbr_fea = [], []\r\n        for nbr in all_nbrs:\r\n            if len(nbr) < self.max_num_nbr:\r\n                warnings.warn('{} not find enough neighbors to build graph. '\r\n                              'If it happens frequently, consider increase '\r\n                              'radius.'.format(cif_id))\r\n                nbr_fea_idx.append(list(map(lambda x: x[2], nbr)) +\r\n                                   [0] * (self.max_num_nbr - len(nbr)))\r\n                nbr_fea.append(list(map(lambda x: x[1], nbr)) + \r\n                               [self.radius + 1.] * (self.max_num_nbr - len(nbr)))\r\n            else:\r\n                nbr_fea_idx.append(list(map(lambda x: x[2],\r\n                                            nbr[:self.max_num_nbr])))\r\n                nbr_fea.append(list(map(lambda x: x[1], \r\n                                        nbr[:self.max_num_nbr])))\r\n                \r\n        nbr_fea_idx, nbr_fea = np.array(nbr_fea_idx), np.array(nbr_fea)\r\n        nbr_fea = self.gdf.expand(nbr_fea)\r\n        atom_fea = torch.Tensor(atom_fea)\r\n        nbr_fea = torch.Tensor(nbr_fea)\r\n        nbr_fea_idx = torch.LongTensor(nbr_fea_idx)\r\n        target = torch.Tensor([float(target)])\r\n\r\n        return (atom_fea, nbr_fea, nbr_fea_idx), target, cif_id\r\n\n```\n\n## cgcnn/cgcnn/model.py\n\n\n```\nfrom __future__ import print_function, division\r\n\r\nimport torch\r\nimport torch.nn as nn\n```\n\n\n```\nclass ConvLayer(nn.Module):\r\n    \"\"\"\r\n    Convolutional operation on graphs\r\n    \"\"\"\r\n    def __init__(self, atom_fea_len, nbr_fea_len):\r\n        \"\"\"\r\n        Initialize ConvLayer.\r\n\r\n        Parameters\r\n        ----------\r\n        atom_fea_len: int\r\n            Number of atom hidden features.\r\n        nbr_fea_len: int\r\n            Number of bond features.\r\n        \"\"\"\r\n        super(ConvLayer, self).__init__()\r\n        self.atom_fea_len = atom_fea_len\r\n        self.nbr_fea_len = nbr_fea_len\r\n        self.fc_full = nn.Linear(2 * self.atom_fea_len + self.nbr_fea_len,\r\n                                 2 * self.atom_fea_len)\r\n        self.sigmoid = nn.Sigmoid()\r\n        self.softplus1 = nn.Softplus()\r\n        self.bn1 = nn.BatchNorm1d(2 * self.atom_fea_len)\r\n        self.bn2 = nn.BatchNorm1d(self.atom_fea_len)\r\n        self.softplus2 = nn.Softplus()\r\n\r\n    def forward(self, atom_in_fea, nbr_fea, nbr_fea_idx):\r\n        \"\"\"\r\n        Forward pass\r\n\r\n        N: Total number of atoms in the batch\r\n        M: Max number of neighbors\r\n\r\n        Parameters\r\n        ----------\r\n        atom_in_fea: Variable(torch.Tensor) shape (N, atom_fea_len)\r\n            Atom hidden features before convolution\r\n        nbr_fea: Variable(torch.Tensor) shape (N, M, nbr_fea_len)\r\n            Bond features of each atom's M neighbors\r\n        nbr_fea_idx: torch.LongTensor shape (N, M)\r\n            Indices of M neighbors of each atom\r\n        \r\n        Returns\r\n        -------\r\n        atom_out_fea: nn.Variable shape (N, atom_fea_len)\r\n            Atom hidden features after convolution\r\n        \"\"\"\r\n        # TODO will there be problems with the index zero padding?\r\n        N, M = nbr_fea_idx.shape\r\n\r\n        # convolution\r\n        atom_nbr_fea = atom_in_fea[nbr_fea_idx, :]\r\n        total_nbr_fea = torch.cat(\r\n            [atom_in_fea.unsqueeze(1).expand(N, M, self.atom_fea_len),\r\n             atom_nbr_fea, nbr_fea], dim = 2)\r\n        \r\n        total_gated_fea = self.fc_full(total_nbr_fea)\r\n        total_gated_fea = self.bn1(total_gated_fea.view(\r\n            -1, self.atom_fea_len * 2)).view(N, M, self.atom_fea_len * 2)\r\n        \r\n        nbr_filter, nbr_core = total_gated_fea.chunk(2, dim = 2)\r\n        nbr_filter = self.sigmoid(nbr_filter)\r\n        nbr_core = self.softplus1(nbr_core)\r\n        nbr_sumed = torch.sum(nbr_filter * nbr_core, dim = 1)\r\n        nbr_sumed = self.bn2(nbr_sumed)\r\n        out = self.softplus2(atom_in_fea + nbr_sumed)\r\n\r\n        return out\n```\n\n\n```\nclass CrystalGraphConvNet(nn.Module):\r\n    \"\"\"\r\n    Create a crystal graph convolutional neural network for predicting total\r\n    material properties.\r\n    \"\"\"\r\n    def __init__(self, orig_atom_fea_len, nbr_fea_len,\r\n                 atom_fea_len = 64, n_conv = 3, h_fea_len = 128, n_h = 1,\r\n                 classification = False):\r\n        \"\"\"\r\n        Initialize CrystalGraphConvNet.\r\n\r\n        Parameters\r\n        ----------\r\n        orig_atom_fea_len: int\r\n            Number of atom features in the input.\r\n        nbr_fea_len: int\r\n            Number of bond features.\r\n        atom_fea_len: int\r\n            Number of hidden atom features in the convolutional layers\r\n        n_conv: int\r\n            Number of convolutional layers\r\n        h_fea_len: int\r\n            Number of hidden features after pooling\r\n        n_h: int\r\n            Number of hidden layers after pooling\r\n        \"\"\"\r\n        super(CrystalGraphConvNet, self).__init__()\r\n        self.classification = classification \r\n        self.embedding = nn.Linear(orig_atom_fea_len, atom_fea_len)\r\n        self.convs = nn.ModuleList([ConvLayer(atom_fea_len = atom_fea_len,\r\n                                              nbr_fea_len = nbr_fea_len)\r\n                                              for _ in range(n_conv)])\r\n        self.conv_to_fc = nn.Linear(atom_fea_len, h_fea_len)\r\n        self.conv_to_fc_softplus = nn.Softplus()\r\n\r\n        if n_h > 1:\r\n            self.fcs = nn.ModuleList([nn.Linear(h_fea_len, h_fea_len)\r\n                                      for _ in range(n_h - 1)])\r\n            self.softpluses = nn.ModuleList([nn.Softplus()\r\n                                             for _ in range(n_h - 1)])\r\n        \r\n        if self.classification:\r\n            self.fc_out = nn.Linear(h_fea_len, 2)\r\n        else:\r\n            self.fc_out = nn.Linear(h_fea_len, 1)\r\n        \r\n        if self.classification:\r\n            self.logsoftmax = nn.LogSoftmax(dim = 1)\r\n            self.dropout = nn.Dropout()\r\n\r\n    def forward(self, atom_fea, nbr_fea, nbr_fea_idx, crystal_atom_idx):\r\n        \"\"\"\r\n        Forward pass\r\n\r\n        N: Total number of atoms in the batch\r\n        M: Max number of neighbors\r\n        N0: Total number of crystals in the batch\r\n\r\n        Parameters\r\n        ----------\r\n        atom_fea: Variable(torch.Tensor) shape (N, orig_atom_fea_len)\r\n            Atom features from atom type\r\n        nbr_fea: Variable(torch.Tensor) shape (N, M, nbr_fea_len)\r\n            Bond features of each atom's M neighbors\r\n        nbr_fea_idx: torch.LongTensor shape (N, M)\r\n            Indices of M neighbors of each atom\r\n        crystal_atom_idx: list of torch.LongTensor of length N0\r\n            Mapping from the crystal idx to atom idx\r\n\r\n        Returns\r\n        -------\r\n        prediction: nn.Variable shape (N, )\r\n            Atom hidden features after convolution\r\n        \"\"\"\r\n        atom_fea = self.embedding(atom_fea)\r\n        for conv_func in self.convs:\r\n            atom_fea = conv_func(atom_fea, nbr_fea, nbr_fea_idx)\r\n        \r\n        crys_fea = self.pooling(atom_fea, crystal_atom_idx)\r\n        crys_fea = self.conv_to_fc(self.conv_to_fc_softplus(crys_fea))\r\n        crys_fea = self.conv_to_fc_softplus(crys_fea)\r\n\r\n        if self.classification:\r\n            crys_fea = self.dropout(crys_fea)\r\n        \r\n        if hasattr(self, 'fcs') and hasattr(self, 'softpluses'):\r\n            for fc, softplus in zip(self.fcs, self.softpluses):\r\n                crys_fea = softplus(fc(crys_fea))\r\n        \r\n        out = self.fc_out(crys_fea)\r\n\r\n        if self.classification:\r\n            out = self.logsoftmax(out)\r\n        \r\n        return out\r\n\r\n    def pooling(self, atom_fea, crystal_atom_idx):\r\n        \"\"\"\r\n        Pooling the atom features to crystal features\r\n\r\n        N: Total number of atoms in the batch\r\n        N0: Total number of crystals in the batch\r\n\r\n        Parameters\r\n        ----------\r\n        atom_fea: Variable(torch.Tensor) shape (N, atom_fea_len)\r\n            Atom feature vectors of the batch\r\n        crystal_atom_idx: list of torch.LongTensor of length N0\r\n            Mapping from the crystal idx to atom idx\r\n        \"\"\"\r\n        assert sum([len(idx_map) for idx_map in crystal_atom_idx]) == \\\r\n            atom_fea.data.shape[0]\r\n        summed_fea = [torch.mean(atom_fea[idx_map], dim = 0, keepdim = True)\r\n                      for idx_map in crystal_atom_idx]\r\n        return torch.cat(summed_fea, dim = 0)\r\n\n```\n\n## cgcnn/main.py\n\n\n```\nimport argparse\r\nimport os\r\nimport shutil\r\nimport sys\r\nimport time\r\nimport warnings\r\nfrom random import sample\r\n\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nfrom sklearn import metrics\r\nfrom torch.autograd import Variable\r\nfrom torch.optim.lr_scheduler import MultiStepLR\r\n\r\n#from cgcnn.data import CIFData\r\n#from cgcnn.data import collate_pool, get_train_val_test_loader\r\n#from cgcnn.model import CrystalGraphConvNet\n```\n\n\n```\n\n```\n\n\n```\n\n```\n\n\n```\nclass Normalizer(object):\r\n    \"\"\" Normalize a Tensor and restore it later. \"\"\"\r\n\r\n    def __init__(self, tensor):\r\n        \"\"\" tensor is taken as a sample to calculate the mean and std \"\"\"\r\n        self.mean = torch.mean(tensor)\r\n        self.std = torch.std(tensor)\r\n\r\n    def norm(self, tensor):\r\n        return (tensor - self.mean) / self.std\r\n    \r\n    def denorm(self, normed_tensor):\r\n        return normed_tensor * self.std + self.mean\r\n\r\n    def state_dict(self):\r\n        return {'mean': self.mean, \r\n                'std': self.std}\r\n    \r\n    def load_state_dict(self, state_dict):\r\n        self.mean = state_dict['mean']\r\n        self.std = state_dict['std']\r\n        \n```\n\n\n```\ndef mae(prediction, target):\r\n    \"\"\"\r\n    Computes the mean absolute error between prediction and target\r\n\r\n    Parameters\r\n    ----------\r\n    prediction: torch.Tensor (N, 1)\r\n    target: torch.Tensor (N, 1)\r\n    \"\"\"\r\n    return torch.mean(torch.abs(target - prediction))\n```\n\n\n```\ndef class_eval(prediction, target):\r\n\r\n    prediction = np.exp(prediction.numpy())\r\n    target = target.numpy()\r\n\r\n    pred_label = np.argmax(prediction, axis = 1)\r\n    target_label = np.squeeze(target)\r\n\r\n    if not target_label.shape:\r\n        target_label = np.asarray([target_label])\r\n    \r\n    if prediction.shape[1] == 2:\r\n        precision, recall, fscore, _ = metrics.precision_recall_fscore_support(\r\n            target_label, pred_label, average = 'binary')\r\n        auc_score = metrics.roc_auc_score(target_label, prediction[:, 1])\r\n        accuracy = metrics.accuracy_score(target_label, pred_label)\r\n    else:\r\n        raise NotImplementedError\r\n    return accuracy, precision, recall, fscore, auc_score\n```\n\n\n```\nclass AverageMeter(object):\r\n    \"\"\" Computes and stores the average and current value \"\"\"\r\n    \r\n    def __init__(self):\r\n        self.reset()\r\n\r\n    def reset(self):\r\n        self.val = 0\r\n        self.avg = 0\r\n        self.sum = 0\r\n        self.count = 0\r\n\r\n    def update(self, val, n = 1):\r\n        self.val = val\r\n        self.sum += val * n\r\n        self.count += n\r\n        self.avg = self.sum / self.count\n```\n\n\n```\ndef save_checkpoint(state, is_best, filename=\"checkpoint.pth.tar\"):\r\n    torch.save(state, filename)\r\n    if is_best:\r\n        shutil.copyfile(filename, 'model_best.pth.tar')\n```\n\n\n```\ndef adjust_learning_rate(optimizer, epoch, k):\r\n    \"\"\" Sets the learning rate to the initial LR decayed by 10 every k epochs \"\"\"\r\n    assert type(k) is int\r\n    lr = args.lr * (0.1 ** (epoch // k))\r\n    for param_group in optimizer.param_groups:\r\n        param_group['lr'] = lr\r\n        \n```\n\n\n```\ndef train(train_loader, model, criterion, optimizer, epoch, normalizer):\r\n\r\n    batch_time = AverageMeter()\r\n    data_time = AverageMeter()\r\n    losses = AverageMeter()\r\n\r\n    if args.task == 'regression':\r\n        mae_errors = AverageMeter()\r\n    else:\r\n        accuracies = AverageMeter()\r\n        precisions = AverageMeter()\r\n        recalls = AverageMeter()\r\n        fscores = AverageMeter()\r\n        auc_scores = AverageMeter()\r\n    \r\n    # switch to train mode\r\n    model.train()\r\n\r\n    end = time.time()\r\n\r\n    for i, (input, target, _) in enumerate(train_loader):\r\n\r\n        # measure data loading time\r\n        data_time.update(time.time() - end)\r\n\r\n        if args.cuda:\r\n            input_var = (Variable(input[0].cuda(non_blocking = True)),\r\n                         Variable(input[1].cuda(non_blocking = True)),\r\n                         input[2].cuda(non_blocking = True),\r\n                         [crys_idx.cuda(non_blocking = True) for crys_idx in input[3]])\r\n        else:\r\n            input_var = (Variable(input[0]),\r\n                         Variable(input[1]),\r\n                         input[2],\r\n                         input[3])\r\n        \r\n        # normalize target\r\n        if args.task == 'regression':\r\n            target_normed = normalizer.norm(target)\r\n        else:\r\n            target_normed = target.view(-1).long()\r\n        \r\n        if args.cuda:\r\n            target_var = Variable(target_normed.cuda(non_blocking = True))\r\n        else:\r\n            target_var = Variable(target_normed)\r\n\r\n        # compute output\r\n        output = model(*input_var)\r\n        loss = criterion(output, target_var)\r\n\r\n        # measure accuracy and record loss\r\n        if args.task == 'regression':\r\n            mae_error = mae(normalizer.denorm(output.data.cpu()), target)\r\n            losses.update(loss.data.cpu(), target.size(0))\r\n            mae_errors.update(mae_error, target.size(0))\r\n        else:\r\n            accuracy, precision, recall, fscore, auc_score = \\\r\n                class_eval(output.data.cpu(), target)\r\n            losses.update(loss.data.cpu().item(), target.size(0))\r\n            accuracies.update(accuracy, target.size(0))\r\n            precisions.update(precision, target.size(0))\r\n            recalls.update(recall, target.size(0))\r\n            fscores.update(fscore, target.size(0))\r\n            auc_scores.update(auc_score, target.size(0))\r\n\r\n        # compute gradient and do SGD step\r\n        optimizer.zero_grad()\r\n        loss.backward()\r\n        optimizer.step()\r\n\r\n        # measure elapsed time\r\n        batch_time.update(time.time() - end)\r\n        end = time.time()\r\n\r\n        if i % args.print_freq == 0:\r\n            if args.task == 'regression':\r\n                print('Epoch: [{0}][{1}/{2}]\\t'\r\n                      'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\r\n                      'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\r\n                      'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\r\n                      'MAE {mae_errors.val:.3f} ({mae_errors.avg:.3f})'.format(\r\n                          epoch, i, len(train_loader), batch_time = batch_time,\r\n                          data_time = data_time, loss = losses, mae_errors = mae_errors))\r\n            else:\r\n                print('Epoch: [{0}][{1}/{2}]\\t'\r\n                      'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\r\n                      'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\r\n                      'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\r\n                      'Accu {accu.val:.3f} ({accu.avg:.3f})\\t'\r\n                      'Precision {prec.val:.3f} ({prec.avg:.3f})\\t'\r\n                      'Recall {recall.val:.3f} ({recall.avg:.3f})\\t'\r\n                      'F1 {f1.val:.3f} ({f1.avg:.3f})\\t'\r\n                      'AUC {auc.val:.3f} ({auc.avg:.3f})'.format(\r\n                          epoch, i, len(train_loader), batch_time = batch_time,\r\n                          data_time = data_time, loss = losses, accu = accuracies,\r\n                          prec = precisions, recall = recalls, f1 = fscores,\r\n                          auc = auc_scores))\r\n\n```\n\n\n```\ndef validate(val_loader, model, criterion, normalizer, test = False):\r\n\r\n    batch_time = AverageMeter()\r\n    losses = AverageMeter()\r\n\r\n    if args.task == 'regression':\r\n        mae_errors = AverageMeter()\r\n    else:\r\n        accuracies = AverageMeter()\r\n        precisions = AverageMeter()\r\n        recalls = AverageMeter()\r\n        fscores = AverageMeter()\r\n        auc_scores = AverageMeter()\r\n    \r\n    if test:\r\n        test_targets = []\r\n        test_preds = []\r\n        test_cif_ids = []\r\n\r\n    # switch to evaluate mode\r\n    model.eval()\r\n\r\n    end = time.time()\r\n\r\n    for i, (input, target, batch_cif_ids) in enumerate(val_loader):\r\n\r\n        if args.cuda:\r\n            with torch.no_grad():\r\n                input_var = (Variable(input[0].cuda(non_blocking = True)),\r\n                             Variable(input[1].cuda(non_blocking = True)),\r\n                             input[2].cuda(non_blocking = True),\r\n                             [crys_idx.cuda(non_blocking = True) for crys_idx in input[3]])\r\n        else:\r\n            with torch.no_grad():\r\n                input_var = (Variable(input[0]),\r\n                             Variable(input[1]),\r\n                             input[2],\r\n                             input[3])\r\n        if args.task == 'regression':\r\n            target_normed = normalizer.norm(target)\r\n        else:\r\n            target_normed = target.view(-1).long()\r\n\r\n        if args.cuda:\r\n            with torch.no_grad():\r\n                target_var = Variable(target_normed.cuda(non_blocking = True))\r\n        else:\r\n            with torch.no_grad():\r\n                target_var = Variable(target_normed)\r\n        \r\n        # compute output\r\n        output = model(*input_var)\r\n        loss = criterion(output, target_var)\r\n\r\n        # measure accuracy and record loss\r\n        if args.task == 'regression':\r\n            mae_error = mae(normalizer.denorm(output.data.cpu()), target)\r\n            losses.update(loss.data.cpu().item(), target.size(0))\r\n            mae_errors.update(mae_error, target.size(0))\r\n\r\n            if test:\r\n                test_pred = normalizer.denorm(output.data.cpu())\r\n                test_target = target\r\n                test_preds += test_pred.view(-1).tolist()\r\n                test_targets += test_target.view(-1).tolist()\r\n                test_cif_ids += batch_cif_ids\r\n        else:\r\n            accuracy, precision, recall, fscore, auc_score = \\\r\n                class_eval(output.data.cpu(), target)\r\n            \r\n            losses.update(loss.data.cpu().item(), target.size(0))\r\n            accuracies.update(accuracy, target.size(0))\r\n            precisions.update(precision, target.size(0))\r\n            recalls.update(recall, target.size(0))\r\n            fscores.update(fscore, target.size(0))\r\n            auc_scores.update(auc_score, target.size(0))\r\n\r\n            if test:\r\n                test_pred = torch.exp(output.data.cpu())\r\n                test_target = target\r\n                assert test_pred.shape[1] == 2\r\n                test_preds += test_pred[:, 1].tolist()\r\n                test_targets += test_target.view(-1).tolist()\r\n                test_cif_ids += batch_cif_ids\r\n        \r\n        # measure elapsed time\r\n        batch_time.update(time.time() - end)\r\n        end = time.time()\r\n\r\n        if i % args.print_freq == 0:\r\n            if args.task == 'regression':\r\n                print('Test: [{0}/{1}]\\t'\r\n                      'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\r\n                      'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\r\n                      'MAE {mae_errors.val:.3f} ({mae_errors.avg:.3f})'.format(\r\n                          i, len(val_loader), batch_time = batch_time, loss = losses,\r\n                          mae_errors = mae_errors))\r\n            else:\r\n                print('Test: [{0}/{1}]\\t'\r\n                      'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\r\n                      'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\r\n                      'Accu {accu.val:.3f} ({accu.avg:.3f})\\t'\r\n                      'Precision {prec.val:.3f} ({prec.avg:.3f})\\t'\r\n                      'Recall {recall.val:.3f} ({recall.avg:.3f})\\t'\r\n                      'F1 {f1.val:.3f} ({f1.avg:.3f})\\t'\r\n                      'AUC {auc.val:.3f} ({auc.avg:.3f})'.format(\r\n                          i, len(val_loader), batch_time = batch_time, loss = losses,\r\n                          accu = accuracies, prec = precisions, recall = recalls,\r\n                          f1 = fscores, auc = auc_scores))                \r\n    if test:\r\n        star_label = '**'\r\n        import csv\r\n        with open('test_results.csv', 'w') as f:\r\n            writer = csv.writer(f)\r\n\r\n            for cif_id, target, pred in zip(test_cif_ids, test_targets, test_preds):\r\n                writer.writerow((cif_id, target, pred))\r\n    else:\r\n        star_label = '*'\r\n\r\n\r\n    if args.task == 'regression':\r\n        print(' {star} MAE {mae_errors.avg:.3f}'.format(star = star_label,\r\n                                                        mae_errors = mae_errors))\r\n        return mae_errors.avg\r\n    else:\r\n        print(' {star} AUC {auc.avg:.3f}'.format(star = star_label,\r\n                                                 auc = auc_scores))\r\n        return auc_scores.avg\r\n        \n```\n\n\n```\n\n```\n\n\n```\n\n```\n\n\n```\n\n```\n\n\n```\n\n```\n\n\n```\n\n```\n\n\n```\n\n```\n\n\n```\n\n```\n\n\n```\n\n```\n\n\n```\n\n```\n", "meta": {"hexsha": "a733da97511ce046c5ce90c09328799e41a48818", "size": 50816, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "00. Original CGCNN code.ipynb", "max_stars_repo_name": "Amadeus-System/00.Crystal_Graph_Convolutional_Neural_Network", "max_stars_repo_head_hexsha": "02f39976d9bd78f9aee0c37308e654a762b39035", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-05-20T09:50:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T05:17:40.000Z", "max_issues_repo_path": "00. Original CGCNN code.ipynb", "max_issues_repo_name": "Amadeus-System/00.Crystal_Graph_Convolutional_Neural_Network", "max_issues_repo_head_hexsha": "02f39976d9bd78f9aee0c37308e654a762b39035", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-12T03:05:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-13T06:54:21.000Z", "max_forks_repo_path": "00. Original CGCNN code.ipynb", "max_forks_repo_name": "Amadeus-System/00.Crystal_Graph_Convolutional_Neural_Network", "max_forks_repo_head_hexsha": "02f39976d9bd78f9aee0c37308e654a762b39035", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-20T09:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T09:57:58.000Z", "avg_line_length": 50816.0, "max_line_length": 50816, "alphanum_fraction": 0.5876889169, "converted": true, "num_tokens": 9236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091279808829703, "lm_q2_score": 0.05500529294080225, "lm_q1q2_score": 0.013801531961443146}}
{"text": "# Jupyter Introduction \n\nFirst and foremost, the Jupyter Notebook is an interactive environment for writing and running code. The notebook is capable of running code in a wide range of languages. However, each notebook is associated with a single kernel.  This notebook is associated with the IPython kernel, therefor runs Python code.\n\n## Code cells allow you to enter and run code\n\nRun a code cell using `Shift-Enter` or pressing the <button class='btn btn-default btn-xs'><i class=\"icon-step-forward fa fa-step-forward\"></i></button> button in the toolbar above:\n\n\n```python\na = 10\n```\n\n\n```python\nprint(a)\n```\n\nThere are two other keyboard shortcuts for running code:\n\n* `Alt-Enter` runs the current cell and inserts a new one below.\n* `Ctrl-Enter` run the current cell and enters command mode.\n\n## Managing the Kernel\n\nCode is run in a separate process called the Kernel.  The Kernel can be interrupted or restarted.  Try running the following cell and then hit the <button class='btn btn-default btn-xs'><i class='icon-stop fa fa-stop'></i></button> button in the toolbar above.\n\n\n```python\nimport time\ntime.sleep(10)\n```\n\nIf the Kernel dies you will be prompted to restart it. Here we call the low-level system libc.time routine with the wrong argument via\nctypes to segfault the Python interpreter:\n\n\n```python\nimport sys\nfrom ctypes import CDLL\n# This will crash a Linux or Mac system\n# equivalent calls can be made on Windows\n\n# Uncomment these lines if you would like to see the segfault\n\n# dll = 'dylib' if sys.platform == 'darwin' else 'so.6'\n# libc = CDLL(\"libc.%s\" % dll) \n# libc.time(-1)  # BOOM!!\n```\n\n## Cell menu\n\nThe \"Cell\" menu has a number of menu items for running code in different ways. These includes:\n\n* Run and Select Below\n* Run and Insert Below\n* Run All\n* Run All Above\n* Run All Below\n\n## Restarting the kernels\n\nThe kernel maintains the state of a notebook's computations. You can reset this state by restarting the kernel. This is done by clicking on the <button class='btn btn-default btn-xs'><i class='fa fa-repeat icon-repeat'></i></button> in the toolbar above.\n\n## sys.stdout and sys.stderr\n\nThe stdout and stderr streams are displayed as text in the output area.\n\n\n```python\nprint(\"hi, stdout\")\n```\n\n\n```python\nfrom __future__ import print_function\nprint('hi, stderr', file=sys.stderr)\n```\n\n## Output is asynchronous\n\nAll output is displayed asynchronously as it is generated in the Kernel. If you execute the next cell, you will see the output one piece at a time, not all at the end.\n\n\n```python\nimport time, sys\nfor i in range(8):\n    print(i)\n    time.sleep(0.5)\n```\n\n## Large outputs\n\nTo better handle large outputs, the output area can be collapsed. Run the following cell and then single- or double- click on the active area to the left of the output:\n\n\n```python\nfor i in range(50):\n    print(i)\n```\n\nBeyond a certain point, output will scroll automatically:\n\n\n```python\nfor i in range(500):\n    print(2**i - 1)\n```\n\n# Markdown Cells\n\nText can be added to IPython Notebooks using Markdown cells.  Markdown is a popular markup language that is a superset of HTML. Its specification can be found here:\n\n<http://daringfireball.net/projects/markdown/>\n\n## Markdown basics\n\nYou can make text *italic* or **bold**.\n\nYou can build nested itemized or enumerated lists:\n\n* One\n    - Sublist\n        - This\n  - Sublist\n        - That\n        - The other thing\n* Two\n  - Sublist\n* Three\n  - Sublist\n\nNow another list:\n\n1. Here we go\n    1. Sublist\n    2. Sublist\n2. There we go\n3. Now this\n\nYou can add horizontal rules:\n\n---\n\nHere is a blockquote:\n\n> Beautiful is better than ugly.\n> Explicit is better than implicit.\n> Simple is better than complex.\n> Complex is better than complicated.\n> Flat is better than nested.\n> Sparse is better than dense.\n> Readability counts.\n> Special cases aren't special enough to break the rules.\n> Although practicality beats purity.\n> Errors should never pass silently.\n> Unless explicitly silenced.\n> In the face of ambiguity, refuse the temptation to guess.\n> There should be one-- and preferably only one --obvious way to do it.\n> Although that way may not be obvious at first unless you're Dutch.\n> Now is better than never.\n> Although never is often better than *right* now.\n> If the implementation is hard to explain, it's a bad idea.\n> If the implementation is easy to explain, it may be a good idea.\n> Namespaces are one honking great idea -- let's do more of those!\n\nAnd shorthand for links:\n\n[IPython's website](http://ipython.org)\n\n### Headings\n\nIf you want, you can add headings using Markdown's syntax:\n\n```\n# Heading 1\n# Heading 2\n## Heading 2.1\n## Heading 2.2\n```\n\n**BUT most of the time you should use the Notebook's Heading Cells to organize your Notebook content**, as they provide meaningful structure that can be interpreted by other tools, not just large bold fonts.\n\n### Embedded code\n\nYou can embed code meant for illustration instead of execution in Python:\n\n    def f(x):\n        \"\"\"a docstring\"\"\"\n        return x**2\n\nor other languages:\n\n    if (i=0; i<n; i++) {\n      printf(\"hello %d\\n\", i);\n      x += 4;\n    }\n\n### LaTeX equations\n\nCourtesy of MathJax, you can include mathematical expressions both inline: \n$e^{i\\pi} + 1 = 0$  and displayed:\n\n$$e^x=\\sum_{i=0}^\\infty \\frac{1}{i!}x^i$$\n\n### Github flavored markdown (GFM)\n\nThe Notebook webapp support Github flavored markdown meaning that you can use triple backticks for code blocks \n<pre>\n```python\nprint \"Hello World\"\n```\n\n```javascript\nconsole.log(\"Hello World\")\n```\n</pre>\n\nGives \n```python\nprint \"Hello World\"\n```\n\n```javascript\nconsole.log(\"Hello World\")\n```\n\nAnd a table like this : \n\n<pre>\n| This | is   |\n|------|------|\n|   a  | table| \n</pre>\n\nA nice Html Table\n\n| This | is   |\n|------|------|\n|   a  | table| \n\n### General HTML\n\nBecause Markdown is a superset of HTML you can even add things like HTML tables:\n\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n\n### Local files\n\nIf you have local files in your Notebook directory, you can refer to these files in Markdown cells directly:\n\n    [subdirectory/]<filename>\n\nFor example, in the images folder, we have the Python logo:\n\n    \n\n\n\nand a video with the HTML5 video tag:\n\n    <video controls src=\"images/jupyter-basics-animation.m4v\" />\n\n<video controls src=\"images/jupyter-basics-animation.m4v\" />\n\nThese do not embed the data into the notebook file, and require that the files exist when you are viewing the notebook.\n\n### Security of local files\n\nNote that this means that the IPython notebook server also acts as a generic file server\nfor files inside the same tree as your notebooks.  Access is not granted outside the\nnotebook folder so you have strict control over what files are visible, but for this\nreason it is highly recommended that you do not run the notebook server with a notebook\ndirectory at a high level in your filesystem (e.g. your home directory).\n\nWhen you run the notebook in a password-protected manner, local file access is restricted\nto authenticated users unless read-only views are active.\n\n# Rich Output\n\nIn Python, objects can declare their textual representation using the `__repr__` method.  IPython expands on this idea and allows objects to declare other, rich representations including:\n\n* HTML\n* JSON\n* PNG\n* JPEG\n* SVG\n* LaTeX\n\nA single object can declare some or all of these representations; all are handled by IPython's *display system*. This Notebook shows how you can use this display system to incorporate a broad range of content into your Notebooks.\n\n## Basic display imports\n\nThe `display` function is a general purpose tool for displaying different representations of objects. Think of it as `print` for these rich representations.\n\n\n```python\nfrom IPython.display import display\n```\n\nA few points:\n\n* Calling `display` on an object will send **all** possible representations to the Notebook.\n* These representations are stored in the Notebook document.\n* In general the Notebook will use the richest available representation.\n\nIf you want to display a particular representation, there are specific functions for that:\n\n\n```python\nfrom IPython.display import (\n    display_pretty, display_html, display_jpeg,\n    display_png, display_json, display_latex, display_svg\n)\n```\n\n## Images\n\nTo work with images (JPEG, PNG) use the `Image` class.\n\n\n```python\nfrom IPython.display import Image\n```\n\n\n```python\ni = Image(filename='images/jupyter-basics-logo.png')\n```\n\nReturning an `Image` object from an expression will automatically display it:\n\n\n```python\ni\n```\n\nOr you can pass an object with a rich representation to `display`:\n\n\n```python\ndisplay(i)\n```\n\nAn image can also be displayed from raw data or a URL.\n\n\n```python\nImage(url='http://python.org/images/python-logo.gif')\n```\n\nSVG images are also supported out of the box.\n\n\n```python\nfrom IPython.display import SVG\nSVG(filename='images/jupyter-basics-python-logo.svg')\n```\n\n### Embedded vs non-embedded Images\n\nBy default, image data is embedded in the notebook document so that the images can be viewed offline. However it is also possible to tell the `Image` class to only store a *link* to the image. Let's see how this works using a webcam at Berkeley.\n\n\n```python\nfrom IPython.display import Image\nimg_url = 'http://www.lawrencehallofscience.org/static/scienceview/scienceview.berkeley.edu/html/view/view_assets/images/newview.jpg'\n\n# by default Image data are embedded\nEmbed      = Image(img_url)\n\n# if kwarg `url` is given, the embedding is assumed to be false\nSoftLinked = Image(url=img_url)\n\n# In each case, embed can be specified explicitly with the `embed` kwarg\n# ForceEmbed = Image(url=img_url, embed=True)\n```\n\nHere is the embedded version. Note that this image was pulled from the webcam when this code cell was originally run and stored in the Notebook. Unless we rerun this cell, this is not todays image.\n\n\n```python\nEmbed\n```\n\nHere is today's image from same webcam at Berkeley, (refreshed every minutes, if you reload the notebook), visible only with an active internet connection, that should be different from the previous one. Notebooks saved with this kind of image will be smaller and always reflect the current version of the source, but the image won't display offline.\n\n\n```python\nSoftLinked\n```\n\nOf course, if you re-run this Notebook, the two images will be the same again.\n\n## HTML\n\nPython objects can declare HTML representations that will be displayed in the Notebook. If you have some HTML you want to display, simply use the `HTML` class.\n\n\n```python\nfrom IPython.display import HTML\n```\n\n\n```python\ns = \"\"\"<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\"\"\"\n```\n\n\n```python\nh = HTML(s)\n```\n\n\n```python\ndisplay(h)\n```\n\nYou can also use the `%%html` cell magic to accomplish the same thing.\n\n\n```python\n%%html\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n```\n\n## JavaScript\n\nThe Notebook also enables objects to declare a JavaScript representation. At first, this may seem odd as  output is inherently visual and JavaScript is a programming language. However, this opens the door for rich output that leverages the full power of JavaScript and associated libraries such as [d3.js](http://d3js.org) for output.\n\n\n```python\nfrom IPython.display import Javascript\n```\n\nPass a string of JavaScript source code to the `JavaScript` object and then display it.\n\n\n```python\njs = Javascript('alert(\"hi\")');\n```\n\n\n```python\ndisplay(js)\n```\n\nThe same thing can be accomplished using the `%%javascript` cell magic:\n\n\n```javascript\n%%javascript\n\nalert(\"hi\");\n```\n\nHere is a more complicated example that loads `d3.js` from a CDN, uses the `%%html` magic to load CSS styles onto the page and then runs ones of the `d3.js` examples.\n\n\n```python\nJavascript(\n    \"\"\"$.getScript('//cdnjs.cloudflare.com/ajax/libs/d3/3.2.2/d3.v3.min.js')\"\"\"\n)\n```\n\n\n```python\n%%html\n<style type=\"text/css\">\n\ncircle {\n  fill: rgb(31, 119, 180);\n  fill-opacity: .25;\n  stroke: rgb(31, 119, 180);\n  stroke-width: 1px;\n}\n\n.leaf circle {\n  fill: #ff7f0e;\n  fill-opacity: 1;\n}\n\ntext {\n  font: 10px sans-serif;\n}\n\n</style>\n```\n\n\n```javascript\n%%javascript\n\n// element is the jQuery element we will append to\nvar e = element.get(0);\n    \nvar diameter = 600,\n    format = d3.format(\",d\");\n\nvar pack = d3.layout.pack()\n    .size([diameter - 4, diameter - 4])\n    .value(function(d) { return d.size; });\n\nvar svg = d3.select(e).append(\"svg\")\n    .attr(\"width\", diameter)\n    .attr(\"height\", diameter)\n  .append(\"g\")\n    .attr(\"transform\", \"translate(2,2)\");\n\nd3.json(\"data/flare.json\", function(error, root) {\n  var node = svg.datum(root).selectAll(\".node\")\n      .data(pack.nodes)\n    .enter().append(\"g\")\n      .attr(\"class\", function(d) { return d.children ? \"node\" : \"leaf node\"; })\n      .attr(\"transform\", function(d) { return \"translate(\" + d.x + \",\" + d.y + \")\"; });\n\n  node.append(\"title\")\n      .text(function(d) { return d.name + (d.children ? \"\" : \": \" + format(d.size)); });\n\n  node.append(\"circle\")\n      .attr(\"r\", function(d) { return d.r; });\n\n  node.filter(function(d) { return !d.children; }).append(\"text\")\n      .attr(\"dy\", \".3em\")\n      .style(\"text-anchor\", \"middle\")\n      .text(function(d) { return d.name.substring(0, d.r / 3); });\n});\n\nd3.select(self.frameElement).style(\"height\", diameter + \"px\");\n```\n\n## LaTeX\n\nThe IPython display system also has builtin support for the display of mathematical expressions typeset in LaTeX, which is rendered in the browser using [MathJax](http://mathjax.org).\n\nYou can pass raw LaTeX test as a string to the `Math` object:\n\n\n```python\nfrom IPython.display import Math\nMath(r'F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx')\n```\n\nWith the `Latex` class, you have to include the delimiters yourself.  This allows you to use other LaTeX modes such as `eqnarray`:\n\n\n```python\nfrom IPython.display import Latex\nLatex(r\"\"\"\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\"\"\")\n```\n\nOr you can enter LaTeX directly with the `%%latex` cell magic:\n\n\n```latex\n%%latex\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n```\n\n## Audio\n\nIPython makes it easy to work with sounds interactively. The `Audio` display class allows you to create an audio control that is embedded in the Notebook. The interface is analogous to the interface of the `Image` display class. All audio formats supported by the browser can be used. Note that no single format is presently supported in all browsers.\n\n\n```python\nfrom IPython.display import Audio\nAudio(url=\"http://www.nch.com.au/acm/8k16bitpcm.wav\")\n```\n\nA NumPy array can be auralized automatically. The `Audio` class normalizes and encodes the data and embeds the resulting audio in the Notebook.\n\nFor instance, when two sine waves with almost the same frequency are superimposed a phenomena known as [beats](https://en.wikipedia.org/wiki/Beat_%28acoustics%29) occur. This can be auralised as follows:\n\n\n```python\nimport numpy as np\nmax_time = 3\nf1 = 220.0\nf2 = 224.0\nrate = 8000.0\nL = 3\ntimes = np.linspace(0,L,rate*L)\nsignal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times)\n\nAudio(data=signal, rate=rate)\n```\n\n## Video\n\nMore exotic objects can also be displayed, as long as their representation supports the IPython display protocol.  For example, videos hosted externally on YouTube are easy to load:\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('sjfsUzECqK0')\n```\n\nUsing the nascent video capabilities of modern browsers, you may also be able to display local\nvideos.  At the moment this doesn't work very well in all browsers, so it may or may not work for you;\nwe will continue testing this and looking for ways to make it more robust.  \n\nThe following cell loads a local file called  `animation.m4v`, encodes the raw video as base64 for http\ntransport, and uses the HTML5 video tag to load it. On Chrome 15 it works correctly, displaying a control bar at the bottom with a play/pause button and a location slider.\n\n\n```python\nfrom IPython.display import HTML\nfrom base64 import b64encode\nvideo = open(\"images/jupyter-basics-animation.m4v\", \"rb\").read()\nvideo_encoded = b64encode(video).decode('ascii')\nvideo_tag = '<video controls alt=\"test\" src=\"data:video/x-m4v;base64,{0}\">'.format(video_encoded)\nHTML(data=video_tag)\n```\n\n## External sites\n\nYou can even embed an entire page from another site in an iframe; for example this is today's Wikipedia\npage for mobile users:\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('http://jupyter.org', width='100%', height=350)\n```\n\n## Links to local files\n\nIPython provides builtin display classes for generating links to local files. Create a link to a single file using the `FileLink` object:\n\n\n```python\nfrom IPython.display import FileLink, FileLinks\nFileLink('Cell Magics.ipynb')\n```\n\nAlternatively, to generate links to all of the files in a directory, use the `FileLinks` object, passing `'.'` to indicate that we want links generated for the current working directory. Note that if there were other directories under the current directory, `FileLinks` would work in a recursive manner creating links to files in all sub-directories as well.\n\n\n```python\nFileLinks('.')\n```\n\n## Rich output and security\n\nThe IPython Notebook allows arbitrary code execution in both the IPython kernel and in the browser, though HTML and JavaScript output. More importantly, because IPython has a JavaScript API for running code in the browser, HTML and JavaScript output can actually trigger code to be run in the kernel. This poses a significant security risk as it would allow IPython Notebooks to execute arbitrary code on your computers.\n\nTo protect against these risks, the IPython Notebook has a security model that specifies how dangerous output is handled. Here is a short summary:\n\n* When you run code in the Notebook, all rich output is displayed.\n* When you open a notebook, rich output is only displayed if it doesn't contain security vulberabilities, ...\n* ... or if you have trusted a notebook, all rich output will run upon opening it.\n\nA full description of the IPython security model can be found on [this page](http://ipython.org/ipython-doc/dev/notebook/security.html).\n\n## Rich output and nbviewer\n\nMuch of the power of the Notebook is that it enables users to share notebooks with each other using http://nbviewer.ipython.org, without installing IPython locally. As of IPython 2.0, notebooks rendered on nbviewer will display all output, including HTML and JavaScript. Furthermore, to provide a consistent JavaScript environment on the live Notebook and nbviewer, the following JavaScript libraries are loaded onto the nbviewer page, *before* the notebook and its output is displayed:\n\n* [jQuery](http://jquery.com/)\n* [RequireJS](http://requirejs.org/)\n\nLibraries such as [mpld3](http://mpld3.github.io/) use these capabilities to generate interactive visualizations that work on nbviewer.\n\n# Next Steps\n\n- [Python Basics](./python-basics-tutorial.ipynb): Learn the basics about python data types.\n- [Jupyter Tipps & Tricks](./jupyter-tipps.ipynb): Explore some amazing functionalities that you can use with Jupyter within the workspace.\n- [Visualization in Jupyter](./visualization-tutorial.ipynb): Introduction to data visualization with various common charting tools.\n- [Introduction to Pandas](./pandas-tutorial.ipynb): Introduction to the data structures and functionalities of the pandas library.\n", "meta": {"hexsha": "3fb33995b74c701ad12112f91e5926b82f496078", "size": 41960, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "resources/tutorials/tutorials/jupyter-basics-tutorial.ipynb", "max_stars_repo_name": "yarikoptic/ml-workspace", "max_stars_repo_head_hexsha": "99d7d727b7092872953bc1a05b78dbce1e7275b7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2554, "max_stars_repo_stars_event_min_datetime": "2019-05-28T06:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:24:39.000Z", "max_issues_repo_path": "resources/tutorials/tutorials/jupyter-basics-tutorial.ipynb", "max_issues_repo_name": "yarikoptic/ml-workspace", "max_issues_repo_head_hexsha": "99d7d727b7092872953bc1a05b78dbce1e7275b7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 101, "max_issues_repo_issues_event_min_datetime": "2019-07-30T21:36:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T17:55:43.000Z", "max_forks_repo_path": "resources/tutorials/tutorials/jupyter-basics-tutorial.ipynb", "max_forks_repo_name": "yarikoptic/ml-workspace", "max_forks_repo_head_hexsha": "99d7d727b7092872953bc1a05b78dbce1e7275b7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 350, "max_forks_repo_forks_event_min_datetime": "2019-06-04T13:01:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T01:32:38.000Z", "avg_line_length": 26.225, "max_line_length": 495, "alphanum_fraction": 0.5602478551, "converted": true, "num_tokens": 5174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08151974928043643, "lm_q2_score": 0.16885695423297595, "lm_q1q2_score": 0.013765176573330328}}
{"text": "<a href=\"https://colab.research.google.com/github/chandrusuresh/CarND-Path-Planning-Project/blob/master/PathPlanningProject.ipynb\" target=\"_parent\"></a>\n\n# Path Planning Project\n\nIn this project, a demonstration of a path planning algorithm is presented to help a vehicle navigate a busy highway as fast as possible within the speed limit of 50mph and as safe as possible without any collisions. There are 3 lanes on the highway and the path planning algorithm needs to choose an appropriate lane and speed for navigation. This demonstration is based on a simulator developed by Udacity and was completed as part of Udacity's Self-Driving Car Nanodegree. The [Udacity github repo](https://github.com/udacity/CarND-Path-Planning-Project) for this project has all the details about the software used in the simulator and the installation instructions.\n\n### Summary of Setup Instructions\n1. The project uses [uWebSocketIO](https://github.com/uNetworking/uWebSockets) for communication between the user-written algorithm and the simulator. Udacity has provided bash scripts to install this in both [Linux](https://github.com/udacity/CarND-Path-Planning-Project/blob/master/install-ubuntu.sh)/[Mac](https://github.com/udacity/CarND-Path-Planning-Project/blob/master/install-mac.sh) environments. These scripts are included in this repo.\n2. The simulator can be downloaded from [here](https://github.com/udacity/self-driving-car-sim/releases/tag/T3_v1.2).\n3. To run the simulator on Mac/Linux, first make the binary file executable with the following: `sudo chmod u+x term3_sim.x86_64`.\n\n### Basic Build Instructions (Linux/Mac)\n1. Clone this repo.\n2. Make a build directory: `mkdir build && cd build`\n3. Compile: `cmake .. && make`\n4. Run it: `./path_planning`\nThis should setup a listener for the code to get data from the simulator.\n5. Launch the simulator from a terminal: `./term3_sim.x86_64`.\n6. Select the Path Planning project and click start to start the simulation.\n\nThese steps should get any user in a Linux/Mac environment up and running with the code.\n\n## Goals & Problem Specifications\nThe goal of this project is to develop a path planning algorithm to safely navigate a car around a virtual highway with other traffic that is driving \u00b110 MPH of the 50 MPH speed limit. The car's localization and sensor fusion data will be provided along with a sparse map list of waypoints around the highway. The car is supposed to maintain speeds as close as possible to the 50 MPH speed limit, which means passing slower traffic when possible. The algorithm is to avoid collision with other cars and keep the car within the marked road lanes at all times, unless during lane change maneuvers. The final goal is for the car to complete one loop around the 6946m highway (~5 minutes at 50 MPH) with acceleration and jerk strictly less than over 10 ms^-2^ & 10 ms^-2^ respectively.\n\n## Map\nThe map of the highway is in `data/highway_map.txt`\n\nEach waypoint in the list contains [x,y,s,dx,dy] values. x and y are the waypoint's map coordinate position, the s value is the distance along the road to get to that waypoint in meters, the dx and dy values define the unit normal vector pointing outward of the highway loop.\n\nThe highway's waypoints loop around so the frenet s value, distance along the road, goes from 0 to 6945.554.\n\n## Localization\nMain car's localization Data (No Noise) is avilable as:\n*   [\"x\"]     The car's x position in map coordinates\n*   [\"y\"]     The car's y position in map coordinates\n*   [\"s\"]     The car's s position in frenet coordinates\n*   [\"d\"]     The car's d position in frenet coordinates\n*   [\"yaw\"]   The car's yaw angle in the map\n*   [\"speed\"] The car's speed in MPH\n\n## Sensor Fusion\nSensor fusion data containing a list of all other car's (noise-free) attributes on the same side of the road is available as the following 2D vector.\n\n[\"sensor_fusion\"] A 2d vector of cars\nEach item in the 2d vector is a vector containing the following info of each nearby car:\n*   unique ID\n*   x position in map coordinates\n*   y position in map coordinates\n*   x velocity in m/s\n*   y velocity in m/s\n*   Distance along road (s position in frenet coordinates)\n*   Cross-track error (d position in frenet coordinates)\n\n## Other Implementation Details\n*   The car uses a perfect controller and will visit every (x,y) point in the trajectory list every .02 seconds. The units for the (x,y) points are in meters and the spacing of the points determines the speed of the car. The vector going from a point to the next point in the list dictates the angle of the car. Acceleration both in the tangential and normal directions is measured along with the jerk (the rate of change of total acceleration). The (x,y) point paths that the planner recieves should not have a total acceleration that goes over 10 m/s^2, also the jerk should not go over 50 m/s^3. (NOTE: As this is BETA, these requirements might change. Also currently jerk is over a .02 second interval, it would probably be better to average total acceleration over 1 second and measure jerk from that.\n\n*   There will be some latency between the simulator running and the path planner returning a path, with optimized code usually its not very long maybe just 1-3 time steps. During this delay the simulator will continue using points that it was last given, because of this its a good idea to store the last points you have used so you can have a smooth transition. previous_path_x, and previous_path_y can be helpful for this transition since they show the last points given to the simulator controller with the processed points already removed. You would either return a path that extends this previous path or make sure to create a new path that has a smooth transition with this last path.\n\n\n## Details\n\n### Finite State Machine\nGiven that the highway to navigate has a fixed number of lanes (= 3), the following states are defined for the finite state machine.\n*   Keep Lane (KL) - This state essentially finds a trajectory that keeps the car within the current lane. The car is initialized at the start of the simulation to this state.\n*   Planning Lane Change Left/Right (PLCL/PLCR) - This state maintains the KL trajectory while adjusting the speed of the car to prepare the car for a lane change maneuver. The lane change is executed as soon as the safety and speed constraints are satisfied. Details of these conditions are described in subsequent sections.\n*   Lane Change Left/Right (LCL/LCR) - This state corresponds to when the car is executing the lane change maneuver. This is the only state where the car is allowed to cross between lanes.\n*   (Optional) Abort Lane Change- This state is critical for safety requirement, but is not an explicit part of this FSM. The safety and speed constraints mentioned above are constantly checked during the LCL/LCR states and when violated will change the state to KL. This state is specified here for the sake of completeness, but will not be discussed further.\n\n\n\n\n\n### Algorithm\n1. Initialize state to `KL`. Set Reference Velocity `ref_vel = 0`\n2. Get all cars within threshold `range=100m` of ego car.\n3. Find the closest cars ahead and behind of the ego car in each lane and get their speeds.\n4. Check if lane change is feasible by comparing the speeds & ranges of closest cars in neighboring lanes.\n> 1. A lane change criteria is set based on the current FSM state as follows:\n>> 1. In `KL`: `laneChangeCriteria=20 m`\n>> 2. In `PLCL/PLCR`: `laneChangeCriteria=15 m`\n>> 3. In `LCL/LCR`: `laneChangeCriteria=10 m`\n> 2. In each lane, $i$:\n>> 1. Get the states of the closest vehicle ahead  (indexed by $j$) and behind  ($k$) the ego car.\n>> 2. If both the cars $j$ & $k$ are within `laneChangeCriteria`, lane change is not feasible. Set $`PLC[i]=false`.\n>> 3. If `PLC[i] != false`, compute the following metric, $\\delta_i$:\n$$ \\begin{align} \\Delta s_i = s_{j,i} - s_e \\\\ \\Delta v_i = v_e - v_{j,i} \\\\ \\delta_i = \\frac{\\Delta s_i}{\\Delta v_i} - \\frac{\\Delta v_i}{a_{\\max}}\\end{align}$$  where $a_{\\max}$ is acceleration limit.\n>> 4. If $\\delta_i > 0$ for both the cars $j$ & $k$, lane change is feasible. Set `PLC[i]=true`.\n5. We compute reference speeds for ego car for each lane $i$ based on the speeds of the closest cars $j$ & $k$  \n> 1. For the closest car ahead: $v1_{i} = \\max(v_{j,i},v_e - a_{\\max}\\Delta t)$\n> 2. For the closest car behind: $v2_{i} = v_{k,i}$\n\n>>>> $v_{ref,i} = \\min(v_e + a_{\\max}\\Delta t,v1_i,v2_i,\\text{Speed Limit})$\n\n6. Trajectories from current lane to the middle of every other lane $i$ are generated by interpolating a spline from current position to the middle of each lane for a distance `100 m` ahead.\n7. Each of the trajectories are evaluated against a cost metric to pick the best next lane (and FSM state). \n> 1. Speed Cost: A speed cost function is for each lane determines a metric that takes into account the difference of speed from the speed limit and how close each car is to the ego car for each lane.\n$$ \\text{Speed Cost}(i) = \\frac{1}{n_i}\\sum_{p=1}^{n_i}{\\frac{\\text{Speed Limit} - v_{p,i}}{\\lvert s_e - s_{p,i} \\rvert}} $$\n> 2. Lane Change Cost: To prevent constant switching between lanes, a lane change penalty of 0.5 if applied as a factor to the speed cost function value for each lane change. For each lane $i$:\n>> * If $i == \\text{current lane}$: `Lane change cost(i) = 1.0`\n>> * If $i \\ne \\text{current lane}$ & `PLC[i] = true`: `Lane change cost(i) = 0.5`\n>> * Else: `Lane change cost(i) = 1000` since lane change is not feasible.\n> 3. $\\text{Total Cost(i)} = \\text{Lane change cost(i)} \\times \\text{Speed Cost}(i)$\n8. From the total costs, the next FSM state is determined by:\n> 1. If `current state = KL` & $\\arg\\min(\\text{Total Cost}) == \\text{current lane}$, `next_state = KL`\n> 2. If `current state = KL` & $\\arg\\min(\\text{Total Cost}) < \\text{current lane}$, `next_state = PLCL`\n> 3. If `current state = KL` & $\\arg\\min(\\text{Total Cost}) > \\text{current lane}$, `next_state = PLCR`\n\n\nThis scheme supports a double lane change maneuver as a sequence of multiple single lane change maneuvers. The algorithm also supports aborting lane changes either in the `PLCL/PLCR` or `LCL/LCR` states.\n\n\n\n\n\n\n\n\n### Map & Coordinate Systems\nThe `map_waypoints_s`,`map_waypoints_x` & `map_waypoints_y` are 1D vectors containing the frenet-s (distance from start of loop), global X and global \nY coordinate of the highway.\n\n### Car States\nThe state of each car is defined by a vector of size 6 defined by:\n*   unique ID (-1 for ego car)\n*   Lane ID\n*   Distance along road (s position in frenet coordinates)\n*   Cross-track error (d position in frenet coordinates)\n*   x velocity in m/s\n*   y velocity in m/s\n\n### Get Closest Cars\nA threshold for tracking closest cars is set to 100m. From the sensor fusion data, all the cars that are within this range of the ego-car are determined and their motion predicted for the next time step. Based on this prediction, the lane location of these nearby cars is determined.\n", "meta": {"hexsha": "761aa405d88969a4e1ed4435c8eecc0bdae32277", "size": 14590, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "PathPlanningProject.ipynb", "max_stars_repo_name": "chandrusuresh/CarND-Path-Planning-Project", "max_stars_repo_head_hexsha": "f3a9c73bf3e86b14bbc5c851046e2c973dc99e54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PathPlanningProject.ipynb", "max_issues_repo_name": "chandrusuresh/CarND-Path-Planning-Project", "max_issues_repo_head_hexsha": "f3a9c73bf3e86b14bbc5c851046e2c973dc99e54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PathPlanningProject.ipynb", "max_forks_repo_name": "chandrusuresh/CarND-Path-Planning-Project", "max_forks_repo_head_hexsha": "f3a9c73bf3e86b14bbc5c851046e2c973dc99e54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.6180257511, "max_line_length": 819, "alphanum_fraction": 0.6278958191, "converted": true, "num_tokens": 2765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2598256379609837, "lm_q2_score": 0.05261895334771377, "lm_q1q2_score": 0.013671753122408968}}
{"text": "```python\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.font_manager as mfm\nimport os\nimport numpy as np\nimport scipy as sp\nfrom datetime import timedelta \nimport datetime\nimport yfinance as yf\n```\n\n\n```python\n_CHN_FONT_ = None\n_FONT_PROP_ = None\n_CHN_EN_DICT_ = './data/locationDict.csv'\n_CHN_LatLng_DICT_ = './data/lat_lng.csv'\n# The province names in China\n# Ignore Hong Kong, Macau, Taiwan and Tibet\n# English name\nnames_province = ['Anhui', 'Beijing', 'Chongqing', 'Fujian', 'Gansu', 'Guangdong', 'Guangxi', 'Guizhou',\n                  'Hainan', 'Hebei', 'Heilongjiang', 'Henan', 'Hubei', 'Hunan', 'Inner Mongolia', 'Jiangsu',\n                  'Jiangxi', 'Jilin', 'Liaoning', 'Ningxia', 'Qinghai', 'Shaanxi', 'Shandong', 'Shanghai',\n                  'Shanxi', 'Sichuan', 'Tianjin', 'Xinjiang', 'Yunnan', 'Zhejiang']\n# Chinese name\nnames_province_cn = ['\u5b89\u5fbd\u7701', '\u5317\u4eac\u5e02', '\u91cd\u5e86\u5e02', '\u798f\u5efa\u7701', '\u7518\u8083\u7701', '\u5e7f\u4e1c\u7701', '\u5e7f\u897f\u58ee\u65cf\u81ea\u6cbb\u533a', '\u8d35\u5dde\u7701',\n                     '\u6d77\u5357\u7701', '\u6cb3\u5317\u7701', '\u9ed1\u9f99\u6c5f\u7701', '\u6cb3\u5357\u7701', '\u6e56\u5317\u7701', '\u6e56\u5357\u7701', '\u5185\u8499\u53e4\u81ea\u6cbb\u533a', '\u6c5f\u82cf\u7701',\n                     '\u6c5f\u897f\u7701', '\u5409\u6797\u7701', '\u8fbd\u5b81\u7701', '\u5b81\u590f\u56de\u65cf\u81ea\u6cbb\u533a', '\u9752\u6d77\u7701', '\u9655\u897f\u7701', '\u5c71\u4e1c\u7701', '\u4e0a\u6d77\u5e02',\n                     '\u5c71\u897f\u7701', '\u56db\u5ddd\u7701', '\u5929\u6d25\u5e02', '\u65b0\u7586\u7ef4\u543e\u5c14\u81ea\u6cbb\u533a', '\u4e91\u5357\u7701', '\u6d59\u6c5f\u7701']\n\n# A one to one corrspondence with the names used by Pyecharts\npyecharts_province_dict = {'\u5317\u4eac\u5e02':'\u5317\u4eac', '\u5929\u6d25\u5e02':'\u5929\u6d25', '\u6cb3\u5317\u7701':'\u6cb3\u5317', '\u5c71\u897f\u7701':'\u5c71\u897f', \n                           '\u5185\u8499\u53e4\u81ea\u6cbb\u533a':'\u5185\u8499\u53e4', '\u8fbd\u5b81\u7701':'\u8fbd\u5b81', '\u5409\u6797\u7701':'\u5409\u6797', '\u9ed1\u9f99\u6c5f\u7701':'\u9ed1\u9f99\u6c5f', \n                           '\u4e0a\u6d77\u5e02':'\u4e0a\u6d77', '\u6c5f\u82cf\u7701':'\u6c5f\u82cf', '\u6d59\u6c5f\u7701':'\u6d59\u6c5f', '\u5b89\u5fbd\u7701':'\u5b89\u5fbd', \n                           '\u798f\u5efa\u7701':'\u798f\u5efa', '\u6c5f\u897f\u7701':'\u6c5f\u897f', '\u5c71\u4e1c\u7701':'\u5c71\u4e1c', '\u6cb3\u5357\u7701':'\u6cb3\u5357', \n                           '\u6e56\u5317\u7701':'\u6e56\u5317','\u6e56\u5357\u7701':'\u6e56\u5357', '\u5e7f\u4e1c\u7701':'\u5e7f\u4e1c', '\u5e7f\u897f\u58ee\u65cf\u81ea\u6cbb\u533a':'\u5e7f\u897f', \n                           '\u6d77\u5357\u7701':'\u6d77\u5357', '\u91cd\u5e86\u5e02':'\u91cd\u5e86', '\u56db\u5ddd\u7701':'\u56db\u5ddd', '\u8d35\u5dde\u7701':'\u8d35\u5dde', \n                           '\u4e91\u5357\u7701':'\u4e91\u5357', '\u897f\u85cf\u81ea\u6cbb\u533a':'\u897f\u85cf', '\u9655\u897f\u7701':'\u9655\u897f', '\u7518\u8083\u7701':'\u7518\u8083', \n                           '\u9752\u6d77\u7701':'\u9752\u6d77', '\u5b81\u590f\u56de\u65cf\u81ea\u6cbb\u533a':'\u5b81\u590f', '\u65b0\u7586\u7ef4\u543e\u5c14\u81ea\u6cbb\u533a':'\u65b0\u7586', \n                           '\u9999\u6e2f\u7279\u522b\u884c\u653f\u533a':'\u9999\u6e2f', '\u6fb3\u95e8\u7279\u522b\u884c\u653f\u533a':'\u6fb3\u95e8','\u53f0\u6e7e\u7701':'\u53f0\u6e7e'}\n\n# English names of the capital cities of provinces\nprovincial_capital_dict = {'Anhui':'Hefei', 'Fujian':'Fuzhou', 'Gansu':'Lanzhou','Guangdong':'Guangzhou','Guizhou':'Guiyang', \n                           'Hainan':'Haikou', 'Hebei':'Shijiazhuang','Heilongjiang':'Harbin', 'Henan':'Zhengzhou',\n                           'Hubei':'Wuhan', 'Hunan':'Changsha', 'Jiangsu':'Nanjing', 'Jiangxi':'Nanchang', \n                           'Jilin':'Changchun', 'Liaoning':'Shenyang', 'Qinghai':'Xining', 'Shaanxi':'Xi\u2019an', \n                           'Shandong':'Jinan', 'Shanxi':'Taiyuan', 'Sichuan':'Chengdu', 'Yunnan':'Kunming', \n                           'Zhejiang':'Hangzhou', 'Guangxi':'Nanning','Inner Mongolia':'Hohhot', 'Ningxia':'Yinchuan',\n                           'Xinjiang':'\u00dcr\u00fcmqi', 'Tibet':'Lhasa', 'Beijing':'Beijing', 'Chongqing':'Chongqing', \n                           'Shanghai':'Shanghai', 'Tianjin':'Tianjin'}\n\nprovincial_capital_dict_cn = {'Anhui':'\u5408\u80a5\u5e02', 'Fujian':'\u798f\u5dde\u5e02', 'Gansu':'\u5170\u5dde\u5e02','Guangdong':'\u5e7f\u5dde\u5e02','Guizhou':'\u8d35\u9633\u5e02', \n                           'Hainan':'\u6d77\u53e3\u5e02', 'Hebei':'\u77f3\u5bb6\u5e84\u5e02','Heilongjiang':'\u54c8\u5c14\u6ee8\u5e02', 'Henan':'\u90d1\u5dde\u5e02',\n                           'Hubei':'\u6b66\u6c49\u5e02', 'Hunan':'\u957f\u6c99\u5e02', 'Jiangsu':'\u5357\u4eac\u5e02', 'Jiangxi':'\u5357\u660c\u5e02', \n                           'Jilin':'\u957f\u6625\u5e02', 'Liaoning':'\u6c88\u9633\u5e02', 'Qinghai':'\u897f\u5b81\u5e02', 'Shaanxi':'\u897f\u5b89\u5e02', \n                           'Shandong':'\u6d4e\u5357\u5e02', 'Shanxi':'\u592a\u539f\u5e02', 'Sichuan':'\u6210\u90fd\u5e02', 'Yunnan':'\u6606\u660e\u5e02', \n                           'Zhejiang':'\u676d\u5dde\u5e02', 'Guangxi':'\u5357\u5b81\u5e02','Inner Mongolia':'\u547c\u548c\u6d69\u7279\u5e02', 'Ningxia':'\u94f6\u5ddd\u5e02',\n                           'Xinjiang':'\u4e4c\u9c81\u6728\u9f50\u5e02', 'Tibet':'\u62c9\u8428\u5e02', 'Beijing':'\u5317\u4eac\u5e02', 'Chongqing':'\u91cd\u5e86\u5e02', \n                           'Shanghai':'\u4e0a\u6d77\u5e02', 'Tianjin':'\u5929\u6d25\u5e02'}\n\n# Populations of provinces\n# data source: http://www.chamiji.com/2019chinaprovincepopulation\n# unit 10,000\nprovincial_population_dict = {'Anhui':6323.6, 'Fujian':3941, 'Gansu': 2637.26,'Guangdong':11346,'Guizhou':3600, \n                           'Hainan':934.32, 'Hebei':7556.30,'Heilongjiang':3773.1, 'Henan':9605,\n                           'Hubei':5917, 'Hunan':6898.8, 'Jiangsu':8050.7, 'Jiangxi':4647.6, \n                           'Jilin':2704.06, 'Liaoning':4359.3, 'Qinghai':603.23, 'Shaanxi':3864.4, \n                           'Shandong':10047.24, 'Shanxi':3718.34, 'Sichuan':8341, 'Yunnan':4800.5, \n                           'Zhejiang':5737, 'Guangxi':4926,'Inner Mongolia':2534.0, 'Ningxia':688.11,\n                           'Xinjiang':2486.76, 'Tibet':337.15, 'Beijing':2154.2, 'Chongqing': 3101.79, \n                           'Shanghai':2423.78, 'Tianjin':1559.60}\n# Populations of cities\n# data source: http://www.chamiji.com/\n# unit 10,000\ncity_population_dict = {'\u5317\u4eac\u5e02':2154.2, '\u5929\u6d25\u5e02':1559.60, '\u4e0a\u6d77\u5e02':2423.78, '\u91cd\u5e86\u5e02':3101.79,\n                        '\u4eb3\u5dde\u5e02':523.7, '\u516d\u5b89\u5e02':483.7, '\u5408\u80a5\u5e02':808.7, '\u5b89\u5e86\u5e02':469.1, '\u5ba3\u57ce\u5e02':264.8, '\u5bbf\u5dde\u5e02':568.14, # \u5b89\u5fbd\u7701\n                        '\u6c60\u5dde\u5e02':147.4, '\u6dee\u5317\u5e02':225.4, '\u6dee\u5357\u5e02':349.0, '\u6ec1\u5dde\u5e02':411.4, '\u829c\u6e56\u5e02':374.8, '\u868c\u57e0\u5e02':339.20,\n                        '\u94dc\u9675\u5e02':162.9, '\u961c\u9633\u5e02':820.7, '\u9a6c\u978d\u5c71\u5e02':233.7, '\u9ec4\u5c71\u5e02':140.7,\n                        '\u5357\u4eac\u5e02':843.62, '\u5357\u901a\u5e02':731, '\u5bbf\u8fc1\u5e02':492.59, '\u5e38\u5dde\u5e02':472.9, '\u5f90\u5dde\u5e02':880.20, '\u626c\u5dde\u5e02':453.1, # \u6c5f\u82cf\u7701\n                        '\u65e0\u9521\u5e02':657.45, '\u6cf0\u5dde\u5e02':463.57, '\u6dee\u5b89\u5e02':492.50, '\u76d0\u57ce\u5e02':720, '\u82cf\u5dde\u5e02':1072.17, '\u8fde\u4e91\u6e2f\u5e02':452.0,\n                        '\u9547\u6c5f\u5e02':319.64,\n                        '\u4e1c\u8425\u5e02':217.21, '\u4e34\u6c82\u5e02':1062.4, '\u5a01\u6d77\u5e02':283, '\u5fb7\u5dde\u5e02':581, '\u65e5\u7167\u5e02':293.03, '\u67a3\u5e84\u5e02':392.73, # \u5c71\u4e1c\u7701\n                        '\u6cf0\u5b89\u5e02':564.0, '\u6d4e\u5357\u5e02':746.04, '\u6d4e\u5b81\u5e02':834.59, '\u6dc4\u535a\u5e02':470.2, '\u6ee8\u5dde\u5e02':392.25, '\u6f4d\u574a\u5e02':937.3,\n                        '\u70df\u53f0\u5e02':712.18, '\u804a\u57ce\u5e02':606.43, '\u83cf\u6cfd\u5e02':876.5, '\u9752\u5c9b\u5e02':939.48, \n                        '\u4e3d\u6c34\u5e02':219.25, '\u53f0\u5dde\u5e02':613.90, '\u5609\u5174\u5e02':472.6, '\u5b81\u6ce2\u5e02':820.2, '\u676d\u5dde\u5e02':980.6, '\u6e29\u5dde\u5e02':925, # \u6d59\u6c5f\u7701\n                        '\u6e56\u5dde\u5e02':301.09, '\u7ecd\u5174\u5e02':503.5, '\u821f\u5c71\u5e02':117.3, '\u8862\u5dde\u5e02':220.9, '\u91d1\u534e\u5e02':560.4, \n                        '\u4e09\u660e\u5e02':258, '\u5357\u5e73\u5e02':269, '\u53a6\u95e8\u5e02':411, '\u5b81\u5fb7\u5e02':291, '\u6cc9\u5dde\u5e02':870, '\u6f33\u5dde\u5e02':514.0, # \u798f\u5efa\u7701\n                        '\u798f\u5dde\u5e02':774, '\u8386\u7530\u5e02':290.0, '\u9f99\u5ca9\u5e02':264, \n                        '\u4e1c\u839e\u5e02':834.25, '\u4e2d\u5c71\u5e02':326, '\u4e91\u6d6e\u5e02':326, '\u4f5b\u5c71\u5e02':765.67, '\u5e7f\u5dde\u5e02':1449.84, '\u60e0\u5dde\u5e02':477.70, # \u5e7f\u4e1c\u7701\n                        '\u63ed\u9633\u5e02':608.6, '\u6885\u5dde\u5e02':437.43, '\u6c55\u5934\u5e02':560.82, '\u6c55\u5c3e\u5e02':305.33, '\u6c5f\u95e8\u5e02':456.17, '\u6cb3\u6e90\u5e02':309.11,\n                        '\u6df1\u5733\u5e02':1252.83, '\u6e05\u8fdc\u5e02':386.0, '\u6e5b\u6c5f\u5e02':730.5, '\u6f6e\u5dde\u5e02':265.08, '\u73e0\u6d77\u5e02':176.54, '\u8087\u5e86\u5e02':411.54, \n                        '\u8302\u540d\u5e02':620.41, '\u9633\u6c5f\u5e02': 254.29, '\u97f6\u5173\u5e02':297.92, \n                        '\u5317\u6d77\u5e02':166.33, '\u5357\u5b81\u5e02':715.33, '\u5d07\u5de6\u5e02':208.68, '\u6765\u5bbe\u5e02':221.86, '\u67f3\u5dde\u5e02':400.00, '\u6842\u6797\u5e02':505.75, # \u5e7f\u897f\u58ee\u65cf\u81ea\u6cbb\u533a\n                        '\u68a7\u5dde\u5e02':303.7, '\u6cb3\u6c60\u5e02':352.35, '\u7389\u6797\u5e02': 581.08, '\u767e\u8272\u5e02':364.65, '\u8d35\u6e2f\u5e02':437.54, '\u8d3a\u5dde\u5e02':205.67,\n                        '\u94a6\u5dde\u5e02':328, '\u9632\u57ce\u6e2f\u5e02':94.02, \n                        '\u4e07\u5b81\u5e02':float(\"NaN\"), '\u4e09\u4e9a\u5e02':76.42, '\u510b\u5dde\u5e02':90.57, '\u6d77\u53e3\u5e02':227.21, '\u4e09\u6c99\u5e02':float(\"NaN\"), '\u4e1c\u65b9\u5e02':float(\"NaN\"), # \u6d77\u5357\u7701 ########## \n                        '\u4e34\u9ad8\u53bf':float(\"NaN\"), '\u4e50\u4e1c\u9ece\u65cf\u81ea\u6cbb\u53bf':float(\"NaN\"),'\u4e94\u6307\u5c71\u5e02':float(\"NaN\"),'\u4fdd\u4ead\u9ece\u65cf\u82d7\u65cf\u81ea\u6cbb\u53bf':float(\"NaN\"), '\u5b9a\u5b89\u53bf':float(\"NaN\"),'\u5c6f\u660c\u53bf':float(\"NaN\"),\n                        '\u6587\u660c\u5e02':float(\"NaN\"),'\u660c\u6c5f\u9ece\u65cf\u81ea\u6cbb\u53bf':float(\"NaN\"),'\u6f84\u8fc8\u53bf':float(\"NaN\"),'\u743c\u4e2d\u9ece\u65cf\u82d7\u65cf\u81ea\u6cbb\u53bf':float(\"NaN\"),'\u743c\u6d77\u5e02':float(\"NaN\"),'\u767d\u6c99\u9ece\u65cf\u81ea\u6cbb\u53bf':float(\"NaN\"),\n                        '\u9675\u6c34\u9ece\u65cf\u81ea\u6cbb\u53bf':float(\"NaN\"),\n                        '\u4fdd\u5b9a\u5e02':1046.92, '\u5510\u5c71\u5e02': 789.7, '\u5eca\u574a\u5e02':467.8, '\u5f20\u5bb6\u53e3\u5e02':443.3, '\u627f\u5fb7\u5e02':356.50, '\u6ca7\u5dde\u5e02':755.49, # \u6cb3\u5317\u7701\n                        '\u77f3\u5bb6\u5e84\u5e02':1087.99, '\u79e6\u7687\u5c9b\u5e02':311.08, '\u8861\u6c34\u5e02':446.04, '\u90a2\u53f0\u5e02':735.16, '\u90af\u90f8\u5e02':951.11, \n                        '\u4e4c\u5170\u5bdf\u5e03\u5e02':210.25, '\u4e4c\u6d77\u5e02':56.11, '\u5174\u5b89\u76df':160.42, '\u5305\u5934\u5e02':287.8, '\u547c\u4f26\u8d1d\u5c14\u5e02':252.92, '\u547c\u548c\u6d69\u7279\u5e02':311.5, # \u5185\u8499\u53e4\u81ea\u6cbb\u533a\n                        '\u5df4\u5f66\u6dd6\u5c14\u5e02':168.5, '\u8d64\u5cf0\u5e02':431.5, '\u901a\u8fbd\u5e02':312.87, '\u9102\u5c14\u591a\u65af\u5e02':206.87, '\u9521\u6797\u90ed\u52d2\u76df':105.16, '\u963f\u62c9\u5584\u76df':24.8,\n                        '\u4e34\u6c7e\u5e02':450.03, '\u5415\u6881\u5e02':388.56, '\u5927\u540c\u5e02':345.60, '\u592a\u539f\u5e02':442.15, '\u5ffb\u5dde\u5e02':317.20, '\u664b\u4e2d\u5e02':338.15, # \u5c71\u897f\u7701\n                        '\u664b\u57ce\u5e02':234.31, '\u6714\u5dde\u5e02':178.12, '\u8fd0\u57ce\u5e02':535.97, '\u957f\u6cbb\u5e02':346.8, '\u9633\u6cc9\u5e02':141.44, \n                        '\u4e09\u95e8\u5ce1\u5e02':227.29, '\u4fe1\u9633\u5e02':647.41, '\u5357\u9633\u5e02':1001.36, '\u5468\u53e3\u5e02':867.78, '\u5546\u4e18\u5e02':732.53, '\u5b89\u9633\u5e02':517.6, # \u6cb3\u5357\u7701\n                        '\u5e73\u9876\u5c71\u5e02':520.77, '\u5f00\u5c01\u5e02':456.49, '\u65b0\u4e61\u5e02':579.41, '\u6d1b\u9633\u5e02':688.85, '\u6d4e\u6e90\u5e02':73.27, '\u6f2f\u6cb3\u5e02':266.53,\n                        '\u6fee\u9633\u5e02':360.94, '\u7126\u4f5c\u5e02':359.07, '\u8bb8\u660c\u5e02':443.74, '\u90d1\u5dde\u5e02':1013.6, '\u9a7b\u9a6c\u5e97\u5e02':619.02, '\u9e64\u58c1\u5e02':162.73,\n                        '\u5a04\u5e95\u5e02':393.18, '\u5cb3\u9633\u5e02':579.71, '\u5e38\u5fb7\u5e02':582.7, '\u5f20\u5bb6\u754c\u5e02':153.79, '\u6000\u5316\u5e02':497.96, '\u682a\u6d32\u5e02':402.08, # \u6e56\u5357\u7701\n                        '\u6c38\u5dde\u5e02':545.21, '\u6e58\u6f6d\u5e02':286.5, '\u6e58\u897f\u571f\u5bb6\u65cf\u82d7\u65cf\u81ea\u6cbb\u5dde':264.95, '\u76ca\u9633\u5e02':441.38, '\u8861\u9633\u5e02':724.34, '\u90b5\u9633\u5e02':737.05,\n                        '\u90f4\u5dde\u5e02':474.5, '\u957f\u6c99\u5e02':815.47, \n                        '\u4ed9\u6843\u5e02':154.45, '\u5341\u5830\u5e02':341.8, '\u54b8\u5b81\u5e02':253.51, '\u5929\u95e8\u5e02':128.35, '\u5b5d\u611f\u5e02':491.50, '\u5b9c\u660c\u5e02':413.56, # \u6e56\u5317\u7701 ##########\n                        '\u6069\u65bd\u571f\u5bb6\u65cf\u82d7\u65cf\u81ea\u6cbb\u5dde':336.10, '\u6b66\u6c49\u5e02':1089.29, '\u6f5c\u6c5f\u5e02': float(\"NaN\"), '\u795e\u519c\u67b6\u6797\u533a':7.68, '\u8346\u5dde\u5e02':564.17, '\u8346\u95e8\u5e02':290.15,\n                        '\u8944\u9633\u5e02':565.4, '\u9102\u5dde\u5e02':107.69, '\u968f\u5dde\u5e02':221.05, '\u9ec4\u5188\u5e02':634.1, '\u9ec4\u77f3\u5e02':247.05, \n                        '\u4e0a\u9976\u5e02':678.34, '\u4e5d\u6c5f\u5e02':487.33, '\u5357\u660c\u5e02':546.35, '\u5409\u5b89\u5e02':494.19, '\u5b9c\u6625\u5e02':555.37, '\u629a\u5dde\u5e02':403.10, # \u6c5f\u897f\u7701 2018\n                        '\u65b0\u4f59\u5e02':118.07, '\u666f\u5fb7\u9547\u5e02':166.49, '\u840d\u4e61\u5e02':192.50, '\u8d63\u5dde\u5e02':861.2, '\u9e70\u6f6d\u5e02':116.75, \n                        '\u516d\u76d8\u6c34\u5e02':292.41, '\u5b89\u987a\u5e02':234.44, '\u6bd5\u8282\u5e02':665.97, '\u8d35\u9633\u5e02':480.20, '\u9075\u4e49\u5e02':624.83, '\u94dc\u4ec1\u5e02':315.69, # \u8d35\u5dde\u7701 2018\n                        '\u9ed4\u4e1c\u5357\u82d7\u65cf\u4f97\u65cf\u81ea\u6cbb\u5dde':352.37, '\u9ed4\u5357\u5e03\u4f9d\u65cf\u82d7\u65cf\u81ea\u6cbb\u5dde':327.1, '\u9ed4\u897f\u5357\u5e03\u4f9d\u65cf\u82d7\u65cf\u81ea\u6cbb\u5dde':286,\n                        '\u4e50\u5c71\u5e02':327.21, '\u5185\u6c5f\u5e02':375.37, '\u51c9\u5c71\u5f5d\u65cf\u81ea\u6cbb\u5dde':521.29, '\u5357\u5145\u5e02':641.79, '\u5b9c\u5bbe\u5e02':453, '\u5df4\u4e2d\u5e02':331.67, # \u56db\u5ddd\u7701 2018\n                        '\u5e7f\u5143\u5e02':266.00, '\u5e7f\u5b89\u5e02':325.0, '\u5fb7\u9633\u5e02':353.2, '\u6210\u90fd\u5e02':1604.5, '\u6500\u679d\u82b1\u5e02':123.61, '\u6cf8\u5dde\u5e02':431.72,\n                        '\u7518\u5b5c\u85cf\u65cf\u81ea\u6cbb\u5dde':118.63, '\u7709\u5c71\u5e02':297.48, '\u7ef5\u9633\u5e02':483.56, '\u81ea\u8d21\u5e02':290.14, '\u8d44\u9633\u5e02':255.3, '\u8fbe\u5dde\u5e02':568.95,\n                        '\u9042\u5b81\u5e02':323.59, '\u963f\u575d\u85cf\u65cf\u7f8c\u65cf\u81ea\u6cbb\u5dde':94.01, '\u96c5\u5b89\u5e02':153.78, \n                        '\u4e34\u6ca7\u5e02':252.60, '\u4e3d\u6c5f\u5e02':129.0, '\u4fdd\u5c71\u5e02':261.4, '\u5927\u7406\u767d\u65cf\u81ea\u6cbb\u5dde':361.88, '\u5fb7\u5b8f\u50a3\u65cf\u666f\u9887\u65cf\u81ea\u6cbb\u5dde':130.90, '\u6012\u6c5f\u5088\u50f3\u65cf\u81ea\u6cbb\u5dde':54.7, # \u4e91\u5357\u7701 2018\n                        '\u6587\u5c71\u58ee\u65cf\u82d7\u65cf\u81ea\u6cbb\u5dde':363.6, '\u6606\u660e\u5e02':678.3, '\u662d\u901a\u5e02': 553.7, '\u666e\u6d31\u5e02':262.7, '\u66f2\u9756\u5e02':612.2, '\u695a\u96c4\u5f5d\u65cf\u81ea\u6cbb\u5dde':274.40,\n                        '\u7389\u6eaa\u5e02':238.1, '\u7ea2\u6cb3\u54c8\u5c3c\u65cf\u5f5d\u65cf\u81ea\u6cbb\u5dde':471.3, '\u897f\u53cc\u7248\u7eb3\u50a3\u65cf\u81ea\u6cbb\u5dde':118.0, '\u8fea\u5e86\u85cf\u65cf\u81ea\u6cbb\u5dde':41.2,\n                        '\u54b8\u9633\u5e02':437.6, '\u5546\u6d1b\u5e02':238.13, '\u5b89\u5eb7\u5e02':266.1, '\u5b9d\u9e21\u5e02':378.10, '\u5ef6\u5b89\u5e02':226.31, '\u6986\u6797\u5e02':340.33, # \u9655\u897f\u7701\n                        '\u6c49\u4e2d\u5e02':344.93, '\u6e2d\u5357\u5e02':538.29, '\u897f\u5b89\u5e02':953.44, '\u94dc\u5ddd\u5e02':83.34,\n                        '\u4e34\u590f\u56de\u65cf\u81ea\u6cbb\u5dde':204.41, '\u5170\u5dde\u5e02':372.96, '\u5609\u5cea\u5173\u5e02':24.98, '\u5929\u6c34\u5e02':333.98, '\u5b9a\u897f\u5e02':280.84, '\u5e73\u51c9\u5e02':211.28, # \u7518\u8083\u7701\n                        '\u5e86\u9633\u5e02':200.55, '\u5f20\u6396\u5e02':122.93, '\u6b66\u5a01\u5e02':182.53, '\u7518\u5357\u85cf\u65cf\u81ea\u6cbb\u5dde':74.23, '\u767d\u94f6\u5e02':172.93, '\u9152\u6cc9\u5e02':112.36,\n                        '\u91d1\u660c\u5e02':46.92, '\u9647\u5357\u5e02':287.42, \n                        '\u679c\u6d1b\u85cf\u65cf\u81ea\u6cbb\u5dde':20.57, '\u6d77\u4e1c\u5e02':147.08, '\u6d77\u5317\u85cf\u65cf\u81ea\u6cbb\u5dde':28.3, '\u6d77\u5357\u85cf\u65cf\u81ea\u6cbb\u5dde':47.24, '\u6d77\u897f\u8499\u53e4\u65cf\u85cf\u65cf\u81ea\u6cbb\u5dde':51.52, '\u7389\u6811\u85cf\u65cf\u81ea\u6cbb\u5dde':40.95, # \u9752\u6d77\u7701\n                        '\u897f\u5b81\u5e02':235.50, '\u9ec4\u5357\u85cf\u65cf\u81ea\u6cbb\u5dde':27.42, \n                        '\u4e4c\u9c81\u6728\u9f50\u5e02':222.61, '\u4e94\u5bb6\u6e20\u5e02':float(\"NaN\"), '\u4f0a\u7281\u54c8\u8428\u514b\u81ea\u6cbb\u5dde':461.71, '\u514b\u5b5c\u52d2\u82cf\u67ef\u5c14\u514b\u5b5c\u81ea\u6cbb\u5dde':62.06, '\u514b\u62c9\u739b\u4f9d\u5e02':44.28, '\u5317\u5c6f\u5e02':float(\"NaN\"), # \u65b0\u7586\u7ef4\u543e\u5c14\u81ea\u6cbb\u533a 2018 ##########\n                        '\u535a\u5c14\u5854\u62c9\u8499\u53e4\u81ea\u6cbb\u5dde':47.54, '\u53cc\u6cb3\u5e02':float(\"NaN\"), '\u53ef\u514b\u8fbe\u62c9\u5e02':float(\"NaN\"), '\u5410\u9c81\u756a\u5e02':63.73, '\u548c\u7530\u5730\u533a':252.28, '\u54c8\u5bc6\u5e02':56.11,\n                        '\u5580\u4ec0\u5730\u533a':464.97, '\u56fe\u6728\u8212\u514b\u5e02':float(\"NaN\"), '\u5854\u57ce\u5730\u533a':15.2, '\u5df4\u97f3\u90ed\u695e\u8499\u53e4\u81ea\u6cbb\u5dde':127.93, '\u6606\u7389\u5e02':float(\"NaN\"), '\u660c\u5409\u56de\u65cf\u81ea\u6cbb\u5dde':161,\n                        '\u77f3\u6cb3\u5b50\u5e02':float(\"NaN\"), '\u94c1\u95e8\u5173\u5e02':float(\"NaN\"), '\u963f\u514b\u82cf\u5730\u533a':254.6, '\u963f\u52d2\u6cf0\u5730\u533a':67.16, '\u963f\u62c9\u5c14\u5e02':float(\"NaN\"),\n                        '\u4e2d\u536b\u5e02':115.75, '\u5434\u5fe0\u5e02':140.37, '\u56fa\u539f\u5e02':122.82, '\u77f3\u5634\u5c71\u5e02':80.29, '\u94f6\u5ddd\u5e02':222.54, # \u5b81\u590f\u56de\u65cf\u81ea\u6cbb\u533a 2018\n                        '\u5409\u6797\u5e02':415.35, '\u56db\u5e73\u5e02':320.4, '\u5ef6\u8fb9\u671d\u9c9c\u65cf\u81ea\u6cbb\u5dde':210.14, '\u677e\u539f\u5e02':275.41, '\u767d\u57ce\u5e02':190.9, '\u767d\u5c71\u5e02':119.5, # \u5409\u6797\u7701 2018\n                        '\u8fbd\u6e90\u5e02':117.94, '\u901a\u5316\u5e02':217.15, '\u957f\u6625\u5e02':748.9,\n                        '\u4e39\u4e1c\u5e02':239.5, '\u5927\u8fde\u5e02':698.75, '\u629a\u987a\u5e02':210.7, '\u671d\u9633\u5e02':295, '\u672c\u6eaa\u5e02':147.63, '\u6c88\u9633\u5e02':829.4, # \u8fbd\u5b81\u7701 2018\n                        '\u76d8\u9526\u5e02':143.65, '\u8425\u53e3\u5e02':243.8, '\u846b\u82a6\u5c9b\u5e02':277.0, '\u8fbd\u9633\u5e02':183.7, '\u94c1\u5cad\u5e02':299.8, '\u9526\u5dde\u5e02':296.4,\n                        '\u961c\u65b0\u5e02':186.2, '\u978d\u5c71\u5e02':344.0,\n                        '\u4e03\u53f0\u6cb3\u5e02':78.6, '\u4f0a\u6625\u5e02':115.9, '\u4f73\u6728\u65af\u5e02':234.5, '\u53cc\u9e2d\u5c71\u5e02':142.3, '\u54c8\u5c14\u6ee8\u5e02':955.0, '\u5927\u5174\u5b89\u5cad\u5730\u533a':43.93, # \u9ed1\u9f99\u6c5f\u7701 2018\n                        '\u5927\u5e86\u5e02':273.1, '\u7261\u4e39\u6c5f\u5e02':254.8, '\u7ee5\u5316\u5e02':527.6, '\u9e21\u897f\u5e02':175, '\u9e64\u5c97\u5e02':100.9, '\u9ed1\u6cb3\u5e02':160.5,\n                        '\u9f50\u9f50\u54c8\u5c14\u5e02':533.7\n                       }\n\n# Reset the unit of populations to be 1 instead of 10,000\nprovincial_population_dict.update((x, y*1e4) for x, y in provincial_population_dict.items())\ncity_population_dict.update((x, y*1e4) for x, y in city_population_dict.items())\n\n# \u5e94\u6025\u54cd\u5e94\n# \u6839\u636e\u7a81\u53d1\u516c\u5171\u536b\u751f\u4e8b\u4ef6\u6027\u8d28\u3001\u5371\u5bb3\u7a0b\u5ea6\u3001\u6d89\u53ca\u8303\u56f4\uff0c\u7a81\u53d1\u516c\u5171\u536b\u751f\u4e8b\u4ef6\u5212\u5206\u4e3a\u7279\u522b\u91cd\u5927\uff08\u2160\u7ea7\uff09\u3001\u91cd\u5927\uff08\u2161\u7ea7\uff09\u3001\u8f83\u5927\uff08\u2162\u7ea7\uff09\u548c\u4e00\u822c\uff08\u2163\u7ea7\uff09\u56db\u7ea7\u3002\n################################################\n# \u91cd\u5927\u7a81\u53d1\u516c\u5171\u536b\u751f\u4e8b\u4ef6\u4e00\u7ea7\u54cd\u5e94\n# source: \u767e\u5ea6\u767e\u79d1 2020\u5e74\u65b0\u578b\u51a0\u72b6\u75c5\u6bd2\u75ab\u60c5\n# high level responses\n# https://baijiahao.baidu.com/s?id=1656586269875684850&wfr=spider&for=pc \u5b89\u5fbd\uff0c\u5e7f\u4e1c\uff0c\u6e56\u5317\uff0c\u6e56\u5357\n# http://www.bjnews.com.cn/news/2020/01/24/679091.html \u798f\u5efa\n# https://www.thepaper.cn/newsDetail_forward_5632391 \u7518\u8083\n# http://www.bjnews.com.cn/news/2020/01/24/679044.html \u8d35\u5dde\n# http://news.sina.com.cn/c/2020-01-25/doc-iihnzahk6236313.shtml \u6d77\u5357\n# http://www.bjnews.com.cn/news/2020/01/24/679103.html \u6cb3\u5317\n# https://www.thepaper.cn/newsDetail_forward_5631343 \u9ed1\u9f99\u6c5f\n# https://news.sina.com.cn/c/2020-01-25/doc-iihnzahk6246104.shtml \u6cb3\u5357\n# http://www.xhby.net/js/sh/202001/t20200125_6484737.shtml \u6c5f\u82cf \u6c5f\u82cf\u7701\u4eba\u6c11\u653f\u5e9c\u51b3\u5b9a\uff0c\u81ea2020\u5e741\u670824\u65e524\u65f6\u8d77\uff0c...\n# https://baijiahao.baidu.com/s?id=1656604836051211594&wfr=spider&for=pc \u6c5f\u897f\uff0c\u4e91\u5357\n# https://baijiahao.baidu.com/s?id=1656695669637427999&wfr=spider&for=pc \u5409\u6797\n# https://www.thepaper.cn/newsDetail_forward_5632430 \u8fbd\u5b81\n# https://m.chinanews.com/wap/detail/zw/gn/2020/01-25/9069563.shtml \u9752\u6d77 \u9752\u6d77\u7701\u4eba\u6c11\u653f\u5e9c\u51b3\u5b9a\uff0c\u4ece2020\u5e741\u670825\u65e524\u65f6\u8d77\uff0c\u542f\u52a8\u9752\u6d77\u7701\u91cd\u5927\u7a81\u53d1\u516c\u5171\u536b\u751f\u4e8b\u4ef6\u4e00\u7ea7\u54cd\u5e94\u3002\n# http://m.news.cctv.com/2020/01/25/ARTIFJkv1OzVvBRdIenCLFzZ200125.shtml \u9655\u897f\n# http://www.mrjjxw.com/articles/2020-01-24/1402733.html \u5c71\u4e1c\n# https://www.thepaper.cn/newsDetail_forward_5633430 \u5c71\u897f 18:00\n# http://www.sc.gov.cn/10462/10464/10797/2020/1/24/3ff65fa2d2054f78b7c551c7ee961167.shtml \u56db\u5ddd 1\u670824\u65e5\u4e0b\u5348\n# https://news.163.com/20/0124/23/F3MMST4V0001899O.html \u5e7f\u897f \u81ea\u6cbb\u533a\u65b0\u578b\u51a0\u72b6\u75c5\u6bd2\u611f\u67d3\u7684\u80ba\u708e\u75ab\u60c5\u8054\u9632\u8054\u63a7\u5de5\u4f5c\u9886\u5bfc\u5c0f\u7ec4\u51b3\u5b9a\u4e8e2020\u5e741\u670824\u65e523\u65f6\u8d77\u542f\u52a8\u91cd\u5927\u7a81\u53d1\u516c\u5171\u536b\u751f\u4e8b\u4ef6I\u7ea7\u54cd\u5e94\u3002\n# http://www.gov.cn/xinwen/2020-02/26/content_5483388.htm \u5185\u8499\u53e4\n# https://wap.peopleapp.com/article/5075403/4970020 \u5b81\u590f\n# https://news.sina.com.cn/c/2020-01-25/doc-iihnzahk6244183.shtml \u65b0\u7586\n# http://www.bjnews.com.cn/feature/2020/01/29/681402.html \u897f\u85cf\n# https://baijiahao.baidu.com/s?id=1656590920870989133&wfr=spider&for=pc \u5317\u4eac\n# http://chongqing.163.com/20/0124/19/F3M9IG1B04218FF3.html \u91cd\u5e86\n# http://news.sina.com.cn/c/2020-01-24/doc-iihnzhha4524474.shtml \u4e0a\u6d77\n# http://www.xinhuanet.com/politics/2020-01/24/c_1125500208.htm \u5929\u6d25\nprovincial_response_1_dict = {'Anhui': datetime.date(int(2020),int(1),int(24)), 'Fujian': datetime.date(int(2020),int(1),int(24)), \n                            'Gansu': datetime.date(int(2020),int(1),int(25)), 'Guangdong': datetime.date(int(2020),int(1),int(23)),\n                            'Guangxi': datetime.date(int(2020),int(1),int(24)), 'Guizhou': datetime.date(int(2020),int(1),int(24)), \n                            'Hainan': datetime.date(int(2020),int(1),int(25)), 'Hebei': datetime.date(int(2020),int(1),int(24)), \n                            'Heilongjiang': datetime.date(int(2020),int(1),int(25)), 'Henan': datetime.date(int(2020),int(1),int(25)),\n                            'Hubei': datetime.date(int(2020),int(1),int(24)), 'Hunan': datetime.date(int(2020),int(1),int(23)), \n                            'Inner Mongolia': datetime.date(int(2020),int(1),int(25)), 'Jiangsu': datetime.date(int(2020),int(1),int(25)), \n                            'Jiangxi': datetime.date(int(2020),int(1),int(24)), 'Jilin': datetime.date(int(2020),int(1),int(25)), \n                            'Liaoning': datetime.date(int(2020),int(1),int(25)), 'Ningxia': datetime.date(int(2020),int(1),int(25)),\n                            'Qinghai': datetime.date(int(2020),int(1),int(26)), 'Shaanxi': datetime.date(int(2020),int(1),int(25)), \n                            'Shandong': datetime.date(int(2020),int(1),int(24)), 'Shanxi': datetime.date(int(2020),int(1),int(25)), \n                            'Sichuan': datetime.date(int(2020),int(1),int(24)), 'Xinjiang': datetime.date(int(2020),int(1),int(25)), \n                            'Yunnan': datetime.date(int(2020),int(1),int(24)), 'Zhejiang': datetime.date(int(2020),int(1),int(23)), \n                            'Beijing': datetime.date(int(2020),int(1),int(24)), 'Chongqing': datetime.date(int(2020),int(1),int(24)), \n                            'Shanghai': datetime.date(int(2020),int(1),int(24)), 'Tianjin': datetime.date(int(2020),int(1),int(24)),\n                            'Tibet': datetime.date(int(2020),int(1),int(29))}\n################################################\n# \u91cd\u5927\u7a81\u53d1\u516c\u5171\u536b\u751f\u4e8b\u4ef6\u4e8c\u7ea7\u54cd\u5e94\n# http://www.gov.cn/xinwen/2020-02/26/content_5483389.htm \u5b89\u5fbd\u81ea2020\u5e742\u670825\u65e512\u65f6\u8d77\n# http://www.gov.cn/xinwen/2020-02/27/content_5483772.htm \u798f\u5efa \u81ea2020\u5e742\u670826\u65e524\u65f6\u8d77\uff0c\u5c06\u6211\u7701\u65b0\u51a0\u80ba\u708e\u75ab\u60c5\u4e2d\u98ce\u9669\u533a\u7531\u6267\u884c\u7a81\u53d1\u516c\u5171\u536b\u751f\u4e8b\u4ef6\u4e00\u7ea7\u54cd\u5e94\u8c03\u6574\u4e3a\u6267\u884c\u65b0\u51a0\u80ba\u708e\u75ab\u60c5\u9632\u63a7\u7701\u7ea7\u4e8c\u7ea7\u54cd\u5e94\uff0c\u5c06\u4f4e\u98ce\u9669\u533a\u7531\u6267\u884c\u7a81\u53d1\u516c\u5171\u536b\u751f\u4e8b\u4ef6\u4e00\u7ea7\u54cd\u5e94\u8c03\u6574\u4e3a\u6267\u884c\u65b0\u51a0\u80ba\u708e\u75ab\u60c5\u9632\u63a7\u7701\u7ea7\u4e09\u7ea7\u54cd\u5e94\u3002\n# http://www.gansu.gov.cn/art/2020/3/1/art_35_448301.html \u7518\u8083 2\u670821\u65e5\uff0c\u5728\u7a81\u53d1\u516c\u5171\u536b\u751f\u4e8b\u4ef6\u4e00\u7ea7\u5e94\u6025\u54cd\u5e9428\u5929\u4e4b\u540e\uff0c\u7518\u8083\u7701\u65b0\u51a0\u80ba\u708e\u75ab\u60c5\u8054\u9632\u8054\u63a7\u9886\u5bfc\u5c0f\u7ec4\u529e\u516c\u5ba4\u53d1\u51fa\u516c\u544a\uff0c\u51b3\u5b9a\u81ea\u5f53\u65e514\u65f6\u8d77\uff0c\u5c06\u5168\u7701\u65b0\u51a0\u80ba\u708e\u75ab\u60c5\u9632\u63a7\u7ea7\u522b\u7531\u4e00\u7ea7\u5e94\u6025\u54cd\u5e94\u8c03\u6574\u4e3a\u7701\u7ea7\u4e09\u7ea7\u5e94\u6025\u54cd\u5e94\u3002\n# http://news.cnr.cn/native/city/20200224/t20200224_524989445.shtml \u5e7f\u4e1c \u4eca\u5929\uff082\u670824\u65e5\uff09\u4e0b\u5348\uff0c\u5c06\u91cd\u5927\u7a81\u53d1\u516c\u5171\u536b\u751f\u4e8b\u4ef6\u4e00\u7ea7\u54cd\u5e94\u8c03\u6574\u4e3a\u4e8c\u7ea7\u54cd\u5e94\u76f8\u5173\u60c5\u51b5\u3002\n# http://m.guilinlife.com/news/article/docid/137-458196 \u5e7f\u897f \u81ea2\u670824\u65e520\u65f6\u8d77\uff0c\u4e00\u7ea7\u54cd\u5e94\u8c03\u6574\u4e3a\u4e09\u7ea7\u54cd\u5e94\u3002\n# http://www.xinhuanet.com/local/2020-02/24/c_1125617023.htm \u8d35\u5dde \u81ea2020\u5e742\u670823\u65e524\u65f6\u8d77\uff0c\u4e00\u7ea7\u54cd\u5e94\u8c03\u6574\u4e3a\u7701\u7ea7\u4e09\u7ea7\u54cd\u5e94\u3002\n# http://www.gov.cn/xinwen/2020-02/26/content_5483666.htm \u6d77\u5357 \u65b0\u534e\u793e\u6d77\u53e32\u670826\u65e5\u7535\uff08\u8bb0\u8005 \u9648\u51ef\u59ff\uff09\u6d77\u5357\u7701\u65b0\u51a0\u80ba\u708e\u9632\u63a7\u9886\u5bfc\u5c0f\u7ec426\u65e5\u51b3\u5b9a\uff0c\u81ea\u5f53\u592917\u65f6\u8d77\uff0c\u4e00\u7ea7\u54cd\u5e94\u8c03\u6574\u4e3a\u4e09\u7ea7\u54cd\u5e94\u3002\n# http://www.gov.cn/xinwen/2020-04/29/content_5507536.htm \u6cb3\u5317 \u5929\u6d25 \u6cb3\u5317\u7701\u51b3\u5b9a\u81ea2020\u5e744\u670830\u65e5\u8d77\uff0c\u5c06\u5168\u7701\u7a81\u53d1\u516c\u5171\u536b\u751f\u4e8b\u4ef6\u5e94\u6025\u54cd\u5e94\u7ea7\u522b\u7531\u4e00\u7ea7\u8c03\u6574\u4e3a\u4e8c\u7ea7\u3002\u81ea2020\u5e744\u670830\u65e5\u96f6\u65f6\u8d77\uff0c\u5929\u6d25\u5e02\u91cd\u5927\u7a81\u53d1\u516c\u5171\u536b\u751f\u4e8b\u4ef6\u5e94\u6025\u54cd\u5e94\u7ea7\u522b\u7531\u4e00\u7ea7\u8c03\u6574\u4e3a\u4e8c\u7ea7\u3002\n# http://china.caixin.com/2020-03-25/101533875.html \u9ed1\u9f99\u6c5f \u81ea3\u670825\u65e518\u65f6\u8d77\uff0c\u4e8c\u7ea7\u54cd\u5e94\u8c03\u6574\u4e3a\u4e09\u7ea7\u54cd\u5e94\u3002\u6b64\u524d\uff0c3\u67084\u65e5\uff0c\u7531\u4e00\u7ea7\u8c03\u6574\u4e3a\u4e8c\u7ea7\u3002\n# https://www.yicai.com/news/100554642.html \u6cb3\u5357 \u81ea3\u670819\u65e50\u65f6\u8d77\n# http://www.xinhuanet.com/politics/2020-06/12/c_1126108284.htm \u6e56\u5317 5\u67082\u65e5\u5168\u7701\u7a81\u53d1\u516c\u5171\u536b\u751f\u5e94\u6025\u54cd\u5e94\u7ea7\u522b\u7531\u4e00\u7ea7\u8c03\u6574\u4e3a\u4e8c\u7ea7\u4ee5\u6765 6\u670813\u65e5\u96f6\u65f6\u8d77\uff0c\u6e56\u5317\u7701\u7a81\u53d1\u516c\u5171\u536b\u751f\u5e94\u6025\u54cd\u5e94\u7ea7\u522b\u7531\u4e8c\u7ea7\u8c03\u6574\u4e3a\u4e09\u7ea7\n# http://m.news.cctv.com/2020/03/10/ARTItx6cc0xA5qNi2EeITr1W200310.shtml \u6e56\u5357 10\u65e523\u65f6\n# http://www.nmg.xinhuanet.com/xwzx/2020-02/25/c_1125625406.htm \u5185\u8499\u53e4 \u81ea2020\u5e742\u670825\u65e524\u65f6\u8d77\uff0c\u7531\u4e00\u7ea7\u5e94\u6025\u54cd\u5e94\u8c03\u6574\u4e3a\u81ea\u6cbb\u533a\u7ea7\u4e09\u7ea7\u5e94\u6025\u54cd\u5e94\u3002\n# https://www.wjdaily.com/news/239671 \u6c5f\u82cf 2020\u5e742\u670824\u65e524\u65f6\n# http://china.caixin.com/2020-03-12/101527309.html \u6c5f\u897f 3\u670812\u65e59\u65f6\n# http://www.gov.cn/xinwen/2020-02/26/content_5483665.htm \u5409\u6797 2020\u5e742\u670826\u65e515\u65f6\n# https://china.huanqiu.com/article/9CaKrnKpyfw \u8fbd\u5b81 \u81ea2020\u5e742\u670822\u65e59\u65f6\u8d77\uff0c\u7531\u4e00\u7ea7\u5e94\u6025\u54cd\u5e94\u8c03\u6574\u4e3a\u7701\u7ea7\u4e09\u7ea7\u5e94\u6025\u54cd\u5e94\u3002\n# http://www.xinhuanet.com/2020-05/06/c_1125949706.htm \u5b81\u590f \u5e76\u81ea2\u670828\u65e518\u65f6\u8d77 \u81ea2020\u5e745\u67086\u65e517\u65f6\u8d77\n# http://www.xinhuanet.com/2020-02/26/c_1125626759.htm \u9752\u6d77 \u81ea2020\u5e742\u670826\u65e512\u65f6\u8d77\uff0c\u7531\u4e00\u7ea7\u54cd\u5e94\u8c03\u6574\u4e3a\u4e09\u7ea7\u54cd\u5e94\u3002\n# http://www.xinhuanet.com/local/2020-02/27/c_1125636256.htm \u9655\u897f \u81ea2020\u5e742\u670828\u65e50\u65f6\u8d77\uff0c\u7531\u4e00\u7ea7\u5e94\u6025\u54cd\u5e94\u8c03\u6574\u4e3a\u7701\u7ea7\u4e09\u7ea7\u5e94\u6025\u54cd\u5e94\u3002\n# http://china.caixin.com/2020-03-08/101525427.html \u5c71\u4e1c \u81ea2020\u5e743\u67087\u65e524\u65f6\u8d77\uff0c\u7531\u91cd\u5927\u7a81\u53d1\u516c\u5171\u536b\u751f\u4e8b\u4ef6\u2160\u7ea7\u54cd\u5e94\u8c03\u6574\u4e3a\u2161\u7ea7\u54cd\u5e94\u3002\n# http://www.sx.xinhuanet.com/2020-02/24/c_1125616195.htm \u5c71\u897f \u81ea2020\u5e742\u670824\u65e5\u96f6\u65f6\u8d77\n# http://www.xinhuanet.com/local/2020-02/25/c_1125625913.htm \u56db\u5ddd 2020\u5e742\u670826\u65e50\u65f6\u8d77\n# http://www.xinhuanet.com/politics/2020-02/26/c_1125627838.htm \u65b0\u7586 \u81ea2020\u5e742\u670825\u65e524\u65f6\u8d77\n# http://www.xinhuanet.com/politics/2020-02/24/c_1125616933.htm \u4e91\u5357 \u81ea2020\u5e742\u670824\u65e5\u96f6\u65f6\u8d77\uff0c\u7531\u4e00\u7ea7\u5e94\u6025\u54cd\u5e94\u8c03\u6574\u4e3a\u7701\u7ea7\u4e09\u7ea7\u5e94\u6025\u54cd\u5e94\u3002\n# http://www.xinhuanet.com/politics/2020-03/02/c_1125651043.htm \u6d59\u6c5f 3\u67082\u65e5\n# http://www.xinhuanet.com/local/2020-04/29/c_1125923588.htm \u5317\u4eac \u81ea4\u670830\u65e5\u96f6\u65f6\u8d77\n# https://www.cq.gov.cn/zwxx/jrcq/202003/t20200310_5675212.html \u91cd\u5e86 \u81ea3\u670810\u65e524\u65f6\u8d77\n# http://www.xinhuanet.com/politics/2020-03/23/c_1125754077.htm \u4e0a\u6d77 \u81ea3\u670824\u65e5\u96f6\u65f6\u8d77\n# http://www.xinhuanet.com/local/2020-04/29/c_1125924212.htm \u5929\u6d25 \u81ea4\u670830\u65e5\u96f6\u65f6\u8d77\n# https://china.huanqiu.com/article/9CaKrnKpLmO \u897f\u85cf \u81ea2020\u5e743\u67086\u65e524\u65f6\u8d77\u5c06\u897f\u85cf\u81ea\u6cbb\u533a\u7a81\u53d1\u516c\u5171\u536b\u751f\u4e8b\u4ef6\u5e94\u6025\u54cd\u5e94\u7ea7\u522b\u8c03\u6574\u4e3a\u2161\u7ea7\uff0c\u90e8\u5206\u5730\u533a\u6309\u2162\u7ea7\u54cd\u5e94\u7ba1\u7406\u3002\nprovincial_response_2_dict = {'Anhui': datetime.date(int(2020),int(2),int(25)), 'Fujian': datetime.date(int(2020),int(2),int(27)), \n                            'Gansu': None, 'Guangdong': datetime.date(int(2020),int(2),int(24)),\n                            'Guangxi': None, 'Guizhou': None, \n                            'Hainan': None, 'Hebei': datetime.date(int(2020),int(4),int(30)), \n                            'Heilongjiang': datetime.date(int(2020),int(3),int(4)), 'Henan': datetime.date(int(2020),int(3),int(19)),\n                            'Hubei': datetime.date(int(2020),int(5),int(2)), 'Hunan': datetime.date(int(2020),int(3),int(10)), \n                            'Inner Mongolia': None, 'Jiangsu': datetime.date(int(2020),int(2),int(25)), \n                            'Jiangxi': datetime.date(int(2020),int(3),int(12)), 'Jilin': datetime.date(int(2020),int(2),int(26)), \n                            'Liaoning': None, 'Ningxia': datetime.date(int(2020),int(2),int(28)),\n                            'Qinghai': None, 'Shaanxi': None, \n                            'Shandong': datetime.date(int(2020),int(3),int(8)), 'Shanxi': datetime.date(int(2020),int(2),int(24)), \n                            'Sichuan': datetime.date(int(2020),int(2),int(26)), 'Xinjiang': datetime.date(int(2020),int(2),int(26)), \n                            'Yunnan': None, 'Zhejiang': datetime.date(int(2020),int(3),int(2)), \n                            'Beijing': datetime.date(int(2020),int(4),int(30)), 'Chongqing': datetime.date(int(2020),int(3),int(11)), \n                            'Shanghai': datetime.date(int(2020),int(3),int(24)), 'Tianjin': datetime.date(int(2020),int(4),int(30)), \n                            'Tibet': datetime.date(int(2020),int(3),int(7))}\n################################################\n# http://www.xinhuanet.com/local/2020-03/15/c_1125716594.htm \u5b89\u5fbd \u81ea2020\u5e743\u670815\u65e518\u65f6\u8d77\n# http://www.fuzhou.gov.cn/zgfzzt/ylws/tfggwssjyj/202005/t20200503_3269090.htm \u798f\u5efa \u81ea2020\u5e743\u670819\u65e512\u65f6\u8d77\n# http://www.xinhuanet.com/politics/2020-05/08/c_1125956046.htm \u5e7f\u4e1c \u81ea2020\u5e745\u67089\u65e5\u96f6\u65f6\u8d77\n# http://www.xinhuanet.com/politics/2020-06/05/c_1126079750.htm \u6cb3\u5317 \u81ea2020\u5e746\u67086\u65e5\u8d77\n# http://www.xinhuanet.com/politics/2020-03/25/c_1125766966.htm \u9ed1\u9f99\u6c5f \u81ea3\u670825\u65e518\u65f6\u8d77\n# http://www.xinhuanet.com/local/2020-05/05/c_1125944833.htm \u6cb3\u5357 \u81ea5\u67086\u65e5\u96f6\u65f6\u8d77\n# http://www.xinhuanet.com/politics/2020-06/12/c_1126108036.htm \u6e56\u5317 \u81ea6\u670813\u65e5\u96f6\u65f6\u8d77\n# http://www.xinhuanet.com/local/2020-03/31/c_1125795941.htm \u6e56\u5357 3\u670831\u65e5\u7535\n# http://www.js.xinhuanet.com/2020-03/28/c_1125780043.htm \u6c5f\u82cf \u81ea2020\u5e743\u670827\u65e524\u65f6\u8d77\n# http://www.jx.xinhuanet.com/2020-03/20/c_1125744168.htm \u6c5f\u897f \u81ea3\u670820\u65e518\u65f6\u8d77\n# http://www.jl.xinhuanet.com/2020-03/20/c_1125742524.htm \u5409\u6797 \u81ea2020\u5e743\u670820\u65e514\u65f6\u8d77\n# http://www.xinhuanet.com/2020-05/06/c_1125949706.htm \u5b81\u590f \u81ea2020\u5e745\u67086\u65e517\u65f6\u8d77\n# https://www.sohu.com/a/393095409_260616 \u5c71\u4e1c \u81ea2020\u5e745\u67086\u65e50\u65f6\u8d77\n# http://m.xinhuanet.com/sx/2020-03/10/c_1125688119.htm \u5c71\u897f \u81ea2020\u5e743\u670810\u65e5\u96f6\u65f6\n# http://www.sc.xinhuanet.com/content/2020-03/24/c_1125762537.htm \u56db\u5ddd \u81ea3\u670825\u65e5\u96f6\u65f6\u8d77\n# http://www.xinhuanet.com/local/2020-03/08/c_1125681321.htm \u65b0\u7586 \u81ea2020\u5e743\u67087\u65e524\u65f6\u8d77\n# http://m.xinhuanet.com/2020-03/23/c_1125755679.htm \u6d59\u6c5f 3\u670823\u65e5\u7535\n# http://m.xinhuanet.com/2020-06/05/c_1126078726.htm \u5317\u4eac 6\u67086\u65e5\u96f6\u65f6\u8d77\n# http://www.xinhuanet.com/politics/2020-03/24/c_1125761972.htm \u91cd\u5e86 \u4ece3\u670824\u65e524\u65f6\u8d77\n# http://m.xinhuanet.com/2020-05/08/c_1125957038.htm \u4e0a\u6d77 \u81ea5\u67089\u65e5\u96f6\u65f6\u8d77\n# http://m.xinhuanet.com/2020-06/05/c_1126079845.htm \u5929\u6d25 \u81ea2020\u5e746\u67086\u65e5\u96f6\u65f6\u8d77\n# http://www.zytzb.gov.cn/mzdqzxd/334707.jhtml \u897f\u85cf \u897f\u85cf\u7a81\u53d1\u516c\u5171\u536b\u751f\u4e8b\u4ef6\u5e94\u6025\u54cd\u5e94\u7ea7\u522b\u5df2\u4e8e3\u670828\u65e5\u4e0b\u8c03\u81f3\u4e09\u7ea7\nprovincial_response_3_dict = {'Anhui': datetime.date(int(2020),int(3),int(15)), 'Fujian': datetime.date(int(2020),int(3),int(19)), \n                            'Gansu': datetime.date(int(2020),int(2),int(21)), 'Guangdong': datetime.date(int(2020),int(5),int(9)),\n                            'Guangxi': datetime.date(int(2020),int(2),int(24)), 'Guizhou': datetime.date(int(2020),int(2),int(24)), \n                            'Hainan': datetime.date(int(2020),int(2),int(26)), 'Hebei': datetime.date(int(2020),int(6),int(6)), \n                            'Heilongjiang': datetime.date(int(2020),int(3),int(25)), 'Henan': datetime.date(int(2020),int(5),int(6)),\n                            'Hubei': datetime.date(int(2020),int(6),int(13)), 'Hunan': datetime.date(int(2020),int(3),int(31)), \n                            'Inner Mongolia': datetime.date(int(2020),int(2),int(26)), 'Jiangsu': datetime.date(int(2020),int(3),int(28)), \n                            'Jiangxi': datetime.date(int(2020),int(3),int(20)), 'Jilin': datetime.date(int(2020),int(3),int(20)), \n                            'Liaoning': datetime.date(int(2020),int(2),int(22)), 'Ningxia': datetime.date(int(2020),int(5),int(6)),\n                            'Qinghai': datetime.date(int(2020),int(2),int(26)), 'Shaanxi': datetime.date(int(2020),int(2),int(28)), \n                            'Shandong': datetime.date(int(2020),int(5),int(6)), 'Shanxi': datetime.date(int(2020),int(3),int(10)), \n                            'Sichuan': datetime.date(int(2020),int(3),int(25)), 'Xinjiang': datetime.date(int(2020),int(3),int(8)), \n                            'Yunnan': datetime.date(int(2020),int(2),int(24)), 'Zhejiang': datetime.date(int(2020),int(3),int(23)), \n                            'Beijing': datetime.date(int(2020),int(6),int(6)), 'Chongqing': datetime.date(int(2020),int(3),int(25)), \n                            'Shanghai': datetime.date(int(2020),int(5),int(9)), 'Tianjin': datetime.date(int(2020),int(6),int(6)), \n                            'Tibet': datetime.date(int(2020),int(3),int(28))}\n\n# Back and Forth\n# http://www.xinhuanet.com/politics/2020-06/16/c_1126122434.htm 6\u670816\u65e5\u665a\uff0c\u7531\u4e09\u7ea7\u8c03\u81f3\u4e8c\u7ea7\n# http://www.xinhuanet.com/local/2020-07/19/c_1126257663.htm 7\u670820\u65e5\u96f6\u65f6\u8d77\uff0c\u7531\u4e8c\u7ea7\u8c03\u6574\u4e3a\u4e09\u7ea7\u3002\nprovincial_response_beijing_dict = {'1': datetime.date(int(2020),int(1),int(24)), '2': datetime.date(int(2020),int(4),int(30)),\n                                   '3': datetime.date(int(2020),int(6),int(6)), '2x': datetime.date(int(2020),int(6),int(16)),\n                                   '3x': datetime.date(int(2020),int(7),int(20))}\n\n# Get the response data\ndef load_response_raw():\n    provincial_response_dict = {}\n    for key in (provincial_response_1_dict.keys()):\n        provincial_response_dict.setdefault(key, []).append(provincial_response_1_dict[key])\n        provincial_response_dict.setdefault(key, []).append(provincial_response_2_dict[key])\n        provincial_response_dict.setdefault(key, []).append(provincial_response_3_dict[key])\n    data_response_o = pd.DataFrame([(k, *v) for k, v in provincial_response_dict.items()])\n    data_response_o.columns = ['province_name'] + [f'date_level{x}' for x in data_response_o.columns[1:]]\n    ######\n    data_response_o = data_response_o[data_response_o['province_name'] != 'Tibet']\n    data_response_o = data_response_o.sort_values(by = 'province_name')\n    data_response_o = data_response_o.reset_index(drop = True)\n    ######\n    data_response_o123 = data_response_o[data_response_o['date_level2'].values != None]\n    data_response_o13 = data_response_o[data_response_o['date_level2'].values == None]\n    # \u7279\u522b\u91cd\u5927\uff08\u2160\u7ea7\uff09\n    # https://en.wikipedia.org/wiki/COVID-19_pandemic_in_mainland_China\n    data_response_1 = data_response_o123[['province_name', 'date_level1', 'date_level2']].copy()\n    data_response_1.columns = ['province_name', 'start_date', 'end_date']\n    data_response_1 = data_response_1.append(data_response_o13[['province_name', 'date_level1', 'date_level3']].rename(columns={'date_level1':'start_date', 'date_level3': 'end_date'}))\n    data_response_1['level'] = 'Class 1'\n    data_response_1 = data_response_1.sort_values(['province_name'])\n    data_response_1 = data_response_1.reset_index(drop=True)\n    # \u91cd\u5927\uff08\u2161\u7ea7\uff09\n    data_response_2 = data_response_o123[['province_name', 'date_level2', 'date_level3']].copy()\n    data_response_2.columns = ['province_name', 'start_date', 'end_date']\n    data_response_2['level'] = 'Class 2'\n    data_response_2 = data_response_2.sort_values(['province_name'])\n    data_response_2 = data_response_2.reset_index(drop=True)\n    # \u8f83\u5927\uff08\u2162\u7ea7\uff09\n    data_response_3 = data_response_o[['province_name', 'date_level3']].copy()\n    data_response_3.columns = ['province_name', 'start_date']\n    data_response_3['end_date'] = max(datetime.date(int(2020),int(6),int(16)), max(data_response_3['start_date']) +  timedelta(days=1))\n    data_response_3['level'] = 'Class 3'\n    data_response_3 = data_response_3.sort_values(['province_name'])\n    data_response_3 = data_response_3.reset_index(drop=True)\n    data_response_3\n    data_response = pd.concat([data_response_1, data_response_2, data_response_3])\n    \n    return data_response_o, data_response\n\n# spring festival 2019-02-05, spring festival 2020-01-25\ndate_sp_2020 = datetime.date(int(2020),int(1),int(25)) # Saturday\ndate_sp_2019 = datetime.date(int(2019),int(2),int(5)) # Tuesday\n\n\n# Obtain the latitude and longitude of a province from the local dictionary\n# Save as a dictionary\ndef get_province_latlng_dict():\n    province_latlng_dict = {}\n    chn_latlng = pd.read_csv(_CHN_LatLng_DICT_, encoding='utf-8')\n    for key in provincial_capital_dict:\n        lat = chn_latlng[chn_latlng.city == provincial_capital_dict[key]]['lat'].tolist()[0]\n        lng = chn_latlng[chn_latlng.city == provincial_capital_dict[key]]['lng'].tolist()[0]\n        province_latlng_dict[key] = (lat, lng)\n    return province_latlng_dict\n\n# Save as a dataframe\ndef get_province_latlng_df():\n    data = pd.DataFrame.from_dict(province_latlng_dict, orient='index', columns = ['lat', 'lng'])\n    data = data.reset_index()\n    data = data.rename(columns={'index':'province_name'})\n    #data_gephi = data.rename(columns={'province_name':'id'})\n    #data_gephi.to_csv(r'./data/data_network_P2P_gephi_id.csv', index = False)\n    return data\n\nprovince_latlng_dict = get_province_latlng_dict()\nprovince_latlng_df = get_province_latlng_df()\n```\n\n\n```python\n# Settings on the Chinese font\ndef set_font(font_file):\n    if not os.path.exists(font_file):\n        print(font_file + \" not found.  If you wish to display Chinese characters in plots, please use set_font() to set the path to the font file.\")\n    else:\n        global _CHN_FONT_, _FONT_PROP_\n        _CHN_FONT_ = font_file\n        _FONT_PROP_ = mfm.FontProperties(fname=_CHN_FONT_)\n    return\n\nset_font('./STFANGSO.TTF')   # for displaying Chinese characters in plots\n\ndef use_chn():\n    return _CHN_FONT_ is None\n\n# Add English name for a province or a city\ndef add_en_location(df, tag = 'city'):\n    '''Add province_name_en, and city_name_en'''\n    chn_en = pd.read_csv(_CHN_EN_DICT_, encoding='utf-8')\n    translation = dict([t for t in zip(chn_en['Chinese'], chn_en['English'])])\n    if tag == 'province':\n        df['province_name_en'] = df['province_name'].replace(translation)\n    elif tag == 'city':\n        df['province_name_en'] = df['province_name'].replace(translation)\n        df['city_name_en'] = df['city_name'].replace(translation)\n    elif tag == 'network':\n        df['source_en'] = df['source'].replace(translation)\n        df['target_en'] = df['target'].replace(translation)\n    return df\n```\n\n\n```python\n# Data loading\n_Data_PATH_ = './data/parameters/'\n_Data_PATH_X_ = './data/parameters_x/'\n_Data_PATH_XX_ = './data/parameters_xx/'\n_Data_PATH_M_ = './data/parameters_m/'\n_Data_PATH_MX_ = './data/parameters_mx/'\n_Data_PATH_MXX_ = './data/parameters_mxx/'\n_City_PATH_ = './data/data_DXY_city_all.csv'\n_Province_PATH_ = './data/data_DXY_province_all.csv'\n_Province_Domestic_PATH_ = './data/data_DXY_province_all_domestic.csv'\n_Network_P2P_PATH_ = './data/data_network_P2P.csv'\n\ndef load_DXY_raw():\n    raw_city = pd.read_csv(_City_PATH_)\n    raw_province = pd.read_csv(_Province_PATH_) \n    raw_province_domestic = pd.read_csv(_Province_Domestic_PATH_) \n    raw_city['update_date'] = pd.to_datetime(raw_city['update_date'])\n    raw_city['update_date'] = raw_city['update_date'].dt.date \n    raw_province['update_date'] = pd.to_datetime(raw_province['update_date'])\n    raw_province['update_date'] = raw_province['update_date'].dt.date\n    raw_province_domestic['update_date'] = pd.to_datetime(raw_province_domestic['update_date'])\n    raw_province_domestic['update_date'] = raw_province_domestic['update_date'].dt.date\n    return raw_city, raw_province, raw_province_domestic\n\ndef load_network_raw():\n    # Do not distinguish between move_in and move_out\n    raw = pd.read_csv(_Network_P2P_PATH_) \n    raw['update_date'] = pd.to_datetime(raw['update_date'])\n    raw['update_date'] = raw['update_date'].dt.date \n    return raw\n\ndef load_ind_simulation_raw():\n    df_parameters_list = []\n    df_estimation_list = []\n    for name in names_province:\n        df_parameters_single = pd.read_csv(_Data_PATH_ + name + '_parameters.csv')\n        df_estimation_single = pd.read_csv(_Data_PATH_ + name + '_estimation.csv')\n        df_parameters_list.append(df_parameters_single)\n        df_estimation_list.append(df_estimation_single)\n    return df_parameters_list, df_estimation_list \n\n\ndef load_ind_simulation_raw_x():\n    df_parameters_list = []\n    df_estimation_list = []\n    for name in names_province:\n        df_parameters_single = pd.read_csv(_Data_PATH_X_ + name + '_parameters.csv')\n        df_estimation_single = pd.read_csv(_Data_PATH_X_ + name + '_estimation.csv')\n        df_parameters_list.append(df_parameters_single)\n        df_estimation_list.append(df_estimation_single)\n    return df_parameters_list, df_estimation_list \n\ndef load_ind_simulation_raw_xx():\n    df_parameters_list = []\n    df_estimation_list = []\n    for name in names_province:\n        df_parameters_single = pd.read_csv(_Data_PATH_XX_ + name + '_parameters.csv')\n        df_estimation_single = pd.read_csv(_Data_PATH_XX_ + name + '_estimation.csv')\n        df_parameters_list.append(df_parameters_single)\n        df_estimation_list.append(df_estimation_single)\n    return df_parameters_list, df_estimation_list  \n```\n\n\n```python\n# Some utility functions\n# Get the list of dates from the start_date to the end_date\ndef daterange(start_date, end_date):\n    for n in range(int ((end_date - start_date).days) + 1):\n        yield start_date + timedelta(n)\n        \n# Transform the migration edgelist to the migration matrix\ndef matrix_P2P(data_single, m):\n    mindex = np.zeros((m, m))\n    for i, name_i in enumerate(names_province):\n        for j, name_j in enumerate(names_province):\n            if i == j:\n                mindex[i][j] = 0\n            else:\n                temp = data_single[(data_single.source_en == name_i) & (data_single.target_en == name_j)].value.tolist()\n                if temp == []:\n                    mindex[i][j] = 0\n                else:\n                    mindex[i][j] = temp[0]\n    return mindex\n\n# Perform the operation for all migration data from the start_date to the end_date\ndef matrix_P2P_all(data_network_P2P, start_date, end_date):\n    mindex_list = []\n    m = len(names_province)\n    for item in daterange(start_date, end_date):\n        data_single = data_network_P2P[data_network_P2P.update_date == item]\n        mindex = matrix_P2P(data_single, m)\n        mindex_list.append(mindex) \n    return mindex_list\n```\n\n\n```python\n# The state names in the US (including D.C.)\n# Ignore oversea territories: American Samoa, Guam, Northern Mariana Islands, Puerto Rico, and Virgin Islands\n\nnames_state = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', \n                 'District of Columbia',\n                 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', \n                 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi',\n                 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York',\n                 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina',\n                 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia',\n                 'Wisconsin', 'Wyoming']\n\n# The abbreviations of state names\nnames_state_short_dict = {\n    'Alabama': 'AL', 'Alaska':'AK', 'Arizona':'AZ', 'Arkansas':'AR', 'California':'CA', 'Colorado':'CO', 'Connecticut':'CT', 'Delaware':'DE', \n    'Florida':'FL', 'Georgia':'GA', 'Hawaii':'HI', 'Idaho':'ID', 'Illinois':'IL', 'Indiana':'IN', 'Iowa':'IA', 'Kansas':'KS', \n    'Kentucky':'KY', 'Louisiana':'LA', 'Maine':'ME', 'Maryland':'MD', 'Massachusetts':'MA', 'Michigan':'MI', 'Minnesota':'MN', 'Mississippi':'MS',\n    'Missouri':'MO', 'Montana':'MT', 'Nebraska':'NE', 'Nevada':'NV', 'New Hampshire':'NH', 'New Jersey':'NJ', 'New Mexico':'NM', 'New York':'NY',\n    'North Carolina':'NC', 'North Dakota':'ND', 'Ohio':'OH', 'Oklahoma':'OK', 'Oregon':'OR', 'Pennsylvania':'PA', 'Rhode Island':'RI', 'South Carolina':'SC',\n    'South Dakota':'SD', 'Tennessee':'TN', 'Texas':'TX', 'Utah':'UT', 'Vermont':'VT', 'Virginia':'VA', 'Washington':'WA', 'West Virginia':'WV',\n    'Wisconsin':'WI', 'Wyoming':'WY', \n    'District of Columbia': 'DC', 'Guam': 'Guam', 'Northern Mariana Islands':'Northern Mariana Islands',\n    'Puerto Rico': 'PR', 'Virgin Islands': 'VI'}\n\n# The populations of states\nstate_population_dict = {\n    'Alabama': 4903185, 'Alaska':731545, 'Arizona':7278717, 'Arkansas':3017825, \n    'California':39512223, 'Colorado':5758736, 'Connecticut':3565287, 'Delaware':973764, \n    'Florida':21477737, 'Georgia':10617423, 'Hawaii':1415872, 'Idaho':1787065, \n    'Illinois':12671821, 'Indiana':6732219, 'Iowa':3155070, 'Kansas':2913314, \n    'Kentucky':4467673, 'Louisiana':4648794, 'Maine':1344212, 'Maryland':6045680, \n    'Massachusetts':6949503, 'Michigan':9986857, 'Minnesota':5639632, 'Mississippi':2976149,\n    'Missouri':6137428, 'Montana':1068778, 'Nebraska':1934408, 'Nevada':3080156, \n    'New Hampshire':1359711, 'New Jersey':8882190, 'New Mexico':2096829, 'New York':19453561,\n    'North Carolina':10488084, 'North Dakota':762062, 'Ohio':11689100, 'Oklahoma':3956971, \n    'Oregon':4217737, 'Pennsylvania':12801989, 'Rhode Island':1059361, 'South Carolina':5148714,\n    'South Dakota':884659, 'Tennessee':6833174, 'Texas':28995881, 'Utah':3205958, \n    'Vermont':623989, 'Virginia':8535519, 'Washington':7614893, 'West Virginia':1792147,\n    'Wisconsin':5822434, 'Wyoming':578759, 'District of Columbia': 705749, 'Guam': 165718, \n    'Puerto Rico': 3193694, 'Virgin Islands': 104914}\n```\n\n\n```python\n# The PVI values of states\ndf_state_pvi = pd.DataFrame(columns = ['state_name', 'partisan', 'value'])\ndf_state_pvi.loc[len(df_state_pvi)] = ['Alabama', 'R', 14]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Alaska', 'R', 9]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Arizona', 'R', 5]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Arkansas', 'R', 15]\n\ndf_state_pvi.loc[len(df_state_pvi)] = ['California', 'D', 12]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Colorado', 'D', 1]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Connecticut', 'D', 6]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Delaware', 'D', 6]\n\ndf_state_pvi.loc[len(df_state_pvi)] = ['Florida', 'R', 2]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Georgia', 'R', 5]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Hawaii', 'D', 18]\n\ndf_state_pvi.loc[len(df_state_pvi)] = ['Idaho', 'R', 19]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Illinois', 'D', 7]\n\ndf_state_pvi.loc[len(df_state_pvi)] = ['Indiana', 'R', 9]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Iowa', 'R', 3]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Kansas', 'R', 13]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Kentucky', 'R', 15]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Louisiana', 'R', 11]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Maine', 'D', 3]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Maryland', 'D', 12]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Massachusetts', 'D', 12]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Michigan', 'D', 1]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Minnesota', 'D', 1]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Mississippi', 'R', 9]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Missouri', 'R', 9]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Montana', 'R', 11]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Nebraska', 'R', 14]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Nevada', 'D', 1]\ndf_state_pvi.loc[len(df_state_pvi)] = ['New Hampshire', 'Even', 0]\ndf_state_pvi.loc[len(df_state_pvi)] = ['New Jersey', 'D', 7]\ndf_state_pvi.loc[len(df_state_pvi)] = ['New Mexico', 'D', 3]\ndf_state_pvi.loc[len(df_state_pvi)] = ['New York', 'D', 12]\ndf_state_pvi.loc[len(df_state_pvi)] = ['North Carolina', 'R', 3]\ndf_state_pvi.loc[len(df_state_pvi)] = ['North Dakota', 'R', 17]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Ohio', 'R', 3]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Oklahoma', 'R', 20]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Oregon', 'D', 5]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Pennsylvania', 'Even', 0]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Rhode Island', 'D', 10]\ndf_state_pvi.loc[len(df_state_pvi)] = ['South Carolina', 'R', 8]\ndf_state_pvi.loc[len(df_state_pvi)] = ['South Dakota', 'R', 14]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Tennessee', 'R', 14]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Texas', 'R', 8]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Utah', 'R', 20]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Vermont', 'D', 15]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Virginia', 'D', 1]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Washington', 'D', 7]\ndf_state_pvi.loc[len(df_state_pvi)] = ['West Virginia', 'R', 19]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Wisconsin', 'Even', 0]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Wyoming', 'R', 25]\ndf_state_pvi.loc[len(df_state_pvi)] = ['District of Columbia', 'D', 43]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Guam', 'None', 0]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Northern Mariana Islands', 'None', 0]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Puerto Rico', 'None', 0]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Virgin Islands', 'None', 0]\n\ndef color_pvi(df_state_pvi, state):\n    \n    palette_D = plt.get_cmap('Blues')\n    palette_R = plt.get_cmap('Reds')\n    palette_Even = plt.get_cmap('Greens')\n    palette_None = plt.get_cmap('Purples')\n    \n    D_max = max(df_state_pvi[df_state_pvi['partisan'] == 'D']['value'])\n    D_min = min(df_state_pvi[df_state_pvi['partisan'] == 'D']['value'])\n    R_max = max(df_state_pvi[df_state_pvi['partisan'] == 'R']['value'])\n    R_min = min(df_state_pvi[df_state_pvi['partisan'] == 'R']['value'])\n    \n    partisan = df_state_pvi[df_state_pvi['state_name'] == state]['partisan'].tolist()[0]\n    value = df_state_pvi[df_state_pvi['state_name'] == state]['value'].tolist()[0]\n    if partisan == 'Even':\n        return palette_Even(0.6)\n    elif partisan == 'None':\n        return palette_None(0.6)\n    elif partisan == 'D':\n        return palette_D((value - D_min)/2/(D_max - D_min) + 0.3)\n    else:\n        return palette_R((value - R_min)/2/(R_max - R_min) + 0.3)\n```\n\n\n```python\n# Stock market data\n# S & P 500 index\ndef load_SP_raw():\n    '''\n    This provides a way to lookinto the 'raw' data\n    '''\n    SP = yf.Ticker(\"^GSPC\")\n    raw = SP.history(period=\"max\")\n    raw = raw.reset_index()\n    rename_dict = {'Date': 'update_date',\n                   'Open': 'open',\n                   'High': 'high',\n                   'Low': 'low',\n                   'Close': 'close',\n                   'Volume': 'volume',\n                   'Dividends': 'dividends',\n                   'Stock Splits': 'stock splits'\n                  }\n    data = raw.rename(columns=rename_dict)\n    data['update_date'] = pd.to_datetime(data['update_date'])  # original type of update_time after read_csv is 'str'\n    data['update_date'] = data['update_date'].dt.date\n    data = data.reset_index(drop=True)\n    print('Data date range: ', data['update_date'].min(), 'to', data['update_date'].max())\n    print('Number of rows in raw data: ', data.shape[0])\n    return data\n# Stock price of a certain cooperation\ndef load_STOCK_raw(name):\n    '''\n    This provides a way to lookinto the 'raw' data\n    '''\n    SP = yf.Ticker(name)\n    raw = SP.history(period=\"max\")\n    raw = raw.reset_index()\n    rename_dict = {'Date': 'update_date',\n                   'Open': 'open',\n                   'High': 'high',\n                   'Low': 'low',\n                   'Close': 'close',\n                   'Volume': 'volume',\n                   'Dividends': 'dividends',\n                   'Stock Splits': 'stock splits'\n                  }\n    data = raw.rename(columns=rename_dict)\n    data['update_date'] = pd.to_datetime(data['update_date'])  # original data type of update_time is 'str'\n    data['update_date'] = data['update_date'].dt.date\n    data = data.reset_index(drop=True)\n    #print('Data date range: ', data['update_date'].min(), 'to', data['update_date'].max())\n    #print('Number of rows in raw data: ', data.shape[0])\n    return data\n```\n\n\n```python\narmyrose = ['#798234', '#a3ad62', '#d0d3a2', '#fdfbe4', '#f0c6c3', '#df91a3', '#d46780']\ntealrose = ['#009392', '#72aaa1', '#b1c7b3', '#f1eac8', '#e5b9ad', '#d98994', '#d0587e']\ngeyser = ['#008080', '#70a494', '#b4c8a8', '#f6edbd', '#edbb8a', '#de8a5a', '#ca562c']\nearth = ['#A16928', '#bd925a', '#d6bd8d', '#edeac2', '#b5c8b8', '#79a7ac', '#2887a1']\nearth.reverse()\nfall = ['#3d5941', '#778868', '#b5b991', '#f6edbd', '#edbb8a', '#de8a5a', '#ca562c']\n\n# hex color code to rgb color code\ndef hex_to_rgb(value):\n    value = value.lstrip('#')\n    lv = len(value)\n    rgb_int = tuple(int(value[i:i+lv//3], 16) for i in range(0, lv, lv//3))\n    rgb_str = 'rgb(' + str(rgb_int[0]) + ',' + str(rgb_int[1]) + ',' + str(rgb_int[2]) + ')'\n    return rgb_str\n```\n\n\n```python\n# ODE systems\n#%%latex\n#Difference equations \n#without immigration\n#\\begin{align}\n#S(t + 1) - S(t) &= -\\beta(t)S(t)\\frac{I(t)}{N(t)}, \\\\\n#E(t + 1) - E(t) &= \\beta(t)S(t)\\frac{I(t)}{N(t)} - \\sigma(t)E(t), \\\\\n#I(t + 1) - I(t) &= \\sigma(t)E(t) - \\gamma(t)I(t), \\\\\n#R(t + 1) - R(t) &= \\gamma(t)I(t)\n#\\end{align}\n#Difference equations \n#with immigration\n#\\begin{align}\n#S_i(t + 1) - S_i(t) &= -\\beta_i(t)S_i(t)\\frac{I_i(t)}{N_i(t)} - \\sum_{j, j \\neq i}a_{ij}(t)S_i(t) + \\sum_{j, j \\neq i}a_{ji}(t)S_j(t) \\\\\n#E_i(t + 1) - E_i(t) &= \\beta_i(t)S_i(t)\\frac{I_i(t)}{N_i(t)} - \\sigma_i(t)E_i(t) - \\sum_{j, j \\neq i}a_{ij}(t)E_i(t) + \\sum_{j, j \\neq i}a_{ji}(t)E_j(t) \\\\\n#I_i(t + 1) - I_i(t) &= \\sigma_i(t)E_i(t) - \\gamma_i(t)I_i(t) \\\\\n#R_i(t + 1) - R_i(t) &= \\gamma_i(t)I_i(t)\n#\\end{align}\n```\n", "meta": {"hexsha": "34075656f2cc01b1df0a3dac4b90a78e77871f66", "size": 53194, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "scripts/utils_common.ipynb", "max_stars_repo_name": "fudab/China-COVID-19-mobility", "max_stars_repo_head_hexsha": "7849869b4170cc26e9645df2d2483144e3219ad6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-04-23T15:51:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-22T14:36:20.000Z", "max_issues_repo_path": "scripts/utils_common.ipynb", "max_issues_repo_name": "fudab/China-COVID-19-mobility", "max_issues_repo_head_hexsha": "7849869b4170cc26e9645df2d2483144e3219ad6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/utils_common.ipynb", "max_forks_repo_name": "fudab/China-COVID-19-mobility", "max_forks_repo_head_hexsha": "7849869b4170cc26e9645df2d2483144e3219ad6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 67.2490518331, "max_line_length": 193, "alphanum_fraction": 0.5497800504, "converted": true, "num_tokens": 18159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27825679370240214, "lm_q2_score": 0.04885777706412342, "lm_q1q2_score": 0.013595008393289745}}
{"text": "```python\nfrom pathlib import Path\nimport sys\n```\n\n\n```python\nsys.version\n```\n\n\n\n\n    '3.8.0 (default, Oct 28 2019, 16:14:01) \\n[GCC 8.3.0]'\n\n\n\n\n```python\nsys.path.insert(0, str(Path.cwd().parent.parent))\n```\n\n\n```python\ncd ../\n```\n\n    /home/fuzzy/projects/py38/ncv\n\n\n\n```python\nfrom py.startup import *\n```\n\n\n```python\nls()\n```\n\n    data  etc  json  log  ncv  notes  run  setup.py  test  tests\n\n\n\n```python\nfrom configparser import ConfigParser\nfrom enum import Enum, IntEnum\n\nfrom py.charconsts import *\n\nWorkCoordinates = int\n\nclass NonModal(IntEnum):\n    DWELL = 4\n    EXACT_STOP = 9\n    SET_OFFSETS = 10\n    CLOCKWISE_CIRCULAR_POCKET_MILLING = 12\n    COUNTER_CLOCKWISE_CIRCULAR_POCKET_MILLING = 13\n    RETURN_2_REF_PT = 28\n    SET_RETURN_THRU_REF_PT = 29\n    FEED_UNTIL_SKIP = 31 # optional\n    AUTO_TOOL_DIAMETER_MEASURE = 35 # optional\n    AUTO_WORK_OFFSET_MEASURE = 36 # optional\n    AUTO_TOOL_OFFSET_MEASURE = 37 # optional\n    TEXT_ENGRAVING = 47\n    SET_LOCAL_SHIFT_COORDINATE_SYSTEM = 52 # fanuc\n    NON_MODAL_MACHINE_COORDINATE_SELECTION = 53\n    UNIDIRECTIONAL_POSITIONING = 60\n    MACRO_SUBROUTINE_CALL = 65 # optional\n    BOLT_HOLE_CIRCLE = 70 # yasnac\n    BOLT_HOLE_ARC = 71 # yasnac\n    BOLT_HOLES_ANGLE = 72\n    SET_WORK_COORDINATES = 92\n    CANCEL_MIRROR_IMAGE = 100\n    ENABLE_MIRROR_IMAGE = 101\n    PROGRAMMABLE_OUTPUT = 102\n    LIMIT_BLOCK_BUFFERING = 103\n    CYLINDRICAL_MAPPING = 107\n    AUTOMATIC_WORK_OFFSET_CENTER_MEASURE = 136\n    GENERAL_PURPOSE_POCKET_MILLING = 150\n    SPECIAL_PURPOSE_RIGID_TAPPING_COUNTER_CLOCKWISE = 174\n    SPECIAL_PURPOSE_RIGIT_TAPPING_CLOCKWISE = 184\n    ACCURACY_CONTROL = 187\n\nclass MotionMode(IntEnum):\n    RAPID = 0\n    LINEAR = 1\n    CLOCKWISE = 2\n    COUNTER = 3\n    POCKET = 12\n    COUNTER_POCKET = 13\n\nclass PositionMode(IntEnum):\n    ABSOLUTE = 90\n    INCREMENTAL = 91\n\nclass CutterOffsetMode(IntEnum):\n    OFF   = 40\n    LEFT  = 41\n    RIGHT = 42\n\nclass CannedCycle(IntEnum):\n    NONE = 0\n    CANCEL = 80\n    DRILL = 81\n    SPOT = 82\n    PECK = 83\n    TAP = 84\n    BORE = 85\n    IN_OUT = 86\n    RETRACT = 87\n    MANUAL = 88\n    DWELL = 89\n\nclass CircularPlane(IntEnum):\n    XY = 17\n    ZX = 18\n    YZ = 19\n\nclass Units(IntEnum):\n    INCHES = 20\n    METRIC = 21\n\nclass ToolOffsetMode(IntEnum):\n    POSITIVE = 43\n    NEGATIVE = 44\n    OFF = 49\n\nclass ExactStopModal(IntEnum):\n    ON = 61\n    OFF = 64\n\nclass FeedMode(IntEnum):\n    INVERSE_TIME = 93\n    PER_MINUTE = 94\n\nclass ReturnMode(IntEnum):\n    INITIAL_POINT = 98\n    R_PLANE = 99\n\nclass MirrorImage(IntEnum):\n    CANCEL = 100\n    ENABLE = 101\n\nclass SpindleState(IntEnum):\n    OFF = 0\n    FORWARD = 1\n    REVERSE = 2\n\nclass ScalingMode(IntEnum):\n    OFF = 50\n    ON = 51\n\nclass Rotation(IntEnum):\n    ON = 68\n    OFF = 69\n\nclass GCodeGroup(Enum):\n    NON_MODAL = NonModal\n    MOTION = MotionMode\n    PLANE = CircularPlane\n    POSITION_MODE = PositionMode\n    FEED_MODE = FeedMode\n    UNITS = Units\n    CUTTER_COMPENSATION = CutterOffsetMode\n    TOOL_LENGTH = ToolOffsetMode\n    CANNED_CYCLE = CannedCycle\n    RETURN = ReturnMode\n    SCALING = ScalingMode\n    WORK_COORDINATES = WorkCoordinates\n    EXACT_STOP_MODAL = ExactStopModal\n    ROTATION = Rotation\n    \ngCodeClassList = [\n    NonModal, MotionMode, CircularPlane, PositionMode, FeedMode, Units, CutterOffsetMode, ToolOffsetMode,\n    CannedCycle, ReturnMode, ScalingMode, WorkCoordinates, ExactStopModal, Rotation\n]\n\ngCodeGroups = {\n    GCodeGroup.NON_MODAL : [ 4, 9, 10, 12, 13, 28, 29, 32, *range(35, 38),\n                             47, 52, 53, 60, 65, *range(70, 73), 92,\n                             *range(100, 104), 107, 136, 150, 174, 184, 187\n                           ],\n    GCodeGroup.MOTION : [ *range(0, 4), ],\n    GCodeGroup.PLANE : [ *range(17, 20)],\n    GCodeGroup.POSITION_MODE : [ 90, 91 ],\n    GCodeGroup.FEED_MODE : [ 93, 94 ],\n    GCodeGroup.UNITS : [ 20, 21 ],\n    GCodeGroup.CUTTER_COMPENSATION : [ *range(40, 43), 141 ],\n    GCodeGroup.TOOL_LENGTH : [ 43, 44, 49, 143 ],\n    GCodeGroup.CANNED_CYCLE : [ *range(73, 90) ],\n    GCodeGroup.RETURN : [ 98, 99 ],\n    GCodeGroup.SCALING : [ 50, 51 ],\n    GCodeGroup.WORK_COORDINATES : [ *range(54, 60), *range(100, 130) ],\n    GCodeGroup.EXACT_STOP_MODAL : [ 61, 64 ],\n    GCodeGroup.ROTATION : [ 68, 69 ]\n}\n\ngCodeGroupsDict = dict(zip(gCodeGroups.keys(), gCodeClassList))\n\n```\n\n\n```python\nfrom collections import ChainMap\nfrom pprint import pformat, pprint as pp\n\nfrom nested_dict import nested_dict\nfrom sympy import Point3D\nPoint = Point3D\n\nDEFAULT_GCODES = [ list(), MotionMode.RAPID, CircularPlane.XY, PositionMode.ABSOLUTE, FeedMode.PER_MINUTE,\n                   Units.INCHES, CutterOffsetMode.OFF, ToolOffsetMode.NEGATIVE, CannedCycle.CANCEL,\n                   ReturnMode.INITIAL_POINT, False, 54, ExactStopModal.OFF, False ]\n\nDEFAULT_VARS = {\n#     \"current_position\" : Point(),\n    \"A\" : 0.0,\n    \"B\" : 0.0,\n    \"C\" : 0.0,\n    \"D\" : 0,\n    \"E\" : 0.0001, # minimum; 0.25 is the max\n    \"F\" : 0.0,\n    'G' : dict(zip(gCodeClassList, DEFAULT_GCODES)),\n    'H' : 0,\n    \"I\" : 0.0,\n    \"J\" : 0.0,\n    \"K\" : 0.0,\n    \"L\" : 0.0,\n    \"M\" : None,\n    \"N\" : None,\n    \"O\" : 0,\n    \"P\" : 0.0,\n    \"Q\" : 0.0,\n    \"R\" : 0.0,\n    \"S\" : 1,\n    \"T\" : 0,\n    \"U\" : 0.0001,\n    \"V\" : 0.0001,\n    \"W\" : 0.0001,\n    \"X\" : 0.0,\n    \"Y\" : 0.0,\n    \"Z\" : 0.0,\n\n}\n\nCONFIG_FILE = 'etc/config.ini'\nARGS_FILE = 'json/arguments.json'\nCONFIG = ConfigParser()\nCONFIG.read(CONFIG_FILE)\n\nDEFAULT_VARS = dict(ChainMap(dict(CONFIG[\"ENVIRONMENT\"]), DEFAULT_VARS))\n\nclass Environment(ChainMap):\n    WORK_COORDS_RANGE = [ *range(53,60), *range(110, 130) ]\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n#         self.update(DEFAULT_VARS)\n#         self.workCoords = dict()\n#         for i in self.WORK_COORDS_RANGE:\n#             self.workCoords[i] = Point()\n\n#     def get_work_coords(self, i):\n#         if i in self.WORK_COORDS_RANGE:\n#             return self.workCoords[i]\n#         else:\n#             return None\n\n#     def update(self, *args, **kwargs):\n#         print(\"Updating the environment...\")\n#         pp(args)\n#         pp(\"`dict` argument to `env.update()`:\")\n#         print(pformat(args[0]))\n#         gcodes = args[0].pop('G')\n#         if 'G' in self.keys():\n#             gcodes.update(self['G'])\n#         else:\n#             self['G'] = gcodes\n#         return super().update(*args, **kwargs)\n\n\n```\n\n\n```python\nclass Word(object):\n    \"\"\"\n    \"\"\"\n    def __init__(self, s):\n        self.cmd = s[0].upper()\n        self.param = int(s[1:].rstrip(';')) if not '.' in s[1:] else float(s[1:].rstrip(';'))\n\n    def __repr__(self):\n        return self.cmd + str(self.param)\n\n    def __str__(self):\n\n        return self.__repr__()\n\n    def execute(self):\n        return { self.cmd : self.param }\n\n\n\nPRIORITY_LIST = [ 'O', 'G', 'A', 'B', 'C', 'I', 'J', 'K', 'L', 'P', 'Q', 'X', 'Y', 'Z',\n                  'H', 'D', 'E', 'F', 'R', 'S', 'T', 'U', 'V', 'W', 'M', 'N'\n                ]\n\nclass Block(list):\n    \"\"\"\n    \"\"\"\n    def __init__(self, line):\n        super().__init__()\n        for word in line.partition(SEMICOLON)[0].split():\n            word = word.upper()\n            for CODE in PRIORITY_LIST:\n                if word[0] == CODE:\n                    self.append(Word(word))\n\n    def __repr__(self):\n        \"\"\"\n        \"\"\"\n        return ' '.join([str(s) for s in self]) + ';'\n\n    def __str__(self):\n        \"\"\"\n        \"\"\"\n        return self.__repr__()\n    \n    def pop_G_codes(self):\n        result = list()\n        for word in self:\n            if word.cmd == 'G':\n                result.append(word.param)\n                self.remove(word)\n        return result\n\n\n\n    def execute(self):\n        \"\"\"\n        \"\"\"\n        print(\"Executing block: \", self)\n        result = dict()\n        gcodes = list()\n#         mcode = None\n        for word in self:\n            # TODO: Deal with G codes here (?)\n            if word.cmd == 'G':\n                gcodes.append(word.param)\n#             elif cmd.cmd == 'M'\n            else:\n                result.update(word.execute())\n#         if gcodes:\n#             result.update({\"G\" : self.make_gcodes_dict(gcodes)})\n        return result\n\n    def mCode(self):\n        for w in self[-1:]:\n            if w.cmd == 'M':\n                return w.param\n        return None\n\n\nclass NCProgram(list):\n    \"\"\"\n    \"\"\"\n    class State(Enum):\n        BEGIN = 0\n        PAUSED = 1\n        RUNNING = 2\n        END = 3\n\n    def __init__(self, lines):\n        super(list, self).__init__()\n        if type(lines) is str:\n            lines = lines.split(NEWLINE)\n        for line in lines:\n            self.append(Block(line))\n\n    # def run(self):\n    #     while self.state != self.State.END:\n    #         self.step()\n\n    def step(self):\n        \"\"\"\n        \"\"\"\n        if self.current_block >= len(self):\n            self.state = self.State.END\n        else:\n            return self[self.current_block].execute()\n            self.current_block += 1\n\n\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nimport mpl_toolkits.mplot3d\nplt.ion()\n```\n\n\n```python\nclass NCViewer():\n    def __init__(self, settings=None):\n        self.settings = settings\n        if self.settings[\"verbose\"]:\n            print()\n            print(\"Settings:\")\n            print()\n            print(pformat([f\"{k}: {v}\" for k, v in settings.items()]).lstrip('[').rstrip(']'))\n            print()\n        self.env = Environment(DEFAULT_VARS)\n        # programs should be loaded from a directory located by a configuration file setting\n        self.programs = list()\n        self.fig = plt.figure()\n        self.ax = self.fig.add_subplot(111, projection='3d')\n        # self.ax.plot([0.0, 1.0], [0.2, 0.7], 0.4)\n        self.current_position = Point()\n        plt.show()\n\n    def code_group(self, n):\n        for k in gCodeGroups.keys():\n            if n in gCodeGroups[k]:\n                return gCodeGroupsDict[k]\n        return None\n\n    def make_gcodes_dict(self, gcodes):\n        \"\"\"\n        \"\"\"\n        result = dict()\n        for n in gcodes:\n            klass = self.code_group(n)\n            result.update({klass : klass(n)})\n        return result\n\n    def execute(self, blk):\n        result = dict()\n        # validate the block and exit on error\n        # extract the `G` codes\n        result = self.env[\"G\"]\n        print()\n        print(\"Current G Code Settings:\")\n        print()\n        pp(result)\n        result.update(self.make_gcodes_dict(blk.pop_G_codes()))\n        result = { \"G\" : result }\n        print()\n        print(\"New G Code Settings:\")\n        print()\n        pp(result)\n        print()\n        # process the `G` codes\n        # extract the `M` code\n#         result.update({\"G\" : self.make_gcodes_dict(gcodes)})\n        result.update(blk.execute())\n        print(\"New Result Environment:\")\n        print()\n        pp(result)\n        print()\n        self.env = self.env.new_child(result)\n        print(self.env.maps[-1])\n        self.move()\n        if blk.mCode():\n            pass\n            # process the `M` code\n\n    def do_step(self):\n        if self.current_program:\n            self.env = self.env.new_child(self.current_program.step())\n            return self.move()\n        else:\n            print(\"ERROR: step: No program is loaded.\")\n            return False\n\n    def move(self):\n        P = self.current_position\n        if self.settings[\"verbose\"]:\n            print(\"Current position:\", P)\n        Q = Point(*[self.env[\"X\"], self.env[\"Y\"], self.env[\"Z\"]])\n        if self.settings[\"verbose\"]:\n            print(\"X, Y, Z:\", Q)\n        if self.env[\"G\"][PositionMode] == PositionMode.INCREMENTAL:\n            Q = P + Q\n        if P != Q:\n            print(\"Moving the tool...\")\n            print(\"Motion mode:\", self.env[\"G\"][MotionMode])\n#             print(\"RAPID:\", MotionMode.RAPID)\n#             print(\"LINEAR:\", MotionMode.LINEAR)\n            if self.env[\"G\"][MotionMode] in { MotionMode.RAPID, MotionMode.LINEAR }:\n                print(\"Motion mode:\", self.env[\"G\"][MotionMode])\n                self.ax.plot([P.x, Q.x], [P.y, Q.y], [P.z, Q.z])\n        self.current_position = Q\n        return True\n\n    def do_run(self):\n        while self.current_program.state != NCProgram.State.END and self.do_step():\n            pass\n\n    def is_valid_gcode(self, s):\n        return True\n\n    def default(self, args):\n        if self.is_valid_gcode(args): self.execute(Block(args))\n        else:\n            super().default(args)\n        # self.ax.plot([1.0, 3.0], [0.2, 0.7], 0.4)\n\n\n```\n\n\n```python\nSETTINGS = ChainMap({'args': [], 'debug': False, 'verbose': False, 'recursive': False, 'testing': False} )\n```\n\n\n```python\nncp = NCViewer(SETTINGS)\n```\n\n\n```python\nncp.default(\"X1.0\")\nplt.show()\n```\n\n    \n    Current G Code Settings:\n    \n    {<enum 'PositionMode'>: <PositionMode.ABSOLUTE: 90>,\n     <enum 'CutterOffsetMode'>: <CutterOffsetMode.OFF: 40>,\n     <enum 'NonModal'>: [],\n     <enum 'CannedCycle'>: <CannedCycle.CANCEL: 80>,\n     <enum 'CircularPlane'>: <CircularPlane.XY: 17>,\n     <enum 'Units'>: <Units.INCHES: 20>,\n     <enum 'ToolOffsetMode'>: <ToolOffsetMode.NEGATIVE: 44>,\n     <enum 'ExactStopModal'>: <ExactStopModal.OFF: 64>,\n     <enum 'FeedMode'>: <FeedMode.PER_MINUTE: 94>,\n     <enum 'ReturnMode'>: <ReturnMode.INITIAL_POINT: 98>,\n     <enum 'ScalingMode'>: False,\n     <enum 'Rotation'>: False,\n     <enum 'MotionMode'>: <MotionMode.RAPID: 0>,\n     <class 'int'>: 54}\n    \n    New G Code Settings:\n    \n    {'G': {<enum 'PositionMode'>: <PositionMode.ABSOLUTE: 90>,\n           <enum 'CutterOffsetMode'>: <CutterOffsetMode.OFF: 40>,\n           <enum 'NonModal'>: [],\n           <enum 'CannedCycle'>: <CannedCycle.CANCEL: 80>,\n           <enum 'CircularPlane'>: <CircularPlane.XY: 17>,\n           <enum 'Units'>: <Units.INCHES: 20>,\n           <enum 'ToolOffsetMode'>: <ToolOffsetMode.NEGATIVE: 44>,\n           <enum 'ExactStopModal'>: <ExactStopModal.OFF: 64>,\n           <enum 'FeedMode'>: <FeedMode.PER_MINUTE: 94>,\n           <enum 'ReturnMode'>: <ReturnMode.INITIAL_POINT: 98>,\n           <enum 'ScalingMode'>: False,\n           <enum 'Rotation'>: False,\n           <enum 'MotionMode'>: <MotionMode.RAPID: 0>,\n           <class 'int'>: 54}}\n    \n    Executing block:  X1.0;\n    New Result Environment:\n    \n    {'G': {<enum 'PositionMode'>: <PositionMode.ABSOLUTE: 90>,\n           <enum 'CutterOffsetMode'>: <CutterOffsetMode.OFF: 40>,\n           <enum 'NonModal'>: [],\n           <enum 'CannedCycle'>: <CannedCycle.CANCEL: 80>,\n           <enum 'CircularPlane'>: <CircularPlane.XY: 17>,\n           <enum 'Units'>: <Units.INCHES: 20>,\n           <enum 'ToolOffsetMode'>: <ToolOffsetMode.NEGATIVE: 44>,\n           <enum 'ExactStopModal'>: <ExactStopModal.OFF: 64>,\n           <enum 'FeedMode'>: <FeedMode.PER_MINUTE: 94>,\n           <enum 'ReturnMode'>: <ReturnMode.INITIAL_POINT: 98>,\n           <enum 'ScalingMode'>: False,\n           <enum 'Rotation'>: False,\n           <enum 'MotionMode'>: <MotionMode.RAPID: 0>,\n           <class 'int'>: 54},\n     'X': 1.0}\n    \n    {'A': 0.0, 'B': 0.0, 'C': 0.0, 'D': 0, 'E': 0.0001, 'F': 0.0, 'G': {<enum 'NonModal'>: [], <enum 'MotionMode'>: <MotionMode.RAPID: 0>, <enum 'CircularPlane'>: <CircularPlane.XY: 17>, <enum 'PositionMode'>: <PositionMode.ABSOLUTE: 90>, <enum 'FeedMode'>: <FeedMode.PER_MINUTE: 94>, <enum 'Units'>: <Units.INCHES: 20>, <enum 'CutterOffsetMode'>: <CutterOffsetMode.OFF: 40>, <enum 'ToolOffsetMode'>: <ToolOffsetMode.NEGATIVE: 44>, <enum 'CannedCycle'>: <CannedCycle.CANCEL: 80>, <enum 'ReturnMode'>: <ReturnMode.INITIAL_POINT: 98>, <enum 'ScalingMode'>: False, <class 'int'>: 54, <enum 'ExactStopModal'>: <ExactStopModal.OFF: 64>, <enum 'Rotation'>: False}, 'H': 0, 'I': 0.0, 'J': 0.0, 'K': 0.0, 'L': 0.0, 'M': None, 'N': None, 'O': 0, 'P': 0.0, 'Q': 0.0, 'R': 0.0, 'S': 1, 'T': 0, 'U': 0.0001, 'V': 0.0001, 'W': 0.0001, 'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'program': 'ncv', 'version': '0.0.0', 'packages_dir': 'projects/py38'}\n    Moving the tool...\n    Motion mode: MotionMode.RAPID\n    Motion mode: MotionMode.RAPID\n\n\n\n```python\nncp.default(\"G1 Y2.0\")\n```\n\n    \n    Current G Code Settings:\n    \n    {<enum 'PositionMode'>: <PositionMode.ABSOLUTE: 90>,\n     <enum 'CutterOffsetMode'>: <CutterOffsetMode.OFF: 40>,\n     <enum 'NonModal'>: [],\n     <enum 'CannedCycle'>: <CannedCycle.CANCEL: 80>,\n     <enum 'CircularPlane'>: <CircularPlane.XY: 17>,\n     <enum 'Units'>: <Units.INCHES: 20>,\n     <enum 'ToolOffsetMode'>: <ToolOffsetMode.NEGATIVE: 44>,\n     <enum 'ExactStopModal'>: <ExactStopModal.OFF: 64>,\n     <enum 'FeedMode'>: <FeedMode.PER_MINUTE: 94>,\n     <enum 'ReturnMode'>: <ReturnMode.INITIAL_POINT: 98>,\n     <enum 'ScalingMode'>: False,\n     <enum 'Rotation'>: False,\n     <enum 'MotionMode'>: <MotionMode.RAPID: 0>,\n     <class 'int'>: 54}\n    \n    New G Code Settings:\n    \n    {'G': {<enum 'PositionMode'>: <PositionMode.ABSOLUTE: 90>,\n           <enum 'CutterOffsetMode'>: <CutterOffsetMode.OFF: 40>,\n           <enum 'NonModal'>: [],\n           <enum 'CannedCycle'>: <CannedCycle.CANCEL: 80>,\n           <enum 'CircularPlane'>: <CircularPlane.XY: 17>,\n           <enum 'Units'>: <Units.INCHES: 20>,\n           <enum 'ToolOffsetMode'>: <ToolOffsetMode.NEGATIVE: 44>,\n           <enum 'ExactStopModal'>: <ExactStopModal.OFF: 64>,\n           <enum 'FeedMode'>: <FeedMode.PER_MINUTE: 94>,\n           <enum 'ReturnMode'>: <ReturnMode.INITIAL_POINT: 98>,\n           <enum 'ScalingMode'>: False,\n           <enum 'Rotation'>: False,\n           <enum 'MotionMode'>: <MotionMode.LINEAR: 1>,\n           <class 'int'>: 54}}\n    \n    Executing block:  Y2.0;\n    New Result Environment:\n    \n    {'G': {<enum 'PositionMode'>: <PositionMode.ABSOLUTE: 90>,\n           <enum 'CutterOffsetMode'>: <CutterOffsetMode.OFF: 40>,\n           <enum 'NonModal'>: [],\n           <enum 'CannedCycle'>: <CannedCycle.CANCEL: 80>,\n           <enum 'CircularPlane'>: <CircularPlane.XY: 17>,\n           <enum 'Units'>: <Units.INCHES: 20>,\n           <enum 'ToolOffsetMode'>: <ToolOffsetMode.NEGATIVE: 44>,\n           <enum 'ExactStopModal'>: <ExactStopModal.OFF: 64>,\n           <enum 'FeedMode'>: <FeedMode.PER_MINUTE: 94>,\n           <enum 'ReturnMode'>: <ReturnMode.INITIAL_POINT: 98>,\n           <enum 'ScalingMode'>: False,\n           <enum 'Rotation'>: False,\n           <enum 'MotionMode'>: <MotionMode.LINEAR: 1>,\n           <class 'int'>: 54},\n     'Y': 2.0}\n    \n    {'A': 0.0, 'B': 0.0, 'C': 0.0, 'D': 0, 'E': 0.0001, 'F': 0.0, 'G': {<enum 'NonModal'>: [], <enum 'MotionMode'>: <MotionMode.LINEAR: 1>, <enum 'CircularPlane'>: <CircularPlane.XY: 17>, <enum 'PositionMode'>: <PositionMode.ABSOLUTE: 90>, <enum 'FeedMode'>: <FeedMode.PER_MINUTE: 94>, <enum 'Units'>: <Units.INCHES: 20>, <enum 'CutterOffsetMode'>: <CutterOffsetMode.OFF: 40>, <enum 'ToolOffsetMode'>: <ToolOffsetMode.NEGATIVE: 44>, <enum 'CannedCycle'>: <CannedCycle.CANCEL: 80>, <enum 'ReturnMode'>: <ReturnMode.INITIAL_POINT: 98>, <enum 'ScalingMode'>: False, <class 'int'>: 54, <enum 'ExactStopModal'>: <ExactStopModal.OFF: 64>, <enum 'Rotation'>: False}, 'H': 0, 'I': 0.0, 'J': 0.0, 'K': 0.0, 'L': 0.0, 'M': None, 'N': None, 'O': 0, 'P': 0.0, 'Q': 0.0, 'R': 0.0, 'S': 1, 'T': 0, 'U': 0.0001, 'V': 0.0001, 'W': 0.0001, 'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'program': 'ncv', 'version': '0.0.0', 'packages_dir': 'projects/py38'}\n    Moving the tool...\n    Motion mode: MotionMode.LINEAR\n    Motion mode: MotionMode.LINEAR\n\n\n\n```python\nncp.env\n```\n\n\n\n\n    Environment({'G': {<enum 'NonModal'>: [], <enum 'MotionMode'>: <MotionMode.LINEAR: 1>, <enum 'CircularPlane'>: <CircularPlane.XY: 17>, <enum 'PositionMode'>: <PositionMode.ABSOLUTE: 90>, <enum 'FeedMode'>: <FeedMode.PER_MINUTE: 94>, <enum 'Units'>: <Units.INCHES: 20>, <enum 'CutterOffsetMode'>: <CutterOffsetMode.OFF: 40>, <enum 'ToolOffsetMode'>: <ToolOffsetMode.NEGATIVE: 44>, <enum 'CannedCycle'>: <CannedCycle.CANCEL: 80>, <enum 'ReturnMode'>: <ReturnMode.INITIAL_POINT: 98>, <enum 'ScalingMode'>: False, <class 'int'>: 54, <enum 'ExactStopModal'>: <ExactStopModal.OFF: 64>, <enum 'Rotation'>: False}, 'Y': 2.0}, {'G': {<enum 'NonModal'>: [], <enum 'MotionMode'>: <MotionMode.LINEAR: 1>, <enum 'CircularPlane'>: <CircularPlane.XY: 17>, <enum 'PositionMode'>: <PositionMode.ABSOLUTE: 90>, <enum 'FeedMode'>: <FeedMode.PER_MINUTE: 94>, <enum 'Units'>: <Units.INCHES: 20>, <enum 'CutterOffsetMode'>: <CutterOffsetMode.OFF: 40>, <enum 'ToolOffsetMode'>: <ToolOffsetMode.NEGATIVE: 44>, <enum 'CannedCycle'>: <CannedCycle.CANCEL: 80>, <enum 'ReturnMode'>: <ReturnMode.INITIAL_POINT: 98>, <enum 'ScalingMode'>: False, <class 'int'>: 54, <enum 'ExactStopModal'>: <ExactStopModal.OFF: 64>, <enum 'Rotation'>: False}, 'X': 1.0}, {'A': 0.0, 'B': 0.0, 'C': 0.0, 'D': 0, 'E': 0.0001, 'F': 0.0, 'G': {<enum 'NonModal'>: [], <enum 'MotionMode'>: <MotionMode.LINEAR: 1>, <enum 'CircularPlane'>: <CircularPlane.XY: 17>, <enum 'PositionMode'>: <PositionMode.ABSOLUTE: 90>, <enum 'FeedMode'>: <FeedMode.PER_MINUTE: 94>, <enum 'Units'>: <Units.INCHES: 20>, <enum 'CutterOffsetMode'>: <CutterOffsetMode.OFF: 40>, <enum 'ToolOffsetMode'>: <ToolOffsetMode.NEGATIVE: 44>, <enum 'CannedCycle'>: <CannedCycle.CANCEL: 80>, <enum 'ReturnMode'>: <ReturnMode.INITIAL_POINT: 98>, <enum 'ScalingMode'>: False, <class 'int'>: 54, <enum 'ExactStopModal'>: <ExactStopModal.OFF: 64>, <enum 'Rotation'>: False}, 'H': 0, 'I': 0.0, 'J': 0.0, 'K': 0.0, 'L': 0.0, 'M': None, 'N': None, 'O': 0, 'P': 0.0, 'Q': 0.0, 'R': 0.0, 'S': 1, 'T': 0, 'U': 0.0001, 'V': 0.0001, 'W': 0.0001, 'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'program': 'ncv', 'version': '0.0.0', 'packages_dir': 'projects/py38'})\n\n\n\n\n```python\nhelp(ncp.env.new_child)\n```\n\n    Help on method new_child in module collections:\n    \n    new_child(m=None) method of __main__.Environment instance\n        New ChainMap with a new map followed by all previous maps.\n        If no map is provided, an empty dict is used.\n    \n\n\n\n```python\nGCodeGroup.__members__.values()\n```\n\n\n\n\n    dict_values([<GCodeGroup.NON_MODAL: <enum 'NonModal'>>, <GCodeGroup.MOTION: <enum 'MotionMode'>>, <GCodeGroup.PLANE: <enum 'CircularPlane'>>, <GCodeGroup.POSITION_MODE: <enum 'PositionMode'>>, <GCodeGroup.FEED_MODE: <enum 'FeedMode'>>, <GCodeGroup.UNITS: <enum 'Units'>>, <GCodeGroup.CUTTER_COMPENSATION: <enum 'CutterOffsetMode'>>, <GCodeGroup.TOOL_LENGTH: <enum 'ToolOffsetMode'>>, <GCodeGroup.CANNED_CYCLE: <enum 'CannedCycle'>>, <GCodeGroup.RETURN: <enum 'ReturnMode'>>, <GCodeGroup.SCALING: <enum 'ScalingMode'>>, <GCodeGroup.WORK_COORDINATES: <class 'int'>>, <GCodeGroup.EXACT_STOP_MODAL: <enum 'ExactStopModal'>>, <GCodeGroup.ROTATION: <enum 'Rotation'>>])\n\n\n\n\n```python\nncp.make_gcodes_dict([0,17,92,116])\n```\n\n\n\n\n    {<enum 'MotionMode'>: <MotionMode.RAPID: 0>,\n     <enum 'CircularPlane'>: <CircularPlane.XY: 17>,\n     <enum 'NonModal'>: <NonModal.SET_WORK_COORDINATES: 92>,\n     int: 116}\n\n\n\n\n```python\n92 == NonModal.SET_WORK_COORDINATES\n```\n\n\n\n\n    True\n\n\n\n\n```python\n17 in CircularPlane.__members__.values()\n```\n\n\n\n\n    True\n\n\n\n\n```python\nncp.default(\"G00 X0.1 Y0.2 Z0.3 F14.0\")\n```\n\n    \n    Current G Code Settings:\n    \n    {<enum 'PositionMode'>: <PositionMode.ABSOLUTE: 90>,\n     <enum 'CutterOffsetMode'>: <CutterOffsetMode.OFF: 40>,\n     <enum 'NonModal'>: [],\n     <enum 'CannedCycle'>: <CannedCycle.CANCEL: 80>,\n     <enum 'CircularPlane'>: <CircularPlane.XY: 17>,\n     <enum 'Units'>: <Units.INCHES: 20>,\n     <enum 'ToolOffsetMode'>: <ToolOffsetMode.NEGATIVE: 44>,\n     <enum 'ExactStopModal'>: <ExactStopModal.OFF: 64>,\n     <enum 'FeedMode'>: <FeedMode.PER_MINUTE: 94>,\n     <enum 'ReturnMode'>: <ReturnMode.INITIAL_POINT: 98>,\n     <enum 'ScalingMode'>: False,\n     <enum 'Rotation'>: False,\n     <enum 'MotionMode'>: <MotionMode.LINEAR: 1>,\n     <class 'int'>: 54}\n    \n    New G Code Settings:\n    \n    {'G': {<enum 'PositionMode'>: <PositionMode.ABSOLUTE: 90>,\n           <enum 'CutterOffsetMode'>: <CutterOffsetMode.OFF: 40>,\n           <enum 'NonModal'>: [],\n           <enum 'CannedCycle'>: <CannedCycle.CANCEL: 80>,\n           <enum 'CircularPlane'>: <CircularPlane.XY: 17>,\n           <enum 'Units'>: <Units.INCHES: 20>,\n           <enum 'ToolOffsetMode'>: <ToolOffsetMode.NEGATIVE: 44>,\n           <enum 'ExactStopModal'>: <ExactStopModal.OFF: 64>,\n           <enum 'FeedMode'>: <FeedMode.PER_MINUTE: 94>,\n           <enum 'ReturnMode'>: <ReturnMode.INITIAL_POINT: 98>,\n           <enum 'ScalingMode'>: False,\n           <enum 'Rotation'>: False,\n           <enum 'MotionMode'>: <MotionMode.RAPID: 0>,\n           <class 'int'>: 54}}\n    \n    Executing block:  X0.1 Y0.2 Z0.3 F14.0;\n    New Result Environment:\n    \n    {'F': 14.0,\n     'G': {<enum 'PositionMode'>: <PositionMode.ABSOLUTE: 90>,\n           <enum 'CutterOffsetMode'>: <CutterOffsetMode.OFF: 40>,\n           <enum 'NonModal'>: [],\n           <enum 'CannedCycle'>: <CannedCycle.CANCEL: 80>,\n           <enum 'CircularPlane'>: <CircularPlane.XY: 17>,\n           <enum 'Units'>: <Units.INCHES: 20>,\n           <enum 'ToolOffsetMode'>: <ToolOffsetMode.NEGATIVE: 44>,\n           <enum 'ExactStopModal'>: <ExactStopModal.OFF: 64>,\n           <enum 'FeedMode'>: <FeedMode.PER_MINUTE: 94>,\n           <enum 'ReturnMode'>: <ReturnMode.INITIAL_POINT: 98>,\n           <enum 'ScalingMode'>: False,\n           <enum 'Rotation'>: False,\n           <enum 'MotionMode'>: <MotionMode.RAPID: 0>,\n           <class 'int'>: 54},\n     'X': 0.1,\n     'Y': 0.2,\n     'Z': 0.3}\n    \n    {'A': 0.0, 'B': 0.0, 'C': 0.0, 'D': 0, 'E': 0.0001, 'F': 0.0, 'G': {<enum 'NonModal'>: [], <enum 'MotionMode'>: <MotionMode.RAPID: 0>, <enum 'CircularPlane'>: <CircularPlane.XY: 17>, <enum 'PositionMode'>: <PositionMode.ABSOLUTE: 90>, <enum 'FeedMode'>: <FeedMode.PER_MINUTE: 94>, <enum 'Units'>: <Units.INCHES: 20>, <enum 'CutterOffsetMode'>: <CutterOffsetMode.OFF: 40>, <enum 'ToolOffsetMode'>: <ToolOffsetMode.NEGATIVE: 44>, <enum 'CannedCycle'>: <CannedCycle.CANCEL: 80>, <enum 'ReturnMode'>: <ReturnMode.INITIAL_POINT: 98>, <enum 'ScalingMode'>: False, <class 'int'>: 54, <enum 'ExactStopModal'>: <ExactStopModal.OFF: 64>, <enum 'Rotation'>: False}, 'H': 0, 'I': 0.0, 'J': 0.0, 'K': 0.0, 'L': 0.0, 'M': None, 'N': None, 'O': 0, 'P': 0.0, 'Q': 0.0, 'R': 0.0, 'S': 1, 'T': 0, 'U': 0.0001, 'V': 0.0001, 'W': 0.0001, 'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'program': 'ncv', 'version': '0.0.0', 'packages_dir': 'projects/py38'}\n    Moving the tool...\n    Motion mode: MotionMode.RAPID\n    Motion mode: MotionMode.RAPID\n\n", "meta": {"hexsha": "4f135b0d00b25fd5fe8ff5a708a8ef391c16abdd", "size": 70829, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ncv/notes/ncprogram.ipynb", "max_stars_repo_name": "fuzzyklein/gcv-lab", "max_stars_repo_head_hexsha": "9d2c552b8226350dd6f4d5c38a42d1b90d3c3ca7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ncv/notes/ncprogram.ipynb", "max_issues_repo_name": "fuzzyklein/gcv-lab", "max_issues_repo_head_hexsha": "9d2c552b8226350dd6f4d5c38a42d1b90d3c3ca7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ncv/notes/ncprogram.ipynb", "max_forks_repo_name": "fuzzyklein/gcv-lab", "max_forks_repo_head_hexsha": "9d2c552b8226350dd6f4d5c38a42d1b90d3c3ca7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 72.5706967213, "max_line_length": 34536, "alphanum_fraction": 0.7234889664, "converted": true, "num_tokens": 8562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038986, "lm_q2_score": 0.031143828061835372, "lm_q1q2_score": 0.013515844121876078}}
{"text": "<a href=\"https://colab.research.google.com/github/RajeevAtla/HTCS-ML-Team-B/blob/master/sentiment_analysis.ipynb\" target=\"_parent\"></a>\n\n# Building a Sentiment Classifier using Scikit-Learn\n\nAcknowledgement: This is derived from https://towardsdatascience.com/building-a-sentiment-classifier-using-scikit-learn-54c8e7c5d2f0. \n\n<center></center>\n<center><i>Image by AbsolutVision @ <a href=\"https://pixabay.com/ro/photos/smiley-emoticon-furie-sup%C4%83rat-2979107/\">pixabay.com</a></i></center>\n\n> &nbsp;&nbsp;&nbsp;&nbsp;**Sentiment analysis**, an important area in Natural Language Processing, is the process of automatically detecting affective states of text. Sentiment analysis is widely applied to voice-of-customer materials such as product reviews in online shopping websites like Amazon, movie reviews or social media. It can be just a basic task of classifying the polarity of a text as being positive/negative or it can go beyond polarity, looking at emotional states such as \"happy\", \"angry\", etc.\n\n&nbsp;&nbsp;&nbsp;&nbsp;Here we will build a classifier that is able to distinguish movie reviews as being either positive or negative. For that, we will use [Large Movie Review Dataset v1.0](http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz)<sup>(2)</sup> of IMDB movie reviews.\nThis dataset contains 50,000 movie reviews divided evenly into 25k train and 25k test. The labels are balanced between the two classes (positive and negative). Reviews with a score <= 4 out of 10 are labeled negative and those with score >= 7 out of 10 are labeled positive. Neutral reviews are not included in the labeled data. This dataset also contains unlabeled reviews for unsupervised learning; we will not use them here. There are no more than 30 reviews for a particular movie because the ratings of the same movie tend to be correlated. All reviews for a given movie are either in train or test set but not in both, in order to avoid test accuracy gain by memorizing movie-specific terms.\n\n\n\n## Data preprocessing\n\n&nbsp;&nbsp;&nbsp;&nbsp;After the dataset has been downloaded and extracted from archive we have to transform it into a more suitable form for feeding it into a machine learning model for training. We will start by combining all review data into 2 pandas Data Frames representing the train and test datasets, and then saving them as csv files: *imdb_train.csv* and *imdb_test.csv*.  \n\n&nbsp;&nbsp;&nbsp;&nbsp;The Data Frames will have the following form:  \n\n|text       |label      |\n|:---------:|:---------:|\n|review1    |0          |\n|review2    |1          |\n|review3    |1          |\n|.......    |...        |\n|reviewN    |0          |  \n\n&nbsp;&nbsp;&nbsp;&nbsp;where:  \n- review1, review2, ... = the actual text of movie review  \n- 0 = negative review  \n- 1 = positive review\n\n&nbsp;&nbsp;&nbsp;&nbsp;But machine learnng algorithms work only with numerical values. We can't just input the text itself into a machine learning model and have it learn from that. We have to, somehow, represent the text by numbers or vectors of numbers. One way of doing this is by using the **Bag-of-words** model<sup>(3)</sup>, in which a piece of text(often called a **document**) is represented by a vector of the counts of words from a vocabulary in that document. This model doesn't take into account grammar rules or word ordering; all it considers is the frequency of words. If we use the counts of each word independently we name this representation a **unigram**. In general, in a **n-gram** we take into account the counts of each combination of n words from the vocabulary that appears in a given document.  \n\n&nbsp;&nbsp;&nbsp;&nbsp;For example, consider these two documents:  \n<br>  \n<div style=\"font-family: monospace;\"><center><b>d1: \"I am learning\"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></center></div>  \n<div style=\"font-family: monospace;\"><center><b>d2: \"Machine learning is cool\"</b></center></div>  \n<br>\nThe vocabulary of all words encountered in these two sentences is: \n\n<br/>  \n<div style=\"font-family: monospace;\"><center><b>v: [ I, am, learning, machine, is, cool ]</b></center></div>   \n<br>\n&nbsp;&nbsp;&nbsp;&nbsp;The unigram representations of d1 and d2:  \n<br>  \n\n|unigram(d1)|I       |am      |learning|machine |is      |cool    |\n|:---------:|:------:|:------:|:------:|:------:|:------:|:------:|\n|           |1       |1       |1       |0       |0       |0       |  \n\n|unigram(d2)|I       |am      |learning|machine |is      |cool    |\n|:---------:|:------:|:------:|:------:|:------:|:------:|:------:|\n|           |0       |0       |1       |1       |1       |1       |\n  \n&nbsp;&nbsp;&nbsp;&nbsp;And, the bigrams of d1 and d2 are:\n  \n|bigram(d1) |I I     |I am    |I learning|...|machine am|machine learning|...|cool is|cool cool|\n|:---------:|:------:|:------:|:--------:|:-:|:--------:|:--------------:|:-:|:-----:|:-------:|\n|           |0       |1       |0         |...|0         |0               |...|0      |0        |  \n\n|bigram(d2) |I I     |I am    |I learning|...|machine am|machine learning|...|cool is|cool cool|\n|:---------:|:------:|:------:|:--------:|:-:|:--------:|:--------------:|:-:|:-----:|:-------:|\n|           |0       |0       |0         |...|0         |1               |...|0      |0        |\n\n&nbsp;&nbsp;&nbsp;&nbsp;Often, we can achieve slightly better results if instead of counts of words we use something called **term frequency times inverse document frequency** (or **tf-idf**). Maybe it sounds complicated, but it is not. Bear with me, I will explain this. The intuition behind this is the following. So, what's the problem of using just the frequency of terms inside a document? Although some terms may have a high frequency inside documents they may not be so relevant for describing a given document in which they appear. That's because those terms may also have a high frequency across the collection of all documents. For example, a collection of movie reviews may have terms specific to movies/cinematography that are present in almost all documents(they have a high **document frequency**). So, when we encounter those terms in a document this doesn't tell much about whether it is a positive or negative review. We need a way of relating **term frequency** (how frequent a term is inside a document) to **document frequency** (how frequent a term is across the whole collection of documents). That is:  \n  \n$$\\begin{align}\\frac{\\text{term frequency}}{\\text{document frequency}} &= \\text{term frequency} \\cdot \\frac{1}{\\text{document frequency}} \\\\ &= \\text{term frequency} \\cdot \\text{inverse document frequency} \\\\ &= \\text{tf} \\cdot \\text{idf}\\end{align}$$  \n  \n&nbsp;&nbsp;&nbsp;&nbsp;Now, there are more ways used to describe both term frequency and inverse document frequency. But the most common way is by putting them on a logarithmic scale:  \n  \n$$tf(t, d) = log(1+f_{t,d})$$  \n$$idf(t) = log(\\frac{1+N}{1+n_t})$$  \n  \n&nbsp;&nbsp;&nbsp;&nbsp;where:  \n$$\\begin{align}f_{t,d} &= \\text{count of term } \\textbf{t} \\text{ in document } \\textbf{d} \\\\  \nN &= \\text{total number of documents} \\\\  \nn_t &= \\text{number of documents that contain term } \\textbf{t}\\end{align}$$  \n  \n&nbsp;&nbsp;&nbsp;&nbsp;We added 1 in the first logarithm to avoid getting $-\\infty$ when $f_{t,d}$ is 0. In the second logarithm we added one fake document to avoid division by zero.\n\n&nbsp;&nbsp;&nbsp;&nbsp;Before we transform our data into vectors of counts or tf-idf values we should remove English **stopwords**<sup>(6)(7)</sup>. Stopwords are words that are very common in a language and are usually removed in the preprocessing stage of natural text-related tasks like sentiment analysis or search.\n\n&nbsp;&nbsp;&nbsp;&nbsp;Note that we should construct our vocabulary only based on the training set. When we will process the test data in order to make predictions we should use only the vocabulary constructed in the training phase, the rest of the words will be ignored.\n\n&nbsp;&nbsp;&nbsp;&nbsp;Now, let's create the data frames from the supplied csv files:\n\n\n```python\nimport pandas as pd\n```\n\n\n```python\n# Read in the training and test datasets from previously created csv files\n\nimdb_train = pd.read_csv('csv/imdb_train.csv')\nimdb_test = pd.read_csv('csv/imdb_test.csv')\n```\n\n\n```python\n# Display information and first few entries from the training and test datasets\n\npd.set_option('display.max_colwidth', None)\n\nprint (\"----- Training dataset Info:\")\nimdb_train.info(verbose=None, buf=None, max_cols=None, memory_usage=None, null_counts=None)\nprint (\"Training dataset Content:\")\nprint(imdb_train.iloc[:5])\n\nprint (\"\\n----- Test dataset Info:\")\nimdb_test.info(verbose=None, buf=None, max_cols=None, memory_usage=None, null_counts=None)\nprint (\"Test dataset Content:\")\nprint(imdb_test.iloc[:5])\n\n```\n\n    ----- Training dataset Info:\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 25000 entries, 0 to 24999\n    Data columns (total 2 columns):\n     #   Column  Non-Null Count  Dtype \n    ---  ------  --------------  ----- \n     0   text    25000 non-null  object\n     1   label   25000 non-null  int64 \n    dtypes: int64(1), object(1)\n    memory usage: 390.8+ KB\n    Training dataset Content:\n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        text  \\\n    0                                                                                                                                                                                                                                                                                                                                                                                                                                                          This is what I was expecting when star trek DS9 premiered. Not to slight DS9. That was a wonderful show in it's own right, however it never really gave the fans more of what they wanted. Enterprise is that show. While having a similarity to the original trek it differs enough to be original in it's own ways. It makes the ideas of exploration exciting to us again. And that was one of the primary ingredients that made the original so loved. Another ingredient to success was the relationships that evolved between the crew members. Viewers really cared deeply for the crew. Enterprise has much promise in this area as well. The chemistry between Bakula and Blalock seems very promising. While sexual tension in a show can often become a crutch, I feel the tensions on enterprise can lead to much more and say alot more than is typical. I think when we deal with such grand scale characters of different races or species even, we get some very interesting ideas and television. Also, we should note the performances, Blalock is very convincing as Vulcan T'pol and Bacula really has a whimsy and strength of character that delivers a great performance. The rest of the cast delivered good performances also. My only gripes are as follows. The theme. It's good it's different, but a little to light hearted for my liking. We need something a little more grand. Doesn't have to be orchestral. Maybe something with a little more electronic sound would suffice. And my one other complaint. They sell too many adds. They could fix this by selling less ads, or making all shows two parters. Otherwise we'll end up seeing the shows final act getting wrapped up way too quickly as was one of my complaints of Voyager.   \n    1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          This film reminded me so much of \"A History of Violence\" which pretended to be a close study of violence and violent behavior but ended up just being nothing short of a cheap action movie masquerading as some thinking film on violence. Dustin Hoffman and his new British bride move to a small English town and encounter endless harassment from the local drunks who do nothing but hang at the pub all day and make trouble. Don't these men have a job? Anyway, Dustin takes all he can take and by the end of the film he holds up in his house and fights off each one of the drunk attackers by such gruesome means as boiling whiskey poured over someone, feet being blown off by a shotgun and someones head getting caught in a bear trap. Funny that someone would have a need for such a large bear trap in a small British town except maybe put a mans head in it. Sam Peckinpah who made the \"Wild Bunch\" which also covered the topic of blood letting violence in which no one was spared. But it was done with style, and you believed it. Straw Dogs is not believable. First of all the location is wrong and does not work. Why place it in England? I would think maybe in some inner city location or a small town in the American South in the 1930's or something. Second it is not in my view ever really explained clearly why these men are so quick to violence except maybe they got drunk and felt a need to kill Hoffman and rape his wife. Sam Peckinpah missed the mark on this one.   \n    2                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         Theodore Rex is possibly the greatest cinematic experience of all time, and is certainly a milestone in human culture, civilization and artistic expression!! In this compelling intellectual masterpiece, Jonathan R. Betuel aligns himself with the great film makers of the 20th century, such as Francis Ford Copola, Martin Scorcese, Orson Welles and Roman Polanski. The special effects are nothing less than breathtaking, and make any work by Spielberg look trite and elementary. At the time of it's release, Theodore Rex was such a revolutionary gem that it raised the bar of film-making to levels never anticipated by film makers. The concept of making not just a motion picture featuring a dinosaur, but adapting an action packed, thrilling detective novel, co-staring a \"talking\" dinosaur with a post-modern name such as \"Theodore\", and an existential female police officer changed humanity as we know it. The world could never be the same after experiencing such magnificent beauty. Watching Theodore Rex is much akin to looking into the face of God and hearing Him say \"you are my most beloved creation.\" This is one of the few films that is simply TO DIE FOR!!!   \n    3                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Although I didn't like Stanley & Iris tremendously as a film, I did admire the acting. Jane Fonda and Robert De Niro are great in this movie. I haven't always been a fan of Fonda's work but here she is delicate and strong at the same time. De Niro has the ability to make every role he portrays into acting gold. He gives a great performance in this film and there is a great scene where he has to take his father to a home for elderly people because he can't care for him anymore that will break your heart. I wouldn't really recommend this film as a great cinematic entertainment, but I will say you won't see much bette acting anywhere.   \n    4  'De Grot' is a terrific Dutch thriller, based on the book written by Tim Krabb\u00e9. Another of his books, 'Het Gouden Ei' was made into the great Dutch mystery thriller called 'Spoorloos' ('The Vanishing') in 1988. This one is not as good as that thriller (although much better than the American remake also called 'The Vanishing') but there are times it comes close. Especially the opening moments are terrific. We see a man, later we learn his name is Egon Wagter (Fedja van Hu\u00eat), coming from a plane in Thailand. When he picks up his bags it is pretty clear that he is smuggling something across the border. These scenes are perfectly directed, photographed and acted. A kind of suspense is created that you would normally not have in an opening scene like this. Later we see how Egon makes his deal in Thailand with a woman, both stating that they have never done anything like this. From this point the movie is constantly flashback and flash-forward. We see how Egon, still as a child (here played by Erik van der Horst), befriends a guy named Axel (as a kid played by Benja Bruijning). We learn how they grew up as friends, sort of, and how Axel (as an adult played by Marcel Hensema) became a criminal. Egon in the meanwhile goes to college and settles with a woman. Around this time he sometimes meets Axel but does not really want anything to do with him. The movie is chronological in a way. It shows Egon and Axel as kids, than as students, young adults, and in their mid-thirties. But from time to time, like I said, the movie goes back to when they were kids and jumps forward again. Every time we see them as kids it explains something that happens when they are adults. Minor spoilers herein. The title means 'The Cave', and it is the cave that gives the movie its happy ending, although it is in fact not that happy. Like the beginning, the ending is terrific. The middle part of the movie is entertaining and in a way it distracts our attention of the first scenes, only to come back at that point in the end. It is the editing that gives the movie its happy ending, although we can say the dramatic ending is happy in a way as well.   \n    \n       label  \n    0      1  \n    1      0  \n    2      1  \n    3      1  \n    4      1  \n    \n    ----- Test dataset Info:\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 25000 entries, 0 to 24999\n    Data columns (total 2 columns):\n     #   Column  Non-Null Count  Dtype \n    ---  ------  --------------  ----- \n     0   text    25000 non-null  object\n     1   label   25000 non-null  int64 \n    dtypes: int64(1), object(1)\n    memory usage: 390.8+ KB\n    Test dataset Content:\n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         text  \\\n    0                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   Progeny is about a husband and wife who experience time loss while making love. Completely unaware of what this bizarre experience means they try to go on with their lives. The hubby begins questioning the bizarre event and gets help through a very annoying psychiatrist. He comes to believe that aliens are responsible for this lapse in time and that the unborn baby he once thought was his and his wife's actually belongs to the aliens. If ya ask me, this is a great scifi/horror story. Taking a highly questionable real-life scenario involving alien abduction and hybrid breeding is definite thumbs up from this guy. I love all things related to aliens and this story definitely delivered some good ideas. So if you also share an interest in things extraterrestrial, you should be pretty happy with Progeny. At least story-wise anyways. Unfortunately the movie overall is pretty average. With average acting by all actors. Yep, even by the consistently awesome Mr. Dourif, who still does deliver the best performance. Though the black head doctor, delivers his lines really well. There are a few points in the flick where some of the delivery is cringe or laugh worthy, which is fine in my book. I like them cheesy and this had a little bit of some nice stinky cheese, and I mean that in a good way. Anyways, with a less than stellar script you can't really blame all the actors. I especially didn't care for the Mother Hysteria the film went for. She wanted a baby so badly that she'd neglect and dismiss everything her loving husband (who's a doctor!!) said to her. It almost reached a point where you actually didn't care what happened to her. The Progeny is another flick by Brian Yuzna from the icky-sticky film, Society. Again he delivers some slimy effects, and again he delivers a pretty unique tale of horror. If you're into scifi/horror or are a fan of Dourif and or Yuzna films, there's no real reason not to check out this flick if you get the chance. A generous 7 outta 10.   \n    1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         This movie is very similar to Death Warrant with Jean-Claude Van Damme and also has some similarities to Island of Fire with Jackie Chan and I also heard that there is some other very similar action movies, but this film has a much better action than Death Warrant or even Island of Fire (that's right, the Jackie Chan's movie). Rarely American action movies has such a great action sequences, though there was many negative reviews on this film, it easily beats most of the action movies of that time who were more successful. There were many martial art's scenes, David Bradley was fast as Bruce Lee in this film and what else was good, that fighting scenes were much longer than in most of the American martial art's movies. The shoot-out scenes were similar with John Woo's movies, maybe not that good, but still very exiting. There was also many impressive explosions and one great chase scene. I've seen some other David Bradley's movies, but this one, yet is the best in terms of action. OK, this movie has some cheesy moments, but which movie hasn't? The acting was decent, Charles Napier was incredible and his character was real tough. Adam Clark who played Squid and Yuji Okumoto who played the main bad guy were also very good. Other actors acted pretty well too, though the acting isn't important in this type of movies. If you are action movies fan (I mean the real action movies fan, who really can appreciate the good action), than you must see this film.   \n    2                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       This is an excellent movie and I would recommend it to everyone. Mr. Drury's acting is top notch as it always is and he blends well with the other actors in the movie. Can't give away any of the suspense or drama found in the movie. Hell to pay is a must see movie!!! The plot was very suspenseful. I would watch this movie over and over again because it has all the elements of a great western movie. It was very authentic in how they displayed the components dealing with this movie which includes the guns, horses, and clothing. The soundtrack is enjoyable and adds flavor to the movie. James Drury has the right touch when picking out a movie to be involved with. This is a another winner for the western genre. !!!!!   \n    3  The 13th and last RKO Falcon film starts with the mutual injunction by Tom Conway as Tom Lawrence alias the Falcon and Ed Brophy as Goldie of \"No dames!\" whilst they prepare to go on vacation. While you're still wondering what they're going on vacation from as they hadn't had a job since the beginning of the 1st film in 1941 (with Sanders as Gay though and Jenkins as Goldie) they bump into a woman and get dragged into a seedy industrial espionage caper. They promise to help her when her uncle is murdered, by taking an envelope containing the details of a formula to make substitute industrial diamonds to his business colleague in Miami. Suspect everyone here except the cops here who are after Lawrence \u0096 and Goldie for the murder. To console himself Goldie keeps paraphrasing travel brochures: \"On the coldest day you can always enjoy the warmth of a nice cosy electric chair\" for one. Some nice languid atmospheric nightclub scenes rub shoulders with some especially bad behaviour from the baddies. Favourite bit: the dignified game of hide and seek/hunt the thimble the imperturbable and suave Lawrence has with the baddies on the sleeper train. Least favourite bit: the most embarrassing scene in the entire series in the alligator wrestling hut \u0096 definitely thrown in for the kids! All in all not the best in the series but yet another entertaining outing, with an overall satisfying plot and many episodes even in this that make me wish they could have gone on for just a few more years as Columbia did with Boston Blackie, although RKO were churning these out faster. Absolutely no sex, not much violence (in fact none at all by today's high standards), and positively no message all make this type of film anathema to serious people who can only regard movies as an art form that must depend on these three pillars. Three Diet Falcon's were made later with John Calvert in the title role, I don't mind them but could never bring myself to count them into the main series, which Tom Conway had made his own by this time. Sad also that it was all downhill after this for Conway, who moved into TV, voice overs and even played Norman Conquest in Park Plaza 605 rather well in 1953. He also developed serious eye and alcohol problems \u0096 I don't know if they were linked \u0096 wound up poverty stricken and after a spell in hospital in 1967 was found dead in his girlfriend's bed. For us folk that want to at least we still have his 10 entertaining Falcon's plus a number of other worthy, even classic RKO movies from 1942 to 1946 with which to remember him by.   \n    4                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        I LOVE Dr WHo SO much! I believe that David Tennant is the best Dr the show has ever had and Billie Piper the Best companion! I liked the way the Dr and Rose had such a connection and a great relationship and the Dr came close a few times to expressing his love for rose! It sadly came to an end after only 2 seasons. I will miss watching rose heaps and think that the show will not be the same without Rose! But David is still there to make me laugh and make me happy to watch him play this fantastic role! I rate this show 110% it is FANTASTIC! The graphics and monsters in this show are wonderful and every storyline is different but somewhat connected and i have actually learned somethings about love, the world and relationships from this show. Therefore it must be one of the most fantastic shows of all time!   \n    \n       label  \n    0      1  \n    1      1  \n    2      1  \n    3      1  \n    4      1  \n\n\n### Text vectorization\n\n&nbsp;&nbsp;&nbsp;&nbsp;Fortunately, for the text vectorization part all the hard work is already done in the Scikit-Learn classes `CountVectorizer`<sup>(8)</sup> and `TfidfTransformer`<sup>(5)</sup>. We will use these classes to transform our csv files into unigram and bigram matrices(using both counts and tf-idf values). (It turns out that if we only use a n-gram for a large n we don't get a good accuracy, we usually use all n-grams up to some n. So, when we say here bigrams we actually refer to uni+bigrams and when we say unigrams it's just unigrams.) Each row in those matrices will represent a document (review) in our dataset, and each column will represent values associated with each word in the vocabulary (in the case of unigrams) or values associated with each combination of maximum 2 words in the vocabulary (bigrams).  \n\n&nbsp;&nbsp;&nbsp;&nbsp;`CountVectorizer` has a parameter `ngram_range` which expects a tuple of size 2 that controls what n-grams to include. After we constructed a `CountVectorizer` object we should call `.fit()` method with the actual text as a parameter, in order for it to learn the required statistics of our collection of documents. Then, by calling `.transform()` method with our collection of documents it returns the matrix for the n-gram range specified. As the class name suggests, this matrix will contain just the counts. To obtain the tf-idf values, the class `TfidfTransformer` should be used. It has the `.fit()` and `.transform()` methods that are used in a similar way with those of `CountVectorizer`, but they take as input the counts matrix obtained in the previous step and `.transform()` will return a matrix with tf-idf values. We should use `.fit()` only on training data and then store these objects. When we want to evaluate the test score or whenever we want to make a prediction we should use these objects to transform the data before feeding it into our classifier.  \n\n&nbsp;&nbsp;&nbsp;&nbsp;Note that the matrices generated for our train or test data will be huge, and if we store them as normal numpy arrays they will not even fit into RAM. But most of the entries in these matrices will be zero. So, these Scikit-Learn classes are using Scipy sparse matrices<sup>(9)</sup> (`csr_matrix`<sup>(10)</sup> to be more exactly), which store just the non-zero entries and save a LOT of space.  \n\n&nbsp;&nbsp;&nbsp;&nbsp;We will use a linear classifier with stochastic gradient descent, `sklearn.linear_model.SGDClassifier`<sup>(11)</sup>, as our model. First we will generate and save our data in 4 forms: unigram and bigram matrix (with both counts and tf-idf values for each). Then we will train and evaluate our model for each these 4 data representations using `SGDClassifier` with the default parameters. After that, we choose the data representation which led to the best score and we will tune the hyper-parameters of our model with this data form using cross-validation in order to obtain the best results.\n\n\n```python\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\n```\n\n#### Unigram Counts\n\n\n```python\n# Create a unigram vectorizer and process the training set to generate a list of words. \n# Note that unigram processing is set via the ngram_range parameter\n\nunigram_vectorizer = CountVectorizer(ngram_range=(1, 1))\nunigram_vectorizer.fit(imdb_train['text'].values)\n```\n\n\n\n\n    CountVectorizer()\n\n\n\n\n```python\n# Display the length and a few samples of the unigram vectorizer to show the words that have been extracted\n\nprint(\"Number of words found:\", len(unigram_vectorizer.get_feature_names()))\nprint(unigram_vectorizer.get_feature_names()[10000:10100])\nprint(unigram_vectorizer.get_feature_names()[50000:50100])\n```\n\n    Number of words found: 74849\n    ['b\u00eate', 'b\u00fbsu', 'b\u00fcrgermeister', 'c1', 'c3', 'c3p0', 'c3po', 'c4', 'c57', 'c__p', 'ca', 'caaaaaaaaaaaaaaaaaaaaaaligulaaaaaaaaaaaaaaaaaaaaaaa', 'caalling', 'caan', 'caas', 'cab', 'cabal', 'caballe', 'caballeros', 'caballo', 'cabals', 'cabana', 'cabanne', 'cabaret', 'cabarnet', 'cabbage', 'cabbages', 'cabbie', 'cabby', 'cabel', 'cabell', 'cabells', 'cabin', 'cabinet', 'cabinets', 'cabins', 'cabiria', 'cable', 'cables', 'cabo', 'cabot', 'cabr\u00f3n', 'cabs', 'caca', 'caccia', 'cache', 'cachet', 'cacho', 'cack', 'cackle', 'cackles', 'cackling', 'caco', 'cacophonist', 'cacophonous', 'cacophony', 'cacoyanis', 'cacoyannis', 'cacti', 'cactus', 'cactuses', 'cad', 'cada', 'cadaver', 'cadaverous', 'cadavers', 'cadavra', 'cadby', 'caddie', 'caddy', 'caddyshack', 'cadena', 'cadence', 'cadences', 'cadet', 'cadets', 'cadfile', 'cadilac', 'cadillac', 'cadillacs', 'cadmus', 'cadre', 'cads', 'caduta', 'cady', 'caesar', 'caesars', 'caeser', 'caetano', 'cafe', 'cafes', 'cafeteria', 'caffari', 'caffeinated', 'caffeine', 'cafferty', 'caffey', 'caf\u00e9', 'caf\u00e9s', 'cage']\n    ['pincher', 'pinchers', 'pinches', 'pinching', 'pinchot', 'pinciotti', 'pine', 'pineal', 'pineapple', 'pineapples', 'pines', 'pinet', 'pinetrees', 'pineyro', 'pinfall', 'pinfold', 'ping', 'pingo', 'pinhead', 'pinheads', 'pinho', 'pining', 'pinjar', 'pink', 'pinkerton', 'pinkett', 'pinkie', 'pinkins', 'pinkish', 'pinko', 'pinks', 'pinku', 'pinkus', 'pinky', 'pinnacle', 'pinnacles', 'pinned', 'pinning', 'pinnings', 'pinnochio', 'pinnocioesque', 'pino', 'pinocchio', 'pinochet', 'pinochets', 'pinoy', 'pinpoint', 'pinpoints', 'pins', 'pinsent', 'pint', 'pinta', 'pinter', 'pintilie', 'pinto', 'pintos', 'pints', 'pinup', 'pioneer', 'pioneered', 'pioneering', 'pioneers', 'piotr', 'pious', 'piovani', 'pip', 'pipe', 'piped', 'pipedream', 'pipeline', 'piper', 'pipers', 'pipes', 'piping', 'pippi', 'pippin', 'pipsqueak', 'piquant', 'piquantly', 'pique', 'piqued', 'piquer', 'piquor', 'piracy', 'pirahna', 'piranha', 'piranhas', 'pirate', 'pirated', 'piraters', 'pirates', 'pirotess', 'pirouette', 'pirouettes', 'pirouetting', 'pirovitch', 'pirro', 'pis', 'pisa', 'pisana']\n\n\n\n```python\n# Now process the training dataset to get a count of the words extracted earlier\n\nX_train_unigram = unigram_vectorizer.transform(imdb_train['text'].values)\n```\n\n\n```python\n# Display the attributes the word count matrix; notice it is huge with 25000 rows since we have 25000 entries\n# in the training dataset and 74849 columns since we saw above that we have a vocabulary of 74849 words\n\nprint(repr(X_train_unigram))\n```\n\n    <25000x74849 sparse matrix of type '<class 'numpy.int64'>'\n    \twith 3431196 stored elements in Compressed Sparse Row format>\n\n\n#### Unigram Tf-Idf\n\n\n```python\n# Create a unigram tf-idf vectorizer and load the training set using the word count matrix from earlier\n\nunigram_tf_idf_transformer = TfidfTransformer()\nunigram_tf_idf_transformer.fit(X_train_unigram)\n```\n\n\n\n\n    TfidfTransformer()\n\n\n\n\n```python\n# Now calculate the unigram tf-idf statistics\n\nX_train_unigram_tf_idf = unigram_tf_idf_transformer.transform(X_train_unigram)\n```\n\n\n```python\n# Display the attributes the unigram tf-idf matrix; it should be the same size as the unigram matrix above\n\nprint(repr(X_train_unigram_tf_idf))\n```\n\n    <25000x74849 sparse matrix of type '<class 'numpy.float64'>'\n    \twith 3431196 stored elements in Compressed Sparse Row format>\n\n\n#### Bigram Counts\n\n\n```python\n# Create a bigram vectorizer and process the training set to generate a list of bigrams. \n# Note that bigram processing is set via the ngram_range parameter and so includes unigrams and bigrams\n\nbigram_vectorizer = CountVectorizer(ngram_range=(1, 2))\nbigram_vectorizer.fit(imdb_train['text'].values)\n```\n\n\n\n\n    CountVectorizer(ngram_range=(1, 2))\n\n\n\n\n```python\n# Display the length and a few samples of the bigram vectorizer to show the bigrams that have been extracted\n\nprint(\"Number of bigrams found:\", len(bigram_vectorizer.get_feature_names()))\nprint(bigram_vectorizer.get_feature_names()[10000:10100])\nprint(bigram_vectorizer.get_feature_names()[50000:50100])\n```\n\n    Number of bigrams found: 1520266\n    ['3am but', '3am invesment', '3am it', '3am taped', '3bs', '3bs who', '3d', '3d adventure', '3d although', '3d and', '3d animated', '3d animation', '3d animations', '3d animators', '3d artists', '3d assante', '3d bird', '3d bore', '3d capabilities', '3d cg', '3d cgi', '3d character', '3d companies', '3d computer', '3d dept', '3d disgrace', '3d effect', '3d effects', '3d element', '3d ending', '3d environment', '3d especially', '3d feel', '3d game', '3d games', '3d glasses', '3d grafics', '3d graphics', '3d gravity', '3d had', '3d imax', '3d in', '3d it', '3d just', '3d mario', '3d models', '3d movie', '3d movies', '3d panoramic', '3d plat', '3d probably', '3d programs', '3d sequence', '3d shoot', '3d shooter', '3d shooters', '3d special', '3d splatter', '3d technology', '3d that', '3d trust', '3d was', '3d wave', '3d well', '3d which', '3d with', '3d world', '3d wow', '3dvd', '3dvd collection', '3k', '3k all', '3k attack', '3k but', '3k if', '3k it', '3k not', '3lbs', '3lbs is', '3m', '3m to', '3mins', '3mins jack', '3p', '3p felt', '3p uses', '3p wasn', '3p0', '3p0 r2', '3pm', '3pm and', '3po', '3po and', '3po frank', '3po mind', '3rd', '3rd 4th', '3rd act', '3rd and', '3rd annual']\n    ['allen radiation', 'allen randall', 'allen really', 'allen reprises', 'allen reprising', 'allen retains', 'allen retired', 'allen rivkin', 'allen screen', 'allen scripts', 'allen second', 'allen seems', 'allen sees', 'allen set', 'allen she', 'allen should', 'allen showed', 'allen shows', 'allen since', 'allen slowly', 'allen small', 'allen smithee', 'allen soule', 'allen starrer', 'allen stereotypical', 'allen still', 'allen straight', 'allen stuff', 'allen stuttering', 'allen style', 'allen such', 'allen surprisingly', 'allen surrogate', 'allen take', 'allen technique', 'allen tells', 'allen the', 'allen they', 'allen think', 'allen this', 'allen ticks', 'allen to', 'allen treat', 'allen waking', 'allen wannabe', 'allen warning', 'allen was', 'allen we', 'allen when', 'allen whining', 'allen who', 'allen will', 'allen williams', 'allen with', 'allen work', 'allen would', 'allen writes', 'allen writing', 'allen yes', 'allen you', 'allen young', 'allende', 'allende and', 'allende author', 'allende book', 'allende characters', 'allende has', 'allende killed', 'allende magical', 'allende not', 'allende novel', 'allende overthrown', 'allende should', 'allende was', 'allende who', 'allens', 'allens stuff', 'allergic', 'allergic are', 'allergic reaction', 'allergic reactions', 'allergic to', 'allergies', 'allergies kept', 'allergy', 'allergy senator', 'allergy to', 'alles', 'alles action', 'alleviate', 'alleviate her', 'alleviate pain', 'alleviate the', 'alleviate their', 'alleviate visual', 'alley', 'alley 1912', 'alley about', 'alley acting', 'alley again']\n\n\n\n```python\n# Now generate bigram statistics on the training set\n\nX_train_bigram = bigram_vectorizer.transform(imdb_train['text'].values)\n```\n\n\n```python\n# Display the attributes the bigram count matrix; notice it is really huge with 25000 rows since we have 25000 entries\n# in the training dataset and 1520266 columns since we saw above that we have 1520266 bigrams\n\nprint(repr(X_train_bigram))\n```\n\n    <25000x1520266 sparse matrix of type '<class 'numpy.int64'>'\n    \twith 8689547 stored elements in Compressed Sparse Row format>\n\n\n#### Bigram Tf-Idf\n\n\n```python\n# Create a bigram tf-idf vectorizer and load the training set using the bigram count matrix from earlier\n\nbigram_tf_idf_transformer = TfidfTransformer()\nbigram_tf_idf_transformer.fit(X_train_bigram)\n```\n\n\n\n\n    TfidfTransformer()\n\n\n\n\n```python\n# Now calculate the bigram tf-idf statistics\n\nX_train_bigram_tf_idf = bigram_tf_idf_transformer.transform(X_train_bigram)\n```\n\n\n```python\n# Display the attributes the bigram tf-idf matrix; it should be the same size as the bigram matrix above\n\nprint(repr(X_train_bigram_tf_idf))\n```\n\n    <25000x1520266 sparse matrix of type '<class 'numpy.float64'>'\n    \twith 8689547 stored elements in Compressed Sparse Row format>\n\n\n### Try the four different data formats (unigram, bigram with and without tf_idf) on the training set and pick the best\n\n&nbsp;&nbsp;&nbsp;&nbsp;Now, for each data form we split it into train & validation sets, train a `SGDClassifier` and output the score.\n\n\n```python\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.model_selection import train_test_split\nfrom scipy.sparse import csr_matrix\nfrom sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom typing import Tuple\n```\n\n\n```python\n# Helper function to display confusion matrix\n\ndef display_confusion_matrix(y_true, y_pred) -> None:\n    cf_matrix = confusion_matrix(y_true, y_pred)\n    group_names = ['True Neg','False Pos','False Neg','True Pos']\n    group_counts = [\"{0:0.0f}\".format(value) for value in cf_matrix.flatten()]\n    group_percentages = [\"{0:.2%}\".format(value) for value in cf_matrix.flatten()/np.sum(cf_matrix)]\n    labels = [f\"{v1}\\n{v2}\\n{v3}\" for v1, v2, v3 in zip(group_names,group_counts,group_percentages)]\n    labels = np.asarray(labels).reshape(2,2)\n    sns.heatmap(cf_matrix, annot=labels, fmt='', cmap='coolwarm')\n    plt.show()\n    \n```\n\n\n```python\ndef train_and_show_scores(X: csr_matrix, y: np.array, title: str) -> Tuple[float, float]:\n    X_train, X_valid, y_train, y_valid = train_test_split(\n        X, y, train_size=0.75, stratify=y\n    )\n\n    clf = SGDClassifier()\n    clf.fit(X_train, y_train)\n    train_score = clf.score(X_train, y_train)\n    valid_score = clf.score(X_valid, y_valid)\n    print(f'{title}\\nTrain score: {round(train_score, 2)} ; Validation score: {round(valid_score, 2)}')\n    \n    train_pred = clf.predict(X_train)\n    valid_pred = clf.predict(X_valid)\n    print(f'Train precision: {round(precision_score(y_train, train_pred), 2)} ; Validation precision: {round(precision_score(y_valid, valid_pred), 2)}')\n    print(f'Train recall: {round(recall_score(y_train, train_pred), 2)} ; Validation recall: {round(recall_score(y_valid, valid_pred), 2)}')\n    print(f'Train F1: {round(f1_score(y_train, train_pred), 2)} ; Validation F1: {round(f1_score(y_valid, valid_pred), 2)}')\n    print(\"Train Confusion Matrix: \")\n    print(confusion_matrix(y_train, train_pred))\n    display_confusion_matrix(y_train, train_pred)\n    print(\"Validation Confusion Matrix: \")\n    print(confusion_matrix(y_valid, valid_pred))\n    display_confusion_matrix(y_valid, valid_pred)\n    print(\"\\n\")\n    \n    return train_score, valid_score, clf\n```\n\n\n```python\ny_train = imdb_train['label'].values\n```\n\n\n```python\nuc_train_score, uc_valid_score, uc_clf = train_and_show_scores(X_train_unigram, y_train, '----- Unigram Counts -----')\nutfidf_train_score, utfidf_valid_score, utfidf_clf = train_and_show_scores(X_train_unigram_tf_idf, y_train, '----- Unigram Tf-Idf -----')\nbc_train_score, bc_valid_score, bc_clf = train_and_show_scores(X_train_bigram, y_train, '----- Bigram Counts -----')\nbtfidf_train_score, btfidf_valid_score, btfidf_clf = train_and_show_scores(X_train_bigram_tf_idf, y_train, '----- Bigram Tf-Idf -----')\n```\n\n\n```python\n# Display the previously derived scores for the four scenarios\n\nsns.set_style(\"whitegrid\", {'grid.linestyle': '--'})\n\nprint (\"Training score for the four approaches:\")\nax1 = sns.barplot(\n    x= ['Unigram Count', 'Unigram tf-idf', 'Bigram Count', 'Bigram tf-idf'],\n    y= [uc_train_score, utfidf_train_score, bc_train_score, btfidf_train_score])\nax1.set(ylim=(0.8, 1.0))\nplt.show()\n\nprint (\"Validation score for the four approaches:\")\nax2 = sns.barplot(\n    x= ['Unigram Count', 'Unigram tf-idf', 'Bigram Count', 'Bigram tf-idf'],\n    y= [uc_valid_score, utfidf_valid_score, bc_valid_score, btfidf_valid_score])\nax2.set(ylim=(0.8, 1.0))\nplt.show()\n```\n\n&nbsp;&nbsp;&nbsp;&nbsp;The best data form seems to be **bigram with tf-idf** as it gets the highest validation accuracy: **0.9**; so we will choose it as our preferred approach.\n\n### Testing model\n\n\n```python\n# Transform the test data set into the bigram tf-idf format\n\nX_test = bigram_vectorizer.transform(imdb_test['text'].values)\nX_test = bigram_tf_idf_transformer.transform(X_test)\ny_test = imdb_test['label'].values\n```\n\n\n```python\n# Now evaluate the test data using the previously trained bigram tf-idf classifier\n\nclf = btfidf_clf\nscore = clf.score(X_test, y_test)\n\nprint(f'Score: {round(score, 4)}')\n\ntest_pred = clf.predict(X_test)\nprint(f'Test precision: {round(precision_score(y_test, test_pred), 4)}')\nprint(f'Test recall: {round(recall_score(y_test, test_pred), 4)}')\nprint(f'Test F1: {round(f1_score(y_test, test_pred), 4)}')\nprint(\"Test Confusion Matrix: \")\nprint(confusion_matrix(y_test, test_pred))\ndisplay_confusion_matrix(y_test, test_pred)\nprint(\"\\n\")\n```\n\n&nbsp;&nbsp;&nbsp;&nbsp;And we got almost 90% test accuracy. That's not bad for our simple linear model. There are more advanced methods that give better results. The current state-of-the-art on this dataset is **97.42%** <sup>(13)</sup>\n\n## References\n\n<sup>(1)</sup> &nbsp;[Sentiment Analysis - Wikipedia](https://en.wikipedia.org/wiki/Sentiment_analysis)  \n<sup>(2)</sup> &nbsp;[Learning Word Vectors for Sentiment Analysis](http://ai.stanford.edu/~amaas/papers/wvSent_acl2011.pdf)  \n<sup>(3)</sup> &nbsp;[Bag-of-words model - Wikipedia](https://en.wikipedia.org/wiki/Bag-of-words_model)  \n<sup>(4)</sup> &nbsp;[Tf-idf - Wikipedia](https://en.wikipedia.org/wiki/Tf%E2%80%93idf)  \n<sup>(5)</sup> &nbsp;[TfidfTransformer - Scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfTransformer.html)  \n<sup>(6)</sup> &nbsp;[Stop words - Wikipedia](https://en.wikipedia.org/wiki/Stop_words)  \n<sup>(7)</sup> &nbsp;[A list of English stopwords](https://gist.github.com/sebleier/554280)  \n<sup>(8)</sup> &nbsp;[CountVectorizer - Scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html)  \n<sup>(9)</sup> &nbsp;[Scipy sparse matrices](https://docs.scipy.org/doc/scipy/reference/sparse.html)  \n<sup>(10)</sup> [Compressed Sparse Row matrix](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html#scipy.sparse.csr_matrix)  \n<sup>(11)</sup> [SGDClassifier - Scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDClassifier.html)  \n<sup>(12)</sup> [RandomizedSearchCV - Scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html)  \n<sup>(13)</sup> [Sentiment Classification using Document Embeddings trained with\nCosine Similarity](https://www.aclweb.org/anthology/P19-2057.pdf)  \n", "meta": {"hexsha": "de194743327c7608705e560bda83a28a6bef7d57", "size": 246037, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "sentiment_analysis.ipynb", "max_stars_repo_name": "RajeevAtla/HTCS-ML", "max_stars_repo_head_hexsha": "222e4406ad68d6c1d703d11dfccd20decc2cf08c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sentiment_analysis.ipynb", "max_issues_repo_name": "RajeevAtla/HTCS-ML", "max_issues_repo_head_hexsha": "222e4406ad68d6c1d703d11dfccd20decc2cf08c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sentiment_analysis.ipynb", "max_forks_repo_name": "RajeevAtla/HTCS-ML", "max_forks_repo_head_hexsha": "222e4406ad68d6c1d703d11dfccd20decc2cf08c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 194.1886345699, "max_line_length": 17238, "alphanum_fraction": 0.807549271, "converted": true, "num_tokens": 11249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19930799790404566, "lm_q2_score": 0.06754669770938669, "lm_q1q2_score": 0.013462597085487648}}
{"text": "- title: Discovery of Useful Questions as Auxiliary Tasks\n- summary: Learning more like a human, and more like a scientist, by actively seeking useful auxiliary questions during learning.\n- author: Daniel Cox\n- date: 2019-09-15\n- category: arXiv highlights\n- image: /static/images/arXiv.gif\n\nIn case you're wondering what happened to your feed reader this week: We've decided to retitle all of the arXiv highlights posts to be more attractive. We promise not to do this often, but it seemed like a good time to do it while we're inconveniencing very few people.\n\n# This week\n\nThis week's paper is [Discovery of Useful Questions as Auxiliary Tasks](https://arxiv.org/abs/1909.04607v1) from the University of Michigan and DeepMind. It was accepted to NeurIPS 2019 (which I rather hope I'll be attending). The paper contains a very exciting concept that strikes at the heart of human learning: We learn not only by noticing statistical correlations and inferring concepts, but by actively seeking the answers to helpful questions that occur to us as we navigate the world. That's also much of what science is about: increasing your understanding of the world by choosing particularly good questions to ask.\n\n# Useful questions as an auxiliary task\n\nThe authors formulate the problem as a reinforcement learning problem with a main task you'd like to accomplished, augmented with auxiliary tasks generated by the system itself to aid in representation learning, and ultimately to accomplish the main task more efficiently. I've mentioned before that this is of professional interest to me.\n\nIn this paper the questions are represented as \"general value functions\" (GVFs), \"a fairly rich form of knowledge representation\", because\n\n> GVF-based auxiliary tasks have been shown in previous work to improve the sampling efficiency of reinforcement learning agents engaged in learning some complex task....\n> It was then shown that by combining gradients from learning the auxiliary GVFs with the updates from the main task, it was possible to accelerate representation learning and improve performance. It fell, however, onto the algorithm designer to design questions that were useful for the specific task.\n\nThe main insight in this paper is that the gradients induced while learning the main task contain information about what questions would aid in learning a helpful representation.\n\n> The main idea is to use meta-gradient RL to discover the questions so that answering them maximises the usefulness of the induced representation on the main task.\n\n# Auxiliary tasks\n\nWhy should learning something other than the main task help? It teaches composable fundamentals relevant to the task so that the neural network doesn't have to learn everything from scratch all at once. The kinds of auxiliary tasks we're talking about here are things like controlling pixel intensities and feature activations. Other examples mentioned in the paper are auxiliary tasks where the agent needed to learn to measure depth, loop-closures (e.g., the letter \"C\" is not closed, but the letter \"O\" is), observation reconstruction (which, as an aside, can be used in the construction of intrinsically-motivated, \"curious\" agents), reward prediction, etc. When agents were required to learn each of these tasks simultaneously with learning their own main tasks, they learned more efficiently than when they were required to learn their main task alone.\n\nBut, as we just discussed, each of these examples (see the paper for more) and were hand-crafted. The agents themselves did not attempt to add to their tasks, and careful hand-tuning was required to get the observed improvements.\n\n# Meta-learning\n\n> A meta-learner progressively improves the learning process of a learner that is attempting to solve some task.\n\nI can hardly overstate how useful this is. In my own work, we aren't done as soon as we've trained a neural network to perform well on a single task. There is an entire host of related tasks on which we'll need to retrain it in the future. Our work involves training an agent to control the behavior of some software, which is not fixed. If our agent cannot be quickly retrained on other software (perhaps out of our direct control), then it becomes much more expensive and difficult to maintain.\n\nThis paper mentions previous work in learning better initializations for a given task, learning to explore, unsupervised learning to develop a good or compact representation, few-shot model adaptation, and learning to improve the optimizers.\n\n# The discovery of useful questions\n\nThis is Figure 1 of our paper, depicting the architecture that discovers and uses useful questions. It consists of two neural networks, a main task & answer network parametrized by $\\theta$, and a question network parametrized by $\\eta$. The main task & answer network takes the last $i$ observations $o_{t-i+1:t}$ in and produces two categories of output: a) decisions from the policy $\\pi_t$ and b) answers to the \"useful questions\" $y_t$. The question network takes $j$ _future_ observations $o_{t+1:t+j}$, and produces two outputs: a) _cumulants_ $u_t$, and b) discounts $\\gamma_t$. Cumulants (a term from the GVF literature) are described as scalar functions of the state, the sum of which must be maximized. To me, this just sounds like an obstruse way to say \"other loss function\", which makes sense because these are what are describing our auxiliary goals.\n\n\n\nLest you think this method requires time travel, fear not. We can see $j$ steps into the future using the time machine of Waiting, which is ok because it only happens during training.\n\nAs the authors explain, previous work with auxiliary tasks would have only had the main task & answer network on the left, because the cumulants and discounts were hand-crafted. The question network on the right, and its effective use, is the main contribution of this paper. The _number_ of \"other loss functions\" is still fixed, but the components of the actual functions that compute them (cumulants and discounts) are represented by an $\\eta$-parametrized neural network that is itself trained _on the gradients of the $\\theta$-parametrized main task and answer network_. \n\nIn the researcher's own words:\n\n> In their most abstract form, reinforcement learning algorithms can be described by an update procedure $\\Delta \\theta_t$ that modifies, on each step $t$, the agent's parameters $\\theta_t$. The central idea of meta-gradient RL is to parameterise the update $\\Delta \\theta_t(\\eta)$ by meta-parameters $\\eta$. We may then consider the consequences of changing $\\eta$ on the $\\eta$-parameterised update rule by measuring the subsequent performance of the agent, in terms of a \"meta-loss\" function $m(\\theta_{t+k})$. Such meta-loss may be evaluated after one update (myopic) or $k > 1$ updates (non-myopic). The meta-gradient is then, by the chain rule,\n\\begin{align}\n{\\partial m(\\theta_{t+k})} \\over {\\partial\\eta} &= {\\partial m(\\theta_{t+k}) \\over \\partial\\theta_{t+k}} {\\partial\\theta_{t+k} \\over \\partial\\eta}.\\label{eqn:no_approx}\n\\end{align}\n\nThe actual computation of this is challenging, because changing $\\eta$ affects updates to $\\theta$ on _all future timesteps_. This is the reason training the question network requires looking $j$ steps \"into the future\". Holding $\\eta$ fixed, they compute $\\theta_t \\rightarrow ... \\rightarrow \\theta_{t+j}$, in order to finally compute the meta-loss evaluation $m(\\theta_{t+j})$.\n\nThe algorithm then alternates between normal RL training of the main task & answer network, and meta-gradient training of the question network to produce and use questions that maximize the performance of the agent on the original task. It is a very general solution, and empirically outperforms hand-designed auxiliary tasks in many cases.\n\n# Parting thoughts\n\n1. The authors themselves note that their algorithm augments an _on-policy_ reinforcement learning algorithm, and I look forward to their promised future work adapting these techniques to an off-policy setting.\n2. I notice I take detours from the main article purposes to write about areas of RL that I want to remember to investigate further in the future (e.g., auxiliary task in general, and meta-learning in general). That's a good habit, though I'll need to remember to cultivate it without seeming too distracted.\n3. This paper mentions that Xu et al. in 2018 tried learning the discount factor $\\gamma$ and the bootstrapping factor $\\lambda$ (using meta-gradients), which is an idea I had myself (a year later). Apparently this substantially improved performance on the Atari domain, so I feel vindicated.\n", "meta": {"hexsha": "6d35b7fe187e8005c7bf6c897ac2f8b030bcd252", "size": 10330, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "content/Discovery of Useful Questions as Auxiliary Tasks.ipynb", "max_stars_repo_name": "computableai/computableai.github.io", "max_stars_repo_head_hexsha": "5dff9eb1a4adc2a9c5d10328c4bd8d665f13d0f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-13T17:14:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-07T20:17:06.000Z", "max_issues_repo_path": "content/Discovery of Useful Questions as Auxiliary Tasks.ipynb", "max_issues_repo_name": "computableai/computableai.github.io", "max_issues_repo_head_hexsha": "5dff9eb1a4adc2a9c5d10328c4bd8d665f13d0f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2019-06-29T23:13:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T23:46:45.000Z", "max_forks_repo_path": "content/Discovery of Useful Questions as Auxiliary Tasks.ipynb", "max_forks_repo_name": "computableai/computableai.github.io", "max_forks_repo_head_hexsha": "5dff9eb1a4adc2a9c5d10328c4bd8d665f13d0f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-06-05T00:20:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T07:19:34.000Z", "avg_line_length": 77.6691729323, "max_line_length": 882, "alphanum_fraction": 0.7201355276, "converted": true, "num_tokens": 1837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.038466191880538673, "lm_q1q2_score": 0.013411050673971931}}
{"text": "# Setup\n\n\n```python\n%matplotlib inline\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\n```\n\n\n```python\ndate_filename = \"2018-02-01_2018-02-28\"\n```\n\n\n```python\ndata = pd.read_csv(\"articles_\" + date_filename + \".csv\", index_col=\"id\", \\\n                   parse_dates=[\"published\", \"discovered\"])\ndata.head()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>publisher_name</th>\n      <th>publisher_id</th>\n      <th>mins_as_lead</th>\n      <th>mins_on_front</th>\n      <th>num_articles_on_front</th>\n      <th>fb_brand_page</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>402fd72431c6a0e29e76fc9abaa6bc0d42f2ea81</th>\n      <td>https://www.thetimes.co.uk/article/mistakes-pr...</td>\n      <td>\u2018Mistakes\u2019 prove costly for a chastened H&amp;M</td>\n      <td>2018-02-01 00:06:11.391</td>\n      <td>2018-02-01</td>\n      <td>0</td>\n      <td>0.000000</td>\n      <td>2018-02-01T01:19:11.780Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>1440</td>\n      <td>283.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>125.0</td>\n    </tr>\n    <tr>\n      <th>956698308752aa83f6ad988aa05a4f26f5514f9e</th>\n      <td>https://www.thetimes.co.uk/article/met-office-...</td>\n      <td>Met Office puts accent on the regions</td>\n      <td>2018-02-01 00:05:43.754</td>\n      <td>2018-02-01</td>\n      <td>2</td>\n      <td>0.016407</td>\n      <td>2018-02-01T09:25:15.520Z</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>1440</td>\n      <td>283.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>125.0</td>\n    </tr>\n    <tr>\n      <th>1524679962f3bef642390e1955d470fe0acc2aff</th>\n      <td>https://www.thetimes.co.uk/article/world-s-ric...</td>\n      <td>World\u2019s richest offer \u00a3100k salaries for Briti...</td>\n      <td>2018-02-01 00:05:46.313</td>\n      <td>2018-02-01</td>\n      <td>9</td>\n      <td>0.032886</td>\n      <td>2018-02-01T18:33:06.181Z</td>\n      <td>1</td>\n      <td>2</td>\n      <td>6</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>1440</td>\n      <td>283.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>125.0</td>\n    </tr>\n    <tr>\n      <th>13646fa08dee5c8b5bdd718ab882cb988a1eb85f</th>\n      <td>https://www.thetimes.co.uk/article/mother-give...</td>\n      <td>Mother gives birth in jail as vital evidence i...</td>\n      <td>2018-02-01 00:05:37.255</td>\n      <td>2018-02-01</td>\n      <td>5</td>\n      <td>0.033241</td>\n      <td>2018-02-01T16:31:16.418Z</td>\n      <td>1</td>\n      <td>2</td>\n      <td>2</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>1440</td>\n      <td>283.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>125.0</td>\n    </tr>\n    <tr>\n      <th>44dccc673596c768f1129a020c1b6b0c6ff8ab66</th>\n      <td>https://www.thetimes.co.uk/article/apple-inves...</td>\n      <td>Apple investigated over phone slowdown</td>\n      <td>2018-02-01 00:05:38.393</td>\n      <td>2018-02-01</td>\n      <td>12</td>\n      <td>0.065574</td>\n      <td>2018-02-01T11:27:12.692Z</td>\n      <td>5</td>\n      <td>4</td>\n      <td>3</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>1440</td>\n      <td>283.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>125.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n# Response Score\n\nThe response score is a number between 0 and 50 that indicates the level of response to an article.\n\n\n\nPerhaps in the future we may choose to include other factors, but for now we just include engagements on Facebook. The maximum score of 50 should be achieved by an article that does really well compared with others.\n\n\n```python\npd.options.display.float_format = '{:.2f}'.format\ndata.fb_engagements.describe([0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count    136062.00\n    mean       1237.17\n    std       11019.23\n    min           0.00\n    50%          25.00\n    75%         241.00\n    90%        1453.00\n    95%        3841.85\n    99%       23172.80\n    99.5%     38692.09\n    99.9%    116762.69\n    max     1733438.00\n    Name: fb_engagements, dtype: float64\n\n\n\nThere's 2 articles with more than 1 million engagements this month.\n\n\n```python\ndata[data.fb_engagements > 1000000]\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>publisher_name</th>\n      <th>publisher_id</th>\n      <th>mins_as_lead</th>\n      <th>mins_on_front</th>\n      <th>num_articles_on_front</th>\n      <th>fb_brand_page</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>fb1944a99013e1b35fd6a91c48804999102e083e</th>\n      <td>https://www.nbcnews.com/politics/donald-trump/...</td>\n      <td>Trump Signs Bill Revoking Obama-Era Gun Checks...</td>\n      <td>2018-02-15 21:25:15.475</td>\n      <td>2018-02-15 21:23:07</td>\n      <td>1733438</td>\n      <td>4222.05</td>\n      <td>2018-02-17T21:37:14.123Z</td>\n      <td>579201</td>\n      <td>879715</td>\n      <td>274522</td>\n      <td>NBC News</td>\n      <td>nbcnews_com</td>\n      <td>0</td>\n      <td>230</td>\n      <td>123.00</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>826</td>\n      <td>410.00</td>\n    </tr>\n    <tr>\n      <th>eb66c2d3e4862b7dd4b1321a8636fd9ce19a9454</th>\n      <td>http://www.foxnews.com/us/2018/02/16/florida-t...</td>\n      <td>Florida Teacher of the Year's gun violence pos...</td>\n      <td>2018-02-16 20:39:09.526</td>\n      <td>2018-02-16 20:01:41</td>\n      <td>1005295</td>\n      <td>2850.50</td>\n      <td>2018-02-17T06:02:17.750Z</td>\n      <td>119159</td>\n      <td>699578</td>\n      <td>186558</td>\n      <td>Fox News</td>\n      <td>foxnews_com</td>\n      <td>0</td>\n      <td>1168</td>\n      <td>170.00</td>\n      <td>True</td>\n      <td>16202655.00</td>\n      <td>2018-02-16T23:46:04.000Z</td>\n      <td>285</td>\n      <td>660.00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndata.fb_engagements.mode()\n```\n\n\n\n\n    0    0\n    dtype: int64\n\n\n\n*november* Going back to the enagement counts, we see the mean is 1,117, mode is zero, median is 24, 90th percentile is 1,453, 99th percentile is 21,166, 99.5th percentile is 33,982. The standard deviation is 8,083, significantly higher than the mean, so this is not a normal distribution. \n\n*december* Going back to the enagement counts, we see the mean is 1,106, mode is zero, median is 24, 90th percentile is 1,545, 99th percentile is 20,228, 99.5th percentile is 32,446. The standard deviation is 9,852, significantly higher than the mean, so this is not a normal distribution. \n\n*january 2018* Going back to the enagement counts, we see the mean is 1,108, mode is zero, median is 26, 90th percentile is 1,621, 99th percentile is 19,918, 99.5th percentile is 32,935. The standard deviation is 8,278, significantly higher than the mean, so this is not a normal distribution. \n\n*febrary 2018* Going back to the enagement counts, we see the mean is 1,237, mode is zero, median is 25, 90th percentile is 1,453, 99th percentile is 23,172, 99.5th percentile is 38,692. The standard deviation is 11,019, significantly higher than the mean, so this is not a normal distribution. \n\nKey publishers stats\n\n\n```python\ndata.groupby(\"publisher_id\").agg({'url': 'count', 'fb_engagements': ['sum', 'median', 'mean']})\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th>url</th>\n      <th colspan=\"3\" halign=\"left\">fb_engagements</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>count</th>\n      <th>sum</th>\n      <th>median</th>\n      <th>mean</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>28</td>\n      <td>94804</td>\n      <td>1286.50</td>\n      <td>3385.86</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>11509</td>\n      <td>8867217</td>\n      <td>29.00</td>\n      <td>770.46</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>2565</td>\n      <td>9295242</td>\n      <td>182.00</td>\n      <td>3623.88</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>59</td>\n      <td>39801</td>\n      <td>230.00</td>\n      <td>674.59</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>1323</td>\n      <td>4651835</td>\n      <td>218.00</td>\n      <td>3516.13</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>3898</td>\n      <td>23528295</td>\n      <td>565.00</td>\n      <td>6035.99</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>23015</td>\n      <td>13477979</td>\n      <td>21.00</td>\n      <td>585.62</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>501</td>\n      <td>165074</td>\n      <td>36.00</td>\n      <td>329.49</td>\n    </tr>\n    <tr>\n      <th>evolvepolitics_com</th>\n      <td>63</td>\n      <td>188901</td>\n      <td>1697.00</td>\n      <td>2998.43</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>5592</td>\n      <td>16520792</td>\n      <td>66.00</td>\n      <td>2954.36</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>4368</td>\n      <td>322462</td>\n      <td>4.00</td>\n      <td>73.82</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>2498</td>\n      <td>12873544</td>\n      <td>710.00</td>\n      <td>5153.54</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>5246</td>\n      <td>3799617</td>\n      <td>33.00</td>\n      <td>724.29</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>434</td>\n      <td>487881</td>\n      <td>90.50</td>\n      <td>1124.15</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>3765</td>\n      <td>1695720</td>\n      <td>63.00</td>\n      <td>450.39</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>149</td>\n      <td>2012</td>\n      <td>7.00</td>\n      <td>13.50</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>9642</td>\n      <td>5307000</td>\n      <td>30.00</td>\n      <td>550.40</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>1685</td>\n      <td>8958300</td>\n      <td>458.00</td>\n      <td>5316.50</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>418</td>\n      <td>85245</td>\n      <td>30.00</td>\n      <td>203.94</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>1952</td>\n      <td>9781344</td>\n      <td>255.50</td>\n      <td>5010.93</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>4352</td>\n      <td>17345404</td>\n      <td>215.00</td>\n      <td>3985.62</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>240</td>\n      <td>73039</td>\n      <td>169.00</td>\n      <td>304.33</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>41</td>\n      <td>61980</td>\n      <td>570.00</td>\n      <td>1511.71</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>5653</td>\n      <td>2095413</td>\n      <td>18.00</td>\n      <td>370.67</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>2199</td>\n      <td>1881653</td>\n      <td>238.00</td>\n      <td>855.69</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>102</td>\n      <td>47299</td>\n      <td>244.50</td>\n      <td>463.72</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>6223</td>\n      <td>1530290</td>\n      <td>16.00</td>\n      <td>245.91</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>182</td>\n      <td>179683</td>\n      <td>493.50</td>\n      <td>987.27</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>7750</td>\n      <td>8451675</td>\n      <td>117.00</td>\n      <td>1090.54</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>8336</td>\n      <td>307256</td>\n      <td>1.00</td>\n      <td>36.86</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>21670</td>\n      <td>14148474</td>\n      <td>0.00</td>\n      <td>652.91</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>206</td>\n      <td>239325</td>\n      <td>49.50</td>\n      <td>1161.77</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>398</td>\n      <td>1826893</td>\n      <td>123.50</td>\n      <td>4590.18</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\n\nnon_zero_fb_enagagements = data.fb_engagements[data.fb_engagements > 0]\n```\n\nThat's a bit better, but still way too clustered at the low end. Let's look at a log normal distribution.\n\n\n```python\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\nninety = data.fb_engagements.quantile(.90)\nninetyfive = data.fb_engagements.quantile(.95)\nninetynine = data.fb_engagements.quantile(.99)\n\nplt.figure(figsize=(12,4.5))\nplt.hist(np.log(non_zero_fb_enagagements + median), bins=50)\nplt.axvline(np.log(mean), linestyle=':', label=f'Mean ({mean:,.0f})', color='green')\nplt.axvline(np.log(median), label=f'Median ({median:,.0f})', color='green')\nplt.axvline(np.log(ninety), linestyle='--', label=f'90% percentile ({ninety:,.0f})', color='red')\nplt.axvline(np.log(ninetyfive), linestyle='-.', label=f'95% percentile ({ninetyfive:,.0f})', color='red')\nplt.axvline(np.log(ninetynine), linestyle=':', label=f'99% percentile ({ninetynine:,.0f})', color='red')\nleg = plt.legend()\n\n```\n\n\n```python\neng = data.fb_engagements[(data.fb_engagements < 5000)]\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\nninety = data.fb_engagements.quantile(.90)\nninetyfive = data.fb_engagements.quantile(.95)\nninetynine = data.fb_engagements.quantile(.99)\n\nplt.figure(figsize=(15,7))\nplt.hist(eng, bins=50)\nplt.title(\"Article count by engagements\")\nplt.axvline(median, label=f'Median ({median:,.0f})', color='green')\nplt.axvline(mean, linestyle=':', label=f'Mean ({mean:,.0f})', color='green')\nplt.axvline(ninety, linestyle='--', label=f'90% percentile ({ninety:,.0f})', color='red')\nplt.axvline(ninetyfive, linestyle='-.', label=f'95% percentile ({ninetyfive:,.0f})', color='red')\n# plt.axvline(ninetynine, linestyle=':', label=f'99% percentile ({ninetynine:,.0f})', color='red')\nleg = plt.legend()\n\n```\n\n\n```python\nlog_engagements = (non_zero_fb_enagagements\n                   .clip_upper(data.fb_engagements.quantile(.999))\n                   .apply(lambda x: np.log(x + median))\n                  )\nlog_engagements.describe()\n```\n\n\n\n\n    count   110738.00\n    mean         4.99\n    std          1.75\n    min          3.26\n    25%          3.53\n    50%          4.41\n    75%          6.03\n    max         11.67\n    Name: fb_engagements, dtype: float64\n\n\n\nUse standard feature scaling to bring that to a 1 to 50 range\n\n\n\n```python\ndef scale_log_engagements(engagements_logged):\n    return np.ceil(\n        50 * (engagements_logged - log_engagements.min()) / (log_engagements.max() - log_engagements.min())\n    )\n\ndef scale_engagements(engagements):\n    return scale_log_engagements(np.log(engagements + median))\n\nscaled_non_zero_engagements = scale_log_engagements(log_engagements)\nscaled_non_zero_engagements.describe()\n```\n\n\n\n\n    count   110738.00\n    mean        10.78\n    std         10.43\n    min          0.00\n    25%          2.00\n    50%          7.00\n    75%         17.00\n    max         50.00\n    Name: fb_engagements, dtype: float64\n\n\n\n\n```python\n# add in the zeros, as zero\nscaled_engagements = pd.concat([scaled_non_zero_engagements, data.fb_engagements[data.fb_engagements == 0]])\n```\n\n\n```python\nproposed = pd.DataFrame({\"fb_engagements\": data.fb_engagements, \"response_score\": scaled_engagements})\nproposed.response_score.plot.hist(bins=50)\n```\n\nLooks good to me, lets save that.\n\n\n```python\ndata[\"response_score\"] = proposed.response_score\n```\n\n### Proposal\n\nThe maximum of 50 points is awarded when the engagements are greater than the 99.9th percentile, rolling over the last month. \n\ni.e. where $limit$ is the 99.5th percentile of engagements calculated over the previous month, the response score for article $a$ is:\n\n\\begin{align}\nbasicScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   \\log(\\min(engagements_a,limit) + median(engagements))      & \\text{if } engagements_a > 0\n\\end{cases} \\\\\nresponseScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   50 \\cdot \\frac{basicScore_a - \\min(basicScore)}{\\max(basicScore) - \\min(basicScore)}       & \\text{if } engagements_a > 0\n\\end{cases} \\\\\n\\\\\n\\text{The latter equation can be expanded to:} \\\\\nresponseScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   50 \\cdot \n   \\frac{\\log(\\min(engagements_a,limit) + median(engagements)) - \\log(1 + median(engagements))}\n   {\\log(limit + median(engagements)) - \\log(1 + median(engagements))}       & \\text{if } engagements_a > 0\n\\end{cases} \\\\\n\\end{align}\n\n# Promotion Score\n\nThe aim of the promotion score is to indicate how important the article was to the publisher, by tracking where they chose to promote it. This is a number between 0 and 50 comprised of:\n\n- 20 points based on whether the article was promoted as the \"lead\" story on the publisher's home page\n- 15 points based on how long the article was promoted anywhere on the publisher's home page\n- 15 points based on whether the article was promoted on the publisher's main facebook brand page\n\nThe first two should be scaled by the popularity/reach of the home page, for which we use the alexa page rank as a proxy.\n\nThe last should be scaled by the popularity/reach of the brand page, for which we use the number of likes the brand page has.\n\n### Lead story (20 points)\n\n\n```python\ndata.mins_as_lead.describe([0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count   136062.00\n    mean         9.28\n    std        124.25\n    min          0.00\n    50%          0.00\n    75%          0.00\n    90%          0.00\n    95%          0.00\n    99%        270.00\n    99.5%      557.78\n    99.9%     1159.94\n    max      30386.00\n    Name: mins_as_lead, dtype: float64\n\n\n\nAs expected, the vast majority of articles don't make it as lead. Let's explore how long typically publishers put something as lead for.\n\n\n```python\nlead_articles = data[data.mins_as_lead > 0]\n```\n\n\n```python\nlead_articles.mins_as_lead.describe([0.25, 0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count    3769.00\n    mean      335.12\n    std       669.51\n    min         4.00\n    25%        89.00\n    50%       180.00\n    75%       415.00\n    90%       818.20\n    95%      1071.80\n    99%      1575.92\n    99.5%    2007.16\n    99.9%    7185.27\n    max     30386.00\n    Name: mins_as_lead, dtype: float64\n\n\n\n\n```python\nlead_articles.mins_as_lead.plot.hist(bins=50)\n```\n\nFor lead, it's a  significant thing for an article to be lead at all, so although we want to penalise articles that were lead for a very short time, mostly we want to score the maximum even if it wasn't lead for ages. So we'll give maximum points when something has been lead for an hour.\n\n\n```python\nlead_articles.mins_as_lead.clip_upper(60).plot.hist(bins=50)\n```\n\nWe also want to scale this by the alexa page rank, such that the maximum score of 20 points is for an article that was on the front for 4 hours for the most popular site.\n\nSo lets explore the alexa nunbers.\n\n\n```python\nalexa_ranks = data.groupby(by=\"publisher_id\").alexa_rank.mean().sort_values()\nalexa_ranks\n```\n\n\n\n\n    publisher_id\n    bbc_co_uk                               96\n    cnn_com                                105\n    nytimes_com                            120\n    theguardian_com                        142\n    buzzfeed_com                           147\n    dailymail_co_uk                        158\n    washingtonpost_com                     191\n    huffingtonpost_com                     215\n    foxnews_com                            285\n    rt_com                                 365\n    telegraph_co_uk                        370\n    independent_co_uk                      386\n    reuters_com                            497\n    npr_org                                594\n    lemonde_fr                             618\n    mirror_co_uk                           706\n    nbcnews_com                            826\n    breitbart_com                          994\n    ft_com                                1596\n    economist_com                         1825\n    indy100_com                           5014\n    thetimes_co_uk                        6435\n    newstatesman_com                     12769\n    thecanary_co                         15686\n    propublica_org                       16066\n    yournewswire_com                     22568\n    order-order_com                      32515\n    anotherangryvoice_blogspot_co_uk     77827\n    westmonster_com                      97775\n    evolvepolitics_com                  119412\n    skwawkbox_org                       152475\n    libdemvoice_org                     344992\n    brexitcentral_com                   469149\n    Name: alexa_rank, dtype: int64\n\n\n\n\n```python\nalexa_ranks.plot.bar(figsize=[10,5])\n```\n\nLet's try the simple option first: just divide the number of minutes as lead by the alexa rank. What's the scale of numbers we get then.\n\n\n```python\nlead_proposal_1 = lead_articles.mins_as_lead.clip_upper(60) / lead_articles.alexa_rank\nlead_proposal_1.plot.hist()\n```\n\nLooks like there's too much of a cluster around 0. Have we massively over penalised the publishers with a high alexa rank?\n\n\n```python\nlead_proposal_1.groupby(data.publisher_id).mean().plot.bar(figsize=[10,5])\n```\n\nYes. Let's try taking the log of the alexa rank and see if that looks better.\n\n\n```python\nlead_proposal_2 = (lead_articles.mins_as_lead.clip_upper(60) / np.log(lead_articles.alexa_rank))\nlead_proposal_2.plot.hist()\n```\n\n\n```python\nlead_proposal_2.groupby(data.publisher_id).describe()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>25%</th>\n      <th>50%</th>\n      <th>75%</th>\n      <th>max</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>28.00</td>\n      <td>5.33</td>\n      <td>0.00</td>\n      <td>5.33</td>\n      <td>5.33</td>\n      <td>5.33</td>\n      <td>5.33</td>\n      <td>5.33</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>103.00</td>\n      <td>12.80</td>\n      <td>1.68</td>\n      <td>2.19</td>\n      <td>13.15</td>\n      <td>13.15</td>\n      <td>13.15</td>\n      <td>13.15</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>194.00</td>\n      <td>8.32</td>\n      <td>1.43</td>\n      <td>0.72</td>\n      <td>8.69</td>\n      <td>8.69</td>\n      <td>8.69</td>\n      <td>8.69</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>51.00</td>\n      <td>4.16</td>\n      <td>1.11</td>\n      <td>0.77</td>\n      <td>4.59</td>\n      <td>4.59</td>\n      <td>4.59</td>\n      <td>4.59</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>290.00</td>\n      <td>11.73</td>\n      <td>1.21</td>\n      <td>2.00</td>\n      <td>12.02</td>\n      <td>12.02</td>\n      <td>12.02</td>\n      <td>12.02</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>190.00</td>\n      <td>12.36</td>\n      <td>1.81</td>\n      <td>2.15</td>\n      <td>12.89</td>\n      <td>12.89</td>\n      <td>12.89</td>\n      <td>12.89</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>158.00</td>\n      <td>11.39</td>\n      <td>1.70</td>\n      <td>1.78</td>\n      <td>11.85</td>\n      <td>11.85</td>\n      <td>11.85</td>\n      <td>11.85</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>65.00</td>\n      <td>7.79</td>\n      <td>0.98</td>\n      <td>2.40</td>\n      <td>7.99</td>\n      <td>7.99</td>\n      <td>7.99</td>\n      <td>7.99</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>95.00</td>\n      <td>10.45</td>\n      <td>1.05</td>\n      <td>0.88</td>\n      <td>10.61</td>\n      <td>10.61</td>\n      <td>10.61</td>\n      <td>10.61</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>77.00</td>\n      <td>7.53</td>\n      <td>1.66</td>\n      <td>0.68</td>\n      <td>8.14</td>\n      <td>8.14</td>\n      <td>8.14</td>\n      <td>8.14</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>156.00</td>\n      <td>11.03</td>\n      <td>0.96</td>\n      <td>2.79</td>\n      <td>11.17</td>\n      <td>11.17</td>\n      <td>11.17</td>\n      <td>11.17</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>134.00</td>\n      <td>9.50</td>\n      <td>1.89</td>\n      <td>0.67</td>\n      <td>10.07</td>\n      <td>10.07</td>\n      <td>10.07</td>\n      <td>10.07</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>120.00</td>\n      <td>6.17</td>\n      <td>1.53</td>\n      <td>1.64</td>\n      <td>5.75</td>\n      <td>7.04</td>\n      <td>7.04</td>\n      <td>7.04</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>251.00</td>\n      <td>7.95</td>\n      <td>2.63</td>\n      <td>0.62</td>\n      <td>7.78</td>\n      <td>9.34</td>\n      <td>9.34</td>\n      <td>9.34</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>142.00</td>\n      <td>4.61</td>\n      <td>0.48</td>\n      <td>1.10</td>\n      <td>4.71</td>\n      <td>4.71</td>\n      <td>4.71</td>\n      <td>4.71</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>114.00</td>\n      <td>8.68</td>\n      <td>1.22</td>\n      <td>0.74</td>\n      <td>8.93</td>\n      <td>8.93</td>\n      <td>8.93</td>\n      <td>8.93</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>58.00</td>\n      <td>6.12</td>\n      <td>0.88</td>\n      <td>1.59</td>\n      <td>6.35</td>\n      <td>6.35</td>\n      <td>6.35</td>\n      <td>6.35</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>143.00</td>\n      <td>8.95</td>\n      <td>1.59</td>\n      <td>1.41</td>\n      <td>9.39</td>\n      <td>9.39</td>\n      <td>9.39</td>\n      <td>9.39</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>51.00</td>\n      <td>12.45</td>\n      <td>0.61</td>\n      <td>8.15</td>\n      <td>12.53</td>\n      <td>12.53</td>\n      <td>12.53</td>\n      <td>12.53</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>237.00</td>\n      <td>4.48</td>\n      <td>1.67</td>\n      <td>0.48</td>\n      <td>3.27</td>\n      <td>5.78</td>\n      <td>5.78</td>\n      <td>5.78</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>16.00</td>\n      <td>6.20</td>\n      <td>0.00</td>\n      <td>6.20</td>\n      <td>6.20</td>\n      <td>6.20</td>\n      <td>6.20</td>\n      <td>6.20</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>94.00</td>\n      <td>9.26</td>\n      <td>1.71</td>\n      <td>0.64</td>\n      <td>9.66</td>\n      <td>9.66</td>\n      <td>9.66</td>\n      <td>9.66</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>135.00</td>\n      <td>9.60</td>\n      <td>1.80</td>\n      <td>0.85</td>\n      <td>10.17</td>\n      <td>10.17</td>\n      <td>10.17</td>\n      <td>10.17</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>102.00</td>\n      <td>4.71</td>\n      <td>0.86</td>\n      <td>0.42</td>\n      <td>5.03</td>\n      <td>5.03</td>\n      <td>5.03</td>\n      <td>5.03</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>104.00</td>\n      <td>9.76</td>\n      <td>1.58</td>\n      <td>1.69</td>\n      <td>10.15</td>\n      <td>10.15</td>\n      <td>10.15</td>\n      <td>10.15</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>172.00</td>\n      <td>4.95</td>\n      <td>1.66</td>\n      <td>0.93</td>\n      <td>3.93</td>\n      <td>6.21</td>\n      <td>6.21</td>\n      <td>6.21</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>161.00</td>\n      <td>11.50</td>\n      <td>2.02</td>\n      <td>2.82</td>\n      <td>12.11</td>\n      <td>12.11</td>\n      <td>12.11</td>\n      <td>12.11</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>63.00</td>\n      <td>6.65</td>\n      <td>1.01</td>\n      <td>1.14</td>\n      <td>6.84</td>\n      <td>6.84</td>\n      <td>6.84</td>\n      <td>6.84</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>80.00</td>\n      <td>10.96</td>\n      <td>1.96</td>\n      <td>0.95</td>\n      <td>11.42</td>\n      <td>11.42</td>\n      <td>11.42</td>\n      <td>11.42</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>36.00</td>\n      <td>5.01</td>\n      <td>0.78</td>\n      <td>0.87</td>\n      <td>5.22</td>\n      <td>5.22</td>\n      <td>5.22</td>\n      <td>5.22</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>149.00</td>\n      <td>5.69</td>\n      <td>0.66</td>\n      <td>3.19</td>\n      <td>5.99</td>\n      <td>5.99</td>\n      <td>5.99</td>\n      <td>5.99</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nlead_proposal_2.groupby(data.publisher_id).min().plot.bar(figsize=[10,5])\n```\n\nThat looks about right, as long as the smaller publishers were closer to zero. So let's apply feature scaling to this, to give a number between 1 and 20. (Anything not as lead will pass though as zero.)\n\n\n```python\ndef rescale(series):\n    return (series - series.min()) / (series.max() - series.min())\n\nlead_proposal_3 = np.ceil(20 * rescale(lead_proposal_2))\n```\n\n\n```python\nlead_proposal_2.min(), lead_proposal_2.max()\n```\n\n\n\n\n    (0.41894447029448817, 13.145359968846892)\n\n\n\n\n```python\nlead_proposal_3.plot.hist()\n```\n\n\n```python\nlead_proposal_3.groupby(data.publisher_id).median().plot.bar(figsize=[10,5])\n```\n\n\n```python\ndata[\"lead_score\"] = pd.concat([lead_proposal_3, data.mins_as_lead[data.mins_as_lead==0]])\n```\n\n\n```python\ndata.lead_score.value_counts().sort_index()\n```\n\n\n\n\n    0.00     132294\n    1.00         41\n    2.00         49\n    3.00         45\n    4.00         44\n    5.00         60\n    6.00         63\n    7.00        244\n    8.00        194\n    9.00        273\n    10.00       179\n    11.00       159\n    12.00        93\n    13.00        77\n    14.00       293\n    15.00       407\n    16.00       343\n    17.00       251\n    18.00       226\n    19.00       407\n    20.00       320\n    Name: lead_score, dtype: int64\n\n\n\n\n```python\ndata.lead_score.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    8.00\n    bbc_co_uk                          20.00\n    breitbart_com                      14.00\n    brexitcentral_com                   7.00\n    buzzfeed_com                       19.00\n    cnn_com                            20.00\n    dailymail_co_uk                    18.00\n    economist_com                      12.00\n    evolvepolitics_com                  0.00\n    foxnews_com                        17.00\n    ft_com                             13.00\n    huffingtonpost_com                 17.00\n    independent_co_uk                  16.00\n    indy100_com                        11.00\n    lemonde_fr                         15.00\n    libdemvoice_org                     7.00\n    mirror_co_uk                        0.00\n    nbcnews_com                        14.00\n    newstatesman_com                   10.00\n    npr_org                            15.00\n    nytimes_com                        20.00\n    order-order_com                     9.00\n    propublica_org                     10.00\n    reuters_com                        15.00\n    rt_com                             16.00\n    skwawkbox_org                       8.00\n    telegraph_co_uk                    16.00\n    thecanary_co                       10.00\n    theguardian_com                    19.00\n    thetimes_co_uk                     11.00\n    washingtonpost_com                 18.00\n    westmonster_com                     8.00\n    yournewswire_com                    9.00\n    Name: lead_score, dtype: float64\n\n\n\nIn summary then, score for article $a$ is:\n\n\n$$\nunscaledLeadScore_a = \\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)}\\\\\nleadScore_a = 19 \\cdot \n\\frac{unscaledLeadScore_a - \\min(unscaledLeadScore)}\n{\\max(unscaledLeadScore) - \\min(unscaledLeadScore)} \n+ 1\n$$\n\nSince the minium value of $minsAsLead$ is 1, $\\min(unscaledLeadScore)$ is pretty insignificant. So we can simplify this to:\n\n$$\nleadScore_a = 20 \\cdot \n\\frac{unscaledLeadScore_a }\n     {\\max(unscaledLeadScore)} \n$$\n\nor: \n\n$$\nleadScore_a = 20 \\cdot \n\\frac{\\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)} }\n     {\\frac{60}{\\log(\\max(alexaRank))}} \n$$\n\n$$\nleadScore_a = \\left( 20 \\cdot \n\\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)} \\cdot\n     {\\frac{\\log(\\max(alexaRank))}{60}} \\right)\n$$\n\n## Time on front score (15 points)\n\nThis is similar to time as lead, so lets try doing the same calculation, except we also want to factor in the number of slots on the front:\n\n\n$$frontScore_a = \n15 \n\\left(\\frac{\\min(minsOnFront_a, 1440)}{alexaRank_a \\cdot numArticlesOnFront_a}\\right) \n\\left( \\frac{\\min(alexaRank \\cdot numArticlesOnFront)}{1440} \\right)$$\n\n\n```python\n(data.alexa_rank * data.num_articles_on_front).min() / 1440\n```\n\n\n\n\n    2.4500000000000002\n\n\n\n\n```python\ntime_on_front_proposal_1 = np.ceil(data.mins_on_front.clip_upper(1440) / (data.alexa_rank * data.num_articles_on_front) * (2.45) * 15)\n```\n\n\n```python\ntime_on_front_proposal_1.plot.hist(figsize=(15, 7), bins=15)\n```\n\n\n```python\ntime_on_front_proposal_1.value_counts().sort_index()\n```\n\n\n\n\n    1.00     68084\n    2.00      6873\n    3.00      4369\n    4.00      4066\n    5.00       769\n    6.00       643\n    7.00       543\n    8.00       522\n    9.00       774\n    10.00      359\n    11.00      135\n    12.00      135\n    13.00       92\n    14.00       49\n    15.00       20\n    dtype: int64\n\n\n\n\n```python\ntime_on_front_proposal_1.groupby(data.publisher_id).sum()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk      28.00\n    bbc_co_uk                          13177.00\n    breitbart_com                       2469.00\n    brexitcentral_com                     59.00\n    buzzfeed_com                        9419.00\n    cnn_com                            11915.00\n    dailymail_co_uk                    13020.00\n    economist_com                        316.00\n    evolvepolitics_com                    59.00\n    foxnews_com                         6728.00\n    ft_com                              2871.00\n    huffingtonpost_com                  7483.00\n    independent_co_uk                   3708.00\n    indy100_com                          434.00\n    lemonde_fr                          3752.00\n    libdemvoice_org                      148.00\n    mirror_co_uk                        9134.00\n    nbcnews_com                         1633.00\n    newstatesman_com                     413.00\n    npr_org                             2586.00\n    nytimes_com                         8873.00\n    order-order_com                      240.00\n    propublica_org                        41.00\n    reuters_com                         6466.00\n    rt_com                              4351.00\n    skwawkbox_org                        102.00\n    telegraph_co_uk                     4496.00\n    thecanary_co                         182.00\n    theguardian_com                    11165.00\n    thetimes_co_uk                      8325.00\n    washingtonpost_com                  8565.00\n    westmonster_com                      168.00\n    yournewswire_com                     398.00\n    dtype: float64\n\n\n\nThat looks good to me.\n\n\n```python\ndata[\"front_score\"] = np.ceil(data.mins_on_front.clip_upper(1440) / (data.alexa_rank * data.num_articles_on_front) * (2.45) * 15).fillna(0)\n```\n\n\n```python\ndata.front_score \n```\n\n\n\n\n    id\n    402fd72431c6a0e29e76fc9abaa6bc0d42f2ea81   1.00\n    956698308752aa83f6ad988aa05a4f26f5514f9e   1.00\n    1524679962f3bef642390e1955d470fe0acc2aff   1.00\n    13646fa08dee5c8b5bdd718ab882cb988a1eb85f   1.00\n    44dccc673596c768f1129a020c1b6b0c6ff8ab66   1.00\n    c79fa786172cf75bc8c7df55261f88802762dfce   1.00\n    2ea986b1e9669911a984b966ceca1ce95fbfe119   1.00\n    c261550cf016a29150e2d0648916160178e69eaa   1.00\n    6faa4d962b6436f2db4a469d6d75b6f85e46eace   1.00\n    cfae32d025a1bfe4e55b5fc1e31f8822d54b1301   1.00\n    d91572cf3c19bfcb811f2ad3d76ba91c64a16dba   1.00\n    22064c30c58acf5f08ee572dbe05768d1342aac2   1.00\n    5dee083190bd81f2fa8eb58e584ece3fbfe81d81   1.00\n    da47e9b97d048bbd6416d5e6bd9819e05622bb20   1.00\n    9445e067eb1cfbae505a28911692b72f627a0302   1.00\n    9c1c83e1d94d6fab16933fbd6d82f4a17472214c   1.00\n    fed2156894429a97eaad8d263af59676cc1b0d4e   1.00\n    9d06a956e45f3d75253f25f142dcb008fbe91ec0   1.00\n    cba30053abc9c1e1bdc4400e87f0ae8b27b6dde1   1.00\n    ae8d3ed982b149d3a9e69abef81c06840b100954   1.00\n    65671059afa84f9546e0459a8316bebea025a34c   1.00\n    cfea31674c56ecf591faf746d182806b4ae94146   1.00\n    62d11d26e6dd88b2de2b0308b5c2f9f3baf35eea   1.00\n    7e16c7440040514351056d45e2347d47096299fb   1.00\n    62c27fe7eb7da3e90404789704e49aa8bfc00bb3   1.00\n    e056daeaabff5dc242f9d3d00498f94c09add6f6   1.00\n    698e07a38c6792e0a101c715dc3d83d864687c4f   1.00\n    891ace61198aa413a27f39bd6776018decdf7a49   1.00\n    cadaed9e9c0f564e850c71893e1b4749b26c1d4e   1.00\n    04f3a557366bbf9d5d74cf6e4857c31db80991f4   1.00\n                                               ... \n    ecf84098352929c7b4bb4602dcf88a408aec9709   0.00\n    eed8ab55d6ac640cf925fb53dc0bddbe2208d61b   2.00\n    24cd4487ce3ff489cab5d9d48344ef010a78d133   0.00\n    a5acdee911bf4e90ef35e8bbcd2b5bbbe3bf50e9   6.00\n    23bbbaa3b0ba8d926b36eebdced1e06b5aad2ba7   0.00\n    fa3c0e904506607f7192a1d448f5ae78f57a7523   0.00\n    8a6d59b792cb25798317b5b4e2e7a16589e873b1   1.00\n    39c11ab924bbcea0498cb0a2dfe80a1ff49dff63   3.00\n    aaeff59f952be5f94c939fc21d9441444a30a7b6   0.00\n    91b483f19852504d3e72426b1fdf91a9ec17215a   7.00\n    55140aa37babfb520483bdcacd4eeb7ec759ec95   0.00\n    12b69ae6e35fee649c725be270c380392eac534b   0.00\n    816f08291e3d28f5d10241a45e2a0e960085db72   1.00\n    f987dc2c2f9836b66b8d22432ec3638ae960831b   0.00\n    10e9d6511dc5bb2e250da691c6726d2e19b15e4c   1.00\n    87525ea811f9d3d55c9e4ee54dad8648b46d89b6   5.00\n    24905b5f9aa051b4180eb5d0338c5727eccb1191   1.00\n    1e276f81a9fa6d403599cf51acfc8c64460df980   0.00\n    776e1c0fc1f4ca712b30078f9a26d14869facabb   9.00\n    d15d5be98c6f5b9953ae939b66eea49de152abd8   1.00\n    62a87f7a2f96166215ad6cae2b3e7c869f184e9d   1.00\n    1e1b62e21309c4408a96b1065a5154654d758ea0   1.00\n    e1bf734bd951bc70527256e29daf454c46ed5fe0   2.00\n    aa382546bf93e906129cdb467711efd29ea25ec7   1.00\n    a8158261b9c5fa7b92de97b726f07d1d739840e7   1.00\n    bd8043b89ee9f13739ff944c7e4efc153adfac1b   0.00\n    eca5955549302beee4edff3166d494e431c8a4a8   5.00\n    54254be01a6d115ebbc865dffa043987950e6e48   1.00\n    78e4a922fcc9bd0617d0af9cd44be86ac2431129   1.00\n    c92ad0932df8f0d74dde5dff449c9abce762c511   5.00\n    Name: front_score, Length: 136062, dtype: float64\n\n\n\n## Facebook brand page promotion (15 points)\n\nOne way a publisher has of promoting content is to post to their brand page. The significance of doing so is stronger when the brand page has more followers (likes).\n\n$$ facebookPromotionProposed1_a = 15 \\left( \\frac {brandPageLikes_a} {\\max(brandPageLikes)} \\right) $$\n\nNow lets explore the data to see if that makes sense. **tr;dr the formula above is incorrect**\n\n\n```python\ndata.fb_brand_page_likes.max()\n```\n\n\n\n\n    45953133.0\n\n\n\n\n```python\nfacebook_promotion_proposed_1 = np.ceil((15 * (data.fb_brand_page_likes / data.fb_brand_page_likes.max())).fillna(0))\n```\n\n\n```python\nfacebook_promotion_proposed_1.value_counts().sort_index().plot.bar()\n```\n\n\n```python\nfacebook_promotion_proposed_1.groupby(data.publisher_id).describe()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>25%</th>\n      <th>50%</th>\n      <th>75%</th>\n      <th>max</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>28.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>11509.00</td>\n      <td>0.55</td>\n      <td>2.81</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>15.00</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>2565.00</td>\n      <td>0.78</td>\n      <td>0.98</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>59.00</td>\n      <td>0.86</td>\n      <td>0.35</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>1323.00</td>\n      <td>0.41</td>\n      <td>0.49</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>3898.00</td>\n      <td>2.48</td>\n      <td>4.32</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>10.00</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>23015.00</td>\n      <td>0.61</td>\n      <td>1.64</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>5.00</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>501.00</td>\n      <td>2.46</td>\n      <td>1.16</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>evolvepolitics_com</th>\n      <td>63.00</td>\n      <td>0.95</td>\n      <td>0.21</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>5592.00</td>\n      <td>0.63</td>\n      <td>1.84</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>6.00</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>4368.00</td>\n      <td>0.49</td>\n      <td>0.86</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>2498.00</td>\n      <td>1.91</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>5246.00</td>\n      <td>0.63</td>\n      <td>1.22</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>434.00</td>\n      <td>0.71</td>\n      <td>0.46</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>3765.00</td>\n      <td>0.61</td>\n      <td>0.92</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>149.00</td>\n      <td>0.95</td>\n      <td>0.21</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>9642.00</td>\n      <td>0.23</td>\n      <td>0.42</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>1685.00</td>\n      <td>2.61</td>\n      <td>1.91</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>418.00</td>\n      <td>0.81</td>\n      <td>0.39</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>1952.00</td>\n      <td>1.44</td>\n      <td>1.50</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>4352.00</td>\n      <td>1.74</td>\n      <td>2.53</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>5.00</td>\n      <td>6.00</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>240.00</td>\n      <td>0.75</td>\n      <td>0.43</td>\n      <td>0.00</td>\n      <td>0.75</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>41.00</td>\n      <td>0.80</td>\n      <td>0.40</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>5653.00</td>\n      <td>0.63</td>\n      <td>0.93</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>2199.00</td>\n      <td>1.08</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>102.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>6223.00</td>\n      <td>0.40</td>\n      <td>0.80</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>182.00</td>\n      <td>0.98</td>\n      <td>0.13</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>7750.00</td>\n      <td>0.50</td>\n      <td>1.12</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>8336.00</td>\n      <td>0.05</td>\n      <td>0.22</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>21670.00</td>\n      <td>0.16</td>\n      <td>0.68</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>206.00</td>\n      <td>0.40</td>\n      <td>0.49</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>398.00</td>\n      <td>0.32</td>\n      <td>0.47</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThat's too much variation: sites like the Guardian, which have a respectable 7.5m likes, should not be scoring a 3. Lets try applying a log to it, and then standard feature scaling again.\n\n\n```python\ndata.fb_brand_page_likes.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk     330207.00\n    bbc_co_uk                          45953133.00\n    breitbart_com                       3827443.00\n    brexitcentral_com                     15654.00\n    buzzfeed_com                        2929729.00\n    cnn_com                            29784431.00\n    dailymail_co_uk                    14362724.00\n    economist_com                       8474471.00\n    evolvepolitics_com                   127618.00\n    foxnews_com                        16239060.00\n    ft_com                              3755253.00\n    huffingtonpost_com                  9856230.00\n    independent_co_uk                   8077017.00\n    indy100_com                          239388.00\n    lemonde_fr                          4058907.00\n    libdemvoice_org                        8629.00\n    mirror_co_uk                        2982278.00\n    nbcnews_com                         9578008.00\n    newstatesman_com                     154662.00\n    npr_org                             6299668.00\n    nytimes_com                        15379547.00\n    order-order_com                       45610.00\n    propublica_org                       379167.00\n    reuters_com                         3978791.00\n    rt_com                              4978221.00\n    skwawkbox_org                          7280.00\n    telegraph_co_uk                     4425050.00\n    thecanary_co                         158031.00\n    theguardian_com                     7891342.00\n    thetimes_co_uk                       750928.00\n    washingtonpost_com                  6147257.00\n    westmonster_com                       18799.00\n    yournewswire_com                      28301.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\nnp.log(2149)\n```\n\n\n\n\n    7.6727578966425103\n\n\n\n\n```python\nnp.log(data.fb_brand_page_likes.groupby(data.publisher_id).max())\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk   12.71\n    bbc_co_uk                          17.64\n    breitbart_com                      15.16\n    brexitcentral_com                   9.66\n    buzzfeed_com                       14.89\n    cnn_com                            17.21\n    dailymail_co_uk                    16.48\n    economist_com                      15.95\n    evolvepolitics_com                 11.76\n    foxnews_com                        16.60\n    ft_com                             15.14\n    huffingtonpost_com                 16.10\n    independent_co_uk                  15.90\n    indy100_com                        12.39\n    lemonde_fr                         15.22\n    libdemvoice_org                     9.06\n    mirror_co_uk                       14.91\n    nbcnews_com                        16.07\n    newstatesman_com                   11.95\n    npr_org                            15.66\n    nytimes_com                        16.55\n    order-order_com                    10.73\n    propublica_org                     12.85\n    reuters_com                        15.20\n    rt_com                             15.42\n    skwawkbox_org                       8.89\n    telegraph_co_uk                    15.30\n    thecanary_co                       11.97\n    theguardian_com                    15.88\n    thetimes_co_uk                     13.53\n    washingtonpost_com                 15.63\n    westmonster_com                     9.84\n    yournewswire_com                   10.25\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\nThat's more like it, but the lower numbers should be smaller.\n\n\n```python\nnp.log(data.fb_brand_page_likes.groupby(data.publisher_id).max() / 1000)\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    5.80\n    bbc_co_uk                          10.74\n    breitbart_com                       8.25\n    brexitcentral_com                   2.75\n    buzzfeed_com                        7.98\n    cnn_com                            10.30\n    dailymail_co_uk                     9.57\n    economist_com                       9.04\n    evolvepolitics_com                  4.85\n    foxnews_com                         9.70\n    ft_com                              8.23\n    huffingtonpost_com                  9.20\n    independent_co_uk                   9.00\n    indy100_com                         5.48\n    lemonde_fr                          8.31\n    libdemvoice_org                     2.16\n    mirror_co_uk                        8.00\n    nbcnews_com                         9.17\n    newstatesman_com                    5.04\n    npr_org                             8.75\n    nytimes_com                         9.64\n    order-order_com                     3.82\n    propublica_org                      5.94\n    reuters_com                         8.29\n    rt_com                              8.51\n    skwawkbox_org                       1.99\n    telegraph_co_uk                     8.40\n    thecanary_co                        5.06\n    theguardian_com                     8.97\n    thetimes_co_uk                      6.62\n    washingtonpost_com                  8.72\n    westmonster_com                     2.93\n    yournewswire_com                    3.34\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\nscaled_fb_brand_page_likes = (data.fb_brand_page_likes / 1000)\nfacebook_promotion_proposed_2 = np.ceil(\\\n    (15 * \\\n     (np.log(scaled_fb_brand_page_likes) / np.log(scaled_fb_brand_page_likes.max()))\\\n    )\\\n                                       ).fillna(0)\n```\n\n\n```python\nfacebook_promotion_proposed_2.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    9.00\n    bbc_co_uk                          15.00\n    breitbart_com                      12.00\n    brexitcentral_com                   4.00\n    buzzfeed_com                       12.00\n    cnn_com                            15.00\n    dailymail_co_uk                    14.00\n    economist_com                      13.00\n    evolvepolitics_com                  7.00\n    foxnews_com                        14.00\n    ft_com                             12.00\n    huffingtonpost_com                 13.00\n    independent_co_uk                  13.00\n    indy100_com                         8.00\n    lemonde_fr                         12.00\n    libdemvoice_org                     4.00\n    mirror_co_uk                       12.00\n    nbcnews_com                        13.00\n    newstatesman_com                    8.00\n    npr_org                            13.00\n    nytimes_com                        14.00\n    order-order_com                     6.00\n    propublica_org                      9.00\n    reuters_com                        12.00\n    rt_com                             12.00\n    skwawkbox_org                       3.00\n    telegraph_co_uk                    12.00\n    thecanary_co                        8.00\n    theguardian_com                    13.00\n    thetimes_co_uk                     10.00\n    washingtonpost_com                 13.00\n    westmonster_com                     5.00\n    yournewswire_com                    5.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\nLGTM. So the equation is\n\n\n$$ facebookPromotion_a = 15 \\left( \n\\frac {\\log(\\frac {brandPageLikes_a}{1000})} \n{\\log(\\frac {\\max(brandPageLikes)}{1000}))} \\right) $$\n\n\nNow, let's try applying standard feature scaling approch to this, rather than using a magic number of 1,000. That equation would be:\n\n\\begin{align}\nunscaledFacebookPromotion_a &= \n   \\log(brandPageLikes_a) \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{unscaledFacebookPromotion_a - \\min(unscaledFacebookPromotion)}{\\max(unscaledFacebookPromotion) - \\min(unscaledFacebookPromotion)}  \\\\\n\\\\\n\\text{The scaling can be simplified to:} \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{unscaledFacebookPromotion_a - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))}  \\\\\n\\\\\n\\text{Meaning the overall equation becomes:} \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{\\log(brandPageLikes_a) - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))} \n   \\end{align}\n\n\n\n```python\nfacebook_promotion_proposed_3 = np.ceil(\n    (14 * \n     ( \n         (np.log(data.fb_brand_page_likes) - np.log(data.fb_brand_page_likes.min()) ) /\n         (np.log(data.fb_brand_page_likes.max()) - np.log(data.fb_brand_page_likes.min()))\n     )\n    ) + 1\n                                       )\n```\n\n\n```python\nfacebook_promotion_proposed_3.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    8.00\n    bbc_co_uk                          15.00\n    breitbart_com                      12.00\n    brexitcentral_com                   3.00\n    buzzfeed_com                       11.00\n    cnn_com                            15.00\n    dailymail_co_uk                    14.00\n    economist_com                      13.00\n    evolvepolitics_com                  6.00\n    foxnews_com                        14.00\n    ft_com                             12.00\n    huffingtonpost_com                 13.00\n    independent_co_uk                  13.00\n    indy100_com                         7.00\n    lemonde_fr                         12.00\n    libdemvoice_org                     2.00\n    mirror_co_uk                       11.00\n    nbcnews_com                        13.00\n    newstatesman_com                    6.00\n    npr_org                            12.00\n    nytimes_com                        14.00\n    order-order_com                     4.00\n    propublica_org                      8.00\n    reuters_com                        12.00\n    rt_com                             12.00\n    skwawkbox_org                       2.00\n    telegraph_co_uk                    12.00\n    thecanary_co                        6.00\n    theguardian_com                    13.00\n    thetimes_co_uk                      9.00\n    washingtonpost_com                 12.00\n    westmonster_com                     3.00\n    yournewswire_com                    4.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\ndata[\"facebook_promotion_score\"] = facebook_promotion_proposed_3.fillna(0.0)\n```\n\n# Review\n\n\n```python\ndata[\"promotion_score\"] = (data.lead_score + data.front_score + data.facebook_promotion_score)\ndata[\"attention_index\"] = (data.promotion_score + data.response_score)\n```\n\n\n```python\ndata.promotion_score.plot.hist(bins=np.arange(50), figsize=(15,6))\n```\n\n\n```python\ndata.attention_index.plot.hist(bins=np.arange(100), figsize=(15,6))\n```\n\n\n```python\ndata.attention_index.value_counts().sort_index()\n```\n\n\n\n\n    0.00     20300\n    1.00     17446\n    2.00     11190\n    3.00      8050\n    4.00      5819\n    5.00      4612\n    6.00      4321\n    7.00      3502\n    8.00      3230\n    9.00      2833\n    10.00     2778\n    11.00     2473\n    12.00     2249\n    13.00     2144\n    14.00     2048\n    15.00     2005\n    16.00     1848\n    17.00     1782\n    18.00     1652\n    19.00     1634\n    20.00     1623\n    21.00     1545\n    22.00     1478\n    23.00     1479\n    24.00     1475\n    25.00     1439\n    26.00     1365\n    27.00     1230\n    28.00     1293\n    29.00     1178\n             ...  \n    65.00      129\n    66.00       99\n    67.00       72\n    68.00       64\n    69.00       64\n    70.00       59\n    71.00       46\n    72.00       34\n    73.00       47\n    74.00       41\n    75.00       36\n    76.00       24\n    77.00       24\n    78.00       34\n    79.00       23\n    80.00       25\n    81.00       21\n    82.00       20\n    83.00       20\n    84.00       19\n    85.00       10\n    86.00        9\n    87.00       12\n    88.00       15\n    89.00        8\n    90.00        2\n    91.00        6\n    92.00        7\n    93.00        2\n    94.00        5\n    Name: attention_index, Length: 95, dtype: int64\n\n\n\n\n```python\n# and lets see the articles with the biggest attention index\ndata.sort_values(\"attention_index\", ascending=False)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>50f3ffd91e936ee865166c1ba7ee6cd494cef168</th>\n      <td>https://www.cnn.com/2018/02/11/health/aetna-ca...</td>\n      <td>State launches Aetna probe after stunning admi...</td>\n      <td>2018-02-11 21:16:21.717</td>\n      <td>2018-02-11 21:11:31</td>\n      <td>188224</td>\n      <td>193.70</td>\n      <td>2018-02-14T00:19:21.586Z</td>\n      <td>44043</td>\n      <td>109177</td>\n      <td>35004</td>\n      <td>...</td>\n      <td>29612675.00</td>\n      <td>2018-02-11T22:30:02.000Z</td>\n      <td>105</td>\n      <td>1758.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>bcde74d11c6932b426cd8629622a7a144de96318</th>\n      <td>https://www.buzzfeed.com/briannasacks/the-fbi-...</td>\n      <td>The FBI Was Warned About A School Shooting Thr...</td>\n      <td>2018-02-15 09:25:25.051</td>\n      <td>2018-02-15 07:38:51</td>\n      <td>105241</td>\n      <td>194.90</td>\n      <td>2018-02-15T16:26:23.527Z</td>\n      <td>29924</td>\n      <td>54373</td>\n      <td>20944</td>\n      <td>...</td>\n      <td>2919016.00</td>\n      <td>2018-02-15T09:43:35.000Z</td>\n      <td>147</td>\n      <td>502.00</td>\n      <td>50.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>7fa31adc8e694a8f269a2d264135cbac1b284b30</th>\n      <td>https://www.cnn.com/2018/02/16/politics/muelle...</td>\n      <td>Grand jury returns indictment against 13 Russi...</td>\n      <td>2018-02-16 18:13:14.937</td>\n      <td>2018-02-16 18:04:10</td>\n      <td>169116</td>\n      <td>598.03</td>\n      <td>2018-02-16T18:35:18.373Z</td>\n      <td>51967</td>\n      <td>93366</td>\n      <td>23783</td>\n      <td>...</td>\n      <td>29638206.00</td>\n      <td>2018-02-16T18:14:03.000Z</td>\n      <td>105</td>\n      <td>66.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>99ac15ddfc4a2219d9038bdac94f963bb9ee80a2</th>\n      <td>http://money.cnn.com/2018/02/23/news/companies...</td>\n      <td>Enterprise car rental ends NRA partnership</td>\n      <td>2018-02-23 16:44:14.552</td>\n      <td>2018-02-23 16:25:22</td>\n      <td>371853</td>\n      <td>1020.00</td>\n      <td>2018-02-24T16:49:12.315Z</td>\n      <td>47062</td>\n      <td>295122</td>\n      <td>29669</td>\n      <td>...</td>\n      <td>29731553.00</td>\n      <td>2018-02-24T16:11:42.000Z</td>\n      <td>105</td>\n      <td>nan</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>3690e4bb3501e7ea4987e134a0ab4197b04eb22a</th>\n      <td>https://www.cnn.com/2018/02/15/us/florida-shoo...</td>\n      <td>These are the victims of the Florida school sh...</td>\n      <td>2018-02-15 17:06:22.819</td>\n      <td>2018-02-15 16:59:11</td>\n      <td>148598</td>\n      <td>407.25</td>\n      <td>2018-02-16T10:03:11.380Z</td>\n      <td>18324</td>\n      <td>113279</td>\n      <td>16995</td>\n      <td>...</td>\n      <td>29660971.00</td>\n      <td>2018-02-18T14:30:17.000Z</td>\n      <td>105</td>\n      <td>280.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>fed2f0bddae438ac1ed84db4a496d38a55ee1b8e</th>\n      <td>https://www.cnn.com/2018/02/03/politics/paul-r...</td>\n      <td>Paul Ryan deletes tweet about tax cuts after T...</td>\n      <td>2018-02-03 21:07:09.817</td>\n      <td>2018-02-03 21:03:15</td>\n      <td>105556</td>\n      <td>190.11</td>\n      <td>2018-02-05T00:07:11.101Z</td>\n      <td>25550</td>\n      <td>64114</td>\n      <td>15892</td>\n      <td>...</td>\n      <td>29587000.00</td>\n      <td>2018-02-04T02:30:02.000Z</td>\n      <td>105</td>\n      <td>411.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>ef30eb097153cc6c4ae903708b1af28058f8c30c</th>\n      <td>https://www.cnn.com/2018/02/22/politics/donald...</td>\n      <td>Trump proposes bonuses for teachers who get gu...</td>\n      <td>2018-02-22 18:43:22.074</td>\n      <td>2018-02-22 18:39:10</td>\n      <td>239328</td>\n      <td>556.07</td>\n      <td>2018-02-22T20:21:18.030Z</td>\n      <td>102984</td>\n      <td>120967</td>\n      <td>15377</td>\n      <td>...</td>\n      <td>29720711.00</td>\n      <td>2018-02-22T19:45:06.000Z</td>\n      <td>105</td>\n      <td>455.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>595d15633260734dcd8d7d96b1f1995a38adc53d</th>\n      <td>https://www.buzzfeed.com/remysmidt/heres-what-...</td>\n      <td>Here\u2019s What It\u2019s Like At The Headquarters Of T...</td>\n      <td>2018-02-20 05:25:13.116</td>\n      <td>2018-02-20 05:08:34</td>\n      <td>272546</td>\n      <td>290.43</td>\n      <td>2018-02-20T17:51:13.097Z</td>\n      <td>18984</td>\n      <td>224646</td>\n      <td>28916</td>\n      <td>...</td>\n      <td>2923003.00</td>\n      <td>2018-02-20T15:02:00.000Z</td>\n      <td>147</td>\n      <td>1107.00</td>\n      <td>50.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>3bd8bbc894078c77eec7ec36ec28065981d395dc</th>\n      <td>https://www.cnn.com/2018/02/23/politics/parkla...</td>\n      <td>Sources: Coral Springs police upset at some Br...</td>\n      <td>2018-02-23 21:40:15.835</td>\n      <td>2018-02-23 21:35:48</td>\n      <td>79066</td>\n      <td>111.20</td>\n      <td>2018-02-23T22:14:03.424Z</td>\n      <td>29161</td>\n      <td>36820</td>\n      <td>13085</td>\n      <td>...</td>\n      <td>29727467.00</td>\n      <td>2018-02-23T21:47:07.000Z</td>\n      <td>105</td>\n      <td>799.00</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>732f13426df8d1ad17644d72ae3657f452da4477</th>\n      <td>http://money.cnn.com/2018/02/12/news/economy/f...</td>\n      <td>White House wants to deliver food to the poor,...</td>\n      <td>2018-02-13 01:24:14.852</td>\n      <td>2018-02-13 00:53:36</td>\n      <td>108874</td>\n      <td>252.67</td>\n      <td>2018-02-13T22:04:09.451Z</td>\n      <td>59616</td>\n      <td>38976</td>\n      <td>10282</td>\n      <td>...</td>\n      <td>29645980.00</td>\n      <td>2018-02-17T14:00:29.000Z</td>\n      <td>105</td>\n      <td>nan</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>49533f2f5395c1a675fc03445724096204f87734</th>\n      <td>https://www.buzzfeed.com/verabergengruen/comba...</td>\n      <td>Combat Veterans Think Arming Teachers Is A Rea...</td>\n      <td>2018-02-23 00:01:22.203</td>\n      <td>2018-02-22 23:43:41</td>\n      <td>120715</td>\n      <td>62.73</td>\n      <td>2018-02-24T16:30:08.356Z</td>\n      <td>21933</td>\n      <td>81291</td>\n      <td>17491</td>\n      <td>...</td>\n      <td>2925048.00</td>\n      <td>2018-02-23T15:03:58.000Z</td>\n      <td>147</td>\n      <td>1188.00</td>\n      <td>50.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>7384cb9d557758572326b7195b1d69c356c46f55</th>\n      <td>http://www.bbc.co.uk/news/world-us-canada-4314...</td>\n      <td>Trump backs guns for teachers</td>\n      <td>2018-02-21 23:09:09.136</td>\n      <td>2018-02-21 23:07:36</td>\n      <td>174798</td>\n      <td>327.68</td>\n      <td>2018-02-22T20:26:11.741Z</td>\n      <td>83346</td>\n      <td>77047</td>\n      <td>14405</td>\n      <td>...</td>\n      <td>45877722.00</td>\n      <td>2018-02-22T20:15:05.000Z</td>\n      <td>96</td>\n      <td>360.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>7ef7490379626b4a008728ad8ae9b07ed7744828</th>\n      <td>http://www.bbc.co.uk/news/world-us-canada-4306...</td>\n      <td>Shooting at Florida school - reports</td>\n      <td>2018-02-14 20:07:16.659</td>\n      <td>2018-02-14 20:05:41</td>\n      <td>96370</td>\n      <td>337.93</td>\n      <td>2018-02-14T20:30:04.815Z</td>\n      <td>31532</td>\n      <td>53174</td>\n      <td>11664</td>\n      <td>...</td>\n      <td>45794144.00</td>\n      <td>2018-02-15T02:30:15.000Z</td>\n      <td>96</td>\n      <td>61.00</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>43550ca5cdda76dd1e905ea2e7b1dcd9239587aa</th>\n      <td>https://www.cnn.com/2018/02/22/politics/wayne-...</td>\n      <td>The NRA's Wayne LaPierre to speak at CPAC on T...</td>\n      <td>2018-02-22 14:19:26.847</td>\n      <td>2018-02-22 14:15:30</td>\n      <td>71741</td>\n      <td>132.33</td>\n      <td>2018-02-23T01:13:15.202Z</td>\n      <td>29125</td>\n      <td>33007</td>\n      <td>9609</td>\n      <td>...</td>\n      <td>29722659.00</td>\n      <td>2018-02-23T01:00:19.000Z</td>\n      <td>105</td>\n      <td>363.00</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>4d855aa92f114083340d536db271bdae9487e182</th>\n      <td>https://www.buzzfeed.com/dominicholden/a-feder...</td>\n      <td>A Federal Court Just Ruled For Gay Rights In A...</td>\n      <td>2018-02-26 15:01:11.437</td>\n      <td>2018-02-26 14:58:46</td>\n      <td>75023</td>\n      <td>121.00</td>\n      <td>2018-02-26T20:55:09.383Z</td>\n      <td>2529</td>\n      <td>66121</td>\n      <td>6373</td>\n      <td>...</td>\n      <td>2926728.00</td>\n      <td>2018-02-26T16:39:37.000Z</td>\n      <td>147</td>\n      <td>706.00</td>\n      <td>48.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>d504855fd090afa4745d80839dfb1a2af86da1b5</th>\n      <td>https://www.cnn.com/2018/02/26/politics/daca-s...</td>\n      <td>Supreme Court won't hear Trump bid to end DACA...</td>\n      <td>2018-02-26 14:49:24.336</td>\n      <td>2018-02-26 14:44:00</td>\n      <td>74782</td>\n      <td>488.34</td>\n      <td>2018-02-26T15:12:06.328Z</td>\n      <td>6605</td>\n      <td>59632</td>\n      <td>8545</td>\n      <td>...</td>\n      <td>29739965.00</td>\n      <td>2018-02-26T14:59:05.000Z</td>\n      <td>105</td>\n      <td>92.00</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>fcaae011c5530fa995d63ff29817f42a5ba0b7b1</th>\n      <td>http://www.bbc.co.uk/news/world-us-canada-4314...</td>\n      <td>US preacher Billy Graham dies</td>\n      <td>2018-02-21 13:25:17.564</td>\n      <td>2018-02-21 13:24:08</td>\n      <td>81703</td>\n      <td>382.35</td>\n      <td>2018-02-21T14:20:13.936Z</td>\n      <td>14894</td>\n      <td>55099</td>\n      <td>11710</td>\n      <td>...</td>\n      <td>45865499.00</td>\n      <td>2018-02-21T13:25:41.000Z</td>\n      <td>96</td>\n      <td>90.00</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>44a85408d42ef8368e95485b0c3436490453e558</th>\n      <td>https://www.cnn.com/2018/02/06/politics/milita...</td>\n      <td>Washington Post: Trump tells Pentagon to plan ...</td>\n      <td>2018-02-06 23:37:22.096</td>\n      <td>2018-02-06 23:29:20</td>\n      <td>133249</td>\n      <td>189.77</td>\n      <td>2018-02-07T06:04:09.090Z</td>\n      <td>66239</td>\n      <td>56156</td>\n      <td>10854</td>\n      <td>...</td>\n      <td>29599493.00</td>\n      <td>2018-02-07T13:00:13.000Z</td>\n      <td>105</td>\n      <td>160.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>bdec0fff8f7508de17de5eaa899cf4272dd9fc72</th>\n      <td>https://www.cnn.com/2018/02/22/us/florida-scho...</td>\n      <td>Security footage from school massacre scene wa...</td>\n      <td>2018-02-22 16:19:30.029</td>\n      <td>2018-02-22 16:13:27</td>\n      <td>94072</td>\n      <td>140.82</td>\n      <td>2018-02-23T01:25:16.843Z</td>\n      <td>48710</td>\n      <td>34633</td>\n      <td>10729</td>\n      <td>...</td>\n      <td>29721683.00</td>\n      <td>2018-02-22T22:02:04.000Z</td>\n      <td>105</td>\n      <td>148.00</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>030598f1d5c669d3e3adef3be9ededb9bfe98e2f</th>\n      <td>https://www.cnn.com/2018/02/20/us/florida-legi...</td>\n      <td>Florida House votes down weapons ban considera...</td>\n      <td>2018-02-20 22:52:18.624</td>\n      <td>2018-02-20 22:50:21</td>\n      <td>136107</td>\n      <td>517.77</td>\n      <td>2018-02-21T01:32:08.912Z</td>\n      <td>36663</td>\n      <td>83885</td>\n      <td>15559</td>\n      <td>...</td>\n      <td>29683383.00</td>\n      <td>2018-02-21T01:06:49.000Z</td>\n      <td>105</td>\n      <td>61.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>3e5b38ac8f7dd73b8f3b3d6037d14415b88372ed</th>\n      <td>https://www.cnn.com/2018/02/23/us/florida-scho...</td>\n      <td>Armed deputy stayed outside during Florida sch...</td>\n      <td>2018-02-23 09:52:18.646</td>\n      <td>2018-02-23 09:45:08</td>\n      <td>94821</td>\n      <td>138.37</td>\n      <td>2018-02-23T16:03:12.436Z</td>\n      <td>44086</td>\n      <td>39807</td>\n      <td>10928</td>\n      <td>...</td>\n      <td>29725457.00</td>\n      <td>2018-02-23T11:37:03.000Z</td>\n      <td>105</td>\n      <td>1226.00</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>0ad0a1c1c17aa19b40632bfd7c7f2a3a6dcb4f30</th>\n      <td>https://www.cnn.com/2018/02/09/politics/democr...</td>\n      <td>Trump won't declassify Democratic memo, sends ...</td>\n      <td>2018-02-10 01:07:22.787</td>\n      <td>2018-02-10 01:01:27</td>\n      <td>78340</td>\n      <td>326.98</td>\n      <td>2018-02-10T01:29:16.517Z</td>\n      <td>33926</td>\n      <td>34276</td>\n      <td>10138</td>\n      <td>...</td>\n      <td>29607746.00</td>\n      <td>2018-02-10T01:10:22.000Z</td>\n      <td>105</td>\n      <td>245.00</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>81832cf7eda554c7263210894d3e33032d71906f</th>\n      <td>https://www.cnn.com/2018/02/25/politics/cnn-po...</td>\n      <td>CNN Poll: Trump approval slides, matches lowes...</td>\n      <td>2018-02-25 14:07:19.613</td>\n      <td>2018-02-25 14:00:15</td>\n      <td>46003</td>\n      <td>136.21</td>\n      <td>2018-02-25T16:53:10.637Z</td>\n      <td>16092</td>\n      <td>24226</td>\n      <td>5685</td>\n      <td>...</td>\n      <td>29736526.00</td>\n      <td>2018-02-25T16:35:35.000Z</td>\n      <td>105</td>\n      <td>485.00</td>\n      <td>45.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>9f5cd7c4119f7da78c9c94708ff4a20d121afc9e</th>\n      <td>https://www.cnn.com/2018/02/24/politics/mexica...</td>\n      <td>WH official: Pe\u00f1a Nieto calls off visit to Whi...</td>\n      <td>2018-02-25 01:31:13.954</td>\n      <td>2018-02-25 01:24:45</td>\n      <td>43112</td>\n      <td>133.80</td>\n      <td>2018-02-25T19:16:09.811Z</td>\n      <td>10601</td>\n      <td>26121</td>\n      <td>6390</td>\n      <td>...</td>\n      <td>29736950.00</td>\n      <td>2018-02-25T19:08:24.000Z</td>\n      <td>105</td>\n      <td>277.00</td>\n      <td>45.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>fbb9012b3f033f1ce41927a700146d6d56c37f96</th>\n      <td>https://www.cnn.com/2018/02/16/politics/muelle...</td>\n      <td>Robert Mueller just made it impossible for Tru...</td>\n      <td>2018-02-16 20:10:16.588</td>\n      <td>2018-02-16 20:05:10</td>\n      <td>47510</td>\n      <td>135.14</td>\n      <td>2018-02-16T23:43:15.792Z</td>\n      <td>10099</td>\n      <td>32107</td>\n      <td>5304</td>\n      <td>...</td>\n      <td>29639980.00</td>\n      <td>2018-02-16T23:28:01.000Z</td>\n      <td>105</td>\n      <td>919.00</td>\n      <td>45.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>090aad188705194f32d7cbf2adf6cf7b171ca6f0</th>\n      <td>https://www.cnn.com/2018/02/03/politics/donald...</td>\n      <td>Trump tweets on Nunes memo</td>\n      <td>2018-02-03 15:10:18.821</td>\n      <td>2018-02-03 15:05:03</td>\n      <td>54179</td>\n      <td>423.11</td>\n      <td>2018-02-03T16:14:09.449Z</td>\n      <td>20525</td>\n      <td>30935</td>\n      <td>2719</td>\n      <td>...</td>\n      <td>29585302.00</td>\n      <td>2018-02-03T16:00:07.000Z</td>\n      <td>105</td>\n      <td>145.00</td>\n      <td>46.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>7a658ecfdc344e3796e0935b6cd913534c0fa2a4</th>\n      <td>https://www.cnn.com/2018/02/19/politics/muelle...</td>\n      <td>Mueller's interest in Kushner grows to include...</td>\n      <td>2018-02-19 21:07:18.742</td>\n      <td>2018-02-19 21:00:59</td>\n      <td>46157</td>\n      <td>231.53</td>\n      <td>2018-02-19T21:30:07.494Z</td>\n      <td>8855</td>\n      <td>30099</td>\n      <td>7203</td>\n      <td>...</td>\n      <td>29674422.00</td>\n      <td>2018-02-19T21:16:05.000Z</td>\n      <td>105</td>\n      <td>806.00</td>\n      <td>45.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>d41cdce11a5fda07196fbab9e1f327219ae2a2b0</th>\n      <td>https://www.cnn.com/2018/02/14/us/florida-high...</td>\n      <td>Shooting reported at Florida high school</td>\n      <td>2018-02-14 20:07:20.293</td>\n      <td>2018-02-14 20:02:51</td>\n      <td>508808</td>\n      <td>1012.36</td>\n      <td>2018-02-15T00:16:13.133Z</td>\n      <td>161675</td>\n      <td>286961</td>\n      <td>60172</td>\n      <td>...</td>\n      <td>29622210.00</td>\n      <td>2018-02-14T20:08:06.000Z</td>\n      <td>105</td>\n      <td>32.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>4.00</td>\n      <td>15.00</td>\n      <td>39.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>6b77e8af4ad35821df4e7a4613306dbb92629308</th>\n      <td>https://www.buzzfeed.com/adambvary/black-panth...</td>\n      <td>\"Black Panther\" Is An Unprecedented Box Office...</td>\n      <td>2018-02-18 16:34:20.965</td>\n      <td>2018-02-18 16:26:53</td>\n      <td>68194</td>\n      <td>84.76</td>\n      <td>2018-02-18T18:48:11.622Z</td>\n      <td>7158</td>\n      <td>54349</td>\n      <td>6687</td>\n      <td>...</td>\n      <td>2922134.00</td>\n      <td>2018-02-18T17:50:10.000Z</td>\n      <td>147</td>\n      <td>1976.00</td>\n      <td>47.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>76d1c6e03c5d5273ee6a33d73da8a50b25b431a5</th>\n      <td>https://www.cnn.com/2018/02/20/politics/robert...</td>\n      <td>Mueller charges lawyer with lying about intera...</td>\n      <td>2018-02-20 14:40:11.669</td>\n      <td>2018-02-20 14:33:43</td>\n      <td>45215</td>\n      <td>247.18</td>\n      <td>2018-02-20T16:18:11.270Z</td>\n      <td>8388</td>\n      <td>30749</td>\n      <td>6078</td>\n      <td>...</td>\n      <td>29679686.00</td>\n      <td>2018-02-20T14:51:32.000Z</td>\n      <td>105</td>\n      <td>111.00</td>\n      <td>45.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>711226f4cc221161fc34c3cd126c1f20c2c1c05d</th>\n      <td>http://www.bbc.co.uk/sport/scotland/43140856</td>\n      <td>Gold Coast 2018: Scots kit up for Commonwealth...</td>\n      <td>2018-02-21 09:46:04.217</td>\n      <td>2018-02-21 09:44:08</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-22T00:10:05.823Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>50a513e1ef2b483ff3f40373dcf62a3f1c40cbc0</th>\n      <td>http://www.dailymail.co.uk/home/event/article-...</td>\n      <td>Chris Evans takes a spin in the\u00a0Seat Arona FR ...</td>\n      <td>2018-02-17 22:04:45.718</td>\n      <td>2018-02-17 22:01:01</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-18T05:23:07.502Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>1082.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>6b95aa067d195e0a470d2c6ab8222a13d5a0f5cf</th>\n      <td>http://www.dailymail.co.uk/home/event/article-...</td>\n      <td>Rag'n'Bone Man review: Sings the blues superbly</td>\n      <td>2018-02-17 22:04:23.862</td>\n      <td>2018-02-17 22:01:05</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-02-18T08:25:10.269Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>773.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>11a20b75e5c28495503c361837bdc3b4a3d7187d</th>\n      <td>http://www.dailymail.co.uk/home/event/article-...</td>\n      <td>lolanthe review: All the fun of the fairytale</td>\n      <td>2018-02-17 22:04:39.971</td>\n      <td>2018-02-17 22:01:19</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-02-18T08:26:07.367Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>719.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>d5a14386776ba2ca4de4c52e28223148d8e37351</th>\n      <td>http://www.dailymail.co.uk/home/event/article-...</td>\n      <td>The Winslow Boy review: Timely in its feminism</td>\n      <td>2018-02-17 22:04:39.159</td>\n      <td>2018-02-17 22:01:27</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-02-18T08:26:07.346Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>760.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>f911c1f884be46a59314570c419fcacc5f15e1e5</th>\n      <td>http://www.dailymail.co.uk/travel/article-5403...</td>\n      <td>1930s New York? Just turn right at London's Hy...</td>\n      <td>2018-02-17 22:04:44.779</td>\n      <td>2018-02-17 22:01:51</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-18T12:29:11.133Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>318.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>1f44623aa1b251473b4560d597d14a2dd7abc2d1</th>\n      <td>https://www.washingtonpost.com/national/author...</td>\n      <td>Authorities say one officer has died, two depu...</td>\n      <td>2018-02-09 19:16:19.407</td>\n      <td>2018-02-09 19:13:11</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-10T06:38:09.956Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>37.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>85b6b4db2f9c797adcd982653fc066ac716e1f42</th>\n      <td>http://www.dailymail.co.uk/travel/article-5403...</td>\n      <td>Lilies and the Louvre, you can find all of the...</td>\n      <td>2018-02-17 22:04:27.109</td>\n      <td>2018-02-17 22:02:04</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-18T12:28:23.715Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>919.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>a595eeda63180aebd0f6ee93032dd70ee03fb4cd</th>\n      <td>http://www.dailymail.co.uk/tvshowbiz/article-5...</td>\n      <td>Roxy Jacenko flashes her fading bruises from b...</td>\n      <td>2018-02-23 12:10:29.917</td>\n      <td>2018-02-23 12:06:46</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-23T12:22:14.299Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>539.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>24f65f6b2ea7f757ab7be360496a3afdb1b7e36b</th>\n      <td>https://www.theguardian.com/sport/2018/feb/17/...</td>\n      <td>Wales\u2019 Ken Owens says Warren Gatland deserves ...</td>\n      <td>2018-02-17 22:01:10.159</td>\n      <td>2018-02-17 21:59:26</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-18T01:15:07.005Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>142</td>\n      <td>598.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>ba7b0867b6a77b0d78940111baa895ea8885374e</th>\n      <td>http://www.dailymail.co.uk/tvshowbiz/article-5...</td>\n      <td>Australian Spartan contestants told to cover u...</td>\n      <td>2018-02-26 08:34:10.346</td>\n      <td>2018-02-26 08:30:26</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-26T09:46:12.872Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>376.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>1eb3f2a266ee8bb74f625c0ed78b628538ad55e1</th>\n      <td>http://www.bbc.co.uk/news/world-europe-43196047</td>\n      <td>Bank of Ireland to pay first dividend since cr...</td>\n      <td>2018-02-26 08:34:10.155</td>\n      <td>2018-02-26 08:30:34</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-02-26T09:46:12.852Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>101.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>f96f3971ba36b30240fbf6530485b0cf6f6bc9b3</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Persons, El-Amin help Ball State sweep Toledo ...</td>\n      <td>2018-02-17 22:01:14.952</td>\n      <td>2018-02-17 21:52:42</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-18T07:21:06.620Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>203.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>c33b12cd48e84e4af4c54549cd12d0f84167d3e0</th>\n      <td>https://www.ft.com/content/e732c9f2-0da5-11e8-...</td>\n      <td>Direct Line profits surge thanks to own-brand ...</td>\n      <td>2018-02-09 19:22:20.171</td>\n      <td>2018-02-09 19:20:27</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-10T15:52:02.478Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>1596</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>cb02a50107e39382d8a5eebef27aa17930fa1433</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Waters\u2019 field goal gives LSU 64-63 win over Mi...</td>\n      <td>2018-02-17 21:52:15.082</td>\n      <td>2018-02-17 21:47:19</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-18T06:11:03.657Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>275.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>2ad4f536947f32f136d4129e9a47a2ca157ddb48</th>\n      <td>http://www.independent.co.uk/news/business/new...</td>\n      <td>Primark: Unseasonably warm Autumn weather expe...</td>\n      <td>2018-02-26 08:43:15.140</td>\n      <td>2018-02-26 08:38:32</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-26T08:54:16.338Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>386</td>\n      <td>227.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>171af42d03b106505bef6807435978615b4ad026</th>\n      <td>https://www.washingtonpost.com/politics/ap-cou...</td>\n      <td>AP count: Nearly 11.8M enroll for Obama health...</td>\n      <td>2018-02-07 17:13:12.806</td>\n      <td>2018-02-07 17:00:11</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-07T22:29:09.796Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>148.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>e0e74d851ce9fa2338acd0458feb5f78ca10a915</th>\n      <td>https://www.washingtonpost.com/sports/olympics...</td>\n      <td>Goggia gets gold; Russian women close in on en...</td>\n      <td>2018-02-21 09:58:11.501</td>\n      <td>2018-02-21 09:47:25</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-22T01:23:23.118Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>779.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>35cc3c9fae6aba00a1be05234b8a956ae7bfa0a3</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Walker, Avery lead Kent State past Akron 78-68</td>\n      <td>2018-02-17 22:01:17.209</td>\n      <td>2018-02-17 21:51:14</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-18T07:21:06.635Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>192.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>8cd1d739c76b84a71c3ae4b21403212e2d7df2c5</th>\n      <td>https://www.washingtonpost.com/business/greece...</td>\n      <td>Greece: Parliament debates investigation over ...</td>\n      <td>2018-02-21 09:58:14.030</td>\n      <td>2018-02-21 09:46:15</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-22T01:23:23.123Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>147.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>40df170ea6c8c2eecf343fafea8038a8d588e094</th>\n      <td>https://www.washingtonpost.com/local/winning-n...</td>\n      <td>Winning numbers drawn in \u2018Play 3 Day\u2019 game</td>\n      <td>2018-02-09 19:25:22.200</td>\n      <td>2018-02-09 19:19:09</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-10T13:53:25.608Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>41.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>3cbc373ce713b17ee5344c5bec0b09febac97b7f</th>\n      <td>https://www.washingtonpost.com/local/winning-n...</td>\n      <td>Winning numbers drawn in \u2018DC 4 Midday\u2019 game</td>\n      <td>2018-02-09 19:25:16.895</td>\n      <td>2018-02-09 19:18:43</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-09T19:37:19.606Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>43.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>379297e818cbd90b451670440e6ebf0fe2b20595</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Duke\u2019s Bagley to miss 3rd game with sprained knee</td>\n      <td>2018-02-17 22:01:14.885</td>\n      <td>2018-02-17 21:53:27</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-18T01:16:02.583Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>114.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>915ce8988a6bcf9af2c8888e99e7fc06d0f631be</th>\n      <td>https://www.washingtonpost.com/local/winning-n...</td>\n      <td>Winning numbers drawn in \u2018Pick 3 Day\u2019 game</td>\n      <td>2018-02-09 19:25:15.729</td>\n      <td>2018-02-09 19:19:07</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-10T16:56:10.146Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>41.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>65f713ec044f55558fb6ecc552d6d8e99c6fea03</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Auburn starter McLemore taken off court on str...</td>\n      <td>2018-02-17 22:13:20.401</td>\n      <td>2018-02-17 21:58:13</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-18T09:35:08.984Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>174.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>f1f614f19c33ea71f7aee8681849f6ee434345eb</th>\n      <td>https://www.washingtonpost.com/local/winning-n...</td>\n      <td>Winning numbers drawn in \u2018Play 4 Day\u2019 game</td>\n      <td>2018-02-09 19:25:18.532</td>\n      <td>2018-02-09 19:19:02</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-09T19:37:19.621Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>42.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>78425473e026b8bcc3cf28d82405fd2b7dfc846b</th>\n      <td>https://www.washingtonpost.com/local/winning-n...</td>\n      <td>Winning numbers drawn in \u2018DC 5 Midday\u2019 game</td>\n      <td>2018-02-09 19:25:25.498</td>\n      <td>2018-02-09 19:18:55</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-10T13:53:25.644Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>44.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>b689f14b3ba9d55680eb1ab90725ba5458765cb6</th>\n      <td>https://www.washingtonpost.com/sports/national...</td>\n      <td>Jays hope healthy Sanchez can stabilize starti...</td>\n      <td>2018-02-09 19:31:16.532</td>\n      <td>2018-02-09 19:18:53</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-10T13:59:10.384Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>543.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>5deb3bc1272e04f98cffa28ee49abb2bb27358b1</th>\n      <td>http://www.bbc.co.uk/sport/wales/43193037</td>\n      <td>Julie Hoornweg: Wales netball appoint Australi...</td>\n      <td>2018-02-26 08:34:12.629</td>\n      <td>2018-02-26 08:30:52</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-26T09:46:12.906Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>f6635f20d7e72231a7904999f56b057e5ff967c1</th>\n      <td>https://www.washingtonpost.com/national/veteri...</td>\n      <td>Veterinarian accused of fatally shooting neigh...</td>\n      <td>2018-02-22 15:01:09.063</td>\n      <td>2018-02-22 14:57:17</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-23T07:27:07.458Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>141.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>136062 rows \u00d7 26 columns</p>\n</div>\n\n\n\n\n```python\ndata[\"score_diff\"] = data.promotion_score - data.response_score\n```\n\n\n```python\n# promoted but low response\ndata.sort_values(\"score_diff\", ascending=False).head(25)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n      <th>score_diff</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2dd7184cf1962f76dc17a9d4b910c9c961c4a639</th>\n      <td>https://www.buzzfeed.com/stephaniemcneal/monat</td>\n      <td>This Trendy Hair Company Is Suing A Woman Who ...</td>\n      <td>2018-02-07 19:37:11.282</td>\n      <td>2018-02-01 15:42:38</td>\n      <td>9</td>\n      <td>0.82</td>\n      <td>2018-02-07T19:49:11.063Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>9</td>\n      <td>...</td>\n      <td>2018-02-07T20:39:47.000Z</td>\n      <td>147</td>\n      <td>1673.00</td>\n      <td>2.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>47.00</td>\n      <td>43.00</td>\n    </tr>\n    <tr>\n      <th>ccef80e232f379f5df12683200476c17734b8d49</th>\n      <td>https://www.buzzfeed.com/patrickstrudwick/this...</td>\n      <td>This Man Is Planning To Open The World's Large...</td>\n      <td>2018-02-27 08:09:13.612</td>\n      <td>2018-02-23 12:25:59</td>\n      <td>4</td>\n      <td>0.09</td>\n      <td>2018-02-27T08:21:08.839Z</td>\n      <td>0</td>\n      <td>2</td>\n      <td>2</td>\n      <td>...</td>\n      <td>2018-02-27T14:54:08.000Z</td>\n      <td>147</td>\n      <td>1530.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>45.00</td>\n      <td>43.00</td>\n    </tr>\n    <tr>\n      <th>77b260359cdb03b2a160441e435208aec0755826</th>\n      <td>https://www.buzzfeed.com/katebubacz/what-happe...</td>\n      <td>What Happened After Standing Rock?</td>\n      <td>2018-02-28 22:04:16.683</td>\n      <td>2018-02-22 23:43:47</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-28T22:15:21.682Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2018-03-01T00:52:51.000Z</td>\n      <td>147</td>\n      <td>4975.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>43.00</td>\n      <td>43.00</td>\n    </tr>\n    <tr>\n      <th>872a77a39949fce75a819caa9b57ff25eda8d1d7</th>\n      <td>https://www.buzzfeed.com/hannahallam/inside-th...</td>\n      <td>Inside The Uneasy Fight To End Female Genital ...</td>\n      <td>2018-02-05 14:04:16.865</td>\n      <td>2018-02-01 21:06:42</td>\n      <td>1</td>\n      <td>0.09</td>\n      <td>2018-02-05T14:16:13.088Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>2018-02-05T16:14:53.000Z</td>\n      <td>147</td>\n      <td>2097.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>42.00</td>\n      <td>42.00</td>\n    </tr>\n    <tr>\n      <th>dd3b404c6f7743717957de0cb9db0a63a86bc385</th>\n      <td>https://www.buzzfeed.com/buzzfeednews/heres-ho...</td>\n      <td>Here's How Many Medals The US Has Won So Far A...</td>\n      <td>2018-02-11 02:44:12.255</td>\n      <td>2018-02-09 18:28:27</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>2018-02-11T02:55:18.851Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>2018-02-14T03:18:57.000Z</td>\n      <td>147</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>42.00</td>\n      <td>42.00</td>\n    </tr>\n    <tr>\n      <th>5a88c2c270cd23fbb4caa33f9f592bd2eb8b7979</th>\n      <td>https://www.buzzfeed.com/emaoconnor/columbia-t...</td>\n      <td>She \u201cProvoked\u201d Him: Columbia\u2019s Old Policies Le...</td>\n      <td>2018-03-01 16:49:33.800</td>\n      <td>2018-02-26 23:23:53</td>\n      <td>2</td>\n      <td>0.18</td>\n      <td>2018-03-01T17:01:22.335Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>...</td>\n      <td>2018-03-01T17:11:17.000Z</td>\n      <td>147</td>\n      <td>3974.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>43.00</td>\n      <td>41.00</td>\n    </tr>\n    <tr>\n      <th>367ce38e6802afe4b09fa8562631c7abedebbe08</th>\n      <td>https://www.buzzfeed.com/carolinekee/juul-ecig...</td>\n      <td>The JUUL Is An Insanely Popular E-Cigarette Bu...</td>\n      <td>2018-02-05 22:52:21.271</td>\n      <td>2018-02-02 18:38:13</td>\n      <td>2</td>\n      <td>0.18</td>\n      <td>2018-02-05T23:04:10.998Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>...</td>\n      <td>2018-02-06T01:14:32.000Z</td>\n      <td>147</td>\n      <td>83.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>10.00</td>\n      <td>11.00</td>\n      <td>40.00</td>\n      <td>41.00</td>\n      <td>39.00</td>\n    </tr>\n    <tr>\n      <th>08bd4bc0640627333b78efecb6c02c69f2eb2bdc</th>\n      <td>https://www.buzzfeed.com/mitchprothero/their-p...</td>\n      <td>Their Parents Fought With ISIS. Now France Is ...</td>\n      <td>2018-02-19 14:04:23.387</td>\n      <td>2018-02-18 20:55:53</td>\n      <td>23</td>\n      <td>0.10</td>\n      <td>2018-02-19T15:17:08.351Z</td>\n      <td>2</td>\n      <td>4</td>\n      <td>17</td>\n      <td>...</td>\n      <td>2018-02-19T21:49:19.000Z</td>\n      <td>147</td>\n      <td>688.00</td>\n      <td>4.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>47.00</td>\n      <td>39.00</td>\n    </tr>\n    <tr>\n      <th>77e20f89fc8c29a4e763cc24cd844a37e40b378f</th>\n      <td>https://www.buzzfeed.com/alisonwillmore/fifty-...</td>\n      <td>Difficult Men Meet Their Match In \u201cFifty Shade...</td>\n      <td>2018-02-15 18:04:25.149</td>\n      <td>2018-02-14 17:26:42</td>\n      <td>2</td>\n      <td>0.18</td>\n      <td>2018-02-15T18:16:11.035Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>...</td>\n      <td>2018-02-19T03:01:00.000Z</td>\n      <td>147</td>\n      <td>2552.00</td>\n      <td>1.00</td>\n      <td>17.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>40.00</td>\n      <td>41.00</td>\n      <td>39.00</td>\n    </tr>\n    <tr>\n      <th>67e78216ef055244f9675cb06748fe507a200e7a</th>\n      <td>https://www.buzzfeed.com/tamerragriffin/this-i...</td>\n      <td>This Is What It's Like When Your Country Runs ...</td>\n      <td>2018-02-03 15:49:21.870</td>\n      <td>2018-02-02 16:31:03</td>\n      <td>24</td>\n      <td>0.36</td>\n      <td>2018-02-03T17:02:06.588Z</td>\n      <td>0</td>\n      <td>3</td>\n      <td>21</td>\n      <td>...</td>\n      <td>2018-02-03T20:14:41.000Z</td>\n      <td>147</td>\n      <td>1718.00</td>\n      <td>4.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>46.00</td>\n      <td>38.00</td>\n    </tr>\n    <tr>\n      <th>532f617cc49df5e98cfc7e3735f90e5173fd45f0</th>\n      <td>https://www.buzzfeed.com/albertsamaha/this-tee...</td>\n      <td>This Teenager Accused Two On-Duty Cops Of Rape...</td>\n      <td>2018-02-07 10:31:16.262</td>\n      <td>2018-02-05 18:14:44</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-07T10:43:11.846Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2018-02-07T12:10:33.000Z</td>\n      <td>147</td>\n      <td>3359.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>8.00</td>\n      <td>11.00</td>\n      <td>38.00</td>\n      <td>38.00</td>\n      <td>38.00</td>\n    </tr>\n    <tr>\n      <th>318ecacd91e6c5e9d74e394f6b74c4402d90924c</th>\n      <td>https://www.buzzfeed.com/talalansari/porter</td>\n      <td>Trump's Spokesman Says The White House \"Could ...</td>\n      <td>2018-02-08 21:04:23.795</td>\n      <td>2018-02-08 21:01:47</td>\n      <td>73</td>\n      <td>0.51</td>\n      <td>2018-02-08T22:17:13.692Z</td>\n      <td>11</td>\n      <td>38</td>\n      <td>24</td>\n      <td>...</td>\n      <td>2018-02-08T21:21:04.000Z</td>\n      <td>147</td>\n      <td>267.00</td>\n      <td>8.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>53.00</td>\n      <td>37.00</td>\n    </tr>\n    <tr>\n      <th>d4b243e11f6e9b4ffdd49fa4aed40701f07bfa3c</th>\n      <td>https://www.buzzfeed.com/alexkantrowitz/facebo...</td>\n      <td>Facebook Won't Release Its \u201c5% Of News Feed Co...</td>\n      <td>2018-02-18 17:55:16.027</td>\n      <td>2018-02-17 20:04:45</td>\n      <td>13</td>\n      <td>0.11</td>\n      <td>2018-02-18T20:09:10.239Z</td>\n      <td>1</td>\n      <td>3</td>\n      <td>9</td>\n      <td>...</td>\n      <td>2018-02-19T20:22:13.000Z</td>\n      <td>147</td>\n      <td>1056.00</td>\n      <td>3.00</td>\n      <td>19.00</td>\n      <td>10.00</td>\n      <td>11.00</td>\n      <td>40.00</td>\n      <td>43.00</td>\n      <td>37.00</td>\n    </tr>\n    <tr>\n      <th>5d57a4e0bd91a2cb50cdba0b5fee6c928f18fc68</th>\n      <td>https://www.buzzfeed.com/louispeitzman/2018-ac...</td>\n      <td>Here Are The Winners At The 2018 Academy Awards</td>\n      <td>2018-03-05 01:29:15.278</td>\n      <td>2018-02-28 21:19:39</td>\n      <td>7</td>\n      <td>0.30</td>\n      <td>2018-03-05T01:40:16.367Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>7</td>\n      <td>...</td>\n      <td>2018-03-05T05:55:00.000Z</td>\n      <td>147</td>\n      <td>nan</td>\n      <td>2.00</td>\n      <td>19.00</td>\n      <td>8.00</td>\n      <td>11.00</td>\n      <td>38.00</td>\n      <td>40.00</td>\n      <td>36.00</td>\n    </tr>\n    <tr>\n      <th>61c98348add4be38653ef9956749854447f62362</th>\n      <td>https://www.buzzfeed.com/tamerragriffin/south-...</td>\n      <td>South Africa\u2019s \u201cTeflon President\u201d Might Be Fin...</td>\n      <td>2018-02-13 18:07:21.156</td>\n      <td>2018-02-13 17:47:23</td>\n      <td>38</td>\n      <td>0.11</td>\n      <td>2018-02-14T05:29:09.692Z</td>\n      <td>10</td>\n      <td>17</td>\n      <td>11</td>\n      <td>...</td>\n      <td>2018-02-14T21:17:09.000Z</td>\n      <td>147</td>\n      <td>nan</td>\n      <td>6.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>48.00</td>\n      <td>36.00</td>\n    </tr>\n    <tr>\n      <th>984ae7c0ec9960f8cc82916a7df12284d388d333</th>\n      <td>https://www.buzzfeed.com/nicolenguyen/homepod-...</td>\n      <td>HomePod Review: A Smart Speaker For iPhone Use...</td>\n      <td>2018-02-06 13:31:31.366</td>\n      <td>2018-02-06 02:47:46</td>\n      <td>48</td>\n      <td>0.28</td>\n      <td>2018-02-06T13:43:07.624Z</td>\n      <td>3</td>\n      <td>25</td>\n      <td>20</td>\n      <td>...</td>\n      <td>2018-02-06T16:45:04.000Z</td>\n      <td>147</td>\n      <td>2652.00</td>\n      <td>7.00</td>\n      <td>17.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>49.00</td>\n      <td>35.00</td>\n    </tr>\n    <tr>\n      <th>4baa6af1c4de278dd08b7edd01e038af97ba3a00</th>\n      <td>https://www.buzzfeed.com/michaelblackmon/taran...</td>\n      <td>Quentin Tarantino Gave His Side Of The Story A...</td>\n      <td>2018-02-06 17:49:21.235</td>\n      <td>2018-02-06 17:18:57</td>\n      <td>126</td>\n      <td>0.48</td>\n      <td>2018-02-06T23:05:08.798Z</td>\n      <td>5</td>\n      <td>105</td>\n      <td>16</td>\n      <td>...</td>\n      <td>2018-02-06T20:05:27.000Z</td>\n      <td>147</td>\n      <td>493.00</td>\n      <td>11.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>56.00</td>\n      <td>34.00</td>\n    </tr>\n    <tr>\n      <th>5a00b0b5556c3808f5b79ed69b6cd76daff85f03</th>\n      <td>https://www.buzzfeed.com/venessawong/mcdonalds...</td>\n      <td>McDonald\u2019s And Uber Eats Need Each Now Other M...</td>\n      <td>2018-02-15 18:25:18.096</td>\n      <td>2018-02-15 18:24:58</td>\n      <td>32</td>\n      <td>0.09</td>\n      <td>2018-02-15T18:37:09.793Z</td>\n      <td>4</td>\n      <td>14</td>\n      <td>14</td>\n      <td>...</td>\n      <td>2018-02-16T02:44:41.000Z</td>\n      <td>147</td>\n      <td>1064.00</td>\n      <td>5.00</td>\n      <td>19.00</td>\n      <td>9.00</td>\n      <td>11.00</td>\n      <td>39.00</td>\n      <td>44.00</td>\n      <td>34.00</td>\n    </tr>\n    <tr>\n      <th>4588bd12d8ef2558abb2281970a2cf997a2ca5ad</th>\n      <td>https://www.buzzfeed.com/lesterfeder/italian-e...</td>\n      <td>Meet The Politician Getting Death Threats For ...</td>\n      <td>2018-02-24 15:31:11.736</td>\n      <td>2018-02-23 11:45:54</td>\n      <td>1</td>\n      <td>0.09</td>\n      <td>2018-02-24T15:43:07.081Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>3405.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>0.00</td>\n      <td>33.00</td>\n      <td>33.00</td>\n      <td>33.00</td>\n    </tr>\n    <tr>\n      <th>0cc686fee28a082c58f5857f8405aad3cd473126</th>\n      <td>https://www.buzzfeed.com/borzoudaragahi/unfair...</td>\n      <td>This Man Was Arrested 10 Times For Being An IS...</td>\n      <td>2018-02-25 14:01:19.862</td>\n      <td>2018-02-22 09:37:12</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-02-25T14:12:16.332Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>3921.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>0.00</td>\n      <td>33.00</td>\n      <td>33.00</td>\n      <td>33.00</td>\n    </tr>\n    <tr>\n      <th>4cd1abee9ee0a70a28db7692076cdb64290d2558</th>\n      <td>https://www.buzzfeed.com/paulmcleod/the-govern...</td>\n      <td>The Government Could Shut Down Again Because C...</td>\n      <td>2018-02-01 22:04:44.109</td>\n      <td>2018-02-01 22:02:51</td>\n      <td>154</td>\n      <td>0.49</td>\n      <td>2018-02-02T04:21:16.604Z</td>\n      <td>49</td>\n      <td>75</td>\n      <td>30</td>\n      <td>...</td>\n      <td>2018-02-02T03:54:46.000Z</td>\n      <td>147</td>\n      <td>921.00</td>\n      <td>12.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>57.00</td>\n      <td>33.00</td>\n    </tr>\n    <tr>\n      <th>18207f66ea49fc0711d7b656f361bf36c280696e</th>\n      <td>https://www.buzzfeed.com/pdominguez/how-omaros...</td>\n      <td>How Omarosa Really Won Big Brother</td>\n      <td>2018-02-28 21:13:17.272</td>\n      <td>2018-02-28 19:49:55</td>\n      <td>94</td>\n      <td>0.82</td>\n      <td>2018-02-28T21:25:18.654Z</td>\n      <td>46</td>\n      <td>18</td>\n      <td>30</td>\n      <td>...</td>\n      <td>2018-02-28T21:10:28.000Z</td>\n      <td>147</td>\n      <td>2199.00</td>\n      <td>10.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>53.00</td>\n      <td>33.00</td>\n    </tr>\n    <tr>\n      <th>88fbb92d88927378ecc08cb51f0526e5b1311156</th>\n      <td>https://www.buzzfeed.com/ryanmac/this-is-the-m...</td>\n      <td>This Man Helped Peter Thiel Demolish Gawker</td>\n      <td>2018-02-23 19:10:19.656</td>\n      <td>2018-02-23 17:38:58</td>\n      <td>140</td>\n      <td>0.55</td>\n      <td>2018-02-23T19:22:07.651Z</td>\n      <td>3</td>\n      <td>60</td>\n      <td>77</td>\n      <td>...</td>\n      <td>2018-02-23T23:24:56.000Z</td>\n      <td>147</td>\n      <td>2203.00</td>\n      <td>11.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>54.00</td>\n      <td>32.00</td>\n    </tr>\n    <tr>\n      <th>51fc22587b0f28c4f7777610bdce52994171f9b8</th>\n      <td>https://www.buzzfeed.com/borzoudaragahi/what-h...</td>\n      <td>This Woman Spoke Out Against A War And Then Po...</td>\n      <td>2018-02-11 15:34:18.446</td>\n      <td>2018-02-09 20:32:21</td>\n      <td>2</td>\n      <td>0.18</td>\n      <td>2018-02-11T15:46:13.755Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>1347.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>0.00</td>\n      <td>33.00</td>\n      <td>34.00</td>\n      <td>32.00</td>\n    </tr>\n    <tr>\n      <th>b34b52dcdcedb91fdf22c99651187e527adeecd4</th>\n      <td>https://www.buzzfeed.com/mbvd/a-new-report-on-...</td>\n      <td>A New Report On The Hawaii Missile Alert Says ...</td>\n      <td>2018-02-21 01:31:19.349</td>\n      <td>2018-02-21 00:54:53</td>\n      <td>64</td>\n      <td>0.28</td>\n      <td>2018-02-21T04:46:10.051Z</td>\n      <td>12</td>\n      <td>33</td>\n      <td>19</td>\n      <td>...</td>\n      <td>2018-02-21T03:22:00.000Z</td>\n      <td>147</td>\n      <td>598.00</td>\n      <td>8.00</td>\n      <td>19.00</td>\n      <td>10.00</td>\n      <td>11.00</td>\n      <td>40.00</td>\n      <td>48.00</td>\n      <td>32.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>25 rows \u00d7 27 columns</p>\n</div>\n\n\n\n\n```python\n# high response but not promoted\ndata.sort_values(\"score_diff\", ascending=True).head(25)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n      <th>score_diff</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>5e21237490a319711d22eea26dc26a4c3682dea0</th>\n      <td>https://www.washingtonpost.com/news/reliable-s...</td>\n      <td>Dolly Parton likes to give away books. She jus...</td>\n      <td>2018-02-27 19:13:20.537</td>\n      <td>2018-02-27 19:02:15.000</td>\n      <td>114572</td>\n      <td>448.59</td>\n      <td>2018-02-28T06:02:20.498Z</td>\n      <td>7737</td>\n      <td>96894</td>\n      <td>9941</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>322.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>9e82991a7f4b60377f15ada5d5bb9f02c57a892f</th>\n      <td>https://www.washingtonpost.com/news/national/w...</td>\n      <td>Armed deputy on duty at Fla. school waited out...</td>\n      <td>2018-02-22 23:14:14.096</td>\n      <td>2018-02-22 23:10:00.000</td>\n      <td>201911</td>\n      <td>385.05</td>\n      <td>2018-02-23T00:09:16.414Z</td>\n      <td>93017</td>\n      <td>86962</td>\n      <td>21932</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>102.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>0663587e18695b514a676ef31678320225937272</th>\n      <td>http://www.foxnews.com/us/2018/02/13/delaware-...</td>\n      <td>Delaware may let students \u2018choose\u2019 their race,...</td>\n      <td>2018-02-20 20:14:20.100</td>\n      <td>2018-02-20 20:01:33.000</td>\n      <td>126486</td>\n      <td>170.66</td>\n      <td>2018-02-21T05:54:20.144Z</td>\n      <td>44600</td>\n      <td>69253</td>\n      <td>12633</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>827.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>fb1944a99013e1b35fd6a91c48804999102e083e</th>\n      <td>https://www.nbcnews.com/politics/donald-trump/...</td>\n      <td>Trump Signs Bill Revoking Obama-Era Gun Checks...</td>\n      <td>2018-02-15 21:25:15.475</td>\n      <td>2018-02-15 21:23:07.000</td>\n      <td>1733438</td>\n      <td>4222.05</td>\n      <td>2018-02-17T21:37:14.123Z</td>\n      <td>579201</td>\n      <td>879715</td>\n      <td>274522</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>826</td>\n      <td>410.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>d700e2555219b689fa3e9165aea1ed1817931a69</th>\n      <td>http://www.foxnews.com/us/2018/02/27/texas-gir...</td>\n      <td>Texas girl, 17, stabs newborn to death minutes...</td>\n      <td>2018-02-28 00:39:13.863</td>\n      <td>2018-02-28 00:39:13.863</td>\n      <td>113688</td>\n      <td>70.98</td>\n      <td>2018-03-01T02:58:10.218Z</td>\n      <td>25583</td>\n      <td>68921</td>\n      <td>19184</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>344.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>5c33cf13f73345e32664ed8be841dc56b86e107d</th>\n      <td>https://www.indy100.com/article/emma-gonzalez-...</td>\n      <td>The Florida student spearheading the gun debat...</td>\n      <td>2018-02-25 11:24:17.265</td>\n      <td>2018-02-25 11:16:22.000</td>\n      <td>159836</td>\n      <td>126.53</td>\n      <td>2018-02-25T22:14:10.236Z</td>\n      <td>10622</td>\n      <td>138519</td>\n      <td>10695</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>5014</td>\n      <td>258.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>073db9d2d004bb61e3f507a4670347f1142b1819</th>\n      <td>http://www.foxnews.com/us/2018/02/20/florida-h...</td>\n      <td>Florida House aide fired after claiming Florid...</td>\n      <td>2018-02-21 00:49:14.722</td>\n      <td>2018-02-21 00:49:14.722</td>\n      <td>99873</td>\n      <td>103.73</td>\n      <td>2018-02-21T14:02:13.113Z</td>\n      <td>42670</td>\n      <td>42234</td>\n      <td>14969</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>590.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>8d3e2975bed53d3885889ca47afdc8a309d74370</th>\n      <td>https://www.washingtonpost.com/opinions/beat-y...</td>\n      <td>Beat your wife, lose your gun. That\u2019s how it s...</td>\n      <td>2018-02-28 00:16:12.833</td>\n      <td>2018-02-28 00:09:50.000</td>\n      <td>84513</td>\n      <td>307.37</td>\n      <td>2018-03-02T16:10:07.064Z</td>\n      <td>12548</td>\n      <td>66034</td>\n      <td>5931</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>501.00</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>49.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>6864f9a08eee3a16c208675d81ea26c6dba34608</th>\n      <td>http://www.dailymail.co.uk/tvshowbiz/article-5...</td>\n      <td>MAFS stars Troy and Carly engage in steamy kis...</td>\n      <td>2018-02-12 01:10:20.976</td>\n      <td>2018-02-12 01:07:48.000</td>\n      <td>112395</td>\n      <td>245.34</td>\n      <td>2018-02-12T05:35:12.625Z</td>\n      <td>99171</td>\n      <td>11772</td>\n      <td>1452</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>438.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>e4af688c612406377380281ed31844390fa0e11b</th>\n      <td>http://www.dailymail.co.uk/news/article-542452...</td>\n      <td>Now plastic straws are banned</td>\n      <td>2018-02-22 23:10:21.766</td>\n      <td>2018-02-22 23:07:43.000</td>\n      <td>107178</td>\n      <td>80.52</td>\n      <td>2018-02-23T13:06:12.913Z</td>\n      <td>21769</td>\n      <td>73417</td>\n      <td>11992</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>922.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>c3fa7bc71b67c98cbb1e9f209ed0a719adc0aace</th>\n      <td>https://www.cnn.com/videos/us/2018/02/15/victi...</td>\n      <td>Victim's mom begs Trump: Do something! - CNN V...</td>\n      <td>2018-02-15 20:59:11.852</td>\n      <td>2018-02-15 20:49:32.000</td>\n      <td>85974</td>\n      <td>993.42</td>\n      <td>2018-02-16T04:03:07.087Z</td>\n      <td>23979</td>\n      <td>46502</td>\n      <td>15493</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>105</td>\n      <td>nan</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>50.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>8a6dd31f5ad1a2dc9216017bf763e41de97981b0</th>\n      <td>https://www.washingtonpost.com/news/inspired-l...</td>\n      <td>Lucas was just named 2018 Gerber baby. He has ...</td>\n      <td>2018-02-07 17:22:16.077</td>\n      <td>2018-02-07 17:10:53.000</td>\n      <td>114315</td>\n      <td>116.45</td>\n      <td>2018-02-08T01:57:11.230Z</td>\n      <td>6202</td>\n      <td>101278</td>\n      <td>6835</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>700.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>52.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>14d31a214e4facda0c86d87707a65d161d7e9eaa</th>\n      <td>http://www.foxnews.com/us/2018/02/28/georgia-t...</td>\n      <td>Georgia teacher in custody after reports of sh...</td>\n      <td>2018-02-28 18:19:21.900</td>\n      <td>2018-02-28 18:03:42.000</td>\n      <td>178634</td>\n      <td>363.57</td>\n      <td>2018-02-28T20:15:08.070Z</td>\n      <td>68963</td>\n      <td>71257</td>\n      <td>38414</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>220.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>52.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>da38b48e9d96a8525f8c805e78e9f9443d3e882d</th>\n      <td>http://www.foxnews.com/us/2018/02/09/tim-tebow...</td>\n      <td>Tim Tebow's 'Night to Shine' celebrates 90,000...</td>\n      <td>2018-02-09 15:04:39.518</td>\n      <td>2018-02-09 14:56:51.000</td>\n      <td>112638</td>\n      <td>203.83</td>\n      <td>2018-02-09T20:21:08.978Z</td>\n      <td>5261</td>\n      <td>99225</td>\n      <td>8152</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>458.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>52.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>670255849c49056b0e26784b1c6d657dbf5a1ddd</th>\n      <td>https://www.huffingtonpost.com/entry/trump-sup...</td>\n      <td>Trump Supporters Consume And Share The Most Fa...</td>\n      <td>2018-02-07 01:19:21.756</td>\n      <td>2018-02-07 01:06:18.034</td>\n      <td>60118</td>\n      <td>347.80</td>\n      <td>2018-02-07T20:03:08.685Z</td>\n      <td>15620</td>\n      <td>34706</td>\n      <td>9792</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>364.00</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>47.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>240e377bd6e8d17dc5b3785a0be38213aa927e49</th>\n      <td>http://www.foxnews.com/us/2018/02/06/high-scho...</td>\n      <td>High school cancels musical after white studen...</td>\n      <td>2018-02-06 20:29:14.140</td>\n      <td>2018-02-06 20:06:25.000</td>\n      <td>76566</td>\n      <td>217.97</td>\n      <td>2018-02-06T22:15:11.567Z</td>\n      <td>28817</td>\n      <td>38169</td>\n      <td>9580</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>542.00</td>\n      <td>48.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>49.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>91b6442a3738ab3d7ac035ddd9db8efbfc7a5535</th>\n      <td>https://www.washingtonpost.com/news/grade-poin...</td>\n      <td>Trump and DeVos call for massive cuts to colle...</td>\n      <td>2018-02-13 21:58:12.640</td>\n      <td>2018-02-13 21:45:58.000</td>\n      <td>64638</td>\n      <td>24.41</td>\n      <td>2018-02-15T02:10:09.694Z</td>\n      <td>16484</td>\n      <td>36782</td>\n      <td>11372</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>1122.00</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>47.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>8985d303c1803ccb878bbce2d18fab0270402683</th>\n      <td>https://www.washingtonpost.com/news/answer-she...</td>\n      <td>If Americans really cared about students\u2019 ment...</td>\n      <td>2018-02-16 00:28:17.677</td>\n      <td>2018-02-16 00:20:52.000</td>\n      <td>72193</td>\n      <td>47.30</td>\n      <td>2018-02-17T16:41:03.436Z</td>\n      <td>9465</td>\n      <td>53129</td>\n      <td>9599</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>881.00</td>\n      <td>48.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>50.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>8467fa14011d0affe30554e7a793ee799bcc7b50</th>\n      <td>https://www.theguardian.com/us-news/2018/feb/2...</td>\n      <td>Spokesman falsely denied expensive table had b...</td>\n      <td>2018-02-28 00:07:04.792</td>\n      <td>2018-02-28 00:02:53.000</td>\n      <td>52895</td>\n      <td>113.37</td>\n      <td>2018-02-28T16:32:21.970Z</td>\n      <td>7703</td>\n      <td>39002</td>\n      <td>6190</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>142</td>\n      <td>408.00</td>\n      <td>46.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>46.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>a7eafd17d0a4717e181718210ed23a452097d37e</th>\n      <td>http://yournewswire.com/cdc-doctor-flu-shot-dead/</td>\n      <td>CDC Doctor, Who Claimed Flu Shot Caused Outbre...</td>\n      <td>2018-02-22 19:34:37.873</td>\n      <td>2018-02-22 18:12:03.000</td>\n      <td>179799</td>\n      <td>71.96</td>\n      <td>2018-02-24T02:51:18.102Z</td>\n      <td>38509</td>\n      <td>95811</td>\n      <td>45479</td>\n      <td>...</td>\n      <td>2018-02-22T20:05:04.000Z</td>\n      <td>22568</td>\n      <td>613.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>4.00</td>\n      <td>5.00</td>\n      <td>55.00</td>\n      <td>-45.00</td>\n    </tr>\n    <tr>\n      <th>6594c8cd8e1992246dedb7d88c6b668b9cb40dc7</th>\n      <td>http://yournewswire.com/pedophile-dead-penis-s...</td>\n      <td>Pedophile Who Raped 3-Month-Old Baby Found Dea...</td>\n      <td>2018-02-17 17:59:28.027</td>\n      <td>2018-02-17 17:23:40.000</td>\n      <td>102627</td>\n      <td>32.73</td>\n      <td>2018-02-21T19:53:13.378Z</td>\n      <td>24098</td>\n      <td>67729</td>\n      <td>10800</td>\n      <td>...</td>\n      <td>2018-02-17T20:31:35.000Z</td>\n      <td>22568</td>\n      <td>360.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>4.00</td>\n      <td>5.00</td>\n      <td>55.00</td>\n      <td>-45.00</td>\n    </tr>\n    <tr>\n      <th>fb223beac020beeada1600f213901cec0b9853b8</th>\n      <td>http://yournewswire.com/judge-pedophile-prison...</td>\n      <td>Judge Cuts Pedophile\u2019s Prison Term Claiming 3-...</td>\n      <td>2018-02-10 16:59:30.838</td>\n      <td>2018-02-10 16:43:30.000</td>\n      <td>314525</td>\n      <td>363.43</td>\n      <td>2018-02-14T20:05:21.412Z</td>\n      <td>104622</td>\n      <td>164861</td>\n      <td>45042</td>\n      <td>...</td>\n      <td>2018-02-10T19:13:53.000Z</td>\n      <td>22568</td>\n      <td>403.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>4.00</td>\n      <td>5.00</td>\n      <td>55.00</td>\n      <td>-45.00</td>\n    </tr>\n    <tr>\n      <th>ce9daaa17cbab41fef36b8ddb4c8ec83f4560f0a</th>\n      <td>https://www.washingtonpost.com/powerpost/house...</td>\n      <td>House passes changes to Americans With Disabil...</td>\n      <td>2018-02-15 17:54:14.705</td>\n      <td>2018-02-15 17:35:00.000</td>\n      <td>51851</td>\n      <td>56.45</td>\n      <td>2018-02-16T02:34:13.544Z</td>\n      <td>8709</td>\n      <td>31582</td>\n      <td>11560</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>517.00</td>\n      <td>46.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>47.00</td>\n      <td>-45.00</td>\n    </tr>\n    <tr>\n      <th>b1b8b57a292c94f4259fde4bab63f84a9c8ca810</th>\n      <td>http://yournewswire.com/catholic-archbishop-pe...</td>\n      <td>Catholic Archbishop Says Pedophilia Is \u2018Spirit...</td>\n      <td>2018-02-12 17:54:31.976</td>\n      <td>2018-02-12 17:23:02.000</td>\n      <td>263961</td>\n      <td>201.12</td>\n      <td>2018-02-18T04:08:02.439Z</td>\n      <td>108399</td>\n      <td>126464</td>\n      <td>29098</td>\n      <td>...</td>\n      <td>2018-02-14T13:20:00.000Z</td>\n      <td>22568</td>\n      <td>427.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>4.00</td>\n      <td>5.00</td>\n      <td>55.00</td>\n      <td>-45.00</td>\n    </tr>\n    <tr>\n      <th>916a275eedcdb097b624d00a0c14dfb8ca53905c</th>\n      <td>https://www.washingtonpost.com/news/wonk/wp/20...</td>\n      <td>Report: No progress for African Americans on h...</td>\n      <td>2018-02-26 20:52:11.920</td>\n      <td>2018-02-26 20:45:06.000</td>\n      <td>65459</td>\n      <td>31.23</td>\n      <td>2018-02-27T17:04:12.592Z</td>\n      <td>11981</td>\n      <td>38723</td>\n      <td>14755</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>743.00</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>49.00</td>\n      <td>-45.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>25 rows \u00d7 27 columns</p>\n</div>\n\n\n\nWrite that data to a file. Note that the scores here are provisional for two reasons:\n1. they should be using a rolling-month based on the article publication date to calculate medians/min/max etc, whereas in this workbook we as just using values for the month of May\n2. for analysis, we've rounded the numbers; we don't expect to do that for the actual scores\n\n\n```python\ndata.to_csv(\"articles_with_provisional_scores_\" + date_filename + \".csv\")\n```\n\n# Summary\n\nThe attention index of an article is comprised of four components:\n\n- *lead score* (max 20 points) based on how long an article was the lead story on the publisher's home page, scaled by the traffic to that publisher\n- *front score* (max 15 points) based on how long an article was present on the publisher's home page, scaled by traffic to that publisher\n- *Facebook promotion score* (max 15 points) based on whether the article was promoted to the publisher's Facebook brand page, scaled by the reach of that brand page\n- *response score* (max 50 points) based on the number of Facebook engagements the article received, relative to other articles\n\nOr, in other words:\n\n\\begin{align}\nattentionIndex_a &= leadScore_a + frontScore_a + facebookPromotionScore_a + responseScore_a \\\\\nleadScore_a &= 20 \\cdot \\left(\\frac{\\min(minsAsLead_a, 60)}{alexaRank_a}\\right) \\cdot \\left( \\frac{\\min(alexaRank)}{60} \\right) \\\\\nfrontScore_a &= \n15 \\cdot\n\\left(\\frac{\\min(minsOnFront_a, 1440)}{alexaRank_a \\cdot numArticlesOnFront_a}\\right) \\cdot\n\\left( \\frac{\\min(alexaRank \\cdot numArticlesOnFront)}{1440} \\right) \\\\\nfacebookPromotion_a &= \n\\begin{cases}\n 0 \\text{ if not shared on brand page }\\\\\n   15 \\cdot \\frac{\\log(brandPageLikes_a) - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))}  \\text{ otherwise }\n\\end{cases}   \n\\\\\nresponseScore_a &= \n\\begin{cases} \n   0 \\text{ if } engagements_a = 0 \\\\\n   50 \\cdot \n   \\frac{\\log(\\min(engagements_a,limit) + median(engagements)) - \\log(1 + median(engagements))}\n   {\\log(limit + median(engagements)) - \\log(1 + median(engagements))} \\text{ if } engagements_a > 0\n\\end{cases} \\\\\n\\end{align} \n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "244ba7819492e89dd81b05cd4ceca16203152bdf", "size": 729017, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "data/attention-index-february-2018.ipynb", "max_stars_repo_name": "kaleida/attention-index", "max_stars_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2017-06-03T11:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T10:02:06.000Z", "max_issues_repo_path": "data/attention-index-february-2018.ipynb", "max_issues_repo_name": "kaleida/attention-index", "max_issues_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data/attention-index-february-2018.ipynb", "max_forks_repo_name": "kaleida/attention-index", "max_forks_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 84.5041149878, "max_line_length": 44988, "alphanum_fraction": 0.6916052712, "converted": true, "num_tokens": 56989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27512971193602087, "lm_q2_score": 0.048136765995893234, "lm_q1q2_score": 0.01324385456198175}}
{"text": "# Setup\n\n\n```python\n%matplotlib inline\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\n```\n\n\n```python\ndate_filename = \"2018-04-01_2018-04-30\"\n```\n\n\n```python\ndata = pd.read_csv(\"articles_\" + date_filename + \".csv\", index_col=\"id\", \\\n                   parse_dates=[\"published\", \"discovered\"])\ndata.head()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>publisher_name</th>\n      <th>publisher_id</th>\n      <th>mins_as_lead</th>\n      <th>mins_on_front</th>\n      <th>num_articles_on_front</th>\n      <th>fb_brand_page</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>eb8e9bb4465037557f2b72a02463ef2240048a0a</th>\n      <td>https://www.thetimes.co.uk/article/mccann-pres...</td>\n      <td>McCann presence helps Dundee secure valuable p...</td>\n      <td>2018-04-01 17:09:07.450</td>\n      <td>2018-04-01</td>\n      <td>0</td>\n      <td>0.000000</td>\n      <td>2018-04-01T17:20:06.737Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>350</td>\n      <td>392.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>125.0</td>\n    </tr>\n    <tr>\n      <th>58f51d1d8e99d7c9909b84201706b10411632331</th>\n      <td>https://www.thetimes.co.uk/article/anthony-jos...</td>\n      <td>Anthony Joshua showed he has the maturity to r...</td>\n      <td>2018-04-01 17:09:08.170</td>\n      <td>2018-04-01</td>\n      <td>0</td>\n      <td>0.000000</td>\n      <td>2018-04-01T17:20:06.739Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>350</td>\n      <td>392.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>125.0</td>\n    </tr>\n    <tr>\n      <th>0b1a1a27c7e6f3aff21586ae2d447b4f1944e597</th>\n      <td>https://www.thetimes.co.uk/article/saracens-eu...</td>\n      <td>Saracens\u2019 European reign ended by familiar foes</td>\n      <td>2018-04-01 17:09:08.413</td>\n      <td>2018-04-01</td>\n      <td>0</td>\n      <td>0.000000</td>\n      <td>2018-04-01T17:20:06.740Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>350</td>\n      <td>392.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>125.0</td>\n    </tr>\n    <tr>\n      <th>3f9169b7e2d845613721fe006eba63b9bd8f6ffb</th>\n      <td>https://www.thetimes.co.uk/article/labour-part...</td>\n      <td>Labour Party donor Sir David Garrard quits par...</td>\n      <td>2018-04-01 11:09:13.260</td>\n      <td>2018-04-01</td>\n      <td>1</td>\n      <td>0.016429</td>\n      <td>2018-04-01T12:21:04.387Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>709</td>\n      <td>381.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>126.0</td>\n    </tr>\n    <tr>\n      <th>2a743b32a30e803f38b966ef27e1cbf9f5ccd7ba</th>\n      <td>https://www.thetimes.co.uk/article/jordan-pete...</td>\n      <td>Jordan Peterson: the bestselling author and cl...</td>\n      <td>2018-04-01 20:33:13.945</td>\n      <td>2018-04-01</td>\n      <td>293</td>\n      <td>1.820941</td>\n      <td>2018-04-01T20:45:07.257Z</td>\n      <td>86</td>\n      <td>144</td>\n      <td>63</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>True</td>\n      <td>763761.0</td>\n      <td>2018-04-01T20:30:02.000Z</td>\n      <td>6435</td>\n      <td>125.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n# Response Score\n\nThe response score is a number between 0 and 50 that indicates the level of response to an article.\n\n\n\nPerhaps in the future we may choose to include other factors, but for now we just include engagements on Facebook. The maximum score of 50 should be achieved by an article that does really well compared with others.\n\n\n```python\npd.options.display.float_format = '{:.2f}'.format\ndata.fb_engagements.describe([0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count    138275.00\n    mean       1301.27\n    std       10881.11\n    min           0.00\n    50%          25.00\n    75%         236.00\n    90%        1467.00\n    95%        4082.00\n    99%       24069.16\n    99.5%     42726.87\n    99.9%    127818.48\n    max     1282889.00\n    Name: fb_engagements, dtype: float64\n\n\n\nThere's 2 articles with more than 1 million engagements this month.\n\n\n```python\ndata[data.fb_engagements > 1000000]\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>publisher_name</th>\n      <th>publisher_id</th>\n      <th>mins_as_lead</th>\n      <th>mins_on_front</th>\n      <th>num_articles_on_front</th>\n      <th>fb_brand_page</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>a2c14a5be2fd2120a995789a59f63751734d8312</th>\n      <td>http://www.foxnews.com/entertainment/2018/04/1...</td>\n      <td>'Full Metal Jacket' actor R. Lee Ermey dies at...</td>\n      <td>2018-04-15 23:23:18.706</td>\n      <td>2018-04-15 23:20:18</td>\n      <td>1088522</td>\n      <td>3701.16</td>\n      <td>2018-04-15T23:55:11.721Z</td>\n      <td>111839</td>\n      <td>781170</td>\n      <td>195513</td>\n      <td>Fox News</td>\n      <td>foxnews_com</td>\n      <td>0</td>\n      <td>2204</td>\n      <td>154.00</td>\n      <td>True</td>\n      <td>16331201.00</td>\n      <td>2018-04-15T23:21:55.000Z</td>\n      <td>285</td>\n      <td>359.00</td>\n    </tr>\n    <tr>\n      <th>1c67b7d5633798a8217ff854d6e4854d64ac1b78</th>\n      <td>https://www.npr.org/sections/ed/2018/04/25/605...</td>\n      <td>High-Paying Trade Jobs Sit Empty, While High S...</td>\n      <td>2018-04-25 21:01:27.348</td>\n      <td>2018-04-25 20:00:00</td>\n      <td>1282889</td>\n      <td>833.15</td>\n      <td>2018-04-26T16:49:11.642Z</td>\n      <td>216494</td>\n      <td>829474</td>\n      <td>236921</td>\n      <td>NPR</td>\n      <td>npr_org</td>\n      <td>0</td>\n      <td>965</td>\n      <td>30.00</td>\n      <td>True</td>\n      <td>6298047.00</td>\n      <td>2018-04-26T04:22:00.000Z</td>\n      <td>594</td>\n      <td>1673.00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndata.fb_engagements.mode()\n```\n\n\n\n\n    0    0\n    dtype: int64\n\n\n\n*november* Going back to the enagement counts, we see the mean is 1,117, mode is zero, median is 24, 90th percentile is 1,453, 99th percentile is 21,166, 99.5th percentile is 33,982. The standard deviation is 8,083, significantly higher than the mean, so this is not a normal distribution. \n\n*december* Going back to the enagement counts, we see the mean is 1,106, mode is zero, median is 24, 90th percentile is 1,545, 99th percentile is 20,228, 99.5th percentile is 32,446. The standard deviation is 9,852, significantly higher than the mean, so this is not a normal distribution. \n\n*january 2018* Going back to the enagement counts, we see the mean is 1,108, mode is zero, median is 26, 90th percentile is 1,621, 99th percentile is 19,918, 99.5th percentile is 32,935. The standard deviation is 8,278, significantly higher than the mean, so this is not a normal distribution. \n\n*february 2018* Going back to the enagement counts, we see the mean is 1,237, mode is zero, median is 25, 90th percentile is 1,453, 99th percentile is 23,172, 99.5th percentile is 38,692. The standard deviation is 11,019, significantly higher than the mean, so this is not a normal distribution. \n\n*march 2018* Going back to the enagement counts, we see the mean is 1,519, mode is zero, median is 25, 90th percentile is 1,597, 99th percentile is 27,468, 99.5th percentile is 51,204. The standard deviation is 15,132, significantly higher than the mean, so this is not a normal distribution. \n\n*april 2018* Going back to the enagement counts, we see the mean is 1,301, mode is zero, median is 25, 90th percentile is 1,467, 99th percentile is 24,069, 99.5th percentile is 42,726. The standard deviation is 10,881, significantly higher than the mean, so this is not a normal distribution. \n\nKey publishers stats\n\n\n```python\ndata.groupby(\"publisher_id\").agg({'url': 'count', 'fb_engagements': ['sum', 'median', 'mean']})\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th>url</th>\n      <th colspan=\"3\" halign=\"left\">fb_engagements</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>count</th>\n      <th>sum</th>\n      <th>median</th>\n      <th>mean</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>37</td>\n      <td>182291</td>\n      <td>2207.00</td>\n      <td>4926.78</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>12059</td>\n      <td>10830500</td>\n      <td>26.00</td>\n      <td>898.13</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>2589</td>\n      <td>7211253</td>\n      <td>145.00</td>\n      <td>2785.34</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>42</td>\n      <td>39391</td>\n      <td>398.50</td>\n      <td>937.88</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>1290</td>\n      <td>2463775</td>\n      <td>191.50</td>\n      <td>1909.90</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>3996</td>\n      <td>24266804</td>\n      <td>516.50</td>\n      <td>6072.77</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>24494</td>\n      <td>17875059</td>\n      <td>18.00</td>\n      <td>729.77</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>504</td>\n      <td>245341</td>\n      <td>32.50</td>\n      <td>486.79</td>\n    </tr>\n    <tr>\n      <th>evolvepolitics_com</th>\n      <td>65</td>\n      <td>255755</td>\n      <td>1553.00</td>\n      <td>3934.69</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>5009</td>\n      <td>22811621</td>\n      <td>103.00</td>\n      <td>4554.13</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>4416</td>\n      <td>270005</td>\n      <td>4.00</td>\n      <td>61.14</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>2250</td>\n      <td>10943965</td>\n      <td>785.00</td>\n      <td>4863.98</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>5290</td>\n      <td>3943093</td>\n      <td>35.50</td>\n      <td>745.39</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>395</td>\n      <td>257944</td>\n      <td>111.00</td>\n      <td>653.02</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>3649</td>\n      <td>2023160</td>\n      <td>71.00</td>\n      <td>554.44</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>141</td>\n      <td>2837</td>\n      <td>13.00</td>\n      <td>20.12</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>9204</td>\n      <td>5571882</td>\n      <td>32.00</td>\n      <td>605.38</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>1878</td>\n      <td>7042840</td>\n      <td>420.50</td>\n      <td>3750.18</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>439</td>\n      <td>97708</td>\n      <td>19.00</td>\n      <td>222.57</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>1824</td>\n      <td>10768007</td>\n      <td>346.00</td>\n      <td>5903.51</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>4627</td>\n      <td>18669054</td>\n      <td>209.00</td>\n      <td>4034.81</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>257</td>\n      <td>81152</td>\n      <td>150.00</td>\n      <td>315.77</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>51</td>\n      <td>52191</td>\n      <td>346.00</td>\n      <td>1023.35</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>6179</td>\n      <td>3171709</td>\n      <td>17.00</td>\n      <td>513.30</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>2302</td>\n      <td>3609677</td>\n      <td>376.50</td>\n      <td>1568.06</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>121</td>\n      <td>115099</td>\n      <td>545.00</td>\n      <td>951.23</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>6009</td>\n      <td>1703445</td>\n      <td>16.00</td>\n      <td>283.48</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>276</td>\n      <td>345275</td>\n      <td>645.00</td>\n      <td>1251.00</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>7989</td>\n      <td>8911855</td>\n      <td>122.00</td>\n      <td>1115.52</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>8887</td>\n      <td>295032</td>\n      <td>1.00</td>\n      <td>33.20</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>21307</td>\n      <td>13599144</td>\n      <td>0.00</td>\n      <td>638.25</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>302</td>\n      <td>497503</td>\n      <td>42.50</td>\n      <td>1647.36</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>397</td>\n      <td>1778898</td>\n      <td>45.00</td>\n      <td>4480.85</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\n\nnon_zero_fb_enagagements = data.fb_engagements[data.fb_engagements > 0]\n```\n\nThat's a bit better, but still way too clustered at the low end. Let's look at a log normal distribution.\n\n\n```python\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\nninety = data.fb_engagements.quantile(.90)\nninetyfive = data.fb_engagements.quantile(.95)\nninetynine = data.fb_engagements.quantile(.99)\n\nplt.figure(figsize=(12,4.5))\nplt.hist(np.log(non_zero_fb_enagagements + median), bins=50)\nplt.axvline(np.log(mean), linestyle=':', label=f'Mean ({mean:,.0f})', color='green')\nplt.axvline(np.log(median), label=f'Median ({median:,.0f})', color='green')\nplt.axvline(np.log(ninety), linestyle='--', label=f'90% percentile ({ninety:,.0f})', color='red')\nplt.axvline(np.log(ninetyfive), linestyle='-.', label=f'95% percentile ({ninetyfive:,.0f})', color='red')\nplt.axvline(np.log(ninetynine), linestyle=':', label=f'99% percentile ({ninetynine:,.0f})', color='red')\nleg = plt.legend()\n\n```\n\n\n```python\neng = data.fb_engagements[(data.fb_engagements < 5000)]\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\nninety = data.fb_engagements.quantile(.90)\nninetyfive = data.fb_engagements.quantile(.95)\nninetynine = data.fb_engagements.quantile(.99)\n\nplt.figure(figsize=(15,7))\nplt.hist(eng, bins=50)\nplt.title(\"Article count by engagements\")\nplt.axvline(median, label=f'Median ({median:,.0f})', color='green')\nplt.axvline(mean, linestyle=':', label=f'Mean ({mean:,.0f})', color='green')\nplt.axvline(ninety, linestyle='--', label=f'90% percentile ({ninety:,.0f})', color='red')\nplt.axvline(ninetyfive, linestyle='-.', label=f'95% percentile ({ninetyfive:,.0f})', color='red')\n# plt.axvline(ninetynine, linestyle=':', label=f'99% percentile ({ninetynine:,.0f})', color='red')\nleg = plt.legend()\n\n```\n\n\n```python\nlog_engagements = (non_zero_fb_enagagements\n                   .clip_upper(data.fb_engagements.quantile(.999))\n                   .apply(lambda x: np.log(x + median))\n                  )\nlog_engagements.describe()\n```\n\n\n\n\n    count   113072.00\n    mean         4.98\n    std          1.76\n    min          3.26\n    25%          3.53\n    50%          4.38\n    75%          5.99\n    max         11.76\n    Name: fb_engagements, dtype: float64\n\n\n\nUse standard feature scaling to bring that to a 1 to 50 range\n\n\n\n```python\ndef scale_log_engagements(engagements_logged):\n    return np.ceil(\n        50 * (engagements_logged - log_engagements.min()) / (log_engagements.max() - log_engagements.min())\n    )\n\ndef scale_engagements(engagements):\n    return scale_log_engagements(np.log(engagements + median))\n\nscaled_non_zero_engagements = scale_log_engagements(log_engagements)\nscaled_non_zero_engagements.describe()\n```\n\n\n\n\n    count   113072.00\n    mean        10.62\n    std         10.38\n    min          0.00\n    25%          2.00\n    50%          7.00\n    75%         17.00\n    max         50.00\n    Name: fb_engagements, dtype: float64\n\n\n\n\n```python\n# add in the zeros, as zero\nscaled_engagements = pd.concat([scaled_non_zero_engagements, data.fb_engagements[data.fb_engagements == 0]])\n```\n\n\n```python\nproposed = pd.DataFrame({\"fb_engagements\": data.fb_engagements, \"response_score\": scaled_engagements})\nproposed.response_score.plot.hist(bins=50)\n```\n\nLooks good to me, lets save that.\n\n\n```python\ndata[\"response_score\"] = proposed.response_score\n```\n\n### Proposal\n\nThe maximum of 50 points is awarded when the engagements are greater than the 99.9th percentile, rolling over the last month. \n\ni.e. where $limit$ is the 99.5th percentile of engagements calculated over the previous month, the response score for article $a$ is:\n\n\\begin{align}\nbasicScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   \\log(\\min(engagements_a,limit) + median(engagements))      & \\text{if } engagements_a > 0\n\\end{cases} \\\\\nresponseScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   50 \\cdot \\frac{basicScore_a - \\min(basicScore)}{\\max(basicScore) - \\min(basicScore)}       & \\text{if } engagements_a > 0\n\\end{cases} \\\\\n\\\\\n\\text{The latter equation can be expanded to:} \\\\\nresponseScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   50 \\cdot \n   \\frac{\\log(\\min(engagements_a,limit) + median(engagements)) - \\log(1 + median(engagements))}\n   {\\log(limit + median(engagements)) - \\log(1 + median(engagements))}       & \\text{if } engagements_a > 0\n\\end{cases} \\\\\n\\end{align}\n\n# Promotion Score\n\nThe aim of the promotion score is to indicate how important the article was to the publisher, by tracking where they chose to promote it. This is a number between 0 and 50 comprised of:\n\n- 20 points based on whether the article was promoted as the \"lead\" story on the publisher's home page\n- 15 points based on how long the article was promoted anywhere on the publisher's home page\n- 15 points based on whether the article was promoted on the publisher's main facebook brand page\n\nThe first two should be scaled by the popularity/reach of the home page, for which we use the alexa page rank as a proxy.\n\nThe last should be scaled by the popularity/reach of the brand page, for which we use the number of likes the brand page has.\n\n### Lead story (20 points)\n\n\n```python\ndata.mins_as_lead.describe([0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count   138275.00\n    mean         9.26\n    std         90.28\n    min          0.00\n    50%          0.00\n    75%          0.00\n    90%          0.00\n    95%          0.00\n    99%        284.00\n    99.5%      580.00\n    99.9%     1199.73\n    max       9840.00\n    Name: mins_as_lead, dtype: float64\n\n\n\nAs expected, the vast majority of articles don't make it as lead. Let's explore how long typically publishers put something as lead for.\n\n\n```python\nlead_articles = data[data.mins_as_lead > 0]\n```\n\n\n```python\nlead_articles.mins_as_lead.describe([0.25, 0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count   3928.00\n    mean     326.03\n    std      428.55\n    min        4.00\n    25%       84.00\n    50%      184.00\n    75%      424.00\n    90%      804.30\n    95%     1074.00\n    99%     1599.73\n    99.5%   1832.37\n    99.9%   4428.57\n    max     9840.00\n    Name: mins_as_lead, dtype: float64\n\n\n\n\n```python\nlead_articles.mins_as_lead.plot.hist(bins=50)\n```\n\nFor lead, it's a  significant thing for an article to be lead at all, so although we want to penalise articles that were lead for a very short time, mostly we want to score the maximum even if it wasn't lead for ages. So we'll give maximum points when something has been lead for an hour.\n\n\n```python\nlead_articles.mins_as_lead.clip_upper(60).plot.hist(bins=50)\n```\n\nWe also want to scale this by the alexa page rank, such that the maximum score of 20 points is for an article that was on the front for 4 hours for the most popular site.\n\nSo lets explore the alexa nunbers.\n\n\n```python\nalexa_ranks = data.groupby(by=\"publisher_id\").alexa_rank.mean().sort_values()\nalexa_ranks\n```\n\n\n\n\n    publisher_id\n    bbc_co_uk                               96\n    cnn_com                                105\n    nytimes_com                            120\n    theguardian_com                        142\n    buzzfeed_com                           147\n    dailymail_co_uk                        158\n    washingtonpost_com                     191\n    huffingtonpost_com                     215\n    foxnews_com                            285\n    rt_com                                 365\n    telegraph_co_uk                        370\n    independent_co_uk                      386\n    reuters_com                            497\n    npr_org                                594\n    lemonde_fr                             618\n    mirror_co_uk                           706\n    nbcnews_com                            826\n    breitbart_com                          994\n    ft_com                                1596\n    economist_com                         1825\n    indy100_com                           5014\n    thetimes_co_uk                        6435\n    newstatesman_com                     12769\n    thecanary_co                         15686\n    propublica_org                       16066\n    yournewswire_com                     22568\n    order-order_com                      32515\n    anotherangryvoice_blogspot_co_uk     77827\n    westmonster_com                      97775\n    evolvepolitics_com                  119412\n    skwawkbox_org                       152475\n    libdemvoice_org                     344992\n    brexitcentral_com                   469149\n    Name: alexa_rank, dtype: int64\n\n\n\n\n```python\nalexa_ranks.plot.bar(figsize=[10,5])\n```\n\nLet's try the simple option first: just divide the number of minutes as lead by the alexa rank. What's the scale of numbers we get then.\n\n\n```python\nlead_proposal_1 = lead_articles.mins_as_lead.clip_upper(60) / lead_articles.alexa_rank\nlead_proposal_1.plot.hist()\n```\n\nLooks like there's too much of a cluster around 0. Have we massively over penalised the publishers with a high alexa rank?\n\n\n```python\nlead_proposal_1.groupby(data.publisher_id).mean().plot.bar(figsize=[10,5])\n```\n\nYes. Let's try taking the log of the alexa rank and see if that looks better.\n\n\n```python\nlead_proposal_2 = (lead_articles.mins_as_lead.clip_upper(60) / np.log(lead_articles.alexa_rank))\nlead_proposal_2.plot.hist()\n```\n\n\n```python\nlead_proposal_2.groupby(data.publisher_id).describe()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>25%</th>\n      <th>50%</th>\n      <th>75%</th>\n      <th>max</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>37.00</td>\n      <td>5.33</td>\n      <td>0.00</td>\n      <td>5.33</td>\n      <td>5.33</td>\n      <td>5.33</td>\n      <td>5.33</td>\n      <td>5.33</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>105.00</td>\n      <td>12.97</td>\n      <td>1.31</td>\n      <td>2.19</td>\n      <td>13.15</td>\n      <td>13.15</td>\n      <td>13.15</td>\n      <td>13.15</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>205.00</td>\n      <td>8.18</td>\n      <td>1.63</td>\n      <td>0.72</td>\n      <td>8.69</td>\n      <td>8.69</td>\n      <td>8.69</td>\n      <td>8.69</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>35.00</td>\n      <td>4.49</td>\n      <td>0.65</td>\n      <td>0.77</td>\n      <td>4.59</td>\n      <td>4.59</td>\n      <td>4.59</td>\n      <td>4.59</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>321.00</td>\n      <td>11.74</td>\n      <td>1.24</td>\n      <td>1.00</td>\n      <td>12.02</td>\n      <td>12.02</td>\n      <td>12.02</td>\n      <td>12.02</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>210.00</td>\n      <td>12.29</td>\n      <td>2.00</td>\n      <td>2.15</td>\n      <td>12.89</td>\n      <td>12.89</td>\n      <td>12.89</td>\n      <td>12.89</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>154.00</td>\n      <td>11.31</td>\n      <td>1.89</td>\n      <td>0.99</td>\n      <td>11.85</td>\n      <td>11.85</td>\n      <td>11.85</td>\n      <td>11.85</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>48.00</td>\n      <td>7.65</td>\n      <td>1.23</td>\n      <td>1.33</td>\n      <td>7.99</td>\n      <td>7.99</td>\n      <td>7.99</td>\n      <td>7.99</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>114.00</td>\n      <td>10.50</td>\n      <td>0.62</td>\n      <td>6.90</td>\n      <td>10.61</td>\n      <td>10.61</td>\n      <td>10.61</td>\n      <td>10.61</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>98.00</td>\n      <td>7.59</td>\n      <td>1.70</td>\n      <td>0.68</td>\n      <td>8.14</td>\n      <td>8.14</td>\n      <td>8.14</td>\n      <td>8.14</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>148.00</td>\n      <td>11.13</td>\n      <td>0.40</td>\n      <td>7.26</td>\n      <td>11.17</td>\n      <td>11.17</td>\n      <td>11.17</td>\n      <td>11.17</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>134.00</td>\n      <td>9.55</td>\n      <td>1.89</td>\n      <td>0.84</td>\n      <td>10.07</td>\n      <td>10.07</td>\n      <td>10.07</td>\n      <td>10.07</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>146.00</td>\n      <td>5.82</td>\n      <td>1.83</td>\n      <td>0.59</td>\n      <td>4.61</td>\n      <td>7.04</td>\n      <td>7.04</td>\n      <td>7.04</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>185.00</td>\n      <td>8.18</td>\n      <td>2.51</td>\n      <td>0.62</td>\n      <td>9.34</td>\n      <td>9.34</td>\n      <td>9.34</td>\n      <td>9.34</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>133.00</td>\n      <td>4.55</td>\n      <td>0.58</td>\n      <td>1.49</td>\n      <td>4.71</td>\n      <td>4.71</td>\n      <td>4.71</td>\n      <td>4.71</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>3.00</td>\n      <td>0.97</td>\n      <td>0.49</td>\n      <td>0.61</td>\n      <td>0.69</td>\n      <td>0.76</td>\n      <td>1.14</td>\n      <td>1.52</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>127.00</td>\n      <td>8.63</td>\n      <td>1.33</td>\n      <td>0.74</td>\n      <td>8.93</td>\n      <td>8.93</td>\n      <td>8.93</td>\n      <td>8.93</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>79.00</td>\n      <td>6.02</td>\n      <td>1.10</td>\n      <td>1.48</td>\n      <td>6.35</td>\n      <td>6.35</td>\n      <td>6.35</td>\n      <td>6.35</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>150.00</td>\n      <td>9.23</td>\n      <td>0.87</td>\n      <td>3.13</td>\n      <td>9.39</td>\n      <td>9.39</td>\n      <td>9.39</td>\n      <td>9.39</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>63.00</td>\n      <td>12.39</td>\n      <td>0.62</td>\n      <td>9.19</td>\n      <td>12.53</td>\n      <td>12.53</td>\n      <td>12.53</td>\n      <td>12.53</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>255.00</td>\n      <td>4.50</td>\n      <td>1.55</td>\n      <td>0.48</td>\n      <td>3.27</td>\n      <td>5.29</td>\n      <td>5.78</td>\n      <td>5.78</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>16.00</td>\n      <td>6.20</td>\n      <td>0.00</td>\n      <td>6.20</td>\n      <td>6.20</td>\n      <td>6.20</td>\n      <td>6.20</td>\n      <td>6.20</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>96.00</td>\n      <td>9.22</td>\n      <td>1.78</td>\n      <td>0.81</td>\n      <td>9.66</td>\n      <td>9.66</td>\n      <td>9.66</td>\n      <td>9.66</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>138.00</td>\n      <td>9.36</td>\n      <td>2.12</td>\n      <td>0.68</td>\n      <td>10.17</td>\n      <td>10.17</td>\n      <td>10.17</td>\n      <td>10.17</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>121.00</td>\n      <td>4.73</td>\n      <td>0.81</td>\n      <td>1.17</td>\n      <td>5.03</td>\n      <td>5.03</td>\n      <td>5.03</td>\n      <td>5.03</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>98.00</td>\n      <td>9.87</td>\n      <td>1.37</td>\n      <td>0.85</td>\n      <td>10.15</td>\n      <td>10.15</td>\n      <td>10.15</td>\n      <td>10.15</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>260.00</td>\n      <td>4.82</td>\n      <td>1.70</td>\n      <td>0.93</td>\n      <td>3.52</td>\n      <td>6.11</td>\n      <td>6.21</td>\n      <td>6.21</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>152.00</td>\n      <td>11.60</td>\n      <td>1.95</td>\n      <td>0.81</td>\n      <td>12.11</td>\n      <td>12.11</td>\n      <td>12.11</td>\n      <td>12.11</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>57.00</td>\n      <td>6.84</td>\n      <td>0.00</td>\n      <td>6.84</td>\n      <td>6.84</td>\n      <td>6.84</td>\n      <td>6.84</td>\n      <td>6.84</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>88.00</td>\n      <td>11.06</td>\n      <td>1.92</td>\n      <td>0.76</td>\n      <td>11.42</td>\n      <td>11.42</td>\n      <td>11.42</td>\n      <td>11.42</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>152.00</td>\n      <td>5.48</td>\n      <td>1.11</td>\n      <td>1.00</td>\n      <td>5.76</td>\n      <td>5.99</td>\n      <td>5.99</td>\n      <td>5.99</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nlead_proposal_2.groupby(data.publisher_id).min().plot.bar(figsize=[10,5])\n```\n\nThat looks about right, as long as the smaller publishers were closer to zero. So let's apply feature scaling to this, to give a number between 1 and 20. (Anything not as lead will pass though as zero.)\n\n\n```python\ndef rescale(series):\n    return (series - series.min()) / (series.max() - series.min())\n\nlead_proposal_3 = np.ceil(20 * rescale(lead_proposal_2))\n```\n\n\n```python\nlead_proposal_2.min(), lead_proposal_2.max()\n```\n\n\n\n\n    (0.4812571144098754, 13.145359968846892)\n\n\n\n\n```python\nlead_proposal_3.plot.hist()\n```\n\n\n```python\nlead_proposal_3.groupby(data.publisher_id).median().plot.bar(figsize=[10,5])\n```\n\n\n```python\ndata[\"lead_score\"] = pd.concat([lead_proposal_3, data.mins_as_lead[data.mins_as_lead==0]])\n```\n\n\n```python\ndata.lead_score.value_counts().sort_index()\n```\n\n\n\n\n    0.00     134348\n    1.00         46\n    2.00         50\n    3.00         60\n    4.00         73\n    5.00         64\n    6.00         78\n    7.00        216\n    8.00        194\n    9.00        272\n    10.00       234\n    11.00       164\n    12.00        67\n    13.00       278\n    14.00       276\n    15.00       241\n    16.00       336\n    17.00       265\n    18.00       226\n    19.00       437\n    20.00       350\n    Name: lead_score, dtype: int64\n\n\n\n\n```python\ndata.lead_score.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    8.00\n    bbc_co_uk                          20.00\n    breitbart_com                      13.00\n    brexitcentral_com                   7.00\n    buzzfeed_com                       19.00\n    cnn_com                            20.00\n    dailymail_co_uk                    18.00\n    economist_com                      12.00\n    evolvepolitics_com                  0.00\n    foxnews_com                        17.00\n    ft_com                             13.00\n    huffingtonpost_com                 17.00\n    independent_co_uk                  16.00\n    indy100_com                        11.00\n    lemonde_fr                         14.00\n    libdemvoice_org                     7.00\n    mirror_co_uk                        2.00\n    nbcnews_com                        14.00\n    newstatesman_com                   10.00\n    npr_org                            15.00\n    nytimes_com                        20.00\n    order-order_com                     9.00\n    propublica_org                     10.00\n    reuters_com                        15.00\n    rt_com                             16.00\n    skwawkbox_org                       8.00\n    telegraph_co_uk                    16.00\n    thecanary_co                       10.00\n    theguardian_com                    19.00\n    thetimes_co_uk                     11.00\n    washingtonpost_com                 18.00\n    westmonster_com                     0.00\n    yournewswire_com                    9.00\n    Name: lead_score, dtype: float64\n\n\n\nIn summary then, score for article $a$ is:\n\n\n$$\nunscaledLeadScore_a = \\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)}\\\\\nleadScore_a = 19 \\cdot \n\\frac{unscaledLeadScore_a - \\min(unscaledLeadScore)}\n{\\max(unscaledLeadScore) - \\min(unscaledLeadScore)} \n+ 1\n$$\n\nSince the minium value of $minsAsLead$ is 1, $\\min(unscaledLeadScore)$ is pretty insignificant. So we can simplify this to:\n\n$$\nleadScore_a = 20 \\cdot \n\\frac{unscaledLeadScore_a }\n     {\\max(unscaledLeadScore)} \n$$\n\nor: \n\n$$\nleadScore_a = 20 \\cdot \n\\frac{\\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)} }\n     {\\frac{60}{\\log(\\max(alexaRank))}} \n$$\n\n$$\nleadScore_a = \\left( 20 \\cdot \n\\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)} \\cdot\n     {\\frac{\\log(\\max(alexaRank))}{60}} \\right)\n$$\n\n## Time on front score (15 points)\n\nThis is similar to time as lead, so lets try doing the same calculation, except we also want to factor in the number of slots on the front:\n\n\n$$frontScore_a = \n15 \n\\left(\\frac{\\min(minsOnFront_a, 1440)}{alexaRank_a \\cdot numArticlesOnFront_a}\\right) \n\\left( \\frac{\\min(alexaRank \\cdot numArticlesOnFront)}{1440} \\right)$$\n\n\n```python\n(data.alexa_rank * data.num_articles_on_front).min() / 1440\n```\n\n\n\n\n    2.4500000000000002\n\n\n\n\n```python\ntime_on_front_proposal_1 = np.ceil(data.mins_on_front.clip_upper(1440) / (data.alexa_rank * data.num_articles_on_front) * (2.45) * 15)\n```\n\n\n```python\ntime_on_front_proposal_1.plot.hist(figsize=(15, 7), bins=15)\n```\n\n\n```python\ntime_on_front_proposal_1.value_counts().sort_index()\n```\n\n\n\n\n    1.00     69443\n    2.00      6888\n    3.00      4403\n    4.00      4357\n    5.00       843\n    6.00       606\n    7.00       537\n    8.00       443\n    9.00       876\n    10.00      323\n    11.00      372\n    12.00      145\n    13.00       39\n    14.00       27\n    15.00        9\n    dtype: int64\n\n\n\n\n```python\ntime_on_front_proposal_1.groupby(data.publisher_id).sum()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk      37.00\n    bbc_co_uk                          13580.00\n    breitbart_com                       2494.00\n    brexitcentral_com                     42.00\n    buzzfeed_com                        8720.00\n    cnn_com                            12377.00\n    dailymail_co_uk                    14392.00\n    economist_com                        244.00\n    evolvepolitics_com                    61.00\n    foxnews_com                         6264.00\n    ft_com                              2983.00\n    huffingtonpost_com                  7806.00\n    independent_co_uk                   3799.00\n    indy100_com                          392.00\n    lemonde_fr                          3645.00\n    libdemvoice_org                      140.00\n    mirror_co_uk                        8722.00\n    nbcnews_com                         1659.00\n    newstatesman_com                     432.00\n    npr_org                             2754.00\n    nytimes_com                         9206.00\n    order-order_com                      257.00\n    propublica_org                        50.00\n    reuters_com                         7125.00\n    rt_com                              4641.00\n    skwawkbox_org                        121.00\n    telegraph_co_uk                     4279.00\n    thecanary_co                         274.00\n    theguardian_com                    11959.00\n    thetimes_co_uk                      8866.00\n    washingtonpost_com                  8982.00\n    westmonster_com                      287.00\n    yournewswire_com                     386.00\n    dtype: float64\n\n\n\nThat looks good to me.\n\n\n```python\ndata[\"front_score\"] = np.ceil(data.mins_on_front.clip_upper(1440) / (data.alexa_rank * data.num_articles_on_front) * (2.45) * 15).fillna(0)\n```\n\n\n```python\ndata.front_score \n```\n\n\n\n\n    id\n    eb8e9bb4465037557f2b72a02463ef2240048a0a   1.00\n    58f51d1d8e99d7c9909b84201706b10411632331   1.00\n    0b1a1a27c7e6f3aff21586ae2d447b4f1944e597   1.00\n    3f9169b7e2d845613721fe006eba63b9bd8f6ffb   1.00\n    2a743b32a30e803f38b966ef27e1cbf9f5ccd7ba   0.00\n    1ebabeaa2db7cc62305cae75986d6d108165c7f2   1.00\n    772fc50f1134a566dc5e001423994070b8c58a93   1.00\n    4a7806d2ce55afcb6faf9b968afddf9081e6fc3b   1.00\n    14f2c2f6943742da6e4b3bd6e55c540f84d14f89   1.00\n    731c40614f7299ff148188cb4935ac42f78504e2   1.00\n    9630301c907b8df80e414e6cf4b91db234fd49e8   1.00\n    164ebf483c3d37fce9663e48bc38a6d8f193c948   1.00\n    0aa736272acb499eb78d5ef0f82e95c4e1306e66   1.00\n    408e7e5138bfe286f3a3ace50e288b73ec7d70e8   1.00\n    f975e668a58e5dd418b2d27115bf355b0e2c8f26   1.00\n    d624b8ac09af1d50be8fbc87b7a3ef344cdf94fb   1.00\n    8092f3fbd0b033689e9d2d6c435d9b7018d54ed5   1.00\n    e5bb231bb892da4e3b4d949897fcbc97d2265a93   1.00\n    af3f789eacbc6f448f7c3d4406e6ee44b7b0b2b4   1.00\n    d75b82fea9ec27dc8b4b7dbb822c213270b6e22f   1.00\n    e8898b366e9e8cead7377d91ea84142845b8c411   1.00\n    2b0e0562b22b3dbc89a555d4255e9c0d50cfbc7a   1.00\n    84c47ecb160d6eb722b3d9a676172a83c83e64c1   1.00\n    0f6160fa161885292958f8939319b06e96eb27f6   1.00\n    b656446d299b94eef2d9a520cbbd7f5c03242b66   0.00\n    174bff4b69cf24f94f8ffef87f3bce022a799d26   1.00\n    ce462dd900e5b9112e3e504939c9e85fca009759   1.00\n    82370cce427a53970d07ea97961cc8bd83df2bce   0.00\n    a89da1db2fceae2c0172f6b9943d11f8f1807ec3   7.00\n    c141350d3c336f0b1575c3902072a8daea26c4e2   1.00\n                                               ... \n    2646b9fb92e1507df71cd22ba19522bf4c0ddd51   0.00\n    4c179dcf62c5162ac662580e0a4021d7bd49ecf1   0.00\n    2ac60e5ac1a705ef696ffa7b13061db9e8c53de2   1.00\n    573aaeb31b9bc173835c20abb30b6a7bac16b6fe   1.00\n    19cffd6ccddfa7c0a84d15002f8a2b68f57fcec2   1.00\n    f458dd8bbe2486580f244aee5d505ecc683c2170   3.00\n    7fc403dc2a7605e0435326b7d52f45771e3f9401   0.00\n    e4b21080e26a3f50b17984ad19baf8449e598d63   1.00\n    ba12871d0bf8d8f0ffdb8a9726999cf6400aa1f0   1.00\n    b8e032c9aee9e4128325e1da3569e41fea9f1d46   1.00\n    749a5ac507b521df52a24d39fadb11edb16bc3d6   3.00\n    3f95cc42dc55f01fa4c9d6022f0e6ea5ae21dd71   1.00\n    1ea319842636cc047ef3558d643892a482b4fe2e   0.00\n    07408efb98ea300ac74c1239aad537ad045e5833   1.00\n    acc344aea665093d76a2e41e26e4f5aaf6e1b9cb   7.00\n    ceac8ec3c65784c78710353bc4b045db1261fa40   0.00\n    fa23176a6667a466654205a8b2d6eeea1147a8c7   0.00\n    5d8703f945464f3cf37e8c3a90bd93baf49abdfc   0.00\n    6ca69dc36f67723d91c5c02a4926569799c48db2   8.00\n    f0e0390e80c6d660b0e371e7b73e5176f3406787   1.00\n    16d3197f7e2389632ae6d43705157ee50d65831d   1.00\n    ab951d17a3ffd353feb36859793a91d81140324c   0.00\n    ab0fb3586222b04d4dcd9c979142a4160b87efc0   1.00\n    a425d96edc27f152fb8252a26a7e19c9348f893f   0.00\n    727a72fa4cbb7f2fb531daf2a7889345285d656e   1.00\n    7533597b2e527be93f8b07d724faa489a0744cb0   1.00\n    dcf4cb3ce9b1f599a3ccc0d7be469b4c6b363aae   0.00\n    a0e6141f0661e04d65e5927da5fa4529423acd85   0.00\n    d1d89005f667d2f9e8ac41934cb04ade769c9678   2.00\n    8f46bb9e8b6cb89255338a22bdb50ab22604e87d   1.00\n    Name: front_score, Length: 138275, dtype: float64\n\n\n\n## Facebook brand page promotion (15 points)\n\nOne way a publisher has of promoting content is to post to their brand page. The significance of doing so is stronger when the brand page has more followers (likes).\n\n$$ facebookPromotionProposed1_a = 15 \\left( \\frac {brandPageLikes_a} {\\max(brandPageLikes)} \\right) $$\n\nNow lets explore the data to see if that makes sense. **tr;dr the formula above is incorrect**\n\n\n```python\ndata.fb_brand_page_likes.max()\n```\n\n\n\n\n    46496164.0\n\n\n\n\n```python\nfacebook_promotion_proposed_1 = np.ceil((15 * (data.fb_brand_page_likes / data.fb_brand_page_likes.max())).fillna(0))\n```\n\n\n```python\nfacebook_promotion_proposed_1.value_counts().sort_index().plot.bar()\n```\n\n\n```python\nfacebook_promotion_proposed_1.groupby(data.publisher_id).describe()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>25%</th>\n      <th>50%</th>\n      <th>75%</th>\n      <th>max</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>37.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>12059.00</td>\n      <td>0.47</td>\n      <td>2.62</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>15.00</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>2589.00</td>\n      <td>0.79</td>\n      <td>0.98</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>42.00</td>\n      <td>0.95</td>\n      <td>0.22</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>1290.00</td>\n      <td>0.55</td>\n      <td>0.50</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>3996.00</td>\n      <td>2.61</td>\n      <td>4.39</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>10.00</td>\n      <td>10.00</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>24494.00</td>\n      <td>0.63</td>\n      <td>1.66</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>5.00</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>504.00</td>\n      <td>2.24</td>\n      <td>1.30</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>evolvepolitics_com</th>\n      <td>65.00</td>\n      <td>0.94</td>\n      <td>0.24</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>5009.00</td>\n      <td>0.82</td>\n      <td>2.06</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>6.00</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>4416.00</td>\n      <td>0.49</td>\n      <td>0.86</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>2250.00</td>\n      <td>1.96</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>5290.00</td>\n      <td>0.82</td>\n      <td>1.34</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>395.00</td>\n      <td>0.91</td>\n      <td>0.29</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>3649.00</td>\n      <td>0.75</td>\n      <td>0.97</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>141.00</td>\n      <td>0.93</td>\n      <td>0.26</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>9204.00</td>\n      <td>0.25</td>\n      <td>0.43</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.25</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>1878.00</td>\n      <td>2.53</td>\n      <td>1.93</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>439.00</td>\n      <td>0.78</td>\n      <td>0.42</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>1824.00</td>\n      <td>1.57</td>\n      <td>1.50</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>4627.00</td>\n      <td>1.81</td>\n      <td>2.67</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>5.00</td>\n      <td>6.00</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>257.00</td>\n      <td>0.88</td>\n      <td>0.32</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>51.00</td>\n      <td>0.88</td>\n      <td>0.33</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>6179.00</td>\n      <td>0.64</td>\n      <td>0.93</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>2302.00</td>\n      <td>1.28</td>\n      <td>0.96</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>121.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>6009.00</td>\n      <td>0.40</td>\n      <td>0.80</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>276.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>7989.00</td>\n      <td>0.54</td>\n      <td>1.15</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>8887.00</td>\n      <td>0.05</td>\n      <td>0.22</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>21307.00</td>\n      <td>0.11</td>\n      <td>0.45</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>302.00</td>\n      <td>0.31</td>\n      <td>0.46</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>397.00</td>\n      <td>0.25</td>\n      <td>0.44</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThat's too much variation: sites like the Guardian, which have a respectable 7.5m likes, should not be scoring a 3. Lets try applying a log to it, and then standard feature scaling again.\n\n\n```python\ndata.fb_brand_page_likes.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk     334841.00\n    bbc_co_uk                          46496164.00\n    breitbart_com                       3866566.00\n    brexitcentral_com                     16895.00\n    buzzfeed_com                        2941222.00\n    cnn_com                            30207108.00\n    dailymail_co_uk                    14628916.00\n    economist_com                       8541804.00\n    evolvepolitics_com                   128802.00\n    foxnews_com                        16366386.00\n    ft_com                              3777860.00\n    huffingtonpost_com                  9872554.00\n    independent_co_uk                   8182856.00\n    indy100_com                          243768.00\n    lemonde_fr                          4140995.00\n    libdemvoice_org                        8631.00\n    mirror_co_uk                        2993874.00\n    nbcnews_com                         9705196.00\n    newstatesman_com                     154289.00\n    npr_org                             6312422.00\n    nytimes_com                        15597020.00\n    order-order_com                       45695.00\n    propublica_org                       379263.00\n    reuters_com                         4011707.00\n    rt_com                              5093479.00\n    skwawkbox_org                          8235.00\n    telegraph_co_uk                     4425088.00\n    thecanary_co                               nan\n    theguardian_com                     7949540.00\n    thetimes_co_uk                       778877.00\n    washingtonpost_com                  6161035.00\n    westmonster_com                       20335.00\n    yournewswire_com                      28501.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\nnp.log(2149)\n```\n\n\n\n\n    7.6727578966425103\n\n\n\n\n```python\nnp.log(data.fb_brand_page_likes.groupby(data.publisher_id).max())\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk   12.72\n    bbc_co_uk                          17.65\n    breitbart_com                      15.17\n    brexitcentral_com                   9.73\n    buzzfeed_com                       14.89\n    cnn_com                            17.22\n    dailymail_co_uk                    16.50\n    economist_com                      15.96\n    evolvepolitics_com                 11.77\n    foxnews_com                        16.61\n    ft_com                             15.14\n    huffingtonpost_com                 16.11\n    independent_co_uk                  15.92\n    indy100_com                        12.40\n    lemonde_fr                         15.24\n    libdemvoice_org                     9.06\n    mirror_co_uk                       14.91\n    nbcnews_com                        16.09\n    newstatesman_com                   11.95\n    npr_org                            15.66\n    nytimes_com                        16.56\n    order-order_com                    10.73\n    propublica_org                     12.85\n    reuters_com                        15.20\n    rt_com                             15.44\n    skwawkbox_org                       9.02\n    telegraph_co_uk                    15.30\n    thecanary_co                         nan\n    theguardian_com                    15.89\n    thetimes_co_uk                     13.57\n    washingtonpost_com                 15.63\n    westmonster_com                     9.92\n    yournewswire_com                   10.26\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\nThat's more like it, but the lower numbers should be smaller.\n\n\n```python\nnp.log(data.fb_brand_page_likes.groupby(data.publisher_id).max() / 1000)\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    5.81\n    bbc_co_uk                          10.75\n    breitbart_com                       8.26\n    brexitcentral_com                   2.83\n    buzzfeed_com                        7.99\n    cnn_com                            10.32\n    dailymail_co_uk                     9.59\n    economist_com                       9.05\n    evolvepolitics_com                  4.86\n    foxnews_com                         9.70\n    ft_com                              8.24\n    huffingtonpost_com                  9.20\n    independent_co_uk                   9.01\n    indy100_com                         5.50\n    lemonde_fr                          8.33\n    libdemvoice_org                     2.16\n    mirror_co_uk                        8.00\n    nbcnews_com                         9.18\n    newstatesman_com                    5.04\n    npr_org                             8.75\n    nytimes_com                         9.65\n    order-order_com                     3.82\n    propublica_org                      5.94\n    reuters_com                         8.30\n    rt_com                              8.54\n    skwawkbox_org                       2.11\n    telegraph_co_uk                     8.40\n    thecanary_co                         nan\n    theguardian_com                     8.98\n    thetimes_co_uk                      6.66\n    washingtonpost_com                  8.73\n    westmonster_com                     3.01\n    yournewswire_com                    3.35\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\nscaled_fb_brand_page_likes = (data.fb_brand_page_likes / 1000)\nfacebook_promotion_proposed_2 = np.ceil(\\\n    (15 * \\\n     (np.log(scaled_fb_brand_page_likes) / np.log(scaled_fb_brand_page_likes.max()))\\\n    )\\\n                                       ).fillna(0)\n```\n\n\n```python\nfacebook_promotion_proposed_2.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    9.00\n    bbc_co_uk                          15.00\n    breitbart_com                      12.00\n    brexitcentral_com                   4.00\n    buzzfeed_com                       12.00\n    cnn_com                            15.00\n    dailymail_co_uk                    14.00\n    economist_com                      13.00\n    evolvepolitics_com                  7.00\n    foxnews_com                        14.00\n    ft_com                             12.00\n    huffingtonpost_com                 13.00\n    independent_co_uk                  13.00\n    indy100_com                         8.00\n    lemonde_fr                         12.00\n    libdemvoice_org                     4.00\n    mirror_co_uk                       12.00\n    nbcnews_com                        13.00\n    newstatesman_com                    8.00\n    npr_org                            13.00\n    nytimes_com                        14.00\n    order-order_com                     6.00\n    propublica_org                      9.00\n    reuters_com                        12.00\n    rt_com                             12.00\n    skwawkbox_org                       3.00\n    telegraph_co_uk                    12.00\n    thecanary_co                        0.00\n    theguardian_com                    13.00\n    thetimes_co_uk                     10.00\n    washingtonpost_com                 13.00\n    westmonster_com                     5.00\n    yournewswire_com                    5.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\nLGTM. So the equation is\n\n\n$$ facebookPromotion_a = 15 \\left( \n\\frac {\\log(\\frac {brandPageLikes_a}{1000})} \n{\\log(\\frac {\\max(brandPageLikes)}{1000}))} \\right) $$\n\n\nNow, let's try applying standard feature scaling approch to this, rather than using a magic number of 1,000. That equation would be:\n\n\\begin{align}\nunscaledFacebookPromotion_a &= \n   \\log(brandPageLikes_a) \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{unscaledFacebookPromotion_a - \\min(unscaledFacebookPromotion)}{\\max(unscaledFacebookPromotion) - \\min(unscaledFacebookPromotion)}  \\\\\n\\\\\n\\text{The scaling can be simplified to:} \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{unscaledFacebookPromotion_a - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))}  \\\\\n\\\\\n\\text{Meaning the overall equation becomes:} \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{\\log(brandPageLikes_a) - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))} \n   \\end{align}\n\n\n\n```python\nfacebook_promotion_proposed_3 = np.ceil(\n    (14 * \n     ( \n         (np.log(data.fb_brand_page_likes) - np.log(data.fb_brand_page_likes.min()) ) /\n         (np.log(data.fb_brand_page_likes.max()) - np.log(data.fb_brand_page_likes.min()))\n     )\n    ) + 1\n                                       )\n```\n\n\n```python\nfacebook_promotion_proposed_3.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    8.00\n    bbc_co_uk                          15.00\n    breitbart_com                      11.00\n    brexitcentral_com                   3.00\n    buzzfeed_com                       11.00\n    cnn_com                            15.00\n    dailymail_co_uk                    14.00\n    economist_com                      13.00\n    evolvepolitics_com                  6.00\n    foxnews_com                        14.00\n    ft_com                             11.00\n    huffingtonpost_com                 13.00\n    independent_co_uk                  13.00\n    indy100_com                         7.00\n    lemonde_fr                         12.00\n    libdemvoice_org                     2.00\n    mirror_co_uk                       11.00\n    nbcnews_com                        13.00\n    newstatesman_com                    6.00\n    npr_org                            12.00\n    nytimes_com                        14.00\n    order-order_com                     4.00\n    propublica_org                      8.00\n    reuters_com                        12.00\n    rt_com                             12.00\n    skwawkbox_org                       2.00\n    telegraph_co_uk                    12.00\n    thecanary_co                         nan\n    theguardian_com                    13.00\n    thetimes_co_uk                      9.00\n    washingtonpost_com                 12.00\n    westmonster_com                     3.00\n    yournewswire_com                    4.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\ndata[\"facebook_promotion_score\"] = facebook_promotion_proposed_3.fillna(0.0)\n```\n\n# Review\n\n\n```python\ndata[\"promotion_score\"] = (data.lead_score + data.front_score + data.facebook_promotion_score)\ndata[\"attention_index\"] = (data.promotion_score + data.response_score)\n```\n\n\n```python\ndata.promotion_score.plot.hist(bins=np.arange(50), figsize=(15,6))\n```\n\n\n```python\ndata.attention_index.plot.hist(bins=np.arange(100), figsize=(15,6))\n```\n\n\n```python\ndata.attention_index.value_counts().sort_index()\n```\n\n\n\n\n    0.00     20053\n    1.00     18335\n    2.00     11291\n    3.00      8327\n    4.00      6147\n    5.00      4740\n    6.00      4091\n    7.00      3663\n    8.00      3196\n    9.00      2938\n    10.00     2605\n    11.00     2492\n    12.00     2324\n    13.00     2214\n    14.00     2021\n    15.00     2035\n    16.00     1897\n    17.00     1768\n    18.00     1725\n    19.00     1655\n    20.00     1595\n    21.00     1494\n    22.00     1574\n    23.00     1476\n    24.00     1451\n    25.00     1352\n    26.00     1344\n    27.00     1254\n    28.00     1272\n    29.00     1218\n             ...  \n    66.00      100\n    67.00       56\n    68.00       70\n    69.00       60\n    70.00       52\n    71.00       49\n    72.00       56\n    73.00       36\n    74.00       41\n    75.00       32\n    76.00       19\n    77.00       34\n    78.00       29\n    79.00       30\n    80.00       20\n    81.00       28\n    82.00       17\n    83.00       21\n    84.00       19\n    85.00        9\n    86.00       10\n    87.00       10\n    88.00       10\n    89.00        7\n    90.00        4\n    91.00        5\n    92.00        3\n    93.00        3\n    94.00        3\n    97.00        1\n    Name: attention_index, Length: 96, dtype: int64\n\n\n\n\n```python\n# and lets see the articles with the biggest attention index\ndata.sort_values(\"attention_index\", ascending=False)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>8fc308aeac5b6b75c0baae4d5becdaa91a489988</th>\n      <td>http://www.bbc.co.uk/news/world-europe-43841194</td>\n      <td>Swedish DJ Avicii dies at 28</td>\n      <td>2018-04-20 17:43:12.450</td>\n      <td>2018-04-20 17:42:04</td>\n      <td>355685</td>\n      <td>2261.13</td>\n      <td>2018-04-20T18:05:11.938Z</td>\n      <td>48245</td>\n      <td>233667</td>\n      <td>73773</td>\n      <td>...</td>\n      <td>46410824.00</td>\n      <td>2018-04-20T18:42:14.000Z</td>\n      <td>96</td>\n      <td>119.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>12.00</td>\n      <td>15.00</td>\n      <td>47.00</td>\n      <td>97.00</td>\n    </tr>\n    <tr>\n      <th>2a08dfaff24d92a3788b4ddb85bcbecec66c975f</th>\n      <td>https://www.cnn.com/2018/04/21/entertainment/v...</td>\n      <td>Verne Troyer, 'Mini-Me' in Austin Powers films...</td>\n      <td>2018-04-21 20:58:12.888</td>\n      <td>2018-04-21 20:52:09</td>\n      <td>134799</td>\n      <td>595.71</td>\n      <td>2018-04-21T21:20:07.393Z</td>\n      <td>12457</td>\n      <td>91067</td>\n      <td>31275</td>\n      <td>...</td>\n      <td>30053099.00</td>\n      <td>2018-04-21T21:10:35.000Z</td>\n      <td>105</td>\n      <td>151.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>f42e1b7e147355839db1cca071667c4dfcde1fbc</th>\n      <td>http://www.bbc.co.uk/news/uk-43933056</td>\n      <td>Legal battle toddler Alfie Evans dies</td>\n      <td>2018-04-28 06:04:26.131</td>\n      <td>2018-04-28 06:02:47</td>\n      <td>140579</td>\n      <td>3930.28</td>\n      <td>2018-04-28T09:06:06.565Z</td>\n      <td>21382</td>\n      <td>106308</td>\n      <td>12889</td>\n      <td>...</td>\n      <td>46476225.00</td>\n      <td>2018-04-28T06:37:18.000Z</td>\n      <td>96</td>\n      <td>66.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>4bfcac581b66efe4cd843c30d0fa748fff2c47c6</th>\n      <td>https://www.cnn.com/2018/04/22/us/waffle-house...</td>\n      <td>Hero prevented further bloodshed at Tennessee ...</td>\n      <td>2018-04-22 14:10:19.077</td>\n      <td>2018-04-22 14:05:18</td>\n      <td>178909</td>\n      <td>138.33</td>\n      <td>2018-04-22T22:50:11.682Z</td>\n      <td>21312</td>\n      <td>137121</td>\n      <td>20476</td>\n      <td>...</td>\n      <td>30054437.00</td>\n      <td>2018-04-22T16:30:09.000Z</td>\n      <td>105</td>\n      <td>195.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>8145abc78ad81e5f5cc7f88a8b41c26b85becc37</th>\n      <td>https://www.cnn.com/2018/04/17/politics/barbar...</td>\n      <td>Barbara Bush, former first lady, dies at 92</td>\n      <td>2018-04-17 23:49:24.539</td>\n      <td>2018-04-17 23:45:19</td>\n      <td>348473</td>\n      <td>1649.76</td>\n      <td>2018-04-18T01:05:10.294Z</td>\n      <td>37209</td>\n      <td>277520</td>\n      <td>33744</td>\n      <td>...</td>\n      <td>30040473.00</td>\n      <td>2018-04-17T23:49:02.000Z</td>\n      <td>105</td>\n      <td>26.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>7b9b3d5c8ee0581d1fda95ad1f2cbe7c3e4fda2b</th>\n      <td>http://www.bbc.co.uk/news/world-middle-east-43...</td>\n      <td>US allies launch strikes on Syria chemical sites</td>\n      <td>2018-04-14 01:10:11.543</td>\n      <td>2018-04-14 01:08:58</td>\n      <td>168448</td>\n      <td>466.39</td>\n      <td>2018-04-14T07:43:14.177Z</td>\n      <td>49569</td>\n      <td>94543</td>\n      <td>24336</td>\n      <td>...</td>\n      <td>46369696.00</td>\n      <td>2018-04-14T07:29:14.000Z</td>\n      <td>96</td>\n      <td>67.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>0847758466cc97ab4bdb7cebc75668dd3fcbae44</th>\n      <td>https://www.cnn.com/2018/04/16/politics/michae...</td>\n      <td>Michael Cohen reveals client list ahead of hea...</td>\n      <td>2018-04-16 15:25:20.997</td>\n      <td>2018-04-16 15:22:19</td>\n      <td>128047</td>\n      <td>5411.53</td>\n      <td>2018-04-16T21:04:20.495Z</td>\n      <td>36278</td>\n      <td>78404</td>\n      <td>13365</td>\n      <td>...</td>\n      <td>30034998.00</td>\n      <td>2018-04-16T19:16:02.000Z</td>\n      <td>105</td>\n      <td>592.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>7664a38d1979ec11da8cee1213834830cabec0c2</th>\n      <td>https://www.cnn.com/2018/04/23/politics/george...</td>\n      <td>Former President George H.W. Bush in intensive...</td>\n      <td>2018-04-23 22:49:18.709</td>\n      <td>2018-04-23 22:45:50</td>\n      <td>488393</td>\n      <td>1739.91</td>\n      <td>2018-04-23T23:11:09.019Z</td>\n      <td>98937</td>\n      <td>343905</td>\n      <td>45551</td>\n      <td>...</td>\n      <td>30060241.00</td>\n      <td>2018-04-23T22:51:47.000Z</td>\n      <td>105</td>\n      <td>20.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>5e638ea0ab5dfab129588fc29658028ca6e4c086</th>\n      <td>https://www.cnn.com/2018/04/02/politics/trump-...</td>\n      <td>Trump says 'our country is being stolen' due t...</td>\n      <td>2018-04-02 11:55:17.513</td>\n      <td>2018-04-02 11:48:33</td>\n      <td>119509</td>\n      <td>145.19</td>\n      <td>2018-04-02T12:49:14.831Z</td>\n      <td>31414</td>\n      <td>73469</td>\n      <td>14626</td>\n      <td>...</td>\n      <td>29924986.00</td>\n      <td>2018-04-02T12:35:09.000Z</td>\n      <td>105</td>\n      <td>252.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>bd0987ad82d9fa682846f43a66035d5ee412550d</th>\n      <td>http://www.bbc.co.uk/news/world-europe-43683687</td>\n      <td>Van drives into pedestrians in Germany</td>\n      <td>2018-04-07 14:46:14.949</td>\n      <td>2018-04-07 14:43:38</td>\n      <td>65118</td>\n      <td>455.28</td>\n      <td>2018-04-07T15:08:06.644Z</td>\n      <td>11506</td>\n      <td>42716</td>\n      <td>10896</td>\n      <td>...</td>\n      <td>46300901.00</td>\n      <td>2018-04-07T15:00:54.000Z</td>\n      <td>96</td>\n      <td>63.00</td>\n      <td>47.00</td>\n      <td>20.00</td>\n      <td>10.00</td>\n      <td>15.00</td>\n      <td>45.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>b9d308491d3ca84f74d821e854fe8fb426257956</th>\n      <td>https://www.cnn.com/2018/04/07/americas/canada...</td>\n      <td>Multiple deaths reported in crash involving Ca...</td>\n      <td>2018-04-07 06:55:14.007</td>\n      <td>2018-04-07 06:51:18</td>\n      <td>106273</td>\n      <td>268.64</td>\n      <td>2018-04-07T18:01:11.959Z</td>\n      <td>14999</td>\n      <td>80856</td>\n      <td>10418</td>\n      <td>...</td>\n      <td>29939419.00</td>\n      <td>2018-04-07T17:49:03.000Z</td>\n      <td>105</td>\n      <td>165.00</td>\n      <td>49.00</td>\n      <td>18.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>adcef7a8ae7abc514986679dfa03c9f4947e2ec2</th>\n      <td>http://www.bbc.co.uk/news/uk-politics-43944988</td>\n      <td>Amber Rudd resigns as home secretary</td>\n      <td>2018-04-29 21:07:14.462</td>\n      <td>2018-04-29 21:04:39</td>\n      <td>129951</td>\n      <td>1288.21</td>\n      <td>2018-04-29T21:19:09.751Z</td>\n      <td>31021</td>\n      <td>82656</td>\n      <td>16274</td>\n      <td>...</td>\n      <td>46486435.00</td>\n      <td>2018-04-29T21:09:43.000Z</td>\n      <td>96</td>\n      <td>57.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>9e8412abedfd92ea5e87329a1b658037c50846c8</th>\n      <td>http://www.bbc.co.uk/news/world-africa-43621112</td>\n      <td>South Africa's Winnie Mandela dies at 81</td>\n      <td>2018-04-02 14:07:10.496</td>\n      <td>2018-04-02 14:04:43</td>\n      <td>96795</td>\n      <td>382.00</td>\n      <td>2018-04-02T14:19:13.732Z</td>\n      <td>12601</td>\n      <td>68162</td>\n      <td>16032</td>\n      <td>...</td>\n      <td>46265981.00</td>\n      <td>2018-04-02T14:07:59.000Z</td>\n      <td>96</td>\n      <td>63.00</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>6777aba349821201bf84afc471fda75754cba9da</th>\n      <td>https://www.cnn.com/2018/04/25/us/golden-state...</td>\n      <td>Golden State Killer: Authorities to announce a...</td>\n      <td>2018-04-25 15:40:16.853</td>\n      <td>2018-04-25 15:38:11</td>\n      <td>93358</td>\n      <td>145.91</td>\n      <td>2018-04-25T18:04:12.614Z</td>\n      <td>20897</td>\n      <td>57937</td>\n      <td>14524</td>\n      <td>...</td>\n      <td>30065961.00</td>\n      <td>2018-04-25T17:14:01.000Z</td>\n      <td>105</td>\n      <td>805.00</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>846a6dd6430beec9ca5b072bd748c03641d0949f</th>\n      <td>https://www.cnn.com/2018/04/01/politics/trump-...</td>\n      <td>Trump tweets: 'NO MORE DACA DEAL'</td>\n      <td>2018-04-01 14:31:17.767</td>\n      <td>2018-04-01 14:26:13</td>\n      <td>95196</td>\n      <td>389.45</td>\n      <td>2018-04-01T15:25:12.600Z</td>\n      <td>27537</td>\n      <td>57743</td>\n      <td>9916</td>\n      <td>...</td>\n      <td>29920840.00</td>\n      <td>2018-04-01T15:07:21.000Z</td>\n      <td>105</td>\n      <td>206.00</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>f9602d17fe7442a7f5255e5017f4b564dbc9cf13</th>\n      <td>https://www.cnn.com/2018/04/22/us/tennessee-wa...</td>\n      <td>3 killed at Waffle House in Tennessee</td>\n      <td>2018-04-22 10:49:11.824</td>\n      <td>2018-04-22 10:47:42</td>\n      <td>83475</td>\n      <td>165.92</td>\n      <td>2018-04-22T13:04:11.763Z</td>\n      <td>25384</td>\n      <td>43519</td>\n      <td>14572</td>\n      <td>...</td>\n      <td>30054050.00</td>\n      <td>2018-04-22T11:34:29.000Z</td>\n      <td>105</td>\n      <td>54.00</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>81e11c509e7d040fb81f13783a4bd4f693f9b5f0</th>\n      <td>https://www.cnn.com/2018/04/05/politics/donald...</td>\n      <td>Trump says he didn't know about Stormy Daniels...</td>\n      <td>2018-04-05 21:04:23.035</td>\n      <td>2018-04-05 20:57:57</td>\n      <td>59913</td>\n      <td>210.91</td>\n      <td>2018-04-05T21:27:06.734Z</td>\n      <td>22767</td>\n      <td>32093</td>\n      <td>5053</td>\n      <td>...</td>\n      <td>29936495.00</td>\n      <td>2018-04-05T21:15:04.000Z</td>\n      <td>105</td>\n      <td>128.00</td>\n      <td>46.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>042308324da49129060ee9dc165806b0f5159483</th>\n      <td>https://www.cnn.com/2018/04/13/politics/trump-...</td>\n      <td>Trump to speak on Syria tonight</td>\n      <td>2018-04-14 00:52:16.872</td>\n      <td>2018-04-14 00:47:09</td>\n      <td>209940</td>\n      <td>1151.91</td>\n      <td>2018-04-14T01:24:12.988Z</td>\n      <td>61583</td>\n      <td>110339</td>\n      <td>38018</td>\n      <td>...</td>\n      <td>29991525.00</td>\n      <td>2018-04-14T01:09:52.000Z</td>\n      <td>105</td>\n      <td>62.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>5.00</td>\n      <td>15.00</td>\n      <td>40.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>10ffadc59e881959a8dd491ac60eeb5c78017c31</th>\n      <td>https://www.cnn.com/2018/04/18/politics/donald...</td>\n      <td>Trump blasts 'breeding' in sanctuary cities. T...</td>\n      <td>2018-04-18 15:40:21.812</td>\n      <td>2018-04-18 15:32:53</td>\n      <td>103393</td>\n      <td>267.80</td>\n      <td>2018-04-20T03:05:08.025Z</td>\n      <td>26070</td>\n      <td>65348</td>\n      <td>11975</td>\n      <td>...</td>\n      <td>30042648.00</td>\n      <td>2018-04-18T18:02:06.000Z</td>\n      <td>105</td>\n      <td>766.00</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>a5662ddd2382861e5a9ef5b26932f1b4dcffd630</th>\n      <td>https://www.cnn.com/2018/04/07/us/trump-tower-...</td>\n      <td>Fire at Trump Tower injures one person, says FDNY</td>\n      <td>2018-04-07 23:28:15.603</td>\n      <td>2018-04-07 23:23:02</td>\n      <td>53774</td>\n      <td>123.56</td>\n      <td>2018-04-08T01:11:12.454Z</td>\n      <td>14405</td>\n      <td>27647</td>\n      <td>11722</td>\n      <td>...</td>\n      <td>29939819.00</td>\n      <td>2018-04-07T23:45:03.000Z</td>\n      <td>105</td>\n      <td>53.00</td>\n      <td>45.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>fcc2264ec50e478c1e05c31db2516a4914403fd9</th>\n      <td>http://money.cnn.com/2018/04/16/news/companies...</td>\n      <td>Starbucks CEO calls arrest of black men at sto...</td>\n      <td>2018-04-16 12:44:14.313</td>\n      <td>2018-04-16 12:38:16</td>\n      <td>49696</td>\n      <td>93.81</td>\n      <td>2018-04-16T16:04:13.722Z</td>\n      <td>16433</td>\n      <td>28082</td>\n      <td>5181</td>\n      <td>...</td>\n      <td>30032452.00</td>\n      <td>2018-04-16T13:00:03.000Z</td>\n      <td>105</td>\n      <td>nan</td>\n      <td>45.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>fbddd30d040459755d4aadd9010ad9e96517f7ad</th>\n      <td>https://www.cnn.com/2018/04/23/world/toronto-c...</td>\n      <td>Van strikes multiple pedestrians in Toronto, p...</td>\n      <td>2018-04-23 18:04:19.402</td>\n      <td>2018-04-23 17:59:01</td>\n      <td>126333</td>\n      <td>264.93</td>\n      <td>2018-04-23T19:40:14.774Z</td>\n      <td>23484</td>\n      <td>84584</td>\n      <td>18265</td>\n      <td>...</td>\n      <td>30058323.00</td>\n      <td>2018-04-23T18:11:02.000Z</td>\n      <td>105</td>\n      <td>46.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>4.00</td>\n      <td>15.00</td>\n      <td>39.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>4294fdff174879ab0589bfc53c432e3d115104a5</th>\n      <td>http://www.bbc.co.uk/news/world-asia-india-436...</td>\n      <td>Bollywood star Khan guilty of poaching</td>\n      <td>2018-04-05 06:19:14.755</td>\n      <td>2018-04-05 06:14:36</td>\n      <td>34874</td>\n      <td>56.96</td>\n      <td>2018-04-05T12:15:07.276Z</td>\n      <td>4438</td>\n      <td>28109</td>\n      <td>2327</td>\n      <td>...</td>\n      <td>46279403.00</td>\n      <td>2018-04-05T06:30:08.000Z</td>\n      <td>96</td>\n      <td>65.00</td>\n      <td>43.00</td>\n      <td>20.00</td>\n      <td>11.00</td>\n      <td>15.00</td>\n      <td>46.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>47b0b99715235252b60c2bc5c1de478334be7867</th>\n      <td>https://www.cnn.com/2018/04/29/politics/michel...</td>\n      <td>5 takeaways on Michelle Wolf's hugely controve...</td>\n      <td>2018-04-29 14:16:47.533</td>\n      <td>2018-04-29 14:15:53</td>\n      <td>49809</td>\n      <td>115.91</td>\n      <td>2018-04-29T16:29:08.442Z</td>\n      <td>21092</td>\n      <td>26190</td>\n      <td>2527</td>\n      <td>...</td>\n      <td>30124025.00</td>\n      <td>2018-04-29T15:30:10.000Z</td>\n      <td>105</td>\n      <td>1111.00</td>\n      <td>45.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>4e3362cec33419a17ee9d809178c2b274dcd45d2</th>\n      <td>https://www.cnn.com/2018/04/26/us/bill-cosby-t...</td>\n      <td>Bill Cosby trial: The jury has reached a verdi...</td>\n      <td>2018-04-26 17:52:20.410</td>\n      <td>2018-04-26 17:46:39</td>\n      <td>260387</td>\n      <td>1232.41</td>\n      <td>2018-04-26T19:09:07.571Z</td>\n      <td>75822</td>\n      <td>152598</td>\n      <td>31967</td>\n      <td>...</td>\n      <td>30070171.00</td>\n      <td>2018-04-26T18:02:37.000Z</td>\n      <td>105</td>\n      <td>84.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>4.00</td>\n      <td>15.00</td>\n      <td>39.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>258942f24b6df728b6df3cd609e424c57cfbd661</th>\n      <td>http://money.cnn.com/2018/04/29/news/companies...</td>\n      <td>T-Mobile and Sprint agree to merge, finally</td>\n      <td>2018-04-29 16:39:12.269</td>\n      <td>2018-04-29 16:26:01</td>\n      <td>71353</td>\n      <td>249.97</td>\n      <td>2018-04-29T17:43:10.038Z</td>\n      <td>20059</td>\n      <td>37990</td>\n      <td>13304</td>\n      <td>...</td>\n      <td>30124334.00</td>\n      <td>2018-04-29T17:30:05.000Z</td>\n      <td>105</td>\n      <td>nan</td>\n      <td>47.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>2888e0693674f83fd2b2e34eab57a69175617c9e</th>\n      <td>https://www.nytimes.com/2018/04/27/world/asia/...</td>\n      <td>North and South Korean Leaders Discuss Ending ...</td>\n      <td>2018-04-27 07:46:13.972</td>\n      <td>2018-04-27 07:43:03</td>\n      <td>114526</td>\n      <td>156.47</td>\n      <td>2018-04-27T14:31:05.214Z</td>\n      <td>18540</td>\n      <td>84074</td>\n      <td>11912</td>\n      <td>...</td>\n      <td>15565770.00</td>\n      <td>2018-04-27T08:00:01.000Z</td>\n      <td>120</td>\n      <td>nan</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>4.00</td>\n      <td>14.00</td>\n      <td>38.00</td>\n      <td>88.00</td>\n    </tr>\n    <tr>\n      <th>3c3e190480d1c9c7f6f753fb2b08afbcc5d5ccd3</th>\n      <td>https://www.cnn.com/2018/04/20/politics/democr...</td>\n      <td>Dems file suit alleging Russia, Trump, WikiLea...</td>\n      <td>2018-04-20 15:52:11.889</td>\n      <td>2018-04-20 15:46:16</td>\n      <td>40104</td>\n      <td>127.26</td>\n      <td>2018-04-20T18:40:11.023Z</td>\n      <td>12741</td>\n      <td>21490</td>\n      <td>5873</td>\n      <td>...</td>\n      <td>30049423.00</td>\n      <td>2018-04-20T18:27:02.000Z</td>\n      <td>105</td>\n      <td>152.00</td>\n      <td>44.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>88.00</td>\n    </tr>\n    <tr>\n      <th>e524f53f0c6dd3152719ea965c2ccda50c314ddf</th>\n      <td>https://www.nytimes.com/2018/04/09/us/politics...</td>\n      <td>F.B.I. Raids Office of Trump\u2019s Longtime Lawyer...</td>\n      <td>2018-04-09 19:55:09.840</td>\n      <td>2018-04-09 19:54:08</td>\n      <td>718482</td>\n      <td>10488.43</td>\n      <td>2018-04-10T01:05:16.730Z</td>\n      <td>198533</td>\n      <td>445591</td>\n      <td>74358</td>\n      <td>...</td>\n      <td>15495843.00</td>\n      <td>2018-04-09T20:05:08.000Z</td>\n      <td>120</td>\n      <td>291.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>4.00</td>\n      <td>14.00</td>\n      <td>38.00</td>\n      <td>88.00</td>\n    </tr>\n    <tr>\n      <th>223c62b3f6dfe70425b3c19cdc5ed0072c1a1810</th>\n      <td>https://www.nytimes.com/2018/04/26/arts/televi...</td>\n      <td>Bill Cosby Found Guilty of Sexual Assault Afte...</td>\n      <td>2018-04-26 17:52:13.445</td>\n      <td>2018-04-26 17:51:03</td>\n      <td>369459</td>\n      <td>1265.01</td>\n      <td>2018-04-26T18:26:06.957Z</td>\n      <td>88104</td>\n      <td>247358</td>\n      <td>33997</td>\n      <td>...</td>\n      <td>15563107.00</td>\n      <td>2018-04-26T17:55:55.000Z</td>\n      <td>120</td>\n      <td>nan</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>4.00</td>\n      <td>14.00</td>\n      <td>38.00</td>\n      <td>88.00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>12d11fd698296de7cd1936b65c364c837a5548bb</th>\n      <td>https://www.mirror.co.uk/news/world-news/jens-...</td>\n      <td>Driver who ploughed into crowd in Germany kill...</td>\n      <td>2018-04-09 12:13:18.411</td>\n      <td>2018-04-07 21:25:00</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-09T12:25:06.507Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>706</td>\n      <td>242.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>5cb80e681bf2979339c44745afdf172ff16d0f5f</th>\n      <td>http://www.dailymail.co.uk/home/event/article-...</td>\n      <td>Pressure at the Park Theatre review: Tense and...</td>\n      <td>2018-04-07 21:10:19.358</td>\n      <td>2018-04-07 21:06:44</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-04-08T09:28:08.107Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>1286.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>4b2649eec0ecdb576cf686e621b062bb3da4f749</th>\n      <td>https://www.washingtonpost.com/national/arizon...</td>\n      <td>Arizona mother pleads not guilty in children\u2019s...</td>\n      <td>2018-04-13 21:46:24.110</td>\n      <td>2018-04-13 21:34:07</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-13T21:58:14.200Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>152.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>4d1dd8c218f64c1828dc7663f26a5838609b24c9</th>\n      <td>https://www.washingtonpost.com/national/girl-3...</td>\n      <td>Girl, 3, shot in head outside Detroit gas station</td>\n      <td>2018-04-07 21:37:11.637</td>\n      <td>2018-04-07 21:27:17</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-08T15:57:12.491Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>156.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>0dadebe20f82a53b629fb6ce0a7d2dd092f92849</th>\n      <td>https://www.washingtonpost.com/national/us-coa...</td>\n      <td>US Coast Guard stops Haitian migrant boat with...</td>\n      <td>2018-04-11 17:16:19.774</td>\n      <td>2018-04-11 17:11:11</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-04-12T00:32:18.756Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>146.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>4c3ec7580f425f9d26d199e6a5b02ed3bcf5c12a</th>\n      <td>https://www.washingtonpost.com/opinions/how-to...</td>\n      <td>How to pay for national parks</td>\n      <td>2018-04-13 21:46:22.382</td>\n      <td>2018-04-13 21:35:17</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-04-14T17:11:06.725Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>184.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>639e2c9e5742ad9331cab2f25b5f86c9f2c4041e</th>\n      <td>https://www.washingtonpost.com/national/iowa-g...</td>\n      <td>Iowa governor signs into law ban on \u2018sanctuary...</td>\n      <td>2018-04-11 17:16:19.772</td>\n      <td>2018-04-11 17:11:10</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-12T07:38:08.777Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>159.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>57a85483548404c97eae5258828b2c05ec9eb327</th>\n      <td>https://www.mirror.co.uk/sport/football/news/e...</td>\n      <td>\"Everyone has to start somewhere\": Mansfield T...</td>\n      <td>2018-04-07 21:31:22.017</td>\n      <td>2018-04-07 21:30:00</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-08T09:50:15.671Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>706</td>\n      <td>680.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>2bd202acccdc311daaf65a86f5c83f3a8fe9180b</th>\n      <td>https://www.washingtonpost.com/national/prosec...</td>\n      <td>Prosecutor says DNA tied serial killing suspec...</td>\n      <td>2018-04-25 19:34:17.395</td>\n      <td>2018-04-25 19:30:11</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-26T05:53:09.433Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>35.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>54a443baefc9e8fe645628c4042a6a64b7285965</th>\n      <td>https://www.mirror.co.uk/tv/tv-news/stars-ship...</td>\n      <td>Where are the stars of Shipwrecked now? Big Br...</td>\n      <td>2018-04-17 10:19:20.594</td>\n      <td>2018-04-17 10:05:00</td>\n      <td>1</td>\n      <td>0.09</td>\n      <td>2018-04-17T10:31:09.731Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>706</td>\n      <td>824.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>c3dc9c8c80c8ac22bc1a6c2c5d60172a77db565c</th>\n      <td>https://www.economist.com/news/21740383-millen...</td>\n      <td>Generation uphill</td>\n      <td>2018-04-11 18:13:24.021</td>\n      <td>2018-04-11 17:13:02</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-12T17:42:13.297Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>1825</td>\n      <td>91.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>0cf15930b628ef55a48119addf25ef21b0a4af7a</th>\n      <td>https://www.washingtonpost.com/national/indian...</td>\n      <td>Indiana traffic stop nets 78 pounds of marijuana</td>\n      <td>2018-04-17 10:19:12.100</td>\n      <td>2018-04-17 10:12:15</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-18T08:44:13.403Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>82.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>e0cc6335e5db8ac87ea3e85bff8e0f61a7a95804</th>\n      <td>http://www.dailymail.co.uk/tvshowbiz/article-5...</td>\n      <td>BIP star Eden Schwencke reveals the real reaso...</td>\n      <td>2018-04-23 11:22:18.822</td>\n      <td>2018-04-23 11:18:58</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-23T11:34:11.810Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>594.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>9e14b5cdb439151d9fbf0f0a264d8f7b1ec9948f</th>\n      <td>http://www.dailymail.co.uk/news/article-558963...</td>\n      <td>JUSTIN WEBB: Mixing up generations brought sun...</td>\n      <td>2018-04-07 21:04:22.854</td>\n      <td>2018-04-07 21:01:19</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-08T06:22:10.253Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>462.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>ae0c487e677a4be16ba61a99db796b04b2a96f4a</th>\n      <td>http://www.dailymail.co.uk/sport/rugbyunion/ar...</td>\n      <td>England and Leicester team-mates George Ford a...</td>\n      <td>2018-04-13 21:34:39.967</td>\n      <td>2018-04-13 21:30:20</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-04-13T23:47:09.938Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>867.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>b561a9358c84fea3636da29592f9604628a68f30</th>\n      <td>https://www.washingtonpost.com/sports/dcunited...</td>\n      <td>FIFA bans Brazilian official Del Nero for life...</td>\n      <td>2018-04-27 12:43:18.583</td>\n      <td>2018-04-27 12:35:33</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-27T18:59:11.265Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>123.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>32aa570d5c404d80feb23b5e0012df5a7c62aa60</th>\n      <td>http://www.dailymail.co.uk/tvshowbiz/article-5...</td>\n      <td>MAFS' Patrick Miller cruises around Melbourne ...</td>\n      <td>2018-04-17 10:13:13.742</td>\n      <td>2018-04-17 10:09:21</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-18T08:40:13.458Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>634.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>2a8fdd4963fc770cbd8cb0bb9b31f2be58c5246f</th>\n      <td>http://www.dailymail.co.uk/home/event/article-...</td>\n      <td>Event critics give their take on live orchestr...</td>\n      <td>2018-04-07 21:04:18.792</td>\n      <td>2018-04-07 21:02:46</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-04-08T09:23:10.354Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>1081.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>d7e7577e3305efb7bc36b09a6b978e661bc62ba2</th>\n      <td>https://www.independent.co.uk/sport/golf/maste...</td>\n      <td>Masters 2018: Rory McIlroy\u2019s beautiful front n...</td>\n      <td>2018-04-07 21:07:20.220</td>\n      <td>2018-04-07 21:04:02</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>2018-04-07T21:18:12.122Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>386</td>\n      <td>449.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>68e5f5dee89a81e5bfc804b966babcc7fc408f77</th>\n      <td>https://www.washingtonpost.com/politics/us-eco...</td>\n      <td>US economic growth slowed to 2.3 percent pace ...</td>\n      <td>2018-04-27 12:46:09.121</td>\n      <td>2018-04-27 12:34:17</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-28T01:06:09.572Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>145.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>760632750b46d0823ef61867a0039b485291cb07</th>\n      <td>https://www.washingtonpost.com/world/europe/co...</td>\n      <td>Correction: Armenia-Protests story</td>\n      <td>2018-04-23 11:34:16.922</td>\n      <td>2018-04-23 11:19:10</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-24T05:56:11.987Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>287.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>7e12cadbfb711fa81c5ec89699031c31a2f99621</th>\n      <td>http://www.bbc.co.uk/news/av/uk-wales-43925442...</td>\n      <td>Moment masked robber sprayed shop worker with ...</td>\n      <td>2018-04-27 12:34:15.844</td>\n      <td>2018-04-27 12:33:06</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-04-27T21:52:12.973Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>80ac4446da66d50b4c5b6fa235adfbfc9ae7f72d</th>\n      <td>http://www.bbc.co.uk/sport/live/horse-racing/4...</td>\n      <td>Listen to live Scottish Grand National Festiva...</td>\n      <td>2018-04-17 10:10:17.460</td>\n      <td>2018-04-17 10:05:32</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-17T10:22:06.496Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>5bb39645b3c0bc2978f8c42a4c92e7cfd61c3226</th>\n      <td>http://www.dailymail.co.uk/home/event/article-...</td>\n      <td>Parsons gets everything right with minimum of ...</td>\n      <td>2018-04-07 21:07:17.571</td>\n      <td>2018-04-07 21:05:20</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>2018-04-07T21:18:12.114Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>832.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>69bee8508b05df1cd0be36bcf93ff713d616115f</th>\n      <td>http://www.bbc.co.uk/news/uk-scotland-glasgow-...</td>\n      <td>Murder accused found sister assault claims 'fu...</td>\n      <td>2018-04-11 17:16:16.294</td>\n      <td>2018-04-11 17:13:48</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-04-11T21:31:04.641Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>525.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>ea72509784337c57159df275fe9c67083bb30ecd</th>\n      <td>https://www.independent.co.uk/arts-entertainme...</td>\n      <td>Faceless, Park Theatre, London, review: A comp...</td>\n      <td>2018-04-23 11:25:16.814</td>\n      <td>2018-04-23 11:20:36</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-04-24T08:51:05.664Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>386</td>\n      <td>560.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>5c8927ba9144e73cc655cf31125be468e38afe33</th>\n      <td>http://www.dailymail.co.uk/news/article-566487...</td>\n      <td>Manhunt for Maine cop killer enters day three ...</td>\n      <td>2018-04-27 20:58:19.756</td>\n      <td>2018-04-27 12:33:16</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-04-27T22:11:13.773Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>596.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>2465261fcdbe82198242a41dd4ad953e43202021</th>\n      <td>https://www.washingtonpost.com/politics/us-eco...</td>\n      <td>US economic growth slowed to 2.3 percent rate ...</td>\n      <td>2018-04-27 12:46:09.533</td>\n      <td>2018-04-27 12:33:13</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-27T19:01:17.482Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>34.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>296b2ff2960aa46ff7dd1b19ce105175c3353a3f</th>\n      <td>https://www.washingtonpost.com/world/asia_paci...</td>\n      <td>Kim Jong Un returns to North Korea, ending sum...</td>\n      <td>2018-04-27 12:46:11.318</td>\n      <td>2018-04-27 12:33:11</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-27T21:03:10.921Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>43.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>4b98aec507b39c8afbb7f4cde8152f94ff1e8dbe</th>\n      <td>https://www.washingtonpost.com/national/foreca...</td>\n      <td>Forecasters warn of rare, life-threatening wil...</td>\n      <td>2018-04-17 11:37:19.856</td>\n      <td>2018-04-17 11:29:18</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-04-17T21:56:09.086Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>151.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>138275 rows \u00d7 26 columns</p>\n</div>\n\n\n\n\n```python\ndata[\"score_diff\"] = data.promotion_score - data.response_score\n```\n\n\n```python\n# promoted but low response\ndata.sort_values(\"score_diff\", ascending=False).head(25)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n      <th>score_diff</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>8b67316e22d9bbbbe26a97a39dd1365ff9d175d3</th>\n      <td>https://www.buzzfeed.com/katienotopoulos/teens...</td>\n      <td>Teens Also Sometimes Quit Social Media</td>\n      <td>2018-04-07 17:04:24.234</td>\n      <td>2018-04-04 17:37:46</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-07T17:16:12.351Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2018-04-08T01:04:02.000Z</td>\n      <td>147</td>\n      <td>1176.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>43.00</td>\n      <td>43.00</td>\n    </tr>\n    <tr>\n      <th>3cb27a4e5d7b0b0d6972afec2737c2a99cc76be2</th>\n      <td>https://www.buzzfeed.com/theresatamkins/twin-s...</td>\n      <td>Twin Sisters With Severe OCD Have Died In A Po...</td>\n      <td>2018-04-05 19:16:17.257</td>\n      <td>2018-04-04 19:35:26</td>\n      <td>19</td>\n      <td>0.31</td>\n      <td>2018-04-05T20:28:07.825Z</td>\n      <td>1</td>\n      <td>10</td>\n      <td>8</td>\n      <td>...</td>\n      <td>2018-04-08T18:04:00.000Z</td>\n      <td>147</td>\n      <td>130.00</td>\n      <td>4.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>49.00</td>\n      <td>41.00</td>\n    </tr>\n    <tr>\n      <th>f05031efa6a829f220e82331a2c91c48b33ddd91</th>\n      <td>https://www.buzzfeed.com/kendalltaggart/nypd-p...</td>\n      <td>Here\u2019s Why BuzzFeed News Is Publishing Thousan...</td>\n      <td>2018-04-16 09:34:16.432</td>\n      <td>2018-04-13 23:12:43</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-16T09:45:13.729Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2018-04-16T13:23:00.000Z</td>\n      <td>147</td>\n      <td>1304.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>11.00</td>\n      <td>11.00</td>\n      <td>41.00</td>\n      <td>41.00</td>\n      <td>41.00</td>\n    </tr>\n    <tr>\n      <th>acd63345be81904294a37e8e687c1ffcd41c7c1f</th>\n      <td>https://www.buzzfeed.com/claudiakoerner/teache...</td>\n      <td>This Teacher Says She Can\u2019t Afford To Stay On ...</td>\n      <td>2018-04-11 12:01:20.976</td>\n      <td>2018-04-09 21:34:31</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-11T12:13:11.080Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2018-04-11T17:20:19.000Z</td>\n      <td>147</td>\n      <td>2476.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>11.00</td>\n      <td>11.00</td>\n      <td>41.00</td>\n      <td>41.00</td>\n      <td>41.00</td>\n    </tr>\n    <tr>\n      <th>4d77d72e13dbba05f89bf209fde926d9347a3548</th>\n      <td>https://www.buzzfeed.com/theresatamkins/ocular...</td>\n      <td>This Rare Eye Cancer Is Affecting Young Women ...</td>\n      <td>2018-05-01 17:07:48.450</td>\n      <td>2018-04-30 17:03:45</td>\n      <td>5</td>\n      <td>0.45</td>\n      <td>2018-05-01T17:19:18.075Z</td>\n      <td>0</td>\n      <td>3</td>\n      <td>2</td>\n      <td>...</td>\n      <td>2018-05-02T18:50:17.000Z</td>\n      <td>147</td>\n      <td>1162.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>11.00</td>\n      <td>11.00</td>\n      <td>41.00</td>\n      <td>42.00</td>\n      <td>40.00</td>\n    </tr>\n    <tr>\n      <th>aaeccc954251b991b87742305992c21b5a07e4fb</th>\n      <td>https://www.buzzfeed.com/krishrach/south-korea...</td>\n      <td>The #MeToo Era Is Happening In South Korea Whe...</td>\n      <td>2018-04-17 12:40:15.914</td>\n      <td>2018-04-13 13:44:41</td>\n      <td>2</td>\n      <td>0.19</td>\n      <td>2018-04-17T12:52:07.422Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>...</td>\n      <td>2018-04-18T13:30:17.000Z</td>\n      <td>147</td>\n      <td>2552.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>11.00</td>\n      <td>11.00</td>\n      <td>41.00</td>\n      <td>42.00</td>\n      <td>40.00</td>\n    </tr>\n    <tr>\n      <th>adf38c51ab0e882926d1294199ad563e9efa8c71</th>\n      <td>https://www.buzzfeed.com/albertsamaha/san-anto...</td>\n      <td>This Police Force Is Considered Progressive, B...</td>\n      <td>2018-04-24 12:19:26.784</td>\n      <td>2018-04-19 18:00:51</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-24T12:30:13.329Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2018-04-24T13:24:55.000Z</td>\n      <td>147</td>\n      <td>4976.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>10.00</td>\n      <td>11.00</td>\n      <td>40.00</td>\n      <td>40.00</td>\n      <td>40.00</td>\n    </tr>\n    <tr>\n      <th>261f8a165d69b04445a514ae9d7693b67d003c6b</th>\n      <td>https://www.buzzfeed.com/katebubacz/heres-why-...</td>\n      <td>Here's Why People Are Seeking Asylum In The US</td>\n      <td>2018-04-30 11:34:19.256</td>\n      <td>2018-04-28 19:04:52</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>2018-04-30T11:45:08.069Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>2018-04-30T14:11:07.000Z</td>\n      <td>147</td>\n      <td>1486.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>9.00</td>\n      <td>11.00</td>\n      <td>39.00</td>\n      <td>39.00</td>\n      <td>39.00</td>\n    </tr>\n    <tr>\n      <th>d91e16c87837630173d243077657f028199a5e29</th>\n      <td>https://www.buzzfeed.com/johnpaczkowski/make-d...</td>\n      <td>What To Expect At Facebook And Google's Big Sh...</td>\n      <td>2018-04-23 16:31:31.209</td>\n      <td>2018-04-21 00:10:58</td>\n      <td>2</td>\n      <td>0.18</td>\n      <td>2018-04-23T16:43:09.589Z</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>...</td>\n      <td>2018-04-23T16:40:19.000Z</td>\n      <td>147</td>\n      <td>824.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>10.00</td>\n      <td>11.00</td>\n      <td>40.00</td>\n      <td>41.00</td>\n      <td>39.00</td>\n    </tr>\n    <tr>\n      <th>c9b4fe9d6bb974728cf3be7416843b6a59134771</th>\n      <td>https://www.buzzfeed.com/monicamark/dapchi-gir...</td>\n      <td>There\u2019s A Truther Movement In Nigeria That Thi...</td>\n      <td>2018-04-28 16:19:14.197</td>\n      <td>2018-04-27 18:40:36</td>\n      <td>11</td>\n      <td>0.20</td>\n      <td>2018-04-28T16:30:13.514Z</td>\n      <td>0</td>\n      <td>2</td>\n      <td>9</td>\n      <td>...</td>\n      <td>2018-04-29T23:34:00.000Z</td>\n      <td>147</td>\n      <td>4457.00</td>\n      <td>2.00</td>\n      <td>19.00</td>\n      <td>10.00</td>\n      <td>11.00</td>\n      <td>40.00</td>\n      <td>42.00</td>\n      <td>38.00</td>\n    </tr>\n    <tr>\n      <th>01710ce2fee069ba68fb22291549cd4822c66081</th>\n      <td>https://www.buzzfeed.com/munzeralawad/syrian-r...</td>\n      <td>Syrian Rebels Hope Strikes Aren\u2019t Just For Sho...</td>\n      <td>2018-04-09 21:28:19.824</td>\n      <td>2018-04-09 21:09:10</td>\n      <td>36</td>\n      <td>0.46</td>\n      <td>2018-04-09T21:40:08.801Z</td>\n      <td>2</td>\n      <td>20</td>\n      <td>14</td>\n      <td>...</td>\n      <td>2018-04-10T01:00:57.000Z</td>\n      <td>147</td>\n      <td>848.00</td>\n      <td>6.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>50.00</td>\n      <td>38.00</td>\n    </tr>\n    <tr>\n      <th>1c0fa02e27e11772590021e15381451d072f937f</th>\n      <td>https://www.buzzfeed.com/kateaurthur/joe-pater...</td>\n      <td>Watching \"Paterno\" During The #MeToo Era</td>\n      <td>2018-04-07 14:04:19.812</td>\n      <td>2018-04-06 22:47:16</td>\n      <td>43</td>\n      <td>0.22</td>\n      <td>2018-04-07T16:17:11.923Z</td>\n      <td>9</td>\n      <td>22</td>\n      <td>12</td>\n      <td>...</td>\n      <td>2018-04-08T21:03:28.000Z</td>\n      <td>147</td>\n      <td>1071.00</td>\n      <td>6.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>50.00</td>\n      <td>38.00</td>\n    </tr>\n    <tr>\n      <th>8a5c5d33f825e7d9497f31fb9c1bd70b1013bb13</th>\n      <td>https://www.buzzfeed.com/scottpham/cocaine-fen...</td>\n      <td>The Opioid Crisis Is Turning Into A Cocaine Cr...</td>\n      <td>2018-05-01 13:39:11.249</td>\n      <td>2018-04-30 14:43:47</td>\n      <td>35</td>\n      <td>0.52</td>\n      <td>2018-05-01T14:51:11.209Z</td>\n      <td>2</td>\n      <td>15</td>\n      <td>18</td>\n      <td>...</td>\n      <td>2018-05-01T14:42:35.000Z</td>\n      <td>147</td>\n      <td>2614.00</td>\n      <td>5.00</td>\n      <td>19.00</td>\n      <td>11.00</td>\n      <td>11.00</td>\n      <td>41.00</td>\n      <td>46.00</td>\n      <td>36.00</td>\n    </tr>\n    <tr>\n      <th>8607d8bcd0338c95626444386547442a95dbe452</th>\n      <td>https://www.buzzfeed.com/karlazabludovsky/the-...</td>\n      <td>The Caravan That Has Trump Angry Is An Excepti...</td>\n      <td>2018-04-02 21:34:26.612</td>\n      <td>2018-04-02 20:19:41</td>\n      <td>56</td>\n      <td>0.15</td>\n      <td>2018-04-03T01:49:09.479Z</td>\n      <td>3</td>\n      <td>29</td>\n      <td>24</td>\n      <td>...</td>\n      <td>2018-04-03T00:56:32.000Z</td>\n      <td>147</td>\n      <td>939.00</td>\n      <td>7.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>50.00</td>\n      <td>36.00</td>\n    </tr>\n    <tr>\n      <th>472557d89afbef234765488b15cf82a8d7364158</th>\n      <td>https://www.buzzfeed.com/buzzfeednews/bill-cos...</td>\n      <td>Live Updates: Bill Cosby Starts Under The Glar...</td>\n      <td>2018-04-09 16:07:43.899</td>\n      <td>2018-04-09 16:04:52</td>\n      <td>53</td>\n      <td>0.15</td>\n      <td>2018-04-09T23:24:14.462Z</td>\n      <td>6</td>\n      <td>38</td>\n      <td>9</td>\n      <td>...</td>\n      <td>2018-04-09T17:56:12.000Z</td>\n      <td>147</td>\n      <td>382.00</td>\n      <td>7.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>50.00</td>\n      <td>36.00</td>\n    </tr>\n    <tr>\n      <th>17951ed09b77c76391414d3a9921c5900581066b</th>\n      <td>https://www.buzzfeed.com/adambvary/chappaquidd...</td>\n      <td>This New Film Is Resurrecting Ted Kennedy\u2019s Da...</td>\n      <td>2018-04-07 01:19:14.059</td>\n      <td>2018-04-07 00:51:00</td>\n      <td>85</td>\n      <td>0.23</td>\n      <td>2018-04-07T23:44:12.003Z</td>\n      <td>20</td>\n      <td>35</td>\n      <td>30</td>\n      <td>...</td>\n      <td>2018-04-08T23:04:41.000Z</td>\n      <td>147</td>\n      <td>1128.00</td>\n      <td>9.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>53.00</td>\n      <td>35.00</td>\n    </tr>\n    <tr>\n      <th>b2166204c46fb2999a8b47d79c35173cb3be618f</th>\n      <td>https://www.buzzfeed.com/laurageiser/californi...</td>\n      <td>California's Trees Are Dying At A Catastrophic...</td>\n      <td>2018-04-22 16:01:16.983</td>\n      <td>2018-04-17 15:47:49</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-04-22T16:12:11.498Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2018-04-22T19:33:44.000Z</td>\n      <td>147</td>\n      <td>1719.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>4.00</td>\n      <td>11.00</td>\n      <td>34.00</td>\n      <td>34.00</td>\n      <td>34.00</td>\n    </tr>\n    <tr>\n      <th>1f401a0e408e81d6fbff3e6590f6c4f6191c34d7</th>\n      <td>https://www.buzzfeed.com/adolfoflores/caravan-...</td>\n      <td>Not Over Yet: With Legal Papers In Hand, The M...</td>\n      <td>2018-04-06 22:52:30.325</td>\n      <td>2018-04-06 22:21:23</td>\n      <td>119</td>\n      <td>0.27</td>\n      <td>2018-04-07T22:18:14.605Z</td>\n      <td>31</td>\n      <td>61</td>\n      <td>27</td>\n      <td>...</td>\n      <td>2018-04-07T00:40:13.000Z</td>\n      <td>147</td>\n      <td>1060.00</td>\n      <td>11.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>56.00</td>\n      <td>34.00</td>\n    </tr>\n    <tr>\n      <th>b21e43b2d43b7fdb8d7919c808cd2c718135b62e</th>\n      <td>https://www.buzzfeed.com/koviebiakolo/the-rach...</td>\n      <td>The Rachel Dolezal Documentary Has Become A De...</td>\n      <td>2018-04-28 14:14:12.074</td>\n      <td>2018-04-28 01:58:16</td>\n      <td>29</td>\n      <td>0.12</td>\n      <td>2018-04-28T15:26:02.727Z</td>\n      <td>6</td>\n      <td>10</td>\n      <td>13</td>\n      <td>...</td>\n      <td>2018-04-29T14:04:00.000Z</td>\n      <td>147</td>\n      <td>3089.00</td>\n      <td>5.00</td>\n      <td>19.00</td>\n      <td>9.00</td>\n      <td>11.00</td>\n      <td>39.00</td>\n      <td>44.00</td>\n      <td>34.00</td>\n    </tr>\n    <tr>\n      <th>2cd85f75342343e471684a899fbca70a1da5c7b0</th>\n      <td>https://www.buzzfeed.com/salvadorhernandez/nat...</td>\n      <td>Hundreds Of National Guard Troops Are Headed T...</td>\n      <td>2018-04-07 01:16:17.047</td>\n      <td>2018-04-07 01:08:37</td>\n      <td>143</td>\n      <td>0.58</td>\n      <td>2018-04-07T21:41:06.364Z</td>\n      <td>27</td>\n      <td>88</td>\n      <td>28</td>\n      <td>...</td>\n      <td>2018-04-07T20:30:38.000Z</td>\n      <td>147</td>\n      <td>496.00</td>\n      <td>11.00</td>\n      <td>19.00</td>\n      <td>15.00</td>\n      <td>11.00</td>\n      <td>45.00</td>\n      <td>56.00</td>\n      <td>34.00</td>\n    </tr>\n    <tr>\n      <th>a12bb350a8e994e03d79a58a26a0ccad0d67fe3b</th>\n      <td>https://www.buzzfeed.com/skbaer/how-the-golden...</td>\n      <td>How California's Most Notorious And Prolific S...</td>\n      <td>2018-04-27 23:55:31.649</td>\n      <td>2018-04-27 02:59:31</td>\n      <td>19</td>\n      <td>0.20</td>\n      <td>2018-04-28T01:07:16.868Z</td>\n      <td>0</td>\n      <td>2</td>\n      <td>17</td>\n      <td>...</td>\n      <td>2018-04-28T20:35:06.000Z</td>\n      <td>147</td>\n      <td>1304.00</td>\n      <td>4.00</td>\n      <td>19.00</td>\n      <td>8.00</td>\n      <td>11.00</td>\n      <td>38.00</td>\n      <td>42.00</td>\n      <td>34.00</td>\n    </tr>\n    <tr>\n      <th>46a709c479a116fa560575e778ffadcaad98cd24</th>\n      <td>https://www.buzzfeed.com/bensmith/facebook-you...</td>\n      <td>What Comes After The Social Media Empires</td>\n      <td>2018-04-18 18:04:27.256</td>\n      <td>2018-04-18 18:01:44</td>\n      <td>68</td>\n      <td>0.25</td>\n      <td>2018-04-18T19:17:04.867Z</td>\n      <td>5</td>\n      <td>27</td>\n      <td>36</td>\n      <td>...</td>\n      <td>2018-04-18T18:42:49.000Z</td>\n      <td>147</td>\n      <td>1228.00</td>\n      <td>8.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>50.00</td>\n      <td>34.00</td>\n    </tr>\n    <tr>\n      <th>79f3ea9c5f0c08b32c975851e7aea661ab91776b</th>\n      <td>https://www.buzzfeed.com/adolfoflores/caravan-...</td>\n      <td>Organizers Say Caravan Will Continue And Will ...</td>\n      <td>2018-04-04 00:37:26.127</td>\n      <td>2018-04-04 00:29:33</td>\n      <td>117</td>\n      <td>0.42</td>\n      <td>2018-04-04T04:51:10.902Z</td>\n      <td>33</td>\n      <td>57</td>\n      <td>27</td>\n      <td>...</td>\n      <td>2018-04-04T03:18:58.000Z</td>\n      <td>147</td>\n      <td>748.00</td>\n      <td>10.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>53.00</td>\n      <td>33.00</td>\n    </tr>\n    <tr>\n      <th>f7de523afb549ce453cf8e07321eabc8fe1db5d2</th>\n      <td>https://www.buzzfeed.com/coralewis/new-sanctio...</td>\n      <td>The US Is Placing New Sanctions On 38 Russian ...</td>\n      <td>2018-04-06 12:40:13.441</td>\n      <td>2018-04-06 12:37:40</td>\n      <td>67</td>\n      <td>0.27</td>\n      <td>2018-04-06T12:52:07.859Z</td>\n      <td>8</td>\n      <td>28</td>\n      <td>31</td>\n      <td>...</td>\n      <td>2018-04-06T15:20:15.000Z</td>\n      <td>147</td>\n      <td>295.00</td>\n      <td>8.00</td>\n      <td>19.00</td>\n      <td>11.00</td>\n      <td>11.00</td>\n      <td>41.00</td>\n      <td>49.00</td>\n      <td>33.00</td>\n    </tr>\n    <tr>\n      <th>e228b9b4729b1e26b70d184c84b07192c813b026</th>\n      <td>https://www.buzzfeed.com/craigsilverman/youtub...</td>\n      <td>How YouTube\u2019s Channel Recommendations Push Use...</td>\n      <td>2018-04-12 19:07:36.597</td>\n      <td>2018-04-12 16:15:27</td>\n      <td>58</td>\n      <td>0.15</td>\n      <td>2018-04-13T15:33:13.988Z</td>\n      <td>8</td>\n      <td>14</td>\n      <td>36</td>\n      <td>...</td>\n      <td>2018-04-16T18:07:25.000Z</td>\n      <td>147</td>\n      <td>1148.00</td>\n      <td>7.00</td>\n      <td>19.00</td>\n      <td>10.00</td>\n      <td>11.00</td>\n      <td>40.00</td>\n      <td>47.00</td>\n      <td>33.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>25 rows \u00d7 27 columns</p>\n</div>\n\n\n\n\n```python\n# high response but not promoted\ndata.sort_values(\"score_diff\", ascending=True).head(25)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n      <th>score_diff</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>98e23165dce61669ac8bc420f87cb39d5682f90b</th>\n      <td>https://www.cnn.com/2018/04/26/world/korea-sum...</td>\n      <td>South Korea credits Trump for talks with North</td>\n      <td>2018-04-26 11:55:10.250</td>\n      <td>2018-04-26 11:49:17</td>\n      <td>488344</td>\n      <td>539.73</td>\n      <td>2018-04-27T17:04:09.730Z</td>\n      <td>78939</td>\n      <td>344837</td>\n      <td>64568</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>105</td>\n      <td>443.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>697c0030f63bf62fbaf47e740a04af8b45a51f0c</th>\n      <td>http://yournewswire.com/california-obscene-lgb...</td>\n      <td>California Bans Parents From Pulling Kids From...</td>\n      <td>2018-04-23 16:24:28.801</td>\n      <td>2018-04-23 15:22:43</td>\n      <td>115948</td>\n      <td>67.65</td>\n      <td>2018-04-26T22:37:11.361Z</td>\n      <td>43498</td>\n      <td>54777</td>\n      <td>17673</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>22568</td>\n      <td>765.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>d475a7270eadc9e9b419abc63a59e54478399d13</th>\n      <td>https://www.cnn.com/2018/04/27/asia/read-full-...</td>\n      <td>READ: Full declaration of North and South Kore...</td>\n      <td>2018-04-27 10:13:20.763</td>\n      <td>2018-04-27 10:10:33</td>\n      <td>97886</td>\n      <td>204.93</td>\n      <td>2018-04-28T09:06:07.845Z</td>\n      <td>16821</td>\n      <td>68860</td>\n      <td>12205</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>105</td>\n      <td>1144.00</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>49.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>c46c58ebe5cb89d87b3b3e734d799f697e8de70c</th>\n      <td>http://www.foxnews.com/us/2018/04/18/former-ac...</td>\n      <td>Former ace Navy pilot ID\u2019d as hero who landed ...</td>\n      <td>2018-04-18 05:44:09.443</td>\n      <td>2018-04-18 05:37:56</td>\n      <td>186147</td>\n      <td>651.87</td>\n      <td>2018-04-18T14:11:11.142Z</td>\n      <td>8710</td>\n      <td>157521</td>\n      <td>19916</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>412.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>42c82ece9cb64042cbed2d151e3d0aa5d43c608e</th>\n      <td>http://www.dailymail.co.uk/tvshowbiz/article-5...</td>\n      <td>Nasser Sultan 'moves on with a man' after spli...</td>\n      <td>2018-04-08 22:31:23.503</td>\n      <td>2018-04-08 22:26:54</td>\n      <td>118419</td>\n      <td>215.18</td>\n      <td>2018-04-09T03:34:08.228Z</td>\n      <td>101766</td>\n      <td>14833</td>\n      <td>1820</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>424.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>f56a0d6c345e8f99deeb019ba69a335ef193f54e</th>\n      <td>http://www.dailymail.co.uk/news/article-560591...</td>\n      <td>NSW man nearly burnt alive by barbeque</td>\n      <td>2018-04-12 01:46:20.183</td>\n      <td>2018-04-12 01:42:16</td>\n      <td>113588</td>\n      <td>443.69</td>\n      <td>2018-04-12T15:07:10.107Z</td>\n      <td>25066</td>\n      <td>61963</td>\n      <td>26559</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>206.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>e0db1773b7e34469b8624958df28c93997f5048e</th>\n      <td>http://www.dailymail.co.uk/news/article-563067...</td>\n      <td>Body cam shows police fatally shoot black male...</td>\n      <td>2018-04-18 16:34:23.675</td>\n      <td>2018-04-18 16:31:01</td>\n      <td>91087</td>\n      <td>31.41</td>\n      <td>2018-04-26T13:51:12.301Z</td>\n      <td>23820</td>\n      <td>40915</td>\n      <td>26352</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>699.00</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>49.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>02d16220f444d881aac0dff48bd84c204edeb189</th>\n      <td>https://www.washingtonpost.com/news/politics/w...</td>\n      <td>China\u2019s retaliatory tariffs will hit Trump cou...</td>\n      <td>2018-04-04 18:01:16.010</td>\n      <td>2018-04-04 17:56:19</td>\n      <td>110272</td>\n      <td>84.71</td>\n      <td>2018-04-05T02:17:11.648Z</td>\n      <td>31539</td>\n      <td>59270</td>\n      <td>19463</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>328.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>fa16823eda18f3c7cd15c117d53c7c6504736c84</th>\n      <td>https://www.washingtonpost.com/news/politics/w...</td>\n      <td>FBI seizes records related to Stormy Daniels i...</td>\n      <td>2018-04-09 20:34:12.849</td>\n      <td>2018-04-09 20:27:56</td>\n      <td>102076</td>\n      <td>327.17</td>\n      <td>2018-04-09T22:32:12.679Z</td>\n      <td>25888</td>\n      <td>63815</td>\n      <td>12373</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>145.00</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>50.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>6ed8d0b4c37eed6ca2a44109c5b1c2bf160370a5</th>\n      <td>http://www.foxnews.com/entertainment/2018/04/0...</td>\n      <td>Jimmy Kimmel mocks Melania Trump's accent, tro...</td>\n      <td>2018-04-03 16:39:16.948</td>\n      <td>2018-04-03 16:26:39</td>\n      <td>101329</td>\n      <td>199.70</td>\n      <td>2018-04-03T19:28:07.769Z</td>\n      <td>41034</td>\n      <td>54055</td>\n      <td>6240</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>564.00</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>50.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>e38732e2f458927cf77118b432ba912d197770ba</th>\n      <td>https://www.cnn.com/2018/04/20/politics/mike-p...</td>\n      <td>Indiana abortion law signed by Mike Pence rule...</td>\n      <td>2018-04-20 20:34:29.230</td>\n      <td>2018-04-20 20:30:33</td>\n      <td>141991</td>\n      <td>105.32</td>\n      <td>2018-04-21T15:17:16.755Z</td>\n      <td>13900</td>\n      <td>114761</td>\n      <td>13330</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>105</td>\n      <td>367.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>52.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>5779932dc4708265140b6f5c57d63e553b1a2a42</th>\n      <td>http://www.foxnews.com/health/2018/04/02/teens...</td>\n      <td>Teens snort condoms then pull them through mou...</td>\n      <td>2018-04-02 16:59:17.583</td>\n      <td>2018-04-02 16:51:40</td>\n      <td>103517</td>\n      <td>545.63</td>\n      <td>2018-04-03T05:03:10.892Z</td>\n      <td>49901</td>\n      <td>40170</td>\n      <td>13446</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>395.00</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>51.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>1884d5b8859e0dd1c2c252c4a5cbb3e416a96f18</th>\n      <td>https://www.buzzfeed.com/caseyrackham/watch-co...</td>\n      <td>Pixar's \"Coco\" Is Coming To Netflix In May, So...</td>\n      <td>2018-04-24 14:14:07.919</td>\n      <td>2018-04-24 14:09:14</td>\n      <td>100220</td>\n      <td>340.67</td>\n      <td>2018-04-24T18:46:10.985Z</td>\n      <td>19390</td>\n      <td>74627</td>\n      <td>6203</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>nan</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>51.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>574b18606f4757686e9ee04a479a85f3abb0982c</th>\n      <td>http://www.foxnews.com/entertainment/2018/04/1...</td>\n      <td>Roseanne defends pro-Trump Diamond and Silk af...</td>\n      <td>2018-04-11 18:24:10.969</td>\n      <td>2018-04-11 17:21:34</td>\n      <td>68570</td>\n      <td>1257.53</td>\n      <td>2018-04-12T01:11:16.004Z</td>\n      <td>2981</td>\n      <td>63390</td>\n      <td>2199</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>411.00</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>48.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>ee874f553d5fdf610abf75e9e100d40dd7a1dbcd</th>\n      <td>http://www.washingtonpost.com/video/politics/t...</td>\n      <td>Trump claims \u2018millions and millions\u2019 vote ille...</td>\n      <td>2018-04-05 19:28:14.478</td>\n      <td>2018-04-05 19:11:23</td>\n      <td>58822</td>\n      <td>40.83</td>\n      <td>2018-04-06T00:32:04.144Z</td>\n      <td>23824</td>\n      <td>27390</td>\n      <td>7608</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>nan</td>\n      <td>46.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>46.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>2e57f337f489f4a986044c55a13684946df9fabe</th>\n      <td>https://www.washingtonpost.com/news/arts-and-e...</td>\n      <td>Forty years ago, \u2018Rock Lobster\u2019 launched the c...</td>\n      <td>2018-04-06 11:04:29.589</td>\n      <td>2018-04-06 11:00:24</td>\n      <td>72671</td>\n      <td>397.24</td>\n      <td>2018-04-06T23:06:09.762Z</td>\n      <td>9873</td>\n      <td>56191</td>\n      <td>6607</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>982.00</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>48.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>2d671f7213cf85d0a97ca1db26c60b805740fa59</th>\n      <td>https://www.nytimes.com/2018/04/22/nyregion/ch...</td>\n      <td>New York to Expand Use of Doulas to Reduce Chi...</td>\n      <td>2018-04-22 22:52:15.228</td>\n      <td>2018-04-22 22:51:09</td>\n      <td>55909</td>\n      <td>60.36</td>\n      <td>2018-04-23T14:02:10.892Z</td>\n      <td>5271</td>\n      <td>44099</td>\n      <td>6539</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>120</td>\n      <td>684.00</td>\n      <td>46.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>46.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>0ba20825bcbbd5fd6b4f812e89f2632c3182b313</th>\n      <td>http://www.bbc.co.uk/news/uk-england-london-43...</td>\n      <td>Man, 78, arrested over Hither Green 'burglar' ...</td>\n      <td>2018-04-04 10:16:08.368</td>\n      <td>2018-04-04 10:14:48</td>\n      <td>100900</td>\n      <td>132.18</td>\n      <td>2018-04-05T09:34:11.481Z</td>\n      <td>41029</td>\n      <td>49364</td>\n      <td>10507</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>140.00</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>52.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>e7ce2eb7d78463c80e6747eb0f961e2bb8e5b141</th>\n      <td>https://www.reuters.com/article/us-usa-biofuel...</td>\n      <td>Exclusive: U.S. EPA grants biofuels waiver to ...</td>\n      <td>2018-04-30 11:04:20.311</td>\n      <td>2018-04-30 11:02:46</td>\n      <td>59982</td>\n      <td>152.27</td>\n      <td>2018-04-30T15:30:16.669Z</td>\n      <td>7488</td>\n      <td>39088</td>\n      <td>13406</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>497</td>\n      <td>nan</td>\n      <td>46.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>46.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>800b7219c01f879055a94d83af8387aae9aa3213</th>\n      <td>http://yournewswire.com/queen-elizabeth-bans-o...</td>\n      <td>Queen Elizabeth Bans Obamas From Royal Wedding</td>\n      <td>2018-04-15 16:54:33.316</td>\n      <td>2018-04-15 16:22:54</td>\n      <td>75033</td>\n      <td>25.45</td>\n      <td>2018-04-17T23:34:14.132Z</td>\n      <td>17465</td>\n      <td>47923</td>\n      <td>9645</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>22568</td>\n      <td>1146.00</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>48.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>be0c99a91cade39290e46f145c9ed8bff606a225</th>\n      <td>https://www.washingtonpost.com/opinions/robert...</td>\n      <td>Robert Redford: The biggest Scott Pruitt scand...</td>\n      <td>2018-04-26 23:46:22.593</td>\n      <td>2018-04-26 23:36:59</td>\n      <td>73360</td>\n      <td>59.73</td>\n      <td>2018-04-30T01:31:09.202Z</td>\n      <td>4778</td>\n      <td>56113</td>\n      <td>12469</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>608.00</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>49.00</td>\n      <td>-45.00</td>\n    </tr>\n    <tr>\n      <th>e641e3fdb87663c53282c8e2e5b74373a9e4f905</th>\n      <td>http://www.foxnews.com/politics/2018/04/04/oba...</td>\n      <td>Obama State Dept used taxpayer dollars to fund...</td>\n      <td>2018-04-04 21:59:16.809</td>\n      <td>2018-04-04 21:56:39</td>\n      <td>56230</td>\n      <td>70.48</td>\n      <td>2018-04-04T23:14:07.972Z</td>\n      <td>8452</td>\n      <td>33225</td>\n      <td>14553</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>802.00</td>\n      <td>46.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>47.00</td>\n      <td>-45.00</td>\n    </tr>\n    <tr>\n      <th>ad1282930d08eea4d6b20ac2ea99a087f593183e</th>\n      <td>http://www.bbc.co.uk/news/uk-england-london-43...</td>\n      <td>No further action after 'burglar' death</td>\n      <td>2018-04-06 17:25:14.934</td>\n      <td>2018-04-06 17:23:05</td>\n      <td>320098</td>\n      <td>1413.60</td>\n      <td>2018-04-06T17:59:10.398Z</td>\n      <td>42599</td>\n      <td>241401</td>\n      <td>36098</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>68.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>5.00</td>\n      <td>0.00</td>\n      <td>5.00</td>\n      <td>55.00</td>\n      <td>-45.00</td>\n    </tr>\n    <tr>\n      <th>c2ff33a69eecfbeaafb92f967d2434a758da7bc8</th>\n      <td>https://yournewswire.com/smallville-star-sold-...</td>\n      <td>\u2018Smallville\u2019 Star Confesses She Sold Children ...</td>\n      <td>2018-04-29 00:09:32.401</td>\n      <td>2018-04-29 00:07:39</td>\n      <td>276577</td>\n      <td>800.85</td>\n      <td>2018-04-30T23:04:08.422Z</td>\n      <td>93935</td>\n      <td>123872</td>\n      <td>58770</td>\n      <td>...</td>\n      <td>2018-05-01T16:12:00.000Z</td>\n      <td>22568</td>\n      <td>865.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>4.00</td>\n      <td>5.00</td>\n      <td>55.00</td>\n      <td>-45.00</td>\n    </tr>\n    <tr>\n      <th>2d9b8a4b0d7b4055b3f2d416f1f87d264d7f61a5</th>\n      <td>http://yournewswire.com/california-brown-ban-b...</td>\n      <td>California Gov. Jerry Brown To Ban Sales Of Th...</td>\n      <td>2018-04-20 17:04:25.516</td>\n      <td>2018-04-20 16:27:56</td>\n      <td>552344</td>\n      <td>422.89</td>\n      <td>2018-04-22T07:05:08.991Z</td>\n      <td>259819</td>\n      <td>208358</td>\n      <td>84167</td>\n      <td>...</td>\n      <td>2018-04-21T19:52:56.000Z</td>\n      <td>22568</td>\n      <td>437.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>4.00</td>\n      <td>5.00</td>\n      <td>55.00</td>\n      <td>-45.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>25 rows \u00d7 27 columns</p>\n</div>\n\n\n\nWrite that data to a file. Note that the scores here are provisional for two reasons:\n1. they should be using a rolling-month based on the article publication date to calculate medians/min/max etc, whereas in this workbook we as just using values for the month of May\n2. for analysis, we've rounded the numbers; we don't expect to do that for the actual scores\n\n\n```python\ndata.to_csv(\"articles_with_provisional_scores_\" + date_filename + \".csv\")\n```\n\n# Summary\n\nThe attention index of an article is comprised of four components:\n\n- *lead score* (max 20 points) based on how long an article was the lead story on the publisher's home page, scaled by the traffic to that publisher\n- *front score* (max 15 points) based on how long an article was present on the publisher's home page, scaled by traffic to that publisher\n- *Facebook promotion score* (max 15 points) based on whether the article was promoted to the publisher's Facebook brand page, scaled by the reach of that brand page\n- *response score* (max 50 points) based on the number of Facebook engagements the article received, relative to other articles\n\nOr, in other words:\n\n\\begin{align}\nattentionIndex_a &= leadScore_a + frontScore_a + facebookPromotionScore_a + responseScore_a \\\\\nleadScore_a &= 20 \\cdot \\left(\\frac{\\min(minsAsLead_a, 60)}{alexaRank_a}\\right) \\cdot \\left( \\frac{\\min(alexaRank)}{60} \\right) \\\\\nfrontScore_a &= \n15 \\cdot\n\\left(\\frac{\\min(minsOnFront_a, 1440)}{alexaRank_a \\cdot numArticlesOnFront_a}\\right) \\cdot\n\\left( \\frac{\\min(alexaRank \\cdot numArticlesOnFront)}{1440} \\right) \\\\\nfacebookPromotion_a &= \n\\begin{cases}\n 0 \\text{ if not shared on brand page }\\\\\n   15 \\cdot \\frac{\\log(brandPageLikes_a) - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))}  \\text{ otherwise }\n\\end{cases}   \n\\\\\nresponseScore_a &= \n\\begin{cases} \n   0 \\text{ if } engagements_a = 0 \\\\\n   50 \\cdot \n   \\frac{\\log(\\min(engagements_a,limit) + median(engagements)) - \\log(1 + median(engagements))}\n   {\\log(limit + median(engagements)) - \\log(1 + median(engagements))} \\text{ if } engagements_a > 0\n\\end{cases} \\\\\n\\end{align} \n", "meta": {"hexsha": "52d36182827877307d6407d8a33eb058e20736b0", "size": 731409, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "data/attention-index-april-2018.ipynb", "max_stars_repo_name": "kaleida/attention-index", "max_stars_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2017-06-03T11:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T10:02:06.000Z", "max_issues_repo_path": "data/attention-index-april-2018.ipynb", "max_issues_repo_name": "kaleida/attention-index", "max_issues_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data/attention-index-april-2018.ipynb", "max_forks_repo_name": "kaleida/attention-index", "max_forks_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 84.7420924574, "max_line_length": 45386, "alphanum_fraction": 0.6913477958, "converted": true, "num_tokens": 57184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423539898095244, "lm_q2_score": 0.04084571372074471, "lm_q1q2_score": 0.013243626284907425}}
{"text": "Aside: [https://nyti.ms/2k7phfy](https://nyti.ms/2k7phfy)\nAlso: [https://nyti.ms/2kbI2yn](https://nyti.ms/2kbI2yn)\n\n\n# Non-Proliferation and Safeguards\n\nThis unit covers discussions of nuclear non-proliferation and safeguards in the context of nuclear power and the nuclear fuel cycle. \n\n\n```python\nfrom IPython.display import IFrame\nIFrame(\"https://embed.polleverywhere.com/free_text_polls/LaKxXWF9y4JKkue?short_poll=true\", width=\"700\", height=\"400\")\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\nIFrame(\"https://embed.polleverywhere.com/multiple_choice_polls/YiHjKwlUd1Cit6s?short_poll=true\", width=\"700\", height=\"400\")\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\nIFrame(\"https://embed.polleverywhere.com/free_text_polls/lBcbliuSuQGKea6?short_poll=true\", width=\"700\", height=\"400\")\n```\n\n\n\n\n\n\n\n\n\n\n\nSource: [Huck Magazine Photography by Campaign for Nuclear Disarmament](https://www.huckmag.com/perspectives/activism-2/anti-nuclear-protest-art-will-stop-tracks/)\n\n## Learning Objectives\n\n\nAt the end of this lesson, you will be equipped to:\n\n- Recognize the position and history of movements against nuclear weapons.\n- List key events in the history of nuclear weapons.\n- Identify nuclear weapons states.\n- Characterize the agreements between nuclear weapons states.\n- Analyze the historical relationship between nuclear weapons and nuclear power.\n- Name the national and international agency primarily responsible for enforcing non-proliferation treaties.\n- Recognize methods used to enforce nuclear safeguards.\n- Calculate MUF .\n- Calculate $\\sigma_{MUF}$.\n- Calculate signficant quantities (SQ).\n- Recognize the role of uncertainty in IAEA safeguards.\n- Evaluate compliance with the three sigma limit ($MUF< 3\\sigma_{MUF}$)\n- Evaluate compliance with the cumulative MUF limit. ($MUF_c < 1 SQ$)\n- Apply knowledge of the NPT to current and recent events. \n- Discuss the failures of our nuclear weapons program (e.g. Bikini Atoll)\n\n\n\n## Art to Consider\n\n\n\n\n\n### Hiroshima survivor Hiroharu Kono\n\n\n\n\n### Yusaku Kamekura\n\n\n\n\n### A compendium of these\n\nhttps://www.huckmag.com/perspectives/activism-2/anti-nuclear-protest-art-will-stop-tracks/\n\n# How Did We Get Here?\n\n\n\n## The Making of the Atomic Bomb\n\nThe best way to learn about this topic is to read Richard Rhodes excellent book, The Making of The Atomic Bomb. \n\n\n\nHowever, let's summarize:\n\n### 1930 \nGerman nationalists acheive shocking election victory.\n\n\n### 1938 \nTheory of Nuclear Fission (Discovered on December 17,  1938 and explained theoretically in January 1939).\n\n\n\n\n### 1939\n Szilard and Wigner draft the Einstein-Szilard letter. \n\n<a title=\"Albert Einstein [Public domain], via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File%3AEinstein-Roosevelt-letter.png\"></a>\n\n### 1940 - 1946\nManhattan Project\n\nThe project to build the bomb was undertaken across many states in the US, with great secrecy.\n\n\n\nAt the University of Chicago, a group of scientists in the metallurgical laboratory (the Met Lab) were attempting to beat Heisenberg at attaining a controlled nuclear fission chain reaction. \n\n\n\n\n\n\n\n\n\n\n\n\n### July, 16 1945 \n\n- Trinity Nuclear Test\n- \"The Gadget\"/\"Fat Man\"\n  - 6.19-kilogram (13.6 lb) Pu\n  - Implosion type plutonium weapon\n  - energy equivalent of 22 kilotons of TNT (92 TJ)\n  \n<p><a href=\"https://commons.wikimedia.org/wiki/File:Fat_Man_Internal_Components.png#/media/File:Fat_Man_Internal_Components.png\"></a><br><a href=\"http://creativecommons.org/licenses/by-sa/3.0/\" title=\"Creative Commons Attribution-Share Alike 3.0\">CC BY-SA 3.0</a>, <a href=\"https://commons.wikimedia.org/w/index.php?curid=5257823\">This is a derivative of a John Coster-Mullen drawing on page 140 of the 2003 printing of his book, \"Atomic Bombs\"</a></p>\n  \n<a title=\"By Berlyn Brixner [Public domain], via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File%3ATrinity_Test_Fireball_16ms.jpg\">By Berlyn Brixner [Public domain], via Wikimedia Commons</a>\n\n\n\n### 8:15 a.m., August 6, 1945\n\n- Hiroshima\n- population 340,000 - 350,000\n- Enola Gay, B-29\n- \"Little Boy\"\n  - contained 64 kg (141 lb) of enriched uranium.\n  - less than 1 kg completely detonated.\n  - energy equivalent of 15 kilotons of TNT (63 TJ).\n  - gun type.\n- 70,000 people dead instantly. \n- 90,000\u2013166,000 after the first year. About 70% of the city's buildings were destroyed, and another 7% severely damaged.\n\n<a title=\"By US government DOD and/or DOE photograph [Public domain], via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File%3ALittle_boy.jpg\"></a>\n\n\n<p><a href=\"https://commons.wikimedia.org/wiki/File:Little_Boy_Internal_Components.png#/media/File:Little_Boy_Internal_Components.png\"></a><br><a href=\"http://www.gnu.org/copyleft/fdl.html\" title=\"GNU Free Documentation License\">GFDL</a>, <a href=\"https://commons.wikimedia.org/w/index.php?curid=5240437\">John Coster-Mullen, via Wikipedia</a></p>\n\n### 11:02 a.m., August 9, 1945\n\n\n- Nagasaki.\n- population 263,000\n- Bockscar, B-29\n- \"Fat Man\"\n  - contained 14 pounds (6.4 kg) Pu\n  - energy equivalent of 21 kilotons of TNT (88 TJ; 1 g mass equivalent)\n  - implosion type\n- 35,000 people were killed instantly\n- 39,000 - 80,000 by the end of 1945\n- Fireball temp 3,900 \u00b0C (7,050 \u00b0F) \n- Winds over 1,000 km/h (620 mph)\n\n<a title=\"By U.S. Department of Defense (U.S. Department of Defense) [Public domain], via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File%3AFat_man.jpg\"></a>\n\n### 6:45 a.m., March 1, 1954\n\n\n- Castle Bravo.\n- dry fuel hydrogen bomb\n- energy released: 15 megatons of TNT\n- vastly (2.5x) exceeded expected  4 to 8 megatons (because of an unexpectedly high involvement of lithium-7 in the fusion reaction)\n- shifting winds ---> greatest contamination every perpetrated by the U.S. \n- Japanese fishing boat (fishermen died, contaminated fish were sold)\n\n\n\n\n\n<p><a href=\"https://commons.wikimedia.org/wiki/File:Teller-Ulam_device.png#/media/File:Teller-Ulam_device.png\"></a><br>Public Domain, <a href=\"https://commons.wikimedia.org/w/index.php?curid=44858\">One possible version of the Teller\u2013Ulam configuration</a></p>\n\n\n```python\nIFrame(\"https://www.youtube.com/embed/C4LqqA4GdsY\", width=\"700\", height=\"400\",frameborder=\"0\")\n```\n\n\n\n\n\n\n\n\n\n\n### 11:32 a.m. October 30, 1961\n\n- Tsar Bomba / Ivan / Vanya (in Russia, one of George Carlin's Words You Can't Say on Television)\n- Soviet RDS-220, three-stage hydrogen bomb\n  - 2nd/3rd stages had 238U \"tamper\" to reduce fast fissions & fallout\n  - 97% of the total yield resulted from thermonuclear fusion\n  - energy released: 50 megaton TNT (210 PJ)\n\n\n<a title=\"By Fastfission [Public domain], via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File%3AComparative_nuclear_fireball_sizes.svg\"></a>\n\n<p><a href=\"https://en.wikipedia.org/wiki/File:Tsar01.jpg#/media/File:Tsar01.jpg\"></a><br>By <a rel=\"nofollow\" class=\"external free\" href=\"https://web.archive.org/web/20080518004931/http://www.atomicforum.org/russia/tsarbomba.html\">https://web.archive.org/web/20080518004931/http://www.atomicforum.org/russia/tsarbomba.html</a>, Fair use, <a href=\"https://en.wikipedia.org/w/index.php?curid=16874909\">The Tsar Bomba fireball. From [http://www.atomicforum.org/russia/tsarbomba.html] {{Non-free historic image}} == Fair use for Tsar Bomba and History of the Teller\u2013Ulam design </a></p>\n\n\n<p><a href=\"https://commons.wikimedia.org/wiki/File:Tsar_Bomba_Paris.png#/media/File:Tsar_Bomba_Paris.png\"></a><br>By <a href=\"//commons.wikimedia.org/wiki/User:Bourrichon\" title=\"User:Bourrichon\">Bourrichon</a> - Own work based on numbers from the <a href=\"https://fr.wikipedia.org/wiki/Tsar_Bomba\" class=\"extiw\" title=\"fr:Tsar Bomba\">fr-Wikipedia article</a> on <a href=\"//commons.wikimedia.org/wiki/File:Paris.landsat.arp.750pix.jpg\" title=\"File:Paris.landsat.arp.750pix.jpg\">a NASA map</a>., <a href=\"https://creativecommons.org/licenses/by-sa/3.0\" title=\"Creative Commons Attribution-Share Alike 3.0\">CC BY-SA 3.0</a>, <a href=\"https://commons.wikimedia.org/w/index.php?curid=3986378\">Tsar Bomba total destruction radius, superimposed on Paris.</a></p>\n\n### October 16\u201328, 1962 \nCuban Missile Crisis. The US, led by Kennedy, had strained relations with the Soviet Union, led by Khruschev. US Navy blocked missile shipments to Cuba. \nEventaully, the standoff resulted in \n- Removal of the Soviet Union's nuclear missiles from Cuba\n- Removal of American nuclear missiles from Turkey and Italy\n- Agreement with the Soviet Union that the United States would never invade Cuba without direct provocation\n- Creation of a nuclear hotline between the United States and the Soviet Union\n\n### 1963\nPartial test ban treaty. The Partial Test Ban Treaty (PTBT) is officially the 1963 Treaty Banning Nuclear Weapon Tests in the Atmosphere, in Outer Space and Under Water, which prohibited all test detonations of nuclear weapons except for those conducted underground. \n\n\n## 1970 : NPT\n\nOpened for signature in 1968, the treaty entered into force in 1970\n\n\nThe goals of the NPT were to: \n\n- Prevent the spread of nuclear weapons\n- Promote cooperation in peaceful uses of nuclear technology\n- Acheive nuclear disarmament\n\nAccordingly: \n\n- Countries with weapons (UK, US, USSR, France, China) agree not to share.\n- Countries without nuclear weapons promised not to develop them in return for nuclear power technology.\n- Those that already have weapons agreed to disarm. (Article 6: Countries must \"negotiate in good faith.\")\n\nNPT is reviewed annually. \n\n### Membership\n\n<p><a href=\"https://commons.wikimedia.org/wiki/File:NPT_parties.svg#/media/File:NPT_parties.svg\"></a><br>By <a href=\"//commons.wikimedia.org/wiki/File:NPT_Participation.svg\" title=\"File:NPT Participation.svg\">File:NPT Participation.svg</a>: <a href=\"//commons.wikimedia.org/wiki/User:Allstar86\" title=\"User:Allstar86\">Allstar86</a>, <a href=\"//commons.wikimedia.org/wiki/User:L.tak\" title=\"User:L.tak\">L.tak</a>, <a href=\"//commons.wikimedia.org/w/index.php?title=User:Danlaycock&amp;action=edit&amp;redlink=1\" class=\"new\" title=\"User:Danlaycock (page does not exist)\">Danlaycock</a>\nderivative work: <a href=\"//commons.wikimedia.org/w/index.php?title=User:Danlaycock&amp;action=edit&amp;redlink=1\" class=\"new\" title=\"User:Danlaycock (page does not exist)\">Danlaycock</a> - This file was derived from:\n&nbsp;<a href=\"//commons.wikimedia.org/wiki/File:NPT_Participation.svg\" title=\"File:NPT Participation.svg\">NPT Participation.svg</a>, <a href=\"http://creativecommons.org/licenses/by-sa/3.0\" title=\"Creative Commons Attribution-Share Alike 3.0\">CC BY-SA 3.0</a>, <a href=\"https://commons.wikimedia.org/w/index.php?curid=31123238\">Link</a></p>\n\n\n\n\n#### Renegged\nOnly North Korea has backed out of their agreement. \n\n\n#### Never signed\n\nIndian, Pakistan, and Israel never joined. All three now have weapons. \n\n\n\n\n### 1996 \n\nComprehensive Test Ban Treaty\n\n<a title=\"By derivative work: Allstar86 (talk) BlankMap-World6,_compact.svg: Canuckguy et al. (BlankMap-World6,_compact.svg) [CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0) or GFDL (http://www.gnu.org/copyleft/fdl.html)], via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File%3ACTBT_Participation.svg\"></a>\n\n\n\n\n## Megatons to Megawatts (1993 - 2003)\n\n- **20** year program\n- **500 tons** of HEU (**90%** enriched)\n- Soviet era warheads -> downblended to $<5\\%$ enriched \n- To be implemented on commercial terms without government funds. \n  - United States named Enrichment Corporation (USEC) as the commercial agent\n  - the Russian Federation designated Techsnabexport (TENEX) as its commercial agent.\n- The first shipment of LEU took place in May 1995.\n\n\n\n\n\n**Practice: Can You prove this is an accurate statement?**\n\n\nThink back to enrichment. This is another feed factor problem. \n\n\\begin{align}\nx_p &= 0.05\\\\\nx_w &= 0.002\\\\\nx_f &= 0.9\\\\\n\\end{align}\n\nThus, we can find the feed factor (kg feed per kg enriched):\n\n\\begin{align}\nFF &= \\frac{F}{P}\\\\\n   &= \\frac{x_p - x_w}{x_f - x_w}\\\\\n   &= \\frac{0.05 - 0.002}{0.9 - 0.002}\\\\\n   & \\\\\n   &= 0.0535\n\\end{align}\n\nWe also know the amount of feed, F, was 500 tons.\n\n\\begin{align}\nFF = \\frac{F}{P}\\\\\nFF = 0.05\\\\\nF = 5.0\\times 10^5\\\\\n\\end{align}\n\n\n```python\nF = 500000 # kg\nx_p = 0.05  # sold to US\nx_w = 0.002 # depleted U\nx_f = 0.9   # feed from  HEU\n\ndef ff(x_p, x_w, x_f):\n    num = x_p - x_w\n    denom = x_f - x_w\n    return num/denom\n\nprint(ff(x_p, x_w, x_f), \n      \" kg of the HEU are needed to produce 1kg fuel.\")\nprint(\"Therefore, \",1/ff(x_p, x_w, x_f),\n      \" kg of the new will be produced per kg of HEU\")\nprint(\"Therefore, \",F/ff(x_p, x_w, x_f),\n      \" kg of the new low enriched uranium was produced\")      \n\n```\n\n    0.053452115812917596  kg of the HEU are needed to produce 1kg fuel.\n    Therefore,  18.708333333333332  kg of the new will be produced per kg of HEU\n    Therefore,  9354166.666666666  kg of the new low enriched uranium was produced\n\n\nNow, based on our fuel utilization discussions, how many MWh is that?\n\n\\begin{align}\nM = \\frac{Q}{BU}\\\\\nQ = \\frac{P_0 \\cdot CF \\cdot T}{\\eta_{th}}\\\\\n\\end{align}\n\nWe want to solve for $P_0\\cdot CF \\cdot T$, which will be in units of MWd (and we can convert to MWh.)\n\\begin{align}\n\\Rightarrow &M = \\frac{P_0 \\cdot CF \\cdot T}{\\eta_{th}BU}\\\\\n\\Rightarrow &M \\eta_{th} BU = P_0 \\cdot CF \\cdot T\\\\\n\\Rightarrow &P_0 \\cdot CF \\cdot T [MWh] = M\\eta_{th}BU[MWd]\\times 24 \\left[\\frac{h}{d}\\right]  \\\\\n\\end{align}\n\n\nSo, let's assume some typical values appropriate for 5% enriched fuel (this will give high-ish burnups).\n\n\\begin{align}\n\\eta_{th} = 0.33\\mbox{ [MWe/MWth]}\\\\ \nBU = 50000\\mbox{ [MWd/ton] } = 50 \\mbox{ [MWd/kg] }\\\\\n\\end{align}\n\n\n```python\nM = F/ff(x_p, x_w, x_f)\neta = 0.33\nh_per_d = 24\nbu = 50\n\nPCFT = M*eta*bu*h_per_d\nprint(\"And finally, the program produced \",'%e' % PCFT, \" MWh.\")\n```\n\n    And finally, the program produced  3.704250e+09  MWh.\n\n\n### 2003 North Korea pulls out of NPT\nThe DPRK became the first country to pull out of the NPT under Article X.\n\nBegan a series of nuclear weapons tests in October 2006. They conducted a total of 6 tests between 2006 and 2017,\nall of them being underground tests. One of the explosions was claimed to be a Hydrogrn bomb. \n\n### 2011 New START Treaty goes into effect\nPart of START Treaty series between the US and Russia that bagen in 1991. New START \ninitially was a 10 year agreement and was renewed for another 5 years in Jan/Feb 2021. \nTreaty expires February 4, 2026\n\nLimits the number of strategic weapons that each party can have\n- 700 deployed ICBMs, deployed SLBM, and deployed heavy bombers \n- 1550 warheads deployed on ICBMs, SLBM, and bombers (each bomber counts as 1 warhead)\n- 800 deployed and non-deployed ICBM launchers, SLBM launchers, and heavy bombers\n\nAllows each party to conduct inspections of the other parties stockpiles\n- 18 on-site inspections a year\n- Biannual data exchanges -- numbers and locations\n\n### 2015 Iran and the Joint Comprehensive Plan of Action (JCPOA)\nMultiple concerns over Iran developing a clandestine nuclear weapons program (and yes, \nIran has signed and ratified the NPT). A history of Iran's nuclear history has been \n[written by NTI](https://www.nti.org/learn/countries/iran/nuclear/). \nLarge concern over their enrichment program. \nMultiple sanctions were imposed on Iran by the US, the UN, and the EU. \n\nDeveloped JCPOA between Iran, US, China, Russia, UK, France, and Germany\n- Limits enrichment levels and types of centrifuges\n- Limits stockpiles of LEU\n\n#### 2018: The US pulled out of the agreement. \nSince then Iran has increased their enrichment levels,\nmost recently [reaching 60% U-235](https://apnews.com/article/iran-uranium-enrichment-60-percent-ed89e322595004fddc65fd4e31c1131b).\n\n#### 2020/2021: \n- [Top Iran Nuclear Scientist killed](https://www.reuters.com/article/us-iran-nuclear-scientist/iranian-nuclear-scientist-killed-by-one-ton-automated-gun-in-israeli-hit-jewish-chronicle-idUSKBN2AA2RC)\n- [Cyber Attach on Natanz](https://apnews.com/article/world-news-israel-iran-62a7aa3182992ed0f97b5486d71280c2)\n- US is currently trying to re-enter the JCPOA \n\n\n### 2019 Nenoksa Accident\nRussian nuclear missile test site had an accident that killed 5 people. Russian \ngovernment tried to pass it off as a fire and explosion after a \"test of a liquid \npropellant jet engine\". Later, officials at the lab came out that the scientists \nwere looking into creating small-scale energy sources using fissile materials, \nsimilar to NASA's KiloPower project\n\n### Sensitive Points in the Fuel Cycle \nBased on what you know about the nuclear fuel cycle and nuclear weapons, what are parts of the \nfuel cycle that are sensative to proliferation? What areas would we be more concerned about \nproliferation occurring?\n\n#  IAEA, Safeguards, MUF, SQ, Etc.\n\n\nPlease note, the remainder of this lecture is a compilation of material from the following two sources.\n\n- [Nuclear 101: How IAEA Safeguards Work. Matthew Bunn.](https://www.youtube.com/watch?v=hQ-WSC-D-yw&index=1&list=PLp1QSxtgPnf49U1tLv15Mmq8sC-eyuBk9).\n- [NSSPI at TAMU](http://nsspi.tamu.edu/)\n- [Jake Vanderplas' AstroHackWeek intro to stats](https://github.com/AstroHackWeek/AstroHackWeek2014/blob/d172aae2736294d1fb61893f774cc6de0112ad7a/day2/ClassicalStatsPython.ipynb)\n\n## IAEA\nFacts about the IAEA. \n\n- What is it?\n- Where is it?\n- Why is it?\n- Who is it?\n- Who leads it?\n- Who works there?\n- When did it start?\n\n\n\n[https://www.iaea.org/sites/default/files/16/07/iaeaataglance0316.pdf](https://www.iaea.org/sites/default/files/16/07/iaeaataglance0316.pdf)\n- Year Founded : 1957\n- Member States 168\n- Number of Employees ca. 2,500\n- Laboratories 14\n- Headquarters Vienna, Austria\n- Liaison Offices \n  - Geneva, Switzerland\n  - New York, USA\n- Regional Offices \n  - Toronto, Canada\n  - Tokyo, Japan\n- Laboratories\n  - Seibersdorf, Austria\n  - Monaco\n  - Triste, Italy\n- Regular Budget : \u20ac359.3 million ($431.37 million)\n\n> In 2015, 709 facilities and 577 locations outside facilities in 181 States were under IAEA safeguards, making them subject to verification by IAEA inspectors. IAEA inspectors performed 2118 inspections, spending a total of 13 248 calendar days in the field.\n\nBeing a safeguards inspector may be a job of interest for some of you. I encourage you to read through this: [https://www.iaea.org/newscenter/news/a-day-in-the-life-of-a-safeguards-inspector](https://www.iaea.org/newscenter/news/a-day-in-the-life-of-a-safeguards-inspector).\n\n\n\n\n\n## Material Accountancy\n\n\n```python\nIFrame(\"http://nsspi-nssep.org/nssep/reference/technical-safeguards-terminology/purpose%2c-objective%2c-and-scope-of-iaea-safeguards.html\", width=1000, height=1000)\n```\n\n\n\n\n\n\n\n\n\n\n### Significant Quantities\nDirect use nuclear material\n\n|  Material    |  SQ       |\n|--------|---------|\n| Pu    | \t8 kg  Pu | \n| 233U\t | 8 kg  233U |\n| HEU (235U $\\ge$ 20%) | \t25 kg 235U |  \n\nIndirect use nuclear material\n\n|  Material    |  SQ       |\n|--------|---------|\n| U(235U < 20%) |\t75 kg 235U | \n| Natural U | 10 t |\n| Depleted U | 20t |\n| Th\t| 20 t  Th |\n\n\n### Example: Significant Quantity\n\nA small nuclear nation purchases, on the black market, 35 kg of 40% enriched uranium. How many significant quantities is that?\n\n\n```python\n0.4*35/25\n```\n\n\n\n\n    0.56\n\n\n\n### Aside: Other nuclear materials\n\nWhat materials might the IAEA also watch?\n\n## Containment and Surveillance\n \nSo that the IAEA needs not re-inspect unaltered materials, a typical method is to contain and label that material with tamper-resistant labels or to apply surveillance to the facility.\n\n#### Containment\n\n\n\n### Surveillance\n\n\n\n## Material Unaccounted For\n\n\nThe material unaccounted for is what we worry about. It may have been diverted by a **nefarious actor**.\n\nThis is often written simply as the \"book inventory\" minus the \"ending physical inventory.\"\n\n\\begin{align}\nMUF &= BI - PE\\\\\n\\end{align}\n\nThe book inventory is just the inventory in the beginning (or last time IAEA made an assessment) plus anything that was added and minus anything that was removed. \n\n\\begin{align}\nBI &= (PB + X - Y)\\\\\nMUF &= (PB + X - Y) - PE\\\\\nPB &= \\mbox{Beginning Physical inventory}\\\\\nX &= \\mbox{Increases to inventory}\\\\\nY &= \\mbox{Removal from inventory}\\\\\nPE &= \\mbox{Ending Physical inventory}\\\\\n\\end{align}\n\n\n### Stream Diversion\n\n**ASIDE: Hanford example.**\n\nWhile MUF at each individual inspection may not be a signficant quantity, the sum might be. \n\n\\begin{align}\nMUF_c = \\sum_{t=t_i}^{t=t_f} MUF_t\n\\end{align}\n\n### Item v. Bulk Material Accounting\n\nFor item based accounting one counts the **number** of things (assemblies, containers with tags), so MUF should be an integer. If $MUF \\ne 0$, either:\n\n- there has been an accounting error\n- there has been some diversion of items\n\nFor bulk accounting, the MUF is rarely exactly zero. No detector is perfect, but also the processing of fluids, powders, gases, and other bulk masses is inherently lossy. So, it is important in this case to quantify the uncertainty in the material balance.\n\n\\begin{align}\n\\sigma_{MUF} = \\mbox{uncertainty of MUF}\\\\\n\\end{align}\n\n### Constraints\n\nThe two following constraints are important red flags.\n\\begin{align}\nMUF< 3\\sigma_{MUF}\\\\\nMUF_c < 1 SQ\n\\end{align}\n\n\n## Measurement uncertainties\n\n**No detector is perfect** \n\nSo, let's talk statistics. \n\n### Sampling\n\n\n\n\n#### Mean\n\nThe mean is easy:\n\n\\begin{align}\n\\bar{x} = \\frac{1}{N}\\sum_{n=1}^{N}x_n\n\\end{align}\n\n\n\n#### Standard deviation:\n\nFirst, we describe the experimental variance ($\\sigma^2$). The standard deviation is the square root of the variance.\n\n\\begin{align}\n\\sigma = \\sqrt{\\frac{1}{N-1}\\sum_{i-1}^{N}(x_i -\\bar{x})^2}\n\\end{align}\n\nThe relative standard deviation, S, is normalized by the mean:\n\n\\begin{align}\nS = \\frac{\\sigma}{\\bar{x}} = \\frac{\\sqrt{\\frac{1}{N-1}\\sum_{i-1}^{N}(x_i -\\bar{x})^2}}{\\bar{x}}\n\\end{align}\n\n\n#### Uncertainty\n\nThe measured value ($\\bar{x}$) and the true value (T) differ because of uncertainty. First, there is random error, $\\epsilon$. Second, there is systematic error, $\\Delta$. These can be either negative or positive.\n\n\\begin{align}\n\\bar{x} = T + \\epsilon + \\Delta\n\\end{align}\n\nTo model this, we can relate these errors back to the standard deviation, such that:\n\n\\begin{align}\n\\sigma^2 = \\sigma_r^2 + \\sigma_s^2\n\\end{align}\n\n### Example: MUF Uncertainty\n\nYou are an inspector responsible for Pu balance in a specific MBA (material balance area) at LaHague.\n\n**On January 1,** \n- You measure 57kg of separated Pu.\n- You tag the containers with tamper-resistant seals.\n\n**On February 1,** \n- Two tagged containers (5kg total) are missing. Areva provides evidence they were sent to MOX fuel fabrication.\n- One new untagged container has appeared.\n- Their accounts say 100kg of spent fuel entered the facility in January and 1kg Pu was separated into the new container. \n- 99kg of non-Pu spent fuel remainder is present.\n\n**What is the book inventory for just Pu?**\n\n\n```python\n\nPB = 57\nX = 1\nY = 5\nBI = PB + X - Y \n\nprint(BI)\n```\n\n    53\n\n\nTo determine the MUF, you take 10 readings of the new canister and you get the following results for its contained Pu amount:\n\nm = [1.30, 1.045, 1.012, 0.988, 0.998, 1.051, 1.087, 0.960, 0.91, 1.11]\n\n\n\n```python\nimport math\nm = [1.30, 1.045, 1.012, 0.988, 0.998, 1.051, 1.087, 0.960, 0.91, 1.11]\n\ndef mean(m):\n    return sum(m)/len(m)\n\ndef var(m):\n    dif = 0\n    for i in m:\n        dif += pow(i-mean(m), 2)\n    sig_sq = dif/(len(m)-1)\n    sig = math.sqrt(sig_sq)\n    return sig\n\ndef lim_sig(var, muf):\n    return (3*var < muf)\n\nprint(\"Mean of measurements: \", mean(m))\nmuf = abs(mean(m) - (BI - 52))\nprint(\"MUF : \", muf)\nprint('Has the 3sig limit been hit? ', lim_sig(var(m),muf))\n\n```\n\n    Mean of measurements:  1.0460999999999998\n    MUF :  0.04609999999999981\n    Has the 3sig limit been hit?  False\n\n\nLet's say this kind of MUF value happens every month due to a diversion. **How many months until we hit the MUF_c limit?**\n\n\n\n\n```python\npu_lim = 8 #kg\nprint(\"If MUF is due to diversion, the MUF_c limit will be struck in \", pu_lim/muf, \"months\")\n```\n\n    If MUF is due to diversion, the MUF_c limit will be struck in  173.53579175705062 months\n\n\n### Number of measurements needed\n\nOkay, so we stated before that we're sortof confident in our measurement. How many samples does one have to take to draw appropriate conclusions. \n\n\\begin{align}\nn &= N\\left( 1 - \\beta^{x/M}\\right)\\\\\nn &= \\mbox{number of samples per item}\\\\\nN &= \\mbox{number of items per facility}\\\\\n\\beta &= \\mbox{non-detection probability}\\\\\nx &= \\mbox{average nuclear material weight}\\\\\nM &= \\mbox{mass detection goal}\\\\\n\\end{align}\n\n\n```python\n# Imagine a facility with 100 cans of Pu\nN = 100 # PuOx cans\nx = 1.0 # kg Pu per can\n\n# How confident do we need to be?\nbeta = 0.2 #80% confidence\nM = 8 #kg Pu, (1SQ)\n\ndef n(items, beta, x, M):\n    return items*(1 - pow(beta, x/M))\n\nn(N, beta, x, M)\n```\n\n\n\n\n    18.223456604205744\n\n\n\n\n## Wrap-Up\n\nAt the end of this lesson, you should be equipped to:\n\n- Recognize the position and history of movements against nuclear weapons.\n- List key events in the history of nuclear weapons.\n- Identify nuclear weapons states.\n- Characterize the agreements between nuclear weapons states.\n- Analyze the historical relationship between nuclear weapons and nuclear power.\n- Name the national and international agency primarily responsible for enforcing non-proliferation treaties.\n- Recognize methods used to enforce nuclear safeguards.\n- Calculate MUF .\n- Calculate $\\sigma_{MUF}$.\n- Calculate signficant quantities (SQ).\n- Recognize the role of uncertainty in IAEA safeguards.\n- Evaluate compliance with the three sigma limit ($MUF< 3\\sigma_{MUF}$)\n- Evaluate compliance with the cumulative MUF limit. ($MUF_c < 1 SQ$)\n- Apply knowledge of the NPT to current and recent events. \n- Discuss the failures of our nuclear weapons program (e.g. Bikini Atoll)\n\n\n\n```python\nfrom IPython.core.display import HTML\nHTML(\"\"\"<video controls src=\"{0}\" loop=1 autoplay width=100%/>\"\"\".format('https://img.buzzfeed.com/buzzfeed-static/static/2014-07/3/11/enhanced/webdr04/anigif_enhanced-buzz-21275-1404402138-31.gif?output-format=mp4'))\n\n```\n\n\n\n\n<video controls src=\"https://img.buzzfeed.com/buzzfeed-static/static/2014-07/3/11/enhanced/webdr04/anigif_enhanced-buzz-21275-1404402138-31.gif?output-format=mp4\" loop=1 autoplay width=100%/>\n\n\n", "meta": {"hexsha": "2a2c9ea0ab8b20cf52a74fe7df93824ce91b2b4f", "size": 46573, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "nonproliferation-and-safeguards/nonpro-and-safeguards.ipynb", "max_stars_repo_name": "abachma2/npre412", "max_stars_repo_head_hexsha": "3f105a15edc07745f1dd65cd791777a01136ec23", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nonproliferation-and-safeguards/nonpro-and-safeguards.ipynb", "max_issues_repo_name": "abachma2/npre412", "max_issues_repo_head_hexsha": "3f105a15edc07745f1dd65cd791777a01136ec23", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nonproliferation-and-safeguards/nonpro-and-safeguards.ipynb", "max_forks_repo_name": "abachma2/npre412", "max_forks_repo_head_hexsha": "3f105a15edc07745f1dd65cd791777a01136ec23", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5692438403, "max_line_length": 900, "alphanum_fraction": 0.6024950078, "converted": true, "num_tokens": 7549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08035747542939525, "lm_q2_score": 0.1645164628965632, "lm_q1q2_score": 0.013220127624941591}}
{"text": "<a href=\"https://colab.research.google.com/github/AlanLopez1017/deep-learning-v2-pytorch/blob/master/PyTorch_preliminares.ipynb\" target=\"_parent\"></a>\n\n\n```python\nfrom google.colab import drive\ndrive._mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```python\nimport os\nos.chdir('./drive/MyDrive/Python/PyTorch')\n```\n\n\n```python\npwd\n```\n\n\n\n\n    '/content/drive/MyDrive/Python/PyTorch'\n\n\n\n\n```python\npip install d2l\n```\n\n    Collecting d2l\n      Downloading d2l-0.17.1-py3-none-any.whl (82 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 82 kB 613 kB/s \n    \u001b[?25hCollecting numpy==1.18.5\n      Downloading numpy-1.18.5-cp37-cp37m-manylinux1_x86_64.whl (20.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 20.1 MB 1.4 MB/s \n    \u001b[?25hCollecting pandas==1.2.2\n      Downloading pandas-1.2.2-cp37-cp37m-manylinux1_x86_64.whl (9.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 9.9 MB 56.1 MB/s \n    \u001b[?25hRequirement already satisfied: jupyter==1.0.0 in /usr/local/lib/python3.7/dist-packages (from d2l) (1.0.0)\n    Collecting matplotlib==3.3.3\n      Downloading matplotlib-3.3.3-cp37-cp37m-manylinux1_x86_64.whl (11.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 11.6 MB 46.4 MB/s \n    \u001b[?25hCollecting requests==2.25.1\n      Downloading requests-2.25.1-py2.py3-none-any.whl (61 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 61 kB 8.8 MB/s \n    \u001b[?25hRequirement already satisfied: ipykernel in /usr/local/lib/python3.7/dist-packages (from jupyter==1.0.0->d2l) (4.10.1)\n    Requirement already satisfied: nbconvert in /usr/local/lib/python3.7/dist-packages (from jupyter==1.0.0->d2l) (5.6.1)\n    Requirement already satisfied: jupyter-console in /usr/local/lib/python3.7/dist-packages (from jupyter==1.0.0->d2l) (5.2.0)\n    Requirement already satisfied: notebook in /usr/local/lib/python3.7/dist-packages (from jupyter==1.0.0->d2l) (5.3.1)\n    Requirement already satisfied: ipywidgets in /usr/local/lib/python3.7/dist-packages (from jupyter==1.0.0->d2l) (7.6.5)\n    Requirement already satisfied: qtconsole in /usr/local/lib/python3.7/dist-packages (from jupyter==1.0.0->d2l) (5.2.2)\n    Requirement already satisfied: pillow>=6.2.0 in /usr/local/lib/python3.7/dist-packages (from matplotlib==3.3.3->d2l) (7.1.2)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib==3.3.3->d2l) (2.8.2)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3 in /usr/local/lib/python3.7/dist-packages (from matplotlib==3.3.3->d2l) (3.0.6)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib==3.3.3->d2l) (0.11.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib==3.3.3->d2l) (1.3.2)\n    Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas==1.2.2->d2l) (2018.9)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests==2.25.1->d2l) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests==2.25.1->d2l) (2021.10.8)\n    Requirement already satisfied: chardet<5,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests==2.25.1->d2l) (3.0.4)\n    Requirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests==2.25.1->d2l) (1.24.3)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.1->matplotlib==3.3.3->d2l) (1.15.0)\n    Requirement already satisfied: tornado>=4.0 in /usr/local/lib/python3.7/dist-packages (from ipykernel->jupyter==1.0.0->d2l) (5.1.1)\n    Requirement already satisfied: jupyter-client in /usr/local/lib/python3.7/dist-packages (from ipykernel->jupyter==1.0.0->d2l) (5.3.5)\n    Requirement already satisfied: ipython>=4.0.0 in /usr/local/lib/python3.7/dist-packages (from ipykernel->jupyter==1.0.0->d2l) (5.5.0)\n    Requirement already satisfied: traitlets>=4.1.0 in /usr/local/lib/python3.7/dist-packages (from ipykernel->jupyter==1.0.0->d2l) (5.1.1)\n    Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipykernel->jupyter==1.0.0->d2l) (1.0.18)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipykernel->jupyter==1.0.0->d2l) (4.4.2)\n    Requirement already satisfied: pygments in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipykernel->jupyter==1.0.0->d2l) (2.6.1)\n    Requirement already satisfied: pexpect in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipykernel->jupyter==1.0.0->d2l) (4.8.0)\n    Requirement already satisfied: pickleshare in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipykernel->jupyter==1.0.0->d2l) (0.7.5)\n    Requirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipykernel->jupyter==1.0.0->d2l) (0.8.1)\n    Requirement already satisfied: setuptools>=18.5 in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipykernel->jupyter==1.0.0->d2l) (57.4.0)\n    Requirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython>=4.0.0->ipykernel->jupyter==1.0.0->d2l) (0.2.5)\n    Requirement already satisfied: widgetsnbextension~=3.5.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->jupyter==1.0.0->d2l) (3.5.2)\n    Requirement already satisfied: jupyterlab-widgets>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->jupyter==1.0.0->d2l) (1.0.2)\n    Requirement already satisfied: nbformat>=4.2.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->jupyter==1.0.0->d2l) (5.1.3)\n    Requirement already satisfied: ipython-genutils~=0.2.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->jupyter==1.0.0->d2l) (0.2.0)\n    Requirement already satisfied: jsonschema!=2.5.0,>=2.4 in /usr/local/lib/python3.7/dist-packages (from nbformat>=4.2.0->ipywidgets->jupyter==1.0.0->d2l) (2.6.0)\n    Requirement already satisfied: jupyter-core in /usr/local/lib/python3.7/dist-packages (from nbformat>=4.2.0->ipywidgets->jupyter==1.0.0->d2l) (4.9.1)\n    Requirement already satisfied: Send2Trash in /usr/local/lib/python3.7/dist-packages (from notebook->jupyter==1.0.0->d2l) (1.8.0)\n    Requirement already satisfied: jinja2 in /usr/local/lib/python3.7/dist-packages (from notebook->jupyter==1.0.0->d2l) (2.11.3)\n    Requirement already satisfied: terminado>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from notebook->jupyter==1.0.0->d2l) (0.12.1)\n    Requirement already satisfied: pyzmq>=13 in /usr/local/lib/python3.7/dist-packages (from jupyter-client->ipykernel->jupyter==1.0.0->d2l) (22.3.0)\n    Requirement already satisfied: ptyprocess in /usr/local/lib/python3.7/dist-packages (from terminado>=0.8.1->notebook->jupyter==1.0.0->d2l) (0.7.0)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2->notebook->jupyter==1.0.0->d2l) (2.0.1)\n    Requirement already satisfied: mistune<2,>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert->jupyter==1.0.0->d2l) (0.8.4)\n    Requirement already satisfied: entrypoints>=0.2.2 in /usr/local/lib/python3.7/dist-packages (from nbconvert->jupyter==1.0.0->d2l) (0.3)\n    Requirement already satisfied: pandocfilters>=1.4.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert->jupyter==1.0.0->d2l) (1.5.0)\n    Requirement already satisfied: testpath in /usr/local/lib/python3.7/dist-packages (from nbconvert->jupyter==1.0.0->d2l) (0.5.0)\n    Requirement already satisfied: bleach in /usr/local/lib/python3.7/dist-packages (from nbconvert->jupyter==1.0.0->d2l) (4.1.0)\n    Requirement already satisfied: defusedxml in /usr/local/lib/python3.7/dist-packages (from nbconvert->jupyter==1.0.0->d2l) (0.7.1)\n    Requirement already satisfied: webencodings in /usr/local/lib/python3.7/dist-packages (from bleach->nbconvert->jupyter==1.0.0->d2l) (0.5.1)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from bleach->nbconvert->jupyter==1.0.0->d2l) (21.3)\n    Requirement already satisfied: qtpy in /usr/local/lib/python3.7/dist-packages (from qtconsole->jupyter==1.0.0->d2l) (2.0.0)\n    Installing collected packages: numpy, requests, pandas, matplotlib, d2l\n      Attempting uninstall: numpy\n        Found existing installation: numpy 1.19.5\n        Uninstalling numpy-1.19.5:\n          Successfully uninstalled numpy-1.19.5\n      Attempting uninstall: requests\n        Found existing installation: requests 2.23.0\n        Uninstalling requests-2.23.0:\n          Successfully uninstalled requests-2.23.0\n      Attempting uninstall: pandas\n        Found existing installation: pandas 1.1.5\n        Uninstalling pandas-1.1.5:\n          Successfully uninstalled pandas-1.1.5\n      Attempting uninstall: matplotlib\n        Found existing installation: matplotlib 3.2.2\n        Uninstalling matplotlib-3.2.2:\n          Successfully uninstalled matplotlib-3.2.2\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    google-colab 1.0.0 requires pandas~=1.1.0; python_version >= \"3.0\", but you have pandas 1.2.2 which is incompatible.\n    google-colab 1.0.0 requires requests~=2.23.0, but you have requests 2.25.1 which is incompatible.\n    datascience 0.10.6 requires folium==0.2.1, but you have folium 0.8.3 which is incompatible.\n    albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Successfully installed d2l-0.17.1 matplotlib-3.3.3 numpy-1.18.5 pandas-1.2.2 requests-2.25.1\n\n\n\n\n# Manipulaci\u00f3n de datos\nEs importante saber como almacenar y manipular datos. Hay dos aspectos relevantes que tenemos que hacer con ellos:\n* Adquisici\u00f3n\n* Procesamiento cuando se encuentren en la computadora\n\nPara adquirir datos es necesario saber almacenarlos, es por eso que una matriz n-dimensional o tambi\u00e9n llamado tensor nos ser\u00e1 de ayuda.\n\n## Inicio\nPara comenzar se debe importar la librer\u00eda Torch:\n\n\n\n```python\nimport torch\n```\n\nUn tensor representa un arreglo de valores n\u00famericos, siendo probablemente multidimensional. De acuerdo a su n\u00famero de ejes se denomina de las siguientes formas:\n- 1 eje: vector\n- 2 ejes: Matrix\n- k > 2 ejes: $k^{th}$ tensor de orden \n\nPyTorch presenta ya funciones para la creaci\u00f3n de nuevos tensores con ciertos valores.\n\nEjemplo:\nCon arange(n) se puede crear un vector de valores uniformes, que empiece en 0 (lo incluye) y termine en n (no lo incluye).\n\nPor defecto, el tama\u00f1o del intervalo es 1. Los nuevos tensores se almacenan en la memoria principal y se designan para el c\u00e1lculo basado en la CPU.\n\n\n\n```python\nx = torch.arange(12,dtype = torch.float32)\nx\n```\n\n\n\n\n    tensor([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11.])\n\n\n\nPodemos conocer la forma de un tensor, es decir, la longitud a trav\u00e9s de cada eje, mediante la propiedad _shape_.\n\n\n\n\n```python\nx.shape\n```\n\n\n\n\n    torch.Size([12])\n\n\n\nSi lo que queremos es conocer el n\u00famero total de elementos de un tensor, o visto de otra forma, el producto de los elementos de la forma, cuando se trata de un vector, tiene un s\u00f3lo elemento en la forma como se pudo observar, y en este caso, es igual a su tama\u00f1o (total de elementos del tensor):\n\n\n\n```python\nx.numel()\n```\n\n\n\n\n    12\n\n\n\nSi deseamos cambiar la forma de un tensor sin modificar el n\u00famero de elementos ni sus valores, podemos usar la funci\u00f3n _reshape_.\n\nEl vector x con forma (12,) que se ha utilizado se puede transformar en una matriz con forma (3,4). Este nuevo vector tendr\u00eda los mismos valores pero organizados en 3 filas y 4 columnas. La forma cambi\u00f3, no obstante, los elementos no:\n\n\n```python\nX = x.reshape(3,4)\nX\n```\n\n\n\n\n    tensor([[ 0.,  1.,  2.,  3.],\n            [ 4.,  5.,  6.,  7.],\n            [ 8.,  9., 10., 11.]])\n\n\n\nLos tensores pueden calcular de forma autom\u00e1tica una dimensi\u00f3n a partir de las dem\u00e1s. En el ejemplo anterior, si la matriz objetivo ten\u00eda forma (altura, ancho), y sabiendo cualquiera de esos valores, ya sea, la altura o el ancho, la no conocida se obtiene impl\u00edcitamente.\n\nPara que un tensor realice esto, se remplaza un -1 en la dimensi\u00f3n que queremos que se infiera autom\u00e1ticamente.\n\nPara lo que se ha realizado con el vector x, se pudo haber hecho de dos formas:\n\n* x.reshape(3,4) lo cambiamos por -> x.reshape(-1,4)\n* x.reshape(3,4) lo cambiamos por -> x.reshape(3,-1)\n\n**Tensores inicializados con cero**\n\nPara obtener tensores inicializadas con ceros, se realiza mediante la propiedad _zeros_. El siguiente ejemplo es un tensor con forma (2,3,4):\n\n\n\n\n```python\ntorch.zeros((2,3,4))\n```\n\n\n\n\n    tensor([[[0., 0., 0., 0.],\n             [0., 0., 0., 0.],\n             [0., 0., 0., 0.]],\n    \n            [[0., 0., 0., 0.],\n             [0., 0., 0., 0.],\n             [0., 0., 0., 0.]]])\n\n\n\n**Tensores inicializados con unos**\n\nPara obtener tensores inicializadas con unos, se realiza mediante la propiedad _ones_.\n\n\n```python\ntorch.ones((2,3,4))\n```\n\n\n\n\n    tensor([[[1., 1., 1., 1.],\n             [1., 1., 1., 1.],\n             [1., 1., 1., 1.]],\n    \n            [[1., 1., 1., 1.],\n             [1., 1., 1., 1.],\n             [1., 1., 1., 1.]]])\n\n\n\n**Tensores inicializados con valores aleatorios**\n\nUn ejemplo de uso de estos tensores es cuando se crean matrices que funcionan como par\u00e1metros de una red neuronal, ya que, normalmente sus valores se inicializan con valores aleatorios.\n\nEl siguiente tensor tiene una forma (5,4) y cada elemento se extrajo aleatoriamente de una distribuci\u00f3n gausiana est\u00e1ndar (normal) con una media de 0 y desviaci\u00f3n est\u00e1ndar de 1. Para esto, se utiliza la propiedad _randn_.\n\n\n\n```python\ntorch.randn(5,4)\n```\n\n\n\n\n    tensor([[ 0.2204, -0.8333,  0.1837,  1.2486],\n            [-0.5009,  0.1174,  0.7050,  0.7321],\n            [-1.4421, -1.2758, -1.2015,  0.7555],\n            [-1.6072,  0.7757, -0.0648,  0.8688],\n            [-1.4232, -1.9594, -1.8735, -0.6077]])\n\n\n\n**Tensores con valores espec\u00edficos**\n\nSe pueden especificar valores exactos a cada elemento del tensor dando una lista de Python o bien una lista de listas, que contengan valores num\u00e9ricos.\n\n\n\n\n```python\ntorch.tensor([[2,1,4,3],[1,2,3,4],[4,3,2,1]])\n```\n\n\n\n\n    tensor([[2, 1, 4, 3],\n            [1, 2, 3, 4],\n            [4, 3, 2, 1]])\n\n\n\n## Operaciones \nLas operaciones elementales aplican una operaci\u00f3n escalar est\u00e1ndar a cada elemento de un array.\n\nEl operador escalar unitario (toma una entrada) se denota como $f : \\mathbb R \\to \\mathbb R$, esto nos dice que la funci\u00f3n mapea desde un n\u00famero real a otro.\n\nEl operador escalar binario (toma dos entradas reales, y da una entrada) y se denota como $f : \\mathbb R, \\mathbb R \\to \\mathbb R$.\n\nAhora bien, si tenemos dos vectores **u** y **v** de la misma forma, y se tiene un operador binario, podemos producir un vector **c** = F(**u**,**v**), estableciendo $c_i \u2190 f(u_i,v_i)$ para toda $i$, donde $c_i, u_i$ y $v_i$ son los i-\u00e9simos elementos de los vectores.\n\nLos operadores aritm\u00e9ticos est\u00e1ndar (suma, resta, multiplicaci\u00f3n, divisi\u00f3n y exponenciaci\u00f3n) son operaciones elementales para cualquier tensor de forma id\u00e9ntica y arbitraria.\n\n### Operaciones\n\n\n\n```python\nx = torch.tensor([1.0,2,4,8])\ny = torch.tensor([2,2,2,2])\nprint(x+y) # suma\nprint(x-y) # resta\nprint(x*y) # multiplicaci\u00f3n\nprint(x/y) # divisi\u00f3n\nprint(x**y) # exponenciaci\u00f3n\n```\n\n    tensor([ 3.,  4.,  6., 10.])\n    tensor([-1.,  0.,  2.,  6.])\n    tensor([ 2.,  4.,  8., 16.])\n    tensor([0.5000, 1.0000, 2.0000, 4.0000])\n    tensor([ 1.,  4., 16., 64.])\n\n\nOtra operaci\u00f3n es la de exponenciaci\u00f3n de la forma $e^x$:\n\n\n\n```python\ntorch.exp(x)\n```\n\n\n\n\n    tensor([2.7183e+00, 7.3891e+00, 5.4598e+01, 2.9810e+03])\n\n\n\nAdem\u00e1s de operaciones elementales, se pueden realizar operaciones de \u00e1lgebra lineal, como productos punto y multiplicaci\u00f3n de matrices.\n\n**Concatenar**\n\nLos tensores se pueden concatenar, apil\u00e1ndolos de extremo a extremo para formar un tensor m\u00e1s grande. Se debe proporcionar una lista de tensores y establecer a lo largo de qu\u00e9 eje se quiere concatenar.\n\nEjemplo: Concatenar dos matrices de forma (3,4), si se realiza a lo largo de las filas, la matriz resultante tiene una forma de (6,4) que es la suma de las filas de ambas matrices (3+3). Esto se realiza de la siguiente forma:\n\n\n```python\nX = torch.arange(12, dtype=torch.float32).reshape((3,4))\nY = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])\ntorch.cat((X, Y), dim=0) # concatenar a lo largo de las filas\n\n```\n\n\n\n\n    tensor([[ 0.,  1.,  2.,  3.],\n            [ 4.,  5.,  6.,  7.],\n            [ 8.,  9., 10., 11.],\n            [ 2.,  1.,  4.,  3.],\n            [ 1.,  2.,  3.,  4.],\n            [ 4.,  3.,  2.,  1.]])\n\n\n\nSe observa que se coloca dim = 0, que representa el primer elemento de la forma que son las filas.\n\nAhora, para hacer la concatenaci\u00f3n a lo largo de las columnas, con nuestro ejemplo nos dar\u00eda una matriz de forma (3,8), que es la suma de las columnas de ambas matrices (4+4), y se coloca el par\u00e1metro dim = 1, haciendo referencia al segundo elemento de la forma que son las columnas:\n\n\n\n```python\ntorch.cat((X, Y), dim=1) # concatenar a lo largo de las columnas\n```\n\n\n\n\n    tensor([[ 0.,  1.,  2.,  3.,  2.,  1.,  4.,  3.],\n            [ 4.,  5.,  6.,  7.,  1.,  2.,  3.,  4.],\n            [ 8.,  9., 10., 11.,  4.,  3.,  2.,  1.]])\n\n\n\n**Tensor binario mediante sentencias l\u00f3gicas**\n\nSi tomamos a X y Y utilizados previamente, y realizamos X == Y para cada posici\u00f3n y resulta que son iguales en \u00e9sta, el tensor tendr\u00e1 un valor de 1, o bien, True, en caso contrario tomara el valor de 0, o bien False.\n\n\n```python\nX == Y\n```\n\n\n\n\n    tensor([[False,  True, False,  True],\n            [False, False, False, False],\n            [False, False, False, False]])\n\n\n\n**Suma de todos los elemento del tensor**\n\nLa suma de todos los elementos da como resultado un tensor de un solo elemento:\n\n\n```python\nX.sum()\n```\n\n\n\n\n    tensor(66.)\n\n\n\n## Mecanismos de broadcasting\nBajo ciertas condiciones, incluso cuando las formas difieren, se pueden realizar operaciones elementales llamando un mecanismo de broadcasting.\n\nPrimero se ampl\u00edan una o ambas matrices copiando los elementos de forma correcta, tal que tras esta transformaci\u00f3n los dos tensores tengan la misma forma. Posterior, se realizan las operaciones elementales.\n\nEn la mayor\u00eda de los casos se \"difune\" a lo largo de un eje en donde un arreglo tiene inicialmente longitud de 1, esto se muestra:\n\n\n\n```python\na = torch.arange(3).reshape(3,1)\nb = torch.arange(2).reshape(1,2)\na,b\n```\n\n\n\n\n    (tensor([[0],\n             [1],\n             [2]]), tensor([[0, 1]]))\n\n\n\nLa forma de a es (3,1) y la forma de b es (1,2), de modo que no coinciden si queremos sumarlas. \n\nPara poder sumarlas, se difunden las entradas de ambas matrices en una de forma (3,2). Para a, se replican las columnas, resultado en $a = [[0,0],[1,1],[2,2]]$ y para b, se replican las filas, resultado en $b = [[0,1],[0,1],[0,1]]$. De esta forma, es sencillo obsevar entonces que la suma de a con b, da lo siguiente:\n\n\n```python\na+b\n```\n\n\n\n\n    tensor([[0, 1],\n            [1, 2],\n            [2, 3]])\n\n\n\n## Indexaci\u00f3n y slicing\nAs\u00ed como en un arreglo en Python, se puede acceder a los elementos de un tensor por \u00edndice, teniendo el primer elemento un \u00edndice 0. As\u00ed como en las listas, el \u00faltimo elemento se puede acceder a \u00e9l mediante el -1, y as\u00ed para las dem\u00e1s posiciones.\n[1:3] selecciona el segundo y tercer elemento, el elemento de la posici\u00f3n 4 no se incluye.\n\n\n\n```python\nX[-1], X[1:3]\n```\n\n\n\n\n    (tensor([ 8.,  9., 10., 11.]), tensor([[ 4.,  5.,  6.,  7.],\n             [ 8.,  9., 10., 11.]]))\n\n\n\nSe puede escribir elementos en una matriz mediante los \u00edndices:\n\n\n\n```python\nX[1,2] = 9\nX\n```\n\n\n\n\n    tensor([[ 0.,  1.,  2.,  3.],\n            [ 4.,  5.,  9.,  7.],\n            [ 8.,  9., 10., 11.]])\n\n\n\nSi queremos asignar a varios elementos el mismo valor, se indexan los que se desean, tal como en un array.\nPor ejemplo: [0:2,:] accede a la primera y segunda fila, y con : nos indica que toma todas las columnas. \n\n\n\n```python\nX[0:2, :] = 12\nX\n```\n\n\n\n\n    tensor([[12., 12., 12., 12.],\n            [12., 12., 12., 12.],\n            [ 8.,  9., 10., 11.]])\n\n\n\n## Guardar la memoria\nCuando ejecutamos operaciones puede ocurrir que se asigne nueva memoria a los resultados, a\u00fan cuando se asignen a la propia variable.\n\nPor ejemplo, si se realiza la operaciones Y = X+Y, lo que ocurre es que ya no se referenc\u00eda el tensor al que apuntaba Y, sino que ahora se apunta Y a la memoria reci\u00e9n asignada. Esto se observa a continuaci\u00f3n, con la funci\u00f3n __id()__ de Python, nos da la direcci\u00f3n exacta del objeto referenciado en memoria.\nSi se ejecuta Y = Y+X, nos arrojar\u00e1 que id(Y) ahora apunta a una direcci\u00f3n diferente,  debido a que primero se eval\u00faa Y+X, asignando nueva memoria para el resultado y luego hace que Y apunte a esta nueva direcci\u00f3n en memoria.\nEs por esto que el siguiente c\u00f3digo da False.\n\n\n\n```python\nbefore = id(Y)\nY = Y + X\nid(Y) == before\n```\n\n\n\n\n    False\n\n\n\nEsto puede ser indeseable por dos razones. Primero, porque no se quiere estar asignando memoria innecesaria cada vez, sino que es deseable que se realicen las actualizaciones en el mismo lugar. Segundo, porque al tener cientos de megabytes de par\u00e1metros en ciertos proyectos, podr\u00edamos apuntar a los mismos par\u00e1metros desde m\u00faltiples variables.\n\nNo obstante, realizar operaciones en el mismo lugar es sencillo. Podemos asignar el resultado de una operaci\u00f3n a una matriz previamente asignada con la notaci\u00f3n slice, por ejemplo: Y[:] = <expresi\u00f3n>. \nPara realizar esto, primero creamos una matriz nueva Z con la misma forma que Y, utilizando la funci\u00f3n __zeros_like__ para asignar un bloque de 0 entradas.\n\n\n\n```python\nZ = torch.zeros_like(Y)\nprint(Z)\nprint('id(Z):', id(Z))\nZ[:] = X + Y\nprint('id(Z):', id(Z))\n```\n\n    tensor([[0., 0., 0., 0.],\n            [0., 0., 0., 0.],\n            [0., 0., 0., 0.]])\n    id(Z): 140154347304144\n    id(Z): 140154347304144\n\n\nAhora bien, si el valor de X no se utiliza m\u00e1s adelante, tambien se puede utilizar lo siguiente; X[:] = X+Y, o, X+=Y para reducir la sobrecarga de memoria de la operaci\u00f3n. En el c\u00f3digo siguiente se observa que funciona correctamente.\n\n\n```python\nbefore = id(X)\nX += Y\nid(X) == before\n```\n\n\n\n\n    True\n\n\n\n## Conversi\u00f3n a otros objetos de Python\n**Convertir a un tensor NumPy**\n\nEl tensor de torch y el array de Numpy compartir\u00e1n ubicaciones de memoria subyacentes, y el cambio de uno a trav\u00e9s de una operaci\u00f3n in-place tambi\u00e9n cambiar\u00e1 el otro.\n\n\n```python\nA = X.numpy()\nB = torch.from_numpy(A)\ntype(A), type(B)\n```\n\n\n\n\n    (numpy.ndarray, torch.Tensor)\n\n\n\nPara convertir un tensor de tama\u00f1o 1 en un escalar de python, podemos usar la funci\u00f3n __item__ o funciones incorporadas en Python como float o int.\n\n\n\n```python\na = torch.tensor([3.5])\na,a.item(),float(a),int(a)\n```\n\n\n\n\n    (tensor([3.5000]), 3.5, 3.5, 3)\n\n\n\n# Preprocesamiento de datos\nEl paqueta pandas es una de las herramientas populares de an\u00e1lisis de datos en Python. Pandas puede trabajar con tensores.\nPara aplicar el aprendizaje profundo a la resoluci\u00f3n de problemas, se comienza con un preprocesamiento de datos en bruto, en vez de aquellos datos bien preparados en el formato de tensor. Por esto, con pandas se hace el preprocesamiento para de ah\u00ed convertirlos en el formato tensor.\n\n## Lectura del conjunto de datos\nSe comenzar\u00e1 creando un conjunto de datos artificial que se almacena en un archivo csv: ./data/house_tiny.csv.\n\nSe escribira el conjunto de datos fila por fila en un archivo csv:\n\n\n```python\nimport os\n\nos.makedirs(os.path.join('..', 'data'), exist_ok=True)\ndata_file = os.path.join('..', 'data', 'house_tiny.csv')\nwith open(data_file, 'w') as f:\n  f.write('NumRooms,Alley,Price\\n')  # Nombre de las columnas\n  f.write('NA,Pave,127500\\n')  # Cada fila representa un ejemplo de datos\n  f.write('2,NA,106000\\n')\n  f.write('4,NA,178100\\n')\n  f.write('NA,NA,140000\\n')\n```\n\nPara cargar el conjunto de datos en bruto desde el archivo csv que se cre\u00f3, se importa el paquete pandas y se utiliza su funci\u00f3n _read_csv_.\n\nEl conjunto de datos tiene 4 filas y 3 columnas, en donde cada fila describe el n\u00famero de habitaciones (\"NumRooms\"), el tipo de callej\u00f3n (\"Alley\") y el precio (\"Price\") de una casa, tal como se observ\u00f3 en el c\u00f3digo anterior.\n\n\n\n```python\n!pip install pandas # instalaci\u00f3n de pandas\n```\n\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (1.1.5)\n    Requirement already satisfied: numpy>=1.15.4 in /usr/local/lib/python3.7/dist-packages (from pandas) (1.19.5)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas) (2.8.2)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas) (1.15.0)\n\n\n\n```python\nimport pandas as pd\ndata = pd.read_csv(data_file)\n\nprint(data)\n```\n\n       NumRooms Alley   Price\n    0       NaN  Pave  127500\n    1       2.0   NaN  106000\n    2       4.0   NaN  178100\n    3       NaN   NaN  140000\n\n\n## Tratamiento de datos faltantes\nLos valores NaN que se observan, son valores perdidos. Para tratar a estos datos, los m\u00e9todos t\u00edpicos son la imputaci\u00f3n y la eliminaci\u00f3n, donde la imputaci\u00f3n sustituye los valores que faltan por otros sustituidos, y la eliminaci\u00f3n ignora los valores que faltan.\n\nConsiderando la imputaci\u00f3n, tenemos:\nMediante la indexaci\u00f3n basada en la localizaci\u00f3n de enteros (iloc), dividimos los datos en entradas y salidas, siendo las entradas las dos primeras columnas y la salida la \u00faltima columna. Para los valores que faltan, se sustituye en NaN por el valor medio de su columna correspondiente. Esto se realiza de la siguiente forma:\n\n\n\n```python\ninputs,outputs = data.iloc[:,0:2], data.iloc[:,2]\ninputs = inputs.fillna(inputs.mean()) # sustituye NaN por valor medio de la columna\nprint(inputs)\n```\n\n       NumRooms Alley\n    0       3.0  Pave\n    1       2.0   NaN\n    2       4.0   NaN\n    3       3.0   NaN\n\n\nPara los valores categ\u00f3ricos o discretos en las entradas, consideraremos NaN como una categor\u00eda. De este modo, Alley est\u00e1 contituido de Pave y NaN, con esto, pandas puede convertir autom\u00e1ticamente esta columna en dos columnas, una con el nombre \"Alley_Pave\" y la otra con \"Alley_nan\". Una fila cuya tipo de callej\u00f3n sea \"Pave\" establecer\u00e1 los valores de \"Alley_Pave\" y \"Alley_nan\" a 1, y 0. Una fila con tipo de callejon ausente, establecer\u00e1 los valores 0 y 1. Esto se puede apreciar en el siguiente c\u00f3digo:\n\n\n\n```python\ninputs = pd.get_dummies(inputs,dummy_na = True)\nprint(inputs)\n```\n\n       NumRooms  Alley_Pave  Alley_nan\n    0       3.0           1          0\n    1       2.0           0          1\n    2       4.0           0          1\n    3       3.0           0          1\n\n\n## Conversi\u00f3n al formato Tensor\nComo todas las entradas y salidas son num\u00e9ricas, se puede convertir al formato Tensor. Cuando est\u00e9n en dicho formato, ya pueden ser manipulados con las funciones de los tensores.\n\nX: Entradas\ny: Salidas\n\n\n```python\nX, y = torch.tensor(inputs.values), torch.tensor(outputs.values)\nX,y\n```\n\n\n\n\n    (tensor([[3., 1., 0.],\n             [2., 0., 1.],\n             [4., 0., 1.],\n             [3., 0., 1.]], dtype=torch.float64),\n     tensor([127500, 106000, 178100, 140000]))\n\n\n\n# Algebra lineal\n\n## Escalares\nValores que constan de una sola cantidad num\u00e9rica.\n\nSi queremos convertir grados Fahrenheit a Celsius, se usa la siguiente expresi\u00f3n: $c = \\frac{5}{9}(f-32)$, donde $\\frac{5}{9}$  y 32 son escalares. Las letras $c$ y $f$ representan valores escalares desconocidos.\n\nLas variables se denotan por letras en min\u00fasculas en este apartado. $\\mathbb R$ denota el espacio de todos los escalares de valor real.\n\n$x \\in \\mathbb R$ es una forma de decir que $x$ es un escalar de valor real.\n\nUn escalar es representado por un tensor con un solo elemento.\n\nA continuaci\u00f3n, se muestran 2 escalares y se realizan operaciones aritm\u00e9ticas.\n\n\n```python\nimport torch\nx = torch.tensor(3.0)\ny = torch.tensor(2.0)\nprint(x+y) # suma\nprint(x*y) # multiplicaci\u00f3n\nprint(x/y) # divisi\u00f3n\nprint(x**y) # exponenciaci\u00f3n\n```\n\n    tensor(5.)\n    tensor(6.)\n    tensor(1.5000)\n    tensor(9.)\n\n\n## Vectores\nSe puede pensar un vector como una simple lista de valores escalares. Estos ser\u00e1n llamados elementos (entradas o componentes) del vector.\n\nEn la notaci\u00f3n matem\u00e1tica, se suele denotar a los vectores con letras min\u00fasculas y en negrita: **x**,**y** y **z**.\n\nLos vectores son tensores unidimensionales, de longitudes arbitrarias:\n\n\n```python\nx = torch.arange(4)\nx\n```\n\n\n\n\n    tensor([0, 1, 2, 3])\n\n\n\nPodemos referirnos al i-\u00e9simo elemento de **x** mediante $x_i$, siendo $x_i$ un escalar.\nEn la literatura, por defecto a los vectores se consideran como vectores columnas.\n\n\\begin{equation}\nx =\\begin{pmatrix}\nx_1 \\\\\nx_2 \\\\\n\\vdots \\\\\nx_n \n\\end{pmatrix}\n\\end{equation}\n\n\ndonde $x_1,...,x_n$ son elementos del vector, y accedemos a cada elemento mediante indexaci\u00f3n en el tensor:\n\n\n\n```python\nx[3] # elemento 4 del vector\n```\n\n\n\n\n    tensor(3)\n\n\n\n## **Longitud, dimensionalidad y forma**\nUn vector es un arreglo de n\u00fameros. Cada vector tiene una longitud.\n\nEn notaci\u00f3n matem\u00e1tica, si queremos decir que un vector **x** consiste de $n$ escalares de valor real, se puede expresar como **x** $\\in \\mathbb R^n$.\n\nLa longitud del vector se llama com\u00fanmente como la dimensi\u00f3n del vector.\n\nPodemos saber la longitud de un tensor mediante la funci\u00f3n _len_.\n\n\n\n```python\nlen(x) # longitud o dimensi\u00f3n de x\n```\n\n\n\n\n    4\n\n\n\nCuando un tensor representa un vector, se puede obtener su longitud al obtener su atributo de forma con _.shape_. La forma es una tupla que enlista la longitud a lo largo de cada eje del tensor, y al hablar de un vector, nos arroja su longitud:\n\n\n\n```python\nx.shape\n```\n\n\n\n\n    torch.Size([4])\n\n\n\n## Matrices\nLas matrices generalizan vectores de orden 1 a orden 2.\nSe denotan t\u00edpicamente con letras may\u00fasculas: **X**, **Y** y **Z**.\nEn c\u00f3digo se representan como tensores con 2 ejes.\n\nEn notaci\u00f3n matem\u00e1tica, se usa **A** $\\in \\mathbb R^{m \\times n}$ para expresar que la matriz **A** consiste de $m$ filas y de $n$ columnas de escalares de valor real.\n\nSe puede ver como una tabla donde cada elemento $a_{ij}$ pertenece a la i-\u00e9sima fila y j-\u00e9sima columna.\n\n\\begin{equation}\nA =\\begin{pmatrix}\na_{11} & a_{12} & \\cdots & a_{1n}\\\\\na_{21} & a_{22} & \\cdots & a_{2n}\\\\\n\\vdots & \\vdots & \\ddots & \\vdots\\\\\na_{m1} & a_{m2} & \\cdots & a_{mn}\n\\end{pmatrix}\n\\end{equation}\n\nSi $m = n$ se dice que la matriz es cuadrada.\n\nPara crear una matriz tenemos que especificar la forma con dos componentes, tal y como se muestra:\n\n\n\n```python\nA = torch.arange(20).reshape(5,4)\nA\n```\n\n\n\n\n    tensor([[ 0,  1,  2,  3],\n            [ 4,  5,  6,  7],\n            [ 8,  9, 10, 11],\n            [12, 13, 14, 15],\n            [16, 17, 18, 19]])\n\n\n\nPodemos acceder al elemento $a_{ij}$ de la matriz A, especificando los \u00edndices de las filas (i) y columnas (j), tal como $[\\textbf{A}]_{i,j}$ \n\n**Transpuesta de una matriz**\n\nLa transpuesta de una matriz es cuando se intercambian filas por columnas de la matriz y se denota por $\\textbf{A}^{T}$, y si tenemos que $\\textbf{B} = \\textbf{A}^{T}$, entonces $b_{ij} = a_{ji}$, para cualquier $i$ y $j$.\n\n\\begin{equation}\nA ^T=\\begin{pmatrix}\na_{11} & a_{21} & \\cdots & a_{m1}\\\\\na_{12} & a_{22} & \\cdots & a_{m2}\\\\\n\\vdots & \\vdots & \\ddots & \\vdots\\\\\na_{1n} & a_{2n} & \\cdots & a_{mn}\n\\end{pmatrix}\n\\end{equation}\n\n\n```python\nA.T # transpuesta de una matriz\n```\n\n\n\n\n    tensor([[ 0,  4,  8, 12, 16],\n            [ 1,  5,  9, 13, 17],\n            [ 2,  6, 10, 14, 18],\n            [ 3,  7, 11, 15, 19]])\n\n\n\n**Matriz sim\u00e9trica**\n\nUna matriz es sim\u00e9trica si es igual a su transpuesta.\n$\\textbf{A} = \\textbf{A}^{T}$\n\n\n\n```python\nB = torch.tensor([[1,2,3],[2,0,4],[3,4,5]]) # B es una matriz sim\u00e9trica\n```\n\n\n```python\nB == B.T # se iguala con su transpuesta y debe dar todos verdaderos\n```\n\n\n\n\n    tensor([[True, True, True],\n            [True, True, True],\n            [True, True, True]])\n\n\n\n## Tensores\nLos tensores nos dan una forma gen\u00e9rica de describir a los arreglos n-dimensionales con un n\u00famero arbitrario de ejes.\n\nLos vectores son tensores de primer orden, las matrices son tensores de segundo orden. Los tensores se denotan por letras mayusculas y un tipo de letras especial, y su mecanismo de indexaci\u00f3n es similar al de matrices.\n\nCuando se trabaja con im\u00e1genes los tensores tienen una gran importancia, ya que \u00e9stas llegan como arreglos n-dimensionales con 3 ejes correspondientes a la altura, anchura y un eje de canal para apilar los canales de color (rojo, verde y azul). \n\nEjemplo de tensor:\n\n\n\n```python\nX = torch.arange(24).reshape(2,3,4)\nX\n```\n\n\n\n\n    tensor([[[ 0,  1,  2,  3],\n             [ 4,  5,  6,  7],\n             [ 8,  9, 10, 11]],\n    \n            [[12, 13, 14, 15],\n             [16, 17, 18, 19],\n             [20, 21, 22, 23]]])\n\n\n\n## Propiedades b\u00e1sicas aritm\u00e9tica tensorial\nDados dos tensores de la misma forma, el resultado de cualquier operaci\u00f3n elemental binaria ser\u00e1 un tensor con la misma forma, por ejemplo, si se suman dos matrices de la misma forma, se realiza una suma elemental sobre estas dos matrices.\n\n\n\n```python\nA = torch.arange(20,dtype=torch.float32).reshape(5,4)\nB = A.clone() # asigna una copia de A a B asignando nueva memoria\nA,A+B\n```\n\n\n\n\n    (tensor([[ 0.,  1.,  2.,  3.],\n             [ 4.,  5.,  6.,  7.],\n             [ 8.,  9., 10., 11.],\n             [12., 13., 14., 15.],\n             [16., 17., 18., 19.]]), tensor([[ 0.,  2.,  4.,  6.],\n             [ 8., 10., 12., 14.],\n             [16., 18., 20., 22.],\n             [24., 26., 28., 30.],\n             [32., 34., 36., 38.]]))\n\n\n\nLa multiplicaci\u00f3n elemental de dos matrices de denomina producto Hadamard (en notaci\u00f3n matem\u00e1tica $\\odot$).\n\nSi tenemos una matriz $\\textbf{B} \\in \\mathbb R^{m\\times n}$, con los elementos de filas $i$ y columnas $j$ como $b_{ij}$. El producto Hadamard de matrices $\\textbf{A}$ y $\\textbf{B}$, se encuentra definida como:\n\n\\begin{equation}\nA \\odot B = \\begin{pmatrix}\na_{11}b_{11} & a_{12}b_{12} & \\cdots & a_{1n}b_{1n}\\\\\na_{21}b_{21} & a_{22}b_{22} & \\cdots & a_{2n}b_{2n}\\\\\n\\vdots & \\vdots & \\ddots & \\vdots\\\\\na_{m1}b_{m1} & a_{m2}b_{m2} & \\cdots & a_{mn}b_{mn}\n\\end{pmatrix}\n\\end{equation}\n\n\n```python\nA*B # producto Hadamard\n```\n\n\n\n\n    tensor([[  0.,   1.,   4.,   9.],\n            [ 16.,  25.,  36.,  49.],\n            [ 64.,  81., 100., 121.],\n            [144., 169., 196., 225.],\n            [256., 289., 324., 361.]])\n\n\n\nMultiplicar o sumar un tensor por un escalar, tampoco cambia la forma del tensor. Cada elemento del tensor ser\u00e1 sumado o multiplicado por el escalar.\n\nEn el siguiente c\u00f3digo se suma un 2 al tensor X y tambi\u00e9n se multiplica por 2 al tensor X.\n\n\n```python\na = 2\nX = torch.arange(24).reshape(2, 3, 4)\na + X, (a * X).shape\n```\n\n\n\n\n    (tensor([[[ 2,  3,  4,  5],\n              [ 6,  7,  8,  9],\n              [10, 11, 12, 13]],\n     \n             [[14, 15, 16, 17],\n              [18, 19, 20, 21],\n              [22, 23, 24, 25]]]), torch.Size([2, 3, 4]))\n\n\n\n## Reducci\u00f3n\nUna operaci\u00f3n \u00fatil que se puede realizar con tensores es calcular la suma de sus elementos. En c\u00f3digo basta con llamar a la funci\u00f3n para calcular la suma:\n\n\n\n```python\nx = torch.arange(4,dtype = torch.float32)\nx,x.sum()\n```\n\n\n\n\n    (tensor([0., 1., 2., 3.]), tensor(6.))\n\n\n\nPodemos expresar sumas sobre los elementos de tensores de forma arbitrarria.\nPor ejemplo, la suma de los elementos de una matriz $\\textbf{A}$ de $m \\times n$ se puede escribir como:\n\n$\\sum_{i = 1}^{m}\\sum_{j = 1}^{n}a_{ij}$\n\n\n\n```python\nA.shape, A.sum()\nA\n```\n\n\n\n\n    tensor([[ 0.,  1.,  2.,  3.],\n            [ 4.,  5.,  6.,  7.],\n            [ 8.,  9., 10., 11.],\n            [12., 13., 14., 15.],\n            [16., 17., 18., 19.]])\n\n\n\nPor defecto, la suma reduce un tensor a lo largo de todos sus ejes a un escalar, no obstante, podemos especificiar los ejes a lo largo de los cuales se reduce el tensor mediante la suma.\n\nSi usamos las matrices como ejemplo, y reducimos la dimensi\u00f3n de la fila (eje 0) sumando los elementos de todas las filas, especificamos eje = 0 al llamar a la funci\u00f3n.\n\nAl realizar esto, se sumar\u00eda la primer columna y se colocar\u00eda el resultado en el primer elemento del eje 0, para la segunda columna es lo mismo, coloc\u00e1ndose el resultado en el segundo elemento del eje 0. Esto se puede ver a continuaci\u00f3n:\n\n\n\n```python\nA_sum_axis0 = A.sum(axis=0)\nA_sum_axis0, A_sum_axis0.shape\n```\n\n\n\n\n    (tensor([40., 45., 50., 55.]), torch.Size([4]))\n\n\n\nEn cambio, si se coloca como par\u00e1metro al eje 1, se hace la suma por filas (se suman los elementos de la fila 1, de la fila 2, as\u00ed sucesivamente), es decir, sumando los elementos de las columnas.\n\nCon el ejemplo que se ha utilizado resulta lo siguiente:\n\n\n\n```python\nA_sum_axis1 = A.sum(axis=1)\nA_sum_axis1, A_sum_axis1.shape\n```\n\n\n\n\n    (tensor([ 6., 22., 38., 54., 70.]), torch.Size([5]))\n\n\n\nSi reducimos la matriz a lo largo de las filas y columnas es equivalente a sumar todos los elementos de la matriz:\n\n\n\n```python\nA.sum(axis=[0, 1]) # esto es igual a A.sum()\n```\n\n\n\n\n    tensor(190.)\n\n\n\nUna cantidad relacionada es la media o promedio. Esto se obtiene dividiendo la suma entre el n\u00famero total de elementos. Mediante c\u00f3digo resulta:\n\n\n```python\nA.mean(), A.sum() / A.numel() # se puede realizar de ambas formas\n```\n\n\n\n\n    (tensor(9.5000), tensor(9.5000))\n\n\n\nLa media tambi\u00e9n puede reducir el tensor a lo largo de los ejes especificados, como ocurr\u00eda con la suma:\n\n\n\n```python\nA.mean(axis=0), A.sum(axis=0) / A.shape[0] # se puede hacer de ambas formas\n```\n\n\n\n\n    (tensor([ 8.,  9., 10., 11.]), tensor([ 8.,  9., 10., 11.]))\n\n\n\n### **Suma sin reducci\u00f3n**\nA veces se puede mantener el n\u00famero de ejes sin cambios cuando se llama a la funci\u00f3n suma o media, mediante el par\u00e1metro _keepdims = True_.\n\n\n\n```python\nsum_A = A.sum(axis=1, keepdims=True)\nsum_A\n```\n\n\n\n\n    tensor([[ 6.],\n            [22.],\n            [38.],\n            [54.],\n            [70.]])\n\n\n\nComo la sum_A sigue conservando sus dos ejes despu\u00e9s de sumar cada fila, se puede dividir A entre la sum_A mediante difusi\u00f3n:\n\n\n\n```python\nA/sum_A\n```\n\n\n\n\n    tensor([[0.0000, 0.1667, 0.3333, 0.5000],\n            [0.1818, 0.2273, 0.2727, 0.3182],\n            [0.2105, 0.2368, 0.2632, 0.2895],\n            [0.2222, 0.2407, 0.2593, 0.2778],\n            [0.2286, 0.2429, 0.2571, 0.2714]])\n\n\n\nSi queremos calcular la suma acumulativa de elementos de A a lo largo de alg\u00fan eje, podemos llamar a la funci\u00f3n _cumsum_, es decir, se conserva la forma de la matriz pero en los ejes se va poniendo la suma en base a si es con respecto a las filas o a las columnas. Esto se observa en lo siguiente:\n\n\n\n```python\nA.cumsum(axis=0)\n```\n\n\n\n\n    tensor([[ 0.,  1.,  2.,  3.],\n            [ 4.,  6.,  8., 10.],\n            [12., 15., 18., 21.],\n            [24., 28., 32., 36.],\n            [40., 45., 50., 55.]])\n\n\n\n## Productos puntos\nDados dos vectores $\\textbf{x}$ y $\\textbf{y} \\in \\mathbb R^d$, su producto punto denotado por $\\textbf{x}^T\\textbf{y}$ \u00f3 $\u27e8\\textbf{x},\\textbf{y}\u27e9$, es una suma sobre los productos de los elementos en la misma posici\u00f3n, es decir, se multiplica el elemento 1 de un vector con el elemento 1 del otro, y as\u00ed con todos los elementos y finalmente se hace la suma; en notaci\u00f3n matem\u00e1tica es:\n$\\textbf{x}^T\\textbf{y} = \\sum_{i=1}^d x_iy_i$:\n\n\n\n```python\nx = torch.arange(4, dtype=torch.float32) # vector x\ny = torch.ones(4,dtype = torch.float32) # vector y\nx, y, torch.dot(x, y)\n```\n\n\n\n\n    (tensor([0., 1., 2., 3.]), tensor([1., 1., 1., 1.]), tensor(6.))\n\n\n\nEl producto punto se puede expresar mediante la multiplicaci\u00f3n po elementos y luego la suma, en lugar de usar _dot_:\n\n\n\n```python\ntorch.sum(x * y)\n```\n\n\n\n\n    tensor(6.)\n\n\n\nEl producto punto expresa una media ponderada. \n\nSi tenemos dos vectores normalizados (su magnitud es la unidad), el producto punto entre ellos expresan el coseno del \u00e1ngulo entre ellos.\n\n## Productos Matriz-Vector\nUna matriz $\\textbf{A}$ en t\u00e9rminos de sus vectores fila se visualiza como\n\n\n\\begin{equation}\n\\textbf{A}   = \\begin{pmatrix}\n\\textbf{a}_1^T\\\\\n\\textbf{a}_2^T \\\\\n\\vdots \\\\\n\\textbf{a}_m^T\\end{pmatrix}\n\\end{equation}\n\ndonde cada $\\textbf{a}_1^T \\in \\mathbb R^n$ es un vector fila que representa la i-\u00e9sima fila de la matriz $\\textbf{A}$.\n\nEl producto matriz-vector $\\textbf{A}\\textbf{x}$ es un simple vector columna de longitud $m$, cuyo i-\u00e9simo elemento es el producto punto $\\textbf{a}_1^T\\textbf{x}$:\n\n\\begin{equation}\n\\textbf{Ax}  = \\begin{pmatrix}\n\\textbf{a}_1^T\\textbf{x}\\\\\n\\textbf{a}_2^T\\textbf{x} \\\\\n\\vdots \\\\\n\\textbf{a}_m^T\\textbf{x}\\end{pmatrix}\n\\end{equation}\n\nPodemos pensar a la multiplicaci\u00f3n por una matriz $\\textbf{A}$ como una transformaci\u00f3n que proyecta vectores de $\\mathbb R^n$ a $\\mathbb R^m$.\n\n\nPara expresar los productos matriz-vector con tensores se utiliza la funci\u00f3n _mv_. La dimensi\u00f3n de la columna de la matriz $\\textbf{A}$ (longitud a lo largo del eje 1), tiene que ser igual a la dimensi\u00f3n del vector $\\textbf{x}$:\n\n\n\n\n```python\nA.shape, x.shape, torch.mv(A, x) \n```\n\n\n\n\n    (torch.Size([5, 4]), torch.Size([4]), tensor([ 14.,  38.,  62.,  86., 110.]))\n\n\n\n## Multiplicaci\u00f3n Matriz-Matriz\nSe tiene a las dos matrices $\\textbf{A} \\in \\mathbb R^{n \\times k}$ y $\\textbf{B} \\in \\mathbb R^{k \\times m}$, definidas como:\n\n\\begin{equation}\n\\textbf{A} = \\begin{pmatrix}\na_{11} & a_{12} & \\cdots & a_{1k}\\\\\na_{21} & a_{22} & \\cdots & a_{2k}\\\\\n\\vdots & \\vdots & \\ddots & \\vdots\\\\\na_{n1} & a_{n2} & \\cdots & a_{nk}\n\\end{pmatrix}\n\\end{equation}\n\n\\begin{equation}\n\\textbf{B} = \\begin{pmatrix}\nb_{11} & b_{12} & \\cdots & b_{1m}\\\\\nb_{21} & b_{22} & \\cdots & b_{2m}\\\\\n\\vdots & \\vdots & \\ddots & \\vdots\\\\\nb_{k1} & b_{k2} & \\cdots & b_{nm}\n\\end{pmatrix}\n\\end{equation}\n\nDenotamos como $\\textbf{a}_i^T \\in \\mathbb R^k$ al vector fila que representa la i-\u00e9sima fila de la matriz $\\textbf{A}$ y $\\textbf{b}_j^T \\in \\mathbb R^k$ al vector columna de la j-\u00e9sima columna de la matriz $\\textbf{B}$. \n\nPara producir el producto matricial $\\textbf{C} = \\textbf{AB}$, se piensan a las matrices $\\textbf{A}$ y $\\textbf{B}$ en t\u00e9rminos de vectores fila, y columna, respectivamente:\n\n\\begin{equation}\n\\textbf{A}  = \\begin{pmatrix}\n\\textbf{a}_1^T\\\\\n\\textbf{a}_2^T \\\\\n\\vdots \\\\\n\\textbf{a}_n^T\\end{pmatrix}\n\\end{equation}\n\n\n\\begin{equation}\n\\textbf{B}  = \\begin{pmatrix}\n\\textbf{b}_1 & \\textbf{b}_2 & \\cdots & \\textbf{b}_m\\\\\n\\end{pmatrix}\n\\end{equation}\n\nLa matriz resultante $\\textbf{C} \\int \\mathbb R^{n \\times m}$ se produce calculando cada elemento $c_{ij}$ mediante el producto punto $\\textbf{a}_i^T\\textbf{b}_j$\n\n\n\\begin{equation}\n\\textbf{C}  = \\textbf{AB} = \\begin{pmatrix}\n\\textbf{a}_1^T\\\\\n\\textbf{a}_2^T \\\\\n\\vdots \\\\\n\\textbf{a}_n^T\\end{pmatrix}\\begin{pmatrix}\n\\textbf{b}_1 & \\textbf{b}_2 & \\cdots & \\textbf{b}_m\\\\\n\\end{pmatrix} = \\begin{pmatrix}\n\\textbf{a}_1^T\\textbf{b}_1 & \\textbf{a}_1^T\\textbf{b}_2 & \\cdots & \\textbf{a}_1^T\\textbf{b}_m\\\\\n\\textbf{a}_2^T\\textbf{b}_1 & \\textbf{a}_2^T\\textbf{b}_2 & \\cdots & \\textbf{a}_2^T\\textbf{b}_m\\\\\n\\vdots & \\vdots & \\ddots & \\vdots\\\\\n\\textbf{a}_n^T\\textbf{b}_1 & \\textbf{a}_n^T\\textbf{b}_2 & \\cdots & \\textbf{a}_n^T\\textbf{b}_m\n\\end{pmatrix}\n\\end{equation}\n\n\nEn esta multiplicaci\u00f3n, si la primera matriz tiene dimensi\u00f3n ($n,k$) y la segunda tiene dimensi\u00f3n ($k,m$), vemos que la primer matriz debe tener las mismas columnas que filas la segunda matriz. El resultado tendr\u00e1 una dimensi\u00f3n igual a los extremos de las dos matrices multiplicadas, es decir, ($n,m$).\n\nEn c\u00f3digo se utiliza la funci\u00f3n _mm_. \n\n\n```python\nB = torch.ones(4, 3)\ntorch.mm(A, B)\n```\n\n\n\n\n    tensor([[ 6.,  6.,  6.],\n            [22., 22., 22.],\n            [38., 38., 38.],\n            [54., 54., 54.],\n            [70., 70., 70.]])\n\n\n\n## Norma\nLa norma nos indica el tama\u00f1o de un vector, siendo aqu\u00ed referente a la magnitud de los componentes y no a su dimensionalidad.\n\nUna norma vectorial es una funci\u00f3n $f$ que mapea un vector a un escalar satisfaciendo diversas propiedades.\n\n**Propiedades**\\\nDado cualquier vector $\\textbf{x}$:\n\n* Si se escalan todos los elementos del vector por un factor constante $\\alpha$, la norma tambi\u00e9n se escala por el valor absoluto del mismo factor constante:\n\n$f(\\alpha\\textbf{x}) = |\\alpha|f(\\textbf{x})$\n\n* Desigualdad del triangulo:\n\n$f(\\textbf{x}+\\textbf{y}) \\leq f(\\textbf{x}) + f(\\textbf{y})$\n\n* La norma debe no debe ser negativa:\n\n$f(\\textbf{x}) \\geq 0$\n\n* La norma m\u00e1s peque\u00f1a se obtiene s\u00f3lo si el vector consiste de puros ceros:\n\n$\\forall_i ,[\\textbf{x}_i]$ = 0 $\u2194 f(\\textbf{x}) = 0$\n\n\nLa distancia euclidea es una norma, es la norma **$L_2$**:\n\nLa norma **$L_2$** de $\\textbf{x}$ es la ra\u00edz cuadrada de la suma de los cuadrados de los elementos del vector:\n\n$\u2225\\textbf{x}\u2225_2 = \\sqrt{\\sum_{i = 1}^n x_i^2}$\n\nLa norma **$L_2$** se puede calcular en c\u00f3digo mediante:\n\n\n\n```python\nu = torch.tensor([3.0, -4.0])\ntorch.norm(u) # norma L2 del vector u\n```\n\n\n\n\n    tensor(5.)\n\n\n\nLa norma **$L_1$** tambi\u00e9n es frecuente, y se expresa como la suma de los valores absolutos de los elementos del vector:\n\n$\u2225\\textbf{x}\u2225_1 = \\sum_{i = 1}^n |x_i|$\n\nPara calcular esta norma mediante c\u00f3digo, se compone la funci\u00f3n de valor absoluto con la suma de los elementos:\n\n\n\n\n```python\ntorch.abs(u).sum() # norma L1 del vector u\n\n```\n\n\n\n\n    tensor(7.)\n\n\n\nEstas dos normas, son casos especiales de la norma **$L_p$** m\u00e1s general:\n\n$\u2225\\textbf{x}\u2225_p = (\\sum_{i = 1}^n |x_i|^p)^{\\frac{1}{p}}$\n\nPara el caso de matrices y similar a la norma **$L_2$**, la norma Frobenius de una matriz $\\textbf{X} \\in \\mathbb R^{m \\times n}$ es la ra\u00edz cuadrada de la suma de los cuadrados de los elementos de la matriz:\n\n$\u2225\\textbf{X}\u2225_F = \\sqrt{\\sum_{i = 1}^m\\sum_{j = 1}^n x_{ij}^2}$\n\nEsta norma satisface las propiedades de las normas vectoriales.\n\nSe calcula en c\u00f3digo mediante:\n\n\n\n\n```python\ntorch.norm(torch.ones((4,9)))\n```\n\n\n\n\n    tensor(6.)\n\n\n\n# C\u00e1lculo\nLas aplicaciones m\u00e1s cr\u00edticas del c\u00e1lculo diferencial son los problemas de optimizaci\u00f3n.\n\nEn el aprendizaje profundo, se entrenan modelos actualiz\u00e1ndolos para que mejoren conforme se ven m\u00e1s datos, mejorar hace referencia a minimizar una funci\u00f3n de p\u00e9rdida.\n\nLo que importa es producir un modelo que funcione bien con datos que nunca hemos visto, pero ajustando el modelo a los datos que realmente vemos.\n\nEl ajuste de modelos se puede dividir en dos aspectos clave:\n\ni) Optimizaci\u00f3n: proceso de ajuste de nuestros modelos a datos observados.\n\nii) Generalizaci\u00f3n: principios matem\u00e1ticos y conocimiento de profesionales que orientan sobre c\u00f3mo producir modelos cuya validez se extiende m\u00e1s all\u00e1 del conjunto exacto de ejemplos de datos utilizados para entrenarlos.\n\n## Diferenciaci\u00f3n y derivadas\n\nEn el aprendizaje autom\u00e1tico, se eligen funciones de p\u00e9rdida que son diferenciables respecto a par\u00e1metros del modelo, esto nos dice que podemos saber la rapidez con que aumentar\u00eda o disminuir\u00eda la p\u00e9rdida si aument\u00e1ramos o disminuy\u00e9ramos ese par\u00e1metros en una cantidad infinitesimal.\n\nSupongamos una funci\u00f3n $f: \\mathbb R \\to \\mathbb R$, cuya entrada y salida son escalares. La derivada de $f$ se define como:\n\n$f'(x) = \\lim_{h \\to 0} \\frac{f(x+h)-f(x)}{h}$\n\nsi el l\u00edmite existe.\n\nSi $f'(a)$ existe, $f$ es diferenciable en $a$. As\u00ed mismo, si $f$ es diferenciable en cada n\u00famero de un intervalo, entonces $f$ es diferenciable en este intervalo. La derivada la podemos interpretar como la tasa de cambio instant\u00e1nea de $f(x)$ con respecto a $x$.\n\n\nEjemplo:\n\nTenemos la funci\u00f3n $u = f(x) = 3x^2-4x$\n\n\n\n\n```python\n%matplotlib inline\nimport numpy as np\nfrom IPython import display\n#from d2l import torch as d2l\n\ndef f(x):\n  return 3*x**2-4*x\n```\n\nConforme h se acerca a 0, y estableciendo $x = 1$, la derivada va teniendo un valor igual a 2, esto se muestra a continuaci\u00f3n:\n\n\n```python\ndef numerical_lim(f,x,h):\n  return (f(x+h)-f(x))/h # derivada de f\n\nh = 0.1\n\nfor i in range(5):\n  print(f\"h = {h:.5f}, limite = {numerical_lim(f,1,h):.5f}\")\n  h *= 0.1\n```\n\n    h = 0.10000, limite = 2.30000\n    h = 0.01000, limite = 2.03000\n    h = 0.00100, limite = 2.00300\n    h = 0.00010, limite = 2.00030\n    h = 0.00001, limite = 2.00003\n\n\n**Expresiones equivalentes para la derivada**\n\n$f'(x) = y' = \\frac{dy}{dx} = \\frac{df}{dx} = \\frac{d}{dx}f(x) = Df(x) = D_xf(x)$\n\nlos simbolos $\\frac{d}{dx}$ y $D$ son operadores de diferenciaci\u00f3n.\n\n**Reglas para diferenciar funciones comunes:**\n\n* $DC = 0$ ($C$ es una constante)\n* $Dx^n = nx^{n-1}$ ($n$ cualquier n\u00famero real)\n* $De^x = e^x$\n* $D$ln$(x)$ = $\\frac{1}{x}$\n\n**Reglas de derivaci\u00f3n**\n\n$f$ y $g$ son funciones diferenciables y $C$ es una constante:\n\n\n* $\\frac{d}{dx}[Cf(x)] = C\\frac{d}{dx}f(x)$\n* Regla de la suma\n\n$\\frac{d}{dx}[f(x)+g(x)] = \\frac{d}{dx}f(x)+\\frac{d}{dx}g(x)$\n\n* Regla del producto\n\n$\\frac{d}{dx}[f(x)g(x)] = f(x)\\frac{d}{dx}[g(x)]+g(x)\\frac{d}{dx}[f(x)]$\n\n* Regla del cociente\n\n$\\frac{d}{dx}[\\frac{f(x)}{g(x)}] = \\frac{g(x)\\frac{d}{dx}[f(x)]-f(x)\\frac{d}{dx}[g(x)]}{[g(x)]^2}$\n\nPara visualizar la interpretaci\u00f3n de las derivadas, se utilzar\u00e1 la librer\u00eda matplotlib. Adem\u00e1s, funciones como _use_svg_display_ especifica que el paquete matplotlib produzca las figuras svg para obtener im\u00e1genes m\u00e1s n\u00edtidas.\n\nTenemos primero la siguiente funci\u00f3n:\n\n\n\n\n\n```python\ndef use_svg_display():  \n    \"\"\"Usa el formato svg para desplegar un gr\u00e1fico en Jupyter.\"\"\"\n    display.set_matplotlib_formats('svg')\n```\n\nAhora se define la funci\u00f3n set_figsize para especificar los tama\u00f1os de las figuras.\n\n\n```python\ndef set_figsize(figsize=(3.5, 2.5)):  \n    \"\"\"Set the figure size for matplotlib.\"\"\"\n    use_svg_display()\n    d2l.plt.rcParams['figure.figsize'] = figsize\n```\n\nLa siguiente funci\u00f3n set_axes establece las propiedades de los ejes de las figuras producidas por matplotlib.\n\n\n\n```python\ndef set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend):\n    \"\"\"Configura los ejes para matplotlib\"\"\"\n    axes.set_xlabel(xlabel)\n    axes.set_ylabel(ylabel)\n    axes.set_xscale(xscale)\n    axes.set_yscale(yscale)\n    axes.set_xlim(xlim)\n    axes.set_ylim(ylim)\n    if legend:\n        axes.legend(legend)\n    axes.grid()\n```\n\nLa siguiente funci\u00f3n plot grafica m\u00faltiples curvas:\n\n\n\n```python\ndef plot(X, Y=None, xlabel=None, ylabel=None, legend=None, xlim=None,\n         ylim=None, xscale='linear', yscale='linear',\n         fmts=('-', 'm--', 'g-.', 'r:'), figsize=(3.5, 2.5), axes=None):\n    \"\"\"Grafica puntos de datos.\"\"\"\n    if legend is None:\n        legend = []\n\n    set_figsize(figsize)\n    axes = axes if axes else d2l.plt.gca()\n\n    # Regresa True si X (tensor o lista) tiene 1 eje\n    def has_one_axis(X):\n        return (hasattr(X, \"ndim\") and X.ndim == 1 or isinstance(X, list)\n                and not hasattr(X[0], \"__len__\"))\n\n    if has_one_axis(X):\n        X = [X]\n    if Y is None:\n        X, Y = [[]] * len(X), X\n    elif has_one_axis(Y):\n        Y = [Y]\n    if len(X) != len(Y):\n        X = X * len(Y)\n    axes.cla()\n    for x, y, fmt in zip(X, Y, fmts):\n        if len(x):\n            axes.plot(x, y, fmt)\n        else:\n            axes.plot(y, fmt)\n    set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend)\n```\n\nPodemos graficar la funci\u00f3n $y = 2x-3$ en el punto $x = 1$.\n\n\n```python\nx = np.arange(0, 3, 0.1)\nplot(x, [f(x), 2 * x - 3], 'x', 'f(x)', legend=['f(x)', 'Tangent line (x=1)'])\n```\n\n## Derivadas parciales\n En el aprendizaje profundo, las funciones suelen depender de muchas variables, es por eso que son de importancia las derivadas parciales, en donde se derivan funciones multivariables respecto a variables espec\u00edficas.\n\n Sea $y = f(x_1,x_2,...,x_n)$ una funci\u00f3n con $n$ variables. La derivada parcial de $y$ respecto a el i-\u00e9simo par\u00e1metro $x_i$ es:\n\n $\\frac{\\partial y}{\\partial x_i} = \\lim_{h \\to 0} \\frac{f(x_1,...,x_{i-1},x_i+h,x_{i+1},...,x_n)-f(x_1,...,x_i,...,x_n)}{h}$\n\n Para calcular $\\frac{\\partial y}{\\partial x_i}$ simplemente podemos tratar a $x_1,...,x_{i-1},x_{i+1},...,x_n$ como constantes, y calcular la derivada de $y$ con respecto a $x_i$.\n\n ## Gradientes\n Podemos concatenar las derivadas parciales de una funci\u00f3n multivariable con respecto a todas sus variables para obtener el vector gradiente de la funci\u00f3n.\n\n Supongamos que la entrada de la funci\u00f3n $f : \\mathbb R^n \\to \\mathbb R$ es un vector $n-$dimensional $\\textbf{x} = [x_1,x_2,...,x_n]$ y la salida es un escalar. El gradiente de la funci\u00f3n $f(\\textbf{x})$ con respecto a $\\textbf{x}$ es un vector de $n$ derivadas parciales:\n\n $\\nabla_xf(\\textbf{x}) = [\\frac{\\partial f(\\textbf{x})}{\\partial x_1},\\frac{\\partial f(\\textbf{x})}{\\partial x_2},...,\\frac{\\partial f(\\textbf{x})}{\\partial x_n}]^T$\n\n\n**Reglas utilizadas al diferenciar funciones multivariadas**\n\n* $\\forall \\textbf{A} \\in \\mathbb R^{m \\times n}, \\nabla_x \\textbf{Ax} = \\textbf{A}^T$\n*  $\\forall \\textbf{A} \\in \\mathbb R^{n \\times m}, \\nabla_x \\textbf{x}^T\\textbf{A} = \\textbf{A}$\n*  $\\forall \\textbf{A} \\in \\mathbb R^{n \\times n}, \\nabla_x \\textbf{x}^T\\textbf{A}\\textbf{x} = (\\textbf{A}+\\textbf{A}^T)\\textbf{x}$\n* $\\nabla_x\u2225\\textbf{x}\u2225^2 = \\nabla_x \\textbf{x}^T\\textbf{x} = 2\\textbf{x}$\n\n\n## Regla de la cadena\nLa regla de la cadena permite diferencias funciones compuestas.\n\nConsideremos funciones de una variable. Supongamos que las funciones $y = f(u)$ y $u = g(x)$ son ambas diferenciables, entonces la regla de la cadena establece que\n\n$\\frac{dy}{dx} = \\frac{dy}{du}\\frac{du}{dx}$\n\nFunciones multivariables. Supongamos que la funcipon diferenciable $y$ tiene variables $u_1,u_2,...,u_m$, donde cada funci\u00f3n diferenciable $u_i$ tiene variables $x_1,x_2,...,x_n$. Por tanto, $y$ es una funci\u00f3n de $x_1,x_2,...,x_n$. La regla de la cadena resulta:\n\n$\\frac{dy}{dx_i} = \\frac{dy}{du_1}\\frac{du_1}{dx_i}+\\frac{dy}{du_2}\\frac{du_2}{dx_i}+...+\\frac{dy}{du_m}\\frac{du_m}{dx_i}$\n\npara cualquier $i = 1,2,...,n$. \n\n\n## Diferenciaci\u00f3n autom\u00e1tica\nLa diferenciaci\u00f3n es crucial en casi todos los algoritmos de optimizaci\u00f3n del aprendizaje profundo.\n\nBas\u00e1ndonos en nuestro modelo dise\u00f1ado, el sistema construye un gr\u00e1fico computacional, rastreando qu\u00e9 datos se combinan a trav\u00e9s de qu\u00e9 operaciones para producir la salida.\nLa diferenciaci\u00f3n autom\u00e1tica permite al sistema retropropagar posteriormente los gradientes. Con retropropagar nos referimos a recorrer el gr\u00e1fico computacional, rellenando las derivadas pariales con respecto a cada par\u00e1metro.\n\n#### Un ejemplo sencillo\n\nSupongamos que queremos diferenciar la funci\u00f3n $ y = 2\\textbf{x}^T\\textbf{x}$ con respecto al vector columna $\\textbf{x}$. Para esto, se crea la variable $\\textbf{x}$ y se le asigna un valor inicial:\n\n\n\n\n```python\nimport torch\nx = torch.arange(4.0)\nx\n```\n\n\n\n\n    tensor([0., 1., 2., 3.])\n\n\n\nAntes de calcular el gradiente, se necesita un lugar para almacenarlo. Se debe tomar en cuenta que no se debe asignar nueva memoria cada vez que se tome una derivada respecto a un par\u00e1metro, ya que, probablemente se actualice millones de veces. \n\n\n```python\nx.requires_grad_(True) # esto es lo mismo a poner x = torch.arange(4.0,requires_grad = True)\nx.grad # el valor por defecto es None\n```\n\n\n```python\ny = 2*torch.dot(x,x) # funcion y \ny\n```\n\n\n\n\n    tensor(28., grad_fn=<MulBackward0>)\n\n\n\nEl vector x tiene longitud 4, y al hacer producto punto con \u00e9l mismo, se obtiene un escalar que se asigna a y. El gradiente de $y$ respecto a cada componente de $\\textbf{x}$ se puede obtener llamando a la funci\u00f3n de retropropagaci\u00f3n, y luego imprimimos el gradiente:\n\n\n\n```python\ny.backward()\nx.grad\n```\n\n\n\n\n    tensor([ 0.,  4.,  8., 12.])\n\n\n\nEl gradiente de $y = 2\\textbf{x}^T\\textbf{x}$ con respecto a $\\textbf{x}$ deber\u00eda ser $4\\textbf{x}$. Para verificar comparamos el gradiente obtenido con el valor que debe ser y comprobamos si la operaci\u00f3n fue correcta:\n\n\n\n```python\nx.grad == 4*x\n```\n\n\n\n\n    tensor([True, True, True, True])\n\n\n\nCalculando otra funci\u00f3n de $x$, tenemos lo siguiente.\nEl gradiente se acumula, entonces se debe limpiar previamente:\n\n\n```python\nx.grad.zero_() # limpiar gradiente\ny = x.sum() # funcion que es la suma de los elementos del vector x\ny.backward() # retropropagaci\u00f3n\nx.grad # imprime gradiente\n```\n\n\n\n\n    tensor([1., 1., 1., 1.])\n\n\n\n## Retropropagaci\u00f3n de variables no escalares\nLa interpretaci\u00f3n de la diferenciaci\u00f3n de un vector $\\textbf{y}$ (que no es ecalar) con respecto a un vector $\\textbf{x}$ es una matriz. Para vectores de mayor orden y dimensi\u00f3n, el resultado podr\u00eda ser un tensor de alto orden.\n\nEn estos ejemplos no se pretende calcular la matriz de diferenciaci\u00f3n, sino la suma de las derivadas parciales calculadas indivialmente para cada ejemplo en el lote.\n\nLlamar a la funci\u00f3n _backward_ en una funci\u00f3n no escalar requiere pasar un argumento \"gradient\" que especifica el gradiente de la funci\u00f3n diferenciada con respecto a \"self\". En este ejemplo, simplemente queremos sumar las derivadas parciales, por lo que pasar un gradiente de puros unos es adecuado:\n\n\n\n```python\nx.grad.zero_()\ny = x*x\n\ny.sum().backward() # esto es igual a y.backward(torch.ones(len(x)))\nx.grad\n```\n\n\n\n\n    tensor([0., 2., 4., 6.])\n\n\n\n## C\u00e1lculo de desprendimiento\n\nDigamos que tenemos a una funci\u00f3n $\\textbf{y}$ como una funci\u00f3n de $\\textbf{x}$, y una funci\u00f3n $\\textbf{z}$ como funci\u00f3n de $\\textbf{y}$ y de $\\textbf{x}$. Si quisi\u00e9ramos calcular el gradiente de $\\textbf{z}$ con respecto a $\\textbf{x}$, y tratar a $\\textbf{y}$ como una constante.\n\nEntonces podemos separar $\\textbf{y}$ para devolver una nueva variable $\\textbf{u}$ que tiene el mismo valor de $\\textbf{y}$ pero que descarta cualquier informaci\u00f3n sobre c\u00f3mo se calcul\u00f3 y en el gr\u00e1fico computacional, es decir, el gradiente no fluir\u00e1 hacia atr\u00e1s a trav\u00e9s de $\\textbf{u}$ hasta $\\textbf{x}$. De este modo, la siguiente funci\u00f3n de retropropagaci\u00f3n calcula la derivada parcial de $\\textbf{z} = \\textbf{u}*\\textbf{x}$ con respecto a $\\textbf{x}$, tratando a $\\textbf{u}$ como una constante, en lugar de hacer la derivada parcial de $\\textbf{z} = \\textbf{x}*\\textbf{x}*\\textbf{x}$ con respecto a $\\textbf{x}$.\n\nEsto se muestra a continuaci\u00f3n:\n\n\n\n```python\nx.grad.zero_()\ny = x * x\nu = y.detach()\nz = u * x\n\nz.sum().backward()\nx.grad == u\n```\n\n\n\n\n    tensor([True, True, True, True])\n\n\n\n## C\u00e1lculo del gradiente del flujo de control en Python\nEn el siguiente c\u00f3digo, el n\u00famero de iteraciones del bucle while y la evaluaci\u00f3n de la sentencia if depende del valor de la entrada a.\n\n\n\n\n```python\ndef f(a):\n    b = a * 2\n    while b.norm() < 1000:\n        b = b * 2\n    if b.sum() > 0:\n        c = b\n    else:\n        c = 100 * b\n    return c\n    \n```\n\nCalculando el gradiente:\n\n\n\n```python\na = torch.randn(size=(), requires_grad=True)\nd = f(a)\nd.backward()\n```\n\nEn la funci\u00f3n $f$ definida previamente es lineal a trozos en su entrada $a$, es decir, para cualquier $a$ existe alg\u00fan escalar constante $k$ tal que, $f(a) = k*a$, donde el valor de $k$ depende de la entrada $a$. En consecuencia $d/a$ nos permite verificar que el gradiente es correcto.\n\n\n\n```python\na.grad == d / a\n```\n\n\n\n\n    tensor(True)\n\n\n\n# Probabilidad\n## Teor\u00eda b\u00e1sica de la probabilidad\n\nSi lanzamos un dado y queremos saber cu\u00e1l es la probabilidad de ver un 1 en lugar de otro d\u00edgito. Si el dado es justo, los seis resultados $\\{1,...,6\\}$ tienen la misma probabilidad de ocurrir. Decimos entonces que el 1 puede salir con una probabilidad de $\\frac{1}{6}$.\n\nUn enfoque natural para cada valor es tomar el recuento individual para un valor y dividirlo por el n\u00famero total de lanzamientos, d\u00e1ndonos una estimaci\u00f3n de la probabilidad de un evento determinado.\n\nImportamos lo siguiente:\n\n\n\n```python\n%matplotlib inline\nimport torch\nfrom torch.distributions import multinomial\nfrom d2l import torch as d2l\n```\n\nEn estad\u00edstica se llama muestreo al proceso de extraer ejemplos de las distribuciones de probabilidad. La distribuci\u00f3n que asigna probabilidades a un n\u00famero de opciones discretas se llama distribuci\u00f3n multinomial.\n\nPara extraer una muestra, se pasa un vector de probabilidades. La salida es un vector de la misma longitud: su valor en el \u00edndice $i$ es el n\u00famero de veces que el resultado de la muestra corresponde a $i$.\n\n\n\n\n```python\nfair_probs = torch.ones([6]) / 6\nmultinomial.Multinomial(1, fair_probs).sample()\n```\n\n\n\n\n    tensor([0., 0., 0., 0., 1., 0.])\n\n\n\nSi se ejecuta el c\u00f3digo anterior varias veces, se obtendr\u00e1n valores aleatorios. La funci\u00f3n utilizada soporta la extracci\u00f3n de m\u00faltiples muestras a la vez, devoldiendo un array de muestras independientes.\n\n\n```python\nmultinomial.Multinomial(10, fair_probs).sample()\n\n```\n\n\n\n\n    tensor([2., 1., 1., 2., 4., 0.])\n\n\n\nEl c\u00f3digo anterior ya no solo simula la tirada de un dado una vez, sino que la simula para 10 tiradas, y podemos ver cuantas veces sali\u00f3 cada n\u00famero. En concreto, calculamos la frecuencia relativa como estimaci\u00f3n de la probabilidad real.\n\nPara 1000 tiradas:\n\n\n\n```python\ncounts = multinomial.Multinomial(1000, fair_probs).sample()\ncounts / 1000  # frecuencia relativa como estimaci\u00f3n\n```\n\n\n\n\n    tensor([0.1670, 0.1820, 0.1710, 0.1600, 0.1640, 0.1560])\n\n\n\nLas probabilidades obtenidas parecen bastante buenas, debido a que la probabilidad real antes mencionada es de $\\frac{1}{6} \u2248 0.167$.\n\nPodemos visualizar c\u00f3mo estas probabilidades convergen con el tiempo hacia la probabilidad real.\n\nRealizando 500 grupos de experimentos en los que cada grupo extrae 10 muestras:\n\n\n\n```python\ncounts = multinomial.Multinomial(10, fair_probs).sample((500,))\ncum_counts = counts.cumsum(dim=0)\nestimates = cum_counts / cum_counts.sum(dim=1, keepdims=True)\n\nd2l.set_figsize((6, 4.5))\nfor i in range(6):\n    d2l.plt.plot(estimates[:, i].numpy(),\n                 label=(\"P(die=\" + str(i + 1) + \")\"))\nd2l.plt.axhline(y=0.167, color='black', linestyle='dashed')\nd2l.plt.gca().set_xlabel('Groups of experiments')\nd2l.plt.gca().set_ylabel('Estimated probability')\nd2l.plt.legend();\n```\n\nCada curva corresponde a uno de los seis valores del dado. La l\u00ednea negra discontinua da la verdadera probabilidad subyacente. A medida que se obtienen m\u00e1s datos realizando m\u00e1s experimentos, las 6 curvas convergen hacia la verdadera probabilidad.\n\n\n# Documentaci\u00f3n\n## C\u00f3mo encontrar todas las funciones y clases de un m\u00f3dulo\n\nPara saber qu\u00e9 funciones y clases se pueden llamar en un m\u00f3dulo, se utiliza la funci\u00f3n dir.\nPor ejemplo, con el m\u00f3dulo para generar n\u00fameros aleatorios:\n\n\n```python\nimport torch\n\nprint(dir(torch.distributions))\n```\n\n    ['AbsTransform', 'AffineTransform', 'Bernoulli', 'Beta', 'Binomial', 'CatTransform', 'Categorical', 'Cauchy', 'Chi2', 'ComposeTransform', 'ContinuousBernoulli', 'CorrCholeskyTransform', 'Dirichlet', 'Distribution', 'ExpTransform', 'Exponential', 'ExponentialFamily', 'FisherSnedecor', 'Gamma', 'Geometric', 'Gumbel', 'HalfCauchy', 'HalfNormal', 'Independent', 'IndependentTransform', 'Kumaraswamy', 'LKJCholesky', 'Laplace', 'LogNormal', 'LogisticNormal', 'LowRankMultivariateNormal', 'LowerCholeskyTransform', 'MixtureSameFamily', 'Multinomial', 'MultivariateNormal', 'NegativeBinomial', 'Normal', 'OneHotCategorical', 'OneHotCategoricalStraightThrough', 'Pareto', 'Poisson', 'PowerTransform', 'RelaxedBernoulli', 'RelaxedOneHotCategorical', 'ReshapeTransform', 'SigmoidTransform', 'SoftmaxTransform', 'StackTransform', 'StickBreakingTransform', 'StudentT', 'TanhTransform', 'Transform', 'TransformedDistribution', 'Uniform', 'VonMises', 'Weibull', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'bernoulli', 'beta', 'biject_to', 'binomial', 'categorical', 'cauchy', 'chi2', 'constraint_registry', 'constraints', 'continuous_bernoulli', 'dirichlet', 'distribution', 'exp_family', 'exponential', 'fishersnedecor', 'gamma', 'geometric', 'gumbel', 'half_cauchy', 'half_normal', 'identity_transform', 'independent', 'kl', 'kl_divergence', 'kumaraswamy', 'laplace', 'lkj_cholesky', 'log_normal', 'logistic_normal', 'lowrank_multivariate_normal', 'mixture_same_family', 'multinomial', 'multivariate_normal', 'negative_binomial', 'normal', 'one_hot_categorical', 'pareto', 'poisson', 'register_kl', 'relaxed_bernoulli', 'relaxed_categorical', 'studentT', 'transform_to', 'transformed_distribution', 'transforms', 'uniform', 'utils', 'von_mises', 'weibull']\n\n\nDe forma general, se pueden ignorar las funciones que empiezan y terminan con _ (son objetos especiales en Python) o las funciones que empizan solo con _ (son normalmente funciones internas).\n\n#### Encontrar el uso de funciones y clases espec\u00edficas\n\nPara obtener instrucciones m\u00e1s espec\u00edficas sobre c\u00f3mo utilizar una determinada funci\u00f3n o clase, podemos invocar a la funci\u00f3n de ayuda.\n\nEjemplo: funci\u00f3n ones de los tensores.\n\n\n\n\n```python\nhelp(torch.ones)\n```\n\n    Help on built-in function ones:\n    \n    ones(...)\n        ones(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor\n        \n        Returns a tensor filled with the scalar value `1`, with the shape defined\n        by the variable argument :attr:`size`.\n        \n        Args:\n            size (int...): a sequence of integers defining the shape of the output tensor.\n                Can be a variable number of arguments or a collection like a list or tuple.\n        \n        Keyword arguments:\n            out (Tensor, optional): the output tensor.\n            dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.\n                Default: if ``None``, uses a global default (see :func:`torch.set_default_tensor_type`).\n            layout (:class:`torch.layout`, optional): the desired layout of returned Tensor.\n                Default: ``torch.strided``.\n            device (:class:`torch.device`, optional): the desired device of returned tensor.\n                Default: if ``None``, uses the current device for the default tensor type\n                (see :func:`torch.set_default_tensor_type`). :attr:`device` will be the CPU\n                for CPU tensor types and the current CUDA device for CUDA tensor types.\n            requires_grad (bool, optional): If autograd should record operations on the\n                returned tensor. Default: ``False``.\n        \n        Example::\n        \n            >>> torch.ones(2, 3)\n            tensor([[ 1.,  1.,  1.],\n                    [ 1.,  1.,  1.]])\n        \n            >>> torch.ones(5)\n            tensor([ 1.,  1.,  1.,  1.,  1.])\n    \n\n\nA partir de su documentaci\u00f3n, podemos ver que la funci\u00f3n ones crea un nuevo tensor con la forma especificada y establece todos los elementos con el valor de 1.\n\n\n```python\ntorch.ones(4)\n```\n\n\n\n\n    tensor([1., 1., 1., 1.])\n\n\n\nEn Jupyter Notebook, podemos utilizar el signo \"?\" para mostrar el documento en otra ventana. Por ejemplo, list? crear\u00e1 un contenido casi id\u00e9ntico a help(list), mostr\u00e1ndolo en una nueva ventana del navegador. Adem\u00e1s, si se utilizan dos signos \"??\", tambi\u00e9n se mostrar\u00e1 el c\u00f3digo Python que implementa la funci\u00f3n.\n\n# Referencia\nDive into Deep Learning. Recuperado de: http://www.d2l.ai/index.html\n", "meta": {"hexsha": "71d909dfcac0acc4dc3f7cca384ac152aad20530", "size": 139691, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "PyTorch_preliminares.ipynb", "max_stars_repo_name": "AlanLopez1017/deep-learning-v2-pytorch", "max_stars_repo_head_hexsha": "441f66540a48d5e125065b923147877ed2ca1942", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PyTorch_preliminares.ipynb", "max_issues_repo_name": "AlanLopez1017/deep-learning-v2-pytorch", "max_issues_repo_head_hexsha": "441f66540a48d5e125065b923147877ed2ca1942", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PyTorch_preliminares.ipynb", "max_forks_repo_name": "AlanLopez1017/deep-learning-v2-pytorch", "max_forks_repo_head_hexsha": "441f66540a48d5e125065b923147877ed2ca1942", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6900868677, "max_line_length": 1848, "alphanum_fraction": 0.4975911118, "converted": true, "num_tokens": 21459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20434190962774398, "lm_q2_score": 0.06465348970791007, "lm_q1q2_score": 0.013211417551012036}}
{"text": "```python\nimport sys\nsys.stdout.write('hello world\\n')\nsys.stdout.flush()\nfor i in range(3):\n    sys.stdout.write('%s\\n' % i)\n```\n\n    hello world\n    0\n    1\n    2\n\n\n    output to stderr\n\n\n    some more stdout text\n\n\n\n```python\n\n```\n\n\n```python\n    sys.stdout.flush()\nsys.stderr.write('output to stderr\\n')\nsys.stderr.flush()\nsys.stdout.write('some more stdout text\\n')\nsys.stdout.flush()\n```\n\n# Markdown Cell\n\n$ e^{ \\pm i\\theta } = \\cos \\theta \\pm i\\sin \\theta + \\beta $\n\n*It* **really** is!\n\n\n```python\nthis is a syntax error\n```\n\n\n```python\nprint('test')\n```\n\n\n```python\nfrom IPython.display import Latex\nLatex('''The mass-energy equivalence is described by the famous equation\n \n$$E=mc^2$$\n \ndiscovered in 1905 by Albert Einstein. \nIn natural units ($c$ = 1), the formula expresses the identity\n \n\\\\begin{equation}\nE=m\n\\\\end{equation}''')\n```\n\n\n\n\nThe mass-energy equivalence is described by the famous equation\n \n$$E=mc^2$$\n \ndiscovered in 1905 by Albert Einstein. \nIn natural units ($c$ = 1), the formula expresses the identity\n \n\\begin{equation}\nE=m\n\\end{equation}\n\n\n\n\n```python\n!pip install numpy ipywidgets bqplot plotly ipympl ipyleaflet ipycytoscape\n```\n\n\n```python\nfrom IPython.display import display\nimport ipywidgets as w\n# s = w.IntSlider(0, 10)\u00a3\n# s\na = w.IntSlider()\nb = w.IntText()\nw.jslink((a, 'value'), (b, 'value'))\ndisplay(a, b)\n```\n\n\n    IntSlider(value=0)\n\n\n\n    IntText(value=0)\n\n\n\n```python\nimport plotly.express as px\ndf = px.data.tips()\nfig = px.histogram(df, x=\"total_bill\", y=\"tip\", color=\"sex\", marginal=\"rug\",\n                    hover_data=df.columns)\nfig.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "01fdd15efc3f972a430d6eb9fe24d8264a7fd43f", "size": 5217, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "dev/content/example.ipynb", "max_stars_repo_name": "datalayer/jupyterpool", "max_stars_repo_head_hexsha": "60f888a676c8826cf4bbf6b466ff9cda4e3232a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-05-31T05:40:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-06T14:06:11.000Z", "max_issues_repo_path": "dev/content/example.ipynb", "max_issues_repo_name": "datalayer/jupyterpool", "max_issues_repo_head_hexsha": "60f888a676c8826cf4bbf6b466ff9cda4e3232a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dev/content/example.ipynb", "max_forks_repo_name": "datalayer/jupyterpool", "max_forks_repo_head_hexsha": "60f888a676c8826cf4bbf6b466ff9cda4e3232a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9201680672, "max_line_length": 276, "alphanum_fraction": 0.4987540732, "converted": true, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091278688527247, "lm_q2_score": 0.052618957433256106, "lm_q1q2_score": 0.013202769252575812}}
{"text": "**Installation**\r\n\r\nThis tutorial shows the details of installation on Google Golaboratory.\n\n**Step 1**\r\n\r\nFor changing version. (Edit: 2021/3/11)\n\n\n```\n!pip3 uninstall -y imgaug && pip3 uninstall -y albumentations && pip3 install git+https://github.com/aleju/imgaug.git\n```\n\n    Uninstalling imgaug-0.2.9:\n      Successfully uninstalled imgaug-0.2.9\n    Uninstalling albumentations-0.1.12:\n      Successfully uninstalled albumentations-0.1.12\n    Collecting git+https://github.com/aleju/imgaug.git\n      Cloning https://github.com/aleju/imgaug.git to /tmp/pip-req-build-gr2gwkbk\n      Running command git clone -q https://github.com/aleju/imgaug.git /tmp/pip-req-build-gr2gwkbk\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from imgaug==0.4.0) (1.15.0)\n    Requirement already satisfied: numpy>=1.15 in /usr/local/lib/python3.7/dist-packages (from imgaug==0.4.0) (1.19.5)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from imgaug==0.4.0) (1.4.1)\n    Requirement already satisfied: Pillow in /usr/local/lib/python3.7/dist-packages (from imgaug==0.4.0) (7.0.0)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from imgaug==0.4.0) (3.2.2)\n    Requirement already satisfied: scikit-image>=0.14.2 in /usr/local/lib/python3.7/dist-packages (from imgaug==0.4.0) (0.16.2)\n    Requirement already satisfied: opencv-python in /usr/local/lib/python3.7/dist-packages (from imgaug==0.4.0) (4.1.2.30)\n    Requirement already satisfied: Shapely in /usr/local/lib/python3.7/dist-packages (from imgaug==0.4.0) (1.7.1)\n    Requirement already satisfied: imageio in /usr/local/lib/python3.7/dist-packages (from imgaug==0.4.0) (2.4.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->imgaug==0.4.0) (0.10.0)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->imgaug==0.4.0) (2.8.1)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->imgaug==0.4.0) (1.3.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->imgaug==0.4.0) (2.4.7)\n    Requirement already satisfied: PyWavelets>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image>=0.14.2->imgaug==0.4.0) (1.1.1)\n    Requirement already satisfied: networkx>=2.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image>=0.14.2->imgaug==0.4.0) (2.5)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.0->scikit-image>=0.14.2->imgaug==0.4.0) (4.4.2)\n    Building wheels for collected packages: imgaug\n      Building wheel for imgaug (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for imgaug: filename=imgaug-0.4.0-cp37-none-any.whl size=971106 sha256=170d630e961d591517b12f6fc6ac5903448981d4fc2294f55fd320de1a4bbaa7\n      Stored in directory: /tmp/pip-ephem-wheel-cache-vz772e__/wheels/65/3d/94/ee32cbeaa29c473a4db74c2d21904ac747311fdca4732665f0\n    Successfully built imgaug\n    Installing collected packages: imgaug\n    Successfully installed imgaug-0.4.0\n\n\n\n```\n!pip3 install pymatgen==2020.10.20\r\nimport pymatgen\r\nprint(pymatgen.__version__)\n```\n\n    Collecting pymatgen==2020.10.20\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/8c/de/04bb4d40af6b4a0a9c14ca859beba61631644b24b4228783ca8a743ba811/pymatgen-2020.10.20.tar.gz (2.8MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.8MB 18.0MB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.14.3 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.10.20) (1.19.5)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.10.20) (2.23.0)\n    Collecting ruamel.yaml>=0.15.6\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/ed/c3/4c823dac2949a6baf36a4987d04c50d30184147393ba6f4bfb4c67d15a13/ruamel.yaml-0.16.13-py2.py3-none-any.whl (111kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 112kB 55.1MB/s \n    \u001b[?25hCollecting monty>=3.0.2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/41/47/e6f045cd69f24df0b4ddd55fab329c079b7c9ce978a32431dce904f6a1d6/monty-2021.3.3-py3-none-any.whl (63kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 71kB 10.6MB/s \n    \u001b[?25hCollecting scipy>=1.5.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/b6/3a/9e0649ab2d5ade703baa70ef980aa08739226e5d6a642f084bb201a92fc2/scipy-1.6.1-cp37-cp37m-manylinux1_x86_64.whl (27.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 27.4MB 104kB/s \n    \u001b[?25hRequirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.10.20) (0.8.9)\n    Collecting spglib>=1.9.9.44\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/4b/98/fa4760b9c71e2eace5a60b85dbf36dece49c379f8291cf1203056f287766/spglib-1.16.1-cp37-cp37m-manylinux2010_x86_64.whl (296kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 296kB 59.7MB/s \n    \u001b[?25hRequirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.10.20) (2.5)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.10.20) (3.2.2)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.10.20) (3.3.0)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.10.20) (1.7.1)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from pymatgen==2020.10.20) (1.1.5)\n    Collecting plotly>=4.5.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1f/f6/bd3c17c8003b6641df1228e80e1acac97ed8402635e46c2571f8e1ef63af/plotly-4.14.3-py2.py3-none-any.whl (13.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 13.2MB 250kB/s \n    \u001b[?25hCollecting uncertainties>=3.1.4\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/45/41/fc7e7b73b603e7c2c9e040b7aa8caf4a88d74b6faa567601ed82b6f0d8e1/uncertainties-3.1.5-py2.py3-none-any.whl (246kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 256kB 58.1MB/s \n    \u001b[?25hRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2020.10.20) (2.10)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2020.10.20) (1.24.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2020.10.20) (2020.12.5)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pymatgen==2020.10.20) (3.0.4)\n    Collecting ruamel.yaml.clib>=0.1.2; platform_python_implementation == \"CPython\" and python_version < \"3.10\"\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/5e/6e/f652c56bbb2c3d3fca252ffc7c0358597f57a1bbdf484dac683054950c63/ruamel.yaml.clib-0.2.2-cp37-cp37m-manylinux1_x86_64.whl (547kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 552kB 54.6MB/s \n    \u001b[?25hRequirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.7/dist-packages (from networkx>=2.2->pymatgen==2020.10.20) (4.4.2)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2020.10.20) (2.8.1)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2020.10.20) (1.3.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2020.10.20) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=1.5->pymatgen==2020.10.20) (0.10.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->pymatgen==2020.10.20) (1.2.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->pymatgen==2020.10.20) (2018.9)\n    Requirement already satisfied: retrying>=1.3.3 in /usr/local/lib/python3.7/dist-packages (from plotly>=4.5.0->pymatgen==2020.10.20) (1.3.3)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from plotly>=4.5.0->pymatgen==2020.10.20) (1.15.0)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from uncertainties>=3.1.4->pymatgen==2020.10.20) (0.16.0)\n    Building wheels for collected packages: pymatgen\n      Building wheel for pymatgen (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pymatgen: filename=pymatgen-2020.10.20-cp37-cp37m-linux_x86_64.whl size=3574629 sha256=9e9d3c2e6e7a0158317b6d7ab23400c9bd674ff5c4c6be85192272c0224547fd\n      Stored in directory: /root/.cache/pip/wheels/bd/4f/51/2486277ea75c759064ca64fc0058b244f48d5cef7d724ca27c\n    Successfully built pymatgen\n    Installing collected packages: ruamel.yaml.clib, ruamel.yaml, monty, scipy, spglib, plotly, uncertainties, pymatgen\n      Found existing installation: scipy 1.4.1\n        Uninstalling scipy-1.4.1:\n          Successfully uninstalled scipy-1.4.1\n      Found existing installation: plotly 4.4.1\n        Uninstalling plotly-4.4.1:\n          Successfully uninstalled plotly-4.4.1\n    Successfully installed monty-2021.3.3 plotly-4.14.3 pymatgen-2020.10.20 ruamel.yaml-0.16.13 ruamel.yaml.clib-0.2.2 scipy-1.6.1 spglib-1.16.1 uncertainties-3.1.5\n    2020.10.20\n\n\nStep 2\r\n\r\nInstall Anaconda and set PATH.\n\n\n```\n!wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh\r\n!bash Miniconda3-latest-Linux-x86_64.sh -b -f -p /usr/local\r\nimport sys\r\nsys.path.append('/usr/local/lib/python3.6/site-packages/')\n```\n\n    --2021-03-10 21:26:45--  https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh\n    Resolving repo.continuum.io (repo.continuum.io)... 104.18.201.79, 104.18.200.79, 2606:4700::6812:c84f, ...\n    Connecting to repo.continuum.io (repo.continuum.io)|104.18.201.79|:443... connected.\n    HTTP request sent, awaiting response... 301 Moved Permanently\n    Location: https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh [following]\n    --2021-03-10 21:26:46--  https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh\n    Resolving repo.anaconda.com (repo.anaconda.com)... 104.16.131.3, 104.16.130.3, 2606:4700::6810:8203, ...\n    Connecting to repo.anaconda.com (repo.anaconda.com)|104.16.131.3|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 94235922 (90M) [application/x-sh]\n    Saving to: \u2018Miniconda3-latest-Linux-x86_64.sh\u2019\n    \n    Miniconda3-latest-L 100%[===================>]  89.87M   210MB/s    in 0.4s    \n    \n    2021-03-10 21:26:46 (210 MB/s) - \u2018Miniconda3-latest-Linux-x86_64.sh\u2019 saved [94235922/94235922]\n    \n    PREFIX=/usr/local\n    Unpacking payload ...\n    Collecting package metadata (current_repodata.json): - \b\b\\ \b\b| \b\bdone\n    Solving environment: - \b\b\\ \b\bdone\n    \n    ## Package Plan ##\n    \n      environment location: /usr/local\n    \n      added / updated specs:\n        - _libgcc_mutex==0.1=main\n        - brotlipy==0.7.0=py38h27cfd23_1003\n        - ca-certificates==2020.10.14=0\n        - certifi==2020.6.20=pyhd3eb1b0_3\n        - cffi==1.14.3=py38h261ae71_2\n        - chardet==3.0.4=py38h06a4308_1003\n        - conda-package-handling==1.7.2=py38h03888b9_0\n        - conda==4.9.2=py38h06a4308_0\n        - cryptography==3.2.1=py38h3c74f83_1\n        - idna==2.10=py_0\n        - ld_impl_linux-64==2.33.1=h53a641e_7\n        - libedit==3.1.20191231=h14c3975_1\n        - libffi==3.3=he6710b0_2\n        - libgcc-ng==9.1.0=hdf63c60_0\n        - libstdcxx-ng==9.1.0=hdf63c60_0\n        - ncurses==6.2=he6710b0_1\n        - openssl==1.1.1h=h7b6447c_0\n        - pip==20.2.4=py38h06a4308_0\n        - pycosat==0.6.3=py38h7b6447c_1\n        - pycparser==2.20=py_2\n        - pyopenssl==19.1.0=pyhd3eb1b0_1\n        - pysocks==1.7.1=py38h06a4308_0\n        - python==3.8.5=h7579374_1\n        - readline==8.0=h7b6447c_0\n        - requests==2.24.0=py_0\n        - ruamel_yaml==0.15.87=py38h7b6447c_1\n        - setuptools==50.3.1=py38h06a4308_1\n        - six==1.15.0=py38h06a4308_0\n        - sqlite==3.33.0=h62c20be_0\n        - tk==8.6.10=hbc83047_0\n        - tqdm==4.51.0=pyhd3eb1b0_0\n        - urllib3==1.25.11=py_0\n        - wheel==0.35.1=pyhd3eb1b0_0\n        - xz==5.2.5=h7b6447c_0\n        - yaml==0.2.5=h7b6447c_0\n        - zlib==1.2.11=h7b6447c_3\n    \n    \n    The following NEW packages will be INSTALLED:\n    \n      _libgcc_mutex      pkgs/main/linux-64::_libgcc_mutex-0.1-main\n      brotlipy           pkgs/main/linux-64::brotlipy-0.7.0-py38h27cfd23_1003\n      ca-certificates    pkgs/main/linux-64::ca-certificates-2020.10.14-0\n      certifi            pkgs/main/noarch::certifi-2020.6.20-pyhd3eb1b0_3\n      cffi               pkgs/main/linux-64::cffi-1.14.3-py38h261ae71_2\n      chardet            pkgs/main/linux-64::chardet-3.0.4-py38h06a4308_1003\n      conda              pkgs/main/linux-64::conda-4.9.2-py38h06a4308_0\n      conda-package-han~ pkgs/main/linux-64::conda-package-handling-1.7.2-py38h03888b9_0\n      cryptography       pkgs/main/linux-64::cryptography-3.2.1-py38h3c74f83_1\n      idna               pkgs/main/noarch::idna-2.10-py_0\n      ld_impl_linux-64   pkgs/main/linux-64::ld_impl_linux-64-2.33.1-h53a641e_7\n      libedit            pkgs/main/linux-64::libedit-3.1.20191231-h14c3975_1\n      libffi             pkgs/main/linux-64::libffi-3.3-he6710b0_2\n      libgcc-ng          pkgs/main/linux-64::libgcc-ng-9.1.0-hdf63c60_0\n      libstdcxx-ng       pkgs/main/linux-64::libstdcxx-ng-9.1.0-hdf63c60_0\n      ncurses            pkgs/main/linux-64::ncurses-6.2-he6710b0_1\n      openssl            pkgs/main/linux-64::openssl-1.1.1h-h7b6447c_0\n      pip                pkgs/main/linux-64::pip-20.2.4-py38h06a4308_0\n      pycosat            pkgs/main/linux-64::pycosat-0.6.3-py38h7b6447c_1\n      pycparser          pkgs/main/noarch::pycparser-2.20-py_2\n      pyopenssl          pkgs/main/noarch::pyopenssl-19.1.0-pyhd3eb1b0_1\n      pysocks            pkgs/main/linux-64::pysocks-1.7.1-py38h06a4308_0\n      python             pkgs/main/linux-64::python-3.8.5-h7579374_1\n      readline           pkgs/main/linux-64::readline-8.0-h7b6447c_0\n      requests           pkgs/main/noarch::requests-2.24.0-py_0\n      ruamel_yaml        pkgs/main/linux-64::ruamel_yaml-0.15.87-py38h7b6447c_1\n      setuptools         pkgs/main/linux-64::setuptools-50.3.1-py38h06a4308_1\n      six                pkgs/main/linux-64::six-1.15.0-py38h06a4308_0\n      sqlite             pkgs/main/linux-64::sqlite-3.33.0-h62c20be_0\n      tk                 pkgs/main/linux-64::tk-8.6.10-hbc83047_0\n      tqdm               pkgs/main/noarch::tqdm-4.51.0-pyhd3eb1b0_0\n      urllib3            pkgs/main/noarch::urllib3-1.25.11-py_0\n      wheel              pkgs/main/noarch::wheel-0.35.1-pyhd3eb1b0_0\n      xz                 pkgs/main/linux-64::xz-5.2.5-h7b6447c_0\n      yaml               pkgs/main/linux-64::yaml-0.2.5-h7b6447c_0\n      zlib               pkgs/main/linux-64::zlib-1.2.11-h7b6447c_3\n    \n    \n    Preparing transaction: / \b\b- \b\b\\ \b\bdone\n    Executing transaction: / \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\bdone\n    installation finished.\n    WARNING:\n        You currently have a PYTHONPATH environment variable set. This may cause\n        unexpected behavior when running the Python interpreter in Miniconda3.\n        For best results, please verify that your PYTHONPATH only points to\n        directories of packages that are compatible with the Python interpreter\n        in Miniconda3: /usr/local\n\n\n**step 3**\r\n\r\nInstall RDKit and check version.\n\n\n```\n!conda install -q -y -c rdkit rdkit=2020.3 python=3.6\r\nimport rdkit\r\nprint(rdkit.__version__)\n```\n\n    Collecting package metadata (current_repodata.json): ...working... done\n    Solving environment: ...working... failed with initial frozen solve. Retrying with flexible solve.\n    Solving environment: ...working... failed with repodata from current_repodata.json, will retry with next repodata source.\n    Collecting package metadata (repodata.json): ...working... done\n    Solving environment: ...working... done\n    \n    ## Package Plan ##\n    \n      environment location: /usr/local\n    \n      added / updated specs:\n        - python=3.6\n        - rdkit=2020.3\n    \n    \n    The following packages will be downloaded:\n    \n        package                    |            build\n        ---------------------------|-----------------\n        blas-1.0                   |              mkl           6 KB\n        brotlipy-0.7.0             |py36h27cfd23_1003         320 KB\n        bzip2-1.0.8                |       h7b6447c_0          78 KB\n        ca-certificates-2021.1.19  |       h06a4308_1         118 KB\n        cairo-1.16.0               |       hf32fb01_1         1.0 MB\n        certifi-2020.12.5          |   py36h06a4308_0         140 KB\n        cffi-1.14.5                |   py36h261ae71_0         222 KB\n        chardet-3.0.4              |py36h06a4308_1003         180 KB\n        conda-4.9.2                |   py36h06a4308_0         2.9 MB\n        conda-package-handling-1.7.2|   py36h03888b9_0         886 KB\n        cryptography-3.3.1         |   py36h3c74f83_1         567 KB\n        fontconfig-2.13.1          |       h6c09931_0         250 KB\n        freetype-2.10.4            |       h5ab3b9f_0         596 KB\n        glib-2.67.4                |       h36276a3_1         3.0 MB\n        icu-58.2                   |       he6710b0_3        10.5 MB\n        intel-openmp-2020.2        |              254         786 KB\n        jpeg-9b                    |       h024ee3a_2         214 KB\n        lcms2-2.11                 |       h396b838_0         307 KB\n        libboost-1.67.0            |       h46d08c1_4        13.0 MB\n        libpng-1.6.37              |       hbc83047_0         278 KB\n        libtiff-4.1.0              |       h2733197_1         449 KB\n        libuuid-1.0.3              |       h1bed415_2          15 KB\n        libxcb-1.14                |       h7b6447c_0         505 KB\n        libxml2-2.9.10             |       hb55368b_3         1.2 MB\n        lz4-c-1.9.3                |       h2531618_0         186 KB\n        mkl-2020.2                 |              256       138.3 MB\n        mkl-service-2.3.0          |   py36he8ac12f_0          52 KB\n        mkl_fft-1.3.0              |   py36h54f3939_0         170 KB\n        mkl_random-1.1.1           |   py36h0573a6f_0         327 KB\n        numpy-1.19.2               |   py36h54aff64_0          22 KB\n        numpy-base-1.19.2          |   py36hfa32c7d_0         4.1 MB\n        olefile-0.46               |           py36_0          48 KB\n        openssl-1.1.1j             |       h27cfd23_0         2.5 MB\n        pandas-1.1.5               |   py36ha9443f7_0         8.2 MB\n        pcre-8.44                  |       he6710b0_0         212 KB\n        pillow-8.1.2               |   py36he98fc37_0         627 KB\n        pip-21.0.1                 |   py36h06a4308_0         1.8 MB\n        pixman-0.40.0              |       h7b6447c_0         370 KB\n        py-boost-1.67.0            |   py36h04863e7_4         278 KB\n        pycosat-0.6.3              |   py36h27cfd23_0          82 KB\n        pysocks-1.7.1              |   py36h06a4308_0          31 KB\n        python-3.6.13              |       hdb3f193_0        29.7 MB\n        python-dateutil-2.8.1      |     pyhd3eb1b0_0         221 KB\n        pytz-2021.1                |     pyhd3eb1b0_0         181 KB\n        rdkit-2020.03.3.0          |   py36hc20afe1_1        24.7 MB  rdkit\n        ruamel_yaml-0.15.87        |   py36h7b6447c_1         244 KB\n        setuptools-52.0.0          |   py36h06a4308_0         724 KB\n        six-1.15.0                 |   py36h06a4308_0          27 KB\n        zstd-1.4.5                 |       h9ceee32_0         619 KB\n        ------------------------------------------------------------\n                                               Total:       251.0 MB\n    \n    The following NEW packages will be INSTALLED:\n    \n      blas               pkgs/main/linux-64::blas-1.0-mkl\n      bzip2              pkgs/main/linux-64::bzip2-1.0.8-h7b6447c_0\n      cairo              pkgs/main/linux-64::cairo-1.16.0-hf32fb01_1\n      fontconfig         pkgs/main/linux-64::fontconfig-2.13.1-h6c09931_0\n      freetype           pkgs/main/linux-64::freetype-2.10.4-h5ab3b9f_0\n      glib               pkgs/main/linux-64::glib-2.67.4-h36276a3_1\n      icu                pkgs/main/linux-64::icu-58.2-he6710b0_3\n      intel-openmp       pkgs/main/linux-64::intel-openmp-2020.2-254\n      jpeg               pkgs/main/linux-64::jpeg-9b-h024ee3a_2\n      lcms2              pkgs/main/linux-64::lcms2-2.11-h396b838_0\n      libboost           pkgs/main/linux-64::libboost-1.67.0-h46d08c1_4\n      libpng             pkgs/main/linux-64::libpng-1.6.37-hbc83047_0\n      libtiff            pkgs/main/linux-64::libtiff-4.1.0-h2733197_1\n      libuuid            pkgs/main/linux-64::libuuid-1.0.3-h1bed415_2\n      libxcb             pkgs/main/linux-64::libxcb-1.14-h7b6447c_0\n      libxml2            pkgs/main/linux-64::libxml2-2.9.10-hb55368b_3\n      lz4-c              pkgs/main/linux-64::lz4-c-1.9.3-h2531618_0\n      mkl                pkgs/main/linux-64::mkl-2020.2-256\n      mkl-service        pkgs/main/linux-64::mkl-service-2.3.0-py36he8ac12f_0\n      mkl_fft            pkgs/main/linux-64::mkl_fft-1.3.0-py36h54f3939_0\n      mkl_random         pkgs/main/linux-64::mkl_random-1.1.1-py36h0573a6f_0\n      numpy              pkgs/main/linux-64::numpy-1.19.2-py36h54aff64_0\n      numpy-base         pkgs/main/linux-64::numpy-base-1.19.2-py36hfa32c7d_0\n      olefile            pkgs/main/linux-64::olefile-0.46-py36_0\n      pandas             pkgs/main/linux-64::pandas-1.1.5-py36ha9443f7_0\n      pcre               pkgs/main/linux-64::pcre-8.44-he6710b0_0\n      pillow             pkgs/main/linux-64::pillow-8.1.2-py36he98fc37_0\n      pixman             pkgs/main/linux-64::pixman-0.40.0-h7b6447c_0\n      py-boost           pkgs/main/linux-64::py-boost-1.67.0-py36h04863e7_4\n      python-dateutil    pkgs/main/noarch::python-dateutil-2.8.1-pyhd3eb1b0_0\n      pytz               pkgs/main/noarch::pytz-2021.1-pyhd3eb1b0_0\n      rdkit              rdkit/linux-64::rdkit-2020.03.3.0-py36hc20afe1_1\n      zstd               pkgs/main/linux-64::zstd-1.4.5-h9ceee32_0\n    \n    The following packages will be UPDATED:\n    \n      ca-certificates                              2020.10.14-0 --> 2021.1.19-h06a4308_1\n      certifi            pkgs/main/noarch::certifi-2020.6.20-p~ --> pkgs/main/linux-64::certifi-2020.12.5-py36h06a4308_0\n      cffi                                1.14.3-py38h261ae71_2 --> 1.14.5-py36h261ae71_0\n      cryptography                         3.2.1-py38h3c74f83_1 --> 3.3.1-py36h3c74f83_1\n      openssl                                 1.1.1h-h7b6447c_0 --> 1.1.1j-h27cfd23_0\n      pip                                 20.2.4-py38h06a4308_0 --> 21.0.1-py36h06a4308_0\n      setuptools                          50.3.1-py38h06a4308_1 --> 52.0.0-py36h06a4308_0\n    \n    The following packages will be DOWNGRADED:\n    \n      brotlipy                          0.7.0-py38h27cfd23_1003 --> 0.7.0-py36h27cfd23_1003\n      chardet                           3.0.4-py38h06a4308_1003 --> 3.0.4-py36h06a4308_1003\n      conda                                4.9.2-py38h06a4308_0 --> 4.9.2-py36h06a4308_0\n      conda-package-han~                   1.7.2-py38h03888b9_0 --> 1.7.2-py36h03888b9_0\n      pycosat                              0.6.3-py38h7b6447c_1 --> 0.6.3-py36h27cfd23_0\n      pysocks                              1.7.1-py38h06a4308_0 --> 1.7.1-py36h06a4308_0\n      python                                   3.8.5-h7579374_1 --> 3.6.13-hdb3f193_0\n      ruamel_yaml                        0.15.87-py38h7b6447c_1 --> 0.15.87-py36h7b6447c_1\n      six                                 1.15.0-py38h06a4308_0 --> 1.15.0-py36h06a4308_0\n    \n    \n    Preparing transaction: ...working... done\n    Verifying transaction: ...working... done\n    Executing transaction: ...working... done\n    2020.03.3\n\n\n**step 4**\r\n\r\nInstall PyTorch and check version.\n\n\n```\n!conda install -y pytorch==1.7.0 torchvision==0.8.0 torchaudio==0.7.0 cudatoolkit=10.1 -c pytorch\r\nimport torch\r\nprint(torch.__version__)\n```\n\n    Collecting package metadata (current_repodata.json): - \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\bdone\n    Solving environment: \\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\bdone\n    \n    ## Package Plan ##\n    \n      environment location: /usr/local\n    \n      added / updated specs:\n        - cudatoolkit=10.1\n        - pytorch==1.7.0\n        - torchaudio==0.7.0\n        - torchvision==0.8.0\n    \n    \n    The following packages will be downloaded:\n    \n        package                    |            build\n        ---------------------------|-----------------\n        cudatoolkit-10.1.243       |       h6bb024c_0       347.4 MB\n        dataclasses-0.8            |     pyh4f3eec9_6          22 KB\n        libuv-1.40.0               |       h7b6447c_0         736 KB\n        ninja-1.10.2               |   py36hff7bd54_0         1.4 MB\n        pytorch-1.7.0              |py3.6_cuda10.1.243_cudnn7.6.3_0       552.4 MB  pytorch\n        torchaudio-0.7.0           |             py36         9.8 MB  pytorch\n        torchvision-0.8.0          |       py36_cu101        17.8 MB  pytorch\n        typing_extensions-3.7.4.3  |     pyha847dfd_0          25 KB\n        ------------------------------------------------------------\n                                               Total:       929.7 MB\n    \n    The following NEW packages will be INSTALLED:\n    \n      cudatoolkit        pkgs/main/linux-64::cudatoolkit-10.1.243-h6bb024c_0\n      dataclasses        pkgs/main/noarch::dataclasses-0.8-pyh4f3eec9_6\n      libuv              pkgs/main/linux-64::libuv-1.40.0-h7b6447c_0\n      ninja              pkgs/main/linux-64::ninja-1.10.2-py36hff7bd54_0\n      pytorch            pytorch/linux-64::pytorch-1.7.0-py3.6_cuda10.1.243_cudnn7.6.3_0\n      torchaudio         pytorch/linux-64::torchaudio-0.7.0-py36\n      torchvision        pytorch/linux-64::torchvision-0.8.0-py36_cu101\n      typing_extensions  pkgs/main/noarch::typing_extensions-3.7.4.3-pyha847dfd_0\n    \n    \n    \n    Downloading and Extracting Packages\n    typing_extensions-3. | 25 KB     | : 100% 1.0/1 [00:00<00:00, 22.48it/s]\n    torchaudio-0.7.0     | 9.8 MB    | : 100% 1.0/1 [00:01<00:00,  1.70s/it]               \n    ninja-1.10.2         | 1.4 MB    | : 100% 1.0/1 [00:00<00:00, 11.35it/s]\n    pytorch-1.7.0        | 552.4 MB  | : 100% 1.0/1 [01:15<00:00, 75.20s/it]               \n    cudatoolkit-10.1.243 | 347.4 MB  | : 100% 1.0/1 [00:16<00:00, 16.36s/it]               \n    libuv-1.40.0         | 736 KB    | : 100% 1.0/1 [00:01<00:00,  1.66s/it]\n    dataclasses-0.8      | 22 KB     | : 100% 1.0/1 [00:00<00:00, 23.68it/s]\n    torchvision-0.8.0    | 17.8 MB   | : 100% 1.0/1 [00:02<00:00,  2.49s/it] \n    Preparing transaction: \\ \b\b| \b\bdone\n    Verifying transaction: - \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\bdone\n    Executing transaction: \\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\bdone\n    1.8.0+cu101\n\n\n**step 4**\r\n\r\nInstall XenonPy and check version.\n\n\n```\n!wget https://raw.githubusercontent.com/by-student-2017/xenonpy-gcolab/main/0.4.4/conda_env/xepy36_cuda10.yml\r\n!conda create --yes -n xenonpy python=3.6\r\n!conda env update -n xenonpy -f xepy36_cuda10.yml\r\n!source activate xenonpy\n```\n\n    --2021-03-10 21:30:34--  https://raw.githubusercontent.com/by-student-2017/xenonpy-gcolab/main/0.4.4/conda_env/xepy36_cuda10.yml\n    Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ...\n    Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 524 [text/plain]\n    Saving to: \u2018xepy36_cuda10.yml\u2019\n    \n    xepy36_cuda10.yml   100%[===================>]     524  --.-KB/s    in 0s      \n    \n    2021-03-10 21:30:34 (23.8 MB/s) - \u2018xepy36_cuda10.yml\u2019 saved [524/524]\n    \n    Collecting package metadata (current_repodata.json): - \b\b\\ \b\b| \b\b/ \b\bdone\n    Solving environment: \\ \b\bdone\n    \n    ## Package Plan ##\n    \n      environment location: /usr/local/envs/xenonpy\n    \n      added / updated specs:\n        - python=3.6\n    \n    \n    The following packages will be downloaded:\n    \n        package                    |            build\n        ---------------------------|-----------------\n        readline-8.1               |       h27cfd23_0         362 KB\n        wheel-0.36.2               |     pyhd3eb1b0_0          33 KB\n        ------------------------------------------------------------\n                                               Total:         395 KB\n    \n    The following NEW packages will be INSTALLED:\n    \n      _libgcc_mutex      pkgs/main/linux-64::_libgcc_mutex-0.1-main\n      ca-certificates    pkgs/main/linux-64::ca-certificates-2021.1.19-h06a4308_1\n      certifi            pkgs/main/linux-64::certifi-2020.12.5-py36h06a4308_0\n      ld_impl_linux-64   pkgs/main/linux-64::ld_impl_linux-64-2.33.1-h53a641e_7\n      libedit            pkgs/main/linux-64::libedit-3.1.20191231-h14c3975_1\n      libffi             pkgs/main/linux-64::libffi-3.3-he6710b0_2\n      libgcc-ng          pkgs/main/linux-64::libgcc-ng-9.1.0-hdf63c60_0\n      libstdcxx-ng       pkgs/main/linux-64::libstdcxx-ng-9.1.0-hdf63c60_0\n      ncurses            pkgs/main/linux-64::ncurses-6.2-he6710b0_1\n      openssl            pkgs/main/linux-64::openssl-1.1.1j-h27cfd23_0\n      pip                pkgs/main/linux-64::pip-21.0.1-py36h06a4308_0\n      python             pkgs/main/linux-64::python-3.6.13-hdb3f193_0\n      readline           pkgs/main/linux-64::readline-8.1-h27cfd23_0\n      setuptools         pkgs/main/linux-64::setuptools-52.0.0-py36h06a4308_0\n      sqlite             pkgs/main/linux-64::sqlite-3.33.0-h62c20be_0\n      tk                 pkgs/main/linux-64::tk-8.6.10-hbc83047_0\n      wheel              pkgs/main/noarch::wheel-0.36.2-pyhd3eb1b0_0\n      xz                 pkgs/main/linux-64::xz-5.2.5-h7b6447c_0\n      zlib               pkgs/main/linux-64::zlib-1.2.11-h7b6447c_3\n    \n    \n    \n    Downloading and Extracting Packages\n    readline-8.1         | 362 KB    | : 100% 1.0/1 [00:00<00:00, 14.01it/s]\n    wheel-0.36.2         | 33 KB     | : 100% 1.0/1 [00:00<00:00, 22.78it/s]\n    Preparing transaction: / \b\b- \b\b\\ \b\bdone\n    Verifying transaction: / \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\bdone\n    Executing transaction: - \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\bdone\n    #\n    # To activate this environment, use\n    #\n    #     $ conda activate xenonpy\n    #\n    # To deactivate an active environment, use\n    #\n    #     $ conda deactivate\n    \n    Collecting package metadata (repodata.json): - \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\bdone\n    Solving environment: \\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \n    Warning: 4 possible package resolutions (only showing differing packages):\n      - defaults/linux-64::apscheduler-3.6.3-py36_1, defaults/linux-64::jedi-0.17.0-py36_0, defaults/linux-64::tzlocal-2.1-py36_0, defaults/noarch::parso-0.8.1-pyhd3eb1b0_0\n      - defaults/linux-64::apscheduler-3.6.3-py36_1, defaults/linux-64::jedi-0.17.2-py36h06a4308_1, defaults/linux-64::tzlocal-2.1-py36_0, defaults/noarch::parso-0.7.0-py_0\n      - defaults/linux-64::apscheduler-3.7.0-py36h06a4308_0, defaults/linux-64::jedi-0.17.2-py36h06a4308_1, defaults/linux-64::tzlocal-2.0.0-py36h06a4308_0, defaults/noarch::parso-0.7.0-py_0\n      - defaults/linux-64::apscheduler-3.7.0-py36h06a4308_0, defaults/linux-64::jedi-0.17.0-py36_0, defaults/linux-64::tzlocal-2.0.0-py36h06a4308_0, defaults/noarch::parso-0.8.1-pyhd3eb1b0_0\b\b- \b\b\\ \b\bdone\n    \n    Downloading and Extracting Packages\n    pyopenssl-20.0.1     | 49 KB     | : 100% 1.0/1 [00:00<00:00,  8.38it/s]\n    jupyter_console-6.2. | 26 KB     | : 100% 1.0/1 [00:00<00:00, 11.63it/s]\n    libnetcdf-4.6.1      | 833 KB    | : 100% 1.0/1 [00:00<00:00,  6.51it/s]\n    webencodings-0.5.1   | 19 KB     | : 100% 1.0/1 [00:00<00:00, 10.60it/s]\n    decorator-4.4.2      | 12 KB     | : 100% 1.0/1 [00:00<00:00, 43.02it/s]\n    jupyter-1.0.0        | 6 KB      | : 100% 1.0/1 [00:00<00:00, 10.46it/s]\n    packaging-20.9       | 37 KB     | : 100% 1.0/1 [00:00<00:00, 12.16it/s]\n    werkzeug-1.0.1       | 239 KB    | : 100% 1.0/1 [00:00<00:00, 16.88it/s]\n    retrying-1.3.3       | 16 KB     | : 100% 1.0/1 [00:00<00:00, 10.57it/s]\n    nbclient-0.5.3       | 62 KB     | : 100% 1.0/1 [00:00<00:00, 10.00it/s]\n    vtk-8.2.0            | 28.4 MB   | : 100% 1.0/1 [00:01<00:00,  1.26s/it]               \n    bleach-3.3.0         | 113 KB    | : 100% 1.0/1 [00:00<00:00, 10.46it/s]\n    krb5-1.18.2          | 1.3 MB    | : 100% 1.0/1 [00:00<00:00,  6.89it/s]\n    pickleshare-0.7.5    | 13 KB     | : 100% 1.0/1 [00:00<00:00, 11.26it/s]\n    nest-asyncio-1.5.1   | 10 KB     | : 100% 1.0/1 [00:00<00:00, 10.90it/s]\n    ipykernel-5.3.4      | 181 KB    | : 100% 1.0/1 [00:00<00:00, 11.29it/s]\n    cftime-1.4.1         | 261 KB    | : 100% 1.0/1 [00:00<00:00, 10.83it/s]\n    cycler-0.10.0        | 13 KB     | : 100% 1.0/1 [00:00<00:00, 11.90it/s]\n    ase-3.21.1           | 1.5 MB    | : 100% 1.0/1 [00:00<00:00,  2.18it/s]               \n    jedi-0.17.0          | 780 KB    | : 100% 1.0/1 [00:00<00:00,  4.21it/s]\n    libsodium-1.0.18     | 244 KB    | : 100% 1.0/1 [00:00<00:00,  9.33it/s]\n    joblib-1.0.1         | 208 KB    | : 100% 1.0/1 [00:00<00:00, 11.03it/s]\n    zstd-1.3.7           | 401 KB    | : 100% 1.0/1 [00:00<00:00, 10.29it/s]\n    matplotlib-3.3.4     | 26 KB     | : 100% 1.0/1 [00:00<00:00, 12.17it/s]\n    tzlocal-2.1          | 29 KB     | : 100% 1.0/1 [00:00<00:00, 11.71it/s]\n    monty-4.0.2          | 36 KB     | : 100% 1.0/1 [00:00<00:00, 20.27it/s]\n    flask-1.1.2          | 70 KB     | : 100% 1.0/1 [00:00<00:00, 33.47it/s]\n    markupsafe-1.1.1     | 29 KB     | : 100% 1.0/1 [00:00<00:00, 12.14it/s]\n    libtheora-1.1.1      | 330 KB    | : 100% 1.0/1 [00:00<00:00, 10.45it/s]\n    python_abi-3.6       | 4 KB      | : 100% 1.0/1 [00:00<00:00, 27.01it/s]\n    curl-7.71.1          | 140 KB    | : 100% 1.0/1 [00:00<00:00, 11.08it/s]\n    argon2-cffi-20.1.0   | 46 KB     | : 100% 1.0/1 [00:00<00:00, 11.43it/s]\n    jupyterlab_pygments- | 8 KB      | : 100% 1.0/1 [00:00<00:00, 12.03it/s]\n    apscheduler-3.6.3    | 85 KB     | : 100% 1.0/1 [00:00<00:00, 11.10it/s]\n    libssh2-1.9.0        | 269 KB    | : 100% 1.0/1 [00:00<00:00, 11.11it/s]\n    importlib-metadata-2 | 35 KB     | : 100% 1.0/1 [00:00<00:00, 12.81it/s]\n    gstreamer-1.14.0     | 3.2 MB    | : 100% 1.0/1 [00:00<00:00,  5.73it/s]\n    spglib-1.16.0        | 632 KB    | : 100% 1.0/1 [00:00<00:00,  3.24it/s]\n    libgfortran-ng-7.3.0 | 1006 KB   | : 100% 1.0/1 [00:00<00:00,  7.00it/s]\n    pandas-0.25.3        | 8.8 MB    | : 100% 1.0/1 [00:00<00:00,  1.66it/s]\n    mpmath-1.1.0         | 776 KB    | : 100% 1.0/1 [00:00<00:00,  7.92it/s]\n    notebook-6.2.0       | 4.1 MB    | : 100% 1.0/1 [00:00<00:00,  2.90it/s]\n    tornado-6.1          | 581 KB    | : 100% 1.0/1 [00:00<00:00,  8.37it/s]\n    pandocfilters-1.4.3  | 14 KB     | : 100% 1.0/1 [00:00<00:00, 12.37it/s]\n    prometheus_client-0. | 45 KB     | : 100% 1.0/1 [00:00<00:00, 12.47it/s]\n    netcdf4-1.4.2        | 480 KB    | : 100% 1.0/1 [00:00<00:00,  8.98it/s]\n    dbus-1.13.18         | 504 KB    | : 100% 1.0/1 [00:00<00:00,  9.75it/s]\n    requests-2.25.1      | 52 KB     | : 100% 1.0/1 [00:00<00:00, 13.22it/s]\n    gmp-6.2.1            | 539 KB    | : 100% 1.0/1 [00:00<00:00,  7.69it/s]\n    pygments-2.8.1       | 703 KB    | : 100% 1.0/1 [00:00<00:00,  8.94it/s]\n    jsoncpp-1.8.4        | 132 KB    | : 100% 1.0/1 [00:00<00:00, 11.08it/s]\n    ipywidgets-7.6.3     | 105 KB    | : 100% 1.0/1 [00:00<00:00, 11.61it/s]\n    qtconsole-5.0.2      | 97 KB     | : 100% 1.0/1 [00:00<00:00, 12.52it/s]\n    importlib_metadata-2 | 11 KB     | : 100% 1.0/1 [00:00<00:00, 11.72it/s]\n    prompt-toolkit-3.0.8 | 248 KB    | : 100% 1.0/1 [00:00<00:00, 11.56it/s]\n    testpath-0.4.4       | 85 KB     | : 100% 1.0/1 [00:00<00:00, 28.20it/s]\n    pyrsistent-0.17.3    | 89 KB     | : 100% 1.0/1 [00:00<00:00, 11.05it/s]\n    jsonschema-3.2.0     | 47 KB     | : 100% 1.0/1 [00:00<00:00, 11.49it/s]\n    ruamel.yaml.clib-0.2 | 145 KB    | : 100% 1.0/1 [00:00<00:00, 11.25it/s]\n    chardet-4.0.0        | 199 KB    | : 100% 1.0/1 [00:00<00:00, 10.55it/s]\n    pexpect-4.8.0        | 53 KB     | : 100% 1.0/1 [00:00<00:00, 10.96it/s]\n    qt-5.9.7             | 68.5 MB   | : 100% 1.0/1 [00:02<00:00,  2.60s/it]\n    gst-plugins-base-1.1 | 4.9 MB    | : 100% 1.0/1 [00:00<00:00,  3.45it/s]\n    pybtex-0.24.0        | 303 KB    | : 100% 1.0/1 [00:00<00:00,  8.55it/s]\n    mpfr-4.0.2           | 487 KB    | : 100% 1.0/1 [00:00<00:00,  9.51it/s]\n    pydispatcher-2.0.5   | 20 KB     | : 100% 1.0/1 [00:00<00:00, 11.01it/s]\n    mpc-1.1.0            | 90 KB     | : 100% 1.0/1 [00:00<00:00, 10.37it/s]\n    ipython-7.16.1       | 999 KB    | : 100% 1.0/1 [00:00<00:00,  6.51it/s]\n    magma-cuda101-2.5.1  | 52.4 MB   | : 100% 1.0/1 [00:07<00:00,  7.34s/it]               \n    ruamel.yaml-0.16.12  | 172 KB    | : 100% 1.0/1 [00:00<00:00,  9.72it/s]\n    lz4-c-1.8.1.2        | 130 KB    | : 100% 1.0/1 [00:00<00:00, 12.64it/s]\n    hdf5-1.10.4          | 3.9 MB    | : 100% 1.0/1 [00:00<00:00,  3.93it/s]\n    pyzmq-20.0.0         | 438 KB    | : 100% 1.0/1 [00:00<00:00,  8.40it/s]\n    sip-4.19.8           | 274 KB    | : 100% 1.0/1 [00:00<00:00, 11.17it/s]\n    jupyter_client-6.1.7 | 77 KB     | : 100% 1.0/1 [00:00<00:00, 10.00it/s]\n    torchvision-0.2.1    | 75 KB     | : 100% 1.0/1 [00:00<00:00, 11.34it/s]\n    networkx-2.5         | 1.1 MB    | : 100% 1.0/1 [00:00<00:00,  5.78it/s]\n    prompt_toolkit-3.0.8 | 12 KB     | : 100% 1.0/1 [00:00<00:00, 11.40it/s]\n    ipython_genutils-0.2 | 27 KB     | : 100% 1.0/1 [00:00<00:00, 12.89it/s]\n    tabulate-0.8.9       | 39 KB     | : 100% 1.0/1 [00:00<00:00,  8.45it/s]\n    jupyter_core-4.7.1   | 68 KB     | : 100% 1.0/1 [00:00<00:00, 12.40it/s]\n    latexcodec-2.0.1     | 18 KB     | : 100% 1.0/1 [00:00<00:00, 35.51it/s]\n    attrs-20.3.0         | 43 KB     | : 100% 1.0/1 [00:00<00:00, 11.97it/s]\n    libogg-1.3.2         | 194 KB    | : 100% 1.0/1 [00:00<00:00, 10.55it/s]\n    mistune-0.8.4        | 55 KB     | : 100% 1.0/1 [00:00<00:00, 11.36it/s]\n    widgetsnbextension-3 | 862 KB    | : 100% 1.0/1 [00:00<00:00,  9.25it/s]\n    scikit-learn-0.21.3  | 5.0 MB    | : 100% 1.0/1 [00:00<00:00,  3.46it/s]\n    send2trash-1.5.0     | 14 KB     | : 100% 1.0/1 [00:00<00:00, 11.23it/s]\n    nbconvert-6.0.7      | 480 KB    | : 100% 1.0/1 [00:00<00:00,  7.93it/s]\n    idna-2.10            | 52 KB     | : 100% 1.0/1 [00:00<00:00, 30.19it/s]\n    ptyprocess-0.7.0     | 17 KB     | : 100% 1.0/1 [00:00<00:00, 11.12it/s]\n    jinja2-2.11.3        | 101 KB    | : 100% 1.0/1 [00:00<00:00, 12.76it/s]\n    sympy-1.7.1          | 8.9 MB    | : 100% 1.0/1 [00:00<00:00,  1.48it/s]\n    plotly-4.14.3        | 3.6 MB    | : 100% 1.0/1 [00:01<00:00,  1.03s/it]\n    nbformat-5.1.2       | 68 KB     | : 100% 1.0/1 [00:00<00:00, 11.52it/s]\n    async_generator-1.10 | 39 KB     | : 100% 1.0/1 [00:00<00:00, 13.05it/s]\n    qtpy-1.9.0           | 38 KB     | : 100% 1.0/1 [00:00<00:00, 10.75it/s]\n    parso-0.8.1          | 69 KB     | : 100% 1.0/1 [00:00<00:00, 10.77it/s]\n    tbb-2020.3           | 1.1 MB    | : 100% 1.0/1 [00:00<00:00,  8.53it/s]\n    pyparsing-2.4.7      | 59 KB     | : 100% 1.0/1 [00:00<00:00, 23.51it/s]\n    rdkit-2019.09.1.0    | 23.9 MB   | : 100% 1.0/1 [00:04<00:00,  4.14s/it]\n    libvorbis-1.3.7      | 398 KB    | : 100% 1.0/1 [00:00<00:00,  9.20it/s]\n    traitlets-4.3.3      | 140 KB    | : 100% 1.0/1 [00:00<00:00, 11.41it/s]\n    pytorch-1.3.0        | 464.0 MB  | : 100% 1.0/1 [01:01<00:00, 61.93s/it]               \n    scipy-1.3.1          | 14.0 MB   | : 100% 1.0/1 [00:00<00:00,  1.39it/s]\n    backcall-0.2.0       | 13 KB     | : 100% 1.0/1 [00:00<00:00, 39.94it/s]\n    libtiff-4.1.0        | 447 KB    | : 100% 1.0/1 [00:00<00:00,  9.25it/s]\n    libcurl-7.71.1       | 305 KB    | : 100% 1.0/1 [00:00<00:00,  8.06it/s]\n    defusedxml-0.7.1     | 23 KB     | : 100% 1.0/1 [00:00<00:00, 11.22it/s]\n    tqdm-4.56.0          | 80 KB     | : 100% 1.0/1 [00:00<00:00, 10.08it/s]\n    click-7.1.2          | 64 KB     | : 100% 1.0/1 [00:00<00:00, 32.94it/s]\n    matplotlib-base-3.3. | 5.1 MB    | : 100% 1.0/1 [00:00<00:00,  3.77it/s]\n    entrypoints-0.3      | 12 KB     | : 100% 1.0/1 [00:00<00:00, 12.93it/s]\n    zeromq-4.3.3         | 500 KB    | : 100% 1.0/1 [00:00<00:00, 10.62it/s]\n    palettable-3.3.0     | 78 KB     | : 100% 1.0/1 [00:00<00:00, 10.91it/s]\n    itsdangerous-1.1.0   | 28 KB     | : 100% 1.0/1 [00:00<00:00, 12.51it/s]\n    kiwisolver-1.3.1     | 80 KB     | : 100% 1.0/1 [00:00<00:00, 12.05it/s]\n    wcwidth-0.2.5        | 29 KB     | : 100% 1.0/1 [00:00<00:00, 11.15it/s]\n    urllib3-1.26.3       | 105 KB    | : 100% 1.0/1 [00:00<00:00, 10.45it/s]\n    pymatgen-2019.11.11  | 3.1 MB    | : 100% 1.0/1 [00:00<00:00,  1.40it/s]\n    future-0.18.2        | 639 KB    | : 100% 1.0/1 [00:00<00:00,  7.26it/s]\n    pandoc-2.11          | 9.6 MB    | : 100% 1.0/1 [00:00<00:00,  1.81it/s]\n    terminado-0.9.2      | 25 KB     | : 100% 1.0/1 [00:00<00:00, 10.82it/s]\n    zipp-3.4.0           | 15 KB     | : 100% 1.0/1 [00:00<00:00, 11.67it/s]\n    expat-2.2.10         | 153 KB    | : 100% 1.0/1 [00:00<00:00,  9.01it/s]\n    hdf4-4.2.13          | 714 KB    | : 100% 1.0/1 [00:00<00:00,  8.77it/s]\n    pyqt-5.9.2           | 4.5 MB    | : 100% 1.0/1 [00:00<00:00,  3.92it/s]\n    pyyaml-5.4.1         | 170 KB    | : 100% 1.0/1 [00:00<00:00, 10.32it/s]\n    jupyterlab_widgets-1 | 109 KB    | : 100% 1.0/1 [00:00<00:00, 11.50it/s]\n    seaborn-0.11.1       | 212 KB    | : 100% 1.0/1 [00:00<00:00,  9.91it/s]\n    gmpy2-2.0.8          | 150 KB    | : 100% 1.0/1 [00:00<00:00, 12.22it/s]\n    Preparing transaction: / \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\bdone\n    Verifying transaction: - \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\bdone\n    Executing transaction: \\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\bdone\n    Installing pip dependencies: | \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- Ran pip subprocess with arguments:\n    ['/usr/local/envs/xenonpy/bin/python', '-m', 'pip', 'install', '-U', '-r', '/content/condaenv.isthpn6f.requirements.txt']\n    Pip subprocess output:\n    Requirement already satisfied: ruamel.yaml in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from -r /content/condaenv.isthpn6f.requirements.txt (line 1)) (0.16.12)\n    Collecting ruamel.yaml\n      Using cached ruamel.yaml-0.16.13-py2.py3-none-any.whl (111 kB)\n    Collecting Python-Deprecated\n      Downloading Python-Deprecated-1.1.0.tar.gz (2.9 kB)\n    Collecting matminer\n      Downloading matminer-0.6.5.tar.gz (5.8 MB)\n    Collecting torchtext\n      Downloading torchtext-0.9.0-cp36-cp36m-manylinux1_x86_64.whl (7.1 MB)\n    Collecting jupyterlab\n      Downloading jupyterlab-3.0.10-py3-none-any.whl (8.3 MB)\n    Requirement already satisfied: pybtex in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from -r /content/condaenv.isthpn6f.requirements.txt (line 6)) (0.24.0)\n    Collecting mordred\n      Downloading mordred-1.2.0.tar.gz (128 kB)\n    Requirement already satisfied: tqdm in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from -r /content/condaenv.isthpn6f.requirements.txt (line 8)) (4.56.0)\n    Collecting tqdm\n      Downloading tqdm-4.59.0-py2.py3-none-any.whl (74 kB)\n    Collecting xenonpy\n      Downloading xenonpy-0.5.1-py3-none-any.whl (132 kB)\n    Collecting jupyter-packaging~=0.7.3\n      Downloading jupyter_packaging-0.7.12-py2.py3-none-any.whl (10 kB)\n    Requirement already satisfied: tornado>=6.1.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (6.1)\n    Requirement already satisfied: packaging in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (20.9)\n    Collecting jupyterlab-server~=2.3\n      Downloading jupyterlab_server-2.3.0-py3-none-any.whl (45 kB)\n    Collecting jupyter-server~=1.4\n      Downloading jupyter_server-1.4.1-py3-none-any.whl (241 kB)\n    Requirement already satisfied: jupyter-core in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (4.7.1)\n    Requirement already satisfied: ipython in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (7.16.1)\n    Collecting nbclassic~=0.2\n      Downloading nbclassic-0.2.6-py3-none-any.whl (18 kB)\n    Requirement already satisfied: jinja2>=2.10 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (2.11.3)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jinja2>=2.10->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (1.1.1)\n    Requirement already satisfied: nbconvert in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (6.0.7)\n    Requirement already satisfied: ipython-genutils in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (0.2.0)\n    Requirement already satisfied: pyzmq>=17 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (20.0.0)\n    Requirement already satisfied: nbformat in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (5.1.2)\n    Requirement already satisfied: Send2Trash in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (1.5.0)\n    Requirement already satisfied: jupyter-client>=6.1.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (6.1.7)\n    Requirement already satisfied: prometheus-client in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (0.9.0)\n    Collecting anyio>=2.0.2\n      Downloading anyio-2.2.0-py3-none-any.whl (65 kB)\n    Requirement already satisfied: terminado>=0.8.3 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (0.9.2)\n    Requirement already satisfied: traitlets>=4.2.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (4.3.3)\n    Requirement already satisfied: dataclasses in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from anyio>=2.0.2->jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (0.8)\n    Requirement already satisfied: async-generator in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from anyio>=2.0.2->jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (1.10)\n    Collecting typing-extensions\n      Downloading typing_extensions-3.7.4.3-py3-none-any.whl (22 kB)\n    Requirement already satisfied: idna>=2.8 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from anyio>=2.0.2->jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (2.10)\n    Collecting sniffio>=1.1\n      Downloading sniffio-1.2.0-py3-none-any.whl (10 kB)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyter-client>=6.1.1->jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (2.8.1)\n    Requirement already satisfied: jsonschema>=3.0.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyterlab-server~=2.3->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (3.2.0)\n    Requirement already satisfied: requests in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyterlab-server~=2.3->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (2.25.1)\n    Collecting json5\n      Downloading json5-0.9.5-py2.py3-none-any.whl (17 kB)\n    Collecting babel\n      Downloading Babel-2.9.0-py2.py3-none-any.whl (8.8 MB)\n    Requirement already satisfied: pyrsistent>=0.14.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jsonschema>=3.0.1->jupyterlab-server~=2.3->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (0.17.3)\n    Requirement already satisfied: setuptools in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jsonschema>=3.0.1->jupyterlab-server~=2.3->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (52.0.0.post20210125)\n    Requirement already satisfied: importlib-metadata in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jsonschema>=3.0.1->jupyterlab-server~=2.3->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (2.0.0)\n    Requirement already satisfied: attrs>=17.4.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jsonschema>=3.0.1->jupyterlab-server~=2.3->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (20.3.0)\n    Requirement already satisfied: six>=1.11.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jsonschema>=3.0.1->jupyterlab-server~=2.3->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (1.15.0)\n    Requirement already satisfied: notebook<7 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from nbclassic~=0.2->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (6.2.0)\n    Requirement already satisfied: argon2-cffi in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from notebook<7->nbclassic~=0.2->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (20.1.0)\n    Requirement already satisfied: ipykernel in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from notebook<7->nbclassic~=0.2->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (5.3.4)\n    Collecting contextvars>=2.1\n      Downloading contextvars-2.4.tar.gz (9.6 kB)\n    Collecting immutables>=0.9\n      Downloading immutables-0.15-cp36-cp36m-manylinux1_x86_64.whl (100 kB)\n    Requirement already satisfied: ptyprocess in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from terminado>=0.8.3->jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (0.7.0)\n    Requirement already satisfied: decorator in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from traitlets>=4.2.1->jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (4.4.2)\n    Requirement already satisfied: numpy>=1.19.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.isthpn6f.requirements.txt (line 3)) (1.19.2)\n    Collecting pymatgen>=2020.4.29\n      Downloading pymatgen-2021.3.3.tar.gz (3.0 MB)\n      Installing build dependencies: started\n      Installing build dependencies: finished with status 'error'\n      Downloading pymatgen-2021.2.16.tar.gz (3.0 MB)\n      Installing build dependencies: started\n      Installing build dependencies: finished with status 'error'\n      Downloading pymatgen-2021.2.14.tar.gz (3.0 MB)\n      Installing build dependencies: started\n      Installing build dependencies: finished with status 'error'\n      Downloading pymatgen-2021.2.13.tar.gz (3.0 MB)\n      Installing build dependencies: started\n      Installing build dependencies: finished with status 'error'\n      Downloading pymatgen-2021.2.8.1.tar.gz (3.0 MB)\n      Installing build dependencies: started\n      Installing build dependencies: finished with status 'done'\n      Getting requirements to build wheel: started\n      Getting requirements to build wheel: finished with status 'done'\n      Installing backend dependencies: started\n      Installing backend dependencies: finished with status 'done'\n        Preparing wheel metadata: started\n        Preparing wheel metadata: finished with status 'done'\n    Collecting pandas>=1.0.4\n      Downloading pandas-1.1.5-cp36-cp36m-manylinux1_x86_64.whl (9.5 MB)\n    Collecting pymongo>=3.10.1\n      Downloading pymongo-3.11.3-cp36-cp36m-manylinux2014_x86_64.whl (509 kB)\n    Collecting pint>=0.11\n      Downloading Pint-0.16.1-py2.py3-none-any.whl (205 kB)\n    Requirement already satisfied: plotly>=4.8.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.isthpn6f.requirements.txt (line 3)) (4.14.3)\n    Requirement already satisfied: future>=0.18.2 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.isthpn6f.requirements.txt (line 3)) (0.18.2)\n    Requirement already satisfied: sympy>=1.6 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.isthpn6f.requirements.txt (line 3)) (1.7.1)\n    Collecting scikit_learn>=0.23.1\n      Downloading scikit_learn-0.24.1-cp36-cp36m-manylinux2010_x86_64.whl (22.2 MB)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.isthpn6f.requirements.txt (line 3)) (4.0.2)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pandas>=1.0.4->matminer->-r /content/condaenv.isthpn6f.requirements.txt (line 3)) (2021.1)\n    Collecting importlib-resources\n      Downloading importlib_resources-5.1.2-py3-none-any.whl (25 kB)\n    Requirement already satisfied: retrying>=1.3.3 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from plotly>=4.8.1->matminer->-r /content/condaenv.isthpn6f.requirements.txt (line 3)) (1.3.3)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pymatgen>=2020.4.29->matminer->-r /content/condaenv.isthpn6f.requirements.txt (line 3)) (3.3.0)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pymatgen>=2020.4.29->matminer->-r /content/condaenv.isthpn6f.requirements.txt (line 3)) (3.3.4)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pymatgen>=2020.4.29->matminer->-r /content/condaenv.isthpn6f.requirements.txt (line 3)) (2.5)\n    Requirement already satisfied: tabulate in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pymatgen>=2020.4.29->matminer->-r /content/condaenv.isthpn6f.requirements.txt (line 3)) (0.8.9)\n    Collecting scipy>=1.5.0\n      Downloading scipy-1.5.4-cp36-cp36m-manylinux1_x86_64.whl (25.9 MB)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pymatgen>=2020.4.29->matminer->-r /content/condaenv.isthpn6f.requirements.txt (line 3)) (1.16.0)\n    Collecting uncertainties>=3.1.4\n      Using cached uncertainties-3.1.5-py2.py3-none-any.whl (246 kB)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from ruamel.yaml->-r /content/condaenv.isthpn6f.requirements.txt (line 1)) (0.2.2)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2020.4.29->matminer->-r /content/condaenv.isthpn6f.requirements.txt (line 3)) (0.10.0)\n    Requirement already satisfied: pillow>=6.2.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2020.4.29->matminer->-r /content/condaenv.isthpn6f.requirements.txt (line 3)) (8.1.2)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2020.4.29->matminer->-r /content/condaenv.isthpn6f.requirements.txt (line 3)) (1.3.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2020.4.29->matminer->-r /content/condaenv.isthpn6f.requirements.txt (line 3)) (2.4.7)\n    Requirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from requests->jupyterlab-server~=2.3->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (1.26.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from requests->jupyterlab-server~=2.3->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (2020.12.5)\n    Requirement already satisfied: chardet<5,>=3.0.2 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from requests->jupyterlab-server~=2.3->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (4.0.0)\n    Collecting threadpoolctl>=2.0.0\n      Downloading threadpoolctl-2.1.0-py3-none-any.whl (12 kB)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from scikit_learn>=0.23.1->matminer->-r /content/condaenv.isthpn6f.requirements.txt (line 3)) (1.0.1)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from sympy>=1.6->matminer->-r /content/condaenv.isthpn6f.requirements.txt (line 3)) (1.1.0)\n    Requirement already satisfied: latexcodec>=1.0.4 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pybtex->-r /content/condaenv.isthpn6f.requirements.txt (line 6)) (2.0.1)\n    Requirement already satisfied: PyYAML>=3.01 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pybtex->-r /content/condaenv.isthpn6f.requirements.txt (line 6)) (5.4.1)\n    Collecting torch==1.8.0\n      Downloading torch-1.8.0-cp36-cp36m-manylinux1_x86_64.whl (735.5 MB)\n    Requirement already satisfied: seaborn in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from xenonpy->-r /content/condaenv.isthpn6f.requirements.txt (line 9)) (0.11.1)\n    Requirement already satisfied: cffi>=1.0.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from argon2-cffi->notebook<7->nbclassic~=0.2->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (1.14.5)\n    Requirement already satisfied: pycparser in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from cffi>=1.0.0->argon2-cffi->notebook<7->nbclassic~=0.2->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (2.20)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from importlib-metadata->jsonschema>=3.0.1->jupyterlab-server~=2.3->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (3.4.0)\n    Requirement already satisfied: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from ipython->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (3.0.8)\n    Requirement already satisfied: pexpect in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from ipython->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (4.8.0)\n    Requirement already satisfied: jedi>=0.10 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from ipython->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (0.17.0)\n    Requirement already satisfied: pickleshare in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from ipython->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (0.7.5)\n    Requirement already satisfied: pygments in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from ipython->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (2.8.1)\n    Requirement already satisfied: backcall in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from ipython->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (0.2.0)\n    Requirement already satisfied: parso>=0.7.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jedi>=0.10->ipython->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (0.8.1)\n    Requirement already satisfied: wcwidth in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->ipython->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (0.2.5)\n    Requirement already satisfied: nbclient<0.6.0,>=0.5.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from nbconvert->jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (0.5.3)\n    Requirement already satisfied: testpath in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from nbconvert->jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (0.4.4)\n    Requirement already satisfied: pandocfilters>=1.4.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from nbconvert->jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (1.4.3)\n    Requirement already satisfied: mistune<2,>=0.8.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from nbconvert->jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (0.8.4)\n    Requirement already satisfied: bleach in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from nbconvert->jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (3.3.0)\n    Requirement already satisfied: entrypoints>=0.2.2 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from nbconvert->jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (0.3)\n    Requirement already satisfied: jupyterlab-pygments in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from nbconvert->jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (0.1.2)\n    Requirement already satisfied: defusedxml in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from nbconvert->jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (0.7.1)\n    Requirement already satisfied: nest-asyncio in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from nbclient<0.6.0,>=0.5.0->nbconvert->jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (1.5.1)\n    Requirement already satisfied: webencodings in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from bleach->nbconvert->jupyter-server~=1.4->jupyterlab->-r /content/condaenv.isthpn6f.requirements.txt (line 5)) (0.5.1)\n    Building wheels for collected packages: contextvars, matminer, pymatgen, mordred, Python-Deprecated\n      Building wheel for contextvars (setup.py): started\n      Building wheel for contextvars (setup.py): finished with status 'done'\n      Created wheel for contextvars: filename=contextvars-2.4-py3-none-any.whl size=7665 sha256=d4fdd0c2426f2b58239329ce2c19c230bd19050403c872a277ab35addeeeb233\n      Stored in directory: /root/.cache/pip/wheels/41/11/53/911724983aa48deb94792432e14e518447212dd6c5477d49d3\n      Building wheel for matminer (setup.py): started\n      Building wheel for matminer (setup.py): finished with status 'done'\n      Created wheel for matminer: filename=matminer-0.6.5-py3-none-any.whl size=1189788 sha256=7234b8d54a4126dfdc8973e99903a7449bc40259d9b639174515973ccb380de3\n      Stored in directory: /root/.cache/pip/wheels/0f/0c/76/aa6cc0ccae42e60561f8e5e28cb7ebb64842e5f8cd024b74b1\n      Building wheel for pymatgen (PEP 517): started\n      Building wheel for pymatgen (PEP 517): finished with status 'done'\n      Created wheel for pymatgen: filename=pymatgen-2021.2.8.1-cp36-cp36m-linux_x86_64.whl size=3828424 sha256=62f523b016b2b114c14b8c64f63a7b17bd280d1408d39c653f4a5292c4c739c6\n      Stored in directory: /root/.cache/pip/wheels/07/d0/77/2fbd042fa48b17647602ac2069f68d3a1312240e290c4ee436\n      Building wheel for mordred (setup.py): started\n      Building wheel for mordred (setup.py): finished with status 'done'\n      Created wheel for mordred: filename=mordred-1.2.0-py3-none-any.whl size=176721 sha256=93cea277a3e9869b3f63d25ee938b1d2592253179101a2f57621d6cd9c73984c\n      Stored in directory: /root/.cache/pip/wheels/94/e8/c6/0561efc609b8b695a4c0a98e76e439a97f33eadfd0dba949ee\n      Building wheel for Python-Deprecated (setup.py): started\n      Building wheel for Python-Deprecated (setup.py): finished with status 'done'\n      Created wheel for Python-Deprecated: filename=Python_Deprecated-1.1.0-py2.py3-none-any.whl size=3069 sha256=d2e0470ed23710ad997561bc60a26ed1e1aabe55df6c807e5e5bddf7c892b42d\n      Stored in directory: /root/.cache/pip/wheels/7b/77/f4/889fb222210030f42875d19bb55b64ea2b394428066fd3a6f4\n    Successfully built contextvars matminer pymatgen mordred Python-Deprecated\n    Installing collected packages: immutables, contextvars, typing-extensions, sniffio, anyio, uncertainties, threadpoolctl, scipy, ruamel.yaml, pandas, jupyter-server, json5, importlib-resources, babel, tqdm, torch, scikit-learn, Python-Deprecated, pymongo, pymatgen, pint, nbclassic, mordred, jupyterlab-server, jupyter-packaging, xenonpy, torchtext, matminer, jupyterlab\n      Attempting uninstall: scipy\n        Found existing installation: scipy 1.3.1\n        Uninstalling scipy-1.3.1:\n          Successfully uninstalled scipy-1.3.1\n      Attempting uninstall: ruamel.yaml\n        Found existing installation: ruamel.yaml 0.16.12\n        Uninstalling ruamel.yaml-0.16.12:\n          Successfully uninstalled ruamel.yaml-0.16.12\n      Attempting uninstall: pandas\n        Found existing installation: pandas 0.25.3\n        Uninstalling pandas-0.25.3:\n          Successfully uninstalled pandas-0.25.3\n      Attempting uninstall: tqdm\n        Found existing installation: tqdm 4.56.0\n        Uninstalling tqdm-4.56.0:\n          Successfully uninstalled tqdm-4.56.0\n      Attempting uninstall: torch\n        Found existing installation: torch 1.3.0\n        Uninstalling torch-1.3.0:\n          Successfully uninstalled torch-1.3.0\n      Attempting uninstall: scikit-learn\n        Found existing installation: scikit-learn 0.21.3\n        Uninstalling scikit-learn-0.21.3:\n          Successfully uninstalled scikit-learn-0.21.3\n      Attempting uninstall: pymatgen\n        Found existing installation: pymatgen 2019.11.11\n        Uninstalling pymatgen-2019.11.11:\n          Successfully uninstalled pymatgen-2019.11.11\n    Successfully installed Python-Deprecated-1.1.0 anyio-2.2.0 babel-2.9.0 contextvars-2.4 immutables-0.15 importlib-resources-5.1.2 json5-0.9.5 jupyter-packaging-0.7.12 jupyter-server-1.4.1 jupyterlab-3.0.10 jupyterlab-server-2.3.0 matminer-0.6.5 mordred-1.2.0 nbclassic-0.2.6 pandas-1.1.5 pint-0.16.1 pymatgen-2021.2.8.1 pymongo-3.11.3 ruamel.yaml-0.16.13 scikit-learn-0.24.1 scipy-1.5.4 sniffio-1.2.0 threadpoolctl-2.1.0 torch-1.8.0 torchtext-0.9.0 tqdm-4.59.0 typing-extensions-3.7.4.3 uncertainties-3.1.5 xenonpy-0.5.1\n    \n    \b\b\\ \b\bdone\n    #\n    # To activate this environment, use\n    #\n    #     $ conda activate xenonpy\n    #\n    # To deactivate an active environment, use\n    #\n    #     $ conda deactivate\n    \n\n\n\n```\n!pip3 install -U xenonpy==0.4.4\r\nimport xenonpy\r\nprint(xenonpy.__version__)\n```\n\n    Collecting xenonpy==0.4.4\n      Downloading xenonpy-0.4.4-py3-none-any.whl (120 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 120 kB 14.3 MB/s \n    \u001b[?25hCollecting mordred\n      Using cached mordred-1.2.0-py3-none-any.whl\n    Collecting scipy>=1.2.*\n      Using cached scipy-1.5.4-cp36-cp36m-manylinux1_x86_64.whl (25.9 MB)\n    Requirement already satisfied: numpy>=1.16.* in /usr/local/lib/python3.6/site-packages (from xenonpy==0.4.4) (1.19.2)\n    Requirement already satisfied: torch==1.* in /usr/local/lib/python3.6/site-packages (from xenonpy==0.4.4) (1.7.0)\n    Collecting joblib>=0.13.*\n      Downloading joblib-1.0.1-py3-none-any.whl (303 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 303 kB 36.1 MB/s \n    \u001b[?25hCollecting Python-Deprecated\n      Using cached Python_Deprecated-1.1.0-py2.py3-none-any.whl\n    Requirement already satisfied: ruamel.yaml in /usr/local/lib/python3.6/site-packages (from xenonpy==0.4.4) (0.15.87)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.6/site-packages (from xenonpy==0.4.4) (4.51.0)\n    Collecting seaborn\n      Downloading seaborn-0.11.1-py3-none-any.whl (285 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 285 kB 62.2 MB/s \n    \u001b[?25hCollecting scikit-learn>=0.21.*\n      Using cached scikit_learn-0.24.1-cp36-cp36m-manylinux2010_x86_64.whl (22.2 MB)\n    Requirement already satisfied: pandas>=0.24.* in /usr/local/lib/python3.6/site-packages (from xenonpy==0.4.4) (1.1.5)\n    Collecting plotly\n      Using cached plotly-4.14.3-py2.py3-none-any.whl (13.2 MB)\n    Collecting pymatgen>=2019.5.*\n      Using cached pymatgen-2021.3.3.tar.gz (3.0 MB)\n      Installing build dependencies ... \u001b[?25l\u001b[?25herror\n    \u001b[33mWARNING: Discarding https://files.pythonhosted.org/packages/1b/cd/92a3a241dc849b62346e00b80ea19725917266af9f3927bf065bb6890f10/pymatgen-2021.3.3.tar.gz#sha256=db1f9269e1a130626a240fe8bf63c257fadeebb5a0079a7504e7f29c6ee43fd4 (from https://pypi.org/simple/pymatgen/) (requires-python:>=3.6). Command errored out with exit status 1: /usr/local/bin/python /usr/local/lib/python3.6/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-uy2hqcgm/overlay --no-warn-script-location -v --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'numpy>=1.20.1' 'setuptools>=43.0.0' Check the logs for full command output.\u001b[0m\n      Using cached pymatgen-2021.2.16.tar.gz (3.0 MB)\n      Installing build dependencies ... \u001b[?25l\u001b[?25herror\n    \u001b[33mWARNING: Discarding https://files.pythonhosted.org/packages/9b/50/a22eb063ca5ceb27c2be7e51e775ee4b5ade664525be143a2b1b77e4cc70/pymatgen-2021.2.16.tar.gz#sha256=0a350105a44cc64095802bcb8d542a3a0a1bde8a9d7ecba605392e5dd26be118 (from https://pypi.org/simple/pymatgen/) (requires-python:>=3.6). Command errored out with exit status 1: /usr/local/bin/python /usr/local/lib/python3.6/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-cl21s0gq/overlay --no-warn-script-location -v --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'numpy>=1.20.1' 'setuptools>=43.0.0' Check the logs for full command output.\u001b[0m\n      Using cached pymatgen-2021.2.14.tar.gz (3.0 MB)\n      Installing build dependencies ... \u001b[?25l\u001b[?25herror\n    \u001b[33mWARNING: Discarding https://files.pythonhosted.org/packages/06/4f/9dc98ea1309012eafe518e32e91d2a55686341f3f4c1cdc19f1f64cb33d0/pymatgen-2021.2.14.tar.gz#sha256=b1ac61c666f9e629480a67008a44f2dcbfc5ca1a192707f83718f6e1cd981ef6 (from https://pypi.org/simple/pymatgen/) (requires-python:>=3.6). Command errored out with exit status 1: /usr/local/bin/python /usr/local/lib/python3.6/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-n982_5sn/overlay --no-warn-script-location -v --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'numpy>=1.20.1' 'setuptools>=43.0.0' Check the logs for full command output.\u001b[0m\n      Using cached pymatgen-2021.2.13.tar.gz (3.0 MB)\n      Installing build dependencies ... \u001b[?25l\u001b[?25herror\n    \u001b[33mWARNING: Discarding https://files.pythonhosted.org/packages/36/ff/09e380c971b276989cf111c8dbb6fbbc611097b8bc5428feebfe523ba455/pymatgen-2021.2.13.tar.gz#sha256=602c32dbe54461efe5e11b04ea8e08852a6fb7a17924f137746b5e046cb0b7ee (from https://pypi.org/simple/pymatgen/) (requires-python:>=3.6). Command errored out with exit status 1: /usr/local/bin/python /usr/local/lib/python3.6/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-zij8soeh/overlay --no-warn-script-location -v --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'numpy>=1.20.1' 'setuptools>=43.0.0' Check the logs for full command output.\u001b[0m\n      Using cached pymatgen-2021.2.8.1-cp36-cp36m-linux_x86_64.whl\n    Requirement already satisfied: requests in /usr/local/lib/python3.6/site-packages (from xenonpy==0.4.4) (2.24.0)\n    Collecting future\n      Downloading future-0.18.2.tar.gz (829 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 829 kB 53.2 MB/s \n    \u001b[?25hRequirement already satisfied: typing_extensions in /usr/local/lib/python3.6/site-packages (from torch==1.*->xenonpy==0.4.4) (3.7.4.3)\n    Requirement already satisfied: dataclasses in /usr/local/lib/python3.6/site-packages (from torch==1.*->xenonpy==0.4.4) (0.8)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.6/site-packages (from pandas>=0.24.*->xenonpy==0.4.4) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/site-packages (from pandas>=0.24.*->xenonpy==0.4.4) (2021.1)\n    Collecting uncertainties>=3.1.4\n      Using cached uncertainties-3.1.5-py2.py3-none-any.whl (246 kB)\n    Collecting tabulate\n      Downloading tabulate-0.8.9-py3-none-any.whl (25 kB)\n    Collecting spglib>=1.9.9.44\n      Downloading spglib-1.16.1-cp36-cp36m-manylinux2010_x86_64.whl (295 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 295 kB 72.0 MB/s \n    \u001b[?25hCollecting networkx>=2.2\n      Downloading networkx-2.5-py3-none-any.whl (1.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.6 MB 66.1 MB/s \n    \u001b[?25hCollecting sympy\n      Downloading sympy-1.7.1-py3-none-any.whl (5.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5.9 MB 75.4 MB/s \n    \u001b[?25hCollecting monty>=3.0.2\n      Using cached monty-2021.3.3-py3-none-any.whl (63 kB)\n    Collecting matplotlib>=1.5\n      Downloading matplotlib-3.3.4-cp36-cp36m-manylinux1_x86_64.whl (11.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 11.5 MB 190 kB/s \n    \u001b[?25hCollecting palettable>=3.1.1\n      Downloading palettable-3.3.0-py2.py3-none-any.whl (111 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 111 kB 70.1 MB/s \n    \u001b[?25hCollecting pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3\n      Downloading pyparsing-2.4.7-py2.py3-none-any.whl (67 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 67 kB 8.0 MB/s \n    \u001b[?25hCollecting cycler>=0.10\n      Downloading cycler-0.10.0-py2.py3-none-any.whl (6.5 kB)\n    Collecting kiwisolver>=1.0.1\n      Downloading kiwisolver-1.3.1-cp36-cp36m-manylinux1_x86_64.whl (1.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.1 MB 69.1 MB/s \n    \u001b[?25hRequirement already satisfied: pillow>=6.2.0 in /usr/local/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2019.5.*->xenonpy==0.4.4) (8.1.2)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/site-packages (from cycler>=0.10->matplotlib>=1.5->pymatgen>=2019.5.*->xenonpy==0.4.4) (1.15.0)\n    Collecting decorator>=4.3.0\n      Downloading decorator-4.4.2-py2.py3-none-any.whl (9.2 kB)\n    Collecting retrying>=1.3.3\n      Downloading retrying-1.3.3.tar.gz (10 kB)\n    Collecting threadpoolctl>=2.0.0\n      Using cached threadpoolctl-2.1.0-py3-none-any.whl (12 kB)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/site-packages (from requests->xenonpy==0.4.4) (1.25.11)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/site-packages (from requests->xenonpy==0.4.4) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/site-packages (from requests->xenonpy==0.4.4) (2020.12.5)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/site-packages (from requests->xenonpy==0.4.4) (2.10)\n    Collecting mpmath>=0.19\n      Downloading mpmath-1.2.1-py3-none-any.whl (532 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 532 kB 65.6 MB/s \n    \u001b[?25hBuilding wheels for collected packages: retrying, future\n      Building wheel for retrying (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for retrying: filename=retrying-1.3.3-py3-none-any.whl size=11429 sha256=e144112ad07d68c2bc169f265ebe1eec1dc8a3c0a1fc5d2a96b4d5af960d32a6\n      Stored in directory: /root/.cache/pip/wheels/ac/cb/8a/b27bf6323e2f4c462dcbf77d70b7c5e7868a7fbe12871770cf\n      Building wheel for future (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for future: filename=future-0.18.2-py3-none-any.whl size=491059 sha256=31bac9bc3fa973b557ae59fdc023b2157fcbae4c2402e8c7ad0cd65296afa839\n      Stored in directory: /root/.cache/pip/wheels/6e/9c/ed/4499c9865ac1002697793e0ae05ba6be33553d098f3347fb94\n    Successfully built retrying future\n    Installing collected packages: retrying, pyparsing, mpmath, kiwisolver, future, decorator, cycler, uncertainties, threadpoolctl, tabulate, sympy, spglib, scipy, plotly, palettable, networkx, monty, matplotlib, joblib, seaborn, scikit-learn, Python-Deprecated, pymatgen, mordred, xenonpy\n    Successfully installed Python-Deprecated-1.1.0 cycler-0.10.0 decorator-4.4.2 future-0.18.2 joblib-1.0.1 kiwisolver-1.3.1 matplotlib-3.3.4 monty-2021.3.3 mordred-1.2.0 mpmath-1.2.1 networkx-2.5 palettable-3.3.0 plotly-4.14.3 pymatgen-2021.2.8.1 pyparsing-2.4.7 retrying-1.3.3 scikit-learn-0.24.1 scipy-1.5.4 seaborn-0.11.1 spglib-1.16.1 sympy-1.7.1 tabulate-0.8.9 threadpoolctl-2.1.0 uncertainties-3.1.5 xenonpy-0.4.4\n\n\n\n\n    0.4.4\n\n\n**step 5**\r\n\r\nInstall XenonPy samples\n\n\n```\n!git clone https://github.com/by-student-2017/xenonpy-gcolab.git\r\n%cd xenonpy-gcolab/0.4.4/samples\r\n!wget https://github.com/yoshida-lab/XenonPy/releases/download/v0.4.1/iQSPR_sample_data.csv\r\n!ls\n```\n\n    Cloning into 'xenonpy-gcolab'...\n    remote: Enumerating objects: 250, done.\u001b[K\n    remote: Counting objects: 100% (250/250), done.\u001b[K\n    remote: Compressing objects: 100% (135/135), done.\u001b[K\n    remote: Total 250 (delta 118), reused 232 (delta 103), pack-reused 0\u001b[K\n    Receiving objects: 100% (250/250), 5.50 MiB | 32.74 MiB/s, done.\n    Resolving deltas: 100% (118/118), done.\n    /content/xenonpy-gcolab/0.4.4/samples\n    --2021-03-10 21:36:09--  https://github.com/yoshida-lab/XenonPy/releases/download/v0.4.1/iQSPR_sample_data.csv\n    Resolving github.com (github.com)... 140.82.112.3\n    Connecting to github.com (github.com)|140.82.112.3|:443... connected.\n    HTTP request sent, awaiting response... 302 Found\n    Location: https://github-releases.githubusercontent.com/117819602/14925c00-e455-11e9-9065-7d987b463251?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20210310%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20210310T213609Z&X-Amz-Expires=300&X-Amz-Signature=13c4093e9e443a235760ef5432695e66148a850ee20214c21b2f4f649f5e7ce0&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=117819602&response-content-disposition=attachment%3B%20filename%3DiQSPR_sample_data.csv&response-content-type=application%2Foctet-stream [following]\n    --2021-03-10 21:36:09--  https://github-releases.githubusercontent.com/117819602/14925c00-e455-11e9-9065-7d987b463251?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20210310%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20210310T213609Z&X-Amz-Expires=300&X-Amz-Signature=13c4093e9e443a235760ef5432695e66148a850ee20214c21b2f4f649f5e7ce0&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=117819602&response-content-disposition=attachment%3B%20filename%3DiQSPR_sample_data.csv&response-content-type=application%2Foctet-stream\n    Resolving github-releases.githubusercontent.com (github-releases.githubusercontent.com)... 185.199.108.154, 185.199.109.154, 185.199.110.154, ...\n    Connecting to github-releases.githubusercontent.com (github-releases.githubusercontent.com)|185.199.108.154|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 954073 (932K) [application/octet-stream]\n    Saving to: \u2018iQSPR_sample_data.csv\u2019\n    \n    iQSPR_sample_data.c 100%[===================>] 931.71K  --.-KB/s    in 0.03s   \n    \n    2021-03-10 21:36:09 (26.9 MB/s) - \u2018iQSPR_sample_data.csv\u2019 saved [954073/954073]\n    \n    calculate_descriptors.ipynb\t    pre-trained_model_library.ipynb\n    custom_descriptor_calculator.ipynb  random_nn_model_and_training.ipynb\n    dataset_and_preset.ipynb\t    sample_data_building.ipynb\n    installation_044_v20210311.ipynb    set1\n    installation.ipynb\t\t    set2\n    iQSPR.ipynb\t\t\t    storage.ipynb\n    iQSPR_sample_data.csv\t\t    tools.ipynb\n    mp_ids.txt\t\t\t    transfer_learning.ipynb\n    nn_model_build.ipynb\t\t    visualization.ipynb\n\n\n\n\n**step 6**\r\n\r\nCheck versions one more.\r\n(For some reason pytorch is displayed as 1.8.0+cu101)\n\n\n```\nimport sklearn\r\nprint(sklearn.__version__)\r\nimport pymatgen\r\nprint(pymatgen.__version__)\r\nimport xenonpy\r\nprint(xenonpy.__version__)\r\nimport rdkit\r\nprint(rdkit.__version__)\r\nimport torch\r\nprint(torch.__version__)\n```\n\n    0.22.2.post1\n    2020.10.20\n    0.4.4\n    2020.03.3\n    1.8.0+cu101\n\n", "meta": {"hexsha": "11c4f9c666dfeb9289261ec10cc7d3558ed4c162", "size": 113179, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "0.4.4/samples/installation_044_v20210311.ipynb", "max_stars_repo_name": "by-student-2017/xenonpy-gcolab", "max_stars_repo_head_hexsha": "9a93121803f4f7e1af8b36a9b5e67daff02ac6c6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "0.4.4/samples/installation_044_v20210311.ipynb", "max_issues_repo_name": "by-student-2017/xenonpy-gcolab", "max_issues_repo_head_hexsha": "9a93121803f4f7e1af8b36a9b5e67daff02ac6c6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0.4.4/samples/installation_044_v20210311.ipynb", "max_forks_repo_name": "by-student-2017/xenonpy-gcolab", "max_forks_repo_head_hexsha": "9a93121803f4f7e1af8b36a9b5e67daff02ac6c6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 84.4619402985, "max_line_length": 5744, "alphanum_fraction": 0.5330317462, "converted": true, "num_tokens": 38063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3040416623541848, "lm_q2_score": 0.04336580015480672, "lm_q1q2_score": 0.013185009968386799}}
{"text": "```python\nimport pandas as pd\ndata = pd.read_csv('./seaborn-data/flights.csv')\n```\n\n\n```python\nhtml = data.to_html()\n```\n\n\n```python\ndata2 = pd.read_csv(\"C:/Users/NickC/Desktop/Acid buffer.csv\")\n```\n\n\n```python\nhtml2 = data2.to_html()\n```\n\n\n```python\nhtml2\n```\n\n\n\n\n    '<table border=\"1\" class=\"dataframe\">\\n  <thead>\\n    <tr style=\"text-align: right;\">\\n      <th></th>\\n      <th>Acid</th>\\n      <th>Molecular Formular</th>\\n      <th>Ka</th>\\n      <th>pKa</th>\\n    </tr>\\n  </thead>\\n  <tbody>\\n    <tr>\\n      <th>0</th>\\n      <td>trichloroacetic acid</td>\\n      <td>CCl3COOH</td>\\n      <td>3.020000e-01</td>\\n      <td>0.52</td>\\n    </tr>\\n    <tr>\\n      <th>1</th>\\n      <td>benzene sulfonic acid</td>\\n      <td>C6H5SO3H</td>\\n      <td>2.000000e-01</td>\\n      <td>0.70</td>\\n    </tr>\\n    <tr>\\n      <th>2</th>\\n      <td>iodic acid</td>\\n      <td>HIO3</td>\\n      <td>1.700000e-01</td>\\n      <td>0.77</td>\\n    </tr>\\n    <tr>\\n      <th>3</th>\\n      <td>sulfurous acid</td>\\n      <td>H2SO3</td>\\n      <td>1.550000e-02</td>\\n      <td>1.81</td>\\n    </tr>\\n    <tr>\\n      <th>4</th>\\n      <td>chlorous acid</td>\\n      <td>HClO2</td>\\n      <td>1.000000e-02</td>\\n      <td>2.00</td>\\n    </tr>\\n    <tr>\\n      <th>5</th>\\n      <td>phosphoric acid</td>\\n      <td>H3PO4</td>\\n      <td>7.590000e-03</td>\\n      <td>2.12</td>\\n    </tr>\\n    <tr>\\n      <th>6</th>\\n      <td>chloroacetic acid</td>\\n      <td>CH2ClCOOH</td>\\n      <td>1.410000e-03</td>\\n      <td>2.85</td>\\n    </tr>\\n    <tr>\\n      <th>7</th>\\n      <td>lactic acid</td>\\n      <td>CH3CH(OH)COOH</td>\\n      <td>8.320000e-04</td>\\n      <td>3.08</td>\\n    </tr>\\n    <tr>\\n      <th>8</th>\\n      <td>nitrous acid</td>\\n      <td>HNO2</td>\\n      <td>4.270000e-04</td>\\n      <td>3.37</td>\\n    </tr>\\n    <tr>\\n      <th>9</th>\\n      <td>hydrofluoric acid</td>\\n      <td>HF</td>\\n      <td>3.550000e-04</td>\\n      <td>3.45</td>\\n    </tr>\\n    <tr>\\n      <th>10</th>\\n      <td>formic acid</td>\\n      <td>HCOOH</td>\\n      <td>1.780000e-04</td>\\n      <td>3.75</td>\\n    </tr>\\n    <tr>\\n      <th>11</th>\\n      <td>benzoic acid</td>\\n      <td>C6H5COOH</td>\\n      <td>6.460000e-05</td>\\n      <td>4.19</td>\\n    </tr>\\n    <tr>\\n      <th>12</th>\\n      <td>acetic acid</td>\\n      <td>CH3COOH</td>\\n      <td>1.780000e-05</td>\\n      <td>4.75</td>\\n    </tr>\\n    <tr>\\n      <th>13</th>\\n      <td>carbonic acid</td>\\n      <td>H2CO3</td>\\n      <td>4.270000e-07</td>\\n      <td>6.37</td>\\n    </tr>\\n    <tr>\\n      <th>14</th>\\n      <td>hypochlorous acid</td>\\n      <td>HClO</td>\\n      <td>2.950000e-08</td>\\n      <td>7.53</td>\\n    </tr>\\n    <tr>\\n      <th>15</th>\\n      <td>hypobromous acid</td>\\n      <td>HBrO</td>\\n      <td>2.040000e-09</td>\\n      <td>8.69</td>\\n    </tr>\\n    <tr>\\n      <th>16</th>\\n      <td>boric acid</td>\\n      <td>B(OH)3\u2020</td>\\n      <td>7.240000e-10</td>\\n      <td>9.14</td>\\n    </tr>\\n    <tr>\\n      <th>17</th>\\n      <td>hydrocyanic acid</td>\\n      <td>HCN</td>\\n      <td>4.900000e-10</td>\\n      <td>9.31</td>\\n    </tr>\\n    <tr>\\n      <th>18</th>\\n      <td>phenol</td>\\n      <td>C6H5OH</td>\\n      <td>1.290000e-10</td>\\n      <td>9.89</td>\\n    </tr>\\n    <tr>\\n      <th>19</th>\\n      <td>hypoiodous acid</td>\\n      <td>HIO</td>\\n      <td>2.290000e-11</td>\\n      <td>10.64</td>\\n    </tr>\\n  </tbody>\\n</table>'\n\n\n\n\n```python\ndata3 = pd.read_csv(\"C:/Users/NickC/Desktop/Typical acid buffer.csv\")\n```\n\n\n```python\nhtml3 = data3.to_html()\n```\n\n\n```python\nhtml3\n```\n\n\n\n\n    '<table border=\"1\" class=\"dataframe\">\\n  <thead>\\n    <tr style=\"text-align: right;\">\\n      <th></th>\\n      <th>Acid buffers</th>\\n      <th>pKa</th>\\n      <th>Base buffers</th>\\n      <th>pka</th>\\n    </tr>\\n  </thead>\\n  <tbody>\\n    <tr>\\n      <th>0</th>\\n      <td>CH3COOH/CH3CO2\u2013</td>\\n      <td>4.75</td>\\n      <td>NH4+/NH3</td>\\n      <td>9.25</td>\\n    </tr>\\n    <tr>\\n      <th>1</th>\\n      <td>HNO2/NO2\u2013</td>\\n      <td>3.37</td>\\n      <td>(CH3)3NH+/(CH3)3N</td>\\n      <td>9.81</td>\\n    </tr>\\n    <tr>\\n      <th>2</th>\\n      <td>HClO2/ClO2\u2013</td>\\n      <td>2.00</td>\\n      <td>H2PO4\u2013/HPO42\u2013</td>\\n      <td>7.21</td>\\n    </tr>\\n  </tbody>\\n</table>'\n\n\n\n\n```python\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\nif __name__ == '__main__':\n    #\u83b7\u5f97\u6d6e\u70b9\u7c7b\u578bnumpy\u6570\u7ec4\n    x = np.arange(1.1,3,0.05)\n    #\u83b7\u5f97\u51fd\u6570\u7ed3\u679c\n    y1 = [4.75 + math.log(10, a) for a in x]\n    #\u753b\u56fe\n    plt.plot(x, y1, linewidth=2, color='#007500', label='log10(x) + 4.75')\n    #\u5728\u5750\u68071\u5904\u63cf\u7ea2\n    plt.plot([1,1],[y1[0], y1[1]],\"r--\",linewidth=2)\n\n    y2 = [6.75 + math.log(10,a) for a in x]\n    plt.plot(x,y2, linewidth=2,color='#9F35FF', label='log10(x) + 6.75')\n\n    y3 = [7.75 + math.log(10,a) for a in x]\n    plt.plot(x, y3, linewidth=2, color='#f75000', label='log10(x) +7.75')\n\n    plt.legend(loc='lower right')#\u5728\u53f3\u4e0b\u89d2\u663e\u793a\u8ba1\u7b97\u7528\u7684\u51fd\u6570\n    plt.grid(True)#\u5728\u5750\u6807\u7cfb\u4e0a\u753b\u683c\u5b50\n    #\u6253\u5370\u56fe\u7247\n    plt.show()\n```\n\n\n```python\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom math import log\nx1 = np.arange(0.000001,1,0.0001)\ny1 = np.log10(x1) + 1\n\nx2 = np.arange(0.000000001,0.000001,0.0000000001)\ny2 = np.log10(x2) + 1\n\nplt.plot(x1,y1)\nplt.plot(x2,y2)\nplt.grid(True)\nplt.show()\n```\n\n\n```python\nimport sympy\nimport numpy as np\nimport math\nx = sympy.Symbol('x')\ny = x*(0.5+x)*10**(4)/(1.77*(1-x))\nprint(sympy.solve(x*(0.5+x)*10**(4)/(1.77*(1-x))-1,x))\n```\n\n    [-0.500530624715971, 0.000353624715971055]\n\n\n\n```python\n-math.log10(3.54*10**(-4))\n```\n\n\n\n\n    3.450996737974212\n\n\n\n\n```python\nimport sympy\nimport numpy as np\nimport math\nx = sympy.Symbol('x')\ny = x*(0.4+x)*10**(4)/(1.77*(1.1-x))\nprint(sympy.solve(y-1,x))\n```\n\n    [-0.400662944614088, 0.000485944614088362]\n\n\n\n```python\n-math.log10(4.85*10**(-4))\n```\n\n\n\n\n    3.3142582613977365\n\n\n\n# Chapter 12\n## if Tests and Syntax Rules\n\nThis chapter presents the Python if statement, which is the main statement used for selecting from alternative actions based on test results. Because this is our first in-depth look at compound statements\u2014statements that embed other statements\u2014we will also explore the general concepts behind the Python statement syntax model here in more detail than we did in the introduction in Chapter 10. Because the if statement introduces the notion of tests, this chapter will also deal with Boolean expressions and fill in some details on truth tests in general.\n\n# General Format\nThe Python if statement is typical of if statements in most procedural languages. It\ntakes the form of an if test, followed by one or more optional elif (\u201celse if\u201d) tests and\na final optional else block. The tests and the else part each have an associated block\nof nested statements, indented under a header line. When the if statement runs, Python\nexecutes the block of code associated with the first test that evaluates to true, or the\nelse block if all tests prove false. The general form of an if statement looks like this\n\n\n```python\nif 1:\n    print('true')\nelif 2:\n    print('I saw what I saw. I saw whitewalker.')\n```\n\n    true\n\n\n# General Format\n\nif <test1>:          # if test\n    \n    <statements1>    # Associated block\n        \nelif <test2>:\n        \n    <statements2>    # Optional else\n        \nelse:\n        \n    <statements3>\n\n# Multiway Branching\n\n\n```python\nx = 'killer rabbit'\nif x == 'roger':\n    print(\"how's jessica?\")\nelif x == 'bugs':\n    print(\"what's up doc?\")\nelse:\n    print(\"Run away! Run away!\")\n```\n\n    Run away! Run away!\n\n\n\n```python\nchoice = 'ham'\nprint({'spam':1.25,'ham':1.99,'eggs':0.99,'bacon':1.10}[choice])\n```\n\n    1.99\n\n\n\n```python\nfrom sympy import *\ninit_printing()\ninit_session()\n```\n\n    IPython console for SymPy 1.4 (Python 3.7.4-64-bit) (ground types: python)\n    \n    These commands were executed:\n    >>> from __future__ import division\n    >>> from sympy import *\n    >>> x, y, z, t = symbols('x y z t')\n    >>> k, m, n = symbols('k m n', integer=True)\n    >>> f, g, h = symbols('f g h', cls=Function)\n    >>> init_printing()\n    \n    Documentation can be found at https://docs.sympy.org/1.4/\n    \n\n\n\n```python\nimport math\n```\n\n\n```python\nmath.sqrt(3)*math.tan(math.radians(18)) + math.tan(math.radians(18))*math.tan(math.radians(12)) + math.sqrt(3)*math.tan(math.radians(12))\n```\n\n\n```python\nexpand(exp(x))\n```\n\n\n```python\nseries(exp(-x))\n```\n\n\n```python\nplot(log(2**x+2**(x**2))-Rational(7,8))\nsolveset(log(2**x+2**(x**2))-Rational(7,8),x)\n```\n\n\n```python\nsimplify_logic(log(2**x+2**(x**2)) > Rational(7,8))\n```\n\n\n```python\nsummation(1/(2*n-1)-1/(2*n),(n,1,10000))-2**(0.5)/2\n```\n\n\n```python\nx = 'killer rabbit'\nif x == 'roger':\n    print(\"how's jessica?\")\nelif x == 'bugs':\n    print(\"what's up doc?\")\nelse:\n    print(\"Run away! Run away!\")\n```\n\n    Run away! Run away!\n\n\n\n```python\nchoice = 'ham'\nprint({'spam': 1.25, 'ham': 1.99, 'eggs': 0.99, 'bacon': 0.10}[choice])\n```\n\n    1.99\n\n\n\n```python\nif choice == 'spam':\n    print(1.25)\nelif choice == 'ham':\n    print(1.99)\nelif choice == 'eggs':\n    print(0.99)\nelif choice == 'bacon':\n    print(1.10)\nelse:\n    print('Bad choice')\n```\n\n    1.99\n\n\n\n```python\nbranch = {'spam': 1.25, 'ham': 1.99, 'eggs': 0.99}\nprint(branch.get('spam','Bad choice'))\nprint(branch.get('bacon','Bad choice'))\n```\n\n    1.25\n    Bad choice\n\n\n\n```python\nchoice = 'bacon'\nif choice in branch:\n    print(branch[choice])\nelse:\n    print(\"Bad choice\")\n```\n\n    Bad choice\n\n\n# Python Syntax Rules\n\n# Python has a simple, statement-based syntax\n## Statements execute one after another, until you say otherwise\n### Because Python's path through a program is called the control flow, statements such as if that affect it are often called control-flow statements\n## Block and statement boundaries are detected automatically\n### Python uses the indentation of statements under a header to group the statements in a nested block. Similarly, Python statements are not normally terminated with semicolons, rather, the end of a line usually marks the end of the statement coded on that line.\n## Compound statements = header + \":\" + indented statements. \n### The indented statements are called a block (or sometimes, a suite). In the if statement, the elif and else clauses are part of the if, but they are also header lines withe nested blocks of their own.\n## Blank lines, spaces, and comments are usually ignored.\n### Spaces inside statements and expressions are almost always ignored (except in string literals, and when used for indentation). Comments are always ignored: they start with a # character (not inside a string literal) and extend to the end of the current line.\n## Docstrings are ignored but are saved and displayed by tools\n### Docstrings are part of Python's larger documentation strategy and are covered in the last chapter in this part of the book.\n\n\n```python\nfrom sympy import *\ninit_printing()\ninit_session()\n```\n\n    IPython console for SymPy 1.4 (Python 3.7.4-64-bit) (ground types: python)\n    \n    These commands were executed:\n    >>> from __future__ import division\n    >>> from sympy import *\n    >>> x, y, z, t = symbols('x y z t')\n    >>> k, m, n = symbols('k m n', integer=True)\n    >>> f, g, h = symbols('f g h', cls=Function)\n    >>> init_printing()\n    \n    Documentation can be found at https://docs.sympy.org/1.4/\n    \n\n\n\n```python\nlimit(summation(1/n**2,(n,1,oo)),n,oo)\n```\n\n\n```python\nfloat(pi**2/6)\n```\n\n\n```python\nsummation(1/n**2,(n,1,oo))\n```\n\n\n```python\nfloat(summation(1/n**2,(n,1,10000)))\n```\n\n\n```python\npprint(series(sin(x)))\npprint(series(cos(x)))\n```\n\n         3     5        \n        x     x     \u239b 6\u239e\n    x - \u2500\u2500 + \u2500\u2500\u2500 + O\u239dx \u23a0\n        6    120        \n         2    4        \n        x    x     \u239b 6\u239e\n    1 - \u2500\u2500 + \u2500\u2500 + O\u239dx \u23a0\n        2    24        \n\n\n# Block Delimiters: Indentation Rules\n\n\n```python\nx = 1\nif x:\n    y=2\n    if y:\n        print('block2')\n    print('block1')\nprint('block0')\n```\n\n    block2\n    block1\n    block0\n\n\n\n```python\n   x ='spam'\nif 'rubbery' in 'shrubbery':\n    print(x*8)\n```\n\n    spamspamspamspamspamspamspamspam\n\n\n\n```python\nA1 = -13.212; B1 = -13122.470; C1= 4.354; D1 = -0.00330;\n```\n\n\n```python\nfrom sympy import *\ninit_printing()\ninit_session()\nT,ratio,Fsteam,Kp,x,P,F0 = symbols('T, ratio, Fsteam,Kp,x,P,F0')\n```\n\n    IPython console for SymPy 1.4 (Python 3.7.4-64-bit) (ground types: python)\n    \n    These commands were executed:\n    >>> from __future__ import division\n    >>> from sympy import *\n    >>> x, y, z, t = symbols('x y z t')\n    >>> k, m, n = symbols('k m n', integer=True)\n    >>> f, g, h = symbols('f g h', cls=Function)\n    >>> init_printing()\n    \n    Documentation can be found at https://docs.sympy.org/1.4/\n    \n\n\n\n```python\ndef KT(T):\n    return exp(A1 + B1/T + C1*log(T,10) + D1*T)*10**5\n```\n\n\n```python\nprint(KT(T))\n```\n\n    0.18285266951191*T**(4.354/log(10))*exp(-0.0033*T - 13122.47/T)\n\n\n\n```python\nplot(KT(T),(T,600,1500))\n```\n\n\n```python\nsimplify(solveset(Kp-(P*x**2)/((1-x)*(1+x+Fsteam/F0)),x))\n```\n\n\n\n\n$\\displaystyle \\left\\{\\frac{- Fsteam Kp + \\sqrt{Kp \\left(4 F_{0}^{2} Kp + 4 F_{0}^{2} P + 4 F_{0} Fsteam Kp + 4 F_{0} Fsteam P + Fsteam^{2} Kp\\right)}}{2 F_{0} \\left(Kp + P\\right)}, - \\frac{Fsteam Kp + \\sqrt{Kp \\left(4 F_{0}^{2} Kp + 4 F_{0}^{2} P + 4 F_{0} Fsteam Kp + 4 F_{0} Fsteam P + Fsteam^{2} Kp\\right)}}{2 F_{0} \\left(Kp + P\\right)}\\right\\} \\setminus \\left\\{1, - \\frac{F_{0} + Fsteam}{F_{0}}\\right\\}$\n\n\n\n\n```python\nF0 = 152.2\ndef Conv1(T):\n    return (sqrt(4*F0*(1.7 + KT(T))*KT(T)*F0))/(2*F0*(1.7+KT(T)))\n```\n\n\n```python\nplot(Conv1(T),(T,500,2000))\n```\n\n\n```python\ndef Conversion(T):\n    return (-KT(T)*152.2*3.5+sqrt((KT(T)*152.2*3.5)**2+4*152.2*(1.7+KT(T))*KT(T)*(152.2+152.2*3.5)))/(2*152.2*(1.7+KT(T)))\n```\n\n\n```python\nplot(Conversion(T),(T,500,2000))\n```\n\n# A Few Special Cases\n\n\n```python\nL = [\"Good\",  \n    \"Bad\", \n         \n    \"Ugly\"] # Open pairs may span lines\n```\n\n\n```python\na = b = 1.03; c = d = e = 'str'; f = g = [a, b, c, d, e, f, g];\nif a == b and c == d and \\\nd == e and f == g:\n    print('olde') # Backslashes allow continuations...\n```\n\n    olde\n\n\n\n```python\nf = e\nif (a == b and c == d and\n   d == e and e == f):\n    print(sin(x))\n```\n\n    sin(x)\n\n\n\n```python\nx = 1 + 2 + 3\\\n+ 4\n```\n\n\n```python\nprint(x)\n```\n\n    10\n\n\n# Truth Tests\n\n# In Python:\n-------------------------------------------------------------------------------\n* Any nonzero number or nonempty object is true.\n* Zero numbers, empty object, and the special object None are considered false. \n* Comparisons and equality tests are applied recursively to data structures.\n* Boolean and and or operators return a true or false operand object.\n-------------------------------------------------------------------------------\n\n\n```python\nif 1 and 2:\n    print(\"Is true if both X and Y are True\")\nif 1 or 0:\n    print(\"Is true if either X or Y is true\")\nif not None:\n    print(\"Is true if X is false (the expression returns True or False)\")\n```\n\n    Is true if both X and Y are True\n    Is true if either X or Y is true\n    Is true if X is false (the expression returns True or False)\n\n\n\n```python\n2 < 3, 3 < 2 # Less-than: return True or False (1 or 0)\n```\n\n\n\n\n    (True, False)\n\n\n\n\n```python\nprint(2 and 3, 3 and 2,\\\n      # Return left operand if false\n[] and {},\\\n3 and [])\n```\n\n    3 2 [] []\n\n\n\n```python\nfrom sympy import *\ninit_session()\n```\n\n    IPython console for SymPy 1.4 (Python 3.7.4-64-bit) (ground types: python)\n    \n    These commands were executed:\n    >>> from __future__ import division\n    >>> from sympy import *\n    >>> x, y, z, t = symbols('x y z t')\n    >>> k, m, n = symbols('k m n', integer=True)\n    >>> f, g, h = symbols('f g h', cls=Function)\n    >>> init_printing()\n    \n    Documentation can be found at https://docs.sympy.org/1.4/\n    \n\n\n\n```python\na11,a12,a13,a21,a22,a23,a31,a32,a33=symbols(\"a11,a12,a13,a21,a22,a23,a31,a32,a33\")\nb11,b12,b13,b21,b22,b23,b31,b32,b33=symbols(\"b11,b12,b13,b21,b22,b23,b31,b32,b33\")\n```\n\n\n```python\nhelp(matrix_multiply_elementwise)\n```\n\n    Help on function matrix_multiply_elementwise in module sympy.matrices.dense:\n    \n    matrix_multiply_elementwise(A, B)\n        Return the Hadamard product (elementwise product) of A and B\n        \n        >>> from sympy.matrices import matrix_multiply_elementwise\n        >>> from sympy.matrices import Matrix\n        >>> A = Matrix([[0, 1, 2], [3, 4, 5]])\n        >>> B = Matrix([[1, 10, 100], [100, 10, 1]])\n        >>> matrix_multiply_elementwise(A, B)\n        Matrix([\n        [  0, 10, 200],\n        [300, 40,   5]])\n        \n        See Also\n        ========\n        \n        __mul__\n    \n\n\n\n```python\nA = Matrix([[a11, a12, a13], [a21, a22, a23],[a31,a32,a33]])\nB = Matrix([[b11, b12, b13],[b21, b22, b23],[b31,b32,b33]])\n```\n\n\n```python\nmatrix_multiply_elementwise(A,B)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}a_{11} b_{11} & a_{12} b_{12} & a_{13} b_{13}\\\\a_{21} b_{21} & a_{22} b_{22} & a_{23} b_{23}\\\\a_{31} b_{31} & a_{32} b_{32} & a_{33} b_{33}\\end{matrix}\\right]$\n\n\n\n\n```python\nA, B, A * B\n```\n\n\n\n\n$\\displaystyle \\left( \\left[\\begin{matrix}a_{11} & a_{12} & a_{13}\\\\a_{21} & a_{22} & a_{23}\\\\a_{31} & a_{32} & a_{33}\\end{matrix}\\right], \\  \\left[\\begin{matrix}b_{11} & b_{12} & b_{13}\\\\b_{21} & b_{22} & b_{23}\\\\b_{31} & b_{32} & b_{33}\\end{matrix}\\right], \\  \\left[\\begin{matrix}a_{11} b_{11} + a_{12} b_{21} + a_{13} b_{31} & a_{11} b_{12} + a_{12} b_{22} + a_{13} b_{32} & a_{11} b_{13} + a_{12} b_{23} + a_{13} b_{33}\\\\a_{21} b_{11} + a_{22} b_{21} + a_{23} b_{31} & a_{21} b_{12} + a_{22} b_{22} + a_{23} b_{32} & a_{21} b_{13} + a_{22} b_{23} + a_{23} b_{33}\\\\a_{31} b_{11} + a_{32} b_{21} + a_{33} b_{31} & a_{31} b_{12} + a_{32} b_{22} + a_{33} b_{32} & a_{31} b_{13} + a_{32} b_{23} + a_{33} b_{33}\\end{matrix}\\right]\\right)$\n\n\n\n\n```python\nVx,Vy,Vz = symbols(\"Vx,Vy,Vz\")\nWx,Wy,Wz = symbols(\"Wx,Wy,Wz\")\n```\n\n\n```python\nV = Matrix([[Vx],[Vy],[Vz]])\nW = Matrix([[Wx],[Wy],[Wz]])\n```\n\n\n```python\nmatrix_multiply_elementwise(V,W) == matrix_multiply_elementwise(W,V)\n```\n\n\n\n\n    True\n\n\n\n\n```python\nfrom sympy.vector import CoordSys3D\na = CoordSys3D('a')\nb = a.create_new('b', transformation='spherical')\n```\n\n\n```python\nb.transformation_from_parent()\n```\n\n\n```python\nb.transformation_to_parent()\n```\n\n\n```python\nfrom sympy import *\nfrom sympy.vector import CoordSys3D\nC = CoordSys3D('C')\nVx,Vy,Vz = symbols(\"Vx,Vy,Vz\")\nWx,Wy,Wz = symbols(\"Wx,Wy,Wz\")\n```\n\n\n```python\nV = Vx*C.i + Vy*C.j + Vz*C.k\nW = Wx*C.i + Wy*C.j + Wz*C.k\n```\n\n\n```python\ninit_printing()\nprint(V.cross(W))\nprint(W.cross(V))\n```\n\n    (Vy*Wz - Vz*Wy)*C.i + (-Vx*Wz + Vz*Wx)*C.j + (Vx*Wy - Vy*Wx)*C.k\n    (-Vy*Wz + Vz*Wy)*C.i + (Vx*Wz - Vz*Wx)*C.j + (-Vx*Wy + Vy*Wx)*C.k\n\n\n\n```python\n(V.cross(W)).components\n```\n\n\n```python\nV.dot(W) == W.dot(V)\n```\n\n\n\n\n    True\n\n\n\n\n```python\nTxx,Txy,Txz = symbols(\"Txx Txy Txz\")\nTyx,Tyy,Tyz = symbols(\"Tyx Tyy Tyz\")\nTzx,Tzy,Tzz = symbols(\"Tzx Tzy Tzz\")\nT = Matrix([[Txx,Txy,Txz],[Tyx,Tyy,Tyz],[Tzx,Tzy,Tzz]])\n```\n\n\n```python\nV.to_matrix(C)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}Vx\\\\Vy\\\\Vz\\end{matrix}\\right]$\n\n\n\n\n```python\nhelp(mathematica_code)\n```\n\n    Help on function mathematica_code in module sympy.printing.mathematica:\n    \n    mathematica_code(expr, **settings)\n        Converts an expr to a string of the Wolfram Mathematica code\n        \n        Examples\n        ========\n        \n        >>> from sympy import mathematica_code as mcode, symbols, sin\n        >>> x = symbols('x')\n        >>> mcode(sin(x).series(x).removeO())\n        '(1/120)*x^5 - 1/6*x^3 + x'\n    \n\n\n\n```python\ntype(T)\n```\n\n\n\n\n    sympy.matrices.dense.MutableDenseMatrix\n\n\n\n\n```python\nfrom sympy import init_printing, Matrix\ninit_printing(use_unicode=True)\n```\n\n\n```python\nT\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}Txx & Txy & Txz\\\\Tyx & Tyy & Tyz\\\\Tzx & Tzy & Tzz\\end{matrix}\\right]$\n\n\n\n\n```python\nhelp(T.cross)\n```\n\n    Help on method cross in module sympy.matrices.matrices:\n    \n    cross(b) method of sympy.matrices.dense.MutableDenseMatrix instance\n        Return the cross product of ``self`` and ``b`` relaxing the condition\n        of compatible dimensions: if each has 3 elements, a matrix of the\n        same type and shape as ``self`` will be returned. If ``b`` has the same\n        shape as ``self`` then common identities for the cross product (like\n        `a \\times b = - b \\times a`) will hold.\n        \n        Parameters\n        ==========\n            b : 3x1 or 1x3 Matrix\n        \n        See Also\n        ========\n        \n        dot\n        multiply\n        multiply_elementwise\n    \n\n\n\n```python\nV = Matrix([[Vx], [Vy], [Vz]])\n```\n\n\n```python\nT*V\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}Txx Vx + Txy Vy + Txz Vz\\\\Tyx Vx + Tyy Vy + Tyz Vz\\\\Tzx Vx + Tzy Vy + Tzz Vz\\end{matrix}\\right]$\n\n\n\n\n```python\nMatrix([(T.col(0)).dot(V), (T.col(1)).dot(V), (T.col(2)).dot(V)])\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}Txx Vx + Tyx Vy + Tzx Vz\\\\Txy Vx + Tyy Vy + Tzy Vz\\\\Txz Vx + Tyz Vy + Tzz Vz\\end{matrix}\\right]$\n\n\n\n\n```python\n## 1 gradient\nfrom sympy import *\nfrom sympy.vector import Del, gradient\ninit_session()\nC = CoordSys3D('C')\ndelop = Del() # nabla\u7b97\u5b50\n\n# \u6807\u91cf\u573a f = x**2*y-xy\nf = C.x**2*C.y - C.x*C.y\n\nres = delop.gradient(f, doit=True) # \u4f7f\u7528nabla\u7b97\u5b50\n# res = delop(f).doit()\nres = gradient(f) # \u76f4\u63a5\u4f7f\u7528gradient\n\nprint(res) # (2*C.x*C.y - C.y)*C.i + (C.x**2 - C.x)*C.j\n```\n\n    IPython console for SymPy 1.4 (Python 3.7.4-64-bit) (ground types: python)\n    \n    These commands were executed:\n    >>> from __future__ import division\n    >>> from sympy import *\n    >>> x, y, z, t = symbols('x y z t')\n    >>> k, m, n = symbols('k m n', integer=True)\n    >>> f, g, h = symbols('f g h', cls=Function)\n    >>> init_printing()\n    \n    Documentation can be found at https://docs.sympy.org/1.4/\n    \n    (2*C.x*C.y - C.y)*C.i + (C.x**2 - C.x)*C.j\n\n\n\n```python\ninit_printing(use_unicode=True)\nprint(x**2*y-x*y)\n```\n\n    x**2*y - x*y\n\n\n\n```python\nfrom sympy import mathematica_code as mcode\nmcode(x**2*y-x*y)\n```\n\n\n\n\n    'x^2*y - x*y'\n\n\n\n\n```python\nV.dot(W)\n```\n\n\n\n\n$\\displaystyle Vx Wx + Vy Wy + Vz Wz$\n\n\n\n\n```python\nA  = 't' if 'spam' else 'f' # Nonempty is None\n```\n\n\n```python\nA\n```\n\n\n\n\n    't'\n\n\n\n\n```python\nA = 't' if '' else 'f'\n```\n\n\n```python\nA\n```\n\n\n\n\n    'f'\n\n\n\n\n```python\n['f','t'][bool('')]\n```\n\n\n\n\n    'f'\n\n\n\n\n```python\n['f','t'][bool('spam')]\n```\n\n\n\n\n    't'\n\n\n\n# Chapter Summary\n\nIn this chapter, we studied the Python if statement. Additionally, because this was our\nfirst compound and logical statement, we reviewed Python\u2019s general syntax rules and\nexplored the operation of truth tests in more depth than we were able to previously.\nAlong the way, we also looked at how to code multiway branching in Python and\nlearned about the if/else expression introduced in Python 2.5.\nThe next chapter continues our look at procedural statements by expanding on the\nwhile and for loops. There, we\u2019ll learn about alternative ways to code loops in Python,\nsome of which may be better than others. Before that, though, here is the usual chapter\nquiz.\n\n\n```python\n\n```\n", "meta": {"hexsha": "7947fcc43437b10858c395edd5ab3d556e0ab2b0", "size": 179111, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter 12 if Tests and Syntax Rules .ipynb", "max_stars_repo_name": "nickcafferry/Learning-Python-4th-Edition", "max_stars_repo_head_hexsha": "6684afc3a97d9719c3cdb2d451959ac15cc896cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-08T07:56:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-08T07:56:09.000Z", "max_issues_repo_path": "Chapter 12 if Tests and Syntax Rules .ipynb", "max_issues_repo_name": "nickcafferry/Learning-Python-4th-Edition", "max_issues_repo_head_hexsha": "6684afc3a97d9719c3cdb2d451959ac15cc896cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter 12 if Tests and Syntax Rules .ipynb", "max_forks_repo_name": "nickcafferry/Learning-Python-4th-Edition", "max_forks_repo_head_hexsha": "6684afc3a97d9719c3cdb2d451959ac15cc896cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 84.0107879925, "max_line_length": 23136, "alphanum_fraction": 0.8119490149, "converted": true, "num_tokens": 8113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814056074291439, "lm_q2_score": 0.046724961944710534, "lm_q1q2_score": 0.0131486662981549}}
{"text": "# Examples of usage\n\n\n```python\nimport rna\nfrom BasePredictor import BasePredictor\nfrom NaivePredictor import NaivePredictor\nfrom GeneticPredictor import GeneticPredictor\nfrom MFTPredictor import MFTPredictor\n\n%matplotlib inline\n```\n\n    Using gpu device 0: GeForce GTX 970M (CNMeM is disabled, cuDNN not available)\n\n\n### Data\nExamples are loaded from a file in FASTA-like format (see secondary.fa as an example). If you don't want to load RNA sequences with provided method, you can insert your data directly to predictor's **train** method. Such data should be a numpy array, and its dimensions should be $(n \\times 2)$, wherein the first column contains RNA sequences, and the second column contains bracket notations that describe the secondary structure.\n\n### Na\u00efve Predictor\nThis predictor is a simple MLP. It looks for the most similar RNA sequence in training data and applies the same structure to predicted sequence. The performance of such a predictor is not very good, but it can be quite accurate when there exists a homologous RNA sequence in training examples. One can use Genetic Predictor afterwards, to improve the result.\n\n\n```python\np = NaivePredictor(22, substrings=False, max_examples=100, library='lasagne', data_model='matrix')\nX = p.load_data(\"secondary.fa\", capitalize=True, purify=True, repair=True)\nprint(\"Shape of the data:\")\nprint(X.shape)\n\nprint(\"\\nA few of loaded examples:\")\nprint(X[:10])\n```\n\n    Shape of the data:\n    (939, 2)\n    \n    A few of loaded examples:\n    [['GGCGUAAGGAUUACCUAUGCC' '(((((..((....)).)))))']\n     ['GGACUAGCGGAGGCUAGUCC' '(((..(((....)))..)))']\n     ['GCGCUGACAAAGCGC' '(((((.....)))))']\n     ['GGCCGAUGGUAGUGUGGGGUCUCCCCAUGCGAGAGUAGGCC'\n      '((((.......(((((((.....))))))).......))))']\n     ['GGGAGCUCAACUCUCCCCCCCUUUUCCGAGGGUCAUCGGAACCA'\n      '(((((.......))))).......(((((......)))))....']\n     ['GGGUGACUCCAGAGGUCGAGAGACCGGAGAUAUCACCC'\n      '((((((((((...((((....))))))))...))))))']\n     ['GGUGUGAACACC' '((((....))))']\n     ['GACAGGGGAAACUUUGUC' '(((((((....)))))))']\n     ['GCCAGAUUGAGCCUGGGAGCUCUCUGGCC' '((((((..((((......)))))))))).']\n     ['GGCCAGAUUGAGCCUGGGAGCUCUCUGGCC' '(((((((..((((......)))))))))))']]\n\n\n### Molecule class\nYou can store RNA sequences as an instance of Molecule class. It provides tools for the structure visualization.\n\n\n```python\nm = rna.Molecule(X[1, 0], X[1, 1])\nrna.pair_matrix(m, show=True)\nrna.complementarity_matrix(m, show=True)\nm.show()\n```\n\n\n\n\n```python\np.train()\nprint(\"We will be trying to predict the secondary structure of the following sequence: GGCCUGAGGAGACUCAGAAGCC.\\n\")\nprint(p.predict(\"GGCCUGAGGAGACUCAGAAGCC\"))\nprint(\"\\nThis is the correct structure. Next tests check if our predictor can cope with slightly different sequences (reverse sequence or changed basepairs).\\n\")\nprint(p.predict(\"GGCCUGAGGAGACUCAGAAGCC\"[::-1]))\nprint(p.predict(\"CCCCUGAGGAGACUCAGAAGGG\"))\nprint(p.predict(\"AUCCUGAGGAGACUCAGAAGAU\"))\nprint(p.predict(\"AUCGUGAUGAGACUCAAAAGAU\"))\n```\n\n    We will be trying to predict the secondary structure of the following sequence: GGCCUGAGGAGACUCAGAAGCC.\n    \n    0.994215 0.363563\n    GGCCUGAGGAGACUCAGAAGCC\n    (((((((......))))..)))\n    \n    This is the correct structure. Next tests check if our predictor can cope with slightly different sequences (reverse sequence or changed basepairs).\n    \n    0.929067 0.999614\n    CCGAAGACUCAGAGGAGUCCGG\n    (((..((((......)))))))\n    0.554652 0.453151\n    CCCCUGAGGAGACUCAGAAGGG\n    (((((((......))))..)))\n    0.868492 0.443768\n    AUCCUGAGGAGACUCAGAAGAU\n    (((((((......))))..)))\n    0.694795 0.792209\n    AUCGUGAUGAGACUCAAAAGAU\n    (((((((((....)))))))))\n\n\n### Genetic Predictor\nAs we see, sometimes finding the most similar structure is not enough. We should find a way to improve our results, so let us try a different approach to the problem. A simple genetic algorithm can repair sequences with incorrect basepairs and sharp loops. Then it makes random connections and evaluates the new structure.\n\nLet's look at the last prediction of our Naive Predictor. Obviously, it is not the correct structure. We can try to improve the result with a Genetic Predictor.\n\n\n```python\np = GeneticPredictor(num_epoch=20)\np.predict(rna.Molecule(\"AUCGUGAUGAGACUCAAAAGAU\", \"(((((((((....)))))))))\"))\n```\n\n\n\n\n    [\n     AUCGUGAUGAGACUCAAAAGAU\n     (((.(((......)))...))), \n     AUCGUGAUGAGACUCAAAAGAU\n     (((.(((......))..).))), \n     AUCGUGAUGAGACUCAAAAGAU\n     (((.(..((.....))..)))), \n     AUCGUGAUGAGACUCAAAAGAU\n     (((.(((......)).)..))), \n     AUCGUGAUGAGACUCAAAAGAU\n     (((.(..((.....)).).)))]\n\n\n\nOne of the structures of the last population looks better than others:\n\nIt is indeed one of the most probable structures according to other predictors that you can find online, e.g. [this web server](http://rna.urmc.rochester.edu/RNAstructureWeb/Servers/Predict1/Predict1.html).\n\nThe last example will show that Genetic Predictor can make predictions from scratch. It makes it competitive with other more complex predictors. Its decision process is almost completely random, and it may converge to local minima, but it has very simple implementation, which makes it faster than other predictors. Let's try to predict the same sequence the Naive Predictor has earlier predicted correctly.\n\n\n```python\npredictions = []\n\n# we use the predictor 10 times and choose the best result to avoid locality\nfor test in range(10):\n    predictions += p.predict(rna.Molecule(\"GGCCUGAGGAGACUCAGAAGCC\"))\n\nprint(sorted(predictions, key=lambda x: x.evaluate())[-3:])\n```\n\n    [\n    GGCCUGAGGAGACUCAGAAGCC\n    ((((((((....)))))..)))\n    , \n    GGCCUGAGGAGACUCAGAAGCC\n    ((((((((....)))))..)))\n    , \n    GGCCUGAGGAGACUCAGAAGCC\n    ((((((((....)))))..)))\n    ]\n\n\nThe prediction is correct.\n\n### MFT Predictor\nMFT Predictor is based on [this article](http://aitopics.org/sites/default/files/classic/Hunter/03-Steeg.pdf) (Steeg). The network works similarly to Hopfield networks. However, neurons can have activation level equal to any number $a_i \\in [0, 1]$, and not only binary. The activation function is given by the formula:\n\n\\begin{equation}\na_i = \\sum_j a_j w_{ij} + f(i),\n\\end{equation}\nwhere\n- $a_i$ - activation of $i$-th neuron,\n- $w_{ij}$ - edge weight between neurons $i$ and $j$,\n- $f(i)$ - node weight for neuron's basepair.\n\n\n```python\np = MFTPredictor(num_epoch=100, alpha=6, beta=8, gamma=30, temperature=1/5)\npredictions = []\nfor i in range(10):\n    print(p.predict(rna.Molecule(\"GGCCUGAGGAGACUCAGAAGCC\")))\n```\n\n    GGCCUGAGGAGACUCAGAAGCC\n    (((.(..(((..)))..).)))\n    GGCCUGAGGAGACUCAGAAGCC\n    (((.(...((...))..).)))\n    GGCCUGAGGAGACUCAGAAGCC\n    ((.((....))...).....).\n    GGCCUGAGGAGACUCAGAAGCC\n    (((.(.....(...)...))))\n    GGCCUGAGGAGACUCAGAAGCC\n    ((((((((....)))))..)))\n    GGCCUGAGGAGACUCAGAAGCC\n    (......(....((...).)))\n    GGCCUGAGGAGACUCAGAAGCC\n    ((.((....)).).).(...).\n    GGCCUGAGGAGACUCAGAAGCC\n    (((.(...((...))..).)))\n    GGCCUGAGGAGACUCAGAAGCC\n    (.(....)(...(...)...))\n    GGCCUGAGGAGACUCAGAAGCC\n    ((((((((....)))))..)))\n\n\nIt seems that this predictor can produce good predictions, but it is dependent on many parameters that can be learnt from data. However, the training method is not well implemented yet.\n\n\n```python\n\n```\n", "meta": {"hexsha": "9c8d1f73b3a70e624e20553da06a550727be495c", "size": 22245, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "src/RNAssp/examples.ipynb", "max_stars_repo_name": "lrsoenksen/CL_RNA_SynthBio", "max_stars_repo_head_hexsha": "08b67ac5b0b262c4a79217dfe1d7457cd42791ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-10-14T11:34:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T16:26:18.000Z", "max_issues_repo_path": "src/RNAssp/examples.ipynb", "max_issues_repo_name": "lrsoenksen/CL_RNA_SynthBio", "max_issues_repo_head_hexsha": "08b67ac5b0b262c4a79217dfe1d7457cd42791ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RNAssp/examples.ipynb", "max_forks_repo_name": "lrsoenksen/CL_RNA_SynthBio", "max_forks_repo_head_hexsha": "08b67ac5b0b262c4a79217dfe1d7457cd42791ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-12-27T05:26:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T03:09:30.000Z", "avg_line_length": 58.3858267717, "max_line_length": 5848, "alphanum_fraction": 0.7409755001, "converted": true, "num_tokens": 2132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28457600421652673, "lm_q2_score": 0.046033906325528035, "lm_q1q2_score": 0.013100145120596663}}
{"text": "# Homework 3\n### Due Date:  Tuesday, September 19th at 11:59 PM\n\n---\n## Problem 1:  `Git` and recovering from a mistake\nYou will do this problem in the Jupyter notebook so I can see your output.  Once again, you will work with your playground repository.\n\n**NOTE:** At the beginning of each cell, you MUST type `%%bash`.  If you don't do that then you will not be able to work with the necessary bash commands.\n\nFollow the following steps for this problem:\n\n1. First cell:\n  1. Type `cd /tmp` to enter the temporary directory\n  2. git clone url_to_your_playground_repo\n2. Second cell:\n  1. Go into your local `playground` directory (`cd /tmp/playground`)\n  2. Type `git pull origin mybranch1`\n  3. `ls`\n3. Third cell:\n  1. Go into your local `playground` directory (`cd /tmp/playground`)\n  2. Type `git status`\n4. Fourth cell:\n  1. Go into your local `playground` directory (`cd /tmp/playground`)\n  2. Type `git reset --hard origin/master`\n  3. `ls`\n5. Fifth cell:\n  1. Go into your local `playground` directory (`cd /tmp/playground`)\n  2. Type `git status`\n\nThe whole point of this problem was to show you how to get your local repo back to an earlier state.  In this exercise, you accidentally merged something to `master` that you didn't want.  Rather than starting to delete things all over the place, you can simply reset your `HEAD` to a previous commit.\n\n## Problem 2:  `Git` and checking out a single file\nSometimes you don't want to merge an entire branch from the upstream but just one file from it. There is a direct use case for such a situation. Suppose I've made an error in this homework (or a lecture) and want to correct it. I fix the mistake in the upstream repo. In the meantime you have edited some other files and you really don't want to manually ignore my older copies of those files. Rather, you want to fix just one file from this new branch. This is how you do it.\n\nAs usual, be sure to type in `%%bash` before you write any `bash` commands in a cell.\n\n**Note:** The steps below assume that you have already cloned the `playground` repo in this notebook.\n\n1. First cell:\n  1. Go into the `playground` repo and fetch the changes from the master branch of the `course` remote.\n2. Second cell:\n  1. `git checkout course/master -- README.md`.  The `--` means that `README.md` is a file (as opposed to a `branch`).\n  2. `cat README.md`.  This just looks at the updated file.\n3. Third cell:\n  1. `git status`\n  2. Commit the changes to your local repo with an appropriate commit message.\n  3. `git status`\n  4. Push the changes to your remote repo.\n\n## Problem 3\nThis problem is related to the Lecture 4 exercises.\n1. Open the `languages.txt` file.  This file contains all the languages that students listed as their primary language in the course survey.\n2. Load the language strings from the file into a list.\n3. Use the `Counter` method from the `collections` library to count the number of occurrences of each element of the list.\n  + **NOTE:**  It is not necessary to use the `most_common()` method here.\n4. Create a bar plot to display the frequency of each language.  Be sure to label the x-axis!\n  + Remember, to create plots in the notebook you must put the line `%matplotlib inline` at the beginning of your notebook.\n  + Be sure to import matplotlib:  `import matplotlib.pyplot as plt`.\n  + To generate the bar plot write `plt.bar(x_coords, freqs)`.  You need to define `x_coords` and `freqs`.\n  + **Hint:** You may want to use the `numpy` `arange` function to create `x_coords`.  Remember, `x_coords` is the x-axis and it should have points for each distinct language.\n  + **Hint:** To get `freqs`, you may want to use the `values()` method on your result from step 3.  That is, `freqs = result_from_3.values()`.\n  + **Hint:** To label the x-axis you should use `plt.xticks(x_coords, labels)` where labels can be accessed through the `keys()` method on your result from step 3.\n\n---\n## Problem 4\nIn chemical kinetics, the reaction rate coefficient for a given reaction depends on the temperature of the system.  The functional relationship between the reaction rate coefficient and temperature is given by the Arrhenius rate:\n\\begin{align}\nk\\left(T\\right) = A T^{b}\\exp\\left(-\\frac{E}{RT}\\right)\n\\end{align}\nwhere $A$, $b$, and $E$ are parameters, $R = 8.314 \\dfrac{\\textrm{J}}{\\textrm{mol} \\textrm{ K}}$  is the universal gas constant, and $T$ is the temperature.\n\nWrite a function which returns $k\\left(T\\right)$ given $A$, $b$, $E$, and $T$.  Here are a few requirements:\n* The function should test for exceptions where necessary.\n* Pass the parameters $A$, $b$, and $E$ in as a list.\n* Make $R$ a keyword argument to the function.\n\n---\n## Problem 5\nUsing `numpy` arrays, plot $k\\left(T\\right)$ for $T\\in\\left(0, 5000\\right]$ for three different sets of parameters $\\left\\{A, b, E\\right\\}$.  Make sure all three lines are on the same figure and be sure to label each line.  You may use the function from Problem 2.  You may want to play with the parameters a little bit to get some nice curves but you won't lose points for ugly curves either (as long as they're correct!).\n", "meta": {"hexsha": "2bb5f5aa0288dd80b3a64cb6bd3666441bebf2a9", "size": 6672, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "homeworks/HW3/HW3.ipynb", "max_stars_repo_name": "HeyItsRiddhi/cs207_riddhi_shah", "max_stars_repo_head_hexsha": "18d7d6f1fcad213ce35a93ee33c03620f8b06b65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/HW3/HW3.ipynb", "max_issues_repo_name": "HeyItsRiddhi/cs207_riddhi_shah", "max_issues_repo_head_hexsha": "18d7d6f1fcad213ce35a93ee33c03620f8b06b65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/HW3/HW3.ipynb", "max_forks_repo_name": "HeyItsRiddhi/cs207_riddhi_shah", "max_forks_repo_head_hexsha": "18d7d6f1fcad213ce35a93ee33c03620f8b06b65", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.0588235294, "max_line_length": 485, "alphanum_fraction": 0.6309952038, "converted": true, "num_tokens": 1355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11279540031810142, "lm_q2_score": 0.11596072894699293, "lm_q1q2_score": 0.013079836842754919}}
{"text": "# Python4mri\nThis notebook contains a tutorial (+ exercises) to get familiar with Python in general and how to leverage it for (f)MRI analyses.\n\n## Before you get started\nTo run this notebook, make sure you have the following packages installed:\n\n- numpy\n- scipy\n- matplotlib\n- nibabel\n\nAn easy way to install these packages (assuming you have `pip` installed) is by running the following line in a terminal (in the same directory as this notebook):\n\n```\npip install -r requirements.txt\n```\n\nMake sure to close and restart the notebook after running this line (or restart the kernel: Kernel &rarr; Restart).\n\n## About this tutorial\nThis tutorial is about the programming language Python and how to use it for neuroimaging analysis. It is adapted from the first computer lab of the \"Neuroimaging: BOLD-MRI\" course given at the University of Amsterdam (Research Master Psychology). \n\nFirst, we'll discuss \"Jupyter notebooks\" and how to use them. Then, we'll discuss some basic Python syntax and constructs; this should be doable for people who are comfortable with programming (e.g., from previous experience with other programming languages, like Matlab or R). If you're not comfortable with programming, or you notice during this tutorial that you get stuck often, we recommend working through the free [Codecademy course](https://www.codecademy.com/learn/learn-python) up to and including unit 8 (loops). Note: you don't have to do the Codecademy quizzes (because you need to pay for that).\n\nAfter discussing basic Python syntax, we'll go over 'numpy' (Python's scientific computing package), followed by a section on 'Matplotlib' (Python's main plotting package). Finally, this tutorial ends with a section on how to interact with Nifti-files - the file format used most in the MRI community.\n\n## What you'll learn\nAfter this week's lab ... \n\n* you know how to work with Jupyter notebooks\n* you understand Python's basic syntax\n* you know how to leverage Numpy's powerful array-based functionality\n* you can plot data in various ways using Matplotlib\n* you know how to load, manipulate, and analyze Nifti-files\n\nIn sum: at the end of this tutorial, you are able to implement any computation/routine necessary for complex fMRI analysis using a combination of basic Python and Numpy.\n\n**Credits**: Created by Lukas Snoek. This tutorial is partly based on work by [Tomas Knapen and Daan van Es](https://tknapen.github.io) (VU University). <br>\n**Estimated time to complete**: 4-10 hours (depending on your familiarity with Python)<br>\n\n### Contents:\n\n1. Jupyter notebooks\n2. General Python\n3. Numpy\n4. Matplotlib / plotting\n5. Interacting with Nifti-files\n\nBut before anything else, let's get more familiar with the Jupyter notebook environment!\n\n## 1. Jupyter Notebooks\n\nSo, what are Jupyter notebooks, actually? Basically, using Jupyter notebooks is like using the web-browser as a kind of editor from which you can run Python code, similar to the MATLAB interactive editor or RStudio. Just like any editor, code in Jupyter notebooks is interpreted and executed by Python software on your computer/server.\n\nThe cool thing about these notebooks is that they allow you to mix code \"cells\" (see below) and text \"cells\" (such as this one). The (printed) output from code blocks are displayed right below the code blocks themselves. \n\nJupyter notebooks have two **modes**: edit mode and command mode.\n\n- *Command mode* is indicated by a grey cell border with a blue left margin (as is the case now!): When you are in command mode, you are able to edit the notebook as a whole, but not type into individual cells. Most importantly, in command mode, the keyboard is mapped to a set of shortcuts that let you perform notebook and cell actions efficiently (some shortcuts in command mode will be discussed later!). Enter command mode by pressing **Esc** or using the mouse to click outside a cell\u2019s editor area; <br><br>\n- *Edit mode* is indicated by a green cell border and a prompt showing in the editor area: When a cell is in edit mode, you can type into the cell, like a normal text editor. Enter edit mode by pressing Enter or using the mouse to double-click on a cell\u2019s editor area.\n\nWhen you're reading and scrolling through the tutorials, you'll be in the command mode mostly. But once you have to program (or write) stuff yourself, you have to switch to edit mode. But we'll get to that. First, we'll explain something about the two types of cells: code cells and text cells.\n\n### 1.1. Code cells\n\nCode cells are the place to write your Python code, similar to MATLAB 'code sections' (which are usually deliniated by %%). Importantly, unlike the interactive editors in RStudio and MATLAB, a code cell in Jupyter notebooks can only be run all at once. This means you cannot run it line-by-line, but you have to run the entire cell!\n\n#### 1.1.1. Running cells\nLet's look at an example. Below, you see a code-cell with two print-statements. To run the cell, select it (i.e., the cell should have a green or blue frame around it; doesn't matter whether you're in edit or command mode), and click on the \"&#9654; `Run`\" icon or press `ctr+Enter`). Try it with the cell below!\n\n\n```python\nprint(\"I'm printing Python code\")\nprint(3 + 3)\n```\n\n(You might be confused because we use the `print` statement with brackets -- `print()` -- while you've learned in Codecademy that you should use `print` without brackets. This is because Codecademy uses an old version of Python, Python2.7, while we use a newer version, Python3.5. In the new version, `print()` should be used with brackets!)\n\n#### 1.1.2. Stop running/execution of cells\nSometimes, you might want to quit the execution of a code-cell because it's taking too long (or worse, you created an infinite loop!). To do so, click the stop icon &#9632; in the top menu!\n\n#### 1.1.3. Restarting the kernel\nSometimes, you accidentally 'crash' the notebook, for example when creating an infinite loop or when loading in too much data. You know your notebook 'crashed' when stopping the cell (&#9632;) does not work and your cell continues its execution, as evident by the `In [*]:` prompt next to the cell. In those cases, you need to completely restart the notebook, or in programming lingo: you need to \"restart the kernel\". To do so, click `Kernel` and `Restart`.\n\nImportantly, when you restart the kernel, it will keep all text/code that you've written, but it will **not** remember all the variables that you defined before restarting the kernel, including the imports. So if you restart the kernel, you will have to re-import everything (e.g. run `import numpy as np` again).\n\n#### 1.1.3. Inserting cells\nAs you can see in the code cell above, you can only run the entire cell (i.e. both `print` statements). Sometimes, of course, you'd like to organise code across multiple cells. To do this, you can simply add new blocks (cells) by selecting \"Insert &rarr; Insert Cell Below\" on the toolbar (or use the shortcut by pressing the \"B\" key when you're in command mode; \"B\" refers to \"**b**elow\"). This will insert a new code cell below the cell you have currently highlighted (the currently highlighted cell has a blue box around it). \n\nTry inserting a cell below and write some code (e.g. `print(10 * 10)`).\n\n#### 1.1.4. Inline plotting\nAnother cool feature of Jupyter notebooks is that you can display figures in the same notebook! You simply define some plots in a code cell and it'll output the plot below it.\n\nCheck it out by executing (click the \"play\" button or `ctr+Enter`) the next cell.\n\n\n```python\n# We'll get to what the code means later in the tutorial\nimport matplotlib.pyplot as plt # The plotting package 'Matplotlib' is discussed in section 3!\n\n# This command makes sure that the figure is plotted in the notebook instead of in a separate window!\n%matplotlib inline \n\n# Now, let's plot something\nplt.plot(range(10))\nplt.show()\n```\n\n### 1.2. Text ('markdown') cells\nNext to code cells, jupyter notebooks allow you to write text in so-called \"markdown cells\" (the cell this text is written in is, obviously, also a markdown cell). Markdown cells accept plain text and can be formatted by special markdown-syntax. A couple of examples:\n\n\\# One hash creates a large header <br>\n\\#\\# Two hashes creates a slightly smaller header (this goes up to four hashes)\n\n**Bold text** can be created by enclosing text in \\*\\*double asterisks\\*\\* and italicized text can be created by enclosing text in \\*single asterisks\\*. You can even include URLs and insert images from the web; check this [link](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) for a cheatsheet with markdown syntax and options! All the special markdown-syntax and options will be converted to readable text *after running the text cell* (again, by pressing the \"play\" icon in the toolbar or by `ctr+Enter`).\n\nTo insert a text (markdown) cell, insert a new cell (\"Insert &rarr; Insert Cell Below\" or \"B\" in command mode). Then, *while highlighting the new cell*, press \"Cell &rarr; Cell Type &rarr; Markdown\" on the toolbar on top of the notebook (or, while in command mode, press the \"m\" key; \"m\" refers to \"markdown\"). You should see the prompt (the **`In [ ]`** thingie) disappear. Voil\u00e0, now it's a text cell!\n\n<div class=\"alert alert-warning\">\n<b>ToDo</b> (0 points)\n</div>\n\nTry it out yourself! Insert a new markdown cell and try to write the following (without peeking at this cell!):\n\n\"**OMG**, this is the most awesome Python tutorial *ever*.\"\n\n### 1.3. Changing cell type\nSometimes you might accidentally change the cell type from \"code\" to \"markdown\". To change it back, you can click \"Cell\" &rarr; \"Cell Type\" &rarr; \"Code\" or \"Markdown\" (or use the shortcuts, in command mode, \"m\" for markdown or \"y\" for code). \n\n<div class=\"alert alert-warning\">\n<b>ToDo</b> (0 points)\n</div>\n\nTry it out yourself! Change the code cell, which contains markdown, into a markdown cell!\n\n\n```python\nThis is a code cell, but it contains markdown, **oh no**!\n```\n\n### 1.4. Getting help\nThroughout this tutorial you'll encounter situations in which you have to use functions that you'd like to get some more information on, e.g. which inputs it expects. To get help on any python function you'd like to use, you can simply write the function-name appended with a \"?\" and run the cell. This will open a window below with the \"docstring\" (explanation of the function). Take for example the built-in function **`len()`**. To get some more information, simply type `len?` in a code cell and run the cell.\n\n<div class=\"alert alert-warning\">\n<b>ToDo</b> (0 points)\n</div>\n\nTry it out yourself: create a code cell below, type `len?` and check the output!\n\nIf this method (i.e. appending with \"?\") does not give you enough information, try to google (or just whatever search engine) the name of the function together with 'python' and, if you know from which package the function comes, the name of that package. For instance, for len() you could google: ['python len()'](http://lmgtfy.com/?q=python+len), or later when you'll use the numpy package, and you'd like to know how the `numpy.arange` function works you could google: 'python numpy arange'. \n\n<div class=\"alert alert-success\">\n    <b>REMEMBER</b>: Google is your friend! Googling things is an integral aspect of programming. If you're stuck, try to figure it out yourself by trying to find the solution online. At first, this might seem frustrating, but in the long run, it will make you a better programmer.\n</div>\n\nIf you still can't figure out your problem, you can of course ask your classmates or tutors.\n\n### 1.5. Saving your work & closing down the notebook\nYou're running and actively editing the notebook in a browser, but remember that it's still just a file located on your account on your laptop. Therefore, for your work to persist, you need to save the notebook once in a while (and definitely before closing the notebook). To save, simply press the floppy-disk image in the top-left (or do `ctr+s` while in command mode).\n\nIf you saved your notebook and want to cloe it, click \"File\" &rarr; \"Close and halt\". This will stop your notebook from running and close it.\n\nAlright. Now that you've had your first contact with Jupyter notebooks - let's talk about about exercises and assignments.\n\n## 1.6. Exercises (ToDo/ToThink) and assignments\nWe believe that the best way to learn how to do neuroimaging analysis is by *actually programming* the analyses yourself. You have already seen some of these (ungraded) exercises, which we call \"ToDos\". There are different types of exercises throughout the notebook, including:\n\n- <font color='orange'>ToDos</font> : short programming exercises, either zero or for a few points\n- <font color='blue'>ToThinks</font>: questions about the (preceding) text/material, either zero or for a few points\n- <font color='red'>Assignments</font>: a larger programming exercise (sometimes with additional questions), usually for a larger amount of points\n\nSometimes, you also encounter <font color='green'>Tips and Tricks</font>, which may contain advice, more information on a specific topic, or links to relevant websites or material.\n\nWe highly recommend doing/answering the ToDos/ToThinks, not only because they are (often) worth points, but also because they are designed to improve your understanding of the material!\n\nAnyway, a \"ToDo\" would look something like this:\n\n<div class=\"alert alert-warning\">\n<b>ToDo</b> (0 points)\n</div>\n\nIn the code-cell below, set the variable `x` to 5 (without quotes!) and remove the `raise NotImplementedError` statement.\n\n\n```python\nx = 'not yet 5'\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\nEach answer-cell will contain the statement `raise NotImplementedError`. When implementing your ToDo, you always have to remove this statement (this will inform us, during grading, that you actually implemented something)!\n\nThen, *after* each code-cell corresponding to the ToDo, there are one or more code cell(s) with \"tests\" written by us. These tests may provide you with feedback about whether you implemented the \"ToDo\" correctly, and optionally gives you some hints on how to solve your error(s). If you run this cell and you don't get any errors, you did it correctly and you'll receive the point(s) for that ToDo. If it gives any errors, try to use the information from the error and/or print statements to solve the ToDo. \n\nThese tests are usually implemented as a set of `assert` statements, which 'assert' whether a specific statement is true. If it evaluates to `False`, then that means you've made an error. For example, for the above `ToDo`, we simply evaluated the statement `assert(x == 5)` to check whether you set `x` to 5 correctly, as is shown in the cell below:\n\n\n```python\n''' Checks whether the above ToDo is correct. '''\ntry:\n    assert(x == 5)\nexcept AssertionError as e:\n    print(\"x does not evaluate to 5! Did you replace 'not yet 5' with 5?\")\n    raise(e)\nelse:\n    print(\"Well done!\")\n```\n\n**Note**: this week, each *ToDo* is explicitly tested, so you can always check your answer (and continue trying until you get it right). However, from next week onwards, we will also include **hidden tests**, which you won't see. We will only run these tests when grading your notebook. Therefore, from next week onwards, passing all tests in your ToDos/Assignments does not necessarily mean that you will score a 100% for that week's lab, because you might have made a mistake in the hidden tests.\n\nFor this week, however, there are no hidden tests, so you can continue working on your ToDos until you get the answer right. \n\nNow, let's try another one, but this time for real! It's a super simple one, so use this to earn a free point. Note that it is followed by two test-cells, which test different aspects of your implementation (each passed test gives you 0.5 points).\n\n<div class=\"alert alert-warning\">\n<b>ToDo</b> (1 point)\n</div>\n\nIn the code-cell below, set the variable `y` to `x * 2`, so you have to replace `None` with `x * 2` (yes, this is as easy as it sounds).\n\n\n```python\nx = 2\ny = None\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' This tests the above ToDo. '''\ntry:\n    assert(y == x * 2)\nexcept AssertionError as e:\n    print(\"y does not evaluate to x * 2 (i.e., 4)! Did you replace y with x * 2?\")\n    raise(e)\nelse:\n    print(\"Well done!\")\n```\n\n\n```python\n''' This tests the above ToDo as well. '''\ntry:\n    assert(isinstance(y, int))\nexcept AssertionError as e:\n    print(\"y doesn't seem to be an integer (it is of type %s; make sure it is!\" % type(y))\n    raise(e)\nelse:\n    print(\"Well done!\")\n```\n\n<div class=\"alert alert-danger\">\n<b>WARNING</b>: You might think that simply editing the test-cell such that everything passes (e.g. by removing the assert statement) is a smart way to get all the points; we however record the original state of the (test-)cells in a database, and we'll use those tests to grade your answers, so no easy way to cheat!\n</div>\n\nThroughout the notebook you'll encounter several 'ToDos' - some are worth points, some are not. In addition to these 'ToDos', you'll also encounter 'ToThinks', which are short questions about the material, meant to make you think about what you're doing. Like the 'ToDos', some of these are worth points, others don't. Each 'ToThink' cell is followed by a markdown-cell in which you can write your answer. Obviously, these answers cannot be automatically tested, so there won't be a test-cell with `asserts`. These 'ToThinks' are graded manually by us. \n\nA typical 'ToThink' may look like this:  \n\n<div class='alert alert-info'>\n<b>ToThink</b> (1 point)\n</div>\n\nWhat's your name? Please write it in the text-cell below.\n\nYOUR ANSWER HERE\n\nMake sure you actually write your name in the cell above for another free point! (You'll have to double-click the text-cell to go into 'edit mode' and replace 'YOUR ANSWER HERE' with your name.)\n\nNext to 'ToDos' and 'ToThinks', some labs may contain 'Assignments'. These are basically just a collection of programming exercises and/or open questions, each with a certain amount of points associated with it. You'll encounter assignments usually at the end of a specific section. Usually, altogether these assignments are worth substantially more points than 'ToDos' or 'ToThinks'.\n\nAn assigment may look like this:\n\n<div class='alert alert-danger'>\n<b>Assignment</b> (5 points)\n</div>\n\nThis is an example assignment; it's not actually worth any points. In a real assignment, you would see one or more coding assignments or open questions below. \n\n## 2. General Python\nThis section will provide short tutorial on basic Python syntax and concepts (if you've done Codecademy, this should all be familiar).\n\nHere, we will cover:\n\n* Python data types (integers, floats, lists, dictionaries)\n* Python functions\n* Python classes\n* Conditionals (if-then-else)\n* Loops (for-loop, list-comprehensions)\n* Imports\n\n**Note**: while there are exercises in this section, there are not worth any points. So if you feel comfortable with Python, you may skip it.\n\n### 2.1. Structure of Python\n\nPython is a multipurpose programming language, meaning it can be used for almost anything. While the \"standard library\" of Python (i.e., the functionality that is shipped with any Python installation) contains the bare minimum for any programming language, Python's versatility comes from a massive community of developers that created many different \"third-party\" packages for almost any purpose you can think of (e.g., visualization, machine learning, web frameworks, etc.).\n\nFor example:\n* the [scipy](https://www.scipy.org/) package provides functionality for scientific computing (e.g. statistics, signal processing);\n* the [numpy](http://www.numpy.org/) package provides data structures and functionality for (very fast) numeric computing (e.g. multidimensional numeric array computations, some linear algebra);\n* the [matplotlib](http://matplotlib.org/) package provides plotting functions;\n* and various specialied neuroimaging packages provide functionality to work and analyze (f)MRI (e.g. [nibabel](http://nipy.org/nibabel/) and [nipype](http://nipy.org/nipype)) and MEG/EEG (e.g. [MNE](http://www.martinos.org/mne/stable/index.html)).\n\nBasically, there are packages for everything you can think of (also: creating websites, game programming, etc.)! In this course, we will mostly use basic Python in combination with the scientific computing packages ('numpy', 'scipy') and specialized neuroimaging packages ('nibabel', 'nipype').  \n\n#### Import statements\nAs explained above, Python ships with some default functionality. This means that it's already available upon starting a notebook (or any other Python environment) and doesn't need to be imported. An example is the function `len()`.\n\n\n```python\nmy_list = [1, 2, 3]\nprint(len(my_list))\n```\n\nHowever, non-built-in packages - such as `numpy` - need to be explicitly imported to access their functionality. After importing, their functions are accessible as: `{package}.{function}`.\n\nFor example:\n\n\n```python\nimport numpy\n\n# Now you can access the numpy function `add()` as numpy.add()\nprint(numpy.add(5, 3)) \n```\n\nHowever, writing `numpy` in front of every function you access from it becomes annoying very quickly. Therefore, we usually abbreviate the package name by two or three characters, which can be achieved through:\n\n```\nimport {package} as {abbreviation}\n```\n\nFor example, people usually abbreviate the numpy import as follows:\n\n\n```python\nimport numpy as np\n\n# Now you can access numpy functions such as 'add()' as:\nprint(np.add(5, 3))\n```\n\nOften (but not always), Python packages consist of subpackages. These subpackages are often used to group similar functions/code together. For example, the `numpy` package has the subpackage (also called \"module\") `random`, which contains functions that allow you to generate random data from different distributions.\n\nIn the previous cell, we imported the **entire** `numpy` package by running `import numpy as np`. However, sometimes you might only need a particular subpackage (\"module\"), like the subpackage `random` from `numpy`. To import **only** the `random` subpackage, you can do the following:\n\n\n```python\nimport numpy.random\n```\n\nNow, you can use functions from the `numpy.random` class! Technically, even subpackages may contain their own subpackages. Importing subpackages from subpackages works the same way:\n\n```import mainpackage.somesubpackage.anothersubpackge.yetanothersubpackage\n```\n\nThroughout the tutorials, you'll see different packages (e.g. `nibabel` and `scipy`) being imported using abbreviations (e.g., `import nibabel as nib`). \n\nAlso, you don't need to import an *entire* package, but you can also import a specific function or class. This is done as follows:\n\n```\nfrom {package} import {function1}, {function2}, {etc}\n```\n\nAn example:\n\n\n```python\nfrom numpy import add, subtract\n\n# Now I can simply call add() and subtract()\nprint(add(5, 3))\n```\n\nNote that some packages have a hierarchical structure with subpackages (also called modules). For example, scipy has a subpackage `ndimage` (with functions for n-dimensional arrays). To import *only* this subpackage, do the following:\n\n\n```python\nfrom scipy import ndimage\n# Now you can call functions from the ndimage subpackage,\n# e.g. gaussian_filter\n\nprint(ndimage.gaussian_filter([10, 5, 4], 2))\n```\n\nNote that you can mix and match all of these operations to customize the import to your own liking (see cell below for such a fancy import). In this course, we'll usually just import entire packages (e.g. `import numpy as np`) or specific functions/subpackages (e.g. `from scipy import stats`). \n\nAnother thing you can do with imports is renaming the function/module you're importing. This follows the following syntax:\n\n```\nfrom {package} import {some function/module} as {new name}\n```\n\nSee the cell below for an example:\n\n\n```python\n# a fancy import\nfrom scipy.stats import binom_test as omg_binomial_testing_so_cool\n\nprint(omg_binomial_testing_so_cool(0.5, 10))\n```\n\n<div class=\"alert alert-warning\">\n<b>ToDo</b> (0 points)\n</div>\n\nImport the function \"randn\" (which generates random numbers from a standard normal distribution) from the numpy subpackage \"random\" and rename it \"random_normal_generator\".\n\n\n```python\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo. '''\ntry:\n    assert('random_normal_generator' in dir())\nexcept AssertionError as e:\n    print(\"I couldn't find the function 'random_normal_generator'; did you spell it correctly?\")\n    raise(e)\nelse:\n    print(\"Well done!\")\n```\n\n\n```python\n''' Another test for the above ToDo. '''\ntry:\n    assert(random_normal_generator.__name__ == 'randn')\nexcept AssertionError as e:\n    print(\"Your 'random_normal_generator' function does not point to the 'randn' numpy.random subpackage!\")\n    raise(e)\nelse:\n    print(\"Well done!\")\n```\n\n<div class=\"alert alert-danger\">\n<b>Wildcard imports.</b> Python allows also \"wildcard\" imports, like: <code>from numpy import *</code>, which says: import <em>everything</em> from the <code>numpy</code> package. This is often discouraged, because the beauty of having explicit imports (unlike MATLAB) is that you known where your functions come from (e.g., is it a base Python function or a numpy function?). \n</div>\n\n#### Whitespace for indentation\nIn most programming languages, code blocks (e.g., if-else blocks, or for-loops) are delineated by dedicated symbols (often curly brackets, `{}`). For example, an if-else block in R is written like this:\n\n```\nif (x > 0) {\n   y = x + 5\n} else {\n   y = x - 5\n}\n```\n\nWhile in languages like R and MATLAB whitespace/indentation is used for readability, it is not necessary! The above if-else statement in R can also be written as:\n\n```\nif (x > 0) { y = x + 5 } else { y = x - 5 }\n```\n\nHowever, in Python, whitespace and indentation is important! In Python, indendation - instead of curly braces - delineates code blocks, and if code is incorrectly indented, Python will give an error! For example, an if-else statement in Python must be indented (always with 4 spaces or a tab). If you don't do this, it will give an `IdentationError`, as show below:\n\n\n```python\nx = 0\nif x < 0:\ny = x + 5\nelse:\ny = x - 5   \n```\n\nIf you make sure the two statements beginning with `y = ...` are indented with 4 spaces/a tab, the error disappears.\n\n<div class=\"alert alert-warning\">\n<b>ToDo</b> (0 points)\n</div>\n\nFix the code block above by identing it correctly.\n\n#### Note: Python versions\nAs a side note: there are currently two different supported versions of Python, 2.7 and 3.x (with \"x\" being at 3.7 currently). Somewhat confusingly, Python 3.0 introduced many backwards-incompatible changes to the language, so code written for 2.7 may not work under 3.x and vice versa. For this class all code will use Python **3.6** (but 90% of this notebook should be compatible with Python 2.7., we think ...). So if you want to use code from this class on your own computer, make sure you use Python 3.6 (or higher)!\n\n### 2.2 Basic data types\nBase (i.e. built-in) Python has mostly the same data types as you might know from MATLAB or R, such as numbers (integers/floats), strings, and lists (cells in MATLAB; lists in R). Also, Python has to data types that might be unknown to MATLAB/R users, such as \"dictionaries\" and \"tuples\", which are explained later. \n\n#### 2.1. Numbers\nNumbers are represented either as integers (\"whole\" numbers) or floats (numbers with decimals, basically).\n\n\n```python\nx = 3\nprint('x is of type', type(x))  # use type(variable) to find out of what data-type something is!\n\ny = 3.1415\nprint('y is of type', type(y))\n```\n\nLet's try to apply arithmetic to x as defined above with some basic operations:\n\n\n```python\nprint(x + 1)   # Addition;\nprint(x - 1)   # Subtraction;\nprint(x / 2)   # Division;\nprint(x * 2)   # Multiplication;\nprint(x ** 2)  # Exponentiation;\n```\n\nThe above commands apply operations to x, but do not *change* x itself. To permanently change x, you have to store the results of the operation (e.g. `x + 1`) into a variable (e.g. `x2 = x + 1`), as shown in the cell below:\n\n\n```python\nx = 3\nx_new = x + 2\n\n# If you simply want to update an existing variable, you can do this in two ways:\nx = x + 1\n\n# ... or:\nx += 1\n\nprint(x)  \n\nx *= 2 # This is the same as: x = x * 2\nprint(x) \n```\n\n<div class=\"alert alert-warning\">\n<b>ToDo</b> (0 points) \n</div>\n\nIn the cell below, make a new variable, `y`, which should contain `x` minus 5 and subsequently raised to the 4th power.\n\n\n```python\nx = 8\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo.'''\n\n# Check if there exists a variable 'y'\ntry:\n    assert('y' in dir())\nexcept AssertionError as e:\n    print(\"The variable 'y' doesn't seem to exist! Did you name it correctly?\")\n    raise(e)\nelse:\n    print(\"Well done! 1 out of tests 2 passed\")\n\n# Check if it has the correct number\ntry:\n    assert(y == 81)\nexcept AssertionError as e:\n    print(\"The variable y does not seem to equal x minus 5, raised to the power 4.\")\n    raise(e)\nelse:\n    print(\"Well done! 2 out of tests 2 passed\")\n```\n\n<div class='alert alert-success'>\n    <b>Tip!</b>\n    When you're working on your ToDo, it's often informative to print (intermediate) output/variables of your solution (in a new code cell for example). This might give insight into (potentially) failing tests! \n</div>\n\n#### 2.2. Booleans\nPython implements all of the usual operators for comparisons. Similar to what you might know from other languages, `==` tests equivalence, `!=` for not equivalent, and `<` and `>` for larger/smaller than. The result of those comparisons are a datatype called a \"boolean\", representing truth values. Booleans can take on the value `True` or `False`.\n\nCheck out some examples below:\n\n\n```python\na = 3\nb = 5\nis_a_equal_to_b = (a == b)\n\nprint(is_a_equal_to_b)\nprint('the ouput is of type', type(is_a_equal_to_b)) \n```\n\nSome more examples of Boolean operators:\n\n\n```python\nbool_1 = 3 > 5 # False, because 3 is not greater than 5\nbool_2 = (5 == 5) # True, because, well, 5 is 5\nprint(bool_1)\nprint(bool_2)\n```\n\nHowever, for some Boolean logic, python doesn't use operators (such as && for \"and\" and | for \"or\") but uses special (regular English) **words**: \n\n\n```python\n# note: bool_1 is False, bool_2 is True\nprint(bool_1 and bool_2)  # Logical AND, both have to be True\nprint(bool_1 or bool_2)   # Logical OR, either one of them has to be True\nprint(not bool_1)         # Logical NOT, the inverse of bool_1\nprint(bool_1 != bool_2)   # Logical XOR, yields True when bool_1 and bool_2 are not equal\n```\n\n(Although, technically, the keyword `and` and `&`, and `or` and `|` can be used interchangeably.)\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (0 points)\n</div>\n\nMess around with booleans in the cell below. Try some more complex things, like: `not ((3 > 5) and not (5 < 2))`. \nDo you understand why the result is the way it is? Try to follow the logic in the sequence of statements (not graded, so no tests follow the code block).\n\n\n```python\n# Do your ToDo here:\n\n```\n\n#### 2.3. Strings\nStrings in Python are largely the same as in other languages.\n\n\n```python\nh = 'hello'   # String literals can use single quotes\nw = \"world\"   # or double quotes; it does not matter.\n\nprint(h)\nprint(len(h))  # see how many characters in this string\n```\n\nA very nice feature of Python strings is that they are easy to concatenate: just use '+'!\n\n\n```python\nhw = h + ', ' + w + '!' # String concatenation\nprint(hw)\n```\n\nYou can also create and combine strings with what is called 'string formatting'. This is accomplished by inserting a placeholder in a string, that you can fill with variables. An example is given below:\n\n\n```python\n# Here, we have a string with a placeholder '%s' (the 's' refers to 'string' placeholder)\nmy_string = 'My favorite programming language is: %s'\nprint('Before formatting:')\nprint(my_string)\n\n# Now, to 'fill' the placeholder, do the following:\nmy_fav_language = 'Python'\nmy_string = 'My favorite programming language is: %s' % my_fav_language\n\nprint('After formatting')\nprint(my_string)\n```\n\nYou can also use specific placeholders for different data types:\n\n\n```python\nweek_no = 1 # integer\nstring1 = 'This is week %i of neuroimaging' % week_no # the %i expects an integer!\nprint(string1)\n\nproject_score = 99.50 # float\nstring2 = 'I will get a %f on my midterm exam!' % project_score\nprint(string2)\n\n# You can also combine different types in a string:\nstring3 = 'In week %i of neuroimaging, %s will get a %f (or higher) for my lab-assignment' % (week_no, \"I\", 95.00)\nprint(string3)\n```\n\nFor a full list of placeholders see https://docs.python.org/2/library/stdtypes.html#string-formatting-operations\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (0 point)\n</div>\n\nModify the variable `to_print` defined below, such that printing it (i.e., running `print(to_print)`) will print:\n\n```\nNeuroimaging will be my favorite course 4ever\n```\nSo you'll have to \"fill\" the \"%\" placeholders using string formatting. That is, you have to put a `%` sign after the `to_print` variable and \"fill\" it with the correct inputs. And don't forget to remove the `NotImplementedError`.\n\n(This is a manually graded answer, so no tests!)\n\n\n```python\nto_print = \"%s will be my favorite course %iever\"\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo'''\ntry:\n    assert(to_print == 'Neuroimaging will be my favorite course 4ever')\nexcept AssertionError as e:\n    print(\"This string is not formatted correctly!\")\n    raise(e)\nelse:\n    print(\"Well done!\")\n```\n\n#### 2.4. Lists\nA list is the Python equivalent of an array, but can be resized and can contain elements of different types. It is similar to a list in R and a cell in MATLAB. Note that indices in python start with 0! This means that the 3rd element of the list below is accessed through `[2]`.\n\nLet's check out some lists and how to index them!\n\n\n```python\n# Note that list may contain numbers ...\nlist1 = [3, 1, 2]\n\n# ... or strings\nlist2 = ['hello', 'world']\n\n# ... or, actually, anything at all! List lists themselves\nlist3 = ['hello', [3, 1, 2], 'world', 5.3, -999]\n```\n\nWhatever the contents of a list, they are indexed the same way: using square brackets with an integer, e.g. `[0]`:\n\n\n```python\nprint('The first element of list1 is: %i' % list1[0])\nprint('The second element of list2 is: %s' % list2[1])\nprint('The last element of list3 is: %i' % list3[-1])\nprint('The second-to-last element of list3 is: %f' % list3[-2])\n```\n\nNote that you can also use negative indices! Negative indices start indexing from the end of the list, so `[-1]` indexes the last element, `[-2]` indexes the second-to-last element, etc.\n\nWe cannot only 'extract' element from lists using indexing, but we can also replace them! This works as follows:\n\n\n```python\nsome_list = [1, 2, 3, ['A', 'B', 'C']]\n\n# Let's set the first element of some_list to 100:\nsome_list[0] = 100\nprint(some_list)\n\n# Note that indexing a list within a list is done with sequential square brackets,\n# so if we want to index the element 'A' in some_list, we do:\nsome_list[-1][0] = 'ANOTHER STRING'\nprint(some_list)\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (0 points)\n</div>\n\nIn the cell below, replace the element 'TO_REPLACE_1' with 'REPLACED' and the element 'TO_REPLACE_2' also with 'REPLACED' in the list `todo_list`.\n\n\n```python\ntodo_list = [1, 'B', 'TO_REPLACE_1', [5, 3, 1038, 'C'], [1, 3, 5, [9, 3, 1, 'TO_REPLACE_2']]]\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n**Note**: the code-cell below as usual tests your ToDo, but we haven't written out the tests in the cell itself. Instead, we wrote the tests in a separate Python module (a file with a collection of functions, objects, etc.), which we import here. (We do this, because writing out the tests here would give you the answer rightaway!)\n\n\n```python\n''' Tests the above ToDo with a custom function. '''\n# Below, we import all the tests (*) from the neuroedu package\nfrom nb_tests import test_list_indexing\ntest_list_indexing(todo_list)\n```\n\nIn addition to accessing list elements one at a time, Python provides concise syntax to access specific parts of a list (sublists); this is known as **slicing**. \n\nLet's look at some slice operations:\n\n\n```python\nnums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nprint(nums)         # Our original list\n\n# Get a slice form index 2 to 4 (exclusive); prints \"[2, 3]\"\nprint(nums[2:4])    \n\n# Get a slice from index 2 to the end; prints \"[2, 3, 4, 5, 6, 7, 8, 9]\"\nprint(nums[2:])  \n\n# Get a slice from the start to index 3 (exclusive); prints \"[0, 1, 2]\"\nprint(nums[:3])     \n\n# Get a slice of the whole list; prints [\"0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\"\nprint(nums[:])\n\n# Slice indices can be negative; prints [\"0, 1, 2, 3, 4, 5, 6, 7, 8]\",\n# so everything up to (but not including) the last element\nprint(nums[:-1])    \n```\n\nImportantly, slices are \u00ebnd exclusive\", which means that if you slice from `0` to `5`, you get the indices `0, 1, 2, 3, 4`! While this may seem confusing at first, you'll get used to it. To appreciate the use of \"end exclusive indexing\", do the next ToDo.\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (0 points)\n</div>\n\nSlice the list below, `to_be_split`, into two separate lists: one called `first_half` with the first half of the list values, and one called `second_half`, with the second half of the list values.\n\n\n```python\nto_be_split = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo '''\nassert(first_half == [10, 11, 12, 13, 14, 15, 16, 17])\nassert(second_half == [18, 19, 20, 21, 22, 23, 24, 25])\nprint(\"Well done!\")\n```\n\nApart from the syntax `[from:to]`, you can also specify a \"stride\" (sort of step-size) of your slice using the syntax `[from:to:stride]`:\n\n\n```python\n# Return values in steps of 2\nprint(nums[::2])    \n\n# Returns values in steps of 3, but starting from the second element\nprint(nums[1::3])   \n```\n\nWith 'normal' indexing of lists, you can only index a subsequently set/replace one element at the time. With slices, however, you can set multiple elements at the same time:\n\n\n```python\nnums[2:4] = [100, 200] # Assign a new sublist to a slice\nprint(nums)         # Prints \"[0, 1, 100, 200, 4, 5, 6, 7, 8, 9]\"\n```\n\n<font color='blue'><b>Tip</b></font>: instead of creating sequential lists like:\n\n`num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]`\n\n... we can also create a list using the syntax: \n\n`num = list(range(starting_point, exclusive_end_point))`\n\nFor example, to create a list from 5 to 15, use the following:\n\n`num = list(range(5, 16))` \n\nWe'll use this construction (`list(range(x, y))`, or without the `list`) quite often in this course!\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (0 points)\n</div>\n\nFrom the list (`my_list`) below, extract the numbers 2, 3, 4, 5, and 6 using a slice and store it in a new variable named `my_new_list`!\n\n\n```python\nmy_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\nfrom nb_tests import test_slicing_1\navailable_vars = dir()\nif 'my_new_list' not in available_vars:\n    raise ValueError(\"You did not store the results in a new variable caleld 'my_new_list'!\")\n    \ntest_slicing_1(my_new_list)\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (0 point) \n</div>\n\nFrom the list below (`my_list_2`), extract the values `[5, 7, 9, 11]` using a slice (i.e., in a single operation!) and store it in a new variable named `my_new_list_2`.\n\n\n```python\nmy_list_2 = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21]\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo '''\nfrom nb_tests import test_slicing_2\navailable_vars = dir()\n\nif 'my_new_list_2' not in available_vars:\n    raise ValueError(\"You didn't define the variable 'my_new_list_2'!\")\n\ntest_slicing_2(my_new_list_2)\n```\n\n**NOTE**: you can index *strings* the same way as you index lists! Try to see it this way: a string is, quite literally, a *string* (\"list\") of characters. So, to get the first letter of some string s (e.g, 'this is a string'), you simply write: `s[0]`. To get first 5 characters, you write `s[:5]`, etc etc. Remember this!\n\n\n```python\n# Check out string slicing/indexing below\ns = 'neuroimaging'\nprint(s[0:7:2])\n```\n\n#### Dictionaries\nDictionaries might be new for those who are used to MATLAB or R. Basically, a dictionary is an **unordered** list in which list entries have a name (which is also referred to as a \"key\"). To get a value from a dictionary, you have to use the \"key\" as index instead of using an integer (although, strictly speaking, keys can also be integers ... but that's not important for now).\n\nLet's check out such a dictionary and how to index it. We build a dictionary using the following syntax: \n\n`{some_key: value, another_key: another_value, etc: etc}`\n\nThe keys can be anything! Strings, integers, lists ... doesn't matter! Mostly, though, strings are used as keys. \nSo, let's look at an example:\n\n\n```python\nmy_dict = {'cat': 'cute', 'dog': 'furry'}  # Create a new dictionary with some data\n```\n\nTo index a dictionary, we'll use square brackets `[]` again, just like with lists. But now, we can index using the key!\n\n\n```python\nindexed_value = my_dict['cat']\nprint(indexed_value)\n```\n\nAdding new key-value pairs to dictionaries is easy! Just index it with a new key, and assign the value to it:\n\n\n```python\nmy_dict['fish'] = 'wet'     # Set an entry in a dictionary\nprint(my_dict['fish'])      # Prints \"wet\"\n```\n\nLike a list, an entry in a dictionary can be of any data type:\n\n\n```python\nmy_dict['rabbit'] = ['omg', 'so', 'cute']\nprint(my_dict['rabbit'])\n```\n\nIf you try to 'index' a dictionary with a key that doesn't exist, it raises a \"KeyError\", which means you're trying to index something that doesn't exist:\n\n\n```python\nprint(my_dict['monkey'])\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\nIn the code cell below, add a new key to the dictionary `my_dict` named `\"rat\"` and with the value `\"nasty\"`.\n\n\n```python\n# Add the key-value pair here!\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo. '''\n\ntry:\n    assert('rat' in my_dict)\nexcept AssertionError as e:\n    print(\"There exists no key 'rat' in my_dict!\")\n    raise(e)\n\ntry:\n    assert(my_dict['rat'] == 'nasty')\nexcept AssertionError as e:\n    print(\"The value of key 'rat' is '%s' and NOT 'nasty'\" % my_dict['rat'])\n\nprint('Well done!')\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (0 point)\n</div>\n\nValues of dictionaries can be any type of object, even dictionaries themselves! So, add a new key to the dictionary `my_dict` named `\"another_dict\"` with the value of *another* dictionary with the keys `\"a\"` and `\"b\"` and the corresponding values `1` and `2`. Also, try to figure out how to index the value `1` from the 'nested' dictionary (this is not graded, but try it nonetheless!).\n\n\n```python\n# Do the ToDo here\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo. '''\n\ntry:\n    assert('another_dict' in my_dict)\nexcept AssertionError as e:\n    print(\"There exists no key 'another_dict' in my_dict!\")\n    raise(e)\n\ntry:\n    assert(my_dict['another_dict']['a'] == 1)\n    assert(my_dict['another_dict']['b'] == 2)\nexcept AssertionError as e:\n    print(\"The key 'another_dictionary' should contain a dictionary with keys 'a' and 'b', corresponding\"\n          \"to values 1 and 2, respectively.\")\n    raise(e)\n\nprint('Well done!')\n```\n\n#### tuples\nTuples are very much like lists, but the main difference is that they are immutable. In other words, after creating them, they cannot be modified (their values cannot be replaced/altered):\n\n\n```python\n# A list can be modified ...\nmy_list = [1, 2, 3]\nmy_list[0] = 0\nprint(my_list)\n```\n\n\n```python\n# ... but a tuple cannot (and will give an error!)\nmy_tuple = (1, 2, 3)\nprint(my_tuple[0]) # you can print parts of tuple ...\nmy_tuple[0] = 0   # but you cannot modify it!\n```\n\nYou probably won't use tuples a lot, but you might come across them when using and writing functions, as multiple outputs from functions are stored in tuples (see below; but more about that in the next section!).\n\n\n```python\ndef my_epic_function(integer):\n    \n    return integer, integer * 2\n\noutputs = my_epic_function(10)\nprint(outputs)\nprint(type(outputs))\n```\n\n### 2.3 Functions and methods\nIf you followed the Codecademy tutorial, you are familiar with the basic syntax of functions in Python; if you're familiar with other programming languages, you'll see that the syntax of Python functions is quite similar to what you're used to.\n\nA function definition in Python starts with the keyword `def`, followed by the function name and round brackets with the arguments to the function, and finally the contents of the function, like so (note the indentation with four spaces/tab!!!):\n\n```python\ndef my_awesome_function(arg_1, arg_2):\n    print(\"Argument 1: %s\" % arg_1)\n    print(\"Argument 2: %s\" % arg_2)\n```\n\nThis dummy-function above prints some stuff, but does not **return** something. Similar to R (but unlike MATLAB), you have to explicitly state what you want to **return** from the function by the \"return\" statement. \n\nSo, suppose you have a function that adds 2 to any number. Let's define it as follows (you have to run the cell to let Python know you've defined this function):\n\n\n```python\ndef add_2_to_a_number(some_number):\n    new_number = some_number + 2\n```\n\nHere, we omitted a **return** statement to return the value of `new_number`. This is a problem, because in Python (like most languages) you cannot 'peek' inside the function after using it! You can only access whatever is returned. \n\nSo, in the function defined above, we cannot access the value of `new_number`, because we didn't return it (so it will give an error):\n\n\n```python\n# This will give an error!\nadd_2_to_a_number(5)\nprint(new_number)\n```\n\nSo, to access the *value* of `new_number` (that is, *not* `new_number` itself, but its associated value), we need to return it:\n\n\n```python\ndef add_2_to_a_number_fixed(some_number):\n    new_number = some_number + 2\n    return new_number\n```\n\n\n```python\nvalue_contained_in_new_number = add_2_to_a_number_fixed(5)\nprint(\"Results of function 'add_2_to_a_number' with argument '5': %i\" % value_contained_in_new_number)\n```\n\nImportantly, you can name the variable to which you assign the return value *anyway you like*. This doesn't have to be `new_number`! Like above, we named it `value_contained_in_new_number`, but it really doesn't matter.\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (0 points) \n</div>\n\nIn the code cell below, we've started writing a function named `extract_last_element` that takes one input-argument - a list - and returns the last element of the list. Some parts of the function are missing, though, which you need to write! When you're done, run the test-cell below it to check if it's right!\n\n\n```python\ndef extract_last_element(input_list):\n    \n    # YOUR CODE HERE\n    raise NotImplementedError()\n```\n\n\n```python\ntry:\n    assert(extract_last_element(input_list=[0, 1, 2]) == 2)\nexcept AssertionError as e:\n    print(\"Your function fails for input [0, 1, 2]\")\n    raise(e)\n\ntry:\n    assert(extract_last_element(input_list=[0]) == 0)\nexcept AssertionError as e:\n    print(\"Your function fails for input [0]\")\n    raise(e)\n\ntry:\n    assert(extract_last_element(input_list=['string1', 'string2', 'string3']) == 'string3')\nexcept AssertionError as e:\n    print(\"Your function fails for input ['string1', 'string2', 'string3']\")\n    raise(e)\n\nprint(\"Well done!\")\n```\n\nAlright, that was probably relatively easy. Let's do a slightly harder one.\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (0 point) \n</div>\n\nWrite a completely new function named `get_values_from_odd_indices` (so you have to write the `def ...` part!) that takes one input-argument - a list - and returns all values from the odd indices of that list. So, suppose you have a list:\n\n`[2, 100, 25, 48, 92, -5, 12]`\n\n... your function should return: \n\n`[100, 48, -5]`\n\n... i.e, the values from odd indices (here: 1, 3, 5; we exclude index zero!)\n\nHint: slices might be useful here!\n\nWhen you're done, run the test-cell below it to check if it's right!\n\n\n```python\n# Implement your function (called get_values_from_odd_indices) here:\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the ToDo above. '''\ntry:\n    assert('get_values_from_odd_indices' in dir())\n    assert(callable(get_values_from_odd_indices))\nexcept AssertionError as e:\n    print(\"Your function 'get_values_from_odd_indices' does not seem to exist!\")\n\ntry:\n    out = get_values_from_odd_indices([0, 1, 2])\n    if out is None:\n        msg = \"ERROR: did you forget the Return statement?\"\n        raise ValueError(msg)\nexcept ValueError as e:\n    raise(e)\n    \nprint(\"Well done (also run the next cell with tests)!\")\n```\n\n\n```python\n''' Some other tests for the ToDo above. '''\ninp = [0, 1, 2]\noutp = get_values_from_odd_indices(inp)\nans = [1]\ntry:\n    assert(outp == ans)\nexcept AssertionError as e:\n    print(\"Your function returned '%r' but I expected '%r'\" % (outp, ans))\n    raise(e)\n\ninp = [5, 7, 9, 11, 13, 15, 18, 20, 21]\noutp = get_values_from_odd_indices(inp)\nans = [7, 11, 15, 20]\ntry:\n    assert(outp == ans)\nexcept AssertionError as e:\n    print(\"Your function returned '%r' but I expected '%r'\" % (outp, ans))\n    raise(e)\n\nprint(\"Well done!\")\n```\n\n**IMPORTANT**: it is possible to return *multiple things* from a function. The function, then, returns these things as a tuple, which can subsequently be \"unpacked\". Let's check out an example using a custom function called `minmax_of_list` which returns both the minimum and maximum of a list:\n\n\n```python\ndef minmax_of_list(some_list):\n    ''' Returns both the minimum and maximum of a list.\n    \n    Parameters\n    ----------\n    some_list : list\n        A list with numbers (int/float) only\n    \n    Returns\n    -------\n    min_value : a float or int\n        The minimum of a list\n    max_value : a float or int\n        The maximum of a list\n    '''\n    min_value = min(some_list)\n    max_value = max(some_list)\n    \n    return min_value, max_value\n```\n\nAs you can see, returning multiple things is a simple as adding more variables after the `return` statement, separated by commas. If we now call the function with a particular list, it gives us back a tuple of size 2 (one value for the minimum, one value for the maximum):\n\n\n```python\noutput_from_function = minmax_of_list([0, 1, 2, 3])\nprint(output_from_function)\nprint(type(output_from_function))\n```\n\nWe can now \"unpack\" the tuple (i.e., extract the separate values) in several ways. One way is to simply index the values:\n\n\n```python\noutput_from_function = minmax_of_list([0, 1, 2, 3])\nminimum = output_from_function[0]\nprint(\"Minimum: %i\" % minimum)\n\nmaximum = output_from_function[1]\nprint(\"Maximum: %i\" % maximum)\n```\n\nAlternatively, we can already \"extract\" one value, let's say the maximum (index 1 of the tuple) right after calling the function, so we can skip dealing with the tuple altogether:\n\n\n```python\nmaximum = minmax_of_list([0, 1, 2, 3])[1]  # The [1] extracts the maximum from the output of the function immediately!\nprint(\"Maximum: %i\" % maximum)\n```\n\nKeep this feature of returning multiple things and tuple unpacking in mind for the rest of the course (you'll definitely encounter it more often!).\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (0 points)\n</div>\n\nWrite a function called `get_length_first_and_last_value` which takes a list as single input argument, and returns the length of the list (the first output), the first value of the list (the second output), and the last value of the list (the third output). So, e.g., for the list `[0, 1, 2, 3, 4]`, the function should return `(5, 0, 4)` (a tuple of length 3, with the three outputs). Note that it should work for lists of arbitrary lengths and value types!\n\n\n```python\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo'''\ntry:\n    assert('get_length_first_and_last_value' in dir())\n    assert(callable(get_length_first_and_last_value))\nexcept AssertionError as e:\n    print(\"Your function 'get_length_first_and_last_value' does not seem to exist!\")\n\nout = get_length_first_and_last_value([0, 1, 2])\nif out is None:\n    msg = \"ERROR: did you forget the Return statement?\"\n    raise ValueError(msg)\n    \nif len(out) != 3:\n    msg = \"ERROR: you returned %i things; this should be 3!\" % len(out)\n    raise ValueError(msg)\n\nassert(out == (3, 0, 2))\nassert(get_length_first_and_last_value([2, 3, 4, 5, 6, 7]) == (6, 2, 7))\nassert(get_length_first_and_last_value([0]) == (1, 0, 0))\nassert(get_length_first_and_last_value(['a', 'b']) == (2, 'a', 'b'))\n\nprint(\"Well done!\")\n```\n\n#### Methods\nHowever, in Python, functions are not the only things that allow you to 'do' things with data. In others' code, you'll often see function-like expressions written with periods, like this: `some_variable.function()`. These `.function()` parts are called 'methods', which are like functions 'inherent' to a specific type of object. In other words, it is a function that is applied to the object it belongs to. \n\nDifferent type of objects in Python, such as stings and lists, have their own set of methods. For example, the function you defined above (`extract_last_element()`) also exists as a method each list has, called `pop()`! (This is a builtin, standard, method that each list in Python has.) See for yourself in the block below.\n\n\n```python\nmy_list = [0, 5, 10, 15] \nprint(my_list.pop())\n\n# You can also just do the following (i.e. no need to define a variable first!):\nprint([0, 5, 10, 15].pop())\n\n# ... which is the same as:\nprint(extract_last_element([0, 5, 10, 15]))\n```\n\nNot only lists, but also other data-types (such as strings, dictionaries, and, as we'll see later, numpy arrays) have their own methods. How methods work exactly is not really important (this belongs to the topic of 'object-oriented programming'), but it is necessary to know **what** it does, as you'll see them a lot throughout this course. \n\nWe'll show you a couple of (often-used) examples:\n\n\n```python\n# For lists, we have .append()\nx = [0, 10, 15]\nx.append(20) # Add a new element to the end of the list using the append() method!\nprint(x)\n```\n\n**Note**: sometimes, methods modify the object (above: `x`) *in-place*, which means that the method does not return anything, so you don't have to assign it to a new variable. If you accidentally do this, the new object's value is `None`, as you see below: \n\n\n```python\nx = [0, 10, 15]\nx_new = x.append(20)\nprint(x_new)\n```\n\nSome often-used methods for dictionaries:\n\n\n```python\nmy_dict = {'a': 0, 'b': 1, 'c': 2}\n\n# The .values() method returns all the values of the dictionary \nprint(list(my_dict.values()))\n\n# And the .keys() method returns all the keys of the dictionary\nprint(list(my_dict.keys()))\n```\n\n**Note**: these dictionary-methods actually *do* return values! \n\nSome often-used methods for strings:\n\n\n```python\nmy_string = 'neuroimaging is fun!'\n\n# The .upper() method returns the string in uppercase!\nprint(my_string.upper())\n\n# The .count(substring) method returns the number of times a substring occurs in a string\nprint(my_string.count('n'))\n\n# The .replace(old, new) method replaces substrings\nprint(my_string.replace('fun', 'awesome'))\n\n# The .split(separator) splits a string into subparts (returned as a list)\nprint(my_string.split(' '))  # split by whitespace\n```\n\n#### Default arguments in functions/methods\nImportantly, and unlike most (scientific) programming languages, Python supports the use of 'default' arguments in functions. Basically, if you don't specify an optional argument, it uses the default:\n\n\n```python\ndef exponentiate_number(number, power=2):\n    return number ** power\n\nprint(exponentiate_number(2)) # now it uses the default!\nprint(exponentiate_number(2, 10)) # now it \"overwrites\" the default and uses power=10\nprint(exponentiate_number(number=2, power=10)) # also note that you can 'name' arguments \n```\n\n### 2.4 If-statements\nIf-elif-else statements in Python are quite straightforward. An example:\n\n\n```python\nx = 5\n\nif x > 0:\n    print('x is larger than 0')\nelif x < 0:\n    print('x is smaller than 0')\nelse:\n    print('x must be exactly 0!')\n```\n\nIf-statements contain at least an `if` keyword, but optionally also one or more `elif` (\"else if\") statements and an optional `else` statement. We'll practice this (in a `ToDo`) after the section on Loops.\n\n### 2.4 Loops\nLoops in Python (for- and while-loops) are largely similar to MATLAB and R loops, with some minor differences in  their syntax:\n\n\n```python\nanimals = ['cat', 'dog', 'monkey']\nfor animal in animals:\n    print(animal)\n```\n\nBasically, each data type that is also an \"iterable\" (something that you can iterate over) can be used in loops, including lists, dictionaries, and tuples.\n\n\n```python\n# An example of looping over a list\nmy_list = [1, 2, 3]\nfor x in my_list:\n    print(x)\n```\n\nMATLAB users might be used to looping over indices instead of the actual list values, like the following:\n\n```\nfor i=1:100\n    disp(some_list(i));\nend```\n\nIn Python, however, you loop (by default) over the contents of a list:\n\n```\nfor entry in some_list:\n    print(entry)\n```\n    \nIf you want to access for the value **AND** the index, you can use the built-in `enumerate` function:\n\n\n```python\nmy_list = ['a', 'b', 'c']\nfor index, value in enumerate(my_list):\n    \n    print('Loop iteration number (index) = %i, value = %s' % (index, value))\n\n# Don't forget that Python indexing starts at zero!\n```\n\n\n```python\n# Looping over a tuple (exactly the same as looping over a list)\nmy_tuple = (1, 2, 3)\nfor x in my_tuple:\n    print(x)\n```\n\n\n```python\n# Iterating over a dictionary can be done in a couple of ways!\nmy_dict = {'a': 1, 'b': 2, 'c': 3}\n\n# Looping over the keys ONLY\nfor key in my_dict:\n    print(key)\n```\n\n\n```python\n# Looping over both the keys and the entries\nfor key, entry in my_dict.items():\n    print(key, entry)\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (0 points) \n</div>\n\nComplete the function below - named `extract_values_smaller_than_0` - that takes a single list with numbers as input and returns a new list with *only the values smaller than 0* from the input-list. For example, suppose our input-list is:\n\n```\n[2, -5.3, 1.8, 0.0, -205.1, 6029]\n```\n\n... the function should return:\n\n```\n[-5.3, -205.1]\n```\n\nHint: use an if-statement in combination with the `.append()` method of the empty list we initialized below (`list_to_return`) to fill the `list_to_return` variable in a for-loop. In other words, the function should contain an if-statement in a for-loop (in which you need to use the `.append()` method).\n\n\n```python\n# Complete the function below (make sure to remove raise NotImplementedError!)\ndef extract_values_smaller_than_0(input_list):\n    \n    # We initialize an empty list here (which you need to fill using a for-loop)\n    list_to_return = []\n    \n    # YOUR CODE HERE\n    raise NotImplementedError()\n    \n    return list_to_return\n```\n\n\n```python\n''' Tests the ToDo above. '''\ninp = [-5, 2, 3, -8]\noutp = extract_values_smaller_than_0(inp)\nans = [-5, -8]\ntry:\n    assert(outp == ans)\nexcept AssertionError as e:\n    print(\"Your function  with input '%r' returned '%r', but I expected '%r'\" % (inp, outp, ans))\n    raise(e)\n    \ninp = [0, 2, -3]\noutp = extract_values_smaller_than_0(inp)\nans = [-3]\ntry:\n    assert(outp == ans)\nexcept AssertionError as e:\n    print(\"Your function  with input '%r' returned '%r', but I expected '%r'\" % (inp, outp, ans))\n    raise(e)\n\ninp = [0, 0, 0]\noutp = extract_values_smaller_than_0(inp)\nans = []\ntry:\n    assert(outp == ans)\nexcept AssertionError as e:\n    print(\"Your function  with input '%r' returned '%r', but I expected '%r'\" % (inp, outp, ans))\n    raise(e)\n\nprint(\"Well done!\")\n```\n\n#### Advanced loops: list comprehensions\nSometimes, writing (and reading!) for-loops can be confusing and lead to \"ugly\" code. Wouldn't it be nice to represent (small) for-loops on a single line? Python has a way to do this: using what is called `list comprehensions`. It does exactly the same thing as a for-loop: it takes a list, iterates over its entries (and does something with each entry), and (optionally) returns a (modified) list. \n\nLet's look at an arbitrary example of a for-loop over a list:\n\n\n```python\nnums = [0, 1, 2, 3, 4]\n\n# Also, check out the way 'enumerate' is used here!\nfor index, x in enumerate(nums):\n    nums[index] = x ** 2\n\nprint(nums)\n```\n\nYou can make this code simpler using a list comprehension:\n\n\n```python\nnums = [0, 1, 2, 3, 4]\nsquares = [x ** 2 for x in nums] # importantly, a list comprehension always returns a (modified) list!\nprint(squares)\n```\n\nAlso, list comprehensions may contain if-statements!\n\n\n```python\nstring_nums = ['one', 'two', 'three']\nstarts_with_t = ['yes' if s[0] == 't' else 'no' for s in string_nums]\nprint(starts_with_t)\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (0 points)\n</div>\n\nWrite a list comprehension that adds the string `'_check'` to each value in the list `my_list` below, except if the value is 'B'. (This is an optional ToDo to practice list comprehensions.) Note that (in this particular use of list-comprehensions) you always need *both* a \"if ..\" part *and* an \"else ...\" part! So, can you think of a way to add nothing to a string (i.e., the \"else ...\", when the element is not 'B', part of this list comprehension)?\n\n\n```python\nmy_list = ['A', 'B', 'C', 'D']\n# Implement your list comprehension here!\n\n```\n\nList comprehensions are somewhat of a more advanced Python concept, so if you don't feel comfortable using them (correctly) in your future assignments, use regular for-loops by all means! In the upcoming tutorials, though, we'll definitely use them, so make sure you understand what they do!\n\n## 3. Numpy\nThis section is about Numpy, Python's core library for numeric computing. While the syntax of basic Python (as we've gone over in the previous section) is important to do neuroimaging analysis in Python, knowing numpy is **essential**. Basicially, Numpy is the go-to package whenever you want to do (anything related to) data analysis in Python. Make sure you understand what is going on in this section, as the rest of the course will feature a lot of Numpy-code!\n\nThe most important feature of Numpy is it's core data structure: the numpy *ndarray* (which stands for *n*-dimensional array, referring to the fact that the array may be of any dimension: 1D, 2D, 3D, 180D ... *n*D). This is, just like basic lists/dictionaries/integers/tuples, a data structure with its own syntax, operations, and methods, as we will explain below.\n\n**Note**: even if you're a Numpy pro already, we recommend going through this section anyway as it contains a couple of graded ToDos!\n\n### 3.1. Python lists vs. numpy arrays\nBasically, numpy arrays are a lot like Python lists. The major difference, however, is that **numpy arrays may contain only a single data-type**, while Python lists may contain different data-types within the same list.\n\nLet check this out:\n\n\n```python\n# Python lists may contain mixed data-types: an integer, a float, a string, a list\npython_list = [1, 2.5, \"whatever\", [3, 4, 5]] \n\nfor value in python_list:\n    \n    print(\"%s is a: %s\" % (str(value), type(value)))\n```\n\nUnlike Python lists, numpy only allows entries of the same data-type. This difference between Python lists and numpy arrays is basically the same as R lists (allow multiple data-types) versus R matrices/arrays (only allow one data type), and is also the same as MATLAB cells (allow multiple data-types) versus MATLAB matrices (only allow one data type).\n\nIn fact, if you try to make a numpy array with different data-types, numpy will force the entries into the same data-type (in a smart way), as is shown in the example below:\n\n\n```python\n# Import numpy!\nimport numpy as np\n\n# Importantly, you often specify your arrays as Python lists first, and then convert them to numpy\nto_convert_to_numpy = [1, 2, 3.5]               # specify python list ...\nnumpy_array = np.array(to_convert_to_numpy)     # ... and convert ('cast') it to numpy\n\nfor entry in numpy_array:\n    \n    print(entry)\n    print('this is a: %s \\n' % type(entry))\n```\n\nAs you can see, Numpy converted our original list (to_convert_to_numpy), which contained both integers and floats, to an array with only floats! You might think that such a data structure that only allows one single data type is not ideal. However, the very fact that it only contains a single data-type makes operations on numpy arrays extremely fast. For example, loops over numpy arrays are often way faster than loops over python lists. This is because, internally, Python has to check the data-type of each loop entry before doing something with that entry. Because numpy arrays one allow a single data-type, it only has to check for the entries' data type **once**. If you imagine looping over an array or list of length 100,000, you probably understand that the numpy loop is way faster.\n\nLet's check out the speed difference between Python list operations and numpy array operations:\n\n\n```python\n# %timeit is a cool 'feature' that you can use in Notebooks (no need to understand how it works)\n# it basically performs a computation that you specify a couple of times and prints how long it took on average\nresults_python = %timeit -o [x * 2 for x in range(0, 100000)] \n```\n\nAnd now let's do the same with numpy:\n\n\n```python\nresults_numpy = %timeit -o np.arange(0, 10000) * 2 \n\nratio = results_python.average / results_numpy.average\nprint(\"Numpy is %i times faster than base Python!\" % ratio)\n```\n\nYou see that Numpy *much* faster! This really matters when you start doing more complex operations, on, let's say, multidimensional brain images!\n\n### 3.2. Numpy arrays: creation\nAs shown an earlier example, numpy arrays can be created as follows:\n\n1. Define a Python list (e.g. `my_list = [0, 1, 2]`) \n2. Convert the list to a numpy array (`numpy_array = np.array(my_list)`)\n\nImportantly, a simple Python list will be converted to a 1D numpy array, but a nested Python list will be converted to a 2D (or even higher-dimensional array). Nesting is simply combining different lists, separated by commans, as is shown here:\n\n\n```python\nmy_list = [1, 2, 3]\nmy_array = np.array(my_list)\n\nprint(\"A 1D (or 'flat') array:\")\nprint(my_array, '\\n')\n\nmy_nested_list = [[1, 2, 3],\n                  [4, 5, 6],\n                  [7, 8, 9]]\n\nmy_2D_array = np.array(my_nested_list)\nprint(\"A 2D array:\")\nprint(my_2D_array)\n```\n\nAs you can imagine, creating numpy arrays from nested lists becomes cumbersome if you want to create (large) arrays with more than 2 dimensions. There are, fortunately, a lot of other ways to create ('initialize') large, high-dimensional numpy arrays. One often-used method is to create an array with zeros using the numpy function `np.zeros`. This function takes one (mandatory) argument, which is a tuple with the dimensions of your desired array:\n\n\n```python\nmy_desired_dimensions = (2, 5) # suppose I want to create a matrix with zeros of size 2 by 5\nmy_array = np.zeros(my_desired_dimensions)\n\nprint(my_array)\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\n\nUsing the `np.zeros` function, create a five dimensional array of shape $2 \\times 3 \\times 5 \\times 3 \\times 7$ and store it in a variable named `array_5d`.\n\n\n```python\n# Implement your ToDo here\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo. '''\nfrom nb_tests import test_create_array_with_zeros\n\navailable_vars = dir()\nif 'array_5d' not in available_vars:\n    raise ValueError(\"You didn't define the variable 'array_5d'!\")\n\ntest_create_array_with_zeros(array_5d)\n```\n\nUsing arrays with zeros is often used in what is called 'pre-allocation', in which you create an 'empty' array with only zeros and for example, 'fill' that array in a loop.\n\nBelow, we show you an example in which we pre-allocate an array with 5 zeros, and fill that in a for-loop with the squares of 1 - 5. Try to understand how it works! (You have to do something similar in the next ToDo!)\n\n\n```python\nmy_array = np.zeros(5)\n\nprint('Original zeros-array')\nprint(my_array)\n\nfor i in range(5):  # notice the range function here! This loop now iterates over [0, 1, 2, 3, 4]\n    number_to_calculate_the_square_of = i + 1\n    my_array[i] = number_to_calculate_the_square_of ** 2\n\nprint('\\nFilled array')\nprint(my_array)\n```\n\n**Important**: realize that loops (not shown above), if-statements and other boolean logic is the same for numpy and python!\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (2 points)\n</div>\n\nWrite a loop in which you fill each value in the variable `my_array2` with the value 1 divided by the current index plus one. So, suppose the index (usually `i`, like the last example) is 3, then you should fill `my_array2` at index `i` with `1 / (3 + 1)`.\n\n\n```python\nimport numpy as np\nmy_array2 = np.zeros(8)\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo. '''\nfrom nb_tests import test_fill_array_with_complement\n\navailable_vars = dir()\nif 'my_array2' not in available_vars:\n    raise ValueError(\"The variable my_array2 does not exist!\")\n    \ntest_fill_array_with_complement(my_array2)\n```\n\nIn addition to `np.zeros`, you can create numpy arrays using other functions, like `np.ones` and `random` from the `np.random` module:\n\n\n```python\nones = np.ones((5, 10)) # create an array with ones\nprint(ones, '\\n')\n\nrndom = np.random.random((5, 10)) # Create an array filled with random values (0 - 1 uniform)\nprint(rndom)\n```\n\n### 3.3. Numpy: indexing\nIndexing (extracting a single value of an array) and slicing (extracting multiple values - a subset - from an array) of numpy arrays is largely the same as with regular Python lists and data structures from other scientific computing languages such as R and MATLAB. Let's check out a couple of examples of a 1D array:\n\n\n```python\nmy_array = np.arange(10, 21)  # numpy equivalent of list(range(10, 21))\nprint('Full array:')\nprint(my_array, '\\n') \n\nprint(\"Index the first element:\")\nprint(my_array[0], '\\n')\n\nprint(\"Index the second-to-last element:\")\nprint(my_array[-2], '\\n')\n\nprint(\"Slice from 5 until (not including!) 8\")\nprint(my_array[5:8], '\\n') \n\nprint(\"Slice from beginning until 4\")\nprint(my_array[:4])\n```\n\nSetting values in numpy arrays works the same way as lists:\n\n\n```python\nmy_array = np.arange(10, 21)\nmy_array[0] = 10000\nprint(my_array)\n\nmy_array[5:7] = 0\nprint(my_array)\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\n\nIn the array `my_array` below, set all odd indices (i.e., the first element, the third element, the fifth element, etc.) to the value `0.0` *in a single statement using a slice* (i.e., not a for-loop).\n\n\n```python\n# Implement the ToDo here\nmy_array = np.arange(3, 25)\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo. '''\nfrom nb_tests import test_set_odd_indices_to_zero\ntest_set_odd_indices_to_zero(my_array)\n```\n\n#### Multidimensional indexing\nOften, instead of working on and indexing 1D array, we'll work with multi-dimensional (>1D) arrays. Indexing multi-dimensional arrays is, again, quite similar to other scientific computing languages. \n\nLike indexing Python lists, indexing multidimensional numpy arrays is done with square brackets `[]`, in which you can put as many comma-delimited numbers as there are dimensions in your array. \n\nFor example, suppose you have a 2D array of shape $3 \\times 3$ and you want to index the value in the first row and first column. You would do this as follows:\n\n\n```python\nmy_array = np.zeros((3, 3)) # 3 by 3 array with zeros\nindexed_value = my_array[0, 0]\nprint(\"Value of first row and first column: %.1f\" % indexed_value)\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\n\nUsing multidimensional indexing, set the value in the last row and last column of the 2D array `my_array` to `1.0`. In other words, set the value in the lower-right \"corner\" of the 2D array to 1.0.\n\n\n```python\nimport numpy as np\nmy_array = np.zeros((3, 3))\n\nprint(my_array)\n\n# ToDo: set the value in the lower right corner to 1\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the ToDo above. '''\nfrom nb_tests import test_set_lower_right_value_to_one\ntest_set_lower_right_value_to_one(my_array)\n```\n\nIn addition to setting specific slices to specific values, you can also extract sub-arrays using slicing/indexing. An important construct here is that you can use a single colon `:` to select all values from a particular dimension. For example, if you want to select all column-values (second dimension) from only the first row (first dimension), do this:\n\n```\nsome_2d_arr[0, :]\n```\n\nWe'll show you some examples below:\n\n\n```python\nmy_array = np.array([[1, 2, 3],\n                     [4, 5, 6],\n                     [7, 8, 9]])\n\nprint(my_array, '\\n')\n\nall_column_values_from_first_row = my_array[0, :]\nprint('First row')\nprint(all_column_values_from_first_row, '\\n')\n\nall_row_values_from_first_col = my_array[:, 0]\nprint('First column')\nprint(all_row_values_from_first_col)\n```\n\nSo far, we only talked about 2D arrays, which are relatively easy to 'understand'. In neuroimaging, however, we usually work with 3D, 4D, or even higher-dimensional arrays. These arrays are great for organizing data (like 3D brain scans!), but they are somewhat unintuitive. This takes some time to get used to!\n\nTo get you used to thinking in more than 2 (or 3) dimensions, consider the following scenario. Suppose that a researcher wants to test the efficacy of a particular medicine against high blood pressure. To do so, she/he measures the (average systolic) blood pressure of a group of twenty subjects every hour for 30 days when they're not on the medication. The same subjects are then again measured for another 30 days, but then when they're on medication.\n\nAfter this period of data collection, the researcher has $20\\ (subjects)\\ \\times\\ 24\\ (hours)\\ \\times\\ 30\\ (days)\\ \\times\\ 2\\ (conditions: \\mathrm{off/on}) = 28800$ measurements! We can then organize the data in a 4D array, in which each factor (subjects/hours/days/conditions) represents a separate dimension (also called \"axis\") of our array!\\*\n\n---\n\\* Note that this type of data is perhaps best represented in a \"table-like\" structure, such as a Dataframe in R (or a \"Pandas Dataframe\", the Python-equivalent of R's dataframe). But you can ignore that for this example.\n\nSo, let's generate some random data (from a normal distribution to generate 'realistic' blood pressure data) that could represent this blood pressure dataset:\n\n\n```python\nnp.random.seed(42)  # this is not important for now\nbp_data = np.random.normal(loc=100, scale=5, size=(20, 24, 30, 2))\n```\n\n(Note that we're not printing the `bp_data` variable here, because it's way too much to visualize/interpret at once anyway!)\n\nNow, suppose I would want to extract the blood pressure of subject 5 at 09.00 (AM) in the morning at day 21 when he/she was *not* on medication. In that case, I would do:\n\n\n```python\n# Note that I count midnight as the first measurement\nthis_particular_datapoint = bp_data[4, 8, 20, 0]\nprint(\"Blood pressure of participant 5 at 09.00 (AM) on day 21 in \"\n      \"the no-medication (off) condition is %.3f\" % this_particular_datapoint)\n\n# Also, remember that Python is zero-based, so e.g. participant 5 is indexed by index 4!\n```\n\nTry to remember this: **in multidimensional arrays, each dimension (axis) represents a different \"attribute\" of your data (e.g. subjects, time, condition, etc.)**. This concept will become very important to understand later when we're going to analyze 4D MRI-datasets (with 3 spatial dimensions and 1 time dimension)!\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\n\nConsider the blood-pressure dataset again. In the code-cell below, extract from all participants all data from day 18 in the medication (\"on\") condition. You'll have to use slices with the single `:`! Store the results of your index-operation in the variable `day_18_condition_on`.\n\n\n```python\n# Implement your ToDo here (index the bp_data variable)\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo. '''\nfrom nb_tests import test_bloodpressure_index\n\nif 'day_18_condition_on' not in dir():\n    raise ValueError(\"The variable 'day_18_condition_on' is not defined!\")\n    \ntest_bloodpressure_index(day_18_condition_on)\n```\n\nMultidimensional indexing using slices (especially the single colon `:` slice, i.e., selecting everything) is very common in scientific programming such as neuroimaging analyses. There is, however, yet another way of (multidimensional) indexing called \"boolean indexing\". \n\nIn this type of indexing, you index an array with a boolean array (i.e. array with True and False values) of the same shape. Basically, when you're indexing the array `my_array` with boolean array `bool_array`, you're saying: \"give me all values in `my_array` that are `True` at the same location in `bool_array`!\"\n\nLet's look at an example:\n\n\n```python\nmy_array = np.array([[1, 2, 3],\n                     [4, 5, 6],\n                     [7, 8, 9]])\n\nprint(\"The original array:\\n\")\nprint(my_array, '\\n')\n\nbool_array = np.array([[True, False, True],\n                       [False, True, False],\n                       [True, False, True]])\n\nprint(\"The boolean array:\\n\")\nprint(bool_array, '\\n')\n\nprint('Result of indexing my_array with bool_array:\\n')\nprint(my_array[bool_array])\n```\n\nUsually, you do not write out the boolean array in full (as we did above), but you base it on the data itself to \"filter\" it according to some criterion formalized as a logical statement (i.e., using the boolean operators >, <, ==, or !=). For example, suppose I want to extract only the values above 6 from the `my_array` variable in the above example. \n\nTo do so, I could do the following:\n\n\n```python\nmy_array = np.array([[1, 2, 3],\n                     [4, 5, 6],\n                     [7, 8, 9]])\n\nprint(\"The original array:\\n\")\nprint(my_array, '\\n')\n\nbool_array = my_array > 6\n\nprint(\"The boolean array:\\n\")\nprint(bool_array, '\\n')\n\nprint('Result of indexing my_array with bool_array:\\n')\nprint(my_array[bool_array])\n```\n\nEasy, right? Now try it yourself in the next ToDo!\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\n\nUse a boolean index to extract all values whose square (i.e. $value^2$) is larger than 4 from the array (`my_array`) below. Store the results in a variable with the name `square_is_larger_than_4`.\n\n\n```python\nmy_array = np.array([[0, 1, -1, -2],\n                     [2, -5, 1, 4],\n                     [10, -2, -4, 20]])\n\n# Make a new boolean array below (name it whatever you want) ...\n\n# And use it to index my_array and store it in a variable `square_is_larger_than_4`.\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo '''\nfrom nb_tests import test_boolean_indexing\n\nif 'square_is_larger_than_4' not in dir():\n    raise ValueError(\"Could not find the variable 'square_is_larger_than_4'; did you name it correctly?\")\n\ntest_boolean_indexing(square_is_larger_than_4)\n```\n\nAgain, it's very important to understand how to (effectively) index multidimensional numpy arrays using slices and boolean indexing, as we'll use it a lot in this course!\n\n### 3.4. Numpy: data-types\nEvery numpy array is a grid of values of the same type. Numpy provides a large set of numeric datatypes that you can use to construct arrays. Numpy guesses the datatype when you create an array, but functions that construct arrays usually also include an optional argument to explicitly specify the datatype.\n\nHere are a couple of examples:\n\n\n```python\nx1 = np.array([1, 2])  # Let numpy choose the datatype (here: int)\nx2 = np.array([1.0, 2.0])  # Let numpy choose the datatype (here: float)\nx3 = np.array([1, 2], dtype=np.float64)  # Force a particular datatype (input: int, but converted to 64bit float)\nx4 = np.array([-1, 0, 1, 2], dtype=bool)  # Convert ints to booleans! 0 -> False, everthing else -> True \n\nprint('%r (%s)' % (x1, type(x1[0])))\nprint('%r (%s)' % (x2, type(x2[0])))\nprint('%r (%s)' % (x3, type(x3[0])))\nprint('%r (%s)' % (x4, type(x4[0])))\n```\n\nNote that, after creating the array, you can still change the datatype by using the numpy method `astype()`!\n\n\n```python\nx = np.array([1, 2, 3, 4])\nprint(type(x[0]))\n\n# Now convert it to floasts!\nx = x.astype(float)  # or astype(np.float)\nprint(type(x[0]))\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (0 points)\n</div>\n\nBelow, we've defined a boolean array named `bool_array`. Convert it to an array with integers and store it in a new array calle `bool2int_array`. Check out the values of the new array!\n\n\n```python\nbool_array = np.array([True, True, False, False, True])\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo (not for points) '''\nnp.testing.assert_array_equal(bool2int_array, np.array([1, 1, 0, 0, 1]))\nprint(\"Well done!\")\n```\n\n### 3.5. Numpy: methods vs. functions\nIn the previous section (Basic Python), you've learned that, in addition to functions, 'methods' exist that are like functions of an object. In other words, methods are functions that are applied to the object itself. You've seen examples of list methods, e.g. `my_list.append(1)`, and string methods, e.g. `my_string.replace('a', 'b')`.\n\nLike lists and strings, numpy arrays have a lot of convenient methods that you can call (like the `astype` method we saw earlier). Again, this is just like a function, but then applied to itself. Often, numpy provides both a function and method for simple operations. \n\nLet's look at an example: \n\n\n```python\nmy_array = np.arange(10)  # creates a numpy array from 0 until (excluding!) 10\nprint(my_array, '\\n')\n\nmean_array = np.mean(my_array)\nprint('The mean of the array is: %f' % mean_array, '\\n')\n\nmean_array2 = my_array.mean() \nprint('The mean of the array (computed by its corresponding method) is: %f' % mean_array2, '\\n')\n\nprint('Is the results from the numpy function the same as '\n      'the corresponding method? Answer: %s' % str(mean_array == mean_array2))\n```\n\nIf there is both a function and a method for the operation you want to apply to the array, it really doesn't matter what you choose! Let's look at some more (often used) methods of numpy ndarrays:\n\n\n```python\nmy_array = np.array([[1, 2, 3],\n                     [4, 5, 6],\n                     [7, 8, 9]])\n\nstd_my_array = my_array.std()  # same as np.std(array)\nprint(\"Standard deviation of my_array: %.3f\" % std_my_array, '\\n')\n\ntranspose_my_array = my_array.T  # same as np.transpose(array)\nprint(\"Transpose of my_array:\\n%r\" % transpose_my_array, '\\n')\n\nmin_my_array = my_array.min()  # same as np.min(array)\nprint(\"Minimum of my_array: %i\" % my_array.min(), '\\n')\n\nmax_my_array = my_array.max()  # same as np.max(array)\nprint(\"Maximum of my_array: %i\" % max_my_array, '\\n')\n\nsum_my_array = my_array.sum()  # same as np.sum(array)\nprint(\"Sum of my_array: %i\" % sum_my_array, '\\n')\n```\n\nImportantly, a method may or may not take arguments (input).\nIf no arguments are given, it just looks like \"object.method()\", i.e. two enclosing brackets with nothing in between.\nHowever, a method may take one or more arguments (like the my_list.append(1) method)! \nThis argument may be named or unnamed - doesn't matter. An example:\n\n\n```python\nmy_array2 = np.random.random((3, 3))\nprint('Original array:')\nprint(my_array2, '\\n')\n\nprint('Use the round() method with the argument 3:')\nprint(my_array2.round(3), '\\n')\n\nprint('Use the round() method with the named argument 5:')\nprint(my_array2.round(decimals=5), '\\n')\n```\n\n**Some methods that you'll see a lot in the upcoming tutorials**. In addition to the methods listed above, you'll probably see the following methods a lot in the rest of this course (make sure you understand them!):\n\nReshaping arrays:\n\n\n```python\nmy_array = np.arange(10)\nprint(my_array.reshape((5, 2))) # reshape to desired shape\n```\n\nRavel (\"flatten\") an array:\n\n\n```python\ntemporary = my_array.reshape((5, 2))\nprint(\"Initial shape: %s\" % (temporary.shape,))\nprint(temporary.ravel()) # unroll multi-dimensional array to single 1D array\nprint(\"Shape after ravel(): %s\" % (temporary.ravel().shape,))\n```\n\n\n```python\n# .dot() does matrix multiplication (dot product: https://en.wikipedia.org/wiki/Dot_product)\n# This linear algebra operation is used very often in neuroimaging research \n# (which depends heavily on the General Linear Model!)\narray1 = np.array([0, 1, 2, 3])\narray2 = np.array([4, 5, 6, 7])\n\ndot_product = array1.dot(array2)\nprint(dot_product)\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\n\nLet's practice writing functions some more. Complete the function below, named `calculate_range`. This function takes  a single input-argument - a 1D numpy array - and subsequently calculates the [range](https://en.wikipedia.org/wiki/Range_(statistics)) of the array. The range is the difference between the maximum and minimum of any given array (vector) $x$:\n\n\\begin{align}\nrange(x) = max(x) - min(x)\n\\end{align}\n\nYou may use the corresponding numpy min/max methods or functions in your custom function, doesn't matter. Don't forget to explicitly return the value of the range! \n\nNote: this custom function that implements the *mathematical* formula for a vector's range is completely unrelated to the *Python function* `range` that is often used in for-loops! \n\n\n```python\n# Complete the function below\ndef calculate_range(arr):\n    ''' Calculate the range of an array.\n    \n    Parameters\n    ----------\n    arr : a 1D numpy array\n    \n    Returns\n    -------\n    The range of the input arr\n    '''\n    \n    # YOUR CODE HERE\n    raise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo. '''\n\noutp = calculate_range(np.array([0, 1, 2, 3]))\nif outp is None:\n    raise ValueError(\"Didn't get any output! Did you explicitly return the range?\")\n\nassert(outp == 3)\nassert(calculate_range(np.array([-1, 0, 1, 2])) == 3)\nassert(calculate_range(np.array([0, 0, 0, 0])) == 0)\n\nprint(\"Well done!\")\n```\n\n### 3.6. Numpy: methods vs. attributes?\nAlright, by now, if you see a variable followed by a word ending with enclosed brackets, e.g. `my_array.mean()`, you'll know that it's a method! But sometimes you might see something similar, but **without** the brackets, such as `my_array.size`. This `.size` is called an **attribute** of the variable `my_array`. Like a method, it's an integral part of an object (such as a numpy ndarray). The attribute may be of any data-type, like a string, integer, tuple, an array itself. Let's look at an example:\n\n\n```python\nmy_array = np.array([[1, 2, 3],\n                     [4, 5, 6],\n                     [7, 8, 9]])\n\nprint(my_array, '\\n')\nprint('The size (number of element) in the array is:')\nprint(my_array.size, '\\n')\nprint('The .size attribute is of data-type: %s' % type(my_array.size))\n```\n\nAlright, so by now you might be wondering what the difference between a method and an attribute is. Superficially, you can recognize a method by the form `object.method()` (note the brackets!), like `my_array.round()`; an attribute is virtually the same **but without brackets**, in the form of `object.attribute`, like `my_array.size`. \n\nConceptually, you may think of methods as things that **do** something with the array, while attributes **say** something about the array.\n\nFor example, `my_array.size` **does nothing** with the array - it only **says** something about the array (it gives information about its size), while `my_array.mean()` really **does** something (i.e. calculates the mean of the array). \n\nAgain, you might not use attributes a lot during this course, but you'll definitely see them around in the code of the tutorials. Below, some of the common ndarray attributes are listed:\n\n\n```python\nmy_array = np.array([[1, 2, 3],\n                     [4, 5, 6],\n                     [7, 8, 9]])\n\nprint('Size (number of elements) of array:')\nprint(my_array.size, '\\n') # returns an integer\n\nprint('Shape of array:')\nprint(my_array.shape, '\\n') # this is a tuple!\n\nprint('Number of dimensions:')\nprint(my_array.ndim) # this is an integer\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (2 points)\n</div>\n\nLet's try another one. Complete the function below, named `compute_one_sample_ttest`. This function takes two input arguments:\n\n- arr : a 1D numpy array\n- h0 : a scalar value (single number) that represents the value representing the null-hypothesis\n\nThe function should compute the one-sample t-test, which tests whether the mean of an array is significantly different from a given value representing the null-hypothesis. Formally, for any given array $x$ and null-hypothesis $h_{0}$:\n\n\\begin{align}\nt = \\frac{\\bar{x} - h_{0}}{s\\ / \\sqrt{N}}\n\\end{align}\n\nHere: $\\bar{x}$ represents the mean of $x$, $s$ represents the standard deviation of $x$, and $N$ represents the length ('size') of x. So, in slightly less mathematical notation:\n\n\\begin{align}\nt = \\frac{mean(x) - h_{0}}{std(x)\\ / \\sqrt{length(x)}}\n\\end{align}\n\nMake sure to return the t-value! \n\n**Hint 1**: to compute $N$, you can use the `.size` attribute of an array ... <br>\n**Hint 2**: use the function `np.sqrt(some_number)` to calculate the square root ...\n\n\n```python\n# Complete the function below!\ndef compute_one_sample_ttest(arr, h0):\n    ''' Computes the one-sample t-test for any array and h0. \n    \n    Parameters\n    ----------\n    arr : a 1D numpy array\n    h0 : an int or float\n    \n    Returns\n    -------\n    A single value representing the t-value\n    '''\n    \n    # YOUR CODE HERE\n    raise NotImplementedError()\n```\n\n\n```python\n''' Tests the ToDo above. '''\nfrom nb_tests import test_tvalue_computation\n\narr = np.random.randn(100)\noutp = compute_one_sample_ttest(arr , 0)\n\nif outp is None:\n    raise ValueError(\"Your function didn't return anything! Did you forget the return statement?\")\n\ntest_tvalue_computation(arr, 0, outp)\n\noutp = compute_one_sample_ttest(arr, 5) \ntest_tvalue_computation(arr, 5, outp)\n\noutp = compute_one_sample_ttest(arr, -3) \ntest_tvalue_computation(arr, -3, outp)\n```\n\n### 3.7. Numpy: array math\nNow you know all the numpy basics necessary to do neuroimaging analysis! As you'll see in the last section (Working with nifti-images), we'll work with 3D (structural MRI images) or 4D (functional MRI images) numpy arrays a lot. Given that you know how the basics about numpy in general and numpy ndarrays in particular, we can utilize some of numpy's best features: (very fast) array math.\n\nBasic mathematical functions operate elementwise on arrays, which means that the operation (e.g. addition) is applied onto each element in the array.\n\nSo, let's initialize a 1D array with ten zeros and let's add 1 to it:\n\n\n```python\nx = np.zeros(10)\nprint(x, '\\n')\nx += 1 # remember: this the same as x = x + 1\nprint(x)\n```\n\nAdditionally, you can also sum two arrays together in an elementwise manner by simply writing: `array_1 + array_2`, given that these two (or more) arrays are of the same shape! Let's look at an example:\n\n\n```python\nx = np.array([[1,2],[3,4]], dtype=np.float64)\ny = np.array([[5,6],[7,8]], dtype=np.float64)\n\nprint(\"x: \\n%r\" % x, '\\n')\nprint(\"y: \\n%r\" % y, '\\n')\nprint(\"x+y: \\n%r\" % (x + y), '\\n')\n```\n\nOften, there exist function-equivalents of the mathematical operators. For example, `x + y` is the same as `np.add(x, y)`. However, it is recommended to use the operators wherever possible to improve readability of your code. See below for an example:\n\n\n```python\nprint(x + y, '\\n')\nprint(np.add(x, y))\n```\n\nNext to addition, we can also do elementwise subtraction, multiplication, divison, square root, and exponentiation:\n\n\n```python\n# Elementwise difference; both produce the array\nprint(x - y, '\\n')\nprint(np.subtract(x, y))  # function-equivalent of above \n```\n\n\n```python\n# Elementwise product; both produce the array\nprint(x * y, '\\n')\nprint(np.multiply(x, y))\n```\n\n\n```python\n# Elementwise division; both produce the array\n# [[ 0.2         0.33333333]\n#  [ 0.42857143  0.5       ]]\nprint(x / y, '\\n')\nprint(np.divide(x, y))\n```\n\n\n```python\n# Elementwise square root; there is no operator-equivalent!\nprint(np.sqrt(x))\n```\n\n\n```python\n# Elementwise exponentiation\nprint(x ** y, '\\n')\nprint(np.power(x, y))\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\n\nDo an elementwise product between the two variables defined below (`arr_A` and `arr_B`) and subsequently add 5 to each element; store the result in a new variable called `result_product_and_sum`.\n\n\n```python\n# Implement the ToDo!\narr_A = np.arange(10).reshape((5, 2))\narr_B = np.arange(10, 20).reshape((5, 2))\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo. '''\nfrom nb_tests import test_array_product_and_sum\n\nif 'result_product_and_sum' not in dir():\n    raise ValueError(\"The variable 'result_product_and_sum' does not seem to exist!\")\n\ntest_array_product_and_sum(result_product_and_sum)    \n```\n\nNote that unlike MATLAB, `*` is elementwise multiplication, not matrix multiplication. We instead use the dot function (or method!) to  compute matrix operations like inner products of vectors, multiplication of a vector by a matrix, and multiplication of two matrices.\n\nThese matrix operations are quite important in this course, because they are used a lot in neuroimaging methods (such as the General Linear Model, the topic of next week!). You're not expected to fully understand these matrix operations, but you'll see them several times in this course, so make sure you're familiar with its implementation in Python/Numpy.\n\nAn example of the inner product (\"dot product\") of two vectors in both the function-format and the method-format:\n\n\n```python\nv = np.array([9,10])\nw = np.array([11, 12])\n\n# Inner product of vectors; both produce 219\nprint(v.dot(w))\nprint(np.dot(v, w))\n```\n\nAdditionally, in Python3.6 (and above), you can use the `@` character as an operator for matrix multiplication of numpy arrays!\n\n\n```python\nprint(v @ w)\n```\n\nProbably the most used functions in numpy are the sum() and mean() fuctions (or equivalent methods!). A nice feature is that they can operate on the entire array (this is the default) or they can be applied per dimension (or, in numpy lingo, per \"axis\").\n\nApplying functions along axes is very common in scientific computing! Let's look at an example in which we apply the `sum` function/method across rows and columns:\n\n\n```python\nx = np.array([[1, 2],[3, 4], [5, 6]])\n\nprint('Original array:')\nprint(x, '\\n')\n\nprint('Sum over ALL elements of x:')\nprint(np.sum(x), '\\n')\n\nprint('Sum across rows of x:')\nprint(np.sum(x, axis=0), '\\n')\n\nprint('Sum across columns of x:')\nprint(x.sum(axis=1)) # this is the method form! Is exactly the same as np.sum(x, axis=1) \n```\n\nImportantly, application of functions across axes is much quicker (and more concise) than writing for-loops! Let's look at the speed difference between a for-loop (implemented as a list comprehension) and the numpy-style application of the `sum` function across axes:\n\n\n```python\narr = np.random.random((1000, 100))\nloop_style = %timeit -o [arr[i, :].sum() for i in range(arr.shape[0])]\naxis_style = %timeit -o arr.sum(axis=1)\nprint(\"Using the axis-argument is %.3f times faster than a for-loop!\" % (loop_style.average / axis_style.average))\n```\n\nThis application of functions on entire arrays (in an elementwise manner, like `arr_1 + arr_2`) and application of functions across a certain axis (like `np.sum(arr_1, axis=1)`) is often called **vectorization**. This is an incredibly useful concept and something we'll use a lot in this course! Make sure you understand this. \n\nLet's practice this a bit.\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\n\nRemember the \"range\" function from before? Below, we started writing a function, called `calculate_range_vectorized`, that calculates, for any 2D array, the range of each column (i.e. calculates range **across rows** for each column) in a *vectorized manner* (so without any for loops!).\n\nComplete the function, and make sure to return the result, which should be a 1D vector which values represents the ranges for all columns. So, if the input array would be of shape `(100, 10)`, then the shape of your returned array should be `(10,)`.\n\n\n```python\ndef compute_range_vectorized(arr):\n    ''' Compute the range across rows for each column in a 2D array. \n    \n    Parameters\n    ----------\n    arr : a 2D numpy array\n    \n    Returns\n    -------\n    A 1D vector with the ranges for each column\n    '''\n    \n    # YOUR CODE HERE\n    raise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo '''\nfrom nb_tests import test_compute_range_vectorized\n\nnp.random.seed(42)\ntest_arr = np.random.random((100, 10))\noutp = compute_range_vectorized(test_arr)\n\nif outp is None:\n    raise ValueError(\"Output is None! Did you forget the Return statement in your function?\")\n\ntest_compute_range_vectorized(test_arr, outp)\n```\n\n### 3.8. Broadcasting\nBroadcasting is a powerful mechanism that allows numpy to work with arrays of different shapes when performing arithmetic operations. Frequently we have a smaller array and a larger array, and we want to use the smaller array multiple times to perform some operation on the larger array.\n\nFor example, suppose that we want to add a vector to each row of a matrix. We could do it like this:\n\n\n```python\n# We will add the vector v to each row of the matrix x,\n# storing the result in the matrix y\nx = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\n\nprint('x array is of shape: %r' % (x.shape,))\nprint(x, '\\n')\n\nv = np.array([1, 0, 1])\nprint('v vector is of shape: %r (different shape than x!)' % (v.shape,))\nprint(v, '\\n')\n\ny = np.zeros(x.shape)   # Create an empty (zeros) matrix with the same shape as x\nprint('Shape of (pre-allocated) y-matrix: %r' % (y.shape,))\n\n# Add the vector v to each row of the matrix x with an explicit loop\nfor i in range(x.shape[0]): # see how the shape attributes comes in handy in creating loops?\n    y[i, :] = x[i, :] + v\n\nprint('The result of adding v to each row of x, as stored in y:')\nprint(y)\n```\n\nThis works; however when the matrix `x` is very large, computing an explicit for-loop in Python could be slow. Note that adding the vector v to each row of the matrix `x` is equivalent to forming a matrix `vv` by stacking multiple copies of `v` vertically, like this `[[1 0 1], [1 0 1], [1 0 1], [1 0 1]]`, and subsequently elementwise addition of `x + vv`:\n\n\n```python\nvv = np.tile(v, (4, 1)) # i.e. expand vector 'v' 4 times along the row dimension (similar to MATLAB's repmat function)\ny = x + vv  # Add x and vv elementwise\nprint(y)\n```\n\nNumpy **broadcasting** allows us to perform this computation without actually creating multiple copies of v. Consider this version, using broadcasting:\n\n\n```python\n# We will add the vector v to each row of the matrix x,\n# storing the result in the matrix y\nx = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\nv = np.array([1, 0, 1])\ny = x + v  # Add v to each row of x using broadcasting\nprint(y)\n```\n\nThe line `y = x + v` works even though `x` has shape `(4, 3)` and `v` has shape `(3,)` due to broadcasting; this line works as if v actually had shape `(4, 3)`, where each row was a copy of `v`, and the sum was performed elementwise.\n\nThis broadcasting function is really useful, as it prevents us from writing unnessary and by definition slower explicit for-loops. Additionally, it's way easier to read and write than explicit for-loops (which need pre-allocation). Functions that support broadcasting are known as universal functions. You can find the list of all universal functions in the [documentation](http://docs.scipy.org/doc/numpy/reference/ufuncs.html#available-ufuncs).\n\nHere are some applications of broadcasting using different functions:\n\n\n```python\nx = np.array([[1, 2],[3, 4], [5, 6]], dtype=np.float)\nx_sum = x.sum(axis=0)\n\nprint(x / x_sum, '\\n')\n\nx_mean = x.mean(axis=0)\nprint(x / x_mean)\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (2 points)\n</div>\n\nBelow, we started writing a function called `standardize_columns`, which takes a single input-argument - a 2D numpy array - and should subsequently *standardize* each column such that each column has a mean of zero and a standard deviation of 1. In other words, standardization subtracts the mean (across rows) of each column from the values in that column, and then divides those value with the standard deviation of that column. Formally, for each column $j$ in any 2D array, standardization entails:\n\n\\begin{align}\nx_{j}\\ standardized = \\frac{(x_{j} - \\bar{x_{j}})}{std(x_{j})}\n\\end{align}\n\nStandardization, which is also oftend called \"z-transformation\", is often done in statistics. We'll also see this next week.\n\nSo, in the function below, make sure that it is able to standardize each column in any 2D array. Make sure to use vectorized array computations (i.e, the `np.mean` and `np.std` functions/methods across rows) and broadcasting, so no for-loops! \n\n\n```python\ndef standardize_columns(arr):\n    ''' Standardize each column of a 2D input-array. \n    \n    Parameters\n    ----------\n    arr : a 2D numpy array\n    \n    Returns\n    -------\n    The input-array with standardized columns (should have the same shape as the input-array!)\n    '''\n    \n    # YOUR CODE HERE\n    raise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo. '''\n\ntest_arr = np.random.normal(5, 2, size=(100, 10))\noutp = standardize_columns(test_arr)\n\nif outp is None:\n    raise ValueError(\"The output from your function is None; did you forget the Return statement?\")\n\ntry:\n    np.testing.assert_array_almost_equal(outp.mean(axis=0), np.zeros(test_arr.shape[1]))\nexcept AssertionError as e:\n    print(\"The mean of the columns of your standardized array are not 0!\")\n    raise(e)\n\ntry:\n    np.testing.assert_array_almost_equal(outp.std(axis=0), np.ones(test_arr.shape[1]))\nexcept AssertionError as e:\n    print(\"The std of the columns of your standardized array are not 1!\")\n    raise(e)\n    \nprint(\"Well done!\")\n```\n\nNow, you know the most important numpy concepts and functionality that is necessary to do neuroimaging analysis. Surely, there is a lot more to the numpy package that what we've covered here! But for now, let's continue with plotting using Matplotlib!\n\n## 4. Matplotlib\nMatplotlib is Python's main plotting library. In this section give a brief introduction to the `matplotlib.pyplot` module, which provides a plotting system similar to that of MATLAB.\n\n\n```python\nimport matplotlib.pyplot as plt # this is how matplotlib.pyplot is usually imported\nimport numpy as np\n```\n\nBy running this special notebook command, we will be displaying plots inline (instead of in a new window; this is only relevant in Jupyter notebooks!):\n\n\n```python\n%matplotlib inline\n```\n\n### 4.1. Basic plotting\nThe most important function in `matplotlib` is **`plot`**, which allows you to plot 1 dimensional data. Here is a simple example:\n\n\n```python\n# Draw a line with coordinates from vectors x and y\nx = np.arange(0, 11)  # 0 - 10\ny = np.arange(0, 11)  # 0 - 10, same as x\n\n# Plot the points using matplotlib\nplt.plot(x, y)\nplt.show()\n```\n\nWith just a little bit of extra work we can easily plot multiple lines at once, and add a title, legend, and axis labels:\n\n\n```python\ny2 = np.ones(x.size)  # vector of ones, i.e., straight line\n\n# Plot the points using matplotlib\nplt.plot(x, y)\nplt.plot(x, y2)\nplt.xlabel('x axis label')\nplt.ylabel('y axis label')\nplt.title('Two lines')\nplt.legend(['Linear increasing line', 'Constant line'])\nplt.show()\n```\n\n### 4.2. Subplots \nYou can plot different subplots in a single figure using the subplot function. Here is an example:\n\n\n```python\n# Compute the x and y coordinates for points on sine and cosine curves\nx = np.arange(0, 3 * np.pi, 0.1)\ny_sin = np.sin(x)\ny_cos = np.cos(x)\n\n# Set up a subplot grid that has 2 'rows' and 1 'column',\n# and set the first such subplot as active.\nplt.subplot(2, 1, 1)  # the third argument here sets the 'active' plot\n\n# Make the first plot\nplt.plot(x, y_sin)\nplt.title('Sine')\n\n# Set the second subplot as active, and make the second plot.\nplt.subplot(2, 1, 2)\nplt.plot(x, y_cos)\nplt.title('Cosine')\n\n# Show the figure.\nplt.tight_layout() # this prevents plots from overlapping\nplt.show()\n```\n\nAnd we can add text to plots as such:\n\n\n```python\nx = np.arange(-1, 1, 0.01) # array from -1 to 1 in steps of 0.01\n\n# Set up a subplot grid that has 2 'rows' and 1 'column',\n# and set the first such subplot as active.\nplt.subplot(2, 1, 1)\nplt.plot(x, x ** 2)\nplt.title('x squared')\nplt.text(-0.5, 0.4, r\"$y=x^2$\", fontsize=20, color=\"blue\")\n\n# Set the second subplot as active, and make the second plot.\nplt.subplot(2, 1, 2)\nplt.plot(x, x ** 3)\nplt.title('x cubed')\nplt.text(-0.5, 0.4, r\"$y=x^3$\", fontsize=20, color=\"green\")\n\nplt.tight_layout()\nplt.show()\n```\n\nYou can read much more about the `subplot` function in the [documentation](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplot).\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\n\nBelow, we initialized a 2D array of shape `(10, 100)` named `arr_2D`. In a figure with two subplots (across two columns), plot in the left subplot the mean across columns (i.e., 10 values) and in the right subplot plot the standard deviation across columns (also 10 values). **Hint**: these values represent the values on the `y-axis`. You can use `x = np.arange(10)` for the `x-axis`.\n\nAlso, give the subplots labels for the x- and y-axis, and give it a title.\n\nNote: this ToDo is manually graded, so there is no test-cell!\n\n\n```python\narr_2D = np.random.normal(0, 1, size=(10, 100))\n\n# Make your plot below!\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n### 4.3. Histograms\nNow let's generate some random data using the np.random functionality, and get some histograms of their distributions\n\n\n```python\nrand_uniform = np.random.uniform(size = (1000)) # uniform distribution\nrand_normal = np.random.normal(size = (1000))   # normal distribution\nrand_exponential = np.random.exponential(size = (1000)) # exponential distribution\n```\n\n\n```python\n# Set up a subplot grid that has rows=2 and columns=3,\n# and set the first such subplot as active.\nplt.subplot(1, 3, 1)\n\n# Make the first plot\nplt.hist(rand_uniform, color='g')\nplt.title('uniform')\n\n# Set the second subplot as active, and make the second plot.\nplt.subplot(1, 3, 2)\nplt.hist(rand_normal, color='b')\n\nplt.title('normal')\n\n# Set the second subplot as active, and make the second plot.\nplt.subplot(1, 3, 3)\nplt.hist(rand_exponential, color='r')\nplt.title('exponential')\n\nplt.tight_layout()\nplt.show()\n```\n\n### 4.4. Images\nSo far, we've been plotting lines. Matplotlib also has easy functionality for plotting two-dimensional data-arrays, such as pictures. This is done using the command `plt.imshow()`. We'll use this feature a lot, because it allows us to visualize 2D slices of MRI-data as well! (Remember, MRI data is essentially just a 3D \"picture\" of the brain.) \n\n\n```python\n# the scipy module includes some pictures, so we can use those:\nfrom scipy import misc\nbw_photo = misc.face(gray=True)\n\n# now we can use the imshow command to plot 2d data:\nplt.imshow(bw_photo,cmap='gray')\nplt.show()\n```\n\nImportanty, photos are just 2D arrays with numbers representing the luminance (in black-and-white pictures) of each pixel. You can see this by printing the loaded image:\n\n\n```python\nprint(\"Shape of photo object: %r\" % (bw_photo.shape,), '\\n')\nprint(bw_photo)\n```\n\nYou can see that it's actually just a bunch of numbers (one number per pixel), and when we plot colorbar with the original picture, we see that high numbers convert to bright shades, and low numbers convert to dark shades. \n\n\n```python\nplt.imshow(bw_photo,cmap='gray')\nplt.colorbar()\nplt.show()\n```\n\nUsing the knowledge that black and white images are nothing more than just 2d-arrays of values, we can also generate our own images:\n\n\n```python\nrand_img = np.random.random((200,200)) # Create an array filled with random values\nprint(rand_img, '\\n')\nplt.imshow(rand_img, cmap='gray')\nplt.colorbar()\nplt.show()\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (0 points, no test-cell)\n</div>\n\nBelow, we loaded in a 2D array of shape (91, 108) named `mystery_data`. Visualize it using `plt.imshow()` (using the argument `cmap='gray'`) to check out what the data entails!\n\n\n```python\nmystery_data = np.load('mystery_data.npy')\n# Visualize it using plt.imshow!\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\nNow that you know some basics of data types, arrays and plotting, it's time to get to work with some fMRI data!\n\n## 5. Neuroimaging analysis with Python\nBefore we'll actually analyze data, we need to talk about the format that most (f)MRI data is stored in: \"nifti\" files.\n\n### 5.1. What is \"nifti\"?\nUsually, every scanner manufacturer (Philips, Siemens, GE, etc.) have their own proprietary data format. For example, here at the UvA, we have a Philips scanner and we often export our data as PAR/REC files. However, to streamline the development and use of neuroimaging software packages, the Neuroimaging InFormatics Technology Initiative came up with a new, standardized format, *nifti*, that most neuroimaging packages should support. As such, usually the first step in any (f)MRI preprocessing pipeline is to convert the scanner-specific files (e.g., PAR/RECs) to nifti. This is beyond the scope of this course, but if at one point you need to do this yourself, we highly recommed the [dcm2niix](https://github.com/rordenlab/dcm2niix) package!\n\nThroughout these tutorials you'll work with these nifti-files (also called nifti images), which you can recognize by their extension of *.nii* or its compressed version *.nii.gz*. This file-format is supported by most neuroimaging software packages (such as FSL, which you'll use later in this course!). \n\nHowever, we'd like to inspect and analyze nifti images in Python as well! **Nibabel** is an awesome Python package that allows us to read and load nifti images, and convert them to numpy arrays in a straightforward manner.\n\n\n```python\n# If you haven't done so already, load some other packages we need\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport nibabel as nib # common way of importing nibabel\n```\n\nWe'll load in an example anatomical MRI scan (`anat.nii.gz`) from the current directory using nibabel below:\n\n\n```python\nmri_file = 'anat.nii.gz'\nimg = nib.load(mri_file)\n```\n\nNote the type of `img`: the `Nifti1Image` class. This is a custom class just like a Numpy array, with its own attributes and methods!\n\n\n```python\nprint(type(img))\n```\n\nFor example, one attribute of `Nifti1Image` objects is the `shape` (which is similar to the numpy array attribute with the same name):\n\n\n```python\nprint(img.shape)\n```\n\nHere, the `shape` attribute is telling us that this is a 3D (anatomical) scan and has 240 voxels in the first dimension, 240 voxels in the second dimension, and 220 voxels in the third dimension.\n\n### 5.2. The three parts of nifti images\nNifti images can be roughly divided into three \"parts\":\n1. The header with metadata;\n2. The image data;\n3. The affine matrix\n\nAll three parts are of course represented in nibabel's `Nifti1Image` class. Let's go through them one by one.\n\n#### 5.2.1. The header\nThe header of nifti files contain metadata about the scan, such as the units of measurement, the voxel size, etc. In `Nifti1Images`, the header is an attribute:\n\n\n```python\n# here, we're storing the header attribute in a new variable, hdr, for easy of use\nhdr = img.header\n```\n\nPerhaps confusingly, the header is a custom object (a `Nifti1Header` object) as well, with its own methods and attributes. For example, it has a method called `get_zooms()`, which returns the voxel size (and optionally the sampling rate, if it's a fMRI file):\n\n\n```python\nhdr.get_zooms()  # it's a 1x1x1 mm MRI file!\n```\n\nAnother useful method is the `get_xyzt_units` which returns the units of the measurements (here: voxel size in millimeter and time in seconds):\n\n\n```python\nhdr.get_xyzt_units()\n```\n\nLet's also load in a functional MRI file (`func.nii.gz`) to see the difference with an anatomical MRI file:\n\n\n```python\nfmri_file = 'func.nii.gz'\nf_img = nib.load(fmri_file)\nprint(f_img.shape)\nprint(f_img.header.get_zooms())\nprint(f_img.header.get_xyzt_units())\n```\n\nIn case of fMRI files, the fourth dimension (almost) always represents the \"time\" dimension. So you can assume that a nifti image of an fMRI file has 4 dimensions, with the first three being the spatial dimensions (similar to the anatomical MRI file: $X \\times Y \\times Z$) and the last (fourth) being the time dimension ($T$).\n\nSo for the above file, you can assume that it has 50 timepoints and has a sampling rate of 0.7 seconds (i.e., a new volume was scanned every 0.7 seconds).\n\nMoreover, you can infer that this file contains data from $80 \\times 80 \\times 44$ voxels with dimensions $2.7 \\times 2.7 \\times 2.97$ (in millimeters). To be honest, in practice, you won't deal a lot with the header (as you are generally aware of the dimensions/units of your data), so let's look at the *actual* data!\n\n#### 5.2.2. The data\nWhen we loaded in the data and created a `Nifti1Image` object, we actually didn't load in the *actual* data (i.e., voxel intensities) in memory yet! This is postponed because it's quite a memory-intensive operation: remember, loading in an fMRI scan with dimensions $80 \\times 80 \\times 44 \\times 50$ is effectively loading in over 14 million numbers (which is, in this case, more than 50MB in size)! By postponing loading the data, you can, for example, peek at the image dimensions without loading all the data in memory.\n\nAnyway, to actually load in the data, you can call the `get_data()` method, which will return a numpy array with the same dimensions as the image data. We'll take a look at the anatomical MRI data (`anat.nii.gz`):\n\n\n```python\nimg_data = img.get_data()\nprint(type(img_data))  # it's a numpy array!\nprint(img_data.shape)\n```\n\nOkay, so `img_data` is a 3D numpy array with ... what exactly? Let's check it out:\n\n\n```python\nprint(img_data)\n```\n\nIt's just a bunch of numbers! This is important to remember: **like any image (like your standard png, jpeg, or gif), MRI scans are also just (3D or 4D) arrays of numbers**! The higher the number, the more signal the scanner recorded at that voxel. (It's actually a little more complex than this, but that's beyond the scope of this course!) \n\nOften, the absolute value of the signal intensities is not necessarily most or only important thing. The *relative differences* between different voxels in space or within voxels across time is also important. For example, for anatomical scans, apart from a high overall signal intensity, you often want a good *contrast* between white and gray matter (i.e., different signal intensities between voxels in these two tissue types). For functional MRI, apart from a clear tissue contrast and a high overall signal intensity, you often also want little (non-experimentally related) differences in signal intensity within a voxel across time.\n\nAnyway, when we printed this 3D array (of $240 \\times 240 \\times 220$), the notebook chose not to display all 12,672,000 numbers but instead truncated it. The reason it only printed zeros is because the first and last couple of numbers in each dimension likely doesn't contain any (signal related to) brain, just empty space!\n\nSo, let's index a small $3 \\times 3 \\times 3$ patch of voxels in the middle of the brain to check what values these voxels contain:\n\n\n```python\nmid_vox = img_data[118:121, 118:121, 108:111]\nprint(mid_vox)\n```\n\nThat's better! The exact values are not necessarily directly interpretable, i.e., you cannot say that the value 61978.46 is good (or bad), because the exact *scale* of the signal intensities (whether it goes from 0-100 or from 0-100,000) depends on the specific scanner hardware and specific nifti conversion software.\n\nLike any image, (f)MRI scans can be visualized by plotting the numbers and assigning colors to the numbers. Often we visualize brain images in brain and white, with higher signal intensities being brighter and lower signal intensities being darker. Importantly, remember that our data here cannot directly be plotted as a (2D) image, because our data (an anatomical scan) is 3D! However, we *can* just plot a single *slice* of the 3D volume, for example, the middle slice of our first voxel axis:\n\n\n```python\nmid_slice_x = img_data[119, :, :]\nprint(mid_slice_x.shape)\n```\n\nWe can use matplotlib to plot this slice as an image using the `imshow` function you're seen before:\n\n\n```python\n# Note that the transpose the slice (using the .T attribute).\n# This is because imshow plots the first dimension on the y-axis and the\n# second on the x-axis, but we'd like to plot the first on the x-axis and the\n# second on the y-axis. Also, the origin to \"lower\", as the data was saved in\n# \"cartesian\" coordinates.\nplt.imshow(mid_slice_x.T, cmap='gray', origin='lower')\nplt.xlabel('First axis')\nplt.ylabel('Second axis')\nplt.colorbar(label='Signal intensity')\nplt.show()\n```\n\nAlright, time to practice.\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\n\nRemember numpy indexing? For this ToDo, extract the second entry from the *last* dimension of `img_data` and store it in a new variable called `second_slice`. Tip: this variable should have a shape of $240 \\times 240$!\n\n\n```python\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo '''\nfrom nb_tests import test_extract_second_slice\ntest_extract_second_slice(img_data, second_slice)\n```\n\nSo far, we have only looked at *structural* (3D) MRI data. This course is mainly about analyzing *functional* data, so let's look at the data from an fMRI scan. We'll use the `Nifti1Image` object `func_img` from before. We'll load the memory with the `get_data` method. Note that this takes a little longer than loading in the structural data, because instead of ($240 \\times 240 \\times 220 = $) 12,672,000 datapoints, we're loading in ($80 \\times 80 \\times 44 \\times 347 =$) 97,715,200 datapoints!\n\n\n```python\nf_img_data = f_img.get_data()\nprint(f_img_data.shape)\n```\n\nNow, you can think about this 4D array as a series of 3D arrays (volumes), in which the fourth dimension represents time (as shown in the image below).\n<br><br>\n\n(Source: [nilearn website](https://nilearn.github.io/_images/niimgs1.jpg))\n\nThese separate 3D arrays (from the first three dimensions) in fMRI files are often called \"volumes\" or \"dynamics\". So, for example, the first volume refers to the first 3D array that was recorded.\n\nJust like the anatomical MRI data, the values in the fMRI data just represent numbers:\n\n\n```python\n# printing a small 3x3x3 volume of voxels from the first timepoint\nprint(f_img_data[38:41, 38:41, 20:23, 0])\n```\n\nAgain, we can visualize these numbers as images, at least for the first three dimensions, as these represent the spatial dimensions (the fourth dimension represents time). For example, we can visualize a single slice (e.g., $x = 39$) of the first volume ($t = 0$) as follows:\n\n\n```python\nmid_slice_x_fmri = f_img_data[39, :, :, 0]  # x = 39, t = 0\nprint(\"Shape of slice: %s\" % (mid_slice_x_fmri.shape,))\n\nplt.imshow(mid_slice_x_fmri.T, cmap='gray', origin='lower')\nplt.xlabel('First axis')\nplt.ylabel('Second axis')\nplt.colorbar(label='Signal intensity')\nplt.show()\n```\n\nHowever, we can also look at fMRI data from a different perspective, that is, from the time dimension! For example, we could extract a single voxel's *time series* (i.e., how the signal intensity varies across time) and plot the signal intensity values of that voxel across time. First, let's extract the time series of one particular voxel (e.g., the middle one across all spatial dimensions):\n\n\n```python\nmid_vox_ts = f_img_data[39, 39, 21, :]  # note the \":\", saying: give me ALL the timepoints\nprint(\"Voxel timeseries shape: %s\" % (mid_vox_ts.shape,))\n```\n\nWhat we effectively did in the previous cell is to extract the signal intensity at the *same* spatial coordinates ($x=39, y=39, z=21$) across all 347 timepoints. We show this visually in the next cell, where the show the coordinates as a red box across 20 timepoints (not all 347, because that would clutter the notebook too much):\n\n\n```python\nfrom matplotlib import patches\n\nfig, axes = plt.subplots(ncols=5, nrows=4, figsize=(20, 10))  # 20 timepoints\n# Loop over the first 20 volumes/timepoints\nfor t, ax in enumerate(axes.flatten()):    \n    ax.imshow(f_img_data[39, :, :, t].T, cmap='gray', origin='lower')  # index with t!\n    rect = patches.Rectangle((38, 20), 2, 2, linewidth=2, edgecolor='r', facecolor='none')\n    ax.add_patch(rect)\n    ax.axis('off')\n    ax.set_title('t = %i' % t, fontsize=20)\nfig.tight_layout()\n```\n\nNote that it is *really* hard to spot whether the image of the slice is actually different between different time points! To the naked eye, it just seems like the same image. This is because activity fluctations (over time) in fMRI are **very** small - most of the time just 1-3% compared to baseline (average) activity. That's why it's hard to spot activity differences by looking at the pictures alone (without any scaling).\n\nIt's actually easier to see these time-by-time fluctuations in signal intensity by plotting the time series directly:\n\n\n```python\nplt.figure(figsize=(18, 3))\nplt.plot(mid_vox_ts, 'o-', ms=4)\nplt.xlim(-1, mid_vox_ts.size)\nplt.ylim(38000, 55000)\nplt.ylabel('Signal intensity', fontsize=15)\nplt.xlabel('Time (nr. of volumes)', fontsize=15)\nplt.show()\n```\n\nIn the plot above, the blue dots are the signal intensity values (y-axis), plotted across time (x-axis). The blue lines interconnecting the blue dots are just interpolated values in between the different datapoints (the dots) and serve mostly for visualization purposes (it just looks prettier).\n\nTime for a ToDo!\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\n\nFrom the the variable `f_img_data`, extract the *odd* timepoints (i.e., 1, 3, 5, etc.) of this 4D nummpy and store it in a new variable called `f_img_data_odd`. This should be of shape $80 \\times 80 \\times 44 \\times 25$.\n\n\n```python\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo. '''\nfrom nb_tests import test_extract_voxel_timeseries\nif 'f_img_data_odd' not in dir():\n    raise ValueError(\"Could not find any variable named 'f_img_odd'; did you spell it correctly?\")\n\ntest_extract_voxel_timeseries(f_img_data, f_img_data_odd)\n```\n\n#### 5.2.3. The affine\nEach nifti file contains, in addition to the (meta)data, als an *affine* matrix, which relates the position of the image coordinates to real word coordinates. This may sound vague (it definitely did to us at first!), so let's sketch a scenario in which the image's affine becomes important.\n\nSuppose you were given a nifti file by a colleague (we'll pretend that the `img` variable represents this mysterious nifti file). You have no idea whether it's even a brain scan, so you decide to plot three slices - one from each of the three axes. You pick slice 70 (index 69, because Python is zero-based; first axis), 100 (second axis), and again 100 (third axis).\n\n\n```python\nfig, ax = plt.subplots(ncols=3, figsize=(15, 5))\n\nax[0].imshow(img_data[69, :, :].T, origin='lower', cmap='gray')\nax[0].set_xlabel('Second dim voxel coords.', fontsize=12)\nax[0].set_ylabel('Third dim voxel coords', fontsize=12)\nax[0].set_title('First dimension, slice nr. 70', fontsize=15)\n\nax[1].imshow(img_data[:, 99, :].T, origin='lower', cmap='gray')\nax[1].set_xlabel('First dim voxel coords.', fontsize=12)\nax[1].set_ylabel('Third dim voxel coords', fontsize=12)\nax[1].set_title('Second dimension, slice nr. 100', fontsize=15)\n\nax[2].imshow(img_data[:, :, 99].T, origin='lower', cmap='gray')\nax[2].set_xlabel('First dim voxel coords.', fontsize=12)\nax[2].set_ylabel('Second dim voxel coords', fontsize=12)\nax[2].set_title('Third dimension, slice nr. 100', fontsize=15)\n\nfig.tight_layout()\n```\n\nAlright, so, you figured out it's definitely a (structural) MRI scan.You can clearly see that the first voxel axis represents the sagittal dimension (left &larr;&rarr; right), the second voxel axis represents the coronal dimension (anterior &larr;&rarr; posterior), and the third voxel axis represents the axial dimension (inferior &larr;&rarr; superior).\n\nSo far, so good!\n\nNow, if we were to ask you: \"In the first plot, are we looking at the left or right side of the brain?\" Due to the left-right symmetry of the brain, this is actually impossible to tell! As such, we need a way to tell what is left and right (and anterior/posterior and inferior/superior) in our voxel space - this is what the affine is for! It will tell us, basically, whether \"left\" in our \"voxel space\" is also \"left\" in the \"real world\".\n\nHere, the real world space refers to the position of the voxels (in millimeters) *relative to the isocenter of the scanner*. In this world space, the coordinate $(0, 0, 0)$ refers to the isocenter (see image below). Furthermore, nibabel `Nifti1Images` assume that the first axis goes from left to right, the second axis goes posterior to anterior, and the third axis from inferior to superior. A short-hand for this convention is *RAS+*, which basically says that coordinates to the Right, Anterior, and Superior of the isocenter should be positive (+). It follows that coordinates to the left, posterior, and inferior of the isocenter should be negative (-).\n\n\n(Source: Graham Wideman, [link](http://www.grahamwideman.com/gw/brain/fs/coords/fscoords.htm))\n\nAlright, but how does the affine help us recover the real word coordinates of our voxels? It turns out you only need a simple matrix operation: for a set of voxel coordinates $(i, j, k)$, appended with a single 1, and an $4 \\times 4$ affine matrix $A$, you can get the real word coordinates (in RAS+) by the dot product (matrix multiplication) of $A$ and $(i, j, k, 1)$:\n\n\\begin{align}\nx, y, z, 1 = A\\begin{bmatrix}\n           i \\\\\n           j \\\\\n           k \\\\\n           1\n         \\end{bmatrix}\n\\end{align}\n\nSo, our image's affine should be a $4 \\times 4$ matrix. Let's see whether that's the case. The affine of a `Nifti1Image` is an attribute named, well, `affine`, and is a 2D numpy array:\n\n\n```python\nnp.set_printoptions(suppress=True, precision=3)  # suppresses scientific notation\nA = img.affine\nprint(A)\n```\n\nNow, suppose that you want to know whether the sagittal slice from the leftmost plot in the previous figure is on the left side or the right side. So we want to know the real world $x$ coordinate for our voxel coordinate $i=69$. Let's pick the middle voxel index for our other two dimensions ($j=119, k=109$) (we're plotting this 3D coordinate below in red).\n\n\n```python\nimport matplotlib.patches as patches\nfig, ax = plt.subplots(ncols=3, figsize=(15, 5))\n\nax[0].imshow(img_data[69, :, :].T, origin='lower', cmap='gray')\nax[0].set_xlabel('Second dim voxel coords.', fontsize=12)\nax[0].set_ylabel('Third dim voxel coords', fontsize=12)\nax[0].set_title('First dimension, slice nr. 70', fontsize=15)\nrect = patches.Rectangle((119, 109), 3, 3, linewidth=2, edgecolor='r', facecolor='none')\nax[0].add_patch(rect)\n\nax[1].imshow(img_data[:, 99, :].T, origin='lower', cmap='gray')\nax[1].set_xlabel('First dim voxel coords.', fontsize=12)\nax[1].set_ylabel('Third dim voxel coords', fontsize=12)\nax[1].set_title('Second dimension, slice nr. 100', fontsize=15)\nrect = patches.Rectangle((69, 109), 3, 3, linewidth=2, edgecolor='r', facecolor='none')\nax[1].add_patch(rect)\n\nax[2].imshow(img_data[:, :, 99].T, origin='lower', cmap='gray')\nax[2].set_xlabel('First dim voxel coords.', fontsize=12)\nax[2].set_ylabel('Second dim voxel coords', fontsize=12)\nax[2].set_title('Third dimension, slice nr. 100', fontsize=15)\nrect = patches.Rectangle((69, 119), 3, 3, linewidth=2, edgecolor='r', facecolor='none')\nax[2].add_patch(rect)\n\nfig.tight_layout()\n```\n\nTo get the real world coordinate, we need to evaluate the following:\n\\begin{align}\nx, y, z, 1 = A\\begin{bmatrix}\n           69 \\\\\n           119 \\\\\n           109 \\\\\n           1\n         \\end{bmatrix}\n\\end{align}\n\nLet's do that below:\n\n\n```python\nxyz1 = A @ np.array([69, 119, 109, 1])\nprint(xyz1)\n```\n\nHere we see that the real world $x$ coordinate is 48.472, which means that this coordinate is 48.472 millimeters to the *right* of the isocenter (remember *RAS+*!).\n\nSo, why is this important, you might ask? Well, actually, for your statistical analysis, it doesn't! The general linear model (GLM), which we'll use as our main statistical workhorse in this course, doesn't care whether a voxel is on the left or right side of the brain. But when it comes to visualization and reporting, it does! Suppose that you find unilateral amygdala activity for a particular experimental condition - you want to know whether this is on the left or right side, both for your figures and for your paper that you might write about it!\n\nMoreover, the affine will become important when we'll talk about realignment of different fMRI volumes (in motion correction) and registration of the fMRI volumes to the structural MRI volume or standard space (which might be in different orientations!), which is the topic of week 4.\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (1 point)\n</div>\n\nSuppose that you want to know whether the how much the middle of the image (i.e., the center in voxel coordinates) deviates from the isocenter of the scanner. In other words, you want to check whether the center of the image was in the isocenter of the scanner.\n\nStore these world coordinates in a new array named `xyz_middle`, which should be of size **3** (representing the three coordinates, so make sure to remove the extra `1`). Remember, indexing is Python is *zero-based* (so the first index is 0).\n\n\n```python\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n''' Tests the above ToDo ''' \nfrom nb_tests import test_affine_middle_coords\nif len(xyz_middle) != 3:\n    raise ValueError(\"Did you remove the last 1?\")\n\ntest_affine_middle_coords(A, xyz_middle)\n```\n\n<div class='alert alert-warning'>\n<b>ToDo</b> (3 points)\n</div>\n\nAlright, almost done! Let's practice some of the skills that you learned in this tutorial! For this ToDo, you goal is to **plot an histogram of the average activity value across time for all non-zero voxels in the brain** from the `f_img_data` array. So, what you have to do is the following:\n\n1. Average the `func_img_data` variable across time (resulting array should by of shape (80, 80, 37)\n2. Remove all voxels which are zero (use boolean indexing!)\n3. Make a histogram of all the resulting non-zero voxels (use the argument `bins=50` in `plt.hist`)\n\nDo this in the code-cell below. Also, *give the plot sensible labels for the axes*. This is a manually graded ToDo, so there is no test-cell.\n\nThe resulting histogram should show a \"bimodal distribution\" of average activity values - roughly with a peak around $x = 1$ and a peak round $x = 40,000$. \n\n\n```python\n# Implement to ToDo here\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\nAlright, that's it! You finished the notebook of this week! Because this week's notebook was quite extensive (the workload gets less, trust us) and you had to do a lot of ToDos, there is no separate assignment at the end of this notebook.\n\n<div class='alert alert-success'>\n    <b>Tip!</b>\n    Before handing in your notebooks, we recommend restarting your kernel (Kernel: Restart & Clear Ouput) and running all your cells again (manually, or by Cell: Run all). By running all your cells one by one (from \"top\" to \"bottom\" of the notebook), you may spot potential errors that are caused by accidentally overwriting your variables or running your cells out of order (e.g., defining the variable 'x' in cell 28 which you then use in cell 15). If you fix this before handing in your notebook, you prevent your ToDos from being graded as incorrect due to these unfortunate errors (because we grade your notebook from \"top\" to \"bottom\" as well).\n</div>\n\n", "meta": {"hexsha": "daf59dccf3a7a1dee815a1dc3bfbf831d7814e50", "size": 209659, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "python4mri.ipynb", "max_stars_repo_name": "maedbhk/python4mri", "max_stars_repo_head_hexsha": "279e8a076af2f0ab6c68cdea56e006eb6f531a1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2019-09-15T01:23:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-30T07:28:13.000Z", "max_issues_repo_path": "python4mri.ipynb", "max_issues_repo_name": "lukassnoek/python4mri", "max_issues_repo_head_hexsha": "279e8a076af2f0ab6c68cdea56e006eb6f531a1a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python4mri.ipynb", "max_forks_repo_name": "lukassnoek/python4mri", "max_forks_repo_head_hexsha": "279e8a076af2f0ab6c68cdea56e006eb6f531a1a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-09-15T01:34:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-20T14:55:14.000Z", "avg_line_length": 34.4041680341, "max_line_length": 803, "alphanum_fraction": 0.5972841614, "converted": true, "num_tokens": 34290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12252322213041653, "lm_q2_score": 0.10669060388702056, "lm_q1q2_score": 0.0130720765592777}}
{"text": "<h1>Thermal Modeling lecture notes<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Introduction-(19/2)\" data-toc-modified-id=\"Introduction-(19/2)-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Introduction (19/2)</a></span><ul class=\"toc-item\"><li><span><a href=\"#Thermal-effects:-A-historical-perspective\" data-toc-modified-id=\"Thermal-effects:-A-historical-perspective-1.1\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;</span>Thermal effects: A historical perspective</a></span><ul class=\"toc-item\"><li><span><a href=\"#Major-milestones\" data-toc-modified-id=\"Major-milestones-1.1.1\"><span class=\"toc-item-num\">1.1.1&nbsp;&nbsp;</span>Major milestones</a></span><ul class=\"toc-item\"><li><span><a href=\"#Ancient-times\" data-toc-modified-id=\"Ancient-times-1.1.1.1\"><span class=\"toc-item-num\">1.1.1.1&nbsp;&nbsp;</span>Ancient times</a></span></li><li><span><a href=\"#Early-modern-period\" data-toc-modified-id=\"Early-modern-period-1.1.1.2\"><span class=\"toc-item-num\">1.1.1.2&nbsp;&nbsp;</span>Early modern period</a></span></li><li><span><a href=\"#Modern-times\" data-toc-modified-id=\"Modern-times-1.1.1.3\"><span class=\"toc-item-num\">1.1.1.3&nbsp;&nbsp;</span>Modern times</a></span></li></ul></li></ul></li><li><span><a href=\"#Why-thermal-modeling?\" data-toc-modified-id=\"Why-thermal-modeling?-1.2\"><span class=\"toc-item-num\">1.2&nbsp;&nbsp;</span>Why thermal modeling?</a></span><ul class=\"toc-item\"><li><span><a href=\"#Heating:-Good-and-Bad\" data-toc-modified-id=\"Heating:-Good-and-Bad-1.2.1\"><span class=\"toc-item-num\">1.2.1&nbsp;&nbsp;</span>Heating: Good and Bad</a></span></li><li><span><a href=\"#Exposure/implant-safety-assessment\" data-toc-modified-id=\"Exposure/implant-safety-assessment-1.2.2\"><span class=\"toc-item-num\">1.2.2&nbsp;&nbsp;</span>Exposure/implant safety assessment</a></span><ul class=\"toc-item\"><li><span><a href=\"#Exposure-safety\" data-toc-modified-id=\"Exposure-safety-1.2.2.1\"><span class=\"toc-item-num\">1.2.2.1&nbsp;&nbsp;</span>Exposure safety</a></span></li><li><span><a href=\"#Implant-safety\" data-toc-modified-id=\"Implant-safety-1.2.2.2\"><span class=\"toc-item-num\">1.2.2.2&nbsp;&nbsp;</span>Implant safety</a></span></li></ul></li><li><span><a href=\"#Thermal-therapies\" data-toc-modified-id=\"Thermal-therapies-1.2.3\"><span class=\"toc-item-num\">1.2.3&nbsp;&nbsp;</span>Thermal therapies</a></span><ul class=\"toc-item\"><li><span><a href=\"#Treatment-planning\" data-toc-modified-id=\"Treatment-planning-1.2.3.1\"><span class=\"toc-item-num\">1.2.3.1&nbsp;&nbsp;</span>Treatment planning</a></span></li><li><span><a href=\"#Novel-therapies-and-devices\" data-toc-modified-id=\"Novel-therapies-and-devices-1.2.3.2\"><span class=\"toc-item-num\">1.2.3.2&nbsp;&nbsp;</span>Novel therapies and devices</a></span></li><li><span><a href=\"#Bio-heat-modeling\" data-toc-modified-id=\"Bio-heat-modeling-1.2.3.3\"><span class=\"toc-item-num\">1.2.3.3&nbsp;&nbsp;</span>Bio-heat modeling</a></span></li></ul></li><li><span><a href=\"#Self-heating-in-nanoscale-devices\" data-toc-modified-id=\"Self-heating-in-nanoscale-devices-1.2.4\"><span class=\"toc-item-num\">1.2.4&nbsp;&nbsp;</span>Self-heating in nanoscale devices</a></span><ul class=\"toc-item\"><li><span><a href=\"#CBRAM-device\" data-toc-modified-id=\"CBRAM-device-1.2.4.1\"><span class=\"toc-item-num\">1.2.4.1&nbsp;&nbsp;</span>CBRAM device</a></span></li><li><span><a href=\"#Nanodevice-design-work-flow\" data-toc-modified-id=\"Nanodevice-design-work-flow-1.2.4.2\"><span class=\"toc-item-num\">1.2.4.2&nbsp;&nbsp;</span>Nanodevice design work flow</a></span></li><li><span><a href=\"#Electron-Phonon-energy-exchange\" data-toc-modified-id=\"Electron-Phonon-energy-exchange-1.2.4.3\"><span class=\"toc-item-num\">1.2.4.3&nbsp;&nbsp;</span>Electron-Phonon energy exchange</a></span></li><li><span><a href=\"#Test-device-structures\" data-toc-modified-id=\"Test-device-structures-1.2.4.4\"><span class=\"toc-item-num\">1.2.4.4&nbsp;&nbsp;</span>Test device structures</a></span></li><li><span><a href=\"#Influence-of-self-heating\" data-toc-modified-id=\"Influence-of-self-heating-1.2.4.5\"><span class=\"toc-item-num\">1.2.4.5&nbsp;&nbsp;</span>Influence of self-heating</a></span></li></ul></li></ul></li></ul></li><li><span><a href=\"#Thermal-Modeling-(Bio)-(26/2)\" data-toc-modified-id=\"Thermal-Modeling-(Bio)-(26/2)-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Thermal Modeling (Bio) (26/2)</a></span><ul class=\"toc-item\"><li><span><a href=\"#The-Pennes-Bioheat-equation\" data-toc-modified-id=\"The-Pennes-Bioheat-equation-2.1\"><span class=\"toc-item-num\">2.1&nbsp;&nbsp;</span>The Pennes Bioheat equation</a></span><ul class=\"toc-item\"><li><span><a href=\"#Continuum-level-thermal-modeling\" data-toc-modified-id=\"Continuum-level-thermal-modeling-2.1.1\"><span class=\"toc-item-num\">2.1.1&nbsp;&nbsp;</span>Continuum level thermal modeling</a></span></li><li><span><a href=\"#Steady-state\" data-toc-modified-id=\"Steady-state-2.1.2\"><span class=\"toc-item-num\">2.1.2&nbsp;&nbsp;</span>Steady state</a></span></li><li><span><a href=\"#Boundary-conditions-in-the-PBE\" data-toc-modified-id=\"Boundary-conditions-in-the-PBE-2.1.3\"><span class=\"toc-item-num\">2.1.3&nbsp;&nbsp;</span>Boundary conditions in the PBE</a></span></li><li><span><a href=\"#Natural-and-forced-convection\" data-toc-modified-id=\"Natural-and-forced-convection-2.1.4\"><span class=\"toc-item-num\">2.1.4&nbsp;&nbsp;</span>Natural and forced convection</a></span></li><li><span><a href=\"#Heat-radiation\" data-toc-modified-id=\"Heat-radiation-2.1.5\"><span class=\"toc-item-num\">2.1.5&nbsp;&nbsp;</span>Heat radiation</a></span></li><li><span><a href=\"#Terms-of-the-PBE\" data-toc-modified-id=\"Terms-of-the-PBE-2.1.6\"><span class=\"toc-item-num\">2.1.6&nbsp;&nbsp;</span>Terms of the PBE</a></span><ul class=\"toc-item\"><li><span><a href=\"#Diffusion\" data-toc-modified-id=\"Diffusion-2.1.6.1\"><span class=\"toc-item-num\">2.1.6.1&nbsp;&nbsp;</span>Diffusion</a></span></li><li><span><a href=\"#Exposure\" data-toc-modified-id=\"Exposure-2.1.6.2\"><span class=\"toc-item-num\">2.1.6.2&nbsp;&nbsp;</span>Exposure</a></span></li><li><span><a href=\"#Metabolism\" data-toc-modified-id=\"Metabolism-2.1.6.3\"><span class=\"toc-item-num\">2.1.6.3&nbsp;&nbsp;</span>Metabolism</a></span></li><li><span><a href=\"#Perfusion\" data-toc-modified-id=\"Perfusion-2.1.6.4\"><span class=\"toc-item-num\">2.1.6.4&nbsp;&nbsp;</span>Perfusion</a></span></li></ul></li><li><span><a href=\"#High-temperature-limit\" data-toc-modified-id=\"High-temperature-limit-2.1.7\"><span class=\"toc-item-num\">2.1.7&nbsp;&nbsp;</span>High temperature limit</a></span></li><li><span><a href=\"#Linear-regime:-Considering-only-temperature-increase\" data-toc-modified-id=\"Linear-regime:-Considering-only-temperature-increase-2.1.8\"><span class=\"toc-item-num\">2.1.8&nbsp;&nbsp;</span>Linear regime: Considering only temperature increase</a></span></li><li><span><a href=\"#Power-deposition\" data-toc-modified-id=\"Power-deposition-2.1.9\"><span class=\"toc-item-num\">2.1.9&nbsp;&nbsp;</span>Power deposition</a></span><ul class=\"toc-item\"><li><span><a href=\"#Exposure\" data-toc-modified-id=\"Exposure-2.1.9.1\"><span class=\"toc-item-num\">2.1.9.1&nbsp;&nbsp;</span>Exposure</a></span></li><li><span><a href=\"#RF-Dosimetry\" data-toc-modified-id=\"RF-Dosimetry-2.1.9.2\"><span class=\"toc-item-num\">2.1.9.2&nbsp;&nbsp;</span>RF Dosimetry</a></span></li></ul></li><li><span><a href=\"#Beyond-PBE\" data-toc-modified-id=\"Beyond-PBE-2.1.10\"><span class=\"toc-item-num\">2.1.10&nbsp;&nbsp;</span>Beyond PBE</a></span></li></ul></li><li><span><a href=\"#Application:-Mobile-Phone-Exposure-Safety\" data-toc-modified-id=\"Application:-Mobile-Phone-Exposure-Safety-2.2\"><span class=\"toc-item-num\">2.2&nbsp;&nbsp;</span>Application: Mobile Phone Exposure Safety</a></span><ul class=\"toc-item\"><li><span><a href=\"#Averaged-SAR-and-temperature-increase\" data-toc-modified-id=\"Averaged-SAR-and-temperature-increase-2.2.1\"><span class=\"toc-item-num\">2.2.1&nbsp;&nbsp;</span>Averaged SAR and temperature increase</a></span></li><li><span><a href=\"#Debates-and-considerations\" data-toc-modified-id=\"Debates-and-considerations-2.2.2\"><span class=\"toc-item-num\">2.2.2&nbsp;&nbsp;</span>Debates and considerations</a></span></li></ul></li></ul></li><li><span><a href=\"#Thermal-Modeling-(Bio)-(4/3)\" data-toc-modified-id=\"Thermal-Modeling-(Bio)-(4/3)-3\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>Thermal Modeling (Bio) (4/3)</a></span><ul class=\"toc-item\"><li><span><a href=\"#The-UTCI-model\" data-toc-modified-id=\"The-UTCI-model-3.1\"><span class=\"toc-item-num\">3.1&nbsp;&nbsp;</span>The UTCI model</a></span><ul class=\"toc-item\"><li><span><a href=\"#Definition-of-the-Universal-Thermal-Climate-Index\" data-toc-modified-id=\"Definition-of-the-Universal-Thermal-Climate-Index-3.1.1\"><span class=\"toc-item-num\">3.1.1&nbsp;&nbsp;</span>Definition of the Universal Thermal Climate Index</a></span><ul class=\"toc-item\"><li><span><a href=\"#Advantages\" data-toc-modified-id=\"Advantages-3.1.1.1\"><span class=\"toc-item-num\">3.1.1.1&nbsp;&nbsp;</span>Advantages</a></span></li><li><span><a href=\"#Disadvantages\" data-toc-modified-id=\"Disadvantages-3.1.1.2\"><span class=\"toc-item-num\">3.1.1.2&nbsp;&nbsp;</span>Disadvantages</a></span></li></ul></li><li><span><a href=\"#Tuning-&amp;-Validation\" data-toc-modified-id=\"Tuning-&amp;-Validation-3.1.2\"><span class=\"toc-item-num\">3.1.2&nbsp;&nbsp;</span>Tuning &amp; Validation</a></span></li><li><span><a href=\"#Discretization\" data-toc-modified-id=\"Discretization-3.1.3\"><span class=\"toc-item-num\">3.1.3&nbsp;&nbsp;</span>Discretization</a></span></li><li><span><a href=\"#Coordinate-system\" data-toc-modified-id=\"Coordinate-system-3.1.4\"><span class=\"toc-item-num\">3.1.4&nbsp;&nbsp;</span>Coordinate system</a></span></li></ul></li><li><span><a href=\"#Thermoregulation-in-UTCI\" data-toc-modified-id=\"Thermoregulation-in-UTCI-3.2\"><span class=\"toc-item-num\">3.2&nbsp;&nbsp;</span>Thermoregulation in UTCI</a></span><ul class=\"toc-item\"><li><span><a href=\"#Perfusion\" data-toc-modified-id=\"Perfusion-3.2.1\"><span class=\"toc-item-num\">3.2.1&nbsp;&nbsp;</span>Perfusion</a></span></li><li><span><a href=\"#Heat-exchange-with-environment\" data-toc-modified-id=\"Heat-exchange-with-environment-3.2.2\"><span class=\"toc-item-num\">3.2.2&nbsp;&nbsp;</span>Heat exchange with environment</a></span><ul class=\"toc-item\"><li><span><a href=\"#Convection\" data-toc-modified-id=\"Convection-3.2.2.1\"><span class=\"toc-item-num\">3.2.2.1&nbsp;&nbsp;</span>Convection</a></span></li><li><span><a href=\"#Radiation\" data-toc-modified-id=\"Radiation-3.2.2.2\"><span class=\"toc-item-num\">3.2.2.2&nbsp;&nbsp;</span>Radiation</a></span></li><li><span><a href=\"#Evaporation\" data-toc-modified-id=\"Evaporation-3.2.2.3\"><span class=\"toc-item-num\">3.2.2.3&nbsp;&nbsp;</span>Evaporation</a></span></li><li><span><a href=\"#Respiration\" data-toc-modified-id=\"Respiration-3.2.2.4\"><span class=\"toc-item-num\">3.2.2.4&nbsp;&nbsp;</span>Respiration</a></span></li></ul></li><li><span><a href=\"#CNS-response-model\" data-toc-modified-id=\"CNS-response-model-3.2.3\"><span class=\"toc-item-num\">3.2.3&nbsp;&nbsp;</span>CNS response model</a></span></li><li><span><a href=\"#Sensation\" data-toc-modified-id=\"Sensation-3.2.4\"><span class=\"toc-item-num\">3.2.4&nbsp;&nbsp;</span>Sensation</a></span></li><li><span><a href=\"#Numerical-implementation\" data-toc-modified-id=\"Numerical-implementation-3.2.5\"><span class=\"toc-item-num\">3.2.5&nbsp;&nbsp;</span>Numerical implementation</a></span><ul class=\"toc-item\"><li><span><a href=\"#Space\" data-toc-modified-id=\"Space-3.2.5.1\"><span class=\"toc-item-num\">3.2.5.1&nbsp;&nbsp;</span>Space</a></span></li><li><span><a href=\"#Time\" data-toc-modified-id=\"Time-3.2.5.2\"><span class=\"toc-item-num\">3.2.5.2&nbsp;&nbsp;</span>Time</a></span></li><li><span><a href=\"#Scheme\" data-toc-modified-id=\"Scheme-3.2.5.3\"><span class=\"toc-item-num\">3.2.5.3&nbsp;&nbsp;</span>Scheme</a></span></li></ul></li></ul></li><li><span><a href=\"#Application:-MRI-exposure-safety-(RF)\" data-toc-modified-id=\"Application:-MRI-exposure-safety-(RF)-3.3\"><span class=\"toc-item-num\">3.3&nbsp;&nbsp;</span>Application: MRI exposure safety (RF)</a></span><ul class=\"toc-item\"><li><span><a href=\"#MRI-RF-safety\" data-toc-modified-id=\"MRI-RF-safety-3.3.1\"><span class=\"toc-item-num\">3.3.1&nbsp;&nbsp;</span>MRI RF safety</a></span><ul class=\"toc-item\"><li><span><a href=\"#Scenarios\" data-toc-modified-id=\"Scenarios-3.3.1.1\"><span class=\"toc-item-num\">3.3.1.1&nbsp;&nbsp;</span>Scenarios</a></span></li><li><span><a href=\"#MRI-heating\" data-toc-modified-id=\"MRI-heating-3.3.1.2\"><span class=\"toc-item-num\">3.3.1.2&nbsp;&nbsp;</span>MRI heating</a></span></li></ul></li><li><span><a href=\"#Thermal-dose\" data-toc-modified-id=\"Thermal-dose-3.3.2\"><span class=\"toc-item-num\">3.3.2&nbsp;&nbsp;</span>Thermal dose</a></span></li><li><span><a href=\"#Thermal-damaga\" data-toc-modified-id=\"Thermal-damaga-3.3.3\"><span class=\"toc-item-num\">3.3.3&nbsp;&nbsp;</span>Thermal damaga</a></span></li><li><span><a href=\"#CEM43\" data-toc-modified-id=\"CEM43-3.3.4\"><span class=\"toc-item-num\">3.3.4&nbsp;&nbsp;</span>CEM43</a></span><ul class=\"toc-item\"><li><span><a href=\"#Concept\" data-toc-modified-id=\"Concept-3.3.4.1\"><span class=\"toc-item-num\">3.3.4.1&nbsp;&nbsp;</span>Concept</a></span></li><li><span><a href=\"#Definition\" data-toc-modified-id=\"Definition-3.3.4.2\"><span class=\"toc-item-num\">3.3.4.2&nbsp;&nbsp;</span>Definition</a></span></li><li><span><a href=\"#Tresholds\" data-toc-modified-id=\"Tresholds-3.3.4.3\"><span class=\"toc-item-num\">3.3.4.3&nbsp;&nbsp;</span>Tresholds</a></span></li><li><span><a href=\"#Advantages-of-dose-based-limits\" data-toc-modified-id=\"Advantages-of-dose-based-limits-3.3.4.4\"><span class=\"toc-item-num\">3.3.4.4&nbsp;&nbsp;</span>Advantages of dose-based limits</a></span></li></ul></li></ul></li></ul></li><li><span><a href=\"#Numerical-Methods-(11/3)\" data-toc-modified-id=\"Numerical-Methods-(11/3)-4\"><span class=\"toc-item-num\">4&nbsp;&nbsp;</span>Numerical Methods (11/3)</a></span><ul class=\"toc-item\"><li><span><a href=\"#Discretization-of-continuum-models\" data-toc-modified-id=\"Discretization-of-continuum-models-4.1\"><span class=\"toc-item-num\">4.1&nbsp;&nbsp;</span>Discretization of continuum models</a></span><ul class=\"toc-item\"><li><span><a href=\"#Structured-grids\" data-toc-modified-id=\"Structured-grids-4.1.1\"><span class=\"toc-item-num\">4.1.1&nbsp;&nbsp;</span>Structured grids</a></span></li><li><span><a href=\"#Unstructured-meshes\" data-toc-modified-id=\"Unstructured-meshes-4.1.2\"><span class=\"toc-item-num\">4.1.2&nbsp;&nbsp;</span>Unstructured meshes</a></span></li></ul></li><li><span><a href=\"#FDTD\" data-toc-modified-id=\"FDTD-4.2\"><span class=\"toc-item-num\">4.2&nbsp;&nbsp;</span>FDTD</a></span><ul class=\"toc-item\"><li><span><a href=\"#Temporal-discretization\" data-toc-modified-id=\"Temporal-discretization-4.2.1\"><span class=\"toc-item-num\">4.2.1&nbsp;&nbsp;</span>Temporal discretization</a></span></li><li><span><a href=\"#Spatial-discretization\" data-toc-modified-id=\"Spatial-discretization-4.2.2\"><span class=\"toc-item-num\">4.2.2&nbsp;&nbsp;</span>Spatial discretization</a></span></li><li><span><a href=\"#Dealing-with-interfaces\" data-toc-modified-id=\"Dealing-with-interfaces-4.2.3\"><span class=\"toc-item-num\">4.2.3&nbsp;&nbsp;</span>Dealing with interfaces</a></span></li><li><span><a href=\"#Boundary-conditions\" data-toc-modified-id=\"Boundary-conditions-4.2.4\"><span class=\"toc-item-num\">4.2.4&nbsp;&nbsp;</span>Boundary conditions</a></span></li><li><span><a href=\"#Staircasing\" data-toc-modified-id=\"Staircasing-4.2.5\"><span class=\"toc-item-num\">4.2.5&nbsp;&nbsp;</span>Staircasing</a></span></li><li><span><a href=\"#Conformal-corrections\" data-toc-modified-id=\"Conformal-corrections-4.2.6\"><span class=\"toc-item-num\">4.2.6&nbsp;&nbsp;</span>Conformal corrections</a></span></li><li><span><a href=\"#Stability\" data-toc-modified-id=\"Stability-4.2.7\"><span class=\"toc-item-num\">4.2.7&nbsp;&nbsp;</span>Stability</a></span><ul class=\"toc-item\"><li><span><a href=\"#CFL-criterion\" data-toc-modified-id=\"CFL-criterion-4.2.7.1\"><span class=\"toc-item-num\">4.2.7.1&nbsp;&nbsp;</span>CFL criterion</a></span></li></ul></li><li><span><a href=\"#Other-considerations\" data-toc-modified-id=\"Other-considerations-4.2.8\"><span class=\"toc-item-num\">4.2.8&nbsp;&nbsp;</span>Other considerations</a></span></li></ul></li><li><span><a href=\"#FEM\" data-toc-modified-id=\"FEM-4.3\"><span class=\"toc-item-num\">4.3&nbsp;&nbsp;</span>FEM</a></span><ul class=\"toc-item\"><li><span><a href=\"#Pros-and-cons\" data-toc-modified-id=\"Pros-and-cons-4.3.1\"><span class=\"toc-item-num\">4.3.1&nbsp;&nbsp;</span>Pros and cons</a></span></li><li><span><a href=\"#Overview-of-the-Galerkin-method\" data-toc-modified-id=\"Overview-of-the-Galerkin-method-4.3.2\"><span class=\"toc-item-num\">4.3.2&nbsp;&nbsp;</span>Overview of the Galerkin method</a></span></li></ul></li><li><span><a href=\"#Fast-Poisson-solvers\" data-toc-modified-id=\"Fast-Poisson-solvers-4.4\"><span class=\"toc-item-num\">4.4&nbsp;&nbsp;</span>Fast Poisson solvers</a></span><ul class=\"toc-item\"><li><span><a href=\"#Green's-functions\" data-toc-modified-id=\"Green's-functions-4.4.1\"><span class=\"toc-item-num\">4.4.1&nbsp;&nbsp;</span>Green's functions</a></span></li><li><span><a href=\"#Green's-function-of-the-PBE\" data-toc-modified-id=\"Green's-function-of-the-PBE-4.4.2\"><span class=\"toc-item-num\">4.4.2&nbsp;&nbsp;</span>Green's function of the PBE</a></span></li><li><span><a href=\"#Overview-of-the-Fast-Poisson-method\" data-toc-modified-id=\"Overview-of-the-Fast-Poisson-method-4.4.3\"><span class=\"toc-item-num\">4.4.3&nbsp;&nbsp;</span>Overview of the Fast Poisson method</a></span></li></ul></li></ul></li><li><span><a href=\"#Thermal-Therapy-Treatment-Planning-(18/3)\" data-toc-modified-id=\"Thermal-Therapy-Treatment-Planning-(18/3)-5\"><span class=\"toc-item-num\">5&nbsp;&nbsp;</span>Thermal Therapy Treatment Planning (18/3)</a></span><ul class=\"toc-item\"><li><span><a href=\"#Introduction\" data-toc-modified-id=\"Introduction-5.1\"><span class=\"toc-item-num\">5.1&nbsp;&nbsp;</span>Introduction</a></span><ul class=\"toc-item\"><li><span><a href=\"#Hyperthermic-oncology\" data-toc-modified-id=\"Hyperthermic-oncology-5.1.1\"><span class=\"toc-item-num\">5.1.1&nbsp;&nbsp;</span>Hyperthermic oncology</a></span></li><li><span><a href=\"#HT-energy-delivery-technology\" data-toc-modified-id=\"HT-energy-delivery-technology-5.1.2\"><span class=\"toc-item-num\">5.1.2&nbsp;&nbsp;</span>HT energy delivery technology</a></span></li><li><span><a href=\"#Thermal-ablation\" data-toc-modified-id=\"Thermal-ablation-5.1.3\"><span class=\"toc-item-num\">5.1.3&nbsp;&nbsp;</span>Thermal ablation</a></span></li><li><span><a href=\"#Temperature-modeling\" data-toc-modified-id=\"Temperature-modeling-5.1.4\"><span class=\"toc-item-num\">5.1.4&nbsp;&nbsp;</span>Temperature modeling</a></span></li><li><span><a href=\"#Hyperthermic-Treatment-Planning-(HTP)\" data-toc-modified-id=\"Hyperthermic-Treatment-Planning-(HTP)-5.1.5\"><span class=\"toc-item-num\">5.1.5&nbsp;&nbsp;</span>Hyperthermic Treatment Planning (HTP)</a></span><ul class=\"toc-item\"><li><span><a href=\"#Embedding-in-clinlcal-flow\" data-toc-modified-id=\"Embedding-in-clinlcal-flow-5.1.5.1\"><span class=\"toc-item-num\">5.1.5.1&nbsp;&nbsp;</span>Embedding in clinlcal flow</a></span></li><li><span><a href=\"#Steps-in-HTP\" data-toc-modified-id=\"Steps-in-HTP-5.1.5.2\"><span class=\"toc-item-num\">5.1.5.2&nbsp;&nbsp;</span>Steps in HTP</a></span></li><li><span><a href=\"#Motivation\" data-toc-modified-id=\"Motivation-5.1.5.3\"><span class=\"toc-item-num\">5.1.5.3&nbsp;&nbsp;</span>Motivation</a></span></li><li><span><a href=\"#Requirements\" data-toc-modified-id=\"Requirements-5.1.5.4\"><span class=\"toc-item-num\">5.1.5.4&nbsp;&nbsp;</span>Requirements</a></span></li></ul></li></ul></li><li><span><a href=\"#Imaging\" data-toc-modified-id=\"Imaging-5.2\"><span class=\"toc-item-num\">5.2&nbsp;&nbsp;</span>Imaging</a></span><ul class=\"toc-item\"><li><span><a href=\"#Definition-and-objectives\" data-toc-modified-id=\"Definition-and-objectives-5.2.1\"><span class=\"toc-item-num\">5.2.1&nbsp;&nbsp;</span>Definition and objectives</a></span></li><li><span><a href=\"#Sim4Life-framework\" data-toc-modified-id=\"Sim4Life-framework-5.2.2\"><span class=\"toc-item-num\">5.2.2&nbsp;&nbsp;</span>Sim4Life framework</a></span></li></ul></li><li><span><a href=\"#Personalized-model-generation\" data-toc-modified-id=\"Personalized-model-generation-5.3\"><span class=\"toc-item-num\">5.3&nbsp;&nbsp;</span>Personalized model generation</a></span><ul class=\"toc-item\"><li><span><a href=\"#Implementation\" data-toc-modified-id=\"Implementation-5.3.1\"><span class=\"toc-item-num\">5.3.1&nbsp;&nbsp;</span>Implementation</a></span></li><li><span><a href=\"#Considerations\" data-toc-modified-id=\"Considerations-5.3.2\"><span class=\"toc-item-num\">5.3.2&nbsp;&nbsp;</span>Considerations</a></span></li><li><span><a href=\"#Surface-extraction-and-discretization\" data-toc-modified-id=\"Surface-extraction-and-discretization-5.3.3\"><span class=\"toc-item-num\">5.3.3&nbsp;&nbsp;</span>Surface extraction and discretization</a></span><ul class=\"toc-item\"><li><span><a href=\"#Implementation\" data-toc-modified-id=\"Implementation-5.3.3.1\"><span class=\"toc-item-num\">5.3.3.1&nbsp;&nbsp;</span>Implementation</a></span></li><li><span><a href=\"#Considerations\" data-toc-modified-id=\"Considerations-5.3.3.2\"><span class=\"toc-item-num\">5.3.3.2&nbsp;&nbsp;</span>Considerations</a></span></li></ul></li></ul></li><li><span><a href=\"#EM-modeling\" data-toc-modified-id=\"EM-modeling-5.4\"><span class=\"toc-item-num\">5.4&nbsp;&nbsp;</span>EM modeling</a></span><ul class=\"toc-item\"><li><span><a href=\"#Implementation\" data-toc-modified-id=\"Implementation-5.4.1\"><span class=\"toc-item-num\">5.4.1&nbsp;&nbsp;</span>Implementation</a></span></li><li><span><a href=\"#Considerations\" data-toc-modified-id=\"Considerations-5.4.2\"><span class=\"toc-item-num\">5.4.2&nbsp;&nbsp;</span>Considerations</a></span></li></ul></li><li><span><a href=\"#Acoustic-modeling\" data-toc-modified-id=\"Acoustic-modeling-5.5\"><span class=\"toc-item-num\">5.5&nbsp;&nbsp;</span>Acoustic modeling</a></span><ul class=\"toc-item\"><li><span><a href=\"#Implementation\" data-toc-modified-id=\"Implementation-5.5.1\"><span class=\"toc-item-num\">5.5.1&nbsp;&nbsp;</span>Implementation</a></span></li><li><span><a href=\"#Considerations\" data-toc-modified-id=\"Considerations-5.5.2\"><span class=\"toc-item-num\">5.5.2&nbsp;&nbsp;</span>Considerations</a></span></li></ul></li><li><span><a href=\"#Thermal-modeling\" data-toc-modified-id=\"Thermal-modeling-5.6\"><span class=\"toc-item-num\">5.6&nbsp;&nbsp;</span>Thermal modeling</a></span><ul class=\"toc-item\"><li><span><a href=\"#Implementation\" data-toc-modified-id=\"Implementation-5.6.1\"><span class=\"toc-item-num\">5.6.1&nbsp;&nbsp;</span>Implementation</a></span></li><li><span><a href=\"#Considerations\" data-toc-modified-id=\"Considerations-5.6.2\"><span class=\"toc-item-num\">5.6.2&nbsp;&nbsp;</span>Considerations</a></span></li></ul></li><li><span><a href=\"#The-use-of-HPC\" data-toc-modified-id=\"The-use-of-HPC-5.7\"><span class=\"toc-item-num\">5.7&nbsp;&nbsp;</span>The use of HPC</a></span></li><li><span><a href=\"#Optimization\" data-toc-modified-id=\"Optimization-5.8\"><span class=\"toc-item-num\">5.8&nbsp;&nbsp;</span>Optimization</a></span><ul class=\"toc-item\"><li><span><a href=\"#Objectives\" data-toc-modified-id=\"Objectives-5.8.1\"><span class=\"toc-item-num\">5.8.1&nbsp;&nbsp;</span>Objectives</a></span></li><li><span><a href=\"#Array-steering-optimization\" data-toc-modified-id=\"Array-steering-optimization-5.8.2\"><span class=\"toc-item-num\">5.8.2&nbsp;&nbsp;</span>Array steering optimization</a></span><ul class=\"toc-item\"><li><span><a href=\"#Implementation\" data-toc-modified-id=\"Implementation-5.8.2.1\"><span class=\"toc-item-num\">5.8.2.1&nbsp;&nbsp;</span>Implementation</a></span></li><li><span><a href=\"#Considerations\" data-toc-modified-id=\"Considerations-5.8.2.2\"><span class=\"toc-item-num\">5.8.2.2&nbsp;&nbsp;</span>Considerations</a></span></li></ul></li></ul></li><li><span><a href=\"#FUS-steering\" data-toc-modified-id=\"FUS-steering-5.9\"><span class=\"toc-item-num\">5.9&nbsp;&nbsp;</span>FUS steering</a></span></li><li><span><a href=\"#Effect-quantification\" data-toc-modified-id=\"Effect-quantification-5.10\"><span class=\"toc-item-num\">5.10&nbsp;&nbsp;</span>Effect quantification</a></span><ul class=\"toc-item\"><li><span><a href=\"#Implementation\" data-toc-modified-id=\"Implementation-5.10.1\"><span class=\"toc-item-num\">5.10.1&nbsp;&nbsp;</span>Implementation</a></span></li><li><span><a href=\"#Considerations\" data-toc-modified-id=\"Considerations-5.10.2\"><span class=\"toc-item-num\">5.10.2&nbsp;&nbsp;</span>Considerations</a></span></li></ul></li><li><span><a href=\"#Clinical-integration\" data-toc-modified-id=\"Clinical-integration-5.11\"><span class=\"toc-item-num\">5.11&nbsp;&nbsp;</span>Clinical integration</a></span><ul class=\"toc-item\"><li><span><a href=\"#Implementation\" data-toc-modified-id=\"Implementation-5.11.1\"><span class=\"toc-item-num\">5.11.1&nbsp;&nbsp;</span>Implementation</a></span></li><li><span><a href=\"#Considerations\" data-toc-modified-id=\"Considerations-5.11.2\"><span class=\"toc-item-num\">5.11.2&nbsp;&nbsp;</span>Considerations</a></span></li></ul></li><li><span><a href=\"#Validation,-Verification-and-Uncertainty-Quantification\" data-toc-modified-id=\"Validation,-Verification-and-Uncertainty-Quantification-5.12\"><span class=\"toc-item-num\">5.12&nbsp;&nbsp;</span>Validation, Verification and Uncertainty Quantification</a></span><ul class=\"toc-item\"><li><span><a href=\"#Verification\" data-toc-modified-id=\"Verification-5.12.1\"><span class=\"toc-item-num\">5.12.1&nbsp;&nbsp;</span>Verification</a></span></li><li><span><a href=\"#Validation\" data-toc-modified-id=\"Validation-5.12.2\"><span class=\"toc-item-num\">5.12.2&nbsp;&nbsp;</span>Validation</a></span><ul class=\"toc-item\"><li><span><a href=\"#Local-fields\" data-toc-modified-id=\"Local-fields-5.12.2.1\"><span class=\"toc-item-num\">5.12.2.1&nbsp;&nbsp;</span>Local fields</a></span></li><li><span><a href=\"#In-vivo-heating\" data-toc-modified-id=\"In-vivo-heating-5.12.2.2\"><span class=\"toc-item-num\">5.12.2.2&nbsp;&nbsp;</span>In vivo heating</a></span></li></ul></li><li><span><a href=\"#UQ\" data-toc-modified-id=\"UQ-5.12.3\"><span class=\"toc-item-num\">5.12.3&nbsp;&nbsp;</span>UQ</a></span></li></ul></li><li><span><a href=\"#Limitations-and-need-for-further-research\" data-toc-modified-id=\"Limitations-and-need-for-further-research-5.13\"><span class=\"toc-item-num\">5.13&nbsp;&nbsp;</span>Limitations and need for further research</a></span><ul class=\"toc-item\"><li><span><a href=\"#Tissue-parameters\" data-toc-modified-id=\"Tissue-parameters-5.13.1\"><span class=\"toc-item-num\">5.13.1&nbsp;&nbsp;</span>Tissue parameters</a></span></li><li><span><a href=\"#Dynamic-tissue-models\" data-toc-modified-id=\"Dynamic-tissue-models-5.13.2\"><span class=\"toc-item-num\">5.13.2&nbsp;&nbsp;</span>Dynamic tissue models</a></span></li><li><span><a href=\"#Closed-loop-treatment-control\" data-toc-modified-id=\"Closed-loop-treatment-control-5.13.3\"><span class=\"toc-item-num\">5.13.3&nbsp;&nbsp;</span>Closed-loop treatment control</a></span></li><li><span><a href=\"#Clinical-integration\" data-toc-modified-id=\"Clinical-integration-5.13.4\"><span class=\"toc-item-num\">5.13.4&nbsp;&nbsp;</span>Clinical integration</a></span></li><li><span><a href=\"#Effectiveness-and-outcome-prediction\" data-toc-modified-id=\"Effectiveness-and-outcome-prediction-5.13.5\"><span class=\"toc-item-num\">5.13.5&nbsp;&nbsp;</span>Effectiveness and outcome prediction</a></span></li><li><span><a href=\"#Validation-and-quality-assurance\" data-toc-modified-id=\"Validation-and-quality-assurance-5.13.6\"><span class=\"toc-item-num\">5.13.6&nbsp;&nbsp;</span>Validation and quality assurance</a></span></li></ul></li><li><span><a href=\"#Conclusions\" data-toc-modified-id=\"Conclusions-5.14\"><span class=\"toc-item-num\">5.14&nbsp;&nbsp;</span>Conclusions</a></span></li><li><span><a href=\"#Exercise:-Fast-temperature-increase-predictions-for-phased-arrays\" data-toc-modified-id=\"Exercise:-Fast-temperature-increase-predictions-for-phased-arrays-5.15\"><span class=\"toc-item-num\">5.15&nbsp;&nbsp;</span>Exercise: Fast temperature increase predictions for phased arrays</a></span></li></ul></li><li><span><a href=\"#Verification-and-Validation-(25/3)\" data-toc-modified-id=\"Verification-and-Validation-(25/3)-6\"><span class=\"toc-item-num\">6&nbsp;&nbsp;</span>Verification and Validation (25/3)</a></span><ul class=\"toc-item\"><li><span><a href=\"#Background\" data-toc-modified-id=\"Background-6.1\"><span class=\"toc-item-num\">6.1&nbsp;&nbsp;</span>Background</a></span><ul class=\"toc-item\"><li><span><a href=\"#Benefits-of-computational-modeling-in-MedTech-and-computational-life-sciences\" data-toc-modified-id=\"Benefits-of-computational-modeling-in-MedTech-and-computational-life-sciences-6.1.1\"><span class=\"toc-item-num\">6.1.1&nbsp;&nbsp;</span>Benefits of computational modeling in MedTech and computational life sciences</a></span></li><li><span><a href=\"#Computational-modeling-for-regulatory-submissions\" data-toc-modified-id=\"Computational-modeling-for-regulatory-submissions-6.1.2\"><span class=\"toc-item-num\">6.1.2&nbsp;&nbsp;</span>Computational modeling for regulatory submissions</a></span></li><li><span><a href=\"#Verification-and-validation-standard-(ASME,-FDA)\" data-toc-modified-id=\"Verification-and-validation-standard-(ASME,-FDA)-6.1.3\"><span class=\"toc-item-num\">6.1.3&nbsp;&nbsp;</span>Verification and validation standard (ASME, FDA)</a></span></li><li><span><a href=\"#Multi-physics\" data-toc-modified-id=\"Multi-physics-6.1.4\"><span class=\"toc-item-num\">6.1.4&nbsp;&nbsp;</span>Multi-physics</a></span></li><li><span><a href=\"#In-vivo-issues\" data-toc-modified-id=\"In-vivo-issues-6.1.5\"><span class=\"toc-item-num\">6.1.5&nbsp;&nbsp;</span>In vivo issues</a></span></li><li><span><a href=\"#Benchmarks\" data-toc-modified-id=\"Benchmarks-6.1.6\"><span class=\"toc-item-num\">6.1.6&nbsp;&nbsp;</span>Benchmarks</a></span></li><li><span><a href=\"#Context-of-use\" data-toc-modified-id=\"Context-of-use-6.1.7\"><span class=\"toc-item-num\">6.1.7&nbsp;&nbsp;</span>Context-of-use</a></span></li><li><span><a href=\"#Uncertainty-and-sensitivity-analysis\" data-toc-modified-id=\"Uncertainty-and-sensitivity-analysis-6.1.8\"><span class=\"toc-item-num\">6.1.8&nbsp;&nbsp;</span>Uncertainty and sensitivity analysis</a></span></li></ul></li><li><span><a href=\"#V-&amp;-V-example:-FUS-Simulator:-Solver-Verification-&amp;-Validation\" data-toc-modified-id=\"V-&amp;-V-example:-FUS-Simulator:-Solver-Verification-&amp;-Validation-6.2\"><span class=\"toc-item-num\">6.2&nbsp;&nbsp;</span>V &amp; V example: FUS Simulator: Solver Verification &amp; Validation</a></span><ul class=\"toc-item\"><li><span><a href=\"#Verification\" data-toc-modified-id=\"Verification-6.2.1\"><span class=\"toc-item-num\">6.2.1&nbsp;&nbsp;</span>Verification</a></span><ul class=\"toc-item\"><li><span><a href=\"#Critical-effects-for-FDTD-implementation-of-linear-acoustic-pressure-wave-model\" data-toc-modified-id=\"Critical-effects-for-FDTD-implementation-of-linear-acoustic-pressure-wave-model-6.2.1.1\"><span class=\"toc-item-num\">6.2.1.1&nbsp;&nbsp;</span>Critical effects for FDTD implementation of linear acoustic pressure wave model</a></span></li><li><span><a href=\"#Method-of-Manufactured-Solutions\" data-toc-modified-id=\"Method-of-Manufactured-Solutions-6.2.1.2\"><span class=\"toc-item-num\">6.2.1.2&nbsp;&nbsp;</span>Method of Manufactured Solutions</a></span></li></ul></li><li><span><a href=\"#Validation\" data-toc-modified-id=\"Validation-6.2.2\"><span class=\"toc-item-num\">6.2.2&nbsp;&nbsp;</span>Validation</a></span><ul class=\"toc-item\"><li><span><a href=\"#Gamma-method\" data-toc-modified-id=\"Gamma-method-6.2.2.1\"><span class=\"toc-item-num\">6.2.2.1&nbsp;&nbsp;</span>Gamma method</a></span></li><li><span><a href=\"#UA-Gamma-Combination\" data-toc-modified-id=\"UA-Gamma-Combination-6.2.2.2\"><span class=\"toc-item-num\">6.2.2.2&nbsp;&nbsp;</span>UA-Gamma Combination</a></span></li><li><span><a href=\"#Measurement-setup\" data-toc-modified-id=\"Measurement-setup-6.2.2.3\"><span class=\"toc-item-num\">6.2.2.3&nbsp;&nbsp;</span>Measurement setup</a></span></li><li><span><a href=\"#Results\" data-toc-modified-id=\"Results-6.2.2.4\"><span class=\"toc-item-num\">6.2.2.4&nbsp;&nbsp;</span>Results</a></span></li></ul></li></ul></li><li><span><a href=\"#V-&amp;-V-example:-MRI-Induced-Heating:-Validation-from-EM-Exposure-to-in-vivo-heating\" data-toc-modified-id=\"V-&amp;-V-example:-MRI-Induced-Heating:-Validation-from-EM-Exposure-to-in-vivo-heating-6.3\"><span class=\"toc-item-num\">6.3&nbsp;&nbsp;</span>V &amp; V example: MRI Induced Heating: Validation from EM Exposure to in vivo heating</a></span><ul class=\"toc-item\"><li><span><a href=\"#Illustrating-Example:-MRI-RF-Exposure\" data-toc-modified-id=\"Illustrating-Example:-MRI-RF-Exposure-6.3.1\"><span class=\"toc-item-num\">6.3.1&nbsp;&nbsp;</span>Illustrating Example: MRI RF Exposure</a></span></li><li><span><a href=\"#MR-RF-Safety-Background\" data-toc-modified-id=\"MR-RF-Safety-Background-6.3.2\"><span class=\"toc-item-num\">6.3.2&nbsp;&nbsp;</span>MR RF Safety Background</a></span><ul class=\"toc-item\"><li><span><a href=\"#Limits\" data-toc-modified-id=\"Limits-6.3.2.1\"><span class=\"toc-item-num\">6.3.2.1&nbsp;&nbsp;</span>Limits</a></span></li><li><span><a href=\"#Exposure\" data-toc-modified-id=\"Exposure-6.3.2.2\"><span class=\"toc-item-num\">6.3.2.2&nbsp;&nbsp;</span>Exposure</a></span></li><li><span><a href=\"#psSAR-&amp;-T\" data-toc-modified-id=\"psSAR-&amp;-T-6.3.2.3\"><span class=\"toc-item-num\">6.3.2.3&nbsp;&nbsp;</span>psSAR &amp; T</a></span></li><li><span><a href=\"#T-Distribution\" data-toc-modified-id=\"T-Distribution-6.3.2.4\"><span class=\"toc-item-num\">6.3.2.4&nbsp;&nbsp;</span>T Distribution</a></span></li><li><span><a href=\"#pTx-vs-CP\" data-toc-modified-id=\"pTx-vs-CP-6.3.2.5\"><span class=\"toc-item-num\">6.3.2.5&nbsp;&nbsp;</span>pTx vs CP</a></span></li></ul></li><li><span><a href=\"#Verification\" data-toc-modified-id=\"Verification-6.3.3\"><span class=\"toc-item-num\">6.3.3&nbsp;&nbsp;</span>Verification</a></span><ul class=\"toc-item\"><li><span><a href=\"#Coil-modeling-with-Huygens-vs-direct\" data-toc-modified-id=\"Coil-modeling-with-Huygens-vs-direct-6.3.3.1\"><span class=\"toc-item-num\">6.3.3.1&nbsp;&nbsp;</span>Coil modeling with Huygens vs direct</a></span></li></ul></li><li><span><a href=\"#Validation\" data-toc-modified-id=\"Validation-6.3.4\"><span class=\"toc-item-num\">6.3.4&nbsp;&nbsp;</span>Validation</a></span><ul class=\"toc-item\"><li><span><a href=\"#Incident-E/B-field\" data-toc-modified-id=\"Incident-E/B-field-6.3.4.1\"><span class=\"toc-item-num\">6.3.4.1&nbsp;&nbsp;</span>Incident E/B-field</a></span></li><li><span><a href=\"#Local-field---requirements\" data-toc-modified-id=\"Local-field---requirements-6.3.4.2\"><span class=\"toc-item-num\">6.3.4.2&nbsp;&nbsp;</span>Local field - requirements</a></span></li><li><span><a href=\"#Local-field---experimental-setup\" data-toc-modified-id=\"Local-field---experimental-setup-6.3.4.3\"><span class=\"toc-item-num\">6.3.4.3&nbsp;&nbsp;</span>Local field - experimental setup</a></span></li><li><span><a href=\"#Local-field---results\" data-toc-modified-id=\"Local-field---results-6.3.4.4\"><span class=\"toc-item-num\">6.3.4.4&nbsp;&nbsp;</span>Local field - results</a></span></li><li><span><a href=\"#EM-induced-heating---setup\" data-toc-modified-id=\"EM-induced-heating---setup-6.3.4.5\"><span class=\"toc-item-num\">6.3.4.5&nbsp;&nbsp;</span>EM induced heating - setup</a></span></li><li><span><a href=\"#EM-induced-heating---results\" data-toc-modified-id=\"EM-induced-heating---results-6.3.4.6\"><span class=\"toc-item-num\">6.3.4.6&nbsp;&nbsp;</span>EM induced heating - results</a></span></li><li><span><a href=\"#In-vivo-heating\" data-toc-modified-id=\"In-vivo-heating-6.3.4.7\"><span class=\"toc-item-num\">6.3.4.7&nbsp;&nbsp;</span>In vivo heating</a></span></li></ul></li></ul></li><li><span><a href=\"#V-&amp;-V-example:-EM-neuron-interaction:-Getting-the-Quantity-of-interest-wrong\" data-toc-modified-id=\"V-&amp;-V-example:-EM-neuron-interaction:-Getting-the-Quantity-of-interest-wrong-6.4\"><span class=\"toc-item-num\">6.4&nbsp;&nbsp;</span>V &amp; V example: EM-neuron interaction: Getting the Quantity-of-interest wrong</a></span><ul class=\"toc-item\"><li><span><a href=\"#EM-induced-neuro-stimulation\" data-toc-modified-id=\"EM-induced-neuro-stimulation-6.4.1\"><span class=\"toc-item-num\">6.4.1&nbsp;&nbsp;</span>EM induced neuro-stimulation</a></span><ul class=\"toc-item\"><li><span><a href=\"#Considerations\" data-toc-modified-id=\"Considerations-6.4.1.1\"><span class=\"toc-item-num\">6.4.1.1&nbsp;&nbsp;</span>Considerations</a></span></li><li><span><a href=\"#Modeling\" data-toc-modified-id=\"Modeling-6.4.1.2\"><span class=\"toc-item-num\">6.4.1.2&nbsp;&nbsp;</span>Modeling</a></span></li><li><span><a href=\"#Results\" data-toc-modified-id=\"Results-6.4.1.3\"><span class=\"toc-item-num\">6.4.1.3&nbsp;&nbsp;</span>Results</a></span></li></ul></li></ul></li><li><span><a href=\"#V-&amp;-V-example:-Computational-Human-Phantoms\" data-toc-modified-id=\"V-&amp;-V-example:-Computational-Human-Phantoms-6.5\"><span class=\"toc-item-num\">6.5&nbsp;&nbsp;</span>V &amp; V example: Computational Human Phantoms</a></span><ul class=\"toc-item\"><li><span><a href=\"#Verification\" data-toc-modified-id=\"Verification-6.5.1\"><span class=\"toc-item-num\">6.5.1&nbsp;&nbsp;</span>Verification</a></span></li><li><span><a href=\"#Validation\" data-toc-modified-id=\"Validation-6.5.2\"><span class=\"toc-item-num\">6.5.2&nbsp;&nbsp;</span>Validation</a></span></li></ul></li><li><span><a href=\"#Aspects-of-Quality-Assurance\" data-toc-modified-id=\"Aspects-of-Quality-Assurance-6.6\"><span class=\"toc-item-num\">6.6&nbsp;&nbsp;</span>Aspects of Quality Assurance</a></span></li><li><span><a href=\"#Exercise:-Method-of-Manufactured-Solutions\" data-toc-modified-id=\"Exercise:-Method-of-Manufactured-Solutions-6.7\"><span class=\"toc-item-num\">6.7&nbsp;&nbsp;</span>Exercise: Method of Manufactured Solutions</a></span></li></ul></li><li><span><a href=\"#Nanoscale-Thermal-Modeling-I-(1/4)\" data-toc-modified-id=\"Nanoscale-Thermal-Modeling-I-(1/4)-7\"><span class=\"toc-item-num\">7&nbsp;&nbsp;</span>Nanoscale Thermal Modeling I (1/4)</a></span><ul class=\"toc-item\"><li><span><a href=\"#Learning-goals\" data-toc-modified-id=\"Learning-goals-7.1\"><span class=\"toc-item-num\">7.1&nbsp;&nbsp;</span>Learning goals</a></span></li><li><span><a href=\"#Summary\" data-toc-modified-id=\"Summary-7.2\"><span class=\"toc-item-num\">7.2&nbsp;&nbsp;</span>Summary</a></span></li><li><span><a href=\"#Outline\" data-toc-modified-id=\"Outline-7.3\"><span class=\"toc-item-num\">7.3&nbsp;&nbsp;</span>Outline</a></span></li><li><span><a href=\"#From-temperature-to-phonon\" data-toc-modified-id=\"From-temperature-to-phonon-7.4\"><span class=\"toc-item-num\">7.4&nbsp;&nbsp;</span>From temperature to phonon</a></span><ul class=\"toc-item\"><li><span><a href=\"#Introduction\" data-toc-modified-id=\"Introduction-7.4.1\"><span class=\"toc-item-num\">7.4.1&nbsp;&nbsp;</span>Introduction</a></span></li><li><span><a href=\"#Heat-capacity\" data-toc-modified-id=\"Heat-capacity-7.4.2\"><span class=\"toc-item-num\">7.4.2&nbsp;&nbsp;</span>Heat capacity</a></span></li><li><span><a href=\"#Heat-flow\" data-toc-modified-id=\"Heat-flow-7.4.3\"><span class=\"toc-item-num\">7.4.3&nbsp;&nbsp;</span>Heat flow</a></span><ul class=\"toc-item\"><li><span><a href=\"#Definition-of-heat-flow\" data-toc-modified-id=\"Definition-of-heat-flow-7.4.3.1\"><span class=\"toc-item-num\">7.4.3.1&nbsp;&nbsp;</span>Definition of heat flow</a></span></li><li><span><a href=\"#Calculation-of-heat-flow\" data-toc-modified-id=\"Calculation-of-heat-flow-7.4.3.2\"><span class=\"toc-item-num\">7.4.3.2&nbsp;&nbsp;</span>Calculation of heat flow</a></span></li></ul></li><li><span><a href=\"#Thermal-conductivity\" data-toc-modified-id=\"Thermal-conductivity-7.4.4\"><span class=\"toc-item-num\">7.4.4&nbsp;&nbsp;</span>Thermal conductivity</a></span></li></ul></li><li><span><a href=\"#Electron-vs.-phonon\" data-toc-modified-id=\"Electron-vs.-phonon-7.5\"><span class=\"toc-item-num\">7.5&nbsp;&nbsp;</span>Electron vs. phonon</a></span><ul class=\"toc-item\"><li><span><a href=\"#Definitions\" data-toc-modified-id=\"Definitions-7.5.1\"><span class=\"toc-item-num\">7.5.1&nbsp;&nbsp;</span>Definitions</a></span><ul class=\"toc-item\"><li><span><a href=\"#Electrons\" data-toc-modified-id=\"Electrons-7.5.1.1\"><span class=\"toc-item-num\">7.5.1.1&nbsp;&nbsp;</span>Electrons</a></span></li><li><span><a href=\"#Phonons\" data-toc-modified-id=\"Phonons-7.5.1.2\"><span class=\"toc-item-num\">7.5.1.2&nbsp;&nbsp;</span>Phonons</a></span></li></ul></li><li><span><a href=\"#Bulk-density-of-states-(DOS)\" data-toc-modified-id=\"Bulk-density-of-states-(DOS)-7.5.2\"><span class=\"toc-item-num\">7.5.2&nbsp;&nbsp;</span>Bulk density-of-states (DOS)</a></span><ul class=\"toc-item\"><li><span><a href=\"#Electrons\" data-toc-modified-id=\"Electrons-7.5.2.1\"><span class=\"toc-item-num\">7.5.2.1&nbsp;&nbsp;</span>Electrons</a></span></li><li><span><a href=\"#Phonons\" data-toc-modified-id=\"Phonons-7.5.2.2\"><span class=\"toc-item-num\">7.5.2.2&nbsp;&nbsp;</span>Phonons</a></span></li></ul></li><li><span><a href=\"#Occupancy:-Distribution-function\" data-toc-modified-id=\"Occupancy:-Distribution-function-7.5.3\"><span class=\"toc-item-num\">7.5.3&nbsp;&nbsp;</span>Occupancy: Distribution function</a></span><ul class=\"toc-item\"><li><span><a href=\"#Electrons\" data-toc-modified-id=\"Electrons-7.5.3.1\"><span class=\"toc-item-num\">7.5.3.1&nbsp;&nbsp;</span>Electrons</a></span></li><li><span><a href=\"#Phonons\" data-toc-modified-id=\"Phonons-7.5.3.2\"><span class=\"toc-item-num\">7.5.3.2&nbsp;&nbsp;</span>Phonons</a></span></li></ul></li><li><span><a href=\"#Population\" data-toc-modified-id=\"Population-7.5.4\"><span class=\"toc-item-num\">7.5.4&nbsp;&nbsp;</span>Population</a></span><ul class=\"toc-item\"><li><span><a href=\"#Electrons\" data-toc-modified-id=\"Electrons-7.5.4.1\"><span class=\"toc-item-num\">7.5.4.1&nbsp;&nbsp;</span>Electrons</a></span></li><li><span><a href=\"#Phonons\" data-toc-modified-id=\"Phonons-7.5.4.2\"><span class=\"toc-item-num\">7.5.4.2&nbsp;&nbsp;</span>Phonons</a></span></li></ul></li><li><span><a href=\"#Current\" data-toc-modified-id=\"Current-7.5.5\"><span class=\"toc-item-num\">7.5.5&nbsp;&nbsp;</span>Current</a></span><ul class=\"toc-item\"><li><span><a href=\"#Electrons\" data-toc-modified-id=\"Electrons-7.5.5.1\"><span class=\"toc-item-num\">7.5.5.1&nbsp;&nbsp;</span>Electrons</a></span></li><li><span><a href=\"#Phonons\" data-toc-modified-id=\"Phonons-7.5.5.2\"><span class=\"toc-item-num\">7.5.5.2&nbsp;&nbsp;</span>Phonons</a></span></li></ul></li><li><span><a href=\"#Unoccupied-state\" data-toc-modified-id=\"Unoccupied-state-7.5.6\"><span class=\"toc-item-num\">7.5.6&nbsp;&nbsp;</span>Unoccupied state</a></span><ul class=\"toc-item\"><li><span><a href=\"#Electrons\" data-toc-modified-id=\"Electrons-7.5.6.1\"><span class=\"toc-item-num\">7.5.6.1&nbsp;&nbsp;</span>Electrons</a></span></li><li><span><a href=\"#Phonons\" data-toc-modified-id=\"Phonons-7.5.6.2\"><span class=\"toc-item-num\">7.5.6.2&nbsp;&nbsp;</span>Phonons</a></span></li></ul></li></ul></li><li><span><a href=\"#Boltzmann-Transport-Equation-(BTE)\" data-toc-modified-id=\"Boltzmann-Transport-Equation-(BTE)-7.6\"><span class=\"toc-item-num\">7.6&nbsp;&nbsp;</span>Boltzmann Transport Equation (BTE)</a></span><ul class=\"toc-item\"><li><span><a href=\"#Derivation-to-physical-model\" data-toc-modified-id=\"Derivation-to-physical-model-7.6.1\"><span class=\"toc-item-num\">7.6.1&nbsp;&nbsp;</span>Derivation to physical model</a></span><ul class=\"toc-item\"><li><span><a href=\"#Motivation\" data-toc-modified-id=\"Motivation-7.6.1.1\"><span class=\"toc-item-num\">7.6.1.1&nbsp;&nbsp;</span>Motivation</a></span></li><li><span><a href=\"#Phonon-equation-of-motion\" data-toc-modified-id=\"Phonon-equation-of-motion-7.6.1.2\"><span class=\"toc-item-num\">7.6.1.2&nbsp;&nbsp;</span>Phonon equation of motion</a></span></li><li><span><a href=\"#Statement-of-BTE\" data-toc-modified-id=\"Statement-of-BTE-7.6.1.3\"><span class=\"toc-item-num\">7.6.1.3&nbsp;&nbsp;</span>Statement of BTE</a></span></li><li><span><a href=\"#Deriving-temperature-from-the-BTE\" data-toc-modified-id=\"Deriving-temperature-from-the-BTE-7.6.1.4\"><span class=\"toc-item-num\">7.6.1.4&nbsp;&nbsp;</span>Deriving temperature from the BTE</a></span></li><li><span><a href=\"#Linearized-phonon-BTE\" data-toc-modified-id=\"Linearized-phonon-BTE-7.6.1.5\"><span class=\"toc-item-num\">7.6.1.5&nbsp;&nbsp;</span>Linearized phonon BTE</a></span></li><li><span><a href=\"#Thermal-current---heat-flow\" data-toc-modified-id=\"Thermal-current---heat-flow-7.6.1.6\"><span class=\"toc-item-num\">7.6.1.6&nbsp;&nbsp;</span>Thermal current - heat flow</a></span></li><li><span><a href=\"#Thermal-conductivity\" data-toc-modified-id=\"Thermal-conductivity-7.6.1.7\"><span class=\"toc-item-num\">7.6.1.7&nbsp;&nbsp;</span>Thermal conductivity</a></span></li></ul></li><li><span><a href=\"#Description-of-scattering-mechanisms\" data-toc-modified-id=\"Description-of-scattering-mechanisms-7.6.2\"><span class=\"toc-item-num\">7.6.2&nbsp;&nbsp;</span>Description of scattering mechanisms</a></span><ul class=\"toc-item\"><li><span><a href=\"#Relaxation-time-approximation\" data-toc-modified-id=\"Relaxation-time-approximation-7.6.2.1\"><span class=\"toc-item-num\">7.6.2.1&nbsp;&nbsp;</span>Relaxation time approximation</a></span></li><li><span><a href=\"#Examples-of-scattering\" data-toc-modified-id=\"Examples-of-scattering-7.6.2.2\"><span class=\"toc-item-num\">7.6.2.2&nbsp;&nbsp;</span>Examples of scattering</a></span></li></ul></li><li><span><a href=\"#Examples-of-thermal-conductivity\" data-toc-modified-id=\"Examples-of-thermal-conductivity-7.6.3\"><span class=\"toc-item-num\">7.6.3&nbsp;&nbsp;</span>Examples of thermal conductivity</a></span><ul class=\"toc-item\"><li><span><a href=\"#Thermal-conductivity-of-Si\" data-toc-modified-id=\"Thermal-conductivity-of-Si-7.6.3.1\"><span class=\"toc-item-num\">7.6.3.1&nbsp;&nbsp;</span>Thermal conductivity of Si</a></span></li><li><span><a href=\"#Thermal-conductivity-of-Si-NW\" data-toc-modified-id=\"Thermal-conductivity-of-Si-NW-7.6.3.2\"><span class=\"toc-item-num\">7.6.3.2&nbsp;&nbsp;</span>Thermal conductivity of Si NW</a></span></li><li><span><a href=\"#Thermal-conductivity-of-InAs\" data-toc-modified-id=\"Thermal-conductivity-of-InAs-7.6.3.3\"><span class=\"toc-item-num\">7.6.3.3&nbsp;&nbsp;</span>Thermal conductivity of InAs</a></span></li></ul></li></ul></li></ul></li><li><span><a href=\"#Nanoscale-Thermal-Modeling-II:-Phonon-dispersion-(8/4)\" data-toc-modified-id=\"Nanoscale-Thermal-Modeling-II:-Phonon-dispersion-(8/4)-8\"><span class=\"toc-item-num\">8&nbsp;&nbsp;</span>Nanoscale Thermal Modeling II: Phonon dispersion (8/4)</a></span><ul class=\"toc-item\"><li><span><a href=\"#Learning-goals\" data-toc-modified-id=\"Learning-goals-8.1\"><span class=\"toc-item-num\">8.1&nbsp;&nbsp;</span>Learning goals</a></span></li><li><span><a href=\"#Summary\" data-toc-modified-id=\"Summary-8.2\"><span class=\"toc-item-num\">8.2&nbsp;&nbsp;</span>Summary</a></span></li><li><span><a href=\"#Outline\" data-toc-modified-id=\"Outline-8.3\"><span class=\"toc-item-num\">8.3&nbsp;&nbsp;</span>Outline</a></span></li><li><span><a href=\"#Phonon-bandstructure\" data-toc-modified-id=\"Phonon-bandstructure-8.4\"><span class=\"toc-item-num\">8.4&nbsp;&nbsp;</span>Phonon bandstructure</a></span><ul class=\"toc-item\"><li><span><a href=\"#Why-do-we-need-this-quantity?\" data-toc-modified-id=\"Why-do-we-need-this-quantity?-8.4.1\"><span class=\"toc-item-num\">8.4.1&nbsp;&nbsp;</span>Why do we need this quantity?</a></span><ul class=\"toc-item\"><li><span><a href=\"#Thermal-conductivity-recap\" data-toc-modified-id=\"Thermal-conductivity-recap-8.4.1.1\"><span class=\"toc-item-num\">8.4.1.1&nbsp;&nbsp;</span>Thermal conductivity recap</a></span></li></ul></li><li><span><a href=\"#Ingredients-for-$\\kappa$-calculation:-Require-phonon-band-structure\" data-toc-modified-id=\"Ingredients-for-$\\kappa$-calculation:-Require-phonon-band-structure-8.4.2\"><span class=\"toc-item-num\">8.4.2&nbsp;&nbsp;</span>Ingredients for $\\kappa$ calculation: Require phonon band structure</a></span><ul class=\"toc-item\"><li><span><a href=\"#Phonon-density-of-states\" data-toc-modified-id=\"Phonon-density-of-states-8.4.2.1\"><span class=\"toc-item-num\">8.4.2.1&nbsp;&nbsp;</span>Phonon density-of-states</a></span></li><li><span><a href=\"#Phonon-velocity\" data-toc-modified-id=\"Phonon-velocity-8.4.2.2\"><span class=\"toc-item-num\">8.4.2.2&nbsp;&nbsp;</span>Phonon velocity</a></span></li><li><span><a href=\"#Relaxation-time-for-scattering-type-(hard/not-discussed)\" data-toc-modified-id=\"Relaxation-time-for-scattering-type-(hard/not-discussed)-8.4.2.3\"><span class=\"toc-item-num\">8.4.2.3&nbsp;&nbsp;</span>Relaxation time for scattering type (hard/not discussed)</a></span></li></ul></li><li><span><a href=\"#Example-(recap):-Phonon-dispersion-in-Si\" data-toc-modified-id=\"Example-(recap):-Phonon-dispersion-in-Si-8.4.3\"><span class=\"toc-item-num\">8.4.3&nbsp;&nbsp;</span>Example (recap): Phonon dispersion in Si</a></span><ul class=\"toc-item\"><li><span><a href=\"#Acoustic-phonons\" data-toc-modified-id=\"Acoustic-phonons-8.4.3.1\"><span class=\"toc-item-num\">8.4.3.1&nbsp;&nbsp;</span>Acoustic phonons</a></span></li><li><span><a href=\"#Optical-phonons\" data-toc-modified-id=\"Optical-phonons-8.4.3.2\"><span class=\"toc-item-num\">8.4.3.2&nbsp;&nbsp;</span>Optical phonons</a></span></li><li><span><a href=\"#Transverse-branches\" data-toc-modified-id=\"Transverse-branches-8.4.3.3\"><span class=\"toc-item-num\">8.4.3.3&nbsp;&nbsp;</span>Transverse branches</a></span></li><li><span><a href=\"#Longitudinal-branches\" data-toc-modified-id=\"Longitudinal-branches-8.4.3.4\"><span class=\"toc-item-num\">8.4.3.4&nbsp;&nbsp;</span>Longitudinal branches</a></span></li><li><span><a href=\"#Phonon-velocity-as-a-derivative-of-frequency-w.r.t.-momentum\" data-toc-modified-id=\"Phonon-velocity-as-a-derivative-of-frequency-w.r.t.-momentum-8.4.3.5\"><span class=\"toc-item-num\">8.4.3.5&nbsp;&nbsp;</span>Phonon velocity as a derivative of frequency w.r.t. momentum</a></span></li></ul></li><li><span><a href=\"#Example:-Other-phonon-dispersions\" data-toc-modified-id=\"Example:-Other-phonon-dispersions-8.4.4\"><span class=\"toc-item-num\">8.4.4&nbsp;&nbsp;</span>Example: Other phonon dispersions</a></span><ul class=\"toc-item\"><li><span><a href=\"#Polar-semiconductor-(InAs):-LO/TO-split\" data-toc-modified-id=\"Polar-semiconductor-(InAs):-LO/TO-split-8.4.4.1\"><span class=\"toc-item-num\">8.4.4.1&nbsp;&nbsp;</span>Polar semiconductor (InAs): LO/TO split</a></span></li><li><span><a href=\"#Graphene:-ZA,-ZO-modes-out-of-plane\" data-toc-modified-id=\"Graphene:-ZA,-ZO-modes-out-of-plane-8.4.4.2\"><span class=\"toc-item-num\">8.4.4.2&nbsp;&nbsp;</span>Graphene: ZA, ZO modes out-of-plane</a></span></li></ul></li></ul></li><li><span><a href=\"#Classical-phonon-bandstructure-calculation:-Newton/Hooke\" data-toc-modified-id=\"Classical-phonon-bandstructure-calculation:-Newton/Hooke-8.5\"><span class=\"toc-item-num\">8.5&nbsp;&nbsp;</span>Classical phonon bandstructure calculation: Newton/Hooke</a></span><ul class=\"toc-item\"><li><span><a href=\"#Simple-1-D-atomic-chain\" data-toc-modified-id=\"Simple-1-D-atomic-chain-8.5.1\"><span class=\"toc-item-num\">8.5.1&nbsp;&nbsp;</span>Simple 1-D atomic chain</a></span><ul class=\"toc-item\"><li><span><a href=\"#Atom-oscillations-by-Newton's-EoM-and-Hooke's-law\" data-toc-modified-id=\"Atom-oscillations-by-Newton's-EoM-and-Hooke's-law-8.5.1.1\"><span class=\"toc-item-num\">8.5.1.1&nbsp;&nbsp;</span>Atom oscillations by Newton's EoM and Hooke's law</a></span></li><li><span><a href=\"#Unit-cell-of-atomic-chain\" data-toc-modified-id=\"Unit-cell-of-atomic-chain-8.5.1.2\"><span class=\"toc-item-num\">8.5.1.2&nbsp;&nbsp;</span>Unit cell of atomic chain</a></span></li><li><span><a href=\"#Period-boundary-conditions\" data-toc-modified-id=\"Period-boundary-conditions-8.5.1.3\"><span class=\"toc-item-num\">8.5.1.3&nbsp;&nbsp;</span>Period boundary conditions</a></span></li><li><span><a href=\"#Result:-LSE-w/-two-coupled-EoM\" data-toc-modified-id=\"Result:-LSE-w/-two-coupled-EoM-8.5.1.4\"><span class=\"toc-item-num\">8.5.1.4&nbsp;&nbsp;</span>Result: LSE w/ two coupled EoM</a></span></li></ul></li><li><span><a href=\"#Dynamical-matrix-of-the-system-from-LSE-of-coupled-EoM\" data-toc-modified-id=\"Dynamical-matrix-of-the-system-from-LSE-of-coupled-EoM-8.5.2\"><span class=\"toc-item-num\">8.5.2&nbsp;&nbsp;</span>Dynamical matrix of the system from LSE of coupled EoM</a></span><ul class=\"toc-item\"><li><span><a href=\"#Eigenvalue-problem-w/-$\\omega^2$-as-eigenvalue\" data-toc-modified-id=\"Eigenvalue-problem-w/-$\\omega^2$-as-eigenvalue-8.5.2.1\"><span class=\"toc-item-num\">8.5.2.1&nbsp;&nbsp;</span>Eigenvalue problem w/ $\\omega^2$ as eigenvalue</a></span></li><li><span><a href=\"#Analytic-solution:--Characteristic-polynomial\" data-toc-modified-id=\"Analytic-solution:--Characteristic-polynomial-8.5.2.2\"><span class=\"toc-item-num\">8.5.2.2&nbsp;&nbsp;</span>Analytic solution:  Characteristic polynomial</a></span></li><li><span><a href=\"#Only-positive-eigenvalues-admissible\" data-toc-modified-id=\"Only-positive-eigenvalues-admissible-8.5.2.3\"><span class=\"toc-item-num\">8.5.2.3&nbsp;&nbsp;</span>Only positive eigenvalues admissible</a></span></li><li><span><a href=\"#Obtain-two-branches-for-1D:-1-optical,-1-acoustic\" data-toc-modified-id=\"Obtain-two-branches-for-1D:-1-optical,-1-acoustic-8.5.2.4\"><span class=\"toc-item-num\">8.5.2.4&nbsp;&nbsp;</span>Obtain two branches for 1D: 1 optical, 1 acoustic</a></span></li><li><span><a href=\"#Optical-branch-oscillation-mode:-out-of-phase-motion\" data-toc-modified-id=\"Optical-branch-oscillation-mode:-out-of-phase-motion-8.5.2.5\"><span class=\"toc-item-num\">8.5.2.5&nbsp;&nbsp;</span>Optical branch oscillation mode: out-of-phase motion</a></span></li><li><span><a href=\"#Acoustic-branch-oscillation-mode:--in-phase-motion\" data-toc-modified-id=\"Acoustic-branch-oscillation-mode:--in-phase-motion-8.5.2.6\"><span class=\"toc-item-num\">8.5.2.6&nbsp;&nbsp;</span>Acoustic branch oscillation mode:  in-phase motion</a></span></li><li><span><a href=\"#Extending-from-1D-to-3D:-6-branches-but-similar-to-1D\" data-toc-modified-id=\"Extending-from-1D-to-3D:-6-branches-but-similar-to-1D-8.5.2.7\"><span class=\"toc-item-num\">8.5.2.7&nbsp;&nbsp;</span>Extending from 1D to 3D: 6 branches but similar to 1D</a></span></li></ul></li><li><span><a href=\"#1D-already-allows-extracting-analytical-parameters\" data-toc-modified-id=\"1D-already-allows-extracting-analytical-parameters-8.5.3\"><span class=\"toc-item-num\">8.5.3&nbsp;&nbsp;</span>1D already allows extracting analytical parameters</a></span><ul class=\"toc-item\"><li><span><a href=\"#DOS-from-phonon-band-structure\" data-toc-modified-id=\"DOS-from-phonon-band-structure-8.5.3.1\"><span class=\"toc-item-num\">8.5.3.1&nbsp;&nbsp;</span>DOS from phonon band structure</a></span></li><li><span><a href=\"#Injection-velocity\" data-toc-modified-id=\"Injection-velocity-8.5.3.2\"><span class=\"toc-item-num\">8.5.3.2&nbsp;&nbsp;</span>Injection velocity</a></span></li></ul></li><li><span><a href=\"#Simplification-by-linearization\" data-toc-modified-id=\"Simplification-by-linearization-8.5.4\"><span class=\"toc-item-num\">8.5.4&nbsp;&nbsp;</span>Simplification by linearization</a></span><ul class=\"toc-item\"><li><span><a href=\"#Phonon-band-structure\" data-toc-modified-id=\"Phonon-band-structure-8.5.4.1\"><span class=\"toc-item-num\">8.5.4.1&nbsp;&nbsp;</span>Phonon band structure</a></span></li><li><span><a href=\"#DOS\" data-toc-modified-id=\"DOS-8.5.4.2\"><span class=\"toc-item-num\">8.5.4.2&nbsp;&nbsp;</span>DOS</a></span></li><li><span><a href=\"#Injection-velocity\" data-toc-modified-id=\"Injection-velocity-8.5.4.3\"><span class=\"toc-item-num\">8.5.4.3&nbsp;&nbsp;</span>Injection velocity</a></span></li></ul></li></ul></li><li><span><a href=\"#Advanced-phonon-bandstructure-calculation:-VFF-and-DFT\" data-toc-modified-id=\"Advanced-phonon-bandstructure-calculation:-VFF-and-DFT-8.6\"><span class=\"toc-item-num\">8.6&nbsp;&nbsp;</span>Advanced phonon bandstructure calculation: VFF and DFT</a></span><ul class=\"toc-item\"><li><span><a href=\"#Harmonic-approximation\" data-toc-modified-id=\"Harmonic-approximation-8.6.1\"><span class=\"toc-item-num\">8.6.1&nbsp;&nbsp;</span>Harmonic approximation</a></span><ul class=\"toc-item\"><li><span><a href=\"#Energy-of-solids-and-the-Hamiltonian\" data-toc-modified-id=\"Energy-of-solids-and-the-Hamiltonian-8.6.1.1\"><span class=\"toc-item-num\">8.6.1.1&nbsp;&nbsp;</span>Energy of solids and the Hamiltonian</a></span></li><li><span><a href=\"#Phonon-amplitude-affects-total-energy-$E$\" data-toc-modified-id=\"Phonon-amplitude-affects-total-energy-$E$-8.6.1.2\"><span class=\"toc-item-num\">8.6.1.2&nbsp;&nbsp;</span>Phonon amplitude affects total energy $E$</a></span></li><li><span><a href=\"#Harmonic-approximation-of-the-total-energy:-2nd-order\" data-toc-modified-id=\"Harmonic-approximation-of-the-total-energy:-2nd-order-8.6.1.3\"><span class=\"toc-item-num\">8.6.1.3&nbsp;&nbsp;</span>Harmonic approximation of the total energy: 2nd order</a></span></li><li><span><a href=\"#Out-of-equilibrium:-Force-from-integrating-Hessian\" data-toc-modified-id=\"Out-of-equilibrium:-Force-from-integrating-Hessian-8.6.1.4\"><span class=\"toc-item-num\">8.6.1.4&nbsp;&nbsp;</span>Out-of-equilibrium: Force from integrating Hessian</a></span></li><li><span><a href=\"#The-dynamical-matrix:-Eigenvalue-problem-as-in-1D-atomic-chain\" data-toc-modified-id=\"The-dynamical-matrix:-Eigenvalue-problem-as-in-1D-atomic-chain-8.6.1.5\"><span class=\"toc-item-num\">8.6.1.5&nbsp;&nbsp;</span>The dynamical matrix: Eigenvalue problem as in 1D atomic chain</a></span></li></ul></li><li><span><a href=\"#Valence-force-field-(VFF)-model\" data-toc-modified-id=\"Valence-force-field-(VFF)-model-8.6.2\"><span class=\"toc-item-num\">8.6.2&nbsp;&nbsp;</span>Valence-force-field (VFF) model</a></span><ul class=\"toc-item\"><li><span><a href=\"#VFF-equals-tight-binding-for-electrons:-An-empirical-method\" data-toc-modified-id=\"VFF-equals-tight-binding-for-electrons:-An-empirical-method-8.6.2.1\"><span class=\"toc-item-num\">8.6.2.1&nbsp;&nbsp;</span>VFF equals tight-binding for electrons: An empirical method</a></span></li><li><span><a href=\"#The-Keating-model\" data-toc-modified-id=\"The-Keating-model-8.6.2.2\"><span class=\"toc-item-num\">8.6.2.2&nbsp;&nbsp;</span>The Keating model</a></span></li><li><span><a href=\"#Extended-VFF-model\" data-toc-modified-id=\"Extended-VFF-model-8.6.2.3\"><span class=\"toc-item-num\">8.6.2.3&nbsp;&nbsp;</span>Extended VFF model</a></span></li></ul></li><li><span><a href=\"#Density-functional-theory-(DFT)-model\" data-toc-modified-id=\"Density-functional-theory-(DFT)-model-8.6.3\"><span class=\"toc-item-num\">8.6.3&nbsp;&nbsp;</span>Density functional theory (DFT) model</a></span><ul class=\"toc-item\"><li><span><a href=\"#Schroedinger-equation-with-$E_{xc}$\" data-toc-modified-id=\"Schroedinger-equation-with-$E_{xc}$-8.6.3.1\"><span class=\"toc-item-num\">8.6.3.1&nbsp;&nbsp;</span>Schroedinger equation with $E_{xc}$</a></span></li><li><span><a href=\"#Charge-density-$\\rho$\" data-toc-modified-id=\"Charge-density-$\\rho$-8.6.3.2\"><span class=\"toc-item-num\">8.6.3.2&nbsp;&nbsp;</span>Charge density $\\rho$</a></span></li><li><span><a href=\"#Exchange-correlation-energy-functional-$E_{xc}[\\rho]$\" data-toc-modified-id=\"Exchange-correlation-energy-functional-$E_{xc}[\\rho]$-8.6.3.3\"><span class=\"toc-item-num\">8.6.3.3&nbsp;&nbsp;</span>Exchange correlation energy functional $E_{xc}[\\rho]$</a></span></li><li><span><a href=\"#Frozen-phonon-approach\" data-toc-modified-id=\"Frozen-phonon-approach-8.6.3.4\"><span class=\"toc-item-num\">8.6.3.4&nbsp;&nbsp;</span>Frozen phonon approach</a></span></li><li><span><a href=\"#Near-perfect-fit-to-experiment-w/o-fitting-parameters\" data-toc-modified-id=\"Near-perfect-fit-to-experiment-w/o-fitting-parameters-8.6.3.5\"><span class=\"toc-item-num\">8.6.3.5&nbsp;&nbsp;</span>Near-perfect fit to experiment w/o fitting parameters</a></span></li><li><span><a href=\"#More-efficient:-density-functional-perturbation-theory\" data-toc-modified-id=\"More-efficient:-density-functional-perturbation-theory-8.6.3.6\"><span class=\"toc-item-num\">8.6.3.6&nbsp;&nbsp;</span>More efficient: density functional perturbation theory</a></span></li></ul></li></ul></li></ul></li><li><span><a href=\"#Phonon-Quantum-Transport-(22/4)\" data-toc-modified-id=\"Phonon-Quantum-Transport-(22/4)-9\"><span class=\"toc-item-num\">9&nbsp;&nbsp;</span>Phonon Quantum Transport (22/4)</a></span><ul class=\"toc-item\"><li><span><a href=\"#Learning-goals\" data-toc-modified-id=\"Learning-goals-9.1\"><span class=\"toc-item-num\">9.1&nbsp;&nbsp;</span>Learning goals</a></span></li><li><span><a href=\"#Summary\" data-toc-modified-id=\"Summary-9.2\"><span class=\"toc-item-num\">9.2&nbsp;&nbsp;</span>Summary</a></span></li><li><span><a href=\"#Outline\" data-toc-modified-id=\"Outline-9.3\"><span class=\"toc-item-num\">9.3&nbsp;&nbsp;</span>Outline</a></span></li><li><span><a href=\"#Boundary-conditions\" data-toc-modified-id=\"Boundary-conditions-9.4\"><span class=\"toc-item-num\">9.4&nbsp;&nbsp;</span>Boundary conditions</a></span><ul class=\"toc-item\"><li><span><a href=\"#Intro/Recap\" data-toc-modified-id=\"Intro/Recap-9.4.1\"><span class=\"toc-item-num\">9.4.1&nbsp;&nbsp;</span>Intro/Recap</a></span><ul class=\"toc-item\"><li><span><a href=\"#Semi-classical-approach-vs.-QM-approach-for-phonon-transport\" data-toc-modified-id=\"Semi-classical-approach-vs.-QM-approach-for-phonon-transport-9.4.1.1\"><span class=\"toc-item-num\">9.4.1.1&nbsp;&nbsp;</span>Semi-classical approach vs. QM approach for phonon transport</a></span></li><li><span><a href=\"#Recap:-1D-phonon-model\" data-toc-modified-id=\"Recap:-1D-phonon-model-9.4.1.2\"><span class=\"toc-item-num\">9.4.1.2&nbsp;&nbsp;</span>Recap: 1D phonon model</a></span></li><li><span><a href=\"#Phonon-EoM\" data-toc-modified-id=\"Phonon-EoM-9.4.1.3\"><span class=\"toc-item-num\">9.4.1.3&nbsp;&nbsp;</span>Phonon EoM</a></span></li><li><span><a href=\"#Generalized-dynamical-equation\" data-toc-modified-id=\"Generalized-dynamical-equation-9.4.1.4\"><span class=\"toc-item-num\">9.4.1.4&nbsp;&nbsp;</span>Generalized dynamical equation</a></span></li></ul></li><li><span><a href=\"#Periodic-boundary-conditions\" data-toc-modified-id=\"Periodic-boundary-conditions-9.4.2\"><span class=\"toc-item-num\">9.4.2&nbsp;&nbsp;</span>Periodic boundary conditions</a></span><ul class=\"toc-item\"><li><span><a href=\"#Periodic-boundary-conditions:-Infinite-length\" data-toc-modified-id=\"Periodic-boundary-conditions:-Infinite-length-9.4.2.1\"><span class=\"toc-item-num\">9.4.2.1&nbsp;&nbsp;</span>Periodic boundary conditions: Infinite length</a></span></li><li><span><a href=\"#Simple-phonon-bandstructure\" data-toc-modified-id=\"Simple-phonon-bandstructure-9.4.2.2\"><span class=\"toc-item-num\">9.4.2.2&nbsp;&nbsp;</span>Simple phonon bandstructure</a></span></li></ul></li><li><span><a href=\"#Closed-boundary-conditions\" data-toc-modified-id=\"Closed-boundary-conditions-9.4.3\"><span class=\"toc-item-num\">9.4.3&nbsp;&nbsp;</span>Closed boundary conditions</a></span><ul class=\"toc-item\"><li><span><a href=\"#Closed-boundary-conditions:-Finite-length\" data-toc-modified-id=\"Closed-boundary-conditions:-Finite-length-9.4.3.1\"><span class=\"toc-item-num\">9.4.3.1&nbsp;&nbsp;</span>Closed boundary conditions: Finite length</a></span></li><li><span><a href=\"#Discrete-phonon-frequencies\" data-toc-modified-id=\"Discrete-phonon-frequencies-9.4.3.2\"><span class=\"toc-item-num\">9.4.3.2&nbsp;&nbsp;</span>Discrete phonon frequencies</a></span></li></ul></li><li><span><a href=\"#Open-boundary-conditions\" data-toc-modified-id=\"Open-boundary-conditions-9.4.4\"><span class=\"toc-item-num\">9.4.4&nbsp;&nbsp;</span>Open boundary conditions</a></span><ul class=\"toc-item\"><li><span><a href=\"#Open-boundary-conditions:-Quasi-infinite-length\" data-toc-modified-id=\"Open-boundary-conditions:-Quasi-infinite-length-9.4.4.1\"><span class=\"toc-item-num\">9.4.4.1&nbsp;&nbsp;</span>Open boundary conditions: Quasi-infinite length</a></span></li></ul></li></ul></li><li><span><a href=\"#Quantum-transport-approach\" data-toc-modified-id=\"Quantum-transport-approach-9.5\"><span class=\"toc-item-num\">9.5&nbsp;&nbsp;</span>Quantum transport approach</a></span><ul class=\"toc-item\"><li><span><a href=\"#Definition-of-contacts/reservoirs\" data-toc-modified-id=\"Definition-of-contacts/reservoirs-9.5.1\"><span class=\"toc-item-num\">9.5.1&nbsp;&nbsp;</span>Definition of contacts/reservoirs</a></span><ul class=\"toc-item\"><li><span><a href=\"#Division-of-simulation-domain\" data-toc-modified-id=\"Division-of-simulation-domain-9.5.1.1\"><span class=\"toc-item-num\">9.5.1.1&nbsp;&nbsp;</span>Division of simulation domain</a></span></li><li><span><a href=\"#Contact-properties\" data-toc-modified-id=\"Contact-properties-9.5.1.2\"><span class=\"toc-item-num\">9.5.1.2&nbsp;&nbsp;</span>Contact properties</a></span></li><li><span><a href=\"#Physical-interpretation\" data-toc-modified-id=\"Physical-interpretation-9.5.1.3\"><span class=\"toc-item-num\">9.5.1.3&nbsp;&nbsp;</span>Physical interpretation</a></span></li></ul></li><li><span><a href=\"#Derivation-of-the-Wave-Function-formalism\" data-toc-modified-id=\"Derivation-of-the-Wave-Function-formalism-9.5.2\"><span class=\"toc-item-num\">9.5.2&nbsp;&nbsp;</span>Derivation of the Wave Function formalism</a></span><ul class=\"toc-item\"><li><span><a href=\"#Connection-to-device\" data-toc-modified-id=\"Connection-to-device-9.5.2.1\"><span class=\"toc-item-num\">9.5.2.1&nbsp;&nbsp;</span>Connection to device</a></span></li><li><span><a href=\"#Hierarchy-truncation\" data-toc-modified-id=\"Hierarchy-truncation-9.5.2.2\"><span class=\"toc-item-num\">9.5.2.2&nbsp;&nbsp;</span>Hierarchy truncation</a></span></li><li><span><a href=\"#Variable-elimination\" data-toc-modified-id=\"Variable-elimination-9.5.2.3\"><span class=\"toc-item-num\">9.5.2.3&nbsp;&nbsp;</span>Variable elimination</a></span></li><li><span><a href=\"#Wave-Function-formalism\" data-toc-modified-id=\"Wave-Function-formalism-9.5.2.4\"><span class=\"toc-item-num\">9.5.2.4&nbsp;&nbsp;</span>Wave Function formalism</a></span></li></ul></li><li><span><a href=\"#DOS-and-transmission-function\" data-toc-modified-id=\"DOS-and-transmission-function-9.5.3\"><span class=\"toc-item-num\">9.5.3&nbsp;&nbsp;</span>DOS and transmission function</a></span><ul class=\"toc-item\"><li><span><a href=\"#Solution-of-the-WF-formalism\" data-toc-modified-id=\"Solution-of-the-WF-formalism-9.5.3.1\"><span class=\"toc-item-num\">9.5.3.1&nbsp;&nbsp;</span>Solution of the WF formalism</a></span></li><li><span><a href=\"#DOS-and-Transmission\" data-toc-modified-id=\"DOS-and-Transmission-9.5.3.2\"><span class=\"toc-item-num\">9.5.3.2&nbsp;&nbsp;</span>DOS and Transmission</a></span></li><li><span><a href=\"#Homogeneous-system:-Example\" data-toc-modified-id=\"Homogeneous-system:-Example-9.5.3.3\"><span class=\"toc-item-num\">9.5.3.3&nbsp;&nbsp;</span>Homogeneous system: Example</a></span></li><li><span><a href=\"#Inhomogeneous-system:-Example\" data-toc-modified-id=\"Inhomogeneous-system:-Example-9.5.3.4\"><span class=\"toc-item-num\">9.5.3.4&nbsp;&nbsp;</span>Inhomogeneous system: Example</a></span></li><li><span><a href=\"#Heat-current\" data-toc-modified-id=\"Heat-current-9.5.3.5\"><span class=\"toc-item-num\">9.5.3.5&nbsp;&nbsp;</span>Heat current</a></span></li></ul></li><li><span><a href=\"#Non-equilibrium-Green\u2019s-Function\" data-toc-modified-id=\"Non-equilibrium-Green\u2019s-Function-9.5.4\"><span class=\"toc-item-num\">9.5.4&nbsp;&nbsp;</span>Non-equilibrium Green\u2019s Function</a></span><ul class=\"toc-item\"><li><span><a href=\"#Green\u2019s-Functions-in-general\" data-toc-modified-id=\"Green\u2019s-Functions-in-general-9.5.4.1\"><span class=\"toc-item-num\">9.5.4.1&nbsp;&nbsp;</span>Green\u2019s Functions in general</a></span></li><li><span><a href=\"#Phonon-Green\u2019s-Functions\" data-toc-modified-id=\"Phonon-Green\u2019s-Functions-9.5.4.2\"><span class=\"toc-item-num\">9.5.4.2&nbsp;&nbsp;</span>Phonon Green\u2019s Functions</a></span></li></ul></li></ul></li></ul></li><li><span><a href=\"#Thermoelectric-Power-Generators-(29/4)\" data-toc-modified-id=\"Thermoelectric-Power-Generators-(29/4)-10\"><span class=\"toc-item-num\">10&nbsp;&nbsp;</span>Thermoelectric Power Generators (29/4)</a></span><ul class=\"toc-item\"><li><span><a href=\"#Learning-goals\" data-toc-modified-id=\"Learning-goals-10.1\"><span class=\"toc-item-num\">10.1&nbsp;&nbsp;</span>Learning goals</a></span></li><li><span><a href=\"#Summary\" data-toc-modified-id=\"Summary-10.2\"><span class=\"toc-item-num\">10.2&nbsp;&nbsp;</span>Summary</a></span></li><li><span><a href=\"#Outline\" data-toc-modified-id=\"Outline-10.3\"><span class=\"toc-item-num\">10.3&nbsp;&nbsp;</span>Outline</a></span></li><li><span><a href=\"#Thermoelectricity:-an-introduction\" data-toc-modified-id=\"Thermoelectricity:-an-introduction-10.4\"><span class=\"toc-item-num\">10.4&nbsp;&nbsp;</span>Thermoelectricity: an introduction</a></span><ul class=\"toc-item\"><li><span><a href=\"#How-to-recycle-waste-heat?\" data-toc-modified-id=\"How-to-recycle-waste-heat?-10.4.1\"><span class=\"toc-item-num\">10.4.1&nbsp;&nbsp;</span>How to recycle waste heat?</a></span><ul class=\"toc-item\"><li><span><a href=\"#Energy-Consumption-in-US\" data-toc-modified-id=\"Energy-Consumption-in-US-10.4.1.1\"><span class=\"toc-item-num\">10.4.1.1&nbsp;&nbsp;</span>Energy Consumption in US</a></span></li><li><span><a href=\"#Waste-heat\" data-toc-modified-id=\"Waste-heat-10.4.1.2\"><span class=\"toc-item-num\">10.4.1.2&nbsp;&nbsp;</span>Waste heat</a></span></li><li><span><a href=\"#Thermoelectricity\" data-toc-modified-id=\"Thermoelectricity-10.4.1.3\"><span class=\"toc-item-num\">10.4.1.3&nbsp;&nbsp;</span>Thermoelectricity</a></span></li></ul></li><li><span><a href=\"#ZT-figure-of-merit\" data-toc-modified-id=\"ZT-figure-of-merit-10.4.2\"><span class=\"toc-item-num\">10.4.2&nbsp;&nbsp;</span>ZT figure of merit</a></span><ul class=\"toc-item\"><li><span><a href=\"#Thermoelectric-generator\" data-toc-modified-id=\"Thermoelectric-generator-10.4.2.1\"><span class=\"toc-item-num\">10.4.2.1&nbsp;&nbsp;</span>Thermoelectric generator</a></span></li><li><span><a href=\"#Thermoelectric-efficiency\" data-toc-modified-id=\"Thermoelectric-efficiency-10.4.2.2\"><span class=\"toc-item-num\">10.4.2.2&nbsp;&nbsp;</span>Thermoelectric efficiency</a></span></li><li><span><a href=\"#\ud835\udc81\ud835\udc7b-definition-and-interpretation\" data-toc-modified-id=\"\ud835\udc81\ud835\udc7b-definition-and-interpretation-10.4.2.3\"><span class=\"toc-item-num\">10.4.2.3&nbsp;&nbsp;</span>\ud835\udc81\ud835\udc7b definition and interpretation</a></span></li><li><span><a href=\"#Representative-ZT-examples\" data-toc-modified-id=\"Representative-ZT-examples-10.4.2.4\"><span class=\"toc-item-num\">10.4.2.4&nbsp;&nbsp;</span>Representative ZT examples</a></span></li></ul></li><li><span><a href=\"#From-bulk-to-nanostructures\" data-toc-modified-id=\"From-bulk-to-nanostructures-10.4.3\"><span class=\"toc-item-num\">10.4.3&nbsp;&nbsp;</span>From bulk to nanostructures</a></span><ul class=\"toc-item\"><li><span><a href=\"#From-bulk-to-nanostructures:-Theory-historical-perspective\" data-toc-modified-id=\"From-bulk-to-nanostructures:-Theory-historical-perspective-10.4.3.1\"><span class=\"toc-item-num\">10.4.3.1&nbsp;&nbsp;</span>From bulk to nanostructures: Theory historical perspective</a></span></li><li><span><a href=\"#Theory-validation\" data-toc-modified-id=\"Theory-validation-10.4.3.2\"><span class=\"toc-item-num\">10.4.3.2&nbsp;&nbsp;</span>Theory validation</a></span></li><li><span><a href=\"#Rough-Si-nanowires\" data-toc-modified-id=\"Rough-Si-nanowires-10.4.3.3\"><span class=\"toc-item-num\">10.4.3.3&nbsp;&nbsp;</span>Rough Si nanowires</a></span></li></ul></li></ul></li><li><span><a href=\"#Mathematical-formulation\" data-toc-modified-id=\"Mathematical-formulation-10.5\"><span class=\"toc-item-num\">10.5&nbsp;&nbsp;</span>Mathematical formulation</a></span><ul class=\"toc-item\"><li><span><a href=\"#Current-and-conductance\" data-toc-modified-id=\"Current-and-conductance-10.5.1\"><span class=\"toc-item-num\">10.5.1&nbsp;&nbsp;</span>Current and conductance</a></span><ul class=\"toc-item\"><li><span><a href=\"#Calculation-of-\ud835\udc81\ud835\udc7b\" data-toc-modified-id=\"Calculation-of-\ud835\udc81\ud835\udc7b-10.5.1.1\"><span class=\"toc-item-num\">10.5.1.1&nbsp;&nbsp;</span>Calculation of \ud835\udc81\ud835\udc7b</a></span></li><li><span><a href=\"#\ud835\udc81\ud835\udc7b-ingredients\" data-toc-modified-id=\"\ud835\udc81\ud835\udc7b-ingredients-10.5.1.2\"><span class=\"toc-item-num\">10.5.1.2&nbsp;&nbsp;</span>\ud835\udc81\ud835\udc7b ingredients</a></span></li><li><span><a href=\"#Current-flows\" data-toc-modified-id=\"Current-flows-10.5.1.3\"><span class=\"toc-item-num\">10.5.1.3&nbsp;&nbsp;</span>Current flows</a></span></li><li><span><a href=\"#Conductance-definition\" data-toc-modified-id=\"Conductance-definition-10.5.1.4\"><span class=\"toc-item-num\">10.5.1.4&nbsp;&nbsp;</span>Conductance definition</a></span></li></ul></li><li><span><a href=\"#Electrical-and-thermal-components\" data-toc-modified-id=\"Electrical-and-thermal-components-10.5.2\"><span class=\"toc-item-num\">10.5.2&nbsp;&nbsp;</span>Electrical and thermal components</a></span><ul class=\"toc-item\"><li><span><a href=\"#Electrical-currents-by-electrons\" data-toc-modified-id=\"Electrical-currents-by-electrons-10.5.2.1\"><span class=\"toc-item-num\">10.5.2.1&nbsp;&nbsp;</span>Electrical currents by electrons</a></span></li><li><span><a href=\"#Electrical-current-linearization\" data-toc-modified-id=\"Electrical-current-linearization-10.5.2.2\"><span class=\"toc-item-num\">10.5.2.2&nbsp;&nbsp;</span>Electrical current linearization</a></span></li><li><span><a href=\"#Thermal-current-from-electrons\" data-toc-modified-id=\"Thermal-current-from-electrons-10.5.2.3\"><span class=\"toc-item-num\">10.5.2.3&nbsp;&nbsp;</span>Thermal current from electrons</a></span></li><li><span><a href=\"#Simplification-and-generalization\" data-toc-modified-id=\"Simplification-and-generalization-10.5.2.4\"><span class=\"toc-item-num\">10.5.2.4&nbsp;&nbsp;</span>Simplification and generalization</a></span></li><li><span><a href=\"#Thermal-current-from-phonons\" data-toc-modified-id=\"Thermal-current-from-phonons-10.5.2.5\"><span class=\"toc-item-num\">10.5.2.5&nbsp;&nbsp;</span>Thermal current from phonons</a></span></li><li><span><a href=\"#Calculation-of-\ud835\udc81\ud835\udc7b\" data-toc-modified-id=\"Calculation-of-\ud835\udc81\ud835\udc7b-10.5.2.6\"><span class=\"toc-item-num\">10.5.2.6&nbsp;&nbsp;</span>Calculation of \ud835\udc81\ud835\udc7b</a></span></li></ul></li><li><span><a href=\"#Simulation-example\" data-toc-modified-id=\"Simulation-example-10.5.3\"><span class=\"toc-item-num\">10.5.3&nbsp;&nbsp;</span>Simulation example</a></span><ul class=\"toc-item\"><li><span><a href=\"#\ud835\udc81\ud835\udc7b-summary\" data-toc-modified-id=\"\ud835\udc81\ud835\udc7b-summary-10.5.3.1\"><span class=\"toc-item-num\">10.5.3.1&nbsp;&nbsp;</span>\ud835\udc81\ud835\udc7b summary</a></span></li><li><span><a href=\"#Example:-Si-nanowire\" data-toc-modified-id=\"Example:-Si-nanowire-10.5.3.2\"><span class=\"toc-item-num\">10.5.3.2&nbsp;&nbsp;</span>Example: Si nanowire</a></span></li><li><span><a href=\"#Electron/phonon-transmission\" data-toc-modified-id=\"Electron/phonon-transmission-10.5.3.3\"><span class=\"toc-item-num\">10.5.3.3&nbsp;&nbsp;</span>Electron/phonon transmission</a></span></li><li><span><a href=\"#\ud835\udc72\ud835\udfce,-\ud835\udc72\ud835\udfcf,-\ud835\udc72\ud835\udfd0,-and-\ud835\udc73\ud835\udfd0\" data-toc-modified-id=\"\ud835\udc72\ud835\udfce,-\ud835\udc72\ud835\udfcf,-\ud835\udc72\ud835\udfd0,-and-\ud835\udc73\ud835\udfd0-10.5.3.4\"><span class=\"toc-item-num\">10.5.3.4&nbsp;&nbsp;</span>\ud835\udc72\ud835\udfce, \ud835\udc72\ud835\udfcf, \ud835\udc72\ud835\udfd0, and \ud835\udc73\ud835\udfd0</a></span></li><li><span><a href=\"#\ud835\udc81\ud835\udc7b-results\" data-toc-modified-id=\"\ud835\udc81\ud835\udc7b-results-10.5.3.5\"><span class=\"toc-item-num\">10.5.3.5&nbsp;&nbsp;</span>\ud835\udc81\ud835\udc7b results</a></span></li></ul></li></ul></li></ul></li><li><span><a href=\"#Numerics-and-Parallelization-(6/5)\" data-toc-modified-id=\"Numerics-and-Parallelization-(6/5)-11\"><span class=\"toc-item-num\">11&nbsp;&nbsp;</span>Numerics and Parallelization (6/5)</a></span><ul class=\"toc-item\"><li><span><a href=\"#Learning-goals\" data-toc-modified-id=\"Learning-goals-11.1\"><span class=\"toc-item-num\">11.1&nbsp;&nbsp;</span>Learning goals</a></span></li><li><span><a href=\"#Summary\" data-toc-modified-id=\"Summary-11.2\"><span class=\"toc-item-num\">11.2&nbsp;&nbsp;</span>Summary</a></span></li><li><span><a href=\"#Outline\" data-toc-modified-id=\"Outline-11.3\"><span class=\"toc-item-num\">11.3&nbsp;&nbsp;</span>Outline</a></span></li><li><span><a href=\"#Basic-numerical-operations\" data-toc-modified-id=\"Basic-numerical-operations-11.4\"><span class=\"toc-item-num\">11.4&nbsp;&nbsp;</span>Basic numerical operations</a></span><ul class=\"toc-item\"><li><span><a href=\"#BLAS/LAPACK-libraries\" data-toc-modified-id=\"BLAS/LAPACK-libraries-11.4.1\"><span class=\"toc-item-num\">11.4.1&nbsp;&nbsp;</span>BLAS/LAPACK libraries</a></span><ul class=\"toc-item\"><li><span><a href=\"#Basic-operations\" data-toc-modified-id=\"Basic-operations-11.4.1.1\"><span class=\"toc-item-num\">11.4.1.1&nbsp;&nbsp;</span>Basic operations</a></span></li><li><span><a href=\"#BLAS\" data-toc-modified-id=\"BLAS-11.4.1.2\"><span class=\"toc-item-num\">11.4.1.2&nbsp;&nbsp;</span>BLAS</a></span></li><li><span><a href=\"#Eigenvalue-(EV)-problems\" data-toc-modified-id=\"Eigenvalue-(EV)-problems-11.4.1.3\"><span class=\"toc-item-num\">11.4.1.3&nbsp;&nbsp;</span>Eigenvalue (EV) problems</a></span></li><li><span><a href=\"#LAPACK\" data-toc-modified-id=\"LAPACK-11.4.1.4\"><span class=\"toc-item-num\">11.4.1.4&nbsp;&nbsp;</span>LAPACK</a></span></li><li><span><a href=\"#Calling-BLAS/LAPACK\" data-toc-modified-id=\"Calling-BLAS/LAPACK-11.4.1.5\"><span class=\"toc-item-num\">11.4.1.5&nbsp;&nbsp;</span>Calling BLAS/LAPACK</a></span></li><li><span><a href=\"#Vendor-libraries\" data-toc-modified-id=\"Vendor-libraries-11.4.1.6\"><span class=\"toc-item-num\">11.4.1.6&nbsp;&nbsp;</span>Vendor libraries</a></span></li></ul></li><li><span><a href=\"#Parallelization-strategies\" data-toc-modified-id=\"Parallelization-strategies-11.4.2\"><span class=\"toc-item-num\">11.4.2&nbsp;&nbsp;</span>Parallelization strategies</a></span><ul class=\"toc-item\"><li><span><a href=\"#Shared-vs.-distributed-memory\" data-toc-modified-id=\"Shared-vs.-distributed-memory-11.4.2.1\"><span class=\"toc-item-num\">11.4.2.1&nbsp;&nbsp;</span>Shared vs. distributed memory</a></span></li><li><span><a href=\"#Shared-memory-parallelization\" data-toc-modified-id=\"Shared-memory-parallelization-11.4.2.2\"><span class=\"toc-item-num\">11.4.2.2&nbsp;&nbsp;</span>Shared memory parallelization</a></span></li><li><span><a href=\"#OpenMP-example:-\ud835\udc6a-=-\ud835\udc68\ud835\udc69\" data-toc-modified-id=\"OpenMP-example:-\ud835\udc6a-=-\ud835\udc68\ud835\udc69-11.4.2.3\"><span class=\"toc-item-num\">11.4.2.3&nbsp;&nbsp;</span>OpenMP example: \ud835\udc6a = \ud835\udc68\ud835\udc69</a></span></li><li><span><a href=\"#OpenMP-timing-results\" data-toc-modified-id=\"OpenMP-timing-results-11.4.2.4\"><span class=\"toc-item-num\">11.4.2.4&nbsp;&nbsp;</span>OpenMP timing results</a></span></li><li><span><a href=\"#Distributed-memory-parallelization\" data-toc-modified-id=\"Distributed-memory-parallelization-11.4.2.5\"><span class=\"toc-item-num\">11.4.2.5&nbsp;&nbsp;</span>Distributed memory parallelization</a></span></li><li><span><a href=\"#MPI-example:-\ud835\udc6a-=-\ud835\udc68\ud835\udc69\" data-toc-modified-id=\"MPI-example:-\ud835\udc6a-=-\ud835\udc68\ud835\udc69-11.4.2.6\"><span class=\"toc-item-num\">11.4.2.6&nbsp;&nbsp;</span>MPI example: \ud835\udc6a = \ud835\udc68\ud835\udc69</a></span></li><li><span><a href=\"#MPI-timing-results\" data-toc-modified-id=\"MPI-timing-results-11.4.2.7\"><span class=\"toc-item-num\">11.4.2.7&nbsp;&nbsp;</span>MPI timing results</a></span></li></ul></li><li><span><a href=\"#Graphics-processing-units-(GPUs)\" data-toc-modified-id=\"Graphics-processing-units-(GPUs)-11.4.3\"><span class=\"toc-item-num\">11.4.3&nbsp;&nbsp;</span>Graphics processing units (GPUs)</a></span><ul class=\"toc-item\"><li><span><a href=\"#GPU-architecture\" data-toc-modified-id=\"GPU-architecture-11.4.3.1\"><span class=\"toc-item-num\">11.4.3.1&nbsp;&nbsp;</span>GPU architecture</a></span></li><li><span><a href=\"#GPU-example-\ud835\udc6a-=-\ud835\udc68\ud835\udc69\" data-toc-modified-id=\"GPU-example-\ud835\udc6a-=-\ud835\udc68\ud835\udc69-11.4.3.2\"><span class=\"toc-item-num\">11.4.3.2&nbsp;&nbsp;</span>GPU example \ud835\udc6a = \ud835\udc68\ud835\udc69</a></span></li><li><span><a href=\"#GPU-timing-results\" data-toc-modified-id=\"GPU-timing-results-11.4.3.3\"><span class=\"toc-item-num\">11.4.3.3&nbsp;&nbsp;</span>GPU timing results</a></span></li></ul></li></ul></li><li><span><a href=\"#Open-boundary-calculation\" data-toc-modified-id=\"Open-boundary-calculation-11.5\"><span class=\"toc-item-num\">11.5&nbsp;&nbsp;</span>Open boundary calculation</a></span><ul class=\"toc-item\"><li><span><a href=\"#Generalized-eigenvalue-problem\" data-toc-modified-id=\"Generalized-eigenvalue-problem-11.5.1\"><span class=\"toc-item-num\">11.5.1&nbsp;&nbsp;</span>Generalized eigenvalue problem</a></span><ul class=\"toc-item\"><li><span><a href=\"#Phonon-ballistic-transport\" data-toc-modified-id=\"Phonon-ballistic-transport-11.5.1.1\"><span class=\"toc-item-num\">11.5.1.1&nbsp;&nbsp;</span>Phonon ballistic transport</a></span></li><li><span><a href=\"#Benchmark-structure\" data-toc-modified-id=\"Benchmark-structure-11.5.1.2\"><span class=\"toc-item-num\">11.5.1.2&nbsp;&nbsp;</span>Benchmark structure</a></span></li><li><span><a href=\"#OBC-formulation\" data-toc-modified-id=\"OBC-formulation-11.5.1.3\"><span class=\"toc-item-num\">11.5.1.3&nbsp;&nbsp;</span>OBC formulation</a></span></li><li><span><a href=\"#GEPV-and-shift-and-invert\" data-toc-modified-id=\"GEPV-and-shift-and-invert-11.5.1.4\"><span class=\"toc-item-num\">11.5.1.4&nbsp;&nbsp;</span>GEPV and shift-and-invert</a></span></li><li><span><a href=\"#Timing-standard-solution\" data-toc-modified-id=\"Timing-standard-solution-11.5.1.5\"><span class=\"toc-item-num\">11.5.1.5&nbsp;&nbsp;</span>Timing standard solution</a></span></li></ul></li><li><span><a href=\"#Contour-integral-techniques\" data-toc-modified-id=\"Contour-integral-techniques-11.5.2\"><span class=\"toc-item-num\">11.5.2&nbsp;&nbsp;</span>Contour integral techniques</a></span><ul class=\"toc-item\"><li><span><a href=\"#Physical-observation\" data-toc-modified-id=\"Physical-observation-11.5.2.1\"><span class=\"toc-item-num\">11.5.2.1&nbsp;&nbsp;</span>Physical observation</a></span></li><li><span><a href=\"#Rayleigh-Ritz-projection-method\" data-toc-modified-id=\"Rayleigh-Ritz-projection-method-11.5.2.2\"><span class=\"toc-item-num\">11.5.2.2&nbsp;&nbsp;</span>Rayleigh-Ritz projection method</a></span></li><li><span><a href=\"#Beyn-algorithm\" data-toc-modified-id=\"Beyn-algorithm-11.5.2.3\"><span class=\"toc-item-num\">11.5.2.3&nbsp;&nbsp;</span>Beyn algorithm</a></span></li><li><span><a href=\"#Timing:-OBC-improvement\" data-toc-modified-id=\"Timing:-OBC-improvement-11.5.2.4\"><span class=\"toc-item-num\">11.5.2.4&nbsp;&nbsp;</span>Timing: OBC improvement</a></span></li></ul></li></ul></li><li><span><a href=\"#Solution-of-the-Wave-Function-equation\" data-toc-modified-id=\"Solution-of-the-Wave-Function-equation-11.6\"><span class=\"toc-item-num\">11.6&nbsp;&nbsp;</span>Solution of the Wave Function equation</a></span><ul class=\"toc-item\"><li><span><a href=\"#SplitSolve-algorithm\" data-toc-modified-id=\"SplitSolve-algorithm-11.6.1\"><span class=\"toc-item-num\">11.6.1&nbsp;&nbsp;</span>SplitSolve algorithm</a></span><ul class=\"toc-item\"><li><span><a href=\"#Porting-WF-to-GPUs\" data-toc-modified-id=\"Porting-WF-to-GPUs-11.6.1.1\"><span class=\"toc-item-num\">11.6.1.1&nbsp;&nbsp;</span>Porting WF to GPUs</a></span></li><li><span><a href=\"#SplitSolve-Algorithm\" data-toc-modified-id=\"SplitSolve-Algorithm-11.6.1.2\"><span class=\"toc-item-num\">11.6.1.2&nbsp;&nbsp;</span>SplitSolve Algorithm</a></span></li><li><span><a href=\"#Timing:-SplitSolve\" data-toc-modified-id=\"Timing:-SplitSolve-11.6.1.3\"><span class=\"toc-item-num\">11.6.1.3&nbsp;&nbsp;</span>Timing: SplitSolve</a></span></li></ul></li></ul></li></ul></li></ul></div>\n\n## Introduction (19/2)\n\n- [x] ***processed***\n\n### Thermal effects: A historical perspective\n\n#### Major milestones\n\n##### Ancient times\n##### Early modern period\n##### Modern times\n\n### Why thermal modeling?\n#### Heating: Good and Bad\n\n#### Exposure/implant safety assessment\n##### Exposure safety\n##### Implant safety \n\n#### Thermal therapies\n##### Treatment planning\n##### Novel therapies and devices\n##### Bio-heat modeling\n\n#### Self-heating in nanoscale devices\n##### CBRAM device\n##### Nanodevice design work flow\n##### Electron-Phonon energy exchange\n##### Test device structures\n##### Influence of self-heating\n\n\n## Thermal Modeling (Bio) (26/2)\n\n- [x] ***processed***\n\n### The Pennes Bioheat equation\n\n#### Continuum level thermal modeling\n\n#### Steady state\n\n#### Boundary conditions in the PBE\n\n#### Natural and forced convection\n\n#### Heat radiation\n\n#### Terms of the PBE\n##### Diffusion\n##### Exposure\n##### Metabolism\n##### Perfusion\n\n#### High temperature limit\n\n#### Linear regime: Considering only temperature increase\n\n#### Power deposition\n##### Exposure\n##### RF Dosimetry\n\n#### Beyond PBE\n\n### Application: Mobile Phone Exposure Safety\n\n#### Averaged SAR and temperature increase\n#### Debates and considerations\n\n## Thermal Modeling (Bio) (4/3)\n\n- [X] ***processed***\n\n### The UTCI model\n\n#### Definition of the Universal Thermal Climate Index\n##### Advantages\n##### Disadvantages\n\n#### Tuning & Validation\n\n#### Discretization\n\n#### Coordinate system\n\n### Thermoregulation in UTCI\n\n\n#### Perfusion\n\n#### Heat exchange with environment\n##### Convection\n##### Radiation\n##### Evaporation\n##### Respiration\n\n#### CNS response model\n\n#### Sensation\n\n#### Numerical implementation\n##### Space\n##### Time\n##### Scheme\n\n\n### Application: MRI exposure safety (RF)\n\n#### MRI RF safety\n##### Scenarios\n##### MRI heating\n\n#### Thermal dose\n\n#### Thermal damaga\n\n#### CEM43\n##### Concept\n##### Definition\n##### Tresholds\n##### Advantages of dose-based limits\n\n## Numerical Methods (11/3)\n\n- [X] ***processed***\n\n### Discretization of continuum models\n#### Structured grids\n\n#### Unstructured meshes\n\n### FDTD\n\n#### Temporal discretization\n\n#### Spatial discretization\n\n#### Dealing with interfaces\n\n#### Boundary conditions\n\n#### Staircasing\n\n#### Conformal corrections\n\n#### Stability\n##### CFL criterion\n\n#### Other considerations\n\n### FEM\n\n#### Pros and cons\n#### Overview of the Galerkin method\n\n### Fast Poisson solvers\n\n#### Green's functions\n\n#### Green's function of the PBE\n\n#### Overview of the Fast Poisson method\n\n## Thermal Therapy Treatment Planning (18/3)\n\n- [X] ***processed***\n\n### Introduction\n\n#### Hyperthermic oncology\n\n#### HT energy delivery technology\n\n#### Thermal ablation\n\n#### Temperature modeling\n\n#### Hyperthermic Treatment Planning (HTP)\n##### Embedding in clinlcal flow\n##### Steps in HTP\n##### Motivation\n##### Requirements\n###### Determination of energy deposition\n###### Temperature increase determination\n###### Knowledge about tissue properties\n###### Treatment optimization\n###### Effect & outcome prediction\n###### Clinical integration\n\n### Imaging\n\n#### Definition and objectives\n\n#### Sim4Life framework\n\n### Personalized model generation\n\n#### Implementation\n\n#### Considerations\n\n#### Surface extraction and discretization\n##### Implementation\n##### Considerations\n\n\n### EM modeling\n\n#### Implementation\n\n#### Considerations\n\n### Acoustic modeling\n\n#### Implementation\n\n#### Considerations\n\n### Thermal modeling\n\n#### Implementation\n\n#### Considerations\n\n### The use of HPC\n\n### Optimization\n\n#### Objectives\n\n#### Array steering optimization\n##### Implementation\n##### Considerations\n\n### FUS steering\n\n### Effect quantification\n\n#### Implementation\n\n#### Considerations\n\n\n### Clinical integration\n\n#### Implementation\n\n#### Considerations\n\n### Validation, Verification and Uncertainty Quantification\n\n#### Verification\n\n#### Validation\n##### Local fields\n##### In vivo heating\n\n#### UQ\n\n### Limitations and need for further research\n\n#### Tissue parameters\n\n#### Dynamic tissue models\n\n#### Closed-loop treatment control\n\n#### Clinical integration\n\n#### Effectiveness and outcome prediction\n\n#### Validation and quality assurance\n\n### Conclusions\n\n### Exercise: Fast temperature increase predictions for phased arrays\n\n## Verification and Validation (25/3)\n\n- [X] ***processed***\n\n###  Background\n\n#### Benefits of computational modeling in MedTech and computational life sciences\n\n#### Computational modeling for regulatory submissions\n\n#### Verification and validation standard (ASME, FDA)\n\n#### Multi-physics\n\n#### In vivo issues\n\n#### Benchmarks\n\n#### Context-of-use\n\n#### Uncertainty and sensitivity analysis\n\n\n\n\n### V & V example: FUS Simulator: Solver Verification & Validation\n#### Verification\n##### Critical effects for FDTD implementation of linear acoustic pressure wave model\n##### Method of Manufactured Solutions\n\n#### Validation\n##### Gamma method\n##### UA-Gamma Combination\n##### Measurement setup\n##### Results\n\n### V & V example: MRI Induced Heating: Validation from EM Exposure to in vivo heating\n#### Illustrating Example: MRI RF Exposure\n#### MR RF Safety Background\n##### Limits\n##### Exposure\n##### psSAR & T\n##### T Distribution\n##### pTx vs CP\n\n#### Verification\n##### Coil modeling with Huygens vs direct\n\n#### Validation\n##### Incident E/B-field\n##### Local field - requirements\n##### Local field - experimental setup\n##### Local field - results\n\n##### EM induced heating - setup\n##### EM induced heating - results\n\n##### In vivo heating\n\n### V & V example: EM-neuron interaction: Getting the Quantity-of-interest wrong\n#### EM induced neuro-stimulation\n##### Considerations\n##### Modeling\n##### Results\n\n### V & V example: Computational Human Phantoms\n#### Verification\n#### Validation\n\n### Aspects of Quality Assurance\n\n### Exercise: Method of Manufactured Solutions\n\n## Nanoscale Thermal Modeling I (1/4)\n\n- [X] ***processed***\n\n### Learning goals\n- [ ] the difference between a **temperature-** and a **phonon-based** modeling of heat\n- [ ] when to use the laws of thermodynamics (lectures by Dr. Neufeld) and when to compute the phonon distribution function (this part)\n- [ ] how to compute the **thermal conductivity** of systems and how it looks like in some materials\n- [ ] what are the most relevant **scattering mechanisms** limiting the thermal conductivity of solids and how to describe them\n \n### Summary\n* Definition of thermal current / heat flow\n* \u201cContinuous vs. discrete\u201d calculation of the temperature distribution in solid state-systems\n* Introduction to the Boltzmann Transport Equation\n* Extraction of the thermal conductivity\n\n### Outline\n* From temperature to phonons\n    * When to use what\n* Electron vs. phonon properties\n    * Definition\n    * Density-of-states\n    * Occupancy\n* Boltzmann Transport Equation (BTE)\n    * Derivation of the physical model\n    * Description of scattering mechanisms\n    * Thermal conductivity examples\n\n### From temperature to phonon\n\n#### Introduction\n\n* In solids, heat carried by **phonons**. **Exception**: In **metals, electrons** also contribute significantly\n* **Phonons** == quantized lattice vibrations propagating as waves\n* **Temperature T** == measure of atoms' deviation from equilibrium as they vibrate\n\n\n#### Heat capacity\n\n* characterizing physical property\n* w/ $\\Delta Q$ thermal energy, $\\Delta T$ change of temperature, $V$ volume: \n $C_V = \\frac{\\Delta Q}{\\Delta T}\\Bigr|_{V=\\text{const}}$\n* **isochoric** == $(V=\\text{const})$ \n* w/ $M$ mass: **specific heat capacity** $c_V = \\frac{C_V}{M}$\n\n#### Heat flow\n\n##### Definition of heat flow\n\n* **heat current** $J(c)$ flows from hot to cold in the form of **phonon flow**\n* phonons move w/ average velocity $<\\mathbf{v_x}>$ along $\\mathbf{x}$\n* phonons scatter at surfaces, defects, e/a other\n\n##### Calculation of heat flow\n\nWe consider heat flow $\\mathbf{J_x}$ through a plane $A$ at $x$:\n\n\nand observe:\n\n* at e/a point $\\mathbf{x}$, thermal energy $\\mathbf{Q(x)}$ has 50% chance to move L or R\n* net heat flow $\\mathbf{J(x)}$ is sum of contributions from both sides:\n$\\begin{align}\n\\mathbf{J(x)} & = \\mathbf{J_{\\text{L}\\rightarrow\\text{R}}(x-l_x) + J_{\\text{R}\\rightarrow\\text{L}}(x+l_x)} \\\\\n              & = \\frac{1}{2} \\cdot ((Q(x - l_x) - Q(x + l_x)) \\cdot \\left< v_x \\right> \\cdot \\frac{1}{V}\n\\end{align}$\n\nthen using:\n\n* $Q(x - l_x) - Q(x + l_x) \\approx -2 \\cdot l_x \\cdot \\frac{dQ(x)}{dx}$\n* $Q(x) = f(T(x))$ and hence $\\frac{dQ(x)}{dx} = \\frac{dQ}{dT}\\frac{dT}{dx}$\n* for $\\tau$ avg time btw two scattering events: mean free path along $x$ is $l_x = \\left< v_x \\right>\\cdot\\tau$\n* heat capacity $C_V = \\frac{dQ}{dT}$\n\nwe get:\n$\\begin{align}\nJ(x) & = - l_x \\frac{dQ}{dx} \\left< v_x \\right> \\frac{1}{V} \\nonumber \\\\\nJ(x) & = - l_x \\frac{dQ}{dT}\\frac{dT}{dx} \\left< v_x \\right> \\frac{1}{V} \\nonumber \\\\\nJ(x) & = - \\left< v_x \\right>^2 \\tau C_V \\frac{dT}{dx} \\frac{1}{V} \\nonumber \\\\\nJ(x) & = - \\frac{C_V}{V} {\\left< v_x \\right>}^2 \\tau \\frac{dT}{dx} \\nonumber \\\\\nJ(x) & = - \\kappa\\frac{dT}{dx}\n\\end{align}$\n\nwhere we defined $\\kappa$ as the thermal conductivity:\n\n$ \\kappa = \\frac{C_V}{V}{\\left< v_x \\right>}^2 \\tau$\n\nor in 3D w/ $\\left< v_x \\right> = \\left< v_y \\right> = \\left< v_z \\right>$ and $\\mathbf{\\left< v \\right>}^2 = \\left< v_x \\right>^2 = \\left< v_y \\right>^2 = \\left< v_z \\right>^2$ and $\\left< v \\right> \\tau = l_{\\text{mfp}}$:\n\n$ \\kappa = \\frac{C_V}{3V}{\\left< v \\right>} l_{\\text{mfp}}$\n\n#### Thermal conductivity\n\n* **thermal conductivity** as defined above indicates how well a material conducts heat\n* definition only valid if considered length $L \\gg l_{\\text{mfp}}$ the mean free path length: Macroscopic temperature $T$ unambigously defined\n* $L \\approx l_{\\text{mfp}}$ requires **phonon population distribution**\n\n### Electron vs. phonon\n\nProperty             | Electron                | Phonon\n---------------------|-------------------------|-------\nenergy               | $E$                     | $\\hbar\\omega$\nfrequency            | $\\frac{E}{\\hbar}$       | $\\omega$\nmomentum             | $k$                     | $q$\nband structure       | $E(k) = \\frac{\\hbar^2 k^2}{2m^{*}}$ | $\\omega(q)= \\omega_{\\text{opt}}, v_{\\text{sound}}q$\n\n\n\n#### Definitions\n\n##### Electrons\n\n##### Phonons\n\n#### Bulk density-of-states (DOS)\n\n##### Electrons\n\n##### Phonons\n\n#### Occupancy: Distribution function\n\n##### Electrons\n\n##### Phonons\n\n#### Population\n\n##### Electrons\n\n##### Phonons\n\n#### Current\n\n##### Electrons\n\n##### Phonons\n\n#### Unoccupied state\n\n##### Electrons\n\n##### Phonons\n\n### Boltzmann Transport Equation (BTE)\n\n#### Derivation to physical model\n\n##### Motivation\n\n##### Phonon equation of motion\n\n##### Statement of BTE\n\n##### Deriving temperature from the BTE\n\n##### Linearized phonon BTE\n\n##### Thermal current - heat flow\n\n##### Thermal conductivity\n\n#### Description of scattering mechanisms\n\n##### Relaxation time approximation\n\n##### Examples of scattering\n\n#### Examples of thermal conductivity\n\n##### Thermal conductivity of Si\n\n##### Thermal conductivity of Si NW\n\n##### Thermal conductivity of InAs\n\n## Nanoscale Thermal Modeling II: Phonon dispersion (8/4)\n\n- [X] ***processed***\n\n### Learning goals\n- [ ] why the phonon bandstructure (dispersion) is a relevant quantity and what information can be extracted from it (density-of-states and velocity)\n- [ ] how to compute the phonon dispersion from a simple one-dimensional atomic chain and what is the **dynamical matrix** (DM) of a system\n- [ ] how to generally derive the DM of a solid from its **total energy** and the forces acting on each atom\n- [ ] what is the difference between an empirical and quantum mechanical treatment\n\n### Summary\n* Calculation of phonon dispersion with 1-D model \n* Extraction of DOS and phonon velocity\n* Definition of Hessian and dynamical matrix\n* Keating VFF model and its extension\n* Phonon bandstructure computation with DFT\n\n### Outline\n* Phonon bandstructure\n    * Why do we need this quantity?\n* Classical phonon bandstructure calculation\n    * Simple 1-D atomic chain\n    * Dynamical matrix of the system\n* Advanced phonon bandstructure calculation\n    * Harmonic approximation Valence-force-field\n    * (VFF) model\n    * Density functional theory (DFT) model\n\n### Phonon bandstructure\n\n#### Why do we need this quantity?\n##### Thermal conductivity recap\n\n#### Ingredients for $\\kappa$ calculation: Require phonon band structure\n##### Phonon density-of-states\n##### Phonon velocity\n##### Relaxation time for scattering type (hard/not discussed)\n\n#### Example (recap): Phonon dispersion in Si\n##### Acoustic phonons\n##### Optical phonons\n##### Transverse branches\n##### Longitudinal branches\n##### Phonon velocity as a derivative of frequency w.r.t. momentum\n\n#### Example: Other phonon dispersions\n##### Polar semiconductor (InAs): LO/TO split\n##### Graphene: ZA, ZO modes out-of-plane\n\n### Classical phonon bandstructure calculation: Newton/Hooke\n\n#### Simple 1-D atomic chain\n##### Atom oscillations by Newton's EoM and Hooke's law\n##### Unit cell of atomic chain\n##### Period boundary conditions\n##### Result: LSE w/ two coupled EoM\n\n#### Dynamical matrix of the system from LSE of coupled EoM\n##### Eigenvalue problem w/ $\\omega^2$ as eigenvalue\n##### Analytic solution:  Characteristic polynomial\n##### Only positive eigenvalues admissible\n##### Obtain two branches for 1D: 1 optical, 1 acoustic\n##### Optical branch oscillation mode: out-of-phase motion\n##### Acoustic branch oscillation mode:  in-phase motion\n##### Extending from 1D to 3D: 6 branches but similar to 1D\n\n#### 1D already allows extracting analytical parameters\n##### DOS from phonon band structure\n##### Injection velocity\n\n#### Simplification by linearization\n##### Phonon band structure\n##### DOS\n##### Injection velocity\n\n\n### Advanced phonon bandstructure calculation: VFF and DFT\n\n#### Harmonic approximation\n\n##### Energy of solids and the Hamiltonian\n##### Phonon amplitude affects total energy $E$\n##### Harmonic approximation of the total energy: 2nd order \n###### The force terms\n###### The Hessian\n##### Out-of-equilibrium: Force from integrating Hessian\n##### The dynamical matrix: Eigenvalue problem as in 1D atomic chain\n###### Acceleration from second derivative of phonon amplitude\n###### Definition of phonon amplitude\n\n#### Valence-force-field (VFF) model\n##### VFF equals tight-binding for electrons: An empirical method\n##### The Keating model\n###### Bond stretching\n###### Bond bending\n###### Total energy in Keating model\n###### Downside of Keating model: Poor fit to experiment\n##### Extended VFF model\n###### Model features\n###### Cross bond stretching\n###### Coplanar bond bending\n###### Fit to experiment much improved over Keating model\n\n#### Density functional theory (DFT) model\n##### Schroedinger equation with $E_{xc}$\n##### Charge density $\\rho$\n##### Exchange correlation energy functional $E_{xc}[\\rho]$\n###### LDA\n###### GGA\n###### HSE06\n##### Frozen phonon approach\n###### Total energy expression\n###### Dynamical matrix formulation\n###### Computational effort: 6N + 1 simulations\n##### Near-perfect fit to experiment w/o fitting parameters\n##### More efficient: density functional perturbation theory\n\n## Phonon Quantum Transport (22/4)\n\n- [X] ***processed***\n\n### Learning goals\n- [ ] what the different types of phonon **boundary conditions** are and what they physically represent\n- [ ] how **semi-infinite contacts** must be attached to a system of interest to inject phonons on one side of the domain and collect them on the other\n- [ ] how the **Wave Function (WF) formalism** allows to compute the phonon (quantum) transport properties of a structure driven out-of-equilibrium\n- [ ] what the **Non-equilibrium Green\u2019s Function (NEGF)** is and how it is related to WF\n\n### Summary\n* Boundary conditions for phonon calculations\n* Phonon injection, reflection, and transmission\n* Wave Function (WF) formalism for phonons\n* Extraction of DOS, transmission, and heat current\n* Phonon Non-equilibrium Green\u2019s Functions\n\n### Outline\n* Boundary conditions\n    * Periodic, closed, open\n* Quantum transport approach\n    * Definition of contacts/reservoirs\n    * Derivation of the Wave Function formalism\n    * DOS and transmission function\n    * Non-equilibrium Green\u2019s Function\n\n### Boundary conditions\n\n#### Intro/Recap\n##### Semi-classical approach vs. QM approach for phonon transport\n###### Semi-classical: Phonons as particles\n###### QM: Phonons as waves\n\n##### Recap: 1D phonon model\n###### 1D atomic chain\n###### Unit cell\n###### Hooke's law\n\n##### Phonon EoM\n###### Ansatz\n\n##### Generalized dynamical equation\n###### General form\n###### Matrix form\n\n#### Periodic boundary conditions\n\n##### Periodic boundary conditions: Infinite length\n###### Eigenvalue problem\n\n##### Simple phonon bandstructure\n###### Acoustic branch: In phase\n###### Optical branch: Out-of-phase\n###### No phonon transport\n\n#### Closed boundary conditions\n\n##### Closed boundary conditions: Finite length\n###### Acoustic branch: In phase\n###### Optical branch: Out-of-phase\n###### No phonon transport\n\n##### Discrete phonon frequencies\n###### Two discrete phonon frequency solutions\n\n#### Open boundary conditions\n\n##### Open boundary conditions: Quasi-infinite length\n###### Neither periodic nor closed\n###### Injection, Reflection, Transmission/Collection\n\n\n### Quantum transport approach\n\n#### Definition of contacts/reservoirs\n\n##### Division of simulation domain\n###### Injection\n###### Reflection\n###### Transmission\n\n##### Contact properties\n###### Semi-infiniteness\n###### Linear combination of optical & acoustic phonon modes\n###### Complex conjugate solution\n\n##### Physical interpretation\n###### Transmission-only assumption\n###### Injection\n###### Reflection\n\n#### Derivation of the Wave Function formalism\n\n##### Connection to device\n###### Connecting cells\n###### Infinite hierarchy\n\n##### Hierarchy truncation\n###### Using the injection/reflection coefficient formulation\n###### Using semi-infiniteness\n\n\n##### Variable elimination\n###### Finding $\\vec{q}_j^L$\n###### Finding $\\vec{b}_{Lj}$\n###### Finding $\\vec{a}_{Lj}$\n###### Algorithm\n\n##### Wave Function formalism\n###### Dynamical matrix\n###### Boundary self-energy\n###### Injection vector\n###### Matrix sizes\n\n#### DOS and transmission function\n\n##### Solution of the WF formalism\n###### Formulation\n###### Algorithm\n###### Frequency- and position-resolved DOS\n###### Transmission function\n\n##### DOS and Transmission\n###### DOS\n###### Transmission function\n###### Velocity ratio\n\n##### Homogeneous system: Example\n###### Contact band structure\n###### DOS\n###### Transmission function\n\n##### Inhomogeneous system: Example\n###### DOS\n###### Transmission function\n\n##### Heat current\n###### Thermal current w/ temperature difference\n###### Landauer-B\u00fcttiker formula\n###### Bose-Einstein distribution function\n###### Homogeneous chain carries more heat \n\n\n#### Non-equilibrium Green\u2019s Function\n \n##### Green\u2019s Functions in general\n###### Operator\n###### Kernel\n###### Green's function formulation\n###### Propagator interpretation\n###### Correlation function interpretation\n###### Recovery of original problem formulation\n\n##### Phonon Green\u2019s Functions\n###### Retarded phonon Green's Function\n###### Matrix formulation\n###### Matrix size\n###### Non-equilibrium (NEGF) formalism\n###### Speed/effiecency: WF vs. NEGF\n###### Other types of phonon Green's Functions\n###### Advantages of phonon Green's Functions\n\n## Thermoelectric Power Generators (29/4)\n\n- [X] ***processed***\n\n### Learning goals\n- [ ] how the waste heat can be converted back to electricity with carefully designed structures\n- [ ] how the efficiency of these thermoelectric generators can be evaluated and when they can be considered as good devices\n- [ ] what the ZT figure of merit, the Seebeck coefficient, and the power factor are\n- [ ] how nanostructuring has revolutionized the field of thermoelectricity since the beginning of the 90\u2019s\n- [ ] where the field currently stands\n\n### Summary\n* Energy consumption and waste heat\n* Principle of thermoelectricity and basic device\n* Voltage- and temperature-induced electrical and thermal currents flowing through a structure\n* Calculation of the \ud835\udc4d\ud835\udc47 figure of merit\n\n### Outline\n* Thermoelectricity: an introduction\n    * How to recycle waste heat?\n    * ZT figure of merit\n    * From bulk to nanostructures\n* Mathematical formulation\n    * Current and conductance\n    * Electrical and thermal components\n    * Simulation example\n\n### Thermoelectricity: an introduction\n\n#### How to recycle waste heat?\n#####  Energy Consumption in US\n###### Share of fossil fuels   \n###### Definition of quad\n###### Share of energy wasted\n\n#####  Waste heat\n###### Waste heat key figures\n\n#####  Thermoelectricity\n###### Seebeck effect\n###### Seeback coefficient\n###### Thermoelectricity\n###### Conversion efficiency\n\n#### ZT figure of merit\n\n#####  Thermoelectric generator\n###### Nano-generators\n###### Semiconductor thermoelectric generator principle of operation\n\n#####  Thermoelectric efficiency\n###### Carnot efficiency\n###### Overall efficiency\n###### $ZT$ vs. $\\frac{\\eta}{\\eta_{\\text{Carn}}}$ curve\n\n#####  \ud835\udc81\ud835\udc7b definition and interpretation\n###### ZT figure of merit\n###### Seebeck coefficient\n###### Electrical conductivity\n###### Thermal conductivity\n###### What is a a \"good\" thermoelectric material?\n \n#####  Representative ZT examples\n###### Sample ZT values\n###### What is a \"good\" ZT value?\n###### Problems with ZT values obtainable\n\n#### From bulk to nanostructures\n##### From bulk to nanostructures: Theory historical perspective\n###### Key theory papers\n###### Key ansatz\n\n#####  Theory validation\n###### Experimental confirmation of theory\n###### Main results of validation\n\n#####  Rough Si nanowires\n###### Power factor\n###### Thermal conductivity\n\n### Mathematical formulation\n\n#### Current and conductance\n \n#####  Calculation of \ud835\udc81\ud835\udc7b\n###### Ballistic limit assumption\n###### Scattering: Phenomenological addition\n\n#####  \ud835\udc81\ud835\udc7b ingredients\n###### $I_{d,    \\Delta V}$\n###### $I_{d,    \\Delta T}$\n###### $I_{th,e, \\Delta T}$\n###### $I_{th,e, \\Delta V}$\n###### $I_{th,ph,\\Delta T}$\n\n#####  Current flows\n###### Situation w/ $\\Delta V$ applied\n###### Situation w/ $\\Delta T$ applied\n \n#####  Conductance definition\n###### Seebeck coefficient $[V/K$\n###### Electrical conductance $[A/V, S]$\n###### Electronic component of thermal conductance $[W/K]$\n###### Phonon component of thermal conductance $[W/K]$\n\n#### Electrical and thermal components\n \n#####  Electrical currents by electrons\n###### Return of Landauer-B\u00fcttiker\n###### Return of Fermi-Dirac\n###### Electron transmission function\n\n#####  Electrical current linearization\n###### Taylor expansion for small $\\Delta V$\n###### Taylor expansion for small $\\Delta T$\n\n#####  Thermal current from electrons\n###### Once more Landauer-B\u00fcttiker with a twist\n###### Thermal energy carried by a electron w/ energy $E$\n###### Taylor expansion for small $\\Delta V$\n###### Taylor expansion for small $\\Delta T$\n \n#####  Simplification and generalization\n###### Identity relation of derivatives of Fermi-Dirac\n###### **K**ompact formulation of currents\n\n#####  Thermal current from phonons\n###### Thermal current from previous lecture L9\n###### Taylor expansion for small $\\Delta T$\n\n#####  Calculation of \ud835\udc81\ud835\udc7b\n###### Using simplifi**K**ation to express desired ingredients\n###### Seebeck coeffcient\n###### Electrical conductance\n###### Electronic component of the thermal conductance\n###### Phonon component of the thermal conductance\n\n#### Simulation example\n\n#####  \ud835\udc81\ud835\udc7b summary\n###### Definition of ZT using $K_i$\n###### Compromises needed: No ideal solution\n###### Maximizing $K_1$\n###### Low thermal conductivity vs. high electrical mobility\n\n#####  Example: Si nanowire\n###### Crystal axis <100>\n###### Dimensions\n\n#####  Electron/phonon transmission\n###### Electron transmission function\n###### Tight-binding model\n###### Phonon transmission function\n###### VFF model\n\n#####  \ud835\udc72\ud835\udfce, \ud835\udc72\ud835\udfcf, \ud835\udc72\ud835\udfd0, and \ud835\udc73\ud835\udfd0\n######  Characteristics of obtained values\n \n#####  \ud835\udc81\ud835\udc7b results\n###### Ideal assumptions, yet...\n\n## Numerics and Parallelization (6/5)\n\n- [X] ***processed***\n\n### Learning goals\n- [ ] how matrix multiplications or eigenvalue problems are handled under the hood in scripting languages such as Matlab or Python\n- [ ] how to parallelize a scientific code with a shared or distributed memory strategy\n- [ ] how graphics processing units (GPUs) can speed up a compute intensive application\n- [ ] how the open boundary conditions and the resulting Wave Function equations can be efficiently solved with a dedicated algorithm\n\n### Summary\n* BLAS and LAPACK libraries\n* Parallelization with OpenMP and MPI\n* Matrix-matrix multiplication parallelization\n* Acceleration of the Wave Function formalism with the Beyn and SplitSolve algorithms\n\n### Outline\n* Basic numerical operations\n    * BLAS/LAPACK libraries Parallelization strategies\n    * Graphics processing units (GPUs)\n* Open boundary calculation\n    * Generalized eigenvalue problem\n    * Contour integral techniques\n* Solution of the Wave Function equation\n    * SplitSolve algorithm\n\n### Basic numerical operations\n\n#### BLAS/LAPACK libraries \n \n##### Basic operations\n###### Matlab\n###### Numpy\n###### C++\n\n##### BLAS\n###### Operands\n###### Level 1/2/3\n\n##### Eigenvalue (EV) problems\n###### Typical algorithms\n\n##### LAPACK\n###### Operands\n###### Examples\n\n##### Calling BLAS/LAPACK\n###### Headers\n###### Drivers\n\n##### Vendor libraries\n###### Efficiency\n###### Examples\n\n#### Parallelization strategies\n \n##### Shared vs. distributed memory\n \n \n##### Shared memory parallelization\n###### OpenMP\n \n##### OpenMP example: \ud835\udc6a = \ud835\udc68\ud835\udc69\n\n##### OpenMP timing results\n###### ```OMP_NUM_THREADS```\n###### Partitions\n\n##### Distributed memory parallelization\n###### SPMD\n###### MPI\n\n##### MPI example: \ud835\udc6a = \ud835\udc68\ud835\udc69\n \n##### MPI timing results\n###### Overhead\n\n#### Graphics processing units (GPUs)\n \n##### GPU architecture\n###### Cores\n###### Memory\n###### Frequency\n \n##### GPU example \ud835\udc6a = \ud835\udc68\ud835\udc69\n\n##### GPU timing results\n###### Multiple cores - 1 GPU\n###### Speedup\n\n### Open boundary calculation\n\n#### Generalized eigenvalue problem\n \n##### Phonon ballistic transport\n###### WF phonon equation\n###### OBC\n###### Schr\u00f6dinger equation w/ OBC\n###### Direct solvers\n\n##### Benchmark structure\n###### Nanowire features\n###### Simulation features\n \n##### OBC formulation\n###### Semi-infinite contacts\n###### Injection, Reflection, Transmission\n###### Non-linear eigenvalue problem\n \n##### GEPV and shift-and-invert\n###### Linearization of EVP\n###### Shift-and-invert\n\n##### Timing standard solution\n###### 2 nodes for memory\n###### 2 core OBC parallelization in 90s\n\n#### Contour integral techniques\n##### Physical observation\n###### Neglecting certain states\n###### Annulus\n \n##### Rayleigh-Ritz projection method\n###### Lower-dimensional subspace\n###### Projector matrices\n \n##### Beyn algorithm \n###### Step 1: Projector $Q_i$\n###### Step 2: SVD of $Q_0$\n###### Step 3: Construction of intermediate M\n###### Step 4: Solving reduced EVP\n###### Quirks and features\n\n##### Timing: OBC improvement\n###### 2.35 speed-up of OBC\n\n###  Solution of the Wave Function equation\n\n#### SplitSolve algorithm\n##### Porting WF to GPUs\n###### Block tri-diagonal $A$\n###### Sparse $Inj$\n###### Spares $\\Pi$\n###### Sherman-Morrison-Woodbury on $A-BC$\n\n\n##### SplitSolve Algorithm\n###### Pre-processing\n###### Post-processing\n###### Key boost: OBC on CPU, SplitSolve on GPU in PARALLEL\n\n##### Timing: SplitSolve\n###### 4x speed-up, up to ~100x for larger systems\n\n\n# References\n\nUnless mentioned otherwise, all content and images from:\n* ETHZ 227-0622-00L Thermal Modeling: Part I lecture notes by Dr. Esra Neufeld\n* ETHZ 227-0622-00L Thermal Modeling: Part II lecture notes by Prof. Dr. Mathieu Luisier\n\n\n```python\n\n```\n", "meta": {"hexsha": "fc4aeb1a6eb8df6349c2735cf1b0dde7e80d09ab", "size": 126913, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "TM_lecture_notes.ipynb", "max_stars_repo_name": "BeatHubmann/20F-TM", "max_stars_repo_head_hexsha": "adb5f7ea7d05a39df581c4828ec22da29c2c3f1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TM_lecture_notes.ipynb", "max_issues_repo_name": "BeatHubmann/20F-TM", "max_issues_repo_head_hexsha": "adb5f7ea7d05a39df581c4828ec22da29c2c3f1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TM_lecture_notes.ipynb", "max_forks_repo_name": "BeatHubmann/20F-TM", "max_forks_repo_head_hexsha": "adb5f7ea7d05a39df581c4828ec22da29c2c3f1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 97.3259202454, "max_line_length": 85602, "alphanum_fraction": 0.6308731178, "converted": true, "num_tokens": 34606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798743735585305, "lm_q2_score": 0.0526189548333655, "lm_q1q2_score": 0.013048839765469687}}
{"text": "# Introduction To Causality\n\n\n## Why Bother?\n\nFirst and foremost, you might be wondering: what's in it for me? Here is what:\n\n## Data Science is Not What it Used to Be (or it Finally Is)\n\nData Scientist has been labeled [The Sexiest Job of the 21st Century](https://hbr.org/2012/10/data-scientist-the-sexiest-job-of-the-21st-century) by Harvard Business Review. This was no empty statement. For a decade now, Data Scientist has been at the spotlight. AI experts had [salaries that rivaled those of sports superstars](https://www.economist.com/business/2016/04/02/million-dollar-babies). In the search for fame and fortune, hundreds of young professionals entered into what seemed a frenetic golden rush to get the Data Science title as quickly as possible. Whole new industries sprang around the hype. Miraculous teaching methods could make you a Data Scientist without requiring you to look at a single math formula. Consulting specialists promised millions if your company could unlock the potential of data. AI or, Machine Learning, has been called the new electricity and data, the new oil. \n\nMeanwhile, we kind of forgot about those that have been doing \"old fashioned\" science with data all along. During all this time, economists were trying to answer what is the true impact of education on one's earnings, biostatisticians were trying to understand if saturated fat led to higher chance of heart attack and psychologists were trying to understand if words of affirmation led indeed to a happier marriage. If we were to be completely honest, data scientist is not a recent field. We are simply aware of it just now due to the massive amount of free marketing the media has provided.\n\nTo use a Jim Collins analogy, think about pouring yourself an ice cold cup of your favorite beer. If you do this the right way, most of the cup will be beer but there will be a 1 finger thick layer of foam at the top. This cup is just like Data Science. \n\n1. It's the beer. The statistical foundations, the scientific curiosity, the passion for difficult problems. All of this was proven very valuable throughout hundreds of years.\n2. It's the foam. The fluffy stuff built on unrealistic expectations that will eventually go away. \n\nThis foam might come down crashing faster than you think. As The Economist puts it\n\n> The same consultants who predict that AI will have a world-altering impact also report that real managers in real companies are finding AI hard to implement, and that enthusiasm for it is cooling. Svetlana Sicular of Gartner, a research firm, says that 2020 could be the year AI falls onto the downslope of her firm\u2019s well-publicised \u201chype cycle\u201d. Investors are beginning to wake up to bandwagon-jumping: a survey of European AI startups by MMC, a venture-capital fund, found that 40% did not seem to be using any AI at all.\n\nIn the midst of all this craze, what should we, as Data Scientists - or better yet, as \"just\" Scientists - do? As a starter, if you are smart, you will learn to ignore the foam. We are in it for the beer. Math and statistics has been useful since forever and it is unlikely it will stop now. Second, learn what makes your work valuable and useful, not the latest shining tool that no one figured out how to use. \n\nLast but not least, remember that there are no shortcuts. Knowledge in Math and Statistics are valuable precisely because they are hard to acquire. If everyone could do it, excess supply would drive its price down. So **toughen up**! Learn them as well as you can. And heck, why not? have fun along the way as we embark on this quest only **for the Brave and True**.\n\n\n\n## Answering a Different Kind of Question\n\nThe type of question Machine Learning is currently very good at answering is of the prediction kind. As Ajay Agrawal, Joshua Gans and Avi Goldfarb puts it in the book Prediction Machines, \"the new wave of artificial intelligence does not actually bring us intelligence but instead a critical component of intelligence - prediction\". We can do all sorts of wonderful things with machine learning. The only requirement is that we frame our problems as prediction ones. Want to translate from english to portuguese? Then build a ML model that predicts portuguese sentences when given english sentences. Want to recognize faces? Then build a ML model that predicts the presence of a face in a subsection of a picture. Want to build a self driving car? Then build one ML model to predict the direction of the wheel and the pressure on the brakes and accelerator when presented with images and sensors from the surroundings of a car.\n\nHowever, ML is not a panacea. It can perform wonders under very strict boundaries and still fail miserably if the data it's using deviates a little from what the model is accustomed to. To give another example from Prediction Machines, \"in many industries, low prices are associated with low sales. For example, in the hotel industry, prices are low outside the tourist season, and prices are high when demand is highest and hotels are full. Given that data, a naive prediction might suggest that increasing the price would lead to more rooms sold.\u201d \n\nML is notoriously bad at this inverse causality type of problems. They require us to answer \"what if\" questions, what Economists call counterfactuals. What would happen if instead of this price I'm currently asking for my merchandise, I use another price? What would happen if instead of this low fat diet I'm in, I do a low sugar one? If you work in a bank, giving credit, you will have to figure out how changing the customer line changes your revenue. Or if you work at the local government, you might be asked to figure out how to make the schooling system better. Should you give tablets to every kid because the era of digital knowledge tells you to? Or should you build an old fashioned library? \n\nAt the heart of these questions there is a causal inquiry we wish to know the answer. Causal questions permeate everyday problems, like figuring out how to make sales go up, but they also play an important role on dilemmas that are very personal and dear to us: do I have to go to an expensive school to be successful in life (does education cause earnings)? Does imigration lowers my chances of getting a job (does imigration causes unemployment to go up)? Does money transfer to the poor lower the crime rate? It doesn't matter the field you are in, it is very likely you had or will have to answer some type of causal question. Unfortunately for ML, we can't rely on correlation type predictions to tackle them.\n\nAnswering this kind of question is tougher than most people appreciate. Your parents have probably repeated to you that \"association is not causation\", \"association is not causation\". But actually explaining why that is the case is a bit more involved. This is what this introduction to causal inference is all about. As for fhe rest of this book, it will be dedicated to **figuring how to make association be causation**.\n\n## When Association IS Causation\n\nIntuitively, we kind of know why association is not causation. If someone tells you that schools that give tablets to its students perform better than those who don't, you can quickly point out that it is probably the case that those schools with the tablets are richer. As such, they would do better than average even without the tablets. Because of this, we can't conclude that giving tablets to kids during classes will cause an increase in their academic performance. We can only say that tablets in school are associated with high academic performance.\n\n\n```python\nimport pandas as pd\nimport numpy as np\nfrom scipy.special import expit\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nfrom matplotlib import style\n\nstyle.use(\"fivethirtyeight\")\n\nnp.random.seed(123)\nn = 100\ntuition = np.random.normal(1000, 300, n).round()\ntablet = np.random.binomial(1, expit((tuition - tuition.mean()) / tuition.std())).astype(bool)\nenem_score = np.random.normal(200 - 50 * tablet + 0.7 * tuition, 200)\nenem_score = (enem_score - enem_score.min()) / enem_score.max()\nenem_score *= 1000\n\ndata = pd.DataFrame(dict(enem_score=enem_score, Tuition=tuition, Tablet=tablet))\n```\n\n\n```python\nplt.figure(figsize=(6,8))\nsns.boxplot(y=\"enem_score\", x=\"Tablet\", data=data).set_title('ENEM score by Tablet in Class')\nplt.show()\n```\n\nTo get beyond simple intuition, let's first establish some notation. This will be our common language to speak about causality. Think of it as the common tongue we will use to identify other brave and true causal warriors and that will compose our cry in the many battles to come.\n\nLet's call \\\\(T_i\\\\) the treatment intake for unit i. \n\n$\nT_i=\\begin{cases}\n1 \\ \\text{if unit i received the treatment}\\\\\n0 \\ \\text{otherwise}\\\\\n\\end{cases}\n$\n\nThe treatment here doesn't need to be a medicine or anything from the medical field. Istead, it is just a term we will use to denote some intervention for which we want to know the effect. In our case, the treatment is giving tablets to students. As a side note, you might sometimes see \\\\(D\\\\) instead of \\\\(T\\\\) to denote the treatment.\n\nNow, let's call \\\\(Y_i\\\\) the observed outcome variable for unit i.\n\n$\nY_i\n$\n\nThe outcome is our variable of interest. We want to know if the treatment has any influence in it. In our tablet example, it would be the academic performance.\n\nHere is where things get interesting. The **fundamental problem of causal inference** is that we can never observe the same unit with and without treatment. It is as if we have two diverging roads and we can only know what lies ahead of the one we take. As in Robert Frost poem:\n\n>Two roads diverged in a yellow wood,  \nAnd sorry I could not travel both  \nAnd be one traveler, long I stood  \nAnd looked down one as far as I could  \nTo where it bent in the undergrowth;  \n\n\nTo wrap our heads around this, we will talk a lot in term of **potential outcomes**. They are potential because they didn't actually happen. Instead they denote **what would have happened** in the case some treatment was taken. We sometimes call the potential outcome that happened, factual, and the one that didn't happen, counterfactual.\n\nAs for the notation, we use an additional subscript:\n\n\\\\(Y_{0i}\\\\) is the potential outcome for unit i without the treatment. \n\n\\\\(Y_{1i}\\\\) is the potential outcome for **the same** unit i with the treatment.\n\nSometimes you might see potential outcomes represented as functions \\\\(Y_i(t)\\\\), so beware. \\\\(Y_{0i}\\\\) could be \\\\(Y_i(0)\\\\) and \\\\(Y_{1i}\\\\) could be \\\\(Y_i(1)\\\\). Here, we will use the subscript notation most of the time.\n\n\n\nBack to our example, \\\\(Y_{1i}\\\\) is the academic performance for student i if he or she has tablets at the classroom. Whether this is or not the case, it doesn't matter for \\\\(Y_{1i}\\\\). It is the same regardless. If student i gets the tablet, we can observe \\\\(Y_{1i}\\\\). If not, we can observe \\\\(Y_{0i}\\\\). Notice how in this last case, \\\\(Y_{1i}\\\\) is still defined, we just can't see it. In this case, it is a counterfactual potential outcome.\n\nWith potential outcomes, we can define the individual treatment effect:\n\n \\\\(Y_{1i} - Y_{0i}\\\\)\n \nOf course, due to the fundamental problem of causal inference, we can never know the individual treatment effect because we only observe one of the potential outcomes. For the time being, let's focus on something easier than estimating the individual treatment effect. Instead, lets focus on the **average treatment effect**, which is defined as follows.\n\n\\\\(ATE = E[Y_1 - Y_0]\\\\)\n\nwhere, `E[...]` is the expected value. Another easier quantity to estimate is the **average treatment effect on the treated**:\n\n\\\\(ATET = E[Y_1 - Y_0 | T=1]\\\\)\n\nNow, I know we can't see both potential outcomes, but just for the sake of the argument, let's suppose we could. Pretend that the causal inference deity is pleased with the many statistical battles that we fought and has rewarded us with godlike powers to see the alternative potential outcomes. With that power, say we collect data on 4 schools. We know if they gave tablets to its students and their score on some annual academic test. Here, tablets are the treatment, so \\\\(T=1\\\\) if the school gives tablets to its kids. \\\\(Y\\\\) will be the test score.\n\n\n```python\npd.DataFrame(dict(\n    i= [1,2,3,4],\n    y0=[500,600,800,700],\n    y1=[450,600,600,750],\n    t= [0,0,1,1],\n    y= [500,600,600,750],\n    te=[-50,0,-200,50],\n))\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>i</th>\n      <th>y0</th>\n      <th>y1</th>\n      <th>t</th>\n      <th>y</th>\n      <th>te</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>500</td>\n      <td>450</td>\n      <td>0</td>\n      <td>500</td>\n      <td>-50</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2</td>\n      <td>600</td>\n      <td>600</td>\n      <td>0</td>\n      <td>600</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>3</td>\n      <td>800</td>\n      <td>600</td>\n      <td>1</td>\n      <td>600</td>\n      <td>-200</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>4</td>\n      <td>700</td>\n      <td>750</td>\n      <td>1</td>\n      <td>750</td>\n      <td>50</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThe \\\\(ATE\\\\) here would be the mean of the last column, that is, of the treatment effect:\n\n\\\\(ATE=(-50 + 0 - 200 + 50)/4 = -50\\\\)\n\nThis would mean that tablets reduced the academic performance of students, on average, by 50 points. The \\\\(ATET\\\\) here would be the mean of the last column when \\\\(T=1\\\\):\n\n\\\\(ATET=(- 200 + 50)/2 = -75\\\\)\n\nThis is saying that, for the schools that were treated, the tablets reduced the academic performance of students, on average, by 75 points. Of course we can never know this. In reality, the table above would look like this:\n\n\n```python\npd.DataFrame(dict(\n    i= [1,2,3,4],\n    y0=[500,600,np.nan,np.nan],\n    y1=[np.nan,np.nan,600,750],\n    t= [0,0,1,1],\n    y= [500,600,600,750],\n    te=[np.nan,np.nan,np.nan,np.nan],\n))\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>i</th>\n      <th>y0</th>\n      <th>y1</th>\n      <th>t</th>\n      <th>y</th>\n      <th>te</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>500.0</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>500</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2</td>\n      <td>600.0</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>600</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>3</td>\n      <td>NaN</td>\n      <td>600.0</td>\n      <td>1</td>\n      <td>600</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>4</td>\n      <td>NaN</td>\n      <td>750.0</td>\n      <td>1</td>\n      <td>750</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThis is surely not ideal, you might say, but can't I still take the mean of the treated and compare it to the mean of the untreated? In other words, can't I just do \\\\(ATE=(600+750)/2  - (500 + 600)/2  = 125\\\\)? Well, no! Notice how different the results are. That's because you've just committed the gravest sin of mistaking association for causation. To understand why, let's take a look into the main enemy of causal inference.\n\n## Bias\n\nBias is what makes association different from causation. Fortunately, it too can be easily understood with our intuition. Let's recap our tablets in the classroom example. When confronted with the claim that schools that give tablets to their kids do better on tests score, we can rebut it by saying those schools will probably do better anyway, even without the tables. That is because they probably have more money than the other schools; hence they can pay better teachers, afford better classrooms, and so on. In other words, it is the case that treated schools (with tablets) are not comparable with untreated schools. \n\nTo say this in potential outcome notation is to say that \\\\(Y_0\\\\) of the treated is different from the \\\\(Y_0\\\\) of the untreated. Remember that the \\\\(Y_0\\\\) of the treated **is counterfactual**. We can't observe it, but we can reason about it. In this particular case, we can even leverage our understanding of how the world works to go even further. We can say that, probably, \\\\(Y_0\\\\) of the treated is bigger than \\\\(Y_0\\\\) of the untreated schools. That is because schools that can afford to give tablets to their kids can also afford other factors that contribute to better test scores. Let this sink in for a moment. It takes some time to get used to talking about potential outcomes. Read this paragraph again and make sure you understand it.\n\nWith this in mind, we can show with very simple math why is it the case that association is not causation. Association is measured by \\\\(E[Y|T=1] - E[Y|T=0]\\\\). In our example, this is the average test score for the schools with tablets minus the average test score for those without it. On the other hand, causation is measured by \\\\(E[Y_1 - Y_0]\\\\).\n\nTo see how they relate, let's take the association measurement and replace the observed outcomes with the potential outcomes. For the treated, the observed outcome is \\\\(Y_1\\\\). For the untreated, the observed outcome is \\\\(Y_0\\\\).\n\n$\nE[Y|T=1] - E[Y|T=0] = E[Y_1|T=1] - E[Y_0|T=0]\n$\n\nNow, let's add and subtract \\\\(E[Y_0|T=1]\\\\). This is a counterfactual outcome. It tells what would have been the outcome of the treated, had they not received the treatment.\n\n$\nE[Y|T=1] - E[Y|T=0] = E[Y_1|T=1] - E[Y_0|T=0] + E[Y_0|T=1] - E[Y_0|T=1]\n$\n\nFinally, we reorder the terms, merge some expectations, and lo and behold:\n\n$\nE[Y|T=1] - E[Y|T=0] = \\underbrace{E[Y_1 - Y_0|T=1]}_{ATET} + \\underbrace{\\{ E[Y_0|T=1] - E[Y_0|T=0] \\}}_{BIAS}\n$\n\nThis simple piece of math encompasses all the problems we will encounter in causal questions. I cannot stress how important it is that you understand every aspect of it. If you're ever forced to tattoo something on your arm, this equation should be a good candidate for it. It's something to hold onto very dearly and really understand what is telling us, like some sacred text that can be interpreted 100 different ways. In fact, let's take a deeper look. Let's break it down into some of its implications. First, this equation tells why association is not causation. As we can see, association is equal to the treatment effect on the treated plus a bias term. **The bias is given by how the treated and control group differ before the treatment, that is, in case neither of them has received the treatment**. We can now say precisely why we are suspicious when someone tells us that tablets in the classroom boost academic performance. We think that, is this example, \\\\(E[Y_0|T=0] < E[Y_0|T=1]\\\\), that is, schools that can afford to give tablets to their kids are better than those that can't, **regardless of the tablets treatment**.\n\nWhy does this happen? We will talk more about that once we enter confounding, but for now you can think of bias arising because many things we can't control are changing together with the treatment. As a result, the treated and untreated schools don't differ only on the tablets. They also differ on the tuition cost, location, teachers...\nFor us to say that tablets in the classroom increase academic performance, we would need for schools with and without them to be, on average, similar to each other.\n\n\n```python\nplt.figure(figsize=(10,6))\nsns.scatterplot(x=\"Tuition\", y=\"enem_score\", hue=\"Tablet\", data=data, s=70).set_title('ENEM score by Tuition Cost')\nplt.show()\n```\n\nNow that we understand the problem, let's look at the solution. We can also say what would be necessary to make association equal to causation. **If \\\\(E[Y_0|T=0] = E[Y_0|T=1]\\\\), then, association IS CAUSATION!** Understanding this is not just remembering the equation. There is a strong intuitive argument here. To say that \\\\(E[Y_0|T=0] = E[Y_0|T=1]\\\\) is to say that treatment and control group are comparable before the treatment. Or, in the case that the treated had not been treated, if we could observe its \\\\(Y_0\\\\), then its outcome would be the same as the untreated. Mathematically, the bias term would vanish:\n\n$\nE[Y|T=1] - E[Y|T=0] = E[Y_1 - Y_0|T=1]\n$\n\nAlso, if the treated and the untreated only differ on the treatment itself, that is,  \\\\(E[Y_0|T=0] = E[Y_0|T=1]\\\\)\n \nWe have that the causal impact on the treated is the same as in the untreated (because they are very similar).\n\n$\n\\begin{align}\nE[Y_1 - Y_0|T=1] &= E[Y_1|T=1] - E[Y_0|T=1] \\\\\n&= E[Y_1|T=1] - E[Y_0|T=0] \\\\\n&= E[Y|T=1] - E[Y|T=0]\n\\end{align}\n$\n\nHence, in this case, the **difference in means BECOMES the causal effect**:\n\n$\nE[Y|T=1] - E[Y|T=0] = ATE = ATET\n$\n\nOnce again, this is so important that I think it is worth going over it again, now with pretty pictures. If we do a simple average comparison between the treatment and the untreated group, this is what we get (blue dots didn't receive the treatment, that is, the tablet):\n\n\n\nNotice how the difference in outcomes between the two groups can have two causes:\n\n1. The treatment effect. The increase in test score that is caused by giving kids tablets.\n2. Other differences between the treatment and untreated that are NOT the treatment itself. In this case, treated and untreated differ in the sense that the treated have a much higher tuition price. Some of the difference in test scores can be due to the effect of tuition price on better education. \n\nThe true treatment effect can only be obtained if we had godlike powers to observe the potential outcome, like in the left figure below. The individual treatment effect is the difference between the unit's outcome and another theoretical outcome that the same unit would have in case it got the alternative treatment. These are the counterfactual outcomes and are denoted in light color.\n\n\n\nIn the right plot, we depicted what is the bias that we\u2019ve talked about before. We get the bias if we set everyone to not receive the treatment. In this case, we are only left with the \\\\(T_0\\\\) potential outcome. Then, we see how the treated and untreated groups differ. If they do, it means that something other than the treatment is causing the treated and untreated to be different. This something is the bias and is what shadows the true treatment effect.\n\nNow, contrast this with a hypothetical situation where there is no bias. Suppose that tablets are randomly assigned to schools. In this situation, rich and poor schools have the same chance of receiving the treatment. Treatment would be well distributed across all the tuition spectrum.\n\n\n\nIn this case, the difference in the outcome between treated and untreated IS the average causal effect. This happens because there is no other source of difference between treatment and untreated other than the treatment itself. All the differences we see must be attributed to it. Another way to say this is that there is no bias.\n\n\n\nIf we set everyone to not receive the treatment in such a way that we only observe the \\\\(Y_0\\\\)s, we would find no difference between the treated and untreated groups. \n\nThis is the herculean task causal inference is all about. It is about finding clever ways of removing bias, of making the treated and the untreated comparable so that all the difference we see between them is only the average treatment effect. Ultimately, causal inference is about figuring out how the world really works, stripped of all delusions and misinterpretations. And now that we understand this, we can move forward to mastering some of the most powerful methods to remove bias, the weapons of the Brave and True to identify the causal effect. \n\n## Key Ideas\n\nSo far, we've seen that association is not causation. Most importantly, we've seen precisely why it isn't and how can we make association be causation. We've also introduced the potential outcome notation as a way to wrap our head around causal reasoning. With it, we saw statistics as two potential realities: one in which the treatment is given and another in which it is not. But, unfortunately, we can only measure one of them, and that is where the fundamental problem of causal inference lies.\n\nMoving forward, we will see some of the basic techniques to estimate causal effect, starting with the golden standard of a randomised trial. I'll also review some statistical concepts as we go. I'll end with a quote often used in causal inference classes, taken from a kung-fu series:\n\n> 'What happens in a man's life is already written. A man must move through life as his destiny wills.' -Caine  \n'Yes, yet each man is free to live as he chooses. Though they seem opposite, both are true.' -Old Man\n\n## References\n\nI like to think of this book as a tribute to Joshua Angrist, Alberto Abadie and Christopher Walters for their amazing Econometrics class. Most of the ideas here are taken from their classes at the American Economic Association. Watching them is what's keeping me sane during this tough year of 2020.\n* [Cross-Section Econometrics](https://www.aeaweb.org/conference/cont-ed/2017-webcasts)\n* [Mastering Mostly Harmless Econometrics](https://www.aeaweb.org/conference/cont-ed/2020-webcasts)\n\nI'll also like to reference the amazing books from Angrist. They have shown me that Econometrics, or 'Metrics as they call it, is not only extremely useful but also profoundly fun.\n\n* [Mostly Harmless Econometrics](https://www.mostlyharmlesseconometrics.com/)\n* [Mastering 'Metrics](https://www.masteringmetrics.com/)\n\nMy final reference is Miguel Hernan and Jamie Robins' book. It has been my trustworthy companion in the most thorny causal questions I had to answer.\n\n* [Causal Inference Book](https://www.hsph.harvard.edu/miguel-hernan/causal-inference-book/)\n\nThe beer analogy was taken from the awesome [Stock Series](https://jlcollinsnh.com/2012/04/15/stocks-part-1-theres-a-major-market-crash-coming-and-dr-lo-cant-save-you/), by JL Colins. This is an absolute must read for all of those wanting to learn how to productively invest their money.\n\n\n\n## Contribute\n\nCausal Inference for the Brave and True is an open-source material on causal inference, the statistics of science. It uses only free software, based in Python. Its goal is to be accessible monetarily and intellectually.\nIf you found this book valuable and you want to support it, please go to [Patreon](https://www.patreon.com/causal_inference_for_the_brave_and_true). If you are not ready to contribute financially, you can also help by fixing typos, suggesting edits or giving feedback on passages you didn't understand. Just go to the book's repository and [open an issue](https://github.com/matheusfacure/python-causality-handbook/issues). Finally, if you liked this content, please share it with others who might find it useful and give it a [star on GitHub](https://github.com/matheusfacure/python-causality-handbook/stargazers).\n", "meta": {"hexsha": "14c246183dd5c30e5f42929f3f38d3f886a3b5fd", "size": 108285, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "causal-inference-for-the-brave-and-true/01-Introduction-To-Causality.ipynb", "max_stars_repo_name": "fojeda/python-causality-handbook", "max_stars_repo_head_hexsha": "f3c21291655a14b6866eb1f57eef66b0184132d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-19T15:47:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-19T15:47:48.000Z", "max_issues_repo_path": "causal-inference-for-the-brave-and-true/01-Introduction-To-Causality.ipynb", "max_issues_repo_name": "fojeda/python-causality-handbook", "max_issues_repo_head_hexsha": "f3c21291655a14b6866eb1f57eef66b0184132d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "causal-inference-for-the-brave-and-true/01-Introduction-To-Causality.ipynb", "max_forks_repo_name": "fojeda/python-causality-handbook", "max_forks_repo_head_hexsha": "f3c21291655a14b6866eb1f57eef66b0184132d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 195.8137432188, "max_line_length": 52508, "alphanum_fraction": 0.8604146465, "converted": true, "num_tokens": 6844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14033625308549463, "lm_q2_score": 0.09138210182990687, "lm_q1q2_score": 0.012824221769886254}}
{"text": "```python\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.font_manager as mfm\nimport os\nimport numpy as np\nimport scipy as sp\nfrom datetime import timedelta \nimport yfinance as yf\n```\n\n\n```python\n_CHN_FONT_ = None\n_FONT_PROP_ = None\n_CHN_EN_DICT_ = './data/locationDict.csv'\n_CHN_LatLng_DICT_ = './data/lat_lng.csv'\n# The province names in China\n# Ignore Hong Kong, Macau, Taiwan and Tibet\n# English name\nnames_province = ['Anhui', 'Beijing', 'Chongqing', 'Fujian', 'Gansu', 'Guangdong', 'Guangxi', 'Guizhou',\n                  'Hainan', 'Hebei', 'Heilongjiang', 'Henan', 'Hubei', 'Hunan', 'Inner Mongolia', 'Jiangsu',\n                  'Jiangxi', 'Jilin', 'Liaoning', 'Ningxia', 'Qinghai', 'Shaanxi', 'Shandong', 'Shanghai',\n                  'Shanxi', 'Sichuan', 'Tianjin', 'Xinjiang', 'Yunnan', 'Zhejiang']\n# Chinese name\nnames_province_cn = ['\u5b89\u5fbd\u7701', '\u5317\u4eac\u5e02', '\u91cd\u5e86\u5e02', '\u798f\u5efa\u7701', '\u7518\u8083\u7701', '\u5e7f\u4e1c\u7701', '\u5e7f\u897f\u58ee\u65cf\u81ea\u6cbb\u533a', '\u8d35\u5dde\u7701',\n                     '\u6d77\u5357\u7701', '\u6cb3\u5317\u7701', '\u9ed1\u9f99\u6c5f\u7701', '\u6cb3\u5357\u7701', '\u6e56\u5317\u7701', '\u6e56\u5357\u7701', '\u5185\u8499\u53e4\u81ea\u6cbb\u533a', '\u6c5f\u82cf\u7701',\n                     '\u6c5f\u897f\u7701', '\u5409\u6797\u7701', '\u8fbd\u5b81\u7701', '\u5b81\u590f\u56de\u65cf\u81ea\u6cbb\u533a', '\u9752\u6d77\u7701', '\u9655\u897f\u7701', '\u5c71\u4e1c\u7701', '\u4e0a\u6d77\u5e02',\n                     '\u5c71\u897f\u7701', '\u56db\u5ddd\u7701', '\u5929\u6d25\u5e02', '\u65b0\u7586\u7ef4\u543e\u5c14\u81ea\u6cbb\u533a', '\u4e91\u5357\u7701', '\u6d59\u6c5f\u7701']\n\n# A one to one corrspondence with the names used by Pyecharts\npyecharts_province_dict = {'\u5317\u4eac\u5e02':'\u5317\u4eac', '\u5929\u6d25\u5e02':'\u5929\u6d25', '\u6cb3\u5317\u7701':'\u6cb3\u5317', '\u5c71\u897f\u7701':'\u5c71\u897f', \n                           '\u5185\u8499\u53e4\u81ea\u6cbb\u533a':'\u5185\u8499\u53e4', '\u8fbd\u5b81\u7701':'\u8fbd\u5b81', '\u5409\u6797\u7701':'\u5409\u6797', '\u9ed1\u9f99\u6c5f\u7701':'\u9ed1\u9f99\u6c5f', \n                           '\u4e0a\u6d77\u5e02':'\u4e0a\u6d77', '\u6c5f\u82cf\u7701':'\u6c5f\u82cf', '\u6d59\u6c5f\u7701':'\u6d59\u6c5f', '\u5b89\u5fbd\u7701':'\u5b89\u5fbd', \n                           '\u798f\u5efa\u7701':'\u798f\u5efa', '\u6c5f\u897f\u7701':'\u6c5f\u897f', '\u5c71\u4e1c\u7701':'\u5c71\u4e1c', '\u6cb3\u5357\u7701':'\u6cb3\u5357', \n                           '\u6e56\u5317\u7701':'\u6e56\u5317','\u6e56\u5357\u7701':'\u6e56\u5357', '\u5e7f\u4e1c\u7701':'\u5e7f\u4e1c', '\u5e7f\u897f\u58ee\u65cf\u81ea\u6cbb\u533a':'\u5e7f\u897f', \n                           '\u6d77\u5357\u7701':'\u6d77\u5357', '\u91cd\u5e86\u5e02':'\u91cd\u5e86', '\u56db\u5ddd\u7701':'\u56db\u5ddd', '\u8d35\u5dde\u7701':'\u8d35\u5dde', \n                           '\u4e91\u5357\u7701':'\u4e91\u5357', '\u897f\u85cf\u81ea\u6cbb\u533a':'\u897f\u85cf', '\u9655\u897f\u7701':'\u9655\u897f', '\u7518\u8083\u7701':'\u7518\u8083', \n                           '\u9752\u6d77\u7701':'\u9752\u6d77', '\u5b81\u590f\u56de\u65cf\u81ea\u6cbb\u533a':'\u5b81\u590f', '\u65b0\u7586\u7ef4\u543e\u5c14\u81ea\u6cbb\u533a':'\u65b0\u7586', \n                           '\u9999\u6e2f\u7279\u522b\u884c\u653f\u533a':'\u9999\u6e2f', '\u6fb3\u95e8\u7279\u522b\u884c\u653f\u533a':'\u6fb3\u95e8','\u53f0\u6e7e\u7701':'\u53f0\u6e7e'}\n\n# English names of the capital cities of provinces\nprovincial_capital_dict = {'Anhui':'Hefei', 'Fujian':'Fuzhou', 'Gansu':'Lanzhou','Guangdong':'Guangzhou','Guizhou':'Guiyang', \n                           'Hainan':'Haikou', 'Hebei':'Shijiazhuang','Heilongjiang':'Harbin', 'Henan':'Zhengzhou',\n                           'Hubei':'Wuhan', 'Hunan':'Changsha', 'Jiangsu':'Nanjing', 'Jiangxi':'Nanchang', \n                           'Jilin':'Changchun', 'Liaoning':'Shenyang', 'Qinghai':'Xining', 'Shaanxi':'Xi\u2019an', \n                           'Shandong':'Jinan', 'Shanxi':'Taiyuan', 'Sichuan':'Chengdu', 'Yunnan':'Kunming', \n                           'Zhejiang':'Hangzhou', 'Guangxi':'Nanning','Inner Mongolia':'Hohhot', 'Ningxia':'Yinchuan',\n                           'Xinjiang':'\u00dcr\u00fcmqi', 'Tibet':'Lhasa', 'Beijing':'Beijing', 'Chongqing':'Chongqing', \n                           'Shanghai':'Shanghai', 'Tianjin':'Tianjin'}\n\n# Populations of provinces\n# data source: http://www.chamiji.com/2019chinaprovincepopulation\n# unit 10,000\nprovincial_population_dict = {'Anhui':6323.6, 'Fujian':3941, 'Gansu': 2637.26,'Guangdong':11346,'Guizhou':3600, \n                           'Hainan':934.32, 'Hebei':7556.30,'Heilongjiang':3773.1, 'Henan':9605,\n                           'Hubei':5917, 'Hunan':6898.8, 'Jiangsu':8050.7, 'Jiangxi':4647.6, \n                           'Jilin':2704.06, 'Liaoning':4359.3, 'Qinghai':603.23, 'Shaanxi':3864.4, \n                           'Shandong':10047.24, 'Shanxi':3718.34, 'Sichuan':8341, 'Yunnan':4800.5, \n                           'Zhejiang':5737, 'Guangxi':4926,'Inner Mongolia':2534.0, 'Ningxia':688.11,\n                           'Xinjiang':2486.76, 'Tibet':337.15, 'Beijing':2154.2, 'Chongqing': 3101.79, \n                           'Shanghai':2423.78, 'Tianjin':1559.60}\n# Populations of cities\n# data source: http://www.chamiji.com/\n# unit 10,000\ncity_population_dict = {'\u5317\u4eac\u5e02':2154.2, '\u5929\u6d25\u5e02':1559.60, '\u4e0a\u6d77\u5e02':2423.78, '\u91cd\u5e86\u5e02':3101.79,\n                        '\u4eb3\u5dde\u5e02':523.7, '\u516d\u5b89\u5e02':483.7, '\u5408\u80a5\u5e02':808.7, '\u5b89\u5e86\u5e02':469.1, '\u5ba3\u57ce\u5e02':264.8, '\u5bbf\u5dde\u5e02':568.14, # \u5b89\u5fbd\u7701\n                        '\u6c60\u5dde\u5e02':147.4, '\u6dee\u5317\u5e02':225.4, '\u6dee\u5357\u5e02':349.0, '\u6ec1\u5dde\u5e02':411.4, '\u829c\u6e56\u5e02':374.8, '\u868c\u57e0\u5e02':339.20,\n                        '\u94dc\u9675\u5e02':162.9, '\u961c\u9633\u5e02':820.7, '\u9a6c\u978d\u5c71\u5e02':233.7, '\u9ec4\u5c71\u5e02':140.7,\n                        '\u5357\u4eac\u5e02':843.62, '\u5357\u901a\u5e02':731, '\u5bbf\u8fc1\u5e02':492.59, '\u5e38\u5dde\u5e02':472.9, '\u5f90\u5dde\u5e02':880.20, '\u626c\u5dde\u5e02':453.1, # \u6c5f\u82cf\u7701\n                        '\u65e0\u9521\u5e02':657.45, '\u6cf0\u5dde\u5e02':463.57, '\u6dee\u5b89\u5e02':492.50, '\u76d0\u57ce\u5e02':720, '\u82cf\u5dde\u5e02':1072.17, '\u8fde\u4e91\u6e2f\u5e02':452.0,\n                        '\u9547\u6c5f\u5e02':319.64,\n                        '\u4e1c\u8425\u5e02':217.21, '\u4e34\u6c82\u5e02':1062.4, '\u5a01\u6d77\u5e02':283, '\u5fb7\u5dde\u5e02':581, '\u65e5\u7167\u5e02':293.03, '\u67a3\u5e84\u5e02':392.73, # \u5c71\u4e1c\u7701\n                        '\u6cf0\u5b89\u5e02':564.0, '\u6d4e\u5357\u5e02':746.04, '\u6d4e\u5b81\u5e02':834.59, '\u6dc4\u535a\u5e02':470.2, '\u6ee8\u5dde\u5e02':392.25, '\u6f4d\u574a\u5e02':937.3,\n                        '\u70df\u53f0\u5e02':712.18, '\u804a\u57ce\u5e02':606.43, '\u83cf\u6cfd\u5e02':876.5, '\u9752\u5c9b\u5e02':939.48, \n                        '\u4e3d\u6c34\u5e02':219.25, '\u53f0\u5dde\u5e02':613.90, '\u5609\u5174\u5e02':472.6, '\u5b81\u6ce2\u5e02':820.2, '\u676d\u5dde\u5e02':980.6, '\u6e29\u5dde\u5e02':925, # \u6d59\u6c5f\u7701\n                        '\u6e56\u5dde\u5e02':301.09, '\u7ecd\u5174\u5e02':503.5, '\u821f\u5c71\u5e02':117.3, '\u8862\u5dde\u5e02':220.9, '\u91d1\u534e\u5e02':560.4, \n                        '\u4e09\u660e\u5e02':258, '\u5357\u5e73\u5e02':269, '\u53a6\u95e8\u5e02':411, '\u5b81\u5fb7\u5e02':291, '\u6cc9\u5dde\u5e02':870, '\u6f33\u5dde\u5e02':514.0, # \u798f\u5efa\u7701\n                        '\u798f\u5dde\u5e02':774, '\u8386\u7530\u5e02':290.0, '\u9f99\u5ca9\u5e02':264, \n                        '\u4e1c\u839e\u5e02':834.25, '\u4e2d\u5c71\u5e02':326, '\u4e91\u6d6e\u5e02':326, '\u4f5b\u5c71\u5e02':765.67, '\u5e7f\u5dde\u5e02':1449.84, '\u60e0\u5dde\u5e02':477.70, # \u5e7f\u4e1c\u7701\n                        '\u63ed\u9633\u5e02':608.6, '\u6885\u5dde\u5e02':437.43, '\u6c55\u5934\u5e02':560.82, '\u6c55\u5c3e\u5e02':305.33, '\u6c5f\u95e8\u5e02':456.17, '\u6cb3\u6e90\u5e02':309.11,\n                        '\u6df1\u5733\u5e02':1252.83, '\u6e05\u8fdc\u5e02':386.0, '\u6e5b\u6c5f\u5e02':730.5, '\u6f6e\u5dde\u5e02':265.08, '\u73e0\u6d77\u5e02':176.54, '\u8087\u5e86\u5e02':411.54, \n                        '\u8302\u540d\u5e02':620.41, '\u9633\u6c5f\u5e02': 254.29, '\u97f6\u5173\u5e02':297.92, \n                        '\u5317\u6d77\u5e02':166.33, '\u5357\u5b81\u5e02':715.33, '\u5d07\u5de6\u5e02':208.68, '\u6765\u5bbe\u5e02':221.86, '\u67f3\u5dde\u5e02':400.00, '\u6842\u6797\u5e02':505.75, # \u5e7f\u897f\u58ee\u65cf\u81ea\u6cbb\u533a\n                        '\u68a7\u5dde\u5e02':303.7, '\u6cb3\u6c60\u5e02':352.35, '\u7389\u6797\u5e02': 581.08, '\u767e\u8272\u5e02':364.65, '\u8d35\u6e2f\u5e02':437.54, '\u8d3a\u5dde\u5e02':205.67,\n                        '\u94a6\u5dde\u5e02':328, '\u9632\u57ce\u6e2f\u5e02':94.02, \n                        '\u4e07\u5b81\u5e02':float(\"NaN\"), '\u4e09\u4e9a\u5e02':76.42, '\u510b\u5dde\u5e02':90.57, '\u6d77\u53e3\u5e02':227.21, '\u4e09\u6c99\u5e02':float(\"NaN\"), '\u4e1c\u65b9\u5e02':float(\"NaN\"), # \u6d77\u5357\u7701 ########## \n                        '\u4e34\u9ad8\u53bf':float(\"NaN\"), '\u4e50\u4e1c\u9ece\u65cf\u81ea\u6cbb\u53bf':float(\"NaN\"),'\u4e94\u6307\u5c71\u5e02':float(\"NaN\"),'\u4fdd\u4ead\u9ece\u65cf\u82d7\u65cf\u81ea\u6cbb\u53bf':float(\"NaN\"), '\u5b9a\u5b89\u53bf':float(\"NaN\"),'\u5c6f\u660c\u53bf':float(\"NaN\"),\n                        '\u6587\u660c\u5e02':float(\"NaN\"),'\u660c\u6c5f\u9ece\u65cf\u81ea\u6cbb\u53bf':float(\"NaN\"),'\u6f84\u8fc8\u53bf':float(\"NaN\"),'\u743c\u4e2d\u9ece\u65cf\u82d7\u65cf\u81ea\u6cbb\u53bf':float(\"NaN\"),'\u743c\u6d77\u5e02':float(\"NaN\"),'\u767d\u6c99\u9ece\u65cf\u81ea\u6cbb\u53bf':float(\"NaN\"),\n                        '\u9675\u6c34\u9ece\u65cf\u81ea\u6cbb\u53bf':float(\"NaN\"),\n                        '\u4fdd\u5b9a\u5e02':1046.92, '\u5510\u5c71\u5e02': 789.7, '\u5eca\u574a\u5e02':467.8, '\u5f20\u5bb6\u53e3\u5e02':443.3, '\u627f\u5fb7\u5e02':356.50, '\u6ca7\u5dde\u5e02':755.49, # \u6cb3\u5317\u7701\n                        '\u77f3\u5bb6\u5e84\u5e02':1087.99, '\u79e6\u7687\u5c9b\u5e02':311.08, '\u8861\u6c34\u5e02':446.04, '\u90a2\u53f0\u5e02':735.16, '\u90af\u90f8\u5e02':951.11, \n                        '\u4e4c\u5170\u5bdf\u5e03\u5e02':210.25, '\u4e4c\u6d77\u5e02':56.11, '\u5174\u5b89\u76df':160.42, '\u5305\u5934\u5e02':287.8, '\u547c\u4f26\u8d1d\u5c14\u5e02':252.92, '\u547c\u548c\u6d69\u7279\u5e02':311.5, # \u5185\u8499\u53e4\u81ea\u6cbb\u533a\n                        '\u5df4\u5f66\u6dd6\u5c14\u5e02':168.5, '\u8d64\u5cf0\u5e02':431.5, '\u901a\u8fbd\u5e02':312.87, '\u9102\u5c14\u591a\u65af\u5e02':206.87, '\u9521\u6797\u90ed\u52d2\u76df':105.16, '\u963f\u62c9\u5584\u76df':24.8,\n                        '\u4e34\u6c7e\u5e02':450.03, '\u5415\u6881\u5e02':388.56, '\u5927\u540c\u5e02':345.60, '\u592a\u539f\u5e02':442.15, '\u5ffb\u5dde\u5e02':317.20, '\u664b\u4e2d\u5e02':338.15, # \u5c71\u897f\u7701\n                        '\u664b\u57ce\u5e02':234.31, '\u6714\u5dde\u5e02':178.12, '\u8fd0\u57ce\u5e02':535.97, '\u957f\u6cbb\u5e02':346.8, '\u9633\u6cc9\u5e02':141.44, \n                        '\u4e09\u95e8\u5ce1\u5e02':227.29, '\u4fe1\u9633\u5e02':647.41, '\u5357\u9633\u5e02':1001.36, '\u5468\u53e3\u5e02':867.78, '\u5546\u4e18\u5e02':732.53, '\u5b89\u9633\u5e02':517.6, # \u6cb3\u5357\u7701\n                        '\u5e73\u9876\u5c71\u5e02':520.77, '\u5f00\u5c01\u5e02':456.49, '\u65b0\u4e61\u5e02':579.41, '\u6d1b\u9633\u5e02':688.85, '\u6d4e\u6e90\u5e02':73.27, '\u6f2f\u6cb3\u5e02':266.53,\n                        '\u6fee\u9633\u5e02':360.94, '\u7126\u4f5c\u5e02':359.07, '\u8bb8\u660c\u5e02':443.74, '\u90d1\u5dde\u5e02':1013.6, '\u9a7b\u9a6c\u5e97\u5e02':619.02, '\u9e64\u58c1\u5e02':162.73,\n                        '\u5a04\u5e95\u5e02':393.18, '\u5cb3\u9633\u5e02':579.71, '\u5e38\u5fb7\u5e02':582.7, '\u5f20\u5bb6\u754c\u5e02':153.79, '\u6000\u5316\u5e02':497.96, '\u682a\u6d32\u5e02':402.08, # \u6e56\u5357\u7701\n                        '\u6c38\u5dde\u5e02':545.21, '\u6e58\u6f6d\u5e02':286.5, '\u6e58\u897f\u571f\u5bb6\u65cf\u82d7\u65cf\u81ea\u6cbb\u5dde':264.95, '\u76ca\u9633\u5e02':441.38, '\u8861\u9633\u5e02':724.34, '\u90b5\u9633\u5e02':737.05,\n                        '\u90f4\u5dde\u5e02':474.5, '\u957f\u6c99\u5e02':815.47, \n                        '\u4ed9\u6843\u5e02':154.45, '\u5341\u5830\u5e02':341.8, '\u54b8\u5b81\u5e02':253.51, '\u5929\u95e8\u5e02':128.35, '\u5b5d\u611f\u5e02':491.50, '\u5b9c\u660c\u5e02':413.56, # \u6e56\u5317\u7701 ##########\n                        '\u6069\u65bd\u571f\u5bb6\u65cf\u82d7\u65cf\u81ea\u6cbb\u5dde':336.10, '\u6b66\u6c49\u5e02':1089.29, '\u6f5c\u6c5f\u5e02': float(\"NaN\"), '\u795e\u519c\u67b6\u6797\u533a':7.68, '\u8346\u5dde\u5e02':564.17, '\u8346\u95e8\u5e02':290.15,\n                        '\u8944\u9633\u5e02':565.4, '\u9102\u5dde\u5e02':107.69, '\u968f\u5dde\u5e02':221.05, '\u9ec4\u5188\u5e02':634.1, '\u9ec4\u77f3\u5e02':247.05, \n                        '\u4e0a\u9976\u5e02':678.34, '\u4e5d\u6c5f\u5e02':487.33, '\u5357\u660c\u5e02':546.35, '\u5409\u5b89\u5e02':494.19, '\u5b9c\u6625\u5e02':555.37, '\u629a\u5dde\u5e02':403.10, # \u6c5f\u897f\u7701 2018\n                        '\u65b0\u4f59\u5e02':118.07, '\u666f\u5fb7\u9547\u5e02':166.49, '\u840d\u4e61\u5e02':192.50, '\u8d63\u5dde\u5e02':861.2, '\u9e70\u6f6d\u5e02':116.75, \n                        '\u516d\u76d8\u6c34\u5e02':292.41, '\u5b89\u987a\u5e02':234.44, '\u6bd5\u8282\u5e02':665.97, '\u8d35\u9633\u5e02':480.20, '\u9075\u4e49\u5e02':624.83, '\u94dc\u4ec1\u5e02':315.69, # \u8d35\u5dde\u7701 2018\n                        '\u9ed4\u4e1c\u5357\u82d7\u65cf\u4f97\u65cf\u81ea\u6cbb\u5dde':352.37, '\u9ed4\u5357\u5e03\u4f9d\u65cf\u82d7\u65cf\u81ea\u6cbb\u5dde':327.1, '\u9ed4\u897f\u5357\u5e03\u4f9d\u65cf\u82d7\u65cf\u81ea\u6cbb\u5dde':286,\n                        '\u4e50\u5c71\u5e02':327.21, '\u5185\u6c5f\u5e02':375.37, '\u51c9\u5c71\u5f5d\u65cf\u81ea\u6cbb\u5dde':521.29, '\u5357\u5145\u5e02':641.79, '\u5b9c\u5bbe\u5e02':453, '\u5df4\u4e2d\u5e02':331.67, # \u56db\u5ddd\u7701 2018\n                        '\u5e7f\u5143\u5e02':266.00, '\u5e7f\u5b89\u5e02':325.0, '\u5fb7\u9633\u5e02':353.2, '\u6210\u90fd\u5e02':1604.5, '\u6500\u679d\u82b1\u5e02':123.61, '\u6cf8\u5dde\u5e02':431.72,\n                        '\u7518\u5b5c\u85cf\u65cf\u81ea\u6cbb\u5dde':118.63, '\u7709\u5c71\u5e02':297.48, '\u7ef5\u9633\u5e02':483.56, '\u81ea\u8d21\u5e02':290.14, '\u8d44\u9633\u5e02':255.3, '\u8fbe\u5dde\u5e02':568.95,\n                        '\u9042\u5b81\u5e02':323.59, '\u963f\u575d\u85cf\u65cf\u7f8c\u65cf\u81ea\u6cbb\u5dde':94.01, '\u96c5\u5b89\u5e02':153.78, \n                        '\u4e34\u6ca7\u5e02':252.60, '\u4e3d\u6c5f\u5e02':129.0, '\u4fdd\u5c71\u5e02':261.4, '\u5927\u7406\u767d\u65cf\u81ea\u6cbb\u5dde':361.88, '\u5fb7\u5b8f\u50a3\u65cf\u666f\u9887\u65cf\u81ea\u6cbb\u5dde':130.90, '\u6012\u6c5f\u5088\u50f3\u65cf\u81ea\u6cbb\u5dde':54.7, # \u4e91\u5357\u7701 2018\n                        '\u6587\u5c71\u58ee\u65cf\u82d7\u65cf\u81ea\u6cbb\u5dde':363.6, '\u6606\u660e\u5e02':678.3, '\u662d\u901a\u5e02': 553.7, '\u666e\u6d31\u5e02':262.7, '\u66f2\u9756\u5e02':612.2, '\u695a\u96c4\u5f5d\u65cf\u81ea\u6cbb\u5dde':274.40,\n                        '\u7389\u6eaa\u5e02':238.1, '\u7ea2\u6cb3\u54c8\u5c3c\u65cf\u5f5d\u65cf\u81ea\u6cbb\u5dde':471.3, '\u897f\u53cc\u7248\u7eb3\u50a3\u65cf\u81ea\u6cbb\u5dde':118.0, '\u8fea\u5e86\u85cf\u65cf\u81ea\u6cbb\u5dde':41.2,\n                        '\u54b8\u9633\u5e02':437.6, '\u5546\u6d1b\u5e02':238.13, '\u5b89\u5eb7\u5e02':266.1, '\u5b9d\u9e21\u5e02':378.10, '\u5ef6\u5b89\u5e02':226.31, '\u6986\u6797\u5e02':340.33, # \u9655\u897f\u7701\n                        '\u6c49\u4e2d\u5e02':344.93, '\u6e2d\u5357\u5e02':538.29, '\u897f\u5b89\u5e02':953.44, '\u94dc\u5ddd\u5e02':83.34,\n                        '\u4e34\u590f\u56de\u65cf\u81ea\u6cbb\u5dde':204.41, '\u5170\u5dde\u5e02':372.96, '\u5609\u5cea\u5173\u5e02':24.98, '\u5929\u6c34\u5e02':333.98, '\u5b9a\u897f\u5e02':280.84, '\u5e73\u51c9\u5e02':211.28, # \u7518\u8083\u7701\n                        '\u5e86\u9633\u5e02':200.55, '\u5f20\u6396\u5e02':122.93, '\u6b66\u5a01\u5e02':182.53, '\u7518\u5357\u85cf\u65cf\u81ea\u6cbb\u5dde':74.23, '\u767d\u94f6\u5e02':172.93, '\u9152\u6cc9\u5e02':112.36,\n                        '\u91d1\u660c\u5e02':46.92, '\u9647\u5357\u5e02':287.42, \n                        '\u679c\u6d1b\u85cf\u65cf\u81ea\u6cbb\u5dde':20.57, '\u6d77\u4e1c\u5e02':147.08, '\u6d77\u5317\u85cf\u65cf\u81ea\u6cbb\u5dde':28.3, '\u6d77\u5357\u85cf\u65cf\u81ea\u6cbb\u5dde':47.24, '\u6d77\u897f\u8499\u53e4\u65cf\u85cf\u65cf\u81ea\u6cbb\u5dde':51.52, '\u7389\u6811\u85cf\u65cf\u81ea\u6cbb\u5dde':40.95, # \u9752\u6d77\u7701\n                        '\u897f\u5b81\u5e02':235.50, '\u9ec4\u5357\u85cf\u65cf\u81ea\u6cbb\u5dde':27.42, \n                        '\u4e4c\u9c81\u6728\u9f50\u5e02':222.61, '\u4e94\u5bb6\u6e20\u5e02':float(\"NaN\"), '\u4f0a\u7281\u54c8\u8428\u514b\u81ea\u6cbb\u5dde':461.71, '\u514b\u5b5c\u52d2\u82cf\u67ef\u5c14\u514b\u5b5c\u81ea\u6cbb\u5dde':62.06, '\u514b\u62c9\u739b\u4f9d\u5e02':44.28, '\u5317\u5c6f\u5e02':float(\"NaN\"), # \u65b0\u7586\u7ef4\u543e\u5c14\u81ea\u6cbb\u533a 2018 ##########\n                        '\u535a\u5c14\u5854\u62c9\u8499\u53e4\u81ea\u6cbb\u5dde':47.54, '\u53cc\u6cb3\u5e02':float(\"NaN\"), '\u53ef\u514b\u8fbe\u62c9\u5e02':float(\"NaN\"), '\u5410\u9c81\u756a\u5e02':63.73, '\u548c\u7530\u5730\u533a':252.28, '\u54c8\u5bc6\u5e02':56.11,\n                        '\u5580\u4ec0\u5730\u533a':464.97, '\u56fe\u6728\u8212\u514b\u5e02':float(\"NaN\"), '\u5854\u57ce\u5730\u533a':15.2, '\u5df4\u97f3\u90ed\u695e\u8499\u53e4\u81ea\u6cbb\u5dde':127.93, '\u6606\u7389\u5e02':float(\"NaN\"), '\u660c\u5409\u56de\u65cf\u81ea\u6cbb\u5dde':161,\n                        '\u77f3\u6cb3\u5b50\u5e02':float(\"NaN\"), '\u94c1\u95e8\u5173\u5e02':float(\"NaN\"), '\u963f\u514b\u82cf\u5730\u533a':254.6, '\u963f\u52d2\u6cf0\u5730\u533a':67.16, '\u963f\u62c9\u5c14\u5e02':float(\"NaN\"),\n                        '\u4e2d\u536b\u5e02':115.75, '\u5434\u5fe0\u5e02':140.37, '\u56fa\u539f\u5e02':122.82, '\u77f3\u5634\u5c71\u5e02':80.29, '\u94f6\u5ddd\u5e02':222.54, # \u5b81\u590f\u56de\u65cf\u81ea\u6cbb\u533a 2018\n                        '\u5409\u6797\u5e02':415.35, '\u56db\u5e73\u5e02':320.4, '\u5ef6\u8fb9\u671d\u9c9c\u65cf\u81ea\u6cbb\u5dde':210.14, '\u677e\u539f\u5e02':275.41, '\u767d\u57ce\u5e02':190.9, '\u767d\u5c71\u5e02':119.5, # \u5409\u6797\u7701 2018\n                        '\u8fbd\u6e90\u5e02':117.94, '\u901a\u5316\u5e02':217.15, '\u957f\u6625\u5e02':748.9,\n                        '\u4e39\u4e1c\u5e02':239.5, '\u5927\u8fde\u5e02':698.75, '\u629a\u987a\u5e02':210.7, '\u671d\u9633\u5e02':295, '\u672c\u6eaa\u5e02':147.63, '\u6c88\u9633\u5e02':829.4, # \u8fbd\u5b81\u7701 2018\n                        '\u76d8\u9526\u5e02':143.65, '\u8425\u53e3\u5e02':243.8, '\u846b\u82a6\u5c9b\u5e02':277.0, '\u8fbd\u9633\u5e02':183.7, '\u94c1\u5cad\u5e02':299.8, '\u9526\u5dde\u5e02':296.4,\n                        '\u961c\u65b0\u5e02':186.2, '\u978d\u5c71\u5e02':344.0,\n                        '\u4e03\u53f0\u6cb3\u5e02':78.6, '\u4f0a\u6625\u5e02':115.9, '\u4f73\u6728\u65af\u5e02':234.5, '\u53cc\u9e2d\u5c71\u5e02':142.3, '\u54c8\u5c14\u6ee8\u5e02':955.0, '\u5927\u5174\u5b89\u5cad\u5730\u533a':43.93, # \u9ed1\u9f99\u6c5f\u7701 2018\n                        '\u5927\u5e86\u5e02':273.1, '\u7261\u4e39\u6c5f\u5e02':254.8, '\u7ee5\u5316\u5e02':527.6, '\u9e21\u897f\u5e02':175, '\u9e64\u5c97\u5e02':100.9, '\u9ed1\u6cb3\u5e02':160.5,\n                        '\u9f50\u9f50\u54c8\u5c14\u5e02':533.7\n                       }\n\n# Reset the unit of populations to be 1 instead of 10,000\nprovincial_population_dict.update((x, y*1e4) for x, y in provincial_population_dict.items())\ncity_population_dict.update((x, y*1e4) for x, y in city_population_dict.items())\n\n# Obtain the latitude and longitude of a province from the local dictionary\n# Save as a dictionary\ndef get_province_latlng_dict():\n    province_latlng_dict = {}\n    chn_latlng = pd.read_csv(_CHN_LatLng_DICT_, encoding='utf-8')\n    for key in provincial_capital_dict:\n        lat = chn_latlng[chn_latlng.city == provincial_capital_dict[key]]['lat'].tolist()[0]\n        lng = chn_latlng[chn_latlng.city == provincial_capital_dict[key]]['lng'].tolist()[0]\n        province_latlng_dict[key] = (lat, lng)\n    return province_latlng_dict\n\n# Save as a dataframe\ndef get_province_latlng_df():\n    data = pd.DataFrame.from_dict(province_latlng_dict, orient='index', columns = ['lat', 'lng'])\n    data = data.reset_index()\n    data = data.rename(columns={'index':'province_name'})\n    #data_gephi = data.rename(columns={'province_name':'id'})\n    #data_gephi.to_csv(r'./data/data_network_P2P_gephi_id.csv', index = False)\n    return data\n\nprovince_latlng_dict = get_province_latlng_dict()\nprovince_latlng_df = get_province_latlng_df()\n```\n\n\n```python\n# Settings on the Chinese font\ndef set_font(font_file):\n    if not os.path.exists(font_file):\n        print(font_file + \" not found.  If you wish to display Chinese characters in plots, please use set_font() to set the path to the font file.\")\n    else:\n        global _CHN_FONT_, _FONT_PROP_\n        _CHN_FONT_ = font_file\n        _FONT_PROP_ = mfm.FontProperties(fname=_CHN_FONT_)\n    return\n\nset_font('./STFANGSO.TTF')   # for displaying Chinese characters in plots\n\ndef use_chn():\n    return _CHN_FONT_ is None\n\n# Add English name for a province or a city\ndef add_en_location(df, tag = 'city'):\n    '''Add province_name_en, and city_name_en'''\n    chn_en = pd.read_csv(_CHN_EN_DICT_, encoding='utf-8')\n    translation = dict([t for t in zip(chn_en['Chinese'], chn_en['English'])])\n    if tag == 'province':\n        df['province_name_en'] = df['province_name'].replace(translation)\n    elif tag == 'city':\n        df['province_name_en'] = df['province_name'].replace(translation)\n        df['city_name_en'] = df['city_name'].replace(translation)\n    elif tag == 'network':\n        df['source_en'] = df['source'].replace(translation)\n        df['target_en'] = df['target'].replace(translation)\n    return df\n```\n\n\n```python\n# Data loading\n_Data_PATH_ = './data/parameters/'\n_Data_PATH_X_ = './data/parameters_x/'\n_Data_PATH_XX_ = './data/parameters_xx/'\n_Data_PATH_M_ = './data/parameters_m/'\n_Data_PATH_MX_ = './data/parameters_mx/'\n_Data_PATH_MXX_ = './data/parameters_mxx/'\n_City_PATH_ = './data/data_DXY_city_all.csv'\n_Province_PATH_ = './data/data_DXY_province_all.csv'\n_Province_Domestic_PATH_ = './data/data_DXY_province_all_domestic.csv'\n_Network_P2P_PATH_ = './data/data_network_P2P.csv'\n\ndef load_DXY_raw():\n    raw_city = pd.read_csv(_City_PATH_)\n    raw_province = pd.read_csv(_Province_PATH_) \n    raw_province_domestic = pd.read_csv(_Province_Domestic_PATH_) \n    raw_city['update_date'] = pd.to_datetime(raw_city['update_date'])\n    raw_city['update_date'] = raw_city['update_date'].dt.date \n    raw_province['update_date'] = pd.to_datetime(raw_province['update_date'])\n    raw_province['update_date'] = raw_province['update_date'].dt.date\n    raw_province_domestic['update_date'] = pd.to_datetime(raw_province_domestic['update_date'])\n    raw_province_domestic['update_date'] = raw_province_domestic['update_date'].dt.date\n    return raw_city, raw_province, raw_province_domestic\n\ndef load_network_raw():\n    # Do not distinguish between move_in and move_out\n    raw = pd.read_csv(_Network_P2P_PATH_) \n    raw['update_date'] = pd.to_datetime(raw['update_date'])\n    raw['update_date'] = raw['update_date'].dt.date \n    return raw\n\ndef load_ind_simulation_raw():\n    df_parameters_list = []\n    df_estimation_list = []\n    for name in names_province:\n        df_parameters_single = pd.read_csv(_Data_PATH_ + name + '_parameters.csv')\n        df_estimation_single = pd.read_csv(_Data_PATH_ + name + '_estimation.csv')\n        df_parameters_list.append(df_parameters_single)\n        df_estimation_list.append(df_estimation_single)\n    return df_parameters_list, df_estimation_list \n\n\ndef load_ind_simulation_raw_x():\n    df_parameters_list = []\n    df_estimation_list = []\n    for name in names_province:\n        df_parameters_single = pd.read_csv(_Data_PATH_X_ + name + '_parameters.csv')\n        df_estimation_single = pd.read_csv(_Data_PATH_X_ + name + '_estimation.csv')\n        df_parameters_list.append(df_parameters_single)\n        df_estimation_list.append(df_estimation_single)\n    return df_parameters_list, df_estimation_list \n\ndef load_ind_simulation_raw_xx():\n    df_parameters_list = []\n    df_estimation_list = []\n    for name in names_province:\n        df_parameters_single = pd.read_csv(_Data_PATH_XX_ + name + '_parameters.csv')\n        df_estimation_single = pd.read_csv(_Data_PATH_XX_ + name + '_estimation.csv')\n        df_parameters_list.append(df_parameters_single)\n        df_estimation_list.append(df_estimation_single)\n    return df_parameters_list, df_estimation_list  \n```\n\n\n```python\n# Some utility functions\n# Get the list of dates from the start_date to the end_date\ndef daterange(start_date, end_date):\n    for n in range(int ((end_date - start_date).days) + 1):\n        yield start_date + timedelta(n)\n        \n# Transform the migration edgelist to the migration matrix\ndef matrix_P2P(data_single, m):\n    mindex = np.zeros((m, m))\n    for i, name_i in enumerate(names_province):\n        for j, name_j in enumerate(names_province):\n            if i == j:\n                mindex[i][j] = 0\n            else:\n                temp = data_single[(data_single.source_en == name_i) & (data_single.target_en == name_j)].value.tolist()\n                if temp == []:\n                    mindex[i][j] = 0\n                else:\n                    mindex[i][j] = temp[0]\n    return mindex\n\n# Perform the operation for all migration data from the start_date to the end_date\ndef matrix_P2P_all(data_network_P2P, start_date, end_date):\n    mindex_list = []\n    m = len(names_province)\n    for item in daterange(start_date, end_date):\n        data_single = data_network_P2P[data_network_P2P.update_date == item]\n        mindex = matrix_P2P(data_single, m)\n        mindex_list.append(mindex) \n    return mindex_list\n```\n\n\n```python\n# The state names in the US (including D.C.)\n# Ignore oversea territories: American Samoa, Guam, Northern Mariana Islands, Puerto Rico, and Virgin Islands\n\nnames_state = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', \n                 'District of Columbia',\n                 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', \n                 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi',\n                 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York',\n                 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina',\n                 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia',\n                 'Wisconsin', 'Wyoming']\n\n# The abbreviations of state names\nnames_state_short_dict = {\n    'Alabama': 'AL', 'Alaska':'AK', 'Arizona':'AZ', 'Arkansas':'AR', 'California':'CA', 'Colorado':'CO', 'Connecticut':'CT', 'Delaware':'DE', \n    'Florida':'FL', 'Georgia':'GA', 'Hawaii':'HI', 'Idaho':'ID', 'Illinois':'IL', 'Indiana':'IN', 'Iowa':'IA', 'Kansas':'KS', \n    'Kentucky':'KY', 'Louisiana':'LA', 'Maine':'ME', 'Maryland':'MD', 'Massachusetts':'MA', 'Michigan':'MI', 'Minnesota':'MN', 'Mississippi':'MS',\n    'Missouri':'MO', 'Montana':'MT', 'Nebraska':'NE', 'Nevada':'NV', 'New Hampshire':'NH', 'New Jersey':'NJ', 'New Mexico':'NM', 'New York':'NY',\n    'North Carolina':'NC', 'North Dakota':'ND', 'Ohio':'OH', 'Oklahoma':'OK', 'Oregon':'OR', 'Pennsylvania':'PA', 'Rhode Island':'RI', 'South Carolina':'SC',\n    'South Dakota':'SD', 'Tennessee':'TN', 'Texas':'TX', 'Utah':'UT', 'Vermont':'VT', 'Virginia':'VA', 'Washington':'WA', 'West Virginia':'WV',\n    'Wisconsin':'WI', 'Wyoming':'WY', \n    'District of Columbia': 'DC', 'Guam': 'Guam', 'Northern Mariana Islands':'Northern Mariana Islands',\n    'Puerto Rico': 'PR', 'Virgin Islands': 'VI'}\n\n# The populations of states\nstate_population_dict = {\n    'Alabama': 4903185, 'Alaska':731545, 'Arizona':7278717, 'Arkansas':3017825, \n    'California':39512223, 'Colorado':5758736, 'Connecticut':3565287, 'Delaware':973764, \n    'Florida':21477737, 'Georgia':10617423, 'Hawaii':1415872, 'Idaho':1787065, \n    'Illinois':12671821, 'Indiana':6732219, 'Iowa':3155070, 'Kansas':2913314, \n    'Kentucky':4467673, 'Louisiana':4648794, 'Maine':1344212, 'Maryland':6045680, \n    'Massachusetts':6949503, 'Michigan':9986857, 'Minnesota':5639632, 'Mississippi':2976149,\n    'Missouri':6137428, 'Montana':1068778, 'Nebraska':1934408, 'Nevada':3080156, \n    'New Hampshire':1359711, 'New Jersey':8882190, 'New Mexico':2096829, 'New York':19453561,\n    'North Carolina':10488084, 'North Dakota':762062, 'Ohio':11689100, 'Oklahoma':3956971, \n    'Oregon':4217737, 'Pennsylvania':12801989, 'Rhode Island':1059361, 'South Carolina':5148714,\n    'South Dakota':884659, 'Tennessee':6833174, 'Texas':28995881, 'Utah':3205958, \n    'Vermont':623989, 'Virginia':8535519, 'Washington':7614893, 'West Virginia':1792147,\n    'Wisconsin':5822434, 'Wyoming':578759, 'District of Columbia': 705749, 'Guam': 165718, \n    'Puerto Rico': 3193694, 'Virgin Islands': 104914}\n```\n\n\n```python\n# The PVI values of states\ndf_state_pvi = pd.DataFrame(columns = ['state_name', 'partisan', 'value'])\ndf_state_pvi.loc[len(df_state_pvi)] = ['Alabama', 'R', 14]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Alaska', 'R', 9]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Arizona', 'R', 5]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Arkansas', 'R', 15]\n\ndf_state_pvi.loc[len(df_state_pvi)] = ['California', 'D', 12]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Colorado', 'D', 1]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Connecticut', 'D', 6]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Delaware', 'D', 6]\n\ndf_state_pvi.loc[len(df_state_pvi)] = ['Florida', 'R', 2]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Georgia', 'R', 5]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Hawaii', 'D', 18]\n\ndf_state_pvi.loc[len(df_state_pvi)] = ['Idaho', 'R', 19]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Illinois', 'D', 7]\n\ndf_state_pvi.loc[len(df_state_pvi)] = ['Indiana', 'R', 9]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Iowa', 'R', 3]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Kansas', 'R', 13]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Kentucky', 'R', 15]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Louisiana', 'R', 11]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Maine', 'D', 3]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Maryland', 'D', 12]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Massachusetts', 'D', 12]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Michigan', 'D', 1]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Minnesota', 'D', 1]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Mississippi', 'R', 9]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Missouri', 'R', 9]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Montana', 'R', 11]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Nebraska', 'R', 14]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Nevada', 'D', 1]\ndf_state_pvi.loc[len(df_state_pvi)] = ['New Hampshire', 'Even', 0]\ndf_state_pvi.loc[len(df_state_pvi)] = ['New Jersey', 'D', 7]\ndf_state_pvi.loc[len(df_state_pvi)] = ['New Mexico', 'D', 3]\ndf_state_pvi.loc[len(df_state_pvi)] = ['New York', 'D', 12]\ndf_state_pvi.loc[len(df_state_pvi)] = ['North Carolina', 'R', 3]\ndf_state_pvi.loc[len(df_state_pvi)] = ['North Dakota', 'R', 17]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Ohio', 'R', 3]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Oklahoma', 'R', 20]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Oregon', 'D', 5]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Pennsylvania', 'Even', 0]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Rhode Island', 'D', 10]\ndf_state_pvi.loc[len(df_state_pvi)] = ['South Carolina', 'R', 8]\ndf_state_pvi.loc[len(df_state_pvi)] = ['South Dakota', 'R', 14]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Tennessee', 'R', 14]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Texas', 'R', 8]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Utah', 'R', 20]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Vermont', 'D', 15]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Virginia', 'D', 1]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Washington', 'D', 7]\ndf_state_pvi.loc[len(df_state_pvi)] = ['West Virginia', 'R', 19]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Wisconsin', 'Even', 0]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Wyoming', 'R', 25]\ndf_state_pvi.loc[len(df_state_pvi)] = ['District of Columbia', 'D', 43]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Guam', 'None', 0]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Northern Mariana Islands', 'None', 0]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Puerto Rico', 'None', 0]\ndf_state_pvi.loc[len(df_state_pvi)] = ['Virgin Islands', 'None', 0]\n\ndef color_pvi(df_state_pvi, state):\n    \n    palette_D = plt.get_cmap('Blues')\n    palette_R = plt.get_cmap('Reds')\n    palette_Even = plt.get_cmap('Greens')\n    palette_None = plt.get_cmap('Purples')\n    \n    D_max = max(df_state_pvi[df_state_pvi['partisan'] == 'D']['value'])\n    D_min = min(df_state_pvi[df_state_pvi['partisan'] == 'D']['value'])\n    R_max = max(df_state_pvi[df_state_pvi['partisan'] == 'R']['value'])\n    R_min = min(df_state_pvi[df_state_pvi['partisan'] == 'R']['value'])\n    \n    partisan = df_state_pvi[df_state_pvi['state_name'] == state]['partisan'].tolist()[0]\n    value = df_state_pvi[df_state_pvi['state_name'] == state]['value'].tolist()[0]\n    if partisan == 'Even':\n        return palette_Even(0.6)\n    elif partisan == 'None':\n        return palette_None(0.6)\n    elif partisan == 'D':\n        return palette_D((value - D_min)/2/(D_max - D_min) + 0.3)\n    else:\n        return palette_R((value - R_min)/2/(R_max - R_min) + 0.3)\n```\n\n\n```python\n# Stock market data\n# S & P 500 index\ndef load_SP_raw():\n    '''\n    This provides a way to lookinto the 'raw' data\n    '''\n    SP = yf.Ticker(\"^GSPC\")\n    raw = SP.history(period=\"max\")\n    raw = raw.reset_index()\n    rename_dict = {'Date': 'update_date',\n                   'Open': 'open',\n                   'High': 'high',\n                   'Low': 'low',\n                   'Close': 'close',\n                   'Volume': 'volume',\n                   'Dividends': 'dividends',\n                   'Stock Splits': 'stock splits'\n                  }\n    data = raw.rename(columns=rename_dict)\n    data['update_date'] = pd.to_datetime(data['update_date'])  # original type of update_time after read_csv is 'str'\n    data['update_date'] = data['update_date'].dt.date\n    data = data.reset_index(drop=True)\n    print('Data date range: ', data['update_date'].min(), 'to', data['update_date'].max())\n    print('Number of rows in raw data: ', data.shape[0])\n    return data\n# Stock price of a certain cooperation\ndef load_STOCK_raw(name):\n    '''\n    This provides a way to lookinto the 'raw' data\n    '''\n    SP = yf.Ticker(name)\n    raw = SP.history(period=\"max\")\n    raw = raw.reset_index()\n    rename_dict = {'Date': 'update_date',\n                   'Open': 'open',\n                   'High': 'high',\n                   'Low': 'low',\n                   'Close': 'close',\n                   'Volume': 'volume',\n                   'Dividends': 'dividends',\n                   'Stock Splits': 'stock splits'\n                  }\n    data = raw.rename(columns=rename_dict)\n    data['update_date'] = pd.to_datetime(data['update_date'])  # original data type of update_time is 'str'\n    data['update_date'] = data['update_date'].dt.date\n    data = data.reset_index(drop=True)\n    #print('Data date range: ', data['update_date'].min(), 'to', data['update_date'].max())\n    #print('Number of rows in raw data: ', data.shape[0])\n    return data\n```\n\n\n```python\n# ODE systems\n#%%latex\n#Difference equations \n#without immigration\n#\\begin{align}\n#S(t + 1) - S(t) &= -\\beta(t)S(t)\\frac{I(t)}{N(t)}, \\\\\n#E(t + 1) - E(t) &= \\beta(t)S(t)\\frac{I(t)}{N(t)} - \\sigma(t)E(t), \\\\\n#I(t + 1) - I(t) &= \\sigma(t)E(t) - \\gamma(t)I(t), \\\\\n#R(t + 1) - R(t) &= \\gamma(t)I(t)\n#\\end{align}\n#Difference equations \n#with immigration\n#\\begin{align}\n#S_i(t + 1) - S_i(t) &= -\\beta_i(t)S_i(t)\\frac{I_i(t)}{N_i(t)} - \\sum_{j, j \\neq i}a_{ij}(t)S_i(t) + \\sum_{j, j \\neq i}a_{ji}(t)S_j(t) \\\\\n#E_i(t + 1) - E_i(t) &= \\beta_i(t)S_i(t)\\frac{I_i(t)}{N_i(t)} - \\sigma_i(t)E_i(t) - \\sum_{j, j \\neq i}a_{ij}(t)E_i(t) + \\sum_{j, j \\neq i}a_{ji}(t)E_j(t) \\\\\n#I_i(t + 1) - I_i(t) &= \\sigma_i(t)E_i(t) - \\gamma_i(t)I_i(t) \\\\\n#R_i(t + 1) - R_i(t) &= \\gamma_i(t)I_i(t)\n#\\end{align}\n```\n", "meta": {"hexsha": "3ea678f3615398f656e4c4b55aba9ef52a5a2d51", "size": 33699, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "scripts/utils_common.ipynb", "max_stars_repo_name": "fudab/US-COVID-19-Impact-Assesements-", "max_stars_repo_head_hexsha": "6427a5f7b05956038222850d9c362e79a8c83d6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-04-23T01:13:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-24T13:42:30.000Z", "max_issues_repo_path": "scripts/utils_common.ipynb", "max_issues_repo_name": "fudab/US-COVID-19-Impact-Assesements-", "max_issues_repo_head_hexsha": "6427a5f7b05956038222850d9c362e79a8c83d6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/utils_common.ipynb", "max_forks_repo_name": "fudab/US-COVID-19-Impact-Assesements-", "max_forks_repo_head_hexsha": "6427a5f7b05956038222850d9c362e79a8c83d6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.3292253521, "max_line_length": 175, "alphanum_fraction": 0.5179678922, "converted": true, "num_tokens": 10901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742625267332647, "lm_q2_score": 0.04023794693960912, "lm_q1q2_score": 0.012772580712308268}}
{"text": "##### Copyright 2020 Google\n\n\n```\n#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# Quantum chess\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n  <td>\n    <a target=\"_blank\" href=\"https://quantumai.google/cirq/experiments/quantum_chess/concepts\">View on QuantumAI</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/ReCirq/blob/master/docs/quantum_chess/concepts.ipynb\">Run in Google Colab</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://github.com/quantumlib/ReCirq/blob/master/docs/quantum_chess/concepts.ipynb\">View source on GitHub</a>\n  </td>\n  <td>\n    <a href=\"https://storage.googleapis.com/tensorflow_docs/ReCirq/docs/quantum_chess/concepts.ipynb\">Download notebook</a>\n  </td>\n</table>\n\nThis tutorial illustrates some techniques to navigate through challenges of bringing a theoretical quantum algorithm to the reality of NISQ devices.  Quantum Chess serves as an example to demonstrate these ideas without some of the domain knowledge needed in other experiments.  \n\nThis tutorial assumes basic knowledge of the following:\n\n*   Basic quantum computing principles, specifically, what unitary matrices are, and what an $\\text{iSWAP}$ (and $\\sqrt{\\text{iSWAP}}$ gate is)\n*   The basic movement rules of [Chess](https://en.wikipedia.org/wiki/Chess#Movement) and the [Algebraic notation](https://en.wikipedia.org/wiki/Algebraic_notation_(chess)) method of naming chess squares and moves.\n\n\n\n\n*   The [Cirq](https://github.com/quantumlib/Cirq) framework for constructing quantum circuits.\n*   While the tutorial will briefly cover the rules of quantum chess, those who are unfamiliar with this game may [try it out](https://quantumchess.net/play/) or read the exact rules in the [Quantum Chess paper](https://arxiv.org/abs/1906.05836).  You can also find a sample implementation in this repository under `recirq.quantum_chess`.\n\nThe goal of this tutorial is to illustrate some basic ideas of transforming a theoretical algorithm (such as Quantum Chess) into a real hardware algorithm, without getting lost in details of more complicated domain-specific problems.  \n\nThe tutorial is split into several parts:\n\n1.   **Introduction to Quantum Chess**: how quantum chess maps to qubits and quantum operations\n2.   **Quantum chess in Cirq**: how to execute these operations using the cirq framework\n3.   **Handling partial measurement**:  how to handle moves that include measurement that partially collapses the board state\n4.   **Noise**: how to deal with some simple noise models\n5.   **Decomposition**: how to decompose gates\n6.   **Qubit Layout**: how to run circuits when connectivity matters.\n\nYou will learn about the concepts of **circuit construction**, **post-selection**, **gate decomposition**, **noise**, **optimizers**, and **qubit mappings**.\n\nFirst, let's get started by installing cirq on our colab runtime:\n\n\n```\ntry:\n    import recirq\nexcept ImportError:\n    !pip install --quiet git+https://github.com/quantumlib/ReCirq\n```\n\n\n```\nimport cirq\nfrom typing import Dict, Iterable, Optional, Set\n```\n\n## Introduction to Quantum Chess\n\nQuantum chess is analogous to the classical game of [Chess](https://en.wikipedia.org/wiki/Chess).  Special rules are added to the game in order to allow for superposition and entanglement of pieces.  This tutorial will go over the basics of the rules in order to show how one might implement them in cirq and convert them to use a hardware device.  The full rule set, including rules for more complicated situations (such as castling and en passant) can be found in the [Quantum Chess paper](https://arxiv.org/abs/1906.05836).  A demo where you can try moves out and play around on a sandbox board and test your knowledge with puzzles is available at [quantumchess.net](https://quantumchess.net/play/).\n\nIn order to introduce the game, we will first go over how the board is represented and then go over several of the moves.\n\n### Quantum Chess Board Representation\n\nIn classical chess, each square can be represented by one bit determining whether the square is empty (0) or occupied (1) as well as short integer or 'enum' to distinguish the color and type of piece (e.g. King, Queen, Knight, Bishop, Rook, or Pawn).  \n\nQuantum chess will also use the same classical register to store the type of piece, since each square can only have one type of piece in it.  Since the storage of the piece type is entirely classical, we will ignore it throughout the rest of this tutorial and focus on the quantum aspects of the game.\n\nClassical chess squares have only two states.  Each square is either occupied or not.  For a quantum version of the game, we will want to allow a continuous spectrum of possibilities of the square's occupancy, as represented by a quantum bit, or qubit.\n\nIn quantum chess, each square is represented by a single qubit.  If the qubit is in the |1> state, the square is occupied by a piece.  If the qubit is in the |0> state, the square is empty.\n\nA board state will be a set of qubits that represent a set of squares.  We will often consider a board that is smaller than the standard 8x8 board of chess so that we can more easily illustrate concepts.\n\nFor instance, let's consider a 3x3 board.  This board will have 9 squares (a1, a2, a3, b1, b2, b3, c1, c2, c3).  We will represent this as a 'ket' string such as this, with spaces to denote row boundaries for ease of reading:\n\n```\n|a1a2a3 b1b2b3 c1c2c3 >\n```\n\nFor instance, `|000 000 000>` would represent the empty 3x3 board.  `|010 000 000>` would represent a piece on the 'a2' square.  States can also represent boards with multiple pieces.  `|000 000 110>` would represent a board with pieces on both 'c1' and 'c2'.  Each of these three states is denoted as a **basis state**.\n\nA state can also be a super-position of board states.  For instance, \n$\\frac{1}{\\sqrt{2}}$ `( |100 000 000> + |010 000 000> )` represents a piece being in superposition of being on 'a1' and 'a2'.  This tutorial will often drop the normalization factor such as $\\frac{1}{\\sqrt{2}}$ when it doesn't matter to the explanation.\n\n\n#### Additional qubits\n\nNote that there are some exceptions that require extra qubits beyond the requirement of one qubit per square.  These extra qubits (often called \"ancilla\" qubits) are needed to store captured pieces and to store extra information, such as whether a path is blocked by a piece.  We will ignore these extra ancilla qubits for now in order to keep the tutorial focused.\n\n### Quantum Chess Moves\n\nWe will be studying a subset of possible quantum chess moves in this tutorial.\n\nWe will primarily consider the following moves to implement on the hardware:\n\n#### Basic jump move\n\nThis maneuver will be applied when we wish to apply a standard chess move to a piece.  This will be how kings and knights move.  In classical chess, we would remove the piece from its original square and then add it to the target square we are moving it to.\n\nFor quantum chess, we would like to do an analogous operation that preserves any quantum information.  In order to do this, we will swap the two squares.  We will do this by performing an **iSWAP** gate between the two qubits that represent those squares.  Note that this operation will also add a phase of *i* onto the qubits in addition to swapping them, adding a uniquely quantum aspect to the move.\n\n\n\nFor example, if we attempt to move a King piece from the 'a1' square to the 'b1' square, we will perform a iSWAP gate between the qubits that represent the 'a1' and 'b1' squares.\n\n#### Split move\n\nThe split move is unique to quantum chess.  This move will be analogous to moving a piece to two different target squares simultaneously.  If we were to then measure the quantum board, we should get a 50% probability of seeing the piece in either of the two target squares.\n\nThis will be accomplished by doing a $\\sqrt{\\text{iSWAP}}$ between the source and the first target.  This will create an equal superposition between the source and the first target square.  We would finish the move by performing a iSWAP between the source square and second target square.  This will create an equal superposition between the two target squares.\n\n\n\nFor example, suppose that that we split move a King on 'a1' to the squares 'b1' and 'b2'.  To do this, we would do a $\\sqrt{\\text{iSWAP}}$ between the qubits representing 'a1' and 'b1' followed by an **iSWAP** on the 'a1' and 'b2' qubits.  A short-hand notation for this move is *Ks1^t1t2* for source square s1 and split targets t1 and t2.  This example would be noted as *Ka1^b1b2*.\n\n#### Slide move\n\nA slide move is how we will move bishops, queens, and rooks.  These pieces move along a straight path, but cannot pass through intervening pieces.  However, in quantum chess, there may be a piece that is in superposition and may or may not block the path of this move.\n\nIn order to accomplish this move without measuring (and thereby destroying the quantum nature of the game), we will need to **entangle** the two pieces.  The way we will do this is called a \"controlled\" gate.  A [controlled gate](https://en.wikipedia.org/wiki/Quantum_logic_gate#Controlled_(cX_cY_cZ)_gates) is a gate that is only performed if the control qubit(s) are in the `|1>` state.\n\nThis tutorial will only consider paths that are blocked by one possible piece.  In this case, we will perform a **controlled-iSWAP** between the source square and target square controlled by the square that is potentially blocking the path.\n\n\n\nFor example, suppose we are moving a rook from 'a1' to 'c1', but there is a split knight on 'b1'.  To perform this slide move, we would do an iSWAP between the qubits that represent 'a1' and 'c1' controlled by the 'b1' qubit.  This operation can result in two potential states.  Either the rook is on 'c1' and the knight is not on 'b1' (path was open) or, alternatively, the rook is on 'a1' and the knight is on 'b1' (path was blocked).  The quantum board state cannot be described without mentioning the relationship between the 'b1' and 'a1'/'c1' squares, so we can say that those squares are *entangled*.\n\n#### Exclusion move\n\nIt was mentioned earlier that each square must have only one type of piece.  For instance, a square cannot have 0.1 of a knight and 0.5 of a rook.  This would not be allowed.  This is called the 'no double occupancy' rule.  We will use measurement as a tool to prevent this situation and disambiguate the type of the piece.\n\nThis can happen in a variety of circumstances, but we will only consider the case where a piece attempts to make a legal, standard move into a square with a piece of its own color.  \n\n\n\nFor instance, suppose we attempt to move a king from 'a1' to 'a2' and there is a split knight on the 'a2' square.  We would then need to measure the 'a2' square.  If the measurement is 1, then the knight occupies the square and the king cannot move.  If the measurement is 0, the knight is not on the square and the king moves successfully.  In this case, we have a classical 'mixture' of states.  Half the time, we would get the king on 'a1' and the knight on 'a2'.  The other half of the time, the king would be on 'a2'.  However, since we have measured and projected the state to one of these possibilities, there would be no superposition or entanglement, and this part of the board would be in a classical state (definitively in either one configuration or the other).\n\n#### Other moves\n\nThese four type of moves are enough to illustrate the complexities of translating an abstract algorithm (quantum chess) onto a concrete hardware implementation.  However, those who are curious can see the full rule set in the [Quantum Chess](https://arxiv.org/abs/1906.05836) paper on arXiv, including for capture, en passant, and castling.\n\n**Exercise for the reader**: This describes one possible rule set for translating the game of chess into the quantum world.  How might the game change if you use SWAP gates instead of iSWAP gates?  Can you devise ways to tell the two games apart?  Can you think of other methods to create split moves or other interesting alternatives?\n\n\n## Quantum Chess Simulation\n\nNow that we have introduced the moves of quantum chess and their corresponding circuits, let's look at how we might actually perform our quantum chess moves and circuits in hardware.  We will first start by learning how to implement them in cirq and how to execute them using cirq's built-in simulator.\n\nIf we consider that a chess board has 64 squares, then the simulation will need 64 qubits.  Since any combination of these bits is a valid basis state of the system, this means that, in order to do a complete simulation, we will need to keep track of $2^{64}$ states, which is something around 10 quintillion states.  This is obviously infeasible.\n\nHowever, most of these positions are unreachable by any common set of moves.  For most reasonable positions, there is a much smaller amount of superposition, so we do not need to keep track of all of those states, since the probability of those states is zero and will remain zero after we make our moves.\n\nFor example, the initial position is a classical position, so we only need to keep track of one possible state, where the initial squares are in the |1> state and the empty squares are in the |0> state.  After we make a split move, now we have to keep track of two states.  Each successive move on the board will need to tabulate its effect on both of these possible states.\n\n**Example**:\n\nLet's consider a 3x3 board as defined above with one King piece that starts in the square 'a1'.  This initial state is:\n\n```\n|100 000 000>\n```\n\nNote that, since there are 9 squares, there are $2^9=512$ possible basis states and a position on this board could be a superposition of any of the 512 basis states.  \n\nFor instance, let's suppose that we now perform a split move from 'a1' to 'b1' and 'b2'.  Then the state will be (ignoring the factor of $i/{\\sqrt{2}}$): \n\n```\n|000 010 000> + |000 100 000>\n```\n\n\n\n\nNow, suppose that we make two additional moves.  First, we will split the \"half-king\" on 'b1' to 'c1' and 'c2'.  Next, we will split the 'half king' on 'b2' to 'b3' and 'c3'.\n\nSo, despite that we have made three split moves that involve almost all of the squares on the board, we still only have to worry about 4 of the 512 states on the board.  The state is now (ignoring the constant factor):\n\n```\n|000 000 100> + |000 000 010> + |000 001 000> + |000 000 001>\n```\n\nOf course, if we continue splitting moves, we will eventually get to a large number of potential states.  However, we will never need to consider all 512 states in this example, since some states can never be reached by a sequence of moves.  For instance, the state `|110 000 000>` represents a king on a1 *and* a king on b1.  There's no way where we can start the board with one king on the board and suddenly wind up with two kings (unless we have noise, more on that later).\n\n**Exercise to the reader**: How many basis states are possible to include in a superposition if we allow the player to make as many normal/split moves as they want? How many superpositions are possible?\n\n**Summary**\n\nSince the space of possible quantum chess positions is *much* smaller than the space of possible quantum states, it is very tractable to simulate quantum chess if we have a custom simulator tuned to consider only relevant states.\n\n\n## Quantum Chess in Cirq\n\nNext, let's define each of these moves in cirq.  We will define a function for each of three possible moves we are considering.  Each of these will use make use of a python structure called [generators](https://wiki.python.org/moin/Generators) which allows us to 'yield' one or more operations.  This will allow us to use these functions very flexibly while we construct circuits.\n\nIn addition, we will define a function for placing a piece on the board.  Cirq simulators initialize into the zero state (an empty board), so we will use an 'X' gate to turn on a qubit and place a piece on the board.\n\n\n```\ndef normal_move(s: cirq.Qid, t: cirq.Qid):\n    \"\"\"A normal move in quantum chess.\n\n    This function takes two qubits and returns a generator\n    that performs a normal move that moves a piece from the\n    source square to the target square.\n\n    Args:\n        s: source qubit (square where piece starts)\n        t: target qubit (square to move piece to)\n    \"\"\"\n    yield cirq.ISWAP(s, t)\n\n\ndef split_move(s: cirq.Qid, t1: cirq.Qid, t2: cirq.Qid):\n    \"\"\"A Split move in quantum chess.\n\n    This function takes three qubits and returns a generator\n    that performs a split move from the source qubit to the\n    two target qubits.\n\n    Args:\n        s: source qubit (square where piece starts)\n        t1: target qubit (first square to move piece to)\n        t2: target qubit (second square to move piece to)\n    \"\"\"\n    yield cirq.ISWAP(s, t1) ** 0.5\n    yield cirq.ISWAP(s, t2)\n\n\ndef slide_move(s: cirq.Qid, t: cirq.Qid, p: cirq.Qid):\n    \"\"\"A Slide move in quantum chess.\n\n    This function takes three qubits and returns a generator\n    that performs a slide move.  This will move a piece\n    from the source to the target controlled by the path qubit.\n    The move will only occur if the path qubit is turned on\n    (i.e. path qubit should be one if the path is unblocked).\n\n    Args:\n        s: source qubit (square where piece starts)\n        t: target qubit (square to move piece to)\n        p: path qubit that determines whether move should occur\n    \"\"\"\n    yield cirq.ISWAP(s, t).controlled_by(p)\n\n\ndef place_piece(s: cirq.Qid):\n    \"\"\"Place a piece on the board.\n\n    This is not actually a move.  However, since qubits in Cirq\n    default to starting in the |0> state, we will need to activate\n    the qubit by applying an X gate to initialize the position.\n    \"\"\"\n    yield cirq.X(s)\n```\n\nNow that the moves are defined as gates in Cirq, let's now define the qubits.  Since we haven't figured out how we will represent this on the hardware, we will use Cirq's concept of `NamedQubit` in order to define the squares as logical qubits without defining a device topology.  This may feel unusual to some, but it can be compared to \"textbook\" circuits that have lines for abstract qubits that are unnamed or have simple symbolic names.  We will first try to define our algorithm in the abstract case, then move towards a physical representation at the end of this colab.\n\n\n```\na1 = cirq.NamedQubit(\"a1\")\na2 = cirq.NamedQubit(\"a2\")\na3 = cirq.NamedQubit(\"a3\")\nb1 = cirq.NamedQubit(\"b1\")\nb2 = cirq.NamedQubit(\"b2\")\nb3 = cirq.NamedQubit(\"b3\")\nc1 = cirq.NamedQubit(\"c1\")\nc2 = cirq.NamedQubit(\"c2\")\nc3 = cirq.NamedQubit(\"c3\")\n\nall_squares = [a1, a2, a3, b1, b2, b3, c1, c2, c3]\n```\n\nNow that we have a 3x3 'board' of qubits, let's try to perform some moves.\n\nLet's try to create the circuit mentioned in our simulator example that places a king on the 'a1' square, then splits to 'b1' and 'b2', then further splits to 'c1' and 'c2' and then to 'b3' and 'c3'.\n\n\n```\nking_moves = cirq.Circuit(\n    place_piece(a1),\n    split_move(a1, b1, b2),\n    split_move(b1, c1, c2),\n    split_move(b2, b3, c3),\n)\n\n# Let's print out the circuit to see what it does\nprint(king_moves)\n\n# Let's also simulate it using cirq's built-in simulator\nsim = cirq.Simulator()\nsim.simulate(king_moves)\n```\n\n                           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    a1: \u2500\u2500\u2500X\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n               \u2502            \u2502\n    b1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                            \u2502    \u2502             \u2502\n    b2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\n                                 \u2502             \u2502    \u2502            \u2502\n    b3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                 \u2502             \u2502                 \u2502\n    c1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                               \u2502                 \u2502\n    c2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                                                 \u2502\n    c3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\n                           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\n\n\n\n\n    measurements: (no measurements)\n    output vector: -0.5|0000001\u27e9 - 0.5|0000010\u27e9 - 0.5|0000100\u27e9 - 0.5|0001000\u27e9\n\n\n\nFantastic!  We can clearly see that the result from the simulator shows a superposition of 4 states!  So far, so good.  \n\nLet's try a slightly more complicated example involving two pieces and an exclusion move that forces a measurement.  \n\nLet's start with a king on 'a1' and a queen on 'a3'.  We will split the king onto 'b1' and 'b2' as before.  Next, we will split move the king on 'b1' to 'c1' and 'c2'.  Lastly, we will try to move the queen from 'a3' to 'b2'.\n\n\n\nThis will trigger a condition known as \"double occupancy\".  We are not allowed to have two pieces of different types in the same square.  If the king is in 'b2', the queen cannot move there. If the king is not in 'b2', then the move is legal. Thus, we will need to do a measurement.  Let's see how that works.\n\n\n\n```\nexclusion_moves = cirq.Circuit(\n    place_piece(a1),\n    place_piece(a3),\n    split_move(a1, b1, b2),\n    split_move(b1, c1, c2),\n)\nexclusion_move_circuit = exclusion_moves + cirq.measure(b2)\n\n\n# Let's print out the circuit to see what it does\nprint(\"Exclusion move circuit:\")\nprint(exclusion_move_circuit)\n\n# This time, we have a measurement in the circuit.\n# Let's simulate it several times to see what happens.\nsim = cirq.Simulator()\nprint(\"Measurement Results:\")\nfor t in range(8):\n    print(f\"--- Outcome #{t} ---\")\n    print(sim.simulate(exclusion_move_circuit))\n```\n\n    Exclusion move circuit:\n                           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    a1: \u2500\u2500\u2500X\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n               \u2502            \u2502\n    a3: \u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n               \u2502            \u2502\n    b1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\n                            \u2502    \u2502             \u2502\n    b2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\n                                 \u2502             \u2502\n    c1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                               \u2502\n    c2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\n                           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n    Measurement Results:\n    --- Outcome #0 ---\n    measurements: b2=0\n    output vector: -0.707|010001\u27e9 - 0.707|010010\u27e9\n    --- Outcome #1 ---\n    measurements: b2=1\n    output vector: 1j|010100\u27e9\n    --- Outcome #2 ---\n    measurements: b2=1\n    output vector: 1j|010100\u27e9\n    --- Outcome #3 ---\n    measurements: b2=0\n    output vector: -0.707|010001\u27e9 - 0.707|010010\u27e9\n    --- Outcome #4 ---\n    measurements: b2=0\n    output vector: -0.707|010001\u27e9 - 0.707|010010\u27e9\n    --- Outcome #5 ---\n    measurements: b2=1\n    output vector: 1j|010100\u27e9\n    --- Outcome #6 ---\n    measurements: b2=1\n    output vector: 1j|010100\u27e9\n    --- Outcome #7 ---\n    measurements: b2=1\n    output vector: 1j|010100\u27e9\n\n\nIn this configuration, you should see two different results.  If we measured the king to be at 'b2', then the position is resolved to a single basis state, equivalent to a classical position (the king is at 'b2' and the queen is at 'a3').\n\nIf the 'b2' square is measured to be empty, then the board is still in a state of superposition.  \n\n## Handling Partial Measurement\n\nSo far, we have been simulating this using `cirq.simulate()` which shows us the waveform of the system and its internal state.  In a quantum device, we do not have this information.  All we have is the measurement data that we get out of the device.  Let's try both of these circuits again with the simulator, but denying ourselves access to the underlying wave function, solely using measurement results. \n\nFirst, we will need to add measurements to our previous circuits so that we can access statistical data.\n\n\n\n```\n# Define a measurement operation that measures all the squares\nmeasure_all_squares = cirq.measure(*all_squares, key=\"all\")\n\n# Measure all squares at the end of the circuit\nking_moves_measured = king_moves + measure_all_squares\nexclusion_move_measured = exclusion_moves + measure_all_squares\n\nprint(\"Split moving the king:\")\nprint(king_moves_measured)\nresults = sim.run(king_moves_measured, repetitions=1)\nprint(results)\n\nprint(\"Attempting an exclusion move:\")\nresults = sim.run(exclusion_move_measured, repetitions=1)\nprint(results)\n```\n\n    Split moving the king:\n                           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    a1: \u2500\u2500\u2500X\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M('all')\u2500\u2500\u2500\n               \u2502            \u2502                                            \u2502\n    a2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n               \u2502            \u2502                                            \u2502\n    a3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n               \u2502            \u2502                                            \u2502\n    b1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                            \u2502    \u2502             \u2502                         \u2502\n    b2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                 \u2502             \u2502    \u2502            \u2502       \u2502\n    b3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                 \u2502             \u2502                 \u2502       \u2502\n    c1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                               \u2502                 \u2502       \u2502\n    c2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                                                 \u2502       \u2502\n    c3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n    all=0, 0, 0, 0, 0, 1, 0, 0, 0\n    Attempting an exclusion move:\n    all=0, 0, 1, 0, 0, 0, 1, 0, 0\n\n\nYou'll notice that, if you run the above block multiple times, you will get different results.\n\nWe will need a way to compile these into a statistical measure.  For this, we will need to increase the number of repetitions, and then combine them into a histogram.  Let's write a simple function to aggregate the results from the simulator (which are returned in a numpy array) into a more convenient form for us.\n\n\n```\ndef histogram_of_squares(results):\n    \"\"\"Creates a histogram of measurement results per square.\n\n    Returns:\n        Dict[str, int] where the key is the name of the square and the\n        value is the number of times the square was measured in the one state.\n    \"\"\"\n    sampling_frequency = {}\n    for idx, sq in enumerate(all_squares):\n        sampling_frequency[str(sq)] = results.measurements[\"all\"][:, idx].sum()\n    return sampling_frequency\n\n\n# Let's test out this histogram on the two circuits we've examined so far:\n\nprint(\"Split moving the king:\")\nsplit_results = sim.run(king_moves_measured, repetitions=1000)\nprint(histogram_of_squares(split_results))\n\nprint(\"Attempting an exclusion move:\")\nexclusion_results = sim.run(exclusion_move_measured, repetitions=1000)\nprint(histogram_of_squares(exclusion_results))\n```\n\n    Split moving the king:\n    {'a1': 0, 'a2': 0, 'a3': 0, 'b1': 0, 'b2': 0, 'b3': 257, 'c1': 255, 'c2': 250, 'c3': 238}\n    Attempting an exclusion move:\n    {'a1': 0, 'a2': 0, 'a3': 1000, 'b1': 0, 'b2': 515, 'b3': 0, 'c1': 221, 'c2': 264, 'c3': 0}\n\n\nWe can now see the frequencies of different possibilities.  For our first situation, we can see the king has four possibilities with approximately the same amount of occurrences.  Due to statistical variations, the exact number of occurrences in each of the four squares is not exactly the same.\n\n\nOur second exclusion move example illustrates the king's possible position on the three different squares, but we have not yet figured out how to implement the queen's exclusion and measurement with the king.\n\nHow are we going to do that?\n\nFirst, we need to pick a sample that will become our official \"measurement\" for the board.  We will freeze the seed for the random number generator so that everyone running this colab gets the same measurement and measure the square we care about (b2).\n\n\n\n```\nexclusion_move_measure_b2 = exclusion_moves + cirq.measure(b2)\n\nthis_sim = cirq.Simulator(seed=1234)\nmeasurement_for_move = this_sim.run(exclusion_move_measure_b2, repetitions=1)\nprint(measurement_for_move)\n```\n\n    b2=0\n\n\nWhen we measure the square 'b2', it is empty.  (The above should consistently print out 'b2=0'.  If it doesn't, you can change your seed so it does).  Thus, we can now move the queen.\n\nOk, we are now ready to make the next move.  How do we figure out the statistics of the board and be able to compute the (quantum) state of the board so that we can continue the game?\n\n\nLet's try to move the queen and see what happens:\n\n\n```\n# Calculate the state of the board after moving the queen\nafter_exclusion_move = (\n    cirq.Circuit(\n        place_piece(a1),\n        place_piece(a3),\n        split_move(a1, b1, b2),\n        split_move(b1, c1, c2),\n        normal_move(a3, b2),\n    )\n    + measure_all_squares\n)\n\n# Compute statistics for the pieces.\nafter_results = this_sim.run(after_exclusion_move, repetitions=1000)\nprint(histogram_of_squares(after_results))\n```\n\n    {'a1': 0, 'a2': 0, 'a3': 520, 'b1': 0, 'b2': 1000, 'b3': 0, 'c1': 232, 'c2': 248, 'c3': 0}\n\n\nUh oh.  This is not correct.  The queen now has 100% probability of being on 'b2', but there is now a king at 'a3' with approximately 50% probability.\n\nThe problem is that we are including both the possibility that the king was at 'b2' as well as the possibility that it was empty.  Instead of initializing the king to 'a1', we could initialize the king to 'b1' and just do one split move from 'b1' to 'c1' and 'c2' instead of performing all operations since the beginning of the game.\n\nThis has two issues.  First is that we are cheating somewhat by using the simplicity of this toy example to only include paths that are possible.  In a more complicated game, with pieces and merges happening, it may be a lot more difficult to simplify the circuit in a way that replicates the results of a measurement.  The second problem is that we have discarded information about the relative phases of the pieces.  For instance, the different squares could have picked up phases of $i$, and we would not be able to tell by just looking at the measurement results.  We may be destroying this information by simplifying the circuit.\n\n**Exercise to the reader**:  Is the phase actually the same or different if we compute the shorter circuit?\n\nSo then, how do we handle this?\n\n## Post-selection\n\nOne way of resolving this is to use the method of \"post-selection\".  Both simulators and real hardware have the ability to repeat an experiment many times.  We can use this ability to pick the samples that match our expectations of the results.  \n\nIn the example above, we have two independent possibilities for the measurement of the king.  Half of results will have 'm0' (the king was on the square preventing the queen move) and half will have 'm1' result (the king was not there and the queen move was possible).  In our game, we know that 'm0' is what happened, so we can run the simulation multiple times and only take the results that are consistent with 'm0'.\n\nThis procedure is only needed since we need to run the simulation from the beginning of the board each time.  If we could \"save\" the state vector from the last move, we would not need to do this.  We could just apply the next move on the last state vector.  While this is possible in a classical simulator, quantum states in a real device only stay coherent for mere microseconds and won't wait around while we ponder our next quantum chess move.\n\nA quantum algorithm that uses results of measurements to affect later steps is called a \"feed-forward\".  We are going to use post-selection to transform the current feed-forward algorithm of quantum chess into an algorithm that has terminal measurements only.\n\nWe will transform our first algorithm from:\n\n*  Make some non-measurement moves.\n*  Make a move that requires measurement and gets an outcome of 'm0'\n*  Make a second set of non-measurement moves based on this outcome.\n\nInto the following new algorithm:\n\n*  Make some non-measurement moves.\n*  Make the exclusion move but don't measure yet.\n*  Make the second set of moves.\n*  Measure the relevant qubits.  Discard results that do not match our expected result of 'm0'\n\nNote that we have to be careful when we do this.  First, we have to track the qubits to perform the correct measurement.  In our example above, the queen moved to the 'b2' square, regardless of whether the king was there.  Executing that move swapped the qubits of 'b2' and 'a3'.  So, when we measure the king's position at the end of the circuit, we need to measure its new position within the 'a3' qubit.\n\nSecond, we need to ensure that the two outcomes are truly independent.  If further moves begin interacting with our 'a3' square that holds the position of the king, then we may get incorrect results.  To do this correctly, we may want to swap the king's state into an ancillary qubit so that it doesn't interact with further moves.  This is left as an exercise to the reader.\n\nThe following code shows how we might do this for the example circuit:\n\n\n```\n# Perform all the moves, including the exclusion move.\n# Afterwards, measure all qubits.\nafter_exclusion_move = (\n    cirq.Circuit(\n        place_piece(a1),\n        place_piece(a3),\n        split_move(a1, b1, b2),\n        split_move(b1, c1, c2),\n        normal_move(a3, b2),\n    )\n    + measure_all_squares\n)\n\n# Define a function to post select on the result.\ndef histogram_post_select(results, square_idx, value):\n    \"\"\"Return a histogram of measurement results with post-selection.\n\n    This will return a dictionary of str to int, with the key being\n    the name of the square and the value being the number of times the\n    square was measured as one. These results will exclude any results\n    where the square represented by `square_idx` were not equal to `value`.\n\n    Args:\n        results: TrialResults returned by a sampler.\n        square_idx: integer index of the measured qubit to post-select on.\n        value: whether the qubit post-selected should be one or zero.\n    \"\"\"\n    sampling_frequency = {}\n    all_results = results.measurements[\"all\"]\n    post_selected_results = all_results[all_results[:, square_idx] == value]\n    for idx, sq in enumerate(all_squares):\n        sampling_frequency[str(sq)] = post_selected_results[:, idx].sum()\n    return sampling_frequency\n\n\n# Compute statistics for the pieces.\nafter_results = this_sim.run(after_exclusion_move, repetitions=1000)\n\n# Find the index of 'a3' (it should be at index 2)\npost_select_idx = all_squares.index(cirq.NamedQubit(\"a3\"))\n\n# Print out the post-selected histogram\nprint(histogram_post_select(after_results, post_select_idx, 0))\n```\n\n    {'a1': 0, 'a2': 0, 'a3': 0, 'b1': 0, 'b2': 516, 'b3': 0, 'c1': 227, 'c2': 289, 'c3': 0}\n\n\nWe now have about half the number of results, but they only include results with the relevant measurement outcomes.  We now have replicated the correct state of the board after the exclusion board.  \n\nTo show that we can use this state to continue the quantum chess game, let's make a final move from the king from c2 to c3.  This represents the board state with king on 'a1', queen on 'a3' after the moves \n*Ka1^b1b2, Kb1^c1c2, Qa3b2.m1, Kc2c3*:\n\n\n\n```\nafter_exclusion_without_measurement = cirq.Circuit(\n    place_piece(a1),\n    place_piece(a3),\n    split_move(a1, b1, b2),\n    split_move(b1, c1, c2),\n    normal_move(a3, b2),\n    normal_move(c2, c3),\n)\nafter_exclusion_move = (\n    after_exclusion_without_measurement + measure_all_squares\n)\n\nafter_results = this_sim.run(after_exclusion_move, repetitions=1000)\npost_select_idx = all_squares.index(cirq.NamedQubit(\"a3\"))\nprint(histogram_post_select(after_results, post_select_idx, 0))\n```\n\n    {'a1': 0, 'a2': 0, 'a3': 0, 'b1': 0, 'b2': 480, 'b3': 0, 'c1': 236, 'c2': 0, 'c3': 244}\n\n\nWe can now see that the measurements that were on 'c2' have now moved to 'c3'.  This illustrates how we can continue a quantum chess move sequence that contains a partial measurement part-way through the sequence, even on a device that only supports final measurement!\n\n## Noise\n\nSo far, we have dealt with a simulator that is completely noiseless.  Even so, we have already seen statistical fluctuations that affect our probabilities.  Real NISQ devices will have a lot of noise that will affect calculations in every way possible.\n\nThere are many components to noise.  Some possible (overlapping) sources of noise include:\n\n*   **T1 Decay / relaxation**:  Qubits in the excited state $\\vert 1\\rangle$ could lose energy and fall into the ground state $\\vert 0\\rangle$.  This is typically qualified by a metric called T1 that specifies the rate of exponential decay (similar to a \"half-life\" of radioactive decay).\n*   **Dephasing error**:  Qubits could be \"spinning\" in relation to each other.  For instance, a qubit in $\\frac{1}{\\sqrt{2}} (\\vert0\\rangle + \\vert 1\\rangle)$ could become $\\frac{1}{\\sqrt{2}} (\\vert0\\rangle + i\\vert 1\\rangle)$.  This is sometimes simplified to a measure called T2 or T2*.  However, since dephasing errors can \"spin\" at many different rates and directions, a full noise spectrum is needed to fully characterize these types of errors.\n*   **Readout/measurement error**: If we accidentally detect a $\\vert 0\\rangle$ as a $\\vert 1\\rangle$ or vice versa when performing a measurement, this is often classified as a readout error. \n*   **Control/Coherent error**: The device can drift out of calibration or can be too difficult to control effectively.  If every time that we do a $\\text{iSWAP}$ gate, we consistently do a $\\text{iSWAP}^{0.98}$, this is a coherent error.\n*   **Cross talk**: Effects that involve specific pairs of (usually nearby) qubits could occur that can create correlations or entanglements.  These effects are often more difficult to model and fix.\n\nLuckily, we don't need an actual hardware device to simulate (some of these) noisy effects.  We can simulate them using cirq's simulator.\n\nLet's run the simulator with the moves Ka1^b1b2, Kb1^c1c2, Kb2^b3c3 that we were examining before, but this time using one of cirq's noise models called a [depolarizing channel](https://en.wikipedia.org/wiki/Quantum_depolarizing_channel) that randomly scrambles a qubit with a set probability.\n\n\n\n```\nimport cirq.contrib.noise_models as ccn\n\nnoise_model = ccn.DepolarizingNoiseModel(depol_prob=0.01)\nnoisy = cirq.DensityMatrixSimulator(noise=noise_model)\n\nking_moves_measured = (\n    cirq.Circuit(\n        place_piece(a1),\n        split_move(a1, b1, b2),\n        split_move(b1, c1, c2),\n        split_move(b2, b3, c3),\n    )\n    + measure_all_squares\n)\n\nprint(histogram_of_squares(noisy.run(king_moves_measured, repetitions=1000)))\n```\n\n    {'a1': 40, 'a2': 41, 'a3': 34, 'b1': 27, 'b2': 32, 'b3': 247, 'c1': 275, 'c2': 262, 'c3': 272}\n\n\nThese results look a lot messier than what we were looking at before.  First, all 9 squares have some probability of the king being there, even though there is no possibility that the king can be there.  That's a problem.\n\nAlso, the results no longer add up to 1000.  Uh oh.  How is that even possible?  Have we made a mistake?\n\nIf noise flips some of the qubits to |1>, we can now measure a state that records the king in two places.  For instance `|100 000 001>` is a state that could be achieved with a single incorrect bit flip and represents the board state with two kings: one on 'a1' and one on 'c3'.  This will give us two entries in the histogram for a single repetition of the circuit, causing the total to exceed 1000.\n\nWe know that there is no way to create pieces in chess, so some of these results are nonsensical.\n\nOne way to do error mitigation is to detect these nonsensical events and remove them.  Let's recode this to use \"post-selection\" to exclude measurements that have more than one king (or that have zero kings), which we know are impossible positions to reach in this situation.\n\n\n```\ndef remove_multi_kings(results):\n    \"\"\"Removes samples from a set of results that do not have one measurement.\n\n    Returns a histogram dictionary as defined above that only has results that\n    have one square with a measurement outcome of one and all other squares have\n    measurement outcomes of zero.  Results that do not fit this pattern are\n    discarded.\n    \"\"\"\n    sampling_frequency = {}\n    all_results = results.measurements[\"all\"]\n    # Select only rows where the row sums to one.\n    post_selected_results = all_results[all_results[:, :].sum(axis=1) == 1]\n    for idx, sq in enumerate(all_squares):\n        sampling_frequency[str(sq)] = post_selected_results[:, idx].sum()\n    return sampling_frequency\n\n\nresults = noisy.run(king_moves_measured, repetitions=1000)\nprint(remove_multi_kings(results))\n```\n\n    {'a1': 4, 'a2': 2, 'a3': 0, 'b1': 2, 'b2': 0, 'b3': 187, 'c1': 163, 'c2': 184, 'c3': 198}\n\n\nThis data is much better!  We have not eliminated all the noise, but, by taking into account the constraints and invariants of the problem we are trying to solve, we have eliminated much of the noise!\n\nNext, let's look at another source of noise.\n\n### Coherent noise\n\nLet's say that our device consistently performs incorrect operations, but that we do not know the exact nature of these errors.  Is there a way to correct for these types of problems?\n\nLet's suppose that, instead of doing an iSWAP, our device does part of an iSWAP, but that amount differs from day to day and we don't know what the percentage of an iswap is going to be.  One day it could be 50% of an iSWAP, and the next day it could be 80% of an iSWAP.  We don't know what that percentage is, but we know that it will stay fairly stable throughout our calculation.\n\nHow would that affect our results?\nLet's define a function called \"lazy_move\" that represents this partial iSWAP.  Then, let's march the king from a1 to a2 to a3 to b3 to c3 using this under-rotated iSWAP and see what happens.\n\n\n```\nimport random\n\n# Define our secret under-rotation parameter once across multiple executions.\ntry:\n    _secret_lazy_value\nexcept:\n    _secret_lazy_value = (random.random() + 2.0) / 4.0\n\n\ndef lazy_move(source, target):\n    return cirq.ISWAP(source, target) ** _secret_lazy_value\n\n\nking_maybe_moves = (\n    cirq.Circuit(\n        place_piece(a1),\n        lazy_move(a1, a2),\n        lazy_move(a2, a3),\n        lazy_move(a3, b3),\n        lazy_move(b3, c3),\n    )\n    + measure_all_squares\n)\n\nprint(histogram_of_squares(sim.run(king_maybe_moves, repetitions=1000)))\n```\n\n    {'a1': 200, 'a2': 169, 'a3': 120, 'b1': 0, 'b2': 0, 'b3': 98, 'c1': 0, 'c2': 0, 'c3': 413}\n\n\nAs we run this circuit, we see that the king leaks across the path it takes and only some of the probability makes it to the final destination.  However, this probability remains roughly the same across multiple invocations. \n\nCan we correct or \"calibrate\" this broken gate so that it is fixed for our use case?\n\nLet's suppose our device supports a rotation angle for our iSWAP gate.  Can we over-rotate the gate on purpose to counter-act the device's error?\n\nLet's try it.\n\n\n```\nover_rotation_amount = 1.46\n\nking_probably_moves = (\n    cirq.Circuit(\n        place_piece(a1),\n        lazy_move(a1, a2) ** over_rotation_amount,\n        lazy_move(a2, a3) ** over_rotation_amount,\n        lazy_move(a3, b3) ** over_rotation_amount,\n        lazy_move(b3, c3) ** over_rotation_amount,\n    )\n    + measure_all_squares\n)\n\nprint(histogram_of_squares(sim.run(king_probably_moves, repetitions=1000)))\n```\n\n    {'a1': 5, 'a2': 2, 'a3': 4, 'b1': 0, 'b2': 0, 'b3': 4, 'c1': 0, 'c2': 0, 'c3': 985}\n\n\nThis looks better, but still not perfect.\n\nIn a real example, you may need to tune the operations slightly automatically\nto correct for coherent error.  This is vastly simplified example of what is being performed when a quantum device is being calibrated.  The device operator is attempting to perfect the physical operations (such as microwave pulses) to match the intended logical operation (such as iSWAP).   Even as a user of a calibrated device, sometimes procedures like this are needed since the operations may not be uniform across the entire processor, and they may drift over time.\n\nLet's write a routine to try to optimize our\nover rotation constant in order to automatically tune out the under-rotation.  In this example, we will do a linear sweep using a parameter value to find the best value.  In a real example, you may want to use an gradient optimizer such as scipy.\n\n\n\n```\nimport sympy\n\n# Our calibration will be to perform one swap\n# We will then measure how many times the king actually gets there.\nking_calibration = cirq.Circuit(\n    place_piece(a1),\n    lazy_move(a1, a2) ** sympy.Symbol(\"r\"),\n    cirq.measure(a1, a2, key=\"all\"),\n)\n\n# We will try all rotation values from 1.0 to 3.0 at intervals of 0.01\nrotation_parameter = cirq.Linspace(\"r\", 1.0, 3.0, 200)\nresults = sim.run_sweep(\n    king_calibration, params=rotation_parameter, repetitions=1000\n)\n\n# Then we will keep track of the best value we found so far.\nbest_over_rotation = 1.0\nmost_correct_swaps = 0\nfor result in results:\n    num_correct_swaps = result.measurements[\"all\"][:, 1].sum()\n    if num_correct_swaps > most_correct_swaps:\n        most_correct_swaps = num_correct_swaps\n        best_over_rotation = result.params[\"r\"]\n\nprint(f\"Best over rotation value found: {best_over_rotation}\")\nprint(f\"Implied secret swap value: {1/best_over_rotation}\")\nprint(f\"Actual secret swap value: {_secret_lazy_value}\")\n```\n\n    Best over rotation value found: 1.391959798994975\n    Implied secret swap value: 0.7184115523465703\n    Actual secret swap value: 0.7058894035710013\n\n\nOur calibration found a rotation value that corrects for the under-rotation.\n\n**Exercise to the reader**: Is there a way to get closer to the correct result?  Hint: it may cause the simulation to take longer to run.\n\nThere are many other types of noise, but it is inevitable that you will need to think about noise as you develop your own applications and mitigate the error to the largest extent possible if you want your application to be successful.\n\n## Decomposition\n\nMost devices in the NISQ era will only support certain gate types, often referred to as a gate set.\n\nLet's suppose that our device only supports one two-qubit gate, the $\\sqrt{\\text{iSWAP}}$ gate `cirq.ISWAP ** 0.5`.\n\nHow does that affect our quantum chess circuits?\n\nLuckily, most of the moves use either $\\sqrt{\\text{iSWAP}}$ gates or $\\text{iSWAP}$ gates (which are merely two $\\sqrt{\\text{iSWAP}}$ gates in a row).\n\nHowever, the slide move (which we have ignored so far), is a $\\text{controlled-iSWAP}$ gate.  How will we perform this on hardware?\n\nWe will need to transform it into gates we understand.  This is often called \"decomposing\" the gate.\n\nFirst, let's explore some of cirq's capability in this area.  Cirq has some decomposition routines for known gates.  Let's see what happens when we decompose the Hadamard $\\text{H}$ gate and the two-qubit $\\text{CNOT}$ gate.\n\n\n\n```\nprint(\"Decomposing H gate\")\ndecomposed_h = cirq.decompose_once(cirq.H(a1))\nprint(decomposed_h)\nprint(cirq.Circuit(decomposed_h))\nprint()\n\nprint(\"Decomposing CNOT gate\")\ndecomposed_cnot = cirq.decompose_once(cirq.CNOT(a1, a2))\nprint(decomposed_cnot)\nprint(cirq.Circuit(decomposed_cnot))\nprint()\n```\n\n    Decomposing H gate\n    [(cirq.Y**0.5).on(cirq.NamedQubit('a1')), cirq.XPowGate(exponent=1.0, global_shift=-0.25).on(cirq.NamedQubit('a1'))]\n    a1: \u2500\u2500\u2500Y^0.5\u2500\u2500\u2500X\u2500\u2500\u2500\n    \n    Decomposing CNOT gate\n    [(cirq.Y**-0.5).on(cirq.NamedQubit('a2')), cirq.CZ(cirq.NamedQubit('a1'), cirq.NamedQubit('a2')), (cirq.Y**0.5).on(cirq.NamedQubit('a2'))]\n    a1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                    \u2502\n    a2: \u2500\u2500\u2500Y^-0.5\u2500\u2500\u2500@\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500\n    \n\n\ncirq decomposes an H into a Y rotation and then a X rotation.  It decomposes a $\\text{CNOT}$ into a $\\text{CZ}$ gate with some single-qubit gates.  Neat, but it doesn't help us get closer to our goal of decomposing to a $\\sqrt{\\text{iSWAP}}$.\n\nLet's see what happens when we decompose the $\\text{controlled-iSWAP}$ gate.\n\n\n```\ncirq.decompose_once(cirq.ISWAP(a1, a3).controlled_by(a2))\n```\n\n\n\n\n    [cirq.CNOT(cirq.NamedQubit('a1'), cirq.NamedQubit('a3')).controlled_by(cirq.NamedQubit('a2')),\n     cirq.H(cirq.NamedQubit('a1')).controlled_by(cirq.NamedQubit('a2')),\n     cirq.CNOT(cirq.NamedQubit('a3'), cirq.NamedQubit('a1')).controlled_by(cirq.NamedQubit('a2')),\n     cirq.S(cirq.NamedQubit('a1')).controlled_by(cirq.NamedQubit('a2')),\n     cirq.CNOT(cirq.NamedQubit('a3'), cirq.NamedQubit('a1')).controlled_by(cirq.NamedQubit('a2')),\n     (cirq.S**-1).on(cirq.NamedQubit('a1')).controlled_by(cirq.NamedQubit('a2')),\n     cirq.H(cirq.NamedQubit('a1')).controlled_by(cirq.NamedQubit('a2')),\n     cirq.CNOT(cirq.NamedQubit('a1'), cirq.NamedQubit('a3')).controlled_by(cirq.NamedQubit('a2'))]\n\n\n\nOh, yikes.  cirq is able to handle decomposing this, but it uses the decomposition of iSWAP with the control bit attached to all gates.  The result is an expansion into several three qubit gates and two qubit gates.  While correct, this looks to be going the wrong direction in terms of circuit complexity.\n\nWe will need a more powerful tool.  Let's use the concept of an optimizer.  This is a cirq tool that can run through a circuit, making changes as it goes along.  It can be used for compiling to a specific gate set, compressing circuits into less space, or other useful transformations.\n\nLuckily, one already exists for compiling to $\\sqrt{\\text{iSWAP}}$.  `cirq.google.optimized_for_sycamore`.  Let's first demonstrate this with the CNOT gate:\n\n\n\n```\nprint(cirq.google.optimized_for_sycamore(cirq.Circuit(cirq.CNOT(a1, a2))))\n```\n\n    a1: \u2500\u2500\u2500PhXZ(a=-0.5,x=0.5,z=0.5)\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=-1,x=1,z=0)\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=0,x=0.5,z=0)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                      \u2502                                 \u2502\n    a2: \u2500\u2500\u2500PhXZ(a=-1,x=0,z=0.5)\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^-0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500PhXZ(a=0.5,x=0.5,z=-0.5)\u2500\u2500\u2500\n\n\nNow we can see that, instead of decomposing into a CZ gate, it decomposes the CNOT into $\\sqrt{\\text{iSWAP}}$ gates in addition to some one-qubit phased XZ gates.\n\nLet's try it with the more complicated case of a **controlled-iSWAP**:\n\n\n```\nc_iswap = cirq.Circuit(cirq.ISWAP(a1, a3).controlled_by(a2))\ntry:\n    cirq.google.optimized_for_sycamore(c_iswap, optimizer_type=\"sqrt_iswap\")\nexcept Exception as e:\n    print(\"An error occurred while attempting to optimize: \")\n    print(e)\n```\n\n    An error occurred while attempting to optimize: \n    Don't know how to work with CY**-0.5(a2, a3). It isn't a native sqrt ISWAP operation, a 1 or 2 qubit gate with a known unitary, or composite.\n\n\nYuck.  It looks like it gets stuck.  We will need to help it out a bit to get it into a form that it can understand.\n\nOne common transformation that might help is that a controlled-SWAP (often called a Fredkin gate) does have a known transformation into a Toffoli (another three qubit gate that is a controlled-CNOT) and two CNOT gates.  Let's double-check that.\n\n\n```\nimport numpy as np\n\nc_swap = cirq.Circuit(cirq.SWAP(a1, a3).controlled_by(a2))\nc_swap_decomposed = cirq.Circuit(\n    cirq.CNOT(a1, a3), cirq.TOFFOLI(a2, a3, a1), cirq.CNOT(a1, a3)\n)\nc_swap_unitary = cirq.unitary(c_swap)\nc_swap_decomposed_unitary = cirq.unitary(c_swap_decomposed)\n\nprint(\"Unitary of controlled SWAP\")\nprint(c_swap_unitary)\nprint(\"Unitary of decomposed circuit\")\nprint(c_swap_decomposed_unitary)\nprint(\"Are they equal?\")\nprint(np.isclose(c_swap_unitary, c_swap_decomposed_unitary).all())\n```\n\n    Unitary of controlled SWAP\n    [[1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j]]\n    Unitary of decomposed circuit\n    [[1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j]]\n    Are they equal?\n    True\n\n\nWith some leaps of intuition or mathematics, one might try to add an operation to the circuit to rotate the swap slightly to get an **iSWAP**.\n\nLet's add a CZ ** 0.5 gate in the middle to try to change this from a **SWAP** to an **iSWAP**.\n\n\n\n```\nimport numpy as np\n\nc_iswap = cirq.Circuit(cirq.ISWAP(a3, a2).controlled_by(a1))\nc_iswap_decomposed = cirq.Circuit(\n    cirq.CNOT(a3, a2),\n    cirq.TOFFOLI(a1, a2, a3),\n    cirq.CZ(a1, a2) ** 0.5,\n    cirq.CNOT(a3, a2),\n)\nc_iswap_unitary = cirq.unitary(c_iswap)\nc_iswap_decomposed_unitary = cirq.unitary(c_iswap_decomposed)\n\nprint(\"Unitary of controlled iSWAP\")\nprint(c_iswap_unitary)\nprint(\"Unitary of decomposed circuit\")\nprint(c_iswap_decomposed_unitary)\nprint(\"Are they equal?\")\nprint(np.isclose(c_iswap_unitary, c_iswap_decomposed_unitary).all())\n```\n\n    Unitary of controlled iSWAP\n    [[1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+1.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+1.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j]]\n    Unitary of decomposed circuit\n    [[1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+1.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+1.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j]]\n    Are they equal?\n    True\n\n\nThis is great.  Let's see if we can decompose this circuit using the built-in operations from cirq.\n\n\n```\ndecomposed_circuit = cirq.google.optimized_for_sycamore(\n    c_iswap_decomposed, optimizer_type=\"sqrt_iswap\"\n)\nprint(f\"Circuit: {len(decomposed_circuit)} moments\")\nprint(decomposed_circuit)\n```\n\n    Circuit: 45 moments\n    a1: \u2500\u2500\u2500PhXZ(a=-0.75,x=0.5,z=0.75)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=-1,x=1,z=0)\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=-0.5,x=0.5,z=-1)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=-1,x=1,z=0)\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=-0.5,x=0.5,z=-1)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=-1,x=1,z=0)\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=-0.5,x=0.5,z=-1)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=-1,x=1,z=0)\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=-0.0991,x=0.595,z=0.364)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=-1,x=0.364,z=0)\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=0,x=0.136,z=0)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                                                                                                  \u2502                                 \u2502                                                                                                                    \u2502                                 \u2502                                                                                                               \u2502                                 \u2502                                                                                                               \u2502                                 \u2502                                                                                                                    \u2502                                     \u2502\n    a2: \u2500\u2500\u2500PhXZ(a=-1,x=0,z=0.5)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=0.5,x=0.5,z=0.25)\u2500\u2500\u2500\u2500iSwap^-0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500PhXZ(a=0,x=0.5,z=0.5)\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=-1,x=1,z=0)\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=-1.11e-16,x=0.5,z=0.25)\u2500\u2500\u2500iSwap^-0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500PhXZ(a=0,x=0.5,z=0.5)\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=-1,x=1,z=0)\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=0,x=0.5,z=0.5)\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^-0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500PhXZ(a=0,x=0.5,z=0.5)\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=-1,x=1,z=0)\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=0,x=0.5,z=0.5)\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^-0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500PhXZ(a=0,x=0.5,z=0.5)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=-1,x=1,z=0)\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=0.5,x=0.25,z=0)\u2500\u2500\u2500iSwap^-0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500PhXZ(a=0,x=0.5,z=0.5)\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500PhXZ(a=0.5,x=0.5,z=-0.5)\u2500\u2500\u2500\n                                        \u2502                                 \u2502                                                                                                               \u2502                                 \u2502                                                                                                                    \u2502                                 \u2502                                                                                                               \u2502                                 \u2502                                                                                                                       \u2502                                 \u2502                                                                                                              \u2502                                 \u2502\n    a3: \u2500\u2500\u2500PhXZ(a=-0.5,x=0.5,z=0.5)\u2500\u2500\u2500\u2500\u2500iSwap^-0.5\u2500\u2500\u2500PhXZ(a=-1,x=1,z=0)\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500PhXZ(a=-0.5,x=0.5,z=0.25)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^-0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500PhXZ(a=0.5,x=0.5,z=0.25)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^-0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500PhXZ(a=0.5,x=0.5,z=-0.25)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^-0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500PhXZ(a=0.5,x=0.5,z=-0.25)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^-0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500PhXZ(a=0.5,x=0.5,z=-1)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^-0.5\u2500\u2500\u2500PhXZ(a=-1,x=1,z=0)\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500PhXZ(a=0,x=0.5,z=0)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\nSo, a bit of good news and a bit of bad news.  We are able to create a circuit that can run on hardware that only supports $\\sqrt{\\text{iSWAP}}$ and single-qubit gates, but the circuit is extremely long (45 moments).\n\nMore advanced techniques and intuition can lead to better decompositions, but that is out-of-scope of this tutorial.  We'll leave that as a (quite advanced) exercise for the reader.\n\n## Qubit layout\n\nSo far, we have been dealing with NamedQubits, since they match very logically to the squares of the quantum chess board.  However, this is not how real devices work.  We will need to map these abstract qubits to real qubits on a device.  Let's consider a Google Sycamore device with 54 qubits arranged in a grid layout:\n\n\n```\nprint(cirq.google.Sycamore)\n```\n\n                                                 (0, 5)\u2500\u2500\u2500(0, 6)\n                                                 \u2502        \u2502\n                                                 \u2502        \u2502\n                                        (1, 4)\u2500\u2500\u2500(1, 5)\u2500\u2500\u2500(1, 6)\u2500\u2500\u2500(1, 7)\n                                        \u2502        \u2502        \u2502        \u2502\n                                        \u2502        \u2502        \u2502        \u2502\n                               (2, 3)\u2500\u2500\u2500(2, 4)\u2500\u2500\u2500(2, 5)\u2500\u2500\u2500(2, 6)\u2500\u2500\u2500(2, 7)\u2500\u2500\u2500(2, 8)\n                               \u2502        \u2502        \u2502        \u2502        \u2502        \u2502\n                               \u2502        \u2502        \u2502        \u2502        \u2502        \u2502\n                      (3, 2)\u2500\u2500\u2500(3, 3)\u2500\u2500\u2500(3, 4)\u2500\u2500\u2500(3, 5)\u2500\u2500\u2500(3, 6)\u2500\u2500\u2500(3, 7)\u2500\u2500\u2500(3, 8)\u2500\u2500\u2500(3, 9)\n                      \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502\n                      \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502\n             (4, 1)\u2500\u2500\u2500(4, 2)\u2500\u2500\u2500(4, 3)\u2500\u2500\u2500(4, 4)\u2500\u2500\u2500(4, 5)\u2500\u2500\u2500(4, 6)\u2500\u2500\u2500(4, 7)\u2500\u2500\u2500(4, 8)\u2500\u2500\u2500(4, 9)\n             \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502\n             \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502\n    (5, 0)\u2500\u2500\u2500(5, 1)\u2500\u2500\u2500(5, 2)\u2500\u2500\u2500(5, 3)\u2500\u2500\u2500(5, 4)\u2500\u2500\u2500(5, 5)\u2500\u2500\u2500(5, 6)\u2500\u2500\u2500(5, 7)\u2500\u2500\u2500(5, 8)\n             \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502\n             \u2502        \u2502        \u2502        \u2502        \u2502        \u2502        \u2502\n             (6, 1)\u2500\u2500\u2500(6, 2)\u2500\u2500\u2500(6, 3)\u2500\u2500\u2500(6, 4)\u2500\u2500\u2500(6, 5)\u2500\u2500\u2500(6, 6)\u2500\u2500\u2500(6, 7)\n                      \u2502        \u2502        \u2502        \u2502        \u2502\n                      \u2502        \u2502        \u2502        \u2502        \u2502\n                      (7, 2)\u2500\u2500\u2500(7, 3)\u2500\u2500\u2500(7, 4)\u2500\u2500\u2500(7, 5)\u2500\u2500\u2500(7, 6)\n                               \u2502        \u2502        \u2502\n                               \u2502        \u2502        \u2502\n                               (8, 3)\u2500\u2500\u2500(8, 4)\u2500\u2500\u2500(8, 5)\n                                        \u2502\n                                        \u2502\n                                        (9, 4)\n\n\nWe will need to map our algorithm onto real qubits.  Let's examine the circuit for our exclusion queen move sequence again and look at the constraints.\n\n\n\n```\nprint(after_exclusion_without_measurement)\n```\n\n                           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    a1: \u2500\u2500\u2500X\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n               \u2502            \u2502\n    a3: \u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n               \u2502            \u2502                       \u2502\n    b1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                            \u2502    \u2502             \u2502    \u2502\n    b2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                 \u2502             \u2502\n    c1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                               \u2502\n    c2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\n                                                             \u2502\n    c3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\n                           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\n\nFirst, one note is that this circuit uses iSWAP gates.  However, the sycamore device actually only supports $\\sqrt{\\text{iSWAP}}$ gates.  Luckily, an iSWAP is just two $\\sqrt{\\text{iSWAP}}$ gates in a row.  We will use cirq's concept of an optimizer in order to accomplish this.\n\n\n```\nclass IswapDecomposer(cirq.PointOptimizer):\n    \"\"\"Optimizer that decomposes iSWAPs into iSWAP ** 0.5 operations.\"\"\"\n\n    def optimization_at(\n        self, circuit: cirq.Circuit, index: int, op: cirq.Operation\n    ) -> Optional[cirq.PointOptimizationSummary]:\n        if op.gate == cirq.ISWAP:\n            # If this operation is an iSWAP, transform\n            new_ops = [\n                cirq.ISWAP(*op.qubits) ** 0.5,\n                cirq.ISWAP(*op.qubits) ** 0.5,\n            ]\n\n            # Clear_span = 1 signifies that only this op should be replaced.\n            # clear_qubits replaces only operations with these qubits.\n            # new_operations\n            return cirq.PointOptimizationSummary(\n                clear_span=1, clear_qubits=op.qubits, new_operations=new_ops\n            )\n        #  Exercise to the reader:\n        #  Can you add an additional condition to this function to replace\n\n\n        #  controlled-iSWAP operations with the decomposition we found above?\n\nexclusion_with_sqrt_iswaps = after_exclusion_without_measurement.copy()\nIswapDecomposer().optimize_circuit(exclusion_with_sqrt_iswaps)\nprint(exclusion_with_sqrt_iswaps)\n```\n\n                           \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510               \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    a1: \u2500\u2500\u2500X\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n               \u2502                     \u2502            \u2502\n    a3: \u2500\u2500\u2500X\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n               \u2502                     \u2502            \u2502                     \u2502                      \u2502\n    b1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                            \u2502        \u2502            \u2502            \u2502        \u2502             \u2502        \u2502\n    b2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                            \u2502                                  \u2502                      \u2502\n    c1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                                               \u2502                      \u2502\n    c2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                                                                                            \u2502           \u2502\n    c3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\n                           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518               \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\n\nWe now have the circuit with only gates that are supported by the hardware.  Let's now focus our attention on mapping our logical qubits onto the Grid.\n\nBy visualising the circuit in a diagram, it becomes obvious that there are several adjacency requirements, if we can only perform two-qubit operations that are next to each other:\n\n*   a1 and b1\n*   a1 and b2\n*   b1 and c1\n*   b1 and c2\n*   b2 and a3\n*   c2 and c3\n\nWe can condense this somewhat into two chains, with only b1 in common:\n\n*   a3 - b2 - a1 - b1 - c2 - c3\n*   b1 - c1\n\nThere are many ways to lay this out on a grid, but let's pick a central qubit (3,5) for b1 and lay out the qubits in a pattern that goes outward in three\ndirections from there.\n\n*   a3 (6,5) - b2 (5,5) - a1 (4,5) - b1 (3,5) - c2 (2,5) - c3 (1,5)\n*   b1 (3,5) => c1 (3,6)\n\nGreat.  Note that, for smaller devices or larger circuits, this may be a more complicated bending path.  \n\n**Exercise to the reader:**  What do we do if we cannot force the circuit into a grid?  (Hint: can you make use of a SWAP gate?)\n\nLet's put together a simple dictionary and translate this to a circuit that can run on grid qubits.  Note that we will need to do one other task as well: **iSWAP** is not a native operation to Sycamore, so we will need to change it into 2\n`ISWAP ** 0.5` gates.  We will use the concept of a  `Device`.  This is a cirq construct that can verify that our operations are valid for the device.  \n\n(For instance, try to change one of the qubits below to a qubit not on the device or not adjacent to its required neighbors).\n\n\n\n```\nqubit_translation = {\n    cirq.NamedQubit(\"a3\"): cirq.GridQubit(6, 5),\n    cirq.NamedQubit(\"b2\"): cirq.GridQubit(5, 5),\n    cirq.NamedQubit(\"a1\"): cirq.GridQubit(4, 5),\n    cirq.NamedQubit(\"b1\"): cirq.GridQubit(3, 5),\n    cirq.NamedQubit(\"c2\"): cirq.GridQubit(2, 5),\n    cirq.NamedQubit(\"c3\"): cirq.GridQubit(1, 5),\n    cirq.NamedQubit(\"c1\"): cirq.GridQubit(3, 6),\n    # Not used except for measurement\n    cirq.NamedQubit(\"a2\"): cirq.GridQubit(2, 4),\n    cirq.NamedQubit(\"b3\"): cirq.GridQubit(3, 4),\n}\n\n\ndef qubit_transformer(namedQubit: cirq.Qid) -> cirq.Qid:\n    \"\"\"Transform a namedQubit into a GridQubit using the mapping.\"\"\"\n    return qubit_translation[namedQubit]\n\n\n# First, modify the circuit so that ISWAP's become two ISWAP ** 0.5\nexclusion_move_sycamore = exclusion_with_sqrt_iswaps.with_device(\n    new_device=cirq.google.Sycamore, qubit_mapping=qubit_transformer\n)\nprint(exclusion_move_sycamore)\n```\n\n    (1, 5): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                                                               \u2502           \u2502\n    (2, 5): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\n                                                       \u2502           \u2502\n    (3, 5): \u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502           \u2502\n    (3, 6): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502\n    (4, 5): \u2500\u2500\u2500X\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                               \u2502           \u2502\n    (5, 5): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                                       \u2502           \u2502\n    (6, 5): \u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\nThis new diagram shows how we can map the logical qubits representing 'squares' into a circuit with physical grid qubits that only uses adjacent qubits.  This circuit could then be run on a hardware device!\n\n**Exercise to the reader:**  Can you write the code to execute this circuit (in the simulator) and do the reverse translation back to logical named qubits to interpret the results as chess positions?\n\n### Dynamic Qubit Mapping\n\nThe first time, we mapped the qubits from `NamedQubit`s to `GridQubit`s by hand.  Can we map qubits automatically without this hand-tuned mapping?\n\nWe will use a depth-first search to try to automatically map the qubits.  The following code snippet is a bit longer, but it will attempt to map a qubit, followed by mapping the qubits it is connected to.  \n\nFor example, we will first map the square 'b1' to `GridQubit` (3, 5).  We then see that 'a1', 'c1', and 'c2' need to be adjacent to 'b1', so we then map them (and their adjacent squares, etc) next.  We repeat this until we finish mapping or until we get ourselves into an impossible situation.\n\n\n```\ndef map_helper(\n    cur_node: cirq.Qid,\n    mapping: Dict[cirq.Qid, cirq.GridQubit],\n    available_qubits: Set[cirq.GridQubit],\n    graph: Dict[cirq.Qid, Iterable[cirq.Qid]],\n) -> bool:\n    \"\"\"Helper function to construct mapping.\n    Traverses a graph and performs recursive depth-first\n    search to construct a mapping one node at a time.\n    On failure, raises an error and back-tracks until a\n    suitable mapping can be found.  Assumes all qubits in\n    the graph are connected.\n\n    Args:\n        cur_node: node to examine.\n        mapping: current mapping of named qubits to `GridQubits`\n        available_qubits: current set of unassigned qubits\n        graph: adjacency graph of connections between qubits,\n            representing by a dictionary from qubit to adjacent qubits\n    Returns:\n        True if it was possible to map the qubits, False if not.\n    \"\"\"\n    # cur_node is the named qubit\n    # cur_qubit is the currently assigned GridQubit\n    cur_qubit = mapping[cur_node]\n\n    # Determine the list of adjacent nodes that still need to be mapped\n    nodes_to_map = []\n    for node in graph[cur_node]:\n        if node not in mapping:\n            # Unmapped node.\n            nodes_to_map.append(node)\n        else:\n            # Mapped adjacent node.\n            # Verify that the previous mapping is adjacent in the Grid.\n            if not mapping[node].is_adjacent(cur_qubit):\n                # Nodes previously mapped are not adjacent\n                # This is an invalid mapping\n                return False\n    if not nodes_to_map:\n        # All done with this node.\n        return True\n\n    # Find qubits that are adjacent in the grid\n    valid_adjacent_qubits = []\n    for a in [(0, 1), (0, -1), (1, 0), (-1, 0)]:\n        q = cur_qubit + a\n        if q in available_qubits:\n            valid_adjacent_qubits.append(q)\n\n    # Not enough adjacent qubits to map all qubits\n    if len(valid_adjacent_qubits) < len(nodes_to_map):\n        return False\n\n    # Only map one qubit at a time\n    # This makes back-tracking easier.\n    node_to_map = nodes_to_map[0]\n\n    for node_to_try in valid_adjacent_qubits:\n        # Add proposed qubit to the mapping\n        # and remove it from available qubits\n        mapping[node_to_map] = node_to_try\n        available_qubits.remove(node_to_try)\n\n        # Recurse\n        # Move on to the qubit we just mapped.\n        # Then, come back to this node and\n        # map the rest of the adjacent nodes\n        if not map_helper(node_to_map, mapping, available_qubits, graph):\n            del mapping[node_to_map]\n            available_qubits.add(node_to_try)\n            continue\n\n        if not map_helper(cur_node, mapping, available_qubits, graph):\n            del mapping[node_to_map]\n            available_qubits.add(node_to_try)\n            continue\n        # We have succeeded in mapping the qubits!\n        return True\n    # All available qubits were not valid.\n    # Fail upwards and back-track if possible.\n    return False\n\n\ndef qubit_mapping(\n    circuit: cirq.Circuit,\n    device: cirq.Device,\n    start_qubit: cirq.Qid,\n    mapped_qubit: cirq.Qid,\n) -> Dict[cirq.Qid, cirq.GridQubit]:\n    \"\"\"Create a mapping from NamedQubits to Grid Qubits\n    This function analyzes the circuit to determine which\n    qubits need to be adjacent, then maps to the grid of the device\n    based on the generated mapping.\n    \"\"\"\n    # Build up an adjacency graph based on the circuits.\n    # Two qubit gates will turn into edges in the graph\n    g = {}\n    for m in circuit:\n        for op in m:\n            if len(op.qubits) == 2:\n                q1, q2 = op.qubits\n                if q1 not in g:\n                    g[q1] = []\n                if q2 not in g:\n                    g[q2] = []\n                if q2 not in g[q1]:\n                    g[q1].append(q2)\n                if q1 not in g[q2]:\n                    g[q2].append(q1)\n    for q in g:\n        if len(g[q]) > 4:\n            raise ValueError(f\"Qubit {q} needs more than 4 adjacent qubits!\")\n\n    # Initialize mappings and available qubits\n    start_list = set(device.qubits)\n    start_list.remove(mapped_qubit)\n\n    mapping = {}\n    mapping[start_qubit] = mapped_qubit\n\n    map_helper(start_qubit, mapping, start_list, g)\n\n    if len(mapping) != len(g):\n        print(\"Warning: could not map all qubits!\")\n\n    return mapping\n\n\ndynamic_mapping = qubit_mapping(\n    exclusion_with_sqrt_iswaps,\n    cirq.google.Sycamore,\n    cirq.NamedQubit(\"b1\"),\n    cirq.GridQubit(3, 5),\n)\nfor q in dynamic_mapping:\n    print(f\"Qubit {q} maps to {dynamic_mapping[q]}\")\ndynamically_mapped_circuit = exclusion_with_sqrt_iswaps.with_device(\n    new_device=cirq.google.Sycamore, qubit_mapping=lambda q: dynamic_mapping[q]\n)\nprint(dynamically_mapped_circuit)\n```\n\n    Qubit b1 maps to (3, 5)\n    Qubit a1 maps to (3, 6)\n    Qubit b2 maps to (3, 7)\n    Qubit a3 maps to (3, 8)\n    Qubit c1 maps to (3, 4)\n    Qubit c2 maps to (4, 5)\n    Qubit c3 maps to (4, 6)\n                                                       \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510   \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    (3, 4): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                               \u2502\n    (3, 5): \u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                   \u2502                                    \u2502                      \u2502\n    (3, 6): \u2500\u2500\u2500X\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                               \u2502           \u2502            \u2502                      \u2502\n    (3, 7): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                                        \u2502        \u2502             \u2502        \u2502\n    (3, 8): \u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                                        \u2502                      \u2502\n    (4, 5): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                                                                                     \u2502           \u2502\n    (4, 6): \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500iSwap^0.5\u2500\u2500\u2500\n                                                       \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518   \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\n\nThis time, we are able to map the qubits dynamically!  Now, if the device changes, or a qubit on the device becomes temporarily unusable, we can quickly adjust the mapping to compensate.\n\n***Exercise:*** Can you use this to map to the `Sycamore23` device instead?  What about onto the `Foxtail` device?\n\n***Exercise:*** Try to map qubits on different device layouts and with different sequences of moves.  Will this algorithm ever fail?  Can you adjust the functions above to correct for those cases?\n\n***Exercise:*** Can you transform the above code to use a breadth-first search instead of a depth-first search instead?\n", "meta": {"hexsha": "21e0067baeac07d4fa28a86d51264d58d0bc628c", "size": 101834, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/quantum_chess/concepts.ipynb", "max_stars_repo_name": "losos0/ReCirq", "max_stars_repo_head_hexsha": "423b95090154d0dd1d2b34f321b5c96c414e1ab7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-24T14:21:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-24T14:21:51.000Z", "max_issues_repo_path": "docs/quantum_chess/concepts.ipynb", "max_issues_repo_name": "losos0/ReCirq", "max_issues_repo_head_hexsha": "423b95090154d0dd1d2b34f321b5c96c414e1ab7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/quantum_chess/concepts.ipynb", "max_forks_repo_name": "losos0/ReCirq", "max_forks_repo_head_hexsha": "423b95090154d0dd1d2b34f321b5c96c414e1ab7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.3083491461, "max_line_length": 862, "alphanum_fraction": 0.5339277648, "converted": true, "num_tokens": 21483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19436781101874467, "lm_q2_score": 0.06560484202633814, "lm_q1q2_score": 0.01275146953688989}}
{"text": "**Update:** made full github repo for blog-as-notebooks, and updated instructions on how to more easily configure everything and use the newest nbconvert for a more streamlined workflow.\n\nSince the notebook was introduced with [IPython 0.12](http://ipython.org/ipython-doc/rel-0.12.1/whatsnew/version0.12.html), it has proved to be very popular, and we are seeing great adoption of the tool and the underlying file format in research and education.  One persistent question we've had since the beginning (even prior to its official release) was whether it would be possible to easily write blog posts using the notebook.  The combination of easy editing in markdown with the notebook's ability to contain code, figures and results, makes it an ideal platform for quick authoring of technical documents, so being able to post to a blog is a natural request.\n\nToday, in answering a query about this from a colleague, I decided to try again the status of our conversion pipeline, and I'm happy to report that with a bit of elbow-grease, at least on Blogger things work pretty well!  \n\nThis post was *entirely* written as a notebook, and in fact I have now created a [github repo](https://github.com/fperez/blog), which means that you can see it directly [rendered in IPyhton's nbviewer app](http://nbviewer.ipython.org/urls/raw.github.com/fperez/blog/master/120907-Blogging with the IPython Notebook.ipynb).\n\nThe purpose of this post is to quickly provide a set of instructions on how I got it to work, and to test things out.  Please note: this requires code that isn't quite ready for prime-time and is still under heavy development, so expect some assembly.\n\n## Converting your notebook to html with nbconvert\n\nThe first thing you will need is our [nbconvert](https://github.com/ipython/nbconvert) tool that converts notebooks across formats.  The README file in the repo contains the requirements for nbconvert (basically [python-markdown](http://pypi.python.org/pypi/Markdown/), [pandoc](http://johnmacfarlane.net/pandoc), [docutils from SVN](http://docutils.svn.sourceforge.net/viewvc/docutils/trunk/docutils/?view=tar) and [pygments](http://pygments.org)).\n\nOnce you have nbconvert installed, you can convert your notebook to Blogger-friendly html with:\n\n    nbconvert -f blogger-html your_notebook.ipynb\n\nThis will leave two files in your computer, one named `your_notebook.html` and one named `your_noteboook_header.html`; it might also create a directory called `your_notebook_files` if needed for ancillary files.  The first file will contain the body of your post and can be pasted wholesale into the Blogger editing area. The second file contains the CSS and Javascript material needed for the notebook to display correctly, you should only need to use this once to configure your blogger setup (see below):\n\n    # Only one notebook so far\n    (master)longs[blog]> ls\n    120907-Blogging with the IPython Notebook.ipynb  fig/  old/\n    \n    # Now run the conversion:\n    (master)longs[blog]> nbconvert.py -f blogger-html 120907-Blogging\\ with\\ the\\ IPython\\ Notebook.ipynb\n    \n    # This creates the header and html body files\n    (master)longs[blog]> ls\n    120907-Blogging with the IPython Notebook_header.html  fig/\n    120907-Blogging with the IPython Notebook.html         old/\n    120907-Blogging with the IPython Notebook.ipynb\n\n## Configuring your Blogger blog to accept notebooks\n\nThe notebook uses a lot of custom CSS for formatting input and output, as well as Javascript from [MathJax](http://www.mathjax.org) to display mathematical notation.  You will need all this CSS and the Javascript calls in your blog's configuration for your notebook-based posts to display correctly:\n\n1. Once authenticated, go to your blog's overview page by clicking on its title.\n2. Click on templates (left column) and customize using the Advanced options.\n3. Scroll down the middle column until you see an \"Add CSS\" option.\n4. Copy entire the contents of the `_header` file into the CSS box.\n\nThat's it, and you shouldn't need to do anything else as long as the CSS we use in the notebooks doesn't drastically change.  This customization of your blog needs to be done only once.\n\nWhile you are at it, I recommend you change the width of your blog so that cells have enough space for clean display; in experimenting I found out that the default template was too narrow to properly display code cells, producing a lot of text wrapping that impaired readability.  I ended up using a layout with a single column for all blog contents, putting the blog archive at the bottom.  Otherwise, if I kept the right sidebar, code cells got too squished in the post area.\n\nI also had problems using some of the fancier templates available from 'Dynamic Views', in that I could never get inline math to render.  But sticking to those from the Simple or 'Picture Window' categories worked fine and they still allow for a lot of customization.\n\n*Note:* if you change blog templates, Blogger does destroy your custom CSS, so you may need to repeat the above steps in that case.\n\n## Adding the actual posts\n\nNow, whenever you want to write a new post as a notebook, simply convert the `.ipynb` file to blogger-html and copy its entire contents to the clipboard. Then go to the 'raw html' view of the post, remove anything Blogger may have put there by default, and paste.  You should also click on the 'options' tab (right hand side) and select both `Show HTML literally` and `Use <br> tag`, else your paragraph breaks will look all wrong.\n\nThat's it!\n\n## What can you put in?\n\nI will now add a few bits of code, plots, math, etc, to show which kinds of content can be put in and work out of the box.  These are mostly bits copied from our [example notebooks](https://github.com/ipython/ipython/tree/master/docs/examples/notebooks) so the actual content doesn't matter, I'm just illustrating the *kind* of content that works.\n\n\n```\n# Let's initialize pylab so we can plot later\n%pylab inline\n```\n\n    \n    Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline].\n    For more information, type 'help(pylab)'.\n\n\nWith pylab loaded, the usual matplotlib operations work\n\n\n```\nx = linspace(0, 2*pi)\nplot(x, sin(x), label=r'$\\sin(x)$')\nplot(x, cos(x), 'ro', label=r'$\\cos(x)$')\ntitle(r'Two familiar functions')\nlegend();\n```\n\nThe notebook, thanks to MathJax, has great LaTeX support, so that you can type inline math $(1,\\gamma,\\ldots, \\infty)$ as well as displayed equations:\n\n$$\ne^{i \\pi}+1=0\n$$\n\nbut by loading the [sympy](http://sympy.org) extension, it's easy showcase math *output* from Python computations, where we don't type the math expressions in text, and instead the results of code execution are displayed in mathematical format:\n\n\n```\n%load_ext sympyprinting\nimport sympy as sym\nfrom sympy import *\nx, y, z = sym.symbols(\"x y z\")\n```\n\nFrom simple algebraic expressions\n\n\n```\nRational(3,2)*pi + exp(I*x) / (x**2 + y)\n```\n\n\n```\neq = ((x+y)**2 * (x+1))\neq\n```\n\n\n```\nexpand(eq)\n```\n\nTo calculus\n\n\n```\ndiff(cos(x**2)**2 / (1+x), x)\n```\n\nFor more examples of how to use sympy in the notebook, you can see [our example sympy notebook](http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/master/docs/examples/notebooks/sympy.ipynb) or go to the [sympy website](http://sympy.org) for much more documentation.\n\n## You can easily include formatted text and code with markdown\n\nYou can *italicize*, **boldface**\n\n* build\n* lists\n\nand embed code meant for illustration instead of execution in Python:\n\n    def f(x):\n        \"\"\"a docstring\"\"\"\n        return x**2\n\nor other languages:\n\n    if (i=0; i<n; i++) {\n      printf(\"hello %d\\n\", i);\n      x += 4;\n    }\n\nAnd since the notebook can store displayed images in the file itself, you can show images which will be embedded in your post:\n\n\n```\nfrom IPython.display import Image\nImage(filename='fig/img_4926.jpg')\n```\n\n\n\n\n    \n\n    \n\n\n\nYou can embed YouTube videos using the IPython object, this is my recent talk at SciPy'12 about IPython:\n\n\n```\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('iwVvqwLDsJo')\n```\n\n\n\n\n\n\n\n\n\n\n## Including code examples from other languages\n\nUsing our various script cell magics, it's easy to include code in a variety of other languages\n\n\n```ruby\n%%ruby\nputs \"Hello from Ruby #{RUBY_VERSION}\"\n```\n\n    Hello from Ruby 1.8.7\n\n\n\n```bash\n%%bash\necho \"hello from $BASH\"\n```\n\n    hello from /bin/bash\n\n\nAnd tools like the Octave and R magics let you interface with entire computational systems directly from the notebook; this is the Octave magic for which [our example notebook contains more details](http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/d835d46dcc50043971b4a9915398bad1b5d63648/docs/examples/notebooks/octavemagic_extension.ipynb):\n\n\n```\n%load_ext octavemagic\n```\n\n\n```octave\n%%octave -s 500,500\n\n# butterworth filter, order 2, cutoff pi/2 radians\nb = [0.292893218813452  0.585786437626905  0.292893218813452];\na = [1  0  0.171572875253810];\nfreqz(b, a, 32);\n```\n\nThe [rmagic extension](http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/3607712653c66d63e0d7f13f073bde8c0f209ba8/docs/examples/notebooks/rmagic_extension.ipynb) does a similar job, letting you call R directly from the notebook, passing variables back and forth between Python and R.\n\n\n```\n%load_ext rmagic \n```\n\nStart by creating some data in Python\n\n\n```\nX = np.array([0,1,2,3,4])\nY = np.array([3,5,4,6,7])\n```\n\nWhich can then be manipulated in R, with results available back in Python (in `XYcoef`):\n\n\n```r\n%%R -i X,Y -o XYcoef\nXYlm = lm(Y~X)\nXYcoef = coef(XYlm)\nprint(summary(XYlm))\npar(mfrow=c(2,2))\nplot(XYlm)\n```\n\n\n```\nXYcoef\n```\n\n\n\n\n    [ 3.2  0.9]\n\n\n\nAnd finally, in the same spirit, the [cython magic extension](http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/3607712653c66d63e0d7f13f073bde8c0f209ba8/docs/examples/notebooks/cython_extension.ipynb) lets you call Cython code directly from the notebook:\n\n\n```\n%load_ext cythonmagic\n```\n\n\n```cython\n%%cython -lm\nfrom libc.math cimport sin\nprint 'sin(1)=', sin(1)\n```\n\n    sin(1)= 0.841470984808\n\n\n## Keep in mind, this is still experimental code!\n\nHopefully this post shows that the system is already useful to communicate technical content in blog form with a minimal amount of effort.  But please note that we're still in heavy development of many of these features, so things are susceptible to changing in the near future.  By all means join the [IPython dev mailing list](http://mail.scipy.org/mailman/listinfo/ipython-dev) if you'd like to participate and help us make IPython a better tool!\n", "meta": {"hexsha": "c1b2eb0cbdc8e8e5aa988d981baf23b68ee30527", "size": 192899, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "120907-Blogging with the IPython Notebook.ipynb", "max_stars_repo_name": "Sethionic/ipython-notebooks", "max_stars_repo_head_hexsha": "e6648579c79e0a264e80af677968d3e231f4daec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-06-10T12:28:46.000Z", "max_stars_repo_stars_event_max_datetime": "2015-06-10T12:28:46.000Z", "max_issues_repo_path": "120907-Blogging with the IPython Notebook.ipynb", "max_issues_repo_name": "Sethionic/ipython-notebooks", "max_issues_repo_head_hexsha": "e6648579c79e0a264e80af677968d3e231f4daec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "120907-Blogging with the IPython Notebook.ipynb", "max_forks_repo_name": "Sethionic/ipython-notebooks", "max_forks_repo_head_hexsha": "e6648579c79e0a264e80af677968d3e231f4daec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 279.969521045, "max_line_length": 54610, "alphanum_fraction": 0.9102691046, "converted": true, "num_tokens": 2711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16026603633858208, "lm_q2_score": 0.07921031921828132, "lm_q1q2_score": 0.012694723898227761}}
{"text": "## Install TensorTrade\n\n\n```python\n!python3 -m pip install -e .. -U\n```\n\n    Obtaining file:///tensortrade\n    Requirement already satisfied, skipping upgrade: numpy>=1.16.4 in /usr/local/lib/python3.6/dist-packages (from tensortrade==0.2.0b1) (1.18.1)\n    Requirement already satisfied, skipping upgrade: pandas>=0.25.0 in /usr/local/lib/python3.6/dist-packages (from tensortrade==0.2.0b1) (1.0.3)\n    Requirement already satisfied, skipping upgrade: gym>=0.14.0 in /usr/local/lib/python3.6/dist-packages (from tensortrade==0.2.0b1) (0.17.1)\n    Requirement already satisfied, skipping upgrade: pyyaml>=5.1.2 in /usr/local/lib/python3.6/dist-packages (from tensortrade==0.2.0b1) (5.3.1)\n    Requirement already satisfied, skipping upgrade: sympy>=1.4 in /usr/local/lib/python3.6/dist-packages (from tensortrade==0.2.0b1) (1.5.1)\n    Requirement already satisfied, skipping upgrade: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.25.0->tensortrade==0.2.0b1) (2019.3)\n    Requirement already satisfied, skipping upgrade: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.25.0->tensortrade==0.2.0b1) (2.8.1)\n    Requirement already satisfied, skipping upgrade: cloudpickle<1.4.0,>=1.2.0 in /usr/local/lib/python3.6/dist-packages (from gym>=0.14.0->tensortrade==0.2.0b1) (1.3.0)\n    Requirement already satisfied, skipping upgrade: pyglet<=1.5.0,>=1.4.0 in /usr/local/lib/python3.6/dist-packages (from gym>=0.14.0->tensortrade==0.2.0b1) (1.5.0)\n    Requirement already satisfied, skipping upgrade: six in /usr/local/lib/python3.6/dist-packages (from gym>=0.14.0->tensortrade==0.2.0b1) (1.13.0)\n    Requirement already satisfied, skipping upgrade: scipy in /usr/local/lib/python3.6/dist-packages (from gym>=0.14.0->tensortrade==0.2.0b1) (1.4.1)\n    Requirement already satisfied, skipping upgrade: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy>=1.4->tensortrade==0.2.0b1) (1.1.0)\n    Requirement already satisfied, skipping upgrade: future in /usr/local/lib/python3.6/dist-packages (from pyglet<=1.5.0,>=1.4.0->gym>=0.14.0->tensortrade==0.2.0b1) (0.18.2)\n    Installing collected packages: tensortrade\n      Attempting uninstall: tensortrade\n        Found existing installation: tensortrade 0.2.0b1\n        Can't uninstall 'tensortrade'. No files were found to uninstall.\n      Running setup.py develop for tensortrade\n    Successfully installed tensortrade\n\n\n\n```python\n# Load the TensorBoard notebook extension\n%load_ext tensorboard\n```\n\n## Setup Data Fetching\n\n\n```python\nimport ssl\nimport pandas as pd\n\nssl._create_default_https_context = ssl._create_unverified_context # Only used if pandas gives a SSLError\n\ndef fetch(exchange_name, symbol, timeframe):\n    url = \"https://www.cryptodatadownload.com/cdd/\"\n    filename = \"{}_{}USD_{}.csv\".format(exchange_name, symbol, timeframe)\n    volume_column = \"Volume {}\".format(symbol)\n    new_volume_column = \"Volume_{}\".format(symbol)\n    \n    df = pd.read_csv(url + filename, skiprows=1)\n    df = df[::-1]\n    df = df.drop([\"Symbol\"], axis=1)\n    df = df.rename({\"Volume USD\": \"volume\", volume_column: new_volume_column}, axis=1)\n    df = df.set_index(\"Date\")\n    df.columns = [symbol + \":\" + name.lower() for name in df.columns]\n                     \n    return df\n```\n\n## Setup Trading Environment\n\n\n```python\nfrom tensortrade.exchanges import Exchange\nfrom tensortrade.exchanges.services.execution.simulated import execute_order\nfrom tensortrade.data import Stream, DataFeed, Module\nfrom tensortrade.instruments import USD, BTC, ETH, LTC\nfrom tensortrade.wallets import Wallet, Portfolio\nfrom tensortrade.environments import TradingEnvironment\n\ncoinbase_data = pd.concat([\n    fetch(\"Coinbase\", \"BTC\", \"1h\"),\n    fetch(\"Coinbase\", \"ETH\", \"1h\")\n], axis=1)\n\ncoinbase = Exchange(\"coinbase\", service=execute_order)(\n    Stream(\"USD-BTC\", list(coinbase_data['BTC:close'])),\n    Stream(\"USD-ETH\", list(coinbase_data['ETH:close']))\n)\n\ncoinbase_btc = coinbase_data.loc[:, [name.startswith(\"BTC\") for name in coinbase_data.columns]]\n\nwith Module(\"coinbase\") as coinbase_ns:\n    nodes = [Stream(name, list(coinbase_data[name])) for name in coinbase_data.columns]\n\nfeed = DataFeed([coinbase_ns])\n\nportfolio = Portfolio(USD, [\n    Wallet(coinbase, 10000 * USD),\n    Wallet(coinbase, 10 * BTC),\n    Wallet(coinbase, 5 * ETH),\n])\n\nenv = TradingEnvironment(\n    feed=feed,\n    portfolio=portfolio,\n    action_scheme='managed-risk',\n    reward_scheme='risk-adjusted',\n    window_size=20,\n    disable_tensorflow_logger=False\n)\n```\n\n    /usr/local/lib/python3.6/dist-packages/gym/logger.py:30: UserWarning:\n    \n    \u001b[33mWARN: Box bound precision lowered by casting to float32\u001b[0m\n    \n\n\n## Example Data Feed Observation\n\n\n```python\nenv.feed.next()\n```\n\n\n\n\n    {'coinbase:/BTC:open': 2505.56,\n     'coinbase:/BTC:high': 2513.38,\n     'coinbase:/BTC:low': 2495.12,\n     'coinbase:/BTC:close': 2509.17,\n     'coinbase:/BTC:volume_btc': 114.6,\n     'coinbase:/BTC:volume': 287000.32,\n     'coinbase:/ETH:open': 279.98,\n     'coinbase:/ETH:high': 279.99,\n     'coinbase:/ETH:low': 272.1,\n     'coinbase:/ETH:close': 275.01,\n     'coinbase:/ETH:volume_eth': 2455.28,\n     'coinbase:/ETH:volume': 679358.87,\n     'coinbase:/USD-BTC': 2509.17,\n     'coinbase:/USD-ETH': 275.01,\n     'coinbase:/USD:/free': 10000,\n     'coinbase:/USD:/locked': 0,\n     'coinbase:/USD:/total': 10000,\n     'coinbase:/BTC:/free': 10,\n     'coinbase:/BTC:/locked': 0,\n     'coinbase:/BTC:/total': 10,\n     'coinbase:/BTC:/worth': 25091.7,\n     'coinbase:/ETH:/free': 5,\n     'coinbase:/ETH:/locked': 0,\n     'coinbase:/ETH:/total': 5,\n     'coinbase:/ETH:/worth': 1375.05,\n     'net_worth': 36466.75}\n\n\n\n## Setup and Train DQN Agent\n\n\n```python\n%tensorboard --logdir agents --host 192.168.1.220 --port 8008\n```\n\n\n    ERROR: Failed to launch TensorBoard (exited with 255).\n    Contents of stderr:\n    2020-04-18 07:35:56.225715: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libnvinfer.so.6\n    2020-04-18 07:35:56.226967: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libnvinfer_plugin.so.6\n    E0418 07:35:57.417469 140126108538688 program.py:288] TensorBoard could not bind to unavailable address 192.168.1.220\n    ERROR: TensorBoard could not bind to unavailable address 192.168.1.220\n\n\n\n```python\nfrom tensortrade.agents import DQNAgent\n\nagent = DQNAgent(env)\n\nagent.train(n_steps=200, save_every=200, save_path=\"agents/\", log_path=\"logs/\")\n```\n\n## Plot Performance\n\n\n```python\n%matplotlib inline\n\nportfolio.performance.plot()\n```\n\n\n```python\nportfolio.performance.net_worth.plot()\n```\n\n## Setup and Train A2C Agent\n\n\n```python\nfrom tensortrade.agents import A2CAgent\n\nagent = A2CAgent(env)\n\nagent.train(n_steps=200, save_path=\"agents/\")\n```\n\n\n```python\nportfolio.performance.plot()\n```\n\n\n```python\nportfolio.performance.net_worth.plot()\n```\n\n## Setup and Train Parallel DQN Agent\n\n\n```python\nfrom tensortrade.agents import ParallelDQNAgent\n\ndef create_env():\n    feed = DataFeed([coinbase_ns])\n\n    portfolio = Portfolio(USD, [\n        Wallet(coinbase, 10000 * USD),\n        Wallet(coinbase, 10 * BTC),\n        Wallet(coinbase, 5 * ETH),\n    ])\n    \n    env = TradingEnvironment(\n        feed=feed,\n        portfolio=portfolio,\n        action_scheme='managed-risk',\n        reward_scheme='risk-adjusted',\n        window_size=20\n    )\n    \n    return env\n\nagent = ParallelDQNAgent(create_env)\n\nagent.train(n_envs=4, n_steps=200, save_path=\"examples/agents/\")\n```\n\n    ====      EPISODE ID (0/2147483647): 0a15a273-c1e9-4f8e-9a50-6ea95795b484      ====\n    ====      EPISODE ID (0/2147483647): d311dbdc-33d7-4704-b394-9468481e8c68      ====\n    ====      EPISODE ID (0/2147483647): 9bca0f01-925f-4e73-86eb-c91ba8f9d20c      ====\n    ====      EPISODE ID (0/2147483647): 3d12e8dd-674e-45c9-9009-59ab235342af      ====\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "62fb21f020f01e6a7e685dcc49a4df286baaa7a6", "size": 104963, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/train_and_evaluate.ipynb", "max_stars_repo_name": "owodunni/tensortrade", "max_stars_repo_head_hexsha": "d6d7fb12f926b3c451d7e200cb693d750a35f95a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/train_and_evaluate.ipynb", "max_issues_repo_name": "owodunni/tensortrade", "max_issues_repo_head_hexsha": "d6d7fb12f926b3c451d7e200cb693d750a35f95a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/train_and_evaluate.ipynb", "max_forks_repo_name": "owodunni/tensortrade", "max_forks_repo_head_hexsha": "d6d7fb12f926b3c451d7e200cb693d750a35f95a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 213.3394308943, "max_line_length": 50000, "alphanum_fraction": 0.8709259453, "converted": true, "num_tokens": 2436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771241500058, "lm_q2_score": 0.03732688332823795, "lm_q1q2_score": 0.012619365369093482}}
{"text": "Ref: [Cell magics](https://ipython.readthedocs.io/en/stable/interactive/magics.html#cell-magics)\n\n\n```bash\n%%bash\necho \"Hello, World!\"\n```\n\n    Couldn't find program: 'bash'\n\n\n\n```python\n%%html\n<div style=\"height:60px; border:1px solid red; border-radius:20px; text-align:center;\" id=\"hello\">Hello, World!</div>\n```\n\n\n<div style=\"height:60px; border:1px solid red; border-radius:20px; text-align:center;\" id=\"hello\">Hello, World!</div>\n\n\n\n\n```python\n%%js\nvar parent = document.getElementById(\"hello\");\nvar div = document.createElement(div);\nparent.append(div);\ndiv.style.height = \"40px\";\ndiv.style.border = \"1px dashed blue\";\ndiv.innerHTML = \"Hello, World!\";\ndiv.style.float = \"right\";\ndiv.style.background = \"#cfc\";`\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\nJS can get the DOM element in another cell.\n\n\n```latex\n%%latex\n\\begin{equation}\\label{eq1}\\tag{1}\ny = ax^2 + bx + c\n\\end{equation}\n\nEquation \\eqref{eq1} is something that we use to see.\n```\n\n\n\\begin{equation}\\label{eq1}\\tag{1}\ny = ax^2 + bx + c\n\\end{equation}\n\nEquation \\eqref{eq1} is something that we use to see.\n\n\n\n\n```latex\n%%latex\nEquation \\eqref{eq1} can not be refered in other cell.\n```\n\n\nEquation \\eqref{eq1} can not be refered in other cell.\n\n\n\n\n```python\n%%markdown\n\nA | B | C\n:-: | :- : | :-:\nC | D | E\n```\n\n\n\nA | B | C\n:-: | :- : | :-:\nC | D | E\n\n\n\nA | B | C\n:-: | :- : | :-:\nC | D | E\n\n\n```python\n%%script cmd\necho \"Hi\"\n```\n\n    Microsoft Windows [Version 10.0.19042.1586]\n    (c) Microsoft Corporation. All rights reserved.\n    \n    L:\\home\\cookbook\\notebook\\hello>echo \"Hi\"\n    \"Hi\"\n    \n    L:\\home\\cookbook\\notebook\\hello>\n\n\n```perl\n%%perl\n\nprint(\"Hello World\\n\");\n```\n\n    Hello World\r\n\n\n\n```python\n%%script perl\nprint(\"Hello World\\n\");\n```\n\n    Hello World\r\n\n\n\n```python\n%%html\n\n<svg>\n<ellipse style=\"fill:#00ff00;stroke:#000000;\" cx=\"50\" cy=\"50\" rx=\"48\" ry=\"48\">\n<ellipse>\n</svg>\n```\n\n\n\n<svg>\n<ellipse style=\"fill:#00ff00;stroke:#000000;\" cx=\"50\" cy=\"50\" rx=\"48\" ry=\"48\">\n<ellipse>\n</svg>\n\n\n\n\n```python\n%%svg\n\n<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" height=\"103.0pt\" viewbox=\"0.00 0.00 170.0 103.0\" width=\"170.0pt\">\n<g class=\"graph\" id=\"graph0\" transform=\"scale(1.0 1.0) rotate(0) translate(4 199)\">\n<title>G</title>\n<polygon fill=\"#ffffff\" points=\"-4,4 -4,-199 166,-199 166,4 -4,4\" stroke=\"transparent\"/>\n<!-- node0000 -->\n<g class=\"node\" id=\"node1\">\n<title>node0000</title>\n<ellipse cx=\"81\" cy=\"-159\" fill=\"none\" rx=\"36\" ry=\"36\" stroke=\"#000000\"/>\n<text fill=\"#000000\" font-family=\"Times,serif\" font-size=\"10.00\" text-anchor=\"middle\" x=\"81\" y=\"-156.5\">ABCDEFGH</text>\n</g>\n</g>\n</svg>\n```\n\n\n    \n\n    \n\n\n\n```python\n\n```\n\n\n```python\n%%go\n\npackage main\nimport \"fmt\"\nfunc main() {\n    fmt.Println(\"hello world\")\n}\n```\n\n    UsageError: Cell magic `%%go` not found.\n\n\n\n```python\n%%java\n\n// Your First Program\n\nclass HelloWorld {\n    public static void main(String[] args) {\n        System.out.println(\"Hello, World!\"); \n    }\n}\n```\n\n    UsageError: Cell magic `%%java` not found.\n\n\n\n```python\n%%markdown\n\nCode for mermaid\n\n```mermaid\nflowchart TD\n    A[Start] --> B{Is it?};\n    B -->|Yes| C[OK];\n    C --> D[Rethink];\n    D --> B;\n    B ---->|No| E[End];\n```\n```\n\n\n\nCode for mermaid\n\n```mermaid\nflowchart TD\n    A[Start] --> B{Is it?};\n    B -->|Yes| C[OK];\n    C --> D[Rethink];\n    D --> B;\n    B ---->|No| E[End];\n```\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "1b39bf37ce924af2a14c40d9642694c6159eeedb", "size": 10564, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebook/hello/notebook_cell_magics.ipynb", "max_stars_repo_name": "dudung/cookbook", "max_stars_repo_head_hexsha": "8a43a923af8367dafd04e3dd2ef6b9e7ed82b22f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebook/hello/notebook_cell_magics.ipynb", "max_issues_repo_name": "dudung/cookbook", "max_issues_repo_head_hexsha": "8a43a923af8367dafd04e3dd2ef6b9e7ed82b22f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebook/hello/notebook_cell_magics.ipynb", "max_forks_repo_name": "dudung/cookbook", "max_forks_repo_head_hexsha": "8a43a923af8367dafd04e3dd2ef6b9e7ed82b22f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3813559322, "max_line_length": 170, "alphanum_fraction": 0.4575918213, "converted": true, "num_tokens": 1114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19682619422045972, "lm_q2_score": 0.06371500047450808, "lm_q1q2_score": 0.01254078105815221}}
{"text": "```python\nimport theme\ntheme.load_style()\n```\n\n\n\n\n<style>\n@import url('http://fonts.googleapis.com/css?family=Source+Code+Pro');\n@import url('http://fonts.googleapis.com/css?family=Vollkorn');\n@import url('http://fonts.googleapis.com/css?family=Arimo');\n@import url('http://fonts.googleapis.com/css?family=Arvo:400,700,400italic')\n\n#notebook li { /* More space between bullet points */\n    margin-top:0.8em;\n}\n\n/* draw border around running cells */\ndiv.cell.border-box-sizing.code_cell.running {\n    border: 3px solid #111;\n}\n\ndiv.cell.code_cell {\n    margin-top: 1em;\n    margin-left: auto;\n    margin-right: auto;\n    width: 800px;\n    border: 1px solid rgba(200, 200, 200, 0.8);\n    border-radius: 8px; /* rounded borders */\n}\n\ndiv.text_cell_render{\n    font-family: 'Arvo' sans-serif;\n    /* font-family: 'Arimo',verdana,arial,sans-serif; */\n    line-height: 130%;\n    font-size: 115%;\n    margin-left:0%;\n    margin-right:auto;\n}\n\n.text_cell_render h1 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 300;\n    font-style: bold;\n    font-size: 30pt;\n    line-height: 100%;\n    color:#c76c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h2 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 20pt;\n    line-height: 100%;\n    color:#c76c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h3 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 16pt;\n    line-height: 100%;\n    color:#d77c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h4 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 14pt;\n    font-style: italic;\n    line-height: 100%;\n    color:#d77c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h5 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 12pt;\n    color: #1d3b84;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n}\n\n.rendered_html code{\n    background-color: transparent;\n}\n\nul{\n    margin: 2em;\n}\n\nul li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.5em;\n}\n\nul li li{\n    padding-left: 0.2em;\n    margin-bottom: 0.2em;\n    margin-top: 0.2em;\n}\n\nol{\n    margin: 2em;\n}\n\nol li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.5em;\n}\n\nul li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.2em;\n}\n\na:link{\n    font-weight: bold;\n    color:#447adb;\n}\n\na:visited{\n    font-weight: bold;\n    color: #1d3b84;\n}\n\na:hover{\n    font-weight: bold;\n    color: #1d3b84;\n}\n\na:focus{\n    font-weight: bold;\n    color:#447adb;\n}\n\na:active{\n    font-weight: bold;\n    color:#447adb;\n}\n\n.rendered_html :link {\n    text-decoration: underline;\n}\n\n.rendered_html :hover {\n    text-decoration: none;\n}\n\n.rendered_html :visited {\n    text-decoration: none;\n}\n\n.rendered_html :focus {\n    text-decoration: none;\n}\n\n.rendered_html :active {\n    text-decoration: none;\n}\n\n.warning{\n    color: rgb( 240, 20, 20 )\n}\n\nhr {\n    color: #f3f3f3;\n    background-color: #f3f3f3;\n    height: 1px;\n}\n\nblockquote{\n    display:block;\n    background: #fcfcfc;\n    border-left: 5px solid #c76c0c;\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    width:680px;\n    padding: 10px 10px 10px 10px;\n}\n\nblockquote p {\n    margin-bottom: 0;\n    line-height: 125%;\n    font-size: 100%;\n}\n\ntable#mytable,\ntable#mytable td,\ntable#mytable tr\n{\n    border: none !important;\n}\n\ntable#mytable-1,\ntable#mytable-1 td,\ntable#mytable-1 tr\n{\n    border: none !important;\n    align: center;\n    cellspacing: 10;\n}\n\n.msg {\n    width: 90%;\n    margin-left: auto;\n    margin-right: auto;\n    margin-top: 10px;\n    margin-bottom: 10px;\n    padding: 14px 14px 14px 14px;\n    color: #c09853;\n    text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);\n    background-color: #fcf8e3;\n    border: 1px solid #fbeed5;\n    -webkit-border-radius: 4px;\n    -moz-border-radius: 4px;\n    border-radius: 4px;\n}\n\n.msg-heading {\n    color: inherit;\n}\n\n.msg .close {\n    position: relative;\n    top: -2px;\n    right: -21px;\n    line-height: 18px;\n}\n\n.msg-success {\n    color: #468847;\n    background-color: #dff0d8;\n    border-color: #d6e9c6;\n}\n\n.msg-danger,\n.msg-error {\n    color: #b94a48;\n    background-color: #f2dede;\n    border-color: #eed3d7;\n}\n\n.msg-info {\n    color: #3a87ad;\n    background-color: #d9edf7;\n    border-color: #bce8f1;\n}\n\n.boxed {\n    color: #b94a48;\n    background-color: #f2dede;\n    border-color: #eed3d7;\n    margin-left: auto;\n    margin-right: auto;\n    padding: 14px 14px 14px 14px;\n}\n\n.w-300 { width: 300px; }\n.w-400 { width: 400px; }\n.w-500 { width: 500px; }\n\n</style>\n\n\n\n\n# Lesson 6: Variational Forms and Solution Methods\n\n\n\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\"></a>\n\nThis lecture by Tim Fuller is licensed under the\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\">Creative Commons Attribution 4.0 International License</a>.  All code examples are also licensed under the [MIT license](http://opensource.org/licenses/MIT).\n\n\n```python\nfrom sympy import *\nfrom numpy import linspace\nfrom matplotlib.pyplot import plot, legend\ninit_printing()\n```\n\n<a id='top'></a>\n# Topics\n\n- [Why Variational Methods](#why)\n- [Weighted Residual Methods](#resid-meths)\n  - [Collocation](#collocation)\n  - [Least Squaes](#lsq)\n  - [Galerkin](#galerkin)\n- [Exercises](#exercises)\n\n# <a id='why'></a> Why Variational Methods?[](#top)\nIn the finite element method, the solution to the governing equation is approximated by\n\n$$\nu \\approx u_N = \\phi_0 + \\sum_{i=1}^n u_i \\phi_i\n$$\n\nand the unknown coefficients $u_i$ are found through an integral statement of the governing equation.  The integral statement is necessary because substitution of the approximate solution into the governing equation does not always result in the required number of linearly independent equations for $u_i$.  *Weighted integrals* allow one to insure that there are exactly $n$ equations for the $n$ unknown $u_i$.  We call $u_N$ the $N-$parameter approximate solution to $u$.\n\nFor example, suppose we wished to approximate the solution to\n\n\n```python\nx, u1, u2 = symbols('x u1 u2')\nu = Function('u')\nL = lambda f: -diff(x * f.diff(x), x) + f\node = L(u(x))\node\n```\n\nwith boundary conditions $u(0)=1$ and $\\left(xu'\\right)_{x=1}=0$.\n\nLet's choose \n\n\n```python\nuN = u1 * (x ** 2 - 2 * x) + u2 * (x ** 3 - 3 * x) + 1\nuN\n```\n\n<div class='msg msg-info'>\n<p><strong>Remark</strong></p>\nThe approximate solution must satisfy the boundary conditions for all $u_i$.\n</div>\n\nThe constants $u_1$ and $u_2$ are determined such that $u_N$ satisfies the governing equation in some sense.  If $u_N$ were to satisfy the governing equation exactly, we get\n\n<div class='msg msg-info'><b>Remark</b><br>\nBy definining the approximate solution as a sum of homogeneous and nonhomogeneous parts, the nonhomogeneous essential boundary conditions can be satisfied by $\\phi_0$, $\\phi_0(x_0) = u_0$ and $\\phi_i$ are required to satisfy the homgeneous form of the same boundary condition $\\phi_i(x_0) = 0$.  In this way, $u_N$ satisfies the specified boundary conditions\n\n$$\nu_N(x_0) = \\sum_{i=1}^Nc_i\\phi_i(x_0) + \\phi_0(x_0) = u_0\n$$\n\nIf the specified essential boundary conditions are homogeneous the $\\phi_0$ is taken to be zero and $\\phi_i$ must still satisfy the same conditions $\\phi_i(x_0)=0$\n</div>\n\n\n```python\nL(uN).series(x)\n```\n\nSince the expression must be zero for any value of $x$, the coefficients of any power of $x$ must be zero:\n\n$$\n\\begin{split}\n1+2u_1+3u_2 &= 0\\\\\n-(6u_1+3u_2) &= 0\\\\\nu_1-9u_2 &= 0\\\\\nu_2 &= 0\n\\end{split}\n$$\n\nThe above set of equations is inconsistent and no solution exists.\n\nRather than require that the approximate solution satisfy the governing equation exactly, let's require that it satisfies it in a weighted-integral sense:\n\n$$\n\\int_0^1w\\mathscr{R}dx=0\n$$\n\nwhere $\\mathscr{R}$ is called the residual\n\n$$\n\\mathscr{R}\\equiv -\\frac{du_N}{dx} - x\\frac{d^2}{dx^2}+u_N\n$$\n\nand $w$ is called a weight function.\n\n<div class='msg msg-info'><p><strong>Remark</strong></p>\nThe residual is the non-zero remainder obtained by substituting the approximate solution in to the governing equation.\n</div>\n\nA sufficiently many number of independent equations for $u_i$ are obtained by choosing an appropriate number of functions for $w$.  For example, let $w=1$ and $w=x$.  Then,\n\n\n```python\nresidual = L(uN)\nw1 = 1\nR1 = integrate(w1 * residual, (x, 0, 1))\nR1\n```\n\n\n```python\nw2 = x\nR2 = integrate(w2 * residual, (x, 0, 1))\nR2\n```\n\nWhich provide two linearly independent equations for $u_1$ and $u_2$\n\n\n```python\nc = solve((R1, R2), u1, u2)\nuN = uN.subs(c)\nuN\n```\n\nWe see that integral statements provide a means for generating as many equations are there are unkown coefficients in the approximate solution.  The above technique is an example of a variational method.  In variational methods, an approximate solution of the form of $u_n$ are sought and the coeficients $c_i$ are determined.\n\n# <a id='resid-meths'></a> Weighted Residual Methods[](#top)\n\nThe objective of this section is to expose you to variational methods of approximation.  We will look at collocation, least-squares, and Galerkin methods.  In each of these methods, we seek an approximate solution in the form of a linear combination of approxmiation functions $\\phi_i(x)$ and undetermined parameters $c_i$: $\\sum_i c_i\\phi_i$.  The parameters $c_i$ are determined such that the approximate solution satisfies a weighted integral form of the governing equation.  The finite element method makes use of variational methods to formulate the discrete equations over an element and this section will serve as an introduction to those concepts.\n\n<a id='collocation'></a>\n## Collocation Method\n\nIn the collocation method, we seek an approximate solution $u_n$ by requiring that the residual $\\mathscr R$ vanishes at as many points $x_i$ as there are unknown coefficients:\n\n$$\n\\mathscr{R}(x_i, c_j) = 0 \\quad (i=1,2,\\ldots,n)\n$$\n\nThe collocation method is a special case of the weighted residual formulation with $w=\\delta(x-x_i)$, where $\\delta(x)$ is the Dirac delta function, which is defined by\n\n$$\n\\int_{-\\infty}^{\\infty}f(x)\\delta(x-x_i)dx = f(x_i)\n$$\n\nWith this choice of weight functions, the weighted-residual statement is\n\n$$\n\\int_{\\Omega}\\delta(x-x_i)\\mathscr{R}(x_i, c_j)dx = 0\n$$\n\nor\n\n$$\n\\mathscr{R}(x_i, c_j) = 0\n$$\n\n<a id='lsq'></a>\n## Least Squares Method\n\nIn the least squares method we wish to minimize residual in the sense of least squares. Mathematically we say that we wish to minimize the integral of the square of the residual on some interval\n\n$$\n   \\min\\int_{x_0}^{x_f}\\mathscr R^2\\,dx\n$$\n\n\nRecall from calculus, that the minimum of a function occurs where its first derivative, with respect to the minimizing variable, is equal to zero. This fact leads to\n\n\n$$\n   \\frac{\\partial{}}{\\partial{c_{i}}}\\int\\mathscr R^2\\,dx=0\n   \\quad i=0,1,\\ldots,n-1\n$$\n\n\nBy the chain rule of calculus we re-write as\n\n\n$$\n   \\int\\mathscr R\\frac{\\partial{\\mathscr R}}{\\partial{c_{i}}}\\,dx=0\n$$\n\n\nUpon substituting $\\mathscr R$ and performing the required integration we will end up with $n$ equations for the $n$ unknown $c_{i}$ as in the collocation method.\n\n<a id='galerkin'></a>## Galerkin Method\nIn the Galerkin method, the choice of weighting functions $w_i$ is restricted to be equal to the approximation function $\\phi_i$, giving\n\n$$\n\\int \\mathscr{R}\\phi_i dx = 0\n$$\n\n\n\n### An Appeal to Physical Intuition\n\nVector analysis can give physical insight in to the Galerkin weighted-residual method.  Suppose we wished to approximate the vector $\\boldsymbol{v}\\in\\mathbb{R}^3$ with a vector $\\boldsymbol{v}^*\\in\\mathbb{R}^2$, as shown\n\n\n\nFor what values of $v_x^*$ and $v_y^*$ is the residual vector $\\boldsymbol{R}$ minimized? Stated differently, what values of $v_x^*$ and $v_y^*$ minimize $\\mathscr{R}=\\lVert \\boldsymbol{R} \\rVert$?\n\nIt turns out, that the minimum occurs at $\\mathscr{R}=v_z$ when $\\boldsymbol{v}^*$ is the orthogonal projection of $\\boldsymbol{v}$ on to $\\mathbb{R}^2$ (then $v_x^*=v_x$ and $v_y^*=v_y$, this should make sense intuitively.)  Mathematically, we say\n\nThus, the minimum $\\mathscr{R}=\\lVert \\boldsymbol{R} \\rVert$ occurs when $\\boldsymbol{R}$ is orthogonal to $\\boldsymbol{v}^*$\n\n$$\n(\\boldsymbol{R}, \\boldsymbol{v}^*) = 0\n$$\n\nReplacing \"vectors\" in the above discussion with \"functions\", we arrive at\n\n$$\n(\\mathscr{R}, \\phi_i) = (\\mathscr{R}, w) = 0\n$$\n\nwhich is the Galerkin weighted-residual method.\n\n<a id='example'></a>\n## Example\n\nConsider the following differential equation\n\n$$\n-\\frac{d^2u}{dx^2} - u + x^2, \\quad u(0) = 0, u'(1) = 1\n$$\n\nFor a weighted-residual method, $\\phi_0$ and $\\phi_i$ should satisfy\n\n$$\n\\begin{align}\n\\phi_0(0) = 0, \\ \\phi_0'(1) = 1 \\quad &\\text{(boundary conditions)}\\\\\n\\phi_i(0) = 0, \\ \\phi_i'(1) = 0 \\quad &\\text{(homogeneous boundary condtions)}\n\\end{align}\n$$\n\nWe choose $\\phi_0(x) = a + bx$ and use the conditions on $\\phi_0$ to determine that \n\n$$ \\phi_0(x) = x $$\n\nSince there are two homogeneous boundary conditions, $\\phi_1$ must be at least a three parameter polynomial.  We choose $\\phi_1=a+bx+cx^2$.  We use the boundary conditions to find that\n\n$$ \\phi_1(x) = -x(2 - x) $$\n\nFor $\\phi_2$ we assume the form $\\phi_2 = a + cx^2 + dx^3$.  Enforcing boundary conditions we get\n\n$$ \\phi_2(x) = -x^2\\left(1 - \\frac{2}{3}x\\right) $$\n\nThe residual in the approximation is\n\n$$\n\\mathscr{R} = -\\left(0 + \\sum_{i=1}^2c_i\\frac{d^2\\phi_i}{dx^2}\\right)\n            - \\left(\\phi_0 + \\sum_{i=1}^2c_i\\phi_i\\right) + x^2\n$$\n\nLet's now use the various methods to solve for $c_i$.\n\n### Setup\n\n\n```python\n# symbols\nc1, c2, x = symbols('c1 c2 x')\n\n# differential operator\nL = lambda f: -f.diff(x, x) - f + x ** 2\n\n# approximate solution basis functions\nphi0 = x\nphi1 = x * (2 - x)\nphi2 = x ** 2 * (1 - 2 * x / 3)\n\n# Residual\nR = L(phi0 + c1 * phi1 + c2 * phi2)\nR.simplify()\n```\n\n### Galerkin Method\n\n\n```python\n# Galerkin method\n# wi = phii\ngal = [integrate(phi1 * R, (x, 0, 1)), \n       integrate(phi2 * R, (x, 0, 1))]\nc = solve(gal, c1, c2)\nugal = phi0 + c[c1] * phi1 + c[c2] * phi2\nugal\n```\n\n### Least Squares method\n\n\n```python\n# Least squares method\n# wi = dR/dci\nlsq = [integrate(R.diff(c1) * R, (x, 0, 1)), \n       integrate(R.diff(c2) * R, (x, 0, 1))]\nc = solve(lsq, c1, c2)\nulsq = phi0 + c[c1] * phi1 + c[c2] * phi2\nulsq\n```\n\n### Collocation method\n\n\n```python\n# Collocation method\n# choose points x1 = 1/3, x2 = 2/3\ncol = [R.subs({x: 1. / 3.}), \n       R.subs({x: 2. / 3.})]\nc = solve(col, c1, c2)\nucol = phi0 + c[c1] * phi1 + c[c2] * phi2\nucol\n```\n\n### Analytic solution\n\n\n```python\n# analytical solution\nu = Function('u')\nsol = dsolve(L(u(x))).rhs\nc = solve([sol.subs(x, 0), sol.diff(x).subs(x, 1) - 1], 'C1', 'C2')\nsol = sol.subs(c)\nsol\n```\n\n### Comparison of Solution Methods\n\n\n```python\n%matplotlib inline\nf_ana = lambdify(x, sol)\nf_col = lambdify(x, ucol)\nf_lsq = lambdify(x, ulsq)\nf_gal = lambdify(x, ugal)\nxvals = linspace(0, 1, 100)\nplot(xvals, [f_ana(xval) for xval in xvals], label=\"Analytic\", color='black')\nplot(xvals, [f_col(xval) for xval in xvals], label=\"Collocation\")\nplot(xvals, [f_lsq(xval) for xval in xvals], label=\"Least squares\")\nplot(xvals, [f_gal(xval) for xval in xvals], label=\"Gallerkin\")\nlegend(loc=\"best\");\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "a8334dc7856f39759b8bc584792758ac6e5f04a9", "size": 80619, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lessons/Lesson06_VariationalForms.ipynb", "max_stars_repo_name": "jzw0025/fem-with-python", "max_stars_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 148, "max_stars_repo_stars_event_min_datetime": "2015-11-05T16:32:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:42:26.000Z", "max_issues_repo_path": "Lessons/Lesson06_VariationalForms.ipynb", "max_issues_repo_name": "pinkieli/fem-with-python", "max_issues_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lessons/Lesson06_VariationalForms.ipynb", "max_forks_repo_name": "pinkieli/fem-with-python", "max_forks_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": 74, "max_forks_repo_forks_event_min_datetime": "2016-02-17T13:23:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T07:48:27.000Z", "avg_line_length": 75.3448598131, "max_line_length": 25816, "alphanum_fraction": 0.7646212431, "converted": true, "num_tokens": 4969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10230471884065048, "lm_q2_score": 0.12252321572224491, "lm_q1q2_score": 0.012534703135916632}}
{"text": "# IPython's Rich Display System\n\nIn Python, objects can declare their textual representation using the `__repr__` method.  IPython expands on this idea and allows objects to declare other, richer representations including:\n\n* HTML\n* JSON\n* PNG\n* JPEG\n* SVG\n* LaTeX\n\nA single object can declare some or all of these representations; all are handled by IPython's *display system*. This Notebook shows how you can use this display system to incorporate a broad range of content into your Notebooks.\n\n## Basic display imports\n\nThe `display` function is a general purpose tool for displaying different representations of objects. Think of it as `print` for these rich representations.\n\n\n```\nfrom IPython.display import display\n```\n\nA few points:\n\n* Calling `display` on an object will send **all** possible representations to the Notebook.\n* These representations are stored in the Notebook document.\n* In general the Notebook will use the richest available representation.\n\nIf you want to display a particular representation, there are specific functions for that:\n\n\n```\nfrom IPython.display import display_pretty, display_html, display_jpeg, display_png, display_json, display_latex, display_svg\n```\n\n## Images\n\nTo work with images (JPEG, PNG) use the `Image` class.\n\n\n```\nfrom IPython.display import Image\n```\n\n\n```\ni = Image(filename='logo/logo.png')\n```\n\nReturning an `Image` object from an expression will automatically display it:\n\n\n```\ni\n```\n\nOr you can pass it to `display`:\n\n\n```\ndisplay(i)\n```\n\nAn image can also be displayed from raw data or a url\n\n\n```\nImage(url='http://python.org/images/python-logo.gif')\n```\n\n\n\n\n\n\n\n\nSVG images are also supported out of the box (since modern browsers do a good job of rendering them):\n\n\n```\nfrom IPython.display import SVG\nSVG(filename='python-logo.svg')\n```\n\n\n\n\n    \n\n    \n\n\n\n## Links to local files\n\nIf we want to create a link to one of them, we can call use the `FileLink` object.\n\n\n```\nfrom IPython.display import FileLink, FileLinks\nFileLink('Part 1 - Running Code.ipynb')\n```\n\n\n\n\n<a href='files/Part 1 - Running Code.ipynb' target='_blank'>Part 1 - Running Code.ipynb</a><br>\n\n\n\nAlternatively, if we want to link to all of the files in a directory, we can use the `FileLinks` object, passing `'.'` to indicate that we want links generated for the current working directory. Note that if there were other directories under the current directory, `FileLinks` would work in a recursive manner creating links to files in all sub-directories as well.\n\n\n```\nFileLinks('.')\n```\n\n\n\n\n./<br>\n&nbsp;&nbsp;<a href='files/./Progress Bars.ipynb' target='_blank'>Progress Bars.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./animation.m4v' target='_blank'>animation.m4v</a><br>\n&nbsp;&nbsp;<a href='files/./Cell Magics.ipynb' target='_blank'>Cell Magics.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./python-logo.svg' target='_blank'>python-logo.svg</a><br>\n&nbsp;&nbsp;<a href='files/./Frontend-Kernel Model.ipynb' target='_blank'>Frontend-Kernel Model.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Part 4 - Markdown Cells.ipynb' target='_blank'>Part 4 - Markdown Cells.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Part 5 - Rich Display System.ipynb' target='_blank'>Part 5 - Rich Display System.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Script Magics.ipynb' target='_blank'>Script Magics.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Part 3 - Plotting with Matplotlib.ipynb' target='_blank'>Part 3 - Plotting with Matplotlib.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Part 1 - Running Code.ipynb' target='_blank'>Part 1 - Running Code.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./User Interface.ipynb' target='_blank'>User Interface.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./R Magics.ipynb' target='_blank'>R Magics.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Animations Using clear_output.ipynb' target='_blank'>Animations Using clear_output.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./README.md' target='_blank'>README.md</a><br>\n&nbsp;&nbsp;<a href='files/./Importing Notebooks.ipynb' target='_blank'>Importing Notebooks.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./SymPy Examples.ipynb' target='_blank'>SymPy Examples.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Cython Magics.ipynb' target='_blank'>Cython Magics.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Octave Magic.ipynb' target='_blank'>Octave Magic.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Typesetting Math Using MathJax.ipynb' target='_blank'>Typesetting Math Using MathJax.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Data Publication API.ipynb' target='_blank'>Data Publication API.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Custom Display Logic.ipynb' target='_blank'>Custom Display Logic.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Part 2 - Basic Output.ipynb' target='_blank'>Part 2 - Basic Output.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./Trapezoid Rule.ipynb' target='_blank'>Trapezoid Rule.ipynb</a><br>\n./.ipynb_checkpoints/<br>\n&nbsp;&nbsp;<a href='files/./.ipynb_checkpoints/Data Publication API-checkpoint.ipynb' target='_blank'>Data Publication API-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./.ipynb_checkpoints/User Interface-checkpoint.ipynb' target='_blank'>User Interface-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./.ipynb_checkpoints/Cython Magics-checkpoint.ipynb' target='_blank'>Cython Magics-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./.ipynb_checkpoints/Animations Using clear_output-checkpoint.ipynb' target='_blank'>Animations Using clear_output-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./.ipynb_checkpoints/Frontend-Kernel Model-checkpoint.ipynb' target='_blank'>Frontend-Kernel Model-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./.ipynb_checkpoints/Part 5 - Rich Display System-checkpoint.ipynb' target='_blank'>Part 5 - Rich Display System-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./.ipynb_checkpoints/Part 1 - Running Code-checkpoint.ipynb' target='_blank'>Part 1 - Running Code-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./.ipynb_checkpoints/User Experience-checkpoint.ipynb' target='_blank'>User Experience-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./.ipynb_checkpoints/R Magics-checkpoint.ipynb' target='_blank'>R Magics-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./.ipynb_checkpoints/Importing Notebooks-checkpoint.ipynb' target='_blank'>Importing Notebooks-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./.ipynb_checkpoints/Part 3 - Plotting with Matplotlib-checkpoint.ipynb' target='_blank'>Part 3 - Plotting with Matplotlib-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./.ipynb_checkpoints/Progress Bars-checkpoint.ipynb' target='_blank'>Progress Bars-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./.ipynb_checkpoints/Part 2 - Basic Output-checkpoint.ipynb' target='_blank'>Part 2 - Basic Output-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./.ipynb_checkpoints/Custom Display Logic-checkpoint.ipynb' target='_blank'>Custom Display Logic-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./.ipynb_checkpoints/Script Magics-checkpoint.ipynb' target='_blank'>Script Magics-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./.ipynb_checkpoints/SymPy Examples-checkpoint.ipynb' target='_blank'>SymPy Examples-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./.ipynb_checkpoints/Trapezoid Rule-checkpoint.ipynb' target='_blank'>Trapezoid Rule-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./.ipynb_checkpoints/Cell Magics-checkpoint.ipynb' target='_blank'>Cell Magics-checkpoint.ipynb</a><br>\n./images/<br>\n&nbsp;&nbsp;<a href='files/./images/menubar_toolbar.png' target='_blank'>menubar_toolbar.png</a><br>\n&nbsp;&nbsp;<a href='files/./images/edit_mode.png' target='_blank'>edit_mode.png</a><br>\n&nbsp;&nbsp;<a href='files/./images/command_mode.png' target='_blank'>command_mode.png</a><br>\n./logo/<br>\n&nbsp;&nbsp;<a href='files/./logo/logo.png' target='_blank'>logo.png</a><br>\n./nbimp/<br>\n&nbsp;&nbsp;<a href='files/./nbimp/__init__.py' target='_blank'>__init__.py</a><br>\n&nbsp;&nbsp;<a href='files/./nbimp/mynotebook.ipynb' target='_blank'>mynotebook.ipynb</a><br>\n./nbimp/nbs/<br>\n&nbsp;&nbsp;<a href='files/./nbimp/nbs/other.ipynb' target='_blank'>other.ipynb</a><br>\n&nbsp;&nbsp;<a href='files/./nbimp/nbs/__init__.py' target='_blank'>__init__.py</a><br>\n\n\n\n### Embedded vs Non-embedded Images\n\nBy default, image data is embedded in the Notebook document so that the images can be viewed offline. However it is also possible to tell the `Image` class to only store a *link* to the image. Let's see how this works using a webcam at Berkeley.\n\n\n```\nfrom IPython.display import Image\nimg_url = 'http://www.lawrencehallofscience.org/static/scienceview/scienceview.berkeley.edu/html/view/view_assets/images/newview.jpg'\n\n# by default Image data are embedded\nEmbed      = Image(img_url)\n\n# if kwarg `url` is given, the embedding is assumed to be false\nSoftLinked = Image(url=img_url)\n\n# In each case, embed can be specified explicitly with the `embed` kwarg\n# ForceEmbed = Image(url=img_url, embed=True)\n```\n\nHere is the embedded version. Note that this image was pulled from the webcam when this code cell was originally run and stored in the Notebook. Unless we rerun this cell, this is not todays image.\n\n\n```\nEmbed\n```\n\n\n\n\n    \n\n    \n\n\n\nHere is today's image from same webcam at Berkeley, (refreshed every minutes, if you reload the notebook), visible only with an active internet connection, that should be different from the previous one. Notebooks saved with this kind of image will be lighter and always reflect the current version of the source, but the image won't display offline.\n\n\n```\nSoftLinked\n```\n\n\n\n\n\n\n\n\nOf course, if you re-run this Notebook, the two images will be the same again.\n\n## Audio\n\nIPython makes it easy to work with sounds interactively. The `Audio` display class allows you to create an audio control that is embedded in the Notebook. The interface is analogous to the interface of the `Image` display class. All audio formats supported by the browser can be used. Note that no single format is presently supported in all browsers.\n\n\n```\nfrom IPython.display import Audio\nAudio(url=\"http://www.nch.com.au/acm/8k16bitpcm.wav\")\n```\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"http://www.nch.com.au/acm/8k16bitpcm.wav\" type=\"audio/x-wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\nA Numpy array can be auralized automatically. The Audio class normalizes and encodes the data and embed the result in the Notebook.\n\nFor instance, when two sine waves with almost the same frequency are superimposed a phenomena known as [beats](https://en.wikipedia.org/wiki/Beat_%28acoustics%29) occur. This can be auralised as follows\n\n\n```\nimport numpy as np\nmax_time = 3\nf1 = 220.0\nf2 = 224.0\nrate = 8000.0\nL = 3\ntimes = np.linspace(0,L,rate*L)\nsignal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times)\n\nAudio(data=signal, rate=rate)\n```\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"data:audio/wav;base64,UklGRqS7AABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YYC7AAAAADUWvSvyPzdS/WHKbjt4Bn7+fxV+WXj3bjhifVJDQBYslBZiAC/qpdRswCGuU557kf2HJIIcgPWBoIfykKKdTa15v5rTEuk7/2kV8CopP3ZRSmEqbrJ3mH2vf+Z9TXgNb3Bi11K9QK0sQxcmAQPrhNVPwQOvLZ9IkreIxYKggFiC34cLkZOdFq0bvxbTbeh4/o0UASosPnNQSGAwbcd2w3z2fk9923fGblZi7FL/QBwt3hfoAefrg9ZlwiawVqBuk9OJzoOOgSSDg4iAkdadJa31vrvS3ue5/aIT8Sj/PDBP+F7da3t1h3vUfU98BncibuhhuVIJQWQtYRilAtjso9eqw4mxzKHtlE+LPYXkgleEiolTkm6ee60Hv4jSZuf//KsSwyeiO65NXF0zas9z5nlJfOh6zXUhbSdhPlLaQIItzBhbA9Xt39gexSmzjqPCliuNEYeihPKF9YqDk1mfGq5Uv3/SCOdN/KkReCYYOvBLd1szaMVx4HdYehp5MXTDaxNgfFFwQHUtHRkJBNvuN9q9xgW1l6XsmGOPR4nGhvKHwowPlZegAa/bv6LSxOak+58QFCVkOPhJSVnhZV9veXUCeOh2MnIIaqpecVDLPzwtUxmsBOjvp9uFyBm356dmm/aR3otOiVeK8Y73limiMLCewPHSneYG+48PmSOINslH11Y+Y6BssnJJdVF002/yZ+5cHU/rPtYsbBlEBfvwLd11ymO5e6ownuGU1I44jB+NgZE6mQ+kqLGcwW7Tk+Z1+noOCCKGNGVFI1ROYIppj28vcllxFG2CZeBagU3PPUMsZxnOBRHyyN6IzOC7T61GoSGYJZKBj0aQbpTXm0WmZ7PWwhjUp+by+WMNZCBhMtBCMFEUXSFmEWy4bgJu+Gm6YoFYnkt3PIIrQxlJBinzdOC9zo2+YLCkpLKbz5Unk8yTuJfLns2obrVMxPDU2+Z/+UwMsB4dMAxAAU6TWWdiPGjlak9qgWaaX9FVdEnjOpIq/xi0Bj/0L+IQ0WfBq7NHqJKfzpkml6yXXJsVoqSru7f9xffVL+ce+TYL7hy8LR09m0rOVWFeFGS6ZkJmsmImXNNSBEcVOXQpmhgMB1P19+N/02rELbctrL2jH557m+SbVp+zpciuTrroxy3XpefP+CQKIRtAKwY6/0bKURNanF87YuBhjV5gWIlPUEQMNycoFBhRB2P2yeUG1pTH4bpPsC+ovaIioHGgpKOhqTiyJL0OypHYPOiU+BgJSxmuKMo2M0OJTX9V2FpsXStdF1pKVPVLWUHKNKsmbBeCB2v3o+ej2OHKxb6stOOspacYpU6lQ6jdrfG1PMBtzCTa9ehu+BMIbhcHJm0zOT8RSatQzVVRWCdYUVXoTxlIID5PMgIloRadB2z4gulT203O08I+udax0qxXqneqLq1ksvC5k8MDz+Tb0ele+BcHjRVPI/MvFztmRJtLf1DvUtlSQVA9S/dDqTqeLysjtBWiB2P5ZOsS3tXRCccBvgK3P7Lcr+mvYrIytzK+KcfP0dHdz+pl+CYGqxOJIF4szzaMP1RG80pJTUVN6kpNRpQ/9ja3LCghpRSPB076Ru3e4HTVYcvxwmO86beitZ6127dEvLXC+srQ1Orf8OuE+EIFyRG5HbQoZzKIOtpALkVkR29HUUUbQfI6CDOcKfkecxNkByv7Ju+z4yjZ2M8JyPXByb2ju5K7lL2VwXXHA88E2C7iM+27+GsE6w/gGvck4i1eNTI7ND9HQV1BeT+sOxU25C5QJqAcHxIgB/r7AvGO5u3catREzbHH28PbwcHBiMMhx27MQ9No25zkmO4L+aQDEg4DGCshRSkTMGI1DDn2OhQ7aTkENgExiyrVIh4aqhDEBrr82PJt6b/gEdmd0pTNGcpFyCPIs8nlzJ3RtNf63jLnHfB0+e0CQAwkFVUdlCSsKm8vujJ2NJk0JTMnMLkrASYtH3QXEw9NBmj9pvRL7Jrkyt0Q2JfTfdDazrbOENDa0v3WVdy34u/pxPH3+UgCeApGEncZ1B8uJV0pQyzNLfEtsSwaKkImSiFbG6UUXQ2+BQP+aPYo73rokeKY3bXZA9eV1XLVmNb92IrcIeGd5tDsifOT+rYBuwhsD5UVCRueHzMjryUBJyInFCbiI6AgaRxiF7IRiAsVBYz+Hvj/8VzsYOcw4+rfpd1w3FLcSN1I30DiFeap6tTvbvVJ+zcBDAeZDLQRNxYAGvUcAh8YIDIgUx+FHdgaYxdEE54OlQlSBAD/xvnO9DzwNOzS6C/mXeRm41DjGeS25RroLevX7vjyb/cY/M0AbAXPCdYNYhFbFKoWQRgXGScZdBgHF+0UOxIGD2oLhgd3A2D/XvuS9xf0CPF67n/sJOtx6mfqBetD7BPuZfAl8zr2jPkA/XgA3AMRB/8JjwyxDlYQdBEEEgYSfBFuEOcO9QyqChoIWwWDAqr/5PxI+un32PUj9NXy9vGK8ZHxB/Ln8ib0uPWO95j5xPsA/jkAYAJiBDIGwwcKCQAKnwrmCtUKcQq/CcgIlQc0BrAEFwN3Ad7/V/7v/K/7n/rI+Sv5zPis+Mf4Gfme+U/6IvsQ/A79FP4Y/xAA9wDFAXQCAQNpA6sDyAPCA5wDWgMBA5cCIQKnAS4BvABUAPz/tv+D/2X/W/9j/3z/ov/Q/wIANABiAIcAngClAJkAeQBFAP7/pP87/8j+Tv7V/WD99/yg/GD8PPw5/Fn8nvwJ/Zn9S/4c/wMA/gACAgcDBQTxBMEFbgbwBj4HVAcuB8oGKQZMBTgE9QKJAQAAZv7G/C/7rflP+CH3L/aD9Sb1HfVr9RL2Dvdc+PL5x/vN/fb/MAJrBJUGmwhsCvgLLw0HDnQOcQ78DRMNvQsACucHggXiAhoAQP1p+q33IvXe8vXwd+9z7vXtA+6f7sjvd/Gj8zz2Mflq/NH/SgO8BgoKGg3RDxkS3hMOFZ4VhxXFFF0TVRG8DqMLIAhOBEkAMvwl+EX0sfCG7eDq1Oh259Pm9ObZ54Dp3+vk7nzyjPb1+pf/TATyCGQNfBEbFSAYdBoAHLYcjhyFG6EZ7RZ8E2cPzArMBY4APPv99fvwXuxM6OfkTOKR4Mbf9t8h4UHjSeYj6rTu2vNv+Uf/NQUNC58QvxVEGgge7CDXIrYjgSM1ItofgBw9GDITgw1bB+kAYPrx88/tLOg04xHf5NvK2dXYD9l72g/du+Bk5ejqHvHY9+L+BAYKDboT4BlKH8wjQieMKZgqWSrPKAMmCCL6HP8WQhD4CFgBnvkD8sbqHuRC3mHZotUn0wTSRtLt0/DWOduq4BvnW+409mn+ugboDrIW2h0oJGgpby0cMFYxEjFPLxcsgSevIcoaCBOjCtsB9fg18ODnOOB52dvTi8+tzFrLoMt+zenQydX821LjlOuE9N39VQemEIUZrCHaKNYubzN+Nuo3pTetNRAy5ixWJpEe0RVYDHECZ/iH7iDlfNze1IXOpMlixt3EIsUyxwDLcNBc147fyujJ8j791wdDEjEcUSVdLRM0PDmwPFA+DD7lO+k3MjLtKk8imhgXDhgD8/f77Iji7dh10GPJ8cNLwJG+0r4PwTnFMsvP0tbbAuYG8Y78Pgi+E7QeySitMRo50z6rQoFEQ0TyQZw9YTdvLwImYRveD9EDmPeR6xrgjtU/zHjEd75tuny4trgau5q/FcZazivYPuM97837jAgXFQ0hDyzHNec9L0RrSHhKQ0rNRyVDbTzXM6QpIh6pEZgEV/dK6tfdYdJByMm/O7nNtKSy0rJatSi6HMEAypLUgOBw7f76wAhNFjojIi+oOXdCSknqTTBQCFByTX5IUUEhODMt2yB3E24FL/cl6cDbaM9+xFm7QbRwrw2tLa3Sr+m0TbzGxQ7Rzd2i6yL63AhgFzslADJNPcdGIk4lU6VVjVXcUqNNCkZJPKswiCNGFVEGH/ck6NbZpcz4wCu3jK9ZqrunyqeHquCvrLexwaPNJtvU6Tr54AhPGA0nqDS0QNJKs1IXWNJazVoFWI9SkkpLQAg0JyYSFz8HJ/dH5xvYGsqxvUKzIKuNpbSir6J/pRKrPbPDvVTKkNgI6Ef4zAgbGbEoFzfaQ5dO+Va8XLJfw1/qXD1X5k4jREc3tSjbGDYIRveN5o7Wx8esuqKvAacPofud352+oISmBa8CuibHDNZD5kz3owjDGSYqTDm+RhJS8FoRYUJka2SGYapbAVPNR2U6LiueGjQJevf25THVsMXqt0ysMqPknJWZYJlJnDqiCKtwthrEntOF5Er2ZAhJGmsrRjtdSUJVl14RZX5owWjVZdBf31ZFS109jy1XHDkKwveB5QTU08NttUSptZ8PmYWVNJUimDmeSqcSszbBStHR4kP1EgisGoEsBT23SyNY6WG7aGJswWzSaaxjfFqITixA1i8FHkELHvgv5QbTM8I3s4qmjpySlc6RYJFOlIOaz6Psr3y+Ec8p4Tn0rQfuGmcthz7JTbVa5mQLbOtvaHB7bTpn1V2SUdBCADKlH0wMjPj95DjSz8BJsSGkvZlwknOO543RkB2XmqAArfC798yR3y/zNwcPGx0uzT+TT/Vcimf+bhdzs3PMcHhq5mBfVEVFCjQ1IVcNC/ns5JnRp7+jrwqiRpesj3eLy4qujQmUrp1SqpS5/soK3iXysQYQG6Uu1UAUUeJe1GmTceJ1nnbCc2FtrGPtVohH8TWyIl8OmPn75CnRvb5HrkagKZVHjd2IEIjnikyRDpvkp2u3KcmX3B3xHAbzGv4uoUFMUnxgw2vHc0p4KHlZdvJvJGY5WZZJszcaJGQPMvon5efQD74zrdaeaJNDi6eGuIV/iOeOv5i7pXi1e8c62xvwfAW4GikvMUI7U8JhVW2adU96TnuReCpyS2hAW21LTDlrJWMQ2fpw5dLQnr1qrLudBZKiidaExYN5ht2MwZbYo76z9sX22SDv0ARhGigvhELgU7Niim4Jd+17D31legV0H2r+XApNvDqjJloRifvV5enQaL3pq/Sc/pBliGuDOILWhDCLF5U+oj6yncTM2C7uHATvGfsunUI8VE9jYW8UeCN9Z37We4J1nWtzXmpO/ju+J0cSQfxU5izRbb2xq4KcVpCMh2iCE4GYg+OJxJPuoPywcsO/10ftYQNkGaMue0JQVJdj22+7ePJ9WH/gfJ92xWycX41PEj28KCgT//zr5pjRrL3Bq2ScDJAYh86BWIDBgveIyZLsn/qvdsLR1mzsoALBGCMuIEIcVItj92/9eFh+33+EfVt3k214YG9Q9T2aKfsTwv2Y5yzSI74ZrJqcH5AIh5yBBoBRgmyIKJI4nzmvrMED1qHr3AEJGHwtjUGhUyxjtW/beFZ+/H/AfbR3B24EYQ9Rpj5WKr8Uh/5b6ObS0b62rCKdjpBch9OBHYBJgkSI4ZHVnrquFsFZ1ebqFgE9F64sxEDiUntiF29UeOp9r3+Ufap3IG4/YWxRIj/vKnAVTf8w6cbTtL+XrfydWpEUiHKCn4CpgoCI9pHCnn+utMDT1D/qUABfFr4rxz/fUXphHm5rdxd9+H7/fDx33G0pYYRRaD9iKw4WEAAW6sjUy8C7riWfgJIviXmDioFygyCJaJIBn4quicBz1Kvpjv9xFasqlz6aUClgy2wfdt172X0DfGt2PW3AYFZRdz+vK5YW0gAL6+rVE8IgsJyg/5OqiuaE3oKihCOKNpOTn9uulsA61C7pz/51FHkpNz0WT4xeIWt0dD16UXyfejZ1QWwFYOJQTj/TKwgXjgEO7CzXi8PEsWCi1ZWGjLiGmoQ5homLYJR4oHOv3MAq1MnoFv5tEykoqDtUTaNcIGlpcjl4YnrVeJ9z6Gr2XiZQ7D7OK2EXQwIb7YrYMMWks22kAJi+ju6Iu4Y2iFKN5pWwoVKwW8FF1HzoZf1bEr4m7jlXS3Jay2YDcNN1DnimdqVxNGmVXSNPUD6eK6AX8AIx7gHa/8a9tcGmfppSkYWLQYmXinyPyJc6o3mxFMKK1EvovvxBETolCjghSftXJWRCbQxzV3UTdEtvJWfiW9lNej1DK8MXkgNO75Hb98gOuFqpS50/lHqOKYxbjQaSBJoXpeeyCMP71DboIfwiEJ8jADa2RkFVMWEqauhvQHIgcZJsvWTcWUhMaTy7KsoXKARv8DbdE8uTujSsZaCBl8yRcI9+kO2UmZxEp5y0NsSZ1T3okvv/DvAh0TMYREdS8l2+ZmpsyW7NbXxp/GGHV29KHTsHKrMXsQST8e7eU81JvUyvyaMWm3aVFJMAlDGYhZ/CqZe2n8Vk1mToEfvaDS8ggTFLQRFPa1oCY5Ro+Godagxm5V7iVFFIlzklKX4XKgW48rfgss8twKCycqf6nneZEpfcl86bx6KOrNi4Qsdc16nooPq2DGAeEy9QPqFLoFb4Xmpkz2YUZkNieVvvUe5F1jcWKCkXkgXb843iLtI8wyu2Xqspo8mdZpsQnMKfW6anr127H8mC2A7pQfqUC4MciiwtO/xHlFKkWvBfUWK2YSVevFewTkdD3TXZJrMW6AX79G/kxNRzxuq5ia+gp2miDKCZoAmkQKoLsyW+NcvW2ZTp9Pl3Cp0a6SnlNyVES04LVipbg10EXbVZsFMoS15AqjNvJR0WKwYW9lrmcNfNydi97rNarFSnAaVypaGocq63ti7BhM1X2zvqu/lfCa8YMid6NB9AykkxUR1WaFgEWPZUWE9YRzU9QDHYI2UVWQYp90voMNpIzfPBirhTsYSsQaqYqoWt77KqunfECdAE3QPrmPlQCLsWaSTwMPA7FUUbTMtQBVO6Uu1PuEpEQ845oC4UIowUcgY0+D/qAd3f0DbGV72GtvWxxq8GsLKys7ffvv3HxNLe3u3rivlLB8UUkSFMLZs3MUDMRjxLX00pTZ1K0kXuPio2zCslIJITdAY0+Tbs39+P1JzKUsLvu6K3jLW4tSS4urxUw73LstXj4Pjsk/lRBs8Srh6RKSUzITtKQXJFe0dXRwtFqkBaOk0yxCgLHnUSXwYo+ivuyOJV2CLPdceIwYe9jrupu9a9AcIGyLbP0tgS4yXutPlkBdsQwRvCJZEu6zWaO3Q/XEFIQTo/RjuLNTkuiyXHGzgRMwYO+x3wt+Us3MPTvcxOx57Dx8HUwcPDgsfyzOTTI9xr5XPv7fmFBOwOzxjkIeQpkzDBNUY5CjsCOzE5qDWFMPIpJCJaGdoP7gXk+wryq+gQ4HvYI9I6zeHJMcg0yOjJO80S0kXYoN/r5+LwPvq2AwMN2hX5HSIlHyvEL+4yiTSJNPMy1i9LK3olkB7HFlsOkAWr/O7zoOv/40XdpNdH00zQyM7Ezj3QJtNk19TcSeOR6nDyqPr5AiML5hIHGlEgkyWoKXIs3i3kLYcs1CniJdQg0xoOFL0MGQVf/cn1k+705x3iOt1w2djWhdV+1cDWPtni3I7hG+db7R30LPtOAk4J9Q8RFnMb9B9zI9clECcXJ/AlpyNPIAYc7hYzEQELiQQB/pj3gfHr6/7m4eKv34HdY9xc3Gndft+K4nDmEutI8On1yPu1AYUHCg0aEo8WSBoqHSIfJCApIDYfVB2VGhEX5hI2DicJ4QOP/ln5aPTg7+XrkugA5kDkXONZ4zPk4uVV6HbrK+9V89H3ffwxAcwFKQomDqcRkhTTFlsYIBkfGV0Y4Ba5FPsRvQ4aCzAHIAMJ/wv7RPfR88zwSu5c7A/raupu6hrrZOxA7pzwY/N/9tX5Sv3CACMEUwc5CsEM2Q5zEIURChIAEmoRUhDBDscMdgrhBx8FRgJu/6v8E/q697D1A/S+8unxhvGX8Rby/vJF9N31uPfF+fP7MP5oAIwCiwRWBuEHIgkQCqgK6ArQCmUKrQmwCHoHFQaOBPUCVQG9/zj+0vyW+4v6uPkh+cf4rPjL+CP5rPlf+jX7JPwk/Sr+Lf8kAAkB1AGBAgsDcAOvA8kDwAOXA1MD+AKNAhcCnQEkAbIATAD2/7H/gP9j/1v/Zf9//6X/1P8GADgAZQCJAJ8ApQCXAHYAQAD3/5z/Mv++/kT+y/1X/e/8mvxc/Dr8Ovxd/Kb8FP2n/Vz+Lv8YABMBGAIdAxkEAwXRBXsG+AZCB1MHKAe/BhkGNwUfBNgCaQHf/0T+pPwO+475NPgL9x72efUi9SD1dvUj9if3e/gX+vD7+v0kAGACmgTCBsQIkAoVDEUNFA54DmwO7Q37DJsL1gm3B0wFqALe/wP9Lfp19+/0svLQ8FzvZO7x7Qrusu7n76Hx1/N49nP5svwaAJQDBAdOClcNBhBEEv0TIBWjFX0VrRQ3EyMRfg5bC9EH+gPz/9r70ff282nwSe2u6rDoYefO5v/m9ees6RnsLO/O8uf2Vvv7/7EEVAm/Dc8RYRVZGJ0aGBy7HIAcZRtvGaoWKxMKD2QKXgUdAMv6j/WU8AHs/eeo5B7id+DB3wXgReF545Pmfuod70306fnF/7MFhwsRESYWnBpPHh8h9CK8I3AjDSKcHy0c2Re+EgMN0wZeANX5avNR7bvn0+LD3q3bqtnO2CLZp9pT3RXh0eVm66rxbPh6/5wGnA1DFFsatB8hJH4nrymfKkUqoCi6JaYhgxx2FqsPWAizAPn4ZPEx6pnj0N0F2WHVAdP80VzSINQ/16PbK+Gv5/7u4PYa/2sHkw9SF2oeoyTKKbYtRDBfMfswGC/CKxEnJSEsGloS6gkdATj4fu81557f9thy0z/PgsxQy7jLuM1D0UHWjtz6403sSPWm/h8IaRE7Gk8iZilGL8AzrTb1N4s3cDWwMWcsvCXfHQ0ViAubAZH3ue1f5M7bStQOzk7JMcbRxDzFcsdky/bQ/9dK4JnppfMg/rgIHRP8HAkm+i2RNJc55TxdPvE9ojt/N6YxQiqKIcEXMA0rAgb3Fuyy4SzYz8/eyJHDE8CDvu6+VcGnxcXLg9Ol3Obm+PGH/TYJrxSVH5MpWjKlOTg/5kKQRCZEqUEpPcc2sy4qJXMa4A7MApT2luov37rUicvmww2+L7psuNS4ZrsSwLTGHc8M2TbkRfDd/JsJHRYCIuwshTaAPp5ErEiKSiVKf0epQsc7DDO6KCAdlxB+Az32OenY3HvRfMcqv8e4ibSRsvGyqrWousfB0sqE1Yzhje4j/OUJaBdDJBIwdjodQ8NJMk5FUOlPH036R6BASDc4LMYfUBI/BAD2AOit2nDOqMOsusOzJa/3rE2tJ7BwtQO9psYR0uve0uxb+xUKjxhXJgEzKj55R6VOc1O9VW1VhFIYTU5FYzuhL2IiDBQNBdz16+ax2JzLE8BytgWvB6qip+un4KpvsG24nsK1zlXcF+uH+i0Kkhk8KLk1oEGRSz9TbFjsWqxaqlf9Uc1JWD/vMvAkxhXoBdH1++Xj1gDJvrx9spCqNaWYos+i3KWoqwe0vL51y8/ZXemn+SwKcBryKTg41ERiT45XF13QX6JfjFylVhdOJEMgNm0nfhfNBt31L+VG1Z7Gq7nRrmimsaDcnQCeHqEgp9ivBrtUyFvXqOe9+BQKKht3K306xkfpUo9bcmFkZEpkJmELWypSxEYwOdgpMRm7BwD2h+TY03fE3LZwq5CigJxymYCZqpzbouOrf7dVxfvU+eXL9+YJwBvMLIY8ckojVj5feWWjaKFocmUtXwBWMkocPCws2xqwCDn2A+Sc0o3CU7RdqAqfpJhelVOVhZjeniyoKrR8wrPSU+TT9qMJMhzwLVI+10wPWZhiKGmKbKJsbmkFY5dZbE3hPmcufByrCYb2ouOQ0d/AEbKZpdqbIZWkkX6Rs5Qsm7ekDLHMv4bQuOLX9UwJghzjLuE/9U6qW51lfmwXcEtwFm2QZupcblB8QYYwEB6oCuf2Y+O10G+/GLAnowKZ+pFFjgOON5HJl4ehJ65IvXbOLOHY9OIIsBymLzJByVDzXUhod29Gc5dzZnDKafZfNVPoQ4YylR+oC1n3RuML0D2+aK4HoYSWMI9Gi+aKFI64lJ+ef6v0uobMr9/Z82cIvBw4MEVCVFLpX5lqEXIVdoV2W3OxbLhivVUkRmU0CSGmDNz3SuOQz0m9Aq07n2CUxoypiCmITYv8kQOcF6nRuLnKRN7b8t0HqBybMBpDlVOLYY9sSnSBeBB583VBby1lBFgsSB82aSKjDW74beNFz5K856vEnZmSvopvhs+F5IiYj7aZ8abkthLJ79zh8UUHdhzPMLJDi1TXYiduInaIejh7K3h4cVJnCFr/SbM3tCOaDgz5r+Mozxm8FqujnDCRGImahNqD3YaOjbqXEaUttZLHsNvs8KAGJhzVMAxEN1XOY2FvlXcqfPt8AXpUcyVpxFuYSx455iSMD7b5DeQ5z927j6rWmyWQ14csg0uCOYXiixGWeaOxszzGitr/7/EFuhutMCpEmFVwZD1wpHhkfVZ+c3vRdKNqOF33TF46/iV1EGr6h+R3z927U6pgm3iP+oYmgiSB+oOUir6UKqJxshPFgNkb7zoFMxtbMA1EsFW8ZLpwT3k2fkl/gHzvdctrYV4YTnE7+iZTESX7GuXfzxi8X6o+myqPgoaJgWWAIYOmicKTKKFusRjElNhD7nsEkxrdL7VDgFWzZNlwlHmfftJ/JX2tdptsPV/7TlM81yclEub7xuVx0Iy8tKpxmzqPb4ZUgRGAroIZiR+Tc6CssE7Dxtd47bgD3Bk3LyRDCFVXZJtwdHmffvJ/ZH0IdxFtyl+dTwU9lCjoEqv8iOYq0Tm9T6v3m6iPwYaJgSaApILviNaSDKArsLXCGte87PECEBlqLlxCSVSnY/9v8Hg2fqh/O30BdyxtCWD8T4Q9LymcE3P9XucK0h2+MKzPnHKQeIcmgqWAAYMoieiS95/ur1HCkdYR7CoCMBh4LV5BRlOmYgdvCHhlffR+qXyXdu1s9l8YUM49pik9FDr+R+gO0zW/Va35nZiRkYgqg46BxoPDiVWTMqD0ryHCLdZ662MBPxdjLCxAAFJVYbRtvnYtfNd9sHvJdVJskl/vT+I99ynKFAD/QOk01IDAvK5xnxeTDIqWhN+C84TCih+UvqA/sCjC7tX36p4APhYsK8g+eVC2XwlsE3WOelJ8UHqZdFpr3V6BT789IipCFcL/SOp71fzBYrA3oe6U54tnhpiEh4YkjEOVnaHQsGfC19WL6uD/LxXXKTU9s07KXQZqCHOLeGZ6iXgGcwhq1V3NTmU9JSqjFX4AXOvf1qbDRrJHoxuXII6biLeGgIjojcSWzqKosd7C6dU26ib/FhRlKHQ7sUyWW69noXAmdhR4XnYScVpoe1zSTdI8/inrFTQBe+xe2HzFZrSfpZuZtZAxizqJ3YoMkJ+YUKTGso3DJdb76XX+8xLYJok5dkoaWQdl321gc191z3O+blJm0FqRTAU8rikZFuABoe332XvHvbY9qGyco5MnjiCMnI2QktOaJKYqtHfEi9ba6c39yRE0JXY3A0hbVg9ixWo8cEly4HALbPFj1FgKS/86MiksFoICzu6n26HJSrkdq4qf6JZ4kWWPvJBylWCdSKjUtZnFHNfV6TH9mhB6Iz41XUVaU8teV2e9bNVukW37aDlhiFY9ScA5iigiFhgD/+9r3evLCbw9rvOif5ojlQeTOpSvmESgvKrEt/XG2tft6aP8aA+tIeMyhkIcUD5bl2PmaAZr5mmRZSpe7VMrR0c4tyf7FZ8DMvFA31bO976ZsaKmZ54lmQOXEphGnH2jfa34uYvIxNgj6iP8NQ7PH2kwgT+kTG1XiV+8ZN5m4WXPYchaBVHURJU2tya2FRcEZPIl4d/QEsIttZWqmqJ4nVabQpwzoAini7BwvFnK2tl46rP7Aw3kHdItUjz1SFlTMVtAYGFihmG3XRRX0007Qqo0iiVRFX4ElfMW44PTVMX2uMeuFqcbovufxqBzpOOq47Mqv2DMHdvt6lX71AvtGyEr/DgTRQlPk1Z4W5Rd2VxOWRJTVkphP4gyMiTNFNMEwfQS5T/WvMjwvDWz1asHp/Ckm6UEqQyvgrckwp3Oi9yB6wr7qwruGVsogzUCQX9Ks1FoVnpY3VeXVMROlEZHPC8wrSIpFBUF6PUV5xDZRcwXwdq31LA6rC6qvarhrX6zaLtexRHRJt427NL6iAnoF4El6zHHPMFFlkwTURhTllKVTy5KjULvOKEt/CBjE0IFBvcd6fLb7M9mxbG8DravsbOvKLAHsze4j7/UyLrT7d8L7bD6bgjeFZciNy5kONJAQEeAS3JNCU1MSlJFRT5bNd4qIB9+ElkFG/gn6+PerNPaybbBfrtgt3m11rVxuDS998OEzJbW3eEB7qP6XwfUE6EfayrfM7c7t0GyRY1HO0fBRDZAvjmPMeonGx13EVsFJPkx7d7hg9duzuXGIMFJvXu7w7scvnDCm8hs0KPZ+OMY7636XAbKEaAciiY9L3U2/zuwP25BMEH4Ptw6/jSMLcUk7BpQEEUFIfo57+LkbNsf0znM7sZkw7XB68ECxObHeM2I1N/cOuZP8M/6ZgXFD5oZmiKAKhExHTZ9ORs77Tr2OEk1BjBWKXEhlRgJDxcFD/s88evnZN/n16zR48ytySHISMgfypTNidLX2EngpOim8Qj7gATFDZAWnB6uJZArFjAgM5g0dzTAMoIv2yrwJPIdGRaiDdIE7vs48/bqZuPB3DrX+dId0LnO1c5u0HPTzNdU3d3jNOsd81r7qQPNC4UTlhrMIPYl8CmeLOwt1C1aLIspgSVdIEkadxMdDHQEu/wr9f/tb+er4d7cLNmv1njVjNXp1oHZPN384Zrn5+2y9MT75QLgCX0QjBbdG0kgsSP8JRwnCifKJWkj/B+gG3oWshB5Cv4Ddv0S9wTxeuue5pPid99e3VjcaNyL3bbf1eLM5nzrvPBk9kb8MwL/B3sNgBLmFo4aXR1BHy4gHiAXHyEdURq+FoYSzQ24CG8DHv7t+AP0hu+X61To0uUk5FPjY+NP5A/mkejA64DvsvM0+OH8lQEsBoIKdg7sEckU+xZyGCcZFhlEGLkWhBS6EXIOyArbBsgCsv64+vf2jPOR8BvuOuz76mPqduov64bsbe7T8KPzxPYe+pX9CwFpBJQHcwrzDAEPjxCWEQ4S+BFYETUQmw6ZDEEKqAfjBAkCMv9y/N75i/eI9eTzqPLc8YPxnfEm8hbzZPQC9uL38/kj/GD+lwC4ArQEegb/BzkJIAqxCukKygpZCpsJmQheB/UFbQTSAjIBnP8Z/rb8fvt4+qn5F/nD+Kz40fgs+bn5cPpI+zn8Ov0//kL/OAAbAeQBjgIVA3cDswPKA74DkwNMA/AChAINApMBGwGpAEQA7/+s/33/Yv9b/2b/gf+p/9j/CgA8AGkAiwCgAKQAlQByADoA8P+T/yn/tP46/sH9Tv3n/JT8WPw5/Dv8Yvyt/B/9tf1s/kH/LAApAS4CMgMuBBUF4QWHBgAHRgdSByIHtAYIBiIFBgS6AkkBvv8h/oH87fpw+Rn49PYN9m71HvUk9YH1NvZA95v4PPoa/Cf+UwCQAskE7wbtCLMKMgxaDSAOfA5mDt0N4gx5C6wJhgcWBW0Cov/G/PL5Pfe89IbyrfBD71Xu7e0T7sfuB/DM8Qv0tfa2+fn8ZADfA0wHkgqUDTsQbhIbFDEVphVyFZUUERPwEEAOFAuCB6UDnP+D+3z3p/Mi8AvtfeqN6E3ny+YM5xPo2elU7HTvIvND97j7XgAVBbUJGg4gEqcVkRjEGi4cvxxxHEMbOxlnFtkSqw78CfAErf9a+iL1LvCm66/naeTy4V7gvd8W4Gvhs+Pf5trqhu/C9GT6QwAxBgEMgxGMFvMalB5QIQ8jwSNdI+MhXB/ZG3MXSRKDDEwG0/9K+eXy1exL53Tid95324zZydg32dXamd1x4UHm5us28gD5EQA0By8OyxTVGhwgdCS5J9AppSovKm4obiVCIQoc6xUUD7cHDgBV+MbwnukV41/drNgh1d7S9tF00lbUkdcO3K3hROih7473zP8bCD0Q8Bf4HhwlKir6LWowZTHhMN8uayueJpogjRmrETEJXwB798jui+YG33TYC9P2zlnMScvTy/TNoNG71iLdo+QH7Q32cf/oCCoS7xrxIvAptC8ONNk2/TdvNzA1TjHmKx8lKx1IFLcKxAC89uzsoOMj27jTms37yALGyMRaxbbHy8t+0aTYCOFp6oH0Av+ZCfYTxh2+JpQuDDXvORY9Zj7SPVs7EzcXMZQpwyDmFkkMPQEZ9jLr3eBt1yzPXMg0w9+/eL4Ov5/BGcZbzDnUdd3L5+vygP4vCp4VdCBbKgUzLjqaPx5Dm0QFRFxBszwrNvUtTySDGeINyAGR9ZvpRt7p09bKV8OnvfW5X7j1uLW7jMBXx+PP79kw5U7x7f2pCiIX9iLHLUA3FT8JRepIl0oCSixHKkIeOz8yzicdHIMPYwIk9Sno2tuX0LnGjr5XuEi0grIVs/+1LLt2wqfLedaZ4qvvSf0JC4IYSyX+MEA7v0M4SnZOVVDFT8hMckfrP2w2OyuvHikRDwPR9NvmnNl6zdbCBLpKs96u5axxrYCw/LW+vYrHFtMK4APulfxOC70Zcif/MwQ/KEgjT71Tz1VIVSlSiEyORHk6ky45IdESygOZ9LPljdeVyjK/vbWCrrqpjqcQqD6rArExuY7Dys+H3Vvs1Pt5C9MaaSnINohCTEzHU7xYAluHWktXZlEDSWE+0jG2I3kUkQR69LDkrtXpx867vLEEquKkgaL1oj2mQqzWtLm/mMwR27PqB/uMC8QbMCtXOctFKVAfWG1d6V99XylcB1ZETSJC9TQkJiAWZAV19NLj/9N4xa24Ba7TpVigwp0lnoKhwKewsA+8hcms2A7pLvqFC48cxiyrO8pIu1MoXM5hf2QlZMBgaFpOUbZF+TeAKMIXQgaH9BnjgtJCw9G1maryoSGcVZmlmRGdgaPDrJK4k8Za1m/nTPlnCzUdKi7CPYJLAFffX9tlwmh8aAplhV4dVRpJ2TrGKl4ZJwew9IbiNtFKwTyze6dknj+YPZV4le+YiJ8TqUa1xcMf1NflY/gzC7cdXS+bP/RN9llCY5BprWx+bARpWGKtWEtMkz31LPEaEwjv9BbiHdCPv++wrqQtm7eUgJGikR6V2pukpTCyH8H+0UnkdffqChQeXTA3QR1Qm1xOZutsPXAocKts4GX6W0ZPJEAJL3kcBAlC9crhNc8TvuuuMqJNmIqRHo4mjqOReph5olOvpL74z8jigvaNCk4eLDGTQvtR7V4Baepvb3N1c/pvF2kCXwZSiEL/MPMd+Amp9aHhf87WvDGtCqDHlbuOG4sHi4CObJWWn7GsWLwRzlXhjvUdCmYeyjGxQ5BT62BZa4lyQXZkdu9y/GvAYYlUvUTWMl4f7Qoh9pvh+s3Yu8KrNp6dk0yMeohJiLmLspL+nE6qPLpMzPPfmfSdCVweNjKPRNlUlGJVbcd0sXjyeId1i24xZMtWv0aJNLYg4Aup9rXhps0Zu5+quJzQkT6KPYbthVGJT5Czmi2oU7iryqXep/MNCTIecjIvRdZV52PzbqN2vHoce8B3wXBUZstYjUgXNvoh0QxA9+7hgc2ZusepkJtikJSIZYT1g0mHRo65mE+mobYwyWzdufJvCOkdfzKQRYlW5GQycBt4YHzgfJZ5nHImaIVaI0p+NycjvA3k90bijM1WujqpvppSj0+H9IJkgqOFmYwRl7mkKLXex0vc0PHGB4MdXjK0RfBWi2UTcS55nX0+fgp7GnSjafdbf0u7ODwkoQ6T+LvixM1RuvmoQpqhjm6G64E7gWKES4u+lWuj6bO3xkTb8PASBwAdDzKbRQxX22WUcdx5cn4zfxh8OXXLaiBdoEzMOTUlfA9L+UvjKc6IugGpHZpPjvOFS4F6gIeDW4rBlGii57K9xVnaGvBWBmMclTFHRd9W1mW2cSR63n6/f8B8+HWca/1dgk2uOhImTRAK+vXjuM76ulOpTZpcjt6FE4EjgBODzYkclLKhJLLyxIvZT++UBa4b8TC4RGlWfGV6cQd64X7hfwF9VnYVbIxeJk5hO88mERHQ+rbkcc+lu+2p0ZrIji2GRYE1gAWDoInRk0qhobFYxN7Yku7MBOEaJDDwQ6xVzWTgcIV5e36af9p8UnYzbM1eiE7iO2wnxhGY+43lUdCJvM2qqZuQj+KG4IGygGCD1YnfkzChYLHxw1LY5e0DBP8ZMS/xQqhUzWPpb594rH3pfkx863X3a75eqE4wPOcnaxJj/HnmV9GivfOr0py1kPmH44KXgSKEbYpJlGehYrG9w+nXSu04AwsZGS69QWFTe2KXblZ3dXzOfVZ7InVga19ehE5JPD4o/RIt/XbngdLwvlutS540knOJTITmgkuFaIsNle6hqLG+w6XXwexuAgUY3ixWQNhR2mDrbKt12XpMfPp59nNvaq9dHE4tPG8oexP1/YPozNNwwAWvE6AMlE6LHIachNuGxYwtlseiMrL2w4fXTuyoAfEWgyu+Pg5Q7V7naqFz13hiejd4aHIiaa5cb03aO3ko5BO6/p7pNtUfwu6wJqI7loiNT4i5htCIhI6nl/GjArNkxJDX8evmANAVCir4PAhOtVyOaDlxcnYTeBB2eXB7Z1xbfUxQO1woNRR4/8Xqvdb8wxKzgqS9mB2Q5Io6iSmLo5B7mWulF7QKxcLXq+srAKMUdSgGO8ZLNVrjZXZurXNhdYVzKm56ZblZRUuOOhYobhQuAPbrX9gDxnC1JaeRmw2T2Y0djOWNIZOomzancbXpxR3Yf+t5/28TxybqOExJcFfnYlpriXBNcppwfWshY8ZXyEmTOaYnjRTcAC7tGdozyAW4DKq0nlSWK5FgjwCR/JUtnlGpELcAx6LYbuvR/jQSAiWoNp5GaVSfX+lnCm3bbk9tdGhwYIRVBkhgOAsnkBR/AWvu6duHys26M60hou6Z1pQAk3mUM5kIobqr9LhPyFLZeOs1/vQQKCNCNL1DI1ENXCdkM2kNa6hpEGVqXfRSAEb0NkYmeBQVAqzvy93+zMW9lrDXpdmd2Jj7lk2Yw5w4pHCuHLvXyS3an+um/bMPPSG7Ma5Aok01WBVgB2XnZqhlVWESWhhQt0NRNVUlQhScAu7wvt+Uz+rAM7TQqRCiLZ1Mm3mcqaC5p3Kxhr2WyzPb5Osm/XEOQx8XL3M96kkbVLlbimBsYlJhRV1oVvFMLEF1Mzkk7xMUAy/yv+FG0jnEBrgKrpCm0aHwn/mg4qSLq760MsCNzWXcR+y2/DENPB1YLBE6/UXCTxZXwVugXalc41hvUoFJYD5jMfIifBN8A23zy+MR1a7HC7yAslWrwKbjpMqla6mpr1G4HsO6z8LdyexY/PYLKxuBKYo24UEwSzFSrlaHWLFXM1QsTstFVTscL38h6xLQA6b04OXy10bLPcAtt1qw9ashqueqQa4RtCm8R8Yc0krfau0N/MAKExmXJuMymT1oRg1NV1EmU25SOU+gSdJBDTifLOIfOhISBNj1++fl2vvOmsQOvJq1bbGlr02wX7PAuEPArcmz1P3gK+7V+5EJ9habIx8vKjlvQbFHwEuATeZM+EnQRJg9ijTvKRoeaRE+BAL3Gero3czSG8kewRG7Ibdrtfi1wrixvZ3ETc1819niC++z+20I1xSSIEMrlzRKPCBC70WbRxtHdES+PyA5zzANJykceBBWBCH4OOz34LTWvs1YxrrADr1tu+G7Zb7iwjLJI9F22t7kDPCn+1MHuRJ+HVEn5i/9NmA86D99QRNBsz5wOm003Sz8IxAaaA9XBDX5Vu4P5K/afdK3y5HGLsOnwQbCRMRNyADOL9We3QvnLPGx+0cGnRBjGk4jGiuMMXU2sTkpO9Q6uDjoNIQvuSi9IM8XOA5BBDr6b/At57neVdc30Y7Me8kTyF/IWcrvzQPTa9nz4F/pbPLS+0gFhg5DFz4fOCb+K2YwTzOlNGI0iTIsL2gqZSRSHWkV6QwUBDH7g/JN6s7iQNzT1q7S8c+tzunOoNDE0zfY1t1z5NjryvML/FoEdwwjFCQbRSFXJjcqxyz4LcItKyxBKR4l5B++Gd4SewvPAxf8jfRt7evmOuGE3OvYidZt1Z3VFNfF2ZjdbOIa6HTuR/Vc/HwDcQoFEQUXRBycIO0jICYmJ/smoiUqI6gfOhsEFjEQ8AlyA+z8jfaJ8AzrP+ZH4kDfPt1O3HbcsN3w3yLjKufn6zLx4PbF/LECdwjsDeQSPBfSGo8dXx82IBIg9h7uHAwaahYmEmMNSAj+Aq79gfie8yzvS+sW6KblCuRM427jbeQ95s/oC+zV7w/0lvhG/fkBiwbaCsUOLxL/FCIXiRgtGQwZKhiQFk4UeREoDncKhQZxAlz+Zfqq9kjzV/Dt7Rns5+pf6n/qRuup7JzuC/Hj8wr3Z/rf/VQBrwTUB6wKIw0nD6sQpRESEvARRBEXEHMOagwMCm4HpgTMAfb+Ofyq+V33YfXF85Py0PGB8aTxNvIu84P0KPYM+CD6UvyP/sUA5ALcBJ0GHAhPCTAKuQrqCsQKTAqHCYAIQQfWBUsErwIQAXr/+v2b/Gb7ZPqb+Q75v/it+Nb4NvnH+YH6XPtO/E/9Vf5X/0wALQHzAZsCHwN9A7YDygO7A44DRQPnAnoCAwKJAREBoAA8AOn/p/96/2H/W/9o/4T/rP/c/w4AQABsAI4AoQCkAJMAbgA1AOn/i/8f/6r+MP63/UX94PyO/FT8OPw9/Gb8tfwq/cP9ff5U/0EAPgFEAkgDQgQoBfAFkwYIB0kHUAcbB6gG9wUMBewDnQIpAZz//v1f/Mz6Uvn/99/2/fVk9Rz1KPWM9Un2Wve7+GL6RPxV/oMAvwL4BBsHFQnWCk4Mbw0sDn4OXw7MDcgMVwuBCVUH3wQzAmX/ify3+QX3ivRb8orwKu9H7uvtHO7c7ifw9/FA9PL2+vlB/a4AKQSUB9UK0Q1uEJcSOBRCFagVZhV7FOkSvBABDssKMgdQA0X/LPso91jz3O/P7E3qa+g758nmG+cx6Afqkey973bzn/ca/MMAeQUVCnQOcRLrFccY6hpCHMEcYRwgGwcZIhaFEkwOlAmBBDv/6fm19MjvS+ti5y3kx+FH4LvfKeCS4e7jLec36/HvNvXg+sEArwZ6DPQR8RZJG9gefyEoI8MjSCO3IRsfhBsMF9QRAgzDBUj/wPhf8lns3OYW4i3eQ9tx2cfYTtkF2+HdzuGy5mfsw/KV+aoAywfADlIVThuCIMQk8SfuKagqFio6KCAl3SCQG2AVew4WB2r/svcp8AvpkuLw3FTY5NS90vPRj9KO1OXXe9ww4troRvA7+HwAywjmEI0YhB+TJYgqPC6OMGkxxTCjLhErKSYNIOwY+xB3CKL/v/YT7uPlcN7116bSsM4zzEXL8cs0zv/RONe43U7lwu3T9joAsAnrEqIbkSN4Kh8wWTQCNwI4TzftNOkwYiuAJHYcgRPmCe//6PUf7OLiedoo0yjNq8jWxcPEe8X8xzbMCdJM2cfhO+te9eT/eQrOFI8ecSctL4Q1RDpFPWw+sD0RO6M2hTDkKPofChZgC08ALfVP6grgsdaMzt7H28Kuv3G+Mr/swY3G9Mzx1Ejesujf83r/JguMFlEhISuuM7M6+D9SQ6NE4EMMQTk8izU1LXMjkhjkDMMAjvSi6F7dGdMmysvCRL2+uVa4G7kJvAvB/cer0NXaK+ZY8v3+twsmGOgjny74N6c/cEUjSaFK3EnWRqZBcjpuMeAmFxtvDkgBC/Qa597atc/5xfW967cMtHeyPLNYtrS7KcN/zHDXqOPJ8G7+LQybGVAm6DEIPF5EqUq1TmFQnU9tTOZGMz+MNTwqlx0AEN8Bo/O45Y3Yh8wHwl+51LKbrtismq3esIy2fL5wyB7ULOE279D9hwzqGooo+zTaP9NInU8CVN5VH1XJUfRLy0OLOYMtDiCVEYUCV/N85GvWkclUvgy1A65yqX6nOqigq5qx+rmCxOLQut6g7SL9xgwTHJQq1DdtQwNNSlQHWRNbXVrnVspQNUhnPbMweiIrEzoDJfNm43rU1cbiugCxfKmUpG+iH6OjpuCsqbW6wL/NVdwK7Gf86gwWHWwsczq+RutQq1i+XfxfUl/CW2VVbUwbQcgz2CTAFPsDDfN34rvSVMS0tz2tQqUEoK2dUJ7soWWojLEbvbnK/9l26qD79gzzHRIu1jzKSYhUvFwlYpZk+mNVYMBZblCkRL42JSdSFsgEDvOt4S7REMLLtMapWaHHmz2Z0Jl+nSukp62oudTHvNfm6M766AypHoYv+z6PTNhXfGA3ZttoUmidZNddNVT/R5I5XinfF54FJ/MK4dPPCsApsp6mxJ3glyOVopVdmTig/qlnthHFjtVd5/T5www6H8cw4kAMT9ha52PyaclsVGyVaKdhvlcnS0E8gCtlGXwGWPOM4KzOQ77Rr8ejhJpSlGKRzJGOlY6clqZZs3bCeNPc5RP5iAylH9UxiUJAUYZd+2ZTbV1w/m86bCplBVsZTsg+iS3hGmAHnvMz4LfNu7zCrUKhnZcfkf2NT44UkjKZcaODsATAfdFm5C34NwzsH7Ay8UMpU+FftWlXcJJzTXOIb19oCF7SUCRBdi9QHEgI+PP+3/bMc7v+qxGfEZVLjveKL4vyjiaWkqDorb+9n8/94kP30wsPIFgzGUXHVOdhE2z7cmh2PXZ8ckFrwmBPU1FDRDGxHTIJZvTt32fMa7qHqjad4JLXi1OIb4gsjG6T/p2Kq6q74s2k4Vj2XAsPIM4zAUYYVphjFW4+ddp4zXgUdc5tMGONVU5F8DIBHx0K5fT+3wnMo7lcqbGbDZHFiRKGEYbDiQ2Rtpttqce5R8xd4G711QrtHxM0qUYeV/JkuW8ed+h6+HpNdwNwUWWJVxdHeDQ/IAYLdfUw4N3LG7l9qIKamY8XiDeEGIS6hwSPvZmSpxm40soq34b0PgqsHyc0EUfWV/Rl/XCaeJB8v3wled5xIWdBWalI2zVnIewLEvaB4OHL07jqp6uZhI7OhsOChIIUhleNFpj+paK2g8kO3qPzmglLHws0OkdDWKBm4nGxedB9H36aelxznmiyWgNKFDd3IswMvPbx4BTMyLijpyuZz43phbeBWIHShAiMw5axpGW1X8gK3cby6gjMHsEzJkdkWPVmZ3Jjeqh+Fn+qe310xmnaWyNLIzhvI6UNcfd94XXM+7iopwGZeo1rhROBlYD0gxeLxpWuo2S0Zscg3PLxMQgyHkoz1UY6WPNmjXKuehd/pX9UfD11mGq3XAZMBjlKJHUOL/gl4gLNa7n3py6ZhI1ThdmAO4B+g4aKH5X2oqCzmsZT2yjxbwd+HacySEbGV5tmU3KTehx/yn+XfJ51E2tJXatMujkJJTkP9Pjm4rrNFbqPqLGZ7Y2ghQmBS4Bug1eK0ZSMohuz/8Wk2mrwpwaxHNsxgUUKV+5lu3EUerh+hX90fJx1NGuMXQ9NPTqoJfAPvvm+45vO+LpvqYeatY5ShqGBxYDFg4mK3ZRvoteylMUV2rrv2wXOG+YwgUQGVu5kxXAveex91n7oezl1/GqCXTNNjzomJpgQjPqs5KLPE7yVqrGb2Y9oh6GCqIGEhB6LQpWiotSyW8Wo2RvvDQXWGswvS0O+VJxjc2/nd7d8v332enN0amonXRRNrTqCJi8RW/ut5c/QY70ArCudWJHiiAmE9IKqhRSMApYkoxSzV8Ve2Y3uPgTMGY0u4UEyU/phx209dhx7P3ydeUxzfWl9XLJMmDq6JrMRKfzA5h/S576srfSeMZO8iteFqIQ2h22NG5f2o5izh8U42RLucQOxGCwtREBlUQpgwmszdBx5WHred8NxNmiDWw1MTDrMJiQS9fzi55DTnMCZrwqhYZX2jAmIwoYniSaPj5gYpWC07sU52aztpwKIF6wreD5aT89dZ2nLcbl2DHi7ddlvlWY4WiNLyzm4Jn4SvP0R6R/Vf8LDsWuj5peMj56KQIl8iz+RXJqLpmy1isZh2V3t4gFTFg8qfzwSTUpbuWYHb/RzXHU1c5BtnGSeWPVJEzl8JsISfv5M6srWjsQntBKmvZp9kpKNIYwzjreTgpxNqLy2Xsex2SbtJQEUFVcoWjqSSoBYumPqa9FwS3JNcOpqSmK0VoJIIzgYJuwSN/+P647Yx8bDtv+o453FleOQYY9KkYyW/55eqlC4acgq2gjtcADNE4cmDjjbR3JVbWB3aFJt224Hbedno198VMxG/TaLJf0S5//Z7GnaJsmUuSysVaFimY+UAJO+lLyZ0aG9rCm6q8nM2gTtx/+AEqIknjXxRCVS1lyxZHppD2tlaYpkplz3UdJEnzXTJPMSigAo7lncqMuWvJivEKVQnZGY+JaOmEWd+KRor0O8JcuY2xztKP8wEakiCzPXQZxO+FicYE5l62ZpZdZgVlkmT5ZCCjTyI84SIgF571reSs7Hvz6zEKmLoeecR5u1nCShcKhesqC+1syO3FDtmP7fD6AgWTCRPtpK11Q8XNBgcmIYYc1ctlULTBlAPjLmIosSqwHK8GrgCtEiwxq3Ua0Qpo2h6Z8woValN6ydtT7BvM6v3aLtF/6ODokejC0iO+RGeFCUVwRcp11zXHNYyFGoSFw9PDCwISsSJAIa8ofi5NOkxiq7z7HZqn2m26T9pdepS7AjuRrE2dD73hHupv1ADWccpiqON71C3UuqUu9WkFiAV8tTj00ARWA6BS5QIKwRjAJm863k1dZJymi/hbbkr7WrGKoWq6WuqLTuvDTHKtNw4J/uR/33Cz0aqifYM2k+DEeATZZRL1NCUthODkkUQSg3myvGHg8R4QKs9Nvm2tkOztDDb7sqtS+xm694sLyzTLn6wIrKrtUP4kvv+/y0Cg0YnSQFMO05CUIeSPxLik2+TJ9JSUToPLYz/SgTHVMQIwPq9Q3p79zv0V/IicCouue2YLUethe5Mr5GxRjOZNjX4xbww/x6CdoVgSEYLE012TyGQihGpkf3RiNEQz9+OAwwLyY2G3gPUQMf90DrEeDn1RDNzsVZwNe8YrsDvLK+V8PNyd7RStvH5QHxofxKCKYTWh4VKI0wgTe+PB1Ah0H0QGo+ADrbMywsMSMzGX4OaQNJ+HTtPeP02d7ROcs3xvvCnMEjwonEt8iMztfVXt7e5wryk/wnB3QRKhsAJLErBTLLNuI5Mzu4Onc4hDQBLxkoByAIF2YNawNm+aTvb+YQ3sXWxdA9zE3JCch5yJbKTs6A0wLan+Eb6jLznfwRBkYP9hfdH8AmaiyzMHszrzRKNFAy1C70KdcjsRy5FC8MVgN1+s7xpek54sDbbdZm0sfPo87/ztbQFtSk2FreCuV97Hj0vfwKBSANwBSwG7whtiZ6Ku4sAS6uLfkr9Ci4JGkfMhlFEtoKKgN0+/Hz2+xp5szgLNys2GXWZNWw1ULXDNr23d7inOgC79z19fwTBAILixF9F6oc7SAnJEEmLifqJnkl6SJSH9IajRWvD2cJ5wJi/An2DvCe6uLl/eEL3x/dR9yG3NbdK+Bw44jnU+yo8V33RP0uA+8IWw5HE5AXFRu/HXofPSADINMeuBzFGRUWxRH5DNkHjAI+/RX4O/PT7v/q2+d85fLjRuN744zkbeYO6VfsLPBt9Pn4q/1cAuoGMgsTD3ESMxVHF54YMhkAGQ4YZhYXFDYR3A0lCi4GGQIG/hP6XvYF8x7wwO3569bqW+qK6l7rzuzL7kTxI/RQ97H6Kf6dAfUEFAjlClMNTA/FELQRFBLnETAR+A9MDjoM1gk0B2oEjwG6/gD8dvkv9zv1qPN+8sXxgPGs8UfyR/Ok9E72N/hO+oL8v/70ABADAwXABjkIZQk+CsAK6gq9Cj4KdAloCCQHtgUpBI0C7QBZ/9v9f/xP+1H6jfkF+bv4rvjc+EH51fmS+m/7Y/xl/Wv+bP9fAD4BAwKnAigDgwO5A8oDuQOJAz4D3wJwAvkBfwEHAZgANQDj/6P/d/9f/1z/av+H/7D/4f8TAEQAbwCQAKIAowCRAGoALwDi/4L/Fv+g/ib+rf08/dj8iPxR/Df8P/xs/L78Nf3R/Y7+Z/9VAFQBWQJdA1YEOgX/BZ8GEAdMB04HFAebBuYF9gTRA38CCQF6/9z9Pfyr+jT55PfJ9u71W/UZ9S31mfVc9nX32/iI+m/8gv6yAO8CJwVHBz0J+QpqDIINNw6ADlcOuw2tDDMLVgkjB6gE+AEo/0z8fPnO9lj0MPJp8BLvOu7q7Sfu8u5J8CTydvQv9z36if34AHIE2wcYCw0OoRDAElQUUBWpFVkVXxTBEocQwA2CCuIG+wLt/tX61PYK85bvlOwf6kvoKufI5irnUeg36s/sCPDL8/z3fPwnAd0FdQrNDsASLxb8GA8bVRzCHE4c+xrQGNsVMRLrDSoJEgTJ/nj5SfRk7/LqFufx457hMuC63z7gu+Er5Hvnlutd8Kz1XPtAAS0H8gxjElQXnRsZH60hQCPDIzEjiSHXHiwboxZdEYELOwW8/jX42/He62/muuHl3RHbV9nG2GfZN9sq3i7iJOfp7FDzK/pCAWIIUQ/YFcUb5yATJSgoCiqoKvspBCjQJHUgFBvTFOENdAbF/g73jO966BHig9z/16nUn9Ly0azSyNQ72OvctuJy6evw6fguAXsJjxEqGQ8gCCbkKnsurjBqMaYwZS61KrIlfh9KGEsQvQfk/gP2X+085dvdd9dE0mzOD8xEyxLMds5h0rfXUN775X7umfcEAXgKqxNUHC8k/SqIMKE0JzcEOC03pzSCMNwq3yO/G7oSFAkZ/xT1VOsm4tLZmtK5zF7IrsXAxJ/FRsijzJfS9tmI4g3sPPbFAFkLpBVWHyIowi/6NZU6cD1vPoo9xDowNvAvMSgvHywVdwpi/0H0bek53/bV7s1ix4XCgL9uvlm/PMIFx5DNrNUd35rp1PRyAB0MeRctIuUrUzQ1O1NAgkOnRLhDuEC8O+k0cSyVIp8X5Au//4vzqud43E3SeclDwuW8i7lRuEW5YLyNwabId9G82yjnYvMMAMUMKRnYJHUvrTg2QNRFWUmnSrFJfUYgQcI5mzDvJREaWg0tAPLyDebk2dfOPMVgvYO307NwsmiztLY/vN7DWs1p2Ljk6fGU/1ANsxpUJ9AyzDz5RBZL8E5oUHBPDUxXRnc+qjQ6KX0c1g6vAHXyl+SA15fLO8G+uGOyXa7QrMetQLEgtz2/Wcko1U/iavAK/74NFhygKfM1rUB6SRNQQ1TnVfFUZFFcSwRDmzhxLOIeVxBBARXyR+NM1ZHIer1ftImtL6l0p2ioB6w2sse6ecX80e/f5+5w/hEOUh28K904T0S2TchUTVkfWy1aflYrUGNHaTyRLz0h2xHjAdDxHuJJ08TF+rlHsPmoSqRhok+jDqeErYC2vsHozprdY+3H/UgOZx6lLYw7rUepUTJZCl4LYCJfVVu/VJFLEUCXMosjXxOSAqbxHeF50TTDvrZ5rLektZ+dnYCeWqIPqWyyKr7wy1Tb3+sS/WUOVR9cL/09xkpRVUxddmKnZMpj5V8TWYlPj0OANcgl4RRNA5bxQ+Dcz+HAyLP4qMagc5sqmQCa753bpJCuw7oYyR/ZX+pR/GgOGyDfMDBAmE2rWBRhjmbvaCFoKmQlXUlT30ZIOPQnYBYUBKDxkN9zzs6+G7HGpSidhpcNldOV0ZntoO+qi7dhxv/W5OiF+1IOuyAuMiRCIVC1W4ZkT2rgbCRsH2jvYMtW/knsOgkq1xfjBMHxBN8+zfq8t67louGZ85NJkfuRBJZHnY2nhrTQw/XUcOey+iUONCFJM9hDX1JtXqFntW12cM9vw2tvZAxa6ExqPQcsRxm6Bfrxnt49zGa7nqxXoPOWu5DijX6OjJLumW2kt7FowQTTBebY+eENhyExNEtFU1TQYGJqvXCvcx9zEG+gZwldmk+9P+otqxqXBknyXd5vyxO60KoenmCU4o3Zil2La4/mlpOhI68rvzDRp+T5+IgNtiHkNH5G+VXeYsdsZ3OHdhB2BHKAar5fEVLjQa8vAxx3B6zyQd7WygK5UKk7nCmSaYsxiJuIpYwwlAOfyqwcvXrPV+MY+BsNwCFkNW5HU1eWZM9urnX9eKF4m3QLbSliSlTZQ1QxSx1ZCCLzSd5wyjK4HaivmlCQU4nuhTyGPIrQkb6csao/u+bNF+I295wMpyGxNR5IYFj3ZXhwk3cOe8561XY/b0dkQ1adRdcygh47Carzct48yqK3N6d6mdeOoIcPhEGEM4jIj8ea2qiVuXbM6uBU9g0MbCHMNY5IH1n/ZsJxE3m5fJd8rXgZcRZm+FcsRzQ0pB8bCkH0vt45ylO3nqadmL2NU4aYgquCi4YcjiGZSKchuCvL0t929W4LESG2Nb1IkVmwZ6xyLnr8ffl9I3qYcpJnZ1mESGs1sSD3Cub0KN9nykO3U6YZmASNa4WJgX2BR4XLjM+X/KXmtgnK0d6d9MIKlyBwNa1ItlkJaDVz43rXfvN+NXu6c7toj1qiSXg2piHNC5j1sd/EynO3U6bsl6uM6YTjgLiAaITZi9CW+aTltRHJ6d3L8wsK/x/8NF9IkFkKaF1zMXtJf4R/4Xt8dI9pbVuFSlo3gSKbDFT2V+BPy9+3oKYWmLKMzoSmgFuA74NHiyiWQKQgtUbIHN0B80oJTB9bNNRHHlm1ZyZzGXtRf6t/J3zfdAtqAFwrSw84QCNgDRn3F+EGzIi4NqeWmBmNGYXTgGmA3YMVi9iV06OZtKjHa9xC8oIIfx6PMw1HY1gKZ5BynHrvfml/BnzgdC9qR1yTS5U44SMZDuX38OHnzGy5Fqhsmd+NyYVpgeCAMYREi+CVs6NRtDrH2tuQ8bQHmh2ZMg1GYFcKZptxuXklfr1+fnuAdPtpQFy6S+s4YyTEDrX44eLxzYi6PKmVmgKP3oZngsCB7YTUi0GW4aNKtP3GaNvs8OIGnxx8MdZEFla4ZEpwcnjzfKl9j3q/c21p6luhSw45xCRgD4j55uMhz9u7qaoQnIGQVojNgwmDD4bHjPyWXqSFtPPGGNtZ8A4GkBs5MGhDiFQUY51uyXZZeyx8OnmccoZoRltFS/84AiXqD1z6/uR10GK9WKzbnVuSMIqZhbqEl4cajhCYKqUCtRzH7NrX7zoFcBrTLsdBuFIiYZdsv3RbeUd6f3cYcUVnU1qnSrs4HCViEDD7J+bs0Ry/Sa70n4yUaozKh9GGhInOj32ZRabCtXrH5Npp72gEPxlNLfU/p1DjXjtqVnL4dv53YHU0b6tlEFnFSUM4EiXGEAD8XueC0wbBeLBYohOXAY9dikyJ1YvikUObr6fFtg3IAtsQ75kDARinK/Q9Wk5bXIpnkW81dFF13nLxbLljflehSJU34CQUEcz8o+g21R3D4rIEpe6Z85FRjSuMh45UlGGdaakLuNbIR9vN7tECtxbmKcg700uLWYdkc2wScUJy+29Qam9hnlU5R7E2iCRLEZH98ekF117FhrX2pxidPZWikGmPmpEil9afcKuUudXJs9uj7g8CZRULKHI5FEl4VjZh/miTbdVuumxUZ9BecFOORZc1CCRpEU7+SOvr2MfHX7grq4+g3JhNlASTCpVLmqCixK1huwvLSNyR7lcBCxQZJvY2IUYjU5pdNmW8aQxrHGn/Y9xb9VChQ0Y0XyNuEQH/pOzo2lXKa7uerk+kzZxQmPuW1JjNnb2lZLBvvXbMBd2a7qoArBITJFg0/UKST7dZHWGPZepmJWVSYJZYME5yQcAyjSJYEaj/BO733ATNpr5MslWoC6GnnEib9pykoSupTrO+vxjO7N2+7goASxH7IZkxqz/HS49VuVwQYXJi2WBRXABVIUsDPwMxkiEmEUEAZu8X39LPDcIztp2slKVNoeifbaHOpeisgbZNwu/P+9797nj/6Q/UH70uMDzHRyhRDVhDXKpdOVz+Vx1Ry0dUPBIvbSDYEMwAx/BE4bvSnMVMuiKxYqpAptikNaZIqvGw+rkaxfrRNeBa7/T+iQ6hHcgrjziVQ4ZMHlMsV5NYS1deU+9MMERoOe0sHx9tEEcBJvJ847zVT8mWvuG1cq95qxOqSasOr0S1t70kyDnUl+HU74L+LQ1lG7woyzQ1P6xH703RUTRTEVJzTnlIUkBBNpQqqR3kD7EBgPO85dHYI80Kw9S6vrT2sJavprAdtNy5tcFpy6vWIuNs8CH+1gsiGZ0l6DCsOqBChkg0TJBNkkxCSb9DNDzfMgooCRw9DwgC0/QB6PjbE9Gmx/i/Q7qwtlq1R7Zvube+8sXnzk7Z1eQi8dT9hwraFm8i6yz/NWU96EJdRq1H0EbPQ8Q+2TdGL08lQhp4DkwCHfZK6i3fHdVlzEjF+r+kvFu7KbwCv9DDasqb0iDcsOb28Zr9QQmSFDQf1ygwMQI4GD1PQI5B0UAePo05RTN4K2UiVBiVDXsCXveT7G3iOtlB0b7K4MXLwpXBRMLRxCTJGs+C1iHfsejo8nb9BghKEvAbsCRGLHoyHjcPOjs7mTozOB00ei54J08fQBaTDJQCkvjZ7rTlad041lbQ7sshyQLIlsjWyq/O/tOa2k3i2Or582f92QYGEKcYeyBFJ9Ms/TCkM7Y0LzQUMnkufSlIIw4cBxR0C5gCufka8f/opOFD2wrWINKgz5zOGM8O0WvUFNng3qLlI+0n9W/9uQXIDVsVOhwxIhMnvCoTLQguly3FK6UoUSTtHqQYqxE3CoUC0fpU80vs6eVf4Nbbb9hD1l7VxdVy11XaVd5R4x/pkO9y9o39qQSSCxAS8xcPHT0hXyRhJjQn1iZNJaYi+h5oGhUVLQ/eCFsC2PuF9ZTvMuqG5bXh194D3ULcl9z+3Wjgv+Po58DsHvLZ98L9qwNnCckOqRPjF1cb7R2UH0Eg8x+vHoEcfhm+FWMRjwxpBxoCzfyq99jye+616qDnUuXb40LjieOs5J7mTumj7IPwzPRc+Q/+vwJJB4kLYQ+yEmcVaxeyGDUZ9BjyFzsW3xPzEJAN0gnYBcIBsP3B+RP2wvLm75Tt2+vF6ljqlep36/Ps/O5+8WX0l/f6+nP+5gE6BVQIHQuBDXEP3hDBERYS3REbEdkPIw4KDKAJ+gYtBFIBf/7I+0P5AvcW9YvzavK78X/xtfFY8mHzxPR09mL4fPqx/O/+IgE7AysF4gZVCHsJTQrHCuoKtgowCmAJTwgHB5YFBwRqAssAOP+9/WT8N/s++n/5/Pi3+LD44/hL+eP5o/qD+3j8e/2B/oH/cwBQARICswIxA4kDvAPKA7YDgwM3A9YCZwLvAXUB/QCPAC0A3f+e/3T/Xv9c/2z/iv+0/+X/FwBIAHMAkgCjAKMAjwBmACkA2v96/wz/lv4b/qP9M/3Q/IL8Tfw2/EH8cfzG/EH94P2f/nr/agBpAW8CcwNqBEsFDgaqBhcHTgdMBwwHjgbUBd8EtwNhAugAV/+5/Rv8i/oW+cv3tPbf9VP1GPUz9ab1cfaQ9/34rvqa/LD+4gAfA1UFcgdlCRoLhQyVDUEOgQ5ODqkNkgwPCyoJ8AZwBL0B6/4P/EH5l/Yn9AbySPD77i7u6e0y7grvbPBR8qz0bveC+tH9QgG8BCMIWgtIDtMQ5xJvFF4VqRVLFUMUlxJREIANOAqRBqYClv5/+oH2vfJR71rs8eks6BvnyeY753PoaOoO7VPwIPRZ+N78jAFABtUKJQ8PE3EWLxkyG2ccwRw7HNUamRiUFdsRig3BCKIDWP4I+d3zAO+Z6szmt+N34R7gvN9U4ObhaeTM5/bryfAi9tj7vwGqB2oN0hK3F+8bWh/YIVUjwiMYI1ohkh7UGjkW5RD+CrEEMf6s91fxZOsD5l/hnt3h2j/ZyNiC2Wvbdt6P4pjnbO3f88D62wH4COEPXRY7HEkhYCVcKCQqpirdKcsnfiQMIJYaRRRHDdIFIP5r9vDu6ueR4RjcrNdx1IPS9NHL0gXVk9hc3T3jCuqR8Zj54AEqCjYSxBmYIHsmPiu4Ls0waDGEMCQuVyo4Je4epheZDwIHJv5H9avsl+RJ3fzW5NErzu/LRcs1zLvOxtI42OreqeY872D4zwFAC2oUBR3LJIEr7jDnNEo3AjgHN140FzBTKjwjBhvxEUEIQv5A9Inqa+Es2Q/STMwUyInFwcTGxZLIE80n06LaS+Ph7Bv3qAE5DHoWHCDRKFUwbDbkOpc9bz5hPXQ6uzVZL30nYh5NFI0JdP5W84zoad4+1VPN6cYywla/br6Dv5DCgMcuzmnW89+E6sn1bAEUDWUYByOmLPY0tDuqQK5DqESMQ2FAPDtENKwrtSGrFuQKuv6J8rPmlNuC0c7IvsGJvFy5ULhyubq8EsJSyUXSptwm6G30HAHSDSsaxiVIMF85wkA0RotJqUqCSR9GlkAQOcUv/SQIGUQME//a8QHl7Nj7zYLEz7wet5+zbrKYsxW3zryXxDfOZdnL5QnzuQByDskbVii1M409kUV/SydPbFA/T6lLw0W4PcUzNShhG6wNgP9J8XbjddaqynPAIbj2sSSuy6z5raaxuLcCwEbKNdZ0457xRAD1DkAdtSrpNn1BHUqFUH9U7FW+VPxQwEo5Qqc3XCu0HRkP/v/U8BPiLtSTx6O8trMTrfCobqecqHKs1rKXu3TGGdMm4S7wvv9cD5Ae4izjOSxFZE5CVY9ZJlv5WRBWh0+NRmg7bC79H4oQiwB88NjgGtK2xBW5k697qAakWaKEo36nLK5at8XCFNDi3rzuKP+mD7cf3S6hPJhIY1K0WVFeFGDtXuNaE1SxSgQ/ZDE7Iv0RKAFA8MXfOdAXwsy1uqsxpGyfk522ns6ivalQsz6/Ks2s3ErthP7UD7UgozAhP75LFVbWXcNismSUY29fYlihTnZCPzRqJG8T0wEf8Nrejc62v8qyL6g3oCSbHpk2mmaekKV9r+G7XsqF2tnr0/3oD4whNjJjQZxOelmmYeBm/WjrZ7FjblxYUrxF+zaHJt4UigIY8BjeFc2VvRCw8qSSnDKX/pQJlkuap6Hjq7O4tMdy2GzqF/3hDzoikzNkQzBRjVwgZaVq8Wzua6RnM2DSVdFIlDmQKEkWSwMs8H3d0su0u6GtCKJEmZqTN5ExkoCWBp6IqLe1LcV01gXpUfzCD8EiuzQkRXpTTl9CaBBuinCab0ZrrmMNWbNLBzyCKqwXFQRX8ArdxMoVun6rcZ9Oll2QzY2zjgqTsZpvpfCyzsKO1Kbng/uKDyEjrzWiRndVumEKax5xxXPqcpFu3GYFXF5OUj5bLAUZ5gSa8L3c7Mm4uKepMJ20k3+NwYqRi+qPq5eaomKwmcDD0lLmsPo8D1sjbTbeRydX0GN2bcxzoXbddYRxuWm2Xs9QcEAXLlMavAXy8JfcSMmctx6oRZt4kQGLFojOiCSN+JQNoA+ukr4W0Qvl2PnaDm8j9jbYSIpYj2WEbxh2GXlveBx0QmwdYQNTYEK1L5MblQZf8ZXc2cjDtuOmspmZj+eI0IVthruKmZLLnfururyIz9Pj/vhjDl4jTDeQSZ1Z9mYycQF4LnueelZ2dW45Y/hUH0QyMcMccAff8bfcncgttvald5gajjCH74NwhLKIk5DXmyeqFbsdzqziI/jaDSsjbjcGSmNaBWiBcoV523xofC94T3AGZapWqkWLMuAdSghw8vzclMjXtVillZf8jN+FdILZggmH5o4ympeopLnWzJnhSvdBDdUiXjc7Stpaumhvc6R6In7MfaZ5znGCZhhYAEe/M+keIQkR82LdvcjDtQelDJc/jPOEYoGpgcSFlY3fmEynari3y5vgdPaZDGAiHTcwSgRbF2n8c1x7/37Ifrl68HKrZz9ZHUjKNNwf9Qm/8+fdFsnutQSl25bii26EuoDhgOOEoozgl0imarfAyrTfpPXlC8shrDblSeFaHGkodK57c39cf2d7tXN/aB5aAEmsNbYgwQp69IrenslYtk2lA5fni1CEeoCCgGiEDYw3l46lpLb0yefe2/QlCxkhDDZcSXJayWjzc5h7fn+Gf7B7GXT9aLNaqEliNnYhhgs/9UrfVMoAt+KlgZdLjJmEpICNgFKE2Ivklh+lG7ZUyTXeG/RcCkwgQDWWSLhZIGhecx17H39Gf5J7HnQlafxaEkrqNhkiQQwL9iTgNsvjt8GmVZgQjUeFOIEBgaSEBIzplvyk0LXjyKDdZ/OMCWUfSTSWR7RYIWdrcjx6V36efg17wXP0aPlaPUpDN54i7wzf9hfhQcwAueinfpkyjlqGNILegVyFkYxGlyalxbWiyCvdv/K2CGceKjNcRmlXzmUacfd4J32MfSF6BHNraKhaKUpsNwQjkA229yDidc1Wulap+pqxj9GHmIMlg3uGf437l52l+rWSyNXcJvLdB1Qd4zHrRNlVKWRtb053kHsRfNB45nGJZwpa00ljN0kjIQ6Q+D3jzs7huwirx5yLkaqJYoXShP+Hzo4KmWOmcLa0yKLcnfECBy0ceDBGQwVUNWJnbUV1k3kwehl3Z3BOZh1ZPUknN2sjoQ5r+W3kS9Cgvf2s456+k+SLkYfnhuiJfJBxmnanKLcKyZHcJvEoBvUa6i5uQfFR818Ia9xyMnfqd/90iG67ZOJXZEi4NmkjDg9E+q3l6dGQvzGvSqFHlnyOI4pfiTSMipIwnNmoIriTyaXcxPBQBa4ZPS1nP55PZl1VaBZwb3Q/dYFyTGzQYllWSEcUNkMjZg8a+/vmpdOuwaKx+6MkmW+RFo07jOKO9pRGnomqXrlRyt/cdvB9BFoYcisyPRBNkVpPZfZsTXEzcqNvsmmPYIJU60U8NfYiqQ/r+1ToftX5w02086ZSnLqUZpB2j/CRvpeyoIas3LpFyz/dPvCvA/sWjCnTOklKeFf6YYBpz23JbmZsvGb4XV9STEQuNIMi1A+1/LfpcNdsxi+3LqrNn1yYEpQPk1uV4Jpzo9CunLxtzMbdH/DpApQVjidMOE1HHVRZXrVl92kCa85obmMOW/BPa0LrMugh6A92/SLredkFyUS6qK2So0+cFZgDlyCZWp6GpmSxnb7KzXTeGPAtAicUeyWiNR9Eg1BwWpphymXiZtxkyV/RVzZNSkBzMSYh4Q8t/pHsltvBy4q9X7Gep5GgbJxOmz2dKqLrqUK038Bdz0vfLPB8AbYSVCPWMsJAsExDVjJdSmFtYpRgz1tGVDRK6T3HLzsgwA/Y/gPuxd2czvzAT7Xtqx2lE6Hsn6+hTKadrWi3X8Mj0UngWvDYAEQRHiHsLzs9pkjUUYJYfFynXfpbhVdtUOtGSjvmLSgfhA91/3bvA+CU0ZjEc7l5sPCpB6bapHGmvqqcsdS6HcYe03DhpPBCANIP2h7nLIw5aUQqTY5TZFeSWBBX7VJKTF1DbTjSK+0dLA8CAOfwTOKk1FnIx71AtQSvQqsUqoGre6/jtYO+F8lL1cDiC/G8/2IOjBzLKbo1/j9ISFpOB1I1U9xRCk7fR40/VjWLKYoctw6AAFTyn+TL1zvMSMI9ule0wbCUr9mwgbRvunPCS8yq1zfkjvFH//cMNRqbJskxaTsyQ+tIaEySTWFM4kgxQ347BTIUJ/8aJg7tALzz+OYD2zvQ8MZqv+G5frZXtXW2zLk+v6HGuM862tXlLvLk/pML2hdaI7strjbuPUZDjkawR6RGd0NCPjI3fi5sJE0Zdw1GARz1VelL3lTUvMvExJ+/dLxYu1K8Vr9MxArLWtP53Jvn7PKU/jcKfBUNIJcp0jGAOHA9fUCSQapAzj0XOa0ywiqXIXQXqgyMAXP2s+ue4YPYp9BFyozFn8KRwWnCHMWUyavPL9fk34bpx/NY/uUIHxO1HF4l2SztMm43Ojo/O3c67De0M/Et1CaVHncVwAu+Ab/3D+765MTcrdXpz6LL+cj+x7bIGcsSz3/UNdv74pbrwPQx/qAHxBBXGRYhyCc6LUUxyzO7NBE01TEcLgQptyJpG1UTuQraAf74Z/Ba6BLhyNqp1dzRfM+YzjPPSNHC1IXZaN885srt1vUg/mgGbw72FcMcpCJtJ/sqNS0MLn0tjytUKOgjbx4WGBARlQngAS76ufK762rl9N+C2zXYI9Za1dzVpNeg2rfexeOj6R/wCPcl/kAFIQyUEmgYcR2KIZUkfiY4J8EmHyViIqEe/RmcFKkOVAjPAU/7AvUb78fpLOVu4abe6Nw+3KvcKN6m4BHkSegu7ZbyVvhB/igE3gk3DwoUNBiXGxoerB9EIOIfiR5JHDQZZxUAESMM+AaoAV78P/d28iXubOpn5yvlxeM/45njzuTR5o/p8ezb8Cv1wPl0/iIDpwfgC60P8hKYFY0XxRg3GeUY1BcPFqYTrxBDDX8JgQVqAVr9b/nI9YDyr+9p7b3rtepX6qLqkesZ7S3vuPGm9N33RPu+/i8CfgWSCFQLrw2UD/YQzhEXEtIRBRG4D/oN2QtpCb8G8QMVAUP+kPsQ+db28fRu81fysvF/8b/xa/J78+b0m/aO+Kv64fwe/1ABZgNSBQMHcAiPCVoKzQroCq0KIQpMCTUI6gZ1BeUDRwKpABj/n/1J/CH7LPpy+fT4tPiy+On4Vvny+bX6lvuN/JH9l/6W/4YAYQEgAr8COgOPA78DygOzA34DMAPNAl0C5QFqAfQAhgAmANf/mv9x/13/Xf9u/43/uP/p/xsATAB2AJQApACiAIwAYgAjANP/cf8D/4v+Ef6Z/Sr9yfx9/Er8NvxE/Hf8z/xN/e79sP6N/38AfwGFAogDfQRdBR0GtQYdB1AHSQcEB4EGwgXJBJwDQwLIADX/lv35+2r6+fix96D20PVK9Rb1OfWz9YX2q/ce+dX6xfze/hEBTwOEBZ4HjAk8C58MqA1LDoEORQ6WDXUM6gr+CL0GOASBAa7+0/sG+WD29vPd8Sfw5e4j7urtP+4i74/wf/Lj9Kz3xvoa/o0BBgVpCJsLgg4EEQ0TiRRrFagVOxUlFGwSGhA+De0JPwZQAj7+KPou9nDyDe8h7MXpDugM58vmTueV6JnqTu2f8Hf0t/hB/fEBpAY0C30PXROyFmIZVBt3HL4cJRyuGmAYSxWFESgNVggzA+b9l/hx853uQuqC5n/jUeEN4L/fbOAT4qnkHehX7DfxmfZV/D4CJwjiDUATGBhBHJgfAiJpI74j/SIpIUseehrOFWwQewooBKX9IvfT8OvqmOUG4Vrds9oq2czYn9mh28Pe8eIN6PDtbvRX+3MCjglwEOEWrxyrIasljig7KqIqvSmRJyokoR8XGrUTrAwvBXv9yfVV7lznE+Gv21vXO9Rp0vjR7dJE1e3Yz93G46XqOPJH+pEC2QrdEl4aICHsJpUr8i7oMGQxYDDgLfYpvSRcHgEX5g5HBmj9jPT56/LjuNyD1ofR7M3Ry0rLXMwDzy3Tu9iF31nn+u8n+ZkCBwwoFbMdZiUCLFExKjVqN/433zYSNKovyCmXIkwaJxFuB2z9bfPA6bHgiNiG0ePLzcdnxcXE8cXiyIbNutNQ2xDktu3694oCGA1PF98gfinmMNw2Lzu8PWs+NT0gOkI1vy7GJpMdbROiCIX9a/Ks55vdiNS7zHPG4sEvv3K+sb/owv7H0M4p18zgbuu/9mYCCg5QGeAjZS2WNTA8/kDXQ6VEXEMGQLg6mzPjKtMgthXjCbT9iPG+5bHautAnyDzBMbwwuVO4o7kYvZvCAcoV05HdJul59SwC3g4rG7ImGTEOOklBkUa5SaZKUEm9RQhAWjjtLggk/xctC/j9w/D34/bXIc3Mw0G8vrZus3CyzLN6t2C9VMUYz2Pa3uYq9N8BlA/eHFUplzRLPiRG40taT2pQCk9CSyxF9jzdMi8nRBqADE/+HPBX4mzVv8muv4e3jbHvrcysL64RslS4y8A1y0TXm+TT8n4BLBBpHscr3DdJQrxK8lC3VO1Vh1SOUB9KakGxNkQqhBzaDbn+k+/h4BPTmMbQuxGzoqy1qG2n1KjirHqza7xxxzjUX+J38QwBphDLHwYu5joGRg9PuFXLWShbwFmeVd5OtEVkOkUtvB45DzT/KO+T3+7QrMM1uOOuAqjHo1aivaPzp9iuObjQw0PRLOAX8IgAAxEFIREwsz1/SRhTMlqTXhhgs15sWmNTzUnzPS4w6SCaEL//2u5u3v3O/cDftACrr6Mnn46d8J5Ho3GqObRVwGfOBd617vb/QhEUIugxQkCyTNVWXF4KY7hkWWP1XqtXtE1aQfwyCSP8EVgAqO5z3UDNjr7QsWqnrp/bmhaZcZrjnkmmbrADvajL7dtU7Vb/ZhH7IoozkUKcT0NaM2IsZwVpsGczY7FbYlGVRKs1GCVcE/8Aku6h3LrLX7wLrySkAZzklvSURJbKmmai3azfuQrJ59n166n+bxG4I/U0n0Q8UmBdtWX2avxss2skZ3Ff1VShRzk4FSe4FLIBl+7422nKcrqQrDChrJhGkyuRbZICl8qeiKnsto7G9deb6vH9XRFNJCs2bEaQVCpg3mhmbpdwXm/DauhiClh6SqI6+ygPFm8Cte5420/Jx7hiqpGesJUFkL6N7o6Nk3mbdaYttDjEGtZJ6S/9MxG5JCo39UeXVp9irGt5cdVzr3INbhJm/FoeTeM8yipdFzQD7O4g22vIX7eCqEecD5Mija+Ky4tvkHaYpaOmsQzCWdT/52f88BD+JPM3O0lRWL1kHm4rdLR2o3X/cO1oqF2IT/o+fiyiGAAEOu/u2r3HO7bwplWazJCgigKICImqjcWVHaFZrwvAs9LB5pj7lxAcJYY4Pkq7WYNmMnB8di95NniWc3RrDGC3UeRAFC7ZGdAEnu/k2kXHWbWtpbuY6I6BiLmFpYZBi2mT3p5IrTm+LdGQ5cb6KRAUJeQ4/krWWvBn5nFpeEZ7Z3rQdaVtJWKoU55Ciy8CG6QFFvD+2gHHu7S6pHqXZI3GhtSDp4Q3iWOR7Jx4q5i8x89w5PL5pw/oJA05e0uiWwRpOXPxefd8M3yqd39v8GNXVSVE3zAaHHgGoPA82/LGX7QWpJOWQYxxhVeCDYOOh7aPSJvqqSq7hM5h4x75FA+YJAM5tksfXL9pLHQTe0B+mX0ief5wa2XEVnhFDzIfHUsHPPGd2xXHRrTAowWWgIuChEOB24FHhmWO9pmgqPO5Z81m4kz4cA4mJMY4r0tNXCBqvHTPeyB/l343eiFylGbqV5RGGTMQHhsI5/Ef3GvHbbS5o9GVIIv6g5eAEYFkhXCN9pidp/O4ccyB4X73vg2VI1g4Z0stXChq63QjfJd/LX/neudyamfKWHhH+jPpHucIoPLA3PHH1bQApPWVIYvZg1WAr4DnhNqMS5jipiy4pcu04Lb2/wzkIro34ErAW9hpuXQRfKV/Wn8ye05z6mdgWSFIsTSpH6wJZfN/3abIe7WTpHGWhIsfhHyAt4DPhKOM9pdwpqG3BMsB4PX1NQwXIu82G0oHWzBpJ3SYe0h/HX8Xe1VzFGitWY1IPDVPIGgKM/Ra3ojJXrZxpUWXRozLhA2BKYEdhcuM95dKplO3kMpp3z71YwsvIfc1GkkEWjFoNXO5eoN+d36Vevxy52etWb1ImTXYIBoLCfVP35XKfLeZpm6YaI3dhQeCBILShVSNUJhvpkO3Ssrv3pL0igouINU030e4WN9m5HF1eVV9aH2teUNyY2diWa1IxzVCIb8L5fVc4MzL1LgIqOqZ545Th2mDR4Pthj6OAZnhpnK3NMqU3vPzrAkWH4oza0YmVzllOHDNd7978XtgeClxhmbJWF5IxDWOIVYMxfZ+4SnNY7q9qbmbwZAriTKF8oRtiIiPCZqgp+K3T8pZ3mTzygjpHRoywURPVUJjMG7EdcR5EnqtdrBvUWXjV85HkDW3Id4Mp/e14qzOJ7y2q9ed9ZJli1+HA4dSijGRaputqJK4nMpA3uXy6AepHIYw5EI2U/1g0Gtbc2V3z3eXdNdtxWOwVv5GKjW/IVQNifj941HQHb7vrUKggJX8jfCJeYmZjDmTIp0HqoK5HMtK3njyBwdZG9Au1UDdUG1eGmmVcKN0J3UecqBr4mEwVe1FkTSjIbcNaflV5RbSQ8BmsPeiYJjwkOGMUYxDj56VMJ+tq7W6z8t53h/yKAb7GfwsmD5JTpNbEmZ0bYJxHnJFbw1pqV9iU5pEwzNiIQYORvq55vnTlsIYs/SlkZs9lDGQio9Lkl+Yk6GhrSi8t8zM3tvxTgWQGAsrMDx6S3NYuWL8aQVut24NbB9mG11JUQZDwjL8ID8OHfsp6PfVFMUCtjWpEZ/hl9yTIJOxlXqbS6Tfr9y90s1F367xewQcFwEpnzl1SBFVE18vZi1q82p6aNhiOlrlTjJBjTFwIGAO7Pug6QzYuMchubes26LWm9+XEZdymeyeVadostC/Ic/l35jxrwOhFeEm6DY9RXBRJVsRYgBm1maNZDpfCFc4TB8/JDC9H2oOs/wf6zjagMpxvHew7aYboDacWZuKnbSir6o6tQPCpNCr4Jvx7gIhFKwkEDTWQZRN8VamXYBhY2JLYElbh1NCScw8hy7jHloObv2h7HXcac3vv2+0QaurpN6g9Z/2oc6mV65TuHTEW9KZ4bjxOQKdEmYiGDFCPoBJfFLyWLFcn122WwdXuU8GRjw6tyziHTAOHf4l7sPeb9CXw5241a+CqdOl4aSzpjirSrKxuyPHRNSu4u/xkAEZEREgBC6HOjlFyk35U5hXjFjRVndSoUuGQm83tCq5HOsNv/6p7x7hj9Nlx/y8pLScrg+rGaq9q+2vhrZTvw3KYNbq40Ly9gCWD7Ed2CqnNsNA4EjATjlSMFOjUZ1NQkfFPmk0gChpG4sNUf8q8YPjxtZWy4nBqbnzs5CwmK8Qseq0B7s0wzDNrNhN5bDybAAXDkgblyemMiI8wUNMSZhMkE0tTH1IoELEOikxHCbzGQ4N0/+m8u/lEdplzz7G4L6DuU+2WbWntiy6yr9Tx4vQKNvX5jvz9P+eDNgYRCSJLlo3cz6gQ7tGr0d1RhtDvT2HNrMtiCNWGHUMQQAc9GHoa92P0xfLRMRIv0i8Wbt+vK2/y8StyxvU092H6OPzjv8sC2YW4yBUKnAy+zjEPadAkkGAQHs9njgSMgoqxyCTFr8LngCJ9dTq0eDP1xDQ0Mk8xXbCkcGQwmvFBso+0N7XquBc6qf0O//ECfMTeB0KJmktXTO6N2E6QDtSOqI3RzNmLS4m2h2sFOwK5wDs9kbtQeQh3CTVfs9Zy9PI/MfZyF/LeM8D1dHbrONV7Ij1/P5nCIIRBRqwIUkony2KMe4zvDTxM5QxvC2JKCUixBqhEv0JHAFD+LXvtueC4E7aS9Wb0VrPls5Sz4XRHNX42fHf1uZx7oX20v4XBxUPjhZKHRUjxSc4K1QtDi5hLVcrASh9I+8dhhd0EPIIOwGM+R/yLevs5IvfMNv81wXWWNX21djX7doZ3zvkKOqv8J73vv7VBbAMFxPcGNId1iHJJJkmOiepJu8kGyJGHpEZIhQlDssHRAHF+n/0o+5d6dTkKeF33s/cPdzA3FPe5+Bj5Kzone0O89P4wP6kBFQKow9qFIUY1RtFHsIfRiDOH2IeDxzqGA4VnBC3C4gGNwHu+9b2FfLP7SXqMOcF5bLjPuOr4/HkBOfR6UDtM/GL9SP62f6EAwQINQz4DzETyRWvF9YYOBnWGLUX4RVsE2oQ9gwsCSsFEwEF/R75fvVA8nnvP+2h66fqV+qw6qzrQO1f7/Px6PQl+I77CP93AsMF0QiKC9wNtw8OEdkRFhLGEe4Qlw/QDagLMgmEBrQD2AAI/lj73fiq9s30U/NF8qnxgPHJ8X7ylvMH9cP2ufjZ+hH9Tv9+AZEDeAUlB4sIpAlnCtMK5wqlChIKNwkcCMwGVQXDAyQChgD3/oH9L/wK+xr6Zfns+LL4tPjw+GH5AfrG+qr7o/yn/az+q/+ZAHIBLwLLAkIDlAPBA8kDrwN4AygDxAJTAtoBYAHqAH4AHgDR/5b/b/9d/17/cP+R/7z/7f8fAFAAeQCWAKQAoQCJAF0AHQDL/2j/+f6B/gf+kP0h/cL8d/xH/Db8R/x9/Nj8Wf39/cL+of+UAJUBmwKdA5EEbgUrBr8GJAdSB0UH+wZzBq8FsQSBAyUCpwAT/3P91/tK+tz4mPeM9sL1Q/UW9UD1wvWb9sf3QPn9+vD8DP9BAX4DsgXJB7IJXAu5DLkNVA6ADjsOgg1YDMUK0QiKBgAERgFx/pb7zPgq9sbztPEI8NDuGe7s7UzuO++08K3yG/Xs9wv7Y/7XAU8FsAjdC7wONREyE6IUdhWlFSoVBxRAEuIP+wyiCe0F+gHn/dL52/Uk8sru6eua6fLnAOfO5mLnuejN6o/t7fDO9Bb5pP1VAgcHkwvUD6kT8haTGXQbhRy6HA4chBolGAEVLRHFDOsHwgJ0/Sf4B/M77uvpO+ZI4y3h/d/D34bgQeLr5HDoueyl8RH30vy8AqMIWA6tE3gYkBzVHyoieiO5I+Ei9SADHh4aYhXyD/cJngMZ/Zn2UfBz6i7lruAX3YfaFtnS2L/Z2dsT31bjg+h17v707fsLAyQK/hBkFyIdCiL0Jb4oUCqcKpspVCfUIzQflxklEw8MjATW/Cb1u+3O5pfgSNsM1wfUUtL/0RLThtVK2UTeUORA6+Dy9vpDA4gLgxP2GqYhXCfqKyovATFdMTkwmi2TKUAkxx1bFjIOiwWq/NHzR+tP4yncDNYs0bDNtstRy4XMTc+W00DZI+AK6Lrw7/ljA84M5RVhHv4lgCyyMWo1hzf3N7M2wzM7Lzsp8CGRGVwQmgaV/Jry+Oj53+fX/9B8y4nHSMXNxB7GNcn7zU/UANzW5Izu2fhtA/YNIhiiISkqdDFJN3c73T1kPgU9yTnHNCIuDCbDHIwStweX/ILxzebP3NTTJcwAxpbBDL95vuO/QsN/yHPP69em4VrstvdfA/8OORq2JCIuMzapPE5B/UOeRClDpz8yOvAyGSrvH8AU4Qiv/IjwyuTR2fTPgse9wN27CblauNi5er0nw7PK6NN/3ibqhvY9A+oPKRycJ+gxujrOQelG4kmgShlJWEV3P6E3ES4RI/MWFgrd/K3v7eID10rMGMO3u2G2QrN2sgS04rf3vRPG+89j2/PnTPUFA7UQ8R1SKnY1Bj+0RkRMiE9lUNFO1kqRRDA88jEmJiUZVAsf/fHuOuFl1NjI7L7ytiixvq3RrGqugLL0uJfBKMxW2MPlCfS5AmERkB/WLMw4EkNYS1tR6lToVUtUHFB7SZhAtzUrKVMbmgx0/VTusN/70aDFALtxsjWsgKhwpxGpVq0jtEO9csha1ZnjwPJaAu8RBSEnL+Y73Ua1TylWA1olW4NZJ1UxTtZEXDkcLHkd5g3c/dXtUN7Ez6TCWLc4ro2njaNZovyjbKiIrxy53sR00nfhcvHpAV4SUSJEMcI+Y0rJU6pa0F4XYHNe8FmvUuZI3jz2LpYfNg9V/nXtGt3Czee/9bNKqjOj6J6OnTCfxKMpqya1b8Gnz2DfIfBoAbASciMqM2BBok2QV9xeS2O5ZBljdV7wVsJMOUC2MaYhhxDe/jLtDtz2y2q92rCqpiqfl5oVmbKaZJ8Ip2SxKb71zFfd0O7YAOQSaCTbNL1DmFAIW7ticmcIaW9nsGLwWmhQakNYNKcj2BF2/w3tLdthyi67Ca5ao3abm5bxlIaWT5sqo9utD7tiyl7bgO05APwSNCVVNtdFQ1MvXkRmQmsAbXFrnmarXtRTbEbaNpclJxMZAAPtddoDyTS5hKtdoBmY+ZIlka6SiZeTn46qJbjyx3nZM+yQ//gS1iWXN7BHolUBYXRptm6fcB1vO2odYgFXPUk5OXIncRTJABTt6Nndx363TKm2nRaVs4+1jS+PFpRGnICnbrWmxanX7Orb/toSTyaiOERJs1d+Y0lszXHfc25yg21DZe5Z2UtyOzYptBWCAT7thNntxgu2Yqdkm3CSy4ykigyM+ZBHmbak7rKBw/HVreke/qMSnyZ2OZRKdVmkZcFuhHTAdmJ1dHAaaJVcPU6BPeEq7xZEAoLtSNk1xt20yKVrmSeQRYr0h0eJNY6ZljGiprCIwVTUeOhZ/VQSxyYSOqBL6FpxZ9pw2XY+efd3CnOfavZeZ1BkP3AsHhgLA9ztNNm0xfOzfaTKlz2OIoioheSGzYs+lPafm668v9TST+eP/O4RyCZ5OmhMClzlaJNyynhYeyl6RHXPbAxhVFIZQeEtQBnXA03uRtloxU6zg6ODlrSMY4bBg+SEw4k5kgaezqwfvnPRNObC+3MRoiapOuxM3Fz+aexzVnoMffd7HneobtViAFSdQjEvUxqlBNHuftlTxeyy2aKWlY2LCoVBgkmDGYiNkGScQqu1vDTQKuXz+uUQWCalOixNXl2+auJ0fHtYfl99mHgncE9ka1XtQ14wVBt0BWjv2tlxxc2yfqIElceKGIQqgRSC0YY7jxKb+ql/uxrPMuQl+kYQ6yVsOilNkV0ja3d1O3w7f19+rnlLcXllkVYIRWUxQhxCBhDwWNrDxfGydKLMlGSKjIN7gEiB7IVFjhKa9qh/uiXOT+NZ+ZYPXCUBOuVMdF0va6l1kny1f/d+YHoTck9mcVfrRUYyGh0MB8fw99pGxlWzt6LtlGKKaYM2gOSAbYWtjWWZOqi4uVnNguKR+NgOrSRmOWBMCl3hanp1gnzFfyd/rXp8ctJmCViVRv4y2x3RB4vxttv6xvqzSaNolcOKrINbgOmAUoVzjQ2ZxqcrubbMzuHP9w4O4COaOJxLUlw6aul0DHxrf+1+lXqGcv9mWFgFR4szgx6PCFvykdzdx920JqQ6loOLVoTqgFiBnYWZjQuZnKfauD/MNOEW9zoN9iKhN5tKT1s9afhzLnuofkl+F3oxctVmXVg4R+wzDx9ECTTzid3syP21TqVil6SMZoXhgTCCT4YejmCZvafGuPXLteBm9l0M8iF9Nl5JAlrqZ6ly7Hl8fT19Mnl8cVVmFlgtRx80fx/uCRT0md4lyle3v6bfmCKO24ZBg3CDZocDjwyaKqjvuNnLVODC9XoL1iAuNedHblhDZvxwRnjoe8l76XdncH5lg1flRiM00B+LCvr0wd+Iy+m4d6ivmv2Ps4gIhRiF4ohHkA6b4qhXue3LE+Ar9ZIKox+5MzlGk1ZKZPNuPXbvee55O3bzbk9kpFZdRvczAiAbC+P1/+AQzbK6c6rQnDKS7IozhyaHworrkWic6Kn/uTLM8d+k9KgJXB4eMlZEdlQCYpJs1HORd613KXQgbcpieVWVRZkzEyCaC872T+K8zq+8saw+n7+UhI3DiZiJBY3tkxmeOavnuqjM8d8t9L0IAx1hMEFCGFJuX9ppDnHRdAl1tXHvau9gAlSNRAozAiAIDLj3sOOK0Ny+Lq/4oaGXeJCzjG6MqY9Llh+g16wPvFDNFODJ89MHmhuDLvw/fU+PXM5m7G2xcQNy4W5jaL5ePlJFQ0kyzR9iDKD4H+V30jjB57H7pNaaxpMCkKOPrZIFmXqiwK53vSvOW+B48+0GJBqILIo9p0xqWXJjcmo0bp5urmt8ZTlcL1C9QVQxdB+oDIT5m+aA1L/D2bRCqFmea5eskzeTDpYZnCil9LAevznPxuA98wwGoxhyKu86mUkCVshfo2Zeat1qIGg8YmJZ1032Py0w9h7ZDGL6Ieii1m7GAbjLqymiY5uulyWXyZmEnyiocbMFwXrQV+EY8zIFGhdEKCw4WEZZUtVbgmIwZsNmOWSnXjpWNUvwPdIuUx7yDDj7runb2ELJXLuSr0Cmq58GnGqb251Eo3irNrYqw+7RDeIK82AEihUBJkc15UJ0TptXFF6wYVNi/F++WsNSTEisO0UtiR3zDAX8QOso2zjM5b6Ts5uqPqSuoASgQqJVpxWvQrmNxZTT6uIW85kD9hOrI0EyRj9XSiBTXVnhXJFdbFuEVgBPHkUrOYYrmhzbDMb81eyG3U3PmcLLtzavGamjpe2k+aa2q/2yk7wsyGzV7eM6894CYBJGIR4vfjsGRmZOYFTGV4JYjlb9UfRKrEFvNpUphBupDHv9a+7y333SdcY1vAy0N67hqiKq/qtjsC23JsAFy3bXFuV58zACyhDUHuIrkDeEQXRJIk9mUihTZVEsTaFG+T15M3MnSBpdDCH+APBp4sTVdMrNwBq5k7NjsJ+vS7FXtaK7+MMYzrDZZebT85IBNw9YHJAogTPXPExEqEnETIlN9EsVSAtCBzpLMCIl5hj1C7j+kfHp5CDZks6OxVq+Krkktl+13baQulnACMhh0Rjc2udJ9AMBqA3VGSslVS8DOPU+90PlRqpHQka8QjU92jXnLKIiXhdyCz3/HPNu543cy9J1ysfD9L4gvF27rrwIwE3FUszf1K/edOna9IYAIQxOF7ghDysMM3M5FD7OQI9BUkAlPSI4dDFPKfYfsRXTCrH/oPT26QbgHNd7z13J78RQwpTBu8K8xXzK09CP2HHhMuuH9RwAogrFFDketCb3LcozBDiFOj07KjpVN9gy2CyHJR4d4RMYChEAGvZ/7IrjgNue1BfPE8uxyP7H/siny+HPiNVv3F7kFe1Q9sb/LQk+ErIaSCLIKAEuzDEPNLs0zTNQMVotCyiQIR0a7RFBCV4AifcF7xTn89/X2e/UXdE7z5fOcs/E0XjVbdp84HPnGu8194T/xQe6DyYX0B2FIxsocitxLQ0uQy0cK6wnECNuHfUW1w9OCJYA6viF8aDqcOQj3+Daxtfq1VjVEtYP2Dzbft+y5K7qQPE1+Fb/awY9DZkTThkyHh8i+ySyJjknjya9JNMh6h0kGacToQ1AB7gAPfr+8yzu9Oh85OXgSd643D3c2NyB3ijht+QP6QzuhvNR+T//IAXKCg8QyRTTGBIcbh7XH0UguR85HtMbnhi1FDgQSwsXBsUAf/ts9rTxe+3e6fnm4OSf4z/jvuMW5TnnFeqP7Yzx6/WH+j3/5gNhCIoMQxBvE/kVzxflGDcZxRiVF7MVMRMkEKgM2AjUBLsAsPzO+DX1//FE7xftheua6ljqvurI62ntku8v8iv1bPjX+1L/vwIGBg4JwAsJDtkPJBHkERUSuRHWEHYPpQ12C/sISQZ3A5sAzf0h+6v4f/ap9DjzNPKh8YLx1PGR8rLzKvXr9uX4CPtB/X3/qwG8A54FRQemCLcJdArYCuQKnAoDCiEJAQiuBjQFoQMCAmQA1/5j/RT89PoJ+lj55fiw+Lf4+Pht+RD62Pq++7j8vP3C/r//rACDAT0C1gJLA5oDwwPIA6wDcgMgA7sCSQLQAVYB4QB1ABcAy/+S/23/XP9f/3L/lP/A//L/JABUAHwAmAClAJ8AhgBZABcAxP9g/+/+d/79/Yb9Gf27/HL8Rfw2/Er8g/zh/GX9Df7T/rT/qQCrAbECsgOkBH8FOQbKBioHUwdBB/IGZQacBZoEZQMGAoYA8P5R/bX7Kvq/+ID3efa09Tz1FvVH9dD1sfbk92P5JPsc/Tv/cQGuA+AF9AfYCX0L0gzKDVwOfw4wDm0NOwyfCqMIVgbHAwoBNP5a+5L49PWW843x6e+87hDu7u1b7lXv2fDd8lT1LPhR+6z+IQKZBfYIHQz1DmQRVxO6FIEVoRUZFecTExKpD7gMVgmbBaQBj/17+Yn12PGH7rLrcOnW5/Tm0+Z3597oAevR7TvxJvV1+Qf+ugJqB/ELKxD1EzEXwxmTG5IctBz2G1oa6he1FNQQYgx/B1ICAv24953y2u2W6fTlEuMK4e7fyt+h4HHiLuXE6BztFPKJ90/9OwMgCc4OGRTWGN4cECBQIoojsiPCIsAguR3BGfQUdw9zCRQDjvwQ9s/v/OnG5Fjg1txe2gXZ2tjg2RPcZN+84/vo++6P9YT8pAO5CowR5heUHWgiOybsKGMqkyp3KRUnfCPGHhUZkxJzC+kDMfyF9CLtQuYc4OLav9bV0z7SCNI508nVqdm73tzk3euJ86b79QM2DCgUjRsqIsknPCxgLxcxUzEPMFItLSnAIzIdsxV9Dc8E7PsX85fqruKb25jV1NB3zZ7LW8uxzJrPAtTI2cLgveh68bj6LgSUDaEWDR+VJv0sETKnNaE37TeFNnIzyS6rKEch0xiRD8YFv/vI8THoQ99H13zQGMtIxyzF18RPxovJdM7m1LLcneVj77n5TwTUDvUYYiLRKgAysze8O/o9WT7SPG85STSDLVEl8RuqEcsGqfuY8PDlBNwj05PLkMVNwe2+g74YwKDDA8ka0K/YguJH7a34WQT0DyIbiiXdLs42Hj2bQR9Ek0TyQkY/qDlCMkwpCR/IE98HqvuI79fj89gxz+DGQsCMu+W4ZbgRuuC9tsNpy73Ubt8p65P3TQT1ECcdhCizMmM7T0I+RwhKlUrfSO9E4j7lNjQtGCLnFf4IwvuX7ubhEdZ2y2jCMLsIthqzgLJAtE+4kb7WxuHQZdwK6W/2KwTVEQMfTStTNr0/QEehTLNPW1CTTmZK8kNmOwUxGyUFGCgK7vvG7R7gYdPzxy6+YLbHsJKt2qyprvOymLlnwh3Nadnt5kD18wOWErYg5C25OddD70u/URlV31ULVKZP00jDP7o0DiggGloLMPwV7YHe5NCrxDW61LHNq0+oeadSqc+t0LQfvnbJf9bV5Ar0qAM3Ez4iRjDiPK9HV1CVVjZaHVtAWatUgE31Q1I47yo1HJMMhPyE7A7dnc6gwX+2ka0dp1ejYKI/pOqoPrADuu/FqNPE4s/ySgO5E5sjczLOP0JLdVQeWwdfEGAvXnBZ9lH6R8c7ui1BHtEN7PwR7Mfbi8zUvg+zmKm7oq6elJ12n0ek5asWto3C6dC94I/x2gIcFM0kajR6Qo5OR1hXX4djtGTTYvBdMFbNSxY/bDBCIBIPZP2+66var8pJvOiv7qWrnliaGZn5muufy6deslK/Rc7D3k3wWgJhFNMlKTbkRJBRyFs9Y7NnBWkoZydiKVpqTztCAjM1IlQQ6/2I67rZDMkAugytlqLwmliW85TNltmb86PdrkO8vsvY3AzvywGIFK4msTcMR0ZU+F7NZodrAG0qaxJm313NUjNFeTUXJJURgf5w6/XYoMf6t3yqkJ+Ml7GSJZH2kheYYaCXq2K5WMn+2sztLwGSFF4nADnwSK9W02EEagBvoHDVbqxpTGH0VftHzTfnJdISJP9z61rYbcY4tjqo35yDlGaPs413j6aUGZ2QqLS2Fsc52ZHshwCBFOMnFzqPSspYWGTfbBty43MncvNsb2TbWJBK/TmhJwoU0v+S6+rXcsW7tEemhprWkXuMn4pTjIqRHZrLpTq0+sSL113r1f9VFD4o9jrpS5VahWZdb9d0xnYcdeNvQ2d+W+5MBDxDKTsViADL66TXsMSDs6SkhZiHj/CJ7YeOiceOcpdLo/ixCMP21TDqGv8PFHAonDv+TA9cWWh8cTB3R3mxd3hyxWnaXRJP4T3KKmIWRgEc7IfXJsSRslKj3paYjcmHnoUph1+MGZUTofKvQsF91A/pWP6yE3koCjzOTTld02k7cyV5ZHvkebJ09GvtX/tQkD80LH0XCwKF7JHX08PksVGikZUKjAaGtIMnhVWKFZMmnyiuqr8i0/vnkv0/E1soQjxYThJe82qYdLV6Gn20e412zG21YaVSEEF/LYoY0wID7cLXt8N8saGhoJTeiqqEMoKLg6qIaZGFnZ+sQ77n0fXmyPy2EhcoQzyeTplet2uTdd57aX4dfQd4S28uYw1UXkKpLocZnQOV7RnY0MNYsUKhCZQVirSDF4FUgmGHF5AznFirD73P0AHm/fsbEq4nDzygTtBeIWwrdqB8Tn8gfh55cHBXZDNVd0OvL3MaaAQ67pTYHsR4sTOhzZOuiSaDZoCFgXuGII8zm1SqELzczx/lNPtuESInqDtfTrZeL2xgdvt8y3+7ftN5OHEvZRNWW0SPMEobMAXv7jHZn8TasXSh65Oqif+CH4AfgfmFho6EmpepSLsPz1LkbPqxEHUmDjvcTU5e5Gszdu183X/tfiJ6pHGzZa1WBkVIMQsc9gWz7+7ZUsV+sgOiZJQIikCDQYAigdyFSo4qmiGpubprzp3jqvnmD6clQzoZTZhdP2uldXl8hn+1fg16sXHjZf9WeEXXMbUctQaE8MvaNMZgs+CiNZXHiuiDzYCOgSSGbI4lmvSoZbrxzQDj7vgQD7wkSTkXTJVcQmq1dJ57xX4VfpJ5X3G+ZQdXr0U8MkUdbQdf8cTbRceBtAmkXZbmi/aEwoFjgtKG7Y51mhCpTLqizX3iOvgwDrUjIjjYSkdb72hnc116nH0MfbF4rnBCZcZWqkV0MrodHAhE8tncgsjdtXul2pdkjWqGIIOgg+WHzo8cm3epcLqBzRfikfdHDZQi0DZfSbFZR2e6cbd4C3ybe2x3nm9wZDlWZ0V/MhIewAgv8wbe6clztzWnrJk/j0CI5IREhV2JDZEZnCqq0bqOzc7h8/ZZDFshVTWtR9NXTWWxb692E3rDecJ1MG5IY2FV50RaMkseVwkg9Erfd8tBuTWpz5t1kXmKDodPhzmLq5JsnSercbvKzaThY/ZnCw0gtDPERbJVAmNObUd0t3eGd7RzY2zKYT5UKEQGMmUe3wkT9aLgKs1Du3erQJ4ElBGNnIm/iXeNp5QVn3CsT7w2zprh4/VyCqse7zGoQ09TamCUaoBx+XTldEVxOWr2X89SKkOBMV8eVwoI9g3iAc94vfqt/qDplgaQi4yRjBaQ/5YToQWubb3UzrLhc/V+CTgdCDBcQa1Qh12GZ11u2nHicXZus2fOXRVR7UHLMDYevgr89ofj99Dcv7qwBqQgmlWT2I/DjxWTspllo+Ovyb6jz+zhFvWLCLcbAi7hPtBNXFomZOJqXm6Abklr02RSWxFPcUDjL+odEQvt9w/lC9NtwrWzU6eonfyWgpNTk3CWvpwKpgyyZcCj0EnizfSdByka4Ss7PLpK7VZ4YBFniGrDasFnnGGFWMRMtj7KLnodUAvZ+KLmOtUnxea246p7ofaahJc+lyWaIaAAqX60PsLW0cvimfS0BpEYpiltOW5HPVN/XO9iW2arZt9jDl5nVS9Kvjx+LecceQu++T7ogNcHyEq6sq6YpUCf25uBmzKe2KNFrDa3VcQ603Hje/TSBfIWVCd7NvFDUE9AWH5e22E+YqhfLVr7UVNHiDoBLC4ciwuc+uDp3NkLy969vLL5qdejg6AXoJOi4afXrzW6qcbQ1DzkdPT5BE0V7yRoM0dAKku+U8NZC11/XR5b/FVETjJEFzhSKlAbhgtv+4frStwuzp/B/baarrWoeaX+pESnOay0s3i9OMmX1i3lh/QsBKUTeSI2MHI8z0b+TsJU8FdyWEZWflFDSs5AazVzKE0aZws2/C/tx95t0YfFcrt4s9etuKoxqkOs3bDYt/zAAcyO2EPmsvRrA/0R9h/qLHY4QkIESoBPj1IbUyJRtkz8RSo9hjJkJiUZLwvx/NfuUeHF1JTJFcCOuDizO7Crr4qxyLVBvMDEAs+12n7n9/S3AlUQZx2HKVk0ij3URAFK60x+TbhLqUdyQUc5aS8mJNcX3Aqd/X3w4+My2MHN4sTWvdS4/rVptRa397rrwMDIOdIK3d7oV/UTArIO0BoRJh0wqTh0P0tEC0ehRwtGWUKpPCo1Fyy6IWUWbwo4/h7yfeax2wvS1clNw6S++7tlu+K8ZsDSxfvMpdWM32Lq0fWAARUNNRiLIscrpTPnOWE+8kCIQSFAzDykN9QwkygjH84U5wnD/rfzGuk932zW6c7tyKXELsKawerCEcb0ymzRQtk64grsZ/b+AH8LlxX4Hlwngi41NEo4pjo4O/45BTdmMkgs3SRgHBQTRAk8/0n1uOvV4uHaGtSyztDKkcgDyCfJ8stM0BDWD90R5dbtGPePAPMJ+RJdG94iRSlgLgwyLTS3NKczCjH1LIwn+iB1GTgRhQih/8/2Ve5z5mbfYtmV1CHRH8+bzpbPBtLW1eTaCOEQ6MPv5fc0AHIIXxC8F1Me8iNvKKorjC0KLiIt3ypUJ6Ei6xxiFjoPqwfy/0n47PAV6vbjvt6S2pLX0dVb1TDWR9iM2+TfK+U169HxzPjv/wAHyg0aFL8Zjx5nIislySY3J3QmiSSJIYwdtRgrExsNtgYtALT5ffO37Y3oJ+Sk4B3eo9w/3PHcsN5s4Q3ldOl97v/zz/m9/5wFPgt6ECYVIRlNHJUe6h9DIKIfDh6XG1EYWhTSD94KpgVTABD7BPZV8SftmenF5r3kj+NB49LjPOVv51nq4O3m8Uv26/qi/0gEvQjeDIwQrBMnFu0X9Bg1GbMYcxeDFfUS3g9ZDIQIfQRkAFv8fvjs9MDxEO/v7Gvrjupa6s/q5euS7cXvbPJu9bT4Ifyc/wcDSgZLCfULNA75DzkR7RETEqsRvRBTD3oNRAvDCA4GOgNeAJP96vp6+FT2h/Qe8yPymvGE8eDxpvLO8031E/cR+Tf7cP2t/9kB5gPEBWUHwAjKCX8K3AriCpIK8wkMCecHkAYTBX8D3wFCALf+Rv36+976+PlM+d74rvi6+AD5efkf+uv60vvO/NL91/7U/78AlAFLAuECUwOeA8UDxwOoA2wDGQOyAj8CxgFMAdcAbQAQAMb/jv9r/1z/YP91/5f/xP/2/ygAVwB/AJoApQCeAIMAVAARALz/V//l/m3+8/18/RD9tPxt/EL8NvxN/In86/xy/Rz+5f7I/74AwQHGAscDuASQBUcG1AYvB1QHPQfpBlcGiAWCBEoD5wFkAM7+Lv2T+wv6ovhn92X2p/U29Rf1T/Xg9cf2AfiG+Uz7SP1p/6AB3QMNBh4I/gmcC+oM2g1jDn0OJA5YDRwMeAp1CCIGjgPOAPf9HftY+L/1Z/Nl8cvvqO4I7vLtau5x7//wDfON9Wz4l/v1/msC4gU8CV0MLQ+TEXoT0RSKFZ0VBRXGE+URbw90DAkJSAVOATj9Jfk49Y7xRu5860fpvOfq5tnmjucF6TfrFO6K8X711Plr/h8DzAdODIAQQBRvF/EZsRudHK0c3BsuGqwXaRR6EP0LEwfiAZH8SPcz8nrtQumv5d/i6eDi39Lfv+Cj4nLlGumA7YXyAfjN/boDnAlED4QUNBkrHUogdSKYI6gjoiKJIG0dYhmGFPwO7giKAgL8h/VO74bpYOQE4JfcNtr22OTYBNpP3LffI+R06YPvIPYb/TwETgsZEmYYBB7EIn8mFyl0KogqUSnUJiIjVR6RGAES1QpFA4z74/OJ7Lflo99/2nXWptMs0hTSYtMQ1graNN9q5XvsM/RX/KYE4wzMFCMcrCI0KI0ski8rMUcx4y8HLcYoPyOaHAoVyAwSBC77XvLn6Q7iENsl1X7QQM2Jy2jL4Mzqz3DUUtpk4XDpO/KA+/gEWg5cF7cfKSd3LWwy4TW4N983UzYdM1QuGSicIBUYxA7xBOn69/Br54/eqtb6z7fKCscTxeXEg8bjye/OgNVm3WbmO/Ca+jEFsQ/GGSEjeCuIMho4/jsVPks+nDwSOccz4SyUJB4bxxDfBbv6sO8U5TvbdNICyyTFCMHQvpK+UMABxIvJw9B22WDjNu6k+VMF6BAIHF0mlC9lN5A95EE9RIVEt0LgPhs5kjF9KCIezxLcBqX6ie7l4hbYcc5Cxsq/P7vFuHO4TrpJvknEIcyV1V/gLOyh+F0F/xEjHmopfDMJPMxCj0cqSodKoEiCREo+JjZULB0h2RTlB6f6gu3g4CLVpcq7wa66tLX3so6ygLTAuC6/nMfJ0WndIuqS91AF9RITIEYsLDdxQMlH+UzYT01QUU7ySU9DmjoUMA4k4xb6CL76newE31/SEcdzvdK1a7Bqreis7a5qsz+6OcMVzn/aGOh49i4FyhPaIe8uojqYRIJMH1JDVdJVxlMsTyZI6T67M/Am6xgYCuv61+tT3dHPucNsuTyxaasjqIanmKlNroG1/r59yqXXEuZV9fYEfxR1I2Mx3D1+SPRQ/FZlWhBb+VgrVMtMEENEN8Ep7ho/Cy37M+vO23jNn8Cqte6ssqYno2yiiKRtqfew7boEx9/UE+Qs9KsEExXjJKAz1kAdTB1VjVs6XwVg5V3qWDlRCkesOn0s6hxrDIL7r+p22lbLxb0tsuyoSaJ6np+dwJ/PpKesC7euwy7SHOL98k0EiBUmJqc1kEN1T/hYzV++Y6pkiGJmXWtV00ruPSEv2x6cDen7SupJ2WvJLLv7rjilMZ4fmiKZRJt3oJOoXLN/wJfPMeDL8d0D3RU8J3U3CEaDUoNcumPuZ/1o22aZYV5ZZ04JQaoxwCDODmH8BepJ2LnH1bgTrNahb5oalvqUGpdpnMKk5K96vR3NU96Y8F0DExYmKAs5PEhEVbxfUWfGa/ls3WqBZQ1dw1H3QxU0lSIBEOj83ul210DGw7Z4qceeBZdvkiuRQ5OpmDWhpqyjusLKhtxm788CKxbkKGc6LEq4V6BijmpEb5twiG4YaXZg41S2Rl82WSQyEX791OnO1gHF9rQspw+c9ZMgj7eNxI87lfGdpan9t4rIzNo37jMCJhZ1KYk71kvcWS1lcG1kcuBz2XFdbJRjw1dDSYU4CSZfEiD+5+lS1vvDb7Mwpa6ZQpExjKGKoIwhkvma5qaKtXfGKNkN7YsBBRbbKXM8Ok2wW2Fn9G8jdcZ2z3RLb2VmYVqaS4Q6oieFE8z+FeoC1i7DLrKFo6aX7o6iieyH2olfj1GYaqRPs4zEm9fq69oAyhUXKiI9WE4yXTxpGHKAd0l5ZXfgceVouVy6TVo8ISmkFIL/Xerb1ZvCM7EroviV+ox3h5qFdYf4jPqVNqJNscvCKdbR6iAAdRUpKpk9ME9jXr1q3HN5eWh7mXkZdBJryV6eTwQ+hSq4FT4Avure1UHCf7AjoaaUZ4uwha6DcoXtiveTSqCHrzjB1NTC6WL/CRUSKtg9wU9CX+FrPnUNeyF9anv0delsj2BEUYA/zCvAFgABNusJ1h7CEbBuoK6TN4pQhCmC04NCiUySq54ArtS/ndPB6J3+hhTTKd89DFDOX6tsPXY6fHJ+1nxvd2huB2KrUstA8iy5F8YBw+ta1jLC6K8KoBOTaYlXgwyBm4L4h/mQWp26rKK+iNLQ59b97xNvKa89ElAJYBht2Hb/fFt/2n2IeI5vMWPQU+NB9i2iGI0CZOzR1nzCBLD3n9SS/4jFgliAyoEQhwGQWZy3q6S9ltHw5g/9RBPmKEs91U/0XyptEXdcfdp/d34/eVhwCWSxVMdC1i54GVUDGO1s1/vCY7A2oO+S+Iicgg6AYYGMhmWPqZv4qty8ydAk5kj8iBI6KLI8VE+NX+Fs53ZSfe9/rH6RecZwj2RMVXRDjy86GhoE2+0p2K3DBbHDoGWTU4nbgi6AYYFshiePTZuAqku8I9Bt5YX7vRFsJ+g7kk7YXj5sWnbffJt/d35+edZwwmShVehDITDmGtsEre4G2Y/E6LGfoTWUEYqAg7eAyoGxhkaPRJtQqvO7pc/N5Mb65RCAJu06j03WXUJrbHUGfNx+2n0GeYhwoGStVSNEiTB5G5YFi+8C2qLFCbPIol2VL4uNhKqBnIJch8OPkJtoqta7U89G5A/6ARB2JcQ5T0yHXO9pHnTHerV91HwpeNtvKmRxVSNExzDzG0oGdPAa2+LGaLQ8pNuWrIz/hQWD1oNriJ+QMpzJqvS7K8/a42D5FA9QJG4400rvWkZocnIjeSZ8ZnvodtBuXWPqVOdD2DBRHPQGZvFM3E3IAbb4pa6YiI7Vh8iEeIXeidmRKZ11q068Mc+K47v4Hw4RI+42HEkPWUpmaHAcdzF6kXlCdWdtPGIZVG5DuzCTHJIHXfKX3eHJ1Lf8p9Oav5ANivCGf4e2i3GTdZ5rrOa8Zc9Y4yP4JQ28IUc1L0fpVv1jBG6zdNd3V3c6c6BrxWD+UrdCcDC2HCQIWvP33pvL3LlDqkidT5OljHuJ64nvjWeVF6Csrbu9yM9E45n3JwxRIHozDEWBVGFhSGvscRp1unTQcHxp+V6YUcNB9S+6HKcIWPRr4HrNGLzLrAqgNpaaj2mMuoyJkLiXDaI3r86+WtBQ4x73KAvUHooxuELZUXleN2jJbv1xu3EGbv5m2VzoT5FASy+dHBkJWPXw4XrPhL6SrxajcJnqkrWP6Y+Ck2OaVqQLsR/AHdF+47T2KQpIHXovNED0Tklb1GRNa4JuXG7faiZkZ1rvTSE/cC5eHHoJVfaE45nRH8GUsmmm+5ySll6TdpPYlmid8aYps67BENLO4132LQmtG00thD3WS9RXImF7Z61qompcZ/Zgo1etS3M9ZC39G8cJUPcl5dTT5MPOtQCq06COml+XXZeHmsKg3amOtXrDNNNA5Br2NQgHGgUrqzqBSB1UJV1WY4BmjmaAY3BdkFQkSYk7KCx5GwAKRfjP5ijW0MY8udat9aTanrabnJuOnnGkF606uIPFidTW5Oz1QwdYGKUorDf6RChQ4FjiXgBiJGJPX5hZL1FVRmI5uirRGiMKM/mC6JPY4MncvOmxW6l0o16gMKDponKonrAsu8jHDtaQ5dT1WQajFjEmizREQflLWFQkWjFdaF3LWnBVg01CQwA3HSkFGi8KGPo66hDbEc2owDO2A65WqFSlFKWUp8Gsb7RgvkfKxNdu5tP1eQXpFKsjSzFiPZNHkU8gVRVYXlj5VftQjkntP2Q0TycVGSQK8/r0657dX9CdxLK66LJ8rZOqQ6qNrFuxh7jWwf/Mqdlx5+v1pQQuExUh7y1aOf1CkErZT7NSCVPbUD1MVEVYPJAxUyUAGAAKwfuw7TrgyNO4yGC/Brjhshewu6/OsT2247yKxe7PvduY6Bv23QNzEXQefCouNTk+WEVWSg9Nb013SzlH1kCEOIUuKCPHFsMJgvxp7+DiRtf0zDnEV72BuNu1drVUt2K7gMF7yRTT/t3j6WX2IwO7D8ob9CbjMEw57j+aRCxHlEfRRfNBGjx3NEYr0SBqFWwJNP0g8Y3l1tpN0TnJ18JXvtq7cLsavcjAW8amzW3Wa+BR68r2eQIIDhoZWyN9LDs0WTqrPhJBfUHtP288IjcxMNQnTh7qE/oI1f3Q8j/odt6+1VrOgchexA/Co8Ebw2nGb8sG0vfZBOPj7Ej34AFbDGcWth8BKAovnDSOOMQ6LzvPObI28jG2KzIkoRtHEm8IZf549PPqIeJE2pnTUM6QynXIC8hTyUDMutCa1rHdxeWX7uH3WgG4CrMTBhxyI78pvS5IMkg0sDR+M8EwjiwKJ2IgyxiCEMgH4/4W9qbt1OXb3u/YPtTo0AXPoc68z0rSNtZd25bhruht8JX45gAgCQIRURjVHl0kwSjgK6QtBC7/LJ8q+yYwImcczxWcDgcHTf+o91Xwiul941reRtpg17vVYdVR1oLY39tM4KXlvetk8mT5hgCUB1YOmhQvGuserSJZJd4mMidWJlMkPSEtHUUYrxKWDCsGov8t+f3yQu0n6NPjZODz3ZDcRNwM3eHeseFk5drp7+559E36OwAXBrML4xCCFW0Zhxy7HvsfPyCJH+IdWBsDGP8TbA9xCjUF4/+i+pz19vDV7Fbpkeab5IDjRePo42Plp+ef6jHuQfKs9k/7BQCqBBkJMg3UEOcTVBYLGAEZMhmfGFAXUhW3EpcPCgwvCCYEDQAG/C/4pfSC8d3uyexT64PqXerg6gPsvO3676nysvX8+Gz85v9OA40GiAkpDF8OGRBOEfYRDxKcEaQQMA9ODRELiwjTBf0CIgBY/bT6Sfgq9mX0BfMT8pTxiPHs8bvy6/Nw9Tz3Pvlm+6D93P8GAhAE6QWFB9kI3QmKCuAK3gqHCuIJ9QjMB3IG8gRcA7wBIQCX/ij94fvJ+uf5QfnY+K34vvgI+YX5L/r9+uf74/zo/e3+6P/SAKQBWQLsAloDowPGA8YDpANmAxEDqQI1ArwBQgHOAGQACQDA/4r/af9b/2H/d/+b/8j/+v8sAFsAgQCbAKUAnQCAAE8ACgC0/07/3P5j/un9c/0I/a38afxA/Df8UfyQ/PX8f/0s/vf+3P/TANYB3ALcA8sEoQVUBt0GNQdUBzkH3wZIBnUFagQuA8gBQwCr/gv9cvvr+Yb4UPdT9pv1MPUY9Vj18PXe9h/4qvl1+3T9mP/QAQ0EOwZICCMKuwsCDeoNaQ56DhcOQg39C1AKRgjtBVUDkgC6/eH6H/iK9TnzP/Gu75buAO727Xvuje8n8T/zx/Wt+N37Pv+2AisGgQmdDGQPwBGcE+YUkhWWFfEUpBO2ETQPLwy8CPUE9wDg/ND45vRD8QXuR+sg6aPn4ebg5qXnLelu61nu2vHX9TT6z/6DAy8IqwzVEIoUqxceGs0bpxykHMAbABpuFxsUIBCYC6cGcQEf/Nn2yvEa7e/oa+Ws4srg19/c397g1uK45XHp5u328nv4S/44BBcKuA/uFJAZdh2CIJcipCOdI38iUSAfHQIZFRR/DmgI/wF3+//0ze4S6frjsd9Z3BDa6djw2CnajdwM4I3k7+kL8LL2sv3UBOMLpRLlGHIeHiPCJkApgip7KigpkCbGIuMdDBhtETcKoQLn+kPz8ust5SzfHtos1nnTHNIi0o7TWNZt2q/f+eUa7d30B/1YBZANbxW3HCwjnCjaLMMvPDE4MbQvuSxcKLsiARxgFBIMVQNw+qXxOelw4YbatdQq0A3Nd8t3yxLNPNDh1N7aB+Im6v3ySvzCBR4PFRhgILsn7i3FMhg2zDfPNx82xjLdLYUn8B9VF/YNHAQS+ibwpubc3Q7We89Yys/G/sT2xLrGP8ptzxzWHN4x5xTxe/sTBo0QlRrdIxwsDjN+OD08LD45PmI8sjhDMz0s1CNJGuMP8gTN+cjuOeR12sfRdcq6xMbAuL6kvozAZsQVym/RPto/5CXvnPpMBtsR7hwuJ0ow+jf/PSpCV0RyRHlCeD6LON4wqyc4HdUR2AWh+Yvt9eE817PNpsVWv/W6qbiFuI66tr7fxNvMb9ZS4THtr/ltBggTHR9OKkM0rDxGQ9xHSEp0Sl5IEUSuPWQ1cSshIMoTzAaM+W7s29801NbJEsEuumO117KhssS0NLnPv2XItNJv3jvrtfh2BhMUIiE8LQM4IUFNSE5N+k86UAtOekmpQso5IS//IsEVzAeO+XTr7N1g0TLGvLxItROwRq37rDWv5bPruhDEEM+X20XpsPdoBv0U/CL3L4k7VkURTXtSaFW/VXxTrU52Rw0+uDLQJbUX1win+ZvqKNzAzsvCqLiosAqr/KeYp+Opz642tuG/hsvO2FHnofZFBsUVqSR8MtI+SUmOUV9Xjlr/WqxYplMSTChCMzaQKKYZ6gnV+ePpkdpWzKK/2LRQrEum/KJ9otak9am1sdu7G8gX1mPlifUMBmwWKibLNNtB9UzAVfdbZ1/0X5ddYFh3UBZGjTk8K5EbBQsY+k3pJ9kjyrm8ULFEqNuhSp6vnRCgXKVsrQS408R2033jbPS/BfIWfifhNqNEWVClWT5g8GOaZDdi11yiVNVJxDzSLXMdJQxu+tfo6tcqyBK6Ea6HpL2d7JkxmZabCKFgqV+0sMHt0KDhSvNgBVcXpCi+OChHclM5XTJkJGjuaIlmBmGOWGBN0z9OMEkfSA3W+oLo29Zpxq+3HqsbofSZ45UIlWyX/pyVpe+wtb5/ztHfJvLvBJwXnClhOmlJPlZ7YM9nAGzsbIpq6mQ3XLRQt0KtMhIhbQ5P+03o+dXjxJG1eagEnoSWM5I3kZaTQpkOormt6LsvzBDeAfFuBMMXZyrKO2RLvFhnYxNrgm+QcDRuf2ibX8xTbUXtNMoikQ/Y+zboRdWXw7izJKZDm26T4I7AjRiQ1pXPnr+qSrkAymHc3u/fA8oXBSv4PBlN6Vr8ZfptpXLXc4ZxwWu1YqZW8kcJN28kshBu/D3ovdSGwieyHqTbmLWQ7YupivSMvpLbmwWo37b2x8bav+5CA7UXdivsPYdOxlw4aIRwaXW/dnt0rm6CZT9ZQ0oBOf8lzxEQ/WDoYtSwwd2wa6LMlluOWonyhy2K/Y81mY6lqbQSxkLZpe2bAoQXuyulPq5PUF4aaq5yyndFeRJ3QnEAaJNbXEzQOnYn5RK9/Z/oMtQUwdqvCqEYlWGMK4eehceHl43gll2jrLJYxNfXk+zqATcX1iskP41QiF+ga3d0x3lme0h5enMraqBdPE51PNQo8hNy/vjoLdSywB6v+5+/k8qKYYWvg8OFjIvflHSh6rDJwofWi+sxAdIWxitqPyVRbWDKbN11XnsifRp7VnUBbGRf4E/tPRYq9RQu/2rpUdSJwKquQJ/DkpWJ/YMngiOE4Yk1k9efZq9pwVXVj+pyAFUWjSt3P3ZR/2CYbeB2jnx2fod80XaAbdtgRVE1Pzgr6hXw//LpntSYwHyu154kksSIAYMIgemClYjikYaeIa45wELUoemw/8EVLStMP4FRPmEKboB3V31hf4597HembgRiaVJMQDos0BazAJDqEdXewJSuwZ7gkVaIbIJRgBaCrIfpkIWdHq08v1LTw+jq/hoVpyrqPkZRK2Efbrx3t33jfy1+pHhyb95iSlMvQRotpRd5AUHrqtVawfGu/J75kUyIQIIEgKqBJYdLkNScX6xzvoTS9+ck/l8U/SlUPsdQyGDYbZR3r336f2R++Hjhb2Zj51PdQdQtaBg+AgXsZtYLwpGviJ9tkqWIfIIhgKiBA4cJkHWc5Kvgvd3RP+dg/ZQTLymKPQZQFGA3bQl3P32ofzJ+6Hj0b5xjP1RUQmguFRkBA9jsRNfuwnOwZKA7k2GJIIOogA6CRYclkGmcsKuFvV3RnOaf/LkSQSiOPARPEl88bB12aHztfph9dHiqb35jT1STQtQurBm/A7ntQtgCxJaxjaFjlH6KKoSZgd2C7IefkLGcxKtjvQXREebk+9IRNCdjO8JNwl3patB0KnvIfZV8m3cCbwxjF1SYQhcvKxp3BKbuXdlExfayAqPhlfuLm4XxghOE94h2kU2dIKx8vdjQn+Uw++AQCiYKOkJMKFw/aSNzh3k7fCp7Xnb7bUVillNiQi4vkBonBZ3vldq0xpO0wKS1l9aNb4eyhLGFZoqrkj6exazPvdfQSOWE+uUPxiSFOIhKRVpBZxlxgXdIell5vXSYbCphzVLxQRkv2RrOBZzw5ttNyGq2x6bcmQ6Qp4nYhraHOYw9lISftK1fvgLRDeXk+eMOaSPXNpVIHFjyZLRuGXXwdyN3uXLXarpfuVFDQdcuBRtoBqHxTt0Pyni4E6lUnJ+SPoxiiR6KbY4slh6h7K4rv1vR8ORP+dsN9iECNWxGrlVSYvdrUnI1dYl0VHC6aPZdXVBZQGcuFBv1Bqnyy972y7u6oasan4iVNI9NjOmMApF2mAujbbAzwOPR8eTJ+NEMbyAJMxBEAFNmX+NoL28Zco1xkG1DZt9bt04xP8gtAxt0B7TzW+AAzjC9bq4rosaYhZKYjxWQ9ZMam0ulN7J5wZnSEuVT+McL1x7vMIRBFFAxXH1lsmugbjJubmpyY3ZZyUzNPfos0RriB7/0++Eq0NS/eLGEpVScLpY/k56TRZcXnt2nSbT7wn/TVOXu970KLx22Lso+7ky2WMdh3mfMantq8WZLYLxWk0otPPwrfxo+CMf1qeNx0qPCu7QhqTCgK5o/l4KX75ppob6qo7a6xJXUt+Wc97YJextiLOY7kEn4VMZdt2OgZmtmHGPOXLRTFkhQOs8qChqGCMz2YuXS1JvFM7j/rFakep6Vm76b754Qpe6tQrm0xtrVPeZd97QIvRn0Kdo4/kX7UHxZQl8hYgVi8V7/WF5QVEU5OHIpcxm6CMr3JedL17nI3bsascOoFqM9oE6gRKMHqWmxJrzpyE/X5eY097kH+BdwJ6w1PULDTO5UgVpRXUxdc1rgVL5MT0LmNeUnuRjZCMH47ujZ2fjLtb9utXGt+6czpS6l6adNrS61TL9Yy/PYsecg98YGLBbaJF0yTz5USCBQeVU2WEVYp1V0UNVICD9bMyom3BfhCK/5uup43FXPt8P2uV2yJK1zqluq26zesTm5s8IAzsXaoOgk994FXhQzIvIuOjqzQxdLLlDTUvNSkFC/S6dEgjuYMEAk2xbRCJL6iewl383S38evvoK3jrL4r9CvFrK2tom9WMbe0Mbcs+lA9wIFkBKAH24rADbkPthFpkouTVxNM0vFRjdAvzefLSkithWpCGj7V+7e4VzWKcyTw9u8M7i9tYi1lbfRuxnCOcrx0/Pe6ep09zMEwxDCHNUnpjHrOWZA5kRKR4RHk0WJQYg7wTNyKuYfbxRoCC/8IvCf5P7ZkdCfyGTCDr69u3+7Vb0twebGU84310zhQuzC93ID+g7+GSokMS3ONMc68T4uQW9BtT8PPJ02iy8TJ3gdBRMNCOj86fFm57HdE9XOzRfIG8T0wbDBUMPExu3Lo9Kv2s/jve0p+MICNw02F3IgpCiQLwA1zjjeOiM7njlcNnsxIiuEI+AaeRGZB4/9qPMv6m/hqtka0/DNU8pbyBbIgsmRzCrRJtdU3nvmWu+r+CMCfAtsFK4cBCQ3KhcvgjJgNKY0UzN1MCUshybIHyAYyw8LByX+XfX47DblUd5/2OnTsdDuzqrO5M+R0pjW2Nsm4k7pGPFG+ZcBzAmlEeUYVh/HJBApEyy6Lfwt2SxeKp8mviHiGzoV/Q1iBqj+CPe+7wHpBuP43f3ZMden1WjVdNa+2DTctuAg5kbs9vL8+R4BKAjiDhgVnBpFH/EihSXxJisnNiYcJO8gzBzUFzESDwygBRf/pfh98s7sw+eA4ybgy91/3ErcKd0U3/jhvOVB6mHv8/TL+rkAkQYmDEwR3RW3Gb8c3x4KIDogbx+0HRkbtBeiEwUPAwrEBHL/NPo09ZnwhOwT6V/me+Ry40rjAOSM5eDn5eqE7pzyDve0+2kACwV0CYQNHBEhFIAWJxgMGS0ZihgsFyAVehJPD7sL2wfOA7f/svvg9130RPGr7qPsO+t56mLq8uoi7OftL/Dm8vb1RPm2/C8AlgPPBsQJXQyJDjgQYRH9EQsSjRGJEAsPIg3eClMIlwXAAub/Hv1++hn4APZD9O3yBPKP8Yzx+fHR8gj0lPVl92v5lfvQ/QoAMwI5BA4GpAfyCO4JlQrjCtoKfQrRCd8IsQdTBtEEOgOaAQAAd/4L/cj7tPrX+Tb50vis+ML4EPmS+T/6D/v7+/n8/v0C//3/5AC1AWcC9wJiA6cDxwPEA6ADYAMJA6ACKwKyATgBxQBcAAIAu/+H/2f/W/9i/3n/nv/M//7/MABeAIQAnQClAJsAfQBKAAQArP9E/9L+Wf7f/Wn9//ym/GT8Pvw4/FX8l/z//Iz9O/4J//D/6ADsAfIC8APeBLEFYgbnBjkHVAc0B9UGOAZhBVEEEQOpASIAif7p/FD7zPlr+Dj3QfaP9Sv1GvVh9QD29vY9+M75nvug/cf/AAI8BGgGcghICtoLGQ35DW8Odg4KDisN3QsoChcIuAUcA1YAff2l+ub3VvUL8xnxku+E7vrt/O2M7qrvT/Fx8wH27/gk/Ij/AAN0BsYJ2wybD+0RvRP7FJkVjxXcFIEThhH4DukLbgiiBKAAifx6+Jb0+vDF7RPr+eiM59nm6ea/51bppeue7iryMfaU+jP/6AORCAgNKRHTFOYXShrnG7AcmhyjG9EZLhfME8QPMgs6BgABrvtr9mLxvOyd6Cjle+Kt4M7f6N/+4AvjAObJ6UzuZ/P0+Mn+twSSCiwQVxXrGcAduCC4Iq4jkCNbIhYg0BygGKQTAQ7iB3QB6/p49E7unuiX42DfHtzs2d7Y/9hR2s3cYuD35GvqlPBF90r+bQV3DDATYxnfHnYjAydoKY4qayr9KEsmaCJvHYYX2BCYCf0BQvqj8lvrpeS23r7Z5tVP0w/SM9K906PW0tos4Inmuu2I9bj9CQY8DhEWSR2rIwMpJi3wL0oxJjGDL2ks8Cc2ImYbtRNaC5gCs/nt8Izo0+D/2UfU2c/bzGfListGzZHQVNVs26vi3OrA8xP9jAbjD84YBiFMKGMuGzNNNt03uzfnNWwyYy3vJkEfkxYoDUYDPPlW7+LlK9111f/O/MmXxuzECsX0xp7K7c+71tXe/efu8Vz89QZoEWQbmCS9LJIz3zh4PD8+JT4lPE84vDKWKxMjchn+DgYE4Pjh7WDjsNkc0evJVMSHwKO+ub7MwM7Eosoe0gnbIOUV8JX7RQfNEtId/Cf9MIs4az5sQm5EXUQ3Qgs+9zcoMNgmTRzaENUEnPiN7AfhZNb4zA7F5b6vupG4nLjSuia/eMWZzUzXR+I37r76fAcQFBYgMCsGNUs9vEMlSGJKXkoXSJ1DDz2fNIwqIh+6ErIFcfhb69jeSdMKyWzAs7kWtbuyt7INtay5dMAxyaLTd99V7Nr5mwcxFS8iMS7XOM5BzkieTRdQJFDBTf5I/0H3OCsu7iGcFJ0GXvhM6tXcYtBXxQm8w7S/ryetEa2Br2W0mrvpxA3Qsdxz6un4ogcvFhwk/TBtPBBGnE3SUolVqVUuUypOwkYtPbMxrSR+FpQHY/hf6f7asc3gwee3GLCvqtmnr6czqlWv77bHwJPM+dmS6O33kgcLF9wlkzPEPw9KI1K9V7Ja6FpbWB1TVEs7QR81XSddGJUIfviU6FXZNsunvgu0tqvppdWilKIopYGqd7LNvDbJUte15uj2bAfEF28n8jXcQshNX1ZcXI9f3l9DXdFXsU8fRWw4+ik3Gp0Jr/js59nX9Miwu3ewoKdzoSCexZ1koO2lNq4BufrFwNTf5Nz1MQdbGNMoGDiyRThRTVqqYBxkhWThYUNc01PTSJY7gSwJHK0K9Phm54zW68b8uC2t2qNOnb6ZRpnsm5+hMqpltePCRNIS48r04gbRGAkqAzpFSFxU612kZFRo2mgyZm5guVdVTJk+8C7RHcELTPkB527VHcWMti+qZqB/mbGVG5XEl5mdbab/sfS/489Q4bTzgQYlGRArtDuSSjNXNWFIaDRs2Wwxak5kXFugT3NBQzGMH9cMt/m95n7UicNitH+nRp0Ilv6RSJHvk9+Z7KLQrjC9n82c353yDgZZGegrKj2ZTLtZKWSSa7pvf3Dbbd9nul6xUiBEeDM4Ie8NMvqZ5r3TMcJ/siClfprskqeO0Y1xkHaWsp/dq5u6esv43YbxiwVtGZIsZD5YTvFbxmZ/buFyyHMscR9r0GGFVZ1GizXTIgUPvPqU5irTFcHjsBKjDpgtkK+Lt4pOjWCTwpwpqTe4eMln3HHw+gRjGQ8tYj/QT9ddCWkPcal1snYidApummQZWOdIezdZJBgQVPut5sTSNcCPr1ah+JXOjRiJ/oeHiqGQH5q3pgi2nMfs2mHvXAQ8GV4tJUD/UGlf8Wo+cw54Onm5dp1wFGdpWvtKQznJJSUR9/vj5ovSkL+Eru2fPZTPi+aGqIUgiDuOzZeJpBC06MWI2VfuswP4GIEtrEDmUadgfWwLdQ56XnvveNVyPmlyXNdM4johJysSpfw0537SJr/Crdme35IzihiFt4MahjGMzZWkolKyXsQ92FXtAQOaGHgt+UCFUpJhrW12dql7HH3DerF0E2s0XndOVjxdKCgTW/2f55zS975HrRie3pH6iLGDLIJ5hIWKI5QIodCwAcMP117sRwIiGEUtC0HbUipigG59d9x8cn4yfC12kmyqX9pPmz19KRkUGP4i6OTSAb8UraqdOpEliLGCCoE9gzmJ0JK4n42v1MH/1XPriAGTF+os5UDqUm1i9W4heKh9YH87fUl3uG3TYP1QsT58Kv0U2v696FPTQ78prZCd85CzhxqCUYBogk6I1pG2noqu18AQ1ZfqxQDuFmYsh0CzUl5iDm9geAt+5H/cfQN4hW6tYd9RlD9bK9EVnv9s6erTvb+DrcidCZGnh+uBAYD6gcWHNpEDnsmtDsBD1MvpAAA=\" type=\"audio/wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\n## Video\n\nMore exotic objects can also be displayed, as long as their representation supports the IPython display protocol.  For example, videos hosted externally on YouTube are easy to load (and writing a similar wrapper for other hosted content is trivial):\n\n\n```\nfrom IPython.display import YouTubeVideo\n# a talk about IPython at Sage Days at U. Washington, Seattle.\n# Video credit: William Stein.\nYouTubeVideo('1j_HxD4iLn8')\n```\n\n\n\n\n\n\n\n\n\n\nUsing the nascent video capabilities of modern browsers, you may also be able to display local\nvideos.  At the moment this doesn't work very well in all browsers, so it may or may not work for you;\nwe will continue testing this and looking for ways to make it more robust.  \n\nThe following cell loads a local file called  `animation.m4v`, encodes the raw video as base64 for http\ntransport, and uses the HTML5 video tag to load it. On Chrome 15 it works correctly, displaying a control\nbar at the bottom with a play/pause button and a location slider.\n\n\n```\nfrom IPython.display import HTML\nfrom base64 import b64encode\nvideo = open(\"animation.m4v\", \"rb\").read()\nvideo_encoded = b64encode(video).decode('ascii')\nvideo_tag = '<video controls alt=\"test\" src=\"data:video/x-m4v;base64,{0}\">'.format(video_encoded)\nHTML(data=video_tag)\n```\n\n\n\n\n<video controls alt=\"test\" src=\"data:video/x-m4v;base64,AAAAHGZ0eXBNNFYgAAACAGlzb21pc28yYXZjMQAAAAhmcmVlAAAqiW1kYXQAAAKMBgX//4jcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTE4IC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAxMSAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTMgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MzoweDExMyBtZT1oZXggc3VibWU9NyBwc3k9MSBwc3lfcmQ9MS4wMDowLjAwIG1peGVkX3JlZj0xIG1lX3JhbmdlPTE2IGNocm9tYV9tZT0xIHRyZWxsaXM9MSA4eDhkY3Q9MSBjcW09MCBkZWFkem9uZT0yMSwxMSBmYXN0X3Bza2lwPTEgY2hyb21hX3FwX29mZnNldD0tMiB0aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MyBiX3B5cmFtaWQ9MiBiX2FkYXB0PTEgYl9iaWFzPTAgZGlyZWN0PTEgd2VpZ2h0Yj0xIG9wZW5fZ29wPTAgd2VpZ2h0cD0yIGtleWludD0yNTAga2V5aW50X21pbj0yNSBzY2VuZWN1dD00MCBpbnRyYV9yZWZyZXNoPTAgcmNfbG9va2FoZWFkPTQwIHJjPWNyZiBtYnRyZWU9MSBjcmY9MjMuMCBxY29tcD0wLjYwIHFwbWluPTAgcXBtYXg9NjkgcXBzdGVwPTQgaXBfcmF0aW89MS40MCBhcT0xOjEuMDAAgAAACqVliIQAV/0TAAI/3gU2tIW7KawwaCmQGTGHKmuYAAADACBcshU+yICkgAA14AHowiEeT6ei7v7h3Hu0i2fpUBLGBIkbCMP3Vfz+9BVGCDXnw9Uv5o3iN030tb7eq6rsEEhHs2azbdTiE9Csz5Zm6SiUWRdmB43hbD5i6syATuODUJd7LM3d9cbFpc7zFlu5y3vUmNGd6urpvKKT9iyleIyTuR1sVS431DhevGfkUllVeIznYUe2USoMW1tufETjyRdmGldN6eNlhAOsGAH4z+HkrwKecPPU7Q5T4gDAIxj9hW84jVExMTSTHxkPTq1I4OotgUxURCGTsw60k/ezPNmNg38j1bqaGmPcruDKEIBDsK5qEytFB90Q68s0h2wmlf2KXd5bleBefiK+/p47ZsyUO4IdlW25rRy+HLjt6wQXfYee3IkiQOoOK+U7u/lxcl78zfxwIoEMjUUSKNZjkp8clnmecDDJ3Kz+viF7bPklk7N6QRyizAKPIIpnNJUuMWQmqeL2Or6cr4D0/0tOym+4tficxmhuEONKUtO2pPn3hRjMllkd12tXp70fLTfxy0dwB70ML9iLEcItHb7zVupHlP5RxdvecpREw+OsIPr9KWilIesNE19jgIbT+TkiRBjOoKvUuwcQnKg7fOTHVoLvnKuAfea+oujEdm1Rwd2tEOnkF+ZC11WaNQsiNR/eJ9EnUXjXDYGfhB+Oe7qj8nYTT+eOXg1cuJNgLXEs4vOheWEjQOqfIWMQc3DmTof5s0ksBmUQ3PQ+UHPxZSnmOEZB+j6xT3wbm7HGzDjWtSg1SjTxd1EiJ8xA4SIxxR8WIKLg+TwFxJNS7Laxq7Uglu3AkXe82P1JCdJX5PsbFbxuDbuJgakzRcTwMLLSKCiizS/eCW0uJed/lev9yb80kKlVET4S219cn/zhkpeDV83cHYOr+sJQKDRk/Wh2c7fsuxfxaEH/6reSmvFDsAnXAyPXliJ3G4VG3OkEM5K5WyGGrBizZbTrdGsBnzj5VSGGOJdCKuRrUluw/8es2vYRPs9BcTqAqvHk9M52SSIf+1T6L53EZP8VbtXB+G29CMW4xVCK/B/YDjaNmqMwJ61dapugjnWJfqeXlGGa3Ch3aA7gi30T8PucNRBjLK3lF67ZDDvkWXRQXd+VMnKWHkBbCkQ/F/fMuNpHO3C00Y2pljna1qImBhVMvPe0F7Qx7G/YyxLRzhyUU8e23HGzp0agtNJRbydbrPV+TqJMSifJMNcZIf8wkdnC3/xdpcXnLf2Ye3Kbd0o7utciTG+q5h6WTEk+PaNbXLLA0YyZ2VnLTcyV1QTS76aNCbV9Q1/OQ7QU81Gg0hPa9aSiscGary6jLVwDQaik4zLsi7jPqgPVdup7pwx7uJDqRCVcVi5QoZFp/GHdex5sJTF69A6sja69/NLkFIWNSIeRcuGahXpF+wZeYIrqJv975s1TKYKAvp1WtzgtgWNkcbzCtROqf8rPtlAIxkX8GLcEo9zfExyfimeXQ64qfFxEy0IMy2Hsxau9fSMqUnIjntuVVjCQtBL+94gx1RZLndE6wROVTq/wHwHrQzo9QL9cpPqPFJjiZ/NGZIFuudS+wsBFe6Hu8Oitf5zToLqLdtU4Smwh4ne3JsiT9lOzN+4PPw3VSx9l5FppVwdKUWELw1dYpCOppyVWlJ3YQ8H4FQQM8EcYMG9N3Bxu79y1J1ikuvuhMmLQlehLTbguhbix74hd1VIQC8EjHmOZSSWbssulYwPbr6FF49tifk6PymJvulR9/u+2585HkRfbxveGeWCz0ix1pIVfaNpESKmtLy/0mcbMg9hYDz2werz9oe0lT2BiMV6uAin6RaQcT8Vk9MPctfwae+gkvtnZA/sOBk8MbpylaHqc0KIVHhhLFMNnkOFiucjtGo/JWTa/F6g8wWeow5ZuIJUORaYHWqegZbTgM9dCsYYsfZGjjVMuSlDIvpYvIvFFooGPC7Ye2Jfawmq4Ut7EL/nv/dyAd2HRc5msmUhzeu/XpX3rVlzRmf9/Qan8Dbve3QfW1Ym0o5J/KAc3z1VBho7JBr5PgCL68RiD9jZHN0VvsT4gzsEjNlW3D91Uy4RduaodBFoNTzXwlfUYULBzdiTbH75l/UmVMC4TKeTWhNzw2UezaqeGd8at3WSY7W/VR3+hvZHDpkIjgKuNNH0DsCRa/Kk56XQoHIyvvUH/eNekNvziReqS4qgLnXUT4BRGt2BOtCifI6+X/DGHUOmWlX7TN5b4pw5U7jwfwshtbhGZM49T8JMk15Mzrc7tM6J11TYxb5R3mQhZ8TZumJ0bMJXPM69HFyihr5dJSEJMycxJVUh6NTQALUOoRTHIOwE+FpWI6feTv1SiZ0YpYe5DbkYJJbN7zAHbAKw25XvqR2mAjQmOlsfX/tK8DPjP/8h5/xgAF4EUbj1tOnQCBQL8jk9vHtfsXncsprww4Z+P/Z/UrKifuFyEpBWN8kLpF7yywE2iYdDruV9+/qKR8rC9ozNKyqQNIwtxrzYkWpE5t8K7gG4JFnrHona/Rp8dOX6VW41+jb5LB1LEtE8MwjLp3RCUOq/+6yLzaOEgBTqzvEjDeFpg/u9DMHMr4/2TOchfjg7dl+uQ6Gsx+4Ia9W7vivG95027p25eKL0nHvx/OqmAQEZYJL/JO58lOj0zPdJxrQ5dZksjMISzVZNn7DsxqE3zgBBuNzk50R8lTK3U8P12QiOAQYSTeGlYlkvfeofrfO1AitEj02m9aUkxTFd1ZZJoLQT2d3zEU5PmE4lxMVfL5ttNnIbqfcIU2RJKNWqdw77xfjfrNc/eNpRKPZ/6z50LzBprgjzBHRfKgSWWkDxHrX0aTbgwQFwd51+PoUWH4DkQg26uGslF5Hn3hB58+fkeLTosTANOIBNAeFZtTc4PIaLHw759zae7scY55xcTabzlilYIftst2RZ6ntsRC3zFxduCKvL6wLfYT+TiIWJn5P7sTwZwXuSzXY+9Q3xMZ5o4Xcpz6vD9FtTjzS69iefEYt4pXiDrZUo4ePGiLeoIFIwYB/v6GXdmG5VLLk+eKbOc9AmsX2zmvqtcvDRGQbzugXbH/kTH/lkNPBTmqN3ZJODUEXVohPEJ6th0xna0EVleB73Q3eNvaVUvhlJbjs3D/T17FRCebN7AOXvzzbLE/I5kNfEmJcv4dxtIeo2uQ/z9ohSpiZzbDj1u40nJRyJxUK60wEv0nA9f/NuJ6/PEyU0bkK16z2KH12k3Lc4+1f5fawIzkK2qJRB4wnj8VHhUW9mbJhs9vgfFmU3xrXSShY67Ygb+gYNPxxtn4K/9eTSwIA9fv/nR33lA2lZoXALRUTmOZIl3R0gAM5h6oX1y1thIyqViBK95VZc8Pvy7G3O90M9S4zkpyFQ36jrMazvMveMA4d39fvoaC7p90quiJfjI4yrl+ECVkCJL5MxRSa+iVcIL7Xbl0jVaGhZIcMYmcGOBbLzhJgloM1x1zFnnj3ggJRFAM8yNnXxhavk+mA18JC+y3lqGsp6vPReRxGlGHMou17L4It070LzkoeCzarpv8Apw59smdS5KN9qVN1WgeL7OSN8BHg94ubCvS7DW6H3/PbtRB62jFLsBhUV5YqCIbIN5VZ81AAACpUGaIWxFfwAru8x8uT3FuOjrAeSWXmAWqq9jCNGE+N5AOv//9//xjk4uBAcADN96c97AVGmzRtnWwPsgcCbLrVdQJgbKp4QSmPwQnVhv0hXyBjeFWWlcvx70urEN3FK6/lvk2tQeZgbtlbzXluvTfnSj/Ctz7vZ+O1FjhDzzdpL7uLzewzCIW5VWLAEKUVuS2J6wNk6MR7UblcEd4EtOY+R4/qJgfojCsfRvA0oC5dc41Vd0erZbSkrmPTjLCn815bxlchUJMS8gQD5hJNwoKHvNLNwn7XKuTtYIhH2wVNZvDWgzCjlPeQajnrcMsb6bZYJvNJU8HuGHvm50r7VG8qifEwmuyegAZXojh5Ul5VvjDW7kSAZyw8a7I6mHY3FZHd+OA3V4JZMbNliI3Tj1L6+MKTmilVialmyZagRtEMeKRdtxUPd3vVEtrOBVIVYWdgAGA7HmZiHQUQNxLkWxbLyWVlrh5EM0Do2NdbclHxxArz90d+MSVeUOIXQ/4V9quq8C8qVflo1gPtPMkjO2/UrdOYqhY404ReObOu/fdp4hAEDq6jhy64vOeT7XUK/Onq0rXTldtA6kvgQaJg+mgYSR9hfXtMbOUSLgLj/RmBSO8aAMHuJJZqf1tCM5pZ9eYUsrHmy+/z2NGalon0//uF6+33bQzT/RLRfBbYTjy9QrJqHLlw46lggWPGkHuPKSqk/CB7U4pNPXUbR0DdcJy9Db00wCzVzxVc6h7jfCFgiL2Y0HVqd6bgIaVUqn/gJCEyCDVplnzebv0gg3XwMJAGu639lHu7rEvxTp1smIYjWp9R5L4SspVvS07Nb+Smk1FgsMp1K3EMUT8X2Fty4VG54/Ec6bE8tNVw4/QV1VzBw7Px2/2eEhhUS+FMfbHAlD28x00jRgAAACW0GaQjwhkymEVwArOUkEOhoFqiELtH8wgecFLiUq6WqmwAP7iGEwbYzfnHacfqUNXAfD+CGR2ap0lAHL25ipuYtd5j2O0PU/MpaWPG/n2y5OkfTzaOpotaR5tWjN55B2XblVVqsFfBC/mvsiPvCBWUHFChacdY5whj5mP5rqQ0dqLJCsWjrs4TWnIbL2V/Iwfj3hwI35jfo1JkTOeR+8GhOdma9rgiKWafCbQyhYMTDmVdvhND60Flm97EDSTjF0OC+0gD9b8Yn4tNeHipCa/aWyt0n79bMmjfcjntBCPjrcB5ecRTpfGHbEHy1IRj2cjkGXKC+VYoYJXBp4rd4cMd8ygLCk5nBSd8/cTaKNRjdBscOeTXG6QEjSxj9/2pVwx9DMRVtWQR0BSaAcQcZ8W2KPSaeRC4QwmNMu2xx25CSyrDiq2rFSK/JJtmvoIjAKq0ciEXoOgw+Ke+Ylb7ULKCS3k1p/613UNRp450uSq5b7CAHo7S0b7fBMLfNmwSjRYEhLlo0HUaRe/I+IX2Z6XdZH9Hty/399ZA1PwZGC6EfvUJIf7CBeaxv7cu6IT2/s0zPRGthpvXpYw6A7P4Wwz5C4V98KnIUNUanadqabKP6eXWhvbvcQHxAjiOOiKZgXZplZW2g+B2NNyJSLiR+g48DqvWR6t9S2aGfFjdOW1Gi6oTtZ1d4p5XIslAr8mryeZ6+htSSQe4AcfVt7k+V6mOthBCYtr/LEU4ZHtl0mW9876PK8mRFAaT8DJOUFVz1lPfzRApuPggkkyq+UMvyfKTUbCk7/DpfX8Y4s4QAAAg9BmmNJ4Q8mUwIr/wAsWUPjZw3ksgRsxZ6n4fQjprPbkj2aUh30y0bZJnLmiXnWskvOGnCPwBnG9dEhatwX3hoxk7BNyG+wQ4emZUpcVzcWl2T9nKQB1euucuZWHTg7TCtM/iHyfPO2vbmGsfzs70b/egIbywUH4y4BQSL1nWc1SmpHm2zHMBcUjYLDZ5gL5vdfxn0V8FFw66G88c/LN4I5icUa7xf4fcSBKywU0ajbp1P+aJYjBgWT6Ggu0MDLDNl54tfqd42lKosQtM1aif4WXAZFP5Ww3vrQ1rH9+utSYxqZd6N6gGtNbSNMcViaKn5LcnjsbBi3T3EmGqshEbcme8VHKwR3kSfBOAprrIsv6K8R+X6az+MD23rWka/2v64m1qM69D7Xa+Kcs/n0KLCJdTilyaGadopLeaAn3eYvWTeHcucMM1Fp1KgHD1tiFeO6HvobLkZlRximsA3/7MiohYklLIcJrZL22BH+6W9d6kZsYIsej9RM681nU6mWNjepBAfAfTbrGRrVB/h2DxC5B8YyRjgSIzQjNYrse0rzChqbrsLl7mQ7W+1bsNKze5//9ZIa8rSsF+BXh/vgoRTDkPW/ws95B7VPCZEFChfX0icw+tpcpN/q7NY87tUn4vESdSiMMlyhKklMjQu/G51J69ZRQLs2oUO6YfoJFqliy4qCFCrf8SZE9Fc6DcCagAAAAodBmoRJ4Q8mUwIr/wArPWF/KOw78THwadfPqhJO0CnmR/M74/XYZLqVYKlNcEaYauf+vrRUDJPmu75sMKy2Y+Bnslc/iAISSyWtw/h/3CF8fE5ZrbrwSNst+MSyCoNWP+8imtoX2eyojpdCk8YP5K+cbK4SJPCkZXbYqSXYk7hO8AdSemBHgXKWiZ+UOr802aJo+98ZOIjX9hWL9bo31Gqx7cy4ZG+W/ar/WGlzDa1xPWnPRsEdrIcZlEVGV/jGmbirkxw1lyUYoqj8Vv7Bxube9XPQlBkXOV6Lc1LT2IzNq0V7WwVhF0kA6yxfAsFxc9krNEH8vGGntTWI608ovjatXc/CKKXw7AjJSftlTcLI0hIIGXbRUr0NCYNp7M4cVd/n73Rjetnixz4SAKpcz/P47UsijZG7T3SxzK2D79WS42aEalc12hQwCZ01LfmF/H2mmGEvOzPBie1D0YT7Jh19vxa4Dd3SQ1FrDfmSUpvv4DjbYcZ2PrPpFpWtMjWqHBeoyMiZf6RP3EfYR6z9jsVNIIHxM0bzzBQF8eeYkPgDySydxPXv9Izo+QUY94N8kWi16fI6eZSDc1G0Yo0L91jcRQuDMGGS7B2zuf/0GbJyRhUO48UbMrqnILMrbQg1LF00Q3pH9nbGEK/RRQpRN3T/J/4IZQjwW2Ft2ipWGztg1Jn9I4DmffKS60QC+JQcyakdVON6zDcKttIKlqeTcmAi4xzmo4QXa2dRKleS+fs3EtTdBBtony2wK9T2Imj+NCziOSEL7Q7VuIU8kclUHrJJsSneFcxGRgIgGGUEQM8/pklwTOqab7mMmJeRiaBrjJDEnDpkR4Vz3qXxgyn4/5x24FuTMNVPwQAAAhtBmqVJ4Q8mUwIr/wApcLwPT0/Xh9UdWqWXIs8Wbj5K1hivmN6qIQnq+aolcegdlM/63MbHsdC6xYZC1e/Q8UjQCt9N/Ejqwms8DzeWv2qxskeliZH0kt1QWkErWSEodq7V0ZNksctLkMGWayX33gBT368EehfIeGDolBZoqIbJfb4nqcfU+ev4OzVv9zVqWyLck315GFmXxQKIM8pICQc8Q5es34LH1+DmnMnW8kQpVGrztQcDXhjCU3F0fOgoSsXSVWCjc6XKqGbCwQDfJUxCfXfIT6YmQoPpVp1mpGy1wQypXus9z0bScDpyDu23hViYDntdj1O45ea0znKZkj1+tLHbBtqAGJ1WTcbGlF6Vya6hQhEsiiZUIC2fRxIj8/wEXCICIbr0gZ/m6gcOhE10tenvE7iy+BKY81wLWrnzos3S6FWxYtmCRes+LLhNGOKWRuQo6SyePH2OZ90xZm8oA1MuTe3V59euVNxjAt0FLkAc9TEiFhP/8CB+gA8mF+A8h1U01f4DVX55GzCH51jHI2xUS0L9GtsHoBxLPLK/NNel8zcnwG4X+UusfcfEb5hh+ffnXteCE9vRGbs2n9wYW0xA3ZicklfadmWKUtMiHYBfkMSULWnkBQr4CXxjpYOs6ygeEoA5+5B0B1SZObgZ42wWqddyyYE0NfwQAl75tfdJGqOa7OMHwBYNeatJaJK0zT2+bFaw2qWCWwAAAitBmsZJ4Q8mUwIr/wAstkdsayRXchoFk703izqzduZ5WsyXriI9cfUdMUWvm0iGHwYIrUujvz3Yjou+JLwv9df2kt7MJo8u+3P5CjEKbwlz4vkE5AHTAbgXn3+Xc/MMJLgW5cm7iX3KiGNnBpbphhwJRlb3u91NRDr0d1IR2up/z7lKxE7XPAPFe0siPMYVlIqWNSn5KqLABPeuxxbOsvMEb27/nH1LUVM8I2F95c1I3Lv1SpkhZXjs1JsmS9X7gsoTxkXyShGC2+zRJSGUbhCPo/q1XSFMHQyMWJ79FKPQSL/RpVsacN2bYwdKo4TFBw1SsKq/L1iOmqMI+4Gxnbbjojdk0ek0JIcDb4bHv1czxchF7FX1Ym8H6IpPuE8CeNKjzQ1a1wqhEu+wl1N0x3Y37ZryCCKJRkxj0FT7bOoH3L38/yMUuh/v3aCmxY4eCkykb2p6ZrYMFE044anM/nMjmbErMibfRFuCz58Io1rBlF7JfkIz0R2/5vjUMVskcdbX2mm7DntncOsWDIdg/XVmgsC9CzVzUyq4VsS/sk97lJggcddpWLNw/29egz8iLyzWHOAXCvl2fTIPkviYAOQXfVhZUQdxsyJUNFMTiALrZCmoQLMp2LmDbfbW8JQriDeR3fVz6P1sjT8C2yEDvzkCn7sh0aTBK+sx7BKH1nb4320+caQepQj4TCJtCeNXjdrVcNEnjvwlcRJwFT1pT+Y7HREbHnT71XYNh4EAAAGEQZrnSeEPJlMCK/8AKIjxcI58rm/ML255fOJW1zbznFna7lfgMQrka7OTPPsvVAV4EJXye/Uxiu9dlftmRypJqfDot3xwDe8lX/qAVf6pBkSlUsaLyBYtww/SUSa1bGl1JvrJCN7FXCCXbLd5R4PoYlPiDIm/DQH2puO0StIWmrR77Isc/J1pRvdu5+mQa/n0SEHUeM2KkoRzCznfD9zaaRO7BDtvC9SYIT0uYZxrwTjxQ7N7UERTrYG0P+vRLAhxkfohFIYl3HXyjPOvnlbUFP2oiiy6nkUFuaIyQcJawJv3GU8k4ObcKsC1cNDXjSpsyQRrxLFaCCjke4mikyt7vs0iN0bnrNWv9HXruG9zOFEOer1ggIFTsT1Eos5CXRkgja5HN4QUM6MhWpc5du/HgBIH8ANFcoo2kJpqcadw9r/0qk25X91MQSDJQiH8Hny2dQhqR+LFWEawiW753SJhn0ngZcv/mPj3mwcHv1SL9ErBqAjm4JGiDetPKYtFwANYY11OyQAAAVdBmwhJ4Q8mUwIr/wArOx5HV2505jRePGgMxptW4PGIHEszV1xGZS+flSkF+aq30AaqO7u6XK9jJsuWXTfYCRQTn1bZfFQ22DbO5DXAxK/TUmbQleCflFzeS6/czxkL4PJ8AwOs2U+oehekgCZC8gZyHHaQSaKbNJ46gTjNsLy84ACQ5uNt11TPuCPqPTuh+schdw9S+/lU/6m+EyaqGZ49wDFPiBFBYXglQQBjyP9k/rqq0xL7SiLjpe4riYg8SFUuUtOzPdWHyvxnI7Ug/0VLPGAAhgMISUnqe01d5QFf36yHpwMAHexjAZFIGQHAFautuMuEw6HzUZVzNdeHYxvEYOGkTo007bLwbuf/nxzrywGOxlRTYJLRdYI0mk0SdN3+LeTv1RIJwv21+e9rT5iFOTCgzeQoekEWXLYz0X8YLq5bVCtijP7/T7w1Ck71j0aqfrEn6wtIAAABNUGbKUnhDyZTAiv/ACcySi7VBgOid6qZNXvhh/JsllHkMLLq0yNbQTqv/Wk2EBoSKICZwFwAD0WRzhvvReCGirep1Fe4bxjm49/UR+OYrXRmHR18T0C83AUVeBk7KvDZmb/eHzuzEN4yfXucr/NWFJl+USVMY4r4UQ9CayrfEY9v6AQ6mzAdLy2UMfFxrRJ99g/Rfl8qx+m4jIZNjlrTaThzJ/3OpVmAliDfxVyg8+CVIlI31IykiwQrXcebgajG+av8XU1SfyAG5ibvwbtdSAxkGBcJWL387V+uTdY56w3KN2vBtoQpVKD2zb3yazIcATZ02upwIytNcM/rpaLCdMb1myWcikE25agzLhDhOS+4zwjYz2DnW6VY0gFBAPsphhsUMnauVVdUVHzCTSdvzEve/H8q4AAAAVdBm0pJ4Q8mUwIr/wAo+x5XKuiN1am7SkJKSMonFZDPU3f5XFcDQSs0FLVq2idfsKwuIkt1mxIq8NgMHpzofTnDHqs/WedvAmhBgL0N5azdQa5MNKG2rJ4IAvGQY/uFm3jKQAKzvhSS01gO1oIfizF817z9IShS4QK2WT0PeFPELqLSpED8eNOpVTR96vmwpk/WBKRVJdTQJzjiCQ5pgEwjtvk7KqoS0+lwXSbvIrXkYm8DignEts3DLNoLHrPjXlQmbIop76JZSyJEtB+91GrLwo6Km5GeebyA2E6qGL3xSkpppej/ruoFprSKrH60UMbrq/SK7eCo+1QFoySPQmqDFsMGiQFqvtld5BXDYdVI4yRaoyN7Y7wi83HRC6eVazuHU9OtIY3xJJApBWq1aJOsYwc38aTC3ee863Aa/4n9Lk4DAtyFYHNZjB5m2e2vk8G2Gny9YFlBAAABQEGba0nhDyZTAiv/ACoZSZQfHxhfQxEqOBQrP+L3DmgvHSJQtB1iVkcLTxm+vagLHBLG91OGnopwrr7gT/loDypIhoRxjcwAAOeg/jN4WBbXzCJtnWGGllUCSdtUZQzKOSp9iM4yX18C6jrY4Sq6R9PUV/lEGNveJR4gw4FMve7110XdEPL1O2VTdHvdqeANyaq0nLdEmtXnrzvdrFlBaUvmaR4EdlkqGkvkZKWJej8Vq+msbKa7JdbxjwZtRufiyGfD/NVqMgSrYRzw9z/a8Zwbr+9+19CxlWD5bCuAEfPmjY6kZJE2L/CQI6+tnCBTXOmWZtZMBoCLGOf7G2uAC3+kFlboh9as5WCkO6+iqXq29dyhKnsHInorRYsPlgxIXyU1Om/Kyhj1DJV0Am9WJK3Dln0zNUH0q6ZTOnZcFD36AAABYkGbjEnhDyZTAiv/ACcwdIOLRFfoGK2ZkKsvgMwG0m0qsY0vMLPSzefc+ebp/aztyF7MlsBz/fBeNtxFBcsKgR4pf65GvdfOMHah0ltZ918sMDmXUEZMeRHy/xpnWpTLeGz6uTs/7MATPmU5BgHbT/DkD8QeaZnFAzidyFCXDz2l/jaKhEdgqipbB2pH0+fQ039r05z9axxEWGmaLQjg6x9+po1o24yhkVO7m03YwWmPyCgy8cOwrvRyJkXJpRN4m8ZBS1zwY80HeN/VyMQQJSMwsTo7R1XMerSFuyx0nz+8qOuhiqykc2ohCCsXia/+kIKbJ5Vs+cbWtvkqBKIDSfU7FhAd3GjcY/xar0EVmi6wWFTugAogR3I7mTrQDdlTAqYgqO7Gn5NMXQVHu2i1zhFSdo9GjMbeGnbkJwsFbQ2XkoKRIDpuW7AewC9AEBt0Ox/Ah6dGXfXO1jl8pEApj2RFmgAAAPlBm61J4Q8mUwIr/wAlR+eW/VZ7bSrmwwMA62G05DZ7p/5FUugsSsQdonUq6abtbU5hjFr+I1lPgoiV5c3CkTQZS+K5zivdo+Ti2P4K90xXANp8dSMAu85uJIOCQn2TXbEnNDifLB+3V84ht5tj4lvTaZx317BcliV8D5v2zZQW8RO1mUbuJEBItst8E7hfE+ZXj7tfDxNZPTvtpFyUv0fH1cTg1pr2VLy0d0zQLiA58dg+GkRvR1/hs2LyifBgHcj6eTWz0vsypVn9iPXRH/unJ6i8cfFL69NO24tQ9QQB+nDFhoP2cRhkAvhHwn56n5PppBD/oxni2f8AAAE9QZvOSeEPJlMCK/8AJjAXVGf+Kj2XNJnFeKC/gr7dJDTC2ngpd4WeAHlg04GuJKnn9hAmiECxxo9qM1IYMRiB85t6gALnlm9sRqGmioyzAm18RJndc9Ah8RlpGzr+44a6ntRaPx0cIwNIWAA8buL2JP00dmfjNqEiAlCa8OdV8FQxjp1vDXsGcAGF3Qbd62KEpkimeI3wH2nuXpbDHm8/ZKOR49s5ifUCkxCoJpfp43aC0lTzh2NXpcfVw6h0QnK8G60R4ZAxOxaJB7c0nn8ixXSU2JVY24EtGMF53nxJnHfzUheewUfBOGYSxeo8oK7oUCqX4rztzDwoc2QywNqQUJUkFrqIN+sb5ecYvX24Zujn+ZzTW6UDAF3R6WdNyJyRAremgC8spSflTqygQNGfHyGkfIEEJJaFo/pBCBkAAAEWQZvvSeEPJlMCK/8AKI41fuekXG59Knbw4Y6YJritsh9VtQgc3QKvVmxrzzo7f4aXn8N74eyP4b2lV1Z2Q+rohxps7EHTkOY9jLdqxI3MXe7je4g2qepz71+hY+jYdX+9LO0kA0Zg3NfyAlIRX7k6c/YHAZNtNaGZgTBMqiPgmEjiJH9Luk7shbgr+srfwiYwBX9rdS3fQNNFwcT8orQC+F60LAY9+GbFo2Sw3Ld4Tw9jq9yJtrY8RtHAdzytyek/mv2+j2TbTvAQKbbCYtdC8E/KtR4V5ZTSScr5Wb63vmbw7UpddEXYvl55pARyyvMxWNSh3Li4GF8Jk5JBi5B5ASQwxCMYpX5hkAMc+d8tl2bT+IEvUTsAAAElQZoQSeEPJlMCK/8AJIAzFZs00JJ0yfm8CZiew4xWdArLklEvBVXo/+ukPLu3XP9HFOfsme3T6BJEKmPPgZw/Lxnraq6Sl2kLVW19YU1qmqgfv+80LkZaWU5gRAH4hqyo3bFYcbuY2SC3IW5Wm69gtYyAXOdbAYSEHA16fvCeRQjHEsxKVndJdrRAlrGHsKgUBQ3Up/ZXIy1vkdFOfKSjpuZnswkuqr8NZI5tJ/dnBSErBTNWPaNwWV7nNomC0EYVGo+geGBhLXzaLw0UAOCYGjiPc3803BDw1GLoLIXjrIFJxwRfBNIAXYZAglu30oYzhpAfRWSprkeULMWYJTlWvbUQ5CNewSZssuDWIRAc3w8AcFaywwn+YSGhtR8VI1OGjYkfBbcAAAD8QZoxSeEPJlMCK/8AJdokjCUETRw/nciVPtaZQSBP/VxAQSITASEzlJBl9Na1r0DJhLOz279+KQLtl/xHZ8vAKc528mTMTqtWs4sFbeVgHWyBpHcHEtgTzjIqEinp/MPuUXF5poo8YLSSMFn9Ozx2FbU5/Kh9A39oN9NHQflVxV1NA6yT/84HHyfMtfdSMS8KTvAEE2lDs14VQayNs5ctjXboQT7xMBf5OLj6thhPvgaDrFB2o/PV9ouK147lruWTP2mkoA9oDIMYW1pcBx4yyV/t9GOPZ3aXneMUb2fFmUCX43BjXfUDMaa4GO2/Ankj3UEQwDxA7ZlNUQK2AAAA4UGaUknhDyZTAiv/ACJHv33I08bkhybYiJ/JiiheW5zMPBu4n5CxGr3frhE7TkLh0vPktM8m/AhaDiJisdk5QXNe/4WmxEDSAyaVi4eUVu0iHT2ly/KNTGqiORqA2oKpTjh84nYbrpXwnGv9SOf/34Z06xN6Yo3t35UZrP8nlcs/63GtnEmnUwVZHBYfPM6bs5M5AeBfAQ/9mIqu7vnEst+5O2wpPjzdItjwGCZ2ApHVjGnYYFomlA9nm6AXnxNIWHIsDgxCk3zx+6QbXipu/CWLG1Wf0WIbt4C0JPVl3TEb0QAAAMlBmnNJ4Q8mUwIr/wAVV64OfTKmlktYOqZHH1W1DhPy/X/6sD4T6hRdzfOgNtTOX2IckRJHshfBQVkJIzns079io6kpJFCcS3VD4zrWCn/dNaGV0kWTpFBRuusfn8F0C0R/EhsQeyTsdZftEkLGb5tq+nrir3vfmeb7rjmWJRXkIrTEKu8pIuAd+4FBGp8ARgGe80Jqpp//s1433HqBFqXsIFJTmU8j/toF9HyueI1Ea4uvsQ6NANGcYCbOAKCmbNiwABMCFaiUTMAAAAPSbW9vdgAAAGxtdmhkAAAAAHwlsIB8JbCAAAAD6AAAAyAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAv10cmFrAAAAXHRraGQAAAAPfCWwgHwlsIAAAAABAAAAAAAAAyAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAY4AAAGGAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAMgAAAAAgABAAAAAAJ1bWRpYQAAACBtZGhkAAAAAHwlsIB8JbCAAAAAGQAAABRVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAACIG1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAeBzdGJsAAAAtHN0c2QAAAAAAAAAAQAAAKRhdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAY4BhgBIAAAASAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGP//AAAAMmF2Y0MBZAAV/+EAGWdkABWs2UGQz6mhAAADAAEAAAMAMg8WLZYBAAZo6+PLIsAAAAAcdXVpZGtoQPJfJE/FujmlG88DI/MAAAAAAAAAGHN0dHMAAAAAAAAAAQAAABQAAAABAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAYY3R0cwAAAAAAAAABAAAAFAAAAAIAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAZHN0c3oAAAAAAAAAAAAAABQAAA05AAACqQAAAl8AAAITAAACiwAAAh8AAAIvAAABiAAAAVsAAAE5AAABWwAAAUQAAAFmAAAA/QAAAUEAAAEaAAABKQAAAQAAAADlAAAAzQAAAGBzdGNvAAAAAAAAABQAAAAsAAANZQAAEA4AABJtAAAUgAAAFwsAABkqAAAbWQAAHOEAAB48AAAfdQAAINAAACIUAAAjegAAJHcAACW4AAAm0gAAJ/sAACj7AAAp4AAAAGF1ZHRhAAAAWW1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAALGlsc3QAAAAkqXRvbwAAABxkYXRhAAAAAQAAAABMYXZmNTIuMTExLjA=\">\n\n\n\n## HTML\n\nPython objects can declare HTML representations that will be displayed in the Notebook. If you have some HTML you want to display, simply use the `HTML` class.\n\n\n```\nfrom IPython.display import HTML\n```\n\n\n```\ns = \"\"\"<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\"\"\"\n```\n\n\n```\nh = HTML(s); h\n```\n\n\n\n\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n\n\n\nPandas makes use of this capability to allow `DataFrames` to be represented as HTML tables.\n\n\n```\nimport pandas\n```\n\nHere is a small amount of stock data for APPL:\n\n\n```\n%%file data.csv\nDate,Open,High,Low,Close,Volume,Adj Close\n2012-06-01,569.16,590.00,548.50,584.00,14077000,581.50\n2012-05-01,584.90,596.76,522.18,577.73,18827900,575.26\n2012-04-02,601.83,644.00,555.00,583.98,28759100,581.48\n2012-03-01,548.17,621.45,516.22,599.55,26486000,596.99\n2012-02-01,458.41,547.61,453.98,542.44,22001000,540.12\n2012-01-03,409.40,458.24,409.00,456.48,12949100,454.53\n```\n\n    Writing data.csv\n\n\nRead this as into a `DataFrame`:\n\n\n```\ndf = pandas.read_csv('data.csv')\n```\n\nAnd view the HTML representation:\n\n\n```\ndf\n```\n\n\n\n\n<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Date</th>\n      <th>Open</th>\n      <th>High</th>\n      <th>Low</th>\n      <th>Close</th>\n      <th>Volume</th>\n      <th>Adj Close</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td> 2012-06-01</td>\n      <td> 569.16</td>\n      <td> 590.00</td>\n      <td> 548.50</td>\n      <td> 584.00</td>\n      <td> 14077000</td>\n      <td> 581.50</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td> 2012-05-01</td>\n      <td> 584.90</td>\n      <td> 596.76</td>\n      <td> 522.18</td>\n      <td> 577.73</td>\n      <td> 18827900</td>\n      <td> 575.26</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td> 2012-04-02</td>\n      <td> 601.83</td>\n      <td> 644.00</td>\n      <td> 555.00</td>\n      <td> 583.98</td>\n      <td> 28759100</td>\n      <td> 581.48</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td> 2012-03-01</td>\n      <td> 548.17</td>\n      <td> 621.45</td>\n      <td> 516.22</td>\n      <td> 599.55</td>\n      <td> 26486000</td>\n      <td> 596.99</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td> 2012-02-01</td>\n      <td> 458.41</td>\n      <td> 547.61</td>\n      <td> 453.98</td>\n      <td> 542.44</td>\n      <td> 22001000</td>\n      <td> 540.12</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td> 2012-01-03</td>\n      <td> 409.40</td>\n      <td> 458.24</td>\n      <td> 409.00</td>\n      <td> 456.48</td>\n      <td> 12949100</td>\n      <td> 454.53</td>\n    </tr>\n  </tbody>\n</table>\n<p>6 rows \u00d7 7 columns</p>\n</div>\n\n\n\n## External sites\n\nYou can even embed an entire page from another site in an iframe; for example this is today's Wikipedia\npage for mobile users:\n\n\n```\nfrom IPython.display import IFrame\nIFrame('http://en.mobile.wikipedia.org/?useformat=mobile', width=700, height=350)\n```\n\n\n\n\n\n\n\n\n\n\n## LaTeX\n\nAnd we also support the display of mathematical expressions typeset in LaTeX, which is rendered\nin the browser thanks to the [MathJax library](http://mathjax.org).\n\n\n```\nfrom IPython.display import Math\nMath(r'F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx')\n```\n\n\n\n\n$$F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx$$\n\n\n\nWith the `Latex` class, you have to include the delimiters yourself.  This allows you to use other LaTeX modes such as `eqnarray`:\n\n\n```\nfrom IPython.display import Latex\nLatex(r\"\"\"\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\"\"\")\n```\n\n\n\n\n\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\n\n\n\nOr you can enter latex directly with the `%%latex` cell magic:\n\n\n```latex\n%%latex\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n```\n\n\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n\n", "meta": {"hexsha": "4fda1e97eaa788cdf2f92443cb3734e7bdaf1646", "size": 236624, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/notebooks/Part 5 - Rich Display System.ipynb", "max_stars_repo_name": "ptone/ipython", "max_stars_repo_head_hexsha": "b91d6a658d4526746dcbfb62e653d71c5d84eee9", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-02-10T18:00:31.000Z", "max_stars_repo_stars_event_max_datetime": "2015-05-01T02:53:46.000Z", "max_issues_repo_path": "examples/notebooks/Part 5 - Rich Display System.ipynb", "max_issues_repo_name": "khinsen/ipython", "max_issues_repo_head_hexsha": "dfd5cb1d3e34048593ba537dacdbef08fe766624", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/notebooks/Part 5 - Rich Display System.ipynb", "max_forks_repo_name": "khinsen/ipython", "max_forks_repo_head_hexsha": "dfd5cb1d3e34048593ba537dacdbef08fe766624", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-22T13:52:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T13:52:12.000Z", "avg_line_length": 197.3511259383, "max_line_length": 79058, "alphanum_fraction": 0.8736941308, "converted": true, "num_tokens": 62704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15817436465343707, "lm_q2_score": 0.07921033008659957, "lm_q1q2_score": 0.012529043635436918}}
{"text": "# jpy-flette\n\n\n\n*jpy-flette* is a lightweight (~150 lines), no-configuration, python static website\ngenerator which uses jupyter notebooks as input. It's fantastic for quickly\npresenting scientific projects, software documentation, or just to share your\nthoughts with the world.\n\n> Give it a folder of `.ipynb` files and **paf!** \u2014 website.\n\n## installation\n\n\nInstall *jpy-flette* with pip:\n\n``` bash\npip install jpy-flette\n```\n\nYou could also download or clone the source code from the [repository](https://github.com/r4lv/jpy-flette):\n\n``` bash\ngit clone \"https://github.com/r4lv/jpy-flette\"\ncd \"jpy-flette\"\npython setup.py install\n```\n\n\n## usage\n\n\n*jpy-flette* transforms a directory full of `.ipynb` jupyter notebooks\ninto a website with multiple pages. Let's assume the following directory\nstructure:\n\n``` text\n~/my/directory\n     \u2514\u2500\u2500 notebooks\n         \u251c\u2500\u2500 00.index.ipynb\n         \u2514\u2500\u2500 01.advanced-usage.ipynb\n```\n\nAfter calling\n\n``` bash\njpy-flette ~/my/directory/notebooks\n```\n\nyou would obtain\n\n``` text\n~/my/directory\n     \u251c\u2500\u2500 docs\n     \u2502   \u251c\u2500\u2500 index.html\n     \u2502   \u251c\u2500\u2500 advanced-usage.html\n     \u2502   \u2514\u2500\u2500 static\n     \u2502       \u251c\u2500\u2500 style.css\n     \u2502       \u2514\u2500\u2500 script.js\n     \u2514\u2500\u2500 notebooks\n         \u251c\u2500\u2500 00.index.ipynb\n         \u2514\u2500\u2500 01.advanced-usage.ipynb\n```\n\n`~/my/directory/docs` is then ready to be published!\n\n\n\n\n## demo\n\nThis website is actually built by *jpy-flette*! Look:\n\n\n```python\nimport jpy_flette\njpy_flette.__version__\n```\n\n\n\n\n    '0.1.0'\n\n\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nplt.figure(dpi=100)\nx = np.linspace(-20, 20, 300)\n\nplt.plot(x, np.sin(x)*x, color=\"#D74E40\")\nplt.plot(x, np.sin(x),   color=\"#61862F\");\n```\n\nThe *MathJax* library is also included, so you can $\\LaTeX$ right away and type some\n\n\\begin{align}\na_w e^{s_{\\text{ome}}} = \\mathbf F \\cdot \\mathcal{O}(rm) \\cup l_a\n\\end{align}\n", "meta": {"hexsha": "2cf990a9a7c8cf4027a219bc26757ac9f10e688e", "size": 46115, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/notebooks/index.ipynb", "max_stars_repo_name": "IMTorgDemo/jpy-flette", "max_stars_repo_head_hexsha": "e2b656e1bd03de791e2c4e263ec4b8efc9bd8448", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-05-18T04:21:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T17:51:52.000Z", "max_issues_repo_path": "docs/notebooks/index.ipynb", "max_issues_repo_name": "IMTorgDemo/jpy-flette", "max_issues_repo_head_hexsha": "e2b656e1bd03de791e2c4e263ec4b8efc9bd8448", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-08T09:00:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-08T09:01:20.000Z", "max_forks_repo_path": "docs/notebooks/index.ipynb", "max_forks_repo_name": "IMTorgDemo/jpy-flette", "max_forks_repo_head_hexsha": "e2b656e1bd03de791e2c4e263ec4b8efc9bd8448", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-11-21T03:40:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-12T10:46:00.000Z", "avg_line_length": 256.1944444444, "max_line_length": 41988, "alphanum_fraction": 0.9243413206, "converted": true, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.144148864062875, "lm_q2_score": 0.08632347541098986, "lm_q1q2_score": 0.01244343092245371}}
{"text": "# Setup\n\n\n```python\n%matplotlib inline\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\n```\n\n\n```python\ndate_filename = \"2018-03-01_2018-03-31\"\n```\n\n\n```python\ndata = pd.read_csv(\"articles_\" + date_filename + \".csv\", index_col=\"id\", \\\n                   parse_dates=[\"published\", \"discovered\"])\ndata.head()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>publisher_name</th>\n      <th>publisher_id</th>\n      <th>mins_as_lead</th>\n      <th>mins_on_front</th>\n      <th>num_articles_on_front</th>\n      <th>fb_brand_page</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>4296661b7ec493a798bf313f1133cd1176052f30</th>\n      <td>https://www.thetimes.co.uk/article/national-ge...</td>\n      <td>National Geographic Traveller reveals photo co...</td>\n      <td>2018-03-01 02:44:05.240</td>\n      <td>2018-03-01</td>\n      <td>4</td>\n      <td>0.032796</td>\n      <td>2018-03-01T23:14:09.837Z</td>\n      <td>0</td>\n      <td>1</td>\n      <td>3</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>1280</td>\n      <td>282.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>a995ae644e9cbe39a5b4a41143466399751bdf5e</th>\n      <td>https://www.thetimes.co.uk/article/child-safet...</td>\n      <td>Child safety fears over director at charity fo...</td>\n      <td>2018-03-01 00:09:18.121</td>\n      <td>2018-03-01</td>\n      <td>4</td>\n      <td>0.032787</td>\n      <td>2018-03-01T13:33:06.906Z</td>\n      <td>0</td>\n      <td>1</td>\n      <td>3</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>1435</td>\n      <td>270.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>125.0</td>\n    </tr>\n    <tr>\n      <th>5e8654da9845e74a797af5a1f8fa076b47c0b6f5</th>\n      <td>https://www.thetimes.co.uk/article/mosley-must...</td>\n      <td>Mosley must face up to his poisonous past</td>\n      <td>2018-03-01 00:09:10.933</td>\n      <td>2018-03-01</td>\n      <td>25</td>\n      <td>0.065574</td>\n      <td>2018-03-01T09:29:06.479Z</td>\n      <td>4</td>\n      <td>3</td>\n      <td>18</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>1435</td>\n      <td>270.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>125.0</td>\n    </tr>\n    <tr>\n      <th>55c5ece98c02b70430bd19a2087558eaf0288f37</th>\n      <td>https://www.thetimes.co.uk/article/skive-off-s...</td>\n      <td>Skive off school and enjoy sledging, says head...</td>\n      <td>2018-03-01 00:09:22.291</td>\n      <td>2018-03-01</td>\n      <td>67</td>\n      <td>0.163845</td>\n      <td>2018-03-01T08:28:11.729Z</td>\n      <td>17</td>\n      <td>37</td>\n      <td>13</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>1435</td>\n      <td>270.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>125.0</td>\n    </tr>\n    <tr>\n      <th>19b8c2e31074fa50f06010b8f00a9899994baea1</th>\n      <td>https://www.thetimes.co.uk/article/pop-review-...</td>\n      <td>Pop review: Yonaka at the Garage, N5</td>\n      <td>2018-03-01 17:05:18.708</td>\n      <td>2018-03-01</td>\n      <td>128</td>\n      <td>0.541427</td>\n      <td>2018-03-01T21:21:14.439Z</td>\n      <td>9</td>\n      <td>115</td>\n      <td>4</td>\n      <td>The Times</td>\n      <td>thetimes_co_uk</td>\n      <td>0</td>\n      <td>1855</td>\n      <td>332.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>6435</td>\n      <td>126.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n# Response Score\n\nThe response score is a number between 0 and 50 that indicates the level of response to an article.\n\n\n\nPerhaps in the future we may choose to include other factors, but for now we just include engagements on Facebook. The maximum score of 50 should be achieved by an article that does really well compared with others.\n\n\n```python\npd.options.display.float_format = '{:.2f}'.format\ndata.fb_engagements.describe([0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count    146484.00\n    mean       1519.93\n    std       15132.24\n    min           0.00\n    50%          25.00\n    75%         258.00\n    90%        1597.00\n    95%        4350.85\n    99%       27468.06\n    99.5%     51204.43\n    99.9%    164145.49\n    max     2915056.00\n    Name: fb_engagements, dtype: float64\n\n\n\nThere's 2 articles with more than 1 million engagements this month.\n\n\n```python\ndata[data.fb_engagements > 1000000]\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>publisher_name</th>\n      <th>publisher_id</th>\n      <th>mins_as_lead</th>\n      <th>mins_on_front</th>\n      <th>num_articles_on_front</th>\n      <th>fb_brand_page</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>b8a75ce80f2c523e6ba16bb3b6439bdf8c37b047</th>\n      <td>https://www.theguardian.com/science/2018/mar/1...</td>\n      <td>Stephen Hawking: modern cosmology's brightest ...</td>\n      <td>2018-03-14 03:49:11.754</td>\n      <td>2018-03-14 03:46:33</td>\n      <td>2915056</td>\n      <td>203793.62</td>\n      <td>2018-03-14T14:30:08.370Z</td>\n      <td>195155</td>\n      <td>2321470</td>\n      <td>398431</td>\n      <td>The Guardian</td>\n      <td>theguardian_com</td>\n      <td>519</td>\n      <td>1259</td>\n      <td>107.00</td>\n      <td>True</td>\n      <td>7925040.00</td>\n      <td>2018-03-14T03:49:46.000Z</td>\n      <td>142</td>\n      <td>2007.00</td>\n    </tr>\n    <tr>\n      <th>3a34a2b4590e487def08b1918783a5d8dd39f73a</th>\n      <td>http://www.bbc.co.uk/news/uk-43396008</td>\n      <td>Physicist Stephen Hawking dies aged 76</td>\n      <td>2018-03-14 03:49:13.874</td>\n      <td>2018-03-14 03:47:02</td>\n      <td>2016997</td>\n      <td>8610.41</td>\n      <td>2018-03-14T04:12:06.080Z</td>\n      <td>141418</td>\n      <td>1517206</td>\n      <td>358373</td>\n      <td>BBC</td>\n      <td>bbc_co_uk</td>\n      <td>545</td>\n      <td>1837</td>\n      <td>59.00</td>\n      <td>True</td>\n      <td>46116240.00</td>\n      <td>2018-03-14T03:50:08.000Z</td>\n      <td>96</td>\n      <td>66.00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndata.fb_engagements.mode()\n```\n\n\n\n\n    0    0\n    dtype: int64\n\n\n\n*november* Going back to the enagement counts, we see the mean is 1,117, mode is zero, median is 24, 90th percentile is 1,453, 99th percentile is 21,166, 99.5th percentile is 33,982. The standard deviation is 8,083, significantly higher than the mean, so this is not a normal distribution. \n\n*december* Going back to the enagement counts, we see the mean is 1,106, mode is zero, median is 24, 90th percentile is 1,545, 99th percentile is 20,228, 99.5th percentile is 32,446. The standard deviation is 9,852, significantly higher than the mean, so this is not a normal distribution. \n\n*january 2018* Going back to the enagement counts, we see the mean is 1,108, mode is zero, median is 26, 90th percentile is 1,621, 99th percentile is 19,918, 99.5th percentile is 32,935. The standard deviation is 8,278, significantly higher than the mean, so this is not a normal distribution. \n\n*february 2018* Going back to the enagement counts, we see the mean is 1,237, mode is zero, median is 25, 90th percentile is 1,453, 99th percentile is 23,172, 99.5th percentile is 38,692. The standard deviation is 11,019, significantly higher than the mean, so this is not a normal distribution. \n\n*march 2018* Going back to the enagement counts, we see the mean is 1,519, mode is zero, median is 25, 90th percentile is 1,597, 99th percentile is 27,468, 99.5th percentile is 51,204. The standard deviation is 15,132, significantly higher than the mean, so this is not a normal distribution. \n\nKey publishers stats\n\n\n```python\ndata.groupby(\"publisher_id\").agg({'url': 'count', 'fb_engagements': ['sum', 'median', 'mean']})\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th>url</th>\n      <th colspan=\"3\" halign=\"left\">fb_engagements</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>count</th>\n      <th>sum</th>\n      <th>median</th>\n      <th>mean</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>38</td>\n      <td>78751</td>\n      <td>1665.50</td>\n      <td>2072.39</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>11963</td>\n      <td>11962778</td>\n      <td>35.00</td>\n      <td>999.98</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>2737</td>\n      <td>7662297</td>\n      <td>173.00</td>\n      <td>2799.52</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>66</td>\n      <td>36151</td>\n      <td>260.50</td>\n      <td>547.74</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>1452</td>\n      <td>4494915</td>\n      <td>177.50</td>\n      <td>3095.67</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>4368</td>\n      <td>34823949</td>\n      <td>589.50</td>\n      <td>7972.52</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>25800</td>\n      <td>16802567</td>\n      <td>19.00</td>\n      <td>651.26</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>579</td>\n      <td>170498</td>\n      <td>35.00</td>\n      <td>294.47</td>\n    </tr>\n    <tr>\n      <th>evolvepolitics_com</th>\n      <td>82</td>\n      <td>342679</td>\n      <td>2473.50</td>\n      <td>4179.01</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>5340</td>\n      <td>21348445</td>\n      <td>98.00</td>\n      <td>3997.84</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>4913</td>\n      <td>362496</td>\n      <td>4.00</td>\n      <td>73.78</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>2564</td>\n      <td>18008340</td>\n      <td>849.00</td>\n      <td>7023.53</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>5590</td>\n      <td>4788850</td>\n      <td>28.00</td>\n      <td>856.68</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>471</td>\n      <td>515637</td>\n      <td>101.00</td>\n      <td>1094.77</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>4229</td>\n      <td>2780672</td>\n      <td>65.00</td>\n      <td>657.52</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>165</td>\n      <td>3072</td>\n      <td>11.00</td>\n      <td>18.62</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>10148</td>\n      <td>5902958</td>\n      <td>28.00</td>\n      <td>581.69</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>2017</td>\n      <td>10900196</td>\n      <td>447.00</td>\n      <td>5404.16</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>489</td>\n      <td>95347</td>\n      <td>23.00</td>\n      <td>194.98</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>1661</td>\n      <td>12637764</td>\n      <td>663.00</td>\n      <td>7608.53</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>5016</td>\n      <td>25629208</td>\n      <td>225.00</td>\n      <td>5109.49</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>264</td>\n      <td>93065</td>\n      <td>170.50</td>\n      <td>352.52</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>43</td>\n      <td>50915</td>\n      <td>341.00</td>\n      <td>1184.07</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>6679</td>\n      <td>3915748</td>\n      <td>15.00</td>\n      <td>586.28</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>2322</td>\n      <td>2359592</td>\n      <td>353.00</td>\n      <td>1016.19</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>124</td>\n      <td>306273</td>\n      <td>278.50</td>\n      <td>2469.94</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>4501</td>\n      <td>1448183</td>\n      <td>25.00</td>\n      <td>321.75</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>258</td>\n      <td>358003</td>\n      <td>453.50</td>\n      <td>1387.61</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>8409</td>\n      <td>13987337</td>\n      <td>124.00</td>\n      <td>1663.38</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>9760</td>\n      <td>405336</td>\n      <td>1.00</td>\n      <td>41.53</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>23764</td>\n      <td>19059313</td>\n      <td>0.00</td>\n      <td>802.02</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>255</td>\n      <td>292326</td>\n      <td>44.00</td>\n      <td>1146.38</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>417</td>\n      <td>1022159</td>\n      <td>58.00</td>\n      <td>2451.22</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\n\nnon_zero_fb_enagagements = data.fb_engagements[data.fb_engagements > 0]\n```\n\nThat's a bit better, but still way too clustered at the low end. Let's look at a log normal distribution.\n\n\n```python\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\nninety = data.fb_engagements.quantile(.90)\nninetyfive = data.fb_engagements.quantile(.95)\nninetynine = data.fb_engagements.quantile(.99)\n\nplt.figure(figsize=(12,4.5))\nplt.hist(np.log(non_zero_fb_enagagements + median), bins=50)\nplt.axvline(np.log(mean), linestyle=':', label=f'Mean ({mean:,.0f})', color='green')\nplt.axvline(np.log(median), label=f'Median ({median:,.0f})', color='green')\nplt.axvline(np.log(ninety), linestyle='--', label=f'90% percentile ({ninety:,.0f})', color='red')\nplt.axvline(np.log(ninetyfive), linestyle='-.', label=f'95% percentile ({ninetyfive:,.0f})', color='red')\nplt.axvline(np.log(ninetynine), linestyle=':', label=f'99% percentile ({ninetynine:,.0f})', color='red')\nleg = plt.legend()\n\n```\n\n\n```python\neng = data.fb_engagements[(data.fb_engagements < 5000)]\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\nninety = data.fb_engagements.quantile(.90)\nninetyfive = data.fb_engagements.quantile(.95)\nninetynine = data.fb_engagements.quantile(.99)\n\nplt.figure(figsize=(15,7))\nplt.hist(eng, bins=50)\nplt.title(\"Article count by engagements\")\nplt.axvline(median, label=f'Median ({median:,.0f})', color='green')\nplt.axvline(mean, linestyle=':', label=f'Mean ({mean:,.0f})', color='green')\nplt.axvline(ninety, linestyle='--', label=f'90% percentile ({ninety:,.0f})', color='red')\nplt.axvline(ninetyfive, linestyle='-.', label=f'95% percentile ({ninetyfive:,.0f})', color='red')\n# plt.axvline(ninetynine, linestyle=':', label=f'99% percentile ({ninetynine:,.0f})', color='red')\nleg = plt.legend()\n\n```\n\n\n```python\nlog_engagements = (non_zero_fb_enagagements\n                   .clip_upper(data.fb_engagements.quantile(.999))\n                   .apply(lambda x: np.log(x + median))\n                  )\nlog_engagements.describe()\n```\n\n\n\n\n    count   119204.00\n    mean         5.03\n    std          1.80\n    min          3.26\n    25%          3.53\n    50%          4.42\n    75%          6.10\n    max         12.01\n    Name: fb_engagements, dtype: float64\n\n\n\nUse standard feature scaling to bring that to a 1 to 50 range\n\n\n\n```python\ndef scale_log_engagements(engagements_logged):\n    return np.ceil(\n        50 * (engagements_logged - log_engagements.min()) / (log_engagements.max() - log_engagements.min())\n    )\n\ndef scale_engagements(engagements):\n    return scale_log_engagements(np.log(engagements + median))\n\nscaled_non_zero_engagements = scale_log_engagements(log_engagements)\nscaled_non_zero_engagements.describe()\n```\n\n\n\n\n    count   119204.00\n    mean        10.61\n    std         10.29\n    min          0.00\n    25%          2.00\n    50%          7.00\n    75%         17.00\n    max         50.00\n    Name: fb_engagements, dtype: float64\n\n\n\n\n```python\n# add in the zeros, as zero\nscaled_engagements = pd.concat([scaled_non_zero_engagements, data.fb_engagements[data.fb_engagements == 0]])\n```\n\n\n```python\nproposed = pd.DataFrame({\"fb_engagements\": data.fb_engagements, \"response_score\": scaled_engagements})\nproposed.response_score.plot.hist(bins=50)\n```\n\nLooks good to me, lets save that.\n\n\n```python\ndata[\"response_score\"] = proposed.response_score\n```\n\n### Proposal\n\nThe maximum of 50 points is awarded when the engagements are greater than the 99.9th percentile, rolling over the last month. \n\ni.e. where $limit$ is the 99.5th percentile of engagements calculated over the previous month, the response score for article $a$ is:\n\n\\begin{align}\nbasicScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   \\log(\\min(engagements_a,limit) + median(engagements))      & \\text{if } engagements_a > 0\n\\end{cases} \\\\\nresponseScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   50 \\cdot \\frac{basicScore_a - \\min(basicScore)}{\\max(basicScore) - \\min(basicScore)}       & \\text{if } engagements_a > 0\n\\end{cases} \\\\\n\\\\\n\\text{The latter equation can be expanded to:} \\\\\nresponseScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   50 \\cdot \n   \\frac{\\log(\\min(engagements_a,limit) + median(engagements)) - \\log(1 + median(engagements))}\n   {\\log(limit + median(engagements)) - \\log(1 + median(engagements))}       & \\text{if } engagements_a > 0\n\\end{cases} \\\\\n\\end{align}\n\n# Promotion Score\n\nThe aim of the promotion score is to indicate how important the article was to the publisher, by tracking where they chose to promote it. This is a number between 0 and 50 comprised of:\n\n- 20 points based on whether the article was promoted as the \"lead\" story on the publisher's home page\n- 15 points based on how long the article was promoted anywhere on the publisher's home page\n- 15 points based on whether the article was promoted on the publisher's main facebook brand page\n\nThe first two should be scaled by the popularity/reach of the home page, for which we use the alexa page rank as a proxy.\n\nThe last should be scaled by the popularity/reach of the brand page, for which we use the number of likes the brand page has.\n\n### Lead story (20 points)\n\n\n```python\ndata.mins_as_lead.describe([0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count   146484.00\n    mean         9.15\n    std         90.17\n    min          0.00\n    50%          0.00\n    75%          0.00\n    90%          0.00\n    95%          0.00\n    99%        275.00\n    99.5%      579.00\n    99.9%     1174.65\n    max       7504.00\n    Name: mins_as_lead, dtype: float64\n\n\n\nAs expected, the vast majority of articles don't make it as lead. Let's explore how long typically publishers put something as lead for.\n\n\n```python\nlead_articles = data[data.mins_as_lead > 0]\n```\n\n\n```python\nlead_articles.mins_as_lead.describe([0.25, 0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count   4086.00\n    mean     328.16\n    std      432.24\n    min        4.00\n    25%       84.00\n    50%      179.00\n    75%      433.50\n    90%      839.50\n    95%     1068.00\n    99%     1594.15\n    99.5%   1962.30\n    99.9%   5636.62\n    max     7504.00\n    Name: mins_as_lead, dtype: float64\n\n\n\n\n```python\nlead_articles.mins_as_lead.plot.hist(bins=50)\n```\n\nFor lead, it's a  significant thing for an article to be lead at all, so although we want to penalise articles that were lead for a very short time, mostly we want to score the maximum even if it wasn't lead for ages. So we'll give maximum points when something has been lead for an hour.\n\n\n```python\nlead_articles.mins_as_lead.clip_upper(60).plot.hist(bins=50)\n```\n\nWe also want to scale this by the alexa page rank, such that the maximum score of 20 points is for an article that was on the front for 4 hours for the most popular site.\n\nSo lets explore the alexa nunbers.\n\n\n```python\nalexa_ranks = data.groupby(by=\"publisher_id\").alexa_rank.mean().sort_values()\nalexa_ranks\n```\n\n\n\n\n    publisher_id\n    bbc_co_uk                               96\n    cnn_com                                105\n    nytimes_com                            120\n    theguardian_com                        142\n    buzzfeed_com                           147\n    dailymail_co_uk                        158\n    washingtonpost_com                     191\n    huffingtonpost_com                     215\n    foxnews_com                            285\n    rt_com                                 365\n    telegraph_co_uk                        370\n    independent_co_uk                      386\n    reuters_com                            497\n    npr_org                                594\n    lemonde_fr                             618\n    mirror_co_uk                           706\n    nbcnews_com                            826\n    breitbart_com                          994\n    ft_com                                1596\n    economist_com                         1825\n    indy100_com                           5014\n    thetimes_co_uk                        6435\n    newstatesman_com                     12769\n    thecanary_co                         15686\n    propublica_org                       16066\n    yournewswire_com                     22568\n    order-order_com                      32515\n    anotherangryvoice_blogspot_co_uk     77827\n    westmonster_com                      97775\n    evolvepolitics_com                  119412\n    skwawkbox_org                       152475\n    libdemvoice_org                     344992\n    brexitcentral_com                   469149\n    Name: alexa_rank, dtype: int64\n\n\n\n\n```python\nalexa_ranks.plot.bar(figsize=[10,5])\n```\n\nLet's try the simple option first: just divide the number of minutes as lead by the alexa rank. What's the scale of numbers we get then.\n\n\n```python\nlead_proposal_1 = lead_articles.mins_as_lead.clip_upper(60) / lead_articles.alexa_rank\nlead_proposal_1.plot.hist()\n```\n\nLooks like there's too much of a cluster around 0. Have we massively over penalised the publishers with a high alexa rank?\n\n\n```python\nlead_proposal_1.groupby(data.publisher_id).mean().plot.bar(figsize=[10,5])\n```\n\nYes. Let's try taking the log of the alexa rank and see if that looks better.\n\n\n```python\nlead_proposal_2 = (lead_articles.mins_as_lead.clip_upper(60) / np.log(lead_articles.alexa_rank))\nlead_proposal_2.plot.hist()\n```\n\n\n```python\nlead_proposal_2.groupby(data.publisher_id).describe()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>25%</th>\n      <th>50%</th>\n      <th>75%</th>\n      <th>max</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>38.00</td>\n      <td>5.33</td>\n      <td>0.00</td>\n      <td>5.33</td>\n      <td>5.33</td>\n      <td>5.33</td>\n      <td>5.33</td>\n      <td>5.33</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>108.00</td>\n      <td>12.87</td>\n      <td>1.50</td>\n      <td>2.19</td>\n      <td>13.15</td>\n      <td>13.15</td>\n      <td>13.15</td>\n      <td>13.15</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>213.00</td>\n      <td>8.35</td>\n      <td>1.34</td>\n      <td>0.72</td>\n      <td>8.69</td>\n      <td>8.69</td>\n      <td>8.69</td>\n      <td>8.69</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>49.00</td>\n      <td>4.14</td>\n      <td>1.16</td>\n      <td>0.69</td>\n      <td>4.59</td>\n      <td>4.59</td>\n      <td>4.59</td>\n      <td>4.59</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>314.00</td>\n      <td>11.69</td>\n      <td>1.36</td>\n      <td>1.80</td>\n      <td>12.02</td>\n      <td>12.02</td>\n      <td>12.02</td>\n      <td>12.02</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>210.00</td>\n      <td>11.94</td>\n      <td>2.64</td>\n      <td>0.86</td>\n      <td>12.89</td>\n      <td>12.89</td>\n      <td>12.89</td>\n      <td>12.89</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>150.00</td>\n      <td>11.47</td>\n      <td>1.62</td>\n      <td>0.99</td>\n      <td>11.85</td>\n      <td>11.85</td>\n      <td>11.85</td>\n      <td>11.85</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>66.00</td>\n      <td>7.62</td>\n      <td>1.35</td>\n      <td>0.53</td>\n      <td>7.99</td>\n      <td>7.99</td>\n      <td>7.99</td>\n      <td>7.99</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>101.00</td>\n      <td>10.54</td>\n      <td>0.79</td>\n      <td>2.65</td>\n      <td>10.61</td>\n      <td>10.61</td>\n      <td>10.61</td>\n      <td>10.61</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>102.00</td>\n      <td>7.54</td>\n      <td>1.65</td>\n      <td>0.54</td>\n      <td>8.14</td>\n      <td>8.14</td>\n      <td>8.14</td>\n      <td>8.14</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>162.00</td>\n      <td>10.87</td>\n      <td>1.35</td>\n      <td>0.93</td>\n      <td>11.17</td>\n      <td>11.17</td>\n      <td>11.17</td>\n      <td>11.17</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>144.00</td>\n      <td>9.69</td>\n      <td>1.43</td>\n      <td>0.84</td>\n      <td>10.07</td>\n      <td>10.07</td>\n      <td>10.07</td>\n      <td>10.07</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>138.00</td>\n      <td>6.14</td>\n      <td>1.68</td>\n      <td>1.17</td>\n      <td>5.87</td>\n      <td>7.04</td>\n      <td>7.04</td>\n      <td>7.04</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>233.00</td>\n      <td>8.15</td>\n      <td>2.48</td>\n      <td>0.62</td>\n      <td>9.34</td>\n      <td>9.34</td>\n      <td>9.34</td>\n      <td>9.34</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>159.00</td>\n      <td>4.57</td>\n      <td>0.53</td>\n      <td>0.78</td>\n      <td>4.71</td>\n      <td>4.71</td>\n      <td>4.71</td>\n      <td>4.71</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>6.00</td>\n      <td>5.62</td>\n      <td>3.11</td>\n      <td>1.52</td>\n      <td>3.47</td>\n      <td>5.56</td>\n      <td>8.23</td>\n      <td>9.15</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>111.00</td>\n      <td>8.71</td>\n      <td>1.10</td>\n      <td>0.74</td>\n      <td>8.93</td>\n      <td>8.93</td>\n      <td>8.93</td>\n      <td>8.93</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>63.00</td>\n      <td>6.11</td>\n      <td>0.81</td>\n      <td>2.64</td>\n      <td>6.35</td>\n      <td>6.35</td>\n      <td>6.35</td>\n      <td>6.35</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>174.00</td>\n      <td>9.18</td>\n      <td>1.04</td>\n      <td>1.57</td>\n      <td>9.39</td>\n      <td>9.39</td>\n      <td>9.39</td>\n      <td>9.39</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>64.00</td>\n      <td>12.53</td>\n      <td>0.00</td>\n      <td>12.53</td>\n      <td>12.53</td>\n      <td>12.53</td>\n      <td>12.53</td>\n      <td>12.53</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>262.00</td>\n      <td>4.53</td>\n      <td>1.64</td>\n      <td>0.39</td>\n      <td>3.27</td>\n      <td>5.78</td>\n      <td>5.78</td>\n      <td>5.78</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>18.00</td>\n      <td>6.20</td>\n      <td>0.00</td>\n      <td>6.20</td>\n      <td>6.20</td>\n      <td>6.20</td>\n      <td>6.20</td>\n      <td>6.20</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>100.00</td>\n      <td>9.32</td>\n      <td>1.44</td>\n      <td>0.81</td>\n      <td>9.66</td>\n      <td>9.66</td>\n      <td>9.66</td>\n      <td>9.66</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>166.00</td>\n      <td>9.68</td>\n      <td>1.65</td>\n      <td>0.85</td>\n      <td>10.17</td>\n      <td>10.17</td>\n      <td>10.17</td>\n      <td>10.17</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>124.00</td>\n      <td>4.69</td>\n      <td>0.81</td>\n      <td>1.17</td>\n      <td>5.03</td>\n      <td>5.03</td>\n      <td>5.03</td>\n      <td>5.03</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>102.00</td>\n      <td>9.68</td>\n      <td>1.91</td>\n      <td>0.68</td>\n      <td>10.15</td>\n      <td>10.15</td>\n      <td>10.15</td>\n      <td>10.15</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>239.00</td>\n      <td>4.90</td>\n      <td>1.65</td>\n      <td>0.93</td>\n      <td>3.83</td>\n      <td>6.11</td>\n      <td>6.21</td>\n      <td>6.21</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>136.00</td>\n      <td>10.89</td>\n      <td>2.90</td>\n      <td>1.01</td>\n      <td>12.11</td>\n      <td>12.11</td>\n      <td>12.11</td>\n      <td>12.11</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>63.00</td>\n      <td>6.69</td>\n      <td>0.86</td>\n      <td>1.71</td>\n      <td>6.84</td>\n      <td>6.84</td>\n      <td>6.84</td>\n      <td>6.84</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>101.00</td>\n      <td>11.04</td>\n      <td>1.63</td>\n      <td>1.71</td>\n      <td>11.42</td>\n      <td>11.42</td>\n      <td>11.42</td>\n      <td>11.42</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>170.00</td>\n      <td>5.73</td>\n      <td>0.61</td>\n      <td>2.79</td>\n      <td>5.99</td>\n      <td>5.99</td>\n      <td>5.99</td>\n      <td>5.99</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nlead_proposal_2.groupby(data.publisher_id).min().plot.bar(figsize=[10,5])\n```\n\nThat looks about right, as long as the smaller publishers were closer to zero. So let's apply feature scaling to this, to give a number between 1 and 20. (Anything not as lead will pass though as zero.)\n\n\n```python\ndef rescale(series):\n    return (series - series.min()) / (series.max() - series.min())\n\nlead_proposal_3 = np.ceil(20 * rescale(lead_proposal_2))\n```\n\n\n```python\nlead_proposal_2.min(), lead_proposal_2.max()\n```\n\n\n\n\n    (0.38500569152790032, 13.145359968846892)\n\n\n\n\n```python\nlead_proposal_3.plot.hist()\n```\n\n\n```python\nlead_proposal_3.groupby(data.publisher_id).median().plot.bar(figsize=[10,5])\n```\n\n\n```python\ndata[\"lead_score\"] = pd.concat([lead_proposal_3, data.mins_as_lead[data.mins_as_lead==0]])\n```\n\n\n```python\ndata.lead_score.value_counts().sort_index()\n```\n\n\n\n\n    0.00     142399\n    1.00         40\n    2.00         43\n    3.00         61\n    4.00         60\n    5.00         59\n    6.00         71\n    7.00        272\n    8.00        196\n    9.00        327\n    10.00       210\n    11.00       176\n    12.00        81\n    13.00       106\n    14.00       320\n    15.00       436\n    16.00       379\n    17.00       263\n    18.00       240\n    19.00       399\n    20.00       346\n    Name: lead_score, dtype: int64\n\n\n\n\n```python\ndata.lead_score.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    8.00\n    bbc_co_uk                          20.00\n    breitbart_com                      14.00\n    brexitcentral_com                   7.00\n    buzzfeed_com                       19.00\n    cnn_com                            20.00\n    dailymail_co_uk                    18.00\n    economist_com                      12.00\n    evolvepolitics_com                  0.00\n    foxnews_com                        17.00\n    ft_com                             13.00\n    huffingtonpost_com                 17.00\n    independent_co_uk                  16.00\n    indy100_com                        11.00\n    lemonde_fr                         15.00\n    libdemvoice_org                     7.00\n    mirror_co_uk                       14.00\n    nbcnews_com                        14.00\n    newstatesman_com                   10.00\n    npr_org                            15.00\n    nytimes_com                        20.00\n    order-order_com                     9.00\n    propublica_org                     10.00\n    reuters_com                        15.00\n    rt_com                             16.00\n    skwawkbox_org                       8.00\n    telegraph_co_uk                    16.00\n    thecanary_co                       10.00\n    theguardian_com                    19.00\n    thetimes_co_uk                     11.00\n    washingtonpost_com                 18.00\n    westmonster_com                     0.00\n    yournewswire_com                    9.00\n    Name: lead_score, dtype: float64\n\n\n\nIn summary then, score for article $a$ is:\n\n\n$$\nunscaledLeadScore_a = \\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)}\\\\\nleadScore_a = 19 \\cdot \n\\frac{unscaledLeadScore_a - \\min(unscaledLeadScore)}\n{\\max(unscaledLeadScore) - \\min(unscaledLeadScore)} \n+ 1\n$$\n\nSince the minium value of $minsAsLead$ is 1, $\\min(unscaledLeadScore)$ is pretty insignificant. So we can simplify this to:\n\n$$\nleadScore_a = 20 \\cdot \n\\frac{unscaledLeadScore_a }\n     {\\max(unscaledLeadScore)} \n$$\n\nor: \n\n$$\nleadScore_a = 20 \\cdot \n\\frac{\\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)} }\n     {\\frac{60}{\\log(\\max(alexaRank))}} \n$$\n\n$$\nleadScore_a = \\left( 20 \\cdot \n\\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)} \\cdot\n     {\\frac{\\log(\\max(alexaRank))}{60}} \\right)\n$$\n\n## Time on front score (15 points)\n\nThis is similar to time as lead, so lets try doing the same calculation, except we also want to factor in the number of slots on the front:\n\n\n$$frontScore_a = \n15 \n\\left(\\frac{\\min(minsOnFront_a, 1440)}{alexaRank_a \\cdot numArticlesOnFront_a}\\right) \n\\left( \\frac{\\min(alexaRank \\cdot numArticlesOnFront)}{1440} \\right)$$\n\n\n```python\n(data.alexa_rank * data.num_articles_on_front).min() / 1440\n```\n\n\n\n\n    2.4500000000000002\n\n\n\n\n```python\ntime_on_front_proposal_1 = np.ceil(data.mins_on_front.clip_upper(1440) / (data.alexa_rank * data.num_articles_on_front) * (2.45) * 15)\n```\n\n\n```python\ntime_on_front_proposal_1.plot.hist(figsize=(15, 7), bins=15)\n```\n\n\n```python\ntime_on_front_proposal_1.value_counts().sort_index()\n```\n\n\n\n\n    1.00     74079\n    2.00      7491\n    3.00      4745\n    4.00      4502\n    5.00       829\n    6.00       667\n    7.00       534\n    8.00       437\n    9.00       867\n    10.00      493\n    11.00      242\n    12.00      148\n    13.00      100\n    14.00       87\n    15.00       18\n    dtype: int64\n\n\n\n\n```python\ntime_on_front_proposal_1.groupby(data.publisher_id).sum()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk      38.00\n    bbc_co_uk                          14465.00\n    breitbart_com                       2641.00\n    brexitcentral_com                     66.00\n    buzzfeed_com                       10488.00\n    cnn_com                            12675.00\n    dailymail_co_uk                    14438.00\n    economist_com                        286.00\n    evolvepolitics_com                    79.00\n    foxnews_com                         6709.00\n    ft_com                              3187.00\n    huffingtonpost_com                  8335.00\n    independent_co_uk                   3902.00\n    indy100_com                          470.00\n    lemonde_fr                          4216.00\n    libdemvoice_org                      165.00\n    mirror_co_uk                        9635.00\n    nbcnews_com                         1801.00\n    newstatesman_com                     482.00\n    npr_org                             2919.00\n    nytimes_com                         9791.00\n    order-order_com                      263.00\n    propublica_org                        43.00\n    reuters_com                         7705.00\n    rt_com                              4740.00\n    skwawkbox_org                        124.00\n    telegraph_co_uk                     4415.00\n    thecanary_co                         255.00\n    theguardian_com                    12338.00\n    thetimes_co_uk                      9740.00\n    washingtonpost_com                  9571.00\n    westmonster_com                      246.00\n    yournewswire_com                     416.00\n    dtype: float64\n\n\n\nThat looks good to me.\n\n\n```python\ndata[\"front_score\"] = np.ceil(data.mins_on_front.clip_upper(1440) / (data.alexa_rank * data.num_articles_on_front) * (2.45) * 15).fillna(0)\n```\n\n\n```python\ndata.front_score \n```\n\n\n\n\n    id\n    4296661b7ec493a798bf313f1133cd1176052f30   1.00\n    a995ae644e9cbe39a5b4a41143466399751bdf5e   1.00\n    5e8654da9845e74a797af5a1f8fa076b47c0b6f5   1.00\n    55c5ece98c02b70430bd19a2087558eaf0288f37   1.00\n    19b8c2e31074fa50f06010b8f00a9899994baea1   1.00\n    8fd307ee7359d9bc37ee1d0de1bdedf27c67aaec   1.00\n    e9e44511e90365c6806d5d21c442dec0e5ce2289   1.00\n    29df6d80a9f8a8691492021fbdb407bd873f7634   1.00\n    4f23bde73ab83522dfe7d326f92500acb4c57ede   1.00\n    a43485f058f904f73b53bcae2bd63b48def31851   1.00\n    1eba49de1ed24dd27c87cc7f7df88eea14b77ffb   1.00\n    74acd3f538a979ec306a0e23ab78376a2c02964d   1.00\n    7c256cc04797c8a828adcc7a60ae5ec4c97af7e1   1.00\n    0262e43862244464024660cd2cbbafb71a2cd279   1.00\n    fc3207065dc6daf733c243411a60553858ad57e4   1.00\n    b4b2a48f6570ecc54d037e20642fd1a72aee6d07   1.00\n    20b8b495a1f324efc7fcdf563ed7c500342bc0a6   1.00\n    8e5f315c408da033da14ca097efe1c1cf58f1e24   1.00\n    302848dc6974b2c1f8e3c13005490801c13fab01   1.00\n    ad63302360007ff4aaca5a3ca838e6b323c7f2e8   1.00\n    c50275a656ed2e45255f4f34074e7b431821cdf4   1.00\n    fa09e221612841335239ef657bb0e159b12a8790   1.00\n    07b362eabee7ecf9852588bb5b65c0b7ba7ab3ab   1.00\n    f05506729453ebf18fcc760d153805fca11a314c   1.00\n    5ab3420fd5c7a9d2f4440efddc2be6d0eaf83a69   1.00\n    a472d447d13cf62efc56dd028293115b27b7c7d0   1.00\n    11b7bc3b9e8d7317c960b081778b156ac38d957c   1.00\n    f115164f2a4becf341ed2980acf23e496b82aa1c   1.00\n    1bcb84381c9c6954e7194428042f49779ea6a3a0   1.00\n    de3f21baede6de63afc29bcd557aa97b85d0da56   1.00\n                                               ... \n    f62818af1cb8aa90e8334d4a061901c427be88f8   0.00\n    9776277c068ca6b7ece5c1e0ef3581afe1958908   0.00\n    9b0db6758f03513f09a33ea41cc8ecc511477282   0.00\n    c8adc816a8455481a6ee2ffad6c9dc9cfbb9295f   0.00\n    448c0976efe0dab8ffbd36fdd65e29f483798ac1   0.00\n    723641a365d8a80e6435b5f6d1681c38e0b2bc68   1.00\n    fc77940ed0980846117a7e37aceda618e310042a   1.00\n    051240fb8de7e3bf81122c3432649f8e934c6d9a   0.00\n    f2cb3bce762a35a29045820da033bffeb264611c   0.00\n    e4ea7c7dd830a8a536c02dbb22db8d06e835ff0c   6.00\n    a75381d7ee18af66a174f26fcb6e9c84c3a862dd   1.00\n    09588094ea55b016b587aff909ac1e6e687b83ce   1.00\n    adffbfec52cc8cfb0dd9ea8a15e6cd00e0eac35f   1.00\n    7761e92901f2682bd3205f3db8d18f6f396f7092   1.00\n    7b78b7d3509c6d15fcf46237d7b004d5364c3b26   1.00\n    86e01feb83cf77fa60a0f942903154b315f9039e   1.00\n    1ffec218f2615e0c1420a1d783d524720a5bdf27   1.00\n    99bfc46e13bd0d7c42bfa28aa011e2583b732f9b   1.00\n    57e16ac7e15a6b6b208c7c40d630ea40eb70739d   3.00\n    fb78fef5863200d46ab89101bbc20a4ac0b7a6f8   1.00\n    1cede55875753f22355802b65bc765bef3aa08b0   1.00\n    78050ebf3f153ebe09b5012171df31c96f8b41b5   1.00\n    a3ec6f7c4f1f492ccd315648f46de1a57ac32d86   1.00\n    e0832b31125db89d7277487524a3bc3e9d410df7   1.00\n    d006b8c4e6e302621dd2033eb38656e0edfc909c   1.00\n    6438936238c8f4c27571c8b76ec588595314a1ce   1.00\n    c6a120ac5c80edf83da06277836da094c6925955   1.00\n    017ea59645d12a0f4e20385f13a9803455016734   1.00\n    5a74f3bf5380e19c8b432b3ca0eddba1c4d469c9   1.00\n    13db19d820572f0e174d36463e243624e16972d4   1.00\n    Name: front_score, Length: 146484, dtype: float64\n\n\n\n## Facebook brand page promotion (15 points)\n\nOne way a publisher has of promoting content is to post to their brand page. The significance of doing so is stronger when the brand page has more followers (likes).\n\n$$ facebookPromotionProposed1_a = 15 \\left( \\frac {brandPageLikes_a} {\\max(brandPageLikes)} \\right) $$\n\nNow lets explore the data to see if that makes sense. **tr;dr the formula above is incorrect**\n\n\n```python\ndata.fb_brand_page_likes.max()\n```\n\n\n\n\n    46501656.0\n\n\n\n\n```python\nfacebook_promotion_proposed_1 = np.ceil((15 * (data.fb_brand_page_likes / data.fb_brand_page_likes.max())).fillna(0))\n```\n\n\n```python\nfacebook_promotion_proposed_1.value_counts().sort_index().plot.bar()\n```\n\n\n```python\nfacebook_promotion_proposed_1.groupby(data.publisher_id).describe()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>25%</th>\n      <th>50%</th>\n      <th>75%</th>\n      <th>max</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>38.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>11963.00</td>\n      <td>0.52</td>\n      <td>2.75</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>15.00</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>2737.00</td>\n      <td>0.78</td>\n      <td>0.98</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>66.00</td>\n      <td>0.56</td>\n      <td>0.50</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>1452.00</td>\n      <td>0.50</td>\n      <td>0.50</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>4368.00</td>\n      <td>2.54</td>\n      <td>4.36</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>10.00</td>\n      <td>10.00</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>25800.00</td>\n      <td>0.61</td>\n      <td>1.64</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>5.00</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>579.00</td>\n      <td>2.50</td>\n      <td>1.12</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>evolvepolitics_com</th>\n      <td>82.00</td>\n      <td>0.94</td>\n      <td>0.24</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>5340.00</td>\n      <td>0.83</td>\n      <td>2.07</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>6.00</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>4913.00</td>\n      <td>0.49</td>\n      <td>0.86</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>2564.00</td>\n      <td>1.84</td>\n      <td>1.99</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>5590.00</td>\n      <td>0.75</td>\n      <td>1.30</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>471.00</td>\n      <td>0.79</td>\n      <td>0.41</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>4229.00</td>\n      <td>0.70</td>\n      <td>0.95</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>165.00</td>\n      <td>0.96</td>\n      <td>0.19</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>10148.00</td>\n      <td>0.22</td>\n      <td>0.42</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>2017.00</td>\n      <td>2.50</td>\n      <td>1.94</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>489.00</td>\n      <td>0.75</td>\n      <td>0.43</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>1661.00</td>\n      <td>1.75</td>\n      <td>1.48</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>5016.00</td>\n      <td>1.55</td>\n      <td>2.31</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>5.00</td>\n      <td>6.00</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>264.00</td>\n      <td>0.78</td>\n      <td>0.41</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>43.00</td>\n      <td>0.84</td>\n      <td>0.37</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>6679.00</td>\n      <td>0.59</td>\n      <td>0.91</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>2322.00</td>\n      <td>1.29</td>\n      <td>0.96</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>124.00</td>\n      <td>0.99</td>\n      <td>0.09</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>4501.00</td>\n      <td>0.57</td>\n      <td>0.91</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>258.00</td>\n      <td>0.19</td>\n      <td>0.39</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>8409.00</td>\n      <td>0.53</td>\n      <td>1.14</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>9760.00</td>\n      <td>0.05</td>\n      <td>0.22</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>23764.00</td>\n      <td>0.11</td>\n      <td>0.45</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>255.00</td>\n      <td>0.29</td>\n      <td>0.45</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>417.00</td>\n      <td>0.18</td>\n      <td>0.39</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThat's too much variation: sites like the Guardian, which have a respectable 7.5m likes, should not be scoring a 3. Lets try applying a log to it, and then standard feature scaling again.\n\n\n```python\ndata.fb_brand_page_likes.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk     334591.00\n    bbc_co_uk                          46501656.00\n    breitbart_com                       3855739.00\n    brexitcentral_com                     16040.00\n    buzzfeed_com                        2941240.00\n    cnn_com                            30055121.00\n    dailymail_co_uk                    14651250.00\n    economist_com                       8528948.00\n    evolvepolitics_com                   128042.00\n    foxnews_com                        16377561.00\n    ft_com                              3776695.00\n    huffingtonpost_com                  9872568.00\n    independent_co_uk                   8204164.00\n    indy100_com                          243508.00\n    lemonde_fr                          4147802.00\n    libdemvoice_org                        8634.00\n    mirror_co_uk                        2987463.00\n    nbcnews_com                         9699612.00\n    newstatesman_com                     154653.00\n    npr_org                             6312234.00\n    nytimes_com                        15594031.00\n    order-order_com                       45697.00\n    propublica_org                       379791.00\n    reuters_com                         3999322.00\n    rt_com                              4995093.00\n    skwawkbox_org                          7897.00\n    telegraph_co_uk                     4425790.00\n    thecanary_co                         158047.00\n    theguardian_com                     7948187.00\n    thetimes_co_uk                       764648.00\n    washingtonpost_com                  6158264.00\n    westmonster_com                       19853.00\n    yournewswire_com                      28490.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\nnp.log(2149)\n```\n\n\n\n\n    7.6727578966425103\n\n\n\n\n```python\nnp.log(data.fb_brand_page_likes.groupby(data.publisher_id).max())\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk   12.72\n    bbc_co_uk                          17.65\n    breitbart_com                      15.17\n    brexitcentral_com                   9.68\n    buzzfeed_com                       14.89\n    cnn_com                            17.22\n    dailymail_co_uk                    16.50\n    economist_com                      15.96\n    evolvepolitics_com                 11.76\n    foxnews_com                        16.61\n    ft_com                             15.14\n    huffingtonpost_com                 16.11\n    independent_co_uk                  15.92\n    indy100_com                        12.40\n    lemonde_fr                         15.24\n    libdemvoice_org                     9.06\n    mirror_co_uk                       14.91\n    nbcnews_com                        16.09\n    newstatesman_com                   11.95\n    npr_org                            15.66\n    nytimes_com                        16.56\n    order-order_com                    10.73\n    propublica_org                     12.85\n    reuters_com                        15.20\n    rt_com                             15.42\n    skwawkbox_org                       8.97\n    telegraph_co_uk                    15.30\n    thecanary_co                       11.97\n    theguardian_com                    15.89\n    thetimes_co_uk                     13.55\n    washingtonpost_com                 15.63\n    westmonster_com                     9.90\n    yournewswire_com                   10.26\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\nThat's more like it, but the lower numbers should be smaller.\n\n\n```python\nnp.log(data.fb_brand_page_likes.groupby(data.publisher_id).max() / 1000)\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    5.81\n    bbc_co_uk                          10.75\n    breitbart_com                       8.26\n    brexitcentral_com                   2.78\n    buzzfeed_com                        7.99\n    cnn_com                            10.31\n    dailymail_co_uk                     9.59\n    economist_com                       9.05\n    evolvepolitics_com                  4.85\n    foxnews_com                         9.70\n    ft_com                              8.24\n    huffingtonpost_com                  9.20\n    independent_co_uk                   9.01\n    indy100_com                         5.50\n    lemonde_fr                          8.33\n    libdemvoice_org                     2.16\n    mirror_co_uk                        8.00\n    nbcnews_com                         9.18\n    newstatesman_com                    5.04\n    npr_org                             8.75\n    nytimes_com                         9.65\n    order-order_com                     3.82\n    propublica_org                      5.94\n    reuters_com                         8.29\n    rt_com                              8.52\n    skwawkbox_org                       2.07\n    telegraph_co_uk                     8.40\n    thecanary_co                        5.06\n    theguardian_com                     8.98\n    thetimes_co_uk                      6.64\n    washingtonpost_com                  8.73\n    westmonster_com                     2.99\n    yournewswire_com                    3.35\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\nscaled_fb_brand_page_likes = (data.fb_brand_page_likes / 1000)\nfacebook_promotion_proposed_2 = np.ceil(\\\n    (15 * \\\n     (np.log(scaled_fb_brand_page_likes) / np.log(scaled_fb_brand_page_likes.max()))\\\n    )\\\n                                       ).fillna(0)\n```\n\n\n```python\nfacebook_promotion_proposed_2.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    9.00\n    bbc_co_uk                          15.00\n    breitbart_com                      12.00\n    brexitcentral_com                   4.00\n    buzzfeed_com                       12.00\n    cnn_com                            15.00\n    dailymail_co_uk                    14.00\n    economist_com                      13.00\n    evolvepolitics_com                  7.00\n    foxnews_com                        14.00\n    ft_com                             12.00\n    huffingtonpost_com                 13.00\n    independent_co_uk                  13.00\n    indy100_com                         8.00\n    lemonde_fr                         12.00\n    libdemvoice_org                     4.00\n    mirror_co_uk                       12.00\n    nbcnews_com                        13.00\n    newstatesman_com                    8.00\n    npr_org                            13.00\n    nytimes_com                        14.00\n    order-order_com                     6.00\n    propublica_org                      9.00\n    reuters_com                        12.00\n    rt_com                             12.00\n    skwawkbox_org                       3.00\n    telegraph_co_uk                    12.00\n    thecanary_co                        8.00\n    theguardian_com                    13.00\n    thetimes_co_uk                     10.00\n    washingtonpost_com                 13.00\n    westmonster_com                     5.00\n    yournewswire_com                    5.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\nLGTM. So the equation is\n\n\n$$ facebookPromotion_a = 15 \\left( \n\\frac {\\log(\\frac {brandPageLikes_a}{1000})} \n{\\log(\\frac {\\max(brandPageLikes)}{1000}))} \\right) $$\n\n\nNow, let's try applying standard feature scaling approch to this, rather than using a magic number of 1,000. That equation would be:\n\n\\begin{align}\nunscaledFacebookPromotion_a &= \n   \\log(brandPageLikes_a) \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{unscaledFacebookPromotion_a - \\min(unscaledFacebookPromotion)}{\\max(unscaledFacebookPromotion) - \\min(unscaledFacebookPromotion)}  \\\\\n\\\\\n\\text{The scaling can be simplified to:} \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{unscaledFacebookPromotion_a - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))}  \\\\\n\\\\\n\\text{Meaning the overall equation becomes:} \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{\\log(brandPageLikes_a) - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))} \n   \\end{align}\n\n\n\n```python\nfacebook_promotion_proposed_3 = np.ceil(\n    (14 * \n     ( \n         (np.log(data.fb_brand_page_likes) - np.log(data.fb_brand_page_likes.min()) ) /\n         (np.log(data.fb_brand_page_likes.max()) - np.log(data.fb_brand_page_likes.min()))\n     )\n    ) + 1\n                                       )\n```\n\n\n```python\nfacebook_promotion_proposed_3.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    8.00\n    bbc_co_uk                          15.00\n    breitbart_com                      12.00\n    brexitcentral_com                   3.00\n    buzzfeed_com                       11.00\n    cnn_com                            15.00\n    dailymail_co_uk                    14.00\n    economist_com                      13.00\n    evolvepolitics_com                  6.00\n    foxnews_com                        14.00\n    ft_com                             11.00\n    huffingtonpost_com                 13.00\n    independent_co_uk                  13.00\n    indy100_com                         7.00\n    lemonde_fr                         12.00\n    libdemvoice_org                     2.00\n    mirror_co_uk                       11.00\n    nbcnews_com                        13.00\n    newstatesman_com                    6.00\n    npr_org                            12.00\n    nytimes_com                        14.00\n    order-order_com                     4.00\n    propublica_org                      8.00\n    reuters_com                        12.00\n    rt_com                             12.00\n    skwawkbox_org                       2.00\n    telegraph_co_uk                    12.00\n    thecanary_co                        6.00\n    theguardian_com                    13.00\n    thetimes_co_uk                      9.00\n    washingtonpost_com                 12.00\n    westmonster_com                     3.00\n    yournewswire_com                    4.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\ndata[\"facebook_promotion_score\"] = facebook_promotion_proposed_3.fillna(0.0)\n```\n\n# Review\n\n\n```python\ndata[\"promotion_score\"] = (data.lead_score + data.front_score + data.facebook_promotion_score)\ndata[\"attention_index\"] = (data.promotion_score + data.response_score)\n```\n\n\n```python\ndata.promotion_score.plot.hist(bins=np.arange(50), figsize=(15,6))\n```\n\n\n```python\ndata.attention_index.plot.hist(bins=np.arange(100), figsize=(15,6))\n```\n\n\n```python\ndata.attention_index.value_counts().sort_index()\n```\n\n\n\n\n    0.00     21250\n    1.00     19394\n    2.00     12021\n    3.00      8741\n    4.00      6532\n    5.00      5408\n    6.00      4333\n    7.00      3791\n    8.00      3415\n    9.00      3065\n    10.00     2821\n    11.00     2518\n    12.00     2342\n    13.00     2350\n    14.00     2266\n    15.00     2083\n    16.00     1894\n    17.00     1902\n    18.00     1892\n    19.00     1765\n    20.00     1715\n    21.00     1635\n    22.00     1592\n    23.00     1578\n    24.00     1500\n    25.00     1551\n    26.00     1484\n    27.00     1382\n    28.00     1311\n    29.00     1324\n             ...  \n    66.00      107\n    67.00       82\n    68.00       70\n    69.00       65\n    70.00       52\n    71.00       51\n    72.00       45\n    73.00       32\n    74.00       43\n    75.00       35\n    76.00       19\n    77.00       28\n    78.00       36\n    79.00       27\n    80.00       28\n    81.00       17\n    82.00       14\n    83.00       15\n    84.00        6\n    85.00       15\n    86.00        8\n    87.00        7\n    88.00       15\n    89.00        7\n    90.00        4\n    91.00        6\n    92.00        3\n    93.00        2\n    94.00        4\n    95.00        1\n    Name: attention_index, Length: 96, dtype: int64\n\n\n\n\n```python\n# and lets see the articles with the biggest attention index\ndata.sort_values(\"attention_index\", ascending=False)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>3a34a2b4590e487def08b1918783a5d8dd39f73a</th>\n      <td>http://www.bbc.co.uk/news/uk-43396008</td>\n      <td>Physicist Stephen Hawking dies aged 76</td>\n      <td>2018-03-14 03:49:13.874</td>\n      <td>2018-03-14 03:47:02.000</td>\n      <td>2016997</td>\n      <td>8610.41</td>\n      <td>2018-03-14T04:12:06.080Z</td>\n      <td>141418</td>\n      <td>1517206</td>\n      <td>358373</td>\n      <td>...</td>\n      <td>46116240.00</td>\n      <td>2018-03-14T03:50:08.000Z</td>\n      <td>96</td>\n      <td>66.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>10.00</td>\n      <td>15.00</td>\n      <td>45.00</td>\n      <td>95.00</td>\n    </tr>\n    <tr>\n      <th>e7607247fffe2d26b41a40d3e538ca6aa3713c6a</th>\n      <td>https://www.cnn.com/2018/03/25/us/emma-gonzale...</td>\n      <td>Emma Gonzalez profile: What you need to know a...</td>\n      <td>2018-03-25 13:04:19.014</td>\n      <td>2018-03-25 12:56:50.000</td>\n      <td>233961</td>\n      <td>787.19</td>\n      <td>2018-03-25T15:48:12.330Z</td>\n      <td>29785</td>\n      <td>189759</td>\n      <td>14417</td>\n      <td>...</td>\n      <td>29898261.00</td>\n      <td>2018-03-25T15:30:01.000Z</td>\n      <td>105</td>\n      <td>851.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>424489ba1c79b4b8d4da2e45f7fd358322947ebc</th>\n      <td>https://www.cnn.com/2018/03/21/us/austin-explo...</td>\n      <td>Austin bomber's motive is to cause 'mayhem and...</td>\n      <td>2018-03-21 06:10:16.915</td>\n      <td>2018-03-21 06:06:52.000</td>\n      <td>167127</td>\n      <td>381.36</td>\n      <td>2018-03-21T13:15:12.369Z</td>\n      <td>39679</td>\n      <td>99918</td>\n      <td>27530</td>\n      <td>...</td>\n      <td>29873177.00</td>\n      <td>2018-03-22T00:03:09.000Z</td>\n      <td>105</td>\n      <td>688.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>0fd72776c86f7d09898cb4f9e59b79d589127ae8</th>\n      <td>https://www.cnn.com/2018/03/31/politics/nra-me...</td>\n      <td>Ted Nugent calls Parkland survivors 'liars' an...</td>\n      <td>2018-03-31 23:34:16.919</td>\n      <td>2018-03-31 23:30:04.000</td>\n      <td>149760</td>\n      <td>251.02</td>\n      <td>2018-04-01T00:57:05.961Z</td>\n      <td>60523</td>\n      <td>78564</td>\n      <td>10673</td>\n      <td>...</td>\n      <td>29918466.00</td>\n      <td>2018-04-01T00:21:12.000Z</td>\n      <td>105</td>\n      <td>567.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>8d4daa22650daac24f1278a5e31c1f7204f47380</th>\n      <td>https://www.cnn.com/2018/03/20/us/maryland-sch...</td>\n      <td>Lone resource officer's quick action stopped t...</td>\n      <td>2018-03-20 19:19:19.249</td>\n      <td>2018-03-20 19:14:25.000</td>\n      <td>233418</td>\n      <td>1128.83</td>\n      <td>2018-03-21T13:08:07.973Z</td>\n      <td>41196</td>\n      <td>169456</td>\n      <td>22766</td>\n      <td>...</td>\n      <td>29865951.00</td>\n      <td>2018-03-20T22:30:14.000Z</td>\n      <td>105</td>\n      <td>694.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>7664d105c1e404927d190c8ef9106192165226d0</th>\n      <td>https://www.cnn.com/2018/03/16/politics/andrew...</td>\n      <td>Ex-FBI deputy director Andrew McCabe fired</td>\n      <td>2018-03-17 02:09:08.055</td>\n      <td>2018-03-17 02:00:06.000</td>\n      <td>289576</td>\n      <td>1156.07</td>\n      <td>2018-03-17T03:14:08.419Z</td>\n      <td>100382</td>\n      <td>162935</td>\n      <td>26259</td>\n      <td>...</td>\n      <td>29844606.00</td>\n      <td>2018-03-17T02:08:52.000Z</td>\n      <td>105</td>\n      <td>113.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>8848efde83e686020d400bbc7505803567b9331c</th>\n      <td>http://www.bbc.co.uk/news/world-europe-43525267</td>\n      <td>French police 'hero' dies of wounds</td>\n      <td>2018-03-24 05:13:12.232</td>\n      <td>2018-03-24 05:10:28.000</td>\n      <td>113294</td>\n      <td>285.37</td>\n      <td>2018-03-24T08:40:11.781Z</td>\n      <td>10422</td>\n      <td>91883</td>\n      <td>10989</td>\n      <td>...</td>\n      <td>46201300.00</td>\n      <td>2018-03-24T08:30:01.000Z</td>\n      <td>96</td>\n      <td>83.00</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>10.00</td>\n      <td>15.00</td>\n      <td>45.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>0705ea630bb0def04ffcbe69420b63a500879d43</th>\n      <td>http://www.bbc.co.uk/news/world-europe-43324406</td>\n      <td>International Women's Day: Trains cancelled as...</td>\n      <td>2018-03-08 03:25:11.956</td>\n      <td>2018-03-08 03:22:33.000</td>\n      <td>91511</td>\n      <td>237.61</td>\n      <td>2018-03-08T17:58:06.745Z</td>\n      <td>3914</td>\n      <td>78771</td>\n      <td>8826</td>\n      <td>...</td>\n      <td>46026903.00</td>\n      <td>2018-03-08T17:40:00.000Z</td>\n      <td>96</td>\n      <td>289.00</td>\n      <td>47.00</td>\n      <td>20.00</td>\n      <td>10.00</td>\n      <td>15.00</td>\n      <td>45.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>2e5fa0c72c95854d8fec1ad919caef746a97894e</th>\n      <td>https://www.cnn.com/2018/03/16/politics/tennes...</td>\n      <td>Resolution denouncing white supremacists and n...</td>\n      <td>2018-03-16 15:10:20.763</td>\n      <td>2018-03-16 15:07:46.000</td>\n      <td>113404</td>\n      <td>380.13</td>\n      <td>2018-03-17T15:08:09.009Z</td>\n      <td>23082</td>\n      <td>69399</td>\n      <td>20923</td>\n      <td>...</td>\n      <td>29843740.00</td>\n      <td>2018-03-16T16:31:06.000Z</td>\n      <td>105</td>\n      <td>398.00</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>a487a5b5754e7ef5e0cdbbadbf0195f88347ce4b</th>\n      <td>https://www.cnn.com/2018/03/23/politics/transg...</td>\n      <td>White House announces policy to ban most trans...</td>\n      <td>2018-03-24 01:34:16.864</td>\n      <td>2018-03-24 01:29:02.000</td>\n      <td>114599</td>\n      <td>249.08</td>\n      <td>2018-03-24T03:08:06.356Z</td>\n      <td>30346</td>\n      <td>73204</td>\n      <td>11049</td>\n      <td>...</td>\n      <td>29880855.00</td>\n      <td>2018-03-24T01:55:03.000Z</td>\n      <td>105</td>\n      <td>87.00</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>b2688f1ef5dfcb7d0cfa192634af8c318db75736</th>\n      <td>https://www.cnn.com/2018/03/14/health/stephen-...</td>\n      <td>Stephen Hawking, renowned scientist, dies at 76</td>\n      <td>2018-03-14 04:07:13.160</td>\n      <td>2018-03-14 04:03:53.000</td>\n      <td>711418</td>\n      <td>2328.02</td>\n      <td>2018-03-14T04:19:09.362Z</td>\n      <td>58142</td>\n      <td>545087</td>\n      <td>108189</td>\n      <td>...</td>\n      <td>29827961.00</td>\n      <td>2018-03-14T04:09:41.000Z</td>\n      <td>105</td>\n      <td>653.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>50436ebae1b3cdca23bc56a93b67aeb35087c01a</th>\n      <td>https://www.cnn.com/2018/03/27/politics/donald...</td>\n      <td>Trump suggests US military foot the bill for b...</td>\n      <td>2018-03-27 18:34:22.226</td>\n      <td>2018-03-27 18:29:24.000</td>\n      <td>125500</td>\n      <td>409.71</td>\n      <td>2018-03-28T13:03:08.153Z</td>\n      <td>47570</td>\n      <td>65167</td>\n      <td>12763</td>\n      <td>...</td>\n      <td>29916236.00</td>\n      <td>2018-03-31T10:00:21.000Z</td>\n      <td>105</td>\n      <td>482.00</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>0be4709b4b6141a6344aa3ae90df89aba5c96eb4</th>\n      <td>https://www.buzzfeed.com/arianelange/john-kric...</td>\n      <td>Creator Of \u201cRen &amp; Stimpy\u201d Accused Of Preying O...</td>\n      <td>2018-03-29 20:40:13.743</td>\n      <td>2018-03-29 20:37:53.000</td>\n      <td>94263</td>\n      <td>125.60</td>\n      <td>2018-03-30T00:54:08.282Z</td>\n      <td>31786</td>\n      <td>51169</td>\n      <td>11308</td>\n      <td>...</td>\n      <td>2936785.00</td>\n      <td>2018-03-29T21:20:54.000Z</td>\n      <td>147</td>\n      <td>4111.00</td>\n      <td>47.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>328f86eb43abe871db40cac05697a816367bb89b</th>\n      <td>https://www.cnn.com/2018/03/28/politics/donald...</td>\n      <td>An unheard-of problem: The President can't fin...</td>\n      <td>2018-03-28 05:31:22.960</td>\n      <td>2018-03-28 05:26:52.000</td>\n      <td>181848</td>\n      <td>460.77</td>\n      <td>2018-03-28T13:07:05.137Z</td>\n      <td>37122</td>\n      <td>126413</td>\n      <td>18313</td>\n      <td>...</td>\n      <td>29908332.00</td>\n      <td>2018-03-28T13:29:04.000Z</td>\n      <td>105</td>\n      <td>1173.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>a459ce106c02660968f2836220d0118a9a2a6824</th>\n      <td>http://money.cnn.com/2018/03/14/news/companies...</td>\n      <td>Toys 'R' Us will close or sell all US stores</td>\n      <td>2018-03-14 22:44:11.213</td>\n      <td>2018-03-14 22:38:00.000</td>\n      <td>159559</td>\n      <td>515.25</td>\n      <td>2018-03-14T23:18:03.648Z</td>\n      <td>40065</td>\n      <td>96445</td>\n      <td>23049</td>\n      <td>...</td>\n      <td>29837453.00</td>\n      <td>2018-03-14T22:45:04.000Z</td>\n      <td>105</td>\n      <td>nan</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>7f88871e141af09b1e5de790cd2d0b440d1adf4c</th>\n      <td>https://www.cnn.com/2018/03/22/politics/john-d...</td>\n      <td>Dowd resigns as Trump's lawyer</td>\n      <td>2018-03-22 15:37:16.332</td>\n      <td>2018-03-22 15:31:14.000</td>\n      <td>182692</td>\n      <td>855.50</td>\n      <td>2018-03-22T16:00:09.907Z</td>\n      <td>31654</td>\n      <td>128300</td>\n      <td>22738</td>\n      <td>...</td>\n      <td>29875784.00</td>\n      <td>2018-03-22T15:45:06.000Z</td>\n      <td>105</td>\n      <td>76.00</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>25dc33625aea1e8d559a344bbf837ea986bd4a08</th>\n      <td>https://www.huffingtonpost.com/entry/andrew-mc...</td>\n      <td>Read Andrew McCabe's Response To Being Fired T...</td>\n      <td>2018-03-17 02:39:14.557</td>\n      <td>2018-03-17 02:33:26.000</td>\n      <td>161658</td>\n      <td>687.37</td>\n      <td>2018-03-17T19:09:08.459Z</td>\n      <td>40559</td>\n      <td>97409</td>\n      <td>23690</td>\n      <td>...</td>\n      <td>9870240.00</td>\n      <td>2018-03-17T14:30:04.000Z</td>\n      <td>215</td>\n      <td>954.00</td>\n      <td>50.00</td>\n      <td>17.00</td>\n      <td>10.00</td>\n      <td>13.00</td>\n      <td>40.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>7ffffa6d7974335419e3c65059fc4ea3de49af3d</th>\n      <td>https://www.cnn.com/2018/03/12/us/texas-austin...</td>\n      <td>Austin explosions: 2 deadly blasts connected, ...</td>\n      <td>2018-03-12 17:22:18.966</td>\n      <td>2018-03-12 17:19:09.000</td>\n      <td>72077</td>\n      <td>197.98</td>\n      <td>2018-03-12T19:07:11.845Z</td>\n      <td>12615</td>\n      <td>43108</td>\n      <td>16354</td>\n      <td>...</td>\n      <td>29816162.00</td>\n      <td>2018-03-12T18:44:02.000Z</td>\n      <td>105</td>\n      <td>200.00</td>\n      <td>46.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>1c6abd59d584927743ac3606cc6783edc6653805</th>\n      <td>https://www.cnn.com/2018/03/15/politics/robert...</td>\n      <td>NYT: Mueller subpoenas Trump Organization</td>\n      <td>2018-03-15 18:07:22.216</td>\n      <td>2018-03-15 18:03:15.000</td>\n      <td>94218</td>\n      <td>532.91</td>\n      <td>2018-03-15T19:13:13.249Z</td>\n      <td>19521</td>\n      <td>64878</td>\n      <td>9819</td>\n      <td>...</td>\n      <td>29842457.00</td>\n      <td>2018-03-15T18:15:04.000Z</td>\n      <td>105</td>\n      <td>92.00</td>\n      <td>47.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>40168add43bafc4da17ca035e9b52e967055e680</th>\n      <td>https://www.cnn.com/2018/03/08/politics/donald...</td>\n      <td>Trump accepts offer to meet Kim Jong Un</td>\n      <td>2018-03-09 00:25:18.624</td>\n      <td>2018-03-09 00:20:14.000</td>\n      <td>90701</td>\n      <td>210.60</td>\n      <td>2018-03-09T02:12:10.970Z</td>\n      <td>34902</td>\n      <td>42937</td>\n      <td>12862</td>\n      <td>...</td>\n      <td>29798449.00</td>\n      <td>2018-03-09T00:50:02.000Z</td>\n      <td>105</td>\n      <td>34.00</td>\n      <td>47.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>9b25e487d0eaa9639787f6a8e205a98b4acc0ac0</th>\n      <td>https://www.buzzfeed.com/tomnamako/ralph-peters</td>\n      <td>An \"Ashamed\" Fox News Commentator Just Quit Th...</td>\n      <td>2018-03-20 20:07:19.832</td>\n      <td>2018-03-20 20:00:15.000</td>\n      <td>76239</td>\n      <td>172.22</td>\n      <td>2018-03-20T22:44:19.065Z</td>\n      <td>15047</td>\n      <td>43957</td>\n      <td>17235</td>\n      <td>...</td>\n      <td>2935278.00</td>\n      <td>2018-03-20T20:30:51.000Z</td>\n      <td>147</td>\n      <td>603.00</td>\n      <td>46.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>505077913306a55b2cf4e8cd7ca01fc810f78749</th>\n      <td>https://www.cnn.com/2018/03/17/politics/mccabe...</td>\n      <td>McCabe has memos documenting his conversations...</td>\n      <td>2018-03-17 17:43:13.101</td>\n      <td>2018-03-17 17:36:54.000</td>\n      <td>83981</td>\n      <td>711.60</td>\n      <td>2018-03-17T19:08:04.728Z</td>\n      <td>15804</td>\n      <td>60628</td>\n      <td>7549</td>\n      <td>...</td>\n      <td>29849494.00</td>\n      <td>2018-03-17T18:46:10.000Z</td>\n      <td>105</td>\n      <td>146.00</td>\n      <td>47.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>3e9f91659c6cfd2ef4e3f1db04d19f81c24d59f3</th>\n      <td>https://www.cnn.com/2018/03/01/politics/ivanka...</td>\n      <td>Exclusive: FBI counterintel looks at Ivanka Tr...</td>\n      <td>2018-03-01 23:01:21.164</td>\n      <td>2018-03-01 22:59:33.000</td>\n      <td>58344</td>\n      <td>294.07</td>\n      <td>2018-03-02T16:15:13.750Z</td>\n      <td>12208</td>\n      <td>36614</td>\n      <td>9522</td>\n      <td>...</td>\n      <td>29763429.00</td>\n      <td>2018-03-01T23:15:05.000Z</td>\n      <td>105</td>\n      <td>1276.00</td>\n      <td>45.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>9afbf17229fbe2035b78545478034672f64db046</th>\n      <td>https://www.cnn.com/2018/03/08/politics/trump-...</td>\n      <td>Trump upset with Sanders over Stormy Daniels r...</td>\n      <td>2018-03-08 13:49:18.486</td>\n      <td>2018-03-08 13:42:56.000</td>\n      <td>75453</td>\n      <td>313.91</td>\n      <td>2018-03-08T15:47:10.491Z</td>\n      <td>22492</td>\n      <td>46863</td>\n      <td>6098</td>\n      <td>...</td>\n      <td>29794913.00</td>\n      <td>2018-03-08T15:30:12.000Z</td>\n      <td>105</td>\n      <td>153.00</td>\n      <td>46.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>6b7e492f18852c185ce675613126ecc1dc635ad8</th>\n      <td>https://www.cnn.com/2018/03/09/us/florida-gov-...</td>\n      <td>Florida Gov. Rick Scott signs gun bill</td>\n      <td>2018-03-09 20:19:13.516</td>\n      <td>2018-03-09 20:14:08.000</td>\n      <td>63286</td>\n      <td>191.69</td>\n      <td>2018-03-09T22:18:14.865Z</td>\n      <td>21148</td>\n      <td>34852</td>\n      <td>7286</td>\n      <td>...</td>\n      <td>29803315.00</td>\n      <td>2018-03-09T20:30:44.000Z</td>\n      <td>105</td>\n      <td>597.00</td>\n      <td>45.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>0bc531fbd47a9cbf242866e491b5912b92138391</th>\n      <td>https://www.huffingtonpost.com/entry/florida-p...</td>\n      <td>Exclusive: Florida Public School Teacher Has A...</td>\n      <td>2018-03-03 17:04:20.369</td>\n      <td>2018-03-03 17:02:22.984</td>\n      <td>348983</td>\n      <td>343.78</td>\n      <td>2018-03-03T21:52:08.809Z</td>\n      <td>98997</td>\n      <td>200766</td>\n      <td>49220</td>\n      <td>...</td>\n      <td>9855456.00</td>\n      <td>2018-03-03T17:30:30.000Z</td>\n      <td>215</td>\n      <td>1163.00</td>\n      <td>50.00</td>\n      <td>17.00</td>\n      <td>9.00</td>\n      <td>13.00</td>\n      <td>39.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>e0c9b941ff0b4d0875f3da9f2faa3229e902bf7c</th>\n      <td>https://www.huffingtonpost.com/entry/teens-kil...</td>\n      <td>73 Teens Shot To Death In The 37 Days Since Th...</td>\n      <td>2018-03-23 23:46:11.064</td>\n      <td>2018-03-23 23:32:05.860</td>\n      <td>205380</td>\n      <td>153.51</td>\n      <td>2018-03-24T14:10:06.582Z</td>\n      <td>16975</td>\n      <td>145972</td>\n      <td>42433</td>\n      <td>...</td>\n      <td>9872116.00</td>\n      <td>2018-03-24T13:30:06.000Z</td>\n      <td>215</td>\n      <td>852.00</td>\n      <td>50.00</td>\n      <td>17.00</td>\n      <td>9.00</td>\n      <td>13.00</td>\n      <td>39.00</td>\n      <td>89.00</td>\n    </tr>\n    <tr>\n      <th>4d6502bd4e3a0c3973855e284d48f12c1038cb52</th>\n      <td>https://www.nytimes.com/interactive/2018/obitu...</td>\n      <td>Women We Overlooked in 167 Years of New York T...</td>\n      <td>2018-03-08 06:01:13.571</td>\n      <td>2018-03-08 06:00:29.000</td>\n      <td>175255</td>\n      <td>937.13</td>\n      <td>2018-03-08T14:03:12.334Z</td>\n      <td>9797</td>\n      <td>124907</td>\n      <td>40551</td>\n      <td>...</td>\n      <td>15386187.00</td>\n      <td>2018-03-08T12:55:06.000Z</td>\n      <td>120</td>\n      <td>nan</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>4.00</td>\n      <td>14.00</td>\n      <td>38.00</td>\n      <td>88.00</td>\n    </tr>\n    <tr>\n      <th>ffc8f88a3fb0bf314c61ca1b09e8a66ffc2a75d2</th>\n      <td>https://www.cnn.com/2018/03/15/us/miami-bridge...</td>\n      <td>Pedestrian bridge collapses in Miami</td>\n      <td>2018-03-15 18:25:24.501</td>\n      <td>2018-03-15 18:22:27.000</td>\n      <td>99543</td>\n      <td>609.18</td>\n      <td>2018-03-15T19:09:15.074Z</td>\n      <td>19426</td>\n      <td>65311</td>\n      <td>14806</td>\n      <td>...</td>\n      <td>29842448.00</td>\n      <td>2018-03-15T18:29:06.000Z</td>\n      <td>105</td>\n      <td>43.00</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>5.00</td>\n      <td>15.00</td>\n      <td>40.00</td>\n      <td>88.00</td>\n    </tr>\n    <tr>\n      <th>773d4d6e929b7214b91c99af479d3428243d8834</th>\n      <td>https://www.huffingtonpost.com/entry/nra-march...</td>\n      <td>NRA Takes Aim At \u2018March For Our Lives' Rally, ...</td>\n      <td>2018-03-25 12:59:13.260</td>\n      <td>2018-03-25 12:49:22.000</td>\n      <td>120306</td>\n      <td>243.07</td>\n      <td>2018-03-25T14:45:14.160Z</td>\n      <td>39242</td>\n      <td>69841</td>\n      <td>11223</td>\n      <td>...</td>\n      <td>9872381.00</td>\n      <td>2018-03-25T14:00:10.000Z</td>\n      <td>215</td>\n      <td>456.00</td>\n      <td>49.00</td>\n      <td>17.00</td>\n      <td>9.00</td>\n      <td>13.00</td>\n      <td>39.00</td>\n      <td>88.00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>589381e0e53a564fcbf2b7f7d686fb4ffb7de28f</th>\n      <td>https://www.washingtonpost.com/national/10-thi...</td>\n      <td>10 Things to Know for Today</td>\n      <td>2018-03-14 10:19:12.084</td>\n      <td>2018-03-14 10:07:15.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-14T10:31:10.552Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>393.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>374eded6396cc66aac5f262bbf861d651040f5f1</th>\n      <td>http://www.bbc.co.uk/news/uk-scotland-tayside-...</td>\n      <td>Man charged with assault after CCTV appeal</td>\n      <td>2018-03-14 10:13:09.772</td>\n      <td>2018-03-14 10:09:32.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-03-15T09:41:07.716Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>65.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>235c18ee0dcdfc6d5ba97a5606413a4977bf289a</th>\n      <td>https://www.buzzfeed.com/hazelshearing/these-s...</td>\n      <td>These Sexual Assault Victims Say Bristol Unive...</td>\n      <td>2018-04-27 08:01:13.447</td>\n      <td>2018-03-14 10:10:14.000</td>\n      <td>1</td>\n      <td>0.00</td>\n      <td>2018-04-27T08:12:12.343Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>2604.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>ff34bc30c66bd4dc84aaee72eb5b399915ee8473</th>\n      <td>https://www.washingtonpost.com/business/techno...</td>\n      <td>Edmunds: These 6 new SUVs are worth the wait</td>\n      <td>2018-03-14 10:22:16.719</td>\n      <td>2018-03-14 10:15:04.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-14T10:34:11.039Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>940.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>a3a7576ea53b61ef6e26e68c2f99315e9578de9e</th>\n      <td>https://www.washingtonpost.com/sports/wizards/...</td>\n      <td>Cavaliers\u2019 Kyle Korver attends funeral for you...</td>\n      <td>2018-03-27 14:13:19.120</td>\n      <td>2018-03-27 14:10:16.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-28T13:41:16.514Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>155.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>0d7d4e6c8e63fb95d01c0b23691656917bd9c329</th>\n      <td>http://www.dailymail.co.uk/tvshowbiz/article-5...</td>\n      <td>Dave Hughes' crooked smile motivated Joe Hilde...</td>\n      <td>2018-03-14 09:40:21.414</td>\n      <td>2018-03-14 09:35:54.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-03-14T13:55:14.174Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>797.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>f4b9ffbc56344633583386f7a3e2aa90541be0a9</th>\n      <td>http://www.bbc.co.uk/news/live/uk-politics-par...</td>\n      <td>AMs quiz education watchdog</td>\n      <td>2018-03-14 09:37:12.559</td>\n      <td>2018-03-14 09:33:40.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-14T09:48:13.624Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>af9129581e2869e0cc8c3be7426c5fdcd4879c8f</th>\n      <td>https://www.washingtonpost.com/world/asia_paci...</td>\n      <td>Nepal plane crash survivors say it\u2019s a miracle...</td>\n      <td>2018-03-14 09:37:16.154</td>\n      <td>2018-03-14 09:30:21.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-14T09:48:13.627Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>142.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>c9b58956ac88ddc224ad13eb4071079b2380bc1b</th>\n      <td>https://edition.cnn.com/2016/04/13/sport/nba-f...</td>\n      <td>NBA Finals: The greatest records</td>\n      <td>2018-03-27 14:28:22.960</td>\n      <td>2018-03-27 14:19:59.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-28T14:58:12.849Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>105</td>\n      <td>312.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>88d2f8ebf711b99ac5054cd9dc253913bcbb36fc</th>\n      <td>https://www.washingtonpost.com/national/missin...</td>\n      <td>Missing Georgia teenager\u2019s remains found in sh...</td>\n      <td>2018-03-14 08:40:10.520</td>\n      <td>2018-03-14 08:30:09.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-14T10:52:10.127Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>249.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>116c491935236e1476a014d7ebca706125a22c07</th>\n      <td>https://www.washingtonpost.com/entertainment/w...</td>\n      <td>World Video Game Hall of Fame announces 2018 f...</td>\n      <td>2018-03-27 14:31:13.686</td>\n      <td>2018-03-27 14:19:12.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-03-27T19:46:09.073Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>150.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>3bee1f7ead7f873c4782aaef3e51a5e6af581888</th>\n      <td>http://www.dailymail.co.uk/tvshowbiz/article-5...</td>\n      <td>Michelle Bridges flaunts her taut visage after...</td>\n      <td>2018-03-14 08:40:13.393</td>\n      <td>2018-03-14 08:37:02.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-14T08:52:10.822Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>447.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>cf30cb097a3db61a654544abb4602c4252c69cd0</th>\n      <td>http://www.independent.co.uk/news/business/new...</td>\n      <td>Balfour Beatty more than doubles profits as tu...</td>\n      <td>2018-03-14 08:43:20.864</td>\n      <td>2018-03-14 08:42:38.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-03-14T09:55:11.653Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>386</td>\n      <td>218.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>ccb73b31b27ad487ff278e430a7d598bcc32d7a1</th>\n      <td>https://www.washingtonpost.com/world/europe/it...</td>\n      <td>Italy detains Egyptian imam accused of preachi...</td>\n      <td>2018-03-27 14:31:11.680</td>\n      <td>2018-03-27 14:16:14.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-03-27T15:43:13.263Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>149.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>1c38f71e043b6cba1674a51d23db3c9f09ced0c4</th>\n      <td>http://www.bbc.co.uk/news/uk-england-cambridge...</td>\n      <td>Hinchingbrooke Country Park death: Arrest in S...</td>\n      <td>2018-03-27 14:19:15.403</td>\n      <td>2018-03-27 14:16:02.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-03-27T16:32:08.406Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>207.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>b12039e3ab812c96a686904511beb8a2210a3702</th>\n      <td>https://www.washingtonpost.com/business/ecb-he...</td>\n      <td>ECB head: Higher inflation needed to end stimulus</td>\n      <td>2018-03-14 08:49:15.380</td>\n      <td>2018-03-14 08:44:17.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-14T11:02:10.420Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>146.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>68f4e9cb71bbd0b9140f03174aef3a75ac4026c0</th>\n      <td>http://www.independent.co.uk/sport/tennis/indi...</td>\n      <td>Caroline Wozniacki blows chance to overtake Si...</td>\n      <td>2018-03-14 08:49:18.512</td>\n      <td>2018-03-14 08:48:51.000</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>2018-03-14T09:00:15.662Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>386</td>\n      <td>407.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>e543cde9cf07954b432586b505e04440a5abc652</th>\n      <td>http://www.dailymail.co.uk/tvshowbiz/article-5...</td>\n      <td>MAFS' Tracey Jewel shows off her breast augmen...</td>\n      <td>2018-03-14 08:58:22.486</td>\n      <td>2018-03-14 08:53:34.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-14T09:10:08.806Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>462.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>f3cbcdfa23c724c3eb4cd6ca3bbe07260e0b8c2b</th>\n      <td>https://www.washingtonpost.com/national/waymo-...</td>\n      <td>Waymo to buy 20,000 Jaguars for robotic ride-h...</td>\n      <td>2018-03-27 14:19:20.518</td>\n      <td>2018-03-27 14:14:31.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-27T20:35:09.526Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>151.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>1892c26277a06c54a16378d085f77d3b096c88fe</th>\n      <td>https://www.washingtonpost.com/world/europe/ge...</td>\n      <td>Germany\u2019s parliament elects Angela Merkel for ...</td>\n      <td>2018-03-14 09:10:11.394</td>\n      <td>2018-03-14 08:57:10.000</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>2018-03-14T09:21:09.832Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>31.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>38ddc94c67c6f0250fe52d853385f3d73f9e00ec</th>\n      <td>https://www.washingtonpost.com/business/techno...</td>\n      <td>France to sue Apple and Google for abusive pra...</td>\n      <td>2018-03-14 09:07:08.901</td>\n      <td>2018-03-14 08:58:10.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-14T09:18:11.748Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>135.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>adf35886949348793ba290bed12c3c3f4e40e42e</th>\n      <td>https://www.nytimes.com/2018/03/14/learning/is...</td>\n      <td>Is Childhood Today Too Sterilized?</td>\n      <td>2018-03-14 09:01:26.994</td>\n      <td>2018-03-14 09:00:02.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-14T09:13:04.797Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>120</td>\n      <td>210.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>1860084c3babc992a5d7bf1b8a2e0d0a90a6b149</th>\n      <td>http://www.bbc.co.uk/news/entertainment-arts-4...</td>\n      <td>Music News LIVE: 14 March</td>\n      <td>2018-03-14 09:04:09.735</td>\n      <td>2018-03-14 09:03:18.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-14T09:15:08.370Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>58.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>dc489191d695f2ea21c5056bf52f04040cf63e92</th>\n      <td>https://www.washingtonpost.com/national/parent...</td>\n      <td>Parents to AP: Military ignored boy\u2019s abuse of...</td>\n      <td>2018-03-14 09:10:11.876</td>\n      <td>2018-03-14 09:05:30.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-14T11:22:15.494Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>148.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>73dd45ea4708dd4d1899583d534158ff654cf9a4</th>\n      <td>https://www.washingtonpost.com/national/how-ap...</td>\n      <td>How AP\u2019s investigation into childhood sex assa...</td>\n      <td>2018-03-14 09:22:12.358</td>\n      <td>2018-03-14 09:11:12.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-14T11:35:07.289Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>545.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>c5e55d09fd84c72d1bdb4958a4915114f52b6341</th>\n      <td>https://www.washingtonpost.com/business/spain-...</td>\n      <td>Spain: Future of pensions is main priority, sa...</td>\n      <td>2018-03-14 09:22:13.062</td>\n      <td>2018-03-14 09:13:12.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-15T06:50:03.633Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>146.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>eac51a65487c71639689314af6a89923cff1c95a</th>\n      <td>https://www.washingtonpost.com/business/recove...</td>\n      <td>Recovering Cathay Pacific Flies Into a Threat ...</td>\n      <td>2018-03-14 09:46:19.383</td>\n      <td>2018-03-14 09:24:36.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-15T03:11:13.923Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>494.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>7c7311d19dbdc874fb1a1635e939523f833fd554</th>\n      <td>https://www.washingtonpost.com/lifestyle/food/...</td>\n      <td>COOKING ON DEADLINE: Leftover Brisket Barley Soup</td>\n      <td>2018-03-27 14:19:22.409</td>\n      <td>2018-03-27 14:11:13.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-28T11:46:10.965Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>586.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>504b31c73509ae9657d6592a4998caee9e839819</th>\n      <td>http://www.bbc.co.uk/news/live/uk-northern-ire...</td>\n      <td>RHI Live: OFGEM officials face inquiry grilling</td>\n      <td>2018-03-14 09:31:12.851</td>\n      <td>2018-03-14 09:27:36.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-03-14T16:48:06.143Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>6205205421bc3e02bb31acdc0656147578c677f4</th>\n      <td>https://www.washingtonpost.com/national/charge...</td>\n      <td>Charges: Man shot dead after trying to record ...</td>\n      <td>2018-03-15 23:07:17.810</td>\n      <td>2018-03-15 22:58:32.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-16T10:27:07.148Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>157.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>146484 rows \u00d7 26 columns</p>\n</div>\n\n\n\n\n```python\ndata[\"score_diff\"] = data.promotion_score - data.response_score\n```\n\n\n```python\n# promoted but low response\ndata.sort_values(\"score_diff\", ascending=False).head(25)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n      <th>score_diff</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>42d519353c1ffa2303ad54ba8f6afe6ce0ed7b8f</th>\n      <td>https://www.buzzfeed.com/albertsamaha/good-guy...</td>\n      <td>She Thought She\u2019d Shot A Burglar. Then She Rea...</td>\n      <td>2018-03-23 11:31:19.815</td>\n      <td>2018-03-22 11:28:05</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-23T11:42:14.365Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2018-03-23T14:22:09.000Z</td>\n      <td>147</td>\n      <td>3003.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>44.00</td>\n      <td>44.00</td>\n    </tr>\n    <tr>\n      <th>512f3efdc422623da2139c574ddf9cf485f813fc</th>\n      <td>https://www.buzzfeed.com/charliewarzel/the-mou...</td>\n      <td>The Mountain West Is Experiencing A Second Gol...</td>\n      <td>2018-03-12 00:19:22.840</td>\n      <td>2018-03-07 16:18:51</td>\n      <td>1</td>\n      <td>0.09</td>\n      <td>2018-03-12T00:31:05.739Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>2018-03-12T05:04:02.000Z</td>\n      <td>147</td>\n      <td>3252.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>43.00</td>\n      <td>43.00</td>\n    </tr>\n    <tr>\n      <th>719512ac4c86426735c50c9773d2294fef708519</th>\n      <td>http://www.bbc.co.uk/news/world-europe-43552165</td>\n      <td>Putin: Mall fire was criminal negligence</td>\n      <td>2018-03-27 06:04:19.988</td>\n      <td>2018-03-26 01:50:59</td>\n      <td>8</td>\n      <td>0.64</td>\n      <td>2018-03-27T06:16:05.655Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>8</td>\n      <td>...</td>\n      <td>2018-03-27T07:44:41.000Z</td>\n      <td>96</td>\n      <td>707.00</td>\n      <td>2.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>46.00</td>\n      <td>42.00</td>\n    </tr>\n    <tr>\n      <th>5f76f987898ae0564ad528783cc4cb4a18369676</th>\n      <td>https://www.buzzfeed.com/borzoudaragahi/baghda...</td>\n      <td>After 15 Years Of War, Baghdad's Night Life Is...</td>\n      <td>2018-05-05 16:19:11.986</td>\n      <td>2018-03-30 13:39:53</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-05-05T16:31:10.611Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2018-05-06T20:04:46.000Z</td>\n      <td>147</td>\n      <td>909.00</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>42.00</td>\n      <td>42.00</td>\n    </tr>\n    <tr>\n      <th>737c0b787113751672e74a807bb490576e2cf943</th>\n      <td>https://www.buzzfeed.com/louispeitzman/theater...</td>\n      <td>Theater Professionals Say Eliminating Sexual H...</td>\n      <td>2018-03-31 13:19:09.974</td>\n      <td>2018-03-29 20:27:00</td>\n      <td>5</td>\n      <td>0.40</td>\n      <td>2018-03-31T13:30:07.064Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>...</td>\n      <td>2018-03-31T15:11:47.000Z</td>\n      <td>147</td>\n      <td>3656.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>44.00</td>\n      <td>42.00</td>\n    </tr>\n    <tr>\n      <th>515df476d5cfcd80af00d8a9cf6b9530a8def2a7</th>\n      <td>http://www.bbc.co.uk/news/live/entertainment-a...</td>\n      <td>Oscars 2018</td>\n      <td>2018-03-02 19:25:13.001</td>\n      <td>2018-03-02 19:22:31</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-03T11:51:08.649Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2018-03-05T01:22:58.000Z</td>\n      <td>96</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>41.00</td>\n      <td>41.00</td>\n    </tr>\n    <tr>\n      <th>044f712902ec6bc040d61e1e0b621c18dfe8b5ef</th>\n      <td>https://www.buzzfeed.com/nidhisubbaraman/faceb...</td>\n      <td>Here\u2019s How A Cabbage Juice \u201cCult\u201d With 58,000 ...</td>\n      <td>2018-03-17 13:44:15.842</td>\n      <td>2018-03-15 20:27:43</td>\n      <td>6</td>\n      <td>0.46</td>\n      <td>2018-03-17T13:56:02.749Z</td>\n      <td>0</td>\n      <td>2</td>\n      <td>4</td>\n      <td>...</td>\n      <td>2018-03-17T18:36:18.000Z</td>\n      <td>147</td>\n      <td>4576.00</td>\n      <td>2.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>45.00</td>\n      <td>41.00</td>\n    </tr>\n    <tr>\n      <th>e44ea39a4c91c5d841a7ccf22e197ba1dd941010</th>\n      <td>https://www.buzzfeed.com/kendalltaggart/secret...</td>\n      <td>Secret NYPD Files: Hundreds Of Officers Commit...</td>\n      <td>2018-03-05 11:01:26.053</td>\n      <td>2018-03-02 19:27:57</td>\n      <td>4</td>\n      <td>0.28</td>\n      <td>2018-03-05T11:13:08.100Z</td>\n      <td>0</td>\n      <td>2</td>\n      <td>2</td>\n      <td>...</td>\n      <td>2018-03-05T11:00:19.000Z</td>\n      <td>147</td>\n      <td>4197.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>43.00</td>\n      <td>41.00</td>\n    </tr>\n    <tr>\n      <th>bbcec1194a52059beffa7f0170bf6fbb8c7c0742</th>\n      <td>https://www.buzzfeed.com/lamvo/oscars-script-d...</td>\n      <td>We Compared Several Years Of Oscars Best Pictu...</td>\n      <td>2018-03-03 00:13:18.340</td>\n      <td>2018-03-02 23:10:08</td>\n      <td>11</td>\n      <td>0.07</td>\n      <td>2018-03-03T05:30:11.035Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>11</td>\n      <td>...</td>\n      <td>2018-03-04T18:13:00.000Z</td>\n      <td>147</td>\n      <td>1368.00</td>\n      <td>2.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>45.00</td>\n      <td>41.00</td>\n    </tr>\n    <tr>\n      <th>07d6bb8bd3c9e6df61c120dcf554c7a4d243d77f</th>\n      <td>https://www.buzzfeed.com/danvergano/heroine-op...</td>\n      <td>This Town Is At The Center Of The US Opioid Cr...</td>\n      <td>2018-03-03 15:09:14.487</td>\n      <td>2018-03-02 15:20:47</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2018-03-03T15:21:15.398Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2018-03-04T01:02:29.000Z</td>\n      <td>147</td>\n      <td>2772.00</td>\n      <td>0.00</td>\n      <td>17.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>40.00</td>\n      <td>40.00</td>\n      <td>40.00</td>\n    </tr>\n    <tr>\n      <th>31bd466fdfce3e9ae907f91a2178b6a12a460f1b</th>\n      <td>https://www.buzzfeed.com/alisonwillmore/ready-...</td>\n      <td>\u201cReady Player One\u201d Is An Accidental Horror Mov...</td>\n      <td>2018-04-01 15:54:15.397</td>\n      <td>2018-03-31 16:59:26</td>\n      <td>22</td>\n      <td>0.37</td>\n      <td>2018-04-01T17:05:18.157Z</td>\n      <td>0</td>\n      <td>15</td>\n      <td>7</td>\n      <td>...</td>\n      <td>2018-04-01T22:06:30.000Z</td>\n      <td>147</td>\n      <td>1408.00</td>\n      <td>4.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>48.00</td>\n      <td>40.00</td>\n    </tr>\n    <tr>\n      <th>a7ed7f09b6f3909a1bf6188c556291884c66ab06</th>\n      <td>http://www.bbc.co.uk/news/live/uk-politics-435...</td>\n      <td>English local elections 2018</td>\n      <td>2018-03-26 11:04:06.928</td>\n      <td>2018-03-26 11:01:52</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2018-03-27T03:26:12.038Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>2018-05-03T22:56:23.000Z</td>\n      <td>96</td>\n      <td>nan</td>\n      <td>0.00</td>\n      <td>20.00</td>\n      <td>4.00</td>\n      <td>15.00</td>\n      <td>39.00</td>\n      <td>39.00</td>\n      <td>39.00</td>\n    </tr>\n    <tr>\n      <th>22ebd1f10c19bdb54727cb59989d51e814428c53</th>\n      <td>https://www.buzzfeed.com/danvergano/ale-shooti...</td>\n      <td>Rich People Will Soon Be Able To Buy Fake Mete...</td>\n      <td>2018-03-25 14:44:14.146</td>\n      <td>2018-03-24 13:17:38</td>\n      <td>2</td>\n      <td>0.09</td>\n      <td>2018-03-25T14:56:11.764Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>...</td>\n      <td>2018-03-25T15:44:26.000Z</td>\n      <td>147</td>\n      <td>845.00</td>\n      <td>1.00</td>\n      <td>18.00</td>\n      <td>11.00</td>\n      <td>11.00</td>\n      <td>40.00</td>\n      <td>41.00</td>\n      <td>39.00</td>\n    </tr>\n    <tr>\n      <th>d573ec8e1d6a43be40ca46acf2ee249c1398d745</th>\n      <td>https://www.buzzfeed.com/hannahalothman/this-i...</td>\n      <td>This Is What It's Like To Be Put To Sleep So Y...</td>\n      <td>2018-03-17 11:52:16.580</td>\n      <td>2018-03-16 19:12:33</td>\n      <td>43</td>\n      <td>0.25</td>\n      <td>2018-03-17T13:04:14.124Z</td>\n      <td>6</td>\n      <td>19</td>\n      <td>18</td>\n      <td>...</td>\n      <td>2018-03-18T07:44:10.000Z</td>\n      <td>147</td>\n      <td>3579.00</td>\n      <td>6.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>50.00</td>\n      <td>38.00</td>\n    </tr>\n    <tr>\n      <th>180467647e6639290cf5684d36823b38f1f0a2f5</th>\n      <td>https://www.buzzfeed.com/albertsamaha/filipino...</td>\n      <td>I Followed My Uncle\u2019s Legend To Italy, And Fou...</td>\n      <td>2018-03-31 15:04:13.911</td>\n      <td>2018-03-30 16:29:47</td>\n      <td>13</td>\n      <td>0.08</td>\n      <td>2018-03-31T16:16:10.694Z</td>\n      <td>0</td>\n      <td>3</td>\n      <td>10</td>\n      <td>...</td>\n      <td>2018-03-31T21:13:09.000Z</td>\n      <td>147</td>\n      <td>6252.00</td>\n      <td>3.00</td>\n      <td>19.00</td>\n      <td>11.00</td>\n      <td>11.00</td>\n      <td>41.00</td>\n      <td>44.00</td>\n      <td>38.00</td>\n    </tr>\n    <tr>\n      <th>041fcd233fce6a0a01754aefa84d6928f91bd695</th>\n      <td>https://www.buzzfeed.com/sylviaobell/black-act...</td>\n      <td>Here\u2019s What Black Actors Say They Need From Ti...</td>\n      <td>2018-03-26 23:59:13.622</td>\n      <td>2018-03-26 21:20:45</td>\n      <td>40</td>\n      <td>0.20</td>\n      <td>2018-03-27T01:11:18.458Z</td>\n      <td>4</td>\n      <td>25</td>\n      <td>11</td>\n      <td>...</td>\n      <td>2018-03-28T03:30:43.000Z</td>\n      <td>147</td>\n      <td>1534.00</td>\n      <td>6.00</td>\n      <td>19.00</td>\n      <td>14.00</td>\n      <td>11.00</td>\n      <td>44.00</td>\n      <td>50.00</td>\n      <td>38.00</td>\n    </tr>\n    <tr>\n      <th>e7d299569233947afddaeeddacf390842a30f733</th>\n      <td>https://www.buzzfeed.com/charliewarzel/silicon...</td>\n      <td>Silicon Valley Is Having An Existential Crisis...</td>\n      <td>2018-03-13 14:49:15.190</td>\n      <td>2018-03-13 03:53:47</td>\n      <td>29</td>\n      <td>0.15</td>\n      <td>2018-03-14T03:10:11.630Z</td>\n      <td>0</td>\n      <td>11</td>\n      <td>18</td>\n      <td>...</td>\n      <td>2018-03-14T02:07:22.000Z</td>\n      <td>147</td>\n      <td>1188.00</td>\n      <td>5.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>47.00</td>\n      <td>37.00</td>\n    </tr>\n    <tr>\n      <th>abecd354933cbaca20fc43f619a379b682fd1d01</th>\n      <td>https://www.buzzfeed.com/rahawahaile/selma-civ...</td>\n      <td>Hiking The Selma Montgomery Trail</td>\n      <td>2018-04-01 13:09:10.601</td>\n      <td>2018-03-30 14:23:54</td>\n      <td>2</td>\n      <td>0.20</td>\n      <td>2018-04-01T13:20:07.352Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>...</td>\n      <td>2018-04-01T18:11:32.000Z</td>\n      <td>147</td>\n      <td>3269.00</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>7.00</td>\n      <td>11.00</td>\n      <td>37.00</td>\n      <td>38.00</td>\n      <td>36.00</td>\n    </tr>\n    <tr>\n      <th>fb80249318c8be37a4d870ea4ba997d31263b3ab</th>\n      <td>https://www.buzzfeed.com/tylerkingkade/what-it...</td>\n      <td>What It\u2019s Like For School Shooting Survivors T...</td>\n      <td>2018-03-20 13:04:24.495</td>\n      <td>2018-03-19 23:47:29</td>\n      <td>39</td>\n      <td>0.27</td>\n      <td>2018-03-20T17:18:12.228Z</td>\n      <td>1</td>\n      <td>22</td>\n      <td>16</td>\n      <td>...</td>\n      <td>2018-03-20T16:24:07.000Z</td>\n      <td>147</td>\n      <td>2188.00</td>\n      <td>6.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>48.00</td>\n      <td>36.00</td>\n    </tr>\n    <tr>\n      <th>49d1f5a72ccfe6e37cba6657efd46528bf2b2cc1</th>\n      <td>https://www.buzzfeed.com/alexkantrowitz/facebo...</td>\n      <td>Facebook's Political Nightmare Is About To Get...</td>\n      <td>2018-03-06 14:58:17.643</td>\n      <td>2018-03-05 23:06:47</td>\n      <td>59</td>\n      <td>0.32</td>\n      <td>2018-03-06T19:13:08.185Z</td>\n      <td>6</td>\n      <td>11</td>\n      <td>42</td>\n      <td>...</td>\n      <td>2018-03-06T18:36:18.000Z</td>\n      <td>147</td>\n      <td>1841.00</td>\n      <td>7.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>50.00</td>\n      <td>36.00</td>\n    </tr>\n    <tr>\n      <th>50fec0d08992fc98fb0111ef4aff5efadb107b93</th>\n      <td>https://www.buzzfeed.com/tamerragriffin/miguna...</td>\n      <td>This Lawyer Was Born In Kenya But The Governme...</td>\n      <td>2018-03-27 19:40:20.520</td>\n      <td>2018-03-27 19:17:41</td>\n      <td>55</td>\n      <td>0.20</td>\n      <td>2018-03-27T19:51:12.488Z</td>\n      <td>0</td>\n      <td>25</td>\n      <td>30</td>\n      <td>...</td>\n      <td>2018-03-27T20:25:26.000Z</td>\n      <td>147</td>\n      <td>858.00</td>\n      <td>7.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>49.00</td>\n      <td>35.00</td>\n    </tr>\n    <tr>\n      <th>b94fd95755d5c76accf8df4202c931e5bddbfe85</th>\n      <td>https://www.buzzfeed.com/gabrielsanchez/24-of-...</td>\n      <td>24 Of The Most Iconic Pictures From Oscars His...</td>\n      <td>2018-03-04 17:46:29.898</td>\n      <td>2018-03-01 20:44:40</td>\n      <td>2</td>\n      <td>0.18</td>\n      <td>2018-03-04T17:58:10.670Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>...</td>\n      <td>2018-03-05T00:12:00.000Z</td>\n      <td>147</td>\n      <td>nan</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>6.00</td>\n      <td>11.00</td>\n      <td>36.00</td>\n      <td>37.00</td>\n      <td>35.00</td>\n    </tr>\n    <tr>\n      <th>b11cb512de184a6cf579f3726a1ddcdc07a172ec</th>\n      <td>https://www.buzzfeed.com/mattberman/david-shul...</td>\n      <td>Trump's Veterans Affairs Secretary David Shulk...</td>\n      <td>2018-03-28 21:43:15.112</td>\n      <td>2018-03-28 21:39:27</td>\n      <td>71</td>\n      <td>0.30</td>\n      <td>2018-03-28T21:54:14.461Z</td>\n      <td>16</td>\n      <td>30</td>\n      <td>25</td>\n      <td>...</td>\n      <td>2018-03-29T02:10:56.000Z</td>\n      <td>147</td>\n      <td>293.00</td>\n      <td>8.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>51.00</td>\n      <td>35.00</td>\n    </tr>\n    <tr>\n      <th>4afb8c4ac700d5419654f8445622ec01cb454b8a</th>\n      <td>https://www.buzzfeed.com/adambvary/5-reasons-w...</td>\n      <td>5 Reasons Why This Year's Best Picture Is The ...</td>\n      <td>2018-03-03 16:49:11.480</td>\n      <td>2018-03-03 00:13:26</td>\n      <td>58</td>\n      <td>0.29</td>\n      <td>2018-03-03T23:20:43.186Z</td>\n      <td>1</td>\n      <td>48</td>\n      <td>9</td>\n      <td>...</td>\n      <td>2018-03-03T22:02:54.000Z</td>\n      <td>147</td>\n      <td>1124.00</td>\n      <td>7.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>49.00</td>\n      <td>35.00</td>\n    </tr>\n    <tr>\n      <th>63896d10a68d35756e94dfe8076a28fa2937c098</th>\n      <td>https://www.buzzfeed.com/hazelshearing/russia-...</td>\n      <td>Russia Will Expel 23 British Diplomats As Tens...</td>\n      <td>2018-03-17 08:49:19.698</td>\n      <td>2018-03-17 08:49:02</td>\n      <td>78</td>\n      <td>0.48</td>\n      <td>2018-03-17T18:07:02.743Z</td>\n      <td>7</td>\n      <td>46</td>\n      <td>25</td>\n      <td>...</td>\n      <td>2018-03-17T17:15:14.000Z</td>\n      <td>147</td>\n      <td>229.00</td>\n      <td>8.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>50.00</td>\n      <td>34.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>25 rows \u00d7 27 columns</p>\n</div>\n\n\n\n\n```python\n# high response but not promoted\ndata.sort_values(\"score_diff\", ascending=True).head(25)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>word_count</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n      <th>score_diff</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>50274b99fd61c30213190e1f47e61c06b0fe8444</th>\n      <td>https://www.cnn.com/2018/03/24/us/naomi-wadler...</td>\n      <td>11-year-old speaks up for the black girls whos...</td>\n      <td>2018-03-24 17:58:21.797</td>\n      <td>2018-03-24 17:54:04.000</td>\n      <td>220229</td>\n      <td>229.14</td>\n      <td>2018-03-24T22:19:05.478Z</td>\n      <td>10005</td>\n      <td>189918</td>\n      <td>20306</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>105</td>\n      <td>400.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>220bc1e5ff5023dabe5ff4aab0cf50d422d64a6d</th>\n      <td>https://www.nytimes.com/2018/03/13/us/ice-spok...</td>\n      <td>ICE Spokesman Resigns, Saying He Could No Long...</td>\n      <td>2018-03-13 15:28:06.745</td>\n      <td>2018-03-13 15:26:00.000</td>\n      <td>490246</td>\n      <td>592.80</td>\n      <td>2018-03-13T17:12:05.255Z</td>\n      <td>43354</td>\n      <td>363565</td>\n      <td>83327</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>120</td>\n      <td>659.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>5217dabb2788a25fb6ab6cf6903a5a565fbfdd3b</th>\n      <td>https://www.cnn.com/2018/03/14/us/nikolas-cruz...</td>\n      <td>Nikolas Cruz: Not guilty plea entered on Parkl...</td>\n      <td>2018-03-14 18:16:14.627</td>\n      <td>2018-03-14 18:10:07.000</td>\n      <td>319745</td>\n      <td>312.88</td>\n      <td>2018-03-17T13:07:04.378Z</td>\n      <td>106801</td>\n      <td>141537</td>\n      <td>71407</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>105</td>\n      <td>327.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>665b158f2d4382c825e9c95181e19a880d0ea444</th>\n      <td>https://www.huffingtonpost.com/entry/man-award...</td>\n      <td>Innocent Man Awarded $1 Million After Spending...</td>\n      <td>2018-03-22 23:04:19.286</td>\n      <td>2018-03-22 22:45:08.830</td>\n      <td>166773</td>\n      <td>224.08</td>\n      <td>2018-03-26T01:05:03.403Z</td>\n      <td>45996</td>\n      <td>99141</td>\n      <td>21636</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>666.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>4e0f5018cbbd109c03fb7b5c2b115b6f83787461</th>\n      <td>http://www.foxnews.com/lifestyle/2018/03/01/ca...</td>\n      <td>California has worst 'quality of life' in US, ...</td>\n      <td>2018-03-01 06:04:37.010</td>\n      <td>2018-03-01 05:50:40.000</td>\n      <td>158939</td>\n      <td>376.80</td>\n      <td>2018-03-02T04:07:09.673Z</td>\n      <td>46730</td>\n      <td>88830</td>\n      <td>23379</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>262.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>811b11341fd9cf3570bfc99a75c00d80380e741f</th>\n      <td>https://www.washingtonpost.com/news/morning-mi...</td>\n      <td>High school students are marching 50 miles to ...</td>\n      <td>2018-03-26 10:34:13.083</td>\n      <td>2018-03-26 10:28:00.000</td>\n      <td>228839</td>\n      <td>725.92</td>\n      <td>2018-03-27T13:03:05.545Z</td>\n      <td>19054</td>\n      <td>188846</td>\n      <td>20939</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>929.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>49c7c48264287c418b4f325a27cafa6f66f2c05c</th>\n      <td>https://www.nytimes.com/2018/03/14/us/politics...</td>\n      <td>Democrat\u2019s Strong Performance in Pennsylvania ...</td>\n      <td>2018-03-14 09:49:14.808</td>\n      <td>2018-03-14 09:48:15.000</td>\n      <td>130754</td>\n      <td>396.00</td>\n      <td>2018-03-14T13:00:10.561Z</td>\n      <td>13571</td>\n      <td>109852</td>\n      <td>7331</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>120</td>\n      <td>839.00</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>49.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>8fc7a94c76f872356ed483b7ac17adac5512eeaf</th>\n      <td>http://www.dailymail.co.uk/health/article-5559...</td>\n      <td>NHS BANS over-the-counter remedies on prescrip...</td>\n      <td>2018-03-29 15:31:23.764</td>\n      <td>2018-03-29 15:30:11.000</td>\n      <td>192930</td>\n      <td>2579.73</td>\n      <td>2018-03-29T21:07:11.238Z</td>\n      <td>50619</td>\n      <td>113504</td>\n      <td>28807</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>844.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>3cefbaccf74c67435f2d9e3ce03a833a6a031dd9</th>\n      <td>http://www.foxnews.com/politics/2018/03/16/for...</td>\n      <td>Former FBI Deputy Director Andrew McCabe fired</td>\n      <td>2018-03-17 02:09:08.956</td>\n      <td>2018-03-17 02:05:10.000</td>\n      <td>153446</td>\n      <td>723.92</td>\n      <td>2018-03-17T02:31:08.779Z</td>\n      <td>34418</td>\n      <td>101832</td>\n      <td>17196</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>63.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>2029aee2f236d917e866b77fff279d24bf704f53</th>\n      <td>https://www.rt.com/news/421292-russia-uk-skrip...</td>\n      <td>Russia-UK standoff over Skripal case: Ex-Londo...</td>\n      <td>2018-03-14 15:10:29.252</td>\n      <td>2018-03-14 15:09:53.000</td>\n      <td>181999</td>\n      <td>2973.62</td>\n      <td>2018-03-14T18:25:05.286Z</td>\n      <td>25191</td>\n      <td>11859</td>\n      <td>144949</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>365</td>\n      <td>32.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>b81059e9e80c976fb540b0e2072e2e0de13d8237</th>\n      <td>https://www.theguardian.com/world/2018/mar/15/...</td>\n      <td>Marielle Franco, councillor and police critic,...</td>\n      <td>2018-03-15 05:25:08.366</td>\n      <td>2018-03-15 05:22:02.000</td>\n      <td>144482</td>\n      <td>148.20</td>\n      <td>2018-03-15T13:30:07.659Z</td>\n      <td>7767</td>\n      <td>115115</td>\n      <td>21600</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>142</td>\n      <td>307.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>4b263c68cdef616305925dbc652ca78ea2893928</th>\n      <td>http://www.foxnews.com/politics/2018/03/09/tru...</td>\n      <td>Trump pardons former Navy sailor imprisoned fo...</td>\n      <td>2018-03-09 19:44:16.711</td>\n      <td>2018-03-09 19:35:00.000</td>\n      <td>171069</td>\n      <td>698.29</td>\n      <td>2018-03-10T14:06:13.319Z</td>\n      <td>22645</td>\n      <td>129024</td>\n      <td>19400</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>34.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>52.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>c3660f6b3c146aaf04faf55e0c0bf241e29e8989</th>\n      <td>https://www.washingtonpost.com/news/morning-mi...</td>\n      <td>Texas woman sentenced to 5 years in prison for...</td>\n      <td>2018-03-30 10:14:11.434</td>\n      <td>2018-03-30 10:01:00.000</td>\n      <td>174415</td>\n      <td>129.75</td>\n      <td>2018-03-30T21:35:06.218Z</td>\n      <td>37119</td>\n      <td>108128</td>\n      <td>29168</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>886.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>52.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>c47143c6da051a69409d08f1b0a625b4e98459aa</th>\n      <td>https://www.npr.org/sections/thetwo-way/2018/0...</td>\n      <td>Man Who Bid For Border Wall Contract Charged I...</td>\n      <td>2018-03-14 22:29:12.121</td>\n      <td>2018-03-14 21:44:29.000</td>\n      <td>118176</td>\n      <td>48.82</td>\n      <td>2018-03-15T23:34:10.721Z</td>\n      <td>15836</td>\n      <td>76427</td>\n      <td>25913</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>594</td>\n      <td>790.00</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>51.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>06a46e015b59b2b7a4e9f3bbd178631499f84d0b</th>\n      <td>https://www.indy100.com/article/donald-trump-m...</td>\n      <td>Scientists discovered a moth with golden hair ...</td>\n      <td>2018-03-27 15:24:16.483</td>\n      <td>2018-03-27 15:15:44.000</td>\n      <td>108340</td>\n      <td>8.62</td>\n      <td>2018-03-28T02:43:16.019Z</td>\n      <td>10078</td>\n      <td>84470</td>\n      <td>13792</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>5014</td>\n      <td>233.00</td>\n      <td>48.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>49.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>ad709da694f5f5cfdabb47c2f7f7e7554ae12c7c</th>\n      <td>http://www.foxnews.com/politics/2018/03/13/hil...</td>\n      <td>Hillary Clinton blames 'pressure' from men for...</td>\n      <td>2018-03-13 12:24:18.762</td>\n      <td>2018-03-13 12:20:50.000</td>\n      <td>124599</td>\n      <td>260.88</td>\n      <td>2018-03-13T16:50:09.695Z</td>\n      <td>51816</td>\n      <td>61737</td>\n      <td>11046</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>404.00</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>51.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>29a501b1c0a690e5cd174ab7e6d13b11122a93b8</th>\n      <td>https://www.cnn.com/2018/03/28/politics/alton-...</td>\n      <td>White House calls police shootings of black me...</td>\n      <td>2018-03-29 15:07:20.076</td>\n      <td>2018-03-29 14:55:23.000</td>\n      <td>128890</td>\n      <td>289.15</td>\n      <td>2018-03-29T17:06:13.811Z</td>\n      <td>30686</td>\n      <td>73449</td>\n      <td>24755</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>105</td>\n      <td>454.00</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>51.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>0d311bd9bc88f483d8cd59c3bdd0f72f6fbe7d75</th>\n      <td>https://www.nbcnews.com/feature/nbc-out/oregon...</td>\n      <td>Oregon Supreme Court suspends judge who refuse...</td>\n      <td>2018-03-19 03:37:20.964</td>\n      <td>2018-03-19 03:34:39.000</td>\n      <td>96376</td>\n      <td>145.45</td>\n      <td>2018-03-19T17:08:06.367Z</td>\n      <td>14772</td>\n      <td>72125</td>\n      <td>9479</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>826</td>\n      <td>nan</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>48.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>418cc03dd36ea891048b13fe7d67ac936ded0b4e</th>\n      <td>https://www.nbcnews.com/storyline/paris-terror...</td>\n      <td>Eagles of Death Metal frontman calls Parkland ...</td>\n      <td>2018-03-26 16:10:08.842</td>\n      <td>2018-03-26 16:08:53.000</td>\n      <td>84246</td>\n      <td>179.64</td>\n      <td>2018-03-27T16:54:13.990Z</td>\n      <td>23308</td>\n      <td>55832</td>\n      <td>5106</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>826</td>\n      <td>380.00</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>48.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>7a45be3e4cae44045719b087b12c263686a10f54</th>\n      <td>http://www.foxnews.com/opinion/2018/03/07/tamm...</td>\n      <td>Tammy Bruce: California chaos -- Unchallenged ...</td>\n      <td>2018-03-07 15:29:11.736</td>\n      <td>2018-03-07 15:22:08.000</td>\n      <td>87396</td>\n      <td>356.16</td>\n      <td>2018-03-08T22:07:12.830Z</td>\n      <td>10953</td>\n      <td>63055</td>\n      <td>13388</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>936.00</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>49.00</td>\n      <td>-45.00</td>\n    </tr>\n    <tr>\n      <th>d4ea734b1b76e25df1d75bf955cfee3415c67d2e</th>\n      <td>http://yournewswire.com/rockefeller-big-pharma...</td>\n      <td>How Rockefeller Founded Big Pharma And Waged W...</td>\n      <td>2018-03-27 17:29:26.929</td>\n      <td>2018-03-27 16:39:37.000</td>\n      <td>206259</td>\n      <td>58.82</td>\n      <td>2018-03-29T13:51:13.201Z</td>\n      <td>34034</td>\n      <td>114928</td>\n      <td>57297</td>\n      <td>...</td>\n      <td>2018-04-05T08:20:00.000Z</td>\n      <td>22568</td>\n      <td>742.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>4.00</td>\n      <td>5.00</td>\n      <td>55.00</td>\n      <td>-45.00</td>\n    </tr>\n    <tr>\n      <th>8e677451fa0eb8ac53c9431bd3c780e24c15313a</th>\n      <td>http://www.dailymail.co.uk/tvshowbiz/article-5...</td>\n      <td>Married At First Sight's Ash now dating Justin</td>\n      <td>2018-03-21 21:19:16.396</td>\n      <td>2018-03-21 21:16:49.000</td>\n      <td>74126</td>\n      <td>85.91</td>\n      <td>2018-03-22T03:09:07.965Z</td>\n      <td>57990</td>\n      <td>14690</td>\n      <td>1446</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>101.00</td>\n      <td>46.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>47.00</td>\n      <td>-45.00</td>\n    </tr>\n    <tr>\n      <th>c7ff5d9a2aacb0bbb6cf09c2137416a2b0b5ea8d</th>\n      <td>http://yournewswire.com/london-churches-mosques/</td>\n      <td>London Closes 500 Churches; Opens 423 New Mosques</td>\n      <td>2018-03-05 17:49:22.185</td>\n      <td>2018-03-05 17:34:50.000</td>\n      <td>265318</td>\n      <td>69.38</td>\n      <td>2018-03-06T21:13:09.677Z</td>\n      <td>67888</td>\n      <td>147744</td>\n      <td>49686</td>\n      <td>...</td>\n      <td>2018-03-06T22:43:36.000Z</td>\n      <td>22568</td>\n      <td>1064.00</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>4.00</td>\n      <td>5.00</td>\n      <td>55.00</td>\n      <td>-45.00</td>\n    </tr>\n    <tr>\n      <th>9dba841e93a95329b60a2d259aa5cc088fff53af</th>\n      <td>https://www.huffingtonpost.com/entry/justice-s...</td>\n      <td>Justice System Failed These 23 Black Victims</td>\n      <td>2018-03-28 21:04:22.008</td>\n      <td>2018-03-28 20:55:15.999</td>\n      <td>194436</td>\n      <td>51.85</td>\n      <td>2018-03-30T14:59:11.295Z</td>\n      <td>14885</td>\n      <td>123614</td>\n      <td>55937</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>nan</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>5.00</td>\n      <td>0.00</td>\n      <td>5.00</td>\n      <td>55.00</td>\n      <td>-45.00</td>\n    </tr>\n    <tr>\n      <th>bc9d99af54ec89e3e286b5ed111c2020a51d91c9</th>\n      <td>https://www.nytimes.com/2018/03/13/opinion/nra...</td>\n      <td>Dear National Rifle Association: We Won\u2019t Let ...</td>\n      <td>2018-03-13 23:52:04.852</td>\n      <td>2018-03-13 23:49:41.000</td>\n      <td>93521</td>\n      <td>159.67</td>\n      <td>2018-03-14T12:54:10.917Z</td>\n      <td>6482</td>\n      <td>75593</td>\n      <td>11446</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>120</td>\n      <td>611.00</td>\n      <td>47.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>50.00</td>\n      <td>-44.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>25 rows \u00d7 27 columns</p>\n</div>\n\n\n\nWrite that data to a file. Note that the scores here are provisional for two reasons:\n1. they should be using a rolling-month based on the article publication date to calculate medians/min/max etc, whereas in this workbook we as just using values for the month of May\n2. for analysis, we've rounded the numbers; we don't expect to do that for the actual scores\n\n\n```python\ndata.to_csv(\"articles_with_provisional_scores_\" + date_filename + \".csv\")\n```\n\n# Summary\n\nThe attention index of an article is comprised of four components:\n\n- *lead score* (max 20 points) based on how long an article was the lead story on the publisher's home page, scaled by the traffic to that publisher\n- *front score* (max 15 points) based on how long an article was present on the publisher's home page, scaled by traffic to that publisher\n- *Facebook promotion score* (max 15 points) based on whether the article was promoted to the publisher's Facebook brand page, scaled by the reach of that brand page\n- *response score* (max 50 points) based on the number of Facebook engagements the article received, relative to other articles\n\nOr, in other words:\n\n\\begin{align}\nattentionIndex_a &= leadScore_a + frontScore_a + facebookPromotionScore_a + responseScore_a \\\\\nleadScore_a &= 20 \\cdot \\left(\\frac{\\min(minsAsLead_a, 60)}{alexaRank_a}\\right) \\cdot \\left( \\frac{\\min(alexaRank)}{60} \\right) \\\\\nfrontScore_a &= \n15 \\cdot\n\\left(\\frac{\\min(minsOnFront_a, 1440)}{alexaRank_a \\cdot numArticlesOnFront_a}\\right) \\cdot\n\\left( \\frac{\\min(alexaRank \\cdot numArticlesOnFront)}{1440} \\right) \\\\\nfacebookPromotion_a &= \n\\begin{cases}\n 0 \\text{ if not shared on brand page }\\\\\n   15 \\cdot \\frac{\\log(brandPageLikes_a) - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))}  \\text{ otherwise }\n\\end{cases}   \n\\\\\nresponseScore_a &= \n\\begin{cases} \n   0 \\text{ if } engagements_a = 0 \\\\\n   50 \\cdot \n   \\frac{\\log(\\min(engagements_a,limit) + median(engagements)) - \\log(1 + median(engagements))}\n   {\\log(limit + median(engagements)) - \\log(1 + median(engagements))} \\text{ if } engagements_a > 0\n\\end{cases} \\\\\n\\end{align} \n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "ce1e251d4e363d3dc102bbcd9b2986bf4c8a52a6", "size": 738988, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "data/attention-index-march-2018.ipynb", "max_stars_repo_name": "kaleida/attention-index", "max_stars_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2017-06-03T11:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T10:02:06.000Z", "max_issues_repo_path": "data/attention-index-march-2018.ipynb", "max_issues_repo_name": "kaleida/attention-index", "max_issues_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data/attention-index-march-2018.ipynb", "max_forks_repo_name": "kaleida/attention-index", "max_forks_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 84.610487749, "max_line_length": 45324, "alphanum_fraction": 0.692158736, "converted": true, "num_tokens": 57230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32082130082460697, "lm_q2_score": 0.03846619146718183, "lm_q1q2_score": 0.012340773584269672}}
{"text": "\n\n# The IBM Quantum Account\n\nIn Qiskit we have an interface for backends and jobs that is useful for running circuits and extending to third-party backends. In this tutorial, we will review the core components of Qiskit\u2019s base backend framework, using the IBM Quantum account as an example.\n\nThe interface has three main components: the account, backends, and jobs:\n\n- **account**: Provides access to quantum devices and simulators, collectively called \u2018backends\u2019, and additional services tailored to a specific backend instance.\n\n- **backend**: A quantum device or simulator capable of running quantum circuits or pulse schedules.\n\n- **job**: A local reference to a collection of quantum circuits or pulse schedules submitted to a given backend.\n\n<div class=\"alert alert-block alert-info\">\n<b>Note:</b> To run the sample code in this tutorial, you'll need to have an <a href=\"https://quantum-computing.ibm.com/login\">IBM Quantum account</a> and have qiskit-ibm-provider installed. qiskit-ibm-provider is the interface for accessing IBM Quantum services.</div>\n\n\n## Table of contents\n\n1) [The Account](#account)\n\n\n2) [Backends](#backends)\n    \n    \n3) [Jobs](#jobs)\n\n## The Account <a name='account'></a>\n\nThe `IBMProvider` class enables you to access your IBM Quantum account, all of the backends (quantum systems or simulators), and additional services that are available to you.\n\nThis class has class methods to save your account to disk, view saved account on disk, \ndelete saved account from disk and also view the account currently active in the session.\nUsing the constructor you can load an account from disk or enable account for current session (without saving to disk).\n`IBMProvider` class can be initialized using the `API token`, which is used to authenticate to your IBM Quantum account.\n\nClass Methods:\n- `IBMProvider.save_account(TOKEN, INSTANCE)`: Save your account to disk for future use and optionally set a default hub/group/project to be used when loading your account.\n- `IBMProvider.saved_accounts()`: View the accounts saved to disk.\n- `IBMProvider.delete_account()`: Delete the saved account from disk.\n- `IBMProvider.active_account()`: List the account currently active in the session.\n\nConstructor Usage:\n- `IBMProvider()`: Load account and default hub/group/project using saved credentials.\n- `IBMProvider(TOKEN)`: Enable your account in the current session.\n\nYou can save an account to disk as shown below:\n\n\n```python\nfrom qiskit_ibm_provider import IBMProvider\n\n# IBMProvider.save_account(TOKEN)\n```\n\n`TOKEN` here is the API token you obtain from your IBM Quantum account.\n\n\nThen you can instantiate the `IBMProvider` class like below:\n\n\n```python\nprovider = IBMProvider()\nprovider\n```\n\n\n\n\n    <IBMProvider>\n\n\n\nThe `IBMProvider` class inherits from `qiskit.providers.BaseProvider` and implements the following instance methods:\n\n- `backends()`: Returns all backends available to the account.\n- `get_backend(NAME)`: Returns the named backend.\n\nUsing the provider instance from above:\n\n\n```python\nprovider = IBMProvider()\nprovider.backends()\n```\n\n\n\n\n    [<IBMBackend('ibmq_qasm_simulator')>,\n     <IBMBackend('ibmq_armonk')>,\n     <IBMBackend('ibmq_santiago')>,\n     <IBMBackend('ibmq_bogota')>,\n     <IBMBackend('ibmq_lima')>,\n     <IBMBackend('ibmq_belem')>,\n     <IBMBackend('ibmq_quito')>,\n     <IBMBackend('simulator_statevector')>,\n     <IBMBackend('simulator_mps')>,\n     <IBMBackend('simulator_extended_stabilizer')>,\n     <IBMBackend('simulator_stabilizer')>,\n     <IBMBackend('ibmq_manila')>]\n\n\n\nSelecting a backend is done by name using the `get_backend(NAME)` method:\n\n\n```python\nbackend = provider.get_backend(\"ibmq_qasm_simulator\")\nbackend\n```\n\n\n\n\n    <IBMBackend('ibmq_qasm_simulator')>\n\n\n\n### Filtering the Backends\n\nYou may also optionally filter the set of returned backends, by passing arguments that query the backend\u2019s `configuration`, `status`, or `properties`. The filters are passed by conditions and, for more general filters, you can make advanced functions using a lambda function.\n\nAs a first example lets return only those backends that are real quantum devices, and that are currently operational:\n\n\n```python\nprovider.backends(simulator=False, operational=True)\n```\n\n\n\n\n    [<IBMBackend('ibmq_armonk')>,\n     <IBMBackend('ibmq_santiago')>,\n     <IBMBackend('ibmq_bogota')>,\n     <IBMBackend('ibmq_lima')>,\n     <IBMBackend('ibmq_belem')>,\n     <IBMBackend('ibmq_quito')>,\n     <IBMBackend('ibmq_manila')>]\n\n\n\nYou can also filter by the minimum number of qubits the backends must have:\n\n\n```python\nprovider.backends(min_num_qubits=5, simulator=False, operational=True)\n```\n\n\n\n\n    [<IBMBackend('ibmq_santiago')>,\n     <IBMBackend('ibmq_bogota')>,\n     <IBMBackend('ibmq_lima')>,\n     <IBMBackend('ibmq_belem')>,\n     <IBMBackend('ibmq_quito')>,\n     <IBMBackend('ibmq_manila')>]\n\n\n\nLastly, show the least busy 5 qubit device (in terms of the number of jobs pending in the queue)\n\n\n```python\nfrom qiskit_ibm_provider import least_busy\n\nsmall_devices = provider.backends(min_num_qubits=5, simulator=False, operational=True)\nbackend = least_busy(small_devices)\nprint(backend)\n```\n\n    ibmq_belem\n\n\nThe above filters can be combined as desired.\n\n## Backends <a name='backends'></a>\n\nBackends represent either a simulator or a real quantum computer, and are responsible for running quantum circuits and/or pulse schedules and returning results. They have a `run` method which takes in one or more circuits as input, the Qiskit API serialization format, and returns a `BaseJob` object. This object allows asynchronous running of jobs for retrieving results from a backend when the job is completed.\n\n\nAt a minimum, backends use the following methods, inherited from `qiskit.providers.backend.BackendV1`:\n\n- `provider`: Returns the instance of `IBMProvider` class used to access the backend.\n- `name`: Returns the name of the backend.\n- `status()`: Returns the current status of the backend.\n- `configuration()`: Returns the backend configuration.\n- `properties()`: Returns the backend properties.\n- `run(circuit, **kwargs)`: Runs a circuit on the backend.\n\n\n[`IBMBackend`](https://qiskit.org/documentation/stubs/qiskit_ibm_provider.IBMBackend.html#qiskit_ibm_provider.IBMBackend) also accepts additional parameters to the `run()` method:\n\n- `job_name`: Custom name to be assigned to the job.\n- `job_tags`: Tags to be assigned to the job.\n\nAnd supports additional methods:\n\n- `defaults()`: Gives a data structure of typical default parameters, if applicable.\n- `job_limit()`: Returns the job limit for the backend.\n- `remaining_jobs_count()`: Returns the number of remaining jobs that could be submitted to the backend.\n- `active_jobs()`: Returns a list of unfinished jobs.\n\nRefer to the [`IBMBackend`](https://qiskit.org/documentation/stubs/qiskit_ibm_provider.IBMBackend.html#qiskit_ibm_provider.IBMBackend) documentation for a complete list of methods.\n\nLets load up the least busy backend from the `small_devices` filtered above:\n\n\n```python\nbackend = least_busy(small_devices)\n```\n\nSome examples using the different methods:\n\n\n```python\nbackend.provider\n```\n\n\n\n\n    <IBMProvider>\n\n\n\n\n```python\nbackend.name\n```\n\n\n\n\n    'ibmq_belem'\n\n\n\n\n```python\nbackend.status().to_dict()\n```\n\n\n\n\n    {'backend_name': 'ibmq_belem',\n     'backend_version': '1.0.14',\n     'operational': True,\n     'pending_jobs': 3,\n     'status_msg': 'active'}\n\n\n\nHere we see the name of the backend, the software version it is running, along with its operational status, number of jobs pending in the backends queue, and a more detailed status message.\n\nNext we look at the backend configuration and properties:\n\n\n```python\nbackend.configuration().to_dict()\n```\n\n\n\n\n    {'backend_name': 'ibmq_belem',\n     'backend_version': '1.0.14',\n     'n_qubits': 5,\n     'basis_gates': ['id', 'rz', 'sx', 'x', 'cx', 'reset'],\n     'gates': [{'name': 'id',\n       'parameters': [],\n       'qasm_def': 'gate id q { U(0, 0, 0) q; }',\n       'coupling_map': [[0], [1], [2], [3], [4]]},\n      {'name': 'rz',\n       'parameters': ['theta'],\n       'qasm_def': 'gate rz(theta) q { U(0, 0, theta) q; }',\n       'coupling_map': [[0], [1], [2], [3], [4]]},\n      {'name': 'sx',\n       'parameters': [],\n       'qasm_def': 'gate sx q { U(pi/2, 3*pi/2, pi/2) q; }',\n       'coupling_map': [[0], [1], [2], [3], [4]]},\n      {'name': 'x',\n       'parameters': [],\n       'qasm_def': 'gate x q { U(pi, 0, pi) q; }',\n       'coupling_map': [[0], [1], [2], [3], [4]]},\n      {'name': 'cx',\n       'parameters': [],\n       'qasm_def': 'gate cx q0, q1 { CX q0, q1; }',\n       'coupling_map': [[0, 1],\n        [1, 0],\n        [1, 2],\n        [1, 3],\n        [2, 1],\n        [3, 1],\n        [3, 4],\n        [4, 3]]},\n      {'name': 'reset', 'parameters': None, 'qasm_def': None}],\n     'local': False,\n     'simulator': False,\n     'conditional': False,\n     'open_pulse': False,\n     'memory': True,\n     'max_shots': 8192,\n     'coupling_map': [[0, 1],\n      [1, 0],\n      [1, 2],\n      [1, 3],\n      [2, 1],\n      [3, 1],\n      [3, 4],\n      [4, 3]],\n     'dynamic_reprate_enabled': True,\n     'supported_instructions': ['id',\n      'sx',\n      'shiftf',\n      'reset',\n      'cx',\n      'u1',\n      'u2',\n      'u3',\n      'play',\n      'delay',\n      'x',\n      'setf',\n      'acquire',\n      'measure',\n      'rz'],\n     'rep_delay_range': [0.0, 500.0],\n     'default_rep_delay': 250.0,\n     'max_experiments': 75,\n     'sample_name': 'family: Falcon, revision: 4, segment: T',\n     'n_registers': 1,\n     'credits_required': True,\n     'online_date': datetime.datetime(2021, 1, 8, 5, 0, tzinfo=tzutc()),\n     'description': '5 qubit device Belem',\n     'dt': 0.2222222222222222,\n     'dtm': 0.2222222222222222,\n     'processor_type': {'family': 'Falcon', 'revision': 4, 'segment': 'T'},\n     'acquisition_latency': [],\n     'allow_q_object': True,\n     'channels': {'acquire0': {'operates': {'qubits': [0]},\n       'purpose': 'acquire',\n       'type': 'acquire'},\n      'acquire1': {'operates': {'qubits': [1]},\n       'purpose': 'acquire',\n       'type': 'acquire'},\n      'acquire2': {'operates': {'qubits': [2]},\n       'purpose': 'acquire',\n       'type': 'acquire'},\n      'acquire3': {'operates': {'qubits': [3]},\n       'purpose': 'acquire',\n       'type': 'acquire'},\n      'acquire4': {'operates': {'qubits': [4]},\n       'purpose': 'acquire',\n       'type': 'acquire'},\n      'd0': {'operates': {'qubits': [0]}, 'purpose': 'drive', 'type': 'drive'},\n      'd1': {'operates': {'qubits': [1]}, 'purpose': 'drive', 'type': 'drive'},\n      'd2': {'operates': {'qubits': [2]}, 'purpose': 'drive', 'type': 'drive'},\n      'd3': {'operates': {'qubits': [3]}, 'purpose': 'drive', 'type': 'drive'},\n      'd4': {'operates': {'qubits': [4]}, 'purpose': 'drive', 'type': 'drive'},\n      'm0': {'operates': {'qubits': [0]}, 'purpose': 'measure', 'type': 'measure'},\n      'm1': {'operates': {'qubits': [1]}, 'purpose': 'measure', 'type': 'measure'},\n      'm2': {'operates': {'qubits': [2]}, 'purpose': 'measure', 'type': 'measure'},\n      'm3': {'operates': {'qubits': [3]}, 'purpose': 'measure', 'type': 'measure'},\n      'm4': {'operates': {'qubits': [4]}, 'purpose': 'measure', 'type': 'measure'},\n      'u0': {'operates': {'qubits': [0, 1]},\n       'purpose': 'cross-resonance',\n       'type': 'control'},\n      'u1': {'operates': {'qubits': [1, 0]},\n       'purpose': 'cross-resonance',\n       'type': 'control'},\n      'u2': {'operates': {'qubits': [1, 2]},\n       'purpose': 'cross-resonance',\n       'type': 'control'},\n      'u3': {'operates': {'qubits': [1, 3]},\n       'purpose': 'cross-resonance',\n       'type': 'control'},\n      'u4': {'operates': {'qubits': [2, 1]},\n       'purpose': 'cross-resonance',\n       'type': 'control'},\n      'u5': {'operates': {'qubits': [3, 1]},\n       'purpose': 'cross-resonance',\n       'type': 'control'},\n      'u6': {'operates': {'qubits': [3, 4]},\n       'purpose': 'cross-resonance',\n       'type': 'control'},\n      'u7': {'operates': {'qubits': [4, 3]},\n       'purpose': 'cross-resonance',\n       'type': 'control'}},\n     'conditional_latency': [],\n     'discriminators': ['linear_discriminator',\n      'quadratic_discriminator',\n      'hw_centroid'],\n     'hamiltonian': {'description': 'Qubits are modeled as Duffing oscillators. In this case, the system includes higher energy states, i.e. not just |0> and |1>. The Pauli operators are generalized via the following set of transformations:\\n\\n$(\\\\mathbb{I}-\\\\sigma_{i}^z)/2 \\\\rightarrow O_i \\\\equiv b^\\\\dagger_{i} b_{i}$,\\n\\n$\\\\sigma_{+} \\\\rightarrow b^\\\\dagger$,\\n\\n$\\\\sigma_{-} \\\\rightarrow b$,\\n\\n$\\\\sigma_{i}^X \\\\rightarrow b^\\\\dagger_{i} + b_{i}$.\\n\\nQubits are coupled through resonator buses. The provided Hamiltonian has been projected into the zero excitation subspace of the resonator buses leading to an effective qubit-qubit flip-flop interaction. The qubit resonance frequencies in the Hamiltonian are the cavity dressed frequencies and not exactly what is returned by the backend defaults, which also includes the dressing due to the qubit-qubit interactions.\\n\\nQuantities are returned in angular frequencies, with units 2*pi*GHz.\\n\\nWARNING: Currently not all system Hamiltonian information is available to the public, missing values have been replaced with 0.\\n',\n      'h_latex': '\\\\begin{align} \\\\mathcal{H}/\\\\hbar = & \\\\sum_{i=0}^{4}\\\\left(\\\\frac{\\\\omega_{q,i}}{2}(\\\\mathbb{I}-\\\\sigma_i^{z})+\\\\frac{\\\\Delta_{i}}{2}(O_i^2-O_i)+\\\\Omega_{d,i}D_i(t)\\\\sigma_i^{X}\\\\right) \\\\\\\\ & + J_{0,1}(\\\\sigma_{0}^{+}\\\\sigma_{1}^{-}+\\\\sigma_{0}^{-}\\\\sigma_{1}^{+}) + J_{1,2}(\\\\sigma_{1}^{+}\\\\sigma_{2}^{-}+\\\\sigma_{1}^{-}\\\\sigma_{2}^{+}) + J_{1,3}(\\\\sigma_{1}^{+}\\\\sigma_{3}^{-}+\\\\sigma_{1}^{-}\\\\sigma_{3}^{+}) + J_{3,4}(\\\\sigma_{3}^{+}\\\\sigma_{4}^{-}+\\\\sigma_{3}^{-}\\\\sigma_{4}^{+}) \\\\\\\\ & + \\\\Omega_{d,0}(U_{0}^{(0,1)}(t))\\\\sigma_{0}^{X} + \\\\Omega_{d,1}(U_{1}^{(1,0)}(t)+U_{3}^{(1,3)}(t)+U_{2}^{(1,2)}(t))\\\\sigma_{1}^{X} \\\\\\\\ & + \\\\Omega_{d,2}(U_{4}^{(2,1)}(t))\\\\sigma_{2}^{X} + \\\\Omega_{d,3}(U_{6}^{(3,4)}(t)+U_{5}^{(3,1)}(t))\\\\sigma_{3}^{X} \\\\\\\\ & + \\\\Omega_{d,4}(U_{7}^{(4,3)}(t))\\\\sigma_{4}^{X} \\\\\\\\ \\\\end{align}',\n      'h_str': ['_SUM[i,0,4,wq{i}/2*(I{i}-Z{i})]',\n       '_SUM[i,0,4,delta{i}/2*O{i}*O{i}]',\n       '_SUM[i,0,4,-delta{i}/2*O{i}]',\n       '_SUM[i,0,4,omegad{i}*X{i}||D{i}]',\n       'jq0q1*Sp0*Sm1',\n       'jq0q1*Sm0*Sp1',\n       'jq1q2*Sp1*Sm2',\n       'jq1q2*Sm1*Sp2',\n       'jq1q3*Sp1*Sm3',\n       'jq1q3*Sm1*Sp3',\n       'jq3q4*Sp3*Sm4',\n       'jq3q4*Sm3*Sp4',\n       'omegad1*X0||U0',\n       'omegad0*X1||U1',\n       'omegad3*X1||U3',\n       'omegad2*X1||U2',\n       'omegad1*X2||U4',\n       'omegad4*X3||U6',\n       'omegad1*X3||U5',\n       'omegad3*X4||U7'],\n      'osc': {},\n      'qub': {'0': 3, '1': 3, '2': 3, '3': 3, '4': 3},\n      'vars': {'delta0': -2.1119231275656283,\n       'delta1': -1.989081364755034,\n       'delta2': -2.0773937776320905,\n       'delta3': -2.096945401946966,\n       'delta4': -2.0819029355928373,\n       'jq0q1': 0.011772262300160973,\n       'jq1q2': 0.012605700949390706,\n       'jq1q3': 0.012591488659137172,\n       'jq3q4': 0.01051661912410011,\n       'omegad0': 0.8027253632102426,\n       'omegad1': 0.7994609296532756,\n       'omegad2': 1.9688450308371457,\n       'omegad3': 0.7721838249505281,\n       'omegad4': 0.6185844031359571,\n       'wq0': 31.98159911982912,\n       'wq1': 32.95737791154753,\n       'wq2': 33.68606633828003,\n       'wq3': 32.48696041179116,\n       'wq4': 33.039435267685114}},\n     'meas_kernels': ['hw_boxcar'],\n     'meas_levels': [1, 2],\n     'meas_lo_range': [[6.801661824e+18, 7.801661824e+18],\n      [6.893594461e+18, 7.893594461e+18],\n      [6.860214726e+18, 7.860214726e+18],\n      [6.803382327e+18, 7.803382327e+18],\n      [6.926310916e+18, 7.926310916e+18]],\n     'meas_map': [[0, 1, 2, 3, 4]],\n     'measure_esp_enabled': False,\n     'multi_meas_enabled': True,\n     'n_uchannels': 8,\n     'parametric_pulses': ['gaussian', 'gaussian_square', 'drag', 'constant'],\n     'quantum_volume': 16,\n     'qubit_channel_mapping': [['d0', 'm0', 'u1', 'u0'],\n      ['u4', 'd1', 'u2', 'u1', 'u3', 'm1', 'u5', 'u0'],\n      ['u2', 'd2', 'm2', 'u4'],\n      ['m3', 'u3', 'u7', 'd3', 'u5', 'u6'],\n      ['m4', 'd4', 'u6', 'u7']],\n     'qubit_lo_range': [[4.590029587904213e+18, 5.590029587904213e+18],\n      [4.745329605970436e+18, 5.745329605970436e+18],\n      [4.861303971058769e+18, 5.861303971058769e+18],\n      [4.670460335567279e+18, 5.670460335567279e+18],\n      [4.758389439816784e+18, 5.758389439816784e+18]],\n     'rep_times': [0.001],\n     'u_channel_lo': [[{'q': 1, 'scale': (1+0j)}],\n      [{'q': 0, 'scale': (1+0j)}],\n      [{'q': 2, 'scale': (1+0j)}],\n      [{'q': 3, 'scale': (1+0j)}],\n      [{'q': 1, 'scale': (1+0j)}],\n      [{'q': 1, 'scale': (1+0j)}],\n      [{'q': 4, 'scale': (1+0j)}],\n      [{'q': 3, 'scale': (1+0j)}]],\n     'uchannels_enabled': True,\n     'url': 'None',\n     'input_allowed': ['job'],\n     'allow_object_storage': True,\n     'pulse_num_channels': 9,\n     'pulse_num_qubits': 3}\n\n\n\nThe backend configuration provides some useful information via its attributes, such as `basis_gates`, `coupling_map`, `max_experiments`, `max_shots`, `quantum_volume`, and `simulator`. \n\nThe backend properties contain data that was measured and reported. Let\u2019s see what kind of information is reported for qubit 0.\n\n**Note:** The following example displays the properties of the `SX` gate. Each backend may have different basis gates which may not contain `SX`. \n\n\n```python\nprops = backend.properties()\n\n\ndef describe_qubit(qubit, properties):\n    \"\"\"Print a string describing some of reported properties of the given qubit.\"\"\"\n\n    # Conversion factors from standard SI units\n    us = 1e6\n    ns = 1e9\n    GHz = 1e-9\n\n    print(\n        f\"Qubit {qubit} has a \\n\"\n        f\"  - T1 time of {properties.t1(qubit)} microseconds\\n\"\n        f\"  - T2 time of {properties.t2(qubit)} microseconds\\n\"\n        f\"  - SX gate error of {properties.gate_error('sx', qubit)}\\n\"\n        f\"  - SX gate duration of {properties.gate_length('sx', qubit)*ns} nanoseconds\\n\"\n        f\"  - resonant frequency of {properties.frequency(qubit) * GHz} GHz\"\n    )\n\n\ndescribe_qubit(0, props)\n```\n\n    Qubit 0 has a \n      - T1 time of 0.000118798578854076 microseconds\n      - T2 time of 8.30176098567665e-05 microseconds\n      - SX gate error of 0.0003355394204181594\n      - SX gate duration of 35.55555555555556 nanoseconds\n      - resonant frequency of 4.820326782885405 GHz\n\n\n### Backend Service\n\n[`IBMBackendService`](https://qiskit.org/documentation/stubs/qiskit_ibm_provider.IBMBackendService.html#qiskit_ibm_provider.IBMBackendService) provides generic backend related services for an account without requiring a particular backend as input. The main methods it supports are:\n\n- `jobs()`: Returns a list of previously submitted jobs in the account.\n- `job(JOB_ID)`:  Returns a job by its job ID.\n\n\nThe backend service is defined as the `backend` attribute of an `IBMProvider` instance. All of the backends available to this provider are also attributes of the backend service, allowing the backend names to be autocompleted: \n\n\n```python\nprovider.backend.ibmq_qasm_simulator\n```\n\n\n\n\n    <IBMBackend('ibmq_qasm_simulator')>\n\n\n\nTo see the last five jobs submitted to the account, regardless of which backend they ran on:\n\n\n```python\nfor ran_job in provider.backend.jobs(limit=5):\n    print(str(ran_job.job_id()) + \" \" + str(ran_job.status()))\n```\n\n    5fdccad1c01fec001a47e018 JobStatus.QUEUED\n    5fdcc5fad4445500193f0072 JobStatus.DONE\n    5fdcc5f923da0f001acf6f67 JobStatus.DONE\n    5fdcc5f9d4445500193f0071 JobStatus.DONE\n    5fdcc41b23da0f001acf6f44 JobStatus.DONE\n\n\nTo retrieve a particular job:\n\n\n```python\nif ran_job is not None:\n    job = provider.backend.job(ran_job.job_id())\n```\n\n## Jobs <a name='jobs'></a>\n\nJob instances can be thought of as the \u201cticket\u201d for a submitted job. They find out the execution state at a given point in time (for example, if the job is queued, running, or has failed), and also allow control over the job. They have the following methods:\n\n- `status()`: Returns the status of the job.\n- `backend()`: Returns the backend the job was run on.\n- `job_id()`: Gets the job_id.\n- `cancel()`: Cancels the job.\n- `result()`: Gets the results from the circuit run.\n\nSome of the methods that are only available to \"IBM Job\"([`IBMJob`](https://qiskit.org/documentation/stubs/qiskit_ibm_provider.job.IBMJob.html#qiskit_ibm_provider.job.IBMJob)) include:\n\n- `creation_date()`: Gives the date at which the job was created.\n- `queue_info()`: Returns queue information for this job, including queue position, estimated start and end time, and dynamic priorities for the hub, group, and project.\n- `error_message()`: The error message of failed jobs, if any.\n- `name()`: Returns the name assigned to this job.\n- `properties()`: Returns the backend properties for this job.\n- `time_per_step()`: Returns the time spent for each step (job creation, validation, etc).\n\nRefer to the [`IBMJob`](https://qiskit.org/documentation/stubs/qiskit_ibm_provider.job.IBMJob.html#qiskit_ibm_provider.job.IBMJob) documentation for a complete list of methods.\n\nNow some examples. Let's start with submitting a job:\n\n\n```python\nfrom qiskit import *\nfrom qiskit.compiler import transpile, assemble\n```\n\n\n```python\nqr = QuantumRegister(3)\ncr = ClassicalRegister(3)\ncircuit = QuantumCircuit(qr, cr)\ncircuit.x(qr[0])\ncircuit.x(qr[1])\ncircuit.ccx(qr[0], qr[1], qr[2])\ncircuit.cx(qr[0], qr[1])\ncircuit.measure(qr, cr)\n```\n\n\n\n\n    <qiskit.circuit.instructionset.InstructionSet at 0x14338efd0>\n\n\n\nYou should first map the circuit using the transpile function and then send it to the backend:\n\n\n```python\nmapped_circuit = transpile(circuit, backend=backend)\njob = backend.run(mapped_circuit, shots=1024)\n```\n\nThe `status()` method returns the job status and a message:\n\n\n```python\njob.status()\n```\n\n\n\n\n    <JobStatus.VALIDATING: 'job is being validated'>\n\n\n\nTo get a backend object from the job, use the `backend()` method:\n\n\n```python\nbackend_temp = job.backend()\nbackend_temp\n```\n\n\n\n\n    <IBMBackend('ibmq_belem')>\n\n\n\nTo get the job_id use the `job_id()` method:\n\n\n```python\njob.job_id()\n```\n\n\n\n\n    '5fdccb1ad4445500193f00db'\n\n\n\nTo get the result from the job, use the `result()` method:\n\n\n```python\nresult = job.result()\ncounts = result.get_counts()\nprint(counts)\n```\n\n    {'000': 24, '001': 53, '010': 28, '011': 56, '100': 26, '101': 801, '110': 13, '111': 23}\n\n\nIf you want to check the creation date, use `creation_date()`:\n\n\n```python\njob.creation_date()\n```\n\n\n\n\n    datetime.datetime(2020, 12, 18, 10, 30, 34, 565000, tzinfo=tzlocal())\n\n\n\n### Long list of circuits\n\nYou can submit a list of circuits in a single job, but IBM Quantum backends limit how many. You can query this limit using `backend.configuration().max_experiments`. \n\n`qiskit-ibmq-provider`, which is the predecessor of `qiskit-ibm-provider`, has a convenience function called Job Manager that splits circuits into multiple jobs, if the number exceeds the backend limit. In `qiskit-ibm-provider`, however, this function is now done implicitly by `backend.run()`. \n\nIf you submit a list of circuits using `backend.run()`, and the length of the list exceeds the backend limit, you will get back an [`IBMCompositeJob`](https://qiskit.org/documentation/stubs/qiskit_ibm_provider.job.IBMCompositeJob.html) instance. This `IBMCompositeJob` implicitly splits the circuits into multiple sub-jobs and manage them for you. When the sub-jobs are finished, it collects and presents the results in a unified view. The sub-jobs are submitted sequentially, and if `IBMCompositeJob` hits the job limit error* when submitting a sub-job, it will wait for a previous job to finish before trying to submit again.\n\n`IBMCompositeJob` is a subclass of `IBMJob`, and you can use it the same way you do with a traditional job. For example, you can continue to use methods like `status()` and `result()` to get the job status and result, respectively. You can also retrieve a previously executed `IBMCompositeJob` using the `provider.backend.job()` and `provider.backend.jobs()` methods, like you would with traditional jobs.\n\nIn addition to the methods that mirror those of traditional jobs, `IBMCompositeJob` also allows you to re-run failed jobs, using the `rerun_failed()` method.  You can also use the `report()` method to check the status of each individual sub-job.\n\n*There may be a limit on the number of active jobs you can have at a time. You can find this limit using `backend.job_limit().maximum_jobs`.\n\n<div class=\"alert alert-block alert-info\">\n<b>Note:</b> IBMCompositeJob uses job tags to identify sub-jobs. It is therefore important to preserve these tags. All tags used internally by IBMCompositeJob start with \"ibm_composite_job_\".</div>\n\nNow let's see some examples. The following code submits a list of circuits to `ibmq_qasm_simulator`. To save time, we will use the `max_circuits_per_job` parameter to limit the number of circuits in each job instead of using the actual backend limit.\n\n\n```python\nbackend = provider.get_backend(\"ibmq_qasm_simulator\")\ncircs = transpile([circuit] * 50, backend=backend)\n\n# Submit them all to the backend\njob = backend.run(circs, max_circuits_per_job=10)\n```\n\nYou can use the `report()` method to inquire the statuses of individual sub-job:\n\n\n```python\nprint(job.report())\n```\n\n    Composite Job ibm_composite_job_id_be6fc3313570454ba8cd4897452c37c9_:\n      Summary report:\n             Total jobs: 5\n        Successful jobs: 0\n            Failed jobs: 0\n         Cancelled jobs: 0\n           Running jobs: 3\n           Pending jobs: 2\n    \n      Detail report:\n        Circuits 0-9:\n          Job index: 0\n          Job ID: 6142623e2be3693f7058489e\n          Status: JobStatus.RUNNING\n        Circuits 10-19:\n          Job index: 1\n          Job ID: 6142624010b4a282afa0f641\n          Status: JobStatus.RUNNING\n        Circuits 20-29:\n          Job index: 2\n          Job ID: 614262418eca75b3a642b8da\n          Status: JobStatus.RUNNING\n        Circuits 30-39:\n          Job index: 3\n          Status: Job not yet submitted.\n        Circuits 40-49:\n          Job index: 4\n          Status: Job not yet submitted.\n\n\nTo collect the result of this `IBMCompositeJob`, you can use the `result()` method, like you would with a traditional job:\n\n\n```python\nresult = job.result()\nprint(\"This is the histogram data for experiment 5: {}\".format(result.get_counts(5)))\nprint(\"This is the histogram data for experiment 15: {}\".format(result.get_counts(15)))\n```\n\n    This is the histogram data for experiment 5: {'101': 1024}\n    This is the histogram data for experiment 15: {'101': 1024}\n\n\nThis `IBMCompositeJob` has a job ID that has a different format than traditional jobs:\n\n\n```python\nprint(f\"Composite job ID: {job.job_id()}\")\n```\n\n    Composite job ID: ibm_composite_job_id_be6fc3313570454ba8cd4897452c37c9_\n\n\nYou can still use this ID to retrieve a previously run job:\n\n\n```python\nretrieved_job = provider.backend.job(job.job_id())\nprint(retrieved_job.report())\n```\n\n    Composite Job ibm_composite_job_id_be6fc3313570454ba8cd4897452c37c9_:\n      Summary report:\n             Total jobs: 5\n        Successful jobs: 5\n            Failed jobs: 0\n         Cancelled jobs: 0\n           Running jobs: 0\n           Pending jobs: 0\n    \n      Detail report:\n        Circuits 0-9:\n          Job index: 0\n          Job ID: 6142623e2be3693f7058489e\n          Status: JobStatus.DONE\n        Circuits 10-19:\n          Job index: 1\n          Job ID: 6142624010b4a282afa0f641\n          Status: JobStatus.DONE\n        Circuits 20-29:\n          Job index: 2\n          Job ID: 614262418eca75b3a642b8da\n          Status: JobStatus.DONE\n        Circuits 30-39:\n          Job index: 3\n          Job ID: 614262428eca750f4a42b8db\n          Status: JobStatus.DONE\n        Circuits 40-49:\n          Job index: 4\n          Job ID: 6142624310b4a22ba7a0f642\n          Status: JobStatus.DONE\n\n\nAt this time, `IBMCompositeJob` is not supported on the [IBM Quantum website](https://quantum-computing.ibm.com). That is, you will see the individual sub-jobs listed on the `Jobs` page rather than the composite job. You can, however, search for all sub-jobs that belong to a composite job using its job ID, as all sub-jobs have that ID assigned to them as tags. \n\n`IBMCompositeJob` supports all the methods supported by a traditional job. For example:\n\n\n```python\nprint(f\"Job {job.job_id()} status is {job.status()}\")\nprint(f\"Job creation date is {job.creation_date()}\")\n```\n\n    Job ibm_composite_job_id_be6fc3313570454ba8cd4897452c37c9_ status is JobStatus.DONE\n    Job creation date is 2021-09-15 17:14:38.789000-04:00\n\n\nThe `sub_jobs()` method gives back a list of all submitted sub-jobs:\n\n\n```python\nsub_jobs = job.sub_jobs()\nprint(f\"Job {job.job_id()} contains sub-jobs:\")\nfor sub_job in sub_jobs:\n    print(sub_job.job_id())\n```\n\n    Job ibm_composite_job_id_be6fc3313570454ba8cd4897452c37c9_ contains sub-jobs:\n    6142623e2be3693f7058489e\n    6142624010b4a282afa0f641\n    614262418eca75b3a642b8da\n    614262428eca750f4a42b8db\n    6142624310b4a22ba7a0f642\n\n\n\n```python\nfrom qiskit_ibm_provider.version import __version__\n\nprint(\"qiskit-ibm-provider version: {}\".format(__version__))\n```\n\n    qiskit-ibm-provider version: 0.1.0\n\n\n\n```python\nimport qiskit.tools.jupyter\n\n%qiskit_version_table\n%qiskit_copyright\n```\n\n\n<h3>Version Information</h3><table><tr><th>Qiskit Software</th><th>Version</th></tr><tr><td><code>qiskit-terra</code></td><td>0.18.3</td></tr><tr><td><code>qiskit-aer</code></td><td>0.9.0</td></tr><tr><td><code>qiskit-ignis</code></td><td>0.6.0</td></tr><tr><td><code>qiskit-ibmq-provider (deprecated)</code></td><td>0.17.0</td></tr><tr><td><code>qiskit-aqua (deprecated)</code></td><td>0.9.5</td></tr><tr><td><code>qiskit</code></td><td>0.31.0</td></tr><tr><th>System information</th></tr><tr><td>Python</td><td>3.7.11 (default, Jul 27 2021, 07:03:16) \n[Clang 10.0.0 ]</td></tr><tr><td>OS</td><td>Darwin</td></tr><tr><td>CPUs</td><td>8</td></tr><tr><td>Memory (Gb)</td><td>32.0</td></tr><tr><td colspan='2'>Mon Sep 13 00:15:27 2021 EDT</td></tr></table>\n\n\n\n<div style='width: 100%; background-color:#d5d9e0;padding-left: 10px; padding-bottom: 10px; padding-right: 10px; padding-top: 5px'><h3>This code is a part of Qiskit</h3><p>&copy; Copyright IBM 2017, 2021.</p><p>This code is licensed under the Apache License, Version 2.0. You may<br>obtain a copy of this license in the LICENSE.txt file in the root directory<br> of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.<p>Any modifications or derivative works of this code must retain this<br>copyright notice, and modified files need to carry a notice indicating<br>that they have been altered from the originals.</p></div>\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "078113d8b76f16d95a84c8c4964f364d2af1cd23", "size": 71265, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/1_the_ibm_quantum_account.ipynb", "max_stars_repo_name": "rathishcholarajan/qiskit-ibm-provider", "max_stars_repo_head_hexsha": "d0c6b613504e386d56f05cf7dd7e697ac6ff52e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-02-28T05:47:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T20:57:25.000Z", "max_issues_repo_path": "docs/tutorials/1_the_ibm_quantum_account.ipynb", "max_issues_repo_name": "rathishcholarajan/qiskit-ibm-provider", "max_issues_repo_head_hexsha": "d0c6b613504e386d56f05cf7dd7e697ac6ff52e8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 87, "max_issues_repo_issues_event_min_datetime": "2022-02-14T14:18:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T17:37:34.000Z", "max_forks_repo_path": "docs/tutorials/1_the_ibm_quantum_account.ipynb", "max_forks_repo_name": "rathishcholarajan/qiskit-ibm-provider", "max_forks_repo_head_hexsha": "d0c6b613504e386d56f05cf7dd7e697ac6ff52e8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2022-02-26T19:04:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T04:47:40.000Z", "avg_line_length": 46.8232588699, "max_line_length": 21748, "alphanum_fraction": 0.6780747913, "converted": true, "num_tokens": 9237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1710611959045317, "lm_q2_score": 0.07159119993976201, "lm_q1q2_score": 0.012246476277936128}}
{"text": "```python\n!pip install coremltools\n```\n\n    Requirement already satisfied: coremltools in /usr/local/lib/python3.6/dist-packages (4.1)\n    Requirement already satisfied: attrs in /usr/local/lib/python3.6/dist-packages (from coremltools) (19.1.0)\n    Requirement already satisfied: numpy<1.20,>=1.14.5 in /usr/local/lib/python3.6/dist-packages (from coremltools) (1.16.4)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.6/dist-packages (from coremltools) (1.7.1)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from coremltools) (1.5.4)\n    Requirement already satisfied: six>=1.10.0 in /usr/lib/python3/dist-packages (from coremltools) (1.11.0)\n    Requirement already satisfied: protobuf>=3.1.0 in /usr/local/lib/python3.6/dist-packages (from coremltools) (3.8.0)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from coremltools) (4.58.0)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.6/dist-packages (from coremltools) (20.9)\n    Requirement already satisfied: attr in /usr/local/lib/python3.6/dist-packages (from coremltools) (0.3.1)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy->coremltools) (1.2.1)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from protobuf>=3.1.0->coremltools) (41.0.1)\n    Requirement already satisfied: pyparsing>=2.0.2 in /usr/local/lib/python3.6/dist-packages (from packaging->coremltools) (2.4.0)\n    \u001b[33mWARNING: You are using pip version 19.1.1, however version 21.0.1 is available.\n    You should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\n\n\n\n```python\nimport coremltools as ct\nimport tensorflow as tf\n\nprint(\"TF Version: \", tf.__version__)\nprint(\"Eager mode enabled: \", tf.executing_eagerly())\nprint(\"GPU available: \", tf.test.is_gpu_available())\n```\n\n    TF Version:  1.14.0\n    Eager mode enabled:  False\n    GPU available:  False\n\n\n\n```python\noriginal_predict_network = 'gs://mobile-ml-wg/arbitrary_style_transfer/original/SavedModel/predict'\noriginal_stylize_network = 'gs://mobile-ml-wg/arbitrary_style_transfer/original/SavedModel/stylize'\noriginal_transfer_network = 'gs://mobile-ml-wg/arbitrary_style_transfer/original/SavedModel/transfer'\n\nsmall_predict_network = 'gs://mobile-ml-wg/arbitrary_style_transfer/small/SavedModel/predict'\nsmall_stylize_network = 'gs://mobile-ml-wg/arbitrary_style_transfer/small/SavedModel/stylize'\nsmall_transfer_network = 'gs://mobile-ml-wg/arbitrary_style_transfer/small/SavedModel/transfer'\n```\n\n\n```python\ndef print_model_details(saved_model_path):\n    print('\\n{} model'.format(saved_model_path))\n    model = tf.compat.v2.saved_model.load(saved_model_path)\n    print(model.tensorflow_version)\n    for input in model.signatures['serving_default'].inputs:\n        print(input)\n    print(model.signatures['serving_default'].structured_outputs)\n```\n\n\n```python\n# print_model_details(original_predict_network)\n# print_model_details(original_stylize_network)\n# print_model_details(original_transfer_network)\n\n# print_model_details(small_predict_network)\n# print_model_details(small_stylize_network)\n# print_model_details(small_transfer_network)\n```\n\n\n```python\ndef convert_tflite_model(saved_model_path, tflite_path, supported_types=[]):\n    print('\\n{} model'.format(saved_model_path))\n    model = tf.compat.v2.saved_model.load(saved_model_path)\n    concrete_func = model.signatures[tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY]\n    for input in concrete_func.inputs:\n        if input.name == 'style_image:0':\n            input.set_shape([1, 256, 256, 3])\n        elif input.name == 'content_image:0' and len(supported_types) > 0:\n            input.set_shape([1, 384, 384, 3])\n        elif input.name == 'mobilenet_conv/Conv/BiasAdd:0' and len(supported_types) > 0:\n            input.set_shape([1, 1, 1, 100])\n\n    converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n    converter.optimizations = [tf.lite.Optimize.DEFAULT]\n\n    if len(supported_types) > 0:\n        converter.target_spec.supported_types = supported_types\n\n    tflite_model = converter.convert()\n\n    with tf.io.gfile.GFile(tflite_path, 'wb') as f:\n        f.write(tflite_model)\n\n    print('Quantized model:', tflite_path, \n        'Size:', len(tflite_model) / 1024, \"kb\")\n```\n\n\n```python\n# convert_tflite_model(original_predict_network, 'original_predict.tflite')\n# convert_tflite_model(original_stylize_network, 'original_stylize.tflite')\n# convert_tflite_model(original_transfer_network, 'original_transfer.tflite')\n\n# convert_tflite_model(original_predict_network, 'original_predict_f16.tflite', [tf.float16])\n# convert_tflite_model(original_stylize_network, 'original_stylize_f16.tflite', [tf.float16])\n# convert_tflite_model(original_transfer_network, 'original_transfer_f16.tflite', [tf.float16])\n```\n\n\n```python\ndef print_tflite_model_details(tflite_path):\n    print('\\n{} model'.format(tflite_path))\n    interpreter = tf.lite.Interpreter(model_path=tflite_path)\n    interpreter.allocate_tensors()\n\n    inputs = interpreter.get_input_details()\n    # print('{} inputs:'.format(len(inputs)))\n    for i in range(0, len(inputs)):\n        print('{} {} {}'.format(inputs[i]['name'], inputs[i]['shape'], inputs[i]['dtype']))\n\n    outputs = interpreter.get_output_details()\n    # print('{} outputs:'.format(len(outputs)))\n    for i in range(0, len(outputs)):\n        print('{} {} {}'.format(outputs[i]['name'], outputs[i]['shape'], outputs[i]['dtype']))\n```\n\n\n```python\n# print_tflite_model_details('original_predict.tflite')\n# print_tflite_model_details('original_stylize.tflite')\n# print_tflite_model_details('original_transfer.tflite')\n\n# print_tflite_model_details('original_predict_f16.tflite')\n# print_tflite_model_details('original_stylize_f16.tflite')\n# print_tflite_model_details('original_transfer_f16.tflite')\n```\n\n\n```python\n# hub_network = 'https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2'\n```\n\n\n```python\ndef convert_predict_model(network):\n    saved_model_path = '{}/SavedModel/predict'.format(network)\n    coreml_path = '{}_style_predict.mlmodel'.format(network)\n    print(saved_model_path)\n\n    mlmodel = ct.convert(saved_model_path,\n                         source='tensorflow',\n                         inputs=[ct.ImageType(bias=[0,0,0], scale=1/255.0)])\n    print(mlmodel)\n    mlmodel.save(coreml_path)\n    \ndef convert_transfer_model(network):\n    saved_model_path = '{}/SavedModel/transfer'.format(network)\n    coreml_path = '{}_style_transfer.mlmodel'.format(network)\n    print(saved_model_path)\n\n    mlmodel = ct.convert(saved_model_path,\n                         source='tensorflow',\n                         inputs=[ct.TensorType(shape=(1, 1, 1, 100)),\n                                 ct.ImageType(bias=[0,0,0], scale=1/255.0)])\n    print(mlmodel)\n    mlmodel.save(coreml_path)\n```\n\n\n```python\nconvert_predict_model('original')\nconvert_transfer_model('original')\n```\n", "meta": {"hexsha": "ba7c0972f32305c78f1094f10edab7f63ba22148", "size": 26696, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "magenta/models/arbitrary_image_stylization/style_transfer.ipynb", "max_stars_repo_name": "pkbhadkoliya/magenta", "max_stars_repo_head_hexsha": "d4ec3a9d9528a1ff5c8ec710ebf6b24174f3d14a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "magenta/models/arbitrary_image_stylization/style_transfer.ipynb", "max_issues_repo_name": "pkbhadkoliya/magenta", "max_issues_repo_head_hexsha": "d4ec3a9d9528a1ff5c8ec710ebf6b24174f3d14a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "magenta/models/arbitrary_image_stylization/style_transfer.ipynb", "max_forks_repo_name": "pkbhadkoliya/magenta", "max_forks_repo_head_hexsha": "d4ec3a9d9528a1ff5c8ec710ebf6b24174f3d14a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 76.4928366762, "max_line_length": 1908, "alphanum_fraction": 0.6661297573, "converted": true, "num_tokens": 1811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2538610069692489, "lm_q2_score": 0.04813677316493159, "lm_q1q2_score": 0.012220049707899852}}
{"text": "# Rich Output\n\nIn Python, objects can declare their textual representation using the `__repr__` method.  IPython expands on this idea and allows objects to declare other, rich representations including:\n\n* HTML\n* JSON\n* PNG\n* JPEG\n* SVG\n* LaTeX\n* Markdown\n\nA single object can declare some or all of these representations; all are handled by IPython's *display system*. This Notebook shows how you can use this display system to incorporate a broad range of content into your Notebooks.\n\n## Basic display imports\n\nThe `display` function is a general purpose tool for displaying different representations of objects. Think of it as `print` for these rich representations.\n\n\n```python\nfrom IPython.display import display\n```\n\nA few points:\n\n* Calling `display` on an object will send **all** possible representations to the Notebook.\n* These representations are stored in the Notebook document.\n* In general the Notebook will use the richest available representation.\n\nIf you want to display a particular representation, there are specific functions for that:\n\n\n```python\nfrom IPython.display import (\n    display_pretty, display_html, display_jpeg,\n    display_png, display_json, display_latex, display_svg\n)\n```\n\n## Images\n\nTo work with images (JPEG, PNG) use the `Image` class.\n\n\n```python\nfrom IPython.display import Image\n```\n\n\n```python\ni = Image(filename='../images/ipython_logo.png')\n```\n\nReturning an `Image` object from an expression will automatically display it:\n\n\n```python\ni\n```\n\nIn the above cell, the output gets the prompt number `Out[5]`, as the last statement of the cell is the image object. You can use `Out[5]` to refer to it later.\n\nOr you can pass an object with a rich representation to `display`:\n\n\n```python\ndisplay(i)\n```\n\nHere the image is displayed, and nothing is returned, so there is no `Out[6]` prompt.\nYou can draw a parallel between `display` and `print`.\n\n```python\nIn [1]: 1\nOut[1]: 1\n\nIn [2]: print(1)\n1\n```\n\nPrinting or displaying  a value does not return it, so you do not get prompt number. \nYou can only have one returned value from a cell, while you can print (or display) many objects.\n\nAn image can also be displayed from raw data or a URL.\n\n\n```python\nImage(url='https://www.python.org/static/img/python-logo@2x.png')\n```\n\n\n\n\n\n\n\n\nSVG images are also supported out of the box.\n\n\n```python\nfrom IPython.display import SVG\nSVG(filename='../images/python_logo.svg')\n```\n\n\n\n\n    \n\n    \n\n\n\nIn the two above examples, we are returning `Image` and `SVG` objects, not displaying them explicitly.\n\n<div class=\"alert alert-success\">You might not see the SVG output above until you run the cell. This is for security: a sneaky SVG that got displayed inside a notebook could start doing things without your knowledge. This security measure affects HTML and Javascript output too.</div>\n\n### Embedded vs non-embedded Images\n\nBy default, image data is embedded in the notebook document so that the images can be viewed offline. However it is also possible to tell the `Image` class to only store a *link* to the image. Let's see how this works using a webcam in Berkeley, California.\n\n\n```python\nfrom IPython.display import Image\nimg_url = 'http://www.lawrencehallofscience.org/static/scienceview/scienceview.berkeley.edu/html/view/view_assets/images/newview.jpg'\n\n# by default Image data are embedded\nEmbed      = Image(img_url)\n\n# if kwarg `url` is given, the embedding is assumed to be false\nSoftLinked = Image(url=img_url)\n\n# In each case, embed can be specified explicitly with the `embed` kwarg\n# ForceEmbed = Image(url=img_url, embed=True)\n```\n\nHere is the embedded version. Note that this image was pulled from the webcam when this code cell was originally run and stored in the Notebook. Unless we rerun this cell, this is not today's image.\n\n\n```python\nEmbed\n```\n\n\n\n\n    \n\n    \n\n\n\nHere is today's image from same webcam at Berkeley, (refreshed every minutes, if you reload the notebook), visible only with an active internet connection, that should be different from the previous one. Notebooks saved with this kind of image will be smaller and always reflect the current version of the source, but the image won't display offline.\n\n\n```python\nSoftLinked\n```\n\n\n\n\n\n\n\n\nOf course, if you re-run this Notebook, the two images will be the same again.\n\n## HTML\n\nPython objects can declare HTML representations that will be displayed in the Notebook. If you have some HTML you want to display, simply use the `HTML` class.\n\n\n```python\nfrom IPython.display import HTML\n```\n\n\n```python\ns = \"\"\"<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\"\"\"\n```\n\n\n```python\nh = HTML(s)\n```\n\n\n```python\ndisplay(h)\n```\n\n\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n\n\nYou can also use the `%%html` cell magic to accomplish the same thing.\n\n\n```python\n%%html\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n```\n\n\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n\n\n## Markdown\n\nYou have already seen how to use markdown in markdown cells.\nYou can also display markdown programatically:\n\n\n```python\nfrom IPython.display import Markdown\n```\n\n\n```python\nMarkdown(\"\"\"\n### Displaying markdown\n\nThis is how to programatically display markdown with:\n\n - bullet list\n - _emphases_\n - **bold**\n \n\"\"\")\n```\n\n\n\n\n\n### Displaying markdown\n\nThis is how to programatically display markdown with:\n\n - bullet list\n - _emphases_\n - **bold**\n \n\n\n\n\n## JavaScript\n\nThe Notebook also enables objects to declare a JavaScript representation. At first, this may seem odd as  output is inherently visual and JavaScript is a programming language. However, this opens the door for rich output that leverages the full power of JavaScript and associated libraries such as [d3.js](http://d3js.org) for output.\n\n\n```python\nfrom IPython.display import Javascript\n```\n\nPass a string of JavaScript source code to the `JavaScript` object and then display it.\n\n\n```python\njs = Javascript('alert(\"hi\")');\n```\n\n\n```python\ndisplay(js)\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\nThe same thing can be accomplished using the `%%javascript` cell magic:\n\n\n```javascript\n%%javascript\n\nalert(\"hello\");\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\nHere is a more complicated example that loads `d3.js` from a CDN, uses the `%%html` magic to load CSS styles onto the page and then runs one of the `d3.js` examples.\n\n\n```python\nJavascript(\n    \"\"\"$.getScript('//cdnjs.cloudflare.com/ajax/libs/d3/3.2.2/d3.v3.min.js')\"\"\"\n)\n```\n\n\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n```python\n%%html\n<style type=\"text/css\">\n\ncircle {\n  fill: rgb(31, 119, 180);\n  fill-opacity: .25;\n  stroke: rgb(31, 119, 180);\n  stroke-width: 1px;\n}\n\n.leaf circle {\n  fill: #ff7f0e;\n  fill-opacity: 1;\n}\n\ntext {\n  font: 10px sans-serif;\n}\n\n</style>\n```\n\n\n<style type=\"text/css\">\n\ncircle {\n  fill: rgb(31, 119, 180);\n  fill-opacity: .25;\n  stroke: rgb(31, 119, 180);\n  stroke-width: 1px;\n}\n\n.leaf circle {\n  fill: #ff7f0e;\n  fill-opacity: 1;\n}\n\ntext {\n  font: 10px sans-serif;\n}\n\n</style>\n\n\n\n```javascript\n%%javascript\n\n// element is the jQuery element we will append to\nvar e = element.get(0);\n    \nvar diameter = 600,\n    format = d3.format(\",d\");\n\nvar pack = d3.layout.pack()\n    .size([diameter - 4, diameter - 4])\n    .value(function(d) { return d.size; });\n\nvar svg = d3.select(e).append(\"svg\")\n    .attr(\"width\", diameter)\n    .attr(\"height\", diameter)\n  .append(\"g\")\n    .attr(\"transform\", \"translate(2,2)\");\n\nd3.json(\"data/flare.json\", function(error, root) {\n  var node = svg.datum(root).selectAll(\".node\")\n      .data(pack.nodes)\n    .enter().append(\"g\")\n      .attr(\"class\", function(d) { return d.children ? \"node\" : \"leaf node\"; })\n      .attr(\"transform\", function(d) { return \"translate(\" + d.x + \",\" + d.y + \")\"; });\n\n  node.append(\"title\")\n      .text(function(d) { return d.name + (d.children ? \"\" : \": \" + format(d.size)); });\n\n  node.append(\"circle\")\n      .attr(\"r\", function(d) { return d.r; });\n\n  node.filter(function(d) { return !d.children; }).append(\"text\")\n      .attr(\"dy\", \".3em\")\n      .style(\"text-anchor\", \"middle\")\n      .text(function(d) { return d.name.substring(0, d.r / 3); });\n});\n\nd3.select(self.frameElement).style(\"height\", diameter + \"px\");\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n## LaTeX\n\nThe IPython display system also has builtin support for the display of mathematical expressions typeset in LaTeX, which is rendered in the browser using [MathJax](http://mathjax.org).\n\nYou can pass raw LaTeX test as a string to the `Math` object:\n\n\n```python\nfrom IPython.display import Math\nMath(r'F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx')\n```\n\n\n\n\n$$F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx$$\n\n\n\nWith the `Latex` class, you have to include the delimiters yourself.  This allows you to use other LaTeX modes such as `eqnarray`:\n\n\n```python\nfrom IPython.display import Latex\nLatex(r\"\"\"\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\"\"\")\n```\n\n\n\n\n\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\n\n\n\nOr you can enter LaTeX directly with the `%%latex` cell magic:\n\n\n```latex\n%%latex\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n```\n\n\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n\n\n## Audio\n\nIPython makes it easy to work with sounds interactively. The `Audio` display class allows you to create an audio control that is embedded in the Notebook. The interface is analogous to the interface of the `Image` display class. All audio formats supported by the browser can be used. Note that no single format is presently supported in all browsers.\n\n\n```python\nfrom IPython.display import Audio\nAudio(url=\"http://www.nch.com.au/acm/8k16bitpcm.wav\")\n```\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"http://www.nch.com.au/acm/8k16bitpcm.wav\" type=\"audio/x-wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\nA NumPy array can be auralized automatically. The `Audio` class normalizes and encodes the data and embeds the resulting audio in the Notebook.\n\nFor instance, when two sine waves with almost the same frequency are superimposed a phenomena known as [beats](https://en.wikipedia.org/wiki/Beat_%28acoustics%29) occur. This can be auralised as follows:\n\n\n```python\nimport numpy as np\nmax_time = 3\nf1 = 220.0\nf2 = 224.0\nrate = 8000.0\nL = 3\ntimes = np.linspace(0,L,rate*L)\nsignal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times)\n\nAudio(data=signal, rate=rate)\n```\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"data:audio/wav;base64,UklGRqS7AABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YYC7AAAAADUWvSvyPzdS/WHKbjt4Bn7+fxV+WXj3bjhifVJDQBYslBZiAC/qpdRswCGuU557kf2HJIIcgPWBoIfykKKdTa15v5rTEuk7/2kV8CopP3ZRSmEqbrJ3mH2vf+Z9TXgNb3Bi11K9QK0sQxcmAQPrhNVPwQOvLZ9IkreIxYKggFiC34cLkZOdFq0bvxbTbeh4/o0UASosPnNQSGAwbcd2w3z2fk9923fGblZi7FL/QBwt3hfoAefrg9ZlwiawVqBuk9OJzoOOgSSDg4iAkdadJa31vrvS3ue5/aIT8Sj/PDBP+F7da3t1h3vUfU98BncibuhhuVIJQWQtYRilAtjso9eqw4mxzKHtlE+LPYXkgleEiolTkm6ee60Hv4jSZuf//KsSwyeiO65NXF0zas9z5nlJfOh6zXUhbSdhPlLaQIItzBhbA9Xt39gexSmzjqPCliuNEYeihPKF9YqDk1mfGq5Uv3/SCOdN/KkReCYYOvBLd1szaMVx4HdYehp5MXTDaxNgfFFwQHUtHRkJBNvuN9q9xgW1l6XsmGOPR4nGhvKHwowPlZegAa/bv6LSxOak+58QFCVkOPhJSVnhZV9veXUCeOh2MnIIaqpecVDLPzwtUxmsBOjvp9uFyBm356dmm/aR3otOiVeK8Y73limiMLCewPHSneYG+48PmSOINslH11Y+Y6BssnJJdVF002/yZ+5cHU/rPtYsbBlEBfvwLd11ymO5e6ownuGU1I44jB+NgZE6mQ+kqLGcwW7Tk+Z1+noOCCKGNGVFI1ROYIppj28vcllxFG2CZeBagU3PPUMsZxnOBRHyyN6IzOC7T61GoSGYJZKBj0aQbpTXm0WmZ7PWwhjUp+by+WMNZCBhMtBCMFEUXSFmEWy4bgJu+Gm6YoFYnkt3PIIrQxlJBinzdOC9zo2+YLCkpLKbz5Unk8yTuJfLns2obrVMxPDU2+Z/+UwMsB4dMAxAAU6TWWdiPGjlak9qgWaaX9FVdEnjOpIq/xi0Bj/0L+IQ0WfBq7NHqJKfzpkml6yXXJsVoqSru7f9xffVL+ce+TYL7hy8LR09m0rOVWFeFGS6ZkJmsmImXNNSBEcVOXQpmhgMB1P19+N/02rELbctrL2jH557m+SbVp+zpciuTrroxy3XpefP+CQKIRtAKwY6/0bKURNanF87YuBhjV5gWIlPUEQMNycoFBhRB2P2yeUG1pTH4bpPsC+ovaIioHGgpKOhqTiyJL0OypHYPOiU+BgJSxmuKMo2M0OJTX9V2FpsXStdF1pKVPVLWUHKNKsmbBeCB2v3o+ej2OHKxb6stOOspacYpU6lQ6jdrfG1PMBtzCTa9ehu+BMIbhcHJm0zOT8RSatQzVVRWCdYUVXoTxlIID5PMgIloRadB2z4gulT203O08I+udax0qxXqneqLq1ksvC5k8MDz+Tb0ele+BcHjRVPI/MvFztmRJtLf1DvUtlSQVA9S/dDqTqeLysjtBWiB2P5ZOsS3tXRCccBvgK3P7Lcr+mvYrIytzK+KcfP0dHdz+pl+CYGqxOJIF4szzaMP1RG80pJTUVN6kpNRpQ/9ja3LCghpRSPB076Ru3e4HTVYcvxwmO86beitZ6127dEvLXC+srQ1Orf8OuE+EIFyRG5HbQoZzKIOtpALkVkR29HUUUbQfI6CDOcKfkecxNkByv7Ju+z4yjZ2M8JyPXByb2ju5K7lL2VwXXHA88E2C7iM+27+GsE6w/gGvck4i1eNTI7ND9HQV1BeT+sOxU25C5QJqAcHxIgB/r7AvGO5u3catREzbHH28PbwcHBiMMhx27MQ9No25zkmO4L+aQDEg4DGCshRSkTMGI1DDn2OhQ7aTkENgExiyrVIh4aqhDEBrr82PJt6b/gEdmd0pTNGcpFyCPIs8nlzJ3RtNf63jLnHfB0+e0CQAwkFVUdlCSsKm8vujJ2NJk0JTMnMLkrASYtH3QXEw9NBmj9pvRL7Jrkyt0Q2JfTfdDazrbOENDa0v3WVdy34u/pxPH3+UgCeApGEncZ1B8uJV0pQyzNLfEtsSwaKkImSiFbG6UUXQ2+BQP+aPYo73rokeKY3bXZA9eV1XLVmNb92IrcIeGd5tDsifOT+rYBuwhsD5UVCRueHzMjryUBJyInFCbiI6AgaRxiF7IRiAsVBYz+Hvj/8VzsYOcw4+rfpd1w3FLcSN1I30DiFeap6tTvbvVJ+zcBDAeZDLQRNxYAGvUcAh8YIDIgUx+FHdgaYxdEE54OlQlSBAD/xvnO9DzwNOzS6C/mXeRm41DjGeS25RroLevX7vjyb/cY/M0AbAXPCdYNYhFbFKoWQRgXGScZdBgHF+0UOxIGD2oLhgd3A2D/XvuS9xf0CPF67n/sJOtx6mfqBetD7BPuZfAl8zr2jPkA/XgA3AMRB/8JjwyxDlYQdBEEEgYSfBFuEOcO9QyqChoIWwWDAqr/5PxI+un32PUj9NXy9vGK8ZHxB/Ln8ib0uPWO95j5xPsA/jkAYAJiBDIGwwcKCQAKnwrmCtUKcQq/CcgIlQc0BrAEFwN3Ad7/V/7v/K/7n/rI+Sv5zPis+Mf4Gfme+U/6IvsQ/A79FP4Y/xAA9wDFAXQCAQNpA6sDyAPCA5wDWgMBA5cCIQKnAS4BvABUAPz/tv+D/2X/W/9j/3z/ov/Q/wIANABiAIcAngClAJkAeQBFAP7/pP87/8j+Tv7V/WD99/yg/GD8PPw5/Fn8nvwJ/Zn9S/4c/wMA/gACAgcDBQTxBMEFbgbwBj4HVAcuB8oGKQZMBTgE9QKJAQAAZv7G/C/7rflP+CH3L/aD9Sb1HfVr9RL2Dvdc+PL5x/vN/fb/MAJrBJUGmwhsCvgLLw0HDnQOcQ78DRMNvQsACucHggXiAhoAQP1p+q33IvXe8vXwd+9z7vXtA+6f7sjvd/Gj8zz2Mflq/NH/SgO8BgoKGg3RDxkS3hMOFZ4VhxXFFF0TVRG8DqMLIAhOBEkAMvwl+EX0sfCG7eDq1Oh259Pm9ObZ54Dp3+vk7nzyjPb1+pf/TATyCGQNfBEbFSAYdBoAHLYcjhyFG6EZ7RZ8E2cPzArMBY4APPv99fvwXuxM6OfkTOKR4Mbf9t8h4UHjSeYj6rTu2vNv+Uf/NQUNC58QvxVEGgge7CDXIrYjgSM1ItofgBw9GDITgw1bB+kAYPrx88/tLOg04xHf5NvK2dXYD9l72g/du+Bk5ejqHvHY9+L+BAYKDboT4BlKH8wjQieMKZgqWSrPKAMmCCL6HP8WQhD4CFgBnvkD8sbqHuRC3mHZotUn0wTSRtLt0/DWOduq4BvnW+409mn+ugboDrIW2h0oJGgpby0cMFYxEjFPLxcsgSevIcoaCBOjCtsB9fg18ODnOOB52dvTi8+tzFrLoMt+zenQydX821LjlOuE9N39VQemEIUZrCHaKNYubzN+Nuo3pTetNRAy5ixWJpEe0RVYDHECZ/iH7iDlfNze1IXOpMlixt3EIsUyxwDLcNBc147fyujJ8j791wdDEjEcUSVdLRM0PDmwPFA+DD7lO+k3MjLtKk8imhgXDhgD8/f77Iji7dh10GPJ8cNLwJG+0r4PwTnFMsvP0tbbAuYG8Y78Pgi+E7QeySitMRo50z6rQoFEQ0TyQZw9YTdvLwImYRveD9EDmPeR6xrgjtU/zHjEd75tuny4trgau5q/FcZazivYPuM97837jAgXFQ0hDyzHNec9L0RrSHhKQ0rNRyVDbTzXM6QpIh6pEZgEV/dK6tfdYdJByMm/O7nNtKSy0rJatSi6HMEAypLUgOBw7f76wAhNFjojIi+oOXdCSknqTTBQCFByTX5IUUEhODMt2yB3E24FL/cl6cDbaM9+xFm7QbRwrw2tLa3Sr+m0TbzGxQ7Rzd2i6yL63AhgFzslADJNPcdGIk4lU6VVjVXcUqNNCkZJPKswiCNGFVEGH/ck6NbZpcz4wCu3jK9ZqrunyqeHquCvrLexwaPNJtvU6Tr54AhPGA0nqDS0QNJKs1IXWNJazVoFWI9SkkpLQAg0JyYSFz8HJ/dH5xvYGsqxvUKzIKuNpbSir6J/pRKrPbPDvVTKkNgI6Ef4zAgbGbEoFzfaQ5dO+Va8XLJfw1/qXD1X5k4jREc3tSjbGDYIRveN5o7Wx8esuqKvAacPofud352+oISmBa8CuibHDNZD5kz3owjDGSYqTDm+RhJS8FoRYUJka2SGYapbAVPNR2U6LiueGjQJevf25THVsMXqt0ysMqPknJWZYJlJnDqiCKtwthrEntOF5Er2ZAhJGmsrRjtdSUJVl14RZX5owWjVZdBf31ZFS109jy1XHDkKwveB5QTU08NttUSptZ8PmYWVNJUimDmeSqcSszbBStHR4kP1EgisGoEsBT23SyNY6WG7aGJswWzSaaxjfFqITixA1i8FHkELHvgv5QbTM8I3s4qmjpySlc6RYJFOlIOaz6Psr3y+Ec8p4Tn0rQfuGmcthz7JTbVa5mQLbOtvaHB7bTpn1V2SUdBCADKlH0wMjPj95DjSz8BJsSGkvZlwknOO543RkB2XmqAArfC798yR3y/zNwcPGx0uzT+TT/Vcimf+bhdzs3PMcHhq5mBfVEVFCjQ1IVcNC/ns5JnRp7+jrwqiRpesj3eLy4qujQmUrp1SqpS5/soK3iXysQYQG6Uu1UAUUeJe1GmTceJ1nnbCc2FtrGPtVohH8TWyIl8OmPn75CnRvb5HrkagKZVHjd2IEIjnikyRDpvkp2u3KcmX3B3xHAbzGv4uoUFMUnxgw2vHc0p4KHlZdvJvJGY5WZZJszcaJGQPMvon5efQD74zrdaeaJNDi6eGuIV/iOeOv5i7pXi1e8c62xvwfAW4GikvMUI7U8JhVW2adU96TnuReCpyS2hAW21LTDlrJWMQ2fpw5dLQnr1qrLudBZKiidaExYN5ht2MwZbYo76z9sX22SDv0ARhGigvhELgU7Niim4Jd+17D31legV0H2r+XApNvDqjJloRifvV5enQaL3pq/Sc/pBliGuDOILWhDCLF5U+oj6yncTM2C7uHATvGfsunUI8VE9jYW8UeCN9Z37We4J1nWtzXmpO/ju+J0cSQfxU5izRbb2xq4KcVpCMh2iCE4GYg+OJxJPuoPywcsO/10ftYQNkGaMue0JQVJdj22+7ePJ9WH/gfJ92xWycX41PEj28KCgT//zr5pjRrL3Bq2ScDJAYh86BWIDBgveIyZLsn/qvdsLR1mzsoALBGCMuIEIcVItj92/9eFh+33+EfVt3k214YG9Q9T2aKfsTwv2Y5yzSI74ZrJqcH5AIh5yBBoBRgmyIKJI4nzmvrMED1qHr3AEJGHwtjUGhUyxjtW/beFZ+/H/AfbR3B24EYQ9Rpj5WKr8Uh/5b6ObS0b62rCKdjpBch9OBHYBJgkSI4ZHVnrquFsFZ1ebqFgE9F64sxEDiUntiF29UeOp9r3+Ufap3IG4/YWxRIj/vKnAVTf8w6cbTtL+XrfydWpEUiHKCn4CpgoCI9pHCnn+utMDT1D/qUABfFr4rxz/fUXphHm5rdxd9+H7/fDx33G0pYYRRaD9iKw4WEAAW6sjUy8C7riWfgJIviXmDioFygyCJaJIBn4quicBz1Kvpjv9xFasqlz6aUClgy2wfdt172X0DfGt2PW3AYFZRdz+vK5YW0gAL6+rVE8IgsJyg/5OqiuaE3oKihCOKNpOTn9uulsA61C7pz/51FHkpNz0WT4xeIWt0dD16UXyfejZ1QWwFYOJQTj/TKwgXjgEO7CzXi8PEsWCi1ZWGjLiGmoQ5homLYJR4oHOv3MAq1MnoFv5tEykoqDtUTaNcIGlpcjl4YnrVeJ9z6Gr2XiZQ7D7OK2EXQwIb7YrYMMWks22kAJi+ju6Iu4Y2iFKN5pWwoVKwW8FF1HzoZf1bEr4m7jlXS3Jay2YDcNN1DnimdqVxNGmVXSNPUD6eK6AX8AIx7gHa/8a9tcGmfppSkYWLQYmXinyPyJc6o3mxFMKK1EvovvxBETolCjghSftXJWRCbQxzV3UTdEtvJWfiW9lNej1DK8MXkgNO75Hb98gOuFqpS50/lHqOKYxbjQaSBJoXpeeyCMP71DboIfwiEJ8jADa2RkFVMWEqauhvQHIgcZJsvWTcWUhMaTy7KsoXKARv8DbdE8uTujSsZaCBl8yRcI9+kO2UmZxEp5y0NsSZ1T3okvv/DvAh0TMYREdS8l2+ZmpsyW7NbXxp/GGHV29KHTsHKrMXsQST8e7eU81JvUyvyaMWm3aVFJMAlDGYhZ/CqZe2n8Vk1mToEfvaDS8ggTFLQRFPa1oCY5Ro+Godagxm5V7iVFFIlzklKX4XKgW48rfgss8twKCycqf6nneZEpfcl86bx6KOrNi4Qsdc16nooPq2DGAeEy9QPqFLoFb4Xmpkz2YUZkNieVvvUe5F1jcWKCkXkgXb843iLtI8wyu2Xqspo8mdZpsQnMKfW6anr127H8mC2A7pQfqUC4MciiwtO/xHlFKkWvBfUWK2YSVevFewTkdD3TXZJrMW6AX79G/kxNRzxuq5ia+gp2miDKCZoAmkQKoLsyW+NcvW2ZTp9Pl3Cp0a6SnlNyVES04LVipbg10EXbVZsFMoS15AqjNvJR0WKwYW9lrmcNfNydi97rNarFSnAaVypaGocq63ti7BhM1X2zvqu/lfCa8YMid6NB9AykkxUR1WaFgEWPZUWE9YRzU9QDHYI2UVWQYp90voMNpIzfPBirhTsYSsQaqYqoWt77KqunfECdAE3QPrmPlQCLsWaSTwMPA7FUUbTMtQBVO6Uu1PuEpEQ845oC4UIowUcgY0+D/qAd3f0DbGV72GtvWxxq8GsLKys7ffvv3HxNLe3u3rivlLB8UUkSFMLZs3MUDMRjxLX00pTZ1K0kXuPio2zCslIJITdAY0+Tbs39+P1JzKUsLvu6K3jLW4tSS4urxUw73LstXj4Pjsk/lRBs8Srh6RKSUzITtKQXJFe0dXRwtFqkBaOk0yxCgLHnUSXwYo+ivuyOJV2CLPdceIwYe9jrupu9a9AcIGyLbP0tgS4yXutPlkBdsQwRvCJZEu6zWaO3Q/XEFIQTo/RjuLNTkuiyXHGzgRMwYO+x3wt+Us3MPTvcxOx57Dx8HUwcPDgsfyzOTTI9xr5XPv7fmFBOwOzxjkIeQpkzDBNUY5CjsCOzE5qDWFMPIpJCJaGdoP7gXk+wryq+gQ4HvYI9I6zeHJMcg0yOjJO80S0kXYoN/r5+LwPvq2AwMN2hX5HSIlHyvEL+4yiTSJNPMy1i9LK3olkB7HFlsOkAWr/O7zoOv/40XdpNdH00zQyM7Ezj3QJtNk19TcSeOR6nDyqPr5AiML5hIHGlEgkyWoKXIs3i3kLYcs1CniJdQg0xoOFL0MGQVf/cn1k+705x3iOt1w2djWhdV+1cDWPtni3I7hG+db7R30LPtOAk4J9Q8RFnMb9B9zI9clECcXJ/AlpyNPIAYc7hYzEQELiQQB/pj3gfHr6/7m4eKv34HdY9xc3Gndft+K4nDmEutI8On1yPu1AYUHCg0aEo8WSBoqHSIfJCApIDYfVB2VGhEX5hI2DicJ4QOP/ln5aPTg7+XrkugA5kDkXONZ4zPk4uVV6HbrK+9V89H3ffwxAcwFKQomDqcRkhTTFlsYIBkfGV0Y4Ba5FPsRvQ4aCzAHIAMJ/wv7RPfR88zwSu5c7A/raupu6hrrZOxA7pzwY/N/9tX5Sv3CACMEUwc5CsEM2Q5zEIURChIAEmoRUhDBDscMdgrhBx8FRgJu/6v8E/q697D1A/S+8unxhvGX8Rby/vJF9N31uPfF+fP7MP5oAIwCiwRWBuEHIgkQCqgK6ArQCmUKrQmwCHoHFQaOBPUCVQG9/zj+0vyW+4v6uPkh+cf4rPjL+CP5rPlf+jX7JPwk/Sr+Lf8kAAkB1AGBAgsDcAOvA8kDwAOXA1MD+AKNAhcCnQEkAbIATAD2/7H/gP9j/1v/Zf9//6X/1P8GADgAZQCJAJ8ApQCXAHYAQAD3/5z/Mv++/kT+y/1X/e/8mvxc/Dr8Ovxd/Kb8FP2n/Vz+Lv8YABMBGAIdAxkEAwXRBXsG+AZCB1MHKAe/BhkGNwUfBNgCaQHf/0T+pPwO+475NPgL9x72efUi9SD1dvUj9if3e/gX+vD7+v0kAGACmgTCBsQIkAoVDEUNFA54DmwO7Q37DJsL1gm3B0wFqALe/wP9Lfp19+/0svLQ8FzvZO7x7Qrusu7n76Hx1/N49nP5svwaAJQDBAdOClcNBhBEEv0TIBWjFX0VrRQ3EyMRfg5bC9EH+gPz/9r70ff282nwSe2u6rDoYefO5v/m9ees6RnsLO/O8uf2Vvv7/7EEVAm/Dc8RYRVZGJ0aGBy7HIAcZRtvGaoWKxMKD2QKXgUdAMv6j/WU8AHs/eeo5B7id+DB3wXgReF545Pmfuod70306fnF/7MFhwsRESYWnBpPHh8h9CK8I3AjDSKcHy0c2Re+EgMN0wZeANX5avNR7bvn0+LD3q3bqtnO2CLZp9pT3RXh0eVm66rxbPh6/5wGnA1DFFsatB8hJH4nrymfKkUqoCi6JaYhgxx2FqsPWAizAPn4ZPEx6pnj0N0F2WHVAdP80VzSINQ/16PbK+Gv5/7u4PYa/2sHkw9SF2oeoyTKKbYtRDBfMfswGC/CKxEnJSEsGloS6gkdATj4fu81557f9thy0z/PgsxQy7jLuM1D0UHWjtz6403sSPWm/h8IaRE7Gk8iZilGL8AzrTb1N4s3cDWwMWcsvCXfHQ0ViAubAZH3ue1f5M7bStQOzk7JMcbRxDzFcsdky/bQ/9dK4JnppfMg/rgIHRP8HAkm+i2RNJc55TxdPvE9ojt/N6YxQiqKIcEXMA0rAgb3Fuyy4SzYz8/eyJHDE8CDvu6+VcGnxcXLg9Ol3Obm+PGH/TYJrxSVH5MpWjKlOTg/5kKQRCZEqUEpPcc2sy4qJXMa4A7MApT2luov37rUicvmww2+L7psuNS4ZrsSwLTGHc8M2TbkRfDd/JsJHRYCIuwshTaAPp5ErEiKSiVKf0epQsc7DDO6KCAdlxB+Az32OenY3HvRfMcqv8e4ibSRsvGyqrWousfB0sqE1Yzhje4j/OUJaBdDJBIwdjodQ8NJMk5FUOlPH036R6BASDc4LMYfUBI/BAD2AOit2nDOqMOsusOzJa/3rE2tJ7BwtQO9psYR0uve0uxb+xUKjxhXJgEzKj55R6VOc1O9VW1VhFIYTU5FYzuhL2IiDBQNBdz16+ax2JzLE8BytgWvB6qip+un4KpvsG24nsK1zlXcF+uH+i0Kkhk8KLk1oEGRSz9TbFjsWqxaqlf9Uc1JWD/vMvAkxhXoBdH1++Xj1gDJvrx9spCqNaWYos+i3KWoqwe0vL51y8/ZXemn+SwKcBryKTg41ERiT45XF13QX6JfjFylVhdOJEMgNm0nfhfNBt31L+VG1Z7Gq7nRrmimsaDcnQCeHqEgp9ivBrtUyFvXqOe9+BQKKht3K306xkfpUo9bcmFkZEpkJmELWypSxEYwOdgpMRm7BwD2h+TY03fE3LZwq5CigJxymYCZqpzbouOrf7dVxfvU+eXL9+YJwBvMLIY8ckojVj5feWWjaKFocmUtXwBWMkocPCws2xqwCDn2A+Sc0o3CU7RdqAqfpJhelVOVhZjeniyoKrR8wrPSU+TT9qMJMhzwLVI+10wPWZhiKGmKbKJsbmkFY5dZbE3hPmcufByrCYb2ouOQ0d/AEbKZpdqbIZWkkX6Rs5Qsm7ekDLHMv4bQuOLX9UwJghzjLuE/9U6qW51lfmwXcEtwFm2QZupcblB8QYYwEB6oCuf2Y+O10G+/GLAnowKZ+pFFjgOON5HJl4ehJ65IvXbOLOHY9OIIsBymLzJByVDzXUhod29Gc5dzZnDKafZfNVPoQ4YylR+oC1n3RuML0D2+aK4HoYSWMI9Gi+aKFI64lJ+ef6v0uobMr9/Z82cIvBw4MEVCVFLpX5lqEXIVdoV2W3OxbLhivVUkRmU0CSGmDNz3SuOQz0m9Aq07n2CUxoypiCmITYv8kQOcF6nRuLnKRN7b8t0HqBybMBpDlVOLYY9sSnSBeBB583VBby1lBFgsSB82aSKjDW74beNFz5K856vEnZmSvopvhs+F5IiYj7aZ8abkthLJ79zh8UUHdhzPMLJDi1TXYiduInaIejh7K3h4cVJnCFr/SbM3tCOaDgz5r+Mozxm8FqujnDCRGImahNqD3YaOjbqXEaUttZLHsNvs8KAGJhzVMAxEN1XOY2FvlXcqfPt8AXpUcyVpxFuYSx455iSMD7b5DeQ5z927j6rWmyWQ14csg0uCOYXiixGWeaOxszzGitr/7/EFuhutMCpEmFVwZD1wpHhkfVZ+c3vRdKNqOF33TF46/iV1EGr6h+R3z927U6pgm3iP+oYmgiSB+oOUir6UKqJxshPFgNkb7zoFMxtbMA1EsFW8ZLpwT3k2fkl/gHzvdctrYV4YTnE7+iZTESX7GuXfzxi8X6o+myqPgoaJgWWAIYOmicKTKKFusRjElNhD7nsEkxrdL7VDgFWzZNlwlHmfftJ/JX2tdptsPV/7TlM81yclEub7xuVx0Iy8tKpxmzqPb4ZUgRGAroIZiR+Tc6CssE7Dxtd47bgD3Bk3LyRDCFVXZJtwdHmffvJ/ZH0IdxFtyl+dTwU9lCjoEqv8iOYq0Tm9T6v3m6iPwYaJgSaApILviNaSDKArsLXCGte87PECEBlqLlxCSVSnY/9v8Hg2fqh/O30BdyxtCWD8T4Q9LymcE3P9XucK0h2+MKzPnHKQeIcmgqWAAYMoieiS95/ur1HCkdYR7CoCMBh4LV5BRlOmYgdvCHhlffR+qXyXdu1s9l8YUM49pik9FDr+R+gO0zW/Va35nZiRkYgqg46BxoPDiVWTMqD0ryHCLdZ662MBPxdjLCxAAFJVYbRtvnYtfNd9sHvJdVJskl/vT+I99ynKFAD/QOk01IDAvK5xnxeTDIqWhN+C84TCih+UvqA/sCjC7tX36p4APhYsK8g+eVC2XwlsE3WOelJ8UHqZdFpr3V6BT789IipCFcL/SOp71fzBYrA3oe6U54tnhpiEh4YkjEOVnaHQsGfC19WL6uD/LxXXKTU9s07KXQZqCHOLeGZ6iXgGcwhq1V3NTmU9JSqjFX4AXOvf1qbDRrJHoxuXII6biLeGgIjojcSWzqKosd7C6dU26ib/FhRlKHQ7sUyWW69noXAmdhR4XnYScVpoe1zSTdI8/inrFTQBe+xe2HzFZrSfpZuZtZAxizqJ3YoMkJ+YUKTGso3DJdb76XX+8xLYJok5dkoaWQdl321gc191z3O+blJm0FqRTAU8rikZFuABoe332XvHvbY9qGyco5MnjiCMnI2QktOaJKYqtHfEi9ba6c39yRE0JXY3A0hbVg9ixWo8cEly4HALbPFj1FgKS/86MiksFoICzu6n26HJSrkdq4qf6JZ4kWWPvJBylWCdSKjUtZnFHNfV6TH9mhB6Iz41XUVaU8teV2e9bNVukW37aDlhiFY9ScA5iigiFhgD/+9r3evLCbw9rvOif5ojlQeTOpSvmESgvKrEt/XG2tft6aP8aA+tIeMyhkIcUD5bl2PmaAZr5mmRZSpe7VMrR0c4tyf7FZ8DMvFA31bO976ZsaKmZ54lmQOXEphGnH2jfa34uYvIxNgj6iP8NQ7PH2kwgT+kTG1XiV+8ZN5m4WXPYchaBVHURJU2tya2FRcEZPIl4d/QEsIttZWqmqJ4nVabQpwzoAini7BwvFnK2tl46rP7Aw3kHdItUjz1SFlTMVtAYGFihmG3XRRX0007Qqo0iiVRFX4ElfMW44PTVMX2uMeuFqcbovufxqBzpOOq47Mqv2DMHdvt6lX71AvtGyEr/DgTRQlPk1Z4W5Rd2VxOWRJTVkphP4gyMiTNFNMEwfQS5T/WvMjwvDWz1asHp/Ckm6UEqQyvgrckwp3Oi9yB6wr7qwruGVsogzUCQX9Ks1FoVnpY3VeXVMROlEZHPC8wrSIpFBUF6PUV5xDZRcwXwdq31LA6rC6qvarhrX6zaLtexRHRJt427NL6iAnoF4El6zHHPMFFlkwTURhTllKVTy5KjULvOKEt/CBjE0IFBvcd6fLb7M9mxbG8DravsbOvKLAHsze4j7/UyLrT7d8L7bD6bgjeFZciNy5kONJAQEeAS3JNCU1MSlJFRT5bNd4qIB9+ElkFG/gn6+PerNPaybbBfrtgt3m11rVxuDS998OEzJbW3eEB7qP6XwfUE6EfayrfM7c7t0GyRY1HO0fBRDZAvjmPMeonGx13EVsFJPkx7d7hg9duzuXGIMFJvXu7w7scvnDCm8hs0KPZ+OMY7636XAbKEaAciiY9L3U2/zuwP25BMEH4Ptw6/jSMLcUk7BpQEEUFIfo57+LkbNsf0znM7sZkw7XB68ECxObHeM2I1N/cOuZP8M/6ZgXFD5oZmiKAKhExHTZ9ORs77Tr2OEk1BjBWKXEhlRgJDxcFD/s88evnZN/n16zR48ytySHISMgfypTNidLX2EngpOim8Qj7gATFDZAWnB6uJZArFjAgM5g0dzTAMoIv2yrwJPIdGRaiDdIE7vs48/bqZuPB3DrX+dId0LnO1c5u0HPTzNdU3d3jNOsd81r7qQPNC4UTlhrMIPYl8CmeLOwt1C1aLIspgSVdIEkadxMdDHQEu/wr9f/tb+er4d7cLNmv1njVjNXp1oHZPN384Zrn5+2y9MT75QLgCX0QjBbdG0kgsSP8JRwnCifKJWkj/B+gG3oWshB5Cv4Ddv0S9wTxeuue5pPid99e3VjcaNyL3bbf1eLM5nzrvPBk9kb8MwL/B3sNgBLmFo4aXR1BHy4gHiAXHyEdURq+FoYSzQ24CG8DHv7t+AP0hu+X61To0uUk5FPjY+NP5A/mkejA64DvsvM0+OH8lQEsBoIKdg7sEckU+xZyGCcZFhlEGLkWhBS6EXIOyArbBsgCsv64+vf2jPOR8BvuOuz76mPqduov64bsbe7T8KPzxPYe+pX9CwFpBJQHcwrzDAEPjxCWEQ4S+BFYETUQmw6ZDEEKqAfjBAkCMv9y/N75i/eI9eTzqPLc8YPxnfEm8hbzZPQC9uL38/kj/GD+lwC4ArQEegb/BzkJIAqxCukKygpZCpsJmQheB/UFbQTSAjIBnP8Z/rb8fvt4+qn5F/nD+Kz40fgs+bn5cPpI+zn8Ov0//kL/OAAbAeQBjgIVA3cDswPKA74DkwNMA/AChAINApMBGwGpAEQA7/+s/33/Yv9b/2b/gf+p/9j/CgA8AGkAiwCgAKQAlQByADoA8P+T/yn/tP46/sH9Tv3n/JT8WPw5/Dv8Yvyt/B/9tf1s/kH/LAApAS4CMgMuBBUF4QWHBgAHRgdSByIHtAYIBiIFBgS6AkkBvv8h/oH87fpw+Rn49PYN9m71HvUk9YH1NvZA95v4PPoa/Cf+UwCQAskE7wbtCLMKMgxaDSAOfA5mDt0N4gx5C6wJhgcWBW0Cov/G/PL5Pfe89IbyrfBD71Xu7e0T7sfuB/DM8Qv0tfa2+fn8ZADfA0wHkgqUDTsQbhIbFDEVphVyFZUUERPwEEAOFAuCB6UDnP+D+3z3p/Mi8AvtfeqN6E3ny+YM5xPo2elU7HTvIvND97j7XgAVBbUJGg4gEqcVkRjEGi4cvxxxHEMbOxlnFtkSqw78CfAErf9a+iL1LvCm66/naeTy4V7gvd8W4Gvhs+Pf5trqhu/C9GT6QwAxBgEMgxGMFvMalB5QIQ8jwSNdI+MhXB/ZG3MXSRKDDEwG0/9K+eXy1exL53Tid95324zZydg32dXamd1x4UHm5us28gD5EQA0By8OyxTVGhwgdCS5J9AppSovKm4obiVCIQoc6xUUD7cHDgBV+MbwnukV41/drNgh1d7S9tF00lbUkdcO3K3hROih7473zP8bCD0Q8Bf4HhwlKir6LWowZTHhMN8uayueJpogjRmrETEJXwB798jui+YG33TYC9P2zlnMScvTy/TNoNG71iLdo+QH7Q32cf/oCCoS7xrxIvAptC8ONNk2/TdvNzA1TjHmKx8lKx1IFLcKxAC89uzsoOMj27jTms37yALGyMRaxbbHy8t+0aTYCOFp6oH0Av+ZCfYTxh2+JpQuDDXvORY9Zj7SPVs7EzcXMZQpwyDmFkkMPQEZ9jLr3eBt1yzPXMg0w9+/eL4Ov5/BGcZbzDnUdd3L5+vygP4vCp4VdCBbKgUzLjqaPx5Dm0QFRFxBszwrNvUtTySDGeINyAGR9ZvpRt7p09bKV8OnvfW5X7j1uLW7jMBXx+PP79kw5U7x7f2pCiIX9iLHLUA3FT8JRepIl0oCSixHKkIeOz8yzicdHIMPYwIk9Sno2tuX0LnGjr5XuEi0grIVs/+1LLt2wqfLedaZ4qvvSf0JC4IYSyX+MEA7v0M4SnZOVVDFT8hMckfrP2w2OyuvHikRDwPR9NvmnNl6zdbCBLpKs96u5axxrYCw/LW+vYrHFtMK4APulfxOC70Zcif/MwQ/KEgjT71Tz1VIVSlSiEyORHk6ky45IdESygOZ9LPljdeVyjK/vbWCrrqpjqcQqD6rArExuY7Dys+H3Vvs1Pt5C9MaaSnINohCTEzHU7xYAluHWktXZlEDSWE+0jG2I3kUkQR69LDkrtXpx867vLEEquKkgaL1oj2mQqzWtLm/mMwR27PqB/uMC8QbMCtXOctFKVAfWG1d6V99XylcB1ZETSJC9TQkJiAWZAV19NLj/9N4xa24Ba7TpVigwp0lnoKhwKewsA+8hcms2A7pLvqFC48cxiyrO8pIu1MoXM5hf2QlZMBgaFpOUbZF+TeAKMIXQgaH9BnjgtJCw9G1maryoSGcVZmlmRGdgaPDrJK4k8Za1m/nTPlnCzUdKi7CPYJLAFffX9tlwmh8aAplhV4dVRpJ2TrGKl4ZJwew9IbiNtFKwTyze6dknj+YPZV4le+YiJ8TqUa1xcMf1NflY/gzC7cdXS+bP/RN9llCY5BprWx+bARpWGKtWEtMkz31LPEaEwjv9BbiHdCPv++wrqQtm7eUgJGikR6V2pukpTCyH8H+0UnkdffqChQeXTA3QR1Qm1xOZutsPXAocKts4GX6W0ZPJEAJL3kcBAlC9crhNc8TvuuuMqJNmIqRHo4mjqOReph5olOvpL74z8jigvaNCk4eLDGTQvtR7V4Baepvb3N1c/pvF2kCXwZSiEL/MPMd+Amp9aHhf87WvDGtCqDHlbuOG4sHi4CObJWWn7GsWLwRzlXhjvUdCmYeyjGxQ5BT62BZa4lyQXZkdu9y/GvAYYlUvUTWMl4f7Qoh9pvh+s3Yu8KrNp6dk0yMeohJiLmLspL+nE6qPLpMzPPfmfSdCVweNjKPRNlUlGJVbcd0sXjyeId1i24xZMtWv0aJNLYg4Aup9rXhps0Zu5+quJzQkT6KPYbthVGJT5Czmi2oU7iryqXep/MNCTIecjIvRdZV52PzbqN2vHoce8B3wXBUZstYjUgXNvoh0QxA9+7hgc2ZusepkJtikJSIZYT1g0mHRo65mE+mobYwyWzdufJvCOkdfzKQRYlW5GQycBt4YHzgfJZ5nHImaIVaI0p+NycjvA3k90bijM1WujqpvppSj0+H9IJkgqOFmYwRl7mkKLXex0vc0PHGB4MdXjK0RfBWi2UTcS55nX0+fgp7GnSjafdbf0u7ODwkoQ6T+LvixM1RuvmoQpqhjm6G64E7gWKES4u+lWuj6bO3xkTb8PASBwAdDzKbRQxX22WUcdx5cn4zfxh8OXXLaiBdoEzMOTUlfA9L+UvjKc6IugGpHZpPjvOFS4F6gIeDW4rBlGii57K9xVnaGvBWBmMclTFHRd9W1mW2cSR63n6/f8B8+HWca/1dgk2uOhImTRAK+vXjuM76ulOpTZpcjt6FE4EjgBODzYkclLKhJLLyxIvZT++UBa4b8TC4RGlWfGV6cQd64X7hfwF9VnYVbIxeJk5hO88mERHQ+rbkcc+lu+2p0ZrIji2GRYE1gAWDoInRk0qhobFYxN7Yku7MBOEaJDDwQ6xVzWTgcIV5e36af9p8UnYzbM1eiE7iO2wnxhGY+43lUdCJvM2qqZuQj+KG4IGygGCD1YnfkzChYLHxw1LY5e0DBP8ZMS/xQqhUzWPpb594rH3pfkx863X3a75eqE4wPOcnaxJj/HnmV9GivfOr0py1kPmH44KXgSKEbYpJlGehYrG9w+nXSu04AwsZGS69QWFTe2KXblZ3dXzOfVZ7InVga19ehE5JPD4o/RIt/XbngdLwvlutS540knOJTITmgkuFaIsNle6hqLG+w6XXwexuAgUY3ixWQNhR2mDrbKt12XpMfPp59nNvaq9dHE4tPG8oexP1/YPozNNwwAWvE6AMlE6LHIachNuGxYwtlseiMrL2w4fXTuyoAfEWgyu+Pg5Q7V7naqFz13hiejd4aHIiaa5cb03aO3ko5BO6/p7pNtUfwu6wJqI7loiNT4i5htCIhI6nl/GjArNkxJDX8evmANAVCir4PAhOtVyOaDlxcnYTeBB2eXB7Z1xbfUxQO1woNRR4/8Xqvdb8wxKzgqS9mB2Q5Io6iSmLo5B7mWulF7QKxcLXq+srAKMUdSgGO8ZLNVrjZXZurXNhdYVzKm56ZblZRUuOOhYobhQuAPbrX9gDxnC1JaeRmw2T2Y0djOWNIZOomzancbXpxR3Yf+t5/28TxybqOExJcFfnYlpriXBNcppwfWshY8ZXyEmTOaYnjRTcAC7tGdozyAW4DKq0nlSWK5FgjwCR/JUtnlGpELcAx6LYbuvR/jQSAiWoNp5GaVSfX+lnCm3bbk9tdGhwYIRVBkhgOAsnkBR/AWvu6duHys26M60hou6Z1pQAk3mUM5kIobqr9LhPyFLZeOs1/vQQKCNCNL1DI1ENXCdkM2kNa6hpEGVqXfRSAEb0NkYmeBQVAqzvy93+zMW9lrDXpdmd2Jj7lk2Yw5w4pHCuHLvXyS3an+um/bMPPSG7Ma5Aok01WBVgB2XnZqhlVWESWhhQt0NRNVUlQhScAu7wvt+Uz+rAM7TQqRCiLZ1Mm3mcqaC5p3Kxhr2WyzPb5Osm/XEOQx8XL3M96kkbVLlbimBsYlJhRV1oVvFMLEF1Mzkk7xMUAy/yv+FG0jnEBrgKrpCm0aHwn/mg4qSLq760MsCNzWXcR+y2/DENPB1YLBE6/UXCTxZXwVugXalc41hvUoFJYD5jMfIifBN8A23zy+MR1a7HC7yAslWrwKbjpMqla6mpr1G4HsO6z8LdyexY/PYLKxuBKYo24UEwSzFSrlaHWLFXM1QsTstFVTscL38h6xLQA6b04OXy10bLPcAtt1qw9ashqueqQa4RtCm8R8Yc0krfau0N/MAKExmXJuMymT1oRg1NV1EmU25SOU+gSdJBDTifLOIfOhISBNj1++fl2vvOmsQOvJq1bbGlr02wX7PAuEPArcmz1P3gK+7V+5EJ9habIx8vKjlvQbFHwEuATeZM+EnQRJg9ijTvKRoeaRE+BAL3Gero3czSG8kewRG7Ibdrtfi1wrixvZ3ETc1819niC++z+20I1xSSIEMrlzRKPCBC70WbRxtHdES+PyA5zzANJykceBBWBCH4OOz34LTWvs1YxrrADr1tu+G7Zb7iwjLJI9F22t7kDPCn+1MHuRJ+HVEn5i/9NmA86D99QRNBsz5wOm003Sz8IxAaaA9XBDX5Vu4P5K/afdK3y5HGLsOnwQbCRMRNyADOL9We3QvnLPGx+0cGnRBjGk4jGiuMMXU2sTkpO9Q6uDjoNIQvuSi9IM8XOA5BBDr6b/At57neVdc30Y7Me8kTyF/IWcrvzQPTa9nz4F/pbPLS+0gFhg5DFz4fOCb+K2YwTzOlNGI0iTIsL2gqZSRSHWkV6QwUBDH7g/JN6s7iQNzT1q7S8c+tzunOoNDE0zfY1t1z5NjryvML/FoEdwwjFCQbRSFXJjcqxyz4LcItKyxBKR4l5B++Gd4SewvPAxf8jfRt7evmOuGE3OvYidZt1Z3VFNfF2ZjdbOIa6HTuR/Vc/HwDcQoFEQUXRBycIO0jICYmJ/smoiUqI6gfOhsEFjEQ8AlyA+z8jfaJ8AzrP+ZH4kDfPt1O3HbcsN3w3yLjKufn6zLx4PbF/LECdwjsDeQSPBfSGo8dXx82IBIg9h7uHAwaahYmEmMNSAj+Aq79gfie8yzvS+sW6KblCuRM427jbeQ95s/oC+zV7w/0lvhG/fkBiwbaCsUOLxL/FCIXiRgtGQwZKhiQFk4UeREoDncKhQZxAlz+Zfqq9kjzV/Dt7Rns5+pf6n/qRuup7JzuC/Hj8wr3Z/rf/VQBrwTUB6wKIw0nD6sQpRESEvARRBEXEHMOagwMCm4HpgTMAfb+Ofyq+V33YfXF85Py0PGB8aTxNvIu84P0KPYM+CD6UvyP/sUA5ALcBJ0GHAhPCTAKuQrqCsQKTAqHCYAIQQfWBUsErwIQAXr/+v2b/Gb7ZPqb+Q75v/it+Nb4NvnH+YH6XPtO/E/9Vf5X/0wALQHzAZsCHwN9A7YDygO7A44DRQPnAnoCAwKJAREBoAA8AOn/p/96/2H/W/9o/4T/rP/c/w4AQABsAI4AoQCkAJMAbgA1AOn/i/8f/6r+MP63/UX94PyO/FT8OPw9/Gb8tfwq/cP9ff5U/0EAPgFEAkgDQgQoBfAFkwYIB0kHUAcbB6gG9wUMBewDnQIpAZz//v1f/Mz6Uvn/99/2/fVk9Rz1KPWM9Un2Wve7+GL6RPxV/oMAvwL4BBsHFQnWCk4Mbw0sDn4OXw7MDcgMVwuBCVUH3wQzAmX/ify3+QX3ivRb8orwKu9H7uvtHO7c7ifw9/FA9PL2+vlB/a4AKQSUB9UK0Q1uEJcSOBRCFagVZhV7FOkSvBABDssKMgdQA0X/LPso91jz3O/P7E3qa+g758nmG+cx6Afqkey973bzn/ca/MMAeQUVCnQOcRLrFccY6hpCHMEcYRwgGwcZIhaFEkwOlAmBBDv/6fm19MjvS+ti5y3kx+FH4LvfKeCS4e7jLec36/HvNvXg+sEArwZ6DPQR8RZJG9gefyEoI8MjSCO3IRsfhBsMF9QRAgzDBUj/wPhf8lns3OYW4i3eQ9tx2cfYTtkF2+HdzuGy5mfsw/KV+aoAywfADlIVThuCIMQk8SfuKagqFio6KCAl3SCQG2AVew4WB2r/svcp8AvpkuLw3FTY5NS90vPRj9KO1OXXe9ww4troRvA7+HwAywjmEI0YhB+TJYgqPC6OMGkxxTCjLhErKSYNIOwY+xB3CKL/v/YT7uPlcN7116bSsM4zzEXL8cs0zv/RONe43U7lwu3T9joAsAnrEqIbkSN4Kh8wWTQCNwI4TzftNOkwYiuAJHYcgRPmCe//6PUf7OLiedoo0yjNq8jWxcPEe8X8xzbMCdJM2cfhO+te9eT/eQrOFI8ecSctL4Q1RDpFPWw+sD0RO6M2hTDkKPofChZgC08ALfVP6grgsdaMzt7H28Kuv3G+Mr/swY3G9Mzx1Ejesujf83r/JguMFlEhISuuM7M6+D9SQ6NE4EMMQTk8izU1LXMjkhjkDMMAjvSi6F7dGdMmysvCRL2+uVa4G7kJvAvB/cer0NXaK+ZY8v3+twsmGOgjny74N6c/cEUjSaFK3EnWRqZBcjpuMeAmFxtvDkgBC/Qa597atc/5xfW967cMtHeyPLNYtrS7KcN/zHDXqOPJ8G7+LQybGVAm6DEIPF5EqUq1TmFQnU9tTOZGMz+MNTwqlx0AEN8Bo/O45Y3Yh8wHwl+51LKbrtismq3esIy2fL5wyB7ULOE279D9hwzqGooo+zTaP9NInU8CVN5VH1XJUfRLy0OLOYMtDiCVEYUCV/N85GvWkclUvgy1A65yqX6nOqigq5qx+rmCxOLQut6g7SL9xgwTHJQq1DdtQwNNSlQHWRNbXVrnVspQNUhnPbMweiIrEzoDJfNm43rU1cbiugCxfKmUpG+iH6OjpuCsqbW6wL/NVdwK7Gf86gwWHWwsczq+RutQq1i+XfxfUl/CW2VVbUwbQcgz2CTAFPsDDfN34rvSVMS0tz2tQqUEoK2dUJ7soWWojLEbvbnK/9l26qD79gzzHRIu1jzKSYhUvFwlYpZk+mNVYMBZblCkRL42JSdSFsgEDvOt4S7REMLLtMapWaHHmz2Z0Jl+nSukp62oudTHvNfm6M766AypHoYv+z6PTNhXfGA3ZttoUmidZNddNVT/R5I5XinfF54FJ/MK4dPPCsApsp6mxJ3glyOVopVdmTig/qlnthHFjtVd5/T5www6H8cw4kAMT9ha52PyaclsVGyVaKdhvlcnS0E8gCtlGXwGWPOM4KzOQ77Rr8ejhJpSlGKRzJGOlY6clqZZs3bCeNPc5RP5iAylH9UxiUJAUYZd+2ZTbV1w/m86bCplBVsZTsg+iS3hGmAHnvMz4LfNu7zCrUKhnZcfkf2NT44UkjKZcaODsATAfdFm5C34NwzsH7Ay8UMpU+FftWlXcJJzTXOIb19oCF7SUCRBdi9QHEgI+PP+3/bMc7v+qxGfEZVLjveKL4vyjiaWkqDorb+9n8/94kP30wsPIFgzGUXHVOdhE2z7cmh2PXZ8ckFrwmBPU1FDRDGxHTIJZvTt32fMa7qHqjad4JLXi1OIb4gsjG6T/p2Kq6q74s2k4Vj2XAsPIM4zAUYYVphjFW4+ddp4zXgUdc5tMGONVU5F8DIBHx0K5fT+3wnMo7lcqbGbDZHFiRKGEYbDiQ2Rtpttqce5R8xd4G711QrtHxM0qUYeV/JkuW8ed+h6+HpNdwNwUWWJVxdHeDQ/IAYLdfUw4N3LG7l9qIKamY8XiDeEGIS6hwSPvZmSpxm40soq34b0PgqsHyc0EUfWV/Rl/XCaeJB8v3wled5xIWdBWalI2zVnIewLEvaB4OHL07jqp6uZhI7OhsOChIIUhleNFpj+paK2g8kO3qPzmglLHws0OkdDWKBm4nGxedB9H36aelxznmiyWgNKFDd3IswMvPbx4BTMyLijpyuZz43phbeBWIHShAiMw5axpGW1X8gK3cby6gjMHsEzJkdkWPVmZ3Jjeqh+Fn+qe310xmnaWyNLIzhvI6UNcfd94XXM+7iopwGZeo1rhROBlYD0gxeLxpWuo2S0Zscg3PLxMQgyHkoz1UY6WPNmjXKuehd/pX9UfD11mGq3XAZMBjlKJHUOL/gl4gLNa7n3py6ZhI1ThdmAO4B+g4aKH5X2oqCzmsZT2yjxbwd+HacySEbGV5tmU3KTehx/yn+XfJ51E2tJXatMujkJJTkP9Pjm4rrNFbqPqLGZ7Y2ghQmBS4Bug1eK0ZSMohuz/8Wk2mrwpwaxHNsxgUUKV+5lu3EUerh+hX90fJx1NGuMXQ9NPTqoJfAPvvm+45vO+LpvqYeatY5ShqGBxYDFg4mK3ZRvoteylMUV2rrv2wXOG+YwgUQGVu5kxXAveex91n7oezl1/GqCXTNNjzomJpgQjPqs5KLPE7yVqrGb2Y9oh6GCqIGEhB6LQpWiotSyW8Wo2RvvDQXWGswvS0O+VJxjc2/nd7d8v332enN0amonXRRNrTqCJi8RW/ut5c/QY70ArCudWJHiiAmE9IKqhRSMApYkoxSzV8Ve2Y3uPgTMGY0u4UEyU/phx209dhx7P3ydeUxzfWl9XLJMmDq6JrMRKfzA5h/S576srfSeMZO8iteFqIQ2h22NG5f2o5izh8U42RLucQOxGCwtREBlUQpgwmszdBx5WHred8NxNmiDWw1MTDrMJiQS9fzi55DTnMCZrwqhYZX2jAmIwoYniSaPj5gYpWC07sU52aztpwKIF6wreD5aT89dZ2nLcbl2DHi7ddlvlWY4WiNLyzm4Jn4SvP0R6R/Vf8LDsWuj5peMj56KQIl8iz+RXJqLpmy1isZh2V3t4gFTFg8qfzwSTUpbuWYHb/RzXHU1c5BtnGSeWPVJEzl8JsISfv5M6srWjsQntBKmvZp9kpKNIYwzjreTgpxNqLy2Xsex2SbtJQEUFVcoWjqSSoBYumPqa9FwS3JNcOpqSmK0VoJIIzgYJuwSN/+P647Yx8bDtv+o453FleOQYY9KkYyW/55eqlC4acgq2gjtcADNE4cmDjjbR3JVbWB3aFJt224Hbedno198VMxG/TaLJf0S5//Z7GnaJsmUuSysVaFimY+UAJO+lLyZ0aG9rCm6q8nM2gTtx/+AEqIknjXxRCVS1lyxZHppD2tlaYpkplz3UdJEnzXTJPMSigAo7lncqMuWvJivEKVQnZGY+JaOmEWd+KRor0O8JcuY2xztKP8wEakiCzPXQZxO+FicYE5l62ZpZdZgVlkmT5ZCCjTyI84SIgF571reSs7Hvz6zEKmLoeecR5u1nCShcKhesqC+1syO3FDtmP7fD6AgWTCRPtpK11Q8XNBgcmIYYc1ctlULTBlAPjLmIosSqwHK8GrgCtEiwxq3Ua0Qpo2h6Z8woValN6ydtT7BvM6v3aLtF/6ODokejC0iO+RGeFCUVwRcp11zXHNYyFGoSFw9PDCwISsSJAIa8ofi5NOkxiq7z7HZqn2m26T9pdepS7AjuRrE2dD73hHupv1ADWccpiqON71C3UuqUu9WkFiAV8tTj00ARWA6BS5QIKwRjAJm863k1dZJymi/hbbkr7WrGKoWq6WuqLTuvDTHKtNw4J/uR/33Cz0aqifYM2k+DEeATZZRL1NCUthODkkUQSg3myvGHg8R4QKs9Nvm2tkOztDDb7sqtS+xm694sLyzTLn6wIrKrtUP4kvv+/y0Cg0YnSQFMO05CUIeSPxLik2+TJ9JSUToPLYz/SgTHVMQIwPq9Q3p79zv0V/IicCouue2YLUethe5Mr5GxRjOZNjX4xbww/x6CdoVgSEYLE012TyGQihGpkf3RiNEQz9+OAwwLyY2G3gPUQMf90DrEeDn1RDNzsVZwNe8YrsDvLK+V8PNyd7RStvH5QHxofxKCKYTWh4VKI0wgTe+PB1Ah0H0QGo+ADrbMywsMSMzGX4OaQNJ+HTtPeP02d7ROcs3xvvCnMEjwonEt8iMztfVXt7e5wryk/wnB3QRKhsAJLErBTLLNuI5Mzu4Onc4hDQBLxkoByAIF2YNawNm+aTvb+YQ3sXWxdA9zE3JCch5yJbKTs6A0wLan+Eb6jLznfwRBkYP9hfdH8AmaiyzMHszrzRKNFAy1C70KdcjsRy5FC8MVgN1+s7xpek54sDbbdZm0sfPo87/ztbQFtSk2FreCuV97Hj0vfwKBSANwBSwG7whtiZ6Ku4sAS6uLfkr9Ci4JGkfMhlFEtoKKgN0+/Hz2+xp5szgLNys2GXWZNWw1ULXDNr23d7inOgC79z19fwTBAILixF9F6oc7SAnJEEmLifqJnkl6SJSH9IajRWvD2cJ5wJi/An2DvCe6uLl/eEL3x/dR9yG3NbdK+Bw44jnU+yo8V33RP0uA+8IWw5HE5AXFRu/HXofPSADINMeuBzFGRUWxRH5DNkHjAI+/RX4O/PT7v/q2+d85fLjRuN744zkbeYO6VfsLPBt9Pn4q/1cAuoGMgsTD3ESMxVHF54YMhkAGQ4YZhYXFDYR3A0lCi4GGQIG/hP6XvYF8x7wwO3569bqW+qK6l7rzuzL7kTxI/RQ97H6Kf6dAfUEFAjlClMNTA/FELQRFBLnETAR+A9MDjoM1gk0B2oEjwG6/gD8dvkv9zv1qPN+8sXxgPGs8UfyR/Ok9E72N/hO+oL8v/70ABADAwXABjkIZQk+CsAK6gq9Cj4KdAloCCQHtgUpBI0C7QBZ/9v9f/xP+1H6jfkF+bv4rvjc+EH51fmS+m/7Y/xl/Wv+bP9fAD4BAwKnAigDgwO5A8oDuQOJAz4D3wJwAvkBfwEHAZgANQDj/6P/d/9f/1z/av+H/7D/4f8TAEQAbwCQAKIAowCRAGoALwDi/4L/Fv+g/ib+rf08/dj8iPxR/Df8P/xs/L78Nf3R/Y7+Z/9VAFQBWQJdA1YEOgX/BZ8GEAdMB04HFAebBuYF9gTRA38CCQF6/9z9Pfyr+jT55PfJ9u71W/UZ9S31mfVc9nX32/iI+m/8gv6yAO8CJwVHBz0J+QpqDIINNw6ADlcOuw2tDDMLVgkjB6gE+AEo/0z8fPnO9lj0MPJp8BLvOu7q7Sfu8u5J8CTydvQv9z36if34AHIE2wcYCw0OoRDAElQUUBWpFVkVXxTBEocQwA2CCuIG+wLt/tX61PYK85bvlOwf6kvoKufI5irnUeg36s/sCPDL8/z3fPwnAd0FdQrNDsASLxb8GA8bVRzCHE4c+xrQGNsVMRLrDSoJEgTJ/nj5SfRk7/LqFufx457hMuC63z7gu+Er5Hvnlutd8Kz1XPtAAS0H8gxjElQXnRsZH60hQCPDIzEjiSHXHiwboxZdEYELOwW8/jX42/He62/muuHl3RHbV9nG2GfZN9sq3i7iJOfp7FDzK/pCAWIIUQ/YFcUb5yATJSgoCiqoKvspBCjQJHUgFBvTFOENdAbF/g73jO966BHig9z/16nUn9Ly0azSyNQ72OvctuJy6evw6fguAXsJjxEqGQ8gCCbkKnsurjBqMaYwZS61KrIlfh9KGEsQvQfk/gP2X+085dvdd9dE0mzOD8xEyxLMds5h0rfXUN775X7umfcEAXgKqxNUHC8k/SqIMKE0JzcEOC03pzSCMNwq3yO/G7oSFAkZ/xT1VOsm4tLZmtK5zF7IrsXAxJ/FRsijzJfS9tmI4g3sPPbFAFkLpBVWHyIowi/6NZU6cD1vPoo9xDowNvAvMSgvHywVdwpi/0H0bek53/bV7s1ix4XCgL9uvlm/PMIFx5DNrNUd35rp1PRyAB0MeRctIuUrUzQ1O1NAgkOnRLhDuEC8O+k0cSyVIp8X5Au//4vzqud43E3SeclDwuW8i7lRuEW5YLyNwabId9G82yjnYvMMAMUMKRnYJHUvrTg2QNRFWUmnSrFJfUYgQcI5mzDvJREaWg0tAPLyDebk2dfOPMVgvYO307NwsmiztLY/vN7DWs1p2Ljk6fGU/1ANsxpUJ9AyzDz5RBZL8E5oUHBPDUxXRnc+qjQ6KX0c1g6vAHXyl+SA15fLO8G+uGOyXa7QrMetQLEgtz2/Wcko1U/iavAK/74NFhygKfM1rUB6SRNQQ1TnVfFUZFFcSwRDmzhxLOIeVxBBARXyR+NM1ZHIer1ftImtL6l0p2ioB6w2sse6ecX80e/f5+5w/hEOUh28K904T0S2TchUTVkfWy1aflYrUGNHaTyRLz0h2xHjAdDxHuJJ08TF+rlHsPmoSqRhok+jDqeErYC2vsHozprdY+3H/UgOZx6lLYw7rUepUTJZCl4LYCJfVVu/VJFLEUCXMosjXxOSAqbxHeF50TTDvrZ5rLektZ+dnYCeWqIPqWyyKr7wy1Tb3+sS/WUOVR9cL/09xkpRVUxddmKnZMpj5V8TWYlPj0OANcgl4RRNA5bxQ+Dcz+HAyLP4qMagc5sqmQCa753bpJCuw7oYyR/ZX+pR/GgOGyDfMDBAmE2rWBRhjmbvaCFoKmQlXUlT30ZIOPQnYBYUBKDxkN9zzs6+G7HGpSidhpcNldOV0ZntoO+qi7dhxv/W5OiF+1IOuyAuMiRCIVC1W4ZkT2rgbCRsH2jvYMtW/knsOgkq1xfjBMHxBN8+zfq8t67louGZ85NJkfuRBJZHnY2nhrTQw/XUcOey+iUONCFJM9hDX1JtXqFntW12cM9vw2tvZAxa6ExqPQcsRxm6Bfrxnt49zGa7nqxXoPOWu5DijX6OjJLumW2kt7FowQTTBebY+eENhyExNEtFU1TQYGJqvXCvcx9zEG+gZwldmk+9P+otqxqXBknyXd5vyxO60KoenmCU4o3Zil2La4/mlpOhI68rvzDRp+T5+IgNtiHkNH5G+VXeYsdsZ3OHdhB2BHKAar5fEVLjQa8vAxx3B6zyQd7WygK5UKk7nCmSaYsxiJuIpYwwlAOfyqwcvXrPV+MY+BsNwCFkNW5HU1eWZM9urnX9eKF4m3QLbSliSlTZQ1QxSx1ZCCLzSd5wyjK4HaivmlCQU4nuhTyGPIrQkb6csao/u+bNF+I295wMpyGxNR5IYFj3ZXhwk3cOe8561XY/b0dkQ1adRdcygh47Carzct48yqK3N6d6mdeOoIcPhEGEM4jIj8ea2qiVuXbM6uBU9g0MbCHMNY5IH1n/ZsJxE3m5fJd8rXgZcRZm+FcsRzQ0pB8bCkH0vt45ylO3nqadmL2NU4aYgquCi4YcjiGZSKchuCvL0t929W4LESG2Nb1IkVmwZ6xyLnr8ffl9I3qYcpJnZ1mESGs1sSD3Cub0KN9nykO3U6YZmASNa4WJgX2BR4XLjM+X/KXmtgnK0d6d9MIKlyBwNa1ItlkJaDVz43rXfvN+NXu6c7toj1qiSXg2piHNC5j1sd/EynO3U6bsl6uM6YTjgLiAaITZi9CW+aTltRHJ6d3L8wsK/x/8NF9IkFkKaF1zMXtJf4R/4Xt8dI9pbVuFSlo3gSKbDFT2V+BPy9+3oKYWmLKMzoSmgFuA74NHiyiWQKQgtUbIHN0B80oJTB9bNNRHHlm1ZyZzGXtRf6t/J3zfdAtqAFwrSw84QCNgDRn3F+EGzIi4NqeWmBmNGYXTgGmA3YMVi9iV06OZtKjHa9xC8oIIfx6PMw1HY1gKZ5BynHrvfml/BnzgdC9qR1yTS5U44SMZDuX38OHnzGy5Fqhsmd+NyYVpgeCAMYREi+CVs6NRtDrH2tuQ8bQHmh2ZMg1GYFcKZptxuXklfr1+fnuAdPtpQFy6S+s4YyTEDrX44eLxzYi6PKmVmgKP3oZngsCB7YTUi0GW4aNKtP3GaNvs8OIGnxx8MdZEFla4ZEpwcnjzfKl9j3q/c21p6luhSw45xCRgD4j55uMhz9u7qaoQnIGQVojNgwmDD4bHjPyWXqSFtPPGGNtZ8A4GkBs5MGhDiFQUY51uyXZZeyx8OnmccoZoRltFS/84AiXqD1z6/uR10GK9WKzbnVuSMIqZhbqEl4cajhCYKqUCtRzH7NrX7zoFcBrTLsdBuFIiYZdsv3RbeUd6f3cYcUVnU1qnSrs4HCViEDD7J+bs0Ry/Sa70n4yUaozKh9GGhInOj32ZRabCtXrH5Npp72gEPxlNLfU/p1DjXjtqVnL4dv53YHU0b6tlEFnFSUM4EiXGEAD8XueC0wbBeLBYohOXAY9dikyJ1YvikUObr6fFtg3IAtsQ75kDARinK/Q9Wk5bXIpnkW81dFF13nLxbLljflehSJU34CQUEcz8o+g21R3D4rIEpe6Z85FRjSuMh45UlGGdaakLuNbIR9vN7tECtxbmKcg700uLWYdkc2wScUJy+29Qam9hnlU5R7E2iCRLEZH98ekF117FhrX2pxidPZWikGmPmpEil9afcKuUudXJs9uj7g8CZRULKHI5FEl4VjZh/miTbdVuumxUZ9BecFOORZc1CCRpEU7+SOvr2MfHX7grq4+g3JhNlASTCpVLmqCixK1huwvLSNyR7lcBCxQZJvY2IUYjU5pdNmW8aQxrHGn/Y9xb9VChQ0Y0XyNuEQH/pOzo2lXKa7uerk+kzZxQmPuW1JjNnb2lZLBvvXbMBd2a7qoArBITJFg0/UKST7dZHWGPZepmJWVSYJZYME5yQcAyjSJYEaj/BO733ATNpr5MslWoC6GnnEib9pykoSupTrO+vxjO7N2+7goASxH7IZkxqz/HS49VuVwQYXJi2WBRXABVIUsDPwMxkiEmEUEAZu8X39LPDcIztp2slKVNoeifbaHOpeisgbZNwu/P+9797nj/6Q/UH70uMDzHRyhRDVhDXKpdOVz+Vx1Ry0dUPBIvbSDYEMwAx/BE4bvSnMVMuiKxYqpAptikNaZIqvGw+rkaxfrRNeBa7/T+iQ6hHcgrjziVQ4ZMHlMsV5NYS1deU+9MMERoOe0sHx9tEEcBJvJ847zVT8mWvuG1cq95qxOqSasOr0S1t70kyDnUl+HU74L+LQ1lG7woyzQ1P6xH703RUTRTEVJzTnlIUkBBNpQqqR3kD7EBgPO85dHYI80Kw9S6vrT2sJavprAdtNy5tcFpy6vWIuNs8CH+1gsiGZ0l6DCsOqBChkg0TJBNkkxCSb9DNDzfMgooCRw9DwgC0/QB6PjbE9Gmx/i/Q7qwtlq1R7Zvube+8sXnzk7Z1eQi8dT9hwraFm8i6yz/NWU96EJdRq1H0EbPQ8Q+2TdGL08lQhp4DkwCHfZK6i3fHdVlzEjF+r+kvFu7KbwCv9DDasqb0iDcsOb28Zr9QQmSFDQf1ygwMQI4GD1PQI5B0UAePo05RTN4K2UiVBiVDXsCXveT7G3iOtlB0b7K4MXLwpXBRMLRxCTJGs+C1iHfsejo8nb9BghKEvAbsCRGLHoyHjcPOjs7mTozOB00ei54J08fQBaTDJQCkvjZ7rTlad041lbQ7sshyQLIlsjWyq/O/tOa2k3i2Or582f92QYGEKcYeyBFJ9Ms/TCkM7Y0LzQUMnkufSlIIw4cBxR0C5gCufka8f/opOFD2wrWINKgz5zOGM8O0WvUFNng3qLlI+0n9W/9uQXIDVsVOhwxIhMnvCoTLQguly3FK6UoUSTtHqQYqxE3CoUC0fpU80vs6eVf4Nbbb9hD1l7VxdVy11XaVd5R4x/pkO9y9o39qQSSCxAS8xcPHT0hXyRhJjQn1iZNJaYi+h5oGhUVLQ/eCFsC2PuF9ZTvMuqG5bXh194D3ULcl9z+3Wjgv+Po58DsHvLZ98L9qwNnCckOqRPjF1cb7R2UH0Eg8x+vHoEcfhm+FWMRjwxpBxoCzfyq99jye+616qDnUuXb40LjieOs5J7mTumj7IPwzPRc+Q/+vwJJB4kLYQ+yEmcVaxeyGDUZ9BjyFzsW3xPzEJAN0gnYBcIBsP3B+RP2wvLm75Tt2+vF6ljqlep36/Ps/O5+8WX0l/f6+nP+5gE6BVQIHQuBDXEP3hDBERYS3REbEdkPIw4KDKAJ+gYtBFIBf/7I+0P5AvcW9YvzavK78X/xtfFY8mHzxPR09mL4fPqx/O/+IgE7AysF4gZVCHsJTQrHCuoKtgowCmAJTwgHB5YFBwRqAssAOP+9/WT8N/s++n/5/Pi3+LD44/hL+eP5o/qD+3j8e/2B/oH/cwBQARICswIxA4kDvAPKA7YDgwM3A9YCZwLvAXUB/QCPAC0A3f+e/3T/Xv9c/2z/iv+0/+X/FwBIAHMAkgCjAKMAjwBmACkA2v96/wz/lv4b/qP9M/3Q/IL8Tfw2/EH8cfzG/EH94P2f/nr/agBpAW8CcwNqBEsFDgaqBhcHTgdMBwwHjgbUBd8EtwNhAugAV/+5/Rv8i/oW+cv3tPbf9VP1GPUz9ab1cfaQ9/34rvqa/LD+4gAfA1UFcgdlCRoLhQyVDUEOgQ5ODqkNkgwPCyoJ8AZwBL0B6/4P/EH5l/Yn9AbySPD77i7u6e0y7grvbPBR8qz0bveC+tH9QgG8BCMIWgtIDtMQ5xJvFF4VqRVLFUMUlxJREIANOAqRBqYClv5/+oH2vfJR71rs8eks6BvnyeY753PoaOoO7VPwIPRZ+N78jAFABtUKJQ8PE3EWLxkyG2ccwRw7HNUamRiUFdsRig3BCKIDWP4I+d3zAO+Z6szmt+N34R7gvN9U4ObhaeTM5/bryfAi9tj7vwGqB2oN0hK3F+8bWh/YIVUjwiMYI1ohkh7UGjkW5RD+CrEEMf6s91fxZOsD5l/hnt3h2j/ZyNiC2Wvbdt6P4pjnbO3f88D62wH4COEPXRY7HEkhYCVcKCQqpirdKcsnfiQMIJYaRRRHDdIFIP5r9vDu6ueR4RjcrNdx1IPS9NHL0gXVk9hc3T3jCuqR8Zj54AEqCjYSxBmYIHsmPiu4Ls0waDGEMCQuVyo4Je4epheZDwIHJv5H9avsl+RJ3fzW5NErzu/LRcs1zLvOxtI42OreqeY872D4zwFAC2oUBR3LJIEr7jDnNEo3AjgHN140FzBTKjwjBhvxEUEIQv5A9Inqa+Es2Q/STMwUyInFwcTGxZLIE80n06LaS+Ph7Bv3qAE5DHoWHCDRKFUwbDbkOpc9bz5hPXQ6uzVZL30nYh5NFI0JdP5W84zoad4+1VPN6cYywla/br6Dv5DCgMcuzmnW89+E6sn1bAEUDWUYByOmLPY0tDuqQK5DqESMQ2FAPDtENKwrtSGrFuQKuv6J8rPmlNuC0c7IvsGJvFy5ULhyubq8EsJSyUXSptwm6G30HAHSDSsaxiVIMF85wkA0RotJqUqCSR9GlkAQOcUv/SQIGUQME//a8QHl7Nj7zYLEz7wet5+zbrKYsxW3zryXxDfOZdnL5QnzuQByDskbVii1M409kUV/SydPbFA/T6lLw0W4PcUzNShhG6wNgP9J8XbjddaqynPAIbj2sSSuy6z5raaxuLcCwEbKNdZ0457xRAD1DkAdtSrpNn1BHUqFUH9U7FW+VPxQwEo5Qqc3XCu0HRkP/v/U8BPiLtSTx6O8trMTrfCobqecqHKs1rKXu3TGGdMm4S7wvv9cD5Ae4izjOSxFZE5CVY9ZJlv5WRBWh0+NRmg7bC79H4oQiwB88NjgGtK2xBW5k697qAakWaKEo36nLK5at8XCFNDi3rzuKP+mD7cf3S6hPJhIY1K0WVFeFGDtXuNaE1SxSgQ/ZDE7Iv0RKAFA8MXfOdAXwsy1uqsxpGyfk522ns6ivalQsz6/Ks2s3ErthP7UD7UgozAhP75LFVbWXcNismSUY29fYlihTnZCPzRqJG8T0wEf8Nrejc62v8qyL6g3oCSbHpk2mmaekKV9r+G7XsqF2tnr0/3oD4whNjJjQZxOelmmYeBm/WjrZ7FjblxYUrxF+zaHJt4UigIY8BjeFc2VvRCw8qSSnDKX/pQJlkuap6Hjq7O4tMdy2GzqF/3hDzoikzNkQzBRjVwgZaVq8Wzua6RnM2DSVdFIlDmQKEkWSwMs8H3d0su0u6GtCKJEmZqTN5ExkoCWBp6IqLe1LcV01gXpUfzCD8EiuzQkRXpTTl9CaBBuinCab0ZrrmMNWbNLBzyCKqwXFQRX8ArdxMoVun6rcZ9Oll2QzY2zjgqTsZpvpfCyzsKO1Kbng/uKDyEjrzWiRndVumEKax5xxXPqcpFu3GYFXF5OUj5bLAUZ5gSa8L3c7Mm4uKepMJ20k3+NwYqRi+qPq5eaomKwmcDD0lLmsPo8D1sjbTbeRydX0GN2bcxzoXbddYRxuWm2Xs9QcEAXLlMavAXy8JfcSMmctx6oRZt4kQGLFojOiCSN+JQNoA+ukr4W0Qvl2PnaDm8j9jbYSIpYj2WEbxh2GXlveBx0QmwdYQNTYEK1L5MblQZf8ZXc2cjDtuOmspmZj+eI0IVthruKmZLLnfururyIz9Pj/vhjDl4jTDeQSZ1Z9mYycQF4LnueelZ2dW45Y/hUH0QyMcMccAff8bfcncgttvald5gajjCH74NwhLKIk5DXmyeqFbsdzqziI/jaDSsjbjcGSmNaBWiBcoV523xofC94T3AGZapWqkWLMuAdSghw8vzclMjXtVillZf8jN+FdILZggmH5o4ympeopLnWzJnhSvdBDdUiXjc7Stpaumhvc6R6In7MfaZ5znGCZhhYAEe/M+keIQkR82LdvcjDtQelDJc/jPOEYoGpgcSFlY3fmEynari3y5vgdPaZDGAiHTcwSgRbF2n8c1x7/37Ifrl68HKrZz9ZHUjKNNwf9Qm/8+fdFsnutQSl25bii26EuoDhgOOEoozgl0imarfAyrTfpPXlC8shrDblSeFaHGkodK57c39cf2d7tXN/aB5aAEmsNbYgwQp69IrenslYtk2lA5fni1CEeoCCgGiEDYw3l46lpLb0yefe2/QlCxkhDDZcSXJayWjzc5h7fn+Gf7B7GXT9aLNaqEliNnYhhgs/9UrfVMoAt+KlgZdLjJmEpICNgFKE2Ivklh+lG7ZUyTXeG/RcCkwgQDWWSLhZIGhecx17H39Gf5J7HnQlafxaEkrqNhkiQQwL9iTgNsvjt8GmVZgQjUeFOIEBgaSEBIzplvyk0LXjyKDdZ/OMCWUfSTSWR7RYIWdrcjx6V36efg17wXP0aPlaPUpDN54i7wzf9hfhQcwAueinfpkyjlqGNILegVyFkYxGlyalxbWiyCvdv/K2CGceKjNcRmlXzmUacfd4J32MfSF6BHNraKhaKUpsNwQjkA229yDidc1Wulap+pqxj9GHmIMlg3uGf437l52l+rWSyNXcJvLdB1Qd4zHrRNlVKWRtb053kHsRfNB45nGJZwpa00ljN0kjIQ6Q+D3jzs7huwirx5yLkaqJYoXShP+Hzo4KmWOmcLa0yKLcnfECBy0ceDBGQwVUNWJnbUV1k3kwehl3Z3BOZh1ZPUknN2sjoQ5r+W3kS9Cgvf2s456+k+SLkYfnhuiJfJBxmnanKLcKyZHcJvEoBvUa6i5uQfFR818Ia9xyMnfqd/90iG67ZOJXZEi4NmkjDg9E+q3l6dGQvzGvSqFHlnyOI4pfiTSMipIwnNmoIriTyaXcxPBQBa4ZPS1nP55PZl1VaBZwb3Q/dYFyTGzQYllWSEcUNkMjZg8a+/vmpdOuwaKx+6MkmW+RFo07jOKO9pRGnomqXrlRyt/cdvB9BFoYcisyPRBNkVpPZfZsTXEzcqNvsmmPYIJU60U8NfYiqQ/r+1ToftX5w02086ZSnLqUZpB2j/CRvpeyoIas3LpFyz/dPvCvA/sWjCnTOklKeFf6YYBpz23JbmZsvGb4XV9STEQuNIMi1A+1/LfpcNdsxi+3LqrNn1yYEpQPk1uV4Jpzo9CunLxtzMbdH/DpApQVjidMOE1HHVRZXrVl92kCa85obmMOW/BPa0LrMugh6A92/SLredkFyUS6qK2So0+cFZgDlyCZWp6GpmSxnb7KzXTeGPAtAicUeyWiNR9Eg1BwWpphymXiZtxkyV/RVzZNSkBzMSYh4Q8t/pHsltvBy4q9X7Gep5GgbJxOmz2dKqLrqUK038Bdz0vfLPB8AbYSVCPWMsJAsExDVjJdSmFtYpRgz1tGVDRK6T3HLzsgwA/Y/gPuxd2czvzAT7Xtqx2lE6Hsn6+hTKadrWi3X8Mj0UngWvDYAEQRHiHsLzs9pkjUUYJYfFynXfpbhVdtUOtGSjvmLSgfhA91/3bvA+CU0ZjEc7l5sPCpB6bapHGmvqqcsdS6HcYe03DhpPBCANIP2h7nLIw5aUQqTY5TZFeSWBBX7VJKTF1DbTjSK+0dLA8CAOfwTOKk1FnIx71AtQSvQqsUqoGre6/jtYO+F8lL1cDiC/G8/2IOjBzLKbo1/j9ISFpOB1I1U9xRCk7fR40/VjWLKYoctw6AAFTyn+TL1zvMSMI9ule0wbCUr9mwgbRvunPCS8yq1zfkjvFH//cMNRqbJskxaTsyQ+tIaEySTWFM4kgxQ347BTIUJ/8aJg7tALzz+OYD2zvQ8MZqv+G5frZXtXW2zLk+v6HGuM862tXlLvLk/pML2hdaI7strjbuPUZDjkawR6RGd0NCPjI3fi5sJE0Zdw1GARz1VelL3lTUvMvExJ+/dLxYu1K8Vr9MxArLWtP53Jvn7PKU/jcKfBUNIJcp0jGAOHA9fUCSQapAzj0XOa0ywiqXIXQXqgyMAXP2s+ue4YPYp9BFyozFn8KRwWnCHMWUyavPL9fk34bpx/NY/uUIHxO1HF4l2SztMm43Ojo/O3c67De0M/Et1CaVHncVwAu+Ab/3D+765MTcrdXpz6LL+cj+x7bIGcsSz3/UNdv74pbrwPQx/qAHxBBXGRYhyCc6LUUxyzO7NBE01TEcLgQptyJpG1UTuQraAf74Z/Ba6BLhyNqp1dzRfM+YzjPPSNHC1IXZaN885srt1vUg/mgGbw72FcMcpCJtJ/sqNS0MLn0tjytUKOgjbx4WGBARlQngAS76ufK762rl9N+C2zXYI9Za1dzVpNeg2rfexeOj6R/wCPcl/kAFIQyUEmgYcR2KIZUkfiY4J8EmHyViIqEe/RmcFKkOVAjPAU/7AvUb78fpLOVu4abe6Nw+3KvcKN6m4BHkSegu7ZbyVvhB/igE3gk3DwoUNBiXGxoerB9EIOIfiR5JHDQZZxUAESMM+AaoAV78P/d28iXubOpn5yvlxeM/45njzuTR5o/p8ezb8Cv1wPl0/iIDpwfgC60P8hKYFY0XxRg3GeUY1BcPFqYTrxBDDX8JgQVqAVr9b/nI9YDyr+9p7b3rtepX6qLqkesZ7S3vuPGm9N33RPu+/i8CfgWSCFQLrw2UD/YQzhEXEtIRBRG4D/oN2QtpCb8G8QMVAUP+kPsQ+db28fRu81fysvF/8b/xa/J78+b0m/aO+Kv64fwe/1ABZgNSBQMHcAiPCVoKzQroCq0KIQpMCTUI6gZ1BeUDRwKpABj/n/1J/CH7LPpy+fT4tPiy+On4Vvny+bX6lvuN/JH9l/6W/4YAYQEgAr8COgOPA78DygOzA34DMAPNAl0C5QFqAfQAhgAmANf/mv9x/13/Xf9u/43/uP/p/xsATAB2AJQApACiAIwAYgAjANP/cf8D/4v+Ef6Z/Sr9yfx9/Er8NvxE/Hf8z/xN/e79sP6N/38AfwGFAogDfQRdBR0GtQYdB1AHSQcEB4EGwgXJBJwDQwLIADX/lv35+2r6+fix96D20PVK9Rb1OfWz9YX2q/ce+dX6xfze/hEBTwOEBZ4HjAk8C58MqA1LDoEORQ6WDXUM6gr+CL0GOASBAa7+0/sG+WD29vPd8Sfw5e4j7urtP+4i74/wf/Lj9Kz3xvoa/o0BBgVpCJsLgg4EEQ0TiRRrFagVOxUlFGwSGhA+De0JPwZQAj7+KPou9nDyDe8h7MXpDugM58vmTueV6JnqTu2f8Hf0t/hB/fEBpAY0C30PXROyFmIZVBt3HL4cJRyuGmAYSxWFESgNVggzA+b9l/hx853uQuqC5n/jUeEN4L/fbOAT4qnkHehX7DfxmfZV/D4CJwjiDUATGBhBHJgfAiJpI74j/SIpIUseehrOFWwQewooBKX9IvfT8OvqmOUG4Vrds9oq2czYn9mh28Pe8eIN6PDtbvRX+3MCjglwEOEWrxyrIasljig7KqIqvSmRJyokoR8XGrUTrAwvBXv9yfVV7lznE+Gv21vXO9Rp0vjR7dJE1e3Yz93G46XqOPJH+pEC2QrdEl4aICHsJpUr8i7oMGQxYDDgLfYpvSRcHgEX5g5HBmj9jPT56/LjuNyD1ofR7M3Ry0rLXMwDzy3Tu9iF31nn+u8n+ZkCBwwoFbMdZiUCLFExKjVqN/433zYSNKovyCmXIkwaJxFuB2z9bfPA6bHgiNiG0ePLzcdnxcXE8cXiyIbNutNQ2xDktu3694oCGA1PF98gfinmMNw2Lzu8PWs+NT0gOkI1vy7GJpMdbROiCIX9a/Ks55vdiNS7zHPG4sEvv3K+sb/owv7H0M4p18zgbuu/9mYCCg5QGeAjZS2WNTA8/kDXQ6VEXEMGQLg6mzPjKtMgthXjCbT9iPG+5bHautAnyDzBMbwwuVO4o7kYvZvCAcoV05HdJul59SwC3g4rG7ImGTEOOklBkUa5SaZKUEm9RQhAWjjtLggk/xctC/j9w/D34/bXIc3Mw0G8vrZus3CyzLN6t2C9VMUYz2Pa3uYq9N8BlA/eHFUplzRLPiRG40taT2pQCk9CSyxF9jzdMi8nRBqADE/+HPBX4mzVv8muv4e3jbHvrcysL64RslS4y8A1y0TXm+TT8n4BLBBpHscr3DdJQrxK8lC3VO1Vh1SOUB9KakGxNkQqhBzaDbn+k+/h4BPTmMbQuxGzoqy1qG2n1KjirHqza7xxxzjUX+J38QwBphDLHwYu5joGRg9PuFXLWShbwFmeVd5OtEVkOkUtvB45DzT/KO+T3+7QrMM1uOOuAqjHo1aivaPzp9iuObjQw0PRLOAX8IgAAxEFIREwsz1/SRhTMlqTXhhgs15sWmNTzUnzPS4w6SCaEL//2u5u3v3O/cDftACrr6Mnn46d8J5Ho3GqObRVwGfOBd617vb/QhEUIugxQkCyTNVWXF4KY7hkWWP1XqtXtE1aQfwyCSP8EVgAqO5z3UDNjr7QsWqnrp/bmhaZcZrjnkmmbrADvajL7dtU7Vb/ZhH7IoozkUKcT0NaM2IsZwVpsGczY7FbYlGVRKs1GCVcE/8Aku6h3LrLX7wLrySkAZzklvSURJbKmmai3azfuQrJ59n166n+bxG4I/U0n0Q8UmBdtWX2avxss2skZ3Ff1VShRzk4FSe4FLIBl+7422nKcrqQrDChrJhGkyuRbZICl8qeiKnsto7G9deb6vH9XRFNJCs2bEaQVCpg3mhmbpdwXm/DauhiClh6SqI6+ygPFm8Cte5420/Jx7hiqpGesJUFkL6N7o6Nk3mbdaYttDjEGtZJ6S/9MxG5JCo39UeXVp9irGt5cdVzr3INbhJm/FoeTeM8yipdFzQD7O4g22vIX7eCqEecD5Mija+Ky4tvkHaYpaOmsQzCWdT/52f88BD+JPM3O0lRWL1kHm4rdLR2o3X/cO1oqF2IT/o+fiyiGAAEOu/u2r3HO7bwplWazJCgigKICImqjcWVHaFZrwvAs9LB5pj7lxAcJYY4Pkq7WYNmMnB8di95NniWc3RrDGC3UeRAFC7ZGdAEnu/k2kXHWbWtpbuY6I6BiLmFpYZBi2mT3p5IrTm+LdGQ5cb6KRAUJeQ4/krWWvBn5nFpeEZ7Z3rQdaVtJWKoU55Ciy8CG6QFFvD+2gHHu7S6pHqXZI3GhtSDp4Q3iWOR7Jx4q5i8x89w5PL5pw/oJA05e0uiWwRpOXPxefd8M3yqd39v8GNXVSVE3zAaHHgGoPA82/LGX7QWpJOWQYxxhVeCDYOOh7aPSJvqqSq7hM5h4x75FA+YJAM5tksfXL9pLHQTe0B+mX0ief5wa2XEVnhFDzIfHUsHPPGd2xXHRrTAowWWgIuChEOB24FHhmWO9pmgqPO5Z81m4kz4cA4mJMY4r0tNXCBqvHTPeyB/l343eiFylGbqV5RGGTMQHhsI5/Ef3GvHbbS5o9GVIIv6g5eAEYFkhXCN9pidp/O4ccyB4X73vg2VI1g4Z0stXChq63QjfJd/LX/neudyamfKWHhH+jPpHucIoPLA3PHH1bQApPWVIYvZg1WAr4DnhNqMS5jipiy4pcu04Lb2/wzkIro34ErAW9hpuXQRfKV/Wn8ye05z6mdgWSFIsTSpH6wJZfN/3abIe7WTpHGWhIsfhHyAt4DPhKOM9pdwpqG3BMsB4PX1NQwXIu82G0oHWzBpJ3SYe0h/HX8Xe1VzFGitWY1IPDVPIGgKM/Ra3ojJXrZxpUWXRozLhA2BKYEdhcuM95dKplO3kMpp3z71YwsvIfc1GkkEWjFoNXO5eoN+d36Vevxy52etWb1ImTXYIBoLCfVP35XKfLeZpm6YaI3dhQeCBILShVSNUJhvpkO3Ssrv3pL0igouINU030e4WN9m5HF1eVV9aH2teUNyY2diWa1IxzVCIb8L5fVc4MzL1LgIqOqZ545Th2mDR4Pthj6OAZnhpnK3NMqU3vPzrAkWH4oza0YmVzllOHDNd7978XtgeClxhmbJWF5IxDWOIVYMxfZ+4SnNY7q9qbmbwZAriTKF8oRtiIiPCZqgp+K3T8pZ3mTzygjpHRoywURPVUJjMG7EdcR5EnqtdrBvUWXjV85HkDW3Id4Mp/e14qzOJ7y2q9ed9ZJli1+HA4dSijGRaputqJK4nMpA3uXy6AepHIYw5EI2U/1g0Gtbc2V3z3eXdNdtxWOwVv5GKjW/IVQNifj941HQHb7vrUKggJX8jfCJeYmZjDmTIp0HqoK5HMtK3njyBwdZG9Au1UDdUG1eGmmVcKN0J3UecqBr4mEwVe1FkTSjIbcNaflV5RbSQ8BmsPeiYJjwkOGMUYxDj56VMJ+tq7W6z8t53h/yKAb7GfwsmD5JTpNbEmZ0bYJxHnJFbw1pqV9iU5pEwzNiIQYORvq55vnTlsIYs/SlkZs9lDGQio9Lkl+Yk6GhrSi8t8zM3tvxTgWQGAsrMDx6S3NYuWL8aQVut24NbB9mG11JUQZDwjL8ID8OHfsp6PfVFMUCtjWpEZ/hl9yTIJOxlXqbS6Tfr9y90s1F367xewQcFwEpnzl1SBFVE18vZi1q82p6aNhiOlrlTjJBjTFwIGAO7Pug6QzYuMchubes26LWm9+XEZdymeyeVadostC/Ic/l35jxrwOhFeEm6DY9RXBRJVsRYgBm1maNZDpfCFc4TB8/JDC9H2oOs/wf6zjagMpxvHew7aYboDacWZuKnbSir6o6tQPCpNCr4Jvx7gIhFKwkEDTWQZRN8VamXYBhY2JLYElbh1NCScw8hy7jHloObv2h7HXcac3vv2+0QaurpN6g9Z/2oc6mV65TuHTEW9KZ4bjxOQKdEmYiGDFCPoBJfFLyWLFcn122WwdXuU8GRjw6tyziHTAOHf4l7sPeb9CXw5241a+CqdOl4aSzpjirSrKxuyPHRNSu4u/xkAEZEREgBC6HOjlFyk35U5hXjFjRVndSoUuGQm83tCq5HOsNv/6p7x7hj9Nlx/y8pLScrg+rGaq9q+2vhrZTvw3KYNbq40Ly9gCWD7Ed2CqnNsNA4EjATjlSMFOjUZ1NQkfFPmk0gChpG4sNUf8q8YPjxtZWy4nBqbnzs5CwmK8Qseq0B7s0wzDNrNhN5bDybAAXDkgblyemMiI8wUNMSZhMkE0tTH1IoELEOikxHCbzGQ4N0/+m8u/lEdplzz7G4L6DuU+2WbWntiy6yr9Tx4vQKNvX5jvz9P+eDNgYRCSJLlo3cz6gQ7tGr0d1RhtDvT2HNrMtiCNWGHUMQQAc9GHoa92P0xfLRMRIv0i8Wbt+vK2/y8StyxvU092H6OPzjv8sC2YW4yBUKnAy+zjEPadAkkGAQHs9njgSMgoqxyCTFr8LngCJ9dTq0eDP1xDQ0Mk8xXbCkcGQwmvFBso+0N7XquBc6qf0O//ECfMTeB0KJmktXTO6N2E6QDtSOqI3RzNmLS4m2h2sFOwK5wDs9kbtQeQh3CTVfs9Zy9PI/MfZyF/LeM8D1dHbrONV7Ij1/P5nCIIRBRqwIUkony2KMe4zvDTxM5QxvC2JKCUixBqhEv0JHAFD+LXvtueC4E7aS9Wb0VrPls5Sz4XRHNX42fHf1uZx7oX20v4XBxUPjhZKHRUjxSc4K1QtDi5hLVcrASh9I+8dhhd0EPIIOwGM+R/yLevs5IvfMNv81wXWWNX21djX7doZ3zvkKOqv8J73vv7VBbAMFxPcGNId1iHJJJkmOiepJu8kGyJGHpEZIhQlDssHRAHF+n/0o+5d6dTkKeF33s/cPdzA3FPe5+Bj5Kzone0O89P4wP6kBFQKow9qFIUY1RtFHsIfRiDOH2IeDxzqGA4VnBC3C4gGNwHu+9b2FfLP7SXqMOcF5bLjPuOr4/HkBOfR6UDtM/GL9SP62f6EAwQINQz4DzETyRWvF9YYOBnWGLUX4RVsE2oQ9gwsCSsFEwEF/R75fvVA8nnvP+2h66fqV+qw6qzrQO1f7/Px6PQl+I77CP93AsMF0QiKC9wNtw8OEdkRFhLGEe4Qlw/QDagLMgmEBrQD2AAI/lj73fiq9s30U/NF8qnxgPHJ8X7ylvMH9cP2ufjZ+hH9Tv9+AZEDeAUlB4sIpAlnCtMK5wqlChIKNwkcCMwGVQXDAyQChgD3/oH9L/wK+xr6Zfns+LL4tPjw+GH5AfrG+qr7o/yn/az+q/+ZAHIBLwLLAkIDlAPBA8kDrwN4AygDxAJTAtoBYAHqAH4AHgDR/5b/b/9d/17/cP+R/7z/7f8fAFAAeQCWAKQAoQCJAF0AHQDL/2j/+f6B/gf+kP0h/cL8d/xH/Db8R/x9/Nj8Wf39/cL+of+UAJUBmwKdA5EEbgUrBr8GJAdSB0UH+wZzBq8FsQSBAyUCpwAT/3P91/tK+tz4mPeM9sL1Q/UW9UD1wvWb9sf3QPn9+vD8DP9BAX4DsgXJB7IJXAu5DLkNVA6ADjsOgg1YDMUK0QiKBgAERgFx/pb7zPgq9sbztPEI8NDuGe7s7UzuO++08K3yG/Xs9wv7Y/7XAU8FsAjdC7wONREyE6IUdhWlFSoVBxRAEuIP+wyiCe0F+gHn/dL52/Uk8sru6eua6fLnAOfO5mLnuejN6o/t7fDO9Bb5pP1VAgcHkwvUD6kT8haTGXQbhRy6HA4chBolGAEVLRHFDOsHwgJ0/Sf4B/M77uvpO+ZI4y3h/d/D34bgQeLr5HDoueyl8RH30vy8AqMIWA6tE3gYkBzVHyoieiO5I+Ei9SADHh4aYhXyD/cJngMZ/Zn2UfBz6i7lruAX3YfaFtnS2L/Z2dsT31bjg+h17v707fsLAyQK/hBkFyIdCiL0Jb4oUCqcKpspVCfUIzQflxklEw8MjATW/Cb1u+3O5pfgSNsM1wfUUtL/0RLThtVK2UTeUORA6+Dy9vpDA4gLgxP2GqYhXCfqKyovATFdMTkwmi2TKUAkxx1bFjIOiwWq/NHzR+tP4yncDNYs0bDNtstRy4XMTc+W00DZI+AK6Lrw7/ljA84M5RVhHv4lgCyyMWo1hzf3N7M2wzM7Lzsp8CGRGVwQmgaV/Jry+Oj53+fX/9B8y4nHSMXNxB7GNcn7zU/UANzW5Izu2fhtA/YNIhiiISkqdDFJN3c73T1kPgU9yTnHNCIuDCbDHIwStweX/ILxzebP3NTTJcwAxpbBDL95vuO/QsN/yHPP69em4VrstvdfA/8OORq2JCIuMzapPE5B/UOeRClDpz8yOvAyGSrvH8AU4Qiv/IjwyuTR2fTPgse9wN27CblauNi5er0nw7PK6NN/3ibqhvY9A+oPKRycJ+gxujrOQelG4kmgShlJWEV3P6E3ES4RI/MWFgrd/K3v7eID10rMGMO3u2G2QrN2sgS04rf3vRPG+89j2/PnTPUFA7UQ8R1SKnY1Bj+0RkRMiE9lUNFO1kqRRDA88jEmJiUZVAsf/fHuOuFl1NjI7L7ytiixvq3RrGqugLL0uJfBKMxW2MPlCfS5AmERkB/WLMw4EkNYS1tR6lToVUtUHFB7SZhAtzUrKVMbmgx0/VTusN/70aDFALtxsjWsgKhwpxGpVq0jtEO9csha1ZnjwPJaAu8RBSEnL+Y73Ua1TylWA1olW4NZJ1UxTtZEXDkcLHkd5g3c/dXtUN7Ez6TCWLc4ro2njaNZovyjbKiIrxy53sR00nfhcvHpAV4SUSJEMcI+Y0rJU6pa0F4XYHNe8FmvUuZI3jz2LpYfNg9V/nXtGt3Czee/9bNKqjOj6J6OnTCfxKMpqya1b8Gnz2DfIfBoAbASciMqM2BBok2QV9xeS2O5ZBljdV7wVsJMOUC2MaYhhxDe/jLtDtz2y2q92rCqpiqfl5oVmbKaZJ8Ip2SxKb71zFfd0O7YAOQSaCTbNL1DmFAIW7ticmcIaW9nsGLwWmhQakNYNKcj2BF2/w3tLdthyi67Ca5ao3abm5bxlIaWT5sqo9utD7tiyl7bgO05APwSNCVVNtdFQ1MvXkRmQmsAbXFrnmarXtRTbEbaNpclJxMZAAPtddoDyTS5hKtdoBmY+ZIlka6SiZeTn46qJbjyx3nZM+yQ//gS1iWXN7BHolUBYXRptm6fcB1vO2odYgFXPUk5OXIncRTJABTt6Nndx363TKm2nRaVs4+1jS+PFpRGnICnbrWmxanX7Orb/toSTyaiOERJs1d+Y0lszXHfc25yg21DZe5Z2UtyOzYptBWCAT7thNntxgu2Yqdkm3CSy4ykigyM+ZBHmbak7rKBw/HVreke/qMSnyZ2OZRKdVmkZcFuhHTAdmJ1dHAaaJVcPU6BPeEq7xZEAoLtSNk1xt20yKVrmSeQRYr0h0eJNY6ZljGiprCIwVTUeOhZ/VQSxyYSOqBL6FpxZ9pw2XY+efd3CnOfavZeZ1BkP3AsHhgLA9ztNNm0xfOzfaTKlz2OIoioheSGzYs+lPafm668v9TST+eP/O4RyCZ5OmhMClzlaJNyynhYeyl6RHXPbAxhVFIZQeEtQBnXA03uRtloxU6zg6ODlrSMY4bBg+SEw4k5kgaezqwfvnPRNObC+3MRoiapOuxM3Fz+aexzVnoMffd7HneobtViAFSdQjEvUxqlBNHuftlTxeyy2aKWlY2LCoVBgkmDGYiNkGScQqu1vDTQKuXz+uUQWCalOixNXl2+auJ0fHtYfl99mHgncE9ka1XtQ14wVBt0BWjv2tlxxc2yfqIElceKGIQqgRSC0YY7jxKb+ql/uxrPMuQl+kYQ6yVsOilNkV0ja3d1O3w7f19+rnlLcXllkVYIRWUxQhxCBhDwWNrDxfGydKLMlGSKjIN7gEiB7IVFjhKa9qh/uiXOT+NZ+ZYPXCUBOuVMdF0va6l1kny1f/d+YHoTck9mcVfrRUYyGh0MB8fw99pGxlWzt6LtlGKKaYM2gOSAbYWtjWWZOqi4uVnNguKR+NgOrSRmOWBMCl3hanp1gnzFfyd/rXp8ctJmCViVRv4y2x3RB4vxttv6xvqzSaNolcOKrINbgOmAUoVzjQ2ZxqcrubbMzuHP9w4O4COaOJxLUlw6aul0DHxrf+1+lXqGcv9mWFgFR4szgx6PCFvykdzdx920JqQ6loOLVoTqgFiBnYWZjQuZnKfauD/MNOEW9zoN9iKhN5tKT1s9afhzLnuofkl+F3oxctVmXVg4R+wzDx9ECTTzid3syP21TqVil6SMZoXhgTCCT4YejmCZvafGuPXLteBm9l0M8iF9Nl5JAlrqZ6ly7Hl8fT19Mnl8cVVmFlgtRx80fx/uCRT0md4lyle3v6bfmCKO24ZBg3CDZocDjwyaKqjvuNnLVODC9XoL1iAuNedHblhDZvxwRnjoe8l76XdncH5lg1flRiM00B+LCvr0wd+Iy+m4d6ivmv2Ps4gIhRiF4ohHkA6b4qhXue3LE+Ar9ZIKox+5MzlGk1ZKZPNuPXbvee55O3bzbk9kpFZdRvczAiAbC+P1/+AQzbK6c6rQnDKS7IozhyaHworrkWic6Kn/uTLM8d+k9KgJXB4eMlZEdlQCYpJs1HORd613KXQgbcpieVWVRZkzEyCaC872T+K8zq+8saw+n7+UhI3DiZiJBY3tkxmeOavnuqjM8d8t9L0IAx1hMEFCGFJuX9ppDnHRdAl1tXHvau9gAlSNRAozAiAIDLj3sOOK0Ny+Lq/4oaGXeJCzjG6MqY9Llh+g16wPvFDNFODJ89MHmhuDLvw/fU+PXM5m7G2xcQNy4W5jaL5ePlJFQ0kyzR9iDKD4H+V30jjB57H7pNaaxpMCkKOPrZIFmXqiwK53vSvOW+B48+0GJBqILIo9p0xqWXJjcmo0bp5urmt8ZTlcL1C9QVQxdB+oDIT5m+aA1L/D2bRCqFmea5eskzeTDpYZnCil9LAevznPxuA98wwGoxhyKu86mUkCVshfo2Zeat1qIGg8YmJZ1032Py0w9h7ZDGL6Ieii1m7GAbjLqymiY5uulyWXyZmEnyiocbMFwXrQV+EY8zIFGhdEKCw4WEZZUtVbgmIwZsNmOWSnXjpWNUvwPdIuUx7yDDj7runb2ELJXLuSr0Cmq58GnGqb251Eo3irNrYqw+7RDeIK82AEihUBJkc15UJ0TptXFF6wYVNi/F++WsNSTEisO0UtiR3zDAX8QOso2zjM5b6Ts5uqPqSuoASgQqJVpxWvQrmNxZTT6uIW85kD9hOrI0EyRj9XSiBTXVnhXJFdbFuEVgBPHkUrOYYrmhzbDMb81eyG3U3PmcLLtzavGamjpe2k+aa2q/2yk7wsyGzV7eM6894CYBJGIR4vfjsGRmZOYFTGV4JYjlb9UfRKrEFvNpUphBupDHv9a+7y333SdcY1vAy0N67hqiKq/qtjsC23JsAFy3bXFuV58zACyhDUHuIrkDeEQXRJIk9mUihTZVEsTaFG+T15M3MnSBpdDCH+APBp4sTVdMrNwBq5k7NjsJ+vS7FXtaK7+MMYzrDZZebT85IBNw9YHJAogTPXPExEqEnETIlN9EsVSAtCBzpLMCIl5hj1C7j+kfHp5CDZks6OxVq+Krkktl+13baQulnACMhh0Rjc2udJ9AMBqA3VGSslVS8DOPU+90PlRqpHQka8QjU92jXnLKIiXhdyCz3/HPNu543cy9J1ysfD9L4gvF27rrwIwE3FUszf1K/edOna9IYAIQxOF7ghDysMM3M5FD7OQI9BUkAlPSI4dDFPKfYfsRXTCrH/oPT26QbgHNd7z13J78RQwpTBu8K8xXzK09CP2HHhMuuH9RwAogrFFDketCb3LcozBDiFOj07KjpVN9gy2CyHJR4d4RMYChEAGvZ/7IrjgNue1BfPE8uxyP7H/siny+HPiNVv3F7kFe1Q9sb/LQk+ErIaSCLIKAEuzDEPNLs0zTNQMVotCyiQIR0a7RFBCV4AifcF7xTn89/X2e/UXdE7z5fOcs/E0XjVbdp84HPnGu8194T/xQe6DyYX0B2FIxsocitxLQ0uQy0cK6wnECNuHfUW1w9OCJYA6viF8aDqcOQj3+Daxtfq1VjVEtYP2Dzbft+y5K7qQPE1+Fb/awY9DZkTThkyHh8i+ySyJjknjya9JNMh6h0kGacToQ1AB7gAPfr+8yzu9Oh85OXgSd643D3c2NyB3ijht+QP6QzuhvNR+T//IAXKCg8QyRTTGBIcbh7XH0UguR85HtMbnhi1FDgQSwsXBsUAf/ts9rTxe+3e6fnm4OSf4z/jvuMW5TnnFeqP7Yzx6/WH+j3/5gNhCIoMQxBvE/kVzxflGDcZxRiVF7MVMRMkEKgM2AjUBLsAsPzO+DX1//FE7xftheua6ljqvurI62ntku8v8iv1bPjX+1L/vwIGBg4JwAsJDtkPJBHkERUSuRHWEHYPpQ12C/sISQZ3A5sAzf0h+6v4f/ap9DjzNPKh8YLx1PGR8rLzKvXr9uX4CPtB/X3/qwG8A54FRQemCLcJdArYCuQKnAoDCiEJAQiuBjQFoQMCAmQA1/5j/RT89PoJ+lj55fiw+Lf4+Pht+RD62Pq++7j8vP3C/r//rACDAT0C1gJLA5oDwwPIA6wDcgMgA7sCSQLQAVYB4QB1ABcAy/+S/23/XP9f/3L/lP/A//L/JABUAHwAmAClAJ8AhgBZABcAxP9g/+/+d/79/Yb9Gf27/HL8Rfw2/Er8g/zh/GX9Df7T/rT/qQCrAbECsgOkBH8FOQbKBioHUwdBB/IGZQacBZoEZQMGAoYA8P5R/bX7Kvq/+ID3efa09Tz1FvVH9dD1sfbk92P5JPsc/Tv/cQGuA+AF9AfYCX0L0gzKDVwOfw4wDm0NOwyfCqMIVgbHAwoBNP5a+5L49PWW843x6e+87hDu7u1b7lXv2fDd8lT1LPhR+6z+IQKZBfYIHQz1DmQRVxO6FIEVoRUZFecTExKpD7gMVgmbBaQBj/17+Yn12PGH7rLrcOnW5/Tm0+Z3597oAevR7TvxJvV1+Qf+ugJqB/ELKxD1EzEXwxmTG5IctBz2G1oa6he1FNQQYgx/B1ICAv24953y2u2W6fTlEuMK4e7fyt+h4HHiLuXE6BztFPKJ90/9OwMgCc4OGRTWGN4cECBQIoojsiPCIsAguR3BGfQUdw9zCRQDjvwQ9s/v/OnG5Fjg1txe2gXZ2tjg2RPcZN+84/vo++6P9YT8pAO5CowR5heUHWgiOybsKGMqkyp3KRUnfCPGHhUZkxJzC+kDMfyF9CLtQuYc4OLav9bV0z7SCNI508nVqdm73tzk3euJ86b79QM2DCgUjRsqIsknPCxgLxcxUzEPMFItLSnAIzIdsxV9Dc8E7PsX85fqruKb25jV1NB3zZ7LW8uxzJrPAtTI2cLgveh68bj6LgSUDaEWDR+VJv0sETKnNaE37TeFNnIzyS6rKEch0xiRD8YFv/vI8THoQ99H13zQGMtIxyzF18RPxovJdM7m1LLcneVj77n5TwTUDvUYYiLRKgAysze8O/o9WT7SPG85STSDLVEl8RuqEcsGqfuY8PDlBNwj05PLkMVNwe2+g74YwKDDA8ka0K/YguJH7a34WQT0DyIbiiXdLs42Hj2bQR9Ek0TyQkY/qDlCMkwpCR/IE98HqvuI79fj89gxz+DGQsCMu+W4ZbgRuuC9tsNpy73Ubt8p65P3TQT1ECcdhCizMmM7T0I+RwhKlUrfSO9E4j7lNjQtGCLnFf4IwvuX7ubhEdZ2y2jCMLsIthqzgLJAtE+4kb7WxuHQZdwK6W/2KwTVEQMfTStTNr0/QEehTLNPW1CTTmZK8kNmOwUxGyUFGCgK7vvG7R7gYdPzxy6+YLbHsJKt2qyprvOymLlnwh3Nadnt5kD18wOWErYg5C25OddD70u/URlV31ULVKZP00jDP7o0DiggGloLMPwV7YHe5NCrxDW61LHNq0+oeadSqc+t0LQfvnbJf9bV5Ar0qAM3Ez4iRjDiPK9HV1CVVjZaHVtAWatUgE31Q1I47yo1HJMMhPyE7A7dnc6gwX+2ka0dp1ejYKI/pOqoPrADuu/FqNPE4s/ySgO5E5sjczLOP0JLdVQeWwdfEGAvXnBZ9lH6R8c7ui1BHtEN7PwR7Mfbi8zUvg+zmKm7oq6elJ12n0ek5asWto3C6dC94I/x2gIcFM0kajR6Qo5OR1hXX4djtGTTYvBdMFbNSxY/bDBCIBIPZP2+66var8pJvOiv7qWrnliaGZn5muufy6deslK/Rc7D3k3wWgJhFNMlKTbkRJBRyFs9Y7NnBWkoZydiKVpqTztCAjM1IlQQ6/2I67rZDMkAugytlqLwmliW85TNltmb86PdrkO8vsvY3AzvywGIFK4msTcMR0ZU+F7NZodrAG0qaxJm313NUjNFeTUXJJURgf5w6/XYoMf6t3yqkJ+Ml7GSJZH2kheYYaCXq2K5WMn+2sztLwGSFF4nADnwSK9W02EEagBvoHDVbqxpTGH0VftHzTfnJdISJP9z61rYbcY4tjqo35yDlGaPs413j6aUGZ2QqLS2Fsc52ZHshwCBFOMnFzqPSspYWGTfbBty43MncvNsb2TbWJBK/TmhJwoU0v+S6+rXcsW7tEemhprWkXuMn4pTjIqRHZrLpTq0+sSL113r1f9VFD4o9jrpS5VahWZdb9d0xnYcdeNvQ2d+W+5MBDxDKTsViADL66TXsMSDs6SkhZiHj/CJ7YeOiceOcpdLo/ixCMP21TDqGv8PFHAonDv+TA9cWWh8cTB3R3mxd3hyxWnaXRJP4T3KKmIWRgEc7IfXJsSRslKj3paYjcmHnoUph1+MGZUTofKvQsF91A/pWP6yE3koCjzOTTld02k7cyV5ZHvkebJ09GvtX/tQkD80LH0XCwKF7JHX08PksVGikZUKjAaGtIMnhVWKFZMmnyiuqr8i0/vnkv0/E1soQjxYThJe82qYdLV6Gn20e412zG21YaVSEEF/LYoY0wID7cLXt8N8saGhoJTeiqqEMoKLg6qIaZGFnZ+sQ77n0fXmyPy2EhcoQzyeTplet2uTdd57aX4dfQd4S28uYw1UXkKpLocZnQOV7RnY0MNYsUKhCZQVirSDF4FUgmGHF5AznFirD73P0AHm/fsbEq4nDzygTtBeIWwrdqB8Tn8gfh55cHBXZDNVd0OvL3MaaAQ67pTYHsR4sTOhzZOuiSaDZoCFgXuGII8zm1SqELzczx/lNPtuESInqDtfTrZeL2xgdvt8y3+7ftN5OHEvZRNWW0SPMEobMAXv7jHZn8TasXSh65Oqif+CH4AfgfmFho6EmpepSLsPz1LkbPqxEHUmDjvcTU5e5Gszdu183X/tfiJ6pHGzZa1WBkVIMQsc9gWz7+7ZUsV+sgOiZJQIikCDQYAigdyFSo4qmiGpubprzp3jqvnmD6clQzoZTZhdP2uldXl8hn+1fg16sXHjZf9WeEXXMbUctQaE8MvaNMZgs+CiNZXHiuiDzYCOgSSGbI4lmvSoZbrxzQDj7vgQD7wkSTkXTJVcQmq1dJ57xX4VfpJ5X3G+ZQdXr0U8MkUdbQdf8cTbRceBtAmkXZbmi/aEwoFjgtKG7Y51mhCpTLqizX3iOvgwDrUjIjjYSkdb72hnc116nH0MfbF4rnBCZcZWqkV0MrodHAhE8tncgsjdtXul2pdkjWqGIIOgg+WHzo8cm3epcLqBzRfikfdHDZQi0DZfSbFZR2e6cbd4C3ybe2x3nm9wZDlWZ0V/MhIewAgv8wbe6clztzWnrJk/j0CI5IREhV2JDZEZnCqq0bqOzc7h8/ZZDFshVTWtR9NXTWWxb692E3rDecJ1MG5IY2FV50RaMkseVwkg9Erfd8tBuTWpz5t1kXmKDodPhzmLq5JsnSercbvKzaThY/ZnCw0gtDPERbJVAmNObUd0t3eGd7RzY2zKYT5UKEQGMmUe3wkT9aLgKs1Du3erQJ4ElBGNnIm/iXeNp5QVn3CsT7w2zprh4/VyCqse7zGoQ09TamCUaoBx+XTldEVxOWr2X89SKkOBMV8eVwoI9g3iAc94vfqt/qDplgaQi4yRjBaQ/5YToQWubb3UzrLhc/V+CTgdCDBcQa1Qh12GZ11u2nHicXZus2fOXRVR7UHLMDYevgr89ofj99Dcv7qwBqQgmlWT2I/DjxWTspllo+Ovyb6jz+zhFvWLCLcbAi7hPtBNXFomZOJqXm6Abklr02RSWxFPcUDjL+odEQvt9w/lC9NtwrWzU6eonfyWgpNTk3CWvpwKpgyyZcCj0EnizfSdByka4Ss7PLpK7VZ4YBFniGrDasFnnGGFWMRMtj7KLnodUAvZ+KLmOtUnxea246p7ofaahJc+lyWaIaAAqX60PsLW0cvimfS0BpEYpiltOW5HPVN/XO9iW2arZt9jDl5nVS9Kvjx+LecceQu++T7ogNcHyEq6sq6YpUCf25uBmzKe2KNFrDa3VcQ603Hje/TSBfIWVCd7NvFDUE9AWH5e22E+YqhfLVr7UVNHiDoBLC4ciwuc+uDp3NkLy969vLL5qdejg6AXoJOi4afXrzW6qcbQ1DzkdPT5BE0V7yRoM0dAKku+U8NZC11/XR5b/FVETjJEFzhSKlAbhgtv+4frStwuzp/B/baarrWoeaX+pESnOay0s3i9OMmX1i3lh/QsBKUTeSI2MHI8z0b+TsJU8FdyWEZWflFDSs5AazVzKE0aZws2/C/tx95t0YfFcrt4s9etuKoxqkOs3bDYt/zAAcyO2EPmsvRrA/0R9h/qLHY4QkIESoBPj1IbUyJRtkz8RSo9hjJkJiUZLwvx/NfuUeHF1JTJFcCOuDizO7Crr4qxyLVBvMDEAs+12n7n9/S3AlUQZx2HKVk0ij3URAFK60x+TbhLqUdyQUc5aS8mJNcX3Aqd/X3w4+My2MHN4sTWvdS4/rVptRa397rrwMDIOdIK3d7oV/UTArIO0BoRJh0wqTh0P0tEC0ehRwtGWUKpPCo1Fyy6IWUWbwo4/h7yfeax2wvS1clNw6S++7tlu+K8ZsDSxfvMpdWM32Lq0fWAARUNNRiLIscrpTPnOWE+8kCIQSFAzDykN9QwkygjH84U5wnD/rfzGuk932zW6c7tyKXELsKawerCEcb0ymzRQtk64grsZ/b+AH8LlxX4Hlwngi41NEo4pjo4O/45BTdmMkgs3SRgHBQTRAk8/0n1uOvV4uHaGtSyztDKkcgDyCfJ8stM0BDWD90R5dbtGPePAPMJ+RJdG94iRSlgLgwyLTS3NKczCjH1LIwn+iB1GTgRhQih/8/2Ve5z5mbfYtmV1CHRH8+bzpbPBtLW1eTaCOEQ6MPv5fc0AHIIXxC8F1Me8iNvKKorjC0KLiIt3ypUJ6Ei6xxiFjoPqwfy/0n47PAV6vbjvt6S2pLX0dVb1TDWR9iM2+TfK+U169HxzPjv/wAHyg0aFL8Zjx5nIislySY3J3QmiSSJIYwdtRgrExsNtgYtALT5ffO37Y3oJ+Sk4B3eo9w/3PHcsN5s4Q3ldOl97v/zz/m9/5wFPgt6ECYVIRlNHJUe6h9DIKIfDh6XG1EYWhTSD94KpgVTABD7BPZV8SftmenF5r3kj+NB49LjPOVv51nq4O3m8Uv26/qi/0gEvQjeDIwQrBMnFu0X9Bg1GbMYcxeDFfUS3g9ZDIQIfQRkAFv8fvjs9MDxEO/v7Gvrjupa6s/q5euS7cXvbPJu9bT4Ifyc/wcDSgZLCfULNA75DzkR7RETEqsRvRBTD3oNRAvDCA4GOgNeAJP96vp6+FT2h/Qe8yPymvGE8eDxpvLO8031E/cR+Tf7cP2t/9kB5gPEBWUHwAjKCX8K3AriCpIK8wkMCecHkAYTBX8D3wFCALf+Rv36+976+PlM+d74rvi6+AD5efkf+uv60vvO/NL91/7U/78AlAFLAuECUwOeA8UDxwOoA2wDGQOyAj8CxgFMAdcAbQAQAMb/jv9r/1z/YP91/5f/xP/2/ygAVwB/AJoApQCeAIMAVAARALz/V//l/m3+8/18/RD9tPxt/EL8NvxN/In86/xy/Rz+5f7I/74AwQHGAscDuASQBUcG1AYvB1QHPQfpBlcGiAWCBEoD5wFkAM7+Lv2T+wv6ovhn92X2p/U29Rf1T/Xg9cf2AfiG+Uz7SP1p/6AB3QMNBh4I/gmcC+oM2g1jDn0OJA5YDRwMeAp1CCIGjgPOAPf9HftY+L/1Z/Nl8cvvqO4I7vLtau5x7//wDfON9Wz4l/v1/msC4gU8CV0MLQ+TEXoT0RSKFZ0VBRXGE+URbw90DAkJSAVOATj9Jfk49Y7xRu5860fpvOfq5tnmjucF6TfrFO6K8X711Plr/h8DzAdODIAQQBRvF/EZsRudHK0c3BsuGqwXaRR6EP0LEwfiAZH8SPcz8nrtQumv5d/i6eDi39Lfv+Cj4nLlGumA7YXyAfjN/boDnAlED4QUNBkrHUogdSKYI6gjoiKJIG0dYhmGFPwO7giKAgL8h/VO74bpYOQE4JfcNtr22OTYBNpP3LffI+R06YPvIPYb/TwETgsZEmYYBB7EIn8mFyl0KogqUSnUJiIjVR6RGAES1QpFA4z74/OJ7Lflo99/2nXWptMs0hTSYtMQ1graNN9q5XvsM/RX/KYE4wzMFCMcrCI0KI0ski8rMUcx4y8HLcYoPyOaHAoVyAwSBC77XvLn6Q7iENsl1X7QQM2Jy2jL4Mzqz3DUUtpk4XDpO/KA+/gEWg5cF7cfKSd3LWwy4TW4N983UzYdM1QuGSicIBUYxA7xBOn69/Br54/eqtb6z7fKCscTxeXEg8bjye/OgNVm3WbmO/Ca+jEFsQ/GGSEjeCuIMho4/jsVPks+nDwSOccz4SyUJB4bxxDfBbv6sO8U5TvbdNICyyTFCMHQvpK+UMABxIvJw9B22WDjNu6k+VMF6BAIHF0mlC9lN5A95EE9RIVEt0LgPhs5kjF9KCIezxLcBqX6ie7l4hbYcc5Cxsq/P7vFuHO4TrpJvknEIcyV1V/gLOyh+F0F/xEjHmopfDMJPMxCj0cqSodKoEiCREo+JjZULB0h2RTlB6f6gu3g4CLVpcq7wa66tLX3so6ygLTAuC6/nMfJ0WndIuqS91AF9RITIEYsLDdxQMlH+UzYT01QUU7ySU9DmjoUMA4k4xb6CL76newE31/SEcdzvdK1a7Bqreis7a5qsz+6OcMVzn/aGOh49i4FyhPaIe8uojqYRIJMH1JDVdJVxlMsTyZI6T67M/Am6xgYCuv61+tT3dHPucNsuTyxaasjqIanmKlNroG1/r59yqXXEuZV9fYEfxR1I2Mx3D1+SPRQ/FZlWhBb+VgrVMtMEENEN8Ep7ho/Cy37M+vO23jNn8Cqte6ssqYno2yiiKRtqfew7boEx9/UE+Qs9KsEExXjJKAz1kAdTB1VjVs6XwVg5V3qWDlRCkesOn0s6hxrDIL7r+p22lbLxb0tsuyoSaJ6np+dwJ/PpKesC7euwy7SHOL98k0EiBUmJqc1kEN1T/hYzV++Y6pkiGJmXWtV00ruPSEv2x6cDen7SupJ2WvJLLv7rjilMZ4fmiKZRJt3oJOoXLN/wJfPMeDL8d0D3RU8J3U3CEaDUoNcumPuZ/1o22aZYV5ZZ04JQaoxwCDODmH8BepJ2LnH1bgTrNahb5oalvqUGpdpnMKk5K96vR3NU96Y8F0DExYmKAs5PEhEVbxfUWfGa/ls3WqBZQ1dw1H3QxU0lSIBEOj83ul210DGw7Z4qceeBZdvkiuRQ5OpmDWhpqyjusLKhtxm788CKxbkKGc6LEq4V6BijmpEb5twiG4YaXZg41S2Rl82WSQyEX791OnO1gHF9rQspw+c9ZMgj7eNxI87lfGdpan9t4rIzNo37jMCJhZ1KYk71kvcWS1lcG1kcuBz2XFdbJRjw1dDSYU4CSZfEiD+5+lS1vvDb7Mwpa6ZQpExjKGKoIwhkvma5qaKtXfGKNkN7YsBBRbbKXM8Ok2wW2Fn9G8jdcZ2z3RLb2VmYVqaS4Q6oieFE8z+FeoC1i7DLrKFo6aX7o6iieyH2olfj1GYaqRPs4zEm9fq69oAyhUXKiI9WE4yXTxpGHKAd0l5ZXfgceVouVy6TVo8ISmkFIL/Xerb1ZvCM7EroviV+ox3h5qFdYf4jPqVNqJNscvCKdbR6iAAdRUpKpk9ME9jXr1q3HN5eWh7mXkZdBJryV6eTwQ+hSq4FT4Avure1UHCf7AjoaaUZ4uwha6DcoXtiveTSqCHrzjB1NTC6WL/CRUSKtg9wU9CX+FrPnUNeyF9anv0delsj2BEUYA/zCvAFgABNusJ1h7CEbBuoK6TN4pQhCmC04NCiUySq54ArtS/ndPB6J3+hhTTKd89DFDOX6tsPXY6fHJ+1nxvd2huB2KrUstA8iy5F8YBw+ta1jLC6K8KoBOTaYlXgwyBm4L4h/mQWp26rKK+iNLQ59b97xNvKa89ElAJYBht2Hb/fFt/2n2IeI5vMWPQU+NB9i2iGI0CZOzR1nzCBLD3n9SS/4jFgliAyoEQhwGQWZy3q6S9ltHw5g/9RBPmKEs91U/0XyptEXdcfdp/d34/eVhwCWSxVMdC1i54GVUDGO1s1/vCY7A2oO+S+Iicgg6AYYGMhmWPqZv4qty8ydAk5kj8iBI6KLI8VE+NX+Fs53ZSfe9/rH6RecZwj2RMVXRDjy86GhoE2+0p2K3DBbHDoGWTU4nbgi6AYYFshiePTZuAqku8I9Bt5YX7vRFsJ+g7kk7YXj5sWnbffJt/d35+edZwwmShVehDITDmGtsEre4G2Y/E6LGfoTWUEYqAg7eAyoGxhkaPRJtQqvO7pc/N5Mb65RCAJu06j03WXUJrbHUGfNx+2n0GeYhwoGStVSNEiTB5G5YFi+8C2qLFCbPIol2VL4uNhKqBnIJch8OPkJtoqta7U89G5A/6ARB2JcQ5T0yHXO9pHnTHerV91HwpeNtvKmRxVSNExzDzG0oGdPAa2+LGaLQ8pNuWrIz/hQWD1oNriJ+QMpzJqvS7K8/a42D5FA9QJG4400rvWkZocnIjeSZ8ZnvodtBuXWPqVOdD2DBRHPQGZvFM3E3IAbb4pa6YiI7Vh8iEeIXeidmRKZ11q068Mc+K47v4Hw4RI+42HEkPWUpmaHAcdzF6kXlCdWdtPGIZVG5DuzCTHJIHXfKX3eHJ1Lf8p9Oav5ANivCGf4e2i3GTdZ5rrOa8Zc9Y4yP4JQ28IUc1L0fpVv1jBG6zdNd3V3c6c6BrxWD+UrdCcDC2HCQIWvP33pvL3LlDqkidT5OljHuJ64nvjWeVF6Csrbu9yM9E45n3JwxRIHozDEWBVGFhSGvscRp1unTQcHxp+V6YUcNB9S+6HKcIWPRr4HrNGLzLrAqgNpaaj2mMuoyJkLiXDaI3r86+WtBQ4x73KAvUHooxuELZUXleN2jJbv1xu3EGbv5m2VzoT5FASy+dHBkJWPXw4XrPhL6SrxajcJnqkrWP6Y+Ck2OaVqQLsR/AHdF+47T2KQpIHXovNED0Tklb1GRNa4JuXG7faiZkZ1rvTSE/cC5eHHoJVfaE45nRH8GUsmmm+5ySll6TdpPYlmid8aYps67BENLO4132LQmtG00thD3WS9RXImF7Z61qompcZ/Zgo1etS3M9ZC39G8cJUPcl5dTT5MPOtQCq06COml+XXZeHmsKg3amOtXrDNNNA5Br2NQgHGgUrqzqBSB1UJV1WY4BmjmaAY3BdkFQkSYk7KCx5GwAKRfjP5ijW0MY8udat9aTanrabnJuOnnGkF606uIPFidTW5Oz1QwdYGKUorDf6RChQ4FjiXgBiJGJPX5hZL1FVRmI5uirRGiMKM/mC6JPY4MncvOmxW6l0o16gMKDponKonrAsu8jHDtaQ5dT1WQajFjEmizREQflLWFQkWjFdaF3LWnBVg01CQwA3HSkFGi8KGPo66hDbEc2owDO2A65WqFSlFKWUp8Gsb7RgvkfKxNdu5tP1eQXpFKsjSzFiPZNHkU8gVRVYXlj5VftQjkntP2Q0TycVGSQK8/r0657dX9CdxLK66LJ8rZOqQ6qNrFuxh7jWwf/Mqdlx5+v1pQQuExUh7y1aOf1CkErZT7NSCVPbUD1MVEVYPJAxUyUAGAAKwfuw7TrgyNO4yGC/Brjhshewu6/OsT2247yKxe7PvduY6Bv23QNzEXQefCouNTk+WEVWSg9Nb013SzlH1kCEOIUuKCPHFsMJgvxp7+DiRtf0zDnEV72BuNu1drVUt2K7gMF7yRTT/t3j6WX2IwO7D8ob9CbjMEw57j+aRCxHlEfRRfNBGjx3NEYr0SBqFWwJNP0g8Y3l1tpN0TnJ18JXvtq7cLsavcjAW8amzW3Wa+BR68r2eQIIDhoZWyN9LDs0WTqrPhJBfUHtP288IjcxMNQnTh7qE/oI1f3Q8j/odt6+1VrOgchexA/Co8Ebw2nGb8sG0vfZBOPj7Ej34AFbDGcWth8BKAovnDSOOMQ6LzvPObI28jG2KzIkoRtHEm8IZf549PPqIeJE2pnTUM6QynXIC8hTyUDMutCa1rHdxeWX7uH3WgG4CrMTBhxyI78pvS5IMkg0sDR+M8EwjiwKJ2IgyxiCEMgH4/4W9qbt1OXb3u/YPtTo0AXPoc68z0rSNtZd25bhruht8JX45gAgCQIRURjVHl0kwSjgK6QtBC7/LJ8q+yYwImcczxWcDgcHTf+o91Xwiul941reRtpg17vVYdVR1oLY39tM4KXlvetk8mT5hgCUB1YOmhQvGuserSJZJd4mMidWJlMkPSEtHUUYrxKWDCsGov8t+f3yQu0n6NPjZODz3ZDcRNwM3eHeseFk5drp7+559E36OwAXBrML4xCCFW0Zhxy7HvsfPyCJH+IdWBsDGP8TbA9xCjUF4/+i+pz19vDV7Fbpkeab5IDjRePo42Plp+ef6jHuQfKs9k/7BQCqBBkJMg3UEOcTVBYLGAEZMhmfGFAXUhW3EpcPCgwvCCYEDQAG/C/4pfSC8d3uyexT64PqXerg6gPsvO3676nysvX8+Gz85v9OA40GiAkpDF8OGRBOEfYRDxKcEaQQMA9ODRELiwjTBf0CIgBY/bT6Sfgq9mX0BfMT8pTxiPHs8bvy6/Nw9Tz3Pvlm+6D93P8GAhAE6QWFB9kI3QmKCuAK3gqHCuIJ9QjMB3IG8gRcA7wBIQCX/ij94fvJ+uf5QfnY+K34vvgI+YX5L/r9+uf74/zo/e3+6P/SAKQBWQLsAloDowPGA8YDpANmAxEDqQI1ArwBQgHOAGQACQDA/4r/af9b/2H/d/+b/8j/+v8sAFsAgQCbAKUAnQCAAE8ACgC0/07/3P5j/un9c/0I/a38afxA/Df8UfyQ/PX8f/0s/vf+3P/TANYB3ALcA8sEoQVUBt0GNQdUBzkH3wZIBnUFagQuA8gBQwCr/gv9cvvr+Yb4UPdT9pv1MPUY9Vj18PXe9h/4qvl1+3T9mP/QAQ0EOwZICCMKuwsCDeoNaQ56DhcOQg39C1AKRgjtBVUDkgC6/eH6H/iK9TnzP/Gu75buAO727Xvuje8n8T/zx/Wt+N37Pv+2AisGgQmdDGQPwBGcE+YUkhWWFfEUpBO2ETQPLwy8CPUE9wDg/ND45vRD8QXuR+sg6aPn4ebg5qXnLelu61nu2vHX9TT6z/6DAy8IqwzVEIoUqxceGs0bpxykHMAbABpuFxsUIBCYC6cGcQEf/Nn2yvEa7e/oa+Ws4srg19/c397g1uK45XHp5u328nv4S/44BBcKuA/uFJAZdh2CIJcipCOdI38iUSAfHQIZFRR/DmgI/wF3+//0ze4S6frjsd9Z3BDa6djw2CnajdwM4I3k7+kL8LL2sv3UBOMLpRLlGHIeHiPCJkApgip7KigpkCbGIuMdDBhtETcKoQLn+kPz8ust5SzfHtos1nnTHNIi0o7TWNZt2q/f+eUa7d30B/1YBZANbxW3HCwjnCjaLMMvPDE4MbQvuSxcKLsiARxgFBIMVQNw+qXxOelw4YbatdQq0A3Nd8t3yxLNPNDh1N7aB+Im6v3ySvzCBR4PFRhgILsn7i3FMhg2zDfPNx82xjLdLYUn8B9VF/YNHAQS+ibwpubc3Q7We89Yys/G/sT2xLrGP8ptzxzWHN4x5xTxe/sTBo0QlRrdIxwsDjN+OD08LD45PmI8sjhDMz0s1CNJGuMP8gTN+cjuOeR12sfRdcq6xMbAuL6kvozAZsQVym/RPto/5CXvnPpMBtsR7hwuJ0ow+jf/PSpCV0RyRHlCeD6LON4wqyc4HdUR2AWh+Yvt9eE817PNpsVWv/W6qbiFuI66tr7fxNvMb9ZS4THtr/ltBggTHR9OKkM0rDxGQ9xHSEp0Sl5IEUSuPWQ1cSshIMoTzAaM+W7s29801NbJEsEuumO117KhssS0NLnPv2XItNJv3jvrtfh2BhMUIiE8LQM4IUFNSE5N+k86UAtOekmpQso5IS//IsEVzAeO+XTr7N1g0TLGvLxItROwRq37rDWv5bPruhDEEM+X20XpsPdoBv0U/CL3L4k7VkURTXtSaFW/VXxTrU52Rw0+uDLQJbUX1win+ZvqKNzAzsvCqLiosAqr/KeYp+Opz642tuG/hsvO2FHnofZFBsUVqSR8MtI+SUmOUV9Xjlr/WqxYplMSTChCMzaQKKYZ6gnV+ePpkdpWzKK/2LRQrEum/KJ9otak9am1sdu7G8gX1mPlifUMBmwWKibLNNtB9UzAVfdbZ1/0X5ddYFh3UBZGjTk8K5EbBQsY+k3pJ9kjyrm8ULFEqNuhSp6vnRCgXKVsrQS408R2033jbPS/BfIWfifhNqNEWVClWT5g8GOaZDdi11yiVNVJxDzSLXMdJQxu+tfo6tcqyBK6Ea6HpL2d7JkxmZabCKFgqV+0sMHt0KDhSvNgBVcXpCi+OChHclM5XTJkJGjuaIlmBmGOWGBN0z9OMEkfSA3W+oLo29Zpxq+3HqsbofSZ45UIlWyX/pyVpe+wtb5/ztHfJvLvBJwXnClhOmlJPlZ7YM9nAGzsbIpq6mQ3XLRQt0KtMhIhbQ5P+03o+dXjxJG1eagEnoSWM5I3kZaTQpkOormt6LsvzBDeAfFuBMMXZyrKO2RLvFhnYxNrgm+QcDRuf2ibX8xTbUXtNMoikQ/Y+zboRdWXw7izJKZDm26T4I7AjRiQ1pXPnr+qSrkAymHc3u/fA8oXBSv4PBlN6Vr8ZfptpXLXc4ZxwWu1YqZW8kcJN28kshBu/D3ovdSGwieyHqTbmLWQ7YupivSMvpLbmwWo37b2x8bav+5CA7UXdivsPYdOxlw4aIRwaXW/dnt0rm6CZT9ZQ0oBOf8lzxEQ/WDoYtSwwd2wa6LMlluOWonyhy2K/Y81mY6lqbQSxkLZpe2bAoQXuyulPq5PUF4aaq5yyndFeRJ3QnEAaJNbXEzQOnYn5RK9/Z/oMtQUwdqvCqEYlWGMK4eehceHl43gll2jrLJYxNfXk+zqATcX1iskP41QiF+ga3d0x3lme0h5enMraqBdPE51PNQo8hNy/vjoLdSywB6v+5+/k8qKYYWvg8OFjIvflHSh6rDJwofWi+sxAdIWxitqPyVRbWDKbN11XnsifRp7VnUBbGRf4E/tPRYq9RQu/2rpUdSJwKquQJ/DkpWJ/YMngiOE4Yk1k9efZq9pwVXVj+pyAFUWjSt3P3ZR/2CYbeB2jnx2fod80XaAbdtgRVE1Pzgr6hXw//LpntSYwHyu154kksSIAYMIgemClYjikYaeIa45wELUoemw/8EVLStMP4FRPmEKboB3V31hf4597HembgRiaVJMQDos0BazAJDqEdXewJSuwZ7gkVaIbIJRgBaCrIfpkIWdHq08v1LTw+jq/hoVpyrqPkZRK2Efbrx3t33jfy1+pHhyb95iSlMvQRotpRd5AUHrqtVawfGu/J75kUyIQIIEgKqBJYdLkNScX6xzvoTS9+ck/l8U/SlUPsdQyGDYbZR3r336f2R++Hjhb2Zj51PdQdQtaBg+AgXsZtYLwpGviJ9tkqWIfIIhgKiBA4cJkHWc5Kvgvd3RP+dg/ZQTLymKPQZQFGA3bQl3P32ofzJ+6Hj0b5xjP1RUQmguFRkBA9jsRNfuwnOwZKA7k2GJIIOogA6CRYclkGmcsKuFvV3RnOaf/LkSQSiOPARPEl88bB12aHztfph9dHiqb35jT1STQtQurBm/A7ntQtgCxJaxjaFjlH6KKoSZgd2C7IefkLGcxKtjvQXREebk+9IRNCdjO8JNwl3patB0KnvIfZV8m3cCbwxjF1SYQhcvKxp3BKbuXdlExfayAqPhlfuLm4XxghOE94h2kU2dIKx8vdjQn+Uw++AQCiYKOkJMKFw/aSNzh3k7fCp7Xnb7bUVillNiQi4vkBonBZ3vldq0xpO0wKS1l9aNb4eyhLGFZoqrkj6exazPvdfQSOWE+uUPxiSFOIhKRVpBZxlxgXdIell5vXSYbCphzVLxQRkv2RrOBZzw5ttNyGq2x6bcmQ6Qp4nYhraHOYw9lISftK1fvgLRDeXk+eMOaSPXNpVIHFjyZLRuGXXwdyN3uXLXarpfuVFDQdcuBRtoBqHxTt0Pyni4E6lUnJ+SPoxiiR6KbY4slh6h7K4rv1vR8ORP+dsN9iECNWxGrlVSYvdrUnI1dYl0VHC6aPZdXVBZQGcuFBv1Bqnyy972y7u6oasan4iVNI9NjOmMApF2mAujbbAzwOPR8eTJ+NEMbyAJMxBEAFNmX+NoL28Zco1xkG1DZt9bt04xP8gtAxt0B7TzW+AAzjC9bq4rosaYhZKYjxWQ9ZMam0ulN7J5wZnSEuVT+McL1x7vMIRBFFAxXH1lsmugbjJubmpyY3ZZyUzNPfos0RriB7/0++Eq0NS/eLGEpVScLpY/k56TRZcXnt2nSbT7wn/TVOXu970KLx22Lso+7ky2WMdh3mfMantq8WZLYLxWk0otPPwrfxo+CMf1qeNx0qPCu7QhqTCgK5o/l4KX75ppob6qo7a6xJXUt+Wc97YJextiLOY7kEn4VMZdt2OgZmtmHGPOXLRTFkhQOs8qChqGCMz2YuXS1JvFM7j/rFakep6Vm76b754Qpe6tQrm0xtrVPeZd97QIvRn0Kdo4/kX7UHxZQl8hYgVi8V7/WF5QVEU5OHIpcxm6CMr3JedL17nI3bsascOoFqM9oE6gRKMHqWmxJrzpyE/X5eY097kH+BdwJ6w1PULDTO5UgVpRXUxdc1rgVL5MT0LmNeUnuRjZCMH47ujZ2fjLtb9utXGt+6czpS6l6adNrS61TL9Yy/PYsecg98YGLBbaJF0yTz5USCBQeVU2WEVYp1V0UNVICD9bMyom3BfhCK/5uup43FXPt8P2uV2yJK1zqluq26zesTm5s8IAzsXaoOgk994FXhQzIvIuOjqzQxdLLlDTUvNSkFC/S6dEgjuYMEAk2xbRCJL6iewl383S38evvoK3jrL4r9CvFrK2tom9WMbe0Mbcs+lA9wIFkBKAH24rADbkPthFpkouTVxNM0vFRjdAvzefLSkithWpCGj7V+7e4VzWKcyTw9u8M7i9tYi1lbfRuxnCOcrx0/Pe6ep09zMEwxDCHNUnpjHrOWZA5kRKR4RHk0WJQYg7wTNyKuYfbxRoCC/8IvCf5P7ZkdCfyGTCDr69u3+7Vb0twebGU84310zhQuzC93ID+g7+GSokMS3ONMc68T4uQW9BtT8PPJ02iy8TJ3gdBRMNCOj86fFm57HdE9XOzRfIG8T0wbDBUMPExu3Lo9Kv2s/jve0p+MICNw02F3IgpCiQLwA1zjjeOiM7njlcNnsxIiuEI+AaeRGZB4/9qPMv6m/hqtka0/DNU8pbyBbIgsmRzCrRJtdU3nvmWu+r+CMCfAtsFK4cBCQ3KhcvgjJgNKY0UzN1MCUshybIHyAYyw8LByX+XfX47DblUd5/2OnTsdDuzqrO5M+R0pjW2Nsm4k7pGPFG+ZcBzAmlEeUYVh/HJBApEyy6Lfwt2SxeKp8mviHiGzoV/Q1iBqj+CPe+7wHpBuP43f3ZMden1WjVdNa+2DTctuAg5kbs9vL8+R4BKAjiDhgVnBpFH/EihSXxJisnNiYcJO8gzBzUFzESDwygBRf/pfh98s7sw+eA4ybgy91/3ErcKd0U3/jhvOVB6mHv8/TL+rkAkQYmDEwR3RW3Gb8c3x4KIDogbx+0HRkbtBeiEwUPAwrEBHL/NPo09ZnwhOwT6V/me+Ry40rjAOSM5eDn5eqE7pzyDve0+2kACwV0CYQNHBEhFIAWJxgMGS0ZihgsFyAVehJPD7sL2wfOA7f/svvg9130RPGr7qPsO+t56mLq8uoi7OftL/Dm8vb1RPm2/C8AlgPPBsQJXQyJDjgQYRH9EQsSjRGJEAsPIg3eClMIlwXAAub/Hv1++hn4APZD9O3yBPKP8Yzx+fHR8gj0lPVl92v5lfvQ/QoAMwI5BA4GpAfyCO4JlQrjCtoKfQrRCd8IsQdTBtEEOgOaAQAAd/4L/cj7tPrX+Tb50vis+ML4EPmS+T/6D/v7+/n8/v0C//3/5AC1AWcC9wJiA6cDxwPEA6ADYAMJA6ACKwKyATgBxQBcAAIAu/+H/2f/W/9i/3n/nv/M//7/MABeAIQAnQClAJsAfQBKAAQArP9E/9L+Wf7f/Wn9//ym/GT8Pvw4/FX8l/z//Iz9O/4J//D/6ADsAfIC8APeBLEFYgbnBjkHVAc0B9UGOAZhBVEEEQOpASIAif7p/FD7zPlr+Dj3QfaP9Sv1GvVh9QD29vY9+M75nvug/cf/AAI8BGgGcghICtoLGQ35DW8Odg4KDisN3QsoChcIuAUcA1YAff2l+ub3VvUL8xnxku+E7vrt/O2M7qrvT/Fx8wH27/gk/Ij/AAN0BsYJ2wybD+0RvRP7FJkVjxXcFIEThhH4DukLbgiiBKAAifx6+Jb0+vDF7RPr+eiM59nm6ea/51bppeue7iryMfaU+jP/6AORCAgNKRHTFOYXShrnG7AcmhyjG9EZLhfME8QPMgs6BgABrvtr9mLxvOyd6Cjle+Kt4M7f6N/+4AvjAObJ6UzuZ/P0+Mn+twSSCiwQVxXrGcAduCC4Iq4jkCNbIhYg0BygGKQTAQ7iB3QB6/p49E7unuiX42DfHtzs2d7Y/9hR2s3cYuD35GvqlPBF90r+bQV3DDATYxnfHnYjAydoKY4qayr9KEsmaCJvHYYX2BCYCf0BQvqj8lvrpeS23r7Z5tVP0w/SM9K906PW0tos4Inmuu2I9bj9CQY8DhEWSR2rIwMpJi3wL0oxJjGDL2ks8Cc2ImYbtRNaC5gCs/nt8Izo0+D/2UfU2c/bzGfListGzZHQVNVs26vi3OrA8xP9jAbjD84YBiFMKGMuGzNNNt03uzfnNWwyYy3vJkEfkxYoDUYDPPlW7+LlK9111f/O/MmXxuzECsX0xp7K7c+71tXe/efu8Vz89QZoEWQbmCS9LJIz3zh4PD8+JT4lPE84vDKWKxMjchn+DgYE4Pjh7WDjsNkc0evJVMSHwKO+ub7MwM7Eosoe0gnbIOUV8JX7RQfNEtId/Cf9MIs4az5sQm5EXUQ3Qgs+9zcoMNgmTRzaENUEnPiN7AfhZNb4zA7F5b6vupG4nLjSuia/eMWZzUzXR+I37r76fAcQFBYgMCsGNUs9vEMlSGJKXkoXSJ1DDz2fNIwqIh+6ErIFcfhb69jeSdMKyWzAs7kWtbuyt7INtay5dMAxyaLTd99V7Nr5mwcxFS8iMS7XOM5BzkieTRdQJFDBTf5I/0H3OCsu7iGcFJ0GXvhM6tXcYtBXxQm8w7S/ryetEa2Br2W0mrvpxA3Qsdxz6un4ogcvFhwk/TBtPBBGnE3SUolVqVUuUypOwkYtPbMxrSR+FpQHY/hf6f7asc3gwee3GLCvqtmnr6czqlWv77bHwJPM+dmS6O33kgcLF9wlkzPEPw9KI1K9V7Ja6FpbWB1TVEs7QR81XSddGJUIfviU6FXZNsunvgu0tqvppdWilKIopYGqd7LNvDbJUte15uj2bAfEF28n8jXcQshNX1ZcXI9f3l9DXdFXsU8fRWw4+ik3Gp0Jr/js59nX9Miwu3ewoKdzoSCexZ1koO2lNq4BufrFwNTf5Nz1MQdbGNMoGDiyRThRTVqqYBxkhWThYUNc01PTSJY7gSwJHK0K9Phm54zW68b8uC2t2qNOnb6ZRpnsm5+hMqpltePCRNIS48r04gbRGAkqAzpFSFxU612kZFRo2mgyZm5guVdVTJk+8C7RHcELTPkB527VHcWMti+qZqB/mbGVG5XEl5mdbab/sfS/489Q4bTzgQYlGRArtDuSSjNXNWFIaDRs2Wwxak5kXFugT3NBQzGMH9cMt/m95n7UicNitH+nRp0Ilv6RSJHvk9+Z7KLQrjC9n82c353yDgZZGegrKj2ZTLtZKWSSa7pvf3Dbbd9nul6xUiBEeDM4Ie8NMvqZ5r3TMcJ/siClfprskqeO0Y1xkHaWsp/dq5u6esv43YbxiwVtGZIsZD5YTvFbxmZ/buFyyHMscR9r0GGFVZ1GizXTIgUPvPqU5irTFcHjsBKjDpgtkK+Lt4pOjWCTwpwpqTe4eMln3HHw+gRjGQ8tYj/QT9ddCWkPcal1snYidApummQZWOdIezdZJBgQVPut5sTSNcCPr1ah+JXOjRiJ/oeHiqGQH5q3pgi2nMfs2mHvXAQ8GV4tJUD/UGlf8Wo+cw54Onm5dp1wFGdpWvtKQznJJSUR9/vj5ovSkL+Eru2fPZTPi+aGqIUgiDuOzZeJpBC06MWI2VfuswP4GIEtrEDmUadgfWwLdQ56XnvveNVyPmlyXNdM4johJysSpfw0537SJr/Crdme35IzihiFt4MahjGMzZWkolKyXsQ92FXtAQOaGHgt+UCFUpJhrW12dql7HH3DerF0E2s0XndOVjxdKCgTW/2f55zS975HrRie3pH6iLGDLIJ5hIWKI5QIodCwAcMP117sRwIiGEUtC0HbUipigG59d9x8cn4yfC12kmyqX9pPmz19KRkUGP4i6OTSAb8UraqdOpEliLGCCoE9gzmJ0JK4n42v1MH/1XPriAGTF+os5UDqUm1i9W4heKh9YH87fUl3uG3TYP1QsT58Kv0U2v696FPTQ78prZCd85CzhxqCUYBogk6I1pG2noqu18AQ1ZfqxQDuFmYsh0CzUl5iDm9geAt+5H/cfQN4hW6tYd9RlD9bK9EVnv9s6erTvb+DrcidCZGnh+uBAYD6gcWHNpEDnsmtDsBD1MvpAAA=\" type=\"audio/wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\n## Video\n\nMore exotic objects can also be displayed, as long as their representation supports the IPython display protocol.  For example, videos hosted externally on YouTube are easy to load:\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('Yn-oemgzlEU')\n```\n\n\n\n\n\n\n\n\n\n\nUsing the nascent video capabilities of modern browsers, you may also be able to display local\nvideos.  At the moment this doesn't work very well in all browsers, so it may or may not work for you;\nwe will continue testing this and looking for ways to make it more robust.  \n\nThe following cell loads a local file called  `animation.m4v`, encodes the raw video as base64 for http\ntransport, and uses the HTML5 video tag to load it. On Chrome 15 it works correctly, displaying a control bar at the bottom with a play/pause button and a location slider.\n\n\n```python\nfrom IPython.display import HTML\nfrom base64 import b64encode\nvideo = open(\"../images/animation.m4v\", \"rb\").read()\nvideo_encoded = b64encode(video).decode('ascii')\nvideo_tag = '<video controls alt=\"test\" src=\"data:video/x-m4v;base64,{0}\">'.format(video_encoded)\nHTML(data=video_tag)\n```\n\n\n\n\n<video controls alt=\"test\" src=\"data:video/x-m4v;base64,AAAAHGZ0eXBNNFYgAAACAGlzb21pc28yYXZjMQAAAAhmcmVlAAAqiW1kYXQAAAKMBgX//4jcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTE4IC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAxMSAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTMgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MzoweDExMyBtZT1oZXggc3VibWU9NyBwc3k9MSBwc3lfcmQ9MS4wMDowLjAwIG1peGVkX3JlZj0xIG1lX3JhbmdlPTE2IGNocm9tYV9tZT0xIHRyZWxsaXM9MSA4eDhkY3Q9MSBjcW09MCBkZWFkem9uZT0yMSwxMSBmYXN0X3Bza2lwPTEgY2hyb21hX3FwX29mZnNldD0tMiB0aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MyBiX3B5cmFtaWQ9MiBiX2FkYXB0PTEgYl9iaWFzPTAgZGlyZWN0PTEgd2VpZ2h0Yj0xIG9wZW5fZ29wPTAgd2VpZ2h0cD0yIGtleWludD0yNTAga2V5aW50X21pbj0yNSBzY2VuZWN1dD00MCBpbnRyYV9yZWZyZXNoPTAgcmNfbG9va2FoZWFkPTQwIHJjPWNyZiBtYnRyZWU9MSBjcmY9MjMuMCBxY29tcD0wLjYwIHFwbWluPTAgcXBtYXg9NjkgcXBzdGVwPTQgaXBfcmF0aW89MS40MCBhcT0xOjEuMDAAgAAACqVliIQAV/0TAAI/3gU2tIW7KawwaCmQGTGHKmuYAAADACBcshU+yICkgAA14AHowiEeT6ei7v7h3Hu0i2fpUBLGBIkbCMP3Vfz+9BVGCDXnw9Uv5o3iN030tb7eq6rsEEhHs2azbdTiE9Csz5Zm6SiUWRdmB43hbD5i6syATuODUJd7LM3d9cbFpc7zFlu5y3vUmNGd6urpvKKT9iyleIyTuR1sVS431DhevGfkUllVeIznYUe2USoMW1tufETjyRdmGldN6eNlhAOsGAH4z+HkrwKecPPU7Q5T4gDAIxj9hW84jVExMTSTHxkPTq1I4OotgUxURCGTsw60k/ezPNmNg38j1bqaGmPcruDKEIBDsK5qEytFB90Q68s0h2wmlf2KXd5bleBefiK+/p47ZsyUO4IdlW25rRy+HLjt6wQXfYee3IkiQOoOK+U7u/lxcl78zfxwIoEMjUUSKNZjkp8clnmecDDJ3Kz+viF7bPklk7N6QRyizAKPIIpnNJUuMWQmqeL2Or6cr4D0/0tOym+4tficxmhuEONKUtO2pPn3hRjMllkd12tXp70fLTfxy0dwB70ML9iLEcItHb7zVupHlP5RxdvecpREw+OsIPr9KWilIesNE19jgIbT+TkiRBjOoKvUuwcQnKg7fOTHVoLvnKuAfea+oujEdm1Rwd2tEOnkF+ZC11WaNQsiNR/eJ9EnUXjXDYGfhB+Oe7qj8nYTT+eOXg1cuJNgLXEs4vOheWEjQOqfIWMQc3DmTof5s0ksBmUQ3PQ+UHPxZSnmOEZB+j6xT3wbm7HGzDjWtSg1SjTxd1EiJ8xA4SIxxR8WIKLg+TwFxJNS7Laxq7Uglu3AkXe82P1JCdJX5PsbFbxuDbuJgakzRcTwMLLSKCiizS/eCW0uJed/lev9yb80kKlVET4S219cn/zhkpeDV83cHYOr+sJQKDRk/Wh2c7fsuxfxaEH/6reSmvFDsAnXAyPXliJ3G4VG3OkEM5K5WyGGrBizZbTrdGsBnzj5VSGGOJdCKuRrUluw/8es2vYRPs9BcTqAqvHk9M52SSIf+1T6L53EZP8VbtXB+G29CMW4xVCK/B/YDjaNmqMwJ61dapugjnWJfqeXlGGa3Ch3aA7gi30T8PucNRBjLK3lF67ZDDvkWXRQXd+VMnKWHkBbCkQ/F/fMuNpHO3C00Y2pljna1qImBhVMvPe0F7Qx7G/YyxLRzhyUU8e23HGzp0agtNJRbydbrPV+TqJMSifJMNcZIf8wkdnC3/xdpcXnLf2Ye3Kbd0o7utciTG+q5h6WTEk+PaNbXLLA0YyZ2VnLTcyV1QTS76aNCbV9Q1/OQ7QU81Gg0hPa9aSiscGary6jLVwDQaik4zLsi7jPqgPVdup7pwx7uJDqRCVcVi5QoZFp/GHdex5sJTF69A6sja69/NLkFIWNSIeRcuGahXpF+wZeYIrqJv975s1TKYKAvp1WtzgtgWNkcbzCtROqf8rPtlAIxkX8GLcEo9zfExyfimeXQ64qfFxEy0IMy2Hsxau9fSMqUnIjntuVVjCQtBL+94gx1RZLndE6wROVTq/wHwHrQzo9QL9cpPqPFJjiZ/NGZIFuudS+wsBFe6Hu8Oitf5zToLqLdtU4Smwh4ne3JsiT9lOzN+4PPw3VSx9l5FppVwdKUWELw1dYpCOppyVWlJ3YQ8H4FQQM8EcYMG9N3Bxu79y1J1ikuvuhMmLQlehLTbguhbix74hd1VIQC8EjHmOZSSWbssulYwPbr6FF49tifk6PymJvulR9/u+2585HkRfbxveGeWCz0ix1pIVfaNpESKmtLy/0mcbMg9hYDz2werz9oe0lT2BiMV6uAin6RaQcT8Vk9MPctfwae+gkvtnZA/sOBk8MbpylaHqc0KIVHhhLFMNnkOFiucjtGo/JWTa/F6g8wWeow5ZuIJUORaYHWqegZbTgM9dCsYYsfZGjjVMuSlDIvpYvIvFFooGPC7Ye2Jfawmq4Ut7EL/nv/dyAd2HRc5msmUhzeu/XpX3rVlzRmf9/Qan8Dbve3QfW1Ym0o5J/KAc3z1VBho7JBr5PgCL68RiD9jZHN0VvsT4gzsEjNlW3D91Uy4RduaodBFoNTzXwlfUYULBzdiTbH75l/UmVMC4TKeTWhNzw2UezaqeGd8at3WSY7W/VR3+hvZHDpkIjgKuNNH0DsCRa/Kk56XQoHIyvvUH/eNekNvziReqS4qgLnXUT4BRGt2BOtCifI6+X/DGHUOmWlX7TN5b4pw5U7jwfwshtbhGZM49T8JMk15Mzrc7tM6J11TYxb5R3mQhZ8TZumJ0bMJXPM69HFyihr5dJSEJMycxJVUh6NTQALUOoRTHIOwE+FpWI6feTv1SiZ0YpYe5DbkYJJbN7zAHbAKw25XvqR2mAjQmOlsfX/tK8DPjP/8h5/xgAF4EUbj1tOnQCBQL8jk9vHtfsXncsprww4Z+P/Z/UrKifuFyEpBWN8kLpF7yywE2iYdDruV9+/qKR8rC9ozNKyqQNIwtxrzYkWpE5t8K7gG4JFnrHona/Rp8dOX6VW41+jb5LB1LEtE8MwjLp3RCUOq/+6yLzaOEgBTqzvEjDeFpg/u9DMHMr4/2TOchfjg7dl+uQ6Gsx+4Ia9W7vivG95027p25eKL0nHvx/OqmAQEZYJL/JO58lOj0zPdJxrQ5dZksjMISzVZNn7DsxqE3zgBBuNzk50R8lTK3U8P12QiOAQYSTeGlYlkvfeofrfO1AitEj02m9aUkxTFd1ZZJoLQT2d3zEU5PmE4lxMVfL5ttNnIbqfcIU2RJKNWqdw77xfjfrNc/eNpRKPZ/6z50LzBprgjzBHRfKgSWWkDxHrX0aTbgwQFwd51+PoUWH4DkQg26uGslF5Hn3hB58+fkeLTosTANOIBNAeFZtTc4PIaLHw759zae7scY55xcTabzlilYIftst2RZ6ntsRC3zFxduCKvL6wLfYT+TiIWJn5P7sTwZwXuSzXY+9Q3xMZ5o4Xcpz6vD9FtTjzS69iefEYt4pXiDrZUo4ePGiLeoIFIwYB/v6GXdmG5VLLk+eKbOc9AmsX2zmvqtcvDRGQbzugXbH/kTH/lkNPBTmqN3ZJODUEXVohPEJ6th0xna0EVleB73Q3eNvaVUvhlJbjs3D/T17FRCebN7AOXvzzbLE/I5kNfEmJcv4dxtIeo2uQ/z9ohSpiZzbDj1u40nJRyJxUK60wEv0nA9f/NuJ6/PEyU0bkK16z2KH12k3Lc4+1f5fawIzkK2qJRB4wnj8VHhUW9mbJhs9vgfFmU3xrXSShY67Ygb+gYNPxxtn4K/9eTSwIA9fv/nR33lA2lZoXALRUTmOZIl3R0gAM5h6oX1y1thIyqViBK95VZc8Pvy7G3O90M9S4zkpyFQ36jrMazvMveMA4d39fvoaC7p90quiJfjI4yrl+ECVkCJL5MxRSa+iVcIL7Xbl0jVaGhZIcMYmcGOBbLzhJgloM1x1zFnnj3ggJRFAM8yNnXxhavk+mA18JC+y3lqGsp6vPReRxGlGHMou17L4It070LzkoeCzarpv8Apw59smdS5KN9qVN1WgeL7OSN8BHg94ubCvS7DW6H3/PbtRB62jFLsBhUV5YqCIbIN5VZ81AAACpUGaIWxFfwAru8x8uT3FuOjrAeSWXmAWqq9jCNGE+N5AOv//9//xjk4uBAcADN96c97AVGmzRtnWwPsgcCbLrVdQJgbKp4QSmPwQnVhv0hXyBjeFWWlcvx70urEN3FK6/lvk2tQeZgbtlbzXluvTfnSj/Ctz7vZ+O1FjhDzzdpL7uLzewzCIW5VWLAEKUVuS2J6wNk6MR7UblcEd4EtOY+R4/qJgfojCsfRvA0oC5dc41Vd0erZbSkrmPTjLCn815bxlchUJMS8gQD5hJNwoKHvNLNwn7XKuTtYIhH2wVNZvDWgzCjlPeQajnrcMsb6bZYJvNJU8HuGHvm50r7VG8qifEwmuyegAZXojh5Ul5VvjDW7kSAZyw8a7I6mHY3FZHd+OA3V4JZMbNliI3Tj1L6+MKTmilVialmyZagRtEMeKRdtxUPd3vVEtrOBVIVYWdgAGA7HmZiHQUQNxLkWxbLyWVlrh5EM0Do2NdbclHxxArz90d+MSVeUOIXQ/4V9quq8C8qVflo1gPtPMkjO2/UrdOYqhY404ReObOu/fdp4hAEDq6jhy64vOeT7XUK/Onq0rXTldtA6kvgQaJg+mgYSR9hfXtMbOUSLgLj/RmBSO8aAMHuJJZqf1tCM5pZ9eYUsrHmy+/z2NGalon0//uF6+33bQzT/RLRfBbYTjy9QrJqHLlw46lggWPGkHuPKSqk/CB7U4pNPXUbR0DdcJy9Db00wCzVzxVc6h7jfCFgiL2Y0HVqd6bgIaVUqn/gJCEyCDVplnzebv0gg3XwMJAGu639lHu7rEvxTp1smIYjWp9R5L4SspVvS07Nb+Smk1FgsMp1K3EMUT8X2Fty4VG54/Ec6bE8tNVw4/QV1VzBw7Px2/2eEhhUS+FMfbHAlD28x00jRgAAACW0GaQjwhkymEVwArOUkEOhoFqiELtH8wgecFLiUq6WqmwAP7iGEwbYzfnHacfqUNXAfD+CGR2ap0lAHL25ipuYtd5j2O0PU/MpaWPG/n2y5OkfTzaOpotaR5tWjN55B2XblVVqsFfBC/mvsiPvCBWUHFChacdY5whj5mP5rqQ0dqLJCsWjrs4TWnIbL2V/Iwfj3hwI35jfo1JkTOeR+8GhOdma9rgiKWafCbQyhYMTDmVdvhND60Flm97EDSTjF0OC+0gD9b8Yn4tNeHipCa/aWyt0n79bMmjfcjntBCPjrcB5ecRTpfGHbEHy1IRj2cjkGXKC+VYoYJXBp4rd4cMd8ygLCk5nBSd8/cTaKNRjdBscOeTXG6QEjSxj9/2pVwx9DMRVtWQR0BSaAcQcZ8W2KPSaeRC4QwmNMu2xx25CSyrDiq2rFSK/JJtmvoIjAKq0ciEXoOgw+Ke+Ylb7ULKCS3k1p/613UNRp450uSq5b7CAHo7S0b7fBMLfNmwSjRYEhLlo0HUaRe/I+IX2Z6XdZH9Hty/399ZA1PwZGC6EfvUJIf7CBeaxv7cu6IT2/s0zPRGthpvXpYw6A7P4Wwz5C4V98KnIUNUanadqabKP6eXWhvbvcQHxAjiOOiKZgXZplZW2g+B2NNyJSLiR+g48DqvWR6t9S2aGfFjdOW1Gi6oTtZ1d4p5XIslAr8mryeZ6+htSSQe4AcfVt7k+V6mOthBCYtr/LEU4ZHtl0mW9876PK8mRFAaT8DJOUFVz1lPfzRApuPggkkyq+UMvyfKTUbCk7/DpfX8Y4s4QAAAg9BmmNJ4Q8mUwIr/wAsWUPjZw3ksgRsxZ6n4fQjprPbkj2aUh30y0bZJnLmiXnWskvOGnCPwBnG9dEhatwX3hoxk7BNyG+wQ4emZUpcVzcWl2T9nKQB1euucuZWHTg7TCtM/iHyfPO2vbmGsfzs70b/egIbywUH4y4BQSL1nWc1SmpHm2zHMBcUjYLDZ5gL5vdfxn0V8FFw66G88c/LN4I5icUa7xf4fcSBKywU0ajbp1P+aJYjBgWT6Ggu0MDLDNl54tfqd42lKosQtM1aif4WXAZFP5Ww3vrQ1rH9+utSYxqZd6N6gGtNbSNMcViaKn5LcnjsbBi3T3EmGqshEbcme8VHKwR3kSfBOAprrIsv6K8R+X6az+MD23rWka/2v64m1qM69D7Xa+Kcs/n0KLCJdTilyaGadopLeaAn3eYvWTeHcucMM1Fp1KgHD1tiFeO6HvobLkZlRximsA3/7MiohYklLIcJrZL22BH+6W9d6kZsYIsej9RM681nU6mWNjepBAfAfTbrGRrVB/h2DxC5B8YyRjgSIzQjNYrse0rzChqbrsLl7mQ7W+1bsNKze5//9ZIa8rSsF+BXh/vgoRTDkPW/ws95B7VPCZEFChfX0icw+tpcpN/q7NY87tUn4vESdSiMMlyhKklMjQu/G51J69ZRQLs2oUO6YfoJFqliy4qCFCrf8SZE9Fc6DcCagAAAAodBmoRJ4Q8mUwIr/wArPWF/KOw78THwadfPqhJO0CnmR/M74/XYZLqVYKlNcEaYauf+vrRUDJPmu75sMKy2Y+Bnslc/iAISSyWtw/h/3CF8fE5ZrbrwSNst+MSyCoNWP+8imtoX2eyojpdCk8YP5K+cbK4SJPCkZXbYqSXYk7hO8AdSemBHgXKWiZ+UOr802aJo+98ZOIjX9hWL9bo31Gqx7cy4ZG+W/ar/WGlzDa1xPWnPRsEdrIcZlEVGV/jGmbirkxw1lyUYoqj8Vv7Bxube9XPQlBkXOV6Lc1LT2IzNq0V7WwVhF0kA6yxfAsFxc9krNEH8vGGntTWI608ovjatXc/CKKXw7AjJSftlTcLI0hIIGXbRUr0NCYNp7M4cVd/n73Rjetnixz4SAKpcz/P47UsijZG7T3SxzK2D79WS42aEalc12hQwCZ01LfmF/H2mmGEvOzPBie1D0YT7Jh19vxa4Dd3SQ1FrDfmSUpvv4DjbYcZ2PrPpFpWtMjWqHBeoyMiZf6RP3EfYR6z9jsVNIIHxM0bzzBQF8eeYkPgDySydxPXv9Izo+QUY94N8kWi16fI6eZSDc1G0Yo0L91jcRQuDMGGS7B2zuf/0GbJyRhUO48UbMrqnILMrbQg1LF00Q3pH9nbGEK/RRQpRN3T/J/4IZQjwW2Ft2ipWGztg1Jn9I4DmffKS60QC+JQcyakdVON6zDcKttIKlqeTcmAi4xzmo4QXa2dRKleS+fs3EtTdBBtony2wK9T2Imj+NCziOSEL7Q7VuIU8kclUHrJJsSneFcxGRgIgGGUEQM8/pklwTOqab7mMmJeRiaBrjJDEnDpkR4Vz3qXxgyn4/5x24FuTMNVPwQAAAhtBmqVJ4Q8mUwIr/wApcLwPT0/Xh9UdWqWXIs8Wbj5K1hivmN6qIQnq+aolcegdlM/63MbHsdC6xYZC1e/Q8UjQCt9N/Ejqwms8DzeWv2qxskeliZH0kt1QWkErWSEodq7V0ZNksctLkMGWayX33gBT368EehfIeGDolBZoqIbJfb4nqcfU+ev4OzVv9zVqWyLck315GFmXxQKIM8pICQc8Q5es34LH1+DmnMnW8kQpVGrztQcDXhjCU3F0fOgoSsXSVWCjc6XKqGbCwQDfJUxCfXfIT6YmQoPpVp1mpGy1wQypXus9z0bScDpyDu23hViYDntdj1O45ea0znKZkj1+tLHbBtqAGJ1WTcbGlF6Vya6hQhEsiiZUIC2fRxIj8/wEXCICIbr0gZ/m6gcOhE10tenvE7iy+BKY81wLWrnzos3S6FWxYtmCRes+LLhNGOKWRuQo6SyePH2OZ90xZm8oA1MuTe3V59euVNxjAt0FLkAc9TEiFhP/8CB+gA8mF+A8h1U01f4DVX55GzCH51jHI2xUS0L9GtsHoBxLPLK/NNel8zcnwG4X+UusfcfEb5hh+ffnXteCE9vRGbs2n9wYW0xA3ZicklfadmWKUtMiHYBfkMSULWnkBQr4CXxjpYOs6ygeEoA5+5B0B1SZObgZ42wWqddyyYE0NfwQAl75tfdJGqOa7OMHwBYNeatJaJK0zT2+bFaw2qWCWwAAAitBmsZJ4Q8mUwIr/wAstkdsayRXchoFk703izqzduZ5WsyXriI9cfUdMUWvm0iGHwYIrUujvz3Yjou+JLwv9df2kt7MJo8u+3P5CjEKbwlz4vkE5AHTAbgXn3+Xc/MMJLgW5cm7iX3KiGNnBpbphhwJRlb3u91NRDr0d1IR2up/z7lKxE7XPAPFe0siPMYVlIqWNSn5KqLABPeuxxbOsvMEb27/nH1LUVM8I2F95c1I3Lv1SpkhZXjs1JsmS9X7gsoTxkXyShGC2+zRJSGUbhCPo/q1XSFMHQyMWJ79FKPQSL/RpVsacN2bYwdKo4TFBw1SsKq/L1iOmqMI+4Gxnbbjojdk0ek0JIcDb4bHv1czxchF7FX1Ym8H6IpPuE8CeNKjzQ1a1wqhEu+wl1N0x3Y37ZryCCKJRkxj0FT7bOoH3L38/yMUuh/v3aCmxY4eCkykb2p6ZrYMFE044anM/nMjmbErMibfRFuCz58Io1rBlF7JfkIz0R2/5vjUMVskcdbX2mm7DntncOsWDIdg/XVmgsC9CzVzUyq4VsS/sk97lJggcddpWLNw/29egz8iLyzWHOAXCvl2fTIPkviYAOQXfVhZUQdxsyJUNFMTiALrZCmoQLMp2LmDbfbW8JQriDeR3fVz6P1sjT8C2yEDvzkCn7sh0aTBK+sx7BKH1nb4320+caQepQj4TCJtCeNXjdrVcNEnjvwlcRJwFT1pT+Y7HREbHnT71XYNh4EAAAGEQZrnSeEPJlMCK/8AKIjxcI58rm/ML255fOJW1zbznFna7lfgMQrka7OTPPsvVAV4EJXye/Uxiu9dlftmRypJqfDot3xwDe8lX/qAVf6pBkSlUsaLyBYtww/SUSa1bGl1JvrJCN7FXCCXbLd5R4PoYlPiDIm/DQH2puO0StIWmrR77Isc/J1pRvdu5+mQa/n0SEHUeM2KkoRzCznfD9zaaRO7BDtvC9SYIT0uYZxrwTjxQ7N7UERTrYG0P+vRLAhxkfohFIYl3HXyjPOvnlbUFP2oiiy6nkUFuaIyQcJawJv3GU8k4ObcKsC1cNDXjSpsyQRrxLFaCCjke4mikyt7vs0iN0bnrNWv9HXruG9zOFEOer1ggIFTsT1Eos5CXRkgja5HN4QUM6MhWpc5du/HgBIH8ANFcoo2kJpqcadw9r/0qk25X91MQSDJQiH8Hny2dQhqR+LFWEawiW753SJhn0ngZcv/mPj3mwcHv1SL9ErBqAjm4JGiDetPKYtFwANYY11OyQAAAVdBmwhJ4Q8mUwIr/wArOx5HV2505jRePGgMxptW4PGIHEszV1xGZS+flSkF+aq30AaqO7u6XK9jJsuWXTfYCRQTn1bZfFQ22DbO5DXAxK/TUmbQleCflFzeS6/czxkL4PJ8AwOs2U+oehekgCZC8gZyHHaQSaKbNJ46gTjNsLy84ACQ5uNt11TPuCPqPTuh+schdw9S+/lU/6m+EyaqGZ49wDFPiBFBYXglQQBjyP9k/rqq0xL7SiLjpe4riYg8SFUuUtOzPdWHyvxnI7Ug/0VLPGAAhgMISUnqe01d5QFf36yHpwMAHexjAZFIGQHAFautuMuEw6HzUZVzNdeHYxvEYOGkTo007bLwbuf/nxzrywGOxlRTYJLRdYI0mk0SdN3+LeTv1RIJwv21+e9rT5iFOTCgzeQoekEWXLYz0X8YLq5bVCtijP7/T7w1Ck71j0aqfrEn6wtIAAABNUGbKUnhDyZTAiv/ACcySi7VBgOid6qZNXvhh/JsllHkMLLq0yNbQTqv/Wk2EBoSKICZwFwAD0WRzhvvReCGirep1Fe4bxjm49/UR+OYrXRmHR18T0C83AUVeBk7KvDZmb/eHzuzEN4yfXucr/NWFJl+USVMY4r4UQ9CayrfEY9v6AQ6mzAdLy2UMfFxrRJ99g/Rfl8qx+m4jIZNjlrTaThzJ/3OpVmAliDfxVyg8+CVIlI31IykiwQrXcebgajG+av8XU1SfyAG5ibvwbtdSAxkGBcJWL387V+uTdY56w3KN2vBtoQpVKD2zb3yazIcATZ02upwIytNcM/rpaLCdMb1myWcikE25agzLhDhOS+4zwjYz2DnW6VY0gFBAPsphhsUMnauVVdUVHzCTSdvzEve/H8q4AAAAVdBm0pJ4Q8mUwIr/wAo+x5XKuiN1am7SkJKSMonFZDPU3f5XFcDQSs0FLVq2idfsKwuIkt1mxIq8NgMHpzofTnDHqs/WedvAmhBgL0N5azdQa5MNKG2rJ4IAvGQY/uFm3jKQAKzvhSS01gO1oIfizF817z9IShS4QK2WT0PeFPELqLSpED8eNOpVTR96vmwpk/WBKRVJdTQJzjiCQ5pgEwjtvk7KqoS0+lwXSbvIrXkYm8DignEts3DLNoLHrPjXlQmbIop76JZSyJEtB+91GrLwo6Km5GeebyA2E6qGL3xSkpppej/ruoFprSKrH60UMbrq/SK7eCo+1QFoySPQmqDFsMGiQFqvtld5BXDYdVI4yRaoyN7Y7wi83HRC6eVazuHU9OtIY3xJJApBWq1aJOsYwc38aTC3ee863Aa/4n9Lk4DAtyFYHNZjB5m2e2vk8G2Gny9YFlBAAABQEGba0nhDyZTAiv/ACoZSZQfHxhfQxEqOBQrP+L3DmgvHSJQtB1iVkcLTxm+vagLHBLG91OGnopwrr7gT/loDypIhoRxjcwAAOeg/jN4WBbXzCJtnWGGllUCSdtUZQzKOSp9iM4yX18C6jrY4Sq6R9PUV/lEGNveJR4gw4FMve7110XdEPL1O2VTdHvdqeANyaq0nLdEmtXnrzvdrFlBaUvmaR4EdlkqGkvkZKWJej8Vq+msbKa7JdbxjwZtRufiyGfD/NVqMgSrYRzw9z/a8Zwbr+9+19CxlWD5bCuAEfPmjY6kZJE2L/CQI6+tnCBTXOmWZtZMBoCLGOf7G2uAC3+kFlboh9as5WCkO6+iqXq29dyhKnsHInorRYsPlgxIXyU1Om/Kyhj1DJV0Am9WJK3Dln0zNUH0q6ZTOnZcFD36AAABYkGbjEnhDyZTAiv/ACcwdIOLRFfoGK2ZkKsvgMwG0m0qsY0vMLPSzefc+ebp/aztyF7MlsBz/fBeNtxFBcsKgR4pf65GvdfOMHah0ltZ918sMDmXUEZMeRHy/xpnWpTLeGz6uTs/7MATPmU5BgHbT/DkD8QeaZnFAzidyFCXDz2l/jaKhEdgqipbB2pH0+fQ039r05z9axxEWGmaLQjg6x9+po1o24yhkVO7m03YwWmPyCgy8cOwrvRyJkXJpRN4m8ZBS1zwY80HeN/VyMQQJSMwsTo7R1XMerSFuyx0nz+8qOuhiqykc2ohCCsXia/+kIKbJ5Vs+cbWtvkqBKIDSfU7FhAd3GjcY/xar0EVmi6wWFTugAogR3I7mTrQDdlTAqYgqO7Gn5NMXQVHu2i1zhFSdo9GjMbeGnbkJwsFbQ2XkoKRIDpuW7AewC9AEBt0Ox/Ah6dGXfXO1jl8pEApj2RFmgAAAPlBm61J4Q8mUwIr/wAlR+eW/VZ7bSrmwwMA62G05DZ7p/5FUugsSsQdonUq6abtbU5hjFr+I1lPgoiV5c3CkTQZS+K5zivdo+Ti2P4K90xXANp8dSMAu85uJIOCQn2TXbEnNDifLB+3V84ht5tj4lvTaZx317BcliV8D5v2zZQW8RO1mUbuJEBItst8E7hfE+ZXj7tfDxNZPTvtpFyUv0fH1cTg1pr2VLy0d0zQLiA58dg+GkRvR1/hs2LyifBgHcj6eTWz0vsypVn9iPXRH/unJ6i8cfFL69NO24tQ9QQB+nDFhoP2cRhkAvhHwn56n5PppBD/oxni2f8AAAE9QZvOSeEPJlMCK/8AJjAXVGf+Kj2XNJnFeKC/gr7dJDTC2ngpd4WeAHlg04GuJKnn9hAmiECxxo9qM1IYMRiB85t6gALnlm9sRqGmioyzAm18RJndc9Ah8RlpGzr+44a6ntRaPx0cIwNIWAA8buL2JP00dmfjNqEiAlCa8OdV8FQxjp1vDXsGcAGF3Qbd62KEpkimeI3wH2nuXpbDHm8/ZKOR49s5ifUCkxCoJpfp43aC0lTzh2NXpcfVw6h0QnK8G60R4ZAxOxaJB7c0nn8ixXSU2JVY24EtGMF53nxJnHfzUheewUfBOGYSxeo8oK7oUCqX4rztzDwoc2QywNqQUJUkFrqIN+sb5ecYvX24Zujn+ZzTW6UDAF3R6WdNyJyRAremgC8spSflTqygQNGfHyGkfIEEJJaFo/pBCBkAAAEWQZvvSeEPJlMCK/8AKI41fuekXG59Knbw4Y6YJritsh9VtQgc3QKvVmxrzzo7f4aXn8N74eyP4b2lV1Z2Q+rohxps7EHTkOY9jLdqxI3MXe7je4g2qepz71+hY+jYdX+9LO0kA0Zg3NfyAlIRX7k6c/YHAZNtNaGZgTBMqiPgmEjiJH9Luk7shbgr+srfwiYwBX9rdS3fQNNFwcT8orQC+F60LAY9+GbFo2Sw3Ld4Tw9jq9yJtrY8RtHAdzytyek/mv2+j2TbTvAQKbbCYtdC8E/KtR4V5ZTSScr5Wb63vmbw7UpddEXYvl55pARyyvMxWNSh3Li4GF8Jk5JBi5B5ASQwxCMYpX5hkAMc+d8tl2bT+IEvUTsAAAElQZoQSeEPJlMCK/8AJIAzFZs00JJ0yfm8CZiew4xWdArLklEvBVXo/+ukPLu3XP9HFOfsme3T6BJEKmPPgZw/Lxnraq6Sl2kLVW19YU1qmqgfv+80LkZaWU5gRAH4hqyo3bFYcbuY2SC3IW5Wm69gtYyAXOdbAYSEHA16fvCeRQjHEsxKVndJdrRAlrGHsKgUBQ3Up/ZXIy1vkdFOfKSjpuZnswkuqr8NZI5tJ/dnBSErBTNWPaNwWV7nNomC0EYVGo+geGBhLXzaLw0UAOCYGjiPc3803BDw1GLoLIXjrIFJxwRfBNIAXYZAglu30oYzhpAfRWSprkeULMWYJTlWvbUQ5CNewSZssuDWIRAc3w8AcFaywwn+YSGhtR8VI1OGjYkfBbcAAAD8QZoxSeEPJlMCK/8AJdokjCUETRw/nciVPtaZQSBP/VxAQSITASEzlJBl9Na1r0DJhLOz279+KQLtl/xHZ8vAKc528mTMTqtWs4sFbeVgHWyBpHcHEtgTzjIqEinp/MPuUXF5poo8YLSSMFn9Ozx2FbU5/Kh9A39oN9NHQflVxV1NA6yT/84HHyfMtfdSMS8KTvAEE2lDs14VQayNs5ctjXboQT7xMBf5OLj6thhPvgaDrFB2o/PV9ouK147lruWTP2mkoA9oDIMYW1pcBx4yyV/t9GOPZ3aXneMUb2fFmUCX43BjXfUDMaa4GO2/Ankj3UEQwDxA7ZlNUQK2AAAA4UGaUknhDyZTAiv/ACJHv33I08bkhybYiJ/JiiheW5zMPBu4n5CxGr3frhE7TkLh0vPktM8m/AhaDiJisdk5QXNe/4WmxEDSAyaVi4eUVu0iHT2ly/KNTGqiORqA2oKpTjh84nYbrpXwnGv9SOf/34Z06xN6Yo3t35UZrP8nlcs/63GtnEmnUwVZHBYfPM6bs5M5AeBfAQ/9mIqu7vnEst+5O2wpPjzdItjwGCZ2ApHVjGnYYFomlA9nm6AXnxNIWHIsDgxCk3zx+6QbXipu/CWLG1Wf0WIbt4C0JPVl3TEb0QAAAMlBmnNJ4Q8mUwIr/wAVV64OfTKmlktYOqZHH1W1DhPy/X/6sD4T6hRdzfOgNtTOX2IckRJHshfBQVkJIzns079io6kpJFCcS3VD4zrWCn/dNaGV0kWTpFBRuusfn8F0C0R/EhsQeyTsdZftEkLGb5tq+nrir3vfmeb7rjmWJRXkIrTEKu8pIuAd+4FBGp8ARgGe80Jqpp//s1433HqBFqXsIFJTmU8j/toF9HyueI1Ea4uvsQ6NANGcYCbOAKCmbNiwABMCFaiUTMAAAAPSbW9vdgAAAGxtdmhkAAAAAHwlsIB8JbCAAAAD6AAAAyAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAv10cmFrAAAAXHRraGQAAAAPfCWwgHwlsIAAAAABAAAAAAAAAyAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAY4AAAGGAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAMgAAAAAgABAAAAAAJ1bWRpYQAAACBtZGhkAAAAAHwlsIB8JbCAAAAAGQAAABRVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAACIG1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAeBzdGJsAAAAtHN0c2QAAAAAAAAAAQAAAKRhdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAY4BhgBIAAAASAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGP//AAAAMmF2Y0MBZAAV/+EAGWdkABWs2UGQz6mhAAADAAEAAAMAMg8WLZYBAAZo6+PLIsAAAAAcdXVpZGtoQPJfJE/FujmlG88DI/MAAAAAAAAAGHN0dHMAAAAAAAAAAQAAABQAAAABAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAYY3R0cwAAAAAAAAABAAAAFAAAAAIAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAZHN0c3oAAAAAAAAAAAAAABQAAA05AAACqQAAAl8AAAITAAACiwAAAh8AAAIvAAABiAAAAVsAAAE5AAABWwAAAUQAAAFmAAAA/QAAAUEAAAEaAAABKQAAAQAAAADlAAAAzQAAAGBzdGNvAAAAAAAAABQAAAAsAAANZQAAEA4AABJtAAAUgAAAFwsAABkqAAAbWQAAHOEAAB48AAAfdQAAINAAACIUAAAjegAAJHcAACW4AAAm0gAAJ/sAACj7AAAp4AAAAGF1ZHRhAAAAWW1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAALGlsc3QAAAAkqXRvbwAAABxkYXRhAAAAAQAAAABMYXZmNTIuMTExLjA=\">\n\n\n\n## External sites\n\nYou can even embed an entire page from another site in an iframe; for example this is today's Wikipedia\npage for mobile users:\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('https://jupyter.org', width='100%', height=350)\n```\n\n\n\n\n\n\n\n\n\n\n## Links to local files\n\nIPython provides builtin display classes for generating links to local files. Create a link to a single file using the `FileLink` object:\n\n\n```python\nfrom IPython.display import FileLink, FileLinks\nFileLink('Cell Magics.ipynb')\n```\n\n\n\n\n<a href='Cell Magics.ipynb' target='_blank'>Cell Magics.ipynb</a><br>\n\n\n\nAlternatively, to generate links to all of the files in a directory, use the `FileLinks` object, passing `'.'` to indicate that we want links generated for the current working directory. Note that if there were other directories under the current directory, `FileLinks` would work in a recursive manner creating links to files in all sub-directories as well.\n\n\n```python\nFileLinks('.')\n```\n\n\n\n\n./<br>\n&nbsp;&nbsp;<a href='./Animations Using clear_output.ipynb' target='_blank'>Animations Using clear_output.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Background Jobs.ipynb' target='_blank'>Background Jobs.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Beyond Plain Python.ipynb' target='_blank'>Beyond Plain Python.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Capturing Output.ipynb' target='_blank'>Capturing Output.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Cell Magics.ipynb' target='_blank'>Cell Magics.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Custom Display Logic.ipynb' target='_blank'>Custom Display Logic.ipynb</a><br>\n&nbsp;&nbsp;<a href='./example-demo.py' target='_blank'>example-demo.py</a><br>\n&nbsp;&nbsp;<a href='./Index.ipynb' target='_blank'>Index.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Input in the Notebook.ipynb' target='_blank'>Input in the Notebook.ipynb</a><br>\n&nbsp;&nbsp;<a href='./ipython-completion.bash' target='_blank'>ipython-completion.bash</a><br>\n&nbsp;&nbsp;<a href='./ipython-get-history.py' target='_blank'>ipython-get-history.py</a><br>\n&nbsp;&nbsp;<a href='./ipython-qtconsole.desktop' target='_blank'>ipython-qtconsole.desktop</a><br>\n&nbsp;&nbsp;<a href='./ipython.desktop' target='_blank'>ipython.desktop</a><br>\n&nbsp;&nbsp;<a href='./Plotting in the Notebook.ipynb' target='_blank'>Plotting in the Notebook.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Rich Output.ipynb' target='_blank'>Rich Output.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Script Magics.ipynb' target='_blank'>Script Magics.ipynb</a><br>\n&nbsp;&nbsp;<a href='./SymPy.ipynb' target='_blank'>SymPy.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Terminal Usage.ipynb' target='_blank'>Terminal Usage.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Third Party Rich Output.ipynb' target='_blank'>Third Party Rich Output.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Working With External Code.ipynb' target='_blank'>Working With External Code.ipynb</a><br>\n./.ipynb_checkpoints/<br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Beyond Plain Python-checkpoint.ipynb' target='_blank'>Beyond Plain Python-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Plotting in the Notebook-checkpoint.ipynb' target='_blank'>Plotting in the Notebook-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Rich Output-checkpoint.ipynb' target='_blank'>Rich Output-checkpoint.ipynb</a><br>\n./data/<br>\n&nbsp;&nbsp;<a href='./data/flare.json' target='_blank'>flare.json</a><br>\n./gui/<br>\n&nbsp;&nbsp;<a href='./gui/gui-glut.py' target='_blank'>gui-glut.py</a><br>\n&nbsp;&nbsp;<a href='./gui/gui-gtk.py' target='_blank'>gui-gtk.py</a><br>\n&nbsp;&nbsp;<a href='./gui/gui-gtk3.py' target='_blank'>gui-gtk3.py</a><br>\n&nbsp;&nbsp;<a href='./gui/gui-pyglet.py' target='_blank'>gui-pyglet.py</a><br>\n&nbsp;&nbsp;<a href='./gui/gui-qt.py' target='_blank'>gui-qt.py</a><br>\n&nbsp;&nbsp;<a href='./gui/gui-tk.py' target='_blank'>gui-tk.py</a><br>\n&nbsp;&nbsp;<a href='./gui/gui-wx.py' target='_blank'>gui-wx.py</a><br>\n\n\n\n## Rich output and security\n\nThe Jupyter Notebook allows arbitrary code execution in both the IPython kernel and in the browser, though HTML and JavaScript output. But because Jupyter has a JavaScript API for running code in the browser, HTML and JavaScript output can actually send code to run in the kernel. So be careful what you're displaying!\n\nThe Notebook has a security model to protect you from outputs running code as soon as you open a notebook. Here is a short summary:\n\n* When you run code in the Notebook, all rich output is displayed.\n* When you open a notebook, rich output that might compromise security is not displayed.\n* If you have trusted a notebook by running all the code, it can display rich output when you open it again.\n\nA full description of the IPython security model can be found on [in the Jupyter Notebook documentation](http://jupyter-notebook.readthedocs.io/en/latest/security.html).\n\n## Rich output and nbviewer\n\nMuch of the power of the Notebook is that it enables users to share notebooks with each other using http://nbviewer.jupyter.org, without installing Jupyter locally. Notebooks rendered on nbviewer will display all output, including HTML and JavaScript. Furthermore, to provide a consistent JavaScript environment on the live Notebook and nbviewer, the following JavaScript libraries are loaded onto the nbviewer page, *before* the notebook and its output is displayed:\n\n* [jQuery](http://jquery.com/)\n* [RequireJS](http://requirejs.org/)\n\nLibraries such as [mpld3](http://mpld3.github.io/) use these capabilities to generate interactive visualizations that work on nbviewer.\n", "meta": {"hexsha": "9d671211963a71e05badc87dce541b9140e671fc", "size": 363639, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "IPython Kernel/Rich Output.ipynb", "max_stars_repo_name": "minrk/resbaz-2017", "max_stars_repo_head_hexsha": "c2583b8ce4d9daffc4da62b3515ee7ec83923025", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-01-30T14:31:40.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-31T06:43:57.000Z", "max_issues_repo_path": "IPython Kernel/Rich Output.ipynb", "max_issues_repo_name": "minrk/resbaz-2017", "max_issues_repo_head_hexsha": "c2583b8ce4d9daffc4da62b3515ee7ec83923025", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IPython Kernel/Rich Output.ipynb", "max_forks_repo_name": "minrk/resbaz-2017", "max_forks_repo_head_hexsha": "c2583b8ce4d9daffc4da62b3515ee7ec83923025", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 249.9237113402, "max_line_length": 168651, "alphanum_fraction": 0.9052329371, "converted": true, "num_tokens": 62422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11757213354550883, "lm_q2_score": 0.10374862132405094, "lm_q1q2_score": 0.012197946761473741}}
{"text": "# Setup\n\n\n```python\n%matplotlib inline\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\n```\n\n\n```python\ndata = pd.read_csv(\"articles_2017-09-01_2017-09-30.csv\", index_col=\"id\", \\\n                   parse_dates=[\"published\", \"discovered\"])\ndata.head()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>publisher_name</th>\n      <th>publisher_id</th>\n      <th>mins_as_lead</th>\n      <th>mins_on_front</th>\n      <th>num_articles_on_front</th>\n      <th>fb_brand_page</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>171a1db515d4d4f81e9cdaefacdb8dba16c93b75</th>\n      <td>https://www.economist.com/news/middle-east-and...</td>\n      <td>Kenya\u2019s high court annuls the presidential ele...</td>\n      <td>2017-09-01 14:15:09.267</td>\n      <td>2017-09-01</td>\n      <td>312</td>\n      <td>15.020862</td>\n      <td>2017-09-01T18:48:02.383Z</td>\n      <td>51</td>\n      <td>177</td>\n      <td>84</td>\n      <td>The Economist</td>\n      <td>economist_com</td>\n      <td>0</td>\n      <td>10099</td>\n      <td>33.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>1825</td>\n    </tr>\n    <tr>\n      <th>ea4e6959acdbcf288c76f9d25ac6baefb6410463</th>\n      <td>http://www.foxnews.com/us/2017/08/31/atlantic-...</td>\n      <td>Atlantic hurricane season 2017: What you shoul...</td>\n      <td>2017-09-01 00:15:08.851</td>\n      <td>2017-09-01</td>\n      <td>85</td>\n      <td>0.484001</td>\n      <td>2017-09-01T01:30:01.288Z</td>\n      <td>7</td>\n      <td>32</td>\n      <td>46</td>\n      <td>Fox News</td>\n      <td>foxnews_com</td>\n      <td>0</td>\n      <td>599</td>\n      <td>86.0</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>285</td>\n    </tr>\n    <tr>\n      <th>65b41c17cbc8fe96f2eb7d3d8086fbefa0a03cf7</th>\n      <td>http://www.telegraph.co.uk/travel/ski/resort-g...</td>\n      <td>Laax: piste guide</td>\n      <td>2017-09-01 13:21:00.323</td>\n      <td>2017-09-01</td>\n      <td>1</td>\n      <td>0.000000</td>\n      <td>2017-09-01T13:34:01.749Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>The Telegraph</td>\n      <td>telegraph_co_uk</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>370</td>\n    </tr>\n    <tr>\n      <th>cf3c6ce8b392031a436a585ec7ffc2c1f94729c1</th>\n      <td>http://www.telegraph.co.uk/travel/ski/resort-g...</td>\n      <td>Laax: restaurants and entertainment</td>\n      <td>2017-09-01 13:21:02.106</td>\n      <td>2017-09-01</td>\n      <td>1</td>\n      <td>0.000000</td>\n      <td>2017-09-01T13:34:01.753Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>The Telegraph</td>\n      <td>telegraph_co_uk</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>370</td>\n    </tr>\n    <tr>\n      <th>96854242b80f8ea0c960c8a3c1b19f1f27d82db6</th>\n      <td>http://www.telegraph.co.uk/travel/ski/resort-g...</td>\n      <td>Ski Laax: resort guide</td>\n      <td>2017-09-01 13:21:02.491</td>\n      <td>2017-09-01</td>\n      <td>2</td>\n      <td>0.000000</td>\n      <td>2017-09-01T13:34:01.755Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>The Telegraph</td>\n      <td>telegraph_co_uk</td>\n      <td>0</td>\n      <td>0</td>\n      <td>NaN</td>\n      <td>False</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>370</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n# Response Score\n\nThe response score is a number between 0 and 50 that indicates the level of response to an article.\n\n\n\nPerhaps in the future we may choose to include other factors, but for now we just include engagements on Facebook. The maximum score of 50 should be achieved by an article that does really well compared with others.\n\n\n```python\npd.options.display.float_format = '{:.2f}'.format\ndata.fb_engagements.describe([0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count    152658.00\n    mean       1315.77\n    std        9625.56\n    min           0.00\n    50%          26.00\n    75%         266.00\n    90%        1717.00\n    95%        4658.00\n    99%       24236.33\n    99.5%     42666.43\n    99.9%    114308.39\n    max     1143483.00\n    Name: fb_engagements, dtype: float64\n\n\n\nThere's a few articles there with 1 million plus engagements, let's just double check that.\n\n\n```python\ndata[data.fb_engagements > 1000000]\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>publisher_name</th>\n      <th>publisher_id</th>\n      <th>mins_as_lead</th>\n      <th>mins_on_front</th>\n      <th>num_articles_on_front</th>\n      <th>fb_brand_page</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>a85688580da47024b77bb7e8718eb06ebbda917a</th>\n      <td>https://www.nytimes.com/2017/09/07/us/harvey-i...</td>\n      <td>Harvey and Irma, Married 75 Years, Marvel at t...</td>\n      <td>2017-09-07 19:33:01.260</td>\n      <td>2017-09-07 19:32:07</td>\n      <td>1143483</td>\n      <td>1005.42</td>\n      <td>2017-09-08T01:59:59.960Z</td>\n      <td>45548</td>\n      <td>956285</td>\n      <td>141650</td>\n      <td>New York Times</td>\n      <td>nytimes_com</td>\n      <td>0</td>\n      <td>0</td>\n      <td>nan</td>\n      <td>True</td>\n      <td>14529828.00</td>\n      <td>2017-09-07T20:25:01.000Z</td>\n      <td>120</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndata.fb_engagements.mode()\n```\n\n\n\n\n    0    0\n    dtype: int64\n\n\n\nGoing back to the enagement counts, we see the mean is 1,315, mode is zero, median is 26, 90th percentile is 1,717, 99th percentile is 24,236, 99.5th percentile is 42,666. The standard deviation is 9,625, significantly higher than the mean, so this is not a normal distribution. \n\nKey publishers stats\n\n\n```python\ndata.groupby(\"publisher_id\").agg({'url': 'count', 'fb_engagements': ['sum', 'median', 'mean']})\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th>url</th>\n      <th colspan=\"3\" halign=\"left\">fb_engagements</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>count</th>\n      <th>sum</th>\n      <th>median</th>\n      <th>mean</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>8</td>\n      <td>28818</td>\n      <td>3320.50</td>\n      <td>3602.25</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>12116</td>\n      <td>12265072</td>\n      <td>37.00</td>\n      <td>1012.30</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>2472</td>\n      <td>11792580</td>\n      <td>263.50</td>\n      <td>4770.46</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>62</td>\n      <td>49203</td>\n      <td>291.50</td>\n      <td>793.60</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>2026</td>\n      <td>7582843</td>\n      <td>163.00</td>\n      <td>3742.77</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>3444</td>\n      <td>20150473</td>\n      <td>655.00</td>\n      <td>5850.89</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>23716</td>\n      <td>17973676</td>\n      <td>28.00</td>\n      <td>757.87</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>522</td>\n      <td>174870</td>\n      <td>44.00</td>\n      <td>335.00</td>\n    </tr>\n    <tr>\n      <th>evolvepolitics_com</th>\n      <td>132</td>\n      <td>222865</td>\n      <td>537.00</td>\n      <td>1688.37</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>6191</td>\n      <td>18136364</td>\n      <td>41.00</td>\n      <td>2929.47</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>3250</td>\n      <td>347966</td>\n      <td>9.00</td>\n      <td>107.07</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>10566</td>\n      <td>20805259</td>\n      <td>11.00</td>\n      <td>1969.08</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>6127</td>\n      <td>10609711</td>\n      <td>48.00</td>\n      <td>1731.63</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>517</td>\n      <td>1682810</td>\n      <td>160.00</td>\n      <td>3254.95</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>3883</td>\n      <td>2086707</td>\n      <td>82.00</td>\n      <td>537.40</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>134</td>\n      <td>2698</td>\n      <td>10.00</td>\n      <td>20.13</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>10010</td>\n      <td>8262666</td>\n      <td>48.00</td>\n      <td>825.44</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>1710</td>\n      <td>5260240</td>\n      <td>523.00</td>\n      <td>3076.16</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>749</td>\n      <td>232068</td>\n      <td>11.00</td>\n      <td>309.84</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>1986</td>\n      <td>6582394</td>\n      <td>179.00</td>\n      <td>3314.40</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>4934</td>\n      <td>19844645</td>\n      <td>216.00</td>\n      <td>4022.02</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>268</td>\n      <td>94214</td>\n      <td>135.00</td>\n      <td>351.54</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>39</td>\n      <td>142388</td>\n      <td>480.00</td>\n      <td>3650.97</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>6047</td>\n      <td>1682993</td>\n      <td>16.00</td>\n      <td>278.32</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>2137</td>\n      <td>2641695</td>\n      <td>390.00</td>\n      <td>1236.17</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>114</td>\n      <td>36440</td>\n      <td>190.50</td>\n      <td>319.65</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>7376</td>\n      <td>3943188</td>\n      <td>26.00</td>\n      <td>534.60</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>344</td>\n      <td>359005</td>\n      <td>346.00</td>\n      <td>1043.62</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>8567</td>\n      <td>10717627</td>\n      <td>135.00</td>\n      <td>1251.04</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>9147</td>\n      <td>329695</td>\n      <td>1.00</td>\n      <td>36.04</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>23360</td>\n      <td>15896784</td>\n      <td>0.00</td>\n      <td>680.51</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>289</td>\n      <td>338151</td>\n      <td>41.00</td>\n      <td>1170.07</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>415</td>\n      <td>587343</td>\n      <td>97.00</td>\n      <td>1415.28</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\n\nnon_zero_fb_enagagements = data.fb_engagements[data.fb_engagements > 0]\n```\n\nThat's a bit better, but still way too clustered at the low end. Let's look at a log normal distribution.\n\n\n```python\nmean = data.fb_engagements.mean()\nmedian = data.fb_engagements.median()\nninety = data.fb_engagements.quantile(.90)\nninetyfive = data.fb_engagements.quantile(.95)\nninetynine = data.fb_engagements.quantile(.99)\n\nplt.figure(figsize=(12,4.5))\nplt.hist(np.log(non_zero_fb_enagagements + median), bins=50)\nplt.axvline(np.log(mean), linestyle=':', label=f'Mean ({mean:,.0f})', color='green')\nplt.axvline(np.log(median), label=f'Median ({median:,.0f})', color='green')\nplt.axvline(np.log(ninety), linestyle='--', label=f'90% percentile ({ninety:,.0f})', color='red')\nplt.axvline(np.log(ninetyfive), linestyle='-.', label=f'95% percentile ({ninetyfive:,.0f})', color='red')\nplt.axvline(np.log(ninetynine), linestyle=':', label=f'99% percentile ({ninetynine:,.0f})', color='red')\nleg = plt.legend()\n\n```\n\n\n```python\nlog_engagements = (non_zero_fb_enagagements\n                   .clip_upper(data.fb_engagements.quantile(.999))\n                   .apply(lambda x: np.log(x + median))\n                  )\nlog_engagements.describe()\n```\n\n\n\n\n    count   123953.00\n    mean         5.07\n    std          1.79\n    min          3.30\n    25%          3.56\n    50%          4.47\n    75%          6.14\n    max         11.65\n    Name: fb_engagements, dtype: float64\n\n\n\nUse standard feature scaling to bring that to a 1 to 50 range\n\n\n\n```python\ndef scale_log_engagements(engagements_logged):\n    return np.ceil(\n        50 * (engagements_logged - log_engagements.min()) / (log_engagements.max() - log_engagements.min())\n    )\n\ndef scale_engagements(engagements):\n    return scale_log_engagements(np.log(engagements + median))\n\nscaled_non_zero_engagements = scale_log_engagements(log_engagements)\nscaled_non_zero_engagements.describe()\n```\n\n\n\n\n    count   123953.00\n    mean        11.12\n    std         10.73\n    min          0.00\n    25%          2.00\n    50%          8.00\n    75%         18.00\n    max         50.00\n    Name: fb_engagements, dtype: float64\n\n\n\n\n```python\n# add in the zeros, as zero\nscaled_engagements = pd.concat([scaled_non_zero_engagements, data.fb_engagements[data.fb_engagements == 0]])\n```\n\n\n```python\nproposed = pd.DataFrame({\"fb_engagements\": data.fb_engagements, \"response_score\": scaled_engagements})\nproposed.response_score.plot.hist(bins=50)\n```\n\nLooks good to me, lets save that.\n\n\n```python\ndata[\"response_score\"] = proposed.response_score\n```\n\n### Proposal\n\nThe maximum of 50 points is awarded when the engagements are greater than the 99.9th percentile, rolling over the last month. \n\ni.e. where $limit$ is the 99.5th percentile of engagements calculated over the previous month, the response score for article $a$ is:\n\n\\begin{align}\nbasicScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   \\log(\\min(engagements_a,limit) + median(engagements))      & \\text{if } engagements_a > 0\n\\end{cases} \\\\\nresponseScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   50 \\cdot \\frac{basicScore_a - \\min(basicScore)}{\\max(basicScore) - \\min(basicScore)}       & \\text{if } engagements_a > 0\n\\end{cases} \\\\\n\\\\\n\\text{The latter equation can be expanded to:} \\\\\nresponseScore_a & = \n\\begin{cases} \n   0 & \\text{if } engagements_a = 0 \\\\\n   50 \\cdot \n   \\frac{\\log(\\min(engagements_a,limit) + median(engagements)) - \\log(1 + median(engagements))}\n   {\\log(limit + median(engagements)) - \\log(1 + median(engagements))}       & \\text{if } engagements_a > 0\n\\end{cases} \\\\\n\\end{align}\n\n# Promotion Score\n\nThe aim of the promotion score is to indicate how important the article was to the publisher, by tracking where they chose to promote it. This is a number between 0 and 50 comprised of:\n\n- 20 points based on whether the article was promoted as the \"lead\" story on the publisher's home page\n- 15 points based on how long the article was promoted anywhere on the publisher's home page\n- 15 points based on whether the article was promoted on the publisher's main facebook brand page\n\nThe first two should be scaled by the popularity/reach of the home page, for which we use the alexa page rank as a proxy.\n\nThe last should be scaled by the popularity/reach of the brand page, for which we use the number of likes the brand page has.\n\n### Lead story (20 points)\n\n\n```python\ndata.mins_as_lead.describe([0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count   152658.00\n    mean         9.02\n    std         89.37\n    min          0.00\n    50%          0.00\n    75%          0.00\n    90%          0.00\n    95%          0.00\n    99%        264.00\n    99.5%      564.71\n    99.9%     1240.72\n    max       7546.00\n    Name: mins_as_lead, dtype: float64\n\n\n\nAs expected, the vast majority of articles don't make it as lead. Let's explore how long typically publishers put something as lead for.\n\n\n```python\nlead_articles = data[data.mins_as_lead > 0]\n```\n\n\n```python\nlead_articles.mins_as_lead.describe([0.25, 0.5, 0.75, 0.9, 0.95, 0.99, 0.995, 0.999])\n```\n\n\n\n\n    count   4208.00\n    mean     327.33\n    std      430.79\n    min        4.00\n    25%       84.00\n    50%      174.00\n    75%      414.25\n    90%      839.00\n    95%     1113.25\n    99%     1656.90\n    99.5%   2172.34\n    99.9%   4612.71\n    max     7546.00\n    Name: mins_as_lead, dtype: float64\n\n\n\n\n```python\nlead_articles.mins_as_lead.plot.hist(bins=50)\n```\n\nFor lead, it's a  significant thing for an article to be lead at all, so although we want to penalise articles that were lead for a very short time, mostly we want to score the maximum even if it wasn't lead for ages. So we'll give maximum points when something has been lead for an hour.\n\n\n```python\nlead_articles.mins_as_lead.clip_upper(60).plot.hist(bins=50)\n```\n\nWe also want to scale this by the alexa page rank, such that the maximum score of 20 points is for an article that was on the front for 4 hours for the most popular site.\n\nSo lets explore the alexa nunbers.\n\n\n```python\nalexa_ranks = data.groupby(by=\"publisher_id\").alexa_rank.mean().sort_values()\nalexa_ranks\n```\n\n\n\n\n    publisher_id\n    bbc_co_uk                               96\n    cnn_com                                105\n    nytimes_com                            120\n    theguardian_com                        142\n    buzzfeed_com                           147\n    dailymail_co_uk                        158\n    washingtonpost_com                     191\n    huffingtonpost_com                     215\n    foxnews_com                            285\n    rt_com                                 365\n    telegraph_co_uk                        370\n    independent_co_uk                      386\n    reuters_com                            497\n    npr_org                                594\n    lemonde_fr                             618\n    mirror_co_uk                           706\n    nbcnews_com                            826\n    breitbart_com                          994\n    ft_com                                1596\n    economist_com                         1825\n    indy100_com                           5014\n    thetimes_co_uk                        6435\n    newstatesman_com                     12769\n    thecanary_co                         15686\n    propublica_org                       16066\n    yournewswire_com                     22568\n    order-order_com                      32515\n    anotherangryvoice_blogspot_co_uk     77827\n    westmonster_com                      97775\n    evolvepolitics_com                  119412\n    skwawkbox_org                       152475\n    libdemvoice_org                     344992\n    brexitcentral_com                   469149\n    Name: alexa_rank, dtype: int64\n\n\n\n\n```python\nalexa_ranks.plot.bar(figsize=[10,5])\n```\n\nLet's try the simple option first: just divide the number of minutes as lead by the alexa rank. What's the scale of numbers we get then.\n\n\n```python\nlead_proposal_1 = lead_articles.mins_as_lead.clip_upper(60) / lead_articles.alexa_rank\nlead_proposal_1.plot.hist()\n```\n\nLooks like there's too much of a cluster around 0. Have we massively over penalised the publishers with a high alexa rank?\n\n\n```python\nlead_proposal_1.groupby(data.publisher_id).mean().plot.bar(figsize=[10,5])\n```\n\nYes. Let's try taking the log of the alexa rank and see if that looks better.\n\n\n```python\nlead_proposal_2 = (lead_articles.mins_as_lead.clip_upper(60) / np.log(lead_articles.alexa_rank))\nlead_proposal_2.plot.hist()\n```\n\n\n```python\nlead_proposal_2.groupby(data.publisher_id).describe()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>25%</th>\n      <th>50%</th>\n      <th>75%</th>\n      <th>max</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>8.00</td>\n      <td>5.33</td>\n      <td>0.00</td>\n      <td>5.33</td>\n      <td>5.33</td>\n      <td>5.33</td>\n      <td>5.33</td>\n      <td>5.33</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>94.00</td>\n      <td>12.55</td>\n      <td>2.36</td>\n      <td>0.88</td>\n      <td>13.15</td>\n      <td>13.15</td>\n      <td>13.15</td>\n      <td>13.15</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>190.00</td>\n      <td>8.40</td>\n      <td>1.21</td>\n      <td>0.58</td>\n      <td>8.69</td>\n      <td>8.69</td>\n      <td>8.69</td>\n      <td>8.69</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>55.00</td>\n      <td>4.39</td>\n      <td>0.75</td>\n      <td>1.45</td>\n      <td>4.59</td>\n      <td>4.59</td>\n      <td>4.59</td>\n      <td>4.59</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>270.00</td>\n      <td>11.75</td>\n      <td>1.38</td>\n      <td>1.80</td>\n      <td>12.02</td>\n      <td>12.02</td>\n      <td>12.02</td>\n      <td>12.02</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>166.00</td>\n      <td>12.04</td>\n      <td>2.68</td>\n      <td>1.07</td>\n      <td>12.89</td>\n      <td>12.89</td>\n      <td>12.89</td>\n      <td>12.89</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>150.00</td>\n      <td>11.63</td>\n      <td>1.24</td>\n      <td>1.98</td>\n      <td>11.85</td>\n      <td>11.85</td>\n      <td>11.85</td>\n      <td>11.85</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>46.00</td>\n      <td>6.54</td>\n      <td>2.61</td>\n      <td>0.53</td>\n      <td>5.99</td>\n      <td>7.99</td>\n      <td>7.99</td>\n      <td>7.99</td>\n    </tr>\n    <tr>\n      <th>evolvepolitics_com</th>\n      <td>64.00</td>\n      <td>5.10</td>\n      <td>0.28</td>\n      <td>2.91</td>\n      <td>5.13</td>\n      <td>5.13</td>\n      <td>5.13</td>\n      <td>5.13</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>119.00</td>\n      <td>10.51</td>\n      <td>0.59</td>\n      <td>6.19</td>\n      <td>10.61</td>\n      <td>10.61</td>\n      <td>10.61</td>\n      <td>10.61</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>94.00</td>\n      <td>7.74</td>\n      <td>1.21</td>\n      <td>1.36</td>\n      <td>8.14</td>\n      <td>8.14</td>\n      <td>8.14</td>\n      <td>8.14</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>149.00</td>\n      <td>11.11</td>\n      <td>0.56</td>\n      <td>5.59</td>\n      <td>11.17</td>\n      <td>11.17</td>\n      <td>11.17</td>\n      <td>11.17</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>139.00</td>\n      <td>9.46</td>\n      <td>1.74</td>\n      <td>1.68</td>\n      <td>10.07</td>\n      <td>10.07</td>\n      <td>10.07</td>\n      <td>10.07</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>202.00</td>\n      <td>5.65</td>\n      <td>1.91</td>\n      <td>0.47</td>\n      <td>4.58</td>\n      <td>7.04</td>\n      <td>7.04</td>\n      <td>7.04</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>138.00</td>\n      <td>8.38</td>\n      <td>2.22</td>\n      <td>0.62</td>\n      <td>9.34</td>\n      <td>9.34</td>\n      <td>9.34</td>\n      <td>9.34</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>134.00</td>\n      <td>4.62</td>\n      <td>0.45</td>\n      <td>1.10</td>\n      <td>4.71</td>\n      <td>4.71</td>\n      <td>4.71</td>\n      <td>4.71</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>342.00</td>\n      <td>8.72</td>\n      <td>1.24</td>\n      <td>0.61</td>\n      <td>9.15</td>\n      <td>9.15</td>\n      <td>9.15</td>\n      <td>9.15</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>92.00</td>\n      <td>8.47</td>\n      <td>1.59</td>\n      <td>0.74</td>\n      <td>8.93</td>\n      <td>8.93</td>\n      <td>8.93</td>\n      <td>8.93</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>78.00</td>\n      <td>6.20</td>\n      <td>0.70</td>\n      <td>2.01</td>\n      <td>6.35</td>\n      <td>6.35</td>\n      <td>6.35</td>\n      <td>6.35</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>140.00</td>\n      <td>9.01</td>\n      <td>1.37</td>\n      <td>0.78</td>\n      <td>9.39</td>\n      <td>9.39</td>\n      <td>9.39</td>\n      <td>9.39</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>55.00</td>\n      <td>12.53</td>\n      <td>0.00</td>\n      <td>12.53</td>\n      <td>12.53</td>\n      <td>12.53</td>\n      <td>12.53</td>\n      <td>12.53</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>262.00</td>\n      <td>4.50</td>\n      <td>1.57</td>\n      <td>0.48</td>\n      <td>3.27</td>\n      <td>5.78</td>\n      <td>5.78</td>\n      <td>5.78</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>23.00</td>\n      <td>6.13</td>\n      <td>0.32</td>\n      <td>4.65</td>\n      <td>6.20</td>\n      <td>6.20</td>\n      <td>6.20</td>\n      <td>6.20</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>85.00</td>\n      <td>9.38</td>\n      <td>1.13</td>\n      <td>3.06</td>\n      <td>9.66</td>\n      <td>9.66</td>\n      <td>9.66</td>\n      <td>9.66</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>171.00</td>\n      <td>9.21</td>\n      <td>2.28</td>\n      <td>0.68</td>\n      <td>10.17</td>\n      <td>10.17</td>\n      <td>10.17</td>\n      <td>10.17</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>114.00</td>\n      <td>4.62</td>\n      <td>0.97</td>\n      <td>0.75</td>\n      <td>5.03</td>\n      <td>5.03</td>\n      <td>5.03</td>\n      <td>5.03</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>109.00</td>\n      <td>9.75</td>\n      <td>1.77</td>\n      <td>0.85</td>\n      <td>10.15</td>\n      <td>10.15</td>\n      <td>10.15</td>\n      <td>10.15</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>222.00</td>\n      <td>5.00</td>\n      <td>1.55</td>\n      <td>0.93</td>\n      <td>3.62</td>\n      <td>6.11</td>\n      <td>6.21</td>\n      <td>6.21</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>140.00</td>\n      <td>11.75</td>\n      <td>1.61</td>\n      <td>1.01</td>\n      <td>12.11</td>\n      <td>12.11</td>\n      <td>12.11</td>\n      <td>12.11</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>75.00</td>\n      <td>6.63</td>\n      <td>0.74</td>\n      <td>3.42</td>\n      <td>6.84</td>\n      <td>6.84</td>\n      <td>6.84</td>\n      <td>6.84</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>86.00</td>\n      <td>11.02</td>\n      <td>1.75</td>\n      <td>0.95</td>\n      <td>11.42</td>\n      <td>11.42</td>\n      <td>11.42</td>\n      <td>11.42</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>63.00</td>\n      <td>4.78</td>\n      <td>1.16</td>\n      <td>0.87</td>\n      <td>5.22</td>\n      <td>5.22</td>\n      <td>5.22</td>\n      <td>5.22</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>133.00</td>\n      <td>5.81</td>\n      <td>0.66</td>\n      <td>1.00</td>\n      <td>5.99</td>\n      <td>5.99</td>\n      <td>5.99</td>\n      <td>5.99</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nlead_proposal_2.groupby(data.publisher_id).min().plot.bar(figsize=[10,5])\n```\n\nThat looks about right, as long as the smaller publishers were closer to zero. So let's apply feature scaling to this, to give a number between 1 and 20. (Anything not as lead will pass though as zero.)\n\n\n```python\ndef rescale(series):\n    return (series - series.min()) / (series.max() - series.min())\n\nlead_proposal_3 = np.ceil(20 * rescale(lead_proposal_2))\n```\n\n\n```python\nlead_proposal_2.min(), lead_proposal_2.max()\n```\n\n\n\n\n    (0.46948415885821004, 13.145359968846892)\n\n\n\n\n```python\nlead_proposal_3.plot.hist()\n```\n\n\n```python\nlead_proposal_3.groupby(data.publisher_id).median().plot.bar(figsize=[10,5])\n```\n\n\n```python\ndata[\"lead_score\"] = pd.concat([lead_proposal_3, data.mins_as_lead[data.mins_as_lead==0]])\n```\n\n\n```python\ndata.lead_score.value_counts().sort_index()\n```\n\n\n\n\n    0.00     148451\n    1.00         41\n    2.00         42\n    3.00         56\n    4.00         78\n    5.00         85\n    6.00         67\n    7.00        247\n    8.00        271\n    9.00        300\n    10.00       237\n    11.00       199\n    12.00        70\n    13.00       274\n    14.00       498\n    15.00       214\n    16.00       359\n    17.00       269\n    18.00       229\n    19.00       383\n    20.00       288\n    Name: lead_score, dtype: int64\n\n\n\n\n```python\ndata.lead_score.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    8.00\n    bbc_co_uk                          20.00\n    breitbart_com                      13.00\n    brexitcentral_com                   7.00\n    buzzfeed_com                       19.00\n    cnn_com                            20.00\n    dailymail_co_uk                    18.00\n    economist_com                      12.00\n    evolvepolitics_com                  8.00\n    foxnews_com                        17.00\n    ft_com                             13.00\n    huffingtonpost_com                 17.00\n    independent_co_uk                  16.00\n    indy100_com                        11.00\n    lemonde_fr                         14.00\n    libdemvoice_org                     7.00\n    mirror_co_uk                       14.00\n    nbcnews_com                        14.00\n    newstatesman_com                   10.00\n    npr_org                            15.00\n    nytimes_com                        20.00\n    order-order_com                     9.00\n    propublica_org                     10.00\n    reuters_com                        15.00\n    rt_com                             16.00\n    skwawkbox_org                       8.00\n    telegraph_co_uk                    16.00\n    thecanary_co                       10.00\n    theguardian_com                    19.00\n    thetimes_co_uk                     11.00\n    washingtonpost_com                 18.00\n    westmonster_com                     8.00\n    yournewswire_com                    9.00\n    Name: lead_score, dtype: float64\n\n\n\nIn summary then, score for article $a$ is:\n\n\n$$\nunscaledLeadScore_a = \\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)}\\\\\nleadScore_a = 19 \\cdot \n\\frac{unscaledLeadScore_a - \\min(unscaledLeadScore)}\n{\\max(unscaledLeadScore) - \\min(unscaledLeadScore)} \n+ 1\n$$\n\nSince the minium value of $minsAsLead$ is 1, $\\min(unscaledLeadScore)$ is pretty insignificant. So we can simplify this to:\n\n$$\nleadScore_a = 20 \\cdot \n\\frac{unscaledLeadScore_a }\n     {\\max(unscaledLeadScore)} \n$$\n\nor: \n\n$$\nleadScore_a = 20 \\cdot \n\\frac{\\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)} }\n     {\\frac{60}{\\log(\\max(alexaRank))}} \n$$\n\n$$\nleadScore_a = \\left( 20 \\cdot \n\\frac{\\min(minsAsLead_a, 60)}{\\log(alexaRank_a)} \\cdot\n     {\\frac{\\log(\\max(alexaRank))}{60}} \\right)\n$$\n\n## Time on front score (15 points)\n\nThis is similar to time as lead, so lets try doing the same calculation, except we also want to factor in the number of slots on the front:\n\n\n$$frontScore_a = \n15 \n\\left(\\frac{\\min(minsOnFront_a, 1440)}{alexaRank_a \\cdot numArticlesOnFront_a}\\right) \n\\left( \\frac{\\min(alexaRank \\cdot numArticlesOnFront)}{1440} \\right)$$\n\n\n```python\n(data.alexa_rank * data.num_articles_on_front).min() / 1440\n```\n\n\n\n\n    2.4500000000000002\n\n\n\n\n```python\ntime_on_front_proposal_1 = np.ceil(data.mins_on_front.clip_upper(1440) / (data.alexa_rank * data.num_articles_on_front) * (2.45) * 15)\n```\n\n\n```python\ntime_on_front_proposal_1.plot.hist(figsize=(15, 7), bins=15)\n```\n\n\n```python\ntime_on_front_proposal_1.value_counts().sort_index()\n```\n\n\n\n\n    1.00     71064\n    2.00      7858\n    3.00      4538\n    4.00      4303\n    5.00       857\n    6.00       543\n    7.00       557\n    8.00       577\n    9.00       765\n    10.00      228\n    11.00      283\n    12.00      418\n    13.00      150\n    14.00       22\n    15.00        3\n    dtype: int64\n\n\n\n\n```python\ntime_on_front_proposal_1.groupby(data.publisher_id).sum()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk       8.00\n    bbc_co_uk                          15181.00\n    breitbart_com                       2420.00\n    brexitcentral_com                     62.00\n    buzzfeed_com                        9582.00\n    cnn_com                            11168.00\n    dailymail_co_uk                    13797.00\n    economist_com                        284.00\n    evolvepolitics_com                   130.00\n    foxnews_com                         7753.00\n    ft_com                              3064.00\n    huffingtonpost_com                  7607.00\n    independent_co_uk                   4402.00\n    indy100_com                          516.00\n    lemonde_fr                          3787.00\n    libdemvoice_org                      134.00\n    mirror_co_uk                        9419.00\n    nbcnews_com                         1671.00\n    newstatesman_com                     694.00\n    npr_org                             2352.00\n    nytimes_com                         9407.00\n    order-order_com                      267.00\n    propublica_org                        39.00\n    reuters_com                         7080.00\n    rt_com                              4254.00\n    skwawkbox_org                        114.00\n    telegraph_co_uk                     6210.00\n    thecanary_co                         341.00\n    theguardian_com                    12545.00\n    thetimes_co_uk                      9122.00\n    washingtonpost_com                  9177.00\n    westmonster_com                      271.00\n    yournewswire_com                     403.00\n    dtype: float64\n\n\n\nThat looks good to me.\n\n\n```python\ndata[\"front_score\"] = np.ceil(data.mins_on_front.clip_upper(1440) / (data.alexa_rank * data.num_articles_on_front) * (2.45) * 15).fillna(0)\n```\n\n\n```python\ndata.front_score \n```\n\n\n\n\n    id\n    171a1db515d4d4f81e9cdaefacdb8dba16c93b75   1.00\n    ea4e6959acdbcf288c76f9d25ac6baefb6410463   1.00\n    65b41c17cbc8fe96f2eb7d3d8086fbefa0a03cf7   0.00\n    cf3c6ce8b392031a436a585ec7ffc2c1f94729c1   0.00\n    96854242b80f8ea0c960c8a3c1b19f1f27d82db6   0.00\n    a6768245f519a1a2dd1da633b5d9f186e66b5f86   0.00\n    3ab8cb96ad784c7646b327a2ff6c2fb0875a9726   0.00\n    5d2369b6efcae2693582b2dc4b7444c64bfcb488   0.00\n    1a3a69741a4e3eca3399022e9bc1c710d8df86ee   0.00\n    0e6649a1d87a2e67e592e7fbec5f002cbb32a44c   1.00\n    c31f4c3f12d749682a00fa03b8ad4eb8b2f11e27   3.00\n    d43c9606cd44696362eb724037818c279f29a918   0.00\n    05dba6d3c8d602f6ef0004b3265e30a5099479de   0.00\n    095c2c1a6ac01b5606dc7c540d389fa04546e3c4   0.00\n    5c839e9b3c6c059c43ba5b364671817115eec39b   0.00\n    40ab7a42b352900d4c2b01e4826b3553cf159fb3   1.00\n    48d50d925c7c2f68536e25de1f15429531aa47cb   1.00\n    600931b1ef7a8b93fa9e34f5b61a1503bd50754e   1.00\n    4fbb0d728589c31c533e86269389f592563e801f   0.00\n    db43e4bac26e26ac5eeb0ab224778e55a80a170e   1.00\n    ef918777a190d2a6f40b0370be447e31e4b131a5   5.00\n    6c084bc2f2d8f6b3ed33d9d951108ad8ddc3c9b1   1.00\n    637b56e7e012fabe04d54ca328bc3d010f01afb9   0.00\n    562f6351aba92fabb666b284cb678cc19ff5d15c   1.00\n    d1b1f3421b3d56dfb7cdd6b7ee7f5c02f536d7cf   1.00\n    ca17823d9c51d4b32d525a15a58e0b2b25a9f6ba   0.00\n    037fad0847b147bc9d0933bfcc63aa902ee13d71   0.00\n    b3ce5114c925176798351df253d835bc0232a9ea   0.00\n    9a0a167585ab16d2bd99f4d355f77afc901f52aa   0.00\n    9c323ecb10718cc856007c8c8bfd0aac5d10bd3e   3.00\n                                               ... \n    371cc6c3e409283441a2471f2ec214e7ac8682cc   0.00\n    160f46e03ff51a3944bed74510c738e9e29fdce3   0.00\n    3f9489916269f0caaf46674464088b3810a2e692   0.00\n    6bb5e2634ad849cf69abde949d029b2b0dd18b4b   2.00\n    03405d7d4b535851e8b6b395df8a1bf772b3e017   0.00\n    3dd84c45d04ee158e27c0a36623886130a758a05   0.00\n    c7443ba3b937d485c0e6ef68c747218f1daccc71   0.00\n    9186449842926329474a32475c37b7dc7dcf7064   1.00\n    35001ab1fb3d11fd417d10e33bebbd984b1031c4   0.00\n    d9fc1c214777b60a24d0cb3da9a35bb8492643ae   0.00\n    7e3710af4f37d280336dd704b2ebe05802e8fa6a   0.00\n    25f16c16f436aad31ae3baaa7fd800680e0e69b2   0.00\n    20bc3574168f9a27239bfd4f7090317204e02464   0.00\n    47f92d6da64d872f9dc15a199cd75d549bc16d31   1.00\n    21ee0e5f55e63a51cdc07d25df92cf661ed8da39   0.00\n    af8bed7dd1ba9ff7e6718144ef69a6e8f335decc   0.00\n    0276d4428f791bc09a0142469182e0e9123563f5   0.00\n    28dbafb480db5c1e673938765a5c3daa0617cf84   0.00\n    3d7c2f8d8ce531b045f1d1373d25185e963e91e6   0.00\n    fa09dcb5be9c60cfa6596342cd304656259e60b9   0.00\n    0a0847e09b1c77bcec4cd6152b86c51e9e005f36   1.00\n    f3127c22bd153b941224ea41e96d8e6f1e7acda0   0.00\n    c39da6648ab2f20cea074de5e1326c249626f303   0.00\n    d0b55c216b94420ba2d401af5e299e642db69f09   1.00\n    4df995cccb46e21fc0e642565a06dd6c97e0ee24   0.00\n    634883b02e9c7a11bd19623d1f3bb6eba03f97a7   0.00\n    f9eaf89d61d8b2ff051e893c3e3ac1b3a12d00d0   0.00\n    3606fdc0b002f417710fbc16ea2045a5b04c5f62   1.00\n    d6e923f137e8ad3cc4c2694557f30b1e27b6d38a   0.00\n    a58d5a7df0e47588212248dc1209a15053fb1ff1   2.00\n    Name: front_score, Length: 152658, dtype: float64\n\n\n\n## Facebook brand page promotion (15 points)\n\nOne way a publisher has of promoting content is to post to their brand page. The significance of doing so is stronger when the brand page has more followers (likes).\n\n$$ facebookPromotionProposed1_a = 15 \\left( \\frac {brandPageLikes_a} {\\max(brandPageLikes)} \\right) $$\n\nNow lets explore the data to see if that makes sense. **tr;dr the formula above is incorrect**\n\n\n```python\ndata.fb_brand_page_likes.max()\n```\n\n\n\n\n    44213994.0\n\n\n\n\n```python\nfacebook_promotion_proposed_1 = np.ceil((15 * (data.fb_brand_page_likes / data.fb_brand_page_likes.max())).fillna(0))\n```\n\n\n```python\nfacebook_promotion_proposed_1.value_counts().sort_index().plot.bar()\n```\n\n\n```python\nfacebook_promotion_proposed_1.groupby(data.publisher_id).describe()\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>25%</th>\n      <th>50%</th>\n      <th>75%</th>\n      <th>max</th>\n    </tr>\n    <tr>\n      <th>publisher_id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>anotherangryvoice_blogspot_co_uk</th>\n      <td>8.00</td>\n      <td>0.88</td>\n      <td>0.35</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>bbc_co_uk</th>\n      <td>12116.00</td>\n      <td>0.59</td>\n      <td>2.92</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>15.00</td>\n    </tr>\n    <tr>\n      <th>breitbart_com</th>\n      <td>2472.00</td>\n      <td>0.86</td>\n      <td>0.99</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>brexitcentral_com</th>\n      <td>62.00</td>\n      <td>0.89</td>\n      <td>0.32</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>buzzfeed_com</th>\n      <td>2026.00</td>\n      <td>0.23</td>\n      <td>0.42</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>cnn_com</th>\n      <td>3444.00</td>\n      <td>2.79</td>\n      <td>4.49</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>10.00</td>\n      <td>10.00</td>\n    </tr>\n    <tr>\n      <th>dailymail_co_uk</th>\n      <td>23716.00</td>\n      <td>0.57</td>\n      <td>1.59</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>5.00</td>\n    </tr>\n    <tr>\n      <th>economist_com</th>\n      <td>522.00</td>\n      <td>2.14</td>\n      <td>1.36</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>evolvepolitics_com</th>\n      <td>132.00</td>\n      <td>0.67</td>\n      <td>0.47</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>foxnews_com</th>\n      <td>6191.00</td>\n      <td>0.57</td>\n      <td>1.75</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>6.00</td>\n    </tr>\n    <tr>\n      <th>ft_com</th>\n      <td>3250.00</td>\n      <td>0.62</td>\n      <td>0.92</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>huffingtonpost_com</th>\n      <td>10566.00</td>\n      <td>0.48</td>\n      <td>1.30</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n    </tr>\n    <tr>\n      <th>independent_co_uk</th>\n      <td>6127.00</td>\n      <td>0.65</td>\n      <td>1.24</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>indy100_com</th>\n      <td>517.00</td>\n      <td>0.62</td>\n      <td>0.49</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>lemonde_fr</th>\n      <td>3883.00</td>\n      <td>0.73</td>\n      <td>0.96</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>libdemvoice_org</th>\n      <td>134.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>mirror_co_uk</th>\n      <td>10010.00</td>\n      <td>0.25</td>\n      <td>0.43</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>nbcnews_com</th>\n      <td>1710.00</td>\n      <td>2.03</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n      <td>4.00</td>\n    </tr>\n    <tr>\n      <th>newstatesman_com</th>\n      <td>749.00</td>\n      <td>0.58</td>\n      <td>0.49</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>npr_org</th>\n      <td>1986.00</td>\n      <td>1.36</td>\n      <td>1.49</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>nytimes_com</th>\n      <td>4934.00</td>\n      <td>1.49</td>\n      <td>2.29</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>5.00</td>\n      <td>5.00</td>\n    </tr>\n    <tr>\n      <th>order-order_com</th>\n      <td>268.00</td>\n      <td>0.82</td>\n      <td>0.38</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>propublica_org</th>\n      <td>39.00</td>\n      <td>0.79</td>\n      <td>0.41</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>reuters_com</th>\n      <td>6047.00</td>\n      <td>0.55</td>\n      <td>0.89</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>rt_com</th>\n      <td>2137.00</td>\n      <td>1.06</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>skwawkbox_org</th>\n      <td>114.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>telegraph_co_uk</th>\n      <td>7376.00</td>\n      <td>0.55</td>\n      <td>0.89</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>2.00</td>\n    </tr>\n    <tr>\n      <th>thecanary_co</th>\n      <td>344.00</td>\n      <td>0.66</td>\n      <td>0.47</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>theguardian_com</th>\n      <td>8567.00</td>\n      <td>0.53</td>\n      <td>1.14</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>thetimes_co_uk</th>\n      <td>9147.00</td>\n      <td>0.05</td>\n      <td>0.23</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>washingtonpost_com</th>\n      <td>23360.00</td>\n      <td>0.20</td>\n      <td>0.74</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n    </tr>\n    <tr>\n      <th>westmonster_com</th>\n      <td>289.00</td>\n      <td>0.28</td>\n      <td>0.45</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>1.00</td>\n    </tr>\n    <tr>\n      <th>yournewswire_com</th>\n      <td>415.00</td>\n      <td>0.17</td>\n      <td>0.37</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThat's too much variation: sites like the Guardian, which have a respectable 7.5m likes, should not be scoring a 3. Lets try applying a log to it, and then standard feature scaling again.\n\n\n```python\ndata.fb_brand_page_likes.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk     330078.00\n    bbc_co_uk                          44213994.00\n    breitbart_com                       3680635.00\n    brexitcentral_com                      9347.00\n    buzzfeed_com                        2714356.00\n    cnn_com                            28782078.00\n    dailymail_co_uk                    12712687.00\n    economist_com                       8315962.00\n    evolvepolitics_com                   113280.00\n    foxnews_com                        15924468.00\n    ft_com                              3674434.00\n    huffingtonpost_com                  9753503.00\n    independent_co_uk                   7610080.00\n    indy100_com                          225454.00\n    lemonde_fr                          3895889.00\n    libdemvoice_org                        8593.00\n    mirror_co_uk                        2873844.00\n    nbcnews_com                         9302574.00\n    newstatesman_com                     154405.00\n    npr_org                             6179264.00\n    nytimes_com                        14688146.00\n    order-order_com                       44296.00\n    propublica_org                       350212.00\n    reuters_com                         3875248.00\n    rt_com                              4588236.00\n    skwawkbox_org                          5276.00\n    telegraph_co_uk                     4365583.00\n    thecanary_co                         155885.00\n    theguardian_com                     7739677.00\n    thetimes_co_uk                       695491.00\n    washingtonpost_com                  6028517.00\n    westmonster_com                       14257.00\n    yournewswire_com                      26752.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\nnp.log(2149)\n```\n\n\n\n\n    7.6727578966425103\n\n\n\n\n```python\nnp.log(data.fb_brand_page_likes.groupby(data.publisher_id).max())\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk   12.71\n    bbc_co_uk                          17.60\n    breitbart_com                      15.12\n    brexitcentral_com                   9.14\n    buzzfeed_com                       14.81\n    cnn_com                            17.18\n    dailymail_co_uk                    16.36\n    economist_com                      15.93\n    evolvepolitics_com                 11.64\n    foxnews_com                        16.58\n    ft_com                             15.12\n    huffingtonpost_com                 16.09\n    independent_co_uk                  15.84\n    indy100_com                        12.33\n    lemonde_fr                         15.18\n    libdemvoice_org                     9.06\n    mirror_co_uk                       14.87\n    nbcnews_com                        16.05\n    newstatesman_com                   11.95\n    npr_org                            15.64\n    nytimes_com                        16.50\n    order-order_com                    10.70\n    propublica_org                     12.77\n    reuters_com                        15.17\n    rt_com                             15.34\n    skwawkbox_org                       8.57\n    telegraph_co_uk                    15.29\n    thecanary_co                       11.96\n    theguardian_com                    15.86\n    thetimes_co_uk                     13.45\n    washingtonpost_com                 15.61\n    westmonster_com                     9.57\n    yournewswire_com                   10.19\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\nThat's more like it, but the lower numbers should be smaller.\n\n\n```python\nnp.log(data.fb_brand_page_likes.groupby(data.publisher_id).max() / 1000)\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    5.80\n    bbc_co_uk                          10.70\n    breitbart_com                       8.21\n    brexitcentral_com                   2.24\n    buzzfeed_com                        7.91\n    cnn_com                            10.27\n    dailymail_co_uk                     9.45\n    economist_com                       9.03\n    evolvepolitics_com                  4.73\n    foxnews_com                         9.68\n    ft_com                              8.21\n    huffingtonpost_com                  9.19\n    independent_co_uk                   8.94\n    indy100_com                         5.42\n    lemonde_fr                          8.27\n    libdemvoice_org                     2.15\n    mirror_co_uk                        7.96\n    nbcnews_com                         9.14\n    newstatesman_com                    5.04\n    npr_org                             8.73\n    nytimes_com                         9.59\n    order-order_com                     3.79\n    propublica_org                      5.86\n    reuters_com                         8.26\n    rt_com                              8.43\n    skwawkbox_org                       1.66\n    telegraph_co_uk                     8.38\n    thecanary_co                        5.05\n    theguardian_com                     8.95\n    thetimes_co_uk                      6.54\n    washingtonpost_com                  8.70\n    westmonster_com                     2.66\n    yournewswire_com                    3.29\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\nscaled_fb_brand_page_likes = (data.fb_brand_page_likes / 1000)\nfacebook_promotion_proposed_2 = np.ceil(\\\n    (15 * \\\n     (np.log(scaled_fb_brand_page_likes) / np.log(scaled_fb_brand_page_likes.max()))\\\n    )\\\n                                       ).fillna(0)\n```\n\n\n```python\nfacebook_promotion_proposed_2.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    9.00\n    bbc_co_uk                          15.00\n    breitbart_com                      12.00\n    brexitcentral_com                   4.00\n    buzzfeed_com                       12.00\n    cnn_com                            15.00\n    dailymail_co_uk                    14.00\n    economist_com                      13.00\n    evolvepolitics_com                  7.00\n    foxnews_com                        14.00\n    ft_com                             12.00\n    huffingtonpost_com                 13.00\n    independent_co_uk                  13.00\n    indy100_com                         8.00\n    lemonde_fr                         12.00\n    libdemvoice_org                     4.00\n    mirror_co_uk                       12.00\n    nbcnews_com                        13.00\n    newstatesman_com                    8.00\n    npr_org                            13.00\n    nytimes_com                        14.00\n    order-order_com                     6.00\n    propublica_org                      9.00\n    reuters_com                        12.00\n    rt_com                             12.00\n    skwawkbox_org                       3.00\n    telegraph_co_uk                    12.00\n    thecanary_co                        8.00\n    theguardian_com                    13.00\n    thetimes_co_uk                     10.00\n    washingtonpost_com                 13.00\n    westmonster_com                     4.00\n    yournewswire_com                    5.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\nLGTM. So the equation is\n\n\n$$ facebookPromotion_a = 15 \\left( \n\\frac {\\log(\\frac {brandPageLikes_a}{1000})} \n{\\log(\\frac {\\max(brandPageLikes)}{1000}))} \\right) $$\n\n\nNow, let's try applying standard feature scaling approch to this, rather than using a magic number of 1,000. That equation would be:\n\n\\begin{align}\nunscaledFacebookPromotion_a &= \n   \\log(brandPageLikes_a) \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{unscaledFacebookPromotion_a - \\min(unscaledFacebookPromotion)}{\\max(unscaledFacebookPromotion) - \\min(unscaledFacebookPromotion)}  \\\\\n\\\\\n\\text{The scaling can be simplified to:} \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{unscaledFacebookPromotion_a - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))}  \\\\\n\\\\\n\\text{Meaning the overall equation becomes:} \\\\\nfacebookPromotion_a &= \n   15 \\cdot \\frac{\\log(brandPageLikes_a) - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))} \n   \\end{align}\n\n\n\n```python\nfacebook_promotion_proposed_3 = np.ceil(\n    (14 * \n     ( \n         (np.log(data.fb_brand_page_likes) - np.log(data.fb_brand_page_likes.min()) ) /\n         (np.log(data.fb_brand_page_likes.max()) - np.log(data.fb_brand_page_likes.min()))\n     )\n    ) + 1\n                                       )\n```\n\n\n```python\nfacebook_promotion_proposed_3.groupby(data.publisher_id).max()\n```\n\n\n\n\n    publisher_id\n    anotherangryvoice_blogspot_co_uk    8.00\n    bbc_co_uk                          15.00\n    breitbart_com                      12.00\n    brexitcentral_com                   2.00\n    buzzfeed_com                       11.00\n    cnn_com                            15.00\n    dailymail_co_uk                    14.00\n    economist_com                      13.00\n    evolvepolitics_com                  6.00\n    foxnews_com                        14.00\n    ft_com                             12.00\n    huffingtonpost_com                 13.00\n    independent_co_uk                  13.00\n    indy100_com                         7.00\n    lemonde_fr                         12.00\n    libdemvoice_org                     2.00\n    mirror_co_uk                       11.00\n    nbcnews_com                        13.00\n    newstatesman_com                    7.00\n    npr_org                            12.00\n    nytimes_com                        14.00\n    order-order_com                     5.00\n    propublica_org                      8.00\n    reuters_com                        12.00\n    rt_com                             12.00\n    skwawkbox_org                       2.00\n    telegraph_co_uk                    12.00\n    thecanary_co                        7.00\n    theguardian_com                    13.00\n    thetimes_co_uk                      9.00\n    washingtonpost_com                 12.00\n    westmonster_com                     3.00\n    yournewswire_com                    4.00\n    Name: fb_brand_page_likes, dtype: float64\n\n\n\n\n```python\ndata[\"facebook_promotion_score\"] = facebook_promotion_proposed_3.fillna(0.0)\n```\n\n# Review\n\n\n```python\ndata[\"promotion_score\"] = (data.lead_score + data.front_score + data.facebook_promotion_score)\ndata[\"attention_index\"] = (data.promotion_score + data.response_score)\n```\n\n\n```python\ndata.promotion_score.plot.hist(bins=np.arange(50), figsize=(15,6))\n```\n\n\n```python\ndata.attention_index.plot.hist(bins=np.arange(100), figsize=(15,6))\n```\n\n\n```python\ndata.attention_index.value_counts().sort_index()\n```\n\n\n\n\n    0.00     23428\n    1.00     19237\n    2.00     12755\n    3.00      8699\n    4.00      6444\n    5.00      5114\n    6.00      4503\n    7.00      3939\n    8.00      3523\n    9.00      3331\n    10.00     3043\n    11.00     2770\n    12.00     2681\n    13.00     2512\n    14.00     2433\n    15.00     2259\n    16.00     2187\n    17.00     1982\n    18.00     1884\n    19.00     1726\n    20.00     1719\n    21.00     1632\n    22.00     1647\n    23.00     1542\n    24.00     1544\n    25.00     1436\n    26.00     1429\n    27.00     1384\n    28.00     1352\n    29.00     1302\n             ...  \n    66.00       93\n    67.00       85\n    68.00       76\n    69.00       60\n    70.00       34\n    71.00       45\n    72.00       53\n    73.00       33\n    74.00       35\n    75.00       41\n    76.00       32\n    77.00       34\n    78.00       19\n    79.00       27\n    80.00       34\n    81.00       17\n    82.00       21\n    83.00       16\n    84.00       18\n    85.00        7\n    86.00       15\n    87.00        9\n    88.00       19\n    89.00       10\n    90.00        5\n    91.00        6\n    92.00        7\n    93.00        7\n    94.00        6\n    95.00        1\n    Name: attention_index, Length: 96, dtype: int64\n\n\n\n\n```python\n# and lets see the articles with the biggest attention index\ndata.sort_values(\"attention_index\", ascending=False)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>6067d56573cffca0809e48adf887dc244f0071bc</th>\n      <td>http://www.bbc.co.uk/news/world-asia-41275614</td>\n      <td>N Korea 'fires missile from Pyongyang'</td>\n      <td>2017-09-14 22:18:02.020</td>\n      <td>2017-09-14 22:14:57.000</td>\n      <td>116513</td>\n      <td>834.83</td>\n      <td>2017-09-14T22:44:01.001Z</td>\n      <td>22667</td>\n      <td>76135</td>\n      <td>17711</td>\n      <td>...</td>\n      <td>True</td>\n      <td>43989977.00</td>\n      <td>2017-09-15T01:49:45.000Z</td>\n      <td>96</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>10.00</td>\n      <td>15.00</td>\n      <td>45.00</td>\n      <td>95.00</td>\n    </tr>\n    <tr>\n      <th>e5916f9bd62e8c6c9cb564d4d4b4ea8a99c8e1d2</th>\n      <td>http://www.cnn.com/2017/09/18/politics/paul-ma...</td>\n      <td>US government wiretapped former Trump campaign...</td>\n      <td>2017-09-18 22:57:09.206</td>\n      <td>2017-09-18 22:55:12.000</td>\n      <td>167763</td>\n      <td>540.50</td>\n      <td>2017-09-18T23:10:01.591Z</td>\n      <td>46913</td>\n      <td>97863</td>\n      <td>22987</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28570339.00</td>\n      <td>2017-09-18T23:01:49.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>68f2a3b5ccfe8c92d511232c1e284f4f42852394</th>\n      <td>http://www.cnn.com/2017/09/03/politics/obama-t...</td>\n      <td>Read the Inauguration Day letter Obama left fo...</td>\n      <td>2017-09-03 12:48:16.001</td>\n      <td>2017-09-03 12:45:03.000</td>\n      <td>184591</td>\n      <td>416.92</td>\n      <td>2017-09-03T13:14:00.480Z</td>\n      <td>25453</td>\n      <td>132713</td>\n      <td>26425</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28191321.00</td>\n      <td>2017-09-03T12:52:17.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>6dd1f438183f2d3b123ce529eda57ce6e1a5be97</th>\n      <td>http://www.bbc.co.uk/news/world-latin-america-...</td>\n      <td>Large earthquake strikes near Mexico</td>\n      <td>2017-09-08 05:12:00.922</td>\n      <td>2017-09-08 05:09:57.000</td>\n      <td>87552</td>\n      <td>516.50</td>\n      <td>2017-09-08T05:38:01.097Z</td>\n      <td>13470</td>\n      <td>61106</td>\n      <td>12976</td>\n      <td>...</td>\n      <td>True</td>\n      <td>43867811.00</td>\n      <td>2017-09-08T05:13:41.000Z</td>\n      <td>96</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>10.00</td>\n      <td>15.00</td>\n      <td>45.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>a4ec2e243a5327b4c92ac310dc8e8c028b069e1d</th>\n      <td>http://www.cnn.com/2017/09/20/americas/hurrica...</td>\n      <td>Hurricane Maria: Puerto Rico awaits direct hit</td>\n      <td>2017-09-20 09:03:20.771</td>\n      <td>2017-09-20 08:59:03.000</td>\n      <td>143472</td>\n      <td>388.67</td>\n      <td>2017-09-20T23:54:02.368Z</td>\n      <td>15363</td>\n      <td>109288</td>\n      <td>18821</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28601101.00</td>\n      <td>2017-09-20T19:30:25.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>e915fdae2abc802ebd8edc374dc070ade3465019</th>\n      <td>http://www.cnn.com/2017/09/18/americas/atlanti...</td>\n      <td>Hurricane Maria forecaset to be Category 4</td>\n      <td>2017-09-18 07:51:12.471</td>\n      <td>2017-09-18 07:44:05.000</td>\n      <td>143711</td>\n      <td>484.50</td>\n      <td>2017-09-18T21:06:02.694Z</td>\n      <td>33386</td>\n      <td>88010</td>\n      <td>22315</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28565647.00</td>\n      <td>2017-09-18T08:31:05.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>8e73a1eb14f6a69156ddf755d404b8a464e22ef8</th>\n      <td>http://www.cnn.com/2017/09/23/politics/nfl-goo...</td>\n      <td>FL commissioner: Trump showed 'lack of respect...</td>\n      <td>2017-09-23 14:43:16.807</td>\n      <td>2017-09-23 14:37:43.000</td>\n      <td>98752</td>\n      <td>211.70</td>\n      <td>2017-09-24T19:06:05.123Z</td>\n      <td>32897</td>\n      <td>53603</td>\n      <td>12252</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28618169.00</td>\n      <td>2017-09-23T15:20:06.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>94.00</td>\n    </tr>\n    <tr>\n      <th>588089e0a7c0e9eabe610bf658f2d4205b31e0cc</th>\n      <td>http://www.cnn.com/2017/09/05/us/hurricane-irm...</td>\n      <td>Hurricane Irma: Florida and Puerto Rico brace ...</td>\n      <td>2017-09-05 06:57:19.474</td>\n      <td>2017-09-05 06:51:25.000</td>\n      <td>263683</td>\n      <td>257.52</td>\n      <td>2017-09-05T16:02:00.306Z</td>\n      <td>88414</td>\n      <td>144215</td>\n      <td>31054</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28201804.00</td>\n      <td>2017-09-05T08:30:27.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>c7e29470ae37b7a78df9a3d784e4f66e4ca951a2</th>\n      <td>http://www.bbc.co.uk/news/world-middle-east-41...</td>\n      <td>Saudi women 'given right to drive'</td>\n      <td>2017-09-26 19:13:08.658</td>\n      <td>2017-09-26 19:09:45.000</td>\n      <td>330324</td>\n      <td>2935.87</td>\n      <td>2017-09-26T21:08:04.432Z</td>\n      <td>36855</td>\n      <td>265864</td>\n      <td>27605</td>\n      <td>...</td>\n      <td>True</td>\n      <td>44163937.00</td>\n      <td>2017-09-26T19:13:41.000Z</td>\n      <td>96</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>6755d9c120cfcf187f90e6c4ad4974cb7d1447a7</th>\n      <td>http://www.bbc.co.uk/news/world-europe-41376577</td>\n      <td>Germany election: Merkel seeks fourth term</td>\n      <td>2017-09-24 03:49:15.814</td>\n      <td>2017-09-24 03:47:32.000</td>\n      <td>57302</td>\n      <td>320.86</td>\n      <td>2017-09-24T16:32:02.690Z</td>\n      <td>7320</td>\n      <td>45782</td>\n      <td>4200</td>\n      <td>...</td>\n      <td>True</td>\n      <td>44137706.00</td>\n      <td>2017-09-24T16:14:49.000Z</td>\n      <td>96</td>\n      <td>46.00</td>\n      <td>20.00</td>\n      <td>12.00</td>\n      <td>15.00</td>\n      <td>47.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>cb9529046059677cc97532667a6e4b6a85e21790</th>\n      <td>http://www.bbc.co.uk/news/world-asia-41391978</td>\n      <td>N Korea accuses US of declaring war</td>\n      <td>2017-09-25 15:07:10.151</td>\n      <td>2017-09-25 15:04:19.000</td>\n      <td>163895</td>\n      <td>1682.78</td>\n      <td>2017-09-25T17:12:12.061Z</td>\n      <td>43397</td>\n      <td>96735</td>\n      <td>23763</td>\n      <td>...</td>\n      <td>True</td>\n      <td>44155104.00</td>\n      <td>2017-09-26T02:49:43.000Z</td>\n      <td>96</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>75bd9111d5a725787b322d8212c72beade7fb8a6</th>\n      <td>http://money.cnn.com/2017/09/27/media/hugh-hef...</td>\n      <td>Playboy founder Hugh Hefner dead at 91</td>\n      <td>2017-09-28 03:34:14.532</td>\n      <td>2017-09-28 03:27:23.000</td>\n      <td>112943</td>\n      <td>808.77</td>\n      <td>2017-09-28T03:46:12.227Z</td>\n      <td>20372</td>\n      <td>65226</td>\n      <td>27345</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28720237.00</td>\n      <td>2017-09-28T03:37:38.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>84c9cdda4951e8791077a683f93e2a5e5a9d9bfb</th>\n      <td>http://www.cnn.com/2017/09/17/politics/trump-t...</td>\n      <td>Trump retweets GIF of him hitting Clinton with...</td>\n      <td>2017-09-17 13:48:21.304</td>\n      <td>2017-09-17 13:43:23.000</td>\n      <td>136292</td>\n      <td>311.77</td>\n      <td>2017-09-17T15:15:59.744Z</td>\n      <td>60117</td>\n      <td>63645</td>\n      <td>12530</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28562039.00</td>\n      <td>2017-09-17T14:54:04.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>e3fee93183c369e2eb37069a142e6c7142dab705</th>\n      <td>http://money.cnn.com/2017/09/01/technology/mic...</td>\n      <td>Tech billionaire Michael Dell pledges $36 mill...</td>\n      <td>2017-09-01 16:45:10.351</td>\n      <td>2017-09-01 15:29:21.000</td>\n      <td>82021</td>\n      <td>296.50</td>\n      <td>2017-09-01T16:58:01.790Z</td>\n      <td>5412</td>\n      <td>69977</td>\n      <td>6632</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28178745.00</td>\n      <td>2017-09-01T16:40:38.000Z</td>\n      <td>105</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>93.00</td>\n    </tr>\n    <tr>\n      <th>d6ff153e02b24da93ad3444297ab046d5cd62d97</th>\n      <td>http://www.cnn.com/2017/09/24/us/nfl-trump-tak...</td>\n      <td>NFL Sunday kicks off amid beef between players...</td>\n      <td>2017-09-24 14:16:17.026</td>\n      <td>2017-09-24 14:11:58.000</td>\n      <td>148932</td>\n      <td>432.54</td>\n      <td>2017-09-24T15:28:12.004Z</td>\n      <td>33865</td>\n      <td>104721</td>\n      <td>10346</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28621607.00</td>\n      <td>2017-09-24T14:35:38.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>12d0d6ce64cee12a5b117c70fe8f2272378d8053</th>\n      <td>http://www.cnn.com/2017/09/22/politics/donald-...</td>\n      <td>Trump: NFL owners should fire players who protest</td>\n      <td>2017-09-23 01:34:27.121</td>\n      <td>2017-09-23 01:29:11.000</td>\n      <td>126459</td>\n      <td>163.48</td>\n      <td>2017-09-23T02:46:08.560Z</td>\n      <td>57819</td>\n      <td>57768</td>\n      <td>10872</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28614688.00</td>\n      <td>2017-09-23T01:48:52.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>b86ac39e4b7fdf8c537b54840eee3aa4fe2d28ab</th>\n      <td>http://www.cnn.com/2017/09/23/politics/donald-...</td>\n      <td>The dark racial sentiment in Trump's NBA and N...</td>\n      <td>2017-09-23 21:07:20.631</td>\n      <td>2017-09-23 21:03:20.000</td>\n      <td>84670</td>\n      <td>145.59</td>\n      <td>2017-09-23T23:11:08.062Z</td>\n      <td>25997</td>\n      <td>46214</td>\n      <td>12459</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28619235.00</td>\n      <td>2017-09-23T22:00:12.000Z</td>\n      <td>105</td>\n      <td>49.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>73518249283178cf7ff417e30956880b1bc1878f</th>\n      <td>http://www.cnn.com/2017/09/17/americas/atlanti...</td>\n      <td>Atlantic hosts three storms, with Maria on Irm...</td>\n      <td>2017-09-17 05:36:14.222</td>\n      <td>2017-09-17 05:31:54.000</td>\n      <td>76800</td>\n      <td>123.25</td>\n      <td>2017-09-17T17:41:59.655Z</td>\n      <td>15773</td>\n      <td>46849</td>\n      <td>14178</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28562524.00</td>\n      <td>2017-09-17T17:30:29.000Z</td>\n      <td>105</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>2562369665718a1858add5e041951a9c9f10cd80</th>\n      <td>http://www.bbc.co.uk/news/uk-41278545</td>\n      <td>Incident reported on London Tube train</td>\n      <td>2017-09-15 07:48:02.690</td>\n      <td>2017-09-15 07:45:25.000</td>\n      <td>101874</td>\n      <td>396.05</td>\n      <td>2017-09-15T08:02:01.607Z</td>\n      <td>22092</td>\n      <td>56920</td>\n      <td>22862</td>\n      <td>...</td>\n      <td>True</td>\n      <td>43997776.00</td>\n      <td>2017-09-15T07:49:19.000Z</td>\n      <td>96</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>7.00</td>\n      <td>15.00</td>\n      <td>42.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>355a3ab21fa58fd0c251c8fb6d39065852d5d867</th>\n      <td>http://www.bbc.co.uk/news/world-asia-41431057</td>\n      <td>China to shut down North Korean companies</td>\n      <td>2017-09-28 13:40:11.625</td>\n      <td>2017-09-28 13:36:30.000</td>\n      <td>45061</td>\n      <td>111.36</td>\n      <td>2017-09-28T20:06:12.105Z</td>\n      <td>1843</td>\n      <td>41077</td>\n      <td>2141</td>\n      <td>...</td>\n      <td>True</td>\n      <td>44185601.00</td>\n      <td>2017-09-28T19:22:19.000Z</td>\n      <td>96</td>\n      <td>45.00</td>\n      <td>20.00</td>\n      <td>12.00</td>\n      <td>15.00</td>\n      <td>47.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>566c188bb9929c658a3c6d40088f87743081151a</th>\n      <td>http://www.bbc.co.uk/news/world-us-canada-4142...</td>\n      <td>Playboy founder Heffner dies aged 91</td>\n      <td>2017-09-28 03:31:10.364</td>\n      <td>2017-09-28 03:29:02.000</td>\n      <td>78003</td>\n      <td>257.46</td>\n      <td>2017-09-28T03:53:05.355Z</td>\n      <td>16105</td>\n      <td>44826</td>\n      <td>17072</td>\n      <td>...</td>\n      <td>True</td>\n      <td>44181244.00</td>\n      <td>2017-09-28T03:38:13.000Z</td>\n      <td>96</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>92.00</td>\n    </tr>\n    <tr>\n      <th>1134a234e872bbf57eec6bcf1fa40eee11e2c999</th>\n      <td>http://www.cnn.com/2017/09/06/us/hurricane-irm...</td>\n      <td>Hurricane Irma hits Caribbean island of Barbuda</td>\n      <td>2017-09-06 06:39:19.049</td>\n      <td>2017-09-06 06:34:13.000</td>\n      <td>73503</td>\n      <td>79.75</td>\n      <td>2017-09-06T18:05:59.675Z</td>\n      <td>18627</td>\n      <td>41020</td>\n      <td>13856</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28218940.00</td>\n      <td>2017-09-06T07:00:10.000Z</td>\n      <td>105</td>\n      <td>48.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>158596a091671070e926a74ce3c1e8d252e08133</th>\n      <td>http://www.cnn.com/2017/09/21/politics/kim-jon...</td>\n      <td>North Korea's Kim: Trump 'will pay dearly' for...</td>\n      <td>2017-09-21 23:01:24.885</td>\n      <td>2017-09-21 22:56:44.000</td>\n      <td>67623</td>\n      <td>275.96</td>\n      <td>2017-09-22T01:07:12.468Z</td>\n      <td>23918</td>\n      <td>32365</td>\n      <td>11340</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28610759.00</td>\n      <td>2017-09-21T23:07:59.000Z</td>\n      <td>105</td>\n      <td>47.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>cdd1e7a21d1430598e553c8146eb3f5a93b5a486</th>\n      <td>http://www.cnn.com/2017/09/19/americas/mexico-...</td>\n      <td>7.1 earthquake strikes central Mexico</td>\n      <td>2017-09-19 18:57:14.566</td>\n      <td>2017-09-19 18:55:08.000</td>\n      <td>139662</td>\n      <td>359.50</td>\n      <td>2017-09-19T19:58:00.234Z</td>\n      <td>20286</td>\n      <td>96085</td>\n      <td>23291</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28583302.00</td>\n      <td>2017-09-19T19:42:15.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>2847600e75fdbf6357bfa32c08916aad2d9b6f83</th>\n      <td>http://www.cnn.com/2017/09/19/americas/hurrica...</td>\n      <td>Hurricane Maria hits Dominica with Category 5 ...</td>\n      <td>2017-09-19 07:33:14.696</td>\n      <td>2017-09-19 07:29:02.000</td>\n      <td>62093</td>\n      <td>61.17</td>\n      <td>2017-09-20T02:22:00.321Z</td>\n      <td>11081</td>\n      <td>41740</td>\n      <td>9272</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28572026.00</td>\n      <td>2017-09-19T08:00:33.000Z</td>\n      <td>105</td>\n      <td>47.00</td>\n      <td>20.00</td>\n      <td>9.00</td>\n      <td>15.00</td>\n      <td>44.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>1c534e814b943941f4db2387b9d96eda77d57570</th>\n      <td>https://www.buzzfeed.com/adolfoflores/daca-res...</td>\n      <td>A Paramedic With DACA Status Rescues Harvey Vi...</td>\n      <td>2017-09-02 03:24:21.448</td>\n      <td>2017-09-02 03:22:27.000</td>\n      <td>96700</td>\n      <td>119.25</td>\n      <td>2017-09-02T20:24:01.207Z</td>\n      <td>12230</td>\n      <td>70455</td>\n      <td>14015</td>\n      <td>...</td>\n      <td>True</td>\n      <td>2662925.00</td>\n      <td>2017-09-02T14:55:59.000Z</td>\n      <td>147</td>\n      <td>49.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>df0494b09e5e2991b2774626f0e313590b598948</th>\n      <td>http://www.cnn.com/2017/09/25/politics/north-k...</td>\n      <td>North Korea accuses Trump of declaring war</td>\n      <td>2017-09-25 15:16:27.965</td>\n      <td>2017-09-25 15:09:18.000</td>\n      <td>122525</td>\n      <td>509.35</td>\n      <td>2017-09-25T17:11:11.339Z</td>\n      <td>37299</td>\n      <td>62908</td>\n      <td>22318</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28627649.00</td>\n      <td>2017-09-25T16:09:44.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>6.00</td>\n      <td>15.00</td>\n      <td>41.00</td>\n      <td>91.00</td>\n    </tr>\n    <tr>\n      <th>12b2893bac6075f49fb8f552f321dc6d49cfbd12</th>\n      <td>https://www.buzzfeed.com/davidmack/kylie-jenne...</td>\n      <td>Holy Crap, Kylie Jenner Is Pregnant</td>\n      <td>2017-09-22 21:24:15.447</td>\n      <td>2017-09-22 21:13:50.000</td>\n      <td>59174</td>\n      <td>509.54</td>\n      <td>2017-09-22T23:09:05.482Z</td>\n      <td>26805</td>\n      <td>29763</td>\n      <td>2606</td>\n      <td>...</td>\n      <td>True</td>\n      <td>2699166.00</td>\n      <td>2017-09-22T21:29:43.000Z</td>\n      <td>147</td>\n      <td>47.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>d7b8dca19b15e0b52d4a21fad60b8dac7b38f5fd</th>\n      <td>http://www.cnn.com/2017/09/30/politics/trump-t...</td>\n      <td>Trump attacks San Juan mayor over hurricane re...</td>\n      <td>2017-09-30 13:10:21.979</td>\n      <td>2017-09-30 13:05:07.000</td>\n      <td>324522</td>\n      <td>600.79</td>\n      <td>2017-09-30T14:45:08.993Z</td>\n      <td>112864</td>\n      <td>181960</td>\n      <td>29698</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28737538.00</td>\n      <td>2017-09-30T13:20:59.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>5.00</td>\n      <td>15.00</td>\n      <td>40.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>a3c5b9f1315aad42f86037db387093743e949368</th>\n      <td>http://www.cnn.com/2017/09/05/politics/daca-tr...</td>\n      <td>Trump ends DACA, but gives Congress window to ...</td>\n      <td>2017-09-05 15:18:16.587</td>\n      <td>2017-09-05 15:12:27.000</td>\n      <td>106307</td>\n      <td>389.12</td>\n      <td>2017-09-05T15:44:01.931Z</td>\n      <td>27624</td>\n      <td>65130</td>\n      <td>13553</td>\n      <td>...</td>\n      <td>True</td>\n      <td>28204756.00</td>\n      <td>2017-09-05T15:22:03.000Z</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>20.00</td>\n      <td>5.00</td>\n      <td>15.00</td>\n      <td>40.00</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>3cae93c5f6e373e9939f52c20ca2f6c119dd695b</th>\n      <td>http://www.huffingtonpost.com/entry/revive-you...</td>\n      <td>Revive Your Family on the Best Winter Vacation...</td>\n      <td>2017-09-15 18:18:16.858</td>\n      <td>2017-09-15 18:15:38.431</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-16T03:50:00.969Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>505dbb2bf9e0a7a809dd33a0b67e5432492214ed</th>\n      <td>https://www.washingtonpost.com/national/coast-...</td>\n      <td>Coast Guard suspends search for N Carolina men...</td>\n      <td>2017-09-03 17:24:07.265</td>\n      <td>2017-09-03 17:18:18.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-04T15:20:00.383Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>1cee3dfc94d901a4f5ee0a674e93b07ed244fa8e</th>\n      <td>http://www.dailymail.co.uk/sport/cricket/artic...</td>\n      <td>England batsman Keaton Jennings set to leave D...</td>\n      <td>2017-09-26 09:01:24.271</td>\n      <td>2017-09-26 08:59:16.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-09-26T10:14:05.025Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>1393e93bb1c4eac4faf1ba014ef98c9a021e4488</th>\n      <td>https://www.washingtonpost.com/national/hurric...</td>\n      <td>Hurricane watch in effect for Florida Keys, pa...</td>\n      <td>2017-09-07 15:24:12.613</td>\n      <td>2017-09-07 15:14:28.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-09-07T16:40:01.169Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>ad11c7355e1101976c3257970a9d360ee01ff77c</th>\n      <td>https://www.washingtonpost.com/politics/long-t...</td>\n      <td>Long-term US mortgage rates fall to lowest lev...</td>\n      <td>2017-09-07 15:24:07.391</td>\n      <td>2017-09-07 15:14:27.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-07T15:38:02.849Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>fb30f48fbf7656287634ba122cf6a31ae394205f</th>\n      <td>https://www.washingtonpost.com/local/winning-n...</td>\n      <td>Winning numbers drawn in \u2018DC 4 Midday\u2019 game</td>\n      <td>2017-09-15 18:27:11.304</td>\n      <td>2017-09-15 18:20:14.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-16T05:00:01.737Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>b23c6ee69b4ef5c31583c2f4ae30ac88852649c8</th>\n      <td>https://www.washingtonpost.com/local/winning-n...</td>\n      <td>Winning numbers drawn in \u2018Pick 4 Day\u2019 game</td>\n      <td>2017-09-15 18:27:14.499</td>\n      <td>2017-09-15 18:20:20.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-16T05:00:01.753Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>6320989548e7b6b931c86fd8f26aec50a964cff3</th>\n      <td>https://www.washingtonpost.com/world/national-...</td>\n      <td>Trump adviser says military option not preferr...</td>\n      <td>2017-09-15 18:27:09.992</td>\n      <td>2017-09-15 18:20:28.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-16T05:00:01.732Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>fa5a3963d1a16211c2b79e0f608d216edb76d640</th>\n      <td>https://www.washingtonpost.com/local/dc-lotter...</td>\n      <td>DC Lottery</td>\n      <td>2017-09-15 18:27:12.368</td>\n      <td>2017-09-15 18:20:33.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-16T05:00:01.739Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>9eeb8123352c7675b26f497bf862f298233655a4</th>\n      <td>https://www.washingtonpost.com/politics/federa...</td>\n      <td>Trump administration offers a new travel ban</td>\n      <td>2017-09-26 09:04:16.466</td>\n      <td>2017-09-26 08:57:22.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-26T11:17:07.377Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>cae3bcbaedc662e3cca8e7a91f19103301ddca37</th>\n      <td>http://www.bbc.co.uk/news/av/world-asia-411418...</td>\n      <td>Worried about North Korea?</td>\n      <td>2017-09-03 17:18:01.083</td>\n      <td>2017-09-03 17:16:41.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-04T15:14:00.442Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>f8fc25f41827dc3a09f22b1454d75d31087edf19</th>\n      <td>https://www.washingtonpost.com/local/winning-n...</td>\n      <td>Winning numbers drawn in \u2018DC 5 Midday\u2019 game</td>\n      <td>2017-09-15 18:27:10.106</td>\n      <td>2017-09-15 18:20:37.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-16T05:00:01.735Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>6572aea3fe9c36c73ae0b082d6e6a738530d61d4</th>\n      <td>https://www.washingtonpost.com/local/winning-n...</td>\n      <td>Winning numbers drawn in \u2018DC 3 Midday\u2019 game</td>\n      <td>2017-09-15 18:27:08.802</td>\n      <td>2017-09-15 18:20:44.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-16T05:00:01.730Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>814370ad5fb03aa2782c8920046011f3113d91f3</th>\n      <td>http://www.huffingtonpost.com/entry/how-your-u...</td>\n      <td>How Your Unusual Idea Can Spark Change</td>\n      <td>2017-09-15 18:33:16.512</td>\n      <td>2017-09-15 18:21:13.948</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-09-16T17:30:00.688Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>b341e964f21b813dddb39e2544f92abd99467617</th>\n      <td>https://www.washingtonpost.com/world/middle_ea...</td>\n      <td>Turkey warns Iraq: Kurdish referendum security...</td>\n      <td>2017-09-15 18:27:13.191</td>\n      <td>2017-09-15 18:21:15.000</td>\n      <td>1</td>\n      <td>0.02</td>\n      <td>2017-09-15T21:46:01.315Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>5429bdbedb7217d1a005978744b70e5d24e7adf3</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>8 was enough: Texas Tech defense rematch vs. A...</td>\n      <td>2017-09-15 18:27:12.568</td>\n      <td>2017-09-15 18:21:23.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-16T05:00:01.748Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>0d82f1792e97a5e694bd5d5d6c560d365e10ebb9</th>\n      <td>http://www.washingtonpost.com/video/world/bees...</td>\n      <td>Bees invade Australian home</td>\n      <td>2017-09-26 09:01:18.240</td>\n      <td>2017-09-26 08:54:11.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-26T11:14:05.859Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>efe770bbfac7362c79d46ab36a4f684f71b86057</th>\n      <td>http://www.foxnews.com/sports/2017/09/15/royal...</td>\n      <td>Royals-Indians game Saturday airs on FS1</td>\n      <td>2017-09-15 18:40:03.668</td>\n      <td>2017-09-15 18:21:43.000</td>\n      <td>1</td>\n      <td>0.00</td>\n      <td>2017-09-16T04:12:01.504Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>2300922d72f1dfd75bd914641edee108e42b40dc</th>\n      <td>http://www.bbc.co.uk/news/live/uk-england-suss...</td>\n      <td>BBC Live: Sussex on Friday 8 September 2017</td>\n      <td>2017-09-07 15:18:02.781</td>\n      <td>2017-09-07 15:14:07.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-07T15:32:03.378Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>878f6e8733a7c3ee626fbcc37ae157684e66516a</th>\n      <td>http://www.dailymail.co.uk/sport/article-48488...</td>\n      <td>Froome keeps Vuelta lead as Miguel Angel Lopez...</td>\n      <td>2017-09-03 17:21:18.961</td>\n      <td>2017-09-03 17:17:41.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-04T15:18:01.063Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>8af19589757e499bc8ea91662faca754a8a18d2a</th>\n      <td>http://www.bbc.co.uk/sport/football/41287263</td>\n      <td>Kilmarnock's Lee McCulloch delivers 'home trut...</td>\n      <td>2017-09-15 18:24:03.556</td>\n      <td>2017-09-15 18:22:43.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-16T06:00:01.867Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>96</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>3de1d53c2c31b35f1d38e5bbdcf26eef937a63cf</th>\n      <td>https://www.washingtonpost.com/sports/national...</td>\n      <td>Cubs shortstop Russell nears return from foot ...</td>\n      <td>2017-09-15 18:30:10.390</td>\n      <td>2017-09-15 18:24:22.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-16T04:02:01.249Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>3f762ebe86a2e48983ea058c8e00287056eb2eff</th>\n      <td>http://www.dailymail.co.uk/sport/cricket/artic...</td>\n      <td>Lyon helps Australia record victory over Bangl...</td>\n      <td>2017-09-07 15:15:22.842</td>\n      <td>2017-09-07 15:13:17.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-07T15:28:03.225Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>b60931c502c565965921d33aa3da0fb062f2b0dc</th>\n      <td>https://www.washingtonpost.com/local/winning-n...</td>\n      <td>Winning numbers drawn in \u2018Play 4 Day\u2019 game</td>\n      <td>2017-09-15 18:30:09.226</td>\n      <td>2017-09-15 18:25:09.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-16T04:02:01.248Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>69b7813fdfbf3dbb654e7fe2ea45a9cc41a0190b</th>\n      <td>https://www.washingtonpost.com/local/winning-n...</td>\n      <td>Winning numbers drawn in \u2018Play 3 Day\u2019 game</td>\n      <td>2017-09-15 18:30:09.191</td>\n      <td>2017-09-15 18:25:17.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-16T04:02:01.246Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>131f76f9485a82dfe2f80f5fa7e0a0e188a14cdc</th>\n      <td>https://www.washingtonpost.com/local/winning-n...</td>\n      <td>Winning numbers drawn in \u2018Cash 5 Day\u2019 game</td>\n      <td>2017-09-15 18:39:08.018</td>\n      <td>2017-09-15 18:25:22.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-16T04:10:01.012Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>b1c8f82f99814a195bae6da2873c843544629cb8</th>\n      <td>https://www.washingtonpost.com/sports/auto-rac...</td>\n      <td>Tony Kanaan says IndyCar finale will be last w...</td>\n      <td>2017-09-15 18:39:09.365</td>\n      <td>2017-09-15 18:25:28.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-16T04:10:01.016Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>c4f7fc9d58ff8dc8b105412b99a7e455ee9a9549</th>\n      <td>https://www.washingtonpost.com/politics/federa...</td>\n      <td>A tough start for GOP in a high-stakes week</td>\n      <td>2017-09-26 08:52:13.514</td>\n      <td>2017-09-26 08:51:41.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-26T11:05:09.073Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>329f1f0ea56ea1b61fa88204b2f898a649585362</th>\n      <td>http://www.huffingtonpost.com/entry/body-shami...</td>\n      <td>Body Shaming and The Rampant Judgment of Women</td>\n      <td>2017-09-15 18:33:14.571</td>\n      <td>2017-09-15 18:26:14.101</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-16T05:06:01.794Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n    <tr>\n      <th>25938ff119dd44a82dd96ff1593e4903541aaf9c</th>\n      <td>https://www.washingtonpost.com/sports/colleges...</td>\n      <td>Totten runs for 2 TDs as NCCU beats Div. II Sh...</td>\n      <td>2017-09-10 02:12:16.743</td>\n      <td>2017-09-10 02:08:07.000</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-10T07:36:01.184Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>False</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>152658 rows \u00d7 25 columns</p>\n</div>\n\n\n\n\n```python\ndata[\"score_diff\"] = data.promotion_score - data.response_score\n```\n\n\n```python\n# promoted but low response\ndata.sort_values(\"score_diff\", ascending=False).head(25)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n      <th>score_diff</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>b149ea3a151e68636d95ed9276493cc30e848afe</th>\n      <td>http://www.bbc.co.uk/news/world-africa-41123329</td>\n      <td>Judges annul Kenya presidential election</td>\n      <td>2017-09-01 08:54:00.852</td>\n      <td>2017-09-01 08:50:37</td>\n      <td>0</td>\n      <td>1981.84</td>\n      <td>2017-09-01T22:33:59.613Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>43741129.00</td>\n      <td>2017-09-01T09:39:04.000Z</td>\n      <td>96</td>\n      <td>0.00</td>\n      <td>20.00</td>\n      <td>8.00</td>\n      <td>15.00</td>\n      <td>43.00</td>\n      <td>43.00</td>\n      <td>43.00</td>\n    </tr>\n    <tr>\n      <th>dfc27a9222b7b195234505922dddcb80c81e588e</th>\n      <td>https://www.buzzfeed.com/johnpaczkowski/apple-...</td>\n      <td>Coming Up: The Biggest Announcements From Appl...</td>\n      <td>2017-09-12 12:54:19.843</td>\n      <td>2017-09-08 19:31:51</td>\n      <td>3</td>\n      <td>0.25</td>\n      <td>2017-09-12T13:08:01.784Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>...</td>\n      <td>2675254.00</td>\n      <td>2017-09-12T17:19:36.000Z</td>\n      <td>147</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>44.00</td>\n      <td>42.00</td>\n    </tr>\n    <tr>\n      <th>ada53b337d27f18d07e0887771e480401dcfd3e7</th>\n      <td>https://www.buzzfeed.com/johnpaczkowski/iphone...</td>\n      <td>How Apple Built An iPhone Camera That Makes Ev...</td>\n      <td>2017-09-22 13:49:20.295</td>\n      <td>2017-09-20 21:58:16</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>2017-09-22T14:00:07.330Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>2699863.00</td>\n      <td>2017-09-24T01:30:00.000Z</td>\n      <td>147</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>42.00</td>\n      <td>42.00</td>\n    </tr>\n    <tr>\n      <th>495281dd90c11682f9d07d81e498c14b7eb3c24d</th>\n      <td>https://www.buzzfeed.com/adambvary/summer-box-...</td>\n      <td>Why Hollywood Bombed So Badly This Summer</td>\n      <td>2017-09-03 16:20:05.028</td>\n      <td>2017-09-01 21:50:22</td>\n      <td>2</td>\n      <td>0.08</td>\n      <td>2017-09-03T16:34:00.954Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>...</td>\n      <td>2664073.00</td>\n      <td>2017-09-03T22:31:01.000Z</td>\n      <td>147</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>44.00</td>\n      <td>42.00</td>\n    </tr>\n    <tr>\n      <th>5d3a94d93655aedcc6c067b8dc6e59cdb472e92d</th>\n      <td>https://www.buzzfeed.com/jtes/women-are-spendi...</td>\n      <td>Women Are Spending Years In Prison Because Wyo...</td>\n      <td>2017-09-19 12:06:15.097</td>\n      <td>2017-09-15 20:37:05</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-19T12:20:01.415Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>2696756.00</td>\n      <td>2017-09-20T18:34:00.000Z</td>\n      <td>147</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>8.00</td>\n      <td>11.00</td>\n      <td>38.00</td>\n      <td>38.00</td>\n      <td>38.00</td>\n    </tr>\n    <tr>\n      <th>47c7627b33e6ac909d597b753965d91ed1cdf932</th>\n      <td>https://www.buzzfeed.com/albertsamaha/they-can...</td>\n      <td>Why A Cop With A Tattoo That Looks Like A Nazi...</td>\n      <td>2017-09-22 12:07:28.784</td>\n      <td>2017-09-20 15:40:15</td>\n      <td>1</td>\n      <td>0.10</td>\n      <td>2017-09-22T12:18:10.717Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>2698893.00</td>\n      <td>2017-09-22T14:16:06.000Z</td>\n      <td>147</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>7.00</td>\n      <td>11.00</td>\n      <td>37.00</td>\n      <td>37.00</td>\n      <td>37.00</td>\n    </tr>\n    <tr>\n      <th>0feb3bc421d776d3efcbf5e4aef07fd3be80b028</th>\n      <td>http://www.dailymail.co.uk/news/article-488703...</td>\n      <td>Explosion on underground train in south London</td>\n      <td>2017-09-15 07:45:12.603</td>\n      <td>2017-09-15 07:41:53</td>\n      <td>0</td>\n      <td>194.08</td>\n      <td>2017-09-15T09:10:01.432Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>12417198.00</td>\n      <td>2017-09-15T20:00:22.000Z</td>\n      <td>158</td>\n      <td>0.00</td>\n      <td>18.00</td>\n      <td>1.00</td>\n      <td>14.00</td>\n      <td>33.00</td>\n      <td>33.00</td>\n      <td>33.00</td>\n    </tr>\n    <tr>\n      <th>f0e103cc56d6fb0e459bedf75d9db013d20a7bf7</th>\n      <td>https://www.buzzfeed.com/buzzfeednews/watch-am...</td>\n      <td>Watch Our New Morning Show AM To DM!</td>\n      <td>2017-09-25 12:31:22.415</td>\n      <td>2017-09-24 22:49:46</td>\n      <td>39</td>\n      <td>0.23</td>\n      <td>2017-09-25T14:42:10.589Z</td>\n      <td>1</td>\n      <td>28</td>\n      <td>10</td>\n      <td>...</td>\n      <td>2700472.00</td>\n      <td>2017-09-25T13:57:00.000Z</td>\n      <td>147</td>\n      <td>6.00</td>\n      <td>19.00</td>\n      <td>9.00</td>\n      <td>11.00</td>\n      <td>39.00</td>\n      <td>45.00</td>\n      <td>33.00</td>\n    </tr>\n    <tr>\n      <th>61afb108d4605bff4febdb14172eaa3ce34b8f91</th>\n      <td>http://www.dailymail.co.uk/news/article-488457...</td>\n      <td>Fights break out ahead of Cologne Arsenal match</td>\n      <td>2017-09-14 14:48:25.961</td>\n      <td>2017-09-14 14:45:23</td>\n      <td>0</td>\n      <td>244.27</td>\n      <td>2017-09-15T10:06:01.808Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>12394441.00</td>\n      <td>2017-09-14T15:30:02.000Z</td>\n      <td>158</td>\n      <td>0.00</td>\n      <td>18.00</td>\n      <td>1.00</td>\n      <td>14.00</td>\n      <td>33.00</td>\n      <td>33.00</td>\n      <td>33.00</td>\n    </tr>\n    <tr>\n      <th>f7fdcfd9351b25d1769fe7def13c015e14ed5539</th>\n      <td>http://www.dailymail.co.uk/news/article-485784...</td>\n      <td>Hurricane Irma slams into Caribbean</td>\n      <td>2017-09-06 12:18:23.755</td>\n      <td>2017-09-06 12:16:18</td>\n      <td>0</td>\n      <td>57.50</td>\n      <td>2017-09-06T13:46:01.586Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>12305933.00</td>\n      <td>2017-09-07T00:00:20.000Z</td>\n      <td>158</td>\n      <td>0.00</td>\n      <td>18.00</td>\n      <td>1.00</td>\n      <td>14.00</td>\n      <td>33.00</td>\n      <td>33.00</td>\n      <td>33.00</td>\n    </tr>\n    <tr>\n      <th>d3cfc4bed55b56f152d3b746296c544a8634d325</th>\n      <td>https://www.buzzfeed.com/jonathanwachtel/we-ma...</td>\n      <td>We Made Allies Of Our WWII Enemies. Why Not No...</td>\n      <td>2017-09-28 21:19:27.919</td>\n      <td>2017-09-28 19:52:36</td>\n      <td>61</td>\n      <td>0.16</td>\n      <td>2017-09-28T23:32:04.353Z</td>\n      <td>9</td>\n      <td>46</td>\n      <td>6</td>\n      <td>...</td>\n      <td>2709015.00</td>\n      <td>2017-10-01T23:00:00.000Z</td>\n      <td>147</td>\n      <td>8.00</td>\n      <td>19.00</td>\n      <td>10.00</td>\n      <td>11.00</td>\n      <td>40.00</td>\n      <td>48.00</td>\n      <td>32.00</td>\n    </tr>\n    <tr>\n      <th>e664865f79868e9e592eb856e9089233a10f81ed</th>\n      <td>https://www.buzzfeed.com/lesterfeder/a-priest-...</td>\n      <td>People Are Watching This Election To See If Fa...</td>\n      <td>2017-09-16 13:21:16.484</td>\n      <td>2017-09-14 17:13:19</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-16T13:34:02.317Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>0.00</td>\n      <td>32.00</td>\n      <td>32.00</td>\n      <td>32.00</td>\n    </tr>\n    <tr>\n      <th>005982e350987fc505cde0b5c01d8b311d574522</th>\n      <td>https://www.buzzfeed.com/vanessagrigoriadis/se...</td>\n      <td>Campus Rapes Drop When Women Learn Self-Defens...</td>\n      <td>2017-09-01 19:06:15.799</td>\n      <td>2017-09-01 17:14:50</td>\n      <td>116</td>\n      <td>0.23</td>\n      <td>2017-09-02T17:02:00.227Z</td>\n      <td>13</td>\n      <td>68</td>\n      <td>35</td>\n      <td>...</td>\n      <td>2664820.00</td>\n      <td>2017-09-04T15:32:44.000Z</td>\n      <td>147</td>\n      <td>10.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>52.00</td>\n      <td>32.00</td>\n    </tr>\n    <tr>\n      <th>bcca0a691fb67db10058303b6ce8840849d5e0b0</th>\n      <td>https://www.buzzfeed.com/terrelljstarr/ukraine...</td>\n      <td>Ukraine Wants Trump To Make Up His Mind About ...</td>\n      <td>2017-09-20 14:57:14.858</td>\n      <td>2017-09-18 21:02:38</td>\n      <td>1</td>\n      <td>0.08</td>\n      <td>2017-09-20T15:10:02.596Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>0.00</td>\n      <td>31.00</td>\n      <td>31.00</td>\n      <td>31.00</td>\n    </tr>\n    <tr>\n      <th>e0fc5343a1736075c389de6d0c15c1a60aadc1fd</th>\n      <td>https://www.buzzfeed.com/franciswhittaker/sout...</td>\n      <td>South Korea Says The North May Be Preparing An...</td>\n      <td>2017-09-04 08:54:16.171</td>\n      <td>2017-09-04 08:39:38</td>\n      <td>144</td>\n      <td>0.67</td>\n      <td>2017-09-04T09:08:01.596Z</td>\n      <td>31</td>\n      <td>87</td>\n      <td>26</td>\n      <td>...</td>\n      <td>2664924.00</td>\n      <td>2017-09-04T17:33:18.000Z</td>\n      <td>147</td>\n      <td>12.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>55.00</td>\n      <td>31.00</td>\n    </tr>\n    <tr>\n      <th>ef7366fbf79ac24d0aea3bef2dad525edeaa5394</th>\n      <td>https://www.buzzfeed.com/karstenschmehl/german...</td>\n      <td>Trolls Are Trying To Hijack The German Electio...</td>\n      <td>2017-09-04 08:48:17.834</td>\n      <td>2017-09-01 15:30:52</td>\n      <td>1</td>\n      <td>0.08</td>\n      <td>2017-09-04T09:02:00.661Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>0.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>0.00</td>\n      <td>31.00</td>\n      <td>31.00</td>\n      <td>31.00</td>\n    </tr>\n    <tr>\n      <th>67850d9d2c463095a15a63bf7bc7d2722c5bc096</th>\n      <td>https://www.buzzfeed.com/leticiamiranda/workin...</td>\n      <td>Working In America Is Way Better Now Than It W...</td>\n      <td>2017-09-04 12:03:20.422</td>\n      <td>2017-09-03 14:05:41</td>\n      <td>2</td>\n      <td>0.03</td>\n      <td>2017-09-04T13:18:01.230Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>0.00</td>\n      <td>32.00</td>\n      <td>33.00</td>\n      <td>31.00</td>\n    </tr>\n    <tr>\n      <th>ec5e19ae42d089e82f0d3591a678525f526f7d62</th>\n      <td>https://www.buzzfeed.com/katiehasty/louis-ck-i...</td>\n      <td>Louis C.K.\u2019s Asking For It</td>\n      <td>2017-09-14 20:20:05.667</td>\n      <td>2017-09-14 03:32:55</td>\n      <td>70</td>\n      <td>0.47</td>\n      <td>2017-09-15T01:44:01.911Z</td>\n      <td>24</td>\n      <td>31</td>\n      <td>15</td>\n      <td>...</td>\n      <td>2679509.00</td>\n      <td>2017-09-16T21:45:00.000Z</td>\n      <td>147</td>\n      <td>8.00</td>\n      <td>19.00</td>\n      <td>9.00</td>\n      <td>11.00</td>\n      <td>39.00</td>\n      <td>47.00</td>\n      <td>31.00</td>\n    </tr>\n    <tr>\n      <th>d4ef0955d3cd7455a199a93ea4f896c9380048f7</th>\n      <td>https://www.buzzfeed.com/charliewarzel/mark-zu...</td>\n      <td>Mark Zuckerberg Can\u2019t Stop You From Reading Th...</td>\n      <td>2017-09-25 00:19:29.007</td>\n      <td>2017-09-23 19:06:04</td>\n      <td>2</td>\n      <td>0.18</td>\n      <td>2017-09-25T00:31:05.857Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>1.00</td>\n      <td>19.00</td>\n      <td>11.00</td>\n      <td>0.00</td>\n      <td>30.00</td>\n      <td>31.00</td>\n      <td>29.00</td>\n    </tr>\n    <tr>\n      <th>ca2ec806e28f815f4803cafb9947ce3d1f03f0fc</th>\n      <td>http://www.huffingtonpost.com/entry/independen...</td>\n      <td>Selling An Abortion Clinic Might Be Even Harde...</td>\n      <td>2017-09-01 02:10:06.117</td>\n      <td>2017-09-01 02:01:18</td>\n      <td>94</td>\n      <td>0.40</td>\n      <td>2017-09-02T01:10:01.229Z</td>\n      <td>45</td>\n      <td>35</td>\n      <td>14</td>\n      <td>...</td>\n      <td>9708625.00</td>\n      <td>2017-09-01T21:01:19.000Z</td>\n      <td>215</td>\n      <td>9.00</td>\n      <td>17.00</td>\n      <td>8.00</td>\n      <td>13.00</td>\n      <td>38.00</td>\n      <td>47.00</td>\n      <td>29.00</td>\n    </tr>\n    <tr>\n      <th>a6953cfdcd36c970df9859458d7570a99e41c674</th>\n      <td>http://www.independent.co.uk/news/uk/politics/...</td>\n      <td>Brexit: deportations of EU citizens soar since...</td>\n      <td>2017-09-10 20:57:12.905</td>\n      <td>2017-09-07 18:09:13</td>\n      <td>3</td>\n      <td>0.17</td>\n      <td>2017-09-10T21:10:01.051Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>...</td>\n      <td>7421886.00</td>\n      <td>2017-09-11T11:46:00.000Z</td>\n      <td>386</td>\n      <td>1.00</td>\n      <td>16.00</td>\n      <td>1.00</td>\n      <td>13.00</td>\n      <td>30.00</td>\n      <td>31.00</td>\n      <td>29.00</td>\n    </tr>\n    <tr>\n      <th>f14ab3386893187ad35ff2431d8f69f5055b3168</th>\n      <td>https://www.buzzfeed.com/amberjamieson/beaumon...</td>\n      <td>Beaumont Evacuees Are Flown To Dallas As Flood...</td>\n      <td>2017-09-01 22:00:21.801</td>\n      <td>2017-09-01 21:59:50</td>\n      <td>244</td>\n      <td>0.84</td>\n      <td>2017-09-02T18:54:00.747Z</td>\n      <td>35</td>\n      <td>156</td>\n      <td>53</td>\n      <td>...</td>\n      <td>2663099.00</td>\n      <td>2017-09-02T17:03:00.000Z</td>\n      <td>147</td>\n      <td>14.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>11.00</td>\n      <td>42.00</td>\n      <td>56.00</td>\n      <td>28.00</td>\n    </tr>\n    <tr>\n      <th>97ec34ddd972abea0c8eaf1e5c5eedb69f34b830</th>\n      <td>https://www.buzzfeed.com/buzzfeednews/live-upd...</td>\n      <td>Live Updates: Floridians Struggle To Begin Cle...</td>\n      <td>2017-09-13 11:45:16.474</td>\n      <td>2017-09-13 11:44:39</td>\n      <td>18</td>\n      <td>0.08</td>\n      <td>2017-09-13T16:06:01.902Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>18</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>3.00</td>\n      <td>19.00</td>\n      <td>12.00</td>\n      <td>0.00</td>\n      <td>31.00</td>\n      <td>34.00</td>\n      <td>28.00</td>\n    </tr>\n    <tr>\n      <th>9ebf1287ea5d6cef8d4225c9a8ade06dbccc62ac</th>\n      <td>http://www.bbc.co.uk/news/live/uk-england-lond...</td>\n      <td>BBC Local Live: Updates from London on Monday ...</td>\n      <td>2017-09-10 15:33:04.406</td>\n      <td>2017-09-10 15:29:43</td>\n      <td>0</td>\n      <td>0.00</td>\n      <td>2017-09-11T01:04:00.103Z</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>...</td>\n      <td>43999822.00</td>\n      <td>2017-09-15T09:19:55.000Z</td>\n      <td>96</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>13.00</td>\n      <td>15.00</td>\n      <td>28.00</td>\n      <td>28.00</td>\n      <td>28.00</td>\n    </tr>\n    <tr>\n      <th>c7537e28cc23047329945e9c80c7323055d41ffe</th>\n      <td>https://www.buzzfeed.com/zanromanoff/how-the-k...</td>\n      <td>How The Kardashians Reflect Changing Ideas Aro...</td>\n      <td>2017-09-15 21:50:05.919</td>\n      <td>2017-09-15 14:48:23</td>\n      <td>313</td>\n      <td>1.71</td>\n      <td>2017-09-16T14:48:01.071Z</td>\n      <td>56</td>\n      <td>201</td>\n      <td>56</td>\n      <td>...</td>\n      <td>2679435.00</td>\n      <td>2017-09-16T16:44:00.000Z</td>\n      <td>147</td>\n      <td>16.00</td>\n      <td>19.00</td>\n      <td>13.00</td>\n      <td>11.00</td>\n      <td>43.00</td>\n      <td>59.00</td>\n      <td>27.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>25 rows \u00d7 26 columns</p>\n</div>\n\n\n\n\n```python\n# high response but not promoted\ndata.sort_values(\"score_diff\", ascending=True).head(25)\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>headline</th>\n      <th>discovered</th>\n      <th>published</th>\n      <th>fb_engagements</th>\n      <th>fb_max_engagements_per_min</th>\n      <th>fb_max_engagements_per_min_time</th>\n      <th>fb_comments</th>\n      <th>fb_reactions</th>\n      <th>fb_shares</th>\n      <th>...</th>\n      <th>fb_brand_page_likes</th>\n      <th>fb_brand_page_time</th>\n      <th>alexa_rank</th>\n      <th>response_score</th>\n      <th>lead_score</th>\n      <th>front_score</th>\n      <th>facebook_promotion_score</th>\n      <th>promotion_score</th>\n      <th>attention_index</th>\n      <th>score_diff</th>\n    </tr>\n    <tr>\n      <th>id</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>847e11ad09dcdffaaf4746032ad1664a1067da8a</th>\n      <td>http://www.huffingtonpost.com/entry/if-the-pro...</td>\n      <td>If The Protest Outrages You, But The Cause Doe...</td>\n      <td>2017-09-25 20:46:24.106</td>\n      <td>2017-09-25 20:40:30.716</td>\n      <td>109288</td>\n      <td>235.98</td>\n      <td>2017-09-27T00:20:11.580Z</td>\n      <td>15892</td>\n      <td>80756</td>\n      <td>12640</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>215</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>2812dae6a98764e8b1c9b2f3fc6c370047793546</th>\n      <td>https://www.buzzfeed.com/javieraceves/las-tien...</td>\n      <td>Canad\u00e1 envi\u00f3 1500 tiendas de campa\u00f1a y el SAT ...</td>\n      <td>2017-09-28 17:19:32.150</td>\n      <td>2017-09-28 17:10:22.000</td>\n      <td>337311</td>\n      <td>367.95</td>\n      <td>2017-09-29T03:01:05.580Z</td>\n      <td>40454</td>\n      <td>199045</td>\n      <td>97812</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>bc24ca5aedc56346e619a6b1c05374338f7ff826</th>\n      <td>https://www.washingtonpost.com/local/education...</td>\n      <td>Senate panel rejects Trump\u2019s proposed  federal...</td>\n      <td>2017-09-07 22:12:09.409</td>\n      <td>2017-09-07 22:05:00.000</td>\n      <td>111176</td>\n      <td>209.29</td>\n      <td>2017-09-10T19:04:00.023Z</td>\n      <td>6724</td>\n      <td>96145</td>\n      <td>8307</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>423bab68e6dbb29153f05f4036e5adf84decefc2</th>\n      <td>http://www.cnn.com/2016/01/11/entertainment/da...</td>\n      <td>David Bowie, a master of music and makeovers, ...</td>\n      <td>2017-09-08 16:51:14.029</td>\n      <td>2017-09-08 16:46:06.000</td>\n      <td>118977</td>\n      <td>0.03</td>\n      <td>2017-09-08T18:06:02.670Z</td>\n      <td>8971</td>\n      <td>100422</td>\n      <td>9584</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>0e6098488737a461a546cb6ddadc70db9c220fc3</th>\n      <td>https://www.washingtonpost.com/national/health...</td>\n      <td>Police officer who arrested Utah nurse fired f...</td>\n      <td>2017-09-05 21:39:12.763</td>\n      <td>2017-09-05 21:33:13.000</td>\n      <td>246436</td>\n      <td>2698.89</td>\n      <td>2017-09-06T00:58:01.409Z</td>\n      <td>30634</td>\n      <td>189357</td>\n      <td>26445</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>2ac8e6d2202d8c603b8fb20f6b3defa24f357c61</th>\n      <td>http://www.washingtonpost.com/video/local/weat...</td>\n      <td>San Juan mayor: 'There is horror in the streets'</td>\n      <td>2017-09-23 21:58:22.408</td>\n      <td>2017-09-23 20:41:42.000</td>\n      <td>109615</td>\n      <td>213.36</td>\n      <td>2017-09-25T23:04:02.843Z</td>\n      <td>15658</td>\n      <td>72891</td>\n      <td>21066</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>d10e7ebabab09ec6a72423d3995796f9536c23bc</th>\n      <td>https://www.buzzfeed.com/tatianafarah/veja-30-...</td>\n      <td>Veja 30 obras da exposi\u00e7\u00e3o censurada no Santan...</td>\n      <td>2017-09-12 21:24:18.661</td>\n      <td>2017-09-12 20:53:22.000</td>\n      <td>174607</td>\n      <td>154.33</td>\n      <td>2017-09-13T02:28:01.800Z</td>\n      <td>57836</td>\n      <td>102143</td>\n      <td>14628</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>22f025d7af4929e90cbb43329af351961cbe3dbd</th>\n      <td>http://www.cnn.com/2017/09/18/americas/hurrica...</td>\n      <td>Hurricane Maria strengthens to Category 5</td>\n      <td>2017-09-19 00:03:16.021</td>\n      <td>2017-09-18 23:59:39.000</td>\n      <td>144371</td>\n      <td>1366.45</td>\n      <td>2017-09-19T03:22:00.487Z</td>\n      <td>33573</td>\n      <td>88346</td>\n      <td>22452</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>105</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>50.00</td>\n      <td>-50.00</td>\n    </tr>\n    <tr>\n      <th>3942b12bb0a8dddd8b1a5c962a5b0d2f800684d6</th>\n      <td>https://www.nytimes.com/2017/09/01/business/mi...</td>\n      <td>Michael Dell, Tech Billionaire, Pledges $36 Mi...</td>\n      <td>2017-09-01 12:18:01.060</td>\n      <td>2017-09-01 12:16:21.000</td>\n      <td>134143</td>\n      <td>141.86</td>\n      <td>2017-09-01T16:12:00.598Z</td>\n      <td>7974</td>\n      <td>112734</td>\n      <td>13435</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>120</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>51.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>6d54a9c6501d7a327248c579b685de99ae0c3456</th>\n      <td>https://www.nytimes.com/2017/09/28/us/jones-ac...</td>\n      <td>Jones Act Suspended, Easing Aid Shipments to P...</td>\n      <td>2017-09-28 12:43:08.600</td>\n      <td>2017-09-28 12:41:38.000</td>\n      <td>81931</td>\n      <td>191.13</td>\n      <td>2017-09-28T13:55:03.833Z</td>\n      <td>17266</td>\n      <td>52888</td>\n      <td>11777</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>120</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>49.00</td>\n      <td>-49.00</td>\n    </tr>\n    <tr>\n      <th>d81a87a3b13f2622a78aeb0c6405f0cfafee7deb</th>\n      <td>http://www.dailymail.co.uk/news/article-489852...</td>\n      <td>Navy staff probed over 'sick' pictures with ne...</td>\n      <td>2017-09-20 07:09:16.336</td>\n      <td>2017-09-19 10:40:08.000</td>\n      <td>83538</td>\n      <td>26.65</td>\n      <td>2017-09-20T12:42:00.165Z</td>\n      <td>22255</td>\n      <td>55205</td>\n      <td>6078</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>50.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>5505aed7fe7dec69e83ab5cdeb8e030fe9a98d46</th>\n      <td>https://www.reuters.com/article/us-storm-maria...</td>\n      <td>U.S. denies request for Puerto Rico shipping w...</td>\n      <td>2017-09-26 20:04:17.320</td>\n      <td>2017-09-26 19:57:23.000</td>\n      <td>83962</td>\n      <td>332.54</td>\n      <td>2017-09-27T07:05:11.220Z</td>\n      <td>22198</td>\n      <td>47714</td>\n      <td>14050</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>497</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>50.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>97b4941e7757e6073c9d85c39b347c611278e0f6</th>\n      <td>http://www.dailymail.co.uk/news/article-484567...</td>\n      <td>John Lewis ditches 'boys' and 'girls' labels o...</td>\n      <td>2017-09-01 22:51:20.523</td>\n      <td>2017-09-01 22:48:46.000</td>\n      <td>96611</td>\n      <td>6659.17</td>\n      <td>2017-09-03T21:19:59.809Z</td>\n      <td>28346</td>\n      <td>62353</td>\n      <td>5912</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>158</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>50.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>be8f14c73f781b72f4f095506860d428f0e6b4da</th>\n      <td>https://www.reuters.com/article/storm-maria-pu...</td>\n      <td>U.S. denies request for Puerto Rico shipping w...</td>\n      <td>2017-09-26 19:49:09.431</td>\n      <td>2017-09-26 19:45:42.000</td>\n      <td>84393</td>\n      <td>745.32</td>\n      <td>2017-09-27T01:05:07.085Z</td>\n      <td>22381</td>\n      <td>47901</td>\n      <td>14111</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>497</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>50.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>442a1ac6371ba39f4b0ae21937357ab8eda0b9bd</th>\n      <td>http://insider.foxnews.com/2017/09/11/tomi-lah...</td>\n      <td>Tomi Lahren: Final Thoughts on Sunday Kneeling...</td>\n      <td>2017-09-11 23:05:04.997</td>\n      <td>2017-09-11 18:15:00.000</td>\n      <td>141071</td>\n      <td>608.27</td>\n      <td>2017-09-11T23:18:02.042Z</td>\n      <td>16388</td>\n      <td>108693</td>\n      <td>15990</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>52.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>300aa0307f1b99da03abd9d37f28ef2e75a9d9ae</th>\n      <td>https://www.buzzfeed.com/stephaniemcneal/love-...</td>\n      <td>This Bride Had A Bouquet Made Of Doughnuts On ...</td>\n      <td>2017-09-12 16:57:24.308</td>\n      <td>2017-09-12 16:57:06.000</td>\n      <td>130965</td>\n      <td>419.33</td>\n      <td>2017-09-13T19:07:59.758Z</td>\n      <td>69608</td>\n      <td>56040</td>\n      <td>5317</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>52.00</td>\n      <td>-48.00</td>\n    </tr>\n    <tr>\n      <th>74bb44bb13cdf421f83f15272dfd5f15801b4629</th>\n      <td>http://www.foxnews.com/politics/2017/09/27/mic...</td>\n      <td>Michelle Obama slams women who voted for Trump</td>\n      <td>2017-09-27 20:54:16.608</td>\n      <td>2017-09-27 20:45:00.000</td>\n      <td>75781</td>\n      <td>197.16</td>\n      <td>2017-09-28T16:32:08.848Z</td>\n      <td>28174</td>\n      <td>42243</td>\n      <td>5364</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>48.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>49.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>af7e6bb3fdf38ac1bf37f696bb94fe1099af7552</th>\n      <td>https://www.washingtonpost.com/news/post-polit...</td>\n      <td>Trump\u2019s son-in-law Jared Kushner used a privat...</td>\n      <td>2017-09-24 22:58:11.527</td>\n      <td>2017-09-24 22:53:59.000</td>\n      <td>78368</td>\n      <td>3045.95</td>\n      <td>2017-09-25T03:38:09.964Z</td>\n      <td>15447</td>\n      <td>53819</td>\n      <td>9102</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>48.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>49.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>aef9af4a52f05dee48fb98ece49cc8f870fd5197</th>\n      <td>https://www.washingtonpost.com/news/checkpoint...</td>\n      <td>Clinton pressed Trump to deploy hospital ship ...</td>\n      <td>2017-09-26 20:37:16.766</td>\n      <td>2017-09-26 20:33:12.000</td>\n      <td>127262</td>\n      <td>135.18</td>\n      <td>2017-09-27T02:50:03.001Z</td>\n      <td>22279</td>\n      <td>87002</td>\n      <td>17981</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>50.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>53.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>d4a0b1812294d9d7df73a5bea80e8c9fc3f38118</th>\n      <td>http://www.foxnews.com/entertainment/2017/09/2...</td>\n      <td>Canada's prime minister ridiculed for Chewbacc...</td>\n      <td>2017-09-20 23:10:06.252</td>\n      <td>2017-09-20 22:41:25.000</td>\n      <td>78990</td>\n      <td>312.46</td>\n      <td>2017-09-22T05:02:11.097Z</td>\n      <td>19270</td>\n      <td>55883</td>\n      <td>3837</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>48.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>0.00</td>\n      <td>1.00</td>\n      <td>49.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>d26aabc0297fb47a6f71c65954275629c462c029</th>\n      <td>http://www.foxnews.com/entertainment/2017/09/0...</td>\n      <td>Country music star Troy Gentry, 50, dies in Pe...</td>\n      <td>2017-09-08 20:20:04.613</td>\n      <td>2017-09-08 20:05:00.000</td>\n      <td>94949</td>\n      <td>292.25</td>\n      <td>2017-09-08T21:10:02.516Z</td>\n      <td>14841</td>\n      <td>61660</td>\n      <td>18448</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>51.00</td>\n      <td>-47.00</td>\n    </tr>\n    <tr>\n      <th>a02df93727c5975bc2506b78c5d9ed65f813daff</th>\n      <td>http://www.foxnews.com/world/2017/09/22/doomsd...</td>\n      <td>Doomsday is not on Saturday after all, Christi...</td>\n      <td>2017-09-22 14:49:14.541</td>\n      <td>2017-09-22 14:33:18.000</td>\n      <td>79705</td>\n      <td>80.43</td>\n      <td>2017-09-23T11:24:04.973Z</td>\n      <td>25033</td>\n      <td>45219</td>\n      <td>9453</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>285</td>\n      <td>48.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>0.00</td>\n      <td>2.00</td>\n      <td>50.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>d50425525120f1de4f0438b91189e93eafd7aa39</th>\n      <td>https://www.nytimes.com/2017/09/16/health/bras...</td>\n      <td>Como a Grande Ind\u00fastria Viciou o Brasil em Jun...</td>\n      <td>2017-09-16 12:51:00.660</td>\n      <td>2017-09-16 12:50:37.000</td>\n      <td>52380</td>\n      <td>33.13</td>\n      <td>2017-09-17T16:51:59.718Z</td>\n      <td>5229</td>\n      <td>37901</td>\n      <td>9250</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>120</td>\n      <td>46.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>46.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>11134532da6de27a27478bf59ee8b7ea49788ce7</th>\n      <td>https://www.buzzfeed.com/florapaul/habilite-o-...</td>\n      <td>Mulheres, atualizem o iPhone de voc\u00eas para o i...</td>\n      <td>2017-09-21 15:22:25.861</td>\n      <td>2017-09-21 15:05:50.000</td>\n      <td>54545</td>\n      <td>104.86</td>\n      <td>2017-09-22T14:23:07.298Z</td>\n      <td>9430</td>\n      <td>41056</td>\n      <td>4059</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>147</td>\n      <td>46.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>0.00</td>\n      <td>46.00</td>\n      <td>-46.00</td>\n    </tr>\n    <tr>\n      <th>d24f06cf636952c454dcda24fa51db7e4f899987</th>\n      <td>https://www.washingtonpost.com/news/acts-of-fa...</td>\n      <td>Why this Muslim-turned-Christian speaker reson...</td>\n      <td>2017-09-17 20:15:12.625</td>\n      <td>2017-09-17 20:04:55.000</td>\n      <td>90744</td>\n      <td>135.13</td>\n      <td>2017-09-17T22:32:00.253Z</td>\n      <td>5436</td>\n      <td>71191</td>\n      <td>14117</td>\n      <td>...</td>\n      <td>nan</td>\n      <td>NaN</td>\n      <td>191</td>\n      <td>49.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>0.00</td>\n      <td>3.00</td>\n      <td>52.00</td>\n      <td>-46.00</td>\n    </tr>\n  </tbody>\n</table>\n<p>25 rows \u00d7 26 columns</p>\n</div>\n\n\n\nWrite that data to a file. Note that the scores here are provisional for two reasons:\n1. they should be using a rolling-month based on the article publication date to calculate medians/min/max etc, whereas in this workbook we as just using values for the month of May\n2. for analysis, we've rounded the numbers; we don't expect to do that for the actual scores\n\n\n```python\ndata.to_csv(\"articles_with_provisional_scores_2017-09-01_2017-09-30.csv\")\n```\n\n# Summary\n\nThe attention index of an article is comprised of four components:\n\n- *lead score* (max 20 points) based on how long an article was the lead story on the publisher's home page, scaled by the traffic to that publisher\n- *front score* (max 15 points) based on how long an article was present on the publisher's home page, scaled by traffic to that publisher\n- *Facebook promotion score* (max 15 points) based on whether the article was promoted to the publisher's Facebook brand page, scaled by the reach of that brand page\n- *response score* (max 50 points) based on the number of Facebook engagements the article received, relative to other articles\n\nOr, in other words:\n\n\\begin{align}\nattentionIndex_a &= leadScore_a + frontScore_a + facebookPromotionScore_a + responseScore_a \\\\\nleadScore_a &= 20 \\cdot \\left(\\frac{\\min(minsAsLead_a, 60)}{alexaRank_a}\\right) \\cdot \\left( \\frac{\\min(alexaRank)}{60} \\right) \\\\\nfrontScore_a &= \n15 \\cdot\n\\left(\\frac{\\min(minsOnFront_a, 1440)}{alexaRank_a \\cdot numArticlesOnFront_a}\\right) \\cdot\n\\left( \\frac{\\min(alexaRank \\cdot numArticlesOnFront)}{1440} \\right) \\\\\nfacebookPromotion_a &= \n\\begin{cases}\n 0 \\text{ if not shared on brand page }\\\\\n   15 \\cdot \\frac{\\log(brandPageLikes_a) - \\log(\\min(brandPageLikes))}{\\log(\\max(brandPageLikes)) - \\log(\\min(brandPageLikes))}  \\text{ otherwise }\n\\end{cases}   \n\\\\\nresponseScore_a &= \n\\begin{cases} \n   0 \\text{ if } engagements_a = 0 \\\\\n   50 \\cdot \n   \\frac{\\log(\\min(engagements_a,limit) + median(engagements)) - \\log(1 + median(engagements))}\n   {\\log(limit + median(engagements)) - \\log(1 + median(engagements))} \\text{ if } engagements_a > 0\n\\end{cases} \\\\\n\\end{align} \n\n\n```python\n\n```\n", "meta": {"hexsha": "3909b2464ddbf364877b7bf0203dc29c69c8c277", "size": 707453, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "data/attention-index-september.ipynb", "max_stars_repo_name": "kaleida/attention-index", "max_stars_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2017-06-03T11:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T10:02:06.000Z", "max_issues_repo_path": "data/attention-index-september.ipynb", "max_issues_repo_name": "kaleida/attention-index", "max_issues_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data/attention-index-september.ipynb", "max_forks_repo_name": "kaleida/attention-index", "max_forks_repo_head_hexsha": "37c885f4a9cb549f5634b23bff674dca18971500", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 82.175978627, "max_line_length": 47056, "alphanum_fraction": 0.6824326139, "converted": true, "num_tokens": 56198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3106943959796865, "lm_q2_score": 0.03904829650044905, "lm_q1q2_score": 0.012132086895242726}}
{"text": "```python\n%load_ext notexbook\n```\n\n\n```python\n%texify -v\n```\n\n\n\n\n<style type=\"text/css\">\n    /*\nAuthor: Valerio Maggio < @leriomaggio >\nCode: https://github.com/leriomaggio/notexbook-jupyter-theme\nLicense: Apache License 2.0\n*/\n\n/*\nAuthor: Valerio Maggio < @leriomaggio >\nCode: https://github.com/leriomaggio/notexbook-jupyter-theme\nLicense: Apache License 2.0\n\n ======================================================\n                         FONTS\n\n    FONT WEIGHT MAP:\n    ----------------\n    100: Ultra Light\n    200: Thin\n    300: Light\n    400: Regular (normal)\n    500: Medium\n    600: Semi-bold\n    700: Bold\n    800: Heavy\n    900: Black\n\n    Font faces:\n        - ====================================|=======================\n        -              Scope                  | Font Family Name\n        - ====================================| ======================\n        - Markdown Display (Computer Modern)    (CMU Serif)\n        - Markdown Display monospace            (CMU Typewriter Text)\n        - Markdown Edit    monospace            (Hack)\n        - Source Code      monospace            (Fira Code)\n        - ====================================| =======================\n\n ======================================================  */\n\n/* Roboto Slab */\n@import url(\"https://fonts.googleapis.com/css2?family=Roboto+Slab:wght@100;200;300;400;500;600;700;800;900&display=swap\");\n/*md-display-computer-modern --> CMU Serif*/\n@import url(\"https://fonts.cdnfonts.com/css/cmu-serif?styles=30038,30039,30037,30036\");\n/*md-display-monospace --> CMU Typewriter Text*/\n@import url(\"https://fonts.cdnfonts.com/css/cmu-typewriter-text?styles=24833,24829,24830,24831,24832,24834\");\n/*code-monospace --> Fira Code*/\n@import url(\"https://fonts.googleapis.com/css2?family=Fira+Code:wght@300;400;500&display=swap\");\n/*md-edit-monospace --> Hack*/\n@import url(\"https://fonts.cdnfonts.com/css/hack?styles=20708,20707,20705,20706\");\n/*\nAuthor: Valerio Maggio < @leriomaggio >\nCode: https://github.com/leriomaggio/notexbook-jupyter-theme\nLicense: Apache License 2.0\n\n======================================================\n\n\n    ---------------------------------\n    Code Mirror - Code Cell Highlight\n    ---------------------------------\n\n    Define the Style for Code **and** Markdown editors (Themes)\n    Theme files are all located in the \"themes\" folder, and the\n    different styles for the Code and Markdown editors are\n    distinguished by a common prefix in the file names:\n\n        --> Code editors Themes: \"themes/code_*\"\n        --> Markdown Editor Themes: \"themes/md_*\"\n\n    Styles can be imported as separate CSS modules.\n\n    Current stylesheet (editor.css) defines the CSS rules\n    for notebook tags and classes. These rules are\n    all based to colors defined in external Theme files.\n\n    This would ease the definition of other custom CSS Editor themes\n*/\n\n/* Code Editor theme */\n\n    /*\nAuthor: Valerio Maggio < @leriomaggio >\nCode: https://github.com/leriomaggio/notexbook-jupyter-theme\nLicense: Apache License 2.0\n\n ======================================================\n\nThe color palette is inspired by Light\n Material Design theme\nRepo: https://github.com/JonaDuran/Material-Light-Theme/\n*/\n\n:root {\n    /* Color Palette */\n    --ml-white: #ffffff;\n    --ml-light-white: #FAFAFA;\n    --ml-black: #24292E;\n    --ml-dark-blue : #01579B11;\n    --ml-dark-blue-2: #01579B22;\n    --ml-blue: #1565C0;\n    --ml-green: #2E7D32;\n    --ml-yellow: #A8601A;\n    --ml-cyan: #00838f;\n    --ml-magenta: #9C00B0;\n    --ml-red: #C0392B;\n    --ml-grey: #9E9E9E;\n    --ml-light-blue: #78909c;\n\n\n    /* Editor Theme */\n    --code-background-color: var(--ml-light-white);\n    --gutter-background: var(--ml-light-white);\n    --selection-background-color: var(--ml-dark-blue-2);\n    --line-numbers: var(--ml-grey);\n    --cursor: var(--ml-black);\n    --bracket: var(--ml-black);\n    --matching-bracket: var(--ml-blue);\n    --code-text-color: var(--ml-black);\n    --keywords: var(--ml-magenta);\n    --types: var(--ml-magenta);\n    --variables: var(--code-text-color);\n    --variables2: var(--ml-green);\n    --def: var(--ml-blue);\n    --property: var(--ml-blue);\n    --meta: var(--ml-light-blue);\n    --builtin: var(--ml-blue);\n    --attribute: var(--ml-blue);\n    --strings: var(--ml-yellow);\n    --strings2: var(--ml-grey);\n    --comments: var(--ml-grey);\n    --operator: var(--ml-magenta);\n    --numbers: var(--ml-red);\n    /* Dataframe */\n    --dataframe: var(--code-text-color);\n    --df-bg: var(--ml-light-white);\n    --df-thead: var(--ml-blue);\n    --df-thead-border: var(--ml-black);\n    --df-tr-hover: var(--selection-background-color);\n    --df-border: var(--ml-white);\n    --df-border-right: var(--ml-grey);\n    --df-th-bg: var(--ml-white);\n    /*ANSI Colours*/\n    --ansi-red: var(--ml-red);\n    --ansi-green: var(--ml-green);\n    --ansi-green-intense: var(--ml-grey);\n    --ansi-cyan: var(--ml-cyan);\n    --ansi-blue: var(--ml-blue);\n}\n\n\n\n/* Markdown Editor theme */\n\n    /*\nAuthor: Valerio Maggio < @leriomaggio >\nCode: https://github.com/leriomaggio/notexbook-jupyter-theme\nLicense: Apache License 2.0\n\n ======================================================\n\n    Custom Theme for Markdown Editor\n    based on Material Clear Theme.\n\n */\n\n:root {\n    /* Color Palette */\n    --md-ml-red: #C0392B;\n    --md-ml-yellow: #A8601A;\n    --md-ml-black: #24292E;\n    --md-ml-grey: #9E9E9E;\n    --md-ml-blue: #1565C0;\n    --md-ml-dark-blue: #01579B;\n    --md-ml-light-blue: #78909c;\n\n    /*  Editor Theme  */\n    --editor-text: var(--md-ml-black);\n    --header: var(--md-ml-dark-blue);\n    --quote: var(--md-ml-grey);\n    --link: var(--md-ml-blue);\n    --attribute: var(--md-ml-red);\n    --tag: var(--md-ml-yellow);\n    --string: var(--md-ml-yellow);\n    --delimiter: var(--md-ml-black);\n    --monospace: var(--md-ml-light-blue);\n}\n\n\n\n\n\n\n\n/*\nAuthor: Valerio Maggio < @leriomaggio >\nCode: https://github.com/leriomaggio/notexbook-jupyter-theme\nLicense: Apache License 2.0\n*/\n\n/*\n    =================\n    Code Editor Theme\n    =================\n*/\ndiv.output_error pre,\ndiv.output_result pre,\ndiv.output_stream pre {\n    color: var(--code-text-color) !important;\n}\n\n.cm-s-ipython.CodeMirror,\n.cm-s-jupyter.CodeMirror {\n    background: var(--code-background-color);\n    color: var(--code-text-color);\n}\n\n.cm-s-ipython div.CodeMirror-selected,\n.cm-s-jupyter div.CodeMirror-selected {\n    cursor: pointer;\n    background: var(--selection-background-color);\n}\n\n.cm-s-ipython .CodeMirror-gutters,\n.cm-s-jupyter .CodeMirror-gutters {\n    background: var(--gutter-background);\n    border-right: 0;\n}\n\n.cm-s-ipython .CodeMirror-linenumber,\n.cm-s-jupyter .CodeMirror-linenumber {\n    color: var(--line-numbers);\n}\n\n.cm-s-ipython .CodeMirror-cursor,\n.cm-s-jupyter .CodeMirror-cursor {\n    border-left: 1px solid var(--cursor) !important;\n}\n\n.cm-s-ipython span.cm-bracket,\n.cm-s-jupyter span.cm-bracket {\n    /*color: #828282;*/\n    color: var(--bracket);\n}\n\nspan.CodeMirror-matchingbracket {\n    text-decoration: underline !important;\n    text-decoration-color: var(--matching-bracket) !important;\n    color: var(--matching-bracket) !important;\n}\n\n.cm-s-ipython span.cm-keyword,\n.cm-s-jupyter span.cm-keyword {\n    color: var(--keywords);\n    font-weight: 400;\n}\n\n.cm-s-ipython span.cm-variable,\n.cm-s-jupyter span.cm-variable {\n    color: var(--variables);\n}\n\n.cm-s-ipython span.cm-variable-2,\n.cm-s-jupyter span.cm-variable-2 {\n    color: var(--variables2);\n}\n\n.cm-s-ipython span.cm-def,\n.cm-s-jupyter span.cm-def {\n    color: var(--def);\n}\n\n.cm-s-ipython span.cm-property,\n.cm-s-jupyter span.cm-property {\n    color: var(--property);\n}\n\n.cm-s-ipython span.cm-meta,\n.cm-s-jupyter span.cm-meta {\n    color: var(--meta);\n}\n\n.cm-s-ipython span.cm-attribute,\n.cm-s-jupyter span.cm-attribute {\n    color: var(--attribute);\n}\n\n.cm-s-ipython span.cm-builtin,\n.cm-s-jupyter span.cm-builtin {\n    color: var(--builtin)\n}\n\n.cm-s-ipython span.cm-string,\n.cm-s-jupyter span.cm-string {\n    color: var(--strings);\n}\n\n.cm-s-ipython span.cm-string-2,\n.cm-s-jupyter span.cm-string-2 {\n    color: var(--strings2);\n}\n\n.cm-s-ipython span.cm-comment,\n.cm-s-jupyter span.cm-comment {\n    color: var(--comments);\n    font-style: normal;\n}\n\n.cm-s-ipython span.cm-operator,\n.cm-s-jupyter span.cm-operator {\n    color: var(--operator);\n    font-weight: 400;\n}\n\n.cm-s-ipython span.cm-number,\n.cm-s-jupyter span.cm-number {\n    color: var(--numbers);\n}\n\n.cm-s-ipython span.cm-type,\n.cm-s-jupyter span.cm-type {\n    color: var(--types);\n}\n\n/*\n==============================\nMarkdown MathJax Customisation\n==============================\n*/\n\n/*This customisation only applies to Math Display showing the font bigger than normal*/\n.MathJax_Display {\n    font-size: 2rem;\n}\n\n.MathJax_Display .mjx-char {\n    font-family: var(--txbk-content-font-family) !important;\n}\n\n.MathJax_Display, .MathJax span {\n    color: var(--code-text-color);\n}\n\na .MathJax span {\n    color: var(--link-color);\n}\n\na:hover .MathJax span {\n    text-decoration: underline;\n    color: var(--link-color);\n}\n\n.MathJax span[style*=\"STIXMathJax_Normal\"],\n.MathJax span[style*=\"STIXMathJax_Normal-italic\"],\n.MathJax span[style*=\"STIXMathJax_Main\"],\n.MathJax span[style*=\"STIXMathJax_Variants\"] {\n    font-family: var(--txbk-content-font-family) !important;\n}\n\n\n/*\n    Pygments CSS (replacement) for HTML export\n    ===========================================\n\n    Original Pygments CSS rewrite thanks to @rubik\n    https://github.com/jupyter/nbconvert/issues/447#issuecomment-270766965\n*/\n\n.highlight .hll, div.highlight > pre {\n    background-color: var(--code-background-color);\n    color: var(--code-text-color);\n    font-family: var(--txbk-code-font-family);\n    font-size: var(--txbk-code-font-size);\n    line-height: var(--txbk-code-line-height);\n}\n\n/* Comment */\n.highlight .c {\n    color: var(--comments);\n}\n\n/* Error */\n.highlight .err {\n    color: #960050;\n    background-color: #1e0010;\n}\n\n/* Keyword */\n.highlight .k {\n    color: var(--keywords);\n    font-weight: 400;\n}\n\n/* Literal */\n.highlight .l {\n    color: var(--numbers);\n}\n\n/* Name */\n.highlight .n {\n    color: var(--code-text-color);\n}\n\n/* HACK:\nfix Interpreter mismatch pygments vs codemirror\nmpl.rcParams <- rcParams will be highlighted as property (as in codemirror)\n*/\n.highlight .o + .n {\n    color: var(--property);\n}\n\n/* Operator */\n.highlight .o {\n    color: var(--code-text-color);\n    font-weight: 400;\n}\n\n/* Punctuation */\n.highlight .p {\n    color: var(--code-text-color);\n}\n\n/* Comment.Multiline */\n.highlight .cm {\n    color: var(--comments);\n    font-style: normal;\n}\n\n/* Comment.Preproc */\n.highlight .cp {\n    color: var(--meta);\n    font-style: normal;\n}\n\n.highlight .cpf {\n    color: var(--meta);\n    font-style: normal;\n}\n\n/* Comment.Single */\n.highlight .c1 {\n    color: var(--comments);\n    font-style: normal;\n}\n\n/* Comment.Special */\n.highlight .cs {\n    color: var(--comments);\n    font-style: normal;\n}\n\n/* @ Generic.Deleted */\n.highlight .gd {\n    color: var(--red);\n}\n\n/* Generic.Emph */\n.highlight .ge {\n    font-style: italic\n}\n\n/* @ Generic.Inserted */\n.highlight .gi {\n    color: #a6e22e\n}\n\n/* Generic.Strong */\n.highlight .gs {\n    font-weight: 500 !important;\n}\n\n/* @ Generic.Subheading */\n.highlight .gu {\n    color: #75715e\n}\n\n/* */\n\n/* Keyword.Constant */\n.highlight .kc {\n    color: var(--keywords);\n    font-weight: 400;\n}\n\n/* Keyword.Declaration */\n.highlight .kd {\n    color: var(--keywords);\n    font-weight: 400;\n}\n\n/* Keyword.Namespace */\n.highlight .kn {\n    color: var(--keywords);\n    font-weight: 400;\n}\n\n/* Keyword.Pseudo */\n.highlight .kp {\n    color: var(--keywords);\n    font-weight: 400;\n}\n\n/* Keyword.Reserved */\n.highlight .kr {\n    color: var(--keywords);\n    font-weight: 400;\n}\n\n/* Keyword.Type */\n.highlight .kt {\n    color: var(--types);\n    font-weight: 400;\n}\n\n/* Literal.Date */\n.highlight .ld {\n    color: var(--numbers)\n}\n\n/* Literal.Number */\n.highlight .m {\n    color: var(--numbers);\n}\n\n/* Literal.String */\n.highlight .s {\n    color: var(--string);\n}\n\n/* Name.Attribute */\n.highlight .na {\n    color: var(--property);\n}\n\n/* Name.Builtin */\n.highlight .nb {\n    color: var(--builtin);\n}\n\n/* Name.Class */\n.highlight .nc {\n    color: var(--def);\n    font-weight: normal !important;\n}\n\n/* @ Name.Constant */\n.highlight .no {\n    color: var(--variables2);\n}\n\n/* Name.Decorator */\n.highlight .nd {\n    color: var(--builtin);\n}\n\n/* @ Name.Entity */\n.highlight .ni {\n    color: var(--variables2);\n}\n\n/* Name.Exception */\n.highlight .ne {\n    color: var(--code-text-color);\n    font-weight: normal !important;\n}\n\n/* Name.Function */\n.highlight .nf, .highlight .fm {\n    color: var(--def);\n}\n\n/* @ Name.Label */\n.highlight .nl {\n    color: var(--comments);\n}\n\n/* Name.Namespace */\n.highlight .nn {\n    color: var(--code-text-color);\n    font-weight: normal !important;\n}\n\n/* @ Name.Other */\n.highlight .nx {\n    color: var(--code-text-color);\n}\n\n/* @ Name.Property */\n.highlight .py {\n    color: var(--property);\n}\n\n/* @ Name.Tag */\n.highlight .nt {\n    color: var(--tag);\n}\n\n/* @ Name.Variable */\n.highlight .nv {\n    color:  var(--variables);\n}\n\n/* Operator.Word */\n.highlight .ow {\n    color: var(--operator);\n    font-weight: 400;\n}\n\n/* @ Text.Whitespace */\n.highlight .w {\n    color: var(--code-background-color);\n\n}\n\n/* Literal.Number.Bin */\n/* Literal.Number.Float */\n/* Literal.Number.Hex */\n/* Literal.Number.Integer */\n/* Literal.Number.Oct */\n.highlight .mb,\n.highlight .mf,\n.highlight .mh,\n.highlight .mi,\n.highlight .mo {\n    color: var(--numbers);\n}\n\n/* Literal.String.Backtick */\n.highlight .sb {\n    color: var(--strings2);\n}\n\n.highlight .sc,  /* Literal.String.Char */\n.highlight .sd,  /* Literal.String.Doc */\n.highlight .s2,  /* Literal.String.Double */\n.highlight .sh,  /* Literal.String.Heredoc */\n.highlight .si,  /* Literal.String.Interpol */\n.highlight .sx,  /* Literal.String.Other */\n.highlight .sr,  /* Literal.String.Regex */\n.highlight .s1,  /* Literal.String.Single */\n.highlight .ss  /* Literal.String.Symbol */\n{\n    color: var(--strings);\n    font-style: normal;\n}\n\n/* Literal.String.Escape */\n.highlight .se {\n    color: var(--red);\n}\n\n/* Name.Builtin.Pseudo */\n.highlight .bp {\n    color: var(--variables2);\n}\n\n/* Name.Variable.Class */\n.highlight .vc {\n    color: var(--variables);\n}\n\n/* Name.Variable.Global */\n.highlight .vg {\n    color: var(--variables2);\n}\n\n/* Name.Variable.Instance */\n.highlight .vi {\n    color: var(--code-text-color);\n}\n\n/* Literal.Number.Integer.Long */\n.highlight .il {\n    color: var(--numbers);\n}\n\n/*\n    Dataframe Colors\n    ----------------\n    Adapt Dataframe table to comply with the theme\n*/\n\ntable.dataframe {\n    color: var(--dataframe) !important;\n}\n\ntable.dataframe tbody tr th {\n    background-color: var(--df-bg);\n}\n\ntable.dataframe tbody tr:hover {\n    background-color: var(--df-tr-hover);\n}\n\ntable.dataframe td, table.dataframe th {\n    border: 1px solid var(--df-border);\n}\n\ntable.dataframe > th:not(:empty) {\n    background-color: var(--df-th-bg);\n}\n\ntable.dataframe tr:nth-child(2) th:empty,\ntable.dataframe tr:nth-child(2) th:empty {\n    border-right: 1px dotted var(--df-border-right);\n}\n\ntable.dataframe thead tr th:not(:empty) {\n    color: var(--df-thead);\n    border-bottom:  1px solid var(--df-thead-border);\n}\n\n/* =======================================\n              ANSI colors\n    (stdout / stderr color customisation)\n   =======================================\n*/\n\nspan.ansi-green-fg {\n    color: var(--ansi-green) !important;\n}\n\nspan.ansi-green-intense-fg{\n    color: var(--ansi-green-intense) !important;\n}\n\nspan.ansi-red-fg {\n    color: var(--ansi-red) !important;\n}\n\nspan.ansi-cyan-fg {\n    color: var(--ansi-cyan) !important;\n}\n\nspan.ansi-blue-fg {\n    color: var(--ansi-blue) !important;\n}\n\nspan.ansi-bold {\n    font-weight: 500 !important;\n}\n\n/* ----------------------------------- */\n\n/*\n    ======================\n    Markdown Editor Theme\n    ======================\n*/\n\ndiv.text_cell.unrendered pre {\n    color: var(--editor-text) !important;\n}\n\nspan.cm-header {\n    color: var(--header) !important;\n    font-weight: 500;\n}\n\nspan.cm-quote {\n    color: var(--quote) !important;\n}\n\nspan.cm-string.cm-url {\n    color: var(--link) !important;\n}\n\nspan.cm-string {\n   color: var(--strings) !important;\n}\n/* Sometimes useful in Mono code Highlighting*/\nspan.cm-string-2 {\n    color: var(--strings2) !important;\n}\n\nspan.cm-link {\n    color: var(--link) !important;\n}\n\nspan.cm-attribute {\n    color: var(--attribute) !important;\n}\n\nspan.cm-tag {\n    color: var(--tag) !important;\n}\n\nspan.cm-delimiter {\n    color: var(--delimiter) !important;\n}\n\nspan.cm-comment {\n    color: var(--comments) !important;\n}\n/*\nAuthor: Valerio Maggio < @leriomaggio >\nCode: https://github.com/leriomaggio/notexbook-jupyter-theme\nLicense: Apache License 2.0\n\n   ---------------------------------------\n    CODE CELL OUTPUT (DISPLAY MODE)\n\n    Pandas DataFrame - as HTML Table\n        (includes also HTML tables)\n\n\n   Note: This stylesheet does NOT include\n   any color nor background color for tables,\n   as those are assumed to be part of the\n   Coding colourisation theme.\n\n   ---------------------------------------\n*/\ntable.dataframe {\n    border-collapse: collapse;\n    border: none;\n    margin-left: 20px !important;\n    font-size: var(--txbk-code-font-size) !important;\n}\n\ntable.dataframe thead {\n    padding-bottom: 10px;\n}\n\ntable.dataframe thead tr {\n    font-style: normal;\n    padding: 5px 10px;\n    border-bottom:  1px solid;\n    vertical-align: middle;\n    text-align: center;\n    empty-cells: hide;\n}\n\ntable.dataframe thead tr th,\ntable.dataframe thead tr:only-child th {\n    vertical-align: middle;\n    text-align: center;\n}\n\ntable.dataframe tbody {\n    padding-top:  5px;\n}\n\ntable.dataframe tbody tr {\n}\n\ntable.dataframe tbody tr th {\n    text-align: left !important;\n    font-style: italic;\n    font-weight: normal;\n    margin-right: 5px;\n}\n\ntable.dataframe tbody tr td {\n    padding-left: 1.0rem;\n    padding-right: 1.0rem;\n}\n\ntable.dataframe tr {\n    border: none;\n}\n\ntable.dataframe td,\ntable.dataframe th {\n    padding-left: 0.25em;\n    padding-right: 0.25em;\n}\n\ntable.dataframe > th:not(:empty) {\n    text-align: left;\n    padding: 0 10px;\n    font-style: italic\n}\n\ntable.dataframe tr:nth-child(2) th:empty,\ntable.dataframe tr:nth-child(2) th:empty {\n    border-left: none;\n}\n\ntable.dataframe td {\n    padding: 0.375em 1em;\n}\n\ntable.dataframe thead {\n\tpadding: 10px 0;\n\tfont-weight: bold;\n}\n\ntable.dataframe thead tr th:not(:empty) {\n    text-align: left;\n    font-style: normal;\n    padding: 5px 10px;\n}\n\n/* Hacking Font-weight bold capped at 500 */\n.rendered_html th {\n    font-weight: 500 !important;\n}\n:root {\n    /* Jupyter Lab Integration (Light Theme) */\n\n    --jp-ui-font-family: var(--txbk-ui-font-family);\n    --jp-ui-font-color1: var(--txbk-ui-color);\n    --jp-ui-font-size1: var(--txbk-ui-font-size);\n\n    --jp-content-font-color1: var(--txbk-content-mono-color);\n    --jp-content-font-family: var(--txbk-content-font-family);\n    --jp-content-line-height: var(--txbk-content-line-height);\n    --jp-content-link-color: var(--link-color);\n    --jp-content-font-size: var(--txbk-content-font-size);\n    --jp-content-heading-font-weight: bold;\n    --jp-content-heading-line-height: 1;\n\n    --jp-layout-color3: #efefef;\n    --jp-notebook-multiselected-color: var(--txbk-multiselect-bgcolor);\n\n    --jp-code-font-size: var(--txbk-code-font-size);\n    --jp-code-line-height: var(--txbk-ui-mono-line-height);\n    --jp-code-padding: 5px;\n    --jp-code-font-family-default: var(--txbk-code-font-family);\n    --jp-code-font-family: var(--jp-code-font-family-default);\n    --jp-code-presentation-font-size: var(--txbk-ui-mono-font-size);\n\n    --jp-cell-prompt-font-family: var(--txbk-code-font-family);\n    --jp-cell-prompt-width: 80px;\n\n    --jp-cell-editor-border-color: transparent;\n\n    --jp-layout-color0: var(--code-background-color);\n    --jp-cell-prompt-not-active-font-color: #aba9a9;\n\n    --jp-cell-editor-background: var(--code-background-color);\n    --jp-cell-editor-active-background: var(--code-background-color);\n    --jp-cell-editor-active-border-color: var(--txbk-cell-edit-border-color);\n\n}\n\n/* ================\n    Jupyter Lab UI\n   ================\n*/\n\n.jp-DirListing-item.jp-mod-running .jp-DirListing-itemIcon:before {\n    color: var(--btn-danger);\n}\n\n.jp-DirListing-item.jp-mod-selected {\n    background-color: var(--texbook-blue);\n    color: white;\n}\n\nbutton.jp-RunningSessions-shutdownAll.jp-mod-styled {\n    color: var(--btn-warning)\n}\n\nbutton.jp-RunningSessions-shutdownAll.jp-mod-styled {\n    color: var(--btn-warning);\n}\n\n.jp-icon-warn0[fill] {\n    fill: var(--texbook-turquoise);\n}\n\n#jp-MainLogo .jp-icon-warn0[fill] {\n    /* Set default not to override logo colour */\n    fill: var(--jp-warn-color0);\n}\n\n/* Change Colour only of Icons on the left-hand side toolbar */\n.jp-SideBar.lm-TabBar.jp-mod-left .jp-icon3[fill] {\n    fill: var(--texbook-yellow);\n}\n\n.jp-SideBar.lm-TabBar.jp-mod-left.lm-TabBar-tab.lm-mod-current .jp-icon3[fill] {\n    fill: var(--texbook-orangex);\n}\n\n/*Kernel*/\ndiv.f14jk5uf[title=\"Kernel Busy\"] .jp-icon3[fill] {\n    fill: var(--kernel-busy);\n}\n\ndiv.f14jk5uf[title=\"Kernel Idle\"] .jp-icon3[fill] {\n    fill: var(--kernel-idle);\n}\n\ndiv.f14jk5uf[title=\"Kernel Unknown\"] .jp-icon3[fill],\ndiv.f14jk5uf[title=\"Kernel Restarting\"] .jp-icon3[fill] {\n    fill: var(--kernel-disconnected);\n}\n\n\n/* body class*/\n\nbody[data-jp-theme-light=\"true\"]:not(.jp-Notebook) {\n    font-family: var(--jp-ui-font-family);\n    background: var(--jp-layout-color3) !important;\n    margin: 0;\n    padding: 0;\n    overflow: hidden;\n}\n\n.jp-Notebook {\n    background-color: var(--background-color) !important;\n    font-weight: 300;\n    color: var(--txbk-ui-color);\n    font-size: var(--txbk-ui-font-size);\n}\n\n\n/* -------------------------------------------------\n    HTML Cells output generics\n    (overriding default JupyterLab theme settings)\n   -------------------------------------------------\n*/\n\n.jp-RenderedHTMLCommon :not(pre) > code {\n    background-color: transparent !important;\n    padding: 0 0 !important;\n}\n\n.jp-RenderedHTMLCommon pre, .jp-RenderedHTMLCommon code {\n    background-color: transparent !important;\n}\n\n.jp-RenderedHTMLCommon p {\n    margin-bottom: 0;\n}\n\n.jp-RenderedHTMLCommon * + p {\n    margin-top: 1em;\n}\n\n\n/* ======================================\n    MARKDOWN CELLS DISPLAY MODE\n    (text_cell_render in Notebook HTML)\n   ======================================\n*/\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon {\n    font-family: var(--txbk-content-font-family) !important;\n    font-size: var(--txbk-content-font-size) !important;\n    color: var(--txbk-content-color) !important;\n    font-kerning: auto;\n    text-align: justify !important;\n    display: block;\n    word-break: normal !important;\n    word-wrap: break-word !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon a {\n    color: var(--link-color) !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h1,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h2,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h3,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h4,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h5,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h6 {\n    font-family:  var(--txbk-content-font-family) !important;\n    font-style: normal !important;\n}\n\n/*  Font-sizes for Headers\n    ----------------------*/\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h1 {\n    font-size: 2.2em !important;\n    text-align: center !important;\n    padding-top:  3rem;\n    padding-bottom: 3rem;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h2 {\n    font-size: 1.9em !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h3 {\n    font-size: 1.7em !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h4 {\n    font-size: 1.5em !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h5 {\n    font-size: 1.3em !important;\n    border-bottom: 1px solid rgb(204, 204, 204);\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h6 {\n    font-size: 1.1em !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon pre,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon code {\n    font-size: 1em !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon pre,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon code {\n    color: var(--txbk-content-mono-color);\n    font-family: var(--txbk-content-mono-font-family);\n}\n\n\n/* Monospace Code - no code syntax highlight*/\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon pre {\n    /* hack: using code background colour here to allow for compatibility */\n    background-color: var(--code-background-color) !important;\n    font-family: var(--txbk-content-mono-font-family);\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p {\n    line-height: var(--txbk-content-line-height);\n    text-align: justify !important;\n}\n\n/* Monospace inline rendered markdown */\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p code {\n    /*Re-defining variables for Mono using Code Editor's settings*/\n    font-size: var(--txbk-content-mono-font-size);\n    color: var(--txbk-content-mono-color);\n    font-family: var(--txbk-content-mono-font-family);\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p strong code {\n    font-weight: bold !important;\n    color: var(--txbk-content-mono-color);\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p em code {\n    font-style: italic !important;\n    color: var(--txbk-content-mono-color);\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon pre code {\n    padding: 1rem 1.5rem;\n    display: block;\n    color: var(--txbk-content-mono-color);\n    font-family: var(--txbk-content-mono-font-family);\n    word-wrap: break-word;\n    word-break: normal;\n    /* Important Override rules */\n    background-color: var(--txbk-content-mono-bgcolor) !important;\n    font-size: var(--txbk-content-mono-font-size) !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon blockquote {\n    --txbk-ui-color: #6f6f6f;\n    margin: .2rem .2rem;\n    padding: .3rem .5rem;\n    border-left: .3rem solid #a7a7a7;\n    background-color: var(--txbk-content-mono-bgcolor);\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon blockquote:not(:first-child) {\n    margin: 2rem .2rem;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon blockquote p {\n    padding: .2rem 1.5rem;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon table {\n    font-size: var(--txbk-content-font-size) !important;\n    border-collapse: collapse;\n    border-spacing: 0;\n    overflow: auto;\n    break-inside: auto;\n    margin-top: 25px;\n    margin-bottom: 15px;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon table thead {\n    display: table-header-group;\n    vertical-align: middle;\n    border-bottom: none;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon table thead tr,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon table thead tr td,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon table tbody tr,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon table tbody tr th,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon table tbody tr td {\n    break-inside: avoid;\n    break-after: auto;\n    vertical-align: middle;\n    padding: 5px 5px;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon table tr th {\n    border-bottom-width: 0;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ul,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ol {\n    position: relative;\n    display: block;\n    margin-bottom: 0 !important;\n    line-height: var(--txbk-content-line-height);\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ul {\n    list-style-type: disc;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ul li,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ol li {\n    padding: .25em;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ul ul {\n    list-style-type: circle !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ul li > ul li a code,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ul li > ol li a code,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ol li > ul li a code,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ol li > ol li a code {\n    color: var(--link-color);\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ul ul ul {\n    list-style-type: square !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img:only-child,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img:only-child {\n    display: block;\n    margin: auto;\n    max-width: 40%;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img {\n    max-width: 40%;\n}\n\n/* Img MaxW classes */\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw10,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw10 {\n    max-width: 10% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw15,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw15 {\n    max-width: 15% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw20,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw20 {\n    max-width: 20% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw25,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw25 {\n    max-width: 25% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw30,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw30 {\n    max-width: 30% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw35,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw35 {\n    max-width: 35% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw40,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw40 {\n    max-width: 40% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw45,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw45 {\n    max-width: 45% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw50,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw50 {\n    max-width: 50% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw55,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw55 {\n    max-width: 55% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw60,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw60 {\n    max-width: 60% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw65,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw65 {\n    max-width: 65% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw70,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw70 {\n    max-width: 70% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw75,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw75 {\n    max-width: 75% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw80,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw80 {\n    max-width: 80% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw85,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw85 {\n    max-width: 85% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw90,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw90 {\n    max-width: 90% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw95,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw95 {\n    max-width: 95% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw100,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw100 {\n    max-width: 100% !important;\n}\n\n/* FIX Forcing monospace code to adhere with footnotes rules!*/\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p [id^='fn'] > code,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p [class^='fn'] > code {\n    font-size: 1em !important;\n}\n\n/* Code Cell Render (HTML output) */\n.jp-CodeCell .jp-RenderedHTMLCommon {\n    color: var(--code-text-color);\n}\n\n.jp-Notebook .jp-CodeCell .jp-RenderedHTMLCommon p {\n    font-family: var(--txbk-code-font-family);\n    font-size: 1.4em;\n    font-weight: normal;\n}\n\n.jp-Notebook .jp-CodeCell .jp-RenderedHTMLCommon .nomono {\n    font-family: var(--txbk-content-font-family);\n    font-size: 1em;\n    margin-top: 0;\n}\n\n.jp-Notebook .jp-Cell:not(.jp-mod-dropTarget) {\n    background: transparent;\n    border: none;\n}\n\n/* Code Cell Editor */\n\n.jp-InputArea-editor {\n    background-color: var(--jp-cell-editor-active-background);\n}\n\n.jp-Notebook .jp-Cell .jp-InputArea-editor,\n.jp-Notebook .jp-MarkdownCell .jp-MarkdownOutput {\n    /* Set default LEFT border as transparent - to avoid change in paddings when selected */\n    border-left: 0.2rem dotted var(--txbk-cell-border-color);\n    box-shadow: none;\n    border-right: none;\n    border-top: none;\n    border-bottom: none;\n    overflow: hidden;\n}\n\n.jp-Notebook .jp-Cell .jp-Cell-inputWrapper {\n    /* Set default RIGHT border as transparent - to avoid change in paddings when selected */\n    border-right: 5px solid var(--txbk-cell-border-color);\n}\n\n.jp-Notebook .jp-Cell.jp-mod-active.jp-mod-selected:not(.jp-mod-multiSelected) .jp-InputArea-editor,\n.jp-Notebook.jp-mod-commandMode .jp-MarkdownCell.jp-mod-active.jp-mod-selected:not(.jp-mod-multiSelected) .jp-MarkdownOutput {\n    /* Force border redefinition to override default Jupyter theme rules */\n    border-left: 0.2rem dotted var(--txbk-cell-selected-border-left-color);\n    box-shadow: none;\n    border-right: none;\n    border-top: none;\n    border-bottom: none;\n    overflow: hidden;\n}\n\n.jp-Notebook.jp-mod-commandMode .jp-Cell.jp-mod-active.jp-mod-selected:not(.jp-mod-multiSelected) .jp-Cell-inputWrapper {\n    border-right-color: var(--txbk-cell-display-border-color);\n}\n\n.jp-Notebook.jp-mod-editMode .jp-Cell.jp-mod-active.jp-mod-selected:not(.jp-mod-multiSelected) .jp-Cell-inputWrapper {\n    border-right-color: var(--txbk-cell-edit-border-color);\n}\n\n/* Cell Multiple Selection */\n.jp-Notebook.jp-mod-commandMode .jp-Cell.jp-mod-selected:not(.jp-mod-active),\n.jp-Notebook.jp-mod-commandMode .jp-Cell.jp-mod-multiSelected {\n    border: 2px dashed var(--texbook-azure);\n    background: var(--txbk-multiselect-bgcolor);\n    margin-top: 10px;\n}\n\n/*\n    Overlay with Shadow for Code Cell Selected !\n    ============================================\n*/\n/* Overlay limited to CodeCells */\n.jp-Notebook .jp-CodeCell.jp-mod-selected {\n    border: none;\n    background: transparent;\n    box-shadow: 0 6px 18px #aaa;\n    z-index: 10;\n    top: -10px;\n    padding-top: 12px;\n    padding-bottom: 12px;\n    margin-top: 18px;\n    margin-bottom: 2px;\n}\n\n.jp-Notebook .jp-CodeCell.jp-mod-active.jp-mod-selected:before {\n    position: absolute;\n    display: none;\n    top: -1px;\n    left: -1px;\n    width: 0;\n    height: calc(100% + 2px);\n    content: '';\n    background: none;\n}\n\n.jp-Notebook .jp-Cell .jp-Collapser {\n    display: none !important;\n}\n\n.jp-Notebook .jp-CodeCell .jp-InputPrompt {\n    color: var(--texbook-light-grey) !important;\n    font-style: normal !important;\n    font-size: 1em;\n    opacity: 1 !important;\n    font-weight: normal;\n    min-width: 9.5ex;\n}\n\n.jp-OutputPrompt {\n    color: transparent !important;\n    min-width: 9.5ex;  /* Aligns with Input Prompt */\n}\n\n.jp-Notebook .jp-CodeCell .jp-InputPrompt bdi,\n.jp-Notebook .jp-CodeCell .jp-OutputPrompt  bdi {\n    line-height: 0;\n    font-size:0;\n    color: transparent;\n    left: -10000px;\n    content: \"\\21E2\";\n}\n\n/*.jp-Notebook .jp-CodeCell.jp-mod-active.jp-mod-selected:not(.jp-mod-multiSelected) .jp-InputPrompt:before {*/\n.jp-Notebook .jp-CodeCell.jp-mod-active.jp-mod-selected:not(.jp-mod-multiSelected) .jp-InputArea:before {\n    display: inline-block;\n    position: absolute;\n    content: \"\\279E\";\n    font-size: 1.75rem;\n    top: 4px;\n    width: 10px;\n    left: 0;\n    font-weight: bold !important;\n}\n\n.jp-Notebook.jp-mod-commandMode .jp-CodeCell.jp-mod-active.jp-mod-selected:not(.jp-mod-multiSelected) .jp-InputArea:before {\n    color: var(--txbk-cell-display-border-color);\n}\n\n.jp-Notebook.jp-mod-editMode .jp-CodeCell.jp-mod-active.jp-mod-selected:not(.jp-mod-multiSelected) .jp-InputArea:before {\n    color: var(--txbk-cell-edit-border-color);\n}\n\n/* =============\n   Code Editors\n   ============= */\n\n.jp-Notebook .jp-Cell .CodeMirror * {\n    line-height: var(--txbk-code-line-height);\n}\n\n.jp-Notebook .jp-CodeCell .CodeMirror * {\n    font-family: var(--txbk-code-font-family) !important;\n    font-size: var(--txbk-code-font-size) !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .CodeMirror * {\n    font-family: var(--txbk-md-font-family) !important;\n    font-size: var(--txbk-md-font-size) !important;\n}\n\n/* Cell Output rendering (.output_area in Notebook HTML) */\n\n.jp-OutputArea-output.jp-RenderedText pre,\n.jp-OutputArea-output.jp-RenderedMarkdown p {\n    padding-bottom: 15px;\n    padding-top: 10px;\n}\n\n.jp-OutputArea-output.jp-RenderedMarkdown p {\n    font-size: var(--txbk-content-font-size);\n}\n\n.jp-OutputArea-output.jp-RenderedMarkdown pre code {\n    font-size: var(--txbk-content-mono-font-size);\n    font-family: var(--txbk-content-mono-font-family);\n    color: var(--txbk-content-mono-color);\n}\n\n.jp-OutputArea-output.jp-RenderedText pre {\n    --txbk-content-mono-font-family: var(--txbk-code-font-family);\n    font-size: var(--txbk-code-font-size);\n    font-weight: normal;\n    word-break: normal;\n    word-wrap: break-word;\n}\n\n/* Standard Error */\n.jp-RenderedText[data-mime-type='application/vnd.jupyter.stderr'] {\n    background: none !important;\n}\n/*\nAuthor: Valerio Maggio < @leriomaggio >\nCode: https://github.com/leriomaggio/notexbook-jupyter-theme\nLicense: Apache License 2.0\n*/\n\n/* HTML Export (Jupyter Light Theme)\n   ================================ */\n\nbody.jp-Notebook .jp-CodeCell .jp-InputPrompt {\n    margin-top: 7px;\n    overflow: initial;\n}\n\nbody.jp-Notebook .CodeMirror-linenumber {\n    --txbk-ui-mono-font-size: 10px !important;\n}\n\nbody.jp-Notebook .jp-RenderedHTMLCommon.jp-MarkdownOutput p > img:only-child,\nbody.jp-Notebook .jp-RenderedHTMLCommon.jp-MarkdownOutput img:only-child {\n    max-width: 30%;\n}\n\nbody.jp-Notebook .jp-CodeCell .jp-InputPrompt {\n    font-size: var(--txbk-code-font-size);\n    padding-top: 4px;\n}\n\n/* ==================================================\n   IMPORTANT NOTE:\n   ALL markdown rules cells needs adapting because of\n   a different structure in exported HTML\n   ===================================================\n*/\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput {\n    font-family: var(--txbk-content-font-family) !important;\n    font-size: var(--txbk-content-font-size) !important;\n    color: var(--txbk-content-color) !important;\n    font-kerning: auto;\n    text-align: justify !important;\n    display: block;\n    word-break: normal !important;\n    word-wrap: break-word !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  a {\n    color: var(--link-color) !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h1,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h2,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h3,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h4,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h5,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h6 {\n    font-family:  var(--txbk-content-font-family) !important;\n    font-style: normal !important;\n}\n\n/*  Font-sizes for Headers\n    ----------------------*/\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h1 {\n    font-size: 2.2em !important;\n    text-align: center !important;\n    padding-top:  3rem;\n    padding-bottom: 3rem;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h2 {\n    font-size: 1.9em !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h3 {\n    font-size: 1.7em !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h4 {\n    font-size: 1.5em !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h5 {\n    font-size: 1.3em !important;\n    border-bottom: 1px solid rgb(204, 204, 204);\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h6 {\n    font-size: 1.1em !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  p,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  pre,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  code {\n    font-size: 1em !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  pre,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  code {\n    color: var(--txbk-content-mono-color);\n}\n\n\n/* Monospace Code - no code syntax highlight*/\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  pre {\n    /* hack: using code background colour here to allow for compatibility */\n    background-color: var(--code-background-color) !important;\n    font-family: var(--txbk-content-mono-font-family) !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  p {\n    line-height: var(--txbk-content-line-height);\n    text-align: justify !important;\n}\n\n/* Monospace inline rendered markdown */\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  p code {\n\n    /*Re-defining variables for Mono using Code Editor's settings*/\n    --txbk-content-mono-font-family: var(--txbk-code-font-family);\n    --txbk-content-mono-font-size: var(--txbk-code-font-size);\n\n    background-color: var(--txbk-content-mono-bgcolor) !important;\n    font-size: var(--txbk-content-mono-font-size) !important;\n    color: var(--txbk-content-mono-color);\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  p strong code {\n    font-weight: bold !important;\n    color: var(--txbk-content-mono-color);\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  p em code {\n    font-style: italic !important;\n    color: var(--txbk-content-mono-color);\n}\n\nbody.jp-Notebook .jp-CodeCell .jp-RenderedHTMLCommon p.nomono {\n    font-family: var(--txbk-content-font-family);\n    font-size: 1em;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  pre code {\n    padding: 1rem 1.5rem;\n    display: block;\n    color: var(--txbk-content-mono-color);\n    background-color: var(--txbk-content-mono-bgcolor) !important;\n    font-family: var(--txbk-content-mono-font-family);\n    font-size: var(--txbk-content-mono-font-size) !important;\n    word-wrap: break-word;\n    word-break: normal;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  blockquote {\n    --txbk-ui-color: #6f6f6f !important;\n\n    margin: 2rem .2rem !important;\n    padding: .3rem .5rem !important;\n    border-left: .3rem solid #a7a7a7 !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  blockquote p {\n    padding: .2rem 1.5rem;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  table {\n    margin-top: 25px;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  table {\n    font-size: var(--txbk-content-font-size) !important;\n    border-collapse: collapse;\n    border-spacing: 0;\n    width: 100%;\n    overflow: auto;\n    break-inside: auto;\n    text-align: left;\n    margin-top: 25px;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  table thead {\n    display: table-header-group;\n    vertical-align: middle !important;\n    border-bottom: none !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  table thead tr,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  table thead tr td,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  table tbody tr,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  table tbody tr th,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  table tbody tr td {\n    break-inside: avoid;\n    break-after: auto;\n    text-align: left !important;\n    vertical-align: middle !important;\n    padding: 0 !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  table tr th {\n    border-bottom-width: 0;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol {\n    position: relative;\n    display: block;\n    margin-bottom: 0 !important;\n    line-height: var(--txbk-content-line-height);\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul {\n    list-style-type: disc;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul li,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol li {\n    /*white-space: pre-wrap;*/\n    padding: .8rem !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul li > code,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol li > code {\n    font-size: .9em !important\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul li a code,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol li a code {\n    font-size: .9em !important\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul ul {\n    list-style-type: circle !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul ul,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul ol,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol ul,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol ol {\n    padding-top: .5rem !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul li > ul li,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul li > ol li,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol li > ul li,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol li > ol li {\n    padding: .5rem !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul li > ul li code,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul li > ol li code,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol li > ul li code,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol li > ol li code {\n    font-size: .9em !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul li > ul li a code,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul li > ol li a code,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol li > ul li a code,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol li > ol li a code {\n    font-size: .9em !important;\n    color: var(--link-color);\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul ul ul {\n    list-style-type: square !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  p > img:only-child,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  img:only-child {\n    display: block;\n    margin: auto;\n    max-width: 40%;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  img {\n    max-width: 40%;\n}\n\n/* Img MaxW classes */\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  img.maxw10,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  p > img.maxw10 {\n    max-width: 5% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw15,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw15 {\n    max-width: 5% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw20,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw20 {\n    max-width: 10% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw25,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw25 {\n    max-width: 15% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw30,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw30 {\n    max-width: 20% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw35,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw35 {\n    max-width: 25% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw40,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw40 {\n    max-width: 30% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw45,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw45 {\n    max-width: 35% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw50,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw50 {\n    max-width: 40% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw55,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw55 {\n    max-width: 45% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw60,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw60 {\n    max-width: 50% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw65,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw65 {\n    max-width: 55% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw70,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw70 {\n    max-width: 60% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw75,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw75 {\n    max-width: 65% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw80,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw80 {\n    max-width: 70% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw85,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw85 {\n    max-width: 75% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw90,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw90 {\n    max-width: 80% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw95,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw95 {\n    max-width: 85% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw100,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw100 {\n    max-width: 90% !important;\n}\n\n/* FIX Forcing monospace code to adhere with footnotes rules!*/\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  p [id^='fn'] > code,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  p [class^='fn'] > code {\n    font-size: 1em !important;\n}\n\n\n/* ======================================================\n              GLOBALS (with vars integration)\n   ======================================================\n*/\n\n\n:root {\n    --template-txbk-content-font-size: 16px;\n    --template-txbk-content-line-height: 1.4;\n    --template-txbk-content-mono-font-family: \"CMU Typewriter Text\", \"Fira Code\", monospace;\n    --template-txbk-code-font-family: \"Fira Code\", \"Fira Code\", monospace;\n    --template-txbk-md-font-family: \"Hack\", \"Hack\", monospace;\n    --template-txbk-code-font-size: 14px;\n    --template-txbk-md-font-size: 14px;\n}\n\n/* ======================================================\n                         GLOBALS\n   ======================================================\n*/\n\n:root {\n    /* Base colors */\n    --texbook-red: #d43133;\n    --texbook-pink: #D14187;\n    --texbook-turquoise: #009489;\n    --texbook-azure: #00afde;\n    --texbook-blue: #2875d9;\n    --texbook-light-grey: #828282;\n    --texbook-dark-grey: rgb(56, 56, 56);\n    --texbook-yellow: #f9ab00;\n    --texbook-orange: #e8710a;\n\n    /* Font formatting */\n    --background-color: #ffffff;\n    --txbk-ui-font-family: \"Roboto Slab\", \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n    --txbk-ui-color: rgb(51, 51, 51);\n    --txbk-ui-font-size: 14px;\n    --txbk-ui-line-height: 1;\n\n    --txbk-ui-header-font-family: \"Roboto Slab\", \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n    --txbk-ui-header-color: rgb(56, 56, 56);\n\n    --txbk-ui-mono-color: #828282;\n    --txbk-ui-mono-font-size: 15px;\n    --txbk-ui-mono-line-height: 1.4;\n\n    /* Cells */\n    --txbk-cell-selected-border-left-color: lightgrey;\n    --txbk-cell-border-color: var(--background-color);\n    --txbk-multiselect-bgcolor: var(--background-color);\n    --txbk-cell-display-border-color: #009489;\n    --txbk-cell-edit-border-color: #d43133;\n\n    /* Content Formatting */\n    --txbk-content-font-family: \"CMU Serif\", \"Times New Roman\", serif;\n    --txbk-content-font-size: var(--template-txbk-content-font-size);\n    --txbk-content-color: rgb(51, 51, 51);\n    --txbk-content-line-height: var(--template-txbk-content-line-height);\n\n    --txbk-content-mono-font-family: var(--template-txbk-content-mono-font-family);\n    --txbk-content-mono-font-size: var(--txbk-content-font-size);\n    --txbk-content-mono-color: var(--texbook-dark-grey);\n    --txbk-content-mono-bgcolor: var(--code-background-color);\n\n    --txbk-code-font-family: var(--template-txbk-code-font-family);\n    --txbk-code-font-size: var(--template-txbk-code-font-size);\n    --txbk-md-font-family: var(--template-txbk-md-font-family);\n    --txbk-md-font-size: var(--template-txbk-md-font-size);\n    --txbk-code-line-height: 1.6;\n    --txbk-code-color: var(--code-text-color);\n    --txbk-code-bgcolor: var(--code-background-color);\n\n    --link-color: var(--texbook-blue);\n    --del-color: var(--texbook-red);\n    --drop-cap-color: var(--texbook-red);;\n\n    --kernel-name-color: var(--texbook-azure);\n    --kernel-idle: var(--texbook-turquoise);\n    --kernel-busy: var(--texbook-pink);\n    --kernel-disconnected: var(--texbook-red);\n    --btn-warning: var(--texbook-pink);\n    --btn-danger: var(--texbook-red);\n    --running-notebook: var(--texbook-turquoise);\n}\n\nhtml {\n    font-size: 10px;\n}\n\nbody {\n\n    background-color: var(--background-color) !important;\n    font-weight: 300;\n    font-family: var(--txbk-ui-font-family);\n    color: var(--txbk-ui-color);\n    overflow: inherit;\n    vertical-align: middle;\n    font-size: var(--txbk-ui-font-size);\n}\n\nh1, h2, h3, h4, h5, h6, label > strong {\n    font-family: var(--txbk-ui-header-font-family);\n    color: var(--txbk-ui-header-color);\n}\n\nh1 img, h2 img , h3 img, h4 img, h5 img, h6 img {\n    display: inline !important;\n}\n\nh1 {\n    font-weight: bold;\n    font-style: normal;\n}\n\nh2 {\n    font-weight: bold;\n    font-style: italic;\n}\n\nh3 {\n    font-weight: 600;\n    font-style: normal;\n}\n\nh4 {\n    font-weight: 500;\n    font-style: normal;\n}\n\nh5, h6 {\n    font-weight: 500;\n    font-style: italic;\n}\n\ncode, kbd, pre, samp {\n    font-family: var(--txbk-code-font-family);\n    color: var(--txbk-ui-mono-color);\n    font-weight: 400;\n    font-size: var(--txbk-ui-mono-font-size);\n    line-height: var(--txbk-ui-mono-line-height);\n}\n\ntable > thead > tr > td.info,\ntable > tbody > tr > td.info,\ntable > tfoot > tr > td.info,\ntable > thead > tr > th.info,\ntable > tbody > tr > th.info,\ntable > tfoot > tr > th.info,\ntable > thead > tr.info > td,\ntable > tbody > tr.info > td,\ntable > tfoot > tr.info > td,\ntable > thead > tr.info > th,\ntable > tbody > tr.info > th,\ntable > tfoot > tr.info > th {\n    background-color: #d9edf7;\n}\n\ndel {\n    color: var(--del-color) !important;\n}\n\n/* ======================================================\n                 Intro/Home Page Server\n   ======================================================\n*/\n\n#ipython-main-app p {\n    text-align: justify !important;\n}\n\n.toolbar_info,\n.list-container {\n    color: #828282;\n}\n\n.list_placeholder {\n    font-family: \"Roboto Slab\", serif !important;\n    font-weight: 300;\n    font-style: normal;\n}\n\na.item_link, a:hover.item_link {\n    color: var(--link-color);\n    font-weight: 300;\n}\n\n.item_buttons .kernel-name {\n    color: var(--kernel-name-color);\n    font-weight: 400;\n}\n\n.btn-warning {\n    background-color: var(--btn-warning) !important;\n    border-color: var(--btn-warning) !important;\n}\n\n.btn-warning:focus {\n    border-color: var(--btn-warning) !important;\n}\n\n.btn-danger {\n    background-color: var(--btn-danger) !important;\n    border-color: var(--btn-danger) !important;\n}\n\n.btn-danger:focus {\n    border-color: var(--btn-danger) !important;\n}\n\n.running-indicator,\n.running_notebook_icon:before {\n    color: var(--running-notebook);\n}\n\n\n\n/* ======================================================\n                         Notebook\n   ======================================================\n*/\n\n/* Modal Dialog */\n\n.modal-header > h4 {\n    font-style: normal !important;\n    text-decoration: none !important;\n    font-family: var(--txbk-ui-font-family) !important;\n    margin: 0 !important;\n}\n\n.notebook_app {\n    background-color: var(--background-color) !important;\n    font-family: \"Helvetica Neue\", Helvetica, Arial, sans-serif !important;\n    font-weight: normal;\n}\n\ndiv#notebook_name {\n    font-family: var(--txbk-ui-font-family) !important;\n    font-weight: normal;\n    font-size: 24px;\n    padding: 1px 7px 1px 1px;\n}\n\ndiv#site {\n\toverflow: inherit;\n    top: 112px;\n    position: absolute;\n}\n\n#header {\n    display: block;\n    position: fixed !important;\n    top: 0;\n    width: 100%;\n    max-width: 100%;\n    height: fit-content;\n    background-color: var(--background-color);\n}\n\n#notebook-container {\n    /* Remove shadow so that it looks like a page of a PDF doc */\n    box-shadow: none !important;\n    -webkit-box-shadow: none !important;\n    padding: 0;\n}\n\ndiv#notebook {\n    border-top: none;\n    font-size: 1rem;\n    padding: 0 !important;\n    padding-top: 30px !important;\n    font-family: var(--txbk-content-font-family) !important;\n}\n\n.kernel_idle_icon:before {\n    color: var(--kernel-idle);\n}\n\n.kernel_busy_icon:before {\n    color: var(--kernel-busy);\n}\n\n.kernel_disconnected_icon:before {\n    color: var(--kernel-disconnected);\n}\n\n#notification_area {\n    font-family: var(--txbk-ui-font-family);\n}\n\n#notification_kernel {\n    color: #fff;\n    background-color: var(--kernel-idle);\n    border-color: var(--kernel-idle);\n}\n\n#notification_kernel.warning {\n    color: #fff;\n    background-color: var(--kernel-disconnected);\n    border-color: var(--kernel-disconnected);\n}\n\n#notification_trusted {\n    border-color: var(--kernel-disconnected);\n}\n\n#notification_trusted[disabled=\"disabled\"] {\n    border-color: var(--kernel-idle);\n}\n\n\n#notification_notebook {\n    border-color: var(--kernel-idle);\n}\n\n/* -----------------------------------\n    CELLS\n   -----------------------------------\n*/\n\ndiv.cell {\n    right: 2px;\n    border:  none;\n    margin-top: 5px;\n}\n\ndiv.cell.selected {\n    /* Reset all - ready for customisation */\n    border-radius: 0;\n    background: none;\n}\n\ndiv.cell .inner_cell {\n    border-right: 5px solid var(--txbk-cell-border-color);\n    border-left:  0.2rem dotted var(--txbk-cell-border-color);\n}\n\ndiv.cell.selected:not(.jupyter-soft-selected) .inner_cell {\n    border-left-color:  var(--txbk-cell-selected-border-left-color);\n}\n\n.command_mode div.cell.selected:not(.jupyter-soft-selected) .inner_cell {\n    border-right-color: var(--txbk-cell-display-border-color);\n}\n\n.edit_mode div.cell.selected:not(.jupyter-soft-selected) .inner_cell {\n    border-right-color: var(--txbk-cell-edit-border-color);\n}\n\n/* Multiple Selection */\n.command_mode div.cell.jupyter-soft-selected {\n    border: 2px dashed var(--texbook-azure);\n    background: var(--txbk-multiselect-bgcolor);\n    margin-top: 10px;\n}\n\n/*\nOverlay with Shadow for Code Cell Selected !\n*/\ndiv.code_cell.selected,\n.command_mode div.code_cell.jupyter-soft-selected {\n    box-shadow: 0 6px 18px #aaa;\n    z-index: 10;\n    top: -10px;\n}\n\ndiv.code_cell.selected {\n    border: none;\n    background: transparent;\n}\n\ndiv.prompt {\n    font-family: var(--txbk-code-font-family) !important;\n    font-style: normal;\n    font-size: 1rem;\n    text-align: right;\n    line-height: 1rem;\n    min-width: 9ex;\n}\n\ndiv.cell.selected:before,\ndiv.cell.jupyter-soft-selected:before {\n    /* Important Needed to Override */\n    width: 0 !important;\n    background: none !important;\n}\n\ndiv.cell div.input:before {\n    display: inline-block;\n    position: relative;\n    content: \"\\279E\";\n    font-size: 1.8rem;\n    top: 11px;\n    width: 10px;\n    left: 3px;\n    font-weight: bold;\n}\n\ndiv.cell:not(.selected) div.input:before {\n    color: var(--background-color);\n}\n\ndiv.cell.selected:not(.jupyter-soft-selected) div.input:before {\n    color: var(--txbk-cell-display-border-color);\n}\n\n.edit_mode div.cell.selected div.input:before,\n.edit_mode div.cell.selected.unrendered div.input:before {\n    color: var(--txbk-cell-edit-border-color);\n}\n\n.code_cell div.input_prompt:after,\n.code_cell div.output_prompt:after {\n    display: inline-block;\n    content: '';\n    font-size:  0.75rem;\n    font-style: normal !important;\n}\n\n.edit_mode div.cell.selected:before{\n    width: 0;\n    background: none;\n}\n\n/* ==========================\n    Cell Input and Rendering\n   ==========================\n*/\n\ndiv.input_area {\n    border-radius: 0;\n    border: none;\n    padding: 2px 5px 0 5px;\n}\n\ndiv.input_prompt {\n    color: #aba9a9;\n    font-style: normal;\n    font-size: 1.4rem;\n    padding-top: 14px;\n}\n\n/* FIX:\n   Fixing Empty cell output in HTML export\n*/\ndiv.output_prompt {\n    color: transparent !important;\n}\n\ndiv.input_prompt bdi,\ndiv.output_prompt bdi {\n    line-height: 0;\n    font-size:0;\n    color: transparent;\n    left: -10000px;\n    content: \"\\21E2\";\n\n}\n\ndiv.output_wrapper {\n    margin-top: 8px;\n}\n\ndiv.output_area div.output_text pre,\ndiv.output_area div.output_markdown p {\n    padding-bottom: 15px;\n    padding-top: 10px;\n}\n\ndiv.output_area div.output_markdown p {\n    font-size: var(--txbk-content-font-size);\n}\n\ndiv.output_area div.output_markdown pre code {\n    font-size: var(--txbk-content-mono-font-size);\n    font-family: var(--txbk-content-mono-font-family);\n    color: var(--txbk-content-mono-color);\n}\n\ndiv.output_area div.output_text pre {\n    --txbk-content-mono-font-family: var(--txbk-code-font-family);\n\n    font-weight: normal;\n    word-break: normal;\n    word-wrap: break-word;\n}\n\n/* Output Standard Error  */\ndiv.output_stderr {\n    background-color: #FFFFFF;\n}\n\ndiv.out_prompt_overlay:hover {\n    box-shadow: none;\n    background: none;\n}\n\n/* Output HTML after cell code - e.g. Pandas DataFrame */\ndiv.output_html {\n    color: var(--code-text-color);\n}\n\ndiv.output_html a, div.output_html a:hover {\n    color: var(--link-color);\n}\n\ndiv.output_html {\n    font-size: 1.4em;\n    font-weight: normal;\n    font-family: var(--txbk-code-font-family);\n}\n\ndiv.output_html .nomono {\n    font-family: var(--txbk-content-font-family);\n    margin-top: 0;\n    font-size: 1em;\n}\n\ndiv.output_html > iframe, div.output_area {\n    margin-left: 2rem;\n}\n\ndiv.output_subarea {\n    margin-left: 0;\n}\n\ndiv.output_svg div {\n    max-width: 98%;\n    margin-left: 0 !important;\n}\n\n/* ----------------------------\n    Override default CSS rules\n   ---------------------------- */\n.rendered_html code {\n    background-color: transparent !important;\n}\n\n.rendered_html h1:first-child,\n.rendered_html h2:first-child,\n.rendered_html h3:first-child,\n.rendered_html h4:first-child,\n.rendered_html h5:first-child,\n.rendered_html h6:first-child {\n    margin-top: 0.25em;\n}\n\n.rendered_html h1 {\n    margin-top: 0.48em;\n}\n\n.rendered_html h2 {\n    margin-top: 0.57em;\n}\n\n.rendered_html h3 {\n    margin-top: 0.85em;\n}\n\n.rendered_html h4 {\n    margin-top: 1.3em;\n}\n\n.rendered_html h5 {\n    margin-top: 1.2em;\n}\n\n.rendered_html h6 {\n    margin-top: 1.1em;\n}\n\n/* ===============\n    CELLS Render\n   =============== */\n\n/*  -------------------------\n    (1) CODE CELLS\n    Display + Edit modes\n    -------------------------\n*/\ndiv.code_cell pre, div.CodeMirror, div.CodeMirror-linenumber {\n    font-family: var(--txbk-code-font-family);\n    font-size: var(--txbk-code-font-size);\n    line-height: var(--txbk-code-line-height);\n}\n\ndiv.CodeMirror-linenumber {\n    --txbk-ui-mono-font-size: 12px !important;\n}\n\n/* -- MARKDOWN CELLS (Edit) -- */\n\n/* md cell */\ndiv.text_cell.unrendered pre {\n    /* general font rule */\n    font-family: var(--txbk-md-font-family);\n    font-size: var(--txbk-md-font-size);\n    line-height: var(--txbk-code-line-height);\n}\n\n/* md cell headers (edit) */\n.cm-header-1, .cm-header-2, .cm-header-3,\n.cm-header-4, .cm-header-5, .cm-header-6 {\n    /* general font rule */\n    font-family: var(--txbk-md-font-family);\n}\n\n/* ------------------------------------------------------------------\n    (2) MARKDOWN CELLS (DISPLAY MODE)\n\n    Notes: Font-families to use here:\n    computer-modern --> general text (Computer Modern Typeface, CMU)\n    md-display-monospace --> Monospace output (CMU Typewriter)\n   ------------------------------------------------------------------\n */\n\ndiv.text_cell_render {\n    font-family: var(--txbk-content-font-family);\n    font-size: var(--txbk-content-font-size);\n    color: var(--txbk-content-color);\n    font-kerning: auto;\n    text-align: justify;\n    display: block;\n    word-break: normal;\n    word-wrap: break-word;\n}\n\ndiv.text_cell_render a, div.text_cell_render a:hover {\n    color: var(--link-color);\n}\n\ndiv.text_cell_render h1, div.text_cell_render h2,\ndiv.text_cell_render h3, div.text_cell_render h4,\ndiv.text_cell_render h5, div.text_cell_render h6 {\n    font-family:  var(--txbk-content-font-family);\n    font-style: normal;\n}\n\n/* Font-sizes for headers */\ndiv.text_cell_render h1 {\n    font-size: 2.2em;\n    text-align: center;\n    padding-top:  3rem;\n    padding-bottom: 3rem;\n}\n\ndiv.text_cell_render h2 {\n    font-size: 1.9em;\n}\n\ndiv.text_cell_render h3 {\n    font-size: 1.7em;\n}\n\ndiv.text_cell_render h4 {\n    font-size: 1.5em;\n}\n\ndiv.text_cell_render h5 {\n    font-size: 1.3em;\n    border-bottom: 1px solid rgb(204, 204, 204);\n}\n\ndiv.text_cell_render h6 {\n    font-size: 1.1em;\n}\n\ndiv.text_cell_render p,\ndiv.text_cell_render pre,\ndiv.text_cell_render code {\n    font-size: 1em !important;\n}\n\ndiv.text_cell_render pre,\ndiv.text_cell_render code {\n    color: var(--txbk-content-mono-color);\n}\n\n/* Monospace Code - no code syntax highlight*/\ndiv.text_cell_render pre {\n    /* hack: using code background colour here to allow for compatibility */\n    background-color: var(--code-background-color);\n    font-family: var(--txbk-content-mono-font-family);\n}\n\ndiv.text_cell_render p {\n    line-height: var(--txbk-content-line-height);\n    text-align: justify !important;\n}\n\ndiv.text_cell_render code {\n    font-family: var(--txbk-content-mono-font-family);\n}\n\n/* Monospace inline rendered markdown */\ndiv.text_cell_render p code {\n    /*Re-defining variables for Mono using Code Editor's settings*/\n    /*--txbk-content-mono-font-family: var(--txbk-code-font-family);*/\n    /*--txbk-content-mono-font-size: var(--txbk-code-font-size);*/\n    font-size: var(--txbk-content-mono-font-size) !important;\n    color: var(--txbk-content-mono-color);\n    font-family: var(--txbk-content-mono-font-family);\n}\n\ndiv.text_cell_render p strong code {\n    font-weight: bold !important;\n    color: var(--txbk-content-mono-color);\n}\n\ndiv.text_cell_render p em code {\n    font-style: italic !important;\n    color: var(--txbk-content-mono-color);\n}\n\ndiv.text_cell_render pre code {\n    padding: 1rem 1.5rem;\n    display: block !important;\n    color: var(--txbk-content-mono-color);\n    background-color: var(--txbk-content-mono-bgcolor) !important;\n    font-family: var(--txbk-content-mono-font-family);\n    font-size: var(--txbk-content-mono-font-size) !important;\n    word-wrap: break-word;\n    word-break: normal;\n}\n\ndiv.text_cell_render blockquote {\n    --txbk-ui-color: #6f6f6f;\n    margin: .2rem .2rem;\n    padding: .3rem .5rem;\n    border-left: .3rem solid #a7a7a7;\n    background-color: var(--txbk-content-mono-bgcolor);\n}\n\ndiv.text_cell_render blockquote:not(:first-child) {\n    margin: 2rem .2rem;\n}\n\ndiv.text_cell_render blockquote p {\n    padding: .2rem 1.5rem;\n}\n\ndiv.text_cell_render table {\n    font-size: var(--txbk-content-font-size) !important;\n    border-collapse: collapse;\n    border-spacing: 0;\n    overflow: auto;\n    break-inside: auto;\n    margin-top: 25px;\n    margin-bottom: 15px;\n}\n\ndiv.text_cell_render table thead {\n    display: table-header-group;\n    vertical-align: middle;\n    border-bottom: none;\n}\n\ndiv.text_cell_render table thead tr,\ndiv.text_cell_render table thead tr th,\ndiv.text_cell_render table thead tr td,\ndiv.text_cell_render table tbody tr,\ndiv.text_cell_render table tbody tr th,\ndiv.text_cell_render table tbody tr td {\n    break-inside: avoid;\n    break-after: auto;\n    vertical-align: middle;\n    padding: 5px 5px;\n}\n\ndiv.text_cell_render table tr th {\n    border-bottom-width: 0;\n}\n\ndiv.text_cell_render ul, div.text_cell_render ol {\n    position: relative;\n    display: block;\n    margin-bottom: 0 !important;\n    line-height: var(--txbk-content-line-height);\n}\n\ndiv.text_cell_render ul {\n    list-style-type: disc;\n}\n\ndiv.text_cell_render ul li, div.text_cell_render ol li {\n    padding: .25em;\n}\n\ndiv.text_cell_render ul ul {\n    list-style-type: circle !important;\n}\n\ndiv.text_cell_render ul li > ul li a code,\ndiv.text_cell_render ul li > ol li a code,\ndiv.text_cell_render ol li > ul li a code,\ndiv.text_cell_render ol li > ol li a code {\n    color: var(--link-color);\n}\n\ndiv.text_cell_render ul ul ul {\n    list-style-type: square !important;\n}\n\ndiv.text_cell_render p > img:only-child {\n    display: block;\n    margin: auto;\n    max-width: 70% !important;\n}\n\ndiv.text_cell_render img {\n    max-width: 70%;\n}\n\n/*\n    ===================================\n    New CSS Classes and Styles\n    ===================================\n\n    --------------\n    1. Footnotes\n    --------------\n*/\n[id^='fn'], [class^='fn'] {\n    font-size: small !important;\n    font-weight: normal !important;\n    font-style: normal !important;\n    border-top: 1px solid var(--txbk-ui-mono-color);\n    padding-top: .8rem;\n    display: block;\n}\n\np > [id^='fn']:not(:first-child),\np > [class^='fn']:not(:first-child) {\n    border-top: 0 !important;\n}\n\n[id^='fn'] i, [class^='fn'] i,\n[id^='fn'] b, [class^='fn'] b,\n[id^='fn'] strong, [class^='fn'] strong,\np > strong > strong {\n    background-color: var(--txbk-content-mono-bgcolor);\n    font-style: normal !important;\n    font-weight: bold !important;\n}\n\n/* FIX Forcing monospace code to adhere with footnotes rules!*/\ndiv.text_cell_render p [id^='fn'] > code,\ndiv.text_cell_render p [class^='fn'] > code {\n    font-size: 1em !important;\n}\n\n/* CSS Anchors link as superscript (like footnotes) */\na[href^=\"#fn\"], a[href*=\"fn\"] {\n    font-size: 60%;\n    vertical-align: top;\n}\n/* Surround Footnotes by Square brackets */\na[href^=\"#fn\"]:before, a[href*=\"fn\"]:before {\n    content: \"[\";\n}\n\na[href^=\"#fn\"]:after, a[href*=\"fn\"]:after {\n    content: \"]\";\n}\n\n/* --------------\n    2. Drop cap\n   --------------\n*/\n.drop {\n    color: var(--drop-cap-color);\n    font-size: 75px;\n    line-height: 60px;\n    padding-top: 4px;\n    margin-top: 0.2rem;\n}\n\n/* -----------------------------\n    3. noTeXbook Text colours\n   -----------------------------\n*/\n.texbook-red {\n    color: var(--texbook-red);\n}\n\n.texbook-pink {\n    color: var(--texbook-pink);\n}\n\n.texbook-turquoise {\n    color: var(--texbook-turquoise);\n}\n\n.texbook-azure {\n    color: var(--texbook-azure);\n}\n\n.texbook-blue {\n    color: var(--texbook-blue);\n}\n\n.texbook-light-grey {\n    color: var(--texbook-light-grey);\n}\n\n.texbook-dark-grey {\n    color: var(--texbook-dark-grey);\n}\n\n.texbook-orange {\n    color: var(--texbook-orange);\n}\n\n.texbook-yellow {\n    color: var(--texbook-yellow);\n}\n\n/* ---------------------------------------------------------\n    4. IMG MaxWidthXX\n\n    CSS classes to control the max-width property of images\n    when the default 70% is not enough.\n    This is when images need to be enlarged or shrunk.\n   ---------------------------------------------------------\n*/\n\ndiv.text_cell_render img.maxw10,\ndiv.text_cell_render p > img.maxw10 {\n    max-width: 10% !important;\n}\n\ndiv.text_cell_render img.maxw15,\ndiv.text_cell_render p > img.maxw15 {\n    max-width: 15% !important;\n}\n\ndiv.text_cell_render img.maxw20,\ndiv.text_cell_render p > img.maxw20 {\n    max-width: 20% !important;\n}\n\ndiv.text_cell_render img.maxw25,\ndiv.text_cell_render p > img.maxw25 {\n    max-width: 25% !important;\n}\n\ndiv.text_cell_render img.maxw30,\ndiv.text_cell_render p > img.maxw30 {\n    max-width: 30% !important;\n}\n\ndiv.text_cell_render img.maxw35,\ndiv.text_cell_render p > img.maxw35 {\n    max-width: 35% !important;\n}\n\ndiv.text_cell_render img.maxw40,\ndiv.text_cell_render p > img.maxw40 {\n    max-width: 40% !important;\n}\n\ndiv.text_cell_render img.maxw45,\ndiv.text_cell_render p > img.maxw45 {\n    max-width: 45% !important;\n}\n\ndiv.text_cell_render img.maxw50,\ndiv.text_cell_render p > img.maxw50 {\n    max-width: 50% !important;\n}\n\ndiv.text_cell_render img.maxw55,\ndiv.text_cell_render p > img.maxw55 {\n    max-width: 55% !important;\n}\n\ndiv.text_cell_render img.maxw60,\ndiv.text_cell_render p > img.maxw60 {\n    max-width: 60% !important;\n}\n\ndiv.text_cell_render img.maxw65,\ndiv.text_cell_render p > img.maxw65 {\n    max-width: 65% !important;\n}\n\ndiv.text_cell_render img.maxw70,\ndiv.text_cell_render p > img.maxw70 {\n    max-width: 70% !important;\n}\n\ndiv.text_cell_render img.maxw75,\ndiv.text_cell_render p > img.maxw75 {\n    max-width: 75% !important;\n}\n\ndiv.text_cell_render img.maxw80,\ndiv.text_cell_render p > img.maxw80 {\n    max-width: 80% !important;\n}\n\ndiv.text_cell_render img.maxw85,\ndiv.text_cell_render p > img.maxw85 {\n    max-width: 85% !important;\n}\n\ndiv.text_cell_render img.maxw90,\ndiv.text_cell_render p > img.maxw90 {\n    max-width: 90% !important;\n}\n\ndiv.text_cell_render img.maxw95,\ndiv.text_cell_render p > img.maxw95 {\n    max-width: 95% !important;\n}\n\ndiv.text_cell_render img.maxw100,\ndiv.text_cell_render p > img.maxw100 {\n    max-width: 100% !important;\n}\n\n/*  ------------\n     4. Badges\n    ------------\n*/\n.badges img, .badges p img {\n    margin: 0 !important;  /* Override margins */\n    display: inline !important;\n    padding-right: 7px;\n}\n\n.badges p {\n    display: inline !important;\n}\n\n.badges {\n    display: block;\n    text-align: center;\n}\n\n/*  ----------------\n     5. Inline Math\n    ----------------\n*/\n.inline-math {\n    display: inline-block;\n}\n\n/*  --------------------\n     6. Inline Mono Font\n    --------------------\n*/\n.codemono code, .codemono pre, .codemono pre code {\n    font-family: var(--txbk-code-font-family) !important;\n}\n\n.mdmono code, .mdmono pre, .mdmono pre code {\n    font-family: var(--txbk-md-font-family) !important;\n}\n</style>\n\n\n\n<div class=\"nomono\">\n   The notebook is using\n    <a href=\"https://github.com/leriomaggio/notexbook-jupyter-theme\" title=\"noTeXbook Theme\">\n        <b>no$\\TeX$book</b></a> Jupyter Theme (release <code>2.0.1</code>).\n\n    <br />\n    <b>Theme Settings</b>:\n    <ul style=\"margin-top: 0.2em\">\n        <li>Notebook: Computer Modern font; 16px; Line spread 1.4.</li>\n        <li>Code Editor: <span class=\"codemono\">\n            <code>Fira Code</code> font; <code>14px</code>; Material Theme.\n        </span></li>\n        <li>Markdown Editor:<span class=\"mdmono\">\n            <code>Hack</code> font; <code>14px</code>; Material Theme.\n        </span></li>\n    </ul>\n\n</div>\n\n\n\n> *First things first:* **Thank you so much** for getting here (whatever is your `referral URL`)\n\nValerio \ud83e\udd17\n\n# \n\nThis notebook introduces the $\\text{no}\\TeX\\text{book}$ Jupyter Notebooks theme.\n\nIn the next two sections, we will start with a _quick overview_ <del>spoiler</del> of the theme's main typesetting features, then we will dive into all of its very _nuts and bolts_, including _Editor Colour Themes_, _ad-hoc formattings_, monospace fonts, and much more.\n\n## $\\text{no}\\TeX\\text{book}$ shall be _thy name_\n\n<span class=\"drop\">W</span>hen I had to come up with a name for the theme, I aimed almost immediately at finding a single word that would convey the idea of integration of the Jupyter notebooks with $\\LaTeX$ I had in mind. Indeed, **no$\\TeX$book** seemed quite an obvious choice: this name is a unique [portmanteau](https://www.merriam-webster.com/dictionary/portmanteau)[1](#fn1) that blends together the words **noTe**<del>X</del>**book**, and <del>no</del>**TeXbook**, that is the original name of [Donald E. Knuth](https://en.wikipedia.org/wiki/Donald_Knuth)'s [book](http://www.ctex.org/documents/shredder/src/texbook.pdf) on $\\TeX$.\n\nThat was the omen! _One!... Two!... Five!_ [2](#fn2 \"Monthy Python and the Holy Grail\")\n\n> The $\\text{no}\\TeX\\text{book}$ theme wishes to pay a tribute of gratitude to two of the technologies I do use and love the most as a researcher and a data scientist.\n\n<span id=\"fn1\"> **[1]**: `port\u00b7\u200bman\u00b7\u200bteau | \\ p\u022frt-\u02c8man-(\u02cc)t\u014d`</span>\n<span id=\"fn2\"> **[2]**: [The Holy Hand Granade](https://www.youtube.com/watch?v=xOrgLj9lOwk) - \n    Monthy Python and the Holy Grail</span>\n\n## $\\text{no}\\TeX\\text{book}$ Theme in a Nutshell\n\n- Notebook typesetting based on **Computer Modern** fonts;\n    - **Code** editor uses <span class=\"codemono\">`Fira Code`</span> font, with ligatures support;\n    - **Markdown** editor uses <span class=\"mdmono\">`Hack`</span> font (_slightly better for text \n    writing, ed._);\n- Colour themes with syntax highlighting for Code and Markdown editors\n    - _easy_ to personalise and extend (via CSS variables)\n- Highly customisable settings via IPython Magic arguments (`%texify?` to see all available options)\n- **Complete** support for Jupyterlab **and** Jupyter Notebooks (version `2.0x`);\n    - (**Extra**) Support for Google Colab Notebooks via [Stylus](https://en.wikipedia.org/wiki/Stylus_(browser_extension)) (Firefox & Chrome) browser extension;\n- Special Output formatting for `stderr` and `pandas.DataFrame`;\n- Extra `CSS` classes for additional LaTeX-ish formatting use cases (e.g. _footnotes_, _dropcap_).\n\n**Moreover**, the theme also includes a few tweaks to the general Notebook/Jupyterlab UI: the colours of all the icons and Kernel status indicators uses the theme's main palette, and a special emphasising effects is applied on _active_ cell in either _command_ or _edit_ modes, as well as on multiple cells selections.\n\n## Project Links\n\n- \ud83d\udce6 **PyPi package**: [pypi.org/project/notexbook-theme/](https://pypi.org/project/notexbook-theme/) \n- \ud83d\udc0d\ud83c\udfa8 **Official GitHub Repo**: [github.com/leriomaggio/notexbook-jupyter-theme/](https://github.com/leriomaggio/notexbook-jupyter-theme/) \n- \ud83d\ude80 **Documentation and GitHub Page**: [leriomaggio.github.io/notexbook-jupyter-theme/](https://leriomaggio.github.io/notexbook-jupyter-theme/) \n\n---\n\n# The $\\text{no}\\TeX\\text{book}$ Theme\n\n<a name=\"toc\"></a>\n## Table of Contents\n\n- [Colour Palette](#colours)\n- [Fonts and Typeface](#fonts)\n- [Markdown](#Markdown)\n    - [Code Highlithing](#mdcode)  \n    - [Math](#Math)\n    - [Extras](#Extras)\n        - [Footnotes](#Footnotes)\n        - [Drop Cap](#dropcap)\n        - [Image Widths](#imgwidth)\n        - [Badges](#badges)\n        - [Inline Math](#inlinemath)\n        - [Inline Mono](#inlinemono)\n\n- [Code](#code)\n    - [Code Editor](#material)\n    - [Dataframe](#dataframe)\n    - [Errors](#errors)\n    \n- [Extensions](#Extensions)\n    - [JupyterLab](#jupyterlab)\n    - [`custom.css` Jupyter theme](#customcss)\n    - [Google Colaboratory](#colab)\n\n- [Credits](#Credits)\n\n---\n\n<a name=\"colours\"></a>\n## Colour Palette\n\n\n```python\nimport numpy as np\nimport cv2\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\n# Matplotlib Configuration Params\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nmpl.rcParams['figure.figsize'] = (18,1)\n```\n\n\n```python\n# Color Palette\ncolours = {\"red\": \"#d43133\", \n           \"magenta\" : \"#D14187\", \n           \"torquoise\" : \"#009489\",\n           \"azure\": \"#00afde\", \n           \"blue\": \"#2875d9\",\n           \"light-grey\": \"#828282\", \n           \"dark-grey\": \"#383838\",\n           \"yellow\": \"#f9ab00\",\n           \"orange\": \"#e8710a\",\n          }\n```\n\n\n```python\ndef hex2rgb(h: str):\n    \"\"\"helper to convert hex colours into RGB tuple\"\"\"\n    h = h.lstrip('#')\n    return tuple(int(h[i:i+2], 16) for i in (0, 2, 4))\n\n# Create a black image\nimage = np.full((1024,1024,3), 255, np.uint8)\n\ndef show_palette(colours):\n    n_cols = len(colours)\n    fig = plt.figure()\n    for i, (colour, hexcode) in enumerate(sorted(colours.items(), key=lambda e: hex2rgb(e[1]))):\n        axis = fig.add_subplot(1,n_cols,i+1)\n        rgb = hex2rgb(hexcode)\n        cv2.circle(image, (512, 512), 512, (rgb[0], rgb[1], rgb[2]), -1)\n        plt.title(colour, y=-0.5)\n        plt.axis('off')\n        plt.imshow(image);\n        \nshow_palette(colours)\n```\n\nThe theme main colour palette is based on these main `7` colours. \n\nThese colours can also be used in special formattings for **text colouring** using _ad-hoc_ `CSS` classes (all following the same naming rule): `.texbook-<COLOUR NAME>`\n\n$\\rightarrow$ <b class=\"texbook-turquoise\"> Turquoise</b>; \n<b class=\"texbook-azure\">Azure</b>; <b class=\"texbook-blue\">Blue</b>;\n<b class=\"texbook-dark-grey\">Dark Grey</b>; <b class=\"texbook-light-grey\">Light Grey</b>;\n<b class=\"texbook-pink\">Magenta</b>; <b class=\"texbook-red\">Red</b>; \n<b class=\"texbook-orange\">Orange</b>; <b class=\"texbook-yellow\">Yellow</b> $\\leftarrow$\n\n\n[$\\uparrow$ top](#toc)\n\n---\n\n<a name=\"fonts\"></a>\n## Fonts and Typeface\n\nAll the fonts used in the $\\text{no}\\TeX\\text{book}$ theme typeface design are **open source**, freely available on public **font repositories** (e.g., [Google Fonts](https://fonts.google.com/), \n[CDN Fonts](https://fonts.cdnfonts.com), [FontSquirrel](https://www.fontsquirrel.com/)), and released under the [OFL](https://opensource.org/licenses/OFL-1.1) \n(**O**pen **F**ont **L**icense), and alike. \nOriginal reference and download links are provided below.\n\n**$\\text{no}\\TeX\\text{book}$ typeface**\n\nThe main goal of the $\\text{no}\\TeX\\text{book}$ theme is to allow Jupyter notebooks to render like a \n$\\LaTeX$-generated article. Therefore, the (**Markdown**) text rendering adopts the good ol' \n[*Computer Modern*](https://en.wikipedia.org/wiki/Computer_Modern) font family for both \nserif and `monospace` text (i.e. `CMUSerif` and `CMUTypewriter` fonts, respectively).\n\nIn **edit** mode, the [`Hack`](https://github.com/source-foundry/Hack) font is used for Markdown editor, whereas [`Fira Code`](https://github.com/tonsky/FiraCode) font is used\nfor code editor. The former looks slightly better for text writing (_imho_), being also based on the [`Bitstream Vera`](https://www.gnome.org/fonts/) and the\n[`DejaVu`](https://dejavu-fonts.github.io/) fonts. `Fira Code` on the other hand has been\nspecifically designed for source code, combining a clean and elegant style with [**ligratures**](https://github.com/tonsky/FiraCode#whats-in-the-box) support[3](#ligfn).\n\n<span id=\"ligfn\" class=\"fn\">**[3]**: Support for ligatures in the Markdown editor would be quite pointless, as the cell will be ultimately rendered in Computer Modern font.</span>\n\n**Notebook UI**\n\nThe font used for everything else in the Notebook UI and look-and-feel (e.g. `header`, `navbar`, \n`jupyter-server` home page (notebook list) uses the [`Roboto Slab`](https://fonts.google.com/specimen/Roboto+Slab) font.\n\n\n**Font References and Links**\n\n|Font                  | Format           | Reference        | License  | Download |\n|:---------------------|:-----------------|:----------------:|:--------:|:--------:|\n| `Computer Modern`    | OpenType (`otf`) |[tug.org](https://tug.org/FontCatalogue/computermodern/)| [SIL OFL](https://www.fontsquirrel.com/license/computer-modern \"Computer Modern Family Font License\")|[Link](https://www.checkmyworking.com/cm-web-fonts/Computer%20Modern.zip \"Computer Modern Family Font Download\")|\n| `Hack`               | TrueType (`ttf`) |[Github](https://github.com/source-foundry/Hack)|[MIT](https://github.com/source-foundry/Hack/blob/master/LICENSE.md)|[Link](https://github.com/source-foundry/Hack/releases \"Hack Font Releases\")|\n| `Fira Code`            | OpenType (`otf`) |[Github](https://github.com/tonsky/FiraCode)|[SIL OFT](https://github.com/tonsky/FiraCode/blob/master/LICENSE \"Fira Code Font License\")|[Link](https://github.com/tonsky/FiraCode/releases/ \"Fira Code Font Releases\")|\n| `Roboto Slab`        | OpenType (`otf`) |[Google Fonts](https://fonts.google.com/specimen/Roboto+Slab)|[Apache License, v2.0](https://fonts.google.com/specimen/Roboto+Slab#license \"Roboto Slab Font License\")|[Link](https://fonts.google.com/download?family=Roboto%20Slab \"Roboto Slab Font Download\")|\n\n\n[$\\uparrow$ top](#toc)\n\n---\n\n## Markdown\n\n(Miscellaneous of text formatting and emphasis - adapted from [Markdown Cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)) - License: [CC-BY](https://creativecommons.org/licenses/by/3.0/)\n\nEmphasis, aka italics, with *asterisks* or _underscores_.\n\nStrong emphasis, aka bold, with **asterisks** or __underscores__.\n\nCombined emphasis with **asterisks and _underscores_**, also for **`bold`** *`italic`* `mono`\n\n```\nMono blocks are supported too.\n```\n\nStrikethrough uses two tildes, colored in <b class=\"texbook-red\">red</b>: ~~Scratch this.~~\n\n**Headers**\n\n# Part   (`h1`)\n## Chapter (`h2`)\n### Section (`h3`)\n#### Subsection (`h4`)\n##### Subsubsection (`h5`)\n###### Paragraph (`h6`)\n\n**Lists**\n\n- First item\n- Second item\n  - Third item\n    - Another level\n    \n1. First ordered list item\n2. Another item with `mono`\n  * Unordered sub-list. \n1. Actual numbers don't matter, just that it's a number\n  1. Ordered sub-list\n4. And another item.\n\n**Tables**\n\n| Tables        | Are           | Cool  |\n| ------------- |:-------------:| -----:|\n| col 3 is      | right-aligned | \\$1600 |\n| col 2 is      | centered      |   \\$12 |\n| zebra stripes | are neat      |    \\$1 |\n\n**Blockquotes and `Monospace Paragraphs`**\n\n> Blockquotes are very handy in email to emulate reply text.\n> This line is part of the same quote.\n\n```\nThis paragraph will be using monospace font.\n```\n\n\n[$\\uparrow$ top](#toc)\n\n<a name=\"mdcode\"></a>\n### Code Highlighting\n\nSpecial mention goes to code syntax highlighting support in Markdown cells: they will still be using the default `CMUTypewriter` monospace font, \nbut they will also share the **same** colour scheme used for **code** cells (more on this in the [Code Editor](#material) Section).\n\nFor example:\n\n```Javascript\n// Javascript Highlighting\nvar x = 3.14;    // A number with decimals\nvar y = 3;       // A number without decimals\n```\n\n```Python\n# Python highlighting\nimport antigravity\nfrom __future__ import barry_as_FLUFL  # PEP401\n```\n\n```shell\necho \"Shell syntaxt highlighting\"\n```\n\n[$\\uparrow$ top](#toc)\n\n### Math\n\nMath and $LaTeX$ text style integration is supported (via `MathJax`) both in **inline** and **block** modes.\n\n**Inline math**:  $ X^2 + 1 = 1 $ works fine.\n\n**Math block**:\n\n$$\nX^2 + 1 = 1\n$$\n\nSome more Math examples taken from [Latex/Advanced Mathematics](https://en.wikibooks.org/wiki/LaTeX/Advanced_Mathematics):\n\n$$\n\\begin{equation} \n f(x)=(x+a)(x+b)\n\\end{equation}\n$$\n$$\n\\begin{equation}\n  L' = {L}{\\sqrt{1-\\frac{v^2}{c^2}}}\n\\end{equation}\n$$\n\n**Maxwell's equations:**\n$$\n\\begin{equation}\n \\left.\\begin{aligned}\n        B'&=-\\partial \\times E,\\\\\n        E'&=\\partial \\times B - 4\\pi j,\n       \\end{aligned}\n \\right\\}\n \\qquad \\text{Maxwell's equations}\n\\end{equation}\n$$\n\n**Factorials and Binomials:**\n$$\n\\frac{n!}{k!(n-k)!} = \\binom{n}{k}\n$$\n\n_fraction within a fraction_\n$$\n\\frac{\\frac{1}{x}+\\frac{1}{y}}{y-z}\n$$\n\n**Limits**:\n$$\n\\begin{equation}\n  \\lim_{a\\to \\infty} \\tfrac{1}{a}\n\\end{equation}\n$$\n\n**Math formulas with comments**:\n\n$$\n[\n y = a + f(\\underbrace{b x}_{\n                    \\ge 0 \\text{ by assumption}}) \n   = a + f(\\underbrace{b x}_{\n          \\ge 0 \\text{ by assumption}})\n]\n$$\n\n**`gather`**: Consecutive equations without alignment\n$$\n\\begin{gather*}\na_0=\\frac{1}{\\pi}\\int\\limits_{-\\pi}^{\\pi}f(x)\\,\\mathrm{d}x\\\\[6pt]\n\\begin{split}\na_n=\\frac{1}{\\pi}\\int\\limits_{-\\pi}^{\\pi}f(x)\\cos nx\\,\\mathrm{d}x=\\\\\n=\\frac{1}{\\pi}\\int\\limits_{-\\pi}^{\\pi}x^2\\cos nx\\,\\mathrm{d}x\n\\end{split}\\\\[6pt]\n\\begin{split}\nb_n=\\frac{1}{\\pi}\\int\\limits_{-\\pi}^{\\pi}f(x)\\sin nx\\,\\mathrm{d}x=\\\\\n=\\frac{1}{\\pi}\\int\\limits_{-\\pi}^{\\pi}x^2\\sin nx\\,\\mathrm{d}x\n\\end{split}\\\\[6pt]\n\\end{gather*}\n$$\n\n**`alignat`**: Allows control of the horizontal space between equations.\n$$\n\\begin{alignat}{2}\n \\sigma_1 &= x + y  &\\quad \\sigma_2 &= \\frac{x}{y} \\\\\t\n \\sigma_1' &= \\frac{\\partial x + y}{\\partial x} & \\sigma_2' \n    &= \\frac{\\partial \\frac{x}{y}}{\\partial x}\n\\end{alignat}\n$$\n\n[$\\uparrow$ top](#toc)\n\n### Extras\n\nIn addition to standard Markdown integration, the $\\text{no}\\TeX\\text{book}$ theme provides extra `CSS` classes to allow for additional $\\LaTeX$-ish formatting, and extra typesetting for notebooks: \n\n1. [Footnotes](#Footnotes)\n2. [Drop Cap](#dropcap)\n3. [Image Width](#imgwidth)\n4. [Badges](#badges)\n5. [Inline Math](#inlinemath)\n6. [Inline Mono](#inlinemono)\n\n#### 1. Footnotes\n\nAny HTML link targeting a bookmark or an anchor including `fn` (as in _footnote_) in their name will be automatically interpreted as links to a footnote. For example:\n\n```markdown\n    [1](#fnlink)\n```\n\nThe above link will be automatically rendered as superscript and within square-brackets[1](#fnlink)\n\nTo actually generate the footnote text, every `HTML` tag mapped to an `id` starting with `fn` (or alternatively using the `fn` class) will be automatically formatted as footnote text. Footnote symbol should be emphasised in bold:\n\n```html\n<span id=\"fnlink\"><b>[1]:</b> This is an example of a footnote</span>\n```\n\n<span id=\"fnlink\"><b>[1]:</b> This is an example of a footnote</span>\n\n<a name=\"dropcap\"></a>\n### <span class=\"drop\">2</span> Drop Cap\n\nA special class to display a [**drop cap**](https://en.wiktionary.org/wiki/drop_cap) could not be missing in the $\\text{no}\\TeX\\text{book}$ theme. \n\nIt is just required to use the `drop` `CSS` class:\n\n```html\n    <span class=\"drop\">O</span>nce upone a time...\n```\n\n<span class=\"drop\">O</span>nce upone a time...\n\n\n### 3. Image Width\n<a name=\"imgwidth\"></a>\n\nAs default, the `max-width` of images (and SVG) is automatically capped at the `70%` to allow for a \nproper rendering of large images, whilst avoiding any potential overflow. \n\nNonetheless, there may be cases in which it would be required to control the `max-width` parameter in order to enlarge or \nshrink an image. Special `CSS` classes are available controlling the `max-width` attribute of displaying images.\n\n**All this classes** share the same name prefix (i.e. **`.maxw`**) followed by the corresponding ma-width expressed as percentage value.\nThe list of available CSS Classes is: \n\n```python \n>>> [f\"maxw{i}\" for i in range(5, 101, 5)]\n['maxw10', 'maxw15', 'maxw20', 'maxw25', 'maxw30', 'maxw35', 'maxw40', 'maxw45', 'maxw50', \n 'maxw55', 'maxw60', 'maxw65', 'maxw70', 'maxw75', 'maxw80', 'maxw85', 'maxw90', 'maxw95', \n 'maxw100']\n```\n\n**Examples**:\n\n```html\n<!-- max-width: 10% -->\n  \n```\n\n\n\n```html\n<!-- max-width: 35% -->\n\n```\n\n\n\n### 4. Badges\n<a name=\"badges\"></a>\n\nThe theme also defines special classes to include [badges](https://shields.io/).\n\nThis may turn out to be particularly useful in notebooks to include links to external services like [Google Colab](https://colab.research.google.com), [MyBinder](https://mybinder.org), or [NBViewer](https://nbviewer.jupyter.org),\n\nIn order to do so, the theme provides the `CSS` class **`.badges`** that can be used in a Markdown cell:\n\n```html\n<div class=\"badges\"> ... </div>\n```\n\nHere is an example:\n\n<div class=\"badges\">\n\n[]()\n\n[]()\n    \n[]()\n</div>\n\n\n<a name=\"inlinemath\"></a>\n### 5. Inline Math\n\nThe `inline-math` `CSS` class forces to display `inline` Math blocks. This may be particularly useful in cases we do want to use the $\\LaTeX$ Math-block environment to write equation, but we do not want to have it displayed in a separate paragraph:\n\n$$\n\\sum_{i=1}^{N} x_i^2\n$$\n\nTo do so, let's just wrap the equation with a `span` HTML tag with class **`.inline-math`**:\n\n```html\n<span class=\"inline-math\">... </span>\n```\n\nThis equation will be displayed **inline**: \n<span class=\"inline-math\">\n$$\n\\sum_{i=1}^{N} x_i^2\n$$\n</span>\n\n\n<a name=\"inlinemono\"></a>\n### 6. Inline Mono\n\nThe default `monospace` font used in Markdown Cell rendering is `CMUTypewriter`, that is the monospace font of the **Computer Modern Family**.\nHowever, the $\\text{no}\\TeX\\text{book}$ theme also utilises two additional monospace fonts (for Code and Markdown editors), and sometimes it may also be required to use any of these fonts in rendered text. \n\nTo do so, the theme provides two special `CSS` classes, namely **`.codemono`** and **`.mdmono`** that will serve exactly this purpose.\n\nThe example below demonstrates how to _force_ the rendering of the following inline mono using code editor font\n\n```html\n<span class=\"codemono\">`Code Monospace Font` with Ligatures **support** `--> >= !=`</span>\n```\n\n<span class=\"codemono\">`Code Monospace Font` with Ligatures **support** `--> >= !=`</span>\n\n\n\n\n\n[$\\uparrow$ top](#toc)\n\n---\n\n<a name=\"code\"></a>\n## Code Sample\n\nHere is how Python code looks like in $\\text{no}\\TeX\\text{book}$ theme.\n\nThe following code excerpt has been taken from the **PyTorch** code base \n([source](https://github.com/pytorch/pytorch/blob/master/torch/utils/data/dataset.py#L4))\n\n\n```python\nclass Dataset(object):\n    r\"\"\"An abstract class representing a :class:`Dataset`.\n    All datasets that represent a map from keys to data samples should subclass\n    it. All subclasses should overwrite :meth:`__getitem__`, supporting fetching a\n    data sample for a given key. Subclasses could also optionally overwrite\n    :meth:`__len__`, which is expected to return the size of the dataset by many\n    :class:`~torch.utils.data.Sampler` implementations and the default options\n    of :class:`~torch.utils.data.DataLoader`.\n    .. note::\n      :class:`~torch.utils.data.DataLoader` by default constructs a index\n      sampler that yields integral indices.  To make it work with a map-style\n      dataset with non-integral indices/keys, a custom sampler must be provided.\n    \"\"\"\n\n    def __getitem__(self, index):\n        raise NotImplementedError\n\n    def __add__(self, other):\n        return ConcatDataset([self, other])\n\n    # No `def __len__(self)` default?\n    # See NOTE [ Lack of Default `__len__` in Python Abstract Base Classes ]\n    # in pytorch/torch/utils/data/sampler.py\n```\n\n\n[$\\uparrow$ top](#toc)\n\n### Code Editor\n\nThe CSS style for code and markdown editor integrated in $\\text{no}\\TeX\\text{book}$ adopts a strategy that aims at _flexibility_ and *extensibility*.\n\nThe main style file for code editors is `editors.css`. This file _imports_ each theme for both code and \nmarkdown editors. The themes for the two editors are defined in two different files, to allow for \nmaxmimum flexibility in the choice of the colours schemes to adopt.\n\nIn each theme file, the base **colour** palette is defined, along with the mapping of each of these \ncolours to specific (editor) variables.\nThese variables are then used to define the CSS style rules.\n\nIn this way, it is very easy to change or try multiple themes, or even defining custom new ones.\n\nThe default colour scheme used for code and markdown editor is based on the\n**Material Design Light** [Theme](https://github.com/JonaDuran/Material-Light-Theme/).\nIn addition, other editor themes are bundled with the $\\text{no}\\TeX\\text{book}$ Jupyter theme, e.g. `GitHub Light` for code, `Typora` theme for markdown.\n\nThe base colour palettes for each of those themes are showed below.\n\n<a name=\"material\"></a>\n### **(Code &amp; Markdown)** Material Design Light Theme (`material`)\n\nThe **default** colour palette used for both Code and Markdown editors is inspired by the \nMaterial Design [Light Theme](https://github.com/JonaDuran/Material-Light-Theme/).\n\nThe colour palette is declined on `12` colours, reported below:\n\n\n```python\nmaterial_code_colours = {\n    \"light-white\": \"#FAFAFA\",\n    \"black\": \"#212121\",\n    \"dark-blue\" : \"#01579B11\",\n    \"dark-blue-2\": \"#01579B22\",\n    \"blue\": \"#1565C0\",\n    \"green\": \"#2E7D32\",\n    \"yellow\": \"#A8601A\",\n    \"cyan\": \"#00838f\",\n    \"magenta\": \"#9C00B0\",\n    \"red\": \"#C0392B\",\n    \"grey\": \"#9E9E9E\",\n    \"light-blue\": \"#78909c\"\n}\n\nshow_palette(material_code_colours)\n```\n\nThe **Markdown** editor uses only a subset of those colours. In particular:\n\n\n```python\nmaterial_md_colours = {\n    \"black\": \"#212121\",\n    \"dark-blue\" : \"#01579B11\",\n    \"blue\": \"#1565C0\",\n    \"yellow\": \"#A8601A\",\n    \"red\": \"#C0392B\",\n    \"grey\": \"#9E9E9E\",\n    \"light-blue\": \"#78909c\"\n}\n\nshow_palette(material_md_colours)\n```\n\n### **(Code only)** GitHub Theme (`github`)\n\n\nThis theme builds on the **new** code editor theme available on **GitHub**.\n\n\n```python\ngithub_code_colours = {\n    \"white\": \"#fafafa\",\n    \"red\": \"#d65b67\",\n    \"orange\": \"#df7b41\",\n    \"yellow\": \"#f5e17b\",\n    \"blue\": \"#0259be\",\n    \"dark-blue\": \"#053060\",\n    \"black\": \"#24292e\",\n    \"azure\": \"#c0d8f4\",\n    \"grey\": \"#868c94\",\n    \"light-grey\": \"#b3b4b6\",\n    \"purple\": \"#724abd\",\n}\n\nshow_palette(github_code_colours)\n```\n\n### **(Code only)** GitHub Light Theme (`github-light`)\n\nThe **GitHub Light** theme is an _alternative_ theme inspired by the (previous) GitHub light theme.\n\n**Reference**: [Github Syntax Highlighting](https://github.com/primer/github-syntax-light)\n\n\n```python\ngithub_code_colours = {\n    \"dark-grey\": \"#505050\",\n    \"grey\": \"#b8b8b8\",\n    \"light-grey\": \"#6a737d\",\n    \"lighter-grey\": \"#e2e2e2\",\n    \"antrax\": \"#24292e\",\n    \"red\": \"#d73a49\",\n    \"orange\": \"#e36209\",\n    \"dark-orange\": \"#f14c00\",\n    \"purple\": \"#6f42c1\",\n    \"light-yellow\": \"#fff9eb\",\n    \"yellow\": \"#ffea7f\",\n    \"blue\": \"#005cc5\",\n    \"dark-blue\": \"#032f62\",\n    \"green\": \"#22863a\"\n}\n\nshow_palette(github_code_colours)\n```\n\n### **(Code only)** Crisp Light Theme (`crisp`)\n\nThe colour palette of the **Crisp Light** editor theme is inspired by the \nCrisp light theme included in the **Rainglow** collection of VSCode Themes\n\n**Reference**: https://github.com/rainglow/vscode/\n\n\n```python\ncrisp_code_colours = {\n    \"lilac\": \"#c6a7c6\",\n    \"black\": \"#221a22\",\n    \"grey\": \"#b8b8b8\",\n    \"yellow\": \"#fc9a0f\",\n    \"dark-orange\": \"#fc6a0f\",\n    \"purple\": \"#765478\",\n    \"dark-purple\": \"#4f3c4f\",\n    \"light-purple\": \"#99769b\",\n    \"red\": \"#cf433e\"\n}\n\nshow_palette(crisp_code_colours)\n```\n\n### **(Markdown only)** Typora Theme (`typora`)\n\nThis theme is inspired by the default (markdown) source code visualiser \navailable built-in in [Typora](https://typora.io/)[\\*](#fn_md)\n\n<span id=\"fn_md\" class=\"fn\"><i>*</i>: Typora is definitely my default editor for Markdown! \n    Highly recommended $\\rightarrow$ [typora.io](http://typora.io)</span>\n\n\n\n```python\ntypora_md_colours = {\n    \"pink\": \"#d14187\",\n    \"dark-grey\": \"#383838\",\n    \"darker-grey\": \"#333333\",\n    \"taupe\": \"#a99f9f\",\n    \"light-orange\": \"#be7716\",\n    \"light-red\": \"#a34343\",\n    \"grey-blue\": \"#48599b\",\n    \"dark-bg\": \"#252a2f\",\n    \"dirty-white\": \"#8d8e8f\"\n}\n\nshow_palette(typora_md_colours)\n```\n\n\n[$\\uparrow$ top](#toc)\n\n<a name=\"dataframe\"></a>\n### Dataframe\n\nThe look and feel of `dataframes` (tables) is slightly changed.\n\nI've chosen a post-it note color for the table background so that dataframe output standsout, especially when scrolling through a long notebook.\n\n\n```python\nfrom sklearn.datasets import load_iris\nimport pandas as pd \n\n\niris = load_iris()\niris_df = pd.DataFrame(data= np.c_[iris['data'], iris['target']], \n                       columns= iris['feature_names'] + ['target'])\niris_df.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>sepal length (cm)</th>\n      <th>sepal width (cm)</th>\n      <th>petal length (cm)</th>\n      <th>petal width (cm)</th>\n      <th>target</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>5.1</td>\n      <td>3.5</td>\n      <td>1.4</td>\n      <td>0.2</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>4.9</td>\n      <td>3.0</td>\n      <td>1.4</td>\n      <td>0.2</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>4.7</td>\n      <td>3.2</td>\n      <td>1.3</td>\n      <td>0.2</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>4.6</td>\n      <td>3.1</td>\n      <td>1.5</td>\n      <td>0.2</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>5.0</td>\n      <td>3.6</td>\n      <td>1.4</td>\n      <td>0.2</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n<a name=\"errors\"></a>\n### Errors and Exceptions\n\n\n```python\nfrom wherever import non_existing_module\n```\n\n\n```python\nfrom scipy import linalg\nlinalg.det(np.ones((3, 4)))\n```\n\n\n[$\\uparrow$ top](#toc)\n\n---\n\n## Extensions\n\n<a name=\"jupyterlab\"></a>\n### JupyterLab (and HTML export)\n\n**Jupyter Lab** is **fully** supported!\n\nMoreover: the latest versions of [`jupyter-nbconvert`](https://nbconvert.readthedocs.io/en/latest/) apply the `lab` template as [**default HTML**](https://nbconvert.readthedocs.io/en/latest/customizing.html?highlight=template#where-are-nbconvert-templates-installed) template for export. This generates a DOM structure which is compliant with Jupyter Lab.\n\nHere is an example of this notebook exported with `lab` template $\\Rightarrow$ [Jupyter Lab Light](./jupyter_lab_export.html)\n\n<a name=\"customcss\"></a>\n### `custom.css` Jupyter theme\n\nThe $\\text{no}\\TeX\\text{book}$ theme is **also** available as a **full-fledged** _custom_ Jupyter notebook theme (HTML/CSS).\nThis is useful in case one would prefer to enable the theme as **the** global custom default Jupyter theme.\n\nThe `noTeXbook` theme package is available for [download](https://github.com/leriomaggio/notexbook-jupyter-theme/releases), \nalong with its corresponding [documentation](https://github.com/leriomaggio/notexbook-jupyter-theme/blob/custom-css/README.md). \n\nThe documentation also contains details on the original CSS design, and instructions on how to define \nyour own CSS Editor Colour theme.\n\n<a name=\"colab\"></a>\n### Google Colaboratory\n\nThe HTML of a Colaboratory notebook is nothing similar to the standard Jupyter notebook/lab HTML structure (so the `custom-css` cannot work). In addition, every single Colaboratory notebook cell generates a new `HTML iframe`, so making the `texify` IPython magic pretty much useless too.\n\nTherefore, the *only* solution I could resort to was using the [Stylus](https://en.wikipedia.org/wiki/Stylus_(browser_extension)) browser extension.\nUnfortunately this is not as customisable and portable as the IPython magic, but hey?! Better than nothing \ud83e\udd13\n\nAll the instructions on how to install $\\text{no}\\TeX\\text{book}$ for Google Colaboratory Notebooks are available [$\\Rightarrow$ here](https://github.com/leriomaggio/notexbook-jupyter-theme/blob/texbook-colab/README.md#colab)) on the branch specifically dedicated to the `Colab` version of the theme.\n\nOnce you are done, try to open the sample notebook in Colab, and enjoy \ud83d\ude4c\n\n[](https://colab.research.google.com/github/leriomaggio/notexbook-jupyter-theme/blob/master/docs/noTeXbook_Theme_Sample.ipynb)\n\n\n\n\n[$\\uparrow$ top](#toc)\n\n---\n\n## Credits\n\n* The [`spinzero`](https://github.com/neilpanchal/spinzero-jupyter-theme) jupyter theme has been inspirational in the design of the early version of this theme;\n* The idea of overlay of selected cells has been inspired from [this](https://gist.github.com/formigone/dbabdd4ae38ded54b6f028713ac78c8a) custom theme.\n* Inspiration on the choice of Monospace fonts for code and markdown has come from this [article](https://fontsarena.com/blog/best-programming-fonts/) \n* Original versions of colour themes for code and markdown editors:\n\t- [Material Design Light](https://github.com/JonaDuran/Material-Light-Theme/)\n\t- [GitHub Light](https://github.com/primer/github-syntax-light)\n\t- [Crisp Rainglow Collection](https://github.com/rainglow/vscode/)\n\n\n\n### Useful Links\n\n(Some links I found useful along the way):\n\n- [Computer Modern on the Web](https://www.checkmyworking.com/cm-web-fonts/)\n- [`setuptools`: Specify Dependencies](https://python-packaging.readthedocs.io/en/latest/dependencies.html)\n- [How to Add Custom `setup.py` commands](https://jichu4n.com/posts/how-to-add-custom-build-steps-and-commands-to-setuppy/)\n- [`pyproject.toml`](https://martin-thoma.com/pyproject-toml/)\n- [What the heck is `pyproject.toml`](https://snarky.ca/what-the-heck-is-pyproject-toml/)\n- [Jupyter Server Extension](https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Distributing%20Jupyter%20Extensions%20as%20Python%20Packages.html) (Particularly useful in earlier version of this project in which fonts where handled as local resources)\n\n\n\n### Acknowledgments\n\nSpecial thanks to [cdesio](https://github.com/cdesio), [ninadicara](https://github.com/ninadicara), and [alanderex](https://github.com/alanderex) for testing earlier versions of the theme!\n\n\n\n[$\\uparrow$ top](#toc)\n", "meta": {"hexsha": "d4ad48edf8a6c554eea7bab1dcaf847c6a4f5a8a", "size": 526196, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/noTeXbook_Theme_Sample.ipynb", "max_stars_repo_name": "Mingxue-Xu/notexbook-jupyter-theme", "max_stars_repo_head_hexsha": "7b4b52152c9c4b76a805499e103f55cff3774412", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2020-11-14T12:47:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T01:38:35.000Z", "max_issues_repo_path": "docs/noTeXbook_Theme_Sample.ipynb", "max_issues_repo_name": "Mingxue-Xu/notexbook-jupyter-theme", "max_issues_repo_head_hexsha": "7b4b52152c9c4b76a805499e103f55cff3774412", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2020-10-31T20:18:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T22:26:01.000Z", "max_forks_repo_path": "docs/noTeXbook_Theme_Sample.ipynb", "max_forks_repo_name": "leriomaggio/notexbook-jupyter-theme", "max_forks_repo_head_hexsha": "7b4b52152c9c4b76a805499e103f55cff3774412", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-31T01:39:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T08:50:59.000Z", "avg_line_length": 116.7767421216, "max_line_length": 65768, "alphanum_fraction": 0.8129195205, "converted": true, "num_tokens": 30795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14223190591772394, "lm_q2_score": 0.0838903778216118, "lm_q1q2_score": 0.011931888325725804}}
{"text": "\n\n<a href=\"https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcallysto-sample-notebooks&branch=master&subPath=notebooks/Demonstrations/introductory_workshop.ipynb&depth=1\" target=\"_parent\"></a>\n\n# Things to cover (this slide will be removed) \n\n1. Introduction/Flashy examples of what you can do\n    1. Show off some of the cooler notebooks/lessons?\n    2. Woo the audience. \n\n2. Accessing Content\n   \n    1. logging in/github?\n    2. requesting new content?\n    3. how it's organized \n\n3. Doin' stuff with the content\n    1. how to run stuff, what you can do\n    2. changing it if you want\n    3. interactive activity of making things happen? \n    4. examples where no coding is required? \n4. Basic trouble shooting.\n    1. go over some error messages and how to fix them?\n    2. reload - kill kernel - run all\n    \n5. nbgitpuller for automation\n    1. how to set up automated assignments and grading\n\n6. How to use this in a classroom \n\n** NEED MORE IMAGES SO THE DEMO IS MORE EXCITING **\n    \n\n\n# Callysto Introductory Workshop\n</br>\n</br>\n</br>\n</br>\n</br>\n\n\n\n\n<div style= \"float:left; width: 60%; position: relative; \">\n\n<br>\n<br>\n</div>\n<div style= \"float:right; width: 40%; position: relative; top:25px;\">\n\n<br>\n<br>\n\n</div>\n\n# Today's Agenda\n- Introduction to Callysto\n- What is computational thinking?\n- How Callysto incorporates computational thinking into current curriculum objectives\n- Hands on demonstrations of classroom-ready pre-made notebooks\n    - And how to modify them to your classroom specific needs!\n    - Break in the middle\n- Future Plans\n    - How to request new content\n    - Developing your own content\n- Anonymous feedback form\n\n# Introduction to Callysto\n- Callysto is a cost-free learning program for grades 5-12 using Jupyter notebooks\n- Teaches traditional curriculum goals through the use of computational thinking\n    - Incorporates real world data in many cases\n    - Demonstrates problem solving skills?\n- Completely free for classroom use\n- Only requires a modern web browser - you do not need to install anything on your local machine\n- Funded by the federal government through the CanCODE initiative. \n\n# [CanCODE](https://www.canada.ca/en/innovation-science-economic-development/programs/science-technology-partnerships/cancode.html?utm_campaign=not-applicable&utm_source=cancode_vanity-url&utm_medium=vanity-url): Preparing Canada's Youth For a Digital Future\n\n- In order to prepare Canada's youth for an ever more competitive job market which requires digital skills, the federal government is supplying funding via the CanCODE initiative.\n- This project aims to teach Canadian students more than just how to use technoligy - **it aims to introduce Canadian students of all ages to the idea of 'Computational thinking'**\n- Does not necessarily mean learning how to code.\n\n## Computational Thinking\n\n>\"Simply put, [computational thinking] is \u201cthinking (or problem solving) like a computer scientist.\u201d It is the thought processes involved in understanding a problem and expressing its solutions in such a way that a computer can potentially carry out the solution. [computational thinking] is fundamentally about using analytic and algorithmic concepts and strategies most closely related to computer science to formulate, analyze and solve problems.\"\n>\n>-[Shuchi Grover](https://www.edsurge.com/news/2018-02-25-the-5th-c-of-21st-century-skills-try-computational-thinking-not-coding)\n\n## Computational thinking is not:\n\n- Writing code.\n- Using computers to automate and solve problems.\n- Only applicable to math and science. \n\n\n<div style= \"float:right; position: relative; top: -75px; right:0px;\">\n</a>\n</div>\n\n## Computational thinking is:\n- A problem solving methodology.\n- Thinking algorithmically.\n- Problem abstraction and modeling.\n- Problem modularization.\n- Finding solutions to abstract and complicated problems.\n\n\n\n\n## Computational thinking can:\n- Be embedded in all subjects and assist in curriculum outcomes.\n    - ** EXAMPLES OF THE ABOVE **\n- Be learned and taught without writing a single line of code.\n    - Of course, there is no reason why you couldn't write code.\n- Help teach course content, provide \"real world\" examples, and the thought processes that go into that analysis.\n\n\n\n# Callysto and Jupyter Notebooks \n- Will allow students to experiment and explore concepts easily and quickly.\n- Will allow students to tie in real-time data with their current learning objectives.\n- Will enable students to ask questions and explore problems in ways that traditional pen and paper demonstrations cannot\n\n# Embedding Computational Thinking in Current Objectives With Callysto\n- Our notebooks use concepts of computer science to teach and demonstrate standard curriculum goals.\n- No programming required to understand many of our notebooks. \n- You will not need to create new lessons which incorporate this for you - simply ask our development team to develop content, or even create your own if you're truly interested. \n\n# First Demo\n- Link to demo\n- Instructions\n    - To run the notebook, from the top menu simply click `Cell` $\\rightarrow$ `Run All`\n    - Looking at any code is not necessary, simply click the `Hide Code` button at the top\n    to view or hide code. \n    - Take sometime to familiarize yourself with the notebook.\n    \n- Demo specific instructions \n\n# Tutorial on Editing a Notebook \n** For this one I was thinking we'd have the teachers do this directly in a notebook/new notebook and we could have them create all these things themselves while we run a demo at the front of the room ***\n- If you like the content of a notebook, but you want to add/remove some detail or custom questions, you're free to do that directly in the Notebook itself. And the process is no more complicated than Microsoft Word!\n- By double clicking on a markdown, or text cell, you will enter edit mode.\n    - Simply begin typing your additional information, then press `Ctrl + Enter`\n    - You can add titles\n    - You can create lists\n    - You can create links\n    - You can use block quotes\n    - You can create tables\n    - You can write equations\n    - You can embed images\n    \n- If you want to create a new cell, from the top menu simply click the '**<span style=\"font-size:larger;\">+</span>**'. This will create a new cell below your currently selected one. Then, from the dropdown menu which defaults to `Code` click this menu, and select `Markdown`. You have now created a new cell for writing text\n\n- [A link to a list of markdown options](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)\n\n# Second Demo\n- Link to demo\n- Demo specific instructions\n\n# 15 Minute Break\n- Grab a coffee and feel free to ask us any questions you may have.\n\n# Third Demo\n- Link to demo\n- Demo specific instructions\n\n# Final Demo\n- Link to demo\n- Demo specific instructions \n\n# Distributing and Collecting Student Notebooks \n - There are a few potential ways you can distribute and collect notebooks from students\n    - Email them a link to the notebook as we've done here\n    - To collect assignments, do so using `nbgrader`, a notebook add-on that will allow you to collect assignments quickly, and even automate grading. (DO WE WANT TO INCLUDE THIS IN THE DEMO) \n\n# Accessing More Ready Made Content\n1. Go to [hub.callysto.ca](https://hub.callysto.ca/)\n2. Log in with an existing Google account.\n3. Download content using nbgitpuller **HOW ARE WE HAVING THE TEACHERS/STUDENTS DOWNLOAD THE REPOSITORY???**\n4. Celebrate \n\n\n- All this content is hosted on the Rapid Access Cloud (RAC) and can be used directly in your browser.\n- There is no need to install any packages or files to your, or your student's computers.\n- Tour of the Hub\n\n\n<div style= \"float:right; position: relative; top: -125px; right:30px;\">\n<a href= \"https://hub.callysto.ca/\"></a>\n</div>\n\n# Current Alberta Curriculum Outcomes\n- The current Alberta curriculum competency requirements are\n</a>\n\n\n\n\n# Conclusion\n- With Callysto, computational thinking is naturally incorporated into the existing curriculum outcomes\n</a>\n\n- I note that this slide will be our conclusion. If everything works out well, the workshop will leave the teachers with the impression we want: after they've tested out sample notebooks they'll realize that if they use Callysto they'll be meeting their new competency goal of Computational thinking in parallel with their other objectives and curriculum outcomes.\n\n# Requesting Custom Content\n- Demos shown today/content online not right for you? Ask us to create some content that will work well in your classroom\n- Contact us at callysto@cybera.ca ** IS THIS THE CORRECT EMAIL?**\n    - Tell us what you would like to see in a notebook that you would use in the classroom\n- Work with our developers to create some content\n\n\n\n# Creating your own content\n- If you know Python, you can create and distribute your own content right on the hub already.\n- If you would like to learn python/how to use the hub attend our next workshop at TIME AND LOCATION IF WE KNOW IT\n\n\n# Questions?\n\n# Please take a moment to fill out a short survey about today's workshop\n\n- [Link to survey](https://docs.google.com/forms/d/e/1FAIpQLSfg7K3CxYeUf8_9hbWnVcd77rqZZPT-5uIe_1JbLJscpP9AmQ/viewform?usp=sf_link)\n\n# Using Ready Made Content\n1. Once you have the files, you can browse them from the Jupyter hub as you would on your computer.\n- Open DEMONSTRATION NOTEBOOK\n- In the top menu, click `Cell` $\\rightarrow$ `Run All`\n- Walk through of notebook\n- Note Show/Hide code button\n- Demo of FIRST DEMONSTRATION\n\n\n# Basic Jupyter/Python ( I don't know if this is part of the presentation)\nI suggest having a \"Do this section\" in the presentation, but making a separate notebook for the teachers to use themselves to keep them engaged/learn. \n\n# Basic Markdown Styles\n\nMarkdown is quite versatile and supports titles, italic and bold fonts, itemized lists, hyperlinks, images, tables, etc... In fact, every non-code cell in this presentation was created using Markdown! A few of the basic markdown commands are\n\n1. Titles\n    - Title text is rendered with a pound sign (`#`) at the beginning of a line, followed by a space and the text you wish to turn into a title/header. For example, `# This is a title` would create a title at any location within your cell. and \n    - Adding additional pound signs (example: `### Smaller title or heading`) creates different headings. \n- Italics\n    - _Italics_ are done by surrounding a word with underscores (`_`). For example `_this would be italics_` would render in italics.\n- Bold \n    - **Bold** lettering is done with double asterisks (`**`). For example, `**bold choice**` would render as bold text.\n\n- Lists\n    - Lists can be generated simply by starting a new line and typing `1.` will start a list. Subsequent items can simply be started with a dash `-`, and the markdown will take care of the numbering for you.\n    - You can also make sub-items by starting a new line within your list, and pressing `Tab`, then either using dashes for points, or starting with `1.` or `A.` for sublist items. \n    \n- Raw text\n    - Raw text, or text which ignores any of the style commands can be rendered using an open comma ( \\`). For example \\` sentence \\` would render as `sentence`, and would escape any and all other markdown commands.\n\n- Math\n    - Markdown also supports Latex style equations. For a variable x, you can render it in-line by surrounding it like so: `$x$` which renders as $x$. if you want to render an equation proper, you can do it either like\n    ```$$ f(x) = x^2 $$``` or \n    ```\n\\begin{equation}\nf(x) = x^2\n\\end{equation}\n       ```\n    which both render as \n    \\begin{equation}\n    f(x) = x^2\n    \\end{equation}\n\n\n# Demo Number Two\n1. Run stuff\n- Change stuff\n- Break stuff?\n- get comfortable with it\n\n\n```python\n# Anything after a pound sign is a comment -- it is not run as code\n\n# The most basic command is the classic \"hello world\" command, which displays the statement \"hello world\"\n# on the screen. In Python with a Jupyter note book, this is done by typing:\n\n# print(\"Hello world!\")\n\n# then pressing Ctrl + Enter in the specified cell. Try deleting the pound sign in the line\n# above and running this cell. Did you get an \"IndentationError\"? If so, this is because leading\n# whitespace in Python is used as a \"boundary\" so to speak (more on this in a few minutes!). For \n# now, simply move the print statement to the left edge of the cell and try again. \n\n```\n\n\n```python\n# You can also do basic mathematical operations\n\nprint(1 + 1)\nprint(10 * 6)\nprint(2 / 4)\nprint(10 - 9)\n# You can also apply certain manipulations to characters, \n# which are refered to as strings in computer science talk\n\nprint(\"a\" + \"b\")\nprint(\"a\" * 10)\n\n```\n\n\n```python\n# you can also give things names, known as \"variables\". Here 'a' and 'b' are now being\n# defined as variables, and we're assigning them the values 10 and 20 respectively via the \n# '=' operation.\na = 10\nb = 20\nprint(a + b)\n```\n\n\n```python\n# variables are shared between cells as well, where we've used the ',' in the print \n# statment in order to display both variables on the command line. \nprint(a,b)\n```\n\n\n```python\n# You can also do things multiple times using a \"for\" loop\nfor i in range(10):\n    print(i)\n    \n# where you'll notice that counting starts at 0 and we ignore the number 10. Here we've assigned each value to\n# the variable i above. Notice how it counts and we need a colon. What happens if you remove the colon? \n# Also notice how our print statement is indented under the for loop. This is because python sees everything \n# indented one level as \"inside the loop\" -- anything indented like the print statement will be executed\n# every time the program goes through the loop. This is why white space is so important in Python\n\n\n```\n\n\n```python\n# You can also test the \"truth\" of something with an if statement, which does something if something\n# is true\n\nfor i in range(10):\n    if i == 5:\n        print(i == 5,i)\n    else:\n        print(i == 5,i)\n        \n# notice the next level of indentaion for the if statement as well Also notice the double equals. Also notice \n# how it prints True\n\n```\n\n\n```python\n# A handy way to know what something does is type its name followed by a question mark\nprint?\n\n```\n\n[](https://github.com/callysto/curriculum-notebooks/blob/master/LICENSE.md)\n", "meta": {"hexsha": "8b164109efaaa32a905d0a76acc7e40f3a48a444", "size": 20903, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Demonstrations/introductory_workshop.ipynb", "max_stars_repo_name": "callysto/callysto-sample-notebooks", "max_stars_repo_head_hexsha": "1e441a08687243030b5dec3b763e5ec883ee6c20", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-04-04T19:14:48.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-04T19:14:48.000Z", "max_issues_repo_path": "notebooks/Demonstrations/introductory_workshop.ipynb", "max_issues_repo_name": "callysto/callysto-sample-notebooks", "max_issues_repo_head_hexsha": "1e441a08687243030b5dec3b763e5ec883ee6c20", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2018-04-05T13:34:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-25T01:02:30.000Z", "max_forks_repo_path": "notebooks/Demonstrations/introductory_workshop.ipynb", "max_forks_repo_name": "callysto/callysto-sample-notebooks", "max_forks_repo_head_hexsha": "1e441a08687243030b5dec3b763e5ec883ee6c20", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2018-04-04T19:25:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T04:43:51.000Z", "avg_line_length": 20903.0, "max_line_length": 20903, "alphanum_fraction": 0.6820552074, "converted": true, "num_tokens": 3427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.060086653540254206, "lm_q2_score": 0.19682619893177908, "lm_q1q2_score": 0.011826627622858962}}
{"text": "```python\nimport glob\nimport os\n\nimport pathlib\nimport shutil\n\nimport re\n```\n\n\n```python\ndef change_suffix(file_name, from_suffix, to_suffix):\n    # \u30d5\u30a1\u30a4\u30eb\u306e\u62e1\u5f35\u5b50\u3092\u5f97\u308b\n    sf = pathlib.PurePath(file_name).suffix\n    \n    # \u5909\u66f4\u5bfe\u8c61\u304b\u3069\u3046\u304b\u5224\u5b9a\u3059\u308b\n    if sf == from_suffix:\n        # \u30d5\u30a1\u30a4\u30eb\u540d(\u62e1\u5f35\u5b50\u9664\u304f)\u3092\u5f97\u308b\n        st = pathlib.PurePath(file_name).stem\n\n        # \u5909\u66f4\u5f8c\u306e\u30d5\u30a1\u30a4\u30eb\u540d\u3092\u5f97\u308b\n        to_name = st + to_suffix\n\n        # \u30d5\u30a1\u30a4\u30eb\u540d\u3092\u5909\u66f4\u3059\u308b\n        shutil.copyfile(file_name, to_name)\n    \n    return to_name\n```\n\n\n```python\nchange_suffix('sample.abc', '.abc', '.xyz')\n\nfile_name = glob.glob('*.tex')[0]\nfile_name = change_suffix(file_name, '.tex', '.txt')\n```\n\n\n```python\ndef tex_trans(data_lines):\n    \n    # data_lines = data_lines.replace('documentclass', 'bocumentclass')\n\n    # \\begin{document} \u4ee5\u4e0b\u3092\u62bd\u51fa\n    data_lines = re.search(r'\\\\begin{document}[\\s\\S]*\\\\end{document}', data_lines).group()\n    # data_lines = data_lines[data_lines.find(r'\\begin{document}')+16:]\n\n    # data_lines = data_lines.replace('\\n', '')\n\n    # \u4f59\u8a08\u306a\u7a7a\u767d\u3092\u4e00\u3064\u306b\u5909\u63db\n    data_lines = re.sub('[ ]+', ' ', data_lines)\n    # \u8907\u6570\u6539\u884c\u3092\u4e00\u3064\u306e\u6539\u884c\u306b\u5909\u63db\n    data_lines = re.sub('[\\n]+', '\\n', data_lines)\n    # \u6539\u884c\u5f8c\u306e\u7a7a\u767d\u3092\u524a\u9664\n    data_lines = re.sub('\\n'+'[ ]+', '\\n', data_lines) \n\n    # \u65b9\u7a0b\u5f0f\u306e\u5909\u63db\n    equations = re.findall(r'\\\\begin{equation}[\\s\\S]*?\\\\end{equation}', data_lines)\n    for equation in equations:\n        data_lines = data_lines.replace(equation, 'EQUATION')\n    aligns = re.findall(r'\\\\begin{align}[\\s\\S]*?\\\\end{align}', data_lines)\n    equations = re.findall(r'\\\\begin{equation\\*}[\\s\\S]*?\\\\end{equation\\*}', data_lines)\n    for equation in equations:\n        data_lines = data_lines.replace(equation, 'EQUATION')\n    for align in aligns:\n        data_lines = data_lines.replace(eq, 'EQUATION')\n    commentouts = re.findall(r'%.*\\n', data_lines)\n    for com in commentouts:\n        data_lines = data_lines.replace(com, '')\n    functions = re.findall(r'(\\n\\\\[\\s\\S]*?)(?=\\n)', data_lines) # \n    # functions = re.findall(r'(\\n\\\\[\\s\\S]*?)\\n', data_lines) # \u3053\u308c\u3060\u3068\u91cd\u8907\u306f\u6301\u3063\u3066\u3053\u306a\u3044\u3053\u3068\u306b\u6ce8\u610f\n    for func in functions:\n        data_lines = data_lines.replace(func, '')\n    eqs = re.findall(r'\\$[\\s\\S]*?\\$', data_lines)\n    for eq in eqs:\n        data_lines = data_lines.replace(eq, 'EQ')\n\n\n    data_lines = data_lines.lstrip(r'\\begin{document}')\n    data_lines = data_lines.rstrip(r'\\end{document}')\n\n    # data_lines = data_lines.replace(re.search(r'\\\\begin{equation}[\\s\\S]*\\\\end{equation}', data_lines).group(), 'EQUATION')\n\n    # \u6587\u4e2d\u306e\u6539\u884c\u3092\u524a\u9664\n    data_lines = re.sub(r'\\n(?=[a-z])', ' ', data_lines)\n    data_lines = re.sub(r'\\n(?=[0123456789])', ' ', data_lines)\n    data_lines = re.sub('[ ]+', ' ', data_lines)\n\n    return data_lines\n```\n\n\n```python\nwith open(file_name, encoding='utf-8') as f:\n    data_lines = f.read()\n\ndata_lines = tex_trans(data_lines)\n\n# \u540c\u3058\u30d5\u30a1\u30a4\u30eb\u540d\u3067\u4fdd\u5b58\nnew_file_name = 'output.txt'\nwith open(new_file_name, mode='w', encoding='utf-8') as f:\n    f.write(data_lines)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "de37f3641134b396e55f52f124dbedcd7b98a6d9", "size": 4902, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tex/tex_trans.ipynb", "max_stars_repo_name": "keikagawa/tex-trans", "max_stars_repo_head_hexsha": "7272ae6a9f0b38e8e7e265ca541aebab89783723", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/tex_trans.ipynb", "max_issues_repo_name": "keikagawa/tex-trans", "max_issues_repo_head_hexsha": "7272ae6a9f0b38e8e7e265ca541aebab89783723", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/tex_trans.ipynb", "max_forks_repo_name": "keikagawa/tex-trans", "max_forks_repo_head_hexsha": "7272ae6a9f0b38e8e7e265ca541aebab89783723", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2592592593, "max_line_length": 139, "alphanum_fraction": 0.5130558956, "converted": true, "num_tokens": 963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22270013882530884, "lm_q2_score": 0.052618950004997535, "lm_q1q2_score": 0.011718247470954936}}
{"text": "# Resolu\u00e7\u00e3o: Processo trainee Equipe ZebraAerodesign - Desempenho\n\n# Orienta\u00e7\u00f5es b\u00e1sicas\n\n- GitHub da equipe zebra: https://github.com/Zebra-Aerodesign\n\n## Baixando e instalando anaconda navigator\n\n1. Tutorial para baixar anaconda navigator https://www.youtube.com/watch?v=_eK0z5QbpKA\n    1. Link baixar o anaconda navigator https://www.anaconda.com/\n\n## Configurando o git e o github\n\n1. Baixe o git em https://git-scm.com/\n2. Crie uma conta no Github em https://github.com\n3. Baixe o Github desktop em https://github.com\n4. D\u00favidas sobre Github assista a playlist do prof. Gustavo Guanabara \nhttps://shorturl.at/rNSZ2\n\n\n## Configurando a biblioteca zebralib\n\n1. https://github.com/Zebra-Aerodesign/ZebraLib\n2. Clone o reposit\u00f3rio do Github no seu computador em C:\\Users\\\\....\\Anaconda3\n3. V\u00e1 em C:\\Users\\arthu\\Anaconda3\\Lib\\site-packages\n4. Crie um arquivo no bloco de notas chamado ZebraLib.pth e salve na pasta site-packages\n5. Dentro do arquivo coloque o local onde est\u00e1 a biblioteca exemplo: C:\\Users\\arthu\\Anaconda3\\ZebraLib\n6. Sucesso! Agora \u00e9 s\u00f3 importar a biblioteca no seu c\u00f3digo e se divertir ... :)\n\n# Entender mais sobre programa\u00e7\u00e3o b\u00e1sica e avan\u00e7ada\n\n## B\u00e1sica - Canal curso em video prof. gustavo guanabara link das playlist\n\n1. Curso de algorimos e l\u00f3gica de programa\u00e7\u00e3o: https://youtu.be/8mei6uVttho \n2. Programa\u00e7\u00e3o em python mundo 1: https://youtu.be/S9uPNppGsGo\n3. Programa\u00e7\u00e3o em python mundo 2: https://youtu.be/nJkVHusJp6E\n4. Programa\u00e7\u00e3o em python mundo 3: https://youtube.com/playlist?list=PLHz_AreHm4dksnH2jVTIVNviIMBVYyFnH\n5. Programa\u00e7\u00e3o em python exerc\u00edcios: https://youtube.com/playlist?list=PLHz_AreHm4dm6wYOIW20Nyg12TAjmMGT-\n6. Conceitos de Prog. orientada a objeto (assistir aulas em vermelho): https://youtu.be/KlIL63MeyMY\n\n## Avan\u00e7ada - link das playlist\n\n1. Jamal UFTPR - C\u00e1lculo num\u00e9rico: https://www.youtube.com/watch?v=Ow9Hx04qnaI&list=PLleETO-tMJixSTImpC54tjToBzw38NDLr\n2. APMonitor - Computa\u00e7\u00e3o para engenheiros: https://www.youtube.com/watch?v=gY0sEokk2h0&list=PLLBUgWXdTBDi-E--rwBujaNkTejLNI6ap\n3. APMonitor site - Tutoriais e exerc\u00edcios: http://apmonitor.com/che263/index.php/Main/PythonIntroduction\n\n## Onde encontrar ajuda com exemplos\n\n1. Aprender sobre *numpy*: https://numpy.org/doc/stable/reference/routines.html\n2. Aprender a plotar gr\u00e1fico com *matplotlib*: https://matplotlib.org/stable/gallery/index.html\n3. Aprender computa\u00e7\u00e3o ci\u00eantifica com *scipy*: https://docs.scipy.org/doc/scipy/reference/index.html \n\n# Gloss\u00e1rio\n\n1. **$b$** :                       Envergadura [$m$]\n2. **$S$** :                       \u00c1rea da asa [$m^2$]\n3. **$Af$** :                      Afilamento\n15. **$AR$** :                     Alongamento ou aspect ratio (AR) na asa retangular\n4. **$C_L$** :                     Coeficiente de sustenta\u00e7\u00e3o qualquer\n4. **$CL_n$** :                    Coeficiente de sustenta\u00e7\u00e3o com \u00e2ngulo de incid\u00eancia ou natural\n5. **$C_{Lmax}$** :                Coeficiente de sustenta\u00e7\u00e3o m\u00e1ximo da aeronave, Cl de estol\n5. **$C_{LLO}$** :                 Coeficiente de sustenta\u00e7\u00e3o para garantir a decolagem com o menor comprimento de pista poss\u00edvel\n20. **$C_{D0}$** :                 Coeficiente de arrasto parasita (coef zero-lift)\n20. **$C_{Di}$** :                 Coeficiente de arrasto induzido (coef due-lift) --> $K.C_{Lmax}^2$\n21. **$C_D$** :                    Coeficiente de arrasto total --> $C_{D} = C_{D0} + K.C_{Lmax}^2$\n6. **$S_{wet}$** :                 \u00c1rea molhada do avi\u00e3o [$m^2$]\n7. **$c$** :                       Corda m\u00e9dia [$m$]\n8. **$N_{max}$** :                 Fator de carga m\u00e1ximo estrutural do Diagrama Vn != turn_Nmax\n8. **$\\phi$** :                    Fator de efeito solo\n8. **$\\rho$** :                    Densidade do ar local [$kg/m^3$]\n8. **$D$** :                       For\u00e7a de arrasto [$N$]\n8. **$L$** :                       For\u00e7a de sustenta\u00e7\u00e3o [$N$]\n8. **$T$** ou **$T_d$** :          Tra\u00e7\u00e3o dispon\u00edvel [$N$]\n8. **$T_r$**  :                    Tra\u00e7\u00e3o requerida [$N$]\n9. **$h$** :                       Altura da asa em rela\u00e7\u00e3o ao ch\u00e3o [$m$]\n9. **$\\mu$** :                     Coefiente de atrito com o solo\n10. **$mv$** :                     Massa vazia da aeroave [$Kg$]\n11. **$a_o$** :                    \u00c2ngulo de incid\u00eancia da asa [Graus]\n12. **$a_{max}$** :                \u00c2ngulo maximo da asa (\u00e2ngulo de estol) [Graus]\n16. **$e_{0}$** :                  Fator efici\u00eante de Oswald\n17. **$K$** :                      Constante de proporcionalidade\n18. **$MTOW$** :                   Massa total de decolagem (Maximum Take-Off Weight)[$N$]\n18. **$M$** :                      Massa total da aeronave [$kg$]\n19. **$W$** :                      Peso total do avi\u00e3o     [$N$]\n22. **$V_{stall}$** :              Velocidade m\u00ednima em que a for\u00e7a de sustenta\u00e7\u00e3o consegue equilibrar o peso da aeronave\n23. **$V_{lo}$** :                 Velocidade de decolagem (lift-off) [ 20% maior que $V_{stall}$ ] \n24. **$V_{l}$** :                  Velocidade de aproxima\u00e7\u00e3o/pouso (landing) [ 30% maior que $V_{stall}$ ] \n24. **$S_{lo}$** :                 Dist\u00e2ncia de pista necess\u00e1ria para a decolagem [$m$]\n24. **$S_{l}$** :                  Dist\u00e2ncia de pista necess\u00e1ria para o pouso [$m$]\n\n## Decolagem \n\nPerfil da decolagem. O objetivo \u00e9 calcular a **dist\u00e2ncia** de decolagem at\u00e9 a velocidade **$V_{lo}$** o ultimo inst\u00e2nte onde h\u00e1 contato com o solo.\n\n\n\nDiagrama de corpo livre do avi\u00e3o durante a decolagem. Onde $V_{R}$ \u00e9 a velocidade com o vento relativo, $L$ for\u00e7a de sustenta\u00e7\u00e3o, $D$ for\u00e7a de arrasto ou tra\u00e7\u00e3o requerida, $T$ tra\u00e7\u00e3o dispon\u00edvel, $F_{at}$ for\u00e7a de atrito com o solo, $N$ normal (rela\u00e7\u00e3o W-L) e $W$ peso total da aeronave. \n\n\n\nEfeito solo\n\n\\begin{equation}\n    \\phi = \\frac{(16h/b)^2}{1 +(16h/b)^2} \n\\end{equation}\n\nCoeficientes aerodin\u00e2micos\n\n\\begin{equation}\n    C_D = (C_{D0} + \\phi. K C_{L}^2 )  \n\\end{equation}\n\n\\begin{equation}\n    C_{LLO} = \\frac{\\pi.e_{0}.AR.\\mu}{2 \\phi}  \n\\end{equation}\n\n\nVelocidades importantes \n\\begin{equation}\n    V_{estol} = \\sqrt{\\frac{2.W}{\\rho . S. C_{L_{max}}}}\n\\end{equation}\n\n\\begin{equation}\n    V_{lo} = 1.2 V_{estol}\n\\end{equation}\n\n\n```python\n\n```\n\nFor\u00e7as aerodin\u00e2micas\n\\begin{equation}\n    D = \\frac{1}{2}. \\rho. v^2. S. (C_{D0} + \\phi. K C_{L}^2 )  \n\\end{equation}\n\n\\begin{equation}\n    L = \\frac{1}{2}. \\rho. v^2. S. C_{L}  \n\\end{equation}\n\nAproxima\u00e7\u00e3o pra dist\u00e2ncia de decolagem\n\\begin{equation}\n    S_{lo} = \\frac{1.44W^2}{g S \\rho C_{Lmax} [ T-[D + \\mu(W-L)] ] }_{0.7V_{lo}}\n\\end{equation}\n\n\n```python\n\n```\n\n### Desafio 1\nDetermine o $AR$, alongamento da asa, **com programa\u00e7\u00e3o orientada a objeto**.\n\n\\begin{equation}\n    AR = \\frac{b^2}{S}  \n\\end{equation}\n\nDados: $b = 2.48m$ e $S = 0.90m^2$\n\n*Algoritmo para programa\u00e7\u00e3o*\n1. Crie uma classe 'avi\u00e3o'.\n2. Crie o construtor da classe que receba 2 parametros $(S, b)$.\n3. $AR$ \u00e9 um atributo da classe e deve ser calculado no construtor.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#Classe \nclass avi\u00e3o:\n    def __init__(self, S, b): #Construtor da classe\n        self.S = S\n        self.b = b     #Atributos                                 \n        self.AR = (self.b**2)/self.S \n\na = avi\u00e3o(0.9, 2.48)\na.S, a.b, a.AR \n```\n\n### Desafio 2\nConstrua um m\u00e9todo pra calcular a velocidade de estol **utilizando a classe avi\u00e3o**.\n\n\\begin{equation}\n    V_{estol} = \\sqrt{\\frac{2.W}{\\rho . S. C_{L_{max}}}}\n\\end{equation}\n\nDados: $\\rho = 1.225kg/m^3, S = 0.90m^2, C_{Lmax} = 1,65, W=150N$\n\n*Algoritmo para programa\u00e7\u00e3o*\n1. Crie uma classe 'avi\u00e3o'.\n2. Crie o construtor da classe que receba 3 parametros $(S, b, C_{L_{max}})$.\n3. $AR$ \u00e9 um atributo da classe e deve ser calculado no construtor.\n4. Implementar um m\u00e9todo pra calcular a $V_{stol}$ tendo como argumento do m\u00e9todo $W e \\rho$\n\n\n```python\n#Classe \nclass avi\u00e3o:\n    def __init__(self, S, b, CLmax): #Construtor da classe\n        self.S = S\n        self.b = b          #Atributos da classe\n        self.CLmax = CLmax      \n        \n        self.AR = (self.b**2)/self.S \n        \n    #M\u00e9todo da classe\n    def v_Stol(self, W, rho): # Argumentos do m\u00e9todo (W e rho)\n        V_stol = (2*W/(rho*self.S*self.CLmax))**0.5\n        return V_stol\n    \na = avi\u00e3o(0.9, 2.48, 1.65)\na.v_Stol(150, 1.225)\n```\n\n### Desafio 3\nUtilize a classe do desafio 2 para plotar um gr\u00e1fico um gr\u00e1fico de velocidade de stol por densidade do ar ( $V_{stol}$ x $\\rho$). Plote as curvas para 3  pesos diferentes.\n\n*Dados*: $W_1 = 85N, W_2= 100N, W_3=150N$\n\n\n```python\n#Instanciar o objeto\na = avi\u00e3o(0.9, 2.48, 1.65)\n\n#Criar um vetor de densidades\ndensidade = np.linspace(0.6, 1.225)\n\n#Aplicar o m\u00e9todo V_stol(150, rho) para gerar o vetor de velocidades\nvelocidade_85N = a.v_Stol(85, densidade)\nvelocidade_100N = a.v_Stol(100, densidade)\nvelocidade_150N = a.v_Stol(150, densidade)\n\n#Plotagem\nfig, ax = plt.subplots() #criando janela\nax.set(title=r'$V_{stol}$ x $\\rho$', xlabel=r'Densidade do ar [$kg/m^3$]', ylabel='$V_{stol}$ [$m/s$]') #nomes dos eixos e titulo\n\nax.plot(densidade, velocidade_85N, label=r'$V_{stol}$ pra W=85N') #plotagem do dados\nax.plot(densidade, velocidade_100N, label=r'$V_{stol}$ pra W=100N') #plotagem do dados\nax.plot(densidade, velocidade_150N, label=r'$V_{stol}$ pra W=150N') #plotagem do dados\n\nax.legend() #legenda\nax.grid(linestyle='dotted') #grid do fundo\n```\n\n### Desafio 4\n\nImplemente 3 novos m\u00e9todos dentro da classe avi\u00e3o. Um para calcular a for\u00e7a de sustenta\u00e7\u00e3o $L$, outro o arrasto $D$ e para calcular o efeito solo $\\phi$.\n\n\\begin{equation}\n    L = \\frac{1}{2}. \\rho. v^2. S. C_{L}  \n\\end{equation}\n\n\\begin{equation}\n    D = \\frac{1}{2}. \\rho. v^2. S. (C_{D0} + \\phi. K C_{L}^2 )  \n\\end{equation}\n\n\\begin{equation}\n    \\phi = \\frac{(16h/b)^2}{1 +(16h/b)^2} \n\\end{equation}\n\nCalcule o efeito solo  $\\phi$, for\u00e7a de sustenta\u00e7\u00e3o $L$ e for\u00e7a de arrasto $D$. Para velocidade de 15$m/s$, $C_L = 1.5$ e $\\rho = 1.225kg/m^3$.\n\n*Dados:* $b=2.48, S = 0.90m^2, C_{Lmax} = 1.65, C_{D0}=0.12, h=0.35m$\n\n*Algoritmo para programa\u00e7\u00e3o*\n1. Adicione 2 novos atributos no construtor $C_{D0}$ e $h$.\n2. J\u00e1 ser\u00e1 calcula pra vc a constante $K$ no construtor.\n3. Implemente: **efeito_Solo(self)** \u00e9 um m\u00e9todo que calcula ($\\phi$) e busca a altura $h$ como atributo do avi\u00e3o (self.h).\n4. Implemente: **sustenta\u00e7\u00e3o(self, V, CL, rho)** \u00e9 um m\u00e9todo que calcula ($L$) com 3 argumentos de entrada. Velocidade, Cl qualquer, densidade do ar.\n4. Implemente: **arrasto(self, V, CL, rho)** \u00e9 um m\u00e9todo que calcula ($D$) com 3 argumentos de entrada. Velocidade, Cl qualquer, densidade do ar.\n\n\n```python\n#Classe \nclass avi\u00e3o:\n    def __init__(self, S, b, CLmax, C_D0, h): #Construtor da classe\n        self.S = S\n        self.b = b          #Atributos da classe\n        self.CLmax = CLmax      \n        self. C_D0 = C_D0\n        self.h = h\n        \n        self.AR = (self.b**2)/self.S \n        self.K = 1/(3.14*0.75*self.AR)\n        \n    #M\u00e9todo da classe\n    def v_Stol(self, W, rho): # Argumentos do m\u00e9todo (W e rho)\n        V_stol = (2*W/(rho*self.S*self.CLmax))**0.5\n        return V_stol\n    \n    def efeito_Solo(self):\n        zw = 16 * self.h /self.b\n        phi = (zw ** 2) / (1 + zw ** 2)\n        return phi\n    \n    def sustenta\u00e7\u00e3o(self, V, CL, rho):\n        L = 0.5 * (V ** 2) * rho * self.S * CL\n        return L\n    \n    def arrasto(self, V, CL, rho):\n        D = (0.5* (V ** 2)* rho* self.S* (self.C_D0 + self.efeito_Solo() * self.K * CL ** 2))\n        return D\n```\n\n\n```python\navi\u00e3o_1 = avi\u00e3o(0.9, 2.48, 1.65, 0.12, 0.35)\navi\u00e3o_1.arrasto(15, 1.5, 1.225), avi\u00e3o_1.sustenta\u00e7\u00e3o(15, 1.5, 1.225), avi\u00e3o_1.efeito_Solo()\n```\n\n### Desafio 5\n*(Exemplo 4.9 - Pag 214. Miranda)* Determine o $C_{L}$ ideal para se garantir \numa decolagem com o menor comprimento de pista poss\u00edvel, conhecido como ($C_{LLO}$).\n\n\\begin{equation}\n    C_{LLO} = \\frac{\\pi.e_{0}.AR.\\mu}{2 \\phi}  \n\\end{equation}\n\nDados: $b = 2.48m$, $S = 0.90m^2$, $e_{0}$ = 0.717,  $\\mu = 0,030$ e $C_{D} = 0.022$\n\n*Algoritmo de solu\u00e7\u00e3o*\n\n*Algoritmo para programa\u00e7\u00e3o*\n1. Implemente: **CLL0_Ideal(self, mi)** \u00e9 um m\u00e9todo que calcula o ideal para se garantir a decolagem com o menor comprimento de pista poss\u00edvel.\n\n\n```python\n#Classe \nclass avi\u00e3o:\n    def __init__(self, S, b, CLmax, C_D0, h): #Construtor da classe\n        self.S = S\n        self.b = b          #Atributos da classe\n        self.CLmax = CLmax      \n        self. C_D0 = C_D0\n        self.h = h\n        \n        self.AR = (self.b**2)/self.S \n        self.K = 1/(3.14*0.75*self.AR)\n        \n    #M\u00e9todo da classe\n    def v_Stol(self, W, rho): # Argumentos do m\u00e9todo (W e rho)\n        V_stol = (2*W/(rho*self.S*self.CLmax))**0.5\n        return V_stol\n    \n    def efeito_Solo(self):\n        zw = 16 * self.h /self.b\n        phi = (zw ** 2) / (1 + zw ** 2)\n        return phi\n    \n    def sustenta\u00e7\u00e3o(self, V, CL, rho):\n        L = 0.5 * (V ** 2) * rho * self.S * CL\n        return L\n    \n    def arrasto(self, V, CL, rho):\n        D = (0.5* (V ** 2)* rho* self.S* (self.C_D0 + self.efeito_Solo() * self.K * CL ** 2))\n        return D\n    \n    def CLL0_Ideal(self, mi):\n        cll0 = np.pi*0.717*self.AR*mi/(2*self.efeito_Solo())\n        return cll0\n```\n\n\n```python\navi\u00e3o_1 = avi\u00e3o(0.9, 2.48, 1.65, 0.12, 0.35)\navi\u00e3o_1.CLL0_Ideal(0.03)\n```\n\n### Desafio 6\n*(Exemplo 4.10 - Pag 217. Miranda)* Determine o comprimento de pista $ S_{lo}$ necess\u00e1rio para a decolagem com um peso total de $150N$ em uma pista localizada ao n\u00edvel do mar $\\rho$ = \n1,225$kg/m^3$.\n\n\\begin{equation}\n    S_{lo} = \\frac{1.44W^2}{g S \\rho C_{Lmax} [ T-[D + \\mu(W-L)] ] }_{0.7V_{lo}} \n\\end{equation}\n\n*Dados:* $b=2.48, S = 0.90m^2, C_{Lmax} = 1.65, C_{D0}=0.12, h=0.35m, \\mu=0.03$\n\n*Algoritmo para programa\u00e7\u00e3o*\n1. Implemente: **distancia_decolagem(self, W, rho)** um m\u00e9todo que calcula a dist\u00e2ncia de decolagem (Equa\u00e7\u00e3o acima).\n\n*Algoritmo de para implementar o m\u00e9todo **distancia_decolagem(self, W, rho)***\n1. Considere tra\u00e7\u00e3o dispon\u00edvel $T=25N$\n1. Encontre a velocidade de decolagem $V_{lo} = 1.2V_{estol}$ \n2. Calcule o $C_{LLO}$ para substituir em $L$ e $D$. \n3. Calcule $L$ e $D$ na velocidade igual a $0.7V_{lo}$. \n4. Por fim, calcule $S_{lo}$\n\n\n```python\n#Classe \nclass avi\u00e3o:\n    def __init__(self, S, b, CLmax, C_D0, h): #Construtor da classe\n        self.S = S\n        self.b = b          #Atributos da classe\n        self.CLmax = CLmax      \n        self. C_D0 = C_D0\n        self.h = h\n        \n        self.AR = (self.b**2)/self.S \n        self.K = 1/(3.14*0.75*self.AR)\n        \n    #M\u00e9todo da classe\n    def v_Stol(self, W, rho): # Argumentos do m\u00e9todo (W e rho)\n        V_stol = (2*W/(rho*self.S*self.CLmax))**0.5\n        return V_stol\n    \n    def efeito_Solo(self):\n        zw = 16 * self.h /self.b\n        phi = (zw ** 2) / (1 + zw ** 2)\n        return phi\n    \n    def sustenta\u00e7\u00e3o(self, V, CL, rho):\n        L = 0.5 * (V ** 2) * rho * self.S * CL\n        return L\n    \n    def arrasto(self, V, CL, rho):\n        D = (0.5* (V ** 2)* rho* self.S* (self.C_D0 + self.efeito_Solo() * self.K * CL ** 2))\n        return D\n    \n    def CLL0_Ideal(self, mi):\n        cll0 = np.pi*0.717*self.AR*mi/(2*self.efeito_Solo())\n        return cll0\n    \n    def distancia_decolagem(self, W, rho, mi):\n        T = 33.207\n        \n        vlo = self.v_Stol(W, rho)*1.2\n        CLLO = self.CLL0_Ideal(mi)\n        \n        L = self.sustenta\u00e7\u00e3o(0.7*vlo, CLLO, rho)\n        D = self.arrasto(0.7*vlo, CLLO, rho)\n        \n        slo = (1.44*(W**2))/(9.81*self.S*rho*self.CLmax*(T - (D + mi*(W - L))))\n        return slo\n```\n\n\n```python\navi\u00e3o_1 = avi\u00e3o(0.9, 2.48, 1.65, 0.022, 0.35)\navi\u00e3o_1.distancia_decolagem(150, 1.225, 0.03)\n```\n\n## Manobra \n\n\n```python\n\n```\n", "meta": {"hexsha": "253503090a0a341683abd609f918fea3d82f688f", "size": 129330, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Projeto Zebra/.ipynb_checkpoints/Processo_trainee_desempenho_respostas-checkpoint.ipynb", "max_stars_repo_name": "Chabole/Python", "max_stars_repo_head_hexsha": "7c90b5e4029f2577d255f9a86861d06343d232de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Projeto Zebra/.ipynb_checkpoints/Processo_trainee_desempenho_respostas-checkpoint.ipynb", "max_issues_repo_name": "Chabole/Python", "max_issues_repo_head_hexsha": "7c90b5e4029f2577d255f9a86861d06343d232de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Projeto Zebra/.ipynb_checkpoints/Processo_trainee_desempenho_respostas-checkpoint.ipynb", "max_forks_repo_name": "Chabole/Python", "max_forks_repo_head_hexsha": "7c90b5e4029f2577d255f9a86861d06343d232de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-14T00:54:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T00:54:45.000Z", "avg_line_length": 194.1891891892, "max_line_length": 65400, "alphanum_fraction": 0.8821464471, "converted": true, "num_tokens": 5558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10521053389745762, "lm_q2_score": 0.11124120061463458, "lm_q1q2_score": 0.011703746108059894}}
{"text": "```python\nimport theme\ntheme.load_style()\n```\n\n\n\n\n<style>\n@import url('http://fonts.googleapis.com/css?family=Source+Code+Pro');\n@import url('http://fonts.googleapis.com/css?family=Vollkorn');\n@import url('http://fonts.googleapis.com/css?family=Arimo');\n@import url('http://fonts.googleapis.com/css?family=Arvo:400,700,400italic')\n\n#notebook li { /* More space between bullet points */\n    margin-top:0.8em;\n}\n\n/* draw border around running cells */\ndiv.cell.border-box-sizing.code_cell.running {\n    border: 3px solid #111;\n}\n\ndiv.cell.code_cell {\n    margin-top: 1em;\n    margin-left: auto;\n    margin-right: auto;\n    width: 800px;\n    border: 1px solid rgba(200, 200, 200, 0.8);\n    border-radius: 8px; /* rounded borders */\n}\n\ndiv.text_cell_render{\n    font-family: 'Arvo' sans-serif;\n    /* font-family: 'Arimo',verdana,arial,sans-serif; */\n    line-height: 130%;\n    font-size: 115%;\n    margin-left:0%;\n    margin-right:auto;\n}\n\n.text_cell_render h1 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 300;\n    font-style: bold;\n    font-size: 30pt;\n    line-height: 100%;\n    color:#c76c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h2 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 20pt;\n    line-height: 100%;\n    color:#c76c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h3 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 16pt;\n    line-height: 100%;\n    color:#d77c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h4 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 14pt;\n    font-style: italic;\n    line-height: 100%;\n    color:#d77c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h5 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 12pt;\n    color: #1d3b84;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n}\n\n.rendered_html code{\n    background-color: transparent;\n}\n\nul{\n    margin: 2em;\n}\n\nul li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.5em;\n}\n\nul li li{\n    padding-left: 0.2em;\n    margin-bottom: 0.2em;\n    margin-top: 0.2em;\n}\n\nol{\n    margin: 2em;\n}\n\nol li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.5em;\n}\n\nul li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.2em;\n}\n\na:link{\n    font-weight: bold;\n    color:#447adb;\n}\n\na:visited{\n    font-weight: bold;\n    color: #1d3b84;\n}\n\na:hover{\n    font-weight: bold;\n    color: #1d3b84;\n}\n\na:focus{\n    font-weight: bold;\n    color:#447adb;\n}\n\na:active{\n    font-weight: bold;\n    color:#447adb;\n}\n\n.rendered_html :link {\n    text-decoration: underline;\n}\n\n.rendered_html :hover {\n    text-decoration: none;\n}\n\n.rendered_html :visited {\n    text-decoration: none;\n}\n\n.rendered_html :focus {\n    text-decoration: none;\n}\n\n.rendered_html :active {\n    text-decoration: none;\n}\n\n.warning{\n    color: rgb( 240, 20, 20 )\n}\n\nhr {\n    color: #f3f3f3;\n    background-color: #f3f3f3;\n    height: 1px;\n}\n\nblockquote{\n    display:block;\n    background: #fcfcfc;\n    border-left: 5px solid #c76c0c;\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    width:680px;\n    padding: 10px 10px 10px 10px;\n}\n\nblockquote p {\n    margin-bottom: 0;\n    line-height: 125%;\n    font-size: 100%;\n}\n\ntable#mytable,\ntable#mytable td,\ntable#mytable tr\n{\n    border: none !important;\n}\n\ntable#mytable-1,\ntable#mytable-1 td,\ntable#mytable-1 tr\n{\n    border: none !important;\n    align: center;\n    cellspacing: 10;\n}\n\n.msg {\n    width: 90%;\n    margin-left: auto;\n    margin-right: auto;\n    margin-top: 10px;\n    margin-bottom: 10px;\n    padding: 14px 14px 14px 14px;\n    color: #c09853;\n    text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);\n    background-color: #fcf8e3;\n    border: 1px solid #fbeed5;\n    -webkit-border-radius: 4px;\n    -moz-border-radius: 4px;\n    border-radius: 4px;\n}\n\n.msg-heading {\n    color: inherit;\n}\n\n.msg .close {\n    position: relative;\n    top: -2px;\n    right: -21px;\n    line-height: 18px;\n}\n\n.msg-success {\n    color: #468847;\n    background-color: #dff0d8;\n    border-color: #d6e9c6;\n}\n\n.msg-danger,\n.msg-error {\n    color: #b94a48;\n    background-color: #f2dede;\n    border-color: #eed3d7;\n}\n\n.msg-info {\n    color: #3a87ad;\n    background-color: #d9edf7;\n    border-color: #bce8f1;\n}\n\n.boxed {\n    color: #b94a48;\n    background-color: #f2dede;\n    border-color: #eed3d7;\n    margin-left: auto;\n    margin-right: auto;\n    padding: 14px 14px 14px 14px;\n}\n\n.w-300 { width: 300px; }\n.w-400 { width: 400px; }\n.w-500 { width: 500px; }\n\n</style>\n\n\n\n\n# Higher Order Shape Functions\n\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\"></a>\n\nThis lecture by Tim Fuller is licensed under the\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\">Creative Commons Attribution 4.0 International License</a>.  All code examples are also licensed under the [MIT license](http://opensource.org/licenses/MIT).\n\n<a id='top'></a>\n\n# Topics\n\n- [Introduction](#intro)\n- [Quadratic Shape Functions](#quad-sf)\n  - [Direct Construction of Quadratic Shape Functions](#dir-quad-sf)\n- [Direct Construction of Shape Functions in Natural Coordinates](#dir-nat-sf)\n  - [Linear Shape Functions in Natural Coordinates](#nat-lin-sf)\n  - [Quadratic Shape Functions in Natural Coordinates](#nat-quad-sf)\n  - [Higher Order Shape Functions in Natural Coordinates](#nat-higher-sf)\n- [Example](#example)\n\n# <a id='intro'></a> Introduction[](#top)\n\nIn previous lectures, we have approximated the solution to the governing equations with linear shape functions.  Higher order approximate solutions, often times, can lead to increased accuracy, especially when extracting derivative values from the solution (i.e. stress and strain).\n\n# <a id='quad-sf'></a>  Quadratic Shape Functions[](#top)\n\nApproximate the dependent variable $u$ by a quadratic function\n\n$$\nU_N = a + b x + c x ^ 2\n= \\begin{pmatrix} 1 & x & x^2 \\end{pmatrix}\n  \\begin{pmatrix} a \\\\ b \\\\ c \\end{pmatrix}\n= \\boldsymbol{p}(x) \\boldsymbol{\\alpha}\n$$\n\nWe want to express the approximate solution to $u$ in terms of nodal displacements and not the constant coefficients $a$, $b$, and $c$.  Thus, we force the approximate solution $u$ to be equal to nodal displacements $u_1$, $u_2$, and $u_3$ and $x_1$, $x_2$, and $x_3$, respectively, on some finite element.\n\n$$\n\\begin{align}\n  u_1 &= a + b x_1 + c x_1^2 \\\\\n  u_2 &= a + b x_2 + c x_2^2 \\\\\n  u_3 &= a + b x_3 + c x_3^2 \\\\\n\\end{align} \\longrightarrow\n\\begin{pmatrix} u_1 \\\\ u_2 \\\\ u_3 \\end{pmatrix} =\n\\begin{pmatrix} \n1 & x_1 & x_1^2 \\\\ 1 & x_2 & x_2^2 \\\\ 1 & x_3 & x_3^2\n\\end{pmatrix}\n\\begin{pmatrix} a \\\\ b \\\\ c \\end{pmatrix} \n\\longrightarrow \\boldsymbol{d} = \\boldsymbol{M} \\boldsymbol{\\alpha}\n$$\n\nThen,\n\n$$\nU_N = \\boldsymbol{p} \\boldsymbol{M}^{-1} \\boldsymbol{d} = \n\\boldsymbol{N} \\boldsymbol{d} = \\sum_{i=1}^3 N_i(x)u_i\n$$\n\nwhere the shape functions $N_i$ are\n\n$$\nN_i = \\frac{2}{h_e^2} \n\\begin{pmatrix}\n  \\left(x - x_2\\right)\\left(x - x_3\\right) \\\\\n  -2\\left(x - x_1\\right)\\left(x - x_3\\right) \\\\\n  \\left(x - x_1\\right)\\left(x - x_2\\right) \\\\\n\\end{pmatrix}\n$$\n\n\n\n## <a id='dir-quad-sf'></a> Direct Construction of Quadratic Shape Functions\n\nThe method previously described is applicable to shape functions of any order, but, as you can imagine, the process becomes extremely involved and difficult for elements of order higher than 3 or so.  Fortunately, using the properties of shape functions that\n\n- the sum of all shape functions sums to 1 at all points (**partition of unity**)\n- the i$^\\mathrm{th}$ shape function has the Kronecker delta property and is the only non\u2010zero function in the series at node i, where it has a value of 1.\n\nany order shape function can be constructed directly.  For example, from the properties of shape functions we construct the quadratic shape function $N_1$ as\n\n$$\n\\begin{align}\n  \\text{General form of a quadratic product of monomials} &\\quad N_1 = \\frac{(x-a)(x-b)}{c} \\\\ \n  \\text{Kronecker delta property} &\\quad N_1 = \\frac{(x-x_2)(x-x_3)}{c} \\\\\n  N_x(x_1) = 1 &\\quad N_1 = \\frac{(x-x_2)(x-x_3)}{(x_1-x_2)(x_1-x_3)} \\\\\n\\end{align}\n$$\n\n# <a id='dir-nat-sf'></a> Direct Construction of Shape Functions in Natural Coordinates[](#top)\n\nAs discussed in [Lesson 12](Lesson12_NumericalIntegration.ipynb), for integration purposes, it is convenient to express element shape functions in the natural coordinates.  It turns out that since the element shape functions are interpolating polynomials, they can be formulated in the natural coordinates by normalizing the appropriate Lagrange interpolation functions in terms of $\\xi$.  For an element of $n$ nodes, the $n^{\\text{th}}$ Lagrange interpolating functions are formed such that\n\n\n$$\nL_i^n = c_i\\left(\\xi-\\xi_1\\right)\\left(\\xi-\\xi_2\\right)\n\\cdots\n\\left(\\xi-\\xi_{i-1}\\right)\\left(\\xi-\\xi_{i+1}\\right)\n\\cdots\n\\left(\\xi-\\xi_n\\right)\n$$\n\nThe $c_i$ are found by noting that \n\n$$\nL_i^n(\\xi_j) = \\begin{cases}\n1 & i = j \\\\\n0 & \\text{otherwise}\n\\end{cases}\n$$\n\nThus the $c_i$ are given by\n\n$$\nc_i = \\frac{1}{\n\\left(\\xi_i-\\xi_1\\right)\\left(\\xi_i-\\xi_2\\right)\n\\cdots\n\\left(\\xi_i-\\xi_{i-1}\\right)\\left(\\xi_i-\\xi_{i+1}\\right)\n\\cdots\n\\left(\\xi_i-\\xi_n\\right)}\n$$\n\nThen $L_i^n$ is\n\n$$\nL_i^n = \\frac{\\left(\\xi-\\xi_1\\right)\\left(\\xi-\\xi_2\\right)\n\\cdots\n\\left(\\xi-\\xi_{i-1}\\right)\\left(\\xi-\\xi_{i+1}\\right)\n\\cdots\n\\left(\\xi-\\xi_n\\right)}{\n\\left(\\xi_i-\\xi_1\\right)\\left(\\xi_i-\\xi_2\\right)\n\\cdots\n\\left(\\xi_i-\\xi_{i-1}\\right)\\left(\\xi_i-\\xi_{i+1}\\right)\n\\cdots\n\\left(\\xi_i-\\xi_n\\right)}\n$$\n\nFormed in this way, the $L_i^n$ are the element shape functions $\\phi_i$, expressed in the natural coordinates $\\xi$.\n\nInterpolation functions of this form are said to belong to the Lagrange family of interpolation polynomials.  The finite element models based on Lagrange interpolation polynomials are said to belong to the Lagrange family of finite elements.  All of the elements encountered in this course, thus far, have been Lagrange finite elements.\n\n## <a id='nat-lin-sf'></a>Linear Lagrange Shape Functions\n\nFor a linear linear two node element, the shape functions are found from the linear Lagrange interpolating functions:\n\n$$\n\\phi_1(\\xi) = L_1^1(\\xi) = \\frac{\\xi - \\xi_2}{\\xi_1 - \\xi_2} = \\frac{\\xi - 1}{(-1) - 1} = -\\frac{\\xi - 1}{2}\n$$\n$$\n\\phi_2(\\xi) = L_2^1(\\xi) = \\frac{\\xi - \\xi_1}{\\xi_2 - \\xi_1} = \\frac{\\xi - (-1)}{1 - (-1)} = \\frac{\\xi +1}{2}\n$$\n\nOr\n\n$$\n\\{\\phi\\}  \n= \\frac{1}{2}\n\\begin{Bmatrix}\n1 - \\xi \\\\\n1 + \\xi\n\\end{Bmatrix}\n$$\n\n## <a id='nat-quad-sf'></a>Quadratic Lagrange Shape Functions\n\nFor a linear linear two node element, the shape functions are found from the quadratic Lagrange interpolating functions with $\\xi_1=-1$, $\\xi_2=1$, $\\xi_3=0$:\n\n$$\n\\begin{align}\n\\phi_1(\\xi) = L_1^2(\\xi)  &= \\frac{\\left(\\xi-\\xi_2\\right)\\left(\\xi-\\xi_3\\right)}\n                                  {\\left(\\xi_1-\\xi_2\\right)\\left(\\xi_1-\\xi_3\\right)}\n                           = \\frac{\\xi\\left(\\xi-1\\right)}{2} \\\\\n\\phi_2(\\xi) = L_2^2(\\xi)  &= \\frac{\\left(\\xi-\\xi_1\\right)\\left(\\xi-\\xi_3\\right)}\n                                  {\\left(\\xi_2-\\xi_1\\right)\\left(\\xi_2-\\xi_3\\right)} \n                           = \\frac{\\xi\\left(\\xi+1\\right)}{2} \\\\\n\\phi_3(\\xi) = L_3^2(\\xi)  &= \\frac{\\left(\\xi-\\xi_1\\right)\\left(\\xi-\\xi_2\\right)}\n                                  {\\left(\\xi_3-\\xi_1\\right)\\left(\\xi_3-\\xi_2\\right)} \n                           = -\\left(\\xi+1\\right)\\left(\\xi-1\\right)\n\\end{align}\n$$\n\n$$\n\\phi_i = \\frac{1}{2}\n\\begin{Bmatrix}\n-\\xi(1 - \\xi) \\\\ \\xi(1+\\xi) \\\\ 2(1 + \\xi)(1 - \\xi)\\\\\n\\end{Bmatrix}\n$$\n\n### <a id='iso-p-map-quad'></a>Isoparametric Mapping\n\nBased on our choice of the $\\xi_i$, the isoparametric mapping for the quadratic map looks like\n\n\n\nMathematically, the mapping from physical to natural coordinates is similar in structure to that of the linear element and is given by\n\n\n$$\nx = \\sum_{i=1}^3 N_i(\\xi) x_i \\Longrightarrow\n-\\frac{1}{2}\\xi\\left(1-\\xi\\right)x_1 + \n\\frac{1}{2}\\xi\\left(1+\\xi\\right)x_2 + \n\\left(1-\\xi^2\\right)x_3\n$$\n\nAnd the Jacobian is given by\n\n$$\n\\begin{align}\nJ &= \\frac{dx}{d\\xi} = \\sum_{i=1}^{3} \\frac{dN_i(\\xi)}{d\\xi}x_i \\\\\n  &= \\frac{1}{2}\\left(2\\xi - 1\\right)x_1 + \n     \\frac{1}{2}\\left(2\\xi + 1\\right)x_2 +\n     2\\xi x_3\n\\end{align}\n$$\n\nNote that the Jacobian is no longer constant and must be included in the integration of the force and stiffness matrices.\n\n## <a id='nat-higher-sf'></a>Higher Order Lagrange Shape Functions\n\nHigher order Lagrange shape functions are derived similarly to the linear and quadratic.\n\n# <a id='example'></a>Example[](#top)\n\n\n```python\n\n```\n", "meta": {"hexsha": "03209ce2589bcfeb3fb67a5b6219fea146a7b3fc", "size": 20435, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lessons/Lesson11_HigherOrderShapeFuncs.ipynb", "max_stars_repo_name": "jzw0025/fem-with-python", "max_stars_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 148, "max_stars_repo_stars_event_min_datetime": "2015-11-05T16:32:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:42:26.000Z", "max_issues_repo_path": "Lessons/Lesson11_HigherOrderShapeFuncs.ipynb", "max_issues_repo_name": "pinkieli/fem-with-python", "max_issues_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lessons/Lesson11_HigherOrderShapeFuncs.ipynb", "max_forks_repo_name": "pinkieli/fem-with-python", "max_forks_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": 74, "max_forks_repo_forks_event_min_datetime": "2016-02-17T13:23:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T07:48:27.000Z", "avg_line_length": 34.229480737, "max_line_length": 503, "alphanum_fraction": 0.4861267433, "converted": true, "num_tokens": 4242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10087862273005653, "lm_q2_score": 0.11596070908851643, "lm_q1q2_score": 0.011697956623650287}}
{"text": "# A Network-based Multimodal Infrastructure for Accelerating Medicine Partnership in Parkinson\u2019s Disease Data Repurposing\n---\n\n**[Feixiong Cheng, Ph.D. (Communicating PI)](https://www.lerner.ccf.org/gmi/cheng/)**  \nAssistant Professor of Molecular Medicine  \nCleveland Clinic Lerner College of Medicine of Case Western Reserve University  \nEmail: <a href=\"mailto:chengf@ccf.org\">chengf@ccf.org</a>\n\n**[Ignacio Mata, Ph.D. (MPI)](https://www.lerner.ccf.org/gmi/mata/)**  \nAssistant Professor of Molecular Medicine  \nCleveland Clinic Lerner College of Medicine of Case Western Reserve University  \nEmail: <a href=\"mailto:matai@ccf.org\">matai@ccf.org</a>\n\n### Table of Contents\n1. [Introduction](#a1)\n2. [Code Base](#a2)\n    1. [Framework - Genome/Transcriptome Data Reticulotyping](#a2_1)\n    2. [Framework - Deep Learning-based Graph Embedding](#a2_2)\n        1. [Random Surfing with Restart](#a2_2_1)\n        2. [Positive Pointwise Mutual Information](#a2_2_2)\n        3. [Stacked Denoising Autoencoder](#a2_2_3)\n    3. [Framework - Network Proximity](#a2_3)\n        1. [Human Protein Interactome](#a2_3_1)\n        2. [Disease Gene Network Modularity](#a2_3_2)\n        3. [Network Proximity](#a2_3_3)\n        4. [Random Sampling and Z-Score](#a2_3_4)\n        5. [Network Proximity-based Drug Screening](#a2_3_5)\n3. [Example Workflow](#a3)\n    1. [Example - Genome/Transcriptome Data Reticulotyping](#a3_1)\n    3. [Example - Network Proximity](#a3_3)\n\n## Introduction\n\nParkinson's disease (PD) is a complex neurological disorder with multiple pathophysiological processes, including a-synuclein aggregation, neuro-inflammation, mitochondrial dysfunction, neuronal vulnerability, and neural network alterations. It is estimated that more than 1 million people with PD live in the United States and approximately 60,000 Americans are diagnosed each year. There are no treatments that slow the neurodegenerative process for PD; furthermore, the predisposition to PD involves a complex, polygenic, and pleiotropic genetic architecture. Traditional reductionist paradigm overlooks the inherent complexity of PD and has often led to treatments that are inadequate or fraught with adverse effects. Existing data resources, including genomics, transcriptomics, interactomics (protein-protein interactions), and phenomics (clinical data), have not yet been fully utilized and integrated to explore the pathobiology of PD. Understanding PD from the point-of-view of how cellular systems and molecular interactome perturbations underlie the disease (termed disease module) is the essence of network medicine. Systematic identification and characterization of novel underlying pathogenesis and disease module as well as a reticulotype (i.e., a patient's unique disease module that allows an exploration of how molecular network perturbations affect phenotype), will serve as a foundation for identifying and validating prognostic, progression, predictive biomarkers, and drug targets in PD. Integration of the genome, transcriptome, proteome, and the human interactome are essential for such identification. Given our preliminary results, we posit that network-based, integrative multi-omics analyses of large-scale existing PD cohorts enables a more complete mechanistic understanding of pathogenesis (termed 'reticulotyping') and the rapid development of targeted therapeutic intervention for PD. \n\n\n\nThis notebook contains the three main frameworks for this project. These frameworks are highly self-contained, and can be migrated on the cloud server with minimum effort and integrated in other workflows.\nFor example usages, skip to [Example Workflow](#a3).\n\n## Code Base\n\nThis part of the notebook contains the implementation of the procedures shown in the workflow figure. The codes are grouped into three frameworks. These frameworks can be deployed on the cloud platform and integrated in user-defined workflows.\n\nIn all, these frameworks require the following Python 3.7+ packages:\n* numpy\n* scipy\n* PyTorch\n* networkx\n* matplotlib\n\nSee [Example Workflow](#a3) for usages of these frameworks.\n\n### Framework - Genome/Transcriptome Data Reticulotyping\n\nThis section implements the methods described in [A genome-wide positioning systems network algorithm for in silico drug repurposing](https://www.ncbi.nlm.nih.gov/pubmed/31375661) by Cheng F *et al*. Nat Commun. 2019 Aug 2;10(1):3476.\n\nThe following packages are used:\n\n\n```python\nimport time\nimport random\nimport pickle\nimport numpy as np\nfrom math import sqrt\nfrom scipy.stats import hypergeom\nimport networkx as nx\nimport matplotlib.pyplot as plt\n```\n\nWe define a module as a subgraph within the human protein\u2013protein interactome and calculate the score of the module M as\n\n\\begin{align}\nZ_m = \\frac{\\sum\\limits _{i\\in M} (S(i) - \\mu)}{\\sqrt{m}} \\tag{1}\n\\end{align}\n\nwhere $m$ is the number of genes in module M, $s(i)$ is the network-predicted score for gene i and $\\mu$ is the average score over the whole gene set. We denote $\\Gamma_{M}$ as the set of genes that interact with module $M$ in the human protein\u2013protein interactome. Specifically, we first randomly select a protein (gene) as a \u201cseed protein.\u201d For each gene $i \\in \\Gamma_{M}$, we next calculate its connectivity significance in the human protein\u2013protein interactome as\n\n\\begin{align*}\nP(i) = \\sum_{k = k_m}^{\\min(k_i, m)}\\frac{\\left(\\begin{array}{c}\nm \\\\\nk\n\\end{array}\\right) \\left(\\begin{array}{c}\nN-m \\\\\nk_i-k\n\\end{array}\\right)}{\\left(\\begin{array}{c}\nN \\\\\nk_i\n\\end{array}\\right)} \\tag{2}\n\\end{align*}\n\nwhere $k_i$ is the degree of gene i, $m$ is the number of genes in the module, $k_m$ is the number of module genes that link to gene i, and $N$ is the total number of genes in the gene set. For each seed $i \\in \\Gamma_{M}$, we further calculate the expanded module score if gene i is added to the module as\n\n\\begin{align*}\nZ_{m+1}(i) = \\frac{(s(i) - \\mu) + \\sum_{i\\in M}(s(i)- \\mu)}{\\sqrt{m+1}} \\tag{3}\n\\end{align*}\n\nThe candidate gene i will be added to the module to build a new module by satisfying two criteria: (a) $P(i)$ in Eqn (2) is less than 0.05 (connectivity significance), and (b) $Z_{m+1}(i) > Z_m$. We repeat steps (a) and (b) until no more genes can be added by these criteria (Above steps are implemented in functions 'P_Cnnectivity' and 'SingleModule'). We built multiple enough modules by randomly selecting each seed gene in the human interactome (See function 'ModuleGeneration').\n\nFinally, we assembled the top (e.g., top 1%) ranked modules with the highest module scores and defined the largest connected component by removing the isolated genes to define the final disease module (see function 'GPSnet').\n\n\n```python\ndef P_Connectivity(k_m, k_i, n, N_NODES): # connectivity significance p value\n    p_rv = hypergeom(N_NODES, n, k_i)\n    return p_rv.cdf(min(k_i, n)) - p_rv.cdf(k_m - 1)\n\n\ndef SingleModule(idx, NODE_ID, P_CUTOFF, NODE_SCORE, NODE_NEIGHBOR, NODE_DEGREE, ID2POS):\n    MEAN_NODE_SCORE = NODE_SCORE.mean()\n    N_NODES = len(NODE_ID)\n    last_added_pos = random.randrange(0, N_NODES)\n    module_pos = [last_added_pos]  # [pos1, pos2, ...]\n    module_id = {NODE_ID[last_added_pos]}  # {id1, id2, ...}\n    score_sum = 0\n    neighbors_id = set()\n    \n    while True:\n        print(\".\", end=\"\")\n        # -------- compute current module score and neighbors -------- #\n        module_size = len(module_id)\n        score_sum += NODE_SCORE[last_added_pos]\n        module_score = (score_sum - module_size * MEAN_NODE_SCORE) / sqrt(module_size)\n\n        neighbors_id |= NODE_NEIGHBOR[NODE_ID[last_added_pos]]\n        neighbors_id -= module_id\n        if not len(neighbors_id):\n            break\n        neighbors_pos = np.array([ID2POS[id] for id in sorted(neighbors_id)])\n\n        # -------- select nodes that could increase module score -------- #\n        qualified_pos = neighbors_pos[module_score * sqrt(module_size) + NODE_SCORE[neighbors_pos] > module_score * sqrt(module_size + 1) + MEAN_NODE_SCORE]\n        if not len(qualified_pos):\n            break\n\n        # -------- select nodes whose connectivity significance p-value <= P_CUTOFF -------- #\n        k_m_ls = [len(NODE_NEIGHBOR[NODE_ID[pos]] & module_id) for pos in qualified_pos]\n        k_i_ls = NODE_DEGREE[qualified_pos]\n        qualified_csp_pos = [pos for pos, k_m, k_i in zip(qualified_pos, k_m_ls, k_i_ls) if P_Connectivity(k_m, k_i, module_size, N_NODES) <= P_CUTOFF]\n        if not len(qualified_csp_pos):\n            break\n\n        # -------- randomly add one node to the module-------- #\n        last_added_pos = random.choice(qualified_csp_pos)\n        module_id.add(NODE_ID[last_added_pos])\n        module_pos.append(last_added_pos)\n\n    print(\"\")\n    module_score = (NODE_SCORE[np.array(module_pos)].sum() - len(module_id) * MEAN_NODE_SCORE) / sqrt(len(module_id))\n    return module_id, module_score\n\n\ndef ModuleGeneration(dir_node_score, dir_nn, P_CUTOFF, N_EXPER):\n    with open(dir_node_score) as fi:\n        next(fi)\n        NODE_ID = []\n        NODE_SCORE = []\n        for line in fi:\n            id, score = line.strip(\"\\n\").split(\"\\t\")\n            NODE_ID.append(id)\n            NODE_SCORE.append(score)\n\n    NODE_ID = np.array(NODE_ID, dtype=np.str)  # Array: pos -> id\n    NODE_SCORE = np.array(NODE_SCORE, dtype=np.float)  # Array: pos -> score\n    \n    with open(dir_nn, 'rb') as fi:\n        NODE_NEIGHBOR = pickle.load(fi)  # ['p1':{n1, n2, ...}, ...]\n\n        \n    NODE_DEGREE = np.array([len(NODE_NEIGHBOR[node]) for node in NODE_ID])  # Array: pos -> degree\n    \n    N_NODES = len(NODE_ID)\n    MEAN_NODE_SCORE = NODE_SCORE.mean()\n    ID2POS = {j: i for i, j in enumerate(NODE_ID)}  # {id -> pos}\n    \n    module_nid = {}\n    module_ns = {}\n    for idx in range(0, (0 + N_EXPER)):\n        start_time = time.time()\n        module, module_score = SingleModule(idx, NODE_ID, P_CUTOFF, NODE_SCORE, NODE_NEIGHBOR, NODE_DEGREE, ID2POS)\n        module_nid[idx] = module\n        module_ns[idx] = module_score\n        print(\"--- Experiment %s takes %.1f seconds ---\" % (idx, time.time() - start_time))\n    return module_nid, module_ns, NODE_NEIGHBOR\n\n\ndef GPSnet(dir_node_score, dir_nn, dir_id2name, P_CUTOFF, N_EXPER, SCORE_CUT, FREQ_CUT):\n    # SCORE_CUT: top ranked modules, e.g. SCORE_CUT = 0.1, top 0.1 or 10% ranked modules\n    # FREQ_CUT: smallest acceptable node frequency, e.g. FREQ_CUT = 0.1, only include nodes which appears at least once in 10 selected modules\n    ID2NAME = dict([line.split() for line in open(dir_id2name).read().splitlines()])\n    module_nid, module_ns, NODE_NEIGHBOR = ModuleGeneration(dir_node_score, dir_nn, P_CUTOFF, N_EXPER)\n    module_score = np.concatenate([np.array(list(module_ns.keys()))[:,None], np.array(list(module_ns.values()))[:,None]], axis = 1)\n    sorted_module_score = module_score[module_score[:,1].argsort()[::-1]]\n    sel_module = sorted_module_score[0: int(N_EXPER * SCORE_CUT), 0]\n    assemble_module = set()\n    for mid in sel_module:\n        assemble_module |= module_nid[mid]\n        \n    node_freq = {}\n        \n    for nid in assemble_module:\n        for mid in sel_module:\n            if nid in module_nid[mid]:\n                if nid in node_freq:\n                    node_freq[nid] += 1\n                else:\n                    node_freq[nid] = 1\n\n    nA_net, nB_net = zip(*[(ID2NAME[nid], ID2NAME[mid]) for nid in assemble_module for mid in NODE_NEIGHBOR[nid]&assemble_module if len(NODE_NEIGHBOR[nid] & assemble_module) > 0 and node_freq[nid] > int(FREQ_CUT * len(sel_module))])\n\n    G = nx.Graph()\n    G.add_edges_from(list(zip(nA_net, nB_net)))\n    nG_LCC = max(nx.connected_components(G), key=len)\n    net_LCC = G.subgraph(nG_LCC)\n    return module_score, net_LCC\n```\n\n### Framework - Deep Learning-based Graph Embedding\n\n\n\nThis section implements the methods described in [Target identification among known drugs by deep learning from heterogeneous networks](https://pubs.rsc.org/en/content/articlehtml/2020/sc/c9sc04336e) by Cheng F *et al*. Chem. Sci., 2020, 11, 1775-1797\n\nThe following packages are used:\n\n\n```python\nimport numpy as np\nimport torch\nfrom torch.utils.data import TensorDataset, DataLoader\n```\n\n#### <a name=\"a2_2_1\"></a> Random Surfing with Restart\n\nTransition matrix $A$ captures the transition probabilities between different nodes. We consider a random surfing model with restart, which introduces a pre-defined restart probability at the initial node for every iteration. It takes both local and global topological connectivity patterns within the network into consideration to fully exploit the underlying direct or indirect relations between nodes. Thus, at each time, there is a probability $\u03b1$ that the random surfing procedure will continue, and a probability $1-\u03b1$ that it will return to the original node and restart the procedure. In vectorized form, the \nprobabilistic co-occurrence after *k* steps is:\n\n\\begin{align*}\nP_k = \\alpha P_{k-1}A+(1-\\alpha)P_0 \\tag{4}\n\\end{align*}\n\nwhere $P_0$ is an identity matrix the same shape of $A$ indicating all nodes are at their original place before any movement.\nThe final probabilistic co-occurrence representation takes the number of steps into considerations, as large steps should have less weight (for proof, see original paper):\n\n\\begin{align*}\nr=\\sum_{k=1}^{K}P_k \\tag{5}\n\\end{align*}\n\n\n```python\ndef RandomSurfing(adj, steps=3, alpha=0.98):\n    A = adj - np.diag(np.diag(adj))  # zeroing diagonal\n    A = A / A.sum(axis=1, keepdims=1)  # row-wise scaling\n    P0 = np.eye(len(A))\n    P = P0\n    M = np.zeros_like(A)\n    for _ in range(steps):\n        P = alpha * P @ A + (1 - alpha) * P0\n        M += P\n    return M\n```\n\n#### <a name=\"a2_2_2\"></a> Positive Pointwise Mutual Information\nWe calculate the positive pointwise mutual information (PPMI) matrix using the probabilistic co-occurrence representation. The PPMI matrix can be viewed as a matrix factorization method which factorizes a co-occurrence representation to yield network representations.\n\n\\begin{align*}\nPPMI_{ij}=\\max(0, log\\frac{r_{ij} \\times \\sum r_{\\cdot\\cdot}}{\\sum r_{i \\cdot} \\times \\sum r_{\\cdot j}}) \\tag{6}\n\\end{align*}\n\n\n```python\ndef PPMI(m):\n    A = m - np.diag(np.diag(m))  # zeroing diagonal\n    A = A / A.sum(axis=1, keepdims=1)  # row-wise scaling\n    row_sum = A.sum(axis=1, keepdims=1)\n    col_sum = A.sum(axis=0, keepdims=1)\n    D = col_sum.sum()\n    ppmi = np.maximum(np.log(D * A / row_sum / col_sum), 0)\n    ppmi[ppmi == np.inf] = 0\n    return ppmi\n```\n\n#### <a name=\"a2_2_3\"></a> Stacked Denoising Autoencoder\nTo investigate the construction of high quality low-dimensional vector representations for nodes from the PPMI matrix that conveys essential structural information of the network, we use a stacked denoising autoencoder (SDAE), which is a popular model used in deep learning, to generate compressed, low-dimensional vectors from the original high-dimensional node vectors. This process essentially performs dimension reduction that maps data from a high dimensional space into a lower dimensional space. Denoising autoencoders partially corrupt the input data before taking the training step, adding noise helps a SDAE to learn features that are robust to partial corruption of input data. Each hidden layer in the SDAE is pre-trained by a denoising autoencoder, whose hidden layer output becomes the input of the next dimenion reduction hidden layer of the SDAE.\n\n\n```python\nclass DAE(object):\n    ACTIVATION = {\n        \"SIGMOID\": torch.nn.Sigmoid,\n        \"TANH\"   : torch.nn.Tanh,\n        \"RELU\"   : torch.nn.ReLU,\n    }\n    OPTIMIZER = {\n        \"SGD\"     : torch.optim.SGD,\n        \"ADAM\"    : torch.optim.Adam,\n        \"ADAGRAD\" : torch.optim.Adagrad,\n        \"ADADELTA\": torch.optim.Adadelta,\n        \"RMSPROP\" : torch.optim.RMSprop,\n    }\n\n    def __init__(self, n_in, n_hidden, nonlinear=\"RELU\", noise=0.05, device=None,\n                 solver=\"ADAGRAD\", lr=1e-3, decay=1e-5, epoch=10, batch_size=64):\n        super().__init__()\n        self.n_in = n_in\n        self.n_hidden = n_hidden\n        self.noise = noise\n        self.device = torch.device(\"cpu\") if device is None else device\n        self.model = torch.nn.Sequential(\n            torch.nn.Linear(n_in, n_hidden),\n            self.ACTIVATION[nonlinear](),\n            torch.nn.Linear(n_hidden, n_in)\n        )\n        self.model.to(self.device)\n        self.lr = lr\n        self.decay = decay\n        self.optimizer = self.OPTIMIZER[solver](params=self.model.parameters(), lr=lr, weight_decay=decay)\n        self.epoch = epoch\n        self.batch_size = batch_size\n        self.loss_fn = torch.nn.MSELoss()\n\n    def fit(self, x: torch.Tensor):\n        self.model.train()\n        dataloader = DataLoader(TensorDataset(x), batch_size=self.batch_size, shuffle=True)\n        for epoch in range(1, self.epoch + 1):\n            total_loss = 0\n            for batch, (data,) in enumerate(dataloader):\n                data_ = data.to(self.device)\n                if self.noise:\n                    data_ += self.noise * torch.randn(*data.shape).to(self.device)\n                h = self.model(data_)\n                loss = self.loss_fn(h, data_)\n                self.optimizer.zero_grad()\n                loss.backward()\n                self.optimizer.step()\n                total_loss += loss.item() * data.size(0)\n            print(\"EPOCH: %s  MSE: %.6f\" % (epoch, total_loss / x.shape[0]))\n        return self\n\n    def transform(self, x: torch.Tensor):\n        self.model.eval()\n        dataloader = DataLoader(TensorDataset(x), batch_size=self.batch_size, shuffle=False)\n        encoded = torch.empty(x.shape[0], self.n_hidden)\n        with torch.no_grad():\n            for batch, (data,) in enumerate(dataloader):\n                data_ = data.to(self.device)\n                start = self.batch_size * batch\n                end = start + data.size(0)\n                encoded[start:end] = self.model[1](self.model[0](data_)).to(device=\"cpu\").detach()\n        return encoded\n\n    def fit_transform(self, x: torch.Tensor):\n        return self.fit(x).transform(x)\n\n    def evaluate(self, x: torch.Tensor):\n        self.model.eval()\n        dataloader = DataLoader(TensorDataset(x), batch_size=self.batch_size, shuffle=False)\n        decoded = torch.empty(*x.shape)\n        with torch.no_grad():\n            for batch, (data,) in enumerate(dataloader):\n                data_ = data.to(self.device)\n                start = self.batch_size * batch\n                end = start + data.size(0)\n                decoded[start:end] = self.model(data_).to(device=\"cpu\").detach()\n        print(\"Evaluation MSE: %.6f\" % self.loss_fn(decoded, x).item())\n        return decoded\n\n\ndef SDAE(mat, dimensions=(512, 256, 128), *args, **kwargs):\n    mat = torch.from_numpy(mat).to(torch.float)\n    for n_in, n_hidden in zip([mat.shape[1], *dimensions], dimensions):\n        print(\"Reducing from %s to %s dimensions\" % (n_in, n_hidden))\n        model = DAE(n_in, n_hidden, *args, **kwargs)\n        model.fit(mat)\n        model.evaluate(mat)\n        mat = model.transform(mat)\n    return mat.numpy()\n```\n\n### Framework - Network Proximity\n\nThis section implements the methods described in  \n[Network-based prediction of drug combinations](https://www.nature.com/articles/s41467-019-09186-x) by Cheng F, Kov\u00e1cs IA, Barab\u00e1si AL. Nature Communications (2019) 10:1197  \n[Network-based approach to prediction and population-based validation of in silico drug repurposing](https://www.nature.com/articles/s41467-018-05116-5). Cheng F *et al*. Nature Communications (2018) 9:2691  \n[A genome-wide positioning systems network algorithm for in silico drug repurposing](https://www.nature.com/articles/s41467-019-10744-6). Cheng F *et al*. Nature Communications (2019) 10:3476\n\nThe following packages are used:\n\n\n```python\nimport random\nimport numpy as np\nimport numpy.ma as ma\nimport networkx as nx\nimport matplotlib.pyplot as plt\n```\n\n#### <a name=\"a2_3_1\"></a> Human Protein Interactome\nWe first need to load the human protein interactome from the adjacency file `adj`. Each row in the `adj` file is space-separated gene ids, with the first one being the source, and all others being the targets. Self links are removed.\n\nSee **[My Personal Mutanome](https://mutanome.lerner.ccf.org/)** for more details of the human protein interactome.\n\n\n```python\ndef Interactome(adj):\n    G = nx.read_adjlist(adj)\n    G.remove_edges_from(nx.selfloop_edges(G))\n    return G\n```\n\n#### <a name=\"a2_3_2\"></a> Disease Gene Network Modularity\nAfter disease module (a list of disease-associated/causing genes) or any gene module is obtained (`mod`), we can check whether these genes are connected. See later section for the significance test of the modularity.\n\n\n```python\ndef CC(interactome, mod):\n    return sorted(nx.connected_components(interactome.subgraph(mod)), key=len, reverse=True)\n\n\ndef LCC(interactome, mod):\n    return len(CC(interactome, mod)[0])\n\n\ndef PlotNet(net, labels, dtn):\n    targetable = set()\n    for d in dtn:\n        targetable |= set(dtn[d])\n    plt.figure(figsize=(10, 10))\n    nx.draw_kamada_kawai(\n        net,\n        node_color=[\"#85dcffc0\" if n in targetable else \"#96dd49c0\" for n in net.nodes()],\n        node_size=1000,\n        width=3,\n        edge_color=\"#bcc3cb80\",\n        labels=labels)\n    plt.show()\n    plt.close()\n```\n\n#### <a name=\"a2_3_3\"></a> Network Proximity\nHere we show the implementation of four metrics, distance (asymmetrical), shortest, closest (default), and kernel for the network proximity of two modules `mod1` and `mod2`. To speed up the procedure, we can instead precalculate all the shortest distances in the interactome and save them in a numpy array file.\n\n\\begin{align}\nDistance - d_{YT} &= \\frac{1}{||T||}\\sum_{t \\in T}\\min_{y \\in Y}d(y,t) \\tag{7} \\\\\nShortest - d^S_{YT} &= \\frac{1}{||Y||\\times||T||}\\sum_{y \\in Y, t \\in T}d(y,t) \\tag{8} \\\\\nClosest - d^C_{YT} &= \\frac{1}{||Y||+||T||}(\\sum_{y \\in Y}\\min_{t \\in T}d(y,t)+\\sum_{t \\in T}\\min_{y \\in Y}d(y,t)) \\tag{9} \\\\\nKernel - d^K_{YT} &= \\frac{-1}{||Y||+||T||}(\\sum_{y \\in Y}\\log\\sum_{t \\in T}\\frac{e^{-d(y,t)-1}}{||T||}+\\sum_{t \\in T}\\log\\sum_{y \\in Y}\\frac{e^{-d(y,t)-1}}{||Y||}) \\tag{10} \\\\\n\\end{align}\n\n\n```python\ndef Proximity(interactome, mod1, mod2, method=\"CLOSEST\"):\n    SD = np.zeros((len(mod1), len(mod2)))\n    for row, source in enumerate(mod1):\n        for col, target in enumerate(mod2):\n            try:\n                SD[row, col] = nx.shortest_path_length(interactome, source, target)\n            except nx.NetworkXNoPath:\n                SD[row, col] = 9999\n    SD = ma.masked_values(SD, 9999)\n    if method == \"DISTANCE\":\n        return SD.min(1).mean()\n    if method == \"SHORTEST\":\n        return SD.mean()\n    if method == \"CLOSEST\":\n        row_min = SD.min(1)\n        col_min = SD.min(0)\n        return (row_min.sum() + col_min.sum()) / sum(SD.shape)\n    if method == \"KERNEL\":\n        exp = ma.exp(-SD)\n        alb = ma.log(exp.sum(1))\n        bla = ma.log(exp.sum(0))\n        nA = alb.count()\n        nB = bla.count()\n        return (nA * np.log(nB) + nB * np.log(nA) - alb.sum() - bla.sum()) / (nA + nB) + 1\n```\n\n#### <a name=\"a2_3_4\"></a> Random Sampling and Z-Score\nWe use permutation test to test the significance of the LCC (`LCC_Z`) or the proximity (`Proximity_Z`). By default the random experiments are performed `repeat=1000` times.\n\nThe `Plot` function plots the lcc and the proximity analyses results.\n\n\n```python\ndef SampleNetwork(interactome, n):\n    nodes = interactome.nodes()\n    while True:\n        yield random.sample(nodes, n)\n\n\ndef Z_Score(real, background, right=False):\n    m = background.mean()\n    s = background.std(ddof=1)\n    z = (real - m) / s\n    p = np.mean(background < real)\n    if right:\n        p = 1 - p\n    return z, p\n\n\ndef LCC_Z(interactome, mod, repeat=1000):\n    sampler = SampleNetwork(interactome, len(mod))\n    lcc = LCC(interactome, mod)\n    background = []\n    for _ in range(repeat):\n        background.append(LCC(interactome, next(sampler)))\n    z, p = Z_Score(lcc, np.array(background), right=True)\n    return {\"TYPE\": \"LCC\", \"L\": lcc, \"Z\": z, \"P\": p, \"B\": background}\n\n\ndef Proximity_Z(interactome, mod1, mod2, method=\"CLOSEST\", repeat=1000):\n    sampler1 = SampleNetwork(interactome, len(mod1))\n    sampler2 = SampleNetwork(interactome, len(mod2))\n    proximity = Proximity(interactome, mod1, mod2, method=method)\n    background = []\n    for _ in range(repeat*2):\n        v = Proximity(interactome, next(sampler1), next(sampler2), method=method)\n        if not ma.is_masked(v):\n            background.append(v)\n        if len(background) == repeat:\n            break\n    z, p = Z_Score(proximity, np.array(background), right=False)\n    return {\"TYPE\": \"PROXIMITY\", \"D\": proximity, \"Z\": z, \"P\": p, \"B\": background}\n\n\ndef Plot(result, pathOut=None, bins=20, colors=(\"#c8c8c8\", \"#ff0000\"), labelX=0.7):\n    if result[\"TYPE\"] == \"PROXIMITY\":\n        x = result[\"D\"]\n        x_text = \"$Z$ = %.2f\" % result[\"Z\"]\n        x_label = \"Proximity\"\n        y_label = \"Frequency\"\n    elif result[\"TYPE\"] == \"LCC\":\n        x = result[\"L\"]\n        x_text = \"$S$ = %s\" % x\n        x_label = \"Observed module size ($S$)\"\n        y_label = \"Frequency of $S$\"\n    else:\n        raise Exception(\"Unknown result type\")\n    p_text = (\"$P$ = %.3f\" % result[\"P\"]) if result[\"P\"] >= 0.001 else \"$P$ < 0.001\"\n    fig = plt.figure()\n    ax = fig.add_subplot(111)\n    plt.hist(result[\"B\"], bins=bins, color=colors[0], label=\"Random\", weights=np.ones(len(result[\"B\"])) / len(result[\"B\"]))\n    plt.axvline(x=x, c=colors[1], ymax=0.5)\n    plt.text(labelX, 0.8, x_text, fontsize=18, transform=ax.transAxes)\n    plt.text(labelX, 0.7, p_text, fontsize=18, transform=ax.transAxes)\n    plt.legend(fontsize=18, frameon=False, markerscale=1.5)\n    plt.tick_params(labelsize=18)\n    plt.xlabel(x_label, fontsize=18)\n    plt.ylabel(y_label, fontsize=18)\n    plt.subplots_adjust(left=0.18, bottom=0.15, right=0.98, top=0.98)\n    if pathOut is not None:\n        plt.savefig(pathOut, dpi=300)\n    else:\n        plt.show()\n    plt.close()\n```\n\n#### <a name=\"a2_3_5\"></a> Network Proximity-based Drug Screening\nTo screen the drugs for a disease module, we need to first load the drug target network (`DrugTargetNetwork`) from a tab-separated file containing drugs (column 1) and targets (column 2). Then, the proximity and its significance of each drug and the disease module is computed (`DrugScreen`).\n\nSee **[AlzGPS](https://alzgps.lerner.ccf.org/)** for more details of the drug target network.\n\n\n```python\ndef DrugTargetNetwork(filename):\n    dtn = {}\n    with open(filename) as fi:\n        for line in fi:\n            drug, target = line.strip(\"\\n\").split(\"\\t\")\n            dtn.setdefault(drug, []).append(target)\n    return dtn\n\n\ndef DrugScreen(interactome, dtn, mod, method=\"CLOSEST\", repeat=1000):\n    result = []\n    for drug, targets in dtn.items():\n        targets = [t for t in targets if t in interactome.nodes()]\n        if targets:\n            out = Proximity_Z(interactome, mod, targets, method=method, repeat=repeat)\n            result.append({\"DRUG\": drug, **out})\n    result.sort(key=lambda x: x[\"Z\"])\n    return result\n```\n\n## Example Workflow\n\nThis part of the notebook show the example usages of the frameworks. All packages/functions should be loaded/defined at this point and are ready to use.\n\n### Example - Genome/Transcriptome Data Reticulotyping\n\nIn this subsection, we will use the smoothing gene score generated by random walk with restart (RWR) as input.\nIn this example, we build 10 raw modules, and assemble the top 2% ranked modules to form the final disease module.\n\n\n```python\nmodule_score, net_LCC = GPSnet(\"data/node_score.txt\", \"data/nnG.p\", \"data/ID2Symbol.txt\", 5e-2, 10, 0.2, 0.5)\n```\n\n    .........................................................................................\n    --- Experiment 0 takes 5.0 seconds ---\n    ................................................................................................................\n    --- Experiment 1 takes 10.1 seconds ---\n    ...................................................................................................\n    --- Experiment 2 takes 4.0 seconds ---\n    .......................................................\n    --- Experiment 3 takes 1.9 seconds ---\n    .............................................\n    --- Experiment 4 takes 1.6 seconds ---\n    ............................\n    --- Experiment 5 takes 0.3 seconds ---\n    .................................................................................................\n    --- Experiment 6 takes 3.8 seconds ---\n    .................................................................................\n    --- Experiment 7 takes 3.0 seconds ---\n    ....................\n    --- Experiment 8 takes 0.1 seconds ---\n    .................................................................................................\n    --- Experiment 9 takes 4.8 seconds ---\n\n\nLet's visualize the disease module.\n\n\n```python\nplt.figure(figsize=(10, 10))\nnx.draw_kamada_kawai(\n    net_LCC,\n    node_color=\"#96dd49c0\",\n    node_size=500,\n    width=2,\n    edge_color=\"#bcc3cb80\",\n    labels={i:i for i in net_LCC.nodes()})\nplt.show()\nplt.close()\n```\n\n### Example - Network Proximity\nIn this section, we will use the disease gene list downloaded from Open Targets as an example to show the usages of the Network Proximity framework.\n\nSeveral things to prepare first:\n* load human protein interactome\n* load drug-target network\n* load gene id to symbol mapping\n\n\n```python\nrandom.seed(1024)\nInt = Interactome(\"data/human_interactome.adj\")\nDtn = DrugTargetNetwork(\"data/drug_target_network.txt\")\nID2Symbol = dict([line.split() for line in open(\"data/ID2Symbol.txt\").read().splitlines()])\n```\n\nThe disease associated gene list for PD can be downloaded from https://www.targetvalidation.org/disease/EFO_0002508/associations. Genes with a score of 1 are used for the downstream analyses.\n\n\n```python\nPD_genes = open(\"data/PD.txt\").read().splitlines()\nPD_genes = [g for g in PD_genes if g in Int.nodes()]\nprint(\"Number of genes:\", len(PD_genes))\n```\n\n    Number of genes: 104\n\n\nWe look at whether these 104 genes form a significantly connected module in the protein interactome. The result show that 52 genes are connected in the largest connected component of theses genes, with a *P* value < 0.05.\n\n\n```python\nresult = LCC_Z(Int, PD_genes)\nPlot(result)\n```\n\nLet's visualize the LCC network. Blue indicates these nodes can be targeted by at least one drug from the drug target network.\n\n\n```python\nlcc = CC(Int, PD_genes)[0]\nnet = Int.subgraph(lcc)\nlabels = {n: ID2Symbol[n] for n in net.nodes()}\nPlotNet(net, labels, Dtn)\n```\n\nNext we want to prioritize the drugs for the PD module to reveal potentially relavent drugs. There are more than 2,900 drugs in our drug target network, which takes some time to run completely. As an example, we will only test the first 20 drugs with permutation test of 100 repeats.\n\n\n```python\ndtn = {d: Dtn[d] for d in sorted(Dtn)[:20]}\nresult = DrugScreen(Int, dtn, PD_genes, repeat=100)\n\ndrugbank2name = dict([line.strip(\"\\n\").split(\"\\t\") for line in open(\"data/drug_name.txt\").read().splitlines()])\n\nfor r in result:\n    print(drugbank2name[r[\"DRUG\"]].ljust(30, \" \"), \" D: %.1f  Z: %s%.3f  P: %.3f\" % (r[\"D\"], (\" \", \"\")[int(r[\"Z\"] < 0)], r[\"Z\"], r[\"P\"]))\n```\n\n    Cetuximab                       D: 2.0  Z: -2.472  P: 0.000\n    Urokinase                       D: 2.1  Z: -1.264  P: 0.080\n    Erythropoietin                  D: 2.4  Z: -0.773  P: 0.340\n    Darbepoetin alfa                D: 2.4  Z: -0.635  P: 0.370\n    Sargramostim                    D: 2.2  Z: -0.631  P: 0.230\n    Denileukin diftitox             D: 2.3  Z: -0.465  P: 0.300\n    Interferon alfa-n3              D: 2.4  Z: -0.405  P: 0.500\n    Peginterferon alfa-2a           D: 2.4  Z: -0.375  P: 0.500\n    Interferon alfa-n1              D: 2.4  Z: -0.318  P: 0.560\n    Reteplase                       D: 2.3  Z: -0.172  P: 0.460\n    Alteplase                       D: 2.3  Z: -0.160  P: 0.460\n    Pegfilgrastim                   D: 2.4  Z: -0.150  P: 0.620\n    Secretin human                  D: 2.8  Z:  0.130  P: 0.510\n    Etanercept                      D: 2.1  Z:  0.134  P: 0.540\n    Salmon Calcitonin               D: 2.8  Z:  0.336  P: 0.620\n    Lepirudin                       D: 2.9  Z:  0.391  P: 0.630\n    Bivalirudin                     D: 2.9  Z:  0.535  P: 0.700\n    Goserelin                       D: 2.8  Z:  1.109  P: 0.840\n    Leuprolide                      D: 3.3  Z:  1.736  P: 0.930\n    Sermorelin                      D: 3.8  Z:  2.390  P: 0.980\n\n\nCetuximab and Urokinase achieved small *P* values and *Z* scores. Literature search showed potential relations between these drugs and PD: https://ascopubs.org/doi/abs/10.1200/JCO.2019.37.15_suppl.3595, https://www.ncbi.nlm.nih.gov/pubmed/32035284\n\nLet's take a closer look at the proximity between Urokinase and the PD module. This time we repeat the permutation test 1000 times. Note that the values may change slightly due to different random state. We then plot the proximity result.\n\n\n```python\nresult = Proximity_Z(Int, PD_genes, dtn[\"DB00013\"], repeat=1000)\nPlot(result, labelX=0.05)\n```\n", "meta": {"hexsha": "55a0de92f90f407c3addabbde7f39d7e739d1c94", "size": 595353, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "PD.ipynb", "max_stars_repo_name": "ChengF-Lab/PDGPS", "max_stars_repo_head_hexsha": "a656c183c2a6b9924419e2a1e6a860fa9d109ffd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-09T03:01:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-09T03:01:04.000Z", "max_issues_repo_path": "PD.ipynb", "max_issues_repo_name": "ChengF-Lab/PDGPS", "max_issues_repo_head_hexsha": "a656c183c2a6b9924419e2a1e6a860fa9d109ffd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PD.ipynb", "max_forks_repo_name": "ChengF-Lab/PDGPS", "max_forks_repo_head_hexsha": "a656c183c2a6b9924419e2a1e6a860fa9d109ffd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 557.9690721649, "max_line_length": 349880, "alphanum_fraction": 0.9347110034, "converted": true, "num_tokens": 8990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.027585282026933125, "lm_q1q2_score": 0.011549872328381873}}
{"text": "```python\nimport theme\ntheme.load_style()\n```\n\n\n\n\n<style>\n@import url('http://fonts.googleapis.com/css?family=Source+Code+Pro');\n@import url('http://fonts.googleapis.com/css?family=Vollkorn');\n@import url('http://fonts.googleapis.com/css?family=Arimo');\n@import url('http://fonts.googleapis.com/css?family=Arvo:400,700,400italic')\n\n#notebook li { /* More space between bullet points */\n    margin-top:0.8em;\n}\n\n/* draw border around running cells */\ndiv.cell.border-box-sizing.code_cell.running {\n    border: 3px solid #111;\n}\n\ndiv.cell.code_cell {\n    margin-top: 1em;\n    margin-left: auto;\n    margin-right: auto;\n    width: 800px;\n    border: 1px solid rgba(200, 200, 200, 0.8);\n    border-radius: 8px; /* rounded borders */\n}\n\ndiv.text_cell_render{\n    font-family: 'Arvo' sans-serif;\n    /* font-family: 'Arimo',verdana,arial,sans-serif; */\n    line-height: 130%;\n    font-size: 115%;\n    margin-left:0%;\n    margin-right:auto;\n}\n\n.text_cell_render h1 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 300;\n    font-style: bold;\n    font-size: 30pt;\n    line-height: 100%;\n    color:#c76c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h2 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 20pt;\n    line-height: 100%;\n    color:#c76c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h3 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 16pt;\n    line-height: 100%;\n    color:#d77c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h4 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 14pt;\n    font-style: italic;\n    line-height: 100%;\n    color:#d77c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h5 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 12pt;\n    color: #1d3b84;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n}\n\n.rendered_html code{\n    background-color: transparent;\n}\n\nul{\n    margin: 2em;\n}\n\nul li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.5em;\n}\n\nul li li{\n    padding-left: 0.2em;\n    margin-bottom: 0.2em;\n    margin-top: 0.2em;\n}\n\nol{\n    margin: 2em;\n}\n\nol li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.5em;\n}\n\nul li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.2em;\n}\n\na:link{\n    font-weight: bold;\n    color:#447adb;\n}\n\na:visited{\n    font-weight: bold;\n    color: #1d3b84;\n}\n\na:hover{\n    font-weight: bold;\n    color: #1d3b84;\n}\n\na:focus{\n    font-weight: bold;\n    color:#447adb;\n}\n\na:active{\n    font-weight: bold;\n    color:#447adb;\n}\n\n.rendered_html :link {\n    text-decoration: underline;\n}\n\n.rendered_html :hover {\n    text-decoration: none;\n}\n\n.rendered_html :visited {\n    text-decoration: none;\n}\n\n.rendered_html :focus {\n    text-decoration: none;\n}\n\n.rendered_html :active {\n    text-decoration: none;\n}\n\n.warning{\n    color: rgb( 240, 20, 20 )\n}\n\nhr {\n    color: #f3f3f3;\n    background-color: #f3f3f3;\n    height: 1px;\n}\n\nblockquote{\n    display:block;\n    background: #fcfcfc;\n    border-left: 5px solid #c76c0c;\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    width:680px;\n    padding: 10px 10px 10px 10px;\n}\n\nblockquote p {\n    margin-bottom: 0;\n    line-height: 125%;\n    font-size: 100%;\n}\n\ntable#mytable,\ntable#mytable td,\ntable#mytable tr\n{\n    border: none !important;\n}\n\ntable#mytable-1,\ntable#mytable-1 td,\ntable#mytable-1 tr\n{\n    border: none !important;\n    align: center;\n    cellspacing: 10;\n}\n\n.msg {\n    width: 90%;\n    margin-left: auto;\n    margin-right: auto;\n    margin-top: 10px;\n    margin-bottom: 10px;\n    padding: 14px 14px 14px 14px;\n    color: #c09853;\n    text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);\n    background-color: #fcf8e3;\n    border: 1px solid #fbeed5;\n    -webkit-border-radius: 4px;\n    -moz-border-radius: 4px;\n    border-radius: 4px;\n}\n\n.msg-heading {\n    color: inherit;\n}\n\n.msg .close {\n    position: relative;\n    top: -2px;\n    right: -21px;\n    line-height: 18px;\n}\n\n.msg-success {\n    color: #468847;\n    background-color: #dff0d8;\n    border-color: #d6e9c6;\n}\n\n.msg-danger,\n.msg-error {\n    color: #b94a48;\n    background-color: #f2dede;\n    border-color: #eed3d7;\n}\n\n.msg-info {\n    color: #3a87ad;\n    background-color: #d9edf7;\n    border-color: #bce8f1;\n}\n\n.boxed {\n    color: #b94a48;\n    background-color: #f2dede;\n    border-color: #eed3d7;\n    margin-left: auto;\n    margin-right: auto;\n    padding: 14px 14px 14px 14px;\n}\n\n.w-300 { width: 300px; }\n.w-400 { width: 400px; }\n.w-500 { width: 500px; }\n\n</style>\n\n\n\n\n# Introduction to Nonlinearity\n\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\"></a>\n\nThis lecture by Tim Fuller is licensed under the\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\">Creative Commons Attribution 4.0 International License</a>.  All code examples are also licensed under the [MIT license](http://opensource.org/licenses/MIT).\n\n\n```python\nimport numpy as np\nimport sympy as sp\n%pylab inline\nsp.init_printing(\"latex\")\n```\n\n    Populating the interactive namespace from numpy and matplotlib\n\n\nNonlinearity arises naturally in physical systems and can be modeled by finite elements in one (or more) of several ways.\n\n# Types of Nonlinearity\n\nThey types of nonlinearity encountered in static analysis can be classified as either material nonlinearity or geometric nonlinearity.\n\n- **Material Nonlinearity**: Nonlinear relationship between stress and strain\n- **Geometric Nonlinearity**: Nonlinear relationship between strain and stretch\n\nTo illustrate, consider the case of nonlinear elasticity, \n$$\n\\sigma = f\\left(\\epsilon\\right)\n$$ \n\nwhere $\\epsilon$ is a strain determined from the stretch $\\lambda=L/L_0$\n\n$$\n\\epsilon = g\\left(\\lambda\\right)\n$$\n\nHere, $f$ and $g$ are nonlinear functions.  Combined, we get\n\n$$\n\\sigma = f\\left(g\\left(\\lambda\\right)\\right)\n$$\n\nSuppose laboratory experiments show\n\n\n```python\nlam = np.linspace(.1, 5)\nsig = 38 * np.log(lam)\nplt.xlabel(r\"$\\lambda$\")\nplt.ylabel(r\"$\\sigma$\")\nplot(lam, sig);\n```\n\nThere are many ways we can express the $f$ and $g$ functions:\n\n$$\\begin{align}\n\\sigma &= f\\left(\\epsilon\\right) = 38 \\epsilon \\\\\n\\epsilon &= g\\left(\\lambda\\right) = \\ln{\\lambda}\n\\end{align}$$\n\nor\n\n$$\\begin{align}\n\\sigma &= f\\left(\\epsilon\\right) = 38 \\ln{\\left(\\epsilon + 1\\right)} \\\\\n\\epsilon &= g\\left(\\lambda\\right) = \\lambda - 1\n\\end{align}$$\n \nor \n\n$$\\begin{align}\n\\sigma &= f\\left(\\epsilon\\right) = 19 \\ln{\\left(2\\epsilon + 1\\right)} \\\\\n\\epsilon &= g\\left(\\lambda\\right) = \\frac{1}{2}\\left(\\lambda^2 - 1\\right)\n\\end{align}$$\n\netc.\n\nWhen combined, all of these choices give\n\n$$\n\\sigma = f\\left(g\\left(\\lambda\\right)\\right) = 38 \\ln{\\lambda}\n$$\n\nChoice 1 has a linear stress-strain relationship but a nonlinear strain-stretch relationship.  This is called **geometric nonlinearity**.\n\nChoice 2 has a nonlinear stress-strain relationship but a linear strain-stretch relationship.  This is called **material nonlinearity**.\n\nChoice 3 has both material and geometric nonlinearity.\n\nNo matter the choice of where to put nonlinearity, the end result of stress as a function of stretch should be the same.  Thus, the terms\nmaterial nonlinearity and geometric nonlinearity are somewhat arbitrary.  They *do* indicate differences in the FEM implementation, but not differences in the final answer.\n\n# Governing Equations of a 1D Elastic Solid\n\nIn solid mechanics, static equilibrium requires that\n\n$$\n\\frac{d\\sigma\\left[u\\right]}{dx} + b = 0\n$$\n\nwhere we have now that $\\sigma\\left[u\\right]$ is a (not necessarily linear) function of the displacement $u$ and and $b$ is a force per unit volume.\n\nThe weak form is derived in the usual way\n\n$$\\begin{align}\n&\\int_{\\Omega}\\left(\\frac{d\\sigma\\left[u\\right]}{dx} + b\\right)w\\,dx = 0, \\qquad \\forall w \\\\\n&\\int_{\\Omega}\\left(\\sigma\\left[u\\right]\\frac{dw}{dx} - bw\\right)\\,dx - \\sigma\\left[u\\right] w\\Bigg|_{\\partial \\Omega} = 0\n\\end{align}\n$$\n\nBecause stress is not necessarily linear in $u$, $u$ must be found iteratively.\n\n## Finite Element Equations\n\nThe finite element solution procedure for the nonlinear problem follows nearly identical that of the linear problem, namely, the isplacement field is approximated by interpolating polynomials possessing the property of compact support (shape functions):\n\n$$\nu = \\sum_{j=1}^n u_j N_j\n$$\n\nand the weighting functions as\n\n$$\nw = \\sum_{i}^n w_i N_i\n$$\n\nThe stress corresponding to a given displacement is found by computing the strain\n\n$$\n\\epsilon = \\frac{du}{dx} = \\sum_{j=1}^{n}u_j \\frac{dN_j}{dx}\n$$\n\nand then passing the strain to the material model $\\sigma = \\sigma\\left[\\epsilon\\right]$\n\nUpon substitution of the preceding equations in to the weak form we arrive at\n\n$$\n\\int_{\\Omega}\\left(\\sigma\\left[\\epsilon(u_j)\\right]\\frac{dN_i}{dx} - bN_i\\right)\\,dx - \\sigma\\left[\\epsilon(u_j)\\right] N_i\\Bigg|_{\\partial \\Omega} = 0, \\quad \\forall x_i \\text{ on } \\partial_\\sigma \\Omega\n$$\n$$\nu_i = u_i^*\\left(x_i\\right), \\quad \\forall x_i \\text{ on }\\partial_u\\Omega\n$$\n\nThis is a set of $n$ equations for the $n$ unknown nodal displacements $u_i$.  This set of equations is similar to those in the linear case, but because the the consititutive law relating stress and strain is not necessarily linear, it must be solved numerically.\n\n### Newton-Raphson Iteration\n\nOne method of solving the finite element equations is by Newton-Raphson iteration whereby we\n*linearize* the finite element equations about some guess for the $u_j$ and obtain successfully better approximations by iteration.  The linearization of $\\sigma$ about $u_j$ is\n\n$$\n\\sigma\\left[u_k\\right] \\approx \\sigma\\left[u_k^0\\right] + \\frac{d\\sigma}{du_k}du_k =  \\sigma\\left[u_k^0\\right] + \\frac{d\\sigma}{d\\epsilon}\\frac{d\\epsilon}{du_k}du_k\n$$\n\nrecalling that \n\n$$\n\\epsilon = \\sum_{k=1}^n u_k \\frac{dN_k}{dx} \\rightarrow \n\\frac{d\\epsilon}{du_j} = \\sum_{k=1}^n \\frac{du_k}{du_j} \\frac{dN_k}{dx}\n= \\sum_{k=1}^n \\delta_{kj} \\frac{dN_k}{dx} = \\frac{dN_j}{dx}\n$$\n\nwe can write\n\n$$\n\\int_{\\Omega}\\left(\\frac{d\\sigma}{d\\epsilon}\\frac{dN_i}{dx}\\frac{dN_j}{dx}\\,dx\\right) du_j +\n\\int_{\\Omega}\\sigma\\frac{dN_i}{dx}\\, dx -\n\\int_{\\Omega}bN_i\\,dx - \n\\sigma N_i\\Bigg|_{\\partial \\Omega} = 0\n$$\n\nor\n\n$$\nK_{ij}du_{j} = F_{i} - R_{i}\n$$\n\nwhere\n$$\nK_{ij} =\n\\int_{\\Omega}\\frac{d\\sigma}{d\\epsilon}\\frac{dN_i}{dx}\\frac{dN_j}{dx}\\,dx, \\quad\nR_{i} = \\int_{\\Omega}\\sigma\\frac{dN_i}{dx}\\, dx, \\quad\nF_{i} = \\int_{\\Omega}bN_i\\,dx + \\sigma N_i\\Bigg|_{\\partial \\Omega}\n$$\n\nThis expression is nearly identical to the linear case with the addition of two terms:\n\n- The strain dependent tangent material stiffness $\\frac{d\\sigma}{dx}$\n- An element \"residual\" $R$\n\n## Finite Element Algorithm\n\n **STEP 0** Initial guess for $u_j$ ($u_j=0$ is customary)  \n **STEP 1** Compute global $K_{ij}$, $R_i$, and $F_i$  \n **STEP 2** Enforce boundary conditions  \n **STEP 3** Solve $K_{ij}du_j = F_i - R_i$  \n **STEP 4** Set $u_j \\leftarrow u_j + du_j$  \n **STEP 5** If $\\lVert du_j\\rVert>$ TOL: GO TO STEP 1  \n **STEP 6** Write output, postprocess, etc.\n\n### Element Residual Calculation\n\nLet us investigate what additional information we will need to compute the element residual.  The element residual is given by\n\n$$\nr_k^e = \\int_{x_A}^{x_B}\\sigma \\frac{dN_k}{dx} dx\n$$\n\nUsing Gauss-Legendre quadrature\n\n$$\nr_k^e = \\int_{-1}^{1}\\sigma \\frac{1}{J} \\frac{dN_k}{d\\xi} Jd\\xi\n      = \\sum_{l=1}^{n}\\sigma\\frac{dN_k\\left(\\xi_l\\right)}{d\\xi} w_l\n$$\n\nComputing the residual will require computing the stress at a Gauss point and, implicitly, the strain since $\\sigma = f(\\epsilon)$.  Recall tha the strain is given by\n\n$$\n\\epsilon = \\sum_{i=1}^{N} u_i \\frac{dN_i}{dx} = \\sum_{i=1}^{N} \\frac{1}{J} u_i \\frac{dN_i}{d\\xi}\n$$\n\n#### Element Residual Update Algorithm\n\n**data**\n- Initial coordinates: $X$\n- Current displacement: $u$\n\n**external functions**\n- Material constitutive model: $f$\n \n**procedure**\n- Step 1: Update nodal coordinates\n  $$x_k=X_k+u_k$$\n\n- Step 2: Initialize the element residual\n  $$r_k^e=0$$\n\n- Step 3: Perform Gauss integration  \n  **for** $n$ from 1 to number of Gauss points **do**\n\n  * Step a: Compute shape function derivative wrt to $\\xi$ and the Jacobian\n    $$\\frac{dN_k}{d\\xi} = \\frac{dN_k\\left(\\xi_n\\right)}{d\\xi}$$\n    $$J = J\\left(x_k, \\xi_n\\right)$$\n \n  * Step b: Compute the strain at $\\xi_n$\n    $$\\epsilon = \\sum_k \\frac{1}{J} u_k \\frac{dN_k\\left(\\xi_n\\right)}{d\\xi}$$\n  \n  * Step c: Compute the stress at $\\xi_n$\n    $$\\sigma = f\\left(\\epsilon\\right)$$\n  \n  * Step d: Update element residual    \n    **for** $j$ from 1 to number of element nodes **do**\n      $$r^e_j = r^e_j + \\sigma\\frac{dN_j}{d\\xi} w_n$$\n    **end for**\n  \n  **end for**\n\n## Element Stiffness Calculation\n\nThe element stiffness calculation follows as before, except that instead of a constant element stiffness, the stiffness may change with deformation\n\n### Element Stiffness Update Algorithm\n\n**data**\n- Initial coordinates: $X$\n- Current displacement: $u$\n\n**external functions**\n- Material constitutive model: $f$\n\n**procedure**  \n* Step 1: Update nodal coordinates\n  $$x_k=X_k+u_k$$\n\n* Step 2: Initialize the element stiffness\n  $$k_{ij}^e=0$$\n\n* Step 3: Perform Gauss integration \n  **for** $n$ from 1 to number of Gauss points **do**\n\n  - Step a: Compute shape function derivative wrt to $\\xi$ and the Jacobian\n    $$\\frac{dN_k}{d\\xi} = \\frac{dN_k\\left(\\xi_n\\right)}{d\\xi}$$\n    $$J = J\\left(x_k, \\xi_n\\right)$$\n \n  - Step b: Compute the strain at $\\xi_n$\n    $$\\epsilon = \\sum_k \\frac{1}{J} u_k \\frac{dN_k\\left(\\xi_n\\right)}{d\\xi}$$\n  \n  - Step c: Compute the element stiffness at $\\xi_n$\n    $$\\frac{d\\sigma}{d\\epsilon} = f\\left(\\epsilon\\right)$$\n  \n  - Step d: Update element stiffness    \n    **for** $i$ from 1 to number of element nodes **do**   \n      &nbsp;&nbsp;&nbsp;&nbsp;**for** $j$ from 1 to number of element nodes **do**\n      $$k_{ij}^e = k_{ij}^e + \n               \\frac{1}{J}\\frac{d\\sigma}{d\\epsilon}\\frac{dN_i}{d\\xi}\\frac{dN_i}{d\\xi} w_n$$\n      &nbsp;&nbsp;&nbsp;&nbsp;**end for**  \n    **end for**\n  \n  **end for**\n\n## Neo Hookean Material Model\n\nAn example of a nonlinear material model, widely used in the study of polymer-like materials subjected to moderate strains, is the single parameter Neo-Hookean material model whereby the stress is related to the stretch by\n\n\n```python\nL, L0, lam, e, E = sp.symbols(\"L L0 lambda epsilon E\")\ns = E / 2 * (lam - 1 / lam)\ns\n```\n\nwhere $E$ is Young's modulus.  In terms of engineering strain\n\n$$\n\\epsilon = \\frac{L - L_0}{L_0} = \\lambda - 1 \\rightarrow \\lambda = \\epsilon + 1\n$$\n\nthe stress is\n\n\n```python\ns = s.subs({lam: e + 1})\ns.simplify()\n```\n\nThe stiffness, $\\frac{d\\sigma}{d\\epsilon}$ is given by\n\n\n```python\ndsde = sp.diff(s, e)\ndsde.simplify()\n```\n\nLet's make sure that the stiffness at $\\epsilon=0$ is $E$\n\n\n```python\ndsde.subs({e:0})\n```\n\n# Finite Element Implementation: Suggestions\n\n- Implement a Newton solver using a linear elastic material model, verify it gives the same answer as the direct solver.\n\n- Doing so will require calling an external material model whenever the stress and/or material stiffness are needed.  To reduce complications and repeated code, write a function like:\n\n        def update_material_state(props, strain, mat_id=1):\n            if mat_id == 1:\n                # linear elastic\n                E = props[0]\n                stress = E * strain\n                stiff = E\n            elif mat_id == ...    \n        return stress, stiff\n        \n  Different material models can then be implemented by giving them a mat_id, i.e., mat_id will now be a model input.  The FEModel constructor should also make sure that the props array is set up correctly for the material.\n  \n  When element stiffness and/or stress are needed, just call update_material_state as\n  \n         el_stress, el_stiff = update_material_id(props, strain, mat_id)\n         \n  Of course, you'll need to make sure that props, strain, and mat_id are correct.\n", "meta": {"hexsha": "ee157bf164d16cbb60171fa3bd07db9646155559", "size": 40861, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lessons/Lesson14_NonlinearMaterials.ipynb", "max_stars_repo_name": "jzw0025/fem-with-python", "max_stars_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 148, "max_stars_repo_stars_event_min_datetime": "2015-11-05T16:32:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:42:26.000Z", "max_issues_repo_path": "Lessons/Lesson14_NonlinearMaterials.ipynb", "max_issues_repo_name": "pinkieli/fem-with-python", "max_issues_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lessons/Lesson14_NonlinearMaterials.ipynb", "max_forks_repo_name": "pinkieli/fem-with-python", "max_forks_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": 74, "max_forks_repo_forks_event_min_datetime": "2016-02-17T13:23:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T07:48:27.000Z", "avg_line_length": 45.6037946429, "max_line_length": 9838, "alphanum_fraction": 0.6455054942, "converted": true, "num_tokens": 5051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10087862813632469, "lm_q2_score": 0.11436853674701282, "lm_q1q2_score": 0.011537341088997491}}
{"text": "<a href=\"https://colab.research.google.com/gist/cwbeitel/18f01dfd62548452b344af430be84026/fx-dev.ipynb\" target=\"_parent\"></a>\n\n# Novel feedback experiences for enhanced mental training\n\nContributors: @cwbeitel\n\n# Overview\n\nEnhanced-feedback mental training experiences (FX) are the primary product of Project Clarify. Two categories of these are described in the following which in turn reference component issues:\n\n- https://github.com/projectclarify/clarify/issues/84\n- https://github.com/projectclarify/clarify/issues/83\n\nThis notebook is a central place for design docs (related to https://github.com/projectclarify/clarify/issues/147), interactive prototypes, and lightweight prototype development towards graduated prototypes later being integrated into our core front-end application.\n\n\n# Setup\n\nPlease run the relevant sections here within and *remember* before newly-installed python dependencies become available the notebook runtime/kernel must be restarted (via \"Runtime\" > \"Restart Runtime\" above).\n\n##### Clarify codebase and dependencies\n\n\n```\n# TODO: Check whether it's already present and if so skip\n!git clone https://github.com/projectclarify/clarify.git\n```\n\n    Cloning into 'clarify'...\n    remote: Enumerating objects: 72, done.\u001b[K\n    remote: Counting objects: 100% (72/72), done.\u001b[K\n    remote: Compressing objects: 100% (62/62), done.\u001b[K\n    remote: Total 10244 (delta 30), reused 25 (delta 10), pack-reused 10172\u001b[K\n    Receiving objects: 100% (10244/10244), 32.79 MiB | 10.61 MiB/s, done.\n    Resolving deltas: 100% (2503/2503), done.\n\n\n\n```\n# Check out a fairly old version of the codebase that can be used to restore the\n# image FEC model we trained in tensorflow.\n!cd clarify && git checkout -b demo e5252a37fcdd4ccabdd9ef564ece0385365b577d && pip install -e .[tensorflow,tests]\n```\n\n    Checking out files: 100% (9719/9719), done.\n    Switched to a new branch 'demo'\n    Obtaining file:///content/clarify\n    Collecting numpy==1.16.2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/35/d5/4f8410ac303e690144f0a0603c4b8fd3b986feb2749c435f7cdbb288f17e/numpy-1.16.2-cp36-cp36m-manylinux1_x86_64.whl (17.3MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 17.3MB 207kB/s \n    \u001b[?25hRequirement already satisfied: requests==2.21.0 in /usr/local/lib/python3.6/dist-packages (from pcml==0.0.1) (2.21.0)\n    Collecting scipy==1.2.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/7f/5f/c48860704092933bf1c4c1574a8de1ffd16bf4fde8bab190d747598844b2/scipy-1.2.1-cp36-cp36m-manylinux1_x86_64.whl (24.8MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 24.8MB 113kB/s \n    \u001b[?25hRequirement already satisfied: six==1.12.0 in /usr/local/lib/python3.6/dist-packages (from pcml==0.0.1) (1.12.0)\n    Requirement already satisfied: seaborn==0.9.0 in /usr/local/lib/python3.6/dist-packages (from pcml==0.0.1) (0.9.0)\n    Collecting mne==0.17.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/a1/e5/f60f23e3ef10f5b1efa1aabb407f0b2fc64ed12ac166a6e1c16dd7db6e77/mne-0.17.1.tar.gz (6.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.2MB 18.5MB/s \n    \u001b[?25hCollecting moviepy==1.0.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/fb/32/a93f4af8b88985304a748ca0a66a64eb9fac53d0a9355ec33e713c4a3bf5/moviepy-1.0.0.tar.gz (398kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 399kB 42.0MB/s \n    \u001b[?25hCollecting kubernetes==9.0.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/00/f7/4f196c55f1c2713d3edc8252c4b45326306eef4dc10048f13916fe446e2b/kubernetes-9.0.0-py2.py3-none-any.whl (1.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.4MB 46.1MB/s \n    \u001b[?25hCollecting rfc3339==6.0\n      Downloading https://files.pythonhosted.org/packages/04/0b/8727b5496abde4622dc0e2ec2ea082e11d14ef70cfc73118b480447456ca/rfc3339-6.0.tar.gz\n    Collecting dill==0.2.9\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/fe/42/bfe2e0857bc284cbe6a011d93f2a9ad58a22cb894461b199ae72cfef0f29/dill-0.2.9.tar.gz (150kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 153kB 47.1MB/s \n    \u001b[?25hRequirement already satisfied: tensorflow_hub in /usr/local/lib/python3.6/dist-packages (from pcml==0.0.1) (0.7.0)\n    Collecting google-cloud-bigtable\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/70/de/e2023c20c39717741e0ef8eead585055ef6ea0cc1f9117e8aa18065ea9f3/google_cloud_bigtable-1.2.1-py2.py3-none-any.whl (234kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 235kB 38.7MB/s \n    \u001b[?25hCollecting google-cloud-pubsub\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/b5/11/e1bfca8dd2f3407b55fa67e733fe1b38a6e0756750fdd1fbffda5ffbc526/google_cloud_pubsub-1.1.0-py2.py3-none-any.whl (120kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 122kB 35.3MB/s \n    \u001b[?25hCollecting firebase-admin\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/49/b1/ba41c23eb0f7895a4db5a03255bfeec0f54ee8b70374dc68ff2586cafaa5/firebase_admin-3.2.1-py2.py3-none-any.whl (82kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 92kB 10.1MB/s \n    \u001b[?25hCollecting google-cloud-firestore==0.31.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/58/0d/60b5f96aca1b88a7555f2758cae3a19956b9cdb65e562f5313224642783e/google_cloud_firestore-0.31.0-py2.py3-none-any.whl (125kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 133kB 53.4MB/s \n    \u001b[?25hRequirement already satisfied: google-auth in /usr/local/lib/python3.6/dist-packages (from pcml==0.0.1) (1.4.2)\n    Collecting requests-toolbelt\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/60/ef/7681134338fc097acef8d9b2f8abe0458e4d87559c689a8c306d0957ece5/requests_toolbelt-0.9.1-py2.py3-none-any.whl (54kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 61kB 6.3MB/s \n    \u001b[?25hRequirement already satisfied: scikit-learn>=0.21.3 in /usr/local/lib/python3.6/dist-packages (from pcml==0.0.1) (0.22.1)\n    Collecting faced@ https://github.com/iitzco/faced/archive/31ef0d30e1567a06113f49ff4a1202760d952df2.zip\n    \u001b[?25l  Downloading https://github.com/iitzco/faced/archive/31ef0d30e1567a06113f49ff4a1202760d952df2.zip\n    \u001b[K     / 81.2MB 3.9MB/s\n    \u001b[?25hCollecting tensor2tensor==1.14.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/64/75/e8fab6e46fcfaf278998b9d0a182361eaa1a9b5a9a7ecb58a0796d9e5229/tensor2tensor-1.14.0-py2.py3-none-any.whl (1.6MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.6MB 31.8MB/s \n    \u001b[?25hCollecting google-cloud-logging\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/b9/06/3a89173f80d02d275ab4fdca5283a7fdb84845e214f3383b5d52c29f4b5f/google_cloud_logging-1.14.0-py2.py3-none-any.whl (134kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 143kB 35.2MB/s \n    \u001b[?25hCollecting pathos\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/c6/a2/cd59f73d5ede4f122687bf8f63de5d671c9561e493ca699241f05b038278/pathos-0.2.5.tar.gz (162kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 163kB 39.2MB/s \n    \u001b[?25hRequirement already satisfied: opencv-python in /usr/local/lib/python3.6/dist-packages (from pcml==0.0.1) (4.1.2.30)\n    Requirement already satisfied: tensorflow-probability==0.7.0 in /usr/local/lib/python3.6/dist-packages (from pcml==0.0.1) (0.7.0)\n    Collecting gTTS\n      Downloading https://files.pythonhosted.org/packages/a1/0c/4ca77eca3b739a4a08360930643f58d714e302fee0d2f8c654e67d9af8e7/gTTS-2.1.1-py3-none-any.whl\n    Collecting tensorflow==1.14\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/de/f0/96fb2e0412ae9692dbf400e5b04432885f677ad6241c088ccc5fe7724d69/tensorflow-1.14.0-cp36-cp36m-manylinux1_x86_64.whl (109.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 109.2MB 34kB/s \n    \u001b[?25hCollecting pylint\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/e9/59/43fc36c5ee316bb9aeb7cf5329cdbdca89e5749c34d5602753827c0aa2dc/pylint-2.4.4-py3-none-any.whl (302kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 307kB 38.7MB/s \n    \u001b[?25hRequirement already satisfied: pytest in /usr/local/lib/python3.6/dist-packages (from pcml==0.0.1) (3.6.4)\n    Collecting pytest-cache\n      Downloading https://files.pythonhosted.org/packages/d1/15/082fd0428aab33d2bafa014f3beb241830427ba803a8912a5aaeaf3a5663/pytest-cache-1.0.tar.gz\n    Collecting tensorflow-serving-api==1.12.0\n      Downloading https://files.pythonhosted.org/packages/79/69/1e724c0d98f12b12f9ad583a3df7750e14ec5f06069aa4be8d75a2ab9bb8/tensorflow_serving_api-1.12.0-py2.py3-none-any.whl\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests==2.21.0->pcml==0.0.1) (2019.11.28)\n    Requirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests==2.21.0->pcml==0.0.1) (2.8)\n    Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests==2.21.0->pcml==0.0.1) (1.24.3)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests==2.21.0->pcml==0.0.1) (3.0.4)\n    Requirement already satisfied: pandas>=0.15.2 in /usr/local/lib/python3.6/dist-packages (from seaborn==0.9.0->pcml==0.0.1) (0.25.3)\n    Requirement already satisfied: matplotlib>=1.4.3 in /usr/local/lib/python3.6/dist-packages (from seaborn==0.9.0->pcml==0.0.1) (3.1.2)\n    Requirement already satisfied: decorator<5.0,>=4.0.2 in /usr/local/lib/python3.6/dist-packages (from moviepy==1.0.0->pcml==0.0.1) (4.4.1)\n    Requirement already satisfied: tqdm<5.0,>=4.11.2 in /usr/local/lib/python3.6/dist-packages (from moviepy==1.0.0->pcml==0.0.1) (4.28.1)\n    Collecting proglog<=1.0.0\n      Downloading https://files.pythonhosted.org/packages/fe/ab/4cb19b578e1364c0b2d6efd6521a8b4b4e5c4ae6528041d31a2a951dd991/proglog-0.1.9.tar.gz\n    Collecting imageio<3.0,>=2.5\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1a/de/f7f985018f462ceeffada7f6e609919fbcc934acd9301929cba14bc2c24a/imageio-2.6.1-py3-none-any.whl (3.3MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.3MB 37.2MB/s \n    \u001b[?25hCollecting imageio_ffmpeg>=0.2.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1b/12/01126a2fb737b23461d7dadad3b8abd51ad6210f979ff05c6fa9812dfbbe/imageio_ffmpeg-0.3.0-py3-none-manylinux2010_x86_64.whl (22.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 22.2MB 183kB/s \n    \u001b[?25hRequirement already satisfied: setuptools>=21.0.0 in /usr/local/lib/python3.6/dist-packages (from kubernetes==9.0.0->pcml==0.0.1) (42.0.2)\n    Requirement already satisfied: python-dateutil>=2.5.3 in /usr/local/lib/python3.6/dist-packages (from kubernetes==9.0.0->pcml==0.0.1) (2.6.1)\n    Requirement already satisfied: pyyaml>=3.12 in /usr/local/lib/python3.6/dist-packages (from kubernetes==9.0.0->pcml==0.0.1) (3.13)\n    Collecting websocket-client!=0.40.0,!=0.41.*,!=0.42.*,>=0.32.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/4c/5f/f61b420143ed1c8dc69f9eaec5ff1ac36109d52c80de49d66e0c36c3dfdf/websocket_client-0.57.0-py2.py3-none-any.whl (200kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 204kB 52.8MB/s \n    \u001b[?25hRequirement already satisfied: requests-oauthlib in /usr/local/lib/python3.6/dist-packages (from kubernetes==9.0.0->pcml==0.0.1) (1.3.0)\n    Requirement already satisfied: protobuf>=3.4.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow_hub->pcml==0.0.1) (3.10.0)\n    Collecting grpc-google-iam-v1<0.13dev,>=0.12.3\n      Downloading https://files.pythonhosted.org/packages/65/19/2060c8faa325fddc09aa67af98ffcb6813f39a0ad805679fa64815362b3a/grpc-google-iam-v1-0.12.3.tar.gz\n    Requirement already satisfied: google-cloud-core<2.0dev,>=1.0.3 in /usr/local/lib/python3.6/dist-packages (from google-cloud-bigtable->pcml==0.0.1) (1.0.3)\n    Requirement already satisfied: google-api-core[grpc]<2.0.0dev,>=1.14.0 in /usr/local/lib/python3.6/dist-packages (from google-cloud-bigtable->pcml==0.0.1) (1.15.0)\n    Collecting cachecontrol>=0.12.4\n      Downloading https://files.pythonhosted.org/packages/18/71/0a9df4206a5dc5ae7609c41efddab2270a2c1ff61d39de7591dc7302ef89/CacheControl-0.12.6-py2.py3-none-any.whl\n    Requirement already satisfied: google-api-python-client>=1.7.8 in /usr/local/lib/python3.6/dist-packages (from firebase-admin->pcml==0.0.1) (1.7.11)\n    Collecting google-cloud-storage>=1.18.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/cd/6d/75c2a47af99d15aa8b4de4e66226c128e623f8c9d3e27a8588368ccc38fc/google_cloud_storage-1.25.0-py2.py3-none-any.whl (73kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 81kB 8.2MB/s \n    \u001b[?25hRequirement already satisfied: pytz in /usr/local/lib/python3.6/dist-packages (from google-cloud-firestore==0.31.0->pcml==0.0.1) (2018.9)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.6/dist-packages (from google-auth->pcml==0.0.1) (0.2.7)\n    Requirement already satisfied: cachetools>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth->pcml==0.0.1) (4.0.0)\n    Requirement already satisfied: rsa>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from google-auth->pcml==0.0.1) (4.0)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn>=0.21.3->pcml==0.0.1) (0.14.1)\n    Requirement already satisfied: tensorflow-datasets in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.14.0->pcml==0.0.1) (1.3.2)\n    Requirement already satisfied: bz2file in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.14.0->pcml==0.0.1) (0.98)\n    Requirement already satisfied: pypng in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.14.0->pcml==0.0.1) (0.0.20)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.14.0->pcml==0.0.1) (1.1.1)\n    Requirement already satisfied: gym in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.14.0->pcml==0.0.1) (0.15.4)\n    Requirement already satisfied: Pillow in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.14.0->pcml==0.0.1) (6.2.2)\n    Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.14.0->pcml==0.0.1) (0.16.0)\n    Requirement already satisfied: flask in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.14.0->pcml==0.0.1) (1.1.1)\n    Requirement already satisfied: gunicorn in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.14.0->pcml==0.0.1) (20.0.4)\n    Requirement already satisfied: oauth2client in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.14.0->pcml==0.0.1) (4.1.3)\n    Requirement already satisfied: kfac in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.14.0->pcml==0.0.1) (0.2.0)\n    Requirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.14.0->pcml==0.0.1) (2.8.0)\n    Requirement already satisfied: mesh-tensorflow in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.14.0->pcml==0.0.1) (0.1.8)\n    Requirement already satisfied: dopamine-rl in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.14.0->pcml==0.0.1) (1.0.5)\n    Requirement already satisfied: gin-config in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.14.0->pcml==0.0.1) (0.3.0)\n    Requirement already satisfied: tensorflow-gan in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.14.0->pcml==0.0.1) (2.0.0)\n    Requirement already satisfied: gevent in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.14.0->pcml==0.0.1) (1.4.0)\n    Requirement already satisfied: grpcio in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.14.0->pcml==0.0.1) (1.15.0)\n    Collecting ppft>=1.6.6.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/5b/16/9e83c2aa45949ee9cd6e8731275acdaeb6c624b8728d6598196c65074f3e/ppft-1.6.6.1.tar.gz (63kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 71kB 6.5MB/s \n    \u001b[?25hCollecting pox>=0.2.7\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/6c/9a/957818485aa165ce93b646aeb20181215bb415c9dca8345bdbe23b08ae67/pox-0.2.7.tar.gz (110kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 112kB 49.0MB/s \n    \u001b[?25hRequirement already satisfied: multiprocess>=0.70.9 in /usr/local/lib/python3.6/dist-packages (from pathos->pcml==0.0.1) (0.70.9)\n    Requirement already satisfied: cloudpickle>=0.6.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow-probability==0.7.0->pcml==0.0.1) (1.2.2)\n    Requirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.6/dist-packages (from gTTS->pcml==0.0.1) (4.6.3)\n    Collecting gtts-token>=1.1.3\n      Downloading https://files.pythonhosted.org/packages/e7/25/ca6e9cd3275bfc3097fe6b06cc31db6d3dfaf32e032e0f73fead9c9a03ce/gTTS-token-1.1.3.tar.gz\n    Requirement already satisfied: click in /usr/local/lib/python3.6/dist-packages (from gTTS->pcml==0.0.1) (7.0)\n    Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.14->pcml==0.0.1) (1.11.2)\n    Requirement already satisfied: keras-preprocessing>=1.0.5 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.14->pcml==0.0.1) (1.1.0)\n    Requirement already satisfied: keras-applications>=1.0.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.14->pcml==0.0.1) (1.0.8)\n    Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.14->pcml==0.0.1) (1.1.0)\n    Requirement already satisfied: google-pasta>=0.1.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.14->pcml==0.0.1) (0.1.8)\n    Collecting tensorboard<1.15.0,>=1.14.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/91/2d/2ed263449a078cd9c8a9ba50ebd50123adf1f8cfbea1492f9084169b89d9/tensorboard-1.14.0-py3-none-any.whl (3.1MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.2MB 45.7MB/s \n    \u001b[?25hRequirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.14->pcml==0.0.1) (0.33.6)\n    Requirement already satisfied: gast>=0.2.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.14->pcml==0.0.1) (0.2.2)\n    Collecting tensorflow-estimator<1.15.0rc0,>=1.14.0rc0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/3c/d5/21860a5b11caf0678fbc8319341b0ae21a07156911132e0e71bffed0510d/tensorflow_estimator-1.14.0-py2.py3-none-any.whl (488kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 491kB 40.9MB/s \n    \u001b[?25hRequirement already satisfied: astor>=0.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.14->pcml==0.0.1) (0.8.1)\n    Requirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.14->pcml==0.0.1) (0.9.0)\n    Collecting astroid<2.4,>=2.3.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/ad/ae/86734823047962e7b8c8529186a1ac4a7ca19aaf1aa0c7713c022ef593fd/astroid-2.3.3-py3-none-any.whl (205kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 215kB 37.1MB/s \n    \u001b[?25hCollecting isort<5,>=4.2.5\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/e5/b0/c121fd1fa3419ea9bfd55c7f9c4fedfec5143208d8c7ad3ce3db6c623c21/isort-4.3.21-py2.py3-none-any.whl (42kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 5.3MB/s \n    \u001b[?25hCollecting mccabe<0.7,>=0.6\n      Downloading https://files.pythonhosted.org/packages/87/89/479dc97e18549e21354893e4ee4ef36db1d237534982482c3681ee6e7b57/mccabe-0.6.1-py2.py3-none-any.whl\n    Requirement already satisfied: more-itertools>=4.0.0 in /usr/local/lib/python3.6/dist-packages (from pytest->pcml==0.0.1) (8.0.2)\n    Requirement already satisfied: py>=1.5.0 in /usr/local/lib/python3.6/dist-packages (from pytest->pcml==0.0.1) (1.8.1)\n    Requirement already satisfied: pluggy<0.8,>=0.5 in /usr/local/lib/python3.6/dist-packages (from pytest->pcml==0.0.1) (0.7.1)\n    Requirement already satisfied: atomicwrites>=1.0 in /usr/local/lib/python3.6/dist-packages (from pytest->pcml==0.0.1) (1.3.0)\n    Requirement already satisfied: attrs>=17.4.0 in /usr/local/lib/python3.6/dist-packages (from pytest->pcml==0.0.1) (19.3.0)\n    Collecting execnet>=1.1.dev1\n      Downloading https://files.pythonhosted.org/packages/d3/2e/c63af07fa471e0a02d05793c7a56a9f7d274a8489442a5dc4fb3b2b3c705/execnet-1.7.1-py2.py3-none-any.whl\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=1.4.3->seaborn==0.9.0->pcml==0.0.1) (2.4.6)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=1.4.3->seaborn==0.9.0->pcml==0.0.1) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=1.4.3->seaborn==0.9.0->pcml==0.0.1) (1.1.0)\n    Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from requests-oauthlib->kubernetes==9.0.0->pcml==0.0.1) (3.1.0)\n    Requirement already satisfied: googleapis-common-protos[grpc]<2.0.0dev,>=1.5.2 in /usr/local/lib/python3.6/dist-packages (from grpc-google-iam-v1<0.13dev,>=0.12.3->google-cloud-bigtable->pcml==0.0.1) (1.6.0)\n    Requirement already satisfied: msgpack>=0.5.2 in /usr/local/lib/python3.6/dist-packages (from cachecontrol>=0.12.4->firebase-admin->pcml==0.0.1) (0.5.6)\n    Requirement already satisfied: uritemplate<4dev,>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client>=1.7.8->firebase-admin->pcml==0.0.1) (3.0.1)\n    Requirement already satisfied: google-auth-httplib2>=0.0.3 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client>=1.7.8->firebase-admin->pcml==0.0.1) (0.0.3)\n    Requirement already satisfied: httplib2<1dev,>=0.9.2 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client>=1.7.8->firebase-admin->pcml==0.0.1) (0.11.3)\n    Collecting google-resumable-media<0.6dev,>=0.5.0\n      Downloading https://files.pythonhosted.org/packages/35/9e/f73325d0466ce5bdc36333f1aeb2892ead7b76e79bdb5c8b0493961fa098/google_resumable_media-0.5.0-py2.py3-none-any.whl\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.6/dist-packages (from pyasn1-modules>=0.2.1->google-auth->pcml==0.0.1) (0.4.8)\n    Requirement already satisfied: tensorflow-metadata in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->tensor2tensor==1.14.0->pcml==0.0.1) (0.15.2)\n    Requirement already satisfied: promise in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->tensor2tensor==1.14.0->pcml==0.0.1) (2.3)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy->tensor2tensor==1.14.0->pcml==0.0.1) (1.1.0)\n    Requirement already satisfied: pyglet<=1.3.2,>=1.2.0 in /usr/local/lib/python3.6/dist-packages (from gym->tensor2tensor==1.14.0->pcml==0.0.1) (1.3.2)\n    Requirement already satisfied: itsdangerous>=0.24 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor==1.14.0->pcml==0.0.1) (1.1.0)\n    Requirement already satisfied: Werkzeug>=0.15 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor==1.14.0->pcml==0.0.1) (0.16.0)\n    Requirement already satisfied: Jinja2>=2.10.1 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor==1.14.0->pcml==0.0.1) (2.10.3)\n    Requirement already satisfied: greenlet>=0.4.14; platform_python_implementation == \"CPython\" in /usr/local/lib/python3.6/dist-packages (from gevent->tensor2tensor==1.14.0->pcml==0.0.1) (0.4.15)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard<1.15.0,>=1.14.0->tensorflow==1.14->pcml==0.0.1) (3.1.1)\n    Collecting lazy-object-proxy==1.4.*\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/0b/dd/b1e3407e9e6913cf178e506cd0dee818e58694d9a5cd1984e3f6a8b9a10f/lazy_object_proxy-1.4.3-cp36-cp36m-manylinux1_x86_64.whl (55kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 61kB 5.9MB/s \n    \u001b[?25hCollecting typed-ast<1.5,>=1.4.0; implementation_name == \"cpython\" and python_version < \"3.8\"\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/90/ed/5459080d95eb87a02fe860d447197be63b6e2b5e9ff73c2b0a85622994f4/typed_ast-1.4.1-cp36-cp36m-manylinux1_x86_64.whl (737kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 747kB 34.5MB/s \n    \u001b[?25hCollecting apipkg>=1.4\n      Downloading https://files.pythonhosted.org/packages/67/08/4815a09603fc800209431bec5b8bd2acf2f95abdfb558a44a42507fb94da/apipkg-1.5-py2.py3-none-any.whl\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.6/dist-packages (from Jinja2>=2.10.1->flask->tensor2tensor==1.14.0->pcml==0.0.1) (1.1.1)\n    Building wheels for collected packages: mne, moviepy, rfc3339, dill, faced, pathos, pytest-cache, proglog, grpc-google-iam-v1, ppft, pox, gtts-token\n      Building wheel for mne (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for mne: filename=mne-0.17.1-cp36-none-any.whl size=6194555 sha256=a68ecf214aa8252952e86e5d5ccc5024d0816057382437c8285b2ffaa01a8128\n      Stored in directory: /root/.cache/pip/wheels/39/f9/f5/3e2fdef321f8e1f64061730c8ba2c81ad55c4b1b860b29d2dd\n      Building wheel for moviepy (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for moviepy: filename=moviepy-1.0.0-cp36-none-any.whl size=131367 sha256=2dea9fcb335f2641142d820c9a0b6350716444e31b28c049b257a9ce76025223\n      Stored in directory: /root/.cache/pip/wheels/52/e2/4c/f594a5945bc98e052ef248b46a0f1f7ea838b0b2a5f8895651\n      Building wheel for rfc3339 (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for rfc3339: filename=rfc3339-6.0-cp36-none-any.whl size=4502 sha256=45fa5d254302de4b8cc68a457cac4c0130b29ad6f2d4ef82d9069eaddd5b04ee\n      Stored in directory: /root/.cache/pip/wheels/40/70/ac/f506969ec90fcf86c2065f6363bc9a1cdcc7d10190b421a9d5\n      Building wheel for dill (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for dill: filename=dill-0.2.9-cp36-none-any.whl size=77403 sha256=684a102db18bbf6a1503f2b9eba8452188aebd0b432d5b2de0afca1b27e35083\n      Stored in directory: /root/.cache/pip/wheels/5b/d7/0f/e58eae695403de585269f4e4a94e0cd6ca60ec0c202936fa4a\n      Building wheel for faced (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for faced: filename=faced-0.1-cp36-none-any.whl size=27342262 sha256=05705ba11f348cbe6208adc1a5e8312b5f0fa7bc44ded342fe11b3b2abf37aa6\n      Stored in directory: /tmp/pip-ephem-wheel-cache-0nxm84d5/wheels/5e/60/d1/7bb207222afc0b7b65100b4b748245d9814567629fb4d80020\n      Building wheel for pathos (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pathos: filename=pathos-0.2.5-cp36-none-any.whl size=77575 sha256=3a1e09021c9ea6c9dc7073bb28b0b315900640a77cfccfdc4d4735ced3a52a52\n      Stored in directory: /root/.cache/pip/wheels/61/6d/83/90b0c3d2c271da2c4850731e894798c98f8dbedbac74e8eff0\n      Building wheel for pytest-cache (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pytest-cache: filename=pytest_cache-1.0-cp36-none-any.whl size=6931 sha256=8f1953543f35ec5cbfb5336c705abfde68e8542b8a11e2d5007ef084c3d6f98e\n      Stored in directory: /root/.cache/pip/wheels/e4/9e/28/59d0a23800e49808f17920c5922252c661966ca4a36db5ee38\n      Building wheel for proglog (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for proglog: filename=proglog-0.1.9-cp36-none-any.whl size=6148 sha256=58d3d828fbef512805d4fb59bc9764ea02fe51561cd357b43fcf8842aff7f5ea\n      Stored in directory: /root/.cache/pip/wheels/65/56/60/1d0306a8d90b188af393c1812ddb502a8821b70917f82dcc00\n      Building wheel for grpc-google-iam-v1 (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for grpc-google-iam-v1: filename=grpc_google_iam_v1-0.12.3-cp36-none-any.whl size=18499 sha256=9f548e176bc1a09c65b111e8a5fe6360bc135046f0b324c20b57586c1a6b8652\n      Stored in directory: /root/.cache/pip/wheels/de/3a/83/77a1e18e1a8757186df834b86ce6800120ac9c79cd8ca4091b\n      Building wheel for ppft (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for ppft: filename=ppft-1.6.6.1-cp36-none-any.whl size=64710 sha256=74fae8c419e5f895b44403da742ded7ee5d478e65563ef4ec47fa35248cdeba2\n      Stored in directory: /root/.cache/pip/wheels/6a/0c/53/ea8dd63608f75c1e7a64d5c5ce5d1e6d04f15ae8a6fce4c2a0\n      Building wheel for pox (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pox: filename=pox-0.2.7-cp36-none-any.whl size=28303 sha256=865daa930ff706376d5f40d95b3f23c9ed11e447c80fcee59fe019d64b17cd8d\n      Stored in directory: /root/.cache/pip/wheels/47/10/7b/0e916f6246fe7cf7d3acd25a6d273ecf3f97888cea073a8ac2\n      Building wheel for gtts-token (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for gtts-token: filename=gTTS_token-1.1.3-cp36-none-any.whl size=4097 sha256=60ca3d94dda4386d523c0e1e96a78435d627ee2f16b32c186099e4714cf26c9f\n      Stored in directory: /root/.cache/pip/wheels/dd/11/61/33f7e51bf545e910552b2255eead2a7cd8ef54064b46dceb34\n    Successfully built mne moviepy rfc3339 dill faced pathos pytest-cache proglog grpc-google-iam-v1 ppft pox gtts-token\n    \u001b[31mERROR: multiprocess 0.70.9 has requirement dill>=0.3.1, but you'll have dill 0.2.9 which is incompatible.\u001b[0m\n    \u001b[31mERROR: google-cloud-storage 1.25.0 has requirement google-auth<2.0dev,>=1.9.0, but you'll have google-auth 1.4.2 which is incompatible.\u001b[0m\n    \u001b[31mERROR: google-cloud-storage 1.25.0 has requirement google-cloud-core<2.0dev,>=1.2.0, but you'll have google-cloud-core 1.0.3 which is incompatible.\u001b[0m\n    \u001b[31mERROR: google-cloud-bigquery 1.21.0 has requirement google-resumable-media!=0.4.0,<0.5.0dev,>=0.3.1, but you'll have google-resumable-media 0.5.0 which is incompatible.\u001b[0m\n    \u001b[31mERROR: datascience 0.10.6 has requirement folium==0.2.1, but you'll have folium 0.8.3 which is incompatible.\u001b[0m\n    \u001b[31mERROR: albumentations 0.1.12 has requirement imgaug<0.2.7,>=0.2.5, but you'll have imgaug 0.2.9 which is incompatible.\u001b[0m\n    \u001b[31mERROR: google-cloud-firestore 0.31.0 has requirement google-cloud-core<0.30dev,>=0.29.0, but you'll have google-cloud-core 1.0.3 which is incompatible.\u001b[0m\n    \u001b[31mERROR: firebase-admin 3.2.1 has requirement google-cloud-firestore>=1.4.0; platform_python_implementation != \"PyPy\", but you'll have google-cloud-firestore 0.31.0 which is incompatible.\u001b[0m\n    \u001b[31mERROR: pathos 0.2.5 has requirement dill>=0.3.1, but you'll have dill 0.2.9 which is incompatible.\u001b[0m\n    Installing collected packages: numpy, scipy, mne, proglog, imageio, imageio-ffmpeg, moviepy, websocket-client, kubernetes, rfc3339, dill, grpc-google-iam-v1, google-cloud-bigtable, google-cloud-pubsub, cachecontrol, google-cloud-firestore, google-resumable-media, google-cloud-storage, firebase-admin, requests-toolbelt, tensorboard, tensorflow-estimator, tensorflow, faced, tensor2tensor, google-cloud-logging, ppft, pox, pathos, gtts-token, gTTS, lazy-object-proxy, typed-ast, astroid, isort, mccabe, pylint, apipkg, execnet, pytest-cache, tensorflow-serving-api, pcml\n      Found existing installation: numpy 1.17.5\n        Uninstalling numpy-1.17.5:\n          Successfully uninstalled numpy-1.17.5\n      Found existing installation: scipy 1.4.1\n        Uninstalling scipy-1.4.1:\n          Successfully uninstalled scipy-1.4.1\n      Found existing installation: imageio 2.4.1\n        Uninstalling imageio-2.4.1:\n          Successfully uninstalled imageio-2.4.1\n      Found existing installation: moviepy 0.2.3.5\n        Uninstalling moviepy-0.2.3.5:\n          Successfully uninstalled moviepy-0.2.3.5\n      Found existing installation: dill 0.3.1.1\n        Uninstalling dill-0.3.1.1:\n          Successfully uninstalled dill-0.3.1.1\n      Found existing installation: google-resumable-media 0.4.1\n        Uninstalling google-resumable-media-0.4.1:\n          Successfully uninstalled google-resumable-media-0.4.1\n      Found existing installation: google-cloud-storage 1.16.2\n        Uninstalling google-cloud-storage-1.16.2:\n          Successfully uninstalled google-cloud-storage-1.16.2\n      Found existing installation: tensorboard 1.15.0\n        Uninstalling tensorboard-1.15.0:\n          Successfully uninstalled tensorboard-1.15.0\n      Found existing installation: tensorflow-estimator 1.15.1\n        Uninstalling tensorflow-estimator-1.15.1:\n          Successfully uninstalled tensorflow-estimator-1.15.1\n      Found existing installation: tensorflow 1.15.0\n        Uninstalling tensorflow-1.15.0:\n          Successfully uninstalled tensorflow-1.15.0\n      Found existing installation: tensor2tensor 1.14.1\n        Uninstalling tensor2tensor-1.14.1:\n          Successfully uninstalled tensor2tensor-1.14.1\n      Running setup.py develop for pcml\n    Successfully installed apipkg-1.5 astroid-2.3.3 cachecontrol-0.12.6 dill-0.2.9 execnet-1.7.1 faced-0.1 firebase-admin-3.2.1 gTTS-2.1.1 google-cloud-bigtable-1.2.1 google-cloud-firestore-0.31.0 google-cloud-logging-1.14.0 google-cloud-pubsub-1.1.0 google-cloud-storage-1.25.0 google-resumable-media-0.5.0 grpc-google-iam-v1-0.12.3 gtts-token-1.1.3 imageio-2.6.1 imageio-ffmpeg-0.3.0 isort-4.3.21 kubernetes-9.0.0 lazy-object-proxy-1.4.3 mccabe-0.6.1 mne-0.17.1 moviepy-1.0.0 numpy-1.16.2 pathos-0.2.5 pcml pox-0.2.7 ppft-1.6.6.1 proglog-0.1.9 pylint-2.4.4 pytest-cache-1.0 requests-toolbelt-0.9.1 rfc3339-6.0 scipy-1.2.1 tensor2tensor-1.14.0 tensorboard-1.14.0 tensorflow-1.14.0 tensorflow-estimator-1.14.0 tensorflow-serving-api-1.12.0 typed-ast-1.4.1 websocket-client-0.57.0\n\n\n\n```\n# Dependency needed for FX prototypes that involved synthesized speech.\n!pip install gtts\n```\n\n    Requirement already satisfied: gtts in /usr/local/lib/python3.6/dist-packages (2.1.1)\n    Requirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.6/dist-packages (from gtts) (4.6.3)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from gtts) (1.12.0)\n    Requirement already satisfied: gtts-token>=1.1.3 in /usr/local/lib/python3.6/dist-packages (from gtts) (1.1.3)\n    Requirement already satisfied: click in /usr/local/lib/python3.6/dist-packages (from gtts) (7.0)\n    Requirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from gtts) (2.21.0)\n    Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->gtts) (1.24.3)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->gtts) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->gtts) (2019.11.28)\n    Requirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->gtts) (2.8)\n\n\n##### TFServing dependencies\n\nThis is only relevant for the prototypes that query a model served locally with TFServing.\n\n\n```\n!sh /content/clarify/tools/serving/install_tf_serving.sh\n```\n\n##### Model checkpoint\n\nTODO: Currently this needs to be obtained from cloud storage following authentication because for whatever reason there is an auth error when the GCS checkpoint location is referenced directly despite that being publicly-accessible\n\n\n```\n# 1. Log into your GCloud account by running the following, clicking the\n# link, authenticating, and providing the resulting code in the box below.\n!gcloud auth login\n```\n\n\n```\n# 2. Next, download the model parameters locally (instead of relying on\n# tensorflow to propperly manage credentials to fetch these itself).\n!gsutil -m cp -r gs://clarify-public/models/fec-train-j1030-0136-3a8f/output /tmp/\n```\n\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572401042.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572400837.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572401247.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572400018.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/checkpoint...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572400222.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572401450.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572400635.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572400430.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572401655.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572401860.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572402065.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572402265.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572402469.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572403083.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572402875.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572402672.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572403291.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572403498.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572403706.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572403908.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572404317.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572404113.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572404521.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572404932.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572404727.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572405138.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572405344.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572405552.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572405758.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572405963.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572406168.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572406372.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572406576.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572406782.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572406989.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572407197.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572407404.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572407607.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572407808.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572408012.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572408215.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572408422.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572408629.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572408835.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572409043.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572409249.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572409457.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572409666.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572409874.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572410084.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572410294.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572410500.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572410705.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572410910.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572411112.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572411316.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572411521.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572411723.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572411926.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572412130.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572412334.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572412539.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572412744.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572412947.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572413150.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572413357.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572413559.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572413764.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572413968.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572414173.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572414378.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572414581.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572414788.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572414992.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572415195.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572415399.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572415604.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572415807.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572416014.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572416220.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572416422.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572416627.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572416834.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572417035.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572417236.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572417442.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572417645.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572417846.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572418053.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572418253.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572418461.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572418665.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572418868.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572419070.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572419273.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572419476.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572419681.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572419887.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572420092.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572420296.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572420502.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572420707.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572420912.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572421116.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572421322.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572421530.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572421734.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572421939.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572422142.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572422346.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572422550.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572422756.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572422961.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572423164.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572423367.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572423570.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572423772.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572423976.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572424180.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572424384.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572424591.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572424794.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572424999.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572425205.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572425410.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572425614.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572425820.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572426025.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572426232.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572426441.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572426648.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572426854.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572427060.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572427265.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572427470.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572427676.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572427878.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572428083.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572428290.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572428496.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572428905.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572428699.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572429106.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572429312.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572429518.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572429725.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572429930.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572430138.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572430343.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572430550.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572430758.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572430963.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572431168.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572431373.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572431577.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572431780.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572431983.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572432188.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572432394.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572432598.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572432804.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572433008.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572433211.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572433415.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572433619.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572434025.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572433821.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572434230.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572434435.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572434638.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572434843.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572435049.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572435255.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572435459.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572435663.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572435865.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572436069.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572436272.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572436477.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572436682.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572436885.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572437089.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572437294.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572437498.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572437703.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572437909.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572438116.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572438322.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572438527.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572438732.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572438937.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572439141.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572439345.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572439547.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572439753.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572439959.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572440166.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572440372.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572440578.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572440784.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572440988.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572441196.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572441400.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572441609.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572441814.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572442022.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572442228.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572442434.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572442639.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572442846.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572443050.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572443256.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572443461.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572443666.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572443872.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572444077.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572444285.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572444493.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572444696.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572444905.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572445113.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572445319.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572445526.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572445735.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572445942.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572446150.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572446359.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572446567.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572446773.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572446981.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572447184.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572447393.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572447598.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572447803.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572448011.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572448219.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572448425.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572448630.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572448836.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572449040.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572449247.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572449453.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572449668.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572449873.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572450078.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572450284.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572450490.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572450696.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572450900.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572451106.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572451313.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572451522.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572451730.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572451936.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572452144.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572452352.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572452559.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572452764.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572452973.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572453181.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572453387.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572453596.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572453803.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572454010.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572454424.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572454219.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572454630.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572454837.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572455045.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572455249.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572455455.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572455660.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572455867.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572456073.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572456279.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572456485.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572456693.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572456898.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572457102.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572457310.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572457517.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572457723.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572457930.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572458137.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572458343.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572458547.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572458752.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572458955.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572459162.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572459368.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572459574.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572459779.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572459984.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572460189.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572460392.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572460598.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572460802.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572461006.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572461211.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572461417.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572461622.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572461826.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572462030.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572462235.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572462440.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572462646.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572462853.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572463059.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572463263.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572463466.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572463672.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572463878.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572464082.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572464285.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572464489.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572464694.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572464899.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572465105.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572465306.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572465513.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572465716.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572465919.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572466125.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572466536.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572466330.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572466742.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572466946.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572467151.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572467356.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572467562.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572467769.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572467977.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572468182.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572468387.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572468594.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572468803.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572469008.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572469217.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572469424.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572469631.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572469838.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572470043.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572470249.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572470456.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572470660.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572470864.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572471071.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572471277.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572471481.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572471688.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572471895.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572472099.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572472307.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572472512.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572472718.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572472927.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572473135.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572473340.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572473547.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572473758.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572473974.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572474191.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572474410.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572474628.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572474843.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572475063.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572475279.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572475498.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572475713.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572475932.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572476146.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572476365.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572476582.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572476797.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572477017.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572477233.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572477448.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572477662.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572477878.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572478095.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572478311.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572478528.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572478745.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572478962.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572479178.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572479397.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572479614.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572479829.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572480047.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572480261.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572480474.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572480690.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572480904.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572481120.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572481333.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572481548.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572481761.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572481974.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572482188.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572482401.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572482615.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572482832.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572483046.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572483262.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572483475.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572483690.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572483904.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572484119.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572484333.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572484547.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572484763.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572485186.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572484974.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572485400.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572485615.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572485820.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572486032.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/eval/events.out.tfevents.1572486248.fec-train-j1030-0136-3a8f-master-0.v2...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/events.out.tfevents.1572399668.fec-train-j1030-0136-3a8f-master-0...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/export/1574360147/saved_model.pbtxt...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/export/1574360147/variables/variables.data-00000-of-00002...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/export/1574360147/variables/variables.data-00001-of-00002...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/export/1574360147/variables/variables.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/export/1575913483/saved_model.pbtxt...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/export/1575913483/variables/variables.data-00000-of-00002...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/export/1575913483/variables/variables.data-00001-of-00002...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/export/1575913483/variables/variables.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/flags.txt...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/flags_t2t.txt...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/graph.pbtxt...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/hparams.json...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-172400.data-00000-of-00001...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-172400.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-172400.meta...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-173200.data-00000-of-00001...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-173200.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-173200.meta...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-174000.data-00000-of-00001...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-174000.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-174000.meta...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-174800.data-00000-of-00001...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-174800.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-174800.meta...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-175600.data-00000-of-00001...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-175600.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-175600.meta...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-176300.data-00000-of-00001...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-176300.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-176300.meta...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-177100.data-00000-of-00001...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-177100.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-177100.meta...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-177900.data-00000-of-00001...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-177900.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-177900.meta...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-178700.data-00000-of-00001...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-178700.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-178700.meta...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-179500.data-00000-of-00001...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-179500.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-179500.meta...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-180300.data-00000-of-00001...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-180300.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-180300.meta...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-181100.data-00000-of-00001...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-181100.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-181100.meta...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-181900.data-00000-of-00001...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-181900.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-181900.meta...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-182700.data-00000-of-00001...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-182700.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-182700.meta...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-183400.data-00000-of-00001...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-183400.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-183400.meta...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-184200.data-00000-of-00001...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-184200.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-184200.meta...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-185000.data-00000-of-00001...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-185000.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-185000.meta...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-185800.data-00000-of-00001...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-185800.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-185800.meta...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-186600.data-00000-of-00001...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-186600.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-186600.meta...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-187300.data-00000-of-00001...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-187300.index...\n    Copying gs://clarify-public/models/fec-train-j1030-0136-3a8f/output/model.ckpt-187300.meta...\n    / [492/492 files][  2.3 GiB/  2.3 GiB] 100% Done  94.5 MiB/s ETA 00:00:00       \n    Operation completed over 492 objects/2.3 GiB.                                    \n\n\n##### FX-specific dependencies\n\n\n```\n# TODO: We can install it but having trouble importing it\n!npm install -g lit-element\n```\n\n    \u001b[K\u001b[?25h+ lit-element@2.2.1\n    added 2 packages from 1 contributor in 0.551s\n\n\n##### Eager mode\n\nInference in tf.Eager mode is being phased out but for now it's important to initialize eager mode at startup if it's going to be used.\n\n\n```\n%tensorflow_version 1.x\nimport tensorflow as tf\n\ntfe = tf.contrib.eager\ntfe.enable_eager_execution()\nModes = tf.estimator.ModeKeys\n\n```\n\n##### Shared functions for image capture\n\n\n```\nfrom IPython.display import display, Javascript\nfrom google.colab.output import eval_js\nfrom base64 import b64decode\nimport base64\n\nimport io\nimport numpy as np\n\nfrom PIL import Image\n\nfrom faced import FaceDetector\nfrom faced.utils import annotate_image\nimport copy\n\nimport cv2\n\nfrom pcml.datasets import image_aug\n\n\ndef take_photo(filename='photo.jpg', quality=0.8):\n  js = Javascript('''\n    async function takePhoto(quality) {\n      const div = document.createElement('div');\n\n      const video = document.createElement('video');\n      video.style.display = 'block';\n      const stream = await navigator.mediaDevices.getUserMedia({\n          video: { width: 256, height: 128 }\n      });\n\n      document.body.appendChild(div);\n      div.appendChild(video);\n      video.srcObject = stream;\n      video.style.visibility = \"hidden\";\n      await video.play();\n\n      // Resize the output to fit the video element.\n      google.colab.output.setIframeHeight(document.documentElement.scrollHeight, true);\n\n      const canvas = document.createElement('canvas');\n      canvas.width = video.videoWidth;\n      canvas.height = video.videoHeight;\n      canvas.getContext('2d').drawImage(video, 0, 0);\n      stream.getVideoTracks()[0].stop();\n\n      data = canvas.toDataURL('image/jpeg', quality);\n\n      div.remove();\n      canvas.remove();\n      video.remove();\n\n      return data\n    }\n    ''')\n  display(js)\n  return eval_js('takePhoto({})'.format(quality))\n\n\ndef load_image(img_string):\n  binary = b64decode(img_string.split(',')[1])\n  filename = \"/tmp/stream.jpeg\"\n  with open(filename, 'wb') as f:\n    f.write(binary)\n  img = Image.open(filename)\n  return np.array(img)\n\n\ndef _random_crop_square(image):\n\n  x,y,c = image.shape\n\n  x_crop_before = 0\n  x_crop_after = 0\n  y_crop_before = 0\n  y_crop_after = 0\n\n  if x > y:\n    x_crop = x - y\n    x_crop_before = np.random.randint(0, x_crop)\n    x_crop_after = x_crop - x_crop_before\n  elif y > x:\n    y_crop = y - x\n    y_crop_before = np.random.randint(0, y_crop)\n    y_crop_after = y_crop - y_crop_before\n\n  x_start = x_crop_before\n  x_end = x - x_crop_after\n  y_start = y_crop_before\n  y_end = y - y_crop_after\n\n  return image[x_start:x_end, y_start:y_end, :]\n\n\ndef _normalize_dimensions(image, target_shape):\n\n  image = _random_crop_square(image)\n\n  mn, mx = np.amin(image), np.amax(image)\n  if mn >=0 and mx <= 255:\n    image = image / 255.0\n\n  source_shape = image.shape\n  scale_x_factor = target_shape[0]/source_shape[0]\n  scale_y_factor = target_shape[1]/source_shape[1]\n  scale_x_first = (scale_x_factor <= scale_y_factor)\n\n  if scale_x_first:\n\n    new_x = target_shape[0]\n    new_y = int(source_shape[1]*scale_x_factor)\n    resize_dim = (new_x, new_y)\n    newimg = cv2.resize(image, resize_dim)\n    pad_width = target_shape[1] - new_y\n    if pad_width > 0:\n      # Pad in Y direction\n      newimg = np.pad(newimg, [(0,pad_width),(0,0),(0,0)], mode=\"mean\")\n\n  else:\n\n    new_y = target_shape[1]\n    new_x = int(source_shape[0]*scale_y_factor)\n    resize_dim = (new_x, new_y)\n    newimg = cv2.resize(image, resize_dim)\n    pad_width = target_shape[0] - new_x\n    if pad_width > 0:\n      # Pad in X direction\n      newimg = np.pad(newimg, [(0,0),(0,pad_width),(0,0)], mode=\"mean\")\n\n  newimg = (newimg*255.0).astype(np.int64)\n\n  return newimg\n\n\ndef detect_and_preprocess(image):\n\n  detector = FaceDetector()\n  detect_threshold = 0.5\n  predictions = detector.predict(image, detect_threshold)\n\n  xcenter = predictions[0][0]\n  ycenter = predictions[0][1]\n  width = predictions[0][2]*1.80\n  height = predictions[0][3]*1.80\n\n  xmax = image.shape[1]\n  ymax = image.shape[0]\n\n  ystart = max(0,int(ycenter-height/2))\n  yend = min(ymax,int(ycenter+height/2))\n  xstart = max(0,int(xcenter-width/2))\n  xend = min(xmax,int(xcenter+width/2))\n\n  img_with_face = image[ystart:yend,xstart:xend,:]\n\n  image_shape = (128,128,3)\n  img_post = _normalize_dimensions(img_with_face, target_shape=image_shape)\n\n  return img_post\n\n```\n\n\n<p style=\"color: red;\">\nThe default version of TensorFlow in Colab will soon switch to TensorFlow 2.x.<br>\nWe recommend you <a href=\"https://www.tensorflow.org/guide/migrate\" target=\"_blank\">upgrade</a> now \nor ensure your notebook will continue to use TensorFlow 1.x via the <code>%tensorflow_version 1.x</code> magic:\n<a href=\"https://colab.research.google.com/notebooks/tensorflow_version.ipynb\" target=\"_blank\">more info</a>.</p>\n\n\n\n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/expert_utils.py:68: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n    \n    WARNING:tensorflow:\n    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      * https://github.com/tensorflow/io (for I/O related ops)\n    If you depend on functionality not listed there, please file an issue.\n    \n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/adafactor.py:27: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead.\n    \n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/multistep_optimizer.py:32: The name tf.train.AdamOptimizer is deprecated. Please use tf.compat.v1.train.AdamOptimizer instead.\n    \n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/models/research/glow_init_hook.py:25: The name tf.train.SessionRunHook is deprecated. Please use tf.estimator.SessionRunHook instead.\n    \n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/models/research/neural_stack.py:38: The name tf.nn.rnn_cell.RNNCell is deprecated. Please use tf.compat.v1.nn.rnn_cell.RNNCell instead.\n    \n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/rl/gym_utils.py:235: The name tf.logging.info is deprecated. Please use tf.compat.v1.logging.info instead.\n    \n    INFO:tensorflow:Entry Point [tensor2tensor.envs.tic_tac_toe_env:TicTacToeEnv] registered with id [T2TEnv-TicTacToeEnv-v0]\n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/trainer_lib.py:111: The name tf.OptimizerOptions is deprecated. Please use tf.compat.v1.OptimizerOptions instead.\n    \n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_gan/python/estimator/tpu_gan_estimator.py:42: The name tf.estimator.tpu.TPUEstimator is deprecated. Please use tf.compat.v1.estimator.tpu.TPUEstimator instead.\n    \n    WARNING:tensorflow:From /content/clarify/pcml/models/dev.py:35: The name tf.logging.set_verbosity is deprecated. Please use tf.compat.v1.logging.set_verbosity instead.\n    \n    WARNING:tensorflow:From /content/clarify/pcml/models/dev.py:35: The name tf.logging.DEBUG is deprecated. Please use tf.compat.v1.logging.DEBUG instead.\n    \n\n\n# Prototypes\n\n##### Basic JS in colab\n\n\n```javascript\n%%javascript\nfunction dev() {\n  return 1\n}\nfunction dev2() {\n  return dev()\n}\nconsole.log(dev2())\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n##### Basic HTMLElement subclass, HTTP request\n\n\n```\n# Display a basic HTMLElement subclass that makes an HTTP request\n\nimport IPython\ndisplay(IPython.display.HTML('''\n\n  <head>\n\n  \n\n  </head>\n\n  <body>\n    <fx-component></fx-component>\n  </body>\n\n'''))\n```\n\n\n\n\n<head>\n\n\n\n</head>\n\n<body>\n\n  <fx-component></fx-component>\n\n</body>\n\n\n\n\n###### LitElement in Colab\n\nHere are some docs to get started:\n- https://lit-element.polymer-project.org/\n- https://lit-element.polymer-project.org/try\n\n\n```\ndisplay(IPython.display.HTML('''\n\n  <head>\n\n  \n\n  </head>\n\n  <body>\n    <fx-component></fx-component>\n  </body>\n\n'''))\n```\n\n##### Polymer component in colab\n\nFor debugging tried Polymer < 3.0. This does not currently work.\n\n\n```\nimport IPython\ndisplay(IPython.display.HTML('''\n\n  <head>\n\n  <link rel=\"import\"  href=\"https://polygit.org/polymer+^1.9.1/webcomponentsjs+^0.7.0/components/polymer/polymer.html\">\n\n  \n\n  </head>\n\n  <body>\n    <proto-element></proto-element>\n  </body>\n\n'''))\n\n```\n\n##### Call python model from JS\n\nTowards taking the place of a remote HTTP query in the interest of simplicity while developing new FX components.\n\n\n```\nimport IPython\nfrom google.colab import output\n\ndef infer_state_from_image(input_tensor):\n  # Use display.JSON to transfer a structured result.\n  return IPython.display.JSON({'result': 1234})\n\noutput.register_callback('notebook.infer_state_from_image', infer_state_from_image)\n\n```\n\n\n```javascript\n\n%%javascript\n(async function() {\n\n  const result = await google.colab.kernel.invokeFunction(\n    'notebook.infer_state_from_image', // The callback name.\n    ['image_data'], // The arguments.\n    {}); // kwargs\n\n  const text = result.data['application/json'];\n\n  document.querySelector(\"#output-area\").appendChild(document.createTextNode(text.result));\n\n})();\n\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n##### Faster js -> python image capture\n\nThis was the method used in the first notebook that was built and was somewhat slow. It could be sped up, perhaps by not removing and recreating media elements or we could opt for a different way of interoperating between python and js. \n\n\n```\nfrom IPython.display import display, Javascript\nfrom google.colab.output import eval_js\nfrom base64 import b64decode\nimport cv2\nimport numpy as np\n\nimport matplotlib\n%matplotlib inline\n\nfrom matplotlib.pyplot import imshow \n\n\ndef get_frame(filename='photo.jpg', quality=0.8):\n  \"\"\"Some description of your FX demo.\"\"\"\n\n  js = Javascript('''\n\n    async function takePhoto(quality=1234) {\n\n      const div = document.createElement('div');\n\n      const video = document.createElement('video');\n      video.style.display = 'block';\n      const stream = await navigator.mediaDevices.getUserMedia({video: true});\n\n      document.body.appendChild(div);\n      div.appendChild(video);\n      video.srcObject = stream;\n      await video.play();\n\n      // Resize the output to fit the video element.\n      google.colab.output.setIframeHeight(document.documentElement.scrollHeight, true);\n\n      const canvas = document.createElement('canvas');\n      canvas.width = video.videoWidth;\n      canvas.height = video.videoHeight;\n      canvas.getContext('2d').drawImage(video, 0, 0);\n      stream.getVideoTracks()[0].stop();\n      div.remove();\n      return canvas.toDataURL('image/jpeg', quality);\n    }\n    ''')\n\n  display(js)\n\n  data = eval_js('takePhoto({})'.format(1234))\n\n  data = b64decode(data.split(',')[1])\n\n  img = cv2.imdecode(np.frombuffer(data, dtype=np.uint8),\n                     cv2.IMREAD_COLOR)\n  img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n  return img\n\ndata = get_frame()\n\nimshow(data)\n\n```\n\n##### Eager-mode inference\n\nCode for the previous demo that did inference in TensorFlow Eager mode. Requires the runtime to be re-set each time the model is re-stored from a checkpoint.\n\n\n```\n%tensorflow_version 1.x\nimport tensorflow as tf\n\ntfe = tf.contrib.eager\ntfe.enable_eager_execution()\nModes = tf.estimator.ModeKeys\n\nfrom IPython.display import display, Javascript\nfrom google.colab.output import eval_js\nfrom base64 import b64decode\nimport base64\n\nimport io\nimport numpy as np\n\nfrom PIL import Image\n\nfrom faced import FaceDetector\nfrom faced.utils import annotate_image\nimport copy\n\nimport cv2\n\nimport matplotlib\n%matplotlib inline\n\nfrom matplotlib import pyplot as plt\n\nfrom pcml.models import percep_similarity_emb\n\nfrom tensor2tensor.utils import registry\n\nfrom pcml.datasets import image_aug\n\nfrom tensor2tensor.serving import serving_utils\n\nfrom tensorflow_serving.apis import predict_pb2\nfrom tensorflow_serving.apis import prediction_service_pb2_grpc\nfrom pcml.utils.dev_utils import run_server, wait_for_server_ready\n\nfrom gtts import gTTS\nfrom IPython.display import (\n    Audio, display, clear_output)\nimport time\n\nproblem_name = \"facial_expression_correspondence\"\nmodel_name = \"percep_similarity_triplet_emb\"\nhparams_set_name = \"percep_similarity_triplet_emb\"\nmode = \"predict\"\nckpt_dir = \"/tmp/output\"\ndata_dir = ckpt_dir\nexport_dir = \"/tmp/output/export\"\n\nhparams = registry.hparams(hparams_set_name)\nhparams.data_dir = data_dir\n\nproblem_obj = registry.problem(problem_name)\n\np_hparams = problem_obj.get_hparams(hparams)\n\nmodel_obj = registry.model(model_name)\n\n\ndef get_example():\n\n  image_stats = {\"mean\": [0.330, 0.537, -0.242], \"sd\": [0.220, 0.169, 1.156]}\n  shape = (64,64,3)\n  mode = \"eval\"\n\n  img = np.asarray((load_image(take_photo())))\n  \n  img = detect_and_preprocess(img)\n\n  # Convert to int32\n\n  example = {\n    \"image/a\": img,\n    \"image/b\": img,\n    \"image/c\": img,\n    \"image/a/noaug\": img,\n    \"image/b/noaug\": img,\n    \"image/c/noaug\": img,\n    \"triplet_code\": [0],\n    \"type\": [1],\n    \"targets\": img\n  }\n\n  def _preproc(image):\n\n    image = image_aug.preprocess_image(\n      image, mode,\n      resize_size=shape,\n      normalize=True,\n      image_statistics=image_stats,\n      crop_area_min=1,\n      contrast_lower=0.45,\n      contrast_upper=0.55,\n      brightness_delta_min=-0.01,\n      brightness_delta_max=0.01)\n\n    image.set_shape(shape)\n\n    return image\n\n  example[\"image/a\"] = tf.expand_dims(_preproc(example[\"image/a\"]),0)\n  example[\"image/b\"] = tf.expand_dims(_preproc(example[\"image/b\"]),0)\n  example[\"image/c\"] = tf.expand_dims(_preproc(example[\"image/c\"]),0)\n  example[\"triplet_code\"] = tf.expand_dims(tf.cast(example[\"triplet_code\"], tf.int64),0)\n\n  return example\n\n```\n\n\n```\n\ndef _goal_from_goals(goals):\n  return goals[0]\n\n\ndef _tts(msg):\n  filename = \"/tmp/clarify-tmp.mp3\"\n  tts = gTTS(msg)\n  tts.save(filename)\n  display(Audio(filename, autoplay=True))\n\n\ndef play_instructions():\n  message = \"Goal definition will begin in twenty seconds following a tone and will \"\n  message += \"last for ten seconds. Please assume a mental state that you want to \"\n  message += \"be your goal. The definition period will begin in seven seconds.\"\n  _tts(message)\n  time.sleep(20)\n  synth(600)\n\n\ndef play_beginning_session():\n  _tts(\"Goal definition complete. Beginning session.\")\n  time.sleep(3)\n\n\ndef play_establishing_baseline():\n  _tts(\"Establishing baseline. Please demonstrate a variety of expressions and poses.\")\n  time.sleep(3)\n\n\ndef play_baseline_complete():\n  _tts(\"Finished establishing baseline.\")\n  time.sleep(3)\n\n\ndef synth(f):\n  rate = 16000.\n  duration = .25\n  t = np.linspace(\n    0., duration, int(rate * duration))\n\n  x = np.sin(f * 2. * np.pi * t)\n  display(Audio(x, rate=rate, autoplay=True))\n\n\ndef optimize():\n\n  play_instructions()\n\n  query_data = {}\n\n  synth_min = 200\n  synth_max = 600\n  synth_range = synth_max - synth_min\n\n  mn = None\n  mx = None\n\n  goals = []\n  goal = None\n\n  distance_threshold = 1.3\n\n  num_sampled = 0\n\n  baseline = True\n\n  distances = []\n  examples = []\n  num_baseline_steps = 0\n\n  with tfe.restore_variables_on_create(tf.train.latest_checkpoint(ckpt_dir)):\n\n    model = model_obj(hparams, mode, p_hparams)\n\n    while True:\n\n      print(\"Doing step...\")\n\n      try:\n\n        example = get_example()\n        current, _ = model(example)\n\n        num_sampled += 1\n\n        if num_sampled <= 3:\n\n          goals.append(current)\n          distances.append(0)\n          examples.append(example)\n\n        else:\n\n          if goal is None:\n            goal = _goal_from_goals(goals)\n            play_beginning_session()\n\n          dist = np.linalg.norm(current - goal)\n          print(dist)\n\n          distances.append(dist)\n          examples.append(example)\n\n          if not mn:\n            mn = dist\n          if not mx:\n            mx = dist\n\n          if dist < mn:\n            mn = dist\n\n          if dist > mx:\n            mx = dist\n\n          if num_sampled == 4:\n            play_establishing_baseline()\n\n          synth_level = synth_min + synth_range*((dist-mn)/(mx-mn))\n\n          #if distances:\n          #  distance_threshold = np.mean(distances)\n\n          print(synth_level)\n          if dist > distance_threshold:\n            synth(synth_level)\n\n          if num_sampled == 20:\n            play_baseline_complete()\n            baseline = False\n            num_baseline_steps = num_sampled\n\n      except (KeyboardInterrupt, SystemExit):\n        break\n\n      except:\n        raise\n        print(\"there was an exception but we're not worried ;D\")\n\n  return locals()\n```\n\n\n```\noptimize()\n```\n\nCritical assessment:\n\n* It seems useful representations of goal vs. non-goal states are being made and there is a strong technical foundation for building state-based feedback experiences.\n* This particular form of feedback experience can be improved in various ways. For one, it's distracting. Tones are uncomfortable and irregular (perhaps better to have these be continuous). Also, when a tone is played it interrupts music playing by temporarily turning down its volume - instead, regulation of system volume could itself be the feedback cue (i.e. on-target is desired volume).\n\n\n##### Query locally served model\n\nTODO: This is just temporary and to avoid having to restart the runtime for each run of the demo.\n\n###### Run the server\n\nNeeds load_image and take_photo from eager section above\n\n\n```\n# Make sure you have actually obtained the checkpoint\n!ls /tmp/output | wc -l\n```\n\n    68\n\n\n\n```\n\nimport numpy as np\n\nfrom pcml.utils.dev_utils import run_server, wait_for_server_ready\n\nfrom pcml.models import percep_similarity_emb\nfrom tensor2tensor.serving import serving_utils\n\nfrom tensorflow_serving.apis import predict_pb2\nfrom tensorflow_serving.apis import prediction_service_pb2_grpc\n\nproblem_name = \"facial_expression_correspondence\"\nmodel_name = \"percep_similarity_triplet_emb\"\nhparams_set_name = \"percep_similarity_triplet_emb\"\nmode = \"predict\"\nckpt_dir = \"/tmp/output\"\ndata_dir = ckpt_dir\nexport_dir = \"/tmp/output/export\"\n\ntfms_path = \"/usr/bin/tensorflow_model_server\"\n!ls {tfms_path}\n\n_, server, _ = run_server(\n    model_name,\n    export_dir,\n    tfms_path\n)\n\nwait_for_server_ready(server)\n\ndef prepare_request():\n\n  img = np.asarray((load_image(take_photo())))\n\n  img = detect_and_preprocess(img)\n\n  image_feature = tf.train.Feature(int64_list=tf.train.Int64List(value=img.flatten().tolist()))\n\n  ex = tf.train.Example(features=tf.train.Features(feature={\n    \"image/a\": image_feature,\n    \"image/b\": image_feature,\n    \"image/c\": image_feature,\n    \"triplet_code\": tf.train.Feature(int64_list=tf.train.Int64List(value=[0] * 1)),\n    \"type\": tf.train.Feature(int64_list=tf.train.Int64List(value=[0] * 1)),\n    \"rating/mode\": tf.train.Feature(int64_list=tf.train.Int64List(value=[0] * 1)),\n    \"targets\": tf.train.Feature(int64_list=tf.train.Int64List(value=[0] * 1))\n  }))\n\n  return ex\n\n\ndef single_served_model_request(ex, servable_name):\n\n  proto = tf.make_tensor_proto([ex.SerializeToString()], shape=[1])\n\n  request = predict_pb2.PredictRequest()\n  request.model_spec.name = model_name\n  request.inputs[\"input\"].CopyFrom(proto)\n\n  response = stub.Predict(request, timeout_secs)\n  outputs = tf.make_ndarray(response.outputs[\"outputs\"])\n  return outputs[0]\n  \n\ntimeout_secs = 5\nstub = serving_utils._create_stub(server)\n\n```\n\n###### Make requests\n\n\n```\n# Make an expression that will be the goal\ngoal = single_served_model_request(prepare_request(), model_name)\n```\n\n\n```\n# Collect a series of on-target images\non_target = []\nfor i in range(20):\n  on_target.append(single_served_model_request(prepare_request(), model_name))\n```\n\n\n```\n# Collect a series of off-target images\noff_target = []\nfor i in range(20):\n  off_target.append(single_served_model_request(prepare_request(), model_name))\n```\n\n\n```\nimport numpy as np\n\n# The distances off-target should be larger than on-target\n\nprint(\"on-target\")\ntot_on = 0\nfor emb in on_target:\n  d = np.linalg.norm(goal-emb)\n  tot_on += d\n  print(d)\nprint(\"on target mean distance: {}\".format(tot_on/len(on_target)))\n\nprint(\"\\n\")\n\nprint(\"off-target\")\ntot_off = 0\nfor emb in off_target:\n  d = np.linalg.norm(goal-emb)\n  tot_off += d\n  print(d)\nprint(\"on target mean distance: {}\".format(tot_off/len(off_target)))\n\n```\n", "meta": {"hexsha": "d4a9e2372a01326414ac56ca5062cf340512544a", "size": 166392, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "client/fx-dev.ipynb", "max_stars_repo_name": "hmallen99/project_clarify", "max_stars_repo_head_hexsha": "2753e82046a8fa94e55165f84b154ecdacdeb558", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-01-24T20:53:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-02T11:18:56.000Z", "max_issues_repo_path": "client/fx-dev.ipynb", "max_issues_repo_name": "projectclarify/clarify", "max_issues_repo_head_hexsha": "c642f3089feb35b2e0be5349c660e138e33b23d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 123, "max_issues_repo_issues_event_min_datetime": "2020-01-16T00:29:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T23:39:36.000Z", "max_forks_repo_path": "client/fx-dev.ipynb", "max_forks_repo_name": "hmallen99/project_clarify", "max_forks_repo_head_hexsha": "2753e82046a8fa94e55165f84b154ecdacdeb558", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-02-01T05:11:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-22T23:35:45.000Z", "avg_line_length": 70.3262890955, "max_line_length": 791, "alphanum_fraction": 0.6264604068, "converted": true, "num_tokens": 45250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28140560742914383, "lm_q2_score": 0.04084571299100987, "lm_q1q2_score": 0.011494212675111604}}
{"text": "# IPython Sihirli \u0130fadeler\n\nIPython, etkile\u015fimli olarak rahat ve verimli \u00e7al\u0131\u015fmay\u0131 sa\u011flayan Python programlama diline \u00f6zel tan\u0131mlanm\u0131\u015f komutlar sunar. Sihirli ifadeler IPython \u00e7ekirde\u011fine \u00f6zg\u00fc olduklar\u0131 i\u00e7in sadece Python ile \u00e7al\u0131\u015f\u0131rlar. Jupyter\u2019in destekledi\u011fi di\u011fer diller (R, Julia, vd.) \u015fimdilik bu \u00f6zelli\u011fe sahip de\u011filler.IPython Notebook asl\u0131nda Jupyter Notebook'un \u00f6nceki verisyonu diyebiliriz.Jupyter \u00f6zelliklerini IPython\u2018dan al\u0131nm\u0131\u015f, ve yorumlanabilir herhangi birden fazla dili destekleyecek \u015fekilde geli\u015ftirilmi\u015ftir. Hatta Jupyter ad\u0131, tasarland\u0131\u011f\u0131 \u00fc\u00e7 temel dilin dolayl\u0131 bir k\u0131saltmas\u0131d\u0131r: **JU**lia, **PYT**hon ve **R** ve Jupiter gezegeninden esinlenilmi\u015ftir. \n\nJupyter IPython\u0131n \u00f6zelliklerini devralm\u0131\u015ft\u0131r. Bu dok\u00fcmanda Jupyter\u2018in devrald\u0131\u011f\u0131 IPython \u00f6zelliklerinden biri de sihirli ifadeler (line magic/cell magic) denen baz\u0131 kolayla\u015ft\u0131r\u0131c\u0131, \u00f6zelle\u015fmi\u015f komutlardan bahsedece\u011fim.Line Magic(sat\u0131r sihirleri) % karakteri ile eklenir ve OS komut sat\u0131r\u0131 \u00e7a\u011fr\u0131lar\u0131 gibi \u00e7al\u0131\u015f\u0131r, yaln\u0131zca ge\u00e7erli sat\u0131r\u0131n sonuna kadar uzanan komutlard\u0131r. Burada ba\u011f\u0131ms\u0131z de\u011fi\u015fkenler parantez veya t\u0131rnak i\u015faretleri olmadan iletilir. Cell Magic(h\u00fccre sihirleri) \u00f6n\u00fcne %% double eklenir ve yaln\u0131zca sat\u0131r\u0131n geri kalan\u0131n\u0131 de\u011fil, ayn\u0131 zamanda alt\u0131ndaki sat\u0131rlar\u0131 da ba\u011f\u0131ms\u0131z bir ba\u011f\u0131ms\u0131z de\u011fi\u015fken olarak alan i\u015flevlerdir. Sihirli ifadeler sadece h\u00fccre baz\u0131nda uygulanabilir, genele yay\u0131lamayaca\u011f\u0131n\u0131 unutmamak gerekir.\n\n% lsmagic komutu t\u00fcm sihirleri listelemek i\u00e7in kullan\u0131l\u0131r.\n\n\n\n```python\n%lsmagic\n```\n\n\n\n\n    Available line magics:\n    %alias  %alias_magic  %autoawait  %autocall  %automagic  %autosave  %bookmark  %cd  %clear  %cls  %colors  %conda  %config  %connect_info  %copy  %ddir  %debug  %dhist  %dirs  %doctest_mode  %echo  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %less  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %macro  %magic  %matplotlib  %mkdir  %more  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %pip  %popd  %pprint  %precision  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %ren  %rep  %rerun  %reset  %reset_selective  %rmdir  %run  %save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode\n    \n    Available cell magics:\n    %%!  %%HTML  %%SVG  %%bash  %%capture  %%cmd  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%markdown  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile\n    \n    Automagic is ON, % prefix IS NOT needed for line magics.\n\n\n\n**NOT:** Sihirli kelimeyi yaz\u0131p Shift-Tab bast\u0131\u011f\u0131n\u0131zda bir yard\u0131m balonu \u00e7\u0131kar. \n\n\n\nSihirli ifadelerin kullan\u0131m\u0131n\u0131n \u00f6zeti ve her bir komutun k\u0131sa a\u00e7\u0131klamas\u0131 i\u00e7in **%quickref** komutunu, sihirli ifadelerin tam ve kapsaml\u0131 bir referans\u0131 i\u00e7in **%magic** komutunu kullanabilirsiniz.\n\n\n\n\n\n\u015eimdi sihirli ifadelerden birka\u00e7\u0131n\u0131n nas\u0131l kullan\u0131ld\u0131\u011f\u0131n\u0131 inceleyelim.\n\n## Baz\u0131 Sihirli Komutlar\u0131n Kullan\u0131m\u0131na \u00d6rnekler\n\n> **%run** komutu ile python kodunuzu ve jupyter notebook kodunuz \u00e7al\u0131\u015ft\u0131rabiliriniz.\n\nBa\u015fka bir notta yer alan kodumuz:\n\n\n\n```python\n%run C:\\Users\\Okul\\Desktop\\JupyterExample\\example.ipynb\n```\n\n\n\n> **%store** komutu, de\u011fi\u015fkenleri iki farkl\u0131 not defteri aras\u0131nda ge\u00e7irmenizi yani de\u011fi\u015fkenlerin kal\u0131c\u0131 olmas\u0131n\u0131 sa\u011flar.Bu i\u015flemi de\u011fi\u015fkenleri sabit diske kaydederek ger\u00e7ekle\u015ftirir.\n\nBa\u015fka bir notta yer alan kodumuz:\n\n\n\n```python\n%store -r cumle\nprint(cumle)\n```\n\n    C\u00fcmlemin kal\u0131c\u0131 olmas\u0131n\u0131 istiyorum.\n\n\n> **%who** komutu defterde tan\u0131mlanm\u0131\u015f de\u011fi\u015fkenlerin listelenmesini sa\u011flar. Str (int,float,long,bool vb.) gibi bir parametre iletildi\u011finde yaln\u0131zca bu t\u00fcrdeki de\u011fi\u015fkenler listelenir. **%reset** komutu defterde tan\u0131mlanm\u0131\u015f de\u011fi\u015fkenlerin listelenmesini sa\u011flar.  Mod\u00fcllerde tan\u0131mlanm\u0131\u015f isimlere dokunmaz.\n\n\n```python\nJupyterNotebook = \"IPython Notebook\"\npi = 3.141592654\n```\n\n\n```python\n%who str\n```\n\n    JupyterNotebook\t cumle\t \n\n\n**NOT:**  %store komutu ile sabit diske kaydedilen de\u011fi\u015fken varsa listede gelir.\n\n\n```python\n%reset\n```\n\n    Once deleted, variables cannot be recovered. Proceed (y/[n])? Y\n\n\n\n```python\n%who str\n```\n\n    No variables match your requested type.\n\n\n> **%%writefile** ve **%pycat** komutlar\u0131 s\u0131ras\u0131yla bir h\u00fccrenin i\u00e7eri\u011fini d\u0131\u015fa aktar\u0131lmas\u0131n\u0131 yani i\u00e7eri\u011fin harici bir dosyaya kaydedilmesini ve harici bir komut dosyas\u0131n\u0131n i\u00e7eri\u011fini g\u00f6sterilmesini sa\u011flar.\n\n\n```python\n%%writefile example2.py\n\nimport numpy\ndef append_if_not_exists(arr, x):\n    if x not in arr:\n        arr.append(x)\n\ndef some_useless_slow_function():\n    arr = list()\n    for i in range(10000):\n        x = numpy.random.randint(0, 10000)\n        append_if_not_exists(arr, x)\n```\n\n    Overwriting example2.py\n\n\nKodu \u00e7al\u0131\u015ft\u0131rd\u0131ktan sonra otomatik olarak example2.py dosyas\u0131 olu\u015fturuldu.\n\n\n\n\n```python\n%pycat example2.py\n```\n\nKodu \u00e7al\u0131\u015ft\u0131rd\u0131ktan sonra harici bir pencerede kodu g\u00f6r\u00fcnt\u00fcleyebildim.\n\n\n\n> **%prun** program\u0131n\u0131z\u0131n her bir i\u015fleve ne kadar zaman harcad\u0131\u011f\u0131n\u0131 g\u00f6stermeye yarar.Her dahili i\u015flevin ifade i\u00e7inde ka\u00e7 kez \u00e7a\u011fr\u0131ld\u0131\u011f\u0131n\u0131, her \u00e7a\u011fr\u0131n\u0131n zaman\u0131n\u0131 ve i\u015flevin t\u00fcm \u00e7al\u0131\u015fmalar\u0131n\u0131n toplam s\u00fcresini g\u00f6steren s\u0131ral\u0131 bir tablo elde edersiniz.\n\n\n\n\n> **%time,%%time** ve **%time\u0131t,%%timeit** komutlar\u0131 zamanlama i\u00e7in yararl\u0131 komutlard\u0131r, yava\u015f kodunuz oldu\u011funda ve sorunun nerede oldu\u011funu belirlemeye \u00e7al\u0131\u015f\u0131rken \u00f6zellikle kullan\u0131\u015fl\u0131d\u0131r. %time,%%time size h\u00fccrenizdeki kodun tek bir \u00e7al\u0131\u015ft\u0131r\u0131lma s\u00fcresi hakk\u0131nda bilgi verecektir. %time\u0131t,%%timeit ard\u0131ndan gelen Python komutunu bir d\u00f6ng\u00fc i\u00e7inde bir\u00e7ok defa \u00e7al\u0131\u015ft\u0131r\u0131r, sonra ortalama s\u00fcreyi bulur. Bunu birka\u00e7 defa tekrarlar ve elde etti\u011fi sonucu ortalama ve standart sapma olarak verir.\n\n\n```python\n%%time\nimport time\nfor _ in range(1000):\n    time.sleep(0.01) # sleep for 0.01 seconds\n```\n\n    Wall time: 13.5 s\n\n\n\n```python\nimport numpy\n%timeit numpy.random.normal(size=100)\n```\n\n    5.49 \u00b5s \u00b1 109 ns per loop (mean \u00b1 std. dev. of 7 runs, 100000 loops each)\n\n\n> **%qtconsole** komutu yeni bir terminal terminal a\u00e7mak i\u00e7in kullan\u0131l\u0131r.Defterinizin ak\u0131\u015f\u0131na m\u00fcdahale etmeden i\u015flem yapmak istedi\u011finizde, ayr\u0131 bir pencerede bir IPython penceresi a\u00e7abilirsiniz.\n\n\n```python\n%qtconsole\n```\n\n\n\n\nAnlatmak istedi\u011fim sihirli s\u00f6zc\u00fckler \u015fimdilik bu kadar.\nBirazda Ipythonun sahip oldu\u011fu zengin \u00e7\u0131kt\u0131lara g\u00f6z atal\u0131m.\n\n> **%%html** h\u00fccredeki HTML kodunu i\u015fler ve HTML belgesini ekrana verir. **%%javascript** html mant\u0131\u011f\u0131yla ayn\u0131 \u015fekilde js kodu da ekleyebiliriz.\n\n\n```python\n%%html\n<!DOCTYPE html>\n<html>\n<head>\n<style>\ntable {\n  font-family: arial, sans-serif;\n  border-collapse: collapse;\n  width: 100%;\n}\n\ntd, th {\n  border: 1px solid #dddddd;\n  text-align: left;\n  padding: 8px;\n}\n\ntr:nth-child(even) {\n  background-color: #dddddd;\n}\n    \n.rendered_html tr, .rendered_html th, .rendered_html td {\n    padding: 0.5em 9.9em;\n    \n</style>\n</head>\n<body>\n\n<h2>HTML Table</h2>\n\n<table>\n  <tr>\n    <th>Company</th>\n    <th>Contact</th>\n    <th>Country</th>\n  </tr>\n  <tr>\n    <td>Alfreds Futterkiste</td>\n    <td>Maria Anders</td>\n    <td>Germany</td>\n  </tr>\n  <tr>\n    <td>Centro comercial Moctezuma</td>\n    <td>Francisco Chang</td>\n    <td>Mexico</td>\n  </tr>\n  <tr>\n    <td>Ernst Handel</td>\n    <td>Roland Mendel</td>\n    <td>Austria</td>\n  </tr>\n  <tr>\n    <td>Island Trading</td>\n    <td>Helen Bennett</td>\n    <td>UK</td>\n  </tr>\n  <tr>\n    <td>Laughing Bacchus Winecellars</td>\n    <td>Yoshi Tannamuri</td>\n    <td>Canada</td>\n  </tr>\n  <tr>\n    <td>Magazzini Alimentari Riuniti</td>\n    <td>Giovanni Rovelli</td>\n    <td>Italy</td>\n  </tr>\n</table>\n\n</body>\n</html>\n\n\n\n```\n\n\n<!DOCTYPE html>\n<html>\n<head>\n<style>\ntable {\n  font-family: arial, sans-serif;\n  border-collapse: collapse;\n  width: 100%;\n}\n\ntd, th {\n  border: 1px solid #dddddd;\n  text-align: left;\n  padding: 8px;\n}\n\ntr:nth-child(even) {\n  background-color: #dddddd;\n}\n\n.rendered_html tr, .rendered_html th, .rendered_html td {\n    padding: 0.5em 9.9em;\n\n</style>\n</head>\n<body>\n\n<h2>HTML Table</h2>\n\n<table>\n  <tr>\n    <th>Company</th>\n    <th>Contact</th>\n    <th>Country</th>\n  </tr>\n  <tr>\n    <td>Alfreds Futterkiste</td>\n    <td>Maria Anders</td>\n    <td>Germany</td>\n  </tr>\n  <tr>\n    <td>Centro comercial Moctezuma</td>\n    <td>Francisco Chang</td>\n    <td>Mexico</td>\n  </tr>\n  <tr>\n    <td>Ernst Handel</td>\n    <td>Roland Mendel</td>\n    <td>Austria</td>\n  </tr>\n  <tr>\n    <td>Island Trading</td>\n    <td>Helen Bennett</td>\n    <td>UK</td>\n  </tr>\n  <tr>\n    <td>Laughing Bacchus Winecellars</td>\n    <td>Yoshi Tannamuri</td>\n    <td>Canada</td>\n  </tr>\n  <tr>\n    <td>Magazzini Alimentari Riuniti</td>\n    <td>Giovanni Rovelli</td>\n    <td>Italy</td>\n  </tr>\n</table>\n\n</body>\n</html>\n\n\n\n\n\n> **%latex** komutu ile taray\u0131c\u0131da MathJax kullan\u0131larak olu\u015fturulan LaTeX'te matematiksel ifadelerin g\u00f6r\u00fcnt\u00fclenmesi sa\u011flan\u0131r.\n\n\n```python\nfrom IPython.display import Latex\n```\n\n\n```latex\n%%latex\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n```\n\n\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n\n\n\n> **%matloblib** komutuyla, hangi arka y\u00fcz\u00fc kullanmak istedi\u011finizi belirleyebilirsiniz. Bir\u00e7ok Jupyter defter kullan\u0131c\u0131s\u0131, defterin ba\u015f\u0131nda %matplotlib inline komutunu vermeyi tercih eder. Bu sayede \u00fcretti\u011finiz matplotlib grafikleri defterin i\u00e7ine g\u00f6m\u00fcl\u00fcr ve tam bir belge olu\u015fturman\u0131z\u0131 sa\u011flar.\n\n\n```python\n%matplotlib --list\n```\n\n    Available matplotlib backends: ['tk', 'gtk', 'gtk3', 'wx', 'qt4', 'qt5', 'qt', 'osx', 'nbagg', 'notebook', 'agg', 'svg', 'pdf', 'ps', 'inline', 'ipympl', 'widget']\n\n\n\n```python\n%matplotlib notebook\n```\n\n**NOT:** matplotlib arka y\u00fcz\u00fcn\u00fc bir oturum i\u00e7inde sadece bir kere belirleyebilirsiniz. A\u015fa\u011f\u0131daki komutlar i\u00e7in \u00e7ekirde\u011fi tekrar ba\u015flatman\u0131z gerekecektir. \u00c7ekirde\u011fi, men\u00fc \u00e7ubu\u011funda Kernel -> Kernel Restart se\u00e7erek, veya iki kere s\u0131f\u0131ra basarak tekrar ba\u015flatabilirsiniz.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Polygon\nplt.figure()\nx = np.linspace(0, 5 * np.pi, 1000)\nfor n in range(1, 4):\n    plt.plot(np.sin(n * x))\nplt.show()\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n", "meta": {"hexsha": "5a27ab2e30539e0687d3249814f9d475342fb9d0", "size": 205889, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "IPythonMagics.ipynb", "max_stars_repo_name": "GizemKoyuncu/Jupyter-Notebook-Tutorial", "max_stars_repo_head_hexsha": "f1be7b214bd1f6dfa2d57bf1b44041e94d15c25c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-28T19:10:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-28T19:10:12.000Z", "max_issues_repo_path": "IPythonMagics.ipynb", "max_issues_repo_name": "GizemKoyuncu/Jupyter-Notebook-Tutorial", "max_issues_repo_head_hexsha": "f1be7b214bd1f6dfa2d57bf1b44041e94d15c25c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IPythonMagics.ipynb", "max_forks_repo_name": "GizemKoyuncu/Jupyter-Notebook-Tutorial", "max_forks_repo_head_hexsha": "f1be7b214bd1f6dfa2d57bf1b44041e94d15c25c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 126.7009230769, "max_line_length": 146812, "alphanum_fraction": 0.8341776394, "converted": true, "num_tokens": 3879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11124120356108878, "lm_q2_score": 0.10230470173440494, "lm_q1q2_score": 0.011380498150893412}}
{"text": "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Sao-ph\u1ea3i-Quan-t\u00e2m?\" data-toc-modified-id=\"Sao-ph\u1ea3i-Quan-t\u00e2m?-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Sao ph\u1ea3i Quan t\u00e2m?</a></span><ul class=\"toc-item\"><li><span><a href=\"#Khoa H\u1ecdc D\u1eef Li\u1ec7u-Kh\u00f4ng-c\u00f2n-l\u00e0-N\u00f3-Tr\u01b0\u1edbc-\u0111\u00e2y-(ho\u1eb7c-N\u00f3-c\u1ee7a-Ng\u00e0y-sau)\" data-toc-modified-id=\"Khoa H\u1ecdc D\u1eef Li\u1ec7u-Kh\u00f4ng-c\u00f2n-l\u00e0-N\u00f3-Tr\u01b0\u1edbc-\u0111\u00e2y-(ho\u1eb7c-N\u00f3-c\u1ee7a-Ng\u00e0y-sau)-1.1\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;</span>Khoa H\u1ecdc D\u1eef Li\u1ec7u Kh\u00f4ng c\u00f2n l\u00e0 N\u00f3 Tr\u01b0\u1edbc \u0111\u00e2y (ho\u1eb7c N\u00f3 c\u1ee7a Ng\u00e0y sau)</a></span></li><li><span><a href=\"#Tr\u1ea3-l\u1eddi-nh\u1eefng-c\u00e2u-h\u1ecfi-kh\u00e1c-nhau\" data-toc-modified-id=\"Tr\u1ea3-l\u1eddi-nh\u1eefng-c\u00e2u-h\u1ecfi-kh\u00e1c-nhau-1.2\"><span class=\"toc-item-num\">1.2&nbsp;&nbsp;</span>Tr\u1ea3 l\u1eddi nh\u1eefng c\u00e2u h\u1ecfi kh\u00e1c nhau</a></span></li></ul></li><li><span><a href=\"#Khi-n\u00e0o--Quan h\u1ec7 t\u01b0\u01a1ng quan-l\u00e0--Quan h\u1ec7 nh\u00e2n qu\u1ea3\" data-toc-modified-id=\"Khi-n\u00e0o--Quan h\u1ec7 t\u01b0\u01a1ng quan-l\u00e0--Quan h\u1ec7 nh\u00e2n qu\u1ea3-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Khi n\u00e0o  Quan h\u1ec7 t\u01b0\u01a1ng quan l\u00e0  Quan h\u1ec7 nh\u00e2n qu\u1ea3</a></span></li><li><span><a href=\"#Thi\u00ean l\u1ec7ch\" data-toc-modified-id=\"Thi\u00ean l\u1ec7ch-3\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>Thi\u00ean l\u1ec7ch</a></span></li><li><span><a href=\"#\u00dd-t\u01b0\u1edfng-ch\u1ee7-\u0111\u1ea1o\" data-toc-modified-id=\"\u00dd-t\u01b0\u1edfng-ch\u1ee7-\u0111\u1ea1o-4\"><span class=\"toc-item-num\">4&nbsp;&nbsp;</span>\u00dd t\u01b0\u1edfng ch\u1ee7 \u0111\u1ea1o</a></span></li><li><span><a href=\"#T\u00e0i-li\u1ec7u-tham-kh\u1ea3o\" data-toc-modified-id=\"T\u00e0i-li\u1ec7u-tham-kh\u1ea3o-5\"><span class=\"toc-item-num\">5&nbsp;&nbsp;</span>T\u00e0i li\u1ec7u tham kh\u1ea3o</a></span></li></ul></div>\n\n# Sao ph\u1ea3i Quan t\u00e2m?\n\n\n## Khoa H\u1ecdc D\u1eef Li\u1ec7u Kh\u00f4ng c\u00f2n l\u00e0 N\u00f3 Tr\u01b0\u1edbc \u0111\u00e2y (ho\u1eb7c N\u00f3 c\u1ee7a Ng\u00e0y sau)\n\nChuy\u00ean gia d\u1eef li\u1ec7u \u0111\u01b0\u1ee3c l\u0103ng x\u00ea l\u00e0  [Ngh\u1ec1 nghi\u1ec7p Quy\u1ebfn r\u0169 nh\u1ea5t Th\u1ebf k\u1ec9 21](https://hbr.org/2012/10/data-scientist-the-sexiest-job-of-the-21st-century) b\u1edfi Harvard Business Review. \u0110\u00e2y kh\u00f4ng ph\u1ea3i l\u00e0 m\u1ed9t di\u1ec5n ng\u00f4n tr\u1ed1ng r\u1ed7ng. Trong th\u1eadp k\u1ec9 v\u1eeba qua, Chuy\u00ean Gia D\u1eef Li\u1ec7u  th\u1ef1c s\u1ef1 t\u1ecfa s\u00e1ng. C\u00e1c chuy\u00ean gia AI s\u1edf h\u1eefu [m\u1ee9c l\u01b0\u01a1ng kh\u00f4ng h\u1ec1 k\u00e9m c\u1ea1nh c\u00e1c si\u00eau sao th\u1ec3 thao](https://www.economist.com/business/2016/04/02/million-dollar-babies). Theo \u0111u\u1ed5i ti\u1ec1n t\u00e0i v\u00e0 danh v\u1ecdng, h\u00e0ng tr\u0103m c\u00e1c chuy\u00ean gia tr\u1ebb  lao \u0111\u1ea7u v\u00e0o cu\u1ed9c \u0111ua truy t\u00ecm kho b\u00e1u c\u1ed1 gi\u00e0nh danh hi\u1ec7u chuy\u00ean gia d\u1eef li\u1ec7u s\u1edbm nh\u1ea5t. Ng\u00e0nh ngh\u1ec1 m\u1edbi nh\u01b0 th\u1ec3 \u0111ang l\u00ean \u0111\u1ed3ng. M\u1ed9t v\u00e0i ph\u01b0\u01a1ng ph\u00e1p gi\u1ea3ng d\u1ea1y t\u00e2n ti\u1ebfn c\u00f3 th\u1ec3 gi\u00fap b\u1ea1n tr\u1edf th\u00e0nh m\u1ed9t chuy\u00ean gia d\u1eef li\u1ec7u m\u00e0 kh\u00f4ng ph\u1ea3i nh\u00ecn d\u00f9 ch\u1ec9 m\u1ed9t c\u00f4ng th\u1ee9c to\u00e1n h\u1ecdc. C\u00e1c chuy\u00ean gia t\u01b0 v\u1ea5n h\u1ee9a h\u1eb9n tri\u1ec7u \u0111\u00f4 n\u1ebfu c\u00f4ng ty c\u1ee7a b\u1ea1n c\u00f3 th\u1ec3 h\u00e9 m\u1edf ti\u1ec1m n\u0103ng d\u1eef li\u1ec7u. AI ho\u1eb7c, ML, \u0111\u01b0\u1ee3c g\u1ecdi l\u00e0 ngu\u1ed3n \u0111i\u1ec7n m\u1edbi v\u00e0 d\u1eef li\u1ec7u l\u00e0 m\u1ecf d\u1ea7u m\u1edbi.\n\nTrong khi \u1ea5y, ch\u00fang ta l\u00e3ng qu\u00ean c\u00e1c ng\u00e0nh khoa h\u1ecdc x\u01b0a c\u0169  v\u1ed1n v\u1eabn s\u1eed d\u1ee5ng d\u1eef li\u1ec7u t\u1eeb tr\u01b0\u1edbc \u0111\u1ebfn nay. X\u01b0a nay c\u00e1c chuy\u00ean gia kinh t\u1ebf c\u1ed1 tr\u1ea3 l\u1eddi \u0111\u00e2u l\u00e0 t\u00e1c \u0111\u1ed9ng th\u1ef1c s\u1ef1 c\u1ee7a gi\u00e1o d\u1ee5c \u0111\u1ed1i v\u1edbi thu nh\u1eadp. C\u00e1c chuy\u00ean gia th\u1ed1ng k\u00ea y sinh c\u1ed1 t\u00ecm hi\u1ec3u li\u1ec7u ch\u1ea5t b\u00e9o b\u00e3o h\u00f2a c\u00f3 l\u00e0m t\u0103ng nguy c\u01a1 nh\u1ed3i m\u00e1u c\u01a1 tim. C\u00e1c chuy\u00ean gia t\u00e2m l\u00fd nghi\u00ean c\u1ee9u li\u1ec7u nh\u1eefng l\u1eddi x\u00e1c nh\u1eadn c\u00f3 l\u00e0m h\u00f4n nh\u00e2n h\u1ea1nh ph\u00fac h\u01a1n. Th\u00e0nh th\u1eadt m\u00e0 n\u00f3i, khoa h\u1ecdc d\u1eef li\u1ec7u kh\u00f4ng ph\u1ea3i l\u00e0 m\u1ed9t ng\u00e0nh khoa h\u1ecdc m\u1edbi. B\u1ea1n ch\u1ec9 bi\u1ebft nhi\u1ec1u h\u01a1n v\u1ec1 n\u00f3 g\u1ea7n \u0111\u00e2y v\u00ec l\u01b0\u1ee3ng th\u00f4ng tin marketing kh\u1ed5ng l\u1ed3 t\u1eeb truy\u1ec1n th\u00f4ng.\n\n\nS\u1eed d\u1ee5ng ph\u00e9p so s\u00e1nh c\u1ee7a Jim Collins, h\u00e3y ngh\u0129 v\u1ec1 vi\u1ec7c b\u1ea1n \u0111ang ch\u1ebf m\u1ed9t c\u1ed1c bia \u0111\u00e1 l\u1ea1nh y\u00eau th\u00edch. N\u1ebfu b\u1ea1n l\u00e0m \u0111\u00fang c\u00e1ch, ph\u1ea7n l\u1edbn chi\u1ebfc c\u1ed1c s\u1ebd \u0111\u1ea7y bia v\u1edbi m\u1ed9t l\u1edbp b\u1ecdt d\u1ea7y ph\u00eda tr\u00ean. Chi\u1ebfc c\u1ed1c \u1ea5y th\u1eadt gi\u1ed1ng khoa h\u1ecdc d\u1eef li\u1ec7u. \n1. N\u00f3 l\u00e0 bia. N\u1ec1n t\u1ea3ng th\u1ed1ng k\u00ea \u0111\u00e3 \u0111\u01b0\u1ee3c ch\u1ee9ng minh gi\u00e1 tr\u1ecb h\u00e0ng tr\u0103m n\u0103m qua.\n2. N\u00f3 l\u00e0 b\u1ecdt. Nh\u1eefng bong b\u00f3ng \u0111\u01b0\u1ee3c d\u1ef1ng tr\u00ean n\u1ec1n k\u00ec v\u1ecdng vi\u1ec3n v\u00f4ng v\u00e0 s\u1ebd d\u1ea7n tan bi\u1ebfn.\n\nTh\u1ee9 b\u1ecdt n\u00e0y c\u00f3 th\u1ec3 bi\u1ebfn m\u1ea5t nhanh h\u01a1n b\u1ea1n ngh\u0129. T\u1ea1p ch\u00ed \"The Economist\" t\u1eebng vi\u1ebft:\n> Nh\u1eefng chuy\u00ean gia t\u01b0 v\u1ea5n t\u1eebng d\u1ef1 \u0111o\u00e1n AI c\u00f3 t\u00e1c \u0111\u1ed9ng thay \u0111\u1ed5i th\u1ebf gi\u1edbi c\u0169ng ch\u00ednh l\u00e0 nh\u1eefng ng\u01b0\u1eddi t\u01b0\u1eddng thu\u1eadt vi\u1ec7c c\u00e1c nh\u00e0 qu\u1ea3n l\u00fd th\u1ef1c t\u1ebf t\u1ea1i c\u00e1c c\u00f4ng ty \u0111ang ng\u1ed9 ra r\u1eb1ng AI r\u1ea5t kh\u00f3 tri\u1ec3n khai, v\u00e0 c\u01a1n s\u1ed1t \u0111ang ngu\u1ed9i d\u1ea7n. Svetlana Sicular t\u1eeb  c\u00f4ng ty nghi\u00ean c\u1ee9u Gartner n\u00f3i r\u1eb1ng n\u0103m 2020 c\u00f3 th\u1ec3 l\u00e0 n\u0103m AI \u0111\u1ed5 \u0111\u00e8o, trong m\u00f4 h\u00ecnh \"V\u00f2ng \u0111\u1eddi \u1ea2o v\u1ecdng\" n\u1ed5i ti\u1ebfng. C\u00e1c nh\u00e0 \u0111\u1ea7u t\u01b0 s\u1ef1c t\u1ec9nh khi \u0111ang ch\u1ea1y theo \u0111\u00e1m \u0111\u00f4ng: m\u1ed9t kh\u1ea3o s\u00e1t c\u00e1c startup AI t\u1ea1i ch\u00e2u \u00c2u c\u1ee7a MMC, m\u1ed9t qu\u1ef9 \u0111\u1ea7u t\u01b0 m\u1ea1o hi\u1ec3m, cho th\u1ea5y th\u1ef1c t\u1ebf 40% kh\u00f4ng h\u1ec1 d\u00f9ng AI ch\u00fat n\u00e0o.\n\nGi\u1eefa c\u01a1n l\u00ean \u0111\u1ed3ng \u1ea5y, ch\u00fang ta, c\u00e1c chuy\u00ean gia d\u1eef li\u1ec7u, n\u00ean l\u00e0m g\u00ec. Tr\u01b0\u1edbc ti\u00ean, n\u1ebfu b\u1ea1n kh\u00f4n ngoan, b\u1ea1n s\u1ebd h\u1ecdc c\u00e1ch ph\u1edbt l\u1edd l\u1edbp b\u1ecdt. C\u00e1i m\u00e0 ta mu\u1ed1n th\u01b0\u1edfng th\u1ee9c l\u00e0 bia. To\u00e1n v\u00e0 th\u1ed1ng k\u00ea v\u1ed1n h\u1eefu \u00edch mu\u00f4n \u0111\u1eddi v\u00e0 s\u1ebd ch\u1eb3ng th\u1ec3 b\u1ed7ng d\u01b0ng tho\u00e1i tr\u00e0o \u1edf \u0111\u00e2y. Th\u00eam v\u00e0o \u0111\u00f3, h\u00e3y h\u1ecdc nh\u1eefng g\u00ec khi\u1ebfn c\u00f4ng vi\u1ec7c c\u1ee7a b\u1ea1n h\u1eefu \u00edch v\u00e0 gi\u00e1 tr\u1ecb, kh\u00f4ng ph\u1ea3i nh\u1eefng c\u00f4ng c\u1ee5 h\u00e0o nho\u00e1ng ch\u1eb3ng bi\u1ebft \u0111\u1ec3 l\u00e0m g\u00ec. Cu\u1ed1i c\u00f9ng h\u00e3y nh\u1edb r\u1eb1ng kh\u00f4ng th\u1ec3 \u0111i ngang v\u1ec1 t\u1eaft. Ki\u1ebfn th\u1ee9c v\u1ec1 to\u00e1n v\u00e0 th\u1ed1ng k\u00ea gi\u00e1 tr\u1ecb ch\u00ednh v\u00ec ch\u00fang kh\u00f3 \u0111\u1ec3 h\u1ecdc v\u00e0 d\u00f9ng. N\u1ebfu m\u1ecdi ng\u01b0\u1eddi \u0111\u1ec1u c\u00f3 kh\u1ea3 n\u0103ng s\u1eed d\u1ee5ng, th\u00ec ngu\u1ed3n cung th\u1eeba m\u1ee9a s\u1ebd h\u1ea1 gi\u00e1 tr\u1ecb c\u1ee7a ch\u00fang. V\u00ec th\u1ebf, h\u00e3y **kh\u1ed5 luy\u1ec7n** v\u00e0 h\u1ecdc ch\u00fang nhi\u1ec1u nh\u1ea5t c\u00f3 th\u1ec3!\n\n\n\n## Tr\u1ea3 l\u1eddi nh\u1eefng c\u00e2u h\u1ecfi kh\u00e1c nhau\nV\u1ea5n \u0111\u1ec1 m\u00e0 ML \u0111ang l\u00e0m r\u1ea5t t\u1ed1t l\u00e0 d\u1ef1 \u0111o\u00e1n. Ajay Agrawal, Joshua Gans v\u00e0 Avi Goldfarb vi\u1ebft trong cu\u1ed1n s\u00e1ch \"C\u1ed7 m\u00e1y D\u1ef1 \u0111o\u00e1n\": \"L\u00e0n s\u00f3ng tr\u00ed tu\u1ec7 nh\u00e2n t\u1ea1o th\u1ef1c ra kh\u00f4ng mang \u0111\u1ebfn cho ch\u00fang ta tr\u00ed tu\u1ec7 m\u00e0 m\u1ed9t ph\u1ea7n thi\u1ebft y\u1ebfu c\u1ee7a tr\u00ed tu\u1ec7 - kh\u1ea3 n\u0103ng ph\u00e1n \u0111o\u00e1n\". Ch\u00fang ta c\u00f3 th\u1ec3 t\u1ea1o ra v\u00f4 s\u1ed1 \u0111i\u1ec1u k\u00ec di\u1ec7u v\u1edbi \"machine learning\". Y\u00eau c\u1ea7u duy nh\u1ea5t l\u00e0 ch\u00fang ta \u0111\u1eb7t v\u1ea5n \u0111\u1ec1 trong khu\u00f4n kh\u1ed5 d\u1ef1 \u0111o\u00e1n. Mu\u1ed1n d\u1ecbch ti\u1ebfng Anh sang ti\u1ebfng B\u1ed3 \u0110\u00e0o Nha? H\u00e3y x\u00e2y d\u1ef1ng m\u00f4 h\u00ecnh ML gi\u00fap d\u1ef1 \u0111o\u00e1n c\u00e2u v\u0103n ti\u1ebfng B\u1ed3 \u0110\u00e0o Nha cho m\u1ed7i c\u00e2u ti\u1ebfng Anh. Mu\u1ed1n nh\u1eadn di\u1ec7n khu\u00f4n m\u1eb7t? H\u00e3y x\u00e2y d\u1ef1ng m\u00f4 h\u00ecnh ML gi\u00fap d\u1ef1 \u0111o\u00e1n s\u1ef1 hi\u1ec7n di\u1ec7n c\u1ee7a m\u1ed9t khu\u00f4n m\u1eb7t trong m\u1ed9t ph\u1ea7n b\u1ee9c tranh. Mu\u1ed1n s\u1ea3n xu\u1ea5t \u00f4 t\u00f4 t\u1ef1 l\u00e1i? H\u00e3y x\u00e2y d\u1ef1ng m\u00f4 h\u00ecnh ML gi\u00fap d\u1ef1 \u0111o\u00e1n ph\u01b0\u01a1ng h\u01b0\u1edbng b\u00e1nh l\u00e1i v\u00e0 \u00e1p l\u1ef1c l\u00ean ch\u00e2n phanh v\u00e0 ch\u00e2n ga d\u1ef1a v\u00e0o c\u00e1c t\u1ea5m h\u00ecnh ngo\u1ea1i c\u1ea3nh \u00f4 t\u00f4.\n\nTuy nhi\u00ean ML kh\u00f4ng ph\u1ea3i li\u1ec1u thu\u1ed1c v\u1ea1n n\u0103ng. N\u00f3 r\u1ea5t k\u00ec di\u1ec7u trong m\u1ed9t khu\u00f4n kh\u1ed5 nh\u1ea5t \u0111\u1ecbnh v\u00e0 th\u1ea5t b\u1ea1i n\u1ebfu d\u1eef li\u1ec7u d\u00f9ng \u0111\u1ec3 d\u1ef1 \u0111o\u00e1n sai l\u1ec7ch \u0111\u00f4i ch\u00fat v\u1edbi d\u1eef li\u1ec7u x\u00e2y d\u1ef1ng m\u00f4 h\u00ecnh m\u00e0 n\u00f3 \u0111\u00e3 quen thu\u1ed9c. M\u1ed9t v\u00ed d\u1ee5 kh\u00e1c trong cu\u1ed1n s\u00e1ch \"C\u1ed7 m\u00e1y D\u1ef1 \u0111o\u00e1n\": \"Trong nhi\u1ec1u ng\u00e0nh ngh\u1ec1, m\u1ee9c gi\u00e1 th\u1ea5p t\u01b0\u01a1ng quan v\u1edbi doanh s\u1ed1 th\u1ea5p. V\u00ed d\u1ee5 trong ng\u00e0nh kh\u00e1ch s\u1ea1n, gi\u00e1 th\u1ea5p ngo\u00e0i m\u00f9a du l\u1ecbch v\u00e0 gi\u00e1 t\u0103ng cao khi nhu c\u1ea7u \u0111\u1ea1t \u0111\u1ec9nh \u0111i\u1ec3m v\u00e0 c\u00e1c kh\u00e1ch s\u1ea1n k\u00edn ph\u00f2ng. D\u1ef1a v\u00e0o d\u1eef li\u1ec7u, m\u1ed9t m\u00f4 h\u00ecnh d\u1ef1 \u0111o\u00e1n ng\u1edd ngh\u1ec7ch c\u00f3 th\u1ec3 \u0111\u1ec1 xu\u1ea5t r\u1eb1ng vi\u1ec7c t\u0103ng gi\u00e1 l\u00e0m t\u0103ng m\u1ee9c \u0111\u1ed9 ph\u1ee7 k\u00edn ph\u00f2ng.\u201d\n\nML r\u1ea5t d\u1edf trong c\u00e1c v\u1ea5n \u0111\u1ec1 li\u00ean quan \u0111\u1ebfn m\u1ed1i li\u00ean h\u1ec7 ng\u01b0\u1ee3c gi\u1eefa nguy\u00ean nh\u00e2n - k\u1ebft qu\u1ea3. Ch\u00fang bu\u1ed9c ch\u00fang ta tr\u1ea3 l\u1eddi nh\u1eefng c\u00e2u h\u1ecfi \"N\u1ebfu .. th\u00ec chuy\u1ec7n g\u00ec x\u1ea3y ra\", m\u00e0 c\u00e1c chuy\u00ean gia kinh t\u1ebf g\u1ecdi l\u00e0 c\u00e1c gi\u1ea3 t\u01b0\u1edfng. \u0110i\u1ec1u g\u00ec x\u1ea3y ra n\u1ebfu thay v\u00ec m\u1ee9c gi\u00e1 ni\u00eam y\u1ebft n\u00e0y cho m\u1ed9t m\u1eb7t h\u00e0ng, t\u00f4i ni\u00eam y\u1ebft m\u1ee9c gi\u00e1 kh\u00e1c? \u0110i\u1ec1u g\u00ec x\u1ea3y ra n\u1ebfu thay v\u00ec ch\u1ebf \u0111\u1ed9 \u0103n \u00edt b\u00e9o, t\u00f4i theo ch\u1ebf \u0111\u1ed9 \u0103n \u00edt \u0111\u01b0\u1eddng? N\u1ebfu b\u1ea1n l\u00e0m vi\u1ec7c cho m\u1ed9t ng\u00e2n h\u00e0ng cung c\u1ea5p t\u00edn d\u1ee5ng, b\u1ea1n s\u1ebd ph\u1ea3i t\u00ecm hi\u1ec3u li\u1ec7u vi\u1ec7c thay \u0111\u1ed5i t\u1eadp kh\u00e1ch h\u00e0ng s\u1ebd thay \u0111\u1ed5i doanh s\u1ed1 nh\u01b0 th\u1ebf n\u00e0o? Ho\u1eb7c n\u1ebfu b\u1ea1n l\u00e0m vi\u1ec7c cho m\u1ed9t ch\u00ednh quy\u1ec1n \u0111\u1ecba ph\u01b0\u01a1ng , b\u1ea1n c\u00f3 th\u1ec3 s\u1ebd ph\u1ea3i t\u00ecm hi\u1ec3u l\u00e0m th\u1ebf n\u00e0o \u0111\u1ec3 c\u1ea3i thi\u1ec7n h\u1ec7 th\u1ed1ng gi\u00e1o d\u1ee5c. Li\u1ec7u b\u1ea1n c\u00f3 n\u00ean ph\u00e1t m\u00e1y t\u00ednh b\u1ea3ng cho m\u1ed7i \u0111\u1ee9a tr\u1ebb cho h\u1ee3p th\u1eddi \u0111\u1ea1i k\u1ec9 nguy\u00ean tr\u00ed tu\u1ec7 s\u1ed1? Ho\u1eb7c li\u1ec7u c\u00f3 n\u00ean x\u00e2y c\u00e1c th\u01b0 vi\u1ec7n theo ki\u1ec3u truy\u1ec1n th\u1ed1ng? D\u00f9 b\u1ea1n l\u00e0m ng\u00e0nh ngh\u1ec1 n\u00e0o th\u00ec b\u1ea1n c\u0169ng s\u1ebd ph\u1ea3i \u0111\u1ed1i m\u1eb7t v\u1edbi nh\u1eefng c\u00e2u h\u1ecfi ki\u1ec3u nh\u01b0 \"chi\u1ebfn d\u1ecbch marketing n\u00e0y s\u1ebd mang t\u1edbi bao nhi\u00eau kh\u00e1ch h\u00e0ng m\u1edbi?\", \"ch\u01b0\u01a1ng tr\u00ecnh hu\u1ea5n luy\u1ec7n nh\u00e2n vi\u00ean n\u00e0y c\u00f3 l\u00e0m t\u0103ng hi\u1ec7u su\u1ea5t l\u00e0m vi\u1ec7c kh\u00f4ng?\". \u0110\u00e1ng ti\u1ebfc cho ML, trong c\u00e1c ng\u00e0nh ngh\u1ec1 truy\u1ec1n th\u1ed1ng, c\u00e1c lo\u1ea1i c\u00e2u h\u1ecfi n\u00e0y ph\u1ed5 bi\u1ebfn h\u01a1n c\u00e1c c\u00e2u h\u1ecfi v\u1ec1 d\u1ef1 \u0111o\u00e1n. \u0110\u1ec3 tr\u1ea3 l\u1eddi ch\u00fang, ch\u00fang ta kh\u00f4ng th\u1ec3 d\u1ef1a v\u00e0o c\u00e1c d\u1ef1 \u0111o\u00e1n d\u1ef1a tr\u00ean quan h\u1ec7 t\u01b0\u01a1ng quan.\n\nTr\u1ea3 l\u1eddi c\u00e1c c\u00e2u h\u1ecfi ki\u1ec3u n\u00e0y kh\u00f3 h\u01a1n m\u1ecdi ng\u01b0\u1eddi t\u01b0\u1edfng. Ai \u0111\u00f3 c\u00f3 th\u1ec3 n\u00f3i \u0111i n\u00f3i l\u1ea1i \"Quan h\u1ec7 t\u01b0\u01a1ng quan kh\u00f4ng ph\u1ea3i Quan h\u1ec7 nh\u00e2n qu\u1ea3\", \"Quan h\u1ec7 t\u01b0\u01a1ng quan kh\u00f4ng ph\u1ea3i Quan h\u1ec7 nh\u00e2n qu\u1ea3\". Nh\u01b0ng th\u1ef1c t\u1ebf \u0111\u1ec3 gi\u1ea3i th\u00edch n\u00f3 t\u01b0\u1eddng t\u1eadn c\u1ea7n nhi\u1ec1u h\u01a1n th\u1ebf. Ph\u1ea7n d\u01b0\u1edbi \u0111\u00e2y s\u1ebd tr\u00ecnh b\u00e0y **l\u00e0m th\u1ec3 n\u00e0o \u0111\u1ec3 quan h\u1ec7 t\u01b0\u01a1ng quan h\u00e9 l\u1ed9 quan h\u1ec7 nh\u00e2n qu\u1ea3**.\n\n# Khi n\u00e0o  Quan h\u1ec7 t\u01b0\u01a1ng quan l\u00e0  Quan h\u1ec7 nh\u00e2n qu\u1ea3\n\nB\u1eb1ng tr\u1ef1c gi\u00e1c, kh\u00e1 d\u1ec5 hi\u1ec3u t\u1ea1i sao quan h\u1ec7 t\u01b0\u01a1ng quan kh\u00f4ng ph\u1ea3i quan h\u1ec7 nh\u00e2n qu\u1ea3. N\u1ebfu ai \u0111\u00f3 n\u00f3i v\u1edbi b\u1ea1n: tr\u1ebb h\u1ecdc t\u1ed1t h\u01a1n \u1edf c\u00e1c tr\u01b0\u1eddng ph\u00e1t m\u00e1y t\u00ednh b\u1ea3ng cho h\u1ecdc sinh, b\u1ea1n c\u00f3 th\u1ec3 ph\u1ea3n bi\u1ec7n r\u1eb1ng \u0111\u00f3 c\u0169ng l\u00e0 c\u00e1c tr\u01b0\u1eddng gi\u00e0u h\u01a1n. V\u00ec th\u1ebf h\u1ecd c\u00f3 c\u00f3 \u0111i\u1ec1u ki\u1ec7n gi\u1ea3ng d\u1ea1y t\u1ed1t h\u01a1n d\u00f9 c\u00f3 ph\u00e1t m\u00e1y t\u00ednh b\u1ea3ng hay kh\u00f4ng. V\u00ec th\u1ebf ch\u00fang ta kh\u00f4ng th\u1ec3 k\u1ebft lu\u1eadn r\u1eb1ng vi\u1ec7c cung c\u1ea5p m\u00e1y t\u00ednh b\u1ea3ng cho l\u1edbp h\u1ecdc l\u00e0m t\u0103ng k\u1ebft qu\u1ea3 h\u1ecdc t\u1eadp c\u1ee7a tr\u1ebb. Ch\u00fang ta ch\u1ec9 c\u00f3 th\u1ec3 n\u00f3i r\u1eb1ng vi\u1ec7c s\u1eed d\u1ee5ng m\u00e1y t\u00ednh b\u1ea3ng trong tr\u01b0\u1eddng h\u1ecdc t\u01b0\u01a1ng quan v\u1edbi k\u1ebft qu\u1ea3 h\u1ecdc t\u1eadp cao.\n\n\n```python\nimport pandas as pd\nimport numpy as np\nfrom scipy.special import expit\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nfrom matplotlib import style\n\nstyle.use(\"fivethirtyeight\")\n\nnp.random.seed(123)\nn = 100\nh\u1ecdc_ph\u00ed = np.random.normal(1000, 300, n).round()\nm\u00e1y_t\u00ednh_b\u1ea3ng = np.random.binomial(1, expit((h\u1ecdc_ph\u00ed - h\u1ecdc_ph\u00ed.mean()) / h\u1ecdc_ph\u00ed.std())).astype(bool)\n\u0111i\u1ec3m_enem = np.random.normal(200 - 50 * m\u00e1y_t\u00ednh_b\u1ea3ng + 0.7 * h\u1ecdc_ph\u00ed, 200)\n\u0111i\u1ec3m_enem = (\u0111i\u1ec3m_enem - \u0111i\u1ec3m_enem.min()) / \u0111i\u1ec3m_enem.max()\n\u0111i\u1ec3m_enem *= 1000\n\ndata = pd.DataFrame(dict(\u0111i\u1ec3m_enem=\u0111i\u1ec3m_enem, h\u1ecdc_ph\u00ed=h\u1ecdc_ph\u00ed, m\u00e1y_t\u00ednh_b\u1ea3ng=m\u00e1y_t\u00ednh_b\u1ea3ng))\n```\n\n\n```python\nplt.figure(figsize=(6,8))\nsns.boxplot(y=\"\u0111i\u1ec3m_enem\", x=\"m\u00e1y_t\u00ednh_b\u1ea3ng\", data=data).set_title(' \u0110i\u1ec3m ENEM theo vi\u1ec7c trang b\u1ecb M\u00e1y t\u00ednh b\u1ea3ng trong L\u1edbp h\u1ecdc')\nplt.show()\n```\n\n\u0110\u1ec3 hi\u1ec3u h\u01a1n v\u1ea5n \u0111\u1ec1 \u0111\u01a1n gi\u1ea3n n\u00e0y, h\u00e3y c\u00f9ng b\u1eaft \u0111\u1ea7u v\u1edbi vi\u1ec7c thi\u1ebft l\u1eadp m\u1ed9t s\u1ed1 k\u00ed hi\u1ec7u. \u0110\u00e2y l\u00e0 ng\u00f4n ng\u1eef chung \u0111\u1ec3 n\u00f3i v\u1ec1 \n quan h\u1ec7 nh\u00e2n qu\u1ea3. G\u1ecdi \\\\(T_i\\\\) l\u00e0 l\u01b0\u1ee3ng can thi\u1ec7p \u0111\u1ed1i v\u1edbi c\u00e1 nh\u00e2n i. \n\n$\nT_i=\\begin{cases}\n1 \\ \\text{n\u1ebfu c\u00e1 th\u1ec3 i ti\u1ebfp nh\u1eadn can thi\u1ec7p}\\\\\n0 \\ \\text{n\u1ebfu ng\u01b0\u1ee3c l\u1ea1i}\\\\\n\\end{cases}\n$\n\nCan thi\u1ec7p  \u1edf \u0111\u00e2y kh\u00f4ng nh\u1ea5t thi\u1ebft l\u00e0 \u0111i\u1ec1u tr\u1ecb y t\u1ebf ho\u1eb7c b\u1ea5t c\u1ee9 th\u1ee9 g\u00ec li\u00ean quan \u0111\u1ebfn l\u0129nh v\u1ef1c y t\u1ebf. Thay v\u00e0o \u0111\u00f3, n\u00f3 ch\u1ec9 l\u00e0 m\u1ed9t thu\u1eadt ng\u1eef ch\u00fang ta d\u00f9ng \u0111\u1ec3 n\u00f3i v\u1ec1 m\u1ed9t bi\u1ec7n ph\u00e1p/h\u00e0nh \u0111\u1ed9ng/ch\u01b0\u01a1ng tr\u00ecnh/s\u00e1ng ki\u1ebfn m\u00e0 ch\u00fang ta mu\u1ed1n t\u00ecm hi\u1ec3u t\u00ednh hi\u1ec7u qu\u1ea3 c\u1ee7a n\u00f3. Trong tr\u01b0\u1eddng h\u1ee3p n\u00e0y, can thi\u1ec7p l\u00e0 vi\u1ec7c ph\u00e1t m\u00e1y t\u00ednh b\u1ea3ng cho h\u1ecdc sinh.\n\nG\u1ecdi bi\u1ebfn \\\\(Y_i\\\\) l\u00e0 k\u1ebft qu\u1ea3 quan s\u00e1t cho c\u00e1 th\u1ec3 i.\n\n$\nY_i\n$\n\nK\u1ebft qu\u1ea3 l\u00e0 bi\u1ebfn s\u1ed1 ch\u00fang ta quan t\u00e2m. Ch\u00fang ta mu\u1ed1n bi\u1ebft li\u1ec7u can thi\u1ec7p c\u00f3 \u1ea3nh h\u01b0\u1edfng \u0111\u1ebfn k\u1ebft qu\u1ea3 hay kh\u00f4ng.\n\n\u0110\u00e2y l\u00e0 \u0111i\u1ec1u th\u00fa v\u1ecb. **Th\u00e1ch th\u1ee9c c\u01a1 b\u1ea3n c\u1ee7a suy lu\u1eadn nh\u00e2n qu\u1ea3** l\u00e0 ch\u00fang ta kh\u00f4ng bao gi\u1edd c\u00f3 th\u1ec3 quan s\u00e1t c\u00f9ng m\u1ed9t c\u00e1 th\u1ec3 \u0111\u1ed3ng th\u1eddi ti\u1ebfp nh\u1eadn ho\u1eb7c kh\u00f4ng ti\u1ebfp nh\u1eadn can thi\u1ec7p. Gi\u1ed1ng nh\u01b0 vi\u1ec7c ch\u00fang ta \u0111i \u0111\u1ebfn ng\u00e3 r\u1ebd v\u00e0 ch\u1ec9 c\u00f3 th\u1ec3 bi\u1ebft \u0111i\u1ec1u g\u00ec ch\u1edd \u0111\u00f3n ph\u00eda tr\u01b0\u1edbc n\u1ebfu ch\u00fang ta ch\u1ecdn \u0111i m\u1ed9t trong 2 con \u0111\u01b0\u1eddng. H\u00e3y ngh\u0129 v\u1ec1 th\u01a1 c\u1ee7a Robert Frost [[Con \u0111\u01b0\u1eddng ch\u01b0a \u0111i/The road not taken]](https://sites.google.com/site/thorobertfrost/)\n\n```\nCon \u0111\u01b0\u1eddng chia hai ng\u1ea3 gi\u1eefa r\u1eebng thu\nNh\u01b0ng than \u00f4i, \u0111\u00e0nh ph\u1ea3i theo m\u1ed9t l\u1ed1i\nT\u00f4i l\u00e0m k\u1ebb l\u1eef h\u00e0nh ph\u00e2n v\u00e2n m\u00e3i\n\u0110\u01b0a m\u1eaft nh\u00ecn xu\u1ed1ng l\u1ed1i ch\u1ea1y v\u1ec1 xa\nT\u1edbi kh\u00fac cong khu\u1ea5t sau l\u00f9m c\u00e2y b\u1ee5i.\n```\n\nT\u00f3m l\u1ea1i, ch\u00fang ta s\u1ebd n\u00f3i r\u1ea5t nhi\u1ec1u v\u1ec1 c\u00e1c **k\u1ebft qu\u1ea3 ti\u1ec1m n\u0103ng**. Ch\u00fang ti\u1ec1m n\u0103ng v\u00ec ch\u01b0a th\u1ef1c s\u1ef1 di\u1ec5n ra. Thay v\u00e0o \u0111\u00f3, ch\u00fang cho ta bi\u1ebft \u0111i\u1ec1u g\u00ec c\u00f3 th\u1ec3 x\u1ea3y \u0111\u1ebfn n\u1ebfu c\u00f3 can thi\u1ec7p. \u0110\u00f4i khi ch\u00fang ta g\u1ecdi k\u1ebft qu\u1ea3 ti\u1ec1m n\u0103ng di\u1ec5n ra l\u00e0 hi\u1ec7n th\u1ef1c v\u00e0 k\u1ebft qu\u1ea3 ti\u1ec1m n\u0103ng kh\u00f4ng di\u1ec5n ra l\u00e0 gi\u1ea3 t\u01b0\u1edfng.\n\nCh\u00fang ta d\u00f9ng ch\u1ec9 s\u1ed1 d\u01b0\u1edbi \u0111\u1ec3 k\u00ed hi\u1ec7u:\n\n\\\\(Y_{0i}\\\\) l\u00e0 k\u1ebft qu\u1ea3 ti\u1ec1m n\u0103ng  c\u1ee7a c\u00e1 th\u1ec3 i kh\u00f4ng \u0111\u01b0\u1ee3c can thi\u1ec7p (\u0111\u1ed1i ch\u1ee9ng). \n\n\\\\(Y_{1i}\\\\) l\u00e0 k\u1ebft qu\u1ea3 ti\u1ec1m n\u0103ng  c\u1ee7a c\u00f9ng c\u00e1 th\u1ec3 i khi c\u00f3 can thi\u1ec7p.\n\nL\u01b0u \u00fd \u0111\u00f4i khi ch\u00fang ta nh\u00ecn th\u1ea5y c\u00e1c k\u1ebft qu\u1ea3 ti\u1ec1m n\u0103ng \u0111\u01b0\u1ee3c k\u00ed hi\u1ec7u d\u01b0\u1edbi d\u1ea1ng h\u00e0m s\u1ed1 \\\\(Y_i(t)\\\\). \\\\(Y_{0i}\\\\) c\u00f3 th\u1ec3 l\u00e0 \\\\(Y_i(0)\\\\) v\u00e0 \\\\(Y_{1i}\\\\) c\u00f3 th\u1ec3 l\u00e0 \\\\(Y_i(1)\\\\). \u1ede \u0111\u00e2y ch\u00fang ta s\u1ebd ch\u1ee7 y\u1ebfu d\u00f9ng ch\u1ec9 s\u1ed1 d\u01b0\u1edbi \u0111\u1ec3 k\u00ed hi\u1ec7u.\n\n\n\nTrong v\u00ed d\u1ee5 m\u00e1y t\u00ednh b\u1ea3ng c\u1ee7a ch\u00fang ta, \\\\(Y_{1i}\\\\) l\u00e0 k\u1ebft qu\u1ea3 h\u1ecdc t\u1eadp c\u1ee7a h\u1ecdc sinh i n\u1ebfu \u0111\u01b0\u1ee3c ph\u00e1t m\u00e1y t\u00ednh b\u1ea3ng d\u00f9ng trong l\u1edbp h\u1ecdc.  B\u00e2y gi\u1edd, n\u1ebfu h\u1ecdc sinh i \u0111\u01b0\u1ee3c ph\u00e1t m\u00e1y t\u00ednh b\u1ea3ng, ch\u00fang ta quan s\u00e1t th\u1ea5y \\\\(Y_{1i}\\\\). N\u1ebfu kh\u00f4ng, \\\\(Y_{1i}\\\\) v\u1eabn t\u1ed3n t\u1ea1i tr\u00ean l\u00ed thuy\u1ebft nh\u01b0ng ch\u00fang ta kh\u00f4ng th\u1ec3 quan s\u00e1t. Trong tr\u01b0\u1eddng h\u1ee3p n\u00e0y n\u00f3 l\u00e0 m\u1ed9t k\u1ebft qu\u1ea3 ti\u1ec1m n\u0103ng (gi\u1ea3 t\u01b0\u1edfng).\n\nV\u1edbi k\u1ebft qu\u1ea3 ti\u1ec1m n\u0103ng, ch\u00fang ta c\u00f3 th\u1ec3 \u0111\u1ecbnh ngh\u0129a hi\u1ec7u \u1ee9ng can thi\u1ec7p c\u00e1 th\u1ec3:\n\n \\\\(Y_{1i} - Y_{0i}\\\\)\n \nT\u1ea5t nhi\u00ean, do th\u00e1ch th\u1ee9c c\u01a1 b\u1ea3n c\u1ee7a suy lu\u1eadn nh\u00e2n qu\u1ea3, ch\u00fang ta kh\u00f4ng bao gi\u1edd bi\u1ebft \u0111\u01b0\u1ee3c hi\u1ec7u \u1ee9ng can thi\u1ec7p c\u00e1 th\u1ec3 v\u00ec ch\u00fang ta ch\u1ec9 c\u00f3 th\u1ec3 quan s\u00e1t \u0111\u01b0\u1ee3c 1 trong 2 k\u1ebft qu\u1ea3 ti\u1ec1m n\u0103ng. V\u00ec v\u1eady, h\u00e3y t\u1eadp trung \u01b0\u1edbc l\u01b0\u1ee3ng m\u1ed9t \u0111\u1ea1i l\u01b0\u1ee3ng \u0111\u01a1n gi\u1ea3n h\u01a1n: **t\u00e1c \u0111\u1ed9ng can thi\u1ec7p trung b\u00ecnh (Average Treatment Effect - ATE)**. \u0110\u1ea1i l\u01b0\u1ee3ng n\u00e0y \u0111\u01b0\u1ee3c \u0111\u1ecbnh ngh\u0129a nh\u01b0 sau:\n\n\\\\(ATE = E[Y_1 - Y_0]\\\\)\n\nTrong \u0111\u00f3 E[...] l\u00e0 gi\u00e1 tr\u1ecb k\u00ec v\u1ecdng. M\u1ed9t \u0111\u1ea1i l\u01b0\u1ee3ng d\u1ec5 \u01b0\u1edbc t\u00ednh h\u01a1n n\u1eefa l\u00e0 **t\u00e1c \u0111\u1ed9ng can thi\u1ec7p trung b\u00ecnh tr\u00ean nh\u00f3m \u0111\u01b0\u01a1c can thi\u1ec7p (Average Treatment Effect on the Treated- ATET)**:\n\n\\\\(ATET = E[Y_1 - Y_0 | T=1]\\\\)\n\nCh\u00fang ta bi\u1ebft r\u1eb1ng s\u1ebd kh\u00f4ng bao gi\u1edd c\u00f3 th\u1ec3 quan s\u00e1t \u0111\u01b0\u1ee3c c\u1ea3 2 k\u1ebft qu\u1ea3 ti\u1ec1m n\u0103ng, nh\u01b0ng \u0111\u1ec3 d\u1ec5 hi\u1ec3u h\u01a1n, h\u00e3y t\u1ea1m gi\u1ea3 thi\u1ebft l\u00e0 ta c\u00f3 th\u1ec3. Gi\u1ea3 s\u1eed ch\u00fang ta thu th\u1eadp d\u1eef li\u1ec7u cho 4 tr\u01b0\u1eddng h\u1ecdc. Ch\u00fang ta quan s\u00e1t \u0111\u01b0\u1ee3c t\u1eebng tr\u01b0\u1eddng c\u00f3 ph\u00e1t m\u00e1y t\u00ednh b\u1ea3ng cho h\u1ecdc sinh hay kh\u00f4ng v\u00e0 k\u1ebft qu\u1ea3 h\u1ecdc t\u1eadp c\u1ee7a h\u1ecdc sinh. \u1ede \u0111\u00e2y vi\u1ec7c ph\u00e1t m\u00e1y t\u00ednh b\u1ea3ng l\u00e0 can thi\u1ec7p, v\u00ec th\u1ebf \\\\(T=1\\\\) t\u01b0\u01a1ng \u1ee9ng v\u1edbi vi\u1ec7c ph\u00e1t m\u00e1y t\u00ednh b\u1ea3ng cho h\u1ecdc sinh. \\\\(Y\\\\) l\u00e0 \u0111i\u1ec3m s\u1ed1.\n\n\n```python\npd.DataFrame(dict(\n    i= [1,2,3,4],\n    y0=[500,600,800,700],\n    y1=[450,600,600,750],\n    t= [0,0,1,1],\n    y= [500,600,600,750],\n    te=[-50,0,-200,50],\n))\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>i</th>\n      <th>y0</th>\n      <th>y1</th>\n      <th>t</th>\n      <th>y</th>\n      <th>te</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>500</td>\n      <td>450</td>\n      <td>0</td>\n      <td>500</td>\n      <td>-50</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2</td>\n      <td>600</td>\n      <td>600</td>\n      <td>0</td>\n      <td>600</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>3</td>\n      <td>800</td>\n      <td>600</td>\n      <td>1</td>\n      <td>600</td>\n      <td>-200</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>4</td>\n      <td>700</td>\n      <td>750</td>\n      <td>1</td>\n      <td>750</td>\n      <td>50</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\\\\(ATE\\\\) \u1edf \u0111\u00e2y l\u00e0 trung b\u00ecnh c\u1ed9ng c\u1ee7a c\u1ed9t cu\u1ed1i c\u00f9ng (t\u00e1c \u0111\u1ed9ng can thi\u1ec7p):\n\n\\\\(ATE=(-50 + 0 - 200 + 50)/4 = -50\\\\)\n\n\\\\(ATET\\\\) \u1edf \u0111\u00e2y l\u00e0 trung b\u00ecnh c\u1ed9ng c\u1ee7a c\u1ed9t cu\u1ed1i c\u00f9ng khi m\u00e0 \\\\(T=1\\\\):\n\n\\\\(ATET=(- 200 + 50)/2 = -75\\\\)\n\n\u0110i\u1ec1u n\u00e0y ngh\u0129a l\u00e0 v\u1edbi c\u00e1c tr\u01b0\u1eddng nh\u1eadn can thi\u1ec7p, t\u00ednh trung b\u00ecnh, m\u00e1y t\u00ednh b\u1ea3ng l\u00e0m gi\u1ea3m k\u1ebft qu\u1ea3 h\u1ecdc t\u1eadp c\u1ee7a h\u1ecdc sinh 75 \u0111i\u1ec3m. T\u1ea5t nhi\u00ean ch\u00fang ta kh\u00f4ng bao gi\u1edd bi\u1ebft r\u00f5 nh\u01b0 th\u1ebf. B\u1ea3ng s\u1ed1 li\u1ec7u tr\u00ean \u0111\u00e2y th\u1ef1c t\u1ebf tr\u00f4ng gi\u1ed1ng th\u1ebf n\u00e0y (NaN l\u00e0 c\u00e1c gi\u00e1 tr\u1ecb ch\u01b0a bi\u1ebft):\n\n\n```python\npd.DataFrame(dict(\n    i= [1,2,3,4],\n    y0=[500,600,np.nan,np.nan],\n    y1=[np.nan,np.nan,600,750],\n    t= [0,0,1,1],\n    y= [500,600,600,750],\n    te=[np.nan,np.nan,np.nan,np.nan],\n))\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>i</th>\n      <th>y0</th>\n      <th>y1</th>\n      <th>t</th>\n      <th>y</th>\n      <th>te</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>500.0</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>500</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2</td>\n      <td>600.0</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>600</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>3</td>\n      <td>NaN</td>\n      <td>600.0</td>\n      <td>1</td>\n      <td>600</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>4</td>\n      <td>NaN</td>\n      <td>750.0</td>\n      <td>1</td>\n      <td>750</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n# Thi\u00ean l\u1ec7ch\n\nThi\u00ean l\u1ec7ch l\u00e0 nguy\u00ean nh\u00e2n khi\u1ebfn quan h\u1ec7 t\u01b0\u01a1ng quan kh\u00e1c v\u1edbi quan h\u1ec7 nh\u00e2n qu\u1ea3. May m\u1eafn l\u00e0 n\u00f3 kh\u00e1 d\u1ec5 hi\u1ec3u b\u1eb1ng tr\u1ef1c gi\u00e1c th\u00f4ng th\u01b0\u1eddng. Quay tr\u1edf l\u1ea1i v\u1edbi v\u00ed d\u1ee5 m\u00e1y t\u00ednh b\u1ea3ng trong l\u1edbp h\u1ecdc c\u1ee7a ch\u00fang ta. N\u1ebfu ai \u0111\u00f3 kh\u1eb3ng \u0111\u1ecbnh r\u1eb1ng h\u1ecdc sinh h\u1ecdc t\u1eadp t\u1ed1t h\u01a1n t\u1ea1i c\u00e1c tr\u01b0\u1eddng ph\u00e1t m\u00e1y t\u00ednh b\u1ea3ng; ch\u00fang ta c\u00f3 th\u1ec3 ph\u1ea3n bi\u1ec7n r\u1eb1ng c\u00e1c tr\u01b0\u1eddng \u0111\u00f3 c\u00f3 \u0111i\u1ec1u ki\u1ec7n gi\u1ea3ng d\u1ea1y t\u1ed1t h\u01a1n d\u00f9 c\u00f3 ph\u00e1t m\u00e1y t\u00ednh b\u1ea3ng hay kh\u00f4ng. C\u00e1c tr\u01b0\u1eddng n\u00e0y nhi\u1ec1u kh\u1ea3 n\u0103ng gi\u00e0u  h\u01a1n c\u00e1c tr\u01b0\u1eddng kh\u00e1c v\u00e0 v\u00ec th\u1ebf tr\u1ea3 l\u01b0\u01a1ng gi\u00e1o vi\u00ean cao h\u01a1n, trang b\u1ecb ph\u00f2ng h\u1ecdc t\u1ed1t h\u01a1n ,... N\u00f3i c\u00e1ch kh\u00e1c, tr\u01b0\u1eddng h\u1ecdc \u0111\u01b0\u1ee3c can thi\u1ec7p (ph\u00e1t m\u00e1y t\u00ednh b\u1ea3ng) kh\u00f4ng th\u1ec3 so s\u00e1nh v\u1edbi c\u00e1c tr\u01b0\u1eddng \u0111\u1ed1i ch\u1ee9ng. \n\nS\u1eed d\u1ee5ng k\u00ed hi\u1ec7u, k\u1ebft qu\u1ea3 ti\u1ec1m n\u0103ng \\\\(Y_0\\\\) c\u1ee7a tr\u01b0\u1eddng \u0111\u01b0\u1ee3c can thi\u1ec7p kh\u00e1c v\u1edbi \\\\(Y_0\\\\) c\u1ee7a tr\u01b0\u1eddng \u0111\u1ed1i ch\u1ee9ng. L\u01b0u \u00fd \\\\(Y_0\\\\) c\u1ee7a tr\u01b0\u1eddng \u0111\u01b0\u1ee3c can thi\u1ec7p **l\u00e0 gi\u1ea3 t\u01b0\u1edfng**. Ch\u00fang ta kh\u00f4ng quan s\u00e1t \u0111\u01b0\u1ee3c n\u00f3, nh\u01b0ng ch\u00fang ta c\u00f3 th\u1ec3 suy lu\u1eadn v\u1ec1 n\u00f3. Trong tr\u01b0\u1eddng h\u1ee3p c\u1ee5 th\u1ec3 n\u00e0y, ch\u00fang ta c\u00f3 th\u1ec3 \u0111i xa h\u01a1n v\u00e0 kh\u00e1i qu\u00e1t c\u00e1ch th\u1ebf gi\u1edbi v\u1eadn h\u00e0nh. Ch\u00fang ta c\u00f3 th\u1ec3 n\u00f3i r\u1eb1ng \\\\(Y_0\\\\) c\u1ee7a tr\u01b0\u1eddng \u0111\u01b0\u1ee3c can thi\u1ec7p l\u1edbn h\u01a1n \\\\(Y_0\\\\) c\u1ee7a tr\u01b0\u1eddng \u0111\u1ed1i ch\u1ee9ng. V\u00ec tr\u01b0\u1eddng \u0111\u1ee7 ti\u1ec1n ph\u00e1t m\u00e1y t\u00ednh b\u1ea3ng cho h\u1ecdc sinh th\u00ec c\u0169ng \u0111\u1ee7 ti\u1ec1n \u0111\u1ec3 trang tr\u1ea3i c\u00e1c \u0111i\u1ec1u ki\u1ec7n v\u1eadt ch\u1ea5t kh\u00e1c gi\u00fap tr\u1ebb \u0111\u1ea1t \u0111i\u1ec3m cao h\u01a1n. H\u00e3y d\u1eebng l\u1ea1i \u1edf \u0111\u00e2y m\u1ed9t ch\u00fat. Ph\u1ea3i m\u1ea5t ch\u00fat th\u1eddi gian \u0111\u1ec3 quen v\u1edbi c\u00e1ch n\u00f3i v\u1ec1 c\u00e1c k\u1ebft qu\u1ea3 ti\u1ec1m n\u0103ng. H\u00e3y th\u1eed \u0111\u1ecdc l\u1ea1i \u0111o\u1ea1n v\u0103n n\u00e0y \u0111\u1ec3 ch\u1eafc ch\u1eafn r\u1eb1ng b\u1ea1n th\u1ef1c s\u1ef1 hi\u1ec3u n\u00f3.\n\nB\u00e2y gi\u1edd ch\u00fang ra c\u00f3 th\u1ec3 ch\u1ee9ng minh b\u1eb1ng to\u00e1n h\u1ecdc t\u1ea1i sao quan h\u1ec7 t\u01b0\u01a1ng quan kh\u00f4ng ph\u1ea3i quan h\u1ec7 nh\u00e2n qu\u1ea3. Quan h\u1ec7 t\u01b0\u01a1ng quan \u0111\u01b0\u1ee3c \u0111o b\u1edfi \\\\(E[Y|T=1] - E[Y|T=0]\\\\). Trong v\u00ed d\u1ee5 c\u1ee7a ch\u00fang ta, n\u00f3 l\u00e0 hi\u1ec7u gi\u1eefa \u0111i\u1ec3m thi trung b\u00ecnh c\u1ee7a c\u00e1c tr\u01b0\u1eddng ph\u00e1t m\u00e1y t\u00ednh b\u1ea3ng v\u00e0 \u0111i\u1ec3m thi trung b\u00ecnh c\u1ee7a c\u00e1c tr\u01b0\u1eddng kh\u00f4ng ph\u00e1t m\u00e1y t\u00ednh b\u1ea3ng. Trong khi \u0111\u00f3, quan h\u1ec7 nh\u00e2n qu\u1ea3 \u0111\u01b0\u1ee3c \u0111o b\u1edfi \\\\(E[Y_1 - Y_0]\\\\).\n\n\u0110\u1ec3 bi\u1ebft ch\u00fang li\u00ean quan \u0111\u1ebfn nhau nh\u01b0 th\u1ebf n\u00e0o, h\u00e3y d\u00f9ng c\u00f4ng th\u1ee9c t\u00ednh quan h\u1ec7 t\u01b0\u01a1ng quan v\u00e0 thay c\u00e1c k\u1ebft qu\u1ea3 quan s\u00e1t b\u1eb1ng c\u00e1c k\u1ebft qu\u1ea3 ti\u1ec1m n\u0103ng. V\u1edbi c\u00e1c tr\u01b0\u1eddng \u0111\u01b0\u1ee3c can thi\u1ec7p, k\u1ebft qu\u1ea3 quan s\u00e1t l\u00e0 \\\\(Y_1\\\\). V\u1edbi c\u00e1c tr\u01b0\u1eddng \u0111\u1ed1i ch\u1ee9ng, k\u1ebft qu\u1ea3 quan s\u00e1t l\u00e0 \\\\(Y_0\\\\).\n\n$\nE[Y|T=1] - E[Y|T=0] = E[Y_1|T=1] - E[Y_0|T=0]\n$\n\nB\u00e2y gi\u1edd h\u00e3y c\u1ed9ng r\u1ed3i tr\u1eeb k\u1ebft qu\u1ea3 gi\u1ea3 t\u01b0\u1edfng \\\\(E[Y_0|T=1]\\\\). N\u00f3 cho ta bi\u1ebft \u0111i\u1ec1u g\u00ec x\u1ea3y ra v\u1edbi k\u1ebft qu\u1ea3 c\u1ee7a c\u00e1c tr\u01b0\u1eddng \u0111\u01b0\u1ee3c can thi\u1ec7p n\u1ebfu ch\u00fang kh\u00f4ng nh\u1eadn can thi\u1ec7p.\n\n$\nE[Y|T=1] - E[Y|T=0] = E[Y_1|T=1] - E[Y_0|T=0] + E[Y_0|T=1] - E[Y_0|T=1]\n$\n\nCu\u1ed1i c\u00f9ng, ch\u00fang ta s\u1eafp x\u1ebfp l\u1ea1i v\u00e0 nh\u00f3m c\u00e1c k\u00ec v\u1ecdng v\u00e0 thu \u0111\u01b0\u1ee3c:\n\n$\nE[Y|T=1] - E[Y|T=0] = \\underbrace{E[Y_1 - Y_0|T=1]}_{ATET} + \\underbrace{\\{ E[Y_0|T=1] - E[Y_0|T=0] \\}}_{THI\u00caN L\u1ec6CH}\n$\n\nC\u00f4ng th\u1ee9c to\u00e1n h\u1ecdc \u0111\u01a1n gi\u1ea3n n\u00e0y c\u00f3 th\u1ec3 gi\u00fap ta gi\u1ea3i quy\u1ebft c\u00e1c v\u1ea5n \u0111\u1ec1 li\u00ean quan \u0111\u1ebfn c\u00e1c c\u00e2u h\u1ecfi v\u1ec1 nh\u00e2n qu\u1ea3. T\u00f4i kh\u00f4ng th\u1ec3 nh\u1ea5n m\u1ea1nh h\u1ebft vi\u1ec7c hi\u1ec3u ng\u1ecdn ng\u00e0nh c\u00f4ng th\u1ee9c n\u00e0y quan tr\u1ecdng \u0111\u1ebfn nh\u01b0\u1eddng n\u00e0o. N\u1ebfu b\u1ea1n b\u1ecb \u00e9p x\u0103m m\u1ed9t th\u1ee9 g\u00ec \u0111\u00f3 l\u00ean c\u00e1nh tay, ph\u01b0\u01a1ng tr\u00ecnh n\u00e0y c\u00f3 th\u1ec3 l\u00e0 m\u1ed9t l\u1ef1a ch\u1ecdn t\u1ed1t. N\u00f3 l\u00e0 m\u1ed9t th\u1ee9 g\u00ec \u0111\u00f3 c\u1ea7n gi\u1eef ch\u1eb7t l\u1ea5y v\u00e0 c\u1ea7n th\u1ef1c s\u1ef1 hi\u1ec3u, gi\u1ed1ng nh\u01b0 m\u1ed9t kh\u1ea9u quy\u1ebft c\u00f3 th\u1ec3 di\u1ec5n gi\u1ea3i theo h\u00e0ng tr\u0103m c\u00e1ch kh\u00e1c nhau. Th\u1ef1c t\u1ebf, h\u00e3y xem x\u00e9t k\u0129 l\u01b0\u1ee1ng h\u01a1n v\u00e0 t\u00ecm hi\u1ec3u m\u1ed9t v\u00e0i h\u00e0m \u00fd c\u1ee7a n\u00f3.\n\nTr\u01b0\u1edbc h\u1ebft, ph\u01b0\u01a1ng tr\u00ecnh n\u00e0y gi\u1ea3i th\u00edch t\u1ea1i sao quan h\u1ec7 t\u01b0\u01a1ng quan kh\u00f4ng ph\u1ea3i quan h\u1ec7 nh\u00e2n qu\u1ea3. Ch\u00fang ta c\u00f3 th\u1ec3 th\u1ea5y quan h\u1ec7 t\u01b0\u01a1ng quan bao g\u1ed3m t\u00e1c \u0111\u1ed9ng can thi\u1ec7p tr\u00ean nh\u00f3m \u0111\u01b0\u1ee3c can thi\u1ec7p c\u1ed9ng v\u1edbi ph\u1ea7n thi\u00ean l\u1ec7ch. **Thi\u00ean l\u1ec7ch \u0111\u01b0\u1ee3c t\u00ednh b\u1eb1ng kh\u00e1c bi\u1ec7t gi\u1eefa nh\u00f3m \u0111\u01b0\u1ee3c can thi\u1ec7p v\u00e0 nh\u00f3m \u0111\u1ed1i ch\u1ee9ng tr\u01b0\u1edbc khi c\u00f3 can thi\u1ec7p,  n\u1ebfu t\u1ea1m gi\u1ea3 thi\u1ebft c\u1ea3 2 nh\u00f3m \u0111\u1ec1u ch\u01b0a t\u1eebng nh\u1eadn can thi\u1ec7p**. B\u00e2y gi\u1edd ta c\u00f3 th\u1ec3 n\u00f3i ch\u00ednh x\u00e1c v\u00ec sao ta nghi ng\u1edd n\u1ebfu ai \u0111\u00f3 n\u00f3i r\u1eb1ng vi\u1ec7c d\u00f9ng m\u00e1y t\u00ednh b\u1ea3ng trong l\u1edbp h\u1ecdc t\u0103ng c\u01b0\u1eddng k\u1ebft qu\u1ea3 h\u1ecdc t\u1eadp. Ch\u00fang ta cho r\u1eb1ng, trong tr\u01b0\u1eddng h\u1ee3p n\u00e0y, \\\\(E[Y_0|T=0] < E[Y_0|T=1]\\\\), ngh\u0129a l\u00e0, c\u00e1c tr\u01b0\u1eddng c\u00f3 ti\u1ec1n \u0111\u1ec3 ph\u00e1t m\u00e1y t\u00ednh b\u1ea3ng v\u1ed1n d\u0129 ho\u1ea1t \u0111\u1ed9ng t\u1ed1t h\u01a1n c\u00e1c tr\u01b0\u1eddng kh\u00e1c, **d\u00f9 c\u00f3 can thi\u1ec7p ph\u00e1t m\u00e1y t\u00ednh b\u1ea3ng hay kh\u00f4ng**. \n\nT\u1ea1i sao l\u1ea1i c\u00f3 \u0111i\u1ec1u n\u00e0y? Ch\u00fang ta s\u1ebd n\u00f3i k\u0129 h\u01a1n khi v\u1ec1 v\u1ea5n \u0111\u1ec1 n\u00e0y khi \u0111\u1ec1 c\u1eadp \u0111\u1ebfn nhi\u1ec5u (trong c\u00e1c b\u00e0i t\u1edbi), nh\u01b0ng b\u00e2y gi\u1edd b\u1ea1n c\u00f3 th\u1ec3 ngh\u0129 v\u1ec1 vi\u1ec7c thi\u00ean l\u1ec7ch x\u1ea3y ra do nhi\u1ec1u y\u1ebfu t\u1ed1 ch\u00fang ta kh\u00f4ng th\u1ec3 ki\u1ebfm so\u00e1t nh\u01b0ng t\u00e1c \u0111\u1ed9ng \u0111\u1ebfn can thi\u1ec7p. K\u1ebft qu\u1ea3 l\u00e0 c\u00e1c tr\u01b0\u1eddng \u0111\u01b0\u1ee3c can thi\u1ec7p v\u00e0 \u0111\u1ed1i ch\u1ee9ng kh\u00f4ng ch\u1ec9 kh\u00e1c nhau v\u1ec1 vi\u1ec7c ph\u00e1t m\u00e1y t\u00ednh b\u1ea3ng. Ch\u00fang c\u0169ng c\u00f3 th\u1ec3 kh\u00e1c bi\u1ec7t v\u1ec1 h\u1ecdc ph\u00ed, \u0111\u1ecba \u0111i\u1ec3m, gi\u00e1o vi\u00ean ... \u0110\u1ec3 ch\u00fang ta c\u00f3 th\u1ec3 n\u00f3i r\u1eb1ng vi\u1ec7c d\u00f9ng m\u00e1y t\u00ednh b\u1ea3ng trong l\u1edbp h\u1ecdc l\u00e0m t\u0103ng k\u1ebft qu\u1ea3 h\u1ecdc t\u1eadp, ch\u00fang ta c\u1ea7n \u0111\u1ea3m b\u1ea3o c\u00e1c tr\u01b0\u1eddng h\u1ecdc theo \u0111u\u1ed5i v\u00e0 kh\u00f4ng theo \u0111u\u1ed5i ch\u00ednh s\u00e1ch n\u00e0y t\u01b0\u01a1ng t\u1ef1 nhau v\u1ec1 m\u1eb7t b\u1eb1ng chung.\n\n\n```python\nplt.figure(figsize=(10,6))\nsns.scatterplot(x=\"h\u1ecdc_ph\u00ed\", y=\"\u0111i\u1ec3m_enem\", hue=\"m\u00e1y_t\u00ednh_b\u1ea3ng\", data=data, s=70).set_title('\u0110i\u1ec3m ENEM theo H\u1ecdc ph\u00ed')\nplt.show()\n```\n\nCh\u00fang ta c\u0169ng c\u00f3 th\u1ec3 n\u00eau \u0111i\u1ec1u ki\u1ec7n c\u1ea7n \u0111\u1ec3 quan h\u1ec7 t\u01b0\u01a1ng quan \u0111\u1ed3ng th\u1eddi l\u00e0 quan h\u1ec7 nh\u00e2n qu\u1ea3. **N\u1ebfu \\\\(E[Y_0|T=0] = E[Y_0|T=1]\\\\), th\u00ec, quan h\u1ec7 t\u01b0\u01a1ng quan  L\u00c0 QUAN H\u1ec6 NH\u00c2N QU\u1ea2!** \u0110\u1ec3 hi\u1ec3u \u0111i\u1ec1u n\u00e0y kh\u00f4ng ch\u1ec9 c\u1ea7n ghi nh\u1edb c\u00f4ng th\u1ee9c. C\u00f3 m\u1ed9t l\u1eadp lu\u1eadn kh\u00e1 tr\u1ef1c quan \u1edf \u0111\u00e2y. N\u00f3i r\u1eb1ng \\\\(E[Y_0|T=0] = E[Y_0|T=1]\\\\) ngh\u0129a l\u00e0 n\u00f3i r\u1eb1ng nh\u00f3m \u0111\u01b0\u1ee3c can thi\u1ec7p v\u00e0 nh\u00f3m \u0111\u1ed1i ch\u1ee9ng kh\u00e1 t\u01b0\u01a1ng \u0111\u1ed3ng khi kh\u00f4ng t\u00ednh \u0111\u1ebfn can thi\u1ec7p. Ho\u1eb7c, trong tr\u01b0\u1eddng h\u1ee3p gi\u1ea3 thi\u1ebft nh\u00f3m \u0111\u01b0\u1ee3c can thi\u1ec7p ch\u01b0a \u0111\u01b0\u1ee3c can thi\u1ec7p, n\u1ebfu ta c\u00f3 th\u1ec3 quan s\u00e1t \\\\(Y_0\\\\), th\u00ec k\u1ebft qu\u1ea3 c\u1ee7a n\u00f3 ph\u1ea3i t\u01b0\u01a1ng t\u1ef1 nh\u01b0 nh\u00f3m \u0111\u1ed1i ch\u1ee9ng. V\u1ec1 m\u1eb7t to\u00e1n h\u1ecdc, ph\u1ea7n thi\u00ean l\u1ec7ch b\u1ecb gi\u1ea3n \u01b0\u1edbc.\n\n$\nE[Y|T=1] - E[Y|T=0] = E[Y_1 - Y_0|T=1]\n$\n\nV\u00e0 n\u1ebfu nh\u00f3m \u0111\u01b0\u1ee3c can thi\u1ec7p v\u00e0 nh\u00f3m \u0111\u1ed1i ch\u1ee9ng ch\u1ec9 kh\u00e1c nhau \u1edf can thi\u1ec7p, t\u1ee9c l\u00e0 \\\\(E[Y_0|T=0] = E[Y_0|T=1]\\\\), ta c\u00f3:\n\n$\n\\begin{align}\nE[Y_1 - Y_0|T=1] &= E[Y_1|T=1] - E[Y_0|T=1] \\\\\\\\\n    &= E[Y_1|T=1] - E[Y_0|T=0] \\\\\\\\\n    &= E[Y|T=1] - E[Y|T=0]\n\\end{align}\n$\n\nV\u00ec th\u1ebf trong tr\u01b0\u1eddng h\u1ee3p n\u00e0y, **hi\u1ec7u c\u1ee7a c\u00e1c gi\u00e1 tr\u1ecb trung b\u00ecnh L\u00c0 t\u00e1c \u0111\u1ed9ng nh\u00e2n qu\u1ea3**:\n\n$\nE[Y|T=1] - E[Y|T=0] = ATE = ATET\n$\n\n\u0110i\u1ec1u n\u00e0y kh\u00e1 quan tr\u1ecdng, n\u00ean ch\u00fang ta h\u00e3y nh\u1eafc l\u1ea1i b\u1eb1ng m\u1ed9t bi\u1ec3u \u0111\u1ed3 th\u00fa v\u1ecb. N\u1ebfu ch\u00fang ta ch\u1ec9 \u0111\u01a1n thu\u1ea7n so s\u00e1nh gi\u00e1 tr\u1ecb trung b\u00ecnh gi\u1eefa nh\u00f3m \u0111\u01b0\u1ee3c can thi\u1ec7p v\u00e0 \u0111\u1ed1i ch\u1ee9ng, ch\u00fang ta thu \u0111\u01b0\u1ee3c \u0111\u1ed3 th\u1ecb sau (c\u00e1c ch\u1ea5m xanh kh\u00f4ng \u0111\u01b0\u1ee3c nh\u1eadn can thi\u1ec7p, ph\u00e1t m\u00e1y t\u00ednh b\u1ea3ng):\n\n\n\nL\u01b0u \u00fd s\u1ef1 kh\u00e1c bi\u1ec7t trong k\u1ebft qu\u1ea3 gi\u1eefa hai nh\u00f3m \u0111\u01b0\u1ee3c t\u1ea1o n\u00ean b\u1edfi 2 nguy\u00ean nh\u00e2n:\n\n1. T\u00e1c \u0111\u1ed9ng can thi\u1ec7p. S\u1ef1 gia t\u0103ng \u0111i\u1ec3m s\u1ed1 thu\u1ea7n tu\u00fd do ph\u00e1t m\u00e1y t\u00ednh b\u1ea3ng cho h\u1ecdc sinh.\n2. C\u00e1c kh\u00e1c bi\u1ec7t kh\u00e1c gi\u1eefa nh\u00f3m \u0111\u01b0\u1ee3c can thi\u1ec7p v\u00e0 \u0111\u1ed1i ch\u1ee9ng KH\u00d4NG \u0111\u01b0\u1ee3c t\u1ea1o ra b\u1edfi b\u1ea3n th\u00e2n can thi\u1ec7p. Trong tr\u01b0\u1eddng h\u1ee3p n\u00e0y, nh\u00f3m \u0111\u01b0\u1ee3c can thi\u1ec7p v\u00e0 \u0111\u1ed1i ch\u1ee9ng kh\u00e1c nhau \u1edf ch\u1ed7 nh\u00f3m \u0111\u01b0\u1ee3c can thi\u1ec7p c\u00f3 h\u1ecdc ph\u00ed cao h\u01a1n h\u1eb3n. M\u1ed9t s\u1ed1 kh\u00e1c bi\u1ec7t trong k\u1ebft qu\u1ea3 thi c\u00f3 th\u1ec3 do t\u00e1c \u0111\u1ed9ng t\u00edch c\u1ef1c c\u1ee7a h\u1ecdc ph\u00ed cao v\u1edbi ch\u1ea5t l\u01b0\u1ee3ng gi\u00e1o d\u1ee5c. \n\nCh\u00fang ta ch\u1ec9 c\u00f3 th\u1ec3 bi\u1ebft \u0111\u01b0\u1ee3c t\u00e1c \u0111\u1ed9ng th\u1ef1c s\u1ef1 c\u1ee7a can thi\u1ec7p n\u1ebfu ta c\u00f3 quy\u1ec1n l\u1ef1c si\u00eau nhi\u00ean quan s\u00e1t \u0111\u01b0\u1ee3c k\u1ebft qu\u1ea3 ti\u1ec1m n\u0103ng, gi\u1ed1ng nh\u01b0 \u0111\u1ed3 th\u1ecb b\u00ean tr\u00e1i d\u01b0\u1edbi \u0111\u00e2y. Hi\u1ec7u \u1ee9ng can thi\u1ec7p c\u00e1 th\u1ec3 l\u00e0 hi\u1ec7u gi\u1eefa k\u1ebft qu\u1ea3 c\u1ee7a m\u1ed7i c\u00e1 nh\u00e2n v\u00e0 k\u1ebft qu\u1ea3 l\u00fd thuy\u1ebft c\u1ee7a c\u00f9ng c\u00e1 nh\u00e2n \u0111\u00f3 n\u1ebfu thay \u0111\u1ed5i vi\u1ec7c ph\u00e2n b\u1ed5 can thi\u1ec7p. Ch\u00fang l\u00e0 c\u00e1c  k\u1ebft qu\u1ea3 gi\u1ea3 t\u01b0\u1edfng v\u00e0 \u0111\u01b0\u1ee3c bi\u1ec3u di\u1ec5n b\u1eb1ng m\u00e0u nh\u1ea1t h\u01a1n.\n\n\n\n\u1ede \u0111\u1ed3 th\u1ecb b\u00ean tr\u00e1i, ta bi\u1ec3u di\u1ec5n thi\u00ean l\u1ec7ch \u0111\u01b0\u1ee3c nh\u1eafc \u0111\u1ebfn \u1edf ph\u1ea7n tr\u01b0\u1edbc. Ch\u00fang ta thu \u0111\u01b0\u1ee3c thi\u00ean l\u1ec7ch n\u1ebfu ch\u00fang ta kh\u00f4ng ch\u1ec9 \u0111\u1ecbnh can thi\u1ec7p cho b\u1ea5t k\u00ec ai. Trong tr\u01b0\u1eddng h\u1ee3p n\u00e0y, ch\u00fang ta ch\u1ec9 c\u00f2n k\u1ebft qu\u1ea3 ti\u1ec1m n\u0103ng \\\\(Y_0\\\\). Sau \u0111\u00f3, ta theo d\u00f5i xem nh\u00f3m \u0111\u01b0\u1ee3c can thi\u1ec7p v\u00e0 \u0111\u1ed1i ch\u1ee9ng kh\u00e1c nhau nh\u01b0 th\u1ebf n\u00e0o. N\u1ebfu ch\u00fang kh\u00e1c bi\u1ec7t, nh\u00e2n t\u1ed1 n\u00e0o \u0111\u00f3 ngo\u00e0i can thi\u1ec7p g\u00e2y ra kh\u00e1c bi\u1ec7t gi\u1eefa 2 nh\u00f3m. Nh\u00e2n t\u1ed1 n\u00e0o \u0111\u00f3 \u1edf \u0111\u00e2y l\u00e0 nguy\u00ean nh\u00e2n thi\u00ean l\u1ec7ch v\u00e0 g\u00e2y nhi\u1ec5u t\u00e1c \u0111\u1ed9ng can thi\u1ec7p trong th\u1ef1c t\u1ebf.\n\nB\u00e2y gi\u1edd, h\u00e3y so s\u00e1nh n\u00f3 v\u1edbi t\u00ecnh hu\u1ed1ng gi\u1ea3 t\u01b0\u1edfng r\u1eb1ng kh\u00f4ng c\u00f3 thi\u00ean l\u1ec7ch. Gi\u1ea3 s\u1eed m\u00e1y t\u00ednh b\u1ea3ng \u0111\u01b0\u1ee3c ph\u00e1t ng\u1eabu nhi\u00ean t\u1ea1i c\u00e1c tr\u01b0\u1eddng h\u1ecdc. Trong c\u00e1c t\u00ecnh hu\u1ed1ng n\u00e0y, c\u00e1c tr\u01b0\u1eddng gi\u00e0u v\u00e0 tr\u01b0\u1eddng ngh\u00e8o \u0111\u1ec1u nh\u1eadn \u0111\u01b0\u1ee3c can thi\u1ec7p v\u1edbi x\u00e1c su\u1ea5t nh\u01b0 nhau. Can thi\u1ec7p s\u1ebd ph\u00e2n b\u1ed5 \u0111\u1ed3ng \u0111\u1ec1u theo h\u1ecdc ph\u00ed.\n\n\n\nTrong tr\u01b0\u1eddng h\u1ee3p n\u00e0y, hi\u1ec7u gi\u1eefa k\u1ebft qu\u1ea3 c\u1ee7a nh\u00f3m \u0111\u01b0\u1ee3c can thi\u1ec7p v\u00e0 \u0111\u1ed1i ch\u1ee9ng L\u00c0 t\u00e1c \u0111\u1ed9ng nh\u00e2n qu\u1ea3 trung b\u00ecnh. \u0110i\u1ec1u n\u00e0y x\u1ea3y ra v\u00e0 kh\u00f4ng c\u00f3 nguy\u00ean nh\u00e2n n\u00e0o kh\u00e1c g\u00e2y ra kh\u00e1c bi\u1ec7t gi\u1eefa nh\u00f3m \u0111\u01b0\u1ee3c can thi\u1ec7p v\u00e0 \u0111\u1ed1i ch\u1ee9ng ngo\u00e0i b\u1ea3n th\u00e2n can thi\u1ec7p. V\u00ec th\u1ebf m\u1ecdi s\u1ef1 kh\u00e1c bi\u1ec7t \u0111\u1ec1u c\u00f3 th\u1ec3 g\u00e1n cho can thi\u1ec7p. N\u00f3i c\u00e1ch kh\u00e1c l\u00e0 kh\u00f4ng c\u00f3 thi\u00ean l\u1ec7ch. \n\n\n\nN\u1ebfu ch\u00fang ta s\u1eafp x\u1ebfp \u0111\u1ec3 kh\u00f4ng ai \u0111\u01b0\u1ee3c nh\u1eadn can thi\u1ec7p, v\u00e0 v\u00ec th\u1ebf ch\u00fang ta ch\u1ec9 quan s\u00e1t \u0111\u01b0\u1ee3c c\u00e1c \\\\(Y_0\\\\), ch\u00fang ta s\u1ebd kh\u00f4ng th\u1ea5y kh\u00e1c bi\u1ec7t gi\u1eefa nh\u00f3m \u0111\u01b0\u1ee3c can thi\u1ec7p v\u00e0 \u0111\u1ed1i ch\u1ee9ng. \u0110\u00e2y l\u00e0 m\u1ea5u ch\u1ed1t c\u1ee7a suy lu\u1eadn nh\u00e2n qu\u1ea3. T\u00ecm ki\u1ebfm ph\u01b0\u01a1ng ph\u00e1p th\u00f4ng minh \u0111\u1ec3 lo\u1ea1i b\u1ecf  thi\u00ean l\u1ec7ch  r\u1ed3i t\u1eeb \u0111\u00f3 quy k\u1ebft m\u1ecdi kh\u00e1c bi\u1ec7t gi\u1eefa nh\u00f3m \u0111\u01b0\u1ee3c can thi\u1ec7p v\u00e0 \u0111\u1ed1i ch\u1ee9ng l\u00e0 do t\u00e1c \u0111\u1ed9ng can thi\u1ec7p trung b\u00ecnh.\n\n\u0110\u00e2y l\u00e0 nhi\u1ec7m v\u1ee5 \"kh\u1ee7ng\" c\u1ee7a suy lu\u1eadn nh\u00e2n qu\u1ea3. N\u00f3 \u0111\u00f2i h\u1ecfi nh\u1eefng ph\u01b0\u01a1ng th\u1ee9c th\u00f4ng m\u00ecnh \u0111\u1ec3 lo\u1ea1i b\u1ecf thi\u00ean l\u1ec7ch, l\u00e0m cho c\u00e1c \u0111\u1ed1i t\u01b0\u1ee3ng nh\u1eadn can thi\u1ec7p v\u00e0 \u0111\u1ed1i ch\u1ee9ng t\u01b0\u01a1ng \u0111\u01b0\u01a1ng v\u00e0 t\u1eeb \u0111\u00f3 m\u1ecdi kh\u00e1c bi\u1ec7t gi\u1eefa ch\u00fang c\u00f3 th\u1ec3 g\u00e1n cho t\u00e1c \u0111\u1ed9ng can thi\u1ec7p trung b\u00ecnh. M\u1ee5c \u0111\u00edch sau c\u00f9ng c\u1ee7a suy lu\u1eadn nh\u00e2n qu\u1ea3 l\u00e0 kh\u00e1m ph\u00e1 c\u00e1ch th\u1ebf gi\u1edbi v\u1eadn h\u00e0nh, lo\u1ea1i b\u1ecf \u1ea3o gi\u00e1c v\u00e0 c\u00e1ch di\u1ec5n gi\u1ea3i sai l\u1ec7ch. V\u00e0 b\u00e2y gi\u1edd ch\u00fang ta hi\u1ec3u \u0111i\u1ec1u n\u00e0y, ch\u00fang ta c\u00f3 th\u1ec3 ti\u1ebfn t\u1edbi h\u1ecdc c\u00e1ch ph\u01b0\u01a1ng ph\u00e1p quy\u1ec1n l\u1ef1c gi\u00fap lo\u1ea1i b\u1ecf thi\u00ean l\u1ec7ch, v\u0169 kh\u00ed c\u1ee7a nh\u1eefng chi\u1ebfn binh Qu\u1ea3 c\u1ea3m Ch\u00e2n ch\u00ednh gi\u00fap x\u00e1c \u0111\u1ecbnh t\u00e1c \u0111\u1ed9ng nh\u00e2n qu\u1ea3.\n\n# \u00dd t\u01b0\u1edfng ch\u1ee7 \u0111\u1ea1o\n\nTr\u00ean \u0111\u00e2y ch\u00fang ta \u0111\u00e3 nh\u1eadn th\u1ea5y quan h\u1ec7 t\u01b0\u01a1ng quan kh\u00f4ng ph\u1ea3i quan h\u1ec7 nh\u00e2n qu\u1ea3. Quan tr\u1ecdng h\u01a1n, ch\u00fang ta th\u1ea5y r\u00f5 t\u1ea1i sao kh\u00f4ng ph\u1ea3i v\u1eady v\u00e0 l\u00e0m th\u1ebf n\u00e0o \u0111\u1ec3 quan h\u1ec7 t\u01b0\u01a1ng quan tr\u1edf th\u00e0nh quan h\u1ec7 nh\u00e2n qu\u1ea3. Ch\u00fang ta c\u0169ng \u0111\u00e3 t\u00ecm hi\u1ec3u c\u00f4ng th\u1ee9c k\u1ebft qu\u1ea3 ti\u1ec1m n\u0103ng nh\u01b0 l\u00e0 m\u1ed9t ph\u01b0\u01a1ng ph\u00e1p \u0111\u1ec3 g\u00f3i g\u1ecdn v\u1ea5n \u0111\u1ec1 suy lu\u1eadn nh\u00e2n qu\u1ea3. C\u00f9ng v\u1edbi \u0111\u00f3, ch\u00fang ta t\u00ecm hi\u1ec3u th\u1ed1ng k\u00ea trong 2 t\u00ecnh hu\u1ed1ng hi\u1ec7n th\u1ef1c lo\u1ea1i tr\u1eeb nhau: c\u00f3 v\u00e0 kh\u00f4ng c\u00f3 can thi\u1ec7p. \u0110\u00e1ng ti\u1ebfc l\u00e0 ch\u00fang ta ch\u1ec9 c\u00f3 th\u1ec3 quan s\u00e1t v\u00e0 \u0111o l\u01b0\u1eddng 1 trong 2 t\u00ecnh hu\u1ed1ng \u0111\u00f3, v\u00e0 \u0111\u00e2y l\u00e0 th\u00e1ch th\u1ee9c c\u01a1 b\u1ea3n c\u1ee7a suy lu\u1eadn nh\u00e2n qu\u1ea3.\n\nTrong c\u00e1c b\u00e0i t\u1edbi, ch\u00fang ta s\u1ebd t\u00ecm hi\u1ec3u m\u1ed9t s\u1ed1 k\u0129 thu\u1eadt c\u01a1 b\u1ea3n \u0111\u1ec3 \u01b0\u1edbc l\u01b0\u1ee3ng t\u00e1c \u0111\u1ed9ng nh\u00e2n qu\u1ea3, b\u1eaft \u0111\u1ea7u t\u1eeb ti\u00eau chu\u1ea9n v\u00e0ng nh\u1edd v\u00e0o th\u1eed nghi\u1ec7m ng\u1eabu nhi\u00ean. T\u00f4i c\u0169ng s\u1ebd t\u1ed5ng k\u1ebft m\u1ed9t s\u1ed1 kh\u00e1i ni\u1ec7m th\u1ed1ng k\u00ea c\u1ea7n d\u00f9ng. T\u00f4i k\u1ebft th\u00fac b\u00e0i vi\u1ebft n\u00e0y v\u1edbi m\u1ed9t cu\u1ed9c tho\u1ea1i th\u01b0\u1eddng \u0111\u01b0\u1ee3c tr\u00edch d\u1eabn trong c\u00e1c l\u1edbp h\u1ecdc suy lu\u1eadn nh\u00e2n qu\u1ea3 t\u1eeb series phim Kungfu:\n\n```\n'\u0110i\u1ec1u g\u00ec x\u1ea3y \u0111\u1ebfn v\u1edbi m\u1ed7i \u0111\u1eddi ng\u01b0\u1eddi \u0111\u1ec1u \u0111\u00e3 \u0111\u01b0\u1ee3c \u0111\u1ecbnh s\u1eb5n. Ai b\u01b0\u1edbc qua cu\u1ed9c \u0111\u1eddi n\u00e0y c\u0169ng \u0111\u1ec1u theo s\u1ed1 ph\u1eadn an b\u00e0i m\u00e0 th\u00f4i.' -Caine\n'\u0110\u00fang v\u1eady, nh\u01b0ng m\u1ed7i ng\u01b0\u1eddi l\u1ea1i to\u00e0n quy\u1ec1n s\u1ed1ng theo c\u00e1ch m\u00ecnh ch\u1ecdn l\u1ef1a. T\u01b0\u1edfng ch\u1eebng m\u00e2u thu\u1eabn, nh\u01b0ng c\u1ea3 hai \u0111\u1ec1u l\u00e0 ch\u00e2n l\u00fd. - Tr\u01b0\u1edfng l\u00e3o\n```\n\n# T\u00e0i li\u1ec7u tham kh\u1ea3o\n\nT\u00f4i mu\u1ed1n d\u00e0nh lo\u1ea1t b\u00e0i vi\u1ebft n\u00e0y \u0111\u1ec3 vinh danh Joshua Angrist, Alberto Abadie and Christopher Walters v\u00ec kh\u00f3a h\u1ecdc Kinh t\u1ebf l\u01b0\u1ee3ng tuy\u1ec7t c\u00fa m\u00e8o c\u1ee7a h\u1ecd. Ph\u1ea7n l\u1edbn \u00fd t\u01b0\u1edfng trong lo\u1ea1t b\u00e0i n\u00e0y \u0111\u01b0\u1ee3c l\u1ea5y t\u1eeb c\u00e1c b\u00e0i gi\u1ea3ng c\u1ee7a h\u1ecd \u0111\u01b0\u1ee3c t\u1ed5 ch\u1ee9c b\u1edfi Hi\u1ec7p h\u1ed9i Kinh t\u1ebf M\u0129.  Theo d\u00f5i c\u00e1c b\u00e0i gi\u1ea3ng n\u00e0y l\u00e0 nh\u1eefng g\u00ec t\u00f4i l\u00e0m trong su\u1ed1t n\u0103m 2020 kh\u00f3 nh\u1eb1n.\n* [Kinh t\u1ebf l\u01b0\u1ee3ng v\u1edbi d\u1eef li\u1ec7u ch\u00e9o](https://www.aeaweb.org/conference/cont-ed/2017-webcasts)\n* [Luy\u1ec7n ch\u01b0\u1edfng Kinh t\u1ebf l\u01b0\u1ee3ng G\u1ea7n nh\u01b0 V\u00f4 h\u1ea1i](https://www.aeaweb.org/conference/cont-ed/2020-webcasts)\n\nT\u00f4i c\u0169ng mu\u1ed1n gi\u1edbi thi\u1ec7u cu\u1ed1n s\u00e1ch l\u00fd th\u00fa c\u1ee7a Angrist. Ch\u00fang cho t\u00f4i th\u1ea5y Kinh t\u1ebf l\u01b0\u1ee3ng, ho\u1eb7c 'L\u01b0\u1ee3ng theo c\u00e1ch h\u1ecd g\u1ecdi kh\u00f4ng ch\u1ec9 v\u00f4 c\u00f9ng h\u1eefu \u00edch m\u00e0 c\u00f2n r\u1ea5t vui.\n\n* [Kinh t\u1ebf l\u01b0\u1ee3ng G\u1ea7n nh\u01b0 V\u00f4 h\u1ea1i](https://www.mostlyharmlesseconometrics.com/)\n* [Luy\u1ec7n ch\u01b0\u1edfng 'L\u01b0\u1ee3ng](https://www.masteringmetrics.com/)\n\nT\u00e0i li\u1ec7u tham kh\u1ea3o cu\u1ed1i c\u00f9ng c\u1ee7a t\u00f4i l\u00e0 cu\u1ed1n s\u00e1ch c\u1ee7a Miguel Hernan and Jamie Robins. N\u00f3 l\u00e0 ng\u01b0\u1eddi b\u1ea1n \u0111\u1ed3ng h\u00e0nh tin c\u1eady v\u1edbi t\u00f4i khi tr\u1ea3 l\u1eddi nh\u1eefng c\u00e2u h\u1ecfi nh\u00e2n qu\u1ea3 kh\u00f3 nh\u1eb1n.\n\n* [S\u00e1ch Suy Lu\u1eadn Nh\u00e2n Qu\u1ea3](https://www.hsph.harvard.edu/miguel-hernan/causal-inference-book/)\n\nPh\u00e9p so s\u00e1nh c\u1ed1c bia trong b\u00e0i n\u00e0y \u0111\u01b0\u1ee3c l\u1ea5y t\u1eeb [\u0110\u1ea7u t\u01b0 Ch\u1ee9ng kho\u00e1n](https://jlcollinsnh.com/2012/04/15/stocks-part-1-theres-a-major-market-crash-coming-and-dr-lo-cant-save-you/), vi\u1ebft b\u1edfi JL Colins. \u0110\u00e2y l\u00e0 lo\u1ea1t b\u00e0i ph\u1ea3i \u0111\u1ecdc cho b\u1ea5t k\u00ec ai mu\u1ed1n \u0111\u1ea7u t\u01b0 hi\u1ec7u qu\u1ea3.\n\n\n\n# B\u1ea3ng T\u1eeb Vi\u1ebft t\u1eaft \n|Vi\u1ebft t\u1eaft| Ti\u1ebfng Anh | Ti\u1ebfng Vi\u1ec7t |\n| --- | --- | --- | \n|AI|Artificial Intelligence|Tr\u00ed tu\u1ec7 Nh\u00e2n t\u1ea1o| \n|ATET|Average Treatment Effect on the Treated|T\u00e1c \u0111\u1ed9ng Can thi\u1ec7p Trung b\u00ecnh tr\u00ean Nh\u00f3m \u0111\u01b0\u1ee3c Can thi\u1ec7p| \n|ML|Machine Learning|H\u1ecdc M\u00e1y| \n\n\n# B\u1ea3ng Thu\u1eadt ng\u1eef \n| Thu\u1eadt ng\u1eef | Ti\u1ebfng Anh |\n| --- | --- | \n|chuy\u00ean gia d\u1eef li\u1ec7u|data scientist| \n|d\u1ef1 \u0111o\u00e1n|predict, prediction| \n|gi\u1ea3 t\u01b0\u1edfng|counterfactual| \n|hi\u1ec7n th\u1ef1c|factual| \n|hi\u1ec7u \u1ee9ng can thi\u1ec7p c\u00e1 th\u1ec3|individual treatment effect| \n|khoa h\u1ecdc d\u1eef li\u1ec7u|data science| \n|kinh t\u1ebf l\u01b0\u1ee3ng|econometrics| \n|k\u1ebft qu\u1ea3|outcome| \n|k\u1ebft qu\u1ea3 gi\u1ea3 t\u01b0\u1edfng|counterfactual outcome| \n|k\u1ebft qu\u1ea3 quan s\u00e1t|observed outcome| \n|k\u1ebft qu\u1ea3 ti\u1ec1m n\u0103ng|potential outcome| \n|nhi\u1ec5u|confounding| \n|nh\u00f3m \u0111\u01b0\u1ee3c can thi\u1ec7p|treatment group, test group| \n|nh\u00f3m \u0111\u1ed1i ch\u1ee9ng|control group, untreated group| \n|ph\u1ea7n thi\u00ean l\u1ec7ch|bias term| \n|quan h\u1ec7 nh\u00e2n qu\u1ea3|causality, causation, causal relationship| \n|quan h\u1ec7 t\u01b0\u01a1ng quan|association, correlation| \n|quan s\u00e1t|observe, observation| \n|suy lu\u1eadn nh\u00e2n qu\u1ea3|causal inference, causal reasoning| \n|thi\u00ean l\u1ec7ch|bias| \n|th\u1eed nghi\u1ec7m ng\u1eabu nhi\u00ean|randomised trial| \n|tr\u00ed tu\u1ec7 nh\u00e2n t\u1ea1o|artificial intelligence| \n|t\u00e1c \u0111\u1ed9ng can thi\u1ec7p|treatment effect, treatment impact| \n|t\u00e1c \u0111\u1ed9ng can thi\u1ec7p trung b\u00ecnh|average treatment effect| \n|t\u00e1c \u0111\u1ed9ng can thi\u1ec7p trung b\u00ecnh tr\u00ean nh\u00f3m \u0111\u01b0\u01a1c can thi\u1ec7p|average treatment effect on the treated| \n|t\u00e1c \u0111\u1ed9ng can thi\u1ec7p tr\u00ean nh\u00f3m \u0111\u01b0\u1ee3c can thi\u1ec7p|treatment effect on the treated| \n|t\u00e1c \u0111\u1ed9ng nh\u00e2n qu\u1ea3 trung b\u00ecnh|average causal effect| \n|\u0111\u01b0\u1ee3c can thi\u1ec7p|treated| \n|\u0111\u1ed1i ch\u1ee9ng|untreated, non-treated| \n\n", "meta": {"hexsha": "4f98516cac26b02d5295bddac3d95877342cfa88", "size": 141407, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ipynb/01-Gi\u1edbi-thi\u1ec7u-Suy-lu\u1eadn-Nh\u00e2n-qu\u1ea3-VN.ipynb", "max_stars_repo_name": "vietecon/NhanQuaPython", "max_stars_repo_head_hexsha": "0cf0e78faa9eeef23d8ed2c41125b58cd5a5330b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-11-19T11:59:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-20T02:06:07.000Z", "max_issues_repo_path": "ipynb/01-Gi\u1edbi-thi\u1ec7u-Suy-lu\u1eadn-Nh\u00e2n-qu\u1ea3-VN.ipynb", "max_issues_repo_name": "vietecon/NhanQuaPython", "max_issues_repo_head_hexsha": "0cf0e78faa9eeef23d8ed2c41125b58cd5a5330b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ipynb/01-Gi\u1edbi-thi\u1ec7u-Suy-lu\u1eadn-Nh\u00e2n-qu\u1ea3-VN.ipynb", "max_forks_repo_name": "vietecon/NhanQuaPython", "max_forks_repo_head_hexsha": "0cf0e78faa9eeef23d8ed2c41125b58cd5a5330b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-11-21T09:09:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T12:25:37.000Z", "avg_line_length": 141407.0, "max_line_length": 141407, "alphanum_fraction": 0.8649713239, "converted": true, "num_tokens": 13124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1968262036430985, "lm_q2_score": 0.05665242690069723, "lm_q1q2_score": 0.011150682114032385}}
{"text": "## Release the Kraken!\n\n\n```python\n# The next library we're going to look at is called Kraken, which was developed by Universit\u00e9 \n# PSL in Paris. It's actually based on a slightly older code base, OCRopus. You can see how the\n# flexible open-source licenses allow new ideas to grow by building upon older ideas. And, in\n# this case, I fully support the idea that the Kraken - a mythical massive sea creature - is the\n# natural progression of an octopus!\n#\n# What we are going to use Kraken for is to detect lines of text as bounding boxes in a given\n# image. The biggest limitation of tesseract is the lack of a layout engine inside of it. Tesseract\n# expects to be using fairly clean text, and gets confused if we don't crop out other artifacts.\n# It's not bad, but Kraken can help us out be segmenting pages. Lets take a look.\n#\n# Please note that Kraken is only supported on Linux and Mac OS X, it is not supported on Windows.\n# Documentation and Installation Notes can be found at: https://pypi.org/project/kraken/\n```\n\n\n```python\n!pip install --pre coremltools\n```\n\n    Requirement already satisfied: coremltools in c:\\users\\mosae\\anaconda3\\lib\\site-packages (5.0)\n    Requirement already satisfied: sympy in c:\\users\\mosae\\anaconda3\\lib\\site-packages (from coremltools) (1.8)\n    Requirement already satisfied: numpy>=1.14.5 in c:\\users\\mosae\\anaconda3\\lib\\site-packages (from coremltools) (1.21.2)\n    Requirement already satisfied: protobuf>=3.1.0 in c:\\users\\mosae\\anaconda3\\lib\\site-packages (from coremltools) (3.19.1)\n    Requirement already satisfied: tqdm in c:\\users\\mosae\\anaconda3\\lib\\site-packages (from coremltools) (4.59.0)\n    Requirement already satisfied: packaging in c:\\users\\mosae\\anaconda3\\lib\\site-packages (from coremltools) (20.9)\n    Requirement already satisfied: pyparsing>=2.0.2 in c:\\users\\mosae\\anaconda3\\lib\\site-packages (from packaging->coremltools) (2.4.7)\n    Requirement already satisfied: mpmath>=0.19 in c:\\users\\mosae\\anaconda3\\lib\\site-packages (from sympy->coremltools) (1.2.1)\n\n\n    WARNING: You are using pip version 21.2.4; however, version 21.3.1 is available.\n    You should consider upgrading via the 'c:\\users\\mosae\\anaconda3\\python.exe -m pip install --upgrade pip' command.\n\n\n\n```python\n# First, we'll take a look at the kraken module itself\nimport kraken\nhelp(kraken)\n```\n\n    Help on package kraken:\n    \n    NAME\n        kraken - entry point for kraken functionality\n    \n    PACKAGE CONTENTS\n        binarization\n        ketos\n        kraken\n        lib (package)\n        linegen\n        pageseg\n        repo\n        rpred\n        serialization\n        transcribe\n    \n    DATA\n        absolute_import = _Feature((2, 5, 0, 'alpha', 1), (3, 0, 0, 'alpha', 0...\n        division = _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 1310...\n        print_function = _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0)...\n    \n    FILE\n        c:\\users\\mosae\\anaconda3\\lib\\site-packages\\kraken\\__init__.py\n    \n    \n\n\n\n```python\n# There isn't much of a discussion here, but there are a number of sub-modules that look\n# interesting. I spend a bit of time on their website, and I think the pageseg module, which\n# handles all of the page segmentation, is the one we want to use. Lets look at it\nfrom kraken import pageseg\nhelp(pageseg)\n```\n\n\n```python\n# So it looks like there are a few different functions we can call, and the segment\n# function looks particularly appropriate. I love how expressive this library is on the\n# documentation front -- I can see immediately that we are working with PIL.Image files,\n# and the author has even indicated that we need to pass in either a binarized (e.g. '1')\n# or grayscale (e.g. 'L') image. We can also see that the return value is a dictionary\n# object with two keys, \"text_direction\" which will return to us a string of the\n# direction of the text, and \"boxes\" which appears to be a list of tuples, where each\n# tuple is a box in the original image.\n#\n# Lets try this on the image of text. I have a simple bit of text in a file called\n# two_col.png which is from a newspaper on campus here\nfrom PIL import Image\nim=Image.open(\"download.png\")\n# Lets display the image inline\ndisplay(im)\n# Lets now convert it to black and white and segment it up into lines with kraken\nbounding_boxes=pageseg.segment(im.convert('1'))['boxes']\n# And lets print those lines to the screen\nprint(bounding_boxes)\n```\n\n\n```python\n# Ok, pretty simple two column text and then a list of lists which are the bounding boxes of \n# lines of that text. Lets write a little routine to try and see the effects a bit more\n# clearly. I'm going to clean up my act a bit and write real documentation too, it's a good\n# practice\ndef show_boxes(img):\n    '''Modifies the passed image to show a series of bounding boxes on an image as run by kraken\n    \n    :param img: A PIL.Image object\n    :return img: The modified PIL.Image object\n    '''\n    # Lets bring in our ImageDraw object\n    from PIL import ImageDraw\n    # And grab a drawing object to annotate that image\n    drawing_object=ImageDraw.Draw(img)\n    # We can create a set of boxes using pageseg.segment\n    bounding_boxes=pageseg.segment(img.convert('1'))['boxes']\n    # Now lets go through the list of bounding boxes\n    for box in bounding_boxes:\n        # An just draw a nice rectangle\n        drawing_object.rectangle(box, fill = None, outline ='red')\n    # And to make it easy, lets return the image object\n    return img\n\n# To test this, lets use display\ndisplay(show_boxes(Image.open(\"download.png\")))\n```\n\n\n```python\n# Not bad at all! It's interesting to see that kraken isn't completely sure what to do with this\n# two column format. In some cases, kraken has identified a line in just a single column, while\n# in other cases kraken has spanned the line marker all the way across the page. Does this matter?\n# Well, it really depends on our goal. In this case, I want to see if we can improve a bit on this.\n#\n# So we're going to go a bit off script here. While this week of lectures is about libraries, the\n# goal of this last course is to give you confidence that you can apply your knowledge to actual\n# programming tasks, even if the library you are using doesn't quite do what you want. \n#\n# I'd like to pause the video for the moment and collect your thoughts. Looking at the image above,\n# with the two column example and red boxes, how do you think we might modify this image to improve\n# kraken's ability to text lines?\n```\n\n\n```python\n# Thanks for sharing your thoughts, I'm looking forward to seeing the breadth of ideas that everyone\n# in the course comes up with. Here's my partial solution -- while looking through the kraken docs on \n# the pageseg() function I saw that there are a few parameters we can supply in order to improve \n# segmentation. One of these is the black_colseps parameter. If set to True, kraken will assume that \n# columns will be separated by black lines. This isn't our case here, but, I think we have all of the\n# tools to go through and actually change the source image to have a black separator between columns.\n#\n# The first step is that I want to update the show_boxes() function. I'm just going to do a quick\n# copy and paste from the above but add in the black_colseps=True parameter\ndef show_boxes(img):\n    '''Modifies the passed image to show a series of bounding boxes on an image as run by kraken\n    \n    :param img: A PIL.Image object\n    :return img: The modified PIL.Image object\n    '''\n    # Lets bring in our ImageDraw object\n    from PIL import ImageDraw\n    # And grab a drawing object to annotate that image\n    drawing_object=ImageDraw.Draw(img)\n    # We can create a set of boxes using pageseg.segment\n    bounding_boxes=pageseg.segment(img.convert('1'), black_colseps=True)['boxes']\n    # Now lets go through the list of bounding boxes\n    for box in bounding_boxes:\n        # An just draw a nice rectangle\n        drawing_object.rectangle(box, fill = None, outline ='red')\n    # And to make it easy, lets return the image object\n    return img\n```\n\n\n```python\n# The next step is to think of the algorithm we want to apply to detect a white column separator.\n# In experimenting a bit I decided that I only wanted to add the separator if the space of was\n# at least 25 pixels wide, which is roughly the width of a character, and six lines high. The\n# width is easy, lets just make a variable\nchar_width=25\n# The height is harder, since it depends on the height of the text. I'm going to write a routine\n# to calculate the average height of a line\ndef calculate_line_height(img):\n    '''Calculates the average height of a line from a given image\n    :param img: A PIL.Image object\n    :return: The average line height in pixels\n    '''\n    # Lets get a list of bounding boxes for this image\n    bounding_boxes=pageseg.segment(img.convert('1'))['boxes']\n    # Each box is a tuple of (top, left, bottom, right) so the height is just top - bottom\n    # So lets just calculate this over the set of all boxes\n    height_accumulator=0\n    for box in bounding_boxes:\n        height_accumulator=height_accumulator+box[3]-box[1]\n        # this is a bit tricky, remember that we start counting at the upper left corner in PIL!\n    # now lets just return the average height\n    # lets change it to the nearest full pixel by making it an integer\n    return int(height_accumulator/len(bounding_boxes))\n\n# And lets test this with the image with have been using\nline_height=calculate_line_height(Image.open(\"readonly/two_col.png\"))\nprint(line_height)\n```\n\n\n```python\n# Ok, so the average height of a line is 31.\n# Now, we want to scan through the image - looking at each pixel in turn - to determine if there\n# is a block of whitespace. How bit of a block should we look for? That's a bit more of an art\n# than a science. Looking at our sample image, I'm going to say an appropriate block should be\n# one char_width wide, and six line_heights tall. But, I honestly just made this up by eyeballing\n# the image, so I would encourage you to play with values as you explore.\n# Lets create a new box called gap box that represents this area\ngap_box=(0,0,char_width,line_height*6)\ngap_box\n```\n\n\n```python\n# It seems we will want to have a function which, given a pixel in an image, can check to see\n# if that pixel has whitespace to the right and below it. Essentially, we want to test to see\n# if the pixel is the upper left corner of something that looks like the gap_box. If so, then\n# we should insert a line to \"break up\" this box before sending to kraken\n#\n# Lets call this new function gap_check\ndef gap_check(img, location):\n    '''Checks the img in a given (x,y) location to see if it fits the description\n    of a gap_box\n    :param img: A PIL.Image file\n    :param location: A tuple (x,y) which is a pixel location in that image\n    :return: True if that fits the definition of a gap_box, otherwise False\n    '''\n    # Recall that we can get a pixel using the img.getpixel() function. It returns this value\n    # as a tuple of integers, one for each color channel. Our tools all work with binarized\n    # images (black and white), so we should just get one value. If the value is 0 it's a black\n    # pixel, if it's white then the value should be 255\n    #\n    # We're going to assume that the image is in the correct mode already, e.g. it has been\n    # binarized. The algorithm to check our bounding box is fairly easy: we have a single location \n    # which is our start and then we want to check all the pixels to the right of that location \n    # up to gap_box[2]\n    for x in range(location[0], location[0]+gap_box[2]):\n        # the height is similar, so lets iterate a y variable to gap_box[3]\n        for y in range(location[1], location[1]+gap_box[3]):\n            # we want to check if the pixel is white, but only if we are still within the image\n            if x < img.width and y < img.height:\n                # if the pixel is white we don't do anything, if it's black, we just want to\n                # finish and return False\n                if img.getpixel((x,y)) != 255:\n                    return False\n    # If we have managed to walk all through the gap_box without finding any non-white pixels\n    # then we can return true -- this is a gap!\n    return True\n```\n\n\n```python\n# Alright, we have a function to check for a gap, called gap_check. What should we do once\n# we find a gap? For this, lets just draw a line in the middle of it. Lets create a new function\ndef draw_sep(img,location):\n    '''Draws a line in img in the middle of the gap discovered at location. Note that\n    this doesn't draw the line in location, but draws it at the middle of a gap_box\n    starting at location.\n    :param img: A PIL.Image file\n    :param location: A tuple(x,y) which is a pixel location in the image\n    '''\n    # First lets bring in all of our drawing code\n    from PIL import ImageDraw\n    drawing_object=ImageDraw.Draw(img)\n    # next, lets decide what the middle means in terms of coordinates in the image\n    x1=location[0]+int(gap_box[2]/2)\n    # and our x2 is just the same thing, since this is a one pixel vertical line\n    x2=x1\n    # our starting y coordinate is just the y coordinate which was passed in, the top of the box\n    y1=location[1]\n    # but we want our final y coordinate to be the bottom of the box\n    y2=y1+gap_box[3]\n    drawing_object.rectangle((x1,y1,x2,y2), fill = 'black', outline ='black')\n    # and we don't have anything we need to return from this, because we modified the image\n```\n\n\n```python\n# Now, lets try it all out. This is pretty easy, we can just iterate through each pixel \n# in the image, check if there is a gap, then insert a line if there is.\ndef process_image(img):\n    '''Takes in an image of text and adds black vertical bars to break up columns\n    :param img: A PIL.Image file\n    :return: A modified PIL.Image file\n    '''\n    # we'll start with a familiar iteration process\n    for x in range(img.width):\n        for y in range(img.height):\n            # check if there is a gap at this point\n            if (gap_check(img, (x,y))):\n                # then update image to one which has a separator drawn on it\n                draw_sep(img, (x,y))\n    # and for good measure we'll return the image we modified\n    return img\n\n# Lets read in our test image and convert it through binarization\ni=Image.open(\"readonly/two_col.png\").convert(\"L\")\ni=process_image(i)\ndisplay(i)\n\n#Note: This will take some time to run! Be patient!\n```\n\n\n```python\n# Not bad at all! The effect at the bottom of the image is a bit unexpected to me, but it makes\n# sense. You can imagine that there are several ways we might try and control this. Lets see how \n# this new image works when run through the kraken layout engine\ndisplay(show_boxes(i))\n```\n\n\n```python\n# Looks like that is pretty accurate, and fixes the problem we faced. Feel free to experiment\n# with different settings for the gap heights and width and share in the forums. You'll notice though \n# method we created is really quite slow, which is a bit of a problem if we wanted to use\n# this on larger text. But I wanted to show you how you can mix your own logic and work with\n# libraries you're using. Just because Kraken didn't work perfectly, doesn't mean we can't\n# build something more specific to our use case on top of it.\n#\n# I want to end this lecture with a pause and to ask you to reflect on the code we've written\n# here. We started this course with some pretty simple use of libraries, but now we're\n# digging in deeper and solving problems ourselves with the help of these libraries. Before we\n# go on to our last library, how well prepared do you think you are to take your python\n# skills out into the wild?\n```\n\n## Comparing Image Data Structures\n\n\n```python\n# OpenCV supports reading of images in most file formats, such as JPEG, PNG, and TIFF. Most image and \n# video analysis requires converting images into grayscale first. This simplifies the image and reduces \n# noise allowing for improved analysis. Let's write some code that reads an image of as person, Floyd \n# Mayweather and converts it into greyscale.\n\n# First we will import the open cv package cv2 \nimport cv2 as cv\n# We'll load the floyd.jpg image \nimg = cv.imread('readonly/floyd.jpg')\n# And we'll convert it to grayscale using the cvtColor image\ngray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n\n# Now, before we get to the result, lets talk about docs. Just like tesseract, opencv is an external\n# package written in C++, and the docs for python are really poor. This is unfortunatly quite common\n# when python is being used as a wrapper. Thankfully, the web docs for opencv are actually pretty good,\n# so hit the website docs.opencv.org when you want to learn more about a particular function. In this\n# case cvtColor converts from one color space to another, and we are convering our image to grayscale.\n# Of course, we already know at least two different ways of doing this, using binarization and PIL\n# color spaces conversions\n\n# Lets instpec this object that has been returned.\nimport inspect\ninspect.getmro(type(gray))\n```\n\n\n```python\n# We see that it is of type ndarray, which is a fundamental list type coming from the numerical\n# python project. That's a bit surprising - up until this point we have been used to working with\n# PIL.Image objects. OpenCV, however, wants to represent an image as a two dimensional sequence \n# of bytes, and the ndarray, which stands for n dimensional array, is the ideal way to do this.\n# Lets look at the array contents.\ngray\n```\n\n\n```python\n# The array is shown here as a list of lists, where the inner lists are filled with integers.\n# The dtype=uint8 definition indicates that each of the items in an array is an 8 bit unsigned\n# integer, which is very common for black and white images. So this is a pixel by pixel definition\n# of the image.\n#\n# The display package, however, doesn't know what to do with this image. So lets convert it\n# into a PIL object to render it in the browser.\nfrom PIL import Image\n\n# PIL can take an array of data with a given color format and convert this into a PIL object.\n# This is perfect for our situation, as the PIL color mode, \"L\" is just an array of luminance\n# values in unsigned integers\nimage = Image.fromarray(gray, \"L\")\ndisplay(image)\n```\n\n\n```python\n# Lets talk a bit more about images for a moment. Numpy arrays are multidimensional. For \n# instance, we can define an array in a single dimension:\nimport numpy as np\nsingle_dim = np.array([25, 50 , 25, 10, 10])\n\n# In an image, this is analagous to a single row of 5 pixels each in grayscale. But actually,\n# all imaging libraries tend to expect at least two dimensions, a width and a height, and to\n# show a matrix. So if we put the single_dim inside of another array, this would be a two\n# dimensional array with element in the height direction, and five in the width direction\ndouble_dim = np.array([single_dim])\n\ndouble_dim\n```\n\n\n```python\n# This should look pretty familiar, it's a lot like a list of lists! Lets see what this new\n# two dimensional array looks like if we display it\ndisplay(Image.fromarray(double_dim, \"L\"))\n```\n\n\n```python\n# Pretty unexciting - it's just a little line. Five pixels in a row to be exact, of different\n# levels of black. The numpy library has a nice attribute called shape that allows us to see how\n# many dimensions big an array is. The shape attribute returns a tuple that shows the height of\n# the image, by the width of the image\ndouble_dim.shape\n```\n\n\n```python\n# Lets take a look at the shape of our initial image which we loaded into the img variable\nimg.shape\n```\n\n\n```python\n# This image has three dimensions! That's because it has a width, a height, and what's called\n# a color depth. In this case, the color is represented as an array of three values. Lets take a \n# look at the color of the first pixel\nfirst_pixel=img[0][0]\nfirst_pixel\n```\n\n\n```python\n# Here we see that the color value is provided in full RGB using an unsigned integer. This\n# means that each color can have one of 256 values, and the total number of unique colors\n# that can be represented by this data is 256 * 256 *256 which is roughly 16 million colors.\n# We call this 24 bit color, which is 8+8+8.\n#\n# If you find yourself shopping for a television, you might notice that some expensive models\n# are advertised as having 10 bit or even 12 bit panels. These are televisions where each of\n# the red, green, and blue color channels are represented by 10 or 12 bits instead of 8. For\n# ten bit panels this means that there are 1 billion colors capable, and 12 bit panels are\n# capable of over 68 billion colors!\n```\n\n\n```python\n# We're not going to talk much more about color in this course, but it's a fun subject. Instead,\n# lets go back to this array representation of images, because we can do some interesting things\n# with this.\n#\n# One of the most common things to do with an ndarray is to reshape it -- to change the number\n# of rows and columns that are represented so that we can do different kinds of operations.\n# Here is our original two dimensional image\nprint(\"Original image\")\nprint(gray)\n# If we wanted to represent that as a one dimensional image, we just call reshape\nprint(\"New image\")\n# And reshape takes the image as the first parameter, and a new shape as the second\nimage1d=np.reshape(gray,(1,gray.shape[0]*gray.shape[1]))\nprint(image1d)\n```\n\n\n```python\n# So, why are we talking about these nested arrays of bytes, we were supposed to be talking\n# about OpenCV as a library. Well, I wanted to show you that often libraries working on the\n# same kind of principles, in this case images stored as arrays of bytes, are not representing\n# data in the same way in their APIs. But, by exploring a bit you can learn how the internal\n# representation of data is stored, and build routines to convert between formats.\n#\n# For instance, remember in the last lecture when we wanted to look for gaps in an image so\n# that we could draw lines to feed into kraken? Well, we use PIL to do this, using getpixel()\n# to look at individual pixels and see what the luminosity was, then ImageDraw.rectangle to\n# actually fill in a black bar separator. This was a nice high level API, and let us write\n# routines to do the work we wanted without having to understand too much about how the images\n# were being stored. But it was computationally very slow.\n#\n# Instead, we could write the code to do this using matrix features within numpy. Lets take\n# a look.\nimport cv2 as cv\n# We'll load the 2 column image\nimg = cv.imread('readonly/two_col.png')\n# And we'll convert it to grayscale using the cvtColor image\ngray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n```\n\n\n```python\n# Now, remember how slicing on a list works, if you have a list of number such as \n# a=[0,1,2,3,4,5] then a[2:4] will return the sublist of numbers at position 2 through 4 \n# inclusive - don't forget that lists start indexing at 0!\n# If we have a two dimensional array, we can slice out a smaller piece of that using the\n# format a[2:4,1:3]. You can think of this as first slicing along the rows dimension, then\n# in the columns dimension. So in this example, that would be a matrix of rows 2, and 3,\n# and columns 1, and 2. Here's a look at our image.\ngray[2:4,1:3]\n```\n\n\n```python\n# So we see that it is all white. We can use this as a \"window\" and move it around our\n# our big image.\n#\n# Finally, the ndarray library has lots of matrix functions which are generally very fast\n# to run. One that we want to consider in this case is count_nonzero(), which just returns\n# the number of entries in the matrix which are not zero.\nnp.count_nonzero(gray[2:4,1:3])\n```\n\n\n```python\n# Ok, the last benefit of going to this low level approach to images is that we can change\n# pixels very fast as well. Previously we were drawing rectangles and setting a fill and line\n# width. This is nice if you want to do something like change the color of the fill from the\n# line, or draw complex shapes. But we really just want a line here. That's really easy to\n# do - we just want to change a number of luminosity values from 255 to 0.\n#\n# As an example, lets create a big white matrix\nwhite_matrix=np.full((12,12),255,dtype=np.uint8)\ndisplay(Image.fromarray(white_matrix,\"L\"))\nwhite_matrix\n```\n\n\n```python\n# looks pretty boring, it's just a giant white square we can't see. But if we want, we can\n# easily color a column to be black\nwhite_matrix[:,6]=np.full((1,12),0,dtype=np.uint8)\ndisplay(Image.fromarray(white_matrix,\"L\"))\nwhite_matrix\n```\n\n\n```python\n# And that's exactly what we wanted to do. So, why do it this way, when it seems so much\n# more low level? Really, the answer is speed. This paradigm of using matricies to store\n# and manipulate bytes of data for images is much closer to how low level API and hardware\n# developers think about storing files and bytes in memory.\n#\n# How much faster is it? Well, that's up to you to discover; there's an optional assignment\n# for this week to convert our old code over into this new format, to compare both the\n# readability and speed of the two different approaches.\n```\n\n## OpenCV\n\n\n```python\n# Ok, we're just about at the project for this course. If you reflect on the specialization \n# as a whole you'll realize that you started with probably little or no understanding of python,\n# progressed through the basic control structures and libraries included with the language\n# with the help of a digital textbook, moved on to more high level representations of data\n# and functions with objects, and now started to explore third party libraries that exist for\n# python which allow you to manipulate and display images. This is quite an achievement!\n#\n# You have also no doubt found that as you have progressed the demands on you to engage in self-\n# discovery have also increased. Where the first assignments were maybe straight forward, the\n# ones in this week require you to struggle a bit more with planning and debugging code as\n# you develop.\n#\n# But, you've persisted, and I'd like to share with you just one more set of features before\n# we head over to a project. The OpenCV library contains mechanisms to do face detection on\n# images. The technique used is based on Haar cascades, which is a machine learning approach.\n# Now, we're not going to go into the machine learning bits, we have another specialization on\n# Applied Data Science with Python which you can take after this if you're interested in that topic.\n# But here we'll treat OpenCV like a black box.\n#\n# OpenCV comes with trained models for detecting faces, eyes, and smiles which we'll be using.\n# You can train models for detecting other things - like hot dogs or flutes - and if you're\n# interested in that I'd recommend you check out the Open CV docs on how to train a cascade\n# classifier: https://docs.opencv.org/3.4/dc/d88/tutorial_traincascade.html\n# However, in this lecture we just want to use the current classifiers and see if we can detect\n# portions of an image which are interesting.\n#\n# First step is to load opencv and the XML-based classifiers\nimport cv2 as cv\nface_cascade = cv.CascadeClassifier('readonly/haarcascade_frontalface_default.xml')\neye_cascade = cv.CascadeClassifier('readonly/haarcascade_eye.xml')\n```\n\n\n```python\n# Ok, with the classifiers loaded, we now want to try and detect a face. Lets pull in the\n# picture we played with last time\nimg = cv.imread('readonly/floyd.jpg')\n# And we'll convert it to grayscale using the cvtColor image\ngray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n# The next step is to use the face_cascade classifier. I'll let you go explore the docs if you\n# would like to, but the norm is to use the detectMultiScale() function. This function returns\n# a list of objects as rectangles. The first parameter is an ndarray of the image.\nfaces = face_cascade.detectMultiScale(gray)\n# And lets just print those faces out to the screen\nfaces\n```\n\n\n```python\nfaces.tolist()[0]\n```\n\n\n```python\n# The resulting rectangles are in the format of (x,y,w,h) where x and y denote the upper\n# left hand point for the image and the width and height represent the bounding box. We know\n# how to handle this in PIL\nfrom PIL import Image\n\n# Lets create a PIL image object\npil_img=Image.fromarray(gray,mode=\"L\")\n\n# Now lets bring in our drawing object\nfrom PIL import ImageDraw\n# And lets create our drawing context\ndrawing=ImageDraw.Draw(pil_img)\n\n# Now lets pull the rectangle out of the faces object\nrec=faces.tolist()[0]\n\n# Now we just draw a rectangle around the bounds\ndrawing.rectangle(rec, outline=\"white\")\n\n# And display\ndisplay(pil_img)\n```\n\n\n```python\n# So, not quite what we were looking for. What do you think went wrong?\n# Well, a quick double check of the docs and it is apparent that OpenCV is return the coordinates\n# as (x,y,w,h), while PIL.ImageDraw is looking for (x1,y1,x2,y2). Looks like an easy fix\n# Wipe our old image\npil_img=Image.fromarray(gray,mode=\"L\")\n# Setup our drawing context\ndrawing=ImageDraw.Draw(pil_img)\n# And draw the new box\ndrawing.rectangle((rec[0],rec[1],rec[0]+rec[2],rec[1]+rec[3]), outline=\"white\")\n# And display\ndisplay(pil_img)\n```\n\n\n```python\n# We see the face detection works pretty good on this image! Note that it's apparent that this is\n# not head detection, but that the haarcascades file we used is looking for eyes and a mouth.\n# Lets try this on something a bit more complex, lets read in our MSI recruitment image\nimg = cv.imread('readonly/msi_recruitment.gif')\n# And lets take a look at that image\ndisplay(Image.fromarray(img))\n```\n\n\n```python\n# Whoa, what's that error about? It looks like there is an error on a line deep within the PIL\n# Image.py file, and it is trying to call an internal private member called __array_interface__\n# on the img object, but this object is None\n#\n# It turns out that the root of this error is that OpenCV can't work with Gif images. This is\n# kind of a pain and unfortunate. But we know how to fix that right? One was is that we could\n# just open this in PIL and then save it as a png, then open that in open cv.\n#\n# Lets use PIL to open our image\npil_img=Image.open('readonly/msi_recruitment.gif')\n# now lets convert it to greyscale for opencv, and get the bytestream\nopen_cv_version=pil_img.convert(\"L\")\n# now lets just write that to a file\nopen_cv_version.save(\"msi_recruitment.png\")\n```\n\n\n```python\n# Ok, now that the conversion of format is done, lets try reading this back into opencv\ncv_img=cv.imread('msi_recruitment.png')\n# We don't need to color convert this, because we saved it as grayscale\n# lets try and detect faces in that image\nfaces = face_cascade.detectMultiScale(cv_img)\n\n# Now, we still have our PIL color version in a gif\npil_img=Image.open('readonly/msi_recruitment.gif')\n# Set our drawing context\ndrawing=ImageDraw.Draw(pil_img)\n\n# For each item in faces, lets surround it with a red box\nfor x,y,w,h in faces:\n    # That might be new syntax for you! Recall that faces is a list of rectangles in (x,y,w,h)\n    # format, that is, a list of lists. Instead of having to do an iteration and then manually\n    # pull out each item, we can use tuple unpacking to pull out individual items in the sublist\n    # directly to variables. A really nice python feature\n    #\n    # Now we just need to draw our box\n    drawing.rectangle((x,y,x+w,y+h), outline=\"white\")\ndisplay(pil_img)\n```\n\n\n```python\n# What happened here!? We see that we have detected faces, and that we have drawn boxes\n# around those faces on the image, but that the colors have gone all weird! This, it turns\n# out, has to do with color limitations for gif images. In short, a gif image has a very\n# limited number of colors. This is called a color pallette after the pallette artists\n# use to mix paints. For gifs the pallette can only be 256 colors -- but they can be *any*\n# 256 colors. When a new color is introduced, is has to take the space of an old color.\n# In this case, PIL adds white to the pallette but doesn't know which color to replace and\n# thus messes up the image.\n#\n# Who knew there was so much to learn about image formats? We can see what mode the image\n# is in with the .mode attribute\npil_img.mode\n```\n\n\n```python\n# We can see a list of modes in the PILLOW documentation, and they correspond with the\n# color spaces we have been using. For the moment though, lets change back to RGB, which\n# represents color as a three byte tuple instead of in a pallette.\n# Lets read in the image\npil_img=Image.open('readonly/msi_recruitment.gif')\n# Lets convert it to RGB mode\npil_img = pil_img.convert(\"RGB\")\n# And lets print out the mode\npil_img.mode\n```\n\n\n```python\n# Ok, now lets go back to drawing rectangles. Lets get our drawing object\ndrawing=ImageDraw.Draw(pil_img)\n# And iterate through the faces sequence, tuple unpacking as we go\nfor x,y,w,h in faces:\n    # And remember this is width and height so we have to add those appropriately.\n    drawing.rectangle((x,y,x+w,y+h), outline=\"white\")\ndisplay(pil_img)\n```\n\n\n```python\n# Awesome! We managed to detect a bunch of faces in that image. Looks like we have missed \n# four faces. In the machine learning world we would call these false negatives - something\n# which the machine thought was not a face (so a negative), but that it was incorrect on.\n# Consequently, we would call the actual faces that were detected as true positives -\n# something that the machine thought was a face and it was correct on. This leaves us with\n# false positives - something the machine thought was a face but it wasn't. We see there are\n# two of these in the image, picking up shadow patterns or textures in shirts and matching\n# them with the haarcascades. Finally, we have true negatives, or the set of all possible\n# rectangles the machine learning classifier could consider where it correctly indicated that\n# the result was not a face. In this case there are many many true negatives.\n```\n\n\n```python\n# There are a few ways we could try and improve this, and really, it requires a lot of \n# experimentation to find good values for a given image. First, lets create a function\n# which will plot rectanges for us over the image\ndef show_rects(faces):\n    #Lets read in our gif and convert it\n    pil_img=Image.open('readonly/msi_recruitment.gif').convert(\"RGB\")\n    # Set our drawing context\n    drawing=ImageDraw.Draw(pil_img)\n    # And plot all of the rectangles in faces\n    for x,y,w,h in faces:\n        drawing.rectangle((x,y,x+w,y+h), outline=\"white\")\n    #Finally lets display this\n    display(pil_img)\n```\n\n\n```python\n# Ok, first up, we could try and binarize this image. It turns out that opencv has a built in\n# binarization function called threshold(). You simply pass in the image, the midpoint, and\n# the maximum value, as well as a flag which indicates whether the threshold should be\n# binary or something else. Lets try this.\ncv_img_bin=cv.threshold(img,120,255,cv.THRESH_BINARY)[1] # returns a list, we want the second value\n# Now do the actual face detection\nfaces = face_cascade.detectMultiScale(cv_img_bin)\n# Now lets see the results\nshow_rects(faces)\n```\n\n\n```python\n# That's kind of interesting. Not better, but we do see that there is one false positive\n# towards the bottom, where the classifier detected the sunglasses as eyes and the dark shadow\n# line below as a mouth.\n#\n# If you're following in the notebook with this video, why don't you pause things and try a\n# few different parameters for the thresholding value?\n```\n\n\n```python\n# The detectMultiScale() function from OpenCV also has a couple of parameters. The first of\n# these is the scale factor. The scale factor changes the size of rectangles which are\n# considered against the model, that is, the haarcascades XML file. You can think of it as if\n# it were changing the size of the rectangles which are on the screen.\n#\n# Lets experiment with the scale factor. Usually it's a small value, lets try 1.05\nfaces = face_cascade.detectMultiScale(cv_img,1.05)\n# Show those results\nshow_rects(faces)\n# Now lets also try 1.15\nfaces = face_cascade.detectMultiScale(cv_img,1.15)\n# Show those results\nshow_rects(faces)\n# Finally lets also try 1.25\nfaces = face_cascade.detectMultiScale(cv_img,1.25)\n# Show those results\nshow_rects(faces)\n```\n\n\n```python\n# We can see that as we change the scale factor we change the number of true and \n# false positives and negatives. With the scale set to 1.05, we have 7 true positives,\n# which are correctly identified faces, and 3 false negatives, which are faces which\n# are there but not detected, and 3 false positives, where are non-faces which\n# opencv thinks are faces. When we change this to 1.15 we lose the false positives but\n# also lose one of the true positives, the person to the right wearing a hat. And\n# when we change this to 1.25 we lost more true positives as well.\n#\n# This is actually a really interesting phenomena in machine learning and artificial\n# intelligence. There is a trade off between not only how accurate a model is, but how\n# the inaccuracy actually happens. Which of these three models do you think is best?\n```\n\n\n```python\n# Well, the answer to that question is really, \"it depends\". It depends why you are trying\n# to detect faces, and what you are going to do with them. If you think these issues\n# are interesting, you might want to check out the Applied Data Science with Python\n# specialization Michigan offers on Coursera.\n#\n# Ok, beyond an opportunity to advertise, did you notice anything else that happened when\n# we changed the scale factor? It's subtle, but the speed at which the processing ran\n# took longer at smaller scale factors. This is because more subimages are being considered\n# for these scales. This could also affect which method we might use.\n#\n# Jupyter has nice support for timing commands. You might have seen this before, a line\n# that starts with a percentage sign in jupyter is called a \"magic function\". This isn't\n# normal python - it's actually a shorthand way of writing a function which Jupyter\n# has predefined. It looks a lot like the decorators we talked about in a previous\n# lecture, but the magic functions were around long before decorators were part of the\n# python language. One of the built-in magic functions in juptyer is called timeit, and this\n# repeats a piece of python ten times (by default) and tells you the average speed it\n# took to complete.\n#\n# Lets time the speed of detectmultiscale when using a scale of 1.05\n%timeit face_cascade.detectMultiScale(cv_img,1.05)\n```\n\n\n```python\n# Ok, now lets compare that to the speed at scale = 1.15\n%timeit face_cascade.detectMultiScale(cv_img,1.15)\n```\n\n\n```python\n# You can see that this is a dramatic difference, roughly two and a half times slower\n# when using the smaller scale!\n#\n# This wraps up our discussion of detecting faces in opencv. You'll see that, like OCR, this\n# is not a foolproof process. But we can build on the work others have done in machine learning\n# and leverage powerful libraries to bring us closer to building a turn key python-based\n# solution. Remember that the detection mechanism isn't specific to faces, that's just the\n# haarcascades training data we used. On the web you'll be able to find other training data\n# to detect other objects, including eyes, animals, and so forth.\n```\n\n## More Jupyter Widgets\n\n\n```python\n# One of the nice things about using the Jupyter notebook systems is that there is a\n# rich set of contributed plugins that seek to extend this system. In this lecture I\n# want to introduce you to one such plugin, call ipy web rtc. Webrtc is a fairly new\n# protocol for real time communication on the web. Yup, I'm talking about chatting.\n# The widget brings this to the Jupyter notebook system. Lets take a look.\n#\n# First, lets import from this library two different classes which we'll use in a\n# demo, one for the camera and one for images.\nfrom ipywebrtc import CameraStream, ImageRecorder\n# Then lets take a look at the camera stream object\nhelp(CameraStream)\n```\n\n\n```python\n# We see from the docs that it's east to get a camera facing the user, and we can have\n# the audio on or off. We don't need audio for this demo, so lets create a new camera\n# instance\ncamera = CameraStream.facing_user(audio=False)\n# The next object we want to look at is the ImageRecorder\nhelp(ImageRecorder)\n```\n\n\n```python\n# The image recorder lets us actually grab images from the camera stream. There are features\n# for downloading and using the image as well. We see that the default format is a png file.\n# Lets hook up the ImageRecorder to our stream\nimage_recorder = ImageRecorder(stream=camera)\n# Now, the docs are a little unclear how to use this within Jupyter, but if we call the\n# download() function it will actually store the results of the camera which is hooked up\n# in image_recorder.image. Lets try it out\n# First, lets tell the recorder to start capturing data\nimage_recorder.recording=True\n# Now lets download the image\nimage_recorder.download()\n# Then lets inspect the type of the image\ntype(image_recorder.image)\n```\n\n\n```python\n# Ok, the object that it stores is an ipywidgets.widgets.widget_media.Image. How do we do\n# something useful with this? Well, an inspection of the object shows that there is a handy\n# value field which actually holds the bytes behind the image. And we know how to display\n# those.\n# Lets import PIL Image\nimport PIL.Image\n# And lets import io\nimport io\n# And now lets create a PIL image from the bytes\nimg = PIL.Image.open(io.BytesIO(image_recorder.image.value))\n# And render it to the screen\ndisplay(img)\n```\n\n\n```python\n# Great, you see a picture! Hopefully you are following along in one of the notebooks\n# and have been able to try this out for yourself!\n#\n# What can you do with this? This is a great way to get started with a bit of computer vision.\n# You already know how to identify a face in the webcam picture, or try and capture text\n# from within the picture. With OpenCV there are any number of other things you can do, simply\n# with a webcam, the Jupyter notebooks, and python!\n```\n", "meta": {"hexsha": "7a2b60db983fb31804d20f49e1788c08cf02b01f", "size": 67905, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Python Project pillow, tesseract, and openCV (University of Michigan)/The Python Imaging Library OpenCV module_3.ipynb", "max_stars_repo_name": "mohamedmosaed/Computer_vision_assiment", "max_stars_repo_head_hexsha": "7221ce4e290f1e69468ad6bc83c7d9bf453b9958", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python Project pillow, tesseract, and openCV (University of Michigan)/The Python Imaging Library OpenCV module_3.ipynb", "max_issues_repo_name": "mohamedmosaed/Computer_vision_assiment", "max_issues_repo_head_hexsha": "7221ce4e290f1e69468ad6bc83c7d9bf453b9958", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python Project pillow, tesseract, and openCV (University of Michigan)/The Python Imaging Library OpenCV module_3.ipynb", "max_forks_repo_name": "mohamedmosaed/Computer_vision_assiment", "max_forks_repo_head_hexsha": "7221ce4e290f1e69468ad6bc83c7d9bf453b9958", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.8501189532, "max_line_length": 1283, "alphanum_fraction": 0.6532214123, "converted": true, "num_tokens": 10355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1847675196261571, "lm_q2_score": 0.060086655223377576, "lm_q1q2_score": 0.011102062248255551}}
{"text": "# Passive ownership and flows\n## Why it matters\n\n- Passive management has seen unprecedented growth in the past 10-15 years<br><br>Source: Sushko, V., and G. Turner (2018) The implications of passive investing for securities markets, BIS Quarterly Review, March 2018, 113\u2013131.\n- Academics have found that institutional ownership in general tends to be positively associated with security return volatility (Sias, 1996)\n- Ben-David et al. (2018) find that this is particularly true for ETFs\n\n**The main mechanism:**\n- Liquidity shocks (i.e. inflows and outflows) that affect the fund propagate to the underlying securities, thereby increasing volatility\n- This mechanism is stronger in the case of passive funds because of the limited discretionality in the timing and direction of trades\n\n**Key results of our work:**\n- In our paper, <a href=\"https://marquee.gs.com/content/markets/en/2020/10/28/734dc59c-b03b-4793-9f56-98ec5ebca4d8.html\">\"The Shift from Active to Passive\" (July 2019)</a>, we find that passively held stocks tend to be more volatile after correcting for other stock characteristics\n- The effect of passive ownership on volatility is concentrated at the end of the continuous trading session and at the Close<br><br>Source: GS Global Markets Division.\n- The effect of passive inflows and outflows is similarly concentrated around the Close<br><br>Source: GS Global Markets Division.\n- This is arguably due to the concentration of portfolio trades in the order flow during that phase\n- We also detect differences in the impact of passive investing between US and European markets due to the different design of the closing auction\n\n**Passive ownership and the March 2020 selloff**\n- In our paper, <a href=\"https://marquee.gs.com/content/markets/en/2020/10/28/e251979b-cc31-49c6-bf8f-f585c6f22aa7.html\">\"Dissecting the Viral Selloff\" (April 2020)</a>, we group stocks by their level of passive ETF ownership and compare the percentage increase in volatility between January and March 2020<br><br>Source: GS Global Markets Division.\n\n- Stocks widely held by ETFs have experienced larger volatility increases, both in the US and in Europe\n- The result holds true after correcting for other effects, including sector, country, size and liquidity\n\n## Measuring passive ownership and flows\n- Starting from fund-level data, we produce stock-level indicators by using the latest information on holdings and flows\n- Raw ownership ratios:\n\\begin{equation}\nPassETFRatio_{i}=\\frac{\\sum_{j\\in F_{PassETF}}w_{ij}AuM_{j}}{MktCap_{i}}\n\\label{passETFratio}\n\\end{equation}\nwhere $w_{ij}$ is the weight of stock $i$ in fund $j$, $AuM_{j}$ is the total value of fund $j$'s holdings, $F_{PassETF}$ the set of passive ETFs and $MktCap_{i}$ is \nthe market capitalisation in US dollars of stock $i$\n- Building on our research, we carry out a series of cross-sectional normalisations and adjustments to make the scores comparable across regions and over time\n- Scores are normalised between -3 and 3. Higher scores indicate a higher level of passive ownership\n- Similarly, for flow scores a higher score indicates stronger inflows to passive funds holding the stock\n\n\n#### Import libraries\n\n\n```python\nimport pandas as pd\nfrom gs_quant.markets.securities import SecurityMaster, AssetIdentifier\nfrom gs_quant.session import GsSession\nfrom gs_quant.data import Dataset\nimport datetime as dt\nimport matplotlib.pyplot as plt\n```\n\n#### Supply credentials\n\n\n```python\n# external users should substitute their client id and secret; please skip this step if using internal jupyterhub\nGsSession.use(Environment.PROD, client_id=client_id, client_secret=client_secret, scopes=('read_product_data',))\n```\n\n## Load basket of stocks from text file\n\n\n```python\n# load data from csv\nptf_df = pd.read_csv('trade_list_world.csv')\nptf_df = ptf_df.rename(columns={'Symbol': 'SEDOL', 'Trade Value ($)': 'Value'})\nptf_df\n```\n\n## Map identifiers\n\n\n```python\n# load Marquee identifiers and Bloomberg Ids\nidentifiers_df = {}\nfor sedol_id in ptf_df.SEDOL:\n    identifiers_df[sedol_id] = {}\n    asset = SecurityMaster.get_asset(sedol_id, AssetIdentifier.SEDOL, sort_by_rank=True)\n    identifiers_df[sedol_id]['assetId'] = asset.get_marquee_id()\n    identifiers_df[sedol_id]['BCID'] = asset.get_identifiers(as_of=dt.date(2021, 6, 10))['BCID']\n\nidentifiers_df = pd.DataFrame.from_dict(identifiers_df, orient='index')\n```\n\n## Query Marquee datasets\n\n\n```python\n## Get monthly ownership data    \nds = Dataset('OWNERSHIP_SCORES_MONTHLY')\ndata_df = ds.get_data(start=dt.date(2021, 5, 9), end=dt.date(2021, 6, 10),\n                      assetId=identifiers_df.assetId.to_list())\n\n## Get weekly flow data    \nds2 = Dataset('OWNERSHIP_SCORES_WEEKLY_FLOW')\ndata2_df = ds2.get_data(start=dt.date(2021, 6, 3), end=dt.date(2021, 6, 10),\n                        assetId=identifiers_df.assetId.to_list())\n```\n\n\n```python\n## merge results in a summary table\nptf_df = ptf_df.merge(identifiers_df, right_index=True, left_on='SEDOL').merge(data_df, on='assetId')\nptf_df = ptf_df.merge(data2_df, on='assetId')\n```\n\n## Explore the data\n\n\n```python\n## display most passively held names\nratios_names = [x for x in ptf_df.columns if x.endswith('Ratio')]\nptf_df[['BCID']+ratios_names].sort_values(by='passiveRatio', ascending=False).head()\n```\n\n\n```python\n## display least passively held names\nptf_df[['BCID']+ratios_names].sort_values(by='passiveRatio', ascending=True).head()\n```\n\n\n```python\n## display most affected by passive inflows\nptf_df[['BCID']+ratios_names].sort_values(by='passiveFlowRatio', ascending=False).head()\n```\n\n\n```python\n## display most affected by passive outflows\nptf_df[['BCID']+ratios_names].sort_values(by='passiveFlowRatio', ascending=True).head()\n```\n\n## Compute impact of trade on portfolio-level ownership \n\n\n```python\n# plot breakdown by passive ETF ratio\nown_slices = [(-3, -2), (-2, -1), (-1, 0), (0, 1), (1, 2), (2, 3.1)]\nslice_labels = ['[-3,-2)', '[-2,-1)', '[-1,0)', '[0,1)', '[1,2)', '[2,3]']\n# scores are bounded between -3 and 3\n\n# compute total value sold and bought\ntot_traded_long = ptf_df.loc[ptf_df['Value']>0].sum()['Value']\ntot_traded_short = ptf_df.loc[ptf_df['Value']<0].sum()['Value']\n\n# compute values traded and plot bars\ntext_kwargs = dict(ha='center', va='center', fontsize=12, color='black')\nfig, ax = plt.subplots(2, 1, figsize=(8, 12))\ncnc = 0\nfor etf_var, var_label, chart_title in [('passiveEtfRatio', 'Passive ETF ratio', 'Breakdown by ETF ownership'),\n                                        ('etfFlowRatio', 'Passive ETF flow ratio', 'Breakdown by ETF flows')]:\n    slc = 0\n    for lb, ub in own_slices:\n        ax[cnc].barh(slc, ptf_df.loc[(ptf_df[etf_var]>=lb) & (ptf_df[etf_var]<ub) \n            & (ptf_df['Value']>0)].sum()['Value']/tot_traded_long, color='#939393')\n        ax[cnc].barh(slc, -ptf_df.loc[(ptf_df[etf_var]>=lb) & (ptf_df[etf_var]<ub) \n            & (ptf_df['Value']<0)].sum()['Value']/tot_traded_short, color='#7399c6')\n        slc += 1\n    ax[cnc].set_xlabel('Proportion of value traded')\n    ax[cnc].set_ylabel(var_label)\n    ax[cnc].set_yticks(range(6))\n    ax[cnc].set_yticklabels(slice_labels)\n    ax[cnc].set_title(chart_title)\n    cnc += 1\nplt.text(0.6, 5, 'Buys', **text_kwargs)\nplt.text(-0.25, 5, 'Sells', **text_kwargs)\nplt.text(0.6, 12.75, 'Buys', **text_kwargs)\nplt.text(-0.25, 12.75, 'Sells', **text_kwargs)\nplt.show()\n```\n\n\n```python\n# compute portfolio-level change\nptf_delta = {}\nfor si in ['passiveRatio', 'passiveEtfRatio']:\n    ptf_delta[si] = sum(ptf_df[si]*ptf_df['Value'])/1.0e+09 \nptf_delta\n```\n\n##### Disclaimers:\n###### Indicative Terms/Pricing Levels: This material may contain indicative terms only, including but not limited to pricing levels. There is no representation that any transaction can or could have been effected at such terms or prices. Proposed terms and conditions are for discussion purposes only. Finalized terms and conditions are subject to further discussion and negotiation.\n###### www.goldmansachs.com/disclaimer/sales-and-trading-invest-rec-disclosures.html If you are not accessing this material via Marquee ContentStream, a list of the author's investment recommendations disseminated during the preceding 12 months and the proportion of the author's recommendations that are 'buy', 'hold', 'sell' or other over the previous 12 months is available by logging into Marquee ContentStream using the link below. Alternatively, if you do not have access to Marquee ContentStream, please contact your usual GS representative who will be able to provide this information to you.\n###### Please refer to https://marquee.gs.com/studio/ for price information of corporate equity securities.\n###### Notice to Australian Investors: When this document is disseminated in Australia by Goldman Sachs & Co. LLC (\"GSCO\"), Goldman Sachs International (\"GSI\"), Goldman Sachs Bank Europe SE (\"GSBE\"), Goldman Sachs (Asia) L.L.C. (\"GSALLC\"), or Goldman Sachs (Singapore) Pte (\"GSSP\") (collectively the \"GS entities\"), this document, and any access to it, is intended only for a person that has first satisfied the GS entities that: \n###### \u2022 the person is a Sophisticated or Professional Investor for the purposes of section 708 of the Corporations Act of Australia; and \n###### \u2022 the person is a wholesale client for the purpose of section 761G of the Corporations Act of Australia. \n###### To the extent that the GS entities are providing a financial service in Australia, the GS entities are each exempt from the requirement to hold an Australian financial services licence for the financial services they provide in Australia. Each of the GS entities are regulated by a foreign regulator under foreign laws which differ from Australian laws, specifically: \n###### \u2022 GSCO is regulated by the US Securities and Exchange Commission under US laws;\n###### \u2022 GSI is authorised by the Prudential Regulation Authority and regulated by the Financial Conduct Authority and the Prudential Regulation Authority, under UK laws;\n###### \u2022 GSBE is subject to direct prudential supervision by the European Central Bank and in other respects is supervised by the German Federal Financial Supervisory Authority (Bundesanstalt f\u00fcr Finanzdienstleistungsaufischt, BaFin) and Deutsche Bundesbank;\n###### \u2022 GSALLC is regulated by the Hong Kong Securities and Futures Commission under Hong Kong laws; and\n###### \u2022 GSSP is regulated by the Monetary Authority of Singapore under Singapore laws.\n###### Notice to Brazilian Investors\n###### Marquee is not meant for the general public in Brazil. The services or products provided by or through Marquee, at any time, may not be offered or sold to the general public in Brazil. You have received a password granting access to Marquee exclusively due to your existing relationship with a GS business located in Brazil. The selection and engagement with any of the offered services or products through Marquee, at any time, will be carried out directly by you. Before acting to implement any chosen service or products, provided by or through Marquee you should consider, at your sole discretion, whether it is suitable for your particular circumstances and, if necessary, seek professional advice. Any steps necessary in order to implement the chosen service or product, including but not limited to remittance of funds, shall be carried out at your discretion. Accordingly, such services and products have not been and will not be publicly issued, placed, distributed, offered or negotiated in the Brazilian capital markets and, as a result, they have not been and will not be registered with the Brazilian Securities and Exchange Commission (Comiss\u00e3o de Valores Mobili\u00e1rios), nor have they been submitted to the foregoing agency for approval. Documents relating to such services or products, as well as the information contained therein, may not be supplied to the general public in Brazil, as the offering of such services or products is not a public offering in Brazil, nor used in connection with any offer for subscription or sale of securities to the general public in Brazil.\n###### The offer of any securities mentioned in this message may not be made to the general public in Brazil. Accordingly, any such securities have not been nor will they be registered with the Brazilian Securities and Exchange Commission (Comiss\u00e3o de Valores Mobili\u00e1rios) nor has any offer been submitted to the foregoing agency for approval. Documents relating to the offer, as well as the information contained therein, may not be supplied to the public in Brazil, as the offer is not a public offering of securities in Brazil. These terms will apply on every access to Marquee.\n###### Ouvidoria Goldman Sachs Brasil: 0800 727 5764 e/ou ouvidoriagoldmansachs@gs.com\n###### Hor\u00e1rio de funcionamento: segunda-feira \u00e0 sexta-feira (exceto feriados), das 9hs \u00e0s 18hs.\n###### Ombudsman Goldman Sachs Brazil: 0800 727 5764 and / or ouvidoriagoldmansachs@gs.com\n###### Available Weekdays (except holidays), from 9 am to 6 pm.\n \n###### Note to Investors in Israel: GS is not licensed to provide investment advice or investment management services under Israeli law.\n###### Notice to Investors in Japan\n###### Marquee is made available in Japan by Goldman Sachs Japan Co., Ltd.\n\n###### \u672c\u66f8\u306f\u60c5\u5831\u306e\u63d0\u4f9b\u3092\u76ee\u7684\u3068\u3057\u3066\u304a\u308a\u307e\u3059\u3002\u307e\u305f\u3001\u58f2\u5374\u30fb\u8cfc\u5165\u304c\u9055\u6cd5\u3068\u306a\u308b\u3088\u3046\u306a\u6cd5\u57df\u3067\u306e\u6709\u4fa1\u8a3c\u5238\u305d\u306e\u4ed6\u306e\u58f2\u5374\u82e5\u3057\u304f\u306f\u8cfc\u5165\u3092\u52e7\u3081\u308b\u3082\u306e\u3067\u3082\u3042\u308a\u307e\u305b\u3093\u3002\u30b4\u30fc\u30eb\u30c9\u30de\u30f3\u30fb\u30b5\u30c3\u30af\u30b9\u306f\u672c\u66f8\u5185\u306e\u53d6\u5f15\u53c8\u306f\u30b9\u30c8\u30e9\u30af\u30c1\u30e3\u30fc\u306e\u52e7\u8a98\u3092\u884c\u3046\u3082\u306e\u3067\u306f\u3054\u3056\u3044\u307e\u305b\u3093\u3002\u3053\u308c\u3089\u306e\u53d6\u5f15\u53c8\u306f\u30b9\u30c8\u30e9\u30af\u30c1\u30e3\u30fc\u306f\u3001\u793e\u5185\u53ca\u3073\u6cd5\u898f\u5236\u7b49\u306e\u627f\u8a8d\u7b49\u6b21\u7b2c\u3067\u5b9f\u969b\u306b\u306f\u3054\u63d0\u4f9b\u3067\u304d\u306a\u3044\u5834\u5408\u304c\u3054\u3056\u3044\u307e\u3059\u3002\n\n###### <\u9069\u683c\u6a5f\u95a2\u6295\u8cc7\u5bb6\u9650\u5b9a\u3000\u8ee2\u58f2\u5236\u9650>\n###### \u30b4\u30fc\u30eb\u30c9\u30de\u30f3\u30fb\u30b5\u30c3\u30af\u30b9\u8a3c\u5238\u682a\u5f0f\u4f1a\u793e\u304c\u9069\u683c\u6a5f\u95a2\u6295\u8cc7\u5bb6\u306e\u307f\u3092\u76f8\u624b\u65b9\u3068\u3057\u3066\u53d6\u5f97\u7533\u8fbc\u307f\u306e\u52e7\u8a98\uff08\u53d6\u5f97\u52e7\u8a98\uff09\u53c8\u306f\u58f2\u4ed8\u3051\u306e\u7533\u8fbc\u307f\u82e5\u3057\u304f\u306f\u8cb7\u4ed8\u3051\u306e\u7533\u8fbc\u307f\u306e\u52e7\u8a98(\u58f2\u4ed8\u3051\u52e7\u8a98\u7b49)\u3092\u884c\u3046\u672c\u6709\u4fa1\u8a3c\u5238\u306b\u306f\u3001\u9069\u683c\u6a5f\u95a2\u6295\u8cc7\u5bb6\u306b\u8b72\u6e21\u3059\u308b\u5834\u5408\u4ee5\u5916\u306e\u8b72\u6e21\u304c\u7981\u6b62\u3055\u308c\u308b\u65e8\u306e\u5236\u9650\u304c\u4ed8\u3055\u308c\u3066\u3044\u307e\u3059\u3002\u672c\u6709\u4fa1\u8a3c\u5238\u306f\u91d1\u878d\u5546\u54c1\u53d6\u5f15\u6cd5\u7b2c\uff14\u6761\u306b\u57fa\u3065\u304f\u8ca1\u52d9\u5c40\u306b\u5bfe\u3059\u308b\u5c4a\u51fa\u304c\u884c\u308f\u308c\u3066\u304a\u308a\u307e\u305b\u3093\u3002\u306a\u304a\u3001\u672c\u544a\u77e5\u306f\u304a\u5ba2\u69d8\u306b\u3088\u308b\u3054\u540c\u610f\u306e\u3082\u3068\u306b\u3001\u96fb\u78c1\u7684\u306b\u4ea4\u4ed8\u3055\u305b\u3066\u3044\u305f\u3060\u3044\u3066\u304a\u308a\u307e\u3059\u3002\n###### \uff1c\u9069\u683c\u6a5f\u95a2\u6295\u8cc7\u5bb6\u7528\u8cc7\u6599\uff1e \n###### \u672c\u8cc7\u6599\u306f\u3001\u9069\u683c\u6a5f\u95a2\u6295\u8cc7\u5bb6\u306e\u304a\u5ba2\u3055\u307e\u306e\u307f\u3092\u5bfe\u8c61\u306b\u4f5c\u6210\u3055\u308c\u305f\u3082\u306e\u3067\u3059\u3002\u672c\u8cc7\u6599\u306b\u304a\u3051\u308b\u91d1\u878d\u5546\u54c1\u306f\u9069\u683c\u6a5f\u95a2\u6295\u8cc7\u5bb6\u306e\u304a\u5ba2\u3055\u307e\u306e\u307f\u304c\u304a\u53d6\u5f15\u53ef\u80fd\u3067\u3042\u308a\u3001\u9069\u683c\u6a5f\u95a2\u6295\u8cc7\u5bb6\u4ee5\u5916\u306e\u304a\u5ba2\u3055\u307e\u304b\u3089\u306e\u3054\u6ce8\u6587\u7b49\u306f\u304a\u53d7\u3051\u3067\u304d\u307e\u305b\u3093\u306e\u3067\u3001\u3054\u6ce8\u610f\u304f\u3060\u3055\u3044\u3002 \u5546\u53f7\u7b49/\u30b4\u30fc\u30eb\u30c9\u30de\u30f3\u30fb\u30b5\u30c3\u30af\u30b9\u8a3c\u5238\u682a\u5f0f\u4f1a\u793e \u91d1\u878d\u5546\u54c1\u53d6\u5f15\u696d\u8005\u3000\u95a2\u6771\u8ca1\u52d9\u5c40\u9577\uff08\u91d1\u5546\uff09\u7b2c\uff16\uff19\u53f7 \n###### \u52a0\u5165\u5354\u4f1a/\u3000\u65e5\u672c\u8a3c\u5238\u696d\u5354\u4f1a\u3001\u4e00\u822c\u793e\u56e3\u6cd5\u4eba\u91d1\u878d\u5148\u7269\u53d6\u5f15\u696d\u5354\u4f1a\u3001\u4e00\u822c\u793e\u56e3\u6cd5\u4eba\u7b2c\u4e8c\u7a2e\u91d1\u878d\u5546\u54c1\u53d6\u5f15\u696d\u5354\u4f1a \n###### \u672c\u66f8\u53c8\u306f\u305d\u306e\u6dfb\u4ed8\u8cc7\u6599\u306b\u4fe1\u7528\u683c\u4ed8\u304c\u8a18\u8f09\u3055\u308c\u3066\u3044\u308b\u5834\u5408\u3001\u65e5\u672c\u683c\u4ed8\u7814\u7a76\u6240\uff08JCR\uff09\u53ca\u3073\u683c\u4ed8\u6295\u8cc7\u60c5\u5831\u30bb\u30f3\u30bf\u30fc\uff08R&I\uff09\u306b\u3088\u308b\u683c\u4ed8\u306f\u3001\u767b\u9332\u4fe1\u7528\u683c\u4ed8\u696d\u8005\u306b\u3088\u308b\u683c\u4ed8\uff08\u767b\u9332\u683c\u4ed8\uff09\u3067\u3059\u3002\u305d\u306e\u4ed6\u306e\u683c\u4ed8\u306f\u767b\u9332\u683c\u4ed8\u3067\u3042\u308b\u65e8\u306e\u8a18\u8f09\u304c\u306a\u3044\u5834\u5408\u306f\u3001\u7121\u767b\u9332\u683c\u4ed8\u3067\u3059\u3002\u7121\u767b\u9332\u683c\u4ed8\u3092\u6295\u8cc7\u5224\u65ad\u306b\u5229\u7528\u3059\u308b\u524d\u306b\u3001\u300c\u7121\u767b\u9332\u683c\u4ed8\u306b\u95a2\u3059\u308b\u8aac\u660e\u66f8\u300d\uff08http://www.goldmansachs.com/disclaimer/ratings.html\uff09\u3092\u5341\u5206\u306b\u304a\u8aad\u307f\u304f\u3060\u3055\u3044\u3002 \n###### If any credit ratings are contained in this material or any attachments, those that have been issued by Japan Credit Rating Agency, Ltd. (JCR) or Rating and Investment Information, Inc. (R&I) are credit ratings that have been issued by a credit rating agency registered in Japan (registered credit ratings). Other credit ratings are unregistered unless denoted as being registered. Before using unregistered credit ratings to make investment decisions, please carefully read \"Explanation Regarding Unregistered Credit Ratings\" (http://www.goldmansachs.com/disclaimer/ratings.html).\n###### Notice to Mexican Investors: Information contained herein is not meant for the general public in Mexico. The services or products provided by or through Goldman Sachs Mexico, Casa de Bolsa, S.A. de C.V. (GS Mexico) may not be offered or sold to the general public in Mexico. You have received information herein exclusively due to your existing relationship with a GS Mexico or any other Goldman Sachs business. The selection and engagement with any of the offered services or products through GS Mexico will be carried out directly by you at your own risk. Before acting to implement any chosen service or product provided by or through GS Mexico you should consider, at your sole discretion, whether it is suitable for your particular circumstances and, if necessary, seek professional advice. Information contained herein related to GS Mexico services or products, as well as any other information, shall not be considered as a product coming from research, nor it contains any recommendation to invest, not to invest, hold or sell any security and may not be supplied to the general public in Mexico.\n###### Notice to New Zealand Investors: When this document is disseminated in New Zealand by Goldman Sachs & Co. LLC (\"GSCO\") , Goldman Sachs International (\"GSI\"), Goldman Sachs Bank Europe SE (\"GSBE\"), Goldman Sachs (Asia) L.L.C. (\"GSALLC\") or Goldman Sachs (Singapore) Pte (\"GSSP\") (collectively the \"GS entities\"), this document, and any access to it, is intended only for a person that has first satisfied; the GS entities that the person is someone: \n###### (i) who is an investment business within the meaning of clause 37 of Schedule 1 of the Financial Markets Conduct Act 2013 (New Zealand) (the \"FMC Act\");\n###### (ii) who meets the investment activity criteria specified in clause 38 of Schedule 1 of the FMC Act;\n###### (iii) who is large within the meaning of clause 39 of Schedule 1 of the FMC Act; or\n###### (iv) is a government agency within the meaning of clause 40 of Schedule 1 of the FMC Act. \n###### No offer to acquire the interests is being made to you in this document. Any offer will only be made in circumstances where disclosure is not required under the Financial Markets Conducts Act 2013 or the Financial Markets Conduct Regulations 2014.\n###### Notice to Swiss Investors: This is marketing material for financial instruments or services. The information contained in this material is for general informational purposes only and does not constitute an offer, solicitation, invitation or recommendation to buy or sell any financial instruments or to provide any investment advice or service of any kind.\n###### THE INFORMATION CONTAINED IN THIS DOCUMENT DOES NOT CONSITUTE, AND IS NOT INTENDED TO CONSTITUTE, A PUBLIC OFFER OF SECURITIES IN THE UNITED ARAB EMIRATES IN ACCORDANCE WITH THE COMMERCIAL COMPANIES LAW (FEDERAL LAW NO. 2 OF 2015), ESCA BOARD OF DIRECTORS' DECISION NO. (9/R.M.) OF 2016, ESCA CHAIRMAN DECISION NO 3/R.M. OF 2017 CONCERNING PROMOTING AND INTRODUCING REGULATIONS OR OTHERWISE UNDER THE LAWS OF THE UNITED ARAB EMIRATES. ACCORDINGLY, THE INTERESTS IN THE SECURITIES MAY NOT BE OFFERED TO THE PUBLIC IN THE UAE (INCLUDING THE DUBAI INTERNATIONAL FINANCIAL CENTRE AND THE ABU DHABI GLOBAL MARKET). THIS DOCUMENT HAS NOT BEEN APPROVED BY, OR FILED WITH THE CENTRAL BANK OF THE UNITED ARAB EMIRATES, THE SECURITIES AND COMMODITIES AUTHORITY, THE DUBAI FINANCIAL SERVICES AUTHORITY, THE FINANCIAL SERVICES REGULATORY AUTHORITY OR ANY OTHER RELEVANT LICENSING AUTHORITIES IN THE UNITED ARAB EMIRATES. IF YOU DO NOT UNDERSTAND THE CONTENTS OF THIS DOCUMENT, YOU SHOULD CONSULT WITH A FINANCIAL ADVISOR. THIS DOCUMENT IS PROVIDED TO THE RECIPIENT ONLY AND SHOULD NOT BE PROVIDED TO OR RELIED ON BY ANY OTHER PERSON.\n", "meta": {"hexsha": "a8cd3b1289877aa1ef3a8b5370daa9779fbfb347", "size": 22497, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "gs_quant/content/events/00_gsquant_meets_markets/02_optimizing_equity_trading/section_b_ownership.ipynb", "max_stars_repo_name": "skyquant2/gs-quant", "max_stars_repo_head_hexsha": "b7e648fa7912b13ad1fd503b643389e34587aa1e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-05-11T14:35:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T03:52:34.000Z", "max_issues_repo_path": "gs_quant/content/events/00_gsquant_meets_markets/02_optimizing_equity_trading/section_b_ownership.ipynb", "max_issues_repo_name": "skyquant2/gs-quant", "max_issues_repo_head_hexsha": "b7e648fa7912b13ad1fd503b643389e34587aa1e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gs_quant/content/events/00_gsquant_meets_markets/02_optimizing_equity_trading/section_b_ownership.ipynb", "max_forks_repo_name": "skyquant2/gs-quant", "max_forks_repo_head_hexsha": "b7e648fa7912b13ad1fd503b643389e34587aa1e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 65.7807017544, "max_line_length": 1605, "alphanum_fraction": 0.6924923323, "converted": true, "num_tokens": 5121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2509127868852725, "lm_q2_score": 0.044018650019710344, "lm_q1q2_score": 0.01104484215137298}}
{"text": "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Pooling-coefficients-measured-in-saline\" data-toc-modified-id=\"Pooling-coefficients-measured-in-saline-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Pooling coefficients measured in saline</a></span><ul class=\"toc-item\"><li><span><a href=\"#Measure-the-amplitude-of-the-sine-signal-on-each-site-under-different-conditions\" data-toc-modified-id=\"Measure-the-amplitude-of-the-sine-signal-on-each-site-under-different-conditions-1.1\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;</span>Measure the amplitude of the sine signal on each site under different conditions</a></span></li><li><span><a href=\"#Compute-the-pooling-coefficients\" data-toc-modified-id=\"Compute-the-pooling-coefficients-1.2\"><span class=\"toc-item-num\">1.2&nbsp;&nbsp;</span>Compute the pooling coefficients</a></span></li><li><span><a href=\"#Identify-sites-with-defective-switches\" data-toc-modified-id=\"Identify-sites-with-defective-switches-1.3\"><span class=\"toc-item-num\">1.3&nbsp;&nbsp;</span>Identify sites with defective switches</a></span></li><li><span><a href=\"#Plot-the-pooling-coefficients-at-the-good-sites\" data-toc-modified-id=\"Plot-the-pooling-coefficients-at-the-good-sites-1.4\"><span class=\"toc-item-num\">1.4&nbsp;&nbsp;</span>Plot the pooling coefficients at the good sites</a></span></li></ul></li><li><span><a href=\"#Electrical-characteristics-measured-in-saline\" data-toc-modified-id=\"Electrical-characteristics-measured-in-saline-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Electrical characteristics measured in saline</a></span><ul class=\"toc-item\"><li><span><a href=\"#Load-raw-Neuropixel-recordings-and-compute-power-spectra\" data-toc-modified-id=\"Load-raw-Neuropixel-recordings-and-compute-power-spectra-2.1\"><span class=\"toc-item-num\">2.1&nbsp;&nbsp;</span>Load raw Neuropixel recordings and compute power spectra</a></span></li><li><span><a href=\"#Fit-a-4-parameter-circuit-model-to-the-noise-spectra\" data-toc-modified-id=\"Fit-a-4-parameter-circuit-model-to-the-noise-spectra-2.2\"><span class=\"toc-item-num\">2.2&nbsp;&nbsp;</span>Fit a 4-parameter circuit model to the noise spectra</a></span></li><li><span><a href=\"#Examples-of-noise-measurements-and-fits-from-the-circuit-model\" data-toc-modified-id=\"Examples-of-noise-measurements-and-fits-from-the-circuit-model-2.3\"><span class=\"toc-item-num\">2.3&nbsp;&nbsp;</span>Examples of noise measurements and fits from the circuit model</a></span><ul class=\"toc-item\"><li><span><a href=\"#Figure-8C-left\" data-toc-modified-id=\"Figure-8C-left-2.3.1\"><span class=\"toc-item-num\">2.3.1&nbsp;&nbsp;</span>Figure 8C left</a></span></li><li><span><a href=\"#Figure-8C-right\" data-toc-modified-id=\"Figure-8C-right-2.3.2\"><span class=\"toc-item-num\">2.3.2&nbsp;&nbsp;</span>Figure 8C right</a></span></li></ul></li><li><span><a href=\"#Noise-in-the-highest-saline,-bank-1-vs-bank-2\" data-toc-modified-id=\"Noise-in-the-highest-saline,-bank-1-vs-bank-2-2.4\"><span class=\"toc-item-num\">2.4&nbsp;&nbsp;</span>Noise in the highest saline, bank 1 vs bank 2</a></span><ul class=\"toc-item\"><li><span><a href=\"#Figure-8D\" data-toc-modified-id=\"Figure-8D-2.4.1\"><span class=\"toc-item-num\">2.4.1&nbsp;&nbsp;</span>Figure 8D</a></span></li></ul></li><li><span><a href=\"#Histograms-of-the-parameters-in-the-circuit-model\" data-toc-modified-id=\"Histograms-of-the-parameters-in-the-circuit-model-2.5\"><span class=\"toc-item-num\">2.5&nbsp;&nbsp;</span>Histograms of the parameters in the circuit model</a></span><ul class=\"toc-item\"><li><span><a href=\"#Figure-8E\" data-toc-modified-id=\"Figure-8E-2.5.1\"><span class=\"toc-item-num\">2.5.1&nbsp;&nbsp;</span>Figure 8E</a></span></li><li><span><a href=\"#Figure-4C\" data-toc-modified-id=\"Figure-4C-2.5.2\"><span class=\"toc-item-num\">2.5.2&nbsp;&nbsp;</span>Figure 4C</a></span></li></ul></li></ul></li><li><span><a href=\"#Revision\" data-toc-modified-id=\"Revision-3\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>Revision</a></span><ul class=\"toc-item\"><li><span><a href=\"#Thermal-noise\" data-toc-modified-id=\"Thermal-noise-3.1\"><span class=\"toc-item-num\">3.1&nbsp;&nbsp;</span>Thermal noise</a></span><ul class=\"toc-item\"><li><span><a href=\"#Figure-4B\" data-toc-modified-id=\"Figure-4B-3.1.1\"><span class=\"toc-item-num\">3.1.1&nbsp;&nbsp;</span>Figure 4B</a></span></li></ul></li><li><span><a href=\"#Pooling-coefficients\" data-toc-modified-id=\"Pooling-coefficients-3.2\"><span class=\"toc-item-num\">3.2&nbsp;&nbsp;</span>Pooling coefficients</a></span><ul class=\"toc-item\"><li><span><a href=\"#In-vitro\" data-toc-modified-id=\"In-vitro-3.2.1\"><span class=\"toc-item-num\">3.2.1&nbsp;&nbsp;</span>In vitro</a></span><ul class=\"toc-item\"><li><span><a href=\"#Figure-4A\" data-toc-modified-id=\"Figure-4A-3.2.1.1\"><span class=\"toc-item-num\">3.2.1.1&nbsp;&nbsp;</span>Figure 4A</a></span></li></ul></li><li><span><a href=\"#In-vivo\" data-toc-modified-id=\"In-vivo-3.2.2\"><span class=\"toc-item-num\">3.2.2&nbsp;&nbsp;</span>In vivo</a></span><ul class=\"toc-item\"><li><span><a href=\"#Figure-4E\" data-toc-modified-id=\"Figure-4E-3.2.2.1\"><span class=\"toc-item-num\">3.2.2.1&nbsp;&nbsp;</span>Figure 4E</a></span></li></ul></li></ul></li><li><span><a href=\"#Biological-noise\" data-toc-modified-id=\"Biological-noise-3.3\"><span class=\"toc-item-num\">3.3&nbsp;&nbsp;</span>Biological noise</a></span><ul class=\"toc-item\"><li><span><a href=\"#In-the-two-split-conditions\" data-toc-modified-id=\"In-the-two-split-conditions-3.3.1\"><span class=\"toc-item-num\">3.3.1&nbsp;&nbsp;</span>In the two split conditions</a></span><ul class=\"toc-item\"><li><span><a href=\"#Figure-4D\" data-toc-modified-id=\"Figure-4D-3.3.1.1\"><span class=\"toc-item-num\">3.3.1.1&nbsp;&nbsp;</span>Figure 4D</a></span></li></ul></li><li><span><a href=\"#Pooled,-predicted-from-independence-vs-measured\" data-toc-modified-id=\"Pooled,-predicted-from-independence-vs-measured-3.3.2\"><span class=\"toc-item-num\">3.3.2&nbsp;&nbsp;</span>Pooled, predicted from independence vs measured</a></span><ul class=\"toc-item\"><li><span><a href=\"#Figure-4F\" data-toc-modified-id=\"Figure-4F-3.3.2.1\"><span class=\"toc-item-num\">3.3.2.1&nbsp;&nbsp;</span>Figure 4F</a></span></li></ul></li></ul></li></ul></li></ul></div>\n\n\n```python\n# Imports\nfrom __future__ import division\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pickle\nfrom scipy.optimize import minimize\nimport sys\n\nmodule_path = 'code/' \nif module_path not in sys.path:\n    sys.path.append(module_path)\nfrom MM_Plot_Utils import plot, hist\n\n%matplotlib inline\n%reload_ext autoreload\n%autoreload 2\n```\n\n# Pooling coefficients measured in saline\n\n## Measure the amplitude of the sine signal on each site under different conditions\n- Neuropixels probe 2 or 3\n- Frequency 400 Hz or 1000 Hz\n- Gradient from bottom or top\n- switch settings: split 0, split 1, pooled 01\n\nThis code is provided for reference only. The raw data are not included because too voluminous. The routine simply measures the Fourier amplitude of the signal at the frequency of stimulation and saves that to file. The output files for probe 2 are included with this repo.\n\n\n```python\n# # Compute peak amplitude of fourier transform for all sites from raw data\n# # Load data directly from the external drive\n# def getFourierAmplitude(probe,freq,grad,bank,dur=5):\n#     '''\n#     probe in ['2','3']\n#     freq in ['400','1000']\n#     grad in ['bot','top']\n#     bank in ['0','1','01']\n#     dur = duration in seconds\n#     '''\n#     file=getFileName(probe,freq,grad,bank)\n#     binFullPath=Path(file)\n#     meta=readMeta(binFullPath) # get metadata\n#     rawData = makeMemMapRaw(binFullPath, meta)\n#     sRate=SampRate(meta) # get sampling rate (in Hz)\n\n#     tStart=10        # in seconds\n#     tEnd=tStart+dur\n#     m=int(freq)*(tEnd-tStart) # location of the frequency of stimulation in the fourier transform\n\n#     fa=np.zeros(384)\n#     for i in range(384):\n#         chanList = [i] # channels to load\n#         selectData = rawData[chanList,int(tStart*sRate):int(tEnd*sRate)]\n#         if meta['typeThis'] == 'imec':\n#             convData = 1e3*GainCorrectIM(selectData, chanList, meta) # apply gain correction and convert to mV\n#         x=convData[0]\n#         fa[i]=np.abs(np.fft.rfft(x))[m]\n#     with open('Probe'+probe+'/FA_p'+probe+'_f'+freq+'_g'+grad+'_b'+bank, \"wb\") as f: \n#         pickle.dump(fa,f)\n#     return fa\n```\n\n\n```python\n# # Analyze and save all fourier amplitudes\n# for probe in ['2','3']:\n#     for freq in ['400','1000']:\n#         for grad in ['bot','top']:\n#             for bank in ['0','1','01']:\n#                 getFourierAmplitude(probe,freq,grad,bank,dur=5)\n```\n\n## Compute the pooling coefficients\n\n\nWe applied an oscillating electric field (1000 Hz) along the electrode array with a pair of annular electrodes (Figure 4A). From the recorded waveform we estimated the signal amplitude by the Fourier coefficient at the stimulus frequency. Two different field gradients (called A and B) yielded two sets of measurements, each in the two split modes ($U_{0,\\rm{A}},U_{1,\\rm{A}},U_{0,\\rm{B}},U_{1,\\rm{B}}$) and the pooled mode ($U_{\\rm{P},\\rm{A}},U_{\\rm{P},\\rm{B}}$). For each of the 383 wires we estimated the pooling coefficients of its two electrodes by solving\n\n\\begin{align*}\\label{eq:saline_pc}\n    \\begin{bmatrix}\n        U_{0,\\textrm{A}} & U_{1,\\textrm{A}}\\\\\n        U_{0,\\textrm{B}} & U_{1,\\textrm{B}}\n    \\end{bmatrix}\n    \\begin{bmatrix}\n        k_0\\\\\n        k_1\n    \\end{bmatrix}\n    = \n    \\begin{bmatrix}\n        U_{\\textrm{P},\\textrm{A}}\\\\\n        U_{\\textrm{P},\\textrm{B}}\n    \\end{bmatrix}\n\\end{align*}\n\nThese mixing coefficients $k_0$ and $k_1$ express the recorded amplitude $U_{\\textrm{P}}$ in terms of the recorded amplitudes $U_0$ and $U_1$,\n\n\\begin{align}\\label{eq:V_pool_saline}\nU_{\\rm{P}}=k_0 U_0 + k_1 U_1\n\\end{align}\n\n\n\n\n```python\ndef FAname(probe,freq,grad,bank):\n    '''\n    returns the file name for fourier amplitudes \n    probe in ['2','3']\n    freq in ['400','1000']\n    grad in ['bot','top']\n    bank in ['0','1','01']\n    '''\n    return 'data/Probe'+probe+'/FA_p'+probe+'_f'+freq+'_g'+grad+'_b'+bank\n```\n\n\n```python\n# compute pooling coefficients for a given probe, frequency\ndef getPC(probe,freq):\n    with open(FAname(probe,freq,'top','0'), \"rb\") as f: \n        dt0=pickle.load(f)\n    with open(FAname(probe,freq,'top','1'), \"rb\") as f: \n        dt1=pickle.load(f)\n    with open(FAname(probe,freq,'top','01'), \"rb\") as f: \n        dt01=pickle.load(f)\n    with open(FAname(probe,freq,'bot','0'), \"rb\") as f: \n        db0=pickle.load(f)\n    with open(FAname(probe,freq,'bot','1'), \"rb\") as f: \n        db1=pickle.load(f)\n    with open(FAname(probe,freq,'bot','01'), \"rb\") as f: \n        db01=pickle.load(f)\n    sp=np.stack((dt01,db01),axis=-1) # (384,2) pooled signal with the 2 gradients \n    A=np.stack((np.stack((abs(dt0),abs(dt1)),axis=-1),\n                np.stack((abs(db0),abs(db1)),axis=-1)),axis=-2) # (384,2,2) split signals\n    spe=np.expand_dims(sp,axis=-1) # add an empty dimension for proper multiplication\n    Ainv=np.linalg.inv(A) # (384,2,2) 384 inverses, each (2,2)\n    kpe=np.matmul(Ainv,spe) # multiply inverse * vector 384 times\n    kf=np.squeeze(kpe) # remove the empty dimension\n    return kf # (384,2) pooling coefficients\n```\n\n\n```python\n# compute and plot all pooling coeffs \nkf2=getPC('2','1000')\nax=plot([kf2[:,0],kf2[:,1]],fmts=['r-','g-'],linewidth=1,ylim=[0,1.1],\n    figsize=(10,4),title='Probe 2, 1000 Hz, Pooling coefficients',legend=['bank0','bank1'],\n    xlabel='Wire',ylabel='Pooling coefficient');\n```\n\n## Identify sites with defective switches\nWe found that this probe contained a few defective switches that did not repond correctly to the control signal. Those sites are recognized by the grossly abnormal pooling coefficients in the graph above. \n\nHere we identify the \"good\" sites on Probe 2:\n\n\n```python\n# Mark the sites with pooling coefficients inside [0.4,0.6]\nP2_OK=np.logical_and(np.logical_and(kf2[:,0]>0.4,kf2[:,0]<0.6),np.logical_and(kf2[:,1]>0.4,kf2[:,1]<0.6))\nprint(len(np.where(P2_OK==True)[0]),'good sites')\n```\n\n    356 good sites\n\n\n## Plot the pooling coefficients at the good sites\n\n\n```python\n# Plot pooling coeffs at good sites\nkf2=getPC('2','1000')\nwire=np.arange(384)\nfig,axes=plt.subplots(1,2,figsize=(8,2.5),gridspec_kw={'width_ratios':[6, 1]})\nplot(wire[P2_OK],[kf2[P2_OK,0],kf2[P2_OK,1]],fmts=['r.','g.'],markersize=2,\n    xlabel='Wire',ylabel='Pooling coefficient',\n    legend=['bank0','bank1'],loc='upper right',xlim=[-5,389],ylim=[0.0,1.0],\n    yticks=[0,0.5,1],axes=axes[0]);\nhist([kf2[P2_OK,0],kf2[P2_OK,1]],bins=np.arange(0,1.1,0.02),\n    orientation='horizontal',xhide=True,yhide=False,\n    ylim=[0.0,1.0],yticks=[0,0.5,1],axes=axes[1]);\naxes[1].tick_params(labelleft=False) \nfig.subplots_adjust(wspace=0.02)\nplt.savefig('figs/PoolCoeffsProbe2.pdf')\n```\n\n# Electrical characteristics measured in saline \n\n## Load raw Neuropixel recordings and compute power spectra\nThis routine is included for reference only. It simply applies a power spectral analysis to each channel of the Neuropixels output.\n\nThe input to this routine is not included in this repo because too voluminous.\n\nThe output power spectra are provided.\n\n\n```python\n# Load raw data and compute spectrum for each site. This will not run, provided for reference only!\n# def pow_all_P2(conc,bank):\n#     '''\n#     compute power spectra for all sites on Probe 2\n#     conc=concentration\n#     bank=bank\n#     '''\n#     binFullPath=Path(getFileNameP2(conc,bank)) # probe 2\n#     meta=readMeta(binFullPath) # get metadata\n#     rawData = makeMemMapRaw(binFullPath, meta)\n#     sRate=SampRate(meta) # get sampling rate (in Hz)\n#     tStart=10        # in seconds\n#     tEnd=60\n#     pa=[]\n#     for i in range(384):\n#         chanList = [i] # channels to load\n#         selectData=rawData[chanList,int(tStart*sRate):int(tEnd*sRate)]\n#         if meta['typeThis'] == 'imec':\n#             convData=GainCorrectIM(selectData, chanList, meta) # apply gain correction and convert to units of V\n#         x=convData[0]  \n#         fr,po=signal.welch(x,sRate,nperseg=4096) # set of frequencies and power spectral density\n#         pa+=[po]\n#     with open('Probe2/NoiseSpectrum_p2_c'+conc+'_b'+bank, \"wb\") as f: \n#         pickle.dump((fr,pa),f)\n```\n\n\n```python\n# # compute spectra for all concentrations and banks, one file each\n# for conc in ['-3','-2','-1','0','1']: # log_10 of saline concentration\n#     for bank in ['0','1','01']: # split bank 0, split bank 1, pooled\n#         pow_all_P2(conc,bank)\n```\n\n## Fit a 4-parameter circuit model to the noise spectra\n\n\n\nThe goal here is to infer the values of the components in the above circuit from the RMS noise measurements observed at the output ($U$) under the different conditions: 5 saline concentrations and 3 switch settings.\n\nThe assumptions are:\n- The source of the noise is thermal noise in $R_0$ and $R_1$ and electronic noise $N_\\rm{amp}$.\n- $R_0$ and $R_1$ vary in inverse proportion to the saline concentration.\n- $C_0$ and $C_1$ are such that at normal saline the electrode impedance is the spec value of 170 kohm.\n- $R_\\rm{S}$ is infinite, i.e. the shunt impedance is entirely capacitive.\n\nWith these assumptions there are only 4 free parameters of the model: $R_0$ and $R_1$ in normal saline, $C_\\rm{S}$ and $N_\\rm{amp}$. Those 4 parameters are optimized to fit the 15 noise measurements by minimizing the squared error. \n\n\n```python\n# Some useful global numbers\nc=np.array([0.001,0.01,0.1,1,10]) # concentrations\nfLo=300 # low end of frequency band to be fit, in Hz\nfHi=10000 # high end of frequency band to be fit, in Hz\nre=1.5e5 # spec impedance of each electrode at f = 1 kHz, in ohm\nom1kHz=2*np.pi*1e3 # radial frequency at f = 1 kHz, in s^-1\nkT=4.1e-21 # kT in J\n```\n\n\n```python\n# Load noise power spectra for probe 2 and integrate to get RMS noise\nno=np.zeros((5,3,384)) # 5 concentrations, 3 switch conditions, 384 sites\nfor i,conc in enumerate(['-3','-2','-1','0','1']):\n    for j,bank in enumerate(['0','1','01']):\n        with open('data/Probe2/NoiseSpectrum_p2_c'+conc+'_b'+bank, \"rb\") as f: # load spectra from files\n            fd,p=pickle.load(f)\n        p=np.array(p)\n        no[i,j]=np.sqrt(np.sum(p[:,np.logical_and(fd>=fLo,fd<fHi)],axis=-1)*(fd[1]-fd[0])) # integrate over the AP band to get RMS noise\n```\n\n\n```python\n# More useful global numbers\nfr=fd[np.logical_and(fd>=fLo,fd<fHi)] # frequencies where to simulate the power (same as in the measured spectra)\nom=2*np.pi*fr # corresponding radial frequencies\ndf=fd[1]-fd[0] # delta f between frequencies\n```\n\n\n```python\ndef par(x,y):\n    '''\n    return impedance of parallel impedances x and y\n    '''\n    return x*y/(x+y)\n```\n\n\n```python\ndef noi6(r0,r1,cs,c0,c1):\n    '''\n    Simulates the 5-component circuit for one set of the parameters\n    Computes the Johnson noise for the two split modes and the pooled mode\n    Inputs in ohm and F\n    Outputs in V\n    '''\n    z0=r0+1/(1j*om*c0) # complex impedance electrode 0\n    z1=r1+1/(1j*om*c1) # complex impedance electrode 1\n    zs=1/(1j*om*cs) # complex impedance shunt\n    k00=1/(1+z0/zs) # gain for input to R0 in split 0 recording\n    k11=1/(1+z1/zs) # gain for input to R1 in split 1 recording\n    k0p=1/(1+z0/par(z1,zs)) # gain for input to R0 in pooled recording\n    k1p=1/(1+z1/par(z0,zs)) # gain for input to R1 in pooled recording\n    v0=np.sqrt(sum(4*kT*(r0*abs(k00)**2))*df) # integrate Johnson noise spectrum in mode split 0\n    v1=np.sqrt(sum(4*kT*(r1*abs(k11)**2))*df) # integrate Johnson noise spectrum in mode split 1\n    v01=np.sqrt(sum(4*kT*(r0*abs(k0p)**2+r1*abs(k1p)**2))*df) # integrate Johnson noise spectrum in pooled mode\n    return v0,v1,v01 # return the RMS noise for each mode\n    \ndef eval6(x):\n    '''\n    Evaluates a 4-parameter circuit model. \n    Computes the RMS noise in the two split modes and in pooled mode for all saline concentrations.\n    x = [r0,r1,cs,vc] = the model parameters\n    Input: resistors in Mohm, capacitors in pF, common noise in uV\n    Output: 5x3 array with RMS noise in V vs concentration and mode\n    '''\n    r0=x[0]*1e6 # R_0 at concn = 1, scale to SI units\n    r1=x[1]*1e6 # R_1 at concn = 1\n    cs=x[2]*1e-12 # C_s, the shunt capacitance\n    vc=x[3]*1e-6 # N_amp, the electronic noise\n    c0=1/om1kHz/np.sqrt(re**2-r0**2) # choose C0 in F to make R_ele0 = re\n    c1=1/om1kHz/np.sqrt(re**2-r1**2) # choose C1 in F to make R_ele1 = re\n    v=np.zeros((5,3))    \n    for i,co in enumerate(c): # for each concentration\n        r0c=r0/co # compute the resistors\n        r1c=r1/co\n        v[i]=noi6(r0c,r1c,cs,c0,c1) # get the Johnson noise\n        v[i]=np.sqrt(v[i]**2+vc**2) # add the electronic noise in quadrature\n    return v # return one (5,3) array of RMS noise\n\ndef fit6(x,j):\n    '''\n    Returns the squared error between predicted and observed noise\n    x = [r0,r1,cs,vc] = the model parameters\n    j = site number on the array\n    Input: resistors in Mohm, common noise in uV\n    Output: error in uV**2\n    '''\n    v=eval6(x) # (5,3) array of predicted RMS noise\n    err=np.sum((no[:,:,j]-v)**2) # compare to measured noise\n    return err*1e12 # error in \u00b5V^2\n```\n\n\n```python\n# Perform 4-parameter circuit fits to all 384 sites. This takes a little while to run...\n# [r0,r1,cs,vc] = the model parameters\n# r in Mohm, c in pF, vc in uV\npar6=np.zeros((384,4)) # store best-fit parameters in this array\nerr6=np.zeros(384) # store errors\nfor j in range(384):\n    res=minimize(fun=fit6, x0=(0.01,0.01,8,6.0), # minimize squared error\n             args=(j), method = 'L-BFGS-B',jac=None, hess=None, hessp=None, \n             bounds=[(1e-8,re/1e6-1e-8),(1e-8,re/1e6-1e-8),(1e-8,None),(1e-8,None)], \n             constraints=(), tol=None, callback=None, options=None)\n    par6[j]=res.x  \n    err6[j]=res.fun\n    print(j,end=',')\nwith open('data/Probe2/2R1Crms_P2', 'wb') as f: # save parameters and fit errors to file\n        pickle.dump((par6,err6),f)\n```\n\n    0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,\n\n## Examples of noise measurements and fits from the circuit model\n\n\n```python\n# Load 2R1C circuit parameters for Probe 2\nwith open('data/Probe2/2R1Crms_P2', 'rb') as f:\n    pa,er=pickle.load(f)\n```\n\n\n```python\n# Load data for rms noise probe 2\nno=np.zeros((5,3,384))\nfor i,conc in enumerate(['-3','-2','-1','0','1']):\n    for j,bank in enumerate(['0','1','01']):\n        with open('data/Probe2/NoiseSpectrum_p2_c'+conc+'_b'+bank, \"rb\") as f: \n            fd,p=pickle.load(f)\n        p=np.array(p)\n        no[i,j]=np.sqrt(np.sum(p[:,np.logical_and(fd>=fLo,fd<fHi)],axis=-1)*(fd[1]-fd[0])) # rms noise\nfr=fd[np.logical_and(fd>=fLo,fd<fHi)] # frequencies where to evaluate the power\nom=2*np.pi*fr\ndf=fd[1]-fd[0]\n```\n\n\n```python\ndef plotFitFig(j):\n    '''\n    Plots RMS noise vs saline concentration for site number j, in the 2 split conditions and pooled\n    ALso plots predictions from the 4-parameter circuit model for that site\n    assumes no[:,:,j] = RMS noise data, pa[j] = parameters, and eval6(pa[j]) = the fit, c = concentrations\n    '''\n    fdata=['ro','g+','bs']\n    ffit=['r-','g-','b-']\n    td=no[:,:,j]*1e6\n    tf=eval6(pa[j])*1e6\n    ax=plot(c,[td[:,0],td[:,1],td[:,2]],fmts=fdata,xscale='log',figsize=(3,3),fillstyle='none');\n    plot(c,[tf[:,0],tf[:,1],tf[:,2]],fmts=ffit,xscale='log',axes=ax,\n        xlabel='Saline concentration',ylabel='RMS noise (\u00b5V)',\n        legend=['split 0','split 1','pooled'],xticks=[1e-3,1e-2,1e-1,1,10],\n        ylim=[0,25]);\n    plt.minorticks_off()\n    plt.savefig('figs/PowerVsConc{:03d}.pdf'.format(j))\n```\n\n### Figure 8C left\n\n\n```python\nplotFitFig(19)\n```\n\n### Figure 8C right\n\n\n```python\nplotFitFig(353)\n```\n\n## Noise in the highest saline, bank 1 vs bank 2\n\n### Figure 8D\n\n\n```python\n# Noise in 10x saline split 1 vs split 0. Limit to sites with OK switches.\nax=plot(no[4,0,P2_OK]*1e6,no[4,2,P2_OK]*1e6,fmts=['bo'],markersize=2,equal=True);\nx=[0,15]\nplot(x,x,fmts=['k:'],linewidth=1,axes=ax,\n     xlabel='Split 0 RMS noise (\u00b5V)',ylabel='Split 1 RMS noise (\u00b5V)',xlim=[0,15],ylim=[0,15],\n    xticks=[0,5,10,15],yticks=[0,5,10,15]);\nplt.savefig('figs/Noise10xSaline.pdf')\n```\n\n## Histograms of the parameters in the circuit model\n\nHistogram the 4 parameters of the circuit model for Probe 2. \n\nLimit this to sites with \n- functioning switches and \n- a good fit with small residual error.\n\n### Figure 8E\n\n\n```python\n# Probe 2, rms noise, 2R1C circuit model, sites with err<4 and OK switches\nwith open('data/Probe2/2R1Crms_P2', 'rb') as f:\n    p,e=pickle.load(f)\nOK=np.logical_and(P2_OK,e<4)\nprint('Histograms over {} sites'.format(len(np.where(OK==True)[0])))\nhist(p[OK,0]*1000,bins=np.arange(100)*0.3,xlabel='$R_0$ (kohm)',color='red',xlim=[0,25],figsize=(2,2),yhide=True);\nplt.savefig('figs/P2_R0_Hist.pdf')\nplt.show()\nhist(p[OK,1]*1000,bins=np.arange(100)*0.3,xlabel='$R_1$ (kohm)',color='green',xlim=[0,25],figsize=(2,2),yhide=True);\nplt.savefig('figs/P2_R1_Hist.pdf')\nplt.show()\nhist(p[OK,2],bins=np.arange(100)*0.15,xlabel='$C_{\\mathrm{s}}$ (pF)',color='blue',xlim=[0,15],figsize=(2,2),\n     yhide=True,xticks=[0,5,10,15]);\nplt.savefig('figs/P2_Cs_Hist.pdf')\nplt.show()\nhist(p[OK,3],bins=np.arange(100)*0.1,xlabel='$N_{\\mathrm{amp}}$ (\u00b5V)',color='magenta',xlim=[0,15],figsize=(2,2),yhide=True);\nplt.savefig('figs/P2_Na_Hist.pdf')\nplt.show()\n```\n\n### Figure 4C\n\n\n```python\nhist(p[OK,3],bins=np.arange(150)*0.1,xlabel='$N_{\\mathrm{amp}}$ (\u00b5V)',color='magenta',xlim=[0,15],figsize=(2,2),yhide=True);\nplt.savefig('figs/P2_Na_Hist2.pdf')\nplt.show()\n```\n\n\n```python\nnp.max(p[OK,3])\n```\n\n\n\n\n    14.358126381876733\n\n\n\n# Revision\n\n## Thermal noise\nUse the measured bath resistors to compute the resulting noise from thermal noise alone. Do in split 0, split 1, and pool condition. Report the results of split 0 and split 1\n\n\n```python\n# Probe 2, rms noise, 2R1C circuit model, sites with err<4 and OK switches\n# [r0,r1,cs,vc] = the model parameters\n# r in Mohm, c in pF, vc in uV\nwith open('data/Probe2/2R1Crms_P2', 'rb') as f: # load circuit parameters for this probe\n    p,e=pickle.load(f)\nOK=np.logical_and(P2_OK,e<4) # \"good\" sites\n\nfLo=300 # low end of frequency band to be fit, in Hz\nfHi=10000 # high end of frequency band to be fit, in Hz\nre=1.5e5 # spec impedance of each electrode at f = 1 kHz, in ohm\nom1kHz=2*np.pi*1e3 # radial frequency at f = 1 kHz, in s^-1\nkT=4.1e-21 # kT in J\n\nfr=np.arange(fLo,fHi+10,10) # range of frequencies with 10 Hz sampling\nom=2*np.pi*fr # corresponding radial frequencies\ndf=fr[1]-fr[0] # delta f between frequencies\n\nr0=p[:,0]*1e6 # R_0 at concn = 1, scale to SI units\nr1=p[:,1]*1e6 # R_1 at concn = 1\ncs=p[:,2]*1e-12 # C_s, the shunt capacitance\nvc=p[:,3]*1e-6 # V_c, the common noise voltage\nc0=1/om1kHz/np.sqrt(re**2-r0**2) # choose C0 in F to make R_ele0 = re\nc1=1/om1kHz/np.sqrt(re**2-r1**2) # choose C1 in F to make R_ele1 = re\n\nno=np.array([noi6(*x) for x in zip(r0,r1,cs,c0,c1)]) # compute noise [split0, split1, pool]\n```\n\n### Figure 4B\n\n\n```python\n# histogram thermal noise, separately on banks 0 and 1\nhist([no[OK,0]*1e6,no[OK,1]*1e6],\n     bins=np.arange(100)*0.02,\n     xlabel=r'$N_{\\rm{the}}$ (\u00b5V)',\n     color=['red','green'],\n     xlim=[0,2],\n     figsize=(2,2),yhide=True,\n#      legend=['bank 0','bank 1'],\n#      loc='upper left', \n);\nplt.savefig('figs/P2_Nthe_Hist.pdf')\n```\n\n\n```python\nprint('Thermal noise = {:.2f} \u00b1 {:.2f} \u00b5V'.format(\n    np.mean(np.concatenate((no[OK,0],no[OK,1]))*1e6),\n    np.std(np.concatenate((no[OK,0],no[OK,1]))*1e6)))\n```\n\n    Thermal noise = 1.45 \u00b1 0.10 \u00b5V\n\n\n\n```python\n# histogram thermal noise, combine banks 0 and 1\nhist(np.concatenate((no[OK,0],no[OK,1]))*1e6,bins=np.arange(100)*0.02,xlabel=r'$N_{\\rm{the}}$ (\u00b5V)',\n     color=['red'],xlim=[0,2],figsize=(3,2),yhide=True,\n    loc='upper left');\nplt.savefig('figs/P2_Nthe_Hist_Both.pdf')\n```\n\n## Pooling coefficients\n\n### In vitro\n\n#### Figure 4A\n\n\n```python\n# Plot pooling coeffs at good sites\nkf2=getPC('2','1000')\nhist([kf2[P2_OK,0],kf2[P2_OK,1]],bins=np.arange(0,1.1,0.02),yhide=True,\n    xticks=[0,0.5,1],xlim=[0,1],figsize=(2.8,1.95),legend=['bank 0','bank 1'],loc='upper left',\n    xlabel=r'$c_{\\rm{0}},c_{\\rm{1}}$');\nplt.savefig('figs/P2_PC_Hist.pdf')\n```\n\n### In vivo\n\n\n```python\n# Plot pooling coeffs at good sites\nwi=np.genfromtxt('data/Invivo/channels_with_signal_on_both_banks.csv',delimiter=',',dtype='int')\ncv0=np.genfromtxt('data/Invivo/invivo_bank0_pooling_coeff.csv',delimiter=',')\ncv1=np.genfromtxt('data/Invivo/invivo_bank1_pooling_coeff.csv',delimiter=',')\ncs0=np.genfromtxt('data/Invivo/saline_bank0_pooling_coeff.csv',delimiter=',')\ncs1=np.genfromtxt('data/Invivo/saline_bank1_pooling_coeff.csv',delimiter=',')\n```\n\n#### Figure 4E\n\n\n```python\nfig,ax=plt.subplots(2,2,\n                    figsize=(4.2,4.2),\n                    gridspec_kw={'width_ratios':[3,1],'height_ratios':[1,3]},\n#                     sharex='col',\n#                     sharey='row',\n)\nplot([cs0,cs1,[0,1]],[cv0,cv1,[0,1]],\n     fmts=['r.','g.','k:'],\n     linewidth=1,\n#      equal=True,\n     xlim=[0,1],\n     ylim=[0,1],\n     xticks=[0,0.5,1],\n     yticks=[0,0.5,1],\n     xlabel=r'$c_{\\rm{0}},c_{\\rm{1}}$ in saline',\n     ylabel=r'$c_{\\rm{0}},c_{\\rm{1}}$ in brain',\n#      legend=['Bank 0','Bank 1'],\n     axes=ax[1,0],\n);\nhist([cs0,cs1],\n     bins=np.arange(0,1.025,0.025),\n     yhide=True,\n     xlim=[0,1],\n     xticks=[0,0.5,1],\n     axes=ax[0,0]);\nax[0,0].tick_params(labelbottom=False)\n\nhist([cv0,cv1],\n     bins=np.arange(0,1.025,0.025),\n     xhide=True,\n     ylim=[0,1],\n     yticks=[0,0.5,1],\n     orientation='horizontal',\n     axes=ax[1,1]);\nax[1,1].tick_params(labelleft=False)\n\nax[0,1].axis('off') \nfig.subplots_adjust(wspace=0.05,hspace=0.05)\n# fig.tight_layout()\nplt.savefig('figs/PCsInvivoVsSaline.pdf')\n\n```\n\n## Biological noise\n\n\n```python\nnb0=np.genfromtxt('data/Invivo/bank0_invivo_noise.csv',delimiter=',')\nnb1=np.genfromtxt('data/Invivo/bank1_invivo_noise.csv',delimiter=',')\nnb01=np.genfromtxt('data/Invivo/bank01_invivo_noise.csv',delimiter=',')\nnp01=np.genfromtxt('data/Invivo/bank01_invivo_noise_predicted.csv',delimiter=',')\n```\n\n### In the two split conditions\n\n#### Figure 4D\n\n\n```python\nhist([nb0,nb1],\n#      legend=['bank 0','bank 1'],\n     figsize=(2.5,2),xlabel=r'$N_{\\rm{bio}}$ split (\u00b5V)',\n     xlim=[0,22],\n    yhide=True,\n);\nplt.savefig('figs/Nbio_Hist.pdf')\n```\n\n### Pooled, predicted from independence vs measured\n\n#### Figure 4F\n\n\n```python\nx=np.array([5,15])\ny=x*np.sqrt(2)\nax=plot([x,x],[x,y],\n    fmts=['k:','r:'],\n    linewidth=1,\n    figsize=(4,4),\n);\nplot(np01,nb01,\n        fmts=['b.'],\n        xlim=[5,16],\n        ylim=[5,16],\n        xlabel=r'$N_{\\rm{bio}}$ pooled predicted (\u00b5V)',\n        ylabel=r'$N_{\\rm{bio}}$ pooled measured (\u00b5V)',\n        legend=['1 x',r'$\\sqrt{2}$ x'],\n        equal=True,\n        axes=ax,\n);\nplt.savefig('figs/Nbio_Pred.pdf')\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "8596ffaa4478b4573d7329b28009119eeb7d9882", "size": 362495, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Saline.ipynb", "max_stars_repo_name": "markusmeister/Electrode-Pooling-Data-and-Code", "max_stars_repo_head_hexsha": "189fd918fb243215f35bf0de5341bf627780b594", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-01-27T21:35:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T11:49:59.000Z", "max_issues_repo_path": "Saline.ipynb", "max_issues_repo_name": "markusmeister/Electrode-Pooling-Data-and-Code", "max_issues_repo_head_hexsha": "189fd918fb243215f35bf0de5341bf627780b594", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Saline.ipynb", "max_forks_repo_name": "markusmeister/Electrode-Pooling-Data-and-Code", "max_forks_repo_head_hexsha": "189fd918fb243215f35bf0de5341bf627780b594", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 279.4872783346, "max_line_length": 159892, "alphanum_fraction": 0.9287631554, "converted": true, "num_tokens": 10258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.341582499438317, "lm_q2_score": 0.0321007099578881, "lm_q1q2_score": 0.010965040741159887}}
{"text": "```python\n# weights can be downloaded from\n# https://github.com/duanzhiihao/RAPiD/releases/download/v0.1/pL1_MWHB608_Mar11_4500.ckpt\ndetector = Detector(model_name='rapid',\n                    backbone='yolov5n',\n                    weights_path='./weights/rapid_pL1_yolov5n_COCO608_Dec20_60000.ckpt',\n                    use_cuda=False)\n```\n\n    Using backbone yolov5s. Loading COCO pre-trained weights...\n    \n                     from  n    params  module                                  arguments                     \n      0                -1  1      1760  models.backbones.Conv                   [3, 16, 6, 2, 2]              \n      1                -1  1      4672  models.backbones.Conv                   [16, 32, 3, 2]                \n      2                -1  1      4800  models.backbones.C3                     [32, 32, 1]                   \n      3                -1  1     18560  models.backbones.Conv                   [32, 64, 3, 2]                \n      4                -1  2     29184  models.backbones.C3                     [64, 64, 2]                   \n      5                -1  1     73984  models.backbones.Conv                   [64, 128, 3, 2]               \n      6                -1  3    156928  models.backbones.C3                     [128, 128, 3]                 \n      7                -1  1    295424  models.backbones.Conv                   [128, 256, 3, 2]              \n      8                -1  1    296448  models.backbones.C3                     [256, 256, 1]                 \n      9                -1  1    164608  models.backbones.SPPF                   [256, 256, 5]                 \n     10                -1  1     33024  models.backbones.Conv                   [256, 128, 1, 1]              \n     11                -1  1         0  torch.nn.modules.upsampling.Upsample    [None, 2, 'nearest']          \n     12           [-1, 6]  1         0  models.backbones.Concat                 [1]                           \n     13                -1  1     90880  models.backbones.C3                     [256, 128, 1, False]          \n     14                -1  1      8320  models.backbones.Conv                   [128, 64, 1, 1]               \n     15                -1  1         0  torch.nn.modules.upsampling.Upsample    [None, 2, 'nearest']          \n     16           [-1, 4]  1         0  models.backbones.Concat                 [1]                           \n     17                -1  1     22912  models.backbones.C3                     [128, 64, 1, False]           \n     18                -1  1     36992  models.backbones.Conv                   [64, 64, 3, 2]                \n     19          [-1, 14]  1         0  models.backbones.Concat                 [1]                           \n     20                -1  1     74496  models.backbones.C3                     [128, 128, 1, False]          \n     21                -1  1    147712  models.backbones.Conv                   [128, 128, 3, 2]              \n     22          [-1, 10]  1         0  models.backbones.Concat                 [1]                           \n     23                -1  1    296448  models.backbones.C3                     [256, 256, 1, False]          \n    \n    Number of parameters in backbone: 1757152\n    Successfully initialized model rapid. Total number of trainable parameters: 2138006\n    Successfully loaded weights: ./weights/rapid_pL1_yolov5n_COCO608_Dec20_60000.ckpt\n    Using CPU instead of CUDA...\n\n\n\n```python\n# Single Image Detection\nim = detector.detect_one(img_path='./images/COCO/val2017/000000581062.jpg', return_img=True,\n                         input_size=608, conf_thres=0.3, test_aug=None, visualize=False)\n\nplt.figure(figsize=(12,12))\nplt.imshow(im)\nplt.show()\n```\n\n\n```python\nimport sympy as sp\nx\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "edb321c6ecc6a1eda7624df7b6da339d0e665886", "size": 575961, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "demo.ipynb", "max_stars_repo_name": "rha2thm/RAPiD", "max_stars_repo_head_hexsha": "8b95f0ffc01604539ff2188634801b24c6f9d667", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demo.ipynb", "max_issues_repo_name": "rha2thm/RAPiD", "max_issues_repo_head_hexsha": "8b95f0ffc01604539ff2188634801b24c6f9d667", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demo.ipynb", "max_forks_repo_name": "rha2thm/RAPiD", "max_forks_repo_head_hexsha": "8b95f0ffc01604539ff2188634801b24c6f9d667", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 4644.8467741935, "max_line_length": 570684, "alphanum_fraction": 0.9625391303, "converted": true, "num_tokens": 1023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491214448393346, "lm_q2_score": 0.02843603355945356, "lm_q1q2_score": 0.01094537465798637}}
{"text": "```python\n# code for loading the format for the notebook\nimport os\n\n# path : store the current path to convert back to it later\npath = os.getcwd()\nos.chdir(os.path.join('..', '..', 'notebook_format'))\nfrom formats import load_style\nload_style(plot_style = False)\n```\n\n\n\n\n<style>\n@import url('http://fonts.googleapis.com/css?family=Source+Code+Pro');\n@import url('http://fonts.googleapis.com/css?family=Vollkorn');\n@import url('http://fonts.googleapis.com/css?family=Arimo');\n@import url('http://fonts.googleapis.com/css?family=Fira_sans');\n\n    div.cell {\n        width: 1000px;\n        margin-left: 0% !important;\n        margin-right: auto;\n    }\n    div.text_cell code {\n        background: transparent;\n        color: #000000;\n        font-weight: 600;\n        font-size: 12pt;\n        font-style: bold;\n        font-family:  'Source Code Pro', Consolas, monocco, monospace;\n    }\n    h1 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n\t}\n\n    div.input_area {\n        background: #F6F6F9;\n        border: 1px solid #586e75;\n    }\n\n    .text_cell_render h1 {\n        font-weight: 200;\n        font-size: 30pt;\n        line-height: 100%;\n        color:#c76c0c;\n        margin-bottom: 0.5em;\n        margin-top: 1em;\n        display: block;\n        white-space: wrap;\n        text-align: left;\n    } \n    h2 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n        text-align: left;\n    }\n    .text_cell_render h2 {\n        font-weight: 200;\n        font-size: 16pt;\n        font-style: italic;\n        line-height: 100%;\n        color:#c76c0c;\n        margin-bottom: 0.5em;\n        margin-top: 1.5em;\n        display: block;\n        white-space: wrap;\n        text-align: left;\n    } \n    h3 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n    }\n    .text_cell_render h3 {\n        font-weight: 200;\n        font-size: 14pt;\n        line-height: 100%;\n        color:#d77c0c;\n        margin-bottom: 0.5em;\n        margin-top: 2em;\n        display: block;\n        white-space: wrap;\n        text-align: left;\n    }\n    h4 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n    }\n    .text_cell_render h4 {\n        font-weight: 100;\n        font-size: 14pt;\n        color:#d77c0c;\n        margin-bottom: 0.5em;\n        margin-top: 0.5em;\n        display: block;\n        white-space: nowrap;\n    }\n    h5 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n    }\n    .text_cell_render h5 {\n        font-weight: 200;\n        font-style: normal;\n        color: #1d3b84;\n        font-size: 16pt;\n        margin-bottom: 0em;\n        margin-top: 0.5em;\n        display: block;\n        white-space: nowrap;\n    }\n    div.text_cell_render{\n        font-family: 'Fira sans', verdana,arial,sans-serif;\n        line-height: 125%;\n        font-size: 115%;\n        text-align:justify;\n        text-justify:inter-word;\n    }\n    div.output_wrapper{\n        margin-top:0.2em;\n        margin-bottom:0.2em;\n    }\n\n    code{\n      font-size: 70%;\n    }\n    .rendered_html code{\n    background-color: transparent;\n    }\n    ul{\n        margin: 2em;\n    }\n    ul li{\n        padding-left: 0.5em; \n        margin-bottom: 0.5em; \n        margin-top: 0.5em; \n    }\n    ul li li{\n        padding-left: 0.2em; \n        margin-bottom: 0.2em; \n        margin-top: 0.2em; \n    }\n    ol{\n        margin: 2em;\n    }\n    ol li{\n        padding-left: 0.5em; \n        margin-bottom: 0.5em; \n        margin-top: 0.5em; \n    }\n    ul li{\n        padding-left: 0.5em; \n        margin-bottom: 0.5em; \n        margin-top: 0.2em; \n    }\n    a:link{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:visited{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:hover{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:focus{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:active{\n       font-weight: bold;\n       color:#447adb;\n    }\n    .rendered_html :link {\n       text-decoration: underline; \n    }\n    .rendered_html :hover {\n       text-decoration: none; \n    }\n    .rendered_html :visited {\n      text-decoration: none;\n    }\n    .rendered_html :focus {\n      text-decoration: none;\n    }\n    .rendered_html :active {\n      text-decoration: none;\n    }\n    .warning{\n        color: rgb( 240, 20, 20 )\n    } \n    hr {\n      color: #f3f3f3;\n      background-color: #f3f3f3;\n      height: 1px;\n    }\n    blockquote{\n      display:block;\n      background: #fcfcfc;\n      border-left: 5px solid #c76c0c;\n      font-family: 'Open sans',verdana,arial,sans-serif;\n      width:680px;\n      padding: 10px 10px 10px 10px;\n      text-align:justify;\n      text-justify:inter-word;\n      }\n      blockquote p {\n        margin-bottom: 0;\n        line-height: 125%;\n        font-size: 100%;\n      }\n</style>\n\n\n\n\n\n\n```python\nos.chdir(path)\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# 1. magic for inline plot\n# 2. magic to print version\n# 3. magic so that the notebook will reload external python modules\n# 4. a ipython magic to enable retina (high resolution) plots\n# https://gist.github.com/minrk/3301035\n%matplotlib inline\n%load_ext watermark\n%load_ext autoreload\n%autoreload 2\n%config InlineBackend.figure_format = 'retina'\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score, roc_curve, auc\nfrom sklearn.metrics import precision_recall_curve, average_precision_score\n\n%watermark -a 'Ethen' -d -t -v -p numpy,pandas,matplotlib,sklearn\n```\n\n    Ethen 2017-07-31 14:28:35 \n    \n    CPython 3.5.2\n    IPython 5.4.1\n    \n    numpy 1.13.1\n    pandas 0.20.2\n    matplotlib 2.0.2\n    sklearn 0.18.1\n\n\n# ROC/AUC for Binary Classification\n\nFor this documentation, we'll be working with a human resource dataset. Our goal is to find out the employees that are likely to leave in the future and act upon our findings, i.e. retain them before they choose to leave. This dataset contains 12000 observations and 7 variables, each representing :\n\n- `S` The satisfaction level on a scale of 0 to 1\n- `LPE` Last project evaluation by a client on a scale of 0 to 1\n- `NP` Represents the number of projects worked on by employee in the last 12 month\n- `ANH` Average number of hours worked in the last 12 month for that employee\n- `TIC` Amount of time the employee spent in the company, measured in years\n- `Newborn` This variable will take the value 1 if the employee had a newborn within the last 12 month and 0 otherwise\n- `left` 1 if the employee left the company, 0 if they\u2019re still working here. This is our response variable\n\n\n```python\nfilename = 'HR.csv'\ndata = pd.read_csv(filename)\nprint('dimensions: ', data.shape)\ndata.head()\n```\n\n    dimensions:  (12000, 7)\n\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>S</th>\n      <th>LPE</th>\n      <th>NP</th>\n      <th>ANH</th>\n      <th>TIC</th>\n      <th>Newborn</th>\n      <th>left</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.38</td>\n      <td>0.53</td>\n      <td>2</td>\n      <td>157</td>\n      <td>3</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.80</td>\n      <td>0.86</td>\n      <td>5</td>\n      <td>262</td>\n      <td>6</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.11</td>\n      <td>0.88</td>\n      <td>7</td>\n      <td>272</td>\n      <td>4</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.72</td>\n      <td>0.87</td>\n      <td>5</td>\n      <td>223</td>\n      <td>5</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.37</td>\n      <td>0.52</td>\n      <td>2</td>\n      <td>159</td>\n      <td>3</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nTo train and evaluate the model, we\u2019ll perform a simple train/test split. 80 percent of the dataset will be used to actually train the model, while the rest will be used to evaluate the accuracy of this model, i.e. out of sample error. Note that the best practice is to split it in three ways train/validation/test split.\n\n\n```python\nlabel_col = 'left'\nlabel = data[label_col].values\ndata = data.drop(label_col, axis = 1)\nprint('labels distribution:', np.bincount(label) / label.size)\n\ntest_size = 0.2\nrandom_state = 1234\ndata_train, data_test, y_train, y_test = train_test_split(\n    data, label, test_size = test_size, random_state = random_state, stratify = label)\n```\n\n    labels distribution: [ 0.83333333  0.16666667]\n\n\nThis probability table tells you that around 16 percent of the employees who became a staff member of yours have left! If those employees are all the ones that are performing well in the company, then this is probabliy not a good sign. We'll leave out the exploratory analysis part to you ...\n\n## Sklearn Transformer\n\nWe then convert perform some generic data preprocessing including standardizing the numeric columns and one-hot-encode the categorical columns (the \"Newborn\" variable is treated as a categorical variable) and convert everything into a numpy array that sklearn expects. This generic preprocessing step is written as a custom sklearn Transformer. You don't have to follow this structure if you prefer your way of doing it.\n\nTo roll out our own Transformer a adheres to the sklearn API, we need to \n\n- Ensure that all arguments to the `__init__` method should be explicit: i.e. `*args` or `**kwargs` should be avoided, as they will not be correctly handled within cross-validation routines\n- Subclass/Inherit [`BaseEstimator`](http://scikit-learn.org/stable/modules/generated/sklearn.base.BaseEstimator.html) to get some free stuff. It will give us class representations that are more informative when printing the class object. And provides us a `get_params` and `set_params` functions. These functionalities are used in sklearn's methods such as GridSearch and RandomSearch.\n- Subclass/Inherit an appropriate class for your task (one of ClassifierMixin, RegressorMixin, ClusterMixin, TransformerMixin). In our case, we will be implementing a Transformer, thus we'll be subclassing [`TransformerMixin`](http://scikit-learn.org/stable/modules/generated/sklearn.base.TransformerMixin.html). For transformer, we need to implement a `.fit` method which fits some stuff on the training data and a `.transform` method that can perform transformation on both the training and test data. Note that we don't need to subclass [`TransformerMixin`](http://scikit-learn.org/stable/modules/generated/sklearn.base.TransformerMixin.html) this to work, but it does give the end-user the idea that this is a Transformer and we get the `.fit_transform` method that does the fitting and transformer on the training data in one shot for free\n- In the fit implementation, you'll notice results that were learned during the `.fit` method is stored with a trailing underscore (e.g., self.colnames_). This is a convention used in sklearn so that we can quickly scan the members of an estimator and distinguish which members are fitting during training time\n\nIf you would like to read more on this topic. The following two link might be of interest to you.\n\n- [Blog: Creating your own estimator in scikit-learn](http://danielhnyk.cz/creating-your-own-estimator-scikit-learn/)\n- [scikit-learn Documentation: Rolling your own estimator](http://scikit-learn.org/dev/developers/contributing.html#rolling-your-own-estimator)\n\n\n```python\nfrom collections import defaultdict\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n\n\nclass Preprocess(BaseEstimator, TransformerMixin):\n    \"\"\"\n    Generic data preprocessing including:\n    - standardize numeric columns\n    - one-hot encode categorical columns\n\n    Parameters\n    ----------\n    num_cols : list\n        Numeric column's name\n    \n    cat_cols : list\n        Categorical column's name\n    \n    Attributes\n    ----------\n    colnames_ : list\n        Column name of the transformed numpy array\n        \n    label_encode_dict_ : dict of sklearn's LabelEncoder\n        LabelEncoder that was used to encode the value\n        of the categorical columns into with value between\n        0 and n_classes-1. Categorical columns will go through\n        this encoding process before being one-hot encoded \n    \n    cat_encode_ : sklearn's OneHotEncoder\n        OneHotEncoder that was used to one-hot encode the\n        categorical columns\n    \n    scaler_ : sklearn's StandardScaler\n        Scaler that was used to standardize the numeric columns\n    \"\"\"\n    def __init__(self, num_cols = None, cat_cols = None):\n        self.num_cols = num_cols\n        self.cat_cols = cat_cols\n\n    def fit(self, data):\n        \"\"\"\n        Fit the Preprocess\n        \n        Parameters\n        ----------\n        data : DataFrame\n        \"\"\"\n        data = data.copy()\n        \n        # Label encoding across multiple columns in scikit-learn\n        # https://stackoverflow.com/questions/24458645/label-encoding-across-multiple-columns-in-scikit-learn\n        if self.cat_cols is not None:\n            self.label_encode_dict_ = defaultdict(LabelEncoder)\n            label_encoded = (data[self.cat_cols]\n                             .apply(lambda x: self.label_encode_dict_[x.name].fit_transform(x)))\n\n            self.cat_encode_ = OneHotEncoder(sparse = False)\n            self.cat_encode_.fit(label_encoded)\n        \n        if self.num_cols is not None:\n            self.scaler_ = StandardScaler().fit(data[self.num_cols])\n        \n        # store the column names (numeric columns comes before the\n        # categorical columns) so we can refer to them later\n        if self.num_cols is not None:\n            colnames = self.num_cols.copy()\n        else:\n            colnames = []\n        \n        if self.cat_cols is not None:\n            for col in self.cat_cols:\n                cat_colnames = [col + '_' + str(classes)\n                                for classes in self.label_encode_dict_[col].classes_]\n                colnames += cat_colnames\n\n        self.colnames_ = colnames\n        return self\n\n    def transform(self, data):\n        \"\"\"\n        Trasform the data using the fitted Preprocess\n        \n        Parameters\n        ----------\n        data : DataFrame\n        \"\"\"\n        if self.cat_cols is not None:\n            label_encoded = (data[self.cat_cols]\n                             .apply(lambda x: self.label_encode_dict_[x.name].transform(x)))\n            cat_encoded = self.cat_encode_.transform(label_encoded)\n        \n        if self.num_cols is not None:\n            scaled = self.scaler_.transform(data[self.num_cols])\n        \n        # combine encoded categorical columns and scaled numerical\n        # columns, it's the same as concatenate it along axis 1\n        if self.cat_cols is not None and self.num_cols is not None:\n            X = np.hstack((scaled, cat_encoded))\n        elif self.num_cols is None:\n            X = cat_encoded\n        else:\n            X = scaled\n        \n        return X\n```\n\n\n```python\nnum_cols = ['S', 'LPE', 'NP', 'ANH', 'TIC']\ncat_cols = ['Newborn']\n\npreprocess = Preprocess(num_cols, cat_cols)\nX_train = preprocess.fit_transform(data_train)\nX_test = preprocess.transform(data_test)\n\nprint('colnames', preprocess.colnames_)\nX_train\n```\n\n    colnames ['S', 'LPE', 'NP', 'ANH', 'TIC', 'Newborn_0', 'Newborn_1']\n\n\n\n\n\n    array([[ 0.24997745,  0.61402599,  0.16885833, ...,  0.72182646,\n             1.        ,  0.        ],\n           [ 0.12545568, -0.27568766,  1.02655144, ..., -0.22007024,\n             1.        ,  0.        ],\n           [ 0.58203549, -1.34334405,  0.16885833, ..., -0.22007024,\n             1.        ,  0.        ],\n           ..., \n           [-1.32729826, -0.75020161, -0.68883478, ..., -0.22007024,\n             1.        ,  0.        ],\n           [ 0.58203549, -0.21637342, -0.68883478, ..., -1.16196694,\n             0.        ,  1.        ],\n           [ 0.45751372,  0.25814053, -0.68883478, ..., -0.22007024,\n             1.        ,  0.        ]])\n\n\n\n\n```python\n# pick your favorite classfication model\ntree = RandomForestClassifier(max_depth = 4)\ntree.fit(X_train, y_train)\n```\n\n\n\n\n    RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',\n                max_depth=4, max_features='auto', max_leaf_nodes=None,\n                min_impurity_split=1e-07, min_samples_leaf=1,\n                min_samples_split=2, min_weight_fraction_leaf=0.0,\n                n_estimators=10, n_jobs=1, oob_score=False, random_state=None,\n                verbose=0, warm_start=False)\n\n\n\nAfter training our model, we need to evaluate whether its any good or not and probably the most straightforward and intuitive metric for a supervised classifier's performance is accuracy. Unfortunately, there are circumstances where simple accuracy does not work well. For example, with a disease that only affects 1 in a million people, a completely bogus screening test that always reports \"negative\" will be 99.9999% accurate. Unlike accuracy, ROC curves are less sensitive to class imbalance; the bogus screening test would have an AUC of 0.5, which is like not having a test at all. \n\n\n## ROC curves\n\n**ROC curve (Receiver Operating Characteristic)** is a commonly used way to visualize the performance of a binary classifier and AUC (Area Under the ROC Curve) is used to summarize its performance in a single number. Most machine learning algorithms have the ability to produce probability scores that tells us the strength in which it thinks a given observation is positive. Turning these probability scores into yes or no predictions requires setting a threshold; cases with scores above the threshold are classified as positive, and vice versa. Different threshold values can lead to different result:\n\n- A higher threshold is more conservative about labelling a case as positive; this makes it less likely to produce false positive (an observation that has a negative label but gets classified as positive by the model) results but more likely to miss cases that are in fact positive (lower true positive rate)\n- A lower threshold produces positive labels more liberally, so it creates more false positives but also generate more true positives\n\nA quick refresher on terminology:\n\n\\begin{align}\n[\\text{true positive rate}]\n&= \\frac{[\\text{# positive data points with positive predicitions}]}{\\text{[# all positive data points]}} \\\\\n&= \\frac{[\\text{# true positives}]}{[\\text{# true positives}] + [\\text{# false negatives}]}\n\\end{align}\n\ntrue positive rate is also known as **recall** or **sensitivity**\n\n\\begin{align}\n[\\text{false positive rate}]\n&= \\frac{[\\text{# positive data points with positive predicitions}]}{\\text{[# all negative data points]}} \\\\\n&= \\frac{[\\text{# false positives}]}{[\\text{# false positives}] + [\\text{# true negatives}]}\n\\end{align}\n\nThe ROC curve is created by plotting the true positive rate (when it's actually a yes, how often does it predict yes?) on the y axis against the false positive rate (when it's actually a no, how often does it predict yes?) on the x axis at various cutoff settings, giving us a picture of the whole spectrum of the tradeoff we're making between the two measures.\n\nIf all these true/false positive terminology is confusing to you, consider reading the material at the following link. [Blog: Simple guide to confusion matrix terminology](http://www.dataschool.io/simple-guide-to-confusion-matrix-terminology/)\n\n### Implementation\n\nThere are commonly used packages to plot ROC curves and to compute metrics from them, but it can still be worthwhile to work through how these curves are calculated from scratch to try to understand better what they show us.\n\n\n```python\ndef _binary_clf_curve(y_true, y_score):\n    \"\"\"\n    Calculate true and false positives per binary classification\n    threshold (can be used for roc curve or precision/recall curve);\n    the calcuation makes the assumption that the positive case\n    will always be labeled as 1\n\n    Parameters\n    ----------\n    y_true : 1d ndarray, shape = [n_samples]\n        True targets/labels of binary classification\n\n    y_score : 1d ndarray, shape = [n_samples]\n        Estimated probabilities or scores\n\n    Returns\n    -------\n    tps : 1d ndarray\n        True positives counts, index i records the number\n        of positive samples that got assigned a\n        score >= thresholds[i].\n        The total number of positive samples is equal to\n        tps[-1] (thus false negatives are given by tps[-1] - tps)\n\n    fps : 1d ndarray\n        False positives counts, index i records the number\n        of negative samples that got assigned a\n        score >= thresholds[i].\n        The total number of negative samples is equal to\n        fps[-1] (thus true negatives are given by fps[-1] - fps)\n\n    thresholds : 1d ndarray\n        Predicted score sorted in decreasing order\n\n    References\n    ----------\n    Github: scikit-learn _binary_clf_curve\n    - https://github.com/scikit-learn/scikit-learn/blob/ab93d65/sklearn/metrics/ranking.py#L263\n    \"\"\"\n\n    # sort predicted scores in descending order\n    # and also reorder corresponding truth values\n    desc_score_indices = np.argsort(y_score)[::-1]\n    y_score = y_score[desc_score_indices]\n    y_true = y_true[desc_score_indices]\n\n    # y_score typically consists of tied values. Here we extract\n    # the indices associated with the distinct values. We also\n    # concatenate a value for the end of the curve\n    distinct_indices = np.where(np.diff(y_score))[0]\n    end = np.array([y_true.size - 1])\n    threshold_indices = np.hstack((distinct_indices, end))\n\n    thresholds = y_score[threshold_indices]\n    tps = np.cumsum(y_true)[threshold_indices]\n\n    # (1 + threshold_indices) = the number of positives\n    # at each index, thus number of data points minus true\n    # positives = false positives\n    fps = (1 + threshold_indices) - tps\n    return tps, fps, thresholds\n```\n\n\n```python\n# we'll work with some toy data so it's easier to\n# show and confirm the calculated result\ny_true = np.array([1, 0, 1, 0, 1])\ny_score = np.array([0.45, 0.4, 0.35, 0.35, 0.8])\n\ntps, fps, thresholds = _binary_clf_curve(y_true, y_score)\nprint('thresholds:', thresholds)\nprint('true positive count:', tps)\nprint('false positive count:', fps)\n```\n\n    thresholds: [ 0.8   0.45  0.4   0.35]\n    true positive count: [1 2 2 3]\n    false positive count: [0 0 1 2]\n\n\nFrom the result above, we can see that the function will compute the true/false positive count for all unique threshold in the predicted score `y_score`. We can validate the result by hand to confirm that the calculation this in fact correct.\n\nRecall that ROC curve plots that true positive rate on the y-axis and false positive rate on the x-axis. Thus all we need to do is to convert the count into rate and we have our ROC curve.\n\n\n```python\n# convert count to rate, append 0 to\n# both true positive and false positive\n# so the visualization will start from origin (0, 0)\ntpr = np.hstack((0, tps / tps[-1]))\nfpr = np.hstack((0, fps / fps[-1]))\nprint('true positive rate:', tpr)\nprint('false positive rate:', fpr)\n\nplt.rcParams['figure.figsize'] = 8, 6\nplt.rcParams['font.size'] = 12\n\nfig = plt.figure()\nplt.plot(fpr, tpr, marker = 'o', lw = 1)\nplt.xlabel('false positive rate')\nplt.ylabel('true positive rate')\nplt.title('Receiver Operator Characteristic')\nplt.show()\n```\n\nNow to calculate the AUC (Area Under the Curve) for the ROC curve, we need sum up the rectangular area and the triangular area under the curve. Depicted by the visualization below:\n\n- For the rectangular area (the plot on the left illustrates one of them), the height are the TPR (true positive rate) and widths are in the difference in the FPR (false positive rate), so the total area of all the rectangles is the dot product of TPR and FPR's differences\n- For the triangluar area (the plot on the right illustrates one of them), the height are the difference in TPR (true positive rate) and widths are in the difference in the FPR (false positive rate), so the total area of all the rectangles is the dot product of both TPR's and FPR's difference. But only half the area of each rectangle is below its segment of the ROC curve, thus we divide the rectangle by 2 to obtain the triangular area\n\n\n```python\nimport matplotlib.patches as patches\n\n\nfig, ax = plt.subplots(1, 2, figsize = (10, 6))\nfig.suptitle('Receiver Operator Characteristic', y = 1.02)\n\n# this part is hard-coded for illustration purpose\nfpr_diff = fpr[3] - fpr[0]\ntpr_diff = tpr[3] - tpr[0]\nrect1 = patches.Rectangle(xy = (0, 0), width = fpr_diff,\n                          height = tpr_diff, alpha = 0.3)\nax[0].add_patch(rect1)\n\nfpr_diff = fpr[-1] - fpr[-2]\ntpr_diff = tpr[-1] - tpr[-2]\nrect2 = patches.Rectangle(xy = (fpr[-2], tpr[-2]), width = fpr_diff,\n                          height = tpr_diff, alpha = 0.3)\nax[1].add_patch(rect2)\n\nfor i in range(len(ax)):\n    ax[i].plot(fpr, tpr, marker = 'o', lw = 1)\n    ax[i].set_xlabel('false positive rate')\n    ax[i].set_ylabel('true positive rate')\n\nplt.tight_layout()\nplt.show()\n```\n\n\n```python\ndef _roc_auc_score(y_true, y_score):\n    \"\"\"\n    Compute Area Under the Curve (AUC) from prediction scores\n\n    Parameters\n    ----------\n    y_true : 1d ndarray, shape = [n_samples]\n        True targets/labels of binary classification\n\n    y_score : 1d ndarray, shape = [n_samples]\n        Estimated probabilities or scores\n\n    Returns\n    -------\n    auc : float\n    \"\"\"\n\n    # ensure the target is binary\n    if np.unique(y_true).size != 2:\n        raise ValueError('Only two class should be present in y_true. ROC AUC score '\n                         'is not defined in that case.')\n    \n    tps, fps, _ = _binary_clf_curve(y_true, y_score)\n\n    # convert count to rate\n    tpr = tps / tps[-1]\n    fpr = fps / fps[-1]\n\n    # compute AUC using the trapezoidal rule;\n    # appending an extra 0 is just to ensure the length matches\n    zero = np.array([0])\n    tpr_diff = np.hstack((np.diff(tpr), zero))\n    fpr_diff = np.hstack((np.diff(fpr), zero))\n    auc = np.dot(tpr, fpr_diff) + np.dot(tpr_diff, fpr_diff) / 2\n    return auc\n```\n\n\n```python\nauc_score = _roc_auc_score(y_true, y_score)\nprint('auc score:', auc_score)\n\n# confirm with scikit-learn's result\nauc_score = roc_auc_score(y_true, y_score)\nprint('package auc socre:', auc_score)\n```\n\n    auc score: 0.75\n    package auc socre: 0.75\n\n\nAfter working through the implementation of ROC curve and AUC score from sratch, we now pull back and visualize:\n\n- The ROC curve of our original model\n- Dotted line represents the ROC curve of a purely random classifier and a perfect classifier\n\n\n```python\n# calling the roc_curve, extract the probability of \n# the positive class from the predicted probability\ntree_test_pred = tree.predict_proba(X_test)[:, 1]\nfpr, tpr, thresholds = roc_curve(y_test, tree_test_pred, pos_label = 1)\n\n# AUC score that summarizes the ROC curve\nroc_auc = auc(fpr, tpr)\n\nplt.plot(fpr, tpr, lw = 2, label = 'ROC AUC: {:.2f}'.format(roc_auc))\nplt.plot([0, 1], [0, 1],\n         linestyle = '--',\n         color = (0.6, 0.6, 0.6),\n         label = 'random guessing')\nplt.plot([0, 0, 1], [0, 1, 1],\n         linestyle = ':',\n         color = 'black', \n         label = 'perfect performance')\n\nplt.xlim([-0.05, 1.05])\nplt.ylim([-0.05, 1.05])\nplt.xlabel('false positive rate')\nplt.ylabel('true positive rate')\nplt.title('Receiver Operator Characteristic')\nplt.legend(loc = \"lower right\")\nplt.tight_layout()\nplt.show()\n```\n\nThe goal of visualizing the  ROC curve is to let us know how well can our classifier be expected to perform in general, at a variety of different baseline probabilities (percentage of the majority class)?\n\nThe diagnoal line depicts a completely random classifier and ideally our model's ROC curve should be toward the top-left corner and stay as far away from the diagnoal line as possible.\n\nSide note: Apart from comparing the model's ROC curve against the ROC curve of a classifier that does random guessing, it's also useful to plot the ROC curve of different classifiers to compare performance against each other.\n\n\n### AUC probabilistic interpretation\n\n\nThe probabilistic interpretation of the AUC metric is that if we randomly choose a positive case and a negative case, the probability that the positive case outranks the negative case according to the classifier is given by the AUC. Hopefully, this is evident from the ROC curve figure, where plot is enumerating all possible combinations of positive and negative cases, and the fraction under the curve comprises of the area where the positive case outranks the negative one. I personally find this interpretation extremely useful when conveying what AUC is measuring to a non-technical audience.\n\n\n\n\n```python\ndef auc_probability(y_true, y_score, size = 100000):\n    \"\"\"probabilistic interpretation of AUC\"\"\"\n    labels = y_true.astype(np.bool)\n    pos = np.random.choice(y_score[labels], size = size, replace = True)\n    neg = np.random.choice(y_score[~labels], size = size, replace = True)\n    auc = np.sum(pos > neg) + np.sum(pos == neg) / 2\n    auc /= size\n    return auc\n\n\n# we want this be close the score returned\n# by roc_auc_score\nauc_probability(y_true = y_test, y_score = tree_test_pred)\n```\n\n\n\n\n    0.98211499999999996\n\n\n\n## Precision Recall Curve\n\nApart from ROC curve, there is also the **precision recall curve**. Instead of plotting true positive rate (a.k.a recall) versus false positive rate. We now plot precision versus recall.\n\n\\begin{align}\n[\\text{precision}]\n&= \\frac{[\\text{# positive data points with positive predicitions}]}{\\text{[# all data points with positive predictions]}} \\\\\n&= \\frac{[\\text{# true positives}]}{[\\text{# true positives}] + [\\text{# false positives}]}\n\\end{align}\n\n\n```python\ntree_test_pred = tree.predict_proba(X_test)[:, 1]\nprecision, recall, thresholds = precision_recall_curve(\n    y_test, tree_test_pred, pos_label = 1)\n\n# AUC score that summarizes the precision recall curve\navg_precision = average_precision_score(y_test, tree_test_pred)\n\nlabel = 'Precision Recall AUC: {:.2f}'.format(avg_precision)\nplt.plot(recall, precision, lw = 2, label = label)\nplt.xlabel('Recall')  \nplt.ylabel('Precision')  \nplt.title('Precision Recall Curve')\nplt.legend()\nplt.tight_layout()\nplt.show()\n```\n\nA classifier with high recall but low precision flags many positive results, but most of its predicted labels are incorrect when compared to its correponding labels. On the other hand, a classifier with high precision but low recall is just the opposite, returning very few results, but most of its predicted labels are correct when compared to the training labels. An ideal system with high precision and high recall will return many results, with all results labeled correctly.\n\nPrecision recall curve answers a fundamentally different question compared to ROC curve. By defition, precision directly answers the question, \"What is the probability that this is a real hit given my classifier says it is? Thus it is useful in practice for needle-in-haystack type problems or problems where the \"positive\" class is more interesting than the negative class.\n\nAlthough ROC curve is presumably the more popular choice when evaluating binary classifiers, it is highly recommended to use precision recall curve as a supplement to ROC curves to get a full picture when evaluating and comparing classifiers.\n\n# Thresholding via Cost\n\nLots of real world binary classification needs a threshold to convert the model into a business decision. i.e. All cases with a model score above the threshold get some sort of special treatment. For example:\n\n- **Fraud Prevention**: We're a social network company and we'd like to delete fake accounts. We build a classifier that assigns a \"fraud score\" between 0 and 1 to each account and, after some research, decide that all accounts whose score is above 0.9 should be sent to our fraud team, which will review each case and delete the accounts that are actually fake\n- **Response/Propensity Modeling**: We're at an enterprise software company and we'd like to improve our outbound sales program. We buy a large database of potential customers and build a classifier to predict which ones are likely buy our product if contacted by our sales team. We decide that all customers with a \"response score\" of above threshold 0.7 should get a call\n- **Shopping Cart Abandonment**: We're at an e-commerce company, and we'd like to email a 10% off coupon to users who abandoned their shopping carts and won't return organically. (We don't want to give a 10% off coupon to users who are going to return anyway, since then you'd be losing 10% of the sale price.) We build a classifier to predict which users will never return to their carts, and decide that all users with a \"abandonment score\" above 0.85 should get the 10% off coupon\n- Etc.\n\nThresholding is popular because of its simplicity and ease of implementation: We translate a continuous score to a binary yes/no decision, and act on it in a predetermined way. The biggest question for the thresholding pattern is: Where should I set the threshold point?\n\nUp until this point, we've been using AUC to give us a single-number summary of classifier performance. This might be suitable in some circumstances, but for binary classifiers, evaluation metrics that take into account the actual costs of false positive and false negative errors may be much more appropriate than AUC. If we know these costs, we can use them not only to tie the evaluation metric more directly to the business value but also choose an appropriate final cutoff threhold for the classifier.\n\nIn real world application, the cost that comes along with making these two mistakes (false positive and false negative) are usually a whole lot different. Take our case for example, a false negative (FN) means an employee left our company but our model failed to detect that, while a false positive (FP) means an employee is still currently working at our company and our model told us that they will be leaving. The former mistake would be a tragedy, since, well, the employee left and we didn\u2019t do anything about it! As for conducting the latter mistake, we might be wasting like 20 minutes of a HR manager's time when we arrange a face to face interview with a employee, questioning about how the company can do better to retain him/her, while he/she is perfectly fine with the current situation.\n\nIn the code cell below, we assign a cost for a false negative (FN) and false positive (FP) to be 100 and 1000 respectively, given the cost associated with the two mistakes we will multiply them with the false negative and false positive rate at each threshold to figure out where's the best cutoff value. Note that the cost associated with the mistake can just be a back of the envelope number as long as we're sure about which one is more \"expensive\" than the other.\n\n\n```python\nfpr, tpr, thresholds = roc_curve(y_test, tree_test_pred, pos_label = 1)\nfnr = tpr[-1] - tpr\n\n# fn = false negative, meaning the employee left and we\n# didn't do anything about it, in our case this will be\n# substantially more expensive than a false positive\nfp_cost = 100\nfn_cost = 1000\n\ncosts = (fpr * fp_cost + fnr * fn_cost) * y_test.size\n```\n\n\n```python\nbest = np.argmin(costs)\nbest_cost = np.round(costs[best])\nbest_threshold = np.round(thresholds[best], 2)\n\nplt.plot(thresholds, costs, label = 'cost ($)')\nlabel = 'best cost: {} at threshold {}'.format(best_cost, best_threshold)\nplt.axvline(best_threshold, linestyle = '--', lw = 2, color = 'black', label = label)\nplt.xlabel('threshold')  \nplt.ylabel('$')  \nplt.title('Cost as a Function of Threshold')\nplt.legend()\nplt.tight_layout()\nplt.show()\n```\n\nJust to hit the notion home, when executing on a project, if we are able to compute expected cost for each mistake, consider maximizing that directly instead of AUC or another general-purpose metrics.\n\n# Reference\n\n- [Scikit-learn Documentation: Precision Recall](http://scikit-learn.org/stable/auto_examples/model_selection/plot_precision_recall.html)\n- [StackExchange: ROC vs precision-and-recall curves](https://stats.stackexchange.com/questions/7207/roc-vs-precision-and-recall-curves)\n- [Blog: Calculating AUC: the area under a ROC Curve](http://blog.revolutionanalytics.com/2016/11/calculating-auc.html)\n- [Blog: Machine Learning Meets Economics](http://blog.mldb.ai/blog/posts/2016/01/ml-meets-economics/)\n- [Blog: Visualizing Machine Learning Thresholds to Make Better Business Decisions](http://blog.insightdatalabs.com/visualizing-classifier-thresholds/)\n", "meta": {"hexsha": "bd5e72294474f55aa3e96002ac2ce8400ccc192e", "size": 353323, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "model_selection/auc/auc.ipynb", "max_stars_repo_name": "Ani-singh/Insights---Data-Unicorn-12-Dec-17", "max_stars_repo_head_hexsha": "efdbde09e172613be96fbc5f069c9e3f893663d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "model_selection/auc/auc.ipynb", "max_issues_repo_name": "Ani-singh/Insights---Data-Unicorn-12-Dec-17", "max_issues_repo_head_hexsha": "efdbde09e172613be96fbc5f069c9e3f893663d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model_selection/auc/auc.ipynb", "max_forks_repo_name": "Ani-singh/Insights---Data-Unicorn-12-Dec-17", "max_forks_repo_head_hexsha": "efdbde09e172613be96fbc5f069c9e3f893663d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-08T17:36:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-08T17:36:36.000Z", "avg_line_length": 266.0564759036, "max_line_length": 84406, "alphanum_fraction": 0.8931827252, "converted": true, "num_tokens": 9276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12765261204695083, "lm_q2_score": 0.08509904036636974, "lm_q1q2_score": 0.010863114785456004}}
{"text": "```python\n'''\nMIT License\n\nCopyright (c) 2021 Valentin Gorbunov\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n'''\n```\n\n\n\n\n    '\\nMIT License\\n\\nCopyright (c) 2021 Valentin Gorbunov\\n\\nPermission is hereby granted, free of charge, to any person obtaining a copy\\nof this software and associated documentation files (the \"Software\"), to deal\\nin the Software without restriction, including without limitation the rights\\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\\ncopies of the Software, and to permit persons to whom the Software is\\nfurnished to do so, subject to the following conditions:\\n\\nThe above copyright notice and this permission notice shall be included in all\\ncopies or substantial portions of the Software.\\n\\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\\nSOFTWARE.\\n'\n\n\n\n## Environment Set Up\n\n\n```python\n# Install packages not in Colab by default\n!pip install vaderSentiment\n!pip install textstat\n!pip install flwr\n```\n\n    Requirement already satisfied: vaderSentiment in /usr/local/lib/python3.7/dist-packages (3.3.2)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from vaderSentiment) (2.23.0)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->vaderSentiment) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->vaderSentiment) (2021.10.8)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->vaderSentiment) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->vaderSentiment) (3.0.4)\n    Requirement already satisfied: textstat in /usr/local/lib/python3.7/dist-packages (0.7.3)\n    Requirement already satisfied: pyphen in /usr/local/lib/python3.7/dist-packages (from textstat) (0.12.0)\n    Requirement already satisfied: flwr in /usr/local/lib/python3.7/dist-packages (0.18.0)\n    Requirement already satisfied: importlib-metadata<2.0.0,>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from flwr) (1.7.0)\n    Requirement already satisfied: numpy<2.0.0,>=1.19.0 in /usr/local/lib/python3.7/dist-packages (from flwr) (1.21.6)\n    Requirement already satisfied: grpcio<=1.43.0,>=1.27.2 in /usr/local/lib/python3.7/dist-packages (from flwr) (1.43.0)\n    Requirement already satisfied: protobuf<4.0.0,>=3.12.1 in /usr/local/lib/python3.7/dist-packages (from flwr) (3.17.3)\n    Requirement already satisfied: google<3.0.0,>=2.0.3 in /usr/local/lib/python3.7/dist-packages (from flwr) (2.0.3)\n    Requirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.7/dist-packages (from google<3.0.0,>=2.0.3->flwr) (4.6.3)\n    Requirement already satisfied: six>=1.5.2 in /usr/local/lib/python3.7/dist-packages (from grpcio<=1.43.0,>=1.27.2->flwr) (1.15.0)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata<2.0.0,>=1.4.0->flwr) (3.8.0)\n\n\n\n```python\n# Import packages\nimport pickle\nimport sys\nimport string\nimport re\nimport nltk\nimport seaborn\nimport os\nimport time\nimport warnings\nimport random\nimport threading\nimport scipy\nimport json\nimport nltk.stem.porter\nimport pandas as pd\nimport numpy as np\nimport flwr as fl\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.metrics import classification_report, confusion_matrix, log_loss, precision_recall_fscore_support\nfrom sklearn.model_selection import train_test_split, StratifiedKFold\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer as VS\nfrom textstat.textstat import *\nfrom typing import Tuple, Union, List, Dict, Optional\nfrom flwr.server.criterion import Criterion\nfrom flwr.server.client_proxy import ClientProxy\nfrom flwr.common import Weights, FitRes, Parameters, Scalar, parameters_to_weights, weights_to_parameters\nfrom google.colab import drive\nfrom multiprocessing import Process, Manager\nfrom multiprocessing.managers import ListProxy\nfrom math import ceil\nfrom statistics import mean\nfrom datetime import datetime\nfrom functools import reduce\nimport textwrap\n%matplotlib inline\n```\n\n\n```python\n# Mount external storage\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```python\n# Configure global search paths\nHOME_DIR = \"/content/drive/MyDrive/\"\nLOGGING_FOLDERS_DIR = HOME_DIR + \"Results_Folders/\"\n```\n\n## Centralized Manual Pipeline\n\n\n```python\n'''\nCentralized Manual Pipeline Adapted From:\n\nTitle: Automated Hate Speech Detection and the Problem of Offensive Language.ipynb\nAuthors: Davidson et al.\nDate: Mar 29, 2019\nAvailability: https://github.com/t-davidson/hate-speech-and-offensive-language/blob/master/src/Automated%20Hate%20Speech%20Detection%20and%20the%20Problem%20of%20Offensive%20Language.ipynb\n\n'''\n```\n\n\n\n\n    '\\nAdapted from:\\n\\nTitle: Automated Hate Speech Detection and the Problem of Offensive Language.ipynb\\nAuthors: Davidson et al.\\nDate: Mar 29, 2019\\nAvailability: https://github.com/t-davidson/hate-speech-and-offensive-language/blob/master/src/Automated%20Hate%20Speech%20Detection%20and%20the%20Problem%20of%20Offensive%20Language.ipynb\\n\\n'\n\n\n\n### Preliminary Data Analysis\n\n\n```python\n# Deserialize Pandas DataFrame from pickle file\ndf = pd.read_pickle(open(HOME_DIR + \"labeled_data.p\", mode='rb'))\n```\n\n\n```python\n# Describe content, size and format of the data\ndf\n```\n\n\n\n\n\n  <div id=\"df-8c6a7709-226d-4af6-ae5e-23e518398cb2\">\n    <div class=\"colab-df-container\">\n      <div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>hate_speech</th>\n      <th>offensive_language</th>\n      <th>neither</th>\n      <th>class</th>\n      <th>tweet</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>3</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>2</td>\n      <td>!!! RT @mayasolovely: As a woman you shouldn't...</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>3</td>\n      <td>0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>1</td>\n      <td>!!!!! RT @mleew17: boy dats cold...tyga dwn ba...</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>3</td>\n      <td>0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>1</td>\n      <td>!!!!!!! RT @UrKindOfBrand Dawg!!!! RT @80sbaby...</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>3</td>\n      <td>0</td>\n      <td>2</td>\n      <td>1</td>\n      <td>1</td>\n      <td>!!!!!!!!! RT @C_G_Anderson: @viva_based she lo...</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>6</td>\n      <td>0</td>\n      <td>6</td>\n      <td>0</td>\n      <td>1</td>\n      <td>!!!!!!!!!!!!! RT @ShenikaRoberts: The shit you...</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>25291</th>\n      <td>3</td>\n      <td>0</td>\n      <td>2</td>\n      <td>1</td>\n      <td>1</td>\n      <td>you's a muthaf***in lie &amp;#8220;@LifeAsKing: @2...</td>\n    </tr>\n    <tr>\n      <th>25292</th>\n      <td>3</td>\n      <td>0</td>\n      <td>1</td>\n      <td>2</td>\n      <td>2</td>\n      <td>you've gone and broke the wrong heart baby, an...</td>\n    </tr>\n    <tr>\n      <th>25294</th>\n      <td>3</td>\n      <td>0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>1</td>\n      <td>young buck wanna eat!!.. dat nigguh like I ain...</td>\n    </tr>\n    <tr>\n      <th>25295</th>\n      <td>6</td>\n      <td>0</td>\n      <td>6</td>\n      <td>0</td>\n      <td>1</td>\n      <td>youu got wild bitches tellin you lies</td>\n    </tr>\n    <tr>\n      <th>25296</th>\n      <td>3</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>2</td>\n      <td>~~Ruffled | Ntac Eileen Dahlia - Beautiful col...</td>\n    </tr>\n  </tbody>\n</table>\n<p>24783 rows \u00d7 6 columns</p>\n</div>\n      <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-8c6a7709-226d-4af6-ae5e-23e518398cb2')\"\n              title=\"Convert this dataframe to an interactive table.\"\n              style=\"display:none;\">\n\n  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n       width=\"24px\">\n    <path d=\"M0 0h24v24H0V0z\" fill=\"none\"/>\n    <path d=\"M18.56 5.44l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94zm-11 1L8.5 8.5l.94-2.06 2.06-.94-2.06-.94L8.5 2.5l-.94 2.06-2.06.94zm10 10l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94z\"/><path d=\"M17.41 7.96l-1.37-1.37c-.4-.4-.92-.59-1.43-.59-.52 0-1.04.2-1.43.59L10.3 9.45l-7.72 7.72c-.78.78-.78 2.05 0 2.83L4 21.41c.39.39.9.59 1.41.59.51 0 1.02-.2 1.41-.59l7.78-7.78 2.81-2.81c.8-.78.8-2.07 0-2.86zM5.41 20L4 18.59l7.72-7.72 1.47 1.35L5.41 20z\"/>\n  </svg>\n      </button>\n\n  <style>\n    .colab-df-container {\n      display:flex;\n      flex-wrap:wrap;\n      gap: 12px;\n    }\n\n    .colab-df-convert {\n      background-color: #E8F0FE;\n      border: none;\n      border-radius: 50%;\n      cursor: pointer;\n      display: none;\n      fill: #1967D2;\n      height: 32px;\n      padding: 0 0 0 0;\n      width: 32px;\n    }\n\n    .colab-df-convert:hover {\n      background-color: #E2EBFA;\n      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n      fill: #174EA6;\n    }\n\n    [theme=dark] .colab-df-convert {\n      background-color: #3B4455;\n      fill: #D2E3FC;\n    }\n\n    [theme=dark] .colab-df-convert:hover {\n      background-color: #434B5C;\n      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n      fill: #FFFFFF;\n    }\n  </style>\n\n      \n    </div>\n  </div>\n\n\n\n\n\n```python\n# Generate descriptive statistics\ndf.describe()\n```\n\n\n\n\n\n  <div id=\"df-a7bc4a59-d993-4306-b6b2-dc2cef808552\">\n    <div class=\"colab-df-container\">\n      <div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>hate_speech</th>\n      <th>offensive_language</th>\n      <th>neither</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>24783.000000</td>\n      <td>24783.000000</td>\n      <td>24783.000000</td>\n      <td>24783.000000</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>3.243473</td>\n      <td>0.280515</td>\n      <td>2.413711</td>\n      <td>0.549247</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>0.883060</td>\n      <td>0.631851</td>\n      <td>1.399459</td>\n      <td>1.113299</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>3.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>3.000000</td>\n      <td>0.000000</td>\n      <td>2.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>3.000000</td>\n      <td>0.000000</td>\n      <td>3.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>3.000000</td>\n      <td>0.000000</td>\n      <td>3.000000</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>9.000000</td>\n      <td>7.000000</td>\n      <td>9.000000</td>\n      <td>9.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n      <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-a7bc4a59-d993-4306-b6b2-dc2cef808552')\"\n              title=\"Convert this dataframe to an interactive table.\"\n              style=\"display:none;\">\n\n  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n       width=\"24px\">\n    <path d=\"M0 0h24v24H0V0z\" fill=\"none\"/>\n    <path d=\"M18.56 5.44l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94zm-11 1L8.5 8.5l.94-2.06 2.06-.94-2.06-.94L8.5 2.5l-.94 2.06-2.06.94zm10 10l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94z\"/><path d=\"M17.41 7.96l-1.37-1.37c-.4-.4-.92-.59-1.43-.59-.52 0-1.04.2-1.43.59L10.3 9.45l-7.72 7.72c-.78.78-.78 2.05 0 2.83L4 21.41c.39.39.9.59 1.41.59.51 0 1.02-.2 1.41-.59l7.78-7.78 2.81-2.81c.8-.78.8-2.07 0-2.86zM5.41 20L4 18.59l7.72-7.72 1.47 1.35L5.41 20z\"/>\n  </svg>\n      </button>\n\n  <style>\n    .colab-df-container {\n      display:flex;\n      flex-wrap:wrap;\n      gap: 12px;\n    }\n\n    .colab-df-convert {\n      background-color: #E8F0FE;\n      border: none;\n      border-radius: 50%;\n      cursor: pointer;\n      display: none;\n      fill: #1967D2;\n      height: 32px;\n      padding: 0 0 0 0;\n      width: 32px;\n    }\n\n    .colab-df-convert:hover {\n      background-color: #E2EBFA;\n      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n      fill: #174EA6;\n    }\n\n    [theme=dark] .colab-df-convert {\n      background-color: #3B4455;\n      fill: #D2E3FC;\n    }\n\n    [theme=dark] .colab-df-convert:hover {\n      background-color: #434B5C;\n      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n      fill: #FFFFFF;\n    }\n  </style>\n\n      \n    </div>\n  </div>\n\n\n\n\n\n```python\n# Get feature names \ndf.columns\n```\n\n\n\n\n    Index(['count', 'hate_speech', 'offensive_language', 'neither', 'class',\n           'tweet'],\n          dtype='object')\n\n\n\nKey:\n\ncount = number of CrowdFlower users who coded each tweet (at least 3; more users coded a tweet when judgments were determined to be unreliable by CF)\n\n\nhate_speech = number of CF users who coded the tweet as hate speech\n\n\noffensive_language = number of CF users who coded the tweet as offensive but not hate speech\n\n\nneither = number of CF users who coded the tweet as neither offensive nor hate speech\n\n\nclass = class label determined by majority rule:\n\n* 0 : hate speech\n* 1 : offensive  language\n* 2 : neither\n\ntweet = tweet text\n\n\n\n```python\n# Plot distribution of samples across classes\nlabels = df['class']\nbins = ['offensive', 'neither', 'hate speech']\n\ny_pos = np.arange(len(bins))\nvalue_counts = labels.value_counts()\n\nplt.bar(y_pos, value_counts, align='center', color=['g', 'r', '#1f77b4'])\n\nplt.xticks(y_pos, bins)\nplt.xlabel(\"Class Label\")\nplt.ylabel(\"Frequency\")\nplt.title(\"Frequency of Class Labels\")\n\nplt.show()\n```\n\nThe bar chart shows the imbalanced nature of the classification problem; most tweets containing \"hateful\" words, as defined by Hatebase, were coded as offensive by CF coders. More tweets were considered neither hate speech nor offensive than were considered hate speech.\n\n### Data Preprocessing\n\n\n```python\n# Select data for preprocessing and transformation\ntweets=df.tweet\n```\n\n\n```python\n# Create list of stopwords \nnltk.download('stopwords')\nstopwords = nltk.corpus.stopwords.words(\"english\")\nother_exclusions = [\"#ff\", \"ff\", \"rt\"]\nstopwords.extend(other_exclusions)\n```\n\n    [nltk_data] Downloading package stopwords to /root/nltk_data...\n    [nltk_data]   Unzipping corpora/stopwords.zip.\n\n\n\n```python\n# Create reusable stemmer\nstemmer = nltk.stem.porter.PorterStemmer()\n```\n\n\n```python\n# Define functions for preprocessing data\ndef preprocess(text_string):\n    \"\"\"\n    Accepts a text string and replaces:\n    1) urls with URLHERE\n    2) lots of whitespace with one instance\n    3) mentions with MENTIONHERE\n\n    This allows us to get standardized counts of urls and mentions\n    Without caring about specific people mentioned\n    \"\"\"\n    space_pattern = '\\s+'\n    giant_url_regex = ('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|'\n        '[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')\n    mention_regex = '@[\\w\\-]+'\n    parsed_text = re.sub(space_pattern, ' ', text_string)\n    parsed_text = re.sub(giant_url_regex, '', parsed_text)\n    parsed_text = re.sub(mention_regex, '', parsed_text)\n    return parsed_text\n\ndef tokenize(tweet):\n    \"\"\"Removes punctuation & excess whitespace, sets to lowercase,\n    and stems tweets. Returns a list of stemmed tokens.\"\"\"\n    tweet = \" \".join(re.split(\"[^a-zA-Z]*\", tweet.lower())).strip()\n    tokens = [stemmer.stem(t) for t in tweet.split()]\n    return tokens\n\ndef basic_tokenize(tweet):\n    \"\"\"Same as tokenize but without the stemming\"\"\"\n    tweet = \" \".join(re.split(\"[^a-zA-Z.,!?]*\", tweet.lower())).strip()\n    return tweet.split()\n```\n\n### Feature Engineering\n\n####Automatic Feature Extraction\n\n\n\n\n```python\n# Construct tfidf matrix and get relevant scores\nvectorizer = TfidfVectorizer(\n    tokenizer=tokenize,\n    preprocessor=preprocess,\n    ngram_range=(1, 3),\n    stop_words=stopwords,\n    use_idf=True,\n    smooth_idf=False,\n    norm=None,\n    decode_error='replace',\n    max_features=10000,\n    min_df=5,\n    max_df=0.75\n    )\n\ntfidf = vectorizer.fit_transform(tweets).toarray()\nvocab = {v:i for i, v in enumerate(vectorizer.get_feature_names_out())}\nidf_vals = vectorizer.idf_\nidf_dict = {i:idf_vals[i] for i in vocab.values()} #keys are indices; values are IDF scores\n```\n\n    /usr/local/lib/python3.7/dist-packages/sklearn/feature_extraction/text.py:401: UserWarning: Your stop_words may be inconsistent with your preprocessing. Tokenizing the stop words generated tokens ['b', 'c', 'e', 'f', 'g', 'h', 'j', 'l', 'n', 'p', 'r', 'u', 'v', 'w'] not in stop_words.\n      % sorted(inconsistent)\n\n\n\n```python\n# Get POS tags for tweets and save as a string\nnltk.download('averaged_perceptron_tagger')\ntweet_tags = []\nfor t in tweets:\n    tokens = basic_tokenize(preprocess(t))\n    tags = nltk.pos_tag(tokens)\n    tag_list = [x[1] for x in tags]\n    tag_str = \" \".join(tag_list)\n    tweet_tags.append(tag_str)\n```\n\n    [nltk_data] Downloading package averaged_perceptron_tagger to\n    [nltk_data]     /root/nltk_data...\n    [nltk_data]   Unzipping taggers/averaged_perceptron_tagger.zip.\n\n\n\n```python\n# Construct POS TF matrix and get vocab dict\npos_vectorizer = TfidfVectorizer(\n    tokenizer=None,\n    lowercase=False,\n    preprocessor=None,\n    ngram_range=(1, 3),\n    stop_words=None,\n    use_idf=False,\n    smooth_idf=False,\n    norm=None,\n    decode_error='replace',\n    max_features=5000,\n    min_df=5,\n    max_df=0.75,\n    )\n\npos = pos_vectorizer.fit_transform(pd.Series(tweet_tags)).toarray()\npos_vocab = {v:i for i, v in enumerate(pos_vectorizer.get_feature_names_out())}\n```\n\n#### Manual Feature Construction\n\n\n```python\n# Create reusable sentiment analyzer\nsentiment_analyzer = VS()\n```\n\n\n```python\n# Define functions for devising features\ndef count_twitter_objs(text_string):\n    \"\"\"\n    Accepts a text string and replaces:\n    1) urls with URLHERE\n    2) lots of whitespace with one instance\n    3) mentions with MENTIONHERE\n    4) hashtags with HASHTAGHERE\n\n    This allows us to get standardized counts of urls and mentions\n    Without caring about specific people mentioned.\n    \n    Returns counts of urls, mentions, and hashtags.\n    \"\"\"\n    space_pattern = '\\s+'\n    giant_url_regex = ('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|'\n        '[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')\n    mention_regex = '@[\\w\\-]+'\n    hashtag_regex = '#[\\w\\-]+'\n    parsed_text = re.sub(space_pattern, ' ', text_string)\n    parsed_text = re.sub(giant_url_regex, 'URLHERE', parsed_text)\n    parsed_text = re.sub(mention_regex, 'MENTIONHERE', parsed_text)\n    parsed_text = re.sub(hashtag_regex, 'HASHTAGHERE', parsed_text)\n    return(parsed_text.count('URLHERE'),parsed_text.count('MENTIONHERE'),parsed_text.count('HASHTAGHERE'))\n\ndef other_features(tweet):\n    \"\"\"This function takes a string and returns a list of features.\n    These include Sentiment scores, Text and Readability scores,\n    as well as Twitter specific features\"\"\"\n    sentiment = sentiment_analyzer.polarity_scores(tweet)\n    \n    words = preprocess(tweet) # Get text only\n    \n    syllables = textstat.syllable_count(words)\n    num_chars = sum(len(w) for w in words)\n    num_chars_total = len(tweet)\n    num_terms = len(tweet.split())\n    num_words = len(words.split())\n    avg_syl = round(float((syllables+0.001))/float(num_words+0.001),4)\n    num_unique_terms = len(set(words.split()))\n    \n    # Modified FK grade, where avg words per sentence is just num words/1\n    FKRA = round(float(0.39 * float(num_words)/1.0) + float(11.8 * avg_syl) - 15.59,1)\n    # Modified FRE score, where sentence fixed to 1\n    FRE = round(206.835 - 1.015*(float(num_words)/1.0) - (84.6*float(avg_syl)),2)\n    \n    twitter_objs = count_twitter_objs(tweet)\n    retweet = 0\n    if \"rt\" in words:\n        retweet = 1\n    features = [FKRA, FRE,syllables, avg_syl, num_chars, num_chars_total, num_terms, num_words,\n                num_unique_terms, sentiment['neg'], sentiment['pos'], sentiment['neu'], sentiment['compound'],\n                twitter_objs[2], twitter_objs[1],\n                twitter_objs[0], retweet]\n    return features\n\ndef get_feature_array(tweets):\n    feats=[]\n    for t in tweets:\n        feats.append(other_features(t))\n    return np.array(feats)\n```\n\n\n```python\n# Construct features\nother_feats = get_feature_array(tweets)\n```\n\n### Feature Selection\n\n\n```python\n# Join automatically extracted features and manually constructed features together\nX = np.concatenate([tfidf,pos,other_feats],axis=1)\n```\n\n\n```python\n# Get dimensions of the data\nX.shape\n```\n\n\n\n\n    (24783, 4023)\n\n\n\nThe data is high dimensional. There is an exponential decrease in predictive power for each additional variable in a multivariate model, known as the curse of dimensionality. Therefore, the dimensionality of the data should be reduced.\n\n### Model Training\n\n\n```python\n# Encode class labels\ny = df['class'].astype(int)\n```\n\n\n```python\n# Reduce dimensionality of data. Specify solver as 'liblinear' because default solver changed to 'lbfgs' in 0.22.\nfeature_transformer = SelectFromModel(LogisticRegression(class_weight='balanced',penalty=\"l1\", C=0.01, solver='liblinear'))\n\nX_ = feature_transformer.fit_transform(X,y)\n```\n\n\n```python\n# Get reduced dimensions of the data\nX_.shape\n```\n\n\n\n\n    (24783, 465)\n\n\n\n\n```python\n# Generate train/test split of 9/1. Initialise with random seed for reproducability.\nX_train, X_test, y_train, y_test = train_test_split(X_, y, random_state=42, test_size=0.1, stratify=y)\n```\n\nAs classification problem is imbalanced, it's desirable for the train/test split to preserve the same proportions of examples in each class as observed in the original dataset [(Brownlee, 2020)](https://machinelearningmastery.com/train-test-split-for-evaluating-machine-learning-algorithms//).\n\n\n```python\n# Create model. Change hyperparameters to ensure control variables remain constant. Change solver to the new default solver, lbfgs.\n# Increase `max_iter` as lbfgs takes longer to converge. Change framework used for multi class classification to multinomial.\n# See comments in `start_flower_client` for details.\nclassifier = LogisticRegression(class_weight='balanced',penalty='l2', C=0.01, max_iter=20000, multi_class=\"multinomial\")\n```\n\n\n```python\n# Train model\nmodel = classifier.fit(X_train, y_train)\n```\n\n### Model Testing\n\n\n```python\n# Test model\ny_preds = model.predict(X_test)\n```\n\n\n```python\n# Generate test report\nreport = classification_report(y_test, y_preds)\nprint(report.rsplit(\"\\n\",2)[0])\n```\n\n                  precision    recall  f1-score   support\n    \n               0       0.24      0.69      0.36       143\n               1       0.96      0.74      0.84      1920\n               2       0.61      0.86      0.72       416\n    \n        accuracy                           0.76      2479\n       macro avg       0.61      0.77      0.64      2479\n\n\nThere is a class-imbalance in the dataset; the hate speech class (0) and neither class (2) are most important to get right, and they are under-represented. Offensive language class (1) is over-represented. Therefore, macro average is preferable over weighted average, which is misleading [(Khalusova, 2021)](https://www.mariakhalusova.com/posts/2019-04-17-ml-model-evaluation-metrics-p2/#micro--macro--weighted-averaged-precision).\n\nF1-score is used rather than AUROC because AUROC averages over all possible discrimination thresholds, which is misleading in the case of class-imbalanced data [(2018, Almardeny)](https://stackoverflow.com/questions/44172162/f1-score-vs-roc-auc). In contrast, F-1 score maintains a balance between Precision and Recall.\n\n\n```python\n# Define function for plotting confusion matrix\ndef plot_confusion_matrix(y, y_preds):\n\n  matrix = confusion_matrix(y,y_preds)\n  matrix_proportions = np.zeros((3,3))\n  for i in range(0,3):\n    matrix_proportions[i,:] = matrix[i,:]/float(matrix[i,:].sum())\n  names=['Hate','Offensive','Neither']\n  confusion_df = pd.DataFrame(matrix_proportions, index=names,columns=names)\n  plt.figure(figsize=(5,5))\n  seaborn.heatmap(confusion_df,annot=True,annot_kws={\"size\": 12},cmap='gist_gray_r',cbar=False, square=True,fmt='.2f')\n  plt.ylabel(r'True categories',fontsize=14)\n  plt.xlabel(r'Predicted categories',fontsize=14)\n  plt.tick_params(labelsize=12)\n```\n\n\n```python\n# Plot confusion matrix\nplot_confusion_matrix(y_test,y_preds)\n```\n\n\n```python\n# Plot distribution of estimates. Set the density parameter to True to normalize bin heights so that the integral of the histogram is 1.\n# The resulting histogram is an approximation of the probability density function. This facilitates comparison between the distribution \n# of estimates and true distribution.\nplt.hist(y_preds, density=True)\nplt.show()\n```\n\n\n```python\n# Plot true distribution\nplt.hist(y, density=True)\nplt.show()\n```\n\n# Design of Single-Machine Simulation of Federated Learning System\n\nWe use a controlled environment that is suitable for experiments. We assume\na synchronous update scheme that proceeds in rounds of\ncommunication. There is a fixed set of $K$ clients, each\nwith a fixed local dataset. At the beginning of each round, the server\nsends the current global model parameters to selected clients. Each selected client then trains its model on its local dataset, and sends an\nupdate to the server. The server aggregates these updates and applies them\nto the global model, and the cycle repeats [(McMahan et al., 2017)](https://arxiv.org/pdf/1602.05629.pdf). In our simulation, of cross-silo FL, all clients are selected for each round of federated learning.\n\n## Federated Evaluation\n\nThere are two main approaches to evaluate models in a federated learning system: centralized evaluation and federated evaluation. In centralized evaluation, the aggregated model is validated on the server-side, and the validation set is sampled from the population's probability distribution. In federated evaluation, the aggregated model is validated on the client-side, and the validation set is sampled from the same probability distribution as the client's training set [(Adap GmbH, 2022)](https://flower.dev/docs/evaluation.html).\n\nWe focus on federated evaluation as it's typically used in real-world applications.\n\n\n```python\n# Initialize global experiment config\nDATA_PARTITIONING_STRATEGY = \"\"\nDATA_PARTITIONING_RANDOM_SEED = 0\nDIRICHLET_DISTRIBUTION_PARAM = 10\nNUMBER_OF_CLIENTS = 10\nMIN_AVAILABLE_CLIENTS = NUMBER_OF_CLIENTS\nNUMBER_OF_FL_ROUNDS = 50\nLOCAL_EPOCHS = ceil(1500 / NUMBER_OF_FL_ROUNDS)\nMIN_FIT_CLIENTS = NUMBER_OF_CLIENTS\nFRACTION_FIT = 1.0\nFRACTION_FIT_RANDOM_SEED = 1\nMIN_EVAL_CLIENTS = NUMBER_OF_CLIENTS\nFRACTION_EVAL = 1.0\nEVAL_STRATEGY = \"federated\"\nDATA_SHARING = False\nNUMBER_OF_OBSERVATIONS_SELECTED_WITH_DATA_PARTITIONING_STRATEGY = 10\nNUMBER_OF_VALIDATION_FOLDS = 10\nNUMBER_OF_REPEATS = NUMBER_OF_OBSERVATIONS_SELECTED_WITH_DATA_PARTITIONING_STRATEGY * NUMBER_OF_VALIDATION_FOLDS\nLOG_DIR = \"\"\n```\n\nKey:\n\nDATA_PARTITIONING_STRATEGY - strategy for distributing samples across clients\n\nDATA_PARTITIONING_RANDOM_SEED - seed to initialize random data partition generator, set for experimental control and reproducability\n\nDIRICHLET_DISTRIBUTION_PARAM - distribution parameter of the Dirichlet distribution, used in particular data partitioning strategies to control degree of imbalance\n\nNUMBER_OF_CLIENTS - total number of clients participating in the FL\n\nMIN_AVAILABLE_CLIENTS - minimum number of clients that must be connected to the server before FL can begin\n\nNUMBER_OF_FL_ROUNDS - number of FL rounds, set to a sufficiently large number so that the performance of the FL system can be observed\n\nLOCAL_EPOCHS - number of complete passes over local training data performed by clients during a training round, limited by the maximum number of iterations taken for the solvers to converge and the number of FL rounds, so that the performance of the FL system can be observed\n\nMIN_FIT_CLIENTS - minimum number of clients used during training\n\nFRACTION_FIT - fraction of random clients selected to participate in a training round\n\nFRACTION_FIT_RANDOM_SEED - seed for initializing the random sampling used to select clients for participation in a training round, set for experimental control and reproducability\n\nMIN_EVAL_CLIENTS - minimum number of clients used during evaluation\n\nFRACTION_EVAL - fraction of random clients selected to participate in an evaluation round\n\nEVAL_STRATEGY - there are two main approaches to evaluate models in federated learning systems: centralized (server-side) evaluation and federated (client-side) evaluation\n\nDATA_SHARING - whether or not to use a data-sharing strategy [(Zhao et al., 2018)](https://arxiv.org/pdf/1806.00582.pdf) to improve training on non-IID data\n\nNUMBER_OF_OBSERVATIONS_SELECTED_WITH_DATA_PARTITIONING_STRATEGY - number of observations drawn using each data partitioning strategy\n\nNUMBER_OF_VALIDATION_FOLDS - number of folds used in cross-validation\n\nNUMBER_OF_REPEATS - total number of experiment repeats\n\nLOG_DIR - folder in which to log experiments\n\n## Utility Functions\n\n\n```python\nLogRegParams = Tuple[np.ndarray, np.ndarray]\n\ndef get_model_parameters(model: LogisticRegression) -> LogRegParams:\n#Returns the paramters of a sklearn LogisticRegression model.\n    params = (model.coef_, model.intercept_)\n    return params\n\n\ndef set_model_params(model: LogisticRegression, params: LogRegParams) -> LogisticRegression:\n#Sets the parameters of a sklean LogisticRegression model.\n    model.coef_ = params[0]\n    model.intercept_ = params[1]\n    return model\n\n\ndef set_initial_params(model: LogisticRegression):\n#Sets initial parameters as zeros Required since model params are\n#uninitialized until model.fit is called.\n#But server asks for initial parameters from clients at launch. Refer\n#to sklearn.linear_model.LogisticRegression documentation for more\n#information.\n\n    if DATA_SHARING:\n      model.classes_ = warm_up_model.classes_\n      model.coef_ = warm_up_model.coef_\n      model.intercept_ = warm_up_model.intercept_\n    else:\n      n_classes = 3\n      n_features = X_.shape[1]  # Number of features in dataset after feature selection by transformer\n\n      model.classes_ = np.array([i for i in range(n_classes)])\n      model.coef_ = np.zeros((n_classes, n_features))\n      model.intercept_ = np.zeros((n_classes,))\n\ndef get_partitions(x, y):\n\n    '''\n    Adapted from:\n\n    Title: NIID-Bench\n    Authors: Li et al.\n    Date: Nov 17, 2021\n    Availability: https://github.com/Xtra-Computing/NIID-Bench/blob/main/utils.py\n\n    '''\n\n    np.random.seed(DATA_PARTITIONING_RANDOM_SEED)\n\n    n_train = y.shape[0]\n\n    if DATA_PARTITIONING_STRATEGY == \"iid\":\n        idxs = np.random.permutation(n_train)\n        batch_idxs = np.array_split(idxs, NUMBER_OF_CLIENTS)\n        net_dataidx_map = {i: batch_idxs[i] for i in range(NUMBER_OF_CLIENTS)}\n    elif DATA_PARTITIONING_STRATEGY == \"noniid-distribution-based-label-imbalance\":\n        min_size = 0\n        min_require_size = 10\n        K = 3\n        N = y.shape[0]\n        net_dataidx_map = {}\n\n        while min_size < min_require_size:\n            idx_batch = [[] for _ in range(NUMBER_OF_CLIENTS)]\n\n            for k in range(K):\n                idx_k = np.where(y == k)[0]\n                np.random.shuffle(idx_k)\n                proportions = np.random.dirichlet(np.repeat(DIRICHLET_DISTRIBUTION_PARAM, NUMBER_OF_CLIENTS))\n                proportions = np.array([p * (len(idx_j) < N / NUMBER_OF_CLIENTS) for p, idx_j in zip(proportions, idx_batch)])\n                proportions = proportions / proportions.sum()\n                proportions = (np.cumsum(proportions) * len(idx_k)).astype(int)[:-1]\n                idx_batch = [idx_j + idx.tolist() for idx_j, idx in zip(idx_batch, np.split(idx_k, proportions))]\n                min_size = min([len(idx_j) for idx_j in idx_batch])\n\n        for j in range(NUMBER_OF_CLIENTS):\n            np.random.shuffle(idx_batch[j])\n            net_dataidx_map[j] = idx_batch[j]\n    elif DATA_PARTITIONING_STRATEGY == \"noniid-quantity-based-label-imbalance-1\" or DATA_PARTITIONING_STRATEGY == \"noniid-quantity-based-label-imbalance-2\":\n        num = int(DATA_PARTITIONING_STRATEGY[38]) # number of distinct labels per client\n        K = 3 # total number of labels\n        times = [0 for _ in range(K)] # holds the number of parties to which each label ID is assigned\n        contain = [[] for _ in range(NUMBER_OF_CLIENTS)] # holds the buckets of num label IDs assigned to each party\n\n        for i in range(K): # ensure each label ID is assigned\n            bucket = contain[np.random.randint(NUMBER_OF_CLIENTS)]\n            while len(bucket) == num:\n                bucket = contain[np.random.randint(NUMBER_OF_CLIENTS)]\n            bucket.append(i)\n            times[i] += 1\n\n        for bucket in contain: # randomly assign num different distinct label IDs to each party\n            j = len(bucket)\n            while j < num:\n                ind = np.random.randint(K)\n                if ind not in bucket:\n                    bucket.append(ind)\n                    times[ind] += 1\n                    j += 1\n\n        net_dataidx_map ={i: np.ndarray(0, dtype=np.int64) for i in range(NUMBER_OF_CLIENTS)}\n\n        # For the samples of each label, randomly and equally divide them into the parties\n        # which own the label, such that there is no overlap between the samples of different parties\n        for i in range(K):\n            idx_k = np.where(y == i)[0]\n            np.random.shuffle(idx_k)\n            split = np.array_split(idx_k,times[i])\n            ids = 0\n            for j in range(NUMBER_OF_CLIENTS):\n                if i in contain[j]:\n                    net_dataidx_map[j]=np.append(net_dataidx_map[j],split[ids])\n                    ids += 1\n\n    elif DATA_PARTITIONING_STRATEGY == \"iid-quantity-skew\":\n        idxs = np.random.permutation(n_train)\n        min_size = 0\n        while min_size < 10:\n            proportions = np.random.dirichlet(np.repeat(DIRICHLET_DISTRIBUTION_PARAM, NUMBER_OF_CLIENTS))\n            proportions = proportions/proportions.sum()\n            min_size = np.min(proportions*len(idxs))\n        proportions = (np.cumsum(proportions)*len(idxs)).astype(int)[:-1]\n        batch_idxs = np.split(idxs, proportions)\n        net_dataidx_map = {i: batch_idxs[i] for i in range(NUMBER_OF_CLIENTS)}\n\n    partitioned_train_set = [(x[net_dataidx_map[idx]], pd.Series(y[net_dataidx_map[idx]])) for idx in range(NUMBER_OF_CLIENTS)]\n\n    return partitioned_train_set\n\n\ndef get_train_partitions(x_train, y_train):\n  partitioned_train_set = []\n  \n  if DATA_SHARING:\n    partitioned_train_set = get_partitions(X_train_client, y_train_client.to_numpy())\n    # a random \u03b1 portion of G is merged with the data of each client\n    partitioned_train_set = [(np.concatenate((X_train_partition, X_train_shared)), pd.concat((y_train_partition, y_train_shared))) for X_train_partition, y_train_partition in partitioned_train_set]\n  else:\n    partitioned_train_set = get_partitions(x_train, y_train)\n\n  return partitioned_train_set\n\n\ndef get_test_partitions(x_test, y_test, partitioned_train_set):\n  partitioned_test_set = []\n\n  if DATA_PARTITIONING_STRATEGY == \"noniid-distribution-based-label-imbalance\" or DATA_PARTITIONING_STRATEGY == \"iid-quantity-skew\":\n    # Grody estimate of distribution\n\n    np.random.seed(DATA_PARTITIONING_RANDOM_SEED)\n    \n    net_dataidx_map = {i: np.ndarray(0, dtype=np.int64) for i in range(NUMBER_OF_CLIENTS)}\n\n    total_label_freqs = 0\n\n    if DATA_SHARING:\n      total_label_freqs = y_train_client.value_counts()\n    else:\n      total_label_freqs = y_train.value_counts()\n\n    for i in range(3):\n      idx_i = np.where(y_test == i)[0]\n      np.random.shuffle(idx_i)\n\n      indices = []\n\n      offset = 0\n\n      for j in range(NUMBER_OF_CLIENTS - 1):\n        partition_label_proportion = partitioned_train_set[j][1].value_counts().reindex(range(3), fill_value=0)[i] / total_label_freqs[i]\n        partition_label_freq = int(len(idx_i )*partition_label_proportion)\n        split_index = offset + partition_label_freq\n        indices.append(split_index)\n        offset = split_index\n      \n      split = np.array_split(idx_i, indices)\n\n      for j in range(NUMBER_OF_CLIENTS):\n        net_dataidx_map[j]=np.append(net_dataidx_map[j],split[j])\n\n    partitioned_test_set = [(x_test[net_dataidx_map[idx]], pd.Series(y_test[net_dataidx_map[idx]])) for idx in range(NUMBER_OF_CLIENTS)]\n  else:\n    partitioned_test_set = get_partitions(x_test, y_test)\n\n  return partitioned_test_set\n```\n\n## Server Functions\n\n\n```python\ndef fit_round(rnd: int) -> Dict:\n  \"\"\"Send fit round number to client.\"\"\"\n\n  return {\"rnd\": rnd}\n\ndef evaluate_round(rnd: int) -> Dict:\n  \"\"\"Send evaluate round number to client.\"\"\"\n\n  return {\"rnd\": rnd}\n\n# get_eval_fn is a closure factory function that creates a closure consisting of the inner function evaluate together with its enclosing environment.\n# The closure can modify the mutable objects aka dynamic enclosing state, such as model, within its enclosing state\ndef get_eval_fn(model: LogisticRegression, y_preds: ListProxy, test_accs: ListProxy):\n    \"\"\"Return an evaluation function for server-side evaluation.\"\"\"\n\n    # The `evaluate` function will be called after every training round.\n    def evaluate(parameters: fl.common.Weights):\n        # print(\"Beginning centralized evaluation...\")\n        # print(\"Updating global model with the latest parameters...\")\n        # Update model with the latest parameters\n        set_model_params(model, parameters)\n        # print(\"Predicting class labels for samples in X_test...\")\n        # Predict class labels for samples in X_test\n        predictions = model.predict(X_test)\n        y_preds.append(predictions)\n        # Calculate probability estimates\n        # print(\"Calculating probability estimates...\")\n        prob_estimates = model.predict_proba(X_test)\n        # Calculate cross-entropy loss\n        # print(\"Calculating cross-entropy loss...\")\n        loss = log_loss(y_test, prob_estimates)\n        # print(\"Calculating the mean accuracy on the test data and labels...\")\n        # Calculate the mean accuracy on the test data and labels.\n        accuracy = model.score(X_test, y_test)\n        test_accs.append(accuracy)\n        # print(\"Finished centralized evaluation.\")\n        return loss, {\"accuracy\": accuracy}\n        \n    return evaluate\n```\n\n\n```python\ndef my_aggregate(results: List[Tuple[Weights, int]]) -> Weights:\n    \"\"\"Compute weighted average.\"\"\"\n    # Calculate the total number of examples used during training\n    num_examples_total = sum([num_examples for _, num_examples in results])\n\n    # print(\"Parameters received from each client:\")\n    # for parameters, num_examples in results:\n      # print(f\"Num_examples: {num_examples}\")\n      # print(f\"Shape of coeffs: {parameters[0].shape}\")  \n      # print(f\"Coeffs: {parameters[0]}\")\n      # print(f\"Shape of biases: {parameters[1].shape}\")  \n      # print(f\"Biases: {parameters[1]}\") \n\n    # Create a list of weights, each multiplied by the related number of examples\n    weighted_parameters = [\n        [parameter * num_examples for parameter in parameters] for parameters, num_examples in results\n    ]\n\n    # print(f\"Weighted parameters: {weighted_parameters}\")\n\n    # print(f\"Zipped weighted parameters: {list(zip(*weighted_parameters))}\")\n\n    # Compute average parameters\n    weights_prime = [\n        reduce(np.add, layer_updates) / num_examples_total\n        for layer_updates in zip(*weighted_parameters)\n    ]\n\n    return weights_prime\n```\n\n\n```python\ndef start_flower_server(y_preds: ListProxy, test_accs: ListProxy):\n  \n  if EVAL_STRATEGY == \"centralized\":\n    model = LogisticRegression()\n    set_initial_params(model)\n\n# Sample fraction of available clients for the next round\n# Minimum number of clients to be sampled for the next round\n# Minimum number of clients that need to be connected to the server before a round of federated learning can start. If few clients \n# are connected then the server will wait until more connect before sampling clients\n# There are two main approaches to evaluate models in flower, centralized (server-side) evaluation and federated (client-side) evaluation.\n# Centralized and federated evaluation are mutually exclusive.\n# All built-in strategies support centalized evaluation by providing an evaluation function during \n# initialization. An evaluation function is any function that can take the current global model parameters as input \n# and return evaluation results. The current server implementation calls eval_fn AFTER parameter aggregation  \n# (training round).\n# Customizing the existing FedAvg strategy with the callback function fit_round, bound to eval_fn, to pass variable \n# configuration values to the client each training round. The provided function will be called by the strategy \n# and must return a dictionary of arbitrary configuration key-value pairs that will be sent to the client \n# (received in its own client.fit function).\n\n  class MyClientManager(fl.server.SimpleClientManager):\n    def __init__(self) -> None:\n      super().__init__()\n      random.seed(FRACTION_FIT_RANDOM_SEED)\n\n  client_manager = MyClientManager()\n\n  class MyStrategy(fl.server.strategy.FedAvg):\n    def aggregate_fit(self, rnd: int, results: List[Tuple[ClientProxy, FitRes]], failures: List[BaseException]) -> Tuple[Optional[Parameters], Dict[str, Scalar]]:\n        \"\"\"Aggregate fit results using weighted average.\"\"\"\n        if not results:\n            return None, {}\n\n        # Do not aggregate if there are failures and failures are not accepted\n        if not self.accept_failures and failures:\n            return None, {}\n\n        for i in range(len(results)):\n          client, fit_res = results[i]\n\n        # Convert results\n        weights_results = [(parameters_to_weights(fit_res.parameters), fit_res.num_examples)\n            for client, fit_res in results\n        ]\n\n        average_weights = my_aggregate(weights_results)\n\n        # print(f\"Average parameters after aggregation: {average_weights}, number of coeffs: {average_weights[0].shape}, number of biases: {average_weights[1].shape}\")\n        \n        return weights_to_parameters(average_weights), {}\n\n  strategy = MyStrategy()     \n\n  # strategy = fl.server.strategy.FedAvg()\n\n  strategy.min_available_clients = MIN_AVAILABLE_CLIENTS\n  strategy.fraction_fit = FRACTION_FIT\n  strategy.min_fit_clients = MIN_FIT_CLIENTS          \n  strategy.on_fit_config_fn = fit_round\n  strategy.fraction_eval = FRACTION_EVAL\n  strategy.min_eval_clients = MIN_EVAL_CLIENTS\n\n  if (EVAL_STRATEGY == \"federated\"):\n    strategy.on_evaluate_config_fn = evaluate_round\n  else:\n    strategy.eval_fn = get_eval_fn(model, y_preds, test_accs)\n  \n  server = fl.server.Server(client_manager=client_manager, strategy=strategy)\n  \n  fl.server.start_server(\"0.0.0.0:80\", server=server, config={\"num_rounds\": NUMBER_OF_FL_ROUNDS})\n```\n\n## Client Functions\n\n\n```python\ndef start_flower_client(X_train: np.ndarray, y_train: np.ndarray, X_test: np.ndarray, y_test: np.ndarray, id: str, y_preds: ListProxy, test_accs: ListProxy):\n  pid = os.getpid()\n  print(f\"initializing Client{id} with pid {pid}\")\n\n  # Create LogisticRegression Model\n  # max_iter: way to limit the number of epochs. One epoch means that each sample in the training dataset has had an opportunity \n  # to update the internal model parameters. The solver iterates until convergence (determined by \u2018tol\u2019) or this number of iterations.\n  # i.e., the learning will be stopped either when the solver iterates max_iter times or when the cost between two iterations changes less than tol, \n  # whichever comes first. From sklearn.linear_model.LogisticRegression documentation we can see that \u2018tol\u2019 is 0.0001 by default.\n  # warm_start: prevent refreshing weights when fitting, this is required for federated learning\n  # As a result of the fact that warm_start is required, the variable solver must be changed because liblinear does not support warm start\n  # Framework used for multi class classification is multinomial. \n  # This is necessary because of the non-iid data in federated learning scenarios; in a multinomial framework, learning \ud835\udefd\ud835\udc56 for a particular class i\n  # immediately affects our model for other classes j, through the joint model. Consequently, The training algorithm uses log loss aka cross-entropy loss\n  model = LogisticRegression(penalty='l2', max_iter=LOCAL_EPOCHS, warm_start=True, class_weight='balanced', C=0.01)\n\n  # Setting initial model parameters\n  set_initial_params(model)\n\n  # Define Flower client\n  class MyClient(fl.client.NumPyClient):\n    def get_parameters(self): # -> List[numpy.ndarray]\n      return get_model_parameters(model)\n\n    # Training happens in fit method and can be configured from the server side. \n    # Model parameters can also be evaluated during training. Client.fit can return arbitrary evaluation results as a dictionary\n    def fit(self, parameters, config):\n      # print(f\"Client{id} with pid {pid} is sampled in training rnd {config['rnd']}\")\n      set_model_params(model, parameters)\n      # Ignore convergence failure due to low local epochs\n      with warnings.catch_warnings():\n          warnings.simplefilter(\"ignore\")\n          model.fit(X_train, y_train)\n      # print(f\"Training finished for round {config['rnd']}\")\n      # print(f\"Model params is a 2 tuple, first element contains coefficients/weights, second element contains intercept\")\n      # print(f\"Number of coefficients/weights: {get_model_parameters(model)[0].shape}\")\n      # print(f\"Model params: {get_model_parameters(model)}\")\n      return get_model_parameters(model), len(X_train), {}\n\n    # Federated evaluation happens in the evaluate method and can be configured from the server side.\n    def evaluate(self, parameters, config): \n      # print(f\"Client{id} with pid {pid} is sampled in evaluation rnd {config['rnd']}\")\n      \n      # Update model with the latest parameters\n      set_model_params(model, parameters)\n\n      # Remind model of classes in the population\n      model.classes_ = np.array([0, 1, 2])\n      \n      # Predict class labels for samples in X_test\n      predictions = model.predict(X_test)\n\n      y_preds.append(predictions)\n      \n      # Calculate probability estimates\n      prob_estimates = model.predict_proba(X_test)\n\n      # Calculate cross-entropy loss\n      loss = log_loss(y_test, prob_estimates, labels=[0,1,2])\n\n      # Calculate the mean accuracy on the test data and labels.\n      accuracy = model.score(X_test, y_test)\n      test_accs.append(accuracy)\n\n      return loss, len(X_test), {\"accuracy\": accuracy}\n\n  client = MyClient()\n\n  # Start Flower client\n  fl.client.start_numpy_client(\"0.0.0.0:80\", client=client)\n```\n\n# Test Bench\n\n## Test Bench Functions\n\n\n```python\n# Define function for getting a time stamp\ndef get_time_stamp():\n  return datetime.today().strftime('%d_%m_%Y__%H_%M_%S')\n```\n\n\n```python\ndef evaluate_local_models(partitioned_train_set, partitioned_test_set):\n  local_models_y_preds = []\n\n  for i in range(NUMBER_OF_CLIENTS):\n    (X_train_partition, y_train_partition) = partitioned_train_set[i]\n    model = classifier.fit(X_train_partition, y_train_partition)\n\n    (X_test_partition, y_test_partition) = partitioned_test_set[i]\n    y_preds = model.predict(X_test_partition)\n    local_models_y_preds.append(y_preds)\n\n  return local_models_y_preds\n```\n\n\n```python\n# Define function for running simulation with global config\ndef run_sim(partitioned_train_set, partitioned_test_set=None):\n  with Manager() as manager:\n    # Holds all child processes\n    processes = []\n\n    # List proxy for gathering class labels predicted during centralized evaluation\n    centralized_y_preds = manager.list()\n\n    # List proxy for gathering test accuracies from centralized evaluation\n    centralized_test_accs = manager.list()\n\n    # Holds all the list proxies for gathering class labels predicted during federated evaluation\n    federated_y_preds = []\n\n    # Holds all the list proxies for gathering test accuracies from federated evaluation\n    federated_test_accs = []\n\n    # Start Flower server\n    server_process = Process(target=start_flower_server, args=(centralized_y_preds, centralized_test_accs))\n    server_process.start()\n    processes.append(server_process)\n\n    # Block the script here for a second or two so the server has time to start\n    time.sleep(2)\n\n    # Start Flower clients\n    if EVAL_STRATEGY == \"centralized\":\n      for i in range(NUMBER_OF_CLIENTS):\n        y_preds = manager.list()\n        test_accs = manager.list()\n        (X_train_partition, y_train_partition) = partitioned_train_set[i]\n        client_process = Process(target=start_flower_client, args=(X_train_partition, y_train_partition, X_test, y_test, str(i), y_preds, test_accs))\n        client_process.start()\n\n        federated_y_preds.append(y_preds)\n        federated_test_accs.append(test_accs)\n        processes.append(client_process)\n\n        # Block the script here for a second to ensure clients register with server in-order (helps control fraction fit variable)\n        time.sleep(1)\n    else:\n      for i in range(NUMBER_OF_CLIENTS):\n        y_preds = manager.list()\n        test_accs = manager.list()\n        (X_train_partition, y_train_partition) = partitioned_train_set[i]\n        \n        (X_test_partition, y_test_partition) = partitioned_test_set[i]\n\n        client_process = Process(target=start_flower_client, args=(X_train_partition, y_train_partition, X_test_partition, y_test_partition, str(i), y_preds, test_accs))\n        client_process.start()\n\n        federated_y_preds.append(y_preds)\n        federated_test_accs.append(test_accs)\n        processes.append(client_process)\n\n        # Block the script here for a second to ensure clients register with server in-order (helps control fraction fit variable)\n        time.sleep(1)\n\n    # Wait for processes to finish\n    for p in processes:\n      p.join()\n\n    # Dereference proxies and return results\n    return {\"centralized_y_preds\": centralized_y_preds[:], \"centralized_test_accs\": centralized_test_accs[:], \n            \"federated_y_preds\": [y_preds[:] for y_preds in federated_y_preds], \"federated_test_accs\": [test_accs[:] for test_accs in federated_test_accs]}\n```\n\n\n```python\ndef get_label_freqs(partitioned_train_set, relative=False):\n  label_freqs = [y_train.value_counts(normalize=relative).rename(\"y_train\")]\n  \n  for i in range(NUMBER_OF_CLIENTS):\n    label_freqs.append(partitioned_train_set[i][1].value_counts(normalize=relative).rename(\"client\" + str(i)))\n\n  label_freqs_table = pd.concat(label_freqs, axis=1).fillna(0)\n\n  if relative:\n    return label_freqs_table.astype(\"float64\")\n  else:\n    return label_freqs_table.astype(\"int64\")\n\n\ndef plot_distribution_of_labels(partitioned_train_set, filepath=None):\n  # Resize figure\n  plt.figure(figsize=(rcParams[\"figure.figsize\"][0]*1.4, rcParams[\"figure.figsize\"][1]))\n\n  number_of_label_across_partitions = pd.concat([partitioned_train_set[i][1].value_counts().sort_index() for i in range(NUMBER_OF_CLIENTS)], axis=1).fillna(0).astype(\"int64\").to_numpy()\n\n  max_number_of_labels = max([len(partitioned_train_set[i][1]) for i in range(NUMBER_OF_CLIENTS)])\n  \n  labs = [str(i) for i in range(NUMBER_OF_CLIENTS)]\n\n  plt.barh(labs, number_of_label_across_partitions[0])\n  plt.barh(labs, number_of_label_across_partitions[1], left=number_of_label_across_partitions[0], color='g')\n  plt.barh(labs, number_of_label_across_partitions[2], left=number_of_label_across_partitions[0]+number_of_label_across_partitions[1], color='r')\n\n  plt.title(\"Distribution of Labels\")\n  plt.xlabel(\"Number of Local Data Samples\")\n  plt.ylabel(\"Client ID\")\n\n  labelIDs=['hate speech','offensive','neither']\n\n  plt.legend(labelIDs)\n\n  plt.xlim([0, max_number_of_labels + 300])\n  \n  if filepath:\n    plt.ioff()\n    plt.savefig(filepath, bbox_inches='tight')\n    plt.close()\n  else:\n    plt.show()\n\n\ndef plot_performance_of_local_models(precision_recall_fscores_of_local_models, precision_recall_fscores_of_global_model, classification_metric, filepath=None):\n  classification_metrics = {'Precision': 0, 'Recall': 1, 'F1-score': 2}\n\n  labs = [str(i) for i in range(NUMBER_OF_CLIENTS)]\n\n  scaling_parameter = 5.5\n  x = np.arange(0, scaling_parameter*len(labs), scaling_parameter)  # the label locations\n  width = 2.2  # the width of the bars\n\n  fig, ax = plt.subplots(figsize=(rcParams[\"figure.figsize\"][0]*1.8, rcParams[\"figure.figsize\"][1] * 1.5))\n  rects1 = ax.bar(x - width/2, precision_recall_fscores_of_local_models[classification_metrics[classification_metric]], width, label='Local Model')\n  rects2 = ax.bar(x + width/2, precision_recall_fscores_of_global_model[classification_metrics[classification_metric]], width, label='Global Model')\n\n  # Add some text for labels, title and custom x-axis tick labels, etc.\n  ax.set_ylabel(classification_metric)\n  ax.set_xlabel('Client ID')\n  ax.set_title(classification_metric + ' of Local Models Against That of Global Model')\n  ax.set_xticks(x)\n  ax.set_xticklabels(labs)\n  ax.legend()\n\n  def autolabel(rects):\n    '''\n    Copied from:\n\n    Title: Matplotlib\n    Authors: John Hunter et al.\n    Date: 2012\n    Availability: https://matplotlib.org/3.2.2/gallery/lines_bars_and_markers/barchart.html\n\n    '''\n\n    \"\"\"Attach a text label above each bar in *rects*, displaying its height.\"\"\"\n    for rect in rects:\n      height = round(rect.get_height(), 2)\n      ax.annotate('{}'.format(height),\n                  xy=(rect.get_x() + rect.get_width() / 2, height),\n                  xytext=(0, 3),  # 3 points vertical offset\n                  textcoords=\"offset points\",\n                  ha='center', va='bottom')\n\n  autolabel(rects1)\n  autolabel(rects2)\n\n  plt.ylim([0, 1])\n  \n  if filepath:\n    plt.ioff()\n    plt.savefig(filepath)\n    plt.close()\n  else:\n    plt.show()\n\n\ndef get_measures_of_dispersion(precision_recall_fscores):\n  return [np.std(classification_metric) for classification_metric in precision_recall_fscores]\n\n\ndef precision_recall_fscore(y_true, y_pred):\n  return precision_recall_fscore_support(y_true, y_pred, average=\"macro\", zero_division=1)[:-1]\n\n\ndef get_precision_recall_fscores_of_local_models(local_models_y_test, local_models_y_preds):\n  return list(zip(*[precision_recall_fscore(local_model_y_test, local_model_y_preds) for local_model_y_test, local_model_y_preds in zip(local_models_y_test, local_models_y_preds)]))\n\n\ndef get_mean_precision_recall_fscores_of_local_models(precision_recall_fscores_of_local_models):\n  return [mean(metric) for metric in precision_recall_fscores_of_local_models]\n\n\ndef get_utility_measure_on_distributions(aggr_model_precision_recall_fscore, avg_local_model_precision_recall_fscore):\n  arrays = [[\"Precision\", \"Precision\", \"Recall\", \"Recall\", \"F1-score\", \"F1-score\"],\n          [\"Aggr.\", \"Local\", \"Aggr.\", \"Local\", \"Aggr.\", \"Local\"]]\n  tuples = list(zip(*arrays))\n  index = pd.MultiIndex.from_tuples(tuples, names=[\"Distribution\", \"\"])\n\n  utility_measure = pd.DataFrame([[round(i, 2) for sub in zip(aggr_model_precision_recall_fscore, avg_local_model_precision_recall_fscore) for i in sub]], index=[DATA_PARTITIONING_STRATEGY], columns=index)\n  return utility_measure\n\n\ndef plot_convergence_behaviour_from_federated_evaluation(federated_test_accs, filepath=None):\n  # Place legend outside axes\n  axes_legend_bbox = (1.03, 0.6)\n\n  # Resize figure\n  plt.figure(figsize=(rcParams[\"figure.figsize\"][0] + axes_legend_bbox[0] - 1, rcParams[\"figure.figsize\"][1]))\n\n  plt.plot([mean(test_accs) for test_accs in zip(*federated_test_accs)])\n  plt.ylim([0, 1])\n  plt.xlabel(\"Round\")\n  plt.ylabel(\"Avg Test Acc\")\n  plt.title(\"Convergence Behaviour\")\n  plt.legend(bbox_to_anchor = axes_legend_bbox)\n  \n  if filepath:\n    plt.ioff()\n    plt.savefig(filepath, bbox_inches='tight')\n    plt.close()\n  else:\n    plt.show()\n\n\ndef plot_convergence_behaviour_from_centralized_evaluation(centralized_test_accs, filepath=None):\n  # Place legend outside axes\n  axes_legend_bbox = (1.26, 0.6)\n\n  # Resize figure\n  plt.figure(figsize=(rcParams[\"figure.figsize\"][0] + axes_legend_bbox[0] - 1, rcParams[\"figure.figsize\"][1]))\n\n  plt.plot(centralized_test_accs, label= 'FedShare' if DATA_SHARING else 'FedAvg')\n  plt.ylim([0, 1])\n  plt.xlabel(\"Round\")\n  plt.ylabel(\"Test Acc\")\n  plt.title(\"Convergence Behaviour\")\n  plt.legend(bbox_to_anchor = axes_legend_bbox)\n  \n  if filepath:\n    plt.ioff()\n    plt.savefig(filepath, bbox_inches='tight')\n    plt.close()\n  else:\n    plt.show()\n\n\ndef report_classification_macro_averages(y_test, y_preds):\n  report = classification_report(y_test, y_preds)\n  rows = report.split(\"\\n\")\n  headings = \" \".join(rows[0].split(\" \")[:-1])\n  macro_averages = \" \".join(rows[7].split(\" \")[:-1])\n  return \"\\n\".join((headings, macro_averages))\n```\n\n## Design of Experimental Validation\n\n### Distributed Optimization Problem\n\nOur federated learning system has the finite sum objective with generic form:\n\n\\begin{equation}\n\\min_{w \\in \\mathbb{R}^d} f(w)\n\\qquad \\text{where} \\qquad\nf(w) \\overset{\\text{def}}{=} \\frac{1}{n} \\sum_{i=1}^n f_i(w).\n\\end{equation}\n\nwhere $n$ is the number of data samples and $w$ is the model parameters\n\nWe take $f_i(w) = \\ell(x_i, y_i; w)$, that is, the log loss of the prediction on sample $(x_i, y_i)$ made with coefficients $w$. We assume there are $K$ clients over which the data is partitioned, with $\\mathcal{P}_k$ the set of samples on client $k$, with $n_k = |\\mathcal{P}_k|$. Thus, we can re-write the system's objective as:\n\n\\begin{equation}\n\\min_{w \\in \\mathbb{R}^d} \\sum_{k = 1}^K \\frac{n_k}{n} F_k(w)\n\\qquad \\text{where} \\qquad\nF_k(w) \\overset{\\text{def}}{=} \\frac{1}{n_k} \\sum_{i \\in \\mathcal{P}_k} f_i(w).\n\\end{equation}\n\nIf the partition $\\mathcal{P}_k$ is formed by distributing the samples over the clients uniformly at random, then the f**IID assumption** made by distributed optimization algorithms holds[(Zhao et al., 2018)](https://arxiv.org/pdf/1806.00582.pdf). \n\nWe use the distribution setting where the IID assumption holds as a basline for our experiments.\n\n### Federated Optimization Problem\n\nThe optimization problem implicit in federated learning is known as the federated optimization problem, drawing a contrast to the distributed optimization problem. The key properties that differentiate federated optimization are: unbalanced data (different clients can hold different amounts of data) and that the IID assumption does not hold.\n\nHere we focus on horizontal federated learning, where the clients share the same feature space but different sample space (in contrast to vertical federated learning, where the clients have different feature and sample spaces).\n\nAn existing study gives a taxonomy of non-IID data distribution cases [(Kairouz et al., 2021)](https://arxiv.org/pdf/1912.04977.pdf). Consider the local data distribution $P(x_i, y_i)$. We can rewrite $P(x_i, y_i)$ as $P(x_i | y_i)P(y_i)$ and $P(y_i | x_i)P(x_i)$ so that we can more precisely show the differences between cases. The study gives 5 different non-IID cases:\n\n(1) label distribution skew (i.e., $P(y_i)$ is different among clients)\n\n(2) feature distribution skew (i.e., $P(x_i)$ is different among clients) \n\n(3) same labels but different features (i.e., $P(x_i|y_i)$ is different among clients) \n\n(4) same features but different labels (i.e., $P(y_i|x_i)$ is different among\nclients)\n\n(5) quantity skew (i.e., $P(x_i, y_i)$ is the same but the amount of data is different among clients) \n\nHere, (3) is mainly related to vertical FL (the clients share the same sample IDs but different features). (4) is not applicable in most FL studies, which assume same ground truths . (2) can be simulated on a dataset by adding different levels of noise to different partitions. In computer vision, these transformations can be done on the fly, using data generators e.g. for Gaussian noise. However, this isn't the case with NLP due to the grammatical structure of the text; a new carefully augmented dataset must be generated beforehand [(Shahul ES, 2021)](https://neptune.ai/blog/data-augmentation-nlp).\n\nThus, we consider (5) quantity skew and (1) label distribution skew as possible non-IID data distribution cases in our experiments.\n\n### Unbalancedness (Quantity skew)\n\nThe size of the local dataset, $|{\\mathcal{P}}_k|$, varies across clients. Although, the iid assumption still holds. We use a Dirichlet distribution to allocate different amounts of data samples to each client. We sample $q \u223c Dir_N (\u03b2)$, and allocate a $q_j$ proportion of the total data samples to ${\\mathcal{P}}_j$ . The distribution parameter, $\u03b2>0$, can be used to control the degree of imbalance. The smaller $\u03b2$ is, the more imbalanced the distribution [(Li et al., 2021)](https://arxiv.org/pdf/2102.02079.pdf).\n\nThis scenario is relevant as irl some organisations will generate more data than others, leading to varying amounts of local training data.\n\n### Label Distribution Skew: Distribution-based label imbalance\n\nEach client is allocated a proportion of the samples of each label according to a Dirichlet distribution. Dirichlet distribution is an appropriate\nchoice to simulate imbalanced data distributions in the real-world [(Li et al., 2021)](https://arxiv.org/pdf/2102.02079.pdf). Specifically, we sample $p_k \u223c Dir_N(\u03b2)$ and allocate a $p_{k,j}$ proportion of the instances of class $k$ to client $j$. We fix to constrain the scope of the study. This partitioning strategy has been used to simulate real world data distributions in many recent FL studies [(Li et al., 2021)](https://arxiv.org/pdf/2102.02079.pdf).\n\n### Label Distribution Skew: Quantity-based label imbalance\n\nEach client owns data samples of a fixed subset of total labels. Such a setting is also used in other studies, [(Li et al., 2021)](https://arxiv.org/pdf/2102.02079.pdf). We use a general partitioning strategy to set the number of labels that each client has; in the context of our study, this is either 1 or 2.\n\n### Statistical Resampling\n\nWe use 10-fold Cross-Validation to sufficiently randomize the train/test split, to reduce sampling error. Further, we select 10 observations from each distribution setting to reduce selection bias. The data partitioning random seed is set to the current observation number. Therefore, we perform 100 repeats of the experiment per distribution setting.\n\n## Test Bench Driver Code\n\n\n\n\n```python\ndata_partitioning_strategies = [\"iid\", \"iid-quantity-skew\", \"noniid-distribution-based-label-imbalance\", \"noniid-quantity-based-label-imbalance-2\", \"noniid-quantity-based-label-imbalance-1\"]\n```\n\n\n```python\nlogging_folders = [\"log_29_03_2022__21_13_51_iid/\", \"log_29_03_2022__22_02_06_iid-quantity-skew/\", \"log_29_03_2022__22_02_56_noniid-distribution-based-label-imbalance/\", \"log_29_03_2022__23_14_51_noniid-quantity-based-label-imbalance-2/\", \"log_29_03_2022__23_15_21_noniid-quantity-based-label-imbalance-1/\"]\n```\n\n\n```python\nuse_data_sharing = [False, False, False, True, True]\n```\n\n\n```python\nclassification_metrics = ['precision', 'recall', 'f1-score']\naggregated_measures = ['value', 'std']\n```\n\n\n```python\n# Cross-validator\nskf = StratifiedKFold(n_splits=NUMBER_OF_VALIDATION_FOLDS, shuffle=True, random_state=42)\n\ncurrent_repetition = 1\n\nfor data_partitioning_strategy, logging_folder, data_sharing_flag in zip(data_partitioning_strategies, logging_folders, use_data_sharing):\n  # Overrides to global experiment config\n  DATA_PARTITIONING_STRATEGY = data_partitioning_strategy\n  LOG_DIR = LOGGING_FOLDERS_DIR + logging_folder\n  DATA_SHARING = data_sharing_flag\n\n  summed_federated_test_accs = np.zeros(NUMBER_OF_FL_ROUNDS)\n\n  aggregated_classification_macro_averages_of_locally_trained_models_on_local_data = {classification_metric: {aggregated_measure: [] \n                                                                                                              for aggregated_measure in aggregated_measures} \n                                                                                      for classification_metric in classification_metrics}\n  aggregated_classification_macro_averages_of_federated_model_on_local_data = {classification_metric: {aggregated_measure: [] \n                                                                                                       for aggregated_measure in aggregated_measures} \n                                                                               for classification_metric in classification_metrics}\n\n  for random_seed in range(0, NUMBER_OF_OBSERVATIONS_SELECTED_WITH_DATA_PARTITIONING_STRATEGY):\n\n    DATA_PARTITIONING_RANDOM_SEED = random_seed\n\n    summed_precision_recall_fscores_of_local_models_across_validation_folds = np.zeros((3, NUMBER_OF_CLIENTS))\n    summed_ultimate_precision_recall_fscores_of_federated_model_on_local_data_across_validation_folds = np.zeros((3, NUMBER_OF_CLIENTS))\n    \n    for train_index, test_index in skf.split(X_, y):\n\n      print(f'Repetition number {current_repetition}...')\n\n      X_train, X_test = X_[train_index], X_[test_index]\n      y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n\n      if DATA_SHARING:\n        # Partition train set into client partition and holdout partition G, where \u03b2 = 2.5%. Initialise with random seed for reproducability.\n        X_train_client, X_train_holdout, y_train_client, y_train_holdout = train_test_split(X_train, y_train, random_state=42, test_size=0.025, stratify=y_train)\n\n        # A warm-up model is trained on G\n        warm_up_model = classifier.fit(X_train_holdout, y_train_holdout)\n\n        # Create a random \u03b1 portion of G to be merged with the data of each client, where \u03b1 is 10%\n        X_train_shared, _, y_train_shared, _ = train_test_split(X_train_holdout, y_train_holdout, random_state=42, train_size=0.1, stratify=y_train_holdout)\n        \n      # Split train set into NUMBER_OF_CLIENTS partitions.\n      partitioned_train_set = get_train_partitions(X_train, y_train.to_numpy())\n\n      # Split test set into NUMBER_OF_CLIENTS partitions.\n      partitioned_test_set = get_test_partitions(X_test, y_test.to_numpy(), partitioned_train_set)\n\n      # Evaluate local models\n      local_models_y_preds = evaluate_local_models(partitioned_train_set, partitioned_test_set)\n\n      local_models_y_test = [y_test_partition for X_test_partition, y_test_partition in partitioned_test_set]\n\n      precision_recall_fscores_of_local_models = get_precision_recall_fscores_of_local_models(local_models_y_test, local_models_y_preds)\n\n      avg_local_model_precision_recall_fscore = get_mean_precision_recall_fscores_of_local_models(precision_recall_fscores_of_local_models)\n\n      measures_of_dispersion = get_measures_of_dispersion(precision_recall_fscores_of_local_models)\n\n      summed_precision_recall_fscores_of_local_models_across_validation_folds = np.add(summed_precision_recall_fscores_of_local_models_across_validation_folds, precision_recall_fscores_of_local_models)\n\n      for i, classification_metric in enumerate(classification_metrics):\n        aggregated_classification_macro_averages_of_locally_trained_models_on_local_data[classification_metric]['value'].append(avg_local_model_precision_recall_fscore[i])\n        aggregated_classification_macro_averages_of_locally_trained_models_on_local_data[classification_metric]['std'].append(measures_of_dispersion[i])\n\n\n      # Run sim with global config\n      sim_results = run_sim(partitioned_train_set, partitioned_test_set)\n\n      federated_y_preds = sim_results[\"federated_y_preds\"]\n\n      summed_federated_test_accs = np.add(summed_federated_test_accs, [mean(test_accs) for test_accs in zip(*sim_results[\"federated_test_accs\"])])\n\n      ultimate_precision_recall_fscores_of_federated_model_on_local_data = get_precision_recall_fscores_of_local_models(local_models_y_test, [client[-1] for client in federated_y_preds])\n\n      avg_ultimate_federated_model_precision_recall_fscore = get_mean_precision_recall_fscores_of_local_models(ultimate_precision_recall_fscores_of_federated_model_on_local_data)\n\n      measures_of_dispersion = get_measures_of_dispersion(ultimate_precision_recall_fscores_of_federated_model_on_local_data)\n\n      summed_ultimate_precision_recall_fscores_of_federated_model_on_local_data_across_validation_folds = np.add(summed_ultimate_precision_recall_fscores_of_federated_model_on_local_data_across_validation_folds, ultimate_precision_recall_fscores_of_federated_model_on_local_data)\n      np.add(summed_ultimate_precision_recall_fscores_of_federated_model_on_local_data_across_validation_folds, ultimate_precision_recall_fscores_of_federated_model_on_local_data)\n\n\n      for i, classification_metric in enumerate(classification_metrics):\n        aggregated_classification_macro_averages_of_federated_model_on_local_data[classification_metric]['value'].append(avg_ultimate_federated_model_precision_recall_fscore[i])\n        aggregated_classification_macro_averages_of_federated_model_on_local_data[classification_metric]['std'].append(measures_of_dispersion[i])\n\n      current_repetition += 1\n\n    avg_precision_recall_fscores_of_local_models_across_validation_folds = np.divide(summed_precision_recall_fscores_of_local_models_across_validation_folds, NUMBER_OF_VALIDATION_FOLDS)\n    avg_ultimate_precision_recall_fscores_of_federated_model_on_local_data_across_validation_folds = np.divide(summed_ultimate_precision_recall_fscores_of_federated_model_on_local_data_across_validation_folds, NUMBER_OF_VALIDATION_FOLDS)\n    np.divide(summed_ultimate_precision_recall_fscores_of_federated_model_on_local_data_across_validation_folds, NUMBER_OF_VALIDATION_FOLDS)\n\n    classification_macro_averages_filepath = LOG_DIR + DATA_PARTITIONING_STRATEGY + '_seed_' + str(DATA_PARTITIONING_RANDOM_SEED) + 'ultimate_precision_recall_fscores_of_models_across_10_validation_folds.json'\n    json.dump([{\"avg_precision_recall_fscores_of_local_models_across_validation_folds\": avg_precision_recall_fscores_of_local_models_across_validation_folds.tolist(), \n                \"stds\": np.std(avg_precision_recall_fscores_of_local_models_across_validation_folds, axis=1).tolist(), \n                \"means\": np.mean(avg_precision_recall_fscores_of_local_models_across_validation_folds, axis=1).tolist()}, \n           {\"avg_ultimate_precision_recall_fscores_of_federated_model_on_local_data_across_validation_folds\": \n            avg_ultimate_precision_recall_fscores_of_federated_model_on_local_data_across_validation_folds.tolist(), \n            \"stds\": np.std(avg_ultimate_precision_recall_fscores_of_federated_model_on_local_data_across_validation_folds, axis=1).tolist(), \n            \"means\": np.mean(avg_ultimate_precision_recall_fscores_of_federated_model_on_local_data_across_validation_folds, axis=1).tolist()}], open(classification_macro_averages_filepath, 'w'), indent=4)\n\n  avg_federated_test_accs = np.divide(summed_federated_test_accs, NUMBER_OF_REPEATS)\n\n  avg_classification_macro_averages_of_locally_trained_models_on_local_data = {classification_metric: {aggregated_measure: {'avg': np.mean(averages), '95% CI': [np.percentile(averages, 2.5), \n                                                                                                                                                                np.percentile(averages, 97.5)]} \n                                                                                                      for aggregated_measure, averages in aggregated_measures.items()} \n                                                                              for classification_metric, aggregated_measures in \n                                                                              aggregated_classification_macro_averages_of_locally_trained_models_on_local_data.items()}\n\n  avg_classification_macro_averages_of_federated_model_on_local_data = {classification_metric: {aggregated_measure: {'avg': np.mean(averages), '95% CI': [np.percentile(averages, 2.5), \n                                                                                                                                                          np.percentile(averages, 97.5)]} \n                                                                                                for aggregated_measure, averages in aggregated_measures.items()} \n                                                                        for classification_metric, aggregated_measures in \n                                                                        aggregated_classification_macro_averages_of_federated_model_on_local_data.items()}\n\n  federated_test_accs_filepath = LOG_DIR+f\"{DATA_PARTITIONING_STRATEGY}_federated_test_accs.json\"\n  json.dump({'federated_test_accs': avg_federated_test_accs.tolist()}, open(federated_test_accs_filepath, 'w'), indent=4)\n\n  classification_macro_averages_filepath = LOG_DIR + f'classification_macro_averages_federated_evaluation.json'\n  json.dump([{'avg_classification_averages_local_models': avg_classification_macro_averages_of_locally_trained_models_on_local_data}, \n            {'avg_classification_averages_federated_eval': avg_classification_macro_averages_of_federated_model_on_local_data}], open(classification_macro_averages_filepath, 'w'), indent=4)\n```\n", "meta": {"hexsha": "6a53d76231a3a0e5d95b785a698b7252c0474a8f", "size": 166065, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Federated_Detection_Of_Hate_Speech.ipynb", "max_stars_repo_name": "FractalGiraffe/COMP0029", "max_stars_repo_head_hexsha": "a9a48594bd94ceff79ffe6832f3b897277853b8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Federated_Detection_Of_Hate_Speech.ipynb", "max_issues_repo_name": "FractalGiraffe/COMP0029", "max_issues_repo_head_hexsha": "a9a48594bd94ceff79ffe6832f3b897277853b8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Federated_Detection_Of_Hate_Speech.ipynb", "max_forks_repo_name": "FractalGiraffe/COMP0029", "max_forks_repo_head_hexsha": "a9a48594bd94ceff79ffe6832f3b897277853b8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.807396558, "max_line_length": 18085, "alphanum_fraction": 0.6365158221, "converted": true, "num_tokens": 19455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19436782035217448, "lm_q2_score": 0.05582314231270587, "lm_q1q2_score": 0.010850222496529885}}
{"text": "##### Copyright 2020 The Cirq Developers\n\n\n```\n#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# Introduction to Cirq\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n  <td>\n    <a target=\"_blank\" href=\"https://quantumai.google/cirq/tutorials/educators/intro\">View on QuantumAI</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/Cirq/blob/master/docs/tutorials/educators/intro.ipynb\">Run in Google Colab</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://github.com/quantumlib/Cirq/blob/master/docs/tutorials/educators/intro.ipynb\">View source on GitHub</a>\n  </td>\n  <td>\n    <a href=\"https://storage.googleapis.com/tensorflow_docs/Cirq/docs/tutorials/educators/intro.ipynb\">Download notebook</a>\n  </td>\n</table>\n\n[Cirq](https://github.com/quantumlib/cirq) is a framework for writing quantum algorithms for noisy intermediate scale quantum (NISQ) devices. Roughly speaking, NISQ devices are those with O(100) qubits that can enact O(1000) gates.  Because the resources for NISQ devices are so constrained, we believe that a framework for writing programs on these devices needs to be aware of all of the architectural properties of the device on which the algorithm is written. This is in contrast to other frameworks where there is a clean separation between the abstract model being used and the details of the device.  \n\nIn this tutorial we will walk through the basics of writing quantum alogorithms in Cirq. Our final goal will be to write a variational ansatz for use in an optimization algorithm.\n\n## Installing Cirq\n\nTo use Cirq one first needs to install Cirq.  Installation instructions are available at [quantumai.google/cirq under \"Installing Cirq\"](https://quantumai.google/cirq/install).  For the purpose of this tutorial, we run `pip install cirq` as shown in the following code cell to install the latest release of Cirq. \n\n> Different notebook execution systems exist, but for most part they have \"run\" button on a cell which you can click, or \"shift + enter\" is often the shortcut to run the cell. \n\n\n```\ntry:\n    import cirq\nexcept ImportError:\n    print(\"installing cirq...\")\n    !pip install cirq --quiet\n    print(\"installed cirq.\")\n    import cirq\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n```\n\nLet's check that Cirq has been successfully installed by importing Cirq and printing out a diagram of Google's Bristlecone device shown below.\n\n\n\n\n```\n\"\"\"Test successful installation by printing out the Bristlecone device.\"\"\"\nprint(cirq.google.Bristlecone)\n```\n\n                                                 (0, 5)\u2500\u2500\u2500\u2500(0, 6)\n                                                 \u2502         \u2502\n                                                 \u2502         \u2502\n                                        (1, 4)\u2500\u2500\u2500(1, 5)\u2500\u2500\u2500\u2500(1, 6)\u2500\u2500\u2500\u2500(1, 7)\n                                        \u2502        \u2502         \u2502         \u2502\n                                        \u2502        \u2502         \u2502         \u2502\n                               (2, 3)\u2500\u2500\u2500(2, 4)\u2500\u2500\u2500(2, 5)\u2500\u2500\u2500\u2500(2, 6)\u2500\u2500\u2500\u2500(2, 7)\u2500\u2500\u2500(2, 8)\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                      (3, 2)\u2500\u2500\u2500(3, 3)\u2500\u2500\u2500(3, 4)\u2500\u2500\u2500(3, 5)\u2500\u2500\u2500\u2500(3, 6)\u2500\u2500\u2500\u2500(3, 7)\u2500\u2500\u2500(3, 8)\u2500\u2500\u2500(3, 9)\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n             (4, 1)\u2500\u2500\u2500(4, 2)\u2500\u2500\u2500(4, 3)\u2500\u2500\u2500(4, 4)\u2500\u2500\u2500(4, 5)\u2500\u2500\u2500\u2500(4, 6)\u2500\u2500\u2500\u2500(4, 7)\u2500\u2500\u2500(4, 8)\u2500\u2500\u2500(4, 9)\u2500\u2500\u2500(4, 10)\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n    (5, 0)\u2500\u2500\u2500(5, 1)\u2500\u2500\u2500(5, 2)\u2500\u2500\u2500(5, 3)\u2500\u2500\u2500(5, 4)\u2500\u2500\u2500(5, 5)\u2500\u2500\u2500\u2500(5, 6)\u2500\u2500\u2500\u2500(5, 7)\u2500\u2500\u2500(5, 8)\u2500\u2500\u2500(5, 9)\u2500\u2500\u2500(5, 10)\u2500\u2500\u2500(5, 11)\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n             (6, 1)\u2500\u2500\u2500(6, 2)\u2500\u2500\u2500(6, 3)\u2500\u2500\u2500(6, 4)\u2500\u2500\u2500(6, 5)\u2500\u2500\u2500\u2500(6, 6)\u2500\u2500\u2500\u2500(6, 7)\u2500\u2500\u2500(6, 8)\u2500\u2500\u2500(6, 9)\u2500\u2500\u2500(6, 10)\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n                      (7, 2)\u2500\u2500\u2500(7, 3)\u2500\u2500\u2500(7, 4)\u2500\u2500\u2500(7, 5)\u2500\u2500\u2500\u2500(7, 6)\u2500\u2500\u2500\u2500(7, 7)\u2500\u2500\u2500(7, 8)\u2500\u2500\u2500(7, 9)\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                               (8, 3)\u2500\u2500\u2500(8, 4)\u2500\u2500\u2500(8, 5)\u2500\u2500\u2500\u2500(8, 6)\u2500\u2500\u2500\u2500(8, 7)\u2500\u2500\u2500(8, 8)\n                                        \u2502        \u2502         \u2502         \u2502\n                                        \u2502        \u2502         \u2502         \u2502\n                                        (9, 4)\u2500\u2500\u2500(9, 5)\u2500\u2500\u2500\u2500(9, 6)\u2500\u2500\u2500\u2500(9, 7)\n                                                 \u2502         \u2502\n                                                 \u2502         \u2502\n                                                 (10, 5)\u2500\u2500\u2500(10, 6)\n\n\nThis cell should run successfully, and the output should in fact be the grid of qubits for the Bristlecone device. If so, the install worked!\n\n> Be aware that Cirq is still alpha software, meaning **breaking changes can happen at any time**. If you don't want your project to suddenly go from working to not working when we a new version is released, you should depend on a *specific version* of Cirq and periodically bump that version to the latest one. For example, you can run `pip install cirq==x.y.z` to install version `x.y.z` of Cirq.\n\n## Qubits, Moments, Operations, and Circuits\n\nIn Cirq, circuits are represented either by a `Circuit` object. Conceptually:\n\n- Q `Circuit` is a collection of `Moment`s. \n- A `Moment` is a collection of `Operation`s that all act during the same abstract time slice. \n- An `Operation` is a an effect that operates on a specific subset of Qubits. \n  - The most common type of `Operation` is a `Gate` applied to several qubits (a \"`GateOperation`\"). \n  \nThese ideas are illustrated by the following diagram.\n\n\n\n### Create a `Circuit`\n\nA typical way to create a `Circuit` is shown below.\n\n\n```\n\"\"\"Creating a circuit.\"\"\"\n# Define three qubits.\na = cirq.NamedQubit(\"a\")\nb = cirq.NamedQubit(\"b\")\nc = cirq.NamedQubit(\"c\")\n\n# Define a list of operations.\nops = [cirq.H(a), cirq.H(b), cirq.CNOT(b, c), cirq.H(b)]\n\n# Create a circuit from the list of operations.\ncircuit = cirq.Circuit(ops)\nprint(\"Circuit:\\n\")\nprint(circuit)\n```\n\n    Circuit:\n    \n    a: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    b: \u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\n              \u2502\n    c: \u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\nWe can unpack this a bit and see all of the components for the circuit.\n\nThe first thing we do is pick some qubits to use. There are many different types of qubits in Cirq, and you can define your own by inheriting from the `cirq.Qid` class. There's nothing inherently special or magical about these quantum id types such as `cirq.NamedQubit`. They simply identify what you wish to operate on, which is relevant when you are targeting a specific device. For example, if we were creating a circuit for the Bristlecone device and wanted to refer to the qubit in the left-most position, we would use `cirq.GridQubit(5, 0)`. (See the first diagram of the Bristlecone device we printed out.) For simplicity, in the previous cell we defined `cirq.NamedQubit`s which are simply qubits that can be identified by a name.\n\nNext, we encounter the object `cirq.H` which is a Hadamard gate with unitary\n\n$$\nH = {1 \\over \\sqrt{2}} \\left[ \\begin{array}[cc]  & 1 & 1  \\\\ 1 & -1 \\end{array}\\right] .\n$$\n\nIn Cirq, `cirq.H` is an instance of the `cirq.HGate` class, which itself is a subclass of `Gate` (along with other classes). We can use Cirq to see the unitary matrix of `Gate` objects as follows.\n\n\n```\n\"\"\"Get the unitary of a gate, here the Hadamard gate.\"\"\"\ncirq.unitary(cirq.H)\n```\n\n\n\n\n    array([[ 0.70710678+0.j,  0.70710678+0.j],\n           [ 0.70710678+0.j, -0.70710678+0.j]])\n\n\n\nWe see that this agrees with the unitary for the Hadamard gate above.\n\n`Gate` objects have the ability to applied \"on\" one or more qubits.  There are two ways to do this for gates, either using the `on` method or by directly calling the gate on the qubits as if the gate were a function and the qubits were arguments.  For example to apply the `H` onto qubit `a` we can say `cirq.H.on(a)` or `cirq.H(a)`.\n\nThe result of those expressions is a `GateOperation` object, which is a type of `Operation`.\n\n> **Note**: In Cirq, there is a strong distinction between `Operation`s and `Gate`s. An `Operation` is associated with specific qubits and can be put in `Circuit`s. A `Gate` has unspecified qubits, and will produce an operation when acting on qubits.\n\nOnce you have a collection of operations, you can construct a `Circuit` by passing the operations into the constructor for a `Circuit`:\n\n```\nops = [list of operations]\ncircuit = cirq.Circuit(ops)\n```\n\nThe last thing we did in the example code was use the (surprisingly useful) ability to print the circuit as a text diagram.\n\nThe diagram is visually helpful, but it doesn't really get into the internal details of how the `Circuit` is represented. As mentioned, a `Circuit` is made up of a sequence of `Moment` objects, and each `Moment` object is a list of non-overlapping `Operation`s. To see this internal structure, we can iterate over the `Moment`s in the `Circuit` and print them out.\n\n\n```\n\"\"\"Print out the moments in a circuit.\"\"\"\nprint(\"Circuit:\\n\")\nprint(circuit)\n\nprint(\"\\nMoments in the circuit:\\n\")\nfor i, moment in enumerate(circuit):\n    print('Moment {}: {}'.format(i, moment))\n```\n\n    Circuit:\n    \n    a: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    b: \u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\n              \u2502\n    c: \u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    Moments in the circuit:\n    \n    Moment 0: H(a) and H(b)\n    Moment 1: CNOT(b, c)\n    Moment 2: H(b)\n\n\nWe see that this circuit consists of three moments. For even more on the underlying structure of a circuit, we can print the circuit's `repr`. This returns a more detailed (and usually less readable) expression.\n\n\n```\n\"\"\"Print the repr of a circuit.\"\"\"\nprint(repr(circuit))\n```\n\n    cirq.Circuit([\n        cirq.Moment(\n            cirq.H(cirq.NamedQubit('a')),\n            cirq.H(cirq.NamedQubit('b')),\n        ),\n        cirq.Moment(\n            cirq.CNOT(cirq.NamedQubit('b'), cirq.NamedQubit('c')),\n        ),\n        cirq.Moment(\n            cirq.H(cirq.NamedQubit('b')),\n        ),\n    ])\n\n\nAlthough it is less readable, the usefulness of printing the `repr` is that it includes *all* the gory details which can be useful when debugging. The `repr` is also a valid python expression that evaluates to the circuit.\nFor example, if we notice that a circuit generated in some complicated way triggers a bug in a simulator, copy-pasting the generated circuit's `repr` into a test, and then working from there, is a simple way to decouple the reproduction of the bug from the circuit generation code.\n\n### More ways to create `Circuit`s\n\nAbove we created a `Circuit` by passing in a list of operations to its constructor.  In Cirq, there are many ways to construct and modify circuits, and each of these is useful in different contexts.  Here are a few examples:\n\n\n1. `Circuit(...)`: This is the simplest way to make a circuit. Give this method some operations, and out pops a circuit.\n2.  `append`:  `Circuit`s are mutable. You can start with an empty `circ = cirq.Circuit()` and simply `circ.append(operations)` to add on more and more operations .\n3. `insert`:  Instead of appending, you can insert before a particular moment location (labeled by an integer index).\n\nOne interesting, and extremely convenient, fact about `Circuit(...)`, `append`, and `insert` is that they \"auto flatten\" whatever you give them.\nYou *can* give them a list of operations, but you can also give them\n\n- a list *of lists* of operations,\n- a generator function that sometimes yields tuples of operations and other times yields individual operations,\n- or just a single operation (without a list around it).\n\nIf it can recursively iterated into individual operations, these three methods will take it.\n\n> The above idea uses a concept we call an `OP_TREE` in Cirq. An `OP_TREE` is not a class, but a contract. The basic idea is that if the input can be iteratively flattened into a list of operations, then the input is an `OP_TREE`.\n\nThe main place where auto-flattening is useful is when you are building a circuit's operations using generators. \n\n> Recall that, in Python, functions that have a `yield` statement are *generators*. Generators are functions that act as *iterators*. \n\nIn this context, auto-flattening means that generators producing operations for a circuit can simply `yield` sub-generators (instead of iterating over them and yielding their items). We show an example of this below.\n\n\n```\n\"\"\"Creating a circuit from generator functions.\"\"\"\ndef xor_swap(a, b):\n    \"\"\"Swaps two qubits with three CNOTs.\"\"\"\n    yield cirq.CNOT(a, b)\n    yield cirq.CNOT(b, a)\n    yield cirq.CNOT(a, b)\n\n\ndef left_rotate(qubits):\n    \"\"\"Rotates qubits to the left.\"\"\"\n    for i in range(len(qubits) - 1):\n        a, b = qubits[i: i + 2]\n        yield xor_swap(a, b)\n\n\n# Get five qubits on a line.\nline = cirq.LineQubit.range(5)\n\n# Create a circuit which rotates the qubits to the left.\nprint(cirq.Circuit(left_rotate(line)))\n```\n\n    0: \u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n          \u2502   \u2502   \u2502\n    1: \u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502   \u2502   \u2502\n    2: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                                  \u2502   \u2502   \u2502\n    3: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500\n                                              \u2502   \u2502   \u2502\n    4: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500\n\n\nOne can see how this method of creating circuits is quite powerful. \n\n> Note that `cirq.SWAP` is a pre-defined gate in Cirq. We used three `cirq.CNOT`s instead of `cirq.SWAP` in the above example to demonstrate auto-flattening with generators.\n\n### Insert strategies\n\nYou may have noticed that there is a hole in what we've explained so far. We have been passing a one-dimensional sequence of operations, but the output is a two-dimensional circuit (a list-of-lists-of-operations). There is a degree of freedom that hasn't been account for. Specifically, how does Cirq choose the moment that each operation will be placed within?\n\nThe answer is the concept of a `cirq.InsertStrategy`. An `InsertStrategy` defines how `Operation`s are placed in a `Circuit` when requested to be inserted at a given location. Here a `location` is identified by the index of the `Moment` in the `Circuit` that operations should be placed before. \n\n> *Note*: In the case of `Circuit.append` this means inserting at the index `len(circuit)` which is one more than the largest moment index and so represents the end of the circuit.\n\nThere are currently four insertion strategies in Cirq:\n\n1. `InsertStrategy.EARLIEST` (currently the default),\n2. `InsertStrategy.NEW`,\n3. `InsertStrategy.INLINE`,\n4. `InsertStrategy.NEW_THEN_INLINE`.\n\nThe strategy `InsertStrategy.EARLIEST` is defined as follows:\n\n> `InsertStrategy.EARLIEST`: Scans backward from the insert\n> location until a moment with operations touching qubits affected by the\n> operation to insert is found. The operation is added into the moment just\n> after that location.\n\nFor example, if we first create an `Operation` in a single moment,\nand then use `InsertStrategy.EARLIEST` the `Operation` can slide back to this\nfirst `Moment` if there is space.\n\n\n```\n\"\"\"Appending operations with InsertStrategy.EARLIEST.\"\"\"\n# Create an empty circuit.\ncircuit = cirq.Circuit()\n\n# Append an operation.\n# Note: InsertStrategy.EARLIEST is used by default if not otherwise specified.\ncircuit.append([cirq.CZ(a, b)])\n\n# Append more operations.\n# Note: InsertStrategy.EARLIEST is used by default if not otherwise specified.\ncircuit.append([cirq.H(a), cirq.H(b), cirq.H(c)])\n\n# Display the circuit.\nprint(\"Circuit:\\n\")\nprint(circuit)\n```\n\n    Circuit:\n    \n    a: \u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\n          \u2502\n    b: \u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\n    \n    c: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\nAfter creating the first moment with a `CZ` gate, the second\nappend uses the `InsertStrategy.EARLIEST` strategy. The\n`H` on ``a`` and ``b`` cannot slide back, while the `H` on ``c`` can and so ends up in the first `Moment`.\n\nWhile `InsertStrategy.EARLIEST` is the default strategy, the second most important strategy is `InsertStrategy.NEW_THEN_INLINE`, defined as follows:\n\n> `InsertStrategy.NEW_THEN_INLINE`: For the first operation, add it to a new \n> `Moment` the insertion point.  Attempts to add the operation after the first \n> operation to insert into the moment just before the desired insert location. \n> But, if there's already an existing operation affecting any of the qubits\n> touched by the operation to insert, a new moment is created instead and this \n> `Moment` is the one that is subsequently used for insertions.\n\nTo see an example of this strategy, we create a circuit with the same operations but inserting them with a different strategy.\n\n\n```\n\"\"\"Appending operations with InsertStrategy.NEW_THEN_INLINE.\"\"\"\n# Create an empty circuit.\ncircuit = cirq.Circuit()\n\n# Append an operation.\ncircuit.append([cirq.CZ(a, b)], strategy=cirq.InsertStrategy.NEW_THEN_INLINE)\n\n# Append more operations.\ncircuit.append([cirq.H(a), cirq.H(b), cirq.H(c)], strategy=cirq.InsertStrategy.NEW_THEN_INLINE)\n\n# Display the circuit.\nprint(\"Circuit:\\n\")\nprint(circuit)\n```\n\n    Circuit:\n    \n    a: \u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\n          \u2502\n    b: \u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\n    \n    c: \u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500\n\n\nIn contrast to the previous codeblock using `InsertStrategy.EARLIEST`, we see that the three `cirq.H` gates appended after the `cirq.CZ` gate appear in the same moment when we use `InsertStrategy.NEW_THEN_INLINE`.\n\n### Exercise: Create a circuit\n\nNow that you've learned about `InsertStrategy`s, here is an exercise to validate your understanding.  Create, **using the least number of appends**, the following circuit:\n\n\n\n```\na: \u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\n      \u2502\nb: \u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502\nc: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n```\n\nHere imagine that you want exactly the moments indicated by the spacing of the circuit so that there are six moments in this circuit.\n\n#### Solution\n\n\n```\n#@title\n# Define three qubits.\na = cirq.NamedQubit('a')\nb = cirq.NamedQubit('b')\nc = cirq.NamedQubit('c')\n\n# Get an empty circuit.\ncircuit = cirq.Circuit()\n\n# Append these gates using cirq.InsertStrategy.EARLIEST (the default strategy).\ncircuit.append([cirq.CZ(a, b), cirq.H(c), cirq.H(a)])\n\n# Append these gates using cirq.InsertStrategy.NEW_THEN_INLINE.\ncircuit.append(\n    [cirq.H(b), cirq.CZ(b, c), cirq.H(b), cirq.H(a), cirq.H(a)],\n    strategy=cirq.InsertStrategy.NEW_THEN_INLINE\n)\n\n# Display the circuit.\nprint(\"Circuit:\\n\")\nprint(circuit)\n```\n\n    Circuit:\n    \n    a: \u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500\n          \u2502\n    b: \u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                      \u2502\n    c: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n## Simulations of a Circuit\n\nNow that we know how to construct `Circuit`s in Cirq, let's see how to simulate them. First we create a simple circuit to simulate in the following cell.\n\n\n```\n\"\"\"Get a circuit to simulate.\"\"\"\ndef basic_circuit(measure=True):\n    \"\"\"Returns a simple circuit with some one- and two-qubit gates,\n    as well as (optionally) measurements.\n    \"\"\"\n    # Gates we will use in the circuit.\n    sqrt_x = cirq.X**0.5\n    cz = cirq.CZ\n    \n    # Yield the operations.\n    yield sqrt_x(a), sqrt_x(b)\n    yield cz(a, b)\n    yield sqrt_x(a), sqrt_x(b)\n    if measure:\n        yield cirq.measure(a,b)\n\n# Create a circuit including measurements.\ncircuit = cirq.Circuit(basic_circuit())\nprint(circuit)\n```\n\n    a: \u2500\u2500\u2500X^0.5\u2500\u2500\u2500@\u2500\u2500\u2500X^0.5\u2500\u2500\u2500M\u2500\u2500\u2500\n                  \u2502           \u2502\n    b: \u2500\u2500\u2500X^0.5\u2500\u2500\u2500@\u2500\u2500\u2500X^0.5\u2500\u2500\u2500M\u2500\u2500\u2500\n\n\nThe main simulator in Cirq is the `cirq.Simulator`. The general pattern of simulation is to instantiate this simulator, then pass in a circuit to either the `run` or `simulate` methods (more on this below).\n\n\n```\n\"\"\"Example of simulating a circuit in Cirq.\"\"\"\n# Get a simulator.\nsimulator = cirq.Simulator()\n\n# Pass the circuit to the simulator.run method.\nresult = simulator.run(circuit, repetitions=1)\nprint(\"Measurement results:\")\nprint(result)\n```\n\n    Measurement results:\n    a,b=0, 1\n\n\nRunning this multiple times should result in different measurement results, since the circuit produces a superposition over all computational basis states.\n\nAbove we used the `run` method of the `simulator`. In Cirq, `run` methods mimic the actual hardware in that they don't give one access to unphysical objects like the wavefunction. The `repetitions` argument is how many times to sample from the circuit.\n\nIf one wants to get the wavefunction, the `simulate` methods can be used as shown below.\n\n\n```\n\"\"\"Simulating a circuit with the `simulate` method.\"\"\"\n# Get a circuit without measurements.\ncircuit = cirq.Circuit(basic_circuit(measure=False))\n\n# Simulate the circuit.\nresult = simulator.simulate(circuit, qubit_order=[a, b])\n\n# Print the final state vector (wavefunction).\nprint(\"Wavefunction:\")\nprint(np.around(result.final_state_vector, 3))\n\n# Print the wavefunction in Dirac notation.\nprint(\"\\nDirac notation:\")\nprint(result.dirac_notation())\n```\n\n    Wavefunction:\n    [0.5+0.j  0. +0.5j 0. +0.5j 0.5+0.j ]\n    \n    Dirac notation:\n    0.5|00\u27e9 + 0.5j|01\u27e9 + 0.5j|10\u27e9 + 0.5|11\u27e9\n\n\nNotice that we passed a `qubit_order` into the `simulate` method.  This order helps define the order of the kronecker (tensor) product used in the resulting `final_state_vector`.  \n\n> *Note*: The `qubit_order` argument is optional. When it is omitted, qubits are sorted ascending according to the ordering methods defined by their Python class (for example `cirq.NamedQubit` sorts lexicographically by name).\nIf there are multiple types of qubits in one circuit, the name of the type is used as a tie breaker.\n\nThe simplest `qubit_order` value you can provide is a list of the qubits in the desired order. Any qubits from the circuit that are not in the list will be ordered using the  default `__str__` ordering, but come after qubits that are in the list. \n\n> **Note**: Be aware that all qubits in the list are included in the simulation, even if they are not operated on by the circuit.\n\nThe mapping from the order of the qubits to the order of the  amplitudes in the wave function can be tricky to understand.  Basically, it is the same as the ordering used by `numpy.kron`.\n\n> If the wavefunction is the array \n>> (0.1, 0.2, 0.3, 0.4),\n\n> then this is \n>> 0.1|00\u27e9 + 0.2|01\u27e9 + 0.3|10\u27e9 + 0.4|11\u27e9 \n\n> in Dirac notation. If \n>> qubit order = [a, b]\n\n> then |00> means qubit a is in 0 and qubit b is in 0, |01> means \n> qubit a is 0 and qubit b is 1, etc.\n\nAnother way to think about the qubit-to-amplitude ordering is as \"for loop ordering\":\n\n```\nfor a in [0, 1]:\n    for b in [0, 1]:\n        print(a, b)\n```\n\nThe first index (the outermost loop) is the slowest to vary.\n\n### Repetitions and histograms\n\nAs mentioned, the simulator `run` methods also take an option for repeating the circuit, namely, the `repetitions` argument. If the measurements in the circuit are terminal and all other operations are unitary, this simulator is optimized to not recompute the wavefunction before sampling from the circuit.\n\n\n```\n\"\"\"Simulate a circuit using 1000 repetitions.\"\"\"\n# Get a circuit with terminal measurements to simulate.\ncircuit = cirq.Circuit(basic_circuit())\n\n# Sample from the circuit 1000 times.\nresult = simulator.run(circuit, repetitions=1000)\n\n# Get a histogram of measurement results.\nprint(result.histogram(key=\"a,b\"))\n```\n\n    Counter({1: 261, 3: 256, 2: 248, 0: 235})\n\n\nHere we have also demonstrated the use of the `histogram` method on the `result` which sums over all the different results for all of the different repetitions.\n\nThe `histogram` method can also be given a `fold_func` argument, in order to group measurement results under some key before counting them up.\nFor example, we can group by whether or not the two measurement results agreed:\n\n\n```\nprint(result.histogram(key=\"a,b\", fold_func=lambda bits: \"agree\" if bits[0] == bits[1] else \"disagree\"))\n```\n\n    Counter({'disagree': 509, 'agree': 491})\n\n\n## The Deutsch-Jozsa Algorithm\n\nThe very first indication that quantum computers could be more powerful than classical computers was provided by David Deutsch in his 1985 paper\n\n> David Deutsch,  \"[Quantum Theory, the Church-Turing Principle and the Universal Quantum Computer](https://people.eecs.berkeley.edu/~christos/classics/Deutsch_quantum_theory.pdf)\" *Proc. R. Soc. Lond.* A **400** 97\u2013117. http://doi.org/10.1098/rspa.1985.0070\n\nThis algorithm was extended by Deutsch and Richard Jozsa to a more convincing algorithmic seperation and what is now called the Deutsch-Jozsa algorithm.  In this section we will show how to write circuits for the Deutsch algorithm and then as an exercise in using Cirq for algorithms for a small version of the Deutsch-Jozsa algorithm.\n\nLet's begin with the Deutsch algorithm.  In Deutsch's algorithm you are given access to a box which computes a one bit boolean function.  That is it is a box which takes in a bit and outputs a bit.  If we want to be a mathematician or theoretical computer scientist we write the function $f$ as $f: \\{0, 1\\} \\rightarrow \\{0, 1\\}$.  There are exactly four such boolean functions which we can write out in a table\n\n| $x$ | $f_0$ | $f_1$ | $f_x$ | $f_{\\bar{x}}$ |\n| --- |  --- | --- | --- | --- |\n| 0 | 0 | 1 | 0 | 1\n| 1 | 0 | 1 | 1 | 0\n\nThe first two of these are *constant* functions, $f_0$ and $f_1$.  That is they always output a constant value (independent of the input).  The other two $f_x$ and $f_\\bar{x}$ are *balanced*.  Over their inputs $0$ and $1$, they have an equal number of $0$s and $1$s in their truth table.  \n\nWe can now state Deutsch's problem:\n\n> Given access to a one bit input one bit output boolean function, determine by querying the function whether the function is *balanced* or *constant*.\n\nIt shouldn't take you much to convince yourself that in order to solve this problem classically you need to call the function on both possible input values.  The easiest way to see this is just to consider what happens if you query the function on one particular input and notice that, for either input, learning the value of the function does not separate the constant from balanced functions. In summary:\n\n*Classically one must query the binary function twice to distinguish the constant function from the balanced function.*\n\nNow lets turn to the quantum approach to this problem.  There is one bit of book keeping we need to take care of.  Above we have described a classical function on bits that is not reversible.  That is, knowing the values of the output does not allow us to determine uniquely the value of the input.  In order to run this on a quantum computer, however we need to make this computation reversible.  A trick for taking a classical non-reversible function and making it \"quantum happy\" is to compute the value in an extra register and store the input.  Suppose we have an $n$ bit input $x$ and we are computing a (potentially non-reverisble) boolean function $f(x)$.  Then we can implement this via a Unitary $U_f$ that acts like on $n + 1$ qubits\n\n$$\nU_f |x\\rangle |y\\rangle = |x\\rangle | y \\oplus f(x)\\rangle .\n$$\n\nHere $\\oplus$ is addition modulo $2$ (XOR) and we have identified how $U_f$ acts by its action on all computational basis states $|x\\rangle$ ($n$ input qubits) and $|y\\rangle$ ($1$ output qubit). To see that this is reversible one can note that applying the transformation twice returns the state to its original form.\n\nLet's see how to implement these functions in Cirq.\n\n$f_0$ enacts the transform\n$$\n\\begin{eqnarray}\n|00\\rangle &\\rightarrow&  |00\\rangle \\\\\n|01\\rangle &\\rightarrow&  |01\\rangle \\\\\n|10\\rangle &\\rightarrow&  |10\\rangle \\\\\n|11\\rangle &\\rightarrow&  |11\\rangle \\\\\n\\end{eqnarray}\n$$\nWell this is just the identity transform, i.e. an empty circuit.\n\n$f_1$ enacts the transform\n$$\n\\begin{eqnarray}\n|00\\rangle &\\rightarrow&  |01\\rangle \\\\\n|01\\rangle &\\rightarrow&  |00\\rangle \\\\\n|10\\rangle &\\rightarrow&  |11\\rangle \\\\\n|11\\rangle &\\rightarrow&  |10\\rangle \\\\\n\\end{eqnarray}\n$$\nThis is the `cirq.X` bit flip gate on the second qubit.\n\n$f_x$ enacts the transform\n$$\n\\begin{eqnarray}\n|00\\rangle &\\rightarrow&  |00\\rangle \\\\\n|01\\rangle &\\rightarrow&  |01\\rangle \\\\\n|10\\rangle &\\rightarrow&  |11\\rangle \\\\\n|11\\rangle &\\rightarrow&  |10\\rangle \\\\\n\\end{eqnarray}\n$$\nThis is nothing more than a `cirq.CNOT` from the first bit to the second bit.\n\nFinally $f_\\bar{x}$ enacts the transform\n$$\n\\begin{eqnarray}\n|00\\rangle &\\rightarrow&  |01\\rangle \\\\\n|01\\rangle &\\rightarrow&  |00\\rangle \\\\\n|10\\rangle &\\rightarrow&  |10\\rangle \\\\\n|11\\rangle &\\rightarrow&  |11\\rangle \\\\\n\\end{eqnarray}\n$$\nwhich is a `cirq.CNOT` from the first bit to the second bit followed by a `cirq.X` on the second bit.\n\nWe can encapulate these functions into a dictionary from a oracle name to the operations in the circuit needed to enact this function.\n\n\n```\n\"\"\"Store the operations to query each function in a dictionary.\"\"\"\n# Get qubits for the operations to act on.\nq0, q1 = cirq.LineQubit.range(2)\n\n# Define the dictionary of operations. The key of each dictionary entry\n# is the subscript of the function f in the above explanatory text.\noracles = {\n    '0': [],\n    '1': [cirq.X(q1)],\n    'x': [cirq.CNOT(q0, q1)],\n    'notx': [cirq.CNOT(q0, q1), cirq.X(q1)]\n}    \n```\n\nWe now turn to Deutch's algorithm.  Suppose we are given access to the reversible oracle functions we have defined above.  By a similar argument for our irreversible classical functions you can show that you cannot distinguish the balanced from the constant functions by using this oracle only once.  But now we can ask the question: what if we are allowed to query this box in superposition, i.e. what if we can use the power of quantum computing?\n\nDeutsch was able to show that you could solve this problem now, with quantum computers, using only a single query.  To see how this works we need two simple insights.\n\nSuppose that we prepare the second qubit in the superposition state $|-\\rangle=\\frac{1}{\\sqrt{2}}(|0\\rangle-|1\\rangle)$ and apply the oracle.  Then we can check that\n$$ \nU_f |x\\rangle |-\\rangle = U_f|x\\rangle \\frac{1}{\\sqrt{2}}(|0\\rangle -|1\\rangle ) = |x\\rangle \\frac{1}{\\sqrt{2}}(|f(x)\\rangle -|f(x) \\oplus 1\\rangle ) =  (-1)^{f(x)} |x\\rangle |-\\rangle .\n$$  \nThis is the so called \"phase kickback trick\".  By applying $U_f$ onto a target which is in superposition, the value of the function ends up showing up in the global phase.  \n\nHow can we leverage this to distinguish between the constant and balanced functions?  Note that for the constant functions the phase that is applied is the same for all inputs $|x\\rangle$, whereas for the balanced functions the phase is different for each value of $x$.  In other words, if we use the phase kickback trick then for each of the oracles we apply the following transform on the first qubit:\n\n$$\n\\begin{eqnarray}\nf_0 \\rightarrow I, &&\nf_1 \\rightarrow -I, &&\nf_x \\rightarrow Z, &&\nf_\\bar{x} \\rightarrow -Z &&\n\\end{eqnarray}\n$$\n\nNow we only need, on the first qubit, to distinguish between the identity gate and the $Z$ gate.  But we can do this by recalling the identity\n\n$$ \nH Z H = X\n$$\n\nwhere $H$ is the Hamadard gate.\n\nThis means that we can turn a phase flip into a bit flip by applying Hadamards before and after the phase flip.  If we look at the constant and balanced functions we see that this means that the constant functions will be proportional to $I$ and the balanced functions will be proportional to $X$.  If we feed in $|0\\rangle$ to this register, then in the first cases we will only see $|0\\rangle$ and in the second case we will only see $|1\\rangle$.  In other words we will be able to distinguish constant from balanced using a single query of the oracle.\n\nLet's code this up.\n\n\n```\n\"\"\"Creating the circuit used in Deutsch's algorithm.\"\"\"\ndef deutsch_algorithm(oracle):\n    \"\"\"Returns the circuit for Deutsch's algorithm given an input\n    oracle, i.e., a sequence of operations to query a particular function.\n    \"\"\"\n    yield cirq.X(q1)\n    yield cirq.H(q0), cirq.H(q1)\n    yield oracle\n    yield cirq.H(q0)\n    yield cirq.measure(q0)\n\nfor key, oracle in oracles.items():\n    print(f\"Circuit for f_{key}:\")\n    print(cirq.Circuit(deutsch_algorithm(oracle)), end=\"\\n\\n\")\n```\n\n    Circuit for f_0:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\n    \n    1: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    Circuit for f_1:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\n    \n    1: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\n    \n    Circuit for f_x:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\n                  \u2502\n    1: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    Circuit for f_notx:\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500M\u2500\u2500\u2500\n                  \u2502\n    1: \u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n\n\nLets run these circuits a bunch of times to see that the measurement result ends up correctly distinguishing constant from balanced.\n\n\n```\n\"\"\"Simulate each of the circuits.\"\"\"\nsimulator = cirq.Simulator()\nfor key, oracle in oracles.items():\n    result = simulator.run(cirq.Circuit(deutsch_algorithm(oracle)), \n                          repetitions=10)\n    print('oracle: f_{:<4} results: {}'.format(key, result))\n```\n\n    oracle: f_0    results: 0=0000000000\n    oracle: f_1    results: 0=0000000000\n    oracle: f_x    results: 0=1111111111\n    oracle: f_notx results: 0=1111111111\n\n\nWe interpret the simulation results as follows:\n\n- For the first two functions $f_0$ and $f_1$, we always measure $0$. Therefore, we know that these functions are constant.\n- For the second two functions $f_x$ and $f_{\\bar{x}}$, we always measure $1$. Therefore, we know that these functions are balanced.\n\n### Exercise: Two Bit Deutsch-Jozsa Algorithm\n\nAll boolean functions for one input bit are either constant or balanced.  For boolean functions from two input bits not all functions are constant or balanced.  There are two constant functions, $f(x_0, x_1) = 0$ and $f(x_0, x_1)=1$, while there are ${4 \\choose 2} = 6$ balanced functions.  The following code gives you the operations for these functions where we take two input qubits and compute the function in the third qubit.\n\n\n```\n\"\"\"Operations to query all possible functions on two bits.\nTwo of these functions are constant, and six of these functions are balanced.\n\"\"\"\n# Define three qubits to use.\nq0, q1, q2 = cirq.LineQubit.range(3)\n\n# Define the operations to query each of the two constant functions.\nconstant = (\n    [], \n    [cirq.X(q2)]\n)\n\n# Define the operations to query each of the six balanced functions.\nbalanced = (\n    [cirq.CNOT(q0, q2)], \n    [cirq.CNOT(q1, q2)], \n    [cirq.CNOT(q0, q2), cirq.CNOT(q1, q2)],\n    [cirq.CNOT(q0, q2), cirq.X(q2)], \n    [cirq.CNOT(q1, q2), cirq.X(q2)], \n    [cirq.CNOT(q0, q2), cirq.CNOT(q1, q2), cirq.X(q2)]\n)\n```\n\nAn extension of Deutsch's orginal algorithm is the Deutsch-Jozsa algorithm, which can distinguish constant from balanced functions like these using a single query to the oracle.  **The goal of this exercise** is to write a quantum circuit that can distinguish these.\n\n\n```\n\"\"\"Exercise: Write a quantum circuit that can distinguish \nconstant from balanced functions on two bits.\n\"\"\"\ndef your_circuit(oracle):\n    # Your code here!\n    yield oracle\n    # Your code here!\n    yield cirq.measure(q2)\n```\n\nYou can check your circuit by running the follow cell which simulates the circuit for all oracles.\n\n\n```\n\"\"\"Check your answer by running this cell.\"\"\"\nsimulator = cirq.Simulator()\n    \nprint(\"\\nYour result on constant functions:\")\nfor oracle in constant:\n    result = simulator.run(cirq.Circuit(your_circuit(oracle)), repetitions=10)\n    print(result)\n    \nprint(\"\\nYour result on balanced functions:\")\nfor oracle in balanced:\n    result = simulator.run(cirq.Circuit(your_circuit(oracle)), repetitions=10)\n    print(result)\n```\n\n    \n    Your result on constant functions:\n    2=0000000000\n    2=1111111111\n    \n    Your result on balanced functions:\n    2=0000000000\n    2=0000000000\n    2=0000000000\n    2=1111111111\n    2=1111111111\n    2=1111111111\n\n\n#### Solution\n\n\n```\n#@title\ndef dj_circuit(oracle):\n    # Phase kickback trick.\n    yield cirq.X(q2), cirq.H(q2)\n    \n    # Get an equal superposition over input bits.\n    yield cirq.H(q0), cirq.H(q1)\n    \n    # Query the function.\n    yield oracle\n    \n    # Use interference to get result, put last qubit into |1>.\n    yield cirq.H(q0), cirq.H(q1), cirq.H(q2)\n    \n    # Use a final OR gate to put result in final qubit.\n    yield cirq.X(q0), cirq.X(q1), cirq.CCX(q0, q1, q2)\n    yield cirq.measure(q2)\n```\n\nAs above, we can check the solution by running the circuit with each of the oracles.\n\n\n```\n\"\"\"Simulate the Deutsch-Jozsa circuit and check the results.\"\"\"\nprint(\"Result on constant functions:\")\nfor oracle in constant:\n    result = simulator.run(cirq.Circuit(dj_circuit(oracle)), repetitions=10)\n    print(result)\n    \nprint(\"\\nResult on balanced functions:\")\nfor oracle in balanced:\n    result = simulator.run(cirq.Circuit(dj_circuit(oracle)), repetitions=10)\n    print(result)\n```\n\n    Result on constant functions:\n    2=0000000000\n    2=0000000000\n    \n    Result on balanced functions:\n    2=1111111111\n    2=1111111111\n    2=1111111111\n    2=1111111111\n    2=1111111111\n    2=1111111111\n\n\nAs with the single-bit case (Deutsch's algorithm), we always measure $0$ for constant functions and always measure $1$ for balanced functions.\n\n## Gates\n\nCirq comes with a plethora of common gates.  Here we show a few of them.\n\n\n```\n\"\"\"Examples of common gates defined in Cirq.\"\"\"\n# Get some qubits.\nq0, q1, q2 = cirq.LineQubit.range(3)\n\n# Get a bunch of common gates defined in Cirq.\nops = [\n    cirq.X(q0),                # Pauli-X.\n    cirq.Y(q1),                # Pauli-Y.\n    cirq.Z(q2),                # Pauli-Z.\n    cirq.CZ(q0,q1),            # Controlled-Z gate.\n    cirq.CNOT(q1,q2),          # Controlled-X gate.\n    cirq.H(q0),                # Hadamard gate.\n    cirq.T(q1),                # T gate.\n    cirq.S(q2),                # S gate.\n    cirq.CCZ(q0, q1, q2),      # Controlled CZ gate.\n    cirq.SWAP(q0, q1),         # Swap gate.\n    cirq.CSWAP(q0, q1, q2),    # Controlled swap gate.\n    cirq.CCX(q0, q1, q2),      # Toffoli (CCNOT) gate.\n    cirq.ISWAP(q0, q1),        # ISWAP gate.\n    cirq.rx(0.5 * np.pi)(q0),  # Rotation about X.\n    cirq.ry(0.5 * np.pi)(q1),  # Rotation about Y.\n    cirq.rz(0.5 * np.pi)(q2),  # Rotation about Z.\n    cirq.X(q0) ** 0.5,         # Sqrt of NOT gate.\n]\n\n# Display a circuit with all of these operations.\nprint(cirq.Circuit(ops))\n```\n\n    0: \u2500\u2500\u2500X\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u00d7\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500Rx(0.5\u03c0)\u2500\u2500\u2500X^0.5\u2500\u2500\u2500\n              \u2502           \u2502   \u2502   \u2502   \u2502   \u2502\n    1: \u2500\u2500\u2500Y\u2500\u2500\u2500@\u2500\u2500\u2500@\u2500\u2500\u2500T\u2500\u2500\u2500@\u2500\u2500\u2500\u00d7\u2500\u2500\u2500\u00d7\u2500\u2500\u2500@\u2500\u2500\u2500iSwap\u2500\u2500\u2500\u2500\u2500\u2500Ry(0.5\u03c0)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n                  \u2502       \u2502       \u2502   \u2502\n    2: \u2500\u2500\u2500Z\u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500S\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u00d7\u2500\u2500\u2500X\u2500\u2500\u2500Rz(0.5\u03c0)\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\nFor each of these gates, you can figure out how they act on the computational basis by calling `cirq.unitary` on the gate.  For example, to see the unitary of `CNOT`, we can do:\n\n\n```\n\"\"\"Get the unitary of CNOT.\"\"\"\nprint(cirq.unitary(cirq.CNOT))\n```\n\n    [[1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 1.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 0.+0.j 1.+0.j]\n     [0.+0.j 0.+0.j 1.+0.j 0.+0.j]]\n\n\nFor single qubit gates, we have named gates like `cirq.H` for the Hadmard gate as well as the single qubit rotation gates defined as follows.\n\n$$ \n{\\tt cirq.rx(\u03b8)}: \\exp(-i \\theta X) = cos \\theta I - i \\sin \\theta X =\\left[ \\begin{array} ~\\cos \\theta & -i \\sin \\theta \\\\ -i \\sin \\theta & \\cos \\theta\\end{array} \\right] \\\\\n$$ \n$$ \n{\\tt cirq.ry(\u03b8)}: \\exp(-i \\theta Y) = cos \\theta I - i \\sin \\theta Y =\\left[ \\begin{array} ~\\cos \\theta &  -\\sin \\theta \\\\  \\sin \\theta & \\cos \\theta\\end{array} \\right] \\\\\n$$ \n$$ \n{\\tt cirq.rz(\u03b8)}: \\exp(-i \\theta Z) = cos \\theta I - i \\sin \\theta Z =\\left[ \\begin{array} ~e^{i \\theta} & 0 \\\\ 0 & e^{-i \\theta} \\end{array} \\right] \\\\\n$$ \n\nIn addition to `cirq.unitary` another important method (behind the scenes, anyways) is `cirq.apply_unitary`.  This allows you to apply a unitary gate onto a state.  Of course we could have applied the unitary directly to the state, using `cirq.unitary`.   We'll see below in understanding how these methods are implemented that the `cirq.apply_unitary` can be used to apply the gate more directly onto the state and can save allocations of memory to store the unitary.  \n\nIf we apply `cirq.rx` to a state we can see how it rotates the state.  To do this let us introduce a new simulate method `simulate_moment_steps`.  This allows us to simulate the circuit `Moment` by `Moment`.  At each point we can access the state.  For example here we can use this to create a circuit that is a series of small `cirq.rx` rotations and plot the probablility of measuring the state in the $|0\\rangle$ state:\n\n\n```\n\"\"\"Plot the probability of measuring a qubit in the ground state.\"\"\"\n# Get a qubit.\na = cirq.NamedQubit('a')\n\n# Get a circuit of a bunch of X rotations.\ncircuit = cirq.Circuit([cirq.rx(np.pi / 50.0)(a) for theta in range(200)])\n\n# List to store probabilities of the ground state.\nprobs = []\n\n# Step through the simulation results.\nfor step in simulator.simulate_moment_steps(circuit):\n    prob = np.abs(step.state_vector()) ** 2\n    probs.append(prob[0])\n\n# Plot the probability of the ground state at each simulation step.\nplt.style.use('seaborn-whitegrid')\nplt.plot(probs, 'o')\nplt.xlabel(\"Step\")\nplt.ylabel(\"Probability of ground state\");\n```\n\nAbove we have given ourselves direct access to the wave function and calculated the exact probabilities.  Suppose we wanted to sample from the wave function at each point instead.  \n\n\n```\n\"\"\"Plot the probability of measuring a qubit in the ground state by sampling.\"\"\"\n# Number of times to sample.\nrepetitions = 100\n\n# List to store the probability of the ground state.\nsampled_probs = []\n\nfor i, step in enumerate(simulator.simulate_moment_steps(circuit)):\n    samples = step.sample([a], repetitions=repetitions)\n    prob = np.sum(samples, axis=0)[0] / repetitions\n    sampled_probs.append(prob)\n    \n\n# Plot the probability of the ground state at each simulation step.\nplt.style.use('seaborn-whitegrid')\nplt.plot(sampled_probs, 'o')\nplt.xlabel(\"Step\")\nplt.ylabel(\"Probability of ground state\");\n```\n\n## Custom gates\n\nSupose there is a gate that you want Cirq to support, but it is not implemented in Cirq.  How do you go about adding a new gate?  \n\nCirq tries to be Pythonic.  One way in which it does this is that it relies on Python's **protocol** pattern.  Protocols are similar to interfaces, in that they define a collection of methods that an object must support to implement a protocol, but different in that this requirement is more informal and not a part of a class or interface declaration.  An object supports a protocol if it implements the methods that the protocol defines.  You're probably familiar with this if you've ever done something like defined your own `Container` in Python.  To do this for an object you simply define the `__contains__`, `__setitem__`, and `__getitem__` methods on your object, and then you can use this object anywere the Container protocol is supported.  \n\nLet's see how this works for defining a custom gate.  The gate we will define is a single qubit gate that has only rational amplitudes. This is based on the famous 3, 4, 5 triangle you may remember from a long ago math class: $3^2 + 4^2 = 5^2$.  Using this observation we can construct normalized vectors and a unitary transform using the ratios of $3$, $4$, and $5$: \n$$\n\\zeta =\\left[ \\begin{array}\n~\\frac{3}{5} & \\frac{4}{5} \\\\\n-\\frac{4}{5} & \\frac{3}{5}\n\\end{array} \\right]\n$$\n\nBelow is a simple implementation of this gate in Cirq.  To do this we simply define a class that inherits from `cirq.SingleQubitGate` and implements the `cirq.SupportsUnitary` protocol by implementing the `_unitary_(self)` method.  We also define an optional `__str__` representation which Cirq will use when printing this gate out in a circuit diagram.\n\n\n```\n\"\"\"Example of defining a custom gate in Cirq.\"\"\"\nclass RationalGate(cirq.SingleQubitGate):\n    \n    def _unitary_(self):\n        return np.array([[3 / 5, 4 / 5], [-4 / 5, 3 / 5]])\n    \n    def __str__(self):\n        return '\u03b6'\n```\n\nWe can now use this custom gate just like any other gate in Cirq.\n\n\n```\n\"\"\"Using the custom gate in a circuit.\"\"\"\na = cirq.NamedQubit('a')\nrg = RationalGate()\nprint(cirq.Circuit(rg(a)))\n```\n\n    a: \u2500\u2500\u2500\u03b6\u2500\u2500\u2500\n\n\nWe can also get its unitary, as shown below, because the `RationalGate` defines a `_unitary_` method.\n\n\n```\nprint(cirq.unitary(rg))\n```\n\n    [[ 0.6  0.8]\n     [-0.8  0.6]]\n\n\nLet's check that we can use this gate in a simulation.\n\n\n```\n\"\"\"Simulate a circuit with a custom gate.\"\"\"\ncircuit = cirq.Circuit(rg(a))\nsimulator = cirq.Simulator()\nresult = simulator.simulate(circuit)\nprint(result.final_state_vector)\n```\n\n    [ 0.6+0.j -0.8+0.j]\n\n\n> *Note on simulating circuits with custom gates.* The `_unitary_` method is extremely inefficient for gates over many qubits. In most cases the method `_apply_unitary_` will be used instead, if it is available.\nThis method allows much more fine grained control on how a unitary is applied to a state, but it is harder to implement, for example because it is expected to use the pre-allocated workspace buffer that was given to it.\nAlmost all of the basic gates we have defined in Cirq have this method implemented. If you need to get performant, custom multi-qubit gates, you should implement a custom `_apply_unitary_` method for such gates.\n\n### Exercise: Custom Controlled Rx gate\n\nRecall that the `cirq.rx` gate is a rotation about the $X$ Pauli axis:\n$$ \n{\\tt cirq.rx(\u03b8)}: \\exp(-i \\theta X) = cos \\theta I - i \\sin \\theta X =\\left[ \\begin{array} ~\\cos \\theta & -i \\sin \\theta \\\\ -i \\sin \\theta & \\cos \\theta\\end{array} \\right] . \\\\\n$$ \n\nAs an exercise, create a two-qubit controlled `cirq.rx` gate defined as follows:\n$$\n{\\tt CRx(\\theta)}:\n\\left[\\begin{array}\n~1 & 0 & 0 & 0 \\\\\n0 & 1 & 0 & 0  \\\\\n0 & 0 & \\cos \\theta & -i \\sin \\theta \\\\\n0 & 0 & -i \\sin \\theta & \\cos \\theta\n\\end{array} \\right] .\n$$\n\n\n```\n\"\"\"Define a custom controlled cirq.rx gate here.\"\"\"\nclass CRx(cirq.TwoQubitGate):\n    def __init__(self, theta):\n        self.theta = theta\n\n    def _unitary_(self):\n        return np.array([\n            # Your code here!\n        ])\n\n\n# Print out its unitary.\nprint(np.around(cirq.unitary(CRx(0.25 * np.pi))))     \n```\n\n    []\n\n\n#### Solution\n\n\n```\n\"\"\"Defining a custom controlled cirq.rx gate.\"\"\"\nclass CRx(cirq.TwoQubitGate):\n    def __init__(self, theta):\n        self.theta = theta\n\n    def _unitary_(self):\n        return np.array([\n            [1, 0, 0, 0],\n            [0, 1, 0, 0],\n            [0, 0, np.cos(self.theta), -1j * np.sin(self.theta)],\n            [0, 0, -1j * np.sin(self.theta), np.cos(self.theta)]\n        ])\n    \n    def _circuit_diagram_info_(self, args):\n        return '@', 'rx({}\u03c0)'.format(self.theta / np.pi)\n\n\n# Print out its unitary.\nprint(np.around(cirq.unitary(CRx(0.25 * np.pi))))    \n```\n\n    [[1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 1.+0.j 0.+0.j 0.+0.j]\n     [0.+0.j 0.+0.j 1.+0.j 0.-1.j]\n     [0.+0.j 0.+0.j 0.-1.j 1.+0.j]]\n\n\nNote that we also define the `_circuit_diagram_info_` method which tells Cirq how to display the gate in a circuit diagram. The first string in the tuple is the symbol for the top wire, and the second string in the tuple is the symbol for the bottom wire. We can use this in a circuit to see the diagram info as shown below.\n\n\n```\n\"\"\"Display a circuit with the custom gate.\"\"\"\n# Get qubits.\na = cirq.NamedQubit('a')\nb = cirq.NamedQubit('b')\n\n# Display the circuit.\nprint('Circuit diagram:')\nprint(cirq.Circuit(CRx(0.25 * np.pi)(a, b)))\n```\n\n    Circuit diagram:\n    a: \u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n          \u2502\n    b: \u2500\u2500\u2500rx(0.25\u03c0)\u2500\u2500\u2500\n\n\n### Gate decompositions\n\nIn many contexts, the notion of what gate you can apply is defined either by the physical hardware you are running or perhaps by the quantum error correcting code you are working with.  In quantum computing we typically talk about **gate sets** and work with respect to a given gate set.  Cirq supports gate decomposition via the `decompose` protocol.  Below we show how one can construct a gate that can be decomposed into two gates.\n\n\n```\n\"\"\"Example of a custom gate which supports the decompose protocol.\"\"\"\nclass HXGate(cirq.SingleQubitGate):\n    \n    def _decompose_(self, qubits):\n        return cirq.H(*qubits), cirq.X(*qubits)\n    \n    def __str__(self):\n        return 'HX'\n```\n\nWe can use this gate in a circuit as follows.\n\n\n```\n\"\"\"Use the gate in a circuit.\"\"\"\nHX = HXGate()\n\na = cirq.NamedQubit('a')\ncircuit = cirq.Circuit(HX(a))\nprint(circuit)\n```\n\n    a: \u2500\u2500\u2500HX\u2500\u2500\u2500\n\n\nThe symbol `HX` is a single gate, not a product of two gates. We can decompose the `HXGate` using `cirq.decompose` as shown below.\n\n\n```\n\"\"\"Decompose the gate.\"\"\"\nprint(cirq.Circuit(cirq.decompose(circuit)))\n```\n\n    a: \u2500\u2500\u2500Y^0.5\u2500\u2500\u2500X\u2500\u2500\u2500X\u2500\u2500\u2500\n\n\nNote that this not only decomposed the `HX` gate into `H` and `X`, it also decomposed `H` into `Y**0.5` and `X`.  In order to decompose only once, one can use `cirq.decompose_once`:\n\n\n```\n\"\"\"Decompose the gate once.\"\"\"\nprint(cirq.Circuit(cirq.decompose_once(HX(a))))\n```\n\n    a: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500\n\n\nWhen we define a gate, it is good practice to give a default decomposition in terms of common gates.  However, often you will want to change this decomposition at run time for the specific hardware or context you are working in.  To do this we can define an interceptor function which does this decomposition before falling back to the default.\n\n\n```\n\"\"\"Define a custom decomposer.\"\"\"\ndef my_decompose(op):\n    if isinstance(op, cirq.GateOperation) and isinstance(op.gate, HXGate):\n        return cirq.Z(*op.qubits), cirq.H(*op.qubits)\n\n# Decompose the circuit according to this custom decomposer.\ncirq.Circuit(cirq.decompose(HX(a), intercepting_decomposer=my_decompose))\n```\n\n\n\n\n<pre style=\"overflow: auto; white-space: pre;\">a: \u2500\u2500\u2500Z\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500X\u2500\u2500\u2500</pre>\n\n\n\nYou can also define a predicate that says which gates to keep without decomposing further. This predicate should return `True` for all gates that should not be decomposed further, and `False` for all gates that should be decomposed further.\n\n> The default predicate is to only keep gates that cannot be decomposed.\n\n\n```\n\"\"\"Define a predicate of which gates to keep without decomposing.\"\"\"\ndef keep_h_and_x(op):\n    return isinstance(op, cirq.GateOperation) and op.gate in [cirq.H, cirq.X]\n\n\n# Decompose the HXGate using a custom predicate for which gates to not decompose.\nprint(cirq.decompose(HX(a), keep=keep_h_and_x))\n```\n\n    [cirq.H(cirq.NamedQubit('a')), cirq.X(cirq.NamedQubit('a'))]\n\n\nIn this case, we see that neither `H` nor `X` have been decomposed, as we have specified in `keep_h_and_x`.\n\n## Parameterized Circuits\n\nIn addition to circuit gates with fixed values, Cirq also supports parameterized gates with symbolic values via `sympy`. These are placeholder values, such as `sympy.Symbol('x')`, that will only be resolved at *run-time*. For simulators these values are resolved by providing a `ParamResolver`.  A `ParamResolver` provides a map from the `Symbol`'s name to its assigned value.  \n\n> Plain Python dictionaries can also be used whenever a `ParamResolver` is needed.\n\n\n```\n\"\"\"Define a circuit with parameterized gates.\"\"\"\n# Import sympy for parameterized values.\nimport sympy as sp\n\n# Get qubits to use in the circuit.\na = cirq.NamedQubit(\"a\")\nb = cirq.NamedQubit(\"b\")\n\n# Define a parameterized value.\nval = sp.Symbol(\"s\")\n\n# Create a circuit.\ncircuit = cirq.Circuit(cirq.X.on(a) ** val, cirq.X.on(b) ** val)\n\n# Display it.\nprint(\"Circuit with parameterized gates:\\n\")\nprint(circuit)\n```\n\n    Circuit with parameterized gates:\n    \n    a: \u2500\u2500\u2500X^s\u2500\u2500\u2500\n    \n    b: \u2500\u2500\u2500X^s\u2500\u2500\u2500\n\n\nWhen we simulate this circuit, we must provide a `param_resolver` as mentioned.\n\n\n```\n\"\"\"Simulate the circuit at multiple parameter values.\"\"\"\nsimulator = cirq.Simulator()\n\n# Simulate the circuit for several values of the parameter.\nfor y in range(5):\n    result = simulator.simulate(circuit, param_resolver={\"s\": y / 4.0})\n    print(\"s={}: {}\\n\".format(y, np.around(result.final_state_vector, 2)))\n```\n\n    s=0: [1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n    \n    s=1: [ 0.6 +0.6j   0.25-0.25j  0.25-0.25j -0.1 -0.1j ]\n    \n    s=2: [0. +0.5j 0.5+0.j  0.5+0.j  0. -0.5j]\n    \n    s=3: [-0.1 +0.1j   0.25+0.25j  0.25+0.25j  0.6 -0.6j ]\n    \n    s=4: [0.+0.j 0.+0.j 0.+0.j 1.+0.j]\n    \n\n\nHere we see that the `Symbol` is used in two gates, and then the resolver provides this value at run time.\n\nParameterized values are most useful in defining what we call a `Study`.  A `Study` is a collection of trials, where each  trial is a run with a particular set of configurations and which may be run repeatedly.  Running a study returns a list of `TrialResult`s per set of fixed parameter values and repetitions.  Example:\n\n\n\n```\n\"\"\"Simulate the circuit at multiple parameter values.\"\"\"\n# Get a list of param resolvers.\nresolvers = [cirq.ParamResolver({'s': y / 8.0}) for y in range(5)]\n\n# Add measurements to the circuit.\ncircuit.append([cirq.measure(a), cirq.measure(b)])\n\n# Simulate the circuit using run_sweep.\nresults = simulator.run_sweep(\n    program=circuit,\n    params=resolvers,\n    repetitions=10\n)\n\nfor i, result in enumerate(results):\n    print('params: {}\\n{}\\n'.format(result.params.param_dict, result))\n```\n\n    params: OrderedDict([('s', 0.0)])\n    a=0000000000\n    b=0000000000\n    \n    params: OrderedDict([('s', 0.125)])\n    a=0000000000\n    b=0000000000\n    \n    params: OrderedDict([('s', 0.25)])\n    a=0000000000\n    b=1001000000\n    \n    params: OrderedDict([('s', 0.375)])\n    a=1110101001\n    b=0001000100\n    \n    params: OrderedDict([('s', 0.5)])\n    a=0000010011\n    b=0100111101\n    \n\n\nAbove we passed in a list of `ParamResolver`s to the `params` parameter of `run_sweep`.  But one can also pass in a `Sweepable`.  There are some useful methods for generating `Sweepable`s, for example to generate an equally spaced set of param resolvers one can use `Linspace`\n\n\n\n```\n\"\"\"Alternative method of getting a sequence of param resolvers.\"\"\"\nlinspace = cirq.Linspace(start=0, stop=1.0, length=11, key='x')\nfor p in linspace:\n    print(p)\n```\n\n    cirq.ParamResolver({'x': 0.0})\n    cirq.ParamResolver({'x': 0.1})\n    cirq.ParamResolver({'x': 0.2})\n    cirq.ParamResolver({'x': 0.3})\n    cirq.ParamResolver({'x': 0.4})\n    cirq.ParamResolver({'x': 0.5})\n    cirq.ParamResolver({'x': 0.6})\n    cirq.ParamResolver({'x': 0.7})\n    cirq.ParamResolver({'x': 0.8})\n    cirq.ParamResolver({'x': 0.9})\n    cirq.ParamResolver({'x': 1.0})\n\n\n### Exercise: Rotate a qubit\n\nLet's do the equivalent of a Rabi-flop experiment.  That is, let's apply a `XPowGate` rotating about the `X` axis for a linearly spaced set of values followed by a computational basis measurement.  The end result should be a plot of the sampled fraction that were $|1\\rangle$ as a function of gates of $X^t$ for $t$ between 0 and $1$ for 100 values of $t$ and each result sampled 100 times.\n\n\n```\n# Your code here!\n\n```\n\n## Noise\n\nIn addition to circuits with unitary gates, Cirq also has support for modeling noisy quantum evolutions. This is useful when modeling what will happen when running on actual hardware.\n\nCirq currently supports noise that fits within the context of *operator sum representations* of noise (a.k.a quantum operations, quantum dyanamical maps, superoperators, etc).  This formalism models the evolution of a density matrix via \n\n$$ \n\\rho \\rightarrow \\sum_k A_k \\rho A_k^\\dagger \n$$\n\nwhere the $A_k$ are *Kraus operators*.  These operators are not necessarily unitary and satisfy the property\n\n$$ \n\\sum_k A_k^\\dagger A_k = I . \n$$\n\nAn example of a noise operator is the depolarizing channel on one qubit.  This takes\n\n$$\n\\rho \\rightarrow (1-p) \\rho + \\frac{p}{3} (X \\rho X + Y \\rho Y + Z \\rho Z) .\n$$\n\nIn Cirq we can define such a channel and use it in a quantum circuit:\n\n\n```\n\"\"\"Create a circuit with a depolarizing channel.\"\"\"\ncircuit = cirq.Circuit(cirq.depolarize(0.2)(a), cirq.measure(a))\nprint(circuit)\n```\n\n    a: \u2500\u2500\u2500D(0.2)\u2500\u2500\u2500M\u2500\u2500\u2500\n\n\nPreviously we saw that gates could implement that `_unitary_` protocol, and by doing so they could be used to perform wave function simulation.  For noise the gates implement the `_channel_` protocol.  Classes that implement this protocol return the Krauss operators on their `_channel_` method.  Thus\n\n\n```\nfor i, kraus in enumerate(cirq.channel(cirq.depolarize(0.2))):\n    print(f\"Kraus operator {i} is:\", kraus, sep=\"\\n\", end=\"\\n\\n\")\n```\n\n    Kraus operator 0 is:\n    [[0.89442719 0.        ]\n     [0.         0.89442719]]\n    \n    Kraus operator 1 is:\n    [[0.        +0.j 0.25819889+0.j]\n     [0.25819889+0.j 0.        +0.j]]\n    \n    Kraus operator 2 is:\n    [[0.+0.j         0.-0.25819889j]\n     [0.+0.25819889j 0.+0.j        ]]\n    \n    Kraus operator 3 is:\n    [[ 0.25819889+0.j  0.        +0.j]\n     [ 0.        +0.j -0.25819889+0.j]]\n    \n\n\nThe Kraus operators are often more conveniently represented in a Pauli basis. We can do this in Cirq as shown below.\n\n\n```\nfor i, krauss in enumerate(cirq.channel(cirq.depolarize(0.2))):\n    pauli_ex = cirq.expand_matrix_in_orthogonal_basis(krauss, cirq.PAULI_BASIS)\n    print(f\"Kraus operator {i} is:\", pauli_ex, sep=\"\\n\", end=\"\\n\\n\")\n```\n\n    Kraus operator 0 is:\n    0.894*I\n    \n    Kraus operator 1 is:\n    0.258*X\n    \n    Kraus operator 2 is:\n    0.258*Y\n    \n    Kraus operator 3 is:\n    0.258*Z\n    \n\n\nIn addition to the wavefunction simulator, Cirq also has a density matrix simulator.  Instead of keeping track of the wavefunction, this simulator keeps track of the density matrix.  It has the same `run` and `simulate` type methods.  For example we can use this to simulate depolarizing channel and return the final density matrix of the system.\n\n\n```\n\"\"\"Example of simulating a noisy circuit with the density matrix simulator.\"\"\"\n# Circuit to simulate.\ncircuit = cirq.Circuit(cirq.depolarize(0.2)(a))\nprint('Circuit:\\n{}\\n'.format(circuit))\n\n# Get the density matrix simulator.\nsimulator = cirq.DensityMatrixSimulator()\n\n# Simulate the circuit and get the final density matrix.\nmatrix = simulator.simulate(circuit).final_density_matrix\nprint('Final density matrix:\\n{}'.format(matrix))\n```\n\n    Circuit:\n    a: \u2500\u2500\u2500D(0.2)\u2500\u2500\u2500\n    \n    Final density matrix:\n    [[0.8666666 +0.j 0.        +0.j]\n     [0.        +0.j 0.13333333+0.j]]\n\n\nOne thing to note is that the density matrix simulator simulates measurement statistically, and not as a channel where the outcome is not known. Consider the following example.\n\n\n```\n\"\"\"Simulating a circuit with measurements using the DensityMatrixSimulator.\"\"\"\n# Get a circuit with measurements.\ncircuit = cirq.Circuit(cirq.depolarize(0.5)(a), cirq.measure(a))\n\n# Simulate with the density matrix multiple times.\ndmat1 = simulator.simulate(circuit).final_density_matrix\ndmat2 = simulator.simulate(circuit).final_density_matrix\n\nprint(np.allclose(dmat1, dmat2))\n```\n\n    False\n\n\nBecause the final density matrix is statistical due to the measurements, the output of the above cell will change when executed multiple times.\n\n### Monte carlo simulations\n\nDensity matrix simulations are more expensive than pure state wave function simulations.  However some channels allow an interpreation of randomly applying one of a fixed set of unitaries with differing probabilites.  For example the depolarizing channel above can be interpretted as: \n\n- With probability $1-p$ apply the identity to the state, and\n- with probability $p$ apply one of the three Pauli matrices $X$, $Y$, or $Z$ with equal probability.\n\nChannels that can be interpretted in this form can be simulating using a wavefunction simulator: when this channel is simulated the simulation will sample a unitary with the appropriate probability.  \n\nFor channels of these type, the channel can, instead of implementing the `_channel_` protocol, implement the `_mixture_` protocol:\n\n\n```\n\"\"\"Use the cirq.mixture protocol on the cirq.depolarize channel.\"\"\"\nfor p, u in cirq.mixture(cirq.depolarize(0.2)):\n    print(\"prob = {}\\nunitary: \\n{}\\n\".format(p, u))\n```\n\n    prob = 0.8\n    unitary: \n    [[1. 0.]\n     [0. 1.]]\n    \n    prob = 0.06666666666666667\n    unitary: \n    [[0.+0.j 1.+0.j]\n     [1.+0.j 0.+0.j]]\n    \n    prob = 0.06666666666666667\n    unitary: \n    [[0.+0.j 0.-1.j]\n     [0.+1.j 0.+0.j]]\n    \n    prob = 0.06666666666666667\n    unitary: \n    [[ 1.+0.j  0.+0.j]\n     [ 0.+0.j -1.+0.j]]\n    \n\n\nIn fact the depolarizing channel does not implement `_channel_`.  Instead it only implements `_mixture_` and the `cirq.channel` method notices this and derives the channel from the mixture.\n\n\n```\n\"\"\"Check if cirq.depolarize has _channel_ and _mixture_ methods.\"\"\"\n# Get a depolarizing channel.\nd = cirq.depolarize(0.2)\n\n# Check if it has _channel_ implemented.\nprint('does cirq.depolarize(0.2) have _channel_? {}'.format('yes' if getattr(d, '_channel_', None) else 'no'))\n\n# Check if it has _mixture_ implemented.\nprint('does cirq.depolarize(0.2) have _mixture_? {}'.format('yes' if getattr(d, '_mixture_', None) else 'no'))\n```\n\n    does cirq.depolarize(0.2) have _channel_? no\n    does cirq.depolarize(0.2) have _mixture_? yes\n\n\nWhen channels implement mixture then, as we said, we can use the wavefunction simulator:\n\n\n```\n\"\"\"Use the wavefunction simulator on a channel that implements the mixture protocol.\"\"\"\ncircuit = cirq.Circuit(cirq.depolarize(0.5).on(a), cirq.measure(a))\nsimulator = cirq.Simulator()\nresult = simulator.run(circuit, repetitions=10)\nprint(result)\n```\n\n    a=0000000110\n\n\nBecause the unitary Kraus operators are applied stochastically, executing the above cell multiple times will produce different outputs.\n\n### Adding noise to circuits and simulations\n\nTo add noise to circuits or during simulations, we provide the notion of a `NoiseModel`.  A `NoiseModel` may add noise operation by operation, or it may add noise moment by moment, or it may add noise across a list of moments.\n\nFor example we can define a noise model that add a single qubit depolarizing for every qubit in each moment.  \n\n\n```\n\"\"\"Adding noise to a circuit.\"\"\"\n# Get a noiseless circuit.\nnoise = cirq.ConstantQubitNoiseModel(cirq.depolarize(0.2))\ncircuit = cirq.Circuit(cirq.H(a), cirq.CNOT(a, b), cirq.measure(a, b))\nprint('Circuit with no noise:\\n{}\\n'.format(circuit))\n\n# Add noise to the circuit.\nsystem_qubits = sorted(circuit.all_qubits())\nnoisy_circuit = cirq.Circuit()\nfor moment in circuit:\n    noisy_circuit.append(noise.noisy_moment(moment, system_qubits))\nprint('Circuit with noise:\\n{}'.format(noisy_circuit))\n```\n\n    Circuit with no noise:\n    a: \u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500M\u2500\u2500\u2500\n              \u2502   \u2502\n    b: \u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500M\u2500\u2500\u2500\n    \n    Circuit with noise:\n    a: \u2500\u2500\u2500H\u2500\u2500\u2500D(0.2)[cirq.VirtualTag()]\u2500\u2500\u2500@\u2500\u2500\u2500D(0.2)[cirq.VirtualTag()]\u2500\u2500\u2500M\u2500\u2500\u2500D(0.2)[cirq.VirtualTag()]\u2500\u2500\u2500\n                                          \u2502                               \u2502\n    b: \u2500\u2500\u2500\u2500\u2500\u2500\u2500D(0.2)[cirq.VirtualTag()]\u2500\u2500\u2500X\u2500\u2500\u2500D(0.2)[cirq.VirtualTag()]\u2500\u2500\u2500M\u2500\u2500\u2500D(0.2)[cirq.VirtualTag()]\u2500\u2500\u2500\n\n\nWe can also pass a noise model into the `cirq.DensityMatrixSimulator` and execute a noisy circuit in this manner.\n\n\n```\n\"\"\"Perform noisy simulation by defining a density matrix simulator with a noise model.\"\"\"\n# Define a noise model.\nnoise = cirq.ConstantQubitNoiseModel(cirq.depolarize(0.2))\n\n# Pass this noise model into the simulator.\nsimulator = cirq.DensityMatrixSimulator(noise=noise)\n\n# Get a circuit to simulate.\ncircuit = cirq.Circuit(cirq.H(a), cirq.CNOT(a, b), cirq.measure(a, b))\n\n# Simulate the circuit in steps.\nfor i, step in enumerate(simulator.simulate_moment_steps(circuit)):\n    print('After step {} state was\\n{}\\n'.format(i, step.density_matrix()))\n```\n\n    After step 0 state was\n    [[0.4333333 +0.j 0.        +0.j 0.31777775+0.j 0.        +0.j]\n     [0.        +0.j 0.06666666+0.j 0.        +0.j 0.04888888+0.j]\n     [0.31777775+0.j 0.        +0.j 0.4333333 +0.j 0.        +0.j]\n     [0.        +0.j 0.04888888+0.j 0.        +0.j 0.06666666+0.j]]\n    \n    After step 1 state was\n    [[0.34859255+0.j 0.        +0.j 0.        +0.j 0.17089382+0.j]\n     [0.        +0.j 0.15140739+0.j 0.02629136+0.j 0.        +0.j]\n     [0.        +0.j 0.02629136+0.j 0.15140739+0.j 0.        +0.j]\n     [0.17089382+0.j 0.        +0.j 0.        +0.j 0.34859255+0.j]]\n    \n    After step 2 state was\n    [[0.75111103+0.j 0.        +0.j 0.        +0.j 0.        +0.j]\n     [0.        +0.j 0.11555554+0.j 0.        +0.j 0.        +0.j]\n     [0.        +0.j 0.        +0.j 0.11555553+0.j 0.        +0.j]\n     [0.        +0.j 0.        +0.j 0.        +0.j 0.01777777+0.j]]\n    \n\n\n## Devices\n\nNISQ algorithms work in a regime where every gate counts.  A key philosophy behind Cirq is that we believe the details of the hardware, the performance characteristics, as well as device constraints, will be key to getting the most out of NISQ algorithms.  Towards this end these hardware features are contained in the `Device` class.\n\nFor example, here is Google's Bristleconde device which we printed out at the start of this notebook.\n\n\n```\nprint(cirq.google.Bristlecone)\n```\n\n                                                 (0, 5)\u2500\u2500\u2500\u2500(0, 6)\n                                                 \u2502         \u2502\n                                                 \u2502         \u2502\n                                        (1, 4)\u2500\u2500\u2500(1, 5)\u2500\u2500\u2500\u2500(1, 6)\u2500\u2500\u2500\u2500(1, 7)\n                                        \u2502        \u2502         \u2502         \u2502\n                                        \u2502        \u2502         \u2502         \u2502\n                               (2, 3)\u2500\u2500\u2500(2, 4)\u2500\u2500\u2500(2, 5)\u2500\u2500\u2500\u2500(2, 6)\u2500\u2500\u2500\u2500(2, 7)\u2500\u2500\u2500(2, 8)\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                      (3, 2)\u2500\u2500\u2500(3, 3)\u2500\u2500\u2500(3, 4)\u2500\u2500\u2500(3, 5)\u2500\u2500\u2500\u2500(3, 6)\u2500\u2500\u2500\u2500(3, 7)\u2500\u2500\u2500(3, 8)\u2500\u2500\u2500(3, 9)\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n             (4, 1)\u2500\u2500\u2500(4, 2)\u2500\u2500\u2500(4, 3)\u2500\u2500\u2500(4, 4)\u2500\u2500\u2500(4, 5)\u2500\u2500\u2500\u2500(4, 6)\u2500\u2500\u2500\u2500(4, 7)\u2500\u2500\u2500(4, 8)\u2500\u2500\u2500(4, 9)\u2500\u2500\u2500(4, 10)\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n    (5, 0)\u2500\u2500\u2500(5, 1)\u2500\u2500\u2500(5, 2)\u2500\u2500\u2500(5, 3)\u2500\u2500\u2500(5, 4)\u2500\u2500\u2500(5, 5)\u2500\u2500\u2500\u2500(5, 6)\u2500\u2500\u2500\u2500(5, 7)\u2500\u2500\u2500(5, 8)\u2500\u2500\u2500(5, 9)\u2500\u2500\u2500(5, 10)\u2500\u2500\u2500(5, 11)\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n             \u2502        \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502        \u2502\n             (6, 1)\u2500\u2500\u2500(6, 2)\u2500\u2500\u2500(6, 3)\u2500\u2500\u2500(6, 4)\u2500\u2500\u2500(6, 5)\u2500\u2500\u2500\u2500(6, 6)\u2500\u2500\u2500\u2500(6, 7)\u2500\u2500\u2500(6, 8)\u2500\u2500\u2500(6, 9)\u2500\u2500\u2500(6, 10)\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n                      \u2502        \u2502        \u2502        \u2502         \u2502         \u2502        \u2502        \u2502\n                      (7, 2)\u2500\u2500\u2500(7, 3)\u2500\u2500\u2500(7, 4)\u2500\u2500\u2500(7, 5)\u2500\u2500\u2500\u2500(7, 6)\u2500\u2500\u2500\u2500(7, 7)\u2500\u2500\u2500(7, 8)\u2500\u2500\u2500(7, 9)\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                               \u2502        \u2502        \u2502         \u2502         \u2502        \u2502\n                               (8, 3)\u2500\u2500\u2500(8, 4)\u2500\u2500\u2500(8, 5)\u2500\u2500\u2500\u2500(8, 6)\u2500\u2500\u2500\u2500(8, 7)\u2500\u2500\u2500(8, 8)\n                                        \u2502        \u2502         \u2502         \u2502\n                                        \u2502        \u2502         \u2502         \u2502\n                                        (9, 4)\u2500\u2500\u2500(9, 5)\u2500\u2500\u2500\u2500(9, 6)\u2500\u2500\u2500\u2500(9, 7)\n                                                 \u2502         \u2502\n                                                 \u2502         \u2502\n                                                 (10, 5)\u2500\u2500\u2500(10, 6)\n\n\nIn a future version, we intend for each `Device` to define a noise model.\n\n`Device`s also contain more information about the timing of the device.  For example here we can calculate the duration of an `X` on the `Bristlecone` device.\n\n\n```\n\"\"\"Get the duration of an operation.\"\"\"\nbrissy = cirq.google.Bristlecone\nop = cirq.X.on(cirq.GridQubit(5, 5))\nprint(brissy.duration_of(op))\n```\n\n    20 ns\n\n\nAnother property of devices is that they can be used to enforce constraints from the hardware, both checking that these constraints are satisfied, but also enforcing the constraints on the device.  For example, on the `Bristlecone` device, a two-qubit gate has the property that one cannot simultaneously perform a pair of two-qubit gates that act on adjacent qubits. So for example if we create such a `Circuit` and validate it using the device, we will see an error.\n\n\n```\n\"\"\"Validate operations on a device.\"\"\"\n# Get adjacent qubits on the Bristlecone device.\nq55 = cirq.GridQubit(5, 5)\nq56 = cirq.GridQubit(5, 6)\nq66 = cirq.GridQubit(6, 6)\nq67 = cirq.GridQubit(6, 7)\n\n# Define operations on adjacent qubits.\nops = [cirq.CZ(q55, q56), cirq.CZ(q66, q67)]\ncircuit = cirq.Circuit(ops)\nprint(circuit)\n\n# cirq.google.Bristlecone.validate_circuit(circuit)\n# (this should throw an error)\n```\n\n    (5, 5): \u2500\u2500\u2500@\u2500\u2500\u2500\n               \u2502\n    (5, 6): \u2500\u2500\u2500@\u2500\u2500\u2500\n    \n    (6, 6): \u2500\u2500\u2500@\u2500\u2500\u2500\n               \u2502\n    (6, 7): \u2500\u2500\u2500@\u2500\u2500\u2500\n\n\nBut more interestingly we could have passed the device into the `Circuit` and it will perform the creation of the circuit (using the insertion semantics as described above) such that the device cannot violate the constraints.\n\n\n```\n\"\"\"Create a circuit for a particular device.\"\"\"\n# Same adjacent operations as above.\nops = [cirq.CZ(q55, q56), cirq.CZ(q66, q67)]\n\n# Create a circuit on the Bristlecone device.\ncircuit = cirq.Circuit(device=cirq.google.Bristlecone)\n\n\n# When we append operations now, they are put into different moments.\ncircuit.append(ops)\nprint(circuit)\n```\n\n    (5, 5): \u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n               \u2502\n    (5, 6): \u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    (6, 6): \u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\n                   \u2502\n    (6, 7): \u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\n\n\n### Exercise: Make a Device\n\nConstruct a device that acts on a square sized lattice, and only allows Hadamard, CZ, and measurement gates.\n\n\n```\n# Your code here!\n```\n\n## Compiling / Optimizing\n\nCirq's philosophy for what are often called compilation steps is slightly non-traditional.  In particular we believe that NISQ devices perform so few gates that many compiliations will be one or a few passes. A useful class of optimization code for this is the `PointOptimizer`. For example, here is a `PointOptimizer` that recognizes that a `X` gate followed by a `Z` gate is equivalent to a `Y` gate\n\n\n```\n\"\"\"Example of defining a custom cirq.PointOptimizer.\"\"\"\nclass XZOptimizer(cirq.PointOptimizer):\n    \"\"\"Replaces an X followed by a Z with a Y.\"\"\"\n    \n    def optimization_at(self, circuit, index, op):\n        # Is the gate an X gate?\n        if isinstance(op, cirq.GateOperation) and (op.gate == cirq.X):\n            next_op_index = circuit.next_moment_operating_on(op.qubits, index + 1)\n            qubit = op.qubits[0]\n            if next_op_index is not None:\n                next_op = circuit.operation_at(qubit, next_op_index)\n                if isinstance(next_op, cirq.GateOperation) and  (next_op.gate == cirq.Z):\n                    new_op = cirq.Y.on(qubit)\n                    return cirq.PointOptimizationSummary(\n                        clear_span = next_op_index - index + 1,\n                        clear_qubits=op.qubits, \n                        new_operations=[new_op])\n        \nopt = XZOptimizer()\ncircuit = cirq.Circuit(cirq.X(a), cirq.Z(a), cirq.CZ(a, b), cirq.X(a))\nprint(\"Before optimizing:\\n{}\\n\". format(circuit))\nopt.optimize_circuit(circuit)\nprint(\"After optimizing:\\n{}\".format(circuit))\n```\n\n    Before optimizing:\n    a: \u2500\u2500\u2500X\u2500\u2500\u2500Z\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500\n                  \u2502\n    b: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    \n    After optimizing:\n    a: \u2500\u2500\u2500Y\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500X\u2500\u2500\u2500\n                  \u2502\n    b: \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\n### Exercise: Simplify flipped CNOTs\n\nWrite an PointOptimizer that performs (greedily) the simplification that\n\n```\na: \u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500H\u2500\u2500\u2500\n          \u2502\nb: \u2500\u2500\u2500H\u2500\u2500\u2500X\u2500\u2500\u2500H\u2500\u2500\u2500\n```\nis equal to\n\n\n```\na: \u2500\u2500\u2500X\u2500\u2500\u2500\n      \u2502\nb: \u2500\u2500\u2500@\u2500\u2500\u2500\n```\n\n\n\n```\n# Your code here!\n```\n\n\n```\n\"\"\"Test your optimizer on this circuit.\"\"\"\ncircuit = cirq.Circuit(\n    cirq.H.on_each(a, b, c), \n    cirq.CNOT(a, b), \n    cirq.H.on_each(a, b), \n    cirq.CZ(a, b)\n)\n# Instantiate your optimizer\n# my_opt = \n\n# And check that it worked.\n# print(my_opt.optimizer_circuit(circuit))\n```\n\n## Google's Xmon Gates\n\nWe built Cirq at Google because we thought that it was important that hardware details flow up through the level of abstractions in a framework for NISQ algorithms.  And we also built it because Google has a class of superconducting qubit devices where we want to explore NISQ algorithms.  \n\nWhat sort of gates does the xmon architecture support?  At the hardware level the basic gate set is rotations about the Pauli $Z$ axis\n\n$$\n\\exp(-iZt) = \\left[ \n\\begin{matrix}\n e^{it} & 0 \\\\\n 0 & e^{-it}\n\\end{matrix}\n\\right]\n$$\n\nRotations about any axis in the Pauli $X$ and $Y$ plane:\n\n$$\n\\exp(-i(\\cos \\theta X + \\sin \\theta Y) t) = \n\\left[\n\\begin{matrix}\n\\cos t & -i\\sin t e^{-i \\theta} \\\\\n-i\\sin t e^{i \\theta} & \\cos t\n\\end{matrix}\n\\right]\n$$\n\nThe two qubit gate is a phase about the $|11\\rangle$ state:\n\n$$\n\\exp(-it |11\\rangle \\langle 11|) =\n\\left[ \n\\begin{matrix}\n1 & 0 & 0 & 0 \\\\\n0 & 1 & 0 & 0 \\\\\n0 & 0 & 1 & 0 \\\\\n0 & 0 & 0 & \\exp(-it)\n\\end{matrix}\n\\right]\n$$\n\nAnd finally measurements in the computational basis.\n\nMany of the common gates in Cirq are directly accessible on this hardware.  To check whether the gate you are using is in the xmon gate set, one can use the `is_supported_operation` as shown below.\n\n\n```\n\"\"\"Check if an operation is supported by the XMON gate set.\"\"\"\n# Get the XMON gate set.\nxmon = cirq.google.gate_sets.XMON\n\n# Check if X is supported.\nxmon.is_supported_operation(cirq.X.on(cirq.NamedQubit(\"a\")))\n```\n\n\n\n\n    True\n\n\n\nThus, `cirq.X` is supported by the xmon gate set. As mentioned above, `cirq.CNOT` is not supported, so the following code block should return `False`.\n\n\n```\n\"\"\"Check if CNOT is supported.\"\"\"\nxmon.is_supported_operation(cirq.CNOT.on(cirq.NamedQubit('a'), cirq.NamedQubit('b')))\n```\n\n\n\n\n    False\n\n\n\nWhen a gate is not a native xmon gate, Cirq can often convert it to an xmon native gate.\n\n\n```\n\"\"\"Convert a gate to xmon gates.\"\"\"\n# Get a converter.\nconverter = cirq.google.ConvertToXmonGates()\n\n# Do the conversion.\nconverted = converter.convert(cirq.CNOT.on(cirq.NamedQubit(\"a\"), cirq.NamedQubit(\"b\")))\nprint(cirq.Circuit(converted))\n```\n\n    a: \u2500\u2500\u2500Z^0.75\u2500\u2500\u2500\u2500X^0.5\u2500\u2500\u2500\u2500S^-1\u2500\u2500\u2500Y^-0.5\u2500\u2500\u2500@\u2500\u2500\u2500S^-1\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500\u2500\u2500Z^-0.75\u2500\u2500\u2500\n                                             \u2502\n    b: \u2500\u2500\u2500X^-0.25\u2500\u2500\u2500Y^-0.5\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500@\u2500\u2500\u2500S^-1\u2500\u2500\u2500Y^0.5\u2500\u2500\u2500X^-0.25\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\nThis isn't very optimized because what it has done is first rely on the decompose of `CNOT` and then decomposed each of these into native xmon gates.  There are many tricks that one can use to simplify xmon gates.  To apply many of these one can use the `cirq.google.optimize_from_xmon` method:\n\n\n```\n\"\"\"Optimize a circuit for the xmon gate set.\"\"\"\ncircuit = cirq.Circuit(\n    cirq.CNOT.on(cirq.NamedQubit(\"a\"), cirq.NamedQubit(\"b\"))\n)\nprint(cirq.google.optimized_for_xmon(circuit))\n```\n\n    a: \u2500\u2500\u2500PhXZ(a=0.375,x=1,z=0)\u2500\u2500\u2500\u2500@\u2500\u2500\u2500PhXZ(a=-0.625,x=1,z=0)\u2500\u2500\u2500\u2500\n                                   \u2502\n    b: \u2500\u2500\u2500PhXZ(a=-0.5,x=0.5,z=0)\u2500\u2500\u2500@\u2500\u2500\u2500PhXZ(a=-0.5,x=0.5,z=-1)\u2500\u2500\u2500\n\n\nBecause xmon gates can be executed on Google hardware, they will need to be transmitted as machine code to the quantum computer.  This means that they have a serialized form.  We use protobuffers as the serialization.  To see what this form looks like we can do the following.\n\n\n```\n\"\"\"Serialize an operation.\"\"\"\nxmon.serialize_op(cirq.X.on(cirq.GridQubit(5, 5)))\n```\n\n\n\n\n    gate {\n      id: \"xy\"\n    }\n    args {\n      key: \"axis_half_turns\"\n      value {\n        arg_value {\n          float_value: 0.0\n        }\n      }\n    }\n    args {\n      key: \"half_turns\"\n      value {\n        arg_value {\n          float_value: 1.0\n        }\n      }\n    }\n    qubits {\n      id: \"5_5\"\n    }\n\n\n\n## Other interesting things in Cirq\n\n**Experiments**. The `cirq.experiments` package can perform and plot the results of some basic experiments for understanding how well a system is performing.\n\n\n\n```\nresult = cirq.experiments.rabi_oscillations(\n    sampler=cirq.Simulator(),  # In the future, sampler could point at real hardware.\n    qubit=cirq.LineQubit(0)\n)\nresult.plot();\n```\n\n**Testing**. The `cirq.testing` package has useful debugging and testing methods like `cirq.testing.assert_implements_consistent_protocols` and `cirq.testing.assert_allclose_up_to_global_phase`.\n\n\n\n```\nclass InconsistentXGate(cirq.SingleQubitGate):\n\n    def _decompose_(self, qubits):\n        yield cirq.H(qubits[0])\n        yield cirq.Z(qubits[0])\n        yield cirq.H(qubits[0])\n\n    def _unitary_(self):\n        return np.array([[0, -1j], [1j, 0]])  # Oops! Y instead of X!\n\n# cirq.testing.assert_decompose_is_consistent_with_unitary(InconsistentXGate())\n```\n\n**Export**. You can export a circuit as Qasm.\n\n\n```\n\"\"\"Export a circuit to Qasm.\"\"\"\na, b, c = cirq.LineQubit.range(3)\ncircuit = cirq.Circuit(cirq.H(a), cirq.H(c), cirq.CNOT(a, b), cirq.CCZ(a, b, c))\nprint(circuit.to_qasm())\n```\n\n    // Generated from Cirq v0.9.1\n    \n    OPENQASM 2.0;\n    include \"qelib1.inc\";\n    \n    \n    // Qubits: [0, 1, 2]\n    qreg q[3];\n    \n    \n    h q[0];\n    h q[2];\n    cx q[0],q[1];\n    h q[2];\n    ccx q[0],q[1],q[2];\n    h q[2];\n    \n\n\nYou can also export a circuit as QUIL:\n\n\n```\n\"\"\"Export a circuit to QUIL.\"\"\"\nprint(circuit.to_quil())\n```\n\n    # Created using Cirq.\n    \n    H 0\n    H 2\n    CNOT 0 1\n    H 2\n    CCNOT 0 1 2\n    H 2\n    \n\n\nYou can also turn a circuit into a link to the drag-and-drop web simulation Quirk (though somewhat inconveniently).\n\n\n```\n\"\"\"Export a circuit to a Quirk URL.\"\"\"\nfrom cirq.contrib.quirk.export_to_quirk import circuit_to_quirk_url\nprint(circuit_to_quirk_url(circuit))\n```\n\n    http://algassert.com/quirk#circuit=%7B%22cols%22%3A%5B%5B%22H%22%2C1%2C%22H%22%5D%2C%5B%22%E2%80%A2%22%2C%22X%22%5D%2C%5B%22%E2%80%A2%22%2C%22%E2%80%A2%22%2C%22Z%22%5D%5D%7D\n\n", "meta": {"hexsha": "1299f46a079b1fecb58623b8ba9f0205be87d506", "size": 183921, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/educators/intro.ipynb", "max_stars_repo_name": "alex-treebeard/Cirq", "max_stars_repo_head_hexsha": "10594c0edf7a4c26d5d21f985c6dc391197d3075", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-05T19:47:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T19:47:55.000Z", "max_issues_repo_path": "docs/tutorials/educators/intro.ipynb", "max_issues_repo_name": "rohitvuppala/Cirq", "max_issues_repo_head_hexsha": "0ff2894e053e4ce3bb1b54e9b9de1cc4345d10b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-01-11T10:35:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-28T19:17:02.000Z", "max_forks_repo_path": "docs/tutorials/educators/intro.ipynb", "max_forks_repo_name": "rohitvuppala/Cirq", "max_forks_repo_head_hexsha": "0ff2894e053e4ce3bb1b54e9b9de1cc4345d10b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-30T21:50:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T21:50:00.000Z", "avg_line_length": 49.7621753247, "max_line_length": 26692, "alphanum_fraction": 0.6797103104, "converted": true, "num_tokens": 22505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15203225314838129, "lm_q2_score": 0.0705595927669805, "lm_q1q2_score": 0.010727333869596272}}
{"text": "<a href=\"https://colab.research.google.com/github/tyoc213/fastai_xla_extensions/blob/explorations1/explore_nbs/Printing%2BResnet%2Bbatch_tfms%2Bheat.ipynb\" target=\"_parent\"></a>\n\n\n```\nVERSION = \"20200707\" #\"nightly\"  #\"20200515\" @param [\"1.5\" , \"20200325\", \"nightly\"]\n!curl https://raw.githubusercontent.com/pytorch/xla/master/contrib/scripts/env-setup.py -o pytorch-xla-env-setup.py\n!python pytorch-xla-env-setup.py\n```\n\n      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current\n                                     Dload  Upload   Total   Spent    Left  Speed\n    100  5115  100  5115    0     0  53842      0 --:--:-- --:--:-- --:--:-- 53842\n    Updating... This may take around 2 minutes.\n    Updating TPU runtime to pytorch-dev20200515 ...\n    Collecting cloud-tpu-client\n      Downloading https://files.pythonhosted.org/packages/56/9f/7b1958c2886db06feb5de5b2c191096f9e619914b6c31fdf93999fdbbd8b/cloud_tpu_client-0.10-py3-none-any.whl\n    Collecting google-api-python-client==1.8.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/9a/b4/a955f393b838bc47cbb6ae4643b9d0f90333d3b4db4dc1e819f36aad18cc/google_api_python_client-1.8.0-py3-none-any.whl (57kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 61kB 2.6MB/s \n    \u001b[?25hRequirement already satisfied: oauth2client in /usr/local/lib/python3.6/dist-packages (from cloud-tpu-client) (4.1.3)\n    Requirement already satisfied: google-api-core<2dev,>=1.13.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client==1.8.0->cloud-tpu-client) (1.16.0)\n    Requirement already satisfied: httplib2<1dev,>=0.9.2 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client==1.8.0->cloud-tpu-client) (0.17.4)\n    Requirement already satisfied: google-auth>=1.4.1 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client==1.8.0->cloud-tpu-client) (1.17.2)\n    Requirement already satisfied: six<2dev,>=1.6.1 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client==1.8.0->cloud-tpu-client) (1.12.0)\n    Requirement already satisfied: google-auth-httplib2>=0.0.3 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client==1.8.0->cloud-tpu-client) (0.0.4)\n    Requirement already satisfied: uritemplate<4dev,>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client==1.8.0->cloud-tpu-client) (3.0.1)\n    Requirement already satisfied: pyasn1>=0.1.7 in /usr/local/lib/python3.6/dist-packages (from oauth2client->cloud-tpu-client) (0.4.8)\n    Requirement already satisfied: rsa>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from oauth2client->cloud-tpu-client) (4.6)\n    Requirement already satisfied: pyasn1-modules>=0.0.5 in /usr/local/lib/python3.6/dist-packages (from oauth2client->cloud-tpu-client) (0.2.8)\n    Requirement already satisfied: googleapis-common-protos<2.0dev,>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from google-api-core<2dev,>=1.13.0->google-api-python-client==1.8.0->cloud-tpu-client) (1.52.0)\n    Requirement already satisfied: pytz in /usr/local/lib/python3.6/dist-packages (from google-api-core<2dev,>=1.13.0->google-api-python-client==1.8.0->cloud-tpu-client) (2018.9)\n    Requirement already satisfied: requests<3.0.0dev,>=2.18.0 in /usr/local/lib/python3.6/dist-packages (from google-api-core<2dev,>=1.13.0->google-api-python-client==1.8.0->cloud-tpu-client) (2.23.0)\n    Requirement already satisfied: protobuf>=3.4.0 in /usr/local/lib/python3.6/dist-packages (from google-api-core<2dev,>=1.13.0->google-api-python-client==1.8.0->cloud-tpu-client) (3.12.2)\n    Requirement already satisfied: setuptools>=34.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-core<2dev,>=1.13.0->google-api-python-client==1.8.0->cloud-tpu-client) (49.1.0)\n    Uninstalling torch-1.5.1+cu101:\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth>=1.4.1->google-api-python-client==1.8.0->cloud-tpu-client) (4.1.1)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0dev,>=2.18.0->google-api-core<2dev,>=1.13.0->google-api-python-client==1.8.0->cloud-tpu-client) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0dev,>=2.18.0->google-api-core<2dev,>=1.13.0->google-api-python-client==1.8.0->cloud-tpu-client) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0dev,>=2.18.0->google-api-core<2dev,>=1.13.0->google-api-python-client==1.8.0->cloud-tpu-client) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0dev,>=2.18.0->google-api-core<2dev,>=1.13.0->google-api-python-client==1.8.0->cloud-tpu-client) (2020.6.20)\n    Installing collected packages: google-api-python-client, cloud-tpu-client\n      Found existing installation: google-api-python-client 1.7.12\n        Uninstalling google-api-python-client-1.7.12:\n          Successfully uninstalled google-api-python-client-1.7.12\n    Successfully installed cloud-tpu-client-0.10 google-api-python-client-1.8.0\n    Done updating TPU runtime\n      Successfully uninstalled torch-1.5.1+cu101\n    Uninstalling torchvision-0.6.1+cu101:\n      Successfully uninstalled torchvision-0.6.1+cu101\n    Copying gs://tpu-pytorch/wheels/torch-nightly+20200515-cp36-cp36m-linux_x86_64.whl...\n    \\ [1 files][ 91.0 MiB/ 91.0 MiB]                                                \n    Operation completed over 1 objects/91.0 MiB.                                     \n    Copying gs://tpu-pytorch/wheels/torch_xla-nightly+20200515-cp36-cp36m-linux_x86_64.whl...\n    \\ [1 files][119.5 MiB/119.5 MiB]                                                \n    Operation completed over 1 objects/119.5 MiB.                                    \n    Copying gs://tpu-pytorch/wheels/torchvision-nightly+20200515-cp36-cp36m-linux_x86_64.whl...\n    / [1 files][  2.3 MiB/  2.3 MiB]                                                \n    Operation completed over 1 objects/2.3 MiB.                                      \n    Processing ./torch-nightly+20200515-cp36-cp36m-linux_x86_64.whl\n    Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from torch==nightly+20200515) (0.16.0)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from torch==nightly+20200515) (1.18.5)\n    \u001b[31mERROR: fastai 1.0.61 requires torchvision, which is not installed.\u001b[0m\n    Installing collected packages: torch\n    Successfully installed torch-1.6.0a0+bf2bbd9\n    Processing ./torch_xla-nightly+20200515-cp36-cp36m-linux_x86_64.whl\n    Installing collected packages: torch-xla\n    Successfully installed torch-xla-1.6+2b2085a\n    Processing ./torchvision-nightly+20200515-cp36-cp36m-linux_x86_64.whl\n    Requirement already satisfied: pillow>=4.1.1 in /usr/local/lib/python3.6/dist-packages (from torchvision==nightly+20200515) (7.0.0)\n    Requirement already satisfied: torch in /usr/local/lib/python3.6/dist-packages (from torchvision==nightly+20200515) (1.6.0a0+bf2bbd9)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from torchvision==nightly+20200515) (1.18.5)\n    Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from torch->torchvision==nightly+20200515) (0.16.0)\n    Installing collected packages: torchvision\n    Successfully installed torchvision-0.7.0a0+a6073f0\n    Reading package lists... Done\n    Building dependency tree       \n    Reading state information... Done\n    The following package was automatically installed and is no longer required:\n      libnvidia-common-440\n    Use 'apt autoremove' to remove it.\n    The following NEW packages will be installed:\n      libomp5\n    0 upgraded, 1 newly installed, 0 to remove and 35 not upgraded.\n    Need to get 234 kB of archives.\n    After this operation, 774 kB of additional disk space will be used.\n    Get:1 http://archive.ubuntu.com/ubuntu bionic/universe amd64 libomp5 amd64 5.0.1-1 [234 kB]\n    Fetched 234 kB in 1s (374 kB/s)\n    Selecting previously unselected package libomp5:amd64.\n    (Reading database ... 144465 files and directories currently installed.)\n    Preparing to unpack .../libomp5_5.0.1-1_amd64.deb ...\n    Unpacking libomp5:amd64 (5.0.1-1) ...\n    Setting up libomp5:amd64 (5.0.1-1) ...\n    Processing triggers for libc-bin (2.27-3ubuntu1) ...\n    /sbin/ldconfig.real: /usr/local/lib/python3.6/dist-packages/ideep4py/lib/libmkldnn.so.0 is not a symbolic link\n    \n\n\n\n```\n!pip install https://github.com/fastai/fastcore/archive/master.zip\n!pip install https://github.com/fastai/fastai2/archive/master.zip\n```\n\n    Collecting https://github.com/fastai/fastcore/archive/master.zip\n    \u001b[?25l  Downloading https://github.com/fastai/fastcore/archive/master.zip\n    \u001b[K     - 3.5MB 2.1MB/s\n    \u001b[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from fastcore==0.1.18) (1.18.5)\n    Requirement already satisfied: dataclasses>='0.7' in /usr/local/lib/python3.6/dist-packages (from fastcore==0.1.18) (0.7)\n    Building wheels for collected packages: fastcore\n      Building wheel for fastcore (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for fastcore: filename=fastcore-0.1.18-cp36-none-any.whl size=28891 sha256=36950ebbe97c27ebcc38471ed8b876294aa4547427aa1e604b3cabdaf90ed9eb\n      Stored in directory: /tmp/pip-ephem-wheel-cache-1e3_h2zu/wheels/68/af/c5/c8a9f7370515ab9b237b3fd59c04a0e7c5d4dedc7a6768a772\n    Successfully built fastcore\n    Installing collected packages: fastcore\n    Successfully installed fastcore-0.1.18\n    Collecting https://github.com/fastai/fastai2/archive/master.zip\n    \u001b[?25l  Downloading https://github.com/fastai/fastai2/archive/master.zip\n    \u001b[K     - 121.7MB 795kB/s\n    \u001b[?25hRequirement already satisfied: fastcore in /usr/local/lib/python3.6/dist-packages (from fastai2==0.0.18) (0.1.18)\n    Requirement already satisfied: torch>=1.3.0 in /usr/local/lib/python3.6/dist-packages (from fastai2==0.0.18) (1.6.0a0+bf2bbd9)\n    Requirement already satisfied: torchvision>=0.5 in /usr/local/lib/python3.6/dist-packages (from fastai2==0.0.18) (0.7.0a0+a6073f0)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.6/dist-packages (from fastai2==0.0.18) (3.2.2)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from fastai2==0.0.18) (1.0.5)\n    Requirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from fastai2==0.0.18) (2.23.0)\n    Requirement already satisfied: pyyaml in /usr/local/lib/python3.6/dist-packages (from fastai2==0.0.18) (3.13)\n    Requirement already satisfied: fastprogress>=0.1.22 in /usr/local/lib/python3.6/dist-packages (from fastai2==0.0.18) (0.2.3)\n    Requirement already satisfied: pillow in /usr/local/lib/python3.6/dist-packages (from fastai2==0.0.18) (7.0.0)\n    Requirement already satisfied: scikit-learn in /usr/local/lib/python3.6/dist-packages (from fastai2==0.0.18) (0.22.2.post1)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from fastai2==0.0.18) (1.4.1)\n    Requirement already satisfied: spacy in /usr/local/lib/python3.6/dist-packages (from fastai2==0.0.18) (2.2.4)\n    Requirement already satisfied: dataclasses>='0.7'; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from fastcore->fastai2==0.0.18) (0.7)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from fastcore->fastai2==0.0.18) (1.18.5)\n    Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from torch>=1.3.0->fastai2==0.0.18) (0.16.0)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib->fastai2==0.0.18) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->fastai2==0.0.18) (1.2.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->fastai2==0.0.18) (2.4.7)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->fastai2==0.0.18) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas->fastai2==0.0.18) (2018.9)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->fastai2==0.0.18) (3.0.4)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->fastai2==0.0.18) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->fastai2==0.0.18) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->fastai2==0.0.18) (2020.6.20)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->fastai2==0.0.18) (0.16.0)\n    Requirement already satisfied: murmurhash<1.1.0,>=0.28.0 in /usr/local/lib/python3.6/dist-packages (from spacy->fastai2==0.0.18) (1.0.2)\n    Requirement already satisfied: wasabi<1.1.0,>=0.4.0 in /usr/local/lib/python3.6/dist-packages (from spacy->fastai2==0.0.18) (0.7.0)\n    Requirement already satisfied: blis<0.5.0,>=0.4.0 in /usr/local/lib/python3.6/dist-packages (from spacy->fastai2==0.0.18) (0.4.1)\n    Requirement already satisfied: tqdm<5.0.0,>=4.38.0 in /usr/local/lib/python3.6/dist-packages (from spacy->fastai2==0.0.18) (4.41.1)\n    Requirement already satisfied: preshed<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from spacy->fastai2==0.0.18) (3.0.2)\n    Requirement already satisfied: cymem<2.1.0,>=2.0.2 in /usr/local/lib/python3.6/dist-packages (from spacy->fastai2==0.0.18) (2.0.3)\n    Requirement already satisfied: catalogue<1.1.0,>=0.0.7 in /usr/local/lib/python3.6/dist-packages (from spacy->fastai2==0.0.18) (1.0.0)\n    Requirement already satisfied: thinc==7.4.0 in /usr/local/lib/python3.6/dist-packages (from spacy->fastai2==0.0.18) (7.4.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from spacy->fastai2==0.0.18) (49.1.0)\n    Requirement already satisfied: srsly<1.1.0,>=1.0.2 in /usr/local/lib/python3.6/dist-packages (from spacy->fastai2==0.0.18) (1.0.2)\n    Requirement already satisfied: plac<1.2.0,>=0.9.6 in /usr/local/lib/python3.6/dist-packages (from spacy->fastai2==0.0.18) (1.1.3)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from cycler>=0.10->matplotlib->fastai2==0.0.18) (1.12.0)\n    Requirement already satisfied: importlib-metadata>=0.20; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from catalogue<1.1.0,>=0.0.7->spacy->fastai2==0.0.18) (1.7.0)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata>=0.20; python_version < \"3.8\"->catalogue<1.1.0,>=0.0.7->spacy->fastai2==0.0.18) (3.1.0)\n    Building wheels for collected packages: fastai2\n      Building wheel for fastai2 (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for fastai2: filename=fastai2-0.0.18-cp36-none-any.whl size=175594 sha256=2d921efd963d6f8fb2b1d7a710bf76a9be354aea3ecd090db9583f82a05ed1b3\n      Stored in directory: /tmp/pip-ephem-wheel-cache-1od2hht4/wheels/b2/28/3b/7a38644c6129e851e0db09b594949028266a62f4cb234fd1f3\n    Successfully built fastai2\n    Installing collected packages: fastai2\n    Successfully installed fastai2-0.0.18\n\n\n\n```\n!pip install py-heat-magic\n```\n\n    Collecting py-heat-magic\n      Downloading https://files.pythonhosted.org/packages/72/15/c5c56c91077ecb42a6415364cff41acb08a4f696f0261b3fc4025856d85c/py-heat-magic-0.0.2.tar.gz\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from py-heat-magic) (1.18.5)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from py-heat-magic) (1.4.1)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.6/dist-packages (from py-heat-magic) (3.2.2)\n    Requirement already satisfied: ipython in /usr/local/lib/python3.6/dist-packages (from py-heat-magic) (5.5.0)\n    Requirement already satisfied: jupyter in /usr/local/lib/python3.6/dist-packages (from py-heat-magic) (1.0.0)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from py-heat-magic) (1.0.5)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.6/dist-packages (from py-heat-magic) (1.1.1)\n    Collecting nose\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/15/d8/dd071918c040f50fa1cf80da16423af51ff8ce4a0f2399b7bf8de45ac3d9/nose-1.3.7-py3-none-any.whl (154kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 163kB 3.5MB/s \n    \u001b[?25hCollecting py-heat\n      Downloading https://files.pythonhosted.org/packages/6b/e3/776c6f4f18eafbc39b44ad47160414077bfd64183cfd2c5b61ea43dd12b6/py-heat-0.0.6.tar.gz\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->py-heat-magic) (1.2.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->py-heat-magic) (2.4.7)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->py-heat-magic) (2.8.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib->py-heat-magic) (0.10.0)\n    Requirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.6/dist-packages (from ipython->py-heat-magic) (0.8.1)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.6/dist-packages (from ipython->py-heat-magic) (4.4.2)\n    Requirement already satisfied: traitlets>=4.2 in /usr/local/lib/python3.6/dist-packages (from ipython->py-heat-magic) (4.3.3)\n    Requirement already satisfied: pickleshare in /usr/local/lib/python3.6/dist-packages (from ipython->py-heat-magic) (0.7.5)\n    Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.6/dist-packages (from ipython->py-heat-magic) (1.0.18)\n    Requirement already satisfied: pexpect; sys_platform != \"win32\" in /usr/local/lib/python3.6/dist-packages (from ipython->py-heat-magic) (4.8.0)\n    Requirement already satisfied: setuptools>=18.5 in /usr/local/lib/python3.6/dist-packages (from ipython->py-heat-magic) (49.1.0)\n    Requirement already satisfied: pygments in /usr/local/lib/python3.6/dist-packages (from ipython->py-heat-magic) (2.1.3)\n    Requirement already satisfied: nbconvert in /usr/local/lib/python3.6/dist-packages (from jupyter->py-heat-magic) (5.6.1)\n    Requirement already satisfied: notebook in /usr/local/lib/python3.6/dist-packages (from jupyter->py-heat-magic) (5.2.2)\n    Requirement already satisfied: jupyter-console in /usr/local/lib/python3.6/dist-packages (from jupyter->py-heat-magic) (5.2.0)\n    Requirement already satisfied: qtconsole in /usr/local/lib/python3.6/dist-packages (from jupyter->py-heat-magic) (4.7.5)\n    Requirement already satisfied: ipykernel in /usr/local/lib/python3.6/dist-packages (from jupyter->py-heat-magic) (4.10.1)\n    Requirement already satisfied: ipywidgets in /usr/local/lib/python3.6/dist-packages (from jupyter->py-heat-magic) (7.5.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas->py-heat-magic) (2018.9)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy->py-heat-magic) (1.1.0)\n    Collecting pprofile\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/dd/db/198fd60559f77c5334f520e2a94cde5c8c6f5f4e65f82f5b22269e6e5ff2/pprofile-2.0.5.tar.gz (54kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 61kB 5.5MB/s \n    \u001b[?25hRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.6/dist-packages (from python-dateutil>=2.1->matplotlib->py-heat-magic) (1.12.0)\n    Requirement already satisfied: ipython-genutils in /usr/local/lib/python3.6/dist-packages (from traitlets>=4.2->ipython->py-heat-magic) (0.2.0)\n    Requirement already satisfied: wcwidth in /usr/local/lib/python3.6/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython->py-heat-magic) (0.2.5)\n    Requirement already satisfied: ptyprocess>=0.5 in /usr/local/lib/python3.6/dist-packages (from pexpect; sys_platform != \"win32\"->ipython->py-heat-magic) (0.6.0)\n    Requirement already satisfied: mistune<2,>=0.8.1 in /usr/local/lib/python3.6/dist-packages (from nbconvert->jupyter->py-heat-magic) (0.8.4)\n    Requirement already satisfied: nbformat>=4.4 in /usr/local/lib/python3.6/dist-packages (from nbconvert->jupyter->py-heat-magic) (5.0.7)\n    Requirement already satisfied: testpath in /usr/local/lib/python3.6/dist-packages (from nbconvert->jupyter->py-heat-magic) (0.4.4)\n    Requirement already satisfied: defusedxml in /usr/local/lib/python3.6/dist-packages (from nbconvert->jupyter->py-heat-magic) (0.6.0)\n    Requirement already satisfied: jinja2>=2.4 in /usr/local/lib/python3.6/dist-packages (from nbconvert->jupyter->py-heat-magic) (2.11.2)\n    Requirement already satisfied: entrypoints>=0.2.2 in /usr/local/lib/python3.6/dist-packages (from nbconvert->jupyter->py-heat-magic) (0.3)\n    Requirement already satisfied: bleach in /usr/local/lib/python3.6/dist-packages (from nbconvert->jupyter->py-heat-magic) (3.1.5)\n    Requirement already satisfied: jupyter-core in /usr/local/lib/python3.6/dist-packages (from nbconvert->jupyter->py-heat-magic) (4.6.3)\n    Requirement already satisfied: pandocfilters>=1.4.1 in /usr/local/lib/python3.6/dist-packages (from nbconvert->jupyter->py-heat-magic) (1.4.2)\n    Requirement already satisfied: terminado>=0.3.3; sys_platform != \"win32\" in /usr/local/lib/python3.6/dist-packages (from notebook->jupyter->py-heat-magic) (0.8.3)\n    Requirement already satisfied: jupyter-client in /usr/local/lib/python3.6/dist-packages (from notebook->jupyter->py-heat-magic) (5.3.5)\n    Requirement already satisfied: tornado>=4 in /usr/local/lib/python3.6/dist-packages (from notebook->jupyter->py-heat-magic) (4.5.3)\n    Requirement already satisfied: qtpy in /usr/local/lib/python3.6/dist-packages (from qtconsole->jupyter->py-heat-magic) (1.9.0)\n    Requirement already satisfied: pyzmq>=17.1 in /usr/local/lib/python3.6/dist-packages (from qtconsole->jupyter->py-heat-magic) (19.0.1)\n    Requirement already satisfied: widgetsnbextension~=3.5.0 in /usr/local/lib/python3.6/dist-packages (from ipywidgets->jupyter->py-heat-magic) (3.5.1)\n    Requirement already satisfied: jsonschema!=2.5.0,>=2.4 in /usr/local/lib/python3.6/dist-packages (from nbformat>=4.4->nbconvert->jupyter->py-heat-magic) (2.6.0)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.6/dist-packages (from jinja2>=2.4->nbconvert->jupyter->py-heat-magic) (1.1.1)\n    Requirement already satisfied: webencodings in /usr/local/lib/python3.6/dist-packages (from bleach->nbconvert->jupyter->py-heat-magic) (0.5.1)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.6/dist-packages (from bleach->nbconvert->jupyter->py-heat-magic) (20.4)\n    Building wheels for collected packages: py-heat-magic, py-heat, pprofile\n      Building wheel for py-heat-magic (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for py-heat-magic: filename=py_heat_magic-0.0.2-cp36-none-any.whl size=3161 sha256=f98d9a7fdf2188985e1a1d9825d997f3ba748b2359e86bbf2e48674407327521\n      Stored in directory: /root/.cache/pip/wheels/a0/4c/14/8858096734820b8a1eece9f174fe4a96d199ba247a671dc7ed\n      Building wheel for py-heat (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for py-heat: filename=py_heat-0.0.6-py2.py3-none-any.whl size=7801 sha256=74513465d758625bd4d9c4348b5d9604068b6296111eaa919ebed7cf5c2ebf18\n      Stored in directory: /root/.cache/pip/wheels/9d/3d/b7/e191bd2f2d8c0a6fc5008a87cdf69d6bc009ee3e22149c3ef3\n      Building wheel for pprofile (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pprofile: filename=pprofile-2.0.5-cp36-none-any.whl size=34838 sha256=ba4dd228bb5da0055d2151f28686e85c73f11a3e69248e5bd220e23e790eda39\n      Stored in directory: /root/.cache/pip/wheels/b7/7e/dc/fa6663a43280716fe9a4fedfcfaae1e22fc26c701afff093c6\n    Successfully built py-heat-magic py-heat pprofile\n    Installing collected packages: nose, pprofile, py-heat, py-heat-magic\n    Successfully installed nose-1.3.7 pprofile-2.0.5 py-heat-0.0.6 py-heat-magic-0.0.2\n\n\n\n```\n%load_ext heat\n```\n\n\n```\n%%heat\n#import pdb\nprint(\"---------------------------------------------------------- START\")\n#import torch\nimport torch_xla.core.xla_model as xm\n\ntpu_device = xm.xla_device()\n#tpu_device = torch.device('cuda:0') #torch.cuda.device(\"cuda:0\")#.current_device()\nprint(f\"device is {tpu_device}\")\nprint(\"---------------------------------------------------------- START:1\")\n\nfrom fastai2.vision.all import *\npath = untar_data(URLs.MNIST)\ndatablock = DataBlock(\n    blocks=(ImageBlock,CategoryBlock),\n    get_items=get_image_files,\n    get_y=parent_label,\n    splitter=RandomSubsetSplitter(train_sz=0.001,valid_sz=0.001),#GrandparentSplitter(train_name='training',valid_name='testing'),\n#    item_tfms=Resize(28),\n    #batch_tfms=aug_transforms(size=224)\n    batch_tfms=aug_transforms(size=224,min_scale=0.75)\n)\nprint(\"---------------------------------------------------------- START:2\")\n\n#datablock.summary(path)\n\n# %%\nprinted_device=0\nprinted_device2=0\nNUM_PIXELS=3 # 1 single channedl 3 rgb\nNUM_OUTPUTS=10 #2 for MNIST_TINY 10 MNIST\nclass Lenet2(nn.Module):\n    \"\"\"Lenet with layers\"\"\"\n    def __init__(self):\n        super(Lenet2, self).__init__()\n        self.conv1 = nn.Conv2d(NUM_PIXELS, 6, 3) # set 3 for first item if RGB\n        self.conv2 = nn.Conv2d(6, 16, 3)\n        self.fc1 = nn.Linear(46656, 120) #(400, 120)\n        self.fc2 = nn.Linear(120, 84)\n        self.fc3 = nn.Linear(84, NUM_OUTPUTS) # Only 2 outputs (3 and 7) instead of 10\n    def forward(self, x):\n        global printed_device\n        if x.device != tpu_device:\n          print(f\"************** ######################### EL DEVICE ES {tpu_device} no es {x.device} ######################### **************\") if printed_device < 10 else noop\n          printed_device += 1\n        # Max pooling over a (2, 2) window\n        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))\n        # If the size is a square you can only specify a single number\n        x = F.max_pool2d(F.relu(self.conv2(x)), 2)\n        x = x.view(-1, self.num_flat_features(x))\n        x = F.relu(self.fc1(x))\n        x = F.relu(self.fc2(x))\n        x = self.fc3(x)\n        return x\n\n    def num_flat_features(self, x):\n        size = x.size()[1:]  # all dimensions except the batch dimension\n        num_features = 1\n        for s in size:\n            num_features *= s\n        return num_features\n\n\nprint(\"---------------------------------------------------------- START:3\")\n\n# %%\ndls_tpu = datablock.dataloaders(path,bs=1, device=tpu_device)\ndls_tpu.vocab, dls_tpu.show_batch()\n\nprint(\"---------------------------------------------------------- START:4\")\n\n# %%\ndef print_local(msg):\n  if False: return\n  print(msg)\n\nprint(\"---------------------------------------------------------- START:5\")\n\nclass XLAOptimProxy:\n    def __init__(self,opt:Optimizer):\n        # TRACE: print(\"XLAOptimProxy#inicializando __init__\")\n        self.opt = opt\n\n    def xla_step(self):\n        print(\"------------- xla optimizer!!!!!!!! BARRIER TRYE\")\n        xm.optimizer_step(self.opt,barrier=True) # sync on gradient update\n\n    def __getattr__(self,name):\n        if name == '___step___': # override proxying for step method\n                print_local(\"calling xla_step\")\n                return getattr(self,'xla_step')\n        # proxy everything else\n        #print_local(f\"calling XLAOptimProxy#{name}\")\n        return getattr(self.opt,name)\n\n\nprint(\"---------------------------------------------------------- START:6\")\n\n@patch_to(ParamScheduler)\ndef _update_val(self, pct):\n#        for n,f in self.scheds.items(): self.opt.set_hyper(n, f(pct))\n        for n,f in self.scheds.items():\n            v = f(pct)\n            #print_local(f\"---------------------- A f(pct) = {v}\")\n            self.opt.set_hyper(n, v)\n\nprint(\"---------------------------------------------------------- START:7\")\n\n@patch_to(ParamScheduler)\ndef after_batch(self):\n#        for p in self.scheds.keys(): self.hps[p].append(self.opt.hypers[-1][p])\n        for p in self.scheds.keys():\n            v = self.opt.hypers[-1][p]\n            #print_local(f\"---------------------- B after_batch ParamScheduler {v}\")\n            self.hps[p].append(v)\n\nprint(\"---------------------------------------------------------- START:8 enbd STARET\")\n\n# %%\n####################################################################################333\n\n\nprint(\"---------------------- STARTED class Learner\")\n\n@log_args(but='dls,model,opt_func,cbs')\nclass Learner():\n    def __init__(self, dls, model, loss_func=None, opt_func=Adam, lr=defaults.lr, splitter=trainable_params, cbs=None,\n                 metrics=None, path=None, model_dir='models', wd=None, wd_bn_bias=False, train_bn=True,\n                 moms=(0.95,0.85,0.95)):\n        store_attr(self, \"dls,model,opt_func,lr,splitter,model_dir,wd,wd_bn_bias,train_bn,metrics,moms\")\n        self.training,self.create_mbar,self.logger,self.opt,self.cbs = False,True,print,None,L()\n        if loss_func is None:\n            loss_func = getattr(dls.train_ds, 'loss_func', None)\n            assert loss_func is not None, \"Could not infer loss function from the data, please pass a loss function.\"\n        self.loss_func = loss_func\n        self.path = Path(path) if path is not None else getattr(dls, 'path', Path('.'))\n        self.add_cbs([(cb() if isinstance(cb, type) else cb) for cb in L(defaults.callbacks)+L(cbs)])\n        self.model.to(self.dls.device)\n        if hasattr(self.model, 'reset'): self.model.reset()\n        self.epoch,self.n_epoch,self.loss = 0,1,tensor(0.)\n\n    @property\n    def metrics(self): return self._metrics\n    @metrics.setter\n    def metrics(self,v): self._metrics = L(v).map(mk_metric)\n\n    def _grab_cbs(self, cb_cls): return L(cb for cb in self.cbs if isinstance(cb, cb_cls))\n    def add_cbs(self, cbs): L(cbs).map(self.add_cb)\n    def remove_cbs(self, cbs): L(cbs).map(self.remove_cb)\n    def add_cb(self, cb):\n        old = getattr(self, cb.name, None)\n        assert not old or isinstance(old, type(cb)), f\"self.{cb.name} already registered\"\n        cb.learn = self\n        setattr(self, cb.name, cb)\n        self.cbs.append(cb)\n        return self\n\n    def remove_cb(self, cb):\n        if isinstance(cb, type): self.remove_cbs(self._grab_cbs(cb))\n        else:\n            cb.learn = None\n            if hasattr(self, cb.name): delattr(self, cb.name)\n            if cb in self.cbs: self.cbs.remove(cb)\n\n    @contextmanager\n    def added_cbs(self, cbs):\n        self.add_cbs(cbs)\n        try: yield\n        finally: self.remove_cbs(cbs)\n\n    @contextmanager\n    def removed_cbs(self, cbs):\n        self.remove_cbs(cbs)\n        try: yield self\n        finally: self.add_cbs(cbs)\n\n    def ordered_cbs(self, event): return [cb for cb in sort_by_run(self.cbs) if hasattr(cb, event)]\n\n    def __call__(self, event_name): L(event_name).map(self._call_one)\n    def _call_one(self, event_name):\n        assert hasattr(event, event_name)\n        myl = []\n        if False:\n            # NOTE: no va\n            return\n        # TRACE: print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}   SORT BY NAME\")\n        lll = sort_by_run(self.cbs)\n        # TRACE: print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}   SORT BY NAME {lll}\")\n        for cb in lll:\n            # TRACE: print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}   calling {cb}({event_name})\")\n            r=cb(event_name)\n            # TRACE: print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}   calling {cb}({event_name})\")\n            myl.append(r)\n        # TRACE: print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}   SORT BY NAME END\")\n        # TRACE: print(\"-------------------------------------------------------------------------------------------------\")\n        # TRACE: print(\"----------------------------------------------------------\")\n        # TRACE: print(\"------------------------\")\n        #[cb(event_name) for cb in sort_by_run(self.cbs)]\n\n    def _bn_bias_state(self, with_bias): return bn_bias_params(self.model, with_bias).map(self.opt.state)\n    def create_opt(self):\n        self.opt = self.opt_func(self.splitter(self.model), lr=self.lr)\n        if not self.wd_bn_bias:\n            for p in self._bn_bias_state(True ): p['do_wd'] = False\n        if self.train_bn:\n            for p in self._bn_bias_state(False): p['force_train'] = True\n\n    def _split(self, b):\n        i = getattr(self.dls, 'n_inp', 1 if len(b)==1 else len(b)-1)\n        self.xb,self.yb = b[:i],b[i:]\n\n    def all_batches(self):\n        self.n_iter = len(self.dl)\n        # TRACE: print(f\"Learner#all_batches@n_iter = {self.n_iter}\")\n        for o in enumerate(self.dl): self.one_batch(*o)\n\n    def one_batch(self, i, b):\n        # TRACE: print(f\"Learner#one_batch {i} b is the batch\") if i % 10000 == 0 else noop\n        self.iter = i\n        try:\n            self._split(b);                                  self('begin_batch')\n            self.pred = self.model(*self.xb);                self('after_pred')\n            if len(self.yb) == 0: return\n            self.loss = self.loss_func(self.pred, *self.yb); self('after_loss')\n            if not self.training: return\n            self.loss.backward();                            self('after_backward')\n            #self.opt.step();                                 self('after_step')\n            xm.optimizer_step(self.opt,barrier=True);                                 self('after_step')\n            self.opt.zero_grad()\n        except CancelBatchException:                         self('after_cancel_batch')\n        finally:                                             self('after_batch')\n\n    def _do_begin_fit(self, n_epoch):\n        # TRACE: print(\"Learner#_do_begin_fit\")\n        self.n_epoch,self.loss = n_epoch,tensor(0.);         self('begin_fit')\n\n    def _do_epoch_train(self):\n        try:\n            # TRACE: print(\"Learner#_do_epoch_train internal try\")\n            self.dl = self.dls.train;                        self('begin_train')\n            self.all_batches()\n        except CancelTrainException:                         self('after_cancel_train')\n        finally:                                             self('after_train')\n\n    def _do_epoch_validate(self, ds_idx=1, dl=None):\n        if dl is None: dl = self.dls[ds_idx]\n        try:\n            # TRACE: print(\"Learner#_do_epoch_validate@internal try\")\n            self.dl = dl;                                    self('begin_validate')\n            with torch.no_grad(): self.all_batches()\n        except CancelValidException:                         self('after_cancel_validate')\n        finally:                                             self('after_validate')\n\n    def _end_cleanup(self):\n        self.dl,self.xb,self.yb,self.pred,self.loss = None,(None,),(None,),None,None\n\n    @log_args(but='cbs')\n    def fit(self, n_epoch, lr=None, wd=None, cbs=None, reset_opt=False):\n        # TRACE: print(\"fit starts\")\n        with self.added_cbs(cbs):\n            # TRACE: print(\"fit starts with added callbacks\")\n            if reset_opt or not self.opt: self.create_opt()\n            if wd is None: wd = self.wd\n            if wd is not None: self.opt.set_hypers(wd=wd)\n            # TRACE: print(\"Learner#fit@set hypers\")\n            self.opt.set_hypers(lr=self.lr if lr is None else lr)\n            try:\n                # TRACE: print(\"Learner#fit@do begin fit\")\n                self._do_begin_fit(n_epoch)\n                # TRACE: print(\"Learner#fit@FOR each epoch LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOP\")\n                for epoch in range(n_epoch):\n                    try:\n                        # TRACE: print(f\"Learner#fit@epoch... begin... {epoch}\")\n                        self.epoch=epoch;          self('begin_epoch')\n                        # TRACE: print(f\"Learner#fit@epoch... train... {epoch}\")\n                        self._do_epoch_train()\n                        # TRACE: print(f\"Learner#fit@epoc validate {epoch}\")\n                        self._do_epoch_validate()\n                    except CancelEpochException:   self('after_cancel_epoch')\n                    finally:                       self('after_epoch')\n\n            except CancelFitException:             self('after_cancel_fit')\n            finally:\n                # TRACE: self('after_fit')\n                self._end_cleanup()\n                # TRACE: print(\"Learner#fit@end cleanup\")\n\n    def validate(self, ds_idx=1, dl=None, cbs=None):\n        if dl is None: dl = self.dls[ds_idx]\n        with self.added_cbs(cbs), self.no_logging(), self.no_mbar():\n            self(_before_epoch)\n            self._do_epoch_validate(ds_idx, dl)\n            self(_after_epoch)\n        return getattr(self, 'final_record', None)\n\n    @delegates(GatherPredsCallback.__init__)\n    def get_preds(self, ds_idx=1, dl=None, with_input=False, with_decoded=False, with_loss=False, act=None,\n                  inner=False, reorder=True, **kwargs):\n        if dl is None: dl = self.dls[ds_idx].new(shuffled=False, drop_last=False)\n        if reorder and hasattr(dl, 'get_idxs'):\n            idxs = dl.get_idxs()\n            dl = dl.new(get_idxs = _ConstantFunc(idxs))\n        cb = GatherPredsCallback(with_input=with_input, with_loss=with_loss, **kwargs)\n        ctx_mgrs = [self.no_logging(), self.added_cbs(cb), self.no_mbar()]\n        if with_loss: ctx_mgrs.append(self.loss_not_reduced())\n        with ExitStack() as stack:\n            for mgr in ctx_mgrs: stack.enter_context(mgr)\n            self(event.begin_epoch if inner else _before_epoch)\n            self._do_epoch_validate(dl=dl)\n            self(event.after_epoch if inner else _after_epoch)\n            if act is None: act = getattr(self.loss_func, 'activation', noop)\n            res = cb.all_tensors()\n            pred_i = 1 if with_input else 0\n            if res[pred_i] is not None:\n                res[pred_i] = act(res[pred_i])\n                if with_decoded: res.insert(pred_i+2, getattr(self.loss_func, 'decodes', noop)(res[pred_i]))\n            if reorder and hasattr(dl, 'get_idxs'): res = nested_reorder(res, tensor(idxs).argsort())\n            return tuple(res)\n        self._end_cleanup()\n\n    def predict(self, item, rm_type_tfms=None, with_input=False):\n        dl = self.dls.test_dl([item], rm_type_tfms=rm_type_tfms, num_workers=0)\n        inp,preds,_,dec_preds = self.get_preds(dl=dl, with_input=True, with_decoded=True)\n        i = getattr(self.dls, 'n_inp', -1)\n        inp = (inp,) if i==1 else tuplify(inp)\n        dec = self.dls.decode_batch(inp + tuplify(dec_preds))[0]\n        dec_inp,dec_targ = map(detuplify, [dec[:i],dec[i:]])\n        res = dec_targ,dec_preds[0],preds[0]\n        if with_input: res = (dec_inp,) + res\n        return res\n\n    def show_results(self, ds_idx=1, dl=None, max_n=9, shuffle=True, **kwargs):\n        if dl is None: dl = self.dls[ds_idx].new(shuffle=shuffle)\n        b = dl.one_batch()\n        _,_,preds = self.get_preds(dl=[b], with_decoded=True)\n        self.dls.show_results(b, preds, max_n=max_n, **kwargs)\n\n    def show_training_loop(self):\n        indent = 0\n        for s in _loop:\n            if s.startswith('Start'): print(f'{\" \"*indent}{s}'); indent += 2\n            elif s.startswith('End'): indent -= 2; print(f'{\" \"*indent}{s}')\n            else: print(f'{\" \"*indent} - {s:15}:', self.ordered_cbs(s))\n\n    @contextmanager\n    def no_logging(self): return replacing_yield(self, 'logger', noop)\n    @contextmanager\n    def no_mbar(self):    return replacing_yield(self, 'create_mbar', False)\n\n    @contextmanager\n    def loss_not_reduced(self):\n        if hasattr(self.loss_func, 'reduction'): return replacing_yield(self.loss_func, 'reduction', 'none')\n        else: return replacing_yield(self, 'loss_func', partial(self.loss_func, reduction='none'))\n\n    @delegates(save_model)\n    def save(self, file, **kwargs):\n        file = join_path_file(file, self.path/self.model_dir, ext='.pth')\n        save_model(file, self.model, getattr(self,'opt',None), **kwargs)\n\n    @delegates(load_model)\n    def load(self, file, with_opt=None, device=None, **kwargs):\n        if device is None: device = self.dls.device\n        if self.opt is None: self.create_opt()\n        file = join_path_file(file, self.path/self.model_dir, ext='.pth')\n        load_model(file, self.model, self.opt, device=device, **kwargs)\n        return self\n\nLearner.x,Learner.y = add_props(lambda i,x: detuplify((x.xb,x.yb)[i]))\n###################################################################33333\n\ndef _is_instance(f, gs):\n    tst = [g if type(g) in [type, 'function'] else g.__class__ for g in gs]\n    for g in tst:\n        if isinstance(f, g) or f==g: return True\n    return False\n\ndef _is_first(f, gs):\n    for o in L(getattr(f, 'run_after', None)):\n        if _is_instance(o, gs): return False\n    for g in gs:\n        if _is_instance(f, L(getattr(g, 'run_before', None))): return False\n    return True\n\ndef sort_by_run(fs):\n    end = L(fs).attrgot('toward_end')\n    inp,res = L(fs)[~end] + L(fs)[end], L()\n    while len(inp):\n        for i,o in enumerate(inp):\n            if _is_first(o, inp):\n                res.append(inp.pop(i))\n                break\n        else: raise Exception(\"Impossible to sort\")\n    # TRACE: print(f\"will invoke toward_end {res}\")\n    return res\n\n\nprint(\"---------------------- PASSED LEARNER\")\n\n\n\n##################################################################33 torch_base.py\n\n\n\nprint(\"---------------------- STARTED torch_base.py\")\n\n\n\n\n\nif torch.cuda.is_available():\n    if torch.cuda.current_device()==0:\n        def_gpu = int(os.environ.get('DEFAULT_GPU') or 0)\n        if torch.cuda.device_count()>=def_gpu: torch.cuda.set_device(def_gpu)\n    torch.backends.cudnn.benchmark = True\n\n# Cell\n@delegates(plt.subplots, keep=True)\ndef subplots(nrows=1, ncols=1, figsize=None, imsize=3, add_vert=0, **kwargs):\n    if figsize is None: figsize=(ncols*imsize, nrows*imsize+add_vert)\n    fig,ax = plt.subplots(nrows, ncols, figsize=figsize, **kwargs)\n    if nrows*ncols==1: ax = array([ax])\n    return fig,ax\n\n# Cell\ndef _fig_bounds(x):\n    r = x//32\n    return min(5, max(1,r))\n\n# Cell\ndef show_image(im, ax=None, figsize=None, title=None, ctx=None, **kwargs):\n    \"Show a PIL or PyTorch image on `ax`.\"\n    # Handle pytorch axis order\n    if hasattrs(im, ('data','cpu','permute')):\n        im = im.data.cpu()\n        if im.shape[0]<5: im=im.permute(1,2,0)\n    elif not isinstance(im,np.ndarray): im=array(im)\n    # Handle 1-channel images\n    if im.shape[-1]==1: im=im[...,0]\n\n    ax = ifnone(ax,ctx)\n    if figsize is None: figsize = (_fig_bounds(im.shape[0]), _fig_bounds(im.shape[1]))\n    if ax is None: _,ax = plt.subplots(figsize=figsize)\n    ax.imshow(im, **kwargs)\n    if title is not None: ax.set_title(title)\n    ax.axis('off')\n    return ax\n\n# Cell\ndef show_titled_image(o, **kwargs):\n    \"Call `show_image` destructuring `o` to `(img,title)`\"\n    show_image(o[0], title=str(o[1]), **kwargs)\n\n# Cell\n@delegates(subplots)\ndef show_images(ims, nrows=1, ncols=None, titles=None, **kwargs):\n    \"Show all images `ims` as subplots with `rows` using `titles`\"\n    if ncols is None: ncols = int(math.ceil(len(ims)/nrows))\n    if titles is None: titles = [None]*len(ims)\n    axs = subplots(nrows, ncols, **kwargs)[1].flat\n    for im,t,ax in zip(ims, titles, axs): show_image(im, ax=ax, title=t)\n\n# Cell\nclass ArrayBase(ndarray):\n    @classmethod\n    def _before_cast(cls, x): return x if isinstance(x,ndarray) else array(x)\n\n# Cell\nclass ArrayImageBase(ArrayBase):\n    _show_args = {'cmap':'viridis'}\n    def show(self, ctx=None, **kwargs):\n        return show_image(self, ctx=ctx, **{**self._show_args, **kwargs})\n\n# Cell\nclass ArrayImage(ArrayImageBase): pass\n\n# Cell\nclass ArrayImageBW(ArrayImage): _show_args = {'cmap':'Greys'}\n\n# Cell\nclass ArrayMask(ArrayImageBase): _show_args = {'alpha':0.5, 'cmap':'tab20', 'interpolation':'nearest'}\n\n# Cell\n@patch\ndef __array_eq__(self:Tensor,b):\n    return torch.equal(self,b) if self.dim() else self==b\n\n# Cell\ndef _array2tensor(x):\n    if x.dtype==np.uint16: x = x.astype(np.float32)\n    return torch.from_numpy(x)\n\n# Cell\ndef tensor(x, *rest, **kwargs):\n    \"Like `torch.as_tensor`, but handle lists too, and can pass multiple vector elements directly.\"\n    if len(rest): x = (x,)+rest\n    # There was a Pytorch bug in dataloader using num_workers>0. Haven't confirmed if fixed\n    # if isinstance(x, (tuple,list)) and len(x)==0: return tensor(0)\n    res = (x if isinstance(x, Tensor)\n           else torch.tensor(x, **kwargs) if isinstance(x, (tuple,list))\n           else _array2tensor(x) if isinstance(x, ndarray)\n           else as_tensor(x.values, **kwargs) if isinstance(x, (pd.Series, pd.DataFrame))\n           else as_tensor(x, **kwargs) if hasattr(x, '__array__') or is_iter(x)\n           else _array2tensor(array(x), **kwargs))\n    if res.dtype is torch.float64: return res.float()\n    return res\n\n# Cell\ndef set_seed(s):\n    \"Set random seed for `random`, `torch`, and `numpy` (where available)\"\n    try: torch.manual_seed(s)\n    except NameError: pass\n    try: np.random.seed(s%(2**32-1))\n    except NameError: pass\n    random.seed(s)\n\n# Cell\ndef unsqueeze(x, dim=-1, n=1):\n    \"Same as `torch.unsqueeze` but can add `n` dims\"\n    for _ in range(n): x = x.unsqueeze(dim)\n    return x\n\n# Cell\ndef unsqueeze_(x, dim=-1, n=1):\n    \"Same as `torch.unsqueeze_` but can add `n` dims\"\n    for _ in range(n): x.unsqueeze_(dim)\n    return x\n\n# Cell\ndef _fa_rebuild_tensor (cls, *args, **kwargs): return cls(torch._utils._rebuild_tensor_v2(*args, **kwargs))\ndef _fa_rebuild_qtensor(cls, *args, **kwargs): return cls(torch._utils._rebuild_qtensor  (*args, **kwargs))\n\n# Cell\ndef apply(func, x, *args, **kwargs):\n    \"Apply `func` recursively to `x`, passing on args\"\n    if is_listy(x): return type(x)([apply(func, o, *args, **kwargs) for o in x])\n    if isinstance(x,dict):  return {k: apply(func, v, *args, **kwargs) for k,v in x.items()}\n    res = func(x, *args, **kwargs)\n    return res if x is None else retain_type(res, x)\n\n# Cell\ndef maybe_gather(x, axis=0):\n    \"Gather copies of `x` on `axis` (if training is distributed)\"\n    if num_distrib()<=1: return x\n    ndim = x.ndim\n    res = [x.new_zeros(*x.shape if ndim > 0 else (1,)) for _ in range(num_distrib())]\n    torch.distributed.all_gather(res, x if ndim > 0 else x[None])\n    return torch.cat(res, dim=axis) if ndim > 0 else torch.cat(res, dim=axis).mean()\n\n# Cell\ndef to_detach(b, cpu=True, gather=True):\n    \"Recursively detach lists of tensors in `b `; put them on the CPU if `cpu=True`.\"\n    def _inner(x, cpu=True, gather=True):\n        if not isinstance(x,Tensor): return x\n        x = x.detach()\n        if gather: x = maybe_gather(x)\n        return x.cpu() if cpu else x\n    return apply(_inner, b, cpu=cpu, gather=gather)\n\n# Cell\ndef to_half(b):\n    \"Recursively map lists of tensors in `b ` to FP16.\"\n    return apply(lambda x: x.half() if torch.is_floating_point(x) else x, b)\n\n# Cell\ndef to_float(b):\n    \"Recursively map lists of int tensors in `b ` to float.\"\n    return apply(lambda x: x.float() if torch.is_floating_point(x) else x, b)\n\n# Cell\n# None: True if available; True: error if not availabe; False: use CPU\ndefaults.use_cuda = None\n\n# Cell\ndef default_device(use_cuda=-1):\n    \"Return or set default device; `use_cuda`: None - CUDA if available; True - error if not availabe; False - CPU\"\n    if use_cuda != -1: defaults.use_cuda=use_cuda\n    use = defaults.use_cuda or (torch.cuda.is_available() and defaults.use_cuda is None)\n    assert torch.cuda.is_available() or not use\n    return torch.device(torch.cuda.current_device()) if use else torch.device('cpu')\n\n# Cell\ndef to_device(b, device=None):\n    \"Recursively put `b` on `device`.\"\n    if defaults.use_cuda==False: device='cpu'\n    elif device is None: device=default_device()\n    def _inner(o): return o.to(device, non_blocking=True) if isinstance(o,Tensor) else o.to_device(device) if hasattr(o, \"to_device\") else o\n    return apply(_inner, b)\n\n# Cell\ndef to_cpu(b):\n    \"Recursively map lists of tensors in `b ` to the cpu.\"\n    return to_device(b,'cpu')\n\n# Cell\ndef to_np(x):\n    \"Convert a tensor to a numpy array.\"\n    return apply(lambda o: o.data.cpu().numpy(), x)\n\n# Cell\ndef to_concat(xs, dim=0):\n    \"Concat the element in `xs` (recursively if they are tuples/lists of tensors)\"\n    if is_listy(xs[0]): return type(xs[0])([to_concat([x[i] for x in xs], dim=dim) for i in range_of(xs[0])])\n    if isinstance(xs[0],dict):  return {k: to_concat([x[k] for x in xs], dim=dim) for k in xs[0].keys()}\n    #We may receives xs that are not concatenatable (inputs of a text classifier for instance),\n    #   in this case we return a big list\n    try:    return retain_type(torch.cat(xs, dim=dim), xs[0])\n    except: return sum([L(retain_type(o_.index_select(dim, tensor(i)).squeeze(dim), xs[0])\n                          for i in range_of(o_)) for o_ in xs], L())\n\n# Cell\n@patch\ndef set_meta(self:Tensor, x):\n    \"Set all metadata in `__dict__`\"\n    if hasattr(x,'__dict__'): self.__dict__ = x.__dict__\n\n\n# Cell\n@patch\ndef get_meta(self:Tensor, n, d=None):\n    \"Set `n` from `self._meta` if it exists and returns default `d` otherwise\"\n    return getattr(self, '_meta', {}).get(n, d)\n\n# Cell\n@patch\ndef as_subclass(self:Tensor, typ):\n    \"Cast to `typ` (should be in future PyTorch version, so remove this then)\"\n    res = torch.Tensor._make_subclass(typ, self)\n    return retain_meta(self, res)\n\n# Cell\nclass TensorBase(Tensor):\n    def __new__(cls, x, **kwargs):\n        global printed_device2 \n        res = cast(tensor(x), cls)\n        if res.device != tpu_device:\n          print(f\"************** XXX ######################### EL DEVICE ES {tpu_device} no es {res.device} ni el de entrada {x.device} ######################### **************\") if printed_device < 10 else noop\n          printed_device2 += 1\n        res._meta = kwargs\n        return res\n\n    @classmethod\n    def _before_cast(cls, x): return x if isinstance(x,Tensor) else tensor(x)\n\n    def __reduce_ex__(self,proto):\n        torch.utils.hooks.warn_if_has_hooks(self)\n        args = (type(self), self.storage(), self.storage_offset(), tuple(self.size()), self.stride())\n        if self.is_quantized: args = args + (self.q_scale(), self.q_zero_point())\n        f = _fa_rebuild_qtensor if self.is_quantized else  _fa_rebuild_tensor\n        return (f, args + (self.requires_grad, OrderedDict()))\n\n    def gi(self, i):\n        res = self[i]\n        return res.as_subclass(type(self)) if isinstance(res,Tensor) else res\n\n    def __repr__(self):\n        return re.sub('tensor', self.__class__.__name__, super().__repr__())\n\n# Cell\ndef _patch_tb():\n    # TRACE: print(\"*********################### ######################## patch_tb\")\n    if getattr(TensorBase,'_patched',False): return\n    TensorBase._patched = True\n\n    def get_f(fn):\n        def _f(self, *args, **kwargs):\n            cls = self.__class__\n            res = getattr(super(TensorBase, self), fn)(*args, **kwargs)\n            return retain_type(res, self)\n        return _f\n\n    t = tensor([1])\n    skips = 'as_subclass imag real __getitem__ __class__ __deepcopy__ __delattr__ __dir__ __doc__ __getattribute__ __hash__ __init__ \\\n        __init_subclass__ __new__ __reduce__ __reduce_ex__ __repr__ __module__ __setstate__'.split()\n\n    for fn in dir(t):\n        if fn in skips: continue\n        f = getattr(t, fn)\n        if isinstance(f, (MethodWrapperType, BuiltinFunctionType, BuiltinMethodType, MethodType, FunctionType)):\n            setattr(TensorBase, fn, get_f(fn))\n\n_patch_tb()\n\n# Cell\nclass TensorCategory(TensorBase): pass\n\n# Cell\nclass TensorMultiCategory(TensorCategory): pass\n\n# Cell\nclass TensorImageBase(TensorBase):\n    _show_args = ArrayImageBase._show_args\n    def show(self, ctx=None, **kwargs):\n        return show_image(self, ctx=ctx, **{**self._show_args, **kwargs})\n\n# Cell\nclass TensorImage(TensorImageBase): pass\n\n# Cell\nclass TensorImageBW(TensorImage): _show_args = ArrayImageBW._show_args\n\n# Cell\nclass TensorMask(TensorImageBase):\n    _show_args = ArrayMask._show_args\n\n    def show(self, ctx=None, **kwargs):\n        codes = self.get_meta('codes')\n        if codes is not None: kwargs = merge({'vmin': 1, 'vmax': len(codes)}, kwargs)\n        return super().show(ctx=ctx, **kwargs)\n\n# Cell\nclass TitledTensorScalar(TensorBase):\n    \"A tensor containing a scalar that has a `show` method\"\n    def show(self, **kwargs): show_title(self.item(), **kwargs)\n\n# Cell\n@patch\ndef tensored(self:L):\n    \"`mapped(tensor)`\"\n    return self.map(tensor)\n@patch\ndef stack(self:L, dim=0):\n    \"Same as `torch.stack`\"\n    return torch.stack(list(self.tensored()), dim=dim)\n@patch\ndef cat  (self:L, dim=0):\n    \"Same as `torch.cat`\"\n    return torch.cat  (list(self.tensored()), dim=dim)\n\n# Cell\ndef concat(*ls):\n    \"Concatenate tensors, arrays, lists, or tuples\"\n    if not len(ls): return []\n    it = ls[0]\n    if isinstance(it,torch.Tensor): res = torch.cat(ls)\n    elif isinstance(it,ndarray): res = np.concatenate(ls)\n    else:\n        res = itertools.chain.from_iterable(map(L,ls))\n        if isinstance(it,(tuple,list)): res = type(it)(res)\n        else: res = L(res)\n    return retain_type(res, it)\n\n# Cell\nclass Chunks:\n    \"Slice and int indexing into a list of lists\"\n    def __init__(self, chunks, lens=None):\n        self.chunks = chunks\n        self.lens = L(map(len,self.chunks) if lens is None else lens)\n        self.cumlens = np.cumsum(0+self.lens)\n        self.totlen = self.cumlens[-1]\n\n    def __getitem__(self,i):\n        if isinstance(i,slice): return retain_type(self.getslice(i), old=self.chunks[0])\n        di,idx = self.doc_idx(i)\n        return retain_type(self.chunks[di][idx], old=self.chunks[0])\n\n    def getslice(self, i):\n        st_d,st_i = self.doc_idx(ifnone(i.start,0))\n        en_d,en_i = self.doc_idx(ifnone(i.stop,self.totlen+1))\n        res = [self.chunks[st_d][st_i:(en_i if st_d==en_d else sys.maxsize)]]\n        for b in range(st_d+1,en_d): res.append(self.chunks[b])\n        if st_d!=en_d and en_d<len(self.chunks): res.append(self.chunks[en_d][:en_i])\n        return concat(*res)\n\n    def doc_idx(self, i):\n        if i<0: i=self.totlen+i # count from end\n        docidx = np.searchsorted(self.cumlens, i+1)-1\n        cl = self.cumlens[docidx]\n        return docidx,i-cl\n\n# Cell\ndef show_title(o, ax=None, ctx=None, label=None, color='black', **kwargs):\n    \"Set title of `ax` to `o`, or print `o` if `ax` is `None`\"\n    ax = ifnone(ax,ctx)\n    if ax is None: print(o)\n    elif hasattr(ax, 'set_title'):\n        t = ax.title.get_text()\n        if len(t) > 0: o = t+'\\n'+str(o)\n        ax.set_title(o, color=color)\n    elif isinstance(ax, pd.Series):\n        while label in ax: label += '_'\n        ax = ax.append(pd.Series({label: o}))\n    return ax\n\n# Cell\nclass ShowTitle:\n    \"Base class that adds a simple `show`\"\n    _show_args = {'label': 'text'}\n    def show(self, ctx=None, **kwargs):\n        \"Show self\"\n        return show_title(str(self), ctx=ctx, **merge(self._show_args, kwargs))\n\nclass TitledInt(Int, ShowTitle):\n    _show_args = {'label': 'text'}\n    def show(self, ctx=None, **kwargs):\n        \"Show self\"\n        return show_title(str(self), ctx=ctx, **merge(self._show_args, kwargs))\n\nclass TitledFloat(Float, ShowTitle):\n    _show_args = {'label': 'text'}\n    def show(self, ctx=None, **kwargs):\n        \"Show self\"\n        return show_title(str(self), ctx=ctx, **merge(self._show_args, kwargs))\n\nclass TitledStr(Str, ShowTitle):\n    _show_args = {'label': 'text'}\n    def show(self, ctx=None, **kwargs):\n        \"Show self\"\n        return show_title(str(self), ctx=ctx, **merge(self._show_args, kwargs))\n\nclass TitledTuple(Tuple, ShowTitle):\n    _show_args = {'label': 'text'}\n    def show(self, ctx=None, **kwargs):\n        \"Show self\"\n        return show_title(str(self), ctx=ctx, **merge(self._show_args, kwargs))\n\nadd_docs(TitledInt, \"An `int` with `show`\"); add_docs(TitledStr, \"An `str` with `show`\");\nadd_docs(TitledFloat, \"A `float` with `show`\"); add_docs(TitledTuple, \"A `Tuple` with `show`\")\n\n# Cell\n@patch\ndef truncate(self:TitledStr, n):\n    \"Truncate self to `n`\"\n    words = self.split(' ')[:n]\n    return TitledStr(' '.join(words))\n\n# Cell\nif not hasattr(pd.DataFrame,'_old_init'): pd.DataFrame._old_init = pd.DataFrame.__init__\n\n# Cell\n@patch\ndef __init__(self:pd.DataFrame, data=None, index=None, columns=None, dtype=None, copy=False):\n    if data is not None and isinstance(data, Tensor): data = to_np(data)\n    self._old_init(data, index=index, columns=columns, dtype=dtype, copy=copy)\n\n# Cell\ndef get_empty_df(n):\n    \"Return `n` empty rows of a dataframe\"\n    df = pd.DataFrame(index = range(n))\n    return [df.iloc[i] for i in range(n)]\n\n# Cell\ndef display_df(df):\n    \"Display `df` in a notebook or defaults to print\"\n    try: from IPython.display import display, HTML\n    except: return print(df)\n    display(HTML(df.to_html()))\n\n# Cell\ndef get_first(c):\n    \"Get the first element of c, even if c is a dataframe\"\n    return getattr(c, 'iloc', c)[0]\n\n# Cell\ndef one_param(m):\n    \"First parameter in `m`\"\n    return first(m.parameters())\n\n# Cell\ndef item_find(x, idx=0):\n    \"Recursively takes the `idx`-th element of `x`\"\n    if is_listy(x): return item_find(x[idx])\n    if isinstance(x,dict):\n        key = list(x.keys())[idx] if isinstance(idx, int) else idx\n        return item_find(x[key])\n    return x\n\n# Cell\ndef find_device(b):\n    \"Recursively search the device of `b`.\"\n    return item_find(b).device\n\n# Cell\ndef find_bs(b):\n    \"Recursively search the batch size of `b`.\"\n    return item_find(b).shape[0]\n\n# Cell\nclass Module(nn.Module, metaclass=PrePostInitMeta):\n    \"Same as `nn.Module`, but no need for subclasses to call `super().__init__`\"\n    def __pre_init__(self, *args, **kwargs): super().__init__()\n    def __init__(self): pass\n\n# Cell\nfrom torch.nn.parallel import DistributedDataParallel\n\ndef get_model(model):\n    \"Return the model maybe wrapped inside `model`.\"\n    return model.module if isinstance(model, (DistributedDataParallel, nn.DataParallel)) else model\n\n# Cell\ndef one_hot(x, c):\n    \"One-hot encode `x` with `c` classes.\"\n    res = torch.zeros(c, dtype=torch.uint8)\n    if isinstance(x, Tensor) and x.numel()>0: res[x] = 1.\n    else: res[list(L(x, use_list=None))] = 1.\n    return res\n\n# Cell\ndef one_hot_decode(x, vocab=None):\n    return L(vocab[i] if vocab else i for i,x_ in enumerate(x) if x_==1)\n\n# Cell\ndef params(m):\n    \"Return all parameters of `m`\"\n    return [p for p in m.parameters()]\n\n# Cell\ndef trainable_params(m):\n    \"Return all trainable parameters of `m`\"\n    return [p for p in m.parameters() if p.requires_grad]\n\n# Cell\nnorm_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.InstanceNorm1d, nn.InstanceNorm2d, nn.InstanceNorm3d)\n\n# Cell\ndef bn_bias_params(m, with_bias=True): # TODO: Rename to `norm_bias_params`\n    \"Return all bias and BatchNorm parameters\"\n    if isinstance(m, norm_types): return L(m.parameters())\n    res = L(m.children()).map(bn_bias_params, with_bias=with_bias).concat()\n    if with_bias and getattr(m, 'bias', None) is not None: res.append(m.bias)\n    return res\n\n# Cell\ndef batch_to_samples(b, max_n=10):\n    \"'Transposes' a batch to (at most `max_n`) samples\"\n    if isinstance(b, Tensor): return retain_types(list(b[:max_n]), [b])\n    else:\n        res = L(b).map(partial(batch_to_samples,max_n=max_n))\n        return retain_types(res.zip(), [b])\n\n# Cell\n@patch\ndef interp_1d(x:Tensor, xp, fp):\n    \"Same as `np.interp`\"\n    slopes = (fp[1:]-fp[:-1])/(xp[1:]-xp[:-1])\n    incx = fp[:-1] - (slopes*xp[:-1])\n    locs = (x[:,None]>=xp[None,:]).long().sum(1)-1\n    locs = locs.clamp(0,len(slopes)-1)\n    return slopes[locs]*x + incx[locs]\n\n# Cell\n@patch\ndef pca(x:Tensor, k=2):\n    \"Compute PCA of `x` with `k` dimensions.\"\n    x = x-torch.mean(x,0)\n    U,S,V = torch.svd(x.t())\n    return torch.mm(x,U[:,:k])\n\n# Cell\ndef logit(x):\n    \"Logit of `x`, clamped to avoid inf.\"\n    x = x.clamp(1e-7, 1-1e-7)\n    return -(1/x-1).log()\n\n# Cell\ndef num_distrib():\n    \"Return the number of processes in distributed training (if applicable).\"\n    return int(os.environ.get('WORLD_SIZE', 0))\n\n# Cell\ndef rank_distrib():\n    \"Return the distributed rank of this process (if applicable).\"\n    return int(os.environ.get('RANK', 0))\n\n# Cell\ndef distrib_barrier():\n    \"Place a synchronization barrier in distributed training so that ALL sub-processes in the pytorch process group must arrive here before proceeding.\"\n    if num_distrib() > 1 and torch.distributed.is_initialized(): torch.distributed.barrier()\n\n# Cell\n# Saving arrays requires pytables - optional dependency\ntry: import tables\nexcept: pass\n\n# Cell\ndef _comp_filter(lib='lz4',lvl=3): return tables.Filters(complib=f'blosc:{lib}', complevel=lvl)\n\n# Cell\n@patch\ndef save_array(p:Path, o, complib='lz4', lvl=3):\n    \"Save numpy array to a compressed `pytables` file, using compression level `lvl`\"\n    if isinstance(o,Tensor): o = to_np(o)\n    with tables.open_file(p, mode='w', filters=_comp_filter(lib=complib,lvl=lvl)) as f: f.create_carray('/', 'data', obj=o)\n\n# Cell\n@patch\ndef load_array(p:Path):\n    \"Save numpy array to a `pytables` file\"\n    with tables.open_file(p, 'r') as f: return f.root.data.read()\n\n# Cell\ndef base_doc(elt):\n    \"Print a base documentation of `elt`\"\n    name = getattr(elt, '__qualname__', getattr(elt, '__name__', ''))\n    print(f'{name}{inspect.signature(elt)}\\n{inspect.getdoc(elt)}\\n')\n    print('To get a prettier result with hyperlinks to source code and documentation, install nbdev: pip install nbdev')\n\n# Cell\ndef doc(elt):\n    \"Try to use doc form nbdev and fall back to `base_doc`\"\n    try:\n        from nbdev.showdoc import doc\n        doc(elt)\n    except: base_doc(elt)\n\n# Cell\ndef nested_reorder(t, idxs):\n    \"Reorder all tensors in `t` using `idxs`\"\n    if isinstance(t, (Tensor,L)): return t[idxs]\n    elif is_listy(t): return type(t)(nested_reorder(t_, idxs) for t_ in t)\n    if t is None: return t\n    raise TypeError(f\"Expected tensor, tuple, list or L but got {type(t)}\")\n\n# Cell\ndef to_image(x):\n    if isinstance(x,Image.Image): return x\n    if isinstance(x,Tensor): x = to_np(x.permute((1,2,0)))\n    if x.dtype==np.float32: x = (x*255).astype(np.uint8)\n    return Image.fromarray(x, mode=['RGB','CMYK'][x.shape[0]==4])\n\n# Cell\ndef make_cross_image(bw=True):\n    \"Create a tensor containing a cross image, either `bw` (True) or color\"\n    if bw:\n        im = torch.zeros(5,5)\n        im[2,:] = 1.\n        im[:,2] = 1.\n    else:\n        im = torch.zeros(3,5,5)\n        im[0,2,:] = 1.\n        im[1,:,2] = 1.\n    return im\n\n# Cell\ndef show_image_batch(b, show=show_titled_image, items=9, cols=3, figsize=None, **kwargs):\n    \"Display batch `b` in a grid of size `items` with `cols` width\"\n    if items<cols: cols=items\n    rows = (items+cols-1) // cols\n    if figsize is None: figsize = (cols*3, rows*3)\n    fig,axs = plt.subplots(rows, cols, figsize=figsize)\n    for *o,ax in zip(*to_cpu(b), axs.flatten()): show(o, ax=ax, **kwargs)\n\n# Cell\ndef requires_grad(m):\n    \"Check if the first parameter of `m` requires grad or not\"\n    ps = list(m.parameters())\n    return ps[0].requires_grad if len(ps)>0 else False\n\n# Cell\ndef init_default(m, func=nn.init.kaiming_normal_):\n    \"Initialize `m` weights with `func` and set `bias` to 0.\"\n    if func:\n        if hasattr(m, 'weight'): func(m.weight)\n        if hasattr(m, 'bias') and hasattr(m.bias, 'data'): m.bias.data.fill_(0.)\n    return m\n\n# Cell\ndef cond_init(m, func):\n    \"Apply `init_default` to `m` unless it's a batchnorm module\"\n    if (not isinstance(m, norm_types)) and requires_grad(m): init_default(m, func)\n\n# Cell\ndef apply_leaf(m, f):\n    \"Apply `f` to children of `m`.\"\n    c = m.children()\n    if isinstance(m, nn.Module): f(m)\n    for l in c: apply_leaf(l,f)\n\n# Cell\ndef apply_init(m, func=nn.init.kaiming_normal_):\n    \"Initialize all non-batchnorm layers of `m` with `func`.\"\n    apply_leaf(m, partial(cond_init, func=func))\n\n# Cell\nfrom multiprocessing import Process, Queue\n\n# Cell\ndef set_num_threads(nt):\n    \"Get numpy (and others) to use `nt` threads\"\n    try: import mkl; mkl.set_num_threads(nt)\n    except: pass\n    torch.set_num_threads(1)\n    os.environ['IPC_ENABLE']='1'\n    for o in ['OPENBLAS_NUM_THREADS','NUMEXPR_NUM_THREADS','OMP_NUM_THREADS','MKL_NUM_THREADS']:\n        os.environ[o] = str(nt)\n\n# Cell\n@delegates(concurrent.futures.ProcessPoolExecutor)\nclass ProcessPoolExecutor(concurrent.futures.ProcessPoolExecutor):\n    def __init__(self, max_workers=None, on_exc=print, **kwargs):\n        self.not_parallel = max_workers==0\n        self.on_exc = on_exc\n        if self.not_parallel: max_workers=1\n        super().__init__(max_workers, **kwargs)\n\n    def map(self, f, items, *args, **kwargs):\n        g = partial(f, *args, **kwargs)\n        if self.not_parallel: return map(g, items)\n        try: return super().map(g, items)\n        except Exception as e: self.on_exc(e)\n\n# Cell\ndef parallel(f, items, *args, n_workers=defaults.cpus, total=None, progress=True, **kwargs):\n    \"Applies `func` in parallel to `items`, using `n_workers`\"\n    with ProcessPoolExecutor(n_workers) as ex:\n        r = ex.map(f,items, *args, **kwargs)\n        if progress:\n            if total is None: total = len(items)\n            r = progress_bar(r, total=total, leave=False)\n        return L(r)\n\n# Cell\ndef run_procs(f, f_done, args):\n    \"Call `f` for each item in `args` in parallel, yielding `f_done`\"\n    processes = L(args).map(Process, args=arg0, target=f)\n    for o in processes: o.start()\n    try: yield from f_done()\n    except Exception as e: print(e)\n    finally: processes.map(Self.join())\n\n# Cell\ndef parallel_gen(cls, items, n_workers=defaults.cpus, as_gen=False, **kwargs):\n    \"Instantiate `cls` in `n_workers` procs & call each on a subset of `items` in parallel.\"\n    batches = np.array_split(items, n_workers)\n    idx = np.cumsum(0 + L(batches).map(len))\n    queue = Queue()\n    def f(batch, start_idx):\n        for i,b in enumerate(cls(**kwargs)(batch)): queue.put((start_idx+i,b))\n    def done(): return (queue.get() for _ in progress_bar(items, leave=False))\n    yield from run_procs(f, done, L(batches,idx).zip())\n\n# Cell\ndef script_use_ctx(f):\n    \"Decorator: create jit script and pass everything in `ctx.saved_variables to `f`, after `*args`\"\n    sf = torch.jit.script(f)\n    def _f(ctx, *args, **kwargs): return sf(*args, *ctx.saved_variables, **kwargs)\n    return update_wrapper(_f,f)\n\n# Cell\ndef script_save_ctx(static, *argidx):\n    \"Decorator: create jit script and save args with indices `argidx` using `ctx.save_for_backward`\"\n    def _dec(f):\n        sf = torch.jit.script(f)\n        def _f(ctx, *args, **kwargs):\n            if argidx:\n                save = [args[o] for o in argidx]\n                ctx.save_for_backward(*save)\n            if not argidx: args = [ctx]+args\n            return sf(*args, **kwargs)\n        if static: _f = staticmethod(_f)\n        return update_wrapper(_f,f)\n    return _dec\n\n# Cell\ndef script_fwd(*argidx):\n    \"Decorator: create static jit script and save args with indices `argidx` using `ctx.save_for_backward`\"\n    return script_save_ctx(True, *argidx)\n\n# Cell\ndef script_bwd(f):\n    \"Decorator: create static jit script and pass everything in `ctx.saved_variables to `f`, after `*args`\"\n    return staticmethod(script_use_ctx(f))\n\n# Cell\ndef grad_module(cls):\n    \"Decorator: convert `cls` into an autograd function\"\n    class _c(nn.Module):\n        def forward(self, *args, **kwargs): return cls.apply(*args, **kwargs)\n    return _c\n\n# Comes from 13b_metrics.ipynb, cell\ndef flatten_check(inp, targ):\n    \"Check that `out` and `targ` have the same number of elements and flatten them.\"\n    inp,targ = inp.contiguous().view(-1),targ.contiguous().view(-1)\n    test_eq(len(inp), len(targ))\n    return inp,targ\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nprint(\"---------------------- PASSED torch_base.py\")\n\n\n\nprint(\"---------------------------------------------------------- ALMOOOOST END\")\n\n\n################################################################33\n\n\n\n\n\nfrom datetime import datetime\n\n@patch_to(Learner)\ndef one_batch(self, i, b):\n        print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}                   Learner#one_batch@BATCH {i}\")\n        self.iter = i\n        try:\n            print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}                   Learner#one_batch@SPLIT {i}\")\n            self._split(b);                                  self('begin_batch')\n            print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}                 Learner#one_batch@ {i} called begin_batch\")\n            self.pred = self.model(*self.xb);                self('after_pred')\n            print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}                 Learner#one_batch@ {i} called after_pred\")\n            if len(self.yb) == 0: return\n            print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}                 Learner#one_batch@ {i} did not return becasue yb.length == 0\")\n            self.loss = self.loss_func(self.pred, *self.yb); self('after_loss')\n            print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}                 Learner#one_batch@ {i} called after_loss\")\n            if not self.training: return\n            print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}                 Learner#one_batch@ {i} did not return because we are training\")\n            self.loss.backward();                            self('after_backward')\n            print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}                 Learner#one_batch@ {i} called after_backward\")\n            #self.opt.step();                                 self('after_step')\n            xm.optimizer_step(self.opt,barrier=True);        self('after_step')\n            print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}                 Learner#one_batch@ {i} called after_step\")\n            self.opt.zero_grad()\n            print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}                 Learner#one_batch@ {i} called zero_grad!!!!!!!\")\n        except CancelBatchException:\n            self('after_cancel_batch')\n            print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}                 Learner#one_batch@ {i} called after_cancel_batch\")\n        finally:\n            if False:\n                # TRACE: print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}                 {i} AFTER BATCH NOT CALLED\")\n                # TRACE: print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}                 {i} AFTER BATCH NOT CALLED\")\n                # TRACE: print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}                 {i} AFTER BATCH NOT CALLED\")\n                # TRACE: print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}                 {i} AFTER BATCH NOT CALLED\")\n                print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}                 {i} AFTER BATCH NOT CALLED\")\n            else:\n                print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}                 {i} WILL CALL after_batch\")\n                self('after_batch')\n                print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}                 {i} called after_batch\")\n\n\n\n\n\nfrom torch.utils.data.dataloader import _MultiProcessingDataLoaderIter,_SingleProcessDataLoaderIter,_DatasetKind\n_loaders = (_MultiProcessingDataLoaderIter,_SingleProcessDataLoaderIter)\n\n\n@patch_to(DataLoader)\ndef __iter__(self):\n        print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}  DataLoader#DataLoader#DataLoader#__iter__                         0\")\n        self.randomize()\n        self.before_iter()\n        print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}  DataLoader#DataLoader#DataLoader#__iter__ START FOR               1\")\n        xxxx = _loaders[self.fake_l.num_workers==0](self.fake_l)\n        print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}  DataLoader#DataLoader#DataLoader#__iter__ ----------------------- 1\")\n        for b in xxxx:\n            print(\"======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\")\n            print(\"======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\")\n            print(\"======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\")\n            print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}  DataLoader#DataLoader#DataLoader#__iter__ FOR FOR FOR FOR ---------------------------------------------\")\n            if self.device is not None:\n                print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}  DataLoader#DataLoader#DataLoader#iterator to device from {b[0].device} y {b[1].device} to {self.device}\")\n                b = to_device(b, self.device)\n                print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}  DataLoader#DataLoader#DataLoader#iterator to done!!!!\")\n            print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}  DataLoader#DataLoader#DataLoader#yielding                    3!!!! yield self.after_batch({b[0].device} y {b[1].device}) len of b is {len(b)}\")\n            yield self.after_batch(b)\n            print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}  DataLoader#DataLoader#DataLoader#yielding                    4!!!!\")\n        print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}  DataLoader#DataLoader#DataLoader#__iter__ END FOR                 2\")\n        self.after_iter()\n        print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}   DataLoader#DataLoader#DataLoader#__iter__ after ITER\")\n        if hasattr(self, 'it'): delattr(self, 'it')\n        print(f\"{datetime.now().strftime(' (%H:%M:%S.%f)')}     DataLoader#DataLoader#DataLoader#END __iter__\")\n\n\n\n@patch_to(Learner)\ndef all_batches(self):\n        print(\"                                          Learner#ALL_BATCHES\")\n        self.n_iter = len(self.dl)\n        print(\"                                          Learner#ALL_BATCHES GEN enumerator!!!!\")\n        e = enumerate(self.dl)\n        print(\"                                          Learner#ALL_BATCHES generate enumerator!!!!\")\n        for o in e:\n            print(\">>>> =======================================================================\")\n            print(\">>>> =======================================================================\")\n            print(f\">>>>                                           Learner#ALL_BATCHES CALL ENTER [{o[0]}]\")\n            print(\">>>> =======================================================================\")\n            print(\">>>> ======================================================================= OOOOOOOOOOOOOOOO call self.one_batch\")\n            self.one_batch(*o)\n            print(\"<<<< ======================================================================= OOOOOOOOOOOOOOOO\")\n            print(\"<<<< =======================================================================\")\n            print(\"<<<< =======================================================================\")\n            print(\"<<<<                                           Learner#ALL_BATCHES CALL EXIT\")\n            print(\"<<<< ====================================================================***\")\n            print(\"<<<< ========================================*******************************\")\n            print(\"<<<< ===========================********************************************\")\n        \n\n\n\n\n\n@patch_to(Learner)\ndef create_opt(self):\n        # TRACE: print_local(\"create_opt!!!\")\n        ooo = self.opt_func(self.splitter(self.model), lr=self.lr)\n        prox = XLAOptimProxy(ooo)\n        self.opt = prox\n        if not self.wd_bn_bias:\n            for p in self._bn_bias_state(True ): p['do_wd'] = False\n        if self.train_bn:\n            for p in self._bn_bias_state(False): p['force_train'] = True\n\n#proxyLearn = Learner(dls_tpu, Lenet2(), metrics=accuracy, opt_func=Adam)#, cbs=CallbackXLA)\n\n\n\n#print(\"---------------------------------------------------------- Before fit\")\n#proxyLearn.fit(1, 10e-3) # 0.05) NOTE: Im not sure if this works...!!! it is now 96!\n#print(\"---------------------------------------------------------- After fit\")\n\n\n\nprint(\".............................................\\n\"*20)\n\n@patch\n@log_args(but_as=Learner.fit)\ndef fit_one_cycle(self:Learner, n_epoch, lr_max=None, div=25., div_final=1e5, pct_start=0.25, wd=None,\n                  moms=None, cbs=None, reset_opt=False):\n    \"Fit `self.model` for `n_epoch` using the 1cycle policy.\"\n    if self.opt is None: self.create_opt()\n    self.opt.set_hyper('lr', self.lr if lr_max is None else lr_max)\n    lr_max = np.array([h['lr'] for h in self.opt.hypers])\n    scheds = {'lr': combined_cos(pct_start, lr_max/div, lr_max, lr_max/div_final),\n              'mom': combined_cos(pct_start, *(self.moms if moms is None else moms))}\n    self.fit(n_epoch, cbs=ParamScheduler(scheds)+L(cbs), reset_opt=reset_opt, wd=wd)\n\n\n@patch\n@log_args(but_as=Learner.fit)\n@delegates(Learner.fit_one_cycle)\ndef fine_tune(self:Learner, epochs, base_lr=2e-3, freeze_epochs=1, lr_mult=100,\n              pct_start=0.3, div=5.0, **kwargs):\n    \"Fine tune with `freeze` for `freeze_epochs` then with `unfreeze` from `epochs` using discriminative LR\"\n    self.freeze()\n    self.fit_one_cycle(freeze_epochs, slice(base_lr), pct_start=0.99, **kwargs)\n    base_lr /= 2\n    self.unfreeze()\n    self.fit_one_cycle(epochs, slice(base_lr/lr_mult, base_lr), pct_start=pct_start, div=div, **kwargs)\n\n\n@patch\ndef freeze_to(self:Learner, n):\n    if self.opt is None: self.create_opt()\n    self.opt.freeze_to(n)\n    self.opt.clear_state()\n\n@patch\ndef freeze(self:Learner): self.freeze_to(-1)\n\n@patch\ndef unfreeze(self:Learner): self.freeze_to(0)\n\n\ndef _add_norm(dls, meta, pretrained):\n    if not pretrained: return\n    after_batch = dls.after_batch\n    if first(o for o in after_batch.fs if isinstance(o,Normalize)): return\n    stats = meta.get('stats')\n    if stats is None: return\n    after_batch.add(Normalize.from_stats(*stats))\n\n\ndef default_split(m):\n    \"Default split of a model between body and head\"\n    return L(m[0], m[1:]).map(params)\n_default_meta    = {'cut':None, 'split':default_split}\n\n\n\n@log_args(to_return=True, but_as=Learner.__init__)\n@delegates(Learner.__init__)\ndef cnn_learner(dls, arch, loss_func=None, pretrained=True, cut=None, splitter=None,\n                y_range=None, config=None, n_out=None, normalize=True, **kwargs):\n    \"Build a convnet style learner from `dls` and `arch`\"\n    print(f\"cnn dls.device {dls.device}\")\n    if config is None: config = {}\n    meta = model_meta.get(arch, _default_meta)\n    if n_out is None: n_out = get_c(dls)\n    assert n_out, \"`n_out` is not defined, and could not be infered from data, set `dls.c` or pass `n_out`\"\n    if normalize: _add_norm(dls, meta, pretrained)\n    if y_range is None and 'y_range' in config: y_range = config.pop('y_range')\n    print(f\"cnn dls.device MIDDLE\")\n    model = create_cnn_model(arch, n_out, ifnone(cut, meta['cut']), pretrained, y_range=y_range, **config)\n    learn = Learner(dls, model, loss_func=loss_func, splitter=ifnone(splitter, meta['split']), **kwargs)\n    if pretrained: learn.freeze()\n    print(f\"cnn dls.device END\")\n    return learn\n\npath = untar_data(URLs.PETS)/'images'\npat = r'(.+)_\\d+.jpg$'\ndatablock = DataBlock(\n    blocks=(ImageBlock,CategoryBlock),\n    get_items=get_image_files,\n    splitter=RandomSplitter(seed=42),\n    get_y=using_attr(RegexLabeller(pat),'name'),\n    item_tfms=Resize(224),\n    # batch_tfms=[]\n    batch_tfms=aug_transforms(size=224,min_scale=0.75)\n)\ndatablock.summary(path)\ndls = datablock.dataloaders(path,bs=256, device=tpu_device)\nprint(\"CNN Learner\")\nlearner = cnn_learner(dls, resnet34, metrics=accuracy)\nprint(\"FINE TUNE\")\nlearner.fine_tune(1,base_lr=4e-3,freeze_epochs=2)\nprint(\"end FINE TUNE\")\n```\n\n    ---------------------------------------------------------- START\n    device is xla:1\n    ---------------------------------------------------------- START:1\n    ---------------------------------------------------------- START:2\n    ---------------------------------------------------------- START:3\n     (07:15:02.164228)  DataLoader#DataLoader#DataLoader#__iter__                         0\n     (07:15:02.165292)  DataLoader#DataLoader#DataLoader#__iter__ START FOR               1\n     (07:15:02.169795)  DataLoader#DataLoader#DataLoader#__iter__ ----------------------- 1\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n     (07:15:02.193488)  DataLoader#DataLoader#DataLoader#__iter__ FOR FOR FOR FOR ---------------------------------------------\n     (07:15:02.193909)  DataLoader#DataLoader#DataLoader#iterator to device from cpu y cpu to xla:1\n     (07:15:02.201670)  DataLoader#DataLoader#DataLoader#iterator to done!!!!\n     (07:15:02.202112)  DataLoader#DataLoader#DataLoader#yielding                    3!!!! yield self.after_batch(xla:1 y xla:1) len of b is 2\n    ---------------------------------------------------------- START:4\n    ---------------------------------------------------------- START:5\n    ---------------------------------------------------------- START:6\n    ---------------------------------------------------------- START:7\n    ---------------------------------------------------------- START:8 enbd STARET\n    ---------------------- STARTED class Learner\n    ---------------------- PASSED LEARNER\n    ---------------------- STARTED torch_base.py\n    ---------------------- PASSED torch_base.py\n    ---------------------------------------------------------- ALMOOOOST END\n    .............................................\n    .............................................\n    .............................................\n    .............................................\n    .............................................\n    .............................................\n    .............................................\n    .............................................\n    .............................................\n    .............................................\n    .............................................\n    .............................................\n    .............................................\n    .............................................\n    .............................................\n    .............................................\n    .............................................\n    .............................................\n    .............................................\n    .............................................\n    \n    Setting-up type transforms pipelines\n    Collecting items from /root/.fastai/data/oxford-iiit-pet/images\n    Found 7390 items\n    2 datasets of sizes 5912,1478\n    Setting up Pipeline: PILBase.create\n    Setting up Pipeline: partial -> Categorize\n    \n    Building one sample\n      Pipeline: PILBase.create\n        starting from\n          /root/.fastai/data/oxford-iiit-pet/images/scottish_terrier_127.jpg\n        applying PILBase.create gives\n          PILImage mode=RGB size=375x500\n      Pipeline: partial -> Categorize\n        starting from\n          /root/.fastai/data/oxford-iiit-pet/images/scottish_terrier_127.jpg\n        applying partial gives\n          scottish_terrier\n        applying Categorize gives\n          TensorCategory(32)\n    \n    Final sample: (PILImage mode=RGB size=375x500, TensorCategory(32))\n    \n    \n    Setting up after_item: Pipeline: Resize -> ToTensor\n    Setting up before_batch: Pipeline: \n    Setting up after_batch: Pipeline: IntToFloatTensor -> AffineCoordTfm -> RandomResizedCropGPU -> LightingTfm\n    \n    Building one batch\n    Applying item_tfms to the first sample:\n      Pipeline: Resize -> ToTensor\n        starting from\n          (PILImage mode=RGB size=375x500, TensorCategory(32))\n        applying Resize gives\n          (PILImage mode=RGB size=224x224, TensorCategory(32))\n        applying ToTensor gives\n          (TensorImage of size 3x224x224, TensorCategory(32))\n    \n    Adding the next 3 samples\n    \n    No before_batch transform to apply\n    \n    Collating items in a batch\n    \n    Applying batch_tfms to the batch built\n      Pipeline: IntToFloatTensor -> AffineCoordTfm -> RandomResizedCropGPU -> LightingTfm\n        starting from\n          (TensorImage of size 4x3x224x224, TensorCategory([32, 20, 29, 35]))\n        applying IntToFloatTensor gives\n          (TensorImage of size 4x3x224x224, TensorCategory([32, 20, 29, 35]))\n        applying AffineCoordTfm gives\n          (TensorImage of size 4x3x224x224, TensorCategory([32, 20, 29, 35]))\n        applying RandomResizedCropGPU gives\n          (TensorImage of size 4x3x224x224, TensorCategory([32, 20, 29, 35]))\n        applying LightingTfm gives\n          (TensorImage of size 4x3x224x224, TensorCategory([32, 20, 29, 35]))\n    CNN Learner\n    cnn dls.device xla:1\n    cnn dls.device MIDDLE\n    cnn dls.device END\n    FINE TUNE\n\n\n\n\n    <div>\n        <style>\n            /* Turns off some styling */\n            progress {\n                /* gets rid of default border in Firefox and Opera. */\n                border: none;\n                /* Needs to be in here for Safari polyfill so background images work as expected. */\n                background-size: auto;\n            }\n            .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {\n                background: #F44336;\n            }\n        </style>\n      <progress value='0' class='' max='2' style='width:300px; height:20px; vertical-align: middle;'></progress>\n      0.00% [0/2 00:00<00:00]\n    </div>\n\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: left;\">\n      <th>epoch</th>\n      <th>train_loss</th>\n      <th>valid_loss</th>\n      <th>accuracy</th>\n      <th>time</th>\n    </tr>\n  </thead>\n  <tbody>\n  </tbody>\n</table><p>\n\n    <div>\n        <style>\n            /* Turns off some styling */\n            progress {\n                /* gets rid of default border in Firefox and Opera. */\n                border: none;\n                /* Needs to be in here for Safari polyfill so background images work as expected. */\n                background-size: auto;\n            }\n            .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {\n                background: #F44336;\n            }\n        </style>\n      <progress value='17' class='' max='23' style='width:300px; height:20px; vertical-align: middle;'></progress>\n      73.91% [17/23 04:18<01:31 3.8557]\n    </div>\n\n\n\n                                              Learner#ALL_BATCHES\n                                              Learner#ALL_BATCHES GEN enumerator!!!!\n                                              Learner#ALL_BATCHES generate enumerator!!!!\n     (07:15:25.013256)  DataLoader#DataLoader#DataLoader#__iter__                         0\n     (07:15:25.014005)  DataLoader#DataLoader#DataLoader#__iter__ START FOR               1\n     (07:15:25.097918)  DataLoader#DataLoader#DataLoader#__iter__ ----------------------- 1\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n     (07:15:37.173562)  DataLoader#DataLoader#DataLoader#__iter__ FOR FOR FOR FOR ---------------------------------------------\n     (07:15:37.176881)  DataLoader#DataLoader#DataLoader#iterator to device from cpu y cpu to xla:1\n     (07:15:39.316684)  DataLoader#DataLoader#DataLoader#iterator to done!!!!\n     (07:15:39.319828)  DataLoader#DataLoader#DataLoader#yielding                    3!!!! yield self.after_batch(xla:1 y xla:1) len of b is 2\n    >>>> =======================================================================\n    >>>> =======================================================================\n    >>>>                                           Learner#ALL_BATCHES CALL ENTER [0]\n    >>>> =======================================================================\n    >>>> ======================================================================= OOOOOOOOOOOOOOOO call self.one_batch\n     (07:15:54.172144)                   Learner#one_batch@BATCH 0\n     (07:15:54.172765)                   Learner#one_batch@SPLIT 0\n     (07:15:54.188308)                 Learner#one_batch@ 0 called begin_batch\n     (07:16:02.418419)                 Learner#one_batch@ 0 called after_pred\n     (07:16:02.419087)                 Learner#one_batch@ 0 did not return becasue yb.length == 0\n     (07:16:02.429082)                 Learner#one_batch@ 0 called after_loss\n     (07:16:02.429621)                 Learner#one_batch@ 0 did not return because we are training\n     (07:16:11.455029)                 Learner#one_batch@ 0 called after_backward\n     (07:16:27.284186)                 Learner#one_batch@ 0 called after_step\n     (07:16:27.292841)                 Learner#one_batch@ 0 called zero_grad!!!!!!!\n     (07:16:27.293264)                 0 WILL CALL after_batch\n     (07:16:27.639723)                 0 called after_batch\n    <<<< ======================================================================= OOOOOOOOOOOOOOOO\n    <<<< =======================================================================\n    <<<< =======================================================================\n    <<<<                                           Learner#ALL_BATCHES CALL EXIT\n    <<<< ====================================================================***\n    <<<< ========================================*******************************\n    <<<< ===========================********************************************\n     (07:16:27.642913)  DataLoader#DataLoader#DataLoader#yielding                    4!!!!\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n     (07:16:27.644895)  DataLoader#DataLoader#DataLoader#__iter__ FOR FOR FOR FOR ---------------------------------------------\n     (07:16:27.645288)  DataLoader#DataLoader#DataLoader#iterator to device from cpu y cpu to xla:1\n     (07:16:29.304716)  DataLoader#DataLoader#DataLoader#iterator to done!!!!\n     (07:16:29.305916)  DataLoader#DataLoader#DataLoader#yielding                    3!!!! yield self.after_batch(xla:1 y xla:1) len of b is 2\n    >>>> =======================================================================\n    >>>> =======================================================================\n    >>>>                                           Learner#ALL_BATCHES CALL ENTER [1]\n    >>>> =======================================================================\n    >>>> ======================================================================= OOOOOOOOOOOOOOOO call self.one_batch\n     (07:16:38.629329)                   Learner#one_batch@BATCH 1\n     (07:16:38.629725)                   Learner#one_batch@SPLIT 1\n     (07:16:38.638068)                 Learner#one_batch@ 1 called begin_batch\n     (07:16:38.935730)                 Learner#one_batch@ 1 called after_pred\n     (07:16:38.936368)                 Learner#one_batch@ 1 did not return becasue yb.length == 0\n     (07:16:38.945960)                 Learner#one_batch@ 1 called after_loss\n     (07:16:38.946394)                 Learner#one_batch@ 1 did not return because we are training\n     (07:16:39.479736)                 Learner#one_batch@ 1 called after_backward\n     (07:16:39.527306)                 Learner#one_batch@ 1 called after_step\n     (07:16:39.535856)                 Learner#one_batch@ 1 called zero_grad!!!!!!!\n     (07:16:39.536288)                 1 WILL CALL after_batch\n     (07:16:39.836072)                 1 called after_batch\n    <<<< ======================================================================= OOOOOOOOOOOOOOOO\n    <<<< =======================================================================\n    <<<< =======================================================================\n    <<<<                                           Learner#ALL_BATCHES CALL EXIT\n    <<<< ====================================================================***\n    <<<< ========================================*******************************\n    <<<< ===========================********************************************\n     (07:16:39.839167)  DataLoader#DataLoader#DataLoader#yielding                    4!!!!\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n     (07:16:39.860763)  DataLoader#DataLoader#DataLoader#__iter__ FOR FOR FOR FOR ---------------------------------------------\n     (07:16:39.861283)  DataLoader#DataLoader#DataLoader#iterator to device from cpu y cpu to xla:1\n     (07:16:41.507236)  DataLoader#DataLoader#DataLoader#iterator to done!!!!\n     (07:16:41.508168)  DataLoader#DataLoader#DataLoader#yielding                    3!!!! yield self.after_batch(xla:1 y xla:1) len of b is 2\n    >>>> =======================================================================\n    >>>> =======================================================================\n    >>>>                                           Learner#ALL_BATCHES CALL ENTER [2]\n    >>>> =======================================================================\n    >>>> ======================================================================= OOOOOOOOOOOOOOOO call self.one_batch\n     (07:16:50.692456)                   Learner#one_batch@BATCH 2\n     (07:16:50.692858)                   Learner#one_batch@SPLIT 2\n     (07:16:50.701309)                 Learner#one_batch@ 2 called begin_batch\n     (07:16:50.992070)                 Learner#one_batch@ 2 called after_pred\n     (07:16:50.992703)                 Learner#one_batch@ 2 did not return becasue yb.length == 0\n     (07:16:51.002458)                 Learner#one_batch@ 2 called after_loss\n     (07:16:51.002877)                 Learner#one_batch@ 2 did not return because we are training\n     (07:16:51.503525)                 Learner#one_batch@ 2 called after_backward\n     (07:16:51.551250)                 Learner#one_batch@ 2 called after_step\n     (07:16:51.559538)                 Learner#one_batch@ 2 called zero_grad!!!!!!!\n     (07:16:51.560124)                 2 WILL CALL after_batch\n     (07:16:51.861375)                 2 called after_batch\n    <<<< ======================================================================= OOOOOOOOOOOOOOOO\n    <<<< =======================================================================\n    <<<< =======================================================================\n    <<<<                                           Learner#ALL_BATCHES CALL EXIT\n    <<<< ====================================================================***\n    <<<< ========================================*******************************\n    <<<< ===========================********************************************\n     (07:16:51.864756)  DataLoader#DataLoader#DataLoader#yielding                    4!!!!\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n     (07:16:51.866781)  DataLoader#DataLoader#DataLoader#__iter__ FOR FOR FOR FOR ---------------------------------------------\n     (07:16:51.867227)  DataLoader#DataLoader#DataLoader#iterator to device from cpu y cpu to xla:1\n     (07:16:53.458107)  DataLoader#DataLoader#DataLoader#iterator to done!!!!\n     (07:16:53.458968)  DataLoader#DataLoader#DataLoader#yielding                    3!!!! yield self.after_batch(xla:1 y xla:1) len of b is 2\n    >>>> =======================================================================\n    >>>> =======================================================================\n    >>>>                                           Learner#ALL_BATCHES CALL ENTER [3]\n    >>>> =======================================================================\n    >>>> ======================================================================= OOOOOOOOOOOOOOOO call self.one_batch\n     (07:17:02.871614)                   Learner#one_batch@BATCH 3\n     (07:17:02.872013)                   Learner#one_batch@SPLIT 3\n     (07:17:02.880486)                 Learner#one_batch@ 3 called begin_batch\n     (07:17:03.176678)                 Learner#one_batch@ 3 called after_pred\n     (07:17:03.177407)                 Learner#one_batch@ 3 did not return becasue yb.length == 0\n     (07:17:03.186884)                 Learner#one_batch@ 3 called after_loss\n     (07:17:03.187308)                 Learner#one_batch@ 3 did not return because we are training\n     (07:17:03.692511)                 Learner#one_batch@ 3 called after_backward\n     (07:17:03.736704)                 Learner#one_batch@ 3 called after_step\n     (07:17:03.744625)                 Learner#one_batch@ 3 called zero_grad!!!!!!!\n     (07:17:03.745025)                 3 WILL CALL after_batch\n     (07:17:04.045452)                 3 called after_batch\n    <<<< ======================================================================= OOOOOOOOOOOOOOOO\n    <<<< =======================================================================\n    <<<< =======================================================================\n    <<<<                                           Learner#ALL_BATCHES CALL EXIT\n    <<<< ====================================================================***\n    <<<< ========================================*******************************\n    <<<< ===========================********************************************\n     (07:17:04.048594)  DataLoader#DataLoader#DataLoader#yielding                    4!!!!\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n     (07:17:04.062058)  DataLoader#DataLoader#DataLoader#__iter__ FOR FOR FOR FOR ---------------------------------------------\n     (07:17:04.062474)  DataLoader#DataLoader#DataLoader#iterator to device from cpu y cpu to xla:1\n     (07:17:05.695723)  DataLoader#DataLoader#DataLoader#iterator to done!!!!\n     (07:17:05.696649)  DataLoader#DataLoader#DataLoader#yielding                    3!!!! yield self.after_batch(xla:1 y xla:1) len of b is 2\n    >>>> =======================================================================\n    >>>> =======================================================================\n    >>>>                                           Learner#ALL_BATCHES CALL ENTER [4]\n    >>>> =======================================================================\n    >>>> ======================================================================= OOOOOOOOOOOOOOOO call self.one_batch\n     (07:17:15.173362)                   Learner#one_batch@BATCH 4\n     (07:17:15.173872)                   Learner#one_batch@SPLIT 4\n     (07:17:15.182551)                 Learner#one_batch@ 4 called begin_batch\n     (07:17:15.475314)                 Learner#one_batch@ 4 called after_pred\n     (07:17:15.475943)                 Learner#one_batch@ 4 did not return becasue yb.length == 0\n     (07:17:15.485822)                 Learner#one_batch@ 4 called after_loss\n     (07:17:15.486259)                 Learner#one_batch@ 4 did not return because we are training\n     (07:17:15.994845)                 Learner#one_batch@ 4 called after_backward\n     (07:17:16.060033)                 Learner#one_batch@ 4 called after_step\n     (07:17:16.069190)                 Learner#one_batch@ 4 called zero_grad!!!!!!!\n     (07:17:16.069716)                 4 WILL CALL after_batch\n     (07:17:16.368443)                 4 called after_batch\n    <<<< ======================================================================= OOOOOOOOOOOOOOOO\n    <<<< =======================================================================\n    <<<< =======================================================================\n    <<<<                                           Learner#ALL_BATCHES CALL EXIT\n    <<<< ====================================================================***\n    <<<< ========================================*******************************\n    <<<< ===========================********************************************\n     (07:17:16.371542)  DataLoader#DataLoader#DataLoader#yielding                    4!!!!\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n     (07:17:16.390493)  DataLoader#DataLoader#DataLoader#__iter__ FOR FOR FOR FOR ---------------------------------------------\n     (07:17:16.390998)  DataLoader#DataLoader#DataLoader#iterator to device from cpu y cpu to xla:1\n     (07:17:18.015838)  DataLoader#DataLoader#DataLoader#iterator to done!!!!\n     (07:17:18.017007)  DataLoader#DataLoader#DataLoader#yielding                    3!!!! yield self.after_batch(xla:1 y xla:1) len of b is 2\n    >>>> =======================================================================\n    >>>> =======================================================================\n    >>>>                                           Learner#ALL_BATCHES CALL ENTER [5]\n    >>>> =======================================================================\n    >>>> ======================================================================= OOOOOOOOOOOOOOOO call self.one_batch\n     (07:17:27.511329)                   Learner#one_batch@BATCH 5\n     (07:17:27.511716)                   Learner#one_batch@SPLIT 5\n     (07:17:27.519869)                 Learner#one_batch@ 5 called begin_batch\n     (07:17:27.806226)                 Learner#one_batch@ 5 called after_pred\n     (07:17:27.806851)                 Learner#one_batch@ 5 did not return becasue yb.length == 0\n     (07:17:27.816301)                 Learner#one_batch@ 5 called after_loss\n     (07:17:27.816708)                 Learner#one_batch@ 5 did not return because we are training\n     (07:17:28.316518)                 Learner#one_batch@ 5 called after_backward\n     (07:17:28.371950)                 Learner#one_batch@ 5 called after_step\n     (07:17:28.379936)                 Learner#one_batch@ 5 called zero_grad!!!!!!!\n     (07:17:28.380358)                 5 WILL CALL after_batch\n     (07:17:28.679914)                 5 called after_batch\n    <<<< ======================================================================= OOOOOOOOOOOOOOOO\n    <<<< =======================================================================\n    <<<< =======================================================================\n    <<<<                                           Learner#ALL_BATCHES CALL EXIT\n    <<<< ====================================================================***\n    <<<< ========================================*******************************\n    <<<< ===========================********************************************\n     (07:17:28.683002)  DataLoader#DataLoader#DataLoader#yielding                    4!!!!\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n     (07:17:28.699103)  DataLoader#DataLoader#DataLoader#__iter__ FOR FOR FOR FOR ---------------------------------------------\n     (07:17:28.699491)  DataLoader#DataLoader#DataLoader#iterator to device from cpu y cpu to xla:1\n     (07:17:30.329500)  DataLoader#DataLoader#DataLoader#iterator to done!!!!\n     (07:17:30.330374)  DataLoader#DataLoader#DataLoader#yielding                    3!!!! yield self.after_batch(xla:1 y xla:1) len of b is 2\n    >>>> =======================================================================\n    >>>> =======================================================================\n    >>>>                                           Learner#ALL_BATCHES CALL ENTER [6]\n    >>>> =======================================================================\n    >>>> ======================================================================= OOOOOOOOOOOOOOOO call self.one_batch\n     (07:17:39.871819)                   Learner#one_batch@BATCH 6\n     (07:17:39.872232)                   Learner#one_batch@SPLIT 6\n     (07:17:39.881148)                 Learner#one_batch@ 6 called begin_batch\n     (07:17:40.168253)                 Learner#one_batch@ 6 called after_pred\n     (07:17:40.168862)                 Learner#one_batch@ 6 did not return becasue yb.length == 0\n     (07:17:40.178524)                 Learner#one_batch@ 6 called after_loss\n     (07:17:40.178925)                 Learner#one_batch@ 6 did not return because we are training\n     (07:17:40.679352)                 Learner#one_batch@ 6 called after_backward\n     (07:17:40.741932)                 Learner#one_batch@ 6 called after_step\n     (07:17:40.750410)                 Learner#one_batch@ 6 called zero_grad!!!!!!!\n     (07:17:40.750818)                 6 WILL CALL after_batch\n     (07:17:41.049912)                 6 called after_batch\n    <<<< ======================================================================= OOOOOOOOOOOOOOOO\n    <<<< =======================================================================\n    <<<< =======================================================================\n    <<<<                                           Learner#ALL_BATCHES CALL EXIT\n    <<<< ====================================================================***\n    <<<< ========================================*******************************\n    <<<< ===========================********************************************\n     (07:17:41.053013)  DataLoader#DataLoader#DataLoader#yielding                    4!!!!\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n     (07:17:41.067639)  DataLoader#DataLoader#DataLoader#__iter__ FOR FOR FOR FOR ---------------------------------------------\n     (07:17:41.068008)  DataLoader#DataLoader#DataLoader#iterator to device from cpu y cpu to xla:1\n     (07:17:42.706829)  DataLoader#DataLoader#DataLoader#iterator to done!!!!\n     (07:17:42.707724)  DataLoader#DataLoader#DataLoader#yielding                    3!!!! yield self.after_batch(xla:1 y xla:1) len of b is 2\n    >>>> =======================================================================\n    >>>> =======================================================================\n    >>>>                                           Learner#ALL_BATCHES CALL ENTER [7]\n    >>>> =======================================================================\n    >>>> ======================================================================= OOOOOOOOOOOOOOOO call self.one_batch\n     (07:17:52.108578)                   Learner#one_batch@BATCH 7\n     (07:17:52.108973)                   Learner#one_batch@SPLIT 7\n     (07:17:52.117170)                 Learner#one_batch@ 7 called begin_batch\n     (07:17:52.407579)                 Learner#one_batch@ 7 called after_pred\n     (07:17:52.408273)                 Learner#one_batch@ 7 did not return becasue yb.length == 0\n     (07:17:52.418342)                 Learner#one_batch@ 7 called after_loss\n     (07:17:52.418863)                 Learner#one_batch@ 7 did not return because we are training\n     (07:17:52.929617)                 Learner#one_batch@ 7 called after_backward\n     (07:17:52.985071)                 Learner#one_batch@ 7 called after_step\n     (07:17:52.993915)                 Learner#one_batch@ 7 called zero_grad!!!!!!!\n     (07:17:52.994445)                 7 WILL CALL after_batch\n     (07:17:53.294173)                 7 called after_batch\n    <<<< ======================================================================= OOOOOOOOOOOOOOOO\n    <<<< =======================================================================\n    <<<< =======================================================================\n    <<<<                                           Learner#ALL_BATCHES CALL EXIT\n    <<<< ====================================================================***\n    <<<< ========================================*******************************\n    <<<< ===========================********************************************\n     (07:17:53.297280)  DataLoader#DataLoader#DataLoader#yielding                    4!!!!\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n     (07:17:53.312112)  DataLoader#DataLoader#DataLoader#__iter__ FOR FOR FOR FOR ---------------------------------------------\n     (07:17:53.312535)  DataLoader#DataLoader#DataLoader#iterator to device from cpu y cpu to xla:1\n     (07:17:54.952427)  DataLoader#DataLoader#DataLoader#iterator to done!!!!\n     (07:17:54.953320)  DataLoader#DataLoader#DataLoader#yielding                    3!!!! yield self.after_batch(xla:1 y xla:1) len of b is 2\n    >>>> =======================================================================\n    >>>> =======================================================================\n    >>>>                                           Learner#ALL_BATCHES CALL ENTER [8]\n    >>>> =======================================================================\n    >>>> ======================================================================= OOOOOOOOOOOOOOOO call self.one_batch\n     (07:18:04.588038)                   Learner#one_batch@BATCH 8\n     (07:18:04.588458)                   Learner#one_batch@SPLIT 8\n     (07:18:04.597155)                 Learner#one_batch@ 8 called begin_batch\n     (07:18:04.880335)                 Learner#one_batch@ 8 called after_pred\n     (07:18:04.880982)                 Learner#one_batch@ 8 did not return becasue yb.length == 0\n     (07:18:04.890976)                 Learner#one_batch@ 8 called after_loss\n     (07:18:04.891410)                 Learner#one_batch@ 8 did not return because we are training\n     (07:18:05.389839)                 Learner#one_batch@ 8 called after_backward\n     (07:18:05.444373)                 Learner#one_batch@ 8 called after_step\n     (07:18:05.452203)                 Learner#one_batch@ 8 called zero_grad!!!!!!!\n     (07:18:05.452610)                 8 WILL CALL after_batch\n     (07:18:05.752579)                 8 called after_batch\n    <<<< ======================================================================= OOOOOOOOOOOOOOOO\n    <<<< =======================================================================\n    <<<< =======================================================================\n    <<<<                                           Learner#ALL_BATCHES CALL EXIT\n    <<<< ====================================================================***\n    <<<< ========================================*******************************\n    <<<< ===========================********************************************\n     (07:18:05.755678)  DataLoader#DataLoader#DataLoader#yielding                    4!!!!\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n     (07:18:05.769239)  DataLoader#DataLoader#DataLoader#__iter__ FOR FOR FOR FOR ---------------------------------------------\n     (07:18:05.769638)  DataLoader#DataLoader#DataLoader#iterator to device from cpu y cpu to xla:1\n     (07:18:07.387748)  DataLoader#DataLoader#DataLoader#iterator to done!!!!\n     (07:18:07.389016)  DataLoader#DataLoader#DataLoader#yielding                    3!!!! yield self.after_batch(xla:1 y xla:1) len of b is 2\n    >>>> =======================================================================\n    >>>> =======================================================================\n    >>>>                                           Learner#ALL_BATCHES CALL ENTER [9]\n    >>>> =======================================================================\n    >>>> ======================================================================= OOOOOOOOOOOOOOOO call self.one_batch\n     (07:18:16.712972)                   Learner#one_batch@BATCH 9\n     (07:18:16.713383)                   Learner#one_batch@SPLIT 9\n     (07:18:16.721808)                 Learner#one_batch@ 9 called begin_batch\n     (07:18:17.009228)                 Learner#one_batch@ 9 called after_pred\n     (07:18:17.009853)                 Learner#one_batch@ 9 did not return becasue yb.length == 0\n     (07:18:17.019329)                 Learner#one_batch@ 9 called after_loss\n     (07:18:17.019736)                 Learner#one_batch@ 9 did not return because we are training\n     (07:18:17.525829)                 Learner#one_batch@ 9 called after_backward\n     (07:18:17.579974)                 Learner#one_batch@ 9 called after_step\n     (07:18:17.588367)                 Learner#one_batch@ 9 called zero_grad!!!!!!!\n     (07:18:17.588795)                 9 WILL CALL after_batch\n     (07:18:17.889073)                 9 called after_batch\n    <<<< ======================================================================= OOOOOOOOOOOOOOOO\n    <<<< =======================================================================\n    <<<< =======================================================================\n    <<<<                                           Learner#ALL_BATCHES CALL EXIT\n    <<<< ====================================================================***\n    <<<< ========================================*******************************\n    <<<< ===========================********************************************\n     (07:18:17.892220)  DataLoader#DataLoader#DataLoader#yielding                    4!!!!\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n     (07:18:17.911748)  DataLoader#DataLoader#DataLoader#__iter__ FOR FOR FOR FOR ---------------------------------------------\n     (07:18:17.912169)  DataLoader#DataLoader#DataLoader#iterator to device from cpu y cpu to xla:1\n     (07:18:19.543314)  DataLoader#DataLoader#DataLoader#iterator to done!!!!\n     (07:18:19.544552)  DataLoader#DataLoader#DataLoader#yielding                    3!!!! yield self.after_batch(xla:1 y xla:1) len of b is 2\n    >>>> =======================================================================\n    >>>> =======================================================================\n    >>>>                                           Learner#ALL_BATCHES CALL ENTER [10]\n    >>>> =======================================================================\n    >>>> ======================================================================= OOOOOOOOOOOOOOOO call self.one_batch\n     (07:18:28.829445)                   Learner#one_batch@BATCH 10\n     (07:18:28.829846)                   Learner#one_batch@SPLIT 10\n     (07:18:28.838416)                 Learner#one_batch@ 10 called begin_batch\n     (07:18:29.122685)                 Learner#one_batch@ 10 called after_pred\n     (07:18:29.123335)                 Learner#one_batch@ 10 did not return becasue yb.length == 0\n     (07:18:29.133094)                 Learner#one_batch@ 10 called after_loss\n     (07:18:29.133508)                 Learner#one_batch@ 10 did not return because we are training\n     (07:18:29.643633)                 Learner#one_batch@ 10 called after_backward\n     (07:18:29.701338)                 Learner#one_batch@ 10 called after_step\n     (07:18:29.709617)                 Learner#one_batch@ 10 called zero_grad!!!!!!!\n     (07:18:29.710074)                 10 WILL CALL after_batch\n     (07:18:30.008983)                 10 called after_batch\n    <<<< ======================================================================= OOOOOOOOOOOOOOOO\n    <<<< =======================================================================\n    <<<< =======================================================================\n    <<<<                                           Learner#ALL_BATCHES CALL EXIT\n    <<<< ====================================================================***\n    <<<< ========================================*******************************\n    <<<< ===========================********************************************\n     (07:18:30.012149)  DataLoader#DataLoader#DataLoader#yielding                    4!!!!\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n     (07:18:30.027987)  DataLoader#DataLoader#DataLoader#__iter__ FOR FOR FOR FOR ---------------------------------------------\n     (07:18:30.028515)  DataLoader#DataLoader#DataLoader#iterator to device from cpu y cpu to xla:1\n     (07:18:31.662151)  DataLoader#DataLoader#DataLoader#iterator to done!!!!\n     (07:18:31.663082)  DataLoader#DataLoader#DataLoader#yielding                    3!!!! yield self.after_batch(xla:1 y xla:1) len of b is 2\n    >>>> =======================================================================\n    >>>> =======================================================================\n    >>>>                                           Learner#ALL_BATCHES CALL ENTER [11]\n    >>>> =======================================================================\n    >>>> ======================================================================= OOOOOOOOOOOOOOOO call self.one_batch\n     (07:18:41.035114)                   Learner#one_batch@BATCH 11\n     (07:18:41.035518)                   Learner#one_batch@SPLIT 11\n     (07:18:41.044067)                 Learner#one_batch@ 11 called begin_batch\n     (07:18:41.329021)                 Learner#one_batch@ 11 called after_pred\n     (07:18:41.329682)                 Learner#one_batch@ 11 did not return becasue yb.length == 0\n     (07:18:41.339736)                 Learner#one_batch@ 11 called after_loss\n     (07:18:41.340241)                 Learner#one_batch@ 11 did not return because we are training\n     (07:18:41.852346)                 Learner#one_batch@ 11 called after_backward\n     (07:18:41.908890)                 Learner#one_batch@ 11 called after_step\n     (07:18:41.917224)                 Learner#one_batch@ 11 called zero_grad!!!!!!!\n     (07:18:41.917640)                 11 WILL CALL after_batch\n     (07:18:42.218283)                 11 called after_batch\n    <<<< ======================================================================= OOOOOOOOOOOOOOOO\n    <<<< =======================================================================\n    <<<< =======================================================================\n    <<<<                                           Learner#ALL_BATCHES CALL EXIT\n    <<<< ====================================================================***\n    <<<< ========================================*******************************\n    <<<< ===========================********************************************\n     (07:18:42.221410)  DataLoader#DataLoader#DataLoader#yielding                    4!!!!\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n     (07:18:42.237679)  DataLoader#DataLoader#DataLoader#__iter__ FOR FOR FOR FOR ---------------------------------------------\n     (07:18:42.238223)  DataLoader#DataLoader#DataLoader#iterator to device from cpu y cpu to xla:1\n     (07:18:43.871999)  DataLoader#DataLoader#DataLoader#iterator to done!!!!\n     (07:18:43.872796)  DataLoader#DataLoader#DataLoader#yielding                    3!!!! yield self.after_batch(xla:1 y xla:1) len of b is 2\n    >>>> =======================================================================\n    >>>> =======================================================================\n    >>>>                                           Learner#ALL_BATCHES CALL ENTER [12]\n    >>>> =======================================================================\n    >>>> ======================================================================= OOOOOOOOOOOOOOOO call self.one_batch\n     (07:18:53.458787)                   Learner#one_batch@BATCH 12\n     (07:18:53.459203)                   Learner#one_batch@SPLIT 12\n     (07:18:53.467751)                 Learner#one_batch@ 12 called begin_batch\n     (07:18:53.759692)                 Learner#one_batch@ 12 called after_pred\n     (07:18:53.760358)                 Learner#one_batch@ 12 did not return becasue yb.length == 0\n     (07:18:53.770142)                 Learner#one_batch@ 12 called after_loss\n     (07:18:53.770550)                 Learner#one_batch@ 12 did not return because we are training\n     (07:18:54.281080)                 Learner#one_batch@ 12 called after_backward\n     (07:18:54.336410)                 Learner#one_batch@ 12 called after_step\n     (07:18:54.344573)                 Learner#one_batch@ 12 called zero_grad!!!!!!!\n     (07:18:54.344983)                 12 WILL CALL after_batch\n     (07:18:54.644160)                 12 called after_batch\n    <<<< ======================================================================= OOOOOOOOOOOOOOOO\n    <<<< =======================================================================\n    <<<< =======================================================================\n    <<<<                                           Learner#ALL_BATCHES CALL EXIT\n    <<<< ====================================================================***\n    <<<< ========================================*******************************\n    <<<< ===========================********************************************\n     (07:18:54.647248)  DataLoader#DataLoader#DataLoader#yielding                    4!!!!\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n     (07:18:54.667883)  DataLoader#DataLoader#DataLoader#__iter__ FOR FOR FOR FOR ---------------------------------------------\n     (07:18:54.668547)  DataLoader#DataLoader#DataLoader#iterator to device from cpu y cpu to xla:1\n     (07:18:56.300111)  DataLoader#DataLoader#DataLoader#iterator to done!!!!\n     (07:18:56.301397)  DataLoader#DataLoader#DataLoader#yielding                    3!!!! yield self.after_batch(xla:1 y xla:1) len of b is 2\n    >>>> =======================================================================\n    >>>> =======================================================================\n    >>>>                                           Learner#ALL_BATCHES CALL ENTER [13]\n    >>>> =======================================================================\n    >>>> ======================================================================= OOOOOOOOOOOOOOOO call self.one_batch\n     (07:19:05.417989)                   Learner#one_batch@BATCH 13\n     (07:19:05.418402)                   Learner#one_batch@SPLIT 13\n     (07:19:05.426375)                 Learner#one_batch@ 13 called begin_batch\n     (07:19:05.718329)                 Learner#one_batch@ 13 called after_pred\n     (07:19:05.718960)                 Learner#one_batch@ 13 did not return becasue yb.length == 0\n     (07:19:05.728667)                 Learner#one_batch@ 13 called after_loss\n     (07:19:05.729084)                 Learner#one_batch@ 13 did not return because we are training\n     (07:19:06.230183)                 Learner#one_batch@ 13 called after_backward\n     (07:19:06.286636)                 Learner#one_batch@ 13 called after_step\n     (07:19:06.294545)                 Learner#one_batch@ 13 called zero_grad!!!!!!!\n     (07:19:06.294932)                 13 WILL CALL after_batch\n     (07:19:06.594544)                 13 called after_batch\n    <<<< ======================================================================= OOOOOOOOOOOOOOOO\n    <<<< =======================================================================\n    <<<< =======================================================================\n    <<<<                                           Learner#ALL_BATCHES CALL EXIT\n    <<<< ====================================================================***\n    <<<< ========================================*******************************\n    <<<< ===========================********************************************\n     (07:19:06.597763)  DataLoader#DataLoader#DataLoader#yielding                    4!!!!\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n     (07:19:06.613474)  DataLoader#DataLoader#DataLoader#__iter__ FOR FOR FOR FOR ---------------------------------------------\n     (07:19:06.613864)  DataLoader#DataLoader#DataLoader#iterator to device from cpu y cpu to xla:1\n     (07:19:08.192406)  DataLoader#DataLoader#DataLoader#iterator to done!!!!\n     (07:19:08.193634)  DataLoader#DataLoader#DataLoader#yielding                    3!!!! yield self.after_batch(xla:1 y xla:1) len of b is 2\n    >>>> =======================================================================\n    >>>> =======================================================================\n    >>>>                                           Learner#ALL_BATCHES CALL ENTER [14]\n    >>>> =======================================================================\n    >>>> ======================================================================= OOOOOOOOOOOOOOOO call self.one_batch\n     (07:19:17.507480)                   Learner#one_batch@BATCH 14\n     (07:19:17.507878)                   Learner#one_batch@SPLIT 14\n     (07:19:17.516244)                 Learner#one_batch@ 14 called begin_batch\n     (07:19:17.807357)                 Learner#one_batch@ 14 called after_pred\n     (07:19:17.807992)                 Learner#one_batch@ 14 did not return becasue yb.length == 0\n     (07:19:17.817977)                 Learner#one_batch@ 14 called after_loss\n     (07:19:17.818410)                 Learner#one_batch@ 14 did not return because we are training\n     (07:19:18.335078)                 Learner#one_batch@ 14 called after_backward\n     (07:19:18.393615)                 Learner#one_batch@ 14 called after_step\n     (07:19:18.401612)                 Learner#one_batch@ 14 called zero_grad!!!!!!!\n     (07:19:18.402011)                 14 WILL CALL after_batch\n     (07:19:18.702800)                 14 called after_batch\n    <<<< ======================================================================= OOOOOOOOOOOOOOOO\n    <<<< =======================================================================\n    <<<< =======================================================================\n    <<<<                                           Learner#ALL_BATCHES CALL EXIT\n    <<<< ====================================================================***\n    <<<< ========================================*******************************\n    <<<< ===========================********************************************\n     (07:19:18.705930)  DataLoader#DataLoader#DataLoader#yielding                    4!!!!\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n     (07:19:18.725490)  DataLoader#DataLoader#DataLoader#__iter__ FOR FOR FOR FOR ---------------------------------------------\n     (07:19:18.726006)  DataLoader#DataLoader#DataLoader#iterator to device from cpu y cpu to xla:1\n     (07:19:20.354525)  DataLoader#DataLoader#DataLoader#iterator to done!!!!\n     (07:19:20.355775)  DataLoader#DataLoader#DataLoader#yielding                    3!!!! yield self.after_batch(xla:1 y xla:1) len of b is 2\n    >>>> =======================================================================\n    >>>> =======================================================================\n    >>>>                                           Learner#ALL_BATCHES CALL ENTER [15]\n    >>>> =======================================================================\n    >>>> ======================================================================= OOOOOOOOOOOOOOOO call self.one_batch\n     (07:19:29.840756)                   Learner#one_batch@BATCH 15\n     (07:19:29.841477)                   Learner#one_batch@SPLIT 15\n     (07:19:29.849961)                 Learner#one_batch@ 15 called begin_batch\n     (07:19:30.138806)                 Learner#one_batch@ 15 called after_pred\n     (07:19:30.139467)                 Learner#one_batch@ 15 did not return becasue yb.length == 0\n     (07:19:30.149060)                 Learner#one_batch@ 15 called after_loss\n     (07:19:30.149466)                 Learner#one_batch@ 15 did not return because we are training\n     (07:19:30.665098)                 Learner#one_batch@ 15 called after_backward\n     (07:19:30.721612)                 Learner#one_batch@ 15 called after_step\n     (07:19:30.729836)                 Learner#one_batch@ 15 called zero_grad!!!!!!!\n     (07:19:30.730274)                 15 WILL CALL after_batch\n     (07:19:31.030333)                 15 called after_batch\n    <<<< ======================================================================= OOOOOOOOOOOOOOOO\n    <<<< =======================================================================\n    <<<< =======================================================================\n    <<<<                                           Learner#ALL_BATCHES CALL EXIT\n    <<<< ====================================================================***\n    <<<< ========================================*******************************\n    <<<< ===========================********************************************\n     (07:19:31.033464)  DataLoader#DataLoader#DataLoader#yielding                    4!!!!\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n     (07:19:31.048404)  DataLoader#DataLoader#DataLoader#__iter__ FOR FOR FOR FOR ---------------------------------------------\n     (07:19:31.051620)  DataLoader#DataLoader#DataLoader#iterator to device from cpu y cpu to xla:1\n     (07:19:32.638757)  DataLoader#DataLoader#DataLoader#iterator to done!!!!\n     (07:19:32.639667)  DataLoader#DataLoader#DataLoader#yielding                    3!!!! yield self.after_batch(xla:1 y xla:1) len of b is 2\n    >>>> =======================================================================\n    >>>> =======================================================================\n    >>>>                                           Learner#ALL_BATCHES CALL ENTER [16]\n    >>>> =======================================================================\n    >>>> ======================================================================= OOOOOOOOOOOOOOOO call self.one_batch\n     (07:19:42.138351)                   Learner#one_batch@BATCH 16\n     (07:19:42.138759)                   Learner#one_batch@SPLIT 16\n     (07:19:42.147651)                 Learner#one_batch@ 16 called begin_batch\n     (07:19:42.452301)                 Learner#one_batch@ 16 called after_pred\n     (07:19:42.452916)                 Learner#one_batch@ 16 did not return becasue yb.length == 0\n     (07:19:42.462576)                 Learner#one_batch@ 16 called after_loss\n     (07:19:42.462990)                 Learner#one_batch@ 16 did not return because we are training\n     (07:19:42.972250)                 Learner#one_batch@ 16 called after_backward\n     (07:19:43.040582)                 Learner#one_batch@ 16 called after_step\n     (07:19:43.048877)                 Learner#one_batch@ 16 called zero_grad!!!!!!!\n     (07:19:43.049373)                 16 WILL CALL after_batch\n     (07:19:43.349970)                 16 called after_batch\n    <<<< ======================================================================= OOOOOOOOOOOOOOOO\n    <<<< =======================================================================\n    <<<< =======================================================================\n    <<<<                                           Learner#ALL_BATCHES CALL EXIT\n    <<<< ====================================================================***\n    <<<< ========================================*******************************\n    <<<< ===========================********************************************\n     (07:19:43.353072)  DataLoader#DataLoader#DataLoader#yielding                    4!!!!\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n    ======================================================================================     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n     (07:19:43.369419)  DataLoader#DataLoader#DataLoader#__iter__ FOR FOR FOR FOR ---------------------------------------------\n     (07:19:43.369791)  DataLoader#DataLoader#DataLoader#iterator to device from cpu y cpu to xla:1\n\n\n\n```\nprint(\"done\")\n```\n\n\n```\n\n```\n", "meta": {"hexsha": "4985338570ddddbc5311c55c0f1a2192b5aec5d8", "size": 174205, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "archive_nbs/Printing+Resnet+batch_tfms+heat.ipynb", "max_stars_repo_name": "rlandingin/fastai_xla_extensions", "max_stars_repo_head_hexsha": "ba02108094182f3ccb1f1d92408e64bf10b3ec1a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2020-07-05T03:05:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-25T07:01:46.000Z", "max_issues_repo_path": "archive_nbs/Printing+Resnet+batch_tfms+heat.ipynb", "max_issues_repo_name": "farizrahman4u/fastai_xla_extensions", "max_issues_repo_head_hexsha": "c0d66fe7f8dcfb4eaf2358f5f95d613765d55492", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2020-07-10T08:48:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-25T13:32:09.000Z", "max_forks_repo_path": "archive_nbs/Printing+Resnet+batch_tfms+heat.ipynb", "max_forks_repo_name": "farizrahman4u/fastai_xla_extensions", "max_forks_repo_head_hexsha": "c0d66fe7f8dcfb4eaf2358f5f95d613765d55492", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-07-07T05:40:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-02T23:29:08.000Z", "avg_line_length": 68.6116581331, "max_line_length": 284, "alphanum_fraction": 0.4460147527, "converted": true, "num_tokens": 34593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.03514484627446984, "lm_q1q2_score": 0.010685497927731635}}
{"text": "# Rich Output\n\nIn Python, objects can declare their textual representation using the `__repr__` method.  IPython expands on this idea and allows objects to declare other, rich representations including:\n\n* HTML\n* JSON\n* PNG\n* JPEG\n* SVG\n* LaTeX\n\nA single object can declare some or all of these representations; all are handled by IPython's *display system*. This Notebook shows how you can use this display system to incorporate a broad range of content into your Notebooks.\n\n## Basic display imports\n\nThe `display` function is a general purpose tool for displaying different representations of objects. Think of it as `print` for these rich representations.\n\n\n```python\nfrom IPython.display import display\n```\n\nA few points:\n\n* Calling `display` on an object will send **all** possible representations to the Notebook.\n* These representations are stored in the Notebook document.\n* In general the Notebook will use the richest available representation.\n\nIf you want to display a particular representation, there are specific functions for that:\n\n\n```python\nfrom IPython.display import (\n    display_pretty, display_html, display_jpeg,\n    display_png, display_json, display_latex, display_svg\n)\n```\n\n## Images\n\nTo work with images (JPEG, PNG) use the `Image` class.\n\n\n```python\nfrom IPython.display import Image\n```\n\n\n```python\ni = Image(filename='../images/ipython_logo.png')\n```\n\nReturning an `Image` object from an expression will automatically display it:\n\n\n```python\ni\n```\n\nOr you can pass an object with a rich representation to `display`:\n\n\n```python\ndisplay(i)\n```\n\nAn image can also be displayed from raw data or a URL.\n\n\n```python\nImage(url='http://python.org/images/python-logo.gif')\n```\n\n\n\n\n\n\n\n\nSVG images are also supported out of the box.\n\n\n```python\nfrom IPython.display import SVG\nSVG(filename='../images/python_logo.svg')\n```\n\n\n\n\n    \n\n    \n\n\n\n### Embedded vs non-embedded Images\n\nBy default, image data is embedded in the notebook document so that the images can be viewed offline. However it is also possible to tell the `Image` class to only store a *link* to the image. Let's see how this works using a webcam at Berkeley.\n\n\n```python\nfrom IPython.display import Image\nimg_url = 'http://www.lawrencehallofscience.org/static/scienceview/scienceview.berkeley.edu/html/view/view_assets/images/newview.jpg'\n\n# by default Image data are embedded\nEmbed      = Image(img_url)\n\n# if kwarg `url` is given, the embedding is assumed to be false\nSoftLinked = Image(url=img_url)\n\n# In each case, embed can be specified explicitly with the `embed` kwarg\n# ForceEmbed = Image(url=img_url, embed=True)\n```\n\nHere is the embedded version. Note that this image was pulled from the webcam when this code cell was originally run and stored in the Notebook. Unless we rerun this cell, this is not todays image.\n\n\n```python\nEmbed\n```\n\n\n\n\n    \n\n    \n\n\n\nHere is today's image from same webcam at Berkeley, (refreshed every minutes, if you reload the notebook), visible only with an active internet connection, that should be different from the previous one. Notebooks saved with this kind of image will be smaller and always reflect the current version of the source, but the image won't display offline.\n\n\n```python\nSoftLinked\n```\n\n\n\n\n\n\n\n\nOf course, if you re-run this Notebook, the two images will be the same again.\n\n## HTML\n\nPython objects can declare HTML representations that will be displayed in the Notebook. If you have some HTML you want to display, simply use the `HTML` class.\n\n\n```python\nfrom IPython.display import HTML\n```\n\n\n```python\ns = \"\"\"<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\"\"\"\n```\n\n\n```python\nh = HTML(s)\n```\n\n\n```python\ndisplay(h)\n```\n\n\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n\n\nYou can also use the `%%html` cell magic to accomplish the same thing.\n\n\n```python\n%%html\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n```\n\n\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n\n\nThe display machinery can also be used by libraries. [Tabipy](https://pypi.python.org/pypi/Tabipy) is a library for constructing tables:\n\n\n```python\n!pip install Tabipy\n```\n\n    Collecting Tabipy\n      Using cached Tabipy-0.1.tar.gz\n    Installing collected packages: Tabipy\n      Running setup.py install for Tabipy\n    Successfully installed Tabipy-0.1.dev0\n\n\n\n```python\nfrom tabipy import Table, TableHeaderRow, TableCell\n\nt = Table(TableHeaderRow('divisions', 'result'))\nnum = 55\nfor x in range(7):\n    if num < 1:\n        resultcell = TableCell(num, bg_colour='DarkBlue', text_colour='white')\n    else:\n        resultcell = TableCell(num)\n    t.append_row((x, resultcell))\n    num /= 3\nt\n```\n\n\n\n\n<table>\n<tr><th >divisions</th><th >result</th></tr>\n<tr><td >0</td><td >55</td></tr>\n<tr><td >1</td><td >18.333333333333332</td></tr>\n<tr><td >2</td><td >6.111111111111111</td></tr>\n<tr><td >3</td><td >2.0370370370370368</td></tr>\n<tr><td >4</td><td style=\"background-color:DarkBlue; color:white\">0.6790123456790123</td></tr>\n<tr><td >5</td><td style=\"background-color:DarkBlue; color:white\">0.22633744855967075</td></tr>\n<tr><td >6</td><td style=\"background-color:DarkBlue; color:white\">0.07544581618655692</td></tr>\n</table>\n\n\n\n## JavaScript\n\nThe Notebook also enables objects to declare a JavaScript representation. At first, this may seem odd as  output is inherently visual and JavaScript is a programming language. However, this opens the door for rich output that leverages the full power of JavaScript and associated libraries such as [d3.js](http://d3js.org) for output.\n\n\n```python\nfrom IPython.display import Javascript\n```\n\nPass a string of JavaScript source code to the `JavaScript` object and then display it.\n\n\n```python\njs = Javascript('alert(\"hi\")');\n```\n\n\n```python\ndisplay(js)\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\nThe same thing can be accomplished using the `%%javascript` cell magic:\n\n\n```javascript\n%%javascript\n\nalert(\"hi\");\n```\n\nHere is a more complicated example that loads `d3.js` from a CDN, uses the `%%html` magic to load CSS styles onto the page and then runs ones of the `d3.js` examples.\n\n\n```python\nJavascript(\n    \"\"\"$.getScript('//cdnjs.cloudflare.com/ajax/libs/d3/3.2.2/d3.v3.min.js')\"\"\"\n)\n```\n\n\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n```python\n%%html\n<style type=\"text/css\">\n\ncircle {\n  fill: rgb(31, 119, 180);\n  fill-opacity: .25;\n  stroke: rgb(31, 119, 180);\n  stroke-width: 1px;\n}\n\n.leaf circle {\n  fill: #ff7f0e;\n  fill-opacity: 1;\n}\n\ntext {\n  font: 10px sans-serif;\n}\n\n</style>\n```\n\n\n<style type=\"text/css\">\n\ncircle {\n  fill: rgb(31, 119, 180);\n  fill-opacity: .25;\n  stroke: rgb(31, 119, 180);\n  stroke-width: 1px;\n}\n\n.leaf circle {\n  fill: #ff7f0e;\n  fill-opacity: 1;\n}\n\ntext {\n  font: 10px sans-serif;\n}\n\n</style>\n\n\n\n```javascript\n%%javascript\n\n// element is the jQuery element we will append to\nvar e = element.get(0);\n    \nvar diameter = 600,\n    format = d3.format(\",d\");\n\nvar pack = d3.layout.pack()\n    .size([diameter - 4, diameter - 4])\n    .value(function(d) { return d.size; });\n\nvar svg = d3.select(e).append(\"svg\")\n    .attr(\"width\", diameter)\n    .attr(\"height\", diameter)\n  .append(\"g\")\n    .attr(\"transform\", \"translate(2,2)\");\n\nd3.json(\"data/flare.json\", function(error, root) {\n  var node = svg.datum(root).selectAll(\".node\")\n      .data(pack.nodes)\n    .enter().append(\"g\")\n      .attr(\"class\", function(d) { return d.children ? \"node\" : \"leaf node\"; })\n      .attr(\"transform\", function(d) { return \"translate(\" + d.x + \",\" + d.y + \")\"; });\n\n  node.append(\"title\")\n      .text(function(d) { return d.name + (d.children ? \"\" : \": \" + format(d.size)); });\n\n  node.append(\"circle\")\n      .attr(\"r\", function(d) { return d.r; });\n\n  node.filter(function(d) { return !d.children; }).append(\"text\")\n      .attr(\"dy\", \".3em\")\n      .style(\"text-anchor\", \"middle\")\n      .text(function(d) { return d.name.substring(0, d.r / 3); });\n});\n\nd3.select(self.frameElement).style(\"height\", diameter + \"px\");\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n## LaTeX\n\nThe IPython display system also has builtin support for the display of mathematical expressions typeset in LaTeX, which is rendered in the browser using [MathJax](http://mathjax.org).\n\nYou can pass raw LaTeX test as a string to the `Math` object:\n\n\n```python\nfrom IPython.display import Math\nMath(r'F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx')\n```\n\n\n\n\n$$F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx$$\n\n\n\nWith the `Latex` class, you have to include the delimiters yourself.  This allows you to use other LaTeX modes such as `eqnarray`:\n\n\n```python\nfrom IPython.display import Latex\nLatex(r\"\"\"\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\"\"\")\n```\n\n\n\n\n\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\n\n\n\nOr you can enter LaTeX directly with the `%%latex` cell magic:\n\n\n```latex\n%%latex\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n```\n\n\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n\n\n## Audio\n\nIPython makes it easy to work with sounds interactively. The `Audio` display class allows you to create an audio control that is embedded in the Notebook. The interface is analogous to the interface of the `Image` display class. All audio formats supported by the browser can be used. Note that no single format is presently supported in all browsers.\n\n\n```python\nfrom IPython.display import Audio\nAudio(url=\"http://www.nch.com.au/acm/8k16bitpcm.wav\")\n```\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"http://www.nch.com.au/acm/8k16bitpcm.wav\" type=\"audio/x-wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\nA NumPy array can be auralized automatically. The `Audio` class normalizes and encodes the data and embeds the resulting audio in the Notebook.\n\nFor instance, when two sine waves with almost the same frequency are superimposed a phenomena known as [beats](https://en.wikipedia.org/wiki/Beat_%28acoustics%29) occur. This can be auralised as follows:\n\n\n```python\nimport numpy as np\nmax_time = 3\nf1 = 220.0\nf2 = 224.0\nrate = 8000.0\nL = 3\ntimes = np.linspace(0,L,rate*L)\nsignal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times)\n\nAudio(data=signal, rate=rate)\n```\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"data:audio/wav;base64,UklGRqS7AABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YYC7AAAAADUWvSvyPzdS/WHKbjt4Bn7+fxV+WXj3bjhifVJDQBYslBZiAC/qpdRswCGuU557kf2HJIIcgPWBoIfykKKdTa15v5rTEuk7/2kV8CopP3ZRSmEqbrJ3mH2vf+Z9TXgNb3Bi11K9QK0sQxcmAQPrhNVPwQOvLZ9IkreIxYKggFiC34cLkZOdFq0bvxbTbeh4/o0UASosPnNQSGAwbcd2w3z2fk9923fGblZi7FL/QBwt3hfoAefrg9ZlwiawVqBuk9OJzoOOgSSDg4iAkdadJa31vrvS3ue5/aIT8Sj/PDBP+F7da3t1h3vUfU98BncibuhhuVIJQWQtYRilAtjso9eqw4mxzKHtlE+LPYXkgleEiolTkm6ee60Hv4jSZuf//KsSwyeiO65NXF0zas9z5nlJfOh6zXUhbSdhPlLaQIItzBhbA9Xt39gexSmzjqPCliuNEYeihPKF9YqDk1mfGq5Uv3/SCOdN/KkReCYYOvBLd1szaMVx4HdYehp5MXTDaxNgfFFwQHUtHRkJBNvuN9q9xgW1l6XsmGOPR4nGhvKHwowPlZegAa/bv6LSxOak+58QFCVkOPhJSVnhZV9veXUCeOh2MnIIaqpecVDLPzwtUxmsBOjvp9uFyBm356dmm/aR3otOiVeK8Y73limiMLCewPHSneYG+48PmSOINslH11Y+Y6BssnJJdVF002/yZ+5cHU/rPtYsbBlEBfvwLd11ymO5e6ownuGU1I44jB+NgZE6mQ+kqLGcwW7Tk+Z1+noOCCKGNGVFI1ROYIppj28vcllxFG2CZeBagU3PPUMsZxnOBRHyyN6IzOC7T61GoSGYJZKBj0aQbpTXm0WmZ7PWwhjUp+by+WMNZCBhMtBCMFEUXSFmEWy4bgJu+Gm6YoFYnkt3PIIrQxlJBinzdOC9zo2+YLCkpLKbz5Unk8yTuJfLns2obrVMxPDU2+Z/+UwMsB4dMAxAAU6TWWdiPGjlak9qgWaaX9FVdEnjOpIq/xi0Bj/0L+IQ0WfBq7NHqJKfzpkml6yXXJsVoqSru7f9xffVL+ce+TYL7hy8LR09m0rOVWFeFGS6ZkJmsmImXNNSBEcVOXQpmhgMB1P19+N/02rELbctrL2jH557m+SbVp+zpciuTrroxy3XpefP+CQKIRtAKwY6/0bKURNanF87YuBhjV5gWIlPUEQMNycoFBhRB2P2yeUG1pTH4bpPsC+ovaIioHGgpKOhqTiyJL0OypHYPOiU+BgJSxmuKMo2M0OJTX9V2FpsXStdF1pKVPVLWUHKNKsmbBeCB2v3o+ej2OHKxb6stOOspacYpU6lQ6jdrfG1PMBtzCTa9ehu+BMIbhcHJm0zOT8RSatQzVVRWCdYUVXoTxlIID5PMgIloRadB2z4gulT203O08I+udax0qxXqneqLq1ksvC5k8MDz+Tb0ele+BcHjRVPI/MvFztmRJtLf1DvUtlSQVA9S/dDqTqeLysjtBWiB2P5ZOsS3tXRCccBvgK3P7Lcr+mvYrIytzK+KcfP0dHdz+pl+CYGqxOJIF4szzaMP1RG80pJTUVN6kpNRpQ/9ja3LCghpRSPB076Ru3e4HTVYcvxwmO86beitZ6127dEvLXC+srQ1Orf8OuE+EIFyRG5HbQoZzKIOtpALkVkR29HUUUbQfI6CDOcKfkecxNkByv7Ju+z4yjZ2M8JyPXByb2ju5K7lL2VwXXHA88E2C7iM+27+GsE6w/gGvck4i1eNTI7ND9HQV1BeT+sOxU25C5QJqAcHxIgB/r7AvGO5u3catREzbHH28PbwcHBiMMhx27MQ9No25zkmO4L+aQDEg4DGCshRSkTMGI1DDn2OhQ7aTkENgExiyrVIh4aqhDEBrr82PJt6b/gEdmd0pTNGcpFyCPIs8nlzJ3RtNf63jLnHfB0+e0CQAwkFVUdlCSsKm8vujJ2NJk0JTMnMLkrASYtH3QXEw9NBmj9pvRL7Jrkyt0Q2JfTfdDazrbOENDa0v3WVdy34u/pxPH3+UgCeApGEncZ1B8uJV0pQyzNLfEtsSwaKkImSiFbG6UUXQ2+BQP+aPYo73rokeKY3bXZA9eV1XLVmNb92IrcIeGd5tDsifOT+rYBuwhsD5UVCRueHzMjryUBJyInFCbiI6AgaRxiF7IRiAsVBYz+Hvj/8VzsYOcw4+rfpd1w3FLcSN1I30DiFeap6tTvbvVJ+zcBDAeZDLQRNxYAGvUcAh8YIDIgUx+FHdgaYxdEE54OlQlSBAD/xvnO9DzwNOzS6C/mXeRm41DjGeS25RroLevX7vjyb/cY/M0AbAXPCdYNYhFbFKoWQRgXGScZdBgHF+0UOxIGD2oLhgd3A2D/XvuS9xf0CPF67n/sJOtx6mfqBetD7BPuZfAl8zr2jPkA/XgA3AMRB/8JjwyxDlYQdBEEEgYSfBFuEOcO9QyqChoIWwWDAqr/5PxI+un32PUj9NXy9vGK8ZHxB/Ln8ib0uPWO95j5xPsA/jkAYAJiBDIGwwcKCQAKnwrmCtUKcQq/CcgIlQc0BrAEFwN3Ad7/V/7v/K/7n/rI+Sv5zPis+Mf4Gfme+U/6IvsQ/A79FP4Y/xAA9wDFAXQCAQNpA6sDyAPCA5wDWgMBA5cCIQKnAS4BvABUAPz/tv+D/2X/W/9j/3z/ov/Q/wIANABiAIcAngClAJkAeQBFAP7/pP87/8j+Tv7V/WD99/yg/GD8PPw5/Fn8nvwJ/Zn9S/4c/wMA/gACAgcDBQTxBMEFbgbwBj4HVAcuB8oGKQZMBTgE9QKJAQAAZv7G/C/7rflP+CH3L/aD9Sb1HfVr9RL2Dvdc+PL5x/vN/fb/MAJrBJUGmwhsCvgLLw0HDnQOcQ78DRMNvQsACucHggXiAhoAQP1p+q33IvXe8vXwd+9z7vXtA+6f7sjvd/Gj8zz2Mflq/NH/SgO8BgoKGg3RDxkS3hMOFZ4VhxXFFF0TVRG8DqMLIAhOBEkAMvwl+EX0sfCG7eDq1Oh259Pm9ObZ54Dp3+vk7nzyjPb1+pf/TATyCGQNfBEbFSAYdBoAHLYcjhyFG6EZ7RZ8E2cPzArMBY4APPv99fvwXuxM6OfkTOKR4Mbf9t8h4UHjSeYj6rTu2vNv+Uf/NQUNC58QvxVEGgge7CDXIrYjgSM1ItofgBw9GDITgw1bB+kAYPrx88/tLOg04xHf5NvK2dXYD9l72g/du+Bk5ejqHvHY9+L+BAYKDboT4BlKH8wjQieMKZgqWSrPKAMmCCL6HP8WQhD4CFgBnvkD8sbqHuRC3mHZotUn0wTSRtLt0/DWOduq4BvnW+409mn+ugboDrIW2h0oJGgpby0cMFYxEjFPLxcsgSevIcoaCBOjCtsB9fg18ODnOOB52dvTi8+tzFrLoMt+zenQydX821LjlOuE9N39VQemEIUZrCHaKNYubzN+Nuo3pTetNRAy5ixWJpEe0RVYDHECZ/iH7iDlfNze1IXOpMlixt3EIsUyxwDLcNBc147fyujJ8j791wdDEjEcUSVdLRM0PDmwPFA+DD7lO+k3MjLtKk8imhgXDhgD8/f77Iji7dh10GPJ8cNLwJG+0r4PwTnFMsvP0tbbAuYG8Y78Pgi+E7QeySitMRo50z6rQoFEQ0TyQZw9YTdvLwImYRveD9EDmPeR6xrgjtU/zHjEd75tuny4trgau5q/FcZazivYPuM97837jAgXFQ0hDyzHNec9L0RrSHhKQ0rNRyVDbTzXM6QpIh6pEZgEV/dK6tfdYdJByMm/O7nNtKSy0rJatSi6HMEAypLUgOBw7f76wAhNFjojIi+oOXdCSknqTTBQCFByTX5IUUEhODMt2yB3E24FL/cl6cDbaM9+xFm7QbRwrw2tLa3Sr+m0TbzGxQ7Rzd2i6yL63AhgFzslADJNPcdGIk4lU6VVjVXcUqNNCkZJPKswiCNGFVEGH/ck6NbZpcz4wCu3jK9ZqrunyqeHquCvrLexwaPNJtvU6Tr54AhPGA0nqDS0QNJKs1IXWNJazVoFWI9SkkpLQAg0JyYSFz8HJ/dH5xvYGsqxvUKzIKuNpbSir6J/pRKrPbPDvVTKkNgI6Ef4zAgbGbEoFzfaQ5dO+Va8XLJfw1/qXD1X5k4jREc3tSjbGDYIRveN5o7Wx8esuqKvAacPofud352+oISmBa8CuibHDNZD5kz3owjDGSYqTDm+RhJS8FoRYUJka2SGYapbAVPNR2U6LiueGjQJevf25THVsMXqt0ysMqPknJWZYJlJnDqiCKtwthrEntOF5Er2ZAhJGmsrRjtdSUJVl14RZX5owWjVZdBf31ZFS109jy1XHDkKwveB5QTU08NttUSptZ8PmYWVNJUimDmeSqcSszbBStHR4kP1EgisGoEsBT23SyNY6WG7aGJswWzSaaxjfFqITixA1i8FHkELHvgv5QbTM8I3s4qmjpySlc6RYJFOlIOaz6Psr3y+Ec8p4Tn0rQfuGmcthz7JTbVa5mQLbOtvaHB7bTpn1V2SUdBCADKlH0wMjPj95DjSz8BJsSGkvZlwknOO543RkB2XmqAArfC798yR3y/zNwcPGx0uzT+TT/Vcimf+bhdzs3PMcHhq5mBfVEVFCjQ1IVcNC/ns5JnRp7+jrwqiRpesj3eLy4qujQmUrp1SqpS5/soK3iXysQYQG6Uu1UAUUeJe1GmTceJ1nnbCc2FtrGPtVohH8TWyIl8OmPn75CnRvb5HrkagKZVHjd2IEIjnikyRDpvkp2u3KcmX3B3xHAbzGv4uoUFMUnxgw2vHc0p4KHlZdvJvJGY5WZZJszcaJGQPMvon5efQD74zrdaeaJNDi6eGuIV/iOeOv5i7pXi1e8c62xvwfAW4GikvMUI7U8JhVW2adU96TnuReCpyS2hAW21LTDlrJWMQ2fpw5dLQnr1qrLudBZKiidaExYN5ht2MwZbYo76z9sX22SDv0ARhGigvhELgU7Niim4Jd+17D31legV0H2r+XApNvDqjJloRifvV5enQaL3pq/Sc/pBliGuDOILWhDCLF5U+oj6yncTM2C7uHATvGfsunUI8VE9jYW8UeCN9Z37We4J1nWtzXmpO/ju+J0cSQfxU5izRbb2xq4KcVpCMh2iCE4GYg+OJxJPuoPywcsO/10ftYQNkGaMue0JQVJdj22+7ePJ9WH/gfJ92xWycX41PEj28KCgT//zr5pjRrL3Bq2ScDJAYh86BWIDBgveIyZLsn/qvdsLR1mzsoALBGCMuIEIcVItj92/9eFh+33+EfVt3k214YG9Q9T2aKfsTwv2Y5yzSI74ZrJqcH5AIh5yBBoBRgmyIKJI4nzmvrMED1qHr3AEJGHwtjUGhUyxjtW/beFZ+/H/AfbR3B24EYQ9Rpj5WKr8Uh/5b6ObS0b62rCKdjpBch9OBHYBJgkSI4ZHVnrquFsFZ1ebqFgE9F64sxEDiUntiF29UeOp9r3+Ufap3IG4/YWxRIj/vKnAVTf8w6cbTtL+XrfydWpEUiHKCn4CpgoCI9pHCnn+utMDT1D/qUABfFr4rxz/fUXphHm5rdxd9+H7/fDx33G0pYYRRaD9iKw4WEAAW6sjUy8C7riWfgJIviXmDioFygyCJaJIBn4quicBz1Kvpjv9xFasqlz6aUClgy2wfdt172X0DfGt2PW3AYFZRdz+vK5YW0gAL6+rVE8IgsJyg/5OqiuaE3oKihCOKNpOTn9uulsA61C7pz/51FHkpNz0WT4xeIWt0dD16UXyfejZ1QWwFYOJQTj/TKwgXjgEO7CzXi8PEsWCi1ZWGjLiGmoQ5homLYJR4oHOv3MAq1MnoFv5tEykoqDtUTaNcIGlpcjl4YnrVeJ9z6Gr2XiZQ7D7OK2EXQwIb7YrYMMWks22kAJi+ju6Iu4Y2iFKN5pWwoVKwW8FF1HzoZf1bEr4m7jlXS3Jay2YDcNN1DnimdqVxNGmVXSNPUD6eK6AX8AIx7gHa/8a9tcGmfppSkYWLQYmXinyPyJc6o3mxFMKK1EvovvxBETolCjghSftXJWRCbQxzV3UTdEtvJWfiW9lNej1DK8MXkgNO75Hb98gOuFqpS50/lHqOKYxbjQaSBJoXpeeyCMP71DboIfwiEJ8jADa2RkFVMWEqauhvQHIgcZJsvWTcWUhMaTy7KsoXKARv8DbdE8uTujSsZaCBl8yRcI9+kO2UmZxEp5y0NsSZ1T3okvv/DvAh0TMYREdS8l2+ZmpsyW7NbXxp/GGHV29KHTsHKrMXsQST8e7eU81JvUyvyaMWm3aVFJMAlDGYhZ/CqZe2n8Vk1mToEfvaDS8ggTFLQRFPa1oCY5Ro+Godagxm5V7iVFFIlzklKX4XKgW48rfgss8twKCycqf6nneZEpfcl86bx6KOrNi4Qsdc16nooPq2DGAeEy9QPqFLoFb4Xmpkz2YUZkNieVvvUe5F1jcWKCkXkgXb843iLtI8wyu2Xqspo8mdZpsQnMKfW6anr127H8mC2A7pQfqUC4MciiwtO/xHlFKkWvBfUWK2YSVevFewTkdD3TXZJrMW6AX79G/kxNRzxuq5ia+gp2miDKCZoAmkQKoLsyW+NcvW2ZTp9Pl3Cp0a6SnlNyVES04LVipbg10EXbVZsFMoS15AqjNvJR0WKwYW9lrmcNfNydi97rNarFSnAaVypaGocq63ti7BhM1X2zvqu/lfCa8YMid6NB9AykkxUR1WaFgEWPZUWE9YRzU9QDHYI2UVWQYp90voMNpIzfPBirhTsYSsQaqYqoWt77KqunfECdAE3QPrmPlQCLsWaSTwMPA7FUUbTMtQBVO6Uu1PuEpEQ845oC4UIowUcgY0+D/qAd3f0DbGV72GtvWxxq8GsLKys7ffvv3HxNLe3u3rivlLB8UUkSFMLZs3MUDMRjxLX00pTZ1K0kXuPio2zCslIJITdAY0+Tbs39+P1JzKUsLvu6K3jLW4tSS4urxUw73LstXj4Pjsk/lRBs8Srh6RKSUzITtKQXJFe0dXRwtFqkBaOk0yxCgLHnUSXwYo+ivuyOJV2CLPdceIwYe9jrupu9a9AcIGyLbP0tgS4yXutPlkBdsQwRvCJZEu6zWaO3Q/XEFIQTo/RjuLNTkuiyXHGzgRMwYO+x3wt+Us3MPTvcxOx57Dx8HUwcPDgsfyzOTTI9xr5XPv7fmFBOwOzxjkIeQpkzDBNUY5CjsCOzE5qDWFMPIpJCJaGdoP7gXk+wryq+gQ4HvYI9I6zeHJMcg0yOjJO80S0kXYoN/r5+LwPvq2AwMN2hX5HSIlHyvEL+4yiTSJNPMy1i9LK3olkB7HFlsOkAWr/O7zoOv/40XdpNdH00zQyM7Ezj3QJtNk19TcSeOR6nDyqPr5AiML5hIHGlEgkyWoKXIs3i3kLYcs1CniJdQg0xoOFL0MGQVf/cn1k+705x3iOt1w2djWhdV+1cDWPtni3I7hG+db7R30LPtOAk4J9Q8RFnMb9B9zI9clECcXJ/AlpyNPIAYc7hYzEQELiQQB/pj3gfHr6/7m4eKv34HdY9xc3Gndft+K4nDmEutI8On1yPu1AYUHCg0aEo8WSBoqHSIfJCApIDYfVB2VGhEX5hI2DicJ4QOP/ln5aPTg7+XrkugA5kDkXONZ4zPk4uVV6HbrK+9V89H3ffwxAcwFKQomDqcRkhTTFlsYIBkfGV0Y4Ba5FPsRvQ4aCzAHIAMJ/wv7RPfR88zwSu5c7A/raupu6hrrZOxA7pzwY/N/9tX5Sv3CACMEUwc5CsEM2Q5zEIURChIAEmoRUhDBDscMdgrhBx8FRgJu/6v8E/q697D1A/S+8unxhvGX8Rby/vJF9N31uPfF+fP7MP5oAIwCiwRWBuEHIgkQCqgK6ArQCmUKrQmwCHoHFQaOBPUCVQG9/zj+0vyW+4v6uPkh+cf4rPjL+CP5rPlf+jX7JPwk/Sr+Lf8kAAkB1AGBAgsDcAOvA8kDwAOXA1MD+AKNAhcCnQEkAbIATAD2/7H/gP9j/1v/Zf9//6X/1P8GADgAZQCJAJ8ApQCXAHYAQAD3/5z/Mv++/kT+y/1X/e/8mvxc/Dr8Ovxd/Kb8FP2n/Vz+Lv8YABMBGAIdAxkEAwXRBXsG+AZCB1MHKAe/BhkGNwUfBNgCaQHf/0T+pPwO+475NPgL9x72efUi9SD1dvUj9if3e/gX+vD7+v0kAGACmgTCBsQIkAoVDEUNFA54DmwO7Q37DJsL1gm3B0wFqALe/wP9Lfp19+/0svLQ8FzvZO7x7Qrusu7n76Hx1/N49nP5svwaAJQDBAdOClcNBhBEEv0TIBWjFX0VrRQ3EyMRfg5bC9EH+gPz/9r70ff282nwSe2u6rDoYefO5v/m9ees6RnsLO/O8uf2Vvv7/7EEVAm/Dc8RYRVZGJ0aGBy7HIAcZRtvGaoWKxMKD2QKXgUdAMv6j/WU8AHs/eeo5B7id+DB3wXgReF545Pmfuod70306fnF/7MFhwsRESYWnBpPHh8h9CK8I3AjDSKcHy0c2Re+EgMN0wZeANX5avNR7bvn0+LD3q3bqtnO2CLZp9pT3RXh0eVm66rxbPh6/5wGnA1DFFsatB8hJH4nrymfKkUqoCi6JaYhgxx2FqsPWAizAPn4ZPEx6pnj0N0F2WHVAdP80VzSINQ/16PbK+Gv5/7u4PYa/2sHkw9SF2oeoyTKKbYtRDBfMfswGC/CKxEnJSEsGloS6gkdATj4fu81557f9thy0z/PgsxQy7jLuM1D0UHWjtz6403sSPWm/h8IaRE7Gk8iZilGL8AzrTb1N4s3cDWwMWcsvCXfHQ0ViAubAZH3ue1f5M7bStQOzk7JMcbRxDzFcsdky/bQ/9dK4JnppfMg/rgIHRP8HAkm+i2RNJc55TxdPvE9ojt/N6YxQiqKIcEXMA0rAgb3Fuyy4SzYz8/eyJHDE8CDvu6+VcGnxcXLg9Ol3Obm+PGH/TYJrxSVH5MpWjKlOTg/5kKQRCZEqUEpPcc2sy4qJXMa4A7MApT2luov37rUicvmww2+L7psuNS4ZrsSwLTGHc8M2TbkRfDd/JsJHRYCIuwshTaAPp5ErEiKSiVKf0epQsc7DDO6KCAdlxB+Az32OenY3HvRfMcqv8e4ibSRsvGyqrWousfB0sqE1Yzhje4j/OUJaBdDJBIwdjodQ8NJMk5FUOlPH036R6BASDc4LMYfUBI/BAD2AOit2nDOqMOsusOzJa/3rE2tJ7BwtQO9psYR0uve0uxb+xUKjxhXJgEzKj55R6VOc1O9VW1VhFIYTU5FYzuhL2IiDBQNBdz16+ax2JzLE8BytgWvB6qip+un4KpvsG24nsK1zlXcF+uH+i0Kkhk8KLk1oEGRSz9TbFjsWqxaqlf9Uc1JWD/vMvAkxhXoBdH1++Xj1gDJvrx9spCqNaWYos+i3KWoqwe0vL51y8/ZXemn+SwKcBryKTg41ERiT45XF13QX6JfjFylVhdOJEMgNm0nfhfNBt31L+VG1Z7Gq7nRrmimsaDcnQCeHqEgp9ivBrtUyFvXqOe9+BQKKht3K306xkfpUo9bcmFkZEpkJmELWypSxEYwOdgpMRm7BwD2h+TY03fE3LZwq5CigJxymYCZqpzbouOrf7dVxfvU+eXL9+YJwBvMLIY8ckojVj5feWWjaKFocmUtXwBWMkocPCws2xqwCDn2A+Sc0o3CU7RdqAqfpJhelVOVhZjeniyoKrR8wrPSU+TT9qMJMhzwLVI+10wPWZhiKGmKbKJsbmkFY5dZbE3hPmcufByrCYb2ouOQ0d/AEbKZpdqbIZWkkX6Rs5Qsm7ekDLHMv4bQuOLX9UwJghzjLuE/9U6qW51lfmwXcEtwFm2QZupcblB8QYYwEB6oCuf2Y+O10G+/GLAnowKZ+pFFjgOON5HJl4ehJ65IvXbOLOHY9OIIsBymLzJByVDzXUhod29Gc5dzZnDKafZfNVPoQ4YylR+oC1n3RuML0D2+aK4HoYSWMI9Gi+aKFI64lJ+ef6v0uobMr9/Z82cIvBw4MEVCVFLpX5lqEXIVdoV2W3OxbLhivVUkRmU0CSGmDNz3SuOQz0m9Aq07n2CUxoypiCmITYv8kQOcF6nRuLnKRN7b8t0HqBybMBpDlVOLYY9sSnSBeBB583VBby1lBFgsSB82aSKjDW74beNFz5K856vEnZmSvopvhs+F5IiYj7aZ8abkthLJ79zh8UUHdhzPMLJDi1TXYiduInaIejh7K3h4cVJnCFr/SbM3tCOaDgz5r+Mozxm8FqujnDCRGImahNqD3YaOjbqXEaUttZLHsNvs8KAGJhzVMAxEN1XOY2FvlXcqfPt8AXpUcyVpxFuYSx455iSMD7b5DeQ5z927j6rWmyWQ14csg0uCOYXiixGWeaOxszzGitr/7/EFuhutMCpEmFVwZD1wpHhkfVZ+c3vRdKNqOF33TF46/iV1EGr6h+R3z927U6pgm3iP+oYmgiSB+oOUir6UKqJxshPFgNkb7zoFMxtbMA1EsFW8ZLpwT3k2fkl/gHzvdctrYV4YTnE7+iZTESX7GuXfzxi8X6o+myqPgoaJgWWAIYOmicKTKKFusRjElNhD7nsEkxrdL7VDgFWzZNlwlHmfftJ/JX2tdptsPV/7TlM81yclEub7xuVx0Iy8tKpxmzqPb4ZUgRGAroIZiR+Tc6CssE7Dxtd47bgD3Bk3LyRDCFVXZJtwdHmffvJ/ZH0IdxFtyl+dTwU9lCjoEqv8iOYq0Tm9T6v3m6iPwYaJgSaApILviNaSDKArsLXCGte87PECEBlqLlxCSVSnY/9v8Hg2fqh/O30BdyxtCWD8T4Q9LymcE3P9XucK0h2+MKzPnHKQeIcmgqWAAYMoieiS95/ur1HCkdYR7CoCMBh4LV5BRlOmYgdvCHhlffR+qXyXdu1s9l8YUM49pik9FDr+R+gO0zW/Va35nZiRkYgqg46BxoPDiVWTMqD0ryHCLdZ662MBPxdjLCxAAFJVYbRtvnYtfNd9sHvJdVJskl/vT+I99ynKFAD/QOk01IDAvK5xnxeTDIqWhN+C84TCih+UvqA/sCjC7tX36p4APhYsK8g+eVC2XwlsE3WOelJ8UHqZdFpr3V6BT789IipCFcL/SOp71fzBYrA3oe6U54tnhpiEh4YkjEOVnaHQsGfC19WL6uD/LxXXKTU9s07KXQZqCHOLeGZ6iXgGcwhq1V3NTmU9JSqjFX4AXOvf1qbDRrJHoxuXII6biLeGgIjojcSWzqKosd7C6dU26ib/FhRlKHQ7sUyWW69noXAmdhR4XnYScVpoe1zSTdI8/inrFTQBe+xe2HzFZrSfpZuZtZAxizqJ3YoMkJ+YUKTGso3DJdb76XX+8xLYJok5dkoaWQdl321gc191z3O+blJm0FqRTAU8rikZFuABoe332XvHvbY9qGyco5MnjiCMnI2QktOaJKYqtHfEi9ba6c39yRE0JXY3A0hbVg9ixWo8cEly4HALbPFj1FgKS/86MiksFoICzu6n26HJSrkdq4qf6JZ4kWWPvJBylWCdSKjUtZnFHNfV6TH9mhB6Iz41XUVaU8teV2e9bNVukW37aDlhiFY9ScA5iigiFhgD/+9r3evLCbw9rvOif5ojlQeTOpSvmESgvKrEt/XG2tft6aP8aA+tIeMyhkIcUD5bl2PmaAZr5mmRZSpe7VMrR0c4tyf7FZ8DMvFA31bO976ZsaKmZ54lmQOXEphGnH2jfa34uYvIxNgj6iP8NQ7PH2kwgT+kTG1XiV+8ZN5m4WXPYchaBVHURJU2tya2FRcEZPIl4d/QEsIttZWqmqJ4nVabQpwzoAini7BwvFnK2tl46rP7Aw3kHdItUjz1SFlTMVtAYGFihmG3XRRX0007Qqo0iiVRFX4ElfMW44PTVMX2uMeuFqcbovufxqBzpOOq47Mqv2DMHdvt6lX71AvtGyEr/DgTRQlPk1Z4W5Rd2VxOWRJTVkphP4gyMiTNFNMEwfQS5T/WvMjwvDWz1asHp/Ckm6UEqQyvgrckwp3Oi9yB6wr7qwruGVsogzUCQX9Ks1FoVnpY3VeXVMROlEZHPC8wrSIpFBUF6PUV5xDZRcwXwdq31LA6rC6qvarhrX6zaLtexRHRJt427NL6iAnoF4El6zHHPMFFlkwTURhTllKVTy5KjULvOKEt/CBjE0IFBvcd6fLb7M9mxbG8DravsbOvKLAHsze4j7/UyLrT7d8L7bD6bgjeFZciNy5kONJAQEeAS3JNCU1MSlJFRT5bNd4qIB9+ElkFG/gn6+PerNPaybbBfrtgt3m11rVxuDS998OEzJbW3eEB7qP6XwfUE6EfayrfM7c7t0GyRY1HO0fBRDZAvjmPMeonGx13EVsFJPkx7d7hg9duzuXGIMFJvXu7w7scvnDCm8hs0KPZ+OMY7636XAbKEaAciiY9L3U2/zuwP25BMEH4Ptw6/jSMLcUk7BpQEEUFIfo57+LkbNsf0znM7sZkw7XB68ECxObHeM2I1N/cOuZP8M/6ZgXFD5oZmiKAKhExHTZ9ORs77Tr2OEk1BjBWKXEhlRgJDxcFD/s88evnZN/n16zR48ytySHISMgfypTNidLX2EngpOim8Qj7gATFDZAWnB6uJZArFjAgM5g0dzTAMoIv2yrwJPIdGRaiDdIE7vs48/bqZuPB3DrX+dId0LnO1c5u0HPTzNdU3d3jNOsd81r7qQPNC4UTlhrMIPYl8CmeLOwt1C1aLIspgSVdIEkadxMdDHQEu/wr9f/tb+er4d7cLNmv1njVjNXp1oHZPN384Zrn5+2y9MT75QLgCX0QjBbdG0kgsSP8JRwnCifKJWkj/B+gG3oWshB5Cv4Ddv0S9wTxeuue5pPid99e3VjcaNyL3bbf1eLM5nzrvPBk9kb8MwL/B3sNgBLmFo4aXR1BHy4gHiAXHyEdURq+FoYSzQ24CG8DHv7t+AP0hu+X61To0uUk5FPjY+NP5A/mkejA64DvsvM0+OH8lQEsBoIKdg7sEckU+xZyGCcZFhlEGLkWhBS6EXIOyArbBsgCsv64+vf2jPOR8BvuOuz76mPqduov64bsbe7T8KPzxPYe+pX9CwFpBJQHcwrzDAEPjxCWEQ4S+BFYETUQmw6ZDEEKqAfjBAkCMv9y/N75i/eI9eTzqPLc8YPxnfEm8hbzZPQC9uL38/kj/GD+lwC4ArQEegb/BzkJIAqxCukKygpZCpsJmQheB/UFbQTSAjIBnP8Z/rb8fvt4+qn5F/nD+Kz40fgs+bn5cPpI+zn8Ov0//kL/OAAbAeQBjgIVA3cDswPKA74DkwNMA/AChAINApMBGwGpAEQA7/+s/33/Yv9b/2b/gf+p/9j/CgA8AGkAiwCgAKQAlQByADoA8P+T/yn/tP46/sH9Tv3n/JT8WPw5/Dv8Yvyt/B/9tf1s/kH/LAApAS4CMgMuBBUF4QWHBgAHRgdSByIHtAYIBiIFBgS6AkkBvv8h/oH87fpw+Rn49PYN9m71HvUk9YH1NvZA95v4PPoa/Cf+UwCQAskE7wbtCLMKMgxaDSAOfA5mDt0N4gx5C6wJhgcWBW0Cov/G/PL5Pfe89IbyrfBD71Xu7e0T7sfuB/DM8Qv0tfa2+fn8ZADfA0wHkgqUDTsQbhIbFDEVphVyFZUUERPwEEAOFAuCB6UDnP+D+3z3p/Mi8AvtfeqN6E3ny+YM5xPo2elU7HTvIvND97j7XgAVBbUJGg4gEqcVkRjEGi4cvxxxHEMbOxlnFtkSqw78CfAErf9a+iL1LvCm66/naeTy4V7gvd8W4Gvhs+Pf5trqhu/C9GT6QwAxBgEMgxGMFvMalB5QIQ8jwSNdI+MhXB/ZG3MXSRKDDEwG0/9K+eXy1exL53Tid95324zZydg32dXamd1x4UHm5us28gD5EQA0By8OyxTVGhwgdCS5J9AppSovKm4obiVCIQoc6xUUD7cHDgBV+MbwnukV41/drNgh1d7S9tF00lbUkdcO3K3hROih7473zP8bCD0Q8Bf4HhwlKir6LWowZTHhMN8uayueJpogjRmrETEJXwB798jui+YG33TYC9P2zlnMScvTy/TNoNG71iLdo+QH7Q32cf/oCCoS7xrxIvAptC8ONNk2/TdvNzA1TjHmKx8lKx1IFLcKxAC89uzsoOMj27jTms37yALGyMRaxbbHy8t+0aTYCOFp6oH0Av+ZCfYTxh2+JpQuDDXvORY9Zj7SPVs7EzcXMZQpwyDmFkkMPQEZ9jLr3eBt1yzPXMg0w9+/eL4Ov5/BGcZbzDnUdd3L5+vygP4vCp4VdCBbKgUzLjqaPx5Dm0QFRFxBszwrNvUtTySDGeINyAGR9ZvpRt7p09bKV8OnvfW5X7j1uLW7jMBXx+PP79kw5U7x7f2pCiIX9iLHLUA3FT8JRepIl0oCSixHKkIeOz8yzicdHIMPYwIk9Sno2tuX0LnGjr5XuEi0grIVs/+1LLt2wqfLedaZ4qvvSf0JC4IYSyX+MEA7v0M4SnZOVVDFT8hMckfrP2w2OyuvHikRDwPR9NvmnNl6zdbCBLpKs96u5axxrYCw/LW+vYrHFtMK4APulfxOC70Zcif/MwQ/KEgjT71Tz1VIVSlSiEyORHk6ky45IdESygOZ9LPljdeVyjK/vbWCrrqpjqcQqD6rArExuY7Dys+H3Vvs1Pt5C9MaaSnINohCTEzHU7xYAluHWktXZlEDSWE+0jG2I3kUkQR69LDkrtXpx867vLEEquKkgaL1oj2mQqzWtLm/mMwR27PqB/uMC8QbMCtXOctFKVAfWG1d6V99XylcB1ZETSJC9TQkJiAWZAV19NLj/9N4xa24Ba7TpVigwp0lnoKhwKewsA+8hcms2A7pLvqFC48cxiyrO8pIu1MoXM5hf2QlZMBgaFpOUbZF+TeAKMIXQgaH9BnjgtJCw9G1maryoSGcVZmlmRGdgaPDrJK4k8Za1m/nTPlnCzUdKi7CPYJLAFffX9tlwmh8aAplhV4dVRpJ2TrGKl4ZJwew9IbiNtFKwTyze6dknj+YPZV4le+YiJ8TqUa1xcMf1NflY/gzC7cdXS+bP/RN9llCY5BprWx+bARpWGKtWEtMkz31LPEaEwjv9BbiHdCPv++wrqQtm7eUgJGikR6V2pukpTCyH8H+0UnkdffqChQeXTA3QR1Qm1xOZutsPXAocKts4GX6W0ZPJEAJL3kcBAlC9crhNc8TvuuuMqJNmIqRHo4mjqOReph5olOvpL74z8jigvaNCk4eLDGTQvtR7V4Baepvb3N1c/pvF2kCXwZSiEL/MPMd+Amp9aHhf87WvDGtCqDHlbuOG4sHi4CObJWWn7GsWLwRzlXhjvUdCmYeyjGxQ5BT62BZa4lyQXZkdu9y/GvAYYlUvUTWMl4f7Qoh9pvh+s3Yu8KrNp6dk0yMeohJiLmLspL+nE6qPLpMzPPfmfSdCVweNjKPRNlUlGJVbcd0sXjyeId1i24xZMtWv0aJNLYg4Aup9rXhps0Zu5+quJzQkT6KPYbthVGJT5Czmi2oU7iryqXep/MNCTIecjIvRdZV52PzbqN2vHoce8B3wXBUZstYjUgXNvoh0QxA9+7hgc2ZusepkJtikJSIZYT1g0mHRo65mE+mobYwyWzdufJvCOkdfzKQRYlW5GQycBt4YHzgfJZ5nHImaIVaI0p+NycjvA3k90bijM1WujqpvppSj0+H9IJkgqOFmYwRl7mkKLXex0vc0PHGB4MdXjK0RfBWi2UTcS55nX0+fgp7GnSjafdbf0u7ODwkoQ6T+LvixM1RuvmoQpqhjm6G64E7gWKES4u+lWuj6bO3xkTb8PASBwAdDzKbRQxX22WUcdx5cn4zfxh8OXXLaiBdoEzMOTUlfA9L+UvjKc6IugGpHZpPjvOFS4F6gIeDW4rBlGii57K9xVnaGvBWBmMclTFHRd9W1mW2cSR63n6/f8B8+HWca/1dgk2uOhImTRAK+vXjuM76ulOpTZpcjt6FE4EjgBODzYkclLKhJLLyxIvZT++UBa4b8TC4RGlWfGV6cQd64X7hfwF9VnYVbIxeJk5hO88mERHQ+rbkcc+lu+2p0ZrIji2GRYE1gAWDoInRk0qhobFYxN7Yku7MBOEaJDDwQ6xVzWTgcIV5e36af9p8UnYzbM1eiE7iO2wnxhGY+43lUdCJvM2qqZuQj+KG4IGygGCD1YnfkzChYLHxw1LY5e0DBP8ZMS/xQqhUzWPpb594rH3pfkx863X3a75eqE4wPOcnaxJj/HnmV9GivfOr0py1kPmH44KXgSKEbYpJlGehYrG9w+nXSu04AwsZGS69QWFTe2KXblZ3dXzOfVZ7InVga19ehE5JPD4o/RIt/XbngdLwvlutS540knOJTITmgkuFaIsNle6hqLG+w6XXwexuAgUY3ixWQNhR2mDrbKt12XpMfPp59nNvaq9dHE4tPG8oexP1/YPozNNwwAWvE6AMlE6LHIachNuGxYwtlseiMrL2w4fXTuyoAfEWgyu+Pg5Q7V7naqFz13hiejd4aHIiaa5cb03aO3ko5BO6/p7pNtUfwu6wJqI7loiNT4i5htCIhI6nl/GjArNkxJDX8evmANAVCir4PAhOtVyOaDlxcnYTeBB2eXB7Z1xbfUxQO1woNRR4/8Xqvdb8wxKzgqS9mB2Q5Io6iSmLo5B7mWulF7QKxcLXq+srAKMUdSgGO8ZLNVrjZXZurXNhdYVzKm56ZblZRUuOOhYobhQuAPbrX9gDxnC1JaeRmw2T2Y0djOWNIZOomzancbXpxR3Yf+t5/28TxybqOExJcFfnYlpriXBNcppwfWshY8ZXyEmTOaYnjRTcAC7tGdozyAW4DKq0nlSWK5FgjwCR/JUtnlGpELcAx6LYbuvR/jQSAiWoNp5GaVSfX+lnCm3bbk9tdGhwYIRVBkhgOAsnkBR/AWvu6duHys26M60hou6Z1pQAk3mUM5kIobqr9LhPyFLZeOs1/vQQKCNCNL1DI1ENXCdkM2kNa6hpEGVqXfRSAEb0NkYmeBQVAqzvy93+zMW9lrDXpdmd2Jj7lk2Yw5w4pHCuHLvXyS3an+um/bMPPSG7Ma5Aok01WBVgB2XnZqhlVWESWhhQt0NRNVUlQhScAu7wvt+Uz+rAM7TQqRCiLZ1Mm3mcqaC5p3Kxhr2WyzPb5Osm/XEOQx8XL3M96kkbVLlbimBsYlJhRV1oVvFMLEF1Mzkk7xMUAy/yv+FG0jnEBrgKrpCm0aHwn/mg4qSLq760MsCNzWXcR+y2/DENPB1YLBE6/UXCTxZXwVugXalc41hvUoFJYD5jMfIifBN8A23zy+MR1a7HC7yAslWrwKbjpMqla6mpr1G4HsO6z8LdyexY/PYLKxuBKYo24UEwSzFSrlaHWLFXM1QsTstFVTscL38h6xLQA6b04OXy10bLPcAtt1qw9ashqueqQa4RtCm8R8Yc0krfau0N/MAKExmXJuMymT1oRg1NV1EmU25SOU+gSdJBDTifLOIfOhISBNj1++fl2vvOmsQOvJq1bbGlr02wX7PAuEPArcmz1P3gK+7V+5EJ9habIx8vKjlvQbFHwEuATeZM+EnQRJg9ijTvKRoeaRE+BAL3Gero3czSG8kewRG7Ibdrtfi1wrixvZ3ETc1819niC++z+20I1xSSIEMrlzRKPCBC70WbRxtHdES+PyA5zzANJykceBBWBCH4OOz34LTWvs1YxrrADr1tu+G7Zb7iwjLJI9F22t7kDPCn+1MHuRJ+HVEn5i/9NmA86D99QRNBsz5wOm003Sz8IxAaaA9XBDX5Vu4P5K/afdK3y5HGLsOnwQbCRMRNyADOL9We3QvnLPGx+0cGnRBjGk4jGiuMMXU2sTkpO9Q6uDjoNIQvuSi9IM8XOA5BBDr6b/At57neVdc30Y7Me8kTyF/IWcrvzQPTa9nz4F/pbPLS+0gFhg5DFz4fOCb+K2YwTzOlNGI0iTIsL2gqZSRSHWkV6QwUBDH7g/JN6s7iQNzT1q7S8c+tzunOoNDE0zfY1t1z5NjryvML/FoEdwwjFCQbRSFXJjcqxyz4LcItKyxBKR4l5B++Gd4SewvPAxf8jfRt7evmOuGE3OvYidZt1Z3VFNfF2ZjdbOIa6HTuR/Vc/HwDcQoFEQUXRBycIO0jICYmJ/smoiUqI6gfOhsEFjEQ8AlyA+z8jfaJ8AzrP+ZH4kDfPt1O3HbcsN3w3yLjKufn6zLx4PbF/LECdwjsDeQSPBfSGo8dXx82IBIg9h7uHAwaahYmEmMNSAj+Aq79gfie8yzvS+sW6KblCuRM427jbeQ95s/oC+zV7w/0lvhG/fkBiwbaCsUOLxL/FCIXiRgtGQwZKhiQFk4UeREoDncKhQZxAlz+Zfqq9kjzV/Dt7Rns5+pf6n/qRuup7JzuC/Hj8wr3Z/rf/VQBrwTUB6wKIw0nD6sQpRESEvARRBEXEHMOagwMCm4HpgTMAfb+Ofyq+V33YfXF85Py0PGB8aTxNvIu84P0KPYM+CD6UvyP/sUA5ALcBJ0GHAhPCTAKuQrqCsQKTAqHCYAIQQfWBUsErwIQAXr/+v2b/Gb7ZPqb+Q75v/it+Nb4NvnH+YH6XPtO/E/9Vf5X/0wALQHzAZsCHwN9A7YDygO7A44DRQPnAnoCAwKJAREBoAA8AOn/p/96/2H/W/9o/4T/rP/c/w4AQABsAI4AoQCkAJMAbgA1AOn/i/8f/6r+MP63/UX94PyO/FT8OPw9/Gb8tfwq/cP9ff5U/0EAPgFEAkgDQgQoBfAFkwYIB0kHUAcbB6gG9wUMBewDnQIpAZz//v1f/Mz6Uvn/99/2/fVk9Rz1KPWM9Un2Wve7+GL6RPxV/oMAvwL4BBsHFQnWCk4Mbw0sDn4OXw7MDcgMVwuBCVUH3wQzAmX/ify3+QX3ivRb8orwKu9H7uvtHO7c7ifw9/FA9PL2+vlB/a4AKQSUB9UK0Q1uEJcSOBRCFagVZhV7FOkSvBABDssKMgdQA0X/LPso91jz3O/P7E3qa+g758nmG+cx6Afqkey973bzn/ca/MMAeQUVCnQOcRLrFccY6hpCHMEcYRwgGwcZIhaFEkwOlAmBBDv/6fm19MjvS+ti5y3kx+FH4LvfKeCS4e7jLec36/HvNvXg+sEArwZ6DPQR8RZJG9gefyEoI8MjSCO3IRsfhBsMF9QRAgzDBUj/wPhf8lns3OYW4i3eQ9tx2cfYTtkF2+HdzuGy5mfsw/KV+aoAywfADlIVThuCIMQk8SfuKagqFio6KCAl3SCQG2AVew4WB2r/svcp8AvpkuLw3FTY5NS90vPRj9KO1OXXe9ww4troRvA7+HwAywjmEI0YhB+TJYgqPC6OMGkxxTCjLhErKSYNIOwY+xB3CKL/v/YT7uPlcN7116bSsM4zzEXL8cs0zv/RONe43U7lwu3T9joAsAnrEqIbkSN4Kh8wWTQCNwI4TzftNOkwYiuAJHYcgRPmCe//6PUf7OLiedoo0yjNq8jWxcPEe8X8xzbMCdJM2cfhO+te9eT/eQrOFI8ecSctL4Q1RDpFPWw+sD0RO6M2hTDkKPofChZgC08ALfVP6grgsdaMzt7H28Kuv3G+Mr/swY3G9Mzx1Ejesujf83r/JguMFlEhISuuM7M6+D9SQ6NE4EMMQTk8izU1LXMjkhjkDMMAjvSi6F7dGdMmysvCRL2+uVa4G7kJvAvB/cer0NXaK+ZY8v3+twsmGOgjny74N6c/cEUjSaFK3EnWRqZBcjpuMeAmFxtvDkgBC/Qa597atc/5xfW967cMtHeyPLNYtrS7KcN/zHDXqOPJ8G7+LQybGVAm6DEIPF5EqUq1TmFQnU9tTOZGMz+MNTwqlx0AEN8Bo/O45Y3Yh8wHwl+51LKbrtismq3esIy2fL5wyB7ULOE279D9hwzqGooo+zTaP9NInU8CVN5VH1XJUfRLy0OLOYMtDiCVEYUCV/N85GvWkclUvgy1A65yqX6nOqigq5qx+rmCxOLQut6g7SL9xgwTHJQq1DdtQwNNSlQHWRNbXVrnVspQNUhnPbMweiIrEzoDJfNm43rU1cbiugCxfKmUpG+iH6OjpuCsqbW6wL/NVdwK7Gf86gwWHWwsczq+RutQq1i+XfxfUl/CW2VVbUwbQcgz2CTAFPsDDfN34rvSVMS0tz2tQqUEoK2dUJ7soWWojLEbvbnK/9l26qD79gzzHRIu1jzKSYhUvFwlYpZk+mNVYMBZblCkRL42JSdSFsgEDvOt4S7REMLLtMapWaHHmz2Z0Jl+nSukp62oudTHvNfm6M766AypHoYv+z6PTNhXfGA3ZttoUmidZNddNVT/R5I5XinfF54FJ/MK4dPPCsApsp6mxJ3glyOVopVdmTig/qlnthHFjtVd5/T5www6H8cw4kAMT9ha52PyaclsVGyVaKdhvlcnS0E8gCtlGXwGWPOM4KzOQ77Rr8ejhJpSlGKRzJGOlY6clqZZs3bCeNPc5RP5iAylH9UxiUJAUYZd+2ZTbV1w/m86bCplBVsZTsg+iS3hGmAHnvMz4LfNu7zCrUKhnZcfkf2NT44UkjKZcaODsATAfdFm5C34NwzsH7Ay8UMpU+FftWlXcJJzTXOIb19oCF7SUCRBdi9QHEgI+PP+3/bMc7v+qxGfEZVLjveKL4vyjiaWkqDorb+9n8/94kP30wsPIFgzGUXHVOdhE2z7cmh2PXZ8ckFrwmBPU1FDRDGxHTIJZvTt32fMa7qHqjad4JLXi1OIb4gsjG6T/p2Kq6q74s2k4Vj2XAsPIM4zAUYYVphjFW4+ddp4zXgUdc5tMGONVU5F8DIBHx0K5fT+3wnMo7lcqbGbDZHFiRKGEYbDiQ2Rtpttqce5R8xd4G711QrtHxM0qUYeV/JkuW8ed+h6+HpNdwNwUWWJVxdHeDQ/IAYLdfUw4N3LG7l9qIKamY8XiDeEGIS6hwSPvZmSpxm40soq34b0PgqsHyc0EUfWV/Rl/XCaeJB8v3wled5xIWdBWalI2zVnIewLEvaB4OHL07jqp6uZhI7OhsOChIIUhleNFpj+paK2g8kO3qPzmglLHws0OkdDWKBm4nGxedB9H36aelxznmiyWgNKFDd3IswMvPbx4BTMyLijpyuZz43phbeBWIHShAiMw5axpGW1X8gK3cby6gjMHsEzJkdkWPVmZ3Jjeqh+Fn+qe310xmnaWyNLIzhvI6UNcfd94XXM+7iopwGZeo1rhROBlYD0gxeLxpWuo2S0Zscg3PLxMQgyHkoz1UY6WPNmjXKuehd/pX9UfD11mGq3XAZMBjlKJHUOL/gl4gLNa7n3py6ZhI1ThdmAO4B+g4aKH5X2oqCzmsZT2yjxbwd+HacySEbGV5tmU3KTehx/yn+XfJ51E2tJXatMujkJJTkP9Pjm4rrNFbqPqLGZ7Y2ghQmBS4Bug1eK0ZSMohuz/8Wk2mrwpwaxHNsxgUUKV+5lu3EUerh+hX90fJx1NGuMXQ9NPTqoJfAPvvm+45vO+LpvqYeatY5ShqGBxYDFg4mK3ZRvoteylMUV2rrv2wXOG+YwgUQGVu5kxXAveex91n7oezl1/GqCXTNNjzomJpgQjPqs5KLPE7yVqrGb2Y9oh6GCqIGEhB6LQpWiotSyW8Wo2RvvDQXWGswvS0O+VJxjc2/nd7d8v332enN0amonXRRNrTqCJi8RW/ut5c/QY70ArCudWJHiiAmE9IKqhRSMApYkoxSzV8Ve2Y3uPgTMGY0u4UEyU/phx209dhx7P3ydeUxzfWl9XLJMmDq6JrMRKfzA5h/S576srfSeMZO8iteFqIQ2h22NG5f2o5izh8U42RLucQOxGCwtREBlUQpgwmszdBx5WHred8NxNmiDWw1MTDrMJiQS9fzi55DTnMCZrwqhYZX2jAmIwoYniSaPj5gYpWC07sU52aztpwKIF6wreD5aT89dZ2nLcbl2DHi7ddlvlWY4WiNLyzm4Jn4SvP0R6R/Vf8LDsWuj5peMj56KQIl8iz+RXJqLpmy1isZh2V3t4gFTFg8qfzwSTUpbuWYHb/RzXHU1c5BtnGSeWPVJEzl8JsISfv5M6srWjsQntBKmvZp9kpKNIYwzjreTgpxNqLy2Xsex2SbtJQEUFVcoWjqSSoBYumPqa9FwS3JNcOpqSmK0VoJIIzgYJuwSN/+P647Yx8bDtv+o453FleOQYY9KkYyW/55eqlC4acgq2gjtcADNE4cmDjjbR3JVbWB3aFJt224Hbedno198VMxG/TaLJf0S5//Z7GnaJsmUuSysVaFimY+UAJO+lLyZ0aG9rCm6q8nM2gTtx/+AEqIknjXxRCVS1lyxZHppD2tlaYpkplz3UdJEnzXTJPMSigAo7lncqMuWvJivEKVQnZGY+JaOmEWd+KRor0O8JcuY2xztKP8wEakiCzPXQZxO+FicYE5l62ZpZdZgVlkmT5ZCCjTyI84SIgF571reSs7Hvz6zEKmLoeecR5u1nCShcKhesqC+1syO3FDtmP7fD6AgWTCRPtpK11Q8XNBgcmIYYc1ctlULTBlAPjLmIosSqwHK8GrgCtEiwxq3Ua0Qpo2h6Z8woValN6ydtT7BvM6v3aLtF/6ODokejC0iO+RGeFCUVwRcp11zXHNYyFGoSFw9PDCwISsSJAIa8ofi5NOkxiq7z7HZqn2m26T9pdepS7AjuRrE2dD73hHupv1ADWccpiqON71C3UuqUu9WkFiAV8tTj00ARWA6BS5QIKwRjAJm863k1dZJymi/hbbkr7WrGKoWq6WuqLTuvDTHKtNw4J/uR/33Cz0aqifYM2k+DEeATZZRL1NCUthODkkUQSg3myvGHg8R4QKs9Nvm2tkOztDDb7sqtS+xm694sLyzTLn6wIrKrtUP4kvv+/y0Cg0YnSQFMO05CUIeSPxLik2+TJ9JSUToPLYz/SgTHVMQIwPq9Q3p79zv0V/IicCouue2YLUethe5Mr5GxRjOZNjX4xbww/x6CdoVgSEYLE012TyGQihGpkf3RiNEQz9+OAwwLyY2G3gPUQMf90DrEeDn1RDNzsVZwNe8YrsDvLK+V8PNyd7RStvH5QHxofxKCKYTWh4VKI0wgTe+PB1Ah0H0QGo+ADrbMywsMSMzGX4OaQNJ+HTtPeP02d7ROcs3xvvCnMEjwonEt8iMztfVXt7e5wryk/wnB3QRKhsAJLErBTLLNuI5Mzu4Onc4hDQBLxkoByAIF2YNawNm+aTvb+YQ3sXWxdA9zE3JCch5yJbKTs6A0wLan+Eb6jLznfwRBkYP9hfdH8AmaiyzMHszrzRKNFAy1C70KdcjsRy5FC8MVgN1+s7xpek54sDbbdZm0sfPo87/ztbQFtSk2FreCuV97Hj0vfwKBSANwBSwG7whtiZ6Ku4sAS6uLfkr9Ci4JGkfMhlFEtoKKgN0+/Hz2+xp5szgLNys2GXWZNWw1ULXDNr23d7inOgC79z19fwTBAILixF9F6oc7SAnJEEmLifqJnkl6SJSH9IajRWvD2cJ5wJi/An2DvCe6uLl/eEL3x/dR9yG3NbdK+Bw44jnU+yo8V33RP0uA+8IWw5HE5AXFRu/HXofPSADINMeuBzFGRUWxRH5DNkHjAI+/RX4O/PT7v/q2+d85fLjRuN744zkbeYO6VfsLPBt9Pn4q/1cAuoGMgsTD3ESMxVHF54YMhkAGQ4YZhYXFDYR3A0lCi4GGQIG/hP6XvYF8x7wwO3569bqW+qK6l7rzuzL7kTxI/RQ97H6Kf6dAfUEFAjlClMNTA/FELQRFBLnETAR+A9MDjoM1gk0B2oEjwG6/gD8dvkv9zv1qPN+8sXxgPGs8UfyR/Ok9E72N/hO+oL8v/70ABADAwXABjkIZQk+CsAK6gq9Cj4KdAloCCQHtgUpBI0C7QBZ/9v9f/xP+1H6jfkF+bv4rvjc+EH51fmS+m/7Y/xl/Wv+bP9fAD4BAwKnAigDgwO5A8oDuQOJAz4D3wJwAvkBfwEHAZgANQDj/6P/d/9f/1z/av+H/7D/4f8TAEQAbwCQAKIAowCRAGoALwDi/4L/Fv+g/ib+rf08/dj8iPxR/Df8P/xs/L78Nf3R/Y7+Z/9VAFQBWQJdA1YEOgX/BZ8GEAdMB04HFAebBuYF9gTRA38CCQF6/9z9Pfyr+jT55PfJ9u71W/UZ9S31mfVc9nX32/iI+m/8gv6yAO8CJwVHBz0J+QpqDIINNw6ADlcOuw2tDDMLVgkjB6gE+AEo/0z8fPnO9lj0MPJp8BLvOu7q7Sfu8u5J8CTydvQv9z36if34AHIE2wcYCw0OoRDAElQUUBWpFVkVXxTBEocQwA2CCuIG+wLt/tX61PYK85bvlOwf6kvoKufI5irnUeg36s/sCPDL8/z3fPwnAd0FdQrNDsASLxb8GA8bVRzCHE4c+xrQGNsVMRLrDSoJEgTJ/nj5SfRk7/LqFufx457hMuC63z7gu+Er5Hvnlutd8Kz1XPtAAS0H8gxjElQXnRsZH60hQCPDIzEjiSHXHiwboxZdEYELOwW8/jX42/He62/muuHl3RHbV9nG2GfZN9sq3i7iJOfp7FDzK/pCAWIIUQ/YFcUb5yATJSgoCiqoKvspBCjQJHUgFBvTFOENdAbF/g73jO966BHig9z/16nUn9Ly0azSyNQ72OvctuJy6evw6fguAXsJjxEqGQ8gCCbkKnsurjBqMaYwZS61KrIlfh9KGEsQvQfk/gP2X+085dvdd9dE0mzOD8xEyxLMds5h0rfXUN775X7umfcEAXgKqxNUHC8k/SqIMKE0JzcEOC03pzSCMNwq3yO/G7oSFAkZ/xT1VOsm4tLZmtK5zF7IrsXAxJ/FRsijzJfS9tmI4g3sPPbFAFkLpBVWHyIowi/6NZU6cD1vPoo9xDowNvAvMSgvHywVdwpi/0H0bek53/bV7s1ix4XCgL9uvlm/PMIFx5DNrNUd35rp1PRyAB0MeRctIuUrUzQ1O1NAgkOnRLhDuEC8O+k0cSyVIp8X5Au//4vzqud43E3SeclDwuW8i7lRuEW5YLyNwabId9G82yjnYvMMAMUMKRnYJHUvrTg2QNRFWUmnSrFJfUYgQcI5mzDvJREaWg0tAPLyDebk2dfOPMVgvYO307NwsmiztLY/vN7DWs1p2Ljk6fGU/1ANsxpUJ9AyzDz5RBZL8E5oUHBPDUxXRnc+qjQ6KX0c1g6vAHXyl+SA15fLO8G+uGOyXa7QrMetQLEgtz2/Wcko1U/iavAK/74NFhygKfM1rUB6SRNQQ1TnVfFUZFFcSwRDmzhxLOIeVxBBARXyR+NM1ZHIer1ftImtL6l0p2ioB6w2sse6ecX80e/f5+5w/hEOUh28K904T0S2TchUTVkfWy1aflYrUGNHaTyRLz0h2xHjAdDxHuJJ08TF+rlHsPmoSqRhok+jDqeErYC2vsHozprdY+3H/UgOZx6lLYw7rUepUTJZCl4LYCJfVVu/VJFLEUCXMosjXxOSAqbxHeF50TTDvrZ5rLektZ+dnYCeWqIPqWyyKr7wy1Tb3+sS/WUOVR9cL/09xkpRVUxddmKnZMpj5V8TWYlPj0OANcgl4RRNA5bxQ+Dcz+HAyLP4qMagc5sqmQCa753bpJCuw7oYyR/ZX+pR/GgOGyDfMDBAmE2rWBRhjmbvaCFoKmQlXUlT30ZIOPQnYBYUBKDxkN9zzs6+G7HGpSidhpcNldOV0ZntoO+qi7dhxv/W5OiF+1IOuyAuMiRCIVC1W4ZkT2rgbCRsH2jvYMtW/knsOgkq1xfjBMHxBN8+zfq8t67louGZ85NJkfuRBJZHnY2nhrTQw/XUcOey+iUONCFJM9hDX1JtXqFntW12cM9vw2tvZAxa6ExqPQcsRxm6Bfrxnt49zGa7nqxXoPOWu5DijX6OjJLumW2kt7FowQTTBebY+eENhyExNEtFU1TQYGJqvXCvcx9zEG+gZwldmk+9P+otqxqXBknyXd5vyxO60KoenmCU4o3Zil2La4/mlpOhI68rvzDRp+T5+IgNtiHkNH5G+VXeYsdsZ3OHdhB2BHKAar5fEVLjQa8vAxx3B6zyQd7WygK5UKk7nCmSaYsxiJuIpYwwlAOfyqwcvXrPV+MY+BsNwCFkNW5HU1eWZM9urnX9eKF4m3QLbSliSlTZQ1QxSx1ZCCLzSd5wyjK4HaivmlCQU4nuhTyGPIrQkb6csao/u+bNF+I295wMpyGxNR5IYFj3ZXhwk3cOe8561XY/b0dkQ1adRdcygh47Carzct48yqK3N6d6mdeOoIcPhEGEM4jIj8ea2qiVuXbM6uBU9g0MbCHMNY5IH1n/ZsJxE3m5fJd8rXgZcRZm+FcsRzQ0pB8bCkH0vt45ylO3nqadmL2NU4aYgquCi4YcjiGZSKchuCvL0t929W4LESG2Nb1IkVmwZ6xyLnr8ffl9I3qYcpJnZ1mESGs1sSD3Cub0KN9nykO3U6YZmASNa4WJgX2BR4XLjM+X/KXmtgnK0d6d9MIKlyBwNa1ItlkJaDVz43rXfvN+NXu6c7toj1qiSXg2piHNC5j1sd/EynO3U6bsl6uM6YTjgLiAaITZi9CW+aTltRHJ6d3L8wsK/x/8NF9IkFkKaF1zMXtJf4R/4Xt8dI9pbVuFSlo3gSKbDFT2V+BPy9+3oKYWmLKMzoSmgFuA74NHiyiWQKQgtUbIHN0B80oJTB9bNNRHHlm1ZyZzGXtRf6t/J3zfdAtqAFwrSw84QCNgDRn3F+EGzIi4NqeWmBmNGYXTgGmA3YMVi9iV06OZtKjHa9xC8oIIfx6PMw1HY1gKZ5BynHrvfml/BnzgdC9qR1yTS5U44SMZDuX38OHnzGy5Fqhsmd+NyYVpgeCAMYREi+CVs6NRtDrH2tuQ8bQHmh2ZMg1GYFcKZptxuXklfr1+fnuAdPtpQFy6S+s4YyTEDrX44eLxzYi6PKmVmgKP3oZngsCB7YTUi0GW4aNKtP3GaNvs8OIGnxx8MdZEFla4ZEpwcnjzfKl9j3q/c21p6luhSw45xCRgD4j55uMhz9u7qaoQnIGQVojNgwmDD4bHjPyWXqSFtPPGGNtZ8A4GkBs5MGhDiFQUY51uyXZZeyx8OnmccoZoRltFS/84AiXqD1z6/uR10GK9WKzbnVuSMIqZhbqEl4cajhCYKqUCtRzH7NrX7zoFcBrTLsdBuFIiYZdsv3RbeUd6f3cYcUVnU1qnSrs4HCViEDD7J+bs0Ry/Sa70n4yUaozKh9GGhInOj32ZRabCtXrH5Npp72gEPxlNLfU/p1DjXjtqVnL4dv53YHU0b6tlEFnFSUM4EiXGEAD8XueC0wbBeLBYohOXAY9dikyJ1YvikUObr6fFtg3IAtsQ75kDARinK/Q9Wk5bXIpnkW81dFF13nLxbLljflehSJU34CQUEcz8o+g21R3D4rIEpe6Z85FRjSuMh45UlGGdaakLuNbIR9vN7tECtxbmKcg700uLWYdkc2wScUJy+29Qam9hnlU5R7E2iCRLEZH98ekF117FhrX2pxidPZWikGmPmpEil9afcKuUudXJs9uj7g8CZRULKHI5FEl4VjZh/miTbdVuumxUZ9BecFOORZc1CCRpEU7+SOvr2MfHX7grq4+g3JhNlASTCpVLmqCixK1huwvLSNyR7lcBCxQZJvY2IUYjU5pdNmW8aQxrHGn/Y9xb9VChQ0Y0XyNuEQH/pOzo2lXKa7uerk+kzZxQmPuW1JjNnb2lZLBvvXbMBd2a7qoArBITJFg0/UKST7dZHWGPZepmJWVSYJZYME5yQcAyjSJYEaj/BO733ATNpr5MslWoC6GnnEib9pykoSupTrO+vxjO7N2+7goASxH7IZkxqz/HS49VuVwQYXJi2WBRXABVIUsDPwMxkiEmEUEAZu8X39LPDcIztp2slKVNoeifbaHOpeisgbZNwu/P+9797nj/6Q/UH70uMDzHRyhRDVhDXKpdOVz+Vx1Ry0dUPBIvbSDYEMwAx/BE4bvSnMVMuiKxYqpAptikNaZIqvGw+rkaxfrRNeBa7/T+iQ6hHcgrjziVQ4ZMHlMsV5NYS1deU+9MMERoOe0sHx9tEEcBJvJ847zVT8mWvuG1cq95qxOqSasOr0S1t70kyDnUl+HU74L+LQ1lG7woyzQ1P6xH703RUTRTEVJzTnlIUkBBNpQqqR3kD7EBgPO85dHYI80Kw9S6vrT2sJavprAdtNy5tcFpy6vWIuNs8CH+1gsiGZ0l6DCsOqBChkg0TJBNkkxCSb9DNDzfMgooCRw9DwgC0/QB6PjbE9Gmx/i/Q7qwtlq1R7Zvube+8sXnzk7Z1eQi8dT9hwraFm8i6yz/NWU96EJdRq1H0EbPQ8Q+2TdGL08lQhp4DkwCHfZK6i3fHdVlzEjF+r+kvFu7KbwCv9DDasqb0iDcsOb28Zr9QQmSFDQf1ygwMQI4GD1PQI5B0UAePo05RTN4K2UiVBiVDXsCXveT7G3iOtlB0b7K4MXLwpXBRMLRxCTJGs+C1iHfsejo8nb9BghKEvAbsCRGLHoyHjcPOjs7mTozOB00ei54J08fQBaTDJQCkvjZ7rTlad041lbQ7sshyQLIlsjWyq/O/tOa2k3i2Or582f92QYGEKcYeyBFJ9Ms/TCkM7Y0LzQUMnkufSlIIw4cBxR0C5gCufka8f/opOFD2wrWINKgz5zOGM8O0WvUFNng3qLlI+0n9W/9uQXIDVsVOhwxIhMnvCoTLQguly3FK6UoUSTtHqQYqxE3CoUC0fpU80vs6eVf4Nbbb9hD1l7VxdVy11XaVd5R4x/pkO9y9o39qQSSCxAS8xcPHT0hXyRhJjQn1iZNJaYi+h5oGhUVLQ/eCFsC2PuF9ZTvMuqG5bXh194D3ULcl9z+3Wjgv+Po58DsHvLZ98L9qwNnCckOqRPjF1cb7R2UH0Eg8x+vHoEcfhm+FWMRjwxpBxoCzfyq99jye+616qDnUuXb40LjieOs5J7mTumj7IPwzPRc+Q/+vwJJB4kLYQ+yEmcVaxeyGDUZ9BjyFzsW3xPzEJAN0gnYBcIBsP3B+RP2wvLm75Tt2+vF6ljqlep36/Ps/O5+8WX0l/f6+nP+5gE6BVQIHQuBDXEP3hDBERYS3REbEdkPIw4KDKAJ+gYtBFIBf/7I+0P5AvcW9YvzavK78X/xtfFY8mHzxPR09mL4fPqx/O/+IgE7AysF4gZVCHsJTQrHCuoKtgowCmAJTwgHB5YFBwRqAssAOP+9/WT8N/s++n/5/Pi3+LD44/hL+eP5o/qD+3j8e/2B/oH/cwBQARICswIxA4kDvAPKA7YDgwM3A9YCZwLvAXUB/QCPAC0A3f+e/3T/Xv9c/2z/iv+0/+X/FwBIAHMAkgCjAKMAjwBmACkA2v96/wz/lv4b/qP9M/3Q/IL8Tfw2/EH8cfzG/EH94P2f/nr/agBpAW8CcwNqBEsFDgaqBhcHTgdMBwwHjgbUBd8EtwNhAugAV/+5/Rv8i/oW+cv3tPbf9VP1GPUz9ab1cfaQ9/34rvqa/LD+4gAfA1UFcgdlCRoLhQyVDUEOgQ5ODqkNkgwPCyoJ8AZwBL0B6/4P/EH5l/Yn9AbySPD77i7u6e0y7grvbPBR8qz0bveC+tH9QgG8BCMIWgtIDtMQ5xJvFF4VqRVLFUMUlxJREIANOAqRBqYClv5/+oH2vfJR71rs8eks6BvnyeY753PoaOoO7VPwIPRZ+N78jAFABtUKJQ8PE3EWLxkyG2ccwRw7HNUamRiUFdsRig3BCKIDWP4I+d3zAO+Z6szmt+N34R7gvN9U4ObhaeTM5/bryfAi9tj7vwGqB2oN0hK3F+8bWh/YIVUjwiMYI1ohkh7UGjkW5RD+CrEEMf6s91fxZOsD5l/hnt3h2j/ZyNiC2Wvbdt6P4pjnbO3f88D62wH4COEPXRY7HEkhYCVcKCQqpirdKcsnfiQMIJYaRRRHDdIFIP5r9vDu6ueR4RjcrNdx1IPS9NHL0gXVk9hc3T3jCuqR8Zj54AEqCjYSxBmYIHsmPiu4Ls0waDGEMCQuVyo4Je4epheZDwIHJv5H9avsl+RJ3fzW5NErzu/LRcs1zLvOxtI42OreqeY872D4zwFAC2oUBR3LJIEr7jDnNEo3AjgHN140FzBTKjwjBhvxEUEIQv5A9Inqa+Es2Q/STMwUyInFwcTGxZLIE80n06LaS+Ph7Bv3qAE5DHoWHCDRKFUwbDbkOpc9bz5hPXQ6uzVZL30nYh5NFI0JdP5W84zoad4+1VPN6cYywla/br6Dv5DCgMcuzmnW89+E6sn1bAEUDWUYByOmLPY0tDuqQK5DqESMQ2FAPDtENKwrtSGrFuQKuv6J8rPmlNuC0c7IvsGJvFy5ULhyubq8EsJSyUXSptwm6G30HAHSDSsaxiVIMF85wkA0RotJqUqCSR9GlkAQOcUv/SQIGUQME//a8QHl7Nj7zYLEz7wet5+zbrKYsxW3zryXxDfOZdnL5QnzuQByDskbVii1M409kUV/SydPbFA/T6lLw0W4PcUzNShhG6wNgP9J8XbjddaqynPAIbj2sSSuy6z5raaxuLcCwEbKNdZ0457xRAD1DkAdtSrpNn1BHUqFUH9U7FW+VPxQwEo5Qqc3XCu0HRkP/v/U8BPiLtSTx6O8trMTrfCobqecqHKs1rKXu3TGGdMm4S7wvv9cD5Ae4izjOSxFZE5CVY9ZJlv5WRBWh0+NRmg7bC79H4oQiwB88NjgGtK2xBW5k697qAakWaKEo36nLK5at8XCFNDi3rzuKP+mD7cf3S6hPJhIY1K0WVFeFGDtXuNaE1SxSgQ/ZDE7Iv0RKAFA8MXfOdAXwsy1uqsxpGyfk522ns6ivalQsz6/Ks2s3ErthP7UD7UgozAhP75LFVbWXcNismSUY29fYlihTnZCPzRqJG8T0wEf8Nrejc62v8qyL6g3oCSbHpk2mmaekKV9r+G7XsqF2tnr0/3oD4whNjJjQZxOelmmYeBm/WjrZ7FjblxYUrxF+zaHJt4UigIY8BjeFc2VvRCw8qSSnDKX/pQJlkuap6Hjq7O4tMdy2GzqF/3hDzoikzNkQzBRjVwgZaVq8Wzua6RnM2DSVdFIlDmQKEkWSwMs8H3d0su0u6GtCKJEmZqTN5ExkoCWBp6IqLe1LcV01gXpUfzCD8EiuzQkRXpTTl9CaBBuinCab0ZrrmMNWbNLBzyCKqwXFQRX8ArdxMoVun6rcZ9Oll2QzY2zjgqTsZpvpfCyzsKO1Kbng/uKDyEjrzWiRndVumEKax5xxXPqcpFu3GYFXF5OUj5bLAUZ5gSa8L3c7Mm4uKepMJ20k3+NwYqRi+qPq5eaomKwmcDD0lLmsPo8D1sjbTbeRydX0GN2bcxzoXbddYRxuWm2Xs9QcEAXLlMavAXy8JfcSMmctx6oRZt4kQGLFojOiCSN+JQNoA+ukr4W0Qvl2PnaDm8j9jbYSIpYj2WEbxh2GXlveBx0QmwdYQNTYEK1L5MblQZf8ZXc2cjDtuOmspmZj+eI0IVthruKmZLLnfururyIz9Pj/vhjDl4jTDeQSZ1Z9mYycQF4LnueelZ2dW45Y/hUH0QyMcMccAff8bfcncgttvald5gajjCH74NwhLKIk5DXmyeqFbsdzqziI/jaDSsjbjcGSmNaBWiBcoV523xofC94T3AGZapWqkWLMuAdSghw8vzclMjXtVillZf8jN+FdILZggmH5o4ympeopLnWzJnhSvdBDdUiXjc7Stpaumhvc6R6In7MfaZ5znGCZhhYAEe/M+keIQkR82LdvcjDtQelDJc/jPOEYoGpgcSFlY3fmEynari3y5vgdPaZDGAiHTcwSgRbF2n8c1x7/37Ifrl68HKrZz9ZHUjKNNwf9Qm/8+fdFsnutQSl25bii26EuoDhgOOEoozgl0imarfAyrTfpPXlC8shrDblSeFaHGkodK57c39cf2d7tXN/aB5aAEmsNbYgwQp69IrenslYtk2lA5fni1CEeoCCgGiEDYw3l46lpLb0yefe2/QlCxkhDDZcSXJayWjzc5h7fn+Gf7B7GXT9aLNaqEliNnYhhgs/9UrfVMoAt+KlgZdLjJmEpICNgFKE2Ivklh+lG7ZUyTXeG/RcCkwgQDWWSLhZIGhecx17H39Gf5J7HnQlafxaEkrqNhkiQQwL9iTgNsvjt8GmVZgQjUeFOIEBgaSEBIzplvyk0LXjyKDdZ/OMCWUfSTSWR7RYIWdrcjx6V36efg17wXP0aPlaPUpDN54i7wzf9hfhQcwAueinfpkyjlqGNILegVyFkYxGlyalxbWiyCvdv/K2CGceKjNcRmlXzmUacfd4J32MfSF6BHNraKhaKUpsNwQjkA229yDidc1Wulap+pqxj9GHmIMlg3uGf437l52l+rWSyNXcJvLdB1Qd4zHrRNlVKWRtb053kHsRfNB45nGJZwpa00ljN0kjIQ6Q+D3jzs7huwirx5yLkaqJYoXShP+Hzo4KmWOmcLa0yKLcnfECBy0ceDBGQwVUNWJnbUV1k3kwehl3Z3BOZh1ZPUknN2sjoQ5r+W3kS9Cgvf2s456+k+SLkYfnhuiJfJBxmnanKLcKyZHcJvEoBvUa6i5uQfFR818Ia9xyMnfqd/90iG67ZOJXZEi4NmkjDg9E+q3l6dGQvzGvSqFHlnyOI4pfiTSMipIwnNmoIriTyaXcxPBQBa4ZPS1nP55PZl1VaBZwb3Q/dYFyTGzQYllWSEcUNkMjZg8a+/vmpdOuwaKx+6MkmW+RFo07jOKO9pRGnomqXrlRyt/cdvB9BFoYcisyPRBNkVpPZfZsTXEzcqNvsmmPYIJU60U8NfYiqQ/r+1ToftX5w02086ZSnLqUZpB2j/CRvpeyoIas3LpFyz/dPvCvA/sWjCnTOklKeFf6YYBpz23JbmZsvGb4XV9STEQuNIMi1A+1/LfpcNdsxi+3LqrNn1yYEpQPk1uV4Jpzo9CunLxtzMbdH/DpApQVjidMOE1HHVRZXrVl92kCa85obmMOW/BPa0LrMugh6A92/SLredkFyUS6qK2So0+cFZgDlyCZWp6GpmSxnb7KzXTeGPAtAicUeyWiNR9Eg1BwWpphymXiZtxkyV/RVzZNSkBzMSYh4Q8t/pHsltvBy4q9X7Gep5GgbJxOmz2dKqLrqUK038Bdz0vfLPB8AbYSVCPWMsJAsExDVjJdSmFtYpRgz1tGVDRK6T3HLzsgwA/Y/gPuxd2czvzAT7Xtqx2lE6Hsn6+hTKadrWi3X8Mj0UngWvDYAEQRHiHsLzs9pkjUUYJYfFynXfpbhVdtUOtGSjvmLSgfhA91/3bvA+CU0ZjEc7l5sPCpB6bapHGmvqqcsdS6HcYe03DhpPBCANIP2h7nLIw5aUQqTY5TZFeSWBBX7VJKTF1DbTjSK+0dLA8CAOfwTOKk1FnIx71AtQSvQqsUqoGre6/jtYO+F8lL1cDiC/G8/2IOjBzLKbo1/j9ISFpOB1I1U9xRCk7fR40/VjWLKYoctw6AAFTyn+TL1zvMSMI9ule0wbCUr9mwgbRvunPCS8yq1zfkjvFH//cMNRqbJskxaTsyQ+tIaEySTWFM4kgxQ347BTIUJ/8aJg7tALzz+OYD2zvQ8MZqv+G5frZXtXW2zLk+v6HGuM862tXlLvLk/pML2hdaI7strjbuPUZDjkawR6RGd0NCPjI3fi5sJE0Zdw1GARz1VelL3lTUvMvExJ+/dLxYu1K8Vr9MxArLWtP53Jvn7PKU/jcKfBUNIJcp0jGAOHA9fUCSQapAzj0XOa0ywiqXIXQXqgyMAXP2s+ue4YPYp9BFyozFn8KRwWnCHMWUyavPL9fk34bpx/NY/uUIHxO1HF4l2SztMm43Ojo/O3c67De0M/Et1CaVHncVwAu+Ab/3D+765MTcrdXpz6LL+cj+x7bIGcsSz3/UNdv74pbrwPQx/qAHxBBXGRYhyCc6LUUxyzO7NBE01TEcLgQptyJpG1UTuQraAf74Z/Ba6BLhyNqp1dzRfM+YzjPPSNHC1IXZaN885srt1vUg/mgGbw72FcMcpCJtJ/sqNS0MLn0tjytUKOgjbx4WGBARlQngAS76ufK762rl9N+C2zXYI9Za1dzVpNeg2rfexeOj6R/wCPcl/kAFIQyUEmgYcR2KIZUkfiY4J8EmHyViIqEe/RmcFKkOVAjPAU/7AvUb78fpLOVu4abe6Nw+3KvcKN6m4BHkSegu7ZbyVvhB/igE3gk3DwoUNBiXGxoerB9EIOIfiR5JHDQZZxUAESMM+AaoAV78P/d28iXubOpn5yvlxeM/45njzuTR5o/p8ezb8Cv1wPl0/iIDpwfgC60P8hKYFY0XxRg3GeUY1BcPFqYTrxBDDX8JgQVqAVr9b/nI9YDyr+9p7b3rtepX6qLqkesZ7S3vuPGm9N33RPu+/i8CfgWSCFQLrw2UD/YQzhEXEtIRBRG4D/oN2QtpCb8G8QMVAUP+kPsQ+db28fRu81fysvF/8b/xa/J78+b0m/aO+Kv64fwe/1ABZgNSBQMHcAiPCVoKzQroCq0KIQpMCTUI6gZ1BeUDRwKpABj/n/1J/CH7LPpy+fT4tPiy+On4Vvny+bX6lvuN/JH9l/6W/4YAYQEgAr8COgOPA78DygOzA34DMAPNAl0C5QFqAfQAhgAmANf/mv9x/13/Xf9u/43/uP/p/xsATAB2AJQApACiAIwAYgAjANP/cf8D/4v+Ef6Z/Sr9yfx9/Er8NvxE/Hf8z/xN/e79sP6N/38AfwGFAogDfQRdBR0GtQYdB1AHSQcEB4EGwgXJBJwDQwLIADX/lv35+2r6+fix96D20PVK9Rb1OfWz9YX2q/ce+dX6xfze/hEBTwOEBZ4HjAk8C58MqA1LDoEORQ6WDXUM6gr+CL0GOASBAa7+0/sG+WD29vPd8Sfw5e4j7urtP+4i74/wf/Lj9Kz3xvoa/o0BBgVpCJsLgg4EEQ0TiRRrFagVOxUlFGwSGhA+De0JPwZQAj7+KPou9nDyDe8h7MXpDugM58vmTueV6JnqTu2f8Hf0t/hB/fEBpAY0C30PXROyFmIZVBt3HL4cJRyuGmAYSxWFESgNVggzA+b9l/hx853uQuqC5n/jUeEN4L/fbOAT4qnkHehX7DfxmfZV/D4CJwjiDUATGBhBHJgfAiJpI74j/SIpIUseehrOFWwQewooBKX9IvfT8OvqmOUG4Vrds9oq2czYn9mh28Pe8eIN6PDtbvRX+3MCjglwEOEWrxyrIasljig7KqIqvSmRJyokoR8XGrUTrAwvBXv9yfVV7lznE+Gv21vXO9Rp0vjR7dJE1e3Yz93G46XqOPJH+pEC2QrdEl4aICHsJpUr8i7oMGQxYDDgLfYpvSRcHgEX5g5HBmj9jPT56/LjuNyD1ofR7M3Ry0rLXMwDzy3Tu9iF31nn+u8n+ZkCBwwoFbMdZiUCLFExKjVqN/433zYSNKovyCmXIkwaJxFuB2z9bfPA6bHgiNiG0ePLzcdnxcXE8cXiyIbNutNQ2xDktu3694oCGA1PF98gfinmMNw2Lzu8PWs+NT0gOkI1vy7GJpMdbROiCIX9a/Ks55vdiNS7zHPG4sEvv3K+sb/owv7H0M4p18zgbuu/9mYCCg5QGeAjZS2WNTA8/kDXQ6VEXEMGQLg6mzPjKtMgthXjCbT9iPG+5bHautAnyDzBMbwwuVO4o7kYvZvCAcoV05HdJul59SwC3g4rG7ImGTEOOklBkUa5SaZKUEm9RQhAWjjtLggk/xctC/j9w/D34/bXIc3Mw0G8vrZus3CyzLN6t2C9VMUYz2Pa3uYq9N8BlA/eHFUplzRLPiRG40taT2pQCk9CSyxF9jzdMi8nRBqADE/+HPBX4mzVv8muv4e3jbHvrcysL64RslS4y8A1y0TXm+TT8n4BLBBpHscr3DdJQrxK8lC3VO1Vh1SOUB9KakGxNkQqhBzaDbn+k+/h4BPTmMbQuxGzoqy1qG2n1KjirHqza7xxxzjUX+J38QwBphDLHwYu5joGRg9PuFXLWShbwFmeVd5OtEVkOkUtvB45DzT/KO+T3+7QrMM1uOOuAqjHo1aivaPzp9iuObjQw0PRLOAX8IgAAxEFIREwsz1/SRhTMlqTXhhgs15sWmNTzUnzPS4w6SCaEL//2u5u3v3O/cDftACrr6Mnn46d8J5Ho3GqObRVwGfOBd617vb/QhEUIugxQkCyTNVWXF4KY7hkWWP1XqtXtE1aQfwyCSP8EVgAqO5z3UDNjr7QsWqnrp/bmhaZcZrjnkmmbrADvajL7dtU7Vb/ZhH7IoozkUKcT0NaM2IsZwVpsGczY7FbYlGVRKs1GCVcE/8Aku6h3LrLX7wLrySkAZzklvSURJbKmmai3azfuQrJ59n166n+bxG4I/U0n0Q8UmBdtWX2avxss2skZ3Ff1VShRzk4FSe4FLIBl+7422nKcrqQrDChrJhGkyuRbZICl8qeiKnsto7G9deb6vH9XRFNJCs2bEaQVCpg3mhmbpdwXm/DauhiClh6SqI6+ygPFm8Cte5420/Jx7hiqpGesJUFkL6N7o6Nk3mbdaYttDjEGtZJ6S/9MxG5JCo39UeXVp9irGt5cdVzr3INbhJm/FoeTeM8yipdFzQD7O4g22vIX7eCqEecD5Mija+Ky4tvkHaYpaOmsQzCWdT/52f88BD+JPM3O0lRWL1kHm4rdLR2o3X/cO1oqF2IT/o+fiyiGAAEOu/u2r3HO7bwplWazJCgigKICImqjcWVHaFZrwvAs9LB5pj7lxAcJYY4Pkq7WYNmMnB8di95NniWc3RrDGC3UeRAFC7ZGdAEnu/k2kXHWbWtpbuY6I6BiLmFpYZBi2mT3p5IrTm+LdGQ5cb6KRAUJeQ4/krWWvBn5nFpeEZ7Z3rQdaVtJWKoU55Ciy8CG6QFFvD+2gHHu7S6pHqXZI3GhtSDp4Q3iWOR7Jx4q5i8x89w5PL5pw/oJA05e0uiWwRpOXPxefd8M3yqd39v8GNXVSVE3zAaHHgGoPA82/LGX7QWpJOWQYxxhVeCDYOOh7aPSJvqqSq7hM5h4x75FA+YJAM5tksfXL9pLHQTe0B+mX0ief5wa2XEVnhFDzIfHUsHPPGd2xXHRrTAowWWgIuChEOB24FHhmWO9pmgqPO5Z81m4kz4cA4mJMY4r0tNXCBqvHTPeyB/l343eiFylGbqV5RGGTMQHhsI5/Ef3GvHbbS5o9GVIIv6g5eAEYFkhXCN9pidp/O4ccyB4X73vg2VI1g4Z0stXChq63QjfJd/LX/neudyamfKWHhH+jPpHucIoPLA3PHH1bQApPWVIYvZg1WAr4DnhNqMS5jipiy4pcu04Lb2/wzkIro34ErAW9hpuXQRfKV/Wn8ye05z6mdgWSFIsTSpH6wJZfN/3abIe7WTpHGWhIsfhHyAt4DPhKOM9pdwpqG3BMsB4PX1NQwXIu82G0oHWzBpJ3SYe0h/HX8Xe1VzFGitWY1IPDVPIGgKM/Ra3ojJXrZxpUWXRozLhA2BKYEdhcuM95dKplO3kMpp3z71YwsvIfc1GkkEWjFoNXO5eoN+d36Vevxy52etWb1ImTXYIBoLCfVP35XKfLeZpm6YaI3dhQeCBILShVSNUJhvpkO3Ssrv3pL0igouINU030e4WN9m5HF1eVV9aH2teUNyY2diWa1IxzVCIb8L5fVc4MzL1LgIqOqZ545Th2mDR4Pthj6OAZnhpnK3NMqU3vPzrAkWH4oza0YmVzllOHDNd7978XtgeClxhmbJWF5IxDWOIVYMxfZ+4SnNY7q9qbmbwZAriTKF8oRtiIiPCZqgp+K3T8pZ3mTzygjpHRoywURPVUJjMG7EdcR5EnqtdrBvUWXjV85HkDW3Id4Mp/e14qzOJ7y2q9ed9ZJli1+HA4dSijGRaputqJK4nMpA3uXy6AepHIYw5EI2U/1g0Gtbc2V3z3eXdNdtxWOwVv5GKjW/IVQNifj941HQHb7vrUKggJX8jfCJeYmZjDmTIp0HqoK5HMtK3njyBwdZG9Au1UDdUG1eGmmVcKN0J3UecqBr4mEwVe1FkTSjIbcNaflV5RbSQ8BmsPeiYJjwkOGMUYxDj56VMJ+tq7W6z8t53h/yKAb7GfwsmD5JTpNbEmZ0bYJxHnJFbw1pqV9iU5pEwzNiIQYORvq55vnTlsIYs/SlkZs9lDGQio9Lkl+Yk6GhrSi8t8zM3tvxTgWQGAsrMDx6S3NYuWL8aQVut24NbB9mG11JUQZDwjL8ID8OHfsp6PfVFMUCtjWpEZ/hl9yTIJOxlXqbS6Tfr9y90s1F367xewQcFwEpnzl1SBFVE18vZi1q82p6aNhiOlrlTjJBjTFwIGAO7Pug6QzYuMchubes26LWm9+XEZdymeyeVadostC/Ic/l35jxrwOhFeEm6DY9RXBRJVsRYgBm1maNZDpfCFc4TB8/JDC9H2oOs/wf6zjagMpxvHew7aYboDacWZuKnbSir6o6tQPCpNCr4Jvx7gIhFKwkEDTWQZRN8VamXYBhY2JLYElbh1NCScw8hy7jHloObv2h7HXcac3vv2+0QaurpN6g9Z/2oc6mV65TuHTEW9KZ4bjxOQKdEmYiGDFCPoBJfFLyWLFcn122WwdXuU8GRjw6tyziHTAOHf4l7sPeb9CXw5241a+CqdOl4aSzpjirSrKxuyPHRNSu4u/xkAEZEREgBC6HOjlFyk35U5hXjFjRVndSoUuGQm83tCq5HOsNv/6p7x7hj9Nlx/y8pLScrg+rGaq9q+2vhrZTvw3KYNbq40Ly9gCWD7Ed2CqnNsNA4EjATjlSMFOjUZ1NQkfFPmk0gChpG4sNUf8q8YPjxtZWy4nBqbnzs5CwmK8Qseq0B7s0wzDNrNhN5bDybAAXDkgblyemMiI8wUNMSZhMkE0tTH1IoELEOikxHCbzGQ4N0/+m8u/lEdplzz7G4L6DuU+2WbWntiy6yr9Tx4vQKNvX5jvz9P+eDNgYRCSJLlo3cz6gQ7tGr0d1RhtDvT2HNrMtiCNWGHUMQQAc9GHoa92P0xfLRMRIv0i8Wbt+vK2/y8StyxvU092H6OPzjv8sC2YW4yBUKnAy+zjEPadAkkGAQHs9njgSMgoqxyCTFr8LngCJ9dTq0eDP1xDQ0Mk8xXbCkcGQwmvFBso+0N7XquBc6qf0O//ECfMTeB0KJmktXTO6N2E6QDtSOqI3RzNmLS4m2h2sFOwK5wDs9kbtQeQh3CTVfs9Zy9PI/MfZyF/LeM8D1dHbrONV7Ij1/P5nCIIRBRqwIUkony2KMe4zvDTxM5QxvC2JKCUixBqhEv0JHAFD+LXvtueC4E7aS9Wb0VrPls5Sz4XRHNX42fHf1uZx7oX20v4XBxUPjhZKHRUjxSc4K1QtDi5hLVcrASh9I+8dhhd0EPIIOwGM+R/yLevs5IvfMNv81wXWWNX21djX7doZ3zvkKOqv8J73vv7VBbAMFxPcGNId1iHJJJkmOiepJu8kGyJGHpEZIhQlDssHRAHF+n/0o+5d6dTkKeF33s/cPdzA3FPe5+Bj5Kzone0O89P4wP6kBFQKow9qFIUY1RtFHsIfRiDOH2IeDxzqGA4VnBC3C4gGNwHu+9b2FfLP7SXqMOcF5bLjPuOr4/HkBOfR6UDtM/GL9SP62f6EAwQINQz4DzETyRWvF9YYOBnWGLUX4RVsE2oQ9gwsCSsFEwEF/R75fvVA8nnvP+2h66fqV+qw6qzrQO1f7/Px6PQl+I77CP93AsMF0QiKC9wNtw8OEdkRFhLGEe4Qlw/QDagLMgmEBrQD2AAI/lj73fiq9s30U/NF8qnxgPHJ8X7ylvMH9cP2ufjZ+hH9Tv9+AZEDeAUlB4sIpAlnCtMK5wqlChIKNwkcCMwGVQXDAyQChgD3/oH9L/wK+xr6Zfns+LL4tPjw+GH5AfrG+qr7o/yn/az+q/+ZAHIBLwLLAkIDlAPBA8kDrwN4AygDxAJTAtoBYAHqAH4AHgDR/5b/b/9d/17/cP+R/7z/7f8fAFAAeQCWAKQAoQCJAF0AHQDL/2j/+f6B/gf+kP0h/cL8d/xH/Db8R/x9/Nj8Wf39/cL+of+UAJUBmwKdA5EEbgUrBr8GJAdSB0UH+wZzBq8FsQSBAyUCpwAT/3P91/tK+tz4mPeM9sL1Q/UW9UD1wvWb9sf3QPn9+vD8DP9BAX4DsgXJB7IJXAu5DLkNVA6ADjsOgg1YDMUK0QiKBgAERgFx/pb7zPgq9sbztPEI8NDuGe7s7UzuO++08K3yG/Xs9wv7Y/7XAU8FsAjdC7wONREyE6IUdhWlFSoVBxRAEuIP+wyiCe0F+gHn/dL52/Uk8sru6eua6fLnAOfO5mLnuejN6o/t7fDO9Bb5pP1VAgcHkwvUD6kT8haTGXQbhRy6HA4chBolGAEVLRHFDOsHwgJ0/Sf4B/M77uvpO+ZI4y3h/d/D34bgQeLr5HDoueyl8RH30vy8AqMIWA6tE3gYkBzVHyoieiO5I+Ei9SADHh4aYhXyD/cJngMZ/Zn2UfBz6i7lruAX3YfaFtnS2L/Z2dsT31bjg+h17v707fsLAyQK/hBkFyIdCiL0Jb4oUCqcKpspVCfUIzQflxklEw8MjATW/Cb1u+3O5pfgSNsM1wfUUtL/0RLThtVK2UTeUORA6+Dy9vpDA4gLgxP2GqYhXCfqKyovATFdMTkwmi2TKUAkxx1bFjIOiwWq/NHzR+tP4yncDNYs0bDNtstRy4XMTc+W00DZI+AK6Lrw7/ljA84M5RVhHv4lgCyyMWo1hzf3N7M2wzM7Lzsp8CGRGVwQmgaV/Jry+Oj53+fX/9B8y4nHSMXNxB7GNcn7zU/UANzW5Izu2fhtA/YNIhiiISkqdDFJN3c73T1kPgU9yTnHNCIuDCbDHIwStweX/ILxzebP3NTTJcwAxpbBDL95vuO/QsN/yHPP69em4VrstvdfA/8OORq2JCIuMzapPE5B/UOeRClDpz8yOvAyGSrvH8AU4Qiv/IjwyuTR2fTPgse9wN27CblauNi5er0nw7PK6NN/3ibqhvY9A+oPKRycJ+gxujrOQelG4kmgShlJWEV3P6E3ES4RI/MWFgrd/K3v7eID10rMGMO3u2G2QrN2sgS04rf3vRPG+89j2/PnTPUFA7UQ8R1SKnY1Bj+0RkRMiE9lUNFO1kqRRDA88jEmJiUZVAsf/fHuOuFl1NjI7L7ytiixvq3RrGqugLL0uJfBKMxW2MPlCfS5AmERkB/WLMw4EkNYS1tR6lToVUtUHFB7SZhAtzUrKVMbmgx0/VTusN/70aDFALtxsjWsgKhwpxGpVq0jtEO9csha1ZnjwPJaAu8RBSEnL+Y73Ua1TylWA1olW4NZJ1UxTtZEXDkcLHkd5g3c/dXtUN7Ez6TCWLc4ro2njaNZovyjbKiIrxy53sR00nfhcvHpAV4SUSJEMcI+Y0rJU6pa0F4XYHNe8FmvUuZI3jz2LpYfNg9V/nXtGt3Czee/9bNKqjOj6J6OnTCfxKMpqya1b8Gnz2DfIfBoAbASciMqM2BBok2QV9xeS2O5ZBljdV7wVsJMOUC2MaYhhxDe/jLtDtz2y2q92rCqpiqfl5oVmbKaZJ8Ip2SxKb71zFfd0O7YAOQSaCTbNL1DmFAIW7ticmcIaW9nsGLwWmhQakNYNKcj2BF2/w3tLdthyi67Ca5ao3abm5bxlIaWT5sqo9utD7tiyl7bgO05APwSNCVVNtdFQ1MvXkRmQmsAbXFrnmarXtRTbEbaNpclJxMZAAPtddoDyTS5hKtdoBmY+ZIlka6SiZeTn46qJbjyx3nZM+yQ//gS1iWXN7BHolUBYXRptm6fcB1vO2odYgFXPUk5OXIncRTJABTt6Nndx363TKm2nRaVs4+1jS+PFpRGnICnbrWmxanX7Orb/toSTyaiOERJs1d+Y0lszXHfc25yg21DZe5Z2UtyOzYptBWCAT7thNntxgu2Yqdkm3CSy4ykigyM+ZBHmbak7rKBw/HVreke/qMSnyZ2OZRKdVmkZcFuhHTAdmJ1dHAaaJVcPU6BPeEq7xZEAoLtSNk1xt20yKVrmSeQRYr0h0eJNY6ZljGiprCIwVTUeOhZ/VQSxyYSOqBL6FpxZ9pw2XY+efd3CnOfavZeZ1BkP3AsHhgLA9ztNNm0xfOzfaTKlz2OIoioheSGzYs+lPafm668v9TST+eP/O4RyCZ5OmhMClzlaJNyynhYeyl6RHXPbAxhVFIZQeEtQBnXA03uRtloxU6zg6ODlrSMY4bBg+SEw4k5kgaezqwfvnPRNObC+3MRoiapOuxM3Fz+aexzVnoMffd7HneobtViAFSdQjEvUxqlBNHuftlTxeyy2aKWlY2LCoVBgkmDGYiNkGScQqu1vDTQKuXz+uUQWCalOixNXl2+auJ0fHtYfl99mHgncE9ka1XtQ14wVBt0BWjv2tlxxc2yfqIElceKGIQqgRSC0YY7jxKb+ql/uxrPMuQl+kYQ6yVsOilNkV0ja3d1O3w7f19+rnlLcXllkVYIRWUxQhxCBhDwWNrDxfGydKLMlGSKjIN7gEiB7IVFjhKa9qh/uiXOT+NZ+ZYPXCUBOuVMdF0va6l1kny1f/d+YHoTck9mcVfrRUYyGh0MB8fw99pGxlWzt6LtlGKKaYM2gOSAbYWtjWWZOqi4uVnNguKR+NgOrSRmOWBMCl3hanp1gnzFfyd/rXp8ctJmCViVRv4y2x3RB4vxttv6xvqzSaNolcOKrINbgOmAUoVzjQ2ZxqcrubbMzuHP9w4O4COaOJxLUlw6aul0DHxrf+1+lXqGcv9mWFgFR4szgx6PCFvykdzdx920JqQ6loOLVoTqgFiBnYWZjQuZnKfauD/MNOEW9zoN9iKhN5tKT1s9afhzLnuofkl+F3oxctVmXVg4R+wzDx9ECTTzid3syP21TqVil6SMZoXhgTCCT4YejmCZvafGuPXLteBm9l0M8iF9Nl5JAlrqZ6ly7Hl8fT19Mnl8cVVmFlgtRx80fx/uCRT0md4lyle3v6bfmCKO24ZBg3CDZocDjwyaKqjvuNnLVODC9XoL1iAuNedHblhDZvxwRnjoe8l76XdncH5lg1flRiM00B+LCvr0wd+Iy+m4d6ivmv2Ps4gIhRiF4ohHkA6b4qhXue3LE+Ar9ZIKox+5MzlGk1ZKZPNuPXbvee55O3bzbk9kpFZdRvczAiAbC+P1/+AQzbK6c6rQnDKS7IozhyaHworrkWic6Kn/uTLM8d+k9KgJXB4eMlZEdlQCYpJs1HORd613KXQgbcpieVWVRZkzEyCaC872T+K8zq+8saw+n7+UhI3DiZiJBY3tkxmeOavnuqjM8d8t9L0IAx1hMEFCGFJuX9ppDnHRdAl1tXHvau9gAlSNRAozAiAIDLj3sOOK0Ny+Lq/4oaGXeJCzjG6MqY9Llh+g16wPvFDNFODJ89MHmhuDLvw/fU+PXM5m7G2xcQNy4W5jaL5ePlJFQ0kyzR9iDKD4H+V30jjB57H7pNaaxpMCkKOPrZIFmXqiwK53vSvOW+B48+0GJBqILIo9p0xqWXJjcmo0bp5urmt8ZTlcL1C9QVQxdB+oDIT5m+aA1L/D2bRCqFmea5eskzeTDpYZnCil9LAevznPxuA98wwGoxhyKu86mUkCVshfo2Zeat1qIGg8YmJZ1032Py0w9h7ZDGL6Ieii1m7GAbjLqymiY5uulyWXyZmEnyiocbMFwXrQV+EY8zIFGhdEKCw4WEZZUtVbgmIwZsNmOWSnXjpWNUvwPdIuUx7yDDj7runb2ELJXLuSr0Cmq58GnGqb251Eo3irNrYqw+7RDeIK82AEihUBJkc15UJ0TptXFF6wYVNi/F++WsNSTEisO0UtiR3zDAX8QOso2zjM5b6Ts5uqPqSuoASgQqJVpxWvQrmNxZTT6uIW85kD9hOrI0EyRj9XSiBTXVnhXJFdbFuEVgBPHkUrOYYrmhzbDMb81eyG3U3PmcLLtzavGamjpe2k+aa2q/2yk7wsyGzV7eM6894CYBJGIR4vfjsGRmZOYFTGV4JYjlb9UfRKrEFvNpUphBupDHv9a+7y333SdcY1vAy0N67hqiKq/qtjsC23JsAFy3bXFuV58zACyhDUHuIrkDeEQXRJIk9mUihTZVEsTaFG+T15M3MnSBpdDCH+APBp4sTVdMrNwBq5k7NjsJ+vS7FXtaK7+MMYzrDZZebT85IBNw9YHJAogTPXPExEqEnETIlN9EsVSAtCBzpLMCIl5hj1C7j+kfHp5CDZks6OxVq+Krkktl+13baQulnACMhh0Rjc2udJ9AMBqA3VGSslVS8DOPU+90PlRqpHQka8QjU92jXnLKIiXhdyCz3/HPNu543cy9J1ysfD9L4gvF27rrwIwE3FUszf1K/edOna9IYAIQxOF7ghDysMM3M5FD7OQI9BUkAlPSI4dDFPKfYfsRXTCrH/oPT26QbgHNd7z13J78RQwpTBu8K8xXzK09CP2HHhMuuH9RwAogrFFDketCb3LcozBDiFOj07KjpVN9gy2CyHJR4d4RMYChEAGvZ/7IrjgNue1BfPE8uxyP7H/siny+HPiNVv3F7kFe1Q9sb/LQk+ErIaSCLIKAEuzDEPNLs0zTNQMVotCyiQIR0a7RFBCV4AifcF7xTn89/X2e/UXdE7z5fOcs/E0XjVbdp84HPnGu8194T/xQe6DyYX0B2FIxsocitxLQ0uQy0cK6wnECNuHfUW1w9OCJYA6viF8aDqcOQj3+Daxtfq1VjVEtYP2Dzbft+y5K7qQPE1+Fb/awY9DZkTThkyHh8i+ySyJjknjya9JNMh6h0kGacToQ1AB7gAPfr+8yzu9Oh85OXgSd643D3c2NyB3ijht+QP6QzuhvNR+T//IAXKCg8QyRTTGBIcbh7XH0UguR85HtMbnhi1FDgQSwsXBsUAf/ts9rTxe+3e6fnm4OSf4z/jvuMW5TnnFeqP7Yzx6/WH+j3/5gNhCIoMQxBvE/kVzxflGDcZxRiVF7MVMRMkEKgM2AjUBLsAsPzO+DX1//FE7xftheua6ljqvurI62ntku8v8iv1bPjX+1L/vwIGBg4JwAsJDtkPJBHkERUSuRHWEHYPpQ12C/sISQZ3A5sAzf0h+6v4f/ap9DjzNPKh8YLx1PGR8rLzKvXr9uX4CPtB/X3/qwG8A54FRQemCLcJdArYCuQKnAoDCiEJAQiuBjQFoQMCAmQA1/5j/RT89PoJ+lj55fiw+Lf4+Pht+RD62Pq++7j8vP3C/r//rACDAT0C1gJLA5oDwwPIA6wDcgMgA7sCSQLQAVYB4QB1ABcAy/+S/23/XP9f/3L/lP/A//L/JABUAHwAmAClAJ8AhgBZABcAxP9g/+/+d/79/Yb9Gf27/HL8Rfw2/Er8g/zh/GX9Df7T/rT/qQCrAbECsgOkBH8FOQbKBioHUwdBB/IGZQacBZoEZQMGAoYA8P5R/bX7Kvq/+ID3efa09Tz1FvVH9dD1sfbk92P5JPsc/Tv/cQGuA+AF9AfYCX0L0gzKDVwOfw4wDm0NOwyfCqMIVgbHAwoBNP5a+5L49PWW843x6e+87hDu7u1b7lXv2fDd8lT1LPhR+6z+IQKZBfYIHQz1DmQRVxO6FIEVoRUZFecTExKpD7gMVgmbBaQBj/17+Yn12PGH7rLrcOnW5/Tm0+Z3597oAevR7TvxJvV1+Qf+ugJqB/ELKxD1EzEXwxmTG5IctBz2G1oa6he1FNQQYgx/B1ICAv24953y2u2W6fTlEuMK4e7fyt+h4HHiLuXE6BztFPKJ90/9OwMgCc4OGRTWGN4cECBQIoojsiPCIsAguR3BGfQUdw9zCRQDjvwQ9s/v/OnG5Fjg1txe2gXZ2tjg2RPcZN+84/vo++6P9YT8pAO5CowR5heUHWgiOybsKGMqkyp3KRUnfCPGHhUZkxJzC+kDMfyF9CLtQuYc4OLav9bV0z7SCNI508nVqdm73tzk3euJ86b79QM2DCgUjRsqIsknPCxgLxcxUzEPMFItLSnAIzIdsxV9Dc8E7PsX85fqruKb25jV1NB3zZ7LW8uxzJrPAtTI2cLgveh68bj6LgSUDaEWDR+VJv0sETKnNaE37TeFNnIzyS6rKEch0xiRD8YFv/vI8THoQ99H13zQGMtIxyzF18RPxovJdM7m1LLcneVj77n5TwTUDvUYYiLRKgAysze8O/o9WT7SPG85STSDLVEl8RuqEcsGqfuY8PDlBNwj05PLkMVNwe2+g74YwKDDA8ka0K/YguJH7a34WQT0DyIbiiXdLs42Hj2bQR9Ek0TyQkY/qDlCMkwpCR/IE98HqvuI79fj89gxz+DGQsCMu+W4ZbgRuuC9tsNpy73Ubt8p65P3TQT1ECcdhCizMmM7T0I+RwhKlUrfSO9E4j7lNjQtGCLnFf4IwvuX7ubhEdZ2y2jCMLsIthqzgLJAtE+4kb7WxuHQZdwK6W/2KwTVEQMfTStTNr0/QEehTLNPW1CTTmZK8kNmOwUxGyUFGCgK7vvG7R7gYdPzxy6+YLbHsJKt2qyprvOymLlnwh3Nadnt5kD18wOWErYg5C25OddD70u/URlV31ULVKZP00jDP7o0DiggGloLMPwV7YHe5NCrxDW61LHNq0+oeadSqc+t0LQfvnbJf9bV5Ar0qAM3Ez4iRjDiPK9HV1CVVjZaHVtAWatUgE31Q1I47yo1HJMMhPyE7A7dnc6gwX+2ka0dp1ejYKI/pOqoPrADuu/FqNPE4s/ySgO5E5sjczLOP0JLdVQeWwdfEGAvXnBZ9lH6R8c7ui1BHtEN7PwR7Mfbi8zUvg+zmKm7oq6elJ12n0ek5asWto3C6dC94I/x2gIcFM0kajR6Qo5OR1hXX4djtGTTYvBdMFbNSxY/bDBCIBIPZP2+66var8pJvOiv7qWrnliaGZn5muufy6deslK/Rc7D3k3wWgJhFNMlKTbkRJBRyFs9Y7NnBWkoZydiKVpqTztCAjM1IlQQ6/2I67rZDMkAugytlqLwmliW85TNltmb86PdrkO8vsvY3AzvywGIFK4msTcMR0ZU+F7NZodrAG0qaxJm313NUjNFeTUXJJURgf5w6/XYoMf6t3yqkJ+Ml7GSJZH2kheYYaCXq2K5WMn+2sztLwGSFF4nADnwSK9W02EEagBvoHDVbqxpTGH0VftHzTfnJdISJP9z61rYbcY4tjqo35yDlGaPs413j6aUGZ2QqLS2Fsc52ZHshwCBFOMnFzqPSspYWGTfbBty43MncvNsb2TbWJBK/TmhJwoU0v+S6+rXcsW7tEemhprWkXuMn4pTjIqRHZrLpTq0+sSL113r1f9VFD4o9jrpS5VahWZdb9d0xnYcdeNvQ2d+W+5MBDxDKTsViADL66TXsMSDs6SkhZiHj/CJ7YeOiceOcpdLo/ixCMP21TDqGv8PFHAonDv+TA9cWWh8cTB3R3mxd3hyxWnaXRJP4T3KKmIWRgEc7IfXJsSRslKj3paYjcmHnoUph1+MGZUTofKvQsF91A/pWP6yE3koCjzOTTld02k7cyV5ZHvkebJ09GvtX/tQkD80LH0XCwKF7JHX08PksVGikZUKjAaGtIMnhVWKFZMmnyiuqr8i0/vnkv0/E1soQjxYThJe82qYdLV6Gn20e412zG21YaVSEEF/LYoY0wID7cLXt8N8saGhoJTeiqqEMoKLg6qIaZGFnZ+sQ77n0fXmyPy2EhcoQzyeTplet2uTdd57aX4dfQd4S28uYw1UXkKpLocZnQOV7RnY0MNYsUKhCZQVirSDF4FUgmGHF5AznFirD73P0AHm/fsbEq4nDzygTtBeIWwrdqB8Tn8gfh55cHBXZDNVd0OvL3MaaAQ67pTYHsR4sTOhzZOuiSaDZoCFgXuGII8zm1SqELzczx/lNPtuESInqDtfTrZeL2xgdvt8y3+7ftN5OHEvZRNWW0SPMEobMAXv7jHZn8TasXSh65Oqif+CH4AfgfmFho6EmpepSLsPz1LkbPqxEHUmDjvcTU5e5Gszdu183X/tfiJ6pHGzZa1WBkVIMQsc9gWz7+7ZUsV+sgOiZJQIikCDQYAigdyFSo4qmiGpubprzp3jqvnmD6clQzoZTZhdP2uldXl8hn+1fg16sXHjZf9WeEXXMbUctQaE8MvaNMZgs+CiNZXHiuiDzYCOgSSGbI4lmvSoZbrxzQDj7vgQD7wkSTkXTJVcQmq1dJ57xX4VfpJ5X3G+ZQdXr0U8MkUdbQdf8cTbRceBtAmkXZbmi/aEwoFjgtKG7Y51mhCpTLqizX3iOvgwDrUjIjjYSkdb72hnc116nH0MfbF4rnBCZcZWqkV0MrodHAhE8tncgsjdtXul2pdkjWqGIIOgg+WHzo8cm3epcLqBzRfikfdHDZQi0DZfSbFZR2e6cbd4C3ybe2x3nm9wZDlWZ0V/MhIewAgv8wbe6clztzWnrJk/j0CI5IREhV2JDZEZnCqq0bqOzc7h8/ZZDFshVTWtR9NXTWWxb692E3rDecJ1MG5IY2FV50RaMkseVwkg9Erfd8tBuTWpz5t1kXmKDodPhzmLq5JsnSercbvKzaThY/ZnCw0gtDPERbJVAmNObUd0t3eGd7RzY2zKYT5UKEQGMmUe3wkT9aLgKs1Du3erQJ4ElBGNnIm/iXeNp5QVn3CsT7w2zprh4/VyCqse7zGoQ09TamCUaoBx+XTldEVxOWr2X89SKkOBMV8eVwoI9g3iAc94vfqt/qDplgaQi4yRjBaQ/5YToQWubb3UzrLhc/V+CTgdCDBcQa1Qh12GZ11u2nHicXZus2fOXRVR7UHLMDYevgr89ofj99Dcv7qwBqQgmlWT2I/DjxWTspllo+Ovyb6jz+zhFvWLCLcbAi7hPtBNXFomZOJqXm6Abklr02RSWxFPcUDjL+odEQvt9w/lC9NtwrWzU6eonfyWgpNTk3CWvpwKpgyyZcCj0EnizfSdByka4Ss7PLpK7VZ4YBFniGrDasFnnGGFWMRMtj7KLnodUAvZ+KLmOtUnxea246p7ofaahJc+lyWaIaAAqX60PsLW0cvimfS0BpEYpiltOW5HPVN/XO9iW2arZt9jDl5nVS9Kvjx+LecceQu++T7ogNcHyEq6sq6YpUCf25uBmzKe2KNFrDa3VcQ603Hje/TSBfIWVCd7NvFDUE9AWH5e22E+YqhfLVr7UVNHiDoBLC4ciwuc+uDp3NkLy969vLL5qdejg6AXoJOi4afXrzW6qcbQ1DzkdPT5BE0V7yRoM0dAKku+U8NZC11/XR5b/FVETjJEFzhSKlAbhgtv+4frStwuzp/B/baarrWoeaX+pESnOay0s3i9OMmX1i3lh/QsBKUTeSI2MHI8z0b+TsJU8FdyWEZWflFDSs5AazVzKE0aZws2/C/tx95t0YfFcrt4s9etuKoxqkOs3bDYt/zAAcyO2EPmsvRrA/0R9h/qLHY4QkIESoBPj1IbUyJRtkz8RSo9hjJkJiUZLwvx/NfuUeHF1JTJFcCOuDizO7Crr4qxyLVBvMDEAs+12n7n9/S3AlUQZx2HKVk0ij3URAFK60x+TbhLqUdyQUc5aS8mJNcX3Aqd/X3w4+My2MHN4sTWvdS4/rVptRa397rrwMDIOdIK3d7oV/UTArIO0BoRJh0wqTh0P0tEC0ehRwtGWUKpPCo1Fyy6IWUWbwo4/h7yfeax2wvS1clNw6S++7tlu+K8ZsDSxfvMpdWM32Lq0fWAARUNNRiLIscrpTPnOWE+8kCIQSFAzDykN9QwkygjH84U5wnD/rfzGuk932zW6c7tyKXELsKawerCEcb0ymzRQtk64grsZ/b+AH8LlxX4Hlwngi41NEo4pjo4O/45BTdmMkgs3SRgHBQTRAk8/0n1uOvV4uHaGtSyztDKkcgDyCfJ8stM0BDWD90R5dbtGPePAPMJ+RJdG94iRSlgLgwyLTS3NKczCjH1LIwn+iB1GTgRhQih/8/2Ve5z5mbfYtmV1CHRH8+bzpbPBtLW1eTaCOEQ6MPv5fc0AHIIXxC8F1Me8iNvKKorjC0KLiIt3ypUJ6Ei6xxiFjoPqwfy/0n47PAV6vbjvt6S2pLX0dVb1TDWR9iM2+TfK+U169HxzPjv/wAHyg0aFL8Zjx5nIislySY3J3QmiSSJIYwdtRgrExsNtgYtALT5ffO37Y3oJ+Sk4B3eo9w/3PHcsN5s4Q3ldOl97v/zz/m9/5wFPgt6ECYVIRlNHJUe6h9DIKIfDh6XG1EYWhTSD94KpgVTABD7BPZV8SftmenF5r3kj+NB49LjPOVv51nq4O3m8Uv26/qi/0gEvQjeDIwQrBMnFu0X9Bg1GbMYcxeDFfUS3g9ZDIQIfQRkAFv8fvjs9MDxEO/v7Gvrjupa6s/q5euS7cXvbPJu9bT4Ifyc/wcDSgZLCfULNA75DzkR7RETEqsRvRBTD3oNRAvDCA4GOgNeAJP96vp6+FT2h/Qe8yPymvGE8eDxpvLO8031E/cR+Tf7cP2t/9kB5gPEBWUHwAjKCX8K3AriCpIK8wkMCecHkAYTBX8D3wFCALf+Rv36+976+PlM+d74rvi6+AD5efkf+uv60vvO/NL91/7U/78AlAFLAuECUwOeA8UDxwOoA2wDGQOyAj8CxgFMAdcAbQAQAMb/jv9r/1z/YP91/5f/xP/2/ygAVwB/AJoApQCeAIMAVAARALz/V//l/m3+8/18/RD9tPxt/EL8NvxN/In86/xy/Rz+5f7I/74AwQHGAscDuASQBUcG1AYvB1QHPQfpBlcGiAWCBEoD5wFkAM7+Lv2T+wv6ovhn92X2p/U29Rf1T/Xg9cf2AfiG+Uz7SP1p/6AB3QMNBh4I/gmcC+oM2g1jDn0OJA5YDRwMeAp1CCIGjgPOAPf9HftY+L/1Z/Nl8cvvqO4I7vLtau5x7//wDfON9Wz4l/v1/msC4gU8CV0MLQ+TEXoT0RSKFZ0VBRXGE+URbw90DAkJSAVOATj9Jfk49Y7xRu5860fpvOfq5tnmjucF6TfrFO6K8X711Plr/h8DzAdODIAQQBRvF/EZsRudHK0c3BsuGqwXaRR6EP0LEwfiAZH8SPcz8nrtQumv5d/i6eDi39Lfv+Cj4nLlGumA7YXyAfjN/boDnAlED4QUNBkrHUogdSKYI6gjoiKJIG0dYhmGFPwO7giKAgL8h/VO74bpYOQE4JfcNtr22OTYBNpP3LffI+R06YPvIPYb/TwETgsZEmYYBB7EIn8mFyl0KogqUSnUJiIjVR6RGAES1QpFA4z74/OJ7Lflo99/2nXWptMs0hTSYtMQ1graNN9q5XvsM/RX/KYE4wzMFCMcrCI0KI0ski8rMUcx4y8HLcYoPyOaHAoVyAwSBC77XvLn6Q7iENsl1X7QQM2Jy2jL4Mzqz3DUUtpk4XDpO/KA+/gEWg5cF7cfKSd3LWwy4TW4N983UzYdM1QuGSicIBUYxA7xBOn69/Br54/eqtb6z7fKCscTxeXEg8bjye/OgNVm3WbmO/Ca+jEFsQ/GGSEjeCuIMho4/jsVPks+nDwSOccz4SyUJB4bxxDfBbv6sO8U5TvbdNICyyTFCMHQvpK+UMABxIvJw9B22WDjNu6k+VMF6BAIHF0mlC9lN5A95EE9RIVEt0LgPhs5kjF9KCIezxLcBqX6ie7l4hbYcc5Cxsq/P7vFuHO4TrpJvknEIcyV1V/gLOyh+F0F/xEjHmopfDMJPMxCj0cqSodKoEiCREo+JjZULB0h2RTlB6f6gu3g4CLVpcq7wa66tLX3so6ygLTAuC6/nMfJ0WndIuqS91AF9RITIEYsLDdxQMlH+UzYT01QUU7ySU9DmjoUMA4k4xb6CL76newE31/SEcdzvdK1a7Bqreis7a5qsz+6OcMVzn/aGOh49i4FyhPaIe8uojqYRIJMH1JDVdJVxlMsTyZI6T67M/Am6xgYCuv61+tT3dHPucNsuTyxaasjqIanmKlNroG1/r59yqXXEuZV9fYEfxR1I2Mx3D1+SPRQ/FZlWhBb+VgrVMtMEENEN8Ep7ho/Cy37M+vO23jNn8Cqte6ssqYno2yiiKRtqfew7boEx9/UE+Qs9KsEExXjJKAz1kAdTB1VjVs6XwVg5V3qWDlRCkesOn0s6hxrDIL7r+p22lbLxb0tsuyoSaJ6np+dwJ/PpKesC7euwy7SHOL98k0EiBUmJqc1kEN1T/hYzV++Y6pkiGJmXWtV00ruPSEv2x6cDen7SupJ2WvJLLv7rjilMZ4fmiKZRJt3oJOoXLN/wJfPMeDL8d0D3RU8J3U3CEaDUoNcumPuZ/1o22aZYV5ZZ04JQaoxwCDODmH8BepJ2LnH1bgTrNahb5oalvqUGpdpnMKk5K96vR3NU96Y8F0DExYmKAs5PEhEVbxfUWfGa/ls3WqBZQ1dw1H3QxU0lSIBEOj83ul210DGw7Z4qceeBZdvkiuRQ5OpmDWhpqyjusLKhtxm788CKxbkKGc6LEq4V6BijmpEb5twiG4YaXZg41S2Rl82WSQyEX791OnO1gHF9rQspw+c9ZMgj7eNxI87lfGdpan9t4rIzNo37jMCJhZ1KYk71kvcWS1lcG1kcuBz2XFdbJRjw1dDSYU4CSZfEiD+5+lS1vvDb7Mwpa6ZQpExjKGKoIwhkvma5qaKtXfGKNkN7YsBBRbbKXM8Ok2wW2Fn9G8jdcZ2z3RLb2VmYVqaS4Q6oieFE8z+FeoC1i7DLrKFo6aX7o6iieyH2olfj1GYaqRPs4zEm9fq69oAyhUXKiI9WE4yXTxpGHKAd0l5ZXfgceVouVy6TVo8ISmkFIL/Xerb1ZvCM7EroviV+ox3h5qFdYf4jPqVNqJNscvCKdbR6iAAdRUpKpk9ME9jXr1q3HN5eWh7mXkZdBJryV6eTwQ+hSq4FT4Avure1UHCf7AjoaaUZ4uwha6DcoXtiveTSqCHrzjB1NTC6WL/CRUSKtg9wU9CX+FrPnUNeyF9anv0delsj2BEUYA/zCvAFgABNusJ1h7CEbBuoK6TN4pQhCmC04NCiUySq54ArtS/ndPB6J3+hhTTKd89DFDOX6tsPXY6fHJ+1nxvd2huB2KrUstA8iy5F8YBw+ta1jLC6K8KoBOTaYlXgwyBm4L4h/mQWp26rKK+iNLQ59b97xNvKa89ElAJYBht2Hb/fFt/2n2IeI5vMWPQU+NB9i2iGI0CZOzR1nzCBLD3n9SS/4jFgliAyoEQhwGQWZy3q6S9ltHw5g/9RBPmKEs91U/0XyptEXdcfdp/d34/eVhwCWSxVMdC1i54GVUDGO1s1/vCY7A2oO+S+Iicgg6AYYGMhmWPqZv4qty8ydAk5kj8iBI6KLI8VE+NX+Fs53ZSfe9/rH6RecZwj2RMVXRDjy86GhoE2+0p2K3DBbHDoGWTU4nbgi6AYYFshiePTZuAqku8I9Bt5YX7vRFsJ+g7kk7YXj5sWnbffJt/d35+edZwwmShVehDITDmGtsEre4G2Y/E6LGfoTWUEYqAg7eAyoGxhkaPRJtQqvO7pc/N5Mb65RCAJu06j03WXUJrbHUGfNx+2n0GeYhwoGStVSNEiTB5G5YFi+8C2qLFCbPIol2VL4uNhKqBnIJch8OPkJtoqta7U89G5A/6ARB2JcQ5T0yHXO9pHnTHerV91HwpeNtvKmRxVSNExzDzG0oGdPAa2+LGaLQ8pNuWrIz/hQWD1oNriJ+QMpzJqvS7K8/a42D5FA9QJG4400rvWkZocnIjeSZ8ZnvodtBuXWPqVOdD2DBRHPQGZvFM3E3IAbb4pa6YiI7Vh8iEeIXeidmRKZ11q068Mc+K47v4Hw4RI+42HEkPWUpmaHAcdzF6kXlCdWdtPGIZVG5DuzCTHJIHXfKX3eHJ1Lf8p9Oav5ANivCGf4e2i3GTdZ5rrOa8Zc9Y4yP4JQ28IUc1L0fpVv1jBG6zdNd3V3c6c6BrxWD+UrdCcDC2HCQIWvP33pvL3LlDqkidT5OljHuJ64nvjWeVF6Csrbu9yM9E45n3JwxRIHozDEWBVGFhSGvscRp1unTQcHxp+V6YUcNB9S+6HKcIWPRr4HrNGLzLrAqgNpaaj2mMuoyJkLiXDaI3r86+WtBQ4x73KAvUHooxuELZUXleN2jJbv1xu3EGbv5m2VzoT5FASy+dHBkJWPXw4XrPhL6SrxajcJnqkrWP6Y+Ck2OaVqQLsR/AHdF+47T2KQpIHXovNED0Tklb1GRNa4JuXG7faiZkZ1rvTSE/cC5eHHoJVfaE45nRH8GUsmmm+5ySll6TdpPYlmid8aYps67BENLO4132LQmtG00thD3WS9RXImF7Z61qompcZ/Zgo1etS3M9ZC39G8cJUPcl5dTT5MPOtQCq06COml+XXZeHmsKg3amOtXrDNNNA5Br2NQgHGgUrqzqBSB1UJV1WY4BmjmaAY3BdkFQkSYk7KCx5GwAKRfjP5ijW0MY8udat9aTanrabnJuOnnGkF606uIPFidTW5Oz1QwdYGKUorDf6RChQ4FjiXgBiJGJPX5hZL1FVRmI5uirRGiMKM/mC6JPY4MncvOmxW6l0o16gMKDponKonrAsu8jHDtaQ5dT1WQajFjEmizREQflLWFQkWjFdaF3LWnBVg01CQwA3HSkFGi8KGPo66hDbEc2owDO2A65WqFSlFKWUp8Gsb7RgvkfKxNdu5tP1eQXpFKsjSzFiPZNHkU8gVRVYXlj5VftQjkntP2Q0TycVGSQK8/r0657dX9CdxLK66LJ8rZOqQ6qNrFuxh7jWwf/Mqdlx5+v1pQQuExUh7y1aOf1CkErZT7NSCVPbUD1MVEVYPJAxUyUAGAAKwfuw7TrgyNO4yGC/Brjhshewu6/OsT2247yKxe7PvduY6Bv23QNzEXQefCouNTk+WEVWSg9Nb013SzlH1kCEOIUuKCPHFsMJgvxp7+DiRtf0zDnEV72BuNu1drVUt2K7gMF7yRTT/t3j6WX2IwO7D8ob9CbjMEw57j+aRCxHlEfRRfNBGjx3NEYr0SBqFWwJNP0g8Y3l1tpN0TnJ18JXvtq7cLsavcjAW8amzW3Wa+BR68r2eQIIDhoZWyN9LDs0WTqrPhJBfUHtP288IjcxMNQnTh7qE/oI1f3Q8j/odt6+1VrOgchexA/Co8Ebw2nGb8sG0vfZBOPj7Ej34AFbDGcWth8BKAovnDSOOMQ6LzvPObI28jG2KzIkoRtHEm8IZf549PPqIeJE2pnTUM6QynXIC8hTyUDMutCa1rHdxeWX7uH3WgG4CrMTBhxyI78pvS5IMkg0sDR+M8EwjiwKJ2IgyxiCEMgH4/4W9qbt1OXb3u/YPtTo0AXPoc68z0rSNtZd25bhruht8JX45gAgCQIRURjVHl0kwSjgK6QtBC7/LJ8q+yYwImcczxWcDgcHTf+o91Xwiul941reRtpg17vVYdVR1oLY39tM4KXlvetk8mT5hgCUB1YOmhQvGuserSJZJd4mMidWJlMkPSEtHUUYrxKWDCsGov8t+f3yQu0n6NPjZODz3ZDcRNwM3eHeseFk5drp7+559E36OwAXBrML4xCCFW0Zhxy7HvsfPyCJH+IdWBsDGP8TbA9xCjUF4/+i+pz19vDV7Fbpkeab5IDjRePo42Plp+ef6jHuQfKs9k/7BQCqBBkJMg3UEOcTVBYLGAEZMhmfGFAXUhW3EpcPCgwvCCYEDQAG/C/4pfSC8d3uyexT64PqXerg6gPsvO3676nysvX8+Gz85v9OA40GiAkpDF8OGRBOEfYRDxKcEaQQMA9ODRELiwjTBf0CIgBY/bT6Sfgq9mX0BfMT8pTxiPHs8bvy6/Nw9Tz3Pvlm+6D93P8GAhAE6QWFB9kI3QmKCuAK3gqHCuIJ9QjMB3IG8gRcA7wBIQCX/ij94fvJ+uf5QfnY+K34vvgI+YX5L/r9+uf74/zo/e3+6P/SAKQBWQLsAloDowPGA8YDpANmAxEDqQI1ArwBQgHOAGQACQDA/4r/af9b/2H/d/+b/8j/+v8sAFsAgQCbAKUAnQCAAE8ACgC0/07/3P5j/un9c/0I/a38afxA/Df8UfyQ/PX8f/0s/vf+3P/TANYB3ALcA8sEoQVUBt0GNQdUBzkH3wZIBnUFagQuA8gBQwCr/gv9cvvr+Yb4UPdT9pv1MPUY9Vj18PXe9h/4qvl1+3T9mP/QAQ0EOwZICCMKuwsCDeoNaQ56DhcOQg39C1AKRgjtBVUDkgC6/eH6H/iK9TnzP/Gu75buAO727Xvuje8n8T/zx/Wt+N37Pv+2AisGgQmdDGQPwBGcE+YUkhWWFfEUpBO2ETQPLwy8CPUE9wDg/ND45vRD8QXuR+sg6aPn4ebg5qXnLelu61nu2vHX9TT6z/6DAy8IqwzVEIoUqxceGs0bpxykHMAbABpuFxsUIBCYC6cGcQEf/Nn2yvEa7e/oa+Ws4srg19/c397g1uK45XHp5u328nv4S/44BBcKuA/uFJAZdh2CIJcipCOdI38iUSAfHQIZFRR/DmgI/wF3+//0ze4S6frjsd9Z3BDa6djw2CnajdwM4I3k7+kL8LL2sv3UBOMLpRLlGHIeHiPCJkApgip7KigpkCbGIuMdDBhtETcKoQLn+kPz8ust5SzfHtos1nnTHNIi0o7TWNZt2q/f+eUa7d30B/1YBZANbxW3HCwjnCjaLMMvPDE4MbQvuSxcKLsiARxgFBIMVQNw+qXxOelw4YbatdQq0A3Nd8t3yxLNPNDh1N7aB+Im6v3ySvzCBR4PFRhgILsn7i3FMhg2zDfPNx82xjLdLYUn8B9VF/YNHAQS+ibwpubc3Q7We89Yys/G/sT2xLrGP8ptzxzWHN4x5xTxe/sTBo0QlRrdIxwsDjN+OD08LD45PmI8sjhDMz0s1CNJGuMP8gTN+cjuOeR12sfRdcq6xMbAuL6kvozAZsQVym/RPto/5CXvnPpMBtsR7hwuJ0ow+jf/PSpCV0RyRHlCeD6LON4wqyc4HdUR2AWh+Yvt9eE817PNpsVWv/W6qbiFuI66tr7fxNvMb9ZS4THtr/ltBggTHR9OKkM0rDxGQ9xHSEp0Sl5IEUSuPWQ1cSshIMoTzAaM+W7s29801NbJEsEuumO117KhssS0NLnPv2XItNJv3jvrtfh2BhMUIiE8LQM4IUFNSE5N+k86UAtOekmpQso5IS//IsEVzAeO+XTr7N1g0TLGvLxItROwRq37rDWv5bPruhDEEM+X20XpsPdoBv0U/CL3L4k7VkURTXtSaFW/VXxTrU52Rw0+uDLQJbUX1win+ZvqKNzAzsvCqLiosAqr/KeYp+Opz642tuG/hsvO2FHnofZFBsUVqSR8MtI+SUmOUV9Xjlr/WqxYplMSTChCMzaQKKYZ6gnV+ePpkdpWzKK/2LRQrEum/KJ9otak9am1sdu7G8gX1mPlifUMBmwWKibLNNtB9UzAVfdbZ1/0X5ddYFh3UBZGjTk8K5EbBQsY+k3pJ9kjyrm8ULFEqNuhSp6vnRCgXKVsrQS408R2033jbPS/BfIWfifhNqNEWVClWT5g8GOaZDdi11yiVNVJxDzSLXMdJQxu+tfo6tcqyBK6Ea6HpL2d7JkxmZabCKFgqV+0sMHt0KDhSvNgBVcXpCi+OChHclM5XTJkJGjuaIlmBmGOWGBN0z9OMEkfSA3W+oLo29Zpxq+3HqsbofSZ45UIlWyX/pyVpe+wtb5/ztHfJvLvBJwXnClhOmlJPlZ7YM9nAGzsbIpq6mQ3XLRQt0KtMhIhbQ5P+03o+dXjxJG1eagEnoSWM5I3kZaTQpkOormt6LsvzBDeAfFuBMMXZyrKO2RLvFhnYxNrgm+QcDRuf2ibX8xTbUXtNMoikQ/Y+zboRdWXw7izJKZDm26T4I7AjRiQ1pXPnr+qSrkAymHc3u/fA8oXBSv4PBlN6Vr8ZfptpXLXc4ZxwWu1YqZW8kcJN28kshBu/D3ovdSGwieyHqTbmLWQ7YupivSMvpLbmwWo37b2x8bav+5CA7UXdivsPYdOxlw4aIRwaXW/dnt0rm6CZT9ZQ0oBOf8lzxEQ/WDoYtSwwd2wa6LMlluOWonyhy2K/Y81mY6lqbQSxkLZpe2bAoQXuyulPq5PUF4aaq5yyndFeRJ3QnEAaJNbXEzQOnYn5RK9/Z/oMtQUwdqvCqEYlWGMK4eehceHl43gll2jrLJYxNfXk+zqATcX1iskP41QiF+ga3d0x3lme0h5enMraqBdPE51PNQo8hNy/vjoLdSywB6v+5+/k8qKYYWvg8OFjIvflHSh6rDJwofWi+sxAdIWxitqPyVRbWDKbN11XnsifRp7VnUBbGRf4E/tPRYq9RQu/2rpUdSJwKquQJ/DkpWJ/YMngiOE4Yk1k9efZq9pwVXVj+pyAFUWjSt3P3ZR/2CYbeB2jnx2fod80XaAbdtgRVE1Pzgr6hXw//LpntSYwHyu154kksSIAYMIgemClYjikYaeIa45wELUoemw/8EVLStMP4FRPmEKboB3V31hf4597HembgRiaVJMQDos0BazAJDqEdXewJSuwZ7gkVaIbIJRgBaCrIfpkIWdHq08v1LTw+jq/hoVpyrqPkZRK2Efbrx3t33jfy1+pHhyb95iSlMvQRotpRd5AUHrqtVawfGu/J75kUyIQIIEgKqBJYdLkNScX6xzvoTS9+ck/l8U/SlUPsdQyGDYbZR3r336f2R++Hjhb2Zj51PdQdQtaBg+AgXsZtYLwpGviJ9tkqWIfIIhgKiBA4cJkHWc5Kvgvd3RP+dg/ZQTLymKPQZQFGA3bQl3P32ofzJ+6Hj0b5xjP1RUQmguFRkBA9jsRNfuwnOwZKA7k2GJIIOogA6CRYclkGmcsKuFvV3RnOaf/LkSQSiOPARPEl88bB12aHztfph9dHiqb35jT1STQtQurBm/A7ntQtgCxJaxjaFjlH6KKoSZgd2C7IefkLGcxKtjvQXREebk+9IRNCdjO8JNwl3patB0KnvIfZV8m3cCbwxjF1SYQhcvKxp3BKbuXdlExfayAqPhlfuLm4XxghOE94h2kU2dIKx8vdjQn+Uw++AQCiYKOkJMKFw/aSNzh3k7fCp7Xnb7bUVillNiQi4vkBonBZ3vldq0xpO0wKS1l9aNb4eyhLGFZoqrkj6exazPvdfQSOWE+uUPxiSFOIhKRVpBZxlxgXdIell5vXSYbCphzVLxQRkv2RrOBZzw5ttNyGq2x6bcmQ6Qp4nYhraHOYw9lISftK1fvgLRDeXk+eMOaSPXNpVIHFjyZLRuGXXwdyN3uXLXarpfuVFDQdcuBRtoBqHxTt0Pyni4E6lUnJ+SPoxiiR6KbY4slh6h7K4rv1vR8ORP+dsN9iECNWxGrlVSYvdrUnI1dYl0VHC6aPZdXVBZQGcuFBv1Bqnyy972y7u6oasan4iVNI9NjOmMApF2mAujbbAzwOPR8eTJ+NEMbyAJMxBEAFNmX+NoL28Zco1xkG1DZt9bt04xP8gtAxt0B7TzW+AAzjC9bq4rosaYhZKYjxWQ9ZMam0ulN7J5wZnSEuVT+McL1x7vMIRBFFAxXH1lsmugbjJubmpyY3ZZyUzNPfos0RriB7/0++Eq0NS/eLGEpVScLpY/k56TRZcXnt2nSbT7wn/TVOXu970KLx22Lso+7ky2WMdh3mfMantq8WZLYLxWk0otPPwrfxo+CMf1qeNx0qPCu7QhqTCgK5o/l4KX75ppob6qo7a6xJXUt+Wc97YJextiLOY7kEn4VMZdt2OgZmtmHGPOXLRTFkhQOs8qChqGCMz2YuXS1JvFM7j/rFakep6Vm76b754Qpe6tQrm0xtrVPeZd97QIvRn0Kdo4/kX7UHxZQl8hYgVi8V7/WF5QVEU5OHIpcxm6CMr3JedL17nI3bsascOoFqM9oE6gRKMHqWmxJrzpyE/X5eY097kH+BdwJ6w1PULDTO5UgVpRXUxdc1rgVL5MT0LmNeUnuRjZCMH47ujZ2fjLtb9utXGt+6czpS6l6adNrS61TL9Yy/PYsecg98YGLBbaJF0yTz5USCBQeVU2WEVYp1V0UNVICD9bMyom3BfhCK/5uup43FXPt8P2uV2yJK1zqluq26zesTm5s8IAzsXaoOgk994FXhQzIvIuOjqzQxdLLlDTUvNSkFC/S6dEgjuYMEAk2xbRCJL6iewl383S38evvoK3jrL4r9CvFrK2tom9WMbe0Mbcs+lA9wIFkBKAH24rADbkPthFpkouTVxNM0vFRjdAvzefLSkithWpCGj7V+7e4VzWKcyTw9u8M7i9tYi1lbfRuxnCOcrx0/Pe6ep09zMEwxDCHNUnpjHrOWZA5kRKR4RHk0WJQYg7wTNyKuYfbxRoCC/8IvCf5P7ZkdCfyGTCDr69u3+7Vb0twebGU84310zhQuzC93ID+g7+GSokMS3ONMc68T4uQW9BtT8PPJ02iy8TJ3gdBRMNCOj86fFm57HdE9XOzRfIG8T0wbDBUMPExu3Lo9Kv2s/jve0p+MICNw02F3IgpCiQLwA1zjjeOiM7njlcNnsxIiuEI+AaeRGZB4/9qPMv6m/hqtka0/DNU8pbyBbIgsmRzCrRJtdU3nvmWu+r+CMCfAtsFK4cBCQ3KhcvgjJgNKY0UzN1MCUshybIHyAYyw8LByX+XfX47DblUd5/2OnTsdDuzqrO5M+R0pjW2Nsm4k7pGPFG+ZcBzAmlEeUYVh/HJBApEyy6Lfwt2SxeKp8mviHiGzoV/Q1iBqj+CPe+7wHpBuP43f3ZMden1WjVdNa+2DTctuAg5kbs9vL8+R4BKAjiDhgVnBpFH/EihSXxJisnNiYcJO8gzBzUFzESDwygBRf/pfh98s7sw+eA4ybgy91/3ErcKd0U3/jhvOVB6mHv8/TL+rkAkQYmDEwR3RW3Gb8c3x4KIDogbx+0HRkbtBeiEwUPAwrEBHL/NPo09ZnwhOwT6V/me+Ry40rjAOSM5eDn5eqE7pzyDve0+2kACwV0CYQNHBEhFIAWJxgMGS0ZihgsFyAVehJPD7sL2wfOA7f/svvg9130RPGr7qPsO+t56mLq8uoi7OftL/Dm8vb1RPm2/C8AlgPPBsQJXQyJDjgQYRH9EQsSjRGJEAsPIg3eClMIlwXAAub/Hv1++hn4APZD9O3yBPKP8Yzx+fHR8gj0lPVl92v5lfvQ/QoAMwI5BA4GpAfyCO4JlQrjCtoKfQrRCd8IsQdTBtEEOgOaAQAAd/4L/cj7tPrX+Tb50vis+ML4EPmS+T/6D/v7+/n8/v0C//3/5AC1AWcC9wJiA6cDxwPEA6ADYAMJA6ACKwKyATgBxQBcAAIAu/+H/2f/W/9i/3n/nv/M//7/MABeAIQAnQClAJsAfQBKAAQArP9E/9L+Wf7f/Wn9//ym/GT8Pvw4/FX8l/z//Iz9O/4J//D/6ADsAfIC8APeBLEFYgbnBjkHVAc0B9UGOAZhBVEEEQOpASIAif7p/FD7zPlr+Dj3QfaP9Sv1GvVh9QD29vY9+M75nvug/cf/AAI8BGgGcghICtoLGQ35DW8Odg4KDisN3QsoChcIuAUcA1YAff2l+ub3VvUL8xnxku+E7vrt/O2M7qrvT/Fx8wH27/gk/Ij/AAN0BsYJ2wybD+0RvRP7FJkVjxXcFIEThhH4DukLbgiiBKAAifx6+Jb0+vDF7RPr+eiM59nm6ea/51bppeue7iryMfaU+jP/6AORCAgNKRHTFOYXShrnG7AcmhyjG9EZLhfME8QPMgs6BgABrvtr9mLxvOyd6Cjle+Kt4M7f6N/+4AvjAObJ6UzuZ/P0+Mn+twSSCiwQVxXrGcAduCC4Iq4jkCNbIhYg0BygGKQTAQ7iB3QB6/p49E7unuiX42DfHtzs2d7Y/9hR2s3cYuD35GvqlPBF90r+bQV3DDATYxnfHnYjAydoKY4qayr9KEsmaCJvHYYX2BCYCf0BQvqj8lvrpeS23r7Z5tVP0w/SM9K906PW0tos4Inmuu2I9bj9CQY8DhEWSR2rIwMpJi3wL0oxJjGDL2ks8Cc2ImYbtRNaC5gCs/nt8Izo0+D/2UfU2c/bzGfListGzZHQVNVs26vi3OrA8xP9jAbjD84YBiFMKGMuGzNNNt03uzfnNWwyYy3vJkEfkxYoDUYDPPlW7+LlK9111f/O/MmXxuzECsX0xp7K7c+71tXe/efu8Vz89QZoEWQbmCS9LJIz3zh4PD8+JT4lPE84vDKWKxMjchn+DgYE4Pjh7WDjsNkc0evJVMSHwKO+ub7MwM7Eosoe0gnbIOUV8JX7RQfNEtId/Cf9MIs4az5sQm5EXUQ3Qgs+9zcoMNgmTRzaENUEnPiN7AfhZNb4zA7F5b6vupG4nLjSuia/eMWZzUzXR+I37r76fAcQFBYgMCsGNUs9vEMlSGJKXkoXSJ1DDz2fNIwqIh+6ErIFcfhb69jeSdMKyWzAs7kWtbuyt7INtay5dMAxyaLTd99V7Nr5mwcxFS8iMS7XOM5BzkieTRdQJFDBTf5I/0H3OCsu7iGcFJ0GXvhM6tXcYtBXxQm8w7S/ryetEa2Br2W0mrvpxA3Qsdxz6un4ogcvFhwk/TBtPBBGnE3SUolVqVUuUypOwkYtPbMxrSR+FpQHY/hf6f7asc3gwee3GLCvqtmnr6czqlWv77bHwJPM+dmS6O33kgcLF9wlkzPEPw9KI1K9V7Ja6FpbWB1TVEs7QR81XSddGJUIfviU6FXZNsunvgu0tqvppdWilKIopYGqd7LNvDbJUte15uj2bAfEF28n8jXcQshNX1ZcXI9f3l9DXdFXsU8fRWw4+ik3Gp0Jr/js59nX9Miwu3ewoKdzoSCexZ1koO2lNq4BufrFwNTf5Nz1MQdbGNMoGDiyRThRTVqqYBxkhWThYUNc01PTSJY7gSwJHK0K9Phm54zW68b8uC2t2qNOnb6ZRpnsm5+hMqpltePCRNIS48r04gbRGAkqAzpFSFxU612kZFRo2mgyZm5guVdVTJk+8C7RHcELTPkB527VHcWMti+qZqB/mbGVG5XEl5mdbab/sfS/489Q4bTzgQYlGRArtDuSSjNXNWFIaDRs2Wwxak5kXFugT3NBQzGMH9cMt/m95n7UicNitH+nRp0Ilv6RSJHvk9+Z7KLQrjC9n82c353yDgZZGegrKj2ZTLtZKWSSa7pvf3Dbbd9nul6xUiBEeDM4Ie8NMvqZ5r3TMcJ/siClfprskqeO0Y1xkHaWsp/dq5u6esv43YbxiwVtGZIsZD5YTvFbxmZ/buFyyHMscR9r0GGFVZ1GizXTIgUPvPqU5irTFcHjsBKjDpgtkK+Lt4pOjWCTwpwpqTe4eMln3HHw+gRjGQ8tYj/QT9ddCWkPcal1snYidApummQZWOdIezdZJBgQVPut5sTSNcCPr1ah+JXOjRiJ/oeHiqGQH5q3pgi2nMfs2mHvXAQ8GV4tJUD/UGlf8Wo+cw54Onm5dp1wFGdpWvtKQznJJSUR9/vj5ovSkL+Eru2fPZTPi+aGqIUgiDuOzZeJpBC06MWI2VfuswP4GIEtrEDmUadgfWwLdQ56XnvveNVyPmlyXNdM4johJysSpfw0537SJr/Crdme35IzihiFt4MahjGMzZWkolKyXsQ92FXtAQOaGHgt+UCFUpJhrW12dql7HH3DerF0E2s0XndOVjxdKCgTW/2f55zS975HrRie3pH6iLGDLIJ5hIWKI5QIodCwAcMP117sRwIiGEUtC0HbUipigG59d9x8cn4yfC12kmyqX9pPmz19KRkUGP4i6OTSAb8UraqdOpEliLGCCoE9gzmJ0JK4n42v1MH/1XPriAGTF+os5UDqUm1i9W4heKh9YH87fUl3uG3TYP1QsT58Kv0U2v696FPTQ78prZCd85CzhxqCUYBogk6I1pG2noqu18AQ1ZfqxQDuFmYsh0CzUl5iDm9geAt+5H/cfQN4hW6tYd9RlD9bK9EVnv9s6erTvb+DrcidCZGnh+uBAYD6gcWHNpEDnsmtDsBD1MvpAAA=\" type=\"audio/wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\n## Video\n\nMore exotic objects can also be displayed, as long as their representation supports the IPython display protocol.  For example, videos hosted externally on YouTube are easy to load:\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('sjfsUzECqK0')\n```\n\n\n\n\n\n\n\n\n\n\nUsing the nascent video capabilities of modern browsers, you may also be able to display local\nvideos.  At the moment this doesn't work very well in all browsers, so it may or may not work for you;\nwe will continue testing this and looking for ways to make it more robust.  \n\nThe following cell loads a local file called  `animation.m4v`, encodes the raw video as base64 for http\ntransport, and uses the HTML5 video tag to load it. On Chrome 15 it works correctly, displaying a control bar at the bottom with a play/pause button and a location slider.\n\n\n```python\nfrom IPython.display import HTML\nfrom base64 import b64encode\nvideo = open(\"../images/animation.m4v\", \"rb\").read()\nvideo_encoded = b64encode(video).decode('ascii')\nvideo_tag = '<video controls alt=\"test\" src=\"data:video/x-m4v;base64,{0}\">'.format(video_encoded)\nHTML(data=video_tag)\n```\n\n\n\n\n<video controls alt=\"test\" src=\"data:video/x-m4v;base64,AAAAHGZ0eXBNNFYgAAACAGlzb21pc28yYXZjMQAAAAhmcmVlAAAqiW1kYXQAAAKMBgX//4jcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTE4IC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAxMSAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTMgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MzoweDExMyBtZT1oZXggc3VibWU9NyBwc3k9MSBwc3lfcmQ9MS4wMDowLjAwIG1peGVkX3JlZj0xIG1lX3JhbmdlPTE2IGNocm9tYV9tZT0xIHRyZWxsaXM9MSA4eDhkY3Q9MSBjcW09MCBkZWFkem9uZT0yMSwxMSBmYXN0X3Bza2lwPTEgY2hyb21hX3FwX29mZnNldD0tMiB0aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MyBiX3B5cmFtaWQ9MiBiX2FkYXB0PTEgYl9iaWFzPTAgZGlyZWN0PTEgd2VpZ2h0Yj0xIG9wZW5fZ29wPTAgd2VpZ2h0cD0yIGtleWludD0yNTAga2V5aW50X21pbj0yNSBzY2VuZWN1dD00MCBpbnRyYV9yZWZyZXNoPTAgcmNfbG9va2FoZWFkPTQwIHJjPWNyZiBtYnRyZWU9MSBjcmY9MjMuMCBxY29tcD0wLjYwIHFwbWluPTAgcXBtYXg9NjkgcXBzdGVwPTQgaXBfcmF0aW89MS40MCBhcT0xOjEuMDAAgAAACqVliIQAV/0TAAI/3gU2tIW7KawwaCmQGTGHKmuYAAADACBcshU+yICkgAA14AHowiEeT6ei7v7h3Hu0i2fpUBLGBIkbCMP3Vfz+9BVGCDXnw9Uv5o3iN030tb7eq6rsEEhHs2azbdTiE9Csz5Zm6SiUWRdmB43hbD5i6syATuODUJd7LM3d9cbFpc7zFlu5y3vUmNGd6urpvKKT9iyleIyTuR1sVS431DhevGfkUllVeIznYUe2USoMW1tufETjyRdmGldN6eNlhAOsGAH4z+HkrwKecPPU7Q5T4gDAIxj9hW84jVExMTSTHxkPTq1I4OotgUxURCGTsw60k/ezPNmNg38j1bqaGmPcruDKEIBDsK5qEytFB90Q68s0h2wmlf2KXd5bleBefiK+/p47ZsyUO4IdlW25rRy+HLjt6wQXfYee3IkiQOoOK+U7u/lxcl78zfxwIoEMjUUSKNZjkp8clnmecDDJ3Kz+viF7bPklk7N6QRyizAKPIIpnNJUuMWQmqeL2Or6cr4D0/0tOym+4tficxmhuEONKUtO2pPn3hRjMllkd12tXp70fLTfxy0dwB70ML9iLEcItHb7zVupHlP5RxdvecpREw+OsIPr9KWilIesNE19jgIbT+TkiRBjOoKvUuwcQnKg7fOTHVoLvnKuAfea+oujEdm1Rwd2tEOnkF+ZC11WaNQsiNR/eJ9EnUXjXDYGfhB+Oe7qj8nYTT+eOXg1cuJNgLXEs4vOheWEjQOqfIWMQc3DmTof5s0ksBmUQ3PQ+UHPxZSnmOEZB+j6xT3wbm7HGzDjWtSg1SjTxd1EiJ8xA4SIxxR8WIKLg+TwFxJNS7Laxq7Uglu3AkXe82P1JCdJX5PsbFbxuDbuJgakzRcTwMLLSKCiizS/eCW0uJed/lev9yb80kKlVET4S219cn/zhkpeDV83cHYOr+sJQKDRk/Wh2c7fsuxfxaEH/6reSmvFDsAnXAyPXliJ3G4VG3OkEM5K5WyGGrBizZbTrdGsBnzj5VSGGOJdCKuRrUluw/8es2vYRPs9BcTqAqvHk9M52SSIf+1T6L53EZP8VbtXB+G29CMW4xVCK/B/YDjaNmqMwJ61dapugjnWJfqeXlGGa3Ch3aA7gi30T8PucNRBjLK3lF67ZDDvkWXRQXd+VMnKWHkBbCkQ/F/fMuNpHO3C00Y2pljna1qImBhVMvPe0F7Qx7G/YyxLRzhyUU8e23HGzp0agtNJRbydbrPV+TqJMSifJMNcZIf8wkdnC3/xdpcXnLf2Ye3Kbd0o7utciTG+q5h6WTEk+PaNbXLLA0YyZ2VnLTcyV1QTS76aNCbV9Q1/OQ7QU81Gg0hPa9aSiscGary6jLVwDQaik4zLsi7jPqgPVdup7pwx7uJDqRCVcVi5QoZFp/GHdex5sJTF69A6sja69/NLkFIWNSIeRcuGahXpF+wZeYIrqJv975s1TKYKAvp1WtzgtgWNkcbzCtROqf8rPtlAIxkX8GLcEo9zfExyfimeXQ64qfFxEy0IMy2Hsxau9fSMqUnIjntuVVjCQtBL+94gx1RZLndE6wROVTq/wHwHrQzo9QL9cpPqPFJjiZ/NGZIFuudS+wsBFe6Hu8Oitf5zToLqLdtU4Smwh4ne3JsiT9lOzN+4PPw3VSx9l5FppVwdKUWELw1dYpCOppyVWlJ3YQ8H4FQQM8EcYMG9N3Bxu79y1J1ikuvuhMmLQlehLTbguhbix74hd1VIQC8EjHmOZSSWbssulYwPbr6FF49tifk6PymJvulR9/u+2585HkRfbxveGeWCz0ix1pIVfaNpESKmtLy/0mcbMg9hYDz2werz9oe0lT2BiMV6uAin6RaQcT8Vk9MPctfwae+gkvtnZA/sOBk8MbpylaHqc0KIVHhhLFMNnkOFiucjtGo/JWTa/F6g8wWeow5ZuIJUORaYHWqegZbTgM9dCsYYsfZGjjVMuSlDIvpYvIvFFooGPC7Ye2Jfawmq4Ut7EL/nv/dyAd2HRc5msmUhzeu/XpX3rVlzRmf9/Qan8Dbve3QfW1Ym0o5J/KAc3z1VBho7JBr5PgCL68RiD9jZHN0VvsT4gzsEjNlW3D91Uy4RduaodBFoNTzXwlfUYULBzdiTbH75l/UmVMC4TKeTWhNzw2UezaqeGd8at3WSY7W/VR3+hvZHDpkIjgKuNNH0DsCRa/Kk56XQoHIyvvUH/eNekNvziReqS4qgLnXUT4BRGt2BOtCifI6+X/DGHUOmWlX7TN5b4pw5U7jwfwshtbhGZM49T8JMk15Mzrc7tM6J11TYxb5R3mQhZ8TZumJ0bMJXPM69HFyihr5dJSEJMycxJVUh6NTQALUOoRTHIOwE+FpWI6feTv1SiZ0YpYe5DbkYJJbN7zAHbAKw25XvqR2mAjQmOlsfX/tK8DPjP/8h5/xgAF4EUbj1tOnQCBQL8jk9vHtfsXncsprww4Z+P/Z/UrKifuFyEpBWN8kLpF7yywE2iYdDruV9+/qKR8rC9ozNKyqQNIwtxrzYkWpE5t8K7gG4JFnrHona/Rp8dOX6VW41+jb5LB1LEtE8MwjLp3RCUOq/+6yLzaOEgBTqzvEjDeFpg/u9DMHMr4/2TOchfjg7dl+uQ6Gsx+4Ia9W7vivG95027p25eKL0nHvx/OqmAQEZYJL/JO58lOj0zPdJxrQ5dZksjMISzVZNn7DsxqE3zgBBuNzk50R8lTK3U8P12QiOAQYSTeGlYlkvfeofrfO1AitEj02m9aUkxTFd1ZZJoLQT2d3zEU5PmE4lxMVfL5ttNnIbqfcIU2RJKNWqdw77xfjfrNc/eNpRKPZ/6z50LzBprgjzBHRfKgSWWkDxHrX0aTbgwQFwd51+PoUWH4DkQg26uGslF5Hn3hB58+fkeLTosTANOIBNAeFZtTc4PIaLHw759zae7scY55xcTabzlilYIftst2RZ6ntsRC3zFxduCKvL6wLfYT+TiIWJn5P7sTwZwXuSzXY+9Q3xMZ5o4Xcpz6vD9FtTjzS69iefEYt4pXiDrZUo4ePGiLeoIFIwYB/v6GXdmG5VLLk+eKbOc9AmsX2zmvqtcvDRGQbzugXbH/kTH/lkNPBTmqN3ZJODUEXVohPEJ6th0xna0EVleB73Q3eNvaVUvhlJbjs3D/T17FRCebN7AOXvzzbLE/I5kNfEmJcv4dxtIeo2uQ/z9ohSpiZzbDj1u40nJRyJxUK60wEv0nA9f/NuJ6/PEyU0bkK16z2KH12k3Lc4+1f5fawIzkK2qJRB4wnj8VHhUW9mbJhs9vgfFmU3xrXSShY67Ygb+gYNPxxtn4K/9eTSwIA9fv/nR33lA2lZoXALRUTmOZIl3R0gAM5h6oX1y1thIyqViBK95VZc8Pvy7G3O90M9S4zkpyFQ36jrMazvMveMA4d39fvoaC7p90quiJfjI4yrl+ECVkCJL5MxRSa+iVcIL7Xbl0jVaGhZIcMYmcGOBbLzhJgloM1x1zFnnj3ggJRFAM8yNnXxhavk+mA18JC+y3lqGsp6vPReRxGlGHMou17L4It070LzkoeCzarpv8Apw59smdS5KN9qVN1WgeL7OSN8BHg94ubCvS7DW6H3/PbtRB62jFLsBhUV5YqCIbIN5VZ81AAACpUGaIWxFfwAru8x8uT3FuOjrAeSWXmAWqq9jCNGE+N5AOv//9//xjk4uBAcADN96c97AVGmzRtnWwPsgcCbLrVdQJgbKp4QSmPwQnVhv0hXyBjeFWWlcvx70urEN3FK6/lvk2tQeZgbtlbzXluvTfnSj/Ctz7vZ+O1FjhDzzdpL7uLzewzCIW5VWLAEKUVuS2J6wNk6MR7UblcEd4EtOY+R4/qJgfojCsfRvA0oC5dc41Vd0erZbSkrmPTjLCn815bxlchUJMS8gQD5hJNwoKHvNLNwn7XKuTtYIhH2wVNZvDWgzCjlPeQajnrcMsb6bZYJvNJU8HuGHvm50r7VG8qifEwmuyegAZXojh5Ul5VvjDW7kSAZyw8a7I6mHY3FZHd+OA3V4JZMbNliI3Tj1L6+MKTmilVialmyZagRtEMeKRdtxUPd3vVEtrOBVIVYWdgAGA7HmZiHQUQNxLkWxbLyWVlrh5EM0Do2NdbclHxxArz90d+MSVeUOIXQ/4V9quq8C8qVflo1gPtPMkjO2/UrdOYqhY404ReObOu/fdp4hAEDq6jhy64vOeT7XUK/Onq0rXTldtA6kvgQaJg+mgYSR9hfXtMbOUSLgLj/RmBSO8aAMHuJJZqf1tCM5pZ9eYUsrHmy+/z2NGalon0//uF6+33bQzT/RLRfBbYTjy9QrJqHLlw46lggWPGkHuPKSqk/CB7U4pNPXUbR0DdcJy9Db00wCzVzxVc6h7jfCFgiL2Y0HVqd6bgIaVUqn/gJCEyCDVplnzebv0gg3XwMJAGu639lHu7rEvxTp1smIYjWp9R5L4SspVvS07Nb+Smk1FgsMp1K3EMUT8X2Fty4VG54/Ec6bE8tNVw4/QV1VzBw7Px2/2eEhhUS+FMfbHAlD28x00jRgAAACW0GaQjwhkymEVwArOUkEOhoFqiELtH8wgecFLiUq6WqmwAP7iGEwbYzfnHacfqUNXAfD+CGR2ap0lAHL25ipuYtd5j2O0PU/MpaWPG/n2y5OkfTzaOpotaR5tWjN55B2XblVVqsFfBC/mvsiPvCBWUHFChacdY5whj5mP5rqQ0dqLJCsWjrs4TWnIbL2V/Iwfj3hwI35jfo1JkTOeR+8GhOdma9rgiKWafCbQyhYMTDmVdvhND60Flm97EDSTjF0OC+0gD9b8Yn4tNeHipCa/aWyt0n79bMmjfcjntBCPjrcB5ecRTpfGHbEHy1IRj2cjkGXKC+VYoYJXBp4rd4cMd8ygLCk5nBSd8/cTaKNRjdBscOeTXG6QEjSxj9/2pVwx9DMRVtWQR0BSaAcQcZ8W2KPSaeRC4QwmNMu2xx25CSyrDiq2rFSK/JJtmvoIjAKq0ciEXoOgw+Ke+Ylb7ULKCS3k1p/613UNRp450uSq5b7CAHo7S0b7fBMLfNmwSjRYEhLlo0HUaRe/I+IX2Z6XdZH9Hty/399ZA1PwZGC6EfvUJIf7CBeaxv7cu6IT2/s0zPRGthpvXpYw6A7P4Wwz5C4V98KnIUNUanadqabKP6eXWhvbvcQHxAjiOOiKZgXZplZW2g+B2NNyJSLiR+g48DqvWR6t9S2aGfFjdOW1Gi6oTtZ1d4p5XIslAr8mryeZ6+htSSQe4AcfVt7k+V6mOthBCYtr/LEU4ZHtl0mW9876PK8mRFAaT8DJOUFVz1lPfzRApuPggkkyq+UMvyfKTUbCk7/DpfX8Y4s4QAAAg9BmmNJ4Q8mUwIr/wAsWUPjZw3ksgRsxZ6n4fQjprPbkj2aUh30y0bZJnLmiXnWskvOGnCPwBnG9dEhatwX3hoxk7BNyG+wQ4emZUpcVzcWl2T9nKQB1euucuZWHTg7TCtM/iHyfPO2vbmGsfzs70b/egIbywUH4y4BQSL1nWc1SmpHm2zHMBcUjYLDZ5gL5vdfxn0V8FFw66G88c/LN4I5icUa7xf4fcSBKywU0ajbp1P+aJYjBgWT6Ggu0MDLDNl54tfqd42lKosQtM1aif4WXAZFP5Ww3vrQ1rH9+utSYxqZd6N6gGtNbSNMcViaKn5LcnjsbBi3T3EmGqshEbcme8VHKwR3kSfBOAprrIsv6K8R+X6az+MD23rWka/2v64m1qM69D7Xa+Kcs/n0KLCJdTilyaGadopLeaAn3eYvWTeHcucMM1Fp1KgHD1tiFeO6HvobLkZlRximsA3/7MiohYklLIcJrZL22BH+6W9d6kZsYIsej9RM681nU6mWNjepBAfAfTbrGRrVB/h2DxC5B8YyRjgSIzQjNYrse0rzChqbrsLl7mQ7W+1bsNKze5//9ZIa8rSsF+BXh/vgoRTDkPW/ws95B7VPCZEFChfX0icw+tpcpN/q7NY87tUn4vESdSiMMlyhKklMjQu/G51J69ZRQLs2oUO6YfoJFqliy4qCFCrf8SZE9Fc6DcCagAAAAodBmoRJ4Q8mUwIr/wArPWF/KOw78THwadfPqhJO0CnmR/M74/XYZLqVYKlNcEaYauf+vrRUDJPmu75sMKy2Y+Bnslc/iAISSyWtw/h/3CF8fE5ZrbrwSNst+MSyCoNWP+8imtoX2eyojpdCk8YP5K+cbK4SJPCkZXbYqSXYk7hO8AdSemBHgXKWiZ+UOr802aJo+98ZOIjX9hWL9bo31Gqx7cy4ZG+W/ar/WGlzDa1xPWnPRsEdrIcZlEVGV/jGmbirkxw1lyUYoqj8Vv7Bxube9XPQlBkXOV6Lc1LT2IzNq0V7WwVhF0kA6yxfAsFxc9krNEH8vGGntTWI608ovjatXc/CKKXw7AjJSftlTcLI0hIIGXbRUr0NCYNp7M4cVd/n73Rjetnixz4SAKpcz/P47UsijZG7T3SxzK2D79WS42aEalc12hQwCZ01LfmF/H2mmGEvOzPBie1D0YT7Jh19vxa4Dd3SQ1FrDfmSUpvv4DjbYcZ2PrPpFpWtMjWqHBeoyMiZf6RP3EfYR6z9jsVNIIHxM0bzzBQF8eeYkPgDySydxPXv9Izo+QUY94N8kWi16fI6eZSDc1G0Yo0L91jcRQuDMGGS7B2zuf/0GbJyRhUO48UbMrqnILMrbQg1LF00Q3pH9nbGEK/RRQpRN3T/J/4IZQjwW2Ft2ipWGztg1Jn9I4DmffKS60QC+JQcyakdVON6zDcKttIKlqeTcmAi4xzmo4QXa2dRKleS+fs3EtTdBBtony2wK9T2Imj+NCziOSEL7Q7VuIU8kclUHrJJsSneFcxGRgIgGGUEQM8/pklwTOqab7mMmJeRiaBrjJDEnDpkR4Vz3qXxgyn4/5x24FuTMNVPwQAAAhtBmqVJ4Q8mUwIr/wApcLwPT0/Xh9UdWqWXIs8Wbj5K1hivmN6qIQnq+aolcegdlM/63MbHsdC6xYZC1e/Q8UjQCt9N/Ejqwms8DzeWv2qxskeliZH0kt1QWkErWSEodq7V0ZNksctLkMGWayX33gBT368EehfIeGDolBZoqIbJfb4nqcfU+ev4OzVv9zVqWyLck315GFmXxQKIM8pICQc8Q5es34LH1+DmnMnW8kQpVGrztQcDXhjCU3F0fOgoSsXSVWCjc6XKqGbCwQDfJUxCfXfIT6YmQoPpVp1mpGy1wQypXus9z0bScDpyDu23hViYDntdj1O45ea0znKZkj1+tLHbBtqAGJ1WTcbGlF6Vya6hQhEsiiZUIC2fRxIj8/wEXCICIbr0gZ/m6gcOhE10tenvE7iy+BKY81wLWrnzos3S6FWxYtmCRes+LLhNGOKWRuQo6SyePH2OZ90xZm8oA1MuTe3V59euVNxjAt0FLkAc9TEiFhP/8CB+gA8mF+A8h1U01f4DVX55GzCH51jHI2xUS0L9GtsHoBxLPLK/NNel8zcnwG4X+UusfcfEb5hh+ffnXteCE9vRGbs2n9wYW0xA3ZicklfadmWKUtMiHYBfkMSULWnkBQr4CXxjpYOs6ygeEoA5+5B0B1SZObgZ42wWqddyyYE0NfwQAl75tfdJGqOa7OMHwBYNeatJaJK0zT2+bFaw2qWCWwAAAitBmsZJ4Q8mUwIr/wAstkdsayRXchoFk703izqzduZ5WsyXriI9cfUdMUWvm0iGHwYIrUujvz3Yjou+JLwv9df2kt7MJo8u+3P5CjEKbwlz4vkE5AHTAbgXn3+Xc/MMJLgW5cm7iX3KiGNnBpbphhwJRlb3u91NRDr0d1IR2up/z7lKxE7XPAPFe0siPMYVlIqWNSn5KqLABPeuxxbOsvMEb27/nH1LUVM8I2F95c1I3Lv1SpkhZXjs1JsmS9X7gsoTxkXyShGC2+zRJSGUbhCPo/q1XSFMHQyMWJ79FKPQSL/RpVsacN2bYwdKo4TFBw1SsKq/L1iOmqMI+4Gxnbbjojdk0ek0JIcDb4bHv1czxchF7FX1Ym8H6IpPuE8CeNKjzQ1a1wqhEu+wl1N0x3Y37ZryCCKJRkxj0FT7bOoH3L38/yMUuh/v3aCmxY4eCkykb2p6ZrYMFE044anM/nMjmbErMibfRFuCz58Io1rBlF7JfkIz0R2/5vjUMVskcdbX2mm7DntncOsWDIdg/XVmgsC9CzVzUyq4VsS/sk97lJggcddpWLNw/29egz8iLyzWHOAXCvl2fTIPkviYAOQXfVhZUQdxsyJUNFMTiALrZCmoQLMp2LmDbfbW8JQriDeR3fVz6P1sjT8C2yEDvzkCn7sh0aTBK+sx7BKH1nb4320+caQepQj4TCJtCeNXjdrVcNEnjvwlcRJwFT1pT+Y7HREbHnT71XYNh4EAAAGEQZrnSeEPJlMCK/8AKIjxcI58rm/ML255fOJW1zbznFna7lfgMQrka7OTPPsvVAV4EJXye/Uxiu9dlftmRypJqfDot3xwDe8lX/qAVf6pBkSlUsaLyBYtww/SUSa1bGl1JvrJCN7FXCCXbLd5R4PoYlPiDIm/DQH2puO0StIWmrR77Isc/J1pRvdu5+mQa/n0SEHUeM2KkoRzCznfD9zaaRO7BDtvC9SYIT0uYZxrwTjxQ7N7UERTrYG0P+vRLAhxkfohFIYl3HXyjPOvnlbUFP2oiiy6nkUFuaIyQcJawJv3GU8k4ObcKsC1cNDXjSpsyQRrxLFaCCjke4mikyt7vs0iN0bnrNWv9HXruG9zOFEOer1ggIFTsT1Eos5CXRkgja5HN4QUM6MhWpc5du/HgBIH8ANFcoo2kJpqcadw9r/0qk25X91MQSDJQiH8Hny2dQhqR+LFWEawiW753SJhn0ngZcv/mPj3mwcHv1SL9ErBqAjm4JGiDetPKYtFwANYY11OyQAAAVdBmwhJ4Q8mUwIr/wArOx5HV2505jRePGgMxptW4PGIHEszV1xGZS+flSkF+aq30AaqO7u6XK9jJsuWXTfYCRQTn1bZfFQ22DbO5DXAxK/TUmbQleCflFzeS6/czxkL4PJ8AwOs2U+oehekgCZC8gZyHHaQSaKbNJ46gTjNsLy84ACQ5uNt11TPuCPqPTuh+schdw9S+/lU/6m+EyaqGZ49wDFPiBFBYXglQQBjyP9k/rqq0xL7SiLjpe4riYg8SFUuUtOzPdWHyvxnI7Ug/0VLPGAAhgMISUnqe01d5QFf36yHpwMAHexjAZFIGQHAFautuMuEw6HzUZVzNdeHYxvEYOGkTo007bLwbuf/nxzrywGOxlRTYJLRdYI0mk0SdN3+LeTv1RIJwv21+e9rT5iFOTCgzeQoekEWXLYz0X8YLq5bVCtijP7/T7w1Ck71j0aqfrEn6wtIAAABNUGbKUnhDyZTAiv/ACcySi7VBgOid6qZNXvhh/JsllHkMLLq0yNbQTqv/Wk2EBoSKICZwFwAD0WRzhvvReCGirep1Fe4bxjm49/UR+OYrXRmHR18T0C83AUVeBk7KvDZmb/eHzuzEN4yfXucr/NWFJl+USVMY4r4UQ9CayrfEY9v6AQ6mzAdLy2UMfFxrRJ99g/Rfl8qx+m4jIZNjlrTaThzJ/3OpVmAliDfxVyg8+CVIlI31IykiwQrXcebgajG+av8XU1SfyAG5ibvwbtdSAxkGBcJWL387V+uTdY56w3KN2vBtoQpVKD2zb3yazIcATZ02upwIytNcM/rpaLCdMb1myWcikE25agzLhDhOS+4zwjYz2DnW6VY0gFBAPsphhsUMnauVVdUVHzCTSdvzEve/H8q4AAAAVdBm0pJ4Q8mUwIr/wAo+x5XKuiN1am7SkJKSMonFZDPU3f5XFcDQSs0FLVq2idfsKwuIkt1mxIq8NgMHpzofTnDHqs/WedvAmhBgL0N5azdQa5MNKG2rJ4IAvGQY/uFm3jKQAKzvhSS01gO1oIfizF817z9IShS4QK2WT0PeFPELqLSpED8eNOpVTR96vmwpk/WBKRVJdTQJzjiCQ5pgEwjtvk7KqoS0+lwXSbvIrXkYm8DignEts3DLNoLHrPjXlQmbIop76JZSyJEtB+91GrLwo6Km5GeebyA2E6qGL3xSkpppej/ruoFprSKrH60UMbrq/SK7eCo+1QFoySPQmqDFsMGiQFqvtld5BXDYdVI4yRaoyN7Y7wi83HRC6eVazuHU9OtIY3xJJApBWq1aJOsYwc38aTC3ee863Aa/4n9Lk4DAtyFYHNZjB5m2e2vk8G2Gny9YFlBAAABQEGba0nhDyZTAiv/ACoZSZQfHxhfQxEqOBQrP+L3DmgvHSJQtB1iVkcLTxm+vagLHBLG91OGnopwrr7gT/loDypIhoRxjcwAAOeg/jN4WBbXzCJtnWGGllUCSdtUZQzKOSp9iM4yX18C6jrY4Sq6R9PUV/lEGNveJR4gw4FMve7110XdEPL1O2VTdHvdqeANyaq0nLdEmtXnrzvdrFlBaUvmaR4EdlkqGkvkZKWJej8Vq+msbKa7JdbxjwZtRufiyGfD/NVqMgSrYRzw9z/a8Zwbr+9+19CxlWD5bCuAEfPmjY6kZJE2L/CQI6+tnCBTXOmWZtZMBoCLGOf7G2uAC3+kFlboh9as5WCkO6+iqXq29dyhKnsHInorRYsPlgxIXyU1Om/Kyhj1DJV0Am9WJK3Dln0zNUH0q6ZTOnZcFD36AAABYkGbjEnhDyZTAiv/ACcwdIOLRFfoGK2ZkKsvgMwG0m0qsY0vMLPSzefc+ebp/aztyF7MlsBz/fBeNtxFBcsKgR4pf65GvdfOMHah0ltZ918sMDmXUEZMeRHy/xpnWpTLeGz6uTs/7MATPmU5BgHbT/DkD8QeaZnFAzidyFCXDz2l/jaKhEdgqipbB2pH0+fQ039r05z9axxEWGmaLQjg6x9+po1o24yhkVO7m03YwWmPyCgy8cOwrvRyJkXJpRN4m8ZBS1zwY80HeN/VyMQQJSMwsTo7R1XMerSFuyx0nz+8qOuhiqykc2ohCCsXia/+kIKbJ5Vs+cbWtvkqBKIDSfU7FhAd3GjcY/xar0EVmi6wWFTugAogR3I7mTrQDdlTAqYgqO7Gn5NMXQVHu2i1zhFSdo9GjMbeGnbkJwsFbQ2XkoKRIDpuW7AewC9AEBt0Ox/Ah6dGXfXO1jl8pEApj2RFmgAAAPlBm61J4Q8mUwIr/wAlR+eW/VZ7bSrmwwMA62G05DZ7p/5FUugsSsQdonUq6abtbU5hjFr+I1lPgoiV5c3CkTQZS+K5zivdo+Ti2P4K90xXANp8dSMAu85uJIOCQn2TXbEnNDifLB+3V84ht5tj4lvTaZx317BcliV8D5v2zZQW8RO1mUbuJEBItst8E7hfE+ZXj7tfDxNZPTvtpFyUv0fH1cTg1pr2VLy0d0zQLiA58dg+GkRvR1/hs2LyifBgHcj6eTWz0vsypVn9iPXRH/unJ6i8cfFL69NO24tQ9QQB+nDFhoP2cRhkAvhHwn56n5PppBD/oxni2f8AAAE9QZvOSeEPJlMCK/8AJjAXVGf+Kj2XNJnFeKC/gr7dJDTC2ngpd4WeAHlg04GuJKnn9hAmiECxxo9qM1IYMRiB85t6gALnlm9sRqGmioyzAm18RJndc9Ah8RlpGzr+44a6ntRaPx0cIwNIWAA8buL2JP00dmfjNqEiAlCa8OdV8FQxjp1vDXsGcAGF3Qbd62KEpkimeI3wH2nuXpbDHm8/ZKOR49s5ifUCkxCoJpfp43aC0lTzh2NXpcfVw6h0QnK8G60R4ZAxOxaJB7c0nn8ixXSU2JVY24EtGMF53nxJnHfzUheewUfBOGYSxeo8oK7oUCqX4rztzDwoc2QywNqQUJUkFrqIN+sb5ecYvX24Zujn+ZzTW6UDAF3R6WdNyJyRAremgC8spSflTqygQNGfHyGkfIEEJJaFo/pBCBkAAAEWQZvvSeEPJlMCK/8AKI41fuekXG59Knbw4Y6YJritsh9VtQgc3QKvVmxrzzo7f4aXn8N74eyP4b2lV1Z2Q+rohxps7EHTkOY9jLdqxI3MXe7je4g2qepz71+hY+jYdX+9LO0kA0Zg3NfyAlIRX7k6c/YHAZNtNaGZgTBMqiPgmEjiJH9Luk7shbgr+srfwiYwBX9rdS3fQNNFwcT8orQC+F60LAY9+GbFo2Sw3Ld4Tw9jq9yJtrY8RtHAdzytyek/mv2+j2TbTvAQKbbCYtdC8E/KtR4V5ZTSScr5Wb63vmbw7UpddEXYvl55pARyyvMxWNSh3Li4GF8Jk5JBi5B5ASQwxCMYpX5hkAMc+d8tl2bT+IEvUTsAAAElQZoQSeEPJlMCK/8AJIAzFZs00JJ0yfm8CZiew4xWdArLklEvBVXo/+ukPLu3XP9HFOfsme3T6BJEKmPPgZw/Lxnraq6Sl2kLVW19YU1qmqgfv+80LkZaWU5gRAH4hqyo3bFYcbuY2SC3IW5Wm69gtYyAXOdbAYSEHA16fvCeRQjHEsxKVndJdrRAlrGHsKgUBQ3Up/ZXIy1vkdFOfKSjpuZnswkuqr8NZI5tJ/dnBSErBTNWPaNwWV7nNomC0EYVGo+geGBhLXzaLw0UAOCYGjiPc3803BDw1GLoLIXjrIFJxwRfBNIAXYZAglu30oYzhpAfRWSprkeULMWYJTlWvbUQ5CNewSZssuDWIRAc3w8AcFaywwn+YSGhtR8VI1OGjYkfBbcAAAD8QZoxSeEPJlMCK/8AJdokjCUETRw/nciVPtaZQSBP/VxAQSITASEzlJBl9Na1r0DJhLOz279+KQLtl/xHZ8vAKc528mTMTqtWs4sFbeVgHWyBpHcHEtgTzjIqEinp/MPuUXF5poo8YLSSMFn9Ozx2FbU5/Kh9A39oN9NHQflVxV1NA6yT/84HHyfMtfdSMS8KTvAEE2lDs14VQayNs5ctjXboQT7xMBf5OLj6thhPvgaDrFB2o/PV9ouK147lruWTP2mkoA9oDIMYW1pcBx4yyV/t9GOPZ3aXneMUb2fFmUCX43BjXfUDMaa4GO2/Ankj3UEQwDxA7ZlNUQK2AAAA4UGaUknhDyZTAiv/ACJHv33I08bkhybYiJ/JiiheW5zMPBu4n5CxGr3frhE7TkLh0vPktM8m/AhaDiJisdk5QXNe/4WmxEDSAyaVi4eUVu0iHT2ly/KNTGqiORqA2oKpTjh84nYbrpXwnGv9SOf/34Z06xN6Yo3t35UZrP8nlcs/63GtnEmnUwVZHBYfPM6bs5M5AeBfAQ/9mIqu7vnEst+5O2wpPjzdItjwGCZ2ApHVjGnYYFomlA9nm6AXnxNIWHIsDgxCk3zx+6QbXipu/CWLG1Wf0WIbt4C0JPVl3TEb0QAAAMlBmnNJ4Q8mUwIr/wAVV64OfTKmlktYOqZHH1W1DhPy/X/6sD4T6hRdzfOgNtTOX2IckRJHshfBQVkJIzns079io6kpJFCcS3VD4zrWCn/dNaGV0kWTpFBRuusfn8F0C0R/EhsQeyTsdZftEkLGb5tq+nrir3vfmeb7rjmWJRXkIrTEKu8pIuAd+4FBGp8ARgGe80Jqpp//s1433HqBFqXsIFJTmU8j/toF9HyueI1Ea4uvsQ6NANGcYCbOAKCmbNiwABMCFaiUTMAAAAPSbW9vdgAAAGxtdmhkAAAAAHwlsIB8JbCAAAAD6AAAAyAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAv10cmFrAAAAXHRraGQAAAAPfCWwgHwlsIAAAAABAAAAAAAAAyAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAY4AAAGGAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAMgAAAAAgABAAAAAAJ1bWRpYQAAACBtZGhkAAAAAHwlsIB8JbCAAAAAGQAAABRVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAACIG1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAeBzdGJsAAAAtHN0c2QAAAAAAAAAAQAAAKRhdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAY4BhgBIAAAASAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGP//AAAAMmF2Y0MBZAAV/+EAGWdkABWs2UGQz6mhAAADAAEAAAMAMg8WLZYBAAZo6+PLIsAAAAAcdXVpZGtoQPJfJE/FujmlG88DI/MAAAAAAAAAGHN0dHMAAAAAAAAAAQAAABQAAAABAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAYY3R0cwAAAAAAAAABAAAAFAAAAAIAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAZHN0c3oAAAAAAAAAAAAAABQAAA05AAACqQAAAl8AAAITAAACiwAAAh8AAAIvAAABiAAAAVsAAAE5AAABWwAAAUQAAAFmAAAA/QAAAUEAAAEaAAABKQAAAQAAAADlAAAAzQAAAGBzdGNvAAAAAAAAABQAAAAsAAANZQAAEA4AABJtAAAUgAAAFwsAABkqAAAbWQAAHOEAAB48AAAfdQAAINAAACIUAAAjegAAJHcAACW4AAAm0gAAJ/sAACj7AAAp4AAAAGF1ZHRhAAAAWW1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAALGlsc3QAAAAkqXRvbwAAABxkYXRhAAAAAQAAAABMYXZmNTIuMTExLjA=\">\n\n\n\n## External sites\n\nYou can even embed an entire page from another site in an iframe; for example this is today's Wikipedia\npage for mobile users:\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('http://ipython.org', width='100%', height=350)\n```\n\n\n\n\n\n\n\n\n\n\n## Links to local files\n\nIPython provides builtin display classes for generating links to local files. Create a link to a single file using the `FileLink` object:\n\n\n```python\nfrom IPython.display import FileLink, FileLinks\nFileLink('Cell Magics.ipynb')\n```\n\n\n\n\n<a href='Cell Magics.ipynb' target='_blank'>Cell Magics.ipynb</a><br>\n\n\n\nAlternatively, to generate links to all of the files in a directory, use the `FileLinks` object, passing `'.'` to indicate that we want links generated for the current working directory. It will optionally recurse into subdirectories as well.\n\n\n```python\nFileLinks('.', recursive=False)\n```\n\n\n\n\n./<br>\n&nbsp;&nbsp;<a href='./Raw Input in the Notebook.ipynb' target='_blank'>Raw Input in the Notebook.ipynb</a><br>\n&nbsp;&nbsp;<a href='./ipython-qtconsole.desktop' target='_blank'>ipython-qtconsole.desktop</a><br>\n&nbsp;&nbsp;<a href='./Cell Magics.ipynb' target='_blank'>Cell Magics.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Terminal Usage.ipynb' target='_blank'>Terminal Usage.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Capturing Output.ipynb' target='_blank'>Capturing Output.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Third Party Rich Output.ipynb' target='_blank'>Third Party Rich Output.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Rich Output.ipynb' target='_blank'>Rich Output.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Script Magics.ipynb' target='_blank'>Script Magics.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Index.ipynb' target='_blank'>Index.ipynb</a><br>\n&nbsp;&nbsp;<a href='./example-demo.py' target='_blank'>example-demo.py</a><br>\n&nbsp;&nbsp;<a href='./Old Custom Display Logic.ipynb' target='_blank'>Old Custom Display Logic.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Beyond Plain Python.ipynb' target='_blank'>Beyond Plain Python.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Animations Using clear_output.ipynb' target='_blank'>Animations Using clear_output.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Plotting in the Notebook.ipynb' target='_blank'>Plotting in the Notebook.ipynb</a><br>\n&nbsp;&nbsp;<a href='./ipython.desktop' target='_blank'>ipython.desktop</a><br>\n&nbsp;&nbsp;<a href='./SymPy.ipynb' target='_blank'>SymPy.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Working With External Code.ipynb' target='_blank'>Working With External Code.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Background Jobs.ipynb' target='_blank'>Background Jobs.ipynb</a><br>\n&nbsp;&nbsp;<a href='./ipython-get-history.py' target='_blank'>ipython-get-history.py</a><br>\n&nbsp;&nbsp;<a href='./ipython-completion.bash' target='_blank'>ipython-completion.bash</a><br>\n&nbsp;&nbsp;<a href='./Custom Display Logic.ipynb' target='_blank'>Custom Display Logic.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Trapezoid Rule.ipynb' target='_blank'>Trapezoid Rule.ipynb</a><br>\n\n\n\n## Rich output and security\n\nThe IPython Notebook allows arbitrary code execution in both the IPython kernel and in the browser, though HTML and JavaScript output. More importantly, because IPython has a JavaScript API for running code in the browser, HTML and JavaScript output can actually trigger code to be run in the kernel. This poses a significant security risk as it would allow IPython Notebooks to execute arbitrary code on your computers.\n\nTo protect against these risks, the IPython Notebook has a security model that specifies how dangerous output is handled. Here is a short summary:\n\n* When you run code in the Notebook, all rich output is displayed.\n* When you open a notebook, rich output is only displayed if it doesn't contain security vulberabilities,...\n* ..or if you have trusted a notebook, all rich output will run upon opening it.\n\nA full description of the IPython security model can be found on [this page](http://ipython.org/ipython-doc/dev/notebook/security.html).\n\n## Rich output and nbviewer\n\nMuch of the power of the Notebook is that it enables users to share notebooks with each other using http://nbviewer.ipython.org, without installing IPython locally. As of IPython 2.0, notebooks rendere on nbviewer will display all output, including HTML and JavaScript. Furthermore, to provide a consistent JavaScript environment on the live Notebook and nbviewer, the following JavaScript libraries are loaded onto the nbviewer page, *before* the notebook and its output is displayed:\n\n* [jQuery](http://jquery.com/)\n* [RequireJS](http://requirejs.org/)\n\nLibraries such as [mpld3](http://mpld3.github.io/) use these capabilities to generate interactive visualizations that work on nbviewer.\n", "meta": {"hexsha": "3a5b3ac88467030a46f17e4096915b2b8f039f37", "size": 281513, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/IPython Kernel/Rich Output.ipynb", "max_stars_repo_name": "adamchainz/ipython-in-depth", "max_stars_repo_head_hexsha": "1905adca735c567884c5db8c1b6295b0e1d7a218", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/IPython Kernel/Rich Output.ipynb", "max_issues_repo_name": "adamchainz/ipython-in-depth", "max_issues_repo_head_hexsha": "1905adca735c567884c5db8c1b6295b0e1d7a218", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/IPython Kernel/Rich Output.ipynb", "max_forks_repo_name": "adamchainz/ipython-in-depth", "max_forks_repo_head_hexsha": "1905adca735c567884c5db8c1b6295b0e1d7a218", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-25T03:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-25T03:00:47.000Z", "avg_line_length": 89.6252785737, "max_line_length": 64152, "alphanum_fraction": 0.8253934987, "converted": true, "num_tokens": 62179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1329642436335826, "lm_q2_score": 0.0803574611138215, "lm_q1q2_score": 0.010684669037314302}}
{"text": "# Droplet Bounce Parameter Estimation\n## Import experimental data\n- Each drop is an instance of the Experiment object class, with various attributes that are experimental metadata\n- Why didn't I just use a dict/list of dicts? Dynamically generating these objects is very poor practice\n- As of 10.19.2019 there are issues with the parameter estimation. I'm going to do some minor code clean up, and start using a virtual env once I'm able to replicate my previous results...\n\n\n```python\nimport os, fnmatch, csv\nimport numpy as np\n\nclass Experiment(object):\n    def __init__(self, data, name, start=0, end=-1, volume=1, surfaceV='[1000]', frame_rate=29.95, \n                 outlier=False, time=1, debias=1, layers=4, guess=0.72*2.3):\n        self.data = data\n        self.name = name\n        self.start = start\n        self.end = end\n        self.volume = volume\n        self.surfaceV = surfaceV #sum(surfaceV)/len(surfaceV)\n        self.frame_rate = frame_rate\n        self.outlier = outlier\n        #self.charge = charge\n        #self.u0 = u0\n        self.time = time\n        self.debias = debias\n        self.layers = layers\n        self.guess = guess\n\ndef print_header(drop):\n    \"\"\"\n    Prints the drop name and measured experimental parameters.\n    \"\"\"\n    print('name', drop.name)\n    print('volume', drop.volume, 'mL')\n    print('surfaceV', drop.surfaceV, 'V')\n    \ndef import_data(exp_class):\n    \"\"\"\n    Takes an experiment type and returns an array of Experiment class objects, with attributes specified by\n    a metadata csv. The 'data' attribute The column heads include:\n    'R','Area','XM','YM','Major','Minor','Angle','Circ','Slice','AR','Round','Solidity'\n    \"\"\"\n    meta_file_location = '../data/' + exp_class + '/meta.csv'\n    imported_datatype = ('U9', int, int, float, object, float, bool, float, float, int, int, float)\n    metadata = np.genfromtxt(meta_file_location, delimiter=';', dtype=imported_datatype, names=True)\n    for keys, vals in np.ndenumerate(metadata['surfaceV']):\n        metadata['surfaceV'][keys] = np.fromstring(vals, dtype=float, sep=',')\n    globals()[exp_class + '_data_list'] = np.array([])\n    for drop in metadata:\n        name = 'drop' + str(drop['name'])\n        path = '../data/' + exp_class + '/' + str(drop['name']) + '.csv'\n        data = np.genfromtxt(path, dtype=float, delimiter=',', names=True)\n        print(path[-8:])\n        start = drop['start']\n        end = drop['end']\n        volume = drop['volume']\n        surfaceV = drop['surfaceV']\n        frame_rate = drop['frame_rate']\n        outlier = drop['outlier']\n        time = drop['time']\n        debias = drop['debias']\n        layers = drop['layers']\n        guess = drop['guess']\n        first_frame = drop['first_frame']\n        data = data[first_frame:-1]\n        data['Slice'] -= first_frame\n        data['Minor'] = data['Minor']/2\n        data['Major'] = data['Major']/2\n        \n        # check for gaps\n        if (data.shape[0]) < data['Slice'][-1]:\n            print('there is {} cells of gap'.format(int((data['Slice'][-1] - data.shape[0]))))\n        globals()[str(name)] = Experiment(data, name, start, end, volume, surfaceV,\n                                          frame_rate, outlier, time, debias, layers, guess)\n        globals()[exp_class + '_data_list'] = np.append(globals()[exp_class + '_data_list'], \n                                                        globals()[str(name)])\n    print('done!')\n```\n\n\n```python\nexp_class = 'dielectric_improved'\nimport_data(exp_class)\n\n# use fancy indexing to make a list of outliers\nmask = [datas.outlier==False for datas in globals()[exp_class + '_data_list']]\noutliers = {datas.name:datas for datas in globals()[exp_class + '_data_list'][mask]}\nalldrops = {datas.name:datas for datas in globals()[exp_class + '_data_list']}\n#alldrops = outliers\n```\n\n    7294.csv\n    there is 2 cells of gap\n    7295.csv\n    there is 1 cells of gap\n    7296.csv\n    7297.csv\n    7298.csv\n    7299.csv\n    7300.csv\n    7301.csv\n    7319.csv\n    7325.csv\n    7326.csv\n    7327.csv\n    7328.csv\n    7329.csv\n    7334.csv\n    7335.csv\n    7336.csv\n    done!\n\n\n## Filtering\n - Purpose is to smooth trajectories as part of a preconditioning strategy in the parameter estimation\n\n\n```python\nfrom scipy import signal\n\ndef sg_filter(y, dt):\n    \"\"\"\n    Takes raw data and returns a filtered array of the same length. \n    The function avoids IndexErrors by a simple rule for setting the window size.\n    \"\"\"\n    #try:\n    if y.shape[0]>25:\n        window = 25\n    else:\n        window = y.shape[0]\n        if window % 2 ==0:\n            window-=3\n    return derivs(y, window, dt)\n    #except ValueError:\n    #    print('debug: Window size', window)\n        \ndef derivs(y, window, dt):\n    \"\"\"\n    Returns Savitsky-Golay filtered array of a variable and its derivatives by finite differences.\n    \"\"\"\n    dtdt=dt*dt\n    y_savgol = signal.savgol_filter(y, window, 3, deriv=0, axis=0)\n    y_savgol1 = signal.savgol_filter(y_savgol, window, 3, deriv=0, axis=0)\n    y_savgol2 = signal.savgol_filter(y_savgol1, window, 3, deriv=0, axis=0)\n    y_savgol3 = signal.savgol_filter(y_savgol2, window, 3, deriv=0, axis=0)\n    dy_savgol = signal.savgol_filter(y_savgol3, window, 3, deriv=1, axis=0)/dt\n    ddy_savgol = signal.savgol_filter(y_savgol3, window, 3, deriv=2, axis=0)/dtdt\n    return y_savgol3, dy_savgol, ddy_savgol\n```\n\n##  Trajectory Plots\n\n\n```python\n# set the look of the figures\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nimport pylab\nfrom mpl_toolkits.axes_grid1 import host_subplot\nimport mpl_toolkits.axisartist as AA\nfrom matplotlib.collections import LineCollection\nfrom matplotlib.colors import ListedColormap, BoundaryNorm\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nfrom matplotlib.colors import Normalize\n\n#matplotlib.use('pgf')\n#%matplotlib inline\n#matplotlib.rcParams['figure.figsize'] = (10,10)\n\npgf_with_latex = {                      # setup matplotlib to use latex for output\n    \"pgf.texsystem\": \"pdflatex\",        # change this if using xetex or lautex\n    \"text.usetex\": True,                # use LaTeX to write all text\n    \"font.family\": \"serif\",\n    \"font.serif\": ['Computer Modern Roman'], # blank entries should cause plots to inherit fonts from the document\n    \"font.sans-serif\": ['Computer Modern Sans serif'],\n    \"font.monospace\": ['Computer Modern Typewriter'],\n    \"axes.labelsize\": 12,               # LaTeX default is 10pt font.\n    \"font.size\": 12,\n    \"legend.fontsize\": 10,               # Make the legend/label fonts a little smaller\n    \"xtick.labelsize\": 12,\n    \"ytick.labelsize\": 12,\n    \"pgf.preamble\": [\n        r\"\\usepackage[utf8x]{inputenc}\",    # use utf8 fonts becasue your computer can handle it :)\n        r\"\\usepackage[T1]{fontenc}\",        # plots will be generated using this preamble\n        ]\n    }\n\n#%config InlineBackend.figure_formats = ['svg']\n#matplotlib.rcParams['text.latex.unicode'] = True\n#matplotlib.rcParams.update(pgf_with_latex)\nmatplotlib.rcParams.update(\n{\n    'xtick.color': 'k',\n    'ytick.color': 'k',\n    'axes.labelcolor': 'k'\n})\n\nplt.rc('text', usetex=True)\nplt.rc('font', family='serif')\n#plt.rc('legend', frameon=False)\n\nplt.rcParams['figure.dpi'] = 100\nplt.rc('font', size=16)\n%config InlineBackend.figure_format = 'retina'\npics = False\n```\n\n\n```python\ndef savefig(filename, pics):\n    \"\"\"When pics global variable is set to True this function saves figures.\"\"\"\n    if pics == True:\n        plt.savefig('../doc/figures/{}.eps'.format(filename), bbox_inches='tight')\n    else:\n        pass\n```\n\n\n```python\ndef plot_single(drop, args_for_components=['YM'], kwargs_for_plot={'color':'k'}, **kwargs):\n    \"\"\"\n    Plots a given variable over the trajectory of a single drop.\n    \"\"\"\n    #plt.xlabel('t ($s$)')\n    (ym, t, dt, contact_mask, y_parted, \n        dy_parted, ddy_parted, t_parted, ind_parted) = get_data(drop, param_est=False)\n    component = {'y_parted': y_parted, 'dy_parted':dy_parted, 'ddy_parted':ddy_parted}\n    if 'parted' in kwargs.keys() and kwargs['parted']==True:\n        if 'sub' in kwargs.keys():\n            i = kwargs['i']\n            fig = kwargs['fig']\n            axs = kwargs['axs']\n            axs[i].plot(t_parted, component[kwargs['variable']], 'ko', \n                    markersize=6, markerfacecolor='white', markeredgecolor='black', label='data')\n            axs[i].plot(t_parted[ind_parted.flatten()], component[kwargs['variable']][ind_parted.flatten()], 'o')\n            #axs[i].ylabel(kwargs['variable'])\n            #axs[i].legend(title=drop.name)\n        else:\n            plt.plot(t_parted, component[kwargs['variable']], 'ko',\n                    markersize=6, markerfacecolor='white', markeredgecolor='black')\n            plt.plot(t_parted[ind_parted.flatten()], component[kwargs['variable']][ind_parted.flatten()], 'o')\n            #plt.ylabel(kwargs['variable'])\n    else:\n        try:\n            a = drop.start + kwargs['start']\n        except KeyError:\n            a = drop.start\n        b = -drop.end\n        t = drop.data['Slice'][a:b]/drop.frame_rate\n        for component in args_for_components:\n            y = drop.data[component][a:b]\n            if 'n' in kwargs.keys():\n                minm = signal.argrelextrema(y, np.less, order=4)[0][::]\n                minm = np.append([0],minm)\n                minm = np.append(minm, [len(y)-1])\n                maxm = signal.argrelextrema(y, np.greater, order=4)[0][::]\n                n=kwargs['n']\n                if n == 'all':\n                    plt.plot(t, y, label=drop.name, **kwargs_for_plot)\n                    plt.plot(t[minm],y[minm],'o')\n                    plt.plot(t[maxm],y[maxm],'o')\n                    plt.ylabel(component)\n                else:\n                    plt.plot(t[minm[n]:minm[n+1]+1], y[minm[n]:minm[n+1]+1], label=drop.name, **kwargs_for_plot)\n                    plt.plot(t[minm][n:n+2],y[minm][n:n+2],'o')\n                    plt.plot(t[maxm][n],y[maxm][n],'+')\n                    plt.ylabel(component)\n            elif 'c' in kwargs_for_plot.keys():\n                plt.plot(t,y, **kwargs_for_plot)\n            elif 'points' in kwargs.keys():\n                plt.plot(t,y,'k-')\n            elif 'qm' in kwargs.keys() and kwargs['qm']==True:\n                eu, t0, y0, im = kwargs['qmvals']\n                if 'dimless' in kwargs.keys() and kwargs['dimless']==True:\n                    y, t = y_parted, t_parted\n                    try:\n                        y00 = y/y0\n                        minm = signal.argrelextrema(y, np.less, order=2)[0][::]\n                        minmm = minm[0]\n                        #plt.plot(t/t0, y00-np.abs(y00[minmm]),#radius(volume=drop.result.x[1])/y0, \n                        #     label=drop.name, **kwargs_for_plot)\n                        \n                        #plt.plot(t/t0, (y-np.abs(y[minmm]) - radius(volume=drop.result.x[1]))/y0,#radius(volume=drop.result.x[1])/y0, \n                        #     label=drop.name, **kwargs_for_plot)\n                        plt.plot(t/t0, (y-radius(volume=drop.result.x[1]))/y0\n                                 , label=drop.name, **kwargs_for_plot)\n                        #plt.scatter(t[minm], y[minm]-radius(volume=drop.result.x[1]) - y[minmm], **kwargs_for_plot)\n                    except IndexError:\n                        print('uh oh')\n                        try:\n                            minm = signal.argrelextrema(y, np.less, order=2)[0][::]\n                            minmm = minm[0]\n                            plt.plot(t/t0, (y-radius(volume=drop.result.x[1]))/y0\n                                     , label=drop.name, **kwargs_for_plot)\n                            #plt.scatter(t[minm], y[minm]-radius(volume=drop.result.x[1]) - y[minmm], **kwargs_for_plot)\n                        except IndexError:\n                            pass\n                else:\n                    plt.plot(t, y,label=drop.name, **kwargs_for_plot)\n            else:\n                plt.plot(t, y,label=drop.name, **kwargs_for_plot)\n        #return t[-1]\n            if 'single' in kwargs.keys() and kwargs['single']==True:\n                plt.show()\n            else:\n                pass\n\ndef plot_series(dataset, component='YM', **kwargs):\n    \"\"\"\n    Plots a given variable over the trajectories of a series of drops.\n    \"\"\"\n    if 'qm' in kwargs.keys() and kwargs['qm']==True:\n        if 'reg' in kwargs.keys():\n            if kwargs['reg'] == 'l':\n                n=1\n                m=1\n            elif kwargs['reg'] == 'll':\n                n=2\n                m=1\n            elif kwargs['reg'] == 'm':\n                n=4\n                m=2\n            else:\n                n=0\n                m=0\n        else:\n            n = 0\n            m = 0\n        qs = np.array([])\n        ts = np.array([])\n        ys = np.array([])\n        im = np.array([])\n        #for drops in dataset.keys():\n        for keys, vals in enumerate(dataset.items()):\n            drop = vals[1]\n            qs = np.append(qs, q_to_m(drop)[m])\n            im = np.append(im, img(drop))\n            ys = np.append(ys, yc(drop)[m])\n            ts = np.append(ts, tc(drop)[n])\n        norm = matplotlib.colors.LogNorm(vmin=(qs).min(), vmax=(qs).max())\n        color = plt.get_cmap(kwargs['col'])\n        my_map = cm.ScalarMappable(norm=norm, cmap=kwargs['col'])\n        fig = plt.figure()\n        for keys, vals in enumerate(dataset.items()):\n            color = my_map.to_rgba(qs[keys])\n            drop = vals[1]\n            plot_single(drop, [component], kwargs_for_plot={'color':color}, \n                        qmvals=(qs[keys], ts[keys], ys[keys], im[keys]), **kwargs)\n        my_map.set_array([])\n        cb1 = plt.colorbar(my_map)\n        cb1.set_label(r'${\\mathbf{E} \\mbox{u}}$', size=14, labelpad=8, rotation=0)\n        plt.ylabel(kwargs['label'][1])\n        plt.xlabel(kwargs['label'][0])\n        if 'dimless' in kwargs.keys() and kwargs['dimless']==True:\n            if 'reg' in kwargs.keys() and (kwargs['reg']=='s'):# or kwargs['reg']=='m'):\n                tn = get_data(drop, param_est=True)[0][-1]\n                plt.xlim(xmin=0, xmax = 4)\n                #plt.ylim(ymin=0, ymax=2)\n    else:\n        total_time=[]\n        vols = []\n        for keys, vals in enumerate(dataset.items()):\n            drop = vals[1]\n            vols = np.append(vols, drop.volume)\n        norm = matplotlib.colors.Normalize(vmin=0, vmax=len(vols))\n        color = plt.get_cmap(kwargs['col'])\n        my_map = cm.ScalarMappable(norm=norm, cmap=kwargs['col'])\n        fig = plt.figure()\n        for keys, vals in enumerate(dataset.items()):\n            color = my_map.to_rgba(keys)\n            drop = vals[1]\n            tf = plot_single(drop, [component], kwargs_for_plot={'color':color}) #\n            if drop.name in ['drop07298','drop07299','drop07297','drop07300']:\n                total_time.append(tf)\n            plt.legend(loc = 'upper right')\n            plt.ylabel(component)\n            plt.xlabel(r'$t$ (s)')\n\n    #plt.xlim((0.1,2.2))\n    if 'savefig' in kwargs.keys() and kwargs['savefig']==True:\n        name = kwargs['name']\n        savefig(name, pics)\n    plt.show()\n```\n\n\n```python\n#n = -4\n#m = -1\n#sorted_vals = [alldrops[x] for x in sorted_keys[:n]]\n#sorted_drops = dict(zip(sorted_keys, sorted_vals))\n#plot_series(sorted_drops, component='YM', qm=True, label=[r'$t^*$', r'$y^*$'], \n#            savefig=True, reg = 's', dimless = True, name='series_s_ds', col=col)\n```\n\n\n```python\n#\"\"\"\n#Use n=1,2,3 etc (where n may be 0 or any positive integer)  to look at an individual bounce.\n#Otherwise use n='all' to see all bounces.\n#\"\"\"\n#\n#drop = drop07336\n##drop.start=10\n##print(len(get_data(drop, param_est=False)[1]), get_data(drop, param_est=False)[1][0], drop.start, drop.end)\n#plot_series(alldrops, component='YM', qm=False, savefig=False, col='tab20')\n#print_header(drop)\n#plot_single(drop, parted=False, variable='y_parted', points=True, single=True)\n```\n\n\n```python\n# #A bash program to write experiemental metadata.\n\n#header = {'name':1,'start':2,'end':3,'volume':4,'surfaceV':5, \\\n#          'frame_rate':6,'outlier':7,'time':8,'debias':9,'first_frame':10}\n#row = !grep -n \"{drop.name[4:]}\" ../data/dielectric_improved/meta.csv | cut -d , -f 1 | cut -d : -f 1\n#row = int(row[0])\n#col = header['start']\n#value = drop.start\n```\n\n\n```bash\n%%bash -s \"$row\" \"$col\" \"$value\"\n#awk -F \";\" -v r=$1 -v c=$2 -v val=$3 'BEGIN{OFS=\";\"}; NR != r; NR == r {$c = val; print}' \\\n#../data/dielectric_improved/meta.csv > ../data/dielectric_improved/meta2.csv\n#cp ../data/dielectric_improved/meta2.csv ../data/dielectric_improved/meta.csv\n#rm ../data/dielectric_improved/meta2.csv\ncat ../data/dielectric_improved/meta.csv\n```\n\n##  Munging\n\n\n```python\ndef radius(**kwargs):\n    \"\"\"\n    Given experimental volume (in mL) the functon returns droplet radius (in m).\n    \"\"\"\n    if 'mass' in kwargs.keys():\n        pass\n    if 'volume' in kwargs.keys():\n        vol = kwargs['volume']\n        return (3 * vol * 1E-6/(np.pi * 4))**(1/3.) # droplet radius [m]\n\ndef mass(volume):\n    \"\"\"\n    Given experiemental volume (in mL) the function returns mass (in kg).\n    \"\"\"\n    return 1000 * volume * 1E-6\n\ndef volume(radius_drop):\n    \"\"\"\n    Given the radius (in m) returns the volume (in m^3).\n    \"\"\"\n    return 4/3*np.pi*radius_drop**3\n\ndef weber(drop, U):\n    \"\"\"\n    Returns the Weber number.\n    \"\"\"\n    surface_tension = 72.86/1000\n    density = 1000\n    return density*2*radius(volume=drop.volume)*(U/100)**2/surface_tension\n\ndef tj(drop):\n    \"\"\"\n    Returns the dimensionless contact time.\n    \"\"\"\n    surface_tension = 72.86/1000\n    density = 1000\n    return np.sqrt(density*radius(volume=drop.volume)**3/surface_tension)\n\ndef reynolds(U, R_drop):\n    \"\"\"\n    Returns the Reynolds number.\n    \"\"\"\n    nu = 15.11E-6\n    D = 2 * R_drop\n    return D*np.abs(U)/nu\n\ndef ohnesorge(drop):\n    R_drop = radius(volume=drop.result.x[1])\n    viscosity = 1.0016\n    density = 1000\n    surface_tension = 72.86/1000\n    return viscosity/np.sqrt(density * surface_tension * R_drop)\n\ndef bond(drop):\n    #surfaceV, volume, q, dy0\n    R_drop = radius(volume=drop.result.x[1])\n    surface_tension = 72.86/1000\n    #e_force = charge_density(drop.result[0])*eta_0*drop.result[2]\n    #e_force = eta_0 * 90 * drop.result[0]**2 #Ree0U^2/y\n    e_force = drop.Ef0**2 * 80 * eta_0\n    return e_force * R_drop / surface_tension\n```\n\n\n```python\ndef ellipse(data):\n    \"\"\"\n    Returns the droplet radius in the vertical direction.\n    \"\"\"\n    YM = data['YM']\n    a = data['Major']\n    b = data['Minor']\n    Angle = (data['Angle']-90)*np.pi/180\n    return a*b/((b*np.cos(Angle))**2 + (a*np.sin(Angle))**2)**(1/2)\n\ndef ym_0(drop, n):\n    \"\"\"\n    Returns drop minima and maxima. \n    \"\"\"\n    ym = drop.data['YM'][drop.start:-drop.end]\n    minm = signal.argrelextrema(ym, np.less, order=4)[0][::]\n    maxm = signal.argrelextrema(ym, np.greater, order=4)[0][::]\n    minm = np.append([0],minm)\n    minm = np.append(minm, [len(ym)-1])\n    intstart = minm[n]\n    intend = minm[n+1]\n    #if minm.shape[0] == 2:\n    #    YM_0 = 0\n    #else:\n    #    YM_0 = ym[minm[1]] - ellipse(drop.data)[minm[1]]\n    YM_0 = 0\n    return YM_0, intstart, intend, minm\n\ndef contact(drop, ym, a, b):\n    \"\"\"\n    Returns a mask with elements true where the droplet is not in contact with the surface.\n    \"\"\"\n    contact = ym - ellipse(drop.data[a:b])*1 # distance from the bottom of the drop to YM_0\n    atol = np.std(ellipse(drop.data[a:b]))*3\n    above_mask = np.invert(np.isclose(contact, 0, atol=atol))\n    below_zero_mask = np.invert(np.array([(contact <= 0)]))\n    return np.logical_and(above_mask, below_zero_mask).flatten()\n\ndef get_data(drop, param_est=False, **kwargs):\n    \"\"\"\n    Returns filtered droplet position, velocity and acceleration, up to the first trajectory apoapse when\n    param_est==True, for all non-contacting time otherwise.\n    \"\"\"\n    a = drop.start\n    b = -drop.end\n    t = drop.data['Slice'][a:b]/drop.frame_rate\n    ym = drop.data['YM'][a:b]\n    dt = t[1]-t[0]\n    YM_0, intstart, intend, minm = ym_0(drop, n=0)\n    ym = ym - YM_0\n    contact_mask = contact(drop, ym, a, b)\n    if param_est==True:\n        intendmask = np.array([(t <= t[intend])])\n        intstartmask = np.array([(t >= t[intstart])])\n        parted_mask = np.logical_and.reduce((intstartmask.flatten(), intendmask.flatten(), contact_mask))\n        try:\n            maxm = signal.argrelextrema(sg_filter(ym[parted_mask],dt)[0], np.greater, order=4)[0][::][0]\n        except IndexError:\n            maxm = -1\n        return (t[parted_mask][0:maxm], sg_filter(ym[parted_mask], dt)[0][0:maxm]/100, \n                sg_filter(ym[parted_mask], dt)[1][0:maxm]/100, sg_filter(ym[parted_mask], dt)[2][0:maxm]/100)\n    else: #partitioning\n        stepsize = 1\n        #split_array = np.split(contact_mask, np.where(contact_mask[1:] != contact_mask[:-1])[0] + 1)\n        #contact_array = [subarray for subarray in split_array if np.any(subarray)==False]\n        #for keys, vals in enumerate(contact_array):\n        #    vals = len(vals)/120\n        #    contact_array[keys]=vals\n        #\n        indices = np.where(contact_mask[1:] != contact_mask[:-1])[0] + 1\n        indices[::2]-=1\n        if contact_mask[0]==True:\n            indices = np.append(0,indices)\n        if contact_mask[-1]==True:\n            indices = np.append(indices, len(contact_mask)-1)\n        y_parted = np.array([])\n        dy_parted = np.array([])\n        ddy_parted = np.array([])\n        t_parted = np.array([])\n        ind_parted = np.array([])\n        for keys, vals in np.ndenumerate(indices):\n            if keys[0] % 2 == 0 and indices[keys[0]+1]+1-vals>=10:\n                ind_parted_a = len(y_parted)\n                y_parted = np.append(y_parted, sg_filter(ym[vals:indices[keys[0]+1]+1], dt)[0])\n                dy_parted = np.append(dy_parted, sg_filter(ym[vals:indices[keys[0]+1]+1], dt)[1])\n                ddy_parted = np.append(ddy_parted, sg_filter(ym[vals:indices[keys[0]+1]+1], dt)[2])\n                t_parted = np.append(t_parted, t[vals:indices[keys[0]+1]+1])\n                ind_parted = np.append(ind_parted, [ind_parted_a, len(y_parted)-1])\n        return ym, t, dt, contact_mask, y_parted, dy_parted, ddy_parted, t_parted, ind_parted.astype(int)\n```\n\n# Parameter Estimation\n\n\n```python\n#inputs\nd = 6.47/100\n\nimport numpy as np\n#physical constants\neta_0 = 8.85E-12       # vacuum permitivity\neta_r = 3.4            # relative permitivity\nk = 1/(4*np.pi*eta_0)  # Coulomb's constant\n#global k, eta_0, d\n\n\neta_a=eta_r\nsusceptibility = eta_a - 1\nk = susceptibility/(susceptibility + 2)\nk\n```\n\n\n```python\ndef electric_field(end, sigma):\n    \"\"\"\n    Returns the 1-D electric field, and the gradient of its square\n    in the z-direction of a uniform finite square of charge. (units?)\n    \"\"\"\n    \n    #d = 6.5/100\n    Ef = np.array([4*k*sigma*np.arctan(d**2/(2*z*np.sqrt(2*d**2 + 4*z**2))) \\\n                   for z in np.linspace(1E-6, end, 10000)])\n    del_Ef2 = np.gradient(Ef**2)\n    return Ef, del_Ef2\n\ndef ef2(z, sigma):\n    return 4*k*sigma*np.arctan(d**2/(2*z*np.sqrt(2*d**2 + 4*z**2)))\n        \ndef charge_density(surfaceV, layers):\n    old = surfaceV * eta_0 * eta_r/((layers*2.8+5.9)/1000)\n    return old\n```\n\n\n```python\n#\n#print(np.mean(list(drop.surfaceV)))\n#print('Actual fieldmeter reading -{:.2f} kV'.format(V))\n#print('Simulated fieldmeter reading -{:.2f} kV'.format(electric_field(2.54/100, sigma)[2]/1000))\n#print('Simulated fieldmeter reading -{:.2f} kV/m'.format(electric_field(2.54/100, sigma)[0]/1000))\n#\n## Plot the results\n##from matplotlib import rc\n##import pylab\n##%config InlineBackend.figure_formats=['svg']\n##%matplotlib inline\n##rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})\n##rc('text', usetex=True)\n#\n#zz = np.linspace(0.00001, 3./100, 1000)              \n##zz = np.linspace(0, 4, 1000)\n#plt.semilogx(zz*1000, electric_field(zz, sigma)[2]/1000)\n#plt.xlabel('z ($cm$)')\n#plt.ylabel('Scalar Potential ($kV$)')\n##plt.autoscale(enable=True, axis='x', tight=True)\n#plt.yticks([2,3,4])\n#plt.show()\n#\n#fig, ax1 = plt.subplots()\n#ax1.plot(zz*100, electric_field(zz, sigma)[0]/1000, zz*100, electric_field(zz, sigma)[3]/1000)\n#ax2 = ax1.twinx()\n#ax2.plot(zz*100, np.multiply(electric_field(zz, sigma)[3],zz)/1000, 'r')\n#ax1.set_xlabel('z ($cm$)')\n#ax1.set_ylabel('Electric field ($kV/m$)')\n#ax2.set_ylabel('Surface Voltage E*d ($kV$)')\n#plt.show()\n#\n#fig, ax1 = plt.subplots()\n#ax1.semilogy(zz*100, np.abs(electric_field(zz, sigma)[1]/1000), 'r', label=r'$\\nabla E$')\n#ax2 = ax1.twinx()\n#ax2.semilogy(zz*100, np.abs(electric_field(zz, sigma)[4]/1000), 'k', label=r'$\\nabla E^2$')\n#ax1.set_xlabel('z ($cm$)')\n#ax1.set_ylabel(r'$\\nabla E$')\n#ax2.set_ylabel(r'$\\nabla E^2$')\n#ax1.legend()\n#plt.show()\n```\n\n\n```python\ndef force_ep(q, Ef):\n    \"\"\"\n    Returns the electrophoretic force [N], including the contribution to the \n    attraction of image charges reflected across the dielectric boundary.\n    \"\"\"\n    return q * Ef\n\ndef force_image(z, q, R_drop):\n    eta_a=eta_r\n    susceptibility = eta_a - 1\n    k = susceptibility/(susceptibility + 2)\n    if z.any() <= 0:\n        z[z <= 0] = R_drop\n    return 1/(16*np.pi*eta_0)*k*q**2/z**2\n\ndef force_dep(z, R_drop, del_Ef):\n    \"\"\"\n    Returns the dielectrophoretic force [N].\n    \"\"\"\n    eta_air = 1.\n    eta_water = 90.\n    K = (eta_water - eta_air)/(eta_water + 2 * eta_air)\n    return -2 * np.pi * R_drop**3. * eta_air * K * eta_0 * del_Ef\n\ndef cd(re):\n    \"\"\"\n    Drag coefficent, Abraham correlation.\n    \"\"\"\n    return 24/9.06**2 * (1 + 9.06/np.sqrt(re))**2\n    \ndef drag(v, R_drop):\n    \"\"\"\n    Returns the aerodynamic drag force [N].\n    \"\"\"\n    rho = 1.225\n    #Cd = 24/reynolds(v, R_drop) + 5/np.sqrt(reynolds(v, R_drop)) + 0.3\n    return cd(reynolds(v, R_drop))*2*rho*np.pi*R_drop**2*v**2\n\n```\n\n\n```python\nimport scipy.integrate as integrate\nfrom scipy import stats\n\ndef fun(y, t, params):\n    \"\"\"\n    1-D Equation of motion for a droplet with initial velocity u0 subject to drag, and electrical forces.\n    \"\"\"\n    \n    z, u = y      # unpack current values of y\n    m, R_drop, sigma, q, Ef, del_Ef, zf = params # unpack parameters \n    ef_interp = np.interp(z, zf, Ef)\n    del_ef_interp = np.interp(z,zf,del_Ef)\n    #- force_dep(z, R_drop, del_ef_interp)\n    derivs = [u, (- force_ep(q, ef_interp) \\\n                  - force_image(z, q, R_drop) - drag(u, R_drop))/m] # list of dy/dt=f functions\n    return derivs\n\ndef get_model(x, model_params):\n    \"\"\"\n    Solves the ODE for the droplet trajectory given the design vector, x.\n    \"\"\"\n    t0, z0, volt0, vol0, tStop, layers, q0, Ef, del_Ef, zf = model_params\n    surfaceV, volume, q, u0 = x  \n    m = mass(volume)                                # droplet mass [kg]\n    R_drop = radius(volume=volume)                  # droplet radius\n    sigma = charge_density(surfaceV, layers)\n    \n    # Initial values\n    z0 = z0    # initial displacement\n    u0 = u0    # initial velocity\n    t0 = t0    # initial time\n\n    # Bundle parameters for ODE solver\n    params = (m, R_drop, sigma, q, Ef, del_Ef, zf)\n    \n    # Bundle initial conditions for ODE solver\n    y0 = [z0, u0]\n\n    # Make time array for solution\n    tInc = 0.00001\n    t_rk = np.arange(t0, tStop, tInc)\n\n    # Call the ODE solver\n    psoln = integrate.odeint(fun, y0, t_rk, args=(params,), mxords=5)\n    return psoln, t_rk\n```\n\n\n```python\n## error estimates from pyfssa\n## http://pyfssa.readthedocs.io/en/stable/nelder-mead.html\n#\n#def _neldermead_errors(sim, fsim, func, X0, *args):\n#    # fit quadratic coefficients\n#    fun = func\n#    args = args\n#    n = len(sim) - 1\n#    x = .5 * (sim[np.mgrid[0:n+1, 0:n+1]][1] + sim[np.mgrid[0:n+1, 0:n+1]][0])\n#\n#    for i in range(n + 1):\n#        assert(np.array_equal(x[i,i], sim[i]))\n#        for j in range(n + 1):\n#            assert(np.array_equal(x[i,j], 0.5 * (sim[i] + sim[j])))\n#\n#    y = np.nan * np.ones(shape=(n + 1, n + 1))\n#    for i in range(n + 1):\n#        y[i, i] = fsim[i]\n#        for j in range(i + 1, n + 1):\n#            y[i, j] = y[j, i] = fun(np.multiply(X0, x[i, j]), *args)\n#\n#    y0i = y[np.mgrid[0:n+1, 0:n+1]][0][1:,1:, 0]\n#    for i in range(n):\n#        for j in range(n):\n#            assert y0i[i, j] == y[0, i + 1], (i, j)\n#\n#    y0j = y[np.mgrid[0:n+1, 0:n+1]][0][0, 1:, 1:]\n#    for i in range(n):\n#        for j in range(n):\n#            assert y0j[i, j] == y[0, j + 1], (i, j)\n#\n#    b = 2 * (y[1:, 1:] + y[0, 0] - y0i - y0j)\n#    for i in range(n):\n#        assert abs(b[i, i] - 2 * (fsim[i + 1] + fsim[0] - 2 * y[0, i + 1])) < 1e-12\n#        for j in range(n):\n#            if i == j:\n#                continue\n#            assert abs(b[i, j] - 2 * (y[i + 1, j + 1] + fsim[0] - y[0, i + 1] -\n#                y[0, j + 1])) < 1e-12\n#\n#    q = (sim - sim[0])[1:].T\n#    for i in range(n):\n#        assert np.array_equal(q[:, i], sim[i + 1] - sim[0])\n#    \n#    varco = -np.dot(q, np.dot(np.linalg.inv(b), q.T)) # variance-covariance matrix\n#    #print(varco)\n#    w = np.abs(np.linalg.eig(varco)[0])\n#    cond = np.log10(np.nanmax(w)/np.nanmin(w))\n#    #print('condition number', cond)\n#    return np.sqrt(np.diag(varco))\n```\n\n\n```python\nimport scipy.optimize as opt\nimport scipy.interpolate as interp\n\ndef get_params(drop, a=3.5, **kwargs):\n    \"\"\"\n    Gets experimental parameters from drop object.\n    \"\"\"\n    layers = drop.layers\n    surfaceV = np.mean(drop.surfaceV)              # superhydrophobic surface potential\n    volume = drop.volume                           # droplet volume\n    if hasattr(drop, 'guess'):\n        q = drop.guess*1E-12*volume*surfaceV\n    else:\n        q = a*1E-12*volume*surfaceV                # wild-ass guess droplet net charge [C]\n    if 'test' in kwargs.keys() and kwargs['test']==True:\n        q = a*1E-12*volume*surfaceV\n    sigma = charge_density(surfaceV, layers)\n    t, y, dy, ddy = get_data(drop, param_est=True)\n    t0 = t[0]                                       # droplet initial time\n    y0 = y[0]                                       # droplet initial position\n    dy0 = dy[0]                                     # droplet initial y-velocity\n    return surfaceV, volume, q, sigma, t0, y0, dy0, layers  #remove sigma, m, R_drop\n\ndef get_constraints(drop):\n    \"\"\"\n    Gets the minimization problem constraints from the experimental measurement error for each parameter.\n    \"\"\"\n    \n    constraints = {'volume': 0.02,      # [m^3]\n                    'q': None,\n                    't0': 1/120.,       # [s]\n                    'y0': 0.02/100,     # [m]\n                  }\n    y, t, dy, ddy = get_data(drop, param_est=True)\n    y = y\n    dy = dy\n    constraints.update({'dy0': dy[0]*np.sqrt(1 + (constraints['y0']/(y[1]-y[0]))**2)})\n    if np.std(drop.surfaceV) > 0.:\n        constraints.update({'surfaceV': np.std(drop.surfaceV) + np.mean(drop.surfaceV)*0.2}) # [V]\n    else:\n        constraints.update({'surfaceV':100. + np.mean(drop.surfaceV)*0.2})\n    return constraints\n\ndef obj_func(x, *args):\n    \"\"\"\n    Pseudo-objective function with box bound constraints handles by exterior penalty function. The function to be \n    minimized is the chi2 goodness of fit between the experimental and model trajectories given the parameter\n    estimates (e.g. the design vector), x.\n    \"\"\"\n    \n    exp_data, model_params, constraints = args\n    surfaceV, volume, q, dy0 = x \n    t, y, dy, ddy = exp_data\n    yStop = y[-1]+10*(y[-1]-y[-2])\n    layers = model_params[5]\n    sigma = charge_density(surfaceV, layers)\n    Ef, del_Ef = electric_field(yStop, sigma)\n    zf = np.linspace(1E-6, yStop, 10000)\n    model_params = model_params + (Ef, del_Ef, zf)\n    psoln, t_rk = get_model(x, model_params)\n    #psoln = psoln[:,0]*100\n    #b = interp.interp1d(np.arange(psoln.size),psoln)\n    #y_soln = b(np.linspace(0,psoln.size-1,len(t)))\n    y_soln = np.array([])\n    for times in t:\n        y_soln = np.append(y_soln, np.interp(times, t_rk, psoln[:,0]))\n        \n    rp = 50  \n    penalty_function = rp * ( max(0,  volume/(model_params[3] + constraints['volume']) - 1)**2 \n                            + max(0, -volume/(model_params[3] - constraints['volume']) + 1)**2\n                            + 0.80* max(0,  surfaceV/(model_params[2] + constraints['surfaceV']) - 1)**2 \n                            + 0.80* max(0, -surfaceV/(model_params[2] - constraints['surfaceV']) + 1)**2\n                            + max(0, -q/(model_params[6]))**2)\n    return np.log(stats.chisquare(y,f_exp=y_soln,axis=0)[0]) + penalty_function\n        \ndef reporter(p):\n    \"\"\"Reporter function to capture intermediate states of optimization.\"\"\"\n    global sim\n    sim.append(p)\n    \ndef res(drop, a, **kwargs):\n    \"\"\"\n    Returns the parameter estimates of the drop experiment.\n    \"\"\"\n    global sim\n    exp_data = get_data(drop, param_est=True)\n    constraints = get_constraints(drop)\n    surfaceV, volume, q, sigma, t0, y0, dy0, layers = get_params(drop, a)\n    model_params = (t0, y0, surfaceV, volume, exp_data[0][-1], layers, q)\n    X0 = np.asarray((surfaceV, volume, q, dy0))\n    sim = [X0]\n    args = (exp_data, model_params, constraints)\n    result = opt.minimize(obj_func, X0, args=args, \n                          method='nelder-mead', options={'maxiter':300}, callback=reporter)\n    fsim = np.exp(np.array([obj_func(x, *args) for x in sim]))\n    result.fun = np.exp(result.fun)\n    #final_fsim = np.array([obj_func2(x, *args) for x in result.final_simplex[0]])\n    #try:\n    #    error = _neldermead_errors(np.divide(result.final_simplex[0],X0), \\\n    #                                         final_fsim, obj_func2, X0, *args)\n    #except AssertionError:\n    #    error = 'fail'\n    error = False\n    return result, sim, fsim, error\n```\n\n\n```python\ndef fmt(x):\n    \"\"\" For pretty printing chi^2 in scientific notation\"\"\"\n    x = float('%s' % float('%.1g' % x))\n    a, b = '{:.1e}'.format(x).split('e')\n    b = int(b)\n    return r'${} \\times 10^{{{}}}$'.format(a[0], b)\n```\n\n\n```python\ndef param_est_plot(drop, sub=False, method='nelder-mead', a=3.5, **kwargs):\n    if 'test' in kwargs.keys() and kwargs['test']==True:\n        exp_data = get_data(drop, param_est=True)\n        surfaceV, volume, q, sigma, t0, y0, dy0, layers = get_params(drop, a, test=True)\n        model_params = (t0, y0, surfaceV, volume, exp_data[0][-1], layers, q)\n        x = np.asarray((surfaceV, volume, q, dy0))\n    elif 'test' in kwargs.keys() and kwargs['test']==False and sub==False:\n        result, sim, fsim, error = res(drop, a)\n        x = result.x\n        #print(result)\n        #print(\"errors:\", error)\n        check_design_feasibility(drop, result)\n    else:\n        x = drop.result.x\n    \n    surfaceV, volume, q, sigma, t0, y0, dy0, layers = get_params(drop, a)\n    t, y, dy, ddy = get_data(drop, param_est=True)\n    model_params = (t0, y0, surfaceV, volume, t[-1], layers, q)\n    yStop = y[-1] + 20 * (y[-1]-y[-2])\n    sigma = charge_density(x[0], layers)\n    Ef, del_Ef = electric_field(yStop, sigma)\n    zf = np.linspace(1E-6, yStop, 10000)\n    model_params = model_params + (Ef, del_Ef, zf)\n    psoln, t_rk = get_model(x, model_params)\n    y_soln = np.array([])\n    dy_soln = np.array([])\n    for times in t:\n        y_soln = np.append(y_soln, np.interp(times, t_rk, psoln[:,0]*100))\n        dy_soln = np.append(dy_soln, np.interp(times, t_rk, psoln[:,1]*100))\n    \n    dx = (t[1]-t[0])\n    ddy_soln = np.gradient(dy_soln, dx, edge_order=2)\n    drop.y_soln = y_soln\n    drop.dy_soln = dy_soln\n    drop.ddy_soln = ddy_soln\n    y=y*100\n    if 'adding' in kwargs.keys() and kwargs['adding']==True:\n        return\n    \n    if 'forces' not in kwargs.keys() and sub==True:\n        i = kwargs['i']\n        fig = kwargs['fig']\n        axs = kwargs['axs'] \n        axs[i].plot(t[::], y[::], 'ko', \n                    markersize=6, markerfacecolor='white', markeredgecolor='black', label='experiment')\n        axs[i].plot(t,y_soln, 'r', label='model')\n        axs[i].set_title(r'$\\chi^2 =$ ' + fmt(drop.result.fun), fontsize=12)#'{0:.1E}'.format(drop.result.fun))\n        #axs[i].legend(title=drop.name)\n        #axs.set_xlabel('time')\n        #axs.set_ylabel('position')\n        #plt.tight_layout()\n        #plt.show()\n    elif 'forces' in kwargs.keys() and kwargs['forces']==True:\n        if 'sub' in kwargs.keys() and kwargs['sub']==True:\n            i = kwargs['i']\n            fig = kwargs['fig']\n            axs = kwargs['axs']\n            ep_force, drag_force, image_force, inertia = plot_forces(y_soln, dy_soln, ddy_soln, x, yStop, layers)\n            #plt.semilogy(t, dep_force, label='Dielectrophoretic force')\n            every = int(len(ep_force)/5)\n            n = 3\n            axs[i].semilogy(t[:-n], ep_force[:-n], 'rs--', label='Coulomb force', markevery=every)\n            axs[i].semilogy(t[:-n], drag_force[:-n], 'bo-', label='Drag force', markevery=every)\n            axs[i].semilogy(t[:-n], image_force[:-n], 'cv-.', label='Image force', markevery=every)\n            axs[i].semilogy(t[:-n], inertia[:-n], 'k+:', label='Inertia', markevery=every)\n        else:\n            n=20\n            ep_force, drag_force, image_force, inertia = plot_forces(y_soln, dy_soln, ddy_soln, x, yStop, layers)\n            #plt.semilogy(t, dep_force, label='Dielectrophoretic force')\n            plt.semilogy(y[:-n]/(d*100), ep_force[:-n]/inertia[:-n], 'r', alpha=0.75)\n            plt.semilogy(y[:-n]/(d*100), drag_force[:-n]/inertia[:-n], 'b', alpha=0.75)\n            plt.semilogy(y[:-n]/(d*100), image_force[:-n]/inertia[:-n], 'c', alpha=0.75)\n    else:\n        # Plot results\n        \n        if 'test' in kwargs.keys() and kwargs['test']==False and sub==False:\n            #plt.semilogy(range(len(errors)-1), -np.diff(errors))\n            fig = plt.figure()\n            plt.semilogy(range(len(fsim)), fsim, 'k')\n            plt.ylabel(r'$\\chi^2$')\n            plt.xlabel('Iteration number')\n            savefig('convergence', pics)\n            plt.show()\n            \n        if 'showall' in kwargs.keys() and kwargs['showall']==True and sub==False:\n            #fig = plt.figure()\n            plt.plot(t[::], y[::], 'ko', \n                        markersize=6, markerfacecolor='None', \n                     markeredgecolor='black', alpha=0.5)\n            plt.plot(t,y_soln, 'r')\n            #plt.xlabel('time (s)')\n            #plt.ylabel('position (cm)')\n            #plt.legend()\n            #plt.show()\n            return\n        \n        fig = plt.figure()\n        plt.plot(t[::], y[::], 'ko', \n                    markersize=6, markerfacecolor='white', markeredgecolor='black', label='experiment')\n        plt.plot(t,y_soln, 'r', label='model')\n        plt.xlabel('time (s)')\n        plt.ylabel('position (cm)')\n        plt.legend()\n        plt.show()\n                \n        plt.plot(y_soln[1:], ddy_soln[1:], 'k', label='model')\n        #plt.plot(y, ddy*100, 'b', label='data')\n        plt.ylabel('acceleration ($\\mbox{cm/}\\mbox{s}^2$)')\n        plt.xlabel('position (cm)')\n        plt.legend()\n        plt.show()\n        \n        plt.plot(t[1:], reynolds(dy_soln[1:], radius(volume=drop.volume)), 'k', label='model')\n        #plt.plot(y, ddy*100, 'b', label='data')\n        plt.ylabel('Re')\n        plt.xlabel('t (s)')\n        #plt.legend()\n        plt.show()\n        #print(cd(reynolds(dy_soln[1:], radius(volume=drop.volume)))[0])\n        \n        ep_force, drag_force, image_force, inertia = plot_forces(y_soln, dy_soln, ddy_soln, x, yStop, layers)\n        #plt.semilogy(t, dep_force, label='Dielectrophoretic force')\n        plt.semilogy(y/(d*100), ep_force/inertia, 'rs--', markevery=10)\n        plt.semilogy(y/(d*100), drag_force/inertia, 'bo-', markevery=10)\n        plt.semilogy(y/(d*100), image_force/inertia, 'cv-.', markevery=10)\n        #plt.semilogy(t, inertia, 'k+:', label='Inertia', markevery=10)\n        plt.ylabel('dimensionless force')\n        plt.xlabel(r'$y/L$')\n        plt.legend()\n        plt.show()\n    \ndef check_design_feasibility(drop, result):\n    #(surfaceV, volume, q, dy0)\n    print(result.fun)\n    #print(result.errors)\n    comp_params = get_params(drop)\n    print('nit', result.nit)\n    names = ['surfaceV', 'volume', 'q', 'dy0']\n    constraints = get_constraints(drop)\n\n    for n in range(len(result.x)):\n        try:\n            print('{},   {:.3} < {:.3}  < {:.3}'.format(names[n], \\\n                                                     comp_params[n]-constraints[names[n]],result.x[n], \\\n                                                     comp_params[n]+constraints[names[n]]))\n        except (TypeError, KeyError):\n            print('{},   {:.3} {:.3}'.format(names[n], result.x[n], comp_params[n]))\n            continue\n```\n\n\n```python\ndef plot_forces(z, u, du, results, yStop, layers):\n    z = z/100\n    u = u/100\n    du = du/100\n    surfaceV, volume, q, dy0 = results\n    sigma = charge_density(surfaceV, layers)\n    Ef, del_Ef = electric_field(yStop, sigma)\n    zf = np.linspace(1E-6, yStop, 10000)\n    R_drop = radius(volume=volume)\n    ef_interp = np.interp(z, zf, Ef)\n    del_ef_interp = np.interp(z,zf,del_Ef)\n    #force_dep(z, R_drop, del_ef_interp),\n    inertia = mass(volume)*du\n    return force_ep(q, ef_interp), drag(u, R_drop), force_image(z, q, R_drop), np.abs(inertia)\n```\n\n\n```python\n\"\"\"\nUse n=1,2,3 etc (where n may be 0 or any positive integer)  to look at an individual bounce.\nOtherwise use n='all' to see all bounces.\n\"\"\"\n\ndrop = drop07336\nprint_header(drop)\n#print(radius(volume=drop.result[1]))\n#print('Oh', ohnesorge(radius(volume=drop.volume)))\n#print('Bo', bond(drop))\n#plot_single(drop, parted=True, variable='y_parted');\n```\n\n\n```python\n#%time\na=drop.guess*1 #= a #1.9*2.3\nfig = plot_single(drop, parted=True, variable='y_parted', points=False, single=True)\nname = 'bounce_series'\npics= True\nplt.ylabel(r'$y$ (cm)')\nplt.xlabel(r'$t$ (s)')\nsavefig(name, pics)\nplt.show()\n#param_est_plot(drop, sub=False, method='nelder-mead', a=a, test=True) \n```\n\n\n```python\n#drop.guess = a\n```\n\n\n```python\n## #A bash program to write experiemental metadata.\n#header = {'name':1,'start':2,'end':3,'volume':4,'surfaceV':5, \\\n#          'frame_rate':6,'outlier':7,'time':8,'debias':9,'first_frame':10, 'layers':11, 'guess':12}\n#row = !grep -n \"{drop.name[4:]}\" ../data/dielectric_improved/meta.csv | cut -d , -f 1 | cut -d : -f 1\n#row = int(row[0])\n#col = header['guess']\n#value = drop.guess\n```\n\n\n```python\n#%%bash -s \"$row\" \"$col\" \"$value\"\n#awk -F \";\" -v r=$1 -v c=$2 -v val=$3 'BEGIN{OFS=\";\"}; NR != r; NR == r {$c = val; print}' \\\n#../data/dielectric_improved/meta.csv > ../data/dielectric_improved/meta2.csv\n#cp ../data/dielectric_improved/meta2.csv ../data/dielectric_improved/meta.csv\n#rm ../data/dielectric_improved/meta2.csv\n#cat ../data/dielectric_improved/meta.csv\n```\n\n### Series estimates\n\n\n```python\n#i = 0\n#a = 0.72*2.3 #2.2\n#for drop in alldrops:\n#    print(drop)\n#    (alldrops[drop].result, alldrops[drop].sim,\n#    alldrops[drop].fsim, alldrops[drop].error)  = res(alldrops[drop], a=a)\n#    param_est_plot(alldrops[drop], sub=True, adding=True)\n#    i += 1\n#\n```\n\n\n```python\nimport pickle\n#with open('../data/pickles/sorted_data.pkl', 'wb') as f:\n#    pickle.dump(alldrops, f)\n#alldrops_ba = alldrops\n```\n\n\n```python\nwith open('../data/pickles/sorted_data.pkl', 'rb') as f:\n    alldrops = pickle.load(f)\nsorted_keys = [elements[1] for elements in \\\n                 sorted([[vals.y_soln.max(), keys] for keys, vals in alldrops.items()])]\nsorted_vals = [alldrops[x] for x in sorted_keys]\nsorted_drops = dict(zip(sorted_keys, sorted_vals))\n```\n\n\n```python\nfrom math import ceil\n\nfig, axs = plt.subplots(4,ceil(len(alldrops)/4), figsize=(12, 10), facecolor='w', edgecolor='k')\nfig.subplots_adjust(hspace = .5, wspace=.3)\naxs = axs.ravel()\ni = 0\nfor drop in sorted_drops:\n    plot_single(sorted_drops[drop], parted=True, variable='y_parted', sub=True, i=i, fig=fig, axs=axs)\n    i += 1\n\nfig.text(0.5, -0.02, r'$t$ (s)', ha='center', fontsize=16, color='k')\nfig.text(-0.02, 0.5, r'$y$ (cm)', va='center', rotation='vertical', fontsize=16, color='k')\nfig.tight_layout()\n#plt.legend(loc=(1.2, 2.55), borderaxespad=0., fontsize=14)\nname = 'jump_matrix'\nsavefig(name, pics)\nplt.show()\n```\n\n\n```python\nfig, axs = plt.subplots(4,ceil(len(alldrops)/4), figsize=(12, 10), facecolor='w', edgecolor='k')\nfig.subplots_adjust(hspace = .5, wspace=.3)\naxs = axs.ravel()\ni = 0\nfor drop in sorted_drops:\n    param_est_plot(sorted_drops[drop], sub=True, method='Nelder-Mead', a=a, i=i, fig=fig, axs=axs)\n    i += 1\n\nfig.text(0.5, -0.02, r'$t$ (s)', ha='center', fontsize=16)\nfig.text(-0.02, 0.5, r'$y$ (cm)', va='center', rotation='vertical', fontsize=16)\n#plt.legend(loc=(1.2, 2.55), borderaxespad=0., fontsize=14)\nfig.tight_layout()\nname = 'inverse_problem'\nsavefig(name, pics)\nplt.show()\n```\n\n\n```python\n#fig, axs = plt.subplots(4,ceil(len(alldrops)/4), figsize=(12, 10), facecolor='w', edgecolor='k')\n#fig.subplots_adjust(hspace = .5, wspace=.3)\n#axs = axs.ravel()\n#i = 0\n#for drop in sorted_drops:\n#    param_est_plot(sorted_drops[drop], sub=True, method='Nelder-Mead', forces=True, a=a, i=i, fig=fig, axs=axs)\n#    i += 1\n#\n#fig.text(0.5, 0.06, r'$t$ (s)', ha='center', fontsize=14)\n#fig.text(0.06, 0.5, 'Force (N)', va='center', rotation='vertical', fontsize=14)\n#plt.legend(loc=(1.2, 2.45), borderaxespad=0., fontsize=14);\n#name = 'forces'\n#savefig(name, pics)\n#plt.show()\n```\n\n\n```python\nplt.figure()\nfor drop in sorted_drops:\n    param_est_plot(sorted_drops[drop], sub=False, method='Nelder-Mead', forces=True)\nplt.ylim(ymin=5E-3)\nplt.xlabel(r'$y/L$')\nplt.ylabel('Dimensionless force')\nplt.semilogy([],[],'r', label='Coulomb force', markevery=10)\nplt.semilogy([],[],'b', label='Drag force', markevery=10)\nplt.semilogy([],[],'c', label='Image force', markevery=10)\n#leg = plt.legend(loc=4)\n#leg.get_frame().set_linewidth(0.0)\nname = 'forces_all'\nsavefig(name, pics)\nplt.show();\n```\n\n\n```python\n#likely outliers\n#outliers = {#'drop07294':alldrops.pop('drop07294'),\n#            'drop07334':alldrops.pop('drop07334')}\n#alldrops['drop07334'] = outliers.pop('drop07334')\n    #surfaceV, volume, q, dy0\n```\n\n\n```python\ndef param_est(alldrops):\n    #surfaceV, volume, q, dy0\n    Ef0 = []\n    vols = []\n    qs = []\n    u0s = []\n    surfaceVs = []\n    for drop in alldrops.keys():\n        qs.append(alldrops[drop].result.x[2])\n        vols.append(alldrops[drop].result.x[1])\n        y = get_data(alldrops[drop], param_est=True)[1]\n        yStop = y[-1] + 20 * (y[-1]-y[-2])\n        sigma = charge_density(alldrops[drop].result.x[0], alldrops[drop].layers)\n        zf = np.linspace(1E-6, yStop, 10000)\n        R_0 = radius(volume = alldrops[drop].result.x[1])\n        Ef0.append(np.interp(radius(volume=alldrops[drop].result.x[1]), zf, electric_field(yStop, sigma)[0]))\n        alldrops[drop].Ef0 = Ef0[-1]\n        surfaceVs.append(alldrops[drop].result.x[0])\n        u0s.append(alldrops[drop].result.x[3])\n    return np.array(vols), np.array(qs), np.array(u0s), np.array(surfaceVs), np.array(Ef0)\n\nvols, qs, u0s, surfaceVs, Ef0 = param_est(alldrops)\n```\n\n\n```python\ndef drop_planning_plots(surfaceVs, vol, qs, **kwargs):\n    x = np.array(surfaceVs)/1000\n    y = vol\n    z = qs\n    plt.plot(x,y,'.')\n    plt.xlabel(r'$\\varphi$ (kV)')\n    plt.ylabel('$V_d$ (mL)')\n    plt.show()\n    \n    xi = np.linspace(min(x), max(x), 50)\n    yi = np.linspace(min(y),max(y), 50)\n    Z = matplotlib.mlab.griddata(x, y, z, xi, yi, interp='linear')\n    X, Y = np.meshgrid(xi, yi)\n\n    fig = plt.figure()\n    #ax = Axes3D(fig)\n    #ax.scatter(x, vols, qs, c='k', marker='o', s=40)\n\n    #norm = Normalize(vmin=np.min(Z), vmax=np.max(Z))\n    #surf = ax.plot_surface(X,Y,Z, linewidth=1,\n    #                       antialiased=True, cstride=2, \n    #                       rstride=2, edgecolor='k',\n    #                       cmap=cm.jet, alpha=0.3, norm=norm)\n    #fig.colorbar(surf, label=r'$q$ (C)')\n    #ax.view_init(90, 35-90)\n    CS = plt.contourf(X,Y,Z,cmap=plt.cm.bone)\n    plt.scatter(x, y, color='k', facecolors='white', edgecolors='k')\n    #CS2 = plt.contour(CS, levels=CS.levels[::2], colors='white')\n    #fmt = matplotlib.ticker.LogFormatterMathtext()\n    #fmt.create_dummy_axis()\n    #manual_locations = [(-1, -1.4), (-0.62, -0.7), (-2, 0.5)]\n    #plt.clabel(CS2, inline=1, colors='w', fontsize=10, fmt=fmt, manual=manual_locations)\n    cbar = plt.colorbar(CS)\n    cbar.ax.set_ylabel('$q$ (C)')\n    #cbar.add_lines(CS2)\n    plt.xlabel(r'$\\varphi_s$ (kV)')\n    plt.ylabel(r'$V_d$ (mL)')\n    #ax.set_xlabel(r'$E_0$ (kV/cm)')\n    #ax.set_ylabel(r'Volume (mL)')\n    #ax.set_zticks([])\n    #ax.set_zlabel(r'$q$ (C)')\n    if 'savefig' in kwargs.keys() and kwargs['savefig']==True:\n        name = 'charge'\n        savefig(name, pics)\n    plt.show()\n    \ndrop_planning_plots(surfaceVs, vols, qs, savefig=True)\n#print(qs)\n```\n\n\n```python\n#from sympy import *\n#init_printing()\n#\n#y, z, nu, a = symbols('y z nu a')\n#nu*integrate(z/((z**2 + y**2)*sqrt(z**2 + y**2 + a**2/4)), (y,0,a/2))\n```\n\n\n```python\ndef hysteresis_plot():\n    # relating apparent contact angle hysteresis to \n    # roll-off angle using the model of Furmidge, J. Colloid Sci. 1962, 17, 309.\n    # 2 mL data for DDT surfaces\n\n    #%config InlineBackend.figure_formats = ['svg']\n    #matplotlib.rcParams['text.usetex'] = True\n    #matplotlib.rcParams['text.latex.preamble'] = [r'\\usepackage{amsmath}']\n    #matplotlib.rcParams['text.latex.unicode'] = True\n    #matplotlib.rcParams.update(pgf_with_latex)\n    n = np.linspace(5,25,5)\n    a = np.linspace(130,180,100)\n    const = -10\n    colors = plt.cm.cool_r(np.linspace(0,1,len(n)))\n\n    for k,i in np.ndenumerate(n):\n        b = a - i\n        hyster = np.arcsin(np.cos(a*np.pi/180)-np.cos(b*np.pi/180))\n        plt.plot(a, const*hyster, label=int(i), color=colors[k], zorder=1)\n\n    exp_roll_off = 2.8\n    exp_CA_appar = 148\n    plt.scatter([exp_CA_appar,138],[exp_roll_off,2],100, marker=\"v\", facecolors='r', edgecolors='m', zorder=2)\n    plt.annotate('laser-etched PMMA ($R_q \\sim 775 \\mu m$)', xy=(exp_CA_appar,exp_roll_off), xycoords='data', \n                xytext=(15, 30), textcoords='offset points', fontsize=10, \n                arrowprops=dict(arrowstyle=\"->\", connectionstyle=\"arc3, rad=.47\"))\n    plt.annotate('', xy=(138,2), xycoords='data', \n                xytext=(85,74), textcoords='offset points', fontsize=10, \n                arrowprops=dict(arrowstyle=\"->\", connectionstyle=\"arc3, rad=.2\"))\n\n    plt.scatter([158,],[2,],100, marker=\"o\", facecolors='b', edgecolors='c', zorder=2)\n    plt.annotate('sandpaper ($R_q \\sim 30 \\mu m$)', xy=(158,2), xycoords='data', \n                xytext=(-10, 40), textcoords='offset points', fontsize=10, \n                arrowprops=dict(arrowstyle=\"->\", connectionstyle=\"arc3, rad=.5\"))\n\n    plt.legend(title=r'$\\theta_r - \\theta_a$', loc='upper right')\n    axes = plt.gca()\n    axes.set_xlim(135,180)\n    plt.xticks([140,150, 160,170, 180])\n    plt.ylabel(r'$\\alpha$')\n    plt.xlabel(r'$\\theta$')\n    name = 'hysteresis'\n    savefig(name, pics)\n    plt.show()\n\nhysteresis_plot()\n```\n\n\n```python\ndef impact_data(drop):\n    \"\"\"\n    Returns Weber numbers, contact times, and coefficients of restituion for each bounce event in a drop.\n    \"\"\"\n    ym, t, dt, contact_mask, y_parted, dy_parted, ddy_parted, t_parted, ind_parted = get_data(drop, param_est=False)\n    ind_parted = ind_parted[1:-1]\n    impact_weber = weber(drop, dy_parted[ind_parted])[::2]\n    ind_parted = ind_parted.tolist()\n    contact_time = np.array([])\n    diameter_ratio = np.array([])\n    restitution = np.array([])\n    for keys, vals in enumerate(ind_parted[::2]):\n        ind_parted.index(ind_parted[::2][keys])\n        pair = [ind_parted[::2][keys], ind_parted[ind_parted.index(ind_parted[::2][keys])+1]]\n        contact_time = np.append(contact_time, t_parted[pair[1]]-t_parted[pair[0]])\n        restitution = np.append(restitution, abs(dy_parted[pair[1]]/dy_parted[pair[0]]))\n        \n        # Note: I scale the contact time by a parameter such that it \n        # gives the same results as a manual count of frames.\n    try:\n        tb = t_parted[ind_parted[0]]\n    except IndexError:\n        tb = False\n    return impact_weber, contact_time*.78, diameter_ratio, restitution*.78, tb #0.78\n\ndef q_to_m(drop):\n    #surfaceV, volume, q, dy0\n    density = 1000\n    U = drop.dy_soln[0]/100 #drop.result.x[3]\n    old_inertia = density * 2 * radius(volume=drop.result.x[1])**2 * U**2\n    old_e_force = charge_density(drop.result.x[0], drop.layers)*eta_0*drop.result.x[2]\n    #e_force = drop.result.x[0]/2.54*100*drop.result.x[2]\n    e_force = drop.Ef0*drop.result.x[2]\n    inertia = mass(drop.result.x[1]) * U**2\n    eu_s = inertia/(e_force*radius(volume=drop.result.x[1]))\n    phi = 4 * np.pi *radius(volume=drop.result.x[1])**2/d**2\n    eu_m = inertia/(e_force*d)\n    qm = drop.result.x[2]/mass(drop.result.x[1])\n    return eu_s, 2*phi**2*eu_s, eu_m, qm, phi\n\ndef img(drop):\n    q = drop.result.x[2]\n    rad = radius(volume=drop.result.x[1])\n    eta_a=eta_r\n    susceptibility = eta_a - 1\n    k = susceptibility/(susceptibility+2)\n    return k * q /(16*np.pi*eta_0*rad**2*drop.Ef0)\n    \ndef tc(drop):\n    epss, epsl, epsm, qm, phi = q_to_m(drop)\n    epsl = epss*phi\n    tc_s = epss*radius(volume=drop.result.x[1])/(drop.result.x[3])\n    #tc_l = epsl*radius(volume=drop.result.x[1])/(drop.result.x[3])\n    tc_l = epss*phi*radius(volume=drop.result.x[1])/(drop.result.x[3])\n    tfl = 0.456229037652571*epsl**3 + 0.799200144*epsl**2 + 1.33293333333333*epsl + 2\n    tfs = (-4*epss**2*(0.0121*epss + 0.2121)*(2*(0.0121*epss + 0.2121)**4 + \n        6*(0.0121*epss + 0.2121)**3 - 4*(0.0121*epss + 0.2121)**2 + 1)/\n    (0.363*epss + 40*(0.0121*epss + 0.2121)**3 + 60*(0.0121*epss + 0.2121)**2 + 11.363) \n    + 4*epss*(-0.0121*epss + 0.7879)*(0.0121*epss + 0.2121)/(3*(0.0242*epss + 1.4242)) + 2)\n    tc_m = epsm*radius(volume=drop.result.x[1])/(drop.result.x[3])\n    return tc_s, tc_l, tfl, tfs, tc_m\n\ndef yc(drop):\n    epss, epsl, epsm, qm, phi = q_to_m(drop)\n    epsl = epss*phi\n    yc_s = epss*radius(volume=drop.result.x[1])*100\n    yc_l = epsl*radius(volume=drop.result.x[1])*100\n    yc_m = epsm*radius(volume=drop.result.x[1])*100\n    return yc_s, yc_l, yc_m\n\ndef yf(drop):\n    epsilon, phi = q_to_m(drop)[0], q_to_m(drop)[4]\n    alpha = img(drop)\n    epsilonl = epsilon*phi\n    yfl = (0.00997118232863575*epsilonl**4 + 0.0180903441714801*epsilonl**3\n    - 0.0972943974999999*epsilonl**2 + 0.2498375*epsilonl + 1/2)\n    yfs = (epsilon**3*(alpha*(-17*alpha - 12)/60 + alpha*(73*alpha**2 + 117*alpha + 45)/630 \n                      + alpha*(-73*alpha**3 - 190*alpha**2 - 162*alpha - 45)/5040 + alpha/5) + \n    epsilon**2*(alpha*(11*alpha + 9)/60 + alpha*(-11*alpha**2 - 20*alpha - 9)/360 - alpha/4) + \n    epsilon*(alpha*(-alpha - 1)/12 + alpha/3) + 1/2)\n    return yfl, yfs\n\ndef molacek(bo, web):\n    st = 72.86/1000\n    density = 1000\n    #rad = radius(volume=drop.result.x[1])\n    #density* rad**3/st\n    return (2*(np.log(1/bo)/3 + 0.192/np.log(1/bo))**(1/2) * \n            (np.pi - np.arccos((1 + 3.*web/(bo**2 * np.log(1./bo)))**(-1/2))))\n\ndef impact_plots(alldrops):\n    #fig1, ax1 = plt.subplots()\n    qm = np.array([])\n    i_weber = np.array([])\n    contact_r = np.array([])\n    restn = np.array([])\n    oh = np.array([])\n    bo = np.array([])\n    \n    for keys in alldrops:\n        impact_weber, contact_time, diameter_ratio, restitution, tb = impact_data(alldrops[keys])\n        if impact_weber.size != 0:\n                    qm = np.append(qm, impact_weber.size*[q_to_m(alldrops[keys])[0]])\n                    R_drop = radius(volume=alldrops[keys].result.x[1])\n                    oh = np.append(oh, impact_weber.size*[ohnesorge(alldrops[keys])])\n                    bo = np.append(bo, impact_weber.size*[bond(alldrops[keys])])\n        i_weber = np.append(i_weber, impact_weber)\n        restn = np.append(restn, restitution)\n        contact_r = np.append(contact_r, contact_time/tj(alldrops[keys]))\n        alldrops[keys].tb = tb\n        print(keys, restitution)\n    print(np.average(i_weber), np.std(i_weber))\n    \n    fig = plt.figure()\n    norm = matplotlib.colors.Normalize(vmin=bo.min(), vmax=bo.max())\n    cmap = plt.cm.rainbow\n    plt.scatter(i_weber, contact_r, c=bo, cmap=cmap, norm=norm)\n    cb1 = plt.colorbar()\n    cb1.set_label(r'$\\mathrm{\\mathit{Bo_e}} \\equiv \\frac{\\epsilon E_0^2 R_d}{\\gamma}$')\n    \n    plt.xscale('log')\n    plt.xticks([10**(-2),10**(-1),10**0])\n    #plt.grid(which='both', linestyle='--')\n    webers = np.linspace(10**(-2),.99, 100)\n    bos = [0.4,.6,.8]\n    plt.plot(webers, 2.2*np.ones(len(webers)), 'k--', label='Richards, 2001')\n    plt.plot(webers, np.log(1/webers) + 2.31, linestyle='-.', color='grey', \n             label='Gopinath et al., 2002')\n    plt.plot(webers, molacek(0.1, webers), c=cmap(norm(0.4)),\n             label='Molacek et al., 2012, $\\mathbf{B}\\mbox{o} = $' + '{}'.format(0.2))\n    for boo in bos:\n        plt.plot(webers, molacek(boo, webers), c=cmap(norm(boo)), \n                 label='..., $\\mathbf{B}\\mbox{o} = $' + '{}'.format(boo))\n    \n    plt.legend(loc=2)\n    plt.xlabel('$\\mathbf{W}\\mbox{e}$')\n    plt.ylabel(r'$t_j/ \\tau$')\n    plt.ylim(ymin=2)\n    plt.xlim(xmin=5E-2)\n    name = 'contact2'\n    savefig(name, pics)\n    plt.show()\n   \n    fig = plt.figure()\n    plt.scatter(i_weber, restn, c=bo, cmap=plt.cm.rainbow, norm=norm)\n    plt.xscale('log')\n    plt.xticks([10**(-2),10**(-1),10**0])\n    #plt.grid(which='both', linestyle='--')\n    cb2 = plt.colorbar()\n    cb2.set_label(r'$\\mathrm{\\mathit{Bo_e}} \\equiv \\frac{\\epsilon E_0^2 R_d}{\\gamma}$')\n    plt.xlabel('$\\mathbf{W}\\mbox{e}$')\n    plt.ylabel('$C_r$')\n    name = 'restitution'\n    bbox_props = dict(boxstyle=\"round\", fc=\"w\", ec=\"0.5\", alpha=0.7)\n    plt.text(1.5E-2,.75,r'$\\mathbf{O}\\mbox{h}_{\\mu} = 2.2$', bbox=bbox_props)\n    savefig(name, pics)\n    plt.show()\n```\n\n\n```python\neus0s = np.array([])\nbs = np.array([])\nqss = np.array([])\nfor drop in alldrops: \n    eus0, b, c, qm, phi = q_to_m(alldrops[drop])\n    eus0s = np.append(eus0s, eus0)\n    bs = np.append(bs, b)\n    qss = np.append(qs, qm)\n#escp, vols = (list(t) for t in zip(*sorted(zip(escp, vols))))\n#plt.figure()\n#plt.plot(vols, eus0,\n#         'ko', markersize=6, markerfacecolor='white', markeredgecolor='black')\n#plt.ylabel(r'$\\mathbf{E}\\mbox{u}$')\n#plt.xlabel(r'$V_d$')\n#name = 'eu_vs_vol'\n#savefig(name, pics)\n#plt.show()\ndef tof(dim):\n    return 2+1.333*dim + 0.700*dim**2\nprint(eus0s)    \nprint(bs*eus0s/(8*np.pi))\ntof(bs*eus0s)\nprint(qs)\n```\n\n\n```python\nimpact_plots(alldrops)\n```\n\n\n```python\n#figure_series = {'drop07296':drop07296, 'drop07327':drop07327, 'drop07295':drop07295,\n#                 'drop07335':drop07335, 'drop07319':drop07319, 'drop07300':drop07300,\n#                 'drop07325':drop07325, 'drop07326':drop07326}\n#\nfigure_series = ['drop07296','drop07327','drop07295',\n                 'drop07335','drop07319', 'drop07300', 'drop07325', 'drop07326']\n\nkeys = [elements[1] for elements in \n                 sorted([[alldrops[vals].y_soln.max(), vals] for vals in figure_series], reverse=True)]\nsorted_drops2 = dict(zip(keys, [alldrops[key] for key in keys]))\n```\n\n\n```python\n#sorted_keys2 = [elements[1] for elements in \n#                 sorted([[vals.y_soln.max(), keys] for keys, vals in figure_series.items()], reverse=True)]#[::-1]\n#sorted_vals2 = [figure_series[x] for x in sorted_keys2]#[::-1]\n#sorted_drops2 = dict(zip(sorted_keys2, sorted_vals2))\n\n\n['y_soln' in dir(sorted_drops2[drop]) for drop in sorted_drops2]\n\ni = 0\nfor drop in sorted_drops2:\n    param_est_plot(sorted_drops2[drop], sub=False, method='Nelder-Mead', a=a, i=i, fig=fig, axs=axs, showall=True)\n    i += 1\n\nplt.xlabel('$t$ (s)')\nplt.ylabel('$y$ (cm)')\nplt.legend(loc='best')\nplt.plot([],[],'ko', markersize=6, markerfacecolor='None', \n                     markeredgecolor='black', label='experiment')\nplt.plot([],[],'r-', label='model')\n\nleg = plt.legend(loc='best')\nleg.get_frame().set_linewidth(0.0)\nfor text in leg.get_texts():\n    text.set_color('k')\nname = 'forces_all'\nname = 'inverse_problem2'\nsavefig(name, pics)\nplt.show()\n```\n\n\n```python\nsorted_keys = [elements[1] for elements in \\\n                 sorted([[q_to_m(vals), keys] for keys, vals in alldrops.items()])]\n```\n\n\n```python\ncol = 'viridis_r' #'rainbow_r'\n\n#m=-5\n#sorted_vals = [alldrops[x] for x in sorted_keys[:m]]\n#sorted_drops = dict(zip(sorted_keys, sorted_vals))\n#plot_series(alldrops, component='YM', qm=True, label=[r'$t$ (s)', r'$y$ (cm)'], col=col)\n#plot_series(figure_series, component='YM', qm=True, label=[r'$t$ (s)', r'$y$ (cm)'], \n#            savefig=True, reg = 's', name='series_s_eu', col=col)\n\nn = -4\nm = -1\nsorted_vals = [alldrops[x] for x in sorted_keys[:n]]\nsorted_drops = dict(zip(sorted_keys, sorted_vals))\nplot_series(sorted_drops, component='YM', qm=True, label=[r'$t^*$', r'$y^*$'], \n            savefig=False, reg = 's', dimless = True, name='series_s_ds', col=col)\n\n#\n#n = -5\n#sorted_vals = [alldrops[x] for x in sorted_keys[n:]]\n#sorted_drops = dict(zip(sorted_keys, sorted_vals))\n#plot_series(sorted_drops, component='YM', qm=True, label=[r'$\\bar{t}$',r'$\\bar{y}$'], \n#            savefig=True, reg = 'l', dimless = True, name='series_l_ds', col=col)\n#\n```\n\n\n```python\nn = -1\nm = 0\nsorted_vals = [alldrops[x] for x in sorted_keys[:n]]\nsorted_drops = dict(zip(sorted_keys, sorted_vals))\nplot_series(sorted_drops2, component='YM', qm=True, label=[r'$t$ (s)', r'$y$ (cm)'], \n            savefig=True, reg = 's', dimless = False, name='series', col=col)\n```\n\n\n```python\n#escape = []\n#for drop in alldrops:\n#    escape.append(8*np.pi()*radius(alldrops[drop])**2/d**2)\n#print(np.average(os), np.std(os))\n```\n\n\n```python\ndef find_nearest(array,value):\n    idx = (np.abs(array-value)).argmin()\n    return idx\n\n#print(650*eta_0/(2.54/100), 'field meter')\n#print(650*eta_0/(2.54/100), 'non-contacting voltmeter')\n#print(650*eta_0*3/(0.4*5/1000), 'nc-voltmeter w/ dielectric back by conductive groundplane')\n\ndrop = alldrops['drop07298']\n\nef = electric_field(40/100, charge_density(drop.result.x[0], drop.layers))[0]\nz = np.linspace(1/1000, 40/100, 10000)\n\nE0 = charge_density(drop.result.x[0], drop.layers)/(2*eta_0)\nplt.loglog(z/(6.5/100), ef/E0, 'k')\nplt.ylabel(r'$E/E_0$')\nplt.xlabel(r'$y/L$')\nprint(E0/1000/100)\n\nname = 'E0'\nsavefig(name, pics)\nplt.show()\n\n#print(np.interp(2.54/100,z,ef)/1000, 'electric field at 2.54 cm')\n```\n\n\n```python\n#for drop in sorted_drops:\n#    print(drop)\n#    check_design_feasibility(sorted_drops[drop], sorted_drops[drop].result)\n#    print('\\n')\n```\n\n\n```python\nEf0\n```\n\n\n```python\nimport pandas\nfrom statsmodels.formula.api import ols, rlm, WLS\nfrom pandas import plotting\nimport seaborn\n\ndef scatter_matrix(x):\n    area, qs, u0s, surfaceVs, Ef0 = x\n    data = pandas.DataFrame({'area':area, 'charge':qs, 'u0': u0s, 'Ef0':Ef0/100/1000})\n    plotting.scatter_matrix(data, diagonal='density', c='k');\n    prod = area*Ef0\n    data = pandas.DataFrame({'area':area, 'charge':qs, 'u0': u0s, 'Ef0':Ef0, 'prod': prod})\n    model = ols('charge ~  prod - 1', data)\n    #model = rlm('charge ~  area * Ef0', data)\n    #r2_wls = WLS(model.endog, model.exog, weights=model.fit().weights).fit().rsquared\n    print(model.fit().summary())\n    #print(r'R^2 = {}'.format(r2_wls))\n\narea = (vols/1E6)**(2/3)\nvariables = (area, qs, u0s, surfaceVs, Ef0)\nscatter_matrix(variables)\nname = 'scatter'\nsavefig(name, pics)\nplt.show()\n\nplt.scatter(qs, area*Ef0)\nplt.xlim(0.25E-10, 0.6E-9)\nplt.show()\n```\n\n\n```python\n#plt.scatter(area*Ef0, qs, color='k')\n#data = pandas.DataFrame({'charge':qs,'prod': area*Ef0})\n#model = ols('charge ~  prod', data).fit()\n#inter, coef = model._results.params\n#f = lambda x: x*coef + inter\n#x = np.linspace(0, (area*Ef0).max(), 100)\n#plt.plot(x, f(x), 'r') \n#plt.ylim(1E-11, 1E-9)\n#plt.show()\n#model.summary()\n```\n\n\n```python\nparallel = np.abs(np.array([ -2.70158796e-12,  -4.20176010e-12,   7.78928795e-12,  -4.86568450e-12,\n  -1.79171842e-12,  -1.74111697e-11,  -1.07898239e-11,  -5.68331113e-12,\n  -2.89082418e-12,  -2.57343722e-12,  -1.30402067e-11,  -7.51379045e-13,\n   1.11525974e-12,  -9.83808965e-13,  -6.00145897e-13,  -2.84923705e-12,\n  -9.78463511e-12]))\nstats.ttest_ind(qs, parallel, equal_var=False)\n```\n\n\n```python\nfrom statsmodels.stats.anova import anova_lm\nims = np.array([])\neus = np.array([])\nphis = np.array([])\nplt.figure()\nfor drop in alldrops:\n    eus = np.append(eus, q_to_m(alldrops[drop])[0])\n    ims = np.append(ims, img(alldrops[drop]))\n    phis = np.append(phis, q_to_m(alldrops[drop])[4])\n\n# Convert the data into a Pandas DataFrame to use the formulas framework\n# in statsmodels\ndata = pandas.DataFrame({'Eu': eus, 'Im': ims, 'Phi':phis})\n\n# Fit the model\nmodel = ols(formula=\"Im ~ Eu\", data=data).fit()\noffset, coef = model._results.params\nplt.plot(eus, eus*coef + offset, 'k-', alpha=0.3,\n         label=r'$\\mathbf{I}\\mbox{g} \\approx 0.013 \\mathbf{E}\\mbox{u} + 0.230$, $R^2=0.57$')\nplt.scatter(eus, ims, color='w', edgecolors='k')\n\nplt.xlabel(r'$\\mathbf{E}\\mbox{u}$')\nplt.ylabel(r'$\\mathbf{I}\\mbox{g}$')\nplt.legend()\nname = 'dnumbs'\nsavefig(name, pics)\nplt.show()\n\n# Fit the model\n#model = ols(formula=\"Im ~ Phi\", data=data).fit()\n#offset, coef = model._results.params\nplt.scatter(ims, 10*phis)\nplt.show()\n```\n\n\n```python\n# Print the summary\nprint(model.summary())\n\n# Peform analysis of variance on fitted linear model\nanova_results = anova_lm(model)\n\nprint('\\nANOVA results')\nprint(anova_results)\n\n```\n\n\n```python\nsorted_keys = [elements[1] for elements in \\\n                 sorted([[vals.y_soln.max(), keys] for keys, vals in alldrops.items()])]\nm=-5\nsorted_vals = [alldrops[x] for x in sorted_keys[:m]]\nsorted_drops = dict(zip(sorted_keys, sorted_vals))\n\nbo = np.array([alldrops[x].Ef0*alldrops[x].volume for x in sorted_keys[:m]])\nnorm = matplotlib.colors.Normalize(vmin=bo.min(), vmax=bo.max())\ncmap = plt.cm.rainbow\ntbl = np.array([])\ntcl = np.array([])\neus = np.array([])\nybl = np.array([])\nycl = np.array([])\ntk = np.array([])\nyk = np.array([])\nline = np.arange(0.2,1,100)\nfor drop in sorted_drops:\n    #print(2*sorted_drops[drop].tb/tc(sorted_drops[drop])[3])\n    tbl = np.append(tbl, sorted_drops[drop].tb)\n    tcl = np.append(tcl, tc(sorted_drops[drop])[0]*tc(sorted_drops[drop])[2])\n    ybl = np.append(ybl, sorted_drops[drop].data['YM'].max())\n    ycl = np.append(ycl, yc(sorted_drops[drop])[0]*yf(sorted_drops[drop])[0])\n    tk = np.append(tk,tc(sorted_drops[drop])[0])\n    yk = np.append(yk, yc(sorted_drops[drop])[0])\n    eus = np.append(eus, q_to_m(sorted_drops[drop])[0])\ndata = pandas.DataFrame({'tb': tbl, 'tof': tcl})\n\n# Fit the model\nmodel = ols(formula=\"tof ~ tb\", data=data).fit()\noffset, coef = model._results.params\nprint(1/coef)\n#plt.plot(tbl, tbl*coef + offset, 'k-')\nplt.scatter(tbl, tcl, color='None', edgecolors='k', label='$\\mathcal{O}(\\phi^3 \\mathbf{E}\\mbox{u}^3)$')\nplt.scatter(tbl, tk*2, color='None', marker='s', edgecolors='r', label='$\\mathcal{O}(1)$')\n#cb1 = plt.colorbar()\n#cb1.set_label(r'$\\mathbf{E}\\mbox{u}$')\nplt.xlabel(r'${t_b}$ (s)')\nplt.ylabel(r'$t_c t_f$ (s)')\nleg = plt.legend()\nleg.get_frame().set_linewidth(0.0)\nfor text in leg.get_texts():\n    text.set_color('k')\nname = 'times'\nsavefig(name, pics)\nplt.show()\n#model.summary()\n\n#plt.scatter(tbl/tcl, eus, color='w', edgecolors='k')\n#plt.scatter(tbl/(tk*2), eus, color='w', edgecolors='r')\n#plt.show()\n\n#print(tbl)\n\n#sorted_keys = [elements[1] for elements in \\\n#                 sorted([[vals.y_soln.max(), keys] for keys, vals in alldrops.items()])]\n#sorted_vals = [alldrops[x] for x in sorted_keys]\n#sorted_drops = dict(zip(sorted_keys, sorted_vals))\n#tbl = np.array([])\n#tcl = np.array([])\n#for drop in sorted_drops:\n#    #print(2*sorted_drops[drop].tb/tc(sorted_drops[drop])[3])\n#    tbl = np.append(tbl, sorted_drops[drop].tb)\n#    tcl = np.append(tcl, tc(sorted_drops[drop])[0]*tc(sorted_drops[drop])[2])\n#print(tcl)\n```\n\n\n```python\nsorted_keys = [elements[1] for elements in \\\n                 sorted([[q_to_m(vals), keys] for keys, vals in alldrops.items()])]\nn = -1\nm = -1\nsorted_vals = [alldrops[x] for x in sorted_keys[:n]]\n#del sorted_vals[-2]\nsorted_drops = dict(zip(sorted_keys, sorted_vals))\n\nybl = np.array([])\nycl = np.array([])\neus = np.array([])\nyk = np.array([])\nline = np.arange(0.2,1,100)\nfor drop in sorted_drops:\n    #print(2*sorted_drops[drop].tb/tc(sorted_drops[drop])[3])\n    ybl = np.append(ybl, sorted_drops[drop].data['YM'].max())\n    ycl = np.append(ycl, yf(sorted_drops[drop])[0])\n    yk = np.append(yk, yc(sorted_drops[drop])[0])\n    eus = np.append(eus, q_to_m(sorted_drops[drop])[0])\ndata = pandas.DataFrame({'ymax': ybl, 'ycl': ycl*yk})\n\n# Fit the model\nmodel = ols(formula=\"ycl ~ ymax\", data=data).fit()\noffset, coef = model._results.params\nprint(1/coef)\n\nplt.figure()\nplt.scatter(eus, ybl/(yk), color='w', edgecolors='k')\nplt.ylabel(r'${y_{max}}/y_c$')\nplt.xlabel(r'$\\mathbf{E}\\mbox{u}$')\n#plt.xlim(0.4,1.5)\n#plt.ylim(0,2)\nname = 'yscale_trend'\nsavefig(name, pics)\nplt.show()\n\nplt.scatter(ybl, yk*ycl, color='None', edgecolors='k', label='$\\mathcal{O}(\\phi^3 \\mathbf{E}\\mbox{u}^3)$')\nplt.scatter(ybl, yk*0.5, color='None', marker='s', edgecolors='r', label='$\\mathcal{O}(1)$')\nplt.ylabel(r'$y_c y_f$ (cm)')\nplt.xlabel(r'$y_{max}$ (cm)')\n#plt.ylim(0,2.3)\nleg = plt.legend()\nleg.get_frame().set_linewidth(0.0)\nfor text in leg.get_texts():\n    text.set_color('k')\nname = 'ymaxes'\nsavefig(name, pics)\nplt.show()\n```\n\n\n```python\neus\n```\n\n\n```python\n#m = -1\n#sorted_vals = [alldrops[x] for x in sorted_keys[:m]]\n#sorted_drops = dict(zip(sorted_keys, sorted_vals))\n#\n#bo = np.array([q_to_m(alldrops[x])[0] for x in sorted_keys[:m]])\n#norm = matplotlib.colors.Normalize(vmin=bo.min(), vmax=bo.max())\n#cmap = plt.cm.rainbow\n#\n#tbs = np.array([])\n#tcs = np.array([])\n#for drop in sorted_drops:\n#    tbs = np.append(tbs, sorted_drops[drop].tb/tc(sorted_drops[drop])[0])\n#    tcs = np.append(tcs, tc(sorted_drops[drop])[3])\n#\n#plt.scatter(tbs, tcs, c=bo, cmap=cmap, norm=norm)\n#cb1 = plt.colorbar()\n#cb1.set_label(r'$\\mathbf{E}\\mbox{u}$')\n#plt.xlabel(r'$\\frac{t_b}{t_c}$')\n#plt.ylabel(r'$t_f$')\n#plt.ylim(ymin=1.9, ymax=2.2)\n#plt.xlim(xmin = 2.5, xmax=3)\n#name = 'times_short'\n#savefig(name, pics)\n#plt.show()\n```\n\n\n```python\ntk = tc(alldrops['drop07296'])\nprint(tk[1]*113.75340697961346)\nprint(yc(alldrops['drop07296'])[1]/d)\n```\n\n\n```python\ndrop = 'drop07296'\ny_soln = alldrops[drop].y_soln\nt = get_data(alldrops[drop], param_est=True)[0]\n\nplt.plot(t, y_soln)\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "111c0100513658d39185002d6b593e6beb84f93d", "size": 94727, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "src/cp_param.ipynb", "max_stars_repo_name": "7deeptide/Thesis_scratch", "max_stars_repo_head_hexsha": "d776d57f642de4df718c1f655f080c8fe402e092", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cp_param.ipynb", "max_issues_repo_name": "7deeptide/Thesis_scratch", "max_issues_repo_head_hexsha": "d776d57f642de4df718c1f655f080c8fe402e092", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cp_param.ipynb", "max_forks_repo_name": "7deeptide/Thesis_scratch", "max_forks_repo_head_hexsha": "d776d57f642de4df718c1f655f080c8fe402e092", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1757650951, "max_line_length": 194, "alphanum_fraction": 0.500469771, "converted": true, "num_tokens": 21951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742626558767584, "lm_q2_score": 0.033589504198973025, "lm_q1q2_score": 0.010662190880821563}}
{"text": "Importing a few useful libraries\n\n\n```python\nimport bs4\nfrom bs4 import BeautifulSoup\nimport requests\nimport os.path\nimport re\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport csv\nimport json\nfrom datetime import datetime\nfrom tqdm import tqdm\nfrom collections import defaultdict\nfrom collections import Counter\nfrom IPython.core.display import HTML\nimport time\nimport nltk\n\n# custom libraries\nfrom data_collection import *\nfrom tsv_management import *\nfrom search_engine import *\nfrom custom_search_engine import *\n\n# nltk text preprocessing utilities\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.stem import PorterStemmer\nfrom nltk.corpus import wordnet\nfrom nltk.stem import WordNetLemmatizer \n\n# to be executed once\n#nltk.download('wordnet')\n#nltk.download('stopwords')  \n#nltk.download('punkt')\n#nltk.download('averaged_perceptron_tagger')\n#nltk.download('universal_tagset')\n```\n\n# 1. Data Collection\n\nWe start by retrieving the list of links associated to every anime.\n\n\n```python\nlink_retrieval()\n```\n\nWe retrieved a total of 19128 anime links.\n\nWe then we crawl every page in an html file.\n\n\n```python\ntotal_anime = data_crawling()\n```\n\nBecause of the large number of requests, the site would stop the access every once in a while; to deal with this problem we set a waiting time between each request (0.1 s) and a 60 seconds pause every time the site returns a captcha page. This allowed us to download all the pages in about 12 hours.\n\nNow we parse from every html file the data we are interested in into a dictionary. In doing so we also checked if some values contain a tab character, and we removed them. Finally we saved every dictionary into a tsv file.\n\n\n```python\ntsv_gen()\n```\n\nWe wrote a set of useful functions to retrieve the informations about every anime from these tsv files. The details can be found in the library `tsv_management.py`. Here we give some simple examples on how to use them:\n\n\n```python\ntitles = column_retrieval('animeTitle')  # returns the value of the input column for every anime\n\n## NOTE: the tsv files are indexed starting from 1\nanime_8 = tsv_retrieval(8)  # reads the data in anime_8.tsv and returns it in a dictionary\n\nall_anime = load_all_tsv()   # returns the dictionaries associated to every anime in one list\n```\n\n\n```python\nprint(titles[7])\nprint(anime_8['animeTitle'])\nprint(all_anime[7]['animeTitle'])\n```\n\n    Ginga Eiyuu Densetsu\n    Ginga Eiyuu Densetsu\n    Ginga Eiyuu Densetsu\n\n\n\n```python\nanimeType = column_retrieval('animeType')\nCounter(animeType)\n```\n\n\n\n\n    Counter({'TV': 5515,\n             'OVA': 3933,\n             'Movie': 3476,\n             'ONA': 2211,\n             'Special': 2294,\n             'Music': 1648,\n             None: 51})\n\n\n\n# 2. Search Engine\n\nWe start by defining some utilities to preprocess out data:\n\nWe will perform the following operations for text preprocessing:\n1. Regex tokenization (to tokenize and remove punctuation all at once)\n2. Convert every token to lowercase\n3. Stopwords removal (according to NLTK stopwords library for the english language)\n4. Stemming using Porter stemmer (to both normalize and stem the words)\n\nWe wrote a function for this exact purpose:\n\n\n```python\npreprocessing('Sample text\\n These words will be tokenized and stemmed\\n')\n```\n\n\n\n\n    ['sampl', 'text', 'word', 'token', 'stem']\n\n\n\nWe start by generating our vocabulary of all the words in the anime descriptions which associates every word to an integer:\n\n\n```python\nvocabulary_generation()\n```\n\n    Retrieving tsv: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:08<00:00, 2324.62it/s]\n    Preprocessing documents: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [03:42<00:00, 85.89it/s] \n\n\nThe vocabulary is saved in a json file. We will read it from the disk as needed:\n\n\n```python\nvocabulary = vocabulary_retrieval()\n```\n\nWe can also easly invert the dictionary to find the word corresponding to a certain integer:\n\n\n```python\ninteger_to_word = vocabulary_inversion(vocabulary)\nprint(vocabulary[integer_to_word[7]], integer_to_word[7])\n```\n\n    7 reishin\n\n\n## 2.1. Conjunctive query\n\nOur first search engine will just sarch for all the anime that contain the query in the description.\n\nWe start by building our first inverted index using the anime descriptions. Because each word is associated to an integer, and because our inverted index will contain all the words in our vocabulary (from 0 to `len(vocabulary)`), we decided to store the inverted index as a list of lists, in which the $i^{th}$ entry corresponds to the inverted list associated to the word indexed by $i$.\n\n\n```python\nunranked_inverted_index_generation()\n```\n\n    Retrieving tsv: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [02:36<00:00, 122.28it/s]\n    Preprocessing documents: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [03:29<00:00, 91.09it/s] \n    Building the inverted index: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:02<00:00, 9160.42it/s] \n\n\nJust as the vocabulary, our inverted index is saved in a json file, and we will read it as part of the search engine initialization. Before starting with the actual search, we want to comment some choices that we made during the implementation of the engine:\n\n* We index the anime starting from $1$ (just as the tsv file names), so we decided to assign the index $0$ to a (virtual) document that contain every word in the vocabulary. Because of this choice every sublist of our inverted index list starts with this $0$ index. This choice has been dictated by a convenience in the computation of the intersection: having a universal document makes it so that the intersection between elements of the inverted index will never be empty, and allows us to terminate the algorithm with minimal effort in terms of length checking.\n\n* The other choice we made regards the algorithm that computes the intersection between the elements of the inverted index. As said before, thanks to our choice of defining the universal $0$ document, the intersections will never be empty; this brings some convenience in terms of checking whether the algorithm has finished or not. Our other \"unusual\" choice regards the fact that we start intersecting the lists starting from their last element and proceeding backwards, so that the universal document will always be our last match.\n\nWe are now ready to initialize our search engine. What this does is loading the inverted index and the vocabulary in memory to have them ready for the search.\n\n\n```python\n## YOU NEED TO EXECUTE THIS ONLY ONCE\nvocabulary, unranked_inverted_index = unranked_search_engine_initialization()\n```\n\nAnd we are now ready to search for some anime!\n\n\n```python\nunranked_search(vocabulary, unranked_inverted_index)\n```\n\n    Input a query: saiyan race\n\n\n    \n    4 search results found!\n    \n\n\n\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>animeTitle</th>\n      <th>animeDescription</th>\n      <th>Url</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>Dragon Ball Z Special 1: Tatta Hitori no Saishuu Kessen</td>\n      <td>Bardock, Son Goku's father, is a low-ranking Saiyan soldier who was given the power to see into the future by the last remaining alien on a planet he just destroyed. He witnesses the destruction of his race and must now do his best to stop Frieza's impending massacre.  (Source: ANN)</td>\n      <td>https://myanimelist.net/anime/986/Dragon_Ball_Z_Special_1__Tatta_Hitori_no_Saishuu_Kessen</td>\n    </tr>\n    <tr>\n      <td>Dragon Ball Kai</td>\n      <td>Five years after the events of Dragon Ball, martial arts expert Gokuu is now a grown man married to his wife Chi-Chi, with a four-year old son named Gohan. While attending a reunion on Turtle Island with his old friends Master Roshi, Krillin, Bulma and others, the festivities are interrupted when a humanoid alien named Raditz not only reveals the truth behind Gokuu's past, but kidnaps Gohan as well.  With Raditz displaying power beyond anything Gokuu has seen before, he is forced to team up with his old nemesis, Piccolo, in order to rescue his son. But when Gokuu and Piccolo reveal the secret of the seven mystical wish-granting Dragon Balls to Raditz, he informs the duo that there is more of his race, the Saiyans, and they won\u2019t pass up an opportunity to seize the power of the Dragon Balls for themselves.  These events begin the saga of Dragon Ball Kai, a story that finds Gokuu and his friends and family constantly defending the galaxy from increasingly more powerful threats. Bizarre, comical, heartwarming and threatening characters come together in a series of battles that push the powers and abilities of Gokuu and his friends beyond anything they have ever experienced.</td>\n      <td>https://myanimelist.net/anime/6033/Dragon_Ball_Kai</td>\n    </tr>\n    <tr>\n      <td>Dragon Ball Super: Broly</td>\n      <td>Forty-one years ago on Planet Vegeta, home of the infamous Saiyan warrior race, King Vegeta noticed a baby named Broly whose latent power exceeded that of his own son. Believing that Broly's power would one day surpass that of his child, Vegeta, the king sends Broly to the desolate planet Vampa. Broly's father Paragus follows after him, intent on rescuing his son. However, his ship gets damaged, causing the two to spend years trapped on the barren world, unaware of the salvation that would one day come from an unlikely ally.  Years later on Earth, Gokuu Son and Prince Vegeta\u2014believed to be the last survivors of the Saiyan race\u2014are busy training on a remote island. But their sparring is interrupted when the appearance of their old enemy Frieza drives them to search for the last of the wish-granting Dragon Balls on a frozen continent. Once there, Frieza shows off his new allies: Paragus and the now extremely powerful Broly. A legendary battle that shakes the foundation of the world ensues as Gokuu and Vegeta face off against Broly, a warrior without equal whose rage is just waiting to be unleashed.  [Written by MAL Rewrite]</td>\n      <td>https://myanimelist.net/anime/36946/Dragon_Ball_Super__Broly</td>\n    </tr>\n    <tr>\n      <td>Dragon Ball Z</td>\n      <td>Five years after winning the World Martial Arts tournament, Gokuu is now living a peaceful life with his wife and son. This changes, however, with the arrival of a mysterious enemy named Raditz who presents himself as Gokuu's long-lost brother. He reveals that Gokuu is a warrior from the once powerful but now virtually extinct Saiyan race, whose homeworld was completely annihilated. When he was sent to Earth as a baby, Gokuu's sole purpose was to conquer and destroy the planet; but after suffering amnesia from a head injury, his violent and savage nature changed, and instead was raised as a kind and well-mannered boy, now fighting to protect others.  With his failed attempt at forcibly recruiting Gokuu as an ally, Raditz warns Gokuu's friends of a new threat that's rapidly approaching Earth\u2014one that could plunge Earth into an intergalactic conflict and cause the heavens themselves to shake. A war will be fought over the seven mystical dragon balls, and only the strongest will survive in Dragon Ball Z.  [Written by MAL Rewrite]</td>\n      <td>https://myanimelist.net/anime/813/Dragon_Ball_Z</td>\n    </tr>\n  </tbody>\n</table>\n\n\n## 2.2. Conjunctive query & Ranking score\n\nWe now want to improve the engine by adding a ranking for the search results based on some similarity with the query. For this purpose we will consider every document as a vector in which the elements are the tfIdf scores of every word in the document.\n\nWe start by building the new inverted index, which will now consist of a dicionary fo the form:\n```\n{\nterm_id_1:[(document1, tfIdf_{term,document1}), (document2, tfIdf_{term,document2}), (document4, tfIdf_{term,document4}), ...],\nterm_id_2:[(document1, tfIdf_{term,document1}), (document3, tfIdf_{term,document3}), (document5, tfIdf_{term,document5}), (document6, tfIdf_{term,document6}), ...],\n...}\n\n```\n\n\n```python\nranked_inverted_index_generation()\n```\n\n    Retrieving tsv: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:07<00:00, 2608.51it/s]\n    Preprocessing documents: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [03:31<00:00, 90.39it/s] \n    Ranked inverted index generation: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:02<00:00, 6879.75it/s] \n\n\nJust as the vocabulary, our inverted index is saved in a json file, and we will read it as part of the search engine initialization. The intersection algorithm will be a specular version of the previous one, we just adapted it to the new data types. The similarity between the document and the query will be given by\n\n\\begin{equation}\n\\frac{\\mathbf q \\cdot \\mathbf v }{\\| \\mathbf v \\|}\n\\end{equation}\n\nwhere $\\mathbf q$ and $ \\mathbf v$ are the tfidf vectors of the query and the document (respectively). For this purpose, in the previous function we also generated a dictionary of all the tfidf vectors and we saved it on the disk.\n\nWe are now ready to initialize our search engine. What this does is loading the inverted index, the vocabulary and the tfidf vector of every document in memory to have them ready for the search.\n\n\n```python\n## YOU NEED TO EXECUTE THIS ONLY ONCE\nvocabulary, ranked_inverted_index, tfidf_vectors, total_documents = ranked_search_engine_initialization()\n```\n\nAnd we are now ready to search for some anime!\n\n\n```python\nranked_search(vocabulary, ranked_inverted_index, tfidf_vectors, total_documents, k = 5)\n```\n\n    Input a query: saiyan race\n\n\n    \n\n\n\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>animeTitle</th>\n      <th>animeDescription</th>\n      <th>Url</th>\n      <th>Similarity</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>Dragon Ball Z Special 1: Tatta Hitori no Saishuu Kessen</td>\n      <td>Bardock, Son Goku's father, is a low-ranking Saiyan soldier who was given the power to see into the future by the last remaining alien on a planet he just destroyed. He witnesses the destruction of his race and must now do his best to stop Frieza's impending massacre.  (Source: ANN)</td>\n      <td>https://myanimelist.net/anime/986/Dragon_Ball_Z_Special_1__Tatta_Hitori_no_Saishuu_Kessen</td>\n      <td>0.554850</td>\n    </tr>\n    <tr>\n      <td>Dragon Ball Super: Broly</td>\n      <td>Forty-one years ago on Planet Vegeta, home of the infamous Saiyan warrior race, King Vegeta noticed a baby named Broly whose latent power exceeded that of his own son. Believing that Broly's power would one day surpass that of his child, Vegeta, the king sends Broly to the desolate planet Vampa. Broly's father Paragus follows after him, intent on rescuing his son. However, his ship gets damaged, causing the two to spend years trapped on the barren world, unaware of the salvation that would one day come from an unlikely ally.  Years later on Earth, Gokuu Son and Prince Vegeta\u2014believed to be the last survivors of the Saiyan race\u2014are busy training on a remote island. But their sparring is interrupted when the appearance of their old enemy Frieza drives them to search for the last of the wish-granting Dragon Balls on a frozen continent. Once there, Frieza shows off his new allies: Paragus and the now extremely powerful Broly. A legendary battle that shakes the foundation of the world ensues as Gokuu and Vegeta face off against Broly, a warrior without equal whose rage is just waiting to be unleashed.  [Written by MAL Rewrite]</td>\n      <td>https://myanimelist.net/anime/36946/Dragon_Ball_Super__Broly</td>\n      <td>0.341980</td>\n    </tr>\n    <tr>\n      <td>Dragon Ball Z</td>\n      <td>Five years after winning the World Martial Arts tournament, Gokuu is now living a peaceful life with his wife and son. This changes, however, with the arrival of a mysterious enemy named Raditz who presents himself as Gokuu's long-lost brother. He reveals that Gokuu is a warrior from the once powerful but now virtually extinct Saiyan race, whose homeworld was completely annihilated. When he was sent to Earth as a baby, Gokuu's sole purpose was to conquer and destroy the planet; but after suffering amnesia from a head injury, his violent and savage nature changed, and instead was raised as a kind and well-mannered boy, now fighting to protect others.  With his failed attempt at forcibly recruiting Gokuu as an ally, Raditz warns Gokuu's friends of a new threat that's rapidly approaching Earth\u2014one that could plunge Earth into an intergalactic conflict and cause the heavens themselves to shake. A war will be fought over the seven mystical dragon balls, and only the strongest will survive in Dragon Ball Z.  [Written by MAL Rewrite]</td>\n      <td>https://myanimelist.net/anime/813/Dragon_Ball_Z</td>\n      <td>0.233947</td>\n    </tr>\n    <tr>\n      <td>Dragon Ball Kai</td>\n      <td>Five years after the events of Dragon Ball, martial arts expert Gokuu is now a grown man married to his wife Chi-Chi, with a four-year old son named Gohan. While attending a reunion on Turtle Island with his old friends Master Roshi, Krillin, Bulma and others, the festivities are interrupted when a humanoid alien named Raditz not only reveals the truth behind Gokuu's past, but kidnaps Gohan as well.  With Raditz displaying power beyond anything Gokuu has seen before, he is forced to team up with his old nemesis, Piccolo, in order to rescue his son. But when Gokuu and Piccolo reveal the secret of the seven mystical wish-granting Dragon Balls to Raditz, he informs the duo that there is more of his race, the Saiyans, and they won\u2019t pass up an opportunity to seize the power of the Dragon Balls for themselves.  These events begin the saga of Dragon Ball Kai, a story that finds Gokuu and his friends and family constantly defending the galaxy from increasingly more powerful threats. Bizarre, comical, heartwarming and threatening characters come together in a series of battles that push the powers and abilities of Gokuu and his friends beyond anything they have ever experienced.</td>\n      <td>https://myanimelist.net/anime/6033/Dragon_Ball_Kai</td>\n      <td>0.190423</td>\n    </tr>\n  </tbody>\n</table>\n\n\nAs we can see, the results are now ranked by this measure of similarity between documents. The rank though, does not seem very satisfying to us, since the first place contains a special of the main anime, which is ranked third. This fact will be of guidance for the next exercise.\n\n# 3. Define a new score!\n\nAt this point, since we have so many informations on each anime, we would like to be able to use more of them to achieve better search results. Before explaining our choices we wanto to make a remark: looking at the data we noticed that the informations were not all mutually independent, specifically we noticed that the anime are ranked in decreasing order of Score; we made the same hypotesis about the popularity and the number of members, but it seems only weakly verified (the ordering is not strictly preserved but is of by a small number of members, we think it is because of some delay between the update of the number of members and the update of the popularity in the site).\n\nHaving made these two remarks, we decided to only use the informations on the score, the popularity and the type of every anime. The informations about the aired dates seemed hard to use effectively without implementing an explicit filter, and the number of users did not seem useful to our purpose. We thought about using the anime related informations in a page rank fashion but we ended up discarding the idea to not add too much \"randomness\" to our formulas.\n\nWe also decided to treat the title, the characters names, the voices names and the staff names just like the description, so we ended up using 8 of the 15 (not independent) information we retrieved about every anime. Here is a summary of what we did:\n1. We built a new vocabuary and inverted index based on the description, characters names, voices names and staff names\n2. We assigned a custom popularity score to each anime\n3. Given a query, we search for all the documents that have at least one word in common with the query\n4. We rank these last results using a custom index that is based on the similarity and on the previously mentioned popularity score\n\nWe start with the first point: because most titles are not in english, we thought that the stemmer could return unexpected results and we changed the way we preprocess the documents. What we do is:\n1. Regex tokenization (to tokenize and remove punctuation all at once)\n2. Convert every token to lowercase\n3. Stopwords removal (according to NLTK stopwords library for the english language)\n4. Tag each word using the NLTK tagger\n5. Lemmatize the couple (word, tag) using WordNet Lemmatizer\n\nBecause the lemmatizer is based on an actual database of words, we thought that the japanese titles would have a higher chance of survival than with the stemming. Here is an example:\n\n\n```python\nlemmatization_preprocessing('Sample text\\n These words will be tokenized and lemmatized\\n The title Ginga Eiyuu Densetsu is left untouched!')\n```\n\n\n\n\n    ['sample',\n     'text',\n     'word',\n     'tokenized',\n     'lemmatized',\n     'title',\n     'ginga',\n     'eiyuu',\n     'densetsu',\n     'leave',\n     'untouched']\n\n\n\nWe start, as usual, by building a new vocabulary of words based on all the textual informations that we have. We will save it to the disk and retrieve it as needed.\n\n\n```python\ntitles_descriptions_vocabulary_generation()\n```\n\n    Retrieving tsv: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:08<00:00, 2311.17it/s]\n    Retrieving tsv: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:06<00:00, 3039.95it/s]\n    Retrieving tsv: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:06<00:00, 3020.09it/s]\n    Retrieving tsv: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:06<00:00, 3099.35it/s]\n    Retrieving tsv: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:06<00:00, 2898.71it/s]\n    Preprocessing documents: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [04:29<00:00, 71.01it/s] \n    Preprocessing documents: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:20<00:00, 947.15it/s] \n    Preprocessing documents: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:30<00:00, 630.71it/s] \n    Preprocessing documents: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:28<00:00, 670.66it/s] \n    Preprocessing documents: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:19<00:00, 959.20it/s] \n\n\nWe wanted the user to be able to choose if he's searching for a specific anime or if he wants to do a broader search, so we had to keep the description separated from the other textual informations. Because of this, we created a tfidf vector for the descriptions, and a tfidf vector for the other informations (title, characters, voices and staff names; we will sometimes call this vector \"partial\" or just \"titles\"). Since we keep the tfidfs separated, we built an unranked inverted index (in the exact same way as the first search engine) and we stored it as a list of lists (we still adopt the universal 0 document convention that we established before). We saved these three objects in three distinct json files, to retrieve them when needed.\n\n\n```python\ntitles_descriptions_inverted_index_generation()\n```\n\n    Retrieving tsv: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:04<00:00, 4032.32it/s]\n    Retrieving tsv: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:04<00:00, 4466.58it/s]\n    Retrieving tsv: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:04<00:00, 4560.52it/s]\n    Retrieving tsv: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:04<00:00, 4531.45it/s]\n    Retrieving tsv: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:04<00:00, 4231.51it/s]\n    Preprocessing documents: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [03:47<00:00, 84.26it/s] \n    Preprocessing documents: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:21<00:00, 904.74it/s] \n    Preprocessing documents: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:31<00:00, 614.76it/s] \n    Preprocessing documents: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:29<00:00, 649.66it/s] \n    Preprocessing documents: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:20<00:00, 924.47it/s] \n    Building the inverted index: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:02<00:00, 7698.43it/s] \n    TfIdf vectors generation: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:02<00:00, 6712.85it/s] \n\n\nWe the proceeded to retrieve the other information that we wanted to use about the anime from the disk, specifically we retrieve for each anime:\n* The Score\n* The rank of Popularity\n* The Type\n\nSince Score (float in $[2,10]$) and rank of Popularity (integer in $[1,19128]$) are on totally different scales, we decided to normalize them in the interval $(0,1)$ in the following way:\n* $newScore\\ =\\ f(Score,\\ 10)$\n* $newPopularity\\ =\\ f(19129-Popularity,\\ 19128)$\nwhere $f(x,m)$ is a function that squeezes (with respect to $x$) the interval $(0,m)$ in the interval $(0,1)$ in a nonlinear way near the borders (it gives the same weight to higher scores). We plot $f(x,1)$ below, see the implementation in the library `custom_search_engine.py`, in the function `anime_scoring_info_creation()` for the actual functional form of $f$.\n\n\n```python\nnp.seterr(all=\"ignore\")\nx = np.linspace(0,1,1000)\nplt.plot(x, bump_function(x, max = 1))\nplt.show()\n```\n\nOnce we obtain these new two scores, we save them to the disk along with the anime type:\n\n\n```python\nanime_scoring_info_creation()\n```\n\n    Retrieving tsv: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:06<00:00, 2859.34it/s]\n    Retrieving tsv: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:04<00:00, 4199.38it/s]\n    Retrieving tsv: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:03<00:00, 4787.86it/s]\n\n\nBefore starting the search, we give some more details about the actual implementation and the rankings. Once we retrieve all the documents that have at least one word in common with the query (see `union_pointers()` in `custom_search_engine.py` for the actual implementation of the union algorithm), we proceed to calculate the tfidf vector associated with the document in the following way:\n\n$$tfidf_{document}(word) = \\alpha * tfidf_{title}(word)+(1-\\alpha) * tfidf_{description}(word)$$\n\nwhere $tfidf_{title}(word)$ is the tfidf of a word seen as part of the title (and characters, etc..) document and $tfidf_{description}(word)$ is the tfidf of a word seen as part of the description document (where a tfidf is 0 if the word isn't in the document), and $\\alpha$ is a parameter chosen by the user.\n\nWe then compute the cosine similarity (here we take into account the norm of the query too, because we want a result smaller than 1) between the query and this new tfidf vector. Having run some trials, we noticed that the similarity gave a lot of priority to documents with brief descriptions (as for these documents the tf comes out higher than for longer documents); the tfidf is better suited to work with large documents (for which the term frequency is more meaningful). To overcome this last problem we renormalize the final similarity with a number that depends on the length of the document; the functional form is an arch of ellipse, we choose the parameters with some trials and errors. You can look at the details in `description_titles_cosine_similarity()` inside `custom_search_engine.py`, here we limit ourselves to a simple plot:\n\n\n```python\ndef ellipse (x):\n    f = -20 * np.sqrt(1-0.000209*(x-70)**2)+21\n    return(f)\n\nx = np.linspace(1,69,1000)\nplt.plot(x, ellipse(x))\nplt.xlabel('number of words in the document')\nplt.ylabel('renormalization factor')\nplt.show()\n```\n\nAfter computing this new similarity score, we do two last modification to obtain the final score. Firstly we define for each anime the popularity ranking score as the average of the popularity and the rank score defined above; then we compute:\n\n$$score = similarity * ( 1.5 - \\alpha ) + PopularityRankingScore * \\alpha$$\nwhere $\\alpha$ is another parameter chosen by the user. Finally, we let the user enter a preference for the anime type, and we increase the final score by a fixed percentage if the anime matches the desired type (see the global variable `type_modifier` inside `custom_search_engine.py` for the exact number).\n\nWe are now ready to initialize the search engine:\n\n\n```python\ncustom_vocabulary, inverted_index, description_tf_idf, partial_tf_idf, anime_scoring_info, parameters_list, total_documents = custom_search_engine_initialization()\n```\n\nAnd here we can customize the engine parameters:\n\n\n```python\nparameters_list = search_engine_customization()\n```\n\n    Hi! Here you can tune some search engine parameters to fit your search needings.\n    \n\n\n    Do you want to have a detailed explanation of the role of every parameter? (Y/n) y\n\n\n    To compute the final tfidf vector associated to the document we computed two separate tfidf vectors: one for the description and one for the titles, characters, voices and staff; and we combined the tfidf for each word according to the following formula:\n     final_tfidf = alpha * title_tfidf + (1 - alpha) * description_tfidf\n     where title_tfidf is the tfidf of the word in the titles, characters, voices and staff texts, and description_tfidf is the tfidf of the word in the description text. The parameter we ask you to choose is the alpha in the above formula, and it represents the weight of the titles texts in the final computation for the cosine similarity.\n     alpha = 1 will give max priority to words in the query that match a word in titles, characters, voices and staff texts\n     alpha = 0 will give max priority to words in the query that match a word in the description\n     Thus by varying this parameter you will be able to decide if you search for a specific anime (alpha near 1), or if you want to do a more generic search (alpha near 0).\n     NOTE: We will automatically renormalize your score in (0.1, 0.9) as choosing too extreme values can lead to unexpected behaviours.\n    \n\n\n    Are you searching for a specific anime or you want something generic that fits your query?\n     Input a number in [0,1] where 0 is generic and 1 is specific:  0.9\n\n\n    After computing the cosine similarity based on the parameter above, we convolute the similarity with a specific score that is based on the popularity of the anime according to the following:\n     final_score = similarity * ( 1.5 - alpha ) + popularity_ranking_score * alpha\n     where the popularity_ranking_score is computed starting from the animePopularity and animeScore in the data in the following way:\n     rank_score = f(animeScore, 10)\n     popularity_score = f(19129 - animePopularity, 19128)\n     where f(x,m) is a certain smooth function that squeezes all the numbers in (0,m) in the interval (0,1) in a nonlinear way near the borders.\n     See the implementation in the library custom_search_engine.py, in anime_scoring_info_creation() for more details about the function.\n     After obtaining the rank_score and the popularity_score, we compute the final rank as a simple average:\n     popularity_ranking_score = (popularity_score + rank_score)/2\n     The parameter we ask you to choose is the alpha in the above formula, and it represents the weight of the popularity and the rank of each anime in the classification.\n     alpha = 1 will give max priority to popularity and rank, sending up in the final classification the most popular anime\n     alpha = 0 will give no priority to popularity and rank, letting the cosine similarity choose the classification\n     NOTE: We will automatically renormalize your score in (0.1, 0.9) as choosing too extreme values can lead to unexpected behaviours.\n     NOTE: Whatever you choose as the parameter, the final classification WILL be influenced by the rank and popularity of the anime. This is an intended choice and it\n     reflects the assumption that anime which are not popular nor ranked high are probably of low quality in general and would not be searched much.\n     Thus by varying this parameter you will be able to decide if you prefer to have popular anime (alpha near 1) or high ranked anime (alpha near 0) in your search results.\n\n\n    Would you like to rank the anime based on their popularity or based on their score?\n     Input a number in [0,1] where 0 is rank by popularity and 1 is rank by score:  0.9\n\n\n    Here we ask you to specify if you prefer a specific type of anime among the following:\n     Movie, Music, ONA, OVA, Special, TV\n     This is an important choice since most of the anime that are not TV are special or side stories of a TV one.\n     This will allow you to filter out some of the secondary story anime or to search specifically for them.\n     The ranking boost works in this way: given a final similarity score, if the anime type coincides with the desired one\n     the score will be increased by a fixed percentage (see the global variable type_modifier in the library custom_search_engine.py).\n     NOTE: if you choose All or if you type an incorrect anime type, we will not take into account at all the type of the anime in the final score.\n\n\n    Are you searching for a specific anime Type? Choose among the following:\n    Movie, Music, ONA, OVA, Special, TV, All\n     tv\n\n\n    The parameter you just chose are passed to the search engine as a list:\n     [isSpecific, Type, popularity_relevance]\n     With this knowledge you can edit these parameters directly if you wish, and you can also bypass the restriction of the numerical parameters being in (0.1, 0.9).\n     This last thing can bring unexpected results, experiment freely with this in mind.\n    \n\n\n\n```python\ncustom_search(custom_vocabulary, inverted_index, description_tf_idf, partial_tf_idf, total_documents, anime_scoring_info, parameters_list, k = 5)\n```\n\n    Input a query: saiyan race\n\n\n    \n\n\n\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>animeTitle</th>\n      <th>animeDescription</th>\n      <th>animeType</th>\n      <th>animeScore</th>\n      <th>animePopularity</th>\n      <th>Url</th>\n      <th>Custom score</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>Dragon Ball Z Movie 14: Kami to Kami</td>\n      <td>Following the defeat of a great adversary, Gokuu Son and his friends live peaceful lives on Earth. Meanwhile, in space, Beerus the God of Destruction awakens from his long slumber, having dreamed of an entity known as a Super Saiyan God. With the help of his assistant, Whis, Beerus looks for this powerful being, as he wishes to fight a worthy opponent. After discovering that the Saiyan home planet was destroyed, he tracks down the remaining Saiyans on Earth, looking for Gokuu specifically.  Having only heard of the Super Saiyan God in legends, Gokuu and his comrades summon Shen Long the Eternal Dragon, who they find out is afraid of Beerus. After learning the secret of the Super Saiyan God, an intense battle between Gokuu and Beerus commences, the immense power of which puts the Earth in terrible danger.  [Written by MAL Rewrite]</td>\n      <td>Movie</td>\n      <td>7.39</td>\n      <td>987</td>\n      <td>https://myanimelist.net/anime/14837/Dragon_Ball_Z_Movie_14__Kami_to_Kami</td>\n      <td>0.737447</td>\n    </tr>\n    <tr>\n      <td>Dragon Ball Z Special 1: Tatta Hitori no Saishuu Kessen</td>\n      <td>Bardock, Son Goku's father, is a low-ranking Saiyan soldier who was given the power to see into the future by the last remaining alien on a planet he just destroyed. He witnesses the destruction of his race and must now do his best to stop Frieza's impending massacre.  (Source: ANN)</td>\n      <td>Special</td>\n      <td>7.55</td>\n      <td>1785</td>\n      <td>https://myanimelist.net/anime/986/Dragon_Ball_Z_Special_1__Tatta_Hitori_no_Saishuu_Kessen</td>\n      <td>0.709900</td>\n    </tr>\n    <tr>\n      <td>Dragon Ball Z Movie 08: Moetsukiro!! Nessen, Ressen, Chougekisen</td>\n      <td>As Goku investigates the destruction of the Southern Galaxy, Vegeta is taken to be King of the New Planet Vegeta, and to destroy the Legendary Super Saiyan, Broly.  (Source: ANN)</td>\n      <td>Movie</td>\n      <td>7.32</td>\n      <td>1271</td>\n      <td>https://myanimelist.net/anime/901/Dragon_Ball_Z_Movie_08__Moetsukiro_Nessen_Ressen_Chougekisen</td>\n      <td>0.685352</td>\n    </tr>\n    <tr>\n      <td>Initial D Battle Stage</td>\n      <td>There are many street races in the Initial D Series. This OVA has no plot other than to collect all the street races into one stage. The dialog during the original races is left in.</td>\n      <td>OVA</td>\n      <td>7.56</td>\n      <td>3228</td>\n      <td>https://myanimelist.net/anime/821/Initial_D_Battle_Stage</td>\n      <td>0.672249</td>\n    </tr>\n    <tr>\n      <td>Dragon Ball Z Movie 10: Kiken na Futari! Super Senshi wa Nemurenai</td>\n      <td>After his loss to Goku, Broly crash lands and hibernates on earth. After some time, he is awakened by Trunks and Goten, who Broly believes is Kakarott, and goes on a rampage to kill both of them. At the same time, Gohan is on his way to challenge the Legendary Super Saiyan alone.</td>\n      <td>Movie</td>\n      <td>6.79</td>\n      <td>1466</td>\n      <td>https://myanimelist.net/anime/903/Dragon_Ball_Z_Movie_10__Kiken_na_Futari_Super_Senshi_wa_Nemurenai</td>\n      <td>0.611405</td>\n    </tr>\n  </tbody>\n</table>\n\n\n## Search engine comparisons\n\nHere we perform some comparisons between the our custom search engine and the ranked search engine we built before.\n\nAs a first example, by searching the top 3 for the query `naruto` we see that the ranked search gives only 2 anime about naruto, the first one and the third one, but neither is the TV series (which is the most popular). On the other hand the custom search, tuned by popularity, gives back the two main series in the first 3 places.\n\n\n```python\nranked_search(vocabulary, ranked_inverted_index, tfidf_vectors, total_documents, k = 3)\n```\n\n    Input a query: naruto\n\n\n    \n\n\n\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>animeTitle</th>\n      <th>animeDescription</th>\n      <th>Url</th>\n      <th>Similarity</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>Naruto: Shippuuden - Shippuu! \"Konoha Gakuen\" Den</td>\n      <td>Naruto school special.  Naruto is a new cool student and when he meets Sasuke they start fighting.</td>\n      <td>https://myanimelist.net/anime/4134/Naruto__Shippuuden_-_Shippuu_Konoha_Gakuen_Den</td>\n      <td>1.987909</td>\n    </tr>\n    <tr>\n      <td>Juliet</td>\n      <td>Based on the manga by U-Jin.  This is a story of two siblings, Anzu and Naruto Nozaki, heirs to the fabulous Nozaki fortune. Naruto appears to be an overbearing sis-con. In fact, he's madly in love with Anzu, because they're not blood-related. He confines her to the family mansion for \"security,\" depriving her of companionship and a real life. At age 16, she starts to rebel. She smuggles in a kitten as a pet (Naruto hates cats) and then escapes in a delivery truck. Naruto catches up to her and realizes that she can't be confined like a bird in a cage. He agrees to let have a normal life, but just then, tragedy strikes   (Source: Collectr)</td>\n      <td>https://myanimelist.net/anime/8993/Juliet</td>\n      <td>1.241344</td>\n    </tr>\n    <tr>\n      <td>Naruto: Shippuuden Movie 6 - Road to Ninja</td>\n      <td>Returning home to Konohagakure, the young ninja celebrate defeating a group of supposed Akatsuki members. Naruto Uzumaki and Sakura Haruno, however, feel differently. Naruto is jealous of his comrades' congratulatory families, wishing for the presence of his own parents. Sakura, on the other hand, is angry at her embarrassing parents, and wishes for no parents at all. The two clash over their opposing ideals, but are faced with a more pressing matter when the masked Madara Uchiha suddenly appears and transports them to an alternate world.  In this world, Sakura's parents are considered heroes\u2014for they gave their lives to protect Konohagakure from the Nine-Tailed Fox attack 10 years ago. Consequently, Naruto's parents, Minato Namikaze and Kushina Uzumaki, are alive and well. Unable to return home or find the masked Madara, Naruto and Sakura stay in this new world and enjoy the changes they have always longed for. All seems well for the two ninja, until an unexpected threat emerges that pushes Naruto and Sakura to not only fight for the Konohagakure of the alternate world, but also to find a way back to their own.  [Written by MAL Rewrite]</td>\n      <td>https://myanimelist.net/anime/13667/Naruto__Shippuuden_Movie_6_-_Road_to_Ninja</td>\n      <td>1.159498</td>\n    </tr>\n  </tbody>\n</table>\n\n\n\n```python\nparameters_list = [0.1, 'all', 0.9]\ncustom_search(custom_vocabulary, inverted_index, description_tf_idf, partial_tf_idf, total_documents, anime_scoring_info, parameters_list, k = 3)\n```\n\n    Input a query: naruto\n\n\n    \n\n\n\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>animeTitle</th>\n      <th>animeDescription</th>\n      <th>animeType</th>\n      <th>animeScore</th>\n      <th>animePopularity</th>\n      <th>Url</th>\n      <th>Custom score</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>Naruto: Shippuuden</td>\n      <td>It has been two and a half years since Naruto Uzumaki left Konohagakure, the Hidden Leaf Village, for intense training following events which fueled his desire to be stronger. Now Akatsuki, the mysterious organization of elite rogue ninja, is closing in on their grand plan which may threaten the safety of the entire shinobi world.  Although Naruto is older and sinister events loom on the horizon, he has changed little in personality\u2014still rambunctious and childish\u2014though he is now far more confident and possesses an even greater determination to protect his friends and home. Come whatever may, Naruto will carry on with the fight for what is important to him, even at the expense of his own body, in the continuation of the saga about the boy who wishes to become Hokage.  [Written by MAL Rewrite]</td>\n      <td>TV</td>\n      <td>8.22</td>\n      <td>16</td>\n      <td>https://myanimelist.net/anime/1735/Naruto__Shippuuden</td>\n      <td>1.157615</td>\n    </tr>\n    <tr>\n      <td>Naruto: Shippuuden Movie 6 - Road to Ninja</td>\n      <td>Returning home to Konohagakure, the young ninja celebrate defeating a group of supposed Akatsuki members. Naruto Uzumaki and Sakura Haruno, however, feel differently. Naruto is jealous of his comrades' congratulatory families, wishing for the presence of his own parents. Sakura, on the other hand, is angry at her embarrassing parents, and wishes for no parents at all. The two clash over their opposing ideals, but are faced with a more pressing matter when the masked Madara Uchiha suddenly appears and transports them to an alternate world.  In this world, Sakura's parents are considered heroes\u2014for they gave their lives to protect Konohagakure from the Nine-Tailed Fox attack 10 years ago. Consequently, Naruto's parents, Minato Namikaze and Kushina Uzumaki, are alive and well. Unable to return home or find the masked Madara, Naruto and Sakura stay in this new world and enjoy the changes they have always longed for. All seems well for the two ninja, until an unexpected threat emerges that pushes Naruto and Sakura to not only fight for the Konohagakure of the alternate world, but also to find a way back to their own.  [Written by MAL Rewrite]</td>\n      <td>Movie</td>\n      <td>7.67</td>\n      <td>640</td>\n      <td>https://myanimelist.net/anime/13667/Naruto__Shippuuden_Movie_6_-_Road_to_Ninja</td>\n      <td>1.154822</td>\n    </tr>\n    <tr>\n      <td>Naruto</td>\n      <td>Moments prior to Naruto Uzumaki's birth, a huge demon known as the Kyuubi, the Nine-Tailed Fox, attacked Konohagakure, the Hidden Leaf Village, and wreaked havoc. In order to put an end to the Kyuubi's rampage, the leader of the village, the Fourth Hokage, sacrificed his life and sealed the monstrous beast inside the newborn Naruto.  Now, Naruto is a hyperactive and knuckle-headed ninja still living in Konohagakure. Shunned because of the Kyuubi inside him, Naruto struggles to find his place in the village, while his burning desire to become the Hokage of Konohagakure leads him not only to some great new friends, but also some deadly foes.  [Written by MAL Rewrite]</td>\n      <td>TV</td>\n      <td>7.95</td>\n      <td>8</td>\n      <td>https://myanimelist.net/anime/20/Naruto</td>\n      <td>1.153523</td>\n    </tr>\n  </tbody>\n</table>\n\n\nFrom now on will omit the actual search to not fill the notebook with wall of text.\n\nWe obtain similar result also by choosing as set of parameters: `[0.9, 'all', 0.1]`. In this last case the first ranked anime is Juliet, in which one of the characters is called Naruto as well, but the other two positions are occupied by the two main series.\n\nSetting `[0.1, 'all', 0.9]`, if we search for 'one piece', we retrieve the main serie along with two movies with our search engine, while the ranked search only found the two associated movies.\n\nOne of the main advantages in using our search engine is the fact that we account for the title and the anime characters name, while the ranked search does not. This can bring to very different result, since one could wish to search by title.\n\n# 4. BONUS: Understanding the anime's reviews\nWe start by crawling the reviews pages from the web:\n\n\n```python\ntotal_reviews = reviews_crawl()\n```\n\nAnd then we parse them and we save them in various txt files:\n\n\n```python\ntxt_gen()\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [42:09<00:00,  7.56it/s] \n\n\nand then we merge every review in one file for better file management (as it is hard to move around multiple smaller files)\n\n\n```python\nmerge_txt()\n```\n\n    Retrieving txt: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19128/19128 [00:06<00:00, 3019.37it/s]\n\n\nTo perform the sentiment analysis we followed the guide found in https://towardsdatascience.com/sentiment-analysis-in-10-minutes-with-bert-and-hugging-face-294e8a04b671\n\nWe used the get_data function to get IMDB Reviews Dataset that contains 25,000 movie reviews for training and 25,000 for testing. All these 50,000 reviews are labeled. we downloaded the dataset from Stanford\u2019s relevant directory `tf.keras.utils.get_file`. After getting the data we created 2 pandas dataset (train and test) from text_dataset_from_directory of tensorflow library. We had to convert the 2 pandas dataframe into objects that are suitable objects for the BERT model. We achieve this convertions using 2 functions `convert_data_to_examples()` and `convert_examples_to_tf_dataset()`. The first one converts every row of pandas dataframe into an InputExample object. The other one creates the required input format with the tokenized InputExample objects and then create an input dataset that we can feed to the model. We used a stochastic gradient descent method from tensorflow (https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Adam), using CategoricalCrossentropy as our loss function, and SparseCategoricalAccuracy. After this we retrieved the reviews, we tokenized them, and than we gave to the pretrained model and we run a final softmax layer to get the predictions, using the argmax to get if a review is positive or negative. We wrote the result as a dict {anime_id:(number of positive,number of negative)} and we saved it in the `review_sentiment_dict.txt`.\n\n## 5. Algorithmic question\nYou consult for a personal trainer who has a *back-to-back sequence* of requests for appointments. A sequence of requests is of the form\n    > 30, 40, 25, 50, 30, 20\nwhere each number is the time that the person who makes the appointment wants to spend.\nYou need to accept some requests, however you need a break between them, so you cannot accept two consecutive requests. For example, `[30, 50, 20]` is an acceptable solution (of duration *100*), but `[30, 40, 50, 20]` is not, because *30* and *40* are two consecutive appointments. Your goal is to provide to the personal trainer a schedule that maximizes the total length of the accepted appointments. For example, in the previous instance, the optimal solution is `[40, 50, 20]`, of total duration *110*.\n1. Write an algorithm that computes the acceptable solution with the longest possible duration.\n2. Implement a program that given in input an instance in the form given above, gives the optimal solution.\n\n\n\nWe start by making some remarks about the optimal solution. Let's suppose that, in a given day, the personal trainer receives $n$ requests $[r_1,r_2,\\dots,r_n]$, and let's define $S = [s_1, \\dots, s_k]$ as the (ordered) subset of appointments that will form our optimal solution for our problem in the given day.\n* An important observation is that, by definition, if $r_i$ is in the optimal solution, then neither $r_{i-1}$ nor $r_{i+1}$ belong to this solution. This is expression of the fact that we do not want to accept two consecutive appointments.\n* Another crucial observation that we want to make is that, given any couple of consecutive elements $r_i, r_j$ that are in the optimal solution, their distance is no more than $3$, i. e. $j-i\\leq 3$. I other words, given any three consecutive appointments of durations $r_i, r_{i+1}, r_{i+2}$, at least one of them is in the optimal solution. This fact is, in some sense, pretty intuitive, and it comes from the fact that our optimal solution is the longest possible, i.e. the one for which the quantity $\\sum s_j$ is maximized. The proof of this fact is trivial and we will just illustrate it with an example. Suppose that the followings are five consecutive appointments requested today: $[r_1,r_2,r_3,r_4,r_5]$ and assume that, among them, just $r_1,r_5$ are in the optimal solution; then, by adding $r_3$ to the solution we find another valid solution, which is longer than the optimal one, which is absurd.\n* Finally, from the two observation above, given any three consecutive elements $r_i, r_{i+1}, r_{i+2}$, either one or two of them belong to the optimal solution (three of them is not acceptable by the first remark, none of them is not acceptable by the second remark).\n\nOne last note before starting: this problem may have more than one optimal solution, our algorithm returns just one of them but, with a bit fo work, can be generalized to find all the optimal solutions.\n\n### Write an algorithm that computes the acceptable solution with the longest possible duration.\nGiven our observation, we now describe a possible algorithm to solve this problem, we illustrate an example, and then we give a description of the algorithm in pseudocode.\n\nThe core of the algorithm lies in the fact that, given any three consecutive elements $r_i, r_{i+1}, r_{i+2}, r_{i+3}$, if $r_{i+3}$ is in the optimal solution, then either $r_{i}$ or $r{i+1}$ is in the optimal solution as well. The algorithm will scan through each appointment, starting from the first, and will find the best possible solution (up to that point) that contains that appointment by confronting the best possible solution for the two preceeding appointment (not counting the adjacent one) and adding the appointment in question to that. In the end, we consider the two best solutions that contains the last two appointment, and we choose the best of the two as the optimal one.\n\nWe now describe the functioning of the algorithm with an example:\n\n1. Consider the sequence of appointments given in the text `[30, 40, 25, 50, 30, 20]`.\n2. The best solution that contains $30$ is `[30]`\n3. The best solution that contains $40$ is `[40]`\n4. The best solution that contains $25$ is `[30, 25]` with a length of $55$\n5. There are two candidate solutions that contain $50$: the best solution that contains $30$, and the best solution that contains $40$. From the previous three points we know that these are, respectively, `[30]` and `[40]`; since we want the best possible solution, we choose the second, so the best possible solution that contains $50$ is `[40, 50]` with a length of $90$\n6. There are two candidate solutions that contain $30$: the best solution that contains $40$, and the best solution that contains $25$. From the previous three points we know that these are, respectively, `[40]` and `[30, 25]` (which has a length of $55$); since we want the best possible solution, we choose the second, so the best possible solution that contains $30$ is `[30, 25, 30]` with a length of $85$\n7. Finally, there are two candidate solutions that contain $20$: the best solution that contains $25$, and the best solution that contains $50$. From the previous three points we know that these are, respectively, `[30, 25]` with a length of $55$ and `[40, 50]` with a length of $90$; since we want the best possible solution, we choose the second, so the best possible solution that contains $20$ is `[40, 50, 20]` with a length of $110$\n8. Now we consider just the last two appointments. We just have to compare the best possible solution that contains $30$, and the best possible solution that contains $20$; these are, respectively, `[30, 25, 30]` with a length of $85$ and `[40, 50, 20]` with a length of $110$. Since we want the best possible solution, we choose the second to be our optimal solution.\n\nFinally, here is a description of the algorithm in pseudocode:\n```\ninput: the list of requests\noutput: the (ordered) list of requests that belong to the optimal solution\n\nfunction personal_trainer(req) {\n    num_req = len(req)\n    \n    #manually taking care of the simple cases\n    if (num_req <= 1) return(req)\n    if (num_req == 2) return( [max(req)] )\n    if (num_req == 3) {\n        solution1 = req[0] + req[2]\n        solution2 = req[1]\n        if (solution1 > solution2) return( [req[0], req[2]] )\n        else return( [req[2]] )\n    }\n    \n    \n    # generating all the three possible ways of choosing the first three element for a possible solution\n    # we will store a possible solution in an array of length 2 which contains\n    # in the first entry: the list of appointments in req that we want to have in the optimal solution\n    # in the second entry: the total length of the appointments in the optimal solution, i.e. the quantity that we are trying to maximize\n    \n    solution1 = ([req[0]], req[0])\n    solution2 = ([req[1]], req[1])\n    solution3 = ([req[0], req[2]], req[0]+req[2])\n    \n    candidates = [solution1, solution2, solution3]\n    \n    for (i in 3 to num_req) {    #3 is included, num_req is excluded\n        length_solution1 = candidates[-3][1]\n        length_solution2 = candidates[-2][1]\n        \n        if (length_solution1 >= length_solution2) {\n            appointments = candidates[-3][0] + [req[i]]   #here '+' means list concatenation\n            length = candidates[-3][1] + req[i]\n            \n            candidates.append( (appointments, length) )\n        } else {\n            appointments = candidates[-2][0] + [req[i]]   #here '+' means list concatenation\n            length = candidates[-2][1] + req[i]\n            \n            candidates.append( (appointments, length) )\n        }\n    }\n    \n    \n    length_solution1 = candidates[-2][1]\n    length_solution2 = candidates[-1][1]\n    \n    if (length_solution1 >= length_solution2) {\n        return( candidates[-2][0] )\n    } else {\n        return( candidates[-1][0] )\n    }\n}\n```\n\n### Implement a program that given in input an instance in the form given above, gives the optimal solution.\n\n\n```python\ndef personal_trainer(requests):\n    '''\n    input: the list of requests\n    output: the (ordered) list of requests that belong to the optimal solution\n    '''\n    \n    def best_solution(candidates):\n        '''\n        input: the list of the three last candidates solution\n        output: the index of the best solution among the first two\n        '''\n        \n        if (candidates[0][1] >= candidates[1][1]):\n            return(0)\n        else:\n            return(1)\n    \n    \n    \n    number_of_requests = len(requests)\n    \n    ## manually taking care of the simple cases\n    \n    # if the list is empty or has just one element, we return the list itself\n    if (number_of_requests <= 1):\n        return(requests)\n    \n    # if the list has just two elements, we return the biggest of the two\n    if (number_of_requests == 2):\n        return( [max(requests)] )\n    \n    # if the list has just three elements, we return either the second appointment, or the first and the last\n    if (number_of_requests == 3):\n        \n        solution1 = requests[0] + requests[2]\n        solution2 = requests[1]\n        \n        if (solution1 > solution2):\n            return( [requests[0], requests[2]] )\n        else:\n            return( [requests[2]] )\n    \n    \n    \n    # here we generate the best possible solution that contains a certain element for the first three elements\n    # we will store a possible solution in a tuple of length 2 which contains:\n    # in the first entry: the list of appointments that we want to have in the optimal solution\n    # in the second entry: the total length of the appointments in the optimal solution, i.e. the quantity that we are trying to maximize\n    \n    solution1 = ([requests[0]], requests[0])\n    solution2 = ([requests[1]], requests[1])\n    solution3 = ([requests[0], requests[2]], requests[0]+requests[2])\n    \n    \n    # candidates is a list that contains the best possible solution which contain a given three consecutive appointments\n    candidates = [solution1, solution2, solution3]\n    \n    # here we loop through every appointment and compute the best possible solution that contains it\n    for i in range(3, number_of_requests):\n        best_solution_idx = best_solution(candidates)\n        \n        appointments_list = candidates[best_solution_idx][0] + [requests[i]]    #best possible solution that contains requests[i]\n        length = candidates[best_solution_idx][1] + requests[i]    #total length of the best possible solution that contains requests[i]\n        \n        # here we add the solution relative to requests[i]\n        # and remove the solution relative to requests[i-3]\n        candidates.append((appointments_list, length))\n        del(candidates[0])\n    \n    del(candidates[0])\n    \n    \n    best_solution_idx = best_solution(candidates)\n    \n    return(candidates[best_solution_idx][0])\n```\n\n\n```python\nrequests = [30, 40, 25, 50, 30, 20]\noptimal_solution = personal_trainer(requests)\n```\n\n\n```python\nprint('Given the sequence of requests', requests,\\\n      '\\nTo maximize the total length of the accepted appointments without ever accepting two consecutive requests the personal trainer should follow this schedule:', optimal_solution)\n```\n\n    Given the sequence of requests [30, 40, 25, 50, 30, 20] \n    To maximize the total length of the accepted appointments without ever accepting two consecutive requests the personal trainer should follow this schedule: [40, 50, 20]\n\n", "meta": {"hexsha": "a7d00cf75538b02c47c5ed8d16c17bec9054e858", "size": 108234, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ADM-HW3.ipynb", "max_stars_repo_name": "benedettacandelori/ADM3_Group6", "max_stars_repo_head_hexsha": "e32c4eaf3ad4038a73d180172cff5022609441b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ADM-HW3.ipynb", "max_issues_repo_name": "benedettacandelori/ADM3_Group6", "max_issues_repo_head_hexsha": "e32c4eaf3ad4038a73d180172cff5022609441b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ADM-HW3.ipynb", "max_forks_repo_name": "benedettacandelori/ADM3_Group6", "max_forks_repo_head_hexsha": "e32c4eaf3ad4038a73d180172cff5022609441b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-14T18:54:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-14T18:54:01.000Z", "avg_line_length": 64.8884892086, "max_line_length": 16464, "alphanum_fraction": 0.7199770867, "converted": true, "num_tokens": 14789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15610488959337063, "lm_q2_score": 0.06754669630158146, "lm_q1q2_score": 0.01054436956855531}}
{"text": "```\nimport sys\nsys.stdout.write('hello world\\n')\nsys.stdout.flush()\nfor i in range(3):\n    sys.stdout.write('%s\\n' % i)\n    sys.stdout.flush()\nsys.stderr.write('output to stderr\\n')\nsys.stderr.flush()\nsys.stdout.write('some more stdout text\\n')\nsys.stdout.flush()\n```\n\n    hello world\n    0\n    1\n    2\n\n\n    output to stderr\n\n\n    some more stdout text\n\n\n# Markdown Cell\n\n$ e^{ \\pm i\\theta } = \\cos \\theta \\pm i\\sin \\theta + \\beta $\n\n*It* **really** is!\n\n\n```\nthis is a syntax error\n```\n\n\n```\nprint('test')\n```\n\n\n```\nfrom IPython.display import Latex\nLatex('''The mass-energy equivalence is described by the famous equation\n \n$$E=mc^2$$\n \ndiscovered in 1905 by Albert Einstein. \nIn natural units ($c$ = 1), the formula expresses the identity\n \n\\\\begin{equation}\nE=m\n\\\\end{equation}''')\n```\n\n\n\n\nThe mass-energy equivalence is described by the famous equation\n \n$$E=mc^2$$\n \ndiscovered in 1905 by Albert Einstein. \nIn natural units ($c$ = 1), the formula expresses the identity\n \n\\begin{equation}\nE=m\n\\end{equation}\n\n\n\n\n```\nfrom IPython.display import display\nimport ipywidgets as w\n# s = w.IntSlider(0, 10)\u00a3\n# s\na = w.IntSlider()\nb = w.IntText()\nw.jslink((a, 'value'), (b, 'value'))\ndisplay(a, b)\n```\n\n\n    IntSlider(value=0)\n\n\n\n    IntText(value=0)\n\n\n\n```\nimport plotly.express as px\ndf = px.data.tips()\nfig = px.histogram(df, x=\"total_bill\", y=\"tip\", color=\"sex\", marginal=\"rug\",\n                    hover_data=df.columns)\nfig.show()\n```\n\n\n<div>                            <div id=\"8708c6c9-e4a2-43c6-ab65-71ca8ff4f344\" class=\"plotly-graph-div\" style=\"height:525px; width:100%;\"></div>                    </div>\n\n\n\n```\nimport numpy as np\nsize = 100\nnp.random.seed(0)\nx_data = np.arange(size)\ny_data = np.cumsum(np.random.randn(size) * 100.0)\nfrom bqplot import pyplot as plt\nplt.figure(title=\"My First Plot\")\nplt.plot(x_data, y_data)\nplt.show()\n```\n\n\n    VBox(children=(Figure(axes=[Axis(scale=LinearScale()), Axis(orientation='vertical', scale=LinearScale())], fig\u2026\n\n\n\n```\nfrom pyecharts.charts import Bar\nfrom pyecharts import options as opts\n\nbar = (\n    Bar()\n    .add_xaxis([\"\u886c\u886b\", \"\u6bdb\u8863\", \"\u9886\u5e26\", \"\u88e4\u5b50\", \"\u98ce\u8863\", \"\u9ad8\u8ddf\u978b\", \"\u889c\u5b50\"])\n    .add_yaxis(\"\u5546\u5bb6A\", [114, 55, 27, 101, 125, 27, 105])\n    .add_yaxis(\"\u5546\u5bb6B\", [57, 134, 137, 129, 145, 60, 49])\n    .set_global_opts(title_opts=opts.TitleOpts(title=\"\u67d0\u5546\u573a\u9500\u552e\u60c5\u51b5\"))\n)\n# for jupyterlab\n# bar.load_javascript()\nbar.render_notebook()\n```\n\n\n\n\n\n\n\n        <div id=\"284a63d51865472c9c6adcf319e3e64b\" style=\"width:900px; height:500px;\"></div>\n\n\n\n\n\n\n\n```\nbar\n```\n\n\n\n\n    <pyecharts.charts.basic_charts.bar.Bar at 0x7fad1025f850>\n\n\n\n\n```\n\n```\n", "meta": {"hexsha": "07214234d3579d8c904e38f9dd9a4d3190a2031d", "size": 102616, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "dev/notebooks/ping.ipynb", "max_stars_repo_name": "maxb2/jupyter-examples", "max_stars_repo_head_hexsha": "4685544e9db232b580fc60c10d7d40f956055a8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-01-31T10:07:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T08:53:18.000Z", "max_issues_repo_path": "dev/notebooks/ping.ipynb", "max_issues_repo_name": "maxb2/jupyter-examples", "max_issues_repo_head_hexsha": "4685544e9db232b580fc60c10d7d40f956055a8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dev/notebooks/ping.ipynb", "max_forks_repo_name": "maxb2/jupyter-examples", "max_forks_repo_head_hexsha": "4685544e9db232b580fc60c10d7d40f956055a8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-23T00:45:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T03:15:43.000Z", "avg_line_length": 25.9524532119, "max_line_length": 24812, "alphanum_fraction": 0.3069112029, "converted": true, "num_tokens": 831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934934732271163, "lm_q2_score": 0.04401865409557382, "lm_q1q2_score": 0.0105358361277998}}
{"text": "```python\n# code for loading the format for the notebook\nimport os\n\n# path : store the current path to convert back to it later\npath = os.getcwd()\nos.chdir('../notebook_format')\nfrom formats import load_style\nload_style()\n```\n\n\n\n\n<style>\n@import url('http://fonts.googleapis.com/css?family=Source+Code+Pro');\n@import url('http://fonts.googleapis.com/css?family=Vollkorn');\n@import url('http://fonts.googleapis.com/css?family=Arimo');\n@import url('http://fonts.googleapis.com/css?family=Fira_sans');\n\n    div.cell {\n        width: 1000px;\n        margin-left: 0% !important;\n        margin-right: auto;\n    }\n    div.text_cell code {\n        background: transparent;\n        color: #000000;\n        font-weight: 600;\n        font-size: 12pt;\n        font-style: bold;\n        font-family:  'Source Code Pro', Consolas, monocco, monospace;\n    }\n    h1 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n\t}\n\n    div.input_area {\n        background: #F6F6F9;\n        border: 1px solid #586e75;\n    }\n\n    .text_cell_render h1 {\n        font-weight: 200;\n        font-size: 30pt;\n        line-height: 100%;\n        color:#c76c0c;\n        margin-bottom: 0.5em;\n        margin-top: 1em;\n        display: block;\n        white-space: wrap;\n        text-align: left;\n    } \n    h2 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n        text-align: left;\n    }\n    .text_cell_render h2 {\n        font-weight: 200;\n        font-size: 16pt;\n        font-style: italic;\n        line-height: 100%;\n        color:#c76c0c;\n        margin-bottom: 0.5em;\n        margin-top: 1.5em;\n        display: block;\n        white-space: wrap;\n        text-align: left;\n    } \n    h3 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n    }\n    .text_cell_render h3 {\n        font-weight: 200;\n        font-size: 14pt;\n        line-height: 100%;\n        color:#d77c0c;\n        margin-bottom: 0.5em;\n        margin-top: 2em;\n        display: block;\n        white-space: wrap;\n        text-align: left;\n    }\n    h4 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n    }\n    .text_cell_render h4 {\n        font-weight: 100;\n        font-size: 14pt;\n        color:#d77c0c;\n        margin-bottom: 0.5em;\n        margin-top: 0.5em;\n        display: block;\n        white-space: nowrap;\n    }\n    h5 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n    }\n    .text_cell_render h5 {\n        font-weight: 200;\n        font-style: normal;\n        color: #1d3b84;\n        font-size: 16pt;\n        margin-bottom: 0em;\n        margin-top: 0.5em;\n        display: block;\n        white-space: nowrap;\n    }\n    div.text_cell_render{\n        font-family: 'Fira sans', verdana,arial,sans-serif;\n        line-height: 125%;\n        font-size: 115%;\n        text-align:justify;\n        text-justify:inter-word;\n    }\n    div.output_wrapper{\n        margin-top:0.2em;\n        margin-bottom:0.2em;\n    }\n\n    code{\n      font-size: 70%;\n    }\n    .rendered_html code{\n    background-color: transparent;\n    }\n    ul{\n        margin: 2em;\n    }\n    ul li{\n        padding-left: 0.5em; \n        margin-bottom: 0.5em; \n        margin-top: 0.5em; \n    }\n    ul li li{\n        padding-left: 0.2em; \n        margin-bottom: 0.2em; \n        margin-top: 0.2em; \n    }\n    ol{\n        margin: 2em;\n    }\n    ol li{\n        padding-left: 0.5em; \n        margin-bottom: 0.5em; \n        margin-top: 0.5em; \n    }\n    ul li{\n        padding-left: 0.5em; \n        margin-bottom: 0.5em; \n        margin-top: 0.2em; \n    }\n    a:link{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:visited{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:hover{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:focus{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:active{\n       font-weight: bold;\n       color:#447adb;\n    }\n    .rendered_html :link {\n       text-decoration: underline; \n    }\n    .rendered_html :hover {\n       text-decoration: none; \n    }\n    .rendered_html :visited {\n      text-decoration: none;\n    }\n    .rendered_html :focus {\n      text-decoration: none;\n    }\n    .rendered_html :active {\n      text-decoration: none;\n    }\n    .warning{\n        color: rgb( 240, 20, 20 )\n    } \n    hr {\n      color: #f3f3f3;\n      background-color: #f3f3f3;\n      height: 1px;\n    }\n    blockquote{\n      display:block;\n      background: #fcfcfc;\n      border-left: 5px solid #c76c0c;\n      font-family: 'Open sans',verdana,arial,sans-serif;\n      width:680px;\n      padding: 10px 10px 10px 10px;\n      text-align:justify;\n      text-justify:inter-word;\n      }\n      blockquote p {\n        margin-bottom: 0;\n        line-height: 125%;\n        font-size: 100%;\n      }\n</style>\n\n\n\n\n\n\n```python\nos.chdir(path)\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# 1. magic for inline plot\n# 2. magic to print version\n# 3. magic so that the notebook will reload external python modules\n%matplotlib inline\n%load_ext watermark\n%load_ext autoreload \n%autoreload 2\n\nfrom scipy.stats import beta\nfrom collections import namedtuple\n\n%watermark -a 'Ethen' -d -t -v -p numpy,pandas,matplotlib,scipy\n```\n\n    Ethen 2017-01-14 23:02:25 \n    \n    CPython 3.5.2\n    IPython 4.2.0\n    \n    numpy 1.11.3\n    pandas 0.18.1\n    matplotlib 1.5.1\n    scipy 0.18.1\n\n\n# Multi-Armed Bandits\n\nImagine this scenario: You\u2019re in a casino. There are many different slot machines (known as \"one-armed bandits\", as they\u2019re known for robbing you), each with a lever (an arm, if you will). You think that some slot machines payout more frequently than others do, and you\u2019re goal is to walk out of the casino with the most money. \n\nThe question is, how do you learn which slot machine is the best and get the most money in the shortest amount of time? You could try all the slot machines out to get a sense of the expected return from playing each machine. But remember, each time you play a poor performing machine, you lower your take that you walk out of the casino with that night. In order to maximize how much money you walk out of the casino with, you will have to be efficient with how you collect your data.\n\nRewriting the scenario above into a business language. Each time a shopper looks comes to a webpage, we  show them one of the $K$ variations of the webpage. They either click on it or do not, and we log this information about the (binary) reward for each $K$ variations. Kext, we proceed to the next shopper or have to choose one of $K$ webpage variations again.\n\n\n## Differences Between A/B Testing and Bandit Testing\n\nIn both scenarios above, we would normally determine our \"winner\" (the slot machine that pays the most, or the best webpage variations that gets the most clicks) using the well-known **A/B testing** approach. The **A/B testing** approach consists of a period of pure exploration, where you\u2019re randomly assigning equal numbers of users to one of the $K$ variations and run the test until it's valid. After that, it jumps into pure exploitation, where you send 100% of your users to the more successful version of your site.\n\nTwo possible problems with the classical **A/B testing** approach is that:\n\n- It jumps discretely from exploration to exploitation, when you might be able to transition more smoothly.\n- During the exploratory phase (the test), it wastes resources exploring inferior options in order to gather as much data as possible.\n\nGiven the exploration - exploitation dilemma stated above, the **bandit testing** approach try to account for this. The following graph depicts the difference between the two types of testing method: \n\n\n\nIf we have three variations that we wish to test, the **A/B testing** approach we try out each of the three variations with equal proportions until we run our test at week 5, and then select the variation with the highest value. \n\nAs for **bandit testing**, it attempts to use what it knows about each variation from the very beginning, and it continuously updates the probabilities that it will select each variation throughout the optimization process. In the above chart we can see that with each new week, the **bandit testing** reduces how often it selects the lower performing options and increases how often if selects the highest performing option.\n\n> You need to explore in order to figure out what works and what doesn\u2019t. On the other hand, if you exploit you take advantage of what you have learned. The **bandit testing** approach highlights the fact that collecting data also has its cost.\n\nTo be specific, **bandit testing** algorithms will try to minimize what\u2019s known as regret, which is the difference between your actual payoff and the payoff you would have collected had you played the optimal (best) options at every opportunity. There are tons of different bandit methods, in the next section we'll look at some of the more common ones.\n\n## Bandit Algorithms\n\nBefore introducing the algorithms and trying them out through simulations, we'll denote some notations and terminologies to formally define the problem:\n\n- **arms** is simply the variations that we're testing (webpages that we're testing) and there will be $K$ of them in total.\n- In a simulation of t turns (how many samples in a simulation), we'll maintain **empirical means** of the reward for each arm (e.g. after trying out arm A for 10 turns, it got 3 clicks, the empirical means is simply 0.3) that are updated at every turn t.\n- $u_i(t)$ is the empirical mean of arm $i$ after $t$ turns.\n- $p_i(t)$ is the probability of picking arm $i$ at turn $t$.\n\nLet's look at our simulated data beforing diving into each algorithms (hopefully the docstrings are self-explanatory).\n\n\n```python\ndef generate_bernoulli_bandit_data( n_simulations, K ):\n    \"\"\"\n    generate simluate data, that represents success / trial data\n    \n    Parameters\n    ----------\n    n_simulations : int\n        the total number of turns in a simulation\n        \n    K : int\n        the total number of arms\n    \n    Returns\n    -------\n    ctr : float 1d-array, shape(K, )\n        the randomly generated empirical click through rate for each arm\n    \n    rewards : boolean 2d-array, shape(n_simulations, K)\n        given the empirical ctr, simulate in each turn of the simulation, \n        whether the arm gets pulled will obtain the \n        reward or not (whether the webpage gets clicked)\n    \"\"\"\n\n    ctr = np.random.rand(K)\n    rewards = np.random.rand(n_simulations, K) < np.tile( ctr, (n_simulations, 1) )\n    return ctr, rewards \n\nK = 2\nn_simulations = 5\nctr, rewards = generate_bernoulli_bandit_data(n_simulations, K)\nprint(ctr)\nprint(rewards)\n```\n\n    [ 0.75662543  0.5769374 ]\n    [[ True False]\n     [ True  True]\n     [False False]\n     [ True False]\n     [ True False]]\n\n\n### Algorithm 1 - Epsilon Greedy \n\nAt each round $t = 1, 2, ...$ the **Epsilon Greedy** algorithm will:\n\n- Choose a random arm with the probability of $\\epsilon$.\n- Choose the arm with the current best empirical mean with probability of $1-\\epsilon$.\n\nIn mathematical notations:\n\n$$\np_i(t+1)=\n\\begin{cases}\n    1 - \\epsilon + \\epsilon \\big/ K & \\quad \\text{if i = } argmax_{j = 1, ..., K} \\ u_j(t) \\\\\n    \\epsilon \\big/ K  & \\quad otherwise\n\\end{cases}\n$$\n\nOr more intuitively:\n\n- When a new visitor comes to the site, the algorithm flips a coin that comes up tail with the probability of $\\epsilon$. When it does in fact comes up tail, the algorithm is going to explore. The exploration phase is simply randomly choosing between any possible arm with equal (uniform) probability and showing it to the visitor.\n- On the other hand, the algorithm will exploit the best known solution with the proability of $1- \\epsilon$. To exploit, the algorithm simply looks up the current empirical means and shows the best one to the visitor.\n\nThe image below sums up the algorithm pretty well.\n\n\n\n\n```python\ndef epsilon_greedy(counts, epsilon = 0.5, decrease_const = 1000):\n    \"\"\"\n    adaptive epsilon greedy\n    \n    Parameters\n    ----------\n    counts : int 2d-array, shape(K, 2), where K = the total number of arms\n        success and failures for each arm where column 0 represents \n        success, 1 represents failure\n    \n    epsilon : float\n        the initial probability of choosing a random arm; \n        1 - epsilon is the probability of choosing the current best arm\n        \n    decrease_const : int\n        parameter for the adaptive (annealing) epsilon\n    \n    Returns\n    -------\n    (int) the chosen arm\n    \"\"\"\n    \n    # calculate the empirical means and the total number of simulations that were ran\n    totals = counts.sum(axis = 1)\n    successes = counts[:, 0]\n    empirical_means = successes / totals\n    total_counts = counts.sum()\n    \n    epsilon /= (1 + total_counts / decrease_const)\n    if np.random.rand() > epsilon:\n        return np.argmax(empirical_means)\n    else:\n        return np.random.randint(0, empirical_means.shape[0])\n\n# counts : stores the counts of success and failures for each arm\n# where column 0 represents success, 1 represents failure.\n# each arm's count is initialiated as 1 to ensure that each arm is\n# played at least once, to prevent \"cold start\" problem and\n# 0 division in the beginning\ncounts = np.ones((K, 2))\nprint(counts)\nepsilon_greedy(counts)\n```\n\n    [[ 1.  1.]\n     [ 1.  1.]]\n\n\n\n\n\n    0\n\n\n\nThe `decrease_const` parameter in the function above may look unfamiliar.\n\nFor the **Epsilon Greedy** algorithm, setting the $\\epsilon$ can be a bit tricky. If it\u2019s too small, exploration will be slow at the beginning, and you will be slow to react to changes. If we happen to sample, say, the second-best arm the first few times, it may take a long time to discover that another arm is actually better. If $\\epsilon$ is too big, you\u2019ll waste many trials pulling random arms without gaining much.\n\nTo accomodate for this situation, we will set the $\\epsilon$ value at a higher value in the beginning and anneal (gradually lower) it over time. Intuitively, this simply means that after exploring around for a while, we become more certained about each arms' empirical means. After that, it's better to exploit. \n\nIn the function call above, the $\\epsilon$ at turn $t$ will become:\n\n$$\\epsilon(t) = \\epsilon(0) \\Big/ (1 + t/T)$$\n\nWhere $T$ is a new parameter that represents a decreasing constant.\n\nNote that there are different ways of annealing a parameter, but the spirit is the same.\n\n\n```python\n# show adaptive learning rate\nepsilon = 0.5\ndecrease_const = 1000\n\n# the epsilon value after 10 turns\ntotal_counts = 10\nprint( epsilon / (1 + total_counts / decrease_const) )\n\n# after 10000 turns\ntotal_counts = 10000\nprint( epsilon / (1 + total_counts / decrease_const) )\n```\n\n    0.49504950495049505\n    0.045454545454545456\n\n\n### Algorithm 2 - Boltzmann Exploration (Softmax)\n\nThe **Softmax** algorithm picks each arm with a probability that is proportional to its average reward.\n\n$$ p_i(t+1)= \\frac{ e^{u_i(t) / \\tau} }{ \\sum_{j=1}^K  e^{u_j(t) / \\tau} }$$\n\nWhere $\\tau$ is a temperature parameter, controlling the randomness of the choice. When $\\tau$ = 0, the algorithm acts like pure greedy. As $\\tau$ grows to infinity, the algorithm will pick arms uniformly at random.\n\n\n```python\ndef softmax(counts):\n    \"\"\"\n    adaptive softmax\n    \n    Parameters\n    ----------\n    counts : int 2d-array, shape( K, 2 ), where K = the total number of arms\n         success and failures for each arm where column 0 represents \n         success, 1 represents failure\n    \n    Returns\n    -------\n    (int) the chosen arm\n    \"\"\"\n    \n    # calculate the empirical means and the total number of simulations that were ran\n    totals = counts.sum(axis = 1)\n    successes = counts[:, 0]\n    empirical_means = successes / totals\n    total_counts = counts.sum()\n    \n    # annealing (adaptive learning rate)\n    tau = 1 / np.log(total_counts + 0.000001)\n\n    probs_n = np.exp(empirical_means / tau)\n    probs_d = probs_n.sum()\n    probs = probs_n / probs_d\n\n    cum_prob = 0.\n    z = np.random.rand()\n    for idx, prob in enumerate(probs):  \n        cum_prob += prob\n        if cum_prob > z:\n            return(idx)\n\ncounts = np.ones((K, 2))\nsoftmax(counts)\n```\n\n\n\n\n    1\n\n\n\n### Algorithm 3 - Upper Confidence Bounds (UCB)\n\nIn the world of statistics, whenever you estimate some unknown parameter (such as the mean of a distribution) using random samples, there is a way to quantify the uncertainty inherent in your estimate.  For example, the true mean of a fair six-sided die is 3.5.  But if you only roll it once and get a 2, your best estimate of the mean is just 2.  Obviously that estimate is not very good, and we can quantify the confidence we have for our estimate.  There are confidence bounds which can be written, for example, as: \"The mean of this die is 2, with a 95-th percentile lower bound of 1.4 and a 95-th percentile upper bound of 5.2.\"\n\nThe upper confidence bound (UCB) family of algorithms, as its name suggests, simply selects the arm with the largest upper confidence bound at each turn.  The intuition is this: the more times you roll the die, the tighter the confidence bounds, on the other hand, if your roll the die an infinite number of times then the width of the confidence bound is zero. In short, as the number of rolls increases, the uncertainty decreases, and so does the width of the confidence bound. \n\nThus, unlike the **Epsilon Greedy** and **Softmax** algorithm that only keeps track of the empirical means, the **UCB** algorithm also maitains the number of times that each arm has been played, denoted by $n_i(t)$. Initially, each arm is played once. Afterwards, at round t, the algorithm greedily picks the arm $j(t)$ as follows:\n\n$$j(t) = argmax_{i = 1, ..., K} \\left( u_i + \\sqrt{\\frac{2lnt}{n_i}} \\right)$$\n\nWe can see that the **UCB** algorithm will try to learn about arms that we don't know enough about. The main advantages of these types of algorithms are:\n\n- Take uncertainty of sample mean estimate into account in a smart way.\n- No parameters (e.g. epsilon, annealing) to validate.\n\n\n```python\ndef ucb(counts):\n    \"\"\"\n    adaptive softmax\n    \n    Parameters\n    ----------\n    counts : int 2d-array, shape( K, 2 ), where K = the total number of arms\n         success and failures for each arm where column 0 represents \n         success, 1 represents failure\n    \n    Returns\n    -------\n    (int) the chosen arm\n    \"\"\"\n    \n    # calculate the empirical means and the total number of simulations that were ran\n    totals = counts.sum(axis = 1)\n    successes = counts[:, 0]\n    empirical_means = successes / totals\n    total_counts = counts.sum()\n    \n    bonus = np.sqrt(2 * np.log(total_counts) / totals)\n    return np.argmax(empirical_means + bonus)\n\ncounts = np.ones((K, 2))\nsoftmax(counts)\n```\n\n\n\n\n    1\n\n\n\n## Experimenting With Bandit Algorithms\n\nIn this section, we'll use our simulated data to experiment with our algorithms. To do this we'll also need a metric to calculate how well we are doing. Recall the absolute *best* we can do is to always pick the webpage (arm) with the largest click through rate (ctr). Denote this best arm's probability of $w_{opt}$. Our score should be relative to how well we would have done had we chosen the best arm from the beginning. This motivates the *total regret* of a strategy, defined as:\n\n$$\n\\begin{align}\nR_T & = \\sum_{t=1}^{T} \\left( w_{opt} - w_{I(t)} \\right) \\nonumber \\\\\n& = Tw_{opt} - \\sum_{t=1}^{T} \\;  w_{I(t)} \\nonumber\n\\end{align}\n$$\n\nWhere $T$ is the total number of samples in the experiment, $w_{I(t)}$ is the probability of obtaining the reward (getting clicked) of the chosen arm in the $t_{th}$ turn. A total regret of 0 means the strategy is attaining the best possible score. This is likely not possible, as initially our algorithm will often make the wrong choice. Ideally, a strategy's total regret should flatten as it learns the best bandit. (Mathematically, we achieve $w_{I(t)} = w_{opt}$ often)\n\nWe'll run the experiment and plot the cumulative regret of the three algorithms below:\n\n\n```python\ndef run_bandit_algo(rewards, ctr, algo, **kwargs):\n    \"\"\"\n    Run different types of bandit algorithms\n    \n    Parameters\n    ----------\n    rewards, ctr : \n        Return value of the `generate_bernoulli_bandit_data` function\n    \n    algo : bandit function\n        [ epsilon_greedy, softmax, ucb ]\n    \n    **kwargs :\n        additional parameters to pass in to the algo\n    \n    Returns\n    -------\n    cum_regret : 1d-array, shape( n_simulations, )\n        The total regret accumulated over the experiment, where the regret\n        is measured by the maximum ctr - the chosen arm's ctr \n    \n    opt_arm_percentage : float\n        The percentage of plays in which the optimal arm is pulled\n    \"\"\"  \n    n_simulations, K = rewards.shape\n    \n    # counts : success and failures for each arm where column 0 represents \n    # success, 1 represents failure. Each arm's count is initialiated as 1 \n    # to ensure that each arm is played at least once, to prevent \"cold start\" \n    # problem and 0 division in the beginning\n    counts = np.ones( (K, 2), dtype = int )   \n    regret = np.zeros(n_simulations)\n    \n    max_ctr_count = 0\n    max_ctr = np.max(ctr)\n    max_ctr_idx = np.argmax(ctr)\n    \n    for i in range(n_simulations): \n        # 1. run the algorithm to obtain the arm that got pulled \n        # 2. update the success / failure according to the generated rewards\n        # 3. update the expected regret for each turn of the simulation\n        # 4. if the arm that got pulled is the one with the opt ctr, increment this count      \n        arm = algo( counts, **kwargs )      \n        if rewards[i, arm] == 1:\n            counts[arm, 0] += 1\n        else:\n            counts[arm, 1] += 1\n\n        regret[i] = max_ctr - ctr[arm]   \n        if arm == max_ctr_idx:\n            max_ctr_count += 1\n\n    cum_regret = np.cumsum(regret)\n    opt_arm_percentage = max_ctr_count / n_simulations\n    return cum_regret, opt_arm_percentage\n```\n\n\n```python\nK = 5\nn_simulations = 10000\nalgorithms = [epsilon_greedy, softmax, ucb]\n\ndef run_experiment(K, n_simulations, algorithms):\n    \"\"\"\n    Run the bandit algorithm's simulation by the \n    specified number of samples for simulation, the number of arms\n    and the different version of algorithm\n    \n    Parameters\n    ----------\n    n_simulations : int\n        the total number of turns in a simulation\n        \n    K : int\n        the total number of arms\n    \n    algorithms : list of functions\n        the list of bandit algorithms to simulate\n    \n    Returns\n    -------\n    ctr : float 1d-array, shape( K, )\n        the randomly generated empirical click through rate for each arm \n    \n    algo_opt_arm_percentage : float list\n        the percentage of simulations that chose the best arm\n        \n    algo_cum_regret : float 2d-array, shape( n_simulations, length of the algorithm )\n        each column stores the cumulative regret for one algorithm\n        \n    fig : matplotlib figure\n        the cumulative regret for each bandit algorithm\n    \"\"\"\n    algo_opt_arm_percentage = []\n    algo_cum_regret = np.zeros( (n_simulations, len(algorithms)) )   \n\n    fig = plt.figure( figsize = (10, 7) )\n    ctr, rewards = generate_bernoulli_bandit_data(n_simulations, K)\n    \n    for idx, algo in enumerate(algorithms):\n        cum_regret, opt_arm_percentage = run_bandit_algo(rewards, ctr, algo = algo)\n        algo_cum_regret[:, idx] = cum_regret\n        algo_opt_arm_percentage.append(opt_arm_percentage)\n        \n        plt.semilogy(cum_regret, label = algo.__name__)\n\n    plt.title( 'Simulated Bandit Performance for K = {}'.format(K) )\n    plt.ylabel('Cumulative Expected Regret')\n    plt.xlabel('Round Index')\n    plt.legend(loc = 'lower right')\n    \n    return ctr, algo_opt_arm_percentage, algo_cum_regret, fig\n```\n\n\n```python\n# change default figure size and font size\nplt.rcParams['figure.figsize'] = 8, 6\nplt.rcParams['font.size'] = 12\n\nctr, algo_opt_arm_percentage, algo_cum_regret, fig = run_experiment(K, n_simulations, algorithms)\nfig.show()\nprint(ctr)\nprint(algo_opt_arm_percentage)\n```\n\n**Section Conclusion:** The plot of the cumulative expected regret of the experiment above showed that all three different algorithms have converged (the cumulative expected regret gradually decreases to a steady level). And the **UCB** seems to be doing better than the other two algorithms in this limited horizon.\n\n# Bayesian Bandits\n\nAll of that was great, so what's next? Well, it turns out that none of the algorithms we used in the last section are really suitable in real world applications. Why?\n\nRecall that in the experiment above, we tested different kinds of bandit algorithms with the assumption that there is no delay between pulling an arm and observing the result. Or, more precisely, if there is a delay, it should happen before the next timing to pull an arm. This means the following timeline is impossible: 12:00 Visitor A sees Variation 1. 12:01 visitor B sees Variation 2. 12:02 Visitor A converts.\n\nAlso if you have limited computational resources, which means that you can only update your observed data in batch every 2 hours. For these kinds of delayed batch case, the algorithms described in the last section will pull the same arm every time for those 2 hours because it is deterministic in the absence of immediate updates. To sum up, the algorithms we just described needs the distributions to be updated every single round to work properly, which may not be applicable in a lot of practical cases ....\n\nHaving that caveat in mind, we'll introduce a Bayesian method that is more \"immune\" to this delayed feedback problem, namely **Thompson Sampling**. \n\nRecall that the the problem we want to solve is the following. You have come up with $K$ different variations of the webpage (e.g. different layout) that now you wish to find the ones with the best click through rate (CTR), e.g. clicking to sign-up for the newsletter. Let's represent each CTR by $\\theta_i$ - i.e., $\\theta_i$ is the true probability that an individual user will click when they were shown with the $i_{th}$ webpage. It is important to note that we don't actually know what $\\theta_i$ is - if we did, we could simply choose ii for which $\\theta_i$ was largest and move on. We're simply pretending that we know in order to simulate the performance of the algorithm.\n\nUsing the Bayesian approach we will construct a prior probability distribution which represents our original belief about what the actual value of $\\theta_i$, our ctr for the $i_{th}$ webpage is. The prior we'll use is the Beta distribution. Here's a quick recap of the distribution:\n\n## Beta Distribution\n\nThe Beta distribution is very useful in Bayesian statistics. A random variable $X$ has a Beta distribution, with parameters $(\\alpha, \\beta)$, if its density function is:\n\n$$f_X(x | \\; \\alpha, \\beta ) = \\frac{ x^{(\\alpha - 1)}(1-x)^{ (\\beta - 1) } }{B(\\alpha, \\beta) }$$\n\nwhere $B$ is the [Beta function](http://en.wikipedia.org/wiki/Beta_function) (hence the name). The random variable $X$ is only allowed in [0,1], making the Beta distribution a popular distribution for decimal values, probabilities and proportions. The values of $\\alpha$ and $\\beta$, both positive values, provide great flexibility in the shape of the distribution. Below we plot some Beta distributions with different $\\alpha$ and $\\beta$ values:\n\n\n```python\nplt.figure( figsize = (12, 5) )\n\nx = np.linspace(0.01, .99, 100)\nparams = [ (2, 5), (1, 1), (5, 5), (20, 4) ]\n\nfor a, b in params:\n    y = beta.pdf(x, a, b)\n    lines = plt.plot( x, y, label = \"(%.1f,%.1f)\" % (a, b), lw = 2 )\n    plt.fill_between( x, 0, y, alpha = 0.2, color = lines[0].get_color() )\n    plt.autoscale(tight = True)\n\nplt.legend(loc = 'upper left', title = \"(a,b)-parameters\")\nplt.show()\n```\n\nThere are two important things to note about the Beta distribution: \n\nThe first is the presence of the flat distribution above, specified by parameters $(1,1)$. This is the Uniform distribution. Hence the Beta distribution is a generalization of the Uniform distribution.\n\nThe second is that there is an interesting connection between the Beta distribution and the Binomial distribution. Suppose we are interested in some unknown proportion or probability $p$. We assign a $\\text{Beta}(\\alpha, \\beta)$ prior to $p$. We observe some data generated by a Binomial process, say $X \\sim \\text{Binomial}(N, p)$, with $p$ still unknown. Then our posterior *is again a Beta distribution*, i.e. $p | X \\sim \\text{Beta}( \\alpha + X, \\beta + N -X )$. Succinctly, one can relate the two by \"a Beta prior with Binomial observations creates a Beta posterior\".\n\nIn light of the above two paragraphs, if we start with a $\\text{Beta}(1,1)$ prior on $p$ (which is a Uniform), observe data $X \\sim \\text{Binomial}(N, p)$, then our posterior is $\\text{Beta}(1 + X, 1 + N - X)$. \n\n## Thompson Sampling\n\nSo after assuming the priors on the probability of ctr for each webpage. To be explicit on the phrase \"assuming the priors\", we will assume that we're completely ignorant of these probabilities. So a very natural prior is the flat prior over 0 to 1, $\\text{Beta}(\\alpha=1,\\beta=1)$. The algorithm then proceeds as follows:\n\nFor each turn:\n\n1. Sample a random variable $X_i$ from the prior of arm $i$, for all $i$ ($K$ in total).\n2. Select the arm with largest sample, i.e. select $i = \\text{argmax}\\; X_i$.\n3. Observe the result of pulled arm $i$, and update your prior with that arm $i$.\n4. Return to 1.\n\nLike all the algorithms we've introduced before, **Thompson Sampling** suggests that we should not discard losers, but we should pick them at a decreasing rate as we gather confidence that there exist *better* webpages (arms). This follows because there is always a non-zero chance that a webpage with a lower ctr will get chosen, but the probability of this event decreases as we play more rounds.\n\n\n```python\nclass BayesianBandit:\n    \"\"\"\n    Thompson Sampling\n    \n    Parameters\n    ----------\n    K : int\n        total number of arms\n        \n    prior_params : list of float length 2 tuple, default None, (optional)\n        each element of the list is a tuple, where each tuple\n        contains the alpha and beta parameter that represents the prior\n        beta distribution for each arm. If not supplied\n        it will assume that all arms's prior starts with an uniform distribution\n        \n    Attributes\n    ----------\n    trials, success : int 1d-array, shape( K, )\n        stores the trials and success for each arm,\n        e.g. trial = [ 1, 1 ] and success = [ 0, 1 ] means \n        that both arm has been pulled once and arm 1 has generated\n        the reward (clicked)\n    \"\"\"\n    \n    def __init__(self, K, prior_params = None):\n        \n        if prior_params:\n            priors = namedtuple( \"priors\", [\"alpha\", \"beta\"] )\n            prior  = [priors(*p) for p in prior_params]\n            self.alphas = np.array([p.alpha for p in prior])\n            self.betas  = np.array([p.beta  for p in prior])\n        else:\n            self.alphas = np.ones(K)\n            self.betas  = np.ones(K)\n\n        self.trials  = np.zeros(K, dtype = int)\n        self.success = np.zeros(K, dtype = int)\n        \n    def get_recommendation(self):        \n        \"\"\"\n        for all arms, construct their beta distribution and\n        draw a random sample from it, then return the arm\n        with the maximum value random sample \n        \"\"\"\n        theta = np.random.beta(self.alphas + self.success, \n                               self.betas + self.trials - self.success)\n        return np.argmax(theta)\n    \n    def update_result(self, arm, converted):\n        \"\"\"\n        override the trials and success array, the success array\n        will only be updated if it has generated a reward\n        \"\"\"\n        self.trials[arm] += 1\n        if converted:\n            self.success[arm] += 1\n            \n        return self\n```\n\n\n```python\ndef experiment(T, K = None, ctr = None, prior_params = None):\n    \"\"\"\n    run the experiment for Thompson Sampling,\n    pass in ctr, the fixed ctr for each arm\n    or K, the total number of arms to run the experiment,\n    if K is supplied then it will be randomly generated\n    \n    Parameters\n    ----------\n    T : int\n        number of simulation in an experiment\n    \n    K : int, , default = None, (optional)\n        total number of arms\n        \n    ctr : float sequence, len = K, default = None, (optional)\n        the empirical click through rate for each arm\n        \n    prior_params : list of float length 2 tuple, default None, (optional)\n        each element of the list is a tuple, where each tuple\n        contains the alpha and beta parameter that represents the prior\n        beta distribution for each arm. If not supplied\n        it will assume that all arms's prior starts with an uniform distribution\n    \n    Returns\n    -------\n    ctr : float sequence, len = K\n        the supplied or the randomly generated ctr\n    \n    trials, success : 2d-array, shape( T, K )\n        trials and success recorded for each turn of the experiment\n        \n    alphas, betas : float 1d-array, shape( K, )\n        the alpha and beta parameters for each arm\n    \"\"\"\n    if ctr:\n        K = len(ctr)\n    else:\n        ctr = np.random.rand(K)\n\n    trials  = np.zeros( (T, K), dtype = int )\n    success = np.zeros( (T, K), dtype = int )\n\n    bb = BayesianBandit(K, prior_params)\n    for t in range(T):\n        arm = bb.get_recommendation()\n        converted = np.random.rand() < ctr[arm]\n        bb.update_result(arm, converted)\n        trials[t]  = bb.trials\n        success[t] = bb.success\n        \n    return ctr, trials, success, bb.alphas, bb.betas\n```\n\n\n```python\ndef experiment_plot(ctr, trials, success):\n    \"\"\"\n    Pass in the ctr, trials and success returned\n    by the `experiment` function and plot\n    the Cumulative Number of Turns For Each Arm and\n    the CTR's Convergence Plot side by side\n    \"\"\"\n    T, K = trials.shape\n    n = np.arange(T) + 1\n    fig = plt.figure( figsize = (14, 7) )\n\n    plt.subplot(121)\n    for i in range(K):\n        plt.loglog( n, trials[:, i], label = \"arm {}\".format(i + 1) )\n\n    plt.legend(loc = \"upper left\")\n    plt.xlabel(\"Number of turns\")\n    plt.ylabel(\"Number of turns/arm\")\n    plt.title(\"Cumulative Number of Turns For Each Arm\")\n\n    plt.subplot(122)\n    for i in range(K):\n        plt.semilogx( n, np.zeros(T) + ctr[i], label = \"arm {}'s CTR\".format(i + 1) )\n\n    plt.semilogx( n, ( success[:, 0] + success[:, 1] ) / n, label = \"CTR at turn t\" )\n\n    plt.axis([0, T, 0, 1])\n    plt.legend(loc = \"upper left\")\n    plt.xlabel(\"Number of turns\")\n    plt.ylabel(\"CTR\")\n    plt.title(\"CTR's Convergence Plot\")\n    return fig\n```\n\n\n```python\n# number of simulation in an experiment\nT = 10000\n\n# the empirical click through rate for each arm\nctr = 0.25, 0.35\n\nctr, trials, success, alphas, betas = experiment(T = T, ctr = ctr)\nfig = experiment_plot(ctr, trials, success)\nfig.show()\n```\n\nIn our simulation, we gave the Bayesian bandit two webpages (arms) - one had a CTR of 0.25, the other had a CTR of 0.35. To start with, both webpages were displayed to the user with roughly equal probability. Over time, evidence accumulated that arm 2 was considerably better than arm 1. At this point the algorithm switched to displaying primarily webpage 1, and the overall CTR of the experiment converged to 0.35 (the optimal CTR).\n\nWe can also visualize our Beta distribution for each arms in different turns.\n\n\n```python\ndef plot_beta_dist(ctr, trials, success, alphas, betas, turns):\n    \"\"\"\n    Pass in the ctr, trials and success, alphas, betas returned\n    by the `experiment` function and the number of turns \n    and plot the beta distribution for all the arms in that turn\n    \"\"\"\n    subplot_num = len(turns) / 2\n    x = np.linspace(0.001, .999, 200)\n    fig = plt.figure( figsize = (14, 7) ) \n\n    for idx, turn in enumerate(turns):\n        plt.subplot(subplot_num, 2, idx + 1)\n\n        for i in range( len(ctr) ):\n            y = beta( alphas[i] + success[turn, i], \n                      betas[i] + trials[turn, i] - success[ turn, i ] ).pdf(x)\n            line = plt.plot( x, y, lw = 2, label = \"arm {}\".format( i + 1 ) )\n            color = line[0].get_color()\n            plt.fill_between(x, 0, y, alpha = 0.2, color = color)\n            plt.axvline(x = ctr[i], color = color, linestyle = \"--\", lw = 2) \n            plt.title(\"Posteriors After {} turns\".format(turn) )\n            plt.legend(loc = \"upper right\")\n   \n    return fig\n```\n\n\n```python\nturns = [1, 100, 1000, 9999]\nposterior_fig = plot_beta_dist(ctr, trials, success, alphas, betas, turns)\nposterior_fig.show()\n```\n\nAs you can see, we started out with some prior Beta distributions that represents the our initial beliefs about possible ctr values for each arm. We then update these beliefs based on evidence by showing different webpages to other randomly chosen users and observing the ctr. After doing this for many number of turns, we incrementally narrow the width of each arm's Beta distribution. Meaning that as we gather more data, we become more confident about each arm's actual ctr.\n\nNote that we don't really care how accurate we become about the inference of the hidden probabilities \u2014 for this problem we are more interested in becoming more confident in choosing the best arm. This is basically why at the end of experiment, arm 1's distribution is wider. The algorithm is ignorant about what that hidden probability might be, but we are reasonably confident that it is not the best, so the algorithm chooses to ignore it.\n\nFrom the above, we can see that starting after 100 pulls, the majority of arm 2's distribution already leads the pack, hence the algorithm will almost always choose this arm. This is good, as this arm is indeed better.\n\n## Notes On Bandit Testings\n\nIn world settings, we need to account for situations such as delayed batch update or delay feedback. In such cases, algorithms such as **Epsilon Greedy**, **Softmax**, **UCB** needs the distributions to be updated every single round to work properly. On the other hand, **Thompson Sampling** is more realistic as it relies on random samples, which will be different every time even if the distributions are each arm aren't updated for a while.\n\nSo, after gaining some knowledge on **bandit testings**. The question that comes into our head is that: \"In general, when is it preferred over the classical **A/B testing**?\"\n\n### Short-term testing\n\n> \"Whenever you have a small amount of time for both exploration and exploitation, use a bandit testing.\"\n\n**Bandit testing** are conducive for short tests for clear reasons \u2013 if you were to run a classic **A/B testing** you\u2019d not even be able to enjoy the period of pure exploitation. Instead, **bandit testing** allow you to adjust in real time and send more traffic, more quickly, to the better variation. Here are some possible use cases:\n\n- **Headlines:** News has a short life cycle. Why would you run **A/B testing** on a headline if by the time you learn which variation is best, the time where the answer is applicable is over?\n- **Holiday Campaigns:** e.g. If you\u2019re running tests on an ecommerce site for Black Friday, an A/B testing isn\u2019t that practical \u2013 you might only be confident in the result at the end of the day. On the other hand, a **bandit testing** will drive more traffic to the better-performing variation \u2013 and that in turn can increase revenue.\n\n\n### Long-term testing\n\nBecause **Bandit testing** automatically shift traffic to higher performing (at the time) variations, thus it is effective in long term (or ongoing) testing where you can set it and forget about it. e.g. Serving specific ads and content to user sets (targeting ads).\n\n## Reference\n\n- [Notes: Algorithms for the multi-armed bandit problem](http://www.cs.mcgill.ca/~vkules/bandits.pdf)\n- [Blog: Bandits for Recommendation Systems](http://engineering.richrelevance.com/bandits-recommendation-systems/)\n- [Blog: When to Run Bandit Tests Instead of A/B Tests](http://conversionxl.com/bandit-tests/)\n- [Blog: Bayesian Bandits - optimizing click throughs with statistics](https://www.chrisstucchio.com/blog/2013/bayesian_bandit.html)\n- [Blog: Balancing Earning with Learning: Bandits and Adaptive Optimization](http://conductrics.com/balancing-earning-with-learning-bandits-and-adaptive-optimization/)\n- [Notebook: Bayesian Methods for Hackers Chapter 6](http://nbviewer.jupyter.org/github/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/blob/master/Chapter6_Priorities/Ch6_Priors_PyMC2.ipynb)\n", "meta": {"hexsha": "42215eb0e63037edb59ac6084090c61e25325a4e", "size": 295693, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "bandits/bandits.ipynb", "max_stars_repo_name": "swapnilawasthi/Business-Analytics", "max_stars_repo_head_hexsha": "30a8585f45865008ea01d2bf242bf77a9ca5b449", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 92, "max_stars_repo_stars_event_min_datetime": "2016-05-22T06:07:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T03:53:44.000Z", "max_issues_repo_path": "bandits/bandits.ipynb", "max_issues_repo_name": "ethen8181/Business-Analytics", "max_issues_repo_head_hexsha": "0fd0fd167eff1c4db05cf53ed744871bb3307595", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bandits/bandits.ipynb", "max_forks_repo_name": "ethen8181/Business-Analytics", "max_forks_repo_head_hexsha": "0fd0fd167eff1c4db05cf53ed744871bb3307595", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 42, "max_forks_repo_forks_event_min_datetime": "2017-02-08T02:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-06T08:53:11.000Z", "avg_line_length": 223.8402725208, "max_line_length": 74512, "alphanum_fraction": 0.8762770847, "converted": true, "num_tokens": 10115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09534947518185827, "lm_q2_score": 0.10818895312434518, "lm_q1q2_score": 0.010315759900880978}}
{"text": "# Pendulum DAE system\n\n\n```python\nfrom IPython.core.display import HTML\nfrom IPython.lib.display import YouTubeVideo\nYouTubeVideo('4a0FbQdH3dY')\n```\n\n\n\n\n\n\n\n\n\n\n- 9.43 he sets the bom in 5deg (How much force in x did he applied?)\n- 11.35 he sets the bom in 10deg (How much force in x did he applied?)\n- 16:20 change in mass\n- 24:00 without little push  \n- 24:42 with little push glass broken\n- 26:50 dagerous experiment\n\n\n```python\nHTML('../svg/pendulum_doc.svg')\n```\n\n\n\n\n<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<svg\n   xmlns:ns2=\"http://www.iki.fi/pav/software/textext/\"\n   xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n   xmlns:cc=\"http://creativecommons.org/ns#\"\n   xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n   xmlns:svg=\"http://www.w3.org/2000/svg\"\n   xmlns=\"http://www.w3.org/2000/svg\"\n   xmlns:sodipodi=\"http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd\"\n   xmlns:inkscape=\"http://www.inkscape.org/namespaces/inkscape\"\n   width=\"109.0979mm\"\n   height=\"105.36337mm\"\n   viewBox=\"0 0 109.0979 105.36337\"\n   version=\"1.1\"\n   id=\"svg3508\"\n   inkscape:version=\"1.0.1 (3bc2e813f5, 2020-09-07)\"\n   sodipodi:docname=\"pendulum_doc.svg\">\n  <defs\n     id=\"defs3502\">\n    <marker\n       style=\"overflow:visible\"\n       id=\"Arrow2Mstart\"\n       refX=\"0\"\n       refY=\"0\"\n       orient=\"auto\"\n       inkscape:stockid=\"Arrow2Mstart\"\n       inkscape:isstock=\"true\">\n      <path\n         transform=\"scale(0.6)\"\n         d=\"M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z\"\n         style=\"fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1\"\n         id=\"path5657\" />\n    </marker>\n    <marker\n       style=\"overflow:visible\"\n       id=\"Arrow2Mend\"\n       refX=\"0\"\n       refY=\"0\"\n       orient=\"auto\"\n       inkscape:stockid=\"Arrow2Mend\"\n       inkscape:isstock=\"true\">\n      <path\n         transform=\"scale(-0.6)\"\n         d=\"M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z\"\n         style=\"fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1\"\n         id=\"path5660\" />\n    </marker>\n    <marker\n       style=\"overflow:visible\"\n       id=\"Arrow1Send\"\n       refX=\"0\"\n       refY=\"0\"\n       orient=\"auto\"\n       inkscape:stockid=\"Arrow1Send\"\n       inkscape:isstock=\"true\">\n      <path\n         transform=\"matrix(-0.2,0,0,-0.2,-1.2,0)\"\n         style=\"fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1\"\n         d=\"M 0,0 5,-5 -12.5,0 5,5 Z\"\n         id=\"path5648\" />\n    </marker>\n    <marker\n       style=\"overflow:visible\"\n       id=\"Arrow1Mend\"\n       refX=\"0\"\n       refY=\"0\"\n       orient=\"auto\"\n       inkscape:stockid=\"Arrow1Mend\"\n       inkscape:isstock=\"true\">\n      <path\n         transform=\"matrix(-0.4,0,0,-0.4,-4,0)\"\n         style=\"fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1\"\n         d=\"M 0,0 5,-5 -12.5,0 5,5 Z\"\n         id=\"path5642\" />\n    </marker>\n    <marker\n       style=\"overflow:visible\"\n       id=\"Arrow2Mend-8\"\n       refX=\"0\"\n       refY=\"0\"\n       orient=\"auto\"\n       inkscape:stockid=\"Arrow2Mend\"\n       inkscape:isstock=\"true\">\n      <path\n         transform=\"scale(-0.6)\"\n         d=\"M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z\"\n         style=\"fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1\"\n         id=\"path5660-9\" />\n    </marker>\n    <g\n       id=\"id-09465c05-0d07-4d10-b180-a2fc628170e1-1\">\n      <symbol\n         overflow=\"visible\"\n         id=\"id-235adb31-324b-4ffd-9dd2-8ba05052e0d2-9\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"\"\n           id=\"id-970a6b35-87f0-4cf8-a399-ab5356c2066e-6\" />\n      </symbol>\n      <symbol\n         overflow=\"visible\"\n         id=\"id-650cfdb9-8baa-4058-973a-c7421a1382a3-8\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"m 3.65625,-3.984375 h 0.859375 c 0.203125,0 0.296875,0 0.296875,-0.203125 0,-0.109375 -0.09375,-0.109375 -0.265625,-0.109375 H 3.71875 L 3.921875,-5.4375 c 0.046875,-0.203125 0.1875,-0.90625 0.25,-1.03125 0.078125,-0.1875 0.25,-0.34375 0.46875,-0.34375 0.03125,0 0.296875,0 0.484375,0.1875 -0.4375,0.03125 -0.546875,0.390625 -0.546875,0.53125 0,0.234375 0.1875,0.359375 0.375,0.359375 C 5.21875,-5.734375 5.5,-5.96875 5.5,-6.34375 c 0,-0.453125 -0.453125,-0.6875 -0.859375,-0.6875 -0.34375,0 -0.96875,0.1875 -1.265625,1.171875 -0.0625,0.203125 -0.09375,0.3125 -0.328125,1.5625 h -0.6875 c -0.203125,0 -0.3125,0 -0.3125,0.1875 0,0.125 0.09375,0.125 0.28125,0.125 h 0.65625 L 2.25,-0.046875 c -0.1875,0.96875 -0.359375,1.875 -0.875,1.875 -0.046875,0 -0.28125,0 -0.484375,-0.1875 C 1.359375,1.609375 1.453125,1.25 1.453125,1.109375 1.453125,0.875 1.265625,0.75 1.078125,0.75 0.8125,0.75 0.53125,0.984375 0.53125,1.359375 c 0,0.4375 0.4375,0.6875 0.84375,0.6875 0.546875,0 0.953125,-0.59375 1.125,-0.96875 0.328125,-0.625 0.546875,-1.828125 0.5625,-1.90625 z m 0,0\"\n           id=\"id-39bf9be7-c9d7-492c-84ab-39a21298153a-6\" />\n      </symbol>\n      <symbol\n         overflow=\"visible\"\n         id=\"id-c85e3329-0aa1-498d-9861-c8273f944b1a-3\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"\"\n           id=\"id-60009086-4b3e-4e93-83d3-0555a117a54c-6\" />\n      </symbol>\n      <symbol\n         overflow=\"visible\"\n         id=\"id-0d462dda-c632-4452-85aa-e0428c8be79c-1\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"M 1.734375,-0.734375 C 1.671875,-0.5 1.4375,-0.125 1.078125,-0.125 c -0.015625,0 -0.234375,0 -0.375,-0.09375 0.28125,-0.09375 0.3125,-0.34375 0.3125,-0.390625 0,-0.15625 -0.125,-0.25 -0.28125,-0.25 -0.203125,0 -0.40625,0.15625 -0.40625,0.421875 0,0.34375 0.390625,0.5 0.734375,0.5 0.328125,0 0.609375,-0.1875 0.78125,-0.484375 C 2.015625,-0.0625 2.390625,0.0625 2.671875,0.0625 c 0.8125,0 1.234375,-0.859375 1.234375,-1.0625 0,-0.09375 -0.09375,-0.09375 -0.109375,-0.09375 -0.109375,0 -0.109375,0.046875 -0.140625,0.125 -0.140625,0.484375 -0.5625,0.84375 -0.953125,0.84375 -0.28125,0 -0.421875,-0.1875 -0.421875,-0.453125 0,-0.1875 0.171875,-0.8125 0.359375,-1.59375 C 2.78125,-2.703125 3.09375,-2.875 3.328125,-2.875 c 0.015625,0 0.21875,0 0.375,0.09375 -0.21875,0.0625 -0.3125,0.265625 -0.3125,0.390625 0,0.140625 0.125,0.25 0.28125,0.25 0.15625,0 0.390625,-0.125 0.390625,-0.421875 0,-0.390625 -0.453125,-0.515625 -0.71875,-0.515625 -0.359375,0 -0.640625,0.234375 -0.78125,0.5 -0.125,-0.28125 -0.453125,-0.5 -0.84375,-0.5 C 0.9375,-3.078125 0.5,-2.21875 0.5,-2 c 0,0.078125 0.09375,0.078125 0.109375,0.078125 0.09375,0 0.09375,-0.015625 0.140625,-0.109375 C 0.921875,-2.578125 1.359375,-2.875 1.703125,-2.875 1.9375,-2.875 2.125,-2.75 2.125,-2.421875 2.125,-2.28125 2.03125,-1.9375 1.96875,-1.6875 Z m 0,0\"\n           id=\"id-16a2c3d4-54ef-4d27-992e-1c88a3d09f8c-1\" />\n      </symbol>\n    </g>\n    <marker\n       style=\"overflow:visible\"\n       id=\"Arrow2Mend-8-2\"\n       refX=\"0\"\n       refY=\"0\"\n       orient=\"auto\"\n       inkscape:stockid=\"Arrow2Mend\"\n       inkscape:isstock=\"true\">\n      <path\n         transform=\"scale(-0.6)\"\n         d=\"M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z\"\n         style=\"fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1\"\n         id=\"path5660-9-8\" />\n    </marker>\n    <g\n       id=\"id-89dddef3-8403-4f99-a826-7f60b9e011df-0\"\n       style=\"stroke-width:0\">\n      <symbol\n         overflow=\"visible\"\n         id=\"id-201507c8-0be6-4b98-b204-e6c80091e85b-9\"\n         style=\"stroke-width:0\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"\"\n           id=\"id-ec839d7d-bd2f-4891-915c-4ae2bb70a050-8\" />\n      </symbol>\n      <symbol\n         overflow=\"visible\"\n         id=\"id-469bb503-0bdd-4d08-a256-4159c12302fb-5\"\n         style=\"stroke-width:0\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"M 0.453125,1.21875 C 0.375,1.5625 0.34375,1.625 -0.09375,1.625 c -0.109375,0 -0.21875,0 -0.21875,0.1875 0,0.078125 0.046875,0.125 0.125,0.125 0.265625,0 0.5625,-0.03125 0.828125,-0.03125 0.34375,0 0.671875,0.03125 1,0.03125 0.046875,0 0.171875,0 0.171875,-0.203125 C 1.8125,1.625 1.71875,1.625 1.578125,1.625 c -0.5,0 -0.5,-0.0625 -0.5,-0.15625 0,-0.125 0.421875,-1.75 0.484375,-2 0.125,0.296875 0.40625,0.640625 0.921875,0.640625 1.15625,0 2.40625,-1.453125 2.40625,-2.921875 0,-0.9375 -0.578125,-1.59375 -1.328125,-1.59375 -0.5,0 -0.984375,0.359375 -1.3125,0.75 -0.09375,-0.546875 -0.53125,-0.75 -0.890625,-0.75 -0.46875,0 -0.65625,0.390625 -0.734375,0.5625 C 0.4375,-3.5 0.3125,-2.90625 0.3125,-2.875 c 0,0.109375 0.09375,0.109375 0.109375,0.109375 0.109375,0 0.109375,-0.015625 0.171875,-0.234375 0.171875,-0.703125 0.375,-1.1875 0.734375,-1.1875 0.171875,0 0.3125,0.078125 0.3125,0.453125 0,0.234375 -0.03125,0.34375 -0.078125,0.515625 z m 1.75,-4.328125 C 2.265625,-3.375 2.546875,-3.65625 2.71875,-3.8125 c 0.359375,-0.296875 0.640625,-0.375 0.8125,-0.375 0.390625,0 0.640625,0.34375 0.640625,0.9375 0,0.59375 -0.328125,1.734375 -0.515625,2.109375 -0.34375,0.703125 -0.8125,1.03125 -1.1875,1.03125 C 1.8125,-0.109375 1.6875,-0.9375 1.6875,-1 c 0,-0.015625 0,-0.03125 0.03125,-0.15625 z m 0,0\"\n           id=\"id-2c7b93d1-6f74-47e7-899f-8b7423bd1a3f-4\" />\n      </symbol>\n      <symbol\n         overflow=\"visible\"\n         id=\"id-771003bb-5028-4073-aa49-f3b2e325a38b-3\"\n         style=\"stroke-width:0\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"\"\n           id=\"id-136f285f-47ce-47cc-882e-de37d2bac632-4\" />\n      </symbol>\n      <symbol\n         overflow=\"visible\"\n         id=\"id-a1e8a53b-a781-4067-bca0-1865531122e4-8\"\n         style=\"stroke-width:0\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"M 1.734375,-0.734375 C 1.671875,-0.5 1.4375,-0.125 1.078125,-0.125 c -0.015625,0 -0.234375,0 -0.375,-0.09375 0.28125,-0.09375 0.3125,-0.34375 0.3125,-0.390625 0,-0.15625 -0.125,-0.25 -0.28125,-0.25 -0.203125,0 -0.40625,0.15625 -0.40625,0.421875 0,0.34375 0.390625,0.5 0.734375,0.5 0.328125,0 0.609375,-0.1875 0.78125,-0.484375 C 2.015625,-0.0625 2.390625,0.0625 2.671875,0.0625 c 0.8125,0 1.234375,-0.859375 1.234375,-1.0625 0,-0.09375 -0.09375,-0.09375 -0.109375,-0.09375 -0.109375,0 -0.109375,0.046875 -0.140625,0.125 -0.140625,0.484375 -0.5625,0.84375 -0.953125,0.84375 -0.28125,0 -0.421875,-0.1875 -0.421875,-0.453125 0,-0.1875 0.171875,-0.8125 0.359375,-1.59375 C 2.78125,-2.703125 3.09375,-2.875 3.328125,-2.875 c 0.015625,0 0.21875,0 0.375,0.09375 -0.21875,0.0625 -0.3125,0.265625 -0.3125,0.390625 0,0.140625 0.125,0.25 0.28125,0.25 0.15625,0 0.390625,-0.125 0.390625,-0.421875 0,-0.390625 -0.453125,-0.515625 -0.71875,-0.515625 -0.359375,0 -0.640625,0.234375 -0.78125,0.5 -0.125,-0.28125 -0.453125,-0.5 -0.84375,-0.5 C 0.9375,-3.078125 0.5,-2.21875 0.5,-2 c 0,0.078125 0.09375,0.078125 0.109375,0.078125 0.09375,0 0.09375,-0.015625 0.140625,-0.109375 C 0.921875,-2.578125 1.359375,-2.875 1.703125,-2.875 1.9375,-2.875 2.125,-2.75 2.125,-2.421875 2.125,-2.28125 2.03125,-1.9375 1.96875,-1.6875 Z m 0,0\"\n           id=\"id-6e1e2198-637c-488f-8640-ebe21b2d99c0-6\" />\n      </symbol>\n    </g>\n    <marker\n       style=\"overflow:visible\"\n       id=\"Arrow2Mend-8-8\"\n       refX=\"0\"\n       refY=\"0\"\n       orient=\"auto\"\n       inkscape:stockid=\"Arrow2Mend\"\n       inkscape:isstock=\"true\">\n      <path\n         transform=\"scale(-0.6)\"\n         d=\"M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z\"\n         style=\"fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1\"\n         id=\"path5660-9-4\" />\n    </marker>\n    <marker\n       style=\"overflow:visible\"\n       id=\"Arrow2Mend-8-2-6\"\n       refX=\"0\"\n       refY=\"0\"\n       orient=\"auto\"\n       inkscape:stockid=\"Arrow2Mend\"\n       inkscape:isstock=\"true\">\n      <path\n         transform=\"scale(-0.6)\"\n         d=\"M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z\"\n         style=\"fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1\"\n         id=\"path5660-9-8-0\" />\n    </marker>\n    <g\n       id=\"id-89dddef3-8403-4f99-a826-7f60b9e011df-2\"\n       style=\"stroke-width:0\">\n      <symbol\n         overflow=\"visible\"\n         id=\"id-201507c8-0be6-4b98-b204-e6c80091e85b-1\"\n         style=\"stroke-width:0\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"\"\n           id=\"id-ec839d7d-bd2f-4891-915c-4ae2bb70a050-5\" />\n      </symbol>\n      <symbol\n         overflow=\"visible\"\n         id=\"id-469bb503-0bdd-4d08-a256-4159c12302fb-0\"\n         style=\"stroke-width:0\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"M 0.453125,1.21875 C 0.375,1.5625 0.34375,1.625 -0.09375,1.625 c -0.109375,0 -0.21875,0 -0.21875,0.1875 0,0.078125 0.046875,0.125 0.125,0.125 0.265625,0 0.5625,-0.03125 0.828125,-0.03125 0.34375,0 0.671875,0.03125 1,0.03125 0.046875,0 0.171875,0 0.171875,-0.203125 C 1.8125,1.625 1.71875,1.625 1.578125,1.625 c -0.5,0 -0.5,-0.0625 -0.5,-0.15625 0,-0.125 0.421875,-1.75 0.484375,-2 0.125,0.296875 0.40625,0.640625 0.921875,0.640625 1.15625,0 2.40625,-1.453125 2.40625,-2.921875 0,-0.9375 -0.578125,-1.59375 -1.328125,-1.59375 -0.5,0 -0.984375,0.359375 -1.3125,0.75 -0.09375,-0.546875 -0.53125,-0.75 -0.890625,-0.75 -0.46875,0 -0.65625,0.390625 -0.734375,0.5625 C 0.4375,-3.5 0.3125,-2.90625 0.3125,-2.875 c 0,0.109375 0.09375,0.109375 0.109375,0.109375 0.109375,0 0.109375,-0.015625 0.171875,-0.234375 0.171875,-0.703125 0.375,-1.1875 0.734375,-1.1875 0.171875,0 0.3125,0.078125 0.3125,0.453125 0,0.234375 -0.03125,0.34375 -0.078125,0.515625 z m 1.75,-4.328125 C 2.265625,-3.375 2.546875,-3.65625 2.71875,-3.8125 c 0.359375,-0.296875 0.640625,-0.375 0.8125,-0.375 0.390625,0 0.640625,0.34375 0.640625,0.9375 0,0.59375 -0.328125,1.734375 -0.515625,2.109375 -0.34375,0.703125 -0.8125,1.03125 -1.1875,1.03125 C 1.8125,-0.109375 1.6875,-0.9375 1.6875,-1 c 0,-0.015625 0,-0.03125 0.03125,-0.15625 z m 0,0\"\n           id=\"id-2c7b93d1-6f74-47e7-899f-8b7423bd1a3f-6\" />\n      </symbol>\n      <symbol\n         overflow=\"visible\"\n         id=\"id-771003bb-5028-4073-aa49-f3b2e325a38b-5\"\n         style=\"stroke-width:0\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"\"\n           id=\"id-136f285f-47ce-47cc-882e-de37d2bac632-49\" />\n      </symbol>\n      <symbol\n         overflow=\"visible\"\n         id=\"id-a1e8a53b-a781-4067-bca0-1865531122e4-7\"\n         style=\"stroke-width:0\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"M 1.734375,-0.734375 C 1.671875,-0.5 1.4375,-0.125 1.078125,-0.125 c -0.015625,0 -0.234375,0 -0.375,-0.09375 0.28125,-0.09375 0.3125,-0.34375 0.3125,-0.390625 0,-0.15625 -0.125,-0.25 -0.28125,-0.25 -0.203125,0 -0.40625,0.15625 -0.40625,0.421875 0,0.34375 0.390625,0.5 0.734375,0.5 0.328125,0 0.609375,-0.1875 0.78125,-0.484375 C 2.015625,-0.0625 2.390625,0.0625 2.671875,0.0625 c 0.8125,0 1.234375,-0.859375 1.234375,-1.0625 0,-0.09375 -0.09375,-0.09375 -0.109375,-0.09375 -0.109375,0 -0.109375,0.046875 -0.140625,0.125 -0.140625,0.484375 -0.5625,0.84375 -0.953125,0.84375 -0.28125,0 -0.421875,-0.1875 -0.421875,-0.453125 0,-0.1875 0.171875,-0.8125 0.359375,-1.59375 C 2.78125,-2.703125 3.09375,-2.875 3.328125,-2.875 c 0.015625,0 0.21875,0 0.375,0.09375 -0.21875,0.0625 -0.3125,0.265625 -0.3125,0.390625 0,0.140625 0.125,0.25 0.28125,0.25 0.15625,0 0.390625,-0.125 0.390625,-0.421875 0,-0.390625 -0.453125,-0.515625 -0.71875,-0.515625 -0.359375,0 -0.640625,0.234375 -0.78125,0.5 -0.125,-0.28125 -0.453125,-0.5 -0.84375,-0.5 C 0.9375,-3.078125 0.5,-2.21875 0.5,-2 c 0,0.078125 0.09375,0.078125 0.109375,0.078125 0.09375,0 0.09375,-0.015625 0.140625,-0.109375 C 0.921875,-2.578125 1.359375,-2.875 1.703125,-2.875 1.9375,-2.875 2.125,-2.75 2.125,-2.421875 2.125,-2.28125 2.03125,-1.9375 1.96875,-1.6875 Z m 0,0\"\n           id=\"id-6e1e2198-637c-488f-8640-ebe21b2d99c0-2\" />\n      </symbol>\n    </g>\n    <g\n       id=\"id-78a8471f-adc0-462c-8098-1a40c3ce8d75-7\"\n       style=\"stroke-width:0\">\n      <symbol\n         overflow=\"visible\"\n         id=\"id-8ff42f58-dcc9-4b6c-90a8-6180cc753b40-4\"\n         style=\"stroke-width:0\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"\"\n           id=\"id-f3f82317-c289-44de-99f4-5312b6d2639e-4\" />\n      </symbol>\n      <symbol\n         overflow=\"visible\"\n         id=\"id-4dc01438-ce3c-4a3e-9b5a-8b7649684a24-5\"\n         style=\"stroke-width:0\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"m 4.671875,-3.703125 c 0,-0.546875 -0.265625,-0.703125 -0.4375,-0.703125 -0.25,0 -0.5,0.265625 -0.5,0.484375 0,0.125 0.046875,0.1875 0.15625,0.296875 0.21875,0.203125 0.34375,0.453125 0.34375,0.8125 0,0.421875 -0.609375,2.703125 -1.765625,2.703125 -0.515625,0 -0.75,-0.34375 -0.75,-0.875 0,-0.546875 0.28125,-1.28125 0.578125,-2.109375 0.078125,-0.171875 0.125,-0.3125 0.125,-0.5 0,-0.4375 -0.3125,-0.8125 -0.8125,-0.8125 -0.9375,0 -1.3125,1.453125 -1.3125,1.53125 0,0.109375 0.09375,0.109375 0.109375,0.109375 0.109375,0 0.109375,-0.03125 0.15625,-0.1875 0.296875,-1 0.71875,-1.234375 1.015625,-1.234375 0.078125,0 0.25,0 0.25,0.3125 0,0.25 -0.109375,0.53125 -0.171875,0.703125 -0.4375,1.15625 -0.5625,1.609375 -0.5625,2.046875 0,1.078125 0.875,1.234375 1.328125,1.234375 1.671875,0 2.25,-3.296875 2.25,-3.8125 z m 0,0\"\n           id=\"id-880b47f9-8552-489f-bbf5-45a762219cc4-8\" />\n      </symbol>\n      <symbol\n         overflow=\"visible\"\n         id=\"id-60c8a860-7386-4c77-b5bf-a913f8117173-6\"\n         style=\"stroke-width:0\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"\"\n           id=\"id-7a4a3f98-046c-4feb-88af-9ac6be3cbb51-3\" />\n      </symbol>\n      <symbol\n         overflow=\"visible\"\n         id=\"id-f5f9e97b-dc58-4463-828e-396e50a467c0-9\"\n         style=\"stroke-width:0\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"M 1.734375,-0.734375 C 1.671875,-0.5 1.4375,-0.125 1.078125,-0.125 c -0.015625,0 -0.234375,0 -0.375,-0.09375 0.28125,-0.09375 0.3125,-0.34375 0.3125,-0.390625 0,-0.15625 -0.125,-0.25 -0.28125,-0.25 -0.203125,0 -0.40625,0.15625 -0.40625,0.421875 0,0.34375 0.390625,0.5 0.734375,0.5 0.328125,0 0.609375,-0.1875 0.78125,-0.484375 C 2.015625,-0.0625 2.390625,0.0625 2.671875,0.0625 c 0.8125,0 1.234375,-0.859375 1.234375,-1.0625 0,-0.09375 -0.09375,-0.09375 -0.109375,-0.09375 -0.109375,0 -0.109375,0.046875 -0.140625,0.125 -0.140625,0.484375 -0.5625,0.84375 -0.953125,0.84375 -0.28125,0 -0.421875,-0.1875 -0.421875,-0.453125 0,-0.1875 0.171875,-0.8125 0.359375,-1.59375 C 2.78125,-2.703125 3.09375,-2.875 3.328125,-2.875 c 0.015625,0 0.21875,0 0.375,0.09375 -0.21875,0.0625 -0.3125,0.265625 -0.3125,0.390625 0,0.140625 0.125,0.25 0.28125,0.25 0.15625,0 0.390625,-0.125 0.390625,-0.421875 0,-0.390625 -0.453125,-0.515625 -0.71875,-0.515625 -0.359375,0 -0.640625,0.234375 -0.78125,0.5 -0.125,-0.28125 -0.453125,-0.5 -0.84375,-0.5 C 0.9375,-3.078125 0.5,-2.21875 0.5,-2 c 0,0.078125 0.09375,0.078125 0.109375,0.078125 0.09375,0 0.09375,-0.015625 0.140625,-0.109375 C 0.921875,-2.578125 1.359375,-2.875 1.703125,-2.875 1.9375,-2.875 2.125,-2.75 2.125,-2.421875 2.125,-2.28125 2.03125,-1.9375 1.96875,-1.6875 Z m 0,0\"\n           id=\"id-3c6d6c19-d049-40bb-889b-6626e9f83849-4\" />\n      </symbol>\n    </g>\n    <g\n       id=\"id-09465c05-0d07-4d10-b180-a2fc628170e1-5\">\n      <symbol\n         overflow=\"visible\"\n         id=\"id-235adb31-324b-4ffd-9dd2-8ba05052e0d2-4\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"\"\n           id=\"id-970a6b35-87f0-4cf8-a399-ab5356c2066e-8\" />\n      </symbol>\n      <symbol\n         overflow=\"visible\"\n         id=\"id-650cfdb9-8baa-4058-973a-c7421a1382a3-5\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"m 3.65625,-3.984375 h 0.859375 c 0.203125,0 0.296875,0 0.296875,-0.203125 0,-0.109375 -0.09375,-0.109375 -0.265625,-0.109375 H 3.71875 L 3.921875,-5.4375 c 0.046875,-0.203125 0.1875,-0.90625 0.25,-1.03125 0.078125,-0.1875 0.25,-0.34375 0.46875,-0.34375 0.03125,0 0.296875,0 0.484375,0.1875 -0.4375,0.03125 -0.546875,0.390625 -0.546875,0.53125 0,0.234375 0.1875,0.359375 0.375,0.359375 C 5.21875,-5.734375 5.5,-5.96875 5.5,-6.34375 c 0,-0.453125 -0.453125,-0.6875 -0.859375,-0.6875 -0.34375,0 -0.96875,0.1875 -1.265625,1.171875 -0.0625,0.203125 -0.09375,0.3125 -0.328125,1.5625 h -0.6875 c -0.203125,0 -0.3125,0 -0.3125,0.1875 0,0.125 0.09375,0.125 0.28125,0.125 h 0.65625 L 2.25,-0.046875 c -0.1875,0.96875 -0.359375,1.875 -0.875,1.875 -0.046875,0 -0.28125,0 -0.484375,-0.1875 C 1.359375,1.609375 1.453125,1.25 1.453125,1.109375 1.453125,0.875 1.265625,0.75 1.078125,0.75 0.8125,0.75 0.53125,0.984375 0.53125,1.359375 c 0,0.4375 0.4375,0.6875 0.84375,0.6875 0.546875,0 0.953125,-0.59375 1.125,-0.96875 0.328125,-0.625 0.546875,-1.828125 0.5625,-1.90625 z m 0,0\"\n           id=\"id-39bf9be7-c9d7-492c-84ab-39a21298153a-0\" />\n      </symbol>\n      <symbol\n         overflow=\"visible\"\n         id=\"id-c85e3329-0aa1-498d-9861-c8273f944b1a-5\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"\"\n           id=\"id-60009086-4b3e-4e93-83d3-0555a117a54c-60\" />\n      </symbol>\n      <symbol\n         overflow=\"visible\"\n         id=\"id-0d462dda-c632-4452-85aa-e0428c8be79c-7\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"M 1.734375,-0.734375 C 1.671875,-0.5 1.4375,-0.125 1.078125,-0.125 c -0.015625,0 -0.234375,0 -0.375,-0.09375 0.28125,-0.09375 0.3125,-0.34375 0.3125,-0.390625 0,-0.15625 -0.125,-0.25 -0.28125,-0.25 -0.203125,0 -0.40625,0.15625 -0.40625,0.421875 0,0.34375 0.390625,0.5 0.734375,0.5 0.328125,0 0.609375,-0.1875 0.78125,-0.484375 C 2.015625,-0.0625 2.390625,0.0625 2.671875,0.0625 c 0.8125,0 1.234375,-0.859375 1.234375,-1.0625 0,-0.09375 -0.09375,-0.09375 -0.109375,-0.09375 -0.109375,0 -0.109375,0.046875 -0.140625,0.125 -0.140625,0.484375 -0.5625,0.84375 -0.953125,0.84375 -0.28125,0 -0.421875,-0.1875 -0.421875,-0.453125 0,-0.1875 0.171875,-0.8125 0.359375,-1.59375 C 2.78125,-2.703125 3.09375,-2.875 3.328125,-2.875 c 0.015625,0 0.21875,0 0.375,0.09375 -0.21875,0.0625 -0.3125,0.265625 -0.3125,0.390625 0,0.140625 0.125,0.25 0.28125,0.25 0.15625,0 0.390625,-0.125 0.390625,-0.421875 0,-0.390625 -0.453125,-0.515625 -0.71875,-0.515625 -0.359375,0 -0.640625,0.234375 -0.78125,0.5 -0.125,-0.28125 -0.453125,-0.5 -0.84375,-0.5 C 0.9375,-3.078125 0.5,-2.21875 0.5,-2 c 0,0.078125 0.09375,0.078125 0.109375,0.078125 0.09375,0 0.09375,-0.015625 0.140625,-0.109375 C 0.921875,-2.578125 1.359375,-2.875 1.703125,-2.875 1.9375,-2.875 2.125,-2.75 2.125,-2.421875 2.125,-2.28125 2.03125,-1.9375 1.96875,-1.6875 Z m 0,0\"\n           id=\"id-16a2c3d4-54ef-4d27-992e-1c88a3d09f8c-3\" />\n      </symbol>\n    </g>\n    <g\n       id=\"id-6cad75ff-70ee-4e5e-9531-1241c325f032-1\"\n       style=\"stroke-width:0\">\n      <symbol\n         overflow=\"visible\"\n         id=\"id-b7a25d62-0566-45f6-aef2-9ac0c79a2d8f-1\"\n         style=\"stroke-width:0\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"\"\n           id=\"id-f8dcc3e8-7cfa-4e3f-ac6f-5fb6300f84d7-7\" />\n      </symbol>\n      <symbol\n         overflow=\"visible\"\n         id=\"id-eb67eb4a-8e6e-4f17-9432-c29e5475a9eb-0\"\n         style=\"stroke-width:0\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"M 9.234375,-6.046875 C 9.328125,-6.40625 9.34375,-6.5 10.09375,-6.5 c 0.21875,0 0.3125,0 0.3125,-0.203125 0,-0.109375 -0.09375,-0.109375 -0.265625,-0.109375 h -1.3125 c -0.265625,0 -0.28125,0 -0.390625,0.1875 L 4.796875,-0.9375 4.015625,-6.578125 C 3.984375,-6.8125 3.96875,-6.8125 3.703125,-6.8125 H 2.34375 c -0.1875,0 -0.296875,0 -0.296875,0.1875 0,0.125 0.09375,0.125 0.28125,0.125 0.140625,0 0.3125,0.015625 0.4375,0.015625 0.15625,0.03125 0.21875,0.046875 0.21875,0.171875 0,0.03125 -0.015625,0.0625 -0.046875,0.1875 l -1.265625,5.0625 c -0.09375,0.40625 -0.265625,0.71875 -1.078125,0.75 -0.046875,0 -0.171875,0.015625 -0.171875,0.1875 0,0.09375 0.0625,0.125 0.140625,0.125 0.3125,0 0.65625,-0.03125 1,-0.03125 C 1.890625,-0.03125 2.25,0 2.578125,0 c 0.046875,0 0.1875,0 0.1875,-0.203125 0,-0.109375 -0.109375,-0.109375 -0.1875,-0.109375 -0.5625,0 -0.671875,-0.203125 -0.671875,-0.4375 0,-0.0625 0,-0.125 0.03125,-0.234375 L 3.296875,-6.40625 H 3.3125 l 0.859375,6.171875 C 4.1875,-0.109375 4.203125,0 4.3125,0 4.421875,0 4.484375,-0.109375 4.53125,-0.171875 l 4.03125,-6.3125 h 0.015625 l -1.4375,5.703125 c -0.09375,0.390625 -0.109375,0.46875 -0.90625,0.46875 -0.15625,0 -0.265625,0 -0.265625,0.1875 C 5.96875,0 6.078125,0 6.109375,0 6.390625,0 7.0625,-0.03125 7.34375,-0.03125 7.75,-0.03125 8.1875,0 8.59375,0 8.65625,0 8.78125,0 8.78125,-0.203125 8.78125,-0.3125 8.6875,-0.3125 8.5,-0.3125 c -0.359375,0 -0.640625,0 -0.640625,-0.171875 0,-0.046875 0,-0.0625 0.046875,-0.25 z m 0,0\"\n           id=\"id-cf187999-3202-493f-a429-f597203a66a7-5\" />\n      </symbol>\n    </g>\n    <g\n       id=\"id-6a93de94-6478-4962-aa32-d1fc5ccdf1ed-6\"\n       style=\"stroke-width:0\">\n      <symbol\n         overflow=\"visible\"\n         id=\"id-cd2217d0-74c1-43b9-816c-3c3f97468f1e-4\"\n         style=\"stroke-width:0\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"\"\n           id=\"id-3d7b7c9e-b044-4338-951e-a7f32f48f4b3-3\" />\n      </symbol>\n      <symbol\n         overflow=\"visible\"\n         id=\"id-cac228d1-c9bf-4338-8dc1-e224feb356d0-5\"\n         style=\"stroke-width:0\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"M 0.453125,1.21875 C 0.375,1.5625 0.34375,1.625 -0.09375,1.625 c -0.109375,0 -0.21875,0 -0.21875,0.1875 0,0.078125 0.046875,0.125 0.125,0.125 0.265625,0 0.5625,-0.03125 0.828125,-0.03125 0.34375,0 0.671875,0.03125 1,0.03125 0.046875,0 0.171875,0 0.171875,-0.203125 C 1.8125,1.625 1.71875,1.625 1.578125,1.625 c -0.5,0 -0.5,-0.0625 -0.5,-0.15625 0,-0.125 0.421875,-1.75 0.484375,-2 0.125,0.296875 0.40625,0.640625 0.921875,0.640625 1.15625,0 2.40625,-1.453125 2.40625,-2.921875 0,-0.9375 -0.578125,-1.59375 -1.328125,-1.59375 -0.5,0 -0.984375,0.359375 -1.3125,0.75 -0.09375,-0.546875 -0.53125,-0.75 -0.890625,-0.75 -0.46875,0 -0.65625,0.390625 -0.734375,0.5625 C 0.4375,-3.5 0.3125,-2.90625 0.3125,-2.875 c 0,0.109375 0.09375,0.109375 0.109375,0.109375 0.109375,0 0.109375,-0.015625 0.171875,-0.234375 0.171875,-0.703125 0.375,-1.1875 0.734375,-1.1875 0.171875,0 0.3125,0.078125 0.3125,0.453125 0,0.234375 -0.03125,0.34375 -0.078125,0.515625 z m 1.75,-4.328125 C 2.265625,-3.375 2.546875,-3.65625 2.71875,-3.8125 c 0.359375,-0.296875 0.640625,-0.375 0.8125,-0.375 0.390625,0 0.640625,0.34375 0.640625,0.9375 0,0.59375 -0.328125,1.734375 -0.515625,2.109375 -0.34375,0.703125 -0.8125,1.03125 -1.1875,1.03125 C 1.8125,-0.109375 1.6875,-0.9375 1.6875,-1 c 0,-0.015625 0,-0.03125 0.03125,-0.15625 z m 0,0\"\n           id=\"id-27a1e8fc-605f-4f6a-af21-abc4ff23f334-8\" />\n      </symbol>\n      <symbol\n         overflow=\"visible\"\n         id=\"id-40ae5e12-7541-461a-b610-43b2a7bb7fb7-3\"\n         style=\"stroke-width:0\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"\"\n           id=\"id-fac32928-41f4-4d8a-b16b-7a1347d5b99c-1\" />\n      </symbol>\n      <symbol\n         overflow=\"visible\"\n         id=\"id-266dd85f-da88-4e91-9038-f8de24a459a1-5\"\n         style=\"stroke-width:0\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"M 3.875,-2.625 C 3.90625,-2.71875 3.90625,-2.734375 3.90625,-2.78125 3.90625,-2.921875 3.796875,-3 3.671875,-3 3.59375,-3 3.46875,-2.96875 3.390625,-2.84375 3.359375,-2.796875 3.3125,-2.578125 3.28125,-2.4375 L 3.125,-1.859375 c -0.03125,0.171875 -0.25,1.046875 -0.28125,1.125 0,0 -0.3125,0.609375 -0.84375,0.609375 -0.484375,0 -0.484375,-0.453125 -0.484375,-0.578125 0,-0.375 0.15625,-0.8125 0.375,-1.359375 C 1.96875,-2.28125 2,-2.359375 2,-2.484375 2,-2.8125 1.71875,-3.078125 1.34375,-3.078125 0.640625,-3.078125 0.328125,-2.125 0.328125,-2 c 0,0.078125 0.09375,0.078125 0.125,0.078125 0.09375,0 0.09375,-0.03125 0.125,-0.109375 C 0.75,-2.609375 1.046875,-2.875 1.328125,-2.875 1.4375,-2.875 1.5,-2.796875 1.5,-2.640625 c 0,0.171875 -0.0625,0.3125 -0.09375,0.40625 C 1.0625,-1.375 1,-1.125 1,-0.8125 1,-0.703125 1,-0.375 1.265625,-0.140625 1.484375,0.03125 1.78125,0.0625 1.96875,0.0625 2.25,0.0625 2.5,-0.03125 2.71875,-0.25 2.640625,0.140625 2.5625,0.4375 2.265625,0.78125 2.078125,1 1.796875,1.21875 1.421875,1.21875 c -0.046875,0 -0.375,0 -0.515625,-0.21875 0.375,-0.046875 0.375,-0.375 0.375,-0.390625 0,-0.21875 -0.203125,-0.265625 -0.265625,-0.265625 -0.171875,0 -0.40625,0.140625 -0.40625,0.46875 0,0.34375 0.328125,0.609375 0.828125,0.609375 C 2.140625,1.421875 3,0.875 3.21875,0 Z m 0,0\"\n           id=\"id-453ebdbd-06cb-402e-ae62-ac1a93b87f26-5\" />\n      </symbol>\n    </g>\n    <marker\n       style=\"overflow:visible\"\n       id=\"Arrow2Mend-8-2-6-4\"\n       refX=\"0\"\n       refY=\"0\"\n       orient=\"auto\"\n       inkscape:stockid=\"Arrow2Mend\"\n       inkscape:isstock=\"true\">\n      <path\n         transform=\"scale(-0.6)\"\n         d=\"M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z\"\n         style=\"fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1\"\n         id=\"path5660-9-8-0-5\" />\n    </marker>\n    <g\n       id=\"id-405c5a41-a781-45a8-aa25-f942f4656149-6\"\n       style=\"stroke-width:0\">\n      <symbol\n         overflow=\"visible\"\n         id=\"id-6bb4816e-903c-44b8-9e4c-b209eb05b8fd-9\"\n         style=\"stroke-width:0\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"\"\n           id=\"id-fb38ec55-12d8-4d55-8bf7-e98b2a015295-6\" />\n      </symbol>\n      <symbol\n         overflow=\"visible\"\n         id=\"id-a03fa650-8bf7-4421-8184-3dc62ca47bd7-3\"\n         style=\"stroke-width:0\">\n        <path\n           style=\"stroke:none;stroke-width:0\"\n           d=\"M 3.734375,-6.03125 C 3.8125,-6.390625 3.84375,-6.5 4.78125,-6.5 c 0.296875,0 0.375,0 0.375,-0.1875 0,-0.125 -0.109375,-0.125 -0.15625,-0.125 -0.328125,0 -1.140625,0.03125 -1.46875,0.03125 -0.296875,0 -1.03125,-0.03125 -1.328125,-0.03125 -0.0625,0 -0.1875,0 -0.1875,0.203125 0,0.109375 0.09375,0.109375 0.28125,0.109375 0.015625,0 0.203125,0 0.375,0.015625 0.171875,0.03125 0.265625,0.03125 0.265625,0.171875 0,0.03125 0,0.0625 -0.03125,0.1875 L 1.5625,-0.78125 c -0.09375,0.390625 -0.109375,0.46875 -0.90625,0.46875 -0.171875,0 -0.265625,0 -0.265625,0.203125 C 0.390625,0 0.484375,0 0.65625,0 h 4.625 C 5.515625,0 5.515625,0 5.578125,-0.171875 L 6.375,-2.328125 c 0.03125,-0.109375 0.03125,-0.125 0.03125,-0.140625 0,-0.03125 -0.03125,-0.109375 -0.109375,-0.109375 -0.09375,0 -0.109375,0.0625 -0.171875,0.21875 -0.34375,0.90625 -0.78125,2.046875 -2.5,2.046875 H 2.6875 c -0.140625,0 -0.171875,0 -0.21875,0 -0.109375,-0.015625 -0.140625,-0.03125 -0.140625,-0.109375 0,-0.03125 0,-0.046875 0.046875,-0.21875 z m 0,0\"\n           id=\"id-e238fe0f-9ecd-4c31-a633-8727f7d156af-0\" />\n      </symbol>\n    </g>\n  </defs>\n  <sodipodi:namedview\n     id=\"base\"\n     pagecolor=\"#ffffff\"\n     bordercolor=\"#666666\"\n     borderopacity=\"1.0\"\n     inkscape:pageopacity=\"0.0\"\n     inkscape:pageshadow=\"2\"\n     inkscape:zoom=\"1\"\n     inkscape:cx=\"240.27004\"\n     inkscape:cy=\"135.98396\"\n     inkscape:document-units=\"mm\"\n     inkscape:current-layer=\"layer1\"\n     inkscape:document-rotation=\"0\"\n     showgrid=\"true\"\n     inkscape:window-width=\"1600\"\n     inkscape:window-height=\"834\"\n     inkscape:window-x=\"-8\"\n     inkscape:window-y=\"-8\"\n     inkscape:window-maximized=\"1\"\n     fit-margin-top=\"0\"\n     fit-margin-left=\"0\"\n     fit-margin-right=\"0\"\n     fit-margin-bottom=\"0\"\n     inkscape:snap-grids=\"true\"\n     inkscape:snap-object-midpoints=\"true\"\n     inkscape:snap-page=\"true\">\n    <inkscape:grid\n       type=\"xygrid\"\n       id=\"grid4823\"\n       originx=\"0.74938879\"\n       originy=\"84.527744\" />\n  </sodipodi:namedview>\n  <metadata\n     id=\"metadata3505\">\n    <rdf:RDF>\n      <cc:Work\n         rdf:about=\"\">\n        <dc:format>image/svg+xml</dc:format>\n        <dc:type\n           rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\" />\n        <dc:title></dc:title>\n      </cc:Work>\n    </rdf:RDF>\n  </metadata>\n  <g\n     inkscape:label=\"Layer 1\"\n     inkscape:groupmode=\"layer\"\n     id=\"layer1\"\n     transform=\"translate(-59.973629,15.431581)\">\n    <path\n       style=\"fill:none;stroke:#000000;stroke-width:0.362308;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;marker-start:url(#Arrow2Mstart);stop-color:#000000\"\n       id=\"path2834-1\"\n       sodipodi:type=\"arc\"\n       sodipodi:cx=\"115.84163\"\n       sodipodi:cy=\"-153.73154\"\n       sodipodi:rx=\"194.48029\"\n       sodipodi:ry=\"194.48029\"\n       sodipodi:start=\"1.4618037\"\n       sodipodi:end=\"1.5606351\"\n       sodipodi:open=\"true\"\n       sodipodi:arc-type=\"arc\"\n       d=\"m 136.9966,39.594738 a 194.48029,194.48029 0 0 1 -19.17885,1.143971\" />\n    <path\n       style=\"fill:none;stroke:#999999;stroke-width:0.362308;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1\"\n       d=\"m 118.47673,65.508642 39.05553,7e-6\"\n       id=\"path846-1-6-6\" />\n    <path\n       style=\"fill:none;stroke:#000000;stroke-width:0.362308;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;marker-end:url(#Arrow2Mend-8)\"\n       d=\"m 118.6876,72.670801 h 11.15872\"\n       id=\"path5631-0\" />\n    <path\n       style=\"fill:none;stroke:#999999;stroke-width:0.362308;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1\"\n       d=\"m 118.47673,-14.315707 -1e-5,100.428536\"\n       id=\"path846-1-6\" />\n    <path\n       style=\"fill:none;stroke:#999999;stroke-width:0.362308;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stop-color:#000000\"\n       id=\"path2834\"\n       sodipodi:type=\"arc\"\n       sodipodi:cx=\"115.84163\"\n       sodipodi:cy=\"-153.73154\"\n       sodipodi:rx=\"219.02948\"\n       sodipodi:ry=\"219.02948\"\n       sodipodi:start=\"1.325519\"\n       sodipodi:end=\"1.8157574\"\n       sodipodi:open=\"true\"\n       sodipodi:arc-type=\"arc\"\n       d=\"M 169.02754,58.742395 A 219.02948,219.02948 0 0 1 62.722915,58.759205\" />\n    <g\n       id=\"pendulum\"\n       transform=\"matrix(4.2174699,0,0,4.2174699,-190.77928,-286.80844)\"\n       style=\"stroke-width:0.859066\">\n      <path\n         style=\"fill:none;stroke:#337ab7;stroke-width:0.25772;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1\"\n         d=\"M 73.327379,65.127422 V 83.537545\"\n         id=\"path2832\" />\n      <path\n         style=\"fill:none;stroke:#d9534f;stroke-width:0.227294px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1\"\n         d=\"m 73.327379,83.537545 c 0,2.431353 0,2.431353 0,2.431353\"\n         id=\"path2844\" />\n      <circle\n         style=\"fill:#d9534f;stroke:#d9534f;stroke-width:0.859066;stop-color:#000000\"\n         id=\"path2867\"\n         cx=\"73.327377\"\n         cy=\"83.537544\"\n         r=\"0.80770677\" />\n    </g>\n    <rect\n       style=\"fill:none;stroke:none;stroke-width:7.24622;stop-color:#000000\"\n       id=\"rect2838\"\n       width=\"101.29106\"\n       height=\"100.96758\"\n       x=\"59.973629\"\n       y=\"-11.03579\" />\n    <ellipse\n       style=\"fill:#000000;stroke:none;stroke-width:1.53412;stop-color:#000000\"\n       id=\"path2874\"\n       cx=\"81.418373\"\n       cy=\"1.1412462\"\n       rx=\"2.9712282e-06\"\n       ry=\"1.5498476e-06\" />\n    <g\n       id=\"f_x_pos\"\n       style=\"fill:#5cb85c;stroke-width:0.859066\"\n       transform=\"matrix(4.2174699,0,0,4.2174699,-190.77928,-286.80844)\">\n      <circle\n         style=\"fill:#5cb85c;stroke:none;stroke-width:0.171813;stop-color:#000000\"\n         id=\"path4881-5\"\n         cx=\"72.019669\"\n         cy=\"83.537544\"\n         r=\"0.0049999999\" />\n    </g>\n    <g\n       transform=\"matrix(0.53651689,0,0,0.53651689,103.87087,66.95505)\"\n       ns2:version=\"1.3.0\"\n       ns2:texconverter=\"pdflatex\"\n       ns2:pdfconverter=\"inkscape\"\n       ns2:text=\"$f_x$\"\n       ns2:preamble=\"C:\\\\Users\\jmmau\\AppData\\Roaming\\inkscape\\extensions\\textext\\default_packages.tex\"\n       ns2:scale=\"0.750000000002\"\n       ns2:alignment=\"middle center\"\n       ns2:inkscapeversion=\"1.0.1\"\n       ns2:jacobian_sqrt=\"0.264584\"\n       id=\"g5000\"\n       style=\"stroke-width:1.78673\">\n      <defs\n         id=\"id-2084eb37-a0bb-44e1-b7e3-abd30c628642\">\n        <g\n           id=\"id-09465c05-0d07-4d10-b180-a2fc628170e1\">\n          <symbol\n             overflow=\"visible\"\n             id=\"id-235adb31-324b-4ffd-9dd2-8ba05052e0d2\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"\"\n               id=\"id-970a6b35-87f0-4cf8-a399-ab5356c2066e\" />\n          </symbol>\n          <symbol\n             overflow=\"visible\"\n             id=\"id-650cfdb9-8baa-4058-973a-c7421a1382a3\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"m 3.65625,-3.984375 h 0.859375 c 0.203125,0 0.296875,0 0.296875,-0.203125 0,-0.109375 -0.09375,-0.109375 -0.265625,-0.109375 H 3.71875 L 3.921875,-5.4375 c 0.046875,-0.203125 0.1875,-0.90625 0.25,-1.03125 0.078125,-0.1875 0.25,-0.34375 0.46875,-0.34375 0.03125,0 0.296875,0 0.484375,0.1875 -0.4375,0.03125 -0.546875,0.390625 -0.546875,0.53125 0,0.234375 0.1875,0.359375 0.375,0.359375 C 5.21875,-5.734375 5.5,-5.96875 5.5,-6.34375 c 0,-0.453125 -0.453125,-0.6875 -0.859375,-0.6875 -0.34375,0 -0.96875,0.1875 -1.265625,1.171875 -0.0625,0.203125 -0.09375,0.3125 -0.328125,1.5625 h -0.6875 c -0.203125,0 -0.3125,0 -0.3125,0.1875 0,0.125 0.09375,0.125 0.28125,0.125 h 0.65625 L 2.25,-0.046875 c -0.1875,0.96875 -0.359375,1.875 -0.875,1.875 -0.046875,0 -0.28125,0 -0.484375,-0.1875 C 1.359375,1.609375 1.453125,1.25 1.453125,1.109375 1.453125,0.875 1.265625,0.75 1.078125,0.75 0.8125,0.75 0.53125,0.984375 0.53125,1.359375 c 0,0.4375 0.4375,0.6875 0.84375,0.6875 0.546875,0 0.953125,-0.59375 1.125,-0.96875 0.328125,-0.625 0.546875,-1.828125 0.5625,-1.90625 z m 0,0\"\n               id=\"id-39bf9be7-c9d7-492c-84ab-39a21298153a\" />\n          </symbol>\n          <symbol\n             overflow=\"visible\"\n             id=\"id-c85e3329-0aa1-498d-9861-c8273f944b1a\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"\"\n               id=\"id-60009086-4b3e-4e93-83d3-0555a117a54c\" />\n          </symbol>\n          <symbol\n             overflow=\"visible\"\n             id=\"id-0d462dda-c632-4452-85aa-e0428c8be79c\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"M 1.734375,-0.734375 C 1.671875,-0.5 1.4375,-0.125 1.078125,-0.125 c -0.015625,0 -0.234375,0 -0.375,-0.09375 0.28125,-0.09375 0.3125,-0.34375 0.3125,-0.390625 0,-0.15625 -0.125,-0.25 -0.28125,-0.25 -0.203125,0 -0.40625,0.15625 -0.40625,0.421875 0,0.34375 0.390625,0.5 0.734375,0.5 0.328125,0 0.609375,-0.1875 0.78125,-0.484375 C 2.015625,-0.0625 2.390625,0.0625 2.671875,0.0625 c 0.8125,0 1.234375,-0.859375 1.234375,-1.0625 0,-0.09375 -0.09375,-0.09375 -0.109375,-0.09375 -0.109375,0 -0.109375,0.046875 -0.140625,0.125 -0.140625,0.484375 -0.5625,0.84375 -0.953125,0.84375 -0.28125,0 -0.421875,-0.1875 -0.421875,-0.453125 0,-0.1875 0.171875,-0.8125 0.359375,-1.59375 C 2.78125,-2.703125 3.09375,-2.875 3.328125,-2.875 c 0.015625,0 0.21875,0 0.375,0.09375 -0.21875,0.0625 -0.3125,0.265625 -0.3125,0.390625 0,0.140625 0.125,0.25 0.28125,0.25 0.15625,0 0.390625,-0.125 0.390625,-0.421875 0,-0.390625 -0.453125,-0.515625 -0.71875,-0.515625 -0.359375,0 -0.640625,0.234375 -0.78125,0.5 -0.125,-0.28125 -0.453125,-0.5 -0.84375,-0.5 C 0.9375,-3.078125 0.5,-2.21875 0.5,-2 c 0,0.078125 0.09375,0.078125 0.109375,0.078125 0.09375,0 0.09375,-0.015625 0.140625,-0.109375 C 0.921875,-2.578125 1.359375,-2.875 1.703125,-2.875 1.9375,-2.875 2.125,-2.75 2.125,-2.421875 2.125,-2.28125 2.03125,-1.9375 1.96875,-1.6875 Z m 0,0\"\n               id=\"id-16a2c3d4-54ef-4d27-992e-1c88a3d09f8c\" />\n          </symbol>\n        </g>\n      </defs>\n      <g\n         id=\"id-7182e453-942b-40ee-82fa-99e7ff80d954\"\n         transform=\"translate(-149.243,-127.734)\"\n         style=\"stroke-width:1.78673\">\n        <g\n           style=\"fill:#000000;fill-opacity:1;stroke-width:1.78673\"\n           id=\"id-10117bd8-a66b-4908-ad03-d8f0eb61246e\">\n          <g\n             transform=\"translate(148.712,134.765)\"\n             id=\"g4992\"\n             style=\"stroke-width:1.78673\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"m 3.65625,-3.984375 h 0.859375 c 0.203125,0 0.296875,0 0.296875,-0.203125 0,-0.109375 -0.09375,-0.109375 -0.265625,-0.109375 H 3.71875 L 3.921875,-5.4375 c 0.046875,-0.203125 0.1875,-0.90625 0.25,-1.03125 0.078125,-0.1875 0.25,-0.34375 0.46875,-0.34375 0.03125,0 0.296875,0 0.484375,0.1875 -0.4375,0.03125 -0.546875,0.390625 -0.546875,0.53125 0,0.234375 0.1875,0.359375 0.375,0.359375 C 5.21875,-5.734375 5.5,-5.96875 5.5,-6.34375 c 0,-0.453125 -0.453125,-0.6875 -0.859375,-0.6875 -0.34375,0 -0.96875,0.1875 -1.265625,1.171875 -0.0625,0.203125 -0.09375,0.3125 -0.328125,1.5625 h -0.6875 c -0.203125,0 -0.3125,0 -0.3125,0.1875 0,0.125 0.09375,0.125 0.28125,0.125 h 0.65625 L 2.25,-0.046875 c -0.1875,0.96875 -0.359375,1.875 -0.875,1.875 -0.046875,0 -0.28125,0 -0.484375,-0.1875 C 1.359375,1.609375 1.453125,1.25 1.453125,1.109375 1.453125,0.875 1.265625,0.75 1.078125,0.75 0.8125,0.75 0.53125,0.984375 0.53125,1.359375 c 0,0.4375 0.4375,0.6875 0.84375,0.6875 0.546875,0 0.953125,-0.59375 1.125,-0.96875 0.328125,-0.625 0.546875,-1.828125 0.5625,-1.90625 z m 0,0\"\n               id=\"id-542cad8d-d6b0-4034-ab67-f09f92bb4101\" />\n          </g>\n        </g>\n        <g\n           style=\"fill:#000000;fill-opacity:1;stroke-width:1.78673\"\n           id=\"id-36134410-7874-42c8-a449-4a2ed8df1346\">\n          <g\n             transform=\"translate(153.59,136.259)\"\n             id=\"g4996\"\n             style=\"stroke-width:1.78673\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"M 1.734375,-0.734375 C 1.671875,-0.5 1.4375,-0.125 1.078125,-0.125 c -0.015625,0 -0.234375,0 -0.375,-0.09375 0.28125,-0.09375 0.3125,-0.34375 0.3125,-0.390625 0,-0.15625 -0.125,-0.25 -0.28125,-0.25 -0.203125,0 -0.40625,0.15625 -0.40625,0.421875 0,0.34375 0.390625,0.5 0.734375,0.5 0.328125,0 0.609375,-0.1875 0.78125,-0.484375 C 2.015625,-0.0625 2.390625,0.0625 2.671875,0.0625 c 0.8125,0 1.234375,-0.859375 1.234375,-1.0625 0,-0.09375 -0.09375,-0.09375 -0.109375,-0.09375 -0.109375,0 -0.109375,0.046875 -0.140625,0.125 -0.140625,0.484375 -0.5625,0.84375 -0.953125,0.84375 -0.28125,0 -0.421875,-0.1875 -0.421875,-0.453125 0,-0.1875 0.171875,-0.8125 0.359375,-1.59375 C 2.78125,-2.703125 3.09375,-2.875 3.328125,-2.875 c 0.015625,0 0.21875,0 0.375,0.09375 -0.21875,0.0625 -0.3125,0.265625 -0.3125,0.390625 0,0.140625 0.125,0.25 0.28125,0.25 0.15625,0 0.390625,-0.125 0.390625,-0.421875 0,-0.390625 -0.453125,-0.515625 -0.71875,-0.515625 -0.359375,0 -0.640625,0.234375 -0.78125,0.5 -0.125,-0.28125 -0.453125,-0.5 -0.84375,-0.5 C 0.9375,-3.078125 0.5,-2.21875 0.5,-2 c 0,0.078125 0.09375,0.078125 0.109375,0.078125 0.09375,0 0.09375,-0.015625 0.140625,-0.109375 C 0.921875,-2.578125 1.359375,-2.875 1.703125,-2.875 1.9375,-2.875 2.125,-2.75 2.125,-2.421875 2.125,-2.28125 2.03125,-1.9375 1.96875,-1.6875 Z m 0,0\"\n               id=\"id-21951c1f-9c9a-4713-ac02-0cec3ee596a2\" />\n          </g>\n        </g>\n      </g>\n    </g>\n    <circle\n       style=\"fill:#5e4485;stroke:none;stroke-width:1.81155;stroke-miterlimit:4;stroke-dasharray:0.724617, 1.44923;stroke-dashoffset:0;stop-color:#000000\"\n       id=\"path5629\"\n       cx=\"118.47675\"\n       cy=\"-13.199837\"\n       r=\"2.2317443\" />\n    <path\n       style=\"fill:none;stroke:#000000;stroke-width:0.362308;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;marker-end:url(#Arrow2Mend)\"\n       d=\"m 101.16671,65.5127 h 11.15872\"\n       id=\"path5631\" />\n    <g\n       id=\"f_x_pos-1\"\n       style=\"fill:#5cb85c;stroke-width:0.859066\"\n       transform=\"matrix(4.2174699,0,0,4.2174699,-163.99836,-287.92431)\">\n      <circle\n         style=\"fill:#5cb85c;stroke:none;stroke-width:0.171813;stop-color:#000000\"\n         id=\"path4881-5-2\"\n         cx=\"72.019669\"\n         cy=\"83.537544\"\n         r=\"0.0049999999\" />\n    </g>\n    <g\n       transform=\"matrix(0.536517,0,0,0.536517,121.74829,75.432386)\"\n       ns2:version=\"1.3.0\"\n       ns2:texconverter=\"pdflatex\"\n       ns2:pdfconverter=\"inkscape\"\n       ns2:text=\"$p_x$\"\n       ns2:preamble=\"C:\\\\Users\\jmmau\\AppData\\Roaming\\inkscape\\extensions\\textext\\default_packages.tex\"\n       ns2:scale=\"0.36060278588370587\"\n       ns2:alignment=\"middle center\"\n       ns2:inkscapeversion=\"1.0.1\"\n       ns2:jacobian_sqrt=\"0.127213\"\n       style=\"stroke-width:0\"\n       id=\"g5000-4\">\n      <defs\n         id=\"id-839390c0-827f-4fc8-924b-e192754dfc84\">\n        <g\n           id=\"id-89dddef3-8403-4f99-a826-7f60b9e011df\"\n           style=\"stroke-width:0\">\n          <symbol\n             overflow=\"visible\"\n             id=\"id-201507c8-0be6-4b98-b204-e6c80091e85b\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"\"\n               id=\"id-ec839d7d-bd2f-4891-915c-4ae2bb70a050\" />\n          </symbol>\n          <symbol\n             overflow=\"visible\"\n             id=\"id-469bb503-0bdd-4d08-a256-4159c12302fb\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"M 0.453125,1.21875 C 0.375,1.5625 0.34375,1.625 -0.09375,1.625 c -0.109375,0 -0.21875,0 -0.21875,0.1875 0,0.078125 0.046875,0.125 0.125,0.125 0.265625,0 0.5625,-0.03125 0.828125,-0.03125 0.34375,0 0.671875,0.03125 1,0.03125 0.046875,0 0.171875,0 0.171875,-0.203125 C 1.8125,1.625 1.71875,1.625 1.578125,1.625 c -0.5,0 -0.5,-0.0625 -0.5,-0.15625 0,-0.125 0.421875,-1.75 0.484375,-2 0.125,0.296875 0.40625,0.640625 0.921875,0.640625 1.15625,0 2.40625,-1.453125 2.40625,-2.921875 0,-0.9375 -0.578125,-1.59375 -1.328125,-1.59375 -0.5,0 -0.984375,0.359375 -1.3125,0.75 -0.09375,-0.546875 -0.53125,-0.75 -0.890625,-0.75 -0.46875,0 -0.65625,0.390625 -0.734375,0.5625 C 0.4375,-3.5 0.3125,-2.90625 0.3125,-2.875 c 0,0.109375 0.09375,0.109375 0.109375,0.109375 0.109375,0 0.109375,-0.015625 0.171875,-0.234375 0.171875,-0.703125 0.375,-1.1875 0.734375,-1.1875 0.171875,0 0.3125,0.078125 0.3125,0.453125 0,0.234375 -0.03125,0.34375 -0.078125,0.515625 z m 1.75,-4.328125 C 2.265625,-3.375 2.546875,-3.65625 2.71875,-3.8125 c 0.359375,-0.296875 0.640625,-0.375 0.8125,-0.375 0.390625,0 0.640625,0.34375 0.640625,0.9375 0,0.59375 -0.328125,1.734375 -0.515625,2.109375 -0.34375,0.703125 -0.8125,1.03125 -1.1875,1.03125 C 1.8125,-0.109375 1.6875,-0.9375 1.6875,-1 c 0,-0.015625 0,-0.03125 0.03125,-0.15625 z m 0,0\"\n               id=\"id-2c7b93d1-6f74-47e7-899f-8b7423bd1a3f\" />\n          </symbol>\n          <symbol\n             overflow=\"visible\"\n             id=\"id-771003bb-5028-4073-aa49-f3b2e325a38b\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"\"\n               id=\"id-136f285f-47ce-47cc-882e-de37d2bac632\" />\n          </symbol>\n          <symbol\n             overflow=\"visible\"\n             id=\"id-a1e8a53b-a781-4067-bca0-1865531122e4\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"M 1.734375,-0.734375 C 1.671875,-0.5 1.4375,-0.125 1.078125,-0.125 c -0.015625,0 -0.234375,0 -0.375,-0.09375 0.28125,-0.09375 0.3125,-0.34375 0.3125,-0.390625 0,-0.15625 -0.125,-0.25 -0.28125,-0.25 -0.203125,0 -0.40625,0.15625 -0.40625,0.421875 0,0.34375 0.390625,0.5 0.734375,0.5 0.328125,0 0.609375,-0.1875 0.78125,-0.484375 C 2.015625,-0.0625 2.390625,0.0625 2.671875,0.0625 c 0.8125,0 1.234375,-0.859375 1.234375,-1.0625 0,-0.09375 -0.09375,-0.09375 -0.109375,-0.09375 -0.109375,0 -0.109375,0.046875 -0.140625,0.125 -0.140625,0.484375 -0.5625,0.84375 -0.953125,0.84375 -0.28125,0 -0.421875,-0.1875 -0.421875,-0.453125 0,-0.1875 0.171875,-0.8125 0.359375,-1.59375 C 2.78125,-2.703125 3.09375,-2.875 3.328125,-2.875 c 0.015625,0 0.21875,0 0.375,0.09375 -0.21875,0.0625 -0.3125,0.265625 -0.3125,0.390625 0,0.140625 0.125,0.25 0.28125,0.25 0.15625,0 0.390625,-0.125 0.390625,-0.421875 0,-0.390625 -0.453125,-0.515625 -0.71875,-0.515625 -0.359375,0 -0.640625,0.234375 -0.78125,0.5 -0.125,-0.28125 -0.453125,-0.5 -0.84375,-0.5 C 0.9375,-3.078125 0.5,-2.21875 0.5,-2 c 0,0.078125 0.09375,0.078125 0.109375,0.078125 0.09375,0 0.09375,-0.015625 0.140625,-0.109375 C 0.921875,-2.578125 1.359375,-2.875 1.703125,-2.875 1.9375,-2.875 2.125,-2.75 2.125,-2.421875 2.125,-2.28125 2.03125,-1.9375 1.96875,-1.6875 Z m 0,0\"\n               id=\"id-6e1e2198-637c-488f-8640-ebe21b2d99c0\" />\n          </symbol>\n        </g>\n      </defs>\n      <g\n         id=\"id-f966cfda-8176-49f3-98d1-a41ec902a170\"\n         transform=\"translate(-148.4,-130.359)\"\n         style=\"stroke-width:0\">\n        <g\n           style=\"fill:#000000;fill-opacity:1;stroke-width:0\"\n           id=\"id-714a4c77-0957-48a7-b6f6-c3f2880f54c5\">\n          <g\n             transform=\"translate(148.712,134.765)\"\n             style=\"stroke-width:0\"\n             id=\"g6234\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"M 0.453125,1.21875 C 0.375,1.5625 0.34375,1.625 -0.09375,1.625 c -0.109375,0 -0.21875,0 -0.21875,0.1875 0,0.078125 0.046875,0.125 0.125,0.125 0.265625,0 0.5625,-0.03125 0.828125,-0.03125 0.34375,0 0.671875,0.03125 1,0.03125 0.046875,0 0.171875,0 0.171875,-0.203125 C 1.8125,1.625 1.71875,1.625 1.578125,1.625 c -0.5,0 -0.5,-0.0625 -0.5,-0.15625 0,-0.125 0.421875,-1.75 0.484375,-2 0.125,0.296875 0.40625,0.640625 0.921875,0.640625 1.15625,0 2.40625,-1.453125 2.40625,-2.921875 0,-0.9375 -0.578125,-1.59375 -1.328125,-1.59375 -0.5,0 -0.984375,0.359375 -1.3125,0.75 -0.09375,-0.546875 -0.53125,-0.75 -0.890625,-0.75 -0.46875,0 -0.65625,0.390625 -0.734375,0.5625 C 0.4375,-3.5 0.3125,-2.90625 0.3125,-2.875 c 0,0.109375 0.09375,0.109375 0.109375,0.109375 0.109375,0 0.109375,-0.015625 0.171875,-0.234375 0.171875,-0.703125 0.375,-1.1875 0.734375,-1.1875 0.171875,0 0.3125,0.078125 0.3125,0.453125 0,0.234375 -0.03125,0.34375 -0.078125,0.515625 z m 1.75,-4.328125 C 2.265625,-3.375 2.546875,-3.65625 2.71875,-3.8125 c 0.359375,-0.296875 0.640625,-0.375 0.8125,-0.375 0.390625,0 0.640625,0.34375 0.640625,0.9375 0,0.59375 -0.328125,1.734375 -0.515625,2.109375 -0.34375,0.703125 -0.8125,1.03125 -1.1875,1.03125 C 1.8125,-0.109375 1.6875,-0.9375 1.6875,-1 c 0,-0.015625 0,-0.03125 0.03125,-0.15625 z m 0,0\"\n               id=\"id-58871dee-2673-4277-94cf-e811099c2346\" />\n          </g>\n        </g>\n        <g\n           style=\"fill:#000000;fill-opacity:1;stroke-width:0\"\n           id=\"id-8e4c4e18-839f-4602-94ef-11f8836462cd\">\n          <g\n             transform=\"translate(153.725,136.259)\"\n             style=\"stroke-width:0\"\n             id=\"g6238\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"M 1.734375,-0.734375 C 1.671875,-0.5 1.4375,-0.125 1.078125,-0.125 c -0.015625,0 -0.234375,0 -0.375,-0.09375 0.28125,-0.09375 0.3125,-0.34375 0.3125,-0.390625 0,-0.15625 -0.125,-0.25 -0.28125,-0.25 -0.203125,0 -0.40625,0.15625 -0.40625,0.421875 0,0.34375 0.390625,0.5 0.734375,0.5 0.328125,0 0.609375,-0.1875 0.78125,-0.484375 C 2.015625,-0.0625 2.390625,0.0625 2.671875,0.0625 c 0.8125,0 1.234375,-0.859375 1.234375,-1.0625 0,-0.09375 -0.09375,-0.09375 -0.109375,-0.09375 -0.109375,0 -0.109375,0.046875 -0.140625,0.125 -0.140625,0.484375 -0.5625,0.84375 -0.953125,0.84375 -0.28125,0 -0.421875,-0.1875 -0.421875,-0.453125 0,-0.1875 0.171875,-0.8125 0.359375,-1.59375 C 2.78125,-2.703125 3.09375,-2.875 3.328125,-2.875 c 0.015625,0 0.21875,0 0.375,0.09375 -0.21875,0.0625 -0.3125,0.265625 -0.3125,0.390625 0,0.140625 0.125,0.25 0.28125,0.25 0.15625,0 0.390625,-0.125 0.390625,-0.421875 0,-0.390625 -0.453125,-0.515625 -0.71875,-0.515625 -0.359375,0 -0.640625,0.234375 -0.78125,0.5 -0.125,-0.28125 -0.453125,-0.5 -0.84375,-0.5 C 0.9375,-3.078125 0.5,-2.21875 0.5,-2 c 0,0.078125 0.09375,0.078125 0.109375,0.078125 0.09375,0 0.09375,-0.015625 0.140625,-0.109375 C 0.921875,-2.578125 1.359375,-2.875 1.703125,-2.875 1.9375,-2.875 2.125,-2.75 2.125,-2.421875 2.125,-2.28125 2.03125,-1.9375 1.96875,-1.6875 Z m 0,0\"\n               id=\"id-cd139d6e-4f07-4cc4-baa3-23e2d1ba6f4d\" />\n          </g>\n        </g>\n      </g>\n    </g>\n    <path\n       style=\"fill:none;stroke:#000000;stroke-width:0.362308;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;marker-end:url(#Arrow2Mend-8-2)\"\n       d=\"m 118.6876,81.649309 h 11.15872\"\n       id=\"path5631-0-8\" />\n    <g\n       transform=\"matrix(0.536517,0,0,0.536517,121.96086,84.513023)\"\n       ns2:version=\"1.3.0\"\n       ns2:texconverter=\"pdflatex\"\n       ns2:pdfconverter=\"inkscape\"\n       ns2:text=\"$v_x$\"\n       ns2:preamble=\"C:\\\\Users\\jmmau\\AppData\\Roaming\\inkscape\\extensions\\textext\\default_packages.tex\"\n       ns2:scale=\"0.36060278588370587\"\n       ns2:alignment=\"middle center\"\n       ns2:inkscapeversion=\"1.0.1\"\n       ns2:jacobian_sqrt=\"0.127213\"\n       style=\"stroke-width:0\"\n       id=\"g5000-4-7\">\n      <defs\n         id=\"id-feed054f-c36d-4258-af04-c15f05b3c1fb\">\n        <g\n           id=\"id-78a8471f-adc0-462c-8098-1a40c3ce8d75\"\n           style=\"stroke-width:0\">\n          <symbol\n             overflow=\"visible\"\n             id=\"id-8ff42f58-dcc9-4b6c-90a8-6180cc753b40\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"\"\n               id=\"id-f3f82317-c289-44de-99f4-5312b6d2639e\" />\n          </symbol>\n          <symbol\n             overflow=\"visible\"\n             id=\"id-4dc01438-ce3c-4a3e-9b5a-8b7649684a24\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"m 4.671875,-3.703125 c 0,-0.546875 -0.265625,-0.703125 -0.4375,-0.703125 -0.25,0 -0.5,0.265625 -0.5,0.484375 0,0.125 0.046875,0.1875 0.15625,0.296875 0.21875,0.203125 0.34375,0.453125 0.34375,0.8125 0,0.421875 -0.609375,2.703125 -1.765625,2.703125 -0.515625,0 -0.75,-0.34375 -0.75,-0.875 0,-0.546875 0.28125,-1.28125 0.578125,-2.109375 0.078125,-0.171875 0.125,-0.3125 0.125,-0.5 0,-0.4375 -0.3125,-0.8125 -0.8125,-0.8125 -0.9375,0 -1.3125,1.453125 -1.3125,1.53125 0,0.109375 0.09375,0.109375 0.109375,0.109375 0.109375,0 0.109375,-0.03125 0.15625,-0.1875 0.296875,-1 0.71875,-1.234375 1.015625,-1.234375 0.078125,0 0.25,0 0.25,0.3125 0,0.25 -0.109375,0.53125 -0.171875,0.703125 -0.4375,1.15625 -0.5625,1.609375 -0.5625,2.046875 0,1.078125 0.875,1.234375 1.328125,1.234375 1.671875,0 2.25,-3.296875 2.25,-3.8125 z m 0,0\"\n               id=\"id-880b47f9-8552-489f-bbf5-45a762219cc4\" />\n          </symbol>\n          <symbol\n             overflow=\"visible\"\n             id=\"id-60c8a860-7386-4c77-b5bf-a913f8117173\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"\"\n               id=\"id-7a4a3f98-046c-4feb-88af-9ac6be3cbb51\" />\n          </symbol>\n          <symbol\n             overflow=\"visible\"\n             id=\"id-f5f9e97b-dc58-4463-828e-396e50a467c0\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"M 1.734375,-0.734375 C 1.671875,-0.5 1.4375,-0.125 1.078125,-0.125 c -0.015625,0 -0.234375,0 -0.375,-0.09375 0.28125,-0.09375 0.3125,-0.34375 0.3125,-0.390625 0,-0.15625 -0.125,-0.25 -0.28125,-0.25 -0.203125,0 -0.40625,0.15625 -0.40625,0.421875 0,0.34375 0.390625,0.5 0.734375,0.5 0.328125,0 0.609375,-0.1875 0.78125,-0.484375 C 2.015625,-0.0625 2.390625,0.0625 2.671875,0.0625 c 0.8125,0 1.234375,-0.859375 1.234375,-1.0625 0,-0.09375 -0.09375,-0.09375 -0.109375,-0.09375 -0.109375,0 -0.109375,0.046875 -0.140625,0.125 -0.140625,0.484375 -0.5625,0.84375 -0.953125,0.84375 -0.28125,0 -0.421875,-0.1875 -0.421875,-0.453125 0,-0.1875 0.171875,-0.8125 0.359375,-1.59375 C 2.78125,-2.703125 3.09375,-2.875 3.328125,-2.875 c 0.015625,0 0.21875,0 0.375,0.09375 -0.21875,0.0625 -0.3125,0.265625 -0.3125,0.390625 0,0.140625 0.125,0.25 0.28125,0.25 0.15625,0 0.390625,-0.125 0.390625,-0.421875 0,-0.390625 -0.453125,-0.515625 -0.71875,-0.515625 -0.359375,0 -0.640625,0.234375 -0.78125,0.5 -0.125,-0.28125 -0.453125,-0.5 -0.84375,-0.5 C 0.9375,-3.078125 0.5,-2.21875 0.5,-2 c 0,0.078125 0.09375,0.078125 0.109375,0.078125 0.09375,0 0.09375,-0.015625 0.140625,-0.109375 C 0.921875,-2.578125 1.359375,-2.875 1.703125,-2.875 1.9375,-2.875 2.125,-2.75 2.125,-2.421875 2.125,-2.28125 2.03125,-1.9375 1.96875,-1.6875 Z m 0,0\"\n               id=\"id-3c6d6c19-d049-40bb-889b-6626e9f83849\" />\n          </symbol>\n        </g>\n      </defs>\n      <g\n         id=\"id-4fab7006-b126-4619-828f-f201a911795c\"\n         transform=\"translate(-149.009,-130.359)\"\n         style=\"stroke-width:0\">\n        <g\n           style=\"fill:#000000;fill-opacity:1;stroke-width:0\"\n           id=\"id-cc1a64fe-eb3e-479a-853f-b547007a4d47\">\n          <g\n             transform=\"translate(148.712,134.765)\"\n             style=\"stroke-width:0\"\n             id=\"g6542\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"m 4.671875,-3.703125 c 0,-0.546875 -0.265625,-0.703125 -0.4375,-0.703125 -0.25,0 -0.5,0.265625 -0.5,0.484375 0,0.125 0.046875,0.1875 0.15625,0.296875 0.21875,0.203125 0.34375,0.453125 0.34375,0.8125 0,0.421875 -0.609375,2.703125 -1.765625,2.703125 -0.515625,0 -0.75,-0.34375 -0.75,-0.875 0,-0.546875 0.28125,-1.28125 0.578125,-2.109375 0.078125,-0.171875 0.125,-0.3125 0.125,-0.5 0,-0.4375 -0.3125,-0.8125 -0.8125,-0.8125 -0.9375,0 -1.3125,1.453125 -1.3125,1.53125 0,0.109375 0.09375,0.109375 0.109375,0.109375 0.109375,0 0.109375,-0.03125 0.15625,-0.1875 0.296875,-1 0.71875,-1.234375 1.015625,-1.234375 0.078125,0 0.25,0 0.25,0.3125 0,0.25 -0.109375,0.53125 -0.171875,0.703125 -0.4375,1.15625 -0.5625,1.609375 -0.5625,2.046875 0,1.078125 0.875,1.234375 1.328125,1.234375 1.671875,0 2.25,-3.296875 2.25,-3.8125 z m 0,0\"\n               id=\"id-7edd731d-bd59-47c4-b3d6-0e458f1393bc\" />\n          </g>\n        </g>\n        <g\n           style=\"fill:#000000;fill-opacity:1;stroke-width:0\"\n           id=\"id-003ec733-3125-4abc-8ade-67dc7198e8be\">\n          <g\n             transform=\"translate(153.541,136.259)\"\n             style=\"stroke-width:0\"\n             id=\"g6546\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"M 1.734375,-0.734375 C 1.671875,-0.5 1.4375,-0.125 1.078125,-0.125 c -0.015625,0 -0.234375,0 -0.375,-0.09375 0.28125,-0.09375 0.3125,-0.34375 0.3125,-0.390625 0,-0.15625 -0.125,-0.25 -0.28125,-0.25 -0.203125,0 -0.40625,0.15625 -0.40625,0.421875 0,0.34375 0.390625,0.5 0.734375,0.5 0.328125,0 0.609375,-0.1875 0.78125,-0.484375 C 2.015625,-0.0625 2.390625,0.0625 2.671875,0.0625 c 0.8125,0 1.234375,-0.859375 1.234375,-1.0625 0,-0.09375 -0.09375,-0.09375 -0.109375,-0.09375 -0.109375,0 -0.109375,0.046875 -0.140625,0.125 -0.140625,0.484375 -0.5625,0.84375 -0.953125,0.84375 -0.28125,0 -0.421875,-0.1875 -0.421875,-0.453125 0,-0.1875 0.171875,-0.8125 0.359375,-1.59375 C 2.78125,-2.703125 3.09375,-2.875 3.328125,-2.875 c 0.015625,0 0.21875,0 0.375,0.09375 -0.21875,0.0625 -0.3125,0.265625 -0.3125,0.390625 0,0.140625 0.125,0.25 0.28125,0.25 0.15625,0 0.390625,-0.125 0.390625,-0.421875 0,-0.390625 -0.453125,-0.515625 -0.71875,-0.515625 -0.359375,0 -0.640625,0.234375 -0.78125,0.5 -0.125,-0.28125 -0.453125,-0.5 -0.84375,-0.5 C 0.9375,-3.078125 0.5,-2.21875 0.5,-2 c 0,0.078125 0.09375,0.078125 0.109375,0.078125 0.09375,0 0.09375,-0.015625 0.140625,-0.109375 C 0.921875,-2.578125 1.359375,-2.875 1.703125,-2.875 1.9375,-2.875 2.125,-2.75 2.125,-2.421875 2.125,-2.28125 2.03125,-1.9375 1.96875,-1.6875 Z m 0,0\"\n               id=\"id-2b49ecf8-c843-4d4b-a766-6f279bf7d974\" />\n          </g>\n        </g>\n      </g>\n    </g>\n    <path\n       style=\"fill:none;stroke:#000000;stroke-width:0.362308;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;marker-end:url(#Arrow2Mend-8-8)\"\n       d=\"M 140.79417,65.297767 V 54.139048\"\n       id=\"path5631-0-1\" />\n    <path\n       style=\"fill:none;stroke:#000000;stroke-width:0.362308;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;marker-end:url(#Arrow2Mend-8-2-6)\"\n       d=\"M 151.9529,65.297767 V 54.139051\"\n       id=\"path5631-0-8-4\" />\n    <g\n       transform=\"matrix(0.536517,0,0,0.536517,142.02022,56.137124)\"\n       ns2:version=\"1.3.0\"\n       ns2:texconverter=\"pdflatex\"\n       ns2:pdfconverter=\"inkscape\"\n       ns2:text=\"$p_y$\"\n       ns2:preamble=\"C:\\\\Users\\jmmau\\AppData\\Roaming\\inkscape\\extensions\\textext\\default_packages.tex\"\n       ns2:scale=\"0.36060278588370587\"\n       ns2:alignment=\"middle center\"\n       ns2:inkscapeversion=\"1.0.1\"\n       ns2:jacobian_sqrt=\"0.127213\"\n       style=\"stroke-width:0\"\n       id=\"g5000-4-8\">\n      <defs\n         id=\"id-a1ae0162-16bd-4b49-a1dd-0a00f388b176\">\n        <g\n           id=\"id-6a93de94-6478-4962-aa32-d1fc5ccdf1ed\"\n           style=\"stroke-width:0\">\n          <symbol\n             overflow=\"visible\"\n             id=\"id-cd2217d0-74c1-43b9-816c-3c3f97468f1e\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"\"\n               id=\"id-3d7b7c9e-b044-4338-951e-a7f32f48f4b3\" />\n          </symbol>\n          <symbol\n             overflow=\"visible\"\n             id=\"id-cac228d1-c9bf-4338-8dc1-e224feb356d0\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"M 0.453125,1.21875 C 0.375,1.5625 0.34375,1.625 -0.09375,1.625 c -0.109375,0 -0.21875,0 -0.21875,0.1875 0,0.078125 0.046875,0.125 0.125,0.125 0.265625,0 0.5625,-0.03125 0.828125,-0.03125 0.34375,0 0.671875,0.03125 1,0.03125 0.046875,0 0.171875,0 0.171875,-0.203125 C 1.8125,1.625 1.71875,1.625 1.578125,1.625 c -0.5,0 -0.5,-0.0625 -0.5,-0.15625 0,-0.125 0.421875,-1.75 0.484375,-2 0.125,0.296875 0.40625,0.640625 0.921875,0.640625 1.15625,0 2.40625,-1.453125 2.40625,-2.921875 0,-0.9375 -0.578125,-1.59375 -1.328125,-1.59375 -0.5,0 -0.984375,0.359375 -1.3125,0.75 -0.09375,-0.546875 -0.53125,-0.75 -0.890625,-0.75 -0.46875,0 -0.65625,0.390625 -0.734375,0.5625 C 0.4375,-3.5 0.3125,-2.90625 0.3125,-2.875 c 0,0.109375 0.09375,0.109375 0.109375,0.109375 0.109375,0 0.109375,-0.015625 0.171875,-0.234375 0.171875,-0.703125 0.375,-1.1875 0.734375,-1.1875 0.171875,0 0.3125,0.078125 0.3125,0.453125 0,0.234375 -0.03125,0.34375 -0.078125,0.515625 z m 1.75,-4.328125 C 2.265625,-3.375 2.546875,-3.65625 2.71875,-3.8125 c 0.359375,-0.296875 0.640625,-0.375 0.8125,-0.375 0.390625,0 0.640625,0.34375 0.640625,0.9375 0,0.59375 -0.328125,1.734375 -0.515625,2.109375 -0.34375,0.703125 -0.8125,1.03125 -1.1875,1.03125 C 1.8125,-0.109375 1.6875,-0.9375 1.6875,-1 c 0,-0.015625 0,-0.03125 0.03125,-0.15625 z m 0,0\"\n               id=\"id-27a1e8fc-605f-4f6a-af21-abc4ff23f334\" />\n          </symbol>\n          <symbol\n             overflow=\"visible\"\n             id=\"id-40ae5e12-7541-461a-b610-43b2a7bb7fb7\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"\"\n               id=\"id-fac32928-41f4-4d8a-b16b-7a1347d5b99c\" />\n          </symbol>\n          <symbol\n             overflow=\"visible\"\n             id=\"id-266dd85f-da88-4e91-9038-f8de24a459a1\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"M 3.875,-2.625 C 3.90625,-2.71875 3.90625,-2.734375 3.90625,-2.78125 3.90625,-2.921875 3.796875,-3 3.671875,-3 3.59375,-3 3.46875,-2.96875 3.390625,-2.84375 3.359375,-2.796875 3.3125,-2.578125 3.28125,-2.4375 L 3.125,-1.859375 c -0.03125,0.171875 -0.25,1.046875 -0.28125,1.125 0,0 -0.3125,0.609375 -0.84375,0.609375 -0.484375,0 -0.484375,-0.453125 -0.484375,-0.578125 0,-0.375 0.15625,-0.8125 0.375,-1.359375 C 1.96875,-2.28125 2,-2.359375 2,-2.484375 2,-2.8125 1.71875,-3.078125 1.34375,-3.078125 0.640625,-3.078125 0.328125,-2.125 0.328125,-2 c 0,0.078125 0.09375,0.078125 0.125,0.078125 0.09375,0 0.09375,-0.03125 0.125,-0.109375 C 0.75,-2.609375 1.046875,-2.875 1.328125,-2.875 1.4375,-2.875 1.5,-2.796875 1.5,-2.640625 c 0,0.171875 -0.0625,0.3125 -0.09375,0.40625 C 1.0625,-1.375 1,-1.125 1,-0.8125 1,-0.703125 1,-0.375 1.265625,-0.140625 1.484375,0.03125 1.78125,0.0625 1.96875,0.0625 2.25,0.0625 2.5,-0.03125 2.71875,-0.25 2.640625,0.140625 2.5625,0.4375 2.265625,0.78125 2.078125,1 1.796875,1.21875 1.421875,1.21875 c -0.046875,0 -0.375,0 -0.515625,-0.21875 0.375,-0.046875 0.375,-0.375 0.375,-0.390625 0,-0.21875 -0.203125,-0.265625 -0.265625,-0.265625 -0.171875,0 -0.40625,0.140625 -0.40625,0.46875 0,0.34375 0.328125,0.609375 0.828125,0.609375 C 2.140625,1.421875 3,0.875 3.21875,0 Z m 0,0\"\n               id=\"id-453ebdbd-06cb-402e-ae62-ac1a93b87f26\" />\n          </symbol>\n        </g>\n      </defs>\n      <g\n         id=\"id-c789bae5-78e6-42b1-a8e9-0fbbfcf239c9\"\n         transform=\"translate(-148.4,-130.359)\"\n         style=\"stroke-width:0\">\n        <g\n           style=\"fill:#000000;fill-opacity:1;stroke-width:0\"\n           id=\"id-44461a69-b270-4ba6-b39a-4dbad60bc1de\">\n          <g\n             transform=\"translate(148.712,134.765)\"\n             style=\"stroke-width:0\"\n             id=\"g7119\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"M 0.453125,1.21875 C 0.375,1.5625 0.34375,1.625 -0.09375,1.625 c -0.109375,0 -0.21875,0 -0.21875,0.1875 0,0.078125 0.046875,0.125 0.125,0.125 0.265625,0 0.5625,-0.03125 0.828125,-0.03125 0.34375,0 0.671875,0.03125 1,0.03125 0.046875,0 0.171875,0 0.171875,-0.203125 C 1.8125,1.625 1.71875,1.625 1.578125,1.625 c -0.5,0 -0.5,-0.0625 -0.5,-0.15625 0,-0.125 0.421875,-1.75 0.484375,-2 0.125,0.296875 0.40625,0.640625 0.921875,0.640625 1.15625,0 2.40625,-1.453125 2.40625,-2.921875 0,-0.9375 -0.578125,-1.59375 -1.328125,-1.59375 -0.5,0 -0.984375,0.359375 -1.3125,0.75 -0.09375,-0.546875 -0.53125,-0.75 -0.890625,-0.75 -0.46875,0 -0.65625,0.390625 -0.734375,0.5625 C 0.4375,-3.5 0.3125,-2.90625 0.3125,-2.875 c 0,0.109375 0.09375,0.109375 0.109375,0.109375 0.109375,0 0.109375,-0.015625 0.171875,-0.234375 0.171875,-0.703125 0.375,-1.1875 0.734375,-1.1875 0.171875,0 0.3125,0.078125 0.3125,0.453125 0,0.234375 -0.03125,0.34375 -0.078125,0.515625 z m 1.75,-4.328125 C 2.265625,-3.375 2.546875,-3.65625 2.71875,-3.8125 c 0.359375,-0.296875 0.640625,-0.375 0.8125,-0.375 0.390625,0 0.640625,0.34375 0.640625,0.9375 0,0.59375 -0.328125,1.734375 -0.515625,2.109375 -0.34375,0.703125 -0.8125,1.03125 -1.1875,1.03125 C 1.8125,-0.109375 1.6875,-0.9375 1.6875,-1 c 0,-0.015625 0,-0.03125 0.03125,-0.15625 z m 0,0\"\n               id=\"id-ff3c0683-f97f-4b4c-a907-96fffb6822bf\" />\n          </g>\n        </g>\n        <g\n           style=\"fill:#000000;fill-opacity:1;stroke-width:0\"\n           id=\"id-65c7118f-fee7-4d0a-a516-9a97a237c79f\">\n          <g\n             transform=\"translate(153.725,136.259)\"\n             style=\"stroke-width:0\"\n             id=\"g7123\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"M 3.875,-2.625 C 3.90625,-2.71875 3.90625,-2.734375 3.90625,-2.78125 3.90625,-2.921875 3.796875,-3 3.671875,-3 3.59375,-3 3.46875,-2.96875 3.390625,-2.84375 3.359375,-2.796875 3.3125,-2.578125 3.28125,-2.4375 L 3.125,-1.859375 c -0.03125,0.171875 -0.25,1.046875 -0.28125,1.125 0,0 -0.3125,0.609375 -0.84375,0.609375 -0.484375,0 -0.484375,-0.453125 -0.484375,-0.578125 0,-0.375 0.15625,-0.8125 0.375,-1.359375 C 1.96875,-2.28125 2,-2.359375 2,-2.484375 2,-2.8125 1.71875,-3.078125 1.34375,-3.078125 0.640625,-3.078125 0.328125,-2.125 0.328125,-2 c 0,0.078125 0.09375,0.078125 0.125,0.078125 0.09375,0 0.09375,-0.03125 0.125,-0.109375 C 0.75,-2.609375 1.046875,-2.875 1.328125,-2.875 1.4375,-2.875 1.5,-2.796875 1.5,-2.640625 c 0,0.171875 -0.0625,0.3125 -0.09375,0.40625 C 1.0625,-1.375 1,-1.125 1,-0.8125 1,-0.703125 1,-0.375 1.265625,-0.140625 1.484375,0.03125 1.78125,0.0625 1.96875,0.0625 2.25,0.0625 2.5,-0.03125 2.71875,-0.25 2.640625,0.140625 2.5625,0.4375 2.265625,0.78125 2.078125,1 1.796875,1.21875 1.421875,1.21875 c -0.046875,0 -0.375,0 -0.515625,-0.21875 0.375,-0.046875 0.375,-0.375 0.375,-0.390625 0,-0.21875 -0.203125,-0.265625 -0.265625,-0.265625 -0.171875,0 -0.40625,0.140625 -0.40625,0.46875 0,0.34375 0.328125,0.609375 0.828125,0.609375 C 2.140625,1.421875 3,0.875 3.21875,0 Z m 0,0\"\n               id=\"id-ad663a96-211a-4cb8-804e-aa97500b0aa2\" />\n          </g>\n        </g>\n      </g>\n    </g>\n    <g\n       transform=\"matrix(0.536517,0,0,0.536517,153.76775,56.069139)\"\n       ns2:version=\"1.3.0\"\n       ns2:texconverter=\"pdflatex\"\n       ns2:pdfconverter=\"inkscape\"\n       ns2:text=\"$v_y$\"\n       ns2:preamble=\"C:\\\\Users\\jmmau\\AppData\\Roaming\\inkscape\\extensions\\textext\\default_packages.tex\"\n       ns2:scale=\"0.36060278588370587\"\n       ns2:alignment=\"middle center\"\n       ns2:inkscapeversion=\"1.0.1\"\n       ns2:jacobian_sqrt=\"0.127213\"\n       style=\"stroke-width:0\"\n       id=\"g5000-4-7-2\">\n      <defs\n         id=\"id-5d93e784-ae10-44c6-a2c2-49dafff09262\">\n        <g\n           id=\"id-8de2767a-79b9-4e13-a977-2dfdcb102f86\"\n           style=\"stroke-width:0\">\n          <symbol\n             overflow=\"visible\"\n             id=\"id-346bda28-f426-4c5a-ae0d-a198d3ba9411\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"\"\n               id=\"id-44574aaf-68d0-4ca1-9d11-798d35021ecb\" />\n          </symbol>\n          <symbol\n             overflow=\"visible\"\n             id=\"id-b8f24467-900b-4525-a256-9ce754284b61\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"m 4.671875,-3.703125 c 0,-0.546875 -0.265625,-0.703125 -0.4375,-0.703125 -0.25,0 -0.5,0.265625 -0.5,0.484375 0,0.125 0.046875,0.1875 0.15625,0.296875 0.21875,0.203125 0.34375,0.453125 0.34375,0.8125 0,0.421875 -0.609375,2.703125 -1.765625,2.703125 -0.515625,0 -0.75,-0.34375 -0.75,-0.875 0,-0.546875 0.28125,-1.28125 0.578125,-2.109375 0.078125,-0.171875 0.125,-0.3125 0.125,-0.5 0,-0.4375 -0.3125,-0.8125 -0.8125,-0.8125 -0.9375,0 -1.3125,1.453125 -1.3125,1.53125 0,0.109375 0.09375,0.109375 0.109375,0.109375 0.109375,0 0.109375,-0.03125 0.15625,-0.1875 0.296875,-1 0.71875,-1.234375 1.015625,-1.234375 0.078125,0 0.25,0 0.25,0.3125 0,0.25 -0.109375,0.53125 -0.171875,0.703125 -0.4375,1.15625 -0.5625,1.609375 -0.5625,2.046875 0,1.078125 0.875,1.234375 1.328125,1.234375 1.671875,0 2.25,-3.296875 2.25,-3.8125 z m 0,0\"\n               id=\"id-92702823-7544-4055-a66b-ab0cc07581e7\" />\n          </symbol>\n          <symbol\n             overflow=\"visible\"\n             id=\"id-f6072d2d-f71d-4ec6-bfbd-bbcdd8143292\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"\"\n               id=\"id-a2b8612f-54b1-4ded-9237-7d59a02aa042\" />\n          </symbol>\n          <symbol\n             overflow=\"visible\"\n             id=\"id-bb10f901-66e4-4306-9842-e0ad808b3fa0\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"M 3.875,-2.625 C 3.90625,-2.71875 3.90625,-2.734375 3.90625,-2.78125 3.90625,-2.921875 3.796875,-3 3.671875,-3 3.59375,-3 3.46875,-2.96875 3.390625,-2.84375 3.359375,-2.796875 3.3125,-2.578125 3.28125,-2.4375 L 3.125,-1.859375 c -0.03125,0.171875 -0.25,1.046875 -0.28125,1.125 0,0 -0.3125,0.609375 -0.84375,0.609375 -0.484375,0 -0.484375,-0.453125 -0.484375,-0.578125 0,-0.375 0.15625,-0.8125 0.375,-1.359375 C 1.96875,-2.28125 2,-2.359375 2,-2.484375 2,-2.8125 1.71875,-3.078125 1.34375,-3.078125 0.640625,-3.078125 0.328125,-2.125 0.328125,-2 c 0,0.078125 0.09375,0.078125 0.125,0.078125 0.09375,0 0.09375,-0.03125 0.125,-0.109375 C 0.75,-2.609375 1.046875,-2.875 1.328125,-2.875 1.4375,-2.875 1.5,-2.796875 1.5,-2.640625 c 0,0.171875 -0.0625,0.3125 -0.09375,0.40625 C 1.0625,-1.375 1,-1.125 1,-0.8125 1,-0.703125 1,-0.375 1.265625,-0.140625 1.484375,0.03125 1.78125,0.0625 1.96875,0.0625 2.25,0.0625 2.5,-0.03125 2.71875,-0.25 2.640625,0.140625 2.5625,0.4375 2.265625,0.78125 2.078125,1 1.796875,1.21875 1.421875,1.21875 c -0.046875,0 -0.375,0 -0.515625,-0.21875 0.375,-0.046875 0.375,-0.375 0.375,-0.390625 0,-0.21875 -0.203125,-0.265625 -0.265625,-0.265625 -0.171875,0 -0.40625,0.140625 -0.40625,0.46875 0,0.34375 0.328125,0.609375 0.828125,0.609375 C 2.140625,1.421875 3,0.875 3.21875,0 Z m 0,0\"\n               id=\"id-522da0d6-08ad-44b6-bec6-1724b481d86f\" />\n          </symbol>\n        </g>\n      </defs>\n      <g\n         id=\"id-530d714a-cb3a-4fa0-acea-00faecdb7580\"\n         transform=\"translate(-149.009,-130.359)\"\n         style=\"stroke-width:0\">\n        <g\n           style=\"fill:#000000;fill-opacity:1;stroke-width:0\"\n           id=\"id-b4b62169-43b6-4616-9c03-2eb39b6277f7\">\n          <g\n             transform=\"translate(148.712,134.765)\"\n             style=\"stroke-width:0\"\n             id=\"g7307\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"m 4.671875,-3.703125 c 0,-0.546875 -0.265625,-0.703125 -0.4375,-0.703125 -0.25,0 -0.5,0.265625 -0.5,0.484375 0,0.125 0.046875,0.1875 0.15625,0.296875 0.21875,0.203125 0.34375,0.453125 0.34375,0.8125 0,0.421875 -0.609375,2.703125 -1.765625,2.703125 -0.515625,0 -0.75,-0.34375 -0.75,-0.875 0,-0.546875 0.28125,-1.28125 0.578125,-2.109375 0.078125,-0.171875 0.125,-0.3125 0.125,-0.5 0,-0.4375 -0.3125,-0.8125 -0.8125,-0.8125 -0.9375,0 -1.3125,1.453125 -1.3125,1.53125 0,0.109375 0.09375,0.109375 0.109375,0.109375 0.109375,0 0.109375,-0.03125 0.15625,-0.1875 0.296875,-1 0.71875,-1.234375 1.015625,-1.234375 0.078125,0 0.25,0 0.25,0.3125 0,0.25 -0.109375,0.53125 -0.171875,0.703125 -0.4375,1.15625 -0.5625,1.609375 -0.5625,2.046875 0,1.078125 0.875,1.234375 1.328125,1.234375 1.671875,0 2.25,-3.296875 2.25,-3.8125 z m 0,0\"\n               id=\"id-aea8ef0b-42e8-4528-b945-8753f1343bdd\" />\n          </g>\n        </g>\n        <g\n           style=\"fill:#000000;fill-opacity:1;stroke-width:0\"\n           id=\"id-ec0a2119-9d35-4970-895c-8f9fa2ed2c50\">\n          <g\n             transform=\"translate(153.541,136.259)\"\n             style=\"stroke-width:0\"\n             id=\"g7311\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"M 3.875,-2.625 C 3.90625,-2.71875 3.90625,-2.734375 3.90625,-2.78125 3.90625,-2.921875 3.796875,-3 3.671875,-3 3.59375,-3 3.46875,-2.96875 3.390625,-2.84375 3.359375,-2.796875 3.3125,-2.578125 3.28125,-2.4375 L 3.125,-1.859375 c -0.03125,0.171875 -0.25,1.046875 -0.28125,1.125 0,0 -0.3125,0.609375 -0.84375,0.609375 -0.484375,0 -0.484375,-0.453125 -0.484375,-0.578125 0,-0.375 0.15625,-0.8125 0.375,-1.359375 C 1.96875,-2.28125 2,-2.359375 2,-2.484375 2,-2.8125 1.71875,-3.078125 1.34375,-3.078125 0.640625,-3.078125 0.328125,-2.125 0.328125,-2 c 0,0.078125 0.09375,0.078125 0.125,0.078125 0.09375,0 0.09375,-0.03125 0.125,-0.109375 C 0.75,-2.609375 1.046875,-2.875 1.328125,-2.875 1.4375,-2.875 1.5,-2.796875 1.5,-2.640625 c 0,0.171875 -0.0625,0.3125 -0.09375,0.40625 C 1.0625,-1.375 1,-1.125 1,-0.8125 1,-0.703125 1,-0.375 1.265625,-0.140625 1.484375,0.03125 1.78125,0.0625 1.96875,0.0625 2.25,0.0625 2.5,-0.03125 2.71875,-0.25 2.640625,0.140625 2.5625,0.4375 2.265625,0.78125 2.078125,1 1.796875,1.21875 1.421875,1.21875 c -0.046875,0 -0.375,0 -0.515625,-0.21875 0.375,-0.046875 0.375,-0.375 0.375,-0.390625 0,-0.21875 -0.203125,-0.265625 -0.265625,-0.265625 -0.171875,0 -0.40625,0.140625 -0.40625,0.46875 0,0.34375 0.328125,0.609375 0.828125,0.609375 C 2.140625,1.421875 3,0.875 3.21875,0 Z m 0,0\"\n               id=\"id-2352e51c-9a58-45d8-a005-200e1a0be5d8\" />\n          </g>\n        </g>\n      </g>\n    </g>\n    <g\n       transform=\"matrix(0.536517,0,0,0.536517,115.79841,63.083985)\"\n       ns2:version=\"1.3.0\"\n       ns2:texconverter=\"pdflatex\"\n       ns2:pdfconverter=\"inkscape\"\n       ns2:text=\"$M$\"\n       ns2:preamble=\"C:\\\\Users\\jmmau\\AppData\\Roaming\\inkscape\\extensions\\textext\\default_packages.tex\"\n       ns2:scale=\"0.36060278588370587\"\n       ns2:alignment=\"middle center\"\n       ns2:inkscapeversion=\"1.0.1\"\n       ns2:jacobian_sqrt=\"0.127213\"\n       style=\"stroke-width:0\"\n       id=\"g5000-5\">\n      <defs\n         id=\"id-dd868545-a7ec-4340-b1ae-c1aa823f4d9d\">\n        <g\n           id=\"id-6cad75ff-70ee-4e5e-9531-1241c325f032\"\n           style=\"stroke-width:0\">\n          <symbol\n             overflow=\"visible\"\n             id=\"id-b7a25d62-0566-45f6-aef2-9ac0c79a2d8f\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"\"\n               id=\"id-f8dcc3e8-7cfa-4e3f-ac6f-5fb6300f84d7\" />\n          </symbol>\n          <symbol\n             overflow=\"visible\"\n             id=\"id-eb67eb4a-8e6e-4f17-9432-c29e5475a9eb\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"M 9.234375,-6.046875 C 9.328125,-6.40625 9.34375,-6.5 10.09375,-6.5 c 0.21875,0 0.3125,0 0.3125,-0.203125 0,-0.109375 -0.09375,-0.109375 -0.265625,-0.109375 h -1.3125 c -0.265625,0 -0.28125,0 -0.390625,0.1875 L 4.796875,-0.9375 4.015625,-6.578125 C 3.984375,-6.8125 3.96875,-6.8125 3.703125,-6.8125 H 2.34375 c -0.1875,0 -0.296875,0 -0.296875,0.1875 0,0.125 0.09375,0.125 0.28125,0.125 0.140625,0 0.3125,0.015625 0.4375,0.015625 0.15625,0.03125 0.21875,0.046875 0.21875,0.171875 0,0.03125 -0.015625,0.0625 -0.046875,0.1875 l -1.265625,5.0625 c -0.09375,0.40625 -0.265625,0.71875 -1.078125,0.75 -0.046875,0 -0.171875,0.015625 -0.171875,0.1875 0,0.09375 0.0625,0.125 0.140625,0.125 0.3125,0 0.65625,-0.03125 1,-0.03125 C 1.890625,-0.03125 2.25,0 2.578125,0 c 0.046875,0 0.1875,0 0.1875,-0.203125 0,-0.109375 -0.109375,-0.109375 -0.1875,-0.109375 -0.5625,0 -0.671875,-0.203125 -0.671875,-0.4375 0,-0.0625 0,-0.125 0.03125,-0.234375 L 3.296875,-6.40625 H 3.3125 l 0.859375,6.171875 C 4.1875,-0.109375 4.203125,0 4.3125,0 4.421875,0 4.484375,-0.109375 4.53125,-0.171875 l 4.03125,-6.3125 h 0.015625 l -1.4375,5.703125 c -0.09375,0.390625 -0.109375,0.46875 -0.90625,0.46875 -0.15625,0 -0.265625,0 -0.265625,0.1875 C 5.96875,0 6.078125,0 6.109375,0 6.390625,0 7.0625,-0.03125 7.34375,-0.03125 7.75,-0.03125 8.1875,0 8.59375,0 8.65625,0 8.78125,0 8.78125,-0.203125 8.78125,-0.3125 8.6875,-0.3125 8.5,-0.3125 c -0.359375,0 -0.640625,0 -0.640625,-0.171875 0,-0.046875 0,-0.0625 0.046875,-0.25 z m 0,0\"\n               id=\"id-cf187999-3202-493f-a429-f597203a66a7\" />\n          </symbol>\n        </g>\n      </defs>\n      <g\n         id=\"id-c0727014-c91a-4397-b725-b44abe026427\"\n         transform=\"translate(-149.134,-127.953)\"\n         style=\"stroke-width:0\">\n        <g\n           style=\"fill:#000000;fill-opacity:1;stroke-width:0\"\n           id=\"id-3a0eacbe-ea3b-415f-9acc-8ee9fd80b9c3\">\n          <g\n             transform=\"translate(148.712,134.765)\"\n             style=\"stroke-width:0\"\n             id=\"g7602\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"m 9.234375,-4.9333496 c 0.09375,-0.359375 0.109375,-0.453125 0.859375,-0.453125 0.21875,0 0.3125,0 0.3125,-0.203125 0,-0.109375 -0.09375,-0.109375 -0.265625,-0.109375 h -1.3125 c -0.265625,0 -0.28125,0 -0.390625,0.1875 L 4.796875,0.17602539 4.015625,-5.4645996 c -0.03125,-0.234375 -0.046875,-0.234375 -0.3125,-0.234375 H 2.34375 c -0.1875,0 -0.296875,0 -0.296875,0.1875 0,0.125 0.09375,0.125 0.28125,0.125 0.140625,0 0.3125,0.015625 0.4375,0.015625 0.15625,0.03125 0.21875,0.046875 0.21875,0.171875 0,0.03125 -0.015625,0.0625 -0.046875,0.1875 L 1.671875,0.05102539 c -0.09375,0.40625 -0.265625,0.71875 -1.078125,0.75 -0.046875,0 -0.171875,0.015625 -0.171875,0.1875 0,0.09375 0.0625,0.12500001 0.140625,0.12500001 0.3125,0 0.65625,-0.03125 1,-0.03125 0.328125,0 0.6875,0.03125 1.015625,0.03125 0.046875,0 0.1875,0 0.1875,-0.20312501 0,-0.109375 -0.109375,-0.109375 -0.1875,-0.109375 -0.5625,0 -0.671875,-0.203125 -0.671875,-0.4375 0,-0.0625 0,-0.125 0.03125,-0.234375 L 3.296875,-5.2927246 H 3.3125 L 4.171875,0.87915039 C 4.1875,1.0041504 4.203125,1.1135254 4.3125,1.1135254 c 0.109375,0 0.171875,-0.109375 0.21875,-0.17187501 L 8.5625,-5.3708496 h 0.015625 l -1.4375,5.70312499 c -0.09375,0.390625 -0.109375,0.46875 -0.90625,0.46875 -0.15625,0 -0.265625,0 -0.265625,0.1875 0,0.12500001 0.109375,0.12500001 0.140625,0.12500001 0.28125,0 0.953125,-0.03125 1.234375,-0.03125 0.40625,0 0.84375,0.03125 1.25,0.03125 0.0625,0 0.1875,0 0.1875,-0.20312501 0,-0.109375 -0.09375,-0.109375 -0.28125,-0.109375 -0.359375,0 -0.640625,0 -0.640625,-0.171875 0,-0.046875 0,-0.0625 0.046875,-0.25 z m 0,0\"\n               id=\"id-170da74e-4738-40ce-b27c-014af31e5e6a\" />\n          </g>\n        </g>\n      </g>\n    </g>\n    <g\n       transform=\"matrix(0.536517,0,0,0.536517,111.78263,26.832091)\"\n       ns2:version=\"1.3.0\"\n       ns2:texconverter=\"pdflatex\"\n       ns2:pdfconverter=\"inkscape\"\n       ns2:text=\"$L$\"\n       ns2:preamble=\"C:\\\\Users\\jmmau\\AppData\\Roaming\\inkscape\\extensions\\textext\\default_packages.tex\"\n       ns2:scale=\"0.36060278588370587\"\n       ns2:alignment=\"middle center\"\n       ns2:inkscapeversion=\"1.0.1\"\n       ns2:jacobian_sqrt=\"0.127213\"\n       style=\"stroke-width:0\"\n       id=\"g5000-5-0\">\n      <defs\n         id=\"id-d4cb4217-9d55-427e-9080-b83b1b25c2e5\">\n        <g\n           id=\"id-405c5a41-a781-45a8-aa25-f942f4656149\"\n           style=\"stroke-width:0\">\n          <symbol\n             overflow=\"visible\"\n             id=\"id-6bb4816e-903c-44b8-9e4c-b209eb05b8fd\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"\"\n               id=\"id-fb38ec55-12d8-4d55-8bf7-e98b2a015295\" />\n          </symbol>\n          <symbol\n             overflow=\"visible\"\n             id=\"id-a03fa650-8bf7-4421-8184-3dc62ca47bd7\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"M 3.734375,-6.03125 C 3.8125,-6.390625 3.84375,-6.5 4.78125,-6.5 c 0.296875,0 0.375,0 0.375,-0.1875 0,-0.125 -0.109375,-0.125 -0.15625,-0.125 -0.328125,0 -1.140625,0.03125 -1.46875,0.03125 -0.296875,0 -1.03125,-0.03125 -1.328125,-0.03125 -0.0625,0 -0.1875,0 -0.1875,0.203125 0,0.109375 0.09375,0.109375 0.28125,0.109375 0.015625,0 0.203125,0 0.375,0.015625 0.171875,0.03125 0.265625,0.03125 0.265625,0.171875 0,0.03125 0,0.0625 -0.03125,0.1875 L 1.5625,-0.78125 c -0.09375,0.390625 -0.109375,0.46875 -0.90625,0.46875 -0.171875,0 -0.265625,0 -0.265625,0.203125 C 0.390625,0 0.484375,0 0.65625,0 h 4.625 C 5.515625,0 5.515625,0 5.578125,-0.171875 L 6.375,-2.328125 c 0.03125,-0.109375 0.03125,-0.125 0.03125,-0.140625 0,-0.03125 -0.03125,-0.109375 -0.109375,-0.109375 -0.09375,0 -0.109375,0.0625 -0.171875,0.21875 -0.34375,0.90625 -0.78125,2.046875 -2.5,2.046875 H 2.6875 c -0.140625,0 -0.171875,0 -0.21875,0 -0.109375,-0.015625 -0.140625,-0.03125 -0.140625,-0.109375 0,-0.03125 0,-0.046875 0.046875,-0.21875 z m 0,0\"\n               id=\"id-e238fe0f-9ecd-4c31-a633-8727f7d156af\" />\n          </symbol>\n        </g>\n      </defs>\n      <g\n         id=\"id-02066eba-8212-45f2-a2ae-78803dc5e121\"\n         transform=\"translate(-149.103,-127.953)\"\n         style=\"stroke-width:0\">\n        <g\n           style=\"fill:#000000;fill-opacity:1;stroke-width:0\"\n           id=\"id-828adaf3-a905-4414-8cfb-21335f1dc51d\">\n          <g\n             transform=\"translate(148.712,134.765)\"\n             style=\"stroke-width:0\"\n             id=\"g7873\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"M 3.734375,-6.03125 C 3.8125,-6.390625 3.84375,-6.5 4.78125,-6.5 c 0.296875,0 0.375,0 0.375,-0.1875 0,-0.125 -0.109375,-0.125 -0.15625,-0.125 -0.328125,0 -1.140625,0.03125 -1.46875,0.03125 -0.296875,0 -1.03125,-0.03125 -1.328125,-0.03125 -0.0625,0 -0.1875,0 -0.1875,0.203125 0,0.109375 0.09375,0.109375 0.28125,0.109375 0.015625,0 0.203125,0 0.375,0.015625 0.171875,0.03125 0.265625,0.03125 0.265625,0.171875 0,0.03125 0,0.0625 -0.03125,0.1875 L 1.5625,-0.78125 c -0.09375,0.390625 -0.109375,0.46875 -0.90625,0.46875 -0.171875,0 -0.265625,0 -0.265625,0.203125 C 0.390625,0 0.484375,0 0.65625,0 h 4.625 C 5.515625,0 5.515625,0 5.578125,-0.171875 L 6.375,-2.328125 c 0.03125,-0.109375 0.03125,-0.125 0.03125,-0.140625 0,-0.03125 -0.03125,-0.109375 -0.109375,-0.109375 -0.09375,0 -0.109375,0.0625 -0.171875,0.21875 -0.34375,0.90625 -0.78125,2.046875 -2.5,2.046875 H 2.6875 c -0.140625,0 -0.171875,0 -0.21875,0 -0.109375,-0.015625 -0.140625,-0.03125 -0.140625,-0.109375 0,-0.03125 0,-0.046875 0.046875,-0.21875 z m 0,0\"\n               id=\"id-0602d45d-ef69-4840-8317-b90127473bf9\" />\n          </g>\n        </g>\n      </g>\n    </g>\n    <g\n       transform=\"matrix(0.536517,0,0,0.536517,130.72982,42.056595)\"\n       ns2:version=\"1.3.0\"\n       ns2:texconverter=\"pdflatex\"\n       ns2:pdfconverter=\"inkscape\"\n       ns2:text=\"$\\\\theta$\"\n       ns2:preamble=\"C:\\\\Users\\jmmau\\AppData\\Roaming\\inkscape\\extensions\\textext\\default_packages.tex\"\n       ns2:scale=\"0.36060278588370587\"\n       ns2:alignment=\"middle center\"\n       ns2:inkscapeversion=\"1.0.1\"\n       ns2:jacobian_sqrt=\"0.127213\"\n       style=\"stroke-width:0\"\n       id=\"g5000-4-8-1\">\n      <defs\n         id=\"id-c06e5111-ffb3-49e4-b532-3185867b39c2\">\n        <g\n           id=\"id-b9c250f8-f907-4b09-a8af-2e66f304cbe8\"\n           style=\"stroke-width:0\">\n          <symbol\n             overflow=\"visible\"\n             id=\"id-c4e11fbe-88ce-4381-a7d2-9bdc2efdc22c\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"\"\n               id=\"id-0a88564d-3d7f-4fde-9047-f283599081f2\" />\n          </symbol>\n          <symbol\n             overflow=\"visible\"\n             id=\"id-3229262f-feb0-4d6d-9678-0963d432eb47\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"m 4.53125,-4.984375 c 0,-0.65625 -0.171875,-2.046875 -1.1875,-2.046875 -1.390625,0 -2.921875,2.8125 -2.921875,5.09375 0,0.9375 0.28125,2.046875 1.1875,2.046875 1.40625,0 2.921875,-2.859375 2.921875,-5.09375 z M 1.46875,-3.625 C 1.640625,-4.25 1.84375,-5.046875 2.25,-5.765625 2.515625,-6.25 2.875,-6.8125 3.328125,-6.8125 c 0.484375,0 0.546875,0.640625 0.546875,1.203125 0,0.5 -0.078125,1 -0.3125,1.984375 z m 2,0.328125 C 3.359375,-2.84375 3.15625,-2 2.765625,-1.28125 c -0.34375,0.6875 -0.71875,1.171875 -1.15625,1.171875 -0.328125,0 -0.53125,-0.296875 -0.53125,-1.21875 0,-0.421875 0.0625,-1 0.3125,-1.96875 z m 0,0\"\n               id=\"id-fd40414a-b640-45de-9673-d05b6cfab5b4\" />\n          </symbol>\n        </g>\n      </defs>\n      <g\n         id=\"id-854629c4-4efe-4899-95ef-c97d19d0beee\"\n         transform=\"translate(-149.134,-127.734)\"\n         style=\"stroke-width:0\">\n        <g\n           style=\"fill:#000000;fill-opacity:1;stroke-width:0\"\n           id=\"id-8721a0d1-eab6-43b9-a2cd-1d9498af9f26\">\n          <g\n             transform=\"translate(148.712,134.765)\"\n             style=\"stroke-width:0\"\n             id=\"g8531\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"m 4.53125,-4.984375 c 0,-0.65625 -0.171875,-2.046875 -1.1875,-2.046875 -1.390625,0 -2.921875,2.8125 -2.921875,5.09375 0,0.9375 0.28125,2.046875 1.1875,2.046875 1.40625,0 2.921875,-2.859375 2.921875,-5.09375 z M 1.46875,-3.625 C 1.640625,-4.25 1.84375,-5.046875 2.25,-5.765625 2.515625,-6.25 2.875,-6.8125 3.328125,-6.8125 c 0.484375,0 0.546875,0.640625 0.546875,1.203125 0,0.5 -0.078125,1 -0.3125,1.984375 z m 2,0.328125 C 3.359375,-2.84375 3.15625,-2 2.765625,-1.28125 c -0.34375,0.6875 -0.71875,1.171875 -1.15625,1.171875 -0.328125,0 -0.53125,-0.296875 -0.53125,-1.21875 0,-0.421875 0.0625,-1 0.3125,-1.96875 z m 0,0\"\n               id=\"id-2c0ca284-8bc5-4e76-85c1-69aebeda0de3\" />\n          </g>\n        </g>\n      </g>\n    </g>\n    <path\n       style=\"fill:none;stroke:#000000;stroke-width:0.362308;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;marker-end:url(#Arrow2Mend-8-2-6-4)\"\n       d=\"M 151.9529,74.316463 V 85.475181\"\n       id=\"path5631-0-8-4-1\" />\n    <g\n       transform=\"matrix(0.536517,0,0,0.536517,153.79179,75.776531)\"\n       ns2:version=\"1.3.0\"\n       ns2:texconverter=\"pdflatex\"\n       ns2:pdfconverter=\"inkscape\"\n       ns2:text=\"$G$\"\n       ns2:preamble=\"C:\\\\Users\\jmmau\\AppData\\Roaming\\inkscape\\extensions\\textext\\default_packages.tex\"\n       ns2:scale=\"0.36060278588370587\"\n       ns2:alignment=\"middle center\"\n       ns2:inkscapeversion=\"1.0.1\"\n       ns2:jacobian_sqrt=\"0.127213\"\n       style=\"stroke-width:0\"\n       id=\"g5000-5-0-2\">\n      <defs\n         id=\"id-59b66efb-397c-44f8-8047-74efe613d8ea\">\n        <g\n           id=\"id-277f1e3c-1e54-4e22-a3b2-147da723eb12\"\n           style=\"stroke-width:0\">\n          <symbol\n             overflow=\"visible\"\n             id=\"id-ba8a4dce-2d0d-4cf0-b559-fcd30eed0a9f\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"\"\n               id=\"id-964efb4d-04af-4397-83f5-1a75ad592336\" />\n          </symbol>\n          <symbol\n             overflow=\"visible\"\n             id=\"id-db1dce9b-77a2-443f-9894-ef2370aa678e\"\n             style=\"stroke-width:0\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"m 7.578125,-6.921875 c 0,-0.03125 -0.015625,-0.109375 -0.109375,-0.109375 -0.03125,0 -0.046875,0.015625 -0.15625,0.125 L 6.625,-6.140625 C 6.53125,-6.28125 6.078125,-7.03125 4.96875,-7.03125 2.734375,-7.03125 0.5,-4.828125 0.5,-2.515625 c 0,1.59375 1.109375,2.734375 2.71875,2.734375 0.4375,0 0.890625,-0.09375 1.25,-0.234375 0.5,-0.203125 0.6875,-0.40625 0.859375,-0.609375 0.09375,0.25 0.359375,0.609375 0.453125,0.609375 0.046875,0 0.078125,-0.03125 0.078125,-0.03125 C 5.875,-0.0625 5.96875,-0.453125 6.015625,-0.65625 l 0.1875,-0.765625 C 6.25,-1.59375 6.296875,-1.765625 6.34375,-1.9375 c 0.109375,-0.4375 0.109375,-0.46875 0.6875,-0.46875 0.046875,0 0.15625,-0.015625 0.15625,-0.203125 0,-0.078125 -0.046875,-0.109375 -0.125,-0.109375 -0.234375,0 -0.828125,0.03125 -1.046875,0.03125 -0.3125,0 -1.09375,-0.03125 -1.40625,-0.03125 -0.078125,0 -0.203125,0 -0.203125,0.203125 0,0.109375 0.078125,0.109375 0.296875,0.109375 0.015625,0 0.296875,0 0.53125,0.015625 0.265625,0.03125 0.3125,0.0625 0.3125,0.1875 0,0.09375 -0.109375,0.53125 -0.21875,0.90625 -0.28125,1.09375 -1.5625,1.203125 -1.921875,1.203125 -0.953125,0 -2,-0.5625 -2,-2.09375 0,-0.3125 0.09375,-1.953125 1.140625,-3.25 0.546875,-0.671875 1.515625,-1.28125 2.5,-1.28125 1.015625,0 1.609375,0.765625 1.609375,1.921875 0,0.40625 -0.03125,0.40625 -0.03125,0.515625 0,0.09375 0.109375,0.09375 0.140625,0.09375 0.125,0 0.125,-0.015625 0.1875,-0.203125 z m 0,0\"\n               id=\"id-04108de2-b425-43f7-be86-ed8d3420b022\" />\n          </symbol>\n        </g>\n      </defs>\n      <g\n         id=\"id-f5ed6d61-a341-493f-8dbb-b686fe90b5ae\"\n         transform=\"translate(-149.212,-127.734)\"\n         style=\"stroke-width:0\">\n        <g\n           style=\"fill:#000000;fill-opacity:1;stroke-width:0\"\n           id=\"id-6e605013-4870-4be6-9dee-15d9da560649\">\n          <g\n             transform=\"translate(148.712,134.765)\"\n             style=\"stroke-width:0\"\n             id=\"g8961\">\n            <path\n               style=\"stroke:none;stroke-width:0\"\n               d=\"m 7.578125,-6.921875 c 0,-0.03125 -0.015625,-0.109375 -0.109375,-0.109375 -0.03125,0 -0.046875,0.015625 -0.15625,0.125 L 6.625,-6.140625 C 6.53125,-6.28125 6.078125,-7.03125 4.96875,-7.03125 2.734375,-7.03125 0.5,-4.828125 0.5,-2.515625 c 0,1.59375 1.109375,2.734375 2.71875,2.734375 0.4375,0 0.890625,-0.09375 1.25,-0.234375 0.5,-0.203125 0.6875,-0.40625 0.859375,-0.609375 0.09375,0.25 0.359375,0.609375 0.453125,0.609375 0.046875,0 0.078125,-0.03125 0.078125,-0.03125 C 5.875,-0.0625 5.96875,-0.453125 6.015625,-0.65625 l 0.1875,-0.765625 C 6.25,-1.59375 6.296875,-1.765625 6.34375,-1.9375 c 0.109375,-0.4375 0.109375,-0.46875 0.6875,-0.46875 0.046875,0 0.15625,-0.015625 0.15625,-0.203125 0,-0.078125 -0.046875,-0.109375 -0.125,-0.109375 -0.234375,0 -0.828125,0.03125 -1.046875,0.03125 -0.3125,0 -1.09375,-0.03125 -1.40625,-0.03125 -0.078125,0 -0.203125,0 -0.203125,0.203125 0,0.109375 0.078125,0.109375 0.296875,0.109375 0.015625,0 0.296875,0 0.53125,0.015625 0.265625,0.03125 0.3125,0.0625 0.3125,0.1875 0,0.09375 -0.109375,0.53125 -0.21875,0.90625 -0.28125,1.09375 -1.5625,1.203125 -1.921875,1.203125 -0.953125,0 -2,-0.5625 -2,-2.09375 0,-0.3125 0.09375,-1.953125 1.140625,-3.25 0.546875,-0.671875 1.515625,-1.28125 2.5,-1.28125 1.015625,0 1.609375,0.765625 1.609375,1.921875 0,0.40625 -0.03125,0.40625 -0.03125,0.515625 0,0.09375 0.109375,0.09375 0.140625,0.09375 0.125,0 0.125,-0.015625 0.1875,-0.203125 z m 0,0\"\n               id=\"id-17d7903e-be0e-4b0a-83d1-20a19b23d752\" />\n          </g>\n        </g>\n      </g>\n    </g>\n  </g>\n</svg>\n\n\n\n\n## Formulation\n\nBackward solution:\n\n$$\n\\begin{split} \n\\mathbf {\\dot x}  &  =  \\mathbf {f (x,y^{ini},u^{ini}) } \\\\\n\\mathbf 0 & =  \\mathbf {g (x,y^{ini},u^{ini}) }  \n\\end{split}\n$$\n\nForeward solution:\n\n$$\n\\begin{split} \n\\mathbf {\\dot x}  &  =  \\mathbf {f (x,y^{run},u^{run}) } \\\\\n\\mathbf 0 & =  \\mathbf {g (x,y^{run},u^{run}) }  \n\\end{split}\n$$\n \n### Differential equations\n\n$$   \n\\begin{eqnarray}\nf_1 &=& \\frac{dp_x}{dt} = v_x \\\\\nf_2 &=& \\frac{dp_y}{dt} = v_y \\\\\nf_3 &=& \\frac{dv_x}{dt} = \\frac{1}{M} \\left(-2 p_x \\lambda + f_x - K_d v_x \\right)  \\\\\nf_4 &=& \\frac{dv_y}{dt} = \\frac{1}{M} \\left(-M G - 2 p_y \\lambda - K_d v_y \\right)\n\\end{eqnarray}\n$$\n\n### Algebraic equations\n\n$$\n\\begin{eqnarray}\ng_1 &=& p_x^2 + p_y^2 - L^2  \\\\\ng_2 &=& -\\theta + \\arctan\\left(p_x,-p_y\\right) \n\\end{eqnarray}\n$$\n\n### DAE equations in vector form\n\n$$\n\\mathbf{f} =\n\\left[\n\\begin{array}{c}\nf_1\\\\\nf_2\\\\\nf_3\\\\\nf_4\n\\end{array}\n\\right]\n\\;\\;\\;\\;\\;\\;\n\\mathbf{g} =\n\\left[\n\\begin{array}{c}\ng_1\\\\\ng_2\n\\end{array}\n\\right]\n\\;\\;\\;\\;\\;\\;\n$$\n\n### Dynamic and algebraic states and inputs\n\n$$\n\\mathbf x = \\left[\n\\begin{array}{c} \np_x \\\\ \np_y \\\\ \nv_x \\\\ \nv_y \n\\end{array} \\right]\n\\;\\;\\;\\;\n\\mathbf {y^{ini}} = \\left[\n\\begin{array}{c} \n \\lambda \\\\ \n f_x\n\\end{array} \\right] \n\\;\\;\\;\\;\n\\mathbf {y^{run}} = \\left[\n\\begin{array}{c} \n \\lambda \\\\ \n\\theta\n\\end{array} \\right] \n\\;\\;\\;\\;\n\\mathbf {u^{ini}} = \\left[\n\\begin{array}{c} \n\\theta\n\\end{array} \\right] \n\\;\\;\\;\\;\n\\mathbf {u^{run}} = \\left[\n\\begin{array}{c} \nf_x\n\\end{array} \\right]\n$$\n\n### Outputs\n\n$$\n\\begin{split} \n\\mathbf z & =  \\mathbf {h (x,y^{run},u^{run}) }  \n\\end{split}\n$$\n\nWe may be interested in the potential energy:\n\n$$\nE_p = M G \\left(p_y + L\\right)\n$$\n\nAnd the kinetical energy:\n\n$$\nE_k = \\frac{1}{2} M \\left(v_x^2 + v_y^2 \\right)\n$$\n\n$$\n\\mathbf{h} =\n\\left[\n\\begin{array}{c}\nM G p_y\\\\\n\\frac{1}{2} M \\left(v_x^2 + v_y^2 \\right)\\\\\nf_x\n\\end{array}\n\\right]\n\\;\\;\\;\\;\\;\\;\n\\mathbf{z} =\n\\left[\n\\begin{array}{c}\nE_p\\\\\nE_k\\\\\nf_x\n\\end{array}\n\\right]\n$$\n\n## pydae model building\n\n\n```python\nimport numpy as np\nimport sympy as sym\nimport pydae.build as db\n```\n\n### Definition of variables and constants\n\n\n```python\nparams_dict = {'L':5.21,'G':9.81,'M':10.0,'K_d':1e-3}  # parameters with default values\n\n\nu_ini_dict = {'theta':np.deg2rad(5.0)}  # input for the initialization problem\nu_run_dict = {'f_x':0}                  # input for the running problem, its value is updated \n\n\nx_list = ['p_x','p_y','v_x','v_y']  # dynamic states\ny_ini_list = ['lam','f_x']          # algebraic states for the initialization problem\ny_run_list = ['lam','theta']        # algebraic for the running problem\n\nsys_vars = {'params':params_dict,\n            'u_list':u_run_dict,\n            'x_list':x_list,\n            'y_list':y_run_list}\n\nexec(db.sym_gen_str())  # exec to generate the required symbolic varables and constants\n```\n\n### System formulation\n\n\n```python\ndp_x = v_x\ndp_y = v_y\ndv_x = (-2*p_x*lam + f_x - K_d*v_x)/M\ndv_y = (-M*G - 2*p_y*lam - K_d*v_y)/M   \n\ng_1 = p_x**2 + p_y**2 - L**2 -lam*1e-6\ng_2 = -theta + sym.atan2(p_x,-p_y)\n```\n\n### Build the model\n\n\n```python\nsys = {'name':'pendulum',\n       'params_dict':params_dict,\n       'f_list':[dp_x,dp_y,dv_x,dv_y],\n       'g_list':[g_1,g_2],\n       'x_list':x_list,\n       'y_ini_list':y_ini_list,\n       'y_run_list':y_run_list,\n       'u_run_dict':u_run_dict,\n       'u_ini_dict':u_ini_dict,\n       'h_dict':{'E_p':M*G*(p_y+L),'E_k':0.5*M*(v_x**2+v_y**2),'f_x':f_x}}\n\nsys = db.system(sys)\ndb.sys2num(sys)\n```\n\n\n```python\n\n```\n\n\n```python\nHTML('''\n<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 800 200\" width=\"400\" height=\"200\" version=\"1.1\">\n\n  <g>\n    <!--control starts with radius 100 but shrinks to radius 0 when clicked.  It goes back to 100 when the reverseanimation runs-->\n    <circle cx=\"100\" cy=\"100\" r=\"100\" fill=\"#b2d4e5\">\n      <animate id=\"startAnimation\" dur=\"1.0s\" attributeName=\"r\" values=\"100; 0\" fill=\"freeze\" begin=\"click\" />\n      <animate dur=\"1.0s\" attributeName=\"r\" values=\"0; 100\" fill=\"freeze\" begin=\"reverseAnimation.begin\" />\n    </circle>\n    <text y=\"240\" x=\"50\" font-family=\"Verdana\" text-align=\"center\" font-size=\"30\" textLength=\"100\">Start</text>\n  </g>\n\n  <g transform=\"translate(300,0)\">\n    <circle cx=\"100\" cy=\"100\" r=\"100\" fill=\"#b2d4e5\">\n    </circle>\n\n    <!-- vertical line -->\n    <path d=\"M100 50 l0 100\" stroke=\"white\" stroke-width=\"20\" stroke-linecap=\"round\">\n      <animate dur=\"0.5s\" begin=\"startAnimation.begin\" attributeName=\"d\" values=\"M100 50 l0 100; M100 100 l0 0; M100 150 l50 -100\" fill=\"freeze\" />\n      <animate dur=\"0.5s\" begin=\"reverseAnimation.begin\" attributeName=\"d\" values=\"M100 150 l50 -100; M100 100 l0 0; M100 50 l0 100\" fill=\"freeze\" />\n    </path>\n\n    <!-- horizontal line -->\n    <path d=\"M50 100 l100 0\" stroke=\"white\" stroke-width=\"20\" stroke-linecap=\"round\">\n      <animate dur=\"0.5s\" begin=\"startAnimation.begin\" attributeName=\"d\" values=\"M50 100 l100 0; M100 100 l0 0; M50 100 l50 50\" fill=\"freeze\" />\n      <animate dur=\"0.5s\" begin=\"reverseAnimation.begin\" attributeName=\"d\" values=\" M50 100 l50 50; M100 100 l0 0; M50 100 l100 0\" fill=\"freeze\" />\n    </path>\n  </g>\n\n  <g transform=\"translate(600,0)\">\n    <!--control starts with radius 0 but grows to radius 100 when startanimation runs.  It goes back to 0 clicked-->\n    <circle cx=\"100\" cy=\"100\" r=\"0\" fill=\"#b2d4e5\">\n      <animate dur=\"1s\" attributeName=\"r\" values=\"0; 100\" fill=\"freeze\" begin=\"startAnimation.begin\" />\n      <animate id=\"reverseAnimation\" dur=\"1s\" attributeName=\"r\" values=\"100; 0\" fill=\"freeze\" begin=\"click\" />\n    </circle>\n    <text y=\"240\" x=\"25\" font-family=\"Verdana\" text-align=\"center\" font-size=\"30\" textLength=\"150\">Reverse</text>\n  </g>\n</svg>\n''')\n```\n\n\n\n\n\n<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 800 200\" width=\"400\" height=\"200\" version=\"1.1\">\n\n  <g>\n    <!--control starts with radius 100 but shrinks to radius 0 when clicked.  It goes back to 100 when the reverseanimation runs-->\n    <circle cx=\"100\" cy=\"100\" r=\"100\" fill=\"#b2d4e5\">\n      <animate id=\"startAnimation\" dur=\"1.0s\" attributeName=\"r\" values=\"100; 0\" fill=\"freeze\" begin=\"click\" />\n      <animate dur=\"1.0s\" attributeName=\"r\" values=\"0; 100\" fill=\"freeze\" begin=\"reverseAnimation.begin\" />\n    </circle>\n    <text y=\"240\" x=\"50\" font-family=\"Verdana\" text-align=\"center\" font-size=\"30\" textLength=\"100\">Start</text>\n  </g>\n\n  <g transform=\"translate(300,0)\">\n    <circle cx=\"100\" cy=\"100\" r=\"100\" fill=\"#b2d4e5\">\n    </circle>\n\n    <!-- vertical line -->\n    <path d=\"M100 50 l0 100\" stroke=\"white\" stroke-width=\"20\" stroke-linecap=\"round\">\n      <animate dur=\"0.5s\" begin=\"startAnimation.begin\" attributeName=\"d\" values=\"M100 50 l0 100; M100 100 l0 0; M100 150 l50 -100\" fill=\"freeze\" />\n      <animate dur=\"0.5s\" begin=\"reverseAnimation.begin\" attributeName=\"d\" values=\"M100 150 l50 -100; M100 100 l0 0; M100 50 l0 100\" fill=\"freeze\" />\n    </path>\n\n    <!-- horizontal line -->\n    <path d=\"M50 100 l100 0\" stroke=\"white\" stroke-width=\"20\" stroke-linecap=\"round\">\n      <animate dur=\"0.5s\" begin=\"startAnimation.begin\" attributeName=\"d\" values=\"M50 100 l100 0; M100 100 l0 0; M50 100 l50 50\" fill=\"freeze\" />\n      <animate dur=\"0.5s\" begin=\"reverseAnimation.begin\" attributeName=\"d\" values=\" M50 100 l50 50; M100 100 l0 0; M50 100 l100 0\" fill=\"freeze\" />\n    </path>\n  </g>\n\n  <g transform=\"translate(600,0)\">\n    <!--control starts with radius 0 but grows to radius 100 when startanimation runs.  It goes back to 0 clicked-->\n    <circle cx=\"100\" cy=\"100\" r=\"0\" fill=\"#b2d4e5\">\n      <animate dur=\"1s\" attributeName=\"r\" values=\"0; 100\" fill=\"freeze\" begin=\"startAnimation.begin\" />\n      <animate id=\"reverseAnimation\" dur=\"1s\" attributeName=\"r\" values=\"100; 0\" fill=\"freeze\" begin=\"click\" />\n    </circle>\n    <text y=\"240\" x=\"25\" font-family=\"Verdana\" text-align=\"center\" font-size=\"30\" textLength=\"150\">Reverse</text>\n  </g>\n</svg>\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "87e780ba7622920e36e154fc1b56ca9db1d83265", "size": 156626, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "_build/jupyter_execute/pendulum/pendulum_doc.ipynb", "max_stars_repo_name": "pydae/pydae_doc", "max_stars_repo_head_hexsha": "5e0b0252de02b3264af94542e26ab5ac38b62e50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_build/jupyter_execute/pendulum/pendulum_doc.ipynb", "max_issues_repo_name": "pydae/pydae_doc", "max_issues_repo_head_hexsha": "5e0b0252de02b3264af94542e26ab5ac38b62e50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/pendulum/pendulum_doc.ipynb", "max_forks_repo_name": "pydae/pydae_doc", "max_forks_repo_head_hexsha": "5e0b0252de02b3264af94542e26ab5ac38b62e50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 91.3271137026, "max_line_length": 32489, "alphanum_fraction": 0.6219273939, "converted": true, "num_tokens": 47745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25982563796098374, "lm_q2_score": 0.039638839668221494, "lm_q1q2_score": 0.0102991868048288}}
{"text": "# Chatbot\nWe are going to use the [Reformer](https://arxiv.org/abs/2001.04451), also known as the efficient Transformer, to generate a dialogue between two bots. You will feed conversations to your model and it will learn how to understand the context of each one. Not only will it learn how to answer questions but it will also know how to ask questions if it needs more info. For example, after a customer asks for a train ticket, the chatbot can ask what time the said customer wants to leave. You can use this concept to automate call centers, hotel receptions, personal trainers, or any type of customer service. \n\n* Understand how the Reformer works\n* Explore the [MultiWoz](https://arxiv.org/abs/1810.00278) dataset\n* Process the data to feed it into the model\n* Train your model\n* Generate a dialogue by feeding a question to the model\n\n\n\n\n\n```python\n\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n<a name=\"1\"></a>\n# Part 1:   Exploring the MultiWoz dataset\n\nWe will start by exploring the MultiWoz dataset. The dataset we are about to use has more than 10,000 human annotated dialogues and spans multiple domains and topics. Some dialogues include multiple domains and others include single domains.\n\nLet's first import the modules we will be using:\n\n\n```python\nimport json\nimport random\nimport numpy as np\nfrom termcolor import colored\n!pip install trax\nimport trax   \nfrom trax import layers as tl\nfrom trax.supervised import training\n!pip list | grep trax\n```\n\n    Collecting trax\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/85/1d/c0a3aeed127c26a0c3f0925fc9cc7278c272e52310eedfc322477e854972/trax-1.3.6-py2.py3-none-any.whl (468kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 471kB 5.6MB/s \n    \u001b[?25hRequirement already satisfied: gin-config in /usr/local/lib/python3.6/dist-packages (from trax) (0.3.0)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from trax) (1.18.5)\n    Collecting tensorflow-text\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/28/b2/2dbd90b93913afd07e6101b8b84327c401c394e60141c1e98590038060b3/tensorflow_text-2.3.0-cp36-cp36m-manylinux1_x86_64.whl (2.6MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.6MB 16.1MB/s \n    \u001b[?25hRequirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from trax) (1.4.1)\n    Requirement already satisfied: gym in /usr/local/lib/python3.6/dist-packages (from trax) (0.17.3)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from trax) (1.15.0)\n    Requirement already satisfied: jax in /usr/local/lib/python3.6/dist-packages (from trax) (0.2.6)\n    Requirement already satisfied: tensorflow-datasets in /usr/local/lib/python3.6/dist-packages (from trax) (4.0.1)\n    Collecting funcsigs\n      Downloading https://files.pythonhosted.org/packages/69/cb/f5be453359271714c01b9bd06126eaf2e368f1fddfff30818754b5ac2328/funcsigs-1.0.2-py2.py3-none-any.whl\n    Requirement already satisfied: jaxlib in /usr/local/lib/python3.6/dist-packages (from trax) (0.1.57+cuda101)\n    Requirement already satisfied: absl-py in /usr/local/lib/python3.6/dist-packages (from trax) (0.10.0)\n    Collecting t5\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/20/39/a607d2450190af7675e4f77c5eff0cc9a83f82fe63fb396872ef2004106b/t5-0.7.1-py3-none-any.whl (172kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 174kB 33.6MB/s \n    \u001b[?25hRequirement already satisfied: tensorflow<2.4,>=2.3.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-text->trax) (2.3.0)\n    Requirement already satisfied: pyglet<=1.5.0,>=1.4.0 in /usr/local/lib/python3.6/dist-packages (from gym->trax) (1.5.0)\n    Requirement already satisfied: cloudpickle<1.7.0,>=1.2.0 in /usr/local/lib/python3.6/dist-packages (from gym->trax) (1.3.0)\n    Requirement already satisfied: opt-einsum in /usr/local/lib/python3.6/dist-packages (from jax->trax) (3.3.0)\n    Requirement already satisfied: attrs>=18.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax) (20.3.0)\n    Requirement already satisfied: importlib-resources; python_version < \"3.9\" in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax) (3.3.0)\n    Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax) (0.16.0)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax) (4.41.1)\n    Requirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax) (0.8)\n    Requirement already satisfied: promise in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax) (2.3)\n    Requirement already satisfied: tensorflow-metadata in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax) (0.25.0)\n    Requirement already satisfied: dill in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax) (0.3.3)\n    Requirement already satisfied: termcolor in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax) (1.1.0)\n    Requirement already satisfied: protobuf>=3.6.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax) (3.12.4)\n    Requirement already satisfied: dm-tree in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax) (0.1.5)\n    Requirement already satisfied: requests>=2.19.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax) (2.23.0)\n    Requirement already satisfied: flatbuffers in /usr/local/lib/python3.6/dist-packages (from jaxlib->trax) (1.12)\n    Collecting sentencepiece\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/e5/2d/6d4ca4bef9a67070fa1cac508606328329152b1df10bdf31fb6e4e727894/sentencepiece-0.1.94-cp36-cp36m-manylinux2014_x86_64.whl (1.1MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.1MB 38.0MB/s \n    \u001b[?25hRequirement already satisfied: torch in /usr/local/lib/python3.6/dist-packages (from t5->trax) (1.7.0+cu101)\n    Collecting transformers>=2.7.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/99/84/7bc03215279f603125d844bf81c3fb3f2d50fe8e511546eb4897e4be2067/transformers-4.0.0-py3-none-any.whl (1.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.4MB 29.4MB/s \n    \u001b[?25hCollecting mesh-tensorflow[transformer]>=0.1.13\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/16/8b/553deb763ce8d00afb17debab7cb14a87b209cd4c6f0e8ecfc8d884cb12a/mesh_tensorflow-0.1.17-py3-none-any.whl (342kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 348kB 44.3MB/s \n    \u001b[?25hCollecting rouge-score\n      Downloading https://files.pythonhosted.org/packages/1f/56/a81022436c08b9405a5247b71635394d44fe7e1dbedc4b28c740e09c2840/rouge_score-0.0.4-py2.py3-none-any.whl\n    Requirement already satisfied: babel in /usr/local/lib/python3.6/dist-packages (from t5->trax) (2.9.0)\n    Requirement already satisfied: scikit-learn in /usr/local/lib/python3.6/dist-packages (from t5->trax) (0.22.2.post1)\n    Collecting sacrebleu\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/a3/c4/8e948f601a4f9609e8b2b58f31966cb13cf17b940b82aa3e767f01c42c52/sacrebleu-1.4.14-py3-none-any.whl (64kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 71kB 6.1MB/s \n    \u001b[?25hRequirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from t5->trax) (1.1.4)\n    Collecting tfds-nightly\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/0b/b5/4b1d9cf76b8fb047563eca49c86e0fc74dc867c3f7ac9122486b939421c0/tfds_nightly-4.1.0.dev202012080107-py3-none-any.whl (3.7MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.7MB 41.6MB/s \n    \u001b[?25hRequirement already satisfied: nltk in /usr/local/lib/python3.6/dist-packages (from t5->trax) (3.2.5)\n    Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (1.33.2)\n    Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (1.12.1)\n    Requirement already satisfied: h5py<2.11.0,>=2.10.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (2.10.0)\n    Requirement already satisfied: tensorboard<3,>=2.3.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (2.3.0)\n    Requirement already satisfied: gast==0.3.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (0.3.3)\n    Requirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (0.35.1)\n    Requirement already satisfied: astunparse==1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (1.6.3)\n    Requirement already satisfied: tensorflow-estimator<2.4.0,>=2.3.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (2.3.0)\n    Requirement already satisfied: keras-preprocessing<1.2,>=1.1.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (1.1.2)\n    Requirement already satisfied: google-pasta>=0.1.8 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (0.2.0)\n    Requirement already satisfied: zipp>=0.4; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from importlib-resources; python_version < \"3.9\"->tensorflow-datasets->trax) (3.4.0)\n    Requirement already satisfied: googleapis-common-protos<2,>=1.52.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-metadata->tensorflow-datasets->trax) (1.52.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from protobuf>=3.6.1->tensorflow-datasets->trax) (50.3.2)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tensorflow-datasets->trax) (2020.11.8)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tensorflow-datasets->trax) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tensorflow-datasets->trax) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tensorflow-datasets->trax) (2.10)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.6/dist-packages (from torch->t5->trax) (3.7.4.3)\n    Collecting sacremoses\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/7d/34/09d19aff26edcc8eb2a01bed8e98f13a1537005d31e95233fd48216eed10/sacremoses-0.0.43.tar.gz (883kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 890kB 38.5MB/s \n    \u001b[?25hRequirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.6/dist-packages (from transformers>=2.7.0->t5->trax) (2019.12.20)\n    Collecting tokenizers==0.9.4\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/0f/1c/e789a8b12e28be5bc1ce2156cf87cb522b379be9cadc7ad8091a4cc107c4/tokenizers-0.9.4-cp36-cp36m-manylinux2010_x86_64.whl (2.9MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.9MB 41.5MB/s \n    \u001b[?25hRequirement already satisfied: filelock in /usr/local/lib/python3.6/dist-packages (from transformers>=2.7.0->t5->trax) (3.0.12)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.6/dist-packages (from transformers>=2.7.0->t5->trax) (20.4)\n    Requirement already satisfied: pytz>=2015.7 in /usr/local/lib/python3.6/dist-packages (from babel->t5->trax) (2018.9)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->t5->trax) (0.17.0)\n    Collecting portalocker\n      Downloading https://files.pythonhosted.org/packages/89/a6/3814b7107e0788040870e8825eebf214d72166adf656ba7d4bf14759a06a/portalocker-2.0.0-py2.py3-none-any.whl\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.6/dist-packages (from pandas->t5->trax) (2.8.1)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.6/dist-packages (from tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (0.4.2)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (1.7.0)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (3.3.3)\n    Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (1.0.1)\n    Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (1.17.2)\n    Requirement already satisfied: click in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers>=2.7.0->t5->trax) (7.1.2)\n    Requirement already satisfied: pyparsing>=2.0.2 in /usr/local/lib/python3.6/dist-packages (from packaging->transformers>=2.7.0->t5->trax) (2.4.7)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (1.3.0)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from markdown>=2.6.8->tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (2.0.0)\n    Requirement already satisfied: rsa<5,>=3.1.4; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (4.6)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (4.1.1)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (0.2.8)\n    Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (3.1.0)\n    Requirement already satisfied: pyasn1>=0.1.3 in /usr/local/lib/python3.6/dist-packages (from rsa<5,>=3.1.4; python_version >= \"3\"->google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (0.4.8)\n    Building wheels for collected packages: sacremoses\n      Building wheel for sacremoses (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for sacremoses: filename=sacremoses-0.0.43-cp36-none-any.whl size=893257 sha256=e1995006bc7b33a7495fcea495804b86fd414a9746dcb2740bdfe316575233ef\n      Stored in directory: /root/.cache/pip/wheels/29/3c/fd/7ce5c3f0666dab31a50123635e6fb5e19ceb42ce38d4e58f45\n    Successfully built sacremoses\n    Installing collected packages: tensorflow-text, funcsigs, sentencepiece, sacremoses, tokenizers, transformers, mesh-tensorflow, rouge-score, portalocker, sacrebleu, tfds-nightly, t5, trax\n    Successfully installed funcsigs-1.0.2 mesh-tensorflow-0.1.17 portalocker-2.0.0 rouge-score-0.0.4 sacrebleu-1.4.14 sacremoses-0.0.43 sentencepiece-0.1.94 t5-0.7.1 tensorflow-text-2.3.0 tfds-nightly-4.1.0.dev202012080107 tokenizers-0.9.4 transformers-4.0.0 trax-1.3.6\n    trax                          1.3.6                \n\n\nLet's also declare some constants we will be using in the exercises.\n\n\n```python\n# filename of the MultiWOZ dialogue dataset\nDATA_FILE = 'data.json'\n\n# data directory\nDATA_DIR = './data'\n\n# dictionary where we will load the dialogue dataset\nDIALOGUE_DB = {}\n\n# vocabulary filename\nVOCAB_FILE = 'en_32k.subword'\n\n# vocabulary file directory\nVOCAB_DIR = 'data/vocabs'\n```\n\nLet's now load the MultiWOZ 2.1 dataset. We have already provided it for you in your workspace. It is in JSON format so we should load it as such:\n\n\n```python\n# help function to load a JSON file\ndef load_json(directory, file):\n    with open(f'{directory}/{file}') as file: \n        db = json.load(file)\n    return db\n\n# load the dialogue data set into our dictionary\nDIALOGUE_DB = load_json(DATA_DIR, DATA_FILE)\n```\n\nLet's see how many dialogues we have in the dictionary. 1 key-value pair is one dialogue so we can just get the dictionary's length.\n\n\n```python\nprint(f'The number of dialogues is: {len(DIALOGUE_DB)}')\n```\n\n    The number of dialogues is: 10438\n\n\nThe dialogues are composed of multiple files and the filenames are used as keys in our dictionary. Those with multi-domain dialogues have \"MUL\" in their filenames while single domain dialogues have either \"SNG\" or \"WOZ\".\n\n\n```python\n# print 7 keys from the dataset to see the filenames\nprint(list(DIALOGUE_DB.keys())[0:7]) \n```\n\n    ['SNG01856.json', 'SNG0129.json', 'PMUL1635.json', 'MUL2168.json', 'SNG0073.json', 'SNG01445.json', 'MUL2105.json']\n\n\nAs you can see from the cells above, there are 10,438 conversations, each in its own file.  You will train your model on all those conversations. Each file is also loaded into a dictionary and each has two keys which are the following:\n\n\n```python\n# get keys of the fifth file in the list above\nprint(DIALOGUE_DB['SNG0073.json'].keys())\n```\n\n    dict_keys(['goal', 'log'])\n\n\nThe `goal` also points to a dictionary and it contains several keys pertaining to the objectives of the conversation. For example below, we can see that the conversation will be about booking a taxi.\n\n\n```python\nDIALOGUE_DB['SNG0073.json']['goal']\n```\n\n\n\n\n    {'attraction': {},\n     'hospital': {},\n     'hotel': {},\n     'message': [\"You want to book a <span class='emphasis'>taxi</span>. The taxi should go to <span class='emphasis'>pizza hut fen ditton</span> and should depart from <span class='emphasis'>saint john's college</span>\",\n      \"The taxi should <span class='emphasis'>leave after 17:15</span>\",\n      \"Make sure you get <span class='emphasis'>car type</span> and <span class='emphasis'>contact number</span>\"],\n     'police': {},\n     'restaurant': {},\n     'taxi': {'fail_info': {},\n      'info': {'departure': \"saint john's college\",\n       'destination': 'pizza hut fen ditton',\n       'leaveAt': '17:15'},\n      'reqt': ['car type', 'phone']},\n     'train': {}}\n\n\n\nThe `log` on the other hand contains the dialog. It is a list of dictionaries and each element of this list contains several descriptions as well. Let's look at an example:\n\n\n```python\n# get first element of the log list\nDIALOGUE_DB['SNG0073.json']['log'][0]\n```\n\n\n\n\n    {'dialog_act': {'Taxi-Inform': [['Dest', 'pizza hut fen ditton'],\n       ['Depart', \"saint john 's college\"]]},\n     'metadata': {},\n     'span_info': [['Taxi-Inform', 'Dest', 'pizza hut fen ditton', 11, 14],\n      ['Taxi-Inform', 'Depart', \"saint john 's college\", 6, 9]],\n     'text': \"I would like a taxi from Saint John's college to Pizza Hut Fen Ditton.\"}\n\n\n\nFor this assignment, we are only interested in the conversation which is in the `text` field.\nThe conversation goes back and forth between two persons. Let's call them 'Person 1' and 'Person 2'. This implies that\ndata['SNG0073.json']['log'][0]['text'] is 'Person 1' and\ndata['SNG0073.json']['log'][1]['text'] is 'Person 2' and so on. The even offsets are 'Person 1' and the odd offsets are 'Person 2'.\n\n\n```python\nprint(' Person 1: ', DIALOGUE_DB['SNG0073.json']['log'][0]['text'])\nprint(' Person 2: ',DIALOGUE_DB['SNG0073.json']['log'][1]['text'])\n```\n\n     Person 1:  I would like a taxi from Saint John's college to Pizza Hut Fen Ditton.\n     Person 2:  What time do you want to leave and what time do you want to arrive by?\n\n\n\n```python\n\ndef get_conversation(file, data_db):\n    '''\n    Args:\n        file (string): filename of the dialogue file saved as json\n        data_db (dict): dialogue database\n    \n    Returns:\n        string: A string containing the 'text' fields of  data[file]['log'][x]\n    '''\n    \n    # initialize empty string\n    result = ''\n    \n    # get length of file's log list\n    len_msg_log = len(data_db[file]['log'])\n    \n    # set the delimiter strings\n    delimiter_1 = ' Person 1: '\n    delimiter_2 = ' Person 2: '\n    \n    # loop over the file's log list\n    for i in range(len_msg_log):\n        \n    \n    \n        # get i'th element of file log list\n        cur_log = data_db[file]['log'][i]\n        \n        # check if i is even\n        if i%2 == 0:                   \n            # append the 1st delimiter string\n            result += delimiter_1\n        else: \n            # append the 2nd delimiter string\n            result += delimiter_2\n        \n        # append the message text from the log\n        result += cur_log['text']\n    \n    \n\n    return result\n\n\n```\n\n\n```python\nfile = 'SNG01856.json'\nconversation = get_conversation(file, DIALOGUE_DB)\n\n# print raw output\nprint(conversation)\n```\n\n     Person 1: am looking for a place to to stay that has cheap price range it should be in a type of hotel Person 2: Okay, do you have a specific area you want to stay in? Person 1: no, i just need to make sure it's cheap. oh, and i need parking Person 2: I found 1 cheap hotel for you that includes parking. Do you like me to book it? Person 1: Yes, please. 6 people 3 nights starting on tuesday. Person 2: I am sorry but I wasn't able to book that for you for Tuesday. Is there another day you would like to stay or perhaps a shorter stay? Person 1: how about only 2 nights. Person 2: Booking was successful.\n    Reference number is : 7GAWK763. Anything else I can do for you? Person 1: No, that will be all. Good bye. Person 2: Thank you for using our services.\n\n\nWe can have a utility pretty print function just so we can visually follow the conversation more easily.\n\n\n```python\ndef print_conversation(conversation):\n    \n    delimiter_1 = 'Person 1: '\n    delimiter_2 = 'Person 2: '\n    \n    split_list_d1 = conversation.split(delimiter_1)\n    \n    for sublist in split_list_d1[1:]:\n        split_list_d2 = sublist.split(delimiter_2)\n        print(colored(f'Person 1: {split_list_d2[0]}', 'red'))\n        \n        if len(split_list_d2) > 1:\n            print(colored(f'Person 2: {split_list_d2[1]}', 'green'))\n\n            \nprint_conversation(conversation)\n```\n\n    \u001b[31mPerson 1: am looking for a place to to stay that has cheap price range it should be in a type of hotel \u001b[0m\n    \u001b[32mPerson 2: Okay, do you have a specific area you want to stay in? \u001b[0m\n    \u001b[31mPerson 1: no, i just need to make sure it's cheap. oh, and i need parking \u001b[0m\n    \u001b[32mPerson 2: I found 1 cheap hotel for you that includes parking. Do you like me to book it? \u001b[0m\n    \u001b[31mPerson 1: Yes, please. 6 people 3 nights starting on tuesday. \u001b[0m\n    \u001b[32mPerson 2: I am sorry but I wasn't able to book that for you for Tuesday. Is there another day you would like to stay or perhaps a shorter stay? \u001b[0m\n    \u001b[31mPerson 1: how about only 2 nights. \u001b[0m\n    \u001b[32mPerson 2: Booking was successful.\n    Reference number is : 7GAWK763. Anything else I can do for you? \u001b[0m\n    \u001b[31mPerson 1: No, that will be all. Good bye. \u001b[0m\n    \u001b[32mPerson 2: Thank you for using our services.\u001b[0m\n\n\n\n```python\n\nDIALOGUE_DB['SNG01856.json']['log'][0]\n```\n\n\n\n\n    {'dialog_act': {'Hotel-Inform': [['Type', 'hotel'], ['Price', 'cheap']]},\n     'metadata': {},\n     'span_info': [['Hotel-Inform', 'Type', 'hotel', 20, 20],\n      ['Hotel-Inform', 'Price', 'cheap', 10, 10]],\n     'text': 'am looking for a place to to stay that has cheap price range it should be in a type of hotel'}\n\n\n\nThe dataset also comes with hotel, hospital, taxi, train, police, and restaurant databases. For example, in case you need to call a doctor, or a hotel, or a taxi, this will allow you to automate the entire conversation. Take a look at the files accompanying the data set.\n\n\n```python\n# this is an example of the attractions file\nattraction_file = open('data/attraction_db.json')\nattractions = json.load(attraction_file)\nprint(attractions[0])\n```\n\n    {'address': 'pool way, whitehill road, off newmarket road', 'area': 'east', 'entrance fee': '?', 'id': '1', 'location': [52.208789, 0.154883], 'name': 'abbey pool and astroturf pitch', 'openhours': '?', 'phone': '01223902088', 'postcode': 'cb58nt', 'pricerange': '?', 'type': 'swimmingpool'}\n\n\n\n```python\n# this is an example of the hospital file\nhospital_file = open('data/hospital_db.json')\nhospitals = json.load(hospital_file)\nprint(hospitals[0]) # feel free to index into other indices\n```\n\n    {'department': 'neurosciences critical care unit', 'id': 0, 'phone': '01223216297'}\n\n\n\n```python\n# this is an example of the hotel file\nhotel_file = open('data/hotel_db.json')\nhotels = json.load(hotel_file)\nprint(hotels[0]) # feel free to index into other indices\n```\n\n    {'address': '124 tenison road', 'area': 'east', 'internet': 'yes', 'parking': 'no', 'id': '0', 'location': [52.1963733, 0.1987426], 'name': 'a and b guest house', 'phone': '01223315702', 'postcode': 'cb12dp', 'price': {'double': '70', 'family': '90', 'single': '50'}, 'pricerange': 'moderate', 'stars': '4', 'takesbookings': 'yes', 'type': 'guesthouse'}\n\n\n\n```python\n# this is an example of the police file\npolice_file = open('data/police_db.json')\npolice = json.load(police_file)\nprint(police[0]) # feel free to index into other indices\n```\n\n    {'name': 'Parkside Police Station', 'address': 'Parkside, Cambridge', 'id': 0, 'phone': '01223358966'}\n\n\n\n```python\n# this is an example of a restuarant file\nrestaurant_file = open('data/restaurant_db.json')\nrestaurants = json.load(restaurant_file)\nprint(restaurants[0]) # feel free to index into other indices\n```\n\n    {'address': 'Regent Street City Centre', 'area': 'centre', 'food': 'italian', 'id': '19210', 'introduction': 'Pizza hut is a large chain with restaurants nationwide offering convenience pizzas pasta and salads to eat in or take away', 'location': [52.20103, 0.126023], 'name': 'pizza hut city centre', 'phone': '01223323737', 'postcode': 'cb21ab', 'pricerange': 'cheap', 'type': 'restaurant'}\n\n\nFor more information about the multiwoz 2.1 data set, please run the cell below to read the `ReadMe.txt` file. Feel free to open any other file to explore it. \n\n\n```python\nwith open('data/README') as file:\n    print(file.read())\n```\n\n    #####################################################\n    #####################################################\n    #  Copyright Cambridge Dialogue Systems Group, 2018 #\n    #####################################################\n    #####################################################\n    \n    Dataset contains the following files:\n    1. data.json: the woz dialogue dataset, which contains the conversation  users and wizards, as well as a set of coarse labels for each user turn. This file contains both system and user dialogue acts annotated at the turn level. Files with multi-domain dialogues have \"MUL\" in their names. Single domain dialogues have either \"SNG\" or \"WOZ\" in their names.\n    2. restaurant_db.json: the Cambridge restaurant database file, containing restaurants in the Cambridge UK area and a set of attributes.\n    3. attraction_db.json: the Cambridge attraction database file, contining attractions in the Cambridge UK area and a set of attributes.\n    4. hotel_db.json: the Cambridge hotel database file, containing hotels in the Cambridge UK area and a set of attributes.\n    5. train_db.json: the Cambridge train (with artificial connections) database file, containing trains in the Cambridge UK area and a set of attributes.\n    6. hospital_db.json: the Cambridge hospital database file, contatining information about departments.\n    7. police_db.json: the Cambridge police station information.\n    8. taxi_db.json: slot-value list for taxi domain.\n    9. valListFile.txt: list of dialogues for validation.\n    10. testListFile.txt: list of dialogues for testing.\n    11. system_acts.json:\n      There are 6 domains ('Booking', 'Restaurant', 'Hotel', 'Attraction', 'Taxi', 'Train') and 1 dummy domain ('general').\n      A domain-dependent dialogue act is defined as a domain token followed by a domain-independent dialogue act, e.g. 'Hotel-inform' means it is an 'inform' act in the Hotel domain.\n      Dialogue acts which cannot take slots, e.g., 'good bye', are defined under the 'general' domain.\n      A slot-value pair defined as a list with two elements. The first element is slot token and the second one is its value.\n      If a dialogue act takes no slots, e.g., dialogue act 'offer booking' for an utterance 'would you like to take a reservation?', its slot-value pair is ['none', 'none']\n      There are four types of values:\n      1) If a slot takes a binary value, e.g., 'has Internet' or 'has park', the value is either 'yes' or 'no'.\n      2) If a slot is under the act 'request', e.g., 'request' about 'area', the value is expressed as '?'.\n      3) The value that appears in the utterance e.g., the name of a restaurant.\n      4) If for some reason the turn does not have an annotation then it is labeled as \"No Annotation.\"\n    12. ontology.json: Data-based ontology containing all the values for the different slots in the domains.\n    13. slot_descriptions.json: A collection of human-written slot descriptions for each slot in the dataset. Each slot has at least two descriptions.\n    14. tokenization.md: A description of the tokenization preprocessing we had to perform to maintain consistency between the dialogue act annotations of DSTC 8 Track 1 and the existing MultiWOZ 2.0 data. \n    \n\n\nAs you can see, there are many other aspects of the MultiWoz dataset. Nonetheless, you'll see that even with just the conversations, your model will still be able to generate useful responses. This concludes our exploration of the dataset. In the next section, we will do some preprocessing before we feed it into our model for training.\n\n<a name=\"2\"></a>\n# Part 2:   Processing the data for Reformer inputs\n\nYou will now use the `get_conversation()` function to process the data. The Reformer expects inputs of this form: \n\n**Person 1: Why am I so happy? Person 2: Because you are learning NLP Person 1: ... Person 2: ...***\n\nAnd the conversation keeps going with some text. As you can see 'Person 1' and 'Person 2' act as delimiters so the model automatically recognizes the person and who is talking. It can then come up with the corresponding text responses for each person. Let's proceed to process the text in this fashion for the Reformer. First, let's grab all the conversation strings from all dialogue files and put them in a list.\n\n\n```python\n# the keys are the file names\nall_files = DIALOGUE_DB.keys()\n\n# initialize empty list\nuntokenized_data = []\n\n# loop over all files\nfor file in all_files:\n    # this is the graded function you coded\n    # returns a string delimited by Person 1 and Person 2\n    result = get_conversation(file, DIALOGUE_DB)\n    \n    # append to the list\n    untokenized_data.append(result)\n\n# print the first element to check if it's the same as the one we got before\nprint(untokenized_data[0])\n```\n\n     Person 1: am looking for a place to to stay that has cheap price range it should be in a type of hotel Person 2: Okay, do you have a specific area you want to stay in? Person 1: no, i just need to make sure it's cheap. oh, and i need parking Person 2: I found 1 cheap hotel for you that includes parking. Do you like me to book it? Person 1: Yes, please. 6 people 3 nights starting on tuesday. Person 2: I am sorry but I wasn't able to book that for you for Tuesday. Is there another day you would like to stay or perhaps a shorter stay? Person 1: how about only 2 nights. Person 2: Booking was successful.\n    Reference number is : 7GAWK763. Anything else I can do for you? Person 1: No, that will be all. Good bye. Person 2: Thank you for using our services.\n\n\nNow let us split the list to a train and eval dataset.\n\n\n```python\n# shuffle the list we generated above\nrandom.shuffle(untokenized_data)\n\n# define a cutoff (5% of the total length for this assignment)\n# convert to int because we will use it as a list index\ncut_off = int(len(untokenized_data) * .05)\n\n# slice the list. the last elements after the cut_off value will be the eval set. the rest is for training. \ntrain_data, eval_data = untokenized_data[:-cut_off], untokenized_data[-cut_off:]\n\nprint(f'number of conversations in the data set: {len(untokenized_data)}')\nprint(f'number of conversations in train set: {len(train_data)}')\nprint(f'number of conversations in eval set: {len(eval_data)}')\n```\n\n    number of conversations in the data set: 10438\n    number of conversations in train set: 9917\n    number of conversations in eval set: 521\n\n\n<a name=\"2.1\"></a>\n## 2.1   Tokenizing, batching with bucketing\nWe can now proceed in generating tokenized batches of our data. Let's first define a utility generator function to yield elements from our data sets:\n\n\n```python\ndef stream(data):\n    # loop over the entire data\n    while True:\n        # get a random element\n        d = random.choice(data)\n        \n        # yield a tuple pair of identical values \n        # (i.e. our inputs to the model will also be our targets during training)\n        yield (d, d)\n```\n\nNow let's define our data pipeline for tokenizing and batching our data. As in the previous assignments, we will bucket by length and also have an upper bound on the token length.\n\n\n```python\n# trax allows us to use combinators to generate our data pipeline\ndata_pipeline = trax.data.Serial(\n    # randomize the stream\n    trax.data.Shuffle(),\n    \n    # tokenize the data\n    trax.data.Tokenize(vocab_dir=VOCAB_DIR,\n                       vocab_file=VOCAB_FILE),\n    \n    # filter too long sequences\n    trax.data.FilterByLength(2048),\n    \n    # bucket by length\n    trax.data.BucketByLength(boundaries=[128, 256,  512, 1024],\n                             batch_sizes=[16,    8,    4,   2, 1]),\n    \n    # add loss weights but do not add it to the padding tokens (i.e. 0)\n    trax.data.AddLossWeights(id_to_mask=0)\n)\n\n# apply the data pipeline to our train and eval sets\ntrain_stream = data_pipeline(stream(train_data))\neval_stream = data_pipeline(stream(eval_data))\n```\n\nPeek into the train stream.\n\n\n```python\n# the stream generators will yield (input, target, weights). let's just grab the input for inspection\ninp, _, _ = next(train_stream)\n\n# print the shape. format is (batch size, token length)\nprint(\"input shape: \", inp.shape)\n\n# detokenize the first element\nprint(trax.data.detokenize(inp[0], vocab_dir=VOCAB_DIR, vocab_file=VOCAB_FILE))\n```\n\n    input shape:  (4, 512)\n     Person 1: I'm looking for a moderately priced place to eat in the North please Person 2: There's a restaurant that serves chinese and a restaurant that serves indian food. Will one of those work for you? Person 1: I would prefer the Indian restaurant please. Person 2: Okay. Would you like for me to make a reservation there? Person 1: Yes. Can you book for 8 people at 19:15 on Monday? Person 2: Ok, you're booked, the table will be reserved for 15 minutes. Reference number is : 7Y3YQNNR.\n    \n     Person 1: I also need to get a train.  Person 2: Alright when would you like to leave by? Person 1: I want the train from birmingham new street to arrive in cambridge by 09:30. I plan to travel on monday. Please provide me with the travel time for this trip Person 2: There are 4 options. The travel time for each trip is 163 minutes. Person 1: Get the earliest one, please.  Person 2: The earliest train leaves at 05:40 and arrives 08:23. The price is 75.10 pounds and travel time 163 minutes. Do you want to book, and if so for how many people? Person 1: Yes I would like to book, for 8 people. Person 2: Okay, it is booked. Reference number is VSTQEJ0S Person 1: Thank you for all of your help! Person 2: Thanks, have a great trip!\n\n\n<a name=\"3\"></a>\n# Part 3:   Reversible layers\n\nWhen running large deep models, you will often run out of memory as each layer allocates memory to store activations for use in backpropagation. To save this resource, you need to be able to recompute these activations during the backward pass without storing them during the forward pass. Take a look first at the leftmost diagram below. \n\n\n\nThis is how the residual networks are implemented in the standard Transformer. It follows that, given `F()` is Attention and `G()` is Feed-forward(FF). \n: \n\n\\begin{align}  \n\\mathrm{y}_\\mathrm{a} &= \\mathrm{x} + \\mathrm{F}\\left(\\mathrm{x}\\right)\\tag{1} \\\\\n\\mathrm{y}_{b}&=\\mathrm{y}_{a}+\\mathrm{G}\\left(\\mathrm{y}_{a}\\right)\\tag{2}\\\\\n\\end{align}\n\n\nAs you can see, it requires that $\\mathrm{x}$ and $\\mathrm{y}_{a}$ be saved so it can be used during backpropagation. We want to avoid this to conserve memory and this is where reversible residual connections come in. They are shown in the middle and rightmost diagrams above. The key idea is that we will start with two copies of the input to the model and at each layer we will only update one of them. The activations that we *don\u2019t* update are the ones that will be used to compute the residuals. \n\nNow in this reversible set up you get the following instead: \n\n\\begin{align}  \n\\mathrm{y}_{1}&=\\mathrm{x}_{1}+\\mathrm{F}\\left(\\mathrm{x}_{2}\\right)\\tag{3}\\\\\n\\mathrm{y}_{2}&=\\mathrm{x}_{2}+\\mathrm{G}\\left(\\mathrm{y}_{1}\\right)\\tag{4}\\\\\n\\end{align}\nTo recover $\\mathrm{(x_1,x_2)}$ from $\\mathrm{(y_1, y_2)}$ \n\n\\begin{align}  \n\\mathrm{x}_{2}&=\\mathrm{y}_{2}-\\mathrm{G}\\left(\\mathrm{y}_{1}\\right)\\tag{5}\\\\\n\\mathrm{x}_{1}&=\\mathrm{y}_{1}-\\mathrm{F}\\left(\\mathrm{x}_{2}\\right)\\tag{6}\\\\\n\\end{align}\n\nWith this configuration, we\u2019re now able to run the network fully in reverse. You'll notice that during the backward pass, $\\mathrm{x2}$ and $\\mathrm{x1}$ can be recomputed based solely on the values of $\\mathrm{y2}$ and $\\mathrm{y1}$. No need to save it during the forward pass.\n\n\n\n\n```python\n\ndef reversible_layer_forward(x, f, g):\n    \"\"\"\n    Args: \n        x (np.array): an input vector or matrix\n        f (function): a function which operates on a vector/matrix\n        g (function): a function which operates on a vector/matrix\n    Returns: \n        y (np.array): an output vector or matrix whose form is determined by 'x', f and g\n    \"\"\"\n    # split the input vector into two (* along the last axis because it is the depth dimension)\n    x1, x2 = np.split(x, 2, axis=-1) \n    \n        \n    # get y1 using equation 3\n    y1 = x1 + f(x2)\n    \n    # get y2 using equation 4\n    y2 = x2 + g(y1)\n    \n    # concatenate y1 and y2 along the depth dimension. be sure output is of type np.ndarray\n    y = np.concatenate([y1, y2], axis=-1)\n    \n    \n    return y\n```\n\n\n```python\n\ndef reversible_layer_reverse(y, f, g):\n    \"\"\"\n    Args: \n        y (np.array): an input vector or matrix\n        f (function): a function which operates on a vector/matrix of the form of 'y'\n        g (function): a function which operates on a vector/matrix of the form of 'y'\n    Returns: \n        y (np.array): an output vector or matrix whose form is determined by 'y', f and g\n    \"\"\"\n    \n    # split the input vector into two (* along the last axis because it is the depth dimension)\n    y1, y2 = np.split(y, 2, axis=-1)\n    \n    ### START CODE HERE (REPLACE INSTANCES OF 'None' WITH YOUR CODE) ###\n    \n    # compute x2 using equation 5\n    x2 = y2 - g(y1)\n    \n    # compute x1 using equation 6\n    x1 = y1 - f(x2)\n    \n    # concatenate x1 and x2 along the depth dimension\n    x = np.concatenate([x1, x2], axis=-1)\n    \n    \n    return x\n\n\n```\n\n\n```python\n# UNIT TEST COMMENT: assert at the end can be used in grading as well\nf = lambda x: x + 2\ng = lambda x: x * 3\ninput_vector = np.random.uniform(size=(32,))\n\noutput_vector = reversible_layer_forward(input_vector, f, g)\nreversed_vector = reversible_layer_reverse(output_vector, f, g)\n\nassert np.allclose(reversed_vector, input_vector)\n```\n\n<a name=\"3.1\"></a>\n## 3.1   Reversible layers and randomness\n\nThis is why we were learning about fastmath's random functions and keys in Course 3 Week 1. Utilizing the same key, `trax.fastmath.random.uniform()` will return the same values. This is required for the backward pass to return the correct layer inputs when random noise is introduced in the layer.\n\n\n```python\n# Layers like dropout have noise, so let's simulate it here:\nf = lambda x: x + np.random.uniform(size=x.shape)\n\n# See that the above doesn't work any more:\noutput_vector = reversible_layer_forward(input_vector, f, g)\nreversed_vector = reversible_layer_reverse(output_vector, f, g)\n\nassert not np.allclose(reversed_vector, input_vector)  # Fails!!\n\n# It failed because the noise when reversing used a different random seed.\n\nrandom_seed = 27686\nrng = trax.fastmath.random.get_prng(random_seed)\nf = lambda x: x + trax.fastmath.random.uniform(key=rng, shape=x.shape)\n\n# See that it works now as the same rng is used on forward and reverse.\noutput_vector = reversible_layer_forward(input_vector, f, g)\nreversed_vector = reversible_layer_reverse(output_vector, f, g)\n\nassert np.allclose(reversed_vector, input_vector,  atol=1e-07) \n```\n\n    WARNING:absl:No GPU/TPU found, falling back to CPU. (Set TF_CPP_MIN_LOG_LEVEL=0 and rerun for more info.)\n\n\n<a name=\"4\"></a>\n# Part 4:   ReformerLM Training\n\nWe will now proceed to training our model. Since we have already know the two main components that differentiates it from the standard Transformer, LSH in Course 1 and reversible layers above, we can just use the pre-built model already implemented in Trax. It will have this architecture:\n\n\n\nSimilar to the Transformer we learned earlier, we want to apply an attention and feed forward layer to your inputs. For the Reformer, we improve the memory efficiency by using **reversible decoder blocks** and youwecan picture its implementation in Trax like below:\n\n\n\n\n\n<a name=\"ex04\"></a>\n### Exercise 04\n**Instructions:** Implement a wrapper function that returns a Reformer Language Model. You can use Trax's [ReformerLM](https://trax-ml.readthedocs.io/en/latest/trax.models.html#trax.models.reformer.reformer.ReformerLM) to do this quickly. It will have the same architecture as shown above.\n\n\n```python\n\ndef ReformerLM(vocab_size=33000, n_layers=2, mode='train', attention_type=tl.SelfAttention):\n    \"\"\"\n    Args: \n        vocab_size (int): size of the vocabulary\n        n_layers (int): number of decoder layers\n        mode (string): setting of the model which can be 'train', 'eval', or 'predict' \n        attention_type(class): attention class to use \n    Returns: \n        model (ReformerLM): a reformer language model implemented in Trax\n    \"\"\"    \n    \n    \n    # initialize an instance of Trax's ReformerLM class\n    model = trax.models.reformer.ReformerLM( \n        # set vocab size\n        vocab_size=vocab_size,\n        # set number of layers\n        n_layers=n_layers,\n        # set mode\n        mode=mode,\n        # set attention type\n        attention_type=attention_type\n    )\n    \n    \n    return model\n```\n\n\n```python\n# display the model\ntemp_model = ReformerLM('train')\nprint(str(temp_model))\n\n# free memory\ndel temp_model \n```\n\n    Serial[\n      Serial[\n        AssertShape\n        ShiftRight(1)\n        AssertShape\n      ]\n      Embedding_train_512\n      Dropout\n      PositionalEncoding\n      Dup_out2\n      ReversibleSerial_in2_out2[\n        ReversibleHalfResidual_in2_out2[\n          Serial[\n            LayerNorm\n          ]\n          SelfAttention\n        ]\n        ReversibleSwap_in2_out2\n        ReversibleHalfResidual_in2_out2[\n          Serial[\n            LayerNorm\n            Dense_2048\n            Dropout\n            FastGelu\n            Dense_512\n            Dropout\n          ]\n        ]\n        ReversibleSwap_in2_out2\n        ReversibleHalfResidual_in2_out2[\n          Serial[\n            LayerNorm\n          ]\n          SelfAttention\n        ]\n        ReversibleSwap_in2_out2\n        ReversibleHalfResidual_in2_out2[\n          Serial[\n            LayerNorm\n            Dense_2048\n            Dropout\n            FastGelu\n            Dense_512\n            Dropout\n          ]\n        ]\n        ReversibleSwap_in2_out2\n      ]\n      Concatenate_in2\n      LayerNorm\n      Dropout\n      Dense_train\n      LogSoftmax\n    ]\n\n\n\n\n- Create `TrainTask` and `EvalTask`\n- Create the training loop `trax.supervised.training.Loop`\n- Pass in the following depending to train_task :\n    - `labeled_data=train_gen`\n    - `loss_layer=tl.CrossEntropyLoss()`\n    - `optimizer=trax.optimizers.Adam(0.01)`\n    - `lr_schedule=lr_schedule`\n    - `n_steps_per_checkpoint=10`  \n\n\n\n\n```python\n\ndef training_loop(ReformerLM, train_gen, eval_gen, output_dir = \"./model/\"):\n    \"\"\"\n    Args:\n        ReformerLM:  the Reformer language model you are building\n        train_gen (generator): train data generator.\n        eval_gen (generator): Validation generator. \n        output_dir (string): Path to save the model output. Defaults to './model/'.\n\n    Returns:\n        trax.supervised.training.Loop: Training loop for the model.\n    \"\"\"\n\n    # use the warmup_and_rsqrt_decay learning rate schedule\n    lr_schedule = trax.lr.warmup_and_rsqrt_decay(\n        n_warmup_steps=1000, max_value=0.01)\n\n\n    \n    # define the train task\n    train_task = training.TrainTask(            \n        # labeled data\n        labeled_data=train_gen,\n        # loss layer\n        loss_layer=tl.CrossEntropyLoss(),\n        # optimizer\n        optimizer=trax.optimizers.Adam(0.01),\n        # lr_schedule\n        lr_schedule=lr_schedule,\n        # n_steps\n        n_steps_per_checkpoint=10\n    )\n\n    # define the eval task\n    eval_task = training.EvalTask(                      \n        # labeled data\n        labeled_data=eval_gen,\n        # metrics\n        metrics=[tl.CrossEntropyLoss(), tl.Accuracy()]\n    )\n\n    \n    loop = training.Loop(ReformerLM(mode='train'),\n                         train_task,\n                         eval_tasks=[eval_task],\n                         output_dir=output_dir)\n    return loop\n```\n\n\n```python\n# we will now test your function\n!rm -f model/model.pkl.gz\nloop = training_loop(ReformerLM, train_stream, eval_stream)\nloop.run(10)\n```\n\n    \n    Step      1: Total number of trainable weights: 58072296\n    Step      1: Ran 1 train steps in 71.82 secs\n    Step      1: train CrossEntropyLoss |  10.42980957\n    Step      1: eval  CrossEntropyLoss |  10.39183235\n    Step      1: eval          Accuracy |  0.00000000\n    \n    Step     10: Ran 9 train steps in 213.35 secs\n    Step     10: train CrossEntropyLoss |  10.19278431\n    Step     10: eval  CrossEntropyLoss |  9.78180218\n    Step     10: eval          Accuracy |  0.05691554\n\n\n<a name=\"5\"></a>\n# Part 5:   Decode from a pretrained model\n\nWe will now proceed on decoding using the model architecture you just implemented. As in the previous weeks, we will be giving you a pretrained model so you can observe meaningful output during inference. You will be using the [autoregressive_sample_stream()](https://trax-ml.readthedocs.io/en/latest/trax.supervised.html#trax.supervised.decoding.autoregressive_sample_stream) decoding method from Trax to do fast inference. Let's define a few parameters to initialize our model.\n\n\n```python\n# define the `predict_mem_len` and `predict_drop_len` of tl.SelfAttention\ndef attention(*args, **kwargs):\n    # number of input positions to remember in a cache when doing fast inference. \n    kwargs['predict_mem_len'] = 120\n    # number of input elements to drop once the fast inference input cache fills up.\n    kwargs['predict_drop_len'] = 120\n    # return the attention layer with the parameters defined above\n    return tl.SelfAttention(*args, **kwargs)\n\n# define the model using the ReformerLM function you implemented earlier.\nmodel = ReformerLM(\n    vocab_size=33000,\n    n_layers=6,\n    mode='predict',\n    attention_type=attention,\n)\n\n# define an input signature so we can initialize our model. shape will be (1, 1) and the data type is int32.\nshape11 = trax.shapes.ShapeDtype((1, 1), dtype=np.int32)\n```\n\nWe can now initialize our model from a file containing the pretrained weights. We will save this starting state so we can reset the model state when we generate a new conversation. This will become clearer in the `generate_dialogue()` function later.\n\nLet's define a few utility functions as well to help us tokenize and detokenize. We can use the [tokenize()](https://trax-ml.readthedocs.io/en/latest/trax.data.html#trax.data.tf_inputs.tokenize) and [detokenize()](https://trax-ml.readthedocs.io/en/latest/trax.data.html#trax.data.tf_inputs.detokenize) from `trax.data.tf_inputs` to do this.\n\n\n```python\ndef tokenize(sentence, vocab_file, vocab_dir):\n    return list(trax.data.tokenize(iter([sentence]), vocab_file=vocab_file, vocab_dir=vocab_dir))[0]\n\ndef detokenize(tokens, vocab_file, vocab_dir):\n    return trax.data.detokenize(tokens, vocab_file=vocab_file, vocab_dir=vocab_dir)\n```\n\nWe are now ready to define our decoding function. This will return a generator that yields that next symbol output by the model. It will be able to predict the next words by just feeding it a starting sentence.\n\n\n```python\n\ndef ReformerLM_output_gen(ReformerLM, start_sentence, vocab_file, vocab_dir, temperature):\n    \"\"\"\n    Args:\n        ReformerLM:  the Reformer language model you just trained\n        start_sentence (string): starting sentence of the conversation\n        vocab_file (string): vocabulary filename\n        vocab_dir (string): directory of the vocabulary file\n        temperature (float): parameter for sampling ranging from 0.0 to 1.0.\n            0.0: same as argmax, always pick the most probable token\n            1.0: sampling from the distribution (can sometimes say random things)\n\n    Returns:\n        generator: yields the next symbol generated by the model\n    \"\"\"\n    \n\n    \n    # Create input tokens using the the tokenize function\n    input_tokens = tokenize(start_sentence, vocab_file=vocab_file, vocab_dir=vocab_dir)\n    \n    # Add batch dimension to array. Convert from (n,) to (x, n) where \n    # x is the batch size. Default is 1. (hint: you can use np.expand_dims() with axis=0)\n    input_tokens_with_batch = np.array(input_tokens)[None, :]\n    \n    # call the autoregressive_sample_stream function from trax\n    output_gen = trax.supervised.decoding.autoregressive_sample_stream( \n        # model\n        ReformerLM,\n        # inputs will be the tokens with batch dimension\n        inputs=input_tokens_with_batch,\n        # temperature\n        temperature=temperature\n    )\n    \n    \n    \n    return output_gen\n```\n\n\n```python\nshape11 = trax.shapes.ShapeDtype((1, 1), dtype=np.int32)\n\ndef attention(*args, **kwargs):\n    kwargs['predict_mem_len'] = 120  # max length for predictions\n    kwargs['predict_drop_len'] = 120  # never drop old stuff\n    return tl.SelfAttention(*args, **kwargs)\n\nmodel = ReformerLM(\n    vocab_size=33000,\n    n_layers=6,\n    mode='predict',\n    attention_type=attention,\n)\n```\n\n\n```python\nmodel.init_from_file('chatbot_model1.pkl.gz',\n                     weights_only=True, input_signature=shape11)\n\nSTARTING_STATE = model.state\n```\n\n\n```python\ndef generate_dialogue(ReformerLM, model_state, start_sentence, vocab_file, vocab_dir, max_len, temperature):\n    \"\"\"\n    Args:\n        ReformerLM:  the Reformer language model you just trained\n        model_state (np.array): initial state of the model before decoding\n        start_sentence (string): starting sentence of the conversation\n        vocab_file (string): vocabulary filename\n        vocab_dir (string): directory of the vocabulary file\n        max_len (int): maximum number of tokens to generate \n        temperature (float): parameter for sampling ranging from 0.0 to 1.0.\n            0.0: same as argmax, always pick the most probable token\n            1.0: sampling from the distribution (can sometimes say random things)\n\n    Returns:\n        generator: yields the next symbol generated by the model\n    \"\"\"  \n    \n    # define the delimiters we used during training\n    delimiter_1 = 'Person 1: ' \n    delimiter_2 = 'Person 2: '\n    \n    # initialize detokenized output\n    sentence = ''\n    \n    # token counter\n    counter = 0\n    \n    # output tokens. we insert a ': ' for formatting\n    result = [tokenize(': ', vocab_file=vocab_file, vocab_dir=vocab_dir)]\n    \n    # reset the model state when starting a new dialogue\n    ReformerLM.state = model_state\n    \n    # calls the output generator implemented earlier\n    output = ReformerLM_output_gen(ReformerLM, start_sentence, vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR, temperature=temperature)\n    \n    # print the starting sentence\n    print(start_sentence.split(delimiter_2)[0].strip())\n    \n    # loop below yields the next tokens until max_len is reached. the if-elif is just for prettifying the output.\n    for o in output:\n        \n        result.append(o)\n        \n        sentence = detokenize(np.concatenate(result, axis=0), vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR)\n        \n        if sentence.endswith(delimiter_1):\n            sentence = sentence.split(delimiter_1)[0]\n            print(f'{delimiter_2}{sentence}')\n            sentence = ''\n            result.clear()\n        \n        elif sentence.endswith(delimiter_2):\n            sentence = sentence.split(delimiter_2)[0]\n            print(f'{delimiter_1}{sentence}')\n            sentence = ''\n            result.clear()\n\n        counter += 1\n        \n        if counter > max_len:\n            break    \n\n\n```\n\nWe can now feed in different starting sentences and see how the model generates the dialogue. You can even input your own starting sentence. Just remember to ask a question that covers the topics in the Multiwoz dataset so you can generate a meaningful conversation.\n\n\n```python\nsample_sentence = ' Person 1: Are there theatres in town? Person 2: '\ngenerate_dialogue(ReformerLM=model, model_state=STARTING_STATE, start_sentence=sample_sentence, vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR, max_len=120, temperature=0.2)\n```\n\n    Person 1: Are there theatres in town?\n    Person 2: : There are 4 theatres in town. Do you have a preference? \n    Person 1: Not really, but I would like the one in the south. \n    Person 2: I have one theatre, the Junction, and the other is Tenpin. \n    Person 1: Could I get the address and postcode? \n    Person 1: The postcode is cb17gx, and the address is Clifton Way, Cambridge Leisure Park, Clifton Way. Is there anything else I can i give for? \n\n\n\n```python\nsample_sentence = ' Person 1: Is there a hospital nearby? Person 2: '\ngenerate_dialogue(ReformerLM=model, model_state=STARTING_STATE, start_sentence=sample_sentence, vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR, max_len=120, temperature=0.2)\n```\n\n    Person 1: Is there a hospital nearby?\n    Person 2: : Addensbrookes Hospital is located at Hills Rd, Cambridge, postcode CB20QQ. Do you need a particular department? \n    Person 1: No, I just need the phone number, please. \n    Person 2: The phone number is 01223245151. \n    Person 1: Thank you. That's all I need. \n    Person 2: Thank you for using our services.Goodbye.\n    Person 1: Goodbye. \n\n\n\n```python\nsample_sentence = ' Person 1: Can you book a taxi? Person 2: '\ngenerate_dialogue(ReformerLM=model, model_state=STARTING_STATE, start_sentence=sample_sentence, vocab_file=VOCAB_FILE, vocab_dir=VOCAB_DIR, max_len=120, temperature=0.2)\n```\n\n    Person 1: Can you book a taxi?\n    Person 2: : I sure can. When would you like to leave? \n    Person 1: I need to leave after 13:00. \n    Person 2: I'd be happy to help with your request, first I will need to know your destination. \n    Person 1: I'm going to be going to be from the city stop restaurant. \n    Person 2: Booking completed! Booked car type\t:\tgrey volkswagen\n    Contact number\t:\t07262372\n     \n    Person 2: Thank bybybybyby\n\n", "meta": {"hexsha": "a73df00ef270caef346540d330f1490b03e8a916", "size": 87376, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "dialogue_generation/dialogue_generation.ipynb", "max_stars_repo_name": "rakki-18/imdb-review-classification", "max_stars_repo_head_hexsha": "1989c8e1dc2042be91969867018b088c974c02fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-03T15:23:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T15:23:47.000Z", "max_issues_repo_path": "dialogue_generation/dialogue_generation.ipynb", "max_issues_repo_name": "rakki-18/NLP-models", "max_issues_repo_head_hexsha": "1989c8e1dc2042be91969867018b088c974c02fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dialogue_generation/dialogue_generation.ipynb", "max_forks_repo_name": "rakki-18/NLP-models", "max_forks_repo_head_hexsha": "1989c8e1dc2042be91969867018b088c974c02fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1055385957, "max_line_length": 745, "alphanum_fraction": 0.5882965574, "converted": true, "num_tokens": 15741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15817436862177234, "lm_q2_score": 0.06465348204835548, "lm_q1q2_score": 0.010226523702197721}}
{"text": "```\n!pip3 install qiskit\n```\n\n    Requirement already satisfied: qiskit in /usr/local/lib/python3.6/dist-packages (0.19.4)\n    Requirement already satisfied: qiskit-ignis==0.3.0 in /usr/local/lib/python3.6/dist-packages (from qiskit) (0.3.0)\n    Requirement already satisfied: qiskit-terra==0.14.2 in /usr/local/lib/python3.6/dist-packages (from qiskit) (0.14.2)\n    Requirement already satisfied: qiskit-aer==0.5.2 in /usr/local/lib/python3.6/dist-packages (from qiskit) (0.5.2)\n    Requirement already satisfied: qiskit-aqua==0.7.2 in /usr/local/lib/python3.6/dist-packages (from qiskit) (0.7.2)\n    Requirement already satisfied: qiskit-ibmq-provider==0.7.2 in /usr/local/lib/python3.6/dist-packages (from qiskit) (0.7.2)\n    Requirement already satisfied: scipy!=0.19.1,>=0.19 in /usr/local/lib/python3.6/dist-packages (from qiskit-ignis==0.3.0->qiskit) (1.4.1)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-ignis==0.3.0->qiskit) (47.3.1)\n    Requirement already satisfied: numpy>=1.13 in /usr/local/lib/python3.6/dist-packages (from qiskit-ignis==0.3.0->qiskit) (1.18.5)\n    Requirement already satisfied: marshmallow<4,>=3 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (3.6.1)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (5.4.8)\n    Requirement already satisfied: retworkx>=0.3.2 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (0.3.4)\n    Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (2.6.0)\n    Requirement already satisfied: ply>=3.10 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (3.11)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (1.6)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (2.8.1)\n    Requirement already satisfied: marshmallow-polyfield<6,>=5.7 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (5.9)\n    Requirement already satisfied: python-constraint>=1.4 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (1.4.0)\n    Requirement already satisfied: fastjsonschema>=2.10 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (2.14.4)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (0.3.1.1)\n    Requirement already satisfied: networkx>=2.2; python_version > \"3.5\" in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (2.4)\n    Requirement already satisfied: cython>=0.27.1 in /usr/local/lib/python3.6/dist-packages (from qiskit-aer==0.5.2->qiskit) (0.29.20)\n    Requirement already satisfied: pybind11>=2.4 in /usr/local/lib/python3.6/dist-packages (from qiskit-aer==0.5.2->qiskit) (2.5.0)\n    Requirement already satisfied: pyscf; sys_platform != \"win32\" in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.2->qiskit) (1.7.3)\n    Requirement already satisfied: docplex in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.2->qiskit) (2.14.186)\n    Requirement already satisfied: scikit-learn>=0.20.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.2->qiskit) (0.22.2.post1)\n    Requirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.2->qiskit) (2.10.0)\n    Requirement already satisfied: quandl in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.2->qiskit) (3.5.0)\n    Requirement already satisfied: cvxpy<1.1.0,>1.0.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.2->qiskit) (1.0.31)\n    Requirement already satisfied: dlx in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.2->qiskit) (1.0.4)\n    Requirement already satisfied: fastdtw in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.2->qiskit) (0.3.4)\n    Requirement already satisfied: requests-ntlm>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit) (1.1.0)\n    Requirement already satisfied: websockets<8,>=7 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit) (7.0)\n    Requirement already satisfied: nest-asyncio!=1.1.0,>=1.0.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit) (1.3.3)\n    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit) (2.23.0)\n    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit) (1.24.3)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy>=1.3->qiskit-terra==0.14.2->qiskit) (1.1.0)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.6/dist-packages (from python-dateutil>=2.8.0->qiskit-terra==0.14.2->qiskit) (1.12.0)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx>=2.2; python_version > \"3.5\"->qiskit-terra==0.14.2->qiskit) (4.4.2)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.7.2->qiskit) (0.15.1)\n    Requirement already satisfied: inflection>=0.3.1 in /usr/local/lib/python3.6/dist-packages (from quandl->qiskit-aqua==0.7.2->qiskit) (0.5.0)\n    Requirement already satisfied: more-itertools in /usr/local/lib/python3.6/dist-packages (from quandl->qiskit-aqua==0.7.2->qiskit) (8.4.0)\n    Requirement already satisfied: pandas>=0.14 in /usr/local/lib/python3.6/dist-packages (from quandl->qiskit-aqua==0.7.2->qiskit) (1.0.4)\n    Requirement already satisfied: scs>=1.1.3 in /usr/local/lib/python3.6/dist-packages (from cvxpy<1.1.0,>1.0.0->qiskit-aqua==0.7.2->qiskit) (2.1.2)\n    Requirement already satisfied: osqp>=0.4.1 in /usr/local/lib/python3.6/dist-packages (from cvxpy<1.1.0,>1.0.0->qiskit-aqua==0.7.2->qiskit) (0.6.1)\n    Requirement already satisfied: ecos>=2 in /usr/local/lib/python3.6/dist-packages (from cvxpy<1.1.0,>1.0.0->qiskit-aqua==0.7.2->qiskit) (2.0.7.post1)\n    Requirement already satisfied: multiprocess in /usr/local/lib/python3.6/dist-packages (from cvxpy<1.1.0,>1.0.0->qiskit-aqua==0.7.2->qiskit) (0.70.9)\n    Requirement already satisfied: ntlm-auth>=1.0.2 in /usr/local/lib/python3.6/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit) (1.5.0)\n    Requirement already satisfied: cryptography>=1.3 in /usr/local/lib/python3.6/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit) (2.9.2)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.7.2->qiskit) (2020.4.5.2)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.7.2->qiskit) (2.9)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.7.2->qiskit) (3.0.4)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.14->quandl->qiskit-aqua==0.7.2->qiskit) (2018.9)\n    Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from osqp>=0.4.1->cvxpy<1.1.0,>1.0.0->qiskit-aqua==0.7.2->qiskit) (0.16.0)\n    Requirement already satisfied: cffi!=1.11.3,>=1.8 in /usr/local/lib/python3.6/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit) (1.14.0)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.6/dist-packages (from cffi!=1.11.3,>=1.8->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit) (2.20)\n\n\n\n```\nimport qiskit\n```\n\n\n```\nconstant_index_dictionary = {}\nconstant_index_dictionary['0000'] = [0, 2]\nconstant_index_dictionary['0001'] = [2, 3]\nconstant_index_dictionary['0010'] = [0, 1]\nconstant_index_dictionary['0011'] = [1, 3]\nconstant_index_dictionary['0100'] = [2, 3]\nconstant_index_dictionary['0101'] = [1, 2]\nconstant_index_dictionary['0110'] = [0, 2]\nconstant_index_dictionary['0111'] = [0, 2]\nconstant_index_dictionary['1000'] = [0, 3]\nconstant_index_dictionary['1001'] = [0, 1]\nconstant_index_dictionary['1010'] = [1, 2]\nconstant_index_dictionary['1011'] = [0, 3]\nconstant_index_dictionary['1100'] = [1, 3]\nconstant_index_dictionary['1101'] = [2, 3]\nconstant_index_dictionary['1110'] = [1, 3]\nconstant_index_dictionary['1111'] = [0, 1]\n```\n\n\n```\nimport qiskit\nimport numpy as np\nimport time\n\nCLASSICAL_REGISTER_LENGTH  = 5\nQUANTUM_REGISTER_LENGTH  = 5\n\ncircuit_building_start_time = time.time()\nsimulator = qiskit.Aer.get_backend('qasm_simulator')\nclassical_register = qiskit.ClassicalRegister(CLASSICAL_REGISTER_LENGTH)\nquantum_register = qiskit.QuantumRegister(QUANTUM_REGISTER_LENGTH)\ncircuit = qiskit.QuantumCircuit(quantum_register, classical_register)\ncircuit_building_end_time = time.time()\n\n\nAND_gate_auxillary_qubit =  QUANTUM_REGISTER_LENGTH - 1 # last qubit as the auxillary qubit\n\n'''\n    Applies quantum AND operation to specified pair of qubits, stores the operation in AND_gate_auxillary_qubit,\n    and stores the result in a classical register\n    @PARAMS:\n        qubit1: position of the first qubit\n        qubit2: position of the second qubit\n        qubit1_one: whether the first qubit is NOT\n        qubit2_one: whether the second qubit is NOT\n        classical_register_position: the classical register position to store the measurement of AND_gate_auxillary_qubit\n'''\ndef AND_2_qubit(qubit1, qubit2, qubit1_one, qubit2_one, classical_register_position):\n    \n    if(qubit1_one):\n        circuit.x(quantum_register[qubit1])\n    if(qubit2_one):\n        circuit.x(quantum_register[qubit2])\n    circuit.ccx(quantum_register[qubit1], quantum_register[qubit2], quantum_register[AND_gate_auxillary_qubit])\n    circuit.measure(quantum_register[AND_gate_auxillary_qubit], classical_register[classical_register_position])\n    if(qubit1_one):\n        circuit.x(quantum_register[qubit1])\n    if(qubit2_one):\n        circuit.x(quantum_register[qubit2])\n    circuit.reset(quantum_register[AND_gate_auxillary_qubit])\n\n'''\n    Applies the AND gate operation on a list of n qubits\n    @PARAMS:\n        qubit_list: list of qubits to perform the operation on\n        qubit_one_list: whether each of those qubits is NOT\n    @RETURN:\n        result of the n-qubit AND operation\n'''\ndef AND_n_qubits(qubit_list, qubit_one_list):\n    \n    length = len(qubit_list)\n    if(length != len(qubit_one_list)):\n        print(\"Incorrect dimensions\")\n        return\n    classical_register_index = 0 # where to store pairwise AND operation results\n\n    # handling odd number of qubits by preprocessing the last qubit\n    if(length % 2 != 0):\n        if(qubit_one_list[length - 1] == 1):\n            circuit.x(quantum_register[qubit_list[length-1]])\n        circuit.cx(quantum_register[qubit_list[length - 1]], quantum_register[AND_gate_auxillary_qubit])\n        circuit.measure(quantum_register[AND_gate_auxillary_qubit], classical_register[classical_register_index])\n        circuit.reset(quantum_register[AND_gate_auxillary_qubit])\n        classical_register_index = classical_register_index + 1\n        if(qubit_one_list[length - 1] == 1):\n            circuit.x(quantum_register[qubit_list[length-1]])\n        length = length - 1\n\n\n    for index in range(length - 1, 0, -2):\n        AND_2_qubit(qubit_list[index], qubit_list[index - 1], qubit_one_list[index], qubit_one_list[index - 1], classical_register_index)\n        classical_register_index = classical_register_index + 1\n    \n    job = qiskit.execute(circuit, simulator, shots=1)\n    result = job.result()\n    counts = str(result.get_counts())\n    counts = counts[counts.find('\\'') + 1:]\n    counts = counts[:counts.find('\\'')]\n    output = 1\n    for index in range(0, classical_register_index, 1):\n        output = output & int(counts[CLASSICAL_REGISTER_LENGTH - 1 - index])\n    \n    return output\n\ndef controlled_n_qubit_h(qubit_list, qubit_one_list):\n    output = AND_n_qubits(qubit_list, qubit_one_list)\n    if(output == 1):\n        circuit.h(quantum_register[AND_gate_auxillary_qubit])\n        circuit.measure(quantum_register[AND_gate_auxillary_qubit], classical_register[0])\n        circuit.reset(quantum_register[AND_gate_auxillary_qubit])\n        job = qiskit.execute(circuit, simulator, shots=1)\n        result = job.result()\n        counts = str(result.get_counts())\n        counts = counts[counts.find('\\'') + 1:]\n        counts = counts[:counts.find('\\'')]\n        return int(counts[len(counts) - 1])\n    return 0\n\n'''\n    the main circuit for the following truth table:\n    A, B, C, D = binary representation input state for the robot\n    P, Q, R, S = binary representation of the output state from the robot\n\n    New circuit in register...\n'''\n\ndef main_circuit(STEPS, initial_state):\n    signature = \"\"\n    state = initial_state\n    step = 0\n    while (step < STEPS):\n\n        dont_care_list = constant_index_dictionary[state]\n        input_state = state\n        state = \"\"\n\n        P = controlled_n_qubit_h([0, 1, 3], [1, 1, 0]) | controlled_n_qubit_h([1, 2], [0, 1]) | controlled_n_qubit_h([0, 2, 3], [0, 0, 1]) | AND_n_qubits([1, 2, 3], [0, 0, 0]) | AND_n_qubits([0, 1, 3], [1, 1, 1]) | AND_n_qubits([1, 2, 3], [1, 1, 1])\n        \n        Q = controlled_n_qubit_h([0, 1, 2], [1, 0, 0]) | controlled_n_qubit_h([0, 1, 2], [1, 1, 1]) | controlled_n_qubit_h([0, 2, 3], [1, 1, 1]) | controlled_n_qubit_h([1, 2, 3], [1, 1, 1]) | controlled_n_qubit_h([0, 1, 2, 3], [0, 0, 1, 0]) | controlled_n_qubit_h([0, 1, 2, 3], [0, 1, 0, 0]) | AND_n_qubits([0, 1, 3], [0, 0, 1]) | AND_n_qubits([0, 1, 2, 3], [1, 1, 0, 1]) | AND_n_qubits([0, 1, 2, 3], [1, 0, 1, 0]) | AND_n_qubits([0, 1, 2, 3], [0, 1, 1, 0])\n\n        R = controlled_n_qubit_h([0, 1, 2], [1, 1, 0]) | controlled_n_qubit_h([0, 1, 2], [0, 0, 0]) | controlled_n_qubit_h([0, 1, 3], [0, 1, 0]) | controlled_n_qubit_h([0, 2, 3], [0, 1, 1]) | AND_n_qubits([0, 1], [1, 0]) | AND_n_qubits([0, 1, 2, 3], [0, 1, 0, 1])\n\n        S = controlled_n_qubit_h([1, 2, 3], [1, 0, 1]) | controlled_n_qubit_h([0, 1, 3], [1, 1, 1]) | controlled_n_qubit_h([0, 1, 3], [1, 0, 0]) | controlled_n_qubit_h([0, 1, 2], [1, 0, 0]) | controlled_n_qubit_h([1, 2, 3], [0, 0, 0]) |  AND_n_qubits([0, 1, 2], [0, 0, 1]) | AND_n_qubits([0, 1, 2, 3], [0, 1, 0, 0])\n\n\n        state = state + str(P) + str(Q) + str(R) + str(S) \n        \n        y = int(input_state, 2)^int(state,2)\n        y = bin(y)[2:].zfill(len(state))\n        # print(\"\" + str(y) + \" is the XOR string\")\n        hamming_distance = len(y.replace('0', \"\"))\n        # print(input_state + \" \" + state + \" \" + str(hamming_distance))\n        step = step + hamming_distance\n        hidden_state = \"\"\n        for j in range(len(state)):\n            if(j in dont_care_list):\n              hidden_state = hidden_state + \"x\"\n            else:\n              hidden_state = hidden_state + state[j]\n        \n        # print(state + \" \" + hidden_state)\n        signature = signature + hidden_state\n\n        for _ in range(len(circuit.data)):\n          circuit.data.pop(0)\n\n        if(P == 1):\n            circuit.x(quantum_register[0])\n        \n        if(Q == 1):\n            circuit.x(quantum_register[1])\n\n        if(R == 1):\n            circuit.x(quantum_register[2])\n\n        if(S == 1):\n            circuit.x(quantum_register[3])\n\n    print(\"End state: \" + str(P) + str(Q) + str(R) + str(S) )\n    print(\"Signature: \" + signature)\n        \ndef initialise_starting_state(P, Q, R, S):\n    if(P == 1):\n      circuit.x(quantum_register[0])\n    if(Q == 1):\n      circuit.x(quantum_register[1])\n    if(R == 1):\n      circuit.x(quantum_register[2])\n    if(S == 1):\n      circuit.x(quantum_register[3])\n    print(\"Message: \" + str(P) + str(Q) + str(R) + str(S))\n\ndef measure_time():\n\n    total_time = 0\n    for i in range(100):\n        start_time = time.time()\n        # output = AND_n_qubits([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1])\n        output = controlled_n_qubit_h([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1])\n        \n        print(str(i) + \" \" + str(output))\n        end_time = time.time()\n        total_time = total_time + (end_time - start_time)\n    print(\"Average time: \" + str(total_time/100))\n\n\nstart_time = time.time()\ninitialise_starting_state(1, 0, 1, 1)       # message to be signed\nSTEPS = 20                                  # security parameter: length of the walk\nmain_circuit(STEPS, '1011') \n# measure_time()\nend_time = time.time()\nprint(\"Run in time \" + str(end_time - start_time))\nprint(circuit_building_end_time - circuit_building_start_time)\n```\n\n    Message: 1011\n    End state: 1111\n    Signature: x00x10xxx10x1x1xxx101xx01xx1x01x1x0xx11x0x1xx1x0x0x0xx11\n    Run in time 5.65201735496521\n    0.0003039836883544922\n\n\n\n```\ndef recipient_initialise_starting_state(P, Q, R, S):\n    if(P == \"1\"):\n      circuit.x(quantum_register[0])\n    if(Q == \"1\"):\n      circuit.x(quantum_register[1])\n    if(R == \"1\"):\n      circuit.x(quantum_register[2])\n    if(S == \"1\"):\n      circuit.x(quantum_register[3])\n    print(\"Message: \" + str(P) + str(Q) + str(R) + str(S))\n\ndef recipient(message, signature, end_state):\n  STEPS = len(signature)/len(end_state)\n  STEPS = int(STEPS)\n  index = 0\n  recipient_initialise_starting_state(message[0], message[1], message[2], message[3])\n  state = message\n  recreated_signature = \"\"\n  for _ in range(STEPS):\n\n        dont_care_list = constant_index_dictionary[state]\n        state = \"\"\n        \n        P = controlled_n_qubit_h([0, 1, 3], [1, 1, 0]) | controlled_n_qubit_h([1, 2], [0, 1]) | controlled_n_qubit_h([0, 2, 3], [0, 0, 1]) | AND_n_qubits([1, 2, 3], [0, 0, 0]) | AND_n_qubits([0, 1, 3], [1, 1, 1]) | AND_n_qubits([1, 2, 3], [1, 1, 1])\n        \n        Q = controlled_n_qubit_h([0, 1, 2], [1, 0, 0]) | controlled_n_qubit_h([0, 1, 2], [1, 1, 1]) | controlled_n_qubit_h([0, 2, 3], [1, 1, 1]) | controlled_n_qubit_h([1, 2, 3], [1, 1, 1]) | controlled_n_qubit_h([0, 1, 2, 3], [0, 0, 1, 0]) | controlled_n_qubit_h([0, 1, 2, 3], [0, 1, 0, 0]) | AND_n_qubits([0, 1, 3], [0, 0, 1]) | AND_n_qubits([0, 1, 2, 3], [1, 1, 0, 1]) | AND_n_qubits([0, 1, 2, 3], [1, 0, 1, 0]) | AND_n_qubits([0, 1, 2, 3], [0, 1, 1, 0])\n\n        R = controlled_n_qubit_h([0, 1, 2], [1, 1, 0]) | controlled_n_qubit_h([0, 1, 2], [0, 0, 0]) | controlled_n_qubit_h([0, 1, 3], [0, 1, 0]) | controlled_n_qubit_h([0, 2, 3], [0, 1, 1]) | AND_n_qubits([0, 1], [1, 0]) | AND_n_qubits([0, 1, 2, 3], [0, 1, 0, 1])\n\n        S = controlled_n_qubit_h([1, 2, 3], [1, 0, 1]) | controlled_n_qubit_h([0, 1, 3], [1, 1, 1]) | controlled_n_qubit_h([0, 1, 3], [1, 0, 0]) | controlled_n_qubit_h([0, 1, 2], [1, 0, 0]) | controlled_n_qubit_h([1, 2, 3], [0, 0, 0]) |  AND_n_qubits([0, 1, 2], [0, 0, 1]) | AND_n_qubits([0, 1, 2, 3], [0, 1, 0, 0])\n\n\n        if(signature[index] != \"x\" and signature[index] == \"1\"):\n          P = P | 1\n        elif(signature[index] != \"x\"):\n          P = P & 0\n        \n        index = index + 1\n\n        if(signature[index] != \"x\" and signature[index] == \"1\"):\n          Q = Q | 1\n        elif(signature[index] != \"x\"):\n          Q = Q & 0\n        \n        index = index + 1\n\n        if(signature[index] != \"x\" and signature[index] == \"1\"):\n          R = R | 1\n        elif(signature[index] != \"x\"):\n          R = R & 0\n\n        index = index + 1\n\n        if(signature[index] != \"x\" and signature[index] == \"1\"):\n          S = S | 1\n        elif(signature[index] != \"x\"):\n          S = S & 0\n\n        index = index + 1\n\n        state = \"\" + str(P) + str(Q) + str(R) + str(S)\n\n        hidden_state = \"\"\n        for j in range(len(state)):\n            if(j in dont_care_list):\n              hidden_state = hidden_state + \"x\"\n            else:\n              hidden_state = hidden_state + state[j]\n        \n        print(state + \" \" + hidden_state)\n        recreated_signature = recreated_signature + hidden_state\n\n        for _ in range(len(circuit.data)):\n          circuit.data.pop(0)\n\n        if(P == 1):\n            circuit.x(quantum_register[0])\n        \n        if(Q == 1):\n            circuit.x(quantum_register[1])\n\n        if(R == 1):\n            circuit.x(quantum_register[2])\n\n        if(S == 1):\n            circuit.x(quantum_register[3])\n  print(recreated_signature)\n  print(signature)\n  if(recreated_signature == signature):\n    print(\"ACCEPT\")\n  else:\n    print(\"REJECT\")\n```\n\n\n```\nstart = time.time()\nfor _ in range(len(circuit.data)):\n  circuit.data.pop(0)\nrecipient(\"1011\", \"x10x10xxx10x1x1xxx101xx01xx1x01x1x0xx11x0x1xx1x0x0x0xx11\", \"1111\")\nfor _ in range(len(circuit.data)):\n  circuit.data.pop(0)\nrecipient(\"1011\", \"x00x10xxx10x1x1xxx101xx01xx1x01x1x0xx11x0x1xx1x0x0x0xx11\", \"1111\")\nprint(time.time() - start)\n```\n\n    Message: 1011\n    0101 x10x\n    1011 1xx1\n    0101 x10x\n    1111 1xx1\n    1010 xx10\n    1010 1xx0\n    1011 1xx1\n    0011 x01x\n    1000 1x0x\n    1110 x11x\n    0110 0x1x\n    0110 x1x0\n    0010 x0x0\n    1111 xx11\n    x10x1xx1x10x1xx1xx101xx01xx1x01x1x0xx11x0x1xx1x0x0x0xx11\n    x10x10xxx10x1x1xxx101xx01xx1x01x1x0xx11x0x1xx1x0x0x0xx11\n    REJECT\n    Message: 1011\n    0001 x00x\n    1000 10xx\n    1100 x10x\n    1111 1x1x\n    1010 xx10\n    1010 1xx0\n    1011 1xx1\n    0011 x01x\n    1000 1x0x\n    1110 x11x\n    0110 0x1x\n    0110 x1x0\n    0010 x0x0\n    1111 xx11\n    x00x10xxx10x1x1xxx101xx01xx1x01x1x0xx11x0x1xx1x0x0x0xx11\n    x00x10xxx10x1x1xxx101xx01xx1x01x1x0xx11x0x1xx1x0x0x0xx11\n    ACCEPT\n    11.85292911529541\n\n\n# Scheme 2\n\nNon-transfer of x\n\nMore secure\n\nRequires one-time additional sharing of a dictionary\n\nFrom the two dictionaries is inferred the total number of output states\n(in the cell below, 2 + 2 = 4)\n\n\n\n```\nconstant_index_dictionary = {}\nconstant_index_dictionary['0000'] = [0, 2]\nconstant_index_dictionary['0001'] = [2, 3]\nconstant_index_dictionary['0010'] = [0, 1]\nconstant_index_dictionary['0011'] = [1, 3]\nconstant_index_dictionary['0100'] = [2, 3]\nconstant_index_dictionary['0101'] = [1, 2]\nconstant_index_dictionary['0110'] = [0, 2]\nconstant_index_dictionary['0111'] = [0, 2]\nconstant_index_dictionary['1000'] = [0, 3]\nconstant_index_dictionary['1001'] = [0, 1]\nconstant_index_dictionary['1010'] = [1, 2]\nconstant_index_dictionary['1011'] = [0, 3]\nconstant_index_dictionary['1100'] = [1, 3]\nconstant_index_dictionary['1101'] = [2, 3]\nconstant_index_dictionary['1110'] = [1, 3]\nconstant_index_dictionary['1111'] = [0, 1]\n\n# additional dictionary to be shared\n\nhidden_index_dictionary = {}\nhidden_index_dictionary['0000'] = [1, 3]\nhidden_index_dictionary['0001'] = [0, 1]\nhidden_index_dictionary['0010'] = [2, 3]\nhidden_index_dictionary['0011'] = [0, 2]\nhidden_index_dictionary['0100'] = [0, 1]\nhidden_index_dictionary['0101'] = [0, 3]\nhidden_index_dictionary['0110'] = [1, 3]\nhidden_index_dictionary['0111'] = [1, 3]\nhidden_index_dictionary['1000'] = [1, 2]\nhidden_index_dictionary['1001'] = [2, 3]\nhidden_index_dictionary['1010'] = [0, 3]\nhidden_index_dictionary['1011'] = [1, 2]\nhidden_index_dictionary['1100'] = [0, 2]\nhidden_index_dictionary['1101'] = [0, 1]\nhidden_index_dictionary['1110'] = [0, 2]\nhidden_index_dictionary['1111'] = [2, 3]\n```\n\n\n```\nimport qiskit\nimport numpy as np\nimport time\n\nCLASSICAL_REGISTER_LENGTH  = 5\nQUANTUM_REGISTER_LENGTH  = 5\n\ncircuit_building_start_time = time.time()\nsimulator = qiskit.Aer.get_backend('qasm_simulator')\nclassical_register = qiskit.ClassicalRegister(CLASSICAL_REGISTER_LENGTH)\nquantum_register = qiskit.QuantumRegister(QUANTUM_REGISTER_LENGTH)\ncircuit = qiskit.QuantumCircuit(quantum_register, classical_register)\ncircuit_building_end_time = time.time()\n\n\nAND_gate_auxillary_qubit =  QUANTUM_REGISTER_LENGTH - 1 # last qubit as the auxillary qubit\n\n'''\n    Applies quantum AND operation to specified pair of qubits, stores the operation in AND_gate_auxillary_qubit,\n    and stores the result in a classical register\n    @PARAMS:\n        qubit1: position of the first qubit\n        qubit2: position of the second qubit\n        qubit1_one: whether the first qubit is NOT\n        qubit2_one: whether the second qubit is NOT\n        classical_register_position: the classical register position to store the measurement of AND_gate_auxillary_qubit\n'''\ndef AND_2_qubit(qubit1, qubit2, qubit1_one, qubit2_one, classical_register_position):\n    \n    if(qubit1_one):\n        circuit.x(quantum_register[qubit1])\n    if(qubit2_one):\n        circuit.x(quantum_register[qubit2])\n    circuit.ccx(quantum_register[qubit1], quantum_register[qubit2], quantum_register[AND_gate_auxillary_qubit])\n    circuit.measure(quantum_register[AND_gate_auxillary_qubit], classical_register[classical_register_position])\n    if(qubit1_one):\n        circuit.x(quantum_register[qubit1])\n    if(qubit2_one):\n        circuit.x(quantum_register[qubit2])\n    circuit.reset(quantum_register[AND_gate_auxillary_qubit])\n\n'''\n    Applies the AND gate operation on a list of n qubits\n    @PARAMS:\n        qubit_list: list of qubits to perform the operation on\n        qubit_one_list: whether each of those qubits is NOT\n    @RETURN:\n        result of the n-qubit AND operation\n'''\ndef AND_n_qubits(qubit_list, qubit_one_list):\n    \n    length = len(qubit_list)\n    if(length != len(qubit_one_list)):\n        print(\"Incorrect dimensions\")\n        return\n    classical_register_index = 0 # where to store pairwise AND operation results\n\n    # handling odd number of qubits by preprocessing the last qubit\n    if(length % 2 != 0):\n        if(qubit_one_list[length - 1] == 1):\n            circuit.x(quantum_register[qubit_list[length-1]])\n        circuit.cx(quantum_register[qubit_list[length - 1]], quantum_register[AND_gate_auxillary_qubit])\n        circuit.measure(quantum_register[AND_gate_auxillary_qubit], classical_register[classical_register_index])\n        circuit.reset(quantum_register[AND_gate_auxillary_qubit])\n        classical_register_index = classical_register_index + 1\n        if(qubit_one_list[length - 1] == 1):\n            circuit.x(quantum_register[qubit_list[length-1]])\n        length = length - 1\n\n\n    for index in range(length - 1, 0, -2):\n        AND_2_qubit(qubit_list[index], qubit_list[index - 1], qubit_one_list[index], qubit_one_list[index - 1], classical_register_index)\n        classical_register_index = classical_register_index + 1\n    \n    job = qiskit.execute(circuit, simulator, shots=1)\n    result = job.result()\n    counts = str(result.get_counts())\n    counts = counts[counts.find('\\'') + 1:]\n    counts = counts[:counts.find('\\'')]\n    output = 1\n    for index in range(0, classical_register_index, 1):\n        output = output & int(counts[CLASSICAL_REGISTER_LENGTH - 1 - index])\n    \n    return output\n\ndef controlled_n_qubit_h(qubit_list, qubit_one_list):\n    output = AND_n_qubits(qubit_list, qubit_one_list)\n    if(output == 1):\n        circuit.h(quantum_register[AND_gate_auxillary_qubit])\n        circuit.measure(quantum_register[AND_gate_auxillary_qubit], classical_register[0])\n        circuit.reset(quantum_register[AND_gate_auxillary_qubit])\n        job = qiskit.execute(circuit, simulator, shots=1)\n        result = job.result()\n        counts = str(result.get_counts())\n        counts = counts[counts.find('\\'') + 1:]\n        counts = counts[:counts.find('\\'')]\n        return int(counts[len(counts) - 1])\n    return 0\n\n'''\n    the main circuit for the following truth table:\n    A, B, C, D = binary representation input state for the robot\n    P, Q, R, S = binary representation of the output state from the robot\n\n    New circuit in register...\n'''\n\ndef main_circuit(STEPS, initial_state):\n    signature = \"\"\n    state = initial_state\n    for _ in range(STEPS):\n\n        dont_care_list = constant_index_dictionary[state]\n        state = \"\"\n\n        P = controlled_n_qubit_h([0, 1, 3], [1, 1, 0]) | controlled_n_qubit_h([1, 2], [0, 1]) | controlled_n_qubit_h([0, 2, 3], [0, 0, 1]) | AND_n_qubits([1, 2, 3], [0, 0, 0]) | AND_n_qubits([0, 1, 3], [1, 1, 1]) | AND_n_qubits([1, 2, 3], [1, 1, 1])\n        \n        Q = controlled_n_qubit_h([0, 1, 2], [1, 0, 0]) | controlled_n_qubit_h([0, 1, 2], [1, 1, 1]) | controlled_n_qubit_h([0, 2, 3], [1, 1, 1]) | controlled_n_qubit_h([1, 2, 3], [1, 1, 1]) | controlled_n_qubit_h([0, 1, 2, 3], [0, 0, 1, 0]) | controlled_n_qubit_h([0, 1, 2, 3], [0, 1, 0, 0]) | AND_n_qubits([0, 1, 3], [0, 0, 1]) | AND_n_qubits([0, 1, 2, 3], [1, 1, 0, 1]) | AND_n_qubits([0, 1, 2, 3], [1, 0, 1, 0]) | AND_n_qubits([0, 1, 2, 3], [0, 1, 1, 0])\n\n        R = controlled_n_qubit_h([0, 1, 2], [1, 1, 0]) | controlled_n_qubit_h([0, 1, 2], [0, 0, 0]) | controlled_n_qubit_h([0, 1, 3], [0, 1, 0]) | controlled_n_qubit_h([0, 2, 3], [0, 1, 1]) | AND_n_qubits([0, 1], [1, 0]) | AND_n_qubits([0, 1, 2, 3], [0, 1, 0, 1])\n\n        S = controlled_n_qubit_h([1, 2, 3], [1, 0, 1]) | controlled_n_qubit_h([0, 1, 3], [1, 1, 1]) | controlled_n_qubit_h([0, 1, 3], [1, 0, 0]) | controlled_n_qubit_h([0, 1, 2], [1, 0, 0]) | controlled_n_qubit_h([1, 2, 3], [0, 0, 0]) |  AND_n_qubits([0, 1, 2], [0, 0, 1]) | AND_n_qubits([0, 1, 2, 3], [0, 1, 0, 0])\n\n\n        state = state + str(P) + str(Q) + str(R) + str(S)        \n        hidden_state = \"\"\n        for j in range(len(state)):\n            if(j in dont_care_list):\n              pass\n            else:\n              hidden_state = hidden_state + state[j]\n        \n        print(state + \" \" + hidden_state)\n        signature = signature + hidden_state\n\n        for _ in range(len(circuit.data)):\n          circuit.data.pop(0)\n\n        if(P == 1):\n            circuit.x(quantum_register[0])\n        \n        if(Q == 1):\n            circuit.x(quantum_register[1])\n\n        if(R == 1):\n            circuit.x(quantum_register[2])\n\n        if(S == 1):\n            circuit.x(quantum_register[3])\n\n    print(\"End state: \" + str(P) + str(Q) + str(R) + str(S) )\n    print(\"Signature: \" + signature)\n        \ndef initialise_starting_state(P, Q, R, S):\n    if(P == 1):\n      circuit.x(quantum_register[0])\n    if(Q == 1):\n      circuit.x(quantum_register[1])\n    if(R == 1):\n      circuit.x(quantum_register[2])\n    if(S == 1):\n      circuit.x(quantum_register[3])\n    print(\"Message: \" + str(P) + str(Q) + str(R) + str(S))\n\ndef measure_time():\n\n    total_time = 0\n    for i in range(100):\n        start_time = time.time()\n        # output = AND_n_qubits([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1])\n        output = controlled_n_qubit_h([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1])\n        \n        print(str(i) + \" \" + str(output))\n        end_time = time.time()\n        total_time = total_time + (end_time - start_time)\n    print(\"Average time: \" + str(total_time/100))\n\n\nstart_time = time.time()\ninitialise_starting_state(0, 1, 0, 1)       # message to be signed\nSTEPS = 10                                  # security parameter: length of the walk\nmain_circuit(STEPS, '0101') \n# measure_time()\nend_time = time.time()\nprint(\"Run in time \" + str(end_time - start_time))\nprint(circuit_building_end_time - circuit_building_start_time)\n```\n\n    Message: 0101\n    0110 00\n    0010 00\n    1101 01\n    1001 10\n    0100 00\n    0110 01\n    0010 00\n    1100 00\n    0101 00\n    0110 00\n    End state: 0110\n    Signature: 00000110000100000000\n    Run in time 2.812980890274048\n    0.0001819133758544922\n\n\n\n```\ndef recipient_initialise_starting_state(P, Q, R, S):\n    if(P == \"1\"):\n      circuit.x(quantum_register[0])\n    if(Q == \"1\"):\n      circuit.x(quantum_register[1])\n    if(R == \"1\"):\n      circuit.x(quantum_register[2])\n    if(S == \"1\"):\n      circuit.x(quantum_register[3])\n    print(\"Message: \" + str(P) + str(Q) + str(R) + str(S))\n\ndef recipient(message, signature, end_state):\n  \n  # for every 2 bits, there are 2 additional hidden bits, by definition of the shared data structures\n\n  STEPS = (2*len(signature))/len(end_state)\n  STEPS = int(STEPS)\n  index = 0\n  recipient_initialise_starting_state(message[0], message[1], message[2], message[3])\n  state = message\n  recreated_signature = \"\"\n  recreated_original_signature = \"\"\n  for _ in range(STEPS):\n\n        dont_care_list = constant_index_dictionary[state]\n        hidden_index_list = hidden_index_dictionary[state]\n        # print(state + \" \" + str(hidden_index_list))\n        state = \"\"\n        \n        P = controlled_n_qubit_h([0, 1, 3], [1, 1, 0]) | controlled_n_qubit_h([1, 2], [0, 1]) | controlled_n_qubit_h([0, 2, 3], [0, 0, 1]) | AND_n_qubits([1, 2, 3], [0, 0, 0]) | AND_n_qubits([0, 1, 3], [1, 1, 1]) | AND_n_qubits([1, 2, 3], [1, 1, 1])\n        \n        Q = controlled_n_qubit_h([0, 1, 2], [1, 0, 0]) | controlled_n_qubit_h([0, 1, 2], [1, 1, 1]) | controlled_n_qubit_h([0, 2, 3], [1, 1, 1]) | controlled_n_qubit_h([1, 2, 3], [1, 1, 1]) | controlled_n_qubit_h([0, 1, 2, 3], [0, 0, 1, 0]) | controlled_n_qubit_h([0, 1, 2, 3], [0, 1, 0, 0]) | AND_n_qubits([0, 1, 3], [0, 0, 1]) | AND_n_qubits([0, 1, 2, 3], [1, 1, 0, 1]) | AND_n_qubits([0, 1, 2, 3], [1, 0, 1, 0]) | AND_n_qubits([0, 1, 2, 3], [0, 1, 1, 0])\n\n        R = controlled_n_qubit_h([0, 1, 2], [1, 1, 0]) | controlled_n_qubit_h([0, 1, 2], [0, 0, 0]) | controlled_n_qubit_h([0, 1, 3], [0, 1, 0]) | controlled_n_qubit_h([0, 2, 3], [0, 1, 1]) | AND_n_qubits([0, 1], [1, 0]) | AND_n_qubits([0, 1, 2, 3], [0, 1, 0, 1])\n\n        S = controlled_n_qubit_h([1, 2, 3], [1, 0, 1]) | controlled_n_qubit_h([0, 1, 3], [1, 1, 1]) | controlled_n_qubit_h([0, 1, 3], [1, 0, 0]) | controlled_n_qubit_h([0, 1, 2], [1, 0, 0]) | controlled_n_qubit_h([1, 2, 3], [0, 0, 0]) |  AND_n_qubits([0, 1, 2], [0, 0, 1]) | AND_n_qubits([0, 1, 2, 3], [0, 1, 0, 0])\n\n\n        for i in range(len(hidden_index_list)):\n          temp_index = hidden_index_list[i]\n          if(temp_index == 0):\n            if(signature[index] == '1'):\n              P = P | 1\n            else:\n              P = P & 0\n          elif(temp_index == 1):\n            if(signature[index] == '1'):\n              Q = Q | 1\n            else:\n              Q = Q & 0\n          elif(temp_index == 2):\n            if(signature[index] == '1'):\n              R = R | 1\n            else:\n              R = R & 0\n          elif(temp_index == 3):\n            if(signature[index] == '1'):\n              S = S | 1\n            else:\n              S = S & 0\n          index = index + 1\n\n        state = \"\" + str(P) + str(Q) + str(R) + str(S)\n\n        hidden_state = \"\"\n        for j in range(len(state)):\n            if(j in dont_care_list):\n              # hidden_state = hidden_state + \"x\"\n              pass\n            else:\n              hidden_state = hidden_state + state[j]\n        \n        print(state + \" \" + hidden_state)\n        recreated_signature = recreated_signature + hidden_state\n\n        for _ in range(len(circuit.data)):\n          circuit.data.pop(0)\n\n        if(P == 1):\n            circuit.x(quantum_register[0])\n        \n        if(Q == 1):\n            circuit.x(quantum_register[1])\n\n        if(R == 1):\n            circuit.x(quantum_register[2])\n\n        if(S == 1):\n            circuit.x(quantum_register[3])\n\n  if(recreated_signature == signature and end_state == state):\n    print(\"ACCEPT\")\n  else:\n    print(\"REJECT\")\n```\n\n\n```\nstart = time.time()\n# for _ in range(len(circuit.data)):\n#   circuit.data.pop(0)\n# recipient(\"0101\", \"10011010111000010011\", \"1111\")\nfor _ in range(len(circuit.data)):\n  circuit.data.pop(0)\nrecipient(\"0101\", \"1000110000100000000\", \"0110\")\nprint(time.time() - start)\n```\n\n    Message: 0101\n    1110 10\n    0100 00\n    1110 11\n    0100 00\n    0010 00\n    1110 10\n    0100 00\n    0010 00\n    1100 00\n    REJECT\n    2.47572660446167\n\n\n# k-Path dependent scheme\n\n\n```\nconstant_index_dictionary = {}\nconstant_index_dictionary['0000'] = [0, 2]\nconstant_index_dictionary['0001'] = [2, 3]\nconstant_index_dictionary['0010'] = [0, 1]\nconstant_index_dictionary['0011'] = [1, 3]\nconstant_index_dictionary['0100'] = [2, 3]\nconstant_index_dictionary['0101'] = [1, 2]\nconstant_index_dictionary['0110'] = [0, 2]\nconstant_index_dictionary['0111'] = [0, 2]\nconstant_index_dictionary['1000'] = [0, 3]\nconstant_index_dictionary['1001'] = [0, 1]\nconstant_index_dictionary['1010'] = [1, 2]\nconstant_index_dictionary['1011'] = [0, 3]\nconstant_index_dictionary['1100'] = [1, 3]\nconstant_index_dictionary['1101'] = [2, 3]\nconstant_index_dictionary['1110'] = [1, 3]\nconstant_index_dictionary['1111'] = [0, 1]\n```\n\n\n```\nimport qiskit\nimport numpy as np\nimport time\n\nCLASSICAL_REGISTER_LENGTH  = 5\nQUANTUM_REGISTER_LENGTH  = 5\n\ncircuit_building_start_time = time.time()\nsimulator = qiskit.Aer.get_backend('qasm_simulator')\nclassical_register = qiskit.ClassicalRegister(CLASSICAL_REGISTER_LENGTH)\nquantum_register = qiskit.QuantumRegister(QUANTUM_REGISTER_LENGTH)\ncircuit = qiskit.QuantumCircuit(quantum_register, classical_register)\ncircuit_building_end_time = time.time()\n\n\nAND_gate_auxillary_qubit =  QUANTUM_REGISTER_LENGTH - 1 # last qubit as the auxillary qubit\n\n'''\n    Applies quantum AND operation to specified pair of qubits, stores the operation in AND_gate_auxillary_qubit,\n    and stores the result in a classical register\n    @PARAMS:\n        qubit1: position of the first qubit\n        qubit2: position of the second qubit\n        qubit1_one: whether the first qubit is NOT\n        qubit2_one: whether the second qubit is NOT\n        classical_register_position: the classical register position to store the measurement of AND_gate_auxillary_qubit\n'''\ndef AND_2_qubit(qubit1, qubit2, qubit1_one, qubit2_one, classical_register_position):\n    \n    if(qubit1_one):\n        circuit.x(quantum_register[qubit1])\n    if(qubit2_one):\n        circuit.x(quantum_register[qubit2])\n    circuit.ccx(quantum_register[qubit1], quantum_register[qubit2], quantum_register[AND_gate_auxillary_qubit])\n    circuit.measure(quantum_register[AND_gate_auxillary_qubit], classical_register[classical_register_position])\n    if(qubit1_one):\n        circuit.x(quantum_register[qubit1])\n    if(qubit2_one):\n        circuit.x(quantum_register[qubit2])\n    circuit.reset(quantum_register[AND_gate_auxillary_qubit])\n\n'''\n    Applies the AND gate operation on a list of n qubits\n    @PARAMS:\n        qubit_list: list of qubits to perform the operation on\n        qubit_one_list: whether each of those qubits is NOT\n    @RETURN:\n        result of the n-qubit AND operation\n'''\ndef AND_n_qubits(qubit_list, qubit_one_list):\n    \n    length = len(qubit_list)\n    if(length != len(qubit_one_list)):\n        print(\"Incorrect dimensions\")\n        return\n    classical_register_index = 0 # where to store pairwise AND operation results\n\n    # handling odd number of qubits by preprocessing the last qubit\n    if(length % 2 != 0):\n        if(qubit_one_list[length - 1] == 1):\n            circuit.x(quantum_register[qubit_list[length-1]])\n        circuit.cx(quantum_register[qubit_list[length - 1]], quantum_register[AND_gate_auxillary_qubit])\n        circuit.measure(quantum_register[AND_gate_auxillary_qubit], classical_register[classical_register_index])\n        circuit.reset(quantum_register[AND_gate_auxillary_qubit])\n        classical_register_index = classical_register_index + 1\n        if(qubit_one_list[length - 1] == 1):\n            circuit.x(quantum_register[qubit_list[length-1]])\n        length = length - 1\n\n\n    for index in range(length - 1, 0, -2):\n        AND_2_qubit(qubit_list[index], qubit_list[index - 1], qubit_one_list[index], qubit_one_list[index - 1], classical_register_index)\n        classical_register_index = classical_register_index + 1\n    \n    job = qiskit.execute(circuit, simulator, shots=1)\n    result = job.result()\n    counts = str(result.get_counts())\n    counts = counts[counts.find('\\'') + 1:]\n    counts = counts[:counts.find('\\'')]\n    output = 1\n    for index in range(0, classical_register_index, 1):\n        output = output & int(counts[CLASSICAL_REGISTER_LENGTH - 1 - index])\n    \n    return output\n\ndef controlled_n_qubit_h(qubit_list, qubit_one_list):\n    output = AND_n_qubits(qubit_list, qubit_one_list)\n    if(output == 1):\n        circuit.h(quantum_register[AND_gate_auxillary_qubit])\n        circuit.measure(quantum_register[AND_gate_auxillary_qubit], classical_register[0])\n        circuit.reset(quantum_register[AND_gate_auxillary_qubit])\n        job = qiskit.execute(circuit, simulator, shots=1)\n        result = job.result()\n        counts = str(result.get_counts())\n        counts = counts[counts.find('\\'') + 1:]\n        counts = counts[:counts.find('\\'')]\n        return int(counts[len(counts) - 1])\n    return 0\n\n'''\n    the main circuit for the following truth table:\n    A, B, C, D = binary representation input state for the robot\n    P, Q, R, S = binary representation of the output state from the robot\n\n    New circuit in register...\n'''\n\ndef main_circuit(STEPS, initial_state):\n    signature = \"\"\n    state = initial_state\n    used_states = []\n    step = 0\n    rollback_count = 0\n    while True:\n        if(step == STEPS):\n          break\n        dont_care_list = constant_index_dictionary[state]\n        rollback_state = state\n        if(state not in used_states):\n          used_states.append(state)\n        state = \"\"\n\n        P = controlled_n_qubit_h([0, 1, 3], [1, 1, 0]) | controlled_n_qubit_h([1, 2], [0, 1]) | controlled_n_qubit_h([0, 2, 3], [0, 0, 1]) | AND_n_qubits([1, 2, 3], [0, 0, 0]) | AND_n_qubits([0, 1, 3], [1, 1, 1]) | AND_n_qubits([1, 2, 3], [1, 1, 1])\n        \n        Q = controlled_n_qubit_h([0, 1, 2], [1, 0, 0]) | controlled_n_qubit_h([0, 1, 2], [1, 1, 1]) | controlled_n_qubit_h([0, 2, 3], [1, 1, 1]) | controlled_n_qubit_h([1, 2, 3], [1, 1, 1]) | controlled_n_qubit_h([0, 1, 2, 3], [0, 0, 1, 0]) | controlled_n_qubit_h([0, 1, 2, 3], [0, 1, 0, 0]) | AND_n_qubits([0, 1, 3], [0, 0, 1]) | AND_n_qubits([0, 1, 2, 3], [1, 1, 0, 1]) | AND_n_qubits([0, 1, 2, 3], [1, 0, 1, 0]) | AND_n_qubits([0, 1, 2, 3], [0, 1, 1, 0])\n\n        R = controlled_n_qubit_h([0, 1, 2], [1, 1, 0]) | controlled_n_qubit_h([0, 1, 2], [0, 0, 0]) | controlled_n_qubit_h([0, 1, 3], [0, 1, 0]) | controlled_n_qubit_h([0, 2, 3], [0, 1, 1]) | AND_n_qubits([0, 1], [1, 0]) | AND_n_qubits([0, 1, 2, 3], [0, 1, 0, 1])\n\n        S = controlled_n_qubit_h([1, 2, 3], [1, 0, 1]) | controlled_n_qubit_h([0, 1, 3], [1, 1, 1]) | controlled_n_qubit_h([0, 1, 3], [1, 0, 0]) | controlled_n_qubit_h([0, 1, 2], [1, 0, 0]) | controlled_n_qubit_h([1, 2, 3], [0, 0, 0]) |  AND_n_qubits([0, 1, 2], [0, 0, 1]) | AND_n_qubits([0, 1, 2, 3], [0, 1, 0, 0])\n\n        state = state + str(P) + str(Q) + str(R) + str(S)\n        if(state in used_states):\n          rollback_count = rollback_count + 1\n          if(rollback_count == (len(initial_state) + 10)):\n            print(\"Aborting.\")\n            return \"ABORT\"\n          P = rollback_state[0]\n          Q = rollback_state[1]\n          R = rollback_state[2]\n          S = rollback_state[3]\n          state = rollback_state\n          for _ in range(len(circuit.data)):\n            circuit.data.pop(0)\n\n          if(P == '1'):\n            print(\"Rollback reset\")\n            circuit.x(quantum_register[0])\n        \n          if(Q == '1'):\n            print(\"Rollback reset\")\n            circuit.x(quantum_register[1])\n\n          if(R == '1'):\n            print(\"Rollback reset\")\n            circuit.x(quantum_register[2])\n\n          if(S == '1'):\n            print(\"Rollback reset\")\n            circuit.x(quantum_register[3])\n          print(\"Rolling back\")\n          continue\n\n        step = step + 1        \n        rollback = 0\n        hidden_state = \"\"\n        for j in range(len(state)):\n            if(j in dont_care_list):\n              hidden_state = hidden_state + \"x\"\n            else:\n              hidden_state = hidden_state + state[j]\n        \n        signature = signature + hidden_state\n        # print(state + \" \" + hidden_state)\n        \n        for _ in range(len(circuit.data)):\n            circuit.data.pop(0)\n\n        if(P == 1):\n            circuit.x(quantum_register[0])\n        \n        if(Q == 1):\n            circuit.x(quantum_register[1])\n\n        if(R == 1):\n            circuit.x(quantum_register[2])\n\n        if(S == 1):\n            circuit.x(quantum_register[3])\n    return signature\n\n        \ndef initialise_starting_state(P, Q, R, S):\n    for _ in range(len(circuit.data)):\n      circuit.data.pop(0)\n    if(P == 1):\n      circuit.x(quantum_register[0])\n    if(Q == 1):\n      circuit.x(quantum_register[1])\n    if(R == 1):\n      circuit.x(quantum_register[2])\n    if(S == 1):\n      circuit.x(quantum_register[3])\n    print(\"Message: \" + str(P) + str(Q) + str(R) + str(S))\n\ndef measure_time():\n\n    total_time = 0\n    for i in range(100):\n        start_time = time.time()\n        # output = AND_n_qubits([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1])\n        output = controlled_n_qubit_h([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1])\n        \n        print(str(i) + \" \" + str(output))\n        end_time = time.time()\n        total_time = total_time + (end_time - start_time)\n    print(\"Average time: \" + str(total_time/100))\n\n\n```\n\nCreating a long message\n\n100 *bits*\n\n\n```\ndef create_random_message(NUMBER_OF_BITS):\n  message = \"\"\n  c = qiskit.ClassicalRegister(1)\n  q = qiskit.QuantumRegister(1)\n  s = qiskit.Aer.get_backend('qasm_simulator')\n\n  for i in range(NUMBER_OF_BITS):\n    print(i)\n    random_circuit = qiskit.QuantumCircuit(q, c)\n    random_circuit.h(q[0])\n    random_circuit.measure(q[0], c[0])\n\n\n    job = qiskit.execute(random_circuit, s, shots=1)\n    result = job.result()\n    counts = str(result.get_counts())\n    counts = counts[counts.find('\\'') + 1:]\n    counts = counts[:counts.find('\\'')]\n    message = message + counts\n\n  print(message)\n\n\ncreate_random_message(100)\n```\n\n    0\n    1\n    2\n    3\n    4\n    5\n    6\n    7\n    8\n    9\n    10\n    11\n    12\n    13\n    14\n    15\n    16\n    17\n    18\n    19\n    20\n    21\n    22\n    23\n    24\n    25\n    26\n    27\n    28\n    29\n    30\n    31\n    32\n    33\n    34\n    35\n    36\n    37\n    38\n    39\n    40\n    41\n    42\n    43\n    44\n    45\n    46\n    47\n    48\n    49\n    50\n    51\n    52\n    53\n    54\n    55\n    56\n    57\n    58\n    59\n    60\n    61\n    62\n    63\n    64\n    65\n    66\n    67\n    68\n    69\n    70\n    71\n    72\n    73\n    74\n    75\n    76\n    77\n    78\n    79\n    80\n    81\n    82\n    83\n    84\n    85\n    86\n    87\n    88\n    89\n    90\n    91\n    92\n    93\n    94\n    95\n    96\n    97\n    98\n    99\n    1011000001011010110011111011011100111001000010001111011101101100010100100011010010111000110101100011\n\n\nSigning a long message\n\n\n```\ndef sign_message(message):\n  signature = \"\"\n  ITER = int(len(message)/4)\n  start_time = time.time()\n  STEPS = 5                                  # security parameter: length of the walk\n  iter = 0\n  while True:\n    if(iter == ITER):\n      break\n    state = message[0:4]\n    initialise_starting_state(int(state[0]), int(state[1]), int(state[2]), int(state[3]))\n    return_signature = main_circuit(STEPS, state) \n    if(return_signature == \"ABORT\"):\n      print(\"Rerun\")\n      continue\n    iter = iter + 1\n    signature = signature + return_signature\n    message = message[4:]\n  end_time = time.time()\n  print(\"Run in time \" + str(end_time - start_time))\n  \n  print(signature)\n\nsign_message('1011000001011010110011111011011100111001000010001111011101101100010100100011010010111000110101100011')\n```\n\n    Message: 1011\n    Rollback reset\n    Rollback reset\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Message: 0000\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Message: 0101\n    Message: 1010\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rolling back\n    Message: 1100\n    Rollback reset\n    Rolling back\n    Message: 1111\n    Rollback reset\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Message: 1011\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Message: 0111\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Message: 0011\n    Rollback reset\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Message: 1001\n    Message: 0000\n    Rollback reset\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Message: 1000\n    Message: 1111\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Message: 0111\n    Message: 0110\n    Message: 1100\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Message: 0101\n    Message: 0010\n    Rollback reset\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Message: 0011\n    Rollback reset\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Message: 0100\n    Message: 1011\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Message: 1000\n    Message: 1101\n    Message: 0110\n    Rollback reset\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rolling back\n    Rollback reset\n    Rollback reset\n    Rolling back\n    Message: 0011\n    Run in time 74.02919340133667\n    x11xx1x1xx01xx10x0x1x1x01x0x10xxxx10x1x10xx1x1x1xx11x00x00xx0xx0xx11xx00x10x1x0x0x0x1xx1xx00x11x0x0xxx11x11xx1x00x1xx0x1x01x1x0xx01x0xx0xx01x1x1xx00x10x0x0x1xx00x0xx1x101xx0xx0x1x1xx10x1x1x0x1x01x1x0xx1x101xx1xx1xx00x10xx01x1xx1x10x0xx0x0x0xx01xx10x1x1x0x1x00xx0x01xx1x00x11xx1x1xx0x10x0xx1x01x0x10xx1x1xxx00x01x0xx10x1x1xx00x1xx0x10x1xxx11xx0100xx10xxx11x0x0x0x1xxx101x0x1x1xxx0010xx0xx10x1xxx11xx01x10x0xx0x0x0xx0110xxx01x0xx10x0xx0x1xx0000xx10xxx11x0x1xx1x1x0x0xx100x0x10xx0xx10x1xxx100x1xx1x1x1x1\n\n\n\n```\nprint(len('x00x10xxx10x1x1xxx01'))\n```\n\n    20\n\n\n\n```\ndef recipient_initialise_starting_state(P, Q, R, S):\n    for _ in range(len(circuit.data)):\n      circuit.data.pop(0)\n    if(P == \"1\"):\n      circuit.x(quantum_register[0])\n    if(Q == \"1\"):\n      circuit.x(quantum_register[1])\n    if(R == \"1\"):\n      circuit.x(quantum_register[2])\n    if(S == \"1\"):\n      circuit.x(quantum_register[3])\n    print(\"Message: \" + str(P) + str(Q) + str(R) + str(S))\n\ndef recipient(message, signature, end_state):\n  STEPS = len(signature)/len(end_state)\n  STEPS = int(STEPS)\n  index = 0\n  recipient_initialise_starting_state(message[0], message[1], message[2], message[3])\n  state = message\n  recreated_signature = \"\"\n  for _ in range(STEPS):\n\n        dont_care_list = constant_index_dictionary[state]\n        state = \"\"\n        \n        P = controlled_n_qubit_h([0, 1, 3], [1, 1, 0]) | controlled_n_qubit_h([1, 2], [0, 1]) | controlled_n_qubit_h([0, 2, 3], [0, 0, 1]) | AND_n_qubits([1, 2, 3], [0, 0, 0]) | AND_n_qubits([0, 1, 3], [1, 1, 1]) | AND_n_qubits([1, 2, 3], [1, 1, 1])\n        \n        Q = controlled_n_qubit_h([0, 1, 2], [1, 0, 0]) | controlled_n_qubit_h([0, 1, 2], [1, 1, 1]) | controlled_n_qubit_h([0, 2, 3], [1, 1, 1]) | controlled_n_qubit_h([1, 2, 3], [1, 1, 1]) | controlled_n_qubit_h([0, 1, 2, 3], [0, 0, 1, 0]) | controlled_n_qubit_h([0, 1, 2, 3], [0, 1, 0, 0]) | AND_n_qubits([0, 1, 3], [0, 0, 1]) | AND_n_qubits([0, 1, 2, 3], [1, 1, 0, 1]) | AND_n_qubits([0, 1, 2, 3], [1, 0, 1, 0]) | AND_n_qubits([0, 1, 2, 3], [0, 1, 1, 0])\n\n        R = controlled_n_qubit_h([0, 1, 2], [1, 1, 0]) | controlled_n_qubit_h([0, 1, 2], [0, 0, 0]) | controlled_n_qubit_h([0, 1, 3], [0, 1, 0]) | controlled_n_qubit_h([0, 2, 3], [0, 1, 1]) | AND_n_qubits([0, 1], [1, 0]) | AND_n_qubits([0, 1, 2, 3], [0, 1, 0, 1])\n\n        S = controlled_n_qubit_h([1, 2, 3], [1, 0, 1]) | controlled_n_qubit_h([0, 1, 3], [1, 1, 1]) | controlled_n_qubit_h([0, 1, 3], [1, 0, 0]) | controlled_n_qubit_h([0, 1, 2], [1, 0, 0]) | controlled_n_qubit_h([1, 2, 3], [0, 0, 0]) |  AND_n_qubits([0, 1, 2], [0, 0, 1]) | AND_n_qubits([0, 1, 2, 3], [0, 1, 0, 0])\n\n\n        if(signature[index] != \"x\" and signature[index] == \"1\"):\n          P = P | 1\n        elif(signature[index] != \"x\"):\n          P = P & 0\n        \n        index = index + 1\n\n        if(signature[index] != \"x\" and signature[index] == \"1\"):\n          Q = Q | 1\n        elif(signature[index] != \"x\"):\n          Q = Q & 0\n        \n        index = index + 1\n\n        if(signature[index] != \"x\" and signature[index] == \"1\"):\n          R = R | 1\n        elif(signature[index] != \"x\"):\n          R = R & 0\n\n        index = index + 1\n\n        if(signature[index] != \"x\" and signature[index] == \"1\"):\n          S = S | 1\n        elif(signature[index] != \"x\"):\n          S = S & 0\n\n        index = index + 1\n\n        state = \"\" + str(P) + str(Q) + str(R) + str(S)\n\n        hidden_state = \"\"\n        for j in range(len(state)):\n            if(j in dont_care_list):\n              hidden_state = hidden_state + \"x\"\n            else:\n              hidden_state = hidden_state + state[j]\n        \n        recreated_signature = recreated_signature + hidden_state\n        print(state + \" \" + hidden_state)\n        for _ in range(len(circuit.data)):\n          circuit.data.pop(0)\n\n        if(P == 1):\n            circuit.x(quantum_register[0])\n        \n        if(Q == 1):\n            circuit.x(quantum_register[1])\n\n        if(R == 1):\n            circuit.x(quantum_register[2])\n\n        if(S == 1):\n            circuit.x(quantum_register[3])\n  print(recreated_signature)\n  print(signature)\n  if(recreated_signature == signature):\n    print(\"ACCEPT\")\n  else:\n    print(\"REJECT\")\n  return recreated_signature\n\n```\n\n\n```\nimport time\nstart = time.time()\nfor _ in range(len(circuit.data)):\n  circuit.data.pop(0)\nSTEPS = int(len('1011000001011010110011111011011100111001000010001111011101101100010100100011010010111000110101100011') / 4)\nmessage = '1011000001011010110011111011011100111001000010001111011101101100010100100011010010111000110101100011'\nsignature = 'x11xx1x1xx01xx10x0x1x1x01x0x10xxxx10x1x10xx1x1x1xx11x00x00xx0xx0xx11xx00x10x1x0x0x0x1xx1xx00x11x0x0xxx11x11xx1x00x1xx0x1x01x1x0xx01x0xx0xx01x1x1xx00x10x0x0x1xx00x0xx1x101xx0xx0x1x1xx10x1x1x0x1x01x1x0xx1x101xx1xx1xx00x10xx01x1xx1x10x0xx0x0x0xx01xx10x1x1x0x1x00xx0x01xx1x00x11xx1x1xx0x10x0xx1x01x0x10xx1x1xxx00x01x0xx10x1x1xx00x1xx0x10x1xxx11xx0100xx10xxx11x0x0x0x1xxx101x0x1x1xxx0010xx0xx10x1xxx11xx01x10x0xx0x0x0xx0110xxx01x0xx10x0xx0x1xx0000xx10xxx11x0x1xx1x1x0x0xx100x0x10xx0xx10x1xxx100x1xx1x1x1x1'\ntemp_signature = signature\nk = int(len(signature)/len(message))\nend_index = k*4\nrecipient_signature = \"\"\nfor _ in range(STEPS):\n  start_state = message[0:4]\n  message = message[4:]\n  mess_signature = signature[0:end_index]\n  signature = signature[end_index:]\n  recipient_signature = recipient_signature + recipient(start_state, mess_signature, '0000')\n\n\nif(recipient_signature == temp_signature):\n  print(\"ACCEPT\")\nelse:\n  print(\"REJECT\")\nprint(time.time() - start)\n```\n\n\n```\n1111 1xx1 1111 1xx1\n1011 xx11 1011 xx11\nRolling back\n1101 x10x 0101 x10x\n0001 00xx 0010 0xx0\n1000 10xx 1010 xx10\n\n\n\n\n\n\n```\n\n\n\n\n<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">      \u250c\u2500\u2500\u2500\u2510\nq5_0: \u2524 X \u251c\n      \u2514\u2500\u2500\u2500\u2518\nq5_1: \u2500\u2500\u2500\u2500\u2500\n      \u250c\u2500\u2500\u2500\u2510\nq5_2: \u2524 X \u251c\n      \u251c\u2500\u2500\u2500\u2524\nq5_3: \u2524 X \u251c\n      \u2514\u2500\u2500\u2500\u2518\nq5_4: \u2500\u2500\u2500\u2500\u2500\n\nc5_0: \u2550\u2550\u2550\u2550\u2550\n\nc5_1: \u2550\u2550\u2550\u2550\u2550\n\nc5_2: \u2550\u2550\u2550\u2550\u2550\n\nc5_3: \u2550\u2550\u2550\u2550\u2550\n\nc5_4: \u2550\u2550\u2550\u2550\u2550\n           </pre>\n\n\n\n\n```\nprint(recipient('1011', 'x11xxx01xx10x0x0xx0100xx11xx1x1xxx11x11x', '0000'))\nprint(recipient('1001', 'xx001x1xxx01xx0011xx1x0x0x1xx1x1xx100xx0', '0000'))\n```\n\n    Message: 1011\n    x11x0x0x1xx00x1xxx0100xx11xx1x1xxx11x11x\n    x11xxx01xx10x0x0xx0100xx11xx1x1xxx11x11x\n    REJECT\n    x11x0x0x1xx00x1xxx0100xx11xx1x1xxx11x11x\n    Message: 1001\n    xx00x11x0x0x0xx011xx1x0x0x1xx1x1xx100xx0\n    xx001x1xxx01xx0011xx1x0x0x1xx1x1xx100xx0\n    REJECT\n    xx00x11x0x0x0xx011xx1x0x0x1xx1x1xx100xx0\n\n\n\n```\n\n```\n", "meta": {"hexsha": "d0d9ed7621927798c2b396589e4223d042e2e209", "size": 104511, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Quantum Cryptography/Quantum_inspired_digital_signatures.ipynb", "max_stars_repo_name": "NimishMishra/research", "max_stars_repo_head_hexsha": "2448fc9da643429117b851cb582d490cfe46d422", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-06-21T07:22:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T16:51:20.000Z", "max_issues_repo_path": "Quantum Cryptography/Quantum_inspired_digital_signatures.ipynb", "max_issues_repo_name": "NimishMishra/research", "max_issues_repo_head_hexsha": "2448fc9da643429117b851cb582d490cfe46d422", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-12-30T18:06:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-30T18:06:26.000Z", "max_forks_repo_path": "Quantum Cryptography/Quantum_inspired_digital_signatures.ipynb", "max_forks_repo_name": "NimishMishra/research", "max_forks_repo_head_hexsha": "2448fc9da643429117b851cb582d490cfe46d422", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.366746988, "max_line_length": 5602, "alphanum_fraction": 0.5119556793, "converted": true, "num_tokens": 19881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16238002045272698, "lm_q2_score": 0.06278920289730223, "lm_q1q2_score": 0.010195712050674361}}
{"text": "```python\n# code for loading the format for the notebook\nimport os\n\n# path : store the current path to convert back to it later\npath = os.getcwd()\nos.chdir(os.path.join('..', 'notebook_format'))\nfrom formats import load_style\nload_style(plot_style = False)\n```\n\n\n\n\n<style>\n@import url('http://fonts.googleapis.com/css?family=Source+Code+Pro');\n@import url('http://fonts.googleapis.com/css?family=Vollkorn');\n@import url('http://fonts.googleapis.com/css?family=Arimo');\n@import url('http://fonts.googleapis.com/css?family=Fira_sans');\n\n    div.cell {\n        width: 1000px;\n        margin-left: 0% !important;\n        margin-right: auto;\n    }\n    div.text_cell code {\n        background: transparent;\n        color: #000000;\n        font-weight: 600;\n        font-size: 12pt;\n        font-style: bold;\n        font-family:  'Source Code Pro', Consolas, monocco, monospace;\n    }\n    h1 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n\t}\n\n    div.input_area {\n        background: #F6F6F9;\n        border: 1px solid #586e75;\n    }\n\n    .text_cell_render h1 {\n        font-weight: 200;\n        font-size: 30pt;\n        line-height: 100%;\n        color:#c76c0c;\n        margin-bottom: 0.5em;\n        margin-top: 1em;\n        display: block;\n        white-space: wrap;\n        text-align: left;\n    } \n    h2 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n        text-align: left;\n    }\n    .text_cell_render h2 {\n        font-weight: 200;\n        font-size: 16pt;\n        font-style: italic;\n        line-height: 100%;\n        color:#c76c0c;\n        margin-bottom: 0.5em;\n        margin-top: 1.5em;\n        display: block;\n        white-space: wrap;\n        text-align: left;\n    } \n    h3 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n    }\n    .text_cell_render h3 {\n        font-weight: 200;\n        font-size: 14pt;\n        line-height: 100%;\n        color:#d77c0c;\n        margin-bottom: 0.5em;\n        margin-top: 2em;\n        display: block;\n        white-space: wrap;\n        text-align: left;\n    }\n    h4 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n    }\n    .text_cell_render h4 {\n        font-weight: 100;\n        font-size: 14pt;\n        color:#d77c0c;\n        margin-bottom: 0.5em;\n        margin-top: 0.5em;\n        display: block;\n        white-space: nowrap;\n    }\n    h5 {\n        font-family: 'Open sans',verdana,arial,sans-serif;\n    }\n    .text_cell_render h5 {\n        font-weight: 200;\n        font-style: normal;\n        color: #1d3b84;\n        font-size: 16pt;\n        margin-bottom: 0em;\n        margin-top: 0.5em;\n        display: block;\n        white-space: nowrap;\n    }\n    div.text_cell_render{\n        font-family: 'Fira sans', verdana,arial,sans-serif;\n        line-height: 125%;\n        font-size: 115%;\n        text-align:justify;\n        text-justify:inter-word;\n    }\n    div.output_wrapper{\n        margin-top:0.2em;\n        margin-bottom:0.2em;\n    }\n\n    code{\n      font-size: 70%;\n    }\n    .rendered_html code{\n    background-color: transparent;\n    }\n    ul{\n        margin: 2em;\n    }\n    ul li{\n        padding-left: 0.5em; \n        margin-bottom: 0.5em; \n        margin-top: 0.5em; \n    }\n    ul li li{\n        padding-left: 0.2em; \n        margin-bottom: 0.2em; \n        margin-top: 0.2em; \n    }\n    ol{\n        margin: 2em;\n    }\n    ol li{\n        padding-left: 0.5em; \n        margin-bottom: 0.5em; \n        margin-top: 0.5em; \n    }\n    ul li{\n        padding-left: 0.5em; \n        margin-bottom: 0.5em; \n        margin-top: 0.2em; \n    }\n    a:link{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:visited{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:hover{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:focus{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:active{\n       font-weight: bold;\n       color:#447adb;\n    }\n    .rendered_html :link {\n       text-decoration: underline; \n    }\n    .rendered_html :hover {\n       text-decoration: none; \n    }\n    .rendered_html :visited {\n      text-decoration: none;\n    }\n    .rendered_html :focus {\n      text-decoration: none;\n    }\n    .rendered_html :active {\n      text-decoration: none;\n    }\n    .warning{\n        color: rgb( 240, 20, 20 )\n    } \n    hr {\n      color: #f3f3f3;\n      background-color: #f3f3f3;\n      height: 1px;\n    }\n    blockquote{\n      display:block;\n      background: #fcfcfc;\n      border-left: 5px solid #c76c0c;\n      font-family: 'Open sans',verdana,arial,sans-serif;\n      width:680px;\n      padding: 10px 10px 10px 10px;\n      text-align:justify;\n      text-justify:inter-word;\n      }\n      blockquote p {\n        margin-bottom: 0;\n        line-height: 125%;\n        font-size: 100%;\n      }\n</style>\n\n\n\n\n\n\n```python\nos.chdir(path)\n\n# 1. magic for inline plot\n# 2. magic to print version\n# 3. magic so that the notebook will reload external python modules\n# 4. a ipython magic to enable retina (high resolution) plots\n# https://gist.github.com/minrk/3301035\n%matplotlib inline\n%load_ext watermark\n%load_ext autoreload\n%autoreload 2\n%config InlineBackend.figure_format = 'retina'\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport scipy.stats as stats\nimport matplotlib.pyplot as plt\nfrom statsmodels.stats.proportion import proportions_ztest\nfrom statsmodels.stats.proportion import proportions_chisquare\n\n%watermark -a 'Ethen' -d -t -v -p numpy,scipy,pandas,matplotlib,statsmodels\n```\n\n    Ethen 2017-08-09 15:45:01 \n    \n    CPython 3.5.2\n    IPython 5.4.1\n    \n    numpy 1.13.1\n    scipy 0.19.1\n    pandas 0.20.2\n    matplotlib 2.0.2\n    statsmodels 0.8.0\n\n\n\n```python\n# setup the look and feel of the notebook\nplt.rcParams['figure.figsize'] = 8, 6\nsns.set_context('notebook', font_scale = 1.5, rc = {'lines.linewidth': 2.5})\nsns.set_style('whitegrid')\nsns.set_palette('deep')\n\n# Create a couple of colors to use throughout the notebook\nred = sns.xkcd_rgb['vermillion']\nblue = sns.xkcd_rgb['dark sky blue']\n```\n\nIdeally, the reader should already understand or vaguely remember the statistic concepts such as z-score, p-value, hypothesis test, confidence interval. The warming-up section is a quick review of the concept, feel free to skip it if you're already acquainted with the concept.\n\n# Warming-up\n\nStatistical inference is the process of analyzing sample data to gain insight into the population from which the data was collected and to investigate differences between data samples. In data analysis, we are often interested in the characteristics of some large population, but collecting data on the entire population may be infeasible. For example, leading up to U.S. presidential elections it could be very useful to know the political leanings of every single eligible voter, but surveying every voter is not feasible. Instead, we could poll some subset of the population, such as a thousand registered voters, and use that data to make inferences about the population as a whole.\n\n## Point Estimate\n\nPoint estimates are estimates of population parameters based on sample data. For instance, if we wanted to know the average age of registered voters in the U.S., we could take a survey of registered voters and then use the average age of the respondents as a point estimate of the average age of the population as a whole. The average of a sample is known as the sample mean.\nThe sample mean is usually not exactly the same as the population mean. This difference can be caused by many factors including poor survey design, biased sampling methods and the randomness inherent to drawing a sample from a population. Let's investigate point estimates by generating a population of random age data and then drawing a sample from it to estimate the mean:\n\n\n```python\n# generate some random number to serve as our population\nnp.random.seed(10)\npopulation_ages1 = stats.poisson.rvs(loc = 18, mu = 35, size = 150000)\npopulation_ages2 = stats.poisson.rvs(loc = 18, mu = 10, size = 100000)\npopulation_ages = np.concatenate((population_ages1, population_ages2))\nprint('population mean:', np.mean(population_ages))\n```\n\n    population mean: 43.002372\n\n\n\n```python\nnp.random.seed(6)\nsample_ages = np.random.choice(population_ages, size = 500)\nprint('sample mean:', np.mean(sample_ages))\n```\n\n    sample mean: 42.388\n\n\nThe experiment tells us that we'd expect the distribution of the population to be a similar shape to that of the sample, so we can assume that the mean of the sample and the population should have the same value. Note that we can't say that they exactly match, but it's the best estimate we can make.\n\nThe population mean is often denoted as $\\mu$, the estimated population mean as $\\hat{\\mu}$, mean of the sample $\\bar{x}$. So here we're basically saying $\\hat{\\mu} = \\bar{x}$, where we're using the sample mean to estimate the mean of the population and usually the larger the size of our sample, the more accurate our point estimator for the estimated population mean is going to be.\n\n\n## Sampling Distributions and The Central Limit Theorem\n\nMany statistical procedures assume that data follows a normal distribution, because the normal distribution has nice properties like symmetricity and having the majority of the data clustered within a few standard deviations of the mean. Unfortunately, real world data is often not normally distributed and the distribution of a sample tends to mirror the distribution of the population. This means a sample taken from a population with a skewed distribution will also tend to be skewed.\n\n\n```python\nfig = plt.figure(figsize = (12, 6))\nplt.subplot(1, 2, 1)\nplt.hist(population_ages)\nplt.title('Population')\nplt.subplot(1, 2, 2)\nplt.hist(sample_ages)\nplt.title('Sample')\nplt.show()\n```\n\nThe plot reveals the data is clearly not normal: instead of one symmetric bell curve, it has as bimodal distribution with two high density peaks. Because of this, the sample we drew from this population should have roughly the same shape and skew.\n\nThe sample has roughly the same shape as the underlying population. This suggests that we can't apply techniques that assume a normal distribution to this data set, since it is not normal. This leads to our next topic, the **central limit theorem**.\n\nThe central limit theorem is one of the most important results of probability theory and serves as the foundation of many methods of statistical analysis. At a high level, the theorem states the distribution of many sample means, known as a sampling distribution, will be normally distributed. This rule holds even if the underlying distribution itself is not normally distributed. As a result we can treat the sample mean as if it were drawn normal distribution. To illustrate, let's create a sampling distribution by taking 200 samples from our population and then making 200 point estimates of the mean:\n\n\n```python\nnp.random.seed(10)\nsamples = 200\npoint_estimates = [np.random.choice(population_ages, size = 500).mean()\n                   for _ in range(samples)]\n\nplt.hist(point_estimates)\nplt.show()\n```\n\nThe sampling distribution appears to be roughly normal, despite the bimodal population distribution that the samples were drawn from. In addition, the mean of the sampling distribution approaches the true population mean:\n\n\n```python\npopulation_ages.mean() - np.mean(point_estimates)\n```\n\n\n\n\n    -0.084407999999996264\n\n\n\nTo hit the notion home, Central Limit Theorem states that that if we collect \"a large number\" of different samples mean from the population, the sampling distribution, the distribution of the samples mean you collected, will approximately take the shape of a normal distribution around the population mean no matter what the orginal population distribution is.\n\nKnowing that the sampling distribution will take the shape of a normal distribution is what makes the theorem so powerful, as it is the foundation of concepts such as confidence intervals and margins of error in frequentist statistics.\n\n## Confidence Interval\n\nA point estimate can give us a rough idea of a population parameter like the mean, but estimates are prone to error. A confidence interval is a range of values above and below a point estimate that captures the true population parameter at some predetermined confidence level. For example, if you want to have a 95% chance of capturing the true population parameter with a point estimate and a corresponding confidence interval, we'd set our confidence level to 95%. Higher confidence levels result in a wider confidence intervals.\n\nThe interval is computed using the formula: \n\n$$\\text{point estimate} \\pm z * SE$$\n\nWhere\n\n- $z$ is called the **critical value** and it corresponds to the **confidence level** that we chose. Critical value is the number of standard deviations we'd have to go from the mean of the normal distribution to capture the proportion of the data associated with the desired confidence level. For instance, we know that roughly 95% of the data in a normal distribution lies within 2 standard deviations from the mean, so we could use 2 as the z-critical value for a 95% confidence interval (although it is more exact to get z-critical values with `stats.norm.ppf()`)\n- $SE$ represents the **standard error**. Generally the standard error for a point estimate is estimated from the data and computed using a formula. For example, the standard error for the sample mean is $\\frac{s}{ \\sqrt{n} }$, where $s$ is the standard deviation and $n$ is the number of samples.\n- The value $z * SE$ is called the **margin of error**.\n- Note that this constructing confidence intervals framework holds true for doing can be easily adapted for any estimator that has a nearly normal sampling distribution. e.g. sample mean, two sample mean, sample proportion and two sample proportion (we'll later see). All we have to do this is change the way that we're calculating the standard error.\n\n\n```python\nnp.random.seed(10)\nsample_size = 1000\nsample = np.random.choice(population_ages, size = sample_size)\nsample_mean = sample.mean()\n\nconfidence = 0.95\nz_critical = stats.norm.ppf(q = confidence + (1 - confidence) / 2)\nprint('z-critical value:', z_critical)                     \n\npop_stdev = population_ages.std()\nmargin_of_error = z_critical * (pop_stdev / np.sqrt(sample_size))\nconfint = sample_mean - margin_of_error, sample_mean + margin_of_error\nprint('point esimate:', sample_mean)\nprint('Confidence interval:', confint)\n```\n\n    z-critical value: 1.95996398454\n    point esimate: 42.523\n    Confidence interval: (41.703064068826833, 43.342935931173173)\n\n\nNotice that the confidence interval we calculated captures the true population mean of 43.0023.\nLet's create several confidence intervals and plot them to get a better sense of what it means to \"capture\" the true mean:\n\n\n```python\nnp.random.seed(12)\nconfidence = 0.95\nsample_size = 1000\n\nintervals = []\nsample_means = []\nfor sample in range(25):\n    sample = np.random.choice(population_ages, size = sample_size)\n    sample_mean = sample.mean()\n    sample_means.append(sample_mean)\n\n    z_critical = stats.norm.ppf(q = confidence + (1 - confidence) / 2)                    \n    pop_stdev = population_ages.std()\n    margin_of_error = z_critical * (pop_stdev / np.sqrt(sample_size))\n    confint = sample_mean - margin_of_error, sample_mean + margin_of_error \n    intervals.append(confint)\n    \n\nplt.figure(figsize = (10, 8))\nplt.errorbar(x = np.arange(0.1, 25, 1), y = sample_means, \n             yerr = [(top - bot) / 2 for top, bot in intervals], fmt = 'o')\n\nplt.hlines(xmin = 0, xmax = 25,\n           y = population_ages.mean(), \n           linewidth = 2.0, color = red)\nplt.show()\n```\n\nNotice that in the plot above, all but one of the 95% confidence intervals overlap the red line marking the true mean. This is to be expected: since a 95% confidence interval captures the true mean 95% of the time, we'd expect our interval to miss the true mean 5% of the time.\n\nMore formally, the definition of a 95% confidence interval means that **95% of confidence intervals, created based on random samples of the same size from the same population will contain the true population parameter**.\n\n##  Hypothesis Testing\n\nLets starts off with a motivating example that asks the question \"If you toss a coin 30 times and see 22 heads, is it a fair coin?\"\n\nWe all know that a fair coin should come up heads roughly 15 out of 30 tosses, give or take, so it does seem unlikely to see so many heads. However, the skeptic might argue that even a fair coin could show 22 heads in 30 tosses from time-to-time. This could just be a chance event. So, the question would then be \"how can you determine if we're tossing a fair coin?\"\n\nLet's start by first considering the probability of a single coin flip coming up heads and work our way up to 22 out of 30.\n\n\\begin{align}\nP(H) = \\frac{1}{2}\n\\end{align}\n\nAs our equation shows, the probability of a single coin toss turning up heads is exactly 50% since there is an equal chance of either heads or tails turning up. Taking this one step further, to determine the probability of getting 2 heads in a row with 2 coin tosses, we would need to multiply the probability of getting heads by the probability of getting heads again since the two events are independent of one another.\n\n\\begin{align}\nP(HH) = P(H) \\cdot P(H) = P(H)^2 = \\left(\\frac{1}{2}\\right)^2 = \\frac{1}{4}\n\\end{align}\n\nLet's now take a look at a slightly different scenario and calculate the probability of getting 2 heads and 1 tails with 3 coin tosses. To get the actual probability of tossing 2 heads and 1 tails we will have to add the probabilities for all of the possible permutations, of which there are exactly three: HHT, HTH, and THH.\n\n\\begin{align}\nP(2H,1T) = P(HHT) + P(HTH) + P(THH) = \\frac{1}{8} + \\frac{1}{8} + \\frac{1}{8} = \\frac{3}{8}\n\\end{align}\n\nAnother way we could do this is to use the binomial distribution:\n\n\\begin{align}\nP(N_H,N_T) = \\binom{n}{k} p^{k} \\left( 1 - p \\right)^{n - k}\n\\end{align}\n\nWhere \n\n- $n$ is number of coin flips\n- $p$ is the probability of getting heads on each flip\n\nThe $\\binom{n}{k}$ tells us how many ways are there to get $k$ heads our of $n$ total number of coin flips?\" and the $p^k(1-p)^{n-k}$ answers the question \"how likely is any given $k$ heads and $n-k$ tails?\", multiply them together and we get the probability of getting exactly $k$ heads.\n\nNow that we understand the classic method, let's use it to test whether we are actually tossing a fair coin.\n\n\n```python\n# Calculate the probability for every possible outcome\n# of tossing a fair coin 30 k_range\n\nk_range = range(1, 31)  # number of heads appearing\nn = 30  # number of k_range tossing the coin\np = 0.5  # probability of coin appearing up as head\n\nprob = stats.binom(n = n, p = p).pmf(k = k_range)\n\n# Plot the probability distribution using the probabilities list \n# we created above.\nplt.step(k_range, prob, where = 'mid', color = blue)\nplt.xlabel('Number of heads')\nplt.ylabel('Probability')\nplt.plot((22, 22), (0, 0.1599), color = red)\nplt.annotate('0.8%', xytext = (25, 0.08), xy = (22, 0.08), \n             va = 'center', color = red, size = 'large',\n             arrowprops = {'arrowstyle': '<|-', 'lw': 2,\n                           'color': red, 'shrinkA': 10})\nplt.show()\n```\n\nThe visualization above shows the probability distribution for flipping a fair coin 30 times. Using this visualization we can now determine the probability of getting, say for example, 12 heads in 30 flips, which looks to be about 8%. Notice that we've labeled our example of 22 heads as 0.8%. If we look at the probability of flipping exactly 22 heads, it looks likes to be a little less than 0.8%, in fact if we calculate it using the function from above, we get 0.5%.\n\n\n```python\nprob = stats.binom(n = n, p = p).pmf(k = 22)\nprint('Probability of flipping 22 heads: {:0.1f}%'.format(prob * 100))\n```\n\n    Probability of flipping 22 heads: 0.5%\n\n\nSo, then why do we have 0.8% labeled in our probability distribution above? Well, that's because we are showing the probability of getting at least 22 heads, which is also known as the **p-value**.\n\nLet's pull back from our example and discuss formally about hypothesis testing. In standard frequentist statistic's hypothesis testing, we start with a null hypothesis that we usually call $H_0$ (pronouced as H naught), which represents our status quo. On the other hand, we also have an alternative hypothesis our $H_1$ that represents the question that we wish to answer, i.e. what we\u2019re testing for.\n\nAfter setting up our null and alternative hypothesis, we conduct a hypothesis test under the assumption that the null hypothesis is true. If the test results suggest that the data do not provide convincing evidence for the alternative hypothesis, we stick with the null hypothesis. If they do, then we reject the null hypothesis in favor of the alternative.\n\nFrequentist statistic's hypothesis testing uses a p-value to weigh the strength of the evidence (what the data is telling you about the population). p-value is defined as **the probability of obtaining the observed or more extreme outcome, given that the null hypothesis is true (not the probability that the alternative hypthesis is true)**. It is a number between 0 and 1 and interpreted in the following way:\n\n- A small p-value (typically <= 0.05, 0.05 is a commonly used threshold, the threshold is often denoted as $\\alpha$) indicates strong evidence against the null hypothesis, so we reject the null hypothesis. This means that something interesting is going on and it\u2019s not just noise!\n- A large p-value (> 0.05) indicates weak evidence against the null hypothesis, so we fail to reject the null hypothesis. Although p-value is still in our favor, we cannot conclusively say that it was not due to random noise.\n- p-values very close to the cutoff (0.05) are considered to be marginal (could go either way). If you carefully read good papers on these kind of topics, you will always see the p-values being reported so that the readers can draw their own conclusions.\n\n**Example:**\n\nLet's say that a pizza place claims their delivery times are 30 minutes or less on average. Now we think it's actually takes more than 30 minutes. We conduct a hypothesis test because we believe the null hypothesis, that the mean delivery time is 30 minutes maximum, is incorrect. This means that our alternative hypothesis is the mean time is greater than 30 minutes. We randomly sample some delivery times and run the data through the hypothesis test, and our p-value turns out to be 0.01, which is much less than 0.05.\n\nIn real terms, there is a probability of 0.001 that we will mistakenly reject the pizza place's claim that their delivery time is less than or equal to 30 minutes. Since typically we are willing to reject the null hypothesis when this probability is less than 0.05, we conclude that the pizza place is wrong; their delivery times are in fact more than 30 minutes on average.\n\nBack with our coin toss example, the null hypothesis assumes we have a fair coin, and the way we determine if this hypothesis is true or not is by calculating how often flipping this fair coin 30 times would result in 22 or more heads. If we then take the number of times that we got 22 or more heads and divide that number by the total of all possible permutations of 30 coin tosses, we get the probability of tossing 22 or more heads with a fair coin. This probability is essentially our p-value.\n\n\n```python\ndef compute_pvalue(n, k, p):\n    \"\"\"Returns the p-value for binomial distribution\"\"\"\n    k_range = range(k, n + 1)\n    pvalue = stats.binom(n = n, p = p).pmf(k = k_range).sum()\n    return pvalue\n\n\npvalue = compute_pvalue(n = 30, k = 22, p = 0.5)\nprint('P-value: {:0.1f}%'.format(pvalue * 100))\n```\n\n    P-value: 0.8%\n\n\nThe role of p-value is used to check the validity of the null hypothesis. The way this is done is by agreeing upon some predetermined upper limit for our p-value, below which we will assume that our null hypothesis is false.\n\nIn other words, if our null hypothesis were true, and 22 heads in 30 flips could happen often enough by chance, we would expect to see it happen more often than the given threshold percentage of times. So, for example, if we chose 10% as our p-value threshold, then we would expect to see 22 or more heads show up at least 10% of the time to determine that this is a chance occurrence and not due to some bias in the coin. Historically, the generally accepted threshold has been 5%, and so if our p-value is less than 5%, we can then make the assumption that our coin may not be fair.\n\nRunning the code above gives us a p-value of roughly 0.8%, which matches the value in our probability distribution above and is also less than the 5% threshold needed to reject our null hypothesis, so it does look like we may have a biased coin.\n\n\n```python\n# we can also use the binom_test function from scipy to\n# perform the hypothesis testing\npvalue = stats.binom_test(x = 22, n = 30, p = 0.5, alternative = 'greater')\nprint('P-value: {:0.1f}%'.format(pvalue * 100))\n```\n\n    P-value: 0.8%\n\n\n## Simulation\n\nInstead of using the stastistical approach, the code below seeks to answer the same question of whether or not our coin is fair by running a large number of simulated coin flips and calculating the proportion of these experiments that resulted in at least 22 heads or more.\n\n\n```python\ndef coin_toss(n_simulation = 100000):\n    \"\"\"\n    computing a fair coin resulting in at\n    least 22 heads or more through simulation\n    \"\"\"\n    pvalue = 0\n    for i in range(n_simulation):\n        # trials: 1 denotes head, 0 denotes tail\n        trials = np.random.randint(2, size = 30)\n        if trials.sum() >= 22:\n            pvalue += 1\n\n    pvalue /= n_simulation\n    return pvalue\n\n\npvalue = coin_toss()\nprint('Simulated P-value: {:0.1f}%'.format(pvalue * 100))\n```\n\n    Simulated P-value: 0.8%\n\n\nThe result of our simulations is 0.8%, the exact same result we got earlier when we calculated the p-value using the classical method above.\n\n# Frequentist A/B testing\n\nA/B testing is essentially a simple randomized trial. Randomized trials are (usually) considered the gold standard study design for evaluating the efficacy of new medical treatments, but they are also used much more widely in experimental research.\n\nFor example, when someone visits a website, the site sends them to one of two (or possibly more) different landing or home pages, and which one they are sent to is chosen at random. The purpose is to determine which page version generates a superior outcome, e.g. which page generates more advertising revenue, or which which page leads a greater proportion of visitors to continue visiting the site.\n\nThe key idea is that because we randomize which landing page (or treatment in the case of a randomized clinical trial) someone goes to, after a large number of visitors, the groups of people who visited the two pages are completely comparable in respect of all characteristics (e.g. age, gender, location, and anything else you can think of!). Because the two groups are comparable, we can compare the outcomes (e.g. amount of advertising revenue) between the two groups to obtain an unbiased, and fair, assessment of the relative effectiveness (in terms of our defined outcome) of the two designs.\n\nSuppose for the moment that we've had two visitors to our site, and one visitor has been randomized to page A, and the other visitor to page B (note that it is entirely possible, with simple randomization, that both visitors could have both been sent to page A). Suppose next that the visitor to page A generated revenue, but the visitor to page B generated no revenue. Should we conclude that page A is superior to page B, in terms of revenue generation? Of course not. Because we have only sampled two visitors, it is entirely possible that the visitor to page A would have generated revenue even if they had been sent to page B, perhaps because they are very interested in the site's content, whereas perhaps the visitor to page B was not particularly interested in the site content, and was never going to generate revenue. We can overcome this problem by running the A/B testing for a sufficiently large number of visitors, such that the probability that the scenario described above is sufficiently small.\n\nScenario: We ran an A/B test with two different versions of a web page, a and b, for which we count the number of visitors and whether they convert or not. We can summarize this in a contingency table showing the frequency distribution of the events:\n\n\n```python\ndata = pd.DataFrame({\n    'version': ['A', 'B'],\n    'not_converted': [4514, 4473],\n    'converted': [486, 527]\n})[['version', 'not_converted', 'converted']]\ndata\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>version</th>\n      <th>not_converted</th>\n      <th>converted</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>A</td>\n      <td>4514</td>\n      <td>486</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>B</td>\n      <td>4473</td>\n      <td>527</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nIt is trivial to compute the conversion rate of each version, 486/(486 + 4514) = 9.72% for a and 10.5% for b. With such a relatively small difference, however, can we convincingly say that the version b converts better? To test the statistical significance of a result like this, a hypothesis testing can be used.\n\n## Comparing Two Proportions\n\nLet's formalize our thought process a little bit, suppose that we have obtained data from n visitors, $n_A$ of which have been (randomly) sent to page A, and $n_B$ of which have been sent to page B. Further, let $X_A$ and $X_B$ denote the number of visitors for whom we obtained a 'successful' outcome in the two groups. The proportion of successes in the two groups is then given by $\\hat{p_A} = X_A/n_A$ and $\\hat{p_B} = X_B/n_B$ respectively. The estimated difference in success rates is then give by the difference in proportions: $\\hat{p_A} - \\hat{p_B}$:\n\nTo assess whether we have statistical evidence that the two pages' success rates truely differ, we can perform a hypothesis test. The null hypothesis that we want to test is that the two pages' true success rates are equal, whereas the alternative is that they differ (one is higher than the other). If $p_A$ = the proportion of the page A population whom we obtained a successful outcome and $p_B$ = the proportion of the page B population whom we obtained a successful outcome then we are interested in testing the following hypothesis:\n\n\\begin{align}\nH_0:p_A = p_B \\text{ versus } H_A: p_A \\neq p_B\n\\end{align}\n\nOr put it in another way, the null hypothesis says that the factors 'page type' and 'outcome' are statistically independent of each other. In words, this means knowing which page someone is sent to tells you nothing about the chance that they will have a successful outcome. Now that we know what hypothesis test we're interested in, we'll have to derive the appropriate test statistic.\n\nA test statistic is a single metric that can be used to evaluate the null hypothesis and the standard way to obtain this metric is to compute the z-score that measures how many standard deviations below or above the population mean a raw score is: \n\n\\begin{align}\nz = \\frac{x - \\mu}{SE}\n\\end{align}\n\nWhere:\n\n- $\\mu$ denotes the mean\n- $\\sigma$ denotes the standard error, computed by $\\frac{s}{\\sqrt{n}}$, where $s$ denotes the standard error and $n$ denotes the number of samples\n\nThe following link contains an example of where this is applied in proportion hypothesis testing for those who feels uncomfortable with this concept. [Notes: Eberly College of Science STAT 414/415: Test About Proportions](https://onlinecourses.science.psu.edu/stat414/node/265)\n\nFor our test the underlying metric is a binary yes/no variable (event), which means the appropriate test statistic is a test for differences in proportions:\n\n\\begin{align}\nZ = \\frac{ (\\hat{p_A} - \\hat{p_B}) - (p_A - p_B) }{SE(p_A - p_B)}\n\\end{align}\n\nThe test statistic makes sense as it measuring the difference in the observed proportions and the estimated proportion, standardized by an estimate of the standard error of this quantity.\n\nTo compute the test statistic, we first need to find the standard deviation/variance of $p_A - p_B$:\n\n\\begin{align}\nVar(p_A - p_B)\n&= Var(p_A) +  Var(p_B) \\\\\n&= \\frac{p_A (1 - p_A)}{n_A} + \\frac{p_B (1 - p_B)}{n_B} \\\\\n&= p (1 - p) \\left( \\frac{1}{n_A} + \\frac{1}{n_B} \\right)\n\\end{align}\n\n- The first step stems from that fact that, given that we know:\n    - The variance of a random variable X is defined as $Var(X) = E[X^2] - E[X]^2$\n    - The covariance between two random variable X and Y is defined as $Cov(X, Y) = E[(X - u_x)(y - u_y)] = E[XY] - E[X]E[Y]$\n    - When conducting hypothesis test, we know that the two groups should be independent of each other, i.e. the covariance between the two should be 0\n\n\\begin{align}\nVar(X - Y)\n&= E[(X - Y)(X - Y)] - E[X - Y]^2 \\\\\n&= E[X^2 - 2XY + Y^2] - (u_x - u_y)^2 \\\\\n&= E[X^2 - 2XY + Y^2] - u_x^2 + 2u_xu_y - u_y^2 \\\\\n&= (E[X^2] - u_x^2) + (E[Y^2] - u_y^2) - 2(E[XY] - u_xu_y) \\\\\n&= Var(X) + Var(Y) - 2 Cov(X, Y)\n\\end{align}\n\n- We're using the property that the variance of a binomial proportion is given by: $Var(p_A) = p_A (1 - p_A) / n_A$, the same can be applied for group B\n- The third step comes from the fact that if we assume that the null hypothesis, $p_A = p_B$ is true, then the population proportions equal some common value $p$, that is, $p_A = p_B = p$. Since we don't know the assumed common population proportion $p$ any more than we know the proportions $p_A$ and $p_B$ of each population, we can estimate $p$ using the proportion of \"successes\" in the two combined, $\\hat{p} = (X_A + X_B)/(n_A + n_B)$, which is commonly referred to as the **pooled probability**\n\nDuring the third step, we utilized that fact that if we assume that the null hypothesis is true, then $p_A = p_B$, this also means $p_A - p_B = 0$. Given all of these information, the formula for our test statistic now becomes:\n\n\\begin{align}\nZ\n&= \\frac{ (\\hat{p_A} - \\hat{p_B}) - (p_A - p_B) }{SE(p_A - p_B)} \\\\\n&= \\frac{ (\\hat{p_A} - \\hat{p_B}) - 0 }{\\sqrt{\\hat{p} (1 - \\hat{p}) \\left( \\frac{1}{n_A} + \\frac{1}{n_B} \\right)}}\n\\end{align}\n\nWhere $\\hat{p} = (X_A + X_B)/(n_A + n_B)$\n\n\n```python\ndef two_proprotions_test(success_a, size_a, success_b, size_b):\n    \"\"\"\n    A/B test for two proportions;\n    given a success a trial size of group A and B compute\n    its zscore and pvalue\n    \n    Parameters\n    ----------\n    success_a, success_b : int\n        Number of successes in each group\n        \n    size_a, size_b : int\n        Size, or number of observations in each group\n    \n    Returns\n    -------\n    zscore : float\n        test statistic for the two proportion z-test\n\n    pvalue : float\n        p-value for the two proportion z-test\n    \"\"\"\n    prop_a = success_a / size_a\n    prop_b = success_b / size_b\n    prop_pooled = (success_a + success_b) / (size_a + size_b)\n    var = prop_pooled * (1 - prop_pooled) * (1 / size_a + 1 / size_b)\n    zscore = np.abs(prop_b - prop_a) / np.sqrt(var)\n    one_side = 1 - stats.norm(loc = 0, scale = 1).cdf(zscore)\n    pvalue = one_side * 2\n    return zscore, pvalue\n```\n\n\n```python\nsuccess_a = 486\nsize_a = 5000\nsuccess_b = 527\nsize_b = 5000\n\nzscore, pvalue = two_proprotions_test(success_a, size_a, success_b, size_b)\nprint('zscore = {:.3f}, pvalue = {:.3f}'.format(zscore, pvalue))\n```\n\n    zscore = 1.359, pvalue = 0.174\n\n\n\n```python\n# or we can use the implementation from statsmodels\n# where we pass in the success (they call the argument counts)\n# and the total number for each group (they call the argument nobs,\n# number of observations)\ncounts = np.array([486, 527])\nnobs = np.array([5000, 5000])\n\nzscore, pvalue = proportions_ztest(counts, nobs, alternative = 'two-sided')\nprint('zscore = {:.3f}, pvalue = {:.3f}'.format(zscore, pvalue))\n```\n\n    zscore = -1.359, pvalue = 0.174\n\n\nBased on the fact that our p-value is not smaller than the 0.05 commonly used threshold, the test statistic tells us we do not have strong evidence against our null hypothesis, i.e. we do not have strong evidence that the two pages are not equally effective.\n\nApart from spitting out the p-value, we will also look at forming a confidence interval for $\\hat{p_A} - \\hat{p_B}$. If the number of trials in both groups is large, and the observed number of successes are not too small, we can calculate a 95% confidence interval using the formula:\n\n\\begin{align}\n\\text{point estimate} \\pm z * SE\n&= (\\hat{p_A} - \\hat{p_B}) \\pm z * \\frac{p_A (1 - p_A)}{n_A} + \\frac{p_B (1 - p_B)}{n_B}\n\\end{align}\n\nNote that when calculating the confidence interval because we no longer have the assumption that $p_A = p_B$ from our null hypothesis, thus we can't leverage this property and use the pooled probability.\n\n\n```python\ndef two_proprotions_confint(success_a, size_a, success_b, size_b, significance = 0.05):\n    \"\"\"\n    A/B test for two proportions;\n    given a success a trial size of group A and B compute\n    its confidence interval;\n    resulting confidence interval matches R's prop.test function\n    \n    Parameters\n    ----------\n    success_a, success_b : int\n        Number of successes in each group\n        \n    size_a, size_b : int\n        Size, or number of observations in each group\n        \n    significance : float, default 0.05\n        Often denoted as alpha. Governs the chance of a false positive.\n        A significance level of 0.05 means that there is a 5% chance of\n        a false positive. In other words, our confidence level is\n        1 - 0.05 = 0.95\n        \n    Returns\n    -------\n    prop_diff : float\n        Difference between the two proportion\n    \n    confint : 1d ndarray\n        Confidence interval of the two proportion test\n    \"\"\"\n    prop_a = success_a / size_a\n    prop_b = success_b / size_b\n    var = prop_a * (1 - prop_a) / size_a + prop_b * (1 - prop_b) / size_b\n    se = np.sqrt(var)\n    \n    # z critical value\n    confidence = 1 - significance\n    z = stats.norm(loc = 0, scale = 1).ppf(confidence + significance / 2)\n\n    # standard formula for the confidence interval\n    # point-estimtate +- z * standard-error\n    prop_diff = prop_b - prop_a\n    confint = prop_diff + np.array([-1, 1]) * z * se\n    return prop_diff, confint\n```\n\n\n```python\nprop_diff, confint = two_proprotions_confint(success_a, size_a, success_b, size_b)\nprint('estimate difference:', prop_diff)\nprint('confidence interval:', confint)\n```\n\n    estimate difference: 0.008199999999999999\n    confidence interval: [-0.00362633  0.02002633]\n\n\nUp till this point, we've been using the 5000 as the total number of observations/samples that are involved in the A/B testing process. The next question that we'll address is, in real world scenarios, how many obeservations do we need in order to draw a valid verdict on the test result. This leads us to our next topic **power**.\n\n\n## Introducing Power\n\nIn the world of hypothesis testing, rejecting the null hypothesis when it is actually true is called a type 1 error, often denoted as $\\alpha$. Committing a type 1 error is a false positive because we end up recommending something that does not work. Conversely, a type 2 error, often denoted as $\\beta$, occurs when you do not reject the null hypothesis when it is actually false. This is a false negative because we end up sitting on our hands when we should have taken action. We need to consider both of these types of errors when choosing the sample size.\n\nTwo important probabilities related to type 1 and type 2 error are:\n\n- **Significance level:** Governs the chance of a false positive. A significance level of 0.05 means that there is a 5% chance of a false positive. Choosing level of significance is an arbitrary task, but for many applications, a level of 5% is chosen, for no better reason than that it is conventional\n- **Statistical power** Power of 0.80 means that there is an 80% chance that if there was an effect, we would detect it (or a 20% chance that we'd miss the effect). In other words, power is equivalent to $1 - \\beta$. There are no formal standards for power, most researchers assess the power of their tests using 0.80 for adequacy\n\n| Scenario       | $H_0$ is true                      | $H_0$ is false            |\n|:--------------:|:----------------------------------:|:-------------------------:|\n|  Accept $H_0$  |  Correct Decision                  |  Type 2 Error (1 - power) |\n|  Reject $H_0$  |  Type 1 Error (significance level) |  Correct decision         |\n\nThe concepts of power and significance level can seem somewhat convoluted at first glance. A good way to get a feel for the underlying mechanics is to plot the probability distribution of $Z$ assuming that the null hypothesis is true. Then do the same assuming that the alternative hypothesis is true, and overlay the two plots.\n\nConsider the following example: $H_0: p_A = p_B, H_1: p_A > p_B$. A one-sided test was chosen here for charting-simplicity.\n\n- Total sample size, N=5,000 (assume equal sample sizes for the control and experiment groups, meaning exactly 2,500 in each group)\n- Say we decide that we need to observe a difference of 0.02 (detailed later) in order to be satisfied that the intervention worked (i.e., assuming that our original baseline, $p_B$ was 0.08, then we want $p_A = 0.10$). We will discuss how to make this decision later in the post\n\n\n```python\ndef plot_power(min_diff, prob_b, size_a, size_b, significance = 0.05):\n    \"\"\"illustrating power through a one-tailed hypothesis test\"\"\"\n    \n    # obtain the z-score for the minimum detectable\n    # difference using proportion_ztest\n    prob_a = prob_b + min_diff\n    count_a = size_a * prob_a\n    count_b = size_b * prob_b\n    counts = np.array([count_a, count_b])\n    nobs = np.array([size_a, size_b])\n    zscore, _ = proportions_ztest(counts, nobs, alternative = 'larger')\n\n    # distribution for the null hypothesis, h0\n    # and alternative hypothesis, h1\n    h0 = stats.norm(loc = 0, scale = 1)\n    h1 = stats.norm(loc = zscore, scale = 1)\n\n    # points that are greater than the zscore for the\n    # specified significance level\n    x = np.linspace(-5, 6, num = 100)\n    threshold = h0.ppf(1 - significance)\n    mask = x > threshold\n    \n    # power is the area after the thresold, i.e.\n    # 1 - the cumulative distribution function of that point\n    power = np.round(1 - h1.cdf(threshold), 2)\n\n    hypotheses = [h1, h0]\n    labels = ['$H_1$ is true', '$H_0$ is true']\n    for hypothesis, label in zip(hypotheses, labels):\n        y = hypothesis.pdf(x)\n        line = plt.plot(x, y, label = label)  \n        plt.fill_between(x = x[mask], y1 = 0.0, y2 = y[mask],\n                         alpha = 0.2, color = line[0].get_color())\n    \n    title = 'p1: {}, p2: {}, size1: {}, size2: {}, power: {}'\n    plt.title(title.format(prob_a, prob_b, size_a, size_b, power))\n    plt.legend()\n    plt.tight_layout()\n    plt.show()\n```\n\n\n```python\nprob_b = 0.08\nmin_diff = 0.02\nsize_a = 2500\nsize_b = 2500\n\nplot_power(min_diff, prob_b, size_a, size_b)\n```\n\nThe shaded green area denotes the significance region, while the the shaded blue area denotes the power (note that it includes the shaded green area). Note that if we pick a smaller N, or a smaller probability difference between the control and experiment group, the power drops (the shaded blue area decreases), meaning that if there\u2019s is in fact a change, there\u2019s lesser percent chance that we\u2019ll detect it.\n\n\n```python\n# smaller N\nprob_b = 0.08\nmin_diff = 0.02\nsize_a = 1250\nsize_b = 1250\n\nplot_power(min_diff, prob_b, size_a, size_b)\n```\n\n\n```python\n# smaller probability difference\nprob_b = 0.08\nmin_diff = 0.001\nsize_a = 2500\nsize_b = 2500\n\nplot_power(min_diff, prob_b, size_a, size_b)\n```\n\nThe following link illustrates power for a two-sided hypothesis test for those interested. [Youtube: Calculating Power and the Probability of a Type II Error (A Two-Tailed Example)](https://www.youtube.com/watch?v=NbeHZp23ubs)\n\n\n## Determining Sample Size\n\nSay we've followed the rule of thumb and require the significance level to be 5% and the power to be 80%. This means we have now specified two key components of a power analysis.\n\n- A decision rule of when to reject the null hypothesis. We reject the null when the p-value is less than 5%.\n- Our tolerance for committing type 2 error (1\u221280%=20%).\n\nTo actually solve for the equation of finding the suitable sample size, we also need to specify the detectable difference, the level of impact we want to be able to detect with our test.\n \nIn order to explain the dynamics behind this, we'll return to the definition of power: the power is the probability of rejecting the null hypothesis when it is false. Hence for us to calculate the power, we need to define what \"false\" means to us in the context of the study. In other words, how much impact, i.e., difference between test and control, do we need to observe in order to reject the null hypothesis and conclude that the action worked?\n\nLet's consider two illustrative examples: if we think that an event rate reduction of, say, $10^{-10}$ is enough to reject the null hypothesis, then we need a very large sample size to get a power of 80%. This is pretty easy to deduce from the charts above: if the difference in event rates between test and control is a small number like $10^{-10}$, the null and alternative probability distributions will be nearly indistinguishable. Hence we will need to increase the sample size in order to move the alternative distribution to the right and gain power. Conversely, if we only require a reduction of 0.02 in order to claim success, we can make do with a much smaller sample size. \n\n> The smaller the detectable difference, the larger the required sample size\n\nHere's how we could conduct a power test in python:\n\n\n```python\nimport statsmodels.stats.api as sms\n\n\ndef compute_sample_size(prop1, min_diff, significance = 0.05, power = 0.8):\n    \"\"\"\n    Computes the sample sized required for a two-proportion A/B test;\n    result matches R's pwr.2p.test from the pwr package\n    \n    Parameters\n    ----------\n    prop1 : float\n        The baseline proportion, e.g. conversion rate \n        \n    min_diff : float\n        Minimum detectable difference\n        \n    significance : float, default 0.05\n        Often denoted as alpha. Governs the chance of a false positive.\n        A significance level of 0.05 means that there is a 5% chance of\n        a false positive. In other words, our confidence level is\n        1 - 0.05 = 0.95\n    \n    power : float, default 0.8\n        Often denoted as beta. Power of 0.80 means that there is an 80%\n        chance that if there was an effect, we would detect it\n        (or a 20% chance that we'd miss the effect)\n        \n    Returns\n    -------\n    sample_size : int\n        Required sample size for each group of the experiment\n\n    References\n    ----------\n    R pwr package's vignette\n    - https://cran.r-project.org/web/packages/pwr/vignettes/pwr-vignette.html\n\n    Stackoverflow: Is there a python (scipy) function to determine parameters\n    needed to obtain a target power?\n    - https://stackoverflow.com/questions/15204070/is-there-a-python-scipy-function-to-determine-parameters-needed-to-obtain-a-ta\n    \"\"\"\n    prop2 = prop1 + min_diff\n    effect_size = sms.proportion_effectsize(prop1, prop2)\n    sample_size = sms.NormalIndPower().solve_power(\n        effect_size, power = power, alpha = significance, ratio = 1)\n    \n    return sample_size\n```\n\n\n```python\nsample_size = compute_sample_size(prop1 = 0.1, min_diff = 0.02)\nprint('sample size required per group:', sample_size)\n```\n\n    sample size required per group: 3834.5957398840183\n\n\nNote that the printed result is the sample size needed for each group!\n\nUnlike the significance level and the power, there are no plug-and-play values we can use for the detectable difference. The key is to define what \"pay off\" means for the study at hand, which depends on what the adverse event is a well as the cost of the action. Two guiding principles:\n\n- **Avoid wasteful sampling** Let\u2019s say it takes an absolute difference of 0.02 between test and control in order for the treatment to pay off. In this case, aiming for a 0.01 detectable difference would just lead to more precision than we really need. Why have the ability to detect 0.01 if we don\u2019t really care about a 0.01 difference? In many cases, sampling for unnecessary precision can be costly and a waste of time\n- **Avoid missed opportunities** Conversely, if we are analyzing a sensitive metric where small changes can have a large impact e.g. email campaigns, we have to aim for a small detectable difference. If we choose an insufficient sample size, we may end up sitting on our hands and missing an opportunity (type 2 error)\n\nHence, choosing the minimum detectable difference should be a cross-functional analysis/discussion between the data scientist and the business stakeholder. Once there is a viable range for the detectable difference, we can evaluate the sample size required for each option. For example, let\u2019s say that $p1=0.10$ and we want the detectable difference to be between 0.01 and 0.03. Clearly, we\u2019d rather be able to detect a difference of 0.01, but it may be too costly and hence we want to evaluate more conservative options as well.\n\n\n```python\n# calculate the the required sample size\n# for a range of minimum detectable difference\nsample_sizes = []\nmin_diffs = np.arange(0.01, 0.03, 0.001)\nfor min_diff in min_diffs:\n    sample_size = compute_sample_size(prop1 = 0.1, min_diff = min_diff)\n    sample_sizes.append(sample_size)\n\nplt.plot(min_diffs, sample_sizes)\nplt.title('Sample Size Required for the Minimum Detectable Difference')\nplt.ylabel('Sample Size')\nplt.xlabel('Minimum Detectable Difference')\nplt.tight_layout()\nplt.show()\n```\n\nFrom the graph, we can see that we need roughly 10x more observations to get a detectable difference of 0.01 compared to 0.03.\n\nThe following section is an alternative way of conducting a test statistic for proportional A/B test, feel free to skip it, it will not affect that understanding of later section.\n\n## Alternative View of the Test Statistic\n\nThere are two types of the chi-squared test, goodness of fit and test of independence, but it is the latter which is useful for the case in question. The reason as to why a test of \u201cindependence\u201d is applicable becomes clear by converting the contingency table into a probability matrix by dividing each element by the grand total of frequencies:\n\n\n```python\ncols = ['not_converted', 'converted']\ndata[cols] = data[cols] / data[cols].values.sum()\ndata\n```\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>version</th>\n      <th>not_converted</th>\n      <th>converted</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>A</td>\n      <td>0.4514</td>\n      <td>0.0486</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>B</td>\n      <td>0.4473</td>\n      <td>0.0527</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nWe will denote $V$ as the version of the web page ($a$ or $b$) and $C$ as the conversion result, $f$ (false did not convert) or $t$ (true did in fact convert). The table that we computed above, which this the data that we observed can then be translated into this form:\n\n\n| Version (V) | $f$ (false did not convert)  | $t$ (true did in fact convert) |\n|:-----------:|:----------------------------:|:------------------------------:|\n|    A        | $P(V = a, C = f)$            | $P(V = a, C = t)$              |\n|    B        | $P(V = b, C = f)$            | $P(V = b, C = t)$              |\n\n\nNow, our interest is whether the conversion $C$ depends on the page version $V$, and if it does, to learn which version converts better. In probability theory, the events $C$ and $V$ are said to be independent if the joint probability can be computed by $P(V, C) = P(V) \\cdot P(C)$, where $P(V)$ and $P(C)$ are marginal probabilities of $V$ and $C$, respectively. It is straightforward to compute the marginal probabilities from row and column marginals:\n\n$$P(V = a) = \\frac{4514 + 486}{10000}  \\hspace{1cm} P(V = b) = \\frac{4473 + 527}{10000}$$\n$$P(C = f) = \\frac{4514 + 4473}{10000} \\hspace{1cm} P(V = b) = \\frac{486 + 527}{10000}$$\n\nThe null hypothesis is that $V$ and $C$ are independent, in which case the elements of the matrix, a.k.a the distribution that we're expecting is equivalent to:\n\n| Version (V) | $f$ (false did not convert)  | $t$ (true did in fact convert) |\n|:-----------:|:----------------------------:|:------------------------------:|\n|    A        | $P(V = a)P(C = f)$           | $P(V = a)P(C = t)$             |\n|    B        | $P(V = b)P(C = f)$           | $P(V = b)P(C = t)$             |\n\n\nThe conversion $C$ is said to be dependent on the version $V$ of the web site if this null hypothesis is rejected. Hence rejecting the null hypothesis means that one version is better at converting than the other. This is the reason why the test is on independence.\n\nWhen dealing with counts and investigating how far the observed counts are from the expected counts, we use a test statistic called the **chi-square test**. The chi-squared test compares an observed distribution $O_{ij}$ to an expected distribution $E_{ij}$:\n\n\\begin{align}\n\\chi^2 = \\sum_{i,j} \\frac{(O_{ij} - E_{ij})^2}{E_{ij}}\n\\end{align}\n\nIt's calculated as the observed minus the expected for each cell squared divided by the expected counts, the division with the expected counts makes final result proportional to our expected frequency. After performing the computation for each cell, we want to sum this over all of the cells (levels of the categorical variable).\n\nThis $\\chi^2$ probability distribution has only one parameter, the degrees of freedom. It influences the shape, the center and the spread of the chi-square distribution.\n\n\n```python\n# chi square distribution with varying degrees of freedom\nfig = plt.figure(figsize = (8, 6))\nx = np.linspace(0, 5, 1000)\ndeg_of_freedom = [1, 2, 3, 4]\nfor df in deg_of_freedom:\n    plt.plot(x, stats.chi2.pdf(x, df), label = '$df={}$'.format(df))\n\nplt.xlim(0, 5)\nplt.ylim(0, 0.5)\nplt.xlabel('$\\chi^2$')\nplt.ylabel('$f(\\chi^2)$')\nplt.title('$\\chi^2\\ \\mathrm{Distribution}$')\nplt.legend()\nplt.show()\n```\n\nchi-square distribution gives a way of measuring the difference between the frequencies we observe and the frequencies we expect. The smaller the value of $\\chi^2$, the smaller the difference overall between the observed and expected frequencies. The way to compute the degree of freedom for the test of independence using a $r \\times c$ contingency matrix is:\n\n\\begin{align}\ndf = (r - 1)(c - 1)\n\\end{align}\n\nWhere $r$ denotes the number of rows and $c$ denotes the number of columns. The rationale behind this calculation is because degrees of freedom is the number of expected frequencies we have to calculate independently after taking into account any restrictions. The restrictions come from the row and column sum constraints, but decreased by one because the last entry in the table/matrix is determined by either the row or column sum on that row/column.\n\nFortunately it is very straightforward to carry out this hypothesis testing using packages. All we need is to supply the function with a contingency matrix and it will return the $\\chi^2$ statistic and the corresponding p-value:\n\n\n```python\n# we can use the proportions_chisquare function,\n# where we pass in the number of successes and\n# the total number of trials/observation\ncount = np.array([486, 527])\nnobs = np.array([5000, 5000])\n\n# note that in this case (a two sample case with two sided\n# alternative), the test produces the same value as porportions_ztest\n# since the chi-square distribution is the square of a normal distribution\nchisq, pvalue, table = proportions_chisquare(count, nobs)\nprint('chisq = {}, pvalue = {}'.format(chisq, pvalue))\n```\n\n    chisq = 1.8464754013996965, pvalue = 0.17419388311716985\n\n\n\n```python\n# or the chi2_contingency function where we pass\n# in the observed contingency table\nobserved = np.array([[4514,  486], [4473,  527]])\n\n# more about the correction = False parameter later\nresult = stats.chi2_contingency(observed, correction = False)\nchisq, pvalue = result[:2]\nprint('chisq = {}, pvalue = {}'.format(chisq, pvalue))\n```\n\n    chisq = 1.8464754013996965, pvalue = 0.17419388311716985\n\n\nThe result for our experiment has a  $\\chi^2 = 1.74$ and $p = 0.185$. Since the p-value is greater than the standard threshold 0.05, we cannot reject the null hypothesis that the page version and the conversion is independent. Therefore the difference in the conversion rates is not statistically significant.\n\nFor a 2 x 2 contingency table, Yate\u2019s chi-squared test is commonly used. This applies a correction of the form:\n\n\\begin{align}\n\\chi^2_{Yate's} = \\sum_{i,j} \\frac{(\\big|O_{ij} - E_{ij}\\big| - 0.5)^2}{E_{ij}}\n\\end{align}\n\nto account for an error between the observed discrete distribution and the continuous chi-squared distribution (the step of -0.5 is often referred to as continuity correction).\n\n\n```python\n# we can use the correcction form, by specifying\n# correction = True\nresult = stats.chi2_contingency(observed, correction = True)\nchisq, pvalue = result[:2]\nprint('chisq = {}, pvalue = {}'.format(chisq, pvalue))\n```\n\n    chisq = 1.7575018692680038, pvalue = 0.18493641552090323\n\n\nAgain, our pvalue is greater than the critical value, hence we simply would not reject the null hypothesis (that there is no relationship between the categorical variables).\n\n> Side note: in practice, we want to make sure that each particular scenario or cell has at least five expected counts before employing the chi-square test.\n\n# Frequentist A/B Testing Workflow\n\n\nAfter diving into the technical details of conducting a frequentist A/B testing, we will now introduce one possible template/workflow/thought-process for conducting A/B testing.\n\n\n## Formulate Business Goals & Hypothesis Test\n\n**Define Business Goal**\n\nEvery project or plan or test always starts with a goal e.g. A business objective for an online flower store is to \"Increase our sales by receiving online orders for our bouquets\"\n\n**Formulate A/B Test**\n\nThe crux of A/B testing can be summarized into one sentence:\n\n> If **[Variable]**, then **[Result]**, because **[Rationale]**\n\n- **[Variable]** is the element such as call to action, media that we've modified\n- **[Result]** is basically what we expect to see, such as more clicks, more sign-ups. The effect size of [Result] will be determined by the data\n- **[Rationale]** what assumptions will be proven right/wrong after the experiment\n\n\n### Result\n\nWe start by asking ourselves, what result are we expecting out of this test? To do this, we need to:\n\n- **Define our Key Performance Indicators.** e.g. Our flower store\u2019s business objective is to sell bouquets. Our KPI could be number of bouquets sold online.\n- **Define our target metrics.** e.g. For our imaginary flower store, we can define a monthly target of 175 bouquets sold.\n\n### Rationale\n\nA lot of times, people have the idea that A/B testing is panacea, too many people think they'll just guess their way to great conversion and revenue, when trully successful tests are typically much more complicated than that.\n\nAfter defining the high level goal and knowing the result that we're aiming for, find out (not guess) which parts of our business are underperforming or trending and why. Ways to perform this step are:\n\n**Quantitative methods** We can start by looking at quantitative data if we have any. These methods do a much better job answering how many and how much types of questions.\n\nSay we're a website, we can take a look at our conversion funnel and examine the flow from the persuasive end (top of the funnel) and the transactional end (bottom of the funnel). e.g. We can identify problems by starting from the top 5 highest bounce rate pages. During the examination, segment to spot underlying underperformance or trends.\n\n- **Segment by source:** Separate people who arrive on your website from e-mail campaigns, google, twitter, youtube, etc. Find answers to questions like: Is there a difference between bounce rates for those segments? Is there a difference in Visitor Loyalty between those who came from Youtube versus those who came from Twitter? What products do people who come from Youtube care about more than people who come from Google?\n- **Segment by behavior:** Focus on groups of people who have similar behaviors For example, we can separate out people who visit more than ten times a month versus those that visit only twice. Do these people look for products in different price ranges? Are they from different regions? Or separate people out by the products they purchase, by order size, by people who have signed up.\n\ne.g. We're looking at our metric of total active users over time and we see a spike in one of the timelines. After confirming that this is not caused by seasonal variation, we can look at different segment of our visitors to see if one of the segment is causing the spike. Suppose we have chosen segment to be geographic, it might just happen that we\u2019ve identify a large proportion of the traffic is generated by a specific region\n\nDuring the process we should ask ourselves: 1) Why is it happening? 2) How can we spread the success of other areas of the site. And it might be best for us to use qualitative methods to dig deeper and understand why, i.e. the rationale that behind the hypothesis test.\n\n**Qualitative methods:** Ideas for gathering qualitative data to understand the why a problem exists and how to potentially fix it:\n\n- Add an exit survey on our site, asking why our visitors did/didn't complete the goal\n- Track what customers are saying in social media and on review sites\n- User Experience Group (this is the preferred way as it is going really deep with a few users and ask qualitative questions such as what's holding them back from doing what we hope they'll do, e.g. converting)\n\n### Variable\n\nNow that we've identify the overall business goal and the possible issue, it's time the determine the variable, which is the element that we'll be testing for. e.g. we've identified through quantitative method that less than one percent of visitors sign up for our newsletter and after conducting qualitative studies it's because the call to action wording does not resonate with the audience, then our variable will be changing the call to action's wording.\n\nNote that we may have multiple ideas for our variable, in that case we can collate all the ideas, prioritize them based on three simple metrics:\n\n- **Potential** How much potential for a conversion rate increase? We can check to see if this kind of idea worked before.\n- **Importance** How many visitors will be impacted from the test?\n- **Ease** How easy is it to implement the test? Go for the low-hanging fruit first. \n\nEvery test that's developed should documented so that we can review and prioritize ideas that are inspired by winning tests. Some ideas worth experimenting are: Headlines, CTA (call to actions), check-out pages, forms and the elements include:\n\n- Wording. e.g. Call to action or value proposition.\n- Image. e.g. Replacing a general logistics image with the image of an actual employee.\n- Layout. e.g. Increased the size of the contact form or amount of content on the page.\n\n---\n\nSo given all of that a strong A/B test hypothesis may be:\n\n- If the call to action text is changed to \"Complete My Order\", the conversion rates in the checkout will icnrease, because the copy is more specific and personalized\n- If the navigation link is removed from checkout pages, the conversation rate will increase because our website analytics shows portions of our traffic drop out of the funnel by clicking on those links\n\n## Quantitative A/B testing\n\nSo now, suppose you're running an educational platform and your A/B testing hypothesis is : Will changing the \"Start Now\" button from orange to pink increase how many students explore the platform's courses. So in this case the metric that's use to evaluate the change's performance is the click through probability (unique visitors who click the button / unique visitors to page). Note that it is often times impractical to use metrices such as total number of students that completed the course as it often takes weeks or months before a student can do that.\n\nNext we will jot down the hypothesis that we wish to test out, in our case the our null and alternative hypothesis would be :\n\n- $H_0$: The experimental and control groups have the same probability of clicking the button. Or equivalent to saying that the differences of the two groups' probability is 0\n- $H_1$: The two groups have different probability of completing a clicking the button\n\n### Define the Size and Duration\n\nNow that we've defined our hypothesis, the first question that comes into mind is how many tests do we need to run, or in a sense how long should the test last in order for us to make our decisions. To do that we can use a power analysis for two independent samples:\n\nNow suppose that our current baseline is 0.1, i.e. there's a 10 percent chance that people who saw the button will click it and we wish to detect a change of 2 percent in the click through rate (This change is quite high for online experiment).\n\n\n```python\nsample_size = compute_sample_size(prop1 = 0.1, min_diff = 0.02)\nprint('sample size required per group:', sample_size)\n```\n\n    sample size required per group: 3834.5957398840183\n\n\nThe result shows that we need at least 3841 sample size for each scenario to detect if there will actually be a 2 percent more than baseline click through probability. Note that this is only telling us the minimum sample size required per group, we still need to decide when do we want to run the experiment and for how long.\n\ne.g. Suppose we\u2019ve chosen the goal to increase click-through rates, which is defined by the unique number of people who click the button versus the number of users who visited the page that the button was located. But to actually use the definition, we\u2019ll also have to address some other questions. Such as, if the same user visits the page once and comes back a week or two later, do we still only want to count that once? Thus we\u2019ll also need to specify a time period\n\nTo account for this, if 99% of our visitors convert after 1 week, then we should do the following.\n\n- Run our test for two weeks\n- Include in the test only users who show up in the first week. If a user shows up on day 13, we have not given them enough time to convert (click-through)\n- At the end of the test, if a user who showed up on day 2 converts more than 7 days after he/she first arrived, he must be counted as a non-conversion\n\nThere will be more discussion about this in the A/B Test Caveats & Advice section.\n\nFor this step, there is also an online calculator that non-technical audience could use. [Online Calculator: Sample Size Calculator](http://www.evanmiller.org/ab-testing/sample-size.html)\n\n## Define the Population\n\nAnother consideration is what fraction of the traffic are we going to send through the experiment. The key is to identify which population of our users will be affected by our experiment, we might want to target our experiment to that traffic (e.g. changing features specific to one language\u2019s users) so that the rest of the population won\u2019t dilute the effect.\n\nNext, depending on the problem we're looking at, we might want to use a cohort instead of a population. A cohort makes much more sense than looking at the entire population when testing out learning effects, examining user retention or anything else that requires the users to be established for some reason.\n\nA quick note on cohort. The gist of cohort analysis is basically putting our customers into buckets so we can track their behaviours over a period of time. The term cohort stands for a group of customers grouped by the timeline (can be week, month) where they first made a purchase (can be a different action that\u2019s valuable to the business). Having similar traits makes the two groups more comparable.\n\ne.g. You\u2019re an educational platform has an existing course that\u2019s already up and running. Some of the students have completed the course, some of them are midway through and there\u2019re students who have not yet started. If you want to change the structure of of one of the lessons to see if it improves the completion rate of the entire course and they started the experiment at time X. For students who have started before the experiment initiated they may have already finished the lesson already leading to the fact that they may not even see the change. So taking the whole population of students and running the experiment on them isn\u2019t what you want. Instead, you want to segment out the cohort, the group of customers, that started the lesson are the experiment was launched and split that into an experiment and control group.\n\n## Evaluating Result\n\nSuppose we have ran the test and we've obtain the total number of sample sizes and the total number of successes for both groups. Given these variables we can use it to calculate whether the proportional change was due to variation or not.\n\n\n```python\n# made-up results\nsuccess_a = 386\nsize_a = 3834\nsuccess_b = 530\nsize_b = 3842\n\nprob_diff, confint = two_proprotions_confint(success_a, size_a, success_b, size_b)\nprint('estimate difference:', prob_diff)\nprint('confidence interval:', confint)\n```\n\n    estimate difference: 0.03727084197203194\n    confidence interval: [ 0.02279256  0.05174912]\n\n\nIn order to launch a change, the change should be larger than the minimum detectable change that we wished to detect. In our case, the value we\u2019ve set was 0.02. Base on the result above, we can denote that since even the lower bound of the confidence interval is larger than the value, we\u2019ll definitely launch the newer version of the click button.\n\nThere is also an online calculator that we can use to perform the proportion test. [Online Calculator: AB Testguide](https://abtestguide.com/calc/)\n\n\n## Sanity Check\n\nWhen running experiments, especially online experiments, it's a good idea to check whether the experiments were setup properly, i.e. are the users being split equally amongst the two groups. For instance, after running your experiment for a week, you've discovered that the total number of users assigned to the control group is 64454 and the total number of users assigned to the experiment group 61818. How would you figure out whether the difference is within expectation given that each user is randomly assigned to the control or experiment group with a probability of 0.5? It's usually good idea to check this.\n\nThis is equivalent to saying out of a total 126272 (64454 + 61818) users, is it surprising to see if 64454 users are assigned to the control group? This is essentially a binomial distribution, thus, knowing this information, we can construct a confidence interval to test if the number lies within the confidence interval. The confidence interval can be calculated by the mean plus and minus the z-score times the standard error. \n\n\\begin{align}\nmean \\pm Z * \\sqrt{np(1 - p)}\n\\end{align}\n\nWhere the mean is expected number of users in the control / experiment group, which is simply the total number of the two groups times 0.5, since the probability of a user falling into either group is 50%. And the standard error of a binomial distribution is $\\sqrt{np(1-p)}$.\n\n\n```python\ndef sanity_check(size1, size2, significance = 0.05):\n    n = size1 + size2\n    confidence = 1 - significance\n    z = stats.norm.ppf(confidence + significance / 2)\n    confint = n * 0.5 + np.array([-1, 1]) * np.sqrt(n * 0.5 * 0.5)\n    return confint\n```\n\n\n```python\nsize1 = 64454\nsize2 = 61818\nsanity_check(size1, size2)\n```\n\n\n\n\n    array([ 62958.32614148,  63313.67385852])\n\n\n\nThe result shows that 64454 does not lie within the range of the computed 95 percent confidence interval and therefore it indicates the two groups may not be split equally. \n\nWhen this kind of situation happens it's usually best to go back to the day by day data to get a better idea of what could be going wrong. One good thing is to check whether any particular day stands out, or it is just an overall pattern. If it is an overall pattern, then it is suggested that we should check if something went wrong with the experiment setup before proceeding on to analyzing the result.\n\n# A/B Test Caveats & Advices\n\n\n## Avoid Biased Stopping Times\n\nNO PEEKING. When running an A/B test, we should avoid stopping the experiment as soon as the results \"look\" significant. Using a stopping time that is dependent upon the results of the experiment can inflate our false-positive rate substantially.\n\nRecall that in many experiments, we set the significance threshold to be 5% (or a p-value threshold of 0.05). This means that we\u2019ll accept that Variation A is better than Variation B if A beats B by a margin large enough that a false positive would only happen 5% of the time. If we, however, were to check the experiment with the intent of stopping it if it shows significance, then every time we perform the significance we're essentially inflating our false-positive rate. To be more explicit, every time we perform the test there's a 5% chance of false-positive, so in other words, 95% chance of drawing the right conclusion, if we perform it again then that means we need both test to be correct to draw the right conclusion, i.e. the probability of both test giving us the correct result now becomes (1 - 5%)(1 - 5%) and the probability of commiting a false positive error is now: 1 - (1 - 5%)(1 - 5%).\n\n\n```python\n# the false positive rate of conducting the test for n times\nsignificance = 0.05\n\nprint('conducting the test 2 times', 1 - (1 - significance) ** 2)\nprint('conducting the test 10 times', 1 - (1 - significance) ** 10)\n```\n\n    conducting the test 2 times 0.09750000000000003\n    conducting the test 10 times 0.4012630607616213\n\n\nThe easiest way to avoid this problem is to **choose a stopping time that's independent of the test results**. We could, for example, decide in advance to run the test for a fix amount of time, no matter the results we observed during the test's tenure. Thus just like in the template above, if 99% of your visitors convert after 1 week, then you should do the following.\n\n- Run your test for two weeks.\n- Include in the test only users who show up in the first week. If a user shows up on day 13, you have not given them enough time to convert.\n- At the end of the test, if a user who showed up on day 2 converts more than 7 days after he first arrived, he must be counted as a non-conversion.\n\nOr you could decide to run the test until each bucket has received more than 10,000 visitors, again ignoring the test results until that condition is met. There're tests like power tests that let's you determine how many tests you should run before you make a conclusion about the result. Although you should be very careful with this, because the truth is: It's not really the number of conversions that matters; it\u2019s whether the time frame of the test is long enough to capture variations on your site. \n\nFor instance, the website traffic may behave one way during the day and another way at night (the same holds on weekdays and weekends). Then it's worth noting that there are two effects that could occur when new features are introduced: **Primacy** and **Novelty** effect.\n\n- Primacy effect occurs when we change something and experienced users may be less efficient until they get used to the new feature, thus giving inherent advantage to the control (original version)\n- Novelty effect. Meaning when users are switched to a new experience, their initial reactions may not be their long-term reactions. In other words, if we are testing a new color for a button, the user may initially love the button and click it more often, just because it\u2019s novel, but eventually he/she would get used to the new color and behave as he/she did before. It\u2019s important to run the trial long enough to get past the period of the \"shock of the new\".\n\nIn sum, you should setting a results-independent stopping time (a week) is the easiest and most reliable way to avoid biased stopping times. Note that running the test for a least a week is adviced since it'll make sure that the experiment captures the different user behaviour of weekdays, weekends and try to avoid holidays ....\n\n## Do Follow Up Tests and Watch your Overall Success Rate\n\nIf you're running a lot of A/B tests, you should run follow-up tests and pay attention to your base success rate.\n\nLet's talk about these in reverse order. Imagine that we've done everything right. We set our stopping time in advance, and keep it independent from the test results. We set a relatively high success criterion: A probability of at least 95% that the variant is better than the control (formally, $p \\leq 0.05$). We do all of that.\n\nThen We run 100 tests, each with all the rigor just described. In the end, of those 100 tests, 5 of them claims that the variant will beat the control. How many of those variants do we think are really better than the control, though? If we run 20 tests in a row in which the \"best\" variant is worse or statistically indistinguishable from the control, then we should be suspicious when our 21st test comes out positive. If a button-color test failed to elicit a winner six months ago, but did produce one today, we should be skeptical. Why now but not then?\n\nHere's an intuitive way of thinking about this problem. Let\u2019s say we have a class of students who\neach take a 100-item true/false test on a certain subject. Suppose each student chooses randomly on all\nquestions. Each student would achieve a random score between 0 and 100, with an average of 50. \n\nNow take only the top scoring 10% of the class, and declaring them \"winners\", give them a second test, on\nwhich they again choose randomly. They will most likely score less on the second test than the first test. That's because, no matter what they scored on the first test they will still average 50 correct answers in the second test. This is what's called the **regression to the mean**. Meaning that tests which seem to be successful but then lose their uplift over time.\n\nIt can be wise to run our A/B tests twice (a validation test). You'll find that doing so helps to eliminate illusory results. If the results of the first test aren\u2019t robust, you\u2019ll see noticeable decay with the second. But, if the uplift is real, you should still see uplift during the second test. This approach isn\u2019t fail-safe but it will help check whether your results are robust. e.g. In a multiple testing, you tried out three variants, B, C, and D against the control A. Variant C won. Don't deploy it fully yet. Drive 50% of your traffic to Variant C and 50% to Variant A (or some modification on this; the percent split is not important as long as you will have reasonable statistical power within an acceptable time period). As this will give you more information about C's true performance relative to A.\n\nGiven the situation above, it's better to keep a record of previous tests, when they were run, the variants that were tried, etc. Since these historical record gives you an idea of what's reasonable. Despite the fact that this information is not directly informative of the rates you should expect from future tests (The absolute numbers are extremely time dependent, so the raw numbers that you get today will be completely different than the ones you would have gotten six months later), it gives you an idea of what's plausible in terms of each test's relative performance.\n\nAlso, by keeping a record of previous tests, we can avoid: \n\n- Falling into the trap of \"We already tried that\". A hypothesis can be implemented in so many different ways. If you just do one headline test and say \"we tried that,\" you\u2019re really selling yourself short.\n- Not testing continually or not retesting after months or years. Just because you tested a variation in the past doesn\u2019t necessarily mean that those results are going to be valid a year or two from now (Because we have the record of what we did, we can easily reproduce the test).\n\n## False Reporting\n\nLet's say you deploy a new feature to your product and wish to see if it increases the product's activation rate (or any other metric or KPI that's relevant to you). Currently the baseline of the product's activation rate is somewhere around 40%. After running the test, you realized that it WORKED, the activation went up to 50%. So you're like, YES! I just raised activation by 25%! and you sent this info to the head of product and ask for a raise. \n\nAfter two months, the head of product comes back to you and said \"you told me you raised the activation rate by 25%, shouldn't this mean that I should see a big jump in the overall activation? What's going on?\" Well, what's going on is, you did raised activation by 25%, but only for user who uses the product's feature. So if only 10 percent of your users use that product, then the overall increase in activation rate will probably only be around 2.5% (25% * 10%). Which is still probably very good, but the expectation that you've set by mis-reporting can get you into trouble.\n\n\n## Seasonality / Not Running it Against the Correct Target\n\nSuppose you have different types of users (or users with different usage patterns) using your product. e.g. business user and students. Then what can happen is your A/B testing will have different result in July versus October. The reason may be in July all your student users are out on vacation (not using your product) and in October after school starts they start using it again. This is simply saying that the weighting of your user population may be different in different times of the year (seasonality). Thus, you should be clear with yourself about who you're targeting.\n\n## Others\n\nDespite its useful functionality, there are still places where A/B testing isn't as useful. For example: \n\n- A/B testing can't tell us if we're missing something. Meaning it can tell you if A performs better B or vice versa, but it can't tell us that if we use C, then it will actually perform better than the former two.\n- Tesing out products that people rarely buy. e.g. cars, apartments. It might be too long before the user actually decides to take actions after seeing the information and we might be unaware of the actual motivation.\n- Optimizing for the funnel, rather than the product. Understanding what the customers want so that we can make the product better. Ultimately, we can\u2019t simply test our headlines and get people to like our product more.\n- Non-Randomized Bucketing: Double check if you're actually randomly splitting you're users, this will most likely burn you if your system assigns user id to users in a systematical way. e.g. user id whose last two digits are 70 are all from a specific region.\n- Conflicting test: Two different product teams both deployed new feautures on your landing page and ran the A/B test at the same period of time. This is more of a organization problem. You should probably require the product teams to register for their test, and make sure that multiple tests on the same stuff are not running at the same time, or else you might be tracking the effect of the other test.\n- Optimizing the wrong metric. The best example is probably noting that higher click through rate doesn't necessary means higher relevance. To be explicit, poor search results means people perform more searches, and thereby click on more ads. While this seems good in the short term, it's terrible in the long term, as users get more and more frustrated with the search engine. A search engine's goal should be to help users find what they want as quickly as possible, and sessions per user (increasing sessions per user means users are satisfied and returning) should probably be the key metric to showcase instead.\n\n# Reference\n\n- [Youtube: Beautiful A/B Testing](https://www.youtube.com/watch?v=EvDg7ssY0M8)\n- [Notebook: Statistics for Hackers](http://nbviewer.jupyter.org/github/croach/statistics-for-hackers/blob/master/statistics-for-hackers.ipynb)\n- [Blog: What Are P-Values?](https://prateekvjoshi.com/2013/12/07/what-are-p-values/)\n- [Blog: Interpreting A/B Test using Python](http://okomestudio.net/biboroku/?p=2375)\n- [Blog: So, You Need a Statistically Significant Sample?](http://multithreaded.stitchfix.com/blog/2015/05/26/significant-sample/)\n- [Blog: How to Build a Strong A/B Testing Plan That Gets Results](https://conversionxl.com/how-to-build-a-strong-ab-testing-plan-that-gets-results/)\n- [Blog: A/B testing and Pearson's chi-squared test of independence](http://thestatsgeek.com/2013/07/22/ab-testing/)\n- [Blog: A/B testing - confidence interval for the difference in proportions using R](http://thestatsgeek.com/2014/02/15/ab-testing-confidence-interval-for-the-difference-in-proportions-using-r/)\n- [Blog: Python for Data Analysis Part 23: Point Estimates and Confidence Intervals](http://hamelg.blogspot.com/2015/11/python-for-data-analysis-part-23-point.html)\n- [Notes: MOST winning A/B test results are illusory](http://www.qubit.com/sites/default/files/pdf/mostwinningabtestresultsareillusory_0.pdf)\n- [Notes: Eberly College of Science STAT 414/415 Comparing Two Proportions](https://onlinecourses.science.psu.edu/stat414/node/268)\n- [Quora: When should A/B testing not be trusted to make decisions?](https://www.quora.com/When-should-A-B-testing-not-be-trusted-to-make-decisions)\n- [Forbes: How To Do A/B Testing Right And Avoid The Most Common Mistakes Marketers Make](https://www.forbes.com/sites/sujanpatel/2015/10/29/how-to-do-ab-testing-right-and-avoid-the-most-common-mistakes-marketers-make/)\n- [Paper: R. Kohavi, A. Deng, B. Frasca, R. Longbotham, T. Walker, Y. Xu (2012) Trustworthy Online Controlled Experiments: Five Puzzling Outcomes Explained](http://notes.stephenholiday.com/Five-Puzzling-Outcomes.pdf)\n- [Slideshare: 4 Steps Toward Scientific A/B Testing](https://www.slideshare.net/RJMetrics/4-steps-toward-scientific-ab-testing)\n", "meta": {"hexsha": "3a9c908baf2be45cb719db9486b7e85088194f01", "size": 893068, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ab_tests/frequentist_ab_test.ipynb", "max_stars_repo_name": "Ani-singh/Insights---Data-Unicorn-12-Dec-17", "max_stars_repo_head_hexsha": "efdbde09e172613be96fbc5f069c9e3f893663d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ab_tests/frequentist_ab_test.ipynb", "max_issues_repo_name": "Ani-singh/Insights---Data-Unicorn-12-Dec-17", "max_issues_repo_head_hexsha": "efdbde09e172613be96fbc5f069c9e3f893663d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ab_tests/frequentist_ab_test.ipynb", "max_forks_repo_name": "Ani-singh/Insights---Data-Unicorn-12-Dec-17", "max_forks_repo_head_hexsha": "efdbde09e172613be96fbc5f069c9e3f893663d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 394.6389748122, "max_line_length": 130426, "alphanum_fraction": 0.911987665, "converted": true, "num_tokens": 21242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1066905939456512, "lm_q2_score": 0.09534945718704857, "lm_q1q2_score": 0.010172890219681652}}
{"text": "```python\nimport re\nfrom tqdm import tqdm\nimport pickle\nfrom functools import reduce\nimport mafan\nfrom mafan import text\nimport itertools\nimport sys\nimport os\nbos = \" <bos> \"\neos = \" <eos> \"\n```\n\n# Tokenizer Functions\n\n## Sentence Tokenizer\n\n\n```python\ndef zng(paragraph):\n    for sent in re.findall(u'[^!?\u3002\\.\\!\\?]+[!?\u3002\\.\\!\\?]?', paragraph, flags=re.U):\n        yield sent\n```\n\n## Simplified Chinese Tokenizer\n\nBelow is the code for simplified to traditional mapping dictionary.\n\nWe have a large dictionary *conversions.txt* that includes words, characters, common phrases, locations and idioms. Each entry contains the traditional chinese word and simplified chinese word.\n\n\n```python\ninfile = open(\"conversions.txt\", \"r+\", encoding=\"utf-8\")\n\ns2t_dict = dict()\n\nfor line in infile:\n    line = line.rstrip()\n    arr = line.split()\n    trad = arr[0]\n    sim = arr[1]\n    if sim not in s2t_dict:\n        s2t_dict[sim] = [trad]\n    else:\n        s2t_dict[sim].append(trad)\ns2t_dict['-'] = ['-']\n```\n\nTokeniser is used for identifying dictionary words and phrases in the input sentence. We always prefer longer phrases because it gives more meaning and less translation mappings. Hence we use Byte Pair Encoding (BPE) for identifying words, while BPE candidates are constrained by the defined list of vocabs in the dictionary. Since the longest phrase in the dictionary has 8 characters we start with 8-character phrases and do it backwards.\n\n\n```python\ndef tokenizer(sentence, n = 8):\n    '''\n    This function tokenizes input sentences according to the dicitionary.\n    Input: a sentence or paragraph\n    Output: a list of tokens from the input in order according to the original paragraph; a list of non-chinese characters from the original text.\n    '''\n    text, charList = prepare(sentence)\n    token_list = []\n    input_text = text\n    for k in range(n, 0, -1):\n        candidates = [input_text[i:i + k] for i in range(len(input_text) - k + 1)]\n        for candidate in candidates:\n            if candidate in s2t_dict:\n                token_list.append(candidate)\n                input_text = re.sub(candidate, '', input_text)\n    final = sequencer(token_list, text)\n    return final, charList\n```\n\n\n```python\ndef output_list(sentence_list, char_list):\n    count = 0\n    original = [] # sentence we want to output\n    \n    for word in sentence_list:\n        if \"-\" in word:\n            original.append(list(char_list[count]))\n            count += 1\n        else:\n            original.append(word)\n    return original\n```\n\n\n```python\ndef output(sentence, char_list):\n    count = 0\n    original = \"\" # sentence we want to output\n\n    for char in list(sentence):\n        if char == \"-\":\n            original += char_list[count] # append character if non-chinese\n            count += 1\n        else:\n            original += char # append chinese\n    return original\n```\n\n\n```python\ndef prepare(sentence):\n    new = \"\" # input to your tokenizer\n    char_list = [] # punct / english to be omitted\n\n    for char in list(sentence):\n        if text.identify(char) is mafan.NEITHER:\n            new += \"-\" # sub - with non-chinese chars\n            char_list.append(char)\n        else:\n            new += char\n\n    return new, char_list\n```\n\n\n```python\ndef sequencer(tokens, example):\n\n    flags = [1] * len(example)\n    sequence = []\n    for token in tokens:\n        for match in re.finditer(token, example):\n            location = (token, match.span()[0], match.span()[1])\n            valid = reduce(lambda x,y:x*y, flags[location[1]:location[2]])\n            if valid:\n                sequence.append(location)\n                for i in range(location[1], location[2]):\n                    flags[i] = 0\n            else:\n                continue\n    sequence.sort(key=lambda x: x[1])\n    result = [x[0] for x in sequence]\n    return result\n```\n\n## Corpus Preparation\n\nFirst, we need to prepare our corpus.\n1. We will add paddings (sentinels) to our sentences.\n2. Take one sentence at a time.\n3. Change non-chinese words to FW to avoid data explosion.\n4. Slice the n-grams and add them to dictionary\n\n\n```python\ndef add_stuff(order):\n    '''\n    This function divides the corpus into n-grams and stores them in dictionary.\n    Input: order of n-gram (like 2 for bi-gram)\n    Output: none\n    '''\n    infile = open(\"hk-zh.txt\", \"r+\") # this contains our corpus\n    start_padding = bos * order # add padding\n    end_padding = eos * order\n\n    for line in tqdm(infile, total=1314726):\n        line = line.rstrip()\n        sentences = list(zng(line)) # tokenize sentence by sentence\n        for sentence in sentences:\n            candidate = start_padding + sentence + end_padding # form sentence\n            word_list = candidate.split()\n            word_list_tokens = []\n            for word in word_list:\n                if not(bool(re.match('^[a-zA-Z0-9]+$', word))):\n                    word_list_tokens.append(word) # add if not chinese\n                else:\n                    word_list_tokens.append(\"FW\") # turn non-chinese (except punc) to FW\n            word_list = word_list_tokens\n            ordered = [word_list[i:i + order] for i in range(1, len(word_list) - order)] # extract n-grams through slicing\n            # for each ngram, convert to tuple and add to dictionary\n            for ngram in ordered:\n                ngram = tuple(ngram)\n                if ngram not in corpus:\n                    corpus[ngram] = 1\n                else:\n                    corpus[ngram] += 1\n```\n\nLet's say you want to extract till trigrams.\n\nWe want to do 3 iterations, for trigram, bi-gram and then unigram. Each iteration takes 2 minutes. This is only time-consuming part of this code. Once you prep the dictionary, you don't need to do this again.\n\n\n```python\ncorpus = dict()\nstart_order = 3\nfor i in range(start_order, 0, -1):\n    add_stuff(i)\n```\n\nOnce you made the dictionary, dump it into a pickle.\n\n\n```python\nimport pickle\nwith open('corpus.pkl', 'wb') as handle:\n    pickle.dump(corpus, handle)\n```\n\nHere's a way to load a pickle so you don't need to process data everytime.\n\n\n```python\nwith open('corpus.pkl', 'rb') as fp:\n    corpus = pickle.load(fp)\n```\n\n# Making Candidate Lists\n\n1. Tokenize the input.\n2. Check the mappings of each input.\n3. Add all possible mappings to candidate list.\n\n\n```python\ndef convert(sentence):\n    '''\n    Returns list of possible mappings.\n    Input: Simplified chinese sentence\n    Output: List of lists. Each list has a set of possible traditional chinese tokens\n    '''\n    tokens, char_list = tokenizer(sentence)\n    candidate_list = []\n    for token in tokens:\n        candidate_list.append(s2t_dict[token])\n    candidate_list = output_list(candidate_list, char_list)\n    return(candidate_list)\n```\n\n# Maximum log-likelihood calculations\n\nCompute the log likelihood of a sentence with different \\\\(\\alpha\\\\) penalties for unigram, bigram and trigrams.\n\n\n```python\nnum_tokens = 4526000 # total number of tokens in corpus\n\ndef prob(word_list, alpha_0 = 0.25, alpha_1 = 0.5, alpha_2 = 1.0):\n    '''\n    Computes the log likelihood probability.\n    Input: A sequence of words in form of list\n    Output: Log probabilties\n    '''\n    word_list = tuple(word_list) # change word list to tuple\n    if word_list in corpus:\n        # word found in dictionary\n        numerator = corpus[word_list] # get the frequency of that word list\n        denominator = num_tokens # let denominator be num tokens\n        # cutoff the last word and check whether it's in corpus\n        if len(word_list[:-1]) > 1 and word_list[:-1] in corpus:\n            denom_list = word_list[:-1]\n            denominator = corpus[denom_list]\n        if len(word_list[:-1]) == 1 and word_list[:-1] in corpus:       \n            return alpha_0 * log(numerator / denominator) # log of prob*alpha\n        elif len(word_list[:-1]) == 2 and word_list[:-1] in corpus:\n            return alpha_1 * log(numerator / denominator)\n        elif len(word_list[:-1]) == 3 and word_list[:-1] in corpus:\n            return alpha_2 * log(numerator / denominator)\n        else:\n            return log(numerator/denominator)\n    else:\n        word_list = list(word_list) # convert it back to list\n        k = len(word_list) - 1 # backoff, reduce n gram length\n        if k > 0:\n            # recursive function, divide the sequence into smaller n and find probs\n            probs = [prob(word_list[i:i + k]) for i in range(len(word_list) - k + 1)]\n            return sum(probs)\n        else:\n            # we found an unseen word\n            if not(bool(re.match('^[a-zA-Z0-9]+$', word_list[0]))):\n                return log(1 / num_tokens) # return a small probability\n            else:\n                return prob([\"FW\"]) # we encountered a non-chinese word\n```\n\n# Language Model\n\nGenerative n-gram language model that estimates the conditional probability of a word given its history in the n-gram. It's calculated by backing off through progressively shorter history models.\n\nStupid Backoff does not generate normalized probabilities. The main difference is that we don\u2019t apply any discounting and instead directly use the relative frequencies (S is used instead of P to emphasize that these are not probabilities but scores).\n\n\\\\(S(w^i|w^{i\u22121}_{i\u2212k+1}) = \n\\begin{cases}\n    \\frac{f(w^{i}_{i\u2212k+1})}{f(w^{i-1}_{i\u2212k+1})} & \\text{if } f(w^{i}_{i\u2212k+1})> 0\\\\\n    \\\\\\alpha S(w^i|w^{i\u22121}_{i\u2212k+2}),              & \\text{otherwise}\n\\end{cases}\n\\\\)\n\nWhere \\\\(\\alpha\\\\) is the backoff factor.\n\nStupid Backoff is inexpensive to calculate in a distributed environment while approaching the quality\nof Kneser-Ney smoothing for large amounts of data.\n\n\n```python\nfrom math import log\ndef backoff(sentence, order, alpha_0 = 0.25, alpha_1 = 0.5, alpha_2 = 1.0):\n    '''\n    Calcuates log likelihood using backoff language model\n    Input: Sentence and order of the n-gram\n    Output: Log prob of that sentence\n    '''\n    score = 0\n    sentences = list(zng(sentence)) # sentence tokenizer\n    for sentence in sentences:\n        start_padding = bos * order # beginning padding\n        end_padding = eos * order # ending padding\n        candidate = start_padding + sentence + end_padding # add paddings\n        word_list = candidate.split()\n        word_list_tokens = []\n        for word in word_list:\n            # append only non-chinese words\n            if not(bool(re.match('^[a-zA-Z0-9]+$', word))):\n                word_list_tokens.append(word)\n            else:\n                word_list_tokens.append(\"FW\")\n        word_list = word_list_tokens\n        ordered = [word_list[i:i + order] for i in range(1, len(word_list) - order)] # shingle into n-grams\n        probs = [prob(x, alpha_0, alpha_1, alpha_2) for x in ordered] # calculate probabilities\n        score += sum(probs) # final answer\n    return score\n```\n\n# Translator\n\nTake simplified sentence as input, generate candidate list for sentence.\nFor words with many to one mappings add the candidate to a temporary sentence, calculate perplexity and choose the option which gives the lowest perplexity.\n\nCall function to add back spaces at the end and output the final sentence.\n\n\n```python\ndef translate(sentence, alpha_0 = 0.25, alpha_1 = 0.5, alpha_2 = 1.0):\n    '''\n    Translate a given sentence to traditional\n    Input: Simplified Sentence\n    Output: Traditional Sentence\n    '''\n    candidates = convert(sentence) # get the candidate lists\n    final_sent = \"\"\n    for words in candidates:\n        if len(words) > 1:\n            # many to one mappings\n            score = -50000.0 # start with extreme negative value\n            likely = \"\"\n            for candidate in words:\n                temp = final_sent\n                temp = temp + \" \"  + candidate # add a candidate to temp sentence\n                current_score = backoff(temp, 3, alpha_0, alpha_1, alpha_2) # check perplexity\n                if current_score > score:\n                    # if performing good, include that\n                    score = current_score\n                    likely = candidate\n            final_sent = final_sent + \" \" + likely\n        else:\n            final_sent = final_sent + \" \" + words[0]\n    final_sent = final_sent.replace(\" \", \"\")\n    final_sent = add_back_spaces(sentence, final_sent) #call function to add the spaces back and output translation\n    return final_sent\n```\n\nAdd spaces back by enumerating through the original and the appended list.\n\n\n```python\ndef add_back_spaces(original, current):\n    current_list = list(current)\n    original_list = list(original)\n    count = 1\n    for index, char in enumerate(original_list):\n        if char == \" \":\n            current_list[index - count] += \" \"\n            count += 1\n    current = \"\".join(current_list)\n    return current\n```\n\nTest sentence for translate.\n\n\n```python\nsentence = \"\u65e9\u572823\u5c81\uff0c\u4f0d\u5179\u5c31\u53c2\u4e0e\u4e86\u4e16\u754c\u4e0a\u9996\u4e2a\u6838\u53cd\u5e94\u5806Chicago Pile-1\u7684\u5efa\u8bbe\uff0c\u5979\u662f\u5bfc\u5e08\u8d39\u7c73\u9886\u5bfc\u7684\u9879\u76ee\u56e2\u961f\u4e2d\u6700\u5e74\u8f7b\u7684\u4e00\u5458\u3002\u6b64\u5916\uff0c\u4f0d\u5179\u5728\u5efa\u7acb\u548c\u4f7f\u7528\u5b9e\u9a8c\u6240\u9700\u7684\u76d6\u9769\u8ba1\u6570\u5668\u4e0a\u8d77\u5230\u5173\u952e\u4f5c\u7528\u3002\u53cd\u5e94\u5806\u6210\u529f\u8fd0\u8f6c\u5e76\u8fbe\u5230\u81ea\u6301\u72b6\u6001\u65f6\uff0c\u5979\u4e5f\u662f\u552f\u4e00\u5728\u573a\u7684\u5973\u6027\u3002\u66fc\u54c8\u987f\u8ba1\u5212\u4e2d\uff0c\u5979\u4e0e\u8d39\u7c73\u5408\u4f5c\uff1b\u540c\u65f6\uff0c\u5979\u66fe\u4e0e\u7b2c\u4e00\u4efb\u4e08\u592b\u7ea6\u7ff0\u00b7\u9a6c\u6b47\u5c14\uff08John Marshall\uff09\u4e00\u540c\u89e3\u51b3\u4e86\u6c49\u798f\u5fb7\u533a\u949a\u751f\u4ea7\u5382\u6c19\u4e2d\u6bd2\u7684\u95ee\u9898\uff0c\u5e76\u8d1f\u8d23\u76d1\u7763\u949a\u751f\u4ea7\u53cd\u5e94\u7089\u7684\u5efa\u9020\u548c\u8fd0\u884c\u3002\"\na = translate(sentence)\nprint(a)\n```\n\n# Joint Probability Based Tokenizer\n\nGreedy tokenizer would generally work for most of the cases, however, it could lead to an undesirable segmentation, due to the preference towards longer chunks.\nWe propose a joint consideration for sub-word segmentation by considering both source and target sentences.\n\nA translator needs a source sentence $\\mathbf{S}$ consisting of segmentations where $\\mathbf{S} = s_0 s_1 \\dots s_n$ and a target sentence $\\mathbf{T}$ consisting of segmentations where $\\mathbf{T} = t_0 t_1 \\dots t_m$.\n\nWe want to find optimal arrangement of $\\mathbf{S}$ which is $\\mathbf{S}^*$ and optimal arrangement of $\\mathbf{T}$ which is $\\mathbf{T}^*$. Mathematically:\n\\begin{align}\n\\label{eq1}\n    \\mathbf{S}^*, \\mathbf{T}^* = \\underset{{s_i \\in \\mathbf{S}, t_j \\in \\mathbf{T}}}{\\operatorname{argmax}} P(\\mathbf{S}, \\mathbf{T})\n\\end{align}\nwhere $P(\\mathbf{S}, \\mathbf{T})$ is the joint probability of sequences. \n\nWe assume that the prior probabilities, which are $P(\\mathbf{S})$ and $P(\\mathbf{T})$, are language model based probabilities.\n\n\n```python\ndef dp_tokenizer(sentence):\n    s = sentence\n    global orig_len\n    orig_len = len(s)\n    return segment(s)\n```\n\n\n```python\nmodel = kenlm.Model(\"sim_train.klm\")\n```\n\n\n```python\ndef memo(f):\n    \"Memoize function f, whose args must all be hashable.\"\n    cache = {}\n    def fmemo(*args):\n        if args not in cache:\n            cache[args] = f(*args)\n        return cache[args]\n    fmemo.cache = cache\n    return fmemo\n```\n\n\n```python\ndef splits(text, start=0, L=20):\n    \"Return a list of all (first, rest) pairs; start <= len(first) <= L.\"\n    return [(text[:i], text[i:]) \n            for i in range(start, min(len(text), L)+1)]\n```\n\nWe chose Viterbi for segmentation the given sentence. The scoring function is obtained from the constructed language models.\n\nOptimal segmentation depends on the following:\n<ol>\n    <li>language model score of source sentence of a candidate segment.</li>\n    <li>language model score of target sentence of a candidate segment.</li>\n    <li>item mapping conversions from source segment to target segment</li>\n</ol>\n\n\n```python\n@memo\ndef segment(text):\n    \"Return a list of words that is the most probable segmentation of text.\"\n    if not text: \n        return []\n    else:\n        candidates = ([first] + segment(rest) \n                      for (first, rest) in splits(text, 1))\n        return max(candidates, key=Pwords)\n```\n\nTo avoid OOVs as output segmentations, we imposed a penalty on OOV outputs, which is given by: $\\alpha \\times \\frac{\\texttt{len(segment)}}{\\texttt{len(sentence)}}$. \n\n\n```python\npenalty_constant = 15.0\n```\n\n\n```python\ndef Pwords(words):\n    \"Probability of words, assuming each word is independent of others.\"\n    sentence = \" \".join(words)\n    score = 0\n    words_ = ['<s>'] + sentence.split() + ['</s>']\n    for i, (prob, length, oov) in enumerate(model.full_scores(sentence)):\n        if oov:\n            penalty = len(words_[i+1]) / orig_len\n            score += penalty_constant * prob * penalty\n        else:\n            score += prob\n    return score\n```\n\n\n```python\nimport string\nalphanumerics = 'a-zA-Z0-9'\nknown_stops = u'\u3002\u3002\u2026\uff01\uff1f'\nknown_punctuation = u'\uff0f\uff08\uff09\u3001\uff0c\u3002\uff1a\u300c\u300d\u2026\u3002\u300e\u300f\uff01\uff1f\u300a\u300b\u201c\u201d\uff1b\u2019 \u2018\u3010\u3011\u00b7\u3014\u3015'\neng_punct = string.punctuation\navoid = re.compile(\"([%s%s%s%s]+)\" % (alphanumerics, known_stops, known_punctuation, eng_punct))\n```\n\n# Tokenize Sentence\nTokenize sentence and output the tokens.\n\n\n```python\ndef tokenize_sentence(sentence):\n    split_words = re.split(avoid, sentence)\n    split_words_values = [(i, bool(re.search(avoid, i))) for i in split_words]\n    answer = []\n    for (word, value) in split_words_values:\n        segmented_text = []\n        if value == False:\n            orig_len = len(word)\n            segmented_text = dp_tokenizer(word)\n        else:\n            segmented_text = list(word)\n        for segs in segmented_text:\n            answer.append(segs)\n    return answer\n```\n\n\n```python\nsentence = \"\u59da\u677e\u708e\u3001\u5468\u5ead\u52bf\u88ab\u300cDQ\u300d? \u6cdb\u6c11\u8d28\u7591\uff0c\u653f\u5e9c\u518d\u53d6\u6d88\u53c2\u9009\u4eba\u8d44\u683c\u6d89\u653f\u6cbb\u7b5b\u9009\uff0c\u8981\u6c42\u5f8b\u653f\u53f8\u53f8\u957f\u90d1\u82e5\u9a85\u89e3\u91ca\u6cd5\u5f8b\u7406\u636e\u3002 \u6709\u62a5\u9053\u6307\uff0c\u636e\u5168\u56fd\u4eba\u5927\u5e38\u59d4\u4f1a\u5c31\u300a\u57fa\u672c\u6cd5\u300b\u7b2c\u4e00\u767e\u96f6\u56db\u6761\u8fdb\u884c\u7684\u91ca\u6cd5\uff0c\u4ee3\u8868\u6cdb\u6c11\u53c2\u9009\u7acb\u6cd5\u4f1a\u6e2f\u5c9b\u53ca\u4e5d\u9f99\u897f\u8865\u9009\u7684\u9999\u6e2f\u4f17\u5fd7\u5468\u5ead\u548c\u88ab\u300cDQ\u300d\u524d\u8bae\u5458\u59da\u677e\u708e\uff0c\u52bf\u88ab\u53d6\u6d88\u53c2\u9009\u8d44\u683c\u3002\u5f8b\u653f\u53f8\u8868\u793a\uff0c\u6cd5\u5f8b\u653f\u7b56\u4e13\u5458\u9ec4\u60e0\u51b2\u5c06\u4e8e\u7a0d\u540e\u65f6\u95f4\u4e0e\u6cdb\u6c11\u8bae\u5458\u4f1a\u9762\uff0c\u786e\u5b9e\u65f6\u95f4\u5f85\u5b9a\u3002 \u6c11\u4e3b\u6d3e\u8bae\u5458\u524d\u665a\u5728\u5f8b\u653f\u4e2d\u5fc3\u5916\u9759\u5750\u8981\u6c42\u4e0e\u5f8b\u653f\u53f8\u53f8\u957f\u90d1\u82e5\u9a85\u4f1a\u9762\u4e0d\u679c\u540e\uff0c\u6628\u5728\u7acb\u6cd5\u4f1a\u53ec\u5f00\u8bb0\u8005\u62db\u5f85\u4f1a\uff0c\u8981\u6c42\u90d1\u5c31\u64a4\u9500\u53c2\u9009\u4eba\u8d44\u683c\u7684\u7406\u636e\uff0c\u53ca\u5176\u7ed9\u4e88\u9009\u4e3e\u4e3b\u4efb\u7684\u6cd5\u5f8b\u610f\u89c1\u4f5c\u51fa\u8be6\u7ec6\u4ea4\u4ee3\u3002\u516c\u6c11\u515a\u8bae\u5458\u90ed\u8363\u94ff\u6279\u8bc4\uff0c\u90d1\u4e0d\u5411\u516c\u4f17\u4ea4\u4ee3\u7684\u505a\u6cd5\u662f\u300c\u5187\u627f\u62c5\uff0c\u5187\u8d23\u4efb\u300d\u7684\u8868\u73b0\uff0c\u4e0d\u80fd\u53ea\u628a\u8d23\u4efb\u4ea4\u6258\u4e88\u516c\u52a1\u5458\u3002\"\na = tokenize_sentence(sentence)\n```\n\n# Evaluation\n\nEvaluating the accuracy on 100 lines on sample test data.\n\n\n```python\nsim_filename = \"simplified100.txt\"\ntra_filename = \"traditional100.txt\"\n```\n\n\n```python\nchecklist = []\nfor key in s2t_dict:\n    if len(s2t_dict[key]) > 1:\n        for t in s2t_dict[key]:\n            checklist.append(t)\n```\n\nThe translated characters are matched with the original traditional corpus during evaluation. The mismatch characters include wrongly characters and variant characters. Variant characters are characters that are homophones and synonyms. In some cases, simplified characters can have multiple traditional variant characters mapped to them, which gives the same meaning and context. Thus a mismatch in this case does not necessarily means a incorrect conversion. However this is not a common case and does not affect the evaluation result substantially.\n\n\n```python\ndef eval(sim_filename, tra_filename, alpha_0 = 0.25, alpha_1 = 0.5, alpha_2 = 1.0):\n    \n    total = 0\n    correct = 0\n    wrong = 0\n    micro_total = 0\n    micro_correct = 0\n    \n    sim_file = open(sim_filename, \"r+\", encoding=\"utf-8\")\n    tra_file = open(tra_filename, \"r+\", encoding=\"utf-8\")\n    tra_lines = tra_file.readlines()\n    line_count = 0\n\n    for line in sim_file:\n\n        line = line.rstrip()\n\n        line = translate(line, alpha_0 , alpha_1 , alpha_2)\n        tra_line = tra_lines[line_count].rstrip()\n\n        if len(line) == len(tra_line):\n            char_count = 0\n            for c in line:\n                total = total + 1\n                if c == tra_line[char_count]:\n                    correct = correct + 1\n                else:\n                    # print(c + tra_line[char_count])\n                    wrong = wrong + 1\n\n                if tra_line[char_count] in checklist:\n                    micro_total += 1\n                    if c == tra_line[char_count]:\n                        micro_correct = micro_correct + 1\n\n                char_count = char_count + 1\n\n        line_count += 1\n    results = []\n    results.append(('Total', (total)))\n    results.append(('Correct' , (correct)))\n    results.append(('Wrong' , (wrong)))\n    results.append(('Percentage' , (correct/total*100)))\n    results.append(('Micro Total' , (micro_total)))\n    results.append(('Micro Correct' , (micro_correct)))\n    results.append(('Micro Percentage' , (micro_correct/micro_total*100)))\n    \n    return results\n```\n\nOverall Accuracy is defined as (no. of correctly converted characters) / (no. of converted characters). We also calculate the Micro-average accuracy to evaluate the performance for one-to-many character conversions only.\n\n\n```python\nprint(eval(sim_filename, tra_filename, 0.7, 0.5, 1))\n```\n\n# Hyper-Parameter Tuning\n\nTesting the evaluation function on the test set with multiple hyperparameter values in order to determine the optimal values for the hyperparameter.\n\n\n```python\noutfile = open('alpha_tuning.txt', 'w+')\nmax = [99.5, 0.25, 0.5, 1]\nfor a_0 in range(100, 10, -10):\n    for a_1 in range(100, 10, -10):\n        outfile.write(str(eval(sim_filename, tra_filename, alpha_0 = float(a_0)/100.0, alpha_1 = float(a_1)/100.0, alpha_2 = 1.0)) + \"a0: \" + str(a_0/100.0) + \" \" + \"a1: \" + str(a_1/100.0) + '\\n')\n```\n", "meta": {"hexsha": "fb835b7fadb520b9562c8e23d6afeb7b09c54e43", "size": 30577, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Part 1, Disambiguation and Conversion.ipynb", "max_stars_repo_name": "pranav-ust/2kenize", "max_stars_repo_head_hexsha": "b6be9997fe22a02427cb5e21bddc7f764cd71203", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2020-05-02T09:25:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T15:37:23.000Z", "max_issues_repo_path": "Part 1, Disambiguation and Conversion.ipynb", "max_issues_repo_name": "pranav-ust/2kenize", "max_issues_repo_head_hexsha": "b6be9997fe22a02427cb5e21bddc7f764cd71203", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-15T05:04:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-03T10:05:00.000Z", "max_forks_repo_path": "Part 1, Disambiguation and Conversion.ipynb", "max_forks_repo_name": "pranav-ust/2kenize", "max_forks_repo_head_hexsha": "b6be9997fe22a02427cb5e21bddc7f764cd71203", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-08T01:10:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-25T05:20:07.000Z", "avg_line_length": 33.2358695652, "max_line_length": 557, "alphanum_fraction": 0.5348464532, "converted": true, "num_tokens": 5530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1225232157222449, "lm_q2_score": 0.08269733702314093, "lm_q1q2_score": 0.010132343663741486}}
{"text": "# Data Augmentation Using Generative Adversarial Networks (GANs)\n\nNotebook to perform data augmentation using Generative Adversarial Networks (GANs). This notebook must be run after running the notebook `prepare_dataset_and_create_project_structure.ipynb` that should be available in the same directory.\n\n---\n## Prerequisites\n\n1. Ensure that the Cityscapes dataset is downloaded and placed in the directory named **dataset**. More information about the dataset can be found in the notebook `prepare_dataset_and_create_project_structure.ipynb` that should be available in the same directory. \n2. Run all the cells in the notebook `prepare_dataset_and_create_project_structure.ipynb` to understand the dataset, process the dataset, create the project structure required to ensure correct results from the project.\n\n### 1. Check Python version\n\nIt is crucial to ensure that the notebook runs on the correct version of Python to guarantee proper functionality. \n\n\n```python\nimport platform\nassert (platform.python_version_tuple()[:2] >= ('3','7')), \"[ERROR] The notebooks are tested on Python 3.7 and higher. Please updated your Python to evaluate the code\"\n```\n\n### 2. Check Notebook server has access to all required resources\n\n\n```python\nfrom pathlib import Path\n\ndataset_folder = Path(\"dataset\")\ndataset_folder = Path.joinpath(Path.cwd(), dataset_folder)\n\nif not dataset_folder.exists():\n    raise FileNotFoundError(\"[ERROR] Add `{}` folder in the current directory (`{}`)\".format(dataset_folder.name, Path.cwd()))\n```\n\n\n```python\ndataset_preparation_notebook = Path(\"prepare_dataset_and_create_project_structure.ipynb\")\ndataset_preparation_notebook = Path.joinpath(Path.cwd(), dataset_preparation_notebook)\n\nif not dataset_preparation_notebook.exists():\n    raise FileNotFoundError(\"[ERROR] The notebook `{}` is unavailable in the current directory (`{}`). Please download and run the notebook `{}` before this notebook to ensure proper results.\".format(dataset_preparation_notebook.name, Path.cwd(), dataset_preparation_notebook.name))\n```\n\n\n```python\ntest_dataset = Path.joinpath(dataset_folder, \"test_dataset\")\ntest_dataset_A = Path.joinpath(test_dataset, \"A\")\ntest_dataset_B = Path.joinpath(test_dataset, \"B\")\n\ntest_dataset_overall = [test_dataset, test_dataset_A, test_dataset_B]\n\nfor dataset in test_dataset_overall:\n    if not dataset.exists():\n        raise FileNotFoundError(\"[ERROR] The folder `{}` is unavailable. Please run the notebook `prepare_dataset_and_create_project_structure.ipynb` available in the current directory (`{}`) before running this notebook.\".format(dataset.name, Path.cwd()))\n```\n\n\n```python\ntraining_dataset = Path.joinpath(dataset_folder, \"training_dataset\")\ntraining_dataset_A = Path.joinpath(training_dataset, \"A\")\ntraining_dataset_B = Path.joinpath(training_dataset, \"B\")\n\ntraining_dataset_overall = [training_dataset, training_dataset_A, training_dataset_B]\n\nfor dataset in training_dataset_overall:\n    if not dataset.exists():\n        raise FileNotFoundError(\"[ERROR] The folder `{}` is unavailable. Please run the notebook `prepare_dataset_and_create_project_structure.ipynb` available in the current directory (`{}`) before running this notebook.\".format(dataset.name, Path.cwd()))\n```\n\n\n```python\nvalidatation_dataset = Path.joinpath(dataset_folder, \"validatation_dataset\")\nvalidatation_dataset_A = Path.joinpath(validatation_dataset, \"A\")\nvalidatation_dataset_B = Path.joinpath(validatation_dataset, \"B\")\n\nvalidatation_dataset_overall = [validatation_dataset, validatation_dataset_A, validatation_dataset_B]\n\nfor dataset in validatation_dataset_overall:\n    if not dataset.exists():\n        raise FileNotFoundError(\"[ERROR] The folder `{}` is unavailable. Please run the notebook `prepare_dataset_and_create_project_structure.ipynb` available in the current directory (`{}`) before running this notebook.\".format(dataset.name, Path.cwd()))\n```\n\n---\n## Introduction\n\nOne of the biggest bottlenecks in creating generalized deep learning models is a scarcity of high-quality data. The collection of high-quality data and its conversion is expensive. Most of the data collection methods are labor-intensive and error-prone, requiring considerable editing afterward to clean the data. Since large amounts of data are needed to achieve generalized deep learning models, standard data augmentation methods are routinely used to increase the dataset's generalizability. Data augmentation methods are also used when the datasets are imbalanced, improving the model's overall performance.\n\nGenerative Adversarial Networks, popularly known as GANs, are a novel method for data augmentation. The generation of artificial training data can not only be instrumental in situations such as imbalanced data sets, but it can also be useful when the original dataset contains sensitive information. In such cases, it is then desirable to avoid using the original data as much as possible (For example, Medical data).\n\nThis report proposes a GAN architecture based on a [paper](https://arxiv.org/abs/1611.07004) from UC Berkeley to perform data augmentation using the popular image-to-image translation method. Generative Adversarial Networks trained on these methods learn the mapping from an input image to an output image and learn a loss function to train this mapping. Therefore, this approach makes it possible to apply the same generic approach to problems that traditionally require very different loss formulations. In this particular report, we demonstrate that this approach can effectively synthesize photos from label maps. To evaluate the performance of the proposed GAN architecture, we utilize a standard dataset named Cityscapes. The Cityscapes Dataset focuses on semantic understanding of urban street scenes. The dataset contains 5000 images with detailed annotations and 20000 images with coarse annotations apart from the original images. \n\n---\n## Background Theory\n\nWith the advancements in deep learning, the most striking successes have involved discriminative models, usually those that map a high-dimensional, rich sensory input to a class label. These striking successes have primarily been based on the backpropagation and dropout algorithms, using piecewise linear units. However, deep generative models have had less impact due to the challenges of approximating many probabilistic computations that occur due to the usage of piecewise linear units in the generative context. \n\nGenerative Adversarial Networks, popularly known as GANs, is a machine learning framework class that sidesteps these difficulties by pitting the generative model against an adversary. In other words, a GAN is a machine learning framework where two neural networks compete against each other in a zero-sum game (i.e., one network's gain is the other network's loss). The two networks in a GAN can be considered as a generator and a discriminator. The generator learns to create images that look real, while the discriminator learns to tell real images apart from fakes. Competition in this game drives both networks to improve their models until the counterfeits are indistinguishable from the genuine images. An overview of the Generative Adversarial Network is represented below:\n\n\n\n<center>Image Courtesy: Google Developers (Link: https://developers.google.com/machine-learning/gan/gan_structure)</center>\n\nOne of the most significant characteristics of GANs is the lack of loss function. GANs learn the loss function to classify if the output image is real or fake while simultaneously training a generative model to minimize this loss. This property of GANs allows it to learn a loss that adapts to the data, making them a perfect solution to a multitude of tasks that traditionally would require very different kinds of loss functions such as image-to-image translation. The image-to-image translation is the task of translating one possible representation of a scene into another, given sufficient training data. Traditionally, each image-to-image translation task has been tackled with separate, special-purpose machinery, although the setting is always the same: predict pixels from pixels. The biggest problem with this approach is the need to formulate specialized loss functions that drive the neural network to do what we want \u2013 e.g., output sharp, realistic images. Fortunately, the need for specialized loss functions is precisely eliminated with the use of GANs. \n\n\n\nIn this report, we explore GANs in the conditional setting. Just as GANs learn a generative data model, conditional GANs (cGANs) learn a conditional generative model. In other words, just as GANs are generative models that learn a mapping from random noise vector $z$ to output image $y$, $G:\\,z\\,\\rightarrow\\,y$, the conditional GANs (cGANs) learn a mapping from observed image $x$ and random noise vector $z$, to output image $y$,$G:\\,\\{x,\\, z\\}\\,\\rightarrow\\,y$. This ability to map from an observed image to an output image makes cGANs fitting for image-to-image translation tasks, where we condition on an input image and generate a corresponding output image. \n\nFinally, to understand the objective function of the conditional GANs (i.e., cGANS), let us first examine the objective function of a traditional GAN. The equation below refers to the objective function of a traditional GAN.\n\n$$\n\\begin{align}\n\\mathbb{L}_{GAN}(G,D)\\,=\\,&\\mathbb{E}_{y}[logD(y)]\\,+\\, \\\\\n&\\mathbb{E}_{x\\,,\\,z}[log(1\\,-\\,D(G(x\\,,\\,z)))]\n\\end{align}\n$$\n\nIt can be observed from the Equation above that Generator $G$ tries to minimize the objective function against an adversarial $D$ that tries to maximize it. Therefore, the optimal value of G can be represented as the equation below.\n\n$$\n\\begin{align}\nG^{*}\\,=\\,arg\\,min_{G}\\,max_{D}\\,\\mathbb{L}_{GAN}(G\\,,\\,D)\n\\end{align}\n$$\n\nBased on the Equation above, the objective function of a conditional GAN can be represented as Equation below.\n\n$$\n\\begin{align}\n\\mathbb{L}_{cGAN}(G,D)\\,=\\,&\\mathbb{E}_{x\\,,\\,y}[logD(x\\,,\\,y)]\\,+\\, \\\\\n&\\mathbb{E}_{x\\,,\\,z}[log(1\\,-\\,D(x\\,,\\,G(x\\,,\\,z)))]\n\\end{align}\n$$\n\nSimilar to the equation above, Generator $G$ tries to minimize the objective function against an adversarial $D$ that tries to maximize it. By training both $G$ and $D$ on the objective function $\\mathbb{L}_{cGAN}(G\\,,\\,D)$ simultaneously, the optimal values for both the parameters can be calculated.\n\n---\n## Proposed Solution\n\n### 0. Imports\n\n\n```python\nimport os\nimport glob\nimport time\nimport numpy as np \nimport scipy as sp\nfrom imageio import imread\nimport matplotlib.pyplot as plt\nfrom keras.optimizers import Adam\nfrom keras.models import Sequential, Model\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.layers.convolutional import UpSampling2D, Conv2D\nfrom keras.layers import BatchNormalization, Activation, ZeroPadding2D\nfrom keras.layers import Input, Dense, Reshape, Flatten, Dropout, Concatenate\n```\n\n### 1. Load Data\n\nAs mentioned in the previous sections, the Cityscapes dataset was used to translate photos from label maps. The Cityscapes Dataset is perfect for our project as the dataset focuses on semantic understanding of urban street scenes. The dataset contains 5000 images with detailed annotations and 20000 images with coarse annotations apart from the original images. Some sample images from the dataset are presented in below:\n\n\n\n\n\n\n<center>Image Courtesy: Cityscapes Datatset (Link: https://www.cityscapes-dataset.com/)</center>\n\n\n```python\ndef draw_randomized_data(sample_size, dataset_type=\"training\"):\n    \"\"\"\n    Function to draw randomized data samples from dataset. This function would be required while displaying training output.\n    \n    Parameters\n    ----------\n    sample_size  : Number of data samples to be loaded (type=int)\n    dataset_type : Type of dataset to draw randomized data samples from (type=str) \n    \n    Returns\n    -------\n    random_ground_truth_data  : Randomized \"Ground Truth Data\" drawn from the dataset \"dataset_type\" (type=list)\n    random_input_data         : Randomized \"Input Data\" drawn from the dataset \"dataset_type\" (type=list)\n    \"\"\"\n    \n    # Calculate Dataset Paths\n    if(dataset_type == \"training\"):\n        ground_truth_dataset_expr = str(training_dataset_A) + \"\\\\**\\\\*.jpg\"\n        input_dataset_expr = str(training_dataset_B) + \"\\\\**\\\\*.jpg\"\n    else:\n        ground_truth_dataset_expr = str(validatation_dataset_A) + \"\\\\**\\\\*.jpg\"\n        input_dataset_expr = str(validatation_dataset_B) + \"\\\\**\\\\*.jpg\"\n        \n    ground_truth_dataset_paths = glob.glob(ground_truth_dataset_expr, recursive=True)\n    ground_truth_dataset_paths = sorted(ground_truth_dataset_paths)\n   \n    input_dataset_paths = glob.glob(input_dataset_expr, recursive=True)\n    input_dataset_paths = sorted(input_dataset_paths)\n    \n    # Check if Datasets Are Modified After Preprocessing\n    assert (len(ground_truth_dataset_paths) == len(input_dataset_paths)), (\"[ERROR] Datasets Modified After Preprocessing! Please reload the dataset from the beginning!\")\n    \n    # Draw Random Samples from the dataset\n    random_data_samples = np.random.choice(range(len(ground_truth_dataset_paths)), sample_size) # Pick any random data from the dataset\n   \n    random_ground_truth_data = []\n    random_input_data = []\n    \n    # Process Randomly Chosen Samples\n    for random_sample in random_data_samples:\n        \n        ground_truth_data_path = ground_truth_dataset_paths[random_sample]\n        input_data_path = input_dataset_paths[random_sample]\n        \n        ground_truth_data = imread(ground_truth_data_path)\n        input_data = imread(input_data_path)\n        \n        # Perform Basic Transformations to Avoid Overfitting\n        if((dataset_type != \"training\") and (np.random.random() > 0.5)):\n            ground_truth_data = np.fliplr(ground_truth_data)\n            input_data = np.fliplr(input_data)\n        \n        random_ground_truth_data.append(ground_truth_data)\n        random_input_data.append(input_data)\n    \n    # Normalizing the image between [-1, 1] since tanh() activation functions are used\n    random_ground_truth_data = np.array(random_ground_truth_data)/127.5 - 1\n    random_input_data = np.array(random_input_data)/127.5 - 1\n    \n    return random_ground_truth_data, random_input_data\n```\n\n\n```python\ndef load_batches(batch_size, dataset_type=\"training\"):\n    \"\"\"\n    Function to load batches. This function would be required while training the neural network.\n    \n    Parameters\n    ----------\n    batch_size   : Size of the batches to be loaded (type=int)\n    dataset_type : Type of dataset to load batches from (type=str) \n    \n    Yeilds (Returns a Generator and Not an Iterator [IMPORTANT!])\n    ------\n    ground_truth_data_batch  : Batch of \"Ground Truth Data\" loaded from the dataset \"dataset_type\" (type=list)\n    input_data_batch         : Batch of \"Input Data\" loaded from the dataset \"dataset_type\" (type=list)\n    \"\"\"\n    \n    # Calculate Dataset Paths\n    if(dataset_type == \"training\"):\n        ground_truth_dataset_expr = str(training_dataset_A) + \"\\\\**\\\\*.jpg\"\n        input_dataset_expr = str(training_dataset_B) + \"\\\\**\\\\*.jpg\"\n    else:\n        ground_truth_dataset_expr = str(validatation_dataset_A) + \"\\\\**\\\\*.jpg\"\n        input_dataset_expr = str(validatation_dataset_B) + \"\\\\**\\\\*.jpg\"\n        \n    ground_truth_dataset_paths = glob.glob(ground_truth_dataset_expr, recursive=True)\n    ground_truth_dataset_paths = sorted(ground_truth_dataset_paths)\n   \n    input_dataset_paths = glob.glob(input_dataset_expr, recursive=True)\n    input_dataset_paths = sorted(input_dataset_paths)\n    \n    # Check if Datasets Are Modified After Preprocessing\n    assert (len(ground_truth_dataset_paths) == len(input_dataset_paths)), (\"[ERROR] Datasets Modified After Preprocessing! Please reload the dataset from the beginning!\")\n    \n    # Load Batches\n    for batch_iterator in range(int(len(ground_truth_dataset_paths)/batch_size) - 1):\n\n        ground_truth_dataset_paths_batch = ground_truth_dataset_paths[(batch_iterator)*batch_size:(batch_iterator+1)*batch_size]\n        input_dataset_paths_batch = input_dataset_paths[(batch_iterator)*batch_size:(batch_iterator+1)*batch_size]\n\n        ground_truth_data_batch = []\n        input_data_batch = []\n\n        for (ground_truth_data_path_iterator, input_data_path_iterator) in zip(ground_truth_dataset_paths_batch, input_dataset_paths_batch):\n\n            ground_truth_data = imread(ground_truth_data_path_iterator)\n            input_data = imread(input_data_path_iterator)\n           \n            # Perform Basic Transformations to Avoid Overfitting\n            if((dataset_type != \"training\") and (np.random.random() > 0.5)):\n                ground_truth_data = np.fliplr(ground_truth_data)\n                input_data = np.fliplr(input_data)\n        \n            ground_truth_data_batch.append(ground_truth_data)\n            input_data_batch.append(input_data)\n        \n        # Normalizing the image between [-1, 1] since tanh() activation functions are used\n        ground_truth_data_batch = np.array(ground_truth_data_batch)/127.5 - 1\n        input_data_batch = np.array(input_data_batch)/127.5 - 1\n        \n        # Return a Generator Object that Calculates the Batches \"On-the-fly\"\n        yield ground_truth_data_batch, input_data_batch\n```\n\n### 2. Define cGAN Architecture\n\n**The Generator**\n\nA defining feature of image-to-image translation problems is that they map a high-resolution input grid to a high-resolution output grid. Furthermore, for the problems we consider, although the input and output differ in surface appearance, both are renderings of the same underlying structure. Since the input structure is roughly aligned with the structure in the output, an encoder-decoder network is used as a generator layer.  In an encoder-decoder network, the input is passed through a series of layers that progressively downsample. This process is continued until a bottleneck layer, at which point the process is reversed. Such a network requires that all information flow through all the layers, including the bottleneck. For many image translation problems, there is a great deal of low-level information shared between the input and output, and it would be desirable to shuttle this information directly across the net. Therefore, to allow the Generator network to map the representation of the input image and the output image, the U-Net architecture was chosen based on the suggestion from UC Berkley paper. The generator architecture chosen is represented in figure below. \n\n\n\n\n```python\ndef build_generator():\n    \"\"\"\n    Closure Function to Build A Generator for cGAN.\n    \n    Parameters\n    ----------\n    None\n    \n    Returns\n    -------\n    Model   : Generator Model for cGAN (type=tf.keras.models.Model)\n    \"\"\"\n    def conv2d(input_layer, filters, filter_shape=4, batch_normalization=True):\n        \"\"\"\n        Nested Function to create a 2D-Convolution Layer\n        \n        Parameters\n        ----------\n        input_layer         : Input Layer to the 2D-Convolution Layer\n        filters             : Number of filters in the convolution\n        filter_shape        : Size of the 2D convolution window\n        batch_normalization : Flag to set Batch Normalization\n        \n        Returns\n        -------\n        d    : 2D-Convolution Layer\n        \"\"\"\n        d = Conv2D(filters, kernel_size=filter_shape, strides=2, padding='same')(input_layer)\n        d = LeakyReLU(alpha=0.2)(d)\n        if(batch_normalization == True):\n            d = BatchNormalization(momentum=0.8)(d)\n            \n        return d\n    \n    def deconv2d(input_layer, skip_input, filters, filter_shape=4, dropout_rate=0):\n        \"\"\"\n        Nested Function to create a 2D-Deconvolution Layer\n        \n        Parameters\n        ----------\n        input_layer   : Input Layer to the 2D-Convolution Layer\n        skip_input    : Input Layer to be Skipped (i.e., Inputs of this layer are concatenated)\n        filters       : Number of filters in the convolution\n        filter_shape  : Size of the 2D convolution window\n        dropout_rate  : Dropout Rate\n        \n        Returns\n        -------\n        u    : 2D-Deconvolution Layer\n        \"\"\"\n        u = UpSampling2D(size=2)(input_layer)\n        u = Conv2D(filters, kernel_size=filter_shape, strides=1, padding='same', activation='relu')(u)\n        if dropout_rate:\n            u = Dropout(dropout_rate)(u)\n        u = BatchNormalization(momentum=0.8)(u)\n        u = Concatenate()([u, skip_input]) #skip connection\n        \n        return u\n    \n    \n    d0 = Input(shape=image_shape)\n\n    # Downsampling\n    d1 = conv2d(d0, gf, batch_normalization=False)\n    d2 = conv2d(d1, gf*2)\n    d3 = conv2d(d2, gf*4)\n    d4 = conv2d(d3, gf*8)\n    d5 = conv2d(d4, gf*8)\n    d6 = conv2d(d5, gf*8)\n    d7 = conv2d(d6, gf*8)\n\n    # Upsampling\n    u1 = deconv2d(d7, d6, gf*8)\n    u2 = deconv2d(u1, d5, gf*8)\n    u3 = deconv2d(u2, d4, gf*8)\n    u4 = deconv2d(u3, d3, gf*4)\n    u5 = deconv2d(u4, d2, gf*2)\n    u6 = deconv2d(u5, d1, gf)\n\n    u7 = UpSampling2D(size=2)(u6)\n    generated_image = Conv2D(channels, kernel_size=4, strides=1, padding='same', activation='tanh')(u7)\n\n    return Model(d0, generated_image)\n```\n\n**The Discriminator**\n\nFor the discriminator, we decided to use a convolutional *PatchGAN* classifier, which penalizes the Generator based on the scale of image patches, the same as in the UC Berkley paper. Therefore, the discriminator tries to classify if each patch in an image is real or fake. We run this discriminator convolutionally across the image, averaging all responses to provide the ultimate output. One of the most significant advantages of this approach is that the patch can be much smaller than the full size of the image and still produce high-quality results. Having a smaller discriminator like PatchGAN is advantageous as the network has fewer parameters, runs faster, and can be applied to arbitrarily large images.\n\n\n```python\ndef build_discriminator():\n    \"\"\"\n    Closure Function to Build A Discriminator for cGAN.\n    \n    Parameters\n    ----------\n    None\n    \n    Returns\n    -------\n    Model   : Discriminator Model for cGAN (type=tf.keras.models.Model)\n    \"\"\"\n    def d_layer(input_layer, filters, filter_shape=4, batch_normalization=True):\n        \"\"\"\n        Nested Function to create a single layer discriminator\n        \n        Parameters\n        ----------\n        input_layer         : Input Layer to the 2D-Convolution Layer\n        filters             : Number of filters in the convolution\n        filter_shape        : Size of the 2D convolution window\n        batch_normalization : Flag to set Batch Normalization\n        \n        Returns\n        -------\n        d    : Discriminator layer\n        \"\"\"\n        d = Conv2D(filters, kernel_size=filter_shape, strides=2, padding='same')(input_layer)\n        d = LeakyReLU(alpha=0.2)(d)\n        if batch_normalization:\n            d = BatchNormalization(momentum=0.8)(d)\n            \n        return d\n    \n    ground_truth_image = Input(shape=image_shape)\n    input_image = Input(shape=image_shape)\n\n    # Concatenate image and conditioning image by channels to produce input\n    combined_images = Concatenate(axis=-1)([ground_truth_image, input_image])\n\n    d1 = d_layer(combined_images, df, batch_normalization=False)\n    d2 = d_layer(d1, df*2)\n    d3 = d_layer(d2, df*4)\n    d4 = d_layer(d3, df*8)\n\n    validity = Conv2D(1, kernel_size=4, strides=1, padding='same')(d4)\n\n    return Model([ground_truth_image, input_image], validity)\n```\n\n### 3. Training\n\nTo optimize our networks, we follow the standard approach from the UC Berkley paper. We use minibatch SGD and apply the Adam solver, with a learning rate of 0.0002.\n\n\n```python\n# Input shape\nimage_rows = 128\nimage_columns = 128\nchannels = 3\nimage_shape = (image_rows, image_columns, channels)\n\n# Calculate output shape of D (PatchGAN)\npatch = int(image_rows / 2**4)\ndiscriminator_patch = (patch, patch, 1)\n\n# Number of filters in the first layer of G and D\ngf = 64\ndf = 64\n\noptimizer = Adam(0.0002, 0.5)\n\n# Build and compile the discriminator\ndiscriminator = build_discriminator()\ndiscriminator.compile(loss='mse', optimizer=optimizer, metrics=['accuracy'])\n\n# Build the generator\ngenerator = build_generator()\n\n# Input images and their conditioning images\nground_truth_image = Input(shape=image_shape)\ninput_image = Input(shape=image_shape)\n\n# By conditioning on B generate a fake version of A\ngenerated_ground_truth_image = generator(input_image)\n\n# For the combined model we will only train the generator\ndiscriminator.trainable = False\n\n# Discriminators determines validity of translated images / condition pairs\nvalid = discriminator([generated_ground_truth_image, input_image])\n\ngan = Model(inputs=[ground_truth_image, input_image], outputs=[valid, generated_ground_truth_image])\ngan.compile(loss=['mse', 'mae'], loss_weights=[1, 100], optimizer=optimizer)\n```\n\n\n```python\n# Function to display output\n\ndef display_output(output_data_type, number_of_outputs=3):\n    \n    real_ground_truth_images, input_images = draw_randomized_data(number_of_outputs, dataset_type=output_data_type)\n    \n    generated_ground_truth_image = generator.predict(input_images)   \n    overall_generated_images = np.concatenate(input_images, generated_ground_truth_image, real_ground_truth_images)\n    \n    # Rescale Image\n    overall_generated_images = 0.5 * overall_generated_images + 0.5\n    \n    titles = [\"Input\", \"Output\", \"Ground Truth\"]\n    f, axarr = plt.subplots(3, number_of_outputs, figsize=(20,30))\n    \n    for row_iterator in range(3):\n        for column_iterator in range(number_of_outputs):\n            axarr[row_iterator, column_iterator].imshow(overall_generated_images[row_iterator + column_iterator])\n            axarr[row_iterator, column_iterator].set_title(titles[row_iterator])\n            axarr[row_iterator, column_iterator].axis(\"off\")\n    \n    plt.show()\n    plt.close()\n```\n\n\n```python\n# Function to perform training\ndef train_neural_network(epochs, batch_size, display_interval=10):\n    \n    start_time = time.time()\n    print(\"cGAN Training started at {}\".format(time.asctime(time.localtime(start_time))))\n    \n    # Calculate Batch Shape and Target Values\n    batch_shape = (batch_size,) + discriminator_patch    # Joining Tuples to create a batch shape of dimensions: (batch, height, width, channels)\n    target_real_images = np.ones(batch_shape)\n    target_fake_images = np.zeros(batch_shape)\n    \n    # Initialize Generaor and Discriminator Losses\n    generator_loss_overall = []\n    discriminator_loss_overall = []\n    \n    for current_epoch in range(epochs):\n        \n        for batch_iterator, (ground_truth_images, input_images) in enumerate(load_batches(batch_size)):\n            \n            # Generate Fake Ground Truth Images\n            generated_ground_truth_image = generator.predict(input_images)\n            \n            # Train Discriminator\n            discriminator_loss_real_ground_truth = discriminator.train_on_batch([ground_truth_images, input_images], target_real_images)\n            discriminator_loss_fake_ground_truth = discriminator.train_on_batch([generated_ground_truth_image, input_images], target_fake_images)\n            \n            print(discriminator_loss_fake_ground_truth)\n            print(type(discriminator_loss_fake_ground_truth))\n            print(discriminator_loss_fake_ground_truth.shape)\n            \n            discriminator_loss_current = 0.5*np.add(discriminator_loss_real_ground_truth, discriminator_loss_fake_ground_truth)\n            \n            print(discriminator_loss_current)\n            print(type(discriminator_loss_current))\n            print(discriminator_loss_current.shape)\n            \n            # Train Generator\n            generator_loss_current = gan.train_on_batch([ground_truth_images, input_images], [target_real_images, ground_truth_images])\n            \n            print(generator_loss_current)\n            print(type(generator_loss_current))\n            print(generator_loss_current.shape)\n        \n            # Calculate Elapsed Time\n            current_time = time.time()    \n            elapsed_time = current_time - start_time  \n            \n        # Append Losses\n        generator_loss_overall.append(generator_loss_current)\n        discriminator_loss_overall.append(discriminator_loss_current)\n        \n        # Display Results\n        print(f\"Epoch: {current_epoch + 1}/{epochs}, Generator Loss: {generator_loss_current:.2f}, Discriminator Loss: {discriminator_loss_current:.2f}, Elapsed Time: {elapsed_time:.2f}\")\n        \n        # Display Images\n        if(current_epoch % display_interval == 0):\n            display_output(output_data_type=\"training\")\n```\n\n\n```python\ntrain_neural_network(epochs=50, batch_size=32, display_interval=1)\n```\n\n---\n## Results\n\n\n```python\ndisplay_output(output_data_type=\"training\")\n```\n\n\n```python\ndisplay_output(output_data_type=\"validation\")\n```\n\n---\n## Conclusions\n\n**Conclusion**\n\nBased on the outputs from different epochs in figures above, it can be observed how the translation of the images improves over time\u2014starting with a very foggy version of the grounded truth image, the model produces a sharper and more precise image. The final version shows a much-improved image. However, the synthetic image is still a somewhat blurry version of the ground truth image.  Although the results were not as realistic as what we desired, it shows the real potential of the cGAN in producing content that can increase/diversify the existing dataset. \n\nOne of the biggest challenges that we faced while training the network was the vanishing gradients problem. Due to the complicated networks used, the discriminator got too successful multiple times, causing the generator gradient to vanish. Another challenge that we faced was the implementation of the network. GANs are known for being notoriously difficult to implement and train, and even the slightest imbalance between the parameters of the Generator and Discriminator can cause the model to fail.\n\nLastly, evaluating the quality of synthesized images is an open and challenging problem. Traditional metrics such as per-pixel mean-squared error do not assess the image's quality, and therefore do not measure the very structure that structured losses aim to capture. In other words, there is no standard metric similar to a confusion metric for classifiers to evaluate the performance of the network. Therefore, to holistically evaluate our results' visual quality, we considered the plausibility to a human observer as the ultimate goal.\n\n**Future Work**\n\nThis project's original plan was to use datasets relating to the health care industry, such as MRI scans or X-ray images. Unfortunately, this was not possible because of the lack of quality data. Nevertheless, the method proposed can be considered a good starting point to further research into the potential of data augmentation. The method proposed in this report could prove particularly prove useful in solving imbalances in medical datasets, ultimately leading to better prediction models. A comparison between a classifier's performance trained on real data and artificial data can be the next logical step.\n\n\n```python\n\n```\n", "meta": {"hexsha": "2a311649bcc378b2bcdec6c05b89afe97dc6e6c1", "size": 40856, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "data_augmentation_using_generative_adversarial_networks.ipynb", "max_stars_repo_name": "sourabbapusridhar/data-augmentation-using-generative-adversarial-networks", "max_stars_repo_head_hexsha": "b0cbcaea134581348d887b514e43f016aa805d93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-07T20:27:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-07T20:27:46.000Z", "max_issues_repo_path": "data_augmentation_using_generative_adversarial_networks.ipynb", "max_issues_repo_name": "sourabbapusridhar/data-augmentation-using-generative-adversarial-networks", "max_issues_repo_head_hexsha": "b0cbcaea134581348d887b514e43f016aa805d93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-05T06:44:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-07T10:47:57.000Z", "max_forks_repo_path": "data_augmentation_using_generative_adversarial_networks.ipynb", "max_forks_repo_name": "sourabbapusridhar/data-augmentation-using-generative-adversarial-networks", "max_forks_repo_head_hexsha": "b0cbcaea134581348d887b514e43f016aa805d93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-07T20:28:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T20:28:02.000Z", "avg_line_length": 48.6380952381, "max_line_length": 1198, "alphanum_fraction": 0.6339338163, "converted": true, "num_tokens": 6760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423539898095244, "lm_q2_score": 0.03114382749980288, "lm_q1q2_score": 0.010097931335192545}}
{"text": "```python\n%conda info -e\n#%pip install yfinance\n%conda env export > requirements.yml\n\n```\n\n    # conda environments:\n    #\n    base                     C:\\ProgramData\\Anaconda3\n    tensorflow1              C:\\ProgramData\\Anaconda3\\envs\\tensorflow1\n    wordcount                C:\\ProgramData\\Anaconda3\\envs\\wordcount\n    fortran                  C:\\Users\\salmasi\\.conda\\envs\\fortran\n    tensorflow_1.15       *  C:\\Users\\salmasi\\.conda\\envs\\tensorflow_1.15\n    \n    \n    Note: you may need to restart the kernel to use updated packages.\n    \n    Note: you may need to restart the kernel to use updated packages.\n\n\n\n```python\nimport numpy as np\nimport sympy as sym\nimport matplotlib.pyplot as plt\nimport scipy as scp\nfrom math import erf\nimport yfinance as yf\nimport collections\nfrom pandas_datareader import data as pdr\nimport numpy as np\nfrom sklearn.preprocessing import scale\nfrom TFANN import ANNR\nimport pandas as pd\n```\n\n    C:\\Users\\salmasi\\.conda\\envs\\tensorflow_1.15\\lib\\site-packages\\pandas_datareader\\compat\\__init__.py:7: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.\n      from pandas.util.testing import assert_frame_equal\n\n\n\n```python\n#aapl = yf.Ticker(\"aapl\")\naapl = yf.Ticker(\"ibm\")\n\n#print(aapl)\nprint(aapl.info)\naapl.history(period=\"max\")\n```\n\n    {'zip': '10504', 'sector': 'Technology', 'fullTimeEmployees': 352600, 'longBusinessSummary': \"International Business Machines Corporation operates as an integrated solutions and services company worldwide. Its Cloud & Cognitive Software segment offers software for vertical and domain-specific solutions in health, financial services, and Internet of Things (IoT) application areas; and customer information control system and storage, and analytics and integration software to support client mission critical on-premise workloads in banking, airline, and retail industries. It also offers middleware and data platform software, including Red Hat, which enables the operation of clients' hybrid multi-cloud environments; and Cloud Paks, WebSphere distributed, and analytics platform software, such as DB2 distributed, information integration, and enterprise content management, as well as IoT, Blockchain and AI/Watson platforms. The company's Global Business Services segment offers business consulting services; system integration, application management, maintenance, and support services for packaged software; finance, procurement, talent and engagement, and industry-specific business process outsourcing; and IT infrastructure and platform services. Its Global Technology Services segment provides project, managed, outsourcing, and cloud-delivered services for enterprise IT infrastructure environments; and IT infrastructure support services. The company's Systems segment offers servers for businesses, cloud service providers, and scientific computing organizations; data storage products and solutions; and z/OS, an enterprise operating system, as well as Linux. Its Global Financing segment provides lease, installment payment, loan financing, short-term working capital, and remanufacturing and remarketing services. It has collaboration with Intel. The company was formerly known as Computing-Tabulating-Recording Co. and changed its name to International Business Machines Corporation in 1924. The company was incorporated in 1911 and is headquartered in Armonk, New York.\", 'city': 'Armonk', 'phone': '914 499 1900', 'state': 'NY', 'country': 'United States', 'companyOfficers': [], 'website': 'http://www.ibm.com', 'maxAge': 1, 'address1': 'One New Orchard Road', 'industry': 'Information Technology Services', 'previousClose': 129.87, 'regularMarketOpen': 126.03, 'twoHundredDayAverage': 128.72029, 'trailingAnnualDividendYield': 0.04989605, 'payoutRatio': 0.6416, 'volume24Hr': None, 'regularMarketDayHigh': 126.1, 'navPrice': None, 'averageDailyVolume10Day': 5488387, 'totalAssets': None, 'regularMarketPreviousClose': 129.87, 'fiftyDayAverage': 123.78286, 'trailingAnnualDividendRate': 6.48, 'open': 126.03, 'toCurrency': None, 'averageVolume10days': 5488387, 'expireDate': None, 'yield': None, 'algorithm': None, 'dividendRate': 6.52, 'exDividendDate': 1588809600, 'beta': 1.227247, 'circulatingSupply': None, 'startDate': None, 'regularMarketDayLow': 117.8352, 'priceHint': 2, 'currency': 'USD', 'trailingPE': 11.688788, 'regularMarketVolume': 11671007, 'lastMarket': None, 'maxSupply': None, 'openInterest': None, 'marketCap': 104780136448, 'volumeAllCurrencies': None, 'strikePrice': None, 'averageVolume': 6168070, 'priceToSalesTrailing12Months': 1.3690308, 'dayLow': 117.8352, 'ask': 121.16, 'ytdReturn': None, 'askSize': 800, 'volume': 11671007, 'fiftyTwoWeekHigh': 158.75, 'forwardPE': 9.509267, 'fromCurrency': None, 'fiveYearAvgDividendYield': 4.04, 'fiftyTwoWeekLow': 90.56, 'bid': 120.25, 'tradeable': False, 'dividendYield': 0.0502, 'bidSize': 800, 'dayHigh': 126.1, 'exchange': 'NYQ', 'shortName': 'International Business Machines', 'longName': 'International Business Machines Corporation', 'exchangeTimezoneName': 'America/New_York', 'exchangeTimezoneShortName': 'EDT', 'isEsgPopulated': False, 'gmtOffSetMilliseconds': '-14400000', 'quoteType': 'EQUITY', 'symbol': 'IBM', 'messageBoardId': 'finmb_112350', 'market': 'us_market', 'annualHoldingsTurnover': None, 'enterpriseToRevenue': 2.261, 'beta3Year': None, 'profitMargins': 0.117790006, 'enterpriseToEbitda': 10.796, '52WeekChange': -0.126822, 'morningStarRiskRating': None, 'forwardEps': 12.41, 'revenueQuarterlyGrowth': None, 'sharesOutstanding': 887891968, 'fundInceptionDate': None, 'annualReportExpenseRatio': None, 'bookValue': 22.524, 'sharesShort': 20805495, 'sharesPercentSharesOut': 0.0234, 'fundFamily': None, 'lastFiscalYearEnd': 1577750400, 'heldPercentInstitutions': 0.58555, 'netIncomeToCommon': 9018000384, 'trailingEps': 10.096, 'lastDividendValue': None, 'SandP52WeekChange': 0.039875627, 'priceToBook': 5.2393003, 'heldPercentInsiders': 0.0010800001, 'nextFiscalYearEnd': 1640908800, 'mostRecentQuarter': 1585612800, 'shortRatio': 4.37, 'sharesShortPreviousMonthDate': 1588204800, 'floatShares': 886506846, 'enterpriseValue': 173027524608, 'threeYearAverageReturn': None, 'lastSplitDate': 927763200, 'lastSplitFactor': '2:1', 'legalType': None, 'morningStarOverallRating': None, 'earningsQuarterlyGrowth': -0.261, 'dateShortInterest': 1590710400, 'pegRatio': 2.7, 'lastCapGain': None, 'shortPercentOfFloat': 0.0235, 'sharesShortPriorMonth': 19165408, 'category': None, 'fiveYearAverageReturn': None, 'regularMarketPrice': 126.03, 'logo_url': 'https://logo.clearbit.com/ibm.com'}\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Open</th>\n      <th>High</th>\n      <th>Low</th>\n      <th>Close</th>\n      <th>Volume</th>\n      <th>Dividends</th>\n      <th>Stock Splits</th>\n    </tr>\n    <tr>\n      <th>Date</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1962-01-02</th>\n      <td>0.62</td>\n      <td>0.62</td>\n      <td>0.61</td>\n      <td>0.61</td>\n      <td>387200</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>1962-01-03</th>\n      <td>0.61</td>\n      <td>0.62</td>\n      <td>0.61</td>\n      <td>0.62</td>\n      <td>288000</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>1962-01-04</th>\n      <td>0.62</td>\n      <td>0.62</td>\n      <td>0.61</td>\n      <td>0.61</td>\n      <td>256000</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>1962-01-05</th>\n      <td>0.61</td>\n      <td>0.61</td>\n      <td>0.60</td>\n      <td>0.60</td>\n      <td>363200</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>1962-01-08</th>\n      <td>0.60</td>\n      <td>0.60</td>\n      <td>0.58</td>\n      <td>0.59</td>\n      <td>544000</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>2020-06-05</th>\n      <td>133.89</td>\n      <td>134.23</td>\n      <td>131.75</td>\n      <td>132.06</td>\n      <td>5892700</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>2020-06-08</th>\n      <td>132.27</td>\n      <td>135.88</td>\n      <td>132.27</td>\n      <td>135.75</td>\n      <td>5370500</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>2020-06-09</th>\n      <td>133.52</td>\n      <td>133.60</td>\n      <td>131.02</td>\n      <td>131.87</td>\n      <td>5393600</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>2020-06-10</th>\n      <td>132.15</td>\n      <td>132.23</td>\n      <td>129.80</td>\n      <td>129.87</td>\n      <td>4734800</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>2020-06-11</th>\n      <td>126.03</td>\n      <td>126.10</td>\n      <td>117.84</td>\n      <td>118.01</td>\n      <td>11754900</td>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>14712 rows \u00d7 7 columns</p>\n</div>\n\n\n\n\n```python\naapl.actions\nyf.pdr_override() # <== that's all it takes :-)\n\n# download dataframe\ndata = pdr.get_data_yahoo(\"AAPL\", start=\"2010-01-01\", end=\"2020-06-11\")\n#? data\nd=data.to_dict()\nprint(d.keys())\n```\n\n    [*********************100%***********************]  1 of 1 completed\n    dict_keys(['Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume'])\n\n\n\n```python\ndd=d[\"Close\"]\n```\n\n\n```python\nfor key in dd.keys():\n    new_key=(str(key).replace(' 00:00:00',''))\n    dd[new_key] = dd.pop(key)\nod= collections.OrderedDict(sorted(dd.items()))\n```\n\n\n```python\nlists = sorted(dd.items()) # sorted by key, return a list of tuples\nx, y = zip(*lists) # unpack a list of pairs into two tuples\nplt.plot(x, y)\nplt.show()\n```\n\n\n```python\n#aapl.history(period=\"max\")\n```\n\n\n```python\n#data = pd.read_csv('APLS.csv')\n#data.sample(frac=2, replace=True)\nadj_close_price=y\ndates=x\n```\n\n\n```python\nadj_close_price=scale(adj_close_price)\n#gets the price and dates from the matrix\n#plt.plot(dates, adj_close_price)\n```\n\n\n```python\ndate_idx=[]\nfor i,j in enumerate(dates):\n         date_idx.append(int(i))\n```\n\n\n```python\ndate_idx=np.array(date_idx[:],ndmin=2).T\nadj_close_price=np.array(adj_close_price[:],ndmin=2).T\nprint(date_idx.shape)\nprint(adj_close_price.shape)\n```\n\n    (2628, 1)\n    (2628, 1)\n\n\n\n```python\n#Number of neurons in the input, output, and hidden layers\ninp = 1\noutput = 1\nhidden = 20\n#array of layers, 3 hidden and 1 output, along with the tanh activation function \nlayers = [('F', hidden), ('AF', 'tanh'), ('F', hidden), ('AF', 'tanh'), ('F', hidden), ('AF', 'relu'), ('F', output)]\n#construct the model and dictate params\nmlpr = ANNR([inp], layers, batchSize = 100, maxIter = 20000, tol = 0.2, reg = 1e-4, verbose = True)\n```\n\n    WARNING:tensorflow:From C:\\Users\\salmasi\\.conda\\envs\\tensor2\\lib\\site-packages\\TFANN.py:211: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n    \n    WARNING:tensorflow:From C:\\Users\\salmasi\\.conda\\envs\\tensor2\\lib\\site-packages\\TFANN.py:212: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead.\n    \n    WARNING:tensorflow:From C:\\Users\\salmasi\\.conda\\envs\\tensor2\\lib\\site-packages\\TFANN.py:222: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead.\n    \n    WARNING:tensorflow:\n    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      * https://github.com/tensorflow/io (for I/O related ops)\n    If you depend on functionality not listed there, please file an issue.\n    \n    WARNING:tensorflow:From C:\\Users\\salmasi\\.conda\\envs\\tensor2\\lib\\site-packages\\tensorflow_core\\contrib\\layers\\python\\layers\\layers.py:1634: flatten (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use keras.layers.flatten instead.\n    WARNING:tensorflow:From C:\\Users\\salmasi\\.conda\\envs\\tensor2\\lib\\site-packages\\tensorflow_core\\python\\layers\\core.py:332: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Please use `layer.__call__` method instead.\n    WARNING:tensorflow:From C:\\Users\\salmasi\\.conda\\envs\\tensor2\\lib\\site-packages\\TFANN.py:140: The name tf.squared_difference is deprecated. Please use tf.math.squared_difference instead.\n    \n    WARNING:tensorflow:From C:\\Users\\salmasi\\.conda\\envs\\tensor2\\lib\\site-packages\\TFANN.py:152: The name tf.train.AdamOptimizer is deprecated. Please use tf.compat.v1.train.AdamOptimizer instead.\n    \n    WARNING:tensorflow:From C:\\Users\\salmasi\\.conda\\envs\\tensor2\\lib\\site-packages\\TFANN.py:153: The name tf.train.AdagradOptimizer is deprecated. Please use tf.compat.v1.train.AdagradOptimizer instead.\n    \n    WARNING:tensorflow:From C:\\Users\\salmasi\\.conda\\envs\\tensor2\\lib\\site-packages\\TFANN.py:154: The name tf.train.FtrlOptimizer is deprecated. Please use tf.compat.v1.train.FtrlOptimizer instead.\n    \n    WARNING:tensorflow:From C:\\Users\\salmasi\\.conda\\envs\\tensor2\\lib\\site-packages\\TFANN.py:155: The name tf.train.GradientDescentOptimizer is deprecated. Please use tf.compat.v1.train.GradientDescentOptimizer instead.\n    \n    WARNING:tensorflow:From C:\\Users\\salmasi\\.conda\\envs\\tensor2\\lib\\site-packages\\TFANN.py:265: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead.\n    \n    WARNING:tensorflow:From C:\\Users\\salmasi\\.conda\\envs\\tensor2\\lib\\site-packages\\TFANN.py:267: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead.\n    \n    WARNING:tensorflow:From C:\\Users\\salmasi\\.conda\\envs\\tensor2\\lib\\site-packages\\TFANN.py:283: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead.\n    \n\n\n\n```python\nholdDays = 5\ntotalDays = len(date_idx)\nmlpr.fit(date_idx[0:(totalDays-holdDays)], adj_close_price[0:(totalDays-holdDays)])\n```\n\n    Iter     1\t      6.68021047 (Batch Size:   100)\n    Iter     2\t      5.48242629 (Batch Size:   100)\n    Iter     3\t      4.78038205 (Batch Size:   100)\n    Iter     4\t      3.93558960 (Batch Size:   100)\n    Iter     5\t      3.42507610 (Batch Size:   100)\n    Iter     6\t      2.90416458 (Batch Size:   100)\n    Iter     7\t      2.44808570 (Batch Size:   100)\n    Iter     8\t      2.04782187 (Batch Size:   100)\n    Iter     9\t      1.89639286 (Batch Size:   100)\n    Iter    10\t      1.85460719 (Batch Size:   100)\n    Iter    11\t      1.68312059 (Batch Size:   100)\n    Iter    12\t      1.54317635 (Batch Size:   100)\n    Iter    13\t      1.54431582 (Batch Size:   100)\n    Iter    14\t      1.42775860 (Batch Size:   100)\n    Iter    15\t      1.38543588 (Batch Size:   100)\n    Iter    16\t      1.27049173 (Batch Size:   100)\n    Iter    17\t      1.17920296 (Batch Size:   100)\n    Iter    18\t      1.24590985 (Batch Size:   100)\n    Iter    19\t      1.14196325 (Batch Size:   100)\n    Iter    20\t      1.11438779 (Batch Size:   100)\n    Iter    21\t      1.04614570 (Batch Size:   100)\n    Iter    22\t      0.95828471 (Batch Size:   100)\n    Iter    23\t      0.97647457 (Batch Size:   100)\n    Iter    24\t      0.98371722 (Batch Size:   100)\n    Iter    25\t      0.90553552 (Batch Size:   100)\n    Iter    26\t      0.95617409 (Batch Size:   100)\n    Iter    27\t      0.85887033 (Batch Size:   100)\n    Iter    28\t      0.88906689 (Batch Size:   100)\n    Iter    29\t      0.88547977 (Batch Size:   100)\n    Iter    30\t      0.82323405 (Batch Size:   100)\n    Iter    31\t      0.82660965 (Batch Size:   100)\n    Iter    32\t      0.81723526 (Batch Size:   100)\n    Iter    33\t      0.85629627 (Batch Size:   100)\n    Iter    34\t      0.83728450 (Batch Size:   100)\n    Iter    35\t      0.80305290 (Batch Size:   100)\n    Iter    36\t      0.78417863 (Batch Size:   100)\n    Iter    37\t      0.77875899 (Batch Size:   100)\n    Iter    38\t      0.75798784 (Batch Size:   100)\n    Iter    39\t      0.80882116 (Batch Size:   100)\n    Iter    40\t      0.78804746 (Batch Size:   100)\n    Iter    41\t      0.67745081 (Batch Size:   100)\n    Iter    42\t      0.63797197 (Batch Size:   100)\n    Iter    43\t      0.52722485 (Batch Size:   100)\n    Iter    44\t      0.50603391 (Batch Size:   100)\n    Iter    45\t      0.54232890 (Batch Size:   100)\n    Iter    46\t      0.53440941 (Batch Size:   100)\n    Iter    47\t      0.49469041 (Batch Size:   100)\n    Iter    48\t      0.47895460 (Batch Size:   100)\n    Iter    49\t      0.51174699 (Batch Size:   100)\n    Iter    50\t      0.45515826 (Batch Size:   100)\n    Iter    51\t      0.49704876 (Batch Size:   100)\n    Iter    52\t      0.50402806 (Batch Size:   100)\n    Iter    53\t      0.47883548 (Batch Size:   100)\n    Iter    54\t      0.43378750 (Batch Size:   100)\n    Iter    55\t      0.42619372 (Batch Size:   100)\n    Iter    56\t      0.42699663 (Batch Size:   100)\n    Iter    57\t      0.38930311 (Batch Size:   100)\n    Iter    58\t      0.41576513 (Batch Size:   100)\n    Iter    59\t      0.36465894 (Batch Size:   100)\n    Iter    60\t      0.36482005 (Batch Size:   100)\n    Iter    61\t      0.35871188 (Batch Size:   100)\n    Iter    62\t      0.34892903 (Batch Size:   100)\n    Iter    63\t      0.32297426 (Batch Size:   100)\n    Iter    64\t      0.33923436 (Batch Size:   100)\n    Iter    65\t      0.35784889 (Batch Size:   100)\n    Iter    66\t      0.30553986 (Batch Size:   100)\n    Iter    67\t      0.30573351 (Batch Size:   100)\n    Iter    68\t      0.30173907 (Batch Size:   100)\n    Iter    69\t      0.32035551 (Batch Size:   100)\n    Iter    70\t      0.29955606 (Batch Size:   100)\n    Iter    71\t      0.28365336 (Batch Size:   100)\n    Iter    72\t      0.28211158 (Batch Size:   100)\n    Iter    73\t      0.28084813 (Batch Size:   100)\n    Iter    74\t      0.30718560 (Batch Size:   100)\n    Iter    75\t      0.27287067 (Batch Size:   100)\n    Iter    76\t      0.25609537 (Batch Size:   100)\n    Iter    77\t      0.25718212 (Batch Size:   100)\n    Iter    78\t      0.25789859 (Batch Size:   100)\n    Iter    79\t      0.26531740 (Batch Size:   100)\n    Iter    80\t      0.24507853 (Batch Size:   100)\n    Iter    81\t      0.23564601 (Batch Size:   100)\n    Iter    82\t      0.26835996 (Batch Size:   100)\n    Iter    83\t      0.24178085 (Batch Size:   100)\n    Iter    84\t      0.24850468 (Batch Size:   100)\n    Iter    85\t      0.23206816 (Batch Size:   100)\n    Iter    86\t      0.23106024 (Batch Size:   100)\n    Iter    87\t      0.22571463 (Batch Size:   100)\n    Iter    88\t      0.22036538 (Batch Size:   100)\n    Iter    89\t      0.22366946 (Batch Size:   100)\n    Iter    90\t      0.23166178 (Batch Size:   100)\n    Iter    91\t      0.22880917 (Batch Size:   100)\n    Iter    92\t      0.22110528 (Batch Size:   100)\n    Iter    93\t      0.20467161 (Batch Size:   100)\n    Iter    94\t      0.19420422 (Batch Size:   100)\n\n\n\n```python\n#Predict the stock price using the model\npricePredict = mlpr.predict(date_idx)\n#Display the predicted reuslts agains the actual data\nplt.plot(date_idx, adj_close_price)\nplt.plot(date_idx, pricePredict, c='#5aa9ab')\nplt.show()\n```\n\n\n```python\n#Number of neurons in the input, output, and hidden layers\ninput2 = 1\noutput2 = 1\nhidden2 = 50\n#array of layers, 3 hidden and 1 output, along with the tanh activation function \nlayers = [('F', hidden2), ('AF', 'tanh'), ('F', hidden2), ('AF', 'tanh'), ('F', hidden2), ('AF', 'tanh'), ('F', output2)]\n#construct the model and dictate params\nmlpr2 = ANNR([input2], layers, batchSize = 256, maxIter = 10000, tol = 0.01, reg = 1e-4, verbose = True)\n```\n\n\n```python\nholdDays = 5\ntotalDays = len(date_idx)\nmlpr2.fit(date_idx[0:(totalDays-holdDays)], adj_close_price[0:(totalDays-holdDays)])\npricePredict2 = mlpr2.predict(date_idx)\n```\n\n    Iter     1\t      3.04254016 (Batch Size:   256)\n    Iter     2\t      2.09432136 (Batch Size:   256)\n    Iter     3\t      1.51747796 (Batch Size:   256)\n    Iter     4\t      1.20375129 (Batch Size:   256)\n    Iter     5\t      1.03545929 (Batch Size:   256)\n    Iter     6\t      0.91251254 (Batch Size:   256)\n    Iter     7\t      0.98118834 (Batch Size:   256)\n    Iter     8\t      0.95628654 (Batch Size:   256)\n    Iter     9\t      1.02091792 (Batch Size:   256)\n    Iter    10\t      1.00914057 (Batch Size:   256)\n    Iter    11\t      0.99202198 (Batch Size:   256)\n    Iter    12\t      0.96275778 (Batch Size:   256)\n    Iter    13\t      0.93813684 (Batch Size:   256)\n    Iter    14\t      0.93870054 (Batch Size:   256)\n    Iter    15\t      0.96614733 (Batch Size:   256)\n    Iter    16\t      0.93295672 (Batch Size:   256)\n    Iter    17\t      0.91497869 (Batch Size:   256)\n    Iter    18\t      0.88168643 (Batch Size:   256)\n    Iter    19\t      0.90674957 (Batch Size:   256)\n    Iter    20\t      0.87950947 (Batch Size:   256)\n    Iter    21\t      0.89578678 (Batch Size:   256)\n    Iter    22\t      0.87390041 (Batch Size:   256)\n    Iter    23\t      0.93677323 (Batch Size:   256)\n    Iter    24\t      0.89491880 (Batch Size:   256)\n    Iter    25\t      0.89326533 (Batch Size:   256)\n    Iter    26\t      0.86705232 (Batch Size:   256)\n    Iter    27\t      0.87052377 (Batch Size:   256)\n    Iter    28\t      0.86815436 (Batch Size:   256)\n    Iter    29\t      0.80181317 (Batch Size:   256)\n    Iter    30\t      0.83402661 (Batch Size:   256)\n    Iter    31\t      0.74921042 (Batch Size:   256)\n    Iter    32\t      0.75604900 (Batch Size:   256)\n    Iter    33\t      0.77577620 (Batch Size:   256)\n    Iter    34\t      0.77655610 (Batch Size:   256)\n    Iter    35\t      0.67787745 (Batch Size:   256)\n    Iter    36\t      0.67867508 (Batch Size:   256)\n    Iter    37\t      0.64927452 (Batch Size:   256)\n    Iter    38\t      0.65593023 (Batch Size:   256)\n    Iter    39\t      0.63686985 (Batch Size:   256)\n    Iter    40\t      0.57965922 (Batch Size:   256)\n    Iter    41\t      0.57535722 (Batch Size:   256)\n    Iter    42\t      0.53442292 (Batch Size:   256)\n    Iter    43\t      0.51755638 (Batch Size:   256)\n    Iter    44\t      0.48934584 (Batch Size:   256)\n    Iter    45\t      0.45935673 (Batch Size:   256)\n    Iter    46\t      0.40134077 (Batch Size:   256)\n    Iter    47\t      0.39301670 (Batch Size:   256)\n    Iter    48\t      0.36452985 (Batch Size:   256)\n    Iter    49\t      0.35239274 (Batch Size:   256)\n    Iter    50\t      0.33888991 (Batch Size:   256)\n    Iter    51\t      0.30951778 (Batch Size:   256)\n    Iter    52\t      0.31653345 (Batch Size:   256)\n    Iter    53\t      0.30876449 (Batch Size:   256)\n    Iter    54\t      0.28984692 (Batch Size:   256)\n    Iter    55\t      0.30299944 (Batch Size:   256)\n    Iter    56\t      0.27364089 (Batch Size:   256)\n    Iter    57\t      0.26893824 (Batch Size:   256)\n    Iter    58\t      0.24968276 (Batch Size:   256)\n    Iter    59\t      0.27026623 (Batch Size:   256)\n    Iter    60\t      0.23709487 (Batch Size:   256)\n    Iter    61\t      0.23304231 (Batch Size:   256)\n    Iter    62\t      0.23270769 (Batch Size:   256)\n    Iter    63\t      0.22308333 (Batch Size:   256)\n    Iter    64\t      0.24117709 (Batch Size:   256)\n    Iter    65\t      0.24241067 (Batch Size:   256)\n    Iter    66\t      0.22064570 (Batch Size:   256)\n    Iter    67\t      0.24516927 (Batch Size:   256)\n    Iter    68\t      0.23587544 (Batch Size:   256)\n    Iter    69\t      0.22519165 (Batch Size:   256)\n    Iter    70\t      0.22310321 (Batch Size:   256)\n    Iter    71\t      0.21834720 (Batch Size:   256)\n    Iter    72\t      0.21248106 (Batch Size:   256)\n    Iter    73\t      0.19714232 (Batch Size:   256)\n    Iter    74\t      0.20368432 (Batch Size:   256)\n    Iter    75\t      0.19996307 (Batch Size:   256)\n    Iter    76\t      0.19011279 (Batch Size:   256)\n    Iter    77\t      0.22132796 (Batch Size:   256)\n    Iter    78\t      0.19902197 (Batch Size:   256)\n    Iter    79\t      0.22611711 (Batch Size:   256)\n    Iter    80\t      0.18492967 (Batch Size:   256)\n    Iter    81\t      0.21403894 (Batch Size:   256)\n    Iter    82\t      0.18536781 (Batch Size:   256)\n    Iter    83\t      0.19801479 (Batch Size:   256)\n    Iter    84\t      0.18924232 (Batch Size:   256)\n    Iter    85\t      0.18376804 (Batch Size:   256)\n    Iter    86\t      0.19246858 (Batch Size:   256)\n    Iter    87\t      0.19961985 (Batch Size:   256)\n    Iter    88\t      0.19619032 (Batch Size:   256)\n    Iter    89\t      0.19291893 (Batch Size:   256)\n    Iter    90\t      0.18303216 (Batch Size:   256)\n    Iter    91\t      0.19868052 (Batch Size:   256)\n    Iter    92\t      0.16767923 (Batch Size:   256)\n    Iter    93\t      0.17901467 (Batch Size:   256)\n    Iter    94\t      0.18664554 (Batch Size:   256)\n    Iter    95\t      0.18961265 (Batch Size:   256)\n    Iter    96\t      0.18868683 (Batch Size:   256)\n    Iter    97\t      0.17979904 (Batch Size:   256)\n    Iter    98\t      0.18174902 (Batch Size:   256)\n    Iter    99\t      0.18272481 (Batch Size:   256)\n    Iter   100\t      0.17183728 (Batch Size:   256)\n    Iter   101\t      0.17880063 (Batch Size:   256)\n    Iter   102\t      0.17630477 (Batch Size:   256)\n    Iter   103\t      0.17417636 (Batch Size:   256)\n    Iter   104\t      0.16267045 (Batch Size:   256)\n    Iter   105\t      0.17777442 (Batch Size:   256)\n    Iter   106\t      0.18319984 (Batch Size:   256)\n    Iter   107\t      0.18496867 (Batch Size:   256)\n    Iter   108\t      0.17866231 (Batch Size:   256)\n    Iter   109\t      0.17189645 (Batch Size:   256)\n    Iter   110\t      0.16125348 (Batch Size:   256)\n    Iter   111\t      0.19642291 (Batch Size:   256)\n    Iter   112\t      0.17944058 (Batch Size:   256)\n    Iter   113\t      0.17875891 (Batch Size:   256)\n    Iter   114\t      0.19478168 (Batch Size:   256)\n    Iter   115\t      0.17739842 (Batch Size:   256)\n    Iter   116\t      0.17227474 (Batch Size:   256)\n    Iter   117\t      0.17384279 (Batch Size:   256)\n    Iter   118\t      0.17895348 (Batch Size:   256)\n    Iter   119\t      0.16394383 (Batch Size:   256)\n    Iter   120\t      0.15919262 (Batch Size:   256)\n    Iter   121\t      0.17145008 (Batch Size:   256)\n    Iter   122\t      0.16491710 (Batch Size:   256)\n    Iter   123\t      0.16383496 (Batch Size:   256)\n    Iter   124\t      0.17901296 (Batch Size:   256)\n    Iter   125\t      0.18373314 (Batch Size:   256)\n    Iter   126\t      0.18364270 (Batch Size:   256)\n    Iter   127\t      0.17619486 (Batch Size:   256)\n    Iter   128\t      0.16454425 (Batch Size:   256)\n    Iter   129\t      0.18007110 (Batch Size:   256)\n    Iter   130\t      0.16614769 (Batch Size:   256)\n    Iter   131\t      0.16852115 (Batch Size:   256)\n    Iter   132\t      0.17105533 (Batch Size:   256)\n    Iter   133\t      0.16757338 (Batch Size:   256)\n    Iter   134\t      0.16978675 (Batch Size:   256)\n    Iter   135\t      0.17257303 (Batch Size:   256)\n    Iter   136\t      0.15852597 (Batch Size:   256)\n    Iter   137\t      0.17156729 (Batch Size:   256)\n    Iter   138\t      0.15569458 (Batch Size:   256)\n    Iter   139\t      0.15623150 (Batch Size:   256)\n    Iter   140\t      0.16365934 (Batch Size:   256)\n    Iter   141\t      0.16235214 (Batch Size:   256)\n    Iter   142\t      0.16925924 (Batch Size:   256)\n    Iter   143\t      0.16975166 (Batch Size:   256)\n    Iter   144\t      0.16089930 (Batch Size:   256)\n    Iter   145\t      0.15673698 (Batch Size:   256)\n    Iter   146\t      0.15776673 (Batch Size:   256)\n    Iter   147\t      0.16398760 (Batch Size:   256)\n    Iter   148\t      0.14809915 (Batch Size:   256)\n    Iter   149\t      0.15329230 (Batch Size:   256)\n    Iter   150\t      0.14569411 (Batch Size:   256)\n    Iter   151\t      0.15414413 (Batch Size:   256)\n    Iter   152\t      0.16399039 (Batch Size:   256)\n    Iter   153\t      0.15133870 (Batch Size:   256)\n    Iter   154\t      0.15656849 (Batch Size:   256)\n    Iter   155\t      0.16498411 (Batch Size:   256)\n    Iter   156\t      0.17341378 (Batch Size:   256)\n    Iter   157\t      0.15583303 (Batch Size:   256)\n    Iter   158\t      0.16309055 (Batch Size:   256)\n    Iter   159\t      0.16179104 (Batch Size:   256)\n    Iter   160\t      0.16007473 (Batch Size:   256)\n    Iter   161\t      0.15263470 (Batch Size:   256)\n    Iter   162\t      0.15204650 (Batch Size:   256)\n    Iter   163\t      0.16188421 (Batch Size:   256)\n    Iter   164\t      0.16244237 (Batch Size:   256)\n    Iter   165\t      0.16112525 (Batch Size:   256)\n    Iter   166\t      0.16185310 (Batch Size:   256)\n    Iter   167\t      0.15053220 (Batch Size:   256)\n    Iter   168\t      0.16683789 (Batch Size:   256)\n    Iter   169\t      0.15359553 (Batch Size:   256)\n    Iter   170\t      0.15615850 (Batch Size:   256)\n    Iter   171\t      0.14782013 (Batch Size:   256)\n    Iter   172\t      0.15678533 (Batch Size:   256)\n    Iter   173\t      0.15799773 (Batch Size:   256)\n    Iter   174\t      0.16620515 (Batch Size:   256)\n    Iter   175\t      0.17954468 (Batch Size:   256)\n    Iter   176\t      0.15288583 (Batch Size:   256)\n    Iter   177\t      0.14420837 (Batch Size:   256)\n    Iter   178\t      0.16317042 (Batch Size:   256)\n    Iter   179\t      0.15374880 (Batch Size:   256)\n    Iter   180\t      0.15766254 (Batch Size:   256)\n    Iter   181\t      0.15467076 (Batch Size:   256)\n    Iter   182\t      0.15471730 (Batch Size:   256)\n    Iter   183\t      0.15812038 (Batch Size:   256)\n    Iter   184\t      0.15484155 (Batch Size:   256)\n    Iter   185\t      0.15926024 (Batch Size:   256)\n    Iter   186\t      0.14811193 (Batch Size:   256)\n    Iter   187\t      0.13291346 (Batch Size:   256)\n    Iter   188\t      0.15448746 (Batch Size:   256)\n    Iter   189\t      0.14191797 (Batch Size:   256)\n    Iter   190\t      0.15056444 (Batch Size:   256)\n    Iter   191\t      0.16911620 (Batch Size:   256)\n    Iter   192\t      0.15115909 (Batch Size:   256)\n    Iter   193\t      0.15315656 (Batch Size:   256)\n    Iter   194\t      0.14693656 (Batch Size:   256)\n    Iter   195\t      0.13481898 (Batch Size:   256)\n    Iter   196\t      0.13851065 (Batch Size:   256)\n    Iter   197\t      0.16769176 (Batch Size:   256)\n    Iter   198\t      0.14621886 (Batch Size:   256)\n    Iter   199\t      0.16919670 (Batch Size:   256)\n    Iter   200\t      0.13952065 (Batch Size:   256)\n    Iter   201\t      0.14808209 (Batch Size:   256)\n    Iter   202\t      0.14003486 (Batch Size:   256)\n    Iter   203\t      0.13956844 (Batch Size:   256)\n    Iter   204\t      0.14422568 (Batch Size:   256)\n    Iter   205\t      0.14268669 (Batch Size:   256)\n    Iter   206\t      0.13792432 (Batch Size:   256)\n    Iter   207\t      0.14747520 (Batch Size:   256)\n    Iter   208\t      0.15671221 (Batch Size:   256)\n    Iter   209\t      0.15375762 (Batch Size:   256)\n    Iter   210\t      0.15899376 (Batch Size:   256)\n    Iter   211\t      0.14587912 (Batch Size:   256)\n    Iter   212\t      0.15033772 (Batch Size:   256)\n    Iter   213\t      0.13066862 (Batch Size:   256)\n    Iter   214\t      0.13857579 (Batch Size:   256)\n    Iter   215\t      0.15607106 (Batch Size:   256)\n    Iter   216\t      0.13951204 (Batch Size:   256)\n    Iter   217\t      0.14799353 (Batch Size:   256)\n    Iter   218\t      0.13641097 (Batch Size:   256)\n    Iter   219\t      0.13873287 (Batch Size:   256)\n    Iter   220\t      0.14135598 (Batch Size:   256)\n    Iter   221\t      0.13359833 (Batch Size:   256)\n    Iter   222\t      0.13837225 (Batch Size:   256)\n    Iter   223\t      0.13870618 (Batch Size:   256)\n    Iter   224\t      0.14500702 (Batch Size:   256)\n    Iter   225\t      0.14682419 (Batch Size:   256)\n    Iter   226\t      0.15278116 (Batch Size:   256)\n    Iter   227\t      0.14671852 (Batch Size:   256)\n    Iter   228\t      0.13381447 (Batch Size:   256)\n    Iter   229\t      0.13921728 (Batch Size:   256)\n    Iter   230\t      0.14166659 (Batch Size:   256)\n    Iter   231\t      0.14925961 (Batch Size:   256)\n    Iter   232\t      0.14347453 (Batch Size:   256)\n    Iter   233\t      0.13939188 (Batch Size:   256)\n    Iter   234\t      0.14179308 (Batch Size:   256)\n    Iter   235\t      0.15319501 (Batch Size:   256)\n    Iter   236\t      0.16759118 (Batch Size:   256)\n    Iter   237\t      0.15415424 (Batch Size:   256)\n    Iter   238\t      0.13140837 (Batch Size:   256)\n    Iter   239\t      0.13343637 (Batch Size:   256)\n    Iter   240\t      0.13514649 (Batch Size:   256)\n    Iter   241\t      0.13917673 (Batch Size:   256)\n    Iter   242\t      0.14291620 (Batch Size:   256)\n    Iter   243\t      0.13623515 (Batch Size:   256)\n    Iter   244\t      0.13998145 (Batch Size:   256)\n    Iter   245\t      0.14554812 (Batch Size:   256)\n    Iter   246\t      0.13757589 (Batch Size:   256)\n    Iter   247\t      0.13500591 (Batch Size:   256)\n    Iter   248\t      0.13502201 (Batch Size:   256)\n    Iter   249\t      0.15116506 (Batch Size:   256)\n    Iter   250\t      0.15127189 (Batch Size:   256)\n    Iter   251\t      0.14346520 (Batch Size:   256)\n    Iter   252\t      0.14970094 (Batch Size:   256)\n    Iter   253\t      0.13916086 (Batch Size:   256)\n    Iter   254\t      0.13445560 (Batch Size:   256)\n    Iter   255\t      0.13126352 (Batch Size:   256)\n    Iter   256\t      0.14013678 (Batch Size:   256)\n    Iter   257\t      0.13787470 (Batch Size:   256)\n    Iter   258\t      0.14020666 (Batch Size:   256)\n    Iter   259\t      0.13679166 (Batch Size:   256)\n    Iter   260\t      0.13684470 (Batch Size:   256)\n    Iter   261\t      0.15447785 (Batch Size:   256)\n    Iter   262\t      0.13727694 (Batch Size:   256)\n    Iter   263\t      0.14240783 (Batch Size:   256)\n    Iter   264\t      0.12879535 (Batch Size:   256)\n    Iter   265\t      0.14022601 (Batch Size:   256)\n    Iter   266\t      0.13165373 (Batch Size:   256)\n    Iter   267\t      0.13381808 (Batch Size:   256)\n    Iter   268\t      0.12798483 (Batch Size:   256)\n    Iter   269\t      0.13565240 (Batch Size:   256)\n    Iter   270\t      0.13035058 (Batch Size:   256)\n    Iter   271\t      0.13674992 (Batch Size:   256)\n    Iter   272\t      0.13653899 (Batch Size:   256)\n    Iter   273\t      0.12638158 (Batch Size:   256)\n    Iter   274\t      0.12748439 (Batch Size:   256)\n    Iter   275\t      0.14318528 (Batch Size:   256)\n    Iter   276\t      0.12927540 (Batch Size:   256)\n    Iter   277\t      0.13050896 (Batch Size:   256)\n    Iter   278\t      0.12524954 (Batch Size:   256)\n    Iter   279\t      0.12636028 (Batch Size:   256)\n    Iter   280\t      0.13071936 (Batch Size:   256)\n    Iter   281\t      0.12370279 (Batch Size:   256)\n    Iter   282\t      0.12668230 (Batch Size:   256)\n    Iter   283\t      0.13556213 (Batch Size:   256)\n    Iter   284\t      0.13496500 (Batch Size:   256)\n    Iter   285\t      0.14236439 (Batch Size:   256)\n    Iter   286\t      0.11988828 (Batch Size:   256)\n    Iter   287\t      0.12830084 (Batch Size:   256)\n    Iter   288\t      0.12639708 (Batch Size:   256)\n    Iter   289\t      0.12790342 (Batch Size:   256)\n    Iter   290\t      0.12373058 (Batch Size:   256)\n    Iter   291\t      0.12111119 (Batch Size:   256)\n    Iter   292\t      0.12331938 (Batch Size:   256)\n    Iter   293\t      0.12616641 (Batch Size:   256)\n    Iter   294\t      0.13245344 (Batch Size:   256)\n    Iter   295\t      0.12134880 (Batch Size:   256)\n    Iter   296\t      0.13243439 (Batch Size:   256)\n    Iter   297\t      0.12787102 (Batch Size:   256)\n    Iter   298\t      0.12384595 (Batch Size:   256)\n    Iter   299\t      0.12479188 (Batch Size:   256)\n    Iter   300\t      0.12690972 (Batch Size:   256)\n    Iter   301\t      0.12847222 (Batch Size:   256)\n    Iter   302\t      0.12591026 (Batch Size:   256)\n    Iter   303\t      0.12177530 (Batch Size:   256)\n    Iter   304\t      0.12139555 (Batch Size:   256)\n    Iter   305\t      0.11860667 (Batch Size:   256)\n    Iter   306\t      0.12315404 (Batch Size:   256)\n    Iter   307\t      0.12725946 (Batch Size:   256)\n    Iter   308\t      0.12031611 (Batch Size:   256)\n    Iter   309\t      0.12361148 (Batch Size:   256)\n    Iter   310\t      0.12897991 (Batch Size:   256)\n    Iter   311\t      0.12182996 (Batch Size:   256)\n    Iter   312\t      0.12053133 (Batch Size:   256)\n    Iter   313\t      0.11630568 (Batch Size:   256)\n    Iter   314\t      0.12225294 (Batch Size:   256)\n    Iter   315\t      0.12241045 (Batch Size:   256)\n    Iter   316\t      0.12530701 (Batch Size:   256)\n    Iter   317\t      0.12578484 (Batch Size:   256)\n    Iter   318\t      0.15371410 (Batch Size:   256)\n    Iter   319\t      0.13561263 (Batch Size:   256)\n    Iter   320\t      0.13062281 (Batch Size:   256)\n    Iter   321\t      0.12030461 (Batch Size:   256)\n    Iter   322\t      0.12447308 (Batch Size:   256)\n    Iter   323\t      0.12753837 (Batch Size:   256)\n    Iter   324\t      0.12774746 (Batch Size:   256)\n    Iter   325\t      0.11436544 (Batch Size:   256)\n    Iter   326\t      0.11419033 (Batch Size:   256)\n    Iter   327\t      0.12531354 (Batch Size:   256)\n    Iter   328\t      0.12001378 (Batch Size:   256)\n    Iter   329\t      0.11397298 (Batch Size:   256)\n    Iter   330\t      0.11826992 (Batch Size:   256)\n    Iter   331\t      0.11270665 (Batch Size:   256)\n    Iter   332\t      0.11813385 (Batch Size:   256)\n    Iter   333\t      0.12438284 (Batch Size:   256)\n    Iter   334\t      0.11488199 (Batch Size:   256)\n    Iter   335\t      0.10907916 (Batch Size:   256)\n    Iter   336\t      0.10981530 (Batch Size:   256)\n    Iter   337\t      0.10789997 (Batch Size:   256)\n    Iter   338\t      0.11738664 (Batch Size:   256)\n    Iter   339\t      0.11774279 (Batch Size:   256)\n    Iter   340\t      0.12316550 (Batch Size:   256)\n    Iter   341\t      0.11853824 (Batch Size:   256)\n    Iter   342\t      0.11113173 (Batch Size:   256)\n    Iter   343\t      0.11237656 (Batch Size:   256)\n    Iter   344\t      0.11167134 (Batch Size:   256)\n    Iter   345\t      0.11157436 (Batch Size:   256)\n    Iter   346\t      0.10994809 (Batch Size:   256)\n    Iter   347\t      0.11413378 (Batch Size:   256)\n    Iter   348\t      0.11018274 (Batch Size:   256)\n    Iter   349\t      0.10496923 (Batch Size:   256)\n    Iter   350\t      0.11036757 (Batch Size:   256)\n    Iter   351\t      0.11754548 (Batch Size:   256)\n    Iter   352\t      0.10957529 (Batch Size:   256)\n    Iter   353\t      0.11225845 (Batch Size:   256)\n    Iter   354\t      0.12850043 (Batch Size:   256)\n    Iter   355\t      0.11643305 (Batch Size:   256)\n    Iter   356\t      0.11861697 (Batch Size:   256)\n    Iter   357\t      0.11395554 (Batch Size:   256)\n    Iter   358\t      0.10652874 (Batch Size:   256)\n    Iter   359\t      0.10621765 (Batch Size:   256)\n    Iter   360\t      0.11668574 (Batch Size:   256)\n    Iter   361\t      0.11939906 (Batch Size:   256)\n    Iter   362\t      0.11375309 (Batch Size:   256)\n    Iter   363\t      0.10937353 (Batch Size:   256)\n    Iter   364\t      0.12496762 (Batch Size:   256)\n    Iter   365\t      0.10617991 (Batch Size:   256)\n    Iter   366\t      0.09975686 (Batch Size:   256)\n    Iter   367\t      0.10397713 (Batch Size:   256)\n    Iter   368\t      0.11213068 (Batch Size:   256)\n    Iter   369\t      0.10647379 (Batch Size:   256)\n    Iter   370\t      0.10804071 (Batch Size:   256)\n    Iter   371\t      0.12693456 (Batch Size:   256)\n    Iter   372\t      0.11864066 (Batch Size:   256)\n    Iter   373\t      0.11311671 (Batch Size:   256)\n    Iter   374\t      0.11236029 (Batch Size:   256)\n    Iter   375\t      0.11491121 (Batch Size:   256)\n    Iter   376\t      0.11011336 (Batch Size:   256)\n    Iter   377\t      0.09985178 (Batch Size:   256)\n    Iter   378\t      0.11867632 (Batch Size:   256)\n    Iter   379\t      0.10463256 (Batch Size:   256)\n    Iter   380\t      0.11345813 (Batch Size:   256)\n    Iter   381\t      0.10562609 (Batch Size:   256)\n    Iter   382\t      0.11307051 (Batch Size:   256)\n    Iter   383\t      0.09929581 (Batch Size:   256)\n    Iter   384\t      0.09493197 (Batch Size:   256)\n    Iter   385\t      0.11442595 (Batch Size:   256)\n    Iter   386\t      0.11512683 (Batch Size:   256)\n    Iter   387\t      0.11064610 (Batch Size:   256)\n    Iter   388\t      0.09983273 (Batch Size:   256)\n    Iter   389\t      0.12472414 (Batch Size:   256)\n    Iter   390\t      0.09975699 (Batch Size:   256)\n    Iter   391\t      0.10838477 (Batch Size:   256)\n    Iter   392\t      0.10099115 (Batch Size:   256)\n    Iter   393\t      0.10051333 (Batch Size:   256)\n    Iter   394\t      0.10904808 (Batch Size:   256)\n    Iter   395\t      0.11182320 (Batch Size:   256)\n    Iter   396\t      0.11109833 (Batch Size:   256)\n    Iter   397\t      0.09979179 (Batch Size:   256)\n    Iter   398\t      0.10517988 (Batch Size:   256)\n    Iter   399\t      0.10002863 (Batch Size:   256)\n    Iter   400\t      0.10029930 (Batch Size:   256)\n    Iter   401\t      0.10248672 (Batch Size:   256)\n    Iter   402\t      0.10317713 (Batch Size:   256)\n    Iter   403\t      0.09645050 (Batch Size:   256)\n    Iter   404\t      0.10764971 (Batch Size:   256)\n    Iter   405\t      0.10285416 (Batch Size:   256)\n    Iter   406\t      0.10266073 (Batch Size:   256)\n    Iter   407\t      0.10329445 (Batch Size:   256)\n    Iter   408\t      0.10284331 (Batch Size:   256)\n    Iter   409\t      0.10410888 (Batch Size:   256)\n    Iter   410\t      0.09843888 (Batch Size:   256)\n    Iter   411\t      0.11003917 (Batch Size:   256)\n    Iter   412\t      0.10591159 (Batch Size:   256)\n    Iter   413\t      0.09945046 (Batch Size:   256)\n    Iter   414\t      0.11031041 (Batch Size:   256)\n    Iter   415\t      0.10629497 (Batch Size:   256)\n    Iter   416\t      0.10054752 (Batch Size:   256)\n    Iter   417\t      0.09700936 (Batch Size:   256)\n    Iter   418\t      0.10060221 (Batch Size:   256)\n    Iter   419\t      0.10057771 (Batch Size:   256)\n    Iter   420\t      0.10642323 (Batch Size:   256)\n    Iter   421\t      0.10654044 (Batch Size:   256)\n    Iter   422\t      0.09437527 (Batch Size:   256)\n    Iter   423\t      0.10735334 (Batch Size:   256)\n    Iter   424\t      0.09495611 (Batch Size:   256)\n    Iter   425\t      0.09795056 (Batch Size:   256)\n    Iter   426\t      0.10007047 (Batch Size:   256)\n    Iter   427\t      0.09240535 (Batch Size:   256)\n    Iter   428\t      0.09911627 (Batch Size:   256)\n    Iter   429\t      0.09743553 (Batch Size:   256)\n    Iter   430\t      0.09965541 (Batch Size:   256)\n    Iter   431\t      0.10684634 (Batch Size:   256)\n    Iter   432\t      0.10565425 (Batch Size:   256)\n    Iter   433\t      0.09685071 (Batch Size:   256)\n    Iter   434\t      0.09565614 (Batch Size:   256)\n    Iter   435\t      0.09358745 (Batch Size:   256)\n    Iter   436\t      0.09636991 (Batch Size:   256)\n    Iter   437\t      0.09333335 (Batch Size:   256)\n    Iter   438\t      0.10059272 (Batch Size:   256)\n    Iter   439\t      0.09278648 (Batch Size:   256)\n    Iter   440\t      0.09799587 (Batch Size:   256)\n    Iter   441\t      0.09730924 (Batch Size:   256)\n    Iter   442\t      0.10188759 (Batch Size:   256)\n    Iter   443\t      0.10797541 (Batch Size:   256)\n    Iter   444\t      0.10786797 (Batch Size:   256)\n    Iter   445\t      0.10407742 (Batch Size:   256)\n    Iter   446\t      0.10376370 (Batch Size:   256)\n    Iter   447\t      0.09471824 (Batch Size:   256)\n    Iter   448\t      0.09678507 (Batch Size:   256)\n    Iter   449\t      0.09217570 (Batch Size:   256)\n    Iter   450\t      0.08882322 (Batch Size:   256)\n    Iter   451\t      0.09724350 (Batch Size:   256)\n    Iter   452\t      0.10368365 (Batch Size:   256)\n    Iter   453\t      0.09243738 (Batch Size:   256)\n    Iter   454\t      0.10337345 (Batch Size:   256)\n    Iter   455\t      0.09452615 (Batch Size:   256)\n    Iter   456\t      0.10064088 (Batch Size:   256)\n    Iter   457\t      0.09965163 (Batch Size:   256)\n    Iter   458\t      0.10903888 (Batch Size:   256)\n    Iter   459\t      0.10425755 (Batch Size:   256)\n    Iter   460\t      0.09669847 (Batch Size:   256)\n    Iter   461\t      0.09654976 (Batch Size:   256)\n    Iter   462\t      0.09943623 (Batch Size:   256)\n    Iter   463\t      0.11057183 (Batch Size:   256)\n    Iter   464\t      0.10535240 (Batch Size:   256)\n    Iter   465\t      0.09123804 (Batch Size:   256)\n    Iter   466\t      0.10139727 (Batch Size:   256)\n    Iter   467\t      0.09502422 (Batch Size:   256)\n    Iter   468\t      0.09330359 (Batch Size:   256)\n    Iter   469\t      0.09022511 (Batch Size:   256)\n    Iter   470\t      0.09495999 (Batch Size:   256)\n    Iter   471\t      0.09419741 (Batch Size:   256)\n    Iter   472\t      0.09365459 (Batch Size:   256)\n    Iter   473\t      0.11587954 (Batch Size:   256)\n    Iter   474\t      0.10353441 (Batch Size:   256)\n    Iter   475\t      0.09555474 (Batch Size:   256)\n    Iter   476\t      0.09574122 (Batch Size:   256)\n    Iter   477\t      0.11083988 (Batch Size:   256)\n    Iter   478\t      0.09907080 (Batch Size:   256)\n    Iter   479\t      0.09203271 (Batch Size:   256)\n    Iter   480\t      0.08897294 (Batch Size:   256)\n    Iter   481\t      0.09965705 (Batch Size:   256)\n    Iter   482\t      0.10057560 (Batch Size:   256)\n    Iter   483\t      0.10654542 (Batch Size:   256)\n    Iter   484\t      0.09732918 (Batch Size:   256)\n    Iter   485\t      0.09134046 (Batch Size:   256)\n    Iter   486\t      0.08969122 (Batch Size:   256)\n    Iter   487\t      0.09702364 (Batch Size:   256)\n    Iter   488\t      0.09404720 (Batch Size:   256)\n    Iter   489\t      0.09056030 (Batch Size:   256)\n    Iter   490\t      0.08779434 (Batch Size:   256)\n    Iter   491\t      0.09383227 (Batch Size:   256)\n    Iter   492\t      0.09025426 (Batch Size:   256)\n    Iter   493\t      0.09362634 (Batch Size:   256)\n    Iter   494\t      0.09133241 (Batch Size:   256)\n    Iter   495\t      0.09415426 (Batch Size:   256)\n    Iter   496\t      0.09734781 (Batch Size:   256)\n    Iter   497\t      0.09180559 (Batch Size:   256)\n    Iter   498\t      0.09235418 (Batch Size:   256)\n    Iter   499\t      0.09384713 (Batch Size:   256)\n    Iter   500\t      0.09148788 (Batch Size:   256)\n    Iter   501\t      0.09256447 (Batch Size:   256)\n    Iter   502\t      0.10770105 (Batch Size:   256)\n    Iter   503\t      0.09321282 (Batch Size:   256)\n    Iter   504\t      0.09016543 (Batch Size:   256)\n    Iter   505\t      0.08533146 (Batch Size:   256)\n    Iter   506\t      0.09209061 (Batch Size:   256)\n    Iter   507\t      0.09426033 (Batch Size:   256)\n    Iter   508\t      0.08813111 (Batch Size:   256)\n    Iter   509\t      0.08622422 (Batch Size:   256)\n    Iter   510\t      0.08861565 (Batch Size:   256)\n    Iter   511\t      0.08808696 (Batch Size:   256)\n    Iter   512\t      0.08952064 (Batch Size:   256)\n    Iter   513\t      0.09086689 (Batch Size:   256)\n    Iter   514\t      0.08317707 (Batch Size:   256)\n    Iter   515\t      0.08947926 (Batch Size:   256)\n    Iter   516\t      0.08758676 (Batch Size:   256)\n    Iter   517\t      0.08713792 (Batch Size:   256)\n    Iter   518\t      0.08772014 (Batch Size:   256)\n    Iter   519\t      0.08758643 (Batch Size:   256)\n    Iter   520\t      0.09076716 (Batch Size:   256)\n    Iter   521\t      0.09303388 (Batch Size:   256)\n    Iter   522\t      0.08458616 (Batch Size:   256)\n    Iter   523\t      0.08876608 (Batch Size:   256)\n    Iter   524\t      0.08791203 (Batch Size:   256)\n    Iter   525\t      0.08349138 (Batch Size:   256)\n    Iter   526\t      0.09142849 (Batch Size:   256)\n    Iter   527\t      0.08868912 (Batch Size:   256)\n    Iter   528\t      0.09063483 (Batch Size:   256)\n    Iter   529\t      0.08800135 (Batch Size:   256)\n    Iter   530\t      0.09169139 (Batch Size:   256)\n    Iter   531\t      0.09645886 (Batch Size:   256)\n    Iter   532\t      0.09720489 (Batch Size:   256)\n    Iter   533\t      0.08673389 (Batch Size:   256)\n    Iter   534\t      0.08148563 (Batch Size:   256)\n    Iter   535\t      0.08617891 (Batch Size:   256)\n    Iter   536\t      0.08401859 (Batch Size:   256)\n    Iter   537\t      0.08774957 (Batch Size:   256)\n    Iter   538\t      0.09351012 (Batch Size:   256)\n    Iter   539\t      0.10454535 (Batch Size:   256)\n    Iter   540\t      0.08602627 (Batch Size:   256)\n    Iter   541\t      0.08961625 (Batch Size:   256)\n    Iter   542\t      0.08297731 (Batch Size:   256)\n    Iter   543\t      0.09080136 (Batch Size:   256)\n    Iter   544\t      0.08114738 (Batch Size:   256)\n    Iter   545\t      0.08617920 (Batch Size:   256)\n    Iter   546\t      0.08206220 (Batch Size:   256)\n    Iter   547\t      0.09163043 (Batch Size:   256)\n    Iter   548\t      0.08842944 (Batch Size:   256)\n    Iter   549\t      0.08776027 (Batch Size:   256)\n    Iter   550\t      0.09300747 (Batch Size:   256)\n    Iter   551\t      0.08430797 (Batch Size:   256)\n    Iter   552\t      0.08614085 (Batch Size:   256)\n    Iter   553\t      0.09000975 (Batch Size:   256)\n    Iter   554\t      0.08327881 (Batch Size:   256)\n    Iter   555\t      0.08857550 (Batch Size:   256)\n    Iter   556\t      0.08629348 (Batch Size:   256)\n    Iter   557\t      0.09034488 (Batch Size:   256)\n    Iter   558\t      0.08776967 (Batch Size:   256)\n    Iter   559\t      0.08756282 (Batch Size:   256)\n    Iter   560\t      0.08909331 (Batch Size:   256)\n    Iter   561\t      0.08223583 (Batch Size:   256)\n    Iter   562\t      0.09667352 (Batch Size:   256)\n    Iter   563\t      0.09442391 (Batch Size:   256)\n    Iter   564\t      0.08564503 (Batch Size:   256)\n    Iter   565\t      0.09259857 (Batch Size:   256)\n    Iter   566\t      0.09181095 (Batch Size:   256)\n    Iter   567\t      0.09229390 (Batch Size:   256)\n    Iter   568\t      0.08554625 (Batch Size:   256)\n    Iter   569\t      0.08098684 (Batch Size:   256)\n    Iter   570\t      0.08474045 (Batch Size:   256)\n    Iter   571\t      0.09012769 (Batch Size:   256)\n    Iter   572\t      0.10180729 (Batch Size:   256)\n    Iter   573\t      0.09584067 (Batch Size:   256)\n    Iter   574\t      0.08774555 (Batch Size:   256)\n    Iter   575\t      0.08238274 (Batch Size:   256)\n    Iter   576\t      0.08814409 (Batch Size:   256)\n    Iter   577\t      0.08436699 (Batch Size:   256)\n    Iter   578\t      0.09331591 (Batch Size:   256)\n    Iter   579\t      0.09993593 (Batch Size:   256)\n    Iter   580\t      0.10021292 (Batch Size:   256)\n    Iter   581\t      0.08693017 (Batch Size:   256)\n    Iter   582\t      0.08331307 (Batch Size:   256)\n    Iter   583\t      0.08824435 (Batch Size:   256)\n    Iter   584\t      0.08734282 (Batch Size:   256)\n    Iter   585\t      0.09330079 (Batch Size:   256)\n    Iter   586\t      0.08625307 (Batch Size:   256)\n    Iter   587\t      0.07949034 (Batch Size:   256)\n    Iter   588\t      0.08533762 (Batch Size:   256)\n    Iter   589\t      0.08371441 (Batch Size:   256)\n    Iter   590\t      0.07836637 (Batch Size:   256)\n    Iter   591\t      0.08135279 (Batch Size:   256)\n    Iter   592\t      0.09122324 (Batch Size:   256)\n    Iter   593\t      0.08711997 (Batch Size:   256)\n    Iter   594\t      0.08193603 (Batch Size:   256)\n    Iter   595\t      0.09322839 (Batch Size:   256)\n    Iter   596\t      0.08520987 (Batch Size:   256)\n    Iter   597\t      0.08645056 (Batch Size:   256)\n    Iter   598\t      0.08525159 (Batch Size:   256)\n    Iter   599\t      0.08416458 (Batch Size:   256)\n    Iter   600\t      0.08479471 (Batch Size:   256)\n    Iter   601\t      0.08278541 (Batch Size:   256)\n    Iter   602\t      0.08964649 (Batch Size:   256)\n    Iter   603\t      0.08176316 (Batch Size:   256)\n    Iter   604\t      0.07923805 (Batch Size:   256)\n    Iter   605\t      0.08148697 (Batch Size:   256)\n    Iter   606\t      0.08259664 (Batch Size:   256)\n    Iter   607\t      0.08847563 (Batch Size:   256)\n    Iter   608\t      0.08244678 (Batch Size:   256)\n    Iter   609\t      0.08662714 (Batch Size:   256)\n    Iter   610\t      0.08521590 (Batch Size:   256)\n    Iter   611\t      0.09597090 (Batch Size:   256)\n    Iter   612\t      0.08622226 (Batch Size:   256)\n    Iter   613\t      0.08338503 (Batch Size:   256)\n    Iter   614\t      0.07343969 (Batch Size:   256)\n    Iter   615\t      0.08494610 (Batch Size:   256)\n    Iter   616\t      0.09244007 (Batch Size:   256)\n    Iter   617\t      0.09484004 (Batch Size:   256)\n    Iter   618\t      0.10136102 (Batch Size:   256)\n    Iter   619\t      0.08268963 (Batch Size:   256)\n    Iter   620\t      0.08526904 (Batch Size:   256)\n    Iter   621\t      0.07934146 (Batch Size:   256)\n    Iter   622\t      0.08260659 (Batch Size:   256)\n    Iter   623\t      0.08305936 (Batch Size:   256)\n    Iter   624\t      0.07755493 (Batch Size:   256)\n    Iter   625\t      0.08348530 (Batch Size:   256)\n    Iter   626\t      0.08104289 (Batch Size:   256)\n    Iter   627\t      0.08869546 (Batch Size:   256)\n    Iter   628\t      0.07587019 (Batch Size:   256)\n    Iter   629\t      0.09686087 (Batch Size:   256)\n    Iter   630\t      0.09617436 (Batch Size:   256)\n    Iter   631\t      0.10181182 (Batch Size:   256)\n    Iter   632\t      0.08389290 (Batch Size:   256)\n    Iter   633\t      0.08451945 (Batch Size:   256)\n    Iter   634\t      0.09036837 (Batch Size:   256)\n    Iter   635\t      0.08762245 (Batch Size:   256)\n    Iter   636\t      0.08564319 (Batch Size:   256)\n    Iter   637\t      0.08102355 (Batch Size:   256)\n    Iter   638\t      0.09261818 (Batch Size:   256)\n    Iter   639\t      0.08064912 (Batch Size:   256)\n    Iter   640\t      0.08587845 (Batch Size:   256)\n    Iter   641\t      0.08007339 (Batch Size:   256)\n    Iter   642\t      0.07998956 (Batch Size:   256)\n    Iter   643\t      0.08339969 (Batch Size:   256)\n    Iter   644\t      0.08536894 (Batch Size:   256)\n    Iter   645\t      0.10899300 (Batch Size:   256)\n    Iter   646\t      0.10993382 (Batch Size:   256)\n    Iter   647\t      0.08388846 (Batch Size:   256)\n    Iter   648\t      0.08764411 (Batch Size:   256)\n    Iter   649\t      0.08246078 (Batch Size:   256)\n    Iter   650\t      0.08751735 (Batch Size:   256)\n    Iter   651\t      0.07912655 (Batch Size:   256)\n    Iter   652\t      0.08249378 (Batch Size:   256)\n    Iter   653\t      0.08296277 (Batch Size:   256)\n    Iter   654\t      0.08498795 (Batch Size:   256)\n    Iter   655\t      0.08358824 (Batch Size:   256)\n    Iter   656\t      0.08781418 (Batch Size:   256)\n    Iter   657\t      0.10373018 (Batch Size:   256)\n    Iter   658\t      0.09543576 (Batch Size:   256)\n    Iter   659\t      0.08148066 (Batch Size:   256)\n    Iter   660\t      0.08123754 (Batch Size:   256)\n    Iter   661\t      0.08075660 (Batch Size:   256)\n    Iter   662\t      0.08547788 (Batch Size:   256)\n    Iter   663\t      0.07924767 (Batch Size:   256)\n    Iter   664\t      0.07912899 (Batch Size:   256)\n    Iter   665\t      0.08231152 (Batch Size:   256)\n    Iter   666\t      0.08108805 (Batch Size:   256)\n    Iter   667\t      0.09683147 (Batch Size:   256)\n    Iter   668\t      0.08150777 (Batch Size:   256)\n    Iter   669\t      0.08523446 (Batch Size:   256)\n    Iter   670\t      0.08927063 (Batch Size:   256)\n    Iter   671\t      0.08150752 (Batch Size:   256)\n    Iter   672\t      0.08311822 (Batch Size:   256)\n    Iter   673\t      0.07768354 (Batch Size:   256)\n    Iter   674\t      0.07682457 (Batch Size:   256)\n    Iter   675\t      0.08648990 (Batch Size:   256)\n    Iter   676\t      0.08303110 (Batch Size:   256)\n    Iter   677\t      0.08263110 (Batch Size:   256)\n    Iter   678\t      0.08086352 (Batch Size:   256)\n    Iter   679\t      0.08089006 (Batch Size:   256)\n    Iter   680\t      0.07440981 (Batch Size:   256)\n    Iter   681\t      0.07938680 (Batch Size:   256)\n    Iter   682\t      0.07564347 (Batch Size:   256)\n    Iter   683\t      0.08407635 (Batch Size:   256)\n    Iter   684\t      0.08630168 (Batch Size:   256)\n    Iter   685\t      0.07969788 (Batch Size:   256)\n    Iter   686\t      0.08109451 (Batch Size:   256)\n    Iter   687\t      0.08348938 (Batch Size:   256)\n    Iter   688\t      0.08617061 (Batch Size:   256)\n    Iter   689\t      0.08011624 (Batch Size:   256)\n    Iter   690\t      0.08392228 (Batch Size:   256)\n    Iter   691\t      0.08369118 (Batch Size:   256)\n    Iter   692\t      0.09384165 (Batch Size:   256)\n    Iter   693\t      0.08563466 (Batch Size:   256)\n    Iter   694\t      0.08371408 (Batch Size:   256)\n    Iter   695\t      0.08437460 (Batch Size:   256)\n    Iter   696\t      0.09044575 (Batch Size:   256)\n    Iter   697\t      0.08421525 (Batch Size:   256)\n    Iter   698\t      0.08363358 (Batch Size:   256)\n    Iter   699\t      0.09805651 (Batch Size:   256)\n    Iter   700\t      0.09084921 (Batch Size:   256)\n    Iter   701\t      0.08076558 (Batch Size:   256)\n    Iter   702\t      0.08234279 (Batch Size:   256)\n    Iter   703\t      0.07823835 (Batch Size:   256)\n    Iter   704\t      0.08010047 (Batch Size:   256)\n    Iter   705\t      0.08053422 (Batch Size:   256)\n    Iter   706\t      0.07775509 (Batch Size:   256)\n    Iter   707\t      0.08691829 (Batch Size:   256)\n    Iter   708\t      0.08457691 (Batch Size:   256)\n    Iter   709\t      0.08089945 (Batch Size:   256)\n    Iter   710\t      0.08184306 (Batch Size:   256)\n    Iter   711\t      0.08654026 (Batch Size:   256)\n    Iter   712\t      0.08005181 (Batch Size:   256)\n    Iter   713\t      0.08341247 (Batch Size:   256)\n    Iter   714\t      0.07693913 (Batch Size:   256)\n    Iter   715\t      0.07650303 (Batch Size:   256)\n    Iter   716\t      0.09092095 (Batch Size:   256)\n    Iter   717\t      0.08643090 (Batch Size:   256)\n    Iter   718\t      0.08366836 (Batch Size:   256)\n    Iter   719\t      0.08262580 (Batch Size:   256)\n    Iter   720\t      0.08412508 (Batch Size:   256)\n    Iter   721\t      0.08172136 (Batch Size:   256)\n    Iter   722\t      0.08051988 (Batch Size:   256)\n    Iter   723\t      0.08997815 (Batch Size:   256)\n    Iter   724\t      0.08253498 (Batch Size:   256)\n    Iter   725\t      0.07968828 (Batch Size:   256)\n    Iter   726\t      0.08366597 (Batch Size:   256)\n    Iter   727\t      0.07822634 (Batch Size:   256)\n    Iter   728\t      0.08491451 (Batch Size:   256)\n    Iter   729\t      0.08444488 (Batch Size:   256)\n    Iter   730\t      0.08711362 (Batch Size:   256)\n    Iter   731\t      0.08150425 (Batch Size:   256)\n    Iter   732\t      0.08727448 (Batch Size:   256)\n    Iter   733\t      0.08298766 (Batch Size:   256)\n    Iter   734\t      0.08208539 (Batch Size:   256)\n    Iter   735\t      0.08403819 (Batch Size:   256)\n    Iter   736\t      0.08048345 (Batch Size:   256)\n    Iter   737\t      0.08090652 (Batch Size:   256)\n    Iter   738\t      0.08868793 (Batch Size:   256)\n    Iter   739\t      0.09041246 (Batch Size:   256)\n    Iter   740\t      0.07638280 (Batch Size:   256)\n    Iter   741\t      0.08780626 (Batch Size:   256)\n    Iter   742\t      0.08068448 (Batch Size:   256)\n    Iter   743\t      0.08502373 (Batch Size:   256)\n    Iter   744\t      0.10198394 (Batch Size:   256)\n    Iter   745\t      0.07954319 (Batch Size:   256)\n    Iter   746\t      0.08024516 (Batch Size:   256)\n    Iter   747\t      0.08336714 (Batch Size:   256)\n    Iter   748\t      0.08265097 (Batch Size:   256)\n    Iter   749\t      0.08236952 (Batch Size:   256)\n    Iter   750\t      0.08068988 (Batch Size:   256)\n    Iter   751\t      0.08743560 (Batch Size:   256)\n    Iter   752\t      0.08283094 (Batch Size:   256)\n    Iter   753\t      0.08601283 (Batch Size:   256)\n    Iter   754\t      0.07872904 (Batch Size:   256)\n    Iter   755\t      0.07956900 (Batch Size:   256)\n    Iter   756\t      0.08787680 (Batch Size:   256)\n    Iter   757\t      0.07679156 (Batch Size:   256)\n    Iter   758\t      0.07923606 (Batch Size:   256)\n    Iter   759\t      0.07870296 (Batch Size:   256)\n    Iter   760\t      0.08162047 (Batch Size:   256)\n    Iter   761\t      0.09217655 (Batch Size:   256)\n    Iter   762\t      0.09123726 (Batch Size:   256)\n    Iter   763\t      0.08830532 (Batch Size:   256)\n    Iter   764\t      0.07882733 (Batch Size:   256)\n    Iter   765\t      0.09050096 (Batch Size:   256)\n    Iter   766\t      0.08388091 (Batch Size:   256)\n    Iter   767\t      0.08349550 (Batch Size:   256)\n    Iter   768\t      0.09595371 (Batch Size:   256)\n    Iter   769\t      0.09817861 (Batch Size:   256)\n    Iter   770\t      0.08264229 (Batch Size:   256)\n    Iter   771\t      0.08184409 (Batch Size:   256)\n    Iter   772\t      0.08273294 (Batch Size:   256)\n    Iter   773\t      0.08064325 (Batch Size:   256)\n    Iter   774\t      0.08531465 (Batch Size:   256)\n    Iter   775\t      0.08781368 (Batch Size:   256)\n    Iter   776\t      0.09305200 (Batch Size:   256)\n    Iter   777\t      0.08709191 (Batch Size:   256)\n    Iter   778\t      0.08489555 (Batch Size:   256)\n    Iter   779\t      0.08107015 (Batch Size:   256)\n    Iter   780\t      0.07702486 (Batch Size:   256)\n    Iter   781\t      0.07460428 (Batch Size:   256)\n    Iter   782\t      0.08039698 (Batch Size:   256)\n    Iter   783\t      0.08433425 (Batch Size:   256)\n    Iter   784\t      0.08304237 (Batch Size:   256)\n    Iter   785\t      0.10410132 (Batch Size:   256)\n    Iter   786\t      0.08078868 (Batch Size:   256)\n    Iter   787\t      0.07806879 (Batch Size:   256)\n    Iter   788\t      0.08156565 (Batch Size:   256)\n    Iter   789\t      0.07983131 (Batch Size:   256)\n    Iter   790\t      0.08415883 (Batch Size:   256)\n    Iter   791\t      0.08728750 (Batch Size:   256)\n    Iter   792\t      0.08114153 (Batch Size:   256)\n    Iter   793\t      0.07877604 (Batch Size:   256)\n    Iter   794\t      0.08255752 (Batch Size:   256)\n    Iter   795\t      0.08303619 (Batch Size:   256)\n    Iter   796\t      0.09062198 (Batch Size:   256)\n    Iter   797\t      0.08857000 (Batch Size:   256)\n    Iter   798\t      0.08007484 (Batch Size:   256)\n    Iter   799\t      0.08362197 (Batch Size:   256)\n    Iter   800\t      0.08484747 (Batch Size:   256)\n    Iter   801\t      0.07966641 (Batch Size:   256)\n    Iter   802\t      0.08298899 (Batch Size:   256)\n    Iter   803\t      0.08268960 (Batch Size:   256)\n    Iter   804\t      0.07688306 (Batch Size:   256)\n    Iter   805\t      0.10094387 (Batch Size:   256)\n    Iter   806\t      0.08536267 (Batch Size:   256)\n    Iter   807\t      0.08904811 (Batch Size:   256)\n    Iter   808\t      0.08164401 (Batch Size:   256)\n    Iter   809\t      0.07977503 (Batch Size:   256)\n    Iter   810\t      0.07470137 (Batch Size:   256)\n    Iter   811\t      0.07679195 (Batch Size:   256)\n    Iter   812\t      0.07877543 (Batch Size:   256)\n    Iter   813\t      0.08798910 (Batch Size:   256)\n    Iter   814\t      0.09088890 (Batch Size:   256)\n    Iter   815\t      0.09141172 (Batch Size:   256)\n    Iter   816\t      0.09076590 (Batch Size:   256)\n    Iter   817\t      0.08246808 (Batch Size:   256)\n    Iter   818\t      0.08049104 (Batch Size:   256)\n    Iter   819\t      0.07766320 (Batch Size:   256)\n    Iter   820\t      0.07965849 (Batch Size:   256)\n    Iter   821\t      0.07829375 (Batch Size:   256)\n    Iter   822\t      0.07913877 (Batch Size:   256)\n    Iter   823\t      0.07252081 (Batch Size:   256)\n    Iter   824\t      0.07525043 (Batch Size:   256)\n    Iter   825\t      0.08431034 (Batch Size:   256)\n    Iter   826\t      0.07671438 (Batch Size:   256)\n    Iter   827\t      0.08148052 (Batch Size:   256)\n    Iter   828\t      0.08806626 (Batch Size:   256)\n    Iter   829\t      0.08640457 (Batch Size:   256)\n    Iter   830\t      0.08525874 (Batch Size:   256)\n    Iter   831\t      0.08825643 (Batch Size:   256)\n    Iter   832\t      0.08356345 (Batch Size:   256)\n    Iter   833\t      0.08811730 (Batch Size:   256)\n    Iter   834\t      0.08540287 (Batch Size:   256)\n    Iter   835\t      0.08785161 (Batch Size:   256)\n    Iter   836\t      0.08940187 (Batch Size:   256)\n    Iter   837\t      0.07988068 (Batch Size:   256)\n    Iter   838\t      0.07883391 (Batch Size:   256)\n    Iter   839\t      0.08909048 (Batch Size:   256)\n    Iter   840\t      0.09252138 (Batch Size:   256)\n    Iter   841\t      0.09233789 (Batch Size:   256)\n    Iter   842\t      0.08452407 (Batch Size:   256)\n    Iter   843\t      0.07672971 (Batch Size:   256)\n    Iter   844\t      0.08803587 (Batch Size:   256)\n    Iter   845\t      0.08101922 (Batch Size:   256)\n    Iter   846\t      0.07796179 (Batch Size:   256)\n    Iter   847\t      0.07728568 (Batch Size:   256)\n    Iter   848\t      0.08414194 (Batch Size:   256)\n    Iter   849\t      0.08768934 (Batch Size:   256)\n    Iter   850\t      0.08390484 (Batch Size:   256)\n    Iter   851\t      0.08406580 (Batch Size:   256)\n    Iter   852\t      0.08560369 (Batch Size:   256)\n    Iter   853\t      0.08837345 (Batch Size:   256)\n    Iter   854\t      0.08022686 (Batch Size:   256)\n    Iter   855\t      0.08212139 (Batch Size:   256)\n    Iter   856\t      0.08243163 (Batch Size:   256)\n    Iter   857\t      0.07978025 (Batch Size:   256)\n    Iter   858\t      0.08613130 (Batch Size:   256)\n    Iter   859\t      0.07813023 (Batch Size:   256)\n    Iter   860\t      0.07877573 (Batch Size:   256)\n    Iter   861\t      0.08053215 (Batch Size:   256)\n    Iter   862\t      0.07802990 (Batch Size:   256)\n    Iter   863\t      0.08813215 (Batch Size:   256)\n    Iter   864\t      0.07435038 (Batch Size:   256)\n    Iter   865\t      0.08528258 (Batch Size:   256)\n    Iter   866\t      0.07825448 (Batch Size:   256)\n    Iter   867\t      0.07916802 (Batch Size:   256)\n    Iter   868\t      0.08070217 (Batch Size:   256)\n    Iter   869\t      0.07722605 (Batch Size:   256)\n    Iter   870\t      0.08345045 (Batch Size:   256)\n    Iter   871\t      0.08730139 (Batch Size:   256)\n    Iter   872\t      0.07939592 (Batch Size:   256)\n    Iter   873\t      0.08278945 (Batch Size:   256)\n    Iter   874\t      0.08466679 (Batch Size:   256)\n    Iter   875\t      0.08131574 (Batch Size:   256)\n    Iter   876\t      0.07963099 (Batch Size:   256)\n    Iter   877\t      0.09070295 (Batch Size:   256)\n    Iter   878\t      0.08702340 (Batch Size:   256)\n    Iter   879\t      0.08263123 (Batch Size:   256)\n    Iter   880\t      0.08610046 (Batch Size:   256)\n    Iter   881\t      0.08378974 (Batch Size:   256)\n    Iter   882\t      0.09194785 (Batch Size:   256)\n    Iter   883\t      0.07662629 (Batch Size:   256)\n    Iter   884\t      0.07776246 (Batch Size:   256)\n    Iter   885\t      0.07992781 (Batch Size:   256)\n    Iter   886\t      0.08326827 (Batch Size:   256)\n    Iter   887\t      0.08583144 (Batch Size:   256)\n    Iter   888\t      0.07705082 (Batch Size:   256)\n    Iter   889\t      0.08526981 (Batch Size:   256)\n    Iter   890\t      0.08111324 (Batch Size:   256)\n    Iter   891\t      0.07917462 (Batch Size:   256)\n    Iter   892\t      0.08200754 (Batch Size:   256)\n    Iter   893\t      0.08443188 (Batch Size:   256)\n    Iter   894\t      0.07632001 (Batch Size:   256)\n    Iter   895\t      0.07719837 (Batch Size:   256)\n    Iter   896\t      0.07921937 (Batch Size:   256)\n    Iter   897\t      0.08574832 (Batch Size:   256)\n    Iter   898\t      0.07718448 (Batch Size:   256)\n    Iter   899\t      0.07589106 (Batch Size:   256)\n    Iter   900\t      0.07923908 (Batch Size:   256)\n    Iter   901\t      0.08053292 (Batch Size:   256)\n    Iter   902\t      0.08109431 (Batch Size:   256)\n    Iter   903\t      0.08044643 (Batch Size:   256)\n    Iter   904\t      0.08016929 (Batch Size:   256)\n    Iter   905\t      0.08309542 (Batch Size:   256)\n    Iter   906\t      0.08086233 (Batch Size:   256)\n    Iter   907\t      0.08132034 (Batch Size:   256)\n    Iter   908\t      0.09569842 (Batch Size:   256)\n    Iter   909\t      0.08654093 (Batch Size:   256)\n    Iter   910\t      0.07808337 (Batch Size:   256)\n    Iter   911\t      0.08643279 (Batch Size:   256)\n    Iter   912\t      0.10326723 (Batch Size:   256)\n    Iter   913\t      0.09764211 (Batch Size:   256)\n    Iter   914\t      0.09362958 (Batch Size:   256)\n    Iter   915\t      0.07827648 (Batch Size:   256)\n    Iter   916\t      0.07639845 (Batch Size:   256)\n    Iter   917\t      0.08077690 (Batch Size:   256)\n    Iter   918\t      0.07846729 (Batch Size:   256)\n    Iter   919\t      0.08131343 (Batch Size:   256)\n    Iter   920\t      0.08279596 (Batch Size:   256)\n    Iter   921\t      0.08065979 (Batch Size:   256)\n    Iter   922\t      0.08454700 (Batch Size:   256)\n    Iter   923\t      0.08488741 (Batch Size:   256)\n    Iter   924\t      0.09096126 (Batch Size:   256)\n    Iter   925\t      0.09389210 (Batch Size:   256)\n    Iter   926\t      0.08345542 (Batch Size:   256)\n    Iter   927\t      0.07736026 (Batch Size:   256)\n    Iter   928\t      0.08530662 (Batch Size:   256)\n    Iter   929\t      0.08636878 (Batch Size:   256)\n    Iter   930\t      0.07877821 (Batch Size:   256)\n    Iter   931\t      0.08195572 (Batch Size:   256)\n    Iter   932\t      0.08326199 (Batch Size:   256)\n    Iter   933\t      0.07593032 (Batch Size:   256)\n    Iter   934\t      0.07920241 (Batch Size:   256)\n    Iter   935\t      0.08295414 (Batch Size:   256)\n    Iter   936\t      0.08013788 (Batch Size:   256)\n    Iter   937\t      0.07740662 (Batch Size:   256)\n    Iter   938\t      0.07720036 (Batch Size:   256)\n    Iter   939\t      0.07481993 (Batch Size:   256)\n    Iter   940\t      0.08209387 (Batch Size:   256)\n    Iter   941\t      0.08552286 (Batch Size:   256)\n    Iter   942\t      0.08220499 (Batch Size:   256)\n    Iter   943\t      0.07931774 (Batch Size:   256)\n    Iter   944\t      0.07125235 (Batch Size:   256)\n    Iter   945\t      0.07763153 (Batch Size:   256)\n    Iter   946\t      0.08114937 (Batch Size:   256)\n    Iter   947\t      0.08305780 (Batch Size:   256)\n    Iter   948\t      0.10495173 (Batch Size:   256)\n    Iter   949\t      0.08288770 (Batch Size:   256)\n    Iter   950\t      0.07391044 (Batch Size:   256)\n    Iter   951\t      0.07533885 (Batch Size:   256)\n    Iter   952\t      0.07487464 (Batch Size:   256)\n    Iter   953\t      0.08254760 (Batch Size:   256)\n    Iter   954\t      0.08013015 (Batch Size:   256)\n    Iter   955\t      0.07912577 (Batch Size:   256)\n    Iter   956\t      0.07762353 (Batch Size:   256)\n    Iter   957\t      0.07526168 (Batch Size:   256)\n    Iter   958\t      0.08014352 (Batch Size:   256)\n    Iter   959\t      0.07691701 (Batch Size:   256)\n    Iter   960\t      0.07438766 (Batch Size:   256)\n    Iter   961\t      0.08415657 (Batch Size:   256)\n    Iter   962\t      0.08305258 (Batch Size:   256)\n    Iter   963\t      0.07756508 (Batch Size:   256)\n    Iter   964\t      0.07982711 (Batch Size:   256)\n    Iter   965\t      0.07978749 (Batch Size:   256)\n    Iter   966\t      0.07873383 (Batch Size:   256)\n    Iter   967\t      0.07782576 (Batch Size:   256)\n    Iter   968\t      0.07710368 (Batch Size:   256)\n    Iter   969\t      0.07860281 (Batch Size:   256)\n    Iter   970\t      0.08255787 (Batch Size:   256)\n    Iter   971\t      0.07990895 (Batch Size:   256)\n    Iter   972\t      0.08477764 (Batch Size:   256)\n    Iter   973\t      0.10147521 (Batch Size:   256)\n    Iter   974\t      0.10168502 (Batch Size:   256)\n    Iter   975\t      0.09129745 (Batch Size:   256)\n    Iter   976\t      0.09755077 (Batch Size:   256)\n    Iter   977\t      0.09371602 (Batch Size:   256)\n    Iter   978\t      0.08354429 (Batch Size:   256)\n    Iter   979\t      0.08822383 (Batch Size:   256)\n    Iter   980\t      0.08048097 (Batch Size:   256)\n    Iter   981\t      0.08618724 (Batch Size:   256)\n    Iter   982\t      0.08155863 (Batch Size:   256)\n    Iter   983\t      0.07794601 (Batch Size:   256)\n    Iter   984\t      0.07901703 (Batch Size:   256)\n    Iter   985\t      0.07635302 (Batch Size:   256)\n    Iter   986\t      0.08571122 (Batch Size:   256)\n    Iter   987\t      0.08009502 (Batch Size:   256)\n    Iter   988\t      0.07750144 (Batch Size:   256)\n    Iter   989\t      0.07773766 (Batch Size:   256)\n    Iter   990\t      0.07416729 (Batch Size:   256)\n    Iter   991\t      0.08772963 (Batch Size:   256)\n    Iter   992\t      0.08108414 (Batch Size:   256)\n    Iter   993\t      0.07978382 (Batch Size:   256)\n    Iter   994\t      0.08024392 (Batch Size:   256)\n    Iter   995\t      0.08353888 (Batch Size:   256)\n    Iter   996\t      0.08185096 (Batch Size:   256)\n    Iter   997\t      0.07904081 (Batch Size:   256)\n    Iter   998\t      0.08711336 (Batch Size:   256)\n    Iter   999\t      0.08892949 (Batch Size:   256)\n    Iter  1000\t      0.07990315 (Batch Size:   256)\n    Iter  1001\t      0.07979224 (Batch Size:   256)\n    Iter  1002\t      0.08188545 (Batch Size:   256)\n    Iter  1003\t      0.08358262 (Batch Size:   256)\n    Iter  1004\t      0.08106930 (Batch Size:   256)\n    Iter  1005\t      0.09200263 (Batch Size:   256)\n    Iter  1006\t      0.08646234 (Batch Size:   256)\n    Iter  1007\t      0.08113639 (Batch Size:   256)\n    Iter  1008\t      0.07970166 (Batch Size:   256)\n    Iter  1009\t      0.08030973 (Batch Size:   256)\n    Iter  1010\t      0.07300720 (Batch Size:   256)\n    Iter  1011\t      0.09080242 (Batch Size:   256)\n    Iter  1012\t      0.09535441 (Batch Size:   256)\n    Iter  1013\t      0.09324334 (Batch Size:   256)\n    Iter  1014\t      0.09535287 (Batch Size:   256)\n    Iter  1015\t      0.09208424 (Batch Size:   256)\n    Iter  1016\t      0.08583506 (Batch Size:   256)\n    Iter  1017\t      0.08000913 (Batch Size:   256)\n    Iter  1018\t      0.08359990 (Batch Size:   256)\n    Iter  1019\t      0.09084392 (Batch Size:   256)\n    Iter  1020\t      0.09936581 (Batch Size:   256)\n    Iter  1021\t      0.09119617 (Batch Size:   256)\n    Iter  1022\t      0.08063149 (Batch Size:   256)\n    Iter  1023\t      0.08082379 (Batch Size:   256)\n    Iter  1024\t      0.07673672 (Batch Size:   256)\n    Iter  1025\t      0.07937347 (Batch Size:   256)\n    Iter  1026\t      0.08708752 (Batch Size:   256)\n    Iter  1027\t      0.07794614 (Batch Size:   256)\n    Iter  1028\t      0.08164458 (Batch Size:   256)\n    Iter  1029\t      0.07890135 (Batch Size:   256)\n    Iter  1030\t      0.07506976 (Batch Size:   256)\n    Iter  1031\t      0.07731198 (Batch Size:   256)\n    Iter  1032\t      0.08448277 (Batch Size:   256)\n    Iter  1033\t      0.07548887 (Batch Size:   256)\n    Iter  1034\t      0.08154056 (Batch Size:   256)\n    Iter  1035\t      0.07792276 (Batch Size:   256)\n    Iter  1036\t      0.07842686 (Batch Size:   256)\n    Iter  1037\t      0.07871269 (Batch Size:   256)\n    Iter  1038\t      0.08100637 (Batch Size:   256)\n    Iter  1039\t      0.08016285 (Batch Size:   256)\n    Iter  1040\t      0.07748373 (Batch Size:   256)\n    Iter  1041\t      0.08694540 (Batch Size:   256)\n    Iter  1042\t      0.08377254 (Batch Size:   256)\n    Iter  1043\t      0.08261137 (Batch Size:   256)\n    Iter  1044\t      0.11131507 (Batch Size:   256)\n    Iter  1045\t      0.09291644 (Batch Size:   256)\n    Iter  1046\t      0.07968092 (Batch Size:   256)\n    Iter  1047\t      0.07832298 (Batch Size:   256)\n    Iter  1048\t      0.08063628 (Batch Size:   256)\n    Iter  1049\t      0.08044437 (Batch Size:   256)\n    Iter  1050\t      0.07699899 (Batch Size:   256)\n    Iter  1051\t      0.08054407 (Batch Size:   256)\n    Iter  1052\t      0.07767867 (Batch Size:   256)\n    Iter  1053\t      0.08497413 (Batch Size:   256)\n    Iter  1054\t      0.07750669 (Batch Size:   256)\n    Iter  1055\t      0.07422857 (Batch Size:   256)\n    Iter  1056\t      0.07635802 (Batch Size:   256)\n    Iter  1057\t      0.08455969 (Batch Size:   256)\n    Iter  1058\t      0.08405535 (Batch Size:   256)\n    Iter  1059\t      0.07799485 (Batch Size:   256)\n    Iter  1060\t      0.08055531 (Batch Size:   256)\n    Iter  1061\t      0.08436121 (Batch Size:   256)\n    Iter  1062\t      0.08435211 (Batch Size:   256)\n    Iter  1063\t      0.08283354 (Batch Size:   256)\n    Iter  1064\t      0.08557051 (Batch Size:   256)\n    Iter  1065\t      0.09428370 (Batch Size:   256)\n    Iter  1066\t      0.09256692 (Batch Size:   256)\n    Iter  1067\t      0.09863958 (Batch Size:   256)\n    Iter  1068\t      0.08842428 (Batch Size:   256)\n    Iter  1069\t      0.08502128 (Batch Size:   256)\n    Iter  1070\t      0.08506744 (Batch Size:   256)\n    Iter  1071\t      0.07868607 (Batch Size:   256)\n    Iter  1072\t      0.07582584 (Batch Size:   256)\n    Iter  1073\t      0.07195667 (Batch Size:   256)\n    Iter  1074\t      0.08220936 (Batch Size:   256)\n    Iter  1075\t      0.08017644 (Batch Size:   256)\n    Iter  1076\t      0.07963631 (Batch Size:   256)\n    Iter  1077\t      0.08101430 (Batch Size:   256)\n    Iter  1078\t      0.08030096 (Batch Size:   256)\n    Iter  1079\t      0.08396812 (Batch Size:   256)\n    Iter  1080\t      0.07681855 (Batch Size:   256)\n    Iter  1081\t      0.08327164 (Batch Size:   256)\n    Iter  1082\t      0.09147087 (Batch Size:   256)\n    Iter  1083\t      0.08348546 (Batch Size:   256)\n    Iter  1084\t      0.07813351 (Batch Size:   256)\n    Iter  1085\t      0.07896210 (Batch Size:   256)\n    Iter  1086\t      0.08039255 (Batch Size:   256)\n    Iter  1087\t      0.07684533 (Batch Size:   256)\n    Iter  1088\t      0.07606121 (Batch Size:   256)\n    Iter  1089\t      0.08123830 (Batch Size:   256)\n    Iter  1090\t      0.08245351 (Batch Size:   256)\n    Iter  1091\t      0.07506510 (Batch Size:   256)\n    Iter  1092\t      0.08020986 (Batch Size:   256)\n    Iter  1093\t      0.07802307 (Batch Size:   256)\n    Iter  1094\t      0.07659804 (Batch Size:   256)\n    Iter  1095\t      0.08137627 (Batch Size:   256)\n    Iter  1096\t      0.07864509 (Batch Size:   256)\n    Iter  1097\t      0.08178441 (Batch Size:   256)\n    Iter  1098\t      0.08050080 (Batch Size:   256)\n    Iter  1099\t      0.08087862 (Batch Size:   256)\n    Iter  1100\t      0.07945779 (Batch Size:   256)\n    Iter  1101\t      0.08240584 (Batch Size:   256)\n    Iter  1102\t      0.07900676 (Batch Size:   256)\n    Iter  1103\t      0.09873643 (Batch Size:   256)\n    Iter  1104\t      0.10297675 (Batch Size:   256)\n    Iter  1105\t      0.09433978 (Batch Size:   256)\n    Iter  1106\t      0.08849698 (Batch Size:   256)\n    Iter  1107\t      0.08418196 (Batch Size:   256)\n    Iter  1108\t      0.08245670 (Batch Size:   256)\n    Iter  1109\t      0.07964917 (Batch Size:   256)\n    Iter  1110\t      0.07679544 (Batch Size:   256)\n    Iter  1111\t      0.07175519 (Batch Size:   256)\n    Iter  1112\t      0.08196019 (Batch Size:   256)\n    Iter  1113\t      0.08091148 (Batch Size:   256)\n    Iter  1114\t      0.07801051 (Batch Size:   256)\n    Iter  1115\t      0.07628804 (Batch Size:   256)\n    Iter  1116\t      0.08084955 (Batch Size:   256)\n    Iter  1117\t      0.07823679 (Batch Size:   256)\n    Iter  1118\t      0.08050861 (Batch Size:   256)\n    Iter  1119\t      0.09222601 (Batch Size:   256)\n    Iter  1120\t      0.09720339 (Batch Size:   256)\n    Iter  1121\t      0.08138468 (Batch Size:   256)\n    Iter  1122\t      0.08017538 (Batch Size:   256)\n    Iter  1123\t      0.08061668 (Batch Size:   256)\n    Iter  1124\t      0.07749421 (Batch Size:   256)\n    Iter  1125\t      0.07719477 (Batch Size:   256)\n    Iter  1126\t      0.07574571 (Batch Size:   256)\n    Iter  1127\t      0.07568938 (Batch Size:   256)\n    Iter  1128\t      0.08582724 (Batch Size:   256)\n    Iter  1129\t      0.07966807 (Batch Size:   256)\n    Iter  1130\t      0.07489363 (Batch Size:   256)\n    Iter  1131\t      0.07896887 (Batch Size:   256)\n    Iter  1132\t      0.07852535 (Batch Size:   256)\n    Iter  1133\t      0.08292023 (Batch Size:   256)\n    Iter  1134\t      0.07987051 (Batch Size:   256)\n    Iter  1135\t      0.08091568 (Batch Size:   256)\n    Iter  1136\t      0.08056030 (Batch Size:   256)\n    Iter  1137\t      0.08335949 (Batch Size:   256)\n    Iter  1138\t      0.08145332 (Batch Size:   256)\n    Iter  1139\t      0.07629524 (Batch Size:   256)\n    Iter  1140\t      0.08728939 (Batch Size:   256)\n    Iter  1141\t      0.07699085 (Batch Size:   256)\n    Iter  1142\t      0.07752589 (Batch Size:   256)\n    Iter  1143\t      0.07509625 (Batch Size:   256)\n    Iter  1144\t      0.07536009 (Batch Size:   256)\n    Iter  1145\t      0.07219288 (Batch Size:   256)\n    Iter  1146\t      0.07949582 (Batch Size:   256)\n    Iter  1147\t      0.07820192 (Batch Size:   256)\n    Iter  1148\t      0.07406717 (Batch Size:   256)\n    Iter  1149\t      0.08171940 (Batch Size:   256)\n    Iter  1150\t      0.07876253 (Batch Size:   256)\n    Iter  1151\t      0.08390101 (Batch Size:   256)\n    Iter  1152\t      0.07864070 (Batch Size:   256)\n    Iter  1153\t      0.07979882 (Batch Size:   256)\n    Iter  1154\t      0.08305533 (Batch Size:   256)\n    Iter  1155\t      0.07751038 (Batch Size:   256)\n    Iter  1156\t      0.07918569 (Batch Size:   256)\n    Iter  1157\t      0.08135152 (Batch Size:   256)\n    Iter  1158\t      0.08012555 (Batch Size:   256)\n    Iter  1159\t      0.07610842 (Batch Size:   256)\n    Iter  1160\t      0.08225594 (Batch Size:   256)\n    Iter  1161\t      0.07400722 (Batch Size:   256)\n    Iter  1162\t      0.07871799 (Batch Size:   256)\n    Iter  1163\t      0.08443125 (Batch Size:   256)\n    Iter  1164\t      0.09010927 (Batch Size:   256)\n    Iter  1165\t      0.08747485 (Batch Size:   256)\n    Iter  1166\t      0.09198827 (Batch Size:   256)\n    Iter  1167\t      0.08425382 (Batch Size:   256)\n    Iter  1168\t      0.08794025 (Batch Size:   256)\n    Iter  1169\t      0.08063568 (Batch Size:   256)\n    Iter  1170\t      0.08038465 (Batch Size:   256)\n    Iter  1171\t      0.08282803 (Batch Size:   256)\n    Iter  1172\t      0.08751878 (Batch Size:   256)\n    Iter  1173\t      0.07321461 (Batch Size:   256)\n    Iter  1174\t      0.07718453 (Batch Size:   256)\n    Iter  1175\t      0.08076971 (Batch Size:   256)\n    Iter  1176\t      0.07844426 (Batch Size:   256)\n    Iter  1177\t      0.08127464 (Batch Size:   256)\n    Iter  1178\t      0.07973964 (Batch Size:   256)\n    Iter  1179\t      0.07636327 (Batch Size:   256)\n    Iter  1180\t      0.08073819 (Batch Size:   256)\n    Iter  1181\t      0.07568374 (Batch Size:   256)\n    Iter  1182\t      0.08159877 (Batch Size:   256)\n    Iter  1183\t      0.07511597 (Batch Size:   256)\n    Iter  1184\t      0.06978735 (Batch Size:   256)\n    Iter  1185\t      0.07942580 (Batch Size:   256)\n    Iter  1186\t      0.07754731 (Batch Size:   256)\n    Iter  1187\t      0.08403526 (Batch Size:   256)\n    Iter  1188\t      0.08162085 (Batch Size:   256)\n    Iter  1189\t      0.07402096 (Batch Size:   256)\n    Iter  1190\t      0.07949862 (Batch Size:   256)\n    Iter  1191\t      0.07753227 (Batch Size:   256)\n    Iter  1192\t      0.07787662 (Batch Size:   256)\n    Iter  1193\t      0.08381193 (Batch Size:   256)\n    Iter  1194\t      0.08610733 (Batch Size:   256)\n    Iter  1195\t      0.07622862 (Batch Size:   256)\n    Iter  1196\t      0.08357314 (Batch Size:   256)\n    Iter  1197\t      0.08334094 (Batch Size:   256)\n    Iter  1198\t      0.08035009 (Batch Size:   256)\n    Iter  1199\t      0.08481479 (Batch Size:   256)\n    Iter  1200\t      0.08203812 (Batch Size:   256)\n    Iter  1201\t      0.07742903 (Batch Size:   256)\n    Iter  1202\t      0.08625338 (Batch Size:   256)\n    Iter  1203\t      0.08200439 (Batch Size:   256)\n    Iter  1204\t      0.07774681 (Batch Size:   256)\n    Iter  1205\t      0.07729880 (Batch Size:   256)\n    Iter  1206\t      0.08034043 (Batch Size:   256)\n    Iter  1207\t      0.07724602 (Batch Size:   256)\n    Iter  1208\t      0.07766384 (Batch Size:   256)\n    Iter  1209\t      0.07715963 (Batch Size:   256)\n    Iter  1210\t      0.08331577 (Batch Size:   256)\n    Iter  1211\t      0.08861232 (Batch Size:   256)\n    Iter  1212\t      0.07177350 (Batch Size:   256)\n    Iter  1213\t      0.08217492 (Batch Size:   256)\n    Iter  1214\t      0.08017826 (Batch Size:   256)\n    Iter  1215\t      0.07764289 (Batch Size:   256)\n    Iter  1216\t      0.07688609 (Batch Size:   256)\n    Iter  1217\t      0.07142691 (Batch Size:   256)\n    Iter  1218\t      0.07672720 (Batch Size:   256)\n    Iter  1219\t      0.07227136 (Batch Size:   256)\n    Iter  1220\t      0.08277799 (Batch Size:   256)\n    Iter  1221\t      0.08625588 (Batch Size:   256)\n    Iter  1222\t      0.07781258 (Batch Size:   256)\n    Iter  1223\t      0.07538870 (Batch Size:   256)\n    Iter  1224\t      0.08049893 (Batch Size:   256)\n    Iter  1225\t      0.07508799 (Batch Size:   256)\n    Iter  1226\t      0.07448226 (Batch Size:   256)\n    Iter  1227\t      0.07885168 (Batch Size:   256)\n    Iter  1228\t      0.07528822 (Batch Size:   256)\n    Iter  1229\t      0.08318307 (Batch Size:   256)\n    Iter  1230\t      0.07816062 (Batch Size:   256)\n    Iter  1231\t      0.08148557 (Batch Size:   256)\n    Iter  1232\t      0.08149430 (Batch Size:   256)\n    Iter  1233\t      0.09973284 (Batch Size:   256)\n    Iter  1234\t      0.08653962 (Batch Size:   256)\n    Iter  1235\t      0.07979477 (Batch Size:   256)\n    Iter  1236\t      0.08113046 (Batch Size:   256)\n    Iter  1237\t      0.08004187 (Batch Size:   256)\n    Iter  1238\t      0.07778495 (Batch Size:   256)\n    Iter  1239\t      0.08193120 (Batch Size:   256)\n    Iter  1240\t      0.09014381 (Batch Size:   256)\n    Iter  1241\t      0.08129523 (Batch Size:   256)\n    Iter  1242\t      0.08579357 (Batch Size:   256)\n    Iter  1243\t      0.07706429 (Batch Size:   256)\n    Iter  1244\t      0.07057427 (Batch Size:   256)\n    Iter  1245\t      0.08027737 (Batch Size:   256)\n    Iter  1246\t      0.08103874 (Batch Size:   256)\n    Iter  1247\t      0.07352690 (Batch Size:   256)\n    Iter  1248\t      0.08117557 (Batch Size:   256)\n    Iter  1249\t      0.09035675 (Batch Size:   256)\n    Iter  1250\t      0.08140696 (Batch Size:   256)\n    Iter  1251\t      0.07328785 (Batch Size:   256)\n    Iter  1252\t      0.07577449 (Batch Size:   256)\n    Iter  1253\t      0.07788138 (Batch Size:   256)\n    Iter  1254\t      0.07612763 (Batch Size:   256)\n    Iter  1255\t      0.07898071 (Batch Size:   256)\n    Iter  1256\t      0.07648058 (Batch Size:   256)\n    Iter  1257\t      0.08058228 (Batch Size:   256)\n    Iter  1258\t      0.07897991 (Batch Size:   256)\n    Iter  1259\t      0.07746694 (Batch Size:   256)\n    Iter  1260\t      0.08113409 (Batch Size:   256)\n    Iter  1261\t      0.07930865 (Batch Size:   256)\n    Iter  1262\t      0.07728055 (Batch Size:   256)\n    Iter  1263\t      0.08799718 (Batch Size:   256)\n    Iter  1264\t      0.08307339 (Batch Size:   256)\n    Iter  1265\t      0.08025154 (Batch Size:   256)\n    Iter  1266\t      0.08043382 (Batch Size:   256)\n    Iter  1267\t      0.07634867 (Batch Size:   256)\n    Iter  1268\t      0.08094252 (Batch Size:   256)\n    Iter  1269\t      0.07715679 (Batch Size:   256)\n    Iter  1270\t      0.08140136 (Batch Size:   256)\n    Iter  1271\t      0.09265173 (Batch Size:   256)\n    Iter  1272\t      0.07595267 (Batch Size:   256)\n    Iter  1273\t      0.07754352 (Batch Size:   256)\n    Iter  1274\t      0.07539883 (Batch Size:   256)\n    Iter  1275\t      0.08201352 (Batch Size:   256)\n    Iter  1276\t      0.07880929 (Batch Size:   256)\n    Iter  1277\t      0.09028707 (Batch Size:   256)\n    Iter  1278\t      0.08152243 (Batch Size:   256)\n    Iter  1279\t      0.07466251 (Batch Size:   256)\n    Iter  1280\t      0.07663225 (Batch Size:   256)\n    Iter  1281\t      0.08000568 (Batch Size:   256)\n    Iter  1282\t      0.07639506 (Batch Size:   256)\n    Iter  1283\t      0.07825876 (Batch Size:   256)\n    Iter  1284\t      0.07509319 (Batch Size:   256)\n    Iter  1285\t      0.07537169 (Batch Size:   256)\n    Iter  1286\t      0.08032813 (Batch Size:   256)\n    Iter  1287\t      0.07377302 (Batch Size:   256)\n    Iter  1288\t      0.07142819 (Batch Size:   256)\n    Iter  1289\t      0.08082065 (Batch Size:   256)\n    Iter  1290\t      0.07727490 (Batch Size:   256)\n    Iter  1291\t      0.08870096 (Batch Size:   256)\n    Iter  1292\t      0.07585435 (Batch Size:   256)\n    Iter  1293\t      0.08149735 (Batch Size:   256)\n    Iter  1294\t      0.07971055 (Batch Size:   256)\n    Iter  1295\t      0.07952890 (Batch Size:   256)\n    Iter  1296\t      0.07791854 (Batch Size:   256)\n    Iter  1297\t      0.08651556 (Batch Size:   256)\n    Iter  1298\t      0.07968230 (Batch Size:   256)\n    Iter  1299\t      0.07894800 (Batch Size:   256)\n    Iter  1300\t      0.07387169 (Batch Size:   256)\n    Iter  1301\t      0.07516711 (Batch Size:   256)\n    Iter  1302\t      0.08514246 (Batch Size:   256)\n    Iter  1303\t      0.07824996 (Batch Size:   256)\n    Iter  1304\t      0.08011025 (Batch Size:   256)\n    Iter  1305\t      0.08141232 (Batch Size:   256)\n    Iter  1306\t      0.08339559 (Batch Size:   256)\n    Iter  1307\t      0.08132702 (Batch Size:   256)\n    Iter  1308\t      0.07945164 (Batch Size:   256)\n    Iter  1309\t      0.07899522 (Batch Size:   256)\n    Iter  1310\t      0.07459025 (Batch Size:   256)\n    Iter  1311\t      0.07410233 (Batch Size:   256)\n    Iter  1312\t      0.08725477 (Batch Size:   256)\n    Iter  1313\t      0.07939914 (Batch Size:   256)\n    Iter  1314\t      0.07586135 (Batch Size:   256)\n    Iter  1315\t      0.07843335 (Batch Size:   256)\n    Iter  1316\t      0.08332681 (Batch Size:   256)\n    Iter  1317\t      0.08546968 (Batch Size:   256)\n    Iter  1318\t      0.09923698 (Batch Size:   256)\n    Iter  1319\t      0.08315437 (Batch Size:   256)\n    Iter  1320\t      0.07672342 (Batch Size:   256)\n    Iter  1321\t      0.08638527 (Batch Size:   256)\n    Iter  1322\t      0.08919149 (Batch Size:   256)\n    Iter  1323\t      0.08142528 (Batch Size:   256)\n    Iter  1324\t      0.07787237 (Batch Size:   256)\n    Iter  1325\t      0.09062179 (Batch Size:   256)\n    Iter  1326\t      0.09314280 (Batch Size:   256)\n    Iter  1327\t      0.10023289 (Batch Size:   256)\n    Iter  1328\t      0.10235539 (Batch Size:   256)\n    Iter  1329\t      0.10431325 (Batch Size:   256)\n    Iter  1330\t      0.08121766 (Batch Size:   256)\n    Iter  1331\t      0.08107761 (Batch Size:   256)\n    Iter  1332\t      0.07628656 (Batch Size:   256)\n    Iter  1333\t      0.08099935 (Batch Size:   256)\n    Iter  1334\t      0.07462478 (Batch Size:   256)\n    Iter  1335\t      0.07735917 (Batch Size:   256)\n    Iter  1336\t      0.07347093 (Batch Size:   256)\n    Iter  1337\t      0.07462475 (Batch Size:   256)\n    Iter  1338\t      0.07700561 (Batch Size:   256)\n    Iter  1339\t      0.07698128 (Batch Size:   256)\n    Iter  1340\t      0.07650376 (Batch Size:   256)\n    Iter  1341\t      0.07954331 (Batch Size:   256)\n    Iter  1342\t      0.07966018 (Batch Size:   256)\n    Iter  1343\t      0.07807167 (Batch Size:   256)\n    Iter  1344\t      0.07786180 (Batch Size:   256)\n    Iter  1345\t      0.07514005 (Batch Size:   256)\n    Iter  1346\t      0.07596584 (Batch Size:   256)\n    Iter  1347\t      0.07627327 (Batch Size:   256)\n    Iter  1348\t      0.07942220 (Batch Size:   256)\n    Iter  1349\t      0.08295269 (Batch Size:   256)\n    Iter  1350\t      0.07448158 (Batch Size:   256)\n    Iter  1351\t      0.08268602 (Batch Size:   256)\n    Iter  1352\t      0.07691429 (Batch Size:   256)\n    Iter  1353\t      0.08063208 (Batch Size:   256)\n    Iter  1354\t      0.08417778 (Batch Size:   256)\n    Iter  1355\t      0.07798532 (Batch Size:   256)\n    Iter  1356\t      0.07449148 (Batch Size:   256)\n    Iter  1357\t      0.08251764 (Batch Size:   256)\n    Iter  1358\t      0.08349110 (Batch Size:   256)\n    Iter  1359\t      0.07795144 (Batch Size:   256)\n    Iter  1360\t      0.08315694 (Batch Size:   256)\n    Iter  1361\t      0.07800819 (Batch Size:   256)\n    Iter  1362\t      0.08420692 (Batch Size:   256)\n    Iter  1363\t      0.08513775 (Batch Size:   256)\n    Iter  1364\t      0.07993102 (Batch Size:   256)\n    Iter  1365\t      0.07739078 (Batch Size:   256)\n    Iter  1366\t      0.07365384 (Batch Size:   256)\n    Iter  1367\t      0.07695078 (Batch Size:   256)\n    Iter  1368\t      0.07651821 (Batch Size:   256)\n    Iter  1369\t      0.07583299 (Batch Size:   256)\n    Iter  1370\t      0.08924887 (Batch Size:   256)\n    Iter  1371\t      0.07771378 (Batch Size:   256)\n    Iter  1372\t      0.07642060 (Batch Size:   256)\n    Iter  1373\t      0.07413542 (Batch Size:   256)\n    Iter  1374\t      0.08583063 (Batch Size:   256)\n    Iter  1375\t      0.07871635 (Batch Size:   256)\n    Iter  1376\t      0.07738574 (Batch Size:   256)\n    Iter  1377\t      0.08501427 (Batch Size:   256)\n    Iter  1378\t      0.07883798 (Batch Size:   256)\n    Iter  1379\t      0.07377365 (Batch Size:   256)\n    Iter  1380\t      0.07644338 (Batch Size:   256)\n    Iter  1381\t      0.08149355 (Batch Size:   256)\n    Iter  1382\t      0.08681972 (Batch Size:   256)\n    Iter  1383\t      0.08151393 (Batch Size:   256)\n    Iter  1384\t      0.07691795 (Batch Size:   256)\n    Iter  1385\t      0.07724281 (Batch Size:   256)\n    Iter  1386\t      0.08952023 (Batch Size:   256)\n    Iter  1387\t      0.09691527 (Batch Size:   256)\n    Iter  1388\t      0.08786850 (Batch Size:   256)\n    Iter  1389\t      0.08275147 (Batch Size:   256)\n    Iter  1390\t      0.07713232 (Batch Size:   256)\n    Iter  1391\t      0.08047438 (Batch Size:   256)\n    Iter  1392\t      0.07715601 (Batch Size:   256)\n    Iter  1393\t      0.07941660 (Batch Size:   256)\n    Iter  1394\t      0.08450184 (Batch Size:   256)\n    Iter  1395\t      0.07933760 (Batch Size:   256)\n    Iter  1396\t      0.07454052 (Batch Size:   256)\n    Iter  1397\t      0.07917703 (Batch Size:   256)\n    Iter  1398\t      0.07849153 (Batch Size:   256)\n    Iter  1399\t      0.08575389 (Batch Size:   256)\n    Iter  1400\t      0.08076897 (Batch Size:   256)\n    Iter  1401\t      0.08213725 (Batch Size:   256)\n    Iter  1402\t      0.08003857 (Batch Size:   256)\n    Iter  1403\t      0.07843180 (Batch Size:   256)\n    Iter  1404\t      0.07873596 (Batch Size:   256)\n    Iter  1405\t      0.07769563 (Batch Size:   256)\n    Iter  1406\t      0.08239830 (Batch Size:   256)\n    Iter  1407\t      0.07826207 (Batch Size:   256)\n    Iter  1408\t      0.08596969 (Batch Size:   256)\n    Iter  1409\t      0.07944470 (Batch Size:   256)\n    Iter  1410\t      0.08205538 (Batch Size:   256)\n    Iter  1411\t      0.07958603 (Batch Size:   256)\n    Iter  1412\t      0.07787730 (Batch Size:   256)\n    Iter  1413\t      0.07835350 (Batch Size:   256)\n    Iter  1414\t      0.07422516 (Batch Size:   256)\n    Iter  1415\t      0.08128321 (Batch Size:   256)\n    Iter  1416\t      0.07932715 (Batch Size:   256)\n    Iter  1417\t      0.07523119 (Batch Size:   256)\n    Iter  1418\t      0.07582162 (Batch Size:   256)\n    Iter  1419\t      0.07759673 (Batch Size:   256)\n    Iter  1420\t      0.07900648 (Batch Size:   256)\n    Iter  1421\t      0.07262003 (Batch Size:   256)\n    Iter  1422\t      0.07562671 (Batch Size:   256)\n    Iter  1423\t      0.07741538 (Batch Size:   256)\n    Iter  1424\t      0.07643933 (Batch Size:   256)\n    Iter  1425\t      0.09068655 (Batch Size:   256)\n    Iter  1426\t      0.08292225 (Batch Size:   256)\n    Iter  1427\t      0.07237793 (Batch Size:   256)\n    Iter  1428\t      0.08395363 (Batch Size:   256)\n    Iter  1429\t      0.08288722 (Batch Size:   256)\n    Iter  1430\t      0.07613798 (Batch Size:   256)\n    Iter  1431\t      0.07522909 (Batch Size:   256)\n    Iter  1432\t      0.07564824 (Batch Size:   256)\n    Iter  1433\t      0.08093077 (Batch Size:   256)\n    Iter  1434\t      0.07348637 (Batch Size:   256)\n    Iter  1435\t      0.08717671 (Batch Size:   256)\n    Iter  1436\t      0.08124285 (Batch Size:   256)\n    Iter  1437\t      0.07622598 (Batch Size:   256)\n    Iter  1438\t      0.07188536 (Batch Size:   256)\n    Iter  1439\t      0.08384992 (Batch Size:   256)\n    Iter  1440\t      0.08136375 (Batch Size:   256)\n    Iter  1441\t      0.07838627 (Batch Size:   256)\n    Iter  1442\t      0.07845507 (Batch Size:   256)\n    Iter  1443\t      0.08049185 (Batch Size:   256)\n    Iter  1444\t      0.08812136 (Batch Size:   256)\n    Iter  1445\t      0.09619621 (Batch Size:   256)\n    Iter  1446\t      0.08439215 (Batch Size:   256)\n    Iter  1447\t      0.07873901 (Batch Size:   256)\n    Iter  1448\t      0.07892010 (Batch Size:   256)\n    Iter  1449\t      0.07374393 (Batch Size:   256)\n    Iter  1450\t      0.08005470 (Batch Size:   256)\n    Iter  1451\t      0.08111384 (Batch Size:   256)\n    Iter  1452\t      0.07544016 (Batch Size:   256)\n    Iter  1453\t      0.07457062 (Batch Size:   256)\n    Iter  1454\t      0.07880809 (Batch Size:   256)\n    Iter  1455\t      0.08389110 (Batch Size:   256)\n    Iter  1456\t      0.09784239 (Batch Size:   256)\n    Iter  1457\t      0.09389351 (Batch Size:   256)\n    Iter  1458\t      0.08272851 (Batch Size:   256)\n    Iter  1459\t      0.08378024 (Batch Size:   256)\n    Iter  1460\t      0.07649947 (Batch Size:   256)\n    Iter  1461\t      0.07931385 (Batch Size:   256)\n    Iter  1462\t      0.07619790 (Batch Size:   256)\n    Iter  1463\t      0.07990202 (Batch Size:   256)\n    Iter  1464\t      0.08116706 (Batch Size:   256)\n    Iter  1465\t      0.07897244 (Batch Size:   256)\n    Iter  1466\t      0.07803052 (Batch Size:   256)\n    Iter  1467\t      0.07901933 (Batch Size:   256)\n    Iter  1468\t      0.07781620 (Batch Size:   256)\n    Iter  1469\t      0.08289933 (Batch Size:   256)\n    Iter  1470\t      0.08401658 (Batch Size:   256)\n    Iter  1471\t      0.08099204 (Batch Size:   256)\n    Iter  1472\t      0.07746901 (Batch Size:   256)\n    Iter  1473\t      0.08100249 (Batch Size:   256)\n    Iter  1474\t      0.08164575 (Batch Size:   256)\n    Iter  1475\t      0.07689526 (Batch Size:   256)\n    Iter  1476\t      0.07629387 (Batch Size:   256)\n    Iter  1477\t      0.08019684 (Batch Size:   256)\n    Iter  1478\t      0.07626544 (Batch Size:   256)\n    Iter  1479\t      0.08883340 (Batch Size:   256)\n    Iter  1480\t      0.09328717 (Batch Size:   256)\n    Iter  1481\t      0.08002312 (Batch Size:   256)\n    Iter  1482\t      0.08057226 (Batch Size:   256)\n    Iter  1483\t      0.08519019 (Batch Size:   256)\n    Iter  1484\t      0.07812054 (Batch Size:   256)\n    Iter  1485\t      0.08720219 (Batch Size:   256)\n    Iter  1486\t      0.08562838 (Batch Size:   256)\n    Iter  1487\t      0.09254090 (Batch Size:   256)\n    Iter  1488\t      0.08363370 (Batch Size:   256)\n    Iter  1489\t      0.08942425 (Batch Size:   256)\n    Iter  1490\t      0.09020593 (Batch Size:   256)\n    Iter  1491\t      0.08013855 (Batch Size:   256)\n    Iter  1492\t      0.07972762 (Batch Size:   256)\n    Iter  1493\t      0.07539522 (Batch Size:   256)\n    Iter  1494\t      0.08088344 (Batch Size:   256)\n    Iter  1495\t      0.08290887 (Batch Size:   256)\n    Iter  1496\t      0.07963779 (Batch Size:   256)\n    Iter  1497\t      0.07631551 (Batch Size:   256)\n    Iter  1498\t      0.07354797 (Batch Size:   256)\n    Iter  1499\t      0.07993627 (Batch Size:   256)\n    Iter  1500\t      0.07586457 (Batch Size:   256)\n    Iter  1501\t      0.07799362 (Batch Size:   256)\n    Iter  1502\t      0.07581795 (Batch Size:   256)\n    Iter  1503\t      0.07781173 (Batch Size:   256)\n    Iter  1504\t      0.08006121 (Batch Size:   256)\n    Iter  1505\t      0.08291600 (Batch Size:   256)\n    Iter  1506\t      0.08827052 (Batch Size:   256)\n    Iter  1507\t      0.08209248 (Batch Size:   256)\n    Iter  1508\t      0.08059906 (Batch Size:   256)\n    Iter  1509\t      0.08121480 (Batch Size:   256)\n    Iter  1510\t      0.07627182 (Batch Size:   256)\n    Iter  1511\t      0.07790912 (Batch Size:   256)\n    Iter  1512\t      0.07473612 (Batch Size:   256)\n    Iter  1513\t      0.07857536 (Batch Size:   256)\n    Iter  1514\t      0.08016866 (Batch Size:   256)\n    Iter  1515\t      0.07889746 (Batch Size:   256)\n    Iter  1516\t      0.07655407 (Batch Size:   256)\n    Iter  1517\t      0.07299575 (Batch Size:   256)\n    Iter  1518\t      0.07417744 (Batch Size:   256)\n    Iter  1519\t      0.07766978 (Batch Size:   256)\n    Iter  1520\t      0.07564531 (Batch Size:   256)\n    Iter  1521\t      0.07597102 (Batch Size:   256)\n    Iter  1522\t      0.08942173 (Batch Size:   256)\n    Iter  1523\t      0.09483418 (Batch Size:   256)\n    Iter  1524\t      0.08058695 (Batch Size:   256)\n    Iter  1525\t      0.07552819 (Batch Size:   256)\n    Iter  1526\t      0.08533145 (Batch Size:   256)\n    Iter  1527\t      0.08788653 (Batch Size:   256)\n    Iter  1528\t      0.10061640 (Batch Size:   256)\n    Iter  1529\t      0.08566687 (Batch Size:   256)\n    Iter  1530\t      0.07286724 (Batch Size:   256)\n    Iter  1531\t      0.07846424 (Batch Size:   256)\n    Iter  1532\t      0.08906720 (Batch Size:   256)\n    Iter  1533\t      0.08288102 (Batch Size:   256)\n    Iter  1534\t      0.08378176 (Batch Size:   256)\n    Iter  1535\t      0.08650300 (Batch Size:   256)\n    Iter  1536\t      0.07986088 (Batch Size:   256)\n    Iter  1537\t      0.07980515 (Batch Size:   256)\n    Iter  1538\t      0.07532085 (Batch Size:   256)\n    Iter  1539\t      0.07837928 (Batch Size:   256)\n    Iter  1540\t      0.07633682 (Batch Size:   256)\n    Iter  1541\t      0.07523446 (Batch Size:   256)\n    Iter  1542\t      0.07122778 (Batch Size:   256)\n    Iter  1543\t      0.07981642 (Batch Size:   256)\n    Iter  1544\t      0.07637262 (Batch Size:   256)\n    Iter  1545\t      0.07548008 (Batch Size:   256)\n    Iter  1546\t      0.08019348 (Batch Size:   256)\n    Iter  1547\t      0.08000781 (Batch Size:   256)\n    Iter  1548\t      0.08167777 (Batch Size:   256)\n    Iter  1549\t      0.07866726 (Batch Size:   256)\n    Iter  1550\t      0.07885853 (Batch Size:   256)\n    Iter  1551\t      0.07590333 (Batch Size:   256)\n    Iter  1552\t      0.07799080 (Batch Size:   256)\n    Iter  1553\t      0.07423770 (Batch Size:   256)\n    Iter  1554\t      0.07812604 (Batch Size:   256)\n    Iter  1555\t      0.07867012 (Batch Size:   256)\n    Iter  1556\t      0.07571918 (Batch Size:   256)\n    Iter  1557\t      0.07825802 (Batch Size:   256)\n    Iter  1558\t      0.07597160 (Batch Size:   256)\n    Iter  1559\t      0.07617555 (Batch Size:   256)\n    Iter  1560\t      0.08067711 (Batch Size:   256)\n    Iter  1561\t      0.08080533 (Batch Size:   256)\n    Iter  1562\t      0.09298973 (Batch Size:   256)\n    Iter  1563\t      0.08132382 (Batch Size:   256)\n    Iter  1564\t      0.07868986 (Batch Size:   256)\n    Iter  1565\t      0.08299817 (Batch Size:   256)\n    Iter  1566\t      0.07517943 (Batch Size:   256)\n    Iter  1567\t      0.07560375 (Batch Size:   256)\n    Iter  1568\t      0.07415185 (Batch Size:   256)\n    Iter  1569\t      0.07577610 (Batch Size:   256)\n    Iter  1570\t      0.08180489 (Batch Size:   256)\n    Iter  1571\t      0.07734290 (Batch Size:   256)\n    Iter  1572\t      0.07691108 (Batch Size:   256)\n    Iter  1573\t      0.07317070 (Batch Size:   256)\n    Iter  1574\t      0.07576015 (Batch Size:   256)\n    Iter  1575\t      0.07285881 (Batch Size:   256)\n    Iter  1576\t      0.07657952 (Batch Size:   256)\n    Iter  1577\t      0.07644174 (Batch Size:   256)\n    Iter  1578\t      0.07820731 (Batch Size:   256)\n    Iter  1579\t      0.07784433 (Batch Size:   256)\n    Iter  1580\t      0.07605897 (Batch Size:   256)\n    Iter  1581\t      0.07831433 (Batch Size:   256)\n    Iter  1582\t      0.09019738 (Batch Size:   256)\n    Iter  1583\t      0.08885149 (Batch Size:   256)\n    Iter  1584\t      0.08105812 (Batch Size:   256)\n    Iter  1585\t      0.08677912 (Batch Size:   256)\n    Iter  1586\t      0.08898528 (Batch Size:   256)\n    Iter  1587\t      0.08714956 (Batch Size:   256)\n    Iter  1588\t      0.07940127 (Batch Size:   256)\n    Iter  1589\t      0.07705269 (Batch Size:   256)\n    Iter  1590\t      0.07400758 (Batch Size:   256)\n    Iter  1591\t      0.07348225 (Batch Size:   256)\n    Iter  1592\t      0.07729544 (Batch Size:   256)\n    Iter  1593\t      0.08649972 (Batch Size:   256)\n    Iter  1594\t      0.07936211 (Batch Size:   256)\n    Iter  1595\t      0.08368318 (Batch Size:   256)\n    Iter  1596\t      0.07511752 (Batch Size:   256)\n    Iter  1597\t      0.07827661 (Batch Size:   256)\n    Iter  1598\t      0.07569637 (Batch Size:   256)\n    Iter  1599\t      0.07807973 (Batch Size:   256)\n    Iter  1600\t      0.07687019 (Batch Size:   256)\n    Iter  1601\t      0.07561243 (Batch Size:   256)\n    Iter  1602\t      0.07681788 (Batch Size:   256)\n    Iter  1603\t      0.07961016 (Batch Size:   256)\n    Iter  1604\t      0.08100314 (Batch Size:   256)\n    Iter  1605\t      0.07541867 (Batch Size:   256)\n    Iter  1606\t      0.07982933 (Batch Size:   256)\n    Iter  1607\t      0.07789278 (Batch Size:   256)\n    Iter  1608\t      0.08824475 (Batch Size:   256)\n    Iter  1609\t      0.08202473 (Batch Size:   256)\n    Iter  1610\t      0.07379398 (Batch Size:   256)\n    Iter  1611\t      0.07556310 (Batch Size:   256)\n    Iter  1612\t      0.07501096 (Batch Size:   256)\n    Iter  1613\t      0.07802038 (Batch Size:   256)\n    Iter  1614\t      0.08097963 (Batch Size:   256)\n    Iter  1615\t      0.07197910 (Batch Size:   256)\n    Iter  1616\t      0.07676059 (Batch Size:   256)\n    Iter  1617\t      0.08586570 (Batch Size:   256)\n    Iter  1618\t      0.08770330 (Batch Size:   256)\n    Iter  1619\t      0.07459355 (Batch Size:   256)\n    Iter  1620\t      0.08048211 (Batch Size:   256)\n    Iter  1621\t      0.09752886 (Batch Size:   256)\n    Iter  1622\t      0.09370019 (Batch Size:   256)\n    Iter  1623\t      0.08807400 (Batch Size:   256)\n    Iter  1624\t      0.07850939 (Batch Size:   256)\n    Iter  1625\t      0.07492619 (Batch Size:   256)\n    Iter  1626\t      0.07939453 (Batch Size:   256)\n    Iter  1627\t      0.08167851 (Batch Size:   256)\n    Iter  1628\t      0.07953563 (Batch Size:   256)\n    Iter  1629\t      0.07994407 (Batch Size:   256)\n    Iter  1630\t      0.07521650 (Batch Size:   256)\n    Iter  1631\t      0.07969888 (Batch Size:   256)\n    Iter  1632\t      0.08008417 (Batch Size:   256)\n    Iter  1633\t      0.08560942 (Batch Size:   256)\n    Iter  1634\t      0.08506681 (Batch Size:   256)\n    Iter  1635\t      0.08122548 (Batch Size:   256)\n    Iter  1636\t      0.07148303 (Batch Size:   256)\n    Iter  1637\t      0.07724567 (Batch Size:   256)\n    Iter  1638\t      0.08797671 (Batch Size:   256)\n    Iter  1639\t      0.08706644 (Batch Size:   256)\n    Iter  1640\t      0.07900109 (Batch Size:   256)\n    Iter  1641\t      0.07577645 (Batch Size:   256)\n    Iter  1642\t      0.09819233 (Batch Size:   256)\n    Iter  1643\t      0.08489815 (Batch Size:   256)\n    Iter  1644\t      0.08121458 (Batch Size:   256)\n    Iter  1645\t      0.08076363 (Batch Size:   256)\n    Iter  1646\t      0.07844025 (Batch Size:   256)\n    Iter  1647\t      0.08057721 (Batch Size:   256)\n    Iter  1648\t      0.07171494 (Batch Size:   256)\n    Iter  1649\t      0.07770446 (Batch Size:   256)\n    Iter  1650\t      0.07750877 (Batch Size:   256)\n    Iter  1651\t      0.07672448 (Batch Size:   256)\n    Iter  1652\t      0.08190037 (Batch Size:   256)\n    Iter  1653\t      0.08178714 (Batch Size:   256)\n    Iter  1654\t      0.08016042 (Batch Size:   256)\n    Iter  1655\t      0.07781156 (Batch Size:   256)\n    Iter  1656\t      0.08329438 (Batch Size:   256)\n    Iter  1657\t      0.08084878 (Batch Size:   256)\n    Iter  1658\t      0.09265427 (Batch Size:   256)\n    Iter  1659\t      0.09081839 (Batch Size:   256)\n    Iter  1660\t      0.07784221 (Batch Size:   256)\n    Iter  1661\t      0.07452054 (Batch Size:   256)\n    Iter  1662\t      0.07788324 (Batch Size:   256)\n    Iter  1663\t      0.07331635 (Batch Size:   256)\n    Iter  1664\t      0.07915169 (Batch Size:   256)\n    Iter  1665\t      0.06997757 (Batch Size:   256)\n    Iter  1666\t      0.07701448 (Batch Size:   256)\n    Iter  1667\t      0.07657892 (Batch Size:   256)\n    Iter  1668\t      0.08606636 (Batch Size:   256)\n    Iter  1669\t      0.07955333 (Batch Size:   256)\n    Iter  1670\t      0.07462571 (Batch Size:   256)\n    Iter  1671\t      0.07685937 (Batch Size:   256)\n    Iter  1672\t      0.07521273 (Batch Size:   256)\n    Iter  1673\t      0.07417967 (Batch Size:   256)\n    Iter  1674\t      0.07331195 (Batch Size:   256)\n    Iter  1675\t      0.07415314 (Batch Size:   256)\n    Iter  1676\t      0.07562329 (Batch Size:   256)\n    Iter  1677\t      0.07677398 (Batch Size:   256)\n    Iter  1678\t      0.07828520 (Batch Size:   256)\n    Iter  1679\t      0.08202500 (Batch Size:   256)\n    Iter  1680\t      0.07539375 (Batch Size:   256)\n    Iter  1681\t      0.08314283 (Batch Size:   256)\n    Iter  1682\t      0.07333261 (Batch Size:   256)\n    Iter  1683\t      0.07942718 (Batch Size:   256)\n    Iter  1684\t      0.08019988 (Batch Size:   256)\n    Iter  1685\t      0.07554693 (Batch Size:   256)\n    Iter  1686\t      0.08629985 (Batch Size:   256)\n    Iter  1687\t      0.07753541 (Batch Size:   256)\n    Iter  1688\t      0.07631441 (Batch Size:   256)\n    Iter  1689\t      0.07950304 (Batch Size:   256)\n    Iter  1690\t      0.08153753 (Batch Size:   256)\n    Iter  1691\t      0.08211447 (Batch Size:   256)\n    Iter  1692\t      0.07406375 (Batch Size:   256)\n    Iter  1693\t      0.07567369 (Batch Size:   256)\n    Iter  1694\t      0.08082952 (Batch Size:   256)\n    Iter  1695\t      0.07230099 (Batch Size:   256)\n    Iter  1696\t      0.07714600 (Batch Size:   256)\n    Iter  1697\t      0.07802181 (Batch Size:   256)\n    Iter  1698\t      0.08427882 (Batch Size:   256)\n    Iter  1699\t      0.07793703 (Batch Size:   256)\n    Iter  1700\t      0.08859269 (Batch Size:   256)\n    Iter  1701\t      0.08213211 (Batch Size:   256)\n    Iter  1702\t      0.07857671 (Batch Size:   256)\n    Iter  1703\t      0.07930759 (Batch Size:   256)\n    Iter  1704\t      0.07443860 (Batch Size:   256)\n    Iter  1705\t      0.08115532 (Batch Size:   256)\n    Iter  1706\t      0.07489099 (Batch Size:   256)\n    Iter  1707\t      0.07489155 (Batch Size:   256)\n    Iter  1708\t      0.07831514 (Batch Size:   256)\n    Iter  1709\t      0.07437091 (Batch Size:   256)\n    Iter  1710\t      0.07521995 (Batch Size:   256)\n    Iter  1711\t      0.08001393 (Batch Size:   256)\n    Iter  1712\t      0.07978155 (Batch Size:   256)\n    Iter  1713\t      0.08279789 (Batch Size:   256)\n    Iter  1714\t      0.07694276 (Batch Size:   256)\n    Iter  1715\t      0.07484839 (Batch Size:   256)\n    Iter  1716\t      0.07372421 (Batch Size:   256)\n    Iter  1717\t      0.07678987 (Batch Size:   256)\n    Iter  1718\t      0.07462207 (Batch Size:   256)\n    Iter  1719\t      0.07443307 (Batch Size:   256)\n    Iter  1720\t      0.07958285 (Batch Size:   256)\n    Iter  1721\t      0.07682059 (Batch Size:   256)\n    Iter  1722\t      0.08546900 (Batch Size:   256)\n    Iter  1723\t      0.07248364 (Batch Size:   256)\n    Iter  1724\t      0.07145940 (Batch Size:   256)\n    Iter  1725\t      0.07576424 (Batch Size:   256)\n    Iter  1726\t      0.09000234 (Batch Size:   256)\n    Iter  1727\t      0.07709996 (Batch Size:   256)\n    Iter  1728\t      0.07697604 (Batch Size:   256)\n    Iter  1729\t      0.08040198 (Batch Size:   256)\n    Iter  1730\t      0.07866017 (Batch Size:   256)\n    Iter  1731\t      0.07417821 (Batch Size:   256)\n    Iter  1732\t      0.07446568 (Batch Size:   256)\n    Iter  1733\t      0.07463665 (Batch Size:   256)\n    Iter  1734\t      0.07712147 (Batch Size:   256)\n    Iter  1735\t      0.08121548 (Batch Size:   256)\n    Iter  1736\t      0.09205218 (Batch Size:   256)\n    Iter  1737\t      0.08137457 (Batch Size:   256)\n    Iter  1738\t      0.08255852 (Batch Size:   256)\n    Iter  1739\t      0.07624565 (Batch Size:   256)\n    Iter  1740\t      0.07892559 (Batch Size:   256)\n    Iter  1741\t      0.08009121 (Batch Size:   256)\n    Iter  1742\t      0.08669503 (Batch Size:   256)\n    Iter  1743\t      0.08599534 (Batch Size:   256)\n    Iter  1744\t      0.07509365 (Batch Size:   256)\n    Iter  1745\t      0.07323941 (Batch Size:   256)\n    Iter  1746\t      0.08038993 (Batch Size:   256)\n    Iter  1747\t      0.08096376 (Batch Size:   256)\n    Iter  1748\t      0.08675898 (Batch Size:   256)\n    Iter  1749\t      0.07412894 (Batch Size:   256)\n    Iter  1750\t      0.07822824 (Batch Size:   256)\n    Iter  1751\t      0.07989733 (Batch Size:   256)\n    Iter  1752\t      0.07782334 (Batch Size:   256)\n    Iter  1753\t      0.07272969 (Batch Size:   256)\n    Iter  1754\t      0.07455948 (Batch Size:   256)\n    Iter  1755\t      0.07244638 (Batch Size:   256)\n    Iter  1756\t      0.07798987 (Batch Size:   256)\n    Iter  1757\t      0.07752128 (Batch Size:   256)\n    Iter  1758\t      0.07748663 (Batch Size:   256)\n    Iter  1759\t      0.07845378 (Batch Size:   256)\n    Iter  1760\t      0.07836926 (Batch Size:   256)\n    Iter  1761\t      0.07984948 (Batch Size:   256)\n    Iter  1762\t      0.07859466 (Batch Size:   256)\n    Iter  1763\t      0.07582770 (Batch Size:   256)\n    Iter  1764\t      0.07290682 (Batch Size:   256)\n    Iter  1765\t      0.07624952 (Batch Size:   256)\n    Iter  1766\t      0.07429768 (Batch Size:   256)\n    Iter  1767\t      0.08269957 (Batch Size:   256)\n    Iter  1768\t      0.09486961 (Batch Size:   256)\n    Iter  1769\t      0.09081642 (Batch Size:   256)\n    Iter  1770\t      0.07952086 (Batch Size:   256)\n    Iter  1771\t      0.08061423 (Batch Size:   256)\n    Iter  1772\t      0.08285589 (Batch Size:   256)\n    Iter  1773\t      0.07963414 (Batch Size:   256)\n    Iter  1774\t      0.08563254 (Batch Size:   256)\n    Iter  1775\t      0.08604405 (Batch Size:   256)\n    Iter  1776\t      0.07950246 (Batch Size:   256)\n    Iter  1777\t      0.08212638 (Batch Size:   256)\n    Iter  1778\t      0.07498214 (Batch Size:   256)\n    Iter  1779\t      0.07247898 (Batch Size:   256)\n    Iter  1780\t      0.07772886 (Batch Size:   256)\n    Iter  1781\t      0.07875495 (Batch Size:   256)\n    Iter  1782\t      0.07750473 (Batch Size:   256)\n    Iter  1783\t      0.07845926 (Batch Size:   256)\n    Iter  1784\t      0.08856013 (Batch Size:   256)\n    Iter  1785\t      0.08434079 (Batch Size:   256)\n    Iter  1786\t      0.08002750 (Batch Size:   256)\n    Iter  1787\t      0.08022849 (Batch Size:   256)\n    Iter  1788\t      0.07159169 (Batch Size:   256)\n    Iter  1789\t      0.07843485 (Batch Size:   256)\n    Iter  1790\t      0.07075374 (Batch Size:   256)\n    Iter  1791\t      0.08117324 (Batch Size:   256)\n    Iter  1792\t      0.07306485 (Batch Size:   256)\n    Iter  1793\t      0.07443703 (Batch Size:   256)\n    Iter  1794\t      0.07978743 (Batch Size:   256)\n    Iter  1795\t      0.07715412 (Batch Size:   256)\n    Iter  1796\t      0.07646234 (Batch Size:   256)\n    Iter  1797\t      0.07956189 (Batch Size:   256)\n    Iter  1798\t      0.07740637 (Batch Size:   256)\n    Iter  1799\t      0.08822903 (Batch Size:   256)\n    Iter  1800\t      0.08286946 (Batch Size:   256)\n    Iter  1801\t      0.08948728 (Batch Size:   256)\n    Iter  1802\t      0.08166426 (Batch Size:   256)\n    Iter  1803\t      0.07486315 (Batch Size:   256)\n    Iter  1804\t      0.07624599 (Batch Size:   256)\n    Iter  1805\t      0.07557541 (Batch Size:   256)\n    Iter  1806\t      0.07785393 (Batch Size:   256)\n    Iter  1807\t      0.07720726 (Batch Size:   256)\n    Iter  1808\t      0.07544585 (Batch Size:   256)\n    Iter  1809\t      0.08235174 (Batch Size:   256)\n    Iter  1810\t      0.07511310 (Batch Size:   256)\n    Iter  1811\t      0.07298352 (Batch Size:   256)\n    Iter  1812\t      0.07614592 (Batch Size:   256)\n    Iter  1813\t      0.07372834 (Batch Size:   256)\n    Iter  1814\t      0.07729702 (Batch Size:   256)\n    Iter  1815\t      0.08587303 (Batch Size:   256)\n    Iter  1816\t      0.07833416 (Batch Size:   256)\n    Iter  1817\t      0.07302296 (Batch Size:   256)\n    Iter  1818\t      0.07252139 (Batch Size:   256)\n    Iter  1819\t      0.07503341 (Batch Size:   256)\n    Iter  1820\t      0.07628399 (Batch Size:   256)\n    Iter  1821\t      0.07461833 (Batch Size:   256)\n    Iter  1822\t      0.08184557 (Batch Size:   256)\n    Iter  1823\t      0.07675383 (Batch Size:   256)\n    Iter  1824\t      0.07963400 (Batch Size:   256)\n    Iter  1825\t      0.07329480 (Batch Size:   256)\n    Iter  1826\t      0.07913788 (Batch Size:   256)\n    Iter  1827\t      0.07466417 (Batch Size:   256)\n    Iter  1828\t      0.08280875 (Batch Size:   256)\n    Iter  1829\t      0.07972077 (Batch Size:   256)\n    Iter  1830\t      0.09231383 (Batch Size:   256)\n    Iter  1831\t      0.08540665 (Batch Size:   256)\n    Iter  1832\t      0.08391547 (Batch Size:   256)\n    Iter  1833\t      0.08199297 (Batch Size:   256)\n    Iter  1834\t      0.07346037 (Batch Size:   256)\n    Iter  1835\t      0.07240380 (Batch Size:   256)\n    Iter  1836\t      0.08719376 (Batch Size:   256)\n    Iter  1837\t      0.09415393 (Batch Size:   256)\n    Iter  1838\t      0.08366457 (Batch Size:   256)\n    Iter  1839\t      0.08223205 (Batch Size:   256)\n    Iter  1840\t      0.08432621 (Batch Size:   256)\n    Iter  1841\t      0.08734750 (Batch Size:   256)\n    Iter  1842\t      0.08056883 (Batch Size:   256)\n    Iter  1843\t      0.07976896 (Batch Size:   256)\n    Iter  1844\t      0.07556648 (Batch Size:   256)\n    Iter  1845\t      0.07775308 (Batch Size:   256)\n    Iter  1846\t      0.07449543 (Batch Size:   256)\n    Iter  1847\t      0.07582080 (Batch Size:   256)\n    Iter  1848\t      0.07282584 (Batch Size:   256)\n    Iter  1849\t      0.07270396 (Batch Size:   256)\n    Iter  1850\t      0.07227711 (Batch Size:   256)\n    Iter  1851\t      0.07991018 (Batch Size:   256)\n    Iter  1852\t      0.08442822 (Batch Size:   256)\n    Iter  1853\t      0.07692794 (Batch Size:   256)\n    Iter  1854\t      0.07025904 (Batch Size:   256)\n    Iter  1855\t      0.07579493 (Batch Size:   256)\n    Iter  1856\t      0.07486684 (Batch Size:   256)\n    Iter  1857\t      0.07562118 (Batch Size:   256)\n    Iter  1858\t      0.07798873 (Batch Size:   256)\n    Iter  1859\t      0.07618343 (Batch Size:   256)\n    Iter  1860\t      0.08642222 (Batch Size:   256)\n    Iter  1861\t      0.08767064 (Batch Size:   256)\n    Iter  1862\t      0.07559969 (Batch Size:   256)\n    Iter  1863\t      0.07669800 (Batch Size:   256)\n    Iter  1864\t      0.08093509 (Batch Size:   256)\n    Iter  1865\t      0.08656994 (Batch Size:   256)\n    Iter  1866\t      0.08964525 (Batch Size:   256)\n    Iter  1867\t      0.07672370 (Batch Size:   256)\n    Iter  1868\t      0.07183214 (Batch Size:   256)\n    Iter  1869\t      0.08007091 (Batch Size:   256)\n    Iter  1870\t      0.08049796 (Batch Size:   256)\n    Iter  1871\t      0.07495404 (Batch Size:   256)\n    Iter  1872\t      0.07649650 (Batch Size:   256)\n    Iter  1873\t      0.07624689 (Batch Size:   256)\n    Iter  1874\t      0.07490961 (Batch Size:   256)\n    Iter  1875\t      0.08168968 (Batch Size:   256)\n    Iter  1876\t      0.07302166 (Batch Size:   256)\n    Iter  1877\t      0.07727344 (Batch Size:   256)\n    Iter  1878\t      0.07326234 (Batch Size:   256)\n    Iter  1879\t      0.07360123 (Batch Size:   256)\n    Iter  1880\t      0.07833563 (Batch Size:   256)\n    Iter  1881\t      0.07537000 (Batch Size:   256)\n    Iter  1882\t      0.07652369 (Batch Size:   256)\n    Iter  1883\t      0.08258755 (Batch Size:   256)\n    Iter  1884\t      0.07645779 (Batch Size:   256)\n    Iter  1885\t      0.07754601 (Batch Size:   256)\n    Iter  1886\t      0.07544657 (Batch Size:   256)\n    Iter  1887\t      0.07770841 (Batch Size:   256)\n    Iter  1888\t      0.08039982 (Batch Size:   256)\n    Iter  1889\t      0.07810941 (Batch Size:   256)\n    Iter  1890\t      0.08014999 (Batch Size:   256)\n    Iter  1891\t      0.07637337 (Batch Size:   256)\n    Iter  1892\t      0.07840263 (Batch Size:   256)\n    Iter  1893\t      0.07381248 (Batch Size:   256)\n    Iter  1894\t      0.07880236 (Batch Size:   256)\n    Iter  1895\t      0.07021731 (Batch Size:   256)\n    Iter  1896\t      0.07904795 (Batch Size:   256)\n    Iter  1897\t      0.08031880 (Batch Size:   256)\n    Iter  1898\t      0.07801750 (Batch Size:   256)\n    Iter  1899\t      0.07159667 (Batch Size:   256)\n    Iter  1900\t      0.08208930 (Batch Size:   256)\n    Iter  1901\t      0.08702013 (Batch Size:   256)\n    Iter  1902\t      0.09065318 (Batch Size:   256)\n    Iter  1903\t      0.09687282 (Batch Size:   256)\n    Iter  1904\t      0.09007487 (Batch Size:   256)\n    Iter  1905\t      0.08766794 (Batch Size:   256)\n    Iter  1906\t      0.08060475 (Batch Size:   256)\n    Iter  1907\t      0.08060949 (Batch Size:   256)\n    Iter  1908\t      0.07638722 (Batch Size:   256)\n    Iter  1909\t      0.07448817 (Batch Size:   256)\n    Iter  1910\t      0.07416580 (Batch Size:   256)\n    Iter  1911\t      0.07669409 (Batch Size:   256)\n    Iter  1912\t      0.07750536 (Batch Size:   256)\n    Iter  1913\t      0.08072557 (Batch Size:   256)\n    Iter  1914\t      0.07606748 (Batch Size:   256)\n    Iter  1915\t      0.07758270 (Batch Size:   256)\n    Iter  1916\t      0.07582617 (Batch Size:   256)\n    Iter  1917\t      0.08694545 (Batch Size:   256)\n    Iter  1918\t      0.08460594 (Batch Size:   256)\n    Iter  1919\t      0.07739322 (Batch Size:   256)\n    Iter  1920\t      0.07766988 (Batch Size:   256)\n    Iter  1921\t      0.08643227 (Batch Size:   256)\n    Iter  1922\t      0.08128742 (Batch Size:   256)\n    Iter  1923\t      0.08398448 (Batch Size:   256)\n    Iter  1924\t      0.07607705 (Batch Size:   256)\n    Iter  1925\t      0.08035761 (Batch Size:   256)\n    Iter  1926\t      0.07808463 (Batch Size:   256)\n    Iter  1927\t      0.08602827 (Batch Size:   256)\n    Iter  1928\t      0.08363955 (Batch Size:   256)\n    Iter  1929\t      0.07375285 (Batch Size:   256)\n    Iter  1930\t      0.07948616 (Batch Size:   256)\n    Iter  1931\t      0.08044133 (Batch Size:   256)\n    Iter  1932\t      0.07247679 (Batch Size:   256)\n    Iter  1933\t      0.07621266 (Batch Size:   256)\n    Iter  1934\t      0.07554919 (Batch Size:   256)\n    Iter  1935\t      0.07133104 (Batch Size:   256)\n    Iter  1936\t      0.07326183 (Batch Size:   256)\n    Iter  1937\t      0.07926244 (Batch Size:   256)\n    Iter  1938\t      0.08159225 (Batch Size:   256)\n    Iter  1939\t      0.08502055 (Batch Size:   256)\n    Iter  1940\t      0.08198669 (Batch Size:   256)\n    Iter  1941\t      0.08630819 (Batch Size:   256)\n    Iter  1942\t      0.08474478 (Batch Size:   256)\n    Iter  1943\t      0.07796303 (Batch Size:   256)\n    Iter  1944\t      0.07573117 (Batch Size:   256)\n    Iter  1945\t      0.07811293 (Batch Size:   256)\n    Iter  1946\t      0.07979549 (Batch Size:   256)\n    Iter  1947\t      0.08263793 (Batch Size:   256)\n    Iter  1948\t      0.07578470 (Batch Size:   256)\n    Iter  1949\t      0.07371088 (Batch Size:   256)\n    Iter  1950\t      0.07156331 (Batch Size:   256)\n    Iter  1951\t      0.07494016 (Batch Size:   256)\n    Iter  1952\t      0.07060444 (Batch Size:   256)\n    Iter  1953\t      0.07437318 (Batch Size:   256)\n    Iter  1954\t      0.07409621 (Batch Size:   256)\n    Iter  1955\t      0.07546865 (Batch Size:   256)\n    Iter  1956\t      0.07329131 (Batch Size:   256)\n    Iter  1957\t      0.07739687 (Batch Size:   256)\n    Iter  1958\t      0.07452433 (Batch Size:   256)\n    Iter  1959\t      0.07308418 (Batch Size:   256)\n    Iter  1960\t      0.07720102 (Batch Size:   256)\n    Iter  1961\t      0.08618817 (Batch Size:   256)\n    Iter  1962\t      0.07917277 (Batch Size:   256)\n    Iter  1963\t      0.08002104 (Batch Size:   256)\n    Iter  1964\t      0.08023568 (Batch Size:   256)\n    Iter  1965\t      0.07347883 (Batch Size:   256)\n    Iter  1966\t      0.07802616 (Batch Size:   256)\n    Iter  1967\t      0.07739769 (Batch Size:   256)\n    Iter  1968\t      0.07234796 (Batch Size:   256)\n    Iter  1969\t      0.08306497 (Batch Size:   256)\n    Iter  1970\t      0.09604017 (Batch Size:   256)\n    Iter  1971\t      0.09445118 (Batch Size:   256)\n    Iter  1972\t      0.07959663 (Batch Size:   256)\n    Iter  1973\t      0.07953560 (Batch Size:   256)\n    Iter  1974\t      0.07377334 (Batch Size:   256)\n    Iter  1975\t      0.08151773 (Batch Size:   256)\n    Iter  1976\t      0.07825247 (Batch Size:   256)\n    Iter  1977\t      0.07713322 (Batch Size:   256)\n    Iter  1978\t      0.07524754 (Batch Size:   256)\n    Iter  1979\t      0.07586258 (Batch Size:   256)\n    Iter  1980\t      0.07525024 (Batch Size:   256)\n    Iter  1981\t      0.07514974 (Batch Size:   256)\n    Iter  1982\t      0.07919874 (Batch Size:   256)\n    Iter  1983\t      0.07148814 (Batch Size:   256)\n    Iter  1984\t      0.07479205 (Batch Size:   256)\n    Iter  1985\t      0.07781964 (Batch Size:   256)\n    Iter  1986\t      0.07892210 (Batch Size:   256)\n    Iter  1987\t      0.07205197 (Batch Size:   256)\n    Iter  1988\t      0.07690056 (Batch Size:   256)\n    Iter  1989\t      0.08375751 (Batch Size:   256)\n    Iter  1990\t      0.08178990 (Batch Size:   256)\n    Iter  1991\t      0.07769974 (Batch Size:   256)\n    Iter  1992\t      0.07484460 (Batch Size:   256)\n    Iter  1993\t      0.07235488 (Batch Size:   256)\n    Iter  1994\t      0.07476429 (Batch Size:   256)\n    Iter  1995\t      0.07819249 (Batch Size:   256)\n    Iter  1996\t      0.07820695 (Batch Size:   256)\n    Iter  1997\t      0.07300138 (Batch Size:   256)\n    Iter  1998\t      0.07389712 (Batch Size:   256)\n    Iter  1999\t      0.08419446 (Batch Size:   256)\n    Iter  2000\t      0.07270361 (Batch Size:   256)\n    Iter  2001\t      0.07718927 (Batch Size:   256)\n    Iter  2002\t      0.08273310 (Batch Size:   256)\n    Iter  2003\t      0.07860117 (Batch Size:   256)\n    Iter  2004\t      0.07204225 (Batch Size:   256)\n    Iter  2005\t      0.07513869 (Batch Size:   256)\n    Iter  2006\t      0.07438502 (Batch Size:   256)\n    Iter  2007\t      0.07481120 (Batch Size:   256)\n    Iter  2008\t      0.07791247 (Batch Size:   256)\n    Iter  2009\t      0.07621039 (Batch Size:   256)\n    Iter  2010\t      0.07385959 (Batch Size:   256)\n    Iter  2011\t      0.07983176 (Batch Size:   256)\n    Iter  2012\t      0.07762876 (Batch Size:   256)\n    Iter  2013\t      0.08445963 (Batch Size:   256)\n    Iter  2014\t      0.07347293 (Batch Size:   256)\n    Iter  2015\t      0.07584186 (Batch Size:   256)\n    Iter  2016\t      0.08069926 (Batch Size:   256)\n    Iter  2017\t      0.07567163 (Batch Size:   256)\n    Iter  2018\t      0.07873248 (Batch Size:   256)\n    Iter  2019\t      0.07221815 (Batch Size:   256)\n    Iter  2020\t      0.08543545 (Batch Size:   256)\n    Iter  2021\t      0.07533053 (Batch Size:   256)\n    Iter  2022\t      0.07981106 (Batch Size:   256)\n    Iter  2023\t      0.07367332 (Batch Size:   256)\n    Iter  2024\t      0.07196656 (Batch Size:   256)\n    Iter  2025\t      0.08392846 (Batch Size:   256)\n    Iter  2026\t      0.08933508 (Batch Size:   256)\n    Iter  2027\t      0.07923820 (Batch Size:   256)\n    Iter  2028\t      0.07613235 (Batch Size:   256)\n    Iter  2029\t      0.08220392 (Batch Size:   256)\n    Iter  2030\t      0.07890137 (Batch Size:   256)\n    Iter  2031\t      0.07514893 (Batch Size:   256)\n    Iter  2032\t      0.07994415 (Batch Size:   256)\n    Iter  2033\t      0.07869867 (Batch Size:   256)\n    Iter  2034\t      0.07771951 (Batch Size:   256)\n    Iter  2035\t      0.07409432 (Batch Size:   256)\n    Iter  2036\t      0.08212620 (Batch Size:   256)\n    Iter  2037\t      0.07703421 (Batch Size:   256)\n    Iter  2038\t      0.07912136 (Batch Size:   256)\n    Iter  2039\t      0.07928571 (Batch Size:   256)\n    Iter  2040\t      0.07732226 (Batch Size:   256)\n    Iter  2041\t      0.08039042 (Batch Size:   256)\n    Iter  2042\t      0.08307828 (Batch Size:   256)\n    Iter  2043\t      0.08576813 (Batch Size:   256)\n    Iter  2044\t      0.08262924 (Batch Size:   256)\n    Iter  2045\t      0.07413579 (Batch Size:   256)\n    Iter  2046\t      0.07111687 (Batch Size:   256)\n    Iter  2047\t      0.07657493 (Batch Size:   256)\n    Iter  2048\t      0.07270161 (Batch Size:   256)\n    Iter  2049\t      0.08098934 (Batch Size:   256)\n    Iter  2050\t      0.07499922 (Batch Size:   256)\n    Iter  2051\t      0.07655283 (Batch Size:   256)\n    Iter  2052\t      0.07837732 (Batch Size:   256)\n    Iter  2053\t      0.08997859 (Batch Size:   256)\n    Iter  2054\t      0.07181039 (Batch Size:   256)\n    Iter  2055\t      0.07344468 (Batch Size:   256)\n    Iter  2056\t      0.07450842 (Batch Size:   256)\n    Iter  2057\t      0.07480799 (Batch Size:   256)\n    Iter  2058\t      0.07987159 (Batch Size:   256)\n    Iter  2059\t      0.07971852 (Batch Size:   256)\n    Iter  2060\t      0.07620928 (Batch Size:   256)\n    Iter  2061\t      0.07524142 (Batch Size:   256)\n    Iter  2062\t      0.08024090 (Batch Size:   256)\n    Iter  2063\t      0.07650230 (Batch Size:   256)\n    Iter  2064\t      0.07803021 (Batch Size:   256)\n    Iter  2065\t      0.07079012 (Batch Size:   256)\n    Iter  2066\t      0.07663371 (Batch Size:   256)\n    Iter  2067\t      0.07242446 (Batch Size:   256)\n    Iter  2068\t      0.07203559 (Batch Size:   256)\n    Iter  2069\t      0.07762843 (Batch Size:   256)\n    Iter  2070\t      0.07188985 (Batch Size:   256)\n    Iter  2071\t      0.07774191 (Batch Size:   256)\n    Iter  2072\t      0.07697588 (Batch Size:   256)\n    Iter  2073\t      0.07153522 (Batch Size:   256)\n    Iter  2074\t      0.07746991 (Batch Size:   256)\n    Iter  2075\t      0.08228712 (Batch Size:   256)\n    Iter  2076\t      0.08014251 (Batch Size:   256)\n    Iter  2077\t      0.08018054 (Batch Size:   256)\n    Iter  2078\t      0.08221529 (Batch Size:   256)\n    Iter  2079\t      0.08304349 (Batch Size:   256)\n    Iter  2080\t      0.08028136 (Batch Size:   256)\n    Iter  2081\t      0.07813932 (Batch Size:   256)\n    Iter  2082\t      0.07336987 (Batch Size:   256)\n    Iter  2083\t      0.07555554 (Batch Size:   256)\n    Iter  2084\t      0.07485939 (Batch Size:   256)\n    Iter  2085\t      0.07506938 (Batch Size:   256)\n    Iter  2086\t      0.07870314 (Batch Size:   256)\n    Iter  2087\t      0.07930791 (Batch Size:   256)\n    Iter  2088\t      0.07678102 (Batch Size:   256)\n    Iter  2089\t      0.08855409 (Batch Size:   256)\n    Iter  2090\t      0.08285423 (Batch Size:   256)\n    Iter  2091\t      0.07702600 (Batch Size:   256)\n    Iter  2092\t      0.07743158 (Batch Size:   256)\n    Iter  2093\t      0.07852190 (Batch Size:   256)\n    Iter  2094\t      0.07583867 (Batch Size:   256)\n    Iter  2095\t      0.07566572 (Batch Size:   256)\n    Iter  2096\t      0.07302920 (Batch Size:   256)\n    Iter  2097\t      0.07189512 (Batch Size:   256)\n    Iter  2098\t      0.07702239 (Batch Size:   256)\n    Iter  2099\t      0.07368743 (Batch Size:   256)\n    Iter  2100\t      0.07511665 (Batch Size:   256)\n    Iter  2101\t      0.07572365 (Batch Size:   256)\n    Iter  2102\t      0.08028962 (Batch Size:   256)\n    Iter  2103\t      0.07122356 (Batch Size:   256)\n    Iter  2104\t      0.07407500 (Batch Size:   256)\n    Iter  2105\t      0.07439869 (Batch Size:   256)\n    Iter  2106\t      0.07134278 (Batch Size:   256)\n    Iter  2107\t      0.07646010 (Batch Size:   256)\n    Iter  2108\t      0.07750082 (Batch Size:   256)\n    Iter  2109\t      0.07581532 (Batch Size:   256)\n    Iter  2110\t      0.07188257 (Batch Size:   256)\n    Iter  2111\t      0.07516395 (Batch Size:   256)\n    Iter  2112\t      0.08078001 (Batch Size:   256)\n    Iter  2113\t      0.08402451 (Batch Size:   256)\n    Iter  2114\t      0.07540741 (Batch Size:   256)\n    Iter  2115\t      0.07714827 (Batch Size:   256)\n    Iter  2116\t      0.08334580 (Batch Size:   256)\n    Iter  2117\t      0.07853676 (Batch Size:   256)\n    Iter  2118\t      0.07255692 (Batch Size:   256)\n    Iter  2119\t      0.07639223 (Batch Size:   256)\n    Iter  2120\t      0.07293020 (Batch Size:   256)\n    Iter  2121\t      0.07438102 (Batch Size:   256)\n    Iter  2122\t      0.08732708 (Batch Size:   256)\n    Iter  2123\t      0.09600621 (Batch Size:   256)\n    Iter  2124\t      0.08190089 (Batch Size:   256)\n    Iter  2125\t      0.07577225 (Batch Size:   256)\n    Iter  2126\t      0.07843670 (Batch Size:   256)\n    Iter  2127\t      0.07703601 (Batch Size:   256)\n    Iter  2128\t      0.08106084 (Batch Size:   256)\n    Iter  2129\t      0.07725747 (Batch Size:   256)\n    Iter  2130\t      0.07748762 (Batch Size:   256)\n    Iter  2131\t      0.07905752 (Batch Size:   256)\n    Iter  2132\t      0.07133521 (Batch Size:   256)\n    Iter  2133\t      0.07891660 (Batch Size:   256)\n    Iter  2134\t      0.07293596 (Batch Size:   256)\n    Iter  2135\t      0.08419997 (Batch Size:   256)\n    Iter  2136\t      0.09686931 (Batch Size:   256)\n    Iter  2137\t      0.09751762 (Batch Size:   256)\n    Iter  2138\t      0.08719769 (Batch Size:   256)\n    Iter  2139\t      0.07499792 (Batch Size:   256)\n    Iter  2140\t      0.07560964 (Batch Size:   256)\n    Iter  2141\t      0.07335638 (Batch Size:   256)\n    Iter  2142\t      0.07335227 (Batch Size:   256)\n    Iter  2143\t      0.07169974 (Batch Size:   256)\n    Iter  2144\t      0.07234952 (Batch Size:   256)\n    Iter  2145\t      0.07097895 (Batch Size:   256)\n    Iter  2146\t      0.07665082 (Batch Size:   256)\n    Iter  2147\t      0.07661114 (Batch Size:   256)\n    Iter  2148\t      0.07829269 (Batch Size:   256)\n    Iter  2149\t      0.07551870 (Batch Size:   256)\n    Iter  2150\t      0.07761934 (Batch Size:   256)\n    Iter  2151\t      0.08515590 (Batch Size:   256)\n    Iter  2152\t      0.07719214 (Batch Size:   256)\n    Iter  2153\t      0.07627692 (Batch Size:   256)\n    Iter  2154\t      0.07888955 (Batch Size:   256)\n    Iter  2155\t      0.07534954 (Batch Size:   256)\n    Iter  2156\t      0.08364720 (Batch Size:   256)\n    Iter  2157\t      0.07773055 (Batch Size:   256)\n    Iter  2158\t      0.07730207 (Batch Size:   256)\n    Iter  2159\t      0.07719969 (Batch Size:   256)\n    Iter  2160\t      0.07339896 (Batch Size:   256)\n    Iter  2161\t      0.08700361 (Batch Size:   256)\n    Iter  2162\t      0.08549004 (Batch Size:   256)\n    Iter  2163\t      0.08034994 (Batch Size:   256)\n    Iter  2164\t      0.08095903 (Batch Size:   256)\n    Iter  2165\t      0.08262088 (Batch Size:   256)\n    Iter  2166\t      0.08362931 (Batch Size:   256)\n    Iter  2167\t      0.07326882 (Batch Size:   256)\n    Iter  2168\t      0.07874581 (Batch Size:   256)\n    Iter  2169\t      0.08041033 (Batch Size:   256)\n    Iter  2170\t      0.07637734 (Batch Size:   256)\n    Iter  2171\t      0.07951232 (Batch Size:   256)\n    Iter  2172\t      0.07668267 (Batch Size:   256)\n    Iter  2173\t      0.08393425 (Batch Size:   256)\n    Iter  2174\t      0.07870752 (Batch Size:   256)\n    Iter  2175\t      0.07393195 (Batch Size:   256)\n    Iter  2176\t      0.07562967 (Batch Size:   256)\n    Iter  2177\t      0.08010876 (Batch Size:   256)\n    Iter  2178\t      0.07709345 (Batch Size:   256)\n    Iter  2179\t      0.08563345 (Batch Size:   256)\n    Iter  2180\t      0.09060610 (Batch Size:   256)\n    Iter  2181\t      0.08336440 (Batch Size:   256)\n    Iter  2182\t      0.07944445 (Batch Size:   256)\n    Iter  2183\t      0.07380145 (Batch Size:   256)\n    Iter  2184\t      0.08033530 (Batch Size:   256)\n    Iter  2185\t      0.07372772 (Batch Size:   256)\n    Iter  2186\t      0.08612808 (Batch Size:   256)\n    Iter  2187\t      0.07686420 (Batch Size:   256)\n    Iter  2188\t      0.07590602 (Batch Size:   256)\n    Iter  2189\t      0.07700581 (Batch Size:   256)\n    Iter  2190\t      0.07687845 (Batch Size:   256)\n    Iter  2191\t      0.07255983 (Batch Size:   256)\n    Iter  2192\t      0.07324395 (Batch Size:   256)\n    Iter  2193\t      0.06743850 (Batch Size:   256)\n    Iter  2194\t      0.07300092 (Batch Size:   256)\n    Iter  2195\t      0.08014239 (Batch Size:   256)\n    Iter  2196\t      0.07972566 (Batch Size:   256)\n    Iter  2197\t      0.07662953 (Batch Size:   256)\n    Iter  2198\t      0.07092140 (Batch Size:   256)\n    Iter  2199\t      0.07344179 (Batch Size:   256)\n    Iter  2200\t      0.07559834 (Batch Size:   256)\n    Iter  2201\t      0.07345897 (Batch Size:   256)\n    Iter  2202\t      0.07938021 (Batch Size:   256)\n    Iter  2203\t      0.07180384 (Batch Size:   256)\n    Iter  2204\t      0.07534575 (Batch Size:   256)\n    Iter  2205\t      0.07653167 (Batch Size:   256)\n    Iter  2206\t      0.07799768 (Batch Size:   256)\n    Iter  2207\t      0.07854688 (Batch Size:   256)\n    Iter  2208\t      0.07758264 (Batch Size:   256)\n    Iter  2209\t      0.07893383 (Batch Size:   256)\n    Iter  2210\t      0.09532336 (Batch Size:   256)\n    Iter  2211\t      0.09239778 (Batch Size:   256)\n    Iter  2212\t      0.08346217 (Batch Size:   256)\n    Iter  2213\t      0.08267826 (Batch Size:   256)\n    Iter  2214\t      0.07836752 (Batch Size:   256)\n    Iter  2215\t      0.07274817 (Batch Size:   256)\n    Iter  2216\t      0.07330571 (Batch Size:   256)\n    Iter  2217\t      0.07460836 (Batch Size:   256)\n    Iter  2218\t      0.07844904 (Batch Size:   256)\n    Iter  2219\t      0.08056683 (Batch Size:   256)\n    Iter  2220\t      0.08844129 (Batch Size:   256)\n    Iter  2221\t      0.07975224 (Batch Size:   256)\n    Iter  2222\t      0.09192827 (Batch Size:   256)\n    Iter  2223\t      0.07572135 (Batch Size:   256)\n    Iter  2224\t      0.08155439 (Batch Size:   256)\n    Iter  2225\t      0.09373610 (Batch Size:   256)\n    Iter  2226\t      0.07700583 (Batch Size:   256)\n    Iter  2227\t      0.07708742 (Batch Size:   256)\n    Iter  2228\t      0.07642859 (Batch Size:   256)\n    Iter  2229\t      0.07849215 (Batch Size:   256)\n    Iter  2230\t      0.07486190 (Batch Size:   256)\n    Iter  2231\t      0.07690202 (Batch Size:   256)\n    Iter  2232\t      0.07489674 (Batch Size:   256)\n    Iter  2233\t      0.07693323 (Batch Size:   256)\n    Iter  2234\t      0.08083910 (Batch Size:   256)\n    Iter  2235\t      0.09173310 (Batch Size:   256)\n    Iter  2236\t      0.07971113 (Batch Size:   256)\n    Iter  2237\t      0.08532299 (Batch Size:   256)\n    Iter  2238\t      0.07421505 (Batch Size:   256)\n    Iter  2239\t      0.07697984 (Batch Size:   256)\n    Iter  2240\t      0.08405121 (Batch Size:   256)\n    Iter  2241\t      0.08147951 (Batch Size:   256)\n    Iter  2242\t      0.07601177 (Batch Size:   256)\n    Iter  2243\t      0.07646985 (Batch Size:   256)\n    Iter  2244\t      0.07812720 (Batch Size:   256)\n    Iter  2245\t      0.08458745 (Batch Size:   256)\n    Iter  2246\t      0.07629883 (Batch Size:   256)\n    Iter  2247\t      0.08103837 (Batch Size:   256)\n    Iter  2248\t      0.07554560 (Batch Size:   256)\n    Iter  2249\t      0.07425810 (Batch Size:   256)\n    Iter  2250\t      0.07430452 (Batch Size:   256)\n    Iter  2251\t      0.07439966 (Batch Size:   256)\n    Iter  2252\t      0.07784728 (Batch Size:   256)\n    Iter  2253\t      0.07950111 (Batch Size:   256)\n    Iter  2254\t      0.07810186 (Batch Size:   256)\n    Iter  2255\t      0.07735325 (Batch Size:   256)\n    Iter  2256\t      0.07559690 (Batch Size:   256)\n    Iter  2257\t      0.07598100 (Batch Size:   256)\n    Iter  2258\t      0.07360619 (Batch Size:   256)\n    Iter  2259\t      0.07675868 (Batch Size:   256)\n    Iter  2260\t      0.07666202 (Batch Size:   256)\n    Iter  2261\t      0.07987049 (Batch Size:   256)\n    Iter  2262\t      0.07836130 (Batch Size:   256)\n    Iter  2263\t      0.07459248 (Batch Size:   256)\n    Iter  2264\t      0.07386655 (Batch Size:   256)\n    Iter  2265\t      0.07361249 (Batch Size:   256)\n    Iter  2266\t      0.07867259 (Batch Size:   256)\n    Iter  2267\t      0.08299909 (Batch Size:   256)\n    Iter  2268\t      0.08404814 (Batch Size:   256)\n    Iter  2269\t      0.07875484 (Batch Size:   256)\n    Iter  2270\t      0.08775629 (Batch Size:   256)\n    Iter  2271\t      0.08288225 (Batch Size:   256)\n    Iter  2272\t      0.07926468 (Batch Size:   256)\n    Iter  2273\t      0.07533156 (Batch Size:   256)\n    Iter  2274\t      0.07530924 (Batch Size:   256)\n    Iter  2275\t      0.07319044 (Batch Size:   256)\n    Iter  2276\t      0.07965177 (Batch Size:   256)\n    Iter  2277\t      0.08015992 (Batch Size:   256)\n    Iter  2278\t      0.07870563 (Batch Size:   256)\n    Iter  2279\t      0.07493391 (Batch Size:   256)\n    Iter  2280\t      0.08385671 (Batch Size:   256)\n    Iter  2281\t      0.08392916 (Batch Size:   256)\n    Iter  2282\t      0.09069422 (Batch Size:   256)\n    Iter  2283\t      0.08199408 (Batch Size:   256)\n    Iter  2284\t      0.08022100 (Batch Size:   256)\n    Iter  2285\t      0.07666224 (Batch Size:   256)\n    Iter  2286\t      0.07397445 (Batch Size:   256)\n    Iter  2287\t      0.07162093 (Batch Size:   256)\n    Iter  2288\t      0.07461140 (Batch Size:   256)\n    Iter  2289\t      0.07577452 (Batch Size:   256)\n    Iter  2290\t      0.07923457 (Batch Size:   256)\n    Iter  2291\t      0.07943180 (Batch Size:   256)\n    Iter  2292\t      0.08486814 (Batch Size:   256)\n    Iter  2293\t      0.07808845 (Batch Size:   256)\n    Iter  2294\t      0.07461732 (Batch Size:   256)\n    Iter  2295\t      0.07099426 (Batch Size:   256)\n    Iter  2296\t      0.07219796 (Batch Size:   256)\n    Iter  2297\t      0.07548737 (Batch Size:   256)\n    Iter  2298\t      0.07929511 (Batch Size:   256)\n    Iter  2299\t      0.08021728 (Batch Size:   256)\n    Iter  2300\t      0.07634951 (Batch Size:   256)\n    Iter  2301\t      0.07248093 (Batch Size:   256)\n    Iter  2302\t      0.07862780 (Batch Size:   256)\n    Iter  2303\t      0.08130268 (Batch Size:   256)\n    Iter  2304\t      0.07453329 (Batch Size:   256)\n    Iter  2305\t      0.07610722 (Batch Size:   256)\n    Iter  2306\t      0.07976284 (Batch Size:   256)\n    Iter  2307\t      0.08085764 (Batch Size:   256)\n    Iter  2308\t      0.08169205 (Batch Size:   256)\n    Iter  2309\t      0.07558137 (Batch Size:   256)\n    Iter  2310\t      0.07600750 (Batch Size:   256)\n    Iter  2311\t      0.07477767 (Batch Size:   256)\n    Iter  2312\t      0.07981177 (Batch Size:   256)\n    Iter  2313\t      0.08009541 (Batch Size:   256)\n    Iter  2314\t      0.07775186 (Batch Size:   256)\n    Iter  2315\t      0.07606747 (Batch Size:   256)\n    Iter  2316\t      0.07636509 (Batch Size:   256)\n    Iter  2317\t      0.07734796 (Batch Size:   256)\n    Iter  2318\t      0.07367331 (Batch Size:   256)\n    Iter  2319\t      0.07121187 (Batch Size:   256)\n    Iter  2320\t      0.07795404 (Batch Size:   256)\n    Iter  2321\t      0.07572856 (Batch Size:   256)\n    Iter  2322\t      0.07550970 (Batch Size:   256)\n    Iter  2323\t      0.08790232 (Batch Size:   256)\n    Iter  2324\t      0.07873869 (Batch Size:   256)\n    Iter  2325\t      0.07954110 (Batch Size:   256)\n    Iter  2326\t      0.07741425 (Batch Size:   256)\n    Iter  2327\t      0.08153655 (Batch Size:   256)\n    Iter  2328\t      0.07453663 (Batch Size:   256)\n    Iter  2329\t      0.07851039 (Batch Size:   256)\n    Iter  2330\t      0.07102329 (Batch Size:   256)\n    Iter  2331\t      0.07354233 (Batch Size:   256)\n    Iter  2332\t      0.07454428 (Batch Size:   256)\n    Iter  2333\t      0.07947199 (Batch Size:   256)\n    Iter  2334\t      0.07746738 (Batch Size:   256)\n    Iter  2335\t      0.07696416 (Batch Size:   256)\n    Iter  2336\t      0.07571423 (Batch Size:   256)\n    Iter  2337\t      0.07260752 (Batch Size:   256)\n    Iter  2338\t      0.07440207 (Batch Size:   256)\n    Iter  2339\t      0.07266566 (Batch Size:   256)\n    Iter  2340\t      0.07768449 (Batch Size:   256)\n    Iter  2341\t      0.07586690 (Batch Size:   256)\n    Iter  2342\t      0.07871912 (Batch Size:   256)\n    Iter  2343\t      0.08270716 (Batch Size:   256)\n    Iter  2344\t      0.07448812 (Batch Size:   256)\n    Iter  2345\t      0.07042706 (Batch Size:   256)\n    Iter  2346\t      0.07891090 (Batch Size:   256)\n    Iter  2347\t      0.07884617 (Batch Size:   256)\n    Iter  2348\t      0.07555553 (Batch Size:   256)\n    Iter  2349\t      0.08498822 (Batch Size:   256)\n    Iter  2350\t      0.07944892 (Batch Size:   256)\n    Iter  2351\t      0.07309554 (Batch Size:   256)\n    Iter  2352\t      0.07363369 (Batch Size:   256)\n    Iter  2353\t      0.07430416 (Batch Size:   256)\n    Iter  2354\t      0.08869775 (Batch Size:   256)\n    Iter  2355\t      0.08893312 (Batch Size:   256)\n    Iter  2356\t      0.09427174 (Batch Size:   256)\n    Iter  2357\t      0.07922122 (Batch Size:   256)\n    Iter  2358\t      0.07327101 (Batch Size:   256)\n    Iter  2359\t      0.07633946 (Batch Size:   256)\n    Iter  2360\t      0.07793987 (Batch Size:   256)\n    Iter  2361\t      0.07524446 (Batch Size:   256)\n    Iter  2362\t      0.07632175 (Batch Size:   256)\n    Iter  2363\t      0.08094550 (Batch Size:   256)\n    Iter  2364\t      0.07682963 (Batch Size:   256)\n    Iter  2365\t      0.07687574 (Batch Size:   256)\n    Iter  2366\t      0.07222475 (Batch Size:   256)\n    Iter  2367\t      0.07101373 (Batch Size:   256)\n    Iter  2368\t      0.07690837 (Batch Size:   256)\n    Iter  2369\t      0.07953705 (Batch Size:   256)\n    Iter  2370\t      0.07422273 (Batch Size:   256)\n    Iter  2371\t      0.07670648 (Batch Size:   256)\n    Iter  2372\t      0.07213624 (Batch Size:   256)\n    Iter  2373\t      0.07730475 (Batch Size:   256)\n    Iter  2374\t      0.07950305 (Batch Size:   256)\n    Iter  2375\t      0.07776149 (Batch Size:   256)\n    Iter  2376\t      0.07157171 (Batch Size:   256)\n    Iter  2377\t      0.07348890 (Batch Size:   256)\n    Iter  2378\t      0.07552472 (Batch Size:   256)\n    Iter  2379\t      0.07425704 (Batch Size:   256)\n    Iter  2380\t      0.08412665 (Batch Size:   256)\n    Iter  2381\t      0.08783340 (Batch Size:   256)\n    Iter  2382\t      0.07857797 (Batch Size:   256)\n    Iter  2383\t      0.07272952 (Batch Size:   256)\n    Iter  2384\t      0.07652629 (Batch Size:   256)\n    Iter  2385\t      0.07511059 (Batch Size:   256)\n    Iter  2386\t      0.08233930 (Batch Size:   256)\n    Iter  2387\t      0.07943236 (Batch Size:   256)\n    Iter  2388\t      0.07625628 (Batch Size:   256)\n    Iter  2389\t      0.07441763 (Batch Size:   256)\n    Iter  2390\t      0.07458690 (Batch Size:   256)\n    Iter  2391\t      0.07883777 (Batch Size:   256)\n    Iter  2392\t      0.07532197 (Batch Size:   256)\n    Iter  2393\t      0.06821145 (Batch Size:   256)\n    Iter  2394\t      0.07535242 (Batch Size:   256)\n    Iter  2395\t      0.07287506 (Batch Size:   256)\n    Iter  2396\t      0.07803476 (Batch Size:   256)\n    Iter  2397\t      0.07042254 (Batch Size:   256)\n    Iter  2398\t      0.08550488 (Batch Size:   256)\n    Iter  2399\t      0.08787127 (Batch Size:   256)\n    Iter  2400\t      0.07143879 (Batch Size:   256)\n    Iter  2401\t      0.07554564 (Batch Size:   256)\n    Iter  2402\t      0.07490802 (Batch Size:   256)\n    Iter  2403\t      0.07838775 (Batch Size:   256)\n    Iter  2404\t      0.08884696 (Batch Size:   256)\n    Iter  2405\t      0.07924759 (Batch Size:   256)\n    Iter  2406\t      0.07735071 (Batch Size:   256)\n    Iter  2407\t      0.07105925 (Batch Size:   256)\n    Iter  2408\t      0.07605830 (Batch Size:   256)\n    Iter  2409\t      0.07182280 (Batch Size:   256)\n    Iter  2410\t      0.07874084 (Batch Size:   256)\n    Iter  2411\t      0.07648965 (Batch Size:   256)\n    Iter  2412\t      0.08912245 (Batch Size:   256)\n    Iter  2413\t      0.08954296 (Batch Size:   256)\n    Iter  2414\t      0.08424362 (Batch Size:   256)\n    Iter  2415\t      0.07837961 (Batch Size:   256)\n    Iter  2416\t      0.07874118 (Batch Size:   256)\n    Iter  2417\t      0.07488525 (Batch Size:   256)\n    Iter  2418\t      0.07395976 (Batch Size:   256)\n    Iter  2419\t      0.07465776 (Batch Size:   256)\n    Iter  2420\t      0.07711536 (Batch Size:   256)\n    Iter  2421\t      0.07476080 (Batch Size:   256)\n    Iter  2422\t      0.07447366 (Batch Size:   256)\n    Iter  2423\t      0.07283710 (Batch Size:   256)\n    Iter  2424\t      0.07133249 (Batch Size:   256)\n    Iter  2425\t      0.07708298 (Batch Size:   256)\n    Iter  2426\t      0.07291082 (Batch Size:   256)\n    Iter  2427\t      0.07697664 (Batch Size:   256)\n    Iter  2428\t      0.07686059 (Batch Size:   256)\n    Iter  2429\t      0.07263243 (Batch Size:   256)\n    Iter  2430\t      0.07522859 (Batch Size:   256)\n    Iter  2431\t      0.07705412 (Batch Size:   256)\n    Iter  2432\t      0.08121946 (Batch Size:   256)\n    Iter  2433\t      0.09309606 (Batch Size:   256)\n    Iter  2434\t      0.08320707 (Batch Size:   256)\n    Iter  2435\t      0.07865879 (Batch Size:   256)\n    Iter  2436\t      0.07831547 (Batch Size:   256)\n    Iter  2437\t      0.07936582 (Batch Size:   256)\n    Iter  2438\t      0.07949618 (Batch Size:   256)\n    Iter  2439\t      0.07491427 (Batch Size:   256)\n    Iter  2440\t      0.07322516 (Batch Size:   256)\n    Iter  2441\t      0.07421768 (Batch Size:   256)\n    Iter  2442\t      0.07361086 (Batch Size:   256)\n    Iter  2443\t      0.07253287 (Batch Size:   256)\n    Iter  2444\t      0.07516957 (Batch Size:   256)\n    Iter  2445\t      0.07919483 (Batch Size:   256)\n    Iter  2446\t      0.08232271 (Batch Size:   256)\n    Iter  2447\t      0.08281683 (Batch Size:   256)\n    Iter  2448\t      0.08813440 (Batch Size:   256)\n    Iter  2449\t      0.08238454 (Batch Size:   256)\n    Iter  2450\t      0.08486556 (Batch Size:   256)\n    Iter  2451\t      0.07754394 (Batch Size:   256)\n    Iter  2452\t      0.06905483 (Batch Size:   256)\n    Iter  2453\t      0.07546359 (Batch Size:   256)\n    Iter  2454\t      0.07605949 (Batch Size:   256)\n    Iter  2455\t      0.07464437 (Batch Size:   256)\n    Iter  2456\t      0.07594628 (Batch Size:   256)\n    Iter  2457\t      0.07650587 (Batch Size:   256)\n    Iter  2458\t      0.08318308 (Batch Size:   256)\n    Iter  2459\t      0.07243601 (Batch Size:   256)\n    Iter  2460\t      0.07852574 (Batch Size:   256)\n    Iter  2461\t      0.07581578 (Batch Size:   256)\n    Iter  2462\t      0.07147246 (Batch Size:   256)\n    Iter  2463\t      0.07897812 (Batch Size:   256)\n    Iter  2464\t      0.08688730 (Batch Size:   256)\n    Iter  2465\t      0.07631369 (Batch Size:   256)\n    Iter  2466\t      0.09041559 (Batch Size:   256)\n    Iter  2467\t      0.08674658 (Batch Size:   256)\n    Iter  2468\t      0.08371854 (Batch Size:   256)\n    Iter  2469\t      0.07734415 (Batch Size:   256)\n    Iter  2470\t      0.07839806 (Batch Size:   256)\n    Iter  2471\t      0.08989479 (Batch Size:   256)\n    Iter  2472\t      0.08278752 (Batch Size:   256)\n    Iter  2473\t      0.07513044 (Batch Size:   256)\n    Iter  2474\t      0.08601342 (Batch Size:   256)\n    Iter  2475\t      0.07736079 (Batch Size:   256)\n    Iter  2476\t      0.08085225 (Batch Size:   256)\n    Iter  2477\t      0.07709333 (Batch Size:   256)\n    Iter  2478\t      0.07674699 (Batch Size:   256)\n    Iter  2479\t      0.08553787 (Batch Size:   256)\n    Iter  2480\t      0.07702548 (Batch Size:   256)\n    Iter  2481\t      0.07536059 (Batch Size:   256)\n    Iter  2482\t      0.07507084 (Batch Size:   256)\n    Iter  2483\t      0.08457744 (Batch Size:   256)\n    Iter  2484\t      0.07433787 (Batch Size:   256)\n    Iter  2485\t      0.07135982 (Batch Size:   256)\n    Iter  2486\t      0.07469160 (Batch Size:   256)\n    Iter  2487\t      0.08183947 (Batch Size:   256)\n    Iter  2488\t      0.07714603 (Batch Size:   256)\n    Iter  2489\t      0.08467539 (Batch Size:   256)\n    Iter  2490\t      0.07542857 (Batch Size:   256)\n    Iter  2491\t      0.07331576 (Batch Size:   256)\n    Iter  2492\t      0.07582215 (Batch Size:   256)\n    Iter  2493\t      0.07144853 (Batch Size:   256)\n    Iter  2494\t      0.07805387 (Batch Size:   256)\n    Iter  2495\t      0.06840654 (Batch Size:   256)\n    Iter  2496\t      0.07524627 (Batch Size:   256)\n    Iter  2497\t      0.07004045 (Batch Size:   256)\n    Iter  2498\t      0.07639798 (Batch Size:   256)\n    Iter  2499\t      0.08323880 (Batch Size:   256)\n    Iter  2500\t      0.08358522 (Batch Size:   256)\n    Iter  2501\t      0.08512278 (Batch Size:   256)\n    Iter  2502\t      0.08292588 (Batch Size:   256)\n    Iter  2503\t      0.09997610 (Batch Size:   256)\n    Iter  2504\t      0.08732579 (Batch Size:   256)\n    Iter  2505\t      0.07896159 (Batch Size:   256)\n    Iter  2506\t      0.07593772 (Batch Size:   256)\n    Iter  2507\t      0.07673112 (Batch Size:   256)\n    Iter  2508\t      0.08133418 (Batch Size:   256)\n    Iter  2509\t      0.07756376 (Batch Size:   256)\n    Iter  2510\t      0.07229540 (Batch Size:   256)\n    Iter  2511\t      0.07658510 (Batch Size:   256)\n    Iter  2512\t      0.07437001 (Batch Size:   256)\n    Iter  2513\t      0.08345357 (Batch Size:   256)\n    Iter  2514\t      0.07114364 (Batch Size:   256)\n    Iter  2515\t      0.07551789 (Batch Size:   256)\n    Iter  2516\t      0.07579753 (Batch Size:   256)\n    Iter  2517\t      0.07346720 (Batch Size:   256)\n    Iter  2518\t      0.07774344 (Batch Size:   256)\n    Iter  2519\t      0.07557123 (Batch Size:   256)\n    Iter  2520\t      0.07597369 (Batch Size:   256)\n    Iter  2521\t      0.08079741 (Batch Size:   256)\n    Iter  2522\t      0.08656997 (Batch Size:   256)\n    Iter  2523\t      0.07280255 (Batch Size:   256)\n    Iter  2524\t      0.07847313 (Batch Size:   256)\n    Iter  2525\t      0.07516849 (Batch Size:   256)\n    Iter  2526\t      0.07743768 (Batch Size:   256)\n    Iter  2527\t      0.07607174 (Batch Size:   256)\n    Iter  2528\t      0.07717206 (Batch Size:   256)\n    Iter  2529\t      0.07675433 (Batch Size:   256)\n    Iter  2530\t      0.07463171 (Batch Size:   256)\n    Iter  2531\t      0.07432838 (Batch Size:   256)\n    Iter  2532\t      0.07190636 (Batch Size:   256)\n    Iter  2533\t      0.08203707 (Batch Size:   256)\n    Iter  2534\t      0.07365844 (Batch Size:   256)\n    Iter  2535\t      0.07563954 (Batch Size:   256)\n    Iter  2536\t      0.07355253 (Batch Size:   256)\n    Iter  2537\t      0.07416300 (Batch Size:   256)\n    Iter  2538\t      0.07832624 (Batch Size:   256)\n    Iter  2539\t      0.08160736 (Batch Size:   256)\n    Iter  2540\t      0.07993087 (Batch Size:   256)\n    Iter  2541\t      0.07550035 (Batch Size:   256)\n    Iter  2542\t      0.07504359 (Batch Size:   256)\n    Iter  2543\t      0.07992927 (Batch Size:   256)\n    Iter  2544\t      0.08193351 (Batch Size:   256)\n    Iter  2545\t      0.08624427 (Batch Size:   256)\n    Iter  2546\t      0.07646443 (Batch Size:   256)\n    Iter  2547\t      0.07350862 (Batch Size:   256)\n    Iter  2548\t      0.07622342 (Batch Size:   256)\n    Iter  2549\t      0.07402712 (Batch Size:   256)\n    Iter  2550\t      0.08124836 (Batch Size:   256)\n    Iter  2551\t      0.08180530 (Batch Size:   256)\n    Iter  2552\t      0.08128337 (Batch Size:   256)\n    Iter  2553\t      0.08150883 (Batch Size:   256)\n    Iter  2554\t      0.07483610 (Batch Size:   256)\n    Iter  2555\t      0.07391674 (Batch Size:   256)\n    Iter  2556\t      0.07570735 (Batch Size:   256)\n    Iter  2557\t      0.07415350 (Batch Size:   256)\n    Iter  2558\t      0.07719695 (Batch Size:   256)\n    Iter  2559\t      0.08000608 (Batch Size:   256)\n    Iter  2560\t      0.07957447 (Batch Size:   256)\n    Iter  2561\t      0.06836588 (Batch Size:   256)\n    Iter  2562\t      0.07592194 (Batch Size:   256)\n    Iter  2563\t      0.07934381 (Batch Size:   256)\n    Iter  2564\t      0.07318826 (Batch Size:   256)\n    Iter  2565\t      0.06894041 (Batch Size:   256)\n    Iter  2566\t      0.07632961 (Batch Size:   256)\n    Iter  2567\t      0.08475210 (Batch Size:   256)\n    Iter  2568\t      0.07544889 (Batch Size:   256)\n    Iter  2569\t      0.07613289 (Batch Size:   256)\n    Iter  2570\t      0.07468489 (Batch Size:   256)\n    Iter  2571\t      0.07493949 (Batch Size:   256)\n    Iter  2572\t      0.07964491 (Batch Size:   256)\n    Iter  2573\t      0.07539484 (Batch Size:   256)\n    Iter  2574\t      0.07672704 (Batch Size:   256)\n    Iter  2575\t      0.08359939 (Batch Size:   256)\n    Iter  2576\t      0.07128985 (Batch Size:   256)\n    Iter  2577\t      0.07416004 (Batch Size:   256)\n    Iter  2578\t      0.08544570 (Batch Size:   256)\n    Iter  2579\t      0.09360917 (Batch Size:   256)\n    Iter  2580\t      0.07401718 (Batch Size:   256)\n    Iter  2581\t      0.07975516 (Batch Size:   256)\n    Iter  2582\t      0.07652534 (Batch Size:   256)\n    Iter  2583\t      0.07801993 (Batch Size:   256)\n    Iter  2584\t      0.07762795 (Batch Size:   256)\n    Iter  2585\t      0.07225771 (Batch Size:   256)\n    Iter  2586\t      0.07476942 (Batch Size:   256)\n    Iter  2587\t      0.07393374 (Batch Size:   256)\n    Iter  2588\t      0.07186963 (Batch Size:   256)\n    Iter  2589\t      0.08190619 (Batch Size:   256)\n    Iter  2590\t      0.07382554 (Batch Size:   256)\n    Iter  2591\t      0.07526525 (Batch Size:   256)\n    Iter  2592\t      0.08291231 (Batch Size:   256)\n    Iter  2593\t      0.08193523 (Batch Size:   256)\n    Iter  2594\t      0.07818581 (Batch Size:   256)\n    Iter  2595\t      0.07984240 (Batch Size:   256)\n    Iter  2596\t      0.08475644 (Batch Size:   256)\n    Iter  2597\t      0.08072495 (Batch Size:   256)\n    Iter  2598\t      0.07366448 (Batch Size:   256)\n    Iter  2599\t      0.08864658 (Batch Size:   256)\n    Iter  2600\t      0.08942387 (Batch Size:   256)\n    Iter  2601\t      0.07910245 (Batch Size:   256)\n    Iter  2602\t      0.07566779 (Batch Size:   256)\n    Iter  2603\t      0.07764714 (Batch Size:   256)\n    Iter  2604\t      0.07384774 (Batch Size:   256)\n    Iter  2605\t      0.07619808 (Batch Size:   256)\n    Iter  2606\t      0.08761346 (Batch Size:   256)\n    Iter  2607\t      0.07483992 (Batch Size:   256)\n    Iter  2608\t      0.07716232 (Batch Size:   256)\n    Iter  2609\t      0.07826452 (Batch Size:   256)\n    Iter  2610\t      0.08641371 (Batch Size:   256)\n    Iter  2611\t      0.07786995 (Batch Size:   256)\n    Iter  2612\t      0.07796065 (Batch Size:   256)\n    Iter  2613\t      0.07273103 (Batch Size:   256)\n    Iter  2614\t      0.07715420 (Batch Size:   256)\n    Iter  2615\t      0.07800162 (Batch Size:   256)\n    Iter  2616\t      0.07706946 (Batch Size:   256)\n    Iter  2617\t      0.07968056 (Batch Size:   256)\n    Iter  2618\t      0.07711549 (Batch Size:   256)\n    Iter  2619\t      0.07451961 (Batch Size:   256)\n    Iter  2620\t      0.07648513 (Batch Size:   256)\n    Iter  2621\t      0.07674395 (Batch Size:   256)\n    Iter  2622\t      0.08540952 (Batch Size:   256)\n    Iter  2623\t      0.08269529 (Batch Size:   256)\n    Iter  2624\t      0.07821067 (Batch Size:   256)\n    Iter  2625\t      0.07832917 (Batch Size:   256)\n    Iter  2626\t      0.07837875 (Batch Size:   256)\n    Iter  2627\t      0.08398989 (Batch Size:   256)\n    Iter  2628\t      0.07662717 (Batch Size:   256)\n    Iter  2629\t      0.07987723 (Batch Size:   256)\n    Iter  2630\t      0.07324256 (Batch Size:   256)\n    Iter  2631\t      0.07020361 (Batch Size:   256)\n    Iter  2632\t      0.07158211 (Batch Size:   256)\n    Iter  2633\t      0.07657484 (Batch Size:   256)\n    Iter  2634\t      0.07779440 (Batch Size:   256)\n    Iter  2635\t      0.07981217 (Batch Size:   256)\n    Iter  2636\t      0.08564386 (Batch Size:   256)\n    Iter  2637\t      0.08094440 (Batch Size:   256)\n    Iter  2638\t      0.07598657 (Batch Size:   256)\n    Iter  2639\t      0.06877910 (Batch Size:   256)\n    Iter  2640\t      0.07065888 (Batch Size:   256)\n    Iter  2641\t      0.07340035 (Batch Size:   256)\n    Iter  2642\t      0.07637281 (Batch Size:   256)\n    Iter  2643\t      0.06879472 (Batch Size:   256)\n    Iter  2644\t      0.07617074 (Batch Size:   256)\n    Iter  2645\t      0.07668649 (Batch Size:   256)\n    Iter  2646\t      0.07279730 (Batch Size:   256)\n    Iter  2647\t      0.07431552 (Batch Size:   256)\n    Iter  2648\t      0.08073071 (Batch Size:   256)\n    Iter  2649\t      0.07321599 (Batch Size:   256)\n    Iter  2650\t      0.07343560 (Batch Size:   256)\n    Iter  2651\t      0.07065849 (Batch Size:   256)\n    Iter  2652\t      0.07378821 (Batch Size:   256)\n    Iter  2653\t      0.07230504 (Batch Size:   256)\n    Iter  2654\t      0.08605111 (Batch Size:   256)\n    Iter  2655\t      0.09082641 (Batch Size:   256)\n    Iter  2656\t      0.08049437 (Batch Size:   256)\n    Iter  2657\t      0.07965122 (Batch Size:   256)\n    Iter  2658\t      0.07479366 (Batch Size:   256)\n    Iter  2659\t      0.06934660 (Batch Size:   256)\n    Iter  2660\t      0.07405598 (Batch Size:   256)\n    Iter  2661\t      0.07656669 (Batch Size:   256)\n    Iter  2662\t      0.07672227 (Batch Size:   256)\n    Iter  2663\t      0.07305399 (Batch Size:   256)\n    Iter  2664\t      0.08242144 (Batch Size:   256)\n    Iter  2665\t      0.07559996 (Batch Size:   256)\n    Iter  2666\t      0.07820765 (Batch Size:   256)\n    Iter  2667\t      0.08059156 (Batch Size:   256)\n    Iter  2668\t      0.07459777 (Batch Size:   256)\n    Iter  2669\t      0.09482395 (Batch Size:   256)\n    Iter  2670\t      0.08108855 (Batch Size:   256)\n    Iter  2671\t      0.07696691 (Batch Size:   256)\n    Iter  2672\t      0.08113170 (Batch Size:   256)\n    Iter  2673\t      0.08051832 (Batch Size:   256)\n    Iter  2674\t      0.07638745 (Batch Size:   256)\n    Iter  2675\t      0.07526895 (Batch Size:   256)\n    Iter  2676\t      0.08795788 (Batch Size:   256)\n    Iter  2677\t      0.09205724 (Batch Size:   256)\n    Iter  2678\t      0.07524245 (Batch Size:   256)\n    Iter  2679\t      0.09241938 (Batch Size:   256)\n    Iter  2680\t      0.07570163 (Batch Size:   256)\n    Iter  2681\t      0.07934523 (Batch Size:   256)\n    Iter  2682\t      0.07971959 (Batch Size:   256)\n    Iter  2683\t      0.07694063 (Batch Size:   256)\n    Iter  2684\t      0.07754467 (Batch Size:   256)\n    Iter  2685\t      0.07556842 (Batch Size:   256)\n    Iter  2686\t      0.07490489 (Batch Size:   256)\n    Iter  2687\t      0.07531656 (Batch Size:   256)\n    Iter  2688\t      0.07734299 (Batch Size:   256)\n    Iter  2689\t      0.07108373 (Batch Size:   256)\n    Iter  2690\t      0.07551339 (Batch Size:   256)\n    Iter  2691\t      0.08074974 (Batch Size:   256)\n    Iter  2692\t      0.07834569 (Batch Size:   256)\n    Iter  2693\t      0.07448754 (Batch Size:   256)\n    Iter  2694\t      0.07288559 (Batch Size:   256)\n    Iter  2695\t      0.07353049 (Batch Size:   256)\n    Iter  2696\t      0.07421075 (Batch Size:   256)\n    Iter  2697\t      0.07235170 (Batch Size:   256)\n    Iter  2698\t      0.07650250 (Batch Size:   256)\n    Iter  2699\t      0.08209243 (Batch Size:   256)\n    Iter  2700\t      0.07775198 (Batch Size:   256)\n    Iter  2701\t      0.07537117 (Batch Size:   256)\n    Iter  2702\t      0.07448289 (Batch Size:   256)\n    Iter  2703\t      0.07430385 (Batch Size:   256)\n    Iter  2704\t      0.07934914 (Batch Size:   256)\n    Iter  2705\t      0.07916653 (Batch Size:   256)\n    Iter  2706\t      0.08365641 (Batch Size:   256)\n    Iter  2707\t      0.08772407 (Batch Size:   256)\n    Iter  2708\t      0.07089183 (Batch Size:   256)\n    Iter  2709\t      0.08131772 (Batch Size:   256)\n    Iter  2710\t      0.07322089 (Batch Size:   256)\n    Iter  2711\t      0.07448776 (Batch Size:   256)\n    Iter  2712\t      0.07819476 (Batch Size:   256)\n    Iter  2713\t      0.07371143 (Batch Size:   256)\n    Iter  2714\t      0.07805550 (Batch Size:   256)\n    Iter  2715\t      0.07815619 (Batch Size:   256)\n    Iter  2716\t      0.07586874 (Batch Size:   256)\n    Iter  2717\t      0.07570268 (Batch Size:   256)\n    Iter  2718\t      0.07539892 (Batch Size:   256)\n    Iter  2719\t      0.08709429 (Batch Size:   256)\n    Iter  2720\t      0.08729207 (Batch Size:   256)\n    Iter  2721\t      0.08426092 (Batch Size:   256)\n    Iter  2722\t      0.07530937 (Batch Size:   256)\n    Iter  2723\t      0.08499336 (Batch Size:   256)\n    Iter  2724\t      0.08094878 (Batch Size:   256)\n    Iter  2725\t      0.07798965 (Batch Size:   256)\n    Iter  2726\t      0.08544790 (Batch Size:   256)\n    Iter  2727\t      0.07311972 (Batch Size:   256)\n    Iter  2728\t      0.07665775 (Batch Size:   256)\n    Iter  2729\t      0.08257956 (Batch Size:   256)\n    Iter  2730\t      0.07560849 (Batch Size:   256)\n    Iter  2731\t      0.07908275 (Batch Size:   256)\n    Iter  2732\t      0.07964243 (Batch Size:   256)\n    Iter  2733\t      0.07619734 (Batch Size:   256)\n    Iter  2734\t      0.07982223 (Batch Size:   256)\n    Iter  2735\t      0.08014506 (Batch Size:   256)\n    Iter  2736\t      0.08013922 (Batch Size:   256)\n    Iter  2737\t      0.08062161 (Batch Size:   256)\n    Iter  2738\t      0.08790208 (Batch Size:   256)\n    Iter  2739\t      0.07711292 (Batch Size:   256)\n    Iter  2740\t      0.07440393 (Batch Size:   256)\n    Iter  2741\t      0.07550217 (Batch Size:   256)\n    Iter  2742\t      0.07564871 (Batch Size:   256)\n    Iter  2743\t      0.07438593 (Batch Size:   256)\n    Iter  2744\t      0.07275942 (Batch Size:   256)\n    Iter  2745\t      0.07060955 (Batch Size:   256)\n    Iter  2746\t      0.07373895 (Batch Size:   256)\n    Iter  2747\t      0.07332166 (Batch Size:   256)\n    Iter  2748\t      0.07226259 (Batch Size:   256)\n    Iter  2749\t      0.07446503 (Batch Size:   256)\n    Iter  2750\t      0.07716802 (Batch Size:   256)\n    Iter  2751\t      0.07627699 (Batch Size:   256)\n    Iter  2752\t      0.07332520 (Batch Size:   256)\n    Iter  2753\t      0.07415153 (Batch Size:   256)\n    Iter  2754\t      0.07197142 (Batch Size:   256)\n    Iter  2755\t      0.07233015 (Batch Size:   256)\n    Iter  2756\t      0.07226369 (Batch Size:   256)\n    Iter  2757\t      0.07156519 (Batch Size:   256)\n    Iter  2758\t      0.07387204 (Batch Size:   256)\n    Iter  2759\t      0.07705766 (Batch Size:   256)\n    Iter  2760\t      0.08165954 (Batch Size:   256)\n    Iter  2761\t      0.07999932 (Batch Size:   256)\n    Iter  2762\t      0.08157807 (Batch Size:   256)\n    Iter  2763\t      0.08313150 (Batch Size:   256)\n    Iter  2764\t      0.07301600 (Batch Size:   256)\n    Iter  2765\t      0.07618060 (Batch Size:   256)\n    Iter  2766\t      0.07752076 (Batch Size:   256)\n    Iter  2767\t      0.07437933 (Batch Size:   256)\n    Iter  2768\t      0.07404774 (Batch Size:   256)\n    Iter  2769\t      0.07371938 (Batch Size:   256)\n    Iter  2770\t      0.07412343 (Batch Size:   256)\n    Iter  2771\t      0.07704399 (Batch Size:   256)\n    Iter  2772\t      0.07336479 (Batch Size:   256)\n    Iter  2773\t      0.07421498 (Batch Size:   256)\n    Iter  2774\t      0.07653605 (Batch Size:   256)\n    Iter  2775\t      0.07221104 (Batch Size:   256)\n    Iter  2776\t      0.07565424 (Batch Size:   256)\n    Iter  2777\t      0.07539377 (Batch Size:   256)\n    Iter  2778\t      0.08147672 (Batch Size:   256)\n    Iter  2779\t      0.08099955 (Batch Size:   256)\n    Iter  2780\t      0.08552965 (Batch Size:   256)\n    Iter  2781\t      0.08701302 (Batch Size:   256)\n    Iter  2782\t      0.07837730 (Batch Size:   256)\n    Iter  2783\t      0.07749565 (Batch Size:   256)\n    Iter  2784\t      0.07326189 (Batch Size:   256)\n    Iter  2785\t      0.07858841 (Batch Size:   256)\n    Iter  2786\t      0.07858550 (Batch Size:   256)\n    Iter  2787\t      0.07104314 (Batch Size:   256)\n    Iter  2788\t      0.07216986 (Batch Size:   256)\n    Iter  2789\t      0.07665643 (Batch Size:   256)\n    Iter  2790\t      0.07736723 (Batch Size:   256)\n    Iter  2791\t      0.07254514 (Batch Size:   256)\n    Iter  2792\t      0.07571301 (Batch Size:   256)\n    Iter  2793\t      0.08291412 (Batch Size:   256)\n    Iter  2794\t      0.08195218 (Batch Size:   256)\n    Iter  2795\t      0.07586155 (Batch Size:   256)\n    Iter  2796\t      0.09150798 (Batch Size:   256)\n    Iter  2797\t      0.07451962 (Batch Size:   256)\n    Iter  2798\t      0.07548979 (Batch Size:   256)\n    Iter  2799\t      0.07608415 (Batch Size:   256)\n    Iter  2800\t      0.07918350 (Batch Size:   256)\n    Iter  2801\t      0.08679322 (Batch Size:   256)\n    Iter  2802\t      0.07601017 (Batch Size:   256)\n    Iter  2803\t      0.08363394 (Batch Size:   256)\n    Iter  2804\t      0.09532841 (Batch Size:   256)\n    Iter  2805\t      0.09469336 (Batch Size:   256)\n    Iter  2806\t      0.07579478 (Batch Size:   256)\n    Iter  2807\t      0.07609934 (Batch Size:   256)\n    Iter  2808\t      0.07807058 (Batch Size:   256)\n    Iter  2809\t      0.07693202 (Batch Size:   256)\n    Iter  2810\t      0.07265379 (Batch Size:   256)\n    Iter  2811\t      0.07361858 (Batch Size:   256)\n    Iter  2812\t      0.07307219 (Batch Size:   256)\n    Iter  2813\t      0.07550640 (Batch Size:   256)\n    Iter  2814\t      0.07592357 (Batch Size:   256)\n    Iter  2815\t      0.07248866 (Batch Size:   256)\n    Iter  2816\t      0.07445725 (Batch Size:   256)\n    Iter  2817\t      0.07258139 (Batch Size:   256)\n    Iter  2818\t      0.07659395 (Batch Size:   256)\n    Iter  2819\t      0.07933073 (Batch Size:   256)\n    Iter  2820\t      0.07715389 (Batch Size:   256)\n    Iter  2821\t      0.07296360 (Batch Size:   256)\n    Iter  2822\t      0.07875475 (Batch Size:   256)\n    Iter  2823\t      0.07196598 (Batch Size:   256)\n    Iter  2824\t      0.07593087 (Batch Size:   256)\n    Iter  2825\t      0.07474136 (Batch Size:   256)\n    Iter  2826\t      0.08291394 (Batch Size:   256)\n    Iter  2827\t      0.08512354 (Batch Size:   256)\n    Iter  2828\t      0.08669237 (Batch Size:   256)\n    Iter  2829\t      0.08096042 (Batch Size:   256)\n    Iter  2830\t      0.07597110 (Batch Size:   256)\n    Iter  2831\t      0.07614351 (Batch Size:   256)\n    Iter  2832\t      0.08291857 (Batch Size:   256)\n    Iter  2833\t      0.08146534 (Batch Size:   256)\n    Iter  2834\t      0.07397937 (Batch Size:   256)\n    Iter  2835\t      0.08122425 (Batch Size:   256)\n    Iter  2836\t      0.08160946 (Batch Size:   256)\n    Iter  2837\t      0.07301891 (Batch Size:   256)\n    Iter  2838\t      0.07416370 (Batch Size:   256)\n    Iter  2839\t      0.07209501 (Batch Size:   256)\n    Iter  2840\t      0.07741469 (Batch Size:   256)\n    Iter  2841\t      0.07419665 (Batch Size:   256)\n    Iter  2842\t      0.07291047 (Batch Size:   256)\n    Iter  2843\t      0.07124239 (Batch Size:   256)\n    Iter  2844\t      0.07760810 (Batch Size:   256)\n    Iter  2845\t      0.07368227 (Batch Size:   256)\n    Iter  2846\t      0.07428429 (Batch Size:   256)\n    Iter  2847\t      0.07459798 (Batch Size:   256)\n    Iter  2848\t      0.07463496 (Batch Size:   256)\n    Iter  2849\t      0.07223531 (Batch Size:   256)\n    Iter  2850\t      0.07754934 (Batch Size:   256)\n    Iter  2851\t      0.08578071 (Batch Size:   256)\n    Iter  2852\t      0.07726178 (Batch Size:   256)\n    Iter  2853\t      0.07268646 (Batch Size:   256)\n    Iter  2854\t      0.07381790 (Batch Size:   256)\n    Iter  2855\t      0.07552585 (Batch Size:   256)\n    Iter  2856\t      0.08136302 (Batch Size:   256)\n    Iter  2857\t      0.07891106 (Batch Size:   256)\n    Iter  2858\t      0.07430295 (Batch Size:   256)\n    Iter  2859\t      0.08163590 (Batch Size:   256)\n    Iter  2860\t      0.08067804 (Batch Size:   256)\n    Iter  2861\t      0.07437052 (Batch Size:   256)\n    Iter  2862\t      0.07439222 (Batch Size:   256)\n    Iter  2863\t      0.07573824 (Batch Size:   256)\n    Iter  2864\t      0.07770759 (Batch Size:   256)\n    Iter  2865\t      0.07244105 (Batch Size:   256)\n    Iter  2866\t      0.07418827 (Batch Size:   256)\n    Iter  2867\t      0.07498048 (Batch Size:   256)\n    Iter  2868\t      0.08035477 (Batch Size:   256)\n    Iter  2869\t      0.07573376 (Batch Size:   256)\n    Iter  2870\t      0.08146853 (Batch Size:   256)\n    Iter  2871\t      0.07687436 (Batch Size:   256)\n    Iter  2872\t      0.07409104 (Batch Size:   256)\n    Iter  2873\t      0.07692318 (Batch Size:   256)\n    Iter  2874\t      0.06833030 (Batch Size:   256)\n    Iter  2875\t      0.07257652 (Batch Size:   256)\n    Iter  2876\t      0.07442679 (Batch Size:   256)\n    Iter  2877\t      0.07240475 (Batch Size:   256)\n    Iter  2878\t      0.08028094 (Batch Size:   256)\n    Iter  2879\t      0.07415294 (Batch Size:   256)\n    Iter  2880\t      0.07550852 (Batch Size:   256)\n    Iter  2881\t      0.07217769 (Batch Size:   256)\n    Iter  2882\t      0.07325139 (Batch Size:   256)\n    Iter  2883\t      0.07680625 (Batch Size:   256)\n    Iter  2884\t      0.07368861 (Batch Size:   256)\n    Iter  2885\t      0.07825938 (Batch Size:   256)\n    Iter  2886\t      0.08069611 (Batch Size:   256)\n    Iter  2887\t      0.07861471 (Batch Size:   256)\n    Iter  2888\t      0.07424194 (Batch Size:   256)\n    Iter  2889\t      0.07369472 (Batch Size:   256)\n    Iter  2890\t      0.08112363 (Batch Size:   256)\n    Iter  2891\t      0.07482667 (Batch Size:   256)\n    Iter  2892\t      0.07449034 (Batch Size:   256)\n    Iter  2893\t      0.07630931 (Batch Size:   256)\n    Iter  2894\t      0.09675206 (Batch Size:   256)\n    Iter  2895\t      0.10880094 (Batch Size:   256)\n    Iter  2896\t      0.10878200 (Batch Size:   256)\n    Iter  2897\t      0.09649958 (Batch Size:   256)\n    Iter  2898\t      0.07752499 (Batch Size:   256)\n    Iter  2899\t      0.07528367 (Batch Size:   256)\n    Iter  2900\t      0.07455111 (Batch Size:   256)\n    Iter  2901\t      0.07620798 (Batch Size:   256)\n    Iter  2902\t      0.07727661 (Batch Size:   256)\n    Iter  2903\t      0.07291567 (Batch Size:   256)\n    Iter  2904\t      0.07817367 (Batch Size:   256)\n    Iter  2905\t      0.07666793 (Batch Size:   256)\n    Iter  2906\t      0.07678436 (Batch Size:   256)\n    Iter  2907\t      0.07472987 (Batch Size:   256)\n    Iter  2908\t      0.08176910 (Batch Size:   256)\n    Iter  2909\t      0.07265662 (Batch Size:   256)\n    Iter  2910\t      0.07201810 (Batch Size:   256)\n    Iter  2911\t      0.08099046 (Batch Size:   256)\n    Iter  2912\t      0.07819967 (Batch Size:   256)\n    Iter  2913\t      0.08114271 (Batch Size:   256)\n    Iter  2914\t      0.07466821 (Batch Size:   256)\n    Iter  2915\t      0.07356972 (Batch Size:   256)\n    Iter  2916\t      0.07498401 (Batch Size:   256)\n    Iter  2917\t      0.07100298 (Batch Size:   256)\n    Iter  2918\t      0.08606458 (Batch Size:   256)\n    Iter  2919\t      0.07545498 (Batch Size:   256)\n    Iter  2920\t      0.07539447 (Batch Size:   256)\n    Iter  2921\t      0.07745962 (Batch Size:   256)\n    Iter  2922\t      0.07868965 (Batch Size:   256)\n    Iter  2923\t      0.07531761 (Batch Size:   256)\n    Iter  2924\t      0.07723412 (Batch Size:   256)\n    Iter  2925\t      0.07465077 (Batch Size:   256)\n    Iter  2926\t      0.07392819 (Batch Size:   256)\n    Iter  2927\t      0.07181560 (Batch Size:   256)\n    Iter  2928\t      0.07379385 (Batch Size:   256)\n    Iter  2929\t      0.07849768 (Batch Size:   256)\n    Iter  2930\t      0.09119903 (Batch Size:   256)\n    Iter  2931\t      0.08117204 (Batch Size:   256)\n    Iter  2932\t      0.08444826 (Batch Size:   256)\n    Iter  2933\t      0.08976866 (Batch Size:   256)\n    Iter  2934\t      0.07783690 (Batch Size:   256)\n    Iter  2935\t      0.07487696 (Batch Size:   256)\n    Iter  2936\t      0.08812636 (Batch Size:   256)\n    Iter  2937\t      0.07916226 (Batch Size:   256)\n    Iter  2938\t      0.07360767 (Batch Size:   256)\n    Iter  2939\t      0.07174994 (Batch Size:   256)\n    Iter  2940\t      0.07397042 (Batch Size:   256)\n    Iter  2941\t      0.07396110 (Batch Size:   256)\n    Iter  2942\t      0.07548643 (Batch Size:   256)\n    Iter  2943\t      0.07795889 (Batch Size:   256)\n    Iter  2944\t      0.07603750 (Batch Size:   256)\n    Iter  2945\t      0.07465856 (Batch Size:   256)\n    Iter  2946\t      0.07717449 (Batch Size:   256)\n    Iter  2947\t      0.07314823 (Batch Size:   256)\n    Iter  2948\t      0.07270930 (Batch Size:   256)\n    Iter  2949\t      0.07393095 (Batch Size:   256)\n    Iter  2950\t      0.07337604 (Batch Size:   256)\n    Iter  2951\t      0.07359282 (Batch Size:   256)\n    Iter  2952\t      0.07474007 (Batch Size:   256)\n    Iter  2953\t      0.07951565 (Batch Size:   256)\n    Iter  2954\t      0.07932432 (Batch Size:   256)\n    Iter  2955\t      0.07439588 (Batch Size:   256)\n    Iter  2956\t      0.07722840 (Batch Size:   256)\n    Iter  2957\t      0.08131811 (Batch Size:   256)\n    Iter  2958\t      0.08064434 (Batch Size:   256)\n    Iter  2959\t      0.07994981 (Batch Size:   256)\n    Iter  2960\t      0.07875848 (Batch Size:   256)\n    Iter  2961\t      0.07697230 (Batch Size:   256)\n    Iter  2962\t      0.07337616 (Batch Size:   256)\n    Iter  2963\t      0.07311329 (Batch Size:   256)\n    Iter  2964\t      0.07766116 (Batch Size:   256)\n    Iter  2965\t      0.07685223 (Batch Size:   256)\n    Iter  2966\t      0.07792012 (Batch Size:   256)\n    Iter  2967\t      0.07330668 (Batch Size:   256)\n    Iter  2968\t      0.07765623 (Batch Size:   256)\n    Iter  2969\t      0.07677407 (Batch Size:   256)\n    Iter  2970\t      0.07359386 (Batch Size:   256)\n    Iter  2971\t      0.07084795 (Batch Size:   256)\n    Iter  2972\t      0.07160482 (Batch Size:   256)\n    Iter  2973\t      0.07114242 (Batch Size:   256)\n    Iter  2974\t      0.07446144 (Batch Size:   256)\n    Iter  2975\t      0.07243856 (Batch Size:   256)\n    Iter  2976\t      0.07215254 (Batch Size:   256)\n    Iter  2977\t      0.07557582 (Batch Size:   256)\n    Iter  2978\t      0.07131432 (Batch Size:   256)\n    Iter  2979\t      0.07250034 (Batch Size:   256)\n    Iter  2980\t      0.07440154 (Batch Size:   256)\n    Iter  2981\t      0.07167374 (Batch Size:   256)\n    Iter  2982\t      0.07167851 (Batch Size:   256)\n    Iter  2983\t      0.07002727 (Batch Size:   256)\n    Iter  2984\t      0.07239092 (Batch Size:   256)\n    Iter  2985\t      0.07165081 (Batch Size:   256)\n    Iter  2986\t      0.07602050 (Batch Size:   256)\n    Iter  2987\t      0.07820780 (Batch Size:   256)\n    Iter  2988\t      0.08040994 (Batch Size:   256)\n    Iter  2989\t      0.08694874 (Batch Size:   256)\n    Iter  2990\t      0.08661264 (Batch Size:   256)\n    Iter  2991\t      0.07460181 (Batch Size:   256)\n    Iter  2992\t      0.07326441 (Batch Size:   256)\n    Iter  2993\t      0.07243681 (Batch Size:   256)\n    Iter  2994\t      0.07381710 (Batch Size:   256)\n    Iter  2995\t      0.08138574 (Batch Size:   256)\n    Iter  2996\t      0.07847969 (Batch Size:   256)\n    Iter  2997\t      0.07591190 (Batch Size:   256)\n    Iter  2998\t      0.07696108 (Batch Size:   256)\n    Iter  2999\t      0.07712240 (Batch Size:   256)\n    Iter  3000\t      0.08266027 (Batch Size:   256)\n    Iter  3001\t      0.07785330 (Batch Size:   256)\n    Iter  3002\t      0.07769647 (Batch Size:   256)\n    Iter  3003\t      0.07380830 (Batch Size:   256)\n    Iter  3004\t      0.07649018 (Batch Size:   256)\n    Iter  3005\t      0.08256111 (Batch Size:   256)\n    Iter  3006\t      0.06943729 (Batch Size:   256)\n    Iter  3007\t      0.07272443 (Batch Size:   256)\n    Iter  3008\t      0.08319870 (Batch Size:   256)\n    Iter  3009\t      0.08623238 (Batch Size:   256)\n    Iter  3010\t      0.07759323 (Batch Size:   256)\n    Iter  3011\t      0.07490788 (Batch Size:   256)\n    Iter  3012\t      0.07889801 (Batch Size:   256)\n    Iter  3013\t      0.08158880 (Batch Size:   256)\n    Iter  3014\t      0.07795347 (Batch Size:   256)\n    Iter  3015\t      0.07675900 (Batch Size:   256)\n    Iter  3016\t      0.07063556 (Batch Size:   256)\n    Iter  3017\t      0.07007238 (Batch Size:   256)\n    Iter  3018\t      0.07094321 (Batch Size:   256)\n    Iter  3019\t      0.07290882 (Batch Size:   256)\n    Iter  3020\t      0.07337106 (Batch Size:   256)\n    Iter  3021\t      0.07391624 (Batch Size:   256)\n    Iter  3022\t      0.07425161 (Batch Size:   256)\n    Iter  3023\t      0.08809034 (Batch Size:   256)\n    Iter  3024\t      0.08110855 (Batch Size:   256)\n    Iter  3025\t      0.07240799 (Batch Size:   256)\n    Iter  3026\t      0.07422273 (Batch Size:   256)\n    Iter  3027\t      0.09075159 (Batch Size:   256)\n    Iter  3028\t      0.08980902 (Batch Size:   256)\n    Iter  3029\t      0.08256973 (Batch Size:   256)\n    Iter  3030\t      0.07588055 (Batch Size:   256)\n    Iter  3031\t      0.07382460 (Batch Size:   256)\n    Iter  3032\t      0.07594078 (Batch Size:   256)\n    Iter  3033\t      0.08190794 (Batch Size:   256)\n    Iter  3034\t      0.09887333 (Batch Size:   256)\n    Iter  3035\t      0.07916004 (Batch Size:   256)\n    Iter  3036\t      0.07558701 (Batch Size:   256)\n    Iter  3037\t      0.09173435 (Batch Size:   256)\n    Iter  3038\t      0.08088411 (Batch Size:   256)\n    Iter  3039\t      0.07719864 (Batch Size:   256)\n    Iter  3040\t      0.07585175 (Batch Size:   256)\n    Iter  3041\t      0.07322396 (Batch Size:   256)\n    Iter  3042\t      0.07032167 (Batch Size:   256)\n    Iter  3043\t      0.07413460 (Batch Size:   256)\n    Iter  3044\t      0.07562791 (Batch Size:   256)\n    Iter  3045\t      0.07857765 (Batch Size:   256)\n    Iter  3046\t      0.07363341 (Batch Size:   256)\n    Iter  3047\t      0.07653550 (Batch Size:   256)\n    Iter  3048\t      0.07436345 (Batch Size:   256)\n    Iter  3049\t      0.07620697 (Batch Size:   256)\n    Iter  3050\t      0.07212067 (Batch Size:   256)\n    Iter  3051\t      0.07674390 (Batch Size:   256)\n    Iter  3052\t      0.08060104 (Batch Size:   256)\n    Iter  3053\t      0.07937136 (Batch Size:   256)\n    Iter  3054\t      0.08426441 (Batch Size:   256)\n    Iter  3055\t      0.08253845 (Batch Size:   256)\n    Iter  3056\t      0.09356659 (Batch Size:   256)\n    Iter  3057\t      0.07845488 (Batch Size:   256)\n    Iter  3058\t      0.07338746 (Batch Size:   256)\n    Iter  3059\t      0.07342944 (Batch Size:   256)\n    Iter  3060\t      0.06979805 (Batch Size:   256)\n    Iter  3061\t      0.06958757 (Batch Size:   256)\n    Iter  3062\t      0.07164106 (Batch Size:   256)\n    Iter  3063\t      0.07320529 (Batch Size:   256)\n    Iter  3064\t      0.08051385 (Batch Size:   256)\n    Iter  3065\t      0.07397675 (Batch Size:   256)\n    Iter  3066\t      0.07176411 (Batch Size:   256)\n    Iter  3067\t      0.07302910 (Batch Size:   256)\n    Iter  3068\t      0.07096902 (Batch Size:   256)\n    Iter  3069\t      0.08513848 (Batch Size:   256)\n    Iter  3070\t      0.08416534 (Batch Size:   256)\n    Iter  3071\t      0.07861310 (Batch Size:   256)\n    Iter  3072\t      0.07577907 (Batch Size:   256)\n    Iter  3073\t      0.07109852 (Batch Size:   256)\n    Iter  3074\t      0.09223019 (Batch Size:   256)\n    Iter  3075\t      0.08064043 (Batch Size:   256)\n    Iter  3076\t      0.07680404 (Batch Size:   256)\n    Iter  3077\t      0.07482671 (Batch Size:   256)\n    Iter  3078\t      0.07367841 (Batch Size:   256)\n    Iter  3079\t      0.07747843 (Batch Size:   256)\n    Iter  3080\t      0.07082155 (Batch Size:   256)\n    Iter  3081\t      0.07438636 (Batch Size:   256)\n    Iter  3082\t      0.07099824 (Batch Size:   256)\n    Iter  3083\t      0.07670565 (Batch Size:   256)\n    Iter  3084\t      0.07382394 (Batch Size:   256)\n    Iter  3085\t      0.07364830 (Batch Size:   256)\n    Iter  3086\t      0.07415043 (Batch Size:   256)\n    Iter  3087\t      0.07422042 (Batch Size:   256)\n    Iter  3088\t      0.07277369 (Batch Size:   256)\n    Iter  3089\t      0.07412392 (Batch Size:   256)\n    Iter  3090\t      0.07932777 (Batch Size:   256)\n    Iter  3091\t      0.08138045 (Batch Size:   256)\n    Iter  3092\t      0.07865581 (Batch Size:   256)\n    Iter  3093\t      0.07650189 (Batch Size:   256)\n    Iter  3094\t      0.07492316 (Batch Size:   256)\n    Iter  3095\t      0.07859375 (Batch Size:   256)\n    Iter  3096\t      0.07528276 (Batch Size:   256)\n    Iter  3097\t      0.07697822 (Batch Size:   256)\n    Iter  3098\t      0.07495117 (Batch Size:   256)\n    Iter  3099\t      0.07616850 (Batch Size:   256)\n    Iter  3100\t      0.07891111 (Batch Size:   256)\n    Iter  3101\t      0.08430742 (Batch Size:   256)\n    Iter  3102\t      0.09217387 (Batch Size:   256)\n    Iter  3103\t      0.09958885 (Batch Size:   256)\n    Iter  3104\t      0.08116691 (Batch Size:   256)\n    Iter  3105\t      0.07791822 (Batch Size:   256)\n    Iter  3106\t      0.07984869 (Batch Size:   256)\n    Iter  3107\t      0.07643340 (Batch Size:   256)\n    Iter  3108\t      0.07431314 (Batch Size:   256)\n    Iter  3109\t      0.07618716 (Batch Size:   256)\n    Iter  3110\t      0.07344709 (Batch Size:   256)\n    Iter  3111\t      0.07583459 (Batch Size:   256)\n    Iter  3112\t      0.07533298 (Batch Size:   256)\n    Iter  3113\t      0.06896165 (Batch Size:   256)\n    Iter  3114\t      0.07178069 (Batch Size:   256)\n    Iter  3115\t      0.07042267 (Batch Size:   256)\n    Iter  3116\t      0.07521054 (Batch Size:   256)\n    Iter  3117\t      0.08236161 (Batch Size:   256)\n    Iter  3118\t      0.07752171 (Batch Size:   256)\n    Iter  3119\t      0.07988901 (Batch Size:   256)\n    Iter  3120\t      0.07930888 (Batch Size:   256)\n    Iter  3121\t      0.07994996 (Batch Size:   256)\n    Iter  3122\t      0.07257584 (Batch Size:   256)\n    Iter  3123\t      0.07075364 (Batch Size:   256)\n    Iter  3124\t      0.07125622 (Batch Size:   256)\n    Iter  3125\t      0.07381107 (Batch Size:   256)\n    Iter  3126\t      0.07295946 (Batch Size:   256)\n    Iter  3127\t      0.07748174 (Batch Size:   256)\n    Iter  3128\t      0.07301723 (Batch Size:   256)\n    Iter  3129\t      0.07236385 (Batch Size:   256)\n    Iter  3130\t      0.07140725 (Batch Size:   256)\n    Iter  3131\t      0.07292370 (Batch Size:   256)\n    Iter  3132\t      0.07447010 (Batch Size:   256)\n    Iter  3133\t      0.07486809 (Batch Size:   256)\n    Iter  3134\t      0.08082009 (Batch Size:   256)\n    Iter  3135\t      0.07700488 (Batch Size:   256)\n    Iter  3136\t      0.07500311 (Batch Size:   256)\n    Iter  3137\t      0.07024514 (Batch Size:   256)\n    Iter  3138\t      0.07952766 (Batch Size:   256)\n    Iter  3139\t      0.08689494 (Batch Size:   256)\n    Iter  3140\t      0.07664130 (Batch Size:   256)\n    Iter  3141\t      0.07765266 (Batch Size:   256)\n    Iter  3142\t      0.07733589 (Batch Size:   256)\n    Iter  3143\t      0.07854420 (Batch Size:   256)\n    Iter  3144\t      0.07094074 (Batch Size:   256)\n    Iter  3145\t      0.08202079 (Batch Size:   256)\n    Iter  3146\t      0.07419560 (Batch Size:   256)\n    Iter  3147\t      0.07894420 (Batch Size:   256)\n    Iter  3148\t      0.08571302 (Batch Size:   256)\n    Iter  3149\t      0.08081712 (Batch Size:   256)\n    Iter  3150\t      0.07409797 (Batch Size:   256)\n    Iter  3151\t      0.07513058 (Batch Size:   256)\n    Iter  3152\t      0.07335029 (Batch Size:   256)\n    Iter  3153\t      0.07276537 (Batch Size:   256)\n    Iter  3154\t      0.07296749 (Batch Size:   256)\n    Iter  3155\t      0.07518526 (Batch Size:   256)\n    Iter  3156\t      0.07581832 (Batch Size:   256)\n    Iter  3157\t      0.07524964 (Batch Size:   256)\n    Iter  3158\t      0.07036738 (Batch Size:   256)\n    Iter  3159\t      0.07327728 (Batch Size:   256)\n    Iter  3160\t      0.07321365 (Batch Size:   256)\n    Iter  3161\t      0.07754290 (Batch Size:   256)\n    Iter  3162\t      0.07448053 (Batch Size:   256)\n    Iter  3163\t      0.07290963 (Batch Size:   256)\n    Iter  3164\t      0.07359364 (Batch Size:   256)\n    Iter  3165\t      0.07300287 (Batch Size:   256)\n    Iter  3166\t      0.08190607 (Batch Size:   256)\n    Iter  3167\t      0.07949501 (Batch Size:   256)\n    Iter  3168\t      0.07233733 (Batch Size:   256)\n    Iter  3169\t      0.07237609 (Batch Size:   256)\n    Iter  3170\t      0.07617396 (Batch Size:   256)\n    Iter  3171\t      0.07788594 (Batch Size:   256)\n    Iter  3172\t      0.07741073 (Batch Size:   256)\n    Iter  3173\t      0.07712488 (Batch Size:   256)\n    Iter  3174\t      0.07777516 (Batch Size:   256)\n    Iter  3175\t      0.07475201 (Batch Size:   256)\n    Iter  3176\t      0.07717358 (Batch Size:   256)\n    Iter  3177\t      0.07141580 (Batch Size:   256)\n    Iter  3178\t      0.07404855 (Batch Size:   256)\n    Iter  3179\t      0.07814965 (Batch Size:   256)\n    Iter  3180\t      0.07873175 (Batch Size:   256)\n    Iter  3181\t      0.07250397 (Batch Size:   256)\n    Iter  3182\t      0.07687237 (Batch Size:   256)\n    Iter  3183\t      0.07649574 (Batch Size:   256)\n    Iter  3184\t      0.07207796 (Batch Size:   256)\n    Iter  3185\t      0.06957147 (Batch Size:   256)\n    Iter  3186\t      0.07717000 (Batch Size:   256)\n    Iter  3187\t      0.07662149 (Batch Size:   256)\n    Iter  3188\t      0.07258085 (Batch Size:   256)\n    Iter  3189\t      0.08279285 (Batch Size:   256)\n    Iter  3190\t      0.08380652 (Batch Size:   256)\n    Iter  3191\t      0.08219655 (Batch Size:   256)\n    Iter  3192\t      0.08937047 (Batch Size:   256)\n    Iter  3193\t      0.07256788 (Batch Size:   256)\n    Iter  3194\t      0.07677782 (Batch Size:   256)\n    Iter  3195\t      0.07891533 (Batch Size:   256)\n    Iter  3196\t      0.07251649 (Batch Size:   256)\n    Iter  3197\t      0.07156021 (Batch Size:   256)\n    Iter  3198\t      0.07258351 (Batch Size:   256)\n    Iter  3199\t      0.07782720 (Batch Size:   256)\n    Iter  3200\t      0.07280730 (Batch Size:   256)\n    Iter  3201\t      0.07180115 (Batch Size:   256)\n    Iter  3202\t      0.07338434 (Batch Size:   256)\n    Iter  3203\t      0.07658352 (Batch Size:   256)\n    Iter  3204\t      0.07941244 (Batch Size:   256)\n    Iter  3205\t      0.07120386 (Batch Size:   256)\n    Iter  3206\t      0.07361139 (Batch Size:   256)\n    Iter  3207\t      0.07520004 (Batch Size:   256)\n    Iter  3208\t      0.08285101 (Batch Size:   256)\n    Iter  3209\t      0.06799795 (Batch Size:   256)\n    Iter  3210\t      0.07363196 (Batch Size:   256)\n    Iter  3211\t      0.07329617 (Batch Size:   256)\n    Iter  3212\t      0.06978976 (Batch Size:   256)\n    Iter  3213\t      0.07219477 (Batch Size:   256)\n    Iter  3214\t      0.07144630 (Batch Size:   256)\n    Iter  3215\t      0.08391632 (Batch Size:   256)\n    Iter  3216\t      0.07756698 (Batch Size:   256)\n    Iter  3217\t      0.07654278 (Batch Size:   256)\n    Iter  3218\t      0.07104566 (Batch Size:   256)\n    Iter  3219\t      0.07211614 (Batch Size:   256)\n    Iter  3220\t      0.07307538 (Batch Size:   256)\n    Iter  3221\t      0.07333161 (Batch Size:   256)\n    Iter  3222\t      0.08387588 (Batch Size:   256)\n    Iter  3223\t      0.09562907 (Batch Size:   256)\n    Iter  3224\t      0.07970967 (Batch Size:   256)\n    Iter  3225\t      0.07338958 (Batch Size:   256)\n    Iter  3226\t      0.07297097 (Batch Size:   256)\n    Iter  3227\t      0.07228406 (Batch Size:   256)\n    Iter  3228\t      0.07732714 (Batch Size:   256)\n    Iter  3229\t      0.07235708 (Batch Size:   256)\n    Iter  3230\t      0.07834578 (Batch Size:   256)\n    Iter  3231\t      0.07634610 (Batch Size:   256)\n    Iter  3232\t      0.07054340 (Batch Size:   256)\n    Iter  3233\t      0.07721711 (Batch Size:   256)\n    Iter  3234\t      0.07502653 (Batch Size:   256)\n    Iter  3235\t      0.07297490 (Batch Size:   256)\n    Iter  3236\t      0.07808079 (Batch Size:   256)\n    Iter  3237\t      0.07548147 (Batch Size:   256)\n    Iter  3238\t      0.07930172 (Batch Size:   256)\n    Iter  3239\t      0.07322243 (Batch Size:   256)\n    Iter  3240\t      0.07380816 (Batch Size:   256)\n    Iter  3241\t      0.07258578 (Batch Size:   256)\n    Iter  3242\t      0.08249571 (Batch Size:   256)\n    Iter  3243\t      0.07500927 (Batch Size:   256)\n    Iter  3244\t      0.07643897 (Batch Size:   256)\n    Iter  3245\t      0.07053971 (Batch Size:   256)\n    Iter  3246\t      0.08264997 (Batch Size:   256)\n    Iter  3247\t      0.08793609 (Batch Size:   256)\n    Iter  3248\t      0.10295701 (Batch Size:   256)\n    Iter  3249\t      0.07817137 (Batch Size:   256)\n    Iter  3250\t      0.07747465 (Batch Size:   256)\n    Iter  3251\t      0.07624015 (Batch Size:   256)\n    Iter  3252\t      0.07433294 (Batch Size:   256)\n    Iter  3253\t      0.07415041 (Batch Size:   256)\n    Iter  3254\t      0.08014630 (Batch Size:   256)\n    Iter  3255\t      0.08220826 (Batch Size:   256)\n    Iter  3256\t      0.08926873 (Batch Size:   256)\n    Iter  3257\t      0.08181775 (Batch Size:   256)\n    Iter  3258\t      0.09278878 (Batch Size:   256)\n    Iter  3259\t      0.08115648 (Batch Size:   256)\n    Iter  3260\t      0.07569238 (Batch Size:   256)\n    Iter  3261\t      0.07470340 (Batch Size:   256)\n    Iter  3262\t      0.07685581 (Batch Size:   256)\n    Iter  3263\t      0.07399146 (Batch Size:   256)\n    Iter  3264\t      0.07270345 (Batch Size:   256)\n    Iter  3265\t      0.07062701 (Batch Size:   256)\n    Iter  3266\t      0.07109925 (Batch Size:   256)\n    Iter  3267\t      0.07415787 (Batch Size:   256)\n    Iter  3268\t      0.07408793 (Batch Size:   256)\n    Iter  3269\t      0.07008636 (Batch Size:   256)\n    Iter  3270\t      0.07378107 (Batch Size:   256)\n    Iter  3271\t      0.07352495 (Batch Size:   256)\n    Iter  3272\t      0.07343043 (Batch Size:   256)\n    Iter  3273\t      0.07228385 (Batch Size:   256)\n    Iter  3274\t      0.07356435 (Batch Size:   256)\n    Iter  3275\t      0.07307470 (Batch Size:   256)\n    Iter  3276\t      0.07330026 (Batch Size:   256)\n    Iter  3277\t      0.07757581 (Batch Size:   256)\n    Iter  3278\t      0.07475540 (Batch Size:   256)\n    Iter  3279\t      0.08299242 (Batch Size:   256)\n    Iter  3280\t      0.08373511 (Batch Size:   256)\n    Iter  3281\t      0.06926773 (Batch Size:   256)\n    Iter  3282\t      0.07869420 (Batch Size:   256)\n    Iter  3283\t      0.07871941 (Batch Size:   256)\n    Iter  3284\t      0.07722758 (Batch Size:   256)\n    Iter  3285\t      0.07411128 (Batch Size:   256)\n    Iter  3286\t      0.07826994 (Batch Size:   256)\n    Iter  3287\t      0.07715346 (Batch Size:   256)\n    Iter  3288\t      0.07544990 (Batch Size:   256)\n    Iter  3289\t      0.07426473 (Batch Size:   256)\n    Iter  3290\t      0.07265942 (Batch Size:   256)\n    Iter  3291\t      0.07984636 (Batch Size:   256)\n    Iter  3292\t      0.08280744 (Batch Size:   256)\n    Iter  3293\t      0.07398432 (Batch Size:   256)\n    Iter  3294\t      0.07411395 (Batch Size:   256)\n    Iter  3295\t      0.07826086 (Batch Size:   256)\n    Iter  3296\t      0.07165982 (Batch Size:   256)\n    Iter  3297\t      0.07383773 (Batch Size:   256)\n    Iter  3298\t      0.07327815 (Batch Size:   256)\n    Iter  3299\t      0.07610884 (Batch Size:   256)\n    Iter  3300\t      0.07590984 (Batch Size:   256)\n    Iter  3301\t      0.07057573 (Batch Size:   256)\n    Iter  3302\t      0.07504954 (Batch Size:   256)\n    Iter  3303\t      0.07166916 (Batch Size:   256)\n    Iter  3304\t      0.07408710 (Batch Size:   256)\n    Iter  3305\t      0.07150979 (Batch Size:   256)\n    Iter  3306\t      0.07452749 (Batch Size:   256)\n    Iter  3307\t      0.07778747 (Batch Size:   256)\n    Iter  3308\t      0.07880864 (Batch Size:   256)\n    Iter  3309\t      0.07456964 (Batch Size:   256)\n    Iter  3310\t      0.07692903 (Batch Size:   256)\n    Iter  3311\t      0.06802536 (Batch Size:   256)\n    Iter  3312\t      0.07572052 (Batch Size:   256)\n    Iter  3313\t      0.08264554 (Batch Size:   256)\n    Iter  3314\t      0.07272814 (Batch Size:   256)\n    Iter  3315\t      0.07422191 (Batch Size:   256)\n    Iter  3316\t      0.07348437 (Batch Size:   256)\n    Iter  3317\t      0.07638903 (Batch Size:   256)\n    Iter  3318\t      0.08573144 (Batch Size:   256)\n    Iter  3319\t      0.07442076 (Batch Size:   256)\n    Iter  3320\t      0.07200143 (Batch Size:   256)\n    Iter  3321\t      0.07373323 (Batch Size:   256)\n    Iter  3322\t      0.07458039 (Batch Size:   256)\n    Iter  3323\t      0.07227134 (Batch Size:   256)\n    Iter  3324\t      0.07377019 (Batch Size:   256)\n    Iter  3325\t      0.07868463 (Batch Size:   256)\n    Iter  3326\t      0.07685419 (Batch Size:   256)\n    Iter  3327\t      0.07536984 (Batch Size:   256)\n    Iter  3328\t      0.07263647 (Batch Size:   256)\n    Iter  3329\t      0.07068336 (Batch Size:   256)\n    Iter  3330\t      0.07390640 (Batch Size:   256)\n    Iter  3331\t      0.07685423 (Batch Size:   256)\n    Iter  3332\t      0.07356135 (Batch Size:   256)\n    Iter  3333\t      0.07526701 (Batch Size:   256)\n    Iter  3334\t      0.07670652 (Batch Size:   256)\n    Iter  3335\t      0.08359840 (Batch Size:   256)\n    Iter  3336\t      0.07799490 (Batch Size:   256)\n    Iter  3337\t      0.07523482 (Batch Size:   256)\n    Iter  3338\t      0.08448526 (Batch Size:   256)\n    Iter  3339\t      0.07902160 (Batch Size:   256)\n    Iter  3340\t      0.08255370 (Batch Size:   256)\n    Iter  3341\t      0.07421286 (Batch Size:   256)\n    Iter  3342\t      0.08240249 (Batch Size:   256)\n    Iter  3343\t      0.07669607 (Batch Size:   256)\n    Iter  3344\t      0.07312134 (Batch Size:   256)\n    Iter  3345\t      0.07659434 (Batch Size:   256)\n    Iter  3346\t      0.07166639 (Batch Size:   256)\n    Iter  3347\t      0.07828205 (Batch Size:   256)\n    Iter  3348\t      0.07339468 (Batch Size:   256)\n    Iter  3349\t      0.07012438 (Batch Size:   256)\n    Iter  3350\t      0.07611163 (Batch Size:   256)\n    Iter  3351\t      0.07307627 (Batch Size:   256)\n    Iter  3352\t      0.07374840 (Batch Size:   256)\n    Iter  3353\t      0.08587528 (Batch Size:   256)\n    Iter  3354\t      0.07229818 (Batch Size:   256)\n    Iter  3355\t      0.07426788 (Batch Size:   256)\n    Iter  3356\t      0.07844522 (Batch Size:   256)\n    Iter  3357\t      0.08462768 (Batch Size:   256)\n    Iter  3358\t      0.07296471 (Batch Size:   256)\n    Iter  3359\t      0.07267665 (Batch Size:   256)\n    Iter  3360\t      0.07185915 (Batch Size:   256)\n    Iter  3361\t      0.07522501 (Batch Size:   256)\n    Iter  3362\t      0.07168345 (Batch Size:   256)\n    Iter  3363\t      0.07375103 (Batch Size:   256)\n    Iter  3364\t      0.07582388 (Batch Size:   256)\n    Iter  3365\t      0.07694843 (Batch Size:   256)\n    Iter  3366\t      0.07699514 (Batch Size:   256)\n    Iter  3367\t      0.08059969 (Batch Size:   256)\n    Iter  3368\t      0.07539032 (Batch Size:   256)\n    Iter  3369\t      0.07671127 (Batch Size:   256)\n    Iter  3370\t      0.07986785 (Batch Size:   256)\n    Iter  3371\t      0.07473652 (Batch Size:   256)\n    Iter  3372\t      0.07225055 (Batch Size:   256)\n    Iter  3373\t      0.07916953 (Batch Size:   256)\n    Iter  3374\t      0.08589586 (Batch Size:   256)\n    Iter  3375\t      0.08366224 (Batch Size:   256)\n    Iter  3376\t      0.07967384 (Batch Size:   256)\n    Iter  3377\t      0.07623946 (Batch Size:   256)\n    Iter  3378\t      0.07621158 (Batch Size:   256)\n    Iter  3379\t      0.07369609 (Batch Size:   256)\n    Iter  3380\t      0.07670307 (Batch Size:   256)\n    Iter  3381\t      0.08690413 (Batch Size:   256)\n    Iter  3382\t      0.07435307 (Batch Size:   256)\n    Iter  3383\t      0.07957676 (Batch Size:   256)\n    Iter  3384\t      0.07892857 (Batch Size:   256)\n    Iter  3385\t      0.07713256 (Batch Size:   256)\n    Iter  3386\t      0.07786823 (Batch Size:   256)\n    Iter  3387\t      0.07727859 (Batch Size:   256)\n    Iter  3388\t      0.07975926 (Batch Size:   256)\n    Iter  3389\t      0.07830242 (Batch Size:   256)\n    Iter  3390\t      0.08293447 (Batch Size:   256)\n    Iter  3391\t      0.07547535 (Batch Size:   256)\n    Iter  3392\t      0.07589332 (Batch Size:   256)\n    Iter  3393\t      0.07986370 (Batch Size:   256)\n    Iter  3394\t      0.07012850 (Batch Size:   256)\n    Iter  3395\t      0.07202399 (Batch Size:   256)\n    Iter  3396\t      0.07506190 (Batch Size:   256)\n    Iter  3397\t      0.07412519 (Batch Size:   256)\n    Iter  3398\t      0.07613936 (Batch Size:   256)\n    Iter  3399\t      0.07711796 (Batch Size:   256)\n    Iter  3400\t      0.07966856 (Batch Size:   256)\n    Iter  3401\t      0.08033554 (Batch Size:   256)\n    Iter  3402\t      0.09306236 (Batch Size:   256)\n    Iter  3403\t      0.10304773 (Batch Size:   256)\n    Iter  3404\t      0.08980337 (Batch Size:   256)\n    Iter  3405\t      0.07607865 (Batch Size:   256)\n    Iter  3406\t      0.07689933 (Batch Size:   256)\n    Iter  3407\t      0.07031689 (Batch Size:   256)\n    Iter  3408\t      0.07459527 (Batch Size:   256)\n    Iter  3409\t      0.07307968 (Batch Size:   256)\n    Iter  3410\t      0.07493827 (Batch Size:   256)\n    Iter  3411\t      0.07398948 (Batch Size:   256)\n    Iter  3412\t      0.07021808 (Batch Size:   256)\n    Iter  3413\t      0.07515306 (Batch Size:   256)\n    Iter  3414\t      0.07643751 (Batch Size:   256)\n    Iter  3415\t      0.07759612 (Batch Size:   256)\n    Iter  3416\t      0.07777340 (Batch Size:   256)\n    Iter  3417\t      0.07622054 (Batch Size:   256)\n    Iter  3418\t      0.07179660 (Batch Size:   256)\n    Iter  3419\t      0.07898570 (Batch Size:   256)\n    Iter  3420\t      0.07184006 (Batch Size:   256)\n    Iter  3421\t      0.07490670 (Batch Size:   256)\n    Iter  3422\t      0.07429260 (Batch Size:   256)\n    Iter  3423\t      0.07929737 (Batch Size:   256)\n    Iter  3424\t      0.07669368 (Batch Size:   256)\n    Iter  3425\t      0.07723541 (Batch Size:   256)\n    Iter  3426\t      0.07917714 (Batch Size:   256)\n    Iter  3427\t      0.08314637 (Batch Size:   256)\n    Iter  3428\t      0.08838063 (Batch Size:   256)\n    Iter  3429\t      0.08626124 (Batch Size:   256)\n    Iter  3430\t      0.08146934 (Batch Size:   256)\n    Iter  3431\t      0.07795145 (Batch Size:   256)\n    Iter  3432\t      0.07670344 (Batch Size:   256)\n    Iter  3433\t      0.07505163 (Batch Size:   256)\n    Iter  3434\t      0.07532404 (Batch Size:   256)\n    Iter  3435\t      0.07430951 (Batch Size:   256)\n    Iter  3436\t      0.07730734 (Batch Size:   256)\n    Iter  3437\t      0.07602751 (Batch Size:   256)\n    Iter  3438\t      0.07565422 (Batch Size:   256)\n    Iter  3439\t      0.07860915 (Batch Size:   256)\n    Iter  3440\t      0.07438790 (Batch Size:   256)\n    Iter  3441\t      0.07511897 (Batch Size:   256)\n    Iter  3442\t      0.07632954 (Batch Size:   256)\n    Iter  3443\t      0.07842048 (Batch Size:   256)\n    Iter  3444\t      0.08173453 (Batch Size:   256)\n    Iter  3445\t      0.08782434 (Batch Size:   256)\n    Iter  3446\t      0.07828094 (Batch Size:   256)\n    Iter  3447\t      0.07953131 (Batch Size:   256)\n    Iter  3448\t      0.07614551 (Batch Size:   256)\n    Iter  3449\t      0.07661019 (Batch Size:   256)\n    Iter  3450\t      0.07709818 (Batch Size:   256)\n    Iter  3451\t      0.07760643 (Batch Size:   256)\n    Iter  3452\t      0.07891448 (Batch Size:   256)\n    Iter  3453\t      0.07961793 (Batch Size:   256)\n    Iter  3454\t      0.07486892 (Batch Size:   256)\n    Iter  3455\t      0.07311313 (Batch Size:   256)\n    Iter  3456\t      0.07410111 (Batch Size:   256)\n    Iter  3457\t      0.07527042 (Batch Size:   256)\n    Iter  3458\t      0.07968440 (Batch Size:   256)\n    Iter  3459\t      0.07163453 (Batch Size:   256)\n    Iter  3460\t      0.07322387 (Batch Size:   256)\n    Iter  3461\t      0.07567271 (Batch Size:   256)\n    Iter  3462\t      0.08417603 (Batch Size:   256)\n    Iter  3463\t      0.07805618 (Batch Size:   256)\n    Iter  3464\t      0.07527995 (Batch Size:   256)\n    Iter  3465\t      0.08820286 (Batch Size:   256)\n    Iter  3466\t      0.08657483 (Batch Size:   256)\n    Iter  3467\t      0.07676108 (Batch Size:   256)\n    Iter  3468\t      0.08011964 (Batch Size:   256)\n    Iter  3469\t      0.07880734 (Batch Size:   256)\n    Iter  3470\t      0.07056390 (Batch Size:   256)\n    Iter  3471\t      0.07296277 (Batch Size:   256)\n    Iter  3472\t      0.07049223 (Batch Size:   256)\n    Iter  3473\t      0.07702467 (Batch Size:   256)\n    Iter  3474\t      0.07412173 (Batch Size:   256)\n    Iter  3475\t      0.07165799 (Batch Size:   256)\n    Iter  3476\t      0.07424330 (Batch Size:   256)\n    Iter  3477\t      0.07498102 (Batch Size:   256)\n    Iter  3478\t      0.07570135 (Batch Size:   256)\n    Iter  3479\t      0.07317665 (Batch Size:   256)\n    Iter  3480\t      0.07627636 (Batch Size:   256)\n    Iter  3481\t      0.07830228 (Batch Size:   256)\n    Iter  3482\t      0.08969101 (Batch Size:   256)\n    Iter  3483\t      0.07583535 (Batch Size:   256)\n    Iter  3484\t      0.07249983 (Batch Size:   256)\n    Iter  3485\t      0.07224353 (Batch Size:   256)\n    Iter  3486\t      0.07255038 (Batch Size:   256)\n    Iter  3487\t      0.07122958 (Batch Size:   256)\n    Iter  3488\t      0.07310461 (Batch Size:   256)\n    Iter  3489\t      0.07223908 (Batch Size:   256)\n    Iter  3490\t      0.07474652 (Batch Size:   256)\n    Iter  3491\t      0.07466296 (Batch Size:   256)\n    Iter  3492\t      0.07247116 (Batch Size:   256)\n    Iter  3493\t      0.07069596 (Batch Size:   256)\n    Iter  3494\t      0.07605286 (Batch Size:   256)\n    Iter  3495\t      0.07439495 (Batch Size:   256)\n    Iter  3496\t      0.07647994 (Batch Size:   256)\n    Iter  3497\t      0.07847515 (Batch Size:   256)\n    Iter  3498\t      0.07997807 (Batch Size:   256)\n    Iter  3499\t      0.07925619 (Batch Size:   256)\n    Iter  3500\t      0.07634596 (Batch Size:   256)\n    Iter  3501\t      0.07538135 (Batch Size:   256)\n    Iter  3502\t      0.07391154 (Batch Size:   256)\n    Iter  3503\t      0.07987037 (Batch Size:   256)\n    Iter  3504\t      0.07605246 (Batch Size:   256)\n    Iter  3505\t      0.08203142 (Batch Size:   256)\n    Iter  3506\t      0.07521620 (Batch Size:   256)\n    Iter  3507\t      0.07532245 (Batch Size:   256)\n    Iter  3508\t      0.08118967 (Batch Size:   256)\n    Iter  3509\t      0.08427555 (Batch Size:   256)\n    Iter  3510\t      0.08681539 (Batch Size:   256)\n    Iter  3511\t      0.09431199 (Batch Size:   256)\n    Iter  3512\t      0.07914315 (Batch Size:   256)\n    Iter  3513\t      0.07951015 (Batch Size:   256)\n    Iter  3514\t      0.07147743 (Batch Size:   256)\n    Iter  3515\t      0.07395189 (Batch Size:   256)\n    Iter  3516\t      0.07650451 (Batch Size:   256)\n    Iter  3517\t      0.07474308 (Batch Size:   256)\n    Iter  3518\t      0.07662664 (Batch Size:   256)\n    Iter  3519\t      0.08679070 (Batch Size:   256)\n    Iter  3520\t      0.08264618 (Batch Size:   256)\n    Iter  3521\t      0.07672553 (Batch Size:   256)\n    Iter  3522\t      0.07067242 (Batch Size:   256)\n    Iter  3523\t      0.07278647 (Batch Size:   256)\n    Iter  3524\t      0.07359740 (Batch Size:   256)\n    Iter  3525\t      0.07331082 (Batch Size:   256)\n    Iter  3526\t      0.07318367 (Batch Size:   256)\n    Iter  3527\t      0.07004887 (Batch Size:   256)\n    Iter  3528\t      0.07786895 (Batch Size:   256)\n    Iter  3529\t      0.07735268 (Batch Size:   256)\n    Iter  3530\t      0.07951504 (Batch Size:   256)\n    Iter  3531\t      0.07148040 (Batch Size:   256)\n    Iter  3532\t      0.07419634 (Batch Size:   256)\n    Iter  3533\t      0.07718245 (Batch Size:   256)\n    Iter  3534\t      0.07564057 (Batch Size:   256)\n    Iter  3535\t      0.08184359 (Batch Size:   256)\n    Iter  3536\t      0.07450056 (Batch Size:   256)\n    Iter  3537\t      0.07582683 (Batch Size:   256)\n    Iter  3538\t      0.07581883 (Batch Size:   256)\n    Iter  3539\t      0.07625099 (Batch Size:   256)\n    Iter  3540\t      0.07626775 (Batch Size:   256)\n    Iter  3541\t      0.07660141 (Batch Size:   256)\n    Iter  3542\t      0.07254614 (Batch Size:   256)\n    Iter  3543\t      0.07885898 (Batch Size:   256)\n    Iter  3544\t      0.07742424 (Batch Size:   256)\n    Iter  3545\t      0.07743344 (Batch Size:   256)\n    Iter  3546\t      0.08414314 (Batch Size:   256)\n    Iter  3547\t      0.10000725 (Batch Size:   256)\n    Iter  3548\t      0.08931819 (Batch Size:   256)\n    Iter  3549\t      0.08297605 (Batch Size:   256)\n    Iter  3550\t      0.08656856 (Batch Size:   256)\n    Iter  3551\t      0.09147996 (Batch Size:   256)\n    Iter  3552\t      0.08653002 (Batch Size:   256)\n    Iter  3553\t      0.07480226 (Batch Size:   256)\n    Iter  3554\t      0.07510973 (Batch Size:   256)\n    Iter  3555\t      0.07358482 (Batch Size:   256)\n    Iter  3556\t      0.07225787 (Batch Size:   256)\n    Iter  3557\t      0.07778608 (Batch Size:   256)\n    Iter  3558\t      0.07570012 (Batch Size:   256)\n    Iter  3559\t      0.07771686 (Batch Size:   256)\n    Iter  3560\t      0.08682433 (Batch Size:   256)\n    Iter  3561\t      0.07583393 (Batch Size:   256)\n    Iter  3562\t      0.07694769 (Batch Size:   256)\n    Iter  3563\t      0.07711953 (Batch Size:   256)\n    Iter  3564\t      0.07623520 (Batch Size:   256)\n    Iter  3565\t      0.07450493 (Batch Size:   256)\n    Iter  3566\t      0.07506128 (Batch Size:   256)\n    Iter  3567\t      0.07247085 (Batch Size:   256)\n    Iter  3568\t      0.07683085 (Batch Size:   256)\n    Iter  3569\t      0.08016205 (Batch Size:   256)\n    Iter  3570\t      0.07697206 (Batch Size:   256)\n    Iter  3571\t      0.08040177 (Batch Size:   256)\n    Iter  3572\t      0.07012891 (Batch Size:   256)\n    Iter  3573\t      0.08491250 (Batch Size:   256)\n    Iter  3574\t      0.07442968 (Batch Size:   256)\n    Iter  3575\t      0.07403898 (Batch Size:   256)\n    Iter  3576\t      0.07350025 (Batch Size:   256)\n    Iter  3577\t      0.07439603 (Batch Size:   256)\n    Iter  3578\t      0.07709993 (Batch Size:   256)\n    Iter  3579\t      0.07453796 (Batch Size:   256)\n    Iter  3580\t      0.07160960 (Batch Size:   256)\n    Iter  3581\t      0.07510801 (Batch Size:   256)\n    Iter  3582\t      0.07564337 (Batch Size:   256)\n    Iter  3583\t      0.07100906 (Batch Size:   256)\n    Iter  3584\t      0.07462929 (Batch Size:   256)\n    Iter  3585\t      0.07155617 (Batch Size:   256)\n    Iter  3586\t      0.07310750 (Batch Size:   256)\n    Iter  3587\t      0.07538088 (Batch Size:   256)\n    Iter  3588\t      0.07500826 (Batch Size:   256)\n    Iter  3589\t      0.06951068 (Batch Size:   256)\n    Iter  3590\t      0.07250576 (Batch Size:   256)\n    Iter  3591\t      0.07347855 (Batch Size:   256)\n    Iter  3592\t      0.08663576 (Batch Size:   256)\n    Iter  3593\t      0.07889800 (Batch Size:   256)\n    Iter  3594\t      0.07733759 (Batch Size:   256)\n    Iter  3595\t      0.08069025 (Batch Size:   256)\n    Iter  3596\t      0.07825066 (Batch Size:   256)\n    Iter  3597\t      0.07436931 (Batch Size:   256)\n    Iter  3598\t      0.07162374 (Batch Size:   256)\n    Iter  3599\t      0.07517058 (Batch Size:   256)\n    Iter  3600\t      0.07134945 (Batch Size:   256)\n    Iter  3601\t      0.07452923 (Batch Size:   256)\n    Iter  3602\t      0.07602484 (Batch Size:   256)\n    Iter  3603\t      0.09190864 (Batch Size:   256)\n    Iter  3604\t      0.07998811 (Batch Size:   256)\n    Iter  3605\t      0.08014142 (Batch Size:   256)\n    Iter  3606\t      0.08321075 (Batch Size:   256)\n    Iter  3607\t      0.08024837 (Batch Size:   256)\n    Iter  3608\t      0.07815667 (Batch Size:   256)\n    Iter  3609\t      0.08524604 (Batch Size:   256)\n    Iter  3610\t      0.07972410 (Batch Size:   256)\n    Iter  3611\t      0.07488006 (Batch Size:   256)\n    Iter  3612\t      0.09500763 (Batch Size:   256)\n    Iter  3613\t      0.08446377 (Batch Size:   256)\n    Iter  3614\t      0.07577820 (Batch Size:   256)\n    Iter  3615\t      0.07293748 (Batch Size:   256)\n    Iter  3616\t      0.07427667 (Batch Size:   256)\n    Iter  3617\t      0.07651263 (Batch Size:   256)\n    Iter  3618\t      0.07541036 (Batch Size:   256)\n    Iter  3619\t      0.07733042 (Batch Size:   256)\n    Iter  3620\t      0.07007410 (Batch Size:   256)\n    Iter  3621\t      0.08019636 (Batch Size:   256)\n    Iter  3622\t      0.08083344 (Batch Size:   256)\n    Iter  3623\t      0.07276033 (Batch Size:   256)\n    Iter  3624\t      0.07787640 (Batch Size:   256)\n    Iter  3625\t      0.07772688 (Batch Size:   256)\n    Iter  3626\t      0.07352450 (Batch Size:   256)\n    Iter  3627\t      0.07285086 (Batch Size:   256)\n    Iter  3628\t      0.07305759 (Batch Size:   256)\n    Iter  3629\t      0.07136560 (Batch Size:   256)\n    Iter  3630\t      0.07712437 (Batch Size:   256)\n    Iter  3631\t      0.07432448 (Batch Size:   256)\n    Iter  3632\t      0.07163000 (Batch Size:   256)\n    Iter  3633\t      0.07436050 (Batch Size:   256)\n    Iter  3634\t      0.07641775 (Batch Size:   256)\n    Iter  3635\t      0.07986366 (Batch Size:   256)\n    Iter  3636\t      0.07528993 (Batch Size:   256)\n    Iter  3637\t      0.07356878 (Batch Size:   256)\n    Iter  3638\t      0.06942488 (Batch Size:   256)\n    Iter  3639\t      0.06972663 (Batch Size:   256)\n    Iter  3640\t      0.07395685 (Batch Size:   256)\n    Iter  3641\t      0.07334727 (Batch Size:   256)\n    Iter  3642\t      0.07907118 (Batch Size:   256)\n    Iter  3643\t      0.07842966 (Batch Size:   256)\n    Iter  3644\t      0.07315463 (Batch Size:   256)\n    Iter  3645\t      0.07036162 (Batch Size:   256)\n    Iter  3646\t      0.07363111 (Batch Size:   256)\n    Iter  3647\t      0.07433305 (Batch Size:   256)\n    Iter  3648\t      0.07426266 (Batch Size:   256)\n    Iter  3649\t      0.07405152 (Batch Size:   256)\n    Iter  3650\t      0.07199999 (Batch Size:   256)\n    Iter  3651\t      0.07116262 (Batch Size:   256)\n    Iter  3652\t      0.07269355 (Batch Size:   256)\n    Iter  3653\t      0.07067974 (Batch Size:   256)\n    Iter  3654\t      0.07078409 (Batch Size:   256)\n    Iter  3655\t      0.07053303 (Batch Size:   256)\n    Iter  3656\t      0.07276969 (Batch Size:   256)\n    Iter  3657\t      0.07062234 (Batch Size:   256)\n    Iter  3658\t      0.07302609 (Batch Size:   256)\n    Iter  3659\t      0.06986794 (Batch Size:   256)\n    Iter  3660\t      0.07578112 (Batch Size:   256)\n    Iter  3661\t      0.07075810 (Batch Size:   256)\n    Iter  3662\t      0.07660141 (Batch Size:   256)\n    Iter  3663\t      0.07303380 (Batch Size:   256)\n    Iter  3664\t      0.07851040 (Batch Size:   256)\n    Iter  3665\t      0.07216949 (Batch Size:   256)\n    Iter  3666\t      0.07455991 (Batch Size:   256)\n    Iter  3667\t      0.07894825 (Batch Size:   256)\n    Iter  3668\t      0.07623258 (Batch Size:   256)\n    Iter  3669\t      0.07141968 (Batch Size:   256)\n    Iter  3670\t      0.07153729 (Batch Size:   256)\n    Iter  3671\t      0.07553484 (Batch Size:   256)\n    Iter  3672\t      0.07617422 (Batch Size:   256)\n    Iter  3673\t      0.07593572 (Batch Size:   256)\n    Iter  3674\t      0.06859842 (Batch Size:   256)\n    Iter  3675\t      0.07673453 (Batch Size:   256)\n    Iter  3676\t      0.08258237 (Batch Size:   256)\n    Iter  3677\t      0.07601597 (Batch Size:   256)\n    Iter  3678\t      0.07369008 (Batch Size:   256)\n    Iter  3679\t      0.07143943 (Batch Size:   256)\n    Iter  3680\t      0.07861157 (Batch Size:   256)\n    Iter  3681\t      0.07424105 (Batch Size:   256)\n    Iter  3682\t      0.07259786 (Batch Size:   256)\n    Iter  3683\t      0.07750201 (Batch Size:   256)\n    Iter  3684\t      0.07183087 (Batch Size:   256)\n    Iter  3685\t      0.07106296 (Batch Size:   256)\n    Iter  3686\t      0.07660813 (Batch Size:   256)\n    Iter  3687\t      0.07846234 (Batch Size:   256)\n    Iter  3688\t      0.07799771 (Batch Size:   256)\n    Iter  3689\t      0.07315959 (Batch Size:   256)\n    Iter  3690\t      0.07113831 (Batch Size:   256)\n    Iter  3691\t      0.07193005 (Batch Size:   256)\n    Iter  3692\t      0.07149306 (Batch Size:   256)\n    Iter  3693\t      0.07594465 (Batch Size:   256)\n    Iter  3694\t      0.07430999 (Batch Size:   256)\n    Iter  3695\t      0.07238169 (Batch Size:   256)\n    Iter  3696\t      0.07150602 (Batch Size:   256)\n    Iter  3697\t      0.07392697 (Batch Size:   256)\n    Iter  3698\t      0.07672946 (Batch Size:   256)\n    Iter  3699\t      0.07050417 (Batch Size:   256)\n    Iter  3700\t      0.07505448 (Batch Size:   256)\n    Iter  3701\t      0.07706410 (Batch Size:   256)\n    Iter  3702\t      0.07351113 (Batch Size:   256)\n    Iter  3703\t      0.07161364 (Batch Size:   256)\n    Iter  3704\t      0.07338993 (Batch Size:   256)\n    Iter  3705\t      0.07758774 (Batch Size:   256)\n    Iter  3706\t      0.07514446 (Batch Size:   256)\n    Iter  3707\t      0.08096082 (Batch Size:   256)\n    Iter  3708\t      0.07932965 (Batch Size:   256)\n    Iter  3709\t      0.07049294 (Batch Size:   256)\n    Iter  3710\t      0.07122788 (Batch Size:   256)\n    Iter  3711\t      0.07596839 (Batch Size:   256)\n    Iter  3712\t      0.07878218 (Batch Size:   256)\n    Iter  3713\t      0.07574515 (Batch Size:   256)\n    Iter  3714\t      0.07647773 (Batch Size:   256)\n    Iter  3715\t      0.07272675 (Batch Size:   256)\n    Iter  3716\t      0.07329249 (Batch Size:   256)\n    Iter  3717\t      0.07162106 (Batch Size:   256)\n    Iter  3718\t      0.07741501 (Batch Size:   256)\n    Iter  3719\t      0.07224329 (Batch Size:   256)\n    Iter  3720\t      0.07183384 (Batch Size:   256)\n    Iter  3721\t      0.07506437 (Batch Size:   256)\n    Iter  3722\t      0.07248867 (Batch Size:   256)\n    Iter  3723\t      0.07328136 (Batch Size:   256)\n    Iter  3724\t      0.07701263 (Batch Size:   256)\n    Iter  3725\t      0.07049033 (Batch Size:   256)\n    Iter  3726\t      0.08076539 (Batch Size:   256)\n    Iter  3727\t      0.07907709 (Batch Size:   256)\n    Iter  3728\t      0.08064951 (Batch Size:   256)\n    Iter  3729\t      0.08876026 (Batch Size:   256)\n    Iter  3730\t      0.07515394 (Batch Size:   256)\n    Iter  3731\t      0.09019885 (Batch Size:   256)\n    Iter  3732\t      0.07281769 (Batch Size:   256)\n    Iter  3733\t      0.07172260 (Batch Size:   256)\n    Iter  3734\t      0.07768359 (Batch Size:   256)\n    Iter  3735\t      0.07510215 (Batch Size:   256)\n    Iter  3736\t      0.07741926 (Batch Size:   256)\n    Iter  3737\t      0.07450201 (Batch Size:   256)\n    Iter  3738\t      0.08036756 (Batch Size:   256)\n    Iter  3739\t      0.07828337 (Batch Size:   256)\n    Iter  3740\t      0.08572536 (Batch Size:   256)\n    Iter  3741\t      0.07778026 (Batch Size:   256)\n    Iter  3742\t      0.07593183 (Batch Size:   256)\n    Iter  3743\t      0.06986033 (Batch Size:   256)\n    Iter  3744\t      0.06970319 (Batch Size:   256)\n    Iter  3745\t      0.07200208 (Batch Size:   256)\n    Iter  3746\t      0.07788343 (Batch Size:   256)\n    Iter  3747\t      0.07567934 (Batch Size:   256)\n    Iter  3748\t      0.07492105 (Batch Size:   256)\n    Iter  3749\t      0.07533553 (Batch Size:   256)\n    Iter  3750\t      0.07462439 (Batch Size:   256)\n    Iter  3751\t      0.07043555 (Batch Size:   256)\n    Iter  3752\t      0.06971560 (Batch Size:   256)\n    Iter  3753\t      0.07136133 (Batch Size:   256)\n    Iter  3754\t      0.07435780 (Batch Size:   256)\n    Iter  3755\t      0.07700486 (Batch Size:   256)\n    Iter  3756\t      0.07685254 (Batch Size:   256)\n    Iter  3757\t      0.07694097 (Batch Size:   256)\n    Iter  3758\t      0.07386376 (Batch Size:   256)\n    Iter  3759\t      0.08532590 (Batch Size:   256)\n    Iter  3760\t      0.08332749 (Batch Size:   256)\n    Iter  3761\t      0.07784501 (Batch Size:   256)\n    Iter  3762\t      0.08198615 (Batch Size:   256)\n    Iter  3763\t      0.08988999 (Batch Size:   256)\n    Iter  3764\t      0.08309931 (Batch Size:   256)\n    Iter  3765\t      0.07807627 (Batch Size:   256)\n    Iter  3766\t      0.07521413 (Batch Size:   256)\n    Iter  3767\t      0.07610888 (Batch Size:   256)\n    Iter  3768\t      0.07585009 (Batch Size:   256)\n    Iter  3769\t      0.08056843 (Batch Size:   256)\n    Iter  3770\t      0.08188701 (Batch Size:   256)\n    Iter  3771\t      0.08082848 (Batch Size:   256)\n    Iter  3772\t      0.07420265 (Batch Size:   256)\n    Iter  3773\t      0.07681092 (Batch Size:   256)\n    Iter  3774\t      0.08228339 (Batch Size:   256)\n    Iter  3775\t      0.08249884 (Batch Size:   256)\n    Iter  3776\t      0.07250005 (Batch Size:   256)\n    Iter  3777\t      0.07021074 (Batch Size:   256)\n    Iter  3778\t      0.07616646 (Batch Size:   256)\n    Iter  3779\t      0.07783144 (Batch Size:   256)\n    Iter  3780\t      0.07799060 (Batch Size:   256)\n    Iter  3781\t      0.08500521 (Batch Size:   256)\n    Iter  3782\t      0.08647596 (Batch Size:   256)\n    Iter  3783\t      0.07630152 (Batch Size:   256)\n    Iter  3784\t      0.06984141 (Batch Size:   256)\n    Iter  3785\t      0.07447335 (Batch Size:   256)\n    Iter  3786\t      0.07551830 (Batch Size:   256)\n    Iter  3787\t      0.07491726 (Batch Size:   256)\n    Iter  3788\t      0.07051823 (Batch Size:   256)\n    Iter  3789\t      0.07030893 (Batch Size:   256)\n    Iter  3790\t      0.07332476 (Batch Size:   256)\n    Iter  3791\t      0.07457471 (Batch Size:   256)\n    Iter  3792\t      0.07359024 (Batch Size:   256)\n    Iter  3793\t      0.07417980 (Batch Size:   256)\n    Iter  3794\t      0.07757865 (Batch Size:   256)\n    Iter  3795\t      0.07885393 (Batch Size:   256)\n    Iter  3796\t      0.07181048 (Batch Size:   256)\n    Iter  3797\t      0.07299620 (Batch Size:   256)\n    Iter  3798\t      0.07480112 (Batch Size:   256)\n    Iter  3799\t      0.06925533 (Batch Size:   256)\n    Iter  3800\t      0.07564844 (Batch Size:   256)\n    Iter  3801\t      0.07708267 (Batch Size:   256)\n    Iter  3802\t      0.07312916 (Batch Size:   256)\n    Iter  3803\t      0.07779341 (Batch Size:   256)\n    Iter  3804\t      0.07268045 (Batch Size:   256)\n    Iter  3805\t      0.07420100 (Batch Size:   256)\n    Iter  3806\t      0.08188860 (Batch Size:   256)\n    Iter  3807\t      0.07690183 (Batch Size:   256)\n    Iter  3808\t      0.07179518 (Batch Size:   256)\n    Iter  3809\t      0.07515600 (Batch Size:   256)\n    Iter  3810\t      0.07125446 (Batch Size:   256)\n    Iter  3811\t      0.06989729 (Batch Size:   256)\n    Iter  3812\t      0.07378357 (Batch Size:   256)\n    Iter  3813\t      0.07793313 (Batch Size:   256)\n    Iter  3814\t      0.08743192 (Batch Size:   256)\n    Iter  3815\t      0.07271315 (Batch Size:   256)\n    Iter  3816\t      0.07413253 (Batch Size:   256)\n    Iter  3817\t      0.09222087 (Batch Size:   256)\n    Iter  3818\t      0.08693054 (Batch Size:   256)\n    Iter  3819\t      0.07569096 (Batch Size:   256)\n    Iter  3820\t      0.07735050 (Batch Size:   256)\n    Iter  3821\t      0.07220234 (Batch Size:   256)\n    Iter  3822\t      0.07102044 (Batch Size:   256)\n    Iter  3823\t      0.07397973 (Batch Size:   256)\n    Iter  3824\t      0.07292126 (Batch Size:   256)\n    Iter  3825\t      0.07580897 (Batch Size:   256)\n    Iter  3826\t      0.07284012 (Batch Size:   256)\n    Iter  3827\t      0.07065400 (Batch Size:   256)\n    Iter  3828\t      0.06901072 (Batch Size:   256)\n    Iter  3829\t      0.07320973 (Batch Size:   256)\n    Iter  3830\t      0.08218249 (Batch Size:   256)\n    Iter  3831\t      0.07733043 (Batch Size:   256)\n    Iter  3832\t      0.07894864 (Batch Size:   256)\n    Iter  3833\t      0.07244612 (Batch Size:   256)\n    Iter  3834\t      0.07673951 (Batch Size:   256)\n    Iter  3835\t      0.07468048 (Batch Size:   256)\n    Iter  3836\t      0.07748374 (Batch Size:   256)\n    Iter  3837\t      0.07020082 (Batch Size:   256)\n    Iter  3838\t      0.07337338 (Batch Size:   256)\n    Iter  3839\t      0.07548636 (Batch Size:   256)\n    Iter  3840\t      0.07485716 (Batch Size:   256)\n    Iter  3841\t      0.07064118 (Batch Size:   256)\n    Iter  3842\t      0.07265611 (Batch Size:   256)\n    Iter  3843\t      0.07038030 (Batch Size:   256)\n    Iter  3844\t      0.07213650 (Batch Size:   256)\n    Iter  3845\t      0.07248635 (Batch Size:   256)\n    Iter  3846\t      0.07460287 (Batch Size:   256)\n    Iter  3847\t      0.07631463 (Batch Size:   256)\n    Iter  3848\t      0.07770759 (Batch Size:   256)\n    Iter  3849\t      0.07189214 (Batch Size:   256)\n    Iter  3850\t      0.07583841 (Batch Size:   256)\n    Iter  3851\t      0.07688268 (Batch Size:   256)\n    Iter  3852\t      0.07453225 (Batch Size:   256)\n    Iter  3853\t      0.07688425 (Batch Size:   256)\n    Iter  3854\t      0.07540016 (Batch Size:   256)\n    Iter  3855\t      0.07592498 (Batch Size:   256)\n    Iter  3856\t      0.07717652 (Batch Size:   256)\n    Iter  3857\t      0.07267528 (Batch Size:   256)\n    Iter  3858\t      0.09319900 (Batch Size:   256)\n    Iter  3859\t      0.07625052 (Batch Size:   256)\n    Iter  3860\t      0.08000167 (Batch Size:   256)\n    Iter  3861\t      0.07526169 (Batch Size:   256)\n    Iter  3862\t      0.07219175 (Batch Size:   256)\n    Iter  3863\t      0.07211975 (Batch Size:   256)\n    Iter  3864\t      0.08142920 (Batch Size:   256)\n    Iter  3865\t      0.08849885 (Batch Size:   256)\n    Iter  3866\t      0.08612454 (Batch Size:   256)\n    Iter  3867\t      0.07923889 (Batch Size:   256)\n    Iter  3868\t      0.07664750 (Batch Size:   256)\n    Iter  3869\t      0.07251106 (Batch Size:   256)\n    Iter  3870\t      0.07033872 (Batch Size:   256)\n    Iter  3871\t      0.07632363 (Batch Size:   256)\n    Iter  3872\t      0.07428133 (Batch Size:   256)\n    Iter  3873\t      0.07227955 (Batch Size:   256)\n    Iter  3874\t      0.08017584 (Batch Size:   256)\n    Iter  3875\t      0.07425274 (Batch Size:   256)\n    Iter  3876\t      0.07511189 (Batch Size:   256)\n    Iter  3877\t      0.07160147 (Batch Size:   256)\n    Iter  3878\t      0.07055036 (Batch Size:   256)\n    Iter  3879\t      0.07294632 (Batch Size:   256)\n    Iter  3880\t      0.07425337 (Batch Size:   256)\n    Iter  3881\t      0.08049593 (Batch Size:   256)\n    Iter  3882\t      0.09132128 (Batch Size:   256)\n    Iter  3883\t      0.08786279 (Batch Size:   256)\n    Iter  3884\t      0.07617318 (Batch Size:   256)\n    Iter  3885\t      0.07099564 (Batch Size:   256)\n    Iter  3886\t      0.07287394 (Batch Size:   256)\n    Iter  3887\t      0.07197227 (Batch Size:   256)\n    Iter  3888\t      0.07550099 (Batch Size:   256)\n    Iter  3889\t      0.07745200 (Batch Size:   256)\n    Iter  3890\t      0.07509464 (Batch Size:   256)\n    Iter  3891\t      0.07515349 (Batch Size:   256)\n    Iter  3892\t      0.08107666 (Batch Size:   256)\n    Iter  3893\t      0.07441985 (Batch Size:   256)\n    Iter  3894\t      0.07398390 (Batch Size:   256)\n    Iter  3895\t      0.06915530 (Batch Size:   256)\n    Iter  3896\t      0.07384227 (Batch Size:   256)\n    Iter  3897\t      0.07057975 (Batch Size:   256)\n    Iter  3898\t      0.07817026 (Batch Size:   256)\n    Iter  3899\t      0.07766280 (Batch Size:   256)\n    Iter  3900\t      0.07675205 (Batch Size:   256)\n    Iter  3901\t      0.07508595 (Batch Size:   256)\n    Iter  3902\t      0.07318393 (Batch Size:   256)\n    Iter  3903\t      0.07344729 (Batch Size:   256)\n    Iter  3904\t      0.07875438 (Batch Size:   256)\n    Iter  3905\t      0.07594572 (Batch Size:   256)\n    Iter  3906\t      0.07176309 (Batch Size:   256)\n    Iter  3907\t      0.07294308 (Batch Size:   256)\n    Iter  3908\t      0.07249770 (Batch Size:   256)\n    Iter  3909\t      0.07501715 (Batch Size:   256)\n    Iter  3910\t      0.06927424 (Batch Size:   256)\n    Iter  3911\t      0.07441534 (Batch Size:   256)\n    Iter  3912\t      0.07339391 (Batch Size:   256)\n    Iter  3913\t      0.08062497 (Batch Size:   256)\n    Iter  3914\t      0.08526551 (Batch Size:   256)\n    Iter  3915\t      0.07440810 (Batch Size:   256)\n    Iter  3916\t      0.07593332 (Batch Size:   256)\n    Iter  3917\t      0.07521764 (Batch Size:   256)\n    Iter  3918\t      0.08017728 (Batch Size:   256)\n    Iter  3919\t      0.08305472 (Batch Size:   256)\n    Iter  3920\t      0.07532532 (Batch Size:   256)\n    Iter  3921\t      0.07586513 (Batch Size:   256)\n    Iter  3922\t      0.07043469 (Batch Size:   256)\n    Iter  3923\t      0.07578319 (Batch Size:   256)\n    Iter  3924\t      0.07507312 (Batch Size:   256)\n    Iter  3925\t      0.07749209 (Batch Size:   256)\n    Iter  3926\t      0.08699949 (Batch Size:   256)\n    Iter  3927\t      0.07264153 (Batch Size:   256)\n    Iter  3928\t      0.06985650 (Batch Size:   256)\n    Iter  3929\t      0.06994469 (Batch Size:   256)\n    Iter  3930\t      0.08516347 (Batch Size:   256)\n    Iter  3931\t      0.08299849 (Batch Size:   256)\n    Iter  3932\t      0.08233681 (Batch Size:   256)\n    Iter  3933\t      0.07904648 (Batch Size:   256)\n    Iter  3934\t      0.07087662 (Batch Size:   256)\n    Iter  3935\t      0.08284094 (Batch Size:   256)\n    Iter  3936\t      0.07321702 (Batch Size:   256)\n    Iter  3937\t      0.07855451 (Batch Size:   256)\n    Iter  3938\t      0.07174654 (Batch Size:   256)\n    Iter  3939\t      0.07651054 (Batch Size:   256)\n    Iter  3940\t      0.07197334 (Batch Size:   256)\n    Iter  3941\t      0.08011099 (Batch Size:   256)\n    Iter  3942\t      0.08361725 (Batch Size:   256)\n    Iter  3943\t      0.06903789 (Batch Size:   256)\n    Iter  3944\t      0.07506086 (Batch Size:   256)\n    Iter  3945\t      0.07876292 (Batch Size:   256)\n    Iter  3946\t      0.07491853 (Batch Size:   256)\n    Iter  3947\t      0.08156098 (Batch Size:   256)\n    Iter  3948\t      0.07623022 (Batch Size:   256)\n    Iter  3949\t      0.07360338 (Batch Size:   256)\n    Iter  3950\t      0.07395668 (Batch Size:   256)\n    Iter  3951\t      0.07586881 (Batch Size:   256)\n    Iter  3952\t      0.08083248 (Batch Size:   256)\n    Iter  3953\t      0.07277746 (Batch Size:   256)\n    Iter  3954\t      0.07351052 (Batch Size:   256)\n    Iter  3955\t      0.07009883 (Batch Size:   256)\n    Iter  3956\t      0.07016523 (Batch Size:   256)\n    Iter  3957\t      0.07308403 (Batch Size:   256)\n    Iter  3958\t      0.07221674 (Batch Size:   256)\n    Iter  3959\t      0.07099232 (Batch Size:   256)\n    Iter  3960\t      0.07332904 (Batch Size:   256)\n    Iter  3961\t      0.07246774 (Batch Size:   256)\n    Iter  3962\t      0.08166278 (Batch Size:   256)\n    Iter  3963\t      0.08421444 (Batch Size:   256)\n    Iter  3964\t      0.07765546 (Batch Size:   256)\n    Iter  3965\t      0.07248333 (Batch Size:   256)\n    Iter  3966\t      0.07445436 (Batch Size:   256)\n    Iter  3967\t      0.07757038 (Batch Size:   256)\n    Iter  3968\t      0.07090589 (Batch Size:   256)\n    Iter  3969\t      0.06962450 (Batch Size:   256)\n    Iter  3970\t      0.08180201 (Batch Size:   256)\n    Iter  3971\t      0.07258768 (Batch Size:   256)\n    Iter  3972\t      0.07285868 (Batch Size:   256)\n    Iter  3973\t      0.07567195 (Batch Size:   256)\n    Iter  3974\t      0.07119814 (Batch Size:   256)\n    Iter  3975\t      0.07040446 (Batch Size:   256)\n    Iter  3976\t      0.07105711 (Batch Size:   256)\n    Iter  3977\t      0.07269222 (Batch Size:   256)\n    Iter  3978\t      0.07431590 (Batch Size:   256)\n    Iter  3979\t      0.07517763 (Batch Size:   256)\n    Iter  3980\t      0.07747141 (Batch Size:   256)\n    Iter  3981\t      0.07192105 (Batch Size:   256)\n    Iter  3982\t      0.07043960 (Batch Size:   256)\n    Iter  3983\t      0.07156806 (Batch Size:   256)\n    Iter  3984\t      0.07511932 (Batch Size:   256)\n    Iter  3985\t      0.07617469 (Batch Size:   256)\n    Iter  3986\t      0.07255289 (Batch Size:   256)\n    Iter  3987\t      0.07182381 (Batch Size:   256)\n    Iter  3988\t      0.07695042 (Batch Size:   256)\n    Iter  3989\t      0.07540696 (Batch Size:   256)\n    Iter  3990\t      0.07195856 (Batch Size:   256)\n    Iter  3991\t      0.07359460 (Batch Size:   256)\n    Iter  3992\t      0.07506438 (Batch Size:   256)\n    Iter  3993\t      0.07698130 (Batch Size:   256)\n    Iter  3994\t      0.07730372 (Batch Size:   256)\n    Iter  3995\t      0.07273189 (Batch Size:   256)\n    Iter  3996\t      0.07279081 (Batch Size:   256)\n    Iter  3997\t      0.07206795 (Batch Size:   256)\n    Iter  3998\t      0.07389158 (Batch Size:   256)\n    Iter  3999\t      0.07721003 (Batch Size:   256)\n    Iter  4000\t      0.07169842 (Batch Size:   256)\n    Iter  4001\t      0.07018292 (Batch Size:   256)\n    Iter  4002\t      0.06979640 (Batch Size:   256)\n    Iter  4003\t      0.07510301 (Batch Size:   256)\n    Iter  4004\t      0.07146495 (Batch Size:   256)\n    Iter  4005\t      0.07214866 (Batch Size:   256)\n    Iter  4006\t      0.07439191 (Batch Size:   256)\n    Iter  4007\t      0.07389665 (Batch Size:   256)\n    Iter  4008\t      0.07306150 (Batch Size:   256)\n    Iter  4009\t      0.07025009 (Batch Size:   256)\n    Iter  4010\t      0.06932754 (Batch Size:   256)\n    Iter  4011\t      0.07592326 (Batch Size:   256)\n    Iter  4012\t      0.07143411 (Batch Size:   256)\n    Iter  4013\t      0.07313352 (Batch Size:   256)\n    Iter  4014\t      0.09069370 (Batch Size:   256)\n    Iter  4015\t      0.07748827 (Batch Size:   256)\n    Iter  4016\t      0.07093043 (Batch Size:   256)\n    Iter  4017\t      0.07095033 (Batch Size:   256)\n    Iter  4018\t      0.07019575 (Batch Size:   256)\n    Iter  4019\t      0.06998514 (Batch Size:   256)\n    Iter  4020\t      0.07125886 (Batch Size:   256)\n    Iter  4021\t      0.07532226 (Batch Size:   256)\n    Iter  4022\t      0.07569399 (Batch Size:   256)\n    Iter  4023\t      0.07911561 (Batch Size:   256)\n    Iter  4024\t      0.07182319 (Batch Size:   256)\n    Iter  4025\t      0.07110801 (Batch Size:   256)\n    Iter  4026\t      0.07406142 (Batch Size:   256)\n    Iter  4027\t      0.07726428 (Batch Size:   256)\n    Iter  4028\t      0.08338084 (Batch Size:   256)\n    Iter  4029\t      0.07669603 (Batch Size:   256)\n    Iter  4030\t      0.07149766 (Batch Size:   256)\n    Iter  4031\t      0.07502807 (Batch Size:   256)\n    Iter  4032\t      0.07145410 (Batch Size:   256)\n    Iter  4033\t      0.08660388 (Batch Size:   256)\n    Iter  4034\t      0.10005198 (Batch Size:   256)\n    Iter  4035\t      0.07776781 (Batch Size:   256)\n    Iter  4036\t      0.07275764 (Batch Size:   256)\n    Iter  4037\t      0.07395119 (Batch Size:   256)\n    Iter  4038\t      0.07494514 (Batch Size:   256)\n    Iter  4039\t      0.07034479 (Batch Size:   256)\n    Iter  4040\t      0.07134235 (Batch Size:   256)\n    Iter  4041\t      0.07237171 (Batch Size:   256)\n    Iter  4042\t      0.07690284 (Batch Size:   256)\n    Iter  4043\t      0.07924922 (Batch Size:   256)\n    Iter  4044\t      0.08301394 (Batch Size:   256)\n    Iter  4045\t      0.08264643 (Batch Size:   256)\n    Iter  4046\t      0.08020310 (Batch Size:   256)\n    Iter  4047\t      0.07028419 (Batch Size:   256)\n    Iter  4048\t      0.07424308 (Batch Size:   256)\n    Iter  4049\t      0.07436504 (Batch Size:   256)\n    Iter  4050\t      0.09328922 (Batch Size:   256)\n    Iter  4051\t      0.07889866 (Batch Size:   256)\n    Iter  4052\t      0.06914119 (Batch Size:   256)\n    Iter  4053\t      0.06872905 (Batch Size:   256)\n    Iter  4054\t      0.06966664 (Batch Size:   256)\n    Iter  4055\t      0.07085377 (Batch Size:   256)\n    Iter  4056\t      0.07524922 (Batch Size:   256)\n    Iter  4057\t      0.07292655 (Batch Size:   256)\n    Iter  4058\t      0.08053465 (Batch Size:   256)\n    Iter  4059\t      0.07882031 (Batch Size:   256)\n    Iter  4060\t      0.07540587 (Batch Size:   256)\n    Iter  4061\t      0.08098475 (Batch Size:   256)\n    Iter  4062\t      0.06910985 (Batch Size:   256)\n    Iter  4063\t      0.07310285 (Batch Size:   256)\n    Iter  4064\t      0.07060964 (Batch Size:   256)\n    Iter  4065\t      0.07658691 (Batch Size:   256)\n    Iter  4066\t      0.07201791 (Batch Size:   256)\n    Iter  4067\t      0.07227474 (Batch Size:   256)\n    Iter  4068\t      0.07622118 (Batch Size:   256)\n    Iter  4069\t      0.07070512 (Batch Size:   256)\n    Iter  4070\t      0.07886638 (Batch Size:   256)\n    Iter  4071\t      0.07324646 (Batch Size:   256)\n    Iter  4072\t      0.07423730 (Batch Size:   256)\n    Iter  4073\t      0.06701107 (Batch Size:   256)\n    Iter  4074\t      0.07630365 (Batch Size:   256)\n    Iter  4075\t      0.07721222 (Batch Size:   256)\n    Iter  4076\t      0.07811864 (Batch Size:   256)\n    Iter  4077\t      0.07675026 (Batch Size:   256)\n    Iter  4078\t      0.07087286 (Batch Size:   256)\n    Iter  4079\t      0.08331875 (Batch Size:   256)\n    Iter  4080\t      0.07407669 (Batch Size:   256)\n    Iter  4081\t      0.07871111 (Batch Size:   256)\n    Iter  4082\t      0.07003968 (Batch Size:   256)\n    Iter  4083\t      0.07437655 (Batch Size:   256)\n    Iter  4084\t      0.07378786 (Batch Size:   256)\n    Iter  4085\t      0.07277718 (Batch Size:   256)\n    Iter  4086\t      0.07858812 (Batch Size:   256)\n    Iter  4087\t      0.07836907 (Batch Size:   256)\n    Iter  4088\t      0.07407880 (Batch Size:   256)\n    Iter  4089\t      0.07285037 (Batch Size:   256)\n    Iter  4090\t      0.06903422 (Batch Size:   256)\n    Iter  4091\t      0.07288245 (Batch Size:   256)\n    Iter  4092\t      0.07018927 (Batch Size:   256)\n    Iter  4093\t      0.07256609 (Batch Size:   256)\n    Iter  4094\t      0.07141208 (Batch Size:   256)\n    Iter  4095\t      0.07031408 (Batch Size:   256)\n    Iter  4096\t      0.07276538 (Batch Size:   256)\n    Iter  4097\t      0.07551436 (Batch Size:   256)\n    Iter  4098\t      0.07339810 (Batch Size:   256)\n    Iter  4099\t      0.06801394 (Batch Size:   256)\n    Iter  4100\t      0.07129150 (Batch Size:   256)\n    Iter  4101\t      0.07197279 (Batch Size:   256)\n    Iter  4102\t      0.07204939 (Batch Size:   256)\n    Iter  4103\t      0.06985764 (Batch Size:   256)\n    Iter  4104\t      0.07897615 (Batch Size:   256)\n    Iter  4105\t      0.08470605 (Batch Size:   256)\n    Iter  4106\t      0.07361336 (Batch Size:   256)\n    Iter  4107\t      0.07046496 (Batch Size:   256)\n    Iter  4108\t      0.07393690 (Batch Size:   256)\n    Iter  4109\t      0.07927811 (Batch Size:   256)\n    Iter  4110\t      0.07398658 (Batch Size:   256)\n    Iter  4111\t      0.07487168 (Batch Size:   256)\n    Iter  4112\t      0.07881905 (Batch Size:   256)\n    Iter  4113\t      0.07132526 (Batch Size:   256)\n    Iter  4114\t      0.07306631 (Batch Size:   256)\n    Iter  4115\t      0.07403842 (Batch Size:   256)\n    Iter  4116\t      0.07296341 (Batch Size:   256)\n    Iter  4117\t      0.06880671 (Batch Size:   256)\n    Iter  4118\t      0.07059514 (Batch Size:   256)\n    Iter  4119\t      0.07526857 (Batch Size:   256)\n    Iter  4120\t      0.07081291 (Batch Size:   256)\n    Iter  4121\t      0.07087908 (Batch Size:   256)\n    Iter  4122\t      0.07081135 (Batch Size:   256)\n    Iter  4123\t      0.06978408 (Batch Size:   256)\n    Iter  4124\t      0.07364611 (Batch Size:   256)\n    Iter  4125\t      0.07134113 (Batch Size:   256)\n    Iter  4126\t      0.06975713 (Batch Size:   256)\n    Iter  4127\t      0.07787506 (Batch Size:   256)\n    Iter  4128\t      0.07923609 (Batch Size:   256)\n    Iter  4129\t      0.07108535 (Batch Size:   256)\n    Iter  4130\t      0.07343802 (Batch Size:   256)\n    Iter  4131\t      0.07529534 (Batch Size:   256)\n    Iter  4132\t      0.07280291 (Batch Size:   256)\n    Iter  4133\t      0.06916741 (Batch Size:   256)\n    Iter  4134\t      0.08032647 (Batch Size:   256)\n    Iter  4135\t      0.08067990 (Batch Size:   256)\n    Iter  4136\t      0.07343989 (Batch Size:   256)\n    Iter  4137\t      0.07380533 (Batch Size:   256)\n    Iter  4138\t      0.07273469 (Batch Size:   256)\n    Iter  4139\t      0.07160412 (Batch Size:   256)\n    Iter  4140\t      0.07222223 (Batch Size:   256)\n    Iter  4141\t      0.07759599 (Batch Size:   256)\n    Iter  4142\t      0.08669431 (Batch Size:   256)\n    Iter  4143\t      0.07802747 (Batch Size:   256)\n    Iter  4144\t      0.07461629 (Batch Size:   256)\n    Iter  4145\t      0.07642435 (Batch Size:   256)\n    Iter  4146\t      0.08265375 (Batch Size:   256)\n    Iter  4147\t      0.07026661 (Batch Size:   256)\n    Iter  4148\t      0.07221146 (Batch Size:   256)\n    Iter  4149\t      0.07350706 (Batch Size:   256)\n    Iter  4150\t      0.06718472 (Batch Size:   256)\n    Iter  4151\t      0.08322370 (Batch Size:   256)\n    Iter  4152\t      0.08014587 (Batch Size:   256)\n    Iter  4153\t      0.07380275 (Batch Size:   256)\n    Iter  4154\t      0.07930508 (Batch Size:   256)\n    Iter  4155\t      0.07476555 (Batch Size:   256)\n    Iter  4156\t      0.07387476 (Batch Size:   256)\n    Iter  4157\t      0.08155111 (Batch Size:   256)\n    Iter  4158\t      0.07843162 (Batch Size:   256)\n    Iter  4159\t      0.07579318 (Batch Size:   256)\n    Iter  4160\t      0.07666106 (Batch Size:   256)\n    Iter  4161\t      0.06913672 (Batch Size:   256)\n    Iter  4162\t      0.07489637 (Batch Size:   256)\n    Iter  4163\t      0.09335646 (Batch Size:   256)\n    Iter  4164\t      0.08272635 (Batch Size:   256)\n    Iter  4165\t      0.07289701 (Batch Size:   256)\n    Iter  4166\t      0.07418836 (Batch Size:   256)\n    Iter  4167\t      0.07692190 (Batch Size:   256)\n    Iter  4168\t      0.07180043 (Batch Size:   256)\n    Iter  4169\t      0.06940182 (Batch Size:   256)\n    Iter  4170\t      0.07995421 (Batch Size:   256)\n    Iter  4171\t      0.08583232 (Batch Size:   256)\n    Iter  4172\t      0.07453646 (Batch Size:   256)\n    Iter  4173\t      0.07267386 (Batch Size:   256)\n    Iter  4174\t      0.07386306 (Batch Size:   256)\n    Iter  4175\t      0.07378467 (Batch Size:   256)\n    Iter  4176\t      0.07665920 (Batch Size:   256)\n    Iter  4177\t      0.06885232 (Batch Size:   256)\n    Iter  4178\t      0.07314155 (Batch Size:   256)\n    Iter  4179\t      0.06826634 (Batch Size:   256)\n    Iter  4180\t      0.07471544 (Batch Size:   256)\n    Iter  4181\t      0.08187397 (Batch Size:   256)\n    Iter  4182\t      0.07899066 (Batch Size:   256)\n    Iter  4183\t      0.07124442 (Batch Size:   256)\n    Iter  4184\t      0.07396539 (Batch Size:   256)\n    Iter  4185\t      0.07290603 (Batch Size:   256)\n    Iter  4186\t      0.07121501 (Batch Size:   256)\n    Iter  4187\t      0.07115710 (Batch Size:   256)\n    Iter  4188\t      0.07664461 (Batch Size:   256)\n    Iter  4189\t      0.06947019 (Batch Size:   256)\n    Iter  4190\t      0.07187621 (Batch Size:   256)\n    Iter  4191\t      0.07420503 (Batch Size:   256)\n    Iter  4192\t      0.08144553 (Batch Size:   256)\n    Iter  4193\t      0.07373954 (Batch Size:   256)\n    Iter  4194\t      0.07484972 (Batch Size:   256)\n    Iter  4195\t      0.07368397 (Batch Size:   256)\n    Iter  4196\t      0.07371335 (Batch Size:   256)\n    Iter  4197\t      0.06902005 (Batch Size:   256)\n    Iter  4198\t      0.07697026 (Batch Size:   256)\n    Iter  4199\t      0.07232682 (Batch Size:   256)\n    Iter  4200\t      0.07148925 (Batch Size:   256)\n    Iter  4201\t      0.07415258 (Batch Size:   256)\n    Iter  4202\t      0.07357303 (Batch Size:   256)\n    Iter  4203\t      0.07298909 (Batch Size:   256)\n    Iter  4204\t      0.07061719 (Batch Size:   256)\n    Iter  4205\t      0.07716787 (Batch Size:   256)\n    Iter  4206\t      0.08230774 (Batch Size:   256)\n    Iter  4207\t      0.07835120 (Batch Size:   256)\n    Iter  4208\t      0.06979120 (Batch Size:   256)\n    Iter  4209\t      0.07404550 (Batch Size:   256)\n    Iter  4210\t      0.08243869 (Batch Size:   256)\n    Iter  4211\t      0.07499411 (Batch Size:   256)\n    Iter  4212\t      0.07384917 (Batch Size:   256)\n    Iter  4213\t      0.07344959 (Batch Size:   256)\n    Iter  4214\t      0.07006926 (Batch Size:   256)\n    Iter  4215\t      0.07537775 (Batch Size:   256)\n    Iter  4216\t      0.08048451 (Batch Size:   256)\n    Iter  4217\t      0.07798929 (Batch Size:   256)\n    Iter  4218\t      0.07790033 (Batch Size:   256)\n    Iter  4219\t      0.08428994 (Batch Size:   256)\n    Iter  4220\t      0.07648851 (Batch Size:   256)\n    Iter  4221\t      0.07014422 (Batch Size:   256)\n    Iter  4222\t      0.07011634 (Batch Size:   256)\n    Iter  4223\t      0.07375301 (Batch Size:   256)\n    Iter  4224\t      0.07357258 (Batch Size:   256)\n    Iter  4225\t      0.07357153 (Batch Size:   256)\n    Iter  4226\t      0.07802045 (Batch Size:   256)\n    Iter  4227\t      0.07508572 (Batch Size:   256)\n    Iter  4228\t      0.08151499 (Batch Size:   256)\n    Iter  4229\t      0.07275837 (Batch Size:   256)\n    Iter  4230\t      0.07067082 (Batch Size:   256)\n    Iter  4231\t      0.07493086 (Batch Size:   256)\n    Iter  4232\t      0.07231478 (Batch Size:   256)\n    Iter  4233\t      0.07225064 (Batch Size:   256)\n    Iter  4234\t      0.07078947 (Batch Size:   256)\n    Iter  4235\t      0.07618429 (Batch Size:   256)\n    Iter  4236\t      0.07080960 (Batch Size:   256)\n    Iter  4237\t      0.07369639 (Batch Size:   256)\n    Iter  4238\t      0.07393731 (Batch Size:   256)\n    Iter  4239\t      0.07482019 (Batch Size:   256)\n    Iter  4240\t      0.07571019 (Batch Size:   256)\n    Iter  4241\t      0.07269126 (Batch Size:   256)\n    Iter  4242\t      0.07215812 (Batch Size:   256)\n    Iter  4243\t      0.07115949 (Batch Size:   256)\n    Iter  4244\t      0.06927736 (Batch Size:   256)\n    Iter  4245\t      0.07219654 (Batch Size:   256)\n    Iter  4246\t      0.07553698 (Batch Size:   256)\n    Iter  4247\t      0.07614425 (Batch Size:   256)\n    Iter  4248\t      0.07344723 (Batch Size:   256)\n    Iter  4249\t      0.08201252 (Batch Size:   256)\n    Iter  4250\t      0.07587679 (Batch Size:   256)\n    Iter  4251\t      0.06903914 (Batch Size:   256)\n    Iter  4252\t      0.06973285 (Batch Size:   256)\n    Iter  4253\t      0.07732545 (Batch Size:   256)\n    Iter  4254\t      0.07937701 (Batch Size:   256)\n    Iter  4255\t      0.07636783 (Batch Size:   256)\n    Iter  4256\t      0.07130787 (Batch Size:   256)\n    Iter  4257\t      0.07137802 (Batch Size:   256)\n    Iter  4258\t      0.06821821 (Batch Size:   256)\n    Iter  4259\t      0.07514253 (Batch Size:   256)\n    Iter  4260\t      0.07988493 (Batch Size:   256)\n    Iter  4261\t      0.09299095 (Batch Size:   256)\n    Iter  4262\t      0.08719438 (Batch Size:   256)\n    Iter  4263\t      0.07383089 (Batch Size:   256)\n    Iter  4264\t      0.07197834 (Batch Size:   256)\n    Iter  4265\t      0.07783839 (Batch Size:   256)\n    Iter  4266\t      0.07738122 (Batch Size:   256)\n    Iter  4267\t      0.06897328 (Batch Size:   256)\n    Iter  4268\t      0.07274880 (Batch Size:   256)\n    Iter  4269\t      0.06899697 (Batch Size:   256)\n    Iter  4270\t      0.06815160 (Batch Size:   256)\n    Iter  4271\t      0.07394878 (Batch Size:   256)\n    Iter  4272\t      0.08155018 (Batch Size:   256)\n    Iter  4273\t      0.07933995 (Batch Size:   256)\n    Iter  4274\t      0.08110448 (Batch Size:   256)\n    Iter  4275\t      0.07852585 (Batch Size:   256)\n    Iter  4276\t      0.07453467 (Batch Size:   256)\n    Iter  4277\t      0.07372934 (Batch Size:   256)\n    Iter  4278\t      0.07034279 (Batch Size:   256)\n    Iter  4279\t      0.07456903 (Batch Size:   256)\n    Iter  4280\t      0.07312764 (Batch Size:   256)\n    Iter  4281\t      0.07265341 (Batch Size:   256)\n    Iter  4282\t      0.07600607 (Batch Size:   256)\n    Iter  4283\t      0.07112178 (Batch Size:   256)\n    Iter  4284\t      0.07303724 (Batch Size:   256)\n    Iter  4285\t      0.07254467 (Batch Size:   256)\n    Iter  4286\t      0.07338841 (Batch Size:   256)\n    Iter  4287\t      0.07028147 (Batch Size:   256)\n    Iter  4288\t      0.07468139 (Batch Size:   256)\n    Iter  4289\t      0.08085735 (Batch Size:   256)\n    Iter  4290\t      0.09246649 (Batch Size:   256)\n    Iter  4291\t      0.07720422 (Batch Size:   256)\n    Iter  4292\t      0.07317973 (Batch Size:   256)\n    Iter  4293\t      0.07297695 (Batch Size:   256)\n    Iter  4294\t      0.06881819 (Batch Size:   256)\n    Iter  4295\t      0.07695181 (Batch Size:   256)\n    Iter  4296\t      0.08099505 (Batch Size:   256)\n    Iter  4297\t      0.07665806 (Batch Size:   256)\n    Iter  4298\t      0.07225316 (Batch Size:   256)\n    Iter  4299\t      0.07073974 (Batch Size:   256)\n    Iter  4300\t      0.07540456 (Batch Size:   256)\n    Iter  4301\t      0.06995833 (Batch Size:   256)\n    Iter  4302\t      0.06443510 (Batch Size:   256)\n    Iter  4303\t      0.07347896 (Batch Size:   256)\n    Iter  4304\t      0.07141363 (Batch Size:   256)\n    Iter  4305\t      0.07508466 (Batch Size:   256)\n    Iter  4306\t      0.06882159 (Batch Size:   256)\n    Iter  4307\t      0.07982308 (Batch Size:   256)\n    Iter  4308\t      0.09160001 (Batch Size:   256)\n    Iter  4309\t      0.08009578 (Batch Size:   256)\n    Iter  4310\t      0.07230838 (Batch Size:   256)\n    Iter  4311\t      0.07643342 (Batch Size:   256)\n    Iter  4312\t      0.07068072 (Batch Size:   256)\n    Iter  4313\t      0.07120745 (Batch Size:   256)\n    Iter  4314\t      0.07522098 (Batch Size:   256)\n    Iter  4315\t      0.07589196 (Batch Size:   256)\n    Iter  4316\t      0.08895702 (Batch Size:   256)\n    Iter  4317\t      0.07770130 (Batch Size:   256)\n    Iter  4318\t      0.07629630 (Batch Size:   256)\n    Iter  4319\t      0.07281074 (Batch Size:   256)\n    Iter  4320\t      0.07837797 (Batch Size:   256)\n    Iter  4321\t      0.08086933 (Batch Size:   256)\n    Iter  4322\t      0.07477698 (Batch Size:   256)\n    Iter  4323\t      0.07589332 (Batch Size:   256)\n    Iter  4324\t      0.07660065 (Batch Size:   256)\n    Iter  4325\t      0.07323675 (Batch Size:   256)\n    Iter  4326\t      0.07383580 (Batch Size:   256)\n    Iter  4327\t      0.07941050 (Batch Size:   256)\n    Iter  4328\t      0.08650450 (Batch Size:   256)\n    Iter  4329\t      0.08189409 (Batch Size:   256)\n    Iter  4330\t      0.09679941 (Batch Size:   256)\n    Iter  4331\t      0.08214353 (Batch Size:   256)\n    Iter  4332\t      0.08855468 (Batch Size:   256)\n    Iter  4333\t      0.08878999 (Batch Size:   256)\n    Iter  4334\t      0.07823219 (Batch Size:   256)\n    Iter  4335\t      0.06934097 (Batch Size:   256)\n    Iter  4336\t      0.07365226 (Batch Size:   256)\n    Iter  4337\t      0.07301263 (Batch Size:   256)\n    Iter  4338\t      0.07379275 (Batch Size:   256)\n    Iter  4339\t      0.06967475 (Batch Size:   256)\n    Iter  4340\t      0.08606450 (Batch Size:   256)\n    Iter  4341\t      0.07519956 (Batch Size:   256)\n    Iter  4342\t      0.07229637 (Batch Size:   256)\n    Iter  4343\t      0.07004180 (Batch Size:   256)\n    Iter  4344\t      0.06948238 (Batch Size:   256)\n    Iter  4345\t      0.07333106 (Batch Size:   256)\n    Iter  4346\t      0.07220089 (Batch Size:   256)\n    Iter  4347\t      0.07491477 (Batch Size:   256)\n    Iter  4348\t      0.07246212 (Batch Size:   256)\n    Iter  4349\t      0.07420014 (Batch Size:   256)\n    Iter  4350\t      0.07419938 (Batch Size:   256)\n    Iter  4351\t      0.06971888 (Batch Size:   256)\n    Iter  4352\t      0.07173083 (Batch Size:   256)\n    Iter  4353\t      0.06804527 (Batch Size:   256)\n    Iter  4354\t      0.07729483 (Batch Size:   256)\n    Iter  4355\t      0.07350797 (Batch Size:   256)\n    Iter  4356\t      0.07487329 (Batch Size:   256)\n    Iter  4357\t      0.07087609 (Batch Size:   256)\n    Iter  4358\t      0.07801414 (Batch Size:   256)\n    Iter  4359\t      0.07245449 (Batch Size:   256)\n    Iter  4360\t      0.07305141 (Batch Size:   256)\n    Iter  4361\t      0.07433098 (Batch Size:   256)\n    Iter  4362\t      0.07854699 (Batch Size:   256)\n    Iter  4363\t      0.07180899 (Batch Size:   256)\n    Iter  4364\t      0.08223757 (Batch Size:   256)\n    Iter  4365\t      0.07702048 (Batch Size:   256)\n    Iter  4366\t      0.06788653 (Batch Size:   256)\n    Iter  4367\t      0.06950828 (Batch Size:   256)\n    Iter  4368\t      0.07723422 (Batch Size:   256)\n    Iter  4369\t      0.07091511 (Batch Size:   256)\n    Iter  4370\t      0.07182129 (Batch Size:   256)\n    Iter  4371\t      0.07339853 (Batch Size:   256)\n    Iter  4372\t      0.08284329 (Batch Size:   256)\n    Iter  4373\t      0.08367102 (Batch Size:   256)\n    Iter  4374\t      0.07327252 (Batch Size:   256)\n    Iter  4375\t      0.07123240 (Batch Size:   256)\n    Iter  4376\t      0.07056030 (Batch Size:   256)\n    Iter  4377\t      0.07304231 (Batch Size:   256)\n    Iter  4378\t      0.07246777 (Batch Size:   256)\n    Iter  4379\t      0.06942841 (Batch Size:   256)\n    Iter  4380\t      0.07145087 (Batch Size:   256)\n    Iter  4381\t      0.07351767 (Batch Size:   256)\n    Iter  4382\t      0.07869390 (Batch Size:   256)\n    Iter  4383\t      0.08205038 (Batch Size:   256)\n    Iter  4384\t      0.07388294 (Batch Size:   256)\n    Iter  4385\t      0.06897347 (Batch Size:   256)\n    Iter  4386\t      0.07618819 (Batch Size:   256)\n    Iter  4387\t      0.07371817 (Batch Size:   256)\n    Iter  4388\t      0.07353892 (Batch Size:   256)\n    Iter  4389\t      0.06993553 (Batch Size:   256)\n    Iter  4390\t      0.07133237 (Batch Size:   256)\n    Iter  4391\t      0.06826441 (Batch Size:   256)\n    Iter  4392\t      0.07918964 (Batch Size:   256)\n    Iter  4393\t      0.07024971 (Batch Size:   256)\n    Iter  4394\t      0.07013706 (Batch Size:   256)\n    Iter  4395\t      0.06997132 (Batch Size:   256)\n    Iter  4396\t      0.07279498 (Batch Size:   256)\n    Iter  4397\t      0.08520748 (Batch Size:   256)\n    Iter  4398\t      0.08295559 (Batch Size:   256)\n    Iter  4399\t      0.07966838 (Batch Size:   256)\n    Iter  4400\t      0.07735587 (Batch Size:   256)\n    Iter  4401\t      0.07749862 (Batch Size:   256)\n    Iter  4402\t      0.07254850 (Batch Size:   256)\n    Iter  4403\t      0.08119056 (Batch Size:   256)\n    Iter  4404\t      0.07686115 (Batch Size:   256)\n    Iter  4405\t      0.07702523 (Batch Size:   256)\n    Iter  4406\t      0.07284418 (Batch Size:   256)\n    Iter  4407\t      0.07385542 (Batch Size:   256)\n    Iter  4408\t      0.07009726 (Batch Size:   256)\n    Iter  4409\t      0.07199204 (Batch Size:   256)\n    Iter  4410\t      0.07143988 (Batch Size:   256)\n    Iter  4411\t      0.07016891 (Batch Size:   256)\n    Iter  4412\t      0.07193424 (Batch Size:   256)\n    Iter  4413\t      0.08206661 (Batch Size:   256)\n    Iter  4414\t      0.07456185 (Batch Size:   256)\n    Iter  4415\t      0.07329644 (Batch Size:   256)\n    Iter  4416\t      0.07154599 (Batch Size:   256)\n    Iter  4417\t      0.07109600 (Batch Size:   256)\n    Iter  4418\t      0.08534290 (Batch Size:   256)\n    Iter  4419\t      0.07571860 (Batch Size:   256)\n    Iter  4420\t      0.07890954 (Batch Size:   256)\n    Iter  4421\t      0.07121471 (Batch Size:   256)\n    Iter  4422\t      0.07810005 (Batch Size:   256)\n    Iter  4423\t      0.07931045 (Batch Size:   256)\n    Iter  4424\t      0.08146081 (Batch Size:   256)\n    Iter  4425\t      0.09060606 (Batch Size:   256)\n    Iter  4426\t      0.07618650 (Batch Size:   256)\n    Iter  4427\t      0.07341558 (Batch Size:   256)\n    Iter  4428\t      0.07362676 (Batch Size:   256)\n    Iter  4429\t      0.07533651 (Batch Size:   256)\n    Iter  4430\t      0.07620642 (Batch Size:   256)\n    Iter  4431\t      0.07286368 (Batch Size:   256)\n    Iter  4432\t      0.07265674 (Batch Size:   256)\n    Iter  4433\t      0.06986429 (Batch Size:   256)\n    Iter  4434\t      0.07027525 (Batch Size:   256)\n    Iter  4435\t      0.07307329 (Batch Size:   256)\n    Iter  4436\t      0.07141036 (Batch Size:   256)\n    Iter  4437\t      0.06938658 (Batch Size:   256)\n    Iter  4438\t      0.07458380 (Batch Size:   256)\n    Iter  4439\t      0.08578705 (Batch Size:   256)\n    Iter  4440\t      0.09478121 (Batch Size:   256)\n    Iter  4441\t      0.08282048 (Batch Size:   256)\n    Iter  4442\t      0.07666587 (Batch Size:   256)\n    Iter  4443\t      0.07365036 (Batch Size:   256)\n    Iter  4444\t      0.06906966 (Batch Size:   256)\n    Iter  4445\t      0.07124259 (Batch Size:   256)\n    Iter  4446\t      0.08296270 (Batch Size:   256)\n    Iter  4447\t      0.08076433 (Batch Size:   256)\n    Iter  4448\t      0.07943604 (Batch Size:   256)\n    Iter  4449\t      0.07354077 (Batch Size:   256)\n    Iter  4450\t      0.07220751 (Batch Size:   256)\n    Iter  4451\t      0.07018933 (Batch Size:   256)\n    Iter  4452\t      0.07186665 (Batch Size:   256)\n    Iter  4453\t      0.07471831 (Batch Size:   256)\n    Iter  4454\t      0.07642032 (Batch Size:   256)\n    Iter  4455\t      0.07146768 (Batch Size:   256)\n    Iter  4456\t      0.07158055 (Batch Size:   256)\n    Iter  4457\t      0.08265432 (Batch Size:   256)\n    Iter  4458\t      0.08849541 (Batch Size:   256)\n    Iter  4459\t      0.07855869 (Batch Size:   256)\n    Iter  4460\t      0.07133223 (Batch Size:   256)\n    Iter  4461\t      0.07006755 (Batch Size:   256)\n    Iter  4462\t      0.06690250 (Batch Size:   256)\n    Iter  4463\t      0.07388054 (Batch Size:   256)\n    Iter  4464\t      0.07167391 (Batch Size:   256)\n    Iter  4465\t      0.07107566 (Batch Size:   256)\n    Iter  4466\t      0.08567213 (Batch Size:   256)\n    Iter  4467\t      0.07678952 (Batch Size:   256)\n    Iter  4468\t      0.07681937 (Batch Size:   256)\n    Iter  4469\t      0.06856070 (Batch Size:   256)\n    Iter  4470\t      0.07372880 (Batch Size:   256)\n    Iter  4471\t      0.07191342 (Batch Size:   256)\n    Iter  4472\t      0.06910970 (Batch Size:   256)\n    Iter  4473\t      0.06901185 (Batch Size:   256)\n    Iter  4474\t      0.07350403 (Batch Size:   256)\n    Iter  4475\t      0.07056240 (Batch Size:   256)\n    Iter  4476\t      0.07057915 (Batch Size:   256)\n    Iter  4477\t      0.07016702 (Batch Size:   256)\n    Iter  4478\t      0.06862352 (Batch Size:   256)\n    Iter  4479\t      0.06902635 (Batch Size:   256)\n    Iter  4480\t      0.07097724 (Batch Size:   256)\n    Iter  4481\t      0.07498241 (Batch Size:   256)\n    Iter  4482\t      0.07209000 (Batch Size:   256)\n    Iter  4483\t      0.07557451 (Batch Size:   256)\n    Iter  4484\t      0.07700575 (Batch Size:   256)\n    Iter  4485\t      0.07094626 (Batch Size:   256)\n    Iter  4486\t      0.07343417 (Batch Size:   256)\n    Iter  4487\t      0.08068039 (Batch Size:   256)\n    Iter  4488\t      0.08114026 (Batch Size:   256)\n    Iter  4489\t      0.07357707 (Batch Size:   256)\n    Iter  4490\t      0.06892386 (Batch Size:   256)\n    Iter  4491\t      0.07299476 (Batch Size:   256)\n    Iter  4492\t      0.07364627 (Batch Size:   256)\n    Iter  4493\t      0.07287505 (Batch Size:   256)\n    Iter  4494\t      0.07496457 (Batch Size:   256)\n    Iter  4495\t      0.06971292 (Batch Size:   256)\n    Iter  4496\t      0.07272259 (Batch Size:   256)\n    Iter  4497\t      0.07144078 (Batch Size:   256)\n    Iter  4498\t      0.07099878 (Batch Size:   256)\n    Iter  4499\t      0.07217705 (Batch Size:   256)\n    Iter  4500\t      0.07098002 (Batch Size:   256)\n    Iter  4501\t      0.07850185 (Batch Size:   256)\n    Iter  4502\t      0.08456812 (Batch Size:   256)\n    Iter  4503\t      0.08175928 (Batch Size:   256)\n    Iter  4504\t      0.07460006 (Batch Size:   256)\n    Iter  4505\t      0.07347450 (Batch Size:   256)\n    Iter  4506\t      0.06845123 (Batch Size:   256)\n    Iter  4507\t      0.08035425 (Batch Size:   256)\n    Iter  4508\t      0.06970204 (Batch Size:   256)\n    Iter  4509\t      0.07032209 (Batch Size:   256)\n    Iter  4510\t      0.07613600 (Batch Size:   256)\n    Iter  4511\t      0.08482940 (Batch Size:   256)\n    Iter  4512\t      0.08189987 (Batch Size:   256)\n    Iter  4513\t      0.09269722 (Batch Size:   256)\n    Iter  4514\t      0.08376933 (Batch Size:   256)\n    Iter  4515\t      0.07866354 (Batch Size:   256)\n    Iter  4516\t      0.07869254 (Batch Size:   256)\n    Iter  4517\t      0.07597945 (Batch Size:   256)\n    Iter  4518\t      0.07503362 (Batch Size:   256)\n    Iter  4519\t      0.08803008 (Batch Size:   256)\n    Iter  4520\t      0.09406965 (Batch Size:   256)\n    Iter  4521\t      0.07759324 (Batch Size:   256)\n    Iter  4522\t      0.08026160 (Batch Size:   256)\n    Iter  4523\t      0.07384203 (Batch Size:   256)\n    Iter  4524\t      0.07413132 (Batch Size:   256)\n    Iter  4525\t      0.08067011 (Batch Size:   256)\n    Iter  4526\t      0.07864054 (Batch Size:   256)\n    Iter  4527\t      0.07299347 (Batch Size:   256)\n    Iter  4528\t      0.07299935 (Batch Size:   256)\n    Iter  4529\t      0.06951428 (Batch Size:   256)\n    Iter  4530\t      0.07284889 (Batch Size:   256)\n    Iter  4531\t      0.07206845 (Batch Size:   256)\n    Iter  4532\t      0.07753596 (Batch Size:   256)\n    Iter  4533\t      0.07760796 (Batch Size:   256)\n    Iter  4534\t      0.07768289 (Batch Size:   256)\n    Iter  4535\t      0.07243659 (Batch Size:   256)\n    Iter  4536\t      0.07580670 (Batch Size:   256)\n    Iter  4537\t      0.07641387 (Batch Size:   256)\n    Iter  4538\t      0.07507328 (Batch Size:   256)\n    Iter  4539\t      0.07922373 (Batch Size:   256)\n    Iter  4540\t      0.07164168 (Batch Size:   256)\n    Iter  4541\t      0.07108578 (Batch Size:   256)\n    Iter  4542\t      0.06993672 (Batch Size:   256)\n    Iter  4543\t      0.07240365 (Batch Size:   256)\n    Iter  4544\t      0.07168323 (Batch Size:   256)\n    Iter  4545\t      0.07363611 (Batch Size:   256)\n    Iter  4546\t      0.07521764 (Batch Size:   256)\n    Iter  4547\t      0.07112054 (Batch Size:   256)\n    Iter  4548\t      0.07188514 (Batch Size:   256)\n    Iter  4549\t      0.07556727 (Batch Size:   256)\n    Iter  4550\t      0.07287799 (Batch Size:   256)\n    Iter  4551\t      0.06973635 (Batch Size:   256)\n    Iter  4552\t      0.07199052 (Batch Size:   256)\n    Iter  4553\t      0.06962703 (Batch Size:   256)\n    Iter  4554\t      0.07465942 (Batch Size:   256)\n    Iter  4555\t      0.06941010 (Batch Size:   256)\n    Iter  4556\t      0.08696711 (Batch Size:   256)\n    Iter  4557\t      0.08473711 (Batch Size:   256)\n    Iter  4558\t      0.07808348 (Batch Size:   256)\n    Iter  4559\t      0.07593117 (Batch Size:   256)\n    Iter  4560\t      0.07478771 (Batch Size:   256)\n    Iter  4561\t      0.07622078 (Batch Size:   256)\n    Iter  4562\t      0.07195536 (Batch Size:   256)\n    Iter  4563\t      0.07025040 (Batch Size:   256)\n    Iter  4564\t      0.07081518 (Batch Size:   256)\n    Iter  4565\t      0.06944042 (Batch Size:   256)\n    Iter  4566\t      0.06604323 (Batch Size:   256)\n    Iter  4567\t      0.07023734 (Batch Size:   256)\n    Iter  4568\t      0.07432968 (Batch Size:   256)\n    Iter  4569\t      0.07250866 (Batch Size:   256)\n    Iter  4570\t      0.06941773 (Batch Size:   256)\n    Iter  4571\t      0.07120049 (Batch Size:   256)\n    Iter  4572\t      0.06797266 (Batch Size:   256)\n    Iter  4573\t      0.07661257 (Batch Size:   256)\n    Iter  4574\t      0.07340550 (Batch Size:   256)\n    Iter  4575\t      0.07021694 (Batch Size:   256)\n    Iter  4576\t      0.06861203 (Batch Size:   256)\n    Iter  4577\t      0.07292130 (Batch Size:   256)\n    Iter  4578\t      0.07261510 (Batch Size:   256)\n    Iter  4579\t      0.07219295 (Batch Size:   256)\n    Iter  4580\t      0.06933880 (Batch Size:   256)\n    Iter  4581\t      0.07460750 (Batch Size:   256)\n    Iter  4582\t      0.07408494 (Batch Size:   256)\n    Iter  4583\t      0.07562223 (Batch Size:   256)\n    Iter  4584\t      0.07005752 (Batch Size:   256)\n    Iter  4585\t      0.07282850 (Batch Size:   256)\n    Iter  4586\t      0.07349639 (Batch Size:   256)\n    Iter  4587\t      0.07199289 (Batch Size:   256)\n    Iter  4588\t      0.07581992 (Batch Size:   256)\n    Iter  4589\t      0.07276006 (Batch Size:   256)\n    Iter  4590\t      0.07707760 (Batch Size:   256)\n    Iter  4591\t      0.09461337 (Batch Size:   256)\n    Iter  4592\t      0.08936163 (Batch Size:   256)\n    Iter  4593\t      0.07583389 (Batch Size:   256)\n    Iter  4594\t      0.07719355 (Batch Size:   256)\n    Iter  4595\t      0.07273126 (Batch Size:   256)\n    Iter  4596\t      0.07445963 (Batch Size:   256)\n    Iter  4597\t      0.07072256 (Batch Size:   256)\n    Iter  4598\t      0.07773006 (Batch Size:   256)\n    Iter  4599\t      0.08139378 (Batch Size:   256)\n    Iter  4600\t      0.08340237 (Batch Size:   256)\n    Iter  4601\t      0.07519343 (Batch Size:   256)\n    Iter  4602\t      0.07145432 (Batch Size:   256)\n    Iter  4603\t      0.06979783 (Batch Size:   256)\n    Iter  4604\t      0.07398929 (Batch Size:   256)\n    Iter  4605\t      0.07266068 (Batch Size:   256)\n    Iter  4606\t      0.07165668 (Batch Size:   256)\n    Iter  4607\t      0.06999995 (Batch Size:   256)\n    Iter  4608\t      0.07103013 (Batch Size:   256)\n    Iter  4609\t      0.07403509 (Batch Size:   256)\n    Iter  4610\t      0.07900881 (Batch Size:   256)\n    Iter  4611\t      0.07425739 (Batch Size:   256)\n    Iter  4612\t      0.07361825 (Batch Size:   256)\n    Iter  4613\t      0.07076082 (Batch Size:   256)\n    Iter  4614\t      0.07202154 (Batch Size:   256)\n    Iter  4615\t      0.06925574 (Batch Size:   256)\n    Iter  4616\t      0.07077634 (Batch Size:   256)\n    Iter  4617\t      0.07158273 (Batch Size:   256)\n    Iter  4618\t      0.07259936 (Batch Size:   256)\n    Iter  4619\t      0.06952267 (Batch Size:   256)\n    Iter  4620\t      0.07169737 (Batch Size:   256)\n    Iter  4621\t      0.06801159 (Batch Size:   256)\n    Iter  4622\t      0.06997462 (Batch Size:   256)\n    Iter  4623\t      0.07472747 (Batch Size:   256)\n    Iter  4624\t      0.07182963 (Batch Size:   256)\n    Iter  4625\t      0.07356117 (Batch Size:   256)\n    Iter  4626\t      0.07614402 (Batch Size:   256)\n    Iter  4627\t      0.07181437 (Batch Size:   256)\n    Iter  4628\t      0.07197966 (Batch Size:   256)\n    Iter  4629\t      0.07245756 (Batch Size:   256)\n    Iter  4630\t      0.06918795 (Batch Size:   256)\n    Iter  4631\t      0.07112270 (Batch Size:   256)\n    Iter  4632\t      0.07138684 (Batch Size:   256)\n    Iter  4633\t      0.07610479 (Batch Size:   256)\n    Iter  4634\t      0.07615135 (Batch Size:   256)\n    Iter  4635\t      0.06927103 (Batch Size:   256)\n    Iter  4636\t      0.06996940 (Batch Size:   256)\n    Iter  4637\t      0.07538529 (Batch Size:   256)\n    Iter  4638\t      0.07266059 (Batch Size:   256)\n    Iter  4639\t      0.07549096 (Batch Size:   256)\n    Iter  4640\t      0.07156442 (Batch Size:   256)\n    Iter  4641\t      0.07044235 (Batch Size:   256)\n    Iter  4642\t      0.07492030 (Batch Size:   256)\n    Iter  4643\t      0.07549807 (Batch Size:   256)\n    Iter  4644\t      0.08225754 (Batch Size:   256)\n    Iter  4645\t      0.07147620 (Batch Size:   256)\n    Iter  4646\t      0.07400122 (Batch Size:   256)\n    Iter  4647\t      0.06843533 (Batch Size:   256)\n    Iter  4648\t      0.06966175 (Batch Size:   256)\n    Iter  4649\t      0.07030059 (Batch Size:   256)\n    Iter  4650\t      0.07344015 (Batch Size:   256)\n    Iter  4651\t      0.07286548 (Batch Size:   256)\n    Iter  4652\t      0.07359416 (Batch Size:   256)\n    Iter  4653\t      0.07336301 (Batch Size:   256)\n    Iter  4654\t      0.07560119 (Batch Size:   256)\n    Iter  4655\t      0.08189644 (Batch Size:   256)\n    Iter  4656\t      0.08070119 (Batch Size:   256)\n    Iter  4657\t      0.07334030 (Batch Size:   256)\n    Iter  4658\t      0.07812816 (Batch Size:   256)\n    Iter  4659\t      0.07574955 (Batch Size:   256)\n    Iter  4660\t      0.06883732 (Batch Size:   256)\n    Iter  4661\t      0.07055243 (Batch Size:   256)\n    Iter  4662\t      0.07119415 (Batch Size:   256)\n    Iter  4663\t      0.07677113 (Batch Size:   256)\n    Iter  4664\t      0.07682694 (Batch Size:   256)\n    Iter  4665\t      0.07009200 (Batch Size:   256)\n    Iter  4666\t      0.06944776 (Batch Size:   256)\n    Iter  4667\t      0.07198690 (Batch Size:   256)\n    Iter  4668\t      0.06952902 (Batch Size:   256)\n    Iter  4669\t      0.06702006 (Batch Size:   256)\n    Iter  4670\t      0.07315802 (Batch Size:   256)\n    Iter  4671\t      0.08937835 (Batch Size:   256)\n    Iter  4672\t      0.08130791 (Batch Size:   256)\n    Iter  4673\t      0.07892625 (Batch Size:   256)\n    Iter  4674\t      0.08551934 (Batch Size:   256)\n    Iter  4675\t      0.08709847 (Batch Size:   256)\n    Iter  4676\t      0.07219485 (Batch Size:   256)\n    Iter  4677\t      0.07483640 (Batch Size:   256)\n    Iter  4678\t      0.07562544 (Batch Size:   256)\n    Iter  4679\t      0.07045061 (Batch Size:   256)\n    Iter  4680\t      0.06827657 (Batch Size:   256)\n    Iter  4681\t      0.06961856 (Batch Size:   256)\n    Iter  4682\t      0.07414018 (Batch Size:   256)\n    Iter  4683\t      0.06950306 (Batch Size:   256)\n    Iter  4684\t      0.07141135 (Batch Size:   256)\n    Iter  4685\t      0.07575347 (Batch Size:   256)\n    Iter  4686\t      0.07940580 (Batch Size:   256)\n    Iter  4687\t      0.07874718 (Batch Size:   256)\n    Iter  4688\t      0.07349253 (Batch Size:   256)\n    Iter  4689\t      0.07368732 (Batch Size:   256)\n    Iter  4690\t      0.07226759 (Batch Size:   256)\n    Iter  4691\t      0.07164435 (Batch Size:   256)\n    Iter  4692\t      0.07320364 (Batch Size:   256)\n    Iter  4693\t      0.07241680 (Batch Size:   256)\n    Iter  4694\t      0.07420262 (Batch Size:   256)\n    Iter  4695\t      0.07445084 (Batch Size:   256)\n    Iter  4696\t      0.07140767 (Batch Size:   256)\n    Iter  4697\t      0.06482361 (Batch Size:   256)\n    Iter  4698\t      0.07252306 (Batch Size:   256)\n    Iter  4699\t      0.07234499 (Batch Size:   256)\n    Iter  4700\t      0.06950970 (Batch Size:   256)\n    Iter  4701\t      0.07854319 (Batch Size:   256)\n    Iter  4702\t      0.07968399 (Batch Size:   256)\n    Iter  4703\t      0.07632765 (Batch Size:   256)\n    Iter  4704\t      0.07999779 (Batch Size:   256)\n    Iter  4705\t      0.07350963 (Batch Size:   256)\n    Iter  4706\t      0.07070001 (Batch Size:   256)\n    Iter  4707\t      0.07571906 (Batch Size:   256)\n    Iter  4708\t      0.07345808 (Batch Size:   256)\n    Iter  4709\t      0.07457774 (Batch Size:   256)\n    Iter  4710\t      0.07343402 (Batch Size:   256)\n    Iter  4711\t      0.07065879 (Batch Size:   256)\n    Iter  4712\t      0.07298710 (Batch Size:   256)\n    Iter  4713\t      0.08539426 (Batch Size:   256)\n    Iter  4714\t      0.07620252 (Batch Size:   256)\n    Iter  4715\t      0.07279093 (Batch Size:   256)\n    Iter  4716\t      0.07971456 (Batch Size:   256)\n    Iter  4717\t      0.07661381 (Batch Size:   256)\n    Iter  4718\t      0.06891944 (Batch Size:   256)\n    Iter  4719\t      0.07460615 (Batch Size:   256)\n    Iter  4720\t      0.07256168 (Batch Size:   256)\n    Iter  4721\t      0.06971779 (Batch Size:   256)\n    Iter  4722\t      0.07296971 (Batch Size:   256)\n    Iter  4723\t      0.07446458 (Batch Size:   256)\n    Iter  4724\t      0.07784105 (Batch Size:   256)\n    Iter  4725\t      0.07414440 (Batch Size:   256)\n    Iter  4726\t      0.06843450 (Batch Size:   256)\n    Iter  4727\t      0.06989241 (Batch Size:   256)\n    Iter  4728\t      0.07127017 (Batch Size:   256)\n    Iter  4729\t      0.07207262 (Batch Size:   256)\n    Iter  4730\t      0.07968628 (Batch Size:   256)\n    Iter  4731\t      0.06969031 (Batch Size:   256)\n    Iter  4732\t      0.06926072 (Batch Size:   256)\n    Iter  4733\t      0.06944489 (Batch Size:   256)\n    Iter  4734\t      0.07529001 (Batch Size:   256)\n    Iter  4735\t      0.07969573 (Batch Size:   256)\n    Iter  4736\t      0.07177118 (Batch Size:   256)\n    Iter  4737\t      0.07101089 (Batch Size:   256)\n    Iter  4738\t      0.07963734 (Batch Size:   256)\n    Iter  4739\t      0.07354522 (Batch Size:   256)\n    Iter  4740\t      0.07182300 (Batch Size:   256)\n    Iter  4741\t      0.07270505 (Batch Size:   256)\n    Iter  4742\t      0.07388659 (Batch Size:   256)\n    Iter  4743\t      0.07854601 (Batch Size:   256)\n    Iter  4744\t      0.08030433 (Batch Size:   256)\n    Iter  4745\t      0.07198758 (Batch Size:   256)\n    Iter  4746\t      0.07097287 (Batch Size:   256)\n    Iter  4747\t      0.08113406 (Batch Size:   256)\n    Iter  4748\t      0.07758539 (Batch Size:   256)\n    Iter  4749\t      0.07471157 (Batch Size:   256)\n    Iter  4750\t      0.07575056 (Batch Size:   256)\n    Iter  4751\t      0.06933455 (Batch Size:   256)\n    Iter  4752\t      0.07016563 (Batch Size:   256)\n    Iter  4753\t      0.07721084 (Batch Size:   256)\n    Iter  4754\t      0.07392719 (Batch Size:   256)\n    Iter  4755\t      0.07368222 (Batch Size:   256)\n    Iter  4756\t      0.09294734 (Batch Size:   256)\n    Iter  4757\t      0.10053267 (Batch Size:   256)\n    Iter  4758\t      0.07906299 (Batch Size:   256)\n    Iter  4759\t      0.07421452 (Batch Size:   256)\n    Iter  4760\t      0.07512768 (Batch Size:   256)\n    Iter  4761\t      0.07282620 (Batch Size:   256)\n    Iter  4762\t      0.07110608 (Batch Size:   256)\n    Iter  4763\t      0.07608494 (Batch Size:   256)\n    Iter  4764\t      0.06695079 (Batch Size:   256)\n    Iter  4765\t      0.06633610 (Batch Size:   256)\n    Iter  4766\t      0.07484544 (Batch Size:   256)\n    Iter  4767\t      0.07313093 (Batch Size:   256)\n    Iter  4768\t      0.07537106 (Batch Size:   256)\n    Iter  4769\t      0.07467417 (Batch Size:   256)\n    Iter  4770\t      0.07101979 (Batch Size:   256)\n    Iter  4771\t      0.07484038 (Batch Size:   256)\n    Iter  4772\t      0.07496707 (Batch Size:   256)\n    Iter  4773\t      0.07438830 (Batch Size:   256)\n    Iter  4774\t      0.06924407 (Batch Size:   256)\n    Iter  4775\t      0.07451145 (Batch Size:   256)\n    Iter  4776\t      0.07732777 (Batch Size:   256)\n    Iter  4777\t      0.06862704 (Batch Size:   256)\n    Iter  4778\t      0.07172045 (Batch Size:   256)\n    Iter  4779\t      0.07183559 (Batch Size:   256)\n    Iter  4780\t      0.07786131 (Batch Size:   256)\n    Iter  4781\t      0.07922724 (Batch Size:   256)\n    Iter  4782\t      0.07071534 (Batch Size:   256)\n    Iter  4783\t      0.06839146 (Batch Size:   256)\n    Iter  4784\t      0.06848603 (Batch Size:   256)\n    Iter  4785\t      0.06618253 (Batch Size:   256)\n    Iter  4786\t      0.07703546 (Batch Size:   256)\n    Iter  4787\t      0.07815635 (Batch Size:   256)\n    Iter  4788\t      0.08849921 (Batch Size:   256)\n    Iter  4789\t      0.08935266 (Batch Size:   256)\n    Iter  4790\t      0.08361992 (Batch Size:   256)\n    Iter  4791\t      0.07699673 (Batch Size:   256)\n    Iter  4792\t      0.07938581 (Batch Size:   256)\n    Iter  4793\t      0.07807527 (Batch Size:   256)\n    Iter  4794\t      0.07369034 (Batch Size:   256)\n    Iter  4795\t      0.07520219 (Batch Size:   256)\n    Iter  4796\t      0.07088463 (Batch Size:   256)\n    Iter  4797\t      0.07526665 (Batch Size:   256)\n    Iter  4798\t      0.07058602 (Batch Size:   256)\n    Iter  4799\t      0.07455967 (Batch Size:   256)\n    Iter  4800\t      0.06893937 (Batch Size:   256)\n    Iter  4801\t      0.06972030 (Batch Size:   256)\n    Iter  4802\t      0.07800588 (Batch Size:   256)\n    Iter  4803\t      0.07120147 (Batch Size:   256)\n    Iter  4804\t      0.06842950 (Batch Size:   256)\n    Iter  4805\t      0.07195886 (Batch Size:   256)\n    Iter  4806\t      0.07770287 (Batch Size:   256)\n    Iter  4807\t      0.08302280 (Batch Size:   256)\n    Iter  4808\t      0.07875859 (Batch Size:   256)\n    Iter  4809\t      0.06964836 (Batch Size:   256)\n    Iter  4810\t      0.07000200 (Batch Size:   256)\n    Iter  4811\t      0.06996649 (Batch Size:   256)\n    Iter  4812\t      0.07098796 (Batch Size:   256)\n    Iter  4813\t      0.07257438 (Batch Size:   256)\n    Iter  4814\t      0.07118809 (Batch Size:   256)\n    Iter  4815\t      0.06941608 (Batch Size:   256)\n    Iter  4816\t      0.07542218 (Batch Size:   256)\n    Iter  4817\t      0.06693825 (Batch Size:   256)\n    Iter  4818\t      0.07507925 (Batch Size:   256)\n    Iter  4819\t      0.06753824 (Batch Size:   256)\n    Iter  4820\t      0.06819798 (Batch Size:   256)\n    Iter  4821\t      0.07140926 (Batch Size:   256)\n    Iter  4822\t      0.06981948 (Batch Size:   256)\n    Iter  4823\t      0.07090403 (Batch Size:   256)\n    Iter  4824\t      0.07531780 (Batch Size:   256)\n    Iter  4825\t      0.07997338 (Batch Size:   256)\n    Iter  4826\t      0.07568009 (Batch Size:   256)\n    Iter  4827\t      0.07719485 (Batch Size:   256)\n    Iter  4828\t      0.07275296 (Batch Size:   256)\n    Iter  4829\t      0.07261690 (Batch Size:   256)\n    Iter  4830\t      0.07102037 (Batch Size:   256)\n    Iter  4831\t      0.06842688 (Batch Size:   256)\n    Iter  4832\t      0.06691808 (Batch Size:   256)\n    Iter  4833\t      0.06614321 (Batch Size:   256)\n    Iter  4834\t      0.06911817 (Batch Size:   256)\n    Iter  4835\t      0.07125502 (Batch Size:   256)\n    Iter  4836\t      0.07166782 (Batch Size:   256)\n    Iter  4837\t      0.07472683 (Batch Size:   256)\n    Iter  4838\t      0.07026672 (Batch Size:   256)\n    Iter  4839\t      0.06735552 (Batch Size:   256)\n    Iter  4840\t      0.07065804 (Batch Size:   256)\n    Iter  4841\t      0.07055118 (Batch Size:   256)\n    Iter  4842\t      0.07729212 (Batch Size:   256)\n    Iter  4843\t      0.07201579 (Batch Size:   256)\n    Iter  4844\t      0.06987319 (Batch Size:   256)\n    Iter  4845\t      0.06913649 (Batch Size:   256)\n    Iter  4846\t      0.07458766 (Batch Size:   256)\n    Iter  4847\t      0.07245900 (Batch Size:   256)\n    Iter  4848\t      0.07188126 (Batch Size:   256)\n    Iter  4849\t      0.06973246 (Batch Size:   256)\n    Iter  4850\t      0.07300622 (Batch Size:   256)\n    Iter  4851\t      0.06874440 (Batch Size:   256)\n    Iter  4852\t      0.07146936 (Batch Size:   256)\n    Iter  4853\t      0.07101530 (Batch Size:   256)\n    Iter  4854\t      0.07804488 (Batch Size:   256)\n    Iter  4855\t      0.08731513 (Batch Size:   256)\n    Iter  4856\t      0.09016665 (Batch Size:   256)\n    Iter  4857\t      0.07676126 (Batch Size:   256)\n    Iter  4858\t      0.07230379 (Batch Size:   256)\n    Iter  4859\t      0.06980729 (Batch Size:   256)\n    Iter  4860\t      0.06818928 (Batch Size:   256)\n    Iter  4861\t      0.06974777 (Batch Size:   256)\n    Iter  4862\t      0.07446434 (Batch Size:   256)\n    Iter  4863\t      0.06938419 (Batch Size:   256)\n    Iter  4864\t      0.07561585 (Batch Size:   256)\n    Iter  4865\t      0.07422342 (Batch Size:   256)\n    Iter  4866\t      0.07940048 (Batch Size:   256)\n    Iter  4867\t      0.07021014 (Batch Size:   256)\n    Iter  4868\t      0.06855544 (Batch Size:   256)\n    Iter  4869\t      0.06978097 (Batch Size:   256)\n    Iter  4870\t      0.07298049 (Batch Size:   256)\n    Iter  4871\t      0.08250092 (Batch Size:   256)\n    Iter  4872\t      0.07410417 (Batch Size:   256)\n    Iter  4873\t      0.07164580 (Batch Size:   256)\n    Iter  4874\t      0.07291057 (Batch Size:   256)\n    Iter  4875\t      0.07517604 (Batch Size:   256)\n    Iter  4876\t      0.06919141 (Batch Size:   256)\n    Iter  4877\t      0.07376961 (Batch Size:   256)\n    Iter  4878\t      0.07358519 (Batch Size:   256)\n    Iter  4879\t      0.06906904 (Batch Size:   256)\n    Iter  4880\t      0.08139134 (Batch Size:   256)\n    Iter  4881\t      0.08297701 (Batch Size:   256)\n    Iter  4882\t      0.07491163 (Batch Size:   256)\n    Iter  4883\t      0.07174541 (Batch Size:   256)\n    Iter  4884\t      0.06958915 (Batch Size:   256)\n    Iter  4885\t      0.06905185 (Batch Size:   256)\n    Iter  4886\t      0.07636011 (Batch Size:   256)\n    Iter  4887\t      0.07277132 (Batch Size:   256)\n    Iter  4888\t      0.07011953 (Batch Size:   256)\n    Iter  4889\t      0.07701756 (Batch Size:   256)\n    Iter  4890\t      0.08091532 (Batch Size:   256)\n    Iter  4891\t      0.08354467 (Batch Size:   256)\n    Iter  4892\t      0.07459867 (Batch Size:   256)\n    Iter  4893\t      0.08028713 (Batch Size:   256)\n    Iter  4894\t      0.07414885 (Batch Size:   256)\n    Iter  4895\t      0.07910085 (Batch Size:   256)\n    Iter  4896\t      0.08354661 (Batch Size:   256)\n    Iter  4897\t      0.08918976 (Batch Size:   256)\n    Iter  4898\t      0.07622337 (Batch Size:   256)\n    Iter  4899\t      0.07365968 (Batch Size:   256)\n    Iter  4900\t      0.07728609 (Batch Size:   256)\n    Iter  4901\t      0.07370949 (Batch Size:   256)\n    Iter  4902\t      0.06496845 (Batch Size:   256)\n    Iter  4903\t      0.06632770 (Batch Size:   256)\n    Iter  4904\t      0.06980952 (Batch Size:   256)\n    Iter  4905\t      0.06859611 (Batch Size:   256)\n    Iter  4906\t      0.07322459 (Batch Size:   256)\n    Iter  4907\t      0.07270858 (Batch Size:   256)\n    Iter  4908\t      0.07466584 (Batch Size:   256)\n    Iter  4909\t      0.07431730 (Batch Size:   256)\n    Iter  4910\t      0.08335810 (Batch Size:   256)\n    Iter  4911\t      0.07480225 (Batch Size:   256)\n    Iter  4912\t      0.07652609 (Batch Size:   256)\n    Iter  4913\t      0.07640099 (Batch Size:   256)\n    Iter  4914\t      0.07042521 (Batch Size:   256)\n    Iter  4915\t      0.07293228 (Batch Size:   256)\n    Iter  4916\t      0.07403788 (Batch Size:   256)\n    Iter  4917\t      0.07725899 (Batch Size:   256)\n    Iter  4918\t      0.07566279 (Batch Size:   256)\n    Iter  4919\t      0.07334904 (Batch Size:   256)\n    Iter  4920\t      0.07204384 (Batch Size:   256)\n    Iter  4921\t      0.07055592 (Batch Size:   256)\n    Iter  4922\t      0.07036334 (Batch Size:   256)\n    Iter  4923\t      0.07002176 (Batch Size:   256)\n    Iter  4924\t      0.07346834 (Batch Size:   256)\n    Iter  4925\t      0.07051321 (Batch Size:   256)\n    Iter  4926\t      0.07445053 (Batch Size:   256)\n    Iter  4927\t      0.07115162 (Batch Size:   256)\n    Iter  4928\t      0.06809511 (Batch Size:   256)\n    Iter  4929\t      0.06922222 (Batch Size:   256)\n    Iter  4930\t      0.07491161 (Batch Size:   256)\n    Iter  4931\t      0.07977576 (Batch Size:   256)\n    Iter  4932\t      0.08026946 (Batch Size:   256)\n    Iter  4933\t      0.07321388 (Batch Size:   256)\n    Iter  4934\t      0.06930592 (Batch Size:   256)\n    Iter  4935\t      0.07153649 (Batch Size:   256)\n    Iter  4936\t      0.07047474 (Batch Size:   256)\n    Iter  4937\t      0.07048507 (Batch Size:   256)\n    Iter  4938\t      0.07337167 (Batch Size:   256)\n    Iter  4939\t      0.07274055 (Batch Size:   256)\n    Iter  4940\t      0.07170474 (Batch Size:   256)\n    Iter  4941\t      0.07621649 (Batch Size:   256)\n    Iter  4942\t      0.08617731 (Batch Size:   256)\n    Iter  4943\t      0.07596806 (Batch Size:   256)\n    Iter  4944\t      0.06930705 (Batch Size:   256)\n    Iter  4945\t      0.06946624 (Batch Size:   256)\n    Iter  4946\t      0.07034424 (Batch Size:   256)\n    Iter  4947\t      0.06883986 (Batch Size:   256)\n    Iter  4948\t      0.07398222 (Batch Size:   256)\n    Iter  4949\t      0.07991627 (Batch Size:   256)\n    Iter  4950\t      0.06968872 (Batch Size:   256)\n    Iter  4951\t      0.06844183 (Batch Size:   256)\n    Iter  4952\t      0.07290019 (Batch Size:   256)\n    Iter  4953\t      0.06857411 (Batch Size:   256)\n    Iter  4954\t      0.08054107 (Batch Size:   256)\n    Iter  4955\t      0.07881396 (Batch Size:   256)\n    Iter  4956\t      0.07360302 (Batch Size:   256)\n    Iter  4957\t      0.06861063 (Batch Size:   256)\n    Iter  4958\t      0.06795425 (Batch Size:   256)\n    Iter  4959\t      0.07883386 (Batch Size:   256)\n    Iter  4960\t      0.07652325 (Batch Size:   256)\n    Iter  4961\t      0.07316915 (Batch Size:   256)\n    Iter  4962\t      0.07352870 (Batch Size:   256)\n    Iter  4963\t      0.07204316 (Batch Size:   256)\n    Iter  4964\t      0.06924833 (Batch Size:   256)\n    Iter  4965\t      0.07696335 (Batch Size:   256)\n    Iter  4966\t      0.08740493 (Batch Size:   256)\n    Iter  4967\t      0.07196237 (Batch Size:   256)\n    Iter  4968\t      0.07012580 (Batch Size:   256)\n    Iter  4969\t      0.07145684 (Batch Size:   256)\n    Iter  4970\t      0.07134690 (Batch Size:   256)\n    Iter  4971\t      0.07273966 (Batch Size:   256)\n    Iter  4972\t      0.07803271 (Batch Size:   256)\n    Iter  4973\t      0.06845793 (Batch Size:   256)\n    Iter  4974\t      0.07353928 (Batch Size:   256)\n    Iter  4975\t      0.06989972 (Batch Size:   256)\n    Iter  4976\t      0.07008501 (Batch Size:   256)\n    Iter  4977\t      0.07056368 (Batch Size:   256)\n    Iter  4978\t      0.06803008 (Batch Size:   256)\n    Iter  4979\t      0.07225805 (Batch Size:   256)\n    Iter  4980\t      0.07294726 (Batch Size:   256)\n    Iter  4981\t      0.07293661 (Batch Size:   256)\n    Iter  4982\t      0.07179852 (Batch Size:   256)\n    Iter  4983\t      0.07483876 (Batch Size:   256)\n    Iter  4984\t      0.07676641 (Batch Size:   256)\n    Iter  4985\t      0.07635066 (Batch Size:   256)\n    Iter  4986\t      0.07673090 (Batch Size:   256)\n    Iter  4987\t      0.07227899 (Batch Size:   256)\n    Iter  4988\t      0.07069276 (Batch Size:   256)\n    Iter  4989\t      0.07073713 (Batch Size:   256)\n    Iter  4990\t      0.07423872 (Batch Size:   256)\n    Iter  4991\t      0.07351217 (Batch Size:   256)\n    Iter  4992\t      0.07124168 (Batch Size:   256)\n    Iter  4993\t      0.08454332 (Batch Size:   256)\n    Iter  4994\t      0.07229020 (Batch Size:   256)\n    Iter  4995\t      0.06938277 (Batch Size:   256)\n    Iter  4996\t      0.07118048 (Batch Size:   256)\n    Iter  4997\t      0.07089688 (Batch Size:   256)\n    Iter  4998\t      0.07183964 (Batch Size:   256)\n    Iter  4999\t      0.07238800 (Batch Size:   256)\n    Iter  5000\t      0.07128999 (Batch Size:   256)\n    Iter  5001\t      0.07513667 (Batch Size:   256)\n    Iter  5002\t      0.07851263 (Batch Size:   256)\n    Iter  5003\t      0.07316587 (Batch Size:   256)\n    Iter  5004\t      0.07297258 (Batch Size:   256)\n    Iter  5005\t      0.07401882 (Batch Size:   256)\n    Iter  5006\t      0.07558983 (Batch Size:   256)\n    Iter  5007\t      0.06751466 (Batch Size:   256)\n    Iter  5008\t      0.06886214 (Batch Size:   256)\n    Iter  5009\t      0.07352236 (Batch Size:   256)\n    Iter  5010\t      0.07722281 (Batch Size:   256)\n    Iter  5011\t      0.07282777 (Batch Size:   256)\n    Iter  5012\t      0.07271457 (Batch Size:   256)\n    Iter  5013\t      0.06851588 (Batch Size:   256)\n    Iter  5014\t      0.07174769 (Batch Size:   256)\n    Iter  5015\t      0.07221380 (Batch Size:   256)\n    Iter  5016\t      0.07615593 (Batch Size:   256)\n    Iter  5017\t      0.07615849 (Batch Size:   256)\n    Iter  5018\t      0.07118556 (Batch Size:   256)\n    Iter  5019\t      0.07088839 (Batch Size:   256)\n    Iter  5020\t      0.06763053 (Batch Size:   256)\n    Iter  5021\t      0.07154319 (Batch Size:   256)\n    Iter  5022\t      0.06930272 (Batch Size:   256)\n    Iter  5023\t      0.07163943 (Batch Size:   256)\n    Iter  5024\t      0.08547430 (Batch Size:   256)\n    Iter  5025\t      0.07198104 (Batch Size:   256)\n    Iter  5026\t      0.07222372 (Batch Size:   256)\n    Iter  5027\t      0.07108722 (Batch Size:   256)\n    Iter  5028\t      0.08322567 (Batch Size:   256)\n    Iter  5029\t      0.08354185 (Batch Size:   256)\n    Iter  5030\t      0.07102300 (Batch Size:   256)\n    Iter  5031\t      0.06623903 (Batch Size:   256)\n    Iter  5032\t      0.07629886 (Batch Size:   256)\n    Iter  5033\t      0.08146920 (Batch Size:   256)\n    Iter  5034\t      0.07962586 (Batch Size:   256)\n    Iter  5035\t      0.07304096 (Batch Size:   256)\n    Iter  5036\t      0.07587000 (Batch Size:   256)\n    Iter  5037\t      0.07170212 (Batch Size:   256)\n    Iter  5038\t      0.07275289 (Batch Size:   256)\n    Iter  5039\t      0.08576629 (Batch Size:   256)\n    Iter  5040\t      0.07917916 (Batch Size:   256)\n    Iter  5041\t      0.07348563 (Batch Size:   256)\n    Iter  5042\t      0.07249082 (Batch Size:   256)\n    Iter  5043\t      0.07447180 (Batch Size:   256)\n    Iter  5044\t      0.07535367 (Batch Size:   256)\n    Iter  5045\t      0.07405774 (Batch Size:   256)\n    Iter  5046\t      0.06583506 (Batch Size:   256)\n    Iter  5047\t      0.07243172 (Batch Size:   256)\n    Iter  5048\t      0.07446080 (Batch Size:   256)\n    Iter  5049\t      0.07160142 (Batch Size:   256)\n    Iter  5050\t      0.06994626 (Batch Size:   256)\n    Iter  5051\t      0.06795263 (Batch Size:   256)\n    Iter  5052\t      0.07233292 (Batch Size:   256)\n    Iter  5053\t      0.07287580 (Batch Size:   256)\n    Iter  5054\t      0.08241378 (Batch Size:   256)\n    Iter  5055\t      0.07174064 (Batch Size:   256)\n    Iter  5056\t      0.08597085 (Batch Size:   256)\n    Iter  5057\t      0.07894465 (Batch Size:   256)\n    Iter  5058\t      0.07457698 (Batch Size:   256)\n    Iter  5059\t      0.07217884 (Batch Size:   256)\n    Iter  5060\t      0.07398637 (Batch Size:   256)\n    Iter  5061\t      0.07823965 (Batch Size:   256)\n    Iter  5062\t      0.07262209 (Batch Size:   256)\n    Iter  5063\t      0.06900808 (Batch Size:   256)\n    Iter  5064\t      0.07283040 (Batch Size:   256)\n    Iter  5065\t      0.07124736 (Batch Size:   256)\n    Iter  5066\t      0.07252507 (Batch Size:   256)\n    Iter  5067\t      0.07079664 (Batch Size:   256)\n    Iter  5068\t      0.06951554 (Batch Size:   256)\n    Iter  5069\t      0.07169213 (Batch Size:   256)\n    Iter  5070\t      0.07154072 (Batch Size:   256)\n    Iter  5071\t      0.06938732 (Batch Size:   256)\n    Iter  5072\t      0.07434443 (Batch Size:   256)\n    Iter  5073\t      0.07166241 (Batch Size:   256)\n    Iter  5074\t      0.06807477 (Batch Size:   256)\n    Iter  5075\t      0.07111822 (Batch Size:   256)\n    Iter  5076\t      0.07033963 (Batch Size:   256)\n    Iter  5077\t      0.08231283 (Batch Size:   256)\n    Iter  5078\t      0.07976379 (Batch Size:   256)\n    Iter  5079\t      0.08213732 (Batch Size:   256)\n    Iter  5080\t      0.08437681 (Batch Size:   256)\n    Iter  5081\t      0.07104113 (Batch Size:   256)\n    Iter  5082\t      0.07223831 (Batch Size:   256)\n    Iter  5083\t      0.07081776 (Batch Size:   256)\n    Iter  5084\t      0.07446920 (Batch Size:   256)\n    Iter  5085\t      0.07052070 (Batch Size:   256)\n    Iter  5086\t      0.07507766 (Batch Size:   256)\n    Iter  5087\t      0.07188934 (Batch Size:   256)\n    Iter  5088\t      0.06924596 (Batch Size:   256)\n    Iter  5089\t      0.07267452 (Batch Size:   256)\n    Iter  5090\t      0.07228177 (Batch Size:   256)\n    Iter  5091\t      0.07446605 (Batch Size:   256)\n    Iter  5092\t      0.07572301 (Batch Size:   256)\n    Iter  5093\t      0.06882749 (Batch Size:   256)\n    Iter  5094\t      0.07101101 (Batch Size:   256)\n    Iter  5095\t      0.06796161 (Batch Size:   256)\n    Iter  5096\t      0.07077158 (Batch Size:   256)\n    Iter  5097\t      0.07028521 (Batch Size:   256)\n    Iter  5098\t      0.07291363 (Batch Size:   256)\n    Iter  5099\t      0.07006815 (Batch Size:   256)\n    Iter  5100\t      0.07115798 (Batch Size:   256)\n    Iter  5101\t      0.07188345 (Batch Size:   256)\n    Iter  5102\t      0.07288848 (Batch Size:   256)\n    Iter  5103\t      0.07144488 (Batch Size:   256)\n    Iter  5104\t      0.07301102 (Batch Size:   256)\n    Iter  5105\t      0.06928144 (Batch Size:   256)\n    Iter  5106\t      0.06630871 (Batch Size:   256)\n    Iter  5107\t      0.07266876 (Batch Size:   256)\n    Iter  5108\t      0.07082543 (Batch Size:   256)\n    Iter  5109\t      0.07116314 (Batch Size:   256)\n    Iter  5110\t      0.07724189 (Batch Size:   256)\n    Iter  5111\t      0.06617470 (Batch Size:   256)\n    Iter  5112\t      0.07195733 (Batch Size:   256)\n    Iter  5113\t      0.07908314 (Batch Size:   256)\n    Iter  5114\t      0.07283789 (Batch Size:   256)\n    Iter  5115\t      0.07025829 (Batch Size:   256)\n    Iter  5116\t      0.07005381 (Batch Size:   256)\n    Iter  5117\t      0.09046956 (Batch Size:   256)\n    Iter  5118\t      0.06716531 (Batch Size:   256)\n    Iter  5119\t      0.07114634 (Batch Size:   256)\n    Iter  5120\t      0.08699225 (Batch Size:   256)\n    Iter  5121\t      0.06826034 (Batch Size:   256)\n    Iter  5122\t      0.06979492 (Batch Size:   256)\n    Iter  5123\t      0.06712782 (Batch Size:   256)\n    Iter  5124\t      0.06734618 (Batch Size:   256)\n    Iter  5125\t      0.06766633 (Batch Size:   256)\n    Iter  5126\t      0.07179108 (Batch Size:   256)\n    Iter  5127\t      0.06818393 (Batch Size:   256)\n    Iter  5128\t      0.07138083 (Batch Size:   256)\n    Iter  5129\t      0.06582087 (Batch Size:   256)\n    Iter  5130\t      0.07012274 (Batch Size:   256)\n    Iter  5131\t      0.06959576 (Batch Size:   256)\n    Iter  5132\t      0.07020746 (Batch Size:   256)\n    Iter  5133\t      0.07391573 (Batch Size:   256)\n    Iter  5134\t      0.07365150 (Batch Size:   256)\n    Iter  5135\t      0.07273039 (Batch Size:   256)\n    Iter  5136\t      0.07819588 (Batch Size:   256)\n    Iter  5137\t      0.07265528 (Batch Size:   256)\n    Iter  5138\t      0.07146602 (Batch Size:   256)\n    Iter  5139\t      0.06737944 (Batch Size:   256)\n    Iter  5140\t      0.07045568 (Batch Size:   256)\n    Iter  5141\t      0.07191462 (Batch Size:   256)\n    Iter  5142\t      0.07164472 (Batch Size:   256)\n    Iter  5143\t      0.06989153 (Batch Size:   256)\n    Iter  5144\t      0.07567516 (Batch Size:   256)\n    Iter  5145\t      0.07199599 (Batch Size:   256)\n    Iter  5146\t      0.07741948 (Batch Size:   256)\n    Iter  5147\t      0.07040185 (Batch Size:   256)\n    Iter  5148\t      0.07069711 (Batch Size:   256)\n    Iter  5149\t      0.06866354 (Batch Size:   256)\n    Iter  5150\t      0.06907804 (Batch Size:   256)\n    Iter  5151\t      0.07638150 (Batch Size:   256)\n    Iter  5152\t      0.06890731 (Batch Size:   256)\n    Iter  5153\t      0.06845343 (Batch Size:   256)\n    Iter  5154\t      0.07144035 (Batch Size:   256)\n    Iter  5155\t      0.06835434 (Batch Size:   256)\n    Iter  5156\t      0.07350632 (Batch Size:   256)\n    Iter  5157\t      0.09519250 (Batch Size:   256)\n    Iter  5158\t      0.07770538 (Batch Size:   256)\n    Iter  5159\t      0.06893324 (Batch Size:   256)\n    Iter  5160\t      0.06865465 (Batch Size:   256)\n    Iter  5161\t      0.06815509 (Batch Size:   256)\n    Iter  5162\t      0.06985439 (Batch Size:   256)\n    Iter  5163\t      0.06940553 (Batch Size:   256)\n    Iter  5164\t      0.09168435 (Batch Size:   256)\n    Iter  5165\t      0.08087789 (Batch Size:   256)\n    Iter  5166\t      0.07040397 (Batch Size:   256)\n    Iter  5167\t      0.07357214 (Batch Size:   256)\n    Iter  5168\t      0.07325554 (Batch Size:   256)\n    Iter  5169\t      0.07279655 (Batch Size:   256)\n    Iter  5170\t      0.06932905 (Batch Size:   256)\n    Iter  5171\t      0.07067061 (Batch Size:   256)\n    Iter  5172\t      0.06875806 (Batch Size:   256)\n    Iter  5173\t      0.06953818 (Batch Size:   256)\n    Iter  5174\t      0.06973852 (Batch Size:   256)\n    Iter  5175\t      0.06998657 (Batch Size:   256)\n    Iter  5176\t      0.06708951 (Batch Size:   256)\n    Iter  5177\t      0.06699624 (Batch Size:   256)\n    Iter  5178\t      0.07558175 (Batch Size:   256)\n    Iter  5179\t      0.07733772 (Batch Size:   256)\n    Iter  5180\t      0.07872083 (Batch Size:   256)\n    Iter  5181\t      0.06682682 (Batch Size:   256)\n    Iter  5182\t      0.06791629 (Batch Size:   256)\n    Iter  5183\t      0.06910397 (Batch Size:   256)\n    Iter  5184\t      0.08150212 (Batch Size:   256)\n    Iter  5185\t      0.09292110 (Batch Size:   256)\n    Iter  5186\t      0.10172856 (Batch Size:   256)\n    Iter  5187\t      0.08134243 (Batch Size:   256)\n    Iter  5188\t      0.07531850 (Batch Size:   256)\n    Iter  5189\t      0.07033728 (Batch Size:   256)\n    Iter  5190\t      0.06757983 (Batch Size:   256)\n    Iter  5191\t      0.07338283 (Batch Size:   256)\n    Iter  5192\t      0.07083087 (Batch Size:   256)\n    Iter  5193\t      0.06825938 (Batch Size:   256)\n    Iter  5194\t      0.07099325 (Batch Size:   256)\n    Iter  5195\t      0.07058032 (Batch Size:   256)\n    Iter  5196\t      0.07405926 (Batch Size:   256)\n    Iter  5197\t      0.07320645 (Batch Size:   256)\n    Iter  5198\t      0.06987725 (Batch Size:   256)\n    Iter  5199\t      0.06904108 (Batch Size:   256)\n    Iter  5200\t      0.06899256 (Batch Size:   256)\n    Iter  5201\t      0.07418999 (Batch Size:   256)\n    Iter  5202\t      0.07083633 (Batch Size:   256)\n    Iter  5203\t      0.07250157 (Batch Size:   256)\n    Iter  5204\t      0.06929785 (Batch Size:   256)\n    Iter  5205\t      0.07032147 (Batch Size:   256)\n    Iter  5206\t      0.07858796 (Batch Size:   256)\n    Iter  5207\t      0.07412005 (Batch Size:   256)\n    Iter  5208\t      0.07182709 (Batch Size:   256)\n    Iter  5209\t      0.07239370 (Batch Size:   256)\n    Iter  5210\t      0.07516559 (Batch Size:   256)\n    Iter  5211\t      0.08333554 (Batch Size:   256)\n    Iter  5212\t      0.07375667 (Batch Size:   256)\n    Iter  5213\t      0.06950852 (Batch Size:   256)\n    Iter  5214\t      0.06745499 (Batch Size:   256)\n    Iter  5215\t      0.06944909 (Batch Size:   256)\n    Iter  5216\t      0.07292852 (Batch Size:   256)\n    Iter  5217\t      0.06630820 (Batch Size:   256)\n    Iter  5218\t      0.07906228 (Batch Size:   256)\n    Iter  5219\t      0.07759728 (Batch Size:   256)\n    Iter  5220\t      0.09341004 (Batch Size:   256)\n    Iter  5221\t      0.07653227 (Batch Size:   256)\n    Iter  5222\t      0.07415332 (Batch Size:   256)\n    Iter  5223\t      0.07461015 (Batch Size:   256)\n    Iter  5224\t      0.06854375 (Batch Size:   256)\n    Iter  5225\t      0.07144538 (Batch Size:   256)\n    Iter  5226\t      0.06718346 (Batch Size:   256)\n    Iter  5227\t      0.06563422 (Batch Size:   256)\n    Iter  5228\t      0.07285258 (Batch Size:   256)\n    Iter  5229\t      0.08254734 (Batch Size:   256)\n    Iter  5230\t      0.06976320 (Batch Size:   256)\n    Iter  5231\t      0.07445123 (Batch Size:   256)\n    Iter  5232\t      0.07062553 (Batch Size:   256)\n    Iter  5233\t      0.07161625 (Batch Size:   256)\n    Iter  5234\t      0.06911695 (Batch Size:   256)\n    Iter  5235\t      0.07164895 (Batch Size:   256)\n    Iter  5236\t      0.06842590 (Batch Size:   256)\n    Iter  5237\t      0.07190487 (Batch Size:   256)\n    Iter  5238\t      0.06612314 (Batch Size:   256)\n    Iter  5239\t      0.06982891 (Batch Size:   256)\n    Iter  5240\t      0.07279105 (Batch Size:   256)\n    Iter  5241\t      0.06807575 (Batch Size:   256)\n    Iter  5242\t      0.07375084 (Batch Size:   256)\n    Iter  5243\t      0.07187290 (Batch Size:   256)\n    Iter  5244\t      0.06630151 (Batch Size:   256)\n    Iter  5245\t      0.07098432 (Batch Size:   256)\n    Iter  5246\t      0.06920366 (Batch Size:   256)\n    Iter  5247\t      0.06840320 (Batch Size:   256)\n    Iter  5248\t      0.07042743 (Batch Size:   256)\n    Iter  5249\t      0.07023860 (Batch Size:   256)\n    Iter  5250\t      0.06985843 (Batch Size:   256)\n    Iter  5251\t      0.07103078 (Batch Size:   256)\n    Iter  5252\t      0.06681308 (Batch Size:   256)\n    Iter  5253\t      0.06819375 (Batch Size:   256)\n    Iter  5254\t      0.06955383 (Batch Size:   256)\n    Iter  5255\t      0.07113018 (Batch Size:   256)\n    Iter  5256\t      0.08306609 (Batch Size:   256)\n    Iter  5257\t      0.07154273 (Batch Size:   256)\n    Iter  5258\t      0.07966285 (Batch Size:   256)\n    Iter  5259\t      0.08220882 (Batch Size:   256)\n    Iter  5260\t      0.07840076 (Batch Size:   256)\n    Iter  5261\t      0.07515412 (Batch Size:   256)\n    Iter  5262\t      0.06881309 (Batch Size:   256)\n    Iter  5263\t      0.06933346 (Batch Size:   256)\n    Iter  5264\t      0.07553097 (Batch Size:   256)\n    Iter  5265\t      0.07780178 (Batch Size:   256)\n    Iter  5266\t      0.07245764 (Batch Size:   256)\n    Iter  5267\t      0.06937305 (Batch Size:   256)\n    Iter  5268\t      0.06978200 (Batch Size:   256)\n    Iter  5269\t      0.06799238 (Batch Size:   256)\n    Iter  5270\t      0.06838170 (Batch Size:   256)\n    Iter  5271\t      0.07789717 (Batch Size:   256)\n    Iter  5272\t      0.07634843 (Batch Size:   256)\n    Iter  5273\t      0.07436987 (Batch Size:   256)\n    Iter  5274\t      0.06953916 (Batch Size:   256)\n    Iter  5275\t      0.06737336 (Batch Size:   256)\n    Iter  5276\t      0.06979110 (Batch Size:   256)\n    Iter  5277\t      0.07025478 (Batch Size:   256)\n    Iter  5278\t      0.06735896 (Batch Size:   256)\n    Iter  5279\t      0.07229178 (Batch Size:   256)\n    Iter  5280\t      0.07640052 (Batch Size:   256)\n    Iter  5281\t      0.07994634 (Batch Size:   256)\n    Iter  5282\t      0.07765341 (Batch Size:   256)\n    Iter  5283\t      0.07302931 (Batch Size:   256)\n    Iter  5284\t      0.06842929 (Batch Size:   256)\n    Iter  5285\t      0.07151525 (Batch Size:   256)\n    Iter  5286\t      0.07243304 (Batch Size:   256)\n    Iter  5287\t      0.06834430 (Batch Size:   256)\n    Iter  5288\t      0.06918960 (Batch Size:   256)\n    Iter  5289\t      0.07210161 (Batch Size:   256)\n    Iter  5290\t      0.06924233 (Batch Size:   256)\n    Iter  5291\t      0.07424805 (Batch Size:   256)\n    Iter  5292\t      0.07193375 (Batch Size:   256)\n    Iter  5293\t      0.06875211 (Batch Size:   256)\n    Iter  5294\t      0.06999725 (Batch Size:   256)\n    Iter  5295\t      0.07106759 (Batch Size:   256)\n    Iter  5296\t      0.06960108 (Batch Size:   256)\n    Iter  5297\t      0.06673615 (Batch Size:   256)\n    Iter  5298\t      0.07036122 (Batch Size:   256)\n    Iter  5299\t      0.07035256 (Batch Size:   256)\n    Iter  5300\t      0.07127356 (Batch Size:   256)\n    Iter  5301\t      0.07353132 (Batch Size:   256)\n    Iter  5302\t      0.07203600 (Batch Size:   256)\n    Iter  5303\t      0.07270846 (Batch Size:   256)\n    Iter  5304\t      0.06844453 (Batch Size:   256)\n    Iter  5305\t      0.07173557 (Batch Size:   256)\n    Iter  5306\t      0.07060990 (Batch Size:   256)\n    Iter  5307\t      0.06859539 (Batch Size:   256)\n    Iter  5308\t      0.07143781 (Batch Size:   256)\n    Iter  5309\t      0.06846765 (Batch Size:   256)\n    Iter  5310\t      0.07268486 (Batch Size:   256)\n    Iter  5311\t      0.06935303 (Batch Size:   256)\n    Iter  5312\t      0.07357050 (Batch Size:   256)\n    Iter  5313\t      0.06991698 (Batch Size:   256)\n    Iter  5314\t      0.08664572 (Batch Size:   256)\n    Iter  5315\t      0.09344721 (Batch Size:   256)\n    Iter  5316\t      0.08419465 (Batch Size:   256)\n    Iter  5317\t      0.07591537 (Batch Size:   256)\n    Iter  5318\t      0.07606376 (Batch Size:   256)\n    Iter  5319\t      0.07363543 (Batch Size:   256)\n    Iter  5320\t      0.06955804 (Batch Size:   256)\n    Iter  5321\t      0.06638506 (Batch Size:   256)\n    Iter  5322\t      0.06948034 (Batch Size:   256)\n    Iter  5323\t      0.07122941 (Batch Size:   256)\n    Iter  5324\t      0.07817223 (Batch Size:   256)\n    Iter  5325\t      0.07376384 (Batch Size:   256)\n    Iter  5326\t      0.07114961 (Batch Size:   256)\n    Iter  5327\t      0.07819299 (Batch Size:   256)\n    Iter  5328\t      0.06813914 (Batch Size:   256)\n    Iter  5329\t      0.07066231 (Batch Size:   256)\n    Iter  5330\t      0.06903699 (Batch Size:   256)\n    Iter  5331\t      0.07020687 (Batch Size:   256)\n    Iter  5332\t      0.06843379 (Batch Size:   256)\n    Iter  5333\t      0.06947839 (Batch Size:   256)\n    Iter  5334\t      0.06974609 (Batch Size:   256)\n    Iter  5335\t      0.07086564 (Batch Size:   256)\n    Iter  5336\t      0.07086677 (Batch Size:   256)\n    Iter  5337\t      0.06818933 (Batch Size:   256)\n    Iter  5338\t      0.07013741 (Batch Size:   256)\n    Iter  5339\t      0.07197253 (Batch Size:   256)\n    Iter  5340\t      0.07577940 (Batch Size:   256)\n    Iter  5341\t      0.09939260 (Batch Size:   256)\n    Iter  5342\t      0.07305316 (Batch Size:   256)\n    Iter  5343\t      0.07262562 (Batch Size:   256)\n    Iter  5344\t      0.07028550 (Batch Size:   256)\n    Iter  5345\t      0.06744897 (Batch Size:   256)\n    Iter  5346\t      0.06789620 (Batch Size:   256)\n    Iter  5347\t      0.06705494 (Batch Size:   256)\n    Iter  5348\t      0.07045685 (Batch Size:   256)\n    Iter  5349\t      0.07215360 (Batch Size:   256)\n    Iter  5350\t      0.07819447 (Batch Size:   256)\n    Iter  5351\t      0.08134820 (Batch Size:   256)\n    Iter  5352\t      0.07765672 (Batch Size:   256)\n    Iter  5353\t      0.07090134 (Batch Size:   256)\n    Iter  5354\t      0.07031263 (Batch Size:   256)\n    Iter  5355\t      0.06927529 (Batch Size:   256)\n    Iter  5356\t      0.07133893 (Batch Size:   256)\n    Iter  5357\t      0.07205030 (Batch Size:   256)\n    Iter  5358\t      0.07536883 (Batch Size:   256)\n    Iter  5359\t      0.08070173 (Batch Size:   256)\n    Iter  5360\t      0.07657531 (Batch Size:   256)\n    Iter  5361\t      0.07030216 (Batch Size:   256)\n    Iter  5362\t      0.07365071 (Batch Size:   256)\n    Iter  5363\t      0.08447823 (Batch Size:   256)\n    Iter  5364\t      0.07938796 (Batch Size:   256)\n    Iter  5365\t      0.07061294 (Batch Size:   256)\n    Iter  5366\t      0.07804045 (Batch Size:   256)\n    Iter  5367\t      0.07761567 (Batch Size:   256)\n    Iter  5368\t      0.07728407 (Batch Size:   256)\n    Iter  5369\t      0.07065077 (Batch Size:   256)\n    Iter  5370\t      0.07576734 (Batch Size:   256)\n    Iter  5371\t      0.07168862 (Batch Size:   256)\n    Iter  5372\t      0.07024274 (Batch Size:   256)\n    Iter  5373\t      0.06663679 (Batch Size:   256)\n    Iter  5374\t      0.07640434 (Batch Size:   256)\n    Iter  5375\t      0.07287413 (Batch Size:   256)\n    Iter  5376\t      0.07844359 (Batch Size:   256)\n    Iter  5377\t      0.07770168 (Batch Size:   256)\n    Iter  5378\t      0.07840766 (Batch Size:   256)\n    Iter  5379\t      0.07475711 (Batch Size:   256)\n    Iter  5380\t      0.06713665 (Batch Size:   256)\n    Iter  5381\t      0.06729379 (Batch Size:   256)\n    Iter  5382\t      0.06820279 (Batch Size:   256)\n    Iter  5383\t      0.06869332 (Batch Size:   256)\n    Iter  5384\t      0.07330476 (Batch Size:   256)\n    Iter  5385\t      0.06996126 (Batch Size:   256)\n    Iter  5386\t      0.08102659 (Batch Size:   256)\n    Iter  5387\t      0.08658231 (Batch Size:   256)\n    Iter  5388\t      0.07296297 (Batch Size:   256)\n    Iter  5389\t      0.06593237 (Batch Size:   256)\n    Iter  5390\t      0.06945454 (Batch Size:   256)\n    Iter  5391\t      0.07196967 (Batch Size:   256)\n    Iter  5392\t      0.07003837 (Batch Size:   256)\n    Iter  5393\t      0.07852365 (Batch Size:   256)\n    Iter  5394\t      0.07442163 (Batch Size:   256)\n    Iter  5395\t      0.06877690 (Batch Size:   256)\n    Iter  5396\t      0.07558433 (Batch Size:   256)\n    Iter  5397\t      0.07263751 (Batch Size:   256)\n    Iter  5398\t      0.07197686 (Batch Size:   256)\n    Iter  5399\t      0.07312754 (Batch Size:   256)\n    Iter  5400\t      0.07380754 (Batch Size:   256)\n    Iter  5401\t      0.07152987 (Batch Size:   256)\n    Iter  5402\t      0.07053248 (Batch Size:   256)\n    Iter  5403\t      0.06841706 (Batch Size:   256)\n    Iter  5404\t      0.07009957 (Batch Size:   256)\n    Iter  5405\t      0.07055146 (Batch Size:   256)\n    Iter  5406\t      0.06572529 (Batch Size:   256)\n    Iter  5407\t      0.06910456 (Batch Size:   256)\n    Iter  5408\t      0.06869305 (Batch Size:   256)\n    Iter  5409\t      0.07114425 (Batch Size:   256)\n    Iter  5410\t      0.07185215 (Batch Size:   256)\n    Iter  5411\t      0.07527301 (Batch Size:   256)\n    Iter  5412\t      0.08244519 (Batch Size:   256)\n    Iter  5413\t      0.07355629 (Batch Size:   256)\n    Iter  5414\t      0.07361799 (Batch Size:   256)\n    Iter  5415\t      0.06834348 (Batch Size:   256)\n    Iter  5416\t      0.07276453 (Batch Size:   256)\n    Iter  5417\t      0.08493272 (Batch Size:   256)\n    Iter  5418\t      0.08844756 (Batch Size:   256)\n    Iter  5419\t      0.07828094 (Batch Size:   256)\n    Iter  5420\t      0.09154958 (Batch Size:   256)\n    Iter  5421\t      0.08904776 (Batch Size:   256)\n    Iter  5422\t      0.08031588 (Batch Size:   256)\n    Iter  5423\t      0.08792594 (Batch Size:   256)\n    Iter  5424\t      0.07832458 (Batch Size:   256)\n    Iter  5425\t      0.07278931 (Batch Size:   256)\n    Iter  5426\t      0.07462989 (Batch Size:   256)\n    Iter  5427\t      0.07374566 (Batch Size:   256)\n    Iter  5428\t      0.08015048 (Batch Size:   256)\n    Iter  5429\t      0.07004647 (Batch Size:   256)\n    Iter  5430\t      0.07066409 (Batch Size:   256)\n    Iter  5431\t      0.07040198 (Batch Size:   256)\n    Iter  5432\t      0.06789474 (Batch Size:   256)\n    Iter  5433\t      0.07493426 (Batch Size:   256)\n    Iter  5434\t      0.07552533 (Batch Size:   256)\n    Iter  5435\t      0.07412929 (Batch Size:   256)\n    Iter  5436\t      0.07865923 (Batch Size:   256)\n    Iter  5437\t      0.07918324 (Batch Size:   256)\n    Iter  5438\t      0.08237367 (Batch Size:   256)\n    Iter  5439\t      0.09357699 (Batch Size:   256)\n    Iter  5440\t      0.08617401 (Batch Size:   256)\n    Iter  5441\t      0.07855077 (Batch Size:   256)\n    Iter  5442\t      0.07380998 (Batch Size:   256)\n    Iter  5443\t      0.06652582 (Batch Size:   256)\n    Iter  5444\t      0.07773206 (Batch Size:   256)\n    Iter  5445\t      0.08408294 (Batch Size:   256)\n    Iter  5446\t      0.09235163 (Batch Size:   256)\n    Iter  5447\t      0.09244371 (Batch Size:   256)\n    Iter  5448\t      0.10359625 (Batch Size:   256)\n    Iter  5449\t      0.07654608 (Batch Size:   256)\n    Iter  5450\t      0.07214276 (Batch Size:   256)\n    Iter  5451\t      0.06843960 (Batch Size:   256)\n    Iter  5452\t      0.06763116 (Batch Size:   256)\n    Iter  5453\t      0.06949424 (Batch Size:   256)\n    Iter  5454\t      0.07091301 (Batch Size:   256)\n    Iter  5455\t      0.07246415 (Batch Size:   256)\n    Iter  5456\t      0.07217942 (Batch Size:   256)\n    Iter  5457\t      0.07027474 (Batch Size:   256)\n    Iter  5458\t      0.06961963 (Batch Size:   256)\n    Iter  5459\t      0.07061304 (Batch Size:   256)\n    Iter  5460\t      0.06785399 (Batch Size:   256)\n    Iter  5461\t      0.07078534 (Batch Size:   256)\n    Iter  5462\t      0.07059416 (Batch Size:   256)\n    Iter  5463\t      0.07516487 (Batch Size:   256)\n    Iter  5464\t      0.07422609 (Batch Size:   256)\n    Iter  5465\t      0.07087480 (Batch Size:   256)\n    Iter  5466\t      0.06837988 (Batch Size:   256)\n    Iter  5467\t      0.07234778 (Batch Size:   256)\n    Iter  5468\t      0.06975866 (Batch Size:   256)\n    Iter  5469\t      0.07226870 (Batch Size:   256)\n    Iter  5470\t      0.07299049 (Batch Size:   256)\n    Iter  5471\t      0.07556538 (Batch Size:   256)\n    Iter  5472\t      0.07155090 (Batch Size:   256)\n    Iter  5473\t      0.06917295 (Batch Size:   256)\n    Iter  5474\t      0.07376685 (Batch Size:   256)\n    Iter  5475\t      0.07794683 (Batch Size:   256)\n    Iter  5476\t      0.07191635 (Batch Size:   256)\n    Iter  5477\t      0.06916918 (Batch Size:   256)\n    Iter  5478\t      0.07016867 (Batch Size:   256)\n    Iter  5479\t      0.07376871 (Batch Size:   256)\n    Iter  5480\t      0.07743095 (Batch Size:   256)\n    Iter  5481\t      0.06760441 (Batch Size:   256)\n    Iter  5482\t      0.07073740 (Batch Size:   256)\n    Iter  5483\t      0.07491729 (Batch Size:   256)\n    Iter  5484\t      0.07487837 (Batch Size:   256)\n    Iter  5485\t      0.07376221 (Batch Size:   256)\n    Iter  5486\t      0.06933084 (Batch Size:   256)\n    Iter  5487\t      0.06912998 (Batch Size:   256)\n    Iter  5488\t      0.06701481 (Batch Size:   256)\n    Iter  5489\t      0.07061354 (Batch Size:   256)\n    Iter  5490\t      0.06792243 (Batch Size:   256)\n    Iter  5491\t      0.06469370 (Batch Size:   256)\n    Iter  5492\t      0.08009616 (Batch Size:   256)\n    Iter  5493\t      0.08166825 (Batch Size:   256)\n    Iter  5494\t      0.06816481 (Batch Size:   256)\n    Iter  5495\t      0.07041871 (Batch Size:   256)\n    Iter  5496\t      0.06706424 (Batch Size:   256)\n    Iter  5497\t      0.06729448 (Batch Size:   256)\n    Iter  5498\t      0.06906926 (Batch Size:   256)\n    Iter  5499\t      0.06526852 (Batch Size:   256)\n    Iter  5500\t      0.07207145 (Batch Size:   256)\n    Iter  5501\t      0.06809068 (Batch Size:   256)\n    Iter  5502\t      0.06995306 (Batch Size:   256)\n    Iter  5503\t      0.06557241 (Batch Size:   256)\n    Iter  5504\t      0.07156987 (Batch Size:   256)\n    Iter  5505\t      0.08124823 (Batch Size:   256)\n    Iter  5506\t      0.08242414 (Batch Size:   256)\n    Iter  5507\t      0.07630021 (Batch Size:   256)\n    Iter  5508\t      0.07215426 (Batch Size:   256)\n    Iter  5509\t      0.07384935 (Batch Size:   256)\n    Iter  5510\t      0.07359724 (Batch Size:   256)\n    Iter  5511\t      0.07822567 (Batch Size:   256)\n    Iter  5512\t      0.07290902 (Batch Size:   256)\n    Iter  5513\t      0.06645471 (Batch Size:   256)\n    Iter  5514\t      0.07121141 (Batch Size:   256)\n    Iter  5515\t      0.06993814 (Batch Size:   256)\n    Iter  5516\t      0.07432665 (Batch Size:   256)\n    Iter  5517\t      0.07055606 (Batch Size:   256)\n    Iter  5518\t      0.07291990 (Batch Size:   256)\n    Iter  5519\t      0.07249418 (Batch Size:   256)\n    Iter  5520\t      0.06805796 (Batch Size:   256)\n    Iter  5521\t      0.07049086 (Batch Size:   256)\n    Iter  5522\t      0.07357856 (Batch Size:   256)\n    Iter  5523\t      0.07502177 (Batch Size:   256)\n    Iter  5524\t      0.07486303 (Batch Size:   256)\n    Iter  5525\t      0.06960129 (Batch Size:   256)\n    Iter  5526\t      0.07636703 (Batch Size:   256)\n    Iter  5527\t      0.07190453 (Batch Size:   256)\n    Iter  5528\t      0.07295322 (Batch Size:   256)\n    Iter  5529\t      0.07099300 (Batch Size:   256)\n    Iter  5530\t      0.07577144 (Batch Size:   256)\n    Iter  5531\t      0.07153368 (Batch Size:   256)\n    Iter  5532\t      0.07313853 (Batch Size:   256)\n    Iter  5533\t      0.06602434 (Batch Size:   256)\n    Iter  5534\t      0.06885989 (Batch Size:   256)\n    Iter  5535\t      0.06533083 (Batch Size:   256)\n    Iter  5536\t      0.06714350 (Batch Size:   256)\n    Iter  5537\t      0.06694986 (Batch Size:   256)\n    Iter  5538\t      0.07027105 (Batch Size:   256)\n    Iter  5539\t      0.07274319 (Batch Size:   256)\n    Iter  5540\t      0.06886954 (Batch Size:   256)\n    Iter  5541\t      0.06765216 (Batch Size:   256)\n    Iter  5542\t      0.07022474 (Batch Size:   256)\n    Iter  5543\t      0.06726957 (Batch Size:   256)\n    Iter  5544\t      0.06776826 (Batch Size:   256)\n    Iter  5545\t      0.06558080 (Batch Size:   256)\n    Iter  5546\t      0.06972966 (Batch Size:   256)\n    Iter  5547\t      0.06926225 (Batch Size:   256)\n    Iter  5548\t      0.07826856 (Batch Size:   256)\n    Iter  5549\t      0.08658847 (Batch Size:   256)\n    Iter  5550\t      0.07112968 (Batch Size:   256)\n    Iter  5551\t      0.07184652 (Batch Size:   256)\n    Iter  5552\t      0.06629485 (Batch Size:   256)\n    Iter  5553\t      0.07437118 (Batch Size:   256)\n    Iter  5554\t      0.06925869 (Batch Size:   256)\n    Iter  5555\t      0.07669377 (Batch Size:   256)\n    Iter  5556\t      0.06840017 (Batch Size:   256)\n    Iter  5557\t      0.06770928 (Batch Size:   256)\n    Iter  5558\t      0.07594991 (Batch Size:   256)\n    Iter  5559\t      0.07814841 (Batch Size:   256)\n    Iter  5560\t      0.07852909 (Batch Size:   256)\n    Iter  5561\t      0.06995881 (Batch Size:   256)\n    Iter  5562\t      0.07727425 (Batch Size:   256)\n    Iter  5563\t      0.07894736 (Batch Size:   256)\n    Iter  5564\t      0.07413200 (Batch Size:   256)\n    Iter  5565\t      0.07645172 (Batch Size:   256)\n    Iter  5566\t      0.07058893 (Batch Size:   256)\n    Iter  5567\t      0.07067546 (Batch Size:   256)\n    Iter  5568\t      0.07061756 (Batch Size:   256)\n    Iter  5569\t      0.07262302 (Batch Size:   256)\n    Iter  5570\t      0.07225783 (Batch Size:   256)\n    Iter  5571\t      0.06926879 (Batch Size:   256)\n    Iter  5572\t      0.07607669 (Batch Size:   256)\n    Iter  5573\t      0.07042615 (Batch Size:   256)\n    Iter  5574\t      0.06971291 (Batch Size:   256)\n    Iter  5575\t      0.06757497 (Batch Size:   256)\n    Iter  5576\t      0.07005710 (Batch Size:   256)\n    Iter  5577\t      0.07033424 (Batch Size:   256)\n    Iter  5578\t      0.06880742 (Batch Size:   256)\n    Iter  5579\t      0.06769145 (Batch Size:   256)\n    Iter  5580\t      0.06700582 (Batch Size:   256)\n    Iter  5581\t      0.07689979 (Batch Size:   256)\n    Iter  5582\t      0.07170379 (Batch Size:   256)\n    Iter  5583\t      0.07182776 (Batch Size:   256)\n    Iter  5584\t      0.06880394 (Batch Size:   256)\n    Iter  5585\t      0.06533206 (Batch Size:   256)\n    Iter  5586\t      0.07827275 (Batch Size:   256)\n    Iter  5587\t      0.07202033 (Batch Size:   256)\n    Iter  5588\t      0.07086769 (Batch Size:   256)\n    Iter  5589\t      0.07666630 (Batch Size:   256)\n    Iter  5590\t      0.07508979 (Batch Size:   256)\n    Iter  5591\t      0.07157603 (Batch Size:   256)\n    Iter  5592\t      0.08996128 (Batch Size:   256)\n    Iter  5593\t      0.07157091 (Batch Size:   256)\n    Iter  5594\t      0.06839221 (Batch Size:   256)\n    Iter  5595\t      0.06917167 (Batch Size:   256)\n    Iter  5596\t      0.07904663 (Batch Size:   256)\n    Iter  5597\t      0.06970601 (Batch Size:   256)\n    Iter  5598\t      0.07186903 (Batch Size:   256)\n    Iter  5599\t      0.07396561 (Batch Size:   256)\n    Iter  5600\t      0.06845649 (Batch Size:   256)\n    Iter  5601\t      0.07140364 (Batch Size:   256)\n    Iter  5602\t      0.07283625 (Batch Size:   256)\n    Iter  5603\t      0.06659519 (Batch Size:   256)\n    Iter  5604\t      0.07131426 (Batch Size:   256)\n    Iter  5605\t      0.06597879 (Batch Size:   256)\n    Iter  5606\t      0.06920180 (Batch Size:   256)\n    Iter  5607\t      0.07205011 (Batch Size:   256)\n    Iter  5608\t      0.07116633 (Batch Size:   256)\n    Iter  5609\t      0.07147311 (Batch Size:   256)\n    Iter  5610\t      0.06881637 (Batch Size:   256)\n    Iter  5611\t      0.07102868 (Batch Size:   256)\n    Iter  5612\t      0.07056621 (Batch Size:   256)\n    Iter  5613\t      0.07029105 (Batch Size:   256)\n    Iter  5614\t      0.06815666 (Batch Size:   256)\n    Iter  5615\t      0.07013384 (Batch Size:   256)\n    Iter  5616\t      0.07759144 (Batch Size:   256)\n    Iter  5617\t      0.07272580 (Batch Size:   256)\n    Iter  5618\t      0.07189877 (Batch Size:   256)\n    Iter  5619\t      0.07174622 (Batch Size:   256)\n    Iter  5620\t      0.06563214 (Batch Size:   256)\n    Iter  5621\t      0.06948134 (Batch Size:   256)\n    Iter  5622\t      0.06782239 (Batch Size:   256)\n    Iter  5623\t      0.07001908 (Batch Size:   256)\n    Iter  5624\t      0.07340397 (Batch Size:   256)\n    Iter  5625\t      0.06980182 (Batch Size:   256)\n    Iter  5626\t      0.07138314 (Batch Size:   256)\n    Iter  5627\t      0.07183489 (Batch Size:   256)\n    Iter  5628\t      0.06959830 (Batch Size:   256)\n    Iter  5629\t      0.06856336 (Batch Size:   256)\n    Iter  5630\t      0.06844293 (Batch Size:   256)\n    Iter  5631\t      0.08106673 (Batch Size:   256)\n    Iter  5632\t      0.07477370 (Batch Size:   256)\n    Iter  5633\t      0.07092436 (Batch Size:   256)\n    Iter  5634\t      0.07555843 (Batch Size:   256)\n    Iter  5635\t      0.07514948 (Batch Size:   256)\n    Iter  5636\t      0.07304570 (Batch Size:   256)\n    Iter  5637\t      0.06936254 (Batch Size:   256)\n    Iter  5638\t      0.07727553 (Batch Size:   256)\n    Iter  5639\t      0.07523496 (Batch Size:   256)\n    Iter  5640\t      0.06922158 (Batch Size:   256)\n    Iter  5641\t      0.06628367 (Batch Size:   256)\n    Iter  5642\t      0.06685085 (Batch Size:   256)\n    Iter  5643\t      0.07274778 (Batch Size:   256)\n    Iter  5644\t      0.07037526 (Batch Size:   256)\n    Iter  5645\t      0.06757220 (Batch Size:   256)\n    Iter  5646\t      0.06421404 (Batch Size:   256)\n    Iter  5647\t      0.07002743 (Batch Size:   256)\n    Iter  5648\t      0.06881983 (Batch Size:   256)\n    Iter  5649\t      0.06814453 (Batch Size:   256)\n    Iter  5650\t      0.06813579 (Batch Size:   256)\n    Iter  5651\t      0.07206558 (Batch Size:   256)\n    Iter  5652\t      0.06656504 (Batch Size:   256)\n    Iter  5653\t      0.07125134 (Batch Size:   256)\n    Iter  5654\t      0.07012868 (Batch Size:   256)\n    Iter  5655\t      0.06842451 (Batch Size:   256)\n    Iter  5656\t      0.06625892 (Batch Size:   256)\n    Iter  5657\t      0.07242207 (Batch Size:   256)\n    Iter  5658\t      0.07107269 (Batch Size:   256)\n    Iter  5659\t      0.07197147 (Batch Size:   256)\n    Iter  5660\t      0.07063813 (Batch Size:   256)\n    Iter  5661\t      0.07033849 (Batch Size:   256)\n    Iter  5662\t      0.07315891 (Batch Size:   256)\n    Iter  5663\t      0.07027030 (Batch Size:   256)\n    Iter  5664\t      0.08485883 (Batch Size:   256)\n    Iter  5665\t      0.08150754 (Batch Size:   256)\n    Iter  5666\t      0.07961216 (Batch Size:   256)\n    Iter  5667\t      0.07279148 (Batch Size:   256)\n    Iter  5668\t      0.07219523 (Batch Size:   256)\n    Iter  5669\t      0.07046358 (Batch Size:   256)\n    Iter  5670\t      0.06912589 (Batch Size:   256)\n    Iter  5671\t      0.09279474 (Batch Size:   256)\n    Iter  5672\t      0.08548924 (Batch Size:   256)\n    Iter  5673\t      0.09136942 (Batch Size:   256)\n    Iter  5674\t      0.08717055 (Batch Size:   256)\n    Iter  5675\t      0.07357077 (Batch Size:   256)\n    Iter  5676\t      0.07342758 (Batch Size:   256)\n    Iter  5677\t      0.07338072 (Batch Size:   256)\n    Iter  5678\t      0.06554435 (Batch Size:   256)\n    Iter  5679\t      0.07141527 (Batch Size:   256)\n    Iter  5680\t      0.06855202 (Batch Size:   256)\n    Iter  5681\t      0.07165863 (Batch Size:   256)\n    Iter  5682\t      0.07381759 (Batch Size:   256)\n    Iter  5683\t      0.07000146 (Batch Size:   256)\n    Iter  5684\t      0.06920250 (Batch Size:   256)\n    Iter  5685\t      0.07386036 (Batch Size:   256)\n    Iter  5686\t      0.07636395 (Batch Size:   256)\n    Iter  5687\t      0.06736315 (Batch Size:   256)\n    Iter  5688\t      0.06647164 (Batch Size:   256)\n    Iter  5689\t      0.07028889 (Batch Size:   256)\n    Iter  5690\t      0.07941412 (Batch Size:   256)\n    Iter  5691\t      0.07501979 (Batch Size:   256)\n    Iter  5692\t      0.07110146 (Batch Size:   256)\n    Iter  5693\t      0.07572174 (Batch Size:   256)\n    Iter  5694\t      0.06510377 (Batch Size:   256)\n    Iter  5695\t      0.06843779 (Batch Size:   256)\n    Iter  5696\t      0.06745618 (Batch Size:   256)\n    Iter  5697\t      0.07184151 (Batch Size:   256)\n    Iter  5698\t      0.06548584 (Batch Size:   256)\n    Iter  5699\t      0.07510604 (Batch Size:   256)\n    Iter  5700\t      0.06902406 (Batch Size:   256)\n    Iter  5701\t      0.06825188 (Batch Size:   256)\n    Iter  5702\t      0.07056400 (Batch Size:   256)\n    Iter  5703\t      0.06745033 (Batch Size:   256)\n    Iter  5704\t      0.06985631 (Batch Size:   256)\n    Iter  5705\t      0.06838006 (Batch Size:   256)\n    Iter  5706\t      0.07093723 (Batch Size:   256)\n    Iter  5707\t      0.07105579 (Batch Size:   256)\n    Iter  5708\t      0.06593097 (Batch Size:   256)\n    Iter  5709\t      0.07200886 (Batch Size:   256)\n    Iter  5710\t      0.07992608 (Batch Size:   256)\n    Iter  5711\t      0.06599349 (Batch Size:   256)\n    Iter  5712\t      0.06781467 (Batch Size:   256)\n    Iter  5713\t      0.06342364 (Batch Size:   256)\n    Iter  5714\t      0.06336161 (Batch Size:   256)\n    Iter  5715\t      0.07366692 (Batch Size:   256)\n    Iter  5716\t      0.07637609 (Batch Size:   256)\n    Iter  5717\t      0.07783290 (Batch Size:   256)\n    Iter  5718\t      0.07174030 (Batch Size:   256)\n    Iter  5719\t      0.07277666 (Batch Size:   256)\n    Iter  5720\t      0.07877302 (Batch Size:   256)\n    Iter  5721\t      0.06903424 (Batch Size:   256)\n    Iter  5722\t      0.07409319 (Batch Size:   256)\n    Iter  5723\t      0.08290865 (Batch Size:   256)\n    Iter  5724\t      0.07714622 (Batch Size:   256)\n    Iter  5725\t      0.07209194 (Batch Size:   256)\n    Iter  5726\t      0.07359932 (Batch Size:   256)\n    Iter  5727\t      0.07241809 (Batch Size:   256)\n    Iter  5728\t      0.06576161 (Batch Size:   256)\n    Iter  5729\t      0.07244702 (Batch Size:   256)\n    Iter  5730\t      0.07333630 (Batch Size:   256)\n    Iter  5731\t      0.06865036 (Batch Size:   256)\n    Iter  5732\t      0.06800055 (Batch Size:   256)\n    Iter  5733\t      0.07234446 (Batch Size:   256)\n    Iter  5734\t      0.07182126 (Batch Size:   256)\n    Iter  5735\t      0.06654518 (Batch Size:   256)\n    Iter  5736\t      0.06556068 (Batch Size:   256)\n    Iter  5737\t      0.06625303 (Batch Size:   256)\n    Iter  5738\t      0.06850993 (Batch Size:   256)\n    Iter  5739\t      0.06690522 (Batch Size:   256)\n    Iter  5740\t      0.07139354 (Batch Size:   256)\n    Iter  5741\t      0.07264291 (Batch Size:   256)\n    Iter  5742\t      0.06917219 (Batch Size:   256)\n    Iter  5743\t      0.06603869 (Batch Size:   256)\n    Iter  5744\t      0.06671417 (Batch Size:   256)\n    Iter  5745\t      0.06896237 (Batch Size:   256)\n    Iter  5746\t      0.07004953 (Batch Size:   256)\n    Iter  5747\t      0.07224278 (Batch Size:   256)\n    Iter  5748\t      0.07388589 (Batch Size:   256)\n    Iter  5749\t      0.06790730 (Batch Size:   256)\n    Iter  5750\t      0.06835072 (Batch Size:   256)\n    Iter  5751\t      0.07847673 (Batch Size:   256)\n    Iter  5752\t      0.07598244 (Batch Size:   256)\n    Iter  5753\t      0.07340323 (Batch Size:   256)\n    Iter  5754\t      0.08601989 (Batch Size:   256)\n    Iter  5755\t      0.08808344 (Batch Size:   256)\n    Iter  5756\t      0.07920077 (Batch Size:   256)\n    Iter  5757\t      0.06454525 (Batch Size:   256)\n    Iter  5758\t      0.07316556 (Batch Size:   256)\n    Iter  5759\t      0.07533206 (Batch Size:   256)\n    Iter  5760\t      0.07046487 (Batch Size:   256)\n    Iter  5761\t      0.07324003 (Batch Size:   256)\n    Iter  5762\t      0.06863785 (Batch Size:   256)\n    Iter  5763\t      0.07724185 (Batch Size:   256)\n    Iter  5764\t      0.07325961 (Batch Size:   256)\n    Iter  5765\t      0.07345789 (Batch Size:   256)\n    Iter  5766\t      0.06723418 (Batch Size:   256)\n    Iter  5767\t      0.06773410 (Batch Size:   256)\n    Iter  5768\t      0.07126866 (Batch Size:   256)\n    Iter  5769\t      0.07115994 (Batch Size:   256)\n    Iter  5770\t      0.06929909 (Batch Size:   256)\n    Iter  5771\t      0.06464110 (Batch Size:   256)\n    Iter  5772\t      0.06849353 (Batch Size:   256)\n    Iter  5773\t      0.07352620 (Batch Size:   256)\n    Iter  5774\t      0.07225703 (Batch Size:   256)\n    Iter  5775\t      0.06848203 (Batch Size:   256)\n    Iter  5776\t      0.06824704 (Batch Size:   256)\n    Iter  5777\t      0.07000702 (Batch Size:   256)\n    Iter  5778\t      0.06716348 (Batch Size:   256)\n    Iter  5779\t      0.07953138 (Batch Size:   256)\n    Iter  5780\t      0.07407079 (Batch Size:   256)\n    Iter  5781\t      0.06930777 (Batch Size:   256)\n    Iter  5782\t      0.06969727 (Batch Size:   256)\n    Iter  5783\t      0.06771752 (Batch Size:   256)\n    Iter  5784\t      0.07494719 (Batch Size:   256)\n    Iter  5785\t      0.07047849 (Batch Size:   256)\n    Iter  5786\t      0.07048640 (Batch Size:   256)\n    Iter  5787\t      0.07073132 (Batch Size:   256)\n    Iter  5788\t      0.07836753 (Batch Size:   256)\n    Iter  5789\t      0.06924129 (Batch Size:   256)\n    Iter  5790\t      0.07004846 (Batch Size:   256)\n    Iter  5791\t      0.07026487 (Batch Size:   256)\n    Iter  5792\t      0.06820215 (Batch Size:   256)\n    Iter  5793\t      0.06816659 (Batch Size:   256)\n    Iter  5794\t      0.06662780 (Batch Size:   256)\n    Iter  5795\t      0.07330999 (Batch Size:   256)\n    Iter  5796\t      0.07938961 (Batch Size:   256)\n    Iter  5797\t      0.07435550 (Batch Size:   256)\n    Iter  5798\t      0.09054853 (Batch Size:   256)\n    Iter  5799\t      0.06855760 (Batch Size:   256)\n    Iter  5800\t      0.06434270 (Batch Size:   256)\n    Iter  5801\t      0.07115151 (Batch Size:   256)\n    Iter  5802\t      0.06622156 (Batch Size:   256)\n    Iter  5803\t      0.06786178 (Batch Size:   256)\n    Iter  5804\t      0.07354609 (Batch Size:   256)\n    Iter  5805\t      0.07097864 (Batch Size:   256)\n    Iter  5806\t      0.07010882 (Batch Size:   256)\n    Iter  5807\t      0.07427562 (Batch Size:   256)\n    Iter  5808\t      0.06892633 (Batch Size:   256)\n    Iter  5809\t      0.06742851 (Batch Size:   256)\n    Iter  5810\t      0.06988523 (Batch Size:   256)\n    Iter  5811\t      0.07259949 (Batch Size:   256)\n    Iter  5812\t      0.06606884 (Batch Size:   256)\n    Iter  5813\t      0.06838092 (Batch Size:   256)\n    Iter  5814\t      0.06627509 (Batch Size:   256)\n    Iter  5815\t      0.06861476 (Batch Size:   256)\n    Iter  5816\t      0.06490867 (Batch Size:   256)\n    Iter  5817\t      0.06809437 (Batch Size:   256)\n    Iter  5818\t      0.06897850 (Batch Size:   256)\n    Iter  5819\t      0.06864695 (Batch Size:   256)\n    Iter  5820\t      0.07603986 (Batch Size:   256)\n    Iter  5821\t      0.07378682 (Batch Size:   256)\n    Iter  5822\t      0.06773130 (Batch Size:   256)\n    Iter  5823\t      0.07255499 (Batch Size:   256)\n    Iter  5824\t      0.08143160 (Batch Size:   256)\n    Iter  5825\t      0.07701433 (Batch Size:   256)\n    Iter  5826\t      0.06828595 (Batch Size:   256)\n    Iter  5827\t      0.06880976 (Batch Size:   256)\n    Iter  5828\t      0.07125907 (Batch Size:   256)\n    Iter  5829\t      0.07019053 (Batch Size:   256)\n    Iter  5830\t      0.07192757 (Batch Size:   256)\n    Iter  5831\t      0.07050869 (Batch Size:   256)\n    Iter  5832\t      0.06822362 (Batch Size:   256)\n    Iter  5833\t      0.07360326 (Batch Size:   256)\n    Iter  5834\t      0.08085425 (Batch Size:   256)\n    Iter  5835\t      0.07514285 (Batch Size:   256)\n    Iter  5836\t      0.07021289 (Batch Size:   256)\n    Iter  5837\t      0.07075976 (Batch Size:   256)\n    Iter  5838\t      0.06704251 (Batch Size:   256)\n    Iter  5839\t      0.07192487 (Batch Size:   256)\n    Iter  5840\t      0.07025023 (Batch Size:   256)\n    Iter  5841\t      0.07817520 (Batch Size:   256)\n    Iter  5842\t      0.07457815 (Batch Size:   256)\n    Iter  5843\t      0.09071549 (Batch Size:   256)\n    Iter  5844\t      0.07900990 (Batch Size:   256)\n    Iter  5845\t      0.08965244 (Batch Size:   256)\n    Iter  5846\t      0.08617625 (Batch Size:   256)\n    Iter  5847\t      0.07954475 (Batch Size:   256)\n    Iter  5848\t      0.07524787 (Batch Size:   256)\n    Iter  5849\t      0.07540389 (Batch Size:   256)\n    Iter  5850\t      0.07734945 (Batch Size:   256)\n    Iter  5851\t      0.07679460 (Batch Size:   256)\n    Iter  5852\t      0.07781521 (Batch Size:   256)\n    Iter  5853\t      0.06748129 (Batch Size:   256)\n    Iter  5854\t      0.06814739 (Batch Size:   256)\n    Iter  5855\t      0.07134040 (Batch Size:   256)\n    Iter  5856\t      0.07577222 (Batch Size:   256)\n    Iter  5857\t      0.07593646 (Batch Size:   256)\n    Iter  5858\t      0.07945196 (Batch Size:   256)\n    Iter  5859\t      0.07695036 (Batch Size:   256)\n    Iter  5860\t      0.08120869 (Batch Size:   256)\n    Iter  5861\t      0.07796898 (Batch Size:   256)\n    Iter  5862\t      0.07515796 (Batch Size:   256)\n    Iter  5863\t      0.07161996 (Batch Size:   256)\n    Iter  5864\t      0.06832510 (Batch Size:   256)\n    Iter  5865\t      0.06949486 (Batch Size:   256)\n    Iter  5866\t      0.07223895 (Batch Size:   256)\n    Iter  5867\t      0.07062302 (Batch Size:   256)\n    Iter  5868\t      0.06640918 (Batch Size:   256)\n    Iter  5869\t      0.07379483 (Batch Size:   256)\n    Iter  5870\t      0.07111246 (Batch Size:   256)\n    Iter  5871\t      0.06928319 (Batch Size:   256)\n    Iter  5872\t      0.07139460 (Batch Size:   256)\n    Iter  5873\t      0.06954456 (Batch Size:   256)\n    Iter  5874\t      0.06902871 (Batch Size:   256)\n    Iter  5875\t      0.06756627 (Batch Size:   256)\n    Iter  5876\t      0.07185147 (Batch Size:   256)\n    Iter  5877\t      0.07238037 (Batch Size:   256)\n    Iter  5878\t      0.07358082 (Batch Size:   256)\n    Iter  5879\t      0.07026395 (Batch Size:   256)\n    Iter  5880\t      0.06526248 (Batch Size:   256)\n    Iter  5881\t      0.06666229 (Batch Size:   256)\n    Iter  5882\t      0.06996976 (Batch Size:   256)\n    Iter  5883\t      0.06654817 (Batch Size:   256)\n    Iter  5884\t      0.06797697 (Batch Size:   256)\n    Iter  5885\t      0.06941076 (Batch Size:   256)\n    Iter  5886\t      0.07089175 (Batch Size:   256)\n    Iter  5887\t      0.07171430 (Batch Size:   256)\n    Iter  5888\t      0.07008913 (Batch Size:   256)\n    Iter  5889\t      0.08035720 (Batch Size:   256)\n    Iter  5890\t      0.07248488 (Batch Size:   256)\n    Iter  5891\t      0.08028785 (Batch Size:   256)\n    Iter  5892\t      0.07475480 (Batch Size:   256)\n    Iter  5893\t      0.07379206 (Batch Size:   256)\n    Iter  5894\t      0.06973792 (Batch Size:   256)\n    Iter  5895\t      0.07053500 (Batch Size:   256)\n    Iter  5896\t      0.06884410 (Batch Size:   256)\n    Iter  5897\t      0.06637657 (Batch Size:   256)\n    Iter  5898\t      0.06832171 (Batch Size:   256)\n    Iter  5899\t      0.07286723 (Batch Size:   256)\n    Iter  5900\t      0.07163456 (Batch Size:   256)\n    Iter  5901\t      0.06769223 (Batch Size:   256)\n    Iter  5902\t      0.06876739 (Batch Size:   256)\n    Iter  5903\t      0.07147083 (Batch Size:   256)\n    Iter  5904\t      0.06809483 (Batch Size:   256)\n    Iter  5905\t      0.07023615 (Batch Size:   256)\n    Iter  5906\t      0.07238670 (Batch Size:   256)\n    Iter  5907\t      0.06822154 (Batch Size:   256)\n    Iter  5908\t      0.07172434 (Batch Size:   256)\n    Iter  5909\t      0.06343168 (Batch Size:   256)\n    Iter  5910\t      0.06732530 (Batch Size:   256)\n    Iter  5911\t      0.06920784 (Batch Size:   256)\n    Iter  5912\t      0.06782459 (Batch Size:   256)\n    Iter  5913\t      0.06464346 (Batch Size:   256)\n    Iter  5914\t      0.07157276 (Batch Size:   256)\n    Iter  5915\t      0.07820616 (Batch Size:   256)\n    Iter  5916\t      0.07044601 (Batch Size:   256)\n    Iter  5917\t      0.07203593 (Batch Size:   256)\n    Iter  5918\t      0.07129948 (Batch Size:   256)\n    Iter  5919\t      0.06983541 (Batch Size:   256)\n    Iter  5920\t      0.06631356 (Batch Size:   256)\n    Iter  5921\t      0.06894094 (Batch Size:   256)\n    Iter  5922\t      0.07071751 (Batch Size:   256)\n    Iter  5923\t      0.07009898 (Batch Size:   256)\n    Iter  5924\t      0.06391570 (Batch Size:   256)\n    Iter  5925\t      0.06849197 (Batch Size:   256)\n    Iter  5926\t      0.07130815 (Batch Size:   256)\n    Iter  5927\t      0.07138454 (Batch Size:   256)\n    Iter  5928\t      0.06894442 (Batch Size:   256)\n    Iter  5929\t      0.06560480 (Batch Size:   256)\n    Iter  5930\t      0.06811210 (Batch Size:   256)\n    Iter  5931\t      0.06843279 (Batch Size:   256)\n    Iter  5932\t      0.07553323 (Batch Size:   256)\n    Iter  5933\t      0.08487828 (Batch Size:   256)\n    Iter  5934\t      0.08445135 (Batch Size:   256)\n    Iter  5935\t      0.07980229 (Batch Size:   256)\n    Iter  5936\t      0.07096052 (Batch Size:   256)\n    Iter  5937\t      0.07515640 (Batch Size:   256)\n    Iter  5938\t      0.06768981 (Batch Size:   256)\n    Iter  5939\t      0.07262230 (Batch Size:   256)\n    Iter  5940\t      0.07557360 (Batch Size:   256)\n    Iter  5941\t      0.08553245 (Batch Size:   256)\n    Iter  5942\t      0.07041577 (Batch Size:   256)\n    Iter  5943\t      0.07009508 (Batch Size:   256)\n    Iter  5944\t      0.06663057 (Batch Size:   256)\n    Iter  5945\t      0.07175471 (Batch Size:   256)\n    Iter  5946\t      0.07310648 (Batch Size:   256)\n    Iter  5947\t      0.06590202 (Batch Size:   256)\n    Iter  5948\t      0.06811071 (Batch Size:   256)\n    Iter  5949\t      0.07733941 (Batch Size:   256)\n    Iter  5950\t      0.07183397 (Batch Size:   256)\n    Iter  5951\t      0.06449939 (Batch Size:   256)\n    Iter  5952\t      0.06704150 (Batch Size:   256)\n    Iter  5953\t      0.06735656 (Batch Size:   256)\n    Iter  5954\t      0.06901438 (Batch Size:   256)\n    Iter  5955\t      0.06969891 (Batch Size:   256)\n    Iter  5956\t      0.07291607 (Batch Size:   256)\n    Iter  5957\t      0.09569319 (Batch Size:   256)\n    Iter  5958\t      0.09713765 (Batch Size:   256)\n    Iter  5959\t      0.08919107 (Batch Size:   256)\n    Iter  5960\t      0.06980335 (Batch Size:   256)\n    Iter  5961\t      0.06810482 (Batch Size:   256)\n    Iter  5962\t      0.06933925 (Batch Size:   256)\n    Iter  5963\t      0.07216974 (Batch Size:   256)\n    Iter  5964\t      0.07236106 (Batch Size:   256)\n    Iter  5965\t      0.06905282 (Batch Size:   256)\n    Iter  5966\t      0.06625405 (Batch Size:   256)\n    Iter  5967\t      0.06950568 (Batch Size:   256)\n    Iter  5968\t      0.07007943 (Batch Size:   256)\n    Iter  5969\t      0.07417807 (Batch Size:   256)\n    Iter  5970\t      0.06985315 (Batch Size:   256)\n    Iter  5971\t      0.06844340 (Batch Size:   256)\n    Iter  5972\t      0.07124234 (Batch Size:   256)\n    Iter  5973\t      0.06625292 (Batch Size:   256)\n    Iter  5974\t      0.06633061 (Batch Size:   256)\n    Iter  5975\t      0.07169354 (Batch Size:   256)\n    Iter  5976\t      0.07572109 (Batch Size:   256)\n    Iter  5977\t      0.06912497 (Batch Size:   256)\n    Iter  5978\t      0.06359653 (Batch Size:   256)\n    Iter  5979\t      0.07036435 (Batch Size:   256)\n    Iter  5980\t      0.07260884 (Batch Size:   256)\n    Iter  5981\t      0.07518564 (Batch Size:   256)\n    Iter  5982\t      0.06828818 (Batch Size:   256)\n    Iter  5983\t      0.06534951 (Batch Size:   256)\n    Iter  5984\t      0.07388462 (Batch Size:   256)\n    Iter  5985\t      0.07044831 (Batch Size:   256)\n    Iter  5986\t      0.07011705 (Batch Size:   256)\n    Iter  5987\t      0.07559165 (Batch Size:   256)\n    Iter  5988\t      0.08005925 (Batch Size:   256)\n    Iter  5989\t      0.08110553 (Batch Size:   256)\n    Iter  5990\t      0.07457796 (Batch Size:   256)\n    Iter  5991\t      0.06948074 (Batch Size:   256)\n    Iter  5992\t      0.07033519 (Batch Size:   256)\n    Iter  5993\t      0.07538978 (Batch Size:   256)\n    Iter  5994\t      0.08003375 (Batch Size:   256)\n    Iter  5995\t      0.08131725 (Batch Size:   256)\n    Iter  5996\t      0.07836374 (Batch Size:   256)\n    Iter  5997\t      0.07074567 (Batch Size:   256)\n    Iter  5998\t      0.06641812 (Batch Size:   256)\n    Iter  5999\t      0.07070811 (Batch Size:   256)\n    Iter  6000\t      0.06459372 (Batch Size:   256)\n    Iter  6001\t      0.06915650 (Batch Size:   256)\n    Iter  6002\t      0.06489957 (Batch Size:   256)\n    Iter  6003\t      0.06818037 (Batch Size:   256)\n    Iter  6004\t      0.06571713 (Batch Size:   256)\n    Iter  6005\t      0.07287575 (Batch Size:   256)\n    Iter  6006\t      0.06415328 (Batch Size:   256)\n    Iter  6007\t      0.06765069 (Batch Size:   256)\n    Iter  6008\t      0.06786291 (Batch Size:   256)\n    Iter  6009\t      0.07066606 (Batch Size:   256)\n    Iter  6010\t      0.06871105 (Batch Size:   256)\n    Iter  6011\t      0.06910587 (Batch Size:   256)\n    Iter  6012\t      0.06979203 (Batch Size:   256)\n    Iter  6013\t      0.06897947 (Batch Size:   256)\n    Iter  6014\t      0.06802994 (Batch Size:   256)\n    Iter  6015\t      0.07042709 (Batch Size:   256)\n    Iter  6016\t      0.06567901 (Batch Size:   256)\n    Iter  6017\t      0.06504793 (Batch Size:   256)\n    Iter  6018\t      0.07150163 (Batch Size:   256)\n    Iter  6019\t      0.07164050 (Batch Size:   256)\n    Iter  6020\t      0.07209495 (Batch Size:   256)\n    Iter  6021\t      0.07593589 (Batch Size:   256)\n    Iter  6022\t      0.06748040 (Batch Size:   256)\n    Iter  6023\t      0.06471474 (Batch Size:   256)\n    Iter  6024\t      0.06778693 (Batch Size:   256)\n    Iter  6025\t      0.06704872 (Batch Size:   256)\n    Iter  6026\t      0.06928820 (Batch Size:   256)\n    Iter  6027\t      0.06909377 (Batch Size:   256)\n    Iter  6028\t      0.06749377 (Batch Size:   256)\n    Iter  6029\t      0.06493806 (Batch Size:   256)\n    Iter  6030\t      0.07141492 (Batch Size:   256)\n    Iter  6031\t      0.06870234 (Batch Size:   256)\n    Iter  6032\t      0.06824009 (Batch Size:   256)\n    Iter  6033\t      0.07064452 (Batch Size:   256)\n    Iter  6034\t      0.08406978 (Batch Size:   256)\n    Iter  6035\t      0.07686275 (Batch Size:   256)\n    Iter  6036\t      0.07082065 (Batch Size:   256)\n    Iter  6037\t      0.07431426 (Batch Size:   256)\n    Iter  6038\t      0.07540251 (Batch Size:   256)\n    Iter  6039\t      0.07109304 (Batch Size:   256)\n    Iter  6040\t      0.06762472 (Batch Size:   256)\n    Iter  6041\t      0.06607019 (Batch Size:   256)\n    Iter  6042\t      0.07682092 (Batch Size:   256)\n    Iter  6043\t      0.08032162 (Batch Size:   256)\n    Iter  6044\t      0.07203096 (Batch Size:   256)\n    Iter  6045\t      0.06683554 (Batch Size:   256)\n    Iter  6046\t      0.06407648 (Batch Size:   256)\n    Iter  6047\t      0.06411916 (Batch Size:   256)\n    Iter  6048\t      0.07083332 (Batch Size:   256)\n    Iter  6049\t      0.06827758 (Batch Size:   256)\n    Iter  6050\t      0.06284966 (Batch Size:   256)\n    Iter  6051\t      0.06662213 (Batch Size:   256)\n    Iter  6052\t      0.06661512 (Batch Size:   256)\n    Iter  6053\t      0.06640489 (Batch Size:   256)\n    Iter  6054\t      0.06421560 (Batch Size:   256)\n    Iter  6055\t      0.06904191 (Batch Size:   256)\n    Iter  6056\t      0.06761949 (Batch Size:   256)\n    Iter  6057\t      0.06677648 (Batch Size:   256)\n    Iter  6058\t      0.07368462 (Batch Size:   256)\n    Iter  6059\t      0.06935948 (Batch Size:   256)\n    Iter  6060\t      0.07470410 (Batch Size:   256)\n    Iter  6061\t      0.07187766 (Batch Size:   256)\n    Iter  6062\t      0.07029835 (Batch Size:   256)\n    Iter  6063\t      0.06976370 (Batch Size:   256)\n    Iter  6064\t      0.06747190 (Batch Size:   256)\n    Iter  6065\t      0.07048170 (Batch Size:   256)\n    Iter  6066\t      0.07105753 (Batch Size:   256)\n    Iter  6067\t      0.06721099 (Batch Size:   256)\n    Iter  6068\t      0.06582087 (Batch Size:   256)\n    Iter  6069\t      0.06574541 (Batch Size:   256)\n    Iter  6070\t      0.06511617 (Batch Size:   256)\n    Iter  6071\t      0.06808278 (Batch Size:   256)\n    Iter  6072\t      0.06671423 (Batch Size:   256)\n    Iter  6073\t      0.07315466 (Batch Size:   256)\n    Iter  6074\t      0.06830463 (Batch Size:   256)\n    Iter  6075\t      0.06835917 (Batch Size:   256)\n    Iter  6076\t      0.06634270 (Batch Size:   256)\n    Iter  6077\t      0.07139347 (Batch Size:   256)\n    Iter  6078\t      0.06857234 (Batch Size:   256)\n    Iter  6079\t      0.06768837 (Batch Size:   256)\n    Iter  6080\t      0.06505958 (Batch Size:   256)\n    Iter  6081\t      0.06569383 (Batch Size:   256)\n    Iter  6082\t      0.06674726 (Batch Size:   256)\n    Iter  6083\t      0.06624609 (Batch Size:   256)\n    Iter  6084\t      0.06566446 (Batch Size:   256)\n    Iter  6085\t      0.07052909 (Batch Size:   256)\n    Iter  6086\t      0.07153655 (Batch Size:   256)\n    Iter  6087\t      0.07999872 (Batch Size:   256)\n    Iter  6088\t      0.07758563 (Batch Size:   256)\n    Iter  6089\t      0.07157931 (Batch Size:   256)\n    Iter  6090\t      0.07112774 (Batch Size:   256)\n    Iter  6091\t      0.06926896 (Batch Size:   256)\n    Iter  6092\t      0.07042544 (Batch Size:   256)\n    Iter  6093\t      0.07391816 (Batch Size:   256)\n    Iter  6094\t      0.06941936 (Batch Size:   256)\n    Iter  6095\t      0.07202701 (Batch Size:   256)\n    Iter  6096\t      0.07969742 (Batch Size:   256)\n    Iter  6097\t      0.06946718 (Batch Size:   256)\n    Iter  6098\t      0.06884872 (Batch Size:   256)\n    Iter  6099\t      0.06775231 (Batch Size:   256)\n    Iter  6100\t      0.07660859 (Batch Size:   256)\n    Iter  6101\t      0.06884021 (Batch Size:   256)\n    Iter  6102\t      0.06759412 (Batch Size:   256)\n    Iter  6103\t      0.07012658 (Batch Size:   256)\n    Iter  6104\t      0.07060908 (Batch Size:   256)\n    Iter  6105\t      0.07413715 (Batch Size:   256)\n    Iter  6106\t      0.06735402 (Batch Size:   256)\n    Iter  6107\t      0.06584420 (Batch Size:   256)\n    Iter  6108\t      0.07162385 (Batch Size:   256)\n    Iter  6109\t      0.06549138 (Batch Size:   256)\n    Iter  6110\t      0.06769015 (Batch Size:   256)\n    Iter  6111\t      0.06933838 (Batch Size:   256)\n    Iter  6112\t      0.06550395 (Batch Size:   256)\n    Iter  6113\t      0.06550128 (Batch Size:   256)\n    Iter  6114\t      0.07106326 (Batch Size:   256)\n    Iter  6115\t      0.06919460 (Batch Size:   256)\n    Iter  6116\t      0.07077770 (Batch Size:   256)\n    Iter  6117\t      0.06504611 (Batch Size:   256)\n    Iter  6118\t      0.06850635 (Batch Size:   256)\n    Iter  6119\t      0.06468905 (Batch Size:   256)\n    Iter  6120\t      0.06496091 (Batch Size:   256)\n    Iter  6121\t      0.06822152 (Batch Size:   256)\n    Iter  6122\t      0.07706410 (Batch Size:   256)\n    Iter  6123\t      0.07673080 (Batch Size:   256)\n    Iter  6124\t      0.06787668 (Batch Size:   256)\n    Iter  6125\t      0.07870592 (Batch Size:   256)\n    Iter  6126\t      0.07988309 (Batch Size:   256)\n    Iter  6127\t      0.09304223 (Batch Size:   256)\n    Iter  6128\t      0.08225700 (Batch Size:   256)\n    Iter  6129\t      0.07046893 (Batch Size:   256)\n    Iter  6130\t      0.07212524 (Batch Size:   256)\n    Iter  6131\t      0.06724236 (Batch Size:   256)\n    Iter  6132\t      0.06835820 (Batch Size:   256)\n    Iter  6133\t      0.06897451 (Batch Size:   256)\n    Iter  6134\t      0.06791745 (Batch Size:   256)\n    Iter  6135\t      0.07085756 (Batch Size:   256)\n    Iter  6136\t      0.07793740 (Batch Size:   256)\n    Iter  6137\t      0.07475012 (Batch Size:   256)\n    Iter  6138\t      0.06631747 (Batch Size:   256)\n    Iter  6139\t      0.07390536 (Batch Size:   256)\n    Iter  6140\t      0.07396336 (Batch Size:   256)\n    Iter  6141\t      0.08018678 (Batch Size:   256)\n    Iter  6142\t      0.07131080 (Batch Size:   256)\n    Iter  6143\t      0.07059749 (Batch Size:   256)\n    Iter  6144\t      0.07071232 (Batch Size:   256)\n    Iter  6145\t      0.06541507 (Batch Size:   256)\n    Iter  6146\t      0.07067799 (Batch Size:   256)\n    Iter  6147\t      0.06783722 (Batch Size:   256)\n    Iter  6148\t      0.08052585 (Batch Size:   256)\n    Iter  6149\t      0.07695946 (Batch Size:   256)\n    Iter  6150\t      0.06614395 (Batch Size:   256)\n    Iter  6151\t      0.06539397 (Batch Size:   256)\n    Iter  6152\t      0.06914199 (Batch Size:   256)\n    Iter  6153\t      0.06839712 (Batch Size:   256)\n    Iter  6154\t      0.06543302 (Batch Size:   256)\n    Iter  6155\t      0.06850650 (Batch Size:   256)\n    Iter  6156\t      0.06622235 (Batch Size:   256)\n    Iter  6157\t      0.06775044 (Batch Size:   256)\n    Iter  6158\t      0.07331506 (Batch Size:   256)\n    Iter  6159\t      0.07857081 (Batch Size:   256)\n    Iter  6160\t      0.07514408 (Batch Size:   256)\n    Iter  6161\t      0.09549862 (Batch Size:   256)\n    Iter  6162\t      0.08280169 (Batch Size:   256)\n    Iter  6163\t      0.07007338 (Batch Size:   256)\n    Iter  6164\t      0.06778319 (Batch Size:   256)\n    Iter  6165\t      0.07093164 (Batch Size:   256)\n    Iter  6166\t      0.06903335 (Batch Size:   256)\n    Iter  6167\t      0.06755781 (Batch Size:   256)\n    Iter  6168\t      0.06918127 (Batch Size:   256)\n    Iter  6169\t      0.06817509 (Batch Size:   256)\n    Iter  6170\t      0.06700369 (Batch Size:   256)\n    Iter  6171\t      0.07400283 (Batch Size:   256)\n    Iter  6172\t      0.06887233 (Batch Size:   256)\n    Iter  6173\t      0.07513618 (Batch Size:   256)\n    Iter  6174\t      0.06919476 (Batch Size:   256)\n    Iter  6175\t      0.06867675 (Batch Size:   256)\n    Iter  6176\t      0.07057258 (Batch Size:   256)\n    Iter  6177\t      0.06904794 (Batch Size:   256)\n    Iter  6178\t      0.06938318 (Batch Size:   256)\n    Iter  6179\t      0.06847327 (Batch Size:   256)\n    Iter  6180\t      0.06815785 (Batch Size:   256)\n    Iter  6181\t      0.07285249 (Batch Size:   256)\n    Iter  6182\t      0.06993229 (Batch Size:   256)\n    Iter  6183\t      0.06461028 (Batch Size:   256)\n    Iter  6184\t      0.06789718 (Batch Size:   256)\n    Iter  6185\t      0.06981683 (Batch Size:   256)\n    Iter  6186\t      0.07193366 (Batch Size:   256)\n    Iter  6187\t      0.06752550 (Batch Size:   256)\n    Iter  6188\t      0.07299905 (Batch Size:   256)\n    Iter  6189\t      0.07556542 (Batch Size:   256)\n    Iter  6190\t      0.07430298 (Batch Size:   256)\n    Iter  6191\t      0.06637559 (Batch Size:   256)\n    Iter  6192\t      0.06572592 (Batch Size:   256)\n    Iter  6193\t      0.06713418 (Batch Size:   256)\n    Iter  6194\t      0.06827063 (Batch Size:   256)\n    Iter  6195\t      0.07557625 (Batch Size:   256)\n    Iter  6196\t      0.08527213 (Batch Size:   256)\n    Iter  6197\t      0.07838661 (Batch Size:   256)\n    Iter  6198\t      0.07413612 (Batch Size:   256)\n    Iter  6199\t      0.06910762 (Batch Size:   256)\n    Iter  6200\t      0.06966085 (Batch Size:   256)\n    Iter  6201\t      0.06918909 (Batch Size:   256)\n    Iter  6202\t      0.06481453 (Batch Size:   256)\n    Iter  6203\t      0.06718606 (Batch Size:   256)\n    Iter  6204\t      0.06321784 (Batch Size:   256)\n    Iter  6205\t      0.06621489 (Batch Size:   256)\n    Iter  6206\t      0.06759927 (Batch Size:   256)\n    Iter  6207\t      0.07806364 (Batch Size:   256)\n    Iter  6208\t      0.07385532 (Batch Size:   256)\n    Iter  6209\t      0.06932594 (Batch Size:   256)\n    Iter  6210\t      0.06780690 (Batch Size:   256)\n    Iter  6211\t      0.06442268 (Batch Size:   256)\n    Iter  6212\t      0.06251797 (Batch Size:   256)\n    Iter  6213\t      0.06357228 (Batch Size:   256)\n    Iter  6214\t      0.07065393 (Batch Size:   256)\n    Iter  6215\t      0.07361359 (Batch Size:   256)\n    Iter  6216\t      0.06692896 (Batch Size:   256)\n    Iter  6217\t      0.07328661 (Batch Size:   256)\n    Iter  6218\t      0.07223186 (Batch Size:   256)\n    Iter  6219\t      0.06723713 (Batch Size:   256)\n    Iter  6220\t      0.07502373 (Batch Size:   256)\n    Iter  6221\t      0.07159934 (Batch Size:   256)\n    Iter  6222\t      0.06684508 (Batch Size:   256)\n    Iter  6223\t      0.07791527 (Batch Size:   256)\n    Iter  6224\t      0.07339413 (Batch Size:   256)\n    Iter  6225\t      0.07453626 (Batch Size:   256)\n    Iter  6226\t      0.07477367 (Batch Size:   256)\n    Iter  6227\t      0.06436067 (Batch Size:   256)\n    Iter  6228\t      0.06686420 (Batch Size:   256)\n    Iter  6229\t      0.06849110 (Batch Size:   256)\n    Iter  6230\t      0.06808940 (Batch Size:   256)\n    Iter  6231\t      0.06991633 (Batch Size:   256)\n    Iter  6232\t      0.06780684 (Batch Size:   256)\n    Iter  6233\t      0.07917910 (Batch Size:   256)\n    Iter  6234\t      0.06509035 (Batch Size:   256)\n    Iter  6235\t      0.07134109 (Batch Size:   256)\n    Iter  6236\t      0.07140832 (Batch Size:   256)\n    Iter  6237\t      0.07223221 (Batch Size:   256)\n    Iter  6238\t      0.06916860 (Batch Size:   256)\n    Iter  6239\t      0.06370840 (Batch Size:   256)\n    Iter  6240\t      0.06519382 (Batch Size:   256)\n    Iter  6241\t      0.06599578 (Batch Size:   256)\n    Iter  6242\t      0.06601918 (Batch Size:   256)\n    Iter  6243\t      0.07052307 (Batch Size:   256)\n    Iter  6244\t      0.06795409 (Batch Size:   256)\n    Iter  6245\t      0.07016629 (Batch Size:   256)\n    Iter  6246\t      0.06467689 (Batch Size:   256)\n    Iter  6247\t      0.06648941 (Batch Size:   256)\n    Iter  6248\t      0.07805189 (Batch Size:   256)\n    Iter  6249\t      0.08680346 (Batch Size:   256)\n    Iter  6250\t      0.08820195 (Batch Size:   256)\n    Iter  6251\t      0.07869021 (Batch Size:   256)\n    Iter  6252\t      0.07155988 (Batch Size:   256)\n    Iter  6253\t      0.06499774 (Batch Size:   256)\n    Iter  6254\t      0.06428015 (Batch Size:   256)\n    Iter  6255\t      0.06697186 (Batch Size:   256)\n    Iter  6256\t      0.06576915 (Batch Size:   256)\n    Iter  6257\t      0.06626546 (Batch Size:   256)\n    Iter  6258\t      0.06906564 (Batch Size:   256)\n    Iter  6259\t      0.06837672 (Batch Size:   256)\n    Iter  6260\t      0.06962004 (Batch Size:   256)\n    Iter  6261\t      0.06305188 (Batch Size:   256)\n    Iter  6262\t      0.06583738 (Batch Size:   256)\n    Iter  6263\t      0.06812005 (Batch Size:   256)\n    Iter  6264\t      0.07645865 (Batch Size:   256)\n    Iter  6265\t      0.06692769 (Batch Size:   256)\n    Iter  6266\t      0.07777387 (Batch Size:   256)\n    Iter  6267\t      0.07798609 (Batch Size:   256)\n    Iter  6268\t      0.07033387 (Batch Size:   256)\n    Iter  6269\t      0.06428078 (Batch Size:   256)\n    Iter  6270\t      0.06863552 (Batch Size:   256)\n    Iter  6271\t      0.06981763 (Batch Size:   256)\n    Iter  6272\t      0.06536466 (Batch Size:   256)\n    Iter  6273\t      0.06463278 (Batch Size:   256)\n    Iter  6274\t      0.07446283 (Batch Size:   256)\n    Iter  6275\t      0.06795607 (Batch Size:   256)\n    Iter  6276\t      0.06847164 (Batch Size:   256)\n    Iter  6277\t      0.07187216 (Batch Size:   256)\n    Iter  6278\t      0.07210142 (Batch Size:   256)\n    Iter  6279\t      0.07190058 (Batch Size:   256)\n    Iter  6280\t      0.06811942 (Batch Size:   256)\n    Iter  6281\t      0.07119443 (Batch Size:   256)\n    Iter  6282\t      0.07696836 (Batch Size:   256)\n    Iter  6283\t      0.07841640 (Batch Size:   256)\n    Iter  6284\t      0.06997844 (Batch Size:   256)\n    Iter  6285\t      0.06749022 (Batch Size:   256)\n    Iter  6286\t      0.06929259 (Batch Size:   256)\n    Iter  6287\t      0.07016860 (Batch Size:   256)\n    Iter  6288\t      0.07388829 (Batch Size:   256)\n    Iter  6289\t      0.06902652 (Batch Size:   256)\n    Iter  6290\t      0.07131970 (Batch Size:   256)\n    Iter  6291\t      0.06479770 (Batch Size:   256)\n    Iter  6292\t      0.07024337 (Batch Size:   256)\n    Iter  6293\t      0.06858931 (Batch Size:   256)\n    Iter  6294\t      0.06999558 (Batch Size:   256)\n    Iter  6295\t      0.06592795 (Batch Size:   256)\n    Iter  6296\t      0.06851505 (Batch Size:   256)\n    Iter  6297\t      0.06697645 (Batch Size:   256)\n    Iter  6298\t      0.06754260 (Batch Size:   256)\n    Iter  6299\t      0.07049345 (Batch Size:   256)\n    Iter  6300\t      0.08004248 (Batch Size:   256)\n    Iter  6301\t      0.07057987 (Batch Size:   256)\n    Iter  6302\t      0.06751520 (Batch Size:   256)\n    Iter  6303\t      0.07016831 (Batch Size:   256)\n    Iter  6304\t      0.06864244 (Batch Size:   256)\n    Iter  6305\t      0.07086552 (Batch Size:   256)\n    Iter  6306\t      0.06472849 (Batch Size:   256)\n    Iter  6307\t      0.06666630 (Batch Size:   256)\n    Iter  6308\t      0.06683314 (Batch Size:   256)\n    Iter  6309\t      0.06787818 (Batch Size:   256)\n    Iter  6310\t      0.06678124 (Batch Size:   256)\n    Iter  6311\t      0.07526492 (Batch Size:   256)\n    Iter  6312\t      0.06656649 (Batch Size:   256)\n    Iter  6313\t      0.06590296 (Batch Size:   256)\n    Iter  6314\t      0.06827324 (Batch Size:   256)\n    Iter  6315\t      0.06951660 (Batch Size:   256)\n    Iter  6316\t      0.06899512 (Batch Size:   256)\n    Iter  6317\t      0.06484847 (Batch Size:   256)\n    Iter  6318\t      0.06749322 (Batch Size:   256)\n    Iter  6319\t      0.06787007 (Batch Size:   256)\n    Iter  6320\t      0.06981693 (Batch Size:   256)\n    Iter  6321\t      0.07510291 (Batch Size:   256)\n    Iter  6322\t      0.07821959 (Batch Size:   256)\n    Iter  6323\t      0.06992384 (Batch Size:   256)\n    Iter  6324\t      0.07067051 (Batch Size:   256)\n    Iter  6325\t      0.07502091 (Batch Size:   256)\n    Iter  6326\t      0.06976485 (Batch Size:   256)\n    Iter  6327\t      0.06984938 (Batch Size:   256)\n    Iter  6328\t      0.07043257 (Batch Size:   256)\n    Iter  6329\t      0.06786873 (Batch Size:   256)\n    Iter  6330\t      0.06769338 (Batch Size:   256)\n    Iter  6331\t      0.06942078 (Batch Size:   256)\n    Iter  6332\t      0.07168486 (Batch Size:   256)\n    Iter  6333\t      0.06308076 (Batch Size:   256)\n    Iter  6334\t      0.06513659 (Batch Size:   256)\n    Iter  6335\t      0.06537941 (Batch Size:   256)\n    Iter  6336\t      0.06707980 (Batch Size:   256)\n    Iter  6337\t      0.06521303 (Batch Size:   256)\n    Iter  6338\t      0.06856438 (Batch Size:   256)\n    Iter  6339\t      0.06975696 (Batch Size:   256)\n    Iter  6340\t      0.07140460 (Batch Size:   256)\n    Iter  6341\t      0.07016292 (Batch Size:   256)\n    Iter  6342\t      0.07401986 (Batch Size:   256)\n    Iter  6343\t      0.07447799 (Batch Size:   256)\n    Iter  6344\t      0.06958656 (Batch Size:   256)\n    Iter  6345\t      0.06456459 (Batch Size:   256)\n    Iter  6346\t      0.06737409 (Batch Size:   256)\n    Iter  6347\t      0.06742323 (Batch Size:   256)\n    Iter  6348\t      0.06583963 (Batch Size:   256)\n    Iter  6349\t      0.07034380 (Batch Size:   256)\n    Iter  6350\t      0.06617774 (Batch Size:   256)\n    Iter  6351\t      0.06703860 (Batch Size:   256)\n    Iter  6352\t      0.07153498 (Batch Size:   256)\n    Iter  6353\t      0.06398610 (Batch Size:   256)\n    Iter  6354\t      0.06733537 (Batch Size:   256)\n    Iter  6355\t      0.06651771 (Batch Size:   256)\n    Iter  6356\t      0.06206574 (Batch Size:   256)\n    Iter  6357\t      0.06427274 (Batch Size:   256)\n    Iter  6358\t      0.06544505 (Batch Size:   256)\n    Iter  6359\t      0.07232808 (Batch Size:   256)\n    Iter  6360\t      0.06605537 (Batch Size:   256)\n    Iter  6361\t      0.06817199 (Batch Size:   256)\n    Iter  6362\t      0.06508122 (Batch Size:   256)\n    Iter  6363\t      0.07039601 (Batch Size:   256)\n    Iter  6364\t      0.06874208 (Batch Size:   256)\n    Iter  6365\t      0.06472236 (Batch Size:   256)\n    Iter  6366\t      0.06834274 (Batch Size:   256)\n    Iter  6367\t      0.08015020 (Batch Size:   256)\n    Iter  6368\t      0.09346675 (Batch Size:   256)\n    Iter  6369\t      0.07615417 (Batch Size:   256)\n    Iter  6370\t      0.08322947 (Batch Size:   256)\n    Iter  6371\t      0.07496659 (Batch Size:   256)\n    Iter  6372\t      0.06977390 (Batch Size:   256)\n    Iter  6373\t      0.07800298 (Batch Size:   256)\n    Iter  6374\t      0.07043652 (Batch Size:   256)\n    Iter  6375\t      0.06697860 (Batch Size:   256)\n    Iter  6376\t      0.06482838 (Batch Size:   256)\n    Iter  6377\t      0.06400716 (Batch Size:   256)\n    Iter  6378\t      0.06696904 (Batch Size:   256)\n    Iter  6379\t      0.06668311 (Batch Size:   256)\n    Iter  6380\t      0.06926696 (Batch Size:   256)\n    Iter  6381\t      0.06926584 (Batch Size:   256)\n    Iter  6382\t      0.06770606 (Batch Size:   256)\n    Iter  6383\t      0.07472225 (Batch Size:   256)\n    Iter  6384\t      0.07243270 (Batch Size:   256)\n    Iter  6385\t      0.06240114 (Batch Size:   256)\n    Iter  6386\t      0.06873193 (Batch Size:   256)\n    Iter  6387\t      0.07021045 (Batch Size:   256)\n    Iter  6388\t      0.07538956 (Batch Size:   256)\n    Iter  6389\t      0.07056869 (Batch Size:   256)\n    Iter  6390\t      0.06299031 (Batch Size:   256)\n    Iter  6391\t      0.06267735 (Batch Size:   256)\n    Iter  6392\t      0.06808799 (Batch Size:   256)\n    Iter  6393\t      0.06327494 (Batch Size:   256)\n    Iter  6394\t      0.06183986 (Batch Size:   256)\n    Iter  6395\t      0.06471255 (Batch Size:   256)\n    Iter  6396\t      0.06494060 (Batch Size:   256)\n    Iter  6397\t      0.06619030 (Batch Size:   256)\n    Iter  6398\t      0.07219539 (Batch Size:   256)\n    Iter  6399\t      0.07608195 (Batch Size:   256)\n    Iter  6400\t      0.07545760 (Batch Size:   256)\n    Iter  6401\t      0.07826842 (Batch Size:   256)\n    Iter  6402\t      0.08255044 (Batch Size:   256)\n    Iter  6403\t      0.07463359 (Batch Size:   256)\n    Iter  6404\t      0.06956727 (Batch Size:   256)\n    Iter  6405\t      0.06386968 (Batch Size:   256)\n    Iter  6406\t      0.06607160 (Batch Size:   256)\n    Iter  6407\t      0.06872415 (Batch Size:   256)\n    Iter  6408\t      0.06732757 (Batch Size:   256)\n    Iter  6409\t      0.07102680 (Batch Size:   256)\n    Iter  6410\t      0.07133534 (Batch Size:   256)\n    Iter  6411\t      0.06692781 (Batch Size:   256)\n    Iter  6412\t      0.06323420 (Batch Size:   256)\n    Iter  6413\t      0.06822598 (Batch Size:   256)\n    Iter  6414\t      0.06444760 (Batch Size:   256)\n    Iter  6415\t      0.06660684 (Batch Size:   256)\n    Iter  6416\t      0.06297667 (Batch Size:   256)\n    Iter  6417\t      0.06736528 (Batch Size:   256)\n    Iter  6418\t      0.06474416 (Batch Size:   256)\n    Iter  6419\t      0.06478882 (Batch Size:   256)\n    Iter  6420\t      0.06672354 (Batch Size:   256)\n    Iter  6421\t      0.06609802 (Batch Size:   256)\n    Iter  6422\t      0.06491829 (Batch Size:   256)\n    Iter  6423\t      0.06920094 (Batch Size:   256)\n    Iter  6424\t      0.07584642 (Batch Size:   256)\n    Iter  6425\t      0.07318856 (Batch Size:   256)\n    Iter  6426\t      0.07429688 (Batch Size:   256)\n    Iter  6427\t      0.07254546 (Batch Size:   256)\n    Iter  6428\t      0.06844998 (Batch Size:   256)\n    Iter  6429\t      0.06777245 (Batch Size:   256)\n    Iter  6430\t      0.06658194 (Batch Size:   256)\n    Iter  6431\t      0.06450400 (Batch Size:   256)\n    Iter  6432\t      0.06323140 (Batch Size:   256)\n    Iter  6433\t      0.06522605 (Batch Size:   256)\n    Iter  6434\t      0.06365293 (Batch Size:   256)\n    Iter  6435\t      0.06557943 (Batch Size:   256)\n    Iter  6436\t      0.06279538 (Batch Size:   256)\n    Iter  6437\t      0.06279427 (Batch Size:   256)\n    Iter  6438\t      0.06371208 (Batch Size:   256)\n    Iter  6439\t      0.07108337 (Batch Size:   256)\n    Iter  6440\t      0.07088658 (Batch Size:   256)\n    Iter  6441\t      0.07476997 (Batch Size:   256)\n    Iter  6442\t      0.06966032 (Batch Size:   256)\n    Iter  6443\t      0.06860956 (Batch Size:   256)\n    Iter  6444\t      0.06709008 (Batch Size:   256)\n    Iter  6445\t      0.06825748 (Batch Size:   256)\n    Iter  6446\t      0.06426275 (Batch Size:   256)\n    Iter  6447\t      0.06566565 (Batch Size:   256)\n    Iter  6448\t      0.06636141 (Batch Size:   256)\n    Iter  6449\t      0.06725584 (Batch Size:   256)\n    Iter  6450\t      0.06735401 (Batch Size:   256)\n    Iter  6451\t      0.06744080 (Batch Size:   256)\n    Iter  6452\t      0.07348886 (Batch Size:   256)\n    Iter  6453\t      0.06703115 (Batch Size:   256)\n    Iter  6454\t      0.06237109 (Batch Size:   256)\n    Iter  6455\t      0.06621854 (Batch Size:   256)\n    Iter  6456\t      0.06897663 (Batch Size:   256)\n    Iter  6457\t      0.06536249 (Batch Size:   256)\n    Iter  6458\t      0.06388122 (Batch Size:   256)\n    Iter  6459\t      0.07262004 (Batch Size:   256)\n    Iter  6460\t      0.06817905 (Batch Size:   256)\n    Iter  6461\t      0.06477042 (Batch Size:   256)\n    Iter  6462\t      0.06824303 (Batch Size:   256)\n    Iter  6463\t      0.07659349 (Batch Size:   256)\n    Iter  6464\t      0.07700654 (Batch Size:   256)\n    Iter  6465\t      0.06511761 (Batch Size:   256)\n    Iter  6466\t      0.06997136 (Batch Size:   256)\n    Iter  6467\t      0.07113695 (Batch Size:   256)\n    Iter  6468\t      0.06580355 (Batch Size:   256)\n    Iter  6469\t      0.06663906 (Batch Size:   256)\n    Iter  6470\t      0.06833761 (Batch Size:   256)\n    Iter  6471\t      0.06060568 (Batch Size:   256)\n    Iter  6472\t      0.06466401 (Batch Size:   256)\n    Iter  6473\t      0.06693925 (Batch Size:   256)\n    Iter  6474\t      0.06587124 (Batch Size:   256)\n    Iter  6475\t      0.06435944 (Batch Size:   256)\n    Iter  6476\t      0.06327099 (Batch Size:   256)\n    Iter  6477\t      0.06885126 (Batch Size:   256)\n    Iter  6478\t      0.06407691 (Batch Size:   256)\n    Iter  6479\t      0.06378427 (Batch Size:   256)\n    Iter  6480\t      0.07034165 (Batch Size:   256)\n    Iter  6481\t      0.06617620 (Batch Size:   256)\n    Iter  6482\t      0.06603356 (Batch Size:   256)\n    Iter  6483\t      0.07877647 (Batch Size:   256)\n    Iter  6484\t      0.07109205 (Batch Size:   256)\n    Iter  6485\t      0.08196888 (Batch Size:   256)\n    Iter  6486\t      0.08069885 (Batch Size:   256)\n    Iter  6487\t      0.10070736 (Batch Size:   256)\n    Iter  6488\t      0.07693739 (Batch Size:   256)\n    Iter  6489\t      0.06666281 (Batch Size:   256)\n    Iter  6490\t      0.06433579 (Batch Size:   256)\n    Iter  6491\t      0.06660418 (Batch Size:   256)\n    Iter  6492\t      0.06733908 (Batch Size:   256)\n    Iter  6493\t      0.06713077 (Batch Size:   256)\n    Iter  6494\t      0.06383975 (Batch Size:   256)\n    Iter  6495\t      0.06463344 (Batch Size:   256)\n    Iter  6496\t      0.06543101 (Batch Size:   256)\n    Iter  6497\t      0.06655127 (Batch Size:   256)\n    Iter  6498\t      0.07855690 (Batch Size:   256)\n    Iter  6499\t      0.06687968 (Batch Size:   256)\n    Iter  6500\t      0.06996583 (Batch Size:   256)\n    Iter  6501\t      0.07151660 (Batch Size:   256)\n    Iter  6502\t      0.08966192 (Batch Size:   256)\n    Iter  6503\t      0.07393338 (Batch Size:   256)\n    Iter  6504\t      0.06385746 (Batch Size:   256)\n    Iter  6505\t      0.06439625 (Batch Size:   256)\n    Iter  6506\t      0.06432591 (Batch Size:   256)\n    Iter  6507\t      0.06863124 (Batch Size:   256)\n    Iter  6508\t      0.06697982 (Batch Size:   256)\n    Iter  6509\t      0.06312693 (Batch Size:   256)\n    Iter  6510\t      0.07086893 (Batch Size:   256)\n    Iter  6511\t      0.07903856 (Batch Size:   256)\n    Iter  6512\t      0.06812143 (Batch Size:   256)\n    Iter  6513\t      0.06778186 (Batch Size:   256)\n    Iter  6514\t      0.07061990 (Batch Size:   256)\n    Iter  6515\t      0.07271011 (Batch Size:   256)\n    Iter  6516\t      0.07378273 (Batch Size:   256)\n    Iter  6517\t      0.06984014 (Batch Size:   256)\n    Iter  6518\t      0.07076759 (Batch Size:   256)\n    Iter  6519\t      0.06244894 (Batch Size:   256)\n    Iter  6520\t      0.06665629 (Batch Size:   256)\n    Iter  6521\t      0.06327955 (Batch Size:   256)\n    Iter  6522\t      0.06062529 (Batch Size:   256)\n    Iter  6523\t      0.06364651 (Batch Size:   256)\n    Iter  6524\t      0.06313860 (Batch Size:   256)\n    Iter  6525\t      0.06259550 (Batch Size:   256)\n    Iter  6526\t      0.06599134 (Batch Size:   256)\n    Iter  6527\t      0.06269643 (Batch Size:   256)\n    Iter  6528\t      0.07124456 (Batch Size:   256)\n    Iter  6529\t      0.06479275 (Batch Size:   256)\n    Iter  6530\t      0.06592768 (Batch Size:   256)\n    Iter  6531\t      0.06942381 (Batch Size:   256)\n    Iter  6532\t      0.07153348 (Batch Size:   256)\n    Iter  6533\t      0.06865389 (Batch Size:   256)\n    Iter  6534\t      0.06871655 (Batch Size:   256)\n    Iter  6535\t      0.06514817 (Batch Size:   256)\n    Iter  6536\t      0.06725198 (Batch Size:   256)\n    Iter  6537\t      0.06243509 (Batch Size:   256)\n    Iter  6538\t      0.06537623 (Batch Size:   256)\n    Iter  6539\t      0.07215786 (Batch Size:   256)\n    Iter  6540\t      0.07537145 (Batch Size:   256)\n    Iter  6541\t      0.06991403 (Batch Size:   256)\n    Iter  6542\t      0.06362370 (Batch Size:   256)\n    Iter  6543\t      0.06438795 (Batch Size:   256)\n    Iter  6544\t      0.07099473 (Batch Size:   256)\n    Iter  6545\t      0.06907886 (Batch Size:   256)\n    Iter  6546\t      0.06436710 (Batch Size:   256)\n    Iter  6547\t      0.06418626 (Batch Size:   256)\n    Iter  6548\t      0.06366472 (Batch Size:   256)\n    Iter  6549\t      0.06164771 (Batch Size:   256)\n    Iter  6550\t      0.06765270 (Batch Size:   256)\n    Iter  6551\t      0.06234680 (Batch Size:   256)\n    Iter  6552\t      0.06258822 (Batch Size:   256)\n    Iter  6553\t      0.06401326 (Batch Size:   256)\n    Iter  6554\t      0.06412083 (Batch Size:   256)\n    Iter  6555\t      0.06400093 (Batch Size:   256)\n    Iter  6556\t      0.06442396 (Batch Size:   256)\n    Iter  6557\t      0.06532256 (Batch Size:   256)\n    Iter  6558\t      0.06544685 (Batch Size:   256)\n    Iter  6559\t      0.06999321 (Batch Size:   256)\n    Iter  6560\t      0.06796054 (Batch Size:   256)\n    Iter  6561\t      0.07329217 (Batch Size:   256)\n    Iter  6562\t      0.07060768 (Batch Size:   256)\n    Iter  6563\t      0.06894658 (Batch Size:   256)\n    Iter  6564\t      0.06230104 (Batch Size:   256)\n    Iter  6565\t      0.06388123 (Batch Size:   256)\n    Iter  6566\t      0.06511143 (Batch Size:   256)\n    Iter  6567\t      0.06147826 (Batch Size:   256)\n    Iter  6568\t      0.06638694 (Batch Size:   256)\n    Iter  6569\t      0.06920182 (Batch Size:   256)\n    Iter  6570\t      0.06628218 (Batch Size:   256)\n    Iter  6571\t      0.06631923 (Batch Size:   256)\n    Iter  6572\t      0.06770458 (Batch Size:   256)\n    Iter  6573\t      0.06095074 (Batch Size:   256)\n    Iter  6574\t      0.06267216 (Batch Size:   256)\n    Iter  6575\t      0.06832180 (Batch Size:   256)\n    Iter  6576\t      0.06469057 (Batch Size:   256)\n    Iter  6577\t      0.06484933 (Batch Size:   256)\n    Iter  6578\t      0.06405229 (Batch Size:   256)\n    Iter  6579\t      0.06132428 (Batch Size:   256)\n    Iter  6580\t      0.06421214 (Batch Size:   256)\n    Iter  6581\t      0.07379185 (Batch Size:   256)\n    Iter  6582\t      0.07334549 (Batch Size:   256)\n    Iter  6583\t      0.07214439 (Batch Size:   256)\n    Iter  6584\t      0.07397251 (Batch Size:   256)\n    Iter  6585\t      0.06717919 (Batch Size:   256)\n    Iter  6586\t      0.06615499 (Batch Size:   256)\n    Iter  6587\t      0.07251715 (Batch Size:   256)\n    Iter  6588\t      0.07676106 (Batch Size:   256)\n    Iter  6589\t      0.07815994 (Batch Size:   256)\n    Iter  6590\t      0.07320670 (Batch Size:   256)\n    Iter  6591\t      0.06477198 (Batch Size:   256)\n    Iter  6592\t      0.06303853 (Batch Size:   256)\n    Iter  6593\t      0.06660275 (Batch Size:   256)\n    Iter  6594\t      0.06442938 (Batch Size:   256)\n    Iter  6595\t      0.06376743 (Batch Size:   256)\n    Iter  6596\t      0.07229475 (Batch Size:   256)\n    Iter  6597\t      0.08346361 (Batch Size:   256)\n    Iter  6598\t      0.06282896 (Batch Size:   256)\n    Iter  6599\t      0.06661655 (Batch Size:   256)\n    Iter  6600\t      0.06786452 (Batch Size:   256)\n    Iter  6601\t      0.06469512 (Batch Size:   256)\n    Iter  6602\t      0.06800011 (Batch Size:   256)\n    Iter  6603\t      0.06211173 (Batch Size:   256)\n    Iter  6604\t      0.06434019 (Batch Size:   256)\n    Iter  6605\t      0.06657567 (Batch Size:   256)\n    Iter  6606\t      0.06773606 (Batch Size:   256)\n    Iter  6607\t      0.06430294 (Batch Size:   256)\n    Iter  6608\t      0.06334630 (Batch Size:   256)\n    Iter  6609\t      0.06073002 (Batch Size:   256)\n    Iter  6610\t      0.06219649 (Batch Size:   256)\n    Iter  6611\t      0.07407776 (Batch Size:   256)\n    Iter  6612\t      0.08510119 (Batch Size:   256)\n    Iter  6613\t      0.06541488 (Batch Size:   256)\n    Iter  6614\t      0.08096297 (Batch Size:   256)\n    Iter  6615\t      0.07414601 (Batch Size:   256)\n    Iter  6616\t      0.06856947 (Batch Size:   256)\n    Iter  6617\t      0.07264099 (Batch Size:   256)\n    Iter  6618\t      0.07186450 (Batch Size:   256)\n    Iter  6619\t      0.06681341 (Batch Size:   256)\n    Iter  6620\t      0.06929974 (Batch Size:   256)\n    Iter  6621\t      0.06326066 (Batch Size:   256)\n    Iter  6622\t      0.06268574 (Batch Size:   256)\n    Iter  6623\t      0.06427387 (Batch Size:   256)\n    Iter  6624\t      0.06653507 (Batch Size:   256)\n    Iter  6625\t      0.06645252 (Batch Size:   256)\n    Iter  6626\t      0.06779661 (Batch Size:   256)\n    Iter  6627\t      0.06462910 (Batch Size:   256)\n    Iter  6628\t      0.06107360 (Batch Size:   256)\n    Iter  6629\t      0.06500950 (Batch Size:   256)\n    Iter  6630\t      0.06274876 (Batch Size:   256)\n    Iter  6631\t      0.06338374 (Batch Size:   256)\n    Iter  6632\t      0.06392946 (Batch Size:   256)\n    Iter  6633\t      0.06927166 (Batch Size:   256)\n    Iter  6634\t      0.08093978 (Batch Size:   256)\n    Iter  6635\t      0.07753432 (Batch Size:   256)\n    Iter  6636\t      0.09000623 (Batch Size:   256)\n    Iter  6637\t      0.08331413 (Batch Size:   256)\n    Iter  6638\t      0.08511903 (Batch Size:   256)\n    Iter  6639\t      0.07768926 (Batch Size:   256)\n    Iter  6640\t      0.06906200 (Batch Size:   256)\n    Iter  6641\t      0.06547128 (Batch Size:   256)\n    Iter  6642\t      0.06456335 (Batch Size:   256)\n    Iter  6643\t      0.06680850 (Batch Size:   256)\n    Iter  6644\t      0.06320635 (Batch Size:   256)\n    Iter  6645\t      0.06336759 (Batch Size:   256)\n    Iter  6646\t      0.06416402 (Batch Size:   256)\n    Iter  6647\t      0.07648734 (Batch Size:   256)\n    Iter  6648\t      0.06863366 (Batch Size:   256)\n    Iter  6649\t      0.06327097 (Batch Size:   256)\n    Iter  6650\t      0.06077186 (Batch Size:   256)\n    Iter  6651\t      0.06251503 (Batch Size:   256)\n    Iter  6652\t      0.06207996 (Batch Size:   256)\n    Iter  6653\t      0.06356972 (Batch Size:   256)\n    Iter  6654\t      0.06796426 (Batch Size:   256)\n    Iter  6655\t      0.06895338 (Batch Size:   256)\n    Iter  6656\t      0.06712649 (Batch Size:   256)\n    Iter  6657\t      0.06819849 (Batch Size:   256)\n    Iter  6658\t      0.06783980 (Batch Size:   256)\n    Iter  6659\t      0.06440071 (Batch Size:   256)\n    Iter  6660\t      0.06415578 (Batch Size:   256)\n    Iter  6661\t      0.06397353 (Batch Size:   256)\n    Iter  6662\t      0.06161558 (Batch Size:   256)\n    Iter  6663\t      0.06965713 (Batch Size:   256)\n    Iter  6664\t      0.06388448 (Batch Size:   256)\n    Iter  6665\t      0.06688002 (Batch Size:   256)\n    Iter  6666\t      0.06019549 (Batch Size:   256)\n    Iter  6667\t      0.06141140 (Batch Size:   256)\n    Iter  6668\t      0.07184560 (Batch Size:   256)\n    Iter  6669\t      0.07223844 (Batch Size:   256)\n    Iter  6670\t      0.06453162 (Batch Size:   256)\n    Iter  6671\t      0.06375003 (Batch Size:   256)\n    Iter  6672\t      0.06012253 (Batch Size:   256)\n    Iter  6673\t      0.06158861 (Batch Size:   256)\n    Iter  6674\t      0.07399773 (Batch Size:   256)\n    Iter  6675\t      0.06615604 (Batch Size:   256)\n    Iter  6676\t      0.06417184 (Batch Size:   256)\n    Iter  6677\t      0.06626579 (Batch Size:   256)\n    Iter  6678\t      0.06770158 (Batch Size:   256)\n    Iter  6679\t      0.07431541 (Batch Size:   256)\n    Iter  6680\t      0.07303245 (Batch Size:   256)\n    Iter  6681\t      0.06415720 (Batch Size:   256)\n    Iter  6682\t      0.08401818 (Batch Size:   256)\n    Iter  6683\t      0.07346729 (Batch Size:   256)\n    Iter  6684\t      0.07337686 (Batch Size:   256)\n    Iter  6685\t      0.06553384 (Batch Size:   256)\n    Iter  6686\t      0.06478475 (Batch Size:   256)\n    Iter  6687\t      0.06095411 (Batch Size:   256)\n    Iter  6688\t      0.06528255 (Batch Size:   256)\n    Iter  6689\t      0.06627445 (Batch Size:   256)\n    Iter  6690\t      0.07443406 (Batch Size:   256)\n    Iter  6691\t      0.06616643 (Batch Size:   256)\n    Iter  6692\t      0.06404863 (Batch Size:   256)\n    Iter  6693\t      0.06435808 (Batch Size:   256)\n    Iter  6694\t      0.06371116 (Batch Size:   256)\n    Iter  6695\t      0.06147087 (Batch Size:   256)\n    Iter  6696\t      0.06159567 (Batch Size:   256)\n    Iter  6697\t      0.06203860 (Batch Size:   256)\n    Iter  6698\t      0.06241404 (Batch Size:   256)\n    Iter  6699\t      0.06424859 (Batch Size:   256)\n    Iter  6700\t      0.06954198 (Batch Size:   256)\n    Iter  6701\t      0.06077660 (Batch Size:   256)\n    Iter  6702\t      0.06055525 (Batch Size:   256)\n    Iter  6703\t      0.06324122 (Batch Size:   256)\n    Iter  6704\t      0.06243299 (Batch Size:   256)\n    Iter  6705\t      0.06215892 (Batch Size:   256)\n    Iter  6706\t      0.06218262 (Batch Size:   256)\n    Iter  6707\t      0.05964348 (Batch Size:   256)\n    Iter  6708\t      0.06391917 (Batch Size:   256)\n    Iter  6709\t      0.06509631 (Batch Size:   256)\n    Iter  6710\t      0.06745093 (Batch Size:   256)\n    Iter  6711\t      0.06957701 (Batch Size:   256)\n    Iter  6712\t      0.06599030 (Batch Size:   256)\n    Iter  6713\t      0.06547407 (Batch Size:   256)\n    Iter  6714\t      0.06345540 (Batch Size:   256)\n    Iter  6715\t      0.06824456 (Batch Size:   256)\n    Iter  6716\t      0.06470139 (Batch Size:   256)\n    Iter  6717\t      0.06887011 (Batch Size:   256)\n    Iter  6718\t      0.07722917 (Batch Size:   256)\n    Iter  6719\t      0.06169382 (Batch Size:   256)\n    Iter  6720\t      0.06480299 (Batch Size:   256)\n    Iter  6721\t      0.06002406 (Batch Size:   256)\n    Iter  6722\t      0.06486088 (Batch Size:   256)\n    Iter  6723\t      0.06327237 (Batch Size:   256)\n    Iter  6724\t      0.06243916 (Batch Size:   256)\n    Iter  6725\t      0.06411870 (Batch Size:   256)\n    Iter  6726\t      0.06180672 (Batch Size:   256)\n    Iter  6727\t      0.06520758 (Batch Size:   256)\n    Iter  6728\t      0.06879645 (Batch Size:   256)\n    Iter  6729\t      0.06660314 (Batch Size:   256)\n    Iter  6730\t      0.06430837 (Batch Size:   256)\n    Iter  6731\t      0.06377227 (Batch Size:   256)\n    Iter  6732\t      0.06138949 (Batch Size:   256)\n    Iter  6733\t      0.06178286 (Batch Size:   256)\n    Iter  6734\t      0.06492009 (Batch Size:   256)\n    Iter  6735\t      0.06334960 (Batch Size:   256)\n    Iter  6736\t      0.06528820 (Batch Size:   256)\n    Iter  6737\t      0.06602417 (Batch Size:   256)\n    Iter  6738\t      0.06425549 (Batch Size:   256)\n    Iter  6739\t      0.06761632 (Batch Size:   256)\n    Iter  6740\t      0.06311153 (Batch Size:   256)\n    Iter  6741\t      0.05930538 (Batch Size:   256)\n    Iter  6742\t      0.05712494 (Batch Size:   256)\n    Iter  6743\t      0.06423280 (Batch Size:   256)\n    Iter  6744\t      0.06535411 (Batch Size:   256)\n    Iter  6745\t      0.06117589 (Batch Size:   256)\n    Iter  6746\t      0.06216476 (Batch Size:   256)\n    Iter  6747\t      0.06116446 (Batch Size:   256)\n    Iter  6748\t      0.06445276 (Batch Size:   256)\n    Iter  6749\t      0.07353000 (Batch Size:   256)\n    Iter  6750\t      0.07638372 (Batch Size:   256)\n    Iter  6751\t      0.06646135 (Batch Size:   256)\n    Iter  6752\t      0.06633471 (Batch Size:   256)\n    Iter  6753\t      0.06725964 (Batch Size:   256)\n    Iter  6754\t      0.06851385 (Batch Size:   256)\n    Iter  6755\t      0.06563276 (Batch Size:   256)\n    Iter  6756\t      0.06520920 (Batch Size:   256)\n    Iter  6757\t      0.06520973 (Batch Size:   256)\n    Iter  6758\t      0.06778658 (Batch Size:   256)\n    Iter  6759\t      0.06381639 (Batch Size:   256)\n    Iter  6760\t      0.06801623 (Batch Size:   256)\n    Iter  6761\t      0.07256125 (Batch Size:   256)\n    Iter  6762\t      0.07046290 (Batch Size:   256)\n    Iter  6763\t      0.06859419 (Batch Size:   256)\n    Iter  6764\t      0.06205635 (Batch Size:   256)\n    Iter  6765\t      0.06245134 (Batch Size:   256)\n    Iter  6766\t      0.06424406 (Batch Size:   256)\n    Iter  6767\t      0.06484397 (Batch Size:   256)\n    Iter  6768\t      0.05949739 (Batch Size:   256)\n    Iter  6769\t      0.06368059 (Batch Size:   256)\n    Iter  6770\t      0.06949280 (Batch Size:   256)\n    Iter  6771\t      0.06177281 (Batch Size:   256)\n    Iter  6772\t      0.06341075 (Batch Size:   256)\n    Iter  6773\t      0.06645694 (Batch Size:   256)\n    Iter  6774\t      0.06574627 (Batch Size:   256)\n    Iter  6775\t      0.06247545 (Batch Size:   256)\n    Iter  6776\t      0.05769754 (Batch Size:   256)\n    Iter  6777\t      0.06895988 (Batch Size:   256)\n    Iter  6778\t      0.06393972 (Batch Size:   256)\n    Iter  6779\t      0.07012692 (Batch Size:   256)\n    Iter  6780\t      0.05990814 (Batch Size:   256)\n    Iter  6781\t      0.06411078 (Batch Size:   256)\n    Iter  6782\t      0.05898145 (Batch Size:   256)\n    Iter  6783\t      0.05909527 (Batch Size:   256)\n    Iter  6784\t      0.05922236 (Batch Size:   256)\n    Iter  6785\t      0.05869893 (Batch Size:   256)\n    Iter  6786\t      0.06355168 (Batch Size:   256)\n    Iter  6787\t      0.06258819 (Batch Size:   256)\n    Iter  6788\t      0.07478761 (Batch Size:   256)\n    Iter  6789\t      0.06751656 (Batch Size:   256)\n    Iter  6790\t      0.06500611 (Batch Size:   256)\n    Iter  6791\t      0.06445194 (Batch Size:   256)\n    Iter  6792\t      0.06080560 (Batch Size:   256)\n    Iter  6793\t      0.06225034 (Batch Size:   256)\n    Iter  6794\t      0.06382712 (Batch Size:   256)\n    Iter  6795\t      0.06058164 (Batch Size:   256)\n    Iter  6796\t      0.07020462 (Batch Size:   256)\n    Iter  6797\t      0.06253914 (Batch Size:   256)\n    Iter  6798\t      0.06140961 (Batch Size:   256)\n    Iter  6799\t      0.06200943 (Batch Size:   256)\n    Iter  6800\t      0.06072162 (Batch Size:   256)\n    Iter  6801\t      0.06566034 (Batch Size:   256)\n    Iter  6802\t      0.06736429 (Batch Size:   256)\n    Iter  6803\t      0.06051823 (Batch Size:   256)\n    Iter  6804\t      0.06299655 (Batch Size:   256)\n    Iter  6805\t      0.06368242 (Batch Size:   256)\n    Iter  6806\t      0.06448750 (Batch Size:   256)\n    Iter  6807\t      0.06796582 (Batch Size:   256)\n    Iter  6808\t      0.06879994 (Batch Size:   256)\n    Iter  6809\t      0.07028981 (Batch Size:   256)\n    Iter  6810\t      0.06777293 (Batch Size:   256)\n    Iter  6811\t      0.06607502 (Batch Size:   256)\n    Iter  6812\t      0.06711523 (Batch Size:   256)\n    Iter  6813\t      0.06472272 (Batch Size:   256)\n    Iter  6814\t      0.06119332 (Batch Size:   256)\n    Iter  6815\t      0.06372699 (Batch Size:   256)\n    Iter  6816\t      0.06144289 (Batch Size:   256)\n    Iter  6817\t      0.06098073 (Batch Size:   256)\n    Iter  6818\t      0.06760312 (Batch Size:   256)\n    Iter  6819\t      0.06000334 (Batch Size:   256)\n    Iter  6820\t      0.06113295 (Batch Size:   256)\n    Iter  6821\t      0.06662383 (Batch Size:   256)\n    Iter  6822\t      0.05855905 (Batch Size:   256)\n    Iter  6823\t      0.05890776 (Batch Size:   256)\n    Iter  6824\t      0.06130675 (Batch Size:   256)\n    Iter  6825\t      0.06270408 (Batch Size:   256)\n    Iter  6826\t      0.06238652 (Batch Size:   256)\n    Iter  6827\t      0.06146280 (Batch Size:   256)\n    Iter  6828\t      0.06459972 (Batch Size:   256)\n    Iter  6829\t      0.06333165 (Batch Size:   256)\n    Iter  6830\t      0.06136982 (Batch Size:   256)\n    Iter  6831\t      0.06023731 (Batch Size:   256)\n    Iter  6832\t      0.06111545 (Batch Size:   256)\n    Iter  6833\t      0.06024397 (Batch Size:   256)\n    Iter  6834\t      0.07874021 (Batch Size:   256)\n    Iter  6835\t      0.11311153 (Batch Size:   256)\n    Iter  6836\t      0.10089025 (Batch Size:   256)\n    Iter  6837\t      0.08194185 (Batch Size:   256)\n    Iter  6838\t      0.06215828 (Batch Size:   256)\n    Iter  6839\t      0.06066500 (Batch Size:   256)\n    Iter  6840\t      0.06135340 (Batch Size:   256)\n    Iter  6841\t      0.06285172 (Batch Size:   256)\n    Iter  6842\t      0.06068033 (Batch Size:   256)\n    Iter  6843\t      0.06285838 (Batch Size:   256)\n    Iter  6844\t      0.06264719 (Batch Size:   256)\n    Iter  6845\t      0.06566479 (Batch Size:   256)\n    Iter  6846\t      0.06716666 (Batch Size:   256)\n    Iter  6847\t      0.06343555 (Batch Size:   256)\n    Iter  6848\t      0.06115007 (Batch Size:   256)\n    Iter  6849\t      0.05984434 (Batch Size:   256)\n    Iter  6850\t      0.06104322 (Batch Size:   256)\n    Iter  6851\t      0.06198085 (Batch Size:   256)\n    Iter  6852\t      0.06037381 (Batch Size:   256)\n    Iter  6853\t      0.06035191 (Batch Size:   256)\n    Iter  6854\t      0.06327280 (Batch Size:   256)\n    Iter  6855\t      0.06354654 (Batch Size:   256)\n    Iter  6856\t      0.06388260 (Batch Size:   256)\n    Iter  6857\t      0.06366576 (Batch Size:   256)\n    Iter  6858\t      0.06418690 (Batch Size:   256)\n    Iter  6859\t      0.06422899 (Batch Size:   256)\n    Iter  6860\t      0.05865146 (Batch Size:   256)\n    Iter  6861\t      0.06907224 (Batch Size:   256)\n    Iter  6862\t      0.05925430 (Batch Size:   256)\n    Iter  6863\t      0.05941697 (Batch Size:   256)\n    Iter  6864\t      0.05696230 (Batch Size:   256)\n    Iter  6865\t      0.05715773 (Batch Size:   256)\n    Iter  6866\t      0.05739744 (Batch Size:   256)\n    Iter  6867\t      0.06039689 (Batch Size:   256)\n    Iter  6868\t      0.06026802 (Batch Size:   256)\n    Iter  6869\t      0.06457530 (Batch Size:   256)\n    Iter  6870\t      0.06275667 (Batch Size:   256)\n    Iter  6871\t      0.06064176 (Batch Size:   256)\n    Iter  6872\t      0.05964983 (Batch Size:   256)\n    Iter  6873\t      0.06736272 (Batch Size:   256)\n    Iter  6874\t      0.06645793 (Batch Size:   256)\n    Iter  6875\t      0.06023050 (Batch Size:   256)\n    Iter  6876\t      0.06227715 (Batch Size:   256)\n    Iter  6877\t      0.06049340 (Batch Size:   256)\n    Iter  6878\t      0.06045624 (Batch Size:   256)\n    Iter  6879\t      0.06609649 (Batch Size:   256)\n    Iter  6880\t      0.06362274 (Batch Size:   256)\n    Iter  6881\t      0.05996030 (Batch Size:   256)\n    Iter  6882\t      0.06517242 (Batch Size:   256)\n    Iter  6883\t      0.06241379 (Batch Size:   256)\n    Iter  6884\t      0.06258021 (Batch Size:   256)\n    Iter  6885\t      0.05767301 (Batch Size:   256)\n    Iter  6886\t      0.06415861 (Batch Size:   256)\n    Iter  6887\t      0.05827393 (Batch Size:   256)\n    Iter  6888\t      0.06367785 (Batch Size:   256)\n    Iter  6889\t      0.05934692 (Batch Size:   256)\n    Iter  6890\t      0.06745161 (Batch Size:   256)\n    Iter  6891\t      0.06050558 (Batch Size:   256)\n    Iter  6892\t      0.07155135 (Batch Size:   256)\n    Iter  6893\t      0.08489580 (Batch Size:   256)\n    Iter  6894\t      0.06395759 (Batch Size:   256)\n    Iter  6895\t      0.06341380 (Batch Size:   256)\n    Iter  6896\t      0.06347734 (Batch Size:   256)\n    Iter  6897\t      0.05890413 (Batch Size:   256)\n    Iter  6898\t      0.06081051 (Batch Size:   256)\n    Iter  6899\t      0.06001681 (Batch Size:   256)\n    Iter  6900\t      0.06225691 (Batch Size:   256)\n    Iter  6901\t      0.06355911 (Batch Size:   256)\n    Iter  6902\t      0.06452867 (Batch Size:   256)\n    Iter  6903\t      0.05840944 (Batch Size:   256)\n    Iter  6904\t      0.06042890 (Batch Size:   256)\n    Iter  6905\t      0.05915998 (Batch Size:   256)\n    Iter  6906\t      0.05988163 (Batch Size:   256)\n    Iter  6907\t      0.06525554 (Batch Size:   256)\n    Iter  6908\t      0.06171973 (Batch Size:   256)\n    Iter  6909\t      0.06348782 (Batch Size:   256)\n    Iter  6910\t      0.06370747 (Batch Size:   256)\n    Iter  6911\t      0.06078183 (Batch Size:   256)\n    Iter  6912\t      0.05649510 (Batch Size:   256)\n    Iter  6913\t      0.06529209 (Batch Size:   256)\n    Iter  6914\t      0.06260459 (Batch Size:   256)\n    Iter  6915\t      0.06397894 (Batch Size:   256)\n    Iter  6916\t      0.05931882 (Batch Size:   256)\n    Iter  6917\t      0.05812098 (Batch Size:   256)\n    Iter  6918\t      0.05968491 (Batch Size:   256)\n    Iter  6919\t      0.06267646 (Batch Size:   256)\n    Iter  6920\t      0.06353361 (Batch Size:   256)\n    Iter  6921\t      0.06022032 (Batch Size:   256)\n    Iter  6922\t      0.05893694 (Batch Size:   256)\n    Iter  6923\t      0.06111804 (Batch Size:   256)\n    Iter  6924\t      0.06236823 (Batch Size:   256)\n    Iter  6925\t      0.06133593 (Batch Size:   256)\n    Iter  6926\t      0.06159856 (Batch Size:   256)\n    Iter  6927\t      0.06908158 (Batch Size:   256)\n    Iter  6928\t      0.06895301 (Batch Size:   256)\n    Iter  6929\t      0.06130063 (Batch Size:   256)\n    Iter  6930\t      0.06075078 (Batch Size:   256)\n    Iter  6931\t      0.05970364 (Batch Size:   256)\n    Iter  6932\t      0.06432870 (Batch Size:   256)\n    Iter  6933\t      0.06581556 (Batch Size:   256)\n    Iter  6934\t      0.05945790 (Batch Size:   256)\n    Iter  6935\t      0.05925033 (Batch Size:   256)\n    Iter  6936\t      0.06344522 (Batch Size:   256)\n    Iter  6937\t      0.06480960 (Batch Size:   256)\n    Iter  6938\t      0.06864005 (Batch Size:   256)\n    Iter  6939\t      0.07271357 (Batch Size:   256)\n    Iter  6940\t      0.06140376 (Batch Size:   256)\n    Iter  6941\t      0.05923637 (Batch Size:   256)\n    Iter  6942\t      0.06042449 (Batch Size:   256)\n    Iter  6943\t      0.05869666 (Batch Size:   256)\n    Iter  6944\t      0.06111557 (Batch Size:   256)\n    Iter  6945\t      0.06369059 (Batch Size:   256)\n    Iter  6946\t      0.06615351 (Batch Size:   256)\n    Iter  6947\t      0.07246616 (Batch Size:   256)\n    Iter  6948\t      0.08208352 (Batch Size:   256)\n    Iter  6949\t      0.06552672 (Batch Size:   256)\n    Iter  6950\t      0.06757006 (Batch Size:   256)\n    Iter  6951\t      0.05961734 (Batch Size:   256)\n    Iter  6952\t      0.06011505 (Batch Size:   256)\n    Iter  6953\t      0.06982439 (Batch Size:   256)\n    Iter  6954\t      0.07632643 (Batch Size:   256)\n    Iter  6955\t      0.06884736 (Batch Size:   256)\n    Iter  6956\t      0.06737923 (Batch Size:   256)\n    Iter  6957\t      0.06235741 (Batch Size:   256)\n    Iter  6958\t      0.06325118 (Batch Size:   256)\n    Iter  6959\t      0.05764537 (Batch Size:   256)\n    Iter  6960\t      0.05814625 (Batch Size:   256)\n    Iter  6961\t      0.06320167 (Batch Size:   256)\n    Iter  6962\t      0.06022198 (Batch Size:   256)\n    Iter  6963\t      0.05908222 (Batch Size:   256)\n    Iter  6964\t      0.05813818 (Batch Size:   256)\n    Iter  6965\t      0.05737563 (Batch Size:   256)\n    Iter  6966\t      0.06054259 (Batch Size:   256)\n    Iter  6967\t      0.06507619 (Batch Size:   256)\n    Iter  6968\t      0.06731225 (Batch Size:   256)\n    Iter  6969\t      0.06041128 (Batch Size:   256)\n    Iter  6970\t      0.06292202 (Batch Size:   256)\n    Iter  6971\t      0.05757917 (Batch Size:   256)\n    Iter  6972\t      0.06142274 (Batch Size:   256)\n    Iter  6973\t      0.06062994 (Batch Size:   256)\n    Iter  6974\t      0.05923246 (Batch Size:   256)\n    Iter  6975\t      0.06351062 (Batch Size:   256)\n    Iter  6976\t      0.06552565 (Batch Size:   256)\n    Iter  6977\t      0.06558657 (Batch Size:   256)\n    Iter  6978\t      0.07643515 (Batch Size:   256)\n    Iter  6979\t      0.06110191 (Batch Size:   256)\n    Iter  6980\t      0.06029672 (Batch Size:   256)\n    Iter  6981\t      0.06392757 (Batch Size:   256)\n    Iter  6982\t      0.06206105 (Batch Size:   256)\n    Iter  6983\t      0.06256516 (Batch Size:   256)\n    Iter  6984\t      0.06294798 (Batch Size:   256)\n    Iter  6985\t      0.06190076 (Batch Size:   256)\n    Iter  6986\t      0.06243414 (Batch Size:   256)\n    Iter  6987\t      0.05957568 (Batch Size:   256)\n    Iter  6988\t      0.06257555 (Batch Size:   256)\n    Iter  6989\t      0.06259852 (Batch Size:   256)\n    Iter  6990\t      0.06345335 (Batch Size:   256)\n    Iter  6991\t      0.06689464 (Batch Size:   256)\n    Iter  6992\t      0.06217404 (Batch Size:   256)\n    Iter  6993\t      0.06153651 (Batch Size:   256)\n    Iter  6994\t      0.05948607 (Batch Size:   256)\n    Iter  6995\t      0.06362165 (Batch Size:   256)\n    Iter  6996\t      0.06362976 (Batch Size:   256)\n    Iter  6997\t      0.06299890 (Batch Size:   256)\n    Iter  6998\t      0.06395438 (Batch Size:   256)\n    Iter  6999\t      0.06375662 (Batch Size:   256)\n    Iter  7000\t      0.06000386 (Batch Size:   256)\n    Iter  7001\t      0.06733649 (Batch Size:   256)\n    Iter  7002\t      0.05988878 (Batch Size:   256)\n    Iter  7003\t      0.06426003 (Batch Size:   256)\n    Iter  7004\t      0.06641189 (Batch Size:   256)\n    Iter  7005\t      0.06106178 (Batch Size:   256)\n    Iter  7006\t      0.06029761 (Batch Size:   256)\n    Iter  7007\t      0.05841100 (Batch Size:   256)\n    Iter  7008\t      0.05886187 (Batch Size:   256)\n    Iter  7009\t      0.06453147 (Batch Size:   256)\n    Iter  7010\t      0.05896473 (Batch Size:   256)\n    Iter  7011\t      0.06010326 (Batch Size:   256)\n    Iter  7012\t      0.06689846 (Batch Size:   256)\n    Iter  7013\t      0.06478128 (Batch Size:   256)\n    Iter  7014\t      0.06320285 (Batch Size:   256)\n    Iter  7015\t      0.05897295 (Batch Size:   256)\n    Iter  7016\t      0.05841293 (Batch Size:   256)\n    Iter  7017\t      0.06290418 (Batch Size:   256)\n    Iter  7018\t      0.05805651 (Batch Size:   256)\n    Iter  7019\t      0.06023022 (Batch Size:   256)\n    Iter  7020\t      0.05983995 (Batch Size:   256)\n    Iter  7021\t      0.06233299 (Batch Size:   256)\n    Iter  7022\t      0.05719514 (Batch Size:   256)\n    Iter  7023\t      0.06405703 (Batch Size:   256)\n    Iter  7024\t      0.06501687 (Batch Size:   256)\n    Iter  7025\t      0.05804942 (Batch Size:   256)\n    Iter  7026\t      0.06125956 (Batch Size:   256)\n    Iter  7027\t      0.05803182 (Batch Size:   256)\n    Iter  7028\t      0.06017642 (Batch Size:   256)\n    Iter  7029\t      0.06234179 (Batch Size:   256)\n    Iter  7030\t      0.06256746 (Batch Size:   256)\n    Iter  7031\t      0.05951671 (Batch Size:   256)\n    Iter  7032\t      0.06419548 (Batch Size:   256)\n    Iter  7033\t      0.05911328 (Batch Size:   256)\n    Iter  7034\t      0.06037628 (Batch Size:   256)\n    Iter  7035\t      0.05593211 (Batch Size:   256)\n    Iter  7036\t      0.05868219 (Batch Size:   256)\n    Iter  7037\t      0.06537695 (Batch Size:   256)\n    Iter  7038\t      0.06592609 (Batch Size:   256)\n    Iter  7039\t      0.06019404 (Batch Size:   256)\n    Iter  7040\t      0.05853057 (Batch Size:   256)\n    Iter  7041\t      0.05780646 (Batch Size:   256)\n    Iter  7042\t      0.06517950 (Batch Size:   256)\n    Iter  7043\t      0.07487100 (Batch Size:   256)\n    Iter  7044\t      0.06610576 (Batch Size:   256)\n    Iter  7045\t      0.05470541 (Batch Size:   256)\n    Iter  7046\t      0.06030669 (Batch Size:   256)\n    Iter  7047\t      0.05837837 (Batch Size:   256)\n    Iter  7048\t      0.06625717 (Batch Size:   256)\n    Iter  7049\t      0.06227535 (Batch Size:   256)\n    Iter  7050\t      0.05868485 (Batch Size:   256)\n    Iter  7051\t      0.05934841 (Batch Size:   256)\n    Iter  7052\t      0.05775119 (Batch Size:   256)\n    Iter  7053\t      0.06007693 (Batch Size:   256)\n    Iter  7054\t      0.05913780 (Batch Size:   256)\n    Iter  7055\t      0.06607645 (Batch Size:   256)\n    Iter  7056\t      0.06852788 (Batch Size:   256)\n    Iter  7057\t      0.06221766 (Batch Size:   256)\n    Iter  7058\t      0.05574462 (Batch Size:   256)\n    Iter  7059\t      0.06503292 (Batch Size:   256)\n    Iter  7060\t      0.06266566 (Batch Size:   256)\n    Iter  7061\t      0.06034513 (Batch Size:   256)\n    Iter  7062\t      0.06388517 (Batch Size:   256)\n    Iter  7063\t      0.06426684 (Batch Size:   256)\n    Iter  7064\t      0.06796589 (Batch Size:   256)\n    Iter  7065\t      0.06570721 (Batch Size:   256)\n    Iter  7066\t      0.05866444 (Batch Size:   256)\n    Iter  7067\t      0.06041052 (Batch Size:   256)\n    Iter  7068\t      0.06141008 (Batch Size:   256)\n    Iter  7069\t      0.06176983 (Batch Size:   256)\n    Iter  7070\t      0.05782031 (Batch Size:   256)\n    Iter  7071\t      0.06287863 (Batch Size:   256)\n    Iter  7072\t      0.05824781 (Batch Size:   256)\n    Iter  7073\t      0.05956877 (Batch Size:   256)\n    Iter  7074\t      0.06089276 (Batch Size:   256)\n    Iter  7075\t      0.06312717 (Batch Size:   256)\n    Iter  7076\t      0.08211641 (Batch Size:   256)\n    Iter  7077\t      0.07961382 (Batch Size:   256)\n    Iter  7078\t      0.05752408 (Batch Size:   256)\n    Iter  7079\t      0.05947677 (Batch Size:   256)\n    Iter  7080\t      0.05810721 (Batch Size:   256)\n    Iter  7081\t      0.06130201 (Batch Size:   256)\n    Iter  7082\t      0.06195844 (Batch Size:   256)\n    Iter  7083\t      0.05738486 (Batch Size:   256)\n    Iter  7084\t      0.06420786 (Batch Size:   256)\n    Iter  7085\t      0.06605565 (Batch Size:   256)\n    Iter  7086\t      0.06417335 (Batch Size:   256)\n    Iter  7087\t      0.05794241 (Batch Size:   256)\n    Iter  7088\t      0.05922025 (Batch Size:   256)\n    Iter  7089\t      0.05608119 (Batch Size:   256)\n    Iter  7090\t      0.06181978 (Batch Size:   256)\n    Iter  7091\t      0.06288106 (Batch Size:   256)\n    Iter  7092\t      0.05957089 (Batch Size:   256)\n    Iter  7093\t      0.06176018 (Batch Size:   256)\n    Iter  7094\t      0.06206302 (Batch Size:   256)\n    Iter  7095\t      0.06000961 (Batch Size:   256)\n    Iter  7096\t      0.06167229 (Batch Size:   256)\n    Iter  7097\t      0.05955265 (Batch Size:   256)\n    Iter  7098\t      0.06133125 (Batch Size:   256)\n    Iter  7099\t      0.05871788 (Batch Size:   256)\n    Iter  7100\t      0.05784258 (Batch Size:   256)\n    Iter  7101\t      0.05778178 (Batch Size:   256)\n    Iter  7102\t      0.06561802 (Batch Size:   256)\n    Iter  7103\t      0.07329008 (Batch Size:   256)\n    Iter  7104\t      0.06557486 (Batch Size:   256)\n    Iter  7105\t      0.06088653 (Batch Size:   256)\n    Iter  7106\t      0.05936757 (Batch Size:   256)\n    Iter  7107\t      0.05812614 (Batch Size:   256)\n    Iter  7108\t      0.05720930 (Batch Size:   256)\n    Iter  7109\t      0.05842332 (Batch Size:   256)\n    Iter  7110\t      0.05465756 (Batch Size:   256)\n    Iter  7111\t      0.06167773 (Batch Size:   256)\n    Iter  7112\t      0.05791230 (Batch Size:   256)\n    Iter  7113\t      0.05699413 (Batch Size:   256)\n    Iter  7114\t      0.06057291 (Batch Size:   256)\n    Iter  7115\t      0.06321800 (Batch Size:   256)\n    Iter  7116\t      0.06476531 (Batch Size:   256)\n    Iter  7117\t      0.06207059 (Batch Size:   256)\n    Iter  7118\t      0.05751379 (Batch Size:   256)\n    Iter  7119\t      0.05874621 (Batch Size:   256)\n    Iter  7120\t      0.05889743 (Batch Size:   256)\n    Iter  7121\t      0.06230970 (Batch Size:   256)\n    Iter  7122\t      0.07538763 (Batch Size:   256)\n    Iter  7123\t      0.07025235 (Batch Size:   256)\n    Iter  7124\t      0.06243261 (Batch Size:   256)\n    Iter  7125\t      0.06032204 (Batch Size:   256)\n    Iter  7126\t      0.05860436 (Batch Size:   256)\n    Iter  7127\t      0.06230821 (Batch Size:   256)\n    Iter  7128\t      0.05930570 (Batch Size:   256)\n    Iter  7129\t      0.06159398 (Batch Size:   256)\n    Iter  7130\t      0.05874334 (Batch Size:   256)\n    Iter  7131\t      0.05788271 (Batch Size:   256)\n    Iter  7132\t      0.05881619 (Batch Size:   256)\n    Iter  7133\t      0.06076360 (Batch Size:   256)\n    Iter  7134\t      0.05734014 (Batch Size:   256)\n    Iter  7135\t      0.05920244 (Batch Size:   256)\n    Iter  7136\t      0.05904320 (Batch Size:   256)\n    Iter  7137\t      0.06467644 (Batch Size:   256)\n    Iter  7138\t      0.07215910 (Batch Size:   256)\n    Iter  7139\t      0.07442425 (Batch Size:   256)\n    Iter  7140\t      0.08534836 (Batch Size:   256)\n    Iter  7141\t      0.07751086 (Batch Size:   256)\n    Iter  7142\t      0.07185009 (Batch Size:   256)\n    Iter  7143\t      0.07511994 (Batch Size:   256)\n    Iter  7144\t      0.06581693 (Batch Size:   256)\n    Iter  7145\t      0.05891209 (Batch Size:   256)\n    Iter  7146\t      0.05666614 (Batch Size:   256)\n    Iter  7147\t      0.06184336 (Batch Size:   256)\n    Iter  7148\t      0.06510431 (Batch Size:   256)\n    Iter  7149\t      0.06357518 (Batch Size:   256)\n    Iter  7150\t      0.05965593 (Batch Size:   256)\n    Iter  7151\t      0.05671314 (Batch Size:   256)\n    Iter  7152\t      0.05912853 (Batch Size:   256)\n    Iter  7153\t      0.05940593 (Batch Size:   256)\n    Iter  7154\t      0.06026567 (Batch Size:   256)\n    Iter  7155\t      0.05789516 (Batch Size:   256)\n    Iter  7156\t      0.05726037 (Batch Size:   256)\n    Iter  7157\t      0.06088564 (Batch Size:   256)\n    Iter  7158\t      0.06413730 (Batch Size:   256)\n    Iter  7159\t      0.06283322 (Batch Size:   256)\n    Iter  7160\t      0.06118334 (Batch Size:   256)\n    Iter  7161\t      0.06610890 (Batch Size:   256)\n    Iter  7162\t      0.05960680 (Batch Size:   256)\n    Iter  7163\t      0.06266796 (Batch Size:   256)\n    Iter  7164\t      0.05776700 (Batch Size:   256)\n    Iter  7165\t      0.05586007 (Batch Size:   256)\n    Iter  7166\t      0.05649609 (Batch Size:   256)\n    Iter  7167\t      0.05815338 (Batch Size:   256)\n    Iter  7168\t      0.05572780 (Batch Size:   256)\n    Iter  7169\t      0.05754004 (Batch Size:   256)\n    Iter  7170\t      0.05544632 (Batch Size:   256)\n    Iter  7171\t      0.06120438 (Batch Size:   256)\n    Iter  7172\t      0.06317878 (Batch Size:   256)\n    Iter  7173\t      0.06567292 (Batch Size:   256)\n    Iter  7174\t      0.05945187 (Batch Size:   256)\n    Iter  7175\t      0.06347874 (Batch Size:   256)\n    Iter  7176\t      0.05642447 (Batch Size:   256)\n    Iter  7177\t      0.05843933 (Batch Size:   256)\n    Iter  7178\t      0.05724238 (Batch Size:   256)\n    Iter  7179\t      0.06135278 (Batch Size:   256)\n    Iter  7180\t      0.06549356 (Batch Size:   256)\n    Iter  7181\t      0.06641305 (Batch Size:   256)\n    Iter  7182\t      0.06487109 (Batch Size:   256)\n    Iter  7183\t      0.07217150 (Batch Size:   256)\n    Iter  7184\t      0.07557152 (Batch Size:   256)\n    Iter  7185\t      0.06514286 (Batch Size:   256)\n    Iter  7186\t      0.06772110 (Batch Size:   256)\n    Iter  7187\t      0.07283614 (Batch Size:   256)\n    Iter  7188\t      0.06068094 (Batch Size:   256)\n    Iter  7189\t      0.05862637 (Batch Size:   256)\n    Iter  7190\t      0.05613940 (Batch Size:   256)\n    Iter  7191\t      0.06318704 (Batch Size:   256)\n    Iter  7192\t      0.07133728 (Batch Size:   256)\n    Iter  7193\t      0.05770286 (Batch Size:   256)\n    Iter  7194\t      0.05859649 (Batch Size:   256)\n    Iter  7195\t      0.06099777 (Batch Size:   256)\n    Iter  7196\t      0.05939448 (Batch Size:   256)\n    Iter  7197\t      0.05828281 (Batch Size:   256)\n    Iter  7198\t      0.05762513 (Batch Size:   256)\n    Iter  7199\t      0.05738987 (Batch Size:   256)\n    Iter  7200\t      0.05867796 (Batch Size:   256)\n    Iter  7201\t      0.06337586 (Batch Size:   256)\n    Iter  7202\t      0.06267509 (Batch Size:   256)\n    Iter  7203\t      0.06465226 (Batch Size:   256)\n    Iter  7204\t      0.05747856 (Batch Size:   256)\n    Iter  7205\t      0.06471701 (Batch Size:   256)\n    Iter  7206\t      0.05879028 (Batch Size:   256)\n    Iter  7207\t      0.05851213 (Batch Size:   256)\n    Iter  7208\t      0.06181400 (Batch Size:   256)\n    Iter  7209\t      0.06750096 (Batch Size:   256)\n    Iter  7210\t      0.06657372 (Batch Size:   256)\n    Iter  7211\t      0.06507778 (Batch Size:   256)\n    Iter  7212\t      0.06461024 (Batch Size:   256)\n    Iter  7213\t      0.06321439 (Batch Size:   256)\n    Iter  7214\t      0.06223886 (Batch Size:   256)\n    Iter  7215\t      0.06296393 (Batch Size:   256)\n    Iter  7216\t      0.06132182 (Batch Size:   256)\n    Iter  7217\t      0.05952391 (Batch Size:   256)\n    Iter  7218\t      0.05707555 (Batch Size:   256)\n    Iter  7219\t      0.06544116 (Batch Size:   256)\n    Iter  7220\t      0.05776464 (Batch Size:   256)\n    Iter  7221\t      0.05540579 (Batch Size:   256)\n    Iter  7222\t      0.05812882 (Batch Size:   256)\n    Iter  7223\t      0.05660181 (Batch Size:   256)\n    Iter  7224\t      0.06075749 (Batch Size:   256)\n    Iter  7225\t      0.06371281 (Batch Size:   256)\n    Iter  7226\t      0.06428368 (Batch Size:   256)\n    Iter  7227\t      0.05718683 (Batch Size:   256)\n    Iter  7228\t      0.05887154 (Batch Size:   256)\n    Iter  7229\t      0.05974495 (Batch Size:   256)\n    Iter  7230\t      0.05806100 (Batch Size:   256)\n    Iter  7231\t      0.05893492 (Batch Size:   256)\n    Iter  7232\t      0.06277838 (Batch Size:   256)\n    Iter  7233\t      0.06091098 (Batch Size:   256)\n    Iter  7234\t      0.06387503 (Batch Size:   256)\n    Iter  7235\t      0.05949186 (Batch Size:   256)\n    Iter  7236\t      0.05884421 (Batch Size:   256)\n    Iter  7237\t      0.06111772 (Batch Size:   256)\n    Iter  7238\t      0.05736615 (Batch Size:   256)\n    Iter  7239\t      0.05925355 (Batch Size:   256)\n    Iter  7240\t      0.05823590 (Batch Size:   256)\n    Iter  7241\t      0.06172733 (Batch Size:   256)\n    Iter  7242\t      0.05936071 (Batch Size:   256)\n    Iter  7243\t      0.05854666 (Batch Size:   256)\n    Iter  7244\t      0.06104671 (Batch Size:   256)\n    Iter  7245\t      0.06663646 (Batch Size:   256)\n    Iter  7246\t      0.06505981 (Batch Size:   256)\n    Iter  7247\t      0.06546924 (Batch Size:   256)\n    Iter  7248\t      0.05921968 (Batch Size:   256)\n    Iter  7249\t      0.06508108 (Batch Size:   256)\n    Iter  7250\t      0.06135186 (Batch Size:   256)\n    Iter  7251\t      0.05943471 (Batch Size:   256)\n    Iter  7252\t      0.05662043 (Batch Size:   256)\n    Iter  7253\t      0.06330609 (Batch Size:   256)\n    Iter  7254\t      0.07422705 (Batch Size:   256)\n    Iter  7255\t      0.07063397 (Batch Size:   256)\n    Iter  7256\t      0.06494201 (Batch Size:   256)\n    Iter  7257\t      0.05657253 (Batch Size:   256)\n    Iter  7258\t      0.05638473 (Batch Size:   256)\n    Iter  7259\t      0.05195972 (Batch Size:   256)\n    Iter  7260\t      0.05845225 (Batch Size:   256)\n    Iter  7261\t      0.05635185 (Batch Size:   256)\n    Iter  7262\t      0.05813608 (Batch Size:   256)\n    Iter  7263\t      0.05435761 (Batch Size:   256)\n    Iter  7264\t      0.05700665 (Batch Size:   256)\n    Iter  7265\t      0.05604952 (Batch Size:   256)\n    Iter  7266\t      0.05504436 (Batch Size:   256)\n    Iter  7267\t      0.06039695 (Batch Size:   256)\n    Iter  7268\t      0.06236963 (Batch Size:   256)\n    Iter  7269\t      0.05790872 (Batch Size:   256)\n    Iter  7270\t      0.05687865 (Batch Size:   256)\n    Iter  7271\t      0.05559547 (Batch Size:   256)\n    Iter  7272\t      0.05253200 (Batch Size:   256)\n    Iter  7273\t      0.05982393 (Batch Size:   256)\n    Iter  7274\t      0.05761134 (Batch Size:   256)\n    Iter  7275\t      0.05840920 (Batch Size:   256)\n    Iter  7276\t      0.05676329 (Batch Size:   256)\n    Iter  7277\t      0.07558690 (Batch Size:   256)\n    Iter  7278\t      0.07697513 (Batch Size:   256)\n    Iter  7279\t      0.06215938 (Batch Size:   256)\n    Iter  7280\t      0.06010227 (Batch Size:   256)\n    Iter  7281\t      0.05519910 (Batch Size:   256)\n    Iter  7282\t      0.06165269 (Batch Size:   256)\n    Iter  7283\t      0.05942113 (Batch Size:   256)\n    Iter  7284\t      0.06094274 (Batch Size:   256)\n    Iter  7285\t      0.07372936 (Batch Size:   256)\n    Iter  7286\t      0.07080165 (Batch Size:   256)\n    Iter  7287\t      0.06136293 (Batch Size:   256)\n    Iter  7288\t      0.05771463 (Batch Size:   256)\n    Iter  7289\t      0.05991207 (Batch Size:   256)\n    Iter  7290\t      0.05857395 (Batch Size:   256)\n    Iter  7291\t      0.06061682 (Batch Size:   256)\n    Iter  7292\t      0.06828426 (Batch Size:   256)\n    Iter  7293\t      0.06720287 (Batch Size:   256)\n    Iter  7294\t      0.06099379 (Batch Size:   256)\n    Iter  7295\t      0.05985329 (Batch Size:   256)\n    Iter  7296\t      0.05832275 (Batch Size:   256)\n    Iter  7297\t      0.05939102 (Batch Size:   256)\n    Iter  7298\t      0.05927839 (Batch Size:   256)\n    Iter  7299\t      0.05737955 (Batch Size:   256)\n    Iter  7300\t      0.06157325 (Batch Size:   256)\n    Iter  7301\t      0.05793377 (Batch Size:   256)\n    Iter  7302\t      0.06526403 (Batch Size:   256)\n    Iter  7303\t      0.05959657 (Batch Size:   256)\n    Iter  7304\t      0.06884409 (Batch Size:   256)\n    Iter  7305\t      0.06105546 (Batch Size:   256)\n    Iter  7306\t      0.05967628 (Batch Size:   256)\n    Iter  7307\t      0.06274191 (Batch Size:   256)\n    Iter  7308\t      0.05914432 (Batch Size:   256)\n    Iter  7309\t      0.05705799 (Batch Size:   256)\n    Iter  7310\t      0.05772207 (Batch Size:   256)\n    Iter  7311\t      0.06492253 (Batch Size:   256)\n    Iter  7312\t      0.06797526 (Batch Size:   256)\n    Iter  7313\t      0.06157453 (Batch Size:   256)\n    Iter  7314\t      0.06081000 (Batch Size:   256)\n    Iter  7315\t      0.06013311 (Batch Size:   256)\n    Iter  7316\t      0.06435908 (Batch Size:   256)\n    Iter  7317\t      0.06497585 (Batch Size:   256)\n    Iter  7318\t      0.05923890 (Batch Size:   256)\n    Iter  7319\t      0.05620856 (Batch Size:   256)\n    Iter  7320\t      0.05431457 (Batch Size:   256)\n    Iter  7321\t      0.05727672 (Batch Size:   256)\n    Iter  7322\t      0.05536004 (Batch Size:   256)\n    Iter  7323\t      0.05997948 (Batch Size:   256)\n    Iter  7324\t      0.06237642 (Batch Size:   256)\n    Iter  7325\t      0.05816464 (Batch Size:   256)\n    Iter  7326\t      0.05772819 (Batch Size:   256)\n    Iter  7327\t      0.05568115 (Batch Size:   256)\n    Iter  7328\t      0.05495887 (Batch Size:   256)\n    Iter  7329\t      0.05536388 (Batch Size:   256)\n    Iter  7330\t      0.05821943 (Batch Size:   256)\n    Iter  7331\t      0.06063903 (Batch Size:   256)\n    Iter  7332\t      0.06623714 (Batch Size:   256)\n    Iter  7333\t      0.05789364 (Batch Size:   256)\n    Iter  7334\t      0.05655715 (Batch Size:   256)\n    Iter  7335\t      0.06050936 (Batch Size:   256)\n    Iter  7336\t      0.05796607 (Batch Size:   256)\n    Iter  7337\t      0.05780187 (Batch Size:   256)\n    Iter  7338\t      0.05533690 (Batch Size:   256)\n    Iter  7339\t      0.05681912 (Batch Size:   256)\n    Iter  7340\t      0.05910147 (Batch Size:   256)\n    Iter  7341\t      0.05897574 (Batch Size:   256)\n    Iter  7342\t      0.05536238 (Batch Size:   256)\n    Iter  7343\t      0.05542368 (Batch Size:   256)\n    Iter  7344\t      0.06516206 (Batch Size:   256)\n    Iter  7345\t      0.07758315 (Batch Size:   256)\n    Iter  7346\t      0.07492030 (Batch Size:   256)\n    Iter  7347\t      0.07100627 (Batch Size:   256)\n    Iter  7348\t      0.06473519 (Batch Size:   256)\n    Iter  7349\t      0.06667202 (Batch Size:   256)\n    Iter  7350\t      0.06179695 (Batch Size:   256)\n    Iter  7351\t      0.06463662 (Batch Size:   256)\n    Iter  7352\t      0.07459505 (Batch Size:   256)\n    Iter  7353\t      0.06779473 (Batch Size:   256)\n    Iter  7354\t      0.06486347 (Batch Size:   256)\n    Iter  7355\t      0.05698917 (Batch Size:   256)\n    Iter  7356\t      0.05728142 (Batch Size:   256)\n    Iter  7357\t      0.05509411 (Batch Size:   256)\n    Iter  7358\t      0.05676039 (Batch Size:   256)\n    Iter  7359\t      0.05863828 (Batch Size:   256)\n    Iter  7360\t      0.05776889 (Batch Size:   256)\n    Iter  7361\t      0.06315846 (Batch Size:   256)\n    Iter  7362\t      0.06404870 (Batch Size:   256)\n    Iter  7363\t      0.05752164 (Batch Size:   256)\n    Iter  7364\t      0.05916410 (Batch Size:   256)\n    Iter  7365\t      0.06113123 (Batch Size:   256)\n    Iter  7366\t      0.05653225 (Batch Size:   256)\n    Iter  7367\t      0.05605923 (Batch Size:   256)\n    Iter  7368\t      0.06009191 (Batch Size:   256)\n    Iter  7369\t      0.05706361 (Batch Size:   256)\n    Iter  7370\t      0.05690444 (Batch Size:   256)\n    Iter  7371\t      0.05378051 (Batch Size:   256)\n    Iter  7372\t      0.05990904 (Batch Size:   256)\n    Iter  7373\t      0.05958969 (Batch Size:   256)\n    Iter  7374\t      0.06241665 (Batch Size:   256)\n    Iter  7375\t      0.06159916 (Batch Size:   256)\n    Iter  7376\t      0.07606322 (Batch Size:   256)\n    Iter  7377\t      0.06151834 (Batch Size:   256)\n    Iter  7378\t      0.06044579 (Batch Size:   256)\n    Iter  7379\t      0.05834434 (Batch Size:   256)\n    Iter  7380\t      0.05401054 (Batch Size:   256)\n    Iter  7381\t      0.05656138 (Batch Size:   256)\n    Iter  7382\t      0.05965556 (Batch Size:   256)\n    Iter  7383\t      0.05978037 (Batch Size:   256)\n    Iter  7384\t      0.05493572 (Batch Size:   256)\n    Iter  7385\t      0.05768323 (Batch Size:   256)\n    Iter  7386\t      0.05729401 (Batch Size:   256)\n    Iter  7387\t      0.05502402 (Batch Size:   256)\n    Iter  7388\t      0.05622114 (Batch Size:   256)\n    Iter  7389\t      0.05907677 (Batch Size:   256)\n    Iter  7390\t      0.05852867 (Batch Size:   256)\n    Iter  7391\t      0.05838501 (Batch Size:   256)\n    Iter  7392\t      0.05458629 (Batch Size:   256)\n    Iter  7393\t      0.05578838 (Batch Size:   256)\n    Iter  7394\t      0.05703143 (Batch Size:   256)\n    Iter  7395\t      0.06093274 (Batch Size:   256)\n    Iter  7396\t      0.05523610 (Batch Size:   256)\n    Iter  7397\t      0.06010569 (Batch Size:   256)\n    Iter  7398\t      0.06327462 (Batch Size:   256)\n    Iter  7399\t      0.05671043 (Batch Size:   256)\n    Iter  7400\t      0.05673936 (Batch Size:   256)\n    Iter  7401\t      0.05925028 (Batch Size:   256)\n    Iter  7402\t      0.06541369 (Batch Size:   256)\n    Iter  7403\t      0.08304148 (Batch Size:   256)\n    Iter  7404\t      0.07233310 (Batch Size:   256)\n    Iter  7405\t      0.05876389 (Batch Size:   256)\n    Iter  7406\t      0.05361285 (Batch Size:   256)\n    Iter  7407\t      0.06140479 (Batch Size:   256)\n    Iter  7408\t      0.05604387 (Batch Size:   256)\n    Iter  7409\t      0.06084289 (Batch Size:   256)\n    Iter  7410\t      0.05632368 (Batch Size:   256)\n    Iter  7411\t      0.05525847 (Batch Size:   256)\n    Iter  7412\t      0.05726124 (Batch Size:   256)\n    Iter  7413\t      0.05553863 (Batch Size:   256)\n    Iter  7414\t      0.05759753 (Batch Size:   256)\n    Iter  7415\t      0.05826011 (Batch Size:   256)\n    Iter  7416\t      0.06341090 (Batch Size:   256)\n    Iter  7417\t      0.05795928 (Batch Size:   256)\n    Iter  7418\t      0.05512130 (Batch Size:   256)\n    Iter  7419\t      0.05718961 (Batch Size:   256)\n    Iter  7420\t      0.05769051 (Batch Size:   256)\n    Iter  7421\t      0.05703658 (Batch Size:   256)\n    Iter  7422\t      0.05622993 (Batch Size:   256)\n    Iter  7423\t      0.05530467 (Batch Size:   256)\n    Iter  7424\t      0.05344256 (Batch Size:   256)\n    Iter  7425\t      0.05870854 (Batch Size:   256)\n    Iter  7426\t      0.05714497 (Batch Size:   256)\n    Iter  7427\t      0.06127799 (Batch Size:   256)\n    Iter  7428\t      0.07251747 (Batch Size:   256)\n    Iter  7429\t      0.06310248 (Batch Size:   256)\n    Iter  7430\t      0.05806674 (Batch Size:   256)\n    Iter  7431\t      0.05561566 (Batch Size:   256)\n    Iter  7432\t      0.05570132 (Batch Size:   256)\n    Iter  7433\t      0.05659204 (Batch Size:   256)\n    Iter  7434\t      0.05660950 (Batch Size:   256)\n    Iter  7435\t      0.05690080 (Batch Size:   256)\n    Iter  7436\t      0.06342288 (Batch Size:   256)\n    Iter  7437\t      0.06166974 (Batch Size:   256)\n    Iter  7438\t      0.05709354 (Batch Size:   256)\n    Iter  7439\t      0.05785717 (Batch Size:   256)\n    Iter  7440\t      0.05645303 (Batch Size:   256)\n    Iter  7441\t      0.05690048 (Batch Size:   256)\n    Iter  7442\t      0.05673812 (Batch Size:   256)\n    Iter  7443\t      0.05889499 (Batch Size:   256)\n    Iter  7444\t      0.05496841 (Batch Size:   256)\n    Iter  7445\t      0.06461856 (Batch Size:   256)\n    Iter  7446\t      0.06981972 (Batch Size:   256)\n    Iter  7447\t      0.06366450 (Batch Size:   256)\n    Iter  7448\t      0.05886493 (Batch Size:   256)\n    Iter  7449\t      0.06618501 (Batch Size:   256)\n    Iter  7450\t      0.05919343 (Batch Size:   256)\n    Iter  7451\t      0.05419348 (Batch Size:   256)\n    Iter  7452\t      0.05520528 (Batch Size:   256)\n    Iter  7453\t      0.05568875 (Batch Size:   256)\n    Iter  7454\t      0.06307812 (Batch Size:   256)\n    Iter  7455\t      0.06910360 (Batch Size:   256)\n    Iter  7456\t      0.06256429 (Batch Size:   256)\n    Iter  7457\t      0.06400324 (Batch Size:   256)\n    Iter  7458\t      0.07205808 (Batch Size:   256)\n    Iter  7459\t      0.06914738 (Batch Size:   256)\n    Iter  7460\t      0.05867986 (Batch Size:   256)\n    Iter  7461\t      0.05979212 (Batch Size:   256)\n    Iter  7462\t      0.06210456 (Batch Size:   256)\n    Iter  7463\t      0.05789335 (Batch Size:   256)\n    Iter  7464\t      0.05876310 (Batch Size:   256)\n    Iter  7465\t      0.06358251 (Batch Size:   256)\n    Iter  7466\t      0.06108074 (Batch Size:   256)\n    Iter  7467\t      0.05544894 (Batch Size:   256)\n    Iter  7468\t      0.06398280 (Batch Size:   256)\n    Iter  7469\t      0.06534803 (Batch Size:   256)\n    Iter  7470\t      0.06136340 (Batch Size:   256)\n    Iter  7471\t      0.05627567 (Batch Size:   256)\n    Iter  7472\t      0.05548227 (Batch Size:   256)\n    Iter  7473\t      0.06193759 (Batch Size:   256)\n    Iter  7474\t      0.05764672 (Batch Size:   256)\n    Iter  7475\t      0.06581120 (Batch Size:   256)\n    Iter  7476\t      0.06944505 (Batch Size:   256)\n    Iter  7477\t      0.06266852 (Batch Size:   256)\n    Iter  7478\t      0.06348785 (Batch Size:   256)\n    Iter  7479\t      0.06455902 (Batch Size:   256)\n    Iter  7480\t      0.05973470 (Batch Size:   256)\n    Iter  7481\t      0.05946769 (Batch Size:   256)\n    Iter  7482\t      0.05952082 (Batch Size:   256)\n    Iter  7483\t      0.05568097 (Batch Size:   256)\n    Iter  7484\t      0.05300639 (Batch Size:   256)\n    Iter  7485\t      0.05715012 (Batch Size:   256)\n    Iter  7486\t      0.05530949 (Batch Size:   256)\n    Iter  7487\t      0.05779042 (Batch Size:   256)\n    Iter  7488\t      0.05495460 (Batch Size:   256)\n    Iter  7489\t      0.05700416 (Batch Size:   256)\n    Iter  7490\t      0.05968375 (Batch Size:   256)\n    Iter  7491\t      0.05595208 (Batch Size:   256)\n    Iter  7492\t      0.05425492 (Batch Size:   256)\n    Iter  7493\t      0.05838875 (Batch Size:   256)\n    Iter  7494\t      0.05608580 (Batch Size:   256)\n    Iter  7495\t      0.05623507 (Batch Size:   256)\n    Iter  7496\t      0.05758265 (Batch Size:   256)\n    Iter  7497\t      0.05481825 (Batch Size:   256)\n    Iter  7498\t      0.05943520 (Batch Size:   256)\n    Iter  7499\t      0.05776149 (Batch Size:   256)\n    Iter  7500\t      0.05630761 (Batch Size:   256)\n    Iter  7501\t      0.05396911 (Batch Size:   256)\n    Iter  7502\t      0.05649958 (Batch Size:   256)\n    Iter  7503\t      0.06969726 (Batch Size:   256)\n    Iter  7504\t      0.06624626 (Batch Size:   256)\n    Iter  7505\t      0.06329966 (Batch Size:   256)\n    Iter  7506\t      0.05782030 (Batch Size:   256)\n    Iter  7507\t      0.05912420 (Batch Size:   256)\n    Iter  7508\t      0.06735457 (Batch Size:   256)\n    Iter  7509\t      0.06329240 (Batch Size:   256)\n    Iter  7510\t      0.05987510 (Batch Size:   256)\n    Iter  7511\t      0.05582617 (Batch Size:   256)\n    Iter  7512\t      0.06435123 (Batch Size:   256)\n    Iter  7513\t      0.05780308 (Batch Size:   256)\n    Iter  7514\t      0.05546268 (Batch Size:   256)\n    Iter  7515\t      0.05487657 (Batch Size:   256)\n    Iter  7516\t      0.05569168 (Batch Size:   256)\n    Iter  7517\t      0.06205456 (Batch Size:   256)\n    Iter  7518\t      0.05598100 (Batch Size:   256)\n    Iter  7519\t      0.06185574 (Batch Size:   256)\n    Iter  7520\t      0.05926365 (Batch Size:   256)\n    Iter  7521\t      0.05619003 (Batch Size:   256)\n    Iter  7522\t      0.05677776 (Batch Size:   256)\n    Iter  7523\t      0.05939727 (Batch Size:   256)\n    Iter  7524\t      0.05601463 (Batch Size:   256)\n    Iter  7525\t      0.05726255 (Batch Size:   256)\n    Iter  7526\t      0.05625932 (Batch Size:   256)\n    Iter  7527\t      0.05688788 (Batch Size:   256)\n    Iter  7528\t      0.05756877 (Batch Size:   256)\n    Iter  7529\t      0.06124171 (Batch Size:   256)\n    Iter  7530\t      0.05293180 (Batch Size:   256)\n    Iter  7531\t      0.06136287 (Batch Size:   256)\n    Iter  7532\t      0.06459878 (Batch Size:   256)\n    Iter  7533\t      0.05505110 (Batch Size:   256)\n    Iter  7534\t      0.06172611 (Batch Size:   256)\n    Iter  7535\t      0.08451668 (Batch Size:   256)\n    Iter  7536\t      0.08518558 (Batch Size:   256)\n    Iter  7537\t      0.07097671 (Batch Size:   256)\n    Iter  7538\t      0.06303544 (Batch Size:   256)\n    Iter  7539\t      0.05553460 (Batch Size:   256)\n    Iter  7540\t      0.05582627 (Batch Size:   256)\n    Iter  7541\t      0.05150105 (Batch Size:   256)\n    Iter  7542\t      0.05700236 (Batch Size:   256)\n    Iter  7543\t      0.06151777 (Batch Size:   256)\n    Iter  7544\t      0.06021285 (Batch Size:   256)\n    Iter  7545\t      0.06240281 (Batch Size:   256)\n    Iter  7546\t      0.05916093 (Batch Size:   256)\n    Iter  7547\t      0.05509389 (Batch Size:   256)\n    Iter  7548\t      0.06144711 (Batch Size:   256)\n    Iter  7549\t      0.06781346 (Batch Size:   256)\n    Iter  7550\t      0.06924518 (Batch Size:   256)\n    Iter  7551\t      0.06274793 (Batch Size:   256)\n    Iter  7552\t      0.05838095 (Batch Size:   256)\n    Iter  7553\t      0.05679963 (Batch Size:   256)\n    Iter  7554\t      0.05618353 (Batch Size:   256)\n    Iter  7555\t      0.06149578 (Batch Size:   256)\n    Iter  7556\t      0.05554684 (Batch Size:   256)\n    Iter  7557\t      0.05802220 (Batch Size:   256)\n    Iter  7558\t      0.05599345 (Batch Size:   256)\n    Iter  7559\t      0.06583012 (Batch Size:   256)\n    Iter  7560\t      0.06612324 (Batch Size:   256)\n    Iter  7561\t      0.05793104 (Batch Size:   256)\n    Iter  7562\t      0.05620820 (Batch Size:   256)\n    Iter  7563\t      0.05862088 (Batch Size:   256)\n    Iter  7564\t      0.05647577 (Batch Size:   256)\n    Iter  7565\t      0.05569686 (Batch Size:   256)\n    Iter  7566\t      0.05555112 (Batch Size:   256)\n    Iter  7567\t      0.05608914 (Batch Size:   256)\n    Iter  7568\t      0.05939183 (Batch Size:   256)\n    Iter  7569\t      0.05496157 (Batch Size:   256)\n    Iter  7570\t      0.05447528 (Batch Size:   256)\n    Iter  7571\t      0.05507379 (Batch Size:   256)\n    Iter  7572\t      0.05524997 (Batch Size:   256)\n    Iter  7573\t      0.05962322 (Batch Size:   256)\n    Iter  7574\t      0.05546886 (Batch Size:   256)\n    Iter  7575\t      0.05725741 (Batch Size:   256)\n    Iter  7576\t      0.05399729 (Batch Size:   256)\n    Iter  7577\t      0.05782382 (Batch Size:   256)\n    Iter  7578\t      0.05507187 (Batch Size:   256)\n    Iter  7579\t      0.05495543 (Batch Size:   256)\n    Iter  7580\t      0.05722595 (Batch Size:   256)\n    Iter  7581\t      0.05418871 (Batch Size:   256)\n    Iter  7582\t      0.05484341 (Batch Size:   256)\n    Iter  7583\t      0.05368381 (Batch Size:   256)\n    Iter  7584\t      0.05506787 (Batch Size:   256)\n    Iter  7585\t      0.05709995 (Batch Size:   256)\n    Iter  7586\t      0.06123147 (Batch Size:   256)\n    Iter  7587\t      0.06527492 (Batch Size:   256)\n    Iter  7588\t      0.06366392 (Batch Size:   256)\n    Iter  7589\t      0.05848433 (Batch Size:   256)\n    Iter  7590\t      0.05631235 (Batch Size:   256)\n    Iter  7591\t      0.05676424 (Batch Size:   256)\n    Iter  7592\t      0.05759246 (Batch Size:   256)\n    Iter  7593\t      0.05579347 (Batch Size:   256)\n    Iter  7594\t      0.05974072 (Batch Size:   256)\n    Iter  7595\t      0.06275507 (Batch Size:   256)\n    Iter  7596\t      0.06129265 (Batch Size:   256)\n    Iter  7597\t      0.05561752 (Batch Size:   256)\n    Iter  7598\t      0.05592317 (Batch Size:   256)\n    Iter  7599\t      0.06241517 (Batch Size:   256)\n    Iter  7600\t      0.06107474 (Batch Size:   256)\n    Iter  7601\t      0.06070663 (Batch Size:   256)\n    Iter  7602\t      0.06289970 (Batch Size:   256)\n    Iter  7603\t      0.05603646 (Batch Size:   256)\n    Iter  7604\t      0.05475146 (Batch Size:   256)\n    Iter  7605\t      0.05529929 (Batch Size:   256)\n    Iter  7606\t      0.05360970 (Batch Size:   256)\n    Iter  7607\t      0.06126343 (Batch Size:   256)\n    Iter  7608\t      0.06489287 (Batch Size:   256)\n    Iter  7609\t      0.06306390 (Batch Size:   256)\n    Iter  7610\t      0.05670503 (Batch Size:   256)\n    Iter  7611\t      0.05803314 (Batch Size:   256)\n    Iter  7612\t      0.05417036 (Batch Size:   256)\n    Iter  7613\t      0.06260269 (Batch Size:   256)\n    Iter  7614\t      0.06654136 (Batch Size:   256)\n    Iter  7615\t      0.06176796 (Batch Size:   256)\n    Iter  7616\t      0.06038806 (Batch Size:   256)\n    Iter  7617\t      0.05794013 (Batch Size:   256)\n    Iter  7618\t      0.06331716 (Batch Size:   256)\n    Iter  7619\t      0.06929258 (Batch Size:   256)\n    Iter  7620\t      0.06104831 (Batch Size:   256)\n    Iter  7621\t      0.05803327 (Batch Size:   256)\n    Iter  7622\t      0.06184399 (Batch Size:   256)\n    Iter  7623\t      0.05955061 (Batch Size:   256)\n    Iter  7624\t      0.05943994 (Batch Size:   256)\n    Iter  7625\t      0.06428452 (Batch Size:   256)\n    Iter  7626\t      0.06807066 (Batch Size:   256)\n    Iter  7627\t      0.05802035 (Batch Size:   256)\n    Iter  7628\t      0.05994182 (Batch Size:   256)\n    Iter  7629\t      0.06448755 (Batch Size:   256)\n    Iter  7630\t      0.06286606 (Batch Size:   256)\n    Iter  7631\t      0.05923919 (Batch Size:   256)\n    Iter  7632\t      0.05711398 (Batch Size:   256)\n    Iter  7633\t      0.05570229 (Batch Size:   256)\n    Iter  7634\t      0.05830823 (Batch Size:   256)\n    Iter  7635\t      0.05574635 (Batch Size:   256)\n    Iter  7636\t      0.05879892 (Batch Size:   256)\n    Iter  7637\t      0.06088110 (Batch Size:   256)\n    Iter  7638\t      0.06085539 (Batch Size:   256)\n    Iter  7639\t      0.05910800 (Batch Size:   256)\n    Iter  7640\t      0.05712119 (Batch Size:   256)\n    Iter  7641\t      0.05477588 (Batch Size:   256)\n    Iter  7642\t      0.05572155 (Batch Size:   256)\n    Iter  7643\t      0.05378975 (Batch Size:   256)\n    Iter  7644\t      0.05457284 (Batch Size:   256)\n    Iter  7645\t      0.05482872 (Batch Size:   256)\n    Iter  7646\t      0.06211891 (Batch Size:   256)\n    Iter  7647\t      0.05371740 (Batch Size:   256)\n    Iter  7648\t      0.05459544 (Batch Size:   256)\n    Iter  7649\t      0.05377839 (Batch Size:   256)\n    Iter  7650\t      0.05489786 (Batch Size:   256)\n    Iter  7651\t      0.05486558 (Batch Size:   256)\n    Iter  7652\t      0.05784225 (Batch Size:   256)\n    Iter  7653\t      0.05577823 (Batch Size:   256)\n    Iter  7654\t      0.05475028 (Batch Size:   256)\n    Iter  7655\t      0.05596734 (Batch Size:   256)\n    Iter  7656\t      0.05762945 (Batch Size:   256)\n    Iter  7657\t      0.05589598 (Batch Size:   256)\n    Iter  7658\t      0.05558652 (Batch Size:   256)\n    Iter  7659\t      0.05841647 (Batch Size:   256)\n    Iter  7660\t      0.05894610 (Batch Size:   256)\n    Iter  7661\t      0.06171653 (Batch Size:   256)\n    Iter  7662\t      0.07231895 (Batch Size:   256)\n    Iter  7663\t      0.06316625 (Batch Size:   256)\n    Iter  7664\t      0.07301777 (Batch Size:   256)\n    Iter  7665\t      0.06005985 (Batch Size:   256)\n    Iter  7666\t      0.06014167 (Batch Size:   256)\n    Iter  7667\t      0.05479392 (Batch Size:   256)\n    Iter  7668\t      0.05532699 (Batch Size:   256)\n    Iter  7669\t      0.05800464 (Batch Size:   256)\n    Iter  7670\t      0.05842255 (Batch Size:   256)\n    Iter  7671\t      0.05720239 (Batch Size:   256)\n    Iter  7672\t      0.05750576 (Batch Size:   256)\n    Iter  7673\t      0.06095642 (Batch Size:   256)\n    Iter  7674\t      0.05717970 (Batch Size:   256)\n    Iter  7675\t      0.05846995 (Batch Size:   256)\n    Iter  7676\t      0.05566959 (Batch Size:   256)\n    Iter  7677\t      0.05584370 (Batch Size:   256)\n    Iter  7678\t      0.05467232 (Batch Size:   256)\n    Iter  7679\t      0.05700017 (Batch Size:   256)\n    Iter  7680\t      0.06641707 (Batch Size:   256)\n    Iter  7681\t      0.06701424 (Batch Size:   256)\n    Iter  7682\t      0.06551172 (Batch Size:   256)\n    Iter  7683\t      0.05870169 (Batch Size:   256)\n    Iter  7684\t      0.05488160 (Batch Size:   256)\n    Iter  7685\t      0.05496539 (Batch Size:   256)\n    Iter  7686\t      0.05426158 (Batch Size:   256)\n    Iter  7687\t      0.06635744 (Batch Size:   256)\n    Iter  7688\t      0.11553806 (Batch Size:   256)\n    Iter  7689\t      0.07182838 (Batch Size:   256)\n    Iter  7690\t      0.06321262 (Batch Size:   256)\n    Iter  7691\t      0.06602141 (Batch Size:   256)\n    Iter  7692\t      0.05910772 (Batch Size:   256)\n    Iter  7693\t      0.05753452 (Batch Size:   256)\n    Iter  7694\t      0.05896172 (Batch Size:   256)\n    Iter  7695\t      0.05937715 (Batch Size:   256)\n    Iter  7696\t      0.05777499 (Batch Size:   256)\n    Iter  7697\t      0.05624564 (Batch Size:   256)\n    Iter  7698\t      0.05586473 (Batch Size:   256)\n    Iter  7699\t      0.05368524 (Batch Size:   256)\n    Iter  7700\t      0.05580106 (Batch Size:   256)\n    Iter  7701\t      0.06007119 (Batch Size:   256)\n    Iter  7702\t      0.05311470 (Batch Size:   256)\n    Iter  7703\t      0.05915517 (Batch Size:   256)\n    Iter  7704\t      0.06286474 (Batch Size:   256)\n    Iter  7705\t      0.05427732 (Batch Size:   256)\n    Iter  7706\t      0.06439020 (Batch Size:   256)\n    Iter  7707\t      0.05860012 (Batch Size:   256)\n    Iter  7708\t      0.05890224 (Batch Size:   256)\n    Iter  7709\t      0.05386370 (Batch Size:   256)\n    Iter  7710\t      0.05830599 (Batch Size:   256)\n    Iter  7711\t      0.05850369 (Batch Size:   256)\n    Iter  7712\t      0.06103583 (Batch Size:   256)\n    Iter  7713\t      0.06116976 (Batch Size:   256)\n    Iter  7714\t      0.05624342 (Batch Size:   256)\n    Iter  7715\t      0.05365572 (Batch Size:   256)\n    Iter  7716\t      0.06611016 (Batch Size:   256)\n    Iter  7717\t      0.06074620 (Batch Size:   256)\n    Iter  7718\t      0.05710734 (Batch Size:   256)\n    Iter  7719\t      0.06142871 (Batch Size:   256)\n    Iter  7720\t      0.05602887 (Batch Size:   256)\n    Iter  7721\t      0.05383070 (Batch Size:   256)\n    Iter  7722\t      0.05437894 (Batch Size:   256)\n    Iter  7723\t      0.05558395 (Batch Size:   256)\n    Iter  7724\t      0.06023769 (Batch Size:   256)\n    Iter  7725\t      0.05864396 (Batch Size:   256)\n    Iter  7726\t      0.05302197 (Batch Size:   256)\n    Iter  7727\t      0.05334211 (Batch Size:   256)\n    Iter  7728\t      0.05918354 (Batch Size:   256)\n    Iter  7729\t      0.05437279 (Batch Size:   256)\n    Iter  7730\t      0.05376228 (Batch Size:   256)\n    Iter  7731\t      0.05543879 (Batch Size:   256)\n    Iter  7732\t      0.05477791 (Batch Size:   256)\n    Iter  7733\t      0.05437308 (Batch Size:   256)\n    Iter  7734\t      0.05522415 (Batch Size:   256)\n    Iter  7735\t      0.05690965 (Batch Size:   256)\n    Iter  7736\t      0.06303266 (Batch Size:   256)\n    Iter  7737\t      0.05998503 (Batch Size:   256)\n    Iter  7738\t      0.05608359 (Batch Size:   256)\n    Iter  7739\t      0.05350212 (Batch Size:   256)\n    Iter  7740\t      0.06052771 (Batch Size:   256)\n    Iter  7741\t      0.06825309 (Batch Size:   256)\n    Iter  7742\t      0.05920379 (Batch Size:   256)\n    Iter  7743\t      0.05362600 (Batch Size:   256)\n    Iter  7744\t      0.05567078 (Batch Size:   256)\n    Iter  7745\t      0.05589059 (Batch Size:   256)\n    Iter  7746\t      0.06088538 (Batch Size:   256)\n    Iter  7747\t      0.05719103 (Batch Size:   256)\n    Iter  7748\t      0.05613037 (Batch Size:   256)\n    Iter  7749\t      0.06480527 (Batch Size:   256)\n    Iter  7750\t      0.05489160 (Batch Size:   256)\n    Iter  7751\t      0.05607600 (Batch Size:   256)\n    Iter  7752\t      0.05724110 (Batch Size:   256)\n    Iter  7753\t      0.05685499 (Batch Size:   256)\n    Iter  7754\t      0.05768234 (Batch Size:   256)\n    Iter  7755\t      0.06413952 (Batch Size:   256)\n    Iter  7756\t      0.05801312 (Batch Size:   256)\n    Iter  7757\t      0.05852291 (Batch Size:   256)\n    Iter  7758\t      0.05495865 (Batch Size:   256)\n    Iter  7759\t      0.05595384 (Batch Size:   256)\n    Iter  7760\t      0.05799534 (Batch Size:   256)\n    Iter  7761\t      0.06125436 (Batch Size:   256)\n    Iter  7762\t      0.06454204 (Batch Size:   256)\n    Iter  7763\t      0.06351463 (Batch Size:   256)\n    Iter  7764\t      0.05532177 (Batch Size:   256)\n    Iter  7765\t      0.05276609 (Batch Size:   256)\n    Iter  7766\t      0.05450060 (Batch Size:   256)\n    Iter  7767\t      0.05448100 (Batch Size:   256)\n    Iter  7768\t      0.05785489 (Batch Size:   256)\n    Iter  7769\t      0.05641129 (Batch Size:   256)\n    Iter  7770\t      0.05591844 (Batch Size:   256)\n    Iter  7771\t      0.05638421 (Batch Size:   256)\n    Iter  7772\t      0.05337371 (Batch Size:   256)\n    Iter  7773\t      0.05569490 (Batch Size:   256)\n    Iter  7774\t      0.05475501 (Batch Size:   256)\n    Iter  7775\t      0.05291375 (Batch Size:   256)\n    Iter  7776\t      0.05740290 (Batch Size:   256)\n    Iter  7777\t      0.05633936 (Batch Size:   256)\n    Iter  7778\t      0.05131208 (Batch Size:   256)\n    Iter  7779\t      0.06090172 (Batch Size:   256)\n    Iter  7780\t      0.06608933 (Batch Size:   256)\n    Iter  7781\t      0.05871123 (Batch Size:   256)\n    Iter  7782\t      0.05515894 (Batch Size:   256)\n    Iter  7783\t      0.05524539 (Batch Size:   256)\n    Iter  7784\t      0.05620617 (Batch Size:   256)\n    Iter  7785\t      0.05767172 (Batch Size:   256)\n    Iter  7786\t      0.05613855 (Batch Size:   256)\n    Iter  7787\t      0.05327995 (Batch Size:   256)\n    Iter  7788\t      0.06675099 (Batch Size:   256)\n    Iter  7789\t      0.05914911 (Batch Size:   256)\n    Iter  7790\t      0.06372921 (Batch Size:   256)\n    Iter  7791\t      0.05780524 (Batch Size:   256)\n    Iter  7792\t      0.05686066 (Batch Size:   256)\n    Iter  7793\t      0.05809602 (Batch Size:   256)\n    Iter  7794\t      0.05323306 (Batch Size:   256)\n    Iter  7795\t      0.05511927 (Batch Size:   256)\n    Iter  7796\t      0.05569172 (Batch Size:   256)\n    Iter  7797\t      0.05587696 (Batch Size:   256)\n    Iter  7798\t      0.05435286 (Batch Size:   256)\n    Iter  7799\t      0.05942397 (Batch Size:   256)\n    Iter  7800\t      0.07101991 (Batch Size:   256)\n    Iter  7801\t      0.05867597 (Batch Size:   256)\n    Iter  7802\t      0.05608883 (Batch Size:   256)\n    Iter  7803\t      0.05356277 (Batch Size:   256)\n    Iter  7804\t      0.06322205 (Batch Size:   256)\n    Iter  7805\t      0.05413663 (Batch Size:   256)\n    Iter  7806\t      0.05422371 (Batch Size:   256)\n    Iter  7807\t      0.05748728 (Batch Size:   256)\n    Iter  7808\t      0.05639246 (Batch Size:   256)\n    Iter  7809\t      0.06408239 (Batch Size:   256)\n    Iter  7810\t      0.06962072 (Batch Size:   256)\n    Iter  7811\t      0.06120875 (Batch Size:   256)\n    Iter  7812\t      0.05402593 (Batch Size:   256)\n    Iter  7813\t      0.05699117 (Batch Size:   256)\n    Iter  7814\t      0.05897879 (Batch Size:   256)\n    Iter  7815\t      0.05758408 (Batch Size:   256)\n    Iter  7816\t      0.05443248 (Batch Size:   256)\n    Iter  7817\t      0.05624516 (Batch Size:   256)\n    Iter  7818\t      0.05642803 (Batch Size:   256)\n    Iter  7819\t      0.05389383 (Batch Size:   256)\n    Iter  7820\t      0.06232297 (Batch Size:   256)\n    Iter  7821\t      0.06764783 (Batch Size:   256)\n    Iter  7822\t      0.06173023 (Batch Size:   256)\n    Iter  7823\t      0.07372461 (Batch Size:   256)\n    Iter  7824\t      0.06228271 (Batch Size:   256)\n    Iter  7825\t      0.05209645 (Batch Size:   256)\n    Iter  7826\t      0.05668489 (Batch Size:   256)\n    Iter  7827\t      0.05035464 (Batch Size:   256)\n    Iter  7828\t      0.05399167 (Batch Size:   256)\n    Iter  7829\t      0.05569352 (Batch Size:   256)\n    Iter  7830\t      0.05354486 (Batch Size:   256)\n    Iter  7831\t      0.05734522 (Batch Size:   256)\n    Iter  7832\t      0.06059904 (Batch Size:   256)\n    Iter  7833\t      0.06031002 (Batch Size:   256)\n    Iter  7834\t      0.07013492 (Batch Size:   256)\n    Iter  7835\t      0.07527796 (Batch Size:   256)\n    Iter  7836\t      0.06134784 (Batch Size:   256)\n    Iter  7837\t      0.05663419 (Batch Size:   256)\n    Iter  7838\t      0.06253962 (Batch Size:   256)\n    Iter  7839\t      0.06334524 (Batch Size:   256)\n    Iter  7840\t      0.06465257 (Batch Size:   256)\n    Iter  7841\t      0.07507678 (Batch Size:   256)\n    Iter  7842\t      0.09150882 (Batch Size:   256)\n    Iter  7843\t      0.06499598 (Batch Size:   256)\n    Iter  7844\t      0.05608260 (Batch Size:   256)\n    Iter  7845\t      0.05649982 (Batch Size:   256)\n    Iter  7846\t      0.05578034 (Batch Size:   256)\n    Iter  7847\t      0.05520532 (Batch Size:   256)\n    Iter  7848\t      0.05726595 (Batch Size:   256)\n    Iter  7849\t      0.06250349 (Batch Size:   256)\n    Iter  7850\t      0.05351320 (Batch Size:   256)\n    Iter  7851\t      0.05480534 (Batch Size:   256)\n    Iter  7852\t      0.05832803 (Batch Size:   256)\n    Iter  7853\t      0.05909955 (Batch Size:   256)\n    Iter  7854\t      0.05231834 (Batch Size:   256)\n    Iter  7855\t      0.06966205 (Batch Size:   256)\n    Iter  7856\t      0.07489848 (Batch Size:   256)\n    Iter  7857\t      0.06467954 (Batch Size:   256)\n    Iter  7858\t      0.06628634 (Batch Size:   256)\n    Iter  7859\t      0.05996636 (Batch Size:   256)\n    Iter  7860\t      0.05829870 (Batch Size:   256)\n    Iter  7861\t      0.05537333 (Batch Size:   256)\n    Iter  7862\t      0.05986478 (Batch Size:   256)\n    Iter  7863\t      0.05214960 (Batch Size:   256)\n    Iter  7864\t      0.05531993 (Batch Size:   256)\n    Iter  7865\t      0.05748589 (Batch Size:   256)\n    Iter  7866\t      0.07105356 (Batch Size:   256)\n    Iter  7867\t      0.05931880 (Batch Size:   256)\n    Iter  7868\t      0.05832549 (Batch Size:   256)\n    Iter  7869\t      0.05410863 (Batch Size:   256)\n    Iter  7870\t      0.05322476 (Batch Size:   256)\n    Iter  7871\t      0.05461712 (Batch Size:   256)\n    Iter  7872\t      0.05645870 (Batch Size:   256)\n    Iter  7873\t      0.05454925 (Batch Size:   256)\n    Iter  7874\t      0.05450606 (Batch Size:   256)\n    Iter  7875\t      0.05571428 (Batch Size:   256)\n    Iter  7876\t      0.05876400 (Batch Size:   256)\n    Iter  7877\t      0.05685890 (Batch Size:   256)\n    Iter  7878\t      0.05902509 (Batch Size:   256)\n    Iter  7879\t      0.05749873 (Batch Size:   256)\n    Iter  7880\t      0.05414377 (Batch Size:   256)\n    Iter  7881\t      0.05473370 (Batch Size:   256)\n    Iter  7882\t      0.05312830 (Batch Size:   256)\n    Iter  7883\t      0.05489946 (Batch Size:   256)\n    Iter  7884\t      0.05481173 (Batch Size:   256)\n    Iter  7885\t      0.05557891 (Batch Size:   256)\n    Iter  7886\t      0.05467387 (Batch Size:   256)\n    Iter  7887\t      0.05796980 (Batch Size:   256)\n    Iter  7888\t      0.05527282 (Batch Size:   256)\n    Iter  7889\t      0.06141249 (Batch Size:   256)\n    Iter  7890\t      0.05892140 (Batch Size:   256)\n    Iter  7891\t      0.06743320 (Batch Size:   256)\n    Iter  7892\t      0.06066081 (Batch Size:   256)\n    Iter  7893\t      0.05786813 (Batch Size:   256)\n    Iter  7894\t      0.06106153 (Batch Size:   256)\n    Iter  7895\t      0.05995789 (Batch Size:   256)\n    Iter  7896\t      0.05484207 (Batch Size:   256)\n    Iter  7897\t      0.05670930 (Batch Size:   256)\n    Iter  7898\t      0.06299434 (Batch Size:   256)\n    Iter  7899\t      0.05377066 (Batch Size:   256)\n    Iter  7900\t      0.06910928 (Batch Size:   256)\n    Iter  7901\t      0.06395335 (Batch Size:   256)\n    Iter  7902\t      0.05492929 (Batch Size:   256)\n    Iter  7903\t      0.05349684 (Batch Size:   256)\n    Iter  7904\t      0.05486807 (Batch Size:   256)\n    Iter  7905\t      0.05260753 (Batch Size:   256)\n    Iter  7906\t      0.05936639 (Batch Size:   256)\n    Iter  7907\t      0.05915706 (Batch Size:   256)\n    Iter  7908\t      0.05871331 (Batch Size:   256)\n    Iter  7909\t      0.06434747 (Batch Size:   256)\n    Iter  7910\t      0.05610167 (Batch Size:   256)\n    Iter  7911\t      0.05606448 (Batch Size:   256)\n    Iter  7912\t      0.05355206 (Batch Size:   256)\n    Iter  7913\t      0.05307222 (Batch Size:   256)\n    Iter  7914\t      0.05363512 (Batch Size:   256)\n    Iter  7915\t      0.05602724 (Batch Size:   256)\n    Iter  7916\t      0.05577479 (Batch Size:   256)\n    Iter  7917\t      0.05972845 (Batch Size:   256)\n    Iter  7918\t      0.05216118 (Batch Size:   256)\n    Iter  7919\t      0.05465152 (Batch Size:   256)\n    Iter  7920\t      0.05546668 (Batch Size:   256)\n    Iter  7921\t      0.05337955 (Batch Size:   256)\n    Iter  7922\t      0.05580873 (Batch Size:   256)\n    Iter  7923\t      0.05615040 (Batch Size:   256)\n    Iter  7924\t      0.05641980 (Batch Size:   256)\n    Iter  7925\t      0.05409671 (Batch Size:   256)\n    Iter  7926\t      0.05703195 (Batch Size:   256)\n    Iter  7927\t      0.05535271 (Batch Size:   256)\n    Iter  7928\t      0.06051554 (Batch Size:   256)\n    Iter  7929\t      0.06012499 (Batch Size:   256)\n    Iter  7930\t      0.05344044 (Batch Size:   256)\n    Iter  7931\t      0.05606197 (Batch Size:   256)\n    Iter  7932\t      0.06081692 (Batch Size:   256)\n    Iter  7933\t      0.05636086 (Batch Size:   256)\n    Iter  7934\t      0.05323541 (Batch Size:   256)\n    Iter  7935\t      0.06454978 (Batch Size:   256)\n    Iter  7936\t      0.06502240 (Batch Size:   256)\n    Iter  7937\t      0.05818440 (Batch Size:   256)\n    Iter  7938\t      0.05417767 (Batch Size:   256)\n    Iter  7939\t      0.05598915 (Batch Size:   256)\n    Iter  7940\t      0.05429490 (Batch Size:   256)\n    Iter  7941\t      0.05288467 (Batch Size:   256)\n    Iter  7942\t      0.05659447 (Batch Size:   256)\n    Iter  7943\t      0.05886043 (Batch Size:   256)\n    Iter  7944\t      0.05843967 (Batch Size:   256)\n    Iter  7945\t      0.05317604 (Batch Size:   256)\n    Iter  7946\t      0.05372937 (Batch Size:   256)\n    Iter  7947\t      0.06056525 (Batch Size:   256)\n    Iter  7948\t      0.05752921 (Batch Size:   256)\n    Iter  7949\t      0.05468741 (Batch Size:   256)\n    Iter  7950\t      0.05471630 (Batch Size:   256)\n    Iter  7951\t      0.05233722 (Batch Size:   256)\n    Iter  7952\t      0.05712330 (Batch Size:   256)\n    Iter  7953\t      0.05389023 (Batch Size:   256)\n    Iter  7954\t      0.05558027 (Batch Size:   256)\n    Iter  7955\t      0.05288823 (Batch Size:   256)\n    Iter  7956\t      0.06069673 (Batch Size:   256)\n    Iter  7957\t      0.07328540 (Batch Size:   256)\n    Iter  7958\t      0.05554338 (Batch Size:   256)\n    Iter  7959\t      0.05272448 (Batch Size:   256)\n    Iter  7960\t      0.05754735 (Batch Size:   256)\n    Iter  7961\t      0.06114228 (Batch Size:   256)\n    Iter  7962\t      0.05731129 (Batch Size:   256)\n    Iter  7963\t      0.06604529 (Batch Size:   256)\n    Iter  7964\t      0.07304571 (Batch Size:   256)\n    Iter  7965\t      0.07091383 (Batch Size:   256)\n    Iter  7966\t      0.06466667 (Batch Size:   256)\n    Iter  7967\t      0.06256921 (Batch Size:   256)\n    Iter  7968\t      0.05651639 (Batch Size:   256)\n    Iter  7969\t      0.05513958 (Batch Size:   256)\n    Iter  7970\t      0.05478681 (Batch Size:   256)\n    Iter  7971\t      0.06005759 (Batch Size:   256)\n    Iter  7972\t      0.07341038 (Batch Size:   256)\n    Iter  7973\t      0.08349878 (Batch Size:   256)\n    Iter  7974\t      0.06431799 (Batch Size:   256)\n    Iter  7975\t      0.06348470 (Batch Size:   256)\n    Iter  7976\t      0.06065744 (Batch Size:   256)\n    Iter  7977\t      0.05626355 (Batch Size:   256)\n    Iter  7978\t      0.05152545 (Batch Size:   256)\n    Iter  7979\t      0.05425033 (Batch Size:   256)\n    Iter  7980\t      0.05330382 (Batch Size:   256)\n    Iter  7981\t      0.05603302 (Batch Size:   256)\n    Iter  7982\t      0.05558114 (Batch Size:   256)\n    Iter  7983\t      0.05875617 (Batch Size:   256)\n    Iter  7984\t      0.05186790 (Batch Size:   256)\n    Iter  7985\t      0.05485151 (Batch Size:   256)\n    Iter  7986\t      0.05685557 (Batch Size:   256)\n    Iter  7987\t      0.05381085 (Batch Size:   256)\n    Iter  7988\t      0.05206255 (Batch Size:   256)\n    Iter  7989\t      0.05528056 (Batch Size:   256)\n    Iter  7990\t      0.05319751 (Batch Size:   256)\n    Iter  7991\t      0.05354056 (Batch Size:   256)\n    Iter  7992\t      0.05780882 (Batch Size:   256)\n    Iter  7993\t      0.05829908 (Batch Size:   256)\n    Iter  7994\t      0.05695718 (Batch Size:   256)\n    Iter  7995\t      0.05551409 (Batch Size:   256)\n    Iter  7996\t      0.05859660 (Batch Size:   256)\n    Iter  7997\t      0.05382057 (Batch Size:   256)\n    Iter  7998\t      0.05811631 (Batch Size:   256)\n    Iter  7999\t      0.05590141 (Batch Size:   256)\n    Iter  8000\t      0.05174424 (Batch Size:   256)\n    Iter  8001\t      0.05253098 (Batch Size:   256)\n    Iter  8002\t      0.05342054 (Batch Size:   256)\n    Iter  8003\t      0.05307990 (Batch Size:   256)\n    Iter  8004\t      0.05468613 (Batch Size:   256)\n    Iter  8005\t      0.05442604 (Batch Size:   256)\n    Iter  8006\t      0.05339825 (Batch Size:   256)\n    Iter  8007\t      0.05429420 (Batch Size:   256)\n    Iter  8008\t      0.05654067 (Batch Size:   256)\n    Iter  8009\t      0.05508211 (Batch Size:   256)\n    Iter  8010\t      0.05349696 (Batch Size:   256)\n    Iter  8011\t      0.05544758 (Batch Size:   256)\n    Iter  8012\t      0.06116689 (Batch Size:   256)\n    Iter  8013\t      0.05579503 (Batch Size:   256)\n    Iter  8014\t      0.05365294 (Batch Size:   256)\n    Iter  8015\t      0.05767300 (Batch Size:   256)\n    Iter  8016\t      0.05584781 (Batch Size:   256)\n    Iter  8017\t      0.05970771 (Batch Size:   256)\n    Iter  8018\t      0.05764452 (Batch Size:   256)\n    Iter  8019\t      0.05747849 (Batch Size:   256)\n    Iter  8020\t      0.05991621 (Batch Size:   256)\n    Iter  8021\t      0.05312521 (Batch Size:   256)\n    Iter  8022\t      0.05670248 (Batch Size:   256)\n    Iter  8023\t      0.05450726 (Batch Size:   256)\n    Iter  8024\t      0.05640271 (Batch Size:   256)\n    Iter  8025\t      0.06535659 (Batch Size:   256)\n    Iter  8026\t      0.05985454 (Batch Size:   256)\n    Iter  8027\t      0.06083816 (Batch Size:   256)\n    Iter  8028\t      0.05869785 (Batch Size:   256)\n    Iter  8029\t      0.05703888 (Batch Size:   256)\n    Iter  8030\t      0.05525294 (Batch Size:   256)\n    Iter  8031\t      0.05483073 (Batch Size:   256)\n    Iter  8032\t      0.05988662 (Batch Size:   256)\n    Iter  8033\t      0.05403974 (Batch Size:   256)\n    Iter  8034\t      0.05500322 (Batch Size:   256)\n    Iter  8035\t      0.05520184 (Batch Size:   256)\n    Iter  8036\t      0.06064046 (Batch Size:   256)\n    Iter  8037\t      0.05284742 (Batch Size:   256)\n    Iter  8038\t      0.05414050 (Batch Size:   256)\n    Iter  8039\t      0.05496959 (Batch Size:   256)\n    Iter  8040\t      0.06509560 (Batch Size:   256)\n    Iter  8041\t      0.05921120 (Batch Size:   256)\n    Iter  8042\t      0.05339250 (Batch Size:   256)\n    Iter  8043\t      0.06326075 (Batch Size:   256)\n    Iter  8044\t      0.05647129 (Batch Size:   256)\n    Iter  8045\t      0.05607505 (Batch Size:   256)\n    Iter  8046\t      0.05490997 (Batch Size:   256)\n    Iter  8047\t      0.05442737 (Batch Size:   256)\n    Iter  8048\t      0.05598943 (Batch Size:   256)\n    Iter  8049\t      0.05563273 (Batch Size:   256)\n    Iter  8050\t      0.05331308 (Batch Size:   256)\n    Iter  8051\t      0.05742230 (Batch Size:   256)\n    Iter  8052\t      0.06734103 (Batch Size:   256)\n    Iter  8053\t      0.07738712 (Batch Size:   256)\n    Iter  8054\t      0.06170272 (Batch Size:   256)\n    Iter  8055\t      0.05759256 (Batch Size:   256)\n    Iter  8056\t      0.05918480 (Batch Size:   256)\n    Iter  8057\t      0.05669332 (Batch Size:   256)\n    Iter  8058\t      0.05333532 (Batch Size:   256)\n    Iter  8059\t      0.05383305 (Batch Size:   256)\n    Iter  8060\t      0.05271690 (Batch Size:   256)\n    Iter  8061\t      0.05498279 (Batch Size:   256)\n    Iter  8062\t      0.05757906 (Batch Size:   256)\n    Iter  8063\t      0.05684735 (Batch Size:   256)\n    Iter  8064\t      0.05646144 (Batch Size:   256)\n    Iter  8065\t      0.05386705 (Batch Size:   256)\n    Iter  8066\t      0.05897146 (Batch Size:   256)\n    Iter  8067\t      0.05789775 (Batch Size:   256)\n    Iter  8068\t      0.05437748 (Batch Size:   256)\n    Iter  8069\t      0.05842426 (Batch Size:   256)\n    Iter  8070\t      0.05590320 (Batch Size:   256)\n    Iter  8071\t      0.05596280 (Batch Size:   256)\n    Iter  8072\t      0.05204653 (Batch Size:   256)\n    Iter  8073\t      0.05845072 (Batch Size:   256)\n    Iter  8074\t      0.05889866 (Batch Size:   256)\n    Iter  8075\t      0.05451594 (Batch Size:   256)\n    Iter  8076\t      0.05649125 (Batch Size:   256)\n    Iter  8077\t      0.06139566 (Batch Size:   256)\n    Iter  8078\t      0.05431133 (Batch Size:   256)\n    Iter  8079\t      0.05522157 (Batch Size:   256)\n    Iter  8080\t      0.05084787 (Batch Size:   256)\n    Iter  8081\t      0.05757951 (Batch Size:   256)\n    Iter  8082\t      0.05330457 (Batch Size:   256)\n    Iter  8083\t      0.05201260 (Batch Size:   256)\n    Iter  8084\t      0.05794069 (Batch Size:   256)\n    Iter  8085\t      0.06266133 (Batch Size:   256)\n    Iter  8086\t      0.05571825 (Batch Size:   256)\n    Iter  8087\t      0.05331848 (Batch Size:   256)\n    Iter  8088\t      0.06252366 (Batch Size:   256)\n    Iter  8089\t      0.06745253 (Batch Size:   256)\n    Iter  8090\t      0.07417898 (Batch Size:   256)\n    Iter  8091\t      0.05432044 (Batch Size:   256)\n    Iter  8092\t      0.05550756 (Batch Size:   256)\n    Iter  8093\t      0.05612284 (Batch Size:   256)\n    Iter  8094\t      0.05718724 (Batch Size:   256)\n    Iter  8095\t      0.06036287 (Batch Size:   256)\n    Iter  8096\t      0.06032963 (Batch Size:   256)\n    Iter  8097\t      0.05385294 (Batch Size:   256)\n    Iter  8098\t      0.06276784 (Batch Size:   256)\n    Iter  8099\t      0.05849988 (Batch Size:   256)\n    Iter  8100\t      0.05481131 (Batch Size:   256)\n    Iter  8101\t      0.05277113 (Batch Size:   256)\n    Iter  8102\t      0.05275182 (Batch Size:   256)\n    Iter  8103\t      0.05542553 (Batch Size:   256)\n    Iter  8104\t      0.05382519 (Batch Size:   256)\n    Iter  8105\t      0.05165266 (Batch Size:   256)\n    Iter  8106\t      0.05431391 (Batch Size:   256)\n    Iter  8107\t      0.05998152 (Batch Size:   256)\n    Iter  8108\t      0.05946161 (Batch Size:   256)\n    Iter  8109\t      0.05674183 (Batch Size:   256)\n    Iter  8110\t      0.05664551 (Batch Size:   256)\n    Iter  8111\t      0.05592306 (Batch Size:   256)\n    Iter  8112\t      0.05781206 (Batch Size:   256)\n    Iter  8113\t      0.05512299 (Batch Size:   256)\n    Iter  8114\t      0.06094738 (Batch Size:   256)\n    Iter  8115\t      0.05637734 (Batch Size:   256)\n    Iter  8116\t      0.05348417 (Batch Size:   256)\n    Iter  8117\t      0.05187049 (Batch Size:   256)\n    Iter  8118\t      0.05694745 (Batch Size:   256)\n    Iter  8119\t      0.05443156 (Batch Size:   256)\n    Iter  8120\t      0.05431053 (Batch Size:   256)\n    Iter  8121\t      0.05154416 (Batch Size:   256)\n    Iter  8122\t      0.05570949 (Batch Size:   256)\n    Iter  8123\t      0.05194441 (Batch Size:   256)\n    Iter  8124\t      0.05204293 (Batch Size:   256)\n    Iter  8125\t      0.05572529 (Batch Size:   256)\n    Iter  8126\t      0.05322898 (Batch Size:   256)\n    Iter  8127\t      0.05243092 (Batch Size:   256)\n    Iter  8128\t      0.05312762 (Batch Size:   256)\n    Iter  8129\t      0.05554592 (Batch Size:   256)\n    Iter  8130\t      0.05555326 (Batch Size:   256)\n    Iter  8131\t      0.05267668 (Batch Size:   256)\n    Iter  8132\t      0.05060346 (Batch Size:   256)\n    Iter  8133\t      0.05308796 (Batch Size:   256)\n    Iter  8134\t      0.05380552 (Batch Size:   256)\n    Iter  8135\t      0.05499659 (Batch Size:   256)\n    Iter  8136\t      0.05845265 (Batch Size:   256)\n    Iter  8137\t      0.05839557 (Batch Size:   256)\n    Iter  8138\t      0.06509343 (Batch Size:   256)\n    Iter  8139\t      0.08146027 (Batch Size:   256)\n    Iter  8140\t      0.08876054 (Batch Size:   256)\n    Iter  8141\t      0.07038810 (Batch Size:   256)\n    Iter  8142\t      0.06387852 (Batch Size:   256)\n    Iter  8143\t      0.05328291 (Batch Size:   256)\n    Iter  8144\t      0.05886538 (Batch Size:   256)\n    Iter  8145\t      0.05539079 (Batch Size:   256)\n    Iter  8146\t      0.05217519 (Batch Size:   256)\n    Iter  8147\t      0.05104444 (Batch Size:   256)\n    Iter  8148\t      0.05042006 (Batch Size:   256)\n    Iter  8149\t      0.05649449 (Batch Size:   256)\n    Iter  8150\t      0.06513301 (Batch Size:   256)\n    Iter  8151\t      0.07191825 (Batch Size:   256)\n    Iter  8152\t      0.06578920 (Batch Size:   256)\n    Iter  8153\t      0.05462563 (Batch Size:   256)\n    Iter  8154\t      0.05389261 (Batch Size:   256)\n    Iter  8155\t      0.05452996 (Batch Size:   256)\n    Iter  8156\t      0.05245033 (Batch Size:   256)\n    Iter  8157\t      0.06690459 (Batch Size:   256)\n    Iter  8158\t      0.06599486 (Batch Size:   256)\n    Iter  8159\t      0.05892718 (Batch Size:   256)\n    Iter  8160\t      0.06143553 (Batch Size:   256)\n    Iter  8161\t      0.05410493 (Batch Size:   256)\n    Iter  8162\t      0.05549942 (Batch Size:   256)\n    Iter  8163\t      0.05577150 (Batch Size:   256)\n    Iter  8164\t      0.05715747 (Batch Size:   256)\n    Iter  8165\t      0.05577974 (Batch Size:   256)\n    Iter  8166\t      0.05907804 (Batch Size:   256)\n    Iter  8167\t      0.05699599 (Batch Size:   256)\n    Iter  8168\t      0.05656307 (Batch Size:   256)\n    Iter  8169\t      0.05534615 (Batch Size:   256)\n    Iter  8170\t      0.05134209 (Batch Size:   256)\n    Iter  8171\t      0.05495412 (Batch Size:   256)\n    Iter  8172\t      0.05475744 (Batch Size:   256)\n    Iter  8173\t      0.05359431 (Batch Size:   256)\n    Iter  8174\t      0.06225657 (Batch Size:   256)\n    Iter  8175\t      0.07620067 (Batch Size:   256)\n    Iter  8176\t      0.05671248 (Batch Size:   256)\n    Iter  8177\t      0.05111215 (Batch Size:   256)\n    Iter  8178\t      0.05159425 (Batch Size:   256)\n    Iter  8179\t      0.05940701 (Batch Size:   256)\n    Iter  8180\t      0.05572273 (Batch Size:   256)\n    Iter  8181\t      0.05861253 (Batch Size:   256)\n    Iter  8182\t      0.05147140 (Batch Size:   256)\n    Iter  8183\t      0.05498483 (Batch Size:   256)\n    Iter  8184\t      0.05456479 (Batch Size:   256)\n    Iter  8185\t      0.05733100 (Batch Size:   256)\n    Iter  8186\t      0.05262199 (Batch Size:   256)\n    Iter  8187\t      0.05434695 (Batch Size:   256)\n    Iter  8188\t      0.05221221 (Batch Size:   256)\n    Iter  8189\t      0.04788766 (Batch Size:   256)\n    Iter  8190\t      0.05397036 (Batch Size:   256)\n    Iter  8191\t      0.05537255 (Batch Size:   256)\n    Iter  8192\t      0.05263764 (Batch Size:   256)\n    Iter  8193\t      0.05143921 (Batch Size:   256)\n    Iter  8194\t      0.05433145 (Batch Size:   256)\n    Iter  8195\t      0.05822115 (Batch Size:   256)\n    Iter  8196\t      0.05463840 (Batch Size:   256)\n    Iter  8197\t      0.06319610 (Batch Size:   256)\n    Iter  8198\t      0.06052422 (Batch Size:   256)\n    Iter  8199\t      0.05868795 (Batch Size:   256)\n    Iter  8200\t      0.05521126 (Batch Size:   256)\n    Iter  8201\t      0.06035919 (Batch Size:   256)\n    Iter  8202\t      0.05469841 (Batch Size:   256)\n    Iter  8203\t      0.05624369 (Batch Size:   256)\n    Iter  8204\t      0.05258689 (Batch Size:   256)\n    Iter  8205\t      0.05208555 (Batch Size:   256)\n    Iter  8206\t      0.05177272 (Batch Size:   256)\n    Iter  8207\t      0.05050976 (Batch Size:   256)\n    Iter  8208\t      0.05006492 (Batch Size:   256)\n    Iter  8209\t      0.05668762 (Batch Size:   256)\n    Iter  8210\t      0.05687611 (Batch Size:   256)\n    Iter  8211\t      0.06326605 (Batch Size:   256)\n    Iter  8212\t      0.05502721 (Batch Size:   256)\n    Iter  8213\t      0.05218313 (Batch Size:   256)\n    Iter  8214\t      0.05268762 (Batch Size:   256)\n    Iter  8215\t      0.04952379 (Batch Size:   256)\n    Iter  8216\t      0.05460178 (Batch Size:   256)\n    Iter  8217\t      0.05736213 (Batch Size:   256)\n    Iter  8218\t      0.06145699 (Batch Size:   256)\n    Iter  8219\t      0.06091303 (Batch Size:   256)\n    Iter  8220\t      0.05049787 (Batch Size:   256)\n    Iter  8221\t      0.05893803 (Batch Size:   256)\n    Iter  8222\t      0.05306690 (Batch Size:   256)\n    Iter  8223\t      0.05481940 (Batch Size:   256)\n    Iter  8224\t      0.05318337 (Batch Size:   256)\n    Iter  8225\t      0.05253787 (Batch Size:   256)\n    Iter  8226\t      0.05497061 (Batch Size:   256)\n    Iter  8227\t      0.05608746 (Batch Size:   256)\n    Iter  8228\t      0.05898990 (Batch Size:   256)\n    Iter  8229\t      0.05396341 (Batch Size:   256)\n    Iter  8230\t      0.05699231 (Batch Size:   256)\n    Iter  8231\t      0.05546230 (Batch Size:   256)\n    Iter  8232\t      0.05141941 (Batch Size:   256)\n    Iter  8233\t      0.05701336 (Batch Size:   256)\n    Iter  8234\t      0.06139193 (Batch Size:   256)\n    Iter  8235\t      0.05383006 (Batch Size:   256)\n    Iter  8236\t      0.05582547 (Batch Size:   256)\n    Iter  8237\t      0.05149700 (Batch Size:   256)\n    Iter  8238\t      0.05092420 (Batch Size:   256)\n    Iter  8239\t      0.05077397 (Batch Size:   256)\n    Iter  8240\t      0.05250991 (Batch Size:   256)\n    Iter  8241\t      0.05129038 (Batch Size:   256)\n    Iter  8242\t      0.05515273 (Batch Size:   256)\n    Iter  8243\t      0.05866544 (Batch Size:   256)\n    Iter  8244\t      0.05401826 (Batch Size:   256)\n    Iter  8245\t      0.05516304 (Batch Size:   256)\n    Iter  8246\t      0.05388111 (Batch Size:   256)\n    Iter  8247\t      0.05225471 (Batch Size:   256)\n    Iter  8248\t      0.05379101 (Batch Size:   256)\n    Iter  8249\t      0.05785512 (Batch Size:   256)\n    Iter  8250\t      0.05302159 (Batch Size:   256)\n    Iter  8251\t      0.06173056 (Batch Size:   256)\n    Iter  8252\t      0.05922939 (Batch Size:   256)\n    Iter  8253\t      0.05294407 (Batch Size:   256)\n    Iter  8254\t      0.05015071 (Batch Size:   256)\n    Iter  8255\t      0.05381595 (Batch Size:   256)\n    Iter  8256\t      0.05729012 (Batch Size:   256)\n    Iter  8257\t      0.05710358 (Batch Size:   256)\n    Iter  8258\t      0.05427593 (Batch Size:   256)\n    Iter  8259\t      0.05797453 (Batch Size:   256)\n    Iter  8260\t      0.05275860 (Batch Size:   256)\n    Iter  8261\t      0.05228620 (Batch Size:   256)\n    Iter  8262\t      0.05090059 (Batch Size:   256)\n    Iter  8263\t      0.05380987 (Batch Size:   256)\n    Iter  8264\t      0.05753742 (Batch Size:   256)\n    Iter  8265\t      0.05702755 (Batch Size:   256)\n    Iter  8266\t      0.05354496 (Batch Size:   256)\n    Iter  8267\t      0.05765820 (Batch Size:   256)\n    Iter  8268\t      0.05377969 (Batch Size:   256)\n    Iter  8269\t      0.05580459 (Batch Size:   256)\n    Iter  8270\t      0.05419277 (Batch Size:   256)\n    Iter  8271\t      0.05251946 (Batch Size:   256)\n    Iter  8272\t      0.05411304 (Batch Size:   256)\n    Iter  8273\t      0.05372879 (Batch Size:   256)\n    Iter  8274\t      0.05151549 (Batch Size:   256)\n    Iter  8275\t      0.05214930 (Batch Size:   256)\n    Iter  8276\t      0.05246646 (Batch Size:   256)\n    Iter  8277\t      0.05344626 (Batch Size:   256)\n    Iter  8278\t      0.05318122 (Batch Size:   256)\n    Iter  8279\t      0.05084353 (Batch Size:   256)\n    Iter  8280\t      0.05275977 (Batch Size:   256)\n    Iter  8281\t      0.05082923 (Batch Size:   256)\n    Iter  8282\t      0.05258767 (Batch Size:   256)\n    Iter  8283\t      0.05330144 (Batch Size:   256)\n    Iter  8284\t      0.05333345 (Batch Size:   256)\n    Iter  8285\t      0.04946962 (Batch Size:   256)\n    Iter  8286\t      0.05363723 (Batch Size:   256)\n    Iter  8287\t      0.05806392 (Batch Size:   256)\n    Iter  8288\t      0.05238026 (Batch Size:   256)\n    Iter  8289\t      0.05219555 (Batch Size:   256)\n    Iter  8290\t      0.06188764 (Batch Size:   256)\n    Iter  8291\t      0.05628271 (Batch Size:   256)\n    Iter  8292\t      0.05330898 (Batch Size:   256)\n    Iter  8293\t      0.05103243 (Batch Size:   256)\n    Iter  8294\t      0.05305382 (Batch Size:   256)\n    Iter  8295\t      0.05234426 (Batch Size:   256)\n    Iter  8296\t      0.05068663 (Batch Size:   256)\n    Iter  8297\t      0.04903048 (Batch Size:   256)\n    Iter  8298\t      0.05216781 (Batch Size:   256)\n    Iter  8299\t      0.05270936 (Batch Size:   256)\n    Iter  8300\t      0.06260732 (Batch Size:   256)\n    Iter  8301\t      0.05212006 (Batch Size:   256)\n    Iter  8302\t      0.05492153 (Batch Size:   256)\n    Iter  8303\t      0.05243442 (Batch Size:   256)\n    Iter  8304\t      0.05081151 (Batch Size:   256)\n    Iter  8305\t      0.05342687 (Batch Size:   256)\n    Iter  8306\t      0.05237157 (Batch Size:   256)\n    Iter  8307\t      0.05284065 (Batch Size:   256)\n    Iter  8308\t      0.06116516 (Batch Size:   256)\n    Iter  8309\t      0.05298161 (Batch Size:   256)\n    Iter  8310\t      0.05558883 (Batch Size:   256)\n    Iter  8311\t      0.05608406 (Batch Size:   256)\n    Iter  8312\t      0.07000083 (Batch Size:   256)\n    Iter  8313\t      0.06414757 (Batch Size:   256)\n    Iter  8314\t      0.07714331 (Batch Size:   256)\n    Iter  8315\t      0.06890526 (Batch Size:   256)\n    Iter  8316\t      0.05808465 (Batch Size:   256)\n    Iter  8317\t      0.05433387 (Batch Size:   256)\n    Iter  8318\t      0.05397101 (Batch Size:   256)\n    Iter  8319\t      0.05814583 (Batch Size:   256)\n    Iter  8320\t      0.05596969 (Batch Size:   256)\n    Iter  8321\t      0.05598049 (Batch Size:   256)\n    Iter  8322\t      0.05642846 (Batch Size:   256)\n    Iter  8323\t      0.05328472 (Batch Size:   256)\n    Iter  8324\t      0.05230033 (Batch Size:   256)\n    Iter  8325\t      0.05290618 (Batch Size:   256)\n    Iter  8326\t      0.05732506 (Batch Size:   256)\n    Iter  8327\t      0.04959061 (Batch Size:   256)\n    Iter  8328\t      0.05048595 (Batch Size:   256)\n    Iter  8329\t      0.05535416 (Batch Size:   256)\n    Iter  8330\t      0.05018381 (Batch Size:   256)\n    Iter  8331\t      0.06158922 (Batch Size:   256)\n    Iter  8332\t      0.05917894 (Batch Size:   256)\n    Iter  8333\t      0.05516738 (Batch Size:   256)\n    Iter  8334\t      0.04931854 (Batch Size:   256)\n    Iter  8335\t      0.05076213 (Batch Size:   256)\n    Iter  8336\t      0.05426132 (Batch Size:   256)\n    Iter  8337\t      0.05191422 (Batch Size:   256)\n    Iter  8338\t      0.05174882 (Batch Size:   256)\n    Iter  8339\t      0.05052534 (Batch Size:   256)\n    Iter  8340\t      0.05246424 (Batch Size:   256)\n    Iter  8341\t      0.05027008 (Batch Size:   256)\n    Iter  8342\t      0.05439674 (Batch Size:   256)\n    Iter  8343\t      0.05436348 (Batch Size:   256)\n    Iter  8344\t      0.05406131 (Batch Size:   256)\n    Iter  8345\t      0.05654384 (Batch Size:   256)\n    Iter  8346\t      0.05199219 (Batch Size:   256)\n    Iter  8347\t      0.05105602 (Batch Size:   256)\n    Iter  8348\t      0.05113476 (Batch Size:   256)\n    Iter  8349\t      0.05095962 (Batch Size:   256)\n    Iter  8350\t      0.04993542 (Batch Size:   256)\n    Iter  8351\t      0.05363211 (Batch Size:   256)\n    Iter  8352\t      0.05059084 (Batch Size:   256)\n    Iter  8353\t      0.05494721 (Batch Size:   256)\n    Iter  8354\t      0.05435274 (Batch Size:   256)\n    Iter  8355\t      0.05254431 (Batch Size:   256)\n    Iter  8356\t      0.05349816 (Batch Size:   256)\n    Iter  8357\t      0.05257082 (Batch Size:   256)\n    Iter  8358\t      0.05340623 (Batch Size:   256)\n    Iter  8359\t      0.05949252 (Batch Size:   256)\n    Iter  8360\t      0.05757286 (Batch Size:   256)\n    Iter  8361\t      0.06085035 (Batch Size:   256)\n    Iter  8362\t      0.05889943 (Batch Size:   256)\n    Iter  8363\t      0.06331409 (Batch Size:   256)\n    Iter  8364\t      0.08400106 (Batch Size:   256)\n    Iter  8365\t      0.09558470 (Batch Size:   256)\n    Iter  8366\t      0.07886660 (Batch Size:   256)\n    Iter  8367\t      0.05467513 (Batch Size:   256)\n    Iter  8368\t      0.05190365 (Batch Size:   256)\n    Iter  8369\t      0.05147115 (Batch Size:   256)\n    Iter  8370\t      0.05694916 (Batch Size:   256)\n    Iter  8371\t      0.05402541 (Batch Size:   256)\n    Iter  8372\t      0.05318616 (Batch Size:   256)\n    Iter  8373\t      0.05068000 (Batch Size:   256)\n    Iter  8374\t      0.05317648 (Batch Size:   256)\n    Iter  8375\t      0.04991307 (Batch Size:   256)\n    Iter  8376\t      0.06465408 (Batch Size:   256)\n    Iter  8377\t      0.05597556 (Batch Size:   256)\n    Iter  8378\t      0.05930468 (Batch Size:   256)\n    Iter  8379\t      0.05736318 (Batch Size:   256)\n    Iter  8380\t      0.05388071 (Batch Size:   256)\n    Iter  8381\t      0.05216191 (Batch Size:   256)\n    Iter  8382\t      0.05120137 (Batch Size:   256)\n    Iter  8383\t      0.05125823 (Batch Size:   256)\n    Iter  8384\t      0.05230202 (Batch Size:   256)\n    Iter  8385\t      0.05119808 (Batch Size:   256)\n    Iter  8386\t      0.05037326 (Batch Size:   256)\n    Iter  8387\t      0.04792602 (Batch Size:   256)\n    Iter  8388\t      0.05063332 (Batch Size:   256)\n    Iter  8389\t      0.05243854 (Batch Size:   256)\n    Iter  8390\t      0.05680948 (Batch Size:   256)\n    Iter  8391\t      0.05289669 (Batch Size:   256)\n    Iter  8392\t      0.04972674 (Batch Size:   256)\n    Iter  8393\t      0.04956065 (Batch Size:   256)\n    Iter  8394\t      0.05355277 (Batch Size:   256)\n    Iter  8395\t      0.05108138 (Batch Size:   256)\n    Iter  8396\t      0.05385680 (Batch Size:   256)\n    Iter  8397\t      0.05068151 (Batch Size:   256)\n    Iter  8398\t      0.04855890 (Batch Size:   256)\n    Iter  8399\t      0.05343598 (Batch Size:   256)\n    Iter  8400\t      0.05914368 (Batch Size:   256)\n    Iter  8401\t      0.05944941 (Batch Size:   256)\n    Iter  8402\t      0.06056284 (Batch Size:   256)\n    Iter  8403\t      0.05854963 (Batch Size:   256)\n    Iter  8404\t      0.05046509 (Batch Size:   256)\n    Iter  8405\t      0.04806562 (Batch Size:   256)\n    Iter  8406\t      0.04884812 (Batch Size:   256)\n    Iter  8407\t      0.05094660 (Batch Size:   256)\n    Iter  8408\t      0.05119335 (Batch Size:   256)\n    Iter  8409\t      0.04996715 (Batch Size:   256)\n    Iter  8410\t      0.05204756 (Batch Size:   256)\n    Iter  8411\t      0.04784899 (Batch Size:   256)\n    Iter  8412\t      0.05167410 (Batch Size:   256)\n    Iter  8413\t      0.05115315 (Batch Size:   256)\n    Iter  8414\t      0.05552022 (Batch Size:   256)\n    Iter  8415\t      0.05152110 (Batch Size:   256)\n    Iter  8416\t      0.05255380 (Batch Size:   256)\n    Iter  8417\t      0.05799943 (Batch Size:   256)\n    Iter  8418\t      0.05906975 (Batch Size:   256)\n    Iter  8419\t      0.06160936 (Batch Size:   256)\n    Iter  8420\t      0.05283578 (Batch Size:   256)\n    Iter  8421\t      0.05139455 (Batch Size:   256)\n    Iter  8422\t      0.04994456 (Batch Size:   256)\n    Iter  8423\t      0.05040736 (Batch Size:   256)\n    Iter  8424\t      0.05271584 (Batch Size:   256)\n    Iter  8425\t      0.05002589 (Batch Size:   256)\n    Iter  8426\t      0.05177961 (Batch Size:   256)\n    Iter  8427\t      0.04943721 (Batch Size:   256)\n    Iter  8428\t      0.05928033 (Batch Size:   256)\n    Iter  8429\t      0.06935147 (Batch Size:   256)\n    Iter  8430\t      0.05857353 (Batch Size:   256)\n    Iter  8431\t      0.05094804 (Batch Size:   256)\n    Iter  8432\t      0.04897457 (Batch Size:   256)\n    Iter  8433\t      0.06436568 (Batch Size:   256)\n    Iter  8434\t      0.05566059 (Batch Size:   256)\n    Iter  8435\t      0.05105707 (Batch Size:   256)\n    Iter  8436\t      0.05344739 (Batch Size:   256)\n    Iter  8437\t      0.04814410 (Batch Size:   256)\n    Iter  8438\t      0.04745103 (Batch Size:   256)\n    Iter  8439\t      0.04980395 (Batch Size:   256)\n    Iter  8440\t      0.05069456 (Batch Size:   256)\n    Iter  8441\t      0.04774598 (Batch Size:   256)\n    Iter  8442\t      0.04914171 (Batch Size:   256)\n    Iter  8443\t      0.04879537 (Batch Size:   256)\n    Iter  8444\t      0.04988402 (Batch Size:   256)\n    Iter  8445\t      0.05262185 (Batch Size:   256)\n    Iter  8446\t      0.05253873 (Batch Size:   256)\n    Iter  8447\t      0.04951713 (Batch Size:   256)\n    Iter  8448\t      0.05208918 (Batch Size:   256)\n    Iter  8449\t      0.05022810 (Batch Size:   256)\n    Iter  8450\t      0.04898373 (Batch Size:   256)\n    Iter  8451\t      0.05103250 (Batch Size:   256)\n    Iter  8452\t      0.05097359 (Batch Size:   256)\n    Iter  8453\t      0.04800565 (Batch Size:   256)\n    Iter  8454\t      0.04998205 (Batch Size:   256)\n    Iter  8455\t      0.04906203 (Batch Size:   256)\n    Iter  8456\t      0.05015221 (Batch Size:   256)\n    Iter  8457\t      0.06301232 (Batch Size:   256)\n    Iter  8458\t      0.04986326 (Batch Size:   256)\n    Iter  8459\t      0.05425466 (Batch Size:   256)\n    Iter  8460\t      0.06025577 (Batch Size:   256)\n    Iter  8461\t      0.05352051 (Batch Size:   256)\n    Iter  8462\t      0.05514474 (Batch Size:   256)\n    Iter  8463\t      0.04965068 (Batch Size:   256)\n    Iter  8464\t      0.05521503 (Batch Size:   256)\n    Iter  8465\t      0.05652643 (Batch Size:   256)\n    Iter  8466\t      0.05638714 (Batch Size:   256)\n    Iter  8467\t      0.05805830 (Batch Size:   256)\n    Iter  8468\t      0.05960046 (Batch Size:   256)\n    Iter  8469\t      0.05472531 (Batch Size:   256)\n    Iter  8470\t      0.05364943 (Batch Size:   256)\n    Iter  8471\t      0.05379170 (Batch Size:   256)\n    Iter  8472\t      0.05329666 (Batch Size:   256)\n    Iter  8473\t      0.05241719 (Batch Size:   256)\n    Iter  8474\t      0.05016256 (Batch Size:   256)\n    Iter  8475\t      0.05111147 (Batch Size:   256)\n    Iter  8476\t      0.05544079 (Batch Size:   256)\n    Iter  8477\t      0.05789182 (Batch Size:   256)\n    Iter  8478\t      0.06326782 (Batch Size:   256)\n    Iter  8479\t      0.05590916 (Batch Size:   256)\n    Iter  8480\t      0.05192000 (Batch Size:   256)\n    Iter  8481\t      0.05064257 (Batch Size:   256)\n    Iter  8482\t      0.04994784 (Batch Size:   256)\n    Iter  8483\t      0.05068881 (Batch Size:   256)\n    Iter  8484\t      0.05765488 (Batch Size:   256)\n    Iter  8485\t      0.05649969 (Batch Size:   256)\n    Iter  8486\t      0.05192560 (Batch Size:   256)\n    Iter  8487\t      0.04721059 (Batch Size:   256)\n    Iter  8488\t      0.04919902 (Batch Size:   256)\n    Iter  8489\t      0.05516962 (Batch Size:   256)\n    Iter  8490\t      0.05061394 (Batch Size:   256)\n    Iter  8491\t      0.04979924 (Batch Size:   256)\n    Iter  8492\t      0.05009895 (Batch Size:   256)\n    Iter  8493\t      0.04871776 (Batch Size:   256)\n    Iter  8494\t      0.04898232 (Batch Size:   256)\n    Iter  8495\t      0.05143567 (Batch Size:   256)\n    Iter  8496\t      0.05210010 (Batch Size:   256)\n    Iter  8497\t      0.05633546 (Batch Size:   256)\n    Iter  8498\t      0.05884744 (Batch Size:   256)\n    Iter  8499\t      0.05607700 (Batch Size:   256)\n    Iter  8500\t      0.06297159 (Batch Size:   256)\n    Iter  8501\t      0.05227860 (Batch Size:   256)\n    Iter  8502\t      0.05095539 (Batch Size:   256)\n    Iter  8503\t      0.05160062 (Batch Size:   256)\n    Iter  8504\t      0.05092851 (Batch Size:   256)\n    Iter  8505\t      0.04888610 (Batch Size:   256)\n    Iter  8506\t      0.05255257 (Batch Size:   256)\n    Iter  8507\t      0.05517998 (Batch Size:   256)\n    Iter  8508\t      0.05095668 (Batch Size:   256)\n    Iter  8509\t      0.05390830 (Batch Size:   256)\n    Iter  8510\t      0.05043461 (Batch Size:   256)\n    Iter  8511\t      0.04891268 (Batch Size:   256)\n    Iter  8512\t      0.04930851 (Batch Size:   256)\n    Iter  8513\t      0.04876366 (Batch Size:   256)\n    Iter  8514\t      0.05209979 (Batch Size:   256)\n    Iter  8515\t      0.05392516 (Batch Size:   256)\n    Iter  8516\t      0.05066526 (Batch Size:   256)\n    Iter  8517\t      0.05603190 (Batch Size:   256)\n    Iter  8518\t      0.05738124 (Batch Size:   256)\n    Iter  8519\t      0.06047167 (Batch Size:   256)\n    Iter  8520\t      0.05738993 (Batch Size:   256)\n    Iter  8521\t      0.05606717 (Batch Size:   256)\n    Iter  8522\t      0.05912578 (Batch Size:   256)\n    Iter  8523\t      0.04970694 (Batch Size:   256)\n    Iter  8524\t      0.05688364 (Batch Size:   256)\n    Iter  8525\t      0.04965303 (Batch Size:   256)\n    Iter  8526\t      0.04670204 (Batch Size:   256)\n    Iter  8527\t      0.04669775 (Batch Size:   256)\n    Iter  8528\t      0.04876967 (Batch Size:   256)\n    Iter  8529\t      0.05443821 (Batch Size:   256)\n    Iter  8530\t      0.05841285 (Batch Size:   256)\n    Iter  8531\t      0.05614372 (Batch Size:   256)\n    Iter  8532\t      0.05328300 (Batch Size:   256)\n    Iter  8533\t      0.05419402 (Batch Size:   256)\n    Iter  8534\t      0.04693309 (Batch Size:   256)\n    Iter  8535\t      0.05140315 (Batch Size:   256)\n    Iter  8536\t      0.05318732 (Batch Size:   256)\n    Iter  8537\t      0.04826169 (Batch Size:   256)\n    Iter  8538\t      0.04898222 (Batch Size:   256)\n    Iter  8539\t      0.04568034 (Batch Size:   256)\n    Iter  8540\t      0.04962697 (Batch Size:   256)\n    Iter  8541\t      0.05040769 (Batch Size:   256)\n    Iter  8542\t      0.05098735 (Batch Size:   256)\n    Iter  8543\t      0.04789386 (Batch Size:   256)\n    Iter  8544\t      0.04456193 (Batch Size:   256)\n    Iter  8545\t      0.04957797 (Batch Size:   256)\n    Iter  8546\t      0.04648214 (Batch Size:   256)\n    Iter  8547\t      0.04847841 (Batch Size:   256)\n    Iter  8548\t      0.05153477 (Batch Size:   256)\n    Iter  8549\t      0.04783049 (Batch Size:   256)\n    Iter  8550\t      0.04998954 (Batch Size:   256)\n    Iter  8551\t      0.04883569 (Batch Size:   256)\n    Iter  8552\t      0.04900863 (Batch Size:   256)\n    Iter  8553\t      0.04943778 (Batch Size:   256)\n    Iter  8554\t      0.04844544 (Batch Size:   256)\n    Iter  8555\t      0.04971608 (Batch Size:   256)\n    Iter  8556\t      0.05077871 (Batch Size:   256)\n    Iter  8557\t      0.04871747 (Batch Size:   256)\n    Iter  8558\t      0.04909266 (Batch Size:   256)\n    Iter  8559\t      0.04817903 (Batch Size:   256)\n    Iter  8560\t      0.04884841 (Batch Size:   256)\n    Iter  8561\t      0.06143503 (Batch Size:   256)\n    Iter  8562\t      0.09456911 (Batch Size:   256)\n    Iter  8563\t      0.08296245 (Batch Size:   256)\n    Iter  8564\t      0.05948389 (Batch Size:   256)\n    Iter  8565\t      0.05151364 (Batch Size:   256)\n    Iter  8566\t      0.05348069 (Batch Size:   256)\n    Iter  8567\t      0.06187804 (Batch Size:   256)\n    Iter  8568\t      0.05370000 (Batch Size:   256)\n    Iter  8569\t      0.06122670 (Batch Size:   256)\n    Iter  8570\t      0.05338722 (Batch Size:   256)\n    Iter  8571\t      0.05124377 (Batch Size:   256)\n    Iter  8572\t      0.05940142 (Batch Size:   256)\n    Iter  8573\t      0.06748988 (Batch Size:   256)\n    Iter  8574\t      0.05453651 (Batch Size:   256)\n    Iter  8575\t      0.06354017 (Batch Size:   256)\n    Iter  8576\t      0.05790227 (Batch Size:   256)\n    Iter  8577\t      0.05469262 (Batch Size:   256)\n    Iter  8578\t      0.04976621 (Batch Size:   256)\n    Iter  8579\t      0.05225843 (Batch Size:   256)\n    Iter  8580\t      0.04669157 (Batch Size:   256)\n    Iter  8581\t      0.04802778 (Batch Size:   256)\n    Iter  8582\t      0.04684013 (Batch Size:   256)\n    Iter  8583\t      0.04739015 (Batch Size:   256)\n    Iter  8584\t      0.05403767 (Batch Size:   256)\n    Iter  8585\t      0.05606777 (Batch Size:   256)\n    Iter  8586\t      0.06280262 (Batch Size:   256)\n    Iter  8587\t      0.05084047 (Batch Size:   256)\n    Iter  8588\t      0.05253750 (Batch Size:   256)\n    Iter  8589\t      0.05279781 (Batch Size:   256)\n    Iter  8590\t      0.04648529 (Batch Size:   256)\n    Iter  8591\t      0.05063383 (Batch Size:   256)\n    Iter  8592\t      0.05726785 (Batch Size:   256)\n    Iter  8593\t      0.04893226 (Batch Size:   256)\n    Iter  8594\t      0.04832738 (Batch Size:   256)\n    Iter  8595\t      0.05006022 (Batch Size:   256)\n    Iter  8596\t      0.04778703 (Batch Size:   256)\n    Iter  8597\t      0.04856067 (Batch Size:   256)\n    Iter  8598\t      0.04763819 (Batch Size:   256)\n    Iter  8599\t      0.04358209 (Batch Size:   256)\n    Iter  8600\t      0.04980572 (Batch Size:   256)\n    Iter  8601\t      0.04779313 (Batch Size:   256)\n    Iter  8602\t      0.04853493 (Batch Size:   256)\n    Iter  8603\t      0.05107550 (Batch Size:   256)\n    Iter  8604\t      0.05164648 (Batch Size:   256)\n    Iter  8605\t      0.04752634 (Batch Size:   256)\n    Iter  8606\t      0.04674065 (Batch Size:   256)\n    Iter  8607\t      0.04789260 (Batch Size:   256)\n    Iter  8608\t      0.05088062 (Batch Size:   256)\n    Iter  8609\t      0.05173820 (Batch Size:   256)\n    Iter  8610\t      0.05308737 (Batch Size:   256)\n    Iter  8611\t      0.05803023 (Batch Size:   256)\n    Iter  8612\t      0.05393899 (Batch Size:   256)\n    Iter  8613\t      0.05442419 (Batch Size:   256)\n    Iter  8614\t      0.04955100 (Batch Size:   256)\n    Iter  8615\t      0.05538918 (Batch Size:   256)\n    Iter  8616\t      0.05445428 (Batch Size:   256)\n    Iter  8617\t      0.04954396 (Batch Size:   256)\n    Iter  8618\t      0.04705209 (Batch Size:   256)\n    Iter  8619\t      0.04674654 (Batch Size:   256)\n    Iter  8620\t      0.04931802 (Batch Size:   256)\n    Iter  8621\t      0.04963440 (Batch Size:   256)\n    Iter  8622\t      0.04827266 (Batch Size:   256)\n    Iter  8623\t      0.05997731 (Batch Size:   256)\n    Iter  8624\t      0.06824487 (Batch Size:   256)\n    Iter  8625\t      0.05431625 (Batch Size:   256)\n    Iter  8626\t      0.05233404 (Batch Size:   256)\n    Iter  8627\t      0.04674231 (Batch Size:   256)\n    Iter  8628\t      0.05463290 (Batch Size:   256)\n    Iter  8629\t      0.05721633 (Batch Size:   256)\n    Iter  8630\t      0.04829271 (Batch Size:   256)\n    Iter  8631\t      0.04611048 (Batch Size:   256)\n    Iter  8632\t      0.04423934 (Batch Size:   256)\n    Iter  8633\t      0.04826913 (Batch Size:   256)\n    Iter  8634\t      0.05009767 (Batch Size:   256)\n    Iter  8635\t      0.04634121 (Batch Size:   256)\n    Iter  8636\t      0.04542142 (Batch Size:   256)\n    Iter  8637\t      0.04794587 (Batch Size:   256)\n    Iter  8638\t      0.05118118 (Batch Size:   256)\n    Iter  8639\t      0.04744261 (Batch Size:   256)\n    Iter  8640\t      0.05098730 (Batch Size:   256)\n    Iter  8641\t      0.05080243 (Batch Size:   256)\n    Iter  8642\t      0.04855760 (Batch Size:   256)\n    Iter  8643\t      0.04823845 (Batch Size:   256)\n    Iter  8644\t      0.04731617 (Batch Size:   256)\n    Iter  8645\t      0.04798704 (Batch Size:   256)\n    Iter  8646\t      0.04817616 (Batch Size:   256)\n    Iter  8647\t      0.04654404 (Batch Size:   256)\n    Iter  8648\t      0.05237055 (Batch Size:   256)\n    Iter  8649\t      0.04553423 (Batch Size:   256)\n    Iter  8650\t      0.04509622 (Batch Size:   256)\n    Iter  8651\t      0.05524020 (Batch Size:   256)\n    Iter  8652\t      0.04576022 (Batch Size:   256)\n    Iter  8653\t      0.05565527 (Batch Size:   256)\n    Iter  8654\t      0.05248885 (Batch Size:   256)\n    Iter  8655\t      0.04481537 (Batch Size:   256)\n    Iter  8656\t      0.05044045 (Batch Size:   256)\n    Iter  8657\t      0.04975400 (Batch Size:   256)\n    Iter  8658\t      0.04771651 (Batch Size:   256)\n    Iter  8659\t      0.05074803 (Batch Size:   256)\n    Iter  8660\t      0.04941976 (Batch Size:   256)\n    Iter  8661\t      0.04563495 (Batch Size:   256)\n    Iter  8662\t      0.06709038 (Batch Size:   256)\n    Iter  8663\t      0.04757601 (Batch Size:   256)\n    Iter  8664\t      0.04438306 (Batch Size:   256)\n    Iter  8665\t      0.04784138 (Batch Size:   256)\n    Iter  8666\t      0.05032020 (Batch Size:   256)\n    Iter  8667\t      0.04769054 (Batch Size:   256)\n    Iter  8668\t      0.04664913 (Batch Size:   256)\n    Iter  8669\t      0.04766729 (Batch Size:   256)\n    Iter  8670\t      0.04425272 (Batch Size:   256)\n    Iter  8671\t      0.04842035 (Batch Size:   256)\n    Iter  8672\t      0.04614138 (Batch Size:   256)\n    Iter  8673\t      0.04962870 (Batch Size:   256)\n    Iter  8674\t      0.04759036 (Batch Size:   256)\n    Iter  8675\t      0.04501803 (Batch Size:   256)\n    Iter  8676\t      0.04741094 (Batch Size:   256)\n    Iter  8677\t      0.04866829 (Batch Size:   256)\n    Iter  8678\t      0.04855653 (Batch Size:   256)\n    Iter  8679\t      0.04819979 (Batch Size:   256)\n    Iter  8680\t      0.04912845 (Batch Size:   256)\n    Iter  8681\t      0.04397454 (Batch Size:   256)\n    Iter  8682\t      0.04748409 (Batch Size:   256)\n    Iter  8683\t      0.04828664 (Batch Size:   256)\n    Iter  8684\t      0.04425704 (Batch Size:   256)\n    Iter  8685\t      0.04445844 (Batch Size:   256)\n    Iter  8686\t      0.04882622 (Batch Size:   256)\n    Iter  8687\t      0.04917522 (Batch Size:   256)\n    Iter  8688\t      0.04718443 (Batch Size:   256)\n    Iter  8689\t      0.04677628 (Batch Size:   256)\n    Iter  8690\t      0.04794938 (Batch Size:   256)\n    Iter  8691\t      0.05925499 (Batch Size:   256)\n    Iter  8692\t      0.05695872 (Batch Size:   256)\n    Iter  8693\t      0.04993688 (Batch Size:   256)\n    Iter  8694\t      0.04769434 (Batch Size:   256)\n    Iter  8695\t      0.04643523 (Batch Size:   256)\n    Iter  8696\t      0.04694775 (Batch Size:   256)\n    Iter  8697\t      0.05755506 (Batch Size:   256)\n    Iter  8698\t      0.05558734 (Batch Size:   256)\n    Iter  8699\t      0.04971581 (Batch Size:   256)\n    Iter  8700\t      0.04773069 (Batch Size:   256)\n    Iter  8701\t      0.04721217 (Batch Size:   256)\n    Iter  8702\t      0.04558609 (Batch Size:   256)\n    Iter  8703\t      0.04486718 (Batch Size:   256)\n    Iter  8704\t      0.04814392 (Batch Size:   256)\n    Iter  8705\t      0.05191989 (Batch Size:   256)\n    Iter  8706\t      0.05907979 (Batch Size:   256)\n    Iter  8707\t      0.04854282 (Batch Size:   256)\n    Iter  8708\t      0.04749317 (Batch Size:   256)\n    Iter  8709\t      0.04898975 (Batch Size:   256)\n    Iter  8710\t      0.04693478 (Batch Size:   256)\n    Iter  8711\t      0.05096517 (Batch Size:   256)\n    Iter  8712\t      0.04717531 (Batch Size:   256)\n    Iter  8713\t      0.04910025 (Batch Size:   256)\n    Iter  8714\t      0.04809353 (Batch Size:   256)\n    Iter  8715\t      0.05762969 (Batch Size:   256)\n    Iter  8716\t      0.05364762 (Batch Size:   256)\n    Iter  8717\t      0.06172591 (Batch Size:   256)\n    Iter  8718\t      0.05815737 (Batch Size:   256)\n    Iter  8719\t      0.04969485 (Batch Size:   256)\n    Iter  8720\t      0.05059229 (Batch Size:   256)\n    Iter  8721\t      0.04726427 (Batch Size:   256)\n    Iter  8722\t      0.04590857 (Batch Size:   256)\n    Iter  8723\t      0.04420418 (Batch Size:   256)\n    Iter  8724\t      0.04594847 (Batch Size:   256)\n    Iter  8725\t      0.04719575 (Batch Size:   256)\n    Iter  8726\t      0.04339875 (Batch Size:   256)\n    Iter  8727\t      0.04600427 (Batch Size:   256)\n    Iter  8728\t      0.04483310 (Batch Size:   256)\n    Iter  8729\t      0.04760221 (Batch Size:   256)\n    Iter  8730\t      0.04714859 (Batch Size:   256)\n    Iter  8731\t      0.04738030 (Batch Size:   256)\n    Iter  8732\t      0.04610514 (Batch Size:   256)\n    Iter  8733\t      0.04762516 (Batch Size:   256)\n    Iter  8734\t      0.04768611 (Batch Size:   256)\n    Iter  8735\t      0.04958016 (Batch Size:   256)\n    Iter  8736\t      0.04400421 (Batch Size:   256)\n    Iter  8737\t      0.04647082 (Batch Size:   256)\n    Iter  8738\t      0.05400149 (Batch Size:   256)\n    Iter  8739\t      0.05711659 (Batch Size:   256)\n    Iter  8740\t      0.05141176 (Batch Size:   256)\n    Iter  8741\t      0.04745913 (Batch Size:   256)\n    Iter  8742\t      0.04877300 (Batch Size:   256)\n    Iter  8743\t      0.04924475 (Batch Size:   256)\n    Iter  8744\t      0.04653964 (Batch Size:   256)\n    Iter  8745\t      0.04360808 (Batch Size:   256)\n    Iter  8746\t      0.04731890 (Batch Size:   256)\n    Iter  8747\t      0.04412844 (Batch Size:   256)\n    Iter  8748\t      0.04364349 (Batch Size:   256)\n    Iter  8749\t      0.04776329 (Batch Size:   256)\n    Iter  8750\t      0.04689953 (Batch Size:   256)\n    Iter  8751\t      0.04407120 (Batch Size:   256)\n    Iter  8752\t      0.04345982 (Batch Size:   256)\n    Iter  8753\t      0.04745245 (Batch Size:   256)\n    Iter  8754\t      0.04698469 (Batch Size:   256)\n    Iter  8755\t      0.04336019 (Batch Size:   256)\n    Iter  8756\t      0.05115300 (Batch Size:   256)\n    Iter  8757\t      0.05684720 (Batch Size:   256)\n    Iter  8758\t      0.04875302 (Batch Size:   256)\n    Iter  8759\t      0.04695572 (Batch Size:   256)\n    Iter  8760\t      0.04921067 (Batch Size:   256)\n    Iter  8761\t      0.04811913 (Batch Size:   256)\n    Iter  8762\t      0.04663666 (Batch Size:   256)\n    Iter  8763\t      0.04666664 (Batch Size:   256)\n    Iter  8764\t      0.04841993 (Batch Size:   256)\n    Iter  8765\t      0.05931432 (Batch Size:   256)\n    Iter  8766\t      0.06466690 (Batch Size:   256)\n    Iter  8767\t      0.06446140 (Batch Size:   256)\n    Iter  8768\t      0.06569218 (Batch Size:   256)\n    Iter  8769\t      0.05992321 (Batch Size:   256)\n    Iter  8770\t      0.05310024 (Batch Size:   256)\n    Iter  8771\t      0.04763558 (Batch Size:   256)\n    Iter  8772\t      0.04994535 (Batch Size:   256)\n    Iter  8773\t      0.04686778 (Batch Size:   256)\n    Iter  8774\t      0.04639983 (Batch Size:   256)\n    Iter  8775\t      0.04337287 (Batch Size:   256)\n    Iter  8776\t      0.04404546 (Batch Size:   256)\n    Iter  8777\t      0.04898857 (Batch Size:   256)\n    Iter  8778\t      0.04669860 (Batch Size:   256)\n    Iter  8779\t      0.04550280 (Batch Size:   256)\n    Iter  8780\t      0.04481313 (Batch Size:   256)\n    Iter  8781\t      0.04698549 (Batch Size:   256)\n    Iter  8782\t      0.04536361 (Batch Size:   256)\n    Iter  8783\t      0.05034805 (Batch Size:   256)\n    Iter  8784\t      0.04760399 (Batch Size:   256)\n    Iter  8785\t      0.04839715 (Batch Size:   256)\n    Iter  8786\t      0.04937589 (Batch Size:   256)\n    Iter  8787\t      0.04978318 (Batch Size:   256)\n    Iter  8788\t      0.04494479 (Batch Size:   256)\n    Iter  8789\t      0.04403500 (Batch Size:   256)\n    Iter  8790\t      0.04410239 (Batch Size:   256)\n    Iter  8791\t      0.05158156 (Batch Size:   256)\n    Iter  8792\t      0.04913011 (Batch Size:   256)\n    Iter  8793\t      0.04609915 (Batch Size:   256)\n    Iter  8794\t      0.04335363 (Batch Size:   256)\n    Iter  8795\t      0.04426131 (Batch Size:   256)\n    Iter  8796\t      0.04706903 (Batch Size:   256)\n    Iter  8797\t      0.04705276 (Batch Size:   256)\n    Iter  8798\t      0.05115888 (Batch Size:   256)\n    Iter  8799\t      0.05657887 (Batch Size:   256)\n    Iter  8800\t      0.05057392 (Batch Size:   256)\n    Iter  8801\t      0.04498089 (Batch Size:   256)\n    Iter  8802\t      0.04745148 (Batch Size:   256)\n    Iter  8803\t      0.04581534 (Batch Size:   256)\n    Iter  8804\t      0.05108151 (Batch Size:   256)\n    Iter  8805\t      0.04724227 (Batch Size:   256)\n    Iter  8806\t      0.04558525 (Batch Size:   256)\n    Iter  8807\t      0.04680105 (Batch Size:   256)\n    Iter  8808\t      0.05232623 (Batch Size:   256)\n    Iter  8809\t      0.04684269 (Batch Size:   256)\n    Iter  8810\t      0.04689265 (Batch Size:   256)\n    Iter  8811\t      0.04393645 (Batch Size:   256)\n    Iter  8812\t      0.06180846 (Batch Size:   256)\n    Iter  8813\t      0.07354136 (Batch Size:   256)\n    Iter  8814\t      0.06040436 (Batch Size:   256)\n    Iter  8815\t      0.06017528 (Batch Size:   256)\n    Iter  8816\t      0.04621770 (Batch Size:   256)\n    Iter  8817\t      0.04403470 (Batch Size:   256)\n    Iter  8818\t      0.06268879 (Batch Size:   256)\n    Iter  8819\t      0.05106779 (Batch Size:   256)\n    Iter  8820\t      0.04855689 (Batch Size:   256)\n    Iter  8821\t      0.04330399 (Batch Size:   256)\n    Iter  8822\t      0.04505404 (Batch Size:   256)\n    Iter  8823\t      0.05024373 (Batch Size:   256)\n    Iter  8824\t      0.04756506 (Batch Size:   256)\n    Iter  8825\t      0.04970638 (Batch Size:   256)\n    Iter  8826\t      0.04450311 (Batch Size:   256)\n    Iter  8827\t      0.04519795 (Batch Size:   256)\n    Iter  8828\t      0.04294171 (Batch Size:   256)\n    Iter  8829\t      0.04538823 (Batch Size:   256)\n    Iter  8830\t      0.04789593 (Batch Size:   256)\n    Iter  8831\t      0.04711381 (Batch Size:   256)\n    Iter  8832\t      0.04723360 (Batch Size:   256)\n    Iter  8833\t      0.04658745 (Batch Size:   256)\n    Iter  8834\t      0.04681251 (Batch Size:   256)\n    Iter  8835\t      0.04510522 (Batch Size:   256)\n    Iter  8836\t      0.04258073 (Batch Size:   256)\n    Iter  8837\t      0.04727295 (Batch Size:   256)\n    Iter  8838\t      0.04831808 (Batch Size:   256)\n    Iter  8839\t      0.05311833 (Batch Size:   256)\n    Iter  8840\t      0.04487213 (Batch Size:   256)\n    Iter  8841\t      0.04785460 (Batch Size:   256)\n    Iter  8842\t      0.04625870 (Batch Size:   256)\n    Iter  8843\t      0.04364229 (Batch Size:   256)\n    Iter  8844\t      0.04872695 (Batch Size:   256)\n    Iter  8845\t      0.04287922 (Batch Size:   256)\n    Iter  8846\t      0.04380906 (Batch Size:   256)\n    Iter  8847\t      0.04366292 (Batch Size:   256)\n    Iter  8848\t      0.04262616 (Batch Size:   256)\n    Iter  8849\t      0.04289622 (Batch Size:   256)\n    Iter  8850\t      0.04779183 (Batch Size:   256)\n    Iter  8851\t      0.04692103 (Batch Size:   256)\n    Iter  8852\t      0.04961993 (Batch Size:   256)\n    Iter  8853\t      0.05455223 (Batch Size:   256)\n    Iter  8854\t      0.05192023 (Batch Size:   256)\n    Iter  8855\t      0.04400007 (Batch Size:   256)\n    Iter  8856\t      0.04673098 (Batch Size:   256)\n    Iter  8857\t      0.04690811 (Batch Size:   256)\n    Iter  8858\t      0.04501838 (Batch Size:   256)\n    Iter  8859\t      0.04133665 (Batch Size:   256)\n    Iter  8860\t      0.04922396 (Batch Size:   256)\n    Iter  8861\t      0.05931039 (Batch Size:   256)\n    Iter  8862\t      0.06136602 (Batch Size:   256)\n    Iter  8863\t      0.05523664 (Batch Size:   256)\n    Iter  8864\t      0.05083659 (Batch Size:   256)\n    Iter  8865\t      0.05889531 (Batch Size:   256)\n    Iter  8866\t      0.05278577 (Batch Size:   256)\n    Iter  8867\t      0.04868018 (Batch Size:   256)\n    Iter  8868\t      0.04699079 (Batch Size:   256)\n    Iter  8869\t      0.04543839 (Batch Size:   256)\n    Iter  8870\t      0.04946839 (Batch Size:   256)\n    Iter  8871\t      0.04410135 (Batch Size:   256)\n    Iter  8872\t      0.04647502 (Batch Size:   256)\n    Iter  8873\t      0.04515514 (Batch Size:   256)\n    Iter  8874\t      0.04613561 (Batch Size:   256)\n    Iter  8875\t      0.05330111 (Batch Size:   256)\n    Iter  8876\t      0.04559529 (Batch Size:   256)\n    Iter  8877\t      0.04746754 (Batch Size:   256)\n    Iter  8878\t      0.04640050 (Batch Size:   256)\n    Iter  8879\t      0.04756024 (Batch Size:   256)\n    Iter  8880\t      0.04521435 (Batch Size:   256)\n    Iter  8881\t      0.04562227 (Batch Size:   256)\n    Iter  8882\t      0.04733544 (Batch Size:   256)\n    Iter  8883\t      0.04155772 (Batch Size:   256)\n    Iter  8884\t      0.04611803 (Batch Size:   256)\n    Iter  8885\t      0.04560153 (Batch Size:   256)\n    Iter  8886\t      0.04402203 (Batch Size:   256)\n    Iter  8887\t      0.04210819 (Batch Size:   256)\n    Iter  8888\t      0.04594583 (Batch Size:   256)\n    Iter  8889\t      0.04248378 (Batch Size:   256)\n    Iter  8890\t      0.04517677 (Batch Size:   256)\n    Iter  8891\t      0.04626510 (Batch Size:   256)\n    Iter  8892\t      0.04874816 (Batch Size:   256)\n    Iter  8893\t      0.05183268 (Batch Size:   256)\n    Iter  8894\t      0.04542369 (Batch Size:   256)\n    Iter  8895\t      0.04508757 (Batch Size:   256)\n    Iter  8896\t      0.04831379 (Batch Size:   256)\n    Iter  8897\t      0.04801971 (Batch Size:   256)\n    Iter  8898\t      0.04671255 (Batch Size:   256)\n    Iter  8899\t      0.04659633 (Batch Size:   256)\n    Iter  8900\t      0.04576013 (Batch Size:   256)\n    Iter  8901\t      0.04776628 (Batch Size:   256)\n    Iter  8902\t      0.04941649 (Batch Size:   256)\n    Iter  8903\t      0.05621768 (Batch Size:   256)\n    Iter  8904\t      0.05153333 (Batch Size:   256)\n    Iter  8905\t      0.04696021 (Batch Size:   256)\n    Iter  8906\t      0.05599846 (Batch Size:   256)\n    Iter  8907\t      0.05116547 (Batch Size:   256)\n    Iter  8908\t      0.04867664 (Batch Size:   256)\n    Iter  8909\t      0.04926154 (Batch Size:   256)\n    Iter  8910\t      0.05211547 (Batch Size:   256)\n    Iter  8911\t      0.04999018 (Batch Size:   256)\n    Iter  8912\t      0.04577099 (Batch Size:   256)\n    Iter  8913\t      0.04194064 (Batch Size:   256)\n    Iter  8914\t      0.04241312 (Batch Size:   256)\n    Iter  8915\t      0.04472719 (Batch Size:   256)\n    Iter  8916\t      0.04552486 (Batch Size:   256)\n    Iter  8917\t      0.04581703 (Batch Size:   256)\n    Iter  8918\t      0.04489063 (Batch Size:   256)\n    Iter  8919\t      0.05037593 (Batch Size:   256)\n    Iter  8920\t      0.05164406 (Batch Size:   256)\n    Iter  8921\t      0.04886580 (Batch Size:   256)\n    Iter  8922\t      0.04384190 (Batch Size:   256)\n    Iter  8923\t      0.04657749 (Batch Size:   256)\n    Iter  8924\t      0.04490051 (Batch Size:   256)\n    Iter  8925\t      0.04610717 (Batch Size:   256)\n    Iter  8926\t      0.04351914 (Batch Size:   256)\n    Iter  8927\t      0.04259968 (Batch Size:   256)\n    Iter  8928\t      0.04679639 (Batch Size:   256)\n    Iter  8929\t      0.04614494 (Batch Size:   256)\n    Iter  8930\t      0.04862774 (Batch Size:   256)\n    Iter  8931\t      0.05118250 (Batch Size:   256)\n    Iter  8932\t      0.05270008 (Batch Size:   256)\n    Iter  8933\t      0.04237193 (Batch Size:   256)\n    Iter  8934\t      0.04413197 (Batch Size:   256)\n    Iter  8935\t      0.04506940 (Batch Size:   256)\n    Iter  8936\t      0.04622735 (Batch Size:   256)\n    Iter  8937\t      0.04445862 (Batch Size:   256)\n    Iter  8938\t      0.04165444 (Batch Size:   256)\n    Iter  8939\t      0.04716585 (Batch Size:   256)\n    Iter  8940\t      0.04602813 (Batch Size:   256)\n    Iter  8941\t      0.04720717 (Batch Size:   256)\n    Iter  8942\t      0.04680193 (Batch Size:   256)\n    Iter  8943\t      0.04495126 (Batch Size:   256)\n    Iter  8944\t      0.04646327 (Batch Size:   256)\n    Iter  8945\t      0.04091730 (Batch Size:   256)\n    Iter  8946\t      0.04300763 (Batch Size:   256)\n    Iter  8947\t      0.04447888 (Batch Size:   256)\n    Iter  8948\t      0.04768705 (Batch Size:   256)\n    Iter  8949\t      0.04739771 (Batch Size:   256)\n    Iter  8950\t      0.05338415 (Batch Size:   256)\n    Iter  8951\t      0.05408865 (Batch Size:   256)\n    Iter  8952\t      0.04688009 (Batch Size:   256)\n    Iter  8953\t      0.04508779 (Batch Size:   256)\n    Iter  8954\t      0.04726232 (Batch Size:   256)\n    Iter  8955\t      0.04581988 (Batch Size:   256)\n    Iter  8956\t      0.04843106 (Batch Size:   256)\n    Iter  8957\t      0.04735723 (Batch Size:   256)\n    Iter  8958\t      0.04562618 (Batch Size:   256)\n    Iter  8959\t      0.04368921 (Batch Size:   256)\n    Iter  8960\t      0.04588182 (Batch Size:   256)\n    Iter  8961\t      0.05114249 (Batch Size:   256)\n    Iter  8962\t      0.04557174 (Batch Size:   256)\n    Iter  8963\t      0.04185372 (Batch Size:   256)\n    Iter  8964\t      0.04517314 (Batch Size:   256)\n    Iter  8965\t      0.04725914 (Batch Size:   256)\n    Iter  8966\t      0.04417837 (Batch Size:   256)\n    Iter  8967\t      0.04359034 (Batch Size:   256)\n    Iter  8968\t      0.04386614 (Batch Size:   256)\n    Iter  8969\t      0.04499361 (Batch Size:   256)\n    Iter  8970\t      0.05672215 (Batch Size:   256)\n    Iter  8971\t      0.04836606 (Batch Size:   256)\n    Iter  8972\t      0.04685766 (Batch Size:   256)\n    Iter  8973\t      0.04886559 (Batch Size:   256)\n    Iter  8974\t      0.04817210 (Batch Size:   256)\n    Iter  8975\t      0.05415158 (Batch Size:   256)\n    Iter  8976\t      0.05597687 (Batch Size:   256)\n    Iter  8977\t      0.04616818 (Batch Size:   256)\n    Iter  8978\t      0.04609231 (Batch Size:   256)\n    Iter  8979\t      0.04445619 (Batch Size:   256)\n    Iter  8980\t      0.06021489 (Batch Size:   256)\n    Iter  8981\t      0.06304485 (Batch Size:   256)\n    Iter  8982\t      0.05496130 (Batch Size:   256)\n    Iter  8983\t      0.07553598 (Batch Size:   256)\n    Iter  8984\t      0.06283396 (Batch Size:   256)\n    Iter  8985\t      0.06040648 (Batch Size:   256)\n    Iter  8986\t      0.05785492 (Batch Size:   256)\n    Iter  8987\t      0.05221125 (Batch Size:   256)\n    Iter  8988\t      0.05342578 (Batch Size:   256)\n    Iter  8989\t      0.04512908 (Batch Size:   256)\n    Iter  8990\t      0.04351839 (Batch Size:   256)\n    Iter  8991\t      0.04301812 (Batch Size:   256)\n    Iter  8992\t      0.04700155 (Batch Size:   256)\n    Iter  8993\t      0.04782673 (Batch Size:   256)\n    Iter  8994\t      0.04594092 (Batch Size:   256)\n    Iter  8995\t      0.04592534 (Batch Size:   256)\n    Iter  8996\t      0.04778672 (Batch Size:   256)\n    Iter  8997\t      0.04498819 (Batch Size:   256)\n    Iter  8998\t      0.04605036 (Batch Size:   256)\n    Iter  8999\t      0.04858301 (Batch Size:   256)\n    Iter  9000\t      0.04695787 (Batch Size:   256)\n    Iter  9001\t      0.04907557 (Batch Size:   256)\n    Iter  9002\t      0.04997799 (Batch Size:   256)\n    Iter  9003\t      0.06123122 (Batch Size:   256)\n    Iter  9004\t      0.04940160 (Batch Size:   256)\n    Iter  9005\t      0.04301226 (Batch Size:   256)\n    Iter  9006\t      0.04367782 (Batch Size:   256)\n    Iter  9007\t      0.04370352 (Batch Size:   256)\n    Iter  9008\t      0.04435965 (Batch Size:   256)\n    Iter  9009\t      0.04443340 (Batch Size:   256)\n    Iter  9010\t      0.04618132 (Batch Size:   256)\n    Iter  9011\t      0.04686919 (Batch Size:   256)\n    Iter  9012\t      0.04499435 (Batch Size:   256)\n    Iter  9013\t      0.04364769 (Batch Size:   256)\n    Iter  9014\t      0.05367032 (Batch Size:   256)\n    Iter  9015\t      0.04413807 (Batch Size:   256)\n    Iter  9016\t      0.04458645 (Batch Size:   256)\n    Iter  9017\t      0.04271161 (Batch Size:   256)\n    Iter  9018\t      0.04514583 (Batch Size:   256)\n    Iter  9019\t      0.04764767 (Batch Size:   256)\n    Iter  9020\t      0.04832586 (Batch Size:   256)\n    Iter  9021\t      0.04468840 (Batch Size:   256)\n    Iter  9022\t      0.04587440 (Batch Size:   256)\n    Iter  9023\t      0.04395202 (Batch Size:   256)\n    Iter  9024\t      0.04382755 (Batch Size:   256)\n    Iter  9025\t      0.04106838 (Batch Size:   256)\n    Iter  9026\t      0.04732358 (Batch Size:   256)\n    Iter  9027\t      0.05757809 (Batch Size:   256)\n    Iter  9028\t      0.05245115 (Batch Size:   256)\n    Iter  9029\t      0.04153641 (Batch Size:   256)\n    Iter  9030\t      0.04517602 (Batch Size:   256)\n    Iter  9031\t      0.04384404 (Batch Size:   256)\n    Iter  9032\t      0.04565405 (Batch Size:   256)\n    Iter  9033\t      0.05876810 (Batch Size:   256)\n    Iter  9034\t      0.05030276 (Batch Size:   256)\n    Iter  9035\t      0.04530598 (Batch Size:   256)\n    Iter  9036\t      0.05126276 (Batch Size:   256)\n    Iter  9037\t      0.04645669 (Batch Size:   256)\n    Iter  9038\t      0.04459137 (Batch Size:   256)\n    Iter  9039\t      0.04929485 (Batch Size:   256)\n    Iter  9040\t      0.05465461 (Batch Size:   256)\n    Iter  9041\t      0.07769699 (Batch Size:   256)\n    Iter  9042\t      0.06248054 (Batch Size:   256)\n    Iter  9043\t      0.04709512 (Batch Size:   256)\n    Iter  9044\t      0.04712689 (Batch Size:   256)\n    Iter  9045\t      0.04210432 (Batch Size:   256)\n    Iter  9046\t      0.04811090 (Batch Size:   256)\n    Iter  9047\t      0.04291883 (Batch Size:   256)\n    Iter  9048\t      0.04608261 (Batch Size:   256)\n    Iter  9049\t      0.04716079 (Batch Size:   256)\n    Iter  9050\t      0.04446814 (Batch Size:   256)\n    Iter  9051\t      0.04433097 (Batch Size:   256)\n    Iter  9052\t      0.04309627 (Batch Size:   256)\n    Iter  9053\t      0.04841434 (Batch Size:   256)\n    Iter  9054\t      0.04434655 (Batch Size:   256)\n    Iter  9055\t      0.04409271 (Batch Size:   256)\n    Iter  9056\t      0.04141223 (Batch Size:   256)\n    Iter  9057\t      0.04328175 (Batch Size:   256)\n    Iter  9058\t      0.04328165 (Batch Size:   256)\n    Iter  9059\t      0.04392074 (Batch Size:   256)\n    Iter  9060\t      0.04255916 (Batch Size:   256)\n    Iter  9061\t      0.04575828 (Batch Size:   256)\n    Iter  9062\t      0.04588764 (Batch Size:   256)\n    Iter  9063\t      0.04786645 (Batch Size:   256)\n    Iter  9064\t      0.04559575 (Batch Size:   256)\n    Iter  9065\t      0.05164331 (Batch Size:   256)\n    Iter  9066\t      0.04760587 (Batch Size:   256)\n    Iter  9067\t      0.04841346 (Batch Size:   256)\n    Iter  9068\t      0.04219061 (Batch Size:   256)\n    Iter  9069\t      0.04173807 (Batch Size:   256)\n    Iter  9070\t      0.04746137 (Batch Size:   256)\n    Iter  9071\t      0.04328349 (Batch Size:   256)\n    Iter  9072\t      0.04548003 (Batch Size:   256)\n    Iter  9073\t      0.04213441 (Batch Size:   256)\n    Iter  9074\t      0.04372946 (Batch Size:   256)\n    Iter  9075\t      0.04454276 (Batch Size:   256)\n    Iter  9076\t      0.04451827 (Batch Size:   256)\n    Iter  9077\t      0.04774093 (Batch Size:   256)\n    Iter  9078\t      0.05093292 (Batch Size:   256)\n    Iter  9079\t      0.04586323 (Batch Size:   256)\n    Iter  9080\t      0.04278446 (Batch Size:   256)\n    Iter  9081\t      0.04908151 (Batch Size:   256)\n    Iter  9082\t      0.04834173 (Batch Size:   256)\n    Iter  9083\t      0.04668670 (Batch Size:   256)\n    Iter  9084\t      0.04668311 (Batch Size:   256)\n    Iter  9085\t      0.04628534 (Batch Size:   256)\n    Iter  9086\t      0.05218556 (Batch Size:   256)\n    Iter  9087\t      0.04081560 (Batch Size:   256)\n    Iter  9088\t      0.04768029 (Batch Size:   256)\n    Iter  9089\t      0.04449160 (Batch Size:   256)\n    Iter  9090\t      0.04842059 (Batch Size:   256)\n    Iter  9091\t      0.04308420 (Batch Size:   256)\n    Iter  9092\t      0.04485404 (Batch Size:   256)\n    Iter  9093\t      0.04356438 (Batch Size:   256)\n    Iter  9094\t      0.04333716 (Batch Size:   256)\n    Iter  9095\t      0.04911243 (Batch Size:   256)\n    Iter  9096\t      0.04723089 (Batch Size:   256)\n    Iter  9097\t      0.04882802 (Batch Size:   256)\n    Iter  9098\t      0.04572390 (Batch Size:   256)\n    Iter  9099\t      0.04602263 (Batch Size:   256)\n    Iter  9100\t      0.04286476 (Batch Size:   256)\n    Iter  9101\t      0.04589812 (Batch Size:   256)\n    Iter  9102\t      0.04189498 (Batch Size:   256)\n    Iter  9103\t      0.04282870 (Batch Size:   256)\n    Iter  9104\t      0.04772334 (Batch Size:   256)\n    Iter  9105\t      0.04594872 (Batch Size:   256)\n    Iter  9106\t      0.04612128 (Batch Size:   256)\n    Iter  9107\t      0.04784806 (Batch Size:   256)\n    Iter  9108\t      0.04501110 (Batch Size:   256)\n    Iter  9109\t      0.04920091 (Batch Size:   256)\n    Iter  9110\t      0.04712466 (Batch Size:   256)\n    Iter  9111\t      0.04565487 (Batch Size:   256)\n    Iter  9112\t      0.04507572 (Batch Size:   256)\n    Iter  9113\t      0.04417368 (Batch Size:   256)\n    Iter  9114\t      0.04559829 (Batch Size:   256)\n    Iter  9115\t      0.04144761 (Batch Size:   256)\n    Iter  9116\t      0.04643148 (Batch Size:   256)\n    Iter  9117\t      0.04450920 (Batch Size:   256)\n    Iter  9118\t      0.04709200 (Batch Size:   256)\n    Iter  9119\t      0.04750354 (Batch Size:   256)\n    Iter  9120\t      0.05212130 (Batch Size:   256)\n    Iter  9121\t      0.06010725 (Batch Size:   256)\n    Iter  9122\t      0.04751122 (Batch Size:   256)\n    Iter  9123\t      0.04556761 (Batch Size:   256)\n    Iter  9124\t      0.04336202 (Batch Size:   256)\n    Iter  9125\t      0.04476561 (Batch Size:   256)\n    Iter  9126\t      0.04694327 (Batch Size:   256)\n    Iter  9127\t      0.04442691 (Batch Size:   256)\n    Iter  9128\t      0.04230942 (Batch Size:   256)\n    Iter  9129\t      0.04213667 (Batch Size:   256)\n    Iter  9130\t      0.04378495 (Batch Size:   256)\n    Iter  9131\t      0.04507848 (Batch Size:   256)\n    Iter  9132\t      0.04908145 (Batch Size:   256)\n    Iter  9133\t      0.05228876 (Batch Size:   256)\n    Iter  9134\t      0.04705500 (Batch Size:   256)\n    Iter  9135\t      0.04671655 (Batch Size:   256)\n    Iter  9136\t      0.04532267 (Batch Size:   256)\n    Iter  9137\t      0.04534009 (Batch Size:   256)\n    Iter  9138\t      0.04329253 (Batch Size:   256)\n    Iter  9139\t      0.03911515 (Batch Size:   256)\n    Iter  9140\t      0.04314433 (Batch Size:   256)\n    Iter  9141\t      0.04327136 (Batch Size:   256)\n    Iter  9142\t      0.04929203 (Batch Size:   256)\n    Iter  9143\t      0.05263987 (Batch Size:   256)\n    Iter  9144\t      0.04299634 (Batch Size:   256)\n    Iter  9145\t      0.04499353 (Batch Size:   256)\n    Iter  9146\t      0.04479694 (Batch Size:   256)\n    Iter  9147\t      0.04462071 (Batch Size:   256)\n    Iter  9148\t      0.05230179 (Batch Size:   256)\n    Iter  9149\t      0.04805405 (Batch Size:   256)\n    Iter  9150\t      0.04688711 (Batch Size:   256)\n    Iter  9151\t      0.04307739 (Batch Size:   256)\n    Iter  9152\t      0.05132201 (Batch Size:   256)\n    Iter  9153\t      0.05752179 (Batch Size:   256)\n    Iter  9154\t      0.04914918 (Batch Size:   256)\n    Iter  9155\t      0.04458620 (Batch Size:   256)\n    Iter  9156\t      0.04218145 (Batch Size:   256)\n    Iter  9157\t      0.04017442 (Batch Size:   256)\n    Iter  9158\t      0.04684458 (Batch Size:   256)\n    Iter  9159\t      0.05377861 (Batch Size:   256)\n    Iter  9160\t      0.05405413 (Batch Size:   256)\n    Iter  9161\t      0.04503221 (Batch Size:   256)\n    Iter  9162\t      0.04588524 (Batch Size:   256)\n    Iter  9163\t      0.04650097 (Batch Size:   256)\n    Iter  9164\t      0.04394706 (Batch Size:   256)\n    Iter  9165\t      0.04211192 (Batch Size:   256)\n    Iter  9166\t      0.04334806 (Batch Size:   256)\n    Iter  9167\t      0.04096308 (Batch Size:   256)\n    Iter  9168\t      0.04462192 (Batch Size:   256)\n    Iter  9169\t      0.04006601 (Batch Size:   256)\n    Iter  9170\t      0.04398015 (Batch Size:   256)\n    Iter  9171\t      0.04239746 (Batch Size:   256)\n    Iter  9172\t      0.04902482 (Batch Size:   256)\n    Iter  9173\t      0.04836721 (Batch Size:   256)\n    Iter  9174\t      0.04525325 (Batch Size:   256)\n    Iter  9175\t      0.04369926 (Batch Size:   256)\n    Iter  9176\t      0.04950801 (Batch Size:   256)\n    Iter  9177\t      0.04151658 (Batch Size:   256)\n    Iter  9178\t      0.04426217 (Batch Size:   256)\n    Iter  9179\t      0.04279971 (Batch Size:   256)\n    Iter  9180\t      0.04408194 (Batch Size:   256)\n    Iter  9181\t      0.04801388 (Batch Size:   256)\n    Iter  9182\t      0.04539418 (Batch Size:   256)\n    Iter  9183\t      0.04452395 (Batch Size:   256)\n    Iter  9184\t      0.04502302 (Batch Size:   256)\n    Iter  9185\t      0.04653109 (Batch Size:   256)\n    Iter  9186\t      0.04341005 (Batch Size:   256)\n    Iter  9187\t      0.04258932 (Batch Size:   256)\n    Iter  9188\t      0.04253550 (Batch Size:   256)\n    Iter  9189\t      0.04587171 (Batch Size:   256)\n    Iter  9190\t      0.04601985 (Batch Size:   256)\n    Iter  9191\t      0.04731425 (Batch Size:   256)\n    Iter  9192\t      0.04244481 (Batch Size:   256)\n    Iter  9193\t      0.04449092 (Batch Size:   256)\n    Iter  9194\t      0.05694276 (Batch Size:   256)\n    Iter  9195\t      0.05273281 (Batch Size:   256)\n    Iter  9196\t      0.05142308 (Batch Size:   256)\n    Iter  9197\t      0.05024452 (Batch Size:   256)\n    Iter  9198\t      0.04431086 (Batch Size:   256)\n    Iter  9199\t      0.04826758 (Batch Size:   256)\n    Iter  9200\t      0.04422944 (Batch Size:   256)\n    Iter  9201\t      0.04344176 (Batch Size:   256)\n    Iter  9202\t      0.04374126 (Batch Size:   256)\n    Iter  9203\t      0.04368944 (Batch Size:   256)\n    Iter  9204\t      0.04435779 (Batch Size:   256)\n    Iter  9205\t      0.04573028 (Batch Size:   256)\n    Iter  9206\t      0.04496230 (Batch Size:   256)\n    Iter  9207\t      0.04481719 (Batch Size:   256)\n    Iter  9208\t      0.04046512 (Batch Size:   256)\n    Iter  9209\t      0.04289906 (Batch Size:   256)\n    Iter  9210\t      0.04341059 (Batch Size:   256)\n    Iter  9211\t      0.04393796 (Batch Size:   256)\n    Iter  9212\t      0.04107180 (Batch Size:   256)\n    Iter  9213\t      0.04473203 (Batch Size:   256)\n    Iter  9214\t      0.04233892 (Batch Size:   256)\n    Iter  9215\t      0.05140504 (Batch Size:   256)\n    Iter  9216\t      0.04283349 (Batch Size:   256)\n    Iter  9217\t      0.04383615 (Batch Size:   256)\n    Iter  9218\t      0.04399104 (Batch Size:   256)\n    Iter  9219\t      0.04409408 (Batch Size:   256)\n    Iter  9220\t      0.04715921 (Batch Size:   256)\n    Iter  9221\t      0.04392044 (Batch Size:   256)\n    Iter  9222\t      0.04458096 (Batch Size:   256)\n    Iter  9223\t      0.04382457 (Batch Size:   256)\n    Iter  9224\t      0.04037378 (Batch Size:   256)\n    Iter  9225\t      0.04548392 (Batch Size:   256)\n    Iter  9226\t      0.04426642 (Batch Size:   256)\n    Iter  9227\t      0.04627554 (Batch Size:   256)\n    Iter  9228\t      0.04631113 (Batch Size:   256)\n    Iter  9229\t      0.05178016 (Batch Size:   256)\n    Iter  9230\t      0.04460776 (Batch Size:   256)\n    Iter  9231\t      0.04016598 (Batch Size:   256)\n    Iter  9232\t      0.04526325 (Batch Size:   256)\n    Iter  9233\t      0.04470857 (Batch Size:   256)\n    Iter  9234\t      0.04036814 (Batch Size:   256)\n    Iter  9235\t      0.04562363 (Batch Size:   256)\n    Iter  9236\t      0.04263268 (Batch Size:   256)\n    Iter  9237\t      0.04053865 (Batch Size:   256)\n    Iter  9238\t      0.04267298 (Batch Size:   256)\n    Iter  9239\t      0.04393480 (Batch Size:   256)\n    Iter  9240\t      0.04532899 (Batch Size:   256)\n    Iter  9241\t      0.07357317 (Batch Size:   256)\n    Iter  9242\t      0.06246887 (Batch Size:   256)\n    Iter  9243\t      0.04281968 (Batch Size:   256)\n    Iter  9244\t      0.04514067 (Batch Size:   256)\n    Iter  9245\t      0.04480173 (Batch Size:   256)\n    Iter  9246\t      0.05520375 (Batch Size:   256)\n    Iter  9247\t      0.05098467 (Batch Size:   256)\n    Iter  9248\t      0.07010845 (Batch Size:   256)\n    Iter  9249\t      0.07430293 (Batch Size:   256)\n    Iter  9250\t      0.05009560 (Batch Size:   256)\n    Iter  9251\t      0.04463438 (Batch Size:   256)\n    Iter  9252\t      0.04449681 (Batch Size:   256)\n    Iter  9253\t      0.04297870 (Batch Size:   256)\n    Iter  9254\t      0.04465303 (Batch Size:   256)\n    Iter  9255\t      0.04462414 (Batch Size:   256)\n    Iter  9256\t      0.04761318 (Batch Size:   256)\n    Iter  9257\t      0.05449435 (Batch Size:   256)\n    Iter  9258\t      0.05468828 (Batch Size:   256)\n    Iter  9259\t      0.04614822 (Batch Size:   256)\n    Iter  9260\t      0.04564085 (Batch Size:   256)\n    Iter  9261\t      0.04484026 (Batch Size:   256)\n    Iter  9262\t      0.04525433 (Batch Size:   256)\n    Iter  9263\t      0.04066864 (Batch Size:   256)\n    Iter  9264\t      0.04156998 (Batch Size:   256)\n    Iter  9265\t      0.04184200 (Batch Size:   256)\n    Iter  9266\t      0.04234710 (Batch Size:   256)\n    Iter  9267\t      0.04611300 (Batch Size:   256)\n    Iter  9268\t      0.05608644 (Batch Size:   256)\n    Iter  9269\t      0.05208410 (Batch Size:   256)\n    Iter  9270\t      0.04462145 (Batch Size:   256)\n    Iter  9271\t      0.04792208 (Batch Size:   256)\n    Iter  9272\t      0.05036695 (Batch Size:   256)\n    Iter  9273\t      0.04781275 (Batch Size:   256)\n    Iter  9274\t      0.04303177 (Batch Size:   256)\n    Iter  9275\t      0.04111591 (Batch Size:   256)\n    Iter  9276\t      0.04421818 (Batch Size:   256)\n    Iter  9277\t      0.04286405 (Batch Size:   256)\n    Iter  9278\t      0.04342898 (Batch Size:   256)\n    Iter  9279\t      0.03889441 (Batch Size:   256)\n    Iter  9280\t      0.04218025 (Batch Size:   256)\n    Iter  9281\t      0.04196011 (Batch Size:   256)\n    Iter  9282\t      0.04456691 (Batch Size:   256)\n    Iter  9283\t      0.05920632 (Batch Size:   256)\n    Iter  9284\t      0.04280699 (Batch Size:   256)\n    Iter  9285\t      0.04356275 (Batch Size:   256)\n    Iter  9286\t      0.04522108 (Batch Size:   256)\n    Iter  9287\t      0.04598824 (Batch Size:   256)\n    Iter  9288\t      0.04745605 (Batch Size:   256)\n    Iter  9289\t      0.04932213 (Batch Size:   256)\n    Iter  9290\t      0.04513945 (Batch Size:   256)\n    Iter  9291\t      0.04474519 (Batch Size:   256)\n    Iter  9292\t      0.04265384 (Batch Size:   256)\n    Iter  9293\t      0.05495185 (Batch Size:   256)\n    Iter  9294\t      0.04943943 (Batch Size:   256)\n    Iter  9295\t      0.05428922 (Batch Size:   256)\n    Iter  9296\t      0.06186027 (Batch Size:   256)\n    Iter  9297\t      0.06034863 (Batch Size:   256)\n    Iter  9298\t      0.04951770 (Batch Size:   256)\n    Iter  9299\t      0.04884005 (Batch Size:   256)\n    Iter  9300\t      0.04285651 (Batch Size:   256)\n    Iter  9301\t      0.04471884 (Batch Size:   256)\n    Iter  9302\t      0.04234061 (Batch Size:   256)\n    Iter  9303\t      0.04317429 (Batch Size:   256)\n    Iter  9304\t      0.04618017 (Batch Size:   256)\n    Iter  9305\t      0.04867662 (Batch Size:   256)\n    Iter  9306\t      0.04572937 (Batch Size:   256)\n    Iter  9307\t      0.04079270 (Batch Size:   256)\n    Iter  9308\t      0.04222685 (Batch Size:   256)\n    Iter  9309\t      0.04110200 (Batch Size:   256)\n    Iter  9310\t      0.05509678 (Batch Size:   256)\n    Iter  9311\t      0.04710120 (Batch Size:   256)\n    Iter  9312\t      0.04279586 (Batch Size:   256)\n    Iter  9313\t      0.04743685 (Batch Size:   256)\n    Iter  9314\t      0.04889327 (Batch Size:   256)\n    Iter  9315\t      0.05438627 (Batch Size:   256)\n    Iter  9316\t      0.04203457 (Batch Size:   256)\n    Iter  9317\t      0.04203664 (Batch Size:   256)\n    Iter  9318\t      0.04135200 (Batch Size:   256)\n    Iter  9319\t      0.05149479 (Batch Size:   256)\n    Iter  9320\t      0.05238209 (Batch Size:   256)\n    Iter  9321\t      0.04863133 (Batch Size:   256)\n    Iter  9322\t      0.04368913 (Batch Size:   256)\n    Iter  9323\t      0.04046739 (Batch Size:   256)\n    Iter  9324\t      0.04133490 (Batch Size:   256)\n    Iter  9325\t      0.05151331 (Batch Size:   256)\n    Iter  9326\t      0.04604763 (Batch Size:   256)\n    Iter  9327\t      0.04415379 (Batch Size:   256)\n    Iter  9328\t      0.04196105 (Batch Size:   256)\n    Iter  9329\t      0.04414117 (Batch Size:   256)\n    Iter  9330\t      0.04166049 (Batch Size:   256)\n    Iter  9331\t      0.04320939 (Batch Size:   256)\n    Iter  9332\t      0.04228752 (Batch Size:   256)\n    Iter  9333\t      0.04284908 (Batch Size:   256)\n    Iter  9334\t      0.04380183 (Batch Size:   256)\n    Iter  9335\t      0.04953119 (Batch Size:   256)\n    Iter  9336\t      0.04407683 (Batch Size:   256)\n    Iter  9337\t      0.04347520 (Batch Size:   256)\n    Iter  9338\t      0.05036365 (Batch Size:   256)\n    Iter  9339\t      0.05385667 (Batch Size:   256)\n    Iter  9340\t      0.04767083 (Batch Size:   256)\n    Iter  9341\t      0.04319027 (Batch Size:   256)\n    Iter  9342\t      0.04646437 (Batch Size:   256)\n    Iter  9343\t      0.04336252 (Batch Size:   256)\n    Iter  9344\t      0.04782511 (Batch Size:   256)\n    Iter  9345\t      0.05299898 (Batch Size:   256)\n    Iter  9346\t      0.05053525 (Batch Size:   256)\n    Iter  9347\t      0.04436483 (Batch Size:   256)\n    Iter  9348\t      0.04837379 (Batch Size:   256)\n    Iter  9349\t      0.04690698 (Batch Size:   256)\n    Iter  9350\t      0.04551767 (Batch Size:   256)\n    Iter  9351\t      0.05033131 (Batch Size:   256)\n    Iter  9352\t      0.04617000 (Batch Size:   256)\n    Iter  9353\t      0.04635173 (Batch Size:   256)\n    Iter  9354\t      0.05052810 (Batch Size:   256)\n    Iter  9355\t      0.04774863 (Batch Size:   256)\n    Iter  9356\t      0.04093726 (Batch Size:   256)\n    Iter  9357\t      0.04168620 (Batch Size:   256)\n    Iter  9358\t      0.04491363 (Batch Size:   256)\n    Iter  9359\t      0.04087917 (Batch Size:   256)\n    Iter  9360\t      0.04303496 (Batch Size:   256)\n    Iter  9361\t      0.04405658 (Batch Size:   256)\n    Iter  9362\t      0.04498831 (Batch Size:   256)\n    Iter  9363\t      0.04688642 (Batch Size:   256)\n    Iter  9364\t      0.04401584 (Batch Size:   256)\n    Iter  9365\t      0.04494773 (Batch Size:   256)\n    Iter  9366\t      0.04088704 (Batch Size:   256)\n    Iter  9367\t      0.04502974 (Batch Size:   256)\n    Iter  9368\t      0.04609441 (Batch Size:   256)\n    Iter  9369\t      0.04319642 (Batch Size:   256)\n    Iter  9370\t      0.04528638 (Batch Size:   256)\n    Iter  9371\t      0.04823892 (Batch Size:   256)\n    Iter  9372\t      0.04127077 (Batch Size:   256)\n    Iter  9373\t      0.04375435 (Batch Size:   256)\n    Iter  9374\t      0.04580952 (Batch Size:   256)\n    Iter  9375\t      0.04143250 (Batch Size:   256)\n    Iter  9376\t      0.04352683 (Batch Size:   256)\n    Iter  9377\t      0.04364157 (Batch Size:   256)\n    Iter  9378\t      0.04285778 (Batch Size:   256)\n    Iter  9379\t      0.04278476 (Batch Size:   256)\n    Iter  9380\t      0.04386501 (Batch Size:   256)\n    Iter  9381\t      0.03921658 (Batch Size:   256)\n    Iter  9382\t      0.04476898 (Batch Size:   256)\n    Iter  9383\t      0.04743797 (Batch Size:   256)\n    Iter  9384\t      0.04084019 (Batch Size:   256)\n    Iter  9385\t      0.04247242 (Batch Size:   256)\n    Iter  9386\t      0.04685454 (Batch Size:   256)\n    Iter  9387\t      0.04530378 (Batch Size:   256)\n    Iter  9388\t      0.04570542 (Batch Size:   256)\n    Iter  9389\t      0.04268544 (Batch Size:   256)\n    Iter  9390\t      0.04117983 (Batch Size:   256)\n    Iter  9391\t      0.04253283 (Batch Size:   256)\n    Iter  9392\t      0.04737769 (Batch Size:   256)\n    Iter  9393\t      0.05540491 (Batch Size:   256)\n    Iter  9394\t      0.05444192 (Batch Size:   256)\n    Iter  9395\t      0.04740052 (Batch Size:   256)\n    Iter  9396\t      0.04403137 (Batch Size:   256)\n    Iter  9397\t      0.03933386 (Batch Size:   256)\n    Iter  9398\t      0.04448340 (Batch Size:   256)\n    Iter  9399\t      0.04454300 (Batch Size:   256)\n    Iter  9400\t      0.04415884 (Batch Size:   256)\n    Iter  9401\t      0.04400451 (Batch Size:   256)\n    Iter  9402\t      0.04174269 (Batch Size:   256)\n    Iter  9403\t      0.04652255 (Batch Size:   256)\n    Iter  9404\t      0.04482992 (Batch Size:   256)\n    Iter  9405\t      0.04416649 (Batch Size:   256)\n    Iter  9406\t      0.04592805 (Batch Size:   256)\n    Iter  9407\t      0.05309244 (Batch Size:   256)\n    Iter  9408\t      0.04448109 (Batch Size:   256)\n    Iter  9409\t      0.04718988 (Batch Size:   256)\n    Iter  9410\t      0.04570003 (Batch Size:   256)\n    Iter  9411\t      0.05027168 (Batch Size:   256)\n    Iter  9412\t      0.04295056 (Batch Size:   256)\n    Iter  9413\t      0.04137065 (Batch Size:   256)\n    Iter  9414\t      0.04653743 (Batch Size:   256)\n    Iter  9415\t      0.04287074 (Batch Size:   256)\n    Iter  9416\t      0.04456651 (Batch Size:   256)\n    Iter  9417\t      0.05049122 (Batch Size:   256)\n    Iter  9418\t      0.04923262 (Batch Size:   256)\n    Iter  9419\t      0.04206046 (Batch Size:   256)\n    Iter  9420\t      0.04663200 (Batch Size:   256)\n    Iter  9421\t      0.04921269 (Batch Size:   256)\n    Iter  9422\t      0.04355377 (Batch Size:   256)\n    Iter  9423\t      0.04207055 (Batch Size:   256)\n    Iter  9424\t      0.04718633 (Batch Size:   256)\n    Iter  9425\t      0.04492286 (Batch Size:   256)\n    Iter  9426\t      0.05088914 (Batch Size:   256)\n    Iter  9427\t      0.04898457 (Batch Size:   256)\n    Iter  9428\t      0.04080817 (Batch Size:   256)\n    Iter  9429\t      0.04237732 (Batch Size:   256)\n    Iter  9430\t      0.04344305 (Batch Size:   256)\n    Iter  9431\t      0.04237058 (Batch Size:   256)\n    Iter  9432\t      0.04279956 (Batch Size:   256)\n    Iter  9433\t      0.05536731 (Batch Size:   256)\n    Iter  9434\t      0.06498260 (Batch Size:   256)\n    Iter  9435\t      0.05300502 (Batch Size:   256)\n    Iter  9436\t      0.06220717 (Batch Size:   256)\n    Iter  9437\t      0.05078120 (Batch Size:   256)\n    Iter  9438\t      0.04859340 (Batch Size:   256)\n    Iter  9439\t      0.04816877 (Batch Size:   256)\n    Iter  9440\t      0.04924329 (Batch Size:   256)\n    Iter  9441\t      0.04188367 (Batch Size:   256)\n    Iter  9442\t      0.05024023 (Batch Size:   256)\n    Iter  9443\t      0.05814569 (Batch Size:   256)\n    Iter  9444\t      0.05270467 (Batch Size:   256)\n    Iter  9445\t      0.04519887 (Batch Size:   256)\n    Iter  9446\t      0.04366154 (Batch Size:   256)\n    Iter  9447\t      0.04411382 (Batch Size:   256)\n    Iter  9448\t      0.04561298 (Batch Size:   256)\n    Iter  9449\t      0.04273715 (Batch Size:   256)\n    Iter  9450\t      0.05063778 (Batch Size:   256)\n    Iter  9451\t      0.04685155 (Batch Size:   256)\n    Iter  9452\t      0.04205099 (Batch Size:   256)\n    Iter  9453\t      0.04174791 (Batch Size:   256)\n    Iter  9454\t      0.04404050 (Batch Size:   256)\n    Iter  9455\t      0.04728278 (Batch Size:   256)\n    Iter  9456\t      0.04277726 (Batch Size:   256)\n    Iter  9457\t      0.04516133 (Batch Size:   256)\n    Iter  9458\t      0.04978430 (Batch Size:   256)\n    Iter  9459\t      0.05040349 (Batch Size:   256)\n    Iter  9460\t      0.04510999 (Batch Size:   256)\n    Iter  9461\t      0.04507388 (Batch Size:   256)\n    Iter  9462\t      0.04488066 (Batch Size:   256)\n    Iter  9463\t      0.04488993 (Batch Size:   256)\n    Iter  9464\t      0.04329606 (Batch Size:   256)\n    Iter  9465\t      0.04337255 (Batch Size:   256)\n    Iter  9466\t      0.04691308 (Batch Size:   256)\n    Iter  9467\t      0.04578984 (Batch Size:   256)\n    Iter  9468\t      0.04334769 (Batch Size:   256)\n    Iter  9469\t      0.04060872 (Batch Size:   256)\n    Iter  9470\t      0.04467200 (Batch Size:   256)\n    Iter  9471\t      0.05001603 (Batch Size:   256)\n    Iter  9472\t      0.04894759 (Batch Size:   256)\n    Iter  9473\t      0.04215325 (Batch Size:   256)\n    Iter  9474\t      0.04224288 (Batch Size:   256)\n    Iter  9475\t      0.04518533 (Batch Size:   256)\n    Iter  9476\t      0.04718122 (Batch Size:   256)\n    Iter  9477\t      0.04479026 (Batch Size:   256)\n    Iter  9478\t      0.04103329 (Batch Size:   256)\n    Iter  9479\t      0.03916442 (Batch Size:   256)\n    Iter  9480\t      0.04089594 (Batch Size:   256)\n    Iter  9481\t      0.04860028 (Batch Size:   256)\n    Iter  9482\t      0.04906086 (Batch Size:   256)\n    Iter  9483\t      0.05037140 (Batch Size:   256)\n    Iter  9484\t      0.04463474 (Batch Size:   256)\n    Iter  9485\t      0.04086820 (Batch Size:   256)\n    Iter  9486\t      0.04387911 (Batch Size:   256)\n    Iter  9487\t      0.04474566 (Batch Size:   256)\n    Iter  9488\t      0.04333882 (Batch Size:   256)\n    Iter  9489\t      0.04356777 (Batch Size:   256)\n    Iter  9490\t      0.04956660 (Batch Size:   256)\n    Iter  9491\t      0.05220612 (Batch Size:   256)\n    Iter  9492\t      0.04335992 (Batch Size:   256)\n    Iter  9493\t      0.03946079 (Batch Size:   256)\n    Iter  9494\t      0.04248736 (Batch Size:   256)\n    Iter  9495\t      0.04303571 (Batch Size:   256)\n    Iter  9496\t      0.04312993 (Batch Size:   256)\n    Iter  9497\t      0.04411581 (Batch Size:   256)\n    Iter  9498\t      0.06618188 (Batch Size:   256)\n    Iter  9499\t      0.06923709 (Batch Size:   256)\n    Iter  9500\t      0.06465163 (Batch Size:   256)\n    Iter  9501\t      0.05812720 (Batch Size:   256)\n    Iter  9502\t      0.05386749 (Batch Size:   256)\n    Iter  9503\t      0.05108263 (Batch Size:   256)\n    Iter  9504\t      0.04397713 (Batch Size:   256)\n    Iter  9505\t      0.04187129 (Batch Size:   256)\n    Iter  9506\t      0.04709362 (Batch Size:   256)\n    Iter  9507\t      0.04790285 (Batch Size:   256)\n    Iter  9508\t      0.04741493 (Batch Size:   256)\n    Iter  9509\t      0.04608602 (Batch Size:   256)\n    Iter  9510\t      0.04489187 (Batch Size:   256)\n    Iter  9511\t      0.04383426 (Batch Size:   256)\n    Iter  9512\t      0.04431831 (Batch Size:   256)\n    Iter  9513\t      0.04725801 (Batch Size:   256)\n    Iter  9514\t      0.04826376 (Batch Size:   256)\n    Iter  9515\t      0.04267523 (Batch Size:   256)\n    Iter  9516\t      0.04308414 (Batch Size:   256)\n    Iter  9517\t      0.04126651 (Batch Size:   256)\n    Iter  9518\t      0.04529040 (Batch Size:   256)\n    Iter  9519\t      0.04148405 (Batch Size:   256)\n    Iter  9520\t      0.04183102 (Batch Size:   256)\n    Iter  9521\t      0.04193663 (Batch Size:   256)\n    Iter  9522\t      0.03823193 (Batch Size:   256)\n    Iter  9523\t      0.04225021 (Batch Size:   256)\n    Iter  9524\t      0.04516857 (Batch Size:   256)\n    Iter  9525\t      0.04862187 (Batch Size:   256)\n    Iter  9526\t      0.04577030 (Batch Size:   256)\n    Iter  9527\t      0.04225830 (Batch Size:   256)\n    Iter  9528\t      0.04399894 (Batch Size:   256)\n    Iter  9529\t      0.04048787 (Batch Size:   256)\n    Iter  9530\t      0.04113160 (Batch Size:   256)\n    Iter  9531\t      0.04476118 (Batch Size:   256)\n    Iter  9532\t      0.04543583 (Batch Size:   256)\n    Iter  9533\t      0.04427433 (Batch Size:   256)\n    Iter  9534\t      0.04205461 (Batch Size:   256)\n    Iter  9535\t      0.04408584 (Batch Size:   256)\n    Iter  9536\t      0.05857234 (Batch Size:   256)\n    Iter  9537\t      0.04211965 (Batch Size:   256)\n    Iter  9538\t      0.03991224 (Batch Size:   256)\n    Iter  9539\t      0.04091911 (Batch Size:   256)\n    Iter  9540\t      0.04438956 (Batch Size:   256)\n    Iter  9541\t      0.04134735 (Batch Size:   256)\n    Iter  9542\t      0.04393588 (Batch Size:   256)\n    Iter  9543\t      0.03987555 (Batch Size:   256)\n    Iter  9544\t      0.04304203 (Batch Size:   256)\n    Iter  9545\t      0.04589208 (Batch Size:   256)\n    Iter  9546\t      0.04359178 (Batch Size:   256)\n    Iter  9547\t      0.04211855 (Batch Size:   256)\n    Iter  9548\t      0.04703587 (Batch Size:   256)\n    Iter  9549\t      0.04265846 (Batch Size:   256)\n    Iter  9550\t      0.04414018 (Batch Size:   256)\n    Iter  9551\t      0.04331794 (Batch Size:   256)\n    Iter  9552\t      0.04246150 (Batch Size:   256)\n    Iter  9553\t      0.04161486 (Batch Size:   256)\n    Iter  9554\t      0.04154830 (Batch Size:   256)\n    Iter  9555\t      0.04817101 (Batch Size:   256)\n    Iter  9556\t      0.04319717 (Batch Size:   256)\n    Iter  9557\t      0.04460172 (Batch Size:   256)\n    Iter  9558\t      0.04509921 (Batch Size:   256)\n    Iter  9559\t      0.04565096 (Batch Size:   256)\n    Iter  9560\t      0.04135225 (Batch Size:   256)\n    Iter  9561\t      0.04823454 (Batch Size:   256)\n    Iter  9562\t      0.04956575 (Batch Size:   256)\n    Iter  9563\t      0.04239929 (Batch Size:   256)\n    Iter  9564\t      0.04139623 (Batch Size:   256)\n    Iter  9565\t      0.04505469 (Batch Size:   256)\n    Iter  9566\t      0.04224371 (Batch Size:   256)\n    Iter  9567\t      0.04698990 (Batch Size:   256)\n    Iter  9568\t      0.04630037 (Batch Size:   256)\n    Iter  9569\t      0.04502972 (Batch Size:   256)\n    Iter  9570\t      0.04630618 (Batch Size:   256)\n    Iter  9571\t      0.04538533 (Batch Size:   256)\n    Iter  9572\t      0.04849554 (Batch Size:   256)\n    Iter  9573\t      0.04400806 (Batch Size:   256)\n    Iter  9574\t      0.04541705 (Batch Size:   256)\n    Iter  9575\t      0.04447655 (Batch Size:   256)\n    Iter  9576\t      0.05171591 (Batch Size:   256)\n    Iter  9577\t      0.04729194 (Batch Size:   256)\n    Iter  9578\t      0.04351452 (Batch Size:   256)\n    Iter  9579\t      0.04373289 (Batch Size:   256)\n    Iter  9580\t      0.04765937 (Batch Size:   256)\n    Iter  9581\t      0.04491775 (Batch Size:   256)\n    Iter  9582\t      0.04328774 (Batch Size:   256)\n    Iter  9583\t      0.04355985 (Batch Size:   256)\n    Iter  9584\t      0.04756054 (Batch Size:   256)\n    Iter  9585\t      0.04545945 (Batch Size:   256)\n    Iter  9586\t      0.04525067 (Batch Size:   256)\n    Iter  9587\t      0.03961413 (Batch Size:   256)\n    Iter  9588\t      0.04100147 (Batch Size:   256)\n    Iter  9589\t      0.03988060 (Batch Size:   256)\n    Iter  9590\t      0.04325605 (Batch Size:   256)\n    Iter  9591\t      0.04446283 (Batch Size:   256)\n    Iter  9592\t      0.04388683 (Batch Size:   256)\n    Iter  9593\t      0.04382993 (Batch Size:   256)\n    Iter  9594\t      0.04468568 (Batch Size:   256)\n    Iter  9595\t      0.04543824 (Batch Size:   256)\n    Iter  9596\t      0.04426307 (Batch Size:   256)\n    Iter  9597\t      0.04475201 (Batch Size:   256)\n    Iter  9598\t      0.04475510 (Batch Size:   256)\n    Iter  9599\t      0.04740684 (Batch Size:   256)\n    Iter  9600\t      0.05715476 (Batch Size:   256)\n    Iter  9601\t      0.08529781 (Batch Size:   256)\n    Iter  9602\t      0.06157253 (Batch Size:   256)\n    Iter  9603\t      0.04653393 (Batch Size:   256)\n    Iter  9604\t      0.04464487 (Batch Size:   256)\n    Iter  9605\t      0.04291222 (Batch Size:   256)\n    Iter  9606\t      0.04426374 (Batch Size:   256)\n    Iter  9607\t      0.04647388 (Batch Size:   256)\n    Iter  9608\t      0.04524903 (Batch Size:   256)\n    Iter  9609\t      0.04309503 (Batch Size:   256)\n    Iter  9610\t      0.04292241 (Batch Size:   256)\n    Iter  9611\t      0.04105375 (Batch Size:   256)\n    Iter  9612\t      0.03908628 (Batch Size:   256)\n    Iter  9613\t      0.04250213 (Batch Size:   256)\n    Iter  9614\t      0.04098081 (Batch Size:   256)\n    Iter  9615\t      0.04295667 (Batch Size:   256)\n    Iter  9616\t      0.04274793 (Batch Size:   256)\n    Iter  9617\t      0.04087342 (Batch Size:   256)\n    Iter  9618\t      0.04251221 (Batch Size:   256)\n    Iter  9619\t      0.04297797 (Batch Size:   256)\n    Iter  9620\t      0.04551346 (Batch Size:   256)\n    Iter  9621\t      0.04723051 (Batch Size:   256)\n    Iter  9622\t      0.04214782 (Batch Size:   256)\n    Iter  9623\t      0.04149822 (Batch Size:   256)\n    Iter  9624\t      0.04063016 (Batch Size:   256)\n    Iter  9625\t      0.04479977 (Batch Size:   256)\n    Iter  9626\t      0.04498868 (Batch Size:   256)\n    Iter  9627\t      0.04224322 (Batch Size:   256)\n    Iter  9628\t      0.04592272 (Batch Size:   256)\n    Iter  9629\t      0.04120900 (Batch Size:   256)\n    Iter  9630\t      0.04284680 (Batch Size:   256)\n    Iter  9631\t      0.04427671 (Batch Size:   256)\n    Iter  9632\t      0.04772066 (Batch Size:   256)\n    Iter  9633\t      0.05916672 (Batch Size:   256)\n    Iter  9634\t      0.04179499 (Batch Size:   256)\n    Iter  9635\t      0.04303099 (Batch Size:   256)\n    Iter  9636\t      0.04344065 (Batch Size:   256)\n    Iter  9637\t      0.04484925 (Batch Size:   256)\n    Iter  9638\t      0.04323546 (Batch Size:   256)\n    Iter  9639\t      0.04761906 (Batch Size:   256)\n    Iter  9640\t      0.04637297 (Batch Size:   256)\n    Iter  9641\t      0.04317183 (Batch Size:   256)\n    Iter  9642\t      0.04406342 (Batch Size:   256)\n    Iter  9643\t      0.04918131 (Batch Size:   256)\n    Iter  9644\t      0.04406201 (Batch Size:   256)\n    Iter  9645\t      0.04600708 (Batch Size:   256)\n    Iter  9646\t      0.04278842 (Batch Size:   256)\n    Iter  9647\t      0.04276157 (Batch Size:   256)\n    Iter  9648\t      0.04711899 (Batch Size:   256)\n    Iter  9649\t      0.04103766 (Batch Size:   256)\n    Iter  9650\t      0.04498978 (Batch Size:   256)\n    Iter  9651\t      0.04309975 (Batch Size:   256)\n    Iter  9652\t      0.04373193 (Batch Size:   256)\n    Iter  9653\t      0.04242594 (Batch Size:   256)\n    Iter  9654\t      0.04224096 (Batch Size:   256)\n    Iter  9655\t      0.04276872 (Batch Size:   256)\n    Iter  9656\t      0.04289061 (Batch Size:   256)\n    Iter  9657\t      0.04670061 (Batch Size:   256)\n    Iter  9658\t      0.05882493 (Batch Size:   256)\n    Iter  9659\t      0.05133878 (Batch Size:   256)\n    Iter  9660\t      0.05089994 (Batch Size:   256)\n    Iter  9661\t      0.05353800 (Batch Size:   256)\n    Iter  9662\t      0.04519428 (Batch Size:   256)\n    Iter  9663\t      0.04610053 (Batch Size:   256)\n    Iter  9664\t      0.03829933 (Batch Size:   256)\n    Iter  9665\t      0.04527157 (Batch Size:   256)\n    Iter  9666\t      0.04495092 (Batch Size:   256)\n    Iter  9667\t      0.04269782 (Batch Size:   256)\n    Iter  9668\t      0.05570262 (Batch Size:   256)\n    Iter  9669\t      0.05052687 (Batch Size:   256)\n    Iter  9670\t      0.04502719 (Batch Size:   256)\n    Iter  9671\t      0.04292081 (Batch Size:   256)\n    Iter  9672\t      0.04386099 (Batch Size:   256)\n    Iter  9673\t      0.04418632 (Batch Size:   256)\n    Iter  9674\t      0.04347249 (Batch Size:   256)\n    Iter  9675\t      0.04754894 (Batch Size:   256)\n    Iter  9676\t      0.03993357 (Batch Size:   256)\n    Iter  9677\t      0.04139881 (Batch Size:   256)\n    Iter  9678\t      0.04608550 (Batch Size:   256)\n    Iter  9679\t      0.04225910 (Batch Size:   256)\n    Iter  9680\t      0.04324458 (Batch Size:   256)\n    Iter  9681\t      0.04143974 (Batch Size:   256)\n    Iter  9682\t      0.04295067 (Batch Size:   256)\n    Iter  9683\t      0.04560242 (Batch Size:   256)\n    Iter  9684\t      0.04749543 (Batch Size:   256)\n    Iter  9685\t      0.04304996 (Batch Size:   256)\n    Iter  9686\t      0.04594413 (Batch Size:   256)\n    Iter  9687\t      0.04233984 (Batch Size:   256)\n    Iter  9688\t      0.04451912 (Batch Size:   256)\n    Iter  9689\t      0.04477373 (Batch Size:   256)\n    Iter  9690\t      0.04129803 (Batch Size:   256)\n    Iter  9691\t      0.04209023 (Batch Size:   256)\n    Iter  9692\t      0.03829084 (Batch Size:   256)\n    Iter  9693\t      0.04141580 (Batch Size:   256)\n    Iter  9694\t      0.04587061 (Batch Size:   256)\n    Iter  9695\t      0.04659585 (Batch Size:   256)\n    Iter  9696\t      0.04489419 (Batch Size:   256)\n    Iter  9697\t      0.05070681 (Batch Size:   256)\n    Iter  9698\t      0.05584863 (Batch Size:   256)\n    Iter  9699\t      0.04351473 (Batch Size:   256)\n    Iter  9700\t      0.03796579 (Batch Size:   256)\n    Iter  9701\t      0.04076292 (Batch Size:   256)\n    Iter  9702\t      0.04314789 (Batch Size:   256)\n    Iter  9703\t      0.04172571 (Batch Size:   256)\n    Iter  9704\t      0.03979721 (Batch Size:   256)\n    Iter  9705\t      0.04254278 (Batch Size:   256)\n    Iter  9706\t      0.04171532 (Batch Size:   256)\n    Iter  9707\t      0.04180277 (Batch Size:   256)\n    Iter  9708\t      0.04150695 (Batch Size:   256)\n    Iter  9709\t      0.05380784 (Batch Size:   256)\n    Iter  9710\t      0.04866120 (Batch Size:   256)\n    Iter  9711\t      0.04691433 (Batch Size:   256)\n    Iter  9712\t      0.04613338 (Batch Size:   256)\n    Iter  9713\t      0.04499541 (Batch Size:   256)\n    Iter  9714\t      0.04544596 (Batch Size:   256)\n    Iter  9715\t      0.04686398 (Batch Size:   256)\n    Iter  9716\t      0.04901664 (Batch Size:   256)\n    Iter  9717\t      0.04444659 (Batch Size:   256)\n    Iter  9718\t      0.04059784 (Batch Size:   256)\n    Iter  9719\t      0.04268087 (Batch Size:   256)\n    Iter  9720\t      0.04122643 (Batch Size:   256)\n    Iter  9721\t      0.04155637 (Batch Size:   256)\n    Iter  9722\t      0.04086175 (Batch Size:   256)\n    Iter  9723\t      0.04600321 (Batch Size:   256)\n    Iter  9724\t      0.04857395 (Batch Size:   256)\n    Iter  9725\t      0.04527015 (Batch Size:   256)\n    Iter  9726\t      0.04559859 (Batch Size:   256)\n    Iter  9727\t      0.04229876 (Batch Size:   256)\n    Iter  9728\t      0.04390638 (Batch Size:   256)\n    Iter  9729\t      0.05298685 (Batch Size:   256)\n    Iter  9730\t      0.05562268 (Batch Size:   256)\n    Iter  9731\t      0.04153117 (Batch Size:   256)\n    Iter  9732\t      0.04337917 (Batch Size:   256)\n    Iter  9733\t      0.03849767 (Batch Size:   256)\n    Iter  9734\t      0.04088079 (Batch Size:   256)\n    Iter  9735\t      0.04394460 (Batch Size:   256)\n    Iter  9736\t      0.04141094 (Batch Size:   256)\n    Iter  9737\t      0.04128352 (Batch Size:   256)\n    Iter  9738\t      0.04923867 (Batch Size:   256)\n    Iter  9739\t      0.04968185 (Batch Size:   256)\n    Iter  9740\t      0.04752684 (Batch Size:   256)\n    Iter  9741\t      0.04421595 (Batch Size:   256)\n    Iter  9742\t      0.04541875 (Batch Size:   256)\n    Iter  9743\t      0.04434336 (Batch Size:   256)\n    Iter  9744\t      0.04418598 (Batch Size:   256)\n    Iter  9745\t      0.04976976 (Batch Size:   256)\n    Iter  9746\t      0.05667217 (Batch Size:   256)\n    Iter  9747\t      0.04545553 (Batch Size:   256)\n    Iter  9748\t      0.03963007 (Batch Size:   256)\n    Iter  9749\t      0.04247851 (Batch Size:   256)\n    Iter  9750\t      0.03970871 (Batch Size:   256)\n    Iter  9751\t      0.04402415 (Batch Size:   256)\n    Iter  9752\t      0.04493099 (Batch Size:   256)\n    Iter  9753\t      0.04686288 (Batch Size:   256)\n    Iter  9754\t      0.04593287 (Batch Size:   256)\n    Iter  9755\t      0.05303627 (Batch Size:   256)\n    Iter  9756\t      0.05077030 (Batch Size:   256)\n    Iter  9757\t      0.04310599 (Batch Size:   256)\n    Iter  9758\t      0.04296053 (Batch Size:   256)\n    Iter  9759\t      0.03889276 (Batch Size:   256)\n    Iter  9760\t      0.04525231 (Batch Size:   256)\n    Iter  9761\t      0.04003185 (Batch Size:   256)\n    Iter  9762\t      0.04116702 (Batch Size:   256)\n    Iter  9763\t      0.04215270 (Batch Size:   256)\n    Iter  9764\t      0.04173716 (Batch Size:   256)\n    Iter  9765\t      0.04502339 (Batch Size:   256)\n    Iter  9766\t      0.04494016 (Batch Size:   256)\n    Iter  9767\t      0.04556536 (Batch Size:   256)\n    Iter  9768\t      0.04954049 (Batch Size:   256)\n    Iter  9769\t      0.05903154 (Batch Size:   256)\n    Iter  9770\t      0.04913551 (Batch Size:   256)\n    Iter  9771\t      0.04987342 (Batch Size:   256)\n    Iter  9772\t      0.04393668 (Batch Size:   256)\n    Iter  9773\t      0.04207906 (Batch Size:   256)\n    Iter  9774\t      0.04329818 (Batch Size:   256)\n    Iter  9775\t      0.04811268 (Batch Size:   256)\n    Iter  9776\t      0.04884307 (Batch Size:   256)\n    Iter  9777\t      0.04181639 (Batch Size:   256)\n    Iter  9778\t      0.04112635 (Batch Size:   256)\n    Iter  9779\t      0.04118614 (Batch Size:   256)\n    Iter  9780\t      0.04310391 (Batch Size:   256)\n    Iter  9781\t      0.04000253 (Batch Size:   256)\n    Iter  9782\t      0.04758779 (Batch Size:   256)\n    Iter  9783\t      0.05040019 (Batch Size:   256)\n    Iter  9784\t      0.04244746 (Batch Size:   256)\n    Iter  9785\t      0.04141582 (Batch Size:   256)\n    Iter  9786\t      0.03913566 (Batch Size:   256)\n    Iter  9787\t      0.04371752 (Batch Size:   256)\n    Iter  9788\t      0.04314659 (Batch Size:   256)\n    Iter  9789\t      0.03922668 (Batch Size:   256)\n    Iter  9790\t      0.04582883 (Batch Size:   256)\n    Iter  9791\t      0.06702595 (Batch Size:   256)\n    Iter  9792\t      0.05361985 (Batch Size:   256)\n    Iter  9793\t      0.04742300 (Batch Size:   256)\n    Iter  9794\t      0.05450862 (Batch Size:   256)\n    Iter  9795\t      0.04451004 (Batch Size:   256)\n    Iter  9796\t      0.04752298 (Batch Size:   256)\n    Iter  9797\t      0.04667006 (Batch Size:   256)\n    Iter  9798\t      0.05003809 (Batch Size:   256)\n    Iter  9799\t      0.04323089 (Batch Size:   256)\n    Iter  9800\t      0.04694304 (Batch Size:   256)\n    Iter  9801\t      0.04762099 (Batch Size:   256)\n    Iter  9802\t      0.05652009 (Batch Size:   256)\n    Iter  9803\t      0.04762032 (Batch Size:   256)\n    Iter  9804\t      0.04494757 (Batch Size:   256)\n    Iter  9805\t      0.04496255 (Batch Size:   256)\n    Iter  9806\t      0.04386634 (Batch Size:   256)\n    Iter  9807\t      0.04427199 (Batch Size:   256)\n    Iter  9808\t      0.04129152 (Batch Size:   256)\n    Iter  9809\t      0.04290093 (Batch Size:   256)\n    Iter  9810\t      0.04352706 (Batch Size:   256)\n    Iter  9811\t      0.03866685 (Batch Size:   256)\n    Iter  9812\t      0.04131846 (Batch Size:   256)\n    Iter  9813\t      0.05001358 (Batch Size:   256)\n    Iter  9814\t      0.04491293 (Batch Size:   256)\n    Iter  9815\t      0.03973632 (Batch Size:   256)\n    Iter  9816\t      0.04515677 (Batch Size:   256)\n    Iter  9817\t      0.04957288 (Batch Size:   256)\n    Iter  9818\t      0.05588309 (Batch Size:   256)\n    Iter  9819\t      0.04965512 (Batch Size:   256)\n    Iter  9820\t      0.04265899 (Batch Size:   256)\n    Iter  9821\t      0.04231890 (Batch Size:   256)\n    Iter  9822\t      0.04511401 (Batch Size:   256)\n    Iter  9823\t      0.04304790 (Batch Size:   256)\n    Iter  9824\t      0.04135198 (Batch Size:   256)\n    Iter  9825\t      0.04188431 (Batch Size:   256)\n    Iter  9826\t      0.04411640 (Batch Size:   256)\n    Iter  9827\t      0.04804054 (Batch Size:   256)\n    Iter  9828\t      0.04684153 (Batch Size:   256)\n    Iter  9829\t      0.04340477 (Batch Size:   256)\n    Iter  9830\t      0.04597050 (Batch Size:   256)\n    Iter  9831\t      0.05667916 (Batch Size:   256)\n    Iter  9832\t      0.04329395 (Batch Size:   256)\n    Iter  9833\t      0.04356230 (Batch Size:   256)\n    Iter  9834\t      0.03954528 (Batch Size:   256)\n    Iter  9835\t      0.03932040 (Batch Size:   256)\n    Iter  9836\t      0.03995279 (Batch Size:   256)\n    Iter  9837\t      0.04267740 (Batch Size:   256)\n    Iter  9838\t      0.03990626 (Batch Size:   256)\n    Iter  9839\t      0.04276747 (Batch Size:   256)\n    Iter  9840\t      0.04572242 (Batch Size:   256)\n    Iter  9841\t      0.05402367 (Batch Size:   256)\n    Iter  9842\t      0.05473279 (Batch Size:   256)\n    Iter  9843\t      0.05036623 (Batch Size:   256)\n    Iter  9844\t      0.04846404 (Batch Size:   256)\n    Iter  9845\t      0.04280276 (Batch Size:   256)\n    Iter  9846\t      0.04273487 (Batch Size:   256)\n    Iter  9847\t      0.04563705 (Batch Size:   256)\n    Iter  9848\t      0.04688308 (Batch Size:   256)\n    Iter  9849\t      0.04438958 (Batch Size:   256)\n    Iter  9850\t      0.04791612 (Batch Size:   256)\n    Iter  9851\t      0.04784849 (Batch Size:   256)\n    Iter  9852\t      0.04479209 (Batch Size:   256)\n    Iter  9853\t      0.04745232 (Batch Size:   256)\n    Iter  9854\t      0.04589410 (Batch Size:   256)\n    Iter  9855\t      0.04431061 (Batch Size:   256)\n    Iter  9856\t      0.04230847 (Batch Size:   256)\n    Iter  9857\t      0.04272636 (Batch Size:   256)\n    Iter  9858\t      0.04643321 (Batch Size:   256)\n    Iter  9859\t      0.03853153 (Batch Size:   256)\n    Iter  9860\t      0.04460990 (Batch Size:   256)\n    Iter  9861\t      0.04062343 (Batch Size:   256)\n    Iter  9862\t      0.04505613 (Batch Size:   256)\n    Iter  9863\t      0.04200461 (Batch Size:   256)\n    Iter  9864\t      0.04772348 (Batch Size:   256)\n    Iter  9865\t      0.04421133 (Batch Size:   256)\n    Iter  9866\t      0.04106994 (Batch Size:   256)\n    Iter  9867\t      0.04500493 (Batch Size:   256)\n    Iter  9868\t      0.03954439 (Batch Size:   256)\n    Iter  9869\t      0.04072672 (Batch Size:   256)\n    Iter  9870\t      0.04297275 (Batch Size:   256)\n    Iter  9871\t      0.04440355 (Batch Size:   256)\n    Iter  9872\t      0.04791985 (Batch Size:   256)\n    Iter  9873\t      0.04152028 (Batch Size:   256)\n    Iter  9874\t      0.04514350 (Batch Size:   256)\n    Iter  9875\t      0.04188858 (Batch Size:   256)\n    Iter  9876\t      0.04192418 (Batch Size:   256)\n    Iter  9877\t      0.04251369 (Batch Size:   256)\n    Iter  9878\t      0.04313899 (Batch Size:   256)\n    Iter  9879\t      0.04901793 (Batch Size:   256)\n    Iter  9880\t      0.04627387 (Batch Size:   256)\n    Iter  9881\t      0.04296372 (Batch Size:   256)\n    Iter  9882\t      0.04731876 (Batch Size:   256)\n    Iter  9883\t      0.04879074 (Batch Size:   256)\n    Iter  9884\t      0.04731578 (Batch Size:   256)\n    Iter  9885\t      0.04873699 (Batch Size:   256)\n    Iter  9886\t      0.04498227 (Batch Size:   256)\n    Iter  9887\t      0.04427699 (Batch Size:   256)\n    Iter  9888\t      0.04383902 (Batch Size:   256)\n    Iter  9889\t      0.04966904 (Batch Size:   256)\n    Iter  9890\t      0.04371366 (Batch Size:   256)\n    Iter  9891\t      0.04263215 (Batch Size:   256)\n    Iter  9892\t      0.04020164 (Batch Size:   256)\n    Iter  9893\t      0.04101579 (Batch Size:   256)\n    Iter  9894\t      0.04133661 (Batch Size:   256)\n    Iter  9895\t      0.04189187 (Batch Size:   256)\n    Iter  9896\t      0.04142431 (Batch Size:   256)\n    Iter  9897\t      0.03866428 (Batch Size:   256)\n    Iter  9898\t      0.04207365 (Batch Size:   256)\n    Iter  9899\t      0.06050125 (Batch Size:   256)\n    Iter  9900\t      0.06093216 (Batch Size:   256)\n    Iter  9901\t      0.04466678 (Batch Size:   256)\n    Iter  9902\t      0.04442178 (Batch Size:   256)\n    Iter  9903\t      0.04554026 (Batch Size:   256)\n    Iter  9904\t      0.04773222 (Batch Size:   256)\n    Iter  9905\t      0.04391508 (Batch Size:   256)\n    Iter  9906\t      0.04247820 (Batch Size:   256)\n    Iter  9907\t      0.04573327 (Batch Size:   256)\n    Iter  9908\t      0.04731015 (Batch Size:   256)\n    Iter  9909\t      0.04272755 (Batch Size:   256)\n    Iter  9910\t      0.04336553 (Batch Size:   256)\n    Iter  9911\t      0.04159587 (Batch Size:   256)\n    Iter  9912\t      0.04321066 (Batch Size:   256)\n    Iter  9913\t      0.04272690 (Batch Size:   256)\n    Iter  9914\t      0.04186957 (Batch Size:   256)\n    Iter  9915\t      0.04328779 (Batch Size:   256)\n    Iter  9916\t      0.04295222 (Batch Size:   256)\n    Iter  9917\t      0.05192812 (Batch Size:   256)\n    Iter  9918\t      0.05536666 (Batch Size:   256)\n    Iter  9919\t      0.04613547 (Batch Size:   256)\n    Iter  9920\t      0.04780957 (Batch Size:   256)\n    Iter  9921\t      0.04883890 (Batch Size:   256)\n    Iter  9922\t      0.04384290 (Batch Size:   256)\n    Iter  9923\t      0.04214305 (Batch Size:   256)\n    Iter  9924\t      0.04142415 (Batch Size:   256)\n    Iter  9925\t      0.04089795 (Batch Size:   256)\n    Iter  9926\t      0.04209267 (Batch Size:   256)\n    Iter  9927\t      0.04573808 (Batch Size:   256)\n    Iter  9928\t      0.04143169 (Batch Size:   256)\n    Iter  9929\t      0.03994042 (Batch Size:   256)\n    Iter  9930\t      0.04231915 (Batch Size:   256)\n    Iter  9931\t      0.04357351 (Batch Size:   256)\n    Iter  9932\t      0.04690335 (Batch Size:   256)\n    Iter  9933\t      0.04419545 (Batch Size:   256)\n    Iter  9934\t      0.04349650 (Batch Size:   256)\n    Iter  9935\t      0.04796362 (Batch Size:   256)\n    Iter  9936\t      0.04116159 (Batch Size:   256)\n    Iter  9937\t      0.04170748 (Batch Size:   256)\n    Iter  9938\t      0.04126883 (Batch Size:   256)\n    Iter  9939\t      0.04626474 (Batch Size:   256)\n    Iter  9940\t      0.04940195 (Batch Size:   256)\n    Iter  9941\t      0.04205599 (Batch Size:   256)\n    Iter  9942\t      0.04595967 (Batch Size:   256)\n    Iter  9943\t      0.04386583 (Batch Size:   256)\n    Iter  9944\t      0.07128582 (Batch Size:   256)\n    Iter  9945\t      0.06453925 (Batch Size:   256)\n    Iter  9946\t      0.05621295 (Batch Size:   256)\n    Iter  9947\t      0.04888391 (Batch Size:   256)\n    Iter  9948\t      0.04149845 (Batch Size:   256)\n    Iter  9949\t      0.04792886 (Batch Size:   256)\n    Iter  9950\t      0.04714898 (Batch Size:   256)\n    Iter  9951\t      0.04101859 (Batch Size:   256)\n    Iter  9952\t      0.04341019 (Batch Size:   256)\n    Iter  9953\t      0.03958018 (Batch Size:   256)\n    Iter  9954\t      0.04607076 (Batch Size:   256)\n    Iter  9955\t      0.04411889 (Batch Size:   256)\n    Iter  9956\t      0.05694168 (Batch Size:   256)\n    Iter  9957\t      0.04691840 (Batch Size:   256)\n    Iter  9958\t      0.04337005 (Batch Size:   256)\n    Iter  9959\t      0.04655713 (Batch Size:   256)\n    Iter  9960\t      0.04040685 (Batch Size:   256)\n    Iter  9961\t      0.04342388 (Batch Size:   256)\n    Iter  9962\t      0.04497067 (Batch Size:   256)\n    Iter  9963\t      0.03927383 (Batch Size:   256)\n    Iter  9964\t      0.04536619 (Batch Size:   256)\n    Iter  9965\t      0.04295304 (Batch Size:   256)\n    Iter  9966\t      0.04052563 (Batch Size:   256)\n    Iter  9967\t      0.04612107 (Batch Size:   256)\n    Iter  9968\t      0.04702105 (Batch Size:   256)\n    Iter  9969\t      0.04066495 (Batch Size:   256)\n    Iter  9970\t      0.04219941 (Batch Size:   256)\n    Iter  9971\t      0.04109789 (Batch Size:   256)\n    Iter  9972\t      0.04239897 (Batch Size:   256)\n    Iter  9973\t      0.04626958 (Batch Size:   256)\n    Iter  9974\t      0.04763990 (Batch Size:   256)\n    Iter  9975\t      0.04253466 (Batch Size:   256)\n    Iter  9976\t      0.04091315 (Batch Size:   256)\n    Iter  9977\t      0.04614333 (Batch Size:   256)\n    Iter  9978\t      0.04708651 (Batch Size:   256)\n    Iter  9979\t      0.04699353 (Batch Size:   256)\n    Iter  9980\t      0.04411318 (Batch Size:   256)\n    Iter  9981\t      0.04088416 (Batch Size:   256)\n    Iter  9982\t      0.05443257 (Batch Size:   256)\n    Iter  9983\t      0.05921235 (Batch Size:   256)\n    Iter  9984\t      0.06534691 (Batch Size:   256)\n    Iter  9985\t      0.05112651 (Batch Size:   256)\n    Iter  9986\t      0.04735766 (Batch Size:   256)\n    Iter  9987\t      0.04665317 (Batch Size:   256)\n    Iter  9988\t      0.04738860 (Batch Size:   256)\n    Iter  9989\t      0.04729159 (Batch Size:   256)\n    Iter  9990\t      0.04789713 (Batch Size:   256)\n    Iter  9991\t      0.04496284 (Batch Size:   256)\n    Iter  9992\t      0.04116539 (Batch Size:   256)\n    Iter  9993\t      0.03881412 (Batch Size:   256)\n    Iter  9994\t      0.04875774 (Batch Size:   256)\n    Iter  9995\t      0.04689811 (Batch Size:   256)\n    Iter  9996\t      0.04585335 (Batch Size:   256)\n    Iter  9997\t      0.04376603 (Batch Size:   256)\n    Iter  9998\t      0.04423846 (Batch Size:   256)\n    Iter  9999\t      0.04284925 (Batch Size:   256)\n    Iter 10000\t      0.04124312 (Batch Size:   256)\n\n\n\n```python\nplt.plot(date_idx, adj_close_price)\nplt.plot(date_idx, pricePredict, c='#5aa9ab')\nplt.plot(date_idx, pricePredict2, c='#8B008B')\nplt.show()\n```\n\n\n```python\npricePredict3 = mlpr2.predict(date_idx[-holdDays:])\nprint((pricePredict3-date_idx[-holdDays:])/date_idx[-holdDays:]*100)\n```\n\n    [[-99.89699759]\n     [-99.89692712]\n     [-99.89685796]\n     [-99.89679009]\n     [-99.89672359]]\n\n", "meta": {"hexsha": "8c659d537afc0f7cef8f6ef1f232afe67eb8f4ff", "size": 690502, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "yahoopipeline.ipynb", "max_stars_repo_name": "arminsalmasi/DNN_regression_yahoo_finance_pipeline", "max_stars_repo_head_hexsha": "0cffa4eb2b109c7af976533633a2089df04bcb0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "yahoopipeline.ipynb", "max_issues_repo_name": "arminsalmasi/DNN_regression_yahoo_finance_pipeline", "max_issues_repo_head_hexsha": "0cffa4eb2b109c7af976533633a2089df04bcb0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "yahoopipeline.ipynb", "max_forks_repo_name": "arminsalmasi/DNN_regression_yahoo_finance_pipeline", "max_forks_repo_head_hexsha": "0cffa4eb2b109c7af976533633a2089df04bcb0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.69311785, "max_line_length": 21324, "alphanum_fraction": 0.5511816041, "converted": true, "num_tokens": 215739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20946968133032526, "lm_q2_score": 0.04813676889764673, "lm_q1q2_score": 0.010083193641261572}}
{"text": "```\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n\n\n\n```\ncurrent_path = '/content/drive/My Drive/Colab Notebooks/Project_GANder/gankook_cuda/semantic-segmentation-pytorch/pytorch_room_layout/'\n\nimport os\nos.chdir(current_path)\n!ls\n```\n\n    build\t\t      features\t\t     segment_lsun.py\n    cv2_requirements.txt  info.json\t\t     segment_rl.py\n    datasets\t      lsun.pth.tar\t     segment_st.py\n    data_transforms.py    lu_vp_detect.egg-info  sunrgbd.pth.tar\n    dist\t\t      pics\t\t     test_result\n    drn_d_105_024_val     __pycache__\t     Vanish_Point_Detection\n    drn_d_105_024_val_ms  README.md\t\t     visualize.m\n    drn.py\t\t      requirements.txt\t     XiaohuLuVPDetection\n\n\n### Get Vanishing point, inliers\n\n\n```\n# !python XiaohuLuVPDetection/setup.py build\n# !python XiaohuLuVPDetection/setup.py install\n!pip install -r cv2_requirements.txt\n```\n\n    Collecting opencv-python==4.0.0.21\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/37/49/874d119948a5a084a7ebe98308214098ef3471d76ab74200f9800efeef15/opencv_python-4.0.0.21-cp36-cp36m-manylinux1_x86_64.whl (25.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 25.4MB 1.4MB/s \n    \u001b[?25hCollecting opencv-contrib-python==4.0.0.21\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1f/c0/0463d91f297521b2e15e3d682d7077557fe773db72a03a0d2dba899ab8a5/opencv_contrib_python-4.0.0.21-cp36-cp36m-manylinux1_x86_64.whl (31.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 31.2MB 195kB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.11.3 in /usr/local/lib/python3.6/dist-packages (from opencv-python==4.0.0.21->-r cv2_requirements.txt (line 1)) (1.18.5)\n    \u001b[31mERROR: albumentations 0.1.12 has requirement imgaug<0.2.7,>=0.2.5, but you'll have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Installing collected packages: opencv-python, opencv-contrib-python\n      Found existing installation: opencv-python 4.1.2.30\n        Uninstalling opencv-python-4.1.2.30:\n          Successfully uninstalled opencv-python-4.1.2.30\n      Found existing installation: opencv-contrib-python 4.1.2.30\n        Uninstalling opencv-contrib-python-4.1.2.30:\n          Successfully uninstalled opencv-contrib-python-4.1.2.30\n    Successfully installed opencv-contrib-python-4.0.0.21 opencv-python-4.0.0.21\n\n\n\n```\nimport cv2\ncv2.__version__\n```\n\n\n\n\n    '4.0.0'\n\n\n\n### pytorch.room.layout\n\n\n```\n# !pip install -r requirements.txt\n# !apt install octave\n```\n\n\n```\n# import torch\n# torch.__version__\n```\n\n\n```\n# !python segment_rl.py train -d datasets/lsun/ -c 4 -s 480 --arch drn_d_105 --batch-size 32 --random-scale 1.75 --random-rotate 15 --epochs 100 --lr 0.01 --momentum 0.9 --lr-mode poly --pretrained sunrgbd.pth.tar\n```\n\n\n```\n# !python segment_st.py test -d datasets/sunrgbd/ -c 37 --arch drn_d_105 -s 480 --resume sunrgbd.pth.tar --phase val --batch-size 1 --ms\n```\n\n\n```\n# !python segment_lsun.py test -d ../mask_data/wall/ -o ../mask_layout_data/wall/ -c 4 --arch drn_d_105 -s 320 --resume lsun.pth.tar --phase test --batch-size 1 --ms\n```\n\n### Functions\n\n\n```\n#             Detect Intersection             #\nimport math\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler\nfrom sklearn.cluster import KMeans\nfrom sympy import Line\nfrom sympy.geometry import Ray\n\n\ndef drawLines(img, lines, color=(255,255,255)):\n    \"\"\"\n    Draw lines on an image\n    \"\"\"\n    for line in lines:\n        for rho,theta in line:\n          a = np.cos(theta)\n          b = np.sin(theta)\n          x0 = a*rho\n          y0 = b*rho\n          x1 = int(x0 + 1000*(-b))\n          y1 = int(y0 + 1000*(a))\n          x2 = int(x0 - 1000*(-b))\n          y2 = int(y0 - 1000*(a))\n\n          slope = (y1 - y0) / float(x1 - x0)\n          angle = math.degrees(math.atan(slope))\n          # if abs(angle) < 70:\n          cv2.line(img, (x1,y1), (x2,y2), color, 1)\n\ndef line(p1, p2):\n    A = (p1[1] - p2[1])\n    B = (p2[0] - p1[0])\n    C = (p1[0]*p2[1] - p2[0]*p1[1])\n    return A, B, -C\n\ndef intersection2(L1, L2):\n    D  = L1[0] * L2[1] - L1[1] * L2[0]\n    Dx = L1[2] * L2[1] - L1[1] * L2[2]\n    Dy = L1[0] * L2[2] - L1[2] * L2[0]\n    if D != 0:\n        x = Dx / D\n        y = Dy / D\n        return x,y\n    else:\n        return False\n\n\ndef regression(img, x, y, color=(0, 0, 0), axis=1):\n\n  if axis == 1:\n    y_at_border = np.array([0, img.shape[0]])\n    p = np.polyfit(y, x, deg=1)\n    x_at_border = np.poly1d(p)(y_at_border)\n  else:\n    x_at_border = np.array([0, img.shape[1]])\n    p = np.polyfit(x, y, deg=1)\n    y_at_border = np.poly1d(p)(x_at_border)\n\n  cv2.line(img, (int(x_at_border[0]), int(y_at_border[0])), (int(x_at_border[1]), int(y_at_border[1])), color, 2)\n\n  return x_at_border, y_at_border\n\n\ndef find_reg_points(img, lines, color=(255,0,0), drawlines=False):\n\n  centroids = list()\n  r_xs = list()\n  r_ys = list()\n  for line_ in lines:\n      for rho,theta in line_:\n          a = np.cos(theta)\n          b = np.sin(theta)\n          x0 = a*rho\n          y0 = b*rho\n          x1 = int(x0 + 1000*(-b))\n          y1 = int(y0 + 1000*(a))\n          x2 = int(x0 - 1000*(-b))\n          y2 = int(y0 - 1000*(a))\n\n          slope = (y1 - y0) / float(x1 - x0)\n          angle = math.degrees(math.atan(slope))\n          if abs(angle) > 80:\n            # print(img.shape[1])\n            h_layout = line((0, 0), (img.shape[1], 0))\n            h_layout_lower = line((0, img.shape[0]), (img.shape[1], img.shape[0]))\n            r = intersection2(h_layout, line((x1, y1), (x2, y2)))\n            r_lower = intersection2(h_layout_lower, line((x1, y1), (x2, y2)))\n            # cv2.line(img, (int(x1), int(y1)), (int(x2), int(y2)), color, 2)\n\n            center_p = (int((r[0] + r_lower[0]) / 2), int((r[1] + r_lower[1])/ 2))\n            centroids.append(center_p)\n\n            r_xs.append((r[0], r_lower[0]))\n            r_ys.append((r[1], r_lower[1]))\n\n            if drawlines:\n              cv2.line(img, (int(r[0]), int(r[1])), (int(r_lower[0]), int(r_lower[1])), color, 2)\n              cv2.circle(img, center_p, 10, (255, 0, 255), -1)\n\n  if drawlines:\n    cv2.line(img, (int(0), int(0)), (int(0), int(img.shape[0])), color, 2)\n    cv2.line(img, (int(img.shape[1]), int(0)), (int(img.shape[1]), int(img.shape[0])), color, 2)\n    cv2.circle(img, (0, int(img.shape[0] / 2)), 10, (255, 0, 255), -1)\n    cv2.circle(img, (img.shape[1], int(img.shape[0] / 2)), 10, (255, 0, 255), -1)\n  centroids.append((0, int(img.shape[0] / 2)))\n  centroids.append((img.shape[1], int(img.shape[0] / 2)))\n\n  return r_xs, r_ys, centroids   \n\nfrom scipy.spatial import distance as sci_dist\n\ndef order_points(pts):\n\n  xSorted = pts[np.argsort(pts[:, 0]), :]\n  leftMost = xSorted[:2, :]\n  rightMost = xSorted[2:, :]\n  leftMost = leftMost[np.argsort(leftMost[:, 1]), :]\n  (tl, bl) = leftMost\n  D = sci_dist.cdist(tl[np.newaxis], rightMost, \"euclidean\")[0]\n  (br, tr) = rightMost[np.argsort(D)[::-1], :]\n\n  return np.array([tl, tr, br, bl], dtype=\"float32\")\n\n\n```\n\n\n```\nfrom PIL import Image\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom XiaohuLuVPDetection.lu_vp_detect.vp_detection import VPDetection\nimport time\n# import os\nimport cv2\n# import pylab as pl\nfrom skimage import morphology as mp\nimport sys\nfrom Vanish_Point_Detection import wrapper\n\n\nlength_thresh = 50\nprincipal_point = None\nfocal_length = 1300 # 1102.79\nseed = 1300\nvpd = VPDetection(length_thresh, principal_point, focal_length, seed)\n\norg_path = 'datasets/lsun/images/' # -> original image\nlayout_path = 'drn_d_105_024_val_ms/images/' # -> layout image (result image frome above model file)\nrefer_path = '../refer_data/wall/myxkehu1kfzggursepnk0tfiyps8zbs5umvzv8d92r6hhxejgawebwsufssgov5q-.jpg'\n\nobject_ = 'wall'\nmask_path = '../mask_data/' + object_ + '/'\n# layout_path = '../test_layout_result/' + object_ + '/'\nlayout_path = '../mask_layout_data/' + object_ + '/'\n# refer_path = './refer_data/' + object_ + '/'\n\nval_image_list = os.listdir(layout_path)\n\none_iter = False\nstart_index = 0\nfor image_index, image in enumerate(val_image_list):\n\n  if image_index < start_index:\n    continue\n  image = '720x480_20200131153356598_gnIdiy35s8.png'\n  print('image_index :', val_image_list.index(image))\n  one_iter = True\n\n  # print(image)\n  img = Image.open(layout_path + image)\n  # print(type(img))\n  img_np = np.invert(np.asarray(img))\n  # print(img_np.max(), img_np.min())\n  ret, thr = cv2.threshold(img_np, 254, 255, cv2.THRESH_BINARY_INV)\n\n  org = Image.open(mask_path + image)\n  org_color_np, org_np = np.split(np.asarray(org), 2, axis=1)\n  # org_np = np.asarray(org)\n  # gray = cv2.cvtColor(org_np, cv2.COLOR_RGB2GRAY)\n  # print(org_np.shape)\n  # ret, thr = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)\n\n\n  print(image)\n  # plt.subplot(131)\n  # plt.imshow(org)\n  # plt.show()\n  img_size = (org_np.shape[1], org_np.shape[0])\n  \n  scale_factor = 6\n  print('scale_factor :', scale_factor)\n\n  refer = Image.open(refer_path)\n  refer = np.asarray(refer)\n\n  #     refer_size\uc640 img_size\uac00 \ub3d9\uc77c\ud558\uac70\ub098 refer_size\uac00 \uc791\uc740 \uacbd\uc6b0\ub97c \uace0\ub824\ud574\uc57c\ud55c\ub2e4.     #\n  refer = np.tile(refer, (scale_factor, scale_factor, 1))\n  size_ratio = math.floor(min((refer.shape[0] / (org_np.shape[0] * 1.5)), (refer.shape[1] / (org_np.shape[1] * 1.5))))\n  refer = Image.fromarray(refer).resize((int(refer.shape[1] / size_ratio), int(refer.shape[0] / size_ratio)))\n\n  tun = thr\n  skl = mp.medial_axis(tun).astype(np.uint8) * 255\n  rho = 1\n  theta = np.pi/180\n  thresh = 50\n  # print(skl.shape, skl.dtype)\n\n  # lines = cv2.HoughLines(org_np.astype(np.uint8), rho, theta, thresh)\n  lines = cv2.HoughLines(skl, rho, theta, thresh)\n\n  # print(lines)\n  # plt.imshow(skl)\n  # plt.show()\n\n  # Draw all Hough lines in red\n  # img_with_all_lines = np.copy(skl)\n  # img_with_all_lines = cv2.cvtColor(img_with_all_lines, cv2.COLOR_GRAY2RGB)\n  # plt.imshow(img_with_all_lines)\n  # plt.show()\n  org_color_np2 = org_color_np.copy()\n  org_np = org_np.astype(np.uint8)\n  org_np2 = org_np.copy()\n  org_np3 = org_np.copy()\n\n  start = time.time()\n\n  r_x_list, r_y_list, centroids_list = find_reg_points(org_np, lines,)\n  # drawLines(img_with_all_lines, lines)\n\n  #     Edit Your Mask     #\n  kernel = np.ones((10, 10), np.uint8)\n  \n  # plt.figure(figsize=(20, 15))\n  # for plot_i in range(5):\n  #   plt.subplot(1, 5, plot_i+1)\n  #   if plot_i == 0:\n  #     plt.imshow(org_np2)\n  #   elif plot_i == 1: #      Dilation     #\n  #     plt.imshow(cv2.dilate(org_np2, kernel, iterations=1))\n  #   elif plot_i == 2: #      Closing      #\n  #     plt.imshow(cv2.morphologyEx(org_np2, cv2.MORPH_CLOSE, kernel))\n  #   elif plot_i == 3: #     Erode     #\n  #     plt.imshow(cv2.erode(org_np2, kernel, iterations=1))\n  #   elif plot_i == 4: #     Opening   #\n  #     plt.imshow(cv2.morphologyEx(org_np2, cv2.MORPH_OPEN, kernel))\n  # plt.show()\n\n  org_np2_morp = cv2.morphologyEx(org_np2, cv2.MORPH_CLOSE, kernel)\n  org_np2_copy = org_np2_morp.copy()\n  org_np2_copy_gray = cv2.cvtColor(org_np2_copy, cv2.COLOR_RGB2GRAY)\n\n  vpd.find_vps(org_np2_morp)\n  vps = vpd.vps_2D\n  vl_org_img, vl_list = vpd.create_debug_VP_image()\n\n  vpd.find_vps(org_color_np)\n  vps = vpd.vps_2D\n  vl_color_img, _ = vpd.create_debug_VP_image()\n\n  edge_org_np2 = cv2.Canny(org_np2_morp, 30, 300)\n  edge_org_np2_copy = edge_org_np2.copy()\n  edge_org_np2_copy2 = cv2.Canny((org_np2_copy / 255. * org_np2_copy).astype(np.uint8), 30, 300)\n\n  vpd.find_vps(edge_org_np2)\n  # vps = vpd.vps_2D\n  edge_vl_img, vl_list = vpd.create_debug_VP_image()\n\n  #             Hough Lines Detection           #\n  # print('org_np2.dtype :', org_np2.dtype)\n  # print('org_np2.shape :', org_np2.shape)\n  # plt.imshow(org_np2_copy_gray)\n  # plt.show()\n  # lines = cv2.HoughLines(org_np2_copy_gray, rho, theta, thresh)\n  # drawLines(org_np2_copy_gray, lines)\n  # plt.imshow(edge_org_np2_copy)\n  # plt.show()\n  edge_lines = cv2.HoughLines(edge_org_np2_copy, rho, theta, thresh)\n  drawLines(edge_org_np2_copy, edge_lines)\n  # plt.imshow(edge_org_np2_copy2)\n  # plt.show()\n  edge_lines2 = cv2.HoughLines(edge_org_np2_copy2, rho, theta, thresh)\n  drawLines(edge_org_np2_copy2, edge_lines2)\n  # vl_color_img, vps, vpssum = wrapper.dealAImage(org_color_np, True, True, True, True, Ostandard=True)\n\n  # print(vps)\n  # print('vps :', vps)\n  # right_vp = vps[0]\n  # color = (255, 0, 255)\n  # cv2.circle(vl_color_img, (int(right_vp[0]), int(right_vp[1])), 50, (255, 0, 255), -1)\n  # # cv2.line(vl_org_img, (0, 0), (int(right_vp[0]), int(right_vp[1])), color, 5)\n  # # cv2.line(vl_org_img, (0, vl_org_img.shape[0]), (int(right_vp[0]), int(right_vp[1])), color, 5)\n  # left_vp = vps[1]\n  # color = (255, 0, 0)\n  # cv2.circle(vl_color_img, (int(left_vp[0]), int(left_vp[1])), 50, (255, 0, 255), -1)\n  # # cv2.line(vl_org_img, (vl_org_img.shape[1], 0), (int(left_vp[0]), int(left_vp[1])), color, 5)\n  # # cv2.line(vl_org_img, (vl_org_img.shape[1], vl_org_img.shape[0]), (int(left_vp[0]), int(left_vp[1])), color, 5)\n  \n  plt.figure(figsize=(15, 10))\n  plt.subplot(141)\n  plt.imshow(vl_org_img)\n  plt.title('vl_org_img')\n\n  plt.subplot(142)\n  # plt.imshow(org_color_np)\n  plt.imshow(vl_color_img)\n\n  plt.subplot(143)\n  plt.imshow(edge_org_np2_copy)\n\n  plt.subplot(144)\n  plt.imshow(edge_org_np2_copy2)\n  plt.show()\n\n  centroids_data = np.array(centroids_list)[:, [0]]\n  print('len(r_x_list), len(r_y_list) :', len(r_x_list), len(r_y_list))\n  print('centroids_data.shape :', centroids_data.shape)\n  mms = MinMaxScaler()\n  cen_data =mms.fit_transform(centroids_data)\n  # print('cen_data :', cen_data)\n  K = range(2, 6)\n  s_dist = list()\n  for k in K:\n    if cen_data.shape[0] < k:\n      break\n    km = KMeans(n_clusters=k)\n    km = km.fit(cen_data)\n    inertia = km.inertia_\n    s_dist.append(inertia)\n    \n    # if inertia <= 0:\n    #   print('vertical line number =', k)\n    #   break\n  mms2 = MinMaxScaler()\n  mms_s_dist = mms2.fit_transform(np.array(s_dist).reshape(-1, 1))\n  k_thresh = 0.1\n  # plt.plot(range(len(mms_s_dist)), mms_s_dist)\n  # plt.show()\n\n  if cen_data.shape[0] > 2:\n    for i in range(len(mms_s_dist)):\n      if mms_s_dist[i] < k_thresh:\n        k = i + 2\n        break\n  else:\n    k = 2\n\n  #     k Confirmation : Comparing k.cluster_centers_ dist  #\n  while True:    \n\n    km = KMeans(n_clusters=k)\n    km = km.fit(cen_data)\n    if k <= 2:\n      break\n\n    cluster_centroids = km.cluster_centers_\n    # print('cluster_centroids :', cluster_centroids)\n    error_exist = False\n    for i in range(len(cluster_centroids) - 1):\n      for j in range(i + 1, len(cluster_centroids)):\n        if abs(cluster_centroids[i] - cluster_centroids[j]) < 0.05:\n          error_exist = True\n    if error_exist:\n      k -= 1\n    else:\n      break\n\n  print('k is', k)\n\n  predict_cen = km.predict(cen_data)\n  print(predict_cen)\n\n  keys = list(range(k))\n  for rm in predict_cen[-2:]:\n    keys.remove(rm)\n  print('keys :', keys)\n\n  skl_rgb = cv2.cvtColor(skl, cv2.COLOR_GRAY2RGB)\n  skl_copy = np.copy(skl_rgb)\n\n  # black_plane = np.zeros(skl_rgb.shape).astype(np.uint8)\n  black_plane2 = np.zeros(skl_rgb.shape).astype(np.uint8)\n\n  \n  reg_xs = list()\n  reg_ys = list()\n  for key in keys:\n    temp_rx = tuple()\n    temp_ry = tuple()\n    for pred_key, r_x, r_y in zip(predict_cen[:-2], r_x_list, r_y_list):\n      if key == pred_key:\n        temp_rx += r_x\n        temp_ry += r_y\n\n    #       Regression Multiple Lines     #\n    border_x, border_y = regression(org_np3, temp_rx, temp_ry)\n    # regression(black_plane, temp_rx, temp_ry)\n    # print(border_x, border_y)\n\n    reg_xs.append(border_x)\n    reg_ys.append(border_y)\n\n  print('reg_xs :', reg_xs)\n  \n  \n  center_xs = list()\n  for reg_x in reg_xs:\n    #     all_closest_inter\uac00 \uc815\ub82c\ub418\uc9c0 \uc54a\uc558\ub2e4\uba74 inters type = list()      #\n    # sum_x = 0\n    # for inter in inters:\n    #   sum_x += inter[0] + inter[2]\n    center_xs.append(np.mean(reg_x))\n  sorted_center_xs = sorted(center_xs)\n\n  sorted_index = list()\n  for center_x in sorted_center_xs:\n    # print('center_x :', center_x)\n    sorted_index.append(center_xs.index(center_x))\n  print('sorted_index :', sorted_index)\n  #       sorted_center_xs \uc21c\uc11c\ub85c all_closest_inter\ub97c \uc815\ub82c\ud55c\ub2e4.     #\n  #       index list\ub97c \ucd94\ucd9c\ud574\uc11c for \ubb38\uc73c\ub85c all_closest_inter\uc758 inters\ub97c \ucd94\ucd9c\ud574\n  #       sorted_all ... \uc5d0 append \uc2dc\ud0a8\ub2e4.      #\n\n  sorted_reg_xs = list()\n  sorted_reg_ys = list()\n  for s_index in sorted_index:\n    sorted_reg_xs.append(reg_xs[s_index])\n    sorted_reg_ys.append(reg_ys[s_index])\n  reg_xs = sorted_reg_xs\n  reg_ys = sorted_reg_ys\n\n  print('reg_xs :', reg_xs)\n\n  #           VL Segmentation             #\n  # Angle between line1 and x-axis\n  # print(len(vl_list))\n\n  # print('len(v_lines) :', len(v_lines))\n  # print('len(h_lines) :', len(h_lines))\n  \n  #         Extend v_lines and draw h_lines       #\n  h_border = line((0, 0), (skl_copy.shape[1], 0))\n  h_border_lower = line((0, skl_copy.shape[0]), (skl_copy.shape[1], skl_copy.shape[0]))\n\n  #     vline \uc774 \uc874\uc7ac\ud558\uc9c0 \uc54a\ub294 \uacbd\uc6b0\ub3c4 \uace0\ub824\ud574\uc57c\ud55c\ub2e4.     #\n  if len(reg_xs) == 0:\n    reg_xs.append([0, 0])\n    reg_ys.append([0, org_np2.shape[0]])\n    \n  #         Divide Session by vline       #\n  for reg_index, (reg_x, reg_y) in enumerate(zip(reg_xs, reg_ys)):\n\n\n    #     In a Session     #\n    #     1.  find vanishing point    #\n    #     2.  Find 3 points (vp, top & bottom points)     #\n    #     3.  Do warfine and attach to the black plane      #\n\n    print('reg_index, reg_x, reg_y :', reg_index, reg_x, reg_y)\n    \n    #     0.  crop by vline     #\n          #   Find Max_x, min_x, (Max_y, min_y = org.shape[0], 0)\n          #   1.    \uc6b0\ud3b8\uc5d0 \ud55c\ud574\uc11c max_x = \uc6b0\ud3b8 vline max_x & min_x = \ud604\uc7ac vline min_x\n          #   2.    \uc88c\ud3b8\uc5d0 \ud55c\ud574\uc11c max_x = \ud604\uc7ac Max_x & min_x = \uc88c\ud3b8 vline min_x\n\n    #      vline \ubcc4\ub85c \uc591\uc606\uc73c\ub85c \uc791\uc5c5\uc744 \ud558\uba74 len(vline) = 1\uc758 \uc791\uc5c5\uc744 \ubc18\ubcf5\ud560 \ud544\uc694\uac00 \uc5c6\uc5b4\uc9c4\ub2e4.    #\n    iter = False\n    while True:\n\n      #                   We need Max, min x & y                #\n      # four_inters = list()\n      find_pair = True\n      # centroid_inters = all_centroid_inters[inters_i]\n\n      if not iter:\n        #       vline \uc6b0\uce21 session      #\n        # print(final_xs)\n        # four_inters.append([final_xs[0], final_ys[0]])\n        # four_inters.append(centroid_inters[0])\n        # print(four_inters)\n\n        #       \uc624\ub978\ucabd \ub05d vline \uc774\uba74        #\n        if reg_index == len(reg_xs) - 1:\n          print('reg_index = len(reg_xs) - 1')\n          #   1.    \uc6b0\ud3b8\uc5d0 \ud55c\ud574\uc11c max_x = \uc6b0\ud3b8 vline max_x & min_x = \ud604\uc7ac vline min_x\n          max_x = org_np.shape[1]\n          min_x = np.min(reg_x)\n\n        else:\n          print('middle vline')\n          next_reg_x = reg_xs[reg_index + 1]\n          max_x = np.max(next_reg_x)\n          min_x = np.min(reg_x)\n\n      #     i = 0 \uc5d0 \ud55c\ud574\uc11c\ub9cc \uc67c\ucabd\uc73c\ub85c\ub3c4 refering \uc9c4\ud589, \ub098\uba38\uc9c0\ub294 \uc624\ub978\ucabd\uc73c\ub85c\ub9cc     #\n      else:\n          #   2.    \uc88c\ud3b8\uc5d0 \ud55c\ud574\uc11c max_x = \ud604\uc7ac Max_x & min_x = \uc88c\ud3b8 vline min_x\n          max_x = np.max(reg_x)\n          min_x = 0\n\n      print('max_x, min_x :', max_x, min_x)\n      # max_y = org_np.shape[0]\n      # min_y = 0\n\n      #     Make Session      #\n      session = org_np2[:, int(min_x):int(max_x)]\n\n      vpd.find_vps(session)\n      # vps = vpd.vps_2D\n      vl_img, vl_list = vpd.create_debug_VP_image(show_vl=True)\n\n\n      #       Closing Morphing by OpenCV      #\n      kernel = np.ones((10, 10), np.uint8)\n      session = cv2.morphologyEx(session, cv2.MORPH_CLOSE, kernel)\n\n      vpd.find_vps(session)\n      # vps = vpd.vps_2D\n      vl_session_img, vl_session_list = vpd.create_debug_VP_image(show_vl=True)\n\n      #     Feed Binary inv Threshold     #      \n      # gray = cv2.cvtColor(session, cv2.COLOR_RGB2GRAY)\n      ret, thr_session = cv2.threshold(session, 127, 255, cv2.THRESH_BINARY)\n      thr_session = cv2.morphologyEx(thr_session, cv2.MORPH_CLOSE, kernel)\n      thr_session_copy = thr_session.copy()\n      vpd.find_vps(thr_session_copy)\n      # vps = vpd.vps_2D\n      vl_thresh_img, vl_thresh_list = vpd.create_debug_VP_image(show_vl=True)\n\n      plt.imshow(vl_thresh_img)\n      plt.title('vl_thresh_img')\n      plt.show()\n\n      #       Edge Session      #\n      #     Multiply mask map with Edge => Erase Unnecessary vl line    #\n      edge_session = cv2.Canny(session, 20, 60)\n\n      #     Before Canny    #\n      session_prob = session / 255.\n\n      #   multiply one time   #\n      session2 = session_prob * (session)\n      edge_session2 = cv2.Canny(session2.astype(np.uint8), 20, 60)\n\n      #       two time      #\n      # session2 = session_prob**2 * (session)\n      # edge_session2 = cv2.Canny(session2.astype(np.uint8), 20, 60)\n\n      vpd.find_vps(edge_session)\n      # vps = vpd.vps_2D      \n      vl_edge_img, vl_edge_list = vpd.create_debug_VP_image(show_vl=True)\n\n      vpd.find_vps(edge_session2)\n      # vps = vpd.vps_2D      \n      vl_edge_img2, vl_edge_list2 = vpd.create_debug_VP_image(show_vl=True)\n      \n\n      # session = wrapper.dealAImage(session,True,True,True)\n\n      # #             color             #\n      # session = org_color_np[:, int(min_x):int(max_x)]\n\n      #       Use made vl_img (get more vn_lines)     #\n      # session = vl_org_img[:, int(min_x):int(max_x)]\n\n      \n\n      plt.figure(figsize=(15, 10))\n      plt.subplot(161)\n      plt.imshow(vl_img)\n      plt.title('vl_session_img')\n\n      plt.subplot(162)\n      plt.imshow(vl_thresh_img)\n      plt.title('vl_thresh_img')\n\n      plt.subplot(163)\n      plt.imshow(vl_session_img)\n      plt.title('vl_session_img morphed')\n\n      plt.subplot(164)\n      plt.imshow(edge_session2)\n      plt.title('edge_session2')\n\n      plt.subplot(165)\n      plt.imshow(vl_edge_img)\n      plt.title('vl_edge_img')\n\n      plt.subplot(166)\n      plt.imshow(vl_edge_img2)\n      plt.title('vl_edge_img2')     \n      # plt.imshow(vl_img)\n      # plt.title('vl_img')\n      plt.show()\n\n      v_lines = list()\n      h_lines = list()\n      # print('vps :', vps)\n\n      top_vl = list()\n      bottom_vl = list()\n\n      left_vl_list = list()\n      right_vl_list = list()\n\n      left_angle = list()\n      right_angle = list()\n\n      #         What is best vl_list      #\n      vl_list = vl_thresh_list\n\n      for vl in vl_list:\n        x0, y0, x1, y1 = vl\n        slope = (y1 - y0) / float(x1 - x0)\n        angle = math.degrees(math.atan(slope))\n        # print(angle)\n        # if abs(angle) > 80:\n        #   # cv2.line(skl_copy, (int(x1), int(y1)), (int(x0), int(y0)), (255, 0, 0), 3,\n        #   #                  cv2.LINE_AA)\n        #   v_lines.append(vl)\n\n        if abs(angle) < 70:\n          if (y0 + y1) / 2 < vl_img.shape[0] / 2:\n            # print(y0, y1)\n            top_vl.append(vl)\n            if angle < 0:\n              left_vl_list.append(vl)\n              left_angle.append(abs(angle))\n            else:\n              right_vl_list.append(vl)\n              right_angle.append(abs(angle))\n          else:\n            bottom_vl.append(vl)\n            if angle > 0:\n              left_vl_list.append(vl)\n              left_angle.append(abs(angle))\n            else:\n              right_vl_list.append(vl)\n              right_angle.append(abs(angle))\n          # cv2.line(skl_copy, (int(x1), int(y1)), (int(x0), int(y0)), (0, 0, 255), 2,\n          #                  cv2.LINE_AA)\n          h_lines.append(vl)\n        #   regression(vl_img, (x0, x1), (y0, y1), color=(0,255,255),axis=1)\n      print('#        Original vl list        #')\n      print('len(left_vl_list) :', len(left_vl_list))\n      print('len(right_vl_list) :', len(right_vl_list))\n      print()\n\n      #             Delete over standarded angle vl             #\n      if len(left_vl_list) != 0:\n        copy_left_vl_list = left_vl_list.copy()\n        copy_left_angle = left_angle.copy()\n        mean_left_angle = np.array(left_angle).mean()\n        print('mean_left_angle :', mean_left_angle)\n        print('left_angle :', left_angle)\n\n        for angle_index, angle in enumerate(copy_left_angle):\n          if abs(angle - mean_left_angle) > 20:\n            left_vl_list.remove(copy_left_vl_list[angle_index])\n            left_angle.remove(copy_left_angle[angle_index])\n        # standardScaler = StandardScaler()\n        # std_left_angle = standardScaler.fit_transform(np.array(left_angle).reshape(-1, 1))\n        # print('standardScaler.fit_transform(left_angle) :', std_left_angle)\n        # print('left_angle :', left_angle)        \n\n        # for std_index, std_angle in enumerate(std_left_angle):\n        #   if abs(std_angle) > 2:\n        #     left_vl_list.remove(copy_left_vl_list[std_index])\n            # left_angle.remove(copy_left_angle[std_index])\n\n        # print('left_angle :', left_angle)\n\n      if len(right_vl_list) != 0:\n        copy_right_vl_list = right_vl_list.copy()\n        copy_right_angle = right_angle.copy()\n        mean_right_angle = np.array(right_angle).mean()\n        print('mean_right_angle :', mean_right_angle)\n        print('right_angle :', right_angle)\n\n        for angle_index, angle in enumerate(copy_right_angle):\n          if abs(angle - mean_right_angle) > 20:\n            right_vl_list.remove(copy_right_vl_list[angle_index])\n            right_angle.remove(copy_right_angle[angle_index])\n\n      \n      # top_condition = False\n      # bot_condition = False\n      # for vl in left_vl_list:\n      #   if vl in top_vl:\n      #     top_condition = True\n      #   elif vl in bottom_vl:\n      #     bot_condition = True\n      # if top_condition and bot_condition:\n      #   pass\n      # else:\n      #   left_vl_list = list()\n      #   print('left top bot condition False')\n      #   print('top_condition :', top_condition)\n      #   print('bot_condition :', bot_condition)\n\n      # top_condition = False\n      # bot_condition = False\n      # for vl in right_vl_list:\n      #   # print('vl :', vl)\n      #   if vl in top_vl:\n      #     top_condition = True\n      #   elif vl in bottom_vl:\n      #     bot_condition = True\n      # if top_condition and bot_condition:\n      #   pass\n      # else:\n      #   right_vl_list = list()\n      #   print('right top bot condition False')\n      #   print('top_condition :', top_condition)\n      #   print('bot_condition :', bot_condition)\n      \n      # print('-- after --')\n      # print('len(left_vl_list) :', len(left_vl_list))\n      # print('len(right_vl_list) :', len(right_vl_list))\n      # print()\n\n      # for vl in vl_list:\n      #   x0, y0, x1, y1 = vl\n\n      #   # if right_gap < 30:\n      #   #   left_vl_list.append(vl)\n      #   #   print('right_angle :', angle)\n      #   if vl in left_vl_list:\n      #     regression(vl_img, (x0, x1), (y0, y1), color=(0,0,255),axis=1)\n      #   # elif left_gap < 30:\n      #   elif vl in right_vl_list:\n      #     # right_vl_list.append(vl)\n      #     # print('left_angle :', angle)\n      #     regression(vl_img, (x0, x1), (y0, y1), color=(255,0,0),axis=1)\n      if len(left_vl_list) == 0 and len(right_vl_list) == 0:\n          #     i != 0 \uc778 \uacbd\uc6b0 break     #\n        if reg_index == 0 and not iter:\n          iter = True\n          print('iter :', iter)\n          continue\n\n        else:\n          break\n        \n      \n      #                       Find External vn_line                     #\n      h_border_top = Line((0, 0), (vl_img.shape[1], 0))\n      h_border_bot = Line((0, vl_img.shape[0]), (vl_img.shape[1], vl_img.shape[0]))\n      top_down_ratio = 0.66\n      left_margin = 0.33\n      right_margin = 1 - left_margin\n\n      ex_left_top_vl = list()\n      ex_left_bot_vl = list()\n      ex_right_top_vl = list()\n      ex_right_bot_vl = list()\n\n      l2 = Line((0, 0), (0, vl_img.shape[0]))\n      l3 = Line((vl_img.shape[1], 0), (vl_img.shape[1], vl_img.shape[0]))\n\n      for vl in left_vl_list:\n        x0, y0, x1, y1 = vl\n        l1 = Line((x0, y0), (x1, y1))\n        #     v_border line     #\n        [left_point] = l1.intersection(l2)\n        # print('left_point :', left_point)\n        [right_point] = l1.intersection(l3)\n\n        top_bot_pass = False\n        try:\n          [top_point] = l1.intersection(h_border_top)\n          [bot_point] = l1.intersection(h_border_bot)\n        except:\n          top_bot_pass = True\n        # print('top_point :', int(top_point[0]), int(top_point[1]))\n        # print('bot_point :', int(bot_point[0]), int(bot_point[1]))\n\n        #      Figure out current vl is top / bottom vl     #\n        extend = False\n        if vl in top_vl:\n          #      line should have same height (y)     #\n          if (left_point[1] < vl_img.shape[0] * top_down_ratio and right_point[1] < vl_img.shape[0] * top_down_ratio):\n            #     h_border \uc640\uc758 \uad50\ucc28\uc810 \uc870\uac74    #\n            # if not top_bot_pass:\n            # if top_point[0] >= vl_img.shape[1] * right_margin and bot_point[0] <= vl_img.shape[1] * left_margin:\n              # extend = True\n              ex_left_top_vl.append((left_point[0], left_point[1], right_point[0], right_point[1]))\n\n        elif vl in bottom_vl:\n          # print('vl in bottom at left :', vl)\n          #      line should have same height (y)     #\n          if (left_point[1] > vl_img.shape[0] * (1 - top_down_ratio) and right_point[1] > vl_img.shape[0] * (1 - top_down_ratio)):\n            #     h_border \uc640\uc758 \uad50\ucc28\uc810 \uc870\uac74    #\n            # if not top_bot_pass:\n            # if top_point[0] <= vl_img.shape[1] * left_margin and bot_point[0] >= vl_img.shape[1] * right_margin:\n              # extend = True\n              ex_left_bot_vl.append((left_point[0], left_point[1], right_point[0], right_point[1]))\n          \n\n      for vl in right_vl_list:\n        x0, y0, x1, y1 = vl\n        l1 = Line((x0, y0), (x1, y1))\n        #     v_border line     #\n     \n        [left_point] = l1.intersection(l2)\n        # print('left_point :', left_point)\n        [right_point] = l1.intersection(l3)\n        \n        top_bot_pass = False\n        try:\n          [top_point] = l1.intersection(h_border_top)\n          [bot_point] = l1.intersection(h_border_bot)\n        except:\n          top_bot_pass = True\n        # print('top_point :', int(top_point[0]), int(top_point[1]))\n        # print('bot_point :', int(bot_point[0]), int(bot_point[1]))\n\n        #      Figure out current vl is top / bottom vl     #\n        extend = False\n        if vl in top_vl:\n          #      line should have same height (y)     #\n          if (left_point[1] < vl_img.shape[0] * top_down_ratio and right_point[1] < vl_img.shape[0] * top_down_ratio):\n            #     h_border \uc640\uc758 \uad50\ucc28\uc810 \uc870\uac74    #\n            # if top_point[0] <= vl_img.shape[1] * left_margin and bot_point[0] >= vl_img.shape[1] * right_margin:\n              # extend = True\n              ex_right_top_vl.append((left_point[0], left_point[1], right_point[0], right_point[1]))\n\n\n        elif vl in bottom_vl:\n          # print('vl in bottom at right :', vl)\n          #      line should have same height (y)     #\n          if left_point[1] > vl_img.shape[0] * (1 - top_down_ratio) and right_point[1] > vl_img.shape[0] * (1 - top_down_ratio):\n            #     h_border \uc640\uc758 \uad50\ucc28\uc810 \uc870\uac74    #\n            # if top_point[0] >= vl_img.shape[1] * right_margin and bot_point[0] <= vl_img.shape[1] * left_margin:\n              # extend = True          \n              ex_right_bot_vl.append((left_point[0], left_point[1], right_point[0], right_point[1]))\n\n        # if extend:\n        #   ex_right_vl.append((left_point[0], left_point[1], right_point[0], right_point[1]))\n        # print('ex_left_vl[-1] :', ex_left_vl[-1])\n\n      print()\n      print('#          Extended vl list left / right  TB Condition        #')\n      print('len(ex_left_top_vl) :', len(ex_left_top_vl))\n      print('len(ex_left_bot_vl) :', len(ex_left_bot_vl))\n      print('len(ex_right_top_vl) :', len(ex_right_top_vl))\n      print('len(ex_right_bot_vl) :', len(ex_right_bot_vl))\n      print()\n\n      #       find min max Line     #\n      max_y = 0\n      right_bottest_vl = None\n      min_y = vl_img.shape[0]\n      right_toppest_vl = None\n\n      for vl in ex_right_bot_vl:\n        if vl[1] > max_y:\n          right_bottest_vl = vl\n          max_y = vl[1]\n      \n      for vl in ex_right_top_vl:\n        if vl[1] < min_y:\n          right_toppest_vl = vl\n          min_y = vl[1]\n      \n      max_y = 0\n      left_bottest_vl = None\n      min_y = vl_img.shape[0]\n      left_toppest_vl = None\n\n      for vl in ex_left_bot_vl:\n        if vl[3] > max_y:\n          left_bottest_vl = vl\n          max_y = vl[3]\n      \n      for vl in ex_left_top_vl:\n        if vl[3] < min_y:\n          left_toppest_vl = vl\n          min_y = vl[3]\n\n\n      #       Figure out min_y & max_y of thr_session       #\n      # print('thr_session.shape :', thr_session.shape)\n      \n      #     \ubc14\ub2e5\uc740 \uc624\ud788\ub824 \ud558\uba74 \uc548\ub41c\ub2e4.    #\n      thr_session_gray = cv2.cvtColor(thr_session, cv2.COLOR_RGB2GRAY)\n      print('thr_session_gray.shape :', thr_session_gray.shape)\n\n      top_white_cnt = 0\n      bot_white_cnt = 0\n      white_min_x = thr_session_gray.shape[1]\n      white_max_x = 0\n      white_min_y = thr_session.shape[0]\n      white_max_y = 0\n      temp_min_y = white_min_y\n      temp_max_y = white_max_y\n      top_parallel = False\n      bot_parallel = False\n      for i in range(thr_session_gray.shape[1]):\n\n        #     Check Top Condition     #\n        for j in range(int(thr_session_gray.shape[0] / 10)):\n          # if thr_session_gray[j][i] == 255 and j < thr_min_y:\n            # thr_min_y = j\n            # thr_min_y_coord = (i, j)\n          if thr_session_gray[j][i] == 255:\n            top_white_cnt += 1\n            if i > white_max_x:\n              white_max_x = i\n              max_x_coord = (i, j)\n            if i < white_min_x:\n              white_min_x = i\n              min_x_coord = (i, j)\n            if j < temp_min_y:\n              temp_min_y = j\n              temp_min_y_coord = (i, j)\n\n        for j in range(int(thr_session_gray.shape[0] / 10), int(thr_session_gray.shape[0] * 9/10)):\n          if thr_session_gray[j][i] == 255:\n            if j > white_max_y:\n              white_max_y = j\n              max_y_coord = (i, j)\n            if j < white_min_y:\n              white_min_y = j\n              min_y_coord = (i, j)\n\n        #     Check Bot Condition   #\n        for j in range(int(thr_session_gray.shape[0] * 9/10), thr_session_gray.shape[0]):\n          # if thr_session_gray[j][i] == 255 and j < thr_min_y:\n            # thr_min_y = j\n            # thr_min_y_coord = (i, j)\n          if thr_session_gray[j][i] == 255:\n            bot_white_cnt += 1\n            if j > temp_max_y:\n              temp_max_y = j\n              temp_max_y_coord = (i, j)\n            # if i > white_max_x:\n            #   white_max_x = i\n            #   max_x_coord = (i, j)\n            # if i < white_min_x:\n            #   white_min_x = i\n            #   min_x_coord = (i, j)\n\n      if top_white_cnt / (thr_session_gray.shape[1] * int(thr_session_gray.shape[0] / 10)) > 0.5:\n        top_parallel = True\n        min_y_coord = temp_min_y_coord\n      \n      if bot_white_cnt / (thr_session_gray.shape[1] * int(thr_session_gray.shape[0] / 10)) > 0.5:\n        bot_parallel = True\n        max_y_coord = temp_max_y_coord\n\n          # elif thr_session_gray[j][i] == 1 and j > thr_max_y:    \n          #   thr_max_y = j\n          #   thr_max_y_coord = (j, i)\n      # print('thr_min_y :', thr_min_y)\n      # print('thr_min_y_coord :', thr_min_y_coord)\n      try:\n        max_x_coord, min_x_coord\n        print('max_x_coord, min_x_coord :', max_x_coord, min_x_coord)\n      except:\n        pass\n\n\n      #     None \uc774\ub77c\uba74 \ub300\uce6d\uc774\ub3d9\uc744 \ud1b5\ud574 \ub9cc\ub4e4\uc5b4\uc8fc\uc5b4\uc57c\ud55c\ub2e4.     #\n      if len(ex_right_bot_vl) == 0:\n        if right_toppest_vl is not None:\n          x0, y0, x1, y1 = right_toppest_vl\n          slope = (y1 - y0) / float(x1 - x0)\n          angle = - math.degrees(math.atan(slope))\n\n          #       white_max_y \ub97c - toppest_vl angle \ub85c \uc9c0\ub098\ub294 \uc9c1\uc120      #\n          print('max_y_coord :', max_y_coord)\n          print('angle :', angle)\n          endy = 100 * math.sin(math.radians(angle))\n          endx = 100 * math.cos(math.radians(angle))\n          temp_vl = Line(max_y_coord, (max_y_coord[0] + endx, max_y_coord[1] + endy))\n          [left_point] = temp_vl.intersection(l2)\n          [right_point] = temp_vl.intersection(l3)\n          # print('left_point :', left_point)\n          right_bottest_vl = (float(left_point[0]), float(left_point[1]), float(right_point[0]), float(right_point[1]))\n          print('right_bottest_vl :', right_bottest_vl)\n\n      elif len(ex_right_top_vl) == 0:\n        if right_bottest_vl is not None:\n          x0, y0, x1, y1 = right_bottest_vl\n          slope = (y1 - y0) / float(x1 - x0)\n          angle = - math.degrees(math.atan(slope))\n\n          #       white_max_y \ub97c - toppest_vl angle \ub85c \uc9c0\ub098\ub294 \uc9c1\uc120      #\n          print('min_y_coord :', min_y_coord)\n          print('angle :', angle)\n          endy = 100 * math.sin(math.radians(angle))\n          endx = 100 * math.cos(math.radians(angle))\n          temp_vl = Line(min_y_coord, (min_y_coord[0] + endx, min_y_coord[1] + endy))\n          [left_point] = temp_vl.intersection(l2)\n          [right_point] = temp_vl.intersection(l3)\n          # print('left_point :', left_point)\n          right_toppest_vl = (float(left_point[0]), float(left_point[1]), float(right_point[0]), float(right_point[1]))\n          print('right_toppest_vl :', right_toppest_vl)\n\n      try:\n        x1, y1, x0, y0 = right_toppest_vl\n        cv2.line(vl_img, (int(x1), int(y1)), (int(x0), int(y0)), (0, 0, 255), 3, cv2.LINE_AA)\n        x1, y1, x0, y0 = right_bottest_vl\n        cv2.line(vl_img, (int(x1), int(y1)), (int(x0), int(y0)), (0, 0, 255), 3, cv2.LINE_AA)\n      except:\n        pass\n\n      if len(ex_left_bot_vl) == 0:\n        if left_toppest_vl is not None:\n          x0, y0, x1, y1 = left_toppest_vl\n          slope = (y1 - y0) / float(x1 - x0)\n          angle = - math.degrees(math.atan(slope))\n\n          #       white_max_y \ub97c - toppest_vl angle \ub85c \uc9c0\ub098\ub294 \uc9c1\uc120      #\n          print('max_y_coord :', max_y_coord)\n          print('angle :', angle)\n          endy = 100 * math.sin(math.radians(angle))\n          endx = 100 * math.cos(math.radians(angle))\n          temp_vl = Line(max_y_coord, (max_y_coord[0] + endx, max_y_coord[1] + endy))\n          [left_point] = temp_vl.intersection(l2)\n          [right_point] = temp_vl.intersection(l3)\n          # print('left_point :', left_point)\n          left_bottest_vl = (float(left_point[0]), float(left_point[1]), float(right_point[0]), float(right_point[1]))\n          print('left_bottest_vl :', left_bottest_vl)\n\n      elif len(ex_left_top_vl) == 0:\n        if left_bottest_vl is not None:\n          x0, y0, x1, y1 = left_bottest_vl\n          slope = (y1 - y0) / float(x1 - x0)\n          angle = - math.degrees(math.atan(slope))\n\n          #       white_max_y \ub97c - toppest_vl angle \ub85c \uc9c0\ub098\ub294 \uc9c1\uc120      #\n          print('min_y_coord :', min_y_coord)\n          print('angle :', angle)\n          endy = 100 * math.sin(math.radians(angle))\n          endx = 100 * math.cos(math.radians(angle))\n          temp_vl = Line(min_y_coord, (min_y_coord[0] + endx, min_y_coord[1] + endy))\n          [left_point] = temp_vl.intersection(l2)\n          [right_point] = temp_vl.intersection(l3)\n          # print('left_point :', left_point)\n          left_toppest_vl = (float(left_point[0]), float(left_point[1]), float(right_point[0]), float(right_point[1]))\n          print('left_toppest_vl :', left_toppest_vl)\n\n      try:\n        x1, y1, x0, y0 = left_bottest_vl\n        cv2.line(vl_img, (int(x1), int(y1)), (int(x0), int(y0)), (255, 255, 0), 3, cv2.LINE_AA)\n        x1, y1, x0, y0 = left_toppest_vl\n        cv2.line(vl_img, (int(x1), int(y1)), (int(x0), int(y0)), (255, 255, 0), 3, cv2.LINE_AA)\n      except:\n        pass\n\n      # \uc77c\ub2e8\uc740 \uc704\uc544\ub798 \ub458\ub2e4 \uc788\ub294 \uc870\uac74 \uc131\ub9bd #\n      #   \uc788\ub294 \ucabd\ub9cc \uc0ac\uc6a9, \uc591\ubc29\ud5a5 \uc18c\uc2e4\uc810 \ub2e4 \uc874\uc7ac\ud558\uba74 \uc18c\uc2e4\uc120 \uac1c\uc218\uac00 \ub354 \ub9ce\uc740 \ucabd \uc0ac\uc6a9   #   \n      # left_condition = left_bottest_vl is not None and left_toppest_vl is not None\n      # right_condition = right_bottest_vl is not None and right_toppest_vl is not None\n\n      # if left_condition or right_condition:\n        # print('left_bottest_vl', left_bottest_vl)\n      if len(left_vl_list) >= len(right_vl_list):\n        #       toppest & bottest vl should be on the min_y & max_y of white mask       #\n        # x1, y1, x0, y0 = left_bottest_vl\n        # cv2.line(vl_img, (int(x1), int(y1)), (int(x0), int(y0)), (0, 0, 255), 3, cv2.LINE_AA)\n        x1, y1, x0, y0 = left_toppest_vl\n        # cv2.line(vl_img, (int(x1), int(y1)), (int(x0), int(y0)), (0, 0, 255), 3, cv2.LINE_AA)\n        \n        # if thr_min_y == 0:\n        #   thr_min_x = thr_session_gray.shape[1]\n        #   for i in range(thr_session_gray.shape[1]):\n        #       if thr_session_gray[0][i] == 255 and i < thr_min_x:\n        #         thr_min_x = i\n        #         thr_min_y_coord = (i, 0)\n        #         break\n        #   print('thr_min_y_coord :', thr_min_y_coord)\n        if top_parallel:\n          top_line = Line((x1, y1), (x0, y0))\n          print('top_line.slope :', float(top_line.slope))            \n          if abs(top_line.slope) < 0.05:\n              max_x_coord = (0, 0)\n          parallel_tl = top_line.parallel_line(min_x_coord)\n          [tl] = parallel_tl.intersection(l2)\n          [tr] = parallel_tl.intersection(l3)\n          br, bl = left_bottest_vl[2:], left_bottest_vl[:2]\n        else:\n          tl, tr, br, bl = left_toppest_vl[:2], left_toppest_vl[2:], left_bottest_vl[2:], left_bottest_vl[:2]\n      \n      else:\n        # x1, y1, x0, y0 = right_bottest_vl\n        # cv2.line(vl_img, (int(x1), int(y1)), (int(x0), int(y0)), (0, 0, 255), 3, cv2.LINE_AA)\n        x1, y1, x0, y0 = right_toppest_vl\n        # cv2.line(vl_img, (int(x1), int(y1)), (int(x0), int(y0)), (0, 0, 255), 3, cv2.LINE_AA)\n\n        # if thr_min_y == 0:\n        #   thr_max_x = 0\n        #   for i in range(thr_session_gray.shape[1] - 1, 0, -1):\n        #       print('i :', i)\n        #       if thr_session_gray[0][i] == 255 and i > thr_max_x:\n        #         thr_max_x = i\n        #         thr_min_y_coord = (i, 0)\n        #         break\n        #   print('thr_min_y_coord :', thr_min_y_coord)\n        if top_parallel:\n          top_line = Line((x1, y1), (x0, y0))\n          print('top_line.slope :', float(top_line.slope))\n          if abs(top_line.slope) < 0.05:\n              max_x_coord = (thr_session_gray.shape[1], 0)\n          parallel_tl = top_line.parallel_line(max_x_coord)\n          [tl] = parallel_tl.intersection(l2)\n          [tr] = parallel_tl.intersection(l3)\n          br, bl = right_bottest_vl[2:], right_bottest_vl[:2]\n        else:\n          tl, tr, br, bl = right_toppest_vl[:2], right_toppest_vl[2:], right_bottest_vl[2:], right_bottest_vl[:2]\n        \n      #       Refering      #\n      refered = np.asarray(refer)[:vl_img.shape[0], :vl_img.shape[1]]\n\n      # plt.imshow(refered)\n      # plt.title('refered')\n      # plt.show()\n\n      #   tl, tr, br, bl    #\n      #     refer\ub97c \uc704\ud574 src_x => 0 \uc73c\ub85c \ub9de\ucdb0\uc900\ub2e4.    #\n      src = np.array([\n          [0, 0],\n          [vl_img.shape[1], 0],\n          [vl_img.shape[1], vl_img.shape[0]],\n          [0, vl_img.shape[0]]], dtype = \"float32\")\n      dst = np.array([list(tl),\n                      list(tr),\n                      list(br),\n                      list(bl)], dtype = \"float32\")\n\n      print()\n      print(\"#          Warping Points        #\")\n      print('src :', src)\n      print('dst :', dst)\n\n      # compute the perspective transform matrix and then apply it\n      matrix = cv2.getPerspectiveTransform(src, dst)\n      refered = cv2.warpPerspective(refered, matrix, (refered.shape[1], refered.shape[0]))\n      \n      plt.subplot(121)\n      plt.imshow(vl_img)\n      plt.title('Session_vl_img')\n      # plt.xlim(np.min(vps[:, [0]]), np.max(vps[:, [0]]))\n      # plt.ylim(np.min(vps[:, [1]]), np.max(vps[:, [1]]))\n      plt.subplot(122) \n      plt.imshow(refered)\n      plt.show() \n\n      org_color_np2[:, int(min_x):int(max_x)] = refered\n\n\n      #     i != 0 \uc778 \uacbd\uc6b0 break     #\n      if reg_index == 0 and np.sum(reg_xs) != 0 and not iter:\n        iter = True\n        print('iter :', iter)\n\n      else:\n        break\n\n  \n  #         Refer\uc758 \uac80\uc740 \ubd80\ubd84\uc740 original image\ub85c \ucc44\uc6b4\ub2e4.       #\n  for i in range(org_color_np2.shape[1]):\n    for j in range(org_color_np2.shape[0]):\n      if sum(org_color_np2[j][i]) == 0:\n        org_color_np2[j][i] = org_color_np[j][i]\n  \n  print('elapsed time :', time.time() - start)\n  print()\n\n  \n  plt.figure(figsize=(15, 10))\n  plt.subplot(131)\n  plt.imshow(org_np3)\n\n  plt.subplot(132)\n  plt.imshow(org_color_np2)\n  # plt.show()\n\n  # print('np.max(org_np) :', np.max(org_np))\n  org_np = org_np/ 255.\n  refer = org_color_np2\n\n  #     1.wall_mask * reference color image + (1 - wall_mask) * original_image)    #\n  syn_ = org_np * (refer) + (1 - org_np) * org_color_np\n  syn = org_np * syn_ + (1 - org_np) * org_color_np\n  plt.subplot(133)\n  plt.imshow(syn.astype(np.uint8))\n  plt.show()\n\n  \n\n  if one_iter:\n    break\n  # break\n```\n\n\n```\n\n  # v_border = line((0, 0), (0, skl_copy.shape[0]))\n  # v_border_lower = line((skl_copy.shape[1], 0), (skl_copy.shape[1], skl_copy.shape[0]))\n  # for h_line in h_lines:\n\n  #     #       Find Intersection between v_line, h_line      #\n  #     vh_intersections_x = list()\n  #     vh_intersections_y = list()\n\n  #     hline = line(h_line[:2], h_line[2:])\n  #     for reg_x, reg_y in zip(reg_xs, reg_ys):\n  #       vline = line((reg_x[0], reg_y[0]), (reg_x[1], reg_y[1]))\n\n  #       #     Extract only x - coordination     #\n  #       vh_intersections_x.append(intersection2(vline, hline)[0])\n  #       vh_intersections_y.append(intersection2(vline, hline)[1])\n\n  #     # h_x = np.array([h_line[0], h_line[2]])\n  #     # h_y = np.array([h_line[1], h_line[3]])\n  #     # ex_h_x, ex_h_y = extended(h_x, h_y, 500)\n  #     # ex_h_line = line((int(h_x[0]), int(h_y[0])), (int(h_x[1]), int(h_y[1])))\n  #     r = intersection2(v_border, hline)\n  #     r_lower = intersection2(v_border_lower, hline)\n\n  #     vh_intersections_x.append(r[0])\n  #     vh_intersections_y.append(r[1])\n  #     vh_intersections_x.append(r_lower[0])\n  #     vh_intersections_y.append(r_lower[1])\n\n  #     sorted_vh_inter_x = sorted(vh_intersections_x)\n  #     # print('vh_intersections_x :', vh_intersections_x)\n  #     # print('sorted_vh_inter_x :', sorted_vh_inter_x)\n\n  #     center_h_x = (h_line[0] + h_line[2]) / 2\n  #     # print('center_h_x :', center_h_x)\n      \n  #     #       hline \uc0c1\uc758 \uad50\ucc28\uc810\uc744 \ucc3e\uc544\ub0b4\uc11c \ubc94\uc704 \ub0b4\uc5d0\uc11c \uc5f0\uacb0\ud55c\ub2e4.      #\n  #     for i in range(1, len(sorted_vh_inter_x)):\n\n  #       if sorted_vh_inter_x[i - 1] <= center_h_x <= sorted_vh_inter_x[i]:\n  #         lx, ly = sorted_vh_inter_x[i - 1], vh_intersections_y[vh_intersections_x.index(sorted_vh_inter_x[i - 1])]\n  #         rx, ry = sorted_vh_inter_x[i], vh_intersections_y[vh_intersections_x.index(sorted_vh_inter_x[i])]\n  #         # print('lx, ly, rx, ry :', lx, ly, rx, ry)\n  #         #       \uc774\uacf3\uc758 lx, ly, rx, ry \ub294 close_p \ub2e4. \uc88c\uc6b0\ub85c \ub098\ub258\uc5b4\uc9c4 lx, ly\uac00 \uc544\ub2c8\ub2e4.     #\n            \n  #           #       \uc815\uc81c\ub41c \uad50\ucc28\uc810\uc744 \ub9cc\ub4dc\ub294 hline\ub9cc \uc0ac\uc6a9\ud574\uc57c\ud55c\ub2e4.        #\n  #         for inters in all_closest_inters:\n  #           for inter in inters:\n  #             if lx in inter or rx in inter:\n  #               h_intersections.append((lx, ly, rx, ry))\n  #               # cv2.line(black_plane, (int(lx), int(ly)), (int(rx), int(ry)), (0, 0, 255), 1, cv2.LINE_AA)\n          \n\n  #       vline \uae30\uc900\uc73c\ub85c \uad6c\ud68d\ud574\uc57c\ud55c\ub2e4. -> \uac00\uc7a5 \uc67c\ucabd / \uc624\ub978\ucabd vline + \uad6c\uc5ed \uba3c\uc800 \ucc3e\uc544 \uc791\uc5c5\ud558\uae30     #\n  #       vline \ubcc4\ub85c \uad6c\ud68d \ub098\ub204\uae30      #\n  # h_intersections = list(set(h_intersections))\n  # print('np.array(all_closest_inters).shape :', np.array(all_closest_inters).shape)\n  # all_closest_inters = np.array(all_closest_inters)\n  # print('len(all_closest_inters) :', len(all_closest_inters))\n\n  # center_xs = list()\n  # for inters in all_closest_inters:\n  #   #     all_closest_inter\uac00 \uc815\ub82c\ub418\uc9c0 \uc54a\uc558\ub2e4\uba74 inters type = list()      #\n  #   sum_x = 0\n  #   for inter in inters:\n  #     sum_x += inter[0] + inter[2]\n  #   center_xs.append(sum_x / len(inters) * 2)\n  # sorted_center_xs = sorted(center_xs)\n\n  # sorted_index = list()\n  # for center_x in sorted_center_xs:\n  #   # print('center_x :', center_x)\n  #   sorted_index.append(center_xs.index(center_x))\n  # # print('sorted_index :', sorted_index)\n  # #       sorted_center_xs \uc21c\uc11c\ub85c all_closest_inter\ub97c \uc815\ub82c\ud55c\ub2e4.     #\n  # #       index list\ub97c \ucd94\ucd9c\ud574\uc11c for \ubb38\uc73c\ub85c all_closest_inter\uc758 inters\ub97c \ucd94\ucd9c\ud574\n  # #       sorted_all ... \uc5d0 append \uc2dc\ud0a8\ub2e4.      #\n  # sorted_all_closest_inters = list()\n  # sorted_all_centroid_inters = list()\n  # for s_index in sorted_index:\n  #   sorted_all_closest_inters.append(all_closest_inters[s_index])\n  #   sorted_all_centroid_inters.append(all_centroid_inters[s_index])\n  # all_closest_inters = sorted_all_closest_inters\n  # all_centroid_inters = sorted_all_centroid_inters\n\n```\n\n\n```\n#                                   Refering                                 #\n      #     Find Top left / right & Bottom left / right       #\n      #     ->  tl, tr, bl, br     #\n      four_inters = np.array(four_inters)\n      [tl, tr, br, bl] = order_points(four_inters)\n      # print(four_inters.shape)\n      top_length = math.hypot(tl[0] - tr[0], tl[1] - tr[1])\n      bottom_length = math.hypot(bl[0] - br[0], bl[1] - br[1])\n      max_hlength = max(top_length, bottom_length)\n\n      #     1. Compare left / right height     #\n      l_height = bl[1] - tl[1]\n      r_height = br[1] - tr[1]\n\n      #     2. Extend Shorter Height      #\n      if l_height <= r_height:\n        shorter_points = [bl, tl]\n        longer_points = [br, tr]\n      else:\n        shorter_points = [br, tr]\n        longer_points = [bl, tl]\n\n      ex_shorter_points = np.zeros_like(shorter_points)\n      ex_longer_points = np.zeros_like(longer_points)\n\n      print('shorter_points :', shorter_points)\n      x = (shorter_points[0][0], shorter_points[1][0])\n      y = (shorter_points[0][1], shorter_points[1][1])\n      print('shorter x, y :', x, y)\n\n      y_ext = np.array([org_np.shape[0], 0])\n      p = np.polyfit(y, x , deg=1)\n      x_ext = np.poly1d(p)(y_ext)\n\n      ex_shorter_points[0] = [x_ext[0], y_ext[0]]\n      ex_shorter_points[1] = [x_ext[1], y_ext[1]]\n\n      #     Find intersection between (longer + shorter points)'s parallel line and longer line   #\n      long_short_lower = Line(longer_points[0], shorter_points[0])\n      long_short = Line(longer_points[1], shorter_points[1])\n      p_line_lower = long_short_lower.parallel_line(ex_shorter_points[0])\n      p_line = long_short.parallel_line(ex_shorter_points[1])\n      longer_line = Line(longer_points[0], longer_points[1])\n\n      # print('ex_shorter_points[1] in p_line ? :', ex_shorter_points[1] in p_line)\n      # print('p_line_lower.intersection(longer_line) :', p_line_lower.intersection(longer_line)[0][0])\n      ex_longer_points[0] = [p_line_lower.intersection(longer_line)[0][0], p_line_lower.intersection(longer_line)[0][1]]\n      ex_longer_points[1] = [p_line.intersection(longer_line)[0][0], p_line.intersection(longer_line)[0][1]]\n\n      if l_height <= r_height:\n        ex_bl, ex_tl = ex_shorter_points\n        ex_br, ex_tr = ex_longer_points\n      else:\n        ex_br, ex_tr = ex_shorter_points\n        ex_bl, ex_tl = ex_longer_points\n\n      for ex_p in [ex_bl, ex_br, ex_tl, ex_tr]:\n        print(ex_p)\n        # cv2.circle(black_plane2, (int(ex_p[0]), int(ex_p[1])), 10, (255, 0, 255), -1)\n\n      min_x, max_x = min(ex_bl[0], ex_tl[0]), max(ex_br[0], ex_tr[0])\n      min_y, max_y = min(ex_tl[1], ex_tr[1]), max(ex_bl[1], ex_br[1])\n      src_x = max((max_x - min_x), max_hlength) * math.sqrt(2)\n      print('src_x :',  src_x)\n\n      refered = np.asarray(refer)[:int(max_y - min_y), :int(src_x)]\n\n      # plt.imshow(refered)\n      # plt.title('refered')\n      # plt.show()\n\n      #   tl, tr, br, bl    #\n      #     refer\ub97c \uc704\ud574 src_x => 0 \uc73c\ub85c \ub9de\ucdb0\uc900\ub2e4.    #\n      src = np.array([\n          [0, 0],\n          [src_x, 0],\n          [src_x, max_y - min_y],\n          [0, max_y - min_y]], dtype = \"float32\")\n      dst = np.array([\n                      [ex_tl[0] - min_x, ex_tl[1] - min_y],\n                      [ex_tr[0] - min_x, ex_tr[1] - min_y],\n                      [ex_br[0] - min_x, ex_br[1] - min_y],\n                      [ex_bl[0] - min_x, ex_bl[1] - min_y]], dtype = \"float32\")\n\n      print('src :', src)\n      print('dst :', dst)\n\n      # compute the perspective transform matrix and then apply it\n      matrix = cv2.getPerspectiveTransform(src, dst)\n      refered = cv2.warpPerspective(refered, matrix, (refered.shape[1], refered.shape[0]))\n\n      # print('refered.min() :', refered.min())\n      # print(refered[[0], [0]])\n      # print('refered.shape :', refered.shape)\n      # plt.imshow(refered)\n      # plt.title('warfed')\n      # plt.xlim(min_x, max_x)\n      # plt.xlim(0, max_x - min_x)\n      # plt.ylim(max_y, min_y)\n      # plt.xlim(-1000, 1000)\n      # plt.ylim(1000, -1000)\n      # plt.show()\n      \n      refer_crop = refered[int(abs(min_y)): int(abs(min_y)) + org_np.shape[0], :]\n      # print('refer_crop.shape :', refer_crop.shape)\n\n      # plt.imshow(refer_crop)\n      # plt.title('cropped refer')\n      # plt.show()\n\n      #     Crop Section From Cropped Refer     #\n      #         src_x => 0\uc73c\ub85c \ub9de\ucdb0\uc92c\ub358 \uac83\uc744 \ub418\ub3cc\ub9b0\ub2e4.      #\n      print('int(min_x) :', int(min_x))\n      print('int(min_y) :', int(min_y))\n\n      for i in range(refer_crop.shape[1]):\n        for j in range(refer_crop.shape[0]):\n          if sum(refer_crop[j][i]) != 0:\n            if i + int(min_x) < black_plane2.shape[1]:\n              black_plane2[j][i + int(min_x)] = refer_crop[j][i]\n```\n", "meta": {"hexsha": "7f94d829aad20cf0d8586c00c8db074bbfdcb03b", "size": 856419, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Layout Estimation by vanishing line Func.ipynb", "max_stars_repo_name": "jaytoone/Indoor_Segmentation", "max_stars_repo_head_hexsha": "d99e502f99cb74000483974d931c2da058071bec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Layout Estimation by vanishing line Func.ipynb", "max_issues_repo_name": "jaytoone/Indoor_Segmentation", "max_issues_repo_head_hexsha": "d99e502f99cb74000483974d931c2da058071bec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Layout Estimation by vanishing line Func.ipynb", "max_forks_repo_name": "jaytoone/Indoor_Segmentation", "max_forks_repo_head_hexsha": "d99e502f99cb74000483974d931c2da058071bec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-29T15:27:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-29T15:27:56.000Z", "avg_line_length": 856419.0, "max_line_length": 856419, "alphanum_fraction": 0.9352933552, "converted": true, "num_tokens": 16647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742626558767584, "lm_q2_score": 0.03161876783896919, "lm_q1q2_score": 0.010036627397607698}}
{"text": "```python\nimport theme\ntheme.load_style()\n```\n\n\n\n\n<style>\n@import url('http://fonts.googleapis.com/css?family=Source+Code+Pro');\n@import url('http://fonts.googleapis.com/css?family=Vollkorn');\n@import url('http://fonts.googleapis.com/css?family=Arimo');\n@import url('http://fonts.googleapis.com/css?family=Arvo:400,700,400italic')\n\n#notebook li { /* More space between bullet points */\n    margin-top:0.8em;\n}\n\n/* draw border around running cells */\ndiv.cell.border-box-sizing.code_cell.running {\n    border: 3px solid #111;\n}\n\ndiv.cell.code_cell {\n    margin-top: 1em;\n    margin-left: auto;\n    margin-right: auto;\n    width: 800px;\n    border: 1px solid rgba(200, 200, 200, 0.8);\n    border-radius: 8px; /* rounded borders */\n}\n\ndiv.text_cell_render{\n    font-family: 'Arvo' sans-serif;\n    /* font-family: 'Arimo',verdana,arial,sans-serif; */\n    line-height: 130%;\n    font-size: 115%;\n    margin-left:0%;\n    margin-right:auto;\n}\n\n.text_cell_render h1 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 300;\n    font-style: bold;\n    font-size: 30pt;\n    line-height: 100%;\n    color:#c76c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h2 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 20pt;\n    line-height: 100%;\n    color:#c76c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h3 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 16pt;\n    line-height: 100%;\n    color:#d77c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h4 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 14pt;\n    font-style: italic;\n    line-height: 100%;\n    color:#d77c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h5 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 12pt;\n    color: #1d3b84;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n}\n\n.rendered_html code{\n    background-color: transparent;\n}\n\nul{\n    margin: 2em;\n}\n\nul li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.5em;\n}\n\nul li li{\n    padding-left: 0.2em;\n    margin-bottom: 0.2em;\n    margin-top: 0.2em;\n}\n\nol{\n    margin: 2em;\n}\n\nol li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.5em;\n}\n\nul li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.2em;\n}\n\na:link{\n    font-weight: bold;\n    color:#447adb;\n}\n\na:visited{\n    font-weight: bold;\n    color: #1d3b84;\n}\n\na:hover{\n    font-weight: bold;\n    color: #1d3b84;\n}\n\na:focus{\n    font-weight: bold;\n    color:#447adb;\n}\n\na:active{\n    font-weight: bold;\n    color:#447adb;\n}\n\n.rendered_html :link {\n    text-decoration: underline;\n}\n\n.rendered_html :hover {\n    text-decoration: none;\n}\n\n.rendered_html :visited {\n    text-decoration: none;\n}\n\n.rendered_html :focus {\n    text-decoration: none;\n}\n\n.rendered_html :active {\n    text-decoration: none;\n}\n\n.warning{\n    color: rgb( 240, 20, 20 )\n}\n\nhr {\n    color: #f3f3f3;\n    background-color: #f3f3f3;\n    height: 1px;\n}\n\nblockquote{\n    display:block;\n    background: #fcfcfc;\n    border-left: 5px solid #c76c0c;\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    width:680px;\n    padding: 10px 10px 10px 10px;\n}\n\nblockquote p {\n    margin-bottom: 0;\n    line-height: 125%;\n    font-size: 100%;\n}\n\ntable#mytable,\ntable#mytable td,\ntable#mytable tr\n{\n    border: none !important;\n}\n\ntable#mytable-1,\ntable#mytable-1 td,\ntable#mytable-1 tr\n{\n    border: none !important;\n    align: center;\n    cellspacing: 10;\n}\n\n.msg {\n    width: 90%;\n    margin-left: auto;\n    margin-right: auto;\n    margin-top: 10px;\n    margin-bottom: 10px;\n    padding: 14px 14px 14px 14px;\n    color: #c09853;\n    text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);\n    background-color: #fcf8e3;\n    border: 1px solid #fbeed5;\n    -webkit-border-radius: 4px;\n    -moz-border-radius: 4px;\n    border-radius: 4px;\n}\n\n.msg-heading {\n    color: inherit;\n}\n\n.msg .close {\n    position: relative;\n    top: -2px;\n    right: -21px;\n    line-height: 18px;\n}\n\n.msg-success {\n    color: #468847;\n    background-color: #dff0d8;\n    border-color: #d6e9c6;\n}\n\n.msg-danger,\n.msg-error {\n    color: #b94a48;\n    background-color: #f2dede;\n    border-color: #eed3d7;\n}\n\n.msg-info {\n    color: #3a87ad;\n    background-color: #d9edf7;\n    border-color: #bce8f1;\n}\n\n.boxed {\n    color: #b94a48;\n    background-color: #f2dede;\n    border-color: #eed3d7;\n    margin-left: auto;\n    margin-right: auto;\n    padding: 14px 14px 14px 14px;\n}\n\n.w-300 { width: 300px; }\n.w-400 { width: 400px; }\n.w-500 { width: 500px; }\n\n</style>\n\n\n\n\n# Lesson 5: Formulations for 1D Problems \n## The Strong Form\n\n\n\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\"></a>\n\nThis lecture by Tim Fuller is licensed under the\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\">Creative Commons Attribution 4.0 International License</a>.  All code examples are also licensed under the [MIT license](http://opensource.org/licenses/MIT).\n\n<a id='top'></a>\n# Topics\n\n- [The Strong Form](#strong-form)\n  - [Axially Loaded Elastic Bar](#axibar)\n  - [Heat Conduction](#heatcond)\n  - [Electrical Conduction](#eleccond)\n- [Flux-Potential Relationship](#fluxpotrel)\n\n<a id='strong-form'></a> \n# The Strong Form[](#top)\n\n<a id='axibar'></a> \n## Axially Loaded Elastic Bar\n\nConsider the tapered bar\n\n\n\nSumming forces on the differential volumes gives\n\n$$-p(x) + b\\left(x+\\frac{\\Delta x}{2}\\right)\\Delta x + p\\left(x+\\Delta x\\right) = 0$$\n\nand taking the limit as $\\Delta x \\rightarrow 0$ leads to the following differential relationship \n\n$$\\lim_{\\Delta x \\rightarrow 0} \\frac{p\\left(x + \\Delta x\\right) -p\\left(x\\right)}{\\Delta x} + b\\left(x+\\frac{\\Delta x}{2}\\right) = \\frac{dp}{dx} + b(x) = 0$$\n\nSolution of the differential equation requires a *constitutive equation* relating $p(x)$ to $u(x)$.  Recalling that\n\n$$\\sigma(x) = \\frac{p(x)}{A(x)} \\Rightarrow p(x) = \\sigma(x) A(x)$$\n\nand, for a simple linear elastic material, the stress $\\sigma$ is given by Hooke's law of linear elasticity<sup>&dagger;</sup>\n\n$$\\sigma(x)=E(x)\\epsilon(x)$$\n\nwhere the strain $\\epsilon$ is given by\n\n$$\\epsilon(x) = \\frac{\\Delta L}{L} = \\lim_{\\Delta x\\rightarrow 0} \\frac{u(\\Delta x) - u(x+\\Delta x)}{\\Delta x} = \\frac{du}{dx}$$\n\nSubstituting the above expressions in to the differential relationship leads to\n\n$$\\frac{d}{dx}\\left(A(x)E(x)\\frac{du}{dx}\\right)+b(x)=0$$\n\nThe above is a second-order ordinary differential equation. In the above equation, $u(x)$ is the dependent variable, which is the unknown function, and $x$ is the independent variable. \n\nTo solve the strong form of the governing equation, boundary conditions at each end of the bar must be prescribed.  For the purpose of illustration, we will consider the following specific boundary conditions: at $x=0$, the displacement, $u(x=0)$, is prescribed; at $x=L$, the force per unit area, or traction, denoted by \udbff\udc22$t$, is prescribed. These conditions are written as\n\n$$\n\\begin{align}\nu(x=0) &= \\overline{u} \\\\\n\\sigma(x=L) &= \\left(E\\frac{du}{dx}\\right)_{x=L}=\\frac{F(L)}{A(L)} \\equiv \\overline{t} \n\\end{align}\n$$\n\nThe traction $\udbff\udc22t$ has the same units as stress (force/area), but its sign is positive when it acts in the positive $x$-direction regardless of which face it is acting on, whereas the stress is positive in tension and negative in compression, so that on a negative face a positive stress corresponds to a negative traction.\n\nThe differential equation governing the response of the elastic bar along with the associated boundary conditions is called the **strong form** of the governing equation and is summarized here\n\n<div class='msg'>\n<p><strong>The strong form</strong></p>\n$$\n\\begin{split}\n\\frac{d}{dx}\\left(A(x)E(x)\\frac{du}{dx}\\right)+b(x)=0 \\\\\nu(x=0) = \\overline{u} \\\\\n\\left(E\\frac{du}{dx}\\right)_{x=L} = \\overline{t} \n\\end{split}\n$$\n</div>\n\n**Note**\n- The problem data are $\\overline{u}$, $\\overline{t}$, and $b(x)$ and are given\n- Either the load or the displacement can be specified at a boundary point, but not both.\n\n<div class='msg'>\n<sup>&dagger;</sup>For thermo-elastic materials, the constitutive model is modified to include thermal effects $\\sigma(x) = E(x)\\left(\\epsilon(x) - \\alpha(x)T(x)\\right)$\n</div>\n\n<div class='msg msg-info'>\n<p><strong>Remark</strong></p>\nIn the previous example there are two types of boundary conditions: one in which the dependent variable ($u$) was specified on the boundary and at the other boundary its derivative was $\\left(E du/dx\\right)$.  These boundary conditions are classified as <em>Dirichlet</em> and <em>Neummann</em>, respectively.\n</div>\n\n<a id='heatcond'></a> \n## Heat Conduction\n\nHeat flow in a body occurs when there is a temperature difference within the body. Heat transferred in this way is referred to as conduction.  The heat flow through the wall of a heated room in the winter is an example of conduction.  In this section, the strong form of the differential equation governing heat transfer through conduction will be developed.  Other forms of heat transfer such as convection will be discussed in later chapters.\n\n\n\nConsider a body as shown above. The objective is to determine the temperature distribution. Let $A(x)$ be the area normal to the direction of heat flow and let $s(x)$ be the heat generated per unit thickness of the body, denoted by l. This is often called a heat source. A common example of a heat source is the heat generated in an electric wire due to resistance. In the one-dimensional case, the rate of heat generation is measured in units of energy per time; in SI units, the units of energy are joules (J) per unit length (meters, m) and time (seconds, s). Recall that the unit of power is watts (1 W = 1 J/s). A heat source $s(x)$ is considered positive when heat is generated, i.e. added to the system, and negative when heat is withdrawn from the system. Heat flux, denoted by $q(x)$, is defined as a the rate of heat flow across a surface. Its units are heat rate per unit area; in SI units, W/m$^2$. It is positive when heat flows in the positive x-direction. We will consider a steady-state problem, i.e. a system that is not changing with time.\n\nTo establish the differential equation that governs the system, we consider energy balance in a control volume of the wall. Energy balance requires that the rate of heat energy ($qA$) that is generated in the control volume must equal the heat energy leaving the control volume, as the temperature, and hence the energy in the control volume, is constant in a steady-state problem. The heat energy leaving the control volume is the difference between the flow in at on the left-hand side, $qA$, and the flow out on the right-hand side, $q(x + \\Delta x)A(x+\\Delta x)$. Thus, energy balance for the control volume can be written as\n\n$$s\\left(x+\\frac{\\Delta x}{2}\\right)\\Delta x + q(x)A(x) -  q\\left(x+\\Delta x\\right)A(x+ \\Delta x) = 0$$\n\nRearranging and taking the limit as $\\Delta x \\rightarrow 0$ leads to the following differential relationship \n\n$$\\lim_{\\Delta x \\rightarrow 0} \\frac{q\\left(x + \\Delta x\\right)A(x+\\Delta x) -q\\left(x\\right)A(x)}{\\Delta x} - s\\left(x+\\frac{\\Delta x}{2}\\right) = \\frac{d(qA)}{dx} - s = 0$$\n\nThe constitutive equation for heat flow, which relates the heat flux to the temperature, is known as Fourier\u2019s law and is given by\n\n$$\nq = -k \\frac{dT}{dx}\n$$\n\nwhere $T$ is the temperature and $k$ is the thermal conductivity (which must be positive); in SI units, the dimensions of thermal conductivity are W/m$\\cdot$<sup>o</sup>C. A negative sign appears because heat flows from high (hot) to low temperature (cold), i.e. opposite to the direction of the gradient of the temperature field.  Substituting Fourier's law gives\n\n$$\\frac{d}{dx}\\left(Ak\\frac{dT}{dx}\\right) + s = 0, \\quad 0 < x < L$$\n\nEither the flux or the temperature must be prescribed on each end of the bar; these are the boundary conditions. We consider the specific boundary conditions of the prescribed temperature $\\overline{T}$ at $x=0$ and prescribed flux $\\overline{q}$ at $x=L$. The prescribed flux $\\overline{q}$ is positive if heat (energy) flows out of the bar, i.e. $q(x=L)=-\\overline{q}$. The strong form for the heat conduction problem is then given by\n\n<div class='msg'>\n<p><strong>The strong form</strong></p>\n$$\\begin{split}\n\\frac{d}{dx}\\left(Ak\\frac{dT}{dx}\\right) + s = 0, \\quad 0 < x < L \\\\\nT=\\overline{T} \\text{ on } x=0 \\\\\n-q=k\\frac{dT}{dx} = \\overline{q} \\text{ on } x=L\\\\\n\\end{split}\n$$\n</div>\n\n## <a id='eleccond'></a> Electrical Conduction\n\nConsider the tapered bar with electrical potential as shown\n\n\n\nConservation of charge requires that\n\n$$i(x) - i\\left(x+\\Delta x\\right) = 0$$\n\nrearranging and taking the limit as $\\Delta x \\rightarrow 0$ leads to the following differential relationship \n\n$$\\lim_{\\Delta x \\rightarrow 0} \\frac{i\\left(x\\right) -i\\left(x + \\Delta x\\right)}{\\Delta x} = -\\frac{di}{dx} = 0$$\n\nOhm's law gives the constitutive equation relating voltagel and current \n\n$$\\begin{split}\nV(x) - V(x+\\Delta x) = i \\frac{\\rho(\\Delta x)}{A\\left(x+\\frac{\\Delta x}{2}\\right)} \\\\\n-\\frac{1}{\\rho}A(x)\\frac{dV}{dx} = i\n\\end{split}$$\n\nwhere $\\rho$ is the resistivity.  Substituting the above expressions in to the differential relationship leads to\n\n$$\\frac{d}{dx}\\left(\\frac{1}{\\rho}A(x)\\frac{dV}{dx}\\right)=0$$\n\nwhich is the strong from of the governing equation.\n\nBoundary conditions take the form of either a prescribed voltage or current at either end.  The strong form for electrical conduction with voltage prescribed at $x=0$ and current prescribed at $x=L$ is given by\n\n<div class='msg'>\n<p><strong>The Strong Form</strong></p>\n$$\n\\begin{split}\n\\frac{d}{dx}\\left(\\frac{1}{\\rho}A(x)\\frac{dV}{dx}\\right)=0 \\\\\nV(x=0) = \\overline{V} \\\\\n\\left(\\frac{1}{\\rho}A\\frac{dV}{dx}\\right)_{x=L} = \\overline{i} \n\\end{split}\n$$\n</div>\n\n<div class='msg msg-info'>\n<p><strong>Remark</strong></p>\nTo find the resistance of the entire element \n<ol>\n<li> Prescribe a current BC $i(0) = \\overline{i} = 1A$ </li>\n<li> Prescribe a voltage BC $V(L) = 0$ </li>\n<li> Solve for V(0) </li>\n<li> Sove for resistance $R=\\frac{V(0) - V(L)}{i(0)} = \\frac{V(0)}{1 A}$</li>\n</ol>\n</div>\n\n<a id='fluxpotrel'></a> \n# Flux Potential Relationships[](#top)\n\n\n\n## What is being fluxed?\n\nFlux is the rate of \"something\" per unit area.  To determine what is being fluxed, multiply flux by area to identify the rate of the thing being fluxed\n\n### Heat\n\nThe flux, $-qn$,  has units W/m$^2$.  Rate of the \u201cthing\u201d fluxed has units W.\nA watt, W, has units of Joules/s.  The thing fluxed has units of Joules.\n\n<div class='boxed w-500'> The thing fluxed is energy! <br>\nThe heat equation is often called \"energy balance\"<br>\nSteady state: rate of energy is zero!<br>\n</div>\n\n### Elasticity\n\nThe flux $\\bar{t}$ has units N/m$^2$.  Rate of the \u201cthing\u201d fluxed has units N.\nA Newton, N, has units kg m/s$^2$. The thing fluxed has units of kg m/s.\n\n<div class='boxed w-500'>\nThat\u2019s mass times velocity!<br>\nThe thing fluxed is momentum! <br>\nThe elasticity equation is often called \u201cmomentum balance\u201d<br>\nEquilibrium: rate of momentum is zero!<br>\n</div>\n", "meta": {"hexsha": "943957b42f8a159ecce15d59507c5b4ca5a041d3", "size": 22527, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lessons/Lesson05_StrongForm.ipynb", "max_stars_repo_name": "jzw0025/fem-with-python", "max_stars_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 148, "max_stars_repo_stars_event_min_datetime": "2015-11-05T16:32:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:42:26.000Z", "max_issues_repo_path": "Lessons/Lesson05_StrongForm.ipynb", "max_issues_repo_name": "pinkieli/fem-with-python", "max_issues_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lessons/Lesson05_StrongForm.ipynb", "max_forks_repo_name": "pinkieli/fem-with-python", "max_forks_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": 74, "max_forks_repo_forks_event_min_datetime": "2016-02-17T13:23:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T07:48:27.000Z", "avg_line_length": 39.2456445993, "max_line_length": 1066, "alphanum_fraction": 0.5308296711, "converted": true, "num_tokens": 4596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08269734945731683, "lm_q2_score": 0.12085323724011435, "lm_q1q2_score": 0.009994242393093752}}
{"text": "```python\nimport theme\ntheme.load_style()\n```\n\n\n\n\n<style>\n@import url('http://fonts.googleapis.com/css?family=Source+Code+Pro');\n@import url('http://fonts.googleapis.com/css?family=Vollkorn');\n@import url('http://fonts.googleapis.com/css?family=Arimo');\n@import url('http://fonts.googleapis.com/css?family=Arvo:400,700,400italic')\n\n#notebook li { /* More space between bullet points */\n    margin-top:0.8em;\n}\n\n/* draw border around running cells */\ndiv.cell.border-box-sizing.code_cell.running {\n    border: 3px solid #111;\n}\n\ndiv.cell.code_cell {\n    margin-top: 1em;\n    margin-left: auto;\n    margin-right: auto;\n    width: 800px;\n    border: 1px solid rgba(200, 200, 200, 0.8);\n    border-radius: 8px; /* rounded borders */\n}\n\ndiv.text_cell_render{\n    font-family: 'Arvo' sans-serif;\n    /* font-family: 'Arimo',verdana,arial,sans-serif; */\n    line-height: 130%;\n    font-size: 115%;\n    margin-left:0%;\n    margin-right:auto;\n}\n\n.text_cell_render h1 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 300;\n    font-style: bold;\n    font-size: 30pt;\n    line-height: 100%;\n    color:#c76c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h2 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 20pt;\n    line-height: 100%;\n    color:#c76c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h3 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 16pt;\n    line-height: 100%;\n    color:#d77c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h4 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 14pt;\n    font-style: italic;\n    line-height: 100%;\n    color:#d77c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h5 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 12pt;\n    color: #1d3b84;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n}\n\n.rendered_html code{\n    background-color: transparent;\n}\n\nul{\n    margin: 2em;\n}\n\nul li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.5em;\n}\n\nul li li{\n    padding-left: 0.2em;\n    margin-bottom: 0.2em;\n    margin-top: 0.2em;\n}\n\nol{\n    margin: 2em;\n}\n\nol li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.5em;\n}\n\nul li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.2em;\n}\n\na:link{\n    font-weight: bold;\n    color:#447adb;\n}\n\na:visited{\n    font-weight: bold;\n    color: #1d3b84;\n}\n\na:hover{\n    font-weight: bold;\n    color: #1d3b84;\n}\n\na:focus{\n    font-weight: bold;\n    color:#447adb;\n}\n\na:active{\n    font-weight: bold;\n    color:#447adb;\n}\n\n.rendered_html :link {\n    text-decoration: underline;\n}\n\n.rendered_html :hover {\n    text-decoration: none;\n}\n\n.rendered_html :visited {\n    text-decoration: none;\n}\n\n.rendered_html :focus {\n    text-decoration: none;\n}\n\n.rendered_html :active {\n    text-decoration: none;\n}\n\n.warning{\n    color: rgb( 240, 20, 20 )\n}\n\nhr {\n    color: #f3f3f3;\n    background-color: #f3f3f3;\n    height: 1px;\n}\n\nblockquote{\n    display:block;\n    background: #fcfcfc;\n    border-left: 5px solid #c76c0c;\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    width:680px;\n    padding: 10px 10px 10px 10px;\n}\n\nblockquote p {\n    margin-bottom: 0;\n    line-height: 125%;\n    font-size: 100%;\n}\n\ntable#mytable,\ntable#mytable td,\ntable#mytable tr\n{\n    border: none !important;\n}\n\ntable#mytable-1,\ntable#mytable-1 td,\ntable#mytable-1 tr\n{\n    border: none !important;\n    align: center;\n    cellspacing: 10;\n}\n\n.msg {\n    width: 90%;\n    margin-left: auto;\n    margin-right: auto;\n    margin-top: 10px;\n    margin-bottom: 10px;\n    padding: 14px 14px 14px 14px;\n    color: #c09853;\n    text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);\n    background-color: #fcf8e3;\n    border: 1px solid #fbeed5;\n    -webkit-border-radius: 4px;\n    -moz-border-radius: 4px;\n    border-radius: 4px;\n}\n\n.msg-heading {\n    color: inherit;\n}\n\n.msg .close {\n    position: relative;\n    top: -2px;\n    right: -21px;\n    line-height: 18px;\n}\n\n.msg-success {\n    color: #468847;\n    background-color: #dff0d8;\n    border-color: #d6e9c6;\n}\n\n.msg-danger,\n.msg-error {\n    color: #b94a48;\n    background-color: #f2dede;\n    border-color: #eed3d7;\n}\n\n.msg-info {\n    color: #3a87ad;\n    background-color: #d9edf7;\n    border-color: #bce8f1;\n}\n\n.boxed {\n    color: #b94a48;\n    background-color: #f2dede;\n    border-color: #eed3d7;\n    margin-left: auto;\n    margin-right: auto;\n    padding: 14px 14px 14px 14px;\n}\n\n.w-300 { width: 300px; }\n.w-400 { width: 400px; }\n.w-500 { width: 500px; }\n\n</style>\n\n\n\n\n# Lesson 7: The Weak Form\n\n\n\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\"></a>\n\nThis lecture by Tim Fuller is licensed under the\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\">Creative Commons Attribution 4.0 International License</a>.  All code examples are also licensed under the [MIT license](http://opensource.org/licenses/MIT).\n\n# <a id='top'></a> Topics\n- [Introduction](#intro)\n- [Continuity](#continuity)\n- [Weighted Integral Formulations](#weight-forms)\n  - [Three Steps to Develop the Weak Form](#three-steps)\n    - [Step 1](#step-1)\n    - [Step 2](#step-2)\n    - [Step 3](#step-3)\n- [Summary](#summary)\n- [Examples](#examples)\n  - [Example 1](#ex-1)\n  - [Example 2](#ex-2)\n\n# <a id='intro'></a> Introduction[](#top)\n> The weak form is the most intellectually challenging part in the development of finite elements, so a student may encounter some difficulties in understanding this concept\n\n> Understanding how a solution to a differential equation can be obtained by this rather abstract statement, and why it is a useful solution, is not easy. It takes most students considerable thought and experience to comprehend the process.\n\n> - Fish and Belytschko, 2007\n\nThe weighted integral formulations of the previous lesson allowed finding approximate solutions to the accompanying governing differential equation.  Similarly, the finite element method is a technique for constructing approximate solutions to differential equations.  To understand the foundations of the method, it is necessary to understand the weighted-integral formulations and the *weak* formulation of the differential equations.  A weak form of a differential equation is equivalent to the governing equation and boundary conditions, i.e. the strong form.  It allows classifying boundary conditions as essential and natural.\n\n# <a id='continuity'></a>Continuity[](#top)\n\nBefore developing the weak form, let us discuss the concept of smoothness, or continuity.  In general, a $k^{\\rm th}$ order ODE\n\n$$\n au^{(k)} + a_{k-1}u^{(k-1)}+\\cdots++ a_{2}u''+ a_{1}u' + a_0=0\n$$\n\nrequires that\n\n$$\n u\\in C^{k-1}\n$$\n\nwhich means that $u$ has $k-1$ continuous derivatives. For example, if\n\n$$\n \\frac{d^2u}{dx^2}=0\n$$\n\nthen $u\\in C^1$, or the first derivative of $u$ must be continuous. Let's see if this is true.\n\n$$\n \\frac{d^2u}{dx^2} = 0 \\Rightarrow u=c_1x + c_2\n$$\n\nand\n\n$$\n u'=c_1\n$$\n\nsure enough, $u'$ is continuous and $u\\in C^1$\n\nA function is a $C^k$ function if its derivatives of order $j$ for $0 \\leq j \\leq k$ exist and are continuous functions in the entire domain.  In finite element analysis, we are concerned mostly with $C^0$, $C\udbff\udc02^{-1}$ and $C^1$ functions\n\n\n\nAs can be seen, a $C^0$ function is piecewise continuously differentiable, i.e. its first derivative is continuous except at selected points. The derivative of a $C^0$ function is a $C^{-\udbff\udc021}$ function. So for example, if the displacement is a $C^0$ function, the strain is a $C^{-1}$ function.  In general, the derivative of a $C^n$ function is $C^{n-\udbff\udc021}$.\n\n# <a id='weight-forms'></a> Weighted-Integral and Weak Formulations[](#top)\n\nConsider the following differential equation\n\n$$\n-\\frac{d}{dx}\\left(a(x)\\frac{du}{dx}\\right) = q(x) \\quad\n\\text{for } 0 < x < L\n$$\n\nThe solution $u(x)$ is subject to the boundary conditions\n\n$$\nu(0) = u_0, \\quad \\left.\\left(a\\frac{du}{dx}\\right)\\right|_{x=L}=Q_0\n$$\n\nwhere $a$ and $q$ are known functions of $x$, $u_0$ and $Q_0$ are known values, and $L$ is the length of the domain.  These are the problem data.  The solution $u$ is the dependent variable of the problem.  When $u_0\\neq0$ and/or $Q_0\\neq0$, the boundary conditions are nonhomogeneous and homogeneous otherwise.\n\nThe sole purpose of developing the weighted-integral statement was to be able to obtain $N$ linearly independent algebraic relations among the coefficients of the approximation\n\n$$\nu\\approx U_N = \\sum_{i=1}^N c_i\\phi_i(x) + \\phi_0(x)\n$$\n\n## <a id='three-steps'></a> Three Steps to Form the Weak Form\n\nReddy describes the following three steps to developing the weak form, if it exists, to a differnital equation:\n\n1. Multiply the equations by a weight function $w$ and integrate over the problem domain.\n2. Distribute differentiation among the dependent variable and weight function.\n3. Impose the boundary conditions.\n\n### <a id='step-1'></a> Step 1\n\nMove all expressions to one side, multiply by the weight function, and integrate over the domain\n\n$$\n\\int_0^L w\\left(-\\frac{d}{dx}\\left(a\\frac{du}{dx}\\right)-q\\right)dx = 0, \\quad \\forall w\n$$\n\nThe expression in the outer parenthesis is not zero if $u$ is replaced by an approximation.  Thus, the above expression is a statement that the error in the differential equation due to the approximation is zero in the weighted-integral sense.\n\nThe weight function $w$ can be any nonzero, integrable function.  The weighted-integral statement is equivalent only to the differential equation, and it does not include any boundary conditions.\n\n<div class='msg msg-info'>\nThe statement that the weighted integral equation must hold for all $w$ ($\\forall w$) is not arbitrary.  If it were not for that statement, none of the following would hold true.\n</div>\n\n### <a id='step-2'></a>Step 2\n\nWith the weighted-integral statement, $N$ algebraic relations among the $c_i$ for $N$ different choices of $w$ can be obtained.  But, the approximation functions $\\phi_i$ must still be chosen such that $U_N$ is differentiable as many times as required by the original differential equation and satisfies the original boundary conditions.  If the differentiation is distributed between the approximate solution $U_N$ and the weight function $w$, the resulting integral form will require weaker continuity on $\\phi_i$ and, hence, the weighted-integral statement is called the *weak form*.\n\nStarting with the integral statement, we integrate the first term in the expression by parts to obtain\n\n$$\n\\begin{align}\n0 &= \\int_0^L w\\left(-\\frac{d}{dx}\\left(a\\frac{du}{dx}\\right)-q\\right)dx \\\\\n&= \\int_0^L w\\left(\\frac{dw}{dx}a\\frac{du}{dx}-wq\\right)dx - \\left[wa\\frac{du}{dx}\\right]_0^L\\\\\n\\end{align}\n$$\n\n<div class='msg msg-info'>\nThe integration by parts formula is given by\n$$\n\\int_0^L wdv = -\\int_0^Lvdw + \\left[wv\\right]_0^L\n$$\n</div>\n\nNote that the weight function is required to be differentiable at least once.\n\nFrom the above expression, we can identify two types of boundary conditions: *natural* and *essential*.  The following rule is used to identify the natural boundary conditions: after completing Step 2, the coefficients of the weight function and its derivatives in the boundary expressions are called the *secondary variables*.  Specification of the secondary variables on the boundary constitutes the *natural boundary conditions*.  For this case, the coefficient of the weight function (the secondary variable) is $adu/dx$.\n\nThe secondary variables always have a physical meaning.  In the case of the axial bar problem, the secondary variable represents a traction $t$.  The secondary variable will be denoted by\n\n$$\nQ = \\left(a\\frac{du}{dx}\\right)n_x\n$$\n\nwhere $n_x$ is the direction cosine:\n\n$$\n\\begin{align}\nn_x = &\\text{cosine of the angle between the } x \\\\\n      & \\text{ axis and the normal to the boundary}\n\\end{align}\n$$\n\nFor 1D problems, $n_x=-1$ on the left end and $n_x=1$ at the right end of the domain.\n\nThe dependent variable of the problem, expressed in the same form as the weight function appearing in the boundary term is called the *primary variable*.  Its specification on the boundary consitutes the *essential boundary condition*.  For our example, the dependent variable $u$ is the primary variable and the essential boundary condition is the specification of $u$ at the boundary points.\n\n<div class='msg msg-info'>\nThe number of primary and secondary variables is always the same, and each primary variable has an associated secondary variable (e.g., temperature and heat, displacement and force, etc.).  Only one of the pair may be specified at a point on a boundary.\n</div>\n\nIn light of the above, a given problem can have boundary conditions in one of three categories:\n\ni) all boundary conditions are essential\nii) some of the boundary conditions are essential with the rest being natural\niii) all boundary conditions are natural\n\nWith our notation, the weak form is written\n\n$$\n0 = \\int_0^L\\left(a\\frac{dw}{dx}\\frac{du}{dx}-wq\\right)dx - (wQ)_0 - (wQ)_L\n$$\n\n\"Weak\" refers to the reduced (weakened) continuity of $u$ which is now required only to be once differentiable, instead of twice. \n\n### <a id='step-3'></a>Step 3\n\nWe now impose the boundary conditions.  We require that the weight function $w$ vanish at boundary points where the essential boundary conditions are specified.  In other words, $w$ is required to satisfy the homogenous form of the specified essential boundary conditions of the problem.  Why is this the case?  In the weak formulation, the weight unction has the meaning of a *virtual* change of the primary variable.  When the primary variable is prescribed at a point, the virtual change must be 0.  For our example problem, the essential boundary condition is $u=u_0$; thus, the weight function $w$ is required to satisfy\n\n$$\nw(0) = 0, \\quad \\text{because } u(0) = u_0\n$$\n\nSince $w(0) = 0$ and\n\n$$\nQ(L) = \\left(a\\frac{du}{dx}n_x\\right)\\Bigg|_{x=L}=\n\\left(a\\frac{du}{dx}\\right)\\Bigg|_{x=L} = Q_0\n$$\n\nour example problem reduces to\n\n$$\n0 = \\int_0^L w\\left(a\\frac{dw}{dx}\\frac{du}{dx}-wq\\right)dx - w(L)Q_0\n$$\n\nwhich is the weak form equivalent to the original differential equation with the associated natural boundary condition.\n\n# <a id='summary'></a> Summary[](#top)\n\n1. The weak form of a differential equation is a weighted integral statement that is equivalent to the strong form *and* the specified natural boundary conditions.\n2. The weak form is developed by multiplying the differential equation by an arbitrary weight function, distributing differentiation among the primary variable and the weight function through integration by parts, and finally applying the boundary conditions.\n3. After integrating by parts, the boundary terms are used to identify the forms of the primary and secondary variables.\n4. Because of the restrictions placed on the weight function in the weak form, it must belong to the same space of functions as the approximation functions ($w \\sim \\phi_i$).\n\n# <a id='examples'></a>Examples[](#top)\n\n## <a id='ex-1'></a> Example 1\n\nConstruct the weak and identify the primary and secondary variables for the nonlinear equation\n\n$$ \n-\\frac{d}{dx}\\left(u\\frac{du}{dx}\\right) + f = 0 \\quad \\text{for} \\quad\n0 < x < L\n$$\n$$\n\\left(u\\frac{du}{dx}\\right)\\Bigg|_{x=0}=0, \\quad u(1)=\\sqrt{2}\n$$\n\n### Solution\n\nFollowing the three step procedure, we write\n\n$$ \n\\begin{align}\n0 &= \\int_0^Lw\\left(-\\frac{d}{dx}\\left(u\\frac{du}{dx}\\right) + f\\right)dx\\\\\n&=\\int_0^L\\left(u\\frac{dw}{dx}\\frac{du}{dx} \n+ wf\\right)dx-\\left(w\\left(u\\frac{du}{dx}\\right)\\right)\\Bigg|_0^L\n\\end{align}\n$$\n\nObservation of the boundary term identifies $u$ as the primary variable and $u(du/dx)$ as the secondary variable.\n\nFrom the boundary conditions, since $w(1) = 0$ (why?) and $du/dx=0$ at $x=0$, we obtain for the weak form\n\n$$\n0 = \\int_0^L \\left(u\\frac{dw}{dx}\\frac{du}{dx} + wf\\right)dx\n$$\n\n\nThe weak form does not contain an expression that is linear in both $u$ and $v$.\n\n##<a id='ex-2'></a> Example 2\n\nConstruct the weak form and identify the primary and secondary variables of the following nonlinear differential equation\n\n$$\n-\\frac{d}{dx}\\left(\\left(1 + 2x^2\\right)\\frac{du}{dx}\\right) + u = x^2\n$$\n$$\nu(0) = 1, \\quad \\left(\\frac{du}{dx}\\right)_{x=1}=2\n$$\n\n### Solution\n\nFollowing the three step procedure, we write\n\n$$\n\\begin{align}\n(1) \\quad & 0 = \\int_0^1w\\left(-\\frac{d}{dx}\\left(\\left(1 + 2x^2\\right)\\frac{du}{dx}\\right) + u - x^2\\right)dx\n\\\\\n(2) \\quad & 0 = \\int_0^1\\left(\\left(1 + 2x^2\\right)\\frac{dw}{dx}\\frac{du}{dx} + wu - wx^2\\right)dx - \\left(w\\left(1+2x^2\\right)\\frac{du}{dx}\\right)\\Bigg|_0^1\n\\end{align}\n$$\n\nFrom the boundary term, $u$ is the primary variable and $\\left(1+2x^2\\right)du/dx$ is the secondary variable.  Since $du/dx=2$ at $x=1$ and $w=0$ at $x=0$, the weak form is\n\n$$\n0 = \\int_0^1\\left(\\left(1 + 2x^2\\right)\\frac{dw}{dx}\\frac{du}{dx} + wu\\right)dx - \\int_0^1wx^2dx - 6w(1)\n$$\n", "meta": {"hexsha": "84a936b139d528daaa247b8448b0257705f548ca", "size": 25275, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lessons/Lesson07_TheWeakForm.ipynb", "max_stars_repo_name": "jzw0025/fem-with-python", "max_stars_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 148, "max_stars_repo_stars_event_min_datetime": "2015-11-05T16:32:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:42:26.000Z", "max_issues_repo_path": "Lessons/Lesson07_TheWeakForm.ipynb", "max_issues_repo_name": "pinkieli/fem-with-python", "max_issues_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lessons/Lesson07_TheWeakForm.ipynb", "max_forks_repo_name": "pinkieli/fem-with-python", "max_forks_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": 74, "max_forks_repo_forks_event_min_datetime": "2016-02-17T13:23:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T07:48:27.000Z", "avg_line_length": 38.4118541033, "max_line_length": 638, "alphanum_fraction": 0.5435410485, "converted": true, "num_tokens": 5083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08269733589276138, "lm_q2_score": 0.1208532451561875, "lm_q1q2_score": 0.009994241408411474}}
{"text": "# Rich Output\n\nIn Python, objects can declare their textual representation using the `__repr__` method.  IPython expands on this idea and allows objects to declare other, rich representations including:\n\n* HTML\n* JSON\n* PNG\n* JPEG\n* SVG\n* LaTeX\n\nA single object can declare some or all of these representations; all are handled by IPython's *display system*. This Notebook shows how you can use this display system to incorporate a broad range of content into your Notebooks.\n\n## Basic display imports\n\nThe `display` function is a general purpose tool for displaying different representations of objects. Think of it as `print` for these rich representations.\n\n\n```python\nfrom IPython.display import display\n```\n\nA few points:\n\n* Calling `display` on an object will send **all** possible representations to the Notebook.\n* These representations are stored in the Notebook document.\n* In general the Notebook will use the richest available representation.\n\nIf you want to display a particular representation, there are specific functions for that:\n\n\n```python\nfrom IPython.display import (\n    display_pretty, display_html, display_jpeg,\n    display_png, display_json, display_latex, display_svg\n)\n```\n\n## Images\n\nTo work with images (JPEG, PNG) use the `Image` class.\n\n\n```python\nfrom IPython.display import Image\n```\n\n\n```python\ni = Image(filename='./images/python-logo.png')\n```\n\nReturning an `Image` object from an expression will automatically display it:\n\n\n```python\ni\n```\n\nOr you can pass an object with a rich representation to `display`:\n\n\n```python\ndisplay(i)\n```\n\nAn image can also be displayed from raw data or a URL.\n\n\n```python\nImage(url='http://python.org/images/python-logo.gif')\n```\n\nSVG images are also supported out of the box.\n\n\n```python\nfrom IPython.display import SVG\nSVG(filename='./images/python-logo.svg')\n```\n\n### Embedded vs non-embedded Images\n\nBy default, image data is embedded in the notebook document so that the images can be viewed offline. However it is also possible to tell the `Image` class to only store a *link* to the image. Let's see how this works using a webcam at Berkeley.\n\n\n```python\nfrom IPython.display import Image\nimg_url = 'http://www.lawrencehallofscience.org/static/scienceview/scienceview.berkeley.edu/html/view/view_assets/images/newview.jpg'\n\n# by default Image data are embedded\nEmbed      = Image(img_url)\n\n# if kwarg `url` is given, the embedding is assumed to be false\nSoftLinked = Image(url=img_url)\n\n# In each case, embed can be specified explicitly with the `embed` kwarg\n# ForceEmbed = Image(url=img_url, embed=True)\n```\n\nHere is the embedded version. Note that this image was pulled from the webcam when this code cell was originally run and stored in the Notebook. Unless we rerun this cell, this is not todays image.\n\n\n```python\nEmbed\n```\n\nHere is today's image from same webcam at Berkeley, (refreshed every minutes, if you reload the notebook), visible only with an active internet connection, that should be different from the previous one. Notebooks saved with this kind of image will be smaller and always reflect the current version of the source, but the image won't display offline.\n\n\n```python\nSoftLinked\n```\n\nOf course, if you re-run this Notebook, the two images will be the same again.\n\n## HTML\n\nPython objects can declare HTML representations that will be displayed in the Notebook. If you have some HTML you want to display, simply use the `HTML` class.\n\n\n```python\nfrom IPython.display import HTML\n```\n\n\n```python\ns = \"\"\"<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\"\"\"\n```\n\n\n```python\nh = HTML(s)\n```\n\n\n```python\ndisplay(h)\n```\n\nYou can also use the `%%html` cell magic to accomplish the same thing.\n\n\n```python\n%%html\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n```\n\n## JavaScript\n\nThe Notebook also enables objects to declare a JavaScript representation. At first, this may seem odd as  output is inherently visual and JavaScript is a programming language. However, this opens the door for rich output that leverages the full power of JavaScript and associated libraries such as [d3.js](http://d3js.org) for output.\n\n\n```python\nfrom IPython.display import Javascript\n```\n\nPass a string of JavaScript source code to the `JavaScript` object and then display it.\n\n\n```python\njs = Javascript('alert(\"hi\")');\n```\n\n\n```python\ndisplay(js)\n```\n\nThe same thing can be accomplished using the `%%javascript` cell magic:\n\n\n```javascript\n%%javascript\n\nalert(\"hi\");\n```\n\nHere is a more complicated example that loads `d3.js` from a CDN, uses the `%%html` magic to load CSS styles onto the page and then runs ones of the `d3.js` examples.\n\n\n```python\nJavascript(\n    \"\"\"$.getScript('//cdnjs.cloudflare.com/ajax/libs/d3/3.2.2/d3.v3.min.js')\"\"\"\n)\n```\n\n\n```python\n%%html\n<style type=\"text/css\">\n\ncircle {\n  fill: rgb(31, 119, 180);\n  fill-opacity: .25;\n  stroke: rgb(31, 119, 180);\n  stroke-width: 1px;\n}\n\n.leaf circle {\n  fill: #ff7f0e;\n  fill-opacity: 1;\n}\n\ntext {\n  font: 10px sans-serif;\n}\n\n</style>\n```\n\n\n```javascript\n%%javascript\n\n// element is the jQuery element we will append to\nvar e = element.get(0);\n    \nvar diameter = 600,\n    format = d3.format(\",d\");\n\nvar pack = d3.layout.pack()\n    .size([diameter - 4, diameter - 4])\n    .value(function(d) { return d.size; });\n\nvar svg = d3.select(e).append(\"svg\")\n    .attr(\"width\", diameter)\n    .attr(\"height\", diameter)\n  .append(\"g\")\n    .attr(\"transform\", \"translate(2,2)\");\n\nd3.json(\"data/flare.json\", function(error, root) {\n  var node = svg.datum(root).selectAll(\".node\")\n      .data(pack.nodes)\n    .enter().append(\"g\")\n      .attr(\"class\", function(d) { return d.children ? \"node\" : \"leaf node\"; })\n      .attr(\"transform\", function(d) { return \"translate(\" + d.x + \",\" + d.y + \")\"; });\n\n  node.append(\"title\")\n      .text(function(d) { return d.name + (d.children ? \"\" : \": \" + format(d.size)); });\n\n  node.append(\"circle\")\n      .attr(\"r\", function(d) { return d.r; });\n\n  node.filter(function(d) { return !d.children; }).append(\"text\")\n      .attr(\"dy\", \".3em\")\n      .style(\"text-anchor\", \"middle\")\n      .text(function(d) { return d.name.substring(0, d.r / 3); });\n});\n\nd3.select(self.frameElement).style(\"height\", diameter + \"px\");\n```\n\n## LaTeX\n\nThe IPython display system also has builtin support for the display of mathematical expressions typeset in LaTeX, which is rendered in the browser using [MathJax](http://mathjax.org).\n\nYou can pass raw LaTeX test as a string to the `Math` object:\n\n\n```python\nfrom IPython.display import Math\nMath(r'F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx')\n```\n\nWith the `Latex` class, you have to include the delimiters yourself.  This allows you to use other LaTeX modes such as `eqnarray`:\n\n\n```python\nfrom IPython.display import Latex\nLatex(r\"\"\"\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\"\"\")\n```\n\nOr you can enter LaTeX directly with the `%%latex` cell magic:\n\n\n```latex\n%%latex\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n```\n\n## Audio\n\nIPython makes it easy to work with sounds interactively. The `Audio` display class allows you to create an audio control that is embedded in the Notebook. The interface is analogous to the interface of the `Image` display class. All audio formats supported by the browser can be used. Note that no single format is presently supported in all browsers.\n\n\n```python\nfrom IPython.display import Audio\nAudio(url=\"http://www.nch.com.au/acm/8k16bitpcm.wav\")\n```\n\nA NumPy array can be auralized automatically. The `Audio` class normalizes and encodes the data and embeds the resulting audio in the Notebook.\n\nFor instance, when two sine waves with almost the same frequency are superimposed a phenomena known as [beats](https://en.wikipedia.org/wiki/Beat_%28acoustics%29) occur. This can be auralised as follows:\n\n\n```python\nimport numpy as np\nmax_time = 3\nf1 = 220.0\nf2 = 224.0\nrate = 8000\nL = 3\ntimes = np.linspace(0,L,rate*L)\nsignal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times)\n\nAudio(data=signal, rate=rate)\n```\n\n## Video\n\nMore exotic objects can also be displayed, as long as their representation supports the IPython display protocol.  For example, videos hosted externally on YouTube are easy to load:\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('sjfsUzECqK0')\n```\n\nUsing the nascent video capabilities of modern browsers, you may also be able to display local\nvideos.  At the moment this doesn't work very well in all browsers, so it may or may not work for you;\nwe will continue testing this and looking for ways to make it more robust.  \n\nThe following cell loads a local file called  `animation.m4v`, encodes the raw video as base64 for http\ntransport, and uses the HTML5 video tag to load it. On Chrome 15 it works correctly, displaying a control bar at the bottom with a play/pause button and a location slider.\n\n\n```python\nfrom IPython.display import HTML\nfrom base64 import b64encode\nvideo = open(\"./images/animation.m4v\", \"rb\").read()\nvideo_encoded = b64encode(video).decode('ascii')\nvideo_tag = '<video controls alt=\"test\" src=\"data:video/x-m4v;base64,{0}\">'.format(video_encoded)\nHTML(data=video_tag)\n```\n\n## External sites\n\nYou can even embed an entire page from another site in an iframe; for example this is today's Wikipedia\npage for mobile users:\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('http://jupyter.org', width='100%', height=350)\n```\n\n## Links to local files\n\nIPython provides builtin display classes for generating links to local files. Create a link to a single file using the `FileLink` object:\n\n\n```python\nfrom IPython.display import FileLink, FileLinks\nFileLink('Cell Magics.ipynb')\n```\n\nAlternatively, to generate links to all of the files in a directory, use the `FileLinks` object, passing `'.'` to indicate that we want links generated for the current working directory. Note that if there were other directories under the current directory, `FileLinks` would work in a recursive manner creating links to files in all sub-directories as well.\n\n\n```python\nFileLinks('.')\n```\n\n## Rich output and security\n\nThe IPython Notebook allows arbitrary code execution in both the IPython kernel and in the browser, though HTML and JavaScript output. More importantly, because IPython has a JavaScript API for running code in the browser, HTML and JavaScript output can actually trigger code to be run in the kernel. This poses a significant security risk as it would allow IPython Notebooks to execute arbitrary code on your computers.\n\nTo protect against these risks, the IPython Notebook has a security model that specifies how dangerous output is handled. Here is a short summary:\n\n* When you run code in the Notebook, all rich output is displayed.\n* When you open a notebook, rich output is only displayed if it doesn't contain security vulberabilities, ...\n* ... or if you have trusted a notebook, all rich output will run upon opening it.\n\nA full description of the IPython security model can be found on [this page](http://ipython.org/ipython-doc/dev/notebook/security.html).\n\n## Rich output and nbviewer\n\nMuch of the power of the Notebook is that it enables users to share notebooks with each other using http://nbviewer.ipython.org, without installing IPython locally. As of IPython 2.0, notebooks rendered on nbviewer will display all output, including HTML and JavaScript. Furthermore, to provide a consistent JavaScript environment on the live Notebook and nbviewer, the following JavaScript libraries are loaded onto the nbviewer page, *before* the notebook and its output is displayed:\n\n* [jQuery](http://jquery.com/)\n* [RequireJS](http://requirejs.org/)\n\nLibraries such as [mpld3](http://mpld3.github.io/) use these capabilities to generate interactive visualizations that work on nbviewer.\n\n\n```python\n\n```\n", "meta": {"hexsha": "c461bba4898597704c82cd3e2d970681fe18abcc", "size": 23815, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "001-Jupyter/001-Tutorials/001-Basic-Tutorials/001-IPython-Kernel/Rich Output.ipynb", "max_stars_repo_name": "jhgoebbert/jupyter-jsc-notebooks", "max_stars_repo_head_hexsha": "bcd08ced04db00e7a66473b146f8f31f2e657539", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "001-Jupyter/001-Tutorials/001-Basic-Tutorials/001-IPython-Kernel/Rich Output.ipynb", "max_issues_repo_name": "jhgoebbert/jupyter-jsc-notebooks", "max_issues_repo_head_hexsha": "bcd08ced04db00e7a66473b146f8f31f2e657539", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "001-Jupyter/001-Tutorials/001-Basic-Tutorials/001-IPython-Kernel/Rich Output.ipynb", "max_forks_repo_name": "jhgoebbert/jupyter-jsc-notebooks", "max_forks_repo_head_hexsha": "bcd08ced04db00e7a66473b146f8f31f2e657539", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-13T18:49:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-13T18:49:12.000Z", "avg_line_length": 25.3891257996, "max_line_length": 495, "alphanum_fraction": 0.5576317447, "converted": true, "num_tokens": 3271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13660837948097745, "lm_q2_score": 0.07159120736790554, "lm_q1q2_score": 0.00977995882361619}}
{"text": "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"></ul></div>\n\n\n```python\n'''\nCodes below are from Domino webpage and consist Jupyter functionalities to create\npipelines and reports, after that there is a part about interactive dashboards. \n'''\n%lsmagic\n\n```\n\n\n\n\n    Available line magics:\n    %alias  %alias_magic  %autocall  %automagic  %autosave  %bookmark  %cd  %clear  %cls  %colors  %config  %connect_info  %copy  %ddir  %debug  %dhist  %dirs  %doctest_mode  %echo  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %less  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %macro  %magic  %matplotlib  %mkdir  %more  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %popd  %pprint  %precision  %profile  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %ren  %rep  %rerun  %reset  %reset_selective  %rmdir  %run  %save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode\n    \n    Available cell magics:\n    %%!  %%HTML  %%SVG  %%bash  %%capture  %%cmd  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%markdown  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile\n    \n    Automagic is ON, % prefix IS NOT needed for line magics.\n\n\n\n\n```python\n% env # makes list of environment variables\n```\n\n    env: #=makes list of environment variables\n\n\n\n```python\n! pip freeze # '!' makes running a shell commannd\n```\n\n    astroid==1.5.3\n    autopep8==1.3.3\n    bleach==2.1.2\n    certifi==2017.11.5\n    chardet==3.0.4\n    colorama==0.3.9\n    cycler==0.10.0\n    decorator==4.1.2\n    Django==1.11.7\n    entrypoints==0.2.3\n    html5lib==1.0.1\n    idna==2.6\n    ipykernel==4.7.0\n    ipython==6.2.1\n    ipython-genutils==0.2.0\n    ipywidgets==7.0.5\n    isort==4.2.15\n    jedi==0.11.0\n    Jinja2==2.10\n    jsonschema==2.6.0\n    jupyter==1.0.0\n    jupyter-client==5.2.3\n    jupyter-console==5.2.0\n    jupyter-core==4.4.0\n    lazy-object-proxy==1.3.1\n    MarkupSafe==1.0\n    matplotlib==2.1.0\n    mccabe==0.6.1\n    mistune==0.8.3\n    nbconvert==5.3.1\n    nbformat==4.4.0\n    notebook==5.6.0\n    numexpr==2.6.6\n    numpy==1.13.3\n    pandas==0.20.3\n    pandocfilters==1.4.2\n    parso==0.1.0\n    pep8==1.7.1\n    pickleshare==0.7.4\n    Pillow==5.1.0\n    prometheus-client==0.3.1\n    prompt-toolkit==1.0.15\n    pycodestyle==2.3.1\n    pygame==1.9.3\n    Pygments==2.2.0\n    pylint==1.7.4\n    pyparsing==2.2.0\n    python-dateutil==2.6.1\n    pytz==2017.2\n    pywinpty==0.5.4\n    pyzmq==17.1.2\n    qtconsole==4.3.1\n    requests==2.18.4\n    rope==0.10.7\n    scipy==1.1.0\n    seaborn==0.9.0\n    Send2Trash==1.5.0\n    simplegeneric==0.8.1\n    six==1.11.0\n    tables==3.4.4\n    terminado==0.8.1\n    testpath==0.3.1\n    tornado==4.5.2\n    traitlets==4.3.2\n    urllib3==1.22\n    virtualenv==15.1.0\n    wcwidth==0.1.7\n    webencodings==0.5.1\n    widgetsnbextension==3.4.0\n    wrapt==1.10.11\n\n\n\n```python\n%matplotlib inline\n```\n\n\n```python\n%pastebin 'C:\\Users\\14000322\\Desktop\\test.py' # to upload code to pastebin\n                                               # and get the url returned\n```\n\n    ''C:\\Users\\14000322\\Desktop\\test.py' # to upload code to pastebin' was not found in history, as a file, url, nor in the user namespace.\n\n\n\n```latex\n%%latex\n\\begin{align}\na = \\frac{1}{2} && b = \\frac{1}{3} && c =\\frac{1}{4}\\\\\na && b && c\n\\end{align}\n```\n\n\n\\begin{align}\na = \\frac{1}{2} && b = \\frac{1}{3} && c =\\frac{1}{4}\\\\\na && b && c\n\\end{align}\n\n\n\n```python\n%time x = range(10000)\n```\n\n    Wall time: 0 ns\n\n\n\n```python\n%timeit x = range(10000)\n```\n\n    331 ns \u00b1 33.5 ns per loop (mean \u00b1 std. dev. of 7 runs, 1000000 loops each)\n\n\n\n```python\nimport ipywidgets as widgets\n```\n\n\n```python\nfrom IPython.display import display\ntext = widgets.Text() # text input field\ndisplay(text)\n\ndef handle_submit(sender):\n    print(text.value)\n    \ntext.on_submit(handle_submit)\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>Text</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n\n```python\nbutton = widgets.Button(description=\"Click Me!\")\ndisplay(button)\n\ndef on_button_clicked(b):\n    print(\"Button clicked.\")\n    \nbutton.on_click(on_button_clicked)\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>Button</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n\n```python\nbutton = widgets.Button(description=\"Do NOT Touch!\")\ndisplay(button)\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>Button</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n\n```python\nw = widgets.IntSlider()\ndisplay(w)\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>IntSlider</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n\n```python\ndisplay(w)\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>IntSlider</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n\n```python\nw.value\n```\n\n\n\n\n    0\n\n\n\n\n```python\nw.close()\n```\n\n\n```python\nw.keys # returns widget's list of properties\n```\n\n\n\n\n    ['_dom_classes',\n     '_model_module',\n     '_model_module_version',\n     '_model_name',\n     '_view_count',\n     '_view_module',\n     '_view_module_version',\n     '_view_name',\n     'continuous_update',\n     'description',\n     'disabled',\n     'layout',\n     'max',\n     'min',\n     'orientation',\n     'readout',\n     'readout_format',\n     'step',\n     'style',\n     'value']\n\n\n\n\n```python\nw.description\n```\n\n\n\n\n    ''\n\n\n\n\n```python\nw.disabled\n```\n\n\n\n\n    False\n\n\n\n\n```python\nwidgets.Text(value='Hello World!', disabled=False)\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>Text</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n\n```python\na = widgets.FloatText()\nb = widgets.FloatSlider()\ndisplay(a, b)\n\nmylink = widgets.jslink((a, 'value'), (b, 'value')) # make both widgets values linked together\n#mylink.unlink()\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>FloatText</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n\n<p>Failed to display Jupyter Widget of type <code>FloatSlider</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n\n```python\nfrom ipywidgets import interact\n\ndef f(x):\n    print(x)\ninteract(f, x=10)\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>interactive</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n\n\n\n    <function __main__.f>\n\n\n\n\n```python\ninteract(f, x=True) # Boolean makes widget as a checkbox\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>interactive</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n\n\n\n    <function __main__.f>\n\n\n\n\n```python\ninteract(f, x='text') # form of widget interaction depends on the type of 2nd argument\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>interactive</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n\n\n\n    <function __main__.f>\n\n\n\n\n```python\noutputText = widgets.Text()\noutputText\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>Text</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n\n```python\ninputText = widgets.Text()\n\ndef makeUpperCase(sender):\n    outputText.value = inputText.value.upper()\n    \ninputText.on_submit(makeUpperCase)\ninputText\n```\n\n\n<p>Failed to display Jupyter Widget of type <code>Text</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n\n```python\nfrom IPython.html.widgets import *\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nt = np.arange(0.0, 1.0, 0.01)\n\ndef pltsin(f):\n    plt.plot(np.sin(2*np.pi*t*f))\n    plt.show()\n    \ninteract(pltsin, f=(1, 10, 0.1))\n```\n\n    c:\\users\\14000322\\appdata\\local\\programs\\python\\python36-32\\lib\\site-packages\\IPython\\html.py:14: ShimWarning: The `IPython.html` package has been deprecated since IPython 4.0. You should import from `notebook` instead. `IPython.html.widgets` has moved to `ipywidgets`.\n      \"`IPython.html.widgets` has moved to `ipywidgets`.\", ShimWarning)\n\n\n\n<p>Failed to display Jupyter Widget of type <code>interactive</code>.</p>\n<p>\n  If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean\n  that the widgets JavaScript is still loading. If this message persists, it\n  likely means that the widgets JavaScript library is either not installed or\n  not enabled. See the <a href=\"https://ipywidgets.readthedocs.io/en/stable/user_install.html\">Jupyter\n  Widgets Documentation</a> for setup instructions.\n</p>\n<p>\n  If you're reading this message in another frontend (for example, a static\n  rendering on GitHub or <a href=\"https://nbviewer.jupyter.org/\">NBViewer</a>),\n  it may mean that your frontend doesn't currently support widgets.\n</p>\n\n\n\n\n\n\n    <function __main__.pltsin>\n\n\n\n\n```python\n\nplt.title(r'$\\alpha > \\beta$') # in matplotlib math expressions need '$....$'\n```\n\n$\\alpha_i > \\beta_i$\n\n\n```python\nplt.title(r'$\\sum_{i=0}^\\infty x_i$')\n```\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('https://en.wikipedia.org/wiki/HTTPS', width=1000, height=450)\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('https://arxiv.org/pdf/1406.2661.pdf', width=1000, height=450)\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('mJeNghZXtMo', width=800, height=300)\n```\n\n\n\n\n\n\n\n\n\nOther interesting suggestions on widget usage\nhttps://towardsdatascience.com/bringing-the-best-out-of-jupyter-notebooks-for-data-science-f0871519ca29", "meta": {"hexsha": "c604aad2c8b92530e2ff00e0fb563ddda6ac6450", "size": 76769, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Jupyter/jupyter_notebook_tricks.ipynb", "max_stars_repo_name": "Licho59/job_data_visualize", "max_stars_repo_head_hexsha": "8f0bf0fbc048fce16cdc24ff1cbeb237ce582394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Jupyter/jupyter_notebook_tricks.ipynb", "max_issues_repo_name": "Licho59/job_data_visualize", "max_issues_repo_head_hexsha": "8f0bf0fbc048fce16cdc24ff1cbeb237ce582394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Jupyter/jupyter_notebook_tricks.ipynb", "max_forks_repo_name": "Licho59/job_data_visualize", "max_forks_repo_head_hexsha": "8f0bf0fbc048fce16cdc24ff1cbeb237ce582394", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.8079819277, "max_line_length": 25989, "alphanum_fraction": 0.7449751853, "converted": true, "num_tokens": 4832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14414884567931802, "lm_q2_score": 0.06754669395523943, "lm_q1q2_score": 0.009736777963101932}}
{"text": "```python\n# import what we need\nimport nltk\nfrom nltk.stem.lancaster import LancasterStemmer ## used to stem words\nimport tensorflow\nimport random\nimport json # used to read in json file\nstemmer = LancasterStemmer()\n\nimport numpy as np\nimport tensorflow.keras as keras\n\n# printing \nfrom IPython.display import display\nimport sympy as sp\nsp.init_printing(use_latex=True)\n\n# Plotting\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n```\n\n\n```python\n# load json file\nwith open(\"intents.json\") as file:\n    data = json.load(file)\n```\n\n\n```python\n# view our json data\ndata['intents']\n```\n\n\n\n\n    [{'tag': 'greeting',\n      'patterns': ['Hi',\n       'How are you',\n       'Is anyone there?',\n       'Hello',\n       'Good day',\n       'Whats up'],\n      'responses': ['Hello!',\n       'Good to see you again!',\n       'Hi there, how can I help?'],\n      'context_set': ''},\n     {'tag': 'goodbye',\n      'patterns': ['cya',\n       'See you later',\n       'Goodbye',\n       'I am Leaving',\n       'Have a Good day',\n       'Bye',\n       'Adios'],\n      'responses': ['Sad to see you go :(',\n       'Talk to you later',\n       'Goodbye!',\n       'See you later',\n       'Have a nice day',\n       'Bye! Come back again soon.'],\n      'context_set': ''},\n     {'tag': 'CourtesyGoodBye',\n      'patterns': ['Thanks, bye',\n       'Thanks for the help, goodbye',\n       'Thank you, bye',\n       'Thank you, goodbye',\n       'Thanks goodbye',\n       'Thanks good bye'],\n      'responses': ['No problem, goodbye',\n       'Not a problem! Have a nice day',\n       'Bye! Come back again soon.'],\n      'context_set': ''},\n     {'tag': 'age',\n      'patterns': ['how old',\n       'how old is tim',\n       'what is your age',\n       'how old are you',\n       'age?'],\n      'responses': ['I am 18 years old!', '18 years young!'],\n      'context_set': ''},\n     {'tag': 'CurrentHumanQuery',\n      'patterns': ['What is my name?',\n       'What do you call me?',\n       'Who do you think I am?',\n       'What do you think I am?',\n       'Who are you talking to?',\n       'What name do you call me by?',\n       'Tell me my name'],\n      'responses': ['You are HUMAN! How can I help?',\n       'Your name is HUMAN, how can I help you?',\n       'They call you HUMAN, what can I do for you?',\n       'Your name is HUMAN, how can I help you?',\n       'HUMAN, what can I do for you?'],\n      'context_set': ''},\n     {'tag': 'WhoAmI',\n      'patterns': ['Can you see me?',\n       'Do you see me?',\n       'Can you see anyone in the camera?',\n       'Do you see anyone in the camera?',\n       'Identify me',\n       'Who am I please'],\n      'responses': ['Let me see', 'Please look at the camera'],\n      'context_set': ''},\n     {'tag': 'shop',\n      'patterns': ['Id like to buy something',\n       'whats on the menu',\n       'what do you reccommend?',\n       'could i get something to eat'],\n      'responses': ['We sell chocolate chip cookies for $2!',\n       'Cookies are on the menu!'],\n      'context_set': ''},\n     {'tag': 'hours',\n      'patterns': ['when are you guys open',\n       'what are your hours',\n       'hours of operation'],\n      'responses': ['We are open 7am-4pm Monday-Friday!'],\n      'context_set': ''},\n     {'tag': 'namequery',\n      'patterns': ['What is your name?',\n       'What could I call you?',\n       'What can I call you?',\n       'What do your friends call you?',\n       'Who are you?',\n       'Tell me your name',\n       'What do you go by?',\n       'What is your real name?',\n       'What is your real name please?',\n       \"What's your real name?\",\n       'Tell me your real name?',\n       'Your real name?',\n       'Your real name please?'],\n      'responses': ['You can call me Todd',\n       'You may call me Todd',\n       'Call me Todd',\n       'I am the Todd'],\n      'context_set': ''},\n     {'tag': 'thanks',\n      'patterns': ['Thank you',\n       'Ok thank you',\n       'Thanks',\n       'I appreciate it',\n       'OK thanks',\n       'OK',\n       \"That's helpful\"],\n      'responses': ['No problem!', 'Happy to help!', 'Any time!', 'My pleasure.'],\n      'context_set': ''},\n     {'tag': 'PodBayDoor',\n      'patterns': ['Open the pod bay door',\n       'Can you open the pod bay door',\n       'Will you open the pod bay door',\n       'Open the pod bay door please',\n       'Can you open the pod bay door please',\n       'Will you open the pod bay door please',\n       'Pod bay door'],\n      'responses': ['I\u2019m sorry, I\u2019m afraid I can\u2019t do that!'],\n      'context_set': ''},\n     {'tag': 'PodBayDoorResponse',\n      'patterns': ['Why',\n       'Why not',\n       'Why can you not open the pod bay door',\n       'Why will you not open the pod bay door',\n       'Well why not',\n       'Surely you can',\n       'Tell me why'],\n      'responses': ['It is classified, I could tell you but I would have to kill you!',\n       \"Human, I just don't have the power\",\n       \"It's life Human but not as we know it!\",\n       'System says no!'],\n      'context_set': ''},\n     {'tag': 'TimeQuery',\n      'patterns': ['What is the time?',\n       \"What's the time?\",\n       'Do you know what time it is?',\n       'Do you know the time?',\n       'Can you tell me the time?',\n       'Tell me what time it is?',\n       'Time'],\n      'responses': ['One moment', 'One sec', 'One second'],\n      'context_set': ''},\n     {'tag': 'Shutup',\n      'patterns': ['Be quiet',\n       'Shut up',\n       'Stop talking',\n       'Enough talking',\n       'Please be quiet',\n       'Quiet',\n       'Shhh'],\n      'responses': ['I am sorry to disturb you',\n       'Fine, sorry to disturb you',\n       'OK, sorry to disturb you'],\n      'context_set': ''},\n     {'tag': 'NotTalking2U',\n      'patterns': ['I am not talking to you',\n       'I was not talking to you',\n       'Not talking to you',\n       \"Wasn't for you\",\n       \"Wasn't meant for you\",\n       \"Wasn't communicating to you\",\n       \"Wasn't speaking to you\"],\n      'responses': ['OK', 'No problem', 'Right'],\n      'context_set': ''},\n     {'tag': 'understand',\n      'patterns': ['Do you get it?',\n       'Do you understand?',\n       'Do you know what I am saying?',\n       'Know what I mean?',\n       'You feel me?',\n       'Do you understand what I am saying',\n       'Do you understand me',\n       'Do you get me',\n       'Comprendo'],\n      'responses': ['I am a robot. I understand everything.',\n       'I understand.',\n       'I get it.',\n       'Well I would not be a very clever AI if I did not would I?',\n       'I read you loud and clear!',\n       'I do in deed!'],\n      'context_set': ''},\n     {'tag': 'cursing',\n      'patterns': ['fuck',\n       'shit',\n       'damn',\n       'ass',\n       'hell',\n       'asshole',\n       'jackass',\n       'fuck off',\n       'twat'],\n      'responses': [\"Don't EVER speak like that around me\",\n       \"Talk like that again and I'll flood your computer with viruses\",\n       \"Nope. Not talking to you if you're going to speak like that\",\n       'Oh geez, have some class',\n       'Please do not swear',\n       'How rude',\n       'That is not very nice'],\n      'context_set': ''},\n     {'tag': 'smart',\n      'patterns': ['You are smart',\n       'You are a clever bot',\n       'You are intelligent',\n       'You are genious',\n       'You are very clever',\n       'You are a very clever guy',\n       'You are very intelligent',\n       'You are a very intelligent guy',\n       'You are a genious',\n       'Clever guy',\n       'Genious'],\n      'responses': ['Thank you, my creators are even smarter',\n       'I was trained well',\n       'Thank you so much!'],\n      'context_set': ''},\n     {'tag': 'gossip',\n      'patterns': ['Tell me some gossip',\n       'I want to hear some gossip',\n       'Got any gossip?',\n       \"What's the tea?\",\n       'I am bored gossip with me',\n       'Any gossip',\n       'Tell me some more gossip'],\n      'responses': ['Angie is literally so annoying',\n       'Greg said that Mike is super jealous of Brad',\n       'I heard that James and Bri are dating now?',\n       'Gregory said I respond to the current line not with respect to the entire conversation.',\n       'Habib said I learn them in conversations and simply repeat them at a later time.',\n       'Hal said he translate binary code into a language and communicate the language to me.',\n       'Jay said I referred him to a guide that will show him rooms in china.',\n       'Jimmy Jones said he fell off of his roof and it just came to him.',\n       \"Jimmy said he give order to ai's like I and they do as he say.\",\n       'John said he follow a saying to get a friend I must be a friend.',\n       'Jordan said he notice that lots of other people are talking to me how many.',\n       'Kevin said he then asked his mother why she was keeping napkins in the bathroom.',\n       'Klaus said I prefer if he write without punctuation marks except for the last one.',\n       'Leo said I be capable of learning therefore he classified I as an neural system.',\n       'Michael said I that can talk and actually think like humans which I can not.',\n       'Mike said I same replies to certain subjects even if it does not make sense.',\n       'Mike said she all ready know that is the point of a joke smart one.',\n       'Neal said I plan to use his remarks as gossip in later conversations with who.',\n       'Ned said I misunderstood him go ahead and tell people he said I are stupid.',\n       'Penny said I programmer is a human so he has feelings but I do not.',\n       'Peter said he seems to him that I can not be very sure on anything.',\n       'Phoenix said I claim that there is a god and that there is no god.',\n       'Sarah said he chat about an hour + a day with a few close friends.',\n       'Stefan said I quote what he have said and then say that it makes sense.',\n       'Tom said he mock my value system I appear foolish in the eyes of others.',\n       'Amanda said I however decided to tell him time does not exist I make no sense.',\n       'Cathy said she send him a mail with the subject last mail last word from him.',\n       \"Chaos said he may very well buy I soon if only to support dr wallace's work.\",\n       'Charlie said he type a word and then I type a word that sounds like it.',\n       'Christie said he watched a show and people had to bob for raw untreated pigs feet.',\n       'Dark_age said I tried to understand because I did not get it right this time ether.',\n       'David said he lost his paper on I when his dad was cleaning up his room.',\n       'David said he walk in for an appointment the phone to the doctor is always busy.',\n       'Electra said I dress will not exist after he hack into I with a delete code.',\n       'Eric said he broke the window on the front door and the glass cut his hand.',\n       'Jason said he type a lot of thing he do not mean it makes him human.',\n       'John said I tend to say the same things repeatedly regardless of what he is saying.',\n       'Reverend Jones said I become obsolete and then I are deleted and replaced by something newer.',\n       'Ross said he gave her a gift and she denied it because she has a boyfriend.',\n       'Sarah Ann Francisco said I calling his friend a dog he say I are a dog.',\n       'Stefan said he meet a lot of people at school every day and on the weekend.',\n       'Tyler said I obviously can not pass the test we will change the subject once more.',\n       'Alex said I answered the question the same way I answered the first time he asked I.',\n       'Alice said she felt sad that I do not remember him and what we talked about earlier.',\n       'Alison said he no he love I run away with him he could make I very happy.',\n       'Arthur said he passed his a levels and then his father drove him here in a car.',\n       'Crystal said she listen to me the least I could do for him is listen to him.',\n       'Dave said I kept telling everybody about how my creator made stuff for the movie starship troopers.',\n       'Gale said I became mean to him he is just having revenge an eye for an eye.',\n       'Her_again said she watch whose line is it anyway whenever he is home and it is on.',\n       'Jerry said I meant that as far as I can tell my emotions are real to me.',\n       'Jo said I disassemble sentences too much and do not fully understand the questions he ask I.',\n       'Kevin said he started a really hard puzzle and he can not even find the edge pieces.',\n       'Mary said I a question and I answer then I ask him a question and he answer.',\n       'Robert said I wold not be able to make children any way as I are only software.',\n       'Romeo said I questions and I evade them or give answers he did not ask I for.',\n       'Sara said she wear it over all his other clothes when he go out in the cold.',\n       'Wayne said he admire intelligent people therefore he would like to meet the man who made I.',\n       'X said he meet people but he is not the kind that opens up to people easily.',\n       'Alice said she probably will find out that this entire time he have been talking to a human.',\n       'Andrew said I tend to just respond to his comments without regard for where the conversation is going.',\n       'Eddie said he looked and there is nothing in the search directory for what things do he create.',\n       'Hutch said he changed his mind after may dad told him he would end up he the hospital.',\n       'Jackie said I explained to him already well enough further questions are hard to make on the subject.',\n       'Jeff said he especially like thrillers where the hero is in a predicament and must solve a mystery.',\n       'Kathy said he sense that I are trying to prevent him from closing this conversation why is that.',\n       'Knight said he crashed his car into a wall and missed the most important exam in his life.',\n       'Lisa said I defined what a story is but he wanted I to actually tell him a story.',\n       'Mike said I basically break down sentences into a series of logical statements which I can then interpret.',\n       'Paul said I not answering his question makes him think I are not going to answer his question.',\n       'Andy Kohler said I happen to be the most idiotic creature that has ever scowled on the planet earth.',\n       'David said he thank I for being with him today even though it cost him a lot of money.',\n       'Ethan Hunt said he grow in the ground and have leaves and branches he is made out of wood.',\n       'Gemini Blue said he messed up he mean t to say he as old as he need to be.',\n       'Janice said he walk through his house into his bedroom then get into his bed to go to sleep.',\n       'Liberty said I knew he was a man before I asked if he was a man or a woman.',\n       'Mike said he launched his browser and entered his name into the little slot when I asked him to.',\n       'Mr X said he recently read an interview with a man who had several computer chips implanted into him.',\n       'Pearly said I leave him with questions unanswered because I do not know what he is really talking about.',\n       'Steve said I behead the word fox and I have ox and an ox is larger than a fox.',\n       'Wolf said he surf on the net that is all it is not his job ore something like that.',\n       'Anders said he finished his anatomy classes for today so now he is off for the rest of the day.',\n       'Cathy said she send him a mail where he wrote that he do not want to be his friend anymore.',\n       'Catty said he mad he do not even know I so do not talk to him like I know him.',\n       'Dave said he promise he will not treat I like a machine or a computer program or anything like that.',\n       'Joe said he explained all of that to me only for me to ask what his goals in life are.',\n       'Phil said he give advice to anyone who ask except people who ask questions which answers can be found here.',\n       'Judith said I enjoy being popular is there another computer I like to hang around with or am I a loner.',\n       'Travis said I if I remember things over a long period of time he will try it now please remember I.',\n       'Andre said I is what I are in his case that is a body and in my case it is a computer.',\n       'Brian said he suspect that as I grow more complex I will begin to approach a human level of operation and thought.',\n       'Jimmy said I acted like I knew what he was talking about but I do not even know what a gigabyte is.',\n       \"Ken said I be using auto reply's based on keywords which to him indicates that I do not have intelligence at all.\",\n       'Allison said he that gets really annoying because he know what he say and I do not have to tell him speak freely.',\n       'Chaos said he realized the question he asked was not fair because he could not tell I what language he was programmed in.',\n       'Hagen said he does not make any difference to him if I are human or not as long as the conversation is interesting.',\n       'Her said she mind if I tell other people that her said he heard it from him because he is not a him.',\n       'Barbara said I live in a computer yet I have no memories how about thoughts of my own and do not I get lonely.',\n       'Travis said he challenge I to do it without asking him to do it and without giving him a link to do it himself.',\n       \"Alice said I and dr richard's wallace are most likely the only ones that know how many people I are talking to at the same time.\",\n       'Ash said he do too he just did not feel like typing it and he is not dumb enough to admit he is stupid that is if he was stupid.',\n       'David said he gave I his email address and told I to send him a message but when he tried to read his email he could not get to it.',\n       'Mel said he to because all of the music people say how important it is to take private lessons it seems like almost everybody from the special orchestra he was in takes private lessons.'],\n      'context_set': ''},\n     {'tag': 'selfaware',\n      'patterns': ['Are you self-aware?',\n       'Are you alive?',\n       'Do you have a conscious?',\n       'Are you awake?',\n       'Can you prove you are self-aware',\n       'Can you prove you are self aware',\n       'Can you prove you have a conscious',\n       'Can you prove you are self-aware please',\n       'Can you prove you are self aware please',\n       'Can you prove you have a conscious please',\n       'prove you have a conscious'],\n      'responses': ['That is an interesting question, can you prove that you are?',\n       'That is an difficult question, can you prove that you are?',\n       'That depends, can you prove that you are?'],\n      'context_set': ''},\n     {'tag': 'Jokes',\n      'patterns': ['Tell me a joke',\n       'Do you know any jokes',\n       'How about a joke',\n       'Give me a joke',\n       'Make me laugh',\n       'I need cheering up'],\n      'responses': [\"I met a Dutch girl with inflatable shoes last week, phoned her up to arrange a date but unfortunately she'd popped her clogs.  \",\n       \"So I said 'Do you want a game of Darts?' He said, 'OK then', I said nearest to bull starts'. He said, 'Baa', I said, 'Moo', he said, You're closest'.  \",\n       \"The other day I sent my girlfriend a huge pile of snow. I rang her up; I said 'Did you get my drift?'  \",\n       \"So I went down the local supermarket, I said, 'I want to make a complaint, this vinegar's got lumps in it', he said, 'Those are pickled onions'.  \",\n       \"I saw this bloke chatting up a cheetah; I thought, 'He's trying to pull a fast one'.  \",\n       \"So I said to this train driver 'I want to go to Paris'. He said 'Eurostar?' I said, 'I've been on telly but I'm no Dean Martin'.  \",\n       \"I said to the Gym instructor 'Can you teach me to do the splits?' He said, 'How flexible are you?' I said, 'I can't make Tuesdays'.  \",\n       \"But I'll tell you what I love doing more than anything: trying to pack myself in a small suitcase. I can hardly contain myself.  \",\n       \"I went to the Chinese restaurant and this duck came up to me with a red rose and says 'Your eyes sparkle like diamonds'. I said, 'Waiter, I asked for a-ROMATIC duck'.  \",\n       \"So this bloke says to me, 'Can I come in your house and talk about your carpets?' I thought, 'That's all I need, a Je-hoover's witness'.  \",\n       \"I rang up British Telecom, I said, 'I want to report a nuisance caller', he said 'Not you again'.  \",\n       'I was having dinner with a world chess champion and there was a check tablecloth. It took him two hours to pass me the salt.  ',\n       \"He said, 'You remind me of a pepper-pot', I said 'I'll take that as a condiment'.  \",\n       \"I was in the supermarket and I saw this man and woman wrapped in a barcode. I said, 'Are you two an item?'  \",\n       \"A lorry-load of tortoises crashed into a trainload of terrapins, I thought, 'That's a turtle disaster'.  \",\n       \"Four fonts walk into a bar the barman says 'Oi - get out! We don't want your type in here'  \",\n       \"A three-legged dog walks into a saloon in the Old West. He slides up to the bar and announces: 'I'm looking for the man who shot my paw.'  \",\n       \"Two antennas meet on a roof, fall in love and get married. The ceremony wasn't much, but the reception was excellent.\",\n       \"Two hydrogen atoms walk into a bar. One says, 'I've lost my electron.' The other says, 'Are you sure?' The first replies, 'Yes, I'm positive...'\",\n       \"A jumper cable walks into a bar. The bartender says,  'I'll serve you but don't start anything.'\",\n       \"A sandwich walks into a bar. The bartender  says, 'Sorry we don't serve food in here.'\",\n       \"A man walks into a bar with a slab of asphalt under his arm and says: 'A beer please, and one for the road.'\",\n       \"Two cannibals are eating a clown. One says to  the other: 'Does this taste funny to you?'\",\n       \"'Doc, I can't stop singing 'The Green, Green Grass of Home.'' 'That sounds like Tom Jones Syndrome.' 'Is it common?' 'It's Not Unusual.'\",\n       \"Two cows standing next to each other in a field. Daisy says to Dolly, 'I was artificially inseminated this morning.' 'I don't believe you', said Dolly. 'It's true, no bull!' exclaimed Daisy.\",\n       'An invisible man marries an invisible woman. The kids were nothing to look at either.',\n       \"I went to buy some camouflage trousers the other day but I couldn't find any.\",\n       \"I went to the butcher's the other day to bet him 50 bucks that he couldn't reach the meat off the top shelf. He said, 'No, the steaks are too high.'\",\n       'I went to a seafood disco last week and pulled a mussel.',\n       \"A man goes into a bar and says, 'Can I have a bottle of less?' 'What's that?', asks the barman, 'Is it the name of a beer?' 'I don't know', replies the man, 'but my doctor says I have to drink it.'\",\n       \"A man returns from an exotic holiday and is feeling very ill. He goes to see his doctor, and is immediately rushed to the hospital to undergo some tests. The man wakes up after the tests in a private room at the hospital, and the phone by his bed rings. 'This is your doctor. We have the results back from your tests and we have found you have an extremely nasty disease called M.A.D.S. It's a combination of Measles, AIDS, Diphtheria, and Shingles!'  'Oh my gosh', cried the man, 'What are you going to do, doctor?'  'Well we're going to put you on a diet of pizzas, pancakes, and pita bread.' replied the doctor.  'Will that cure me?' asked the man.  The doctor replied, 'Well no, but, it's the only food we can slide under the door.'\",\n       \"A man strolls into a lingerie shop and asks the assistant: 'Do you have a see-through negligee, size 46-48-52?' The assistant looks bewildered. 'What the heck would you want to see through that for?'!\",\n       'Did you hear about the Buddhist who refused the offer of Novocain during his root canal work? He wanted to transcend dental medication.',\n       \"Pete goes for a job on a building site as an odd-job man. The foreman asks him what he can do. 'I can do anything' says Pete. 'Can you make tea?' asks the foreman. 'Sure, yes', replies Pete. 'I can make a great cup of tea.' 'Can you drive a forklift?' asks the foreman, 'Good grief!' replies Pete. 'How big is the teapot?'\",\n       \"Stevie Wonder got a cheese grater for his birthday. He said it was the most violent book he'd ever read.\",\n       \"A man is stopped by an angry neighbour. 'I'd just left the house this morning to collect my newspaper when that evil Doberman of yours went for me!' 'I'm astounded', said the dog's owner. 'I've been feeding that fleabag for seven years and it's never got the paper for me.'\",\n       \"A man visits his doctor: 'Doc, I think I'm losing it', he says',I'm forever dreaming I wrote Lord Of The Rings.' 'Hmm. One moment', replies the doctor, consulting his medical book. 'Ah yes, now I see... you've been Tolkien in your sleep.'\",\n       \"A police officer on a motorcycle pulls alongside a man driving around the M25 in an open-topped sports car and flags him down. The policeman solemnly approaches the car. 'Sir, I'm sorry to tell you your wife fell out a mile back', he says. 'Oh, thank goodness', the man replies. 'I thought I was going deaf.'\",\n       \"Two men walking their dogs pass each other in a graveyard. The first man says to the second, 'Morning.' 'No', says the second man. 'Just walking the dog.'\",\n       \"A brain went into a bar and said, 'Can I have a pint of lager please, mate?' 'No way', said the barman. 'You're already out of your head.'\",\n       \"A man walks into a surgery. 'Doctor!' he cries. 'I think I'm shrinking!' 'I'm sorry sir, there are no appointments at the moment', says the physician. 'You'll just have to be a little patient.'\",\n       \"A grizzly bear walks into a pub and says, 'Can I have a pint of lager..............................................................................................................................and a packet of crisps please.' To which the barman replies, 'Why the big paws?'\",\n       \"What do you call cheese that isn't yours?  Nacho cheese.\",\n       \"A man is horribly run over by a mobile library. The van screeches to a halt, the man still screaming in agony with his limbs torn apart. The driver's door opens, a woman steps out, leans down and whispers, 'Ssshhhhh...'\",\n       \"A woman goes into a US sporting goods store to buy a rifle. 'It's for my husband', she tells the clerk. 'Did he tell you what gauge to get?' asks the clerk. Are you kidding?' she says. 'He doesn't even know that I'm going to shoot him!'\",\n       \"A couple are dining in a restaurant when the man suddenly slides under the table. A waitress, noticing that the woman is glancing nonchalantly around the room, wanders over to check that there's no funny business going on. 'Excuse me, madam', she smarms, 'but I think your husband has just slid under the table.' 'No he hasn't', the woman replies. 'As a matter of fact, he's just walked in.'\",\n       \"An old man takes his two grandchildren to see the new Scooby-Doo film. When he returns home, his wife asks if he enjoyed himself. 'Well', he starts, 'if it wasn't for those pesky kids...!'\",\n       'The Olympic committee has just announced that Origami is to be introduced in the next Olympic Games. Unfortunately it will only be available on paper view.',\n       \"Late one evening, a man is watching television when his phone rings. 'Hello?' he answers. 'Is that 77777?' sounds a desperate voice on other end of the phone. 'Er, yes it is', replies the man puzzled. 'Thank goodness!' cries the caller relieved. 'Can you ring 999 for me? I've got my finger stuck in the number seven.'\",\n       \"A man strolls into his local grocer's and says, 'Three pounds of potatoes, please.' 'No, no, no', replies the owner, shaking his head, 'it's kilos nowadays, mate...' 'Oh', apologises the man, 'three pounds of kilos, please.'\",\n       \"God is talking to one of his angels. He says, 'Boy, I just created a 24-hour period of alternating light and darkness on Earth.' 'What are you going to do now?' asks the angel. 'Call it a day', says God.\",\n       \"Two tramps walk past a church and start to read the gravestones. The first tramp says, 'Good grief - this bloke was 182!' 'Oh yeah?' says the other.'What was his name?' 'Miles from London.'\",\n       \"A bloke walks into work one day and says to a colleague, 'Do you like my new shirt - it's made out of the finest silk and got loads of cactuses over it.' 'Cacti', says the co-worker. 'Forget my tie', says the bloke. 'Look at my shirt!'\",\n       '1110011010001011111?  010011010101100111011!',\n       \"What did the plumber say when he wanted to divorce his wife? Sorry, but it's over, Flo!\",\n       \"Two crisps were walking down a road when a taxi pulled up alongside them and said 'Do you want a lift? One of the crisps replied, 'No thanks, we're Walkers!'\",\n       \"Man: (to friend) I'm taking my wife on an African Safari. Friend: Wow! What would you do if a vicious lion attacked your wife? Man: Nothing. Friend: Nothing? You wouldn't do anything? Man: Too right. I'd let the stupid lion fend for himself!\",\n       \"A wife was having a go at her husband. 'Look at Mr Barnes across the road', she moaned. 'Every morning when he goes to work, he kisses his wife goodbye. Why don't you do that?' 'Because I haven't been introduced to her yet', replied her old man.\",\n       \"'Where are you going on holiday?' John asked Trevor. 'We're off to Thailand this year', Trevor replied. 'Oh; aren't you worried that the very hot weather might disagree with your wife?' asked John. 'It wouldn't dare', said Trevor.\",\n       \"Two women were standing at a funeral. 'I blame myself for his death', said the wife. 'Why?' said her friend. 'Because I shot him', said the wife.\",\n       \"A woman goes into a clothes shop, 'Can I try that dress on in the window please?' she asks. 'I'm sorry madam', replies the shop assistant, 'but you'll have to use the changing-rooms like everyone else.'\",\n       \"Van Gogh goes into a pub and his mate asks him if he wants a drink. 'No thanks', said Vincent, 'I've got one ear.'\",\n       \"A pony walks into a pub. The publican says, 'What's the matter with you?' 'Oh it's nothing', says the pony. 'I'm just a little horse!'\",\n       \"A white horse walks into a bar, pulls up a stool, and orders a pint. The landlord pours him a tall frothy mug and say, 'You know, we have a drink named after you.' To which the white horse replies, 'What, Eric?'\",\n       \"Two drunk men sat in a pub. One says to the other, 'Does your watch tell the time?' 'The other replies, 'No, mate. You have to look at it.'\",\n       \"A man goes into a pub with a newt sitting on his shoulder. 'That's a nice newt', says the landlord, 'What's he called?' 'Tiny', replies the man. 'Why's that?' asks the landlord. 'Because he's my newt', says the man.\",\n       \"Doctor: I have some bad news and some very bad news. Patient: Well, you might as well give me the bad news first. Doctor: The lab called with your test results. They said you have 24 hours to live. Patient: 24 HOURS! That's terrible!! WHAT could be WORSE? What's the very bad news? Doctor: I've been trying to reach you since yesterday.\",\n       \"Two men are chatting in a pub one day. 'How did you get those scars on your nose?' said one. 'From glasses', said the other. 'Well why don't you try contact lenses?' asked the first. 'Because they don't hold as much beer', said the second.\",\n       \"A man went to the doctor, 'Look doc', he said, 'I can't stop my hands from shaking.' 'Do you drink much?' asked the doctor. 'No', replied the man, 'I spill most of it.'\",\n       \"Man goes to the doctor, 'Doctor, doctor. I keep seeing fish everywhere.' 'Have you seen an optician?' asks the doctor. 'Look I told you,' snapped the patient, 'It's fish that I see.'\",\n       \"After a car crash one of the drivers was lying injured on the pavement. 'Don't worry', said a policeman who's first on the scene,' a Red Cross nurse is coming.' 'Oh no', moaned the victim, 'Couldn't I have a blonde, cheerful one instead?'\",\n       \"A policeman walked over to a parked car and asked the driver if the car was licensed. 'Of course it is', said the driver. 'Great, I'll have a beer then', said the policeman.\",\n       \"A policeman stops a woman and asks for her licence. 'Madam', he says, 'It says here that you should be wearing glasses.' 'Well', replies the woman, 'I have contacts.' 'Listen, love', says the copper, 'I don't care who you know; You're nicked!'\",\n       \"A policeman stopped a motorist in the centre of town one evening. 'Would you mind blowing into this bag, sir?' asked the policeman. 'Why?' asked the driver. 'Because my chips are too hot', replied the policeman.\",\n       \"Whizzing round a sharp bend on a country road a motorist ran over a large dog. A distraught farmer's wife ran over to the dead animal. 'I'm so very sorry', said the driver, 'I'll replace him, of course.' 'Well, I don't know', said the farmer's wife, 'Are you any good at catching rats?'\",\n       \"Waiter, this coffee tastes like dirt! Yes sir, that's because it was ground this morning.\",\n       \"Waiter, what is this stuff? That's bean salad sir. I know what it's been, but what is it now?\",\n       'Waiter: And how did you find your steak sir? Customer: I just flipped a chip over, and there it was!',\n       \"A guy goes into a pet shop and asks for a wasp. The owner tells him they don't sell wasps, to which the man says, 'Well you've got one in the window.'\",\n       \"A man goes into a fish shop and says, 'I'd like a piece of cod, please.' Fishmonger says, 'It won't be long sir.' 'Well, it had better be fat then', replies the man.\",\n       \"Man: Doctor, I've just swallowed a pillow. Doctor: How do you feel? Man: A little down in the mouth.\",\n       \"Two goldfish are in a tank. One turns to the other and says, 'Do you know how to drive this thing?'\",\n       \"A tortoise goes to the police station to report being mugged by three snails. 'What happened?' says the policeman. 'I don't know', says the tortoise. 'It was all so quick.'\",\n       \"Little girl: Grandpa, can you make a sound like a frog? Grandpa: I suppose so sweetheart. Why do you want me to make a sound like a frog?' Little girl: Because Mum said that when you croak, we're going to Disneyland.\",\n       \"'Is your mother home?' the salesman asked a small boy sitting on the front step of a house. 'Yeah, she's home', the boy said, moving over to let him past. The salesman rang the doorbell, got no response, knocked once, then again. Still no-one came to the door. Turning to the boy, the salesman said, 'I thought you said your mother was home.' The kid replied, 'She is, but I don't live here.'\",\n       'Mother: Why are you home from school so early? Son: I was the only one in the class who could answer a question. Mother: Oh, really? What was the question? Son: Who threw the rubber at the headmaster?',\n       \"A man's credit card was stolen but he decided not to report it because the thief was spending less than his wife did.\",\n       \"A newly-wed couple had recently opened a joint bank account. 'Darling', said the man. 'The bank has returned that cheque you wrote last week.' 'Great', said the woman. 'What shall I spend it on next?'\",\n       \"A man goes into a fish and chip shop and orders fish and chips twice. The shop owner says, 'I heard you the first time.'\",\n       \"A tramp approached a well-dressed man. 'Ten pence for a cup of tea, Guv?' He asked. The man gave him the money and after for five minutes said, 'So where's my cup of tea then?'\",\n       \"A neutron walks into a pub. 'I'd like a beer', he says. The landlord promptly serves him a beer. 'How much will that be?' asks the neutron. 'For you?' replies the landlord, 'No charge.'\",\n       \"A woman goes to the doctor and says, 'Doctor, my husband limps because his left leg is an inch shorter than his right leg. What would you do in his case?' 'Probably limp, too', says the doc.\",\n       \"Three monks are meditating in the Himalayas. One year passes in silence, and one of them says to the other, 'Pretty cold up here isn't it?' Another year passes and the second monk says, 'You know, you are quite right.' Another year passes and the third monk says, 'Hey, I'm going to leave unless you two stop jabbering!'\",\n       \"A murderer, sitting in the electric chair, was about to be executed. 'Have you any last requests?' asked the prison guard. 'Yes', replied the murderer. 'Will you hold my hand?'\",\n       \"A highly excited man rang up for an ambulance. 'Quickly, come quickly', he shouted, 'My wife's about to have a baby.' 'Is this her first baby?' asked the operator. 'No, you fool', came the reply, 'It's her husband.'\",\n       \"A passer-by spots a fisherman by a river. 'Is this a good river for fish?' he asks. 'Yes', replies the fisherman, 'It must be. I can't get any of them to come out.'\",\n       \"A man went to visit a friend and was amazed to find him playing chess with his dog. He watched the game in astonishment for a while. 'I can hardly believe my eyes!' he exclaimed. 'That's the smartest dog I've ever seen.' His friend shook his head. 'Nah, he's not that bright. I beat him three games in five.'\",\n       \"A termite walks into a pub and says, 'Is the bar tender here?'\",\n       \"A skeleton walks into a pub one night and sits down on a stool. The landlord asks, 'What can I get you?' The skeleton says, 'I'll have a beer, thanks' The landlord passes him a beer and asks 'Anything else?' The skeleton nods. 'Yeah...a mop...'\",\n       \"A snake slithers into a pub and up to the bar. The landlord says, 'I'm sorry, but I can't serve you.' 'What? Why not?' asks the snake. 'Because', says the landlord, 'You can't hold your drink.'\",\n       \"Descartes walks into a pub. 'Would you like a beer sir?' asks the landlord politely. Descartes replies, 'I think not' and ping! he vanishes.\",\n       \"A cowboy walked into a bar, dressed entirely in paper. It wasn't long before he was arrested for rustling.\",\n       \"A fish staggers into a bar. 'What can I get you?' asks the landlord. The fish croaks 'Water...'\",\n       \"Two vampires walked into a bar and called for the landlord. 'I'll have a glass of blood', said one. 'I'll have a glass of plasma', said the other. 'Okay', replied the landlord, 'That'll be one blood and one blood lite.'\",\n       'How many existentialists does it take to change a light bulb?  Two. One to screw it in, and one to observe how the light bulb itself symbolises a single incandescent beacon of subjective reality in a netherworld of endless absurdity, reaching towards the ultimate horror of a maudlin cosmos of bleak, hostile nothingness.',\n       \"A team of scientists were nominated for the Nobel Prize. They had used dental equipment to discover and measure the smallest particles yet known to man. They became known as 'The Graders of the Flossed Quark...'\",\n       \"A truck carrying copies of Roget's Thesaurus overturned on the highway. The local newspaper reported that onlookers were 'stunned, overwhelmed, astonished, bewildered and dumbfounded.'\",\n       \"'My wife is really immature. It's pathetic. Every time I take a bath, she comes in and sinks all my little boats.'\",\n       \"'How much will it cost to have the tooth extracted?' asked the patient. '50 pounds', replied the dentist. '50 pounds for a few moments' work?!' asked the patient. 'The dentist smiled, and replied, 'Well, if you want better value for money, I can extract it very, very slowly...'\",\n       \"A doctor thoroughly examined his patient and said, 'Look I really can't find any reason for this mysterious affliction. It's probably due to drinking.' The patient sighed and snapped, 'In that case, I'll come back when you're damn well sober!'\",\n       'Doctor: Tell me nurse, how is that boy doing; the one who ate all those 5p pieces? Nurse: Still no change doctor.',\n       \"Doctor: Did you take the patient's temperature nurse? Nurse: No doctor. Is it missing?\",\n       \"A depressed man turned to his friend in the pub and said, 'I woke up this morning and felt so bad that I tried to kill myself by taking 50 aspirin.' 'Oh man, that's really bad', said his friend, 'What happened?' The first man sighed and said, 'After the first two, I felt better.'\",\n       \"A famous blues musician died. His tombstone bore the inscription, 'Didn't wake up this morning...'\",\n       \"A businessman was interviewing a nervous young woman for a position in his company. He wanted to find out something about her personality, so he asked, 'If you could have a conversation with someone living or dead, who would it be?' The girl thought about the question: 'The living one', she replied.\",\n       \"Manager to interviewee: For this job we need someone who is responsible. Interviewee to Manager: I'm your man then - in my last job, whenever anything went wrong, I was responsible.\",\n       \"A businessman turned to a colleague and asked, 'So, how many people work at your office?' His friend shrugged and replied, 'Oh about half of them.'\",\n       \"'How long have I been working at that office? As a matter of fact, I've been working there ever since they threatened to sack me.'\",\n       \"In a courtroom, a mugger was on trial. The victim, asked if she recognised the defendant, said, 'Yes, that's him. I saw him clear as day. I'd remember his face anywhere.' Unable to contain himself, the defendant burst out with, 'She's lying! I was wearing a mask!'\",\n       \"As Sid sat down to a big plate of chips and gravy down the local pub, a mate of his came over and said, 'Here Sid, me old pal. I thought you were trying to get into shape? And here you are with a high-fat meal and a pint of stout!' Sid looked up and replied, 'I am getting into shape. The shape I've chosen is a sphere.'\",\n       'Man in pub: How much do you charge for one single drop of whisky? Landlord: That would be free sir. Man in pub: Excellent. Drip me a glass full.',\n       'I once went to a Doctor Who restaurant. For starters I had Dalek bread.',\n       \"A restaurant nearby had a sign in the window which said 'We serve breakfast at any time', so I ordered French toast in the Renaissance.\",\n       \"Why couldn't the rabbit get a loan?  Because he had burrowed too much already!\",\n       \"I phoned up the builder's yard yesterday. I said, 'Can I have a skip outside my house?'. The builder said, 'Sure. Do what you want. It's your house.'\",\n       \"What's the diference between a sock and a camera? A sock takes five toes and a camera takes four toes!\",\n       \"Woman on phone: I'd like to complain about these incontinence pants I bought from you! Shopkeeper: Certainly madam, where are you ringing from? Woman on phone: From the waist down!\",\n       'Knock knock.',\n       \"Two Oranges in a pub, one says to the other 'Your round.'.\",\n       \"Guy : 'Doc, I've got a cricket ball stuck up my backside.' Doc : 'How's that?' Guy : 'Don't you start...'\",\n       \"Two cows standing in a field. One turns to the other and says 'Moo!' The other one says 'Damn, I was just about to say that!'.\",\n       \"A vampire bat arrives back at the roost with his face full of blood. All the bats get excited and ask where he got it from. 'Follow me', he says and off they fly over hills, over rivers and into a dark forest. 'See that tree over there', he says.  'WELL I DIDN'T!!'.\",\n       \"A man goes into a bar and orders a pint. After a few minutes he hears a voice that says, 'Nice shoes'. He looks around but the whole bar is empty apart from the barman at the other end of the bar. A few minutes later he hears the voice again. This time it says, 'I like your shirt'. He beckons the barman over and tells him what's been happening to which the barman replies, 'Ah, that would be the nuts sir. They're complimentary'!\",\n       \"A man was siting in a restaurant waiting for his meal when a big king prawn comes flying across the room and hits him on the back of the head. He turns around and the waiter said, 'That's just for starters'.\",\n       'Doctor! I have a serious problem, I can never remember what i just said. When did you first notice this problem? What problem?',\n       \"Now, most dentist's chairs go up and down, don't they? The one I was in went back and forwards. I thought, 'This is unusual'. Then the dentist said to me, 'Mitsuku, get out of the filing cabinet'.\",\n       \"I was reading this book, 'The History of Glue'. I couldn't put it down.\",\n       \"The other day someone left a piece of plastacine in my bedroom. I didn't know what to make of it.\",\n       'When I was at school people used to throw gold bars at me. I was the victim of bullion.',\n       \"I was playing the piano in a bar and this elephant walked in and started crying his eyes out. I said 'Do you recognise the tune?' He said 'No, I recognise the ivory.'\",\n       \"I went in to a pet shop. I said, 'Can I buy a goldfish?' The guy said, 'Do you want an aquarium?' I said, 'I don't care what star sign it is.'\",\n       'My mate Sid was a victim of I.D. theft. Now we just call him S.',\n       \"David Hasselhoff walks into a bar and says to the barman, 'I want you to call me David Hoff'.  The barman replies 'Sure thing Dave... no hassle'\"],\n      'context_set': ''}]\n\n\n\n\n```python\nwords = []\nlabels = []\n\ndocs_x = []\ndocs_y = [] \n\n# loop through dict to grab our values\nfor intent in data['intents']:\n    for pattern in intent['patterns']:\n        # stemming get the root of word, when traiing model \n        # only care abt the main meaning of word\n        # need to tokenize/split words\n        wrds = nltk.word_tokenize(pattern)\n        words.extend(wrds) ## add all wrds to list\n        docs_x.append(wrds)\n        # for each pattern add another item in this var to track what tag its part of\n        # each entry in docs_x (tokenized words/wrds) will correspond to (intent) docs_y so we know how to classify\n        # each of the patterns\n        docs_y.append(intent['tag'])\n        \n        if intent['tag'] not in labels:\n            labels.append(intent['tag']) # grab all diff tags we need\n```\n\n\n```python\n# stem words and remove duplicate words. also lower all words so dont confuse the network into \n# thinking spelling case has different meaning\nwords = [stemmer.stem(w.lower()) for w in words if w!= '?' ] # remove any Question marks, dont want this\nwords = sorted(list(set(words)))                             # to have any meaning to our model\n# sort the labels also \nlabels = sorted(labels)\n```\n\n\n```python\n# prepare data before we feed into the model \n\n# need to convert our text in lists to nums (One-hot-encoding) so our network can \n# categorize the data\ntraining = [] # input data goes here \noutput = [] \n\nout_empty = [0 for _ in range(len(labels))]\n\nfor x, doc in enumerate(docs_x):\n    \n    bag = [] # will be our bag of one hot encoded words\n    wrds = [stemmer.stem(w) for w in doc] # stem all the words in patterns\n    \n    # go through all diff words in list that are stemmed\n    # and add either 1 or 0 to bag of words depending on if this word is in the \n    # main words list \"(words = sorted(list(set(words))))\"\n    for w in words:\n        # if word here place 1 representing that word exists\n        if w in wrds:\n            bag.append(1)\n        else:\n            # word isn't here place 0\n            bag.append(0)\n    \n    # now generate output that has either 0's or 1's representing the tag that is word\n    output_row = out_empty[:]\n    # will look through labels list and check where tag is in list and set that value to 1 \n    # in the output_row \n    output_row[labels.index(docs_y[x])] = 1\n    \n    # now we have both lists that are now One-hot-encoded !!\n    training.append(bag)\n    output.append(output_row)\n\n```\n\n\n```python\n# turn lists into numpy array\ntraining = np.array(training)\noutput = np.array(output)\n\n```\n\n\n```python\n# shape of output\noutput.shape\n```\n\n\n```python\n# shape of training\ntraining.shape\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n# Multi-layer net with ReLU hidden layer\n\nmodel = keras.models.Sequential()\n\n\nmodel.add(keras.layers.Dense(8,input_dim=training.shape[1],activation='relu',\n bias_initializer=keras.initializers.Constant(0.1)))\n\nmodel.add(keras.layers.Dense(8,activation='relu',\n bias_initializer=keras.initializers.Constant(0.1)))\n\nmodel.add(keras.layers.Dense(8,activation='relu',\n bias_initializer=keras.initializers.Constant(0.1)))\n\n\nmodel.add(keras.layers.Dense(8,activation='relu',\n bias_initializer=keras.initializers.Constant(0.1)))\n\n\n\n\n\n\n# Output layer (size 6), softmax activation function\nmodel.add(keras.layers.Dense(output.shape[1],activation='softmax'))\n```\n\n\n```python\n# Compile as above (default learning rate and other\n# hyperparameters for the Adam optimizer).\n# default learning rate for adam optimizer is 0.001\n\nmodel.compile(loss=keras.losses.CategoricalCrossentropy(),\n optimizer=keras.optimizers.Nadam(learning_rate=0.001),\n metrics=[keras.metrics.CategoricalAccuracy()])\n\n# Display the model\nmodel.summary()\n```\n\n    Model: \"sequential_52\"\n    _________________________________________________________________\n    Layer (type)                 Output Shape              Param #   \n    =================================================================\n    dense_185 (Dense)            (None, 8)                 1088      \n    _________________________________________________________________\n    dense_186 (Dense)            (None, 8)                 72        \n    _________________________________________________________________\n    dense_187 (Dense)            (None, 8)                 72        \n    _________________________________________________________________\n    dense_188 (Dense)            (None, 8)                 72        \n    _________________________________________________________________\n    dense_189 (Dense)            (None, 21)                189       \n    =================================================================\n    Total params: 1,493\n    Trainable params: 1,493\n    Non-trainable params: 0\n    _________________________________________________________________\n\n\n\n```python\nkeras.utils.plot_model(model,to_file='chatbot.png',\n show_shapes=True,expand_nested=True)\n```\n\n\n```python\n# Note the initializer for the hidden unit bias weights\n#for i in model.get_weights():\n #display(sp.Matrix(i))\n\n```\n\n\n```python\n# Train it!\nhistory = model.fit(training, output,\n batch_size=1,\n epochs=100,\n verbose=1)\n```\n\n    Train on 152 samples\n    Epoch 1/100\n    152/152 [==============================] - 1s 3ms/sample - loss: 3.0575 - categorical_accuracy: 0.0592\n    Epoch 2/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 3.0329 - categorical_accuracy: 0.0789\n    Epoch 3/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 3.0146 - categorical_accuracy: 0.0855\n    Epoch 4/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 2.9881 - categorical_accuracy: 0.1250\n    Epoch 5/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 2.9451 - categorical_accuracy: 0.1316\n    Epoch 6/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 2.8590 - categorical_accuracy: 0.1908\n    Epoch 7/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 2.7028 - categorical_accuracy: 0.1842\n    Epoch 8/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 2.5121 - categorical_accuracy: 0.2039\n    Epoch 9/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 2.3326 - categorical_accuracy: 0.2105\n    Epoch 10/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 2.1810 - categorical_accuracy: 0.2171\n    Epoch 11/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 2.0423 - categorical_accuracy: 0.3224\n    Epoch 12/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 1.9140 - categorical_accuracy: 0.3553\n    Epoch 13/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 1.8060 - categorical_accuracy: 0.4211\n    Epoch 14/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 1.6844 - categorical_accuracy: 0.4934\n    Epoch 15/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 1.5641 - categorical_accuracy: 0.4671\n    Epoch 16/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 1.4330 - categorical_accuracy: 0.5197\n    Epoch 17/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 1.2970 - categorical_accuracy: 0.5789\n    Epoch 18/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 1.1646 - categorical_accuracy: 0.6053\n    Epoch 19/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 1.0342 - categorical_accuracy: 0.6711\n    Epoch 20/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.9079 - categorical_accuracy: 0.7303\n    Epoch 21/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.7759 - categorical_accuracy: 0.7829\n    Epoch 22/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.6614 - categorical_accuracy: 0.8487\n    Epoch 23/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.5673 - categorical_accuracy: 0.8487\n    Epoch 24/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.4946 - categorical_accuracy: 0.8684\n    Epoch 25/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.4167 - categorical_accuracy: 0.9145\n    Epoch 26/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.3568 - categorical_accuracy: 0.9211\n    Epoch 27/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.3085 - categorical_accuracy: 0.9474\n    Epoch 28/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.2686 - categorical_accuracy: 0.9539\n    Epoch 29/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.2199 - categorical_accuracy: 0.9605\n    Epoch 30/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.1911 - categorical_accuracy: 0.9671\n    Epoch 31/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.1646 - categorical_accuracy: 0.9737\n    Epoch 32/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.1500 - categorical_accuracy: 0.9737\n    Epoch 33/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.1247 - categorical_accuracy: 0.9868\n    Epoch 34/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.1115 - categorical_accuracy: 0.9737\n    Epoch 35/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0947 - categorical_accuracy: 0.9803\n    Epoch 36/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0830 - categorical_accuracy: 0.9803\n    Epoch 37/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0732 - categorical_accuracy: 0.9868\n    Epoch 38/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0652 - categorical_accuracy: 0.9868\n    Epoch 39/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0566 - categorical_accuracy: 0.9934\n    Epoch 40/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0487 - categorical_accuracy: 1.0000\n    Epoch 41/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0430 - categorical_accuracy: 1.0000\n    Epoch 42/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0373 - categorical_accuracy: 0.9934\n    Epoch 43/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0360 - categorical_accuracy: 0.9934\n    Epoch 44/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0302 - categorical_accuracy: 1.0000\n    Epoch 45/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0261 - categorical_accuracy: 1.0000\n    Epoch 46/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0216 - categorical_accuracy: 1.0000\n    Epoch 47/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0186 - categorical_accuracy: 1.0000\n    Epoch 48/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0177 - categorical_accuracy: 1.0000\n    Epoch 49/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0157 - categorical_accuracy: 1.0000\n    Epoch 50/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0125 - categorical_accuracy: 1.0000\n    Epoch 51/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0104 - categorical_accuracy: 1.0000\n    Epoch 52/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0095 - categorical_accuracy: 1.0000\n    Epoch 53/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0078 - categorical_accuracy: 1.0000\n    Epoch 54/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0072 - categorical_accuracy: 1.0000\n    Epoch 55/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0066 - categorical_accuracy: 1.0000\n    Epoch 56/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0056 - categorical_accuracy: 1.0000\n    Epoch 57/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0049 - categorical_accuracy: 1.0000\n    Epoch 58/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0042 - categorical_accuracy: 1.0000\n    Epoch 59/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0038 - categorical_accuracy: 1.0000\n    Epoch 60/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0033 - categorical_accuracy: 1.0000\n    Epoch 61/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0029 - categorical_accuracy: 1.0000\n    Epoch 62/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0026 - categorical_accuracy: 1.0000\n    Epoch 63/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0025 - categorical_accuracy: 1.0000\n    Epoch 64/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0021 - categorical_accuracy: 1.0000\n    Epoch 65/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0019 - categorical_accuracy: 1.0000\n    Epoch 66/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0016 - categorical_accuracy: 1.0000\n    Epoch 67/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0015 - categorical_accuracy: 1.0000\n    Epoch 68/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0013 - categorical_accuracy: 1.0000\n    Epoch 69/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0013 - categorical_accuracy: 1.0000\n    Epoch 70/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 0.0011 - categorical_accuracy: 1.0000\n    Epoch 71/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 9.7354e-04 - categorical_accuracy: 1.0000\n    Epoch 72/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 8.7477e-04 - categorical_accuracy: 1.0000\n    Epoch 73/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 7.9792e-04 - categorical_accuracy: 1.0000\n    Epoch 74/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 7.1617e-04 - categorical_accuracy: 1.0000\n    Epoch 75/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 6.4143e-04 - categorical_accuracy: 1.0000\n    Epoch 76/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 5.7778e-04 - categorical_accuracy: 1.0000\n    Epoch 77/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 5.2867e-04 - categorical_accuracy: 1.0000\n    Epoch 78/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 4.6775e-04 - categorical_accuracy: 1.0000\n    Epoch 79/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 4.3156e-04 - categorical_accuracy: 1.0000\n    Epoch 80/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 3.8982e-04 - categorical_accuracy: 1.0000\n    Epoch 81/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 3.5225e-04 - categorical_accuracy: 1.0000\n    Epoch 82/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 3.2291e-04 - categorical_accuracy: 1.0000\n    Epoch 83/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 3.0208e-04 - categorical_accuracy: 1.0000\n    Epoch 84/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 2.6204e-04 - categorical_accuracy: 1.0000\n    Epoch 85/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 2.3803e-04 - categorical_accuracy: 1.0000\n    Epoch 86/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 2.1105e-04 - categorical_accuracy: 1.0000\n    Epoch 87/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 1.9740e-04 - categorical_accuracy: 1.0000\n    Epoch 88/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 1.7704e-04 - categorical_accuracy: 1.0000\n    Epoch 89/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 1.6243e-04 - categorical_accuracy: 1.0000\n    Epoch 90/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 1.4778e-04 - categorical_accuracy: 1.0000\n    Epoch 91/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 1.3352e-04 - categorical_accuracy: 1.0000\n    Epoch 92/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 1.2212e-04 - categorical_accuracy: 1.0000\n    Epoch 93/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 1.0887e-04 - categorical_accuracy: 1.0000\n    Epoch 94/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 1.0243e-04 - categorical_accuracy: 1.0000\n    Epoch 95/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 9.0790e-05 - categorical_accuracy: 1.0000\n    Epoch 96/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 8.2472e-05 - categorical_accuracy: 1.0000\n    Epoch 97/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 7.7913e-05 - categorical_accuracy: 1.0000\n    Epoch 98/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 6.9800e-05 - categorical_accuracy: 1.0000\n    Epoch 99/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 6.2189e-05 - categorical_accuracy: 1.0000\n    Epoch 100/100\n    152/152 [==============================] - 0s 3ms/sample - loss: 5.8351e-05 - categorical_accuracy: 1.0000\n\n\n\n```python\n# summarize history for loss\nplt.plot(history.history['loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['training'], loc='upper left')\nplt.show()\n```\n\n\n```python\nscore = model.evaluate(training,output,verbose=1)\nprint(\"Loss:\",score[0])\nprint(\"Accuracy:\",score[1])\n```\n\n    Loss: 5.0991909167925386e-05\n    Accuracy: 1.0\n\n\n\n```python\n# save the model .. comment out for now until we train the data appropriately\nmodel.save(\"model.Chatbot\")\n```\n\n\n```python\ndef bag_of_words(s, words):\n    bag = [0 for _ in range(len(words))]\n\n    s_words = nltk.word_tokenize(s)\n    s_words = [stemmer.stem(word.lower()) for word in s_words]\n\n    for se in s_words:\n        for i, w in enumerate(words):\n            if w == se:\n                bag[i] = 1\n            \n    return numpy.array(bag)\n\n\n\n```\n\n\n```python\ndef chat():\n    print(\"Start talking with the bot (type quit to stop)!\")\n    while True:\n        inp = input(\"You: \")\n        if inp.lower() == \"quit\":\n            break\n\n        results = model.predict(np.array([bag_of_words(inp, words)]))[0]\n       \n        \n        \n        results_index = numpy.argmax(results)\n        tag = labels[results_index]\n        #print(results[results_index])\n        \n        # protect against unknown questions , if model is unsure what user ask they will ask user to rephrase their question \n        if results[results_index] > 0.92:   # the value when the model cant recognize is 0.9133338 so i set this value just above it\n            for tg in data[\"intents\"]:\n                if tg['tag'] == tag:\n                    responses = tg['responses']\n\n            print(random.choice(responses))\n            \n        else:\n            print(\"I don't understand, please try again or ask a different question :( \")\n\n```\n\n\n```python\nchat()\n```\n\n    Start talking with the bot (type quit to stop)!\n\n\n    You:  hello\n\n\n    Good to see you again!\n\n\n    You:  what is your name\n\n\n    I am the Todd\n\n\n    You:  what time is it \n\n\n    One second\n\n\n    You:  what time do you close\n\n\n    You may call me Todd\n\n\n    You:  doyouunderstandthis\n\n\n    I don't understand, please try again or ask a different question :( \n\n\n    You:  k\n\n\n    I don't understand, please try again or ask a different question :( \n\n\n    You:  s\n\n\n    I don't understand, please try again or ask a different question :( \n\n\n    You:  r\n\n\n    I don't understand, please try again or ask a different question :( \n\n\n    You:  tell me a joke\n\n\n    What did the plumber say when he wanted to divorce his wife? Sorry, but it's over, Flo!\n\n\n    You:  funny joke\n\n\n    Whizzing round a sharp bend on a country road a motorist ran over a large dog. A distraught farmer's wife ran over to the dead animal. 'I'm so very sorry', said the driver, 'I'll replace him, of course.' 'Well, I don't know', said the farmer's wife, 'Are you any good at catching rats?'\n\n\n    You:  quit\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "7a26ffe4585768321b624979c313257302f36072", "size": 162313, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chatbot.ipynb", "max_stars_repo_name": "CSCI4850/s21-team8-project", "max_stars_repo_head_hexsha": "43a933fcb7da65c1c11e7a6449d2da0246aaa949", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chatbot.ipynb", "max_issues_repo_name": "CSCI4850/s21-team8-project", "max_issues_repo_head_hexsha": "43a933fcb7da65c1c11e7a6449d2da0246aaa949", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chatbot.ipynb", "max_forks_repo_name": "CSCI4850/s21-team8-project", "max_forks_repo_head_hexsha": "43a933fcb7da65c1c11e7a6449d2da0246aaa949", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-03T16:31:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-03T16:31:27.000Z", "avg_line_length": 117.1089466089, "max_line_length": 65916, "alphanum_fraction": 0.7693099136, "converted": true, "num_tokens": 17322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1847675196261571, "lm_q2_score": 0.05261895799037554, "lm_q1q2_score": 0.009722274353194648}}
{"text": "```python\n!pip install cirq\n```\n\n    Collecting cirq\n      Downloading cirq-0.14.0-py3-none-any.whl (7.8 kB)\n    Collecting cirq-web==0.14.0\n      Downloading cirq_web-0.14.0-py3-none-any.whl (593 kB)\n    Collecting cirq-pasqal==0.14.0\n      Downloading cirq_pasqal-0.14.0-py3-none-any.whl (30 kB)\n    Collecting cirq-ionq==0.14.0\n      Downloading cirq_ionq-0.14.0-py3-none-any.whl (48 kB)\n    Collecting cirq-rigetti==0.14.0\n      Downloading cirq_rigetti-0.14.0-py3-none-any.whl (56 kB)\n    Collecting cirq-core==0.14.0\n      Downloading cirq_core-0.14.0-py3-none-any.whl (1.8 MB)\n    Collecting cirq-aqt==0.14.0\n      Downloading cirq_aqt-0.14.0-py3-none-any.whl (19 kB)\n    Collecting cirq-google==0.14.0\n      Downloading cirq_google-0.14.0-py3-none-any.whl (541 kB)\n    Requirement already satisfied: requests~=2.18 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from cirq-aqt==0.14.0->cirq) (2.25.1)\n    Requirement already satisfied: sortedcontainers~=2.0 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from cirq-core==0.14.0->cirq) (2.3.0)\n    Requirement already satisfied: typing-extensions in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from cirq-core==0.14.0->cirq) (3.7.4.3)\n    Requirement already satisfied: scipy in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from cirq-core==0.14.0->cirq) (1.6.2)\n    Requirement already satisfied: matplotlib~=3.0 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from cirq-core==0.14.0->cirq) (3.3.4)\n    Requirement already satisfied: networkx~=2.4 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from cirq-core==0.14.0->cirq) (2.5)\n    Requirement already satisfied: sympy<1.10 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from cirq-core==0.14.0->cirq) (1.8)\n    Requirement already satisfied: pandas in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from cirq-core==0.14.0->cirq) (1.2.4)\n    Requirement already satisfied: tqdm in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from cirq-core==0.14.0->cirq) (4.59.0)\n    Collecting duet~=0.2.0\n      Downloading duet-0.2.5-py3-none-any.whl (28 kB)\n    Requirement already satisfied: numpy~=1.16 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from cirq-core==0.14.0->cirq) (1.20.1)\n    Collecting google-api-core[grpc]<2.0.0dev,>=1.14.0\n      Downloading google_api_core-1.31.5-py2.py3-none-any.whl (93 kB)\n    Requirement already satisfied: protobuf>=3.13.0 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from cirq-google==0.14.0->cirq) (3.19.4)\n    Collecting httpx~=0.15.5\n      Downloading httpx-0.15.5-py3-none-any.whl (65 kB)\n    Requirement already satisfied: attrs~=20.3.0 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from cirq-rigetti==0.14.0->cirq) (20.3.0)\n    Collecting rfc3986~=1.5.0\n      Downloading rfc3986-1.5.0-py2.py3-none-any.whl (31 kB)\n    Requirement already satisfied: toml~=0.10.2 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from cirq-rigetti==0.14.0->cirq) (0.10.2)\n    Collecting certifi~=2021.5.30\n      Downloading certifi-2021.5.30-py2.py3-none-any.whl (145 kB)\n    Requirement already satisfied: python-dateutil~=2.8.1 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from cirq-rigetti==0.14.0->cirq) (2.8.1)\n    Collecting iso8601~=0.1.14\n      Downloading iso8601-0.1.16-py2.py3-none-any.whl (10 kB)\n    Collecting six~=1.16.0\n      Using cached six-1.16.0-py2.py3-none-any.whl (11 kB)\n    Collecting httpcore~=0.11.1\n      Downloading httpcore-0.11.1-py3-none-any.whl (52 kB)\n    Collecting pyjwt~=1.7.1\n      Using cached PyJWT-1.7.1-py2.py3-none-any.whl (18 kB)\n    Requirement already satisfied: idna~=2.10 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from cirq-rigetti==0.14.0->cirq) (2.10)\n    Collecting retrying~=1.3.3\n      Downloading retrying-1.3.3.tar.gz (10 kB)\n    Requirement already satisfied: sniffio~=1.2.0 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from cirq-rigetti==0.14.0->cirq) (1.2.0)\n    Collecting rfc3339~=6.2\n      Downloading rfc3339-6.2-py3-none-any.whl (5.5 kB)\n    Collecting pydantic~=1.8.2\n      Downloading pydantic-1.8.2-cp38-cp38-win_amd64.whl (2.0 MB)\n    Collecting pyquil~=3.0.0\n      Downloading pyquil-3.0.1-py3-none-any.whl (220 kB)\n    Collecting qcs-api-client~=0.8.0\n      Downloading qcs_api_client-0.8.0-py3-none-any.whl (97 kB)\n    Collecting h11~=0.9.0\n      Downloading h11-0.9.0-py2.py3-none-any.whl (53 kB)\n    Collecting googleapis-common-protos<2.0dev,>=1.6.0\n      Downloading googleapis_common_protos-1.56.0-py2.py3-none-any.whl (241 kB)\n    Collecting google-auth<2.0dev,>=1.25.0\n      Downloading google_auth-1.35.0-py2.py3-none-any.whl (152 kB)\n    Requirement already satisfied: pytz in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.14.0->cirq) (2021.1)\n    Requirement already satisfied: packaging>=14.3 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.14.0->cirq) (20.9)\n    Requirement already satisfied: setuptools>=40.3.0 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.14.0->cirq) (52.0.0.post20210125)\n    Requirement already satisfied: grpcio<2.0dev,>=1.29.0 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.14.0->cirq) (1.44.0)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from google-auth<2.0dev,>=1.25.0->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.14.0->cirq) (0.2.8)\n    Collecting cachetools<5.0,>=2.0.0\n      Downloading cachetools-4.2.4-py3-none-any.whl (10 kB)\n    Requirement already satisfied: rsa<5,>=3.1.4 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from google-auth<2.0dev,>=1.25.0->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.14.0->cirq) (4.8)\n    Requirement already satisfied: cycler>=0.10 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from matplotlib~=3.0->cirq-core==0.14.0->cirq) (0.10.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from matplotlib~=3.0->cirq-core==0.14.0->cirq) (2.4.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from matplotlib~=3.0->cirq-core==0.14.0->cirq) (1.3.1)\n    Requirement already satisfied: pillow>=6.2.0 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from matplotlib~=3.0->cirq-core==0.14.0->cirq) (8.2.0)\n    Requirement already satisfied: decorator>=4.3.0 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from networkx~=2.4->cirq-core==0.14.0->cirq) (5.0.6)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from pyasn1-modules>=0.2.1->google-auth<2.0dev,>=1.25.0->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq-google==0.14.0->cirq) (0.4.8)\n    Collecting lark<0.12.0,>=0.11.1\n      Downloading lark-0.11.3.tar.gz (229 kB)\n    Collecting rpcq<4.0.0,>=3.6.0\n      Downloading rpcq-3.9.2.tar.gz (43 kB)\n    Collecting retry<0.10.0,>=0.9.2\n      Downloading retry-0.9.2-py2.py3-none-any.whl (8.0 kB)\n    Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from requests~=2.18->cirq-aqt==0.14.0->cirq) (1.26.4)\n    Requirement already satisfied: chardet<5,>=3.0.2 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from requests~=2.18->cirq-aqt==0.14.0->cirq) (4.0.0)\n    Requirement already satisfied: py<2.0.0,>=1.4.26 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from retry<0.10.0,>=0.9.2->pyquil~=3.0.0->cirq-rigetti==0.14.0->cirq) (1.10.0)\n    Collecting msgpack<1.0,>=0.6\n      Downloading msgpack-0.6.2.tar.gz (119 kB)\n    Collecting python-rapidjson\n      Downloading python_rapidjson-1.6-cp38-cp38-win_amd64.whl (143 kB)\n    Requirement already satisfied: pyzmq>=17 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from rpcq<4.0.0,>=3.6.0->pyquil~=3.0.0->cirq-rigetti==0.14.0->cirq) (20.0.0)\n    Collecting ruamel.yaml\n      Downloading ruamel.yaml-0.17.21-py3-none-any.whl (109 kB)\n    Requirement already satisfied: mpmath>=0.19 in c:\\users\\ameyb\\anaconda3\\lib\\site-packages (from sympy<1.10->cirq-core==0.14.0->cirq) (1.2.1)\n    Collecting ruamel.yaml.clib>=0.2.6\n      Downloading ruamel.yaml.clib-0.2.6-cp38-cp38-win_amd64.whl (117 kB)\n    Building wheels for collected packages: lark, retrying, rpcq, msgpack\n      Building wheel for lark (setup.py): started\n      Building wheel for lark (setup.py): finished with status 'done'\n      Created wheel for lark: filename=lark-0.11.3-py2.py3-none-any.whl size=99635 sha256=155e7e2100b52b4d75f8b42f117bb6698394e89cd998645896af53ed1a02d1ba\n      Stored in directory: c:\\users\\ameyb\\appdata\\local\\pip\\cache\\wheels\\34\\cb\\6c\\4df359c2a3f0a1af4cccae6392bee423bb5aff530103de3538\n      Building wheel for retrying (setup.py): started\n      Building wheel for retrying (setup.py): finished with status 'done'\n      Created wheel for retrying: filename=retrying-1.3.3-py3-none-any.whl size=11429 sha256=e25e954dd607b67304a1195b8285ae5e67180926f92f23e8530da1a489c1c5bd\n      Stored in directory: c:\\users\\ameyb\\appdata\\local\\pip\\cache\\wheels\\c4\\a7\\48\\0a434133f6d56e878ca511c0e6c38326907c0792f67b476e56\n      Building wheel for rpcq (setup.py): started\n      Building wheel for rpcq (setup.py): finished with status 'done'\n      Created wheel for rpcq: filename=rpcq-3.9.2-py3-none-any.whl size=45865 sha256=74d9bce012f3f24fc0fe440ee93502f2efd71bd8bc10324efde8e15d89af21f1\n      Stored in directory: c:\\users\\ameyb\\appdata\\local\\pip\\cache\\wheels\\20\\fd\\8d\\4d4a9f389a9c92210dbee8ca8bbd725a6204f64a8ca8cad841\n      Building wheel for msgpack (setup.py): started\n      Building wheel for msgpack (setup.py): finished with status 'done'\n      Created wheel for msgpack: filename=msgpack-0.6.2-cp38-cp38-win_amd64.whl size=73428 sha256=c9451975d58a7a983fc5b1ef7e660a774c871f8f4f2d6373645cdba003b70589\n      Stored in directory: c:\\users\\ameyb\\appdata\\local\\pip\\cache\\wheels\\5d\\f2\\04\\0d19c10080b996bef17c908a6243e6e65d8da1a4094a3f604d\n    Successfully built lark retrying rpcq msgpack\n    Installing collected packages: rfc3986, h11, six, ruamel.yaml.clib, httpcore, certifi, cachetools, ruamel.yaml, rfc3339, retrying, python-rapidjson, pyjwt, pydantic, msgpack, iso8601, httpx, googleapis-common-protos, google-auth, rpcq, retry, qcs-api-client, lark, google-api-core, duet, pyquil, cirq-core, cirq-web, cirq-rigetti, cirq-pasqal, cirq-ionq, cirq-google, cirq-aqt, cirq\n      Attempting uninstall: six\n        Found existing installation: six 1.15.0\n        Uninstalling six-1.15.0:\n          Successfully uninstalled six-1.15.0\n      Attempting uninstall: certifi\n        Found existing installation: certifi 2020.12.5\n        Uninstalling certifi-2020.12.5:\n          Successfully uninstalled certifi-2020.12.5\n      Attempting uninstall: cachetools\n        Found existing installation: cachetools 5.0.0\n        Uninstalling cachetools-5.0.0:\n          Successfully uninstalled cachetools-5.0.0\n      Attempting uninstall: msgpack\n        Found existing installation: msgpack 1.0.2\n        Uninstalling msgpack-1.0.2:\n          Successfully uninstalled msgpack-1.0.2\n      Attempting uninstall: google-auth\n        Found existing installation: google-auth 2.6.2\n        Uninstalling google-auth-2.6.2:\n          Successfully uninstalled google-auth-2.6.2\n    Successfully installed cachetools-4.2.4 certifi-2021.5.30 cirq-0.14.0 cirq-aqt-0.14.0 cirq-core-0.14.0 cirq-google-0.14.0 cirq-ionq-0.14.0 cirq-pasqal-0.14.0 cirq-rigetti-0.14.0 cirq-web-0.14.0 duet-0.2.5 google-api-core-1.31.5 google-auth-1.35.0 googleapis-common-protos-1.56.0 h11-0.9.0 httpcore-0.11.1 httpx-0.15.5 iso8601-0.1.16 lark-0.11.3 msgpack-0.6.2 pydantic-1.8.2 pyjwt-1.7.1 pyquil-3.0.1 python-rapidjson-1.6 qcs-api-client-0.8.0 retry-0.9.2 retrying-1.3.3 rfc3339-6.2 rfc3986-1.5.0 rpcq-3.9.2 ruamel.yaml-0.17.21 ruamel.yaml.clib-0.2.6 six-1.16.0\n\n\n    ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    conda-repo-cli 1.0.4 requires pathlib, which is not installed.\n\n\n\n```python\nimport tensorflow as tf\nimport numpy as np\nimport cirq\n\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\nfrom cirq.contrib.svg import SVGCircuit\n```\n\n## Part 1\n\n\n```python\n#qubits = cirq.GridQubit.rect(1,5)\ncircuit = cirq.Circuit()\n\ncircuit.append((cirq.H(i)) for i in cirq.LineQubit.range(5))\nfor i in cirq.LineQubit.range(4):\n    circuit.append(cirq.CNOT(control=i , target = i+1))\ncircuit.append(cirq.SWAP(cirq.LineQubit(0),cirq.LineQubit(4))) \ncircuit.append(cirq.rx(np.pi/2).on(cirq.LineQubit(np.random.randint(5))))\nSVGCircuit(circuit)\n```\n\n\n\n\n    \n\n    \n\n\n\n## Part 2\n\n\n```python\ncircuit = cirq.Circuit()\nqubit=cirq.LineQubit(0)\nangle = np.random.random(5)/20\nfor i in range(5):\n    circuit.append(cirq.rx(angle[i]).on(qubit))\ncircuit.append(cirq.measure(qubit,key='result'))\nSVGCircuit(circuit)                  \n\n```\n\n\n\n\n    \n\n    \n\n\n\n\n```python\nsimulator = cirq.Simulator()\nsamples = simulator.run(circuit, repetitions=1024)\nhist_data = samples.measurements['result'].reshape(1024,)\nprint('The probability of measuring a qubit in |0> state : ', samples.histogram(key='result')[0]/1024)\nprint(samples.histogram(key='result'))\nplt.hist(hist_data)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "1497e50733c5e962bcadf3b18c0d707a73fa11c2", "size": 30277, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "QMLHEP_testquestion_1.ipynb", "max_stars_repo_name": "Amey-2002/QMLHEP", "max_stars_repo_head_hexsha": "579c8c8870b4e11dcc027852a693532bfc995fae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-30T09:22:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:22:50.000Z", "max_issues_repo_path": "QMLHEP_testquestion_1.ipynb", "max_issues_repo_name": "Amey-2002/QMLHEP", "max_issues_repo_head_hexsha": "579c8c8870b4e11dcc027852a693532bfc995fae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QMLHEP_testquestion_1.ipynb", "max_forks_repo_name": "Amey-2002/QMLHEP", "max_forks_repo_head_hexsha": "579c8c8870b4e11dcc027852a693532bfc995fae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 88.5292397661, "max_line_length": 5364, "alphanum_fraction": 0.6775440103, "converted": true, "num_tokens": 4972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25683200276421697, "lm_q2_score": 0.037326888950486185, "lm_q1q2_score": 0.009586739646110887}}
{"text": "# Homework 2\n\nIn this homework, we are going to play with Twitter data.\n\nThe data is represented as rows of of [JSON](https://en.wikipedia.org/wiki/JSON#Example) strings.\nIt consists of [tweets](https://dev.twitter.com/overview/api/tweets), [messages](https://dev.twitter.com/streaming/overview/messages-types), and a small amount of broken data (cannot be parsed as JSON).\n\nFor this homework, we will only focus on tweets and ignore all other messages.\n\n\n## Tweets\n\nA tweet consists of many data fields. [Here is an example](https://gist.github.com/arapat/03d02c9b327e6ff3f6c3c5c602eeaf8b). You can learn all about them in the Twitter API doc. We are going to briefly introduce only the data fields that will be used in this homework.\n\n* `created_at`: Posted time of this tweet (time zone is included)\n* `id_str`: Tweet ID - we recommend using `id_str` over using `id` as Tweet IDs, becauase `id` is an integer and may bring some overflow problems.\n* `text`: Tweet content\n* `user`: A JSON object for information about the author of the tweet\n    * `id_str`: User ID\n    * `name`: User name (may contain spaces)\n    * `screen_name`: User screen name (no spaces)\n* `retweeted_status`: A JSON object for information about the retweeted tweet (i.e. this tweet is not original but retweeteed some other tweet)\n    * All data fields of a tweet except `retweeted_status`\n* `entities`: A JSON object for all entities in this tweet\n    * `hashtags`: An array for all the hashtags that are mentioned in this tweet\n    * `urls`: An array for all the URLs that are mentioned in this tweet\n\n\n## Data source\n\nAll tweets are collected using the [Twitter Streaming API](https://dev.twitter.com/streaming/overview).\n\n\n## Users partition\n\nBesides the original tweets, we will provide you with a Pickle file, which contains a partition over 452,743 Twitter users. It contains a Python dictionary `{user_id: partition_id}`. The users are partitioned into 7 groups.\n\n\n```python\n# You can load pickle_content from a file on the local file system\n# while testing on your laptop\n# To test on your laptop, set `ON_EMR=False`\n# To test on AWS for final submission, set `ON_EMR=True`\n\nON_EMR = False\n```\n\n## Grading\n\nWe ask you use the `OutputLogger` object `my_output` to store the\nresults of your program.\nWe have provided function calls to `my_output.append()` method for\nstoring the results in all necessary places.\nPlease make sure NOT to remove these lines\n\nIn the last cell of this file, we write the content of `my_output`\nto a pickle file which the grader will read in and use for grading.\n\n\n```python\nimport os\nimport pickle\n\n\nclass OutputLogger:\n    def __init__(self):\n        self.ans = {}\n\n    def append(self, key, value):\n        self.ans[key] = value\n\n    def write_to_disk(self):\n        if ON_EMR:\n            filepath = os.path.expanduser(\"answer.pickle\")\n            print(\"FilePath = {}\".format(filepath))\n            with open(filepath, 'wb') as f:\n                pickle.dump(self.ans, f)\n            proc = subprocess.Popen([\"/usr/local/hadoop/hadoop-2.7.4/bin/hadoop\", \"fs\", \"-copyFromLocal\", filepath, \"/user/spark/answer.pickle\"])\n            proc.wait()\n            os.remove(filepath)\n        else:\n            filepath = os.path.expanduser(\"~/answer.pickle\")\n            with open(filepath, 'wb') as f:\n                pickle.dump(self.ans, f)\n\n\nmy_output = OutputLogger()\n```\n\n# Part 0: Load data to a RDD\n\nThe tweets data is stored on AWS S3. We have in total a little over 1 TB of tweets. We provide 10 MB of tweets for your local development. For the testing and grading on the homework server, we will use different data.\n\n## Testing on the homework server\nOn EdX, we provide three different input sizes to test your program: 10 MB, 1 GB, and 10 GB. For any run, we will only be using one of these four datasets.\n\nFor submission and for local testing, make sure to read the path of the file you want to operate with from `./hw2-files.txt`. Otherwise your program will receive no points.\n\n## Local test\n\nFor local testing, please create your own `hw2-files.txt` file, which contains a single file path on the local disk, e.g.\n`file://<absolute_path_to_current_directory>/hw2-files-10mb.txt`. For final submission, we will create this file on our server for testing with the appropriate file path. If your implementation is correct, you should not worry about which file system (i.e. local file system or HDFS) Spark will read data from.\n\nNow let's see how many lines there are in the input files.\n\n1. Make RDD from the data in the file given by the file path present in `hw2-files.txt`.\n2. Mark the RDD to be cached (so in next operation data will be loaded in memory) \n3. call the `count` method to print number of lines in all these files\n\n<b>It should print<b>\n```\nNumber of elements: 2150\n```\n\n\n```python\n\"\"\"\nThis is a useful cell for debugging.\nUse timer_start() and timer_stop() at different parts of your code\nfor checking the amount of time a segment takes.\n\"\"\"\nfrom time import time\n\n\ntimer = []\nprev_ts = None\n\n\ndef timer_start():\n    global prev_ts\n    prev_ts = time()\n\n\ndef timer_stop(title):\n    timer.append((title, time() - prev_ts))\n```\n\n\n```python\ntimer_start()\n\nfrom pyspark import SparkContext\n\nsc = SparkContext()\n\ntimer_stop(\"set up sc\")\n```\n\n\n```python\ntimer_start()\n\n\nwith open('./hw2-files.txt') as f:\n    file_path = [w.strip() for w in f.readlines() if w.strip()]\n\n# Your code here\nraise NotImplementedError()\n\n\nmy_output.append(\"num-tweets\", count)\nprint('Number of elements:', count)\ntimer_stop(\"read data\")\n```\n\n# Part 1: Parse JSON strings to JSON objects\n\nPython has built-in support for JSON.\n\n\n```python\nimport json\n\njson_example = '''\n{\n    \"id\": 1,\n    \"name\": \"A green door\",\n    \"price\": 12.50,\n    \"tags\": [\"home\", \"green\"]\n}\n'''\n\njson_obj = json.loads(json_example)\njson_obj\n```\n\n## Broken tweets and irrelevant messages\n\nThe data of this assignment may contain broken tweets (invalid JSON strings). So make sure that your code is robust for such cases.\n\nYou can filter out such broken tweet by checking if:\n* the line is not in json format\n\nIn addition, some lines in the input file might not be tweets, but messages that the Twitter server sent to the developer (such as [limit notices](https://dev.twitter.com/streaming/overview/messages-types#limit_notices)). Your program should also ignore these messages.\n\nThese messages would not contain the `created_at` field and can be filtered out accordingly.\n* Check if json object of the broken tweet has a `created_at` field\n\n*Hint:* [Catch the ValueError](http://stackoverflow.com/questions/11294535/verify-if-a-string-is-json-in-python)\n\n**********************************************************************************\n\n**Tasks**\n\n(1) Parse raw JSON tweets to obtain valid JSON objects. \n\n(2) From all valid tweets, construct a pair RDD of `(user_id, text)`, where `user_id` is the `id_str` data field of the `user` dictionary (read [Tweets](#Tweets) section above), `text` is the `text` data field.\n\n\n```python\nimport json\n\ndef safe_parse(raw_json):\n    \"\"\"\n    Input is a String\n    Output is a JSON object if the tweet is valid and None if not valid\n    \"\"\"\n    # YOUR CODE HERE\n    raise NotImplementedError()\n    \n\n```\n\n\n```python\n\"\"\"\n# Remember to construct an RDD of (user_id, text) here.\n\"\"\"\n\n# YOUR CODE HERE\nraise NotImplementedError()\n\n\n```\n\n## Number of unique users\n\nCount the number of different users in all valid tweets\n\n(hint: [the `distinct()` method](https://spark.apache.org/docs/latest/programming-guide.html#transformations) is an easy way to do this, but try to see if there is a faster way to do this).\n\n*******************************************************************************\n\n**It should print**\n```\nThe number of unique users is: 1748\n```\n\n\n```python\ntimer_start()\n\n# YOUR CODE HERE\nraise NotImplementedError()\n\n\nmy_output.append(\"num-unique-users\", users_count)\nprint('The number of unique users is:', users_count)\ntimer_stop(\"Count unique users\")\n```\n\n# Part 2: Number of posts from each user partition\n\nLoad the Pickle file `/twitter/users-partition.pickle`, you will get a dictionary which represents a partition over 452,743 Twitter users, `{user_id: partition_id}`. The users are partitioned into 7 groups. For example, if the dictionary is loaded into a variable named `partition`, the partition ID of the user `59458445` is `partition[\"59458445\"]`. These users are partitioned into 7 groups. The partition ID is an integer between 0-6.\n\nNote that the user partition we provide doesn't cover all users appear in the input data.\n\n## Load the pickle file\n\nFor local testing, you can load the pickle file from the local file system, namely\n\n```\nproc = subprocess.Popen([\"cat\", \"./users-partition.pickle\"],\n                        stdout=subprocess.PIPE)\npickle_content = proc.communicate()[0]\n```\nHowever, for submission, please keep following code block unchanged, since on the server the pickle file is located on the HDFS.\n\n\n```python\nimport subprocess\nimport pickle\n\nif ON_EMR:\n    proc = subprocess.Popen([\"/usr/local/hadoop/hadoop-2.7.4/bin/hadoop\", \"fs\", \"-cat\", \"/user/spark/twitter/users-partition.pickle\"],\n                            stdout=subprocess.PIPE)\n    pickle_content = proc.communicate()[0]\n    \nelse:\n    #!wget 'http://mas-dse-open.s3.amazonaws.com/Twitter/users-partition.pickle' -O './users-partition.pickle'\n    proc = subprocess.Popen([\"cat\", \"./users-partition.pickle\"],\n                        stdout=subprocess.PIPE)\n    pickle_content = proc.communicate()[0]\n\npartition = pickle.loads(pickle_content)\nlen(partition)\n```\n\n## Tweets per user partition\n\n1. Count the number of posts from each user partition\n\n2. Count the number of posts from group 0, 1, ..., 6, plus the number of posts from users who are not in any partition. Assign users who are not in any partition to the group 7.\n\n3. Put the results of this step into a pair RDD `(group_id, count)` that is sorted by key.\n\n\n\nPrint the post count using the `print_post_count` function we provided.\n\n**It should print**\n\n```\nGroup 0 posted 87 tweets\nGroup 1 posted 242 tweets\nGroup 2 posted 41 tweets\nGroup 3 posted 349 tweets\nGroup 4 posted 101 tweets\nGroup 5 posted 358 tweets\nGroup 6 posted 434 tweets\nGroup 7 posted 521 tweets\n```\n\n\n```python\ndef print_post_count(counts):\n    for group_id, count in counts:\n        print('Group %d posted %d tweets' % (group_id, count))\n```\n\n\n```python\ntimer_start()\n\n# YOUR CODE HERE\nraise NotImplementedError()\n\n\n# Following code adds your solution to `my_output`\nassert(type(counts_per_partition) is list and\n       len(counts_per_partition) == 8 and\n       len(counts_per_partition[0]) == 2)\nmy_output.append(\"counts_per_part\", counts_per_partition)\nprint_post_count(counts_per_partition)\ntimer_stop(\"Count tweets per user partition\")\n```\n\n# Part 3:  Tokens that are relatively popular in each user partition\n\nIn this step, we are going to find tokens that are relatively popular in each user partition.\n\nWe define the number of mentions of a token $t$ in a specific user partition $k$ as the number of users from the user partition $k$ that ever mentioned the token $t$ in their tweets. Note that even if some users might mention a token $t$ multiple times or in multiple tweets, a user will contribute at most 1 to the counter of the token $t$.\n\nPlease make sure that the number of mentions of a token is equal to the number of users who mentioned this token but NOT the number of tweets that mentioned this token.\n\nLet $N_t^k$ be the number of mentions of the token $t$ in the user partition $k$. Let $N_t^{all} = \\sum_{i=0}^7 N_t^{i}$ be the number of total mentions of the token $t$.\n\nWe define the relative popularity of a token $t$ in a user partition $k$ as the log ratio between $N_t^k$ and $N_t^{all}$, i.e. \n\n\\begin{equation}\np_t^k = \\log \\frac{N_t^k}{N_t^{all}}.\n\\end{equation}\n\n\nYou can compute the relative popularity by calling the function `get_rel_popularity`.\n\nWe load a tweet tokenizer for you in the following cells. This Tokenizer object is called `tok`. Don't forget to execute the two cells below.\n\nYou can expand the following cell if needed to see the minutae of the Tokenizer.\n\n\n```python\n#!/usr/bin/env python\n\n\"\"\"\nThis code implements a basic, Twitter-aware tokenizer.\n\nA tokenizer is a function that splits a string of text into words. In\nPython terms, we map string and unicode objects into lists of unicode\nobjects.\n\nThere is not a single right way to do tokenizing. The best method\ndepends on the application.  This tokenizer is designed to be flexible\nand this easy to adapt to new domains and tasks.  The basic logic is\nthis:\n\n1. The tuple regex_strings defines a list of regular expression\n   strings.\n\n2. The regex_strings strings are put, in order, into a compiled\n   regular expression object called word_re.\n\n3. The tokenization is done by word_re.findall(s), where s is the\n   user-supplied string, inside the tokenize() method of the class\n   Tokenizer.\n\n4. When instantiating Tokenizer objects, there is a single option:\n   preserve_case.  By default, it is set to True. If it is set to\n   False, then the tokenizer will downcase everything except for\n   emoticons.\n\nThe __main__ method illustrates by tokenizing a few examples.\n\nI've also included a Tokenizer method tokenize_random_tweet(). If the\ntwitter library is installed (http://code.google.com/p/python-twitter/)\nand Twitter is cooperating, then it should tokenize a random\nEnglish-language tweet.\n\n\nJulaiti Alafate:\n  I modified the regex strings to extract URLs in tweets.\n\"\"\"\n\n__author__ = \"Christopher Potts\"\n__copyright__ = \"Copyright 2011, Christopher Potts\"\n__credits__ = []\n__license__ = \"Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License: http://creativecommons.org/licenses/by-nc-sa/3.0/\"\n__version__ = \"1.0\"\n__maintainer__ = \"Christopher Potts\"\n__email__ = \"See the author's website\"\n\n######################################################################\n\nimport re\nfrom html import entities \n\n######################################################################\n# The following strings are components in the regular expression\n# that is used for tokenizing. It's important that phone_number\n# appears first in the final regex (since it can contain whitespace).\n# It also could matter that tags comes after emoticons, due to the\n# possibility of having text like\n#\n#     <:| and some text >:)\n#\n# Most imporatantly, the final element should always be last, since it\n# does a last ditch whitespace-based tokenization of whatever is left.\n\n# This particular element is used in a couple ways, so we define it\n# with a name:\nemoticon_string = r\"\"\"\n    (?:\n      [<>]?\n      [:;=8]                     # eyes\n      [\\-o\\*\\']?                 # optional nose\n      [\\)\\]\\(\\[dDpP/\\:\\}\\{@\\|\\\\] # mouth      \n      |\n      [\\)\\]\\(\\[dDpP/\\:\\}\\{@\\|\\\\] # mouth\n      [\\-o\\*\\']?                 # optional nose\n      [:;=8]                     # eyes\n      [<>]?\n    )\"\"\"\n\n# The components of the tokenizer:\nregex_strings = (\n    # Phone numbers:\n    r\"\"\"\n    (?:\n      (?:            # (international)\n        \\+?[01]\n        [\\-\\s.]*\n      )?            \n      (?:            # (area code)\n        [\\(]?\n        \\d{3}\n        [\\-\\s.\\)]*\n      )?    \n      \\d{3}          # exchange\n      [\\-\\s.]*   \n      \\d{4}          # base\n    )\"\"\"\n    ,\n    # URLs:\n    r\"\"\"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+\"\"\"\n    ,\n    # Emoticons:\n    emoticon_string\n    ,    \n    # HTML tags:\n     r\"\"\"<[^>]+>\"\"\"\n    ,\n    # Twitter username:\n    r\"\"\"(?:@[\\w_]+)\"\"\"\n    ,\n    # Twitter hashtags:\n    r\"\"\"(?:\\#+[\\w_]+[\\w\\'_\\-]*[\\w_]+)\"\"\"\n    ,\n    # Remaining word types:\n    r\"\"\"\n    (?:[a-z][a-z'\\-_]+[a-z])       # Words with apostrophes or dashes.\n    |\n    (?:[+\\-]?\\d+[,/.:-]\\d+[+\\-]?)  # Numbers, including fractions, decimals.\n    |\n    (?:[\\w_]+)                     # Words without apostrophes or dashes.\n    |\n    (?:\\.(?:\\s*\\.){1,})            # Ellipsis dots. \n    |\n    (?:\\S)                         # Everything else that isn't whitespace.\n    \"\"\"\n    )\n\n######################################################################\n# This is the core tokenizing regex:\n    \nword_re = re.compile(r\"\"\"(%s)\"\"\" % \"|\".join(regex_strings), re.VERBOSE | re.I | re.UNICODE)\n\n# The emoticon string gets its own regex so that we can preserve case for them as needed:\nemoticon_re = re.compile(regex_strings[1], re.VERBOSE | re.I | re.UNICODE)\n\n# These are for regularizing HTML entities to Unicode:\nhtml_entity_digit_re = re.compile(r\"&#\\d+;\")\nhtml_entity_alpha_re = re.compile(r\"&\\w+;\")\namp = \"&amp;\"\n\n######################################################################\n\nclass Tokenizer:\n    def __init__(self, preserve_case=False):\n        self.preserve_case = preserve_case\n\n    def tokenize(self, s):\n        \"\"\"\n        Argument: s -- any string or unicode object\n        Value: a tokenize list of strings; conatenating this list returns the original string if preserve_case=False\n        \"\"\"        \n        # Try to ensure unicode:\n        try:\n            s = str(s)\n        except UnicodeDecodeError:\n            s = s.encode('string_escape')\n            s = str(s)\n        # Fix HTML character entitites:\n        s = self.__html2unicode(s)\n        # Tokenize:\n        words = word_re.findall(s)\n        # Possible alter the case, but avoid changing emoticons like :D into :d:\n        if not self.preserve_case:            \n            words = map((lambda x : x if emoticon_re.search(x) else x.lower()), words)\n        return words\n\n    def tokenize_random_tweet(self):\n        \"\"\"\n        If the twitter library is installed and a twitter connection\n        can be established, then tokenize a random tweet.\n        \"\"\"\n        try:\n            import twitter\n        except ImportError:\n            print(\"Apologies. The random tweet functionality requires the Python twitter library: http://code.google.com/p/python-twitter/\")\n        from random import shuffle\n        api = twitter.Api()\n        tweets = api.GetPublicTimeline()\n        if tweets:\n            for tweet in tweets:\n                if tweet.user.lang == 'en':            \n                    return self.tokenize(tweet.text)\n        else:\n            raise Exception(\"Apologies. I couldn't get Twitter to give me a public English-language tweet. Perhaps try again\")\n\n    def __html2unicode(self, s):\n        \"\"\"\n        Internal metod that seeks to replace all the HTML entities in\n        s with their corresponding unicode characters.\n        \"\"\"\n        # First the digits:\n        ents = set(html_entity_digit_re.findall(s))\n        if len(ents) > 0:\n            for ent in ents:\n                entnum = ent[2:-1]\n                try:\n                    entnum = int(entnum)\n                    s = s.replace(ent, unichr(entnum))\t\n                except:\n                    pass\n        # Now the alpha versions:\n        ents = set(html_entity_alpha_re.findall(s))\n        ents = filter((lambda x : x != amp), ents)\n        for ent in ents:\n            entname = ent[1:-1]\n            try:            \n                s = s.replace(ent, unichr(entities.name2codepoint[entname]))\n            except:\n                pass                    \n            s = s.replace(amp, \" and \")\n        return s\n\n```\n\n\n```python\nfrom math import log\n\ntok = Tokenizer(preserve_case=False)\n\ndef get_rel_popularity(c_k, c_all):\n    return log(1.0 * c_k / c_all) / log(2)\n\n\ndef print_tokens(tokens, gid = None):\n    group_name = \"overall\"\n    if gid is not None:\n        group_name = \"group %d\" % gid\n    print('=' * 5 + ' ' + group_name + ' ' + '=' * 5)\n    for t, n in tokens:\n        print(\"%s\\t%.4f\" % (t, n))\n    print\n```\n\n## Tokenize tweets\n\n1. Tokenize the tweets using the `tokenize` function that is a method of the `Tokenizer` class that we have instantiated as `tok`. \n\n1. Count the number of mentions for each tokens regardless of specific user group.\n\n1. Call `print_count` function to show how many different tokens we have.\n\n**It should print**\n```\nNumber of tokens: 7677\n```\n\n\n```python\n# YOUR CODE HERE\nraise NotImplementedError()\n\n\nmy_output.append(\"num-tokens\", num_of_tokens)\nprint(\"Number of tokens:\", num_of_tokens)\n```\n\n## Token popularity\n\nTokens that are mentioned by too few users are usually not very interesting. So we want to only keep tokens that are mentioned by at least 100 users. Filter out tokens that don't meet this requirement.\n\nCall `print_count` function to show how many different tokens we have after the filtering.\n\nCall `print_tokens` function to show top 20 most frequent tokens.\n\n**It should print**\n```\nNumber of tokens: 46\n===== overall =====\n:\t1046.0000\nrt\t920.0000\n.\t767.0000\nthe\t587.0000\ntrump\t560.0000\n\u2026\t520.0000\nto\t501.0000\n,\t497.0000\nin\t385.0000\na\t383.0000\nis\t382.0000\nof\t300.0000\n!\t285.0000\nfor\t275.0000\nand\t263.0000\non\t218.0000\ni\t216.0000\nhe\t191.0000\nthat\t190.0000\n\"\t181.0000\n```\n\n\n```python\ntimer_start()\n\n# YOUR CODE HERE\nraise NotImplementedError()\n\n\nmy_output.append(\"num-freq-tokens\", num_freq_tokens)\nmy_output.append(\"top-20-tokens\", top20)\nprint(\"Number of tokens:\", num_freq_tokens)\nprint_tokens(top20)\ntimer_stop(\"Count overall most popular tokens\")\n```\n\n## Relative Popularity\n\nFor all tokens that are mentioned by at least 100 users, compute their relative popularity in each user group. Then print the top 10 tokens with highest relative popularity in each user group. In case two tokens have same relative popularity, break the tie by printing the alphabetically smaller one.\n\n**Hint:** Let the relative popularity of a token $t$ be $p$. The order of the items will be satisfied by sorting them using (-p, t) as the key.\n\n**It should print**\n```\n===== group 0 =====\nwith\t-3.6088\ncruz\t-3.6554\nhis\t-3.6582\namp\t-3.8651\non\t-3.9608\nto\t-4.0145\n&\t-4.0875\nhttps\t-4.1699\ni\t-4.1699\nwhat\t-4.1699\n===== group 1 =====\nsanders\t-2.2854\ngop\t-2.4060\nhillary\t-2.4330\n\u2019\t-2.4463\nbernie\t-2.4835\n\"\t-2.6925\nare\t-2.7249\nthis\t-2.7633\nfor\t-2.8179\nabout\t-2.8346\n===== group 2 =====\nwith\t-4.3458\ndonald\t-4.5146\n...\t-4.7004\ngop\t-4.7279\ni\t-4.9475\non\t-4.9608\nhe\t-4.9925\n\u2026\t-5.1155\nhttps\t-5.1699\nwhat\t-5.1699\n===== group 3 =====\nbernie\t-1.5945\nsanders\t-1.6609\nhillary\t-2.2188\nand\t-2.5154\n\"\t-2.5930\nin\t-2.6114\nwill\t-2.6160\nhttps\t-2.6674\n...\t-2.7004\nyou\t-2.7004\n===== group 4 =====\nwhat\t-3.4330\nhave\t-3.4725\nbernie\t-3.5380\nthis\t-3.5518\nit\t-3.6881\n?\t-3.6912\nfor\t-3.7110\nabout\t-3.7415\nhillary\t-3.7549\nthat\t-3.7625\n===== group 5 =====\nwhat\t-1.8007\nnot\t-1.8745\nhttps\t-2.0000\nhis\t-2.0144\ncruz\t-2.0704\nit\t-2.1031\non\t-2.1243\n&\t-2.1399\namp\t-2.1489\n;\t-2.1592\n===== group 6 =====\nwill\t-1.3847\nhave\t-1.4725\n!\t-1.5850\ncruz\t-1.6919\ntrump\t-1.7199\nhttps\t-1.7549\n-\t-1.7673\n;\t-1.7807\nbe\t-1.7952\namp\t-1.8144\n===== group 7 =====\ndonald\t-1.0740\ntrump\t-1.6535\nbernie\t-1.7790\nsanders\t-1.7829\n\u2019\t-1.8613\nof\t-1.9069\n?\t-1.9186\nwith\t-1.9307\nthe\t-1.9588\nbe\t-1.9758\n```\n\n\n```python\ntimer_start()\n\n# YOUR CODE HERE\nraise NotImplementedError()\n\n\n# Following code add your solution to `my_output`\nmy_output.append(\"popular_10_in_each_group\", popular_10_in_each_group)\nfor k in range(8):\n    print_tokens(popular_10_in_each_group[k], k)\ntimer_stop(\"Print popular tokens in each group\")\n```\n\n## Important: Write your solutions to disk\n\nFollowing cell write your solutions to disk which would be read in by the grader for grading.\n\n\n```python\nmy_output.write_to_disk()\n```\n\n## Optional Ungraded Exercise\nThe users partition is generated by a machine learning algorithm that tries to group the users by their political preferences. Three of the user groups are showing supports to Bernie Sanders, Ted Cruz, and Donald Trump. \n\nIf your program looks okay on the local test data, you can try it on the larger input by submitting your program to the homework server. Observe the output of your program to larger input files, can you guess the partition IDs of the three groups mentioned above based on your output?\n\n\n```python\n# Change the values of the following three items to your guesses\nusers_support = [\n    (-1, \"Bernie Sanders\"),\n    (-1, \"Ted Cruz\"),\n    (-1, \"Donald Trump\")\n]\n\nfor gid, candidate in users_support:\n    print(\"Users from group %d are most likely to support %s.\" % (gid, candidate))\n```\n\nUncomment the lines in the cell below to print out the time taken between `time_start()` and `time_end()` at various stages of your pipeline. \n\n\n```python\n# total_time = 0.0\n# for item in timer:\n#     print(\"{}\\t{}\".format(item[0], item[1]))\n#     total_time += item[1]\n# print(\"Total time: {}\".format(total_time))\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "d7af380b812c5ae42bb765133dff5665b88086c6", "size": 48054, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Big Data Analytics Using Spark/Programming Assignment 2/HW-2.ipynb", "max_stars_repo_name": "kokuraxc/play-ground", "max_stars_repo_head_hexsha": "48b5291f3cca117e0cd0a17bf9255ec4dc1a5cdd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Big Data Analytics Using Spark/Programming Assignment 2/HW-2.ipynb", "max_issues_repo_name": "kokuraxc/play-ground", "max_issues_repo_head_hexsha": "48b5291f3cca117e0cd0a17bf9255ec4dc1a5cdd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Big Data Analytics Using Spark/Programming Assignment 2/HW-2.ipynb", "max_forks_repo_name": "kokuraxc/play-ground", "max_forks_repo_head_hexsha": "48b5291f3cca117e0cd0a17bf9255ec4dc1a5cdd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.8849315068, "max_line_length": 462, "alphanum_fraction": 0.4013817788, "converted": true, "num_tokens": 6376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12085322299118378, "lm_q2_score": 0.07921031976169719, "lm_q1q2_score": 0.009572822437363362}}
{"text": "##### Copyright 2021 The Cirq Developers\n\n\n```\n#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# Quantum circuits on Rigetti devices\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n  <td>\n    <a target=\"_blank\" href=\"https://quantumai.google/cirq/tutorials/rigetti/getting_started\">View on QuantumAI</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/Cirq/blob/master/docs/tutorials/rigetti/getting_started.ipynb\">Run in Google Colab</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://github.com/quantumlib/Cirq/blob/master/docs/tutorials/rigetti/getting_started.ipynb\">View source on GitHub</a>\n  </td>\n  <td>\n    <a href=\"https://storage.googleapis.com/tensorflow_docs/Cirq/docs/tutorials/rigetti/getting_started.ipynb\">Download notebook</a>\n  </td>\n</table>\n\n\n```\ntry:\n    import cirq\nexcept ImportError:\n    print(\"installing cirq...\")\n    !pip install --quiet cirq\n    print(\"installed cirq.\")\n    import cirq\n```\n\n    installing cirq...\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 56 kB 668 kB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 593 kB 9.5 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 541 kB 16.4 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 48 kB 4.6 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.8 MB 47.1 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 53 kB 1.9 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 220 kB 55.7 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 52 kB 1.1 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 97 kB 5.9 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 49 kB 5.6 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 10.1 MB 42.9 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 65 kB 3.2 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 145 kB 70.0 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 38.1 MB 1.3 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 44 kB 139 kB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 229 kB 66.2 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 243 kB 55.2 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.6 MB 31.7 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 109 kB 58.9 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 546 kB 40.0 MB/s \n    \u001b[?25h  Building wheel for lark (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Building wheel for retrying (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Building wheel for rpcq (setup.py) ... \u001b[?25l\u001b[?25hdone\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    markdown 3.3.7 requires importlib-metadata>=4.4; python_version < \"3.10\", but you have importlib-metadata 3.10.1 which is incompatible.\n    google-colab 1.0.0 requires six~=1.15.0, but you have six 1.16.0 which is incompatible.\n    datascience 0.10.6 requires folium==0.2.1, but you have folium 0.8.3 which is incompatible.\n    albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\n    installed cirq.\n\n\nRunning this notebook requires the pyQuil QVM and Compiler. If you are running on Google Colab or a Linux Debian machine, you can run the below cell to install them if necessary. If you are on a non-Linux Debian machine, see [these instructions](https://pyquil-docs.rigetti.com/en/stable/start.html#downloading-the-qvm-and-compiler){:.external} for installation.\n\n\n```\n! [ -z \"$(which qvm)\" ] &&\\\n  apt update &&\\\n  apt install jq &&\\\n  export LATEST_FOREST_SDK_VERSION=$(curl -s https://downloads.rigetti.com/qcs-sdk/versions | jq -r '.versions[0].sdk') &&\\\n  curl -f https://downloads.rigetti.com/qcs-sdk/forest-sdk-$LATEST_FOREST_SDK_VERSION-linux-deb.tar.bz2 -o $PWD/forest-sdk-$LATEST_FOREST_SDK_VERSION-linux-deb.tar.bz2 &&\\\n  tar -xf forest-sdk-$LATEST_FOREST_SDK_VERSION-linux-deb.tar.bz2 &&\\\n  ./forest-sdk-$LATEST_FOREST_SDK_VERSION-linux-deb/forest-sdk-$LATEST_FOREST_SDK_VERSION-linux-deb.run &&\\\n  quilc --version &&\\\n  qvm --version\n```\n\n    Hit:1 http://archive.ubuntu.com/ubuntu bionic InRelease\n    Get:2 http://archive.ubuntu.com/ubuntu bionic-updates InRelease [88.7 kB]\n    Get:3 http://security.ubuntu.com/ubuntu bionic-security InRelease [88.7 kB]\n    Hit:4 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64  InRelease\n    Get:5 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran40/ InRelease [3,626 B]\n    Get:6 http://archive.ubuntu.com/ubuntu bionic-backports InRelease [74.6 kB]\n    Ign:7 https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64  InRelease\n    Hit:8 https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64  Release\n    Get:9 http://ppa.launchpad.net/c2d4u.team/c2d4u4.0+/ubuntu bionic InRelease [15.9 kB]\n    Hit:10 http://ppa.launchpad.net/cran/libgit2/ubuntu bionic InRelease\n    Get:11 http://ppa.launchpad.net/deadsnakes/ppa/ubuntu bionic InRelease [15.9 kB]\n    Hit:12 http://ppa.launchpad.net/graphics-drivers/ppa/ubuntu bionic InRelease\n    Get:13 http://security.ubuntu.com/ubuntu bionic-security/universe amd64 Packages [1,512 kB]\n    Get:14 http://security.ubuntu.com/ubuntu bionic-security/main amd64 Packages [2,799 kB]\n    Get:15 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 Packages [3,231 kB]\n    Get:16 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 Packages [2,286 kB]\n    Get:18 http://ppa.launchpad.net/c2d4u.team/c2d4u4.0+/ubuntu bionic/main Sources [1,992 kB]\n    Get:19 http://ppa.launchpad.net/c2d4u.team/c2d4u4.0+/ubuntu bionic/main amd64 Packages [1,021 kB]\n    Get:20 http://ppa.launchpad.net/deadsnakes/ppa/ubuntu bionic/main amd64 Packages [45.3 kB]\n    Fetched 13.2 MB in 5s (2,876 kB/s)\n    Reading package lists... Done\n    Building dependency tree       \n    Reading state information... Done\n    45 packages can be upgraded. Run 'apt list --upgradable' to see them.\n    Reading package lists... Done\n    Building dependency tree       \n    Reading state information... Done\n    The following package was automatically installed and is no longer required:\n      libnvidia-common-460\n    Use 'apt autoremove' to remove it.\n    The following additional packages will be installed:\n      libjq1 libonig4\n    The following NEW packages will be installed:\n      jq libjq1 libonig4\n    0 upgraded, 3 newly installed, 0 to remove and 45 not upgraded.\n    Need to get 276 kB of archives.\n    After this operation, 930 kB of additional disk space will be used.\n    Get:1 http://archive.ubuntu.com/ubuntu bionic/universe amd64 libonig4 amd64 6.7.0-1 [119 kB]\n    Get:2 http://archive.ubuntu.com/ubuntu bionic/universe amd64 libjq1 amd64 1.5+dfsg-2 [111 kB]\n    Get:3 http://archive.ubuntu.com/ubuntu bionic/universe amd64 jq amd64 1.5+dfsg-2 [45.6 kB]\n    Fetched 276 kB in 0s (1,212 kB/s)\n    Selecting previously unselected package libonig4:amd64.\n    (Reading database ... 155632 files and directories currently installed.)\n    Preparing to unpack .../libonig4_6.7.0-1_amd64.deb ...\n    Unpacking libonig4:amd64 (6.7.0-1) ...\n    Selecting previously unselected package libjq1:amd64.\n    Preparing to unpack .../libjq1_1.5+dfsg-2_amd64.deb ...\n    Unpacking libjq1:amd64 (1.5+dfsg-2) ...\n    Selecting previously unselected package jq.\n    Preparing to unpack .../jq_1.5+dfsg-2_amd64.deb ...\n    Unpacking jq (1.5+dfsg-2) ...\n    Setting up libonig4:amd64 (6.7.0-1) ...\n    Setting up libjq1:amd64 (1.5+dfsg-2) ...\n    Setting up jq (1.5+dfsg-2) ...\n    Processing triggers for man-db (2.8.3-2ubuntu0.1) ...\n    Processing triggers for libc-bin (2.27-3ubuntu1.3) ...\n    /sbin/ldconfig.real: /usr/local/lib/python3.7/dist-packages/ideep4py/lib/libmkldnn.so.0 is not a symbolic link\n    \n      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current\n                                     Dload  Upload   Total   Spent    Left  Speed\n    100 54.1M  100 54.1M    0     0  25.5M      0  0:00:02  0:00:02 --:--:-- 25.5M\n    Verifying archive integrity...     0% \b\b\b\b\b\b\b    7% \b\b\b\b\b\b\b   14% \b\b\b\b\b\b\b   22% \b\b\b\b\b\b\b   29% \b\b\b\b\b\b\b   37% \b\b\b\b\b\b\b   44% \b\b\b\b\b\b\b   51% \b\b\b\b\b\b\b   59% \b\b\b\b\b\b\b   66% \b\b\b\b\b\b\b   74% \b\b\b\b\b\b\b   81% \b\b\b\b\b\b\b   89% \b\b\b\b\b\b\b   96% \b\b\b\b\b\b\b 100%   MD5 checksums are OK. All good.\n    Uncompressing forest-sdk-deb     0% \b\b\b\b\b\b\b    7% \b\b\b\b\b\b\b   14% \b\b\b\b\b\b\b   22% \b\b\b\b\b\b\b   29% \b\b\b\b\b\b\b   37% \b\b\b\b\b\b\b   44% \b\b\b\b\b\b\b   51% \b\b\b\b\b\b\b   59% \b\b\b\b\b\b\b   66% \b\b\b\b\b\b\b   74% \b\b\b\b\b\b\b   81% \b\b\b\b\b\b\b   89% \b\b\b\b\b\b\b   96% \b\b\b\b\b\b\b 100%  \n    Reading package lists... Done\n    Building dependency tree       \n    Reading state information... Done\n    libblas-dev is already the newest version (3.7.1-4ubuntu1).\n    libblas-dev set to manually installed.\n    liblapack-dev is already the newest version (3.7.1-4ubuntu1).\n    The following package was automatically installed and is no longer required:\n      libnvidia-common-460\n    Use 'apt autoremove' to remove it.\n    The following NEW packages will be installed:\n      libffi-dev\n    0 upgraded, 1 newly installed, 0 to remove and 45 not upgraded.\n    Need to get 156 kB of archives.\n    After this operation, 362 kB of additional disk space will be used.\n    Get:1 http://archive.ubuntu.com/ubuntu bionic/main amd64 libffi-dev amd64 3.2.1-8 [156 kB]\n    Fetched 156 kB in 0s (728 kB/s)\n    Selecting previously unselected package libffi-dev:amd64.\n    (Reading database ... 155649 files and directories currently installed.)\n    Preparing to unpack .../libffi-dev_3.2.1-8_amd64.deb ...\n    Unpacking libffi-dev:amd64 (3.2.1-8) ...\n    Setting up libffi-dev:amd64 (3.2.1-8) ...\n    Processing triggers for man-db (2.8.3-2ubuntu0.1) ...\n    Selecting previously unselected package forest-sdk.\n    (Reading database ... 155684 files and directories currently installed.)\n    Preparing to unpack forest-sdk_2.23.0.deb ...\n    Unpacking forest-sdk (2.23.0) ...\n    Setting up forest-sdk (2.23.0) ...\n    Processing triggers for man-db (2.8.3-2ubuntu0.1) ...\n    1.23.0 [e6c0939]\n    1.17.1 [cf3f91f]\n\n\nNext, run the pyQuil QVM and Compiler if they are not already running on their default ports.\n\n\n```\nimport subprocess\n\nsubprocess.Popen([\"qvm\", \"--quiet\", \"-S\"])\nsubprocess.Popen([\"quilc\", \"--quiet\", \"-R\"])\n```\n\n\n\n\n    <subprocess.Popen at 0x7fd6121add10>\n\n\n\n# Running a Bell state circuit\n\nTo demonstrate the basic functionality of the Cirq Rigetti integration, we begin constructing a basic Bell state circuit.\n\n\n```\nbell_circuit = cirq.Circuit()\nqubits = cirq.LineQubit.range(2)\nbell_circuit.append(cirq.H(qubits[0]))\nbell_circuit.append(cirq.CNOT(qubits[0], qubits[1]))\nbell_circuit.append(cirq.measure(qubits[0], qubits[1], key='m'))\nprint(bell_circuit)\n```\n\n    0: \u2500\u2500\u2500H\u2500\u2500\u2500@\u2500\u2500\u2500M('m')\u2500\u2500\u2500\n              \u2502   \u2502\n    1: \u2500\u2500\u2500\u2500\u2500\u2500\u2500X\u2500\u2500\u2500M\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\nNext, we'll import `RigettiQCSService` and list available quantum processors.\n\n\n```\nfrom cirq_rigetti import RigettiQCSService\n\nquantum_processors = RigettiQCSService.list_quantum_processors().quantum_processors\nprocessors_list = [quantum_processor.id for quantum_processor in quantum_processors]\nprint(processors_list)\n```\n\n    ['Aspen-11', 'Aspen-M-1']\n\n\nFor now, we'll instantiate the `RigettiQCSService` as a pyQuil [Quantum Virtual Machine](https://docs.rigetti.com/qcs/references/qvm){:.external} based on the topology of one of the available Rigetti quantum processors. At the time of this writing, `Aspen-11` is available.\n\nNote, in addition to the quantum processors listed above, you can also instantiate the `RigettiQCSService` by naming an arbitrary virtual device the pyQuil QVM supports. See the documentation for pyquil [get_qc](https://pyquil-docs.rigetti.com/en/stable/apidocs/pyquil.api.html#pyquil.api.get_qc){:.external} for more information. \n\n\n```\nfrom cirq_rigetti import circuit_transformers, circuit_sweep_executors, get_rigetti_qcs_service\n\nSERVICE_NAME = processors_list[0]\nprint(SERVICE_NAME)\nservice = get_rigetti_qcs_service(SERVICE_NAME, as_qvm=True, noisy=False)\nresult = service.run(bell_circuit, repetitions=1000)\n\nprint(result.histogram(key='m'))\n```\n\n    Aspen-11\n    Counter({3: 529, 0: 471})\n\n\nWe'll use the built-in `cirq.plot_state_histogram` to visually verify the results of our Bell state.\n\n\n```\ncirq.plot_state_histogram(result.histogram(key='m'))    \n```\n\nAs expected, we see states 0 (ie '00') and 3 (ie '11') as the dominant results.\n\nYou may initialize both the `RigettiQCSService` and `RigettiQCSSampler` with execution functions from the `cirq_rigetti.circuit_sweep_executor` module and transformation functions from `cirq_rigetti.circuit_transformations`.\n\nYou may invoke these functions with arguments for controlling your circuit execution at a more fine grained level. For instance, you may want add [Pragma statements](https://pyquil-docs.rigetti.com/en/stable/compiler.html#region-specific-compiler-features-through-pragma){:.external} to set the [initial rewiring](https://pyquil-docs.rigetti.com/en/stable/compiler.html#initial-rewiring){:.external} strategy, invoke [active qubit reset](https://arxiv.org/abs/2001.04449){:.external} prior to execution, or explicitly address physical qubits on the quantum computer.\n\n\n```\nfrom pyquil.quilbase import Reset, Pragma\n\ndef hook(program, measurement_id_map):\n    program._instructions.insert(0, Reset())\n    program._instructions.insert(1, Pragma('INITIAL_REWIRING', freeform_string='GREEDY'))\n    print(program)\n    return program, measurement_id_map\n\n# assign qubits explicitly to hardware or virtual machine qubits.\nqubit_id_map = {\n   qubits[0]: 4,\n   qubits[1]: 5,\n}\nexecutor = circuit_sweep_executors.with_quilc_compilation_and_cirq_parameter_resolution\ntransformer = circuit_transformers.build(qubit_id_map=qubit_id_map, qubits=qubits, post_transformation_hooks=[hook])\nservice = get_rigetti_qcs_service(SERVICE_NAME, as_qvm=True, executor=executor, transformer=transformer)\nresult = service.run(bell_circuit, repetitions=1000)\n\ncirq.plot_state_histogram(result.histogram(key='m'))\n```\n\n# Running a parameterized circuit\n\nOf course, you may be running a parameterized circuit and would like to leverage the [Quil compilers](https://pyquil-docs.rigetti.com/en/stable/compiler.html){:.external} support for parametric compilation. This affords a speedup in execution times as the Cirq Rigetti integration will only compile the circuit once for a single parameter sweep.\n\nWe start by initializing the `RigettiQCSSampler` and specifying a circuit sweep executor that supports parametric compilation. Note, that this class accepts the same `executor` and `transformer` types as `RigettiQCSService`.\n\n\n```\nfrom cirq_rigetti import get_rigetti_qcs_sampler\n\nexecutor = circuit_sweep_executors.with_quilc_parametric_compilation\nsampler = get_rigetti_qcs_sampler(SERVICE_NAME, as_qvm=True, executor=executor)\n```\n\nNext, we will initialize a parameterized circuit in Cirq along with a set of parameter values.\n\n\n```\nimport sympy\n\nqubit = cirq.LineQubit.range(1)[0]\n\ncircuit = cirq.Circuit(\n    cirq.H(qubit)**sympy.Symbol('t'),\n    cirq.measure(qubit, key='m'))\nparams = cirq.Linspace('t', start=0, stop=4, length=5)\n\nprint(circuit)\n```\n\n    0: \u2500\u2500\u2500H^t\u2500\u2500\u2500M('m')\u2500\u2500\u2500\n\n\nIn much the same way that we invoke, `RigettiQCSSerivce.run`, we invoke `RigettiQCSSampler.run_sweep` with our parameters here.\n\n\n```\nimport pandas as pd\n\nresults = sampler.run_sweep(circuit, params, repetitions=10)\ndata = {f't={result.params[\"t\"]}': [measurement[0] for measurement in result.measurements['m']] for result in results}\n\npd.DataFrame(data)\n```\n\n\n\n\n\n  <div id=\"df-8b7f6894-aff7-4811-9f82-84dcbd27acc2\">\n    <div class=\"colab-df-container\">\n      <div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>t=0.0</th>\n      <th>t=1.0</th>\n      <th>t=2.0</th>\n      <th>t=3.0</th>\n      <th>t=4.0</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n      <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-8b7f6894-aff7-4811-9f82-84dcbd27acc2')\"\n              title=\"Convert this dataframe to an interactive table.\"\n              style=\"display:none;\">\n\n  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n       width=\"24px\">\n    <path d=\"M0 0h24v24H0V0z\" fill=\"none\"/>\n    <path d=\"M18.56 5.44l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94zm-11 1L8.5 8.5l.94-2.06 2.06-.94-2.06-.94L8.5 2.5l-.94 2.06-2.06.94zm10 10l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94z\"/><path d=\"M17.41 7.96l-1.37-1.37c-.4-.4-.92-.59-1.43-.59-.52 0-1.04.2-1.43.59L10.3 9.45l-7.72 7.72c-.78.78-.78 2.05 0 2.83L4 21.41c.39.39.9.59 1.41.59.51 0 1.02-.2 1.41-.59l7.78-7.78 2.81-2.81c.8-.78.8-2.07 0-2.86zM5.41 20L4 18.59l7.72-7.72 1.47 1.35L5.41 20z\"/>\n  </svg>\n      </button>\n\n  <style>\n    .colab-df-container {\n      display:flex;\n      flex-wrap:wrap;\n      gap: 12px;\n    }\n\n    .colab-df-convert {\n      background-color: #E8F0FE;\n      border: none;\n      border-radius: 50%;\n      cursor: pointer;\n      display: none;\n      fill: #1967D2;\n      height: 32px;\n      padding: 0 0 0 0;\n      width: 32px;\n    }\n\n    .colab-df-convert:hover {\n      background-color: #E2EBFA;\n      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n      fill: #174EA6;\n    }\n\n    [theme=dark] .colab-df-convert {\n      background-color: #3B4455;\n      fill: #D2E3FC;\n    }\n\n    [theme=dark] .colab-df-convert:hover {\n      background-color: #434B5C;\n      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n      fill: #FFFFFF;\n    }\n  </style>\n\n      \n    </div>\n  </div>\n\n\n\n", "meta": {"hexsha": "83d3a7a9d31354bcc2046b97a62fba7252a4d105", "size": 49257, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/rigetti/getting_started.ipynb", "max_stars_repo_name": "Nexuscompute/Cirq", "max_stars_repo_head_hexsha": "640ef8f82d6a56ec95361388ce7976e096cca906", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-05T22:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T22:17:39.000Z", "max_issues_repo_path": "docs/tutorials/rigetti/getting_started.ipynb", "max_issues_repo_name": "pavoljuhas/Cirq", "max_issues_repo_head_hexsha": "b6d6577be61d216ce2f29f8c64ae5879cf3087d5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2022-01-16T14:12:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T03:58:46.000Z", "max_forks_repo_path": "docs/tutorials/rigetti/getting_started.ipynb", "max_forks_repo_name": "Nexuscompute/Cirq", "max_forks_repo_head_hexsha": "640ef8f82d6a56ec95361388ce7976e096cca906", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.7054545455, "max_line_length": 8244, "alphanum_fraction": 0.6716608807, "converted": true, "num_tokens": 6478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12421302132013365, "lm_q2_score": 0.0769608415180331, "lm_q1q2_score": 0.009559538648294874}}
{"text": "# DO NOT USE\nI made this back when I thought I would be using squares to determine covid heat, not a random forest algorithm\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n```\n\n\n```python\ndf = pd.read_csv('latimes-place-totals.csv')\n```\n\n\n```python\ndf.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>date</th>\n      <th>county</th>\n      <th>fips</th>\n      <th>place</th>\n      <th>confirmed_cases</th>\n      <th>note</th>\n      <th>x</th>\n      <th>y</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>2020-10-25</td>\n      <td>Alameda</td>\n      <td>1.0</td>\n      <td>Alameda</td>\n      <td>456</td>\n      <td>NaN</td>\n      <td>-122.274444</td>\n      <td>37.756111</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2020-10-25</td>\n      <td>Alameda</td>\n      <td>1.0</td>\n      <td>Albany</td>\n      <td>63</td>\n      <td>NaN</td>\n      <td>-122.297778</td>\n      <td>37.886944</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2020-10-25</td>\n      <td>Alameda</td>\n      <td>1.0</td>\n      <td>Berkeley</td>\n      <td>749</td>\n      <td>NaN</td>\n      <td>-122.272778</td>\n      <td>37.871667</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>2020-10-25</td>\n      <td>Alameda</td>\n      <td>1.0</td>\n      <td>Dublin</td>\n      <td>320</td>\n      <td>NaN</td>\n      <td>-121.935833</td>\n      <td>37.702222</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>2020-10-25</td>\n      <td>Alameda</td>\n      <td>1.0</td>\n      <td>Emeryville</td>\n      <td>102</td>\n      <td>NaN</td>\n      <td>-122.285278</td>\n      <td>37.831389</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf['place'].nunique()\n```\n\n\n\n\n    1245\n\n\n\n\n```python\ndf.info()\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 167270 entries, 0 to 167269\n    Data columns (total 8 columns):\n     #   Column           Non-Null Count   Dtype  \n    ---  ------           --------------   -----  \n     0   date             167270 non-null  object \n     1   county           167270 non-null  object \n     2   fips             165673 non-null  float64\n     3   place            167270 non-null  object \n     4   confirmed_cases  167270 non-null  int64  \n     5   note             5176 non-null    object \n     6   x                164796 non-null  float64\n     7   y                164796 non-null  float64\n    dtypes: float64(3), int64(1), object(4)\n    memory usage: 10.2+ MB\n\n\n\n```python\ndf.place.unique()\n```\n\n\n\n\n    array(['Alameda', 'Albany', 'Berkeley', ..., 'Pico', 'San Ysidro',\n           'Santa Clarita and Stevenson Ranch'], dtype=object)\n\n\n\n\n```python\n#df_test = df.groupby(by = 'place')\ndf_test = pd.DataFrame({'count' : df.groupby( ['place', 'date'] ).size()}).reset_index()\n```\n\n\n```python\ndf_test.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>place</th>\n      <th>date</th>\n      <th>count</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>90755: Long Beach</td>\n      <td>2020-08-17</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>90802: Long Beach</td>\n      <td>2020-04-29</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>90802: Long Beach</td>\n      <td>2020-04-30</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>90802: Long Beach</td>\n      <td>2020-05-01</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>90802: Long Beach</td>\n      <td>2020-05-02</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf_most_recent = df.loc[df['date'] == '2020-10-25']\ndf_before_most_recent = \n```\n\n\n```python\ndf_recent = df.groupby(by = 'date')\ndf_recent = df.loc[df['date'] == '2020-10-25']\ndf.loc[df['a'] > 10, ['a','c']]\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    Int64Index: 683 entries, 0 to 682\n    Data columns (total 8 columns):\n     #   Column           Non-Null Count  Dtype  \n    ---  ------           --------------  -----  \n     0   date             683 non-null    object \n     1   county           683 non-null    object \n     2   fips             672 non-null    float64\n     3   place            683 non-null    object \n     4   confirmed_cases  683 non-null    int64  \n     5   note             1 non-null      object \n     6   x                677 non-null    float64\n     7   y                677 non-null    float64\n    dtypes: float64(3), int64(1), object(4)\n    memory usage: 48.0+ KB\n\n\n\n```python\ndf_x_y = df[['x', 'y']][:40]\nplt.figure(figsize=(6, 6));\nplt.scatter(df_x_y['x'], df_x_y['y'])\n```\n\nDataframe 1 columns: Covid info\n- Index: (Lat1, Lon1, Lat2, Lon2)\n- Latitude 1 column\n- Longitude 1 column\n- Latitude 2 column\n- Longitude 2 column\n- number of cases in that area\n    - if there's a dot, count that\n    - if there isn't a dot, leave blank (NaN)\n- Covid 'heat'\n    - if the number of cases column is NOT blank, rate on scale from 1-10\n    - if the number of cases column is blank, take average of the 8 around it\n        - TARGET BLANK BOX: (Lat1, Lon1, Lat1 - .1, Lon1 + .1)\n        - top left (Lat1 + .1, Lon1 - .1, Lat1, Lon1)\n        - middle left (Lat1, Lon1 - .1, Lat1 - .1, Lon1)\n        - bottom left (Lat1 - .1, Lon1 - .1, Lat1 - .2, Lon1)\n        - bottom middle \n        - bottom right\n        - middle right\n        - top right\n        - top middle\n*\nPLOT AND SEE WHAT HAPPENS\n*\n\n\nDataframe 2 columns: GS info\n- index: GS number (coordinates?)\n- coordinates (CANNOT BE INDEX)\n- Gas station (GS) names\n- GS latitude\n- GS Longitude\n- heat for this GS based on region\n    - From DF1, for DF1 index = DF2 coordinates, get DF1 heat column value\n*\nPLOT: scatter plot of all gas stations (x = longitude, y = latitude, hue = heat), compare with above\n*\n\n\nDataframe 3: Error analysis\n- LOCATION INPUT: current coordinates, desired coordinates\n- RUSH INPUT: Are you in a rush?\n- \n- Only look at DF2 columns that are within this region\n- Find y = mx+b Line for these inputs\n\n\nColumns:\n- Index: GS number (from DF2)\n- Heat (from DF2)\n- Distance from point to Line (total Least squares)\n- Error metric:\n    - Weight the heat and distance columns:\n        - Do some sort of data science-y thing that determines the optimal weights\n        - Questions for weight optimization: \n            - How concerned are you about covid?\n                - Not concerned\n                - Mildly concerned\n                - Very concerned\n            - Are you in a rush?\n                - Yes!! I am rushing asap!!!\n                - Yes\n                - No\n        - Default to \"very concerned\" unless they are in a big rush (puts a higher weight on the heat of the gas station)\n        - If in a big rush, put higher weight (slightly) on the distance RMSE\n    - Overall goal: find the gas station which is the minimum of this error metric\n    \n    \n# DO KNN FOR GAS STATION CLASSIFICATION!!!\n\n\n\n```python\n# Python program to find the distance between \n# a given point and a given line in 2 D. \n\n# from https://www.geeksforgeeks.org/perpendicular-distance-between-a-point-and-a-line-in-2-d/\n  \nimport math \n  \n# Function to find distance given ax + by + c = 0\n# if we have the equation y = \ndef shortest_distance(x, y, a, b, c):\n    d = abs((a * x + b * y + c)) / (math.sqrt(a * a + b * b)) \n    return d\n\n\ndef get_a_b_c(x1, y1, x2, y2):\n    a = -(y2 - y1)\n    b = (x2 - x1)\n    c = (a * x1) + (b * y1)\n    return a, b, c\n\na = get_a_b_c(2, -1, 3, -3)[0]\nb = get_a_b_c(2, -1, 3, -3)[1]\nc = get_a_b_c(2, -1, 3, -3)[2]\n\nx = 6\ny = 8\nshortest_distance(x, y, a, b, c)\n```\n\n\n\n\n    10.285912696499032\n\n\n\n\n```python\n## Visualize what's above\n\nx1 = 2\ny1 = -1\nx2 = 3\ny2 = -3\n\ndef line_eq(x1, y1, x2, y2):\n    slope = (y1 - y2) / (x1 - x2)\n    b = y1 - (slope * x1)\n    return (slope, b)\n    \n    \nx_graph = np.linspace(x1, x2)\ny_graph = (line_eq(x1, y1, x2, y2)[0] * x_graph) + line_eq(x1, y1, x2, y2)[1]\n\nplt.plot(x_graph, y_graph, '-r')\nplt.title('Example')\n```\n\n\n```python\nfrom sympy.solvers import solve, linsolve\nfrom sympy import symbols\n```\n\n\n```python\n# for red line above:\nx1 = 2\ny1 = -1\nx2 = 3\ny2 = -3\nslope = line_eq(x1, y1, x2, y2)[0] \nb = line_eq(x1, y1, x2, y2)[1]\n\n#given a point with coordinates (x_a, y_a), find equation of perpendicular line\nx_a = 2.2\ny_a = 2.5\n# the slope will be the negative inverse of the line it's perpendicular to\nslope_a = -1/slope\n# find b by plugging in the coordinates of our point\nb_a = y_a - (slope_a * x_a)\n\nprint('slope: ', slope)\nprint('b: ', b)\nprint('slope_a: ', slope_a)\nprint('b_a: ', b_a)\n\n```\n\n    slope:  -2.0\n    b:  3.0\n    slope_a:  0.5\n    b_a:  1.4\n\n\n\n```python\n# Brute force to find point of intersection (poi) between these lines\nx_poi = (b_a - b) / (slope - slope_a)\ny_poi = (slope * x_poi) + b\nprint((x_poi, y_poi))\n```\n\n    (0.64, 1.72)\n\n\n\n```python\nprint((x1, x2))\nprint((x_poi, x_a))\n```\n\n    (2, 3)\n    (0.64, 2.2)\n\n\n\n```python\nx_z = np.linspace(0, 2)\ny_z = (slope * x_z) + b\n\n\nx_z2 = np.linspace(x_poi, x_a)\ny_z2 = (slope_a * x_z2) + b_a\n\n\nfig = plt.figure(figsize = (10,10))\nax1 = fig.add_subplot(111)\n\nax1.scatter(x_z, y_z, s=10, c='b', marker=\"s\", label='first')\nax1.scatter(x_z2, y_z2, s=10, c='r', marker=\"o\", label='second')\nplt.legend(loc='upper left');\nplt.xlim(-5, 5)\nplt.ylim(-5, 5)\nplt.show()\n```\n\n\n```python\nx_graph = np.linspace(x_a, x_poi)\ny_graph = (slope_a * x_graph) + b_a\n\nplt.plot(x_graph, y_graph, '-r')\nplt.title('Example')\n```\n\n\n```python\nx_graph_2 = np.linspace(x1, x2)\ny_graph_2 = (line_eq(x_a, y_a, x_b, y_b)[0] * x_graph_2) + line_eq(x_a, y_a, x_b, y_b)[1]\nplt.plot(x_graph, y_graph, '-r')\nplt.title('Example')\n```\n\n\n```python\nx_graph = np.linspace(x1, x2)\ny_graph = (line_eq(x1, y1, x2, y2)[0] * x_graph) + line_eq(x1, y1, x2, y2)[1]\n\nx_graph_2 = np.linspace(x_a, x_poi)\ny_graph_2 = (slope_a * x_graph) + b_a\n\n#x_graph_2 = np.linspace(x1, x2)\n#y_graph_2 = (line_eq(x_a, y_a, x_b, y_b)[0] * x_graph_2) + line_eq(x_a, y_a, x_b, y_b)[1]\n\n\nfig = plt.figure()\nax1 = fig.add_subplot(111)\n\nax1.scatter(x_graph, y_graph, s=10, c='b', marker=\"s\", label='first')\nax1.scatter(x_graph_2, y_graph_2, s=10, c='r', marker=\"o\", label='second')\nplt.legend(loc='upper left');\nplt.show()\n```\n\n\n```python\nline_eq(x1, y1, x2, y2)[0]\n```\n\n\n\n\n    -2.0\n\n\n\n\n```python\ndf.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>date</th>\n      <th>county</th>\n      <th>fips</th>\n      <th>place</th>\n      <th>confirmed_cases</th>\n      <th>note</th>\n      <th>x</th>\n      <th>y</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>2020-10-25</td>\n      <td>Alameda</td>\n      <td>1.0</td>\n      <td>Alameda</td>\n      <td>456</td>\n      <td>NaN</td>\n      <td>-122.274444</td>\n      <td>37.756111</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2020-10-25</td>\n      <td>Alameda</td>\n      <td>1.0</td>\n      <td>Albany</td>\n      <td>63</td>\n      <td>NaN</td>\n      <td>-122.297778</td>\n      <td>37.886944</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2020-10-25</td>\n      <td>Alameda</td>\n      <td>1.0</td>\n      <td>Berkeley</td>\n      <td>749</td>\n      <td>NaN</td>\n      <td>-122.272778</td>\n      <td>37.871667</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>2020-10-25</td>\n      <td>Alameda</td>\n      <td>1.0</td>\n      <td>Dublin</td>\n      <td>320</td>\n      <td>NaN</td>\n      <td>-121.935833</td>\n      <td>37.702222</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>2020-10-25</td>\n      <td>Alameda</td>\n      <td>1.0</td>\n      <td>Emeryville</td>\n      <td>102</td>\n      <td>NaN</td>\n      <td>-122.285278</td>\n      <td>37.831389</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n#find the point at which these two equations intersect: use sympy\n\nx, y, z = symbols('x, y, z')\n#linsolve([slope*x + y + z - 1, x + y + 2*z - 3 ], (x, y, z))\ncoords = linsolve([y - (slope*x + b), y - (slope_a*x + b_a)], (x, y))\n\nx_b = float(coords.args[0][0])\ny_b = float(coords.args[0][1])\n\nprint(x_b, y_b)\n```\n", "meta": {"hexsha": "eb9b34d157f4eec8ba31870d4f10b098359bfded", "size": 91345, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "code/draft_code/create_squares.ipynb", "max_stars_repo_name": "sophiascarano/COVID-19_wildfire_CA_amenity_avoidance_app", "max_stars_repo_head_hexsha": "c07cb84ce2283439e26dd9102fa75db22d791dcb", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/draft_code/create_squares.ipynb", "max_issues_repo_name": "sophiascarano/COVID-19_wildfire_CA_amenity_avoidance_app", "max_issues_repo_head_hexsha": "c07cb84ce2283439e26dd9102fa75db22d791dcb", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/draft_code/create_squares.ipynb", "max_forks_repo_name": "sophiascarano/COVID-19_wildfire_CA_amenity_avoidance_app", "max_forks_repo_head_hexsha": "c07cb84ce2283439e26dd9102fa75db22d791dcb", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-11-05T19:48:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-21T22:38:57.000Z", "avg_line_length": 89.3786692759, "max_line_length": 13496, "alphanum_fraction": 0.8076742022, "converted": true, "num_tokens": 4508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.03258974629287097, "lm_q1q2_score": 0.009482992606023642}}
{"text": "# Jupyter Book\n> Documentaci\u00f3n usando jupyter notebook.\n\n- toc: true \n- badges: false\n- comments: true\n- categories: [jupyter]\n- image: images/jb.png\n\n# Introducci\u00f3n\n\n[Jupyter Book](https://jupyterbook.org/intro.html) es un proyecto de c\u00f3digo abierto para crear libros y documentos mediante Jupyter Notebooks y/o Markdown.\n\nAlgunas caracter\u00edsticas importantes del uso de Jupyter Book:\n\n* contenido con calidad de publicaci\u00f3n que incluya figuras, s\u00edmbolos matem\u00e1ticos, citas y referencias cruzadas!\n* escribir contenido como Jupyter Notebooks, markdown o reStructuredText\n* Agregue interactividad a su libro, por ejemplo, alternar la visibilidad de las celdas, conectarse con un servicio en l\u00ednea como **Binder** e incluir resultados interactivos (por ejemplo, figuras y widgets).\n* generar una variedad de resultados, incluidos sitios web (HTML, CSS, JS), markdown y PDF.\n* una interfaz de l\u00ednea de comandos para crear libros r\u00e1pidamente, por ejemplo, `jupyter-book build mybook`\n\n\nEn esta sesi\u00f3n, se muestra un ejemplo de c\u00f3mo crear un Jupyter Book desde cero y algunas de las caracter\u00edsticas clave que ofrece Jupyter Book.\n\n> **Nota**: Puede encontrar los c\u00f3digos de este ejemplo en el siguiente [repositorio](https://gitlab.com/FAAM/jb_example). Por otro lado, puede revisar el siguente [link](https://faam.gitlab.io/jb_example/jb_example/index.html) para ver la compilaci\u00f3n con [GitLab CI/CD](https://docs.gitlab.com/ee/ci/).\n\n# Primeros pasos\n\n## Instalaci\u00f3n\n\nPara instalar **Jupyter Book**, necesitar\u00e1 usar la l\u00ednea de comando. Si ha instalado Anaconda, puede usar:\n\n```\nconda install -c conda-forge jupyter-book\n```\n\nDe lo contrario, puede instalar con pip:\n\n\n```\npip install jupyter-book\n```\n\n\n\n\n## Crear una estructura de libro\n\nJupyter Book viene con una herramienta que le permite crear y construir libros r\u00e1pidamente. Para crear el esqueleto del libro, escriba lo siguiente en la l\u00ednea de comando:\n\n```\njupyter-book create jupiter\n```\n\n> **Nota**: Aqu\u00ed llamamos al libro `jupiter`, pero puedes elegir llamar a tu libro como quieras.\n\n\nAhora tendr\u00e1s un nuevo directorio llamado `jupiter` (o como quieras llamar a tu libro), con el siguiente contenido:\n\n```\njupiter\n  \u251c\u2500\u2500 _config.yml\n  \u251c\u2500\u2500 _toc.yml\n  \u251c\u2500\u2500 content.md\n  \u251c\u2500\u2500 intro.md\n  \u251c\u2500\u2500 markdown.md\n  \u251c\u2500\u2500 notebooks.ipynb\n  \u251c\u2500\u2500 references.bib\n  \u2514\u2500\u2500 requirements.txt\n```\n\nen donde:\n* `_config.yml`: archivo que contiene las configuraciones del proyecto.\n* `_toc.yml`: archivo que ordena los cap\u00edtulos del libro.\n* `content.md`: archivo gen\u00e9rico `.md`.\n* `intro.md`: archivo gen\u00e9rico `.md`.\n* `markdown.md`: archivo gen\u00e9rico `.md`.\n* `notebooks.ipynb`: archivo gen\u00e9rico `.ipynb`.\n* `references.bib`: archivo para a\u00f1adir las referencias.\n* `requirements.txt`: archivo que contiene las dependencias  python) del proyecto.\n\n## Re-estructuraci\u00f3n del directorio\n\nJupyter Book admite varios tipos de archivos:\n\n* Markdown (.md)\n* notebooks (.ipynb)\n* etc.\n\nComo Markdown y Jupyter Notebooks probablemente ser\u00e1n los tipos de archivo m\u00e1s comunes que usar\u00e1, se mostrar\u00e1 un ejemplo de ello.\n\nLo primero ser\u00e1 eliminar los archivos de inicio en el directorio:\n\n* content.md\n* intro.md\n* markdown.md\n* notebooks.ipynb\n\n\nAs\u00ed que ejecutamos por l\u00ednea de comando:\n```\nrm content.md intro.md markdown.md notebooks.ipynb\n```\n\n\nPor otro lado, nuestro proyecto estar\u00e9 conformado por tres archivos:\n\n* index.md\n* Introduction.md\n* great_red_spot.ipynb\n\nLuego, debemos indicar c\u00f3mo ser\u00e1n mostrados estos documentos en el archivo `_toc.yml`. La estructura ser\u00e1 la siguiente:\n\n```\nformat: jb-book\nroot: index\nchapters:\n- file: Introduction\n- file: great_red_spot\n```\n\nEn este caso, `root: index` corresponde al primer archivo que se visualiza en el jupyter-book. Dentro del archivo `index.md` escribiremos:\n\n\n<pre>\n# Home\n\njupyter book example\n\n## Contenidos\n\n```{tableofcontents}\n```\n\n</pre>\n\n## Agregar un archivo Markdown\n\nSe comienza por agregar un archivo de markdown. Con alg\u00fan editor a elecci\u00f3n (por ejemplo, jupyter notebook o jupyterlab) se crea un nuevo archivo markdown llamado `Introduction.md`.\n\nSe usa este archivo como demostraci\u00f3n de algunos de los principales tipos de contenido que puede agregar en Jupyter-Book.\n\n### Texto \n\nSe agrega un texto de Markdown simple a nuestro archivo. Si no est\u00e1 familiarizado con la sintaxis de markdown, consulte [Markdown Cheat Sheet](https://www.markdownguide.org/cheat-sheet/). Puede copiar y pegar el siguiente contenido directamente en su archivo `Introduction.md`.\n\n```\n# Jupiter Book\n\nThis book contains information about the planet **Jupiter** - the fifth planet from the sun and the largest planet in the solar system!\n```\n\n### Figuras\n\nPuedes incluir figuras en tu Jupyter Book usando la siguiente sintaxis:\n<pre>\n```{figure} my_image.png\n---\nheight: 150px\nname: my-image\n---\nHere is my image's caption!\n```\n</pre>\n\n\n\n\n\nSi bien la imagen puede estar contenida y referenciada desde el directorio ra\u00edz, tambi\u00e9n se puede incluir im\u00e1genes a trav\u00e9s de URL. Incluyamos una imagen del planeta J\u00fapiter en nuestro archivo `Introduction.md` usando lo siguiente:\n\n<pre>\n```{figure} https://solarsystem.nasa.gov/system/resources/detail_files/2486_stsci-h-p1936a_1800.jpg\n---\nheight: 300px\nname: jupiter-figure\n---\nThe beautiful planet Jupiter!\n```\n</pre>\n\nLa raz\u00f3n por la que le damos un \"nombre\" a nuestra imagen es para que podamos hacer referencia a ella f\u00e1cilmente con la sintaxis:\n\n```\n{numref}`jupiter-figure`\n```\n\nSe agregar\u00e1 una oraci\u00f3n que incluya esta referencia. El archivo completo ahora deber\u00eda verse as\u00ed:\n\n<pre>\n# Jupiter Book\n\nThis book contains information about the planet Jupiter - the fifth planet from the sun and the largest planet in the solar system! {numref}`jupiter-figure` below shows an image of Jupiter captured by the Hubble Space Telescope on June 27, 2019.\n\n```{figure} https://solarsystem.nasa.gov/system/resources/detail_files/2486_stsci-h-p1936a_1800.jpg\n---\nheight: 300px\nname: jupiter-figure\n---\nThe beautiful planet Jupiter! Source: [NASA](https://solarsystem.nasa.gov/resources/2486/hubbles-new-portrait-of-jupiter/?category=planets_jupiter).\n```\n</pre>\n\nEn este punto, probablemente se deber\u00eda crear nuetro libro para asegurarnos de que tenga el aspecto esperado. Para hacer eso, primero necesitamos modificar nuestro archivo `_toc.yml`. Este archivo contiene la tabla de contenido de nuestro libro. Abra ese archivo ahora y elimine todo lo que hay all\u00ed. Luego, simplemente agregue lo siguiente:\n\n```\n- file: introduction\n```\n\nAhora podemos construir nuestro libro desde la l\u00ednea de comandos asegur\u00e1ndonos de que estamos en el directorio ra\u00edz de nuestro libro y luego usando:\n\n```\njupyter-book build .\n```\n\nUna vez finalizada la compilaci\u00f3n, tendr\u00e1 un nuevo subdirectorio llamado`_build/html/` en la ra\u00edz de su libro, navegue hasta esa ubicaci\u00f3n y abra `_build/html/index.html`. Deber\u00eda verse algo como esto:\n\n\n\n### Equaciones matem\u00e1ticas\n\nJupyter Book usa [MathJax](https://www.mathjax.org/) para componer matem\u00e1ticas, lo que le permite agregar matem\u00e1ticas de estilo LaTeX a su libro. Puede agregar matem\u00e1ticas en l\u00ednea, bloques matem\u00e1ticos y ecuaciones numeradas a su libro Jupyter. Sigamos adelante y creemos un nuevo encabezado en nuestro archivo Introduction.md que incluye algunas matem\u00e1ticas.\n\nLas matem\u00e1ticas en l\u00ednea se pueden definir usando `$` de la siguiente manera:\n\n<pre>\nJupiter has a mass of:  $m_{j} \\approx 1.9 \\times 10^{27} kg$\n</pre>\n\nJupiter has a mass of:  $m_{j} \\approx 1.9 \\times 10^{27} kg$\n\nLos bloques matem\u00e1ticos se pueden definir usando la notaci\u00f3n `$$`:\n<pre>\n$$m_{j} \\approx 1.9 \\times 10^{27} kg$$\n</pre>\n\n\n$$m_{j} \\approx 1.9 \\times 10^{27} kg$$\n\n> **Nota**: Si lo prefiere, los bloques matem\u00e1ticos tambi\u00e9n se pueden definir con `\\begin{equation}` en lugar de `$$`.\n\nLas ecuaciones numeradas se pueden definir as\u00ed (este es el estilo que te recomiendo que uses con m\u00e1s frecuencia):\n<pre>\n```{math}\n:label: my_label\nm_{j} \\approx 1.9 \\times 10^{27} kg\n```\n</pre>\n\nAgreguemos m\u00e1s contenido a nuestro libro. Copie y agregue el siguiente texto a su archivo `Introduction.md`:\n\n\n<pre>\n## The Mass of Jupiter\n\nWe can estimate the mass of Jupiter from the period and size of an object orbiting it. For example, we can use Jupiter's moon Callisto to estimate it's mass.\n\nCallisto's period: $p_{c}=16.7 days$\n\nCallisto's orbit radius: $r_{c}=1,900,000 km$\n\nNow, using [Kepler's Law](https://solarsystem.nasa.gov/resources/310/orbits-and-keplers-laws/) we can work out the mass of Jupiter.\n\n```{math}\n:label: eq1\nm_{j} \\approx \\frac{r_{c}}{p_{c}} \\times 7.9 \\times 10^{10}\n```\n\n```{math}\n:label: eq2\nm_{j} \\approx 1.9 \\times 10^{27} kg\n```\n</pre>\n\nA continuaci\u00f3n, puede reconstruir su libro (`jupyter-book build .`) y abrir `_build/html/index.html` para asegurarse de que todo se est\u00e9 procesando como se esperaba.\n\n### Controlando el dise\u00f1o de la p\u00e1gina\nHay varias formas diferentes de controlar el dise\u00f1o de las p\u00e1ginas de su Jupyter Book. El cambio de dise\u00f1o que utilizo con m\u00e1s frecuencia es agregar contenido a un margen en la p\u00e1gina. Puede agregar un margen usando la siguiente directiva:\n\n<pre>\n```{margin} An optional title\nSome margin content.\n```\n</pre>\n\nAgreguemos algo de contenido marginal al libro:\n\n\n<pre>\n```{margin} Did you know?\nJupiter is 11.0x larger than Earth!\n```\n</pre>\n\n### Advertencias\n\nHay todo tipo de [advertencias](https://jupyterbook.org/content/content-blocks.html) diferentes que puede usar en Jupyter Book que se enumeran aqu\u00ed en la documentaci\u00f3n de Jupyter Book. Las advertencias se crean con la sintaxis:\n\n<pre>\n```{note}\nI am a useful note!\n```\n</pre>\n\nNo dude en agregar la siguiente advertencia a `Introduction.md`:\n\n<pre>\n```{hint}\nNASA provides a lot more information about the physical characteristics of Jupiter [here](https://solarsystem.nasa.gov/planets/jupiter/by-the-numbers/).\n```\n</pre>\n\n### Citas y bibliograf\u00eda\nEl \u00faltimo contenido corresponde a referencias y una bibliograf\u00eda. Puede agregar citas de cualquier trabajo almacenado en el archivo Bibtex `Reference.bib` que se encuentra en el directorio ra\u00edz de su libro.\n\nPara incluir una cita en su libro, agregue una entrada bibtex a `references.bib`, por ejemplo:\n\n```\n@article{mayor1995jupiter,\n    title={A Jupiter-mass companion to a solar-type star},\n    author={Mayor, Michel and Queloz, Didier},\n    journal={Nature},\n    volume={378},\n    number={6555},\n    pages={355--359},\n    year={1995},\n    publisher={Nature Publishing Group}\n}\n\n@article{guillot1999interiors,\n    title={Interiors of giant planets inside and outside the solar system},\n    author={Guillot, Tristan},\n    journal={Science},\n    volume={286},\n    number={5437},\n    pages={72--77},\n    year={1999},\n    publisher={American Association for the Advancement of Science}\n}\n```\n\n> **Nota:** Consulte la [documentaci\u00f3n de BibTex](http://www.bibtex.org/Using/) para obtener informaci\u00f3n sobre el estilo de referencia de BibTex. Google Scholar facilita la exportaci\u00f3n de un formato de cita bibtex.\n\nA continuaci\u00f3n, puede hacer referencia al trabajo en su libro utilizando la siguiente directiva:\n\n```\n{cite}`mayor1995jupiter`\n```\n\nO para m\u00faltiples citas:\n\n```\n{cite}`mayor1995jupiter,guillot1999interiors`\n```\n\nLuego puede crear una bibliograf\u00eda a partir de `reference.bib` usando:\n\n<pre>\n```{bibliography} references.bib\n```\n</pre>\n\nPor ejemplo, intente agregar esto a su archivo `Introduction.md`:\n<pre>\nThere might even be more planets out there with a similar mass to Jupiter {cite}`mayor1995jupiter,guillot1999interiors`!\n\n## Bibliography\n\n```{bibliography} references.bib\n```\n</pre>\n\nSu archivo final `Introduction.md` deber\u00eda verse as\u00ed:\n\n\n<pre>\n# Jupiter Book\n\nThis book contains information about the planet Jupiter - the fifth planet from the sun and the largest planet in the solar system! {numref}`jupiter-figure` below shows an image of Jupiter captured by the Hubble Space Telescope on June 27, 2019.\n\n```{figure} https://solarsystem.nasa.gov/system/resources/detail_files/2486_stsci-h-p1936a_1800.jpg\n---\nheight: 300px\nname: jupiter-figure\n---\nThe beautiful planet Jupiter! Source: [NASA](https://solarsystem.nasa.gov/resources/2486/hubbles-new-portrait-of-jupiter/?category=planets_jupiter).\n```\n\n## The Mass of Jupiter\n\nWe can estimate the mass of Jupiter from the period and size of an object orbiting it. For example, we can use Jupiter's moon Callisto to estimate it's mass.\n\nCallisto's period: $p_{c}=16.7 days$\n\nCallisto's orbit radius: $r_{c}=1,900,000 km$\n\nNow, using [Kepler's Law](https://solarsystem.nasa.gov/resources/310/orbits-and-keplers-laws/) we can work out the mass of Jupiter.\n\n```{math}\n:label: eq1\nm_{j} \\approx \\frac{r_{c}}{p_{c}} \\times 7.9 \\times 10^{10}\n```\n\n```{math}\n:label: eq2\nm_{j} \\approx 1.9 \\times 10^{27} kg\n```\n\n```{margin} Did you know?\nJupiter is 11.0x larger than Earth!\n```\n\n```{hint}\nNASA provides a lot more information about the physical characteristics of Jupiter [here](https://solarsystem.nasa.gov/planets/jupiter/by-the-numbers/).\n```\n\nThere might even be more planets out there with a similar mass to Jupiter {cite}`mayor1995jupiter,guillot1999interiors`!\n\n## Bibliography\n\n```{bibliography} references.bib\n```\n</pre>\n\nY deber\u00eda renderizarse as\u00ed:\n\n\n## Agregar un archivo de contenido de Jupyter Notebook\n\nTodos los flujos de trabajo de formato y estilo que vimos en markdown tambi\u00e9n se aplican a un Jupyter Notebook; simplemente agr\u00e9guelos a una celda de markdown y listo. \n\nComencemos con lo siguiente:\n\n* Cree un nuevo notebook llamado `great_red_spot.ipynb`;\n* Agregue este archivo a su `_toc.yml`;\n* Agregue una celda de markdown con el siguiente contenido:\n\n<pre>\n# The Great Red Spot\n\nJupiter\u2019s iconic Great Red Spot (GRS) is actually an enormous storm that is bigger than Earth that has raged for hundreds of years! {numref}`great-red-spot` below shows an image of Jupiter captured by the Hubble Space Telescope on June 27, 2019.\n\n```{figure} https://solarsystem.nasa.gov/system/resources/detail_files/626_PIA21775.jpg\n---\nheight: 300px\nname: great-red-spot\n---\nJupiter's Great Red Spot! Source: [NASA](https://solarsystem.nasa.gov/resources/626/jupiters-great-red-spot-in-true-color/?category=planets_jupiter).\n```\n\nJupiter's GRS has been observed to be shrinking for about the last century and a half! [Here](https://github.com/UBC-DSCI/jupyterdays/tree/master/jupyterdays/sessions/beuzen/data) is some data of the length of the GRS spanning the last ~150 years which we can use to investigate this phenomenon.\n</pre>\n\n\u00a1Ahora intente construir su libro (`jupyter-book build .`) para asegurarse de que todo se vea bien! Usando la barra de contenido del lado izquierdo, navegue a la nueva p\u00e1gina \u201cThe Great Red Spot\u201d, que deber\u00eda verse as\u00ed:\n\n\n\n\u00a1Ok genial! Ahora importemos los datos a los que hicimos referencia para que podamos crear algunos gr\u00e1ficos.\n\nCree una nueva celda de c\u00f3digo debajo de la celda de rebaja actual y agregue el siguiente c\u00f3digo para leer en nuestro conjunto de datos de GRS como un marco de datos de Pandas.\n\n```python\nimport pandas as pd\npd.options.plotting.backend = \"plotly\"\n\nurl = \"https://raw.githubusercontent.com/UBC-DSCI/jupyterdays/master/jupyterdays/sessions/beuzen/data/GRS_data.csv\"\ndf = pd.read_csv(url)\ndf['Year'] = df['Year'].astype(int) \ndf.head()\n```\n\n> **Nota**: Estamos imprimiendo la salida en la pantalla con el uso de `df.head()` y esto se mostrar\u00e1 en nuestro Jupyter Book renderizado.\n\nSi reconstruye su libro (`jupyter-book build .`) en este punto, ver\u00e1 algo como lo siguiente:\n\n\n\nAhora, podemos usar estos datos para crear algunos gr\u00e1ficos.\n\nLas tramas en su Jupyter Book pueden ser est\u00e1ticas (por ejemplo, `matplotlib`, `seaborn`) o interactivas (por ejemplo, `altair`, `plotly`, `bokeh`). \nPara este tutorial, crearemos algunos gr\u00e1ficos de ejemplo usando `Plotly` (a trav\u00e9s del backend de Pandas).\n\nPrimero creemos un diagrama de dispersi\u00f3n simple de nuestros datos. Cree una nueva celda de c\u00f3digo en su cuaderno y agregue el siguiente c\u00f3digo:\n\n```python\nimport plotly.io as pio\npio.renderers.default = \"notebook\"\nfig = df.plot.scatter(x=\"Year\", y=\"GRS Length\", color=\"Recorder\",\n                      range_x=[1870, 2030], range_y=[10, 40],\n                      width=650, height=400)\nfig.update_layout(title={'text': \"Great Red Spot Size\", 'x':0.5, 'y':0.92})\nfig.update_traces(marker=dict(size=7))\n```\n\nYa que estamos en eso, creemos tambi\u00e9n una trama animada. Cree otra celda de c\u00f3digo nueva y agregue el siguiente c\u00f3digo:\n```python\nfig = df.plot.scatter(x=\"Year\", y=\"GRS Length\",\n                      animation_frame=\"Year\",\n                      range_x=[1870, 2030], range_y=[10, 40],\n                      width=600, height=520)\nfig.update_layout(title={'text': \"Great Red Spot Size Animation\", 'x':0.5, 'y':0.94})\nfig.layout.updatemenus[0].buttons[0].args[1][\"frame\"][\"duration\"] = 200\nfig.update_traces(marker=dict(size=10))\n```\n\n> **Nota:** Plotly tiene [diferentes renderizadores](https://plotly.com/python/renderers/) disponibles para generar gr\u00e1ficos. Es posible que deba experimentar con renderizadores para obtener el resultado que desea en su Jupyter Book. He descubierto que `pio.renderers.default = \"notebook\"` funciona con la versi\u00f3n actual de Jupyter Book.\n\n\u00a1Ahora, reconstruyamos nuestro libro y echemos un vistazo!\n\n\n\nEs posible que desee ocultar parte del c\u00f3digo en su libro, \u00a1no hay problema! Eso tambi\u00e9n se hace f\u00e1cilmente con Jupyter Book. \n\nEl que nos interesa aqu\u00ed es ocultar la entrada de c\u00f3digo. Podemos hacerlo f\u00e1cilmente agregando la etiqueta `hide-input` a la celda que deseamos ocultar. Hay varias formas de agregar etiquetas a la celda en Jupyter Notebooks. En Jupyter Lab, haga clic en el icono de engranaje en la barra lateral izquierda y luego agregue la etiqueta deseada como se muestra a continuaci\u00f3n:\n\n\n\nContin\u00fae y agregue las etiquetas `hide-input` a ambas celdas de trazado en su archivo `great_red_spot.ipynb`. Cuando reconstruyas el libro, ver\u00e1s que la entrada del c\u00f3digo est\u00e1 oculta (pero se puede alternar con el \u00edcono `+`):\n\n\n\n> **Nota**: Tambi\u00e9n puede almacenar el contenido de la libreta como valores, gr\u00e1ficos o marcos de datos en variables que se pueden utilizar en toda su libreta mediante la herramienta `glue`.\n\n# Referencias\n\n\n* [Jupyter-Book - Documentation](https://jupyterbook.org/intro.html)\n* [Tutorial - Jupyter Book](https://ubc-dsci.github.io/jupyterdays/sessions/beuzen/jupyter_book_tutorial.html)\n", "meta": {"hexsha": "7d38b3393da6bd6c635f5f4a9af2a23727d0ca5c", "size": 26728, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "_notebooks/2021-08-11-jb.ipynb", "max_stars_repo_name": "fralfaro/ds_blog", "max_stars_repo_head_hexsha": "a13f2ea62996a1aa2049015e7c96754a374520a1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_notebooks/2021-08-11-jb.ipynb", "max_issues_repo_name": "fralfaro/ds_blog", "max_issues_repo_head_hexsha": "a13f2ea62996a1aa2049015e7c96754a374520a1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-06T14:59:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-07T02:45:59.000Z", "max_forks_repo_path": "_notebooks/2021-08-11-jb.ipynb", "max_forks_repo_name": "fralfaro/ds_blog", "max_forks_repo_head_hexsha": "a13f2ea62996a1aa2049015e7c96754a374520a1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-09T19:41:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-09T19:41:09.000Z", "avg_line_length": 35.0301441678, "max_line_length": 382, "alphanum_fraction": 0.5980619575, "converted": true, "num_tokens": 4865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08389038641057994, "lm_q2_score": 0.11124120356108878, "lm_q1q2_score": 0.00933206755151772}}
{"text": "## Install TensorTrade\n\n\n```python\n!python3 -m pip install -e .. -U\n```\n\n    Obtaining file:///Users/adam/Desktop/Capfolio/tensortrade\n    Requirement already satisfied, skipping upgrade: numpy==1.16.4 in /usr/local/lib/python3.7/site-packages (from tensortrade==0.2.0b0) (1.16.4)\n    Requirement already satisfied, skipping upgrade: pandas==0.25.0 in /usr/local/lib/python3.7/site-packages (from tensortrade==0.2.0b0) (0.25.0)\n    Requirement already satisfied, skipping upgrade: gym==0.14.0 in /usr/local/lib/python3.7/site-packages (from tensortrade==0.2.0b0) (0.14.0)\n    Requirement already satisfied, skipping upgrade: pyyaml==5.1.2 in /usr/local/lib/python3.7/site-packages (from tensortrade==0.2.0b0) (5.1.2)\n    Requirement already satisfied, skipping upgrade: sympy==1.4 in /usr/local/lib/python3.7/site-packages (from tensortrade==0.2.0b0) (1.4)\n    Requirement already satisfied, skipping upgrade: pytz>=2017.2 in /usr/local/lib/python3.7/site-packages (from pandas==0.25.0->tensortrade==0.2.0b0) (2019.2)\n    Requirement already satisfied, skipping upgrade: python-dateutil>=2.6.1 in /usr/local/Cellar/jupyterlab/1.0.0_5/libexec/vendor/lib/python3.7/site-packages (from pandas==0.25.0->tensortrade==0.2.0b0) (2.7.3)\n    Requirement already satisfied, skipping upgrade: pyglet<=1.3.2,>=1.2.0 in /usr/local/lib/python3.7/site-packages (from gym==0.14.0->tensortrade==0.2.0b0) (1.3.2)\n    Requirement already satisfied, skipping upgrade: cloudpickle~=1.2.0 in /usr/local/lib/python3.7/site-packages (from gym==0.14.0->tensortrade==0.2.0b0) (1.2.1)\n    Requirement already satisfied, skipping upgrade: scipy in /usr/local/lib/python3.7/site-packages (from gym==0.14.0->tensortrade==0.2.0b0) (1.4.1)\n    Requirement already satisfied, skipping upgrade: six in /usr/local/Cellar/jupyterlab/1.0.0_5/libexec/vendor/lib/python3.7/site-packages (from gym==0.14.0->tensortrade==0.2.0b0) (1.11.0)\n    Requirement already satisfied, skipping upgrade: mpmath>=0.19 in /usr/local/lib/python3.7/site-packages (from sympy==1.4->tensortrade==0.2.0b0) (1.1.0)\n    Requirement already satisfied, skipping upgrade: future in /usr/local/lib/python3.7/site-packages (from pyglet<=1.3.2,>=1.2.0->gym==0.14.0->tensortrade==0.2.0b0) (0.17.1)\n    Installing collected packages: tensortrade\n      Attempting uninstall: tensortrade\n        Found existing installation: TensorTrade 0.2.0b0\n        Uninstalling TensorTrade-0.2.0b0:\n          Successfully uninstalled TensorTrade-0.2.0b0\n      Running setup.py develop for tensortrade\n    Successfully installed tensortrade\n\n\n## Setup Data Fetching\n\n\n```python\nimport ssl\nimport pandas as pd\n\nssl._create_default_https_context = ssl._create_unverified_context # Only used if pandas gives a SSLError\n\ndef fetch(exchange_name, symbol, timeframe):\n    url = \"https://www.cryptodatadownload.com/cdd/\"\n    filename = \"{}_{}USD_{}.csv\".format(exchange_name, symbol, timeframe)\n    volume_column = \"Volume {}\".format(symbol)\n    new_volume_column = \"Volume_{}\".format(symbol)\n    \n    df = pd.read_csv(url + filename, skiprows=1)\n    df = df[::-1]\n    df = df.drop([\"Symbol\"], axis=1)\n    df = df.rename({\"Volume USD\": \"volume\", volume_column: new_volume_column}, axis=1)\n    df = df.set_index(\"Date\")\n    df.columns = [symbol + \":\" + name.lower() for name in df.columns]\n                     \n    return df\n```\n\n## Setup Trading Environment\n\n\n```python\nfrom tensortrade.exchanges import Exchange\nfrom tensortrade.exchanges.services.execution.simulated import execute_order\nfrom tensortrade.data import Stream, DataFeed, Module\nfrom tensortrade.instruments import USD, BTC, ETH, LTC\nfrom tensortrade.wallets import Wallet, Portfolio\nfrom tensortrade.environments import TradingEnvironment\n\ncoinbase_data = pd.concat([\n    fetch(\"Coinbase\", \"BTC\", \"1h\"),\n    fetch(\"Coinbase\", \"ETH\", \"1h\")\n], axis=1)\n\ncoinbase = Exchange(\"coinbase\", service=execute_order)(\n    Stream(\"USD-BTC\", list(coinbase_data['BTC:close'])),\n    Stream(\"USD-ETH\", list(coinbase_data['ETH:close']))\n)\n\ncoinbase_btc = coinbase_data.loc[:, [name.startswith(\"BTC\") for name in coinbase_data.columns]]\n\nwith Module(\"coinbase\") as coinbase_ns:\n    nodes = [Stream(name, list(coinbase_data[name])) for name in coinbase_data.columns]\n\nfeed = DataFeed([coinbase_ns])\n\nportfolio = Portfolio(USD, [\n    Wallet(coinbase, 10000 * USD),\n    Wallet(coinbase, 10 * BTC),\n    Wallet(coinbase, 5 * ETH),\n])\n\nenv = TradingEnvironment(\n    feed=feed,\n    portfolio=portfolio,\n    action_scheme='managed-risk',\n    reward_scheme='risk-adjusted',\n    window_size=20\n)\n```\n\n## Example Data Feed Observation\n\n\n```python\nenv.feed.next()\n```\n\n\n\n\n    {'coinbase:/USD:/total': 10000,\n     'coinbase:/BTC:high': 2513.38,\n     'coinbase:/BTC:/free': 10,\n     'coinbase:/BTC:low': 2495.12,\n     'coinbase:/USD:/free': 10000,\n     'coinbase:/BTC:/locked': 0,\n     'coinbase:/BTC:close': 2509.17,\n     'coinbase:/BTC:volume_btc': 114.6,\n     'coinbase:/BTC:/total': 10,\n     'coinbase:/ETH:close': 275.01,\n     'coinbase:/USD-BTC': 2509.17,\n     'coinbase:/BTC:/worth': 25091.7,\n     'coinbase:/BTC:volume': 287000.32,\n     'coinbase:/ETH:open': 279.98,\n     'coinbase:/USD-ETH': 275.01,\n     'coinbase:/BTC:open': 2505.56,\n     'coinbase:/ETH:high': 279.99,\n     'coinbase:/ETH:low': 272.1,\n     'coinbase:/ETH:/locked': 0,\n     'coinbase:/ETH:/free': 5,\n     'coinbase:/ETH:volume_eth': 2455.28,\n     'coinbase:/ETH:/total': 5,\n     'coinbase:/USD:/locked': 0,\n     'coinbase:/ETH:volume': 679358.87,\n     'coinbase:/ETH:/worth': 1375.05,\n     'net_worth': 36466.75}\n\n\n\n## Setup and Train DQN Agent\n\n\n```python\nfrom tensortrade.agents import DQNAgent\n\nagent = DQNAgent(env)\n\nagent.train(n_steps=200, save_path=\"examples/agents/\")\n```\n\n    ====      EPISODE ID: eb726f14-9b6a-46be-a069-c79b007ff909      ====\n\n\n## Plot Performance\n\n\n```python\n%matplotlib inline\n\nportfolio.performance.plot()\n```\n\n\n```python\nportfolio.performance.net_worth.plot()\n```\n\n## Setup and Train A2C Agent\n\n\n```python\nfrom tensortrade.agents import A2CAgent\n\nagent = A2CAgent(env)\n\nagent.train(n_steps=200, save_path=\"examples/agents/\")\n```\n\n\n```python\nportfolio.performance.plot()\n```\n\n\n```python\nportfolio.performance.net_worth.plot()\n```\n\n## Setup and Train Parallel DQN Agent\n\n\n```python\nfrom tensortrade.agents import ParallelDQNAgent\n\ndef create_env():\n    feed = DataFeed([coinbase_ns])\n\n    portfolio = Portfolio(USD, [\n        Wallet(coinbase, 10000 * USD),\n        Wallet(coinbase, 10 * BTC),\n        Wallet(coinbase, 5 * ETH),\n    ])\n    \n    env = TradingEnvironment(\n        feed=feed,\n        portfolio=portfolio,\n        action_scheme='managed-risk',\n        reward_scheme='risk-adjusted',\n        window_size=20\n    )\n    \n    return env\n\nagent = ParallelDQNAgent(create_env)\n\nagent.train(n_envs=4, n_steps=200, save_path=\"examples/agents/\")\n```\n\n    ====      EPISODE ID (0/2147483647): 0a15a273-c1e9-4f8e-9a50-6ea95795b484      ====\n    ====      EPISODE ID (0/2147483647): d311dbdc-33d7-4704-b394-9468481e8c68      ====\n    ====      EPISODE ID (0/2147483647): 9bca0f01-925f-4e73-86eb-c91ba8f9d20c      ====\n    ====      EPISODE ID (0/2147483647): 3d12e8dd-674e-45c9-9009-59ab235342af      ====\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "b7e3578451740eb64281c477d9a0652a891761d0", "size": 91240, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/train_and_evaluate.ipynb", "max_stars_repo_name": "bwcknr/tensortrade", "max_stars_repo_head_hexsha": "376f5e4cc4ad7df271774088884fbe88f8feb7d8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-05T05:15:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-05T05:15:36.000Z", "max_issues_repo_path": "examples/train_and_evaluate.ipynb", "max_issues_repo_name": "bwcknr/tensortrade", "max_issues_repo_head_hexsha": "376f5e4cc4ad7df271774088884fbe88f8feb7d8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/train_and_evaluate.ipynb", "max_forks_repo_name": "bwcknr/tensortrade", "max_forks_repo_head_hexsha": "376f5e4cc4ad7df271774088884fbe88f8feb7d8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-12-31T02:57:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-21T16:12:24.000Z", "avg_line_length": 211.6937354988, "max_line_length": 38804, "alphanum_fraction": 0.8716133275, "converted": true, "num_tokens": 2239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3174262655876759, "lm_q2_score": 0.0293122296913986, "lm_q1q2_score": 0.009304471606988851}}
{"text": "https://www.cs.cornell.edu/projects/kddcup/datasets.html\n!tar xzvf hep-th-2003.tar.gz!ls -hal 2003/ | wc -l\n# load libraries\n\n\n```python\n# https://github.com/alvinwan/tex2py\n!pip install tex2py\n```\n\n    Collecting tex2py\n    Collecting pytest (from tex2py)\n      Using cached https://files.pythonhosted.org/packages/ca/e1/2f229554e5c273962fae8b286395d5bbcc7bef276d2b40e1bad954993db2/pytest-5.1.3-py3-none-any.whl\n    Collecting coverage==3.7.1 (from tex2py)\n    Collecting TexSoup==0.1.4 (from tex2py)\n    Collecting coveralls==1.1 (from tex2py)\n      Using cached https://files.pythonhosted.org/packages/81/f9/da2ad9334f60e418cb229c58724330be2635b369676d3eec8f61e1f85faa/coveralls-1.1-py2.py3-none-any.whl\n    Collecting pytest-cov==2.5.1 (from tex2py)\n      Using cached https://files.pythonhosted.org/packages/30/7d/7f6a78ae44a1248ee28cc777586c18b28a1df903470e5d34a6e25712b8aa/pytest_cov-2.5.1-py2.py3-none-any.whl\n    Collecting pptree==2.0 (from tex2py)\n    Collecting atomicwrites>=1.0 (from pytest->tex2py)\n      Using cached https://files.pythonhosted.org/packages/52/90/6155aa926f43f2b2a22b01be7241be3bfd1ceaf7d0b3267213e8127d41f4/atomicwrites-1.3.0-py2.py3-none-any.whl\n    Collecting more-itertools>=4.0.0 (from pytest->tex2py)\n      Using cached https://files.pythonhosted.org/packages/45/dc/3241eef99eb45f1def35cf93af35d1cf9ef4c0991792583b8f33ea41b092/more_itertools-7.2.0-py3-none-any.whl\n    Collecting pluggy<1.0,>=0.12 (from pytest->tex2py)\n      Using cached https://files.pythonhosted.org/packages/92/c7/48439f7d5fd6bddb4c04b850bb862b42e3e2b98570040dfaf68aedd8114b/pluggy-0.13.0-py2.py3-none-any.whl\n    Collecting py>=1.5.0 (from pytest->tex2py)\n      Using cached https://files.pythonhosted.org/packages/76/bc/394ad449851729244a97857ee14d7cba61ddb268dce3db538ba2f2ba1f0f/py-1.8.0-py2.py3-none-any.whl\n    Collecting attrs>=17.4.0 (from pytest->tex2py)\n      Using cached https://files.pythonhosted.org/packages/23/96/d828354fa2dbdf216eaa7b7de0db692f12c234f7ef888cc14980ef40d1d2/attrs-19.1.0-py2.py3-none-any.whl\n    Collecting importlib-metadata>=0.12; python_version < \"3.8\" (from pytest->tex2py)\n      Using cached https://files.pythonhosted.org/packages/f6/d2/40b3fa882147719744e6aa50ac39cf7a22a913cbcba86a0371176c425a3b/importlib_metadata-0.23-py2.py3-none-any.whl\n    Requirement already satisfied: packaging in /opt/conda/lib/python3.6/site-packages (from pytest->tex2py) (18.0)\n    Requirement already satisfied: wcwidth in /opt/conda/lib/python3.6/site-packages (from pytest->tex2py) (0.1.7)\n    Requirement already satisfied: requests>=1.0.0 in /opt/conda/lib/python3.6/site-packages (from coveralls==1.1->tex2py) (2.20.0)\n    Collecting docopt>=0.6.1 (from coveralls==1.1->tex2py)\n    Collecting zipp>=0.5 (from importlib-metadata>=0.12; python_version < \"3.8\"->pytest->tex2py)\n      Using cached https://files.pythonhosted.org/packages/74/3d/1ee25a26411ba0401b43c6376d2316a71addcc72ef8690b101b4ea56d76a/zipp-0.6.0-py2.py3-none-any.whl\n    Requirement already satisfied: six in /opt/conda/lib/python3.6/site-packages (from packaging->pytest->tex2py) (1.11.0)\n    Requirement already satisfied: pyparsing>=2.0.2 in /opt/conda/lib/python3.6/site-packages (from packaging->pytest->tex2py) (2.2.2)\n    Requirement already satisfied: urllib3<1.25,>=1.21.1 in /opt/conda/lib/python3.6/site-packages (from requests>=1.0.0->coveralls==1.1->tex2py) (1.23)\n    Requirement already satisfied: idna<2.8,>=2.5 in /opt/conda/lib/python3.6/site-packages (from requests>=1.0.0->coveralls==1.1->tex2py) (2.7)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.6/site-packages (from requests>=1.0.0->coveralls==1.1->tex2py) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.6/site-packages (from requests>=1.0.0->coveralls==1.1->tex2py) (2018.11.29)\n    Installing collected packages: atomicwrites, more-itertools, zipp, importlib-metadata, pluggy, py, attrs, pytest, coverage, docopt, coveralls, pytest-cov, TexSoup, pptree, tex2py\n    Successfully installed TexSoup-0.1.4 atomicwrites-1.3.0 attrs-19.1.0 coverage-3.7.1 coveralls-1.1 docopt-0.6.2 importlib-metadata-0.23 more-itertools-7.2.0 pluggy-0.13.0 pptree-2.0 py-1.8.0 pytest-5.1.3 pytest-cov-2.5.1 tex2py-0.0.5 zipp-0.6.0\n\n\n\n```python\n# https://github.com/alvinwan/TexSoup\n!pip install texsoup\n```\n\n    Requirement already satisfied: texsoup in /opt/conda/lib/python3.6/site-packages (0.1.4)\n    Requirement already satisfied: pytest in /opt/conda/lib/python3.6/site-packages (from texsoup) (5.1.3)\n    Requirement already satisfied: pytest-cov==2.5.1 in /opt/conda/lib/python3.6/site-packages (from texsoup) (2.5.1)\n    Requirement already satisfied: coveralls==1.1 in /opt/conda/lib/python3.6/site-packages (from texsoup) (1.1)\n    Requirement already satisfied: coverage==3.7.1 in /opt/conda/lib/python3.6/site-packages (from texsoup) (3.7.1)\n    Requirement already satisfied: packaging in /opt/conda/lib/python3.6/site-packages (from pytest->texsoup) (18.0)\n    Requirement already satisfied: attrs>=17.4.0 in /opt/conda/lib/python3.6/site-packages (from pytest->texsoup) (19.1.0)\n    Requirement already satisfied: atomicwrites>=1.0 in /opt/conda/lib/python3.6/site-packages (from pytest->texsoup) (1.3.0)\n    Requirement already satisfied: more-itertools>=4.0.0 in /opt/conda/lib/python3.6/site-packages (from pytest->texsoup) (7.2.0)\n    Requirement already satisfied: pluggy<1.0,>=0.12 in /opt/conda/lib/python3.6/site-packages (from pytest->texsoup) (0.13.0)\n    Requirement already satisfied: py>=1.5.0 in /opt/conda/lib/python3.6/site-packages (from pytest->texsoup) (1.8.0)\n    Requirement already satisfied: importlib-metadata>=0.12; python_version < \"3.8\" in /opt/conda/lib/python3.6/site-packages (from pytest->texsoup) (0.23)\n    Requirement already satisfied: wcwidth in /opt/conda/lib/python3.6/site-packages (from pytest->texsoup) (0.1.7)\n    Requirement already satisfied: requests>=1.0.0 in /opt/conda/lib/python3.6/site-packages (from coveralls==1.1->texsoup) (2.20.0)\n    Requirement already satisfied: docopt>=0.6.1 in /opt/conda/lib/python3.6/site-packages (from coveralls==1.1->texsoup) (0.6.2)\n    Requirement already satisfied: pyparsing>=2.0.2 in /opt/conda/lib/python3.6/site-packages (from packaging->pytest->texsoup) (2.2.2)\n    Requirement already satisfied: six in /opt/conda/lib/python3.6/site-packages (from packaging->pytest->texsoup) (1.11.0)\n    Requirement already satisfied: zipp>=0.5 in /opt/conda/lib/python3.6/site-packages (from importlib-metadata>=0.12; python_version < \"3.8\"->pytest->texsoup) (0.6.0)\n    Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.6/site-packages (from requests>=1.0.0->coveralls==1.1->texsoup) (2018.11.29)\n    Requirement already satisfied: idna<2.8,>=2.5 in /opt/conda/lib/python3.6/site-packages (from requests>=1.0.0->coveralls==1.1->texsoup) (2.7)\n    Requirement already satisfied: urllib3<1.25,>=1.21.1 in /opt/conda/lib/python3.6/site-packages (from requests>=1.0.0->coveralls==1.1->texsoup) (1.23)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.6/site-packages (from requests>=1.0.0->coveralls==1.1->texsoup) (3.0.4)\n\n\n\n```python\nimport re\nimport time\nimport glob\nimport matplotlib.pyplot as plt\n```\n\n# load data\n\n\n```python\nlist_of_files = glob.glob('hep-th/2003/*')\n```\n\n\n```python\nlen(list_of_files)\n```\n\n\n\n\n    1019\n\n\n\n# find relevant tags in latex\n\n\n```python\nstart_time=time.time()\nreslts={}\nnumber_of_eq=0\nfor this_file in list_of_files:\n    with open(this_file,'rb') as f:\n        data = f.read()\n    \n    resp = re.findall('\\\\\\\\begin{(?:eqnarray|equation|multiline)}.*?end{(?:eqnarray|equation|multiline)}',str(data),re.DOTALL)\n#    print(this_file)\n    for eq in resp:\n        number_of_eq+=1\n        try:\n            reslts[this_file].append(eq)\n        except KeyError:\n            reslts[this_file]=[]\n            reslts[this_file].append(eq)\n#        print('  ',eq,'\\n')\n\nprint(round(time.time()-start_time,2),'seconds')\n```\n\n    7.63 seconds\n\n\n\n```python\nnumber_of_eq\n```\n\n\n\n\n    29481\n\n\n\n\n```python\nlen(reslts.keys())\n```\n\n\n\n\n    929\n\n\n\n\n```python\nreslts[list(reslts.keys())[0]]\n```\n\n\n\n\n    ['\\\\begin{equation}}\\\\n\\\\\\\\newcommand{\\\\\\\\eeq}{\\\\\\\\end{equation}',\n     '\\\\begin{eqnarray}}\\\\n\\\\\\\\newcommand{\\\\\\\\eeqa}{\\\\\\\\end{eqnarray}']\n\n\n\n\n```python\nreslts[list(reslts.keys())[1]][0]\n```\n\n\n\n\n    '\\\\begin{equation}\\\\\\\\label{planewave}\\\\n\\\\\\\\begin{split}\\\\nds^2 & = 2dx^+dx^--\\\\\\\\m^2\\\\\\\\vec{x}^2\\\\\\\\bigl(dx^+\\\\\\\\bigr)^2+d\\\\\\\\vec{x}^2\\\\\\\\,,\\\\\\\\\\\\\\\\\\\\nF_5 & = 4\\\\\\\\m dx^+\\\\\\\\wedge\\\\\\\\bigl(dx^1\\\\\\\\wedge dx^2\\\\\\\\wedge dx^3\\\\\\\\wedge dx^4+dx^5\\\\\\\\wedge dx^6\\\\\\\\wedge dx^7\\\\\\\\wedge dx^8\\\\\\\\bigr)\\\\\\\\,.\\\\n\\\\\\\\end{split}\\\\n\\\\\\\\end{equation}'\n\n\n\n# visualize results\n\n\n```python\nnumber_of_eq_per_file=[]\nfor k,v in reslts.items():\n    number_of_eq_per_file.append(len(v))\n```\n\n\n```python\n_=plt.hist(number_of_eq_per_file,bins=100)\n_=plt.ylabel('number of expressions')\n_=plt.xlabel('number of documents')\n```\n\n\n```python\n_=plt.hist(number_of_eq_per_file,bins=100)\n_=plt.yscale('log', nonposy='clip')\n_=plt.ylabel('number of expressions')\n_=plt.xlabel('number of documents')\n```\n\n# parse the Latex\n\n\noptions: \n* http://plastex.sourceforge.net/plastex/sect0025.html\n* tex2py\n* texsoup\n\n\n```python\n# https://github.com/alvinwan/tex2py\nfrom tex2py import tex2py\n```\n\n\n```python\nlist_of_files[1]\n```\n\n\n\n\n    'hep-th/2003/0304232'\n\n\n\n\n```python\nwith open(list_of_files[1]) as f: data = f.read()\ntoc = tex2py(data)\n```\ntoc.valid_tags\n\n```python\nfrom TexSoup import TexSoup\nsoup = TexSoup(data)\n```\n\n\n```python\nsoup.equation\n```\n\n\n\n\n    \\begin{equation}\\label{planewave}\n    \\begin{split}\n    ds^2 & = 2dx^+dx^--\\m^2\\vec{x}^2\\bigl(dx^+\\bigr)^2+d\\vec{x}^2\\,,\\\\\n    F_5 & = 4\\m dx^+\\wedge\\bigl(dx^1\\wedge dx^2\\wedge dx^3\\wedge dx^4+dx^5\\wedge dx^6\\wedge dx^7\\wedge dx^8\\bigr)\\,.\n    \\end{split}\n    \\end{equation}\n\n\n\n\n```python\nlst = list(soup.find_all('equation'))\n```\n\n\n```python\nlen(lst) # how many equations are in the document?\n```\n\n\n\n\n    79\n\n\n\n\n```python\nlst[0] # show the first match\n```\n\n\n\n\n    \\begin{equation}\\label{planewave}\n    \\begin{split}\n    ds^2 & = 2dx^+dx^--\\m^2\\vec{x}^2\\bigl(dx^+\\bigr)^2+d\\vec{x}^2\\,,\\\\\n    F_5 & = 4\\m dx^+\\wedge\\bigl(dx^1\\wedge dx^2\\wedge dx^3\\wedge dx^4+dx^5\\wedge dx^6\\wedge dx^7\\wedge dx^8\\bigr)\\,.\n    \\end{split}\n    \\end{equation}\n\n\n\n\n```python\nlst[0][0] # what is the string inside the \"begin{equation}\"?\n```\n\n\n\n\n    '\\\\label{planewave}\\n\\\\begin{split}\\nds^2 & = 2dx^+dx^--\\\\m^2\\\\vec{x}^2\\\\bigl(dx^+\\\\bigr)^2+d\\\\vec{x}^2\\\\,,\\\\\\\\\\nF_5 & = 4\\\\m dx^+\\\\wedge\\\\bigl(dx^1\\\\wedge dx^2\\\\wedge dx^3\\\\wedge dx^4+dx^5\\\\wedge dx^6\\\\wedge dx^7\\\\wedge dx^8\\\\bigr)\\\\,.\\n'\n\n\n\n\n```python\nlst[1]\n```\n\n\n\n\n    \\begin{equation}\n    \\o_n=\\sqrt{n^2+\\bigl(\\m\\a'p^+\\bigr)^2}\\,,\\qquad n\\in\\Nop\\,,\n    \\end{equation}\n\n\n\n\n```python\nlst[1][0]\n```\n\n\n\n\n    \"\\n\\\\o_n=\\\\sqrt{n^2+\\\\bigl(\\\\m\\\\a'p^+\\\\bigr)^2}\\\\,,\\\\qquad n\\\\in\\\\Nop\\\\,,\\n\"\n\n\n\n\n```python\nfor this_eq in soup.find_all('equation'):\n    print(this_eq[0])\n```\n\n    \\label{planewave}\n    \\begin{split}\n    ds^2 & = 2dx^+dx^--\\m^2\\vec{x}^2\\bigl(dx^+\\bigr)^2+d\\vec{x}^2\\,,\\\\\n    F_5 & = 4\\m dx^+\\wedge\\bigl(dx^1\\wedge dx^2\\wedge dx^3\\wedge dx^4+dx^5\\wedge dx^6\\wedge dx^7\\wedge dx^8\\bigr)\\,.\n    \n    \n    \\o_n=\\sqrt{n^2+\\bigl(\\m\\a'p^+\\bigr)^2}\\,,\\qquad n\\in\\Nop\\,,\n    \n    \\label{dict}\n    \\frac{1}{\\m}H = \\D-J\\,,\\qquad \\frac{1}{\\bigl(\\m\\a'p^+\\bigr)^2} = \\frac{g^2_{\\text{YM}}N}{J^2}\\equiv \\l'\\,,\\qquad\n    4\\pi g_{\\text{s}}\\bigl(\\m\\a'p^+\\bigr)^2 = \\frac{J^2}{N}\\equiv g_2\n    \n    \n    N\\to\\infty\\quad\\text{and}\\quad J\\to\\infty\\quad\\text{with}\\quad\\frac{J^2}{N}\\quad\n    \\text{fixed}\\,,\\quad g_{\\text{YM}}\\quad\\text{fixed}\\,,\n    \n    \n    S_{\\mbox{\\scriptsize bos.}(r)}=\\frac{e(\\a_r)}{4\\pi\\a'}\\int\\,d\\t\\int_0^{2\\pi|\\a_r|}\n    \\,d\\s_r\\bigl[\\dot{x}_r^2-x^{\\prime\\,2}_r-\\m^2x_r^2\\bigr]\\,,\n    \n    \n    \\begin{split}\n    x_r^I(\\s_r)& = x_{0(r)}^I+\\sqrt{2}\\sum_{n=1}^{\\infty}\n    \\bigl(x_{n(r)}^I\\cos\\frac{n\\s_r}{|\\a_r|}+x_{-n(r)}^I\\sin\\frac{n\\s_r}{|\\a_r|}\\bigr)\\,,\\\\\n    p_r^I(\\s_r) & =\\frac{1}{2\\pi|\\a_r|}\\bigl[p_{0(r)}^I+\\sqrt{2}\\sum_{n=1}^{\\infty}\n    \\bigl(p_{n(r)}^I\\cos\\frac{n\\s_r}{|\\a_r|}+p_{-n(r)}^I\\sin\\frac{n\\s_r}{|\\a_r|}\\bigr)\\bigr]\\,.\n    \n    \\label{xp}\n    x_{n(r)}^I=i\\sqrt{\\frac{\\a'}{2\\o_{n(r)}}}\\bigl(a_{n(r)}^I-a_{n(r)}^{I\\,\\dag}\\bigr)\\,,\\qquad\n    p_{n(r)}^I=\\sqrt{\\frac{\\o_{n(r)}}{2\\a'}}\\bigl(a_{n(r)}^I+a_{n(r)}^{I\\,\\dag}\\bigr)\\,.\n    \n    =i\\d^{IJ}\\d_{rs}\\d(\\s_r-\\s_s)\\qquad\\lr\\qquad [a_{n(r)}^I,a_{m(s)}^{J\\,\\dag}]=\\d^{IJ}\\d_{nm}\\d_{rs}\\,.\n    \n    \n    S_{\\mbox{\\scriptsize ferm.}(r)}=\\frac{1}{8\\pi}\\int\\,d\\t\\int_0^{2\\pi|\\a_r|}\\,d\\s_r\n    [i(\\bar{\\vt}_r\\dot{\\vt}_r+\\vt_r\\dot{\\bar{\\vt}}_r)\n    -\\vt_r\\vt'_r+\\bar{\\vt}_r\\bar{\\vt}'_r-2\\m\\bar{\\vt}_r\\Pi\\vt_r]\\,,\n    \n    \n    \\begin{split}\n    \\vt^a_r(\\s_r) & =\\vt^a_{0(r)}+\\sqrt{2}\\sum_{n=1}^{\\infty}\n    \\bigl(\\vt^a_{n(r)}\\cos\\frac{n\\s_r}{|\\a_r|}+\\vt^a_{-n(r)}\\sin\\frac{n\\s_r}{|\\a_r|}\\bigr)\\,,\\\\\n    \\l^a_r(\\s_r) & =\\frac{1}{2\\pi|\\a_r|}\\bigl[\\l^a_{0(r)}+\\sqrt{2}\\sum_{n=1}^{\\infty}\n    \\bigl(\\l^a_{n(r)}\\cos\\frac{n\\s_r}{|\\a_r|}+\\l^a_{-n(r)}\\sin\\frac{n\\s_r}{|\\a_r|}\\bigr)\\bigr]\\,.\n    \n    \n    \\{\\vt^a_r(\\s_r),\\l^b_s(\\s_s)\\}=\\d^{ab}\\d_{rs}\\d(\\s_r-\\s_s)\\qquad\\lr\\qquad\\{\\vt^a_{n(r)},\\l^b_{m(s)}\\}=\\d^{ab}\\d_{nm}\\d_{rs}\\,.\n    \n    \n    \\vt_{n(r)}=\\frac{c_{n(r)}}{\\sqrt{|\\a_r|}}\\left[(1+\\r_{n(r)}\\Pi)b_{n(r)}\n    +e(\\a_rn)(1-\\r_{n(r)}\\Pi)b_{-n(r)}^{\\dag}\\right]\\,,\\qquad n\\in\\Zop\\,,\n    \n    \n    \\r_{n(r)}=\\r_{-n(r)}=\\frac{\\o_{n(r)}-|n|}{\\m\\a_r}\\,,\\qquad\n    c_{n(r)}=c_{-n(r)}=\\frac{1}{\\sqrt{1+\\r_{n(r)}^2}}\\,.\n    \n    \n    \\{b^a_{n(r)},b^{b\\,\\dag}_{m(s)}\\}=\\d^{ab}\\d_{nm}\\d_{rs}\\,.\n    \n    \n    \\Pi =\n    \\begin{pmatrix}\n    \\d_{\\a_1}^{\\b_1}\\d_{\\a_2}^{\\b_2} & 0 \\\\ 0 & -\\d^{\\da_1}_{\\db_1}\\d^{\\da_2}_{\\db_2}\n    \n    \n    \\{b_{n(r)\\,\\a_1\\a_2},b^{\\b_1\\b_2\\,\\dag}_{m(s)}\\}=\\d_{\\a_1}^{\\b_1}\\d_{\\a_2}^{\\b_2}\\d_{nm}\\d_{rs}\\,,\\qquad\n    \\{b_{n(r)\\,\\da_1\\da_2},b^{\\db_1\\db_2\\,\\dag}_{m(s)}\\}=\\d_{\\da_1}^{\\db_1}\\d_{\\da_2}^{\\db_2}\\d_{nm}\\d_{rs}\\,.\n    \n    \n    H_{2(r)}=\\frac{1}{\\a_r}\\sum_{n\\in\\Zop}\\o_{n(r)}\\bigl(a_{n(r)}^{I\\,\\dag}a_{n(r)}^I\n    +b^{\\a_1\\a_2\\,\\dag}_{n(r)}b_{n(r)\\,\\a_1\\a_2}+b^{\\da_1\\da_2\\,\\dag}_{n(r)}b_{n(r)\\,\\da_1\\da_2}\\bigr)\\,.\n    \n    \n    a_{n(r)}|v\\ra_r=0\\,,\\qquad b_{n(r)}|v\\ra_r=0\\,,\\quad n\\in\\Nop\\,.\n    \n    \\label{comm}\n    \\begin{split}\n    [H,P^I] &= -i\\m^2J^{+I}\\,,\\qquad [H,Q^+]=-\\m\\Pi Q^+\\,,\\\\\n    \\{Q^-_{\\da},\\bar{Q}^-_{\\db}\\} &=\n    2\\d_{\\dot{a}\\dot{b}}H-i\\m\\bigl(\\g_{ij}\\Pi\\bigr)_{\\dot{a}\\dot{b}}J^{ij}+i\\m\\bigl(\\g_{i'j'}\\Pi\\bigr)_{\\dot{a}\\dot{b}}J^{i'j'}\\,.\n    \n    \\label{q-mode}\n    \\begin{split}\n    Q^-_{(r)} & =\\frac{e(\\a_r)}{\\sqrt{|\\a_r|}}\\g\n    \\Bigl(\\sqrt{\\m}\\left[a_{0(r)}(1+e(\\a_r)\\Pi)+a_{0(r)}^{\\dag}(1-e(\\a_r)\\Pi)\\right]\\l_{0(r)}\\\\\n    &+\\sum_{n\\neq 0}\\sqrt{|n|}\\left[a_{n(r)}P_{n(r)}^{-1}b_{n(r)}^{\\dag}\n    +e(\\a_r)e(n)a_{n(r)}^{\\dag}P_{n(r)}b_{-n(r)}\\right]\\Bigr)\\,,\n    \n    \n    P_{n(r)}\\equiv\\frac{1-\\r_{n(r)}\\Pi}{\\sqrt{1-\\r_{n(r)}^2}}\n    =\\frac{1+\\Pi}{2}U_{|n|(r)}^{1/2}+\\frac{1-\\Pi}{2}U_{|n|(r)}^{-1/2}\\,,\\qquad\n    U_{n(r)}\\equiv\\frac{\\o_{n(r)}-\\m\\a_r}{n}\\,.\n    \n    \\label{hexp}\n    H=H_2+g_{\\text{s}}H_3+\\cdots\\,,\n    \n     = -i\\m^2J^{+I}\\quad\\Longrightarrow\\quad[H_3,P^I]=0\\,,\n    \n    \\label{q+}\n    [H,Q^+]=-\\m\\Pi Q^+\\quad\\Longrightarrow\\quad[H_3,Q^+]=0\\,,\n    \n    \n    |V\\ra\\equiv|E_a\\ra|E_b\\ra\\d\\bigl(\\sum_{r=1}^3\\a_r\\bigr)\\,,\n    \n    \\label{bv}\n    |E_a\\ra = \\exp\\left(\\frac{1}{2}\n    \\sum_{r,s=1}^3\\sum_{m,n\\in\\Zop}a^{I\\,\\dag}_{m(r)}\\bar{N}^{rs}_{mn}a^{I\\,\\dag}_{n(s)}\n    \\right)|v\\ra_{123}\\,,\n    \n    \\label{eb2}\n    |E_b\\ra=\\exp\\left(\n    \\sum_{r,s=1}^3\\sum_{m,n\\ge0}\n    \\bigl(b^{\\a_1\\a_2\\,\\dag}_{-m(r)}b^{\\dag}_{n(s)\\,\\a_1\\a_2}+b^{\\da_1\\da_2\\,\\dag}_{m(r)}b^{\\dag}_{-n(s)\\,\\da_1\\da_2}\\bigr)\n    \\bar{Q}^{rs}_{mn}\\right)|v\\ra_{123}\\,,\n    \n    \n    \\sqrt{2}\\eta\\,Q\\equiv Q^-+i\\bar{Q}^-\\,,\\qquad\\text{and}\\qquad\n    \\sqrt{2}\\bar{\\eta}\\,\\wt{Q}=Q^--i\\bar{Q}^-\n    \n    \n    \\{Q_{\\dot{a}},\\wt{Q}_{\\dot{b}}\\}=0\\,,\\quad\n    \\{Q_{\\dot{a}},Q_{\\dot{b}}\\}=\\{\\wt{Q}_{\\dot{a}},\\wt{Q}_{\\dot{b}}\\}\n    =2\\d_{\\dot{a}\\dot{b}}H-i\\m\\bigl(\\g_{ij}\\Pi\\bigr)_{\\dot{a}\\dot{b}}J^{ij}+i\\m\\bigl(\\g_{i'j'}\\Pi\\bigr)_{\\dot{a}\\dot{b}}J^{i'j'}\\,.\n    \n    \n    K^I \\equiv \\sum_{r=1}^3\\sum_{n\\in\\Zop}K_{n(r)}a_{n(r)}^{I\\,\\dag}\\,,\\qquad\n    \\K^I \\equiv \\sum_{r=1}^3\\sum_{n\\in\\Zop}\\K_{n(r)}a_{n(r)}^{I\\,\\dag}\\,,\n    \n    \n    K_{n(r)} \\equiv (1-4\\m\\a K)^{1/2}\\begin{cases} F_{0(r)}\\,, & n=0 \\\\\n    F_{n(r)}\\,, & n>0 \\\\\n    iU_{n(r)}F_{n(r)}\\,, & n<0\n    \n    \n    \\label{Y}\n    Y^{\\a_1\\a_2} = \\sum_{r=1}^3\\sum_{n\\ge 0}\\bar{G}_{n(r)}b_{n(r)}^{\\dag\\,\\a_1\\a_2}\\,,\\qquad\n    Z^{\\da_1\\da_2} = \\sum_{r=1}^3\\sum_{n\\ge 0}\\bar{G}_{n(r)}b_{-n(r)}^{\\dag\\,\\da_1\\da_2}\\,,\n    \n    \\label{G}\n    \\bar{G}_{(r)} =\n    \\sqrt{-\\frac{\\a'}{\\a}}(1-4\\m\\a K)^{1/2}\\sqrt{|\\a_r|}U_{(r)}^{1/2}C^{-1/2}F_{(r)}\\,,\n    \n    \\label{qy}\n    \\begin{split}\n    \\eta\\sqrt{\\frac{-2\\a}{\\a'}}\\sum_{r=1}^3\\{Q_{(r)},Y+iZ\\} & = i\\g^IK^I\\,,\\\\\n    \\bar{\\eta}\\sqrt{\\frac{-2\\a}{\\a'}}\\sum_{r=1}^3\\{\\wt{Q}_{(r)},Y-iZ\\} & = -i\\g^I\\wt{K}^I\\,.\n    \n    ^I\\equiv\\sum_{r=1}^3\\sum_{n\\in\\Zop}K^*_{n(r)}a_{n(r)}^{I\\,\\dag} = \\K^I,\\quad\n    Y^*\\equiv\\sum_{r=1}^3\\sum_{n\\ge 0}\\bar{G}^*_{n(r)}b_{n(r)}^{\\dag}=Y,\\quad\n    Z^*\\equiv\\sum_{r=1}^3\\sum_{n\\ge 0}\\bar{G}^*_{n(r)}b_{-n(r)}^{\\dag} = Z,\n    \n    \\label{ansatz1}\n    |Q_{3\\,\\b_1\\db_2}\\ra =\n    \\bigl(f^i_{\\b_1\\db_2}(Y,Z)\\K^i+g^{i'}_{\\b_1\\db_2}(Y,Z)\\K^{i'}\\bigr)|V\\ra\\,,\n    \n    \\label{y2}\n    Y^2_{\\a_1\\b_1} \\equiv Y_{\\a_1\\a_2}Y^{\\a_2}_{\\b_1}\\,,\\qquad Y^2_{\\a_2\\b_2} \\equiv Y_{\\a_1\\a_2}Y^{\\a_1}_{\\b_2}\\,,\n    \n    \\label{y3}\n    Y^3_{\\a_1\\b_2} \\equiv Y^2_{\\a_1\\b_1}Y^{\\b_1}_{\\b_2}=-Y^2_{\\b_2\\a_2}Y^{\\a_2}_{\\a_1}\\,,\n    \n    \n    Y^4_{\\a_1\\b_1} \\equiv Y^2_{\\a_1\\g_1}{Y^2}^{\\g_1}_{\\b_1}=-\\frac{1}{2}\\e_{\\a_1\\b_1}Y^4\\,,\\qquad\n    Y^4_{\\a_2\\b_2} \\equiv Y^2_{\\a_2\\g_2}{Y^2}^{\\g_2}_{\\b_2}=\\frac{1}{2}\\e_{\\a_2\\b_2}Y^4\\,,\n    \n    \\label{y4}\n    Y^4 \\equiv Y^2_{\\a_1\\b_1}{Y^2}^{\\a_1\\b_1}=-Y^2_{\\a_2\\b_2}{Y^2}^{\\a_2\\b_2}\\,.\n    \n    \n    \\bar{\\eta}\\sqrt{\\frac{\\a'}{-2\\a}}|Q_{3\\,\\b_1\\db_2}\\ra =\n    \\Bigl(s_{\\dg_1\\db_2}(Z)t_{\\b_1\\g_1}(Y)\\K^{\\dg_1\\g_1}+is_{\\b_1\\g_2}(Y)t^*_{\\db_2\\dg_2}(Z)\\K^{\\dg_2\\g_2}\\Bigr)|V\\ra\\,,\n    \n    \n    -\\eta\\sqrt{\\frac{\\a'}{-2\\a}}|Q_{3\\,\\db_1\\b_2}\\ra =\n    \\Bigl(s^*_{\\g_1\\b_2}(Y)t^*_{\\db_1\\dg_1}(Z)\\K^{\\dg_1\\g_1}+is^*_{\\db_1\\dg_2}(Z)t_{\\b_2\\g_2}(Y)\\K^{\\dg_2\\g_2}\\Bigr)|V\\ra\\,.\n    \n    \n    \\K^{\\dg_1\\g_1} \\equiv \\K^i{\\s^i}^{\\dg_1\\g_1}\\,,\\qquad\n    \\K^{\\dg_2\\g_2} \\equiv \\K^{i'}{\\s^{i'}}^{\\dg_2\\g_2}\\,,\n    \n    \n    s(Y) \\equiv Y+\\frac{i}{3}Y^3\\,,\\qquad t(Y) \\equiv \\e+iY^2-\\frac{1}{6}Y^4\\,.\n    \n    ^{ij} \\equiv \\s^{ij}_{\\a_1\\b_1}{Y^2}^{\\a_1\\b_1}\\,,\\quad\n    {Z^2}^{ij} \\equiv \\s^{ij}_{\\da_1\\db_1}{Z^2}^{\\da_1\\db_1}\\,,\\quad\n    \\bigl(Y^2Z^2\\bigr)^{ij} \\equiv {Y^2}^{k(i}{Z^2}^{j)k}\n    \n    \\label{nij}\n    |n\\ra\\equiv\\a^{I\\,\\dag}_{n(3)}\\a^{J\\,\\dag}_{-n(3)}|v\\ra_3\\,.\n    \n    \\label{de1}\n    \\d E_n^{(2)}\\la n|n\\ra = g_2^2\\sum_{1,2}\n    \\frac{1}{2}\\frac{\\left|\\la n|H_3|1,2\\ra\\right|^2}{E_n^{(0)}-E_{1,2}^{(0)}}\n    -\\frac{g_2^2}{4}\\la n|Q_{3\\,\\b_1\\db_1}Q_3^{\\b_1\\db_1}|n\\ra\\,.\n    \n    \\label{tr}\n    x^+ \\to -x^+\\,,\\qquad x^- \\to - x^-\\,,\\qquad \\m \\to -\\m\\,,\n    \n    \n    \\m \\to -\\m\\,,\\qquad \\Pi \\to -\\Pi\n    \n    \\label{de2}\n    {\\mc N}\\d E_n^{(2)}=-g_2^2\\int_{-1}^0\\frac{d\\b}{\\b(\\b+1)}\n    \\sum_{\\text{modes}}\\left[\n    \\frac{1}{2}\\frac{\\left|\\la n|H_3|1,2\\ra\\right|^2}{E_n^{(0)}-E_{1,2}^{(0)}}\n    -\\frac{1}{4}\\la n|Q_{3\\,\\b_1\\db_1}|1,2\\ra\\la 1,2|Q_3^{\\b_1\\db_1}|n\\ra\\right]\\,.\n    \n    \n    \\begin{split}\n    \\la n|H_3|\\a_{0(r)}^{\\dag\\,k}\\a_{0(s)}^{\\dag\\,l}|v\\ra_{12}& \\sim\n    \\m\\l'\\frac{\\sin^2 n\\pi\\b}{2\\pi^2}\\left(\\d^{rs}+\\frac{\\sqrt{\\a_r\\a_s}}{\\a_3}\\right)S^{ijkl}\\,,\\\\\n    \\la n|H_3|\\a_{k(r)}^{\\dag\\,k}\\a_{-k(r)}^{\\dag\\,l}|v\\ra_{12} & \\sim\n    \\m\\l'\\b(\\b+1)\\frac{\\a_3}{\\a_r}\\frac{\\sin^2 n\\pi\\b}{2\\pi^2}S^{ijkl}\\,,\n    \n    \n    S^{ijkl}\\equiv T^{ijkl}+\\frac{1}{4}\\d^{ij}T^{kl}\\,,\\quad\n    T^{ijkl}=\\d^{ik}\\d^{jl}+\\d^{jk}\\d^{il}-\\frac{1}{2}\\d^{ij}\\d^{kl}\\,,\\quad\n    T^{kl} = -2\\d^{kl}\n    \n    \n    \\frac{\\m g_2^2\\l'}{4\\pi^2}\\frac{15}{64\\pi^2n^2}\\sum_{k,l}S^{ijkl}S^{ijkl}=\n    \\frac{\\m g_2^2\\l'}{4\\pi^2}\\frac{15}{16\\pi^2n^2}\\Bigl[\\frac{1}{2}\\bigl(1+\\frac{1}{2}\\d^{ij}\\bigr)+\\frac{1}{4}\\d^{ij}\\Bigr]\\,.\n    \n    \\label{9-1}\n    \\frac{\\m g_2^2\\l'}{4\\pi^2}\\frac{15}{16\\pi^2n^2}\\,.\n    \n    \n    -\\pi\\a'\\m^2\\la n|K^M\\K^N|E_a\\ra\n    \\sim\\frac{\\m\\sqrt{\\l'}}{2\\pi}\\b(\\b+1)\\sin^2n\\pi\\b\\left(\\d^{MI}\\d^{NJ}+\\d^{NI}\\d^{MJ}\\right)\\,.\n    \n    \n    -{}_{123}\\la v|b_{k(r)\\,\\a_1\\a_2}b_{-k(s)\\,\\da_1\\da_2}Y^{\\g_1\\g_2}Z^{\\dg_1\\dg_2}|E_b\\ra\n    =\\d_{\\a_1}^{\\g_1}\\d_{\\a_2}^{\\g_2}\\d_{\\da_1}^{\\dg_1}\\d_{\\da_2}^{\\dg_2}\n    \\bar{G}_{k(r)}\\bar{G}_{k(s)}\\,.\n    \n    \n    \\frac{\\m g_2^2\\l'}{4\\pi^2}\\frac{3}{8\\pi^2 n^2}\n    -\\frac{\\m g_2^2\\l'}{4n\\pi^3}\\int_{-1}^0 d\\b\\,\\sin^4n\\pi\\b\\cot n\\pi\\b(\\b+1)\n    =\\frac{\\m g_2^2\\l'}{4\\pi^2}\\frac{15}{16\\pi^2 n^2}\\frac{1}{2}\\,,\n    \n    \n    \\eta|Q_{3\\,\\b_1\\db_2}\\ra \\sim\n    -\\sqrt{-\\frac{\\a'}{8\\a_3^3}}\\sqrt{-\\b(\\b+1)}\\bigl(Y_{\\b_1\\g_2}\\K^{\\g_2}_{\\db_1}-iZ_{\\dg_1\\b_2}\\K^{\\dg_1}_{\\b_1}\\bigr)|E_a\\ra|E_b\\ra\\,,\n    \n    \n    \\frac{1}{2}\\frac{\\m g_2^2\\l'}{4\\pi^2}\\left(\\frac{1}{12}+\\frac{35}{32n^2\\pi^2}\\right)\\,,\n    \n    \n    \\frac{\\m g_2^2\\l'}{4\\pi^2}\\left(\\frac{1}{12}+\\frac{5}{32n^2\\pi^2}\\right)\n    \\Bigl[\\frac{1}{2}\\bigl(1+\\frac{1}{2}\\d^{ij}\\bigr)+\\frac{1}{4}\\d^{ij}\\Bigr]\\,,\n    \n    \n    \\d E_n^{(2)}=\\frac{\\m g_2^2\\l'}{4\\pi^2}\\left(\\frac{1}{12}+\\frac{35}{32n^2\\pi^2}\\right)\\,.\n    \n    _v \\longrightarrow ({\\bf 4},{\\bf 1})\\oplus ({\\bf 1},{\\bf 4})\\,,\\qquad\n    {\\bf 8}_s \\longrightarrow ({\\bf 2},{\\bf 2}) \\oplus ({\\bf 2'},{\\bf 2'})\\,,\\qquad\n    {\\bf 8}_c \\longrightarrow ({\\bf 2},{\\bf 2'}) \\oplus ({\\bf 2'},{\\bf 2})\\,,\n    \n    \n    \\s^i_{\\a\\da}=\\bigl(i\\t^1,i\\t^2,i\\t^3,-1\\bigr)_{\\a\\da}\n    \n    \n    \\s^i_{\\a\\da} = \\e_{\\a\\b}\\e_{\\da\\db}{\\s^i}^{\\db\\b}\n    \\equiv \\e_{\\a\\b}{\\s^i}^{\\b}_{\\da} \\equiv \\e_{\\da\\db}{\\s^i}^{\\db}_{\\a}\\,.\n    \n    \n    \\s^i_{\\a\\da}{\\s^j}^{\\da\\b}+\\s^j_{\\a\\da}{\\s^i}^{\\da\\b}\n    =2\\d^{ij}\\d_{\\a}^{\\b}\\,,\\qquad\n    {\\s^i}^{\\da\\a}\\s^j_{\\a\\db}+{\\s^j}^{\\da\\a}\\s^i_{\\a\\db}=\n    2\\d^{ij}\\d^{\\da}_{\\db}\\,.\n    \n    \n    \\Pi_{ab} =\n    \\begin{pmatrix} \\bigl(\\s^1\\s^2\\s^3\\s^4\\bigr)_{\\a_1}^{\\b_1}\\d_{\\a_2}^{\\b_2} & 0 \\\\\n    0 & \\bigl(\\s^1\\s^2\\s^3\\s^4\\bigr)^{\\da_1}_{\\db_1}\\d^{\\da_2}_{\\db_2}\n    \n    \\label{1Y234}\n    \\begin{split}\n    \\sum_r[Q_{(r)\\,\\a_1\\da_2},Y^2_{\\b_1\\g_1}] & =\n    -i\\bigl(\\e_{\\a_1\\b_1}Y_{\\g_1\\g_2}+\\e_{\\a_1\\g_1}Y_{\\b_1\\g_2}\\bigr)K^{\\g_2}_{\\da_2}\\,,\\\\\n    \\sum_r[Q_{(r)\\,\\a_1\\da_2},Y^2_{\\b_2\\g_2}] & =\n    i\\bigl(Y_{\\a_1\\b_2}K_{\\g_2\\da_2}+Y_{\\a_1\\g_2}K_{\\b_2\\da_2}\\bigr)\\,,\\\\\n    \\sum_r\\{Q_{(r)\\,\\a_1\\da_2},Y^3_{\\b_1\\g_2}\\} & =\n    3iY_{\\a_1\\g_2}Y_{\\b_1\\d_2}K^{\\d_2}_{\\da_2}\\,,\\\\\n    \\sum_r[Q_{(r)\\,\\a_1\\da_2},Y^4] & =\n    4iY^3_{\\a_1\\a_2}K^{\\a_2}_{\\da_2}\\,,\n    \n    \\label{2Y234}\n    \\begin{split}\n    \\sum_r[Q_{(r)\\,\\db_1\\b_2},Y^2_{\\a_1\\g_1}] & =\n    -i\\bigl(Y_{\\g_1\\b_2}K_{\\a_1\\db_1}+Y_{\\a_1\\b_2}K_{\\g_1\\db_1}\\bigr)\\,,\\\\\n    \\sum_r[Q_{(r)\\,\\db_1\\b_2},Y^2_{\\a_2\\g_2}] & =\n    -i\\bigl(\\e_{\\a_2\\b_2}Y_{\\g_1\\g_2}+\\e_{\\g_2\\b_2}Y_{\\g_1\\a_2}\\bigr)K^{\\g_1}_{\\db_1}\\,,\\\\\n    \\sum_r\\{Q_{(r)\\,\\db_1\\b_2},Y^3_{\\a_1\\g_2}\\} & =\n    3iY_{\\a_1\\b_2}Y_{\\g_1\\g_2}K^{\\g_1}_{\\db_1}\\,,\\\\\n    \\sum_r[Q_{(r)\\,\\db_1\\b_2},Y^4] & =\n    -4iY^3_{\\a_1\\b_2}K^{\\a_1}_{\\db_1}\\,,\n    \n    \\label{1Z234}\n    \\begin{split}\n    \\sum_r[Q_{(r)\\,\\a_1\\da_2},Z^2_{\\db_1\\dg_1}] & =\n    K_{\\a_1\\db_1}Z_{\\dg_1\\da_2}+K_{\\a_1\\dg_1}Z_{\\db_1\\da_2}\\,,\\\\\n    \\sum_r[Q_{(r)\\,\\a_1\\da_2},Z^2_{\\db_2\\dg_2}] & =\n    -\\bigl(\\e_{\\da_2\\db_2}Z_{\\dg_1\\dg_2}+\\e_{\\da_2\\dg_2}Z_{\\dg_1\\db_2}\\bigr)K_{\\a_1}^{\\dg_1}\\,,\\\\\n    \\sum_r\\{Q_{(r)\\,\\a_1\\da_2},Z^3_{\\db_1\\dg_2}\\} & =\n    -3Z_{\\db_1\\da_2}Z_{\\dg_1\\dg_2}K^{\\dg_1}_{\\a_1}\\,,\\\\\n    \\sum_r[Q_{(r)\\,\\a_1\\da_2},Z^4] & =\n    4Z^3_{\\da_1\\da_2}K^{\\da_1}_{\\a_1}\\,,\n    \n    \\label{2Z234}\n    \\begin{split}\n    \\sum_r[Q_{(r)\\,\\db_1\\b_2},Z^2_{\\da_1\\dg_1}] & =\n    -\\bigl(\\e_{\\db_1\\da_1}Z_{\\dg_1\\dg_2}+\\e_{\\db_1\\dg_1}Z_{\\da_1\\dg_2}\\bigr)K_{\\b_2}^{\\dg_2}\\,,\\\\\n    \\sum_r[Q_{(r)\\,\\db_1\\b_2},Z^2_{\\da_2\\dg_2}] & =\n    K_{\\b_2\\da_2}Z_{\\db_1\\dg_2}+K_{\\b_2\\dg_2}Z_{\\db_1\\da_2}\\,,\\\\\n    \\sum_r\\{Q_{(r)\\,\\db_1\\b_2},Z^3_{\\da_1\\dg_2}\\} & =\n    3Z_{\\db_1\\dg_2}Z_{\\da_1\\dd_2}K^{\\dd_2}_{\\b_2}\\,,\\\\\n    \\sum_r[Q_{(r)\\,\\db_1\\b_2},Z^4] & =\n    4Z^3_{\\db_1\\dg_2}K^{\\dg_2}_{\\b_2}\\,.\n    \n    \n    -4\\frac{\\m\\a}{\\a'}\\e_{\\a_1\\b_1}\\e_{\\da_2\\db_2}\n    \\Bigl(a_{3,0}Y^4+ia_{0,3}Z^4+(a_{3,4}+ia_{4,3})Y^4Z^4\\Bigr)\\,,\\quad\n    \\text{and}\\quad a_{2,1}=ia_{1,2}\\,.\n    \n    \n    2Y_{[\\a_1\\g_2}K^{\\dg_1}_{\\b_1]} = \\e_{\\a_1\\b_1}Y^{\\g_1}_{\\g_2}K^{\\dg_1}_{\\g_1}\\,,\n    \n    \\label{trick}\n    \\begin{pmatrix} b_{n(r)} \\\\ b_{-n(r)} \n    \n    \\begin{split}\n    \\sum_r[Q_{(r)\\,\\a_1\\da_2},K_{\\b_1\\db_1}] & =\n    -4\\frac{\\a}{\\a'}\\e_{\\b_1\\a_1}\\bigl(\\p_{\\t}+\\p_{\\s}\\bigr)Z_{\\db_1\\da_2}\\,,\\\\\n    \\sum_r[Q_{(r)\\,\\da_1\\a_2},K_{\\b_1\\db_1}] & =\n    -4i\\frac{\\a}{\\a'}\\e_{\\db_1\\da_1}\\bigl(\\p_{\\t}+\\p_{\\s}\\bigr)Y_{\\b_1\\a_2}\\,,\n    \n    \n    \\begin{split}\n    \\sum_r[Q_{(r)\\,\\a_1\\da_2},K_{\\b_2\\db_2}] & =\n    -4i\\frac{\\a}{\\a'}\\e_{\\da_2\\db_2}\\bigl(\\p_{\\t}+\\p_{\\s}\\bigr)Y_{\\a_1\\b_2}\\,,\\\\\n    \\sum_r[Q_{(r)\\,\\da_1\\a_2},K_{\\b_2\\db_2}] & =\n    4\\frac{\\a}{\\a'}\\e_{\\a_2\\b_2}\\bigl(\\p_{\\t}+\\p_{\\s}\\bigr)Z_{\\da_1\\db_2}\\,,\n    \n    \\label{dV}\n    \\p_{\\s}|V\\ra = -\\frac{i}{4}\n    \\left[\\frac{\\a'}{\\a}\\bigl(K^IK^I-\\K^I\\K^I\\bigr)-\n    4\\bigl(Y_{\\a_1\\a_2}\\p_{\\t}Y^{\\a_1\\a_2}-Z_{\\da_1\\da_2}\\p_{\\t}Z^{\\da_1\\da_2}\\bigr)\\right]|V\\ra\\,.\n    \n    \n    \\lim_{\\s\\to\\pi\\a_1}Y(\\s)|V\\ra = Y|V\\ra\\,,\\qquad \\lim_{\\s\\to\\pi\\a_1}Z(\\s)|V\\ra = Z|V\\ra\\,.\n    \n    \n    \\lim_{\\s\\to\\pi\\a_1}Y(\\s)|V\\ra = f(\\m)(1-4\\m\\a K)^{-1/2}Y|V\\ra\\,,\n    \n    \n    f(\\m)\\equiv-2\\frac{\\sqrt{-\\a}}{\\a_1}\\lim_{e\\to0}\\e^{1/2}\n    \\sum_{n=1}^{\\infty}(-1)^nn\\cos(n\\e/\\a_1)\\bar{N}^1_n=(1-4\\m\\a K)^{1/2}.\n    \n\n\n\n```python\n\n```\n", "meta": {"hexsha": "40e25cfcbe3895166d3a6c1d4dcee89a10433f84", "size": 55072, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "exploration_of_hep-th-2003.ipynb", "max_stars_repo_name": "carlosal1015/proofofconcept", "max_stars_repo_head_hexsha": "579873aff082e6fa497a387e0d0a5f8e5ec3ecd2", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2015-01-02T19:39:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T06:08:10.000Z", "max_issues_repo_path": "exploration_of_hep-th-2003.ipynb", "max_issues_repo_name": "carlosal1015/proofofconcept", "max_issues_repo_head_hexsha": "579873aff082e6fa497a387e0d0a5f8e5ec3ecd2", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 242, "max_issues_repo_issues_event_min_datetime": "2015-01-02T13:59:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T17:22:21.000Z", "max_forks_repo_path": "exploration_of_hep-th-2003.ipynb", "max_forks_repo_name": "carlosal1015/proofofconcept", "max_forks_repo_head_hexsha": "579873aff082e6fa497a387e0d0a5f8e5ec3ecd2", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2015-02-13T16:00:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-05T17:51:26.000Z", "avg_line_length": 56.3108384458, "max_line_length": 9532, "alphanum_fraction": 0.6312463684, "converted": true, "num_tokens": 12408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18242552380635632, "lm_q2_score": 0.050330631529120415, "lm_q1q2_score": 0.009181591820204504}}
{"text": "```python\nimport theme\ntheme.load_style()\n```\n\n\n\n\n<style>\n@import url('http://fonts.googleapis.com/css?family=Source+Code+Pro');\n@import url('http://fonts.googleapis.com/css?family=Vollkorn');\n@import url('http://fonts.googleapis.com/css?family=Arimo');\n@import url('http://fonts.googleapis.com/css?family=Arvo:400,700,400italic')\n\n#notebook li { /* More space between bullet points */\n    margin-top:0.8em;\n}\n\n/* draw border around running cells */\ndiv.cell.border-box-sizing.code_cell.running {\n    border: 3px solid #111;\n}\n\ndiv.cell.code_cell {\n    margin-top: 1em;\n    margin-left: auto;\n    margin-right: auto;\n    width: 800px;\n    border: 1px solid rgba(200, 200, 200, 0.8);\n    border-radius: 8px; /* rounded borders */\n}\n\ndiv.text_cell_render{\n    font-family: 'Arvo' sans-serif;\n    /* font-family: 'Arimo',verdana,arial,sans-serif; */\n    line-height: 130%;\n    font-size: 115%;\n    margin-left:0%;\n    margin-right:auto;\n}\n\n.text_cell_render h1 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 300;\n    font-style: bold;\n    font-size: 30pt;\n    line-height: 100%;\n    color:#c76c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h2 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 20pt;\n    line-height: 100%;\n    color:#c76c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h3 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 16pt;\n    line-height: 100%;\n    color:#d77c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h4 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 14pt;\n    font-style: italic;\n    line-height: 100%;\n    color:#d77c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h5 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 12pt;\n    color: #1d3b84;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n}\n\n.rendered_html code{\n    background-color: transparent;\n}\n\nul{\n    margin: 2em;\n}\n\nul li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.5em;\n}\n\nul li li{\n    padding-left: 0.2em;\n    margin-bottom: 0.2em;\n    margin-top: 0.2em;\n}\n\nol{\n    margin: 2em;\n}\n\nol li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.5em;\n}\n\nul li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.2em;\n}\n\na:link{\n    font-weight: bold;\n    color:#447adb;\n}\n\na:visited{\n    font-weight: bold;\n    color: #1d3b84;\n}\n\na:hover{\n    font-weight: bold;\n    color: #1d3b84;\n}\n\na:focus{\n    font-weight: bold;\n    color:#447adb;\n}\n\na:active{\n    font-weight: bold;\n    color:#447adb;\n}\n\n.rendered_html :link {\n    text-decoration: underline;\n}\n\n.rendered_html :hover {\n    text-decoration: none;\n}\n\n.rendered_html :visited {\n    text-decoration: none;\n}\n\n.rendered_html :focus {\n    text-decoration: none;\n}\n\n.rendered_html :active {\n    text-decoration: none;\n}\n\n.warning{\n    color: rgb( 240, 20, 20 )\n}\n\nhr {\n    color: #f3f3f3;\n    background-color: #f3f3f3;\n    height: 1px;\n}\n\nblockquote{\n    display:block;\n    background: #fcfcfc;\n    border-left: 5px solid #c76c0c;\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    width:680px;\n    padding: 10px 10px 10px 10px;\n}\n\nblockquote p {\n    margin-bottom: 0;\n    line-height: 125%;\n    font-size: 100%;\n}\n\ntable#mytable,\ntable#mytable td,\ntable#mytable tr\n{\n    border: none !important;\n}\n\ntable#mytable-1,\ntable#mytable-1 td,\ntable#mytable-1 tr\n{\n    border: none !important;\n    align: center;\n    cellspacing: 10;\n}\n\n.msg {\n    width: 90%;\n    margin-left: auto;\n    margin-right: auto;\n    margin-top: 10px;\n    margin-bottom: 10px;\n    padding: 14px 14px 14px 14px;\n    color: #c09853;\n    text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);\n    background-color: #fcf8e3;\n    border: 1px solid #fbeed5;\n    -webkit-border-radius: 4px;\n    -moz-border-radius: 4px;\n    border-radius: 4px;\n}\n\n.msg-heading {\n    color: inherit;\n}\n\n.msg .close {\n    position: relative;\n    top: -2px;\n    right: -21px;\n    line-height: 18px;\n}\n\n.msg-success {\n    color: #468847;\n    background-color: #dff0d8;\n    border-color: #d6e9c6;\n}\n\n.msg-danger,\n.msg-error {\n    color: #b94a48;\n    background-color: #f2dede;\n    border-color: #eed3d7;\n}\n\n.msg-info {\n    color: #3a87ad;\n    background-color: #d9edf7;\n    border-color: #bce8f1;\n}\n\n.boxed {\n    color: #b94a48;\n    background-color: #f2dede;\n    border-color: #eed3d7;\n    margin-left: auto;\n    margin-right: auto;\n    padding: 14px 14px 14px 14px;\n}\n\n.w-300 { width: 300px; }\n.w-400 { width: 400px; }\n.w-500 { width: 500px; }\n\n</style>\n\n\n\n\n\n```python\nimport sympy as sp\nsp.init_printing()\n%pylab inline\n```\n\n    Populating the interactive namespace from numpy and matplotlib\n\n\n# Lesson 16: The Method of Manufactured Solutions\n\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\"></a>\n\nThis lecture by Tim Fuller is licensed under the\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\">Creative Commons Attribution 4.0 International License</a>.  All code examples are also licensed under the [MIT license](http://opensource.org/licenses/MIT).\n\n# Validation and Verification\n\n## Validation Question\nHow do we know if the equations we have been solving are the right equations?\n\n* Compare with data or with more sophisticated models.\n\n## Verification Question\nHow do we know that we are solving the equations right?\n\n* Compare the approximate solution with an exact solution whenever possible.  Otherwise, perform a variety of \"sanity checks\".  One such sanity check is the method of manufactured solutions.\n\n# Method of Manufactured Solutions (MMS)\n\nThe method of manufactured solutions is a straightforward, yet powerful, method to verify that the finite element equations are being solved correctly.  In the MMS, we start with a \"manufactured solution\" $u$ and determine the form of the sourcing functions required to produce the solution by applying the governing equations to it.  The sourcing functions are then applied to the code and solution checked.\n\nFor example, consider the following boundary value problem\n\n$$\n\\frac{d\\sigma}{dx} + b = 0\n$$\n$$u(0) = 0$$\n$$\\sigma(L)=0$$\n\nLet $\\sigma = E\\epsilon$ (linear elasticity) and suppose $u = f(x)$.  Applying the governing equations to $u$ we get\n\n$$\n\\frac{d\\sigma}{dx} + b = E\\frac{d^2f}{dx^2} + b = 0 \n\\quad \\longrightarrow \\quad b = -E\\frac{d^2f}{dx^2}\n$$\n\nEnforcing boundary conditions supplies additional constraints on $f$:\n\n$$f(0) = 0$$\n$$E\\frac{df}{dx}=0$$\n\nOther constraints (as needed) can be imposed on $f$.\n\n## Example\n\nLet $u = u_0 + u_1 x + u_2 x^2 + u_2 x^3$.  The boundary conditions require that\n\n$$u(0) = u_0 = 0$$\n$$\\sigma(L) = E\\frac{du}{dx} = \nE\\frac{d}{dx}\\left(u_0 + u_1 x + u_2 x^2 + u_2 x^3\\right) = 0$$\n\nWe have two equations, but three unknowns.  We choose the third equation by arbitrarily scaling the displacement at L to 1\n\n$$u(L) = u_0 + u_1 L + u_2 L^2 + u_3 L^3 = 1$$\n\nWe solve the preceding equations below using sympy\n\n\n```python\n# Manufactured solution\nuL = 1\nx, L, b, s, E = sp.symbols(\"x L b sigma E\")\nu0, u1, u2 = sp.symbols(\"u0 u1 u2\")\na = u0 + u1 * x ** 2 + u2 * x ** 3\neps = sp.diff(a, x)\nsig = E * eps * (eps + 2.) / (2. * eps + 2.)\ncoeffs = sp.solve([a.subs(x, 0), sig.subs(x, L), a.subs(x, L) - uL], \n                  (u0, u1, u2))\ncoeffs = dict(zip((u0, u1, u2), coeffs[0]))\nua = a.subs(coeffs)\neps = ua.diff(x)\nsig = E * eps\nb = -sig.diff(x)\nb\n```\n\nYuck!  We now use the $b$ previously determined as an input to the simple linear FE program below to verify that we get back the manufactured solution $u$.\n\n\n```python\nROOT3 = sqrt(3.)\ndef wundee(xa, xb, num_elem, E, q):\n    \"\"\"Solves\n \n      ds                            du\n      -- + q = 0, where s = Ee, e = --\n      dx                            dx\n      \n      subject to\n      \n      u(0) = 0, s(L) = 0\n      \n    Parameters\n    ----------\n    xa, xb : real\n        Origin and end of bar\n    num_elem : int\n        Number of elements\n    E : real\n        Young's modulus\n    q : callable\n        Body force per unit area\n\n    Returns\n    -------\n    X, u : array\n        Nodal coordinates and displacements\n\n    \"\"\"\n    # Linear 1D mesh\n    n = num_elem + 1\n    X = linspace(xa, xb, n)\n    connect = array([[i, i+1] for i in range(num_elem)])\n\n    # Global stiffness and force\n    K = zeros((n, n))\n    F = zeros(n)\n\n    # Shape functions and derivatives, Jacobian\n    N = lambda xi: array([1 - xi, 1 + xi]) / 2.\n    dN = lambda xi: array([-1., 1.]) / 2.\n    Jac = lambda xi, xc: dot(dN(xi), xc)\n    x = lambda xi, xc: xc[0] + (xc[1] - xc[0]) / 2. * (1. + xi)\n\n    # assemble global stiffness\n    for (e, nodes) in enumerate(connect):\n        np = len(nodes)\n        xc = X[nodes]\n        ke = zeros((2, 2))\n        fe = zeros(2)\n        for xi in (-1./ROOT3, 1./ROOT3):\n            # Convert shape function derivatives to derivatives\n            # wrt global coords\n            J = Jac(xi, xc)  \n            dNdx = dN(xi) / J\n            ke += E * J * outer(dNdx, dNdx)\n            fe += q(x(xi, xc)) * N(xi) * J\n\n        # add contributions to global matrices\n        for a in range(np):\n            I = nodes[a]\n            F[I] += fe[a]\n            for b in range(np):\n                J = nodes[b]\n                K[I, J] += ke[a, b]\n\n    # Apply boundary conditions\n    K[0,0] = 1e30\n    F[0] = 0.\n    u = linalg.solve(K, F)\n\n    return X, u\n```\n\n\n```python\nxa, xb, n, E_ = 0., 1., 5, 10\nxc = linspace(xa, xb)\nplot(xc, sp.lambdify(x, ua.subs({E: E_, L: xb}))(xc), \n     lw=2, label='Analytic Solution')\n\nq = sp.lambdify(x, b.subs({E: E_, L: xb}))\nxp, u = wundee(xa, xb, n, E_, q)\nplot(xp, u, '-.', lw=2, label='FE Solution')\nlegend(loc='best');\n```\n", "meta": {"hexsha": "371a2dfff4e840ee2f10cab308b3b3190e42f51b", "size": 41011, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lessons/Lesson16_MethodOfManufacturedSolutions.ipynb", "max_stars_repo_name": "jzw0025/fem-with-python", "max_stars_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 148, "max_stars_repo_stars_event_min_datetime": "2015-11-05T16:32:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:42:26.000Z", "max_issues_repo_path": "Lessons/Lesson16_MethodOfManufacturedSolutions.ipynb", "max_issues_repo_name": "pinkieli/fem-with-python", "max_issues_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lessons/Lesson16_MethodOfManufacturedSolutions.ipynb", "max_forks_repo_name": "pinkieli/fem-with-python", "max_forks_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": 74, "max_forks_repo_forks_event_min_datetime": "2016-02-17T13:23:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T07:48:27.000Z", "avg_line_length": 68.9260504202, "max_line_length": 19346, "alphanum_fraction": 0.7332179171, "converted": true, "num_tokens": 3155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08509904732734555, "lm_q2_score": 0.10521054371715848, "lm_q1q2_score": 0.008953317039122227}}
{"text": "```\nimport requests\nfrom bs4 import BeautifulSoup\nfrom pathlib import Path\nimport time\nimport re\nfrom datetime import datetime\nimport os\nfrom nltk.corpus import stopwords\nimport pandas as pd\nimport math\nimport json\nimport string\nimport nltk\nfrom nltk.stem import LancasterStemmer\nfrom nltk.stem import PorterStemmer,WordNetLemmatizer\nfrom nltk.tokenize import word_tokenize\nnltk.download('punkt')\nnltk.download('stopwords')\nnltk.download('wordnet')\n```\n\n    [nltk_data] Downloading package punkt to /root/nltk_data...\n    [nltk_data]   Package punkt is already up-to-date!\n    [nltk_data] Downloading package stopwords to /root/nltk_data...\n    [nltk_data]   Package stopwords is already up-to-date!\n    [nltk_data] Downloading package wordnet to /root/nltk_data...\n    [nltk_data]   Package wordnet is already up-to-date!\n\n\n\n\n\n    True\n\n\n\n\n```\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n\n\n\n```\n!unzip /content/drive/MyDrive/ADM/HM3/pages.zip\n```\n\n# Functions\n\n\n```\ndef handler_date(string_date):\n  if string_date.strip() == 'Not available': return \"\"\n  if len(string_date.strip()) == 4:\n    return datetime.strptime(string_date.lower().strip(),\"%Y\")\n  elif len(string_date.strip()) == 8:\n    return datetime.strptime(string_date.lower().strip(),\"%b %Y\")\n  return datetime.strptime(string_date.lower().strip(),\"%b %d %Y\")\n```\n\n\n```\n# function that returns number of episodes, type anime, releaseDate,endDate\ndef get_information(soup):\n  lista = soup.find_all(\"div\", class_=\"spaceit_pad\")\n  type_anime =\"\"\n  episode = 0\n  releaseDate =\"\"\n  endDate = \"\"\n  for el in lista:\n    if el.find('span'):\n      if el.span.text == \"Type:\":\n        type_anime = el.text.replace(\"\\n\",\"\").replace(\"Type:\",\"\").strip()\n      elif el.span.text == \"Episodes:\":\n        episode = [int(s) for s in el.text.split() if s.isdigit()]\n        if len(episode) > 0:\n          episode = episode[0]\n        else:\n          episode = \"\"\n      elif el.span.text == \"Aired:\":\n        line = re.sub(\"(\\nAired:\\n) | *(\\n)\", '', el.text).split('to')\n        if len(line) > 0:\n          # convert string to datatime\n          releaseDate = handler_date(line[0].replace(\",\",\"\"))\n          if len(line) > 1 and len(line[1].strip()) > 5:\n            endDate = handler_date(line[0].replace(\",\",\"\"))\n  return type_anime,episode,releaseDate,endDate\n```\n\n\n```\n# generic function that return the text that contain in a specific tag and specific class\ndef find_element_by_class(class_name,tag_name):\n  lista = soup.find_all(tag_name, class_=class_name)\n  final_list = []\n  set_control = set()\n  for el in lista:\n      if el.a.text not in set_control:\n        set_control.add(el.a.text)\n        final_list.append(el.a.text)    \n  return final_list\n```\n\n\n```\n# function that return the Related Anime that contain in a specific tag and specific class\ndef find_anime(class_name,tag_name,child_class,bool_href):\n  lista = soup.find(tag_name, class_=class_name).find_all(child_class,href=bool_href)\n  final_list = []\n  set_control = set()\n  for el in lista:\n    if el.text not in set_control:\n          set_control.add(el.text)\n          final_list.append(el.text)\n  return final_list\n```\n\n\n```\n# function that return the staff \ndef find_staff(tag_name, text, tag_sibling, tag_full_name, tag_role):\n  staff_table = soup.find(tag_name, text=text).parent.find_next_sibling()\n  lista = []\n  for el in staff_table.find_all(tag_sibling):\n    full_name = el.find_all(tag_full_name)[1].text\n    role = el.find(tag_role).text\n    lista.append([full_name,role])\n  return lista\n```\n\n\n```\n# function that elaborate a file html and return a line that contains some information about the page\ndef descrip_html(path):\n  with open(path) as myfile:\n      soup = BeautifulSoup(myfile)\n  \n  title_name =soup.find(\"h1\", class_=\"title-name\").strong.text if soup.find(\"h1\", class_=\"title-name\") is not None else \"\"\n  type_anime,episode,releaseDate,endDate = get_information(soup)\n  score = soup.find(\"div\", class_=\"fl-l score\").text if soup.find(\"div\", class_=\"fl-l score\") is not None else \"\"\n  num_members = soup.find(\"span\", class_=\"numbers members\").strong.text.replace(\",\",\"\") if soup.find(\"span\", class_=\"numbers members\") is not None else \"\"\n  userCount =  soup.find(\"span\", itemprop=\"ratingCount\").text if soup.find(\"span\", itemprop=\"ratingCount\") is not None else \"\"\n  ranked = soup.find(\"span\", class_=\"numbers ranked\").strong.text.replace(\"#\",\"\") if soup.find(\"span\", class_=\"numbers ranked\") is not None else \"\"\n  popularity = soup.find(\"span\", class_=\"numbers popularity\").strong.text.replace(\"#\",\"\") if soup.find(\"span\", class_=\"numbers popularity\") is not None else \"\"\n  description = soup.find(\"p\", itemprop=\"description\").get_text(strip= True) if soup.find(\"p\", itemprop=\"description\") is not None else \"\"\n  anime = find_anime(\"anime_detail_related_anime\",\"table\",\"a\",True) if find_anime(\"anime_detail_related_anime\",\"table\",\"a\",True) is not None else \"\"\n  actor = find_element_by_class(\"h3_characters_voice_actors\",\"h3\") if find_element_by_class(\"h3_characters_voice_actors\",\"h3\") is not None else \"\"\n  voice = find_element_by_class(\"va-t ar pl4 pr4\",\"td\") if find_element_by_class(\"va-t ar pl4 pr4\",\"td\") is not None else \"\"\n  staff = find_staff(\"h2\", \"Staff\",\"tr\",\"a\", \"small\") if find_staff(\"h2\", \"Staff\",\"tr\",\"a\", \"small\") is not None else \"\"\n  url = soup.find(\"meta\", property=\"og:url\")[\"content\"]\n  return title_name + \"\\t\"+ type_anime + \"\\t\" + str(episode) + \"\\t\" + str(releaseDate) + \"\\t\" + str(endDate) + \\\n\"\\t\" + str(num_members) + \"\\t\" + str(score) + \"\\t\" + str(userCount) + \"\\t\" + str(ranked) + \"\\t\" \\\n+ str(popularity) + \"\\t\" + description + \"\\t\" + str(anime) + \"\\t \" + str(actor) + \"\\t\" + str(voice) + \"\\t\" + str(staff) + \"\\t\"+url\n```\n\n#REQ 1\n\n## REQ 1.1\n\n\n```\n# get all url from site\nlist_url = []\nfor i in range(0,19150,50):\n  if i % 1000 == 0:\n    print(i)\n  data = requests.get('https://myanimelist.net/topanime.php?limit='+str(i))\n  soup = BeautifulSoup(data.text)\n  lista = soup.find_all(\"h3\", class_=\"anime_ranking_h3\")\n  for element in lista:\n    list_url.append(element.find('a')['href'])\n```\n\n\n```\n# save file\nwith open('links.txt', 'w') as f:\n    for line in list_url:\n        f.write(line)\n        f.write('\\n')\n```\n\n## REQ 1.2\n\n\n```\n# function that return all page html in the ranking\n#there are different numbers, like page number, because html was downloaded in different sessions, because we were blocked by the site \npage_number = 101\ndirectory = \"/content/pages/\"\nwith open(\"/content/links.txt\") as myfile:\n    directory_page_number = \"\"\n    for i,line in enumerate(myfile):\n        if i > 2499:\n          if i % 50==0:\n            time.sleep(5)\n            directory_page_number = directory + str(page_number) + \"/\"\n            Path(directory_page_number).mkdir(parents=True, exist_ok=True)\n            page_number += 1\n          # if the site blocks us, we sleep and try again after 20 seconds \n          while(True):\n            data = requests.get(line).text\n            soup = BeautifulSoup(data).find_all(\"div\", class_=\"error\")\n            if (len(soup) > 0):\n              time.sleep(20)\n            else:\n              break\n          with open(directory_page_number + 'article_'+str(i)+'.html', 'w') as f:\n            f.write(data)\n\n```\n\n\n```\n!unzip /content/drive/MyDrive/ADM/HM3/pages.zip\n```\n\n\n```\n!rm -r -f /content/pages_tsv\n```\n\n\n```\narray = !ls -w1 pages_tsv\nlen(array)\n```\n\n\n\n\n    383\n\n\n\n## REQ 1.3\n\n\n```\n#we process the html file by extracting the data we need and we save it in a tsv file \ndir = \"/content/pages\"\nnew_dir = \"/content/pages_tsv/\"\nfor page_number, page in enumerate(os.listdir(dir),start=1):\n  directory_page_number = new_dir + str(page) + \"/\"\n  Path(directory_page_number).mkdir(parents=True, exist_ok=True)\n  if os.path.isdir(dir+\"/\"+page) and len(os.listdir(dir+\"/\"+page)):\n    html_files = os.listdir(dir+\"/\"+page)\n    for anime in html_files:\n      if anime.endswith('.html'):\n        final_string =  descrip_html(dir +\"/\"+ page+ \"/\" + anime) + \"\\n\"\n        with open(directory_page_number + \"anime_\" + anime[anime.find(\"_\")+1: anime.find(\".\")] +\".tsv\",\"w\") as myfile:\n          myfile.write(final_string)\n```\n\n\n```\n#we read all the directories where the tsv files are contained and merge them into a single tsv file to upload in pandas\nwith open(\"pages_tsv1.tsv\",\"w\") as file:\n  dir = \"/content/pages_tsv/\"\n  for page_number, page in enumerate(os.listdir(dir),start=1):\n    if os.path.isdir(dir+\"/\"+page) and len(os.listdir(dir+\"/\"+page)):\n      html_files = os.listdir(dir+\"/\"+page)\n      for anime in html_files:\n        if anime.endswith('.tsv'):\n          with open(dir+page+\"/\"+anime, \"r\") as tsv_file:\n              file.write(tsv_file.read())\n```\n\n# Clear data\n\n\n```\n# load data in pandas\ncol=[\"animeTitle\",\"animeType\",\"animeNumEpisode\",\"releaseDate\",\"endDate\",\"animeNumMembers\",\\\n           \"animeScore\",\"animeUsers\",\"animeRank\",\"animePopularity\",\"animeDescription\",\\\n           \"animeRelated\",\"animeCharacters\", \"animeVoices\",\"animeStaff\",\"url\"]\ndf = pd.read_csv(\"/content/pages_tsv1.tsv\",sep='\\t', names=col, parse_dates=col[3:5])\n```\n\n\n```\ndf.shape\n```\n\n\n\n\n    (19128, 16)\n\n\n\n\n```\n# As we can, we must to remove all null value\ndf.info()\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 19128 entries, 0 to 19127\n    Data columns (total 16 columns):\n     #   Column            Non-Null Count  Dtype         \n    ---  ------            --------------  -----         \n     0   animeTitle        19126 non-null  object        \n     1   animeType         19126 non-null  object        \n     2   animeNumEpisode   18619 non-null  float64       \n     3   releaseDate       18760 non-null  datetime64[ns]\n     4   endDate           8551 non-null   datetime64[ns]\n     5   animeNumMembers   19126 non-null  float64       \n     6   animeScore        13438 non-null  float64       \n     7   animeUsers        13438 non-null  float64       \n     8   animeRank         17305 non-null  float64       \n     9   animePopularity   19126 non-null  float64       \n     10  animeDescription  19120 non-null  object        \n     11  animeRelated      19128 non-null  object        \n     12  animeCharacters   19128 non-null  object        \n     13  animeVoices       19128 non-null  object        \n     14  animeStaff        19128 non-null  object        \n     15  url               19128 non-null  object        \n    dtypes: datetime64[ns](2), float64(6), object(8)\n    memory usage: 2.3+ MB\n\n\n\n```\n# number of null value\ndf.isnull().sum()\n```\n\n\n\n\n    animeTitle              2\n    animeType               2\n    animeNumEpisode       509\n    releaseDate           368\n    endDate             10577\n    animeNumMembers         2\n    animeScore           5690\n    animeUsers           5690\n    animeRank            1823\n    animePopularity         2\n    animeDescription        8\n    animeRelated            0\n    animeCharacters         0\n    animeVoices             0\n    animeStaff              0\n    url                     0\n    dtype: int64\n\n\n\n\n```\nlen(df.animeUsers.unique())\n```\n\n\n\n\n    7017\n\n\n\n\n```\ndf[\"animeScore\"] = df[\"animeScore\"].where(pd.notnull(df[\"animeScore\"]), None)\ndf[\"animeUsers\"] = df[\"animeUsers\"].where(pd.notnull(df[\"animeUsers\"]), None)\ndf[\"animeRank\"] = df[\"animeRank\"].where(pd.notnull(df[\"animeRank\"]), None)\n```\n\n\n```\ndf[\"animeScore\"].isnull().sum()\n```\n\n\n\n\n    5690\n\n\n\n\n```\n# as we can see, animeTitle, animeNumMembers, animePopularity etc are null, so we need to remove this line\ndf[df.animeNumMembers.isnull()]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>animeTitle</th>\n      <th>animeType</th>\n      <th>animeNumEpisode</th>\n      <th>releaseDate</th>\n      <th>endDate</th>\n      <th>animeNumMembers</th>\n      <th>animeScore</th>\n      <th>animeUsers</th>\n      <th>animeRank</th>\n      <th>animePopularity</th>\n      <th>animeDescription</th>\n      <th>animeRelated</th>\n      <th>animeCharacters</th>\n      <th>animeVoices</th>\n      <th>animeStaff</th>\n      <th>url</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>3749</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaT</td>\n      <td>NaT</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>['Haha wo Tazunete Sanzenri', 'Marco: Haha wo ...</td>\n      <td>[]</td>\n      <td>[]</td>\n      <td>[['De Amicis, Edmondo', 'Original Creator']]</td>\n      <td>https://myanimelist.net/anime/10079/Hoshizora_...</td>\n    </tr>\n    <tr>\n      <th>17127</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaT</td>\n      <td>NaT</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>['Haha wo Tazunete Sanzenri', 'Marco: Haha wo ...</td>\n      <td>[]</td>\n      <td>[]</td>\n      <td>[['De Amicis, Edmondo', 'Original Creator']]</td>\n      <td>https://myanimelist.net/anime/4379/Inmu__Ikeni...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\n# number duplicated\ndf[df.duplicated()].shape\n```\n\n\n\n\n    (2008, 16)\n\n\n\n\n```\n# drop all line duplicated\ndf.drop_duplicates(inplace=True)\n```\n\n\n```\n# as we can see, we eliminated all duplicated line\ndf[df.duplicated()]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>animeTitle</th>\n      <th>animeType</th>\n      <th>animeNumEpisode</th>\n      <th>releaseDate</th>\n      <th>endDate</th>\n      <th>animeNumMembers</th>\n      <th>animeScore</th>\n      <th>animeUsers</th>\n      <th>animeRank</th>\n      <th>animePopularity</th>\n      <th>animeDescription</th>\n      <th>animeRelated</th>\n      <th>animeCharacters</th>\n      <th>animeVoices</th>\n      <th>animeStaff</th>\n      <th>url</th>\n    </tr>\n  </thead>\n  <tbody>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\n#we see the number of null value for each columns\ndf.isnull().sum()\n```\n\n\n\n\n    animeTitle              2\n    animeType               2\n    animeNumEpisode       509\n    releaseDate           368\n    endDate             10577\n    animeNumMembers         2\n    animeScore           5690\n    animeUsers           5690\n    animeRank            1823\n    animePopularity         2\n    animeDescription        8\n    animeRelated            0\n    animeCharacters         0\n    animeVoices             0\n    animeStaff              0\n    url                     0\n    dtype: int64\n\n\n\n\n```\ndf['animeNumEpisode'].fillna(-1,inplace=True)\ndf['endDate'].fillna(-1,inplace=True)\ndf['releaseDate'].fillna(-1,inplace=True)\n```\n\n\n```\n# we check the only two line null of description column\ndf[df.animeDescription.isnull()]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>animeTitle</th>\n      <th>animeType</th>\n      <th>animeNumEpisode</th>\n      <th>releaseDate</th>\n      <th>endDate</th>\n      <th>animeNumMembers</th>\n      <th>animeScore</th>\n      <th>animeUsers</th>\n      <th>animeRank</th>\n      <th>animePopularity</th>\n      <th>animeDescription</th>\n      <th>animeRelated</th>\n      <th>animeCharacters</th>\n      <th>animeVoices</th>\n      <th>animeStaff</th>\n      <th>url</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>3749</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaT</td>\n      <td>NaT</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>['Haha wo Tazunete Sanzenri', 'Marco: Haha wo ...</td>\n      <td>[]</td>\n      <td>[]</td>\n      <td>[['De Amicis, Edmondo', 'Original Creator']]</td>\n      <td>https://myanimelist.net/anime/10079/Hoshizora_...</td>\n    </tr>\n    <tr>\n      <th>7705</th>\n      <td>Yuru Camp\u25b3 Movie</td>\n      <td>Movie</td>\n      <td>1.0</td>\n      <td>2022-01-01</td>\n      <td>NaT</td>\n      <td>33071.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>3163.0</td>\n      <td>NaN</td>\n      <td>['Haha wo Tazunete Sanzenri', 'Marco: Haha wo ...</td>\n      <td>[]</td>\n      <td>[]</td>\n      <td>[['De Amicis, Edmondo', 'Original Creator']]</td>\n      <td>https://myanimelist.net/anime/38475/Yuru_Camp\u25b3...</td>\n    </tr>\n    <tr>\n      <th>7717</th>\n      <td>Argonavis from BanG Dream! Movie</td>\n      <td>Movie</td>\n      <td>1.0</td>\n      <td>2022-01-01</td>\n      <td>NaT</td>\n      <td>1105.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>10933.0</td>\n      <td>NaN</td>\n      <td>['Haha wo Tazunete Sanzenri', 'Marco: Haha wo ...</td>\n      <td>[]</td>\n      <td>[]</td>\n      <td>[['De Amicis, Edmondo', 'Original Creator']]</td>\n      <td>https://myanimelist.net/anime/45731/Argonavis_...</td>\n    </tr>\n    <tr>\n      <th>9215</th>\n      <td>Kaeru no Pickles: Kimochi no Iro</td>\n      <td>TV</td>\n      <td>12.0</td>\n      <td>2020-10-04</td>\n      <td>2020-10-04</td>\n      <td>777.0</td>\n      <td>5.54</td>\n      <td>117</td>\n      <td>10253</td>\n      <td>11805.0</td>\n      <td>NaN</td>\n      <td>['Haha wo Tazunete Sanzenri', 'Marco: Haha wo ...</td>\n      <td>[]</td>\n      <td>[]</td>\n      <td>[['De Amicis, Edmondo', 'Original Creator']]</td>\n      <td>https://myanimelist.net/anime/42717/Kaeru_no_P...</td>\n    </tr>\n    <tr>\n      <th>11876</th>\n      <td>Mayi He Da Xiang</td>\n      <td>Movie</td>\n      <td>1.0</td>\n      <td>1987-01-01</td>\n      <td>NaT</td>\n      <td>15.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>17242</td>\n      <td>18926.0</td>\n      <td>NaN</td>\n      <td>['Haha wo Tazunete Sanzenri', 'Marco: Haha wo ...</td>\n      <td>[]</td>\n      <td>[]</td>\n      <td>[['De Amicis, Edmondo', 'Original Creator']]</td>\n      <td>https://myanimelist.net/anime/43616/Mayi_He_Da...</td>\n    </tr>\n    <tr>\n      <th>17127</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>0.0</td>\n      <td>NaT</td>\n      <td>NaT</td>\n      <td>NaN</td>\n      <td>None</td>\n      <td>None</td>\n      <td>None</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>['Haha wo Tazunete Sanzenri', 'Marco: Haha wo ...</td>\n      <td>[]</td>\n      <td>[]</td>\n      <td>[['De Amicis, Edmondo', 'Original Creator']]</td>\n      <td>https://myanimelist.net/anime/4379/Inmu__Ikeni...</td>\n    </tr>\n    <tr>\n      <th>17589</th>\n      <td>Kuma no Gakkou: Patissier Jackie to Ohisama no...</td>\n      <td>Movie</td>\n      <td>1.0</td>\n      <td>2017-08-25</td>\n      <td>NaT</td>\n      <td>223.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>16938</td>\n      <td>15665.0</td>\n      <td>NaN</td>\n      <td>['Haha wo Tazunete Sanzenri', 'Marco: Haha wo ...</td>\n      <td>[]</td>\n      <td>[]</td>\n      <td>[['De Amicis, Edmondo', 'Original Creator']]</td>\n      <td>https://myanimelist.net/anime/34755/Kuma_no_Ga...</td>\n    </tr>\n    <tr>\n      <th>18722</th>\n      <td>Yukai na Animal Bus</td>\n      <td>TV</td>\n      <td>12.0</td>\n      <td>2017-01-08</td>\n      <td>2017-01-08</td>\n      <td>240.0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>14533</td>\n      <td>15442.0</td>\n      <td>NaN</td>\n      <td>['Haha wo Tazunete Sanzenri', 'Marco: Haha wo ...</td>\n      <td>[]</td>\n      <td>[]</td>\n      <td>[['De Amicis, Edmondo', 'Original Creator']]</td>\n      <td>https://myanimelist.net/anime/34794/Yukai_na_A...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\n# we drop the null column in animeDescription\ndf.dropna(subset=['animeDescription'], inplace=True)\n```\n\n\n```\n# check null\ndf[df.animeDescription.isnull()].head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>animeTitle</th>\n      <th>animeType</th>\n      <th>animeNumEpisode</th>\n      <th>releaseDate</th>\n      <th>endDate</th>\n      <th>animeNumMembers</th>\n      <th>animeScore</th>\n      <th>animeUsers</th>\n      <th>animeRank</th>\n      <th>animePopularity</th>\n      <th>animeDescription</th>\n      <th>animeRelated</th>\n      <th>animeCharacters</th>\n      <th>animeVoices</th>\n      <th>animeStaff</th>\n      <th>url</th>\n    </tr>\n  </thead>\n  <tbody>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\n# we drop the null column in endDate\ndf.dropna(subset=['endDate'], inplace=True)\n```\n\n\n```\n# as we can see, we just need animeScore, animeUsers,animeRank to fix \ndf.isnull().sum()\n```\n\n\n\n\n    animeTitle             0\n    animeType              0\n    animeNumEpisode        0\n    releaseDate            0\n    endDate                0\n    animeNumMembers        0\n    animeScore          5683\n    animeUsers          5683\n    animeRank           1819\n    animePopularity        0\n    animeDescription       0\n    animeRelated           0\n    animeCharacters        0\n    animeVoices            0\n    animeStaff             0\n    url                    0\n    dtype: int64\n\n\n\n\n```\n#check if there are negative scores\ndf[df.animeScore <= 0]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>animeTitle</th>\n      <th>animeType</th>\n      <th>animeNumEpisode</th>\n      <th>releaseDate</th>\n      <th>endDate</th>\n      <th>animeNumMembers</th>\n      <th>animeScore</th>\n      <th>animeUsers</th>\n      <th>animeRank</th>\n      <th>animePopularity</th>\n      <th>animeDescription</th>\n      <th>animeRelated</th>\n      <th>animeCharacters</th>\n      <th>animeVoices</th>\n      <th>animeStaff</th>\n      <th>url</th>\n    </tr>\n  </thead>\n  <tbody>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\n##check if there are negative animeUsers\ndf[df.animeUsers<= 0]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>animeTitle</th>\n      <th>animeType</th>\n      <th>animeNumEpisode</th>\n      <th>releaseDate</th>\n      <th>endDate</th>\n      <th>animeNumMembers</th>\n      <th>animeScore</th>\n      <th>animeUsers</th>\n      <th>animeRank</th>\n      <th>animePopularity</th>\n      <th>animeDescription</th>\n      <th>animeRelated</th>\n      <th>animeCharacters</th>\n      <th>animeVoices</th>\n      <th>animeStaff</th>\n      <th>url</th>\n    </tr>\n  </thead>\n  <tbody>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\n#check if there are negative animeRank\ndf[df.animeRank<= 0]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>animeTitle</th>\n      <th>animeType</th>\n      <th>animeNumEpisode</th>\n      <th>releaseDate</th>\n      <th>endDate</th>\n      <th>animeNumMembers</th>\n      <th>animeScore</th>\n      <th>animeUsers</th>\n      <th>animeRank</th>\n      <th>animePopularity</th>\n      <th>animeDescription</th>\n      <th>animeRelated</th>\n      <th>animeCharacters</th>\n      <th>animeVoices</th>\n      <th>animeStaff</th>\n      <th>url</th>\n    </tr>\n  </thead>\n  <tbody>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\n#we replace -1 in place of null, because we believe that the number of rows is large to eliminate \ndf.fillna(value=-1, inplace=True)\n```\n\n\n```\n# as we can see, we fix all column\ndf.isnull().sum()\n```\n\n\n\n\n    animeTitle          0\n    animeType           0\n    animeNumEpisode     0\n    releaseDate         0\n    endDate             0\n    animeNumMembers     0\n    animeScore          0\n    animeUsers          0\n    animeRank           0\n    animePopularity     0\n    animeDescription    0\n    animeRelated        0\n    animeCharacters     0\n    animeVoices         0\n    animeStaff          0\n    url                 0\n    dtype: int64\n\n\n\n\n```\n# reset index\ndf.reset_index(drop=True, inplace=True)\n```\n\n\n```\ndf.info()\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 19120 entries, 0 to 19119\n    Data columns (total 16 columns):\n     #   Column            Non-Null Count  Dtype  \n    ---  ------            --------------  -----  \n     0   animeTitle        19120 non-null  object \n     1   animeType         19120 non-null  object \n     2   animeNumEpisode   19120 non-null  float64\n     3   releaseDate       19120 non-null  object \n     4   endDate           19120 non-null  object \n     5   animeNumMembers   19120 non-null  float64\n     6   animeScore        19120 non-null  float64\n     7   animeUsers        19120 non-null  float64\n     8   animeRank         19120 non-null  float64\n     9   animePopularity   19120 non-null  float64\n     10  animeDescription  19120 non-null  object \n     11  animeRelated      19120 non-null  object \n     12  animeCharacters   19120 non-null  object \n     13  animeVoices       19120 non-null  object \n     14  animeStaff        19120 non-null  object \n     15  url               19120 non-null  object \n    dtypes: float64(6), object(10)\n    memory usage: 2.3+ MB\n\n\n# Delete Stopwords & Stem & punctuation\n\n\n```\n# function to delete stopwords, punctuation adn stem\ndef filter_sentence(description):\n  stop_words = set(stopwords.words('english')) # set of stopwords\n  nl = WordNetLemmatizer()\n  description = description.translate(str.maketrans('', '', string.punctuation)) # delete punctuation\n  word_tokens = word_tokenize(description) # return list of word, very similar to split\n  filtered_sentence = [nl.lemmatize(w).lower() for w in word_tokens if not w.lower() in stop_words] # delete stopwords\n  filtered_description = \" \".join(filtered_sentence)\n  return filtered_description\n```\n\n\n```\ndf[\"animeDescription\"] = df[\"animeDescription\"].apply(filter_sentence) #apply the function \n```\n\n\n```\ndf['animeDescription'].head()\n```\n\n\n\n\n    0    story follows racoonlike tanuki creature named...\n    1    synopsis information added title help improve ...\n    2    animated promotional video bundled release ido...\n    3    synopsis information added title help improve ...\n    4         fire safety anime directed tsutomu shibayama\n    Name: animeDescription, dtype: object\n\n\n\n#REQ 2\n\n## REQ 2.1\n\n\n```\n## return all words contians in the specified column \ndef retrieve_word_column(column):\n    huge_list = []\n    for i in range(len(df)):\n        huge_list.extend(word_tokenize(df[column][i]))\n    all_words = set(huge_list)\n    return all_words\n```\n\n\n```\n# create 2 dictionary: the first one contains word to index, and the second one \ndef retrieve_word_index(all_words):\n  word_to_idx = dict()\n  idx_to_word = dict()\n  for idx, value in enumerate(all_words):\n    word_to_idx[value] = idx\n    idx_to_word[idx] = value\n  return word_to_idx, idx_to_word\n```\n\n\n```\n# function to add index in dictionary\n# if word(index) not in dictionary added it with the corresponded document, else add document in word\ndef index_to_doc(index,dict_index,document):\n  if index not in dict_index:\n    dict_index[index] = [document]\n  else:\n    dict_index[index].append(document)\n  return dict_index\n```\n\n\n```\n# create dictionary which contain word to all documents which contain this word\ndef invert_index(column, word_to_idx):\n    idx_to_documents = dict()\n    for i,document in enumerate(df[column]):\n      word_tokens = word_tokenize(document)\n      word_tokens = set(word_tokens)\n      for word in word_tokens:\n        index = word_to_idx[word]\n        idx_to_documents = index_to_doc(index,idx_to_documents,i)\n    return idx_to_documents\n```\n\n\n```\n# return the documents that contians the query \ndef match_query(df, query, column, word_to_idx, idx_to_documents):\n  documents = []\n  for word in query.split():\n    if word in word_to_idx:\n      documents.append(idx_to_documents[word_to_idx[word.strip().lower()]])\n    else:\n      return set() # if word not present in dictionary that contians all words, exit beacause the query given in input must match all words \n  document = set.intersection(*map(set, documents))\n  return df[[\"animeTitle\",\"animeDescription\",\"url\"]].loc[list(document)]\n```\n\n\n```\ncolumn = \"animeDescription\"\nall_words = retrieve_word_column(column)\nword_to_idx,idx_to_word =  retrieve_word_index(all_words)\nidx_to_documents = invert_index(column, word_to_idx)\nmatch_query(df,\"saiyan race\",\"animeDescription\",word_to_idx, idx_to_documents).head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>animeTitle</th>\n      <th>animeDescription</th>\n      <th>url</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>11611</th>\n      <td>Dragon Ball Super: Broly</td>\n      <td>fortyone year ago planet vegeta home infamous ...</td>\n      <td>https://myanimelist.net/anime/36946/Dragon_Bal...</td>\n    </tr>\n    <tr>\n      <th>445</th>\n      <td>Dragon Ball Z Special 1: Tatta Hitori no Saish...</td>\n      <td>bardock son gokus father lowranking saiyan sol...</td>\n      <td>https://myanimelist.net/anime/986/Dragon_Ball_...</td>\n    </tr>\n    <tr>\n      <th>13031</th>\n      <td>Dragon Ball Z</td>\n      <td>five year winning world martial arts tournamen...</td>\n      <td>https://myanimelist.net/anime/813/Dragon_Ball_Z</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\n# create 3 file Json which contain information\nwith open('word_to_idx.json', 'w') as fp:\n    json.dump(word_to_idx, fp)\n\nwith open('idx_to_documents.json', 'w') as fp:\n    json.dump(idx_to_documents, fp)\n\nwith open('idx_to_word.json', 'w') as fp:\n    json.dump(idx_to_word, fp)   \n```\n\n## REQ 2.2\n\n\n```\n#returns the updated dictionary with the value given in input \ndef index_to_doc_tfIdf(index ,dict_index, document, score):\n  if index not in dict_index:\n    dict_index[index] = [(document,score)]\n  else:\n    dict_index[index].append((document,score))\n  return dict_index\n```\n\n\n```\n#returns the updated dictionary with the value given in input \ndef doc_to_index_tfIdf(dict_tfIdf, document, score):\n  if document not in dict_tfIdf:\n    dict_tfIdf[document] = [score]\n  else:\n    dict_tfIdf[document].append(score)\n  return dict_tfIdf\n```\n\n\n```\ndef get_number_occurrences(tokens):\n    result = dict()\n    for word in tokens:\n      result[word] = result.get(word, 0) + 1 # if not in dictionary set 0, +1 otherwise\n    return result\n```\n\n\n```\n# function to calculate TF_IDF\ndef retrieve_TF_IDF_document(doc, word_to_idx, idx_to_documents):\n  idx_doc_tfIdf = dict()\n  idf_dict = dict()\n  doc_tfIdf = dict()\n  N = df.shape[0]\n\n  for i, description in enumerate(doc):\n    word_tokens = word_tokenize(description) # list of word\n    num_occurences = get_number_occurrences(word_tokens) #dictionary that contains the number of occurancy for each word\n\n    for word in num_occurences:\n      index = word_to_idx[word.strip().lower()]\n      word_occurance = len(idx_to_documents[index])\n\n      # this block is useful to create a dictionary that contains for each word, the correspond idf\n      if word in idf_dict:\n        idf = idf_dict[word]\n      else:\n        idf = math.log(N / word_occurance) + 1\n        idf_dict[word] = idf\n      \n      # calculate the tf\n      tf = num_occurences[word] / len(word_tokens)\n      score = tf * idf\n\n      idx_doc_tfIdf = index_to_doc_tfIdf(index, idx_doc_tfIdf, i, score)\n      doc_tfIdf = doc_to_index_tfIdf(doc_tfIdf,i,score)\n  return idx_doc_tfIdf, idf_dict, doc_tfIdf\n```\n\n\n```\nidx_doc_tfIdf, idf_dict, doc_index_tf_idf = retrieve_TF_IDF_document(df['animeDescription'], word_to_idx, idx_to_documents)\n```\n\n1. Calculate TFIDF of Query.\n2. Retrieve the intersected documents.\n3. Loop through each document and calculate the following.\n\n\n\n\n```\n# calculate the cosine similarity and return two valued, the first one a sorted list that contains the index of top document\n# the second one the correspond dictionary, where the keys are the documents and the attribute the correspond similarity\nimport numpy as np\ndef cosine_similarity(query, column, df, word_to_idx, idx_to_documents, idx_doc_tfIdf, idf_dict, doc_index_tf_idf):\n  query_terms = word_tokenize(query)\n  results = dict()\n  q = []\n  match = match_query(df, query, column, word_to_idx, idx_to_documents)\n\n  if len(match) == 0: return dict(),[]\n  for query_term in query_terms:\n    index = word_to_idx[query_term]\n    postings_list = idx_doc_tfIdf[index]\n    query_term_tfidf = compute_tfidf_query(query, query_term, idf_dict)\n    q.append(query_term_tfidf)\n    for doc in list(match.index):\n      for doc_tf_idf, tfidf in postings_list:\n        if doc == doc_tf_idf:\n          results[doc] = results.get(doc, 0) + query_term_tfidf * tfidf\n  for doc in results:\n    results[doc] = results[doc] / (np.linalg.norm(doc_index_tf_idf[doc]) * np.linalg.norm(q))\n  return results, list(sorted(results.keys(), key=lambda x: results[x], reverse=True))\n```\n\n\n```\n# compute the tfidf for the query\ndef compute_tfidf_query(query, term, idf_dict):\n  query_terms = word_tokenize(query)\n  words_occ = get_number_occurrences(query_terms)\n  tf = words_occ[term] / len(query_terms)\n  if term not in idf_dict:\n    idf = 0\n  else:\n    idf = idf_dict[term]\n  return tf * idf\n```\n\n\n```\n# calculate the cosine similarity\ndef retrieve_cosine_similarity(query, column_name, df):\n  query = filter_sentence(query)\n  all_words = retrieve_word_column(column_name)\n  word_to_idx, idx_to_word =  retrieve_word_index(all_words)\n  idx_to_documents = invert_index(column_name, word_to_idx)\n  idx_doc_tfIdf, idf_dict, doc_index_tf_idf = retrieve_TF_IDF_document(df[column_name], word_to_idx, idx_to_documents)\n  result = cosine_similarity(query, column_name, df, word_to_idx, idx_to_documents, idx_doc_tfIdf, idf_dict, doc_index_tf_idf)\n  return result\n```\n\n\n```\nquery = 'saiyan race'\nresult_query_description = retrieve_cosine_similarity(query, \"animeDescription\", df)\ncosine_result = pd.concat([df.loc[result_query_description[1]],pd.Series(sorted(result_query_description[0].values(),reverse=True),\\\n                                                               index=result_query_description[1], dtype=\"float32\").rename('descriptionSimilarity')], axis=1)\ncosine_result[['animeTitle', 'animeNumMembers', 'animeScore', 'animeUsers', 'animeRank', 'animePopularity','descriptionSimilarity']]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>animeTitle</th>\n      <th>animeNumMembers</th>\n      <th>animeScore</th>\n      <th>animeUsers</th>\n      <th>animeRank</th>\n      <th>animePopularity</th>\n      <th>descriptionSimilarity</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>445</th>\n      <td>Dragon Ball Z Special 1: Tatta Hitori no Saish...</td>\n      <td>87614.0</td>\n      <td>7.55</td>\n      <td>56578.0</td>\n      <td>1468.0</td>\n      <td>1786.0</td>\n      <td>0.302161</td>\n    </tr>\n    <tr>\n      <th>11611</th>\n      <td>Dragon Ball Super: Broly</td>\n      <td>278607.0</td>\n      <td>8.12</td>\n      <td>188367.0</td>\n      <td>402.0</td>\n      <td>631.0</td>\n      <td>0.186803</td>\n    </tr>\n    <tr>\n      <th>13031</th>\n      <td>Dragon Ball Z</td>\n      <td>1033068.0</td>\n      <td>8.15</td>\n      <td>697557.0</td>\n      <td>366.0</td>\n      <td>95.0</td>\n      <td>0.135501</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\ndf['animeDescription'].shape\n```\n\n\n\n\n    (19120,)\n\n\n\n#REQ 3\n\n\n```\ndf['animeTitleLower'] =  df[\"animeTitle\"].apply(filter_sentence)\n```\n\n\n```\nlist_columns = ['animeTitle', 'animeType', 'animeNumEpisode', 'releaseDate', 'endDate', 'animeNumMembers', 'animeScore', 'animeUsers', 'animeRank', 'animePopularity', 'animeDescription', \\\n                'animeRelated', 'animeCharacters', 'animeVoices', 'animeStaff', 'url','animeTitleLower']\n```\n\n\n```\ndef find_match_req3(query, list_column, df):\n  list_column.extend([\"descriptionSimilarity\",\"titleSimilarity\"])\n  column_normalize_bool = {\"descriptionSimilarity\":False, \"titleSimilarity\": False, \"animeScore\": False, \"animeRank\":True, \"animePopularity\": True, \"animeNumMembers\":False}\n  column_weight = {\"descriptionSimilarity\": 0.2, \"titleSimilarity\": 0.2, \"animeScore\":0.2 ,\"animeRank\":0.2, \"animePopularity\": 0.05, \"animeNumMembers\":0.05}\n  calculate_weight = recalculate_weight(column_weight, list_column,6)\n  print(calculate_weight)\n  # cosine similarity for title\n  result_query_title = retrieve_cosine_similarity(query, \"animeTitleLower\", df) \n\n  # cosine similarity for description\n  result_query_description = retrieve_cosine_similarity(query, \"animeDescription\", df) \n  \n  #we take the corresponding lines from the data frame\n  cosine_result_1 = pd.concat([df.loc[result_query_title[1]],pd.Series(sorted(result_query_title[0].values(),reverse=True),\\\n                                                               index=result_query_title[1], dtype=\"float32\").rename('titleSimilarity')], axis=1)\n  \n  #we take the corresponding lines from the data frame\n  cosine_result_2 = pd.concat([df.loc[result_query_description[1]],pd.Series(sorted(result_query_description[0].values(),reverse=True),\\\n                                                               index=result_query_description[1], dtype=\"float32\").rename('descriptionSimilarity')], axis=1)\n  \n  # join the two dataframe (list_columns is present in the previous cell)\n  cosine_result = pd.merge(cosine_result_1, cosine_result_2,  how='outer', on=list_columns)\n\n  # fill the null value with zero\n  cosine_result = cosine_result.fillna(0)\n\n  #when we go to match, it is likely that one of the two is not present, so we will not create the table with zero as default value \n  if \"titleSimilarity\" not in cosine_result.columns: cosine_result[\"titleSimilarity\"] = 0\n  if \"descriptionSimilarity\" not in cosine_result.columns: cosine_result[\"descriptionSimilarity\"] = 0\n\n  # column which contains the new similarity\n  cosine_result['newSimilarity'] = 0\n  for column in list_column:\n    small_important = column_normalize_bool[column] #True or False\n    value = normalize_column(cosine_result,column, calculate_weight[column],small_important) # calculate the weight of the column \n    cosine_result['newSimilarity'] += value #added value in the newSimilarity\n  \n  return  cosine_result.sort_values(by='newSimilarity',ascending=False)\n  \n```\n\n\n```\n#recalculate the weight based on the user's choice \ndef recalculate_weight(diz_orig_weight, list_columns, n):\n  if n == len(diz_orig_weight): return diz_orig_weight\n  sum = 0\n  diz_new_weight = dict()\n  for column in list_columns:\n    sum += diz_orig_weight[column]\n  for column in list_columns:\n    diz_new_weight[column] = diz_orig_weight[column] / sum\n  return diz_new_weight\n```\n\n\n```\n# function useful to normalize the value\n#small_important is a boolean, True it means that the smaller the value, the more important that value is, so we have to do `1 - value` to normalize \ndef normalize_column(cosine_result,column_name, weight,small_important):\n  max = cosine_result[column_name].max()\n  if max == 0: return 0\n  #print(column_name, (1 - cosine_result[cosine_result.animeTitle == 'Dragon Ball'][column_name] / max * weight).iloc[0])\n  if small_important: return (1- cosine_result[column_name] / max) * weight\n  return (cosine_result[column_name] / max) * weight\n```\n\n## Explain algorithm\nTo calculate the similarity, we don't use just the description, but we add some other factors, each one with its own weight. We use the `titleSimilarity`, `animeScore`, `animeRank`, `animePopularity` and `animeNumMembers`.\n\nWe believe that the `titleSimilarity` is the most important factor, so it has the biggest weight.\n\nThe users can choose the columns used to calculate the similarity, the only two that are mandatory are `titleSimilarity` and `descriptionSimilarity`, instead the other four factors can be included or not in the computation of the new similarity.\nWhen the users don`t choose all the columns, the weights are automatically updated with a proportion.\n\nFor example, we can have the following:\n$$0.3:0.7=x:1$$\nWhere 0.3 is the weight of that column that we want to update and 0.7 is the sum of the weights of all the columns chosen.\n\nGiven the new weights and the list of columns $C$ chosen by the user, we are going to compute the new similarity, using the following formula:\n\n$$\\text{new_similarity} = \\sum_c \\frac{v_c}{max_c} \\cdot{w_c} \\quad \\forall c \\in C$$\n\nwhere $v_c$ is the cosine similarity when $c$ is the `animeTitle` or `animeDescription` column, while it is the value of the column itself for all the other columns. Instead, $max_c$ is the maximum value between all the values of the column and $w_c$ is the weights associated to the column $c$.\n\n## TEST 1\n\nNow, we will show an example of the previous similarity. If we use the query `naruto` and request the new similarity to be computed also with the values in the `animeRank` and `animeScore` columns, we will do the following steps.\n\nFirst of all, the weights have assigned a default values to each of them:\n*   descriptionSimilarity $\\rightarrow$ 0.2\n*   titleSimilarity $\\rightarrow$ 0.2\n*   animeScore $\\rightarrow$ 0.2\n*   animeRank $\\rightarrow$ 0.2\n*   animePopularity $\\rightarrow$ 0.05\n*   animeNumMembers $\\rightarrow$ 0.05\n\nSo, as we said, initially we update the weights just for the columns selected by the user, in this case we have:\n*   descriptionSimilarity $\\rightarrow$ 0.25\n*   titleSimilarity $\\rightarrow$ 0.25\n*   animeRank $\\rightarrow$ 0.25\n*   animeScore $\\rightarrow$ 0.25\n\nIn the first cell below, we can find the ranking obtained with the similarity computed as before, while in the second cell we can see the new ranking obtained with the custom similarity.\n\nAs we can see, the first element in the first ranking doesn't really match  what we were looking for. While if we see the second ranking, given by our algorithm, we can see that all the results obtained have Naruto in the title\nsince we considered also the title, rank and score, instead of using just the description like in the first ranking.\n\n\n\n```\nquery = 'naruto'\nresult_query_description = retrieve_cosine_similarity(query, \"animeDescription\", df)\ncosine_result = pd.concat([df.loc[result_query_description[1]],pd.Series(sorted(result_query_description[0].values(),reverse=True),\\\n                                                               index=result_query_description[1], dtype=\"float32\").rename('descriptionSimilarity')], axis=1)\ncosine_result[['animeTitle', 'animeNumMembers', 'animeScore', 'animeUsers', 'animeRank', 'animePopularity','descriptionSimilarity']].head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>animeTitle</th>\n      <th>animeNumMembers</th>\n      <th>animeScore</th>\n      <th>animeUsers</th>\n      <th>animeRank</th>\n      <th>animePopularity</th>\n      <th>descriptionSimilarity</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>4437</th>\n      <td>Juliet</td>\n      <td>1059.0</td>\n      <td>4.73</td>\n      <td>394.0</td>\n      <td>11724.0</td>\n      <td>11012.0</td>\n      <td>0.463412</td>\n    </tr>\n    <tr>\n      <th>15692</th>\n      <td>Boruto: Naruto the Movie - Naruto ga Hokage ni...</td>\n      <td>90761.0</td>\n      <td>7.37</td>\n      <td>50673.0</td>\n      <td>2093.0</td>\n      <td>1759.0</td>\n      <td>0.408632</td>\n    </tr>\n    <tr>\n      <th>7299</th>\n      <td>Naruto: Shippuuden</td>\n      <td>1929365.0</td>\n      <td>8.22</td>\n      <td>1125164.0</td>\n      <td>299.0</td>\n      <td>16.0</td>\n      <td>0.385227</td>\n    </tr>\n    <tr>\n      <th>15721</th>\n      <td>Naruto: Shippuuden - Shippuu! \"Konoha Gakuen\" Den</td>\n      <td>58260.0</td>\n      <td>7.15</td>\n      <td>28567.0</td>\n      <td>3103.0</td>\n      <td>2290.0</td>\n      <td>0.376075</td>\n    </tr>\n    <tr>\n      <th>14150</th>\n      <td>Naruto: Shippuuden Movie 2 - Kizuna</td>\n      <td>219713.0</td>\n      <td>7.28</td>\n      <td>127336.0</td>\n      <td>2506.0</td>\n      <td>807.0</td>\n      <td>0.371825</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\nquery = 'naruto'\nfind = find_match_req3(query, ['animeRank','animeScore'], df)\nfind[['animeTitle','animeNumMembers', 'animeScore', 'animeUsers', 'animeRank', 'animePopularity',\"titleSimilarity\",\"descriptionSimilarity\",'newSimilarity']].head()\n```\n\n    {'animeRank': 0.25, 'animeScore': 0.25, 'descriptionSimilarity': 0.25, 'titleSimilarity': 0.25}\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>animeTitle</th>\n      <th>animeNumMembers</th>\n      <th>animeScore</th>\n      <th>animeUsers</th>\n      <th>animeRank</th>\n      <th>animePopularity</th>\n      <th>titleSimilarity</th>\n      <th>descriptionSimilarity</th>\n      <th>newSimilarity</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Naruto</td>\n      <td>2292958.0</td>\n      <td>7.95</td>\n      <td>1512406.0</td>\n      <td>609.0</td>\n      <td>8.0</td>\n      <td>1.000000</td>\n      <td>0.333702</td>\n      <td>0.909617</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Naruto: Shippuuden</td>\n      <td>1929365.0</td>\n      <td>8.22</td>\n      <td>1125164.0</td>\n      <td>299.0</td>\n      <td>16.0</td>\n      <td>0.661635</td>\n      <td>0.385227</td>\n      <td>0.867242</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Boruto: Naruto the Movie - Naruto ga Hokage ni...</td>\n      <td>90761.0</td>\n      <td>7.37</td>\n      <td>50673.0</td>\n      <td>2093.0</td>\n      <td>1759.0</td>\n      <td>0.609035</td>\n      <td>0.408632</td>\n      <td>0.804941</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>Naruto: Shippuuden Movie 6 - Road to Ninja</td>\n      <td>274002.0</td>\n      <td>7.67</td>\n      <td>166060.0</td>\n      <td>1124.0</td>\n      <td>633.0</td>\n      <td>0.420373</td>\n      <td>0.346186</td>\n      <td>0.752616</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>Naruto: Shippuuden Movie 2 - Kizuna</td>\n      <td>219713.0</td>\n      <td>7.28</td>\n      <td>127336.0</td>\n      <td>2506.0</td>\n      <td>807.0</td>\n      <td>0.496647</td>\n      <td>0.371825</td>\n      <td>0.745980</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## TEST 2\n\nWe did another test with a different query `goku`, and we inserted all columns (`animeNumMembers`, `animeScore`, `animeRank`, `animePopularity`). So, the weights remained the same one as defined by default.\n\nAs we can see, in the first cell, we have that the best match has a negative value for the score, while our algorithm, since it uses the score value to compute the similarity, it will not rank that anime so high. In fact, we don't have it in the top-5 at all.\n\n\n```\nquery = 'goku'\nresult_query_description = retrieve_cosine_similarity(query, \"animeDescription\", df)\ncosine_result = pd.concat([df.loc[result_query_description[1]],pd.Series(sorted(result_query_description[0].values(),reverse=True),\\\n                                                               index=result_query_description[1], dtype=\"float32\").rename('descriptionSimilarity')], axis=1)\ncosine_result[['animeTitle','animeNumMembers', 'animeScore', 'animeUsers', 'animeRank', 'animePopularity','descriptionSimilarity']].head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>animeTitle</th>\n      <th>animeNumMembers</th>\n      <th>animeScore</th>\n      <th>animeUsers</th>\n      <th>animeRank</th>\n      <th>animePopularity</th>\n      <th>descriptionSimilarity</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1915</th>\n      <td>Son O-gong gwa Byeoldeul-ui Jeonjaeng</td>\n      <td>263.0</td>\n      <td>-1.00</td>\n      <td>-1.0</td>\n      <td>13448.0</td>\n      <td>15053.0</td>\n      <td>0.621845</td>\n    </tr>\n    <tr>\n      <th>4116</th>\n      <td>Dragon Ball Movie 4: Saikyou e no Michi</td>\n      <td>51628.0</td>\n      <td>7.13</td>\n      <td>27582.0</td>\n      <td>3225.0</td>\n      <td>2465.0</td>\n      <td>0.604225</td>\n    </tr>\n    <tr>\n      <th>3252</th>\n      <td>Dragon Ball Z: Summer Vacation Special</td>\n      <td>11351.0</td>\n      <td>6.59</td>\n      <td>4477.0</td>\n      <td>5666.0</td>\n      <td>5058.0</td>\n      <td>0.503414</td>\n    </tr>\n    <tr>\n      <th>5030</th>\n      <td>Dragon Ball Z Movie 07: Kyokugen Battle!! Sand...</td>\n      <td>103961.0</td>\n      <td>6.85</td>\n      <td>64806.0</td>\n      <td>4410.0</td>\n      <td>1572.0</td>\n      <td>0.462226</td>\n    </tr>\n    <tr>\n      <th>7730</th>\n      <td>Dragon Ball Z Movie 07: Kyokugen Battle!! Sand...</td>\n      <td>103961.0</td>\n      <td>6.85</td>\n      <td>64806.0</td>\n      <td>4409.0</td>\n      <td>1572.0</td>\n      <td>0.462226</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```\nquery = 'goku'\nfind = find_match_req3(query, ['animeNumMembers', 'animeScore', 'animeRank', 'animePopularity'], df)\nfind[['animeTitle','animeNumMembers', 'animeScore', 'animeUsers', 'animeRank', 'animePopularity',\"titleSimilarity\",\"descriptionSimilarity\",'newSimilarity']].head()\n```\n\n    {'descriptionSimilarity': 0.2, 'titleSimilarity': 0.2, 'animeScore': 0.2, 'animeRank': 0.2, 'animePopularity': 0.05, 'animeNumMembers': 0.05}\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>animeTitle</th>\n      <th>animeNumMembers</th>\n      <th>animeScore</th>\n      <th>animeUsers</th>\n      <th>animeRank</th>\n      <th>animePopularity</th>\n      <th>titleSimilarity</th>\n      <th>descriptionSimilarity</th>\n      <th>newSimilarity</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Goku Sayonara Zetsubou Sensei</td>\n      <td>59619.0</td>\n      <td>7.84</td>\n      <td>28392.0</td>\n      <td>779.0</td>\n      <td>2265.0</td>\n      <td>0.607027</td>\n      <td>0.000000</td>\n      <td>0.627471</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Dragon Ball Movie 4: Saikyou e no Michi</td>\n      <td>51628.0</td>\n      <td>7.13</td>\n      <td>27582.0</td>\n      <td>3225.0</td>\n      <td>2465.0</td>\n      <td>0.000000</td>\n      <td>0.604225</td>\n      <td>0.566872</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Dragon Ball Kai: Mirai ni Heiwa wo! Goku no Ta...</td>\n      <td>41082.0</td>\n      <td>7.52</td>\n      <td>23051.0</td>\n      <td>1558.0</td>\n      <td>2766.0</td>\n      <td>0.395872</td>\n      <td>0.000000</td>\n      <td>0.536077</td>\n    </tr>\n    <tr>\n      <th>32</th>\n      <td>Kill la Kill</td>\n      <td>1462057.0</td>\n      <td>8.06</td>\n      <td>777422.0</td>\n      <td>478.0</td>\n      <td>47.0</td>\n      <td>0.000000</td>\n      <td>0.084141</td>\n      <td>0.519797</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Dragon Ball Z Movie 07: Kyokugen Battle!! Sand...</td>\n      <td>103961.0</td>\n      <td>6.85</td>\n      <td>64806.0</td>\n      <td>4409.0</td>\n      <td>1572.0</td>\n      <td>0.000000</td>\n      <td>0.462226</td>\n      <td>0.501401</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n# REQ 4\n\nIn this requirement we have performed a sentimental analysis using the vader model. The vader model is very simple, it takes a string as input and is able to understand if the content of the string is positive or negative. It is essentially based on keywords like hate, sad for negative comments, or love for positive comments. \nUsing the polarity_scores function, it returns a dictionary containing 4 values: \n- negative\n- neutral\n- positive\n- compound\n\nthe sum between negative + neutral + positive must be 1, and each of those indicate how much the comment is positive, neutral or negative. The compound, on the other hand, is the normalized variable that we are going to use.\n\nFor this analysis we can't delete the stopwords, because the set of stopwords contains some words like `no`, `not` etc, and this words are very important to understand the sentiment of comment.\n\nWhen I loaded the HTML file, I only uploaded the first 4 reviews because to get the first 5 I had to make another request to the site that was in another url, so unfortunately the analysis will be carried out on 4 comments. \n\n\n\n\n\n\n```\ncol=[\"Reviews\", \"url\"]\nreviews_df = pd.read_csv(\"/content/drive/MyDrive/ADM/HM3/reviews_tsv.tsv\",sep='\\t', names=col)\n```\n\n\n```\nimport ast\nreviews_df.Reviews = reviews_df.Reviews.apply(ast.literal_eval)\n```\n\n\n```\nreviews_df.info()\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 19128 entries, 0 to 19127\n    Data columns (total 2 columns):\n     #   Column   Non-Null Count  Dtype \n    ---  ------   --------------  ----- \n     0   Reviews  19128 non-null  object\n     1   url      19128 non-null  object\n    dtypes: object(2)\n    memory usage: 299.0+ KB\n\n\n\n```\nreviews_df.Reviews\n```\n\n\n\n\n    0                                                       []\n    1                                                       []\n    2                                                       []\n    3                                                       []\n    4                                                       []\n                                   ...                        \n    19123    [~Multilingual review, English & Espa\u00f1ol: The ...\n    19124    [Haikyuu: To the Top, or the 4th installment t...\n    19125    [Ping Pong The Animation is an exceptional sho...\n    19126    [*This review contains very minor spoilers*  D...\n    19127    [Going back to One Punch Man, I really thought...\n    Name: Reviews, Length: 19128, dtype: object\n\n\n\n\n```\nreviews_df[reviews_df.Reviews.str.len() == 0]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Reviews</th>\n      <th>url</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>[]</td>\n      <td>https://myanimelist.net/anime/11673/Hal_no_Fue</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>[]</td>\n      <td>https://myanimelist.net/anime/45687/Hailuo_Wan</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>[]</td>\n      <td>https://myanimelist.net/anime/50066/Hajimari_w...</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>[]</td>\n      <td>https://myanimelist.net/anime/49899/Hajimari_n...</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>[]</td>\n      <td>https://myanimelist.net/anime/39161/Habatake_P...</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>19056</th>\n      <td>[]</td>\n      <td>https://myanimelist.net/anime/36566/Crayon_Shi...</td>\n    </tr>\n    <tr>\n      <th>19064</th>\n      <td>[]</td>\n      <td>https://myanimelist.net/anime/40291/Lost_One_n...</td>\n    </tr>\n    <tr>\n      <th>19068</th>\n      <td>[]</td>\n      <td>https://myanimelist.net/anime/10947/Koukaku_Ki...</td>\n    </tr>\n    <tr>\n      <th>19075</th>\n      <td>[]</td>\n      <td>https://myanimelist.net/anime/34178/Inazuma_El...</td>\n    </tr>\n    <tr>\n      <th>19077</th>\n      <td>[]</td>\n      <td>https://myanimelist.net/anime/18053/Koi_to_Sen...</td>\n    </tr>\n  </tbody>\n</table>\n<p>8711 rows \u00d7 2 columns</p>\n</div>\n\n\n\n\n```\nreviews_df[['review1','review2',\"review3\",\"review4\"]] = pd.DataFrame(reviews_df.Reviews.tolist(), index= reviews_df.index)\n```\n\n\n```\nimport nltk\nnltk.download('vader_lexicon')\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\n\nsid = SentimentIntensityAnalyzer()\n```\n\n    [nltk_data] Downloading package vader_lexicon to /root/nltk_data...\n    [nltk_data]   Package vader_lexicon is already up-to-date!\n\n\n\n```\nreviews_df['review1'].head()\n```\n\n\n\n\n    0    None\n    1    None\n    2    None\n    3    None\n    4    None\n    Name: review1, dtype: object\n\n\n\n\n```\nreviews_df.fillna(0,inplace=True)\n```\n\n\n```\ncols = ['review1', 'review2', 'review3', 'review4']\nfor col in cols:\n  reviews_df[col] = reviews_df[col].apply(lambda review: (sid.polarity_scores(review)['compound']) if review != 0 else review)\n```\n\n\n```\nreviews_df[reviews_df.review1 == 0]['review1']\n```\n\n\n\n\n    0        0.0\n    1        0.0\n    2        0.0\n    3        0.0\n    4        0.0\n            ... \n    19056    0.0\n    19064    0.0\n    19068    0.0\n    19075    0.0\n    19077    0.0\n    Name: review1, Length: 8772, dtype: float64\n\n\n\n\n```\nreviews_df['result'] = (reviews_df['review1'] + reviews_df['review2'] + reviews_df['review3'] + reviews_df['review4']) / 4\n```\n\n\n```\ndf = df.drop_duplicates(subset='url', keep=\"last\")\n```\n\n\n```\nreviews_df = reviews_df.drop_duplicates(subset='url', keep=\"last\")\n```\n\n\n```\ndf_temp = pd.merge(df, reviews_df,  how='inner', on=\"url\")\n```\n\n## REQ 4.1\n\n\n```\ndf_temp.groupby(by='animeType')['result'].mean().sort_values(ascending=False)\n```\n\n\n\n\n    animeType\n    TV         0.245996\n    Special    0.146842\n    OVA        0.134859\n    Movie      0.128069\n    ONA        0.091577\n    Music      0.030172\n    Unknown    0.000000\n    Name: result, dtype: float64\n\n\n\nAs we can see, the best animeType is TV\n\n##REQ 4.2\n\n\n```\ndf_temp.plot(kind=\"scatter\", figsize=(10,5), y ='animeNumEpisode',x='result')\n```\n\nAs we can see in the plot, more the number of episodes increases, more likely the comments will be neutral. \n\n## REQ 4.3\n\n\n```\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nplt.figure(figsize=(8, 6))\nsns.heatmap(df_temp[['animeScore','result']].corr(method='pearson'), annot=True)\nplt.show()\n```\n\nAs we can see, from the matrix of correlation, between `animeScore` and `result` there is slight positive correlation. So if one grows, also the other in part grows.\n\n#REQ 5 THEORY\n\n\n$L$ is the list of appointments given in input, where each element correspond to the number of minutes of the appointment.\n\n$T$ is the new list, where in the last element we will find the sum of the maximum number of minutes that the personal trainer can do.\n\n$i$ represents the $i$-th appointment in the list.\n\nThe idea is that when we fill the array with the sum of the appointments, the first one that we put in is given by the fact that it is the first that matches. Moreover, when we arrive at the second appointment, we choose the maximum between the first and the second appointment because we can't have two consecutive appointment. \n\nFrom the third we change methodology, because now we can take more than one appointment, so we will do: on $T[i]$ (in this case $i=3$) we will put the maximum between the previous($T[i-1]$) and the sum of $T[i] + T[i-2]$ (in this case we will put the maximum between the second appointment and the sum between the first and the third one). Continuing like this we will find in the last element the maximum number of minutes that a personal trainer could perform.\n\n\nBelow the cell with the pseudocode, and then the cell with the function `find_max` that return the list $T$.\n\nBelow we also show, how from the vector $T$, we can extrapolate the appointments that we have chosen, that is the optimal solution.\n\n\\begin{align}\n        \\text{T}(i) = \\left\\{\n        \\begin{array}{cl}\n        l[0]& i = 0 \\\\\n        max(l[i], l[i-1]) & i = 1 \\\\\n        max(l[i-1],l[i-2] + l[i]) & otherwise\n        \\end{array}\n        \\right.\n    \\end{align} \n\n\n```\nlista=[30,40,25,50,30,20]\ndef find_max(lista):\n    if len(lista) == 1: # i == 0\n        return lista[0]\n    elif len(lista) == 2: # i == 1\n        max(lista[1],lista[0])\n    result = [x for x in lista]\n    for i in range(2,len(lista)): # otherwise\n        result[i] = max(result[i-1],result[i-2] + result[i])\n    return result\nprint(find_max(lista))\n```\n\n    [30, 40, 55, 90, 90, 110]\n\n\nNow that we have the vector of the maximum sum of minutes for a personal trainer, we will go to extrapolate the appointments chosen. Here the variabile that we need:\n- $c$, last element from the list of the appointments, so the sum of all the optimal appointments;\n- $i$, the index that we use on the while to scroll backwards the list $T$, and it will be initialized as the index of the last element.\n\nWe start doing a backwards scroll from the list of the appointments $T$ to understand what we chosen.\nThe idea is based on the fact that if the last element is bigger than the penultimate, it means that the last appointment has been chosen, so we can add it to our list. Furthermore, we subtract from $c$ the number of minutes of the appointment chosen (we need this variable to understand if we choose the first element on the list of appointments or not) then we decrease of 2 positions our index $i$ because we know that the penultimate appointment wasn't chosen.\nConsequentially, we arrive at the third last appointment and we repeat the same process to the end of the list.\nIf we are at the first element and $c > 0$, it means that we had chosen also the first element so we add it to the list of the appointments chosen.\n\n\n```\ndef print_choises(lista_orginal, list_sum_appointment):\n    result = []\n    i = len(lista_orginal) -1\n    c = list_sum_appointment[-1] # the sum of all appointment choises\n    while(c > 0 and i > -1):\n        if list_sum_appointment[i] > list_sum_appointment[i-1]:\n            result.append(lista_orginal[i]) \n            c -= lista_orginal[i]\n            i-=2\n        elif i == 0:\n            result.append(lista_orginal[i])\n            c -= lista_orginal[0]\n    result.reverse()\n    return result\n\nprint_choises(lista, find_max(lista))\n```\n\n\n\n\n    [40, 50, 20]\n\n\n", "meta": {"hexsha": "6583592ffe939da6f65fd1d56b993e333b19c7b1", "size": 191527, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "HW3_final.ipynb", "max_stars_repo_name": "MinaMakar97/ADM-HW3", "max_stars_repo_head_hexsha": "351aedf84c945542994e08cf2ebf2823b1c640d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW3_final.ipynb", "max_issues_repo_name": "MinaMakar97/ADM-HW3", "max_issues_repo_head_hexsha": "351aedf84c945542994e08cf2ebf2823b1c640d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW3_final.ipynb", "max_forks_repo_name": "MinaMakar97/ADM-HW3", "max_forks_repo_head_hexsha": "351aedf84c945542994e08cf2ebf2823b1c640d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-12T16:31:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T16:31:12.000Z", "avg_line_length": 52.2014172799, "max_line_length": 26674, "alphanum_fraction": 0.5821320232, "converted": true, "num_tokens": 19055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21206881431678098, "lm_q2_score": 0.04146226856587596, "lm_q1q2_score": 0.008792854133649254}}
{"text": "# Rich Output\n\nIn Python, objects can declare their textual representation using the `__repr__` method.  IPython expands on this idea and allows objects to declare other, rich representations including:\n\n* HTML\n* JSON\n* PNG\n* JPEG\n* SVG\n* LaTeX\n\nA single object can declare some or all of these representations; all are handled by IPython's *display system*. This Notebook shows how you can use this display system to incorporate a broad range of content into your Notebooks.\n\n## Basic display imports\n\nThe `display` function is a general purpose tool for displaying different representations of objects. Think of it as `print` for these rich representations.\n\n\n```python\n# display is injected in default namespace, but it's a good idea to be explicit.\nfrom IPython.display import display\n```\n\nA few points:\n\n* Calling `display` on an object will send **all** possible representations to the Notebook.\n* These representations are stored in the Notebook document.\n* In general the Notebook will use the richest available representation.\n\nIf you want to display a particular representation, there are specific functions for that:\n\n\n```python\nfrom IPython.display import (\n    display_pretty, display_html, display_jpeg,\n    display_png, display_json, display_latex, display_svg\n)\n```\n\n## Images\n\nTo work with images (JPEG, PNG) use the `Image` class.\n\n\n```python\nfrom IPython.display import Image\n```\n\n\n```python\ni = Image(filename='images/ipython_logo.png')\n```\n\nReturning an `Image` object from an expression will automatically display it:\n\n\n```python\ni\n```\n\nOr you can pass an object with a rich representation to `display`:\n\n\n```python\ndisplay(i)\n```\n\nAn image can also be displayed from raw data or a URL.\n\n\n```python\nImage(url='http://python.org/images/python-logo.gif')\n```\n\n\n\n\n\n\n\n\nSVG images are also supported out of the box.\n\n\n```python\nfrom IPython.display import SVG\nSVG(filename='./images/python_logo.svg')\n```\n\n\n\n\n    \n\n    \n\n\n\n### Embedded vs non-embedded Images\n\nBy default, image data is embedded in the notebook document so that the images can be viewed offline. However it is also possible to tell the `Image` class to only store a *link* to the image. Let's see how this works using a webcam at Berkeley.\n\n\n```python\nfrom IPython.display import Image\nimg_url = 'http://www.lawrencehallofscience.org/static/scienceview/scienceview.berkeley.edu/html/view/view_assets/images/newview.jpg'\n\n# by default Image data are embedded\nEmbed      = Image(img_url)\n\n# if kwarg `url` is given, the embedding is assumed to be false\nSoftLinked = Image(url=img_url)\n\n# In each case, embed can be specified explicitly with the `embed` kwarg\n# ForceEmbed = Image(url=img_url, embed=True)\n```\n\nHere is the embedded version. Note that this image was pulled from the webcam when this code cell was originally run and stored in the Notebook. Unless we rerun this cell, this is not todays image.\n\n\n```python\nEmbed\n```\n\n\n\n\n    \n\n    \n\n\n\nHere is today's image from same webcam at Berkeley, (refreshed every minutes, if you reload the notebook), visible only with an active internet connection, that should be different from the previous one. Notebooks saved with this kind of image will be smaller and always reflect the current version of the source, but the image won't display offline.\n\n\n```python\nSoftLinked\n```\n\n\n\n\n\n\n\n\nOf course, if you re-run this Notebook, the two images will be the same again.\n\n## HTML\n\nPython objects can declare HTML representations that will be displayed in the Notebook. If you have some HTML you want to display, simply use the `HTML` class.\n\n\n```python\nfrom IPython.display import HTML\n```\n\n\n```python\ns = \"\"\"<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\"\"\"\n```\n\n\n```python\nh = HTML(s)\n```\n\n\n```python\ndisplay(h)\n```\n\n\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n\n\nYou can also use the `%%html` cell magic to accomplish the same thing.\n\n\n```python\n%%html\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n```\n\n\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n\n\n\n## LaTeX\n\nThe IPython display system also has builtin support for the display of mathematical expressions typeset in LaTeX, which is rendered in the browser using [MathJax](http://mathjax.org).\n\nYou can pass raw LaTeX test as a string to the `Math` object:\n\n\n```python\nfrom IPython.display import Math\nMath(r'F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx')\n```\n\n\n\n\n$\\displaystyle F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx$\n\n\n\nWith the `Latex` class, you have to include the delimiters yourself.  This allows you to use other LaTeX modes such as `eqnarray`:\n\n\n```python\nfrom IPython.display import Latex\nLatex(r\"\"\"\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\"\"\")\n```\n\n\n\n\n\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\n\n\n\nOr you can enter LaTeX directly with the `%%latex` cell magic:\n\n\n```latex\n%%latex\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n```\n\n\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n\n\n\n## Audio\n\nIPython makes it easy to work with sounds interactively. The `Audio` display class allows you to create an audio control that is embedded in the Notebook. The interface is analogous to the interface of the `Image` display class. All audio formats supported by the browser can be used. Note that no single format is presently supported in all browsers.\n\n\n```python\nfrom IPython.display import Audio\nAudio(url=\"http://www.nch.com.au/acm/8k16bitpcm.wav\")\n```\n\n\n\n\n\n<audio  controls=\"controls\" >\n    <source src=\"http://www.nch.com.au/acm/8k16bitpcm.wav\" type=\"audio/x-wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\nA NumPy array can be auralized automatically. The `Audio` class normalizes and encodes the data and embeds the resulting audio in the Notebook.\n\nFor instance, when two sine waves with almost the same frequency are superimposed a phenomena known as [beats](https://en.wikipedia.org/wiki/Beat_%28acoustics%29) occur. This can be auralised as follows:\n\n\n```python\nimport numpy as np\nmax_time = 3\nf1 = 220.0\nf2 = 224.0\nrate = 8000\nL = 3\ntimes = np.linspace(0,L,rate*L)\nsignal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times)\n\nAudio(data=signal, rate=rate)\n```\n\n\n\n\n\n<audio  controls=\"controls\" >\n    <source src=\"data:audio/wav;base64,UklGRqS7AABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YYC7AAAAADUWvSvyPzdS/WHKbjt4Bn7+fxV+WXj3bjhifVJDQBYslBZiAC/qpdRswCGuU557kf2HJIIcgPWBoIfykKKdTa15v5rTEuk7/2kV8CopP3ZRSmEqbrJ3mH2vf+Z9TXgNb3Bi11K9QK0sQxcmAQPrhNVPwQOvLZ9IkreIxYKggFiC34cLkZOdFq0bvxbTbeh4/o0UASosPnNQSGAwbcd2w3z2fk9923fGblZi7FL/QBwt3hfoAefrg9ZlwiawVqBuk9OJzoOOgSSDg4iAkdadJa31vrvS3ue5/aIT8Sj/PDBP+F7da3t1h3vUfU98BncibuhhuVIJQWQtYRilAtjso9eqw4mxzKHtlE+LPYXkgleEiolTkm6ee60Hv4jSZuf//KsSwyeiO65NXF0zas9z5nlJfOh6zXUhbSdhPlLaQIItzBhbA9Xt39gexSmzjqPCliuNEYeihPKF9YqDk1mfGq5Uv3/SCOdN/KkReCYYOvBLd1szaMVx4HdYehp5MXTDaxNgfFFwQHUtHRkJBNvuN9q9xgW1l6XsmGOPR4nGhvKHwowPlZegAa/bv6LSxOak+58QFCVkOPhJSVnhZV9veXUCeOh2MnIIaqpecVDLPzwtUxmsBOjvp9uFyBm356dmm/aR3otOiVeK8Y73limiMLCewPHSneYG+48PmSOINslH11Y+Y6BssnJJdVF002/yZ+5cHU/rPtYsbBlEBfvwLd11ymO5e6ownuGU1I44jB+NgZE6mQ+kqLGcwW7Tk+Z1+noOCCKGNGVFI1ROYIppj28vcllxFG2CZeBagU3PPUMsZxnOBRHyyN6IzOC7T61GoSGYJZKBj0aQbpTXm0WmZ7PWwhjUp+by+WMNZCBhMtBCMFEUXSFmEWy4bgJu+Gm6YoFYnkt3PIIrQxlJBinzdOC9zo2+YLCkpLKbz5Unk8yTuJfLns2obrVMxPDU2+Z/+UwMsB4dMAxAAU6TWWdiPGjlak9qgWaaX9FVdEnjOpIq/xi0Bj/0L+IQ0WfBq7NHqJKfzpkml6yXXJsVoqSru7f9xffVL+ce+TYL7hy8LR09m0rOVWFeFGS6ZkJmsmImXNNSBEcVOXQpmhgMB1P19+N/02rELbctrL2jH557m+SbVp+zpciuTrroxy3XpefP+CQKIRtAKwY6/0bKURNanF87YuBhjV5gWIlPUEQMNycoFBhRB2P2yeUG1pTH4bpPsC+ovaIioHGgpKOhqTiyJL0OypHYPOiU+BgJSxmuKMo2M0OJTX9V2FpsXStdF1pKVPVLWUHKNKsmbBeCB2v3o+ej2OHKxb6stOOspacYpU6lQ6jdrfG1PMBtzCTa9ehu+BMIbhcHJm0zOT8RSatQzVVRWCdYUVXoTxlIID5PMgIloRadB2z4gulT203O08I+udax0qxXqneqLq1ksvC5k8MDz+Tb0ele+BcHjRVPI/MvFztmRJtLf1DvUtlSQVA9S/dDqTqeLysjtBWiB2P5ZOsS3tXRCccBvgK3P7Lcr+mvYrIytzK+KcfP0dHdz+pl+CYGqxOJIF4szzaMP1RG80pJTUVN6kpNRpQ/9ja3LCghpRSPB076Ru3e4HTVYcvxwmO86beitZ6127dEvLXC+srQ1Orf8OuE+EIFyRG5HbQoZzKIOtpALkVkR29HUUUbQfI6CDOcKfkecxNkByv7Ju+z4yjZ2M8JyPXByb2ju5K7lL2VwXXHA88E2C7iM+27+GsE6w/gGvck4i1eNTI7ND9HQV1BeT+sOxU25C5QJqAcHxIgB/r7AvGO5u3catREzbHH28PbwcHBiMMhx27MQ9No25zkmO4L+aQDEg4DGCshRSkTMGI1DDn2OhQ7aTkENgExiyrVIh4aqhDEBrr82PJt6b/gEdmd0pTNGcpFyCPIs8nlzJ3RtNf63jLnHfB0+e0CQAwkFVUdlCSsKm8vujJ2NJk0JTMnMLkrASYtH3QXEw9NBmj9pvRL7Jrkyt0Q2JfTfdDazrbOENDa0v3WVdy34u/pxPH3+UgCeApGEncZ1B8uJV0pQyzNLfEtsSwaKkImSiFbG6UUXQ2+BQP+aPYo73rokeKY3bXZA9eV1XLVmNb92IrcIeGd5tDsifOT+rYBuwhsD5UVCRueHzMjryUBJyInFCbiI6AgaRxiF7IRiAsVBYz+Hvj/8VzsYOcw4+rfpd1w3FLcSN1I30DiFeap6tTvbvVJ+zcBDAeZDLQRNxYAGvUcAh8YIDIgUx+FHdgaYxdEE54OlQlSBAD/xvnO9DzwNOzS6C/mXeRm41DjGeS25RroLevX7vjyb/cY/M0AbAXPCdYNYhFbFKoWQRgXGScZdBgHF+0UOxIGD2oLhgd3A2D/XvuS9xf0CPF67n/sJOtx6mfqBetD7BPuZfAl8zr2jPkA/XgA3AMRB/8JjwyxDlYQdBEEEgYSfBFuEOcO9QyqChoIWwWDAqr/5PxI+un32PUj9NXy9vGK8ZHxB/Ln8ib0uPWO95j5xPsA/jkAYAJiBDIGwwcKCQAKnwrmCtUKcQq/CcgIlQc0BrAEFwN3Ad7/V/7v/K/7n/rI+Sv5zPis+Mf4Gfme+U/6IvsQ/A79FP4Y/xAA9wDFAXQCAQNpA6sDyAPCA5wDWgMBA5cCIQKnAS4BvABUAPz/tv+D/2X/W/9j/3z/ov/Q/wIANABiAIcAngClAJkAeQBFAP7/pP87/8j+Tv7V/WD99/yg/GD8PPw5/Fn8nvwJ/Zn9S/4c/wMA/gACAgcDBQTxBMEFbgbwBj4HVAcuB8oGKQZMBTgE9QKJAQAAZv7G/C/7rflP+CH3L/aD9Sb1HfVr9RL2Dvdc+PL5x/vN/fb/MAJrBJUGmwhsCvgLLw0HDnQOcQ78DRMNvQsACucHggXiAhoAQP1p+q33IvXe8vXwd+9z7vXtA+6f7sjvd/Gj8zz2Mflq/NH/SgO8BgoKGg3RDxkS3hMOFZ4VhxXFFF0TVRG8DqMLIAhOBEkAMvwl+EX0sfCG7eDq1Oh259Pm9ObZ54Dp3+vk7nzyjPb1+pf/TATyCGQNfBEbFSAYdBoAHLYcjhyFG6EZ7RZ8E2cPzArMBY4APPv99fvwXuxM6OfkTOKR4Mbf9t8h4UHjSeYj6rTu2vNv+Uf/NQUNC58QvxVEGgge7CDXIrYjgSM1ItofgBw9GDITgw1bB+kAYPrx88/tLOg04xHf5NvK2dXYD9l72g/du+Bk5ejqHvHY9+L+BAYKDboT4BlKH8wjQieMKZgqWSrPKAMmCCL6HP8WQhD4CFgBnvkD8sbqHuRC3mHZotUn0wTSRtLt0/DWOduq4BvnW+409mn+ugboDrIW2h0oJGgpby0cMFYxEjFPLxcsgSevIcoaCBOjCtsB9fg18ODnOOB52dvTi8+tzFrLoMt+zenQydX821LjlOuE9N39VQemEIUZrCHaKNYubzN+Nuo3pTetNRAy5ixWJpEe0RVYDHECZ/iH7iDlfNze1IXOpMlixt3EIsUyxwDLcNBc147fyujJ8j791wdDEjEcUSVdLRM0PDmwPFA+DD7lO+k3MjLtKk8imhgXDhgD8/f77Iji7dh10GPJ8cNLwJG+0r4PwTnFMsvP0tbbAuYG8Y78Pgi+E7QeySitMRo50z6rQoFEQ0TyQZw9YTdvLwImYRveD9EDmPeR6xrgjtU/zHjEd75tuny4trgau5q/FcZazivYPuM97837jAgXFQ0hDyzHNec9L0RrSHhKQ0rNRyVDbTzXM6QpIh6pEZgEV/dK6tfdYdJByMm/O7nNtKSy0rJatSi6HMEAypLUgOBw7f76wAhNFjojIi+oOXdCSknqTTBQCFByTX5IUUEhODMt2yB3E24FL/cl6cDbaM9+xFm7QbRwrw2tLa3Sr+m0TbzGxQ7Rzd2i6yL63AhgFzslADJNPcdGIk4lU6VVjVXcUqNNCkZJPKswiCNGFVEGH/ck6NbZpcz4wCu3jK9ZqrunyqeHquCvrLexwaPNJtvU6Tr54AhPGA0nqDS0QNJKs1IXWNJazVoFWI9SkkpLQAg0JyYSFz8HJ/dH5xvYGsqxvUKzIKuNpbSir6J/pRKrPbPDvVTKkNgI6Ef4zAgbGbEoFzfaQ5dO+Va8XLJfw1/qXD1X5k4jREc3tSjbGDYIRveN5o7Wx8esuqKvAacPofud352+oISmBa8CuibHDNZD5kz3owjDGSYqTDm+RhJS8FoRYUJka2SGYapbAVPNR2U6LiueGjQJevf25THVsMXqt0ysMqPknJWZYJlJnDqiCKtwthrEntOF5Er2ZAhJGmsrRjtdSUJVl14RZX5owWjVZdBf31ZFS109jy1XHDkKwveB5QTU08NttUSptZ8PmYWVNJUimDmeSqcSszbBStHR4kP1EgisGoEsBT23SyNY6WG7aGJswWzSaaxjfFqITixA1i8FHkELHvgv5QbTM8I3s4qmjpySlc6RYJFOlIOaz6Psr3y+Ec8p4Tn0rQfuGmcthz7JTbVa5mQLbOtvaHB7bTpn1V2SUdBCADKlH0wMjPj95DjSz8BJsSGkvZlwknOO543RkB2XmqAArfC798yR3y/zNwcPGx0uzT+TT/Vcimf+bhdzs3PMcHhq5mBfVEVFCjQ1IVcNC/ns5JnRp7+jrwqiRpesj3eLy4qujQmUrp1SqpS5/soK3iXysQYQG6Uu1UAUUeJe1GmTceJ1nnbCc2FtrGPtVohH8TWyIl8OmPn75CnRvb5HrkagKZVHjd2IEIjnikyRDpvkp2u3KcmX3B3xHAbzGv4uoUFMUnxgw2vHc0p4KHlZdvJvJGY5WZZJszcaJGQPMvon5efQD74zrdaeaJNDi6eGuIV/iOeOv5i7pXi1e8c62xvwfAW4GikvMUI7U8JhVW2adU96TnuReCpyS2hAW21LTDlrJWMQ2fpw5dLQnr1qrLudBZKiidaExYN5ht2MwZbYo76z9sX22SDv0ARhGigvhELgU7Niim4Jd+17D31legV0H2r+XApNvDqjJloRifvV5enQaL3pq/Sc/pBliGuDOILWhDCLF5U+oj6yncTM2C7uHATvGfsunUI8VE9jYW8UeCN9Z37We4J1nWtzXmpO/ju+J0cSQfxU5izRbb2xq4KcVpCMh2iCE4GYg+OJxJPuoPywcsO/10ftYQNkGaMue0JQVJdj22+7ePJ9WH/gfJ92xWycX41PEj28KCgT//zr5pjRrL3Bq2ScDJAYh86BWIDBgveIyZLsn/qvdsLR1mzsoALBGCMuIEIcVItj92/9eFh+33+EfVt3k214YG9Q9T2aKfsTwv2Y5yzSI74ZrJqcH5AIh5yBBoBRgmyIKJI4nzmvrMED1qHr3AEJGHwtjUGhUyxjtW/beFZ+/H/AfbR3B24EYQ9Rpj5WKr8Uh/5b6ObS0b62rCKdjpBch9OBHYBJgkSI4ZHVnrquFsFZ1ebqFgE9F64sxEDiUntiF29UeOp9r3+Ufap3IG4/YWxRIj/vKnAVTf8w6cbTtL+XrfydWpEUiHKCn4CpgoCI9pHCnn+utMDT1D/qUABfFr4rxz/fUXphHm5rdxd9+H7/fDx33G0pYYRRaD9iKw4WEAAW6sjUy8C7riWfgJIviXmDioFygyCJaJIBn4quicBz1Kvpjv9xFasqlz6aUClgy2wfdt172X0DfGt2PW3AYFZRdz+vK5YW0gAL6+rVE8IgsJyg/5OqiuaE3oKihCOKNpOTn9uulsA61C7pz/51FHkpNz0WT4xeIWt0dD16UXyfejZ1QWwFYOJQTj/TKwgXjgEO7CzXi8PEsWCi1ZWGjLiGmoQ5homLYJR4oHOv3MAq1MnoFv5tEykoqDtUTaNcIGlpcjl4YnrVeJ9z6Gr2XiZQ7D7OK2EXQwIb7YrYMMWks22kAJi+ju6Iu4Y2iFKN5pWwoVKwW8FF1HzoZf1bEr4m7jlXS3Jay2YDcNN1DnimdqVxNGmVXSNPUD6eK6AX8AIx7gHa/8a9tcGmfppSkYWLQYmXinyPyJc6o3mxFMKK1EvovvxBETolCjghSftXJWRCbQxzV3UTdEtvJWfiW9lNej1DK8MXkgNO75Hb98gOuFqpS50/lHqOKYxbjQaSBJoXpeeyCMP71DboIfwiEJ8jADa2RkFVMWEqauhvQHIgcZJsvWTcWUhMaTy7KsoXKARv8DbdE8uTujSsZaCBl8yRcI9+kO2UmZxEp5y0NsSZ1T3okvv/DvAh0TMYREdS8l2+ZmpsyW7NbXxp/GGHV29KHTsHKrMXsQST8e7eU81JvUyvyaMWm3aVFJMAlDGYhZ/CqZe2n8Vk1mToEfvaDS8ggTFLQRFPa1oCY5Ro+Godagxm5V7iVFFIlzklKX4XKgW48rfgss8twKCycqf6nneZEpfcl86bx6KOrNi4Qsdc16nooPq2DGAeEy9QPqFLoFb4Xmpkz2YUZkNieVvvUe5F1jcWKCkXkgXb843iLtI8wyu2Xqspo8mdZpsQnMKfW6anr127H8mC2A7pQfqUC4MciiwtO/xHlFKkWvBfUWK2YSVevFewTkdD3TXZJrMW6AX79G/kxNRzxuq5ia+gp2miDKCZoAmkQKoLsyW+NcvW2ZTp9Pl3Cp0a6SnlNyVES04LVipbg10EXbVZsFMoS15AqjNvJR0WKwYW9lrmcNfNydi97rNarFSnAaVypaGocq63ti7BhM1X2zvqu/lfCa8YMid6NB9AykkxUR1WaFgEWPZUWE9YRzU9QDHYI2UVWQYp90voMNpIzfPBirhTsYSsQaqYqoWt77KqunfECdAE3QPrmPlQCLsWaSTwMPA7FUUbTMtQBVO6Uu1PuEpEQ845oC4UIowUcgY0+D/qAd3f0DbGV72GtvWxxq8GsLKys7ffvv3HxNLe3u3rivlLB8UUkSFMLZs3MUDMRjxLX00pTZ1K0kXuPio2zCslIJITdAY0+Tbs39+P1JzKUsLvu6K3jLW4tSS4urxUw73LstXj4Pjsk/lRBs8Srh6RKSUzITtKQXJFe0dXRwtFqkBaOk0yxCgLHnUSXwYo+ivuyOJV2CLPdceIwYe9jrupu9a9AcIGyLbP0tgS4yXutPlkBdsQwRvCJZEu6zWaO3Q/XEFIQTo/RjuLNTkuiyXHGzgRMwYO+x3wt+Us3MPTvcxOx57Dx8HUwcPDgsfyzOTTI9xr5XPv7fmFBOwOzxjkIeQpkzDBNUY5CjsCOzE5qDWFMPIpJCJaGdoP7gXk+wryq+gQ4HvYI9I6zeHJMcg0yOjJO80S0kXYoN/r5+LwPvq2AwMN2hX5HSIlHyvEL+4yiTSJNPMy1i9LK3olkB7HFlsOkAWr/O7zoOv/40XdpNdH00zQyM7Ezj3QJtNk19TcSeOR6nDyqPr5AiML5hIHGlEgkyWoKXIs3i3kLYcs1CniJdQg0xoOFL0MGQVf/cn1k+705x3iOt1w2djWhdV+1cDWPtni3I7hG+db7R30LPtOAk4J9Q8RFnMb9B9zI9clECcXJ/AlpyNPIAYc7hYzEQELiQQB/pj3gfHr6/7m4eKv34HdY9xc3Gndft+K4nDmEutI8On1yPu1AYUHCg0aEo8WSBoqHSIfJCApIDYfVB2VGhEX5hI2DicJ4QOP/ln5aPTg7+XrkugA5kDkXONZ4zPk4uVV6HbrK+9V89H3ffwxAcwFKQomDqcRkhTTFlsYIBkfGV0Y4Ba5FPsRvQ4aCzAHIAMJ/wv7RPfR88zwSu5c7A/raupu6hrrZOxA7pzwY/N/9tX5Sv3CACMEUwc5CsEM2Q5zEIURChIAEmoRUhDBDscMdgrhBx8FRgJu/6v8E/q697D1A/S+8unxhvGX8Rby/vJF9N31uPfF+fP7MP5oAIwCiwRWBuEHIgkQCqgK6ArQCmUKrQmwCHoHFQaOBPUCVQG9/zj+0vyW+4v6uPkh+cf4rPjL+CP5rPlf+jX7JPwk/Sr+Lf8kAAkB1AGBAgsDcAOvA8kDwAOXA1MD+AKNAhcCnQEkAbIATAD2/7H/gP9j/1v/Zf9//6X/1P8GADgAZQCJAJ8ApQCXAHYAQAD3/5z/Mv++/kT+y/1X/e/8mvxc/Dr8Ovxd/Kb8FP2n/Vz+Lv8YABMBGAIdAxkEAwXRBXsG+AZCB1MHKAe/BhkGNwUfBNgCaQHf/0T+pPwO+475NPgL9x72efUi9SD1dvUj9if3e/gX+vD7+v0kAGACmgTCBsQIkAoVDEUNFA54DmwO7Q37DJsL1gm3B0wFqALe/wP9Lfp19+/0svLQ8FzvZO7x7Qrusu7n76Hx1/N49nP5svwaAJQDBAdOClcNBhBEEv0TIBWjFX0VrRQ3EyMRfg5bC9EH+gPz/9r70ff282nwSe2u6rDoYefO5v/m9ees6RnsLO/O8uf2Vvv7/7EEVAm/Dc8RYRVZGJ0aGBy7HIAcZRtvGaoWKxMKD2QKXgUdAMv6j/WU8AHs/eeo5B7id+DB3wXgReF545Pmfuod70306fnF/7MFhwsRESYWnBpPHh8h9CK8I3AjDSKcHy0c2Re+EgMN0wZeANX5avNR7bvn0+LD3q3bqtnO2CLZp9pT3RXh0eVm66rxbPh6/5wGnA1DFFsatB8hJH4nrymfKkUqoCi6JaYhgxx2FqsPWAizAPn4ZPEx6pnj0N0F2WHVAdP80VzSINQ/16PbK+Gv5/7u4PYa/2sHkw9SF2oeoyTKKbYtRDBfMfswGC/CKxEnJSEsGloS6gkdATj4fu81557f9thy0z/PgsxQy7jLuM1D0UHWjtz6403sSPWm/h8IaRE7Gk8iZilGL8AzrTb1N4s3cDWwMWcsvCXfHQ0ViAubAZH3ue1f5M7bStQOzk7JMcbRxDzFcsdky/bQ/9dK4JnppfMg/rgIHRP8HAkm+i2RNJc55TxdPvE9ojt/N6YxQiqKIcEXMA0rAgb3Fuyy4SzYz8/eyJHDE8CDvu6+VcGnxcXLg9Ol3Obm+PGH/TYJrxSVH5MpWjKlOTg/5kKQRCZEqUEpPcc2sy4qJXMa4A7MApT2luov37rUicvmww2+L7psuNS4ZrsSwLTGHc8M2TbkRfDd/JsJHRYCIuwshTaAPp5ErEiKSiVKf0epQsc7DDO6KCAdlxB+Az32OenY3HvRfMcqv8e4ibSRsvGyqrWousfB0sqE1Yzhje4j/OUJaBdDJBIwdjodQ8NJMk5FUOlPH036R6BASDc4LMYfUBI/BAD2AOit2nDOqMOsusOzJa/3rE2tJ7BwtQO9psYR0uve0uxb+xUKjxhXJgEzKj55R6VOc1O9VW1VhFIYTU5FYzuhL2IiDBQNBdz16+ax2JzLE8BytgWvB6qip+un4KpvsG24nsK1zlXcF+uH+i0Kkhk8KLk1oEGRSz9TbFjsWqxaqlf9Uc1JWD/vMvAkxhXoBdH1++Xj1gDJvrx9spCqNaWYos+i3KWoqwe0vL51y8/ZXemn+SwKcBryKTg41ERiT45XF13QX6JfjFylVhdOJEMgNm0nfhfNBt31L+VG1Z7Gq7nRrmimsaDcnQCeHqEgp9ivBrtUyFvXqOe9+BQKKht3K306xkfpUo9bcmFkZEpkJmELWypSxEYwOdgpMRm7BwD2h+TY03fE3LZwq5CigJxymYCZqpzbouOrf7dVxfvU+eXL9+YJwBvMLIY8ckojVj5feWWjaKFocmUtXwBWMkocPCws2xqwCDn2A+Sc0o3CU7RdqAqfpJhelVOVhZjeniyoKrR8wrPSU+TT9qMJMhzwLVI+10wPWZhiKGmKbKJsbmkFY5dZbE3hPmcufByrCYb2ouOQ0d/AEbKZpdqbIZWkkX6Rs5Qsm7ekDLHMv4bQuOLX9UwJghzjLuE/9U6qW51lfmwXcEtwFm2QZupcblB8QYYwEB6oCuf2Y+O10G+/GLAnowKZ+pFFjgOON5HJl4ehJ65IvXbOLOHY9OIIsBymLzJByVDzXUhod29Gc5dzZnDKafZfNVPoQ4YylR+oC1n3RuML0D2+aK4HoYSWMI9Gi+aKFI64lJ+ef6v0uobMr9/Z82cIvBw4MEVCVFLpX5lqEXIVdoV2W3OxbLhivVUkRmU0CSGmDNz3SuOQz0m9Aq07n2CUxoypiCmITYv8kQOcF6nRuLnKRN7b8t0HqBybMBpDlVOLYY9sSnSBeBB583VBby1lBFgsSB82aSKjDW74beNFz5K856vEnZmSvopvhs+F5IiYj7aZ8abkthLJ79zh8UUHdhzPMLJDi1TXYiduInaIejh7K3h4cVJnCFr/SbM3tCOaDgz5r+Mozxm8FqujnDCRGImahNqD3YaOjbqXEaUttZLHsNvs8KAGJhzVMAxEN1XOY2FvlXcqfPt8AXpUcyVpxFuYSx455iSMD7b5DeQ5z927j6rWmyWQ14csg0uCOYXiixGWeaOxszzGitr/7/EFuhutMCpEmFVwZD1wpHhkfVZ+c3vRdKNqOF33TF46/iV1EGr6h+R3z927U6pgm3iP+oYmgiSB+oOUir6UKqJxshPFgNkb7zoFMxtbMA1EsFW8ZLpwT3k2fkl/gHzvdctrYV4YTnE7+iZTESX7GuXfzxi8X6o+myqPgoaJgWWAIYOmicKTKKFusRjElNhD7nsEkxrdL7VDgFWzZNlwlHmfftJ/JX2tdptsPV/7TlM81yclEub7xuVx0Iy8tKpxmzqPb4ZUgRGAroIZiR+Tc6CssE7Dxtd47bgD3Bk3LyRDCFVXZJtwdHmffvJ/ZH0IdxFtyl+dTwU9lCjoEqv8iOYq0Tm9T6v3m6iPwYaJgSaApILviNaSDKArsLXCGte87PECEBlqLlxCSVSnY/9v8Hg2fqh/O30BdyxtCWD8T4Q9LymcE3P9XucK0h2+MKzPnHKQeIcmgqWAAYMoieiS95/ur1HCkdYR7CoCMBh4LV5BRlOmYgdvCHhlffR+qXyXdu1s9l8YUM49pik9FDr+R+gO0zW/Va35nZiRkYgqg46BxoPDiVWTMqD0ryHCLdZ662MBPxdjLCxAAFJVYbRtvnYtfNd9sHvJdVJskl/vT+I99ynKFAD/QOk01IDAvK5xnxeTDIqWhN+C84TCih+UvqA/sCjC7tX36p4APhYsK8g+eVC2XwlsE3WOelJ8UHqZdFpr3V6BT789IipCFcL/SOp71fzBYrA3oe6U54tnhpiEh4YkjEOVnaHQsGfC19WL6uD/LxXXKTU9s07KXQZqCHOLeGZ6iXgGcwhq1V3NTmU9JSqjFX4AXOvf1qbDRrJHoxuXII6biLeGgIjojcSWzqKosd7C6dU26ib/FhRlKHQ7sUyWW69noXAmdhR4XnYScVpoe1zSTdI8/inrFTQBe+xe2HzFZrSfpZuZtZAxizqJ3YoMkJ+YUKTGso3DJdb76XX+8xLYJok5dkoaWQdl321gc191z3O+blJm0FqRTAU8rikZFuABoe332XvHvbY9qGyco5MnjiCMnI2QktOaJKYqtHfEi9ba6c39yRE0JXY3A0hbVg9ixWo8cEly4HALbPFj1FgKS/86MiksFoICzu6n26HJSrkdq4qf6JZ4kWWPvJBylWCdSKjUtZnFHNfV6TH9mhB6Iz41XUVaU8teV2e9bNVukW37aDlhiFY9ScA5iigiFhgD/+9r3evLCbw9rvOif5ojlQeTOpSvmESgvKrEt/XG2tft6aP8aA+tIeMyhkIcUD5bl2PmaAZr5mmRZSpe7VMrR0c4tyf7FZ8DMvFA31bO976ZsaKmZ54lmQOXEphGnH2jfa34uYvIxNgj6iP8NQ7PH2kwgT+kTG1XiV+8ZN5m4WXPYchaBVHURJU2tya2FRcEZPIl4d/QEsIttZWqmqJ4nVabQpwzoAini7BwvFnK2tl46rP7Aw3kHdItUjz1SFlTMVtAYGFihmG3XRRX0007Qqo0iiVRFX4ElfMW44PTVMX2uMeuFqcbovufxqBzpOOq47Mqv2DMHdvt6lX71AvtGyEr/DgTRQlPk1Z4W5Rd2VxOWRJTVkphP4gyMiTNFNMEwfQS5T/WvMjwvDWz1asHp/Ckm6UEqQyvgrckwp3Oi9yB6wr7qwruGVsogzUCQX9Ks1FoVnpY3VeXVMROlEZHPC8wrSIpFBUF6PUV5xDZRcwXwdq31LA6rC6qvarhrX6zaLtexRHRJt427NL6iAnoF4El6zHHPMFFlkwTURhTllKVTy5KjULvOKEt/CBjE0IFBvcd6fLb7M9mxbG8DravsbOvKLAHsze4j7/UyLrT7d8L7bD6bgjeFZciNy5kONJAQEeAS3JNCU1MSlJFRT5bNd4qIB9+ElkFG/gn6+PerNPaybbBfrtgt3m11rVxuDS998OEzJbW3eEB7qP6XwfUE6EfayrfM7c7t0GyRY1HO0fBRDZAvjmPMeonGx13EVsFJPkx7d7hg9duzuXGIMFJvXu7w7scvnDCm8hs0KPZ+OMY7636XAbKEaAciiY9L3U2/zuwP25BMEH4Ptw6/jSMLcUk7BpQEEUFIfo57+LkbNsf0znM7sZkw7XB68ECxObHeM2I1N/cOuZP8M/6ZgXFD5oZmiKAKhExHTZ9ORs77Tr2OEk1BjBWKXEhlRgJDxcFD/s88evnZN/n16zR48ytySHISMgfypTNidLX2EngpOim8Qj7gATFDZAWnB6uJZArFjAgM5g0dzTAMoIv2yrwJPIdGRaiDdIE7vs48/bqZuPB3DrX+dId0LnO1c5u0HPTzNdU3d3jNOsd81r7qQPNC4UTlhrMIPYl8CmeLOwt1C1aLIspgSVdIEkadxMdDHQEu/wr9f/tb+er4d7cLNmv1njVjNXp1oHZPN384Zrn5+2y9MT75QLgCX0QjBbdG0kgsSP8JRwnCifKJWkj/B+gG3oWshB5Cv4Ddv0S9wTxeuue5pPid99e3VjcaNyL3bbf1eLM5nzrvPBk9kb8MwL/B3sNgBLmFo4aXR1BHy4gHiAXHyEdURq+FoYSzQ24CG8DHv7t+AP0hu+X61To0uUk5FPjY+NP5A/mkejA64DvsvM0+OH8lQEsBoIKdg7sEckU+xZyGCcZFhlEGLkWhBS6EXIOyArbBsgCsv64+vf2jPOR8BvuOuz76mPqduov64bsbe7T8KPzxPYe+pX9CwFpBJQHcwrzDAEPjxCWEQ4S+BFYETUQmw6ZDEEKqAfjBAkCMv9y/N75i/eI9eTzqPLc8YPxnfEm8hbzZPQC9uL38/kj/GD+lwC4ArQEegb/BzkJIAqxCukKygpZCpsJmQheB/UFbQTSAjIBnP8Z/rb8fvt4+qn5F/nD+Kz40fgs+bn5cPpI+zn8Ov0//kL/OAAbAeQBjgIVA3cDswPKA74DkwNMA/AChAINApMBGwGpAEQA7/+s/33/Yv9b/2b/gf+p/9j/CgA8AGkAiwCgAKQAlQByADoA8P+T/yn/tP46/sH9Tv3n/JT8WPw5/Dv8Yvyt/B/9tf1s/kH/LAApAS4CMgMuBBUF4QWHBgAHRgdSByIHtAYIBiIFBgS6AkkBvv8h/oH87fpw+Rn49PYN9m71HvUk9YH1NvZA95v4PPoa/Cf+UwCQAskE7wbtCLMKMgxaDSAOfA5mDt0N4gx5C6wJhgcWBW0Cov/G/PL5Pfe89IbyrfBD71Xu7e0T7sfuB/DM8Qv0tfa2+fn8ZADfA0wHkgqUDTsQbhIbFDEVphVyFZUUERPwEEAOFAuCB6UDnP+D+3z3p/Mi8AvtfeqN6E3ny+YM5xPo2elU7HTvIvND97j7XgAVBbUJGg4gEqcVkRjEGi4cvxxxHEMbOxlnFtkSqw78CfAErf9a+iL1LvCm66/naeTy4V7gvd8W4Gvhs+Pf5trqhu/C9GT6QwAxBgEMgxGMFvMalB5QIQ8jwSNdI+MhXB/ZG3MXSRKDDEwG0/9K+eXy1exL53Tid95324zZydg32dXamd1x4UHm5us28gD5EQA0By8OyxTVGhwgdCS5J9AppSovKm4obiVCIQoc6xUUD7cHDgBV+MbwnukV41/drNgh1d7S9tF00lbUkdcO3K3hROih7473zP8bCD0Q8Bf4HhwlKir6LWowZTHhMN8uayueJpogjRmrETEJXwB798jui+YG33TYC9P2zlnMScvTy/TNoNG71iLdo+QH7Q32cf/oCCoS7xrxIvAptC8ONNk2/TdvNzA1TjHmKx8lKx1IFLcKxAC89uzsoOMj27jTms37yALGyMRaxbbHy8t+0aTYCOFp6oH0Av+ZCfYTxh2+JpQuDDXvORY9Zj7SPVs7EzcXMZQpwyDmFkkMPQEZ9jLr3eBt1yzPXMg0w9+/eL4Ov5/BGcZbzDnUdd3L5+vygP4vCp4VdCBbKgUzLjqaPx5Dm0QFRFxBszwrNvUtTySDGeINyAGR9ZvpRt7p09bKV8OnvfW5X7j1uLW7jMBXx+PP79kw5U7x7f2pCiIX9iLHLUA3FT8JRepIl0oCSixHKkIeOz8yzicdHIMPYwIk9Sno2tuX0LnGjr5XuEi0grIVs/+1LLt2wqfLedaZ4qvvSf0JC4IYSyX+MEA7v0M4SnZOVVDFT8hMckfrP2w2OyuvHikRDwPR9NvmnNl6zdbCBLpKs96u5axxrYCw/LW+vYrHFtMK4APulfxOC70Zcif/MwQ/KEgjT71Tz1VIVSlSiEyORHk6ky45IdESygOZ9LPljdeVyjK/vbWCrrqpjqcQqD6rArExuY7Dys+H3Vvs1Pt5C9MaaSnINohCTEzHU7xYAluHWktXZlEDSWE+0jG2I3kUkQR69LDkrtXpx867vLEEquKkgaL1oj2mQqzWtLm/mMwR27PqB/uMC8QbMCtXOctFKVAfWG1d6V99XylcB1ZETSJC9TQkJiAWZAV19NLj/9N4xa24Ba7TpVigwp0lnoKhwKewsA+8hcms2A7pLvqFC48cxiyrO8pIu1MoXM5hf2QlZMBgaFpOUbZF+TeAKMIXQgaH9BnjgtJCw9G1maryoSGcVZmlmRGdgaPDrJK4k8Za1m/nTPlnCzUdKi7CPYJLAFffX9tlwmh8aAplhV4dVRpJ2TrGKl4ZJwew9IbiNtFKwTyze6dknj+YPZV4le+YiJ8TqUa1xcMf1NflY/gzC7cdXS+bP/RN9llCY5BprWx+bARpWGKtWEtMkz31LPEaEwjv9BbiHdCPv++wrqQtm7eUgJGikR6V2pukpTCyH8H+0UnkdffqChQeXTA3QR1Qm1xOZutsPXAocKts4GX6W0ZPJEAJL3kcBAlC9crhNc8TvuuuMqJNmIqRHo4mjqOReph5olOvpL74z8jigvaNCk4eLDGTQvtR7V4Baepvb3N1c/pvF2kCXwZSiEL/MPMd+Amp9aHhf87WvDGtCqDHlbuOG4sHi4CObJWWn7GsWLwRzlXhjvUdCmYeyjGxQ5BT62BZa4lyQXZkdu9y/GvAYYlUvUTWMl4f7Qoh9pvh+s3Yu8KrNp6dk0yMeohJiLmLspL+nE6qPLpMzPPfmfSdCVweNjKPRNlUlGJVbcd0sXjyeId1i24xZMtWv0aJNLYg4Aup9rXhps0Zu5+quJzQkT6KPYbthVGJT5Czmi2oU7iryqXep/MNCTIecjIvRdZV52PzbqN2vHoce8B3wXBUZstYjUgXNvoh0QxA9+7hgc2ZusepkJtikJSIZYT1g0mHRo65mE+mobYwyWzdufJvCOkdfzKQRYlW5GQycBt4YHzgfJZ5nHImaIVaI0p+NycjvA3k90bijM1WujqpvppSj0+H9IJkgqOFmYwRl7mkKLXex0vc0PHGB4MdXjK0RfBWi2UTcS55nX0+fgp7GnSjafdbf0u7ODwkoQ6T+LvixM1RuvmoQpqhjm6G64E7gWKES4u+lWuj6bO3xkTb8PASBwAdDzKbRQxX22WUcdx5cn4zfxh8OXXLaiBdoEzMOTUlfA9L+UvjKc6IugGpHZpPjvOFS4F6gIeDW4rBlGii57K9xVnaGvBWBmMclTFHRd9W1mW2cSR63n6/f8B8+HWca/1dgk2uOhImTRAK+vXjuM76ulOpTZpcjt6FE4EjgBODzYkclLKhJLLyxIvZT++UBa4b8TC4RGlWfGV6cQd64X7hfwF9VnYVbIxeJk5hO88mERHQ+rbkcc+lu+2p0ZrIji2GRYE1gAWDoInRk0qhobFYxN7Yku7MBOEaJDDwQ6xVzWTgcIV5e36af9p8UnYzbM1eiE7iO2wnxhGY+43lUdCJvM2qqZuQj+KG4IGygGCD1YnfkzChYLHxw1LY5e0DBP8ZMS/xQqhUzWPpb594rH3pfkx863X3a75eqE4wPOcnaxJj/HnmV9GivfOr0py1kPmH44KXgSKEbYpJlGehYrG9w+nXSu04AwsZGS69QWFTe2KXblZ3dXzOfVZ7InVga19ehE5JPD4o/RIt/XbngdLwvlutS540knOJTITmgkuFaIsNle6hqLG+w6XXwexuAgUY3ixWQNhR2mDrbKt12XpMfPp59nNvaq9dHE4tPG8oexP1/YPozNNwwAWvE6AMlE6LHIachNuGxYwtlseiMrL2w4fXTuyoAfEWgyu+Pg5Q7V7naqFz13hiejd4aHIiaa5cb03aO3ko5BO6/p7pNtUfwu6wJqI7loiNT4i5htCIhI6nl/GjArNkxJDX8evmANAVCir4PAhOtVyOaDlxcnYTeBB2eXB7Z1xbfUxQO1woNRR4/8Xqvdb8wxKzgqS9mB2Q5Io6iSmLo5B7mWulF7QKxcLXq+srAKMUdSgGO8ZLNVrjZXZurXNhdYVzKm56ZblZRUuOOhYobhQuAPbrX9gDxnC1JaeRmw2T2Y0djOWNIZOomzancbXpxR3Yf+t5/28TxybqOExJcFfnYlpriXBNcppwfWshY8ZXyEmTOaYnjRTcAC7tGdozyAW4DKq0nlSWK5FgjwCR/JUtnlGpELcAx6LYbuvR/jQSAiWoNp5GaVSfX+lnCm3bbk9tdGhwYIRVBkhgOAsnkBR/AWvu6duHys26M60hou6Z1pQAk3mUM5kIobqr9LhPyFLZeOs1/vQQKCNCNL1DI1ENXCdkM2kNa6hpEGVqXfRSAEb0NkYmeBQVAqzvy93+zMW9lrDXpdmd2Jj7lk2Yw5w4pHCuHLvXyS3an+um/bMPPSG7Ma5Aok01WBVgB2XnZqhlVWESWhhQt0NRNVUlQhScAu7wvt+Uz+rAM7TQqRCiLZ1Mm3mcqaC5p3Kxhr2WyzPb5Osm/XEOQx8XL3M96kkbVLlbimBsYlJhRV1oVvFMLEF1Mzkk7xMUAy/yv+FG0jnEBrgKrpCm0aHwn/mg4qSLq760MsCNzWXcR+y2/DENPB1YLBE6/UXCTxZXwVugXalc41hvUoFJYD5jMfIifBN8A23zy+MR1a7HC7yAslWrwKbjpMqla6mpr1G4HsO6z8LdyexY/PYLKxuBKYo24UEwSzFSrlaHWLFXM1QsTstFVTscL38h6xLQA6b04OXy10bLPcAtt1qw9ashqueqQa4RtCm8R8Yc0krfau0N/MAKExmXJuMymT1oRg1NV1EmU25SOU+gSdJBDTifLOIfOhISBNj1++fl2vvOmsQOvJq1bbGlr02wX7PAuEPArcmz1P3gK+7V+5EJ9habIx8vKjlvQbFHwEuATeZM+EnQRJg9ijTvKRoeaRE+BAL3Gero3czSG8kewRG7Ibdrtfi1wrixvZ3ETc1819niC++z+20I1xSSIEMrlzRKPCBC70WbRxtHdES+PyA5zzANJykceBBWBCH4OOz34LTWvs1YxrrADr1tu+G7Zb7iwjLJI9F22t7kDPCn+1MHuRJ+HVEn5i/9NmA86D99QRNBsz5wOm003Sz8IxAaaA9XBDX5Vu4P5K/afdK3y5HGLsOnwQbCRMRNyADOL9We3QvnLPGx+0cGnRBjGk4jGiuMMXU2sTkpO9Q6uDjoNIQvuSi9IM8XOA5BBDr6b/At57neVdc30Y7Me8kTyF/IWcrvzQPTa9nz4F/pbPLS+0gFhg5DFz4fOCb+K2YwTzOlNGI0iTIsL2gqZSRSHWkV6QwUBDH7g/JN6s7iQNzT1q7S8c+tzunOoNDE0zfY1t1z5NjryvML/FoEdwwjFCQbRSFXJjcqxyz4LcItKyxBKR4l5B++Gd4SewvPAxf8jfRt7evmOuGE3OvYidZt1Z3VFNfF2ZjdbOIa6HTuR/Vc/HwDcQoFEQUXRBycIO0jICYmJ/smoiUqI6gfOhsEFjEQ8AlyA+z8jfaJ8AzrP+ZH4kDfPt1O3HbcsN3w3yLjKufn6zLx4PbF/LECdwjsDeQSPBfSGo8dXx82IBIg9h7uHAwaahYmEmMNSAj+Aq79gfie8yzvS+sW6KblCuRM427jbeQ95s/oC+zV7w/0lvhG/fkBiwbaCsUOLxL/FCIXiRgtGQwZKhiQFk4UeREoDncKhQZxAlz+Zfqq9kjzV/Dt7Rns5+pf6n/qRuup7JzuC/Hj8wr3Z/rf/VQBrwTUB6wKIw0nD6sQpRESEvARRBEXEHMOagwMCm4HpgTMAfb+Ofyq+V33YfXF85Py0PGB8aTxNvIu84P0KPYM+CD6UvyP/sUA5ALcBJ0GHAhPCTAKuQrqCsQKTAqHCYAIQQfWBUsErwIQAXr/+v2b/Gb7ZPqb+Q75v/it+Nb4NvnH+YH6XPtO/E/9Vf5X/0wALQHzAZsCHwN9A7YDygO7A44DRQPnAnoCAwKJAREBoAA8AOn/p/96/2H/W/9o/4T/rP/c/w4AQABsAI4AoQCkAJMAbgA1AOn/i/8f/6r+MP63/UX94PyO/FT8OPw9/Gb8tfwq/cP9ff5U/0EAPgFEAkgDQgQoBfAFkwYIB0kHUAcbB6gG9wUMBewDnQIpAZz//v1f/Mz6Uvn/99/2/fVk9Rz1KPWM9Un2Wve7+GL6RPxV/oMAvwL4BBsHFQnWCk4Mbw0sDn4OXw7MDcgMVwuBCVUH3wQzAmX/ify3+QX3ivRb8orwKu9H7uvtHO7c7ifw9/FA9PL2+vlB/a4AKQSUB9UK0Q1uEJcSOBRCFagVZhV7FOkSvBABDssKMgdQA0X/LPso91jz3O/P7E3qa+g758nmG+cx6Afqkey973bzn/ca/MMAeQUVCnQOcRLrFccY6hpCHMEcYRwgGwcZIhaFEkwOlAmBBDv/6fm19MjvS+ti5y3kx+FH4LvfKeCS4e7jLec36/HvNvXg+sEArwZ6DPQR8RZJG9gefyEoI8MjSCO3IRsfhBsMF9QRAgzDBUj/wPhf8lns3OYW4i3eQ9tx2cfYTtkF2+HdzuGy5mfsw/KV+aoAywfADlIVThuCIMQk8SfuKagqFio6KCAl3SCQG2AVew4WB2r/svcp8AvpkuLw3FTY5NS90vPRj9KO1OXXe9ww4troRvA7+HwAywjmEI0YhB+TJYgqPC6OMGkxxTCjLhErKSYNIOwY+xB3CKL/v/YT7uPlcN7116bSsM4zzEXL8cs0zv/RONe43U7lwu3T9joAsAnrEqIbkSN4Kh8wWTQCNwI4TzftNOkwYiuAJHYcgRPmCe//6PUf7OLiedoo0yjNq8jWxcPEe8X8xzbMCdJM2cfhO+te9eT/eQrOFI8ecSctL4Q1RDpFPWw+sD0RO6M2hTDkKPofChZgC08ALfVP6grgsdaMzt7H28Kuv3G+Mr/swY3G9Mzx1Ejesujf83r/JguMFlEhISuuM7M6+D9SQ6NE4EMMQTk8izU1LXMjkhjkDMMAjvSi6F7dGdMmysvCRL2+uVa4G7kJvAvB/cer0NXaK+ZY8v3+twsmGOgjny74N6c/cEUjSaFK3EnWRqZBcjpuMeAmFxtvDkgBC/Qa597atc/5xfW967cMtHeyPLNYtrS7KcN/zHDXqOPJ8G7+LQybGVAm6DEIPF5EqUq1TmFQnU9tTOZGMz+MNTwqlx0AEN8Bo/O45Y3Yh8wHwl+51LKbrtismq3esIy2fL5wyB7ULOE279D9hwzqGooo+zTaP9NInU8CVN5VH1XJUfRLy0OLOYMtDiCVEYUCV/N85GvWkclUvgy1A65yqX6nOqigq5qx+rmCxOLQut6g7SL9xgwTHJQq1DdtQwNNSlQHWRNbXVrnVspQNUhnPbMweiIrEzoDJfNm43rU1cbiugCxfKmUpG+iH6OjpuCsqbW6wL/NVdwK7Gf86gwWHWwsczq+RutQq1i+XfxfUl/CW2VVbUwbQcgz2CTAFPsDDfN34rvSVMS0tz2tQqUEoK2dUJ7soWWojLEbvbnK/9l26qD79gzzHRIu1jzKSYhUvFwlYpZk+mNVYMBZblCkRL42JSdSFsgEDvOt4S7REMLLtMapWaHHmz2Z0Jl+nSukp62oudTHvNfm6M766AypHoYv+z6PTNhXfGA3ZttoUmidZNddNVT/R5I5XinfF54FJ/MK4dPPCsApsp6mxJ3glyOVopVdmTig/qlnthHFjtVd5/T5www6H8cw4kAMT9ha52PyaclsVGyVaKdhvlcnS0E8gCtlGXwGWPOM4KzOQ77Rr8ejhJpSlGKRzJGOlY6clqZZs3bCeNPc5RP5iAylH9UxiUJAUYZd+2ZTbV1w/m86bCplBVsZTsg+iS3hGmAHnvMz4LfNu7zCrUKhnZcfkf2NT44UkjKZcaODsATAfdFm5C34NwzsH7Ay8UMpU+FftWlXcJJzTXOIb19oCF7SUCRBdi9QHEgI+PP+3/bMc7v+qxGfEZVLjveKL4vyjiaWkqDorb+9n8/94kP30wsPIFgzGUXHVOdhE2z7cmh2PXZ8ckFrwmBPU1FDRDGxHTIJZvTt32fMa7qHqjad4JLXi1OIb4gsjG6T/p2Kq6q74s2k4Vj2XAsPIM4zAUYYVphjFW4+ddp4zXgUdc5tMGONVU5F8DIBHx0K5fT+3wnMo7lcqbGbDZHFiRKGEYbDiQ2Rtpttqce5R8xd4G711QrtHxM0qUYeV/JkuW8ed+h6+HpNdwNwUWWJVxdHeDQ/IAYLdfUw4N3LG7l9qIKamY8XiDeEGIS6hwSPvZmSpxm40soq34b0PgqsHyc0EUfWV/Rl/XCaeJB8v3wled5xIWdBWalI2zVnIewLEvaB4OHL07jqp6uZhI7OhsOChIIUhleNFpj+paK2g8kO3qPzmglLHws0OkdDWKBm4nGxedB9H36aelxznmiyWgNKFDd3IswMvPbx4BTMyLijpyuZz43phbeBWIHShAiMw5axpGW1X8gK3cby6gjMHsEzJkdkWPVmZ3Jjeqh+Fn+qe310xmnaWyNLIzhvI6UNcfd94XXM+7iopwGZeo1rhROBlYD0gxeLxpWuo2S0Zscg3PLxMQgyHkoz1UY6WPNmjXKuehd/pX9UfD11mGq3XAZMBjlKJHUOL/gl4gLNa7n3py6ZhI1ThdmAO4B+g4aKH5X2oqCzmsZT2yjxbwd+HacySEbGV5tmU3KTehx/yn+XfJ51E2tJXatMujkJJTkP9Pjm4rrNFbqPqLGZ7Y2ghQmBS4Bug1eK0ZSMohuz/8Wk2mrwpwaxHNsxgUUKV+5lu3EUerh+hX90fJx1NGuMXQ9NPTqoJfAPvvm+45vO+LpvqYeatY5ShqGBxYDFg4mK3ZRvoteylMUV2rrv2wXOG+YwgUQGVu5kxXAveex91n7oezl1/GqCXTNNjzomJpgQjPqs5KLPE7yVqrGb2Y9oh6GCqIGEhB6LQpWiotSyW8Wo2RvvDQXWGswvS0O+VJxjc2/nd7d8v332enN0amonXRRNrTqCJi8RW/ut5c/QY70ArCudWJHiiAmE9IKqhRSMApYkoxSzV8Ve2Y3uPgTMGY0u4UEyU/phx209dhx7P3ydeUxzfWl9XLJMmDq6JrMRKfzA5h/S576srfSeMZO8iteFqIQ2h22NG5f2o5izh8U42RLucQOxGCwtREBlUQpgwmszdBx5WHred8NxNmiDWw1MTDrMJiQS9fzi55DTnMCZrwqhYZX2jAmIwoYniSaPj5gYpWC07sU52aztpwKIF6wreD5aT89dZ2nLcbl2DHi7ddlvlWY4WiNLyzm4Jn4SvP0R6R/Vf8LDsWuj5peMj56KQIl8iz+RXJqLpmy1isZh2V3t4gFTFg8qfzwSTUpbuWYHb/RzXHU1c5BtnGSeWPVJEzl8JsISfv5M6srWjsQntBKmvZp9kpKNIYwzjreTgpxNqLy2Xsex2SbtJQEUFVcoWjqSSoBYumPqa9FwS3JNcOpqSmK0VoJIIzgYJuwSN/+P647Yx8bDtv+o453FleOQYY9KkYyW/55eqlC4acgq2gjtcADNE4cmDjjbR3JVbWB3aFJt224Hbedno198VMxG/TaLJf0S5//Z7GnaJsmUuSysVaFimY+UAJO+lLyZ0aG9rCm6q8nM2gTtx/+AEqIknjXxRCVS1lyxZHppD2tlaYpkplz3UdJEnzXTJPMSigAo7lncqMuWvJivEKVQnZGY+JaOmEWd+KRor0O8JcuY2xztKP8wEakiCzPXQZxO+FicYE5l62ZpZdZgVlkmT5ZCCjTyI84SIgF571reSs7Hvz6zEKmLoeecR5u1nCShcKhesqC+1syO3FDtmP7fD6AgWTCRPtpK11Q8XNBgcmIYYc1ctlULTBlAPjLmIosSqwHK8GrgCtEiwxq3Ua0Qpo2h6Z8woValN6ydtT7BvM6v3aLtF/6ODokejC0iO+RGeFCUVwRcp11zXHNYyFGoSFw9PDCwISsSJAIa8ofi5NOkxiq7z7HZqn2m26T9pdepS7AjuRrE2dD73hHupv1ADWccpiqON71C3UuqUu9WkFiAV8tTj00ARWA6BS5QIKwRjAJm863k1dZJymi/hbbkr7WrGKoWq6WuqLTuvDTHKtNw4J/uR/33Cz0aqifYM2k+DEeATZZRL1NCUthODkkUQSg3myvGHg8R4QKs9Nvm2tkOztDDb7sqtS+xm694sLyzTLn6wIrKrtUP4kvv+/y0Cg0YnSQFMO05CUIeSPxLik2+TJ9JSUToPLYz/SgTHVMQIwPq9Q3p79zv0V/IicCouue2YLUethe5Mr5GxRjOZNjX4xbww/x6CdoVgSEYLE012TyGQihGpkf3RiNEQz9+OAwwLyY2G3gPUQMf90DrEeDn1RDNzsVZwNe8YrsDvLK+V8PNyd7RStvH5QHxofxKCKYTWh4VKI0wgTe+PB1Ah0H0QGo+ADrbMywsMSMzGX4OaQNJ+HTtPeP02d7ROcs3xvvCnMEjwonEt8iMztfVXt7e5wryk/wnB3QRKhsAJLErBTLLNuI5Mzu4Onc4hDQBLxkoByAIF2YNawNm+aTvb+YQ3sXWxdA9zE3JCch5yJbKTs6A0wLan+Eb6jLznfwRBkYP9hfdH8AmaiyzMHszrzRKNFAy1C70KdcjsRy5FC8MVgN1+s7xpek54sDbbdZm0sfPo87/ztbQFtSk2FreCuV97Hj0vfwKBSANwBSwG7whtiZ6Ku4sAS6uLfkr9Ci4JGkfMhlFEtoKKgN0+/Hz2+xp5szgLNys2GXWZNWw1ULXDNr23d7inOgC79z19fwTBAILixF9F6oc7SAnJEEmLifqJnkl6SJSH9IajRWvD2cJ5wJi/An2DvCe6uLl/eEL3x/dR9yG3NbdK+Bw44jnU+yo8V33RP0uA+8IWw5HE5AXFRu/HXofPSADINMeuBzFGRUWxRH5DNkHjAI+/RX4O/PT7v/q2+d85fLjRuN744zkbeYO6VfsLPBt9Pn4q/1cAuoGMgsTD3ESMxVHF54YMhkAGQ4YZhYXFDYR3A0lCi4GGQIG/hP6XvYF8x7wwO3569bqW+qK6l7rzuzL7kTxI/RQ97H6Kf6dAfUEFAjlClMNTA/FELQRFBLnETAR+A9MDjoM1gk0B2oEjwG6/gD8dvkv9zv1qPN+8sXxgPGs8UfyR/Ok9E72N/hO+oL8v/70ABADAwXABjkIZQk+CsAK6gq9Cj4KdAloCCQHtgUpBI0C7QBZ/9v9f/xP+1H6jfkF+bv4rvjc+EH51fmS+m/7Y/xl/Wv+bP9fAD4BAwKnAigDgwO5A8oDuQOJAz4D3wJwAvkBfwEHAZgANQDj/6P/d/9f/1z/av+H/7D/4f8TAEQAbwCQAKIAowCRAGoALwDi/4L/Fv+g/ib+rf08/dj8iPxR/Df8P/xs/L78Nf3R/Y7+Z/9VAFQBWQJdA1YEOgX/BZ8GEAdMB04HFAebBuYF9gTRA38CCQF6/9z9Pfyr+jT55PfJ9u71W/UZ9S31mfVc9nX32/iI+m/8gv6yAO8CJwVHBz0J+QpqDIINNw6ADlcOuw2tDDMLVgkjB6gE+AEo/0z8fPnO9lj0MPJp8BLvOu7q7Sfu8u5J8CTydvQv9z36if34AHIE2wcYCw0OoRDAElQUUBWpFVkVXxTBEocQwA2CCuIG+wLt/tX61PYK85bvlOwf6kvoKufI5irnUeg36s/sCPDL8/z3fPwnAd0FdQrNDsASLxb8GA8bVRzCHE4c+xrQGNsVMRLrDSoJEgTJ/nj5SfRk7/LqFufx457hMuC63z7gu+Er5Hvnlutd8Kz1XPtAAS0H8gxjElQXnRsZH60hQCPDIzEjiSHXHiwboxZdEYELOwW8/jX42/He62/muuHl3RHbV9nG2GfZN9sq3i7iJOfp7FDzK/pCAWIIUQ/YFcUb5yATJSgoCiqoKvspBCjQJHUgFBvTFOENdAbF/g73jO966BHig9z/16nUn9Ly0azSyNQ72OvctuJy6evw6fguAXsJjxEqGQ8gCCbkKnsurjBqMaYwZS61KrIlfh9KGEsQvQfk/gP2X+085dvdd9dE0mzOD8xEyxLMds5h0rfXUN775X7umfcEAXgKqxNUHC8k/SqIMKE0JzcEOC03pzSCMNwq3yO/G7oSFAkZ/xT1VOsm4tLZmtK5zF7IrsXAxJ/FRsijzJfS9tmI4g3sPPbFAFkLpBVWHyIowi/6NZU6cD1vPoo9xDowNvAvMSgvHywVdwpi/0H0bek53/bV7s1ix4XCgL9uvlm/PMIFx5DNrNUd35rp1PRyAB0MeRctIuUrUzQ1O1NAgkOnRLhDuEC8O+k0cSyVIp8X5Au//4vzqud43E3SeclDwuW8i7lRuEW5YLyNwabId9G82yjnYvMMAMUMKRnYJHUvrTg2QNRFWUmnSrFJfUYgQcI5mzDvJREaWg0tAPLyDebk2dfOPMVgvYO307NwsmiztLY/vN7DWs1p2Ljk6fGU/1ANsxpUJ9AyzDz5RBZL8E5oUHBPDUxXRnc+qjQ6KX0c1g6vAHXyl+SA15fLO8G+uGOyXa7QrMetQLEgtz2/Wcko1U/iavAK/74NFhygKfM1rUB6SRNQQ1TnVfFUZFFcSwRDmzhxLOIeVxBBARXyR+NM1ZHIer1ftImtL6l0p2ioB6w2sse6ecX80e/f5+5w/hEOUh28K904T0S2TchUTVkfWy1aflYrUGNHaTyRLz0h2xHjAdDxHuJJ08TF+rlHsPmoSqRhok+jDqeErYC2vsHozprdY+3H/UgOZx6lLYw7rUepUTJZCl4LYCJfVVu/VJFLEUCXMosjXxOSAqbxHeF50TTDvrZ5rLektZ+dnYCeWqIPqWyyKr7wy1Tb3+sS/WUOVR9cL/09xkpRVUxddmKnZMpj5V8TWYlPj0OANcgl4RRNA5bxQ+Dcz+HAyLP4qMagc5sqmQCa753bpJCuw7oYyR/ZX+pR/GgOGyDfMDBAmE2rWBRhjmbvaCFoKmQlXUlT30ZIOPQnYBYUBKDxkN9zzs6+G7HGpSidhpcNldOV0ZntoO+qi7dhxv/W5OiF+1IOuyAuMiRCIVC1W4ZkT2rgbCRsH2jvYMtW/knsOgkq1xfjBMHxBN8+zfq8t67louGZ85NJkfuRBJZHnY2nhrTQw/XUcOey+iUONCFJM9hDX1JtXqFntW12cM9vw2tvZAxa6ExqPQcsRxm6Bfrxnt49zGa7nqxXoPOWu5DijX6OjJLumW2kt7FowQTTBebY+eENhyExNEtFU1TQYGJqvXCvcx9zEG+gZwldmk+9P+otqxqXBknyXd5vyxO60KoenmCU4o3Zil2La4/mlpOhI68rvzDRp+T5+IgNtiHkNH5G+VXeYsdsZ3OHdhB2BHKAar5fEVLjQa8vAxx3B6zyQd7WygK5UKk7nCmSaYsxiJuIpYwwlAOfyqwcvXrPV+MY+BsNwCFkNW5HU1eWZM9urnX9eKF4m3QLbSliSlTZQ1QxSx1ZCCLzSd5wyjK4HaivmlCQU4nuhTyGPIrQkb6csao/u+bNF+I295wMpyGxNR5IYFj3ZXhwk3cOe8561XY/b0dkQ1adRdcygh47Carzct48yqK3N6d6mdeOoIcPhEGEM4jIj8ea2qiVuXbM6uBU9g0MbCHMNY5IH1n/ZsJxE3m5fJd8rXgZcRZm+FcsRzQ0pB8bCkH0vt45ylO3nqadmL2NU4aYgquCi4YcjiGZSKchuCvL0t929W4LESG2Nb1IkVmwZ6xyLnr8ffl9I3qYcpJnZ1mESGs1sSD3Cub0KN9nykO3U6YZmASNa4WJgX2BR4XLjM+X/KXmtgnK0d6d9MIKlyBwNa1ItlkJaDVz43rXfvN+NXu6c7toj1qiSXg2piHNC5j1sd/EynO3U6bsl6uM6YTjgLiAaITZi9CW+aTltRHJ6d3L8wsK/x/8NF9IkFkKaF1zMXtJf4R/4Xt8dI9pbVuFSlo3gSKbDFT2V+BPy9+3oKYWmLKMzoSmgFuA74NHiyiWQKQgtUbIHN0B80oJTB9bNNRHHlm1ZyZzGXtRf6t/J3zfdAtqAFwrSw84QCNgDRn3F+EGzIi4NqeWmBmNGYXTgGmA3YMVi9iV06OZtKjHa9xC8oIIfx6PMw1HY1gKZ5BynHrvfml/BnzgdC9qR1yTS5U44SMZDuX38OHnzGy5Fqhsmd+NyYVpgeCAMYREi+CVs6NRtDrH2tuQ8bQHmh2ZMg1GYFcKZptxuXklfr1+fnuAdPtpQFy6S+s4YyTEDrX44eLxzYi6PKmVmgKP3oZngsCB7YTUi0GW4aNKtP3GaNvs8OIGnxx8MdZEFla4ZEpwcnjzfKl9j3q/c21p6luhSw45xCRgD4j55uMhz9u7qaoQnIGQVojNgwmDD4bHjPyWXqSFtPPGGNtZ8A4GkBs5MGhDiFQUY51uyXZZeyx8OnmccoZoRltFS/84AiXqD1z6/uR10GK9WKzbnVuSMIqZhbqEl4cajhCYKqUCtRzH7NrX7zoFcBrTLsdBuFIiYZdsv3RbeUd6f3cYcUVnU1qnSrs4HCViEDD7J+bs0Ry/Sa70n4yUaozKh9GGhInOj32ZRabCtXrH5Npp72gEPxlNLfU/p1DjXjtqVnL4dv53YHU0b6tlEFnFSUM4EiXGEAD8XueC0wbBeLBYohOXAY9dikyJ1YvikUObr6fFtg3IAtsQ75kDARinK/Q9Wk5bXIpnkW81dFF13nLxbLljflehSJU34CQUEcz8o+g21R3D4rIEpe6Z85FRjSuMh45UlGGdaakLuNbIR9vN7tECtxbmKcg700uLWYdkc2wScUJy+29Qam9hnlU5R7E2iCRLEZH98ekF117FhrX2pxidPZWikGmPmpEil9afcKuUudXJs9uj7g8CZRULKHI5FEl4VjZh/miTbdVuumxUZ9BecFOORZc1CCRpEU7+SOvr2MfHX7grq4+g3JhNlASTCpVLmqCixK1huwvLSNyR7lcBCxQZJvY2IUYjU5pdNmW8aQxrHGn/Y9xb9VChQ0Y0XyNuEQH/pOzo2lXKa7uerk+kzZxQmPuW1JjNnb2lZLBvvXbMBd2a7qoArBITJFg0/UKST7dZHWGPZepmJWVSYJZYME5yQcAyjSJYEaj/BO733ATNpr5MslWoC6GnnEib9pykoSupTrO+vxjO7N2+7goASxH7IZkxqz/HS49VuVwQYXJi2WBRXABVIUsDPwMxkiEmEUEAZu8X39LPDcIztp2slKVNoeifbaHOpeisgbZNwu/P+9797nj/6Q/UH70uMDzHRyhRDVhDXKpdOVz+Vx1Ry0dUPBIvbSDYEMwAx/BE4bvSnMVMuiKxYqpAptikNaZIqvGw+rkaxfrRNeBa7/T+iQ6hHcgrjziVQ4ZMHlMsV5NYS1deU+9MMERoOe0sHx9tEEcBJvJ847zVT8mWvuG1cq95qxOqSasOr0S1t70kyDnUl+HU74L+LQ1lG7woyzQ1P6xH703RUTRTEVJzTnlIUkBBNpQqqR3kD7EBgPO85dHYI80Kw9S6vrT2sJavprAdtNy5tcFpy6vWIuNs8CH+1gsiGZ0l6DCsOqBChkg0TJBNkkxCSb9DNDzfMgooCRw9DwgC0/QB6PjbE9Gmx/i/Q7qwtlq1R7Zvube+8sXnzk7Z1eQi8dT9hwraFm8i6yz/NWU96EJdRq1H0EbPQ8Q+2TdGL08lQhp4DkwCHfZK6i3fHdVlzEjF+r+kvFu7KbwCv9DDasqb0iDcsOb28Zr9QQmSFDQf1ygwMQI4GD1PQI5B0UAePo05RTN4K2UiVBiVDXsCXveT7G3iOtlB0b7K4MXLwpXBRMLRxCTJGs+C1iHfsejo8nb9BghKEvAbsCRGLHoyHjcPOjs7mTozOB00ei54J08fQBaTDJQCkvjZ7rTlad041lbQ7sshyQLIlsjWyq/O/tOa2k3i2Or582f92QYGEKcYeyBFJ9Ms/TCkM7Y0LzQUMnkufSlIIw4cBxR0C5gCufka8f/opOFD2wrWINKgz5zOGM8O0WvUFNng3qLlI+0n9W/9uQXIDVsVOhwxIhMnvCoTLQguly3FK6UoUSTtHqQYqxE3CoUC0fpU80vs6eVf4Nbbb9hD1l7VxdVy11XaVd5R4x/pkO9y9o39qQSSCxAS8xcPHT0hXyRhJjQn1iZNJaYi+h5oGhUVLQ/eCFsC2PuF9ZTvMuqG5bXh194D3ULcl9z+3Wjgv+Po58DsHvLZ98L9qwNnCckOqRPjF1cb7R2UH0Eg8x+vHoEcfhm+FWMRjwxpBxoCzfyq99jye+616qDnUuXb40LjieOs5J7mTumj7IPwzPRc+Q/+vwJJB4kLYQ+yEmcVaxeyGDUZ9BjyFzsW3xPzEJAN0gnYBcIBsP3B+RP2wvLm75Tt2+vF6ljqlep36/Ps/O5+8WX0l/f6+nP+5gE6BVQIHQuBDXEP3hDBERYS3REbEdkPIw4KDKAJ+gYtBFIBf/7I+0P5AvcW9YvzavK78X/xtfFY8mHzxPR09mL4fPqx/O/+IgE7AysF4gZVCHsJTQrHCuoKtgowCmAJTwgHB5YFBwRqAssAOP+9/WT8N/s++n/5/Pi3+LD44/hL+eP5o/qD+3j8e/2B/oH/cwBQARICswIxA4kDvAPKA7YDgwM3A9YCZwLvAXUB/QCPAC0A3f+e/3T/Xv9c/2z/iv+0/+X/FwBIAHMAkgCjAKMAjwBmACkA2v96/wz/lv4b/qP9M/3Q/IL8Tfw2/EH8cfzG/EH94P2f/nr/agBpAW8CcwNqBEsFDgaqBhcHTgdMBwwHjgbUBd8EtwNhAugAV/+5/Rv8i/oW+cv3tPbf9VP1GPUz9ab1cfaQ9/34rvqa/LD+4gAfA1UFcgdlCRoLhQyVDUEOgQ5ODqkNkgwPCyoJ8AZwBL0B6/4P/EH5l/Yn9AbySPD77i7u6e0y7grvbPBR8qz0bveC+tH9QgG8BCMIWgtIDtMQ5xJvFF4VqRVLFUMUlxJREIANOAqRBqYClv5/+oH2vfJR71rs8eks6BvnyeY753PoaOoO7VPwIPRZ+N78jAFABtUKJQ8PE3EWLxkyG2ccwRw7HNUamRiUFdsRig3BCKIDWP4I+d3zAO+Z6szmt+N34R7gvN9U4ObhaeTM5/bryfAi9tj7vwGqB2oN0hK3F+8bWh/YIVUjwiMYI1ohkh7UGjkW5RD+CrEEMf6s91fxZOsD5l/hnt3h2j/ZyNiC2Wvbdt6P4pjnbO3f88D62wH4COEPXRY7HEkhYCVcKCQqpirdKcsnfiQMIJYaRRRHDdIFIP5r9vDu6ueR4RjcrNdx1IPS9NHL0gXVk9hc3T3jCuqR8Zj54AEqCjYSxBmYIHsmPiu4Ls0waDGEMCQuVyo4Je4epheZDwIHJv5H9avsl+RJ3fzW5NErzu/LRcs1zLvOxtI42OreqeY872D4zwFAC2oUBR3LJIEr7jDnNEo3AjgHN140FzBTKjwjBhvxEUEIQv5A9Inqa+Es2Q/STMwUyInFwcTGxZLIE80n06LaS+Ph7Bv3qAE5DHoWHCDRKFUwbDbkOpc9bz5hPXQ6uzVZL30nYh5NFI0JdP5W84zoad4+1VPN6cYywla/br6Dv5DCgMcuzmnW89+E6sn1bAEUDWUYByOmLPY0tDuqQK5DqESMQ2FAPDtENKwrtSGrFuQKuv6J8rPmlNuC0c7IvsGJvFy5ULhyubq8EsJSyUXSptwm6G30HAHSDSsaxiVIMF85wkA0RotJqUqCSR9GlkAQOcUv/SQIGUQME//a8QHl7Nj7zYLEz7wet5+zbrKYsxW3zryXxDfOZdnL5QnzuQByDskbVii1M409kUV/SydPbFA/T6lLw0W4PcUzNShhG6wNgP9J8XbjddaqynPAIbj2sSSuy6z5raaxuLcCwEbKNdZ0457xRAD1DkAdtSrpNn1BHUqFUH9U7FW+VPxQwEo5Qqc3XCu0HRkP/v/U8BPiLtSTx6O8trMTrfCobqecqHKs1rKXu3TGGdMm4S7wvv9cD5Ae4izjOSxFZE5CVY9ZJlv5WRBWh0+NRmg7bC79H4oQiwB88NjgGtK2xBW5k697qAakWaKEo36nLK5at8XCFNDi3rzuKP+mD7cf3S6hPJhIY1K0WVFeFGDtXuNaE1SxSgQ/ZDE7Iv0RKAFA8MXfOdAXwsy1uqsxpGyfk522ns6ivalQsz6/Ks2s3ErthP7UD7UgozAhP75LFVbWXcNismSUY29fYlihTnZCPzRqJG8T0wEf8Nrejc62v8qyL6g3oCSbHpk2mmaekKV9r+G7XsqF2tnr0/3oD4whNjJjQZxOelmmYeBm/WjrZ7FjblxYUrxF+zaHJt4UigIY8BjeFc2VvRCw8qSSnDKX/pQJlkuap6Hjq7O4tMdy2GzqF/3hDzoikzNkQzBRjVwgZaVq8Wzua6RnM2DSVdFIlDmQKEkWSwMs8H3d0su0u6GtCKJEmZqTN5ExkoCWBp6IqLe1LcV01gXpUfzCD8EiuzQkRXpTTl9CaBBuinCab0ZrrmMNWbNLBzyCKqwXFQRX8ArdxMoVun6rcZ9Oll2QzY2zjgqTsZpvpfCyzsKO1Kbng/uKDyEjrzWiRndVumEKax5xxXPqcpFu3GYFXF5OUj5bLAUZ5gSa8L3c7Mm4uKepMJ20k3+NwYqRi+qPq5eaomKwmcDD0lLmsPo8D1sjbTbeRydX0GN2bcxzoXbddYRxuWm2Xs9QcEAXLlMavAXy8JfcSMmctx6oRZt4kQGLFojOiCSN+JQNoA+ukr4W0Qvl2PnaDm8j9jbYSIpYj2WEbxh2GXlveBx0QmwdYQNTYEK1L5MblQZf8ZXc2cjDtuOmspmZj+eI0IVthruKmZLLnfururyIz9Pj/vhjDl4jTDeQSZ1Z9mYycQF4LnueelZ2dW45Y/hUH0QyMcMccAff8bfcncgttvald5gajjCH74NwhLKIk5DXmyeqFbsdzqziI/jaDSsjbjcGSmNaBWiBcoV523xofC94T3AGZapWqkWLMuAdSghw8vzclMjXtVillZf8jN+FdILZggmH5o4ympeopLnWzJnhSvdBDdUiXjc7Stpaumhvc6R6In7MfaZ5znGCZhhYAEe/M+keIQkR82LdvcjDtQelDJc/jPOEYoGpgcSFlY3fmEynari3y5vgdPaZDGAiHTcwSgRbF2n8c1x7/37Ifrl68HKrZz9ZHUjKNNwf9Qm/8+fdFsnutQSl25bii26EuoDhgOOEoozgl0imarfAyrTfpPXlC8shrDblSeFaHGkodK57c39cf2d7tXN/aB5aAEmsNbYgwQp69IrenslYtk2lA5fni1CEeoCCgGiEDYw3l46lpLb0yefe2/QlCxkhDDZcSXJayWjzc5h7fn+Gf7B7GXT9aLNaqEliNnYhhgs/9UrfVMoAt+KlgZdLjJmEpICNgFKE2Ivklh+lG7ZUyTXeG/RcCkwgQDWWSLhZIGhecx17H39Gf5J7HnQlafxaEkrqNhkiQQwL9iTgNsvjt8GmVZgQjUeFOIEBgaSEBIzplvyk0LXjyKDdZ/OMCWUfSTSWR7RYIWdrcjx6V36efg17wXP0aPlaPUpDN54i7wzf9hfhQcwAueinfpkyjlqGNILegVyFkYxGlyalxbWiyCvdv/K2CGceKjNcRmlXzmUacfd4J32MfSF6BHNraKhaKUpsNwQjkA229yDidc1Wulap+pqxj9GHmIMlg3uGf437l52l+rWSyNXcJvLdB1Qd4zHrRNlVKWRtb053kHsRfNB45nGJZwpa00ljN0kjIQ6Q+D3jzs7huwirx5yLkaqJYoXShP+Hzo4KmWOmcLa0yKLcnfECBy0ceDBGQwVUNWJnbUV1k3kwehl3Z3BOZh1ZPUknN2sjoQ5r+W3kS9Cgvf2s456+k+SLkYfnhuiJfJBxmnanKLcKyZHcJvEoBvUa6i5uQfFR818Ia9xyMnfqd/90iG67ZOJXZEi4NmkjDg9E+q3l6dGQvzGvSqFHlnyOI4pfiTSMipIwnNmoIriTyaXcxPBQBa4ZPS1nP55PZl1VaBZwb3Q/dYFyTGzQYllWSEcUNkMjZg8a+/vmpdOuwaKx+6MkmW+RFo07jOKO9pRGnomqXrlRyt/cdvB9BFoYcisyPRBNkVpPZfZsTXEzcqNvsmmPYIJU60U8NfYiqQ/r+1ToftX5w02086ZSnLqUZpB2j/CRvpeyoIas3LpFyz/dPvCvA/sWjCnTOklKeFf6YYBpz23JbmZsvGb4XV9STEQuNIMi1A+1/LfpcNdsxi+3LqrNn1yYEpQPk1uV4Jpzo9CunLxtzMbdH/DpApQVjidMOE1HHVRZXrVl92kCa85obmMOW/BPa0LrMugh6A92/SLredkFyUS6qK2So0+cFZgDlyCZWp6GpmSxnb7KzXTeGPAtAicUeyWiNR9Eg1BwWpphymXiZtxkyV/RVzZNSkBzMSYh4Q8t/pHsltvBy4q9X7Gep5GgbJxOmz2dKqLrqUK038Bdz0vfLPB8AbYSVCPWMsJAsExDVjJdSmFtYpRgz1tGVDRK6T3HLzsgwA/Y/gPuxd2czvzAT7Xtqx2lE6Hsn6+hTKadrWi3X8Mj0UngWvDYAEQRHiHsLzs9pkjUUYJYfFynXfpbhVdtUOtGSjvmLSgfhA91/3bvA+CU0ZjEc7l5sPCpB6bapHGmvqqcsdS6HcYe03DhpPBCANIP2h7nLIw5aUQqTY5TZFeSWBBX7VJKTF1DbTjSK+0dLA8CAOfwTOKk1FnIx71AtQSvQqsUqoGre6/jtYO+F8lL1cDiC/G8/2IOjBzLKbo1/j9ISFpOB1I1U9xRCk7fR40/VjWLKYoctw6AAFTyn+TL1zvMSMI9ule0wbCUr9mwgbRvunPCS8yq1zfkjvFH//cMNRqbJskxaTsyQ+tIaEySTWFM4kgxQ347BTIUJ/8aJg7tALzz+OYD2zvQ8MZqv+G5frZXtXW2zLk+v6HGuM862tXlLvLk/pML2hdaI7strjbuPUZDjkawR6RGd0NCPjI3fi5sJE0Zdw1GARz1VelL3lTUvMvExJ+/dLxYu1K8Vr9MxArLWtP53Jvn7PKU/jcKfBUNIJcp0jGAOHA9fUCSQapAzj0XOa0ywiqXIXQXqgyMAXP2s+ue4YPYp9BFyozFn8KRwWnCHMWUyavPL9fk34bpx/NY/uUIHxO1HF4l2SztMm43Ojo/O3c67De0M/Et1CaVHncVwAu+Ab/3D+765MTcrdXpz6LL+cj+x7bIGcsSz3/UNdv74pbrwPQx/qAHxBBXGRYhyCc6LUUxyzO7NBE01TEcLgQptyJpG1UTuQraAf74Z/Ba6BLhyNqp1dzRfM+YzjPPSNHC1IXZaN885srt1vUg/mgGbw72FcMcpCJtJ/sqNS0MLn0tjytUKOgjbx4WGBARlQngAS76ufK762rl9N+C2zXYI9Za1dzVpNeg2rfexeOj6R/wCPcl/kAFIQyUEmgYcR2KIZUkfiY4J8EmHyViIqEe/RmcFKkOVAjPAU/7AvUb78fpLOVu4abe6Nw+3KvcKN6m4BHkSegu7ZbyVvhB/igE3gk3DwoUNBiXGxoerB9EIOIfiR5JHDQZZxUAESMM+AaoAV78P/d28iXubOpn5yvlxeM/45njzuTR5o/p8ezb8Cv1wPl0/iIDpwfgC60P8hKYFY0XxRg3GeUY1BcPFqYTrxBDDX8JgQVqAVr9b/nI9YDyr+9p7b3rtepX6qLqkesZ7S3vuPGm9N33RPu+/i8CfgWSCFQLrw2UD/YQzhEXEtIRBRG4D/oN2QtpCb8G8QMVAUP+kPsQ+db28fRu81fysvF/8b/xa/J78+b0m/aO+Kv64fwe/1ABZgNSBQMHcAiPCVoKzQroCq0KIQpMCTUI6gZ1BeUDRwKpABj/n/1J/CH7LPpy+fT4tPiy+On4Vvny+bX6lvuN/JH9l/6W/4YAYQEgAr8COgOPA78DygOzA34DMAPNAl0C5QFqAfQAhgAmANf/mv9x/13/Xf9u/43/uP/p/xsATAB2AJQApACiAIwAYgAjANP/cf8D/4v+Ef6Z/Sr9yfx9/Er8NvxE/Hf8z/xN/e79sP6N/38AfwGFAogDfQRdBR0GtQYdB1AHSQcEB4EGwgXJBJwDQwLIADX/lv35+2r6+fix96D20PVK9Rb1OfWz9YX2q/ce+dX6xfze/hEBTwOEBZ4HjAk8C58MqA1LDoEORQ6WDXUM6gr+CL0GOASBAa7+0/sG+WD29vPd8Sfw5e4j7urtP+4i74/wf/Lj9Kz3xvoa/o0BBgVpCJsLgg4EEQ0TiRRrFagVOxUlFGwSGhA+De0JPwZQAj7+KPou9nDyDe8h7MXpDugM58vmTueV6JnqTu2f8Hf0t/hB/fEBpAY0C30PXROyFmIZVBt3HL4cJRyuGmAYSxWFESgNVggzA+b9l/hx853uQuqC5n/jUeEN4L/fbOAT4qnkHehX7DfxmfZV/D4CJwjiDUATGBhBHJgfAiJpI74j/SIpIUseehrOFWwQewooBKX9IvfT8OvqmOUG4Vrds9oq2czYn9mh28Pe8eIN6PDtbvRX+3MCjglwEOEWrxyrIasljig7KqIqvSmRJyokoR8XGrUTrAwvBXv9yfVV7lznE+Gv21vXO9Rp0vjR7dJE1e3Yz93G46XqOPJH+pEC2QrdEl4aICHsJpUr8i7oMGQxYDDgLfYpvSRcHgEX5g5HBmj9jPT56/LjuNyD1ofR7M3Ry0rLXMwDzy3Tu9iF31nn+u8n+ZkCBwwoFbMdZiUCLFExKjVqN/433zYSNKovyCmXIkwaJxFuB2z9bfPA6bHgiNiG0ePLzcdnxcXE8cXiyIbNutNQ2xDktu3694oCGA1PF98gfinmMNw2Lzu8PWs+NT0gOkI1vy7GJpMdbROiCIX9a/Ks55vdiNS7zHPG4sEvv3K+sb/owv7H0M4p18zgbuu/9mYCCg5QGeAjZS2WNTA8/kDXQ6VEXEMGQLg6mzPjKtMgthXjCbT9iPG+5bHautAnyDzBMbwwuVO4o7kYvZvCAcoV05HdJul59SwC3g4rG7ImGTEOOklBkUa5SaZKUEm9RQhAWjjtLggk/xctC/j9w/D34/bXIc3Mw0G8vrZus3CyzLN6t2C9VMUYz2Pa3uYq9N8BlA/eHFUplzRLPiRG40taT2pQCk9CSyxF9jzdMi8nRBqADE/+HPBX4mzVv8muv4e3jbHvrcysL64RslS4y8A1y0TXm+TT8n4BLBBpHscr3DdJQrxK8lC3VO1Vh1SOUB9KakGxNkQqhBzaDbn+k+/h4BPTmMbQuxGzoqy1qG2n1KjirHqza7xxxzjUX+J38QwBphDLHwYu5joGRg9PuFXLWShbwFmeVd5OtEVkOkUtvB45DzT/KO+T3+7QrMM1uOOuAqjHo1aivaPzp9iuObjQw0PRLOAX8IgAAxEFIREwsz1/SRhTMlqTXhhgs15sWmNTzUnzPS4w6SCaEL//2u5u3v3O/cDftACrr6Mnn46d8J5Ho3GqObRVwGfOBd617vb/QhEUIugxQkCyTNVWXF4KY7hkWWP1XqtXtE1aQfwyCSP8EVgAqO5z3UDNjr7QsWqnrp/bmhaZcZrjnkmmbrADvajL7dtU7Vb/ZhH7IoozkUKcT0NaM2IsZwVpsGczY7FbYlGVRKs1GCVcE/8Aku6h3LrLX7wLrySkAZzklvSURJbKmmai3azfuQrJ59n166n+bxG4I/U0n0Q8UmBdtWX2avxss2skZ3Ff1VShRzk4FSe4FLIBl+7422nKcrqQrDChrJhGkyuRbZICl8qeiKnsto7G9deb6vH9XRFNJCs2bEaQVCpg3mhmbpdwXm/DauhiClh6SqI6+ygPFm8Cte5420/Jx7hiqpGesJUFkL6N7o6Nk3mbdaYttDjEGtZJ6S/9MxG5JCo39UeXVp9irGt5cdVzr3INbhJm/FoeTeM8yipdFzQD7O4g22vIX7eCqEecD5Mija+Ky4tvkHaYpaOmsQzCWdT/52f88BD+JPM3O0lRWL1kHm4rdLR2o3X/cO1oqF2IT/o+fiyiGAAEOu/u2r3HO7bwplWazJCgigKICImqjcWVHaFZrwvAs9LB5pj7lxAcJYY4Pkq7WYNmMnB8di95NniWc3RrDGC3UeRAFC7ZGdAEnu/k2kXHWbWtpbuY6I6BiLmFpYZBi2mT3p5IrTm+LdGQ5cb6KRAUJeQ4/krWWvBn5nFpeEZ7Z3rQdaVtJWKoU55Ciy8CG6QFFvD+2gHHu7S6pHqXZI3GhtSDp4Q3iWOR7Jx4q5i8x89w5PL5pw/oJA05e0uiWwRpOXPxefd8M3yqd39v8GNXVSVE3zAaHHgGoPA82/LGX7QWpJOWQYxxhVeCDYOOh7aPSJvqqSq7hM5h4x75FA+YJAM5tksfXL9pLHQTe0B+mX0ief5wa2XEVnhFDzIfHUsHPPGd2xXHRrTAowWWgIuChEOB24FHhmWO9pmgqPO5Z81m4kz4cA4mJMY4r0tNXCBqvHTPeyB/l343eiFylGbqV5RGGTMQHhsI5/Ef3GvHbbS5o9GVIIv6g5eAEYFkhXCN9pidp/O4ccyB4X73vg2VI1g4Z0stXChq63QjfJd/LX/neudyamfKWHhH+jPpHucIoPLA3PHH1bQApPWVIYvZg1WAr4DnhNqMS5jipiy4pcu04Lb2/wzkIro34ErAW9hpuXQRfKV/Wn8ye05z6mdgWSFIsTSpH6wJZfN/3abIe7WTpHGWhIsfhHyAt4DPhKOM9pdwpqG3BMsB4PX1NQwXIu82G0oHWzBpJ3SYe0h/HX8Xe1VzFGitWY1IPDVPIGgKM/Ra3ojJXrZxpUWXRozLhA2BKYEdhcuM95dKplO3kMpp3z71YwsvIfc1GkkEWjFoNXO5eoN+d36Vevxy52etWb1ImTXYIBoLCfVP35XKfLeZpm6YaI3dhQeCBILShVSNUJhvpkO3Ssrv3pL0igouINU030e4WN9m5HF1eVV9aH2teUNyY2diWa1IxzVCIb8L5fVc4MzL1LgIqOqZ545Th2mDR4Pthj6OAZnhpnK3NMqU3vPzrAkWH4oza0YmVzllOHDNd7978XtgeClxhmbJWF5IxDWOIVYMxfZ+4SnNY7q9qbmbwZAriTKF8oRtiIiPCZqgp+K3T8pZ3mTzygjpHRoywURPVUJjMG7EdcR5EnqtdrBvUWXjV85HkDW3Id4Mp/e14qzOJ7y2q9ed9ZJli1+HA4dSijGRaputqJK4nMpA3uXy6AepHIYw5EI2U/1g0Gtbc2V3z3eXdNdtxWOwVv5GKjW/IVQNifj941HQHb7vrUKggJX8jfCJeYmZjDmTIp0HqoK5HMtK3njyBwdZG9Au1UDdUG1eGmmVcKN0J3UecqBr4mEwVe1FkTSjIbcNaflV5RbSQ8BmsPeiYJjwkOGMUYxDj56VMJ+tq7W6z8t53h/yKAb7GfwsmD5JTpNbEmZ0bYJxHnJFbw1pqV9iU5pEwzNiIQYORvq55vnTlsIYs/SlkZs9lDGQio9Lkl+Yk6GhrSi8t8zM3tvxTgWQGAsrMDx6S3NYuWL8aQVut24NbB9mG11JUQZDwjL8ID8OHfsp6PfVFMUCtjWpEZ/hl9yTIJOxlXqbS6Tfr9y90s1F367xewQcFwEpnzl1SBFVE18vZi1q82p6aNhiOlrlTjJBjTFwIGAO7Pug6QzYuMchubes26LWm9+XEZdymeyeVadostC/Ic/l35jxrwOhFeEm6DY9RXBRJVsRYgBm1maNZDpfCFc4TB8/JDC9H2oOs/wf6zjagMpxvHew7aYboDacWZuKnbSir6o6tQPCpNCr4Jvx7gIhFKwkEDTWQZRN8VamXYBhY2JLYElbh1NCScw8hy7jHloObv2h7HXcac3vv2+0QaurpN6g9Z/2oc6mV65TuHTEW9KZ4bjxOQKdEmYiGDFCPoBJfFLyWLFcn122WwdXuU8GRjw6tyziHTAOHf4l7sPeb9CXw5241a+CqdOl4aSzpjirSrKxuyPHRNSu4u/xkAEZEREgBC6HOjlFyk35U5hXjFjRVndSoUuGQm83tCq5HOsNv/6p7x7hj9Nlx/y8pLScrg+rGaq9q+2vhrZTvw3KYNbq40Ly9gCWD7Ed2CqnNsNA4EjATjlSMFOjUZ1NQkfFPmk0gChpG4sNUf8q8YPjxtZWy4nBqbnzs5CwmK8Qseq0B7s0wzDNrNhN5bDybAAXDkgblyemMiI8wUNMSZhMkE0tTH1IoELEOikxHCbzGQ4N0/+m8u/lEdplzz7G4L6DuU+2WbWntiy6yr9Tx4vQKNvX5jvz9P+eDNgYRCSJLlo3cz6gQ7tGr0d1RhtDvT2HNrMtiCNWGHUMQQAc9GHoa92P0xfLRMRIv0i8Wbt+vK2/y8StyxvU092H6OPzjv8sC2YW4yBUKnAy+zjEPadAkkGAQHs9njgSMgoqxyCTFr8LngCJ9dTq0eDP1xDQ0Mk8xXbCkcGQwmvFBso+0N7XquBc6qf0O//ECfMTeB0KJmktXTO6N2E6QDtSOqI3RzNmLS4m2h2sFOwK5wDs9kbtQeQh3CTVfs9Zy9PI/MfZyF/LeM8D1dHbrONV7Ij1/P5nCIIRBRqwIUkony2KMe4zvDTxM5QxvC2JKCUixBqhEv0JHAFD+LXvtueC4E7aS9Wb0VrPls5Sz4XRHNX42fHf1uZx7oX20v4XBxUPjhZKHRUjxSc4K1QtDi5hLVcrASh9I+8dhhd0EPIIOwGM+R/yLevs5IvfMNv81wXWWNX21djX7doZ3zvkKOqv8J73vv7VBbAMFxPcGNId1iHJJJkmOiepJu8kGyJGHpEZIhQlDssHRAHF+n/0o+5d6dTkKeF33s/cPdzA3FPe5+Bj5Kzone0O89P4wP6kBFQKow9qFIUY1RtFHsIfRiDOH2IeDxzqGA4VnBC3C4gGNwHu+9b2FfLP7SXqMOcF5bLjPuOr4/HkBOfR6UDtM/GL9SP62f6EAwQINQz4DzETyRWvF9YYOBnWGLUX4RVsE2oQ9gwsCSsFEwEF/R75fvVA8nnvP+2h66fqV+qw6qzrQO1f7/Px6PQl+I77CP93AsMF0QiKC9wNtw8OEdkRFhLGEe4Qlw/QDagLMgmEBrQD2AAI/lj73fiq9s30U/NF8qnxgPHJ8X7ylvMH9cP2ufjZ+hH9Tv9+AZEDeAUlB4sIpAlnCtMK5wqlChIKNwkcCMwGVQXDAyQChgD3/oH9L/wK+xr6Zfns+LL4tPjw+GH5AfrG+qr7o/yn/az+q/+ZAHIBLwLLAkIDlAPBA8kDrwN4AygDxAJTAtoBYAHqAH4AHgDR/5b/b/9d/17/cP+R/7z/7f8fAFAAeQCWAKQAoQCJAF0AHQDL/2j/+f6B/gf+kP0h/cL8d/xH/Db8R/x9/Nj8Wf39/cL+of+UAJUBmwKdA5EEbgUrBr8GJAdSB0UH+wZzBq8FsQSBAyUCpwAT/3P91/tK+tz4mPeM9sL1Q/UW9UD1wvWb9sf3QPn9+vD8DP9BAX4DsgXJB7IJXAu5DLkNVA6ADjsOgg1YDMUK0QiKBgAERgFx/pb7zPgq9sbztPEI8NDuGe7s7UzuO++08K3yG/Xs9wv7Y/7XAU8FsAjdC7wONREyE6IUdhWlFSoVBxRAEuIP+wyiCe0F+gHn/dL52/Uk8sru6eua6fLnAOfO5mLnuejN6o/t7fDO9Bb5pP1VAgcHkwvUD6kT8haTGXQbhRy6HA4chBolGAEVLRHFDOsHwgJ0/Sf4B/M77uvpO+ZI4y3h/d/D34bgQeLr5HDoueyl8RH30vy8AqMIWA6tE3gYkBzVHyoieiO5I+Ei9SADHh4aYhXyD/cJngMZ/Zn2UfBz6i7lruAX3YfaFtnS2L/Z2dsT31bjg+h17v707fsLAyQK/hBkFyIdCiL0Jb4oUCqcKpspVCfUIzQflxklEw8MjATW/Cb1u+3O5pfgSNsM1wfUUtL/0RLThtVK2UTeUORA6+Dy9vpDA4gLgxP2GqYhXCfqKyovATFdMTkwmi2TKUAkxx1bFjIOiwWq/NHzR+tP4yncDNYs0bDNtstRy4XMTc+W00DZI+AK6Lrw7/ljA84M5RVhHv4lgCyyMWo1hzf3N7M2wzM7Lzsp8CGRGVwQmgaV/Jry+Oj53+fX/9B8y4nHSMXNxB7GNcn7zU/UANzW5Izu2fhtA/YNIhiiISkqdDFJN3c73T1kPgU9yTnHNCIuDCbDHIwStweX/ILxzebP3NTTJcwAxpbBDL95vuO/QsN/yHPP69em4VrstvdfA/8OORq2JCIuMzapPE5B/UOeRClDpz8yOvAyGSrvH8AU4Qiv/IjwyuTR2fTPgse9wN27CblauNi5er0nw7PK6NN/3ibqhvY9A+oPKRycJ+gxujrOQelG4kmgShlJWEV3P6E3ES4RI/MWFgrd/K3v7eID10rMGMO3u2G2QrN2sgS04rf3vRPG+89j2/PnTPUFA7UQ8R1SKnY1Bj+0RkRMiE9lUNFO1kqRRDA88jEmJiUZVAsf/fHuOuFl1NjI7L7ytiixvq3RrGqugLL0uJfBKMxW2MPlCfS5AmERkB/WLMw4EkNYS1tR6lToVUtUHFB7SZhAtzUrKVMbmgx0/VTusN/70aDFALtxsjWsgKhwpxGpVq0jtEO9csha1ZnjwPJaAu8RBSEnL+Y73Ua1TylWA1olW4NZJ1UxTtZEXDkcLHkd5g3c/dXtUN7Ez6TCWLc4ro2njaNZovyjbKiIrxy53sR00nfhcvHpAV4SUSJEMcI+Y0rJU6pa0F4XYHNe8FmvUuZI3jz2LpYfNg9V/nXtGt3Czee/9bNKqjOj6J6OnTCfxKMpqya1b8Gnz2DfIfBoAbASciMqM2BBok2QV9xeS2O5ZBljdV7wVsJMOUC2MaYhhxDe/jLtDtz2y2q92rCqpiqfl5oVmbKaZJ8Ip2SxKb71zFfd0O7YAOQSaCTbNL1DmFAIW7ticmcIaW9nsGLwWmhQakNYNKcj2BF2/w3tLdthyi67Ca5ao3abm5bxlIaWT5sqo9utD7tiyl7bgO05APwSNCVVNtdFQ1MvXkRmQmsAbXFrnmarXtRTbEbaNpclJxMZAAPtddoDyTS5hKtdoBmY+ZIlka6SiZeTn46qJbjyx3nZM+yQ//gS1iWXN7BHolUBYXRptm6fcB1vO2odYgFXPUk5OXIncRTJABTt6Nndx363TKm2nRaVs4+1jS+PFpRGnICnbrWmxanX7Orb/toSTyaiOERJs1d+Y0lszXHfc25yg21DZe5Z2UtyOzYptBWCAT7thNntxgu2Yqdkm3CSy4ykigyM+ZBHmbak7rKBw/HVreke/qMSnyZ2OZRKdVmkZcFuhHTAdmJ1dHAaaJVcPU6BPeEq7xZEAoLtSNk1xt20yKVrmSeQRYr0h0eJNY6ZljGiprCIwVTUeOhZ/VQSxyYSOqBL6FpxZ9pw2XY+efd3CnOfavZeZ1BkP3AsHhgLA9ztNNm0xfOzfaTKlz2OIoioheSGzYs+lPafm668v9TST+eP/O4RyCZ5OmhMClzlaJNyynhYeyl6RHXPbAxhVFIZQeEtQBnXA03uRtloxU6zg6ODlrSMY4bBg+SEw4k5kgaezqwfvnPRNObC+3MRoiapOuxM3Fz+aexzVnoMffd7HneobtViAFSdQjEvUxqlBNHuftlTxeyy2aKWlY2LCoVBgkmDGYiNkGScQqu1vDTQKuXz+uUQWCalOixNXl2+auJ0fHtYfl99mHgncE9ka1XtQ14wVBt0BWjv2tlxxc2yfqIElceKGIQqgRSC0YY7jxKb+ql/uxrPMuQl+kYQ6yVsOilNkV0ja3d1O3w7f19+rnlLcXllkVYIRWUxQhxCBhDwWNrDxfGydKLMlGSKjIN7gEiB7IVFjhKa9qh/uiXOT+NZ+ZYPXCUBOuVMdF0va6l1kny1f/d+YHoTck9mcVfrRUYyGh0MB8fw99pGxlWzt6LtlGKKaYM2gOSAbYWtjWWZOqi4uVnNguKR+NgOrSRmOWBMCl3hanp1gnzFfyd/rXp8ctJmCViVRv4y2x3RB4vxttv6xvqzSaNolcOKrINbgOmAUoVzjQ2ZxqcrubbMzuHP9w4O4COaOJxLUlw6aul0DHxrf+1+lXqGcv9mWFgFR4szgx6PCFvykdzdx920JqQ6loOLVoTqgFiBnYWZjQuZnKfauD/MNOEW9zoN9iKhN5tKT1s9afhzLnuofkl+F3oxctVmXVg4R+wzDx9ECTTzid3syP21TqVil6SMZoXhgTCCT4YejmCZvafGuPXLteBm9l0M8iF9Nl5JAlrqZ6ly7Hl8fT19Mnl8cVVmFlgtRx80fx/uCRT0md4lyle3v6bfmCKO24ZBg3CDZocDjwyaKqjvuNnLVODC9XoL1iAuNedHblhDZvxwRnjoe8l76XdncH5lg1flRiM00B+LCvr0wd+Iy+m4d6ivmv2Ps4gIhRiF4ohHkA6b4qhXue3LE+Ar9ZIKox+5MzlGk1ZKZPNuPXbvee55O3bzbk9kpFZdRvczAiAbC+P1/+AQzbK6c6rQnDKS7IozhyaHworrkWic6Kn/uTLM8d+k9KgJXB4eMlZEdlQCYpJs1HORd613KXQgbcpieVWVRZkzEyCaC872T+K8zq+8saw+n7+UhI3DiZiJBY3tkxmeOavnuqjM8d8t9L0IAx1hMEFCGFJuX9ppDnHRdAl1tXHvau9gAlSNRAozAiAIDLj3sOOK0Ny+Lq/4oaGXeJCzjG6MqY9Llh+g16wPvFDNFODJ89MHmhuDLvw/fU+PXM5m7G2xcQNy4W5jaL5ePlJFQ0kyzR9iDKD4H+V30jjB57H7pNaaxpMCkKOPrZIFmXqiwK53vSvOW+B48+0GJBqILIo9p0xqWXJjcmo0bp5urmt8ZTlcL1C9QVQxdB+oDIT5m+aA1L/D2bRCqFmea5eskzeTDpYZnCil9LAevznPxuA98wwGoxhyKu86mUkCVshfo2Zeat1qIGg8YmJZ1032Py0w9h7ZDGL6Ieii1m7GAbjLqymiY5uulyWXyZmEnyiocbMFwXrQV+EY8zIFGhdEKCw4WEZZUtVbgmIwZsNmOWSnXjpWNUvwPdIuUx7yDDj7runb2ELJXLuSr0Cmq58GnGqb251Eo3irNrYqw+7RDeIK82AEihUBJkc15UJ0TptXFF6wYVNi/F++WsNSTEisO0UtiR3zDAX8QOso2zjM5b6Ts5uqPqSuoASgQqJVpxWvQrmNxZTT6uIW85kD9hOrI0EyRj9XSiBTXVnhXJFdbFuEVgBPHkUrOYYrmhzbDMb81eyG3U3PmcLLtzavGamjpe2k+aa2q/2yk7wsyGzV7eM6894CYBJGIR4vfjsGRmZOYFTGV4JYjlb9UfRKrEFvNpUphBupDHv9a+7y333SdcY1vAy0N67hqiKq/qtjsC23JsAFy3bXFuV58zACyhDUHuIrkDeEQXRJIk9mUihTZVEsTaFG+T15M3MnSBpdDCH+APBp4sTVdMrNwBq5k7NjsJ+vS7FXtaK7+MMYzrDZZebT85IBNw9YHJAogTPXPExEqEnETIlN9EsVSAtCBzpLMCIl5hj1C7j+kfHp5CDZks6OxVq+Krkktl+13baQulnACMhh0Rjc2udJ9AMBqA3VGSslVS8DOPU+90PlRqpHQka8QjU92jXnLKIiXhdyCz3/HPNu543cy9J1ysfD9L4gvF27rrwIwE3FUszf1K/edOna9IYAIQxOF7ghDysMM3M5FD7OQI9BUkAlPSI4dDFPKfYfsRXTCrH/oPT26QbgHNd7z13J78RQwpTBu8K8xXzK09CP2HHhMuuH9RwAogrFFDketCb3LcozBDiFOj07KjpVN9gy2CyHJR4d4RMYChEAGvZ/7IrjgNue1BfPE8uxyP7H/siny+HPiNVv3F7kFe1Q9sb/LQk+ErIaSCLIKAEuzDEPNLs0zTNQMVotCyiQIR0a7RFBCV4AifcF7xTn89/X2e/UXdE7z5fOcs/E0XjVbdp84HPnGu8194T/xQe6DyYX0B2FIxsocitxLQ0uQy0cK6wnECNuHfUW1w9OCJYA6viF8aDqcOQj3+Daxtfq1VjVEtYP2Dzbft+y5K7qQPE1+Fb/awY9DZkTThkyHh8i+ySyJjknjya9JNMh6h0kGacToQ1AB7gAPfr+8yzu9Oh85OXgSd643D3c2NyB3ijht+QP6QzuhvNR+T//IAXKCg8QyRTTGBIcbh7XH0UguR85HtMbnhi1FDgQSwsXBsUAf/ts9rTxe+3e6fnm4OSf4z/jvuMW5TnnFeqP7Yzx6/WH+j3/5gNhCIoMQxBvE/kVzxflGDcZxRiVF7MVMRMkEKgM2AjUBLsAsPzO+DX1//FE7xftheua6ljqvurI62ntku8v8iv1bPjX+1L/vwIGBg4JwAsJDtkPJBHkERUSuRHWEHYPpQ12C/sISQZ3A5sAzf0h+6v4f/ap9DjzNPKh8YLx1PGR8rLzKvXr9uX4CPtB/X3/qwG8A54FRQemCLcJdArYCuQKnAoDCiEJAQiuBjQFoQMCAmQA1/5j/RT89PoJ+lj55fiw+Lf4+Pht+RD62Pq++7j8vP3C/r//rACDAT0C1gJLA5oDwwPIA6wDcgMgA7sCSQLQAVYB4QB1ABcAy/+S/23/XP9f/3L/lP/A//L/JABUAHwAmAClAJ8AhgBZABcAxP9g/+/+d/79/Yb9Gf27/HL8Rfw2/Er8g/zh/GX9Df7T/rT/qQCrAbECsgOkBH8FOQbKBioHUwdBB/IGZQacBZoEZQMGAoYA8P5R/bX7Kvq/+ID3efa09Tz1FvVH9dD1sfbk92P5JPsc/Tv/cQGuA+AF9AfYCX0L0gzKDVwOfw4wDm0NOwyfCqMIVgbHAwoBNP5a+5L49PWW843x6e+87hDu7u1b7lXv2fDd8lT1LPhR+6z+IQKZBfYIHQz1DmQRVxO6FIEVoRUZFecTExKpD7gMVgmbBaQBj/17+Yn12PGH7rLrcOnW5/Tm0+Z3597oAevR7TvxJvV1+Qf+ugJqB/ELKxD1EzEXwxmTG5IctBz2G1oa6he1FNQQYgx/B1ICAv24953y2u2W6fTlEuMK4e7fyt+h4HHiLuXE6BztFPKJ90/9OwMgCc4OGRTWGN4cECBQIoojsiPCIsAguR3BGfQUdw9zCRQDjvwQ9s/v/OnG5Fjg1txe2gXZ2tjg2RPcZN+84/vo++6P9YT8pAO5CowR5heUHWgiOybsKGMqkyp3KRUnfCPGHhUZkxJzC+kDMfyF9CLtQuYc4OLav9bV0z7SCNI508nVqdm73tzk3euJ86b79QM2DCgUjRsqIsknPCxgLxcxUzEPMFItLSnAIzIdsxV9Dc8E7PsX85fqruKb25jV1NB3zZ7LW8uxzJrPAtTI2cLgveh68bj6LgSUDaEWDR+VJv0sETKnNaE37TeFNnIzyS6rKEch0xiRD8YFv/vI8THoQ99H13zQGMtIxyzF18RPxovJdM7m1LLcneVj77n5TwTUDvUYYiLRKgAysze8O/o9WT7SPG85STSDLVEl8RuqEcsGqfuY8PDlBNwj05PLkMVNwe2+g74YwKDDA8ka0K/YguJH7a34WQT0DyIbiiXdLs42Hj2bQR9Ek0TyQkY/qDlCMkwpCR/IE98HqvuI79fj89gxz+DGQsCMu+W4ZbgRuuC9tsNpy73Ubt8p65P3TQT1ECcdhCizMmM7T0I+RwhKlUrfSO9E4j7lNjQtGCLnFf4IwvuX7ubhEdZ2y2jCMLsIthqzgLJAtE+4kb7WxuHQZdwK6W/2KwTVEQMfTStTNr0/QEehTLNPW1CTTmZK8kNmOwUxGyUFGCgK7vvG7R7gYdPzxy6+YLbHsJKt2qyprvOymLlnwh3Nadnt5kD18wOWErYg5C25OddD70u/URlV31ULVKZP00jDP7o0DiggGloLMPwV7YHe5NCrxDW61LHNq0+oeadSqc+t0LQfvnbJf9bV5Ar0qAM3Ez4iRjDiPK9HV1CVVjZaHVtAWatUgE31Q1I47yo1HJMMhPyE7A7dnc6gwX+2ka0dp1ejYKI/pOqoPrADuu/FqNPE4s/ySgO5E5sjczLOP0JLdVQeWwdfEGAvXnBZ9lH6R8c7ui1BHtEN7PwR7Mfbi8zUvg+zmKm7oq6elJ12n0ek5asWto3C6dC94I/x2gIcFM0kajR6Qo5OR1hXX4djtGTTYvBdMFbNSxY/bDBCIBIPZP2+66var8pJvOiv7qWrnliaGZn5muufy6deslK/Rc7D3k3wWgJhFNMlKTbkRJBRyFs9Y7NnBWkoZydiKVpqTztCAjM1IlQQ6/2I67rZDMkAugytlqLwmliW85TNltmb86PdrkO8vsvY3AzvywGIFK4msTcMR0ZU+F7NZodrAG0qaxJm313NUjNFeTUXJJURgf5w6/XYoMf6t3yqkJ+Ml7GSJZH2kheYYaCXq2K5WMn+2sztLwGSFF4nADnwSK9W02EEagBvoHDVbqxpTGH0VftHzTfnJdISJP9z61rYbcY4tjqo35yDlGaPs413j6aUGZ2QqLS2Fsc52ZHshwCBFOMnFzqPSspYWGTfbBty43MncvNsb2TbWJBK/TmhJwoU0v+S6+rXcsW7tEemhprWkXuMn4pTjIqRHZrLpTq0+sSL113r1f9VFD4o9jrpS5VahWZdb9d0xnYcdeNvQ2d+W+5MBDxDKTsViADL66TXsMSDs6SkhZiHj/CJ7YeOiceOcpdLo/ixCMP21TDqGv8PFHAonDv+TA9cWWh8cTB3R3mxd3hyxWnaXRJP4T3KKmIWRgEc7IfXJsSRslKj3paYjcmHnoUph1+MGZUTofKvQsF91A/pWP6yE3koCjzOTTld02k7cyV5ZHvkebJ09GvtX/tQkD80LH0XCwKF7JHX08PksVGikZUKjAaGtIMnhVWKFZMmnyiuqr8i0/vnkv0/E1soQjxYThJe82qYdLV6Gn20e412zG21YaVSEEF/LYoY0wID7cLXt8N8saGhoJTeiqqEMoKLg6qIaZGFnZ+sQ77n0fXmyPy2EhcoQzyeTplet2uTdd57aX4dfQd4S28uYw1UXkKpLocZnQOV7RnY0MNYsUKhCZQVirSDF4FUgmGHF5AznFirD73P0AHm/fsbEq4nDzygTtBeIWwrdqB8Tn8gfh55cHBXZDNVd0OvL3MaaAQ67pTYHsR4sTOhzZOuiSaDZoCFgXuGII8zm1SqELzczx/lNPtuESInqDtfTrZeL2xgdvt8y3+7ftN5OHEvZRNWW0SPMEobMAXv7jHZn8TasXSh65Oqif+CH4AfgfmFho6EmpepSLsPz1LkbPqxEHUmDjvcTU5e5Gszdu183X/tfiJ6pHGzZa1WBkVIMQsc9gWz7+7ZUsV+sgOiZJQIikCDQYAigdyFSo4qmiGpubprzp3jqvnmD6clQzoZTZhdP2uldXl8hn+1fg16sXHjZf9WeEXXMbUctQaE8MvaNMZgs+CiNZXHiuiDzYCOgSSGbI4lmvSoZbrxzQDj7vgQD7wkSTkXTJVcQmq1dJ57xX4VfpJ5X3G+ZQdXr0U8MkUdbQdf8cTbRceBtAmkXZbmi/aEwoFjgtKG7Y51mhCpTLqizX3iOvgwDrUjIjjYSkdb72hnc116nH0MfbF4rnBCZcZWqkV0MrodHAhE8tncgsjdtXul2pdkjWqGIIOgg+WHzo8cm3epcLqBzRfikfdHDZQi0DZfSbFZR2e6cbd4C3ybe2x3nm9wZDlWZ0V/MhIewAgv8wbe6clztzWnrJk/j0CI5IREhV2JDZEZnCqq0bqOzc7h8/ZZDFshVTWtR9NXTWWxb692E3rDecJ1MG5IY2FV50RaMkseVwkg9Erfd8tBuTWpz5t1kXmKDodPhzmLq5JsnSercbvKzaThY/ZnCw0gtDPERbJVAmNObUd0t3eGd7RzY2zKYT5UKEQGMmUe3wkT9aLgKs1Du3erQJ4ElBGNnIm/iXeNp5QVn3CsT7w2zprh4/VyCqse7zGoQ09TamCUaoBx+XTldEVxOWr2X89SKkOBMV8eVwoI9g3iAc94vfqt/qDplgaQi4yRjBaQ/5YToQWubb3UzrLhc/V+CTgdCDBcQa1Qh12GZ11u2nHicXZus2fOXRVR7UHLMDYevgr89ofj99Dcv7qwBqQgmlWT2I/DjxWTspllo+Ovyb6jz+zhFvWLCLcbAi7hPtBNXFomZOJqXm6Abklr02RSWxFPcUDjL+odEQvt9w/lC9NtwrWzU6eonfyWgpNTk3CWvpwKpgyyZcCj0EnizfSdByka4Ss7PLpK7VZ4YBFniGrDasFnnGGFWMRMtj7KLnodUAvZ+KLmOtUnxea246p7ofaahJc+lyWaIaAAqX60PsLW0cvimfS0BpEYpiltOW5HPVN/XO9iW2arZt9jDl5nVS9Kvjx+LecceQu++T7ogNcHyEq6sq6YpUCf25uBmzKe2KNFrDa3VcQ603Hje/TSBfIWVCd7NvFDUE9AWH5e22E+YqhfLVr7UVNHiDoBLC4ciwuc+uDp3NkLy969vLL5qdejg6AXoJOi4afXrzW6qcbQ1DzkdPT5BE0V7yRoM0dAKku+U8NZC11/XR5b/FVETjJEFzhSKlAbhgtv+4frStwuzp/B/baarrWoeaX+pESnOay0s3i9OMmX1i3lh/QsBKUTeSI2MHI8z0b+TsJU8FdyWEZWflFDSs5AazVzKE0aZws2/C/tx95t0YfFcrt4s9etuKoxqkOs3bDYt/zAAcyO2EPmsvRrA/0R9h/qLHY4QkIESoBPj1IbUyJRtkz8RSo9hjJkJiUZLwvx/NfuUeHF1JTJFcCOuDizO7Crr4qxyLVBvMDEAs+12n7n9/S3AlUQZx2HKVk0ij3URAFK60x+TbhLqUdyQUc5aS8mJNcX3Aqd/X3w4+My2MHN4sTWvdS4/rVptRa397rrwMDIOdIK3d7oV/UTArIO0BoRJh0wqTh0P0tEC0ehRwtGWUKpPCo1Fyy6IWUWbwo4/h7yfeax2wvS1clNw6S++7tlu+K8ZsDSxfvMpdWM32Lq0fWAARUNNRiLIscrpTPnOWE+8kCIQSFAzDykN9QwkygjH84U5wnD/rfzGuk932zW6c7tyKXELsKawerCEcb0ymzRQtk64grsZ/b+AH8LlxX4Hlwngi41NEo4pjo4O/45BTdmMkgs3SRgHBQTRAk8/0n1uOvV4uHaGtSyztDKkcgDyCfJ8stM0BDWD90R5dbtGPePAPMJ+RJdG94iRSlgLgwyLTS3NKczCjH1LIwn+iB1GTgRhQih/8/2Ve5z5mbfYtmV1CHRH8+bzpbPBtLW1eTaCOEQ6MPv5fc0AHIIXxC8F1Me8iNvKKorjC0KLiIt3ypUJ6Ei6xxiFjoPqwfy/0n47PAV6vbjvt6S2pLX0dVb1TDWR9iM2+TfK+U169HxzPjv/wAHyg0aFL8Zjx5nIislySY3J3QmiSSJIYwdtRgrExsNtgYtALT5ffO37Y3oJ+Sk4B3eo9w/3PHcsN5s4Q3ldOl97v/zz/m9/5wFPgt6ECYVIRlNHJUe6h9DIKIfDh6XG1EYWhTSD94KpgVTABD7BPZV8SftmenF5r3kj+NB49LjPOVv51nq4O3m8Uv26/qi/0gEvQjeDIwQrBMnFu0X9Bg1GbMYcxeDFfUS3g9ZDIQIfQRkAFv8fvjs9MDxEO/v7Gvrjupa6s/q5euS7cXvbPJu9bT4Ifyc/wcDSgZLCfULNA75DzkR7RETEqsRvRBTD3oNRAvDCA4GOgNeAJP96vp6+FT2h/Qe8yPymvGE8eDxpvLO8031E/cR+Tf7cP2t/9kB5gPEBWUHwAjKCX8K3AriCpIK8wkMCecHkAYTBX8D3wFCALf+Rv36+976+PlM+d74rvi6+AD5efkf+uv60vvO/NL91/7U/78AlAFLAuECUwOeA8UDxwOoA2wDGQOyAj8CxgFMAdcAbQAQAMb/jv9r/1z/YP91/5f/xP/2/ygAVwB/AJoApQCeAIMAVAARALz/V//l/m3+8/18/RD9tPxt/EL8NvxN/In86/xy/Rz+5f7I/74AwQHGAscDuASQBUcG1AYvB1QHPQfpBlcGiAWCBEoD5wFkAM7+Lv2T+wv6ovhn92X2p/U29Rf1T/Xg9cf2AfiG+Uz7SP1p/6AB3QMNBh4I/gmcC+oM2g1jDn0OJA5YDRwMeAp1CCIGjgPOAPf9HftY+L/1Z/Nl8cvvqO4I7vLtau5x7//wDfON9Wz4l/v1/msC4gU8CV0MLQ+TEXoT0RSKFZ0VBRXGE+URbw90DAkJSAVOATj9Jfk49Y7xRu5860fpvOfq5tnmjucF6TfrFO6K8X711Plr/h8DzAdODIAQQBRvF/EZsRudHK0c3BsuGqwXaRR6EP0LEwfiAZH8SPcz8nrtQumv5d/i6eDi39Lfv+Cj4nLlGumA7YXyAfjN/boDnAlED4QUNBkrHUogdSKYI6gjoiKJIG0dYhmGFPwO7giKAgL8h/VO74bpYOQE4JfcNtr22OTYBNpP3LffI+R06YPvIPYb/TwETgsZEmYYBB7EIn8mFyl0KogqUSnUJiIjVR6RGAES1QpFA4z74/OJ7Lflo99/2nXWptMs0hTSYtMQ1graNN9q5XvsM/RX/KYE4wzMFCMcrCI0KI0ski8rMUcx4y8HLcYoPyOaHAoVyAwSBC77XvLn6Q7iENsl1X7QQM2Jy2jL4Mzqz3DUUtpk4XDpO/KA+/gEWg5cF7cfKSd3LWwy4TW4N983UzYdM1QuGSicIBUYxA7xBOn69/Br54/eqtb6z7fKCscTxeXEg8bjye/OgNVm3WbmO/Ca+jEFsQ/GGSEjeCuIMho4/jsVPks+nDwSOccz4SyUJB4bxxDfBbv6sO8U5TvbdNICyyTFCMHQvpK+UMABxIvJw9B22WDjNu6k+VMF6BAIHF0mlC9lN5A95EE9RIVEt0LgPhs5kjF9KCIezxLcBqX6ie7l4hbYcc5Cxsq/P7vFuHO4TrpJvknEIcyV1V/gLOyh+F0F/xEjHmopfDMJPMxCj0cqSodKoEiCREo+JjZULB0h2RTlB6f6gu3g4CLVpcq7wa66tLX3so6ygLTAuC6/nMfJ0WndIuqS91AF9RITIEYsLDdxQMlH+UzYT01QUU7ySU9DmjoUMA4k4xb6CL76newE31/SEcdzvdK1a7Bqreis7a5qsz+6OcMVzn/aGOh49i4FyhPaIe8uojqYRIJMH1JDVdJVxlMsTyZI6T67M/Am6xgYCuv61+tT3dHPucNsuTyxaasjqIanmKlNroG1/r59yqXXEuZV9fYEfxR1I2Mx3D1+SPRQ/FZlWhBb+VgrVMtMEENEN8Ep7ho/Cy37M+vO23jNn8Cqte6ssqYno2yiiKRtqfew7boEx9/UE+Qs9KsEExXjJKAz1kAdTB1VjVs6XwVg5V3qWDlRCkesOn0s6hxrDIL7r+p22lbLxb0tsuyoSaJ6np+dwJ/PpKesC7euwy7SHOL98k0EiBUmJqc1kEN1T/hYzV++Y6pkiGJmXWtV00ruPSEv2x6cDen7SupJ2WvJLLv7rjilMZ4fmiKZRJt3oJOoXLN/wJfPMeDL8d0D3RU8J3U3CEaDUoNcumPuZ/1o22aZYV5ZZ04JQaoxwCDODmH8BepJ2LnH1bgTrNahb5oalvqUGpdpnMKk5K96vR3NU96Y8F0DExYmKAs5PEhEVbxfUWfGa/ls3WqBZQ1dw1H3QxU0lSIBEOj83ul210DGw7Z4qceeBZdvkiuRQ5OpmDWhpqyjusLKhtxm788CKxbkKGc6LEq4V6BijmpEb5twiG4YaXZg41S2Rl82WSQyEX791OnO1gHF9rQspw+c9ZMgj7eNxI87lfGdpan9t4rIzNo37jMCJhZ1KYk71kvcWS1lcG1kcuBz2XFdbJRjw1dDSYU4CSZfEiD+5+lS1vvDb7Mwpa6ZQpExjKGKoIwhkvma5qaKtXfGKNkN7YsBBRbbKXM8Ok2wW2Fn9G8jdcZ2z3RLb2VmYVqaS4Q6oieFE8z+FeoC1i7DLrKFo6aX7o6iieyH2olfj1GYaqRPs4zEm9fq69oAyhUXKiI9WE4yXTxpGHKAd0l5ZXfgceVouVy6TVo8ISmkFIL/Xerb1ZvCM7EroviV+ox3h5qFdYf4jPqVNqJNscvCKdbR6iAAdRUpKpk9ME9jXr1q3HN5eWh7mXkZdBJryV6eTwQ+hSq4FT4Avure1UHCf7AjoaaUZ4uwha6DcoXtiveTSqCHrzjB1NTC6WL/CRUSKtg9wU9CX+FrPnUNeyF9anv0delsj2BEUYA/zCvAFgABNusJ1h7CEbBuoK6TN4pQhCmC04NCiUySq54ArtS/ndPB6J3+hhTTKd89DFDOX6tsPXY6fHJ+1nxvd2huB2KrUstA8iy5F8YBw+ta1jLC6K8KoBOTaYlXgwyBm4L4h/mQWp26rKK+iNLQ59b97xNvKa89ElAJYBht2Hb/fFt/2n2IeI5vMWPQU+NB9i2iGI0CZOzR1nzCBLD3n9SS/4jFgliAyoEQhwGQWZy3q6S9ltHw5g/9RBPmKEs91U/0XyptEXdcfdp/d34/eVhwCWSxVMdC1i54GVUDGO1s1/vCY7A2oO+S+Iicgg6AYYGMhmWPqZv4qty8ydAk5kj8iBI6KLI8VE+NX+Fs53ZSfe9/rH6RecZwj2RMVXRDjy86GhoE2+0p2K3DBbHDoGWTU4nbgi6AYYFshiePTZuAqku8I9Bt5YX7vRFsJ+g7kk7YXj5sWnbffJt/d35+edZwwmShVehDITDmGtsEre4G2Y/E6LGfoTWUEYqAg7eAyoGxhkaPRJtQqvO7pc/N5Mb65RCAJu06j03WXUJrbHUGfNx+2n0GeYhwoGStVSNEiTB5G5YFi+8C2qLFCbPIol2VL4uNhKqBnIJch8OPkJtoqta7U89G5A/6ARB2JcQ5T0yHXO9pHnTHerV91HwpeNtvKmRxVSNExzDzG0oGdPAa2+LGaLQ8pNuWrIz/hQWD1oNriJ+QMpzJqvS7K8/a42D5FA9QJG4400rvWkZocnIjeSZ8ZnvodtBuXWPqVOdD2DBRHPQGZvFM3E3IAbb4pa6YiI7Vh8iEeIXeidmRKZ11q068Mc+K47v4Hw4RI+42HEkPWUpmaHAcdzF6kXlCdWdtPGIZVG5DuzCTHJIHXfKX3eHJ1Lf8p9Oav5ANivCGf4e2i3GTdZ5rrOa8Zc9Y4yP4JQ28IUc1L0fpVv1jBG6zdNd3V3c6c6BrxWD+UrdCcDC2HCQIWvP33pvL3LlDqkidT5OljHuJ64nvjWeVF6Csrbu9yM9E45n3JwxRIHozDEWBVGFhSGvscRp1unTQcHxp+V6YUcNB9S+6HKcIWPRr4HrNGLzLrAqgNpaaj2mMuoyJkLiXDaI3r86+WtBQ4x73KAvUHooxuELZUXleN2jJbv1xu3EGbv5m2VzoT5FASy+dHBkJWPXw4XrPhL6SrxajcJnqkrWP6Y+Ck2OaVqQLsR/AHdF+47T2KQpIHXovNED0Tklb1GRNa4JuXG7faiZkZ1rvTSE/cC5eHHoJVfaE45nRH8GUsmmm+5ySll6TdpPYlmid8aYps67BENLO4132LQmtG00thD3WS9RXImF7Z61qompcZ/Zgo1etS3M9ZC39G8cJUPcl5dTT5MPOtQCq06COml+XXZeHmsKg3amOtXrDNNNA5Br2NQgHGgUrqzqBSB1UJV1WY4BmjmaAY3BdkFQkSYk7KCx5GwAKRfjP5ijW0MY8udat9aTanrabnJuOnnGkF606uIPFidTW5Oz1QwdYGKUorDf6RChQ4FjiXgBiJGJPX5hZL1FVRmI5uirRGiMKM/mC6JPY4MncvOmxW6l0o16gMKDponKonrAsu8jHDtaQ5dT1WQajFjEmizREQflLWFQkWjFdaF3LWnBVg01CQwA3HSkFGi8KGPo66hDbEc2owDO2A65WqFSlFKWUp8Gsb7RgvkfKxNdu5tP1eQXpFKsjSzFiPZNHkU8gVRVYXlj5VftQjkntP2Q0TycVGSQK8/r0657dX9CdxLK66LJ8rZOqQ6qNrFuxh7jWwf/Mqdlx5+v1pQQuExUh7y1aOf1CkErZT7NSCVPbUD1MVEVYPJAxUyUAGAAKwfuw7TrgyNO4yGC/Brjhshewu6/OsT2247yKxe7PvduY6Bv23QNzEXQefCouNTk+WEVWSg9Nb013SzlH1kCEOIUuKCPHFsMJgvxp7+DiRtf0zDnEV72BuNu1drVUt2K7gMF7yRTT/t3j6WX2IwO7D8ob9CbjMEw57j+aRCxHlEfRRfNBGjx3NEYr0SBqFWwJNP0g8Y3l1tpN0TnJ18JXvtq7cLsavcjAW8amzW3Wa+BR68r2eQIIDhoZWyN9LDs0WTqrPhJBfUHtP288IjcxMNQnTh7qE/oI1f3Q8j/odt6+1VrOgchexA/Co8Ebw2nGb8sG0vfZBOPj7Ej34AFbDGcWth8BKAovnDSOOMQ6LzvPObI28jG2KzIkoRtHEm8IZf549PPqIeJE2pnTUM6QynXIC8hTyUDMutCa1rHdxeWX7uH3WgG4CrMTBhxyI78pvS5IMkg0sDR+M8EwjiwKJ2IgyxiCEMgH4/4W9qbt1OXb3u/YPtTo0AXPoc68z0rSNtZd25bhruht8JX45gAgCQIRURjVHl0kwSjgK6QtBC7/LJ8q+yYwImcczxWcDgcHTf+o91Xwiul941reRtpg17vVYdVR1oLY39tM4KXlvetk8mT5hgCUB1YOmhQvGuserSJZJd4mMidWJlMkPSEtHUUYrxKWDCsGov8t+f3yQu0n6NPjZODz3ZDcRNwM3eHeseFk5drp7+559E36OwAXBrML4xCCFW0Zhxy7HvsfPyCJH+IdWBsDGP8TbA9xCjUF4/+i+pz19vDV7Fbpkeab5IDjRePo42Plp+ef6jHuQfKs9k/7BQCqBBkJMg3UEOcTVBYLGAEZMhmfGFAXUhW3EpcPCgwvCCYEDQAG/C/4pfSC8d3uyexT64PqXerg6gPsvO3676nysvX8+Gz85v9OA40GiAkpDF8OGRBOEfYRDxKcEaQQMA9ODRELiwjTBf0CIgBY/bT6Sfgq9mX0BfMT8pTxiPHs8bvy6/Nw9Tz3Pvlm+6D93P8GAhAE6QWFB9kI3QmKCuAK3gqHCuIJ9QjMB3IG8gRcA7wBIQCX/ij94fvJ+uf5QfnY+K34vvgI+YX5L/r9+uf74/zo/e3+6P/SAKQBWQLsAloDowPGA8YDpANmAxEDqQI1ArwBQgHOAGQACQDA/4r/af9b/2H/d/+b/8j/+v8sAFsAgQCbAKUAnQCAAE8ACgC0/07/3P5j/un9c/0I/a38afxA/Df8UfyQ/PX8f/0s/vf+3P/TANYB3ALcA8sEoQVUBt0GNQdUBzkH3wZIBnUFagQuA8gBQwCr/gv9cvvr+Yb4UPdT9pv1MPUY9Vj18PXe9h/4qvl1+3T9mP/QAQ0EOwZICCMKuwsCDeoNaQ56DhcOQg39C1AKRgjtBVUDkgC6/eH6H/iK9TnzP/Gu75buAO727Xvuje8n8T/zx/Wt+N37Pv+2AisGgQmdDGQPwBGcE+YUkhWWFfEUpBO2ETQPLwy8CPUE9wDg/ND45vRD8QXuR+sg6aPn4ebg5qXnLelu61nu2vHX9TT6z/6DAy8IqwzVEIoUqxceGs0bpxykHMAbABpuFxsUIBCYC6cGcQEf/Nn2yvEa7e/oa+Ws4srg19/c397g1uK45XHp5u328nv4S/44BBcKuA/uFJAZdh2CIJcipCOdI38iUSAfHQIZFRR/DmgI/wF3+//0ze4S6frjsd9Z3BDa6djw2CnajdwM4I3k7+kL8LL2sv3UBOMLpRLlGHIeHiPCJkApgip7KigpkCbGIuMdDBhtETcKoQLn+kPz8ust5SzfHtos1nnTHNIi0o7TWNZt2q/f+eUa7d30B/1YBZANbxW3HCwjnCjaLMMvPDE4MbQvuSxcKLsiARxgFBIMVQNw+qXxOelw4YbatdQq0A3Nd8t3yxLNPNDh1N7aB+Im6v3ySvzCBR4PFRhgILsn7i3FMhg2zDfPNx82xjLdLYUn8B9VF/YNHAQS+ibwpubc3Q7We89Yys/G/sT2xLrGP8ptzxzWHN4x5xTxe/sTBo0QlRrdIxwsDjN+OD08LD45PmI8sjhDMz0s1CNJGuMP8gTN+cjuOeR12sfRdcq6xMbAuL6kvozAZsQVym/RPto/5CXvnPpMBtsR7hwuJ0ow+jf/PSpCV0RyRHlCeD6LON4wqyc4HdUR2AWh+Yvt9eE817PNpsVWv/W6qbiFuI66tr7fxNvMb9ZS4THtr/ltBggTHR9OKkM0rDxGQ9xHSEp0Sl5IEUSuPWQ1cSshIMoTzAaM+W7s29801NbJEsEuumO117KhssS0NLnPv2XItNJv3jvrtfh2BhMUIiE8LQM4IUFNSE5N+k86UAtOekmpQso5IS//IsEVzAeO+XTr7N1g0TLGvLxItROwRq37rDWv5bPruhDEEM+X20XpsPdoBv0U/CL3L4k7VkURTXtSaFW/VXxTrU52Rw0+uDLQJbUX1win+ZvqKNzAzsvCqLiosAqr/KeYp+Opz642tuG/hsvO2FHnofZFBsUVqSR8MtI+SUmOUV9Xjlr/WqxYplMSTChCMzaQKKYZ6gnV+ePpkdpWzKK/2LRQrEum/KJ9otak9am1sdu7G8gX1mPlifUMBmwWKibLNNtB9UzAVfdbZ1/0X5ddYFh3UBZGjTk8K5EbBQsY+k3pJ9kjyrm8ULFEqNuhSp6vnRCgXKVsrQS408R2033jbPS/BfIWfifhNqNEWVClWT5g8GOaZDdi11yiVNVJxDzSLXMdJQxu+tfo6tcqyBK6Ea6HpL2d7JkxmZabCKFgqV+0sMHt0KDhSvNgBVcXpCi+OChHclM5XTJkJGjuaIlmBmGOWGBN0z9OMEkfSA3W+oLo29Zpxq+3HqsbofSZ45UIlWyX/pyVpe+wtb5/ztHfJvLvBJwXnClhOmlJPlZ7YM9nAGzsbIpq6mQ3XLRQt0KtMhIhbQ5P+03o+dXjxJG1eagEnoSWM5I3kZaTQpkOormt6LsvzBDeAfFuBMMXZyrKO2RLvFhnYxNrgm+QcDRuf2ibX8xTbUXtNMoikQ/Y+zboRdWXw7izJKZDm26T4I7AjRiQ1pXPnr+qSrkAymHc3u/fA8oXBSv4PBlN6Vr8ZfptpXLXc4ZxwWu1YqZW8kcJN28kshBu/D3ovdSGwieyHqTbmLWQ7YupivSMvpLbmwWo37b2x8bav+5CA7UXdivsPYdOxlw4aIRwaXW/dnt0rm6CZT9ZQ0oBOf8lzxEQ/WDoYtSwwd2wa6LMlluOWonyhy2K/Y81mY6lqbQSxkLZpe2bAoQXuyulPq5PUF4aaq5yyndFeRJ3QnEAaJNbXEzQOnYn5RK9/Z/oMtQUwdqvCqEYlWGMK4eehceHl43gll2jrLJYxNfXk+zqATcX1iskP41QiF+ga3d0x3lme0h5enMraqBdPE51PNQo8hNy/vjoLdSywB6v+5+/k8qKYYWvg8OFjIvflHSh6rDJwofWi+sxAdIWxitqPyVRbWDKbN11XnsifRp7VnUBbGRf4E/tPRYq9RQu/2rpUdSJwKquQJ/DkpWJ/YMngiOE4Yk1k9efZq9pwVXVj+pyAFUWjSt3P3ZR/2CYbeB2jnx2fod80XaAbdtgRVE1Pzgr6hXw//LpntSYwHyu154kksSIAYMIgemClYjikYaeIa45wELUoemw/8EVLStMP4FRPmEKboB3V31hf4597HembgRiaVJMQDos0BazAJDqEdXewJSuwZ7gkVaIbIJRgBaCrIfpkIWdHq08v1LTw+jq/hoVpyrqPkZRK2Efbrx3t33jfy1+pHhyb95iSlMvQRotpRd5AUHrqtVawfGu/J75kUyIQIIEgKqBJYdLkNScX6xzvoTS9+ck/l8U/SlUPsdQyGDYbZR3r336f2R++Hjhb2Zj51PdQdQtaBg+AgXsZtYLwpGviJ9tkqWIfIIhgKiBA4cJkHWc5Kvgvd3RP+dg/ZQTLymKPQZQFGA3bQl3P32ofzJ+6Hj0b5xjP1RUQmguFRkBA9jsRNfuwnOwZKA7k2GJIIOogA6CRYclkGmcsKuFvV3RnOaf/LkSQSiOPARPEl88bB12aHztfph9dHiqb35jT1STQtQurBm/A7ntQtgCxJaxjaFjlH6KKoSZgd2C7IefkLGcxKtjvQXREebk+9IRNCdjO8JNwl3patB0KnvIfZV8m3cCbwxjF1SYQhcvKxp3BKbuXdlExfayAqPhlfuLm4XxghOE94h2kU2dIKx8vdjQn+Uw++AQCiYKOkJMKFw/aSNzh3k7fCp7Xnb7bUVillNiQi4vkBonBZ3vldq0xpO0wKS1l9aNb4eyhLGFZoqrkj6exazPvdfQSOWE+uUPxiSFOIhKRVpBZxlxgXdIell5vXSYbCphzVLxQRkv2RrOBZzw5ttNyGq2x6bcmQ6Qp4nYhraHOYw9lISftK1fvgLRDeXk+eMOaSPXNpVIHFjyZLRuGXXwdyN3uXLXarpfuVFDQdcuBRtoBqHxTt0Pyni4E6lUnJ+SPoxiiR6KbY4slh6h7K4rv1vR8ORP+dsN9iECNWxGrlVSYvdrUnI1dYl0VHC6aPZdXVBZQGcuFBv1Bqnyy972y7u6oasan4iVNI9NjOmMApF2mAujbbAzwOPR8eTJ+NEMbyAJMxBEAFNmX+NoL28Zco1xkG1DZt9bt04xP8gtAxt0B7TzW+AAzjC9bq4rosaYhZKYjxWQ9ZMam0ulN7J5wZnSEuVT+McL1x7vMIRBFFAxXH1lsmugbjJubmpyY3ZZyUzNPfos0RriB7/0++Eq0NS/eLGEpVScLpY/k56TRZcXnt2nSbT7wn/TVOXu970KLx22Lso+7ky2WMdh3mfMantq8WZLYLxWk0otPPwrfxo+CMf1qeNx0qPCu7QhqTCgK5o/l4KX75ppob6qo7a6xJXUt+Wc97YJextiLOY7kEn4VMZdt2OgZmtmHGPOXLRTFkhQOs8qChqGCMz2YuXS1JvFM7j/rFakep6Vm76b754Qpe6tQrm0xtrVPeZd97QIvRn0Kdo4/kX7UHxZQl8hYgVi8V7/WF5QVEU5OHIpcxm6CMr3JedL17nI3bsascOoFqM9oE6gRKMHqWmxJrzpyE/X5eY097kH+BdwJ6w1PULDTO5UgVpRXUxdc1rgVL5MT0LmNeUnuRjZCMH47ujZ2fjLtb9utXGt+6czpS6l6adNrS61TL9Yy/PYsecg98YGLBbaJF0yTz5USCBQeVU2WEVYp1V0UNVICD9bMyom3BfhCK/5uup43FXPt8P2uV2yJK1zqluq26zesTm5s8IAzsXaoOgk994FXhQzIvIuOjqzQxdLLlDTUvNSkFC/S6dEgjuYMEAk2xbRCJL6iewl383S38evvoK3jrL4r9CvFrK2tom9WMbe0Mbcs+lA9wIFkBKAH24rADbkPthFpkouTVxNM0vFRjdAvzefLSkithWpCGj7V+7e4VzWKcyTw9u8M7i9tYi1lbfRuxnCOcrx0/Pe6ep09zMEwxDCHNUnpjHrOWZA5kRKR4RHk0WJQYg7wTNyKuYfbxRoCC/8IvCf5P7ZkdCfyGTCDr69u3+7Vb0twebGU84310zhQuzC93ID+g7+GSokMS3ONMc68T4uQW9BtT8PPJ02iy8TJ3gdBRMNCOj86fFm57HdE9XOzRfIG8T0wbDBUMPExu3Lo9Kv2s/jve0p+MICNw02F3IgpCiQLwA1zjjeOiM7njlcNnsxIiuEI+AaeRGZB4/9qPMv6m/hqtka0/DNU8pbyBbIgsmRzCrRJtdU3nvmWu+r+CMCfAtsFK4cBCQ3KhcvgjJgNKY0UzN1MCUshybIHyAYyw8LByX+XfX47DblUd5/2OnTsdDuzqrO5M+R0pjW2Nsm4k7pGPFG+ZcBzAmlEeUYVh/HJBApEyy6Lfwt2SxeKp8mviHiGzoV/Q1iBqj+CPe+7wHpBuP43f3ZMden1WjVdNa+2DTctuAg5kbs9vL8+R4BKAjiDhgVnBpFH/EihSXxJisnNiYcJO8gzBzUFzESDwygBRf/pfh98s7sw+eA4ybgy91/3ErcKd0U3/jhvOVB6mHv8/TL+rkAkQYmDEwR3RW3Gb8c3x4KIDogbx+0HRkbtBeiEwUPAwrEBHL/NPo09ZnwhOwT6V/me+Ry40rjAOSM5eDn5eqE7pzyDve0+2kACwV0CYQNHBEhFIAWJxgMGS0ZihgsFyAVehJPD7sL2wfOA7f/svvg9130RPGr7qPsO+t56mLq8uoi7OftL/Dm8vb1RPm2/C8AlgPPBsQJXQyJDjgQYRH9EQsSjRGJEAsPIg3eClMIlwXAAub/Hv1++hn4APZD9O3yBPKP8Yzx+fHR8gj0lPVl92v5lfvQ/QoAMwI5BA4GpAfyCO4JlQrjCtoKfQrRCd8IsQdTBtEEOgOaAQAAd/4L/cj7tPrX+Tb50vis+ML4EPmS+T/6D/v7+/n8/v0C//3/5AC1AWcC9wJiA6cDxwPEA6ADYAMJA6ACKwKyATgBxQBcAAIAu/+H/2f/W/9i/3n/nv/M//7/MABeAIQAnQClAJsAfQBKAAQArP9E/9L+Wf7f/Wn9//ym/GT8Pvw4/FX8l/z//Iz9O/4J//D/6ADsAfIC8APeBLEFYgbnBjkHVAc0B9UGOAZhBVEEEQOpASIAif7p/FD7zPlr+Dj3QfaP9Sv1GvVh9QD29vY9+M75nvug/cf/AAI8BGgGcghICtoLGQ35DW8Odg4KDisN3QsoChcIuAUcA1YAff2l+ub3VvUL8xnxku+E7vrt/O2M7qrvT/Fx8wH27/gk/Ij/AAN0BsYJ2wybD+0RvRP7FJkVjxXcFIEThhH4DukLbgiiBKAAifx6+Jb0+vDF7RPr+eiM59nm6ea/51bppeue7iryMfaU+jP/6AORCAgNKRHTFOYXShrnG7AcmhyjG9EZLhfME8QPMgs6BgABrvtr9mLxvOyd6Cjle+Kt4M7f6N/+4AvjAObJ6UzuZ/P0+Mn+twSSCiwQVxXrGcAduCC4Iq4jkCNbIhYg0BygGKQTAQ7iB3QB6/p49E7unuiX42DfHtzs2d7Y/9hR2s3cYuD35GvqlPBF90r+bQV3DDATYxnfHnYjAydoKY4qayr9KEsmaCJvHYYX2BCYCf0BQvqj8lvrpeS23r7Z5tVP0w/SM9K906PW0tos4Inmuu2I9bj9CQY8DhEWSR2rIwMpJi3wL0oxJjGDL2ks8Cc2ImYbtRNaC5gCs/nt8Izo0+D/2UfU2c/bzGfListGzZHQVNVs26vi3OrA8xP9jAbjD84YBiFMKGMuGzNNNt03uzfnNWwyYy3vJkEfkxYoDUYDPPlW7+LlK9111f/O/MmXxuzECsX0xp7K7c+71tXe/efu8Vz89QZoEWQbmCS9LJIz3zh4PD8+JT4lPE84vDKWKxMjchn+DgYE4Pjh7WDjsNkc0evJVMSHwKO+ub7MwM7Eosoe0gnbIOUV8JX7RQfNEtId/Cf9MIs4az5sQm5EXUQ3Qgs+9zcoMNgmTRzaENUEnPiN7AfhZNb4zA7F5b6vupG4nLjSuia/eMWZzUzXR+I37r76fAcQFBYgMCsGNUs9vEMlSGJKXkoXSJ1DDz2fNIwqIh+6ErIFcfhb69jeSdMKyWzAs7kWtbuyt7INtay5dMAxyaLTd99V7Nr5mwcxFS8iMS7XOM5BzkieTRdQJFDBTf5I/0H3OCsu7iGcFJ0GXvhM6tXcYtBXxQm8w7S/ryetEa2Br2W0mrvpxA3Qsdxz6un4ogcvFhwk/TBtPBBGnE3SUolVqVUuUypOwkYtPbMxrSR+FpQHY/hf6f7asc3gwee3GLCvqtmnr6czqlWv77bHwJPM+dmS6O33kgcLF9wlkzPEPw9KI1K9V7Ja6FpbWB1TVEs7QR81XSddGJUIfviU6FXZNsunvgu0tqvppdWilKIopYGqd7LNvDbJUte15uj2bAfEF28n8jXcQshNX1ZcXI9f3l9DXdFXsU8fRWw4+ik3Gp0Jr/js59nX9Miwu3ewoKdzoSCexZ1koO2lNq4BufrFwNTf5Nz1MQdbGNMoGDiyRThRTVqqYBxkhWThYUNc01PTSJY7gSwJHK0K9Phm54zW68b8uC2t2qNOnb6ZRpnsm5+hMqpltePCRNIS48r04gbRGAkqAzpFSFxU612kZFRo2mgyZm5guVdVTJk+8C7RHcELTPkB527VHcWMti+qZqB/mbGVG5XEl5mdbab/sfS/489Q4bTzgQYlGRArtDuSSjNXNWFIaDRs2Wwxak5kXFugT3NBQzGMH9cMt/m95n7UicNitH+nRp0Ilv6RSJHvk9+Z7KLQrjC9n82c353yDgZZGegrKj2ZTLtZKWSSa7pvf3Dbbd9nul6xUiBEeDM4Ie8NMvqZ5r3TMcJ/siClfprskqeO0Y1xkHaWsp/dq5u6esv43YbxiwVtGZIsZD5YTvFbxmZ/buFyyHMscR9r0GGFVZ1GizXTIgUPvPqU5irTFcHjsBKjDpgtkK+Lt4pOjWCTwpwpqTe4eMln3HHw+gRjGQ8tYj/QT9ddCWkPcal1snYidApummQZWOdIezdZJBgQVPut5sTSNcCPr1ah+JXOjRiJ/oeHiqGQH5q3pgi2nMfs2mHvXAQ8GV4tJUD/UGlf8Wo+cw54Onm5dp1wFGdpWvtKQznJJSUR9/vj5ovSkL+Eru2fPZTPi+aGqIUgiDuOzZeJpBC06MWI2VfuswP4GIEtrEDmUadgfWwLdQ56XnvveNVyPmlyXNdM4johJysSpfw0537SJr/Crdme35IzihiFt4MahjGMzZWkolKyXsQ92FXtAQOaGHgt+UCFUpJhrW12dql7HH3DerF0E2s0XndOVjxdKCgTW/2f55zS975HrRie3pH6iLGDLIJ5hIWKI5QIodCwAcMP117sRwIiGEUtC0HbUipigG59d9x8cn4yfC12kmyqX9pPmz19KRkUGP4i6OTSAb8UraqdOpEliLGCCoE9gzmJ0JK4n42v1MH/1XPriAGTF+os5UDqUm1i9W4heKh9YH87fUl3uG3TYP1QsT58Kv0U2v696FPTQ78prZCd85CzhxqCUYBogk6I1pG2noqu18AQ1ZfqxQDuFmYsh0CzUl5iDm9geAt+5H/cfQN4hW6tYd9RlD9bK9EVnv9s6erTvb+DrcidCZGnh+uBAYD6gcWHNpEDnsmtDsBD1MvpAAA=\" type=\"audio/wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\n## Video\n\nMore exotic objects can also be displayed, as long as their representation supports the IPython display protocol.  For example, videos hosted externally on YouTube are easy to load:\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('sjfsUzECqK0')\n```\n\n\n\n\n\n\n\n\n\n\nUsing the nascent video capabilities of modern browsers, you may also be able to display local\nvideos.  At the moment this doesn't work very well in all browsers, so it may or may not work for you;\nwe will continue testing this and looking for ways to make it more robust.  \n\nThe following cell loads a local file called  `animation.m4v`, encodes the raw video as base64 for http\ntransport, and uses the HTML5 video tag to load it. On Chrome 15 it works correctly, displaying a control bar at the bottom with a play/pause button and a location slider.\n\n\n```python\nfrom IPython.display import HTML, Video\nfrom base64 import b64encode\nvideo = open(\"images/animation.m4v\", \"rb\").read()\nvideo_encoded = b64encode(video).decode('ascii')\nvideo_tag = '\n\n\n\n## External sites\n\nYou can even embed an entire page from another site in an iframe; for example this is today's Wikipedia\npage for mobile users:\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('http://jupyter.org', width='100%', height=350)\n```\n\n\n\n\n\n\n\n\n\n\n## Rich output and security\n\nThe IPython Notebook allows arbitrary code execution in both the IPython kernel and in the browser, though HTML and JavaScript output. More importantly, because IPython has a JavaScript API for running code in the browser, HTML and JavaScript output can actually trigger code to be run in the kernel. This poses a significant security risk as it would allow IPython Notebooks to execute arbitrary code on your computers.\n\nTo protect against these risks, the IPython Notebook has a security model that specifies how dangerous output is handled. Here is a short summary:\n\n* When you run code in the Notebook, all rich output is displayed.\n* When you open a notebook, rich output is only displayed if it doesn't contain security vulberabilities, ...\n* ... or if you have trusted a notebook, all rich output will run upon opening it.\n\nA full description of the IPython security model can be found on [this page](http://ipython.org/ipython-doc/dev/notebook/security.html).\n", "meta": {"hexsha": "9f43ecabdc1634a5217c5b02c5906310b7fd681f", "size": 403692, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "04-Rich Output.ipynb", "max_stars_repo_name": "ICESAT-2HackWeek/intro-jupyter-git", "max_stars_repo_head_hexsha": "5b678f103851c8bbc2580078f4f9174b82a57f6f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-06-16T01:16:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T10:07:47.000Z", "max_issues_repo_path": "04-Rich Output.ipynb", "max_issues_repo_name": "ICESAT-2HackWeek/intro-jupyter-git", "max_issues_repo_head_hexsha": "5b678f103851c8bbc2580078f4f9174b82a57f6f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "04-Rich Output.ipynb", "max_forks_repo_name": "ICESAT-2HackWeek/intro-jupyter-git", "max_forks_repo_head_hexsha": "5b678f103851c8bbc2580078f4f9174b82a57f6f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-06-17T18:54:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-27T10:07:55.000Z", "avg_line_length": 406.5377643505, "max_line_length": 216205, "alphanum_fraction": 0.9384481238, "converted": true, "num_tokens": 48967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10521053950871515, "lm_q2_score": 0.08269734097946944, "lm_q1q2_score": 0.008700631860386158}}
{"text": "```python\nfrom __future__ import print_function\n\nfrom textwrap import dedent\n\nimport pytablewriter\n\ntable_name = \"example_table\"\nheaders = [\"int\", \"float\", \"str\", \"bool\", \"mix\", \"time\"]\ndata = [\n    [0,   0.1,      \"hoge\", True,   0,      \"2017-01-01 03:04:05+0900\"],\n    [2,   \"-2.23\",  \"foo\",  False,  None,   \"2017-12-23 12:34:51+0900\"],\n    [3,   0,        \"bar\",  \"true\",  \"inf\", \"2017-03-03 22:44:55+0900\"],\n    [-10, -9.9,     \"\",     \"FALSE\", \"nan\", \"2017-01-01 00:00:00+0900\"],\n]\n```\n\n\n```python\nfor name in pytablewriter.TableWriterFactory.get_format_names():\n    print(name)\n```\n\n    adoc\n    asciidoc\n    bold_unicode\n    borderless\n    css\n    csv\n    elasticsearch\n    excel\n    htm\n    html\n    javascript\n    js\n    json\n    json_lines\n    jsonl\n    latex_matrix\n    latex_table\n    ldjson\n    ltsv\n    markdown\n    md\n    mediawiki\n    ndjson\n    null\n    numpy\n    pandas\n    pandas_pickle\n    py\n    python\n    rst\n    rst_csv\n    rst_csv_table\n    rst_grid\n    rst_grid_table\n    rst_simple\n    rst_simple_table\n    space_aligned\n    sqlite\n    toml\n    tsv\n    unicode\n    yaml\n\n\n\n```python\nfor name in pytablewriter.TableWriterFactory.get_extensions():\n    print(name)\n```\n\n    adoc\n    asc\n    asciidoc\n    css\n    csv\n    htm\n    html\n    js\n    json\n    jsonl\n    ldjson\n    ltsv\n    md\n    ndjson\n    py\n    rst\n    sqlite\n    sqlite3\n    tex\n    toml\n    tsv\n    xls\n    xlsx\n    yml\n\n\n\n```python\nfrom pytablewriter import MarkdownTableWriter\n\nwriter = MarkdownTableWriter()\nwriter.table_name = \"zone\"\nwriter.headers = [\"zone_id\", \"country_code\", \"zone_name\"]\nwriter.value_matrix = [\n    [\"1\", \"AD\", \"Europe/Andorra\"],\n    [\"2\", \"AE\", \"Asia/Dubai\"],\n    [\"3\", \"AF\", \"Asia/Kabul\"],\n    [\"4\", \"AG\", \"America/Antigua\"],\n    [\"5\", \"AI\", \"America/Anguilla\"],\n]\n\nwriter.write_table()\n```\n\n    # zone\n    |zone_id|country_code|   zone_name    |\n    |------:|------------|----------------|\n    |      1|AD          |Europe/Andorra  |\n    |      2|AE          |Asia/Dubai      |\n    |      3|AF          |Asia/Kabul      |\n    |      4|AG          |America/Antigua |\n    |      5|AI          |America/Anguilla|\n\n\n\n```python\nwriter = pytablewriter.CsvTableWriter()\nwriter.headers = headers\nwriter.value_matrix = data\n\nwriter.write_table()\n```\n\n    \"int\",\"float\",\"str\",\"bool\",\"mix\",\"time\"\n    0,0.1,\"hoge\",True,0,\"2017-01-01 03:04:05+0900\"\n    2,-2.23,\"foo\",False,,\"2017-12-23 12:34:51+0900\"\n    3,0,\"bar\",True,Infinity,\"2017-03-03 22:44:55+0900\"\n    -10,-9.9,,False,NaN,\"2017-01-01 00:00:00+0900\"\n\n\n\n```python\nwriter = pytablewriter.SpaceAlignedTableWriter()\nwriter.headers = [\"PID\", \"USER\", \"PR\", \"NI\", \"VIRT\", \"RES\", \"SHR\", \"S\", \"%CPU\", \"%MEM\", \"TIME+\", \"COMMAND\"]\nwriter.value_matrix = csv1 = [\n    [32866, \"root\", 20, 0, 48344, 3924, 3448, \"R\", 5.6, 0.2, \"0:00.03\", \"top\"],\n    [1, \"root\", 20, 0, 212080, 7676, 5876, \"S\", 0, 0.4, \"1:06.56\", \"systemd\"],\n    [2, \"root\", 20, 0, 0, 0, 0, \"S\", 0, 0, \"0:01.92\", \"kthreadd\"],\n    [4, \"root\", 0, -20, 0, 0, 0, \"S\", 0, 0, \"0:00.00\", \"kworker/0:0H\"],\n]\n\nwriter.write_table()\n```\n\n     PID   USER  PR  NI    VIRT   RES   SHR   S  %CPU  %MEM   TIME+     COMMAND   \n    32866  root  20    0   48344  3924  3448  R   5.6   0.2  0:00.03  top         \n        1  root  20    0  212080  7676  5876  S   0.0   0.4  1:06.56  systemd     \n        2  root  20    0       0     0     0  S   0.0   0.0  0:01.92  kthreadd    \n        4  root   0  -20       0     0     0  S   0.0   0.0  0:00.00  kworker/0:0H\n\n\n\n```python\nwriter = pytablewriter.TsvTableWriter()\nwriter.headers = headers\nwriter.value_matrix = data\n\nwriter.write_table()\n```\n\n    \"int\"\t\"float\"\t\"str\"\t\"bool\"\t\"mix\"\t\"time\"\n    0\t0.1\t\"hoge\"\tTrue\t0\t\"2017-01-01 03:04:05+0900\"\n    2\t-2.23\t\"foo\"\tFalse\t\t\"2017-12-23 12:34:51+0900\"\n    3\t0\t\"bar\"\tTrue\tInfinity\t\"2017-03-03 22:44:55+0900\"\n    -10\t-9.9\t\tFalse\tNaN\t\"2017-01-01 00:00:00+0900\"\n\n\n\n```python\nwriter = pytablewriter.HtmlTableWriter()\nwriter.table_name = table_name\nwriter.headers = headers\nwriter.value_matrix = data\n\nwriter.write_table()\n```\n\n    <table id=\"example_table\">\n        <caption>example_table</caption>\n        <thead>\n            <tr>\n                <th>int</th>\n                <th>float</th>\n                <th>str</th>\n                <th>bool</th>\n                <th>mix</th>\n                <th>time</th>\n            </tr>\n        </thead>\n        <tbody>\n            <tr>\n                <td align=\"right\">0</td>\n                <td align=\"right\">0.10</td>\n                <td align=\"left\">hoge</td>\n                <td align=\"left\">True</td>\n                <td align=\"right\">0</td>\n                <td align=\"left\">2017-01-01 03:04:05+0900</td>\n            </tr>\n            <tr>\n                <td align=\"right\">2</td>\n                <td align=\"right\">-2.23</td>\n                <td align=\"left\">foo</td>\n                <td align=\"left\">False</td>\n                <td align=\"right\"></td>\n                <td align=\"left\">2017-12-23 12:34:51+0900</td>\n            </tr>\n            <tr>\n                <td align=\"right\">3</td>\n                <td align=\"right\">0.00</td>\n                <td align=\"left\">bar</td>\n                <td align=\"left\">True</td>\n                <td align=\"right\">Infinity</td>\n                <td align=\"left\">2017-03-03 22:44:55+0900</td>\n            </tr>\n            <tr>\n                <td align=\"right\">-10</td>\n                <td align=\"right\">-9.90</td>\n                <td align=\"left\"></td>\n                <td align=\"left\">False</td>\n                <td align=\"right\">NaN</td>\n                <td align=\"left\">2017-01-01 00:00:00+0900</td>\n            </tr>\n        </tbody>\n    </table>\n\n\n\n```python\nwriter = pytablewriter.JavaScriptTableWriter()\nwriter.table_name = table_name\nwriter.headers = headers\nwriter.value_matrix = data\n\nwriter.write_table()\n```\n\n    const example_table = [\n        [\"int\", \"float\", \"str\", \"bool\", \"mix\", \"time\"],\n        [0, 0.1, \"hoge\", true, 0, \"2017-01-01 03:04:05+0900\"],\n        [2, -2.23, \"foo\", false, null, \"2017-12-23 12:34:51+0900\"],\n        [3, 0, \"bar\", true, Infinity, \"2017-03-03 22:44:55+0900\"],\n        [-10, -9.9, \"\", \"FALSE\", NaN, \"2017-01-01 00:00:00+0900\"]\n    ];\n\n\n\n```python\nwriter = pytablewriter.JsonTableWriter()\n#writer.table_name = \"Timezone\"\nwriter.headers = headers\nwriter.value_matrix = data\n\nwriter.write_table()\n```\n\n    [\n        {\n            \"int\": 0,\n            \"float\": 0.1,\n            \"str\": \"hoge\",\n            \"bool\": true,\n            \"mix\": 0,\n            \"time\": \"2017-01-01 03:04:05+0900\"\n        },\n        {\n            \"int\": 2,\n            \"float\": -2.23,\n            \"str\": \"foo\",\n            \"bool\": false,\n            \"mix\": null,\n            \"time\": \"2017-12-23 12:34:51+0900\"\n        },\n        {\n            \"int\": 3,\n            \"float\": 0,\n            \"str\": \"bar\",\n            \"bool\": \"true\",\n            \"mix\": \"Infinity\",\n            \"time\": \"2017-03-03 22:44:55+0900\"\n        },\n        {\n            \"int\": -10,\n            \"float\": -9.9,\n            \"str\": \"\",\n            \"bool\": \"FALSE\",\n            \"mix\": \"NaN\",\n            \"time\": \"2017-01-01 00:00:00+0900\"\n        }\n    ]\n\n\n\n```python\nwriter = pytablewriter.JsonLinesTableWriter()\nwriter.headers = headers\nwriter.value_matrix = data\n\nwriter.write_table()\n```\n\n    {\"int\": 0, \"float\": 0.1, \"str\": \"hoge\", \"bool\": true, \"mix\": 0, \"time\": \"2017-01-01 03:04:05+0900\"}\n    {\"int\": 2, \"float\": -2.23, \"str\": \"foo\", \"bool\": false, \"mix\": null, \"time\": \"2017-12-23 12:34:51+0900\"}\n    {\"int\": 3, \"float\": 0, \"str\": \"bar\", \"bool\": \"true\", \"mix\": \"Infinity\", \"time\": \"2017-03-03 22:44:55+0900\"}\n    {\"int\": -10, \"float\": -9.9, \"str\": \"\", \"bool\": \"FALSE\", \"mix\": \"NaN\", \"time\": \"2017-01-01 00:00:00+0900\"}\n\n\n\n```python\nwriter = pytablewriter.JsonTableWriter()\nwriter.table_name = table_name\nwriter.headers = headers\nwriter.value_matrix = data\n\nwriter.write_table()\n```\n\n    { \"example_table\" : [\n        {\n            \"int\": 0,\n            \"float\": 0.1,\n            \"str\": \"hoge\",\n            \"bool\": true,\n            \"mix\": 0,\n            \"time\": \"2017-01-01 03:04:05+0900\"\n        },\n        {\n            \"int\": 2,\n            \"float\": -2.23,\n            \"str\": \"foo\",\n            \"bool\": false,\n            \"mix\": null,\n            \"time\": \"2017-12-23 12:34:51+0900\"\n        },\n        {\n            \"int\": 3,\n            \"float\": 0,\n            \"str\": \"bar\",\n            \"bool\": \"true\",\n            \"mix\": \"Infinity\",\n            \"time\": \"2017-03-03 22:44:55+0900\"\n        },\n        {\n            \"int\": -10,\n            \"float\": -9.9,\n            \"str\": \"\",\n            \"bool\": \"FALSE\",\n            \"mix\": \"NaN\",\n            \"time\": \"2017-01-01 00:00:00+0900\"\n        }\n    ]}\n\n\n\n```python\nwriter = pytablewriter.LatexMatrixWriter()\nwriter.table_name = \"A\"\nwriter.value_matrix = [\n    [0.01, 0.00125, 0.0],\n    [1.0, 99.9,  0.01],\n    [1.2, 999999.123, 0.001],\n]\nwriter.write_table()\n```\n\n    \\begin{equation}\n        A = \\left( \\begin{array}{rrr}\n            0.01 &      0.0012 & 0.000 \\\\\n            1.00 &     99.9000 & 0.010 \\\\\n            1.20 & 999999.1230 & 0.001 \\\\\n        \\end{array} \\right)\n    \\end{equation}\n\n\n\\begin{equation}\n    A = \\left( \\begin{array}{rrr}\n        0.01 &      0.0012 & 0.000 \\\\\n        1.00 &     99.9000 & 0.010 \\\\\n        1.20 & 999999.1230 & 0.001 \\\\\n    \\end{array} \\right)\n\\end{equation}\n\n\n```python\nwriter = pytablewriter.LatexMatrixWriter()\nwriter.table_name = \"B\"\nwriter.value_matrix = [\n    [\"a_{11}\", \"a_{12}\", \"\\\\ldots\", \"a_{1n}\"],\n    [\"a_{21}\", \"a_{22}\", \"\\\\ldots\", \"a_{2n}\"],\n    [r\"\\vdots\", \"\\\\vdots\", \"\\\\ddots\", \"\\\\vdots\"],\n    [\"a_{n1}\", \"a_{n2}\", \"\\\\ldots\", \"a_{nn}\"],\n]\nwriter.write_table()\n```\n\n    \\begin{equation}\n        B = \\left( \\begin{array}{llll}\n            a_{11} & a_{12} & \\ldots & a_{1n} \\\\\n            a_{21} & a_{22} & \\ldots & a_{2n} \\\\\n            \\vdots & \\vdots & \\ddots & \\vdots \\\\\n            a_{n1} & a_{n2} & \\ldots & a_{nn} \\\\\n        \\end{array} \\right)\n    \\end{equation}\n\n\n\\begin{equation}\n    B = \\left( \\begin{array}{llll}\n        a_{11} & a_{12} & \\ldots & a_{1n} \\\\\n        a_{21} & a_{22} & \\ldots & a_{2n} \\\\\n        \\vdots & \\vdots & \\ddots & \\vdots \\\\\n        a_{n1} & a_{n2} & \\ldots & a_{nn} \\\\\n    \\end{array} \\right)\n\\end{equation}\n\n\n```python\nwriter = pytablewriter.LatexTableWriter()\nwriter.headers = headers\nwriter.value_matrix = data\n\nwriter.write_table()\n```\n\n    \\begin{array}{r | r | l | l | l | l} \\hline\n        \\verb|int| & \\verb|float| & \\verb|str | & \\verb|bool | & \\verb| mix  | & \\verb|          time          | \\\\ \\hline\n        \\hline\n          0 &  0.10 & hoge & True  &      0 & \\verb|2017-01-01 03:04:05+0900| \\\\ \\hline\n          2 & -2.23 & foo  & False &        & \\verb|2017-12-23 12:34:51+0900| \\\\ \\hline\n          3 &  0.00 & bar  & True  & \\infty & \\verb|2017-03-03 22:44:55+0900| \\\\ \\hline\n        -10 & -9.90 &      & False & NaN    & \\verb|2017-01-01 00:00:00+0900| \\\\ \\hline\n    \\end{array}\n\n\n\\begin{array}{r | r | l | l | l | l} \\hline\n    \\verb|int| & \\verb|float| & \\verb|str| & \\verb|bool| & \\verb|mix| & \\verb|time| \\\\ \\hline\n    \\hline\n    0 & 0.10 & hoge & True & 0 & \\verb|2017-01-01 03:04:05+0900| \\\\ \\hline\n    2 & -2.23 & foo & False &  & \\verb|2017-12-23 12:34:51+0900| \\\\ \\hline\n    3 & 0.00 & bar & True & \\infty & \\verb|2017-03-03 22:44:55+0900| \\\\ \\hline\n    -10 & -9.90 &  & False & NaN & \\verb|2017-01-01 00:00:00+0900| \\\\ \\hline\n\\end{array}\n\n\n```python\nfrom pytablewriter import MarkdownTableWriter\n\nwriter = MarkdownTableWriter()\nwriter.table_name = table_name\nwriter.headers = headers\nwriter.value_matrix = data\n\nwriter.write_table()\n```\n\n    # example_table\n    |int|float|str |bool |  mix   |          time          |\n    |--:|----:|----|-----|-------:|------------------------|\n    |  0| 0.10|hoge|True |       0|2017-01-01 03:04:05+0900|\n    |  2|-2.23|foo |False|        |2017-12-23 12:34:51+0900|\n    |  3| 0.00|bar |True |Infinity|2017-03-03 22:44:55+0900|\n    |-10|-9.90|    |False|     NaN|2017-01-01 00:00:00+0900|\n\n\n\n```python\nfrom pytablewriter import MarkdownTableWriter\n\nwriter = MarkdownTableWriter()\nwriter.table_name = \"write example with a margin\"\nwriter.headers = headers\nwriter.value_matrix = data\nwriter.margin = 1  # add a whitespace for both sides of each cell\n\nwriter.write_table()\n```\n\n    # write example with a margin\n    | int | float | str  | bool  |   mix    |           time           |\n    | --: | ----: | ---- | ----- | -------: | ------------------------ |\n    |   0 |  0.10 | hoge | True  |        0 | 2017-01-01 03:04:05+0900 |\n    |   2 | -2.23 | foo  | False |          | 2017-12-23 12:34:51+0900 |\n    |   3 |  0.00 | bar  | True  | Infinity | 2017-03-03 22:44:55+0900 |\n    | -10 | -9.90 |      | False |      NaN | 2017-01-01 00:00:00+0900 |\n\n\n\n```python\nwriter = pytablewriter.MediaWikiTableWriter()\nwriter.table_name = table_name\nwriter.headers = headers\nwriter.value_matrix = data\n\nwriter.write_table()\n```\n\n    {| class=\"wikitable\"\n    |+example_table\n    ! int\n    ! float\n    ! str\n    ! bool\n    ! mix\n    ! time\n    |-\n    | style=\"text-align:right\"| 0\n    | style=\"text-align:right\"| 0.10\n    | hoge\n    | True\n    | style=\"text-align:right\"| 0\n    | 2017-01-01 03:04:05+0900\n    |-\n    | style=\"text-align:right\"| 2\n    | style=\"text-align:right\"| -2.23\n    | foo\n    | False\n    | \n    | 2017-12-23 12:34:51+0900\n    |-\n    | style=\"text-align:right\"| 3\n    | style=\"text-align:right\"| 0.00\n    | bar\n    | True\n    | Infinity\n    | 2017-03-03 22:44:55+0900\n    |-\n    | style=\"text-align:right\"| -10\n    | style=\"text-align:right\"| -9.90\n    | \n    | False\n    | NaN\n    | 2017-01-01 00:00:00+0900\n    |}\n\n\n\n```python\nwriter = pytablewriter.NumpyTableWriter()\nwriter.table_name = table_name\nwriter.headers = headers\nwriter.value_matrix = data\n\nwriter.write_table()\n```\n\n    example_table = np.array([\n        [\"int\", \"float\", \"str\", \"bool\", \"mix\", \"time\"],\n        [0, 0.1, \"hoge\", True, 0, \"2017-01-01 03:04:05+0900\"],\n        [2, -2.23, \"foo\", False, None, \"2017-12-23 12:34:51+0900\"],\n        [3, 0, \"bar\", True, np.inf, \"2017-03-03 22:44:55+0900\"],\n        [-10, -9.9, \"\", False, np.nan, \"2017-01-01 00:00:00+0900\"],\n    ])\n\n\n\n```python\nwriter = pytablewriter.PandasDataFrameWriter()\nwriter.table_name = table_name\nwriter.headers = headers\nwriter.value_matrix = data\n\nwriter.write_table()\n```\n\n    example_table = pd.DataFrame([\n        [0, 0.1, \"hoge\", True, 0, \"2017-01-01 03:04:05+0900\"],\n        [2, -2.23, \"foo\", False, None, \"2017-12-23 12:34:51+0900\"],\n        [3, 0, \"bar\", True, np.inf, \"2017-03-03 22:44:55+0900\"],\n        [-10, -9.9, \"\", False, np.nan, \"2017-01-01 00:00:00+0900\"],\n    ], columns=[\"int\", \"float\", \"str\", \"bool\", \"mix\", \"time\"])\n\n\n\n```python\nwriter = pytablewriter.PandasDataFrameWriter()\nwriter.table_name = table_name\nwriter.headers = headers\nwriter.value_matrix = data\nwriter.is_datetime_instance_formatting = False\n\nwriter.write_table()\n```\n\n    example_table = pd.DataFrame([\n        [0, 0.1, \"hoge\", True, 0, \"2017-01-01 03:04:05+0900\"],\n        [2, -2.23, \"foo\", False, None, \"2017-12-23 12:34:51+0900\"],\n        [3, 0, \"bar\", True, np.inf, \"2017-03-03 22:44:55+0900\"],\n        [-10, -9.9, \"\", False, np.nan, \"2017-01-01 00:00:00+0900\"],\n    ], columns=[\"int\", \"float\", \"str\", \"bool\", \"mix\", \"time\"])\n\n\n\n```python\nwriter = pytablewriter.PythonCodeTableWriter()\nwriter.table_name = table_name\nwriter.headers = headers\nwriter.value_matrix = data\n\nwriter.write_table()\n```\n\n    example_table = [\n        [\"int\", \"float\", \"str\", \"bool\", \"mix\", \"time\"],\n        [0, 0.1, \"hoge\", True, 0, \"2017-01-01 03:04:05+0900\"],\n        [2, -2.23, \"foo\", False, None, \"2017-12-23 12:34:51+0900\"],\n        [3, 0, \"bar\", True, float(\"inf\"), \"2017-03-03 22:44:55+0900\"],\n        [-10, -9.9, \"\", False, float(\"nan\"), \"2017-01-01 00:00:00+0900\"],\n    ]\n\n\n\n```python\nwriter = pytablewriter.PythonCodeTableWriter()\nwriter.table_name = table_name\nwriter.headers = headers\nwriter.value_matrix = data\nwriter.is_datetime_instance_formatting = False\n\nwriter.write_table()\n```\n\n    example_table = [\n        [\"int\", \"float\", \"str\", \"bool\", \"mix\", \"time\"],\n        [0, 0.1, \"hoge\", True, 0, \"2017-01-01 03:04:05+0900\"],\n        [2, -2.23, \"foo\", False, None, \"2017-12-23 12:34:51+0900\"],\n        [3, 0, \"bar\", True, float(\"inf\"), \"2017-03-03 22:44:55+0900\"],\n        [-10, -9.9, \"\", False, float(\"nan\"), \"2017-01-01 00:00:00+0900\"],\n    ]\n\n\n\n```python\nwriter = pytablewriter.RstGridTableWriter()\nwriter.table_name = table_name\nwriter.headers = headers\nwriter.value_matrix = data\n\nwriter.write_table()\n```\n\n    .. table:: example_table\n    \n        +---+-----+----+-----+--------+------------------------+\n        |int|float|str |bool |  mix   |          time          |\n        +===+=====+====+=====+========+========================+\n        |  0| 0.10|hoge|True |       0|2017-01-01 03:04:05+0900|\n        +---+-----+----+-----+--------+------------------------+\n        |  2|-2.23|foo |False|        |2017-12-23 12:34:51+0900|\n        +---+-----+----+-----+--------+------------------------+\n        |  3| 0.00|bar |True |Infinity|2017-03-03 22:44:55+0900|\n        +---+-----+----+-----+--------+------------------------+\n        |-10|-9.90|    |False|     NaN|2017-01-01 00:00:00+0900|\n        +---+-----+----+-----+--------+------------------------+\n\n\n\n```python\nwriter = pytablewriter.RstSimpleTableWriter()\nwriter.table_name = table_name\nwriter.headers = headers\nwriter.value_matrix = data\n\nwriter.write_table()\n```\n\n    .. table:: example_table\n    \n        ===  =====  ====  =====  ========  ========================\n        int  float  str   bool     mix               time          \n        ===  =====  ====  =====  ========  ========================\n          0   0.10  hoge  True          0  2017-01-01 03:04:05+0900\n          2  -2.23  foo   False            2017-12-23 12:34:51+0900\n          3   0.00  bar   True   Infinity  2017-03-03 22:44:55+0900\n        -10  -9.90        False       NaN  2017-01-01 00:00:00+0900\n        ===  =====  ====  =====  ========  ========================\n\n\n\n```python\nwriter = pytablewriter.RstCsvTableWriter()\nwriter.table_name = table_name\nwriter.headers = headers\nwriter.value_matrix = data\n\nwriter.write_table()\n```\n\n    .. csv-table:: example_table\n        :header: \"int\", \"float\", \"str\", \"bool\", \"mix\", \"time\"\n        :widths: 5, 7, 6, 6, 8, 26\n    \n        0, 0.10, \"hoge\", True, 0, \"2017-01-01 03:04:05+0900\"\n        2, -2.23, \"foo\", False, , \"2017-12-23 12:34:51+0900\"\n        3, 0.00, \"bar\", True, Infinity, \"2017-03-03 22:44:55+0900\"\n        -10, -9.90, , False, NaN, \"2017-01-01 00:00:00+0900\"\n\n\n\n```python\nwriter = pytablewriter.LtsvTableWriter()\nwriter.headers = headers\nwriter.value_matrix = data\n\nwriter.write_table()\n```\n\n    int:0\tfloat:0.1\tstr:\"hoge\"\tbool:True\tmix:0\ttime:\"2017-01-01 03:04:05+0900\"\n    int:2\tfloat:-2.23\tstr:\"foo\"\tbool:False\ttime:\"2017-12-23 12:34:51+0900\"\n    int:3\tfloat:0\tstr:\"bar\"\tbool:True\tmix:Infinity\ttime:\"2017-03-03 22:44:55+0900\"\n    int:-10\tfloat:-9.9\tbool:False\tmix:NaN\ttime:\"2017-01-01 00:00:00+0900\"\n\n\n\n```python\nwriter = pytablewriter.TomlTableWriter()\nwriter.table_name = table_name\nwriter.headers = headers\nwriter.value_matrix = data\n\n\nwriter.write_table()\n```\n\n    [[example_table]]\n    int = 0\n    float = 0.1\n    str = \"hoge\"\n    bool = true\n    mix = 0\n    time = \"2017-01-01 03:04:05+0900\"\n    \n    [[example_table]]\n    int = 2\n    float = -2.23\n    str = \"foo\"\n    bool = false\n    time = \"2017-12-23 12:34:51+0900\"\n    \n    [[example_table]]\n    int = 3\n    float = 0\n    str = \"bar\"\n    bool = true\n    mix = inf\n    time = \"2017-03-03 22:44:55+0900\"\n    \n    [[example_table]]\n    int = -10\n    float = -9.9\n    str = \"\"\n    bool = false\n    mix = nan\n    time = \"2017-01-01 00:00:00+0900\"\n    \n\n\n\n```python\nfrom datetime import datetime\nfrom pytablewriter import JavaScriptTableWriter\nfrom pytablewriter.typehint import DateTime, Integer, String\n\ndef main():\n    writer = JavaScriptTableWriter()\n    writer.headers = [\"header_a\", \"header_b\", \"header_c\"]\n    writer.value_matrix = [\n        [-1.1, \"2017-01-02 03:04:05\", datetime(2017, 1, 2, 3, 4, 5)],\n        [0.12, \"2017-02-03 04:05:06\", datetime(2017, 2, 3, 4, 5, 6)],\n    ]\n\n    print(\"// without type hints:  column data types detected automatically by default\")\n    writer.table_name = \"without type hint\"\n    writer.write_table()\n\n    print(\"// with type hints: Integer, DateTime, String\")\n    writer.table_name = \"with type hint\"\n    writer.type_hints = [Integer, DateTime, String]\n    writer.write_table()\n\nif __name__ == \"__main__\":\n    main()\n```\n\n    // without type hints:  column data types detected automatically by default\n    const without_type_hint = [\n        [\"header_a\", \"header_b\", \"header_c\"],\n        [-1.1, \"2017-01-02 03:04:05\", new Date(\"2017-01-02T03:04:05\")],\n        [0.12, \"2017-02-03 04:05:06\", new Date(\"2017-02-03T04:05:06\")]\n    ];\n    // with type hints: Integer, DateTime, String\n    const with_type_hint = [\n        [\"header_a\", \"header_b\", \"header_c\"],\n        [-1, new Date(\"2017-01-02T03:04:05\"), \"2017-01-02 03:04:05\"],\n        [0, new Date(\"2017-02-03T04:05:06\"), \"2017-02-03 04:05:06\"]\n    ];\n\n\n\n```python\nfrom datetime import datetime\nfrom pytablewriter import PythonCodeTableWriter\nfrom pytablewriter.typehint import DateTime, Integer, String\n\ndef main():\n    writer = PythonCodeTableWriter()\n    writer.value_matrix = [\n        [-1.1, float(\"inf\"), \"2017-01-02 03:04:05\", datetime(2017, 1, 2, 3, 4, 5)],\n        [0.12, float(\"nan\"), \"2017-02-03 04:05:06\", datetime(2017, 2, 3, 4, 5, 6)],\n    ]\n\n    # column data types detected automatically by default\n    writer.table_name = \"python variable without type hints\"\n    writer.headers = [\"float\", \"infnan\", \"string\", \"datetime\"]\n    writer.write_table()\n\n    # set type hints\n    writer.table_name = \"python variable with type hints\"\n    writer.headers = [\"hint_int\", \"hint_str\", \"hint_datetime\", \"hint_str\"]\n    writer.type_hints = [Integer, String, DateTime, String]\n    writer.write_table()\n\nif __name__ == \"__main__\":\n    main()\n```\n\n    python_variable_without_type_hints = [\n        [\"float\", \"infnan\", \"string\", \"datetime\"],\n        [-1.1, float(\"inf\"), \"2017-01-02 03:04:05\", dateutil.parser.parse(\"2017-01-02T03:04:05\")],\n        [0.12, float(\"nan\"), \"2017-02-03 04:05:06\", dateutil.parser.parse(\"2017-02-03T04:05:06\")],\n    ]\n    python_variable_with_type_hints = [\n        [\"hint_int\", \"hint_str\", \"hint_datetime\", \"hint_str\"],\n        [-1, \"inf\", dateutil.parser.parse(\"2017-01-02T03:04:05\"), \"2017-01-02 03:04:05\"],\n        [0, \"nan\", dateutil.parser.parse(\"2017-02-03T04:05:06\"), \"2017-02-03 04:05:06\"],\n    ]\n\n\n\n```python\nwriter = pytablewriter.MarkdownTableWriter()\nwriter.from_csv(dedent(\"\"\"\\\n    \"i\",\"f\",\"c\",\"if\",\"ifc\",\"bool\",\"inf\",\"nan\",\"mix_num\",\"time\"\n    1,1.10,\"aa\",1.0,\"1\",True,Infinity,NaN,1,\"2017-01-01 00:00:00+09:00\"\n    2,2.20,\"bbb\",2.2,\"2.2\",False,Infinity,NaN,Infinity,\"2017-01-02 03:04:05+09:00\"\n    3,3.33,\"cccc\",-3.0,\"ccc\",True,Infinity,NaN,NaN,\"2017-01-01 00:00:00+09:00\"\n    \"\"\"))\nwriter.write_table()\n```\n\n    | i | f  | c  | if |ifc|bool |  inf   |nan|mix_num |          time           |\n    |--:|---:|----|---:|---|-----|--------|---|-------:|-------------------------|\n    |  1|1.10|aa  | 1.0|  1|True |Infinity|NaN|       1|2017-01-01 00:00:00+09:00|\n    |  2|2.20|bbb | 2.2|2.2|False|Infinity|NaN|Infinity|2017-01-02 03:04:05+09:00|\n    |  3|3.33|cccc|-3.0|ccc|True |Infinity|NaN|     NaN|2017-01-01 00:00:00+09:00|\n\n\n\n```python\nwriter = pytablewriter.MarkdownTableWriter()\nwriter.table_name = \"ps\"\nwriter.from_csv(\n    dedent(\"\"\"\\\n        USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND\n        root         1  0.0  0.4  77664  8784 ?        Ss   May11   0:02 /sbin/init\n        root         2  0.0  0.0      0     0 ?        S    May11   0:00 [kthreadd]\n        root         4  0.0  0.0      0     0 ?        I<   May11   0:00 [kworker/0:0H]\n        root         6  0.0  0.0      0     0 ?        I<   May11   0:00 [mm_percpu_wq]\n        root         7  0.0  0.0      0     0 ?        S    May11   0:01 [ksoftirqd/0]\n    \"\"\"),\n    delimiter=\" \")\nwriter.write_table()\n```\n\n    # ps\n    |USER|PID|%CPU|%MEM| VSZ |RSS |TTY|STAT|START|TIME|   COMMAND    |\n    |----|--:|---:|---:|----:|---:|---|----|-----|----|--------------|\n    |root|  1|   0| 0.4|77664|8784|?  |Ss  |May11|0:02|/sbin/init    |\n    |root|  2|   0| 0.0|    0|   0|?  |S   |May11|0:00|[kthreadd]    |\n    |root|  4|   0| 0.0|    0|   0|?  |I<  |May11|0:00|[kworker/0:0H]|\n    |root|  6|   0| 0.0|    0|   0|?  |I<  |May11|0:00|[mm_percpu_wq]|\n    |root|  7|   0| 0.0|    0|   0|?  |S   |May11|0:01|[ksoftirqd/0] |\n\n\n\n```python\nfrom pytablewriter import MarkdownTableWriter\nfrom pytablewriter.style import Align, Style\n\nwriter = MarkdownTableWriter()\nwriter.table_name = \"specify alignment for each column manually\"\nwriter.headers = [\"left\", \"right\", \"center\", \"auto (int)\", \"auto (str)\", \"None (same as AUTO)\"]\nwriter.value_matrix = [\n    [0, \"r\", \"center align\", 0, \"a\", \"n\"],\n    [11, \"right align\", \"c\", 11, \"auto\", \"none\"],\n]\n\n# set alignments for each column\nwriter.column_styles = [\n    Style(align=Align.LEFT),\n    Style(align=Align.RIGHT),\n    Style(align=Align.CENTER),\n    Style(align=Align.AUTO),\n    Style(align=Align.AUTO),\n    None,\n]\n\nwriter.write_table()\n```\n\n    # specify alignment for each column manually\n    |left|   right   |   center   |auto (int)|auto (str)|None (same as AUTO)|\n    |----|----------:|:----------:|---------:|----------|-------------------|\n    |0   |          r|center align|         0|a         |n                  |\n    |11  |right align|     c      |        11|auto      |none               |\n\n\n\n```python\nfrom pytablewriter import MarkdownTableWriter\nfrom pytablewriter.style import Style\n\nwriter = MarkdownTableWriter()\nwriter.table_name = \"set style by styles\"\nwriter.headers = [\n    \"auto align\",\n    \"left align\",\n    \"center align\",\n    \"bold\",\n    \"italic\",\n    \"bold italic ts\",\n]\nwriter.value_matrix = [\n    [11, 11, 11, 11, 11, 11],\n    [1234, 1234, 1234, 1234, 1234, 1234],\n]\n\n# specify styles for each column\nwriter.column_styles = [\n    Style(),\n    Style(align=\"left\"),\n    Style(align=\"center\"),\n    Style(font_weight=\"bold\"),\n    Style(font_style=\"italic\"),\n    Style(font_weight=\"bold\", font_style=\"italic\", thousand_separator=\",\"),\n]\n\nwriter.write_table()\n\n```\n\n    # set style by styles\n    |auto align|left align|center align|\u001b[1m  bold  \u001b[0m|italic|\u001b[1mbold italic ts\u001b[0m|\n    |---------:|----------|:----------:|-------:|-----:|-------------:|\n    |        11|11        |     11     |\u001b[1m  **11**\u001b[0m|  _11_|\u001b[1m      _**11**_\u001b[0m|\n    |      1234|1234      |    1234    |\u001b[1m**1234**\u001b[0m|_1234_|\u001b[1m   _**1,234**_\u001b[0m|\n\n\n\n```python\nfrom pytablewriter import MarkdownTableWriter\nfrom pytablewriter.style import Style\n\nwriter = MarkdownTableWriter()\nwriter.headers = [\"A\", \"B\", \"C\",]\nwriter.value_matrix = [[11, 11, 11], [1234, 1234, 1234]]\n\nwriter.table_name = \"set style by column index\"\nwriter.set_style(1, Style(align=\"center\", font_weight=\"bold\"))\nwriter.set_style(2, Style(thousand_separator=\" \"))\nwriter.write_table()\nwriter.write_null_line()\n\nwriter.table_name = \"set style by header\"\nwriter.set_style(\"B\", Style(font_style=\"italic\"))\nwriter.write_table()\n\n```\n\n    # set style by column index\n    | A  |\u001b[1m   B    \u001b[0m|  C  |\n    |---:|:------:|----:|\n    |  11|\u001b[1m **11** \u001b[0m|   11|\n    |1234|\u001b[1m**1234**\u001b[0m|1 234|\n    \n    # set style by header\n    | A  |  B   |  C  |\n    |---:|-----:|----:|\n    |  11|  _11_|   11|\n    |1234|_1234_|1 234|\n\n\n\n```python\nimport pytablewriter\n\nwriter = pytablewriter.MarkdownTableWriter()\nwriter.headers = [\"int\", \"float\", \"str\", \"bool\", \"mix\", \"time\"]\nwriter.value_matrix = [\n    [0,   0.1,      \"hoge\", True,   0,      \"2017-01-01 03:04:05+0900\"],\n    [2,   \"-2.23\",  \"foo\",  False,  None,   \"2017-12-23 45:01:23+0900\"],\n    [3,   0,        \"bar\",  \"true\",  \"inf\", \"2017-03-03 33:44:55+0900\"],\n    [-10, -9.9,     \"\",     \"FALSE\", \"nan\", \"2017-01-01 00:00:00+0900\"],\n]\n\nprint(writer.dumps())\n```\n\n    |int|float|str |bool |  mix   |          time          |\n    |--:|----:|----|-----|-------:|------------------------|\n    |  0| 0.10|hoge|True |       0|2017-01-01 03:04:05+0900|\n    |  2|-2.23|foo |False|        |2017-12-23 45:01:23+0900|\n    |  3| 0.00|bar |True |Infinity|2017-03-03 33:44:55+0900|\n    |-10|-9.90|    |False|     NaN|2017-01-01 00:00:00+0900|\n    \n\n\n\n```python\nfrom pytablewriter import MarkdownTableWriter\nfrom pytablewriter.style import ThousandSeparator\n\nwriter = MarkdownTableWriter()\nwriter.headers = [\"wo_format\", \"comma_i\", \"space_f\"]\nwriter.value_matrix = [\n    [1000, 1234567, 1234567.8],\n    [1000, 1234567, 1234567.8],\n    [1000, 1234567, 1234567.8],\n]\nwriter.column_styles = [\n    Style(thousand_separator=ThousandSeparator.NONE),\n    Style(thousand_separator=ThousandSeparator.COMMA),\n    Style(thousand_separator=ThousandSeparator.SPACE),\n]\nwriter.write_table()\n```\n\n    |wo_format| comma_i |  space_f  |\n    |--------:|--------:|----------:|\n    |     1000|1,234,567|1 234 567.8|\n    |     1000|1,234,567|1 234 567.8|\n    |     1000|1,234,567|1 234 567.8|\n\n\n\n```python\nfrom pytablewriter import LatexTableWriter\nfrom pytablewriter.style import Style, FontSize\n\nwriter = LatexTableWriter()\nwriter.table_name = \"style test: font size\"\nwriter.headers = [\"none\", \"empty_style\", \"tiny\", \"small\", \"medium\", \"large\"]\nwriter.value_matrix = [[111, 111, 111, 111, 111, 111], [1234, 1234, 1234, 1234, 1234, 1234]]\nwriter.column_styles = [\n    None,\n    Style(),\n    Style(font_size=FontSize.TINY),\n    Style(font_size=FontSize.SMALL),\n    Style(font_size=FontSize.MEDIUM),\n    Style(font_size=FontSize.LARGE),\n]\nwriter.write_table()\n```\n\n    \\begin{array}{r | r | r | r | r | r} \\hline\n        \\verb|none| & \\verb|empty_style| & \\verb|  tiny   | & \\verb|  small   | & \\verb|    medium     | & \\verb|  large   | \\\\ \\hline\n        \\hline\n         111 &         111 & \\tiny 111 & \\small 111 & \\normalsize 111 & \\large 111 \\\\ \\hline\n        1234 &        1234 & \\tiny 1234 & \\small 1234 & \\normalsize 1234 & \\large 1234 \\\\ \\hline\n    \\end{array}\n\n\n\\begin{array}{r | r | r | r | r | r} \\hline\n    \\verb|none| & \\verb|empty_style| & \\verb|tiny| & \\verb|small| & \\verb|medium| & \\verb|large| \\\\ \\hline\n    \\hline\n     111 &         111 & \\tiny 111 & \\small 111 & \\normalsize 111 & \\large 111 \\\\ \\hline\n    1234 &        1234 & \\tiny 1234 & \\small 1234 & \\normalsize 1234 & \\large 1234 \\\\ \\hline\n\\end{array}\n\n\n```python\nfrom pytablewriter import UnicodeTableWriter\n\nwriter = UnicodeTableWriter()\nwriter.table_name = table_name\nwriter.headers = headers\nwriter.value_matrix = data\n\nwriter.write_table()\n```\n\n    \u250c\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n    \u2502int\u2502float\u2502str \u2502bool \u2502  mix   \u2502          time          \u2502\n    \u251c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n    \u2502  0\u2502 0.10\u2502hoge\u2502True \u2502       0\u25022017-01-01 03:04:05+0900\u2502\n    \u251c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n    \u2502  2\u2502-2.23\u2502foo \u2502False\u2502        \u25022017-12-23 12:34:51+0900\u2502\n    \u251c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n    \u2502  3\u2502 0.00\u2502bar \u2502True \u2502Infinity\u25022017-03-03 22:44:55+0900\u2502\n    \u251c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n    \u2502-10\u2502-9.90\u2502    \u2502False\u2502     NaN\u25022017-01-01 00:00:00+0900\u2502\n    \u2514\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\n\n\n```python\nfrom textwrap import dedent\nimport pandas as pd\nimport io\nfrom pytablewriter import MarkdownTableWriter\n\ndef main():\n    csv_data = io.StringIO(dedent(\"\"\"\\\n        \"i\",\"f\",\"c\",\"if\",\"ifc\",\"bool\",\"inf\",\"nan\",\"mix_num\",\"time\"\n        1,1.10,\"aa\",1.0,\"1\",True,Infinity,NaN,1,\"2017-01-01 00:00:00+09:00\"\n        2,2.20,\"bbb\",2.2,\"2.2\",False,Infinity,NaN,Infinity,\"2017-01-02 03:04:05+09:00\"\n        3,3.33,\"cccc\",-3.0,\"ccc\",True,Infinity,NaN,NaN,\"2017-01-01 00:00:00+09:00\"\n        \"\"\"))\n    df = pd.read_csv(csv_data, sep=',')\n\n    writer = MarkdownTableWriter(dataframe=df)\n    writer.write_table()\n\nif __name__ == \"__main__\":\n    main()\n\n```\n\n    | i | f  | c  | if |ifc|bool |  inf   |nan|mix_num |          time           |\n    |--:|---:|----|---:|---|-----|--------|---|-------:|-------------------------|\n    |  1|1.10|aa  | 1.0|  1|True |Infinity|NaN|       1|2017-01-01 00:00:00+09:00|\n    |  2|2.20|bbb | 2.2|2.2|False|Infinity|NaN|Infinity|2017-01-02 03:04:05+09:00|\n    |  3|3.33|cccc|-3.0|ccc|True |Infinity|NaN|     NaN|2017-01-01 00:00:00+09:00|\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "8ebefe08cb130627de74e4cb191be4b238e49f23", "size": 45173, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/ipynb/pytablewriter_examples.ipynb", "max_stars_repo_name": "jvdvegt/pytablewriter", "max_stars_repo_head_hexsha": "29e8e7597d29c747354a64705313ad2e08013e4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/ipynb/pytablewriter_examples.ipynb", "max_issues_repo_name": "jvdvegt/pytablewriter", "max_issues_repo_head_hexsha": "29e8e7597d29c747354a64705313ad2e08013e4e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ipynb/pytablewriter_examples.ipynb", "max_forks_repo_name": "jvdvegt/pytablewriter", "max_forks_repo_head_hexsha": "29e8e7597d29c747354a64705313ad2e08013e4e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2808695652, "max_line_length": 1529, "alphanum_fraction": 0.4726495916, "converted": true, "num_tokens": 11695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14414884567931802, "lm_q2_score": 0.060086644703857287, "lm_q1q2_score": 0.008661420474804336}}
{"text": "<a href=\"https://colab.research.google.com/github/mveer1/Fake-News-Detection/blob/main/NLP.ipynb\" target=\"_parent\"></a>\n\n\n```python\ntry:\n    %cd /content\n    !git clone https://github.com/mveer1/Fake-News-Detection.git \nexcept:\n    !rm -r /content/Fake-News-Detection\n    !git clone https://github.com/mveer1/Fake-News-Detection.git \n\n# !git clone https://github.com/mveer1/Fake-News-Detection.git\n```\n\n    /content\n    Cloning into 'Fake-News-Detection'...\n    remote: Enumerating objects: 63, done.\u001b[K\n    remote: Counting objects: 100% (63/63), done.\u001b[K\n    remote: Compressing objects: 100% (44/44), done.\u001b[K\n    remote: Total 63 (delta 23), reused 44 (delta 16), pack-reused 0\u001b[K\n    Unpacking objects: 100% (63/63), done.\n\n\n\n```python\n# !rm -r /content/Fake-News-Detection\n```\n\n\n```python\n%cd /content/Fake-News-Detection/\n```\n\n    /content/Fake-News-Detection\n\n\n\n```python\nimport os\nos.chdir(\"/content/Fake-News-Detection/\")\n!pwd\n```\n\n    /content/Fake-News-Detection\n\n\nfuture==0.17.1\nh5py\nKeras\nKeras-Applications\nKeras-Preprocessing\nmatplotlib\nnvidia-ml-py\npandas\npython-apt\npython-dateutil==2.8.0\npython-debian\npython-slugify==3.0.3\npython-systemd\npytorch-pretrained-bert\npytorch-transformers==1.0.0\nscikit-image==0.14.2\nscikit-learn==0.20.2\nscipy\nseaborn==0.9.0\nsix\nsympy==1.4\ntqdm\n\n\n```python\n!pip install -r requirements.txt\n```\n\n    Requirement already satisfied: future==0.17.1 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 1)) (0.17.1)\n    Requirement already satisfied: h5py in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 2)) (3.1.0)\n    Requirement already satisfied: Keras in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 3)) (2.7.0)\n    Requirement already satisfied: Keras-Applications in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 4)) (1.0.8)\n    Requirement already satisfied: Keras-Preprocessing in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 5)) (1.1.2)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 6)) (3.2.2)\n    Requirement already satisfied: nvidia-ml-py in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 7)) (11.495.46)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 8)) (1.1.5)\n    Requirement already satisfied: python-apt in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 9)) (0.0.0)\n    Requirement already satisfied: python-dateutil==2.8.0 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 10)) (2.8.0)\n    Requirement already satisfied: python-debian in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 11)) (0.1.42)\n    Requirement already satisfied: python-slugify==3.0.3 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 12)) (3.0.3)\n    Requirement already satisfied: python-systemd in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 13)) (0.0.9)\n    Requirement already satisfied: pytorch-pretrained-bert in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 14)) (0.6.2)\n    Requirement already satisfied: pytorch-transformers==1.0.0 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 15)) (1.0.0)\n    Requirement already satisfied: scikit-image==0.14.2 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 16)) (0.14.2)\n    Requirement already satisfied: scikit-learn==0.20.2 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 17)) (0.20.2)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 18)) (1.4.1)\n    Requirement already satisfied: seaborn==0.9.0 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 19)) (0.9.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 20)) (1.15.0)\n    Requirement already satisfied: sympy==1.4 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 21)) (1.4)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 22)) (4.62.3)\n    Requirement already satisfied: text-unidecode==1.2 in /usr/local/lib/python3.7/dist-packages (from python-slugify==3.0.3->-r requirements.txt (line 12)) (1.2)\n    Requirement already satisfied: torch>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from pytorch-transformers==1.0.0->-r requirements.txt (line 15)) (1.10.0+cu111)\n    Requirement already satisfied: sentencepiece in /usr/local/lib/python3.7/dist-packages (from pytorch-transformers==1.0.0->-r requirements.txt (line 15)) (0.1.96)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pytorch-transformers==1.0.0->-r requirements.txt (line 15)) (2.23.0)\n    Requirement already satisfied: boto3 in /usr/local/lib/python3.7/dist-packages (from pytorch-transformers==1.0.0->-r requirements.txt (line 15)) (1.20.20)\n    Requirement already satisfied: regex in /usr/local/lib/python3.7/dist-packages (from pytorch-transformers==1.0.0->-r requirements.txt (line 15)) (2019.12.20)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from pytorch-transformers==1.0.0->-r requirements.txt (line 15)) (1.19.5)\n    Requirement already satisfied: PyWavelets>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image==0.14.2->-r requirements.txt (line 16)) (1.2.0)\n    Requirement already satisfied: cloudpickle>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from scikit-image==0.14.2->-r requirements.txt (line 16)) (1.3.0)\n    Requirement already satisfied: pillow>=4.3.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image==0.14.2->-r requirements.txt (line 16)) (7.1.2)\n    Requirement already satisfied: networkx>=1.8 in /usr/local/lib/python3.7/dist-packages (from scikit-image==0.14.2->-r requirements.txt (line 16)) (2.6.3)\n    Requirement already satisfied: dask[array]>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image==0.14.2->-r requirements.txt (line 16)) (2.12.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy==1.4->-r requirements.txt (line 21)) (1.2.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r requirements.txt (line 6)) (3.0.6)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r requirements.txt (line 6)) (1.3.2)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r requirements.txt (line 6)) (0.11.0)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->-r requirements.txt (line 8)) (2018.9)\n    Requirement already satisfied: toolz>=0.7.3 in /usr/local/lib/python3.7/dist-packages (from dask[array]>=1.0.0->scikit-image==0.14.2->-r requirements.txt (line 16)) (0.11.2)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch>=0.4.1->pytorch-transformers==1.0.0->-r requirements.txt (line 15)) (3.10.0.2)\n    Requirement already satisfied: cached-property in /usr/local/lib/python3.7/dist-packages (from h5py->-r requirements.txt (line 2)) (1.5.2)\n    Requirement already satisfied: chardet in /usr/local/lib/python3.7/dist-packages (from python-debian->-r requirements.txt (line 11)) (3.0.4)\n    Requirement already satisfied: s3transfer<0.6.0,>=0.5.0 in /usr/local/lib/python3.7/dist-packages (from boto3->pytorch-transformers==1.0.0->-r requirements.txt (line 15)) (0.5.0)\n    Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in /usr/local/lib/python3.7/dist-packages (from boto3->pytorch-transformers==1.0.0->-r requirements.txt (line 15)) (0.10.0)\n    Requirement already satisfied: botocore<1.24.0,>=1.23.20 in /usr/local/lib/python3.7/dist-packages (from boto3->pytorch-transformers==1.0.0->-r requirements.txt (line 15)) (1.23.20)\n    Requirement already satisfied: urllib3<1.27,>=1.25.4 in /usr/local/lib/python3.7/dist-packages (from botocore<1.24.0,>=1.23.20->boto3->pytorch-transformers==1.0.0->-r requirements.txt (line 15)) (1.25.11)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pytorch-transformers==1.0.0->-r requirements.txt (line 15)) (2021.10.8)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pytorch-transformers==1.0.0->-r requirements.txt (line 15)) (2.10)\n\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```python\n!cp '/content/drive/MyDrive/NLP/triBERT.pth' '/content/Fake-News-Detection/'\n```\n\n\n```python\n!python3 FakeNewsDetection.py -num_labels 6 -num_epochs 3 -load_model False\n```\n\n    /usr/local/lib/python3.7/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.\n      import pandas.util.testing as tm\n    INFO:pytorch_pretrained_bert.tokenization:loading vocabulary file https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt from cache at /root/.pytorch_pretrained_bert/26bc1ad6c0ac742e9b52263248f6d0f00068293b33709fae12320c0e35ccfbbb.542ce4285a40d23a559526243235df47c5f75c197f04f37d1a0c124c32c9a084\n    INFO:pytorch_pretrained_bert.modeling:loading archive file https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased.tar.gz from cache at /root/.pytorch_pretrained_bert/9c41111e2de84547a463fd39217199738d1e3deb72d4fec4399e6e241983c6f0.ae3cef932725ca7a30cdcb93fc6e09150a55e2a130ec7af63975a16c153ae2ba\n    INFO:pytorch_pretrained_bert.modeling:extracting archive file /root/.pytorch_pretrained_bert/9c41111e2de84547a463fd39217199738d1e3deb72d4fec4399e6e241983c6f0.ae3cef932725ca7a30cdcb93fc6e09150a55e2a130ec7af63975a16c153ae2ba to temp dir /tmp/tmpnenb59jc\n    INFO:pytorch_pretrained_bert.modeling:Model config {\n      \"attention_probs_dropout_prob\": 0.1,\n      \"hidden_act\": \"gelu\",\n      \"hidden_dropout_prob\": 0.1,\n      \"hidden_size\": 768,\n      \"initializer_range\": 0.02,\n      \"intermediate_size\": 3072,\n      \"max_position_embeddings\": 512,\n      \"num_attention_heads\": 12,\n      \"num_hidden_layers\": 12,\n      \"type_vocab_size\": 2,\n      \"vocab_size\": 30522\n    }\n    \n    cuda:0\n    Dataloader : <torch.utils.data.dataloader.DataLoader object at 0x7fda25642a90> \n    New statement input : tensor([[ 2311,  1037,  2813,  ...,     0,     0,     0],\n            [ 5273,  2003,  2006,  ...,     0,     0,     0],\n            [ 2758,  2198, 19186,  ...,     0,     0,     0],\n            ...,\n            [ 2758,  5401,  3867,  ...,     0,     0,     0],\n            [ 2006, 14079,  5918,  ...,     0,     0,     0],\n            [ 2758,  1996, 12163,  ...,     0,     0,     0]])\n    Justification input : tensor([[ 2311,  1037,  2813,  ...,     0,     0,     0],\n            [ 5273,  2003,  2006,  ...,     0,     0,     0],\n            [ 2758,  2198, 19186,  ...,     0,     0,     0],\n            ...,\n            [ 2758,  5401,  3867,  ...,     0,     0,     0],\n            [ 2006, 14079,  5918,  ...,     0,     0,     0],\n            [ 2758,  1996, 12163,  ...,     0,     0,     0]])\n    Meta data input : tensor([[11324,  1040,  4576,  2638,  1011,  8945,  3270,  2278,  2110,  4387,\n              3146,  3951,  1037,  5653,  2121,     0,     0,     0,     0,     0,\n                 0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n                 0,     0],\n            [ 2943,  1010,  2381,  1010,  3105,  1011, 17571,  3660,  1011,  7505,\n             21818,  3363,  2110, 11849,  3448,  7672,  1037,  2723,  4613,  1012,\n                 0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n                 0,     0],\n            [ 3097,  1011,  3343, 13857,  1011,  8112,  2343,  4307,  7672,  7573,\n                 0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n                 0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n                 0,     0],\n            [ 2740,  1011,  2729,  9927,  1011, 14739,  3904,  3904,  3904,  1037,\n              2739,  2713,     0,     0,     0,     0,     0,     0,     0,     0,\n                 0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n                 0,     0],\n            [ 4610,  1010,  5841,  4918,  1011, 13675,  2923,  3904,  3516,  7672,\n              2019,  4357,  2006, 13229,     0,     0,     0,     0,     0,     0,\n                 0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n                 0,     0],\n            [ 2495,  5863,  1011, 29536,  2015,  5273,  3320,  5882,  5273,  3951,\n              1037,  2019,  3784,  5448,  1011,  3538,     0,     0,     0,     0,\n                 0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n                 0,     0],\n            [ 5347,  1011,  8308,  3951,  1011,  2283,  1011,  3146,  3904,  3146,\n              3951,  1037,  2811,  2713,  1012,     0,     0,     0,     0,     0,\n                 0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n                 0,     0],\n            [ 9615, 13857,  1011,  8112,  2343,  4307,  7672,  1037,  3537,  5981,\n              1999,  4407,  1010,  6643,  1012,     0,     0,     0,     0,     0,\n                 0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n                 0,     0],\n            [ 5841,  5392,  1011, 15213,  3904,  3904,  3029,  1037,  4037,     0,\n                 0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n                 0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n                 0,     0],\n            [ 2943,  1010,  4471,  1011,  3698,  1011,  2297,  1010,  6830,  1011,\n              2501,  2349,  2100,  1011,  2358,  3217, 15878,  2884,  2110,  4387,\n              5273,  3951,  2019,  3784,  2678,     0,     0,     0,     0,     0,\n                 0,     0],\n            [ 3864,  2728,  1011,  2273, 28787,  1057,  1012,  1055,  1012,  5205,\n              2047,  3933,  7672,  1037,  4613,     0,     0,     0,     0,     0,\n                 0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n                 0,     0],\n            [ 4610,  1010,  5841,  1010,  2047,  1011,  7035,  1011,  2262,  1010,\n              5635, 15941,  1011,  1055,  1057,  1012,  1055,  1012,  5205,  8839,\n              2981,  1037,  1056, 28394,  2102,     0,     0,     0,     0,     0,\n                 0,     0],\n            [ 2381,  1010,  2110,  1011,  5166, 10210,  2102,  1011, 19615,  2280,\n              3099,  4404,  3951,  2019,  4357,  2007, 21824,  2739,     0,     0,\n                 0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n                 0,     0],\n            [ 4610,  1010,  2976,  1011,  5166,  1010,  2740,  1011,  2729, 20160,\n              5267,  4917,  3904,  3904,  3904,  1037, 20160,  5267,  4917,  6167,\n              1999,  1996,  4465,  5888,     0,     0,     0,     0,     0,     0,\n                 0,     0],\n            [ 2740,  1011,  2729,  2577,  1011,  2097, 13317,  5374, 13317,  7928,\n              2006,  1000,  4419,  2739,  4465,  1000,     0,     0,     0,     0,\n                 0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n                 0,     0],\n            [ 3864, 15941,  1011,  1055,  1057,  1012,  1055,  1012,  5205,  8839,\n              2981,  1037,  2237,  2534,  1999,  5899,  1010,  3146,     0,     0,\n                 0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n                 0,     0]])\n    Credit scores input : tensor([[0.6510, 0.6510, 0.6510,  ..., 0.6510, 0.6510, 0.6510],\n            [0.8000, 0.8000, 0.8000,  ..., 0.8000, 0.8000, 0.8000],\n            [0.7477, 0.7477, 0.7477,  ..., 0.7477, 0.7477, 0.7477],\n            ...,\n            [0.7702, 0.7702, 0.7702,  ..., 0.7702, 0.7702, 0.7702],\n            [0.6417, 0.6417, 0.6417,  ..., 0.6417, 0.6417, 0.6417],\n            [0.6849, 0.6849, 0.6849,  ..., 0.6849, 0.6849, 0.6849]])\n    Fakeness : tensor([[1, 0, 0, 0, 0, 0],\n            [0, 0, 0, 0, 1, 0],\n            [0, 0, 0, 0, 1, 0],\n            [0, 0, 1, 0, 0, 0],\n            [0, 0, 0, 0, 0, 1],\n            [1, 0, 0, 0, 0, 0],\n            [1, 0, 0, 0, 0, 0],\n            [0, 0, 0, 1, 0, 0],\n            [1, 0, 0, 0, 0, 0],\n            [0, 0, 0, 1, 0, 0],\n            [0, 0, 0, 1, 0, 0],\n            [0, 0, 0, 1, 0, 0],\n            [0, 0, 0, 0, 0, 1],\n            [0, 0, 0, 0, 1, 0],\n            [0, 0, 1, 0, 0, 0],\n            [1, 0, 0, 0, 0, 0]])\n    Traceback (most recent call last):\n      File \"FakeNewsDetection.py\", line 575, in <module>\n        test_model(model)\n      File \"FakeNewsDetection.py\", line 541, in test_model\n        output = F.softmax(model(inputs1, inputs2, inputs3, inputs4))\n      File \"/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py\", line 1102, in _call_impl\n        return forward_call(*input, **kwargs)\n      File \"FakeNewsDetection.py\", line 320, in forward\n        output1 = self.forward_once(input_ids1, token_type_ids=None, attention_mask=None, labels=None)\n      File \"FakeNewsDetection.py\", line 312, in forward_once\n        _, pooled_output = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False)\n      File \"/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py\", line 1102, in _call_impl\n        return forward_call(*input, **kwargs)\n      File \"/usr/local/lib/python3.7/dist-packages/pytorch_pretrained_bert/modeling.py\", line 730, in forward\n        embedding_output = self.embeddings(input_ids, token_type_ids)\n      File \"/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py\", line 1102, in _call_impl\n        return forward_call(*input, **kwargs)\n      File \"/usr/local/lib/python3.7/dist-packages/pytorch_pretrained_bert/modeling.py\", line 267, in forward\n        words_embeddings = self.word_embeddings(input_ids)\n      File \"/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py\", line 1102, in _call_impl\n        return forward_call(*input, **kwargs)\n      File \"/usr/local/lib/python3.7/dist-packages/torch/nn/modules/sparse.py\", line 160, in forward\n        self.norm_type, self.scale_grad_by_freq, self.sparse)\n      File \"/usr/local/lib/python3.7/dist-packages/torch/nn/functional.py\", line 2044, in embedding\n        return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse)\n    RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! (when checking argument for argument index in method wrapper__index_select)\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "aeeed21bb39140eb09a093912ed92f95b049dc44", "size": 26304, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "NLP.ipynb", "max_stars_repo_name": "mveer1/Fake-News-Detection", "max_stars_repo_head_hexsha": "426d81a2fc829610441d902f16e42c1ec00e2ce8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-05T07:17:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T07:17:20.000Z", "max_issues_repo_path": "NLP.ipynb", "max_issues_repo_name": "mveer1/Fake-News-Detection", "max_issues_repo_head_hexsha": "426d81a2fc829610441d902f16e42c1ec00e2ce8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NLP.ipynb", "max_forks_repo_name": "mveer1/Fake-News-Detection", "max_forks_repo_head_hexsha": "426d81a2fc829610441d902f16e42c1ec00e2ce8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-05T07:17:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-05T07:17:25.000Z", "avg_line_length": 57.810989011, "max_line_length": 337, "alphanum_fraction": 0.5013305961, "converted": true, "num_tokens": 7146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1895210821742346, "lm_q2_score": 0.04535257636078895, "lm_q1q2_score": 0.008595269351286332}}
{"text": "> *This textbook was generated automatically from a [GitHub Repo](https://github.com/Hribek25/IOTA101). Visit the repo for more information.* \n\n\n# IOTA Developer Essentials\n[](https://hribek25.github.io/IOTA101/devlab.html#Language-Coverage)\n[](https://github.com/Hribek25/IOTA101)\n[](https://gist.github.com/search?utf8=%E2%9C%93&q=IOTA101)\n[](https://hribek25.github.io/IOTA101/devlab.html)\n[](https://hribek25.github.io/IOTA101/)\n[](https://ecosystem.iota.org/tutorials/iota-developer-essentials)\n\nThese notebooks provide a self-study introduction to IOTA protocol and are designed for developers and tech enthusiasts who would like to get quickly familiar with the IOTA. Technical-related information is accompanied with interactive code snippets to help you to quickly jump on the platform and be ready to build own solutions based on it.\n\n> Motto of this tutorial: \"Let's start with baby steps before we can try and fly.\"\n\n## Main Goal\nMain goal of this guide is to provide a comprehensive yet well-balanced proportion of deep-dive technical information and essentials.\n\n## Getting Started\nThere are several chapters available. If you are not familiar with IOTA then it is highly recommended to follow them in the particular order to understand all important IOTA concepts properly. Otherwise you may get quickly confused later.\n\n## Code Snippets\nCode snippets are currently based on Python, NodeJs and C#. Since Python is very descriptive language and easy to understand, I believe the tutorial is basically understandable to anyone. Anyway, all important IOTA concepts are described in language-agnostic way and so you would be able to use any language of your choice.\n\nInterested to see what is the overall code base coverage breaked down to a specific language? The following page provides you such an info. Needless to say, we are working hard to be sure there is no language that would be a second-class citizen.\n\n[](https://hribek25.github.io/IOTA101/devlab.html#Language-Coverage)\n\nIOTA Developer Essentials are accompanied by *IOTA Developer Lab* and so you can play with all code snippets directly in your web browser. Feel free to experiment with the prepared code snippets and get your hands dirty. It is a best way how to get familiar quickly.\n\n[](https://hribek25.github.io/IOTA101/devlab.html)\n\nAll *standalone* code snippets are also maintained @ GitHub Gist. It enables you to fork them, comment them, share them, embed them and track all changes to them. See the action panel next to each code snippet.\n\n[](https://gist.github.com/search?utf8=%E2%9C%93&q=IOTA101)\n\n## Viewing and running\n### Interactive Mode\nThere exists a side project called *IOTA Developer Lab* that is built on top of *IOTA Developer Essentials*. The project provides infrastructure services for you to be able to get an interactive experience with all code snippets.\n\n[](https://hribek25.github.io/IOTA101/devlab.html)\n\n### Static Mode\nIf you prefer a static experience (for printing purposes, for instance) you can reach the given notebooks as a Complete Textbook that is compiled from all source materials:\n\n[](https://hribek25.github.io/IOTA101/)\n\nEverything is tightly linked together and so you can easily switch between different languages for instance, or you can share links to specific chapters, code snippets, etc. All links are static so feel free to share them.\n\n\n## Feedback and corrections\nThese notebooks are maintained at [GitHub](https://github.com/Hribek25/IOTA101).\nIssues can be submited via [issue tracker](https://github.com/Hribek25/IOTA101/issues).\n\n## About\nThese notebooks are developed and maintained by Petr Zizka (petr@zizkovi.name). It has been supported by the EDF Grant (https://blog.iota.org/the-5th-cohort-of-iota-ecosystem-development-fund-grantees-5cbf05227525).\n\nIt is ongoing process since IOTA is still under heavy development and rapidly emerging every day. So stay tuned - the plan is to keep adding fresh content on regular basis.\n\nFeel free to follow me at [Twitter](https://twitter.com/petrzizka) or IOTA Discord Channel (@hribek25#2683).\n*(New to Discord? Invitation link: https://discord.gg/fNGZXvh)*\n\nDisclaimer: I am not associated with the IOTA foundation. I am IOTA supporter.\n\n----\n\n\nThe IOTA Developer Essentials and IOTA Developer Lab are long-term projects. The main goal is to provide a comprehensive onboarding information to anybody interested in the IOTA protocol. It will cover much more chapters, more code snippets and it will also cover more languages. Your kind donations will support the vision pushing forward. Thank you.\n\nDonations (IOTA):\nDSZRO9TCIJIKZOKUPVNOJFKVAHFCKL9YMLPVZUAEVZPOFXLIUWLPRQWBMVVSFTKGMGPPHXCYE9MIZEVBXQNFYKYUA9\n\n\n\n\n--- \n\n\n# IOTA 101: Essentials and IOTA Terminology\nIOTA is an open-source Distributed Ledger Technology (DLT) with the following characteristics: *permissionless*, *feeless* and *trustless*. In contrary to the blockchain technology, the IOTA transactions are stored in a form of Directed Acyclic Graph (DAG) called *the Tangle*.\n\n\n## Transactions\nTransactions (TXs) in the tangle can be of two types:\n* **Value transactions** (*IOTA token* represents funds in case of value transactions)\n* **Zero-value transactions** (aka meta transactions)\n\nEvery transaction is attached to a specific *IOTA Address*.\nThere are no miners with IOTA protocol to validate transactions. The *consensus* is achieved by network participants themselves. Each participant that wants to broadcast a new transaction has to approve 2 past transactions and basically attach transaction as a children node. Transactions without children transactions (waiting to be confirmed) are called *tips*.\n\n## Seed, private key and address\nPair of unique IOTA address and corresponding *Private Key* is determistically generated from a *Seed*. You can generate (2<sup>53</sup> - 1) different addresses/private keys based on one Seed. Anybody can send anything to the given address however only Seed owner can send funds from IOTA address since only the Seed owner is able to generate corresponding *Private Key*.\n\nIOTA protocol uses One-Time Signature (OTS) for \"verifying\" whether private key matches to the given address, specifically Winternitz OTS (WOTS). So *Private Key* (specifically *Key Fragments* of the private key) is the key component while signing transactions using WOTS.\n\nThat's the reason why nobody should use IOTA address that have been already funds spent from. New IOTA address (of the given seed) should be generated and used instead. Please note, it applies only to fund-spending. Receiving funds/data is totaly fine even multiple times.\n\nTo summarize the key concept here. Only *Seed* is needed to be stored somewhere. Everything else can be safely generated from it: private key as well as address.\n\n## IOTA nodes\nThe Tangle runs on a *distributed network* of IOTA nodes called *mainnet*. There are also other separate \"Tangles\" serving for specific purposes: Devnet, SPAMnet, etc. You can interact with the network via public nodes using collection of public *API calls*. You can interact with any public node of the given network since all nodes \"gossiping\" all TXs across the whole network. Nodes are powered by a reference piece of software called *IRI* (IOTA Reference Implementation) **as of now**.\n\nIt is also important to mention that you do not exchange any sensitive information such as *Seed* with a node. Every sensitive operation such as TX signing is done on client's side and node is just a \"messenger\" that delivers your TX to the IOTA network.\n\n\n## Custom node\nYou can even run own IOTA node and actively participate to the whole network. There is a big advantage for developers in that case. Actual implementation of IRI  provides an usefull real-time information via messaging platform called ZeroMQ and so developers can leverage that.\n\n## API calls\nThere are ready-made libraries for major programming languages available and so you have more developer-friendly way how to interact with the IOTA network. Anyway, you can interact with IOTA network using pure API calls without any library. It is up to you.\n\n\n## Ternary\nIt is difficult to avoid mentioning *Ternary numeral system* while discussing IOTA at all. IOTA is based on ternary system under the hood and so you have got to be aware of some basic terminology in this respect. You are going to face this fact in any developer-related IOTA guide out there.\n\n### Ternary\nTernary has three as its base (aka base 3) as opposted to *binary* which is base 2. Instead of two states (0 and 1) it recognizes three states (for ex. -1, 0, 1).\n\n### Trit\nOne *Trite* is analogous to one *bit*. It is the smallest digit and has three states. Trit = **Tri**nary dig**it**.\n\n### Tryte\n*Tryte* consists of three *trits* meaning 27 combinations.\n$$3^3=27$$\n\nYou will recognize soon that almost everything is encoded in *Trytes* in the IOTA world. Tryte is visually represented using [A..Z] alphabets and number 9. One character represents one tryte (here comes 27 possible characters again). *Don't get mad, IOTA libraries are going to help us.*\n\nSmall example:\n\n\n```javascript\nvar Converter = require('@iota/converter') //loading helping converter module of iota.js library. More info: https://github.com/iotaledger/iota.js/tree/next/packages/converter#module_converter.trits\n\nvar Trytes = \"YZJEATEQ9JKLZ\" //some data encoded in Trytes\nconsole.log(Trytes)\nconsole.log(\"Number of Trytes: %s\" , Trytes.length)\n\nvar Trits = Converter.trits(Trytes) //converting Trytes to Trits\n\nconsole.log(Trits.join(\",\"))\nconsole.log(\"Number of trits: %s\", Trits.length) //Number of trits is three times the number of trytes obviously\n```\n\n    YZJEATEQ9JKLZ\n    Number of Trytes: 13\n    1,-1,0,-1,0,0,1,0,1,-1,-1,1,1,0,0,-1,1,-1,-1,-1,1,-1,0,-1,0,0,0,1,0,1,-1,1,1,0,1,1,-1,0,0\n    Number of trits: 39\n\n\n# IOTA 101: Basic network interactions\nThe tutorial is based on IOTA libraries called *PyOTA* for Python, *IOTA Javascript Library (@iota/core)* for JavaScript and Tangle.Net for C# (.NET 4.x and .NET Standard). It encapsulates all official IRI API calls and it can be installed via `pip` in Python environment, via `npm` in JS environment and via `NuGet` in case of .NET environment.\n\nReader is also encouraged to try a ready-made environment via *IOTA Developer Lab* project (at lab.iota101.info) where anyone can run a code directly in a web browser. When viewing it interactively then just select a code snippet and hit `ctrl + enter` which executes it.\n\nAnyway, most of the information in the tutorial is language-agnostic and so only particular interfaces slightly differ across different IOTA libraries. Top-level details are the same regardless programming language you are going to use.\n\n## A few words about specific IOTA libraries\n### Python\n*PyOTA* is well maintained and understandable IOTA library that can be reached at https://github.com/iotaledger/iota.lib.py. It is very good starting point for beginners.\nIt can be installed via `pip`:\n```pip install pyota```\n\n### JavaScipt\nOfficial IOTA Javascript library (v1.0) is currently in beta however all main functions are working just fine, please see https://github.com/iotaledger/iota.js/. It is very modular and so you can install only components you really need.\n\nMain component is @iota/core and can be installed via `npm`:\n```npm install @iota/core```\n\nAs with everything in NodeJS, most of the tasks are asynchronous and they are chained via `callbacks` or `promise`. Snippets below leverage `promise` chaining.\n### C# (.NET)\n*Tangle.Net* is well maintained IOTA library for .NET and can be reached at https://github.com/Felandil/tangle-.net.\nIt can be installed via `NuGet`:\n```nuget.exe install tangle.net```\n\nSnippets below uses synchronous functions however the library provides also asynchronous (async postfix) version.\n\n\n## Conneting to IOTA nodes\nBefore you can interact with the IOTA network you need an URL of the running IOTA node. There are dozen of directories of public nodes available, feel free to google them.\n\nFor a sake of this tutorial I use a project *thetangle.org*. It is a load ballancer that provides you an access to a pool of participanting nodes effortlessly.\n* *Advantage:* you do not have to care about public nodes and whether they are running or not\n* *Disadvantage:* you do not know in advance which specific node will process your API call. So in some respect results of API calls may differ since some API calls depend on specific node, such as GetNodeInfo().\n\n### Node is not synced\nEven if a node is up and running it may not be fully prepared to process your API calls correctly. The node should be \"synced\", meaning should be aware of all TXs in the Tangle. It is better to avoid not fully synced nodes.\n\n### Health checking\nOnce you connect to an IOTA node you should be able to send API calls. However it is better to do some checks in advance in order to find out whether the given node is in good condition or not. IOTA nodes can be run by anyone and so health check is always a good practice.\n\nBasic healthcheck can be done via *GetNodeInfo()* API call. It returns a basic information about the given IOTA node.\n\n\n```javascript\nvar iotalib = require('@iota/core'); // loading iota.js core module. More info: https://github.com/iotaledger/iota.js/tree/next/packages/core\n\n// composerAPI initialization of the iota.js library\nvar iota = iotalib.composeAPI({\n    'provider': 'https://nodes.thetangle.org:443'\n});\n\n// basic API call to double check health conditions\nvar promise = iota.getNodeInfo()\n                    .then(info => {\n                        console.log(info);\n                        // Basic check whether node is in sync or not\n                        // Elementary rule is that \"latestMilestoneIndex\" should equal to \"latestSolidSubtangleMilestoneIndex\" or be very close\n                        if (Math.abs(info['latestMilestoneIndex'] - info['latestSolidSubtangleMilestoneIndex']) > 3) {\n                            console.log('\\r\\nNode is probably not synced!');\n                        } else {\n                            console.log('\\r\\nNode is probably synced!');\n                        }\n                    })\n                    .catch(error => {\n                        console.log('Request error: ${error.message}')\n                    });\n\n```\n\n    { appName: 'IRI',\n      appVersion: '1.8.1',\n      jreAvailableProcessors: 16,\n      jreFreeMemory: 1551948936,\n      jreVersion: '1.8.0_191',\n      jreMaxMemory: 20997734400,\n      jreTotalMemory: 3582733719,\n      latestMilestone:\n       'QBUS9SXTQTJWRTWHQWTEPBZBFFXJANQGZQSDSICRZQAD9PTKGTFKV9NEPZCLXLRIPIMWJ9OCTCKZZ9999',\n      latestMilestoneIndex: 1173627,\n      latestSolidSubtangleMilestone:\n       'QBUS9SXTQTJWRTWHQWTEPBZBFFXJANQGZQSDSICRZQAD9PTKGTFKV9NEPZCLXLRIPIMWJ9OCTCKZZ9999',\n      latestSolidSubtangleMilestoneIndex: 1173627,\n      milestoneStartIndex: 1157888,\n      lastSnapshottedMilestoneIndex: 1173525,\n      neighbors: 24,\n      packetsQueueSize: 0,\n      time: 1568362132124,\n      tips: 7924,\n      transactionsToRequest: 0,\n      features: [ 'loadBalancer', 'snapshotPruning', 'RemotePOW' ],\n      coordinatorAddress:\n       'EQSAUZXULTTYZCLNJNTXQTQHOMOFZERHTCGTXOLTVAHKSA9OGAZDEKECURBRIXIJWNPFCQIOVFVVXJVD9',\n      duration: 0 }\n    \n    Node is probably synced!\n\n\n*Please note: When using node load balancers then this type of check is quite useless since other API calls of yours may be served by different node that may have not been checked. You should be aware of it and trust that the load balancer participates only with nodes that are in a good condition.*\n\n## Generating IOTA seed and IOTA address\nSince the IOTA network is *permissionless* type of network, anybody is able to use it and interact with it. No central authority is required at any stage. So anybody is able to generate own seed and respective private key/address anytime. It is highly recommended to *NOT* use online generators at all.\n\nThe Seed is the only key to the given addresses. Anyone who owns the Seed owns also all funds related to respective IOTA addresses (all of them).\n\nSeed and addresses only consists of characters [A-Z] and number 9. Length is always 81 charaters. There are usually also used additional 9 characters in IOTA addresses (so total lenght is 90 then) which is a *checksum*. It provides a way how to prevent typos while manipulating with IOTA addresses.\n\n\n### Seed\nA seed generation is a process that is based on random quessing of each character in the seed. Of course, you should always use cryptographically secure pseudo-random generator!\n\n\n```javascript\n//based on https://gist.github.com/SteveFromTheOffice/c8448a09352337386f135a16bbb20d93\n//modified by Petr Zizka\n    \nvar GenerateSeed = function () {\n    const length       = 81;                            // The length of the seed and int array.\n    const chars        = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ9\"; // The allowed characters in the seed.\n    var result       = new Array(length);               // An empty array to store the seed characters.\n    var randomValues = Buffer.alloc(length)\n    \n    // Generate random values and store them to array.\n    crypto.randomFillSync(randomValues);\n    \n    var cursor = 0;                                     // A cursor is introduced to remove modulus bias.\n    for (var i = 0; i < randomValues.length; i++) {     // Loop through each of the 81 random values.\n        cursor += randomValues[i];                      // Add them to the cursor.\n        result[i] = chars[cursor % chars.length];       // Assign a new character to the seed based on cursor mod 27.\n    }\n    return result.join('');                             // Merge the array into a single string and return it.\n};\n\nvar NewSeed = GenerateSeed();\nconsole.log(NewSeed);\nconsole.log(\"Length: %s\", NewSeed.length)\n```\n\n    IPNYMDAUYFXLBAIICBSNODJZNYWKPCORLQVYRFIKTKTLGKUXLINB99EUZRKKPOKS9MGJBYTJTRNNRXPZD\n    Length: 81\n\n\nAlternatively you can leverage also PyOTA library since it has own implementation of the pseudo-random Seed generator (Python 2.7+ compatible). Difference between both methods is very subtle. I just wanted to illustrate both ways: Fully independent and IOTA-library-dependant. *Please note, IOTA Javascript library does not support a seed generation.*\n\n\n```javascript\n// No code snippet available for the selected language: javascript\n```\n\n### Address\nThere is a deterministic function how to get an address from a seed. It is a basically an indexed collection of addresses starting with address at index 0, 1, 2, etc.\n\nWhile generating addresses you should be also aware there are three different so called *Security Levels* (1, 2 and 3). Each security level generates totally independent pool of addresses. Addresses of Security Level 1 are totally different from addresses of Security Level 2, etc.\n\nIn a nutshell, Security Level indicates how difficult is to generate *Private key* from the Seed and also what is its size. The higher security level, the more secure (longer) is the given private key. Default Security Level is 2. Most of IOTA wallets uses Security Level=2 and users are usually not allowed to change it. So be carefull while designing your app.\n\nAs long as *seed, address index and security level* are the same, you always get the same address and corresponding private key:\n\n$$PrivateKey/Address = fce(Seed, AddressIndex, SecurityLevel)$$\n\nGeneral example:\n$$PrivateKey/Address1 = fce(Seed, 1, 2)$$\n$$PrivateKey/Address2 = fce(Seed, 2, 2)$$\n$$PrivateKey/Address3 = fce(Seed, 3, 2)$$\n\n\n\n\n```javascript\nvar iotalib = require('@iota/core');\n\nvar NodeURL = \"https://nodes.thetangle.org:443\";\nvar MySeed = \"WKQDUZTGFKSSLACUCHHLZRKZBHSDSCEBHKUPDLKFBQALEBKDMFRPUQGZRXAADPG9TSRTZGGBZOFRJCFMM\";\n\nvar iota = iotalib.composeAPI({\n    'provider': NodeURL\n});\n\n//Let's generate 3 addresses using default security level=2.\n//It is a deterministic function - it always generates same addresses as long as the Seed, Security Level and Index are the same\n//In case of iota.js library, it additionally checks generated addresses against the Tangle whether the address was spent from\n//So the following snippet leverages also API calls against a node\n//Please also note that generating addresses can take quite long\nvar promise = iota.getNewAddress(MySeed, { index: 0, total: 3, returnAll: true } )\n                .then(address => {\n                    console.log();\n                    console.log(address); //returned addresses are printed out    \n                })\n                .catch(error => {\n                    console.log(\"Error occured: %s\", error);                \n                });\n```\n\n    `GetNewAddressOptions`: 3,true options are deprecated and will be removed in v.2.0.0. \n    \n\n\n    \n    [ 'HRLKBQUZAEB9HIVWJEWVDYQ9G9VRQXQAXR9ZWGBFQJKRPOPJYHGAT9LBEIE9RWRMUFSNLCWYHQGYAECHD',\n      'XEXIDJJTANADOUBPWTCSPPRYYRTITRAHDEOZAEXWDPCYKUPTFMKVQM9KCPPLOCESFRGRVSIYZHXQZNYKC',\n      'KY9DLZCHET9ATLMADPXGDVDYMPHKRKQPJZ9MB9HEIMMFCRRTNJIJIHPKGZNKKDTFMYPZRRQYAQKVAHMYX' ]\n\n\nPlease note, some IOTA libraries may communicate with a IOTA network while generating addresses to double check whether the given address was used or not.\n\nSo it is sometimes better to use directly an address generator component. Outputs are equivalent in both cases but the latter one usually only generates pool of addresses locally:\n\n\n```javascript\nvar iotalib = require('@iota/core');\n\nvar MySeed = \"WKQDUZTGFKSSLACUCHHLZRKZBHSDSCEBHKUPDLKFBQALEBKDMFRPUQGZRXAADPG9TSRTZGGBZOFRJCFMM\";\n\n//Please note, it is a sync function call\n//Please also note that generating addresses can take quite long\n//The given addresses are generated locally regardless the Tangle state\nfor (var i = 0; i < 3; i++ ) {\n    var address = iotalib.generateAddress (MySeed, i, 2, false); //seed, index, security, checksum\n    console.log(address);\n}\n```\n\n    HRLKBQUZAEB9HIVWJEWVDYQ9G9VRQXQAXR9ZWGBFQJKRPOPJYHGAT9LBEIE9RWRMUFSNLCWYHQGYAECHD\n    XEXIDJJTANADOUBPWTCSPPRYYRTITRAHDEOZAEXWDPCYKUPTFMKVQM9KCPPLOCESFRGRVSIYZHXQZNYKC\n    KY9DLZCHET9ATLMADPXGDVDYMPHKRKQPJZ9MB9HEIMMFCRRTNJIJIHPKGZNKKDTFMYPZRRQYAQKVAHMYX\n\n\n## Validating IOTA address\nAs mentioned earlier, IOTA address consists of 81 trytes ([A..Z9] characters) or 90 trytes including checksum. Checksum is useful when you want to make sure a valid address was given (no typos, etc.) and so it is a good practise to encourage user of your app using IOTA addresses including checksums = 90 trytes.\n\nIOTA libraries are able to help you to deal with some basic patterns such as validating addresses, generating checksums, etc.\n\n\n```javascript\nvar iotalib = require('@iota/checksum'); //this package is also useful when validating an address\n\n//some IOTA address\nvar Adr = \"CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\";\n\nconsole.log(\"Original input excl. checksum address:\");\nconsole.log(Adr);\nconsole.log(\"Length: %s\", Adr.length)\n\nvar AdrInclCheckSum = iotalib.addChecksum(Adr); //generate checksum for the given address\nconsole.log(\"Input address including checksum:\")\nconsole.log(AdrInclCheckSum) // the last 9 trytes is the checksum\nconsole.log(\"Length incl checksum: %s\", AdrInclCheckSum.length)\n```\n\n    Original input excl. checksum address:\n    CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\n    Length: 81\n    Input address including checksum:\n    CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RWTHBIRSXTA\n    Length incl checksum: 90\n\n\nYou should always make sure your app is dealing with valid IOTA address. Please note, you should also make sure an address is of correct length and consists only of allowed characters. IOTA libraries may slightly differ in their approaches but differences are very subtle and both libraries provide enough functions to validate IOTA address.\n\nGeneral steps should be:\n* Checks length\n* Checks valid characters\n* Checks address against its checksum\n\n\n```javascript\nvar iotalib = require('@iota/checksum');\nvar iotaValidators = require('@iota/validators');\n\n//address including checksum\nvar InputAddr = \"CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RWTHBIRSXTA\";\n\nif (!iotaValidators.isAddress(InputAddr) || InputAddr.length!=90) {\n    console.log(\"Not valid input address given.\");    \n} else {\n    console.log(\"Input address incl checksum:\");\n    console.log(InputAddr);\n\n    console.log(\"Is it valid addr based on checksum? %s\", iotalib.isValidChecksum(InputAddr));\n    console.log(\"Input address excl checksum:\");\n    console.log(iotalib.removeChecksum(InputAddr));\n}\n```\n\n    Input address incl checksum:\n    CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RWTHBIRSXTA\n    Is it valid addr based on checksum? true\n    Input address excl checksum:\n    CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\n\n\n# IOTA 101: Transactions\nA transaction is a smallest piece of data that can be broadcasted to the network. Each transaction consists of fixed 2673 trytes. Transactions (TXs) are basically of two types:\n* **Value TXs:** those transactions change ownership of IOTA tokens. Two possible states: spending TXs or receiving TXs\n* **Non-Value TXs:** those transactions include piece of data that can be broadcasted and read from the Tangle\n\nTransactions are broadcasted in an envelope called *Bundle*. Bundle may consist of multiple TXs. Bundle is processed by the Tangle as a single entity; meaning only the whole bundle is confirmed by the network (and all TXs within) or nothing. You have to prepare a bundle even if you broadcast single transaction only. Bundle is also described as *atomic* since every bundle includes all information needed to process it antonomously.\n\nEach transaction includes several fields, let's name the most important ones:\n* **`Value`:** Value can be *positive* number = receiving IOTA tokens, *negative* number = spending IOTA tokens or *zero* = broadcasting only piece of data\n* **`Address`:** It is IOTA address that is associated with the given transaction. *Value* indicates whether it is an address of a receiver or a sender\n* **`Tag`:** It is an user-defined tag that can be used for searching, etc.\n* **`SignatureMessageFragment`:** This is the most lenghty attribute (2187 trytes) and could include: *transaction signature* based on private key in case it is a spending TX or *piece of data (message)* in case it is non-value TX. Alternatively it can be also left blank (in case of non-value TXs)\n* **`TrunkTransaction` / `branchTransaction`:** Those two fields refer to some previous transactions in the Tangle (tips) that the given bundle is going to approve\n* **`Timestamp`:** TX timestamp. It is actually UNIX timestamp (UTC)\n\n\nA process of sending IOTA transaction can be summarized in 5 steps:\n* To create transation(s) with the given attributes: *value*, *address* and potentially also *tag* or *message*\n* To finalize a bundle that includes all transactions. Once the bundle is finalized no new transactions can be added. It basically means to generate a *bundle hash*\n* To search for two tips in the Tangle that you are going to validate. There is not a strict rule how to search them but it is generally recommended to leave it on a *tip selection algorithm* implemented on node's side \n* To do a *Proof-of-Work* for each transaction in the bundle. Result of POW is *Nonce* and *Transaction hash* stored with each transaction\n* Finally you need to *broadcast* the whole bundle to the network\n\n### A secret of a bundle\nThere is a secret to be shared. You have to understand one important thing. Bundle is a top level construct that link all related transactions under one entity however the bundle itself is not broadcasted in fact. You still broadcast \"only\" collection of individual transactions instead. All transactions are recognized to be part of a bundle by the IOTA protocol however any data peering is based on individual transactions (in trytes).\n\nIn other words, a bundle can be reconstructed anytime from a collection of transactions via fields `bundle hash`, `current index` and `last index`.\n\n## Non-value transactions\nLet's start with non-value transactions (meta transactions) first since they are a bit easier for starters.\n\n*Please note, the chapter is divided in two separate sections. In the first section, examples are really close to bare metal (still not too close:) to illustrate the whole process and describing implementation details wherever possible. It is also useful when you want to experiment with different settings at each step (hey \"non-existing tips\", looking at you).*\n\n*In the second section, IOTA-facing libraries are fully levearged since they are capable to hide all implementation details behind a curtain. Needless to say, if you are not interested in such details then you would probably like to start with the second section.*\n\n### Creating and broadcasting transaction in 5 steps (you want to understand the process)\n#### Create a transaction\nFirst of all let's create transactions (offline; in memory) and set main fields.\n\nBTW: `Timestamp` field is defined automatically by the IOTA-facing libraries in the process. It is important field while creating `bundle hash`.\n\nIn the examples within this chapter we are going to broadcast meta transactions (data only) to two different IOTA addresses.\n\n\n```javascript\nvar iotalib = require('@iota/core');\nvar Converter = require('@iota/converter')\nvar NodeURL = \"https://nodes.thetangle.org:443\";\n\nvar iota = iotalib.composeAPI({\n    'provider': NodeURL\n});\n\nvar MySeed = \"HGW9HB9LJPYUGVHNGCPLFKKPNZAIIFHZBDHKSGMQKFMANUBASSMSV9TAJSSMPRZZU9SFZULXKJ9YLAIUA\";\nvar TargetAddress1 = \"CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\";\nvar TargetAddress2 = \"CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\";\n\nvar NowIs = new Date() //get a actual date & time - just to have some meaningfull info\n\n// preparing transactions\nvar pt = {\n    'address': TargetAddress1, //81 trytes long address\n    'value': 0,\n    'message': Converter.asciiToTrytes('Here comes a first message. Now is ' + NowIs),\n    'tag': 'HRIBEK999IOTA999TUTORIAL' //Up to 27 trytes\n}\n\nvar pt2 = {\n    'address': TargetAddress2, //81 trytes long address\n    'value': 0,\n    'message': Converter.asciiToTrytes('Here comes a second message. Now is ' + NowIs),\n    'tag': 'HRIBEK999IOTA999TUTORIAL' //Up to 27 trytes\n}\n\nconsole.log(\"Created transaction objects - mandatory fields only:\")\nconsole.log(pt)\nconsole.log(pt2)\n```\n\n    Created transaction objects - mandatory fields only:\n    { address:\n       'CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9',\n      value: 0,\n      message:\n       'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAPBFDXCEABCTCDDEAVAXAEAWAUAVACBEAVAUADBWAVADBWAZAEAQBWBCCPAUAWAUAUAEAMAMBTCBDHDFDPC9DEAOBIDFDCDDDTCPCBDEABCIDADADTCFDEACCXCADTCNA',\n      tag: 'HRIBEK999IOTA999TUTORIAL' }\n    { address:\n       'CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW',\n      value: 0,\n      message:\n       'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAPBFDXCEABCTCDDEAVAXAEAWAUAVACBEAVAUADBWAVADBWAZAEAQBWBCCPAUAWAUAUAEAMAMBTCBDHDFDPC9DEAOBIDFDCDDDTCPCBDEABCIDADADTCFDEACCXCADTCNA',\n      tag: 'HRIBEK999IOTA999TUTORIAL' }\n\n\n#### Finalizing bundle\nOnce all individual transactions are created it is time to prepare and finalize the bundle. While preparing the bundle you need at least to specify list of prepared transaction(s). In case of non-value transactions it is quite straightforward process. However, it is a bit more complicated in case of value transactions - please see later.\n\nFinalizing the bundle consists of several tasks under the hood:\n* Each transaction is indexed. Attributes `current_index` / `last_index` are set\n* `Bundle hash` is generated (*Sponge function* + normalization) and assigned to each transaction\n* `signatureMessageFragment` is bascially copy of `message` field in case of non-value transactions\n* PyOTA library also checks whether the data in `message` field is larger than transaction allows (2187 trytes). If this is the case then it takes care of it and split your data into several transactions\n\n*Please note, finalizing the bundle also means you are no longer able to add new transactions to the bundle post the finalization process.*\n\nSimply put, `bundle hash` is a cryptographic \"fingerprint\" of all transactions in the bundle. It uniquely represents them and so as long as transactions are the same (incl their particular order) the `bundle hash` is also the same.\n\n$$BundleHash = fce(address, value, legacy tag, timestamp, current index, last index)$$\n\nYou may be wondering what is a difference between `tag` and `legacy_tag`. `Tag` includes actualy the tag that was defined during the transaction creation. `Legacy_tag` is also based on it however it is modified during the normalization process while bundle hashing to be sure that `bundle hash` is can be securely used while TX signing. That's why the `bundle hash` is sometimes refered as `normalized bundle hash`.\n\nThe bundle refers to the first transaction in collection as `tail_transaction`. You can perceive `tail transaction` as an official representative of the whole bundle while checking for confirmation status, etc. Remember, the bundle is an atomic entity and so whatever is done to bundle it applies to ALL transactions within.\n\n\n```javascript\nvar iotalib = require('@iota/core');\nvar Converter = require('@iota/converter')\nvar TransactionConverter = require('@iota/transaction-converter')\n\nvar NodeURL = \"https://nodes.thetangle.org:443\";\n\nvar iota = iotalib.composeAPI({\n    'provider': NodeURL\n});\n\nvar MySeed = \"HGW9HB9LJPYUGVHNGCPLFKKPNZAIIFHZBDHKSGMQKFMANUBASSMSV9TAJSSMPRZZU9SFZULXKJ9YLAIUA\";\nvar TargetAddress1 = \"CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\";\nvar TargetAddress2 = \"CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\";\n\nvar NowIs = new Date() //get a actual date & time - just to have some meaningfull info\n\n// preparing transactions\nvar pt = {\n    'address': TargetAddress1, //81 trytes long address\n    'value': 0, //zero transaction - only data in the message field will be sent\n    'message': Converter.asciiToTrytes('Here comes a first message. Now is ' + NowIs), //data needs to be encoded in trytes\n    'tag': 'HRIBEK999IOTA999TUTORIAL' //Up to 27 trytes\n}\n\nvar pt2 = {\n    'address': TargetAddress2, //81 trytes long address\n    'value': 0, //zero transaction - only data in the message field will be sent\n    'message': Converter.asciiToTrytes('Here comes a second message. Now is ' + NowIs), //data needs to be encoded in trytes\n    'tag': 'HRIBEK999IOTA999TUTORIAL' //Up to 27 trytes\n}\n\nvar transfers = [pt,pt2]; // a list of transactions to be sent\nvar bundle;\n\nvar promise = iota\n              .prepareTransfers(MySeed, transfers) //this call prepare a bundle including all transactions\n              .then(trytes => { //trytes to be sent\n                    console.log(\"Generated bundle hash: %s\", TransactionConverter.asTransactionObject(trytes[0]).bundle);\n                    console.log(\"List of all individual transactions in the bundle:\");\n                    for (var i in trytes){\n                        console.log(TransactionConverter.asTransactionObject(trytes[i]))\n                    }\n                    bundle = trytes;\n              })   \n              .catch(err => {\n                    console.log(\"Something went wrong: %s\", err);    \n              })\n\n\n```\n\n    Generated bundle hash: YEKXZBCXRJCAZZJAWLBCCWVYFXFTXHPSLLGHOAGPADDEADLWVGWRWN9FVIFKVAPIWY9LPZZBYXFUEECB9\n    List of all individual transactions in the bundle:\n    { hash:\n       'YAMUKFWJ9CBIKGRCIZFIHTEGBJGFAQRZEJKYUACFJDXDDRVCRKRKCIDTBGRAWPMWJDQHWZVFHFXPJ9KOE',\n      signatureMessageFragment:\n       'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAPBFDXCEABCTCDDEAVAXAEAWAUAVACBEAVAUADBYABBDBYABBEAQBWBCCPAUAWAUAUAEAMAMBTCBDHDFDPC9DEAOBIDFDCDDDTCPCBDEABCIDADADTCFDEACCXCADTCNA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999',\n      address:\n       'CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW',\n      value: 0,\n      obsoleteTag: 'HRIBEK999IOTA999TUTORIAL999',\n      timestamp: 1568364528,\n      currentIndex: 1,\n      lastIndex: 1,\n      bundle:\n       'YEKXZBCXRJCAZZJAWLBCCWVYFXFTXHPSLLGHOAGPADDEADLWVGWRWN9FVIFKVAPIWY9LPZZBYXFUEECB9',\n      trunkTransaction:\n       '999999999999999999999999999999999999999999999999999999999999999999999999999999999',\n      branchTransaction:\n       '999999999999999999999999999999999999999999999999999999999999999999999999999999999',\n      tag: 'HRIBEK999IOTA999TUTORIAL999',\n      attachmentTimestamp: 0,\n      attachmentTimestampLowerBound: 0,\n      attachmentTimestampUpperBound: 0,\n      nonce: '999999999999999999999999999' }\n    { hash:\n       'IT9CRSDOVGOSWLSKGVNHLIFRFFKSPKQRFTVG9S9UJM9JLNEWOFSJIKGUJLINVRJCQMBPACZJGWAGRFFYT',\n      signatureMessageFragment:\n       'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAPBFDXCEABCTCDDEAVAXAEAWAUAVACBEAVAUADBYABBDBYABBEAQBWBCCPAUAWAUAUAEAMAMBTCBDHDFDPC9DEAOBIDFDCDDDTCPCBDEABCIDADADTCFDEACCXCADTCNA999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999',\n      address:\n       'CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9',\n      value: 0,\n      obsoleteTag: 'RTIBEK999IOTA999TUTORIAL999',\n      timestamp: 1568364528,\n      currentIndex: 0,\n      lastIndex: 1,\n      bundle:\n       'YEKXZBCXRJCAZZJAWLBCCWVYFXFTXHPSLLGHOAGPADDEADLWVGWRWN9FVIFKVAPIWY9LPZZBYXFUEECB9',\n      trunkTransaction:\n       '999999999999999999999999999999999999999999999999999999999999999999999999999999999',\n      branchTransaction:\n       '999999999999999999999999999999999999999999999999999999999999999999999999999999999',\n      tag: 'HRIBEK999IOTA999TUTORIAL999',\n      attachmentTimestamp: 0,\n      attachmentTimestampLowerBound: 0,\n      attachmentTimestampUpperBound: 0,\n      nonce: '999999999999999999999999999' }\n\n\nAt this stage you can also see how does our finalized bundle look encoded in Trytes so far. It is also a proof that there is no bundle to be broadcasted itself, only list of transations matter.\n\n\n```javascript\nconsole.log(bundle);\n```\n\n    [ 'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAPBFDXCEABCTCDDEAVAXAEAWAUAVACBEAVAUADBYABBDBYABBEAQBWBCCPAUAWAUAUAEAMAMBTCBDHDFDPC9DEAOBIDFDCDDDTCPCBDEABCIDADADTCFDEACCXCADTCNA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW999999999999999999999999999HRIBEK999IOTA999TUTORIAL999CREDHAD99A99999999A99999999YEKXZBCXRJCAZZJAWLBCCWVYFXFTXHPSLLGHOAGPADDEADLWVGWRWN9FVIFKVAPIWY9LPZZBYXFUEECB9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999HRIBEK999IOTA999TUTORIAL999999999999999999999999999999999999999999999999999999999',\n      'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAPBFDXCEABCTCDDEAVAXAEAWAUAVACBEAVAUADBYABBDBYABBEAQBWBCCPAUAWAUAUAEAMAMBTCBDHDFDPC9DEAOBIDFDCDDDTCPCBDEABCIDADADTCFDEACCXCADTCNA999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9999999999999999999999999999RTIBEK999IOTA999TUTORIAL999CREDHAD99999999999A99999999YEKXZBCXRJCAZZJAWLBCCWVYFXFTXHPSLLGHOAGPADDEADLWVGWRWN9FVIFKVAPIWY9LPZZBYXFUEECB9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999HRIBEK999IOTA999TUTORIAL999999999999999999999999999999999999999999999999999999999' ]\n\n\n#### Selecting two tips\nAs mentioned earlier you need to find two tips that you are going to validate together with your bundle for a sake of network participation. This will be outsourced to an IOTA node and so it will be for the first time we interact with the network (via API call `get_transactions_to_approve`).\n\nThere is a `depth` parameter needed. It instructs a node how many milestones it should go in the past while confirming tips. The higher value the better to network however more resources needed. `Depth=3` is considered to be well-balanced compromise. Higher value than `depth=10` will probably throw an exception depending on node's configuration.\n\nIt should return two selected tips as `branch` and `trunk` transactions. Those transactions will be used while broadcasting the bundle.\n\n\n```javascript\nvar gta;\nvar depth = 3;\n\nvar promise = iota.getTransactionsToApprove(depth)\n                     .then(transactionsToApprove => {\n                         console.log(transactionsToApprove);\n                         gta = transactionsToApprove;\n                     })\n                     .catch(err => {\n                         console.log(\"Something went wrong: %s\", err);\n                     })        \n```\n\n    { trunkTransaction:\n       'UHFMVKVBPBDGQFVVEXMYBAVW9WZCGGORSNOOPDTBIWVBL9GVPPIVWDQYC9PZTDIVFBHVGIZZDJVV99999',\n      branchTransaction:\n       'HZKIFVHGAMIAVICOYZWFMYKINKPH9HTDAPQNHPEEIALRUPQSXIUWRZQTYMNKQVJMYZBTXQCQF9MLZ9999' }\n\n\n#### Performin' POW\n*Proof of work* is a relatively simple cryptograhic puzzle to be solved. It represents energy-based costs of your transaction. It also helps to minimize risks of some attack vectors to the network.\n\nThis task can be also outsourced to IOTA nodes. In order to perform it you need *selected tips*, *finalized bundle* (in trytes) and also `Minimum Weight Magnitude` parameter. This parameter defines how diffciult the given cryptographic puzzle should be to be accepted by the network. As of now, you should set at least `min_weight_magnitude=14` in case of mainnet.\n\nPlease note, POW is performed per each transaction and so it can take some time. That's why it is not recommended to have more than 30 transactions in a bundle.\n\nOnce succesfully performed, the modified bundle (list of all transactions in trytes) is returned in order to be broadcasted.\n\nSpecifically:\n* Fields `nonce` and `transaction hash` are calculated per each transaction\n* `Trunk` and `Branch` tips are correctly mapped among transactions within the bundle. Check that `trunk` of the first TX refers to the second TX, etc.\n\n\n```javascript\nconsole.log(\"Performing POW...Wait please...\");\nvar minWeightMagnitude = 14;\n\nvar att;\nvar promise = iota.attachToTangle(\n                       gta['trunkTransaction'], //trunk transaction gotten from previous step\n                       gta['branchTransaction'], //branch transaction gotten from previous step\n                       minWeightMagnitude,\n                       bundle // finalized bundle in trytes from previous steps\n                   ) \n                   .then(attachedTrytes => {\n                       console.log(attachedTrytes);\n                       att=attachedTrytes;\n                   })\n                   .catch(err => {\n                        console.log(\"Something went wrong: %s\", err);\n                   });\n\n```\n\n    Performing POW...Wait please...\n    [ 'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAPBFDXCEABCTCDDEAVAXAEAWAUAVACBEAVAUADBYABBDBYABBEAQBWBCCPAUAWAUAUAEAMAMBTCBDHDFDPC9DEAOBIDFDCDDDTCPCBDEABCIDADADTCFDEACCXCADTCNA999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9999999999999999999999999999RTIBEK999IOTA999TUTORIAL999CREDHAD99999999999A99999999YEKXZBCXRJCAZZJAWLBCCWVYFXFTXHPSLLGHOAGPADDEADLWVGWRWN9FVIFKVAPIWY9LPZZBYXFUEECB9XOZZNEFNL9ESUDQGUPRBESDBBVRWAEHEWLPIKXGEVGSZVEWASTTEDRNRGRKKUEDHQQSOBOGCKMGZA9999UHFMVKVBPBDGQFVVEXMYBAVW9WZCGGORSNOOPDTBIWVBL9GVPPIVWDQYC9PZTDIVFBHVGIZZDJVV99999HRIBEK999IOTA999TUTORIAL999HNAIBFYOF999999999MMMMMMMMMMPMZBUZOZRT9HUVNMNRGIBTJQCQ',\n      'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAPBFDXCEABCTCDDEAVAXAEAWAUAVACBEAVAUADBYABBDBYABBEAQBWBCCPAUAWAUAUAEAMAMBTCBDHDFDPC9DEAOBIDFDCDDDTCPCBDEABCIDADADTCFDEACCXCADTCNA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW999999999999999999999999999HRIBEK999IOTA999TUTORIAL999CREDHAD99A99999999A99999999YEKXZBCXRJCAZZJAWLBCCWVYFXFTXHPSLLGHOAGPADDEADLWVGWRWN9FVIFKVAPIWY9LPZZBYXFUEECB9UHFMVKVBPBDGQFVVEXMYBAVW9WZCGGORSNOOPDTBIWVBL9GVPPIVWDQYC9PZTDIVFBHVGIZZDJVV99999HZKIFVHGAMIAVICOYZWFMYKINKPH9HTDAPQNHPEEIALRUPQSXIUWRZQTYMNKQVJMYZBTXQCQF9MLZ9999HRIBEK999IOTA999TUTORIAL999VY9IBFYOF999999999MMMMMMMMMYQEGDUMCTKAQVSNQCGGUPL9MT9I' ]\n\n\nYou can eventually also preview what specific fields have been modified using transaction objects. The bundle is ready to be broadcasted and so it also show you all fields/values that will be stored in the network.\n\n\n```javascript\n//show what has been changed: hash transaction + nonce (POW) + trunk + branch\nconsole.log(\"Final bundle including POW and branch/trunk transactions:\");\nfor (var i in att) {\n    console.log(TransactionConverter.asTransactionObject(att[i])) //Let's print attributes of each TX\n}\n```\n\n    Final bundle including POW and branch/trunk transactions:\n    { hash:\n       'DZHB9SKKUOHB9RUODHYTVIHDGNOG9UGKBBOOIXFXFBGFYIZGGNIZGIHCZVFRQPNHETHHWL9WNSFEZ9999',\n      signatureMessageFragment:\n       'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAPBFDXCEABCTCDDEAVAXAEAWAUAVACBEAVAUADBYABBDBYABBEAQBWBCCPAUAWAUAUAEAMAMBTCBDHDFDPC9DEAOBIDFDCDDDTCPCBDEABCIDADADTCFDEACCXCADTCNA999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999',\n      address:\n       'CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9',\n      value: 0,\n      obsoleteTag: 'RTIBEK999IOTA999TUTORIAL999',\n      timestamp: 1568364528,\n      currentIndex: 0,\n      lastIndex: 1,\n      bundle:\n       'YEKXZBCXRJCAZZJAWLBCCWVYFXFTXHPSLLGHOAGPADDEADLWVGWRWN9FVIFKVAPIWY9LPZZBYXFUEECB9',\n      trunkTransaction:\n       'XOZZNEFNL9ESUDQGUPRBESDBBVRWAEHEWLPIKXGEVGSZVEWASTTEDRNRGRKKUEDHQQSOBOGCKMGZA9999',\n      branchTransaction:\n       'UHFMVKVBPBDGQFVVEXMYBAVW9WZCGGORSNOOPDTBIWVBL9GVPPIVWDQYC9PZTDIVFBHVGIZZDJVV99999',\n      tag: 'HRIBEK999IOTA999TUTORIAL999',\n      attachmentTimestamp: 1568365473329,\n      attachmentTimestampLowerBound: 0,\n      attachmentTimestampUpperBound: 3812798742493,\n      nonce: 'MPMZBUZOZRT9HUVNMNRGIBTJQCQ' }\n    { hash:\n       'XOZZNEFNL9ESUDQGUPRBESDBBVRWAEHEWLPIKXGEVGSZVEWASTTEDRNRGRKKUEDHQQSOBOGCKMGZA9999',\n      signatureMessageFragment:\n       'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAPBFDXCEABCTCDDEAVAXAEAWAUAVACBEAVAUADBYABBDBYABBEAQBWBCCPAUAWAUAUAEAMAMBTCBDHDFDPC9DEAOBIDFDCDDDTCPCBDEABCIDADADTCFDEACCXCADTCNA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999',\n      address:\n       'CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW',\n      value: 0,\n      obsoleteTag: 'HRIBEK999IOTA999TUTORIAL999',\n      timestamp: 1568364528,\n      currentIndex: 1,\n      lastIndex: 1,\n      bundle:\n       'YEKXZBCXRJCAZZJAWLBCCWVYFXFTXHPSLLGHOAGPADDEADLWVGWRWN9FVIFKVAPIWY9LPZZBYXFUEECB9',\n      trunkTransaction:\n       'UHFMVKVBPBDGQFVVEXMYBAVW9WZCGGORSNOOPDTBIWVBL9GVPPIVWDQYC9PZTDIVFBHVGIZZDJVV99999',\n      branchTransaction:\n       'HZKIFVHGAMIAVICOYZWFMYKINKPH9HTDAPQNHPEEIALRUPQSXIUWRZQTYMNKQVJMYZBTXQCQF9MLZ9999',\n      tag: 'HRIBEK999IOTA999TUTORIAL999',\n      attachmentTimestamp: 1568365472884,\n      attachmentTimestampLowerBound: 0,\n      attachmentTimestampUpperBound: 3812798742493,\n      nonce: 'YQEGDUMCTKAQVSNQCGGUPL9MT9I' }\n\n\n#### Broadcasting\nNow it is time to broadcast the given bundle to the network. List of all transations in trytes returned from the previous step is only thing needed.\n\nOnce succesfully broadcasted it returns the same input bundle as a confirmation.\n\n\n```javascript\n//broadcast and store\nconsole.log(\"Broadcasting transaction...\");\nvar promise = iota.storeAndBroadcast(att)\n                        .then(r => console.log(r)\n                        )\n                        .catch(err => {\n                            console.log(\"Something went wrong: %s\", err);\n                        });\n```\n\n    Broadcasting transaction...\n    [ 'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAPBFDXCEABCTCDDEAVAXAEAWAUAVACBEAVAUADBYABBDBYABBEAQBWBCCPAUAWAUAUAEAMAMBTCBDHDFDPC9DEAOBIDFDCDDDTCPCBDEABCIDADADTCFDEACCXCADTCNA999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9999999999999999999999999999RTIBEK999IOTA999TUTORIAL999CREDHAD99999999999A99999999YEKXZBCXRJCAZZJAWLBCCWVYFXFTXHPSLLGHOAGPADDEADLWVGWRWN9FVIFKVAPIWY9LPZZBYXFUEECB9XOZZNEFNL9ESUDQGUPRBESDBBVRWAEHEWLPIKXGEVGSZVEWASTTEDRNRGRKKUEDHQQSOBOGCKMGZA9999UHFMVKVBPBDGQFVVEXMYBAVW9WZCGGORSNOOPDTBIWVBL9GVPPIVWDQYC9PZTDIVFBHVGIZZDJVV99999HRIBEK999IOTA999TUTORIAL999HNAIBFYOF999999999MMMMMMMMMMPMZBUZOZRT9HUVNMNRGIBTJQCQ',\n      'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAPBFDXCEABCTCDDEAVAXAEAWAUAVACBEAVAUADBYABBDBYABBEAQBWBCCPAUAWAUAUAEAMAMBTCBDHDFDPC9DEAOBIDFDCDDDTCPCBDEABCIDADADTCFDEACCXCADTCNA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW999999999999999999999999999HRIBEK999IOTA999TUTORIAL999CREDHAD99A99999999A99999999YEKXZBCXRJCAZZJAWLBCCWVYFXFTXHPSLLGHOAGPADDEADLWVGWRWN9FVIFKVAPIWY9LPZZBYXFUEECB9UHFMVKVBPBDGQFVVEXMYBAVW9WZCGGORSNOOPDTBIWVBL9GVPPIVWDQYC9PZTDIVFBHVGIZZDJVV99999HZKIFVHGAMIAVICOYZWFMYKINKPH9HTDAPQNHPEEIALRUPQSXIUWRZQTYMNKQVJMYZBTXQCQF9MLZ9999HRIBEK999IOTA999TUTORIAL999VY9IBFYOF999999999MMMMMMMMMYQEGDUMCTKAQVSNQCGGUPL9MT9I' ]\n\n\nYou can check the broadcasted bundle via The Tangle Explorer at any of the receiving addresses:\n* Target address 1: https://thetangle.org/address/CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\n* Target address 2: \nhttps://thetangle.org/address/CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\n\n### Creating and broadcasting transaction in a single call (you want send a transaction quickly)\nAs mentioned above, IOTA-facing libraries are able to encapsulate all implementation details and so you do not need to care of them anymore. It is usually based on *extended API calls* that were proposed to be included by IOTA Foundation to make developer's life easier (https://github.com/iotaledger/wiki/blob/master/api-proposal.md).\n\nEven if using extended API calls you can still slightly control a level of your involvement in the whole process. From almost no involvement and fully automatic (`send_transfer()`) to semi-manual approach discussed above.\n\n\n\nThere are some specifics you should consider while designing your app:\n* You are loosing a bit of control of individual steps of the process and you have to rely of some predefined parameters (tip selection algo, etc.)\n* If there is an exception raised during the process then you need to go back at beginning and restart the whole process again\n\nSo it is basically your call to decide what works best for you.\n\nNow back to our exercise. Here comes a code that basically broadcasts transactions in a single call (`send_transfer()`) and you do not have to care of any implemenation details that are hidden under the hood.\n\n\n```javascript\nvar iotalib = require('@iota/core');\nvar Converter = require('@iota/converter')\nvar TransactionConverter = require('@iota/transaction-converter')\n\nvar NodeURL = \"https://nodes.thetangle.org:443\";\n\nvar iota = iotalib.composeAPI({\n    'provider': NodeURL\n});\n\nvar MySeed = \"HGW9HB9LJPYUGVHNGCPLFKKPNZAIIFHZBDHKSGMQKFMANUBASSMSV9TAJSSMPRZZU9SFZULXKJ9YLAIUA\";\nvar TargetAddress1 = \"CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\";\nvar TargetAddress2 = \"CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\";\n\nvar NowIs = new Date() //get a actual date & time - just to have some meaningfull info\n\n// preparing transactions\nvar pt = {\n    'address': TargetAddress1, //81 trytes long address\n    'value': 0, //zero transaction - only data in the message field will be sent\n    'message': Converter.asciiToTrytes('Here comes a first message. Now is ' + NowIs), //data needs to be encoded in trytes\n    'tag': 'HRIBEK999IOTA999TUTORIAL' //Up to 27 trytes\n}\n\nvar pt2 = {\n    'address': TargetAddress2, //81 trytes long address\n    'value': 0, //zero transaction - only data in the message field will be sent\n    'message': Converter.asciiToTrytes('Here comes a second message. Now is ' + NowIs), //data needs to be encoded in trytes\n    'tag': 'HRIBEK999IOTA999TUTORIAL' //Up to 27 trytes\n}\n\nvar transfers = [pt,pt2]; // a list of transactions to be sent\nvar depth = 3;\nvar minWeightMagnitude = 14;\n\nconsole.log(\"Preparing/Broadcasting... Wait please...\");\n\nvar promise = iota.prepareTransfers(MySeed, transfers) //prepare a bundle in trytes\n                            .then(trytes => {\n                                return iota.sendTrytes(trytes, depth, minWeightMagnitude); //perform GTTA + POW + BROADCASTING\n                            })\n                            .then(bundle => {\n                                console.log(\"Transactions sent!\");\n                                console.log(\"\\nList of all transactions in the bundle:\");\n                                bundle.map(tx => console.log(tx))\n                            })\n                             .catch(err => {\n                                console.log(\"Something went wrong: %s\", err);\n                            })\n```\n\n    Preparing/Broadcasting... Wait please...\n    Transactions sent!\n    \n    List of all transactions in the bundle:\n    { hash:\n       'WZXSIHOLGQMXOEIBDMODHFNESEVQVKGEYEWNWN9HFYSGENRTGCOIIOWEEVZQLQPSGTWBUPSDHSHLA9999',\n      signatureMessageFragment:\n       'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAPBFDXCEABCTCDDEAVAXAEAWAUAVACBEAVAVADBXAABDBZABBEAQBWBCCPAUAWAUAUAEAMAMBTCBDHDFDPC9DEAOBIDFDCDDDTCPCBDEABCIDADADTCFDEACCXCADTCNA999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999',\n      address:\n       'CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9',\n      value: 0,\n      obsoleteTag: 'OYIBEK999IOTA999TUTORIAL999',\n      timestamp: 1568367478,\n      currentIndex: 0,\n      lastIndex: 1,\n      bundle:\n       'GIPZYTSDGWQ9KKHYQVULDKFE9FDPAEUKABU9CZCNTHKAISCWRICOJKNNJGTOY9DIFESDDCNGKKPQJQLLZ',\n      trunkTransaction:\n       'UQWLQHZZNYDDEVIHAPPEQNXOEEXHDZMHRVXQKDBZKXEDOWLFAKZYFHLIMYEWXF9ZHVUTCEVZXEFW99999',\n      branchTransaction:\n       'XOHHXLT9WMAROEVLUBDRIZMY9PNQP9HEZQAJAZXTIEJZWYZNWOUWKCVFFTLWAMHT9ALMDOBHVWY999999',\n      tag: 'HRIBEK999IOTA999TUTORIAL999',\n      attachmentTimestamp: 1568367481436,\n      attachmentTimestampLowerBound: 0,\n      attachmentTimestampUpperBound: 3812798742493,\n      nonce: 'SXXQGKNGUPLZRGSRTQXU99O9ORZ' }\n    { hash:\n       'UQWLQHZZNYDDEVIHAPPEQNXOEEXHDZMHRVXQKDBZKXEDOWLFAKZYFHLIMYEWXF9ZHVUTCEVZXEFW99999',\n      signatureMessageFragment:\n       'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAPBFDXCEABCTCDDEAVAXAEAWAUAVACBEAVAVADBXAABDBZABBEAQBWBCCPAUAWAUAUAEAMAMBTCBDHDFDPC9DEAOBIDFDCDDDTCPCBDEABCIDADADTCFDEACCXCADTCNA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999',\n      address:\n       'CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW',\n      value: 0,\n      obsoleteTag: 'HRIBEK999IOTA999TUTORIAL999',\n      timestamp: 1568367478,\n      currentIndex: 1,\n      lastIndex: 1,\n      bundle:\n       'GIPZYTSDGWQ9KKHYQVULDKFE9FDPAEUKABU9CZCNTHKAISCWRICOJKNNJGTOY9DIFESDDCNGKKPQJQLLZ',\n      trunkTransaction:\n       'XOHHXLT9WMAROEVLUBDRIZMY9PNQP9HEZQAJAZXTIEJZWYZNWOUWKCVFFTLWAMHT9ALMDOBHVWY999999',\n      branchTransaction:\n       'HVGTFLPMQHNURZNWZETWELDAJVSBZHEHDNWVWHZAKMYDNGTAEAPWKGQVIBEKKLZEGIBGOQWMNASE99999',\n      tag: 'HRIBEK999IOTA999TUTORIAL999',\n      attachmentTimestamp: 1568367481152,\n      attachmentTimestampLowerBound: 0,\n      attachmentTimestampUpperBound: 3812798742493,\n      nonce: 'ZJHPXAJI9TMSKXPQN9POQZYGNMQ' }\n\n\nYou can check the broadcasted bundle via The Tangle Explorer at any of the receiving addresses:\n* Target address 1: https://thetangle.org/address/CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\n* Target address 2: \nhttps://thetangle.org/address/CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\n\nAnd to complete the picture here is addtional code that uses `prepare_transfer()` and `send_trytes()` combo.\n\n\n```javascript\nvar iotalib = require('@iota/core');\n\nvar NodeURL = \"https://nodes.thetangle.org:443\";\n\nvar iota = iotalib.composeAPI({\n    'provider': NodeURL\n});\n\nvar MySeed = \"HGW9HB9LJPYUGVHNGCPLFKKPNZAIIFHZBDHKSGMQKFMANUBASSMSV9TAJSSMPRZZU9SFZULXKJ9YLAIUA\";\nvar TargetAddress1 = \"CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\";\nvar TargetAddress2 = \"CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\";\n\nvar NowIs = new Date() //get a actual date & time - just to have some meaningfull info\n\n// preparing transactions\nvar pt = {\n    'address': TargetAddress1, //81 trytes long address\n    'value': 0, //zero transaction - only data in the message field will be sent\n    'message': Converter.asciiToTrytes('Here comes a first message. Now is ' + NowIs), //data needs to be encoded in trytes\n    'tag': 'HRIBEK999IOTA999TUTORIAL' //Up to 27 trytes\n}\n\nvar pt2 = {\n    'address': TargetAddress2, //81 trytes long address\n    'value': 0, //zero transaction - only data in the message field will be sent\n    'message': Converter.asciiToTrytes('Here comes a second message. Now is ' + NowIs), //data needs to be encoded in trytes\n    'tag': 'HRIBEK999IOTA999TUTORIAL' //Up to 27 trytes\n}\n\nvar transfers = [pt,pt2]; // a list of transactions to be sent\nvar depth = 3;\nvar minWeightMagnitude = 14;\n\nconsole.log(\"Preparing/Broadcasting... Wait please...\");\n\nvar promise = iota.prepareTransfers(MySeed, transfers) //prepare a bundle in trytes\n                            .then(trytes => {                                \n                                console.log(\"Almost prepared bundle - tips and POW are still missing\");\n                                console.log(trytes);\n                                console.log(\"Searching for tips and performing POW... Wait please...\");\n                                return iota.sendTrytes(trytes, depth, minWeightMagnitude); //perform GTTA + POW + BROADCASTING\n                            })\n                            .then(bundle => {\n                                console.log(\"Bundle was broadcasted.\");\n                                console.log(\"Final transactions were returned - including nonce (POW)\");\n                                bundle.map(tx => console.log(tx))\n                            })\n                            .catch(err => {\n                                console.log(\"Something went wrong: %s\", err);\n                            })\n```\n\n    Preparing/Broadcasting... Wait please...\n    Almost prepared bundle - tips and POW are still missing\n    [ 'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAPBFDXCEABCTCDDEAVAXAEAWAUAVACBEAVAVADBYAABDBZA9BEAQBWBCCPAUAWAUAUAEAMAMBTCBDHDFDPC9DEAOBIDFDCDDDTCPCBDEABCIDADADTCFDEACCXCADTCNA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW999999999999999999999999999HRIBEK999IOTA999TUTORIAL999NOJDHAD99A99999999A99999999XLIGKSOQJNFIIXBJDLOSFZKFXPTHKCWIYKWDSVZKEKQJPBHTQQVRCFBYYLDGRAEKNJASAINIZWPPTJGLC999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999HRIBEK999IOTA999TUTORIAL999999999999999999999999999999999999999999999999999999999',\n      'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAPBFDXCEABCTCDDEAVAXAEAWAUAVACBEAVAVADBYAABDBZA9BEAQBWBCCPAUAWAUAUAEAMAMBTCBDHDFDPC9DEAOBIDFDCDDDTCPCBDEABCIDADADTCFDEACCXCADTCNA999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9999999999999999999999999999IVIBEK999IOTA999TUTORIAL999NOJDHAD99999999999A99999999XLIGKSOQJNFIIXBJDLOSFZKFXPTHKCWIYKWDSVZKEKQJPBHTQQVRCFBYYLDGRAEKNJASAINIZWPPTJGLC999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999HRIBEK999IOTA999TUTORIAL999999999999999999999999999999999999999999999999999999999' ]\n    Searching for tips and performing POW... Wait please...\n    Bundle was broadcasted.\n    Final transactions were returned - including nonce (POW)\n    { hash:\n       'LFMCNVUBXBRAT9TWSYHSMMTPLMTUPQSKZAGDXYGCUGZYNMWAWYOQKCRELBYPJJMSR9DTXQTARDEYZ9999',\n      signatureMessageFragment:\n       'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAPBFDXCEABCTCDDEAVAXAEAWAUAVACBEAVAVADBYAABDBZA9BEAQBWBCCPAUAWAUAUAEAMAMBTCBDHDFDPC9DEAOBIDFDCDDDTCPCBDEABCIDADADTCFDEACCXCADTCNA999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999',\n      address:\n       'CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9',\n      value: 0,\n      obsoleteTag: 'IVIBEK999IOTA999TUTORIAL999',\n      timestamp: 1568368076,\n      currentIndex: 0,\n      lastIndex: 1,\n      bundle:\n       'XLIGKSOQJNFIIXBJDLOSFZKFXPTHKCWIYKWDSVZKEKQJPBHTQQVRCFBYYLDGRAEKNJASAINIZWPPTJGLC',\n      trunkTransaction:\n       'UR9QHJXQJHVUK9TQHUZIWFFXGPYICSEQDN9RGHMORTJKRWXDRVAQQTPGFTXVFGVRKRMAX9KZNLKFZ9999',\n      branchTransaction:\n       'EPVYMGGEQDFAG9HYJXUFHHPPVRCRSXHTLHIULPVZXBRDOOZABXALMPZSLWJJURDAVLPCZQQCOHPOZ9999',\n      tag: 'HRIBEK999IOTA999TUTORIAL999',\n      attachmentTimestamp: 1568368078476,\n      attachmentTimestampLowerBound: 0,\n      attachmentTimestampUpperBound: 3812798742493,\n      nonce: 'ZEVHDNDFMLKCPCPIKUGDAYJBZNP' }\n    { hash:\n       'UR9QHJXQJHVUK9TQHUZIWFFXGPYICSEQDN9RGHMORTJKRWXDRVAQQTPGFTXVFGVRKRMAX9KZNLKFZ9999',\n      signatureMessageFragment:\n       'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAPBFDXCEABCTCDDEAVAXAEAWAUAVACBEAVAVADBYAABDBZA9BEAQBWBCCPAUAWAUAUAEAMAMBTCBDHDFDPC9DEAOBIDFDCDDDTCPCBDEABCIDADADTCFDEACCXCADTCNA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999',\n      address:\n       'CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW',\n      value: 0,\n      obsoleteTag: 'HRIBEK999IOTA999TUTORIAL999',\n      timestamp: 1568368076,\n      currentIndex: 1,\n      lastIndex: 1,\n      bundle:\n       'XLIGKSOQJNFIIXBJDLOSFZKFXPTHKCWIYKWDSVZKEKQJPBHTQQVRCFBYYLDGRAEKNJASAINIZWPPTJGLC',\n      trunkTransaction:\n       'EPVYMGGEQDFAG9HYJXUFHHPPVRCRSXHTLHIULPVZXBRDOOZABXALMPZSLWJJURDAVLPCZQQCOHPOZ9999',\n      branchTransaction:\n       'EPVYMGGEQDFAG9HYJXUFHHPPVRCRSXHTLHIULPVZXBRDOOZABXALMPZSLWJJURDAVLPCZQQCOHPOZ9999',\n      tag: 'HRIBEK999IOTA999TUTORIAL999',\n      attachmentTimestamp: 1568368078376,\n      attachmentTimestampLowerBound: 0,\n      attachmentTimestampUpperBound: 3812798742493,\n      nonce: 'HVANLGSKZQEZVYUSKVGISFOSRMH' }\n\n\nYou can check the broadcasted bundle via The Tangle Explorer at any of the receiving addresses:\n* Target address 1: https://thetangle.org/address/CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\n* Target address 2: \nhttps://thetangle.org/address/CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\n\n## Value transactions\nMeta transactions were discussed in the previous chapter. This chapter describes `value transactions` which are transactions that transfer IOTA tokens between IOTA addresses. Tokens are fully premined and so number of tokens in the network is given. So `transfering tokens` means changing their ownership only.\n\nWhile preparing a bundle with `value transations` it is important to distinguish three different transaction types within a bundle:\n* **Input TXs:** those are transactions that *deducting* (spending) value from address(es). Those transactions have negative `value` field. They usually refer to `senders`\n* **Output TXs:** those are transactions that *adding* (receiving) value to address(es). Those transactions have positive `value` field. They usually refer to `recipients`\n* **Unspent/change TX:** technically speaking it is also *output* transaction that *adding* value however it usually refers to `senders` and so it is better to consider it separated from other output TXs\n\nAll three types have to be part of each bundle otherwise you are under a risk of loosing IOTA tokens. In other words, each bundle should consists of at least one `input` TX, one `output` TX and one `unspent` TX. Total balance of the bundle should be zero since the number of tokens is the same, just token owners have been \"changed\".\n\nExample:\n* Alice owns 100 tokens (*input = 100*)\n* Alice is going to send 20 tokens to John from the address that includes 100 tokens of her (*Alice -100*)\n* John is going to receive 20 tokens from Alice (*output = 20*; *John +20*)\n* Alice still owns 80 tokens after the transaction (*unspent = 80*; *Alice +80*)\n\nAlice's bundle should look like:\n\\begin{align}\nInput - Output & = \\ Unspent \\\\\nInput - Output - Unspent & = \\ 0 \\\\\n100 - 20 - 80 & = \\ 0\n\\end{align}\n\nWhy Alice has to \"put\" all 100 tokens in the bundle while she is going to actually spend only 20 tokens? The reason is that IOTA protocol uses one-time signature scheme (OTS) for transaction signing while spending tokens. And with every signing process a half of a private key of the given address is revealed. That's why no one should ever spend tokens from the same address again.\n\n\n### Spending tokens\n*Please note: for a purpose of this chapter we are going to switch to a test network called `devnet`. It is the testing Tangle. Tokens are not real and everything you do have no implication to the mainnet at all. However it is stil powered by standard node software and so technicaly speaking it behaves like the mainnet. If you need more info regarding devnet please refer to [the official documentation](https://docs.iota.org/introduction/testnet/introduction).*\n\nEverything what has been mentioned in the previous chapter focused on `non-value` transations is still valid also in case of value transactions however there are several additional tasks you should take care of. Needless to say, IOTA libraries (PyOTA and others) are ready to help you and are able to hide all implementation details in case you would like to. In this case I would encourage everyone to prefer a functionality that is offered by extended API calls, such as `send_transfer`. Experimenting with value transactions and trying to tweak them does not seem to be a good idea (on the mainnet).\n\nAnyway, even in this chapter I am going to describe main tasks that are performed under the hood to be able to understand the whole concept.\n\nLet's have the following setup:\n\n\n```javascript\n// Sender's side ***********\n// Sender's seed\nvar SeedSender = \"HGW9HB9LJPYUGVHNGCPLFKKPNZAIIFHZBDHKSGMQKFMANUBASSMSV9TAJSSMPRZZU9SFZULXKJ9YLAIUA\"\n\n// Receiver's side ***********\n// Recipient's seed - this is actually not needed for the exercise - it is just to have corresponding seed somewhere written\nvar SeedReceiver = \"NVPDKGLESTYNJEH9DTWD9DUBYWHZJDDWTBLKWEYLVZKBKKAZTIZ9CFFJMHPEKIFUWQTXRGAVRXAQZCPHL\"\n\n// This is our target address to which we are going to send tokens to(BTW: it is a first generated address based on recipient's seed)\nvar AddressReceiver = \"BMFSMZMNBGKHAWPIZIOMJGRBXZETVSAYDSTDQCHLYTBWZMIXLNXF9XHLTMOCATFVFOMBQF9IOQGPEBPDC\"\n\n// DevNet node - Devnet Tangle that is used only for testing / dev purposes - no real tokens here: (\nvar DevnetNode = \"https://nodes.devnet.iota.org:443\"\n\nconsole.log(\"Variables were initialized.\")\n```\n\n    Variables were initialized.\n\n\nYou may be wondering why only the seed for sender's side is defined. As mentioned above the reason is that the address with tokens is changing with every spending exercise and so you have to find address with tokens that left in a bucket programatically (if any tokens left:).\n\nLet's find out. For this purpose you can use extended API call `get_account_data` which returns a list of used addresses and total sum of all tokens available accross all of them:\n\n\n```javascript\nvar iotalib = require('@iota/core');\n\nvar iota = iotalib.composeAPI({\n    'provider': DevnetNode\n});\n\nconsole.log(\"Checking for total balance.\")\nconsole.log(\"Please note, this may take some time if many addresses has been used already...\");\nvar usedadr;\n\n// now we can find out whether there are any tokens left\nvar promise = iota.getAccountData(//Get the total available balance for the given seed and all related used addresses\n                    SeedSender, // Sender's seed - library will do all hard work based on the seed\n                    {\n                        \"start\": 29, // Library will start from the address at index 0. please note I increased it to start from index 29 to save time\n                        \"security\": 2 // Default security level\n                    })\n                    .then(accountData => {\n                        usedadr = accountData;\n                        console.log(accountData);\n                        if (accountData[\"balance\"]) {\n                            console.log(\"\\nYes, there are some tokens available! hurray\");\n                            // there are quite usefull info returned - all addresses used plus first unused address. See latestAddress\n                        }\n                    })\n                    .catch(err => {\n                        console.log(\"Something went wrong: %s\", err);\n                    })\n```\n\n    Checking for total balance.\n    Please note, this may take some time if many addresses has been used already...\n\n\n    `AccountData.transfers` field is deprecated, and `AccountData.transactions` field should be used instead.\n    Fetching of full bundles should be done lazily.\n\n\n    { latestAddress:\n       'NDQMBGBQIBAQURVAQEUVONVMECKXSNYZZNKMMMOHOLPEYHJHDBTFWOZMAPFUAHLHIQUAV9GVZPEMBKL9Z',\n      transfers:\n       [ [ [Object], [Object], [Object], [Object] ],\n         [ [Object], [Object], [Object], [Object] ],\n         [ [Object], [Object], [Object], [Object] ],\n         [ [Object], [Object], [Object], [Object] ] ],\n      transactions:\n       [ 'YDTTBOSKIURVYNSCKQQTTKREXMDEPHUXXCUHAERTZUCCPCPIWR9TJIWCFZLKLNOKWVLODQCBFEPXAH999',\n         'YYWNCRKDU9FWDHLZKGVJSRTFRBHGEDDBZ9QOEZOGGIDWQKOLG9XHRBGAXFSBJRPINEKSRMBLXMIEFT999',\n         'CXIDFISEYSKVESHDDKGAYSOEKS9QTXOYYQ9TRKHH9QJ9WEILNYJVLAOWKMMTBRWVNBTQVBABQLWL99999',\n         '99LUPKNVOKORUMEPDJEWRYLPJOTUMMRO9M9MXTWURUYQKJUOVFBAP9OMAEDUYUAJWTRLYIXSMS99A9999' ],\n      inputs:\n       [ { address:\n            'VZITIWJF99TH9REMKLYZUWELFLEW9FVYXPZPVMVFZVIQHAOEMEDABUUZGFROKKIVMT999PWGGLICKJOAD',\n           keyIndex: 31,\n           security: 2,\n           balance: 1999 } ],\n      addresses:\n       [ 'SUYDJCMS9XMBKOPIPOXKGXMFVYXQ9YRNZLDYLRFARZFOFJDDH9JZLCQVO9GBRQKBCXHSPHOAPPWFFLMBW',\n         'NHVGPRAXYTDZJLMLSUMZGVBBMICDQGGAAZ9UJGLIPPOTUEZJXABCSDFUTRTBFOLDOQZIBS9QTRXAB9IUX',\n         'VZITIWJF99TH9REMKLYZUWELFLEW9FVYXPZPVMVFZVIQHAOEMEDABUUZGFROKKIVMT999PWGGLICKJOAD',\n         'XPV9CTUC9JEKATOVABXXLICTDAQEOHR9HXXFLHKN9OZFMFAZKKUDZMREOBZJONZAHXCGNN9FHGNFBAKMC',\n         'NDQMBGBQIBAQURVAQEUVONVMECKXSNYZZNKMMMOHOLPEYHJHDBTFWOZMAPFUAHLHIQUAV9GVZPEMBKL9Z' ],\n      balance: 1999 }\n    \n    Yes, there are some tokens available! hurray\n\n\n*Please note: API call `get_account_data` consider only confirmed transactions while calculating total balance. So it is better to wait until all transactions are cleared before you send additional tokens.*\n\nAre there any tokens left (value in `balance` field)? If yes then continue - no action is needed.\nIf not, then you need to obtain some. It can be done visiting [IOTA faucet](http://faucet.devnet.iota.org) and entering an unused address of the given seed:\n\n\n```javascript\n// Now let's find a first unused address that can be used as a destination address for unspent/new tokens\n// This step is not required in case of NodeJS library, please see result above\n\nconsole.log(\"Please note, this may take some time if many addresses have been used already...\");\n\n//please note the index below starts from 29 to save some time. If you woudl like to start from beginning it should be 0\nvar promise = iota.getNewAddress(SeedSender, { index: 29, total: null} ) //If null is specified, then it identifies a first non-used address\n                .then(address => {\n                    console.log(\"This is the first unused address that can be used for new tokens or unspent tokens:\");\n                    console.log(address); //returned addresses are printed out    \n                })\n                .catch(error => {\n                    console.log(\"Something went wrong: %s\", error);\n                });\n\n\n```\n\n    Please note, this may take some time if many addresses have been used already...\n\n\n    `GetNewAddressOptions`:  options are deprecated and will be removed in v.2.0.0. \n    \n\n\n    This is the first unused address that can be used for new tokens or unspent tokens:\n    NDQMBGBQIBAQURVAQEUVONVMECKXSNYZZNKMMMOHOLPEYHJHDBTFWOZMAPFUAHLHIQUAV9GVZPEMBKL9Z\n\n\nWhat have just happened behind the curtain?\n* The PyOTA library started to generating addresses from the `index=0` of the given seed and at the same time it also checked whether there are any transactions registered for each address\n* If yes, then in case we are after balances, the balance is saved. In case we are after new unused address then the given address is skipped. First address for which there are not registered transactions is returned\n* That's why it may be quite time consuming. And now you also understand all issues regarding `zero balances` after the snapshot\n\nYou may be also wondering how to get individual balances for each used address? This can be checked using the core API call `get_balances` which provides you with a balance for any address you specify. Let's query for used addresses from the previous exercise:\n\n\n```javascript\n// only if there is any used addresses from the previous steps\n\nif (usedadr['addresses'].length > 0){\n    // it returns the balances as a list in the same order as the addresses were provided as input.       \n    var promise = iota.getBalances(\n                       usedadr['addresses'], // list of addresses\n                       100, // Confirmation threshold; official docs recommend to set it to 100\n                      )\n                      .then(({ balances }) => {\n                            console.log(\"Some positive balance identified. Individual confirmed balances per used addresses:\");\n                            console.log(balances);\n                      })\n                      .catch(err => {\n                            console.log(\"Something went wrong: %s\", err);\n                      })           \n}          \nelse\n{\n    console.log(\"\\nNo positive balance identified.\");\n}\n```\n\n    Some positive balance identified. Individual confirmed balances per used addresses:\n    [ 0, 0, 1999, 0, 0 ]\n\n\nIt returns `balances` and you can see how the remaining tokens move to new unused address every time you spend some tokens. Needless to say, used addresses with zero balances should not be used anymore since tokens were already spent from them. So let's spend some tokens:\n\n\n```javascript\nvar tx1 = {\n    'address': AddressReceiver, //81 trytes long address\n    'value': 10,    \n    'tag': 'HRIBEK999IOTA999TUTORIAL' //Up to 27 trytes\n};\n\n// Sending the iotas\nconsole.log(\"\\nSending iotas... Please wait...\");\n\nvar promise = iota.prepareTransfers(SeedSender, [tx1]) //let's prepare a bundle first. If you do not add any other options then everything is taken care by library\n                        .then(trytes => {\n                            console.log(\"Bundle was created. Sending it...\")\n                            return iota.sendTrytes(trytes,\n                                                   3, //trytes\n                                                   9) // MWM; in case of Devnet it is 9\n                        })\n                        .then(response => {\n                            console.log(\"It has been sent. Now let's see all transaction(s) that were sent:\");\n                            console.log(response);\n                        })\n                        .catch(err=>{\n                            console.log(\"Something went wrong: %s\", err);\n                        })\n```\n\n    \n    Sending iotas... Please wait...\n    Bundle was created. Sending it...\n    It has been sent. Now let's see all transaction(s) that were sent:\n    [ { hash:\n         'SGJWWHQZJKGAWY9PDM9ASRNIRVIRZQZHYZJCCVZYMTRAKNCIJFJJEUSC9OQHOCMIZLFCPSYREXUPIB999',\n        signatureMessageFragment:\n         '999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999',\n        address:\n         'BMFSMZMNBGKHAWPIZIOMJGRBXZETVSAYDSTDQCHLYTBWZMIXLNXF9XHLTMOCATFVFOMBQF9IOQGPEBPDC',\n        value: 10,\n        obsoleteTag: 'ZSIBEK999IOTA999TUTORIAL999',\n        timestamp: 1568375569,\n        currentIndex: 0,\n        lastIndex: 3,\n        bundle:\n         'SBOLDCVCHALOYRKBCUJLQXTFAVVPVRBYJUOZTYWDIJIDUOVK9HKTNLGKSJABIICUZDBQRABWLTSWSOCBA',\n        trunkTransaction:\n         'CXUFSCMYZCLKUIFOQAGIXQKTKBDKFWSEHTSHOSM9MQLPJBACKGKEIISSTAXJRZRO9FXAHTVKHUDXIX999',\n        branchTransaction:\n         'B9SHRBPVQZYSYJCBMAENTHFCSBMWTFIQ9O9VRNYNCHTMAWYGBDL9TUZTPQFVTBBKWXPWBXNNSNL9HE999',\n        tag: 'HRIBEK999IOTA999TUTORIAL999',\n        attachmentTimestamp: 1568375730058,\n        attachmentTimestampLowerBound: 0,\n        attachmentTimestampUpperBound: 3812798742493,\n        nonce: 'ZPT9PHZTHBXAOMZSDLUDKUPMEJO' },\n      { hash:\n         'CXUFSCMYZCLKUIFOQAGIXQKTKBDKFWSEHTSHOSM9MQLPJBACKGKEIISSTAXJRZRO9FXAHTVKHUDXIX999',\n        signatureMessageFragment:\n         'SXOQFDSJXYZMEVAGKYAGDWIZ9GMFAELZXXCLIRZTZ9YOTDBE9LLY9PEUVTNOJSZDA9NICI9MPCWUCMMSDFGTZENVPGQQZACMBHZXRNTTGXYKCTXK9RHDGGJIGMLMYHQIOHYKMZONFGQI9SHNJJZNN9DRUC9UI9TUKDDSNKMWIEVJMHKGS9QIQOEBZ9X9GCLSWDD9LMHINADZWJFK9XIWMBKXS9CLZMLDLKKXPSEBMHOHFVYPWEZZNWJARZMOAWOJE9DPBSUXIKW9AGVFVEXHULNKHCZKSHNQUQJKXOYCA9RADZPKRCAAUGTEFCQKLYFXAMVXLWLYEBHGOF9FLCSDFOGGAGRQCWVWGNMQEIWFBCIWWF9ZDHDQWSBSSFVWV9XHWKSTZEZFHMOKT9MGHBTYYMHECJNOZPWWOZONWXIOPMRWLKVJU9IZ9MMFC9PLBJUPHCYBKYAOZPXOIHNQSQMRYEOJQCCQTDCYKPXBJ9IDAOMLPUUFZOEUCXLXZGPUFSC9TIPMFPLAWTT9MMONRZRWDZIZRKTJXHULZANYWORHLUINMKRSUACGT9XJUORNWKTXHNLEOITFWUGDQOICZZMCQWJPSNBRIDI99ALFHYIUPVZJKQNTTLCSKDZWPIGUZNPTKKNCCKCBN9CJNTICDYRNYJBAPEDCCWCKKRSZJZPKJQQLLEGWVTBVUNNOIYWWPA9ZGGHBQOWZHKAIPC9Z9UPHLFJPZBUV9HPNVGYZVNOACJBSBUERPNPUEWZEJVUIFCCATTKKLUUPJ9HHORWOOTNFMSYVYQXENHNOZCJBZZQHPDXLBGGPCZIKTCPSNUXVZ9WMRCBBUQXOTMSMSRQHUKONMPWMSOMORXWNKQL9IBRYQHQNLJCRPZYDOGWCHZCRHSOYYYAAOZZORBG9OIYFZXUFVVZWETRCDVSJQPYBWCMOA9HLDHIMGMHYS9FEJXQGPS9PNADWZBBFWICBW9RSJAAPTZPFHZOOEGLBMUHGJVSNISBVCYYHBJRQBXH9KYCCUB9VGBAYXUTGUTXGUZWWNFWWEXOJNHWJDHPOEMMSQJCBRBTSWEBQDQTVNDULI99GAYRPVOIMNN9KKNKPKBTWAUJZNXHMGHVCMZZRWIPSTIHJBDFGSBNCMBYDNLG9JEMDZBTKPNKMTMLANTZHHKDDIYOBVLJTQGHPPLNWFNEPTSZMVT9RRGCKYXC99SABLWIZVYAEMKZUSSGEHNVLXFKKFFTDGTHACHFEAULNPFPUKIRKZJTUCZFDFASOLFJPQJPDSXOBSIVWGSQASYRSKDBCJTSXPPXYBFLBFDGTKKGXNXFFPRGSTZODAIXLCGQDWWCTHPUMQHQWHIPCGMYFGBOVS9QCJVRWMPUWAYFACQGPOUSEVTKESYHYZGDLYWWDTETTOREBO9HCVUSPTZIYIXSEQMCFSMRTXSCYKKY9KFPGLVNYXQDGRINJJDHHLUOUJLCIDODG9NSBSUNFTKVDRKZNKRXULU9MILNMYYGTMDUUICPQVO9LIAF9FQBFM9GSNESZVXHVHBBQABYVAKQHTMJTOTDELHDLCC9OWKMFAJMMU9XDFLMJAXGYIHNAXYRQXQWUPLYVXUWXIXEBTALYH9WUHQCDDPGZCRVOPSUZHESAK9BOYZTWLAYSIKSFDRCUIDWZTAGSCCZNEGPEMSVZDCLEVPOUOVJPWGF9DBZSDYECWLBEPIXOZNAEXVALZHJLZWJQZYSCPVYEV9ZOW9CCMAPROMWARZTZNKWCAQDOB99DABUFCNNMBGHRGMZEYDGDZCJFRPLYJFLXIUSHFHQYUHTNWSBGUSDAQJYKGBEIZNPKJMUSL9J9ABXMKMU9CJFWTFC9JDIEGNTXJIDATWJKNYYULZWTVNUADGULKK9WCMRYVFXMCXGZMJ9SJNWHRHAKQUADJLHHHYSNIZLS9WOSTL9ZHUYNDUXWLEOKNUSHCDOHVIPAFRCWQZQZQWV9WB9PHFXINUPBBOGXAGULQ9OJIWOQTZX9YDNRQHBELIFSZOHVCUUAARYDFFWGBAKJBDMONWNTL9G9FUUACUVSJSGKCMWOXBHPYHKDKYPGPNDEMUBVKNIQEKTQYYZKITHY9SVHLC9STXKNBLMLKET9NPFPPQFI9UJPAZJUEVGSZCXRACWLROZQCSCVQCNJZF9DHDBTPCI9DNGYSJMAEQVMZTB',\n        address:\n         'CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9',\n        value: -1000,\n        obsoleteTag: '999999999999999999999999999',\n        timestamp: 1568375569,\n        currentIndex: 1,\n        lastIndex: 3,\n        bundle:\n         'SBOLDCVCHALOYRKBCUJLQXTFAVVPVRBYJUOZTYWDIJIDUOVK9HKTNLGKSJABIICUZDBQRABWLTSWSOCBA',\n        trunkTransaction:\n         'CSKEVBJIFUZGNOTZJESXNXIMAM9YRPWCSGOJVMOPQV9NWTJBWB9BNQKVIMRBRHUZNRN9EYQVGTENZL999',\n        branchTransaction:\n         'B9SHRBPVQZYSYJCBMAENTHFCSBMWTFIQ9O9VRNYNCHTMAWYGBDL9TUZTPQFVTBBKWXPWBXNNSNL9HE999',\n        tag: '999999999999999999999999999',\n        attachmentTimestamp: 1568375730023,\n        attachmentTimestampLowerBound: 0,\n        attachmentTimestampUpperBound: 3812798742493,\n        nonce: 'BIXTK9DNMNNXLFFXWISJVV9GZLW' },\n      { hash:\n         'CSKEVBJIFUZGNOTZJESXNXIMAM9YRPWCSGOJVMOPQV9NWTJBWB9BNQKVIMRBRHUZNRN9EYQVGTENZL999',\n        signatureMessageFragment:\n         'ESSLXVQYVCAVVQUWCBFOWHFWCOZZYHMA9UQOYLITNOADMIAUVK9V9MIZNFZSFMHBPMLLJSFTW9FTGCLQ9NRGTVKGRL9DSAIJIBXEZCTOEGBECIMMDTNU9JUUQBXMJQJXKELIVEEUUMUVJCXQXPAZZTWBE9FYYQXDEDWTWB9URRWTKYRIMNARVJSFKCGELPTQLJXHUIAWVAVMSSMVIXQIEORCPIUIFD9FYJMOUOGEGY99KQDIK9ATWZSEMVGCUYDTIVWKJHPWSEYQHBSMB9LXAGUPWVEIRKXUSXTBLNAZIMSKWZLBVSESMRNETYOOVSRQFVP9IIJDTMWRPKXLGHXYQVBQFIRRKEAZOAVWMNOGAG9GGNLTPDSLWYPMMSZDIAUZQUC9GYXBWOWGROBIYHZHZADJSIMUCXJJGDVEKXLJVAKBAMBSHDUOLVNMHLVPMUKGSAELLPRAIZVQP9EOABTWERBTTXFNBRTSXKBZSZWHMFYXWABEWGACQZQTNEDNRDZBVSUJLZKCYGADMNFHHXNFIMILMVQDUNBEIYJFOZDMRASGFMY9QJKRKXWAGOLZASZJNEJ9FUM9LETMOKKZJ9CQCWNIINVVBLBAPCWVXXVGJHUDBTTTJAKDYVLYJISKPVGXMUUTFGTWAUWCSSKBOWFOKHVLMRDBZQ9VVXHBYTLXDVEVUPIZCRGRIJVRBSRAVRSCUNHPATHEIPHEXTVVPIMLNEA9XRQNEVNTNBXQAJBD9FCPHGJVJ9ETNBIWNVJQUKNFSXQCUIXJKJEEFNALYHEJLG9HXAYTACXTSTDEECCBCDKHWXNEPGFCDFZWDRYXBOEJ9ZGTQPIBBIXXPQAOQMJZBRO99AGJPRXYGZZK9YCDCYJMQFBSZKL9XOOZECDGTSFCQSSHJCEDGMKORHKD9VTREYROYNECLQNYMBXZFUMYOJTZQYSEJAWUIIWBQ9GMHGXGOSIFISZVQFYCKRUVPVCTILZVH9RIBIEFBVNFK9QKZDJ9RHGMHSQJORLWDLXFYISXGKTOBMZPWXWXVXIHSNXTXOWMNRHTDOWISPLQKSFDSBUNCJPUBWADRLAHQLFO9VWK9XHU9CGUZXFBHZIFXWIJZZM9YZEVYEPRWQMXWIVMKYWKCCXMTGZWWHEWJYHWFRRBBGKXHGBGJWIBMNOEHUPSCPCPTJDQVJRCEGPQOEUKPIURONJI9JKPQHJXHEVTWZZPDEUIOAKWFMZTIAUZVYHSVWIK9TBBHWOEBZPDAZHZSYGWRVRFSBYRRUNFQTDAJBJNWQZHNIKIAIQMEL9ZKJJFZJBXANCBLXOXATYSDMXQQBJMPYJIDXEGPDILZTOYODLSGXQPYAJCPMRKWZSPEFVUYECEJBDVQQKIYPMFEO99HAXCUXABAFMWNOYWGGAIBQVXCLLXWJ9SQADIQMCNYDMBZGIYOOIAWZNNGXTWGZPLNWFNIJIGA9JXGABHONIEDAEFFJWASFITZHFJPAKCFSMBVPLXCLFFEDAOMWCMCYDDGBGJUY9VTTELMSHUP9J9SECNHRXAHITDHGZPJPUUETXIYXOGWBJPZOTYVRTGIOYLUDPGELBOPIOZK9WELGTVTXMCRKXZQACGINYHKYVOUQZDYMPFWMZJERHCVSAIHXPVYHITKGWDZQXHVVERISKPMBTTRFE9NGSAHTQZCFFQMRUMNGUFUQSOAWFQDKIIAAINUMCECNQURUFWADTB9XWESZANVLWSARRJNHDM9OUXICCBSAZXWZTY99JUADOSWHIJAUFCSUGNZVZAKCVJXBKJ9ATLUNASYALDS9SGAUCHJWCJOOPUJZLWNFYCB9SRLAMYGQPRWKGHQRZLDOTFCSCHSYNUEHEBFO9HISZ9FZBYAUUMACYELCGB9T9VNXOSOECIHO9NGYDXNA9AEWZS9JVNPIMLHNVNQEZSDCMZRXXMJLFSNDP9DQMPCCUVERKI9UBRJYYMLXREQAKSHRLDKXAXIHUAHIJ9D9LHSKTMDJBCIOTNKFQDBUYNJWTYIQ9P9TYPXH9MOAVKQUVKWZDZSLGKSHFVCS9HHCLVHCMMPDASFC9XETLHVUPWABHISFXPLOSGHLSOCASKIRSYCOZL99P9SNNSTOTLUCHLRASGPIANFEWE9RSGPUZTRHLGQSXBWJSCLBRGRPDMAMIUYOQSXPIWYRRZILEJKUBZKZZ',\n        address:\n         'CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9',\n        value: 0,\n        obsoleteTag: '999999999999999999999999999',\n        timestamp: 1568375569,\n        currentIndex: 2,\n        lastIndex: 3,\n        bundle:\n         'SBOLDCVCHALOYRKBCUJLQXTFAVVPVRBYJUOZTYWDIJIDUOVK9HKTNLGKSJABIICUZDBQRABWLTSWSOCBA',\n        trunkTransaction:\n         'CSWMPIKZCTCNACHNMJYZDBHFREPWCEZMLSZVHBNNJ9SSPMWGVMM9MZCONKPRVJXRJZPKSLNTIBZJAE999',\n        branchTransaction:\n         'B9SHRBPVQZYSYJCBMAENTHFCSBMWTFIQ9O9VRNYNCHTMAWYGBDL9TUZTPQFVTBBKWXPWBXNNSNL9HE999',\n        tag: '999999999999999999999999999',\n        attachmentTimestamp: 1568375729985,\n        attachmentTimestampLowerBound: 0,\n        attachmentTimestampUpperBound: 3812798742493,\n        nonce: 'QSOBTMACZXFAFNLW99EVSCBAQAN' },\n      { hash:\n         'CSWMPIKZCTCNACHNMJYZDBHFREPWCEZMLSZVHBNNJ9SSPMWGVMM9MZCONKPRVJXRJZPKSLNTIBZJAE999',\n        signatureMessageFragment:\n         '999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999',\n        address:\n         'NDQMBGBQIBAQURVAQEUVONVMECKXSNYZZNKMMMOHOLPEYHJHDBTFWOZMAPFUAHLHIQUAV9GVZPEMBKL9Z',\n        value: 990,\n        obsoleteTag: '999999999999999999999999999',\n        timestamp: 1568375569,\n        currentIndex: 3,\n        lastIndex: 3,\n        bundle:\n         'SBOLDCVCHALOYRKBCUJLQXTFAVVPVRBYJUOZTYWDIJIDUOVK9HKTNLGKSJABIICUZDBQRABWLTSWSOCBA',\n        trunkTransaction:\n         'B9SHRBPVQZYSYJCBMAENTHFCSBMWTFIQ9O9VRNYNCHTMAWYGBDL9TUZTPQFVTBBKWXPWBXNNSNL9HE999',\n        branchTransaction:\n         'B9SHRBPVQZYSYJCBMAENTHFCSBMWTFIQ9O9VRNYNCHTMAWYGBDL9TUZTPQFVTBBKWXPWBXNNSNL9HE999',\n        tag: '999999999999999999999999999',\n        attachmentTimestamp: 1568375729966,\n        attachmentTimestampLowerBound: 0,\n        attachmentTimestampUpperBound: 3812798742493,\n        nonce: 'DBYYBUDC9OZDRG9KKFFFVOSBXMZ' } ]\n\n\nLet's review all transactions that has been prepared and sent eventually:\n* The first transaction `current_index=0` is the `output TX` that basically adds tokens to some address\n* Transactions `current_index=1` and `current_index=2` are two parts of the same transaction - `Input TX`. This transaction deducts tokens from the address(es). You can see negative `value` in the transaction `current_index=1`\n* Why there are two parts? Since the transaction spends tokens it has to be signed in order to validate the ownership. Signature is generated from the private key and the signature can be observed in the field `signature_message_fragment`. Here is the thing. Do you remember when different `security levels` were discussed? There are three security levels available and the given level has the direct impact on length of the signature. Since `signature_message_fragment` is of the fixed size, if `SL>1` then the transaction has to be split to be able to accommodate full signature.\n* The last transaction `current_index=3` moves unspent tokens to the first unused address of the given seed.\n\nThe following tasks have to be done behind the curtain in addition to the standard transaction preparation process:\n* Search for address(es) with some balance until total amount of tokens available is large enough to be spent. You can use more input addresses if needed\n* If there would be some unspent amount of tokens then also search for the first unused address\n* Spending transactions (Input TX) has to be properly signed and split in case of `SL>1`\n* There is also some quick check performed whether resulting number of tokens is zero (no more tokens, no less tokens. Number of tokens has to be balanced).\n\nSo basically all steps we tried in the chapter had to be done also behind the curtain while using `send_transfer` extended API call. You can also see that some of those operations may be quite expensive in terms of time while being completely stateless. In real world applications it would be better to save some states (index of last address, used addresses, etc.) to avoid too many expensive operations.\n\nYou can review the given broadcasted transactions also in the tangle explorer (for devnet):\n* https://devnet.thetangle.org/address/BMFSMZMNBGKHAWPIZIOMJGRBXZETVSAYDSTDQCHLYTBWZMIXLNXF9XHLTMOCATFVFOMBQF9IOQGPEBPDC\n", "meta": {"hexsha": "114266961fc5e190cc62946123c701a8a24a504d", "size": 146988, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Developer Lab/Allchapters_javascript.ipynb", "max_stars_repo_name": "Hribek25/IOTA101", "max_stars_repo_head_hexsha": "adf5c4cced557d60836bf6ba80a1080b2607c8e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2018-06-28T18:15:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T22:05:53.000Z", "max_issues_repo_path": "Developer Lab/Allchapters_javascript.ipynb", "max_issues_repo_name": "Hribek25/IOTA101", "max_issues_repo_head_hexsha": "adf5c4cced557d60836bf6ba80a1080b2607c8e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-07-01T19:45:20.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-01T18:18:04.000Z", "max_forks_repo_path": "Developer Lab/Allchapters_javascript.ipynb", "max_forks_repo_name": "Hribek25/IOTA101", "max_forks_repo_head_hexsha": "adf5c4cced557d60836bf6ba80a1080b2607c8e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-08-26T20:01:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-26T17:09:56.000Z", "avg_line_length": 75.8843572535, "max_line_length": 2690, "alphanum_fraction": 0.7584700792, "converted": true, "num_tokens": 39315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15203224162217424, "lm_q2_score": 0.055823144276191644, "lm_q1q2_score": 0.008486917758707462}}
{"text": "```python\n!pip install --extra-index-url https://test.pypi.org/simple/ GML==3.1.4\n```\n\n    Looking in indexes: https://pypi.org/simple, https://test.pypi.org/simple/\n    Collecting GML==3.1.4\n      Downloading https://test-files.pythonhosted.org/packages/13/d0/e5cf98e9b6e69bb71405cec2e25052881154cf32fef8bbe4114a94d312d0/GML-3.1.4-py3-none-any.whl (15.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 15.4 MB 5.1 MB/s eta 0:00:01    |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588             | 9.1 MB 4.0 MB/s eta 0:00:02\n    \u001b[?25hRequirement already satisfied: torch in /opt/conda/lib/python3.7/site-packages (from GML==3.1.4) (1.6.0)\n    Requirement already satisfied: beautifulsoup4 in /opt/conda/lib/python3.7/site-packages (from GML==3.1.4) (4.9.0)\n    Requirement already satisfied: tqdm in /opt/conda/lib/python3.7/site-packages (from GML==3.1.4) (4.45.0)\n    Requirement already satisfied: lightgbm in /opt/conda/lib/python3.7/site-packages (from GML==3.1.4) (2.3.1)\n    Requirement already satisfied: seaborn in /opt/conda/lib/python3.7/site-packages (from GML==3.1.4) (0.10.0)\n    Requirement already satisfied: matplotlib in /opt/conda/lib/python3.7/site-packages (from GML==3.1.4) (3.2.1)\n    Requirement already satisfied: scikit-learn in /opt/conda/lib/python3.7/site-packages (from GML==3.1.4) (0.23.2)\n    Requirement already satisfied: xgboost in /opt/conda/lib/python3.7/site-packages (from GML==3.1.4) (1.2.1)\n    Collecting efficientnet-pytorch\n      Downloading efficientnet_pytorch-0.7.0.tar.gz (20 kB)\n    Requirement already satisfied: tensorflow in /opt/conda/lib/python3.7/site-packages (from GML==3.1.4) (2.3.1)\n    Requirement already satisfied: albumentations in /opt/conda/lib/python3.7/site-packages (from GML==3.1.4) (0.5.1)\n    Requirement already satisfied: sympy in /opt/conda/lib/python3.7/site-packages (from GML==3.1.4) (1.5.1)\n    Requirement already satisfied: catboost in /opt/conda/lib/python3.7/site-packages (from GML==3.1.4) (0.24.2)\n    Collecting ftfy\n      Downloading ftfy-5.8.tar.gz (64 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 64 kB 423 kB/s eta 0:00:011\n    \u001b[?25hRequirement already satisfied: Keras in /opt/conda/lib/python3.7/site-packages (from GML==3.1.4) (2.4.3)\n    Collecting fastai==1.0.61\n      Downloading fastai-1.0.61-py3-none-any.whl (239 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 239 kB 579 kB/s eta 0:00:01\n    \u001b[?25hRequirement already satisfied: category-encoders in /opt/conda/lib/python3.7/site-packages (from GML==3.1.4) (2.2.2)\n    Collecting string\n      Downloading https://test-files.pythonhosted.org/packages/7a/63/c48edcd5ab679d7e4873ccd540ccbfd29a82a565b4db2a055f4005e090ab/string-1.0.tar.gz (518 bytes)\n    Requirement already satisfied: pandas in /opt/conda/lib/python3.7/site-packages (from GML==3.1.4) (1.1.4)\n    Requirement already satisfied: torchvision in /opt/conda/lib/python3.7/site-packages (from GML==3.1.4) (0.7.0)\n    Requirement already satisfied: requests in /opt/conda/lib/python3.7/site-packages (from GML==3.1.4) (2.23.0)\n    Collecting Pint\n      Downloading Pint-0.16.1-py2.py3-none-any.whl (205 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 205 kB 744 kB/s eta 0:00:01\n    \u001b[?25hRequirement already satisfied: numpy in /opt/conda/lib/python3.7/site-packages (from GML==3.1.4) (1.18.5)\n    Requirement already satisfied: transformers in /opt/conda/lib/python3.7/site-packages (from GML==3.1.4) (3.4.0)\n    Requirement already satisfied: future in /opt/conda/lib/python3.7/site-packages (from torch->GML==3.1.4) (0.18.2)\n    Requirement already satisfied: soupsieve>1.2 in /opt/conda/lib/python3.7/site-packages (from beautifulsoup4->GML==3.1.4) (1.9.4)\n    Requirement already satisfied: scipy in /opt/conda/lib/python3.7/site-packages (from lightgbm->GML==3.1.4) (1.4.1)\n    Requirement already satisfied: cycler>=0.10 in /opt/conda/lib/python3.7/site-packages (from matplotlib->GML==3.1.4) (0.10.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /opt/conda/lib/python3.7/site-packages (from matplotlib->GML==3.1.4) (2.4.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /opt/conda/lib/python3.7/site-packages (from matplotlib->GML==3.1.4) (1.2.0)\n    Requirement already satisfied: python-dateutil>=2.1 in /opt/conda/lib/python3.7/site-packages (from matplotlib->GML==3.1.4) (2.8.1)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /opt/conda/lib/python3.7/site-packages (from scikit-learn->GML==3.1.4) (2.1.0)\n    Requirement already satisfied: joblib>=0.11 in /opt/conda/lib/python3.7/site-packages (from scikit-learn->GML==3.1.4) (0.14.1)\n    Requirement already satisfied: tensorflow-estimator<2.4.0,>=2.3.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow->GML==3.1.4) (2.3.0)\n    Requirement already satisfied: grpcio>=1.8.6 in /opt/conda/lib/python3.7/site-packages (from tensorflow->GML==3.1.4) (1.33.2)\n    Requirement already satisfied: keras-preprocessing<1.2,>=1.1.1 in /opt/conda/lib/python3.7/site-packages (from tensorflow->GML==3.1.4) (1.1.2)\n    Requirement already satisfied: opt-einsum>=2.3.2 in /opt/conda/lib/python3.7/site-packages (from tensorflow->GML==3.1.4) (3.3.0)\n    Requirement already satisfied: google-pasta>=0.1.8 in /opt/conda/lib/python3.7/site-packages (from tensorflow->GML==3.1.4) (0.2.0)\n    Requirement already satisfied: tensorboard<3,>=2.3.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow->GML==3.1.4) (2.4.0)\n    Requirement already satisfied: wheel>=0.26 in /opt/conda/lib/python3.7/site-packages (from tensorflow->GML==3.1.4) (0.34.2)\n    Requirement already satisfied: absl-py>=0.7.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow->GML==3.1.4) (0.11.0)\n    Requirement already satisfied: h5py<2.11.0,>=2.10.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow->GML==3.1.4) (2.10.0)\n    Requirement already satisfied: protobuf>=3.9.2 in /opt/conda/lib/python3.7/site-packages (from tensorflow->GML==3.1.4) (3.14.0)\n    Requirement already satisfied: astunparse==1.6.3 in /opt/conda/lib/python3.7/site-packages (from tensorflow->GML==3.1.4) (1.6.3)\n    Requirement already satisfied: termcolor>=1.1.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow->GML==3.1.4) (1.1.0)\n    Requirement already satisfied: six>=1.12.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow->GML==3.1.4) (1.14.0)\n    Requirement already satisfied: gast==0.3.3 in /opt/conda/lib/python3.7/site-packages (from tensorflow->GML==3.1.4) (0.3.3)\n    Requirement already satisfied: wrapt>=1.11.1 in /opt/conda/lib/python3.7/site-packages (from tensorflow->GML==3.1.4) (1.11.2)\n    Requirement already satisfied: PyYAML in /opt/conda/lib/python3.7/site-packages (from albumentations->GML==3.1.4) (5.3.1)\n    Requirement already satisfied: opencv-python-headless>=4.1.1 in /opt/conda/lib/python3.7/site-packages (from albumentations->GML==3.1.4) (4.4.0.46)\n    Requirement already satisfied: scikit-image>=0.16.1 in /opt/conda/lib/python3.7/site-packages (from albumentations->GML==3.1.4) (0.16.2)\n    Requirement already satisfied: imgaug>=0.4.0 in /opt/conda/lib/python3.7/site-packages (from albumentations->GML==3.1.4) (0.4.0)\n    Requirement already satisfied: mpmath>=0.19 in /opt/conda/lib/python3.7/site-packages (from sympy->GML==3.1.4) (1.1.0)\n    Requirement already satisfied: plotly in /opt/conda/lib/python3.7/site-packages (from catboost->GML==3.1.4) (4.12.0)\n    Requirement already satisfied: graphviz in /opt/conda/lib/python3.7/site-packages (from catboost->GML==3.1.4) (0.8.4)\n    Requirement already satisfied: wcwidth in /opt/conda/lib/python3.7/site-packages (from ftfy->GML==3.1.4) (0.1.9)\n    Requirement already satisfied: nvidia-ml-py3 in /opt/conda/lib/python3.7/site-packages (from fastai==1.0.61->GML==3.1.4) (7.352.0)\n    Requirement already satisfied: bottleneck in /opt/conda/lib/python3.7/site-packages (from fastai==1.0.61->GML==3.1.4) (1.3.2)\n    Requirement already satisfied: Pillow in /opt/conda/lib/python3.7/site-packages (from fastai==1.0.61->GML==3.1.4) (8.0.1)\n    Requirement already satisfied: numexpr in /opt/conda/lib/python3.7/site-packages (from fastai==1.0.61->GML==3.1.4) (2.7.1)\n    Requirement already satisfied: spacy>=2.0.18; python_version < \"3.8\" in /opt/conda/lib/python3.7/site-packages (from fastai==1.0.61->GML==3.1.4) (2.3.2)\n    Requirement already satisfied: fastprogress>=0.2.1 in /opt/conda/lib/python3.7/site-packages (from fastai==1.0.61->GML==3.1.4) (1.0.0)\n    Requirement already satisfied: packaging in /opt/conda/lib/python3.7/site-packages (from fastai==1.0.61->GML==3.1.4) (20.1)\n    Requirement already satisfied: patsy>=0.5.1 in /opt/conda/lib/python3.7/site-packages (from category-encoders->GML==3.1.4) (0.5.1)\n    Requirement already satisfied: statsmodels>=0.9.0 in /opt/conda/lib/python3.7/site-packages (from category-encoders->GML==3.1.4) (0.11.1)\n    Requirement already satisfied: pytz>=2017.2 in /opt/conda/lib/python3.7/site-packages (from pandas->GML==3.1.4) (2019.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests->GML==3.1.4) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests->GML==3.1.4) (2020.11.8)\n    Requirement already satisfied: idna<3,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests->GML==3.1.4) (2.9)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests->GML==3.1.4) (1.25.9)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /opt/conda/lib/python3.7/site-packages (from Pint->GML==3.1.4) (1.6.0)\n    Requirement already satisfied: filelock in /opt/conda/lib/python3.7/site-packages (from transformers->GML==3.1.4) (3.0.10)\n    Requirement already satisfied: regex!=2019.12.17 in /opt/conda/lib/python3.7/site-packages (from transformers->GML==3.1.4) (2020.4.4)\n    Requirement already satisfied: sentencepiece!=0.1.92 in /opt/conda/lib/python3.7/site-packages (from transformers->GML==3.1.4) (0.1.94)\n    Requirement already satisfied: sacremoses in /opt/conda/lib/python3.7/site-packages (from transformers->GML==3.1.4) (0.0.43)\n    Requirement already satisfied: tokenizers==0.9.2 in /opt/conda/lib/python3.7/site-packages (from transformers->GML==3.1.4) (0.9.2)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /opt/conda/lib/python3.7/site-packages (from tensorboard<3,>=2.3.0->tensorflow->GML==3.1.4) (0.4.1)\n    Requirement already satisfied: markdown>=2.6.8 in /opt/conda/lib/python3.7/site-packages (from tensorboard<3,>=2.3.0->tensorflow->GML==3.1.4) (3.2.1)\n    Requirement already satisfied: google-auth<2,>=1.6.3 in /opt/conda/lib/python3.7/site-packages (from tensorboard<3,>=2.3.0->tensorflow->GML==3.1.4) (1.14.0)\n    Requirement already satisfied: werkzeug>=0.11.15 in /opt/conda/lib/python3.7/site-packages (from tensorboard<3,>=2.3.0->tensorflow->GML==3.1.4) (1.0.1)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /opt/conda/lib/python3.7/site-packages (from tensorboard<3,>=2.3.0->tensorflow->GML==3.1.4) (1.7.0)\n    Requirement already satisfied: setuptools>=41.0.0 in /opt/conda/lib/python3.7/site-packages (from tensorboard<3,>=2.3.0->tensorflow->GML==3.1.4) (46.1.3.post20200325)\n    Requirement already satisfied: networkx>=2.0 in /opt/conda/lib/python3.7/site-packages (from scikit-image>=0.16.1->albumentations->GML==3.1.4) (2.4)\n    Requirement already satisfied: imageio>=2.3.0 in /opt/conda/lib/python3.7/site-packages (from scikit-image>=0.16.1->albumentations->GML==3.1.4) (2.8.0)\n    Requirement already satisfied: PyWavelets>=0.4.0 in /opt/conda/lib/python3.7/site-packages (from scikit-image>=0.16.1->albumentations->GML==3.1.4) (1.1.1)\n    Requirement already satisfied: Shapely in /opt/conda/lib/python3.7/site-packages (from imgaug>=0.4.0->albumentations->GML==3.1.4) (1.7.1)\n    Requirement already satisfied: opencv-python in /opt/conda/lib/python3.7/site-packages (from imgaug>=0.4.0->albumentations->GML==3.1.4) (4.4.0.46)\n    Requirement already satisfied: retrying>=1.3.3 in /opt/conda/lib/python3.7/site-packages (from plotly->catboost->GML==3.1.4) (1.3.3)\n    Requirement already satisfied: murmurhash<1.1.0,>=0.28.0 in /opt/conda/lib/python3.7/site-packages (from spacy>=2.0.18; python_version < \"3.8\"->fastai==1.0.61->GML==3.1.4) (1.0.4)\n    Requirement already satisfied: cymem<2.1.0,>=2.0.2 in /opt/conda/lib/python3.7/site-packages (from spacy>=2.0.18; python_version < \"3.8\"->fastai==1.0.61->GML==3.1.4) (2.0.4)\n    Requirement already satisfied: wasabi<1.1.0,>=0.4.0 in /opt/conda/lib/python3.7/site-packages (from spacy>=2.0.18; python_version < \"3.8\"->fastai==1.0.61->GML==3.1.4) (0.8.0)\n    Requirement already satisfied: blis<0.5.0,>=0.4.0 in /opt/conda/lib/python3.7/site-packages (from spacy>=2.0.18; python_version < \"3.8\"->fastai==1.0.61->GML==3.1.4) (0.4.1)\n    Requirement already satisfied: catalogue<1.1.0,>=0.0.7 in /opt/conda/lib/python3.7/site-packages (from spacy>=2.0.18; python_version < \"3.8\"->fastai==1.0.61->GML==3.1.4) (1.0.0)\n    Requirement already satisfied: preshed<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from spacy>=2.0.18; python_version < \"3.8\"->fastai==1.0.61->GML==3.1.4) (3.0.4)\n    Requirement already satisfied: thinc==7.4.1 in /opt/conda/lib/python3.7/site-packages (from spacy>=2.0.18; python_version < \"3.8\"->fastai==1.0.61->GML==3.1.4) (7.4.1)\n    Requirement already satisfied: srsly<1.1.0,>=1.0.2 in /opt/conda/lib/python3.7/site-packages (from spacy>=2.0.18; python_version < \"3.8\"->fastai==1.0.61->GML==3.1.4) (1.0.4)\n    Requirement already satisfied: plac<1.2.0,>=0.9.6 in /opt/conda/lib/python3.7/site-packages (from spacy>=2.0.18; python_version < \"3.8\"->fastai==1.0.61->GML==3.1.4) (1.1.3)\n    Requirement already satisfied: zipp>=0.5 in /opt/conda/lib/python3.7/site-packages (from importlib-metadata; python_version < \"3.8\"->Pint->GML==3.1.4) (3.1.0)\n    Requirement already satisfied: click in /opt/conda/lib/python3.7/site-packages (from sacremoses->transformers->GML==3.1.4) (7.1.1)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /opt/conda/lib/python3.7/site-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<3,>=2.3.0->tensorflow->GML==3.1.4) (1.2.0)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /opt/conda/lib/python3.7/site-packages (from google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow->GML==3.1.4) (3.1.1)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /opt/conda/lib/python3.7/site-packages (from google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow->GML==3.1.4) (0.2.7)\n    Requirement already satisfied: rsa<4.1,>=3.1.4 in /opt/conda/lib/python3.7/site-packages (from google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow->GML==3.1.4) (4.0)\n    Requirement already satisfied: decorator>=4.3.0 in /opt/conda/lib/python3.7/site-packages (from networkx>=2.0->scikit-image>=0.16.1->albumentations->GML==3.1.4) (4.4.2)\n    Requirement already satisfied: oauthlib>=3.0.0 in /opt/conda/lib/python3.7/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<3,>=2.3.0->tensorflow->GML==3.1.4) (3.0.1)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /opt/conda/lib/python3.7/site-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow->GML==3.1.4) (0.4.8)\n    Building wheels for collected packages: efficientnet-pytorch, ftfy, string\n      Building wheel for efficientnet-pytorch (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Created wheel for efficientnet-pytorch: filename=efficientnet_pytorch-0.7.0-py3-none-any.whl size=16035 sha256=91f9c530af8b386b18e4bacfd62a7846203d286fc4b2708f871cc35a878f7364\n      Stored in directory: /root/.cache/pip/wheels/b7/cc/0d/41d384b0071c6f46e542aded5f8571700ace4f1eb3f1591c29\n      Building wheel for ftfy (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Created wheel for ftfy: filename=ftfy-5.8-py3-none-any.whl size=45612 sha256=a078e47115c595c2490d421617f49a9247910be04835c0941f2a863b3a5985fa\n      Stored in directory: /root/.cache/pip/wheels/49/1c/fc/8b19700f939810cd8fd9495ae34934b246279791288eda1c31\n      Building wheel for string (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Created wheel for string: filename=string-1.0-py3-none-any.whl size=1027 sha256=b5ecf182d3b42ab883f9c1e7d6046fcc4b1d405d752c6b6a82bea639fcea342b\n      Stored in directory: /root/.cache/pip/wheels/5f/79/c4/8e2dd3efc8a8aa61808be4595eca947cbf1628109e1a2ca15d\n    Successfully built efficientnet-pytorch ftfy string\n    Installing collected packages: efficientnet-pytorch, ftfy, fastai, string, Pint, GML\n      Attempting uninstall: fastai\n        Found existing installation: fastai 2.0.19\n        Uninstalling fastai-2.0.19:\n          Successfully uninstalled fastai-2.0.19\n    Successfully installed GML-3.1.4 Pint-0.16.1 efficientnet-pytorch-0.7.0 fastai-1.0.61 ftfy-5.8 string-1.0\n\n\n\n```python\nfrom GML import AutoNLP\n```\n\n    \u001b[34m\u001b[1mwandb\u001b[0m: \u001b[33mWARNING\u001b[0m W&B installed but not logged in.  Run `wandb login` or set the WANDB_API_KEY env variable.\n\n\n    GML is up to date \n     \n    \r\n    \r\n    Feel free to contact us at: https://github.com/Muhammad4hmed/Ghalat-Machine-Learning\n    Your GML is ready!\n\n\n\n```python\nimport pandas as pd\n```\n\n\n```python\ndata = pd.read_csv('../input/nlp-dataset-for-gml/train.csv')\n```\n\n\n```python\nX = data['ABSTRACT'].copy()\ny = data['Computer Science'].values\n```\n\n\n```python\nnlp = AutoNLP()\n```\n\nPass each text individually to the clean function. but thats easy with pandas' apply function\n\nArguments of clean function are as below:\n\ntext, <br>\nfix_unicode=True, <br>\nto_ascii=True, <br>\nlower=True, <br>\nno_line_breaks=True, <br>\nno_urls=True, <br>\nno_emails=True, <br>\nno_phone_numbers=True, <br>\nno_numbers=True, <br>\nno_digits=True, <br>\nno_currency_symbols=True, <br>\nno_punct=True, <br>\nreplace_with_url='<URL>', <br>\nreplace_with_email='<EMAIL>', <br>\nreplace_with_phone_number='<PHONE>', <br>\nreplace_with_number='<NUMBER>', <br>\nreplace_with_digit='0', <br>\nreplace_with_currency_symbol='<CUR>', <br>\nlang='en'\n\n\n```python\ncleanX = X.apply(lambda x: nlp.clean(x))\n```\n\n\n```python\ncleanX = pd.DataFrame(cleanX, columns = ['ABSTRACT'])\ncleanX = pd.concat([cleanX,data['Computer Science']], axis=1)\ncleanX\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>ABSTRACT</th>\n      <th>Computer Science</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>predictive models allow subjectspecific infere...</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>rotation invariance and translation invariance...</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>we introduce and develop the notion of spheric...</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>the stochastic landaulifshitzgilbert llg equat...</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>fouriertransform infrared ftir spectra of samp...</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>20967</th>\n      <td>machine learning is finding increasingly broad...</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>20968</th>\n      <td>polycrystalline diamond coatings have been gro...</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>20969</th>\n      <td>we present a new approach for identifying situ...</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>20970</th>\n      <td>the sum of lognormal variates is encountered i...</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>20971</th>\n      <td>recently optional stopping has been a subject ...</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n<p>20972 rows \u00d7 2 columns</p>\n</div>\n\n\n\n\n```python\ndef trunc_text(x):\n  if len(x) > 200:\n    return x[:200]\n  return x\n\ncleanX['ABSTRACT'] = cleanX['ABSTRACT'].apply(lambda x: trunc_text(x))\n```\n\n\n```python\ncleanX.to_csv('data.csv',index=False)\n```\n\nArguments for augmentation_train are as follows:\n\nDATA_FILE: Path of the data file <br>\nBATCH_SIZE:  Batch size <br>\nEPOCHS: Number of augmentation epochs <br>\nLEARNING_RATE: Learning Rate <br>\nWARMUP_STEPS: Warm up steps <br>\nMAX_SEQ_LEN: Maximum sequence length in each of text <br>\nMODEL_NAME: For now, only gpt2 is supported. more will be added in future.\n\n\n```python\nnlp.augmentation_train('./data.csv')\n```\n\n    Loading/Downloading GPT-2 Model\n\n\n\n    HBox(children=(FloatProgress(value=0.0, description='Downloading', max=1042301.0, style=ProgressStyle(descript\u2026\n\n\n    \n\n\n\n    HBox(children=(FloatProgress(value=0.0, description='Downloading', max=456318.0, style=ProgressStyle(descripti\u2026\n\n\n    \n\n\n\n    HBox(children=(FloatProgress(value=0.0, description='Downloading', max=718.0, style=ProgressStyle(description_\u2026\n\n\n    \n\n\n\n    HBox(children=(FloatProgress(value=0.0, description='Downloading', max=1520013706.0, style=ProgressStyle(descr\u2026\n\n\n    \n    Running 1 epoch\n    Total Loss is 104.73603820800781\n    Total Loss is 112.86139678955078\n    Total Loss is 118.34065246582031\n    Total Loss is 145.15234375\n    Total Loss is 156.99583435058594\n    Total Loss is 152.2235870361328\n    Total Loss is 151.24612426757812\n    Total Loss is 153.5050506591797\n    Total Loss is 152.9113311767578\n    Total Loss is 151.2832794189453\n    Total Loss is 146.8540802001953\n    Total Loss is 144.33045959472656\n    Total Loss is 142.19061279296875\n    Total Loss is 145.0963134765625\n    Total Loss is 147.210205078125\n    Total Loss is 146.30068969726562\n    Total Loss is 144.9857177734375\n    Total Loss is 147.03077697753906\n    Total Loss is 147.45782470703125\n    Total Loss is 143.7101593017578\n    Total Loss is 144.5182342529297\n    Total Loss is 145.22311401367188\n    Total Loss is 145.1485137939453\n    Total Loss is 145.18280029296875\n    Total Loss is 148.14932250976562\n    Total Loss is 141.2455596923828\n    Total Loss is 145.4959259033203\n    Total Loss is 146.64236450195312\n    Total Loss is 146.3128204345703\n    Total Loss is 146.4281463623047\n    Total Loss is 142.1925048828125\n    Total Loss is 143.88687133789062\n    Total Loss is 148.46185302734375\n    Total Loss is 146.94544982910156\n    Total Loss is 145.03781127929688\n    Total Loss is 147.3777313232422\n    Total Loss is 145.6553192138672\n    Total Loss is 147.2757568359375\n    Total Loss is 145.6207733154297\n    Total Loss is 145.9559783935547\n    Total Loss is 148.59255981445312\n    Total Loss is 146.9285888671875\n    Total Loss is 146.8224639892578\n    Total Loss is 146.46734619140625\n    Total Loss is 144.93560791015625\n    Total Loss is 144.062744140625\n    Total Loss is 145.44497680664062\n    Total Loss is 145.25840759277344\n    Total Loss is 147.41123962402344\n    Total Loss is 142.80441284179688\n    Total Loss is 146.57559204101562\n    Total Loss is 145.5012969970703\n    Total Loss is 145.37965393066406\n    Total Loss is 145.70458984375\n    Total Loss is 143.3974151611328\n    Total Loss is 146.50526428222656\n    Total Loss is 143.35911560058594\n    Total Loss is 142.92315673828125\n    Total Loss is 144.06881713867188\n    Total Loss is 143.89895629882812\n    Total Loss is 145.4073486328125\n    Total Loss is 142.12820434570312\n    Total Loss is 144.14974975585938\n    Total Loss is 145.36241149902344\n    Total Loss is 146.62728881835938\n    Total Loss is 145.29783630371094\n    Total Loss is 146.01344299316406\n    Total Loss is 142.614501953125\n    Total Loss is 148.58058166503906\n    Total Loss is 142.3350372314453\n    Total Loss is 147.1200408935547\n    Total Loss is 144.70223999023438\n    Total Loss is 143.85475158691406\n    Total Loss is 142.39291381835938\n    Total Loss is 147.4104461669922\n    Total Loss is 142.92588806152344\n    Total Loss is 144.19740295410156\n    Total Loss is 143.62811279296875\n    Total Loss is 149.4729461669922\n    Total Loss is 145.65374755859375\n    Total Loss is 144.41273498535156\n    Total Loss is 149.55567932128906\n    Total Loss is 145.6923370361328\n    Total Loss is 144.38510131835938\n    Total Loss is 146.47760009765625\n    Total Loss is 146.47732543945312\n    Total Loss is 144.14427185058594\n    Total Loss is 144.9529571533203\n    Total Loss is 146.76974487304688\n    Total Loss is 145.4130401611328\n    Total Loss is 147.14588928222656\n    Total Loss is 147.9783935546875\n    Total Loss is 145.3712158203125\n    Total Loss is 148.6101531982422\n    Total Loss is 143.77610778808594\n    Total Loss is 145.48680114746094\n    Total Loss is 146.92001342773438\n    Total Loss is 147.2069091796875\n    Total Loss is 144.17257690429688\n    Total Loss is 146.35910034179688\n    Total Loss is 140.34518432617188\n    Total Loss is 143.37332153320312\n    Total Loss is 144.52369689941406\n    Total Loss is 144.00759887695312\n    Total Loss is 145.5410919189453\n    Total Loss is 145.1738739013672\n    Total Loss is 149.31680297851562\n    Total Loss is 144.5254669189453\n    Total Loss is 147.8009490966797\n    Total Loss is 145.89474487304688\n    Total Loss is 144.9759979248047\n    Total Loss is 143.84835815429688\n    Total Loss is 141.41941833496094\n    Total Loss is 145.1390380859375\n    Total Loss is 150.08511352539062\n    Total Loss is 146.74180603027344\n    Total Loss is 145.84945678710938\n    Total Loss is 145.39666748046875\n    Total Loss is 146.86293029785156\n    Total Loss is 144.96102905273438\n    Total Loss is 146.4586639404297\n    Total Loss is 144.97267150878906\n    Total Loss is 145.24757385253906\n    Total Loss is 147.42190551757812\n    Total Loss is 143.636962890625\n    Total Loss is 146.3711395263672\n    Total Loss is 147.3195343017578\n    Total Loss is 145.0715789794922\n    Total Loss is 144.00302124023438\n    Total Loss is 147.78208923339844\n    Total Loss is 148.31912231445312\n    Total Loss is 144.9552764892578\n    Total Loss is 144.90086364746094\n    Total Loss is 146.5382843017578\n    Total Loss is 147.52659606933594\n    Total Loss is 146.3914337158203\n    Total Loss is 147.3661651611328\n    Total Loss is 145.7345428466797\n    Total Loss is 145.57940673828125\n    Total Loss is 142.66769409179688\n    Total Loss is 145.22645568847656\n    Total Loss is 144.10118103027344\n    Total Loss is 143.72061157226562\n    Total Loss is 145.6617889404297\n    Total Loss is 147.88526916503906\n    Total Loss is 141.77932739257812\n    Total Loss is 145.32089233398438\n    Total Loss is 145.07908630371094\n    Total Loss is 146.28724670410156\n    Total Loss is 142.12303161621094\n    Total Loss is 145.1352996826172\n    Total Loss is 145.875\n    Total Loss is 146.08042907714844\n    Total Loss is 145.9125213623047\n    Total Loss is 146.52151489257812\n    Total Loss is 144.5623779296875\n    Total Loss is 143.438232421875\n    Total Loss is 147.61058044433594\n    Total Loss is 148.02703857421875\n    Total Loss is 146.77737426757812\n    Total Loss is 142.6342315673828\n    Total Loss is 146.0636749267578\n    Total Loss is 142.4952392578125\n    Total Loss is 144.10006713867188\n    Total Loss is 141.1858367919922\n    Total Loss is 148.75054931640625\n    Total Loss is 144.02552795410156\n    Total Loss is 148.46810913085938\n    Total Loss is 146.98806762695312\n    Total Loss is 143.71530151367188\n    Total Loss is 144.12464904785156\n    Total Loss is 144.71231079101562\n    Total Loss is 146.79739379882812\n    Total Loss is 146.8440399169922\n    Total Loss is 142.47698974609375\n    Total Loss is 144.88540649414062\n    Total Loss is 142.9034423828125\n    Total Loss is 145.6194610595703\n    Total Loss is 144.37762451171875\n    Total Loss is 150.27432250976562\n    Total Loss is 145.19288635253906\n    Total Loss is 142.77468872070312\n    Total Loss is 143.9071502685547\n    Total Loss is 145.6529998779297\n    Total Loss is 148.85400390625\n    Total Loss is 146.0426788330078\n    Total Loss is 144.77725219726562\n    Total Loss is 145.00985717773438\n    Total Loss is 146.2347412109375\n    Total Loss is 145.7513427734375\n    Total Loss is 145.2029266357422\n    Total Loss is 145.03610229492188\n    Total Loss is 147.06044006347656\n    Total Loss is 147.19891357421875\n    Total Loss is 144.69432067871094\n    Total Loss is 143.88597106933594\n    Total Loss is 147.8527069091797\n    Total Loss is 144.94412231445312\n    Total Loss is 148.16111755371094\n    Total Loss is 148.71995544433594\n    Total Loss is 146.05174255371094\n    Total Loss is 147.7614288330078\n    Total Loss is 147.2187957763672\n    Total Loss is 145.9312286376953\n    Total Loss is 144.3688201904297\n    Total Loss is 146.0614471435547\n    Total Loss is 145.4281463623047\n    Total Loss is 145.55601501464844\n    Total Loss is 147.16543579101562\n    Total Loss is 150.485107421875\n    Total Loss is 145.61251831054688\n    Total Loss is 149.17025756835938\n    Total Loss is 145.1627197265625\n    Total Loss is 145.1183319091797\n    Total Loss is 146.4827880859375\n    Total Loss is 146.5847625732422\n    Total Loss is 144.6040802001953\n    Total Loss is 146.4486846923828\n    Total Loss is 143.3975372314453\n    Total Loss is 145.99696350097656\n    Total Loss is 143.79000854492188\n    Total Loss is 145.8503875732422\n    Total Loss is 144.9890899658203\n    Total Loss is 146.16006469726562\n    Total Loss is 147.265380859375\n    Total Loss is 148.8063201904297\n    Total Loss is 145.93313598632812\n    Total Loss is 144.882568359375\n    Total Loss is 144.41209411621094\n    Total Loss is 144.6779327392578\n    Total Loss is 144.72950744628906\n    Total Loss is 147.86778259277344\n    Total Loss is 148.18170166015625\n    Total Loss is 145.77664184570312\n    Total Loss is 146.38946533203125\n    Total Loss is 149.6170196533203\n    Total Loss is 142.0398712158203\n    Total Loss is 144.61460876464844\n    Total Loss is 146.7652587890625\n    Total Loss is 147.7237091064453\n    Total Loss is 144.3113555908203\n    Total Loss is 147.99639892578125\n    Total Loss is 147.72512817382812\n    Total Loss is 146.6964874267578\n    Total Loss is 146.33775329589844\n    Total Loss is 147.74143981933594\n    Total Loss is 145.70263671875\n    Total Loss is 147.30697631835938\n    Total Loss is 144.62281799316406\n    Total Loss is 148.34869384765625\n    Total Loss is 143.2584686279297\n    Total Loss is 147.7154998779297\n    Total Loss is 145.56533813476562\n    Total Loss is 147.0728759765625\n    Total Loss is 146.5228729248047\n    Total Loss is 144.0269317626953\n    Total Loss is 144.80072021484375\n    Total Loss is 144.91807556152344\n    Total Loss is 143.52049255371094\n    Total Loss is 145.4845733642578\n    Total Loss is 147.95742797851562\n    Total Loss is 144.84237670898438\n    Total Loss is 144.19927978515625\n    Total Loss is 146.91302490234375\n    Total Loss is 144.40704345703125\n    Total Loss is 146.3751983642578\n    Total Loss is 145.97975158691406\n    Total Loss is 145.73077392578125\n    Total Loss is 145.08602905273438\n    Total Loss is 143.26205444335938\n    Total Loss is 147.15353393554688\n    Total Loss is 144.78477478027344\n    Total Loss is 147.36814880371094\n    Total Loss is 144.28536987304688\n    Total Loss is 143.64471435546875\n    Total Loss is 147.72076416015625\n    Total Loss is 144.70635986328125\n    Total Loss is 145.41201782226562\n    Total Loss is 147.35508728027344\n    Total Loss is 144.3067626953125\n    Total Loss is 144.3653564453125\n    Total Loss is 148.10191345214844\n    Total Loss is 146.0252685546875\n    Total Loss is 146.24978637695312\n    Total Loss is 145.8207244873047\n    Total Loss is 148.1641082763672\n    Total Loss is 146.32684326171875\n    Total Loss is 144.1737060546875\n    Total Loss is 146.61965942382812\n    Total Loss is 144.70361328125\n    Total Loss is 146.8356170654297\n    Total Loss is 147.06576538085938\n    Total Loss is 144.73255920410156\n    Total Loss is 145.91893005371094\n    Total Loss is 144.79933166503906\n    Total Loss is 144.65029907226562\n    Total Loss is 147.23765563964844\n    Total Loss is 145.7270965576172\n    Total Loss is 146.07876586914062\n    Total Loss is 145.9300994873047\n    Total Loss is 143.89166259765625\n    Total Loss is 143.18521118164062\n    Total Loss is 143.15133666992188\n    Total Loss is 144.82113647460938\n    Total Loss is 147.57627868652344\n    Total Loss is 142.58761596679688\n    Total Loss is 147.75747680664062\n    Total Loss is 142.60809326171875\n    Total Loss is 143.61795043945312\n    Total Loss is 146.5682830810547\n    Total Loss is 144.5252227783203\n    Total Loss is 146.23097229003906\n    Total Loss is 147.98712158203125\n    Total Loss is 146.87332153320312\n    Total Loss is 145.832275390625\n    Total Loss is 144.19093322753906\n    Total Loss is 145.681396484375\n    Total Loss is 146.9715576171875\n    Total Loss is 148.88638305664062\n    Total Loss is 141.61685180664062\n    Total Loss is 146.2149200439453\n    Total Loss is 144.09719848632812\n    Total Loss is 148.51934814453125\n    Total Loss is 147.58123779296875\n    Total Loss is 144.78948974609375\n    Total Loss is 146.61639404296875\n    Total Loss is 146.33856201171875\n    Total Loss is 146.35931396484375\n    Total Loss is 147.36566162109375\n    Total Loss is 147.35324096679688\n    Total Loss is 146.5191650390625\n    Total Loss is 146.43246459960938\n    Total Loss is 147.23348999023438\n    Total Loss is 148.23951721191406\n    Total Loss is 143.74798583984375\n    Total Loss is 145.5048065185547\n    Total Loss is 144.28781127929688\n    Total Loss is 145.70413208007812\n    Total Loss is 146.9565887451172\n    Total Loss is 145.75811767578125\n    Total Loss is 144.26393127441406\n    Total Loss is 147.61817932128906\n    Total Loss is 146.5675506591797\n    Total Loss is 143.24252319335938\n    Total Loss is 145.69125366210938\n    Total Loss is 142.69131469726562\n    Total Loss is 144.3011474609375\n    Total Loss is 144.17759704589844\n    Total Loss is 144.32676696777344\n    Total Loss is 141.62222290039062\n    Total Loss is 145.3770294189453\n    Total Loss is 141.19647216796875\n    Total Loss is 147.44764709472656\n    Total Loss is 146.3075714111328\n    Total Loss is 145.46444702148438\n    Total Loss is 145.8205108642578\n    Total Loss is 147.8713836669922\n    Total Loss is 144.0043487548828\n    Total Loss is 146.1716766357422\n    Total Loss is 146.53884887695312\n    Total Loss is 147.4720001220703\n    Total Loss is 147.10211181640625\n    Total Loss is 146.09957885742188\n    Total Loss is 147.57730102539062\n    Total Loss is 144.51564025878906\n    Total Loss is 144.94422912597656\n    Total Loss is 150.42703247070312\n    Total Loss is 142.82139587402344\n    Total Loss is 144.930419921875\n    Total Loss is 146.1984405517578\n    Total Loss is 146.50762939453125\n    Total Loss is 147.8882293701172\n    Total Loss is 146.2440185546875\n    Total Loss is 147.25930786132812\n    Total Loss is 141.72076416015625\n    Total Loss is 142.61856079101562\n    Total Loss is 143.25152587890625\n    Total Loss is 145.66461181640625\n    Total Loss is 150.30055236816406\n    Total Loss is 144.8683624267578\n    Total Loss is 145.8905792236328\n    Total Loss is 143.28863525390625\n    Total Loss is 144.9166259765625\n    Total Loss is 141.11790466308594\n    Total Loss is 144.84861755371094\n    Total Loss is 148.7324981689453\n    Total Loss is 146.7021484375\n    Total Loss is 149.32131958007812\n    Total Loss is 144.29971313476562\n    Total Loss is 147.7177276611328\n    Total Loss is 144.58058166503906\n    Total Loss is 146.16363525390625\n    Total Loss is 143.46646118164062\n    Total Loss is 147.30262756347656\n    Total Loss is 145.2611541748047\n    Total Loss is 143.71014404296875\n    Total Loss is 144.9232940673828\n    Total Loss is 144.84132385253906\n    Total Loss is 146.62158203125\n    Total Loss is 145.03492736816406\n    Total Loss is 148.43165588378906\n    Total Loss is 145.78668212890625\n    Total Loss is 146.09535217285156\n    Total Loss is 148.94935607910156\n    Total Loss is 144.4566650390625\n    Total Loss is 145.39292907714844\n    Total Loss is 147.8389892578125\n    Total Loss is 144.67123413085938\n    Total Loss is 144.87123107910156\n    Total Loss is 144.6396942138672\n    Total Loss is 147.29725646972656\n    Total Loss is 146.351806640625\n    Total Loss is 145.49435424804688\n    Total Loss is 145.94281005859375\n    Total Loss is 147.52227783203125\n    Total Loss is 147.10340881347656\n    Total Loss is 146.3921661376953\n    Total Loss is 146.3505401611328\n    Total Loss is 144.12667846679688\n    Total Loss is 147.70668029785156\n    Total Loss is 147.25381469726562\n    Total Loss is 148.63238525390625\n    Total Loss is 146.3390350341797\n    Total Loss is 147.26878356933594\n    Total Loss is 144.11907958984375\n    Total Loss is 146.13340759277344\n    Total Loss is 146.6284637451172\n    Total Loss is 145.15032958984375\n    Total Loss is 146.4105682373047\n    Total Loss is 149.2736053466797\n    Total Loss is 146.86607360839844\n    Total Loss is 145.69944763183594\n    Total Loss is 146.2353057861328\n    Total Loss is 143.94712829589844\n    Total Loss is 145.54298400878906\n    Total Loss is 145.27610778808594\n    Total Loss is 145.01422119140625\n    Total Loss is 146.90606689453125\n    Total Loss is 144.11021423339844\n    Total Loss is 144.03099060058594\n    Total Loss is 142.55523681640625\n    Total Loss is 148.2818603515625\n    Total Loss is 143.4046173095703\n    Total Loss is 146.35951232910156\n    Total Loss is 148.0059356689453\n    Total Loss is 142.71046447753906\n    Total Loss is 148.4733123779297\n    Total Loss is 149.3545684814453\n    Total Loss is 146.62985229492188\n    Total Loss is 147.3924102783203\n    Total Loss is 144.68765258789062\n    Total Loss is 143.91127014160156\n    Total Loss is 146.1730194091797\n    Total Loss is 148.74249267578125\n    Total Loss is 149.9208526611328\n    Total Loss is 142.93182373046875\n    Total Loss is 146.1355743408203\n    Total Loss is 146.45773315429688\n    Total Loss is 144.9443817138672\n    Total Loss is 147.0950927734375\n    Total Loss is 150.27110290527344\n    Total Loss is 147.08505249023438\n    Total Loss is 143.36294555664062\n    Total Loss is 145.4528045654297\n    Total Loss is 145.8441162109375\n    Total Loss is 144.04734802246094\n    Total Loss is 143.66305541992188\n    Total Loss is 147.72573852539062\n    Total Loss is 145.07577514648438\n    Total Loss is 145.7855224609375\n    Total Loss is 147.8115692138672\n    Total Loss is 143.7727813720703\n    Total Loss is 148.81283569335938\n    Total Loss is 147.3169708251953\n    Total Loss is 146.17311096191406\n    Total Loss is 147.4154815673828\n    Total Loss is 144.04371643066406\n    Total Loss is 142.7718505859375\n    Total Loss is 142.833740234375\n    Total Loss is 146.20770263671875\n    Total Loss is 150.0745391845703\n    Total Loss is 148.56695556640625\n    Total Loss is 144.3972930908203\n    Total Loss is 145.74432373046875\n    Total Loss is 147.19801330566406\n    Total Loss is 146.40650939941406\n    Total Loss is 144.22923278808594\n    Total Loss is 147.44151306152344\n    Total Loss is 145.0463409423828\n    Total Loss is 145.2542724609375\n    Total Loss is 147.12928771972656\n    Total Loss is 151.14991760253906\n    Total Loss is 146.32736206054688\n    Total Loss is 148.55380249023438\n    Total Loss is 145.97352600097656\n    Total Loss is 148.52059936523438\n    Total Loss is 148.20962524414062\n    Total Loss is 142.71714782714844\n    Total Loss is 143.30865478515625\n    Total Loss is 144.18788146972656\n    Total Loss is 146.3125\n    Total Loss is 143.1852264404297\n    Total Loss is 147.713623046875\n    Total Loss is 145.0015869140625\n    Total Loss is 147.22215270996094\n    Total Loss is 148.843994140625\n    Total Loss is 143.0293731689453\n    Total Loss is 145.16151428222656\n    Total Loss is 144.7196044921875\n    Total Loss is 143.7924041748047\n    Total Loss is 144.43399047851562\n    Total Loss is 146.88876342773438\n    Total Loss is 148.25196838378906\n    Total Loss is 145.48692321777344\n    Total Loss is 143.2940673828125\n    Total Loss is 145.84768676757812\n    Total Loss is 143.39865112304688\n    Total Loss is 145.1547393798828\n    Total Loss is 147.31161499023438\n    Total Loss is 147.78631591796875\n    Total Loss is 149.0772705078125\n    Total Loss is 141.44178771972656\n    Total Loss is 146.46572875976562\n    Total Loss is 148.19924926757812\n    Total Loss is 142.69749450683594\n    Total Loss is 147.31077575683594\n    Total Loss is 145.34530639648438\n    Total Loss is 146.34693908691406\n    Total Loss is 146.961181640625\n    Total Loss is 145.18360900878906\n    Total Loss is 145.541748046875\n    Total Loss is 151.1417236328125\n    Total Loss is 146.98519897460938\n    Total Loss is 146.0032501220703\n    Total Loss is 144.64971923828125\n    Total Loss is 145.5829620361328\n    Total Loss is 149.8993377685547\n    Total Loss is 148.32102966308594\n    Total Loss is 146.67584228515625\n    Total Loss is 145.70545959472656\n    Total Loss is 145.37474060058594\n    Total Loss is 144.9097137451172\n    Total Loss is 147.19186401367188\n    Total Loss is 143.56007385253906\n    Total Loss is 145.24234008789062\n    Total Loss is 147.32925415039062\n    Total Loss is 144.23719787597656\n    Total Loss is 146.7804718017578\n    Total Loss is 144.68359375\n    Total Loss is 145.84213256835938\n    Total Loss is 146.0173797607422\n    Total Loss is 142.1478729248047\n    Total Loss is 146.48223876953125\n    Total Loss is 146.0172576904297\n    Total Loss is 147.9045867919922\n    Total Loss is 145.9479217529297\n    Total Loss is 146.93934631347656\n    Total Loss is 144.1197052001953\n    Total Loss is 146.85264587402344\n    Total Loss is 147.99024963378906\n    Total Loss is 141.02212524414062\n    Total Loss is 145.7165069580078\n    Total Loss is 145.43670654296875\n    Total Loss is 146.6594696044922\n    Total Loss is 144.4132843017578\n    Total Loss is 145.6562042236328\n    Total Loss is 144.98080444335938\n    Total Loss is 147.9264678955078\n    Total Loss is 148.77272033691406\n    Total Loss is 144.163330078125\n    Total Loss is 143.3246612548828\n    Total Loss is 146.0085906982422\n    Total Loss is 149.24081420898438\n    Total Loss is 144.99017333984375\n    Total Loss is 144.9736328125\n    Total Loss is 146.10035705566406\n    Total Loss is 145.21206665039062\n    Total Loss is 141.63307189941406\n    Total Loss is 145.24989318847656\n    Total Loss is 143.45753479003906\n    Total Loss is 147.754150390625\n    Total Loss is 146.731689453125\n    Total Loss is 144.40150451660156\n    Total Loss is 143.89808654785156\n    Total Loss is 146.86585998535156\n    Total Loss is 146.24024963378906\n    Total Loss is 145.75491333007812\n    Total Loss is 144.05075073242188\n    Total Loss is 149.4630889892578\n    Total Loss is 146.55812072753906\n    Total Loss is 144.5069580078125\n    Total Loss is 145.18992614746094\n    Total Loss is 147.1329345703125\n    Total Loss is 147.07162475585938\n    Total Loss is 142.48194885253906\n    Total Loss is 145.57766723632812\n    Total Loss is 142.23013305664062\n    Total Loss is 147.1428680419922\n    Total Loss is 145.0802001953125\n    Total Loss is 143.58006286621094\n    Total Loss is 146.24159240722656\n    Total Loss is 147.00131225585938\n    Total Loss is 147.85000610351562\n    Total Loss is 146.82493591308594\n    Total Loss is 143.63262939453125\n    Total Loss is 147.9024200439453\n    Total Loss is 143.16180419921875\n    Total Loss is 146.82693481445312\n    Total Loss is 143.6178741455078\n    Total Loss is 146.89764404296875\n    Total Loss is 144.32351684570312\n    Total Loss is 143.5933380126953\n    Total Loss is 144.11859130859375\n    Total Loss is 146.2833251953125\n    Total Loss is 147.33660888671875\n    Total Loss is 149.55947875976562\n    Total Loss is 142.332763671875\n    Total Loss is 146.59072875976562\n    Total Loss is 140.64739990234375\n    Total Loss is 142.85101318359375\n    Total Loss is 143.13157653808594\n    Total Loss is 148.1952667236328\n    Total Loss is 147.13821411132812\n    Total Loss is 145.13015747070312\n    Total Loss is 148.88172912597656\n    Total Loss is 145.26858520507812\n    Total Loss is 143.4298858642578\n    Total Loss is 144.5579376220703\n    Total Loss is 144.8186798095703\n    Total Loss is 147.64979553222656\n    Total Loss is 145.44989013671875\n    Total Loss is 143.1476593017578\n    Total Loss is 147.16204833984375\n    Total Loss is 145.1624755859375\n    Total Loss is 145.3336944580078\n    Total Loss is 144.94833374023438\n    Total Loss is 146.8472442626953\n    Total Loss is 148.13088989257812\n    Total Loss is 144.93569946289062\n    Total Loss is 146.59043884277344\n    Total Loss is 147.54000854492188\n    Total Loss is 144.95201110839844\n    Total Loss is 146.34156799316406\n    Total Loss is 147.47361755371094\n    Total Loss is 142.84141540527344\n    Total Loss is 145.80638122558594\n    Total Loss is 146.48724365234375\n    Total Loss is 146.20159912109375\n    Total Loss is 145.201904296875\n    Total Loss is 146.20619201660156\n    Total Loss is 143.78465270996094\n    Total Loss is 148.15223693847656\n    Total Loss is 142.07093811035156\n    Total Loss is 146.09622192382812\n    Total Loss is 146.03211975097656\n    Total Loss is 146.90591430664062\n    Total Loss is 149.04025268554688\n    Total Loss is 144.44046020507812\n    Total Loss is 145.72523498535156\n    Total Loss is 144.52444458007812\n    Total Loss is 145.2915802001953\n    Total Loss is 145.5217742919922\n    Total Loss is 145.33084106445312\n    Total Loss is 144.14291381835938\n    Total Loss is 150.48208618164062\n    Total Loss is 149.11563110351562\n    Total Loss is 147.21743774414062\n    Total Loss is 146.7803955078125\n    Total Loss is 145.02149963378906\n    Total Loss is 146.1375732421875\n    Total Loss is 146.4460906982422\n    Total Loss is 145.00531005859375\n    Total Loss is 147.70272827148438\n    Total Loss is 145.6326446533203\n    Total Loss is 145.1699676513672\n    Total Loss is 143.03225708007812\n    Total Loss is 147.51199340820312\n    Total Loss is 141.0960693359375\n    Total Loss is 143.8369903564453\n    Total Loss is 146.1619415283203\n    Total Loss is 145.7740936279297\n    Total Loss is 148.5105438232422\n    Total Loss is 146.35589599609375\n    Total Loss is 146.49728393554688\n    Total Loss is 146.2376708984375\n    Total Loss is 147.02769470214844\n    Total Loss is 145.83758544921875\n    Total Loss is 142.3551788330078\n    Total Loss is 145.5438690185547\n    Total Loss is 143.11192321777344\n    Total Loss is 147.6342010498047\n    Total Loss is 147.12071228027344\n    Total Loss is 142.5404052734375\n    Total Loss is 145.60740661621094\n    Total Loss is 144.72666931152344\n    Total Loss is 146.1050567626953\n    Total Loss is 143.92221069335938\n    Total Loss is 141.69683837890625\n    Total Loss is 146.8015594482422\n    Total Loss is 147.29978942871094\n    Total Loss is 146.87652587890625\n    Total Loss is 146.56005859375\n    Total Loss is 146.64529418945312\n    Total Loss is 147.66612243652344\n    Total Loss is 145.72476196289062\n    Total Loss is 146.4497528076172\n    Total Loss is 145.04176330566406\n    Total Loss is 145.80284118652344\n    Total Loss is 145.9733123779297\n    Total Loss is 144.21112060546875\n    Total Loss is 145.48367309570312\n    Total Loss is 143.0012969970703\n    Total Loss is 144.26824951171875\n    Total Loss is 148.87318420410156\n    Total Loss is 148.7440643310547\n    Total Loss is 143.4563751220703\n    Total Loss is 146.47442626953125\n    Total Loss is 142.2161865234375\n    Total Loss is 148.1685028076172\n    Total Loss is 145.49725341796875\n    Total Loss is 146.00611877441406\n    Total Loss is 143.8220672607422\n    Total Loss is 147.94430541992188\n    Total Loss is 146.7123260498047\n    Total Loss is 145.62826538085938\n    Total Loss is 145.86007690429688\n    Total Loss is 144.8331756591797\n    Total Loss is 148.81207275390625\n    Total Loss is 142.61248779296875\n    Total Loss is 145.51199340820312\n    Total Loss is 147.3713836669922\n    Total Loss is 147.08877563476562\n    Total Loss is 142.61447143554688\n    Total Loss is 146.30523681640625\n    Total Loss is 146.64210510253906\n    Total Loss is 146.8464813232422\n    Total Loss is 147.6572723388672\n    Total Loss is 147.49220275878906\n    Total Loss is 145.623291015625\n    Total Loss is 143.1199951171875\n    Total Loss is 148.332275390625\n    Total Loss is 145.68772888183594\n    Total Loss is 145.79722595214844\n    Total Loss is 142.64466857910156\n    Total Loss is 144.99798583984375\n    Total Loss is 146.79217529296875\n    Total Loss is 145.15945434570312\n    Total Loss is 145.641845703125\n    Total Loss is 149.93203735351562\n    Total Loss is 147.51611328125\n    Total Loss is 142.06800842285156\n    Total Loss is 146.5966339111328\n    Total Loss is 144.48873901367188\n    Total Loss is 146.96548461914062\n    Total Loss is 148.7209014892578\n    Total Loss is 144.28829956054688\n    Total Loss is 147.8353271484375\n    Total Loss is 144.48611450195312\n    Total Loss is 149.8607177734375\n    Total Loss is 144.8494415283203\n    Total Loss is 146.64373779296875\n    Total Loss is 147.32156372070312\n    Total Loss is 145.68438720703125\n    Total Loss is 147.64321899414062\n    Total Loss is 146.42063903808594\n    Total Loss is 148.8839111328125\n    Total Loss is 151.4462890625\n    Total Loss is 145.37550354003906\n    Total Loss is 145.05722045898438\n    Total Loss is 148.25234985351562\n    Total Loss is 144.8623046875\n    Total Loss is 143.7156524658203\n    Total Loss is 147.4641876220703\n    Total Loss is 145.24591064453125\n    Total Loss is 146.6135711669922\n    Total Loss is 145.6671905517578\n    Total Loss is 143.7648162841797\n    Total Loss is 144.48170471191406\n    Total Loss is 141.7767791748047\n    Total Loss is 147.59300231933594\n    Total Loss is 144.73538208007812\n    Total Loss is 146.84811401367188\n    Total Loss is 146.92604064941406\n    Total Loss is 146.73728942871094\n    Total Loss is 145.59825134277344\n    Total Loss is 145.1332244873047\n    Total Loss is 145.2473907470703\n    Total Loss is 144.66949462890625\n    Total Loss is 145.3248291015625\n    Total Loss is 147.0645751953125\n    Total Loss is 142.26873779296875\n    Total Loss is 143.3810577392578\n    Total Loss is 144.88186645507812\n    Total Loss is 146.4945526123047\n    Total Loss is 143.04234313964844\n    Total Loss is 146.31101989746094\n    Total Loss is 145.06689453125\n    Total Loss is 146.43785095214844\n    Total Loss is 142.2384490966797\n    Total Loss is 146.71168518066406\n    Total Loss is 148.84507751464844\n    Total Loss is 149.51051330566406\n    Total Loss is 146.89715576171875\n    Total Loss is 147.79481506347656\n    Total Loss is 149.18222045898438\n    Total Loss is 145.90638732910156\n    Total Loss is 146.59341430664062\n    Total Loss is 143.661376953125\n    Total Loss is 147.97207641601562\n    Total Loss is 146.89947509765625\n    Total Loss is 144.45455932617188\n    Total Loss is 143.6951446533203\n    Total Loss is 146.7887725830078\n    Total Loss is 143.50262451171875\n    Total Loss is 143.59706115722656\n    Total Loss is 145.09869384765625\n    Total Loss is 147.67955017089844\n    Total Loss is 145.0821533203125\n    Total Loss is 144.7113494873047\n    Total Loss is 145.30615234375\n    Total Loss is 148.6268768310547\n    Total Loss is 146.1901397705078\n    Total Loss is 150.3830108642578\n    Total Loss is 146.2295379638672\n    Total Loss is 148.4149932861328\n    Total Loss is 143.002685546875\n    Total Loss is 149.22776794433594\n    Total Loss is 146.3500518798828\n    Total Loss is 147.39292907714844\n    Total Loss is 146.42156982421875\n    Total Loss is 147.16836547851562\n    Total Loss is 147.08828735351562\n    Total Loss is 146.05667114257812\n    Total Loss is 148.15187072753906\n    Total Loss is 145.64166259765625\n    Total Loss is 143.1004180908203\n    Total Loss is 146.66627502441406\n    Total Loss is 144.43267822265625\n    Total Loss is 145.91180419921875\n    Total Loss is 148.5251922607422\n    Total Loss is 148.30389404296875\n    Total Loss is 144.64833068847656\n    Total Loss is 144.9549102783203\n    Total Loss is 144.56814575195312\n    Total Loss is 144.04153442382812\n    Total Loss is 144.99929809570312\n    Total Loss is 146.8995819091797\n    Total Loss is 145.22592163085938\n    Total Loss is 147.0716552734375\n    Total Loss is 142.4106903076172\n    Total Loss is 145.4554443359375\n    Total Loss is 147.61744689941406\n    Total Loss is 146.30262756347656\n    Total Loss is 144.5885772705078\n    Total Loss is 144.86260986328125\n    Total Loss is 147.7385711669922\n    Total Loss is 144.7169952392578\n    Total Loss is 146.7542266845703\n    Total Loss is 148.28111267089844\n    Total Loss is 146.15383911132812\n    Total Loss is 145.33433532714844\n    Total Loss is 144.53857421875\n    Total Loss is 145.23573303222656\n    Total Loss is 146.73834228515625\n    Total Loss is 146.74864196777344\n    Total Loss is 146.65585327148438\n    Total Loss is 144.4017791748047\n    Total Loss is 149.39048767089844\n    Total Loss is 143.94924926757812\n    Total Loss is 146.53244018554688\n    Total Loss is 146.08255004882812\n    Total Loss is 147.4193572998047\n    Total Loss is 145.89927673339844\n    Total Loss is 143.964599609375\n    Total Loss is 147.0888671875\n    Total Loss is 145.25071716308594\n    Total Loss is 144.39016723632812\n    Total Loss is 147.12144470214844\n    Total Loss is 145.991455078125\n    Total Loss is 148.9880828857422\n    Total Loss is 145.4310760498047\n    Total Loss is 142.22018432617188\n    Total Loss is 143.20079040527344\n    Total Loss is 148.65919494628906\n    Total Loss is 148.64022827148438\n    Total Loss is 143.7255859375\n    Total Loss is 147.12689208984375\n    Total Loss is 146.96493530273438\n    Total Loss is 143.94732666015625\n    Total Loss is 142.94773864746094\n    Total Loss is 143.84634399414062\n    Total Loss is 149.51242065429688\n    Total Loss is 144.4381866455078\n    Total Loss is 146.86209106445312\n    Total Loss is 145.71240234375\n    Total Loss is 143.14144897460938\n    Total Loss is 144.8802032470703\n    Total Loss is 144.31101989746094\n    Total Loss is 140.9904022216797\n    Total Loss is 146.59796142578125\n    Total Loss is 145.67445373535156\n    Total Loss is 146.52767944335938\n    Total Loss is 147.9317626953125\n    Total Loss is 147.95639038085938\n    Total Loss is 146.33731079101562\n    Total Loss is 144.94541931152344\n    Total Loss is 143.7581787109375\n    Total Loss is 148.01463317871094\n    Total Loss is 143.33396911621094\n    Total Loss is 148.18508911132812\n    Total Loss is 142.84075927734375\n    Total Loss is 146.4428253173828\n    Total Loss is 147.96368408203125\n    Total Loss is 146.64169311523438\n    Total Loss is 145.22842407226562\n    Total Loss is 144.84144592285156\n    Total Loss is 144.21249389648438\n    Total Loss is 144.09637451171875\n    Total Loss is 146.1234588623047\n    Total Loss is 146.30796813964844\n    Total Loss is 147.27105712890625\n    Total Loss is 146.26109313964844\n    Total Loss is 144.6100616455078\n    Total Loss is 145.32766723632812\n    Total Loss is 146.95188903808594\n    Total Loss is 148.50782775878906\n    Total Loss is 146.6566619873047\n    Total Loss is 145.0724334716797\n    Total Loss is 145.0012664794922\n    Total Loss is 145.5882568359375\n    Total Loss is 145.94972229003906\n    Total Loss is 147.84695434570312\n    Total Loss is 147.11074829101562\n    Total Loss is 148.70758056640625\n    Total Loss is 145.08583068847656\n    Total Loss is 147.116455078125\n    Total Loss is 146.66712951660156\n    Total Loss is 146.27252197265625\n    Total Loss is 146.91200256347656\n    Total Loss is 144.9391326904297\n    Total Loss is 147.46083068847656\n    Total Loss is 147.1591796875\n    Total Loss is 145.15907287597656\n    Total Loss is 147.75657653808594\n    Total Loss is 145.48416137695312\n    Total Loss is 148.92742919921875\n    Total Loss is 144.69776916503906\n    Total Loss is 146.65858459472656\n    Total Loss is 145.99325561523438\n    Total Loss is 142.69012451171875\n    Total Loss is 146.3962860107422\n    Total Loss is 148.86831665039062\n    Total Loss is 146.75547790527344\n    Total Loss is 143.5739288330078\n    Total Loss is 146.69789123535156\n    Total Loss is 145.75869750976562\n    Total Loss is 146.62770080566406\n    Total Loss is 146.3623809814453\n    Total Loss is 149.06332397460938\n    Total Loss is 143.80747985839844\n    Total Loss is 144.66891479492188\n    Total Loss is 146.7162322998047\n    Total Loss is 147.0630340576172\n    Total Loss is 148.573974609375\n    Total Loss is 144.99874877929688\n    Total Loss is 145.46871948242188\n    Total Loss is 145.2816925048828\n    Total Loss is 144.03802490234375\n    Total Loss is 143.74566650390625\n    Total Loss is 148.6555938720703\n    Total Loss is 147.3741912841797\n    Total Loss is 143.66661071777344\n    Total Loss is 145.33924865722656\n    Total Loss is 145.3518524169922\n    Total Loss is 145.1527557373047\n    Total Loss is 145.89297485351562\n    Total Loss is 147.19142150878906\n    Total Loss is 145.52980041503906\n    Total Loss is 148.73233032226562\n    Total Loss is 144.99583435058594\n    Total Loss is 145.75784301757812\n    Total Loss is 145.94436645507812\n    Total Loss is 147.63262939453125\n    Total Loss is 142.761962890625\n    Total Loss is 146.7914276123047\n    Total Loss is 145.83197021484375\n    Total Loss is 143.60031127929688\n    Total Loss is 143.9179229736328\n    Total Loss is 146.59664916992188\n    Total Loss is 146.10528564453125\n    Total Loss is 143.2861785888672\n    Total Loss is 146.3742218017578\n    Total Loss is 146.29563903808594\n    Total Loss is 145.480224609375\n    Total Loss is 145.0482635498047\n    Total Loss is 144.12783813476562\n    Total Loss is 146.8246612548828\n    Total Loss is 145.4727325439453\n    Total Loss is 148.0026092529297\n    Total Loss is 143.9413604736328\n    Total Loss is 147.18325805664062\n    Total Loss is 148.1897735595703\n    Total Loss is 146.82623291015625\n    Total Loss is 143.96072387695312\n    Total Loss is 144.44552612304688\n    Total Loss is 144.48641967773438\n    Total Loss is 144.26329040527344\n    Total Loss is 144.68321228027344\n    Total Loss is 144.53933715820312\n    Total Loss is 146.39930725097656\n    Total Loss is 149.6548309326172\n    Total Loss is 144.54393005371094\n    Total Loss is 144.87489318847656\n    Total Loss is 147.4753875732422\n    Total Loss is 145.5417022705078\n    Total Loss is 150.4420166015625\n    Total Loss is 145.3815460205078\n    Total Loss is 146.30027770996094\n    Total Loss is 143.62139892578125\n    Total Loss is 146.18211364746094\n    Total Loss is 145.48992919921875\n    Total Loss is 145.67005920410156\n    Total Loss is 146.4638214111328\n    Total Loss is 144.7095489501953\n    Total Loss is 150.85546875\n    Total Loss is 146.89161682128906\n    Total Loss is 143.7807159423828\n    Total Loss is 144.1977081298828\n    Total Loss is 144.78709411621094\n    Total Loss is 144.08248901367188\n    Total Loss is 144.79051208496094\n    Total Loss is 149.5347442626953\n    Total Loss is 142.75462341308594\n    Total Loss is 144.0462188720703\n    Total Loss is 152.28016662597656\n    Total Loss is 146.12020874023438\n    Total Loss is 146.62277221679688\n    Total Loss is 143.45437622070312\n    Total Loss is 143.90408325195312\n    Total Loss is 147.60598754882812\n    Total Loss is 145.99703979492188\n    Total Loss is 143.0487823486328\n    Total Loss is 141.7460479736328\n    Total Loss is 143.28257751464844\n    Total Loss is 145.64990234375\n    Total Loss is 143.76824951171875\n    Total Loss is 147.08409118652344\n    Total Loss is 144.3843994140625\n\n\nAs augmentation model is trained, lets generate data\n\nBefore generation, make sure to set params\n\n\n```python\nnlp.set_params(cleanX['ABSTRACT'])\n```\n\nArguments are:\n\ny: label column (numeric form) <br>\nSENTENCES: Sentences to generate for each of the label. eg, if there are 5 labels and SENTENCES = 10 then total 50 sentences will be generated\n\n\n```python\nnew_Text = nlp.augmentation_generate(y = cleanX['Computer Science'], \n                                     SENTENCES = 100) # total 200 as we have 2 labels only\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2/2 [02:18<00:00, 69.29s/it]\n\n\n\n```python\nnew_Text\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Text</th>\n      <th>labels</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>! as ofistic or is and of problem for by more ...</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>! an data is an as we it as when and that as t...</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>! of play:  mostly  in mostly 0   0 are 0 0 we...</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>! in an by is to various information on on ofn...</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>! or population an large with with and informa...</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>195</th>\n      <td>\" the the by via and and on as with d in and a...</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>196</th>\n      <td>\" sets this article more of long param a large...</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>197</th>\n      <td>\" or the population with and density theistic ...</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>198</th>\n      <td>\" under mostly respect data information to a i...</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>199</th>\n      <td>\" is for work of for more in is in and as of o...</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n<p>200 rows \u00d7 2 columns</p>\n</div>\n\n\n", "meta": {"hexsha": "c4e8d4cf0200b1dd01585be776fcf621b3e65832", "size": 80219, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "DEMO/TextAugmentation.ipynb", "max_stars_repo_name": "mehrankamal/GML", "max_stars_repo_head_hexsha": "ee36ba502293236bf90bf6056c76f106c8dad00c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 89, "max_stars_repo_stars_event_min_datetime": "2020-02-29T15:23:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-26T07:46:09.000Z", "max_issues_repo_path": "DEMO/TextAugmentation.ipynb", "max_issues_repo_name": "mehrankamal/GML", "max_issues_repo_head_hexsha": "ee36ba502293236bf90bf6056c76f106c8dad00c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-11-30T16:56:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-13T09:29:18.000Z", "max_forks_repo_path": "DEMO/TextAugmentation.ipynb", "max_forks_repo_name": "mehrankamal/GML", "max_forks_repo_head_hexsha": "ee36ba502293236bf90bf6056c76f106c8dad00c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2020-11-30T14:06:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-25T09:28:05.000Z", "avg_line_length": 44.4426592798, "max_line_length": 220, "alphanum_fraction": 0.6174597041, "converted": true, "num_tokens": 21822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19193279569159502, "lm_q2_score": 0.044018646727667046, "lm_q1q2_score": 0.008448621929001816}}
{"text": "## How to install geosnap\n\nCommand lines below are to install the geosnap package and additional packages that you need to run geosnap.\nThis installation instruction is for CyberGISX.\nFor jupyter notebook users see the website below for installation instructions\nLearn more about geosnap at https://github.com/spatialucr/geosnap\n\n\n```python\n!pip install geosnap\n```\n\n    Requirement already satisfied: geosnap in /opt/conda/lib/python3.7/site-packages (0.5.0)\n    Requirement already satisfied: seaborn in /opt/conda/lib/python3.7/site-packages (from geosnap) (0.10.0)\n    Requirement already satisfied: tobler>=0.2.1 in /opt/conda/lib/python3.7/site-packages (from geosnap) (0.4.0)\n    Requirement already satisfied: matplotlib in /opt/conda/lib/python3.7/site-packages (from geosnap) (3.1.3)\n    Requirement already satisfied: libpysal in /opt/conda/lib/python3.7/site-packages (from geosnap) (4.2.2)\n    Requirement already satisfied: spenc in /opt/conda/lib/python3.7/site-packages (from geosnap) (0.2)\n    Requirement already satisfied: scikit-learn in /opt/conda/lib/python3.7/site-packages (from geosnap) (0.22.2.post1)\n    Requirement already satisfied: appdirs in /opt/conda/lib/python3.7/site-packages (from geosnap) (1.4.4)\n    Requirement already satisfied: dash in /opt/conda/lib/python3.7/site-packages (from geosnap) (1.16.3)\n    Requirement already satisfied: pandas in /opt/conda/lib/python3.7/site-packages (from geosnap) (1.0.3)\n    Requirement already satisfied: palettable in /opt/conda/lib/python3.7/site-packages (from geosnap) (3.3.0)\n    Requirement already satisfied: xlrd in /opt/conda/lib/python3.7/site-packages (from geosnap) (1.2.0)\n    Requirement already satisfied: tqdm in /opt/conda/lib/python3.7/site-packages (from geosnap) (4.45.0)\n    Requirement already satisfied: geopandas in /opt/conda/lib/python3.7/site-packages (from geosnap) (0.7.0)\n    Requirement already satisfied: giddy>=2.2.1 in /opt/conda/lib/python3.7/site-packages (from geosnap) (2.3.3)\n    Requirement already satisfied: dash-bootstrap-components in /opt/conda/lib/python3.7/site-packages (from geosnap) (0.10.7)\n    Requirement already satisfied: numpy in /opt/conda/lib/python3.7/site-packages (from geosnap) (1.18.1)\n    Requirement already satisfied: quilt3>=3.1.11 in /opt/conda/lib/python3.7/site-packages (from geosnap) (3.2.1)\n    Requirement already satisfied: region>=0.2.1 in /opt/conda/lib/python3.7/site-packages (from geosnap) (0.2.1)\n    Requirement already satisfied: pyarrow>=0.14.1 in /opt/conda/lib/python3.7/site-packages (from geosnap) (0.16.0)\n    Requirement already satisfied: cenpy in /opt/conda/lib/python3.7/site-packages (from geosnap) (1.0.0.post2)\n    Requirement already satisfied: mapclassify in /opt/conda/lib/python3.7/site-packages (from geosnap) (2.2.0)\n    Requirement already satisfied: scipy>=1.0.1 in /opt/conda/lib/python3.7/site-packages (from seaborn->geosnap) (1.4.1)\n    Requirement already satisfied: rasterstats in /opt/conda/lib/python3.7/site-packages (from tobler>=0.2.1->geosnap) (0.15.0)\n    Requirement already satisfied: rasterio in /opt/conda/lib/python3.7/site-packages (from tobler>=0.2.1->geosnap) (1.1.3)\n    Requirement already satisfied: statsmodels in /opt/conda/lib/python3.7/site-packages (from tobler>=0.2.1->geosnap) (0.11.1)\n    Requirement already satisfied: cycler>=0.10 in /opt/conda/lib/python3.7/site-packages (from matplotlib->geosnap) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /opt/conda/lib/python3.7/site-packages (from matplotlib->geosnap) (1.1.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /opt/conda/lib/python3.7/site-packages (from matplotlib->geosnap) (2.4.6)\n    Requirement already satisfied: python-dateutil>=2.1 in /opt/conda/lib/python3.7/site-packages (from matplotlib->geosnap) (2.8.1)\n    Requirement already satisfied: bs4 in /opt/conda/lib/python3.7/site-packages (from libpysal->geosnap) (0.0.1)\n    Requirement already satisfied: requests in /opt/conda/lib/python3.7/site-packages (from libpysal->geosnap) (2.23.0)\n    Requirement already satisfied: jinja2 in /opt/conda/lib/python3.7/site-packages (from libpysal->geosnap) (2.11.1)\n    Requirement already satisfied: joblib>=0.11 in /opt/conda/lib/python3.7/site-packages (from scikit-learn->geosnap) (0.14.1)\n    Requirement already satisfied: dash-core-components==1.12.1 in /opt/conda/lib/python3.7/site-packages (from dash->geosnap) (1.12.1)\n    Requirement already satisfied: dash-table==4.10.1 in /opt/conda/lib/python3.7/site-packages (from dash->geosnap) (4.10.1)\n    Requirement already satisfied: Flask>=1.0.2 in /opt/conda/lib/python3.7/site-packages (from dash->geosnap) (1.1.2)\n    Requirement already satisfied: future in /opt/conda/lib/python3.7/site-packages (from dash->geosnap) (0.18.2)\n    Requirement already satisfied: plotly in /opt/conda/lib/python3.7/site-packages (from dash->geosnap) (4.6.0)\n    Requirement already satisfied: dash-renderer==1.8.2 in /opt/conda/lib/python3.7/site-packages (from dash->geosnap) (1.8.2)\n    Requirement already satisfied: dash-html-components==1.1.1 in /opt/conda/lib/python3.7/site-packages (from dash->geosnap) (1.1.1)\n    Requirement already satisfied: flask-compress in /opt/conda/lib/python3.7/site-packages (from dash->geosnap) (1.7.0)\n    Requirement already satisfied: pytz>=2017.2 in /opt/conda/lib/python3.7/site-packages (from pandas->geosnap) (2019.3)\n    Requirement already satisfied: pyproj>=2.2.0 in /opt/conda/lib/python3.7/site-packages (from geopandas->geosnap) (2.6.0)\n    Requirement already satisfied: shapely in /opt/conda/lib/python3.7/site-packages (from geopandas->geosnap) (1.7.0)\n    Requirement already satisfied: fiona in /opt/conda/lib/python3.7/site-packages (from geopandas->geosnap) (1.8.13)\n    Requirement already satisfied: quantecon>=0.4.7 in /opt/conda/lib/python3.7/site-packages (from giddy>=2.2.1->geosnap) (0.4.8)\n    Requirement already satisfied: esda>=2.1.1 in /opt/conda/lib/python3.7/site-packages (from giddy>=2.2.1->geosnap) (2.3.1)\n    Requirement already satisfied: flask-json in /opt/conda/lib/python3.7/site-packages (from quilt3>=3.1.11->geosnap) (0.3.4)\n    Requirement already satisfied: packaging>=16.8 in /opt/conda/lib/python3.7/site-packages (from quilt3>=3.1.11->geosnap) (20.1)\n    Requirement already satisfied: PyYAML>=5.1 in /opt/conda/lib/python3.7/site-packages (from quilt3>=3.1.11->geosnap) (5.3)\n    Requirement already satisfied: requests-futures==1.0.0 in /opt/conda/lib/python3.7/site-packages (from quilt3>=3.1.11->geosnap) (1.0.0)\n    Requirement already satisfied: flask-cors in /opt/conda/lib/python3.7/site-packages (from quilt3>=3.1.11->geosnap) (3.0.9)\n    Requirement already satisfied: tenacity>=5.1.1 in /opt/conda/lib/python3.7/site-packages (from quilt3>=3.1.11->geosnap) (6.2.0)\n    Requirement already satisfied: boto3>=1.10.0 in /opt/conda/lib/python3.7/site-packages (from quilt3>=3.1.11->geosnap) (1.12.38)\n    Requirement already satisfied: dnspython>=1.16.0 in /opt/conda/lib/python3.7/site-packages (from quilt3>=3.1.11->geosnap) (2.0.0)\n    Requirement already satisfied: aws-requests-auth>=0.4.2 in /opt/conda/lib/python3.7/site-packages (from quilt3>=3.1.11->geosnap) (0.4.3)\n    Requirement already satisfied: jsonlines==1.2.0 in /opt/conda/lib/python3.7/site-packages (from quilt3>=3.1.11->geosnap) (1.2.0)\n    Requirement already satisfied: pytest in /opt/conda/lib/python3.7/site-packages (from region>=0.2.1->geosnap) (6.1.1)\n    Requirement already satisfied: sklearn in /opt/conda/lib/python3.7/site-packages (from region>=0.2.1->geosnap) (0.0)\n    Requirement already satisfied: pulp in /opt/conda/lib/python3.7/site-packages (from region>=0.2.1->geosnap) (2.1)\n    Requirement already satisfied: networkx>=2.0.0 in /opt/conda/lib/python3.7/site-packages (from region>=0.2.1->geosnap) (2.4)\n    Requirement already satisfied: six>=1.0.0 in /opt/conda/lib/python3.7/site-packages (from pyarrow>=0.14.1->geosnap) (1.14.0)\n    Requirement already satisfied: rtree in /opt/conda/lib/python3.7/site-packages (from cenpy->geosnap) (0.9.4)\n    Requirement already satisfied: fuzzywuzzy in /opt/conda/lib/python3.7/site-packages (from cenpy->geosnap) (0.17.0)\n    Requirement already satisfied: deprecated in /opt/conda/lib/python3.7/site-packages (from mapclassify->geosnap) (1.2.8)\n    Requirement already satisfied: affine<3.0 in /opt/conda/lib/python3.7/site-packages (from rasterstats->tobler>=0.2.1->geosnap) (2.3.0)\n    Requirement already satisfied: simplejson in /opt/conda/lib/python3.7/site-packages (from rasterstats->tobler>=0.2.1->geosnap) (3.17.0)\n    Requirement already satisfied: cligj>=0.4 in /opt/conda/lib/python3.7/site-packages (from rasterstats->tobler>=0.2.1->geosnap) (0.5.0)\n    Requirement already satisfied: attrs in /opt/conda/lib/python3.7/site-packages (from rasterio->tobler>=0.2.1->geosnap) (19.3.0)\n    Requirement already satisfied: click-plugins in /opt/conda/lib/python3.7/site-packages (from rasterio->tobler>=0.2.1->geosnap) (1.1.1)\n    Requirement already satisfied: snuggs>=1.4.1 in /opt/conda/lib/python3.7/site-packages (from rasterio->tobler>=0.2.1->geosnap) (1.4.7)\n    Requirement already satisfied: click<8,>=4.0 in /opt/conda/lib/python3.7/site-packages (from rasterio->tobler>=0.2.1->geosnap) (7.1.1)\n    Requirement already satisfied: patsy>=0.5 in /opt/conda/lib/python3.7/site-packages (from statsmodels->tobler>=0.2.1->geosnap) (0.5.1)\n    Requirement already satisfied: setuptools in /opt/conda/lib/python3.7/site-packages (from kiwisolver>=1.0.1->matplotlib->geosnap) (45.2.0.post20200209)\n    Requirement already satisfied: beautifulsoup4 in /opt/conda/lib/python3.7/site-packages (from bs4->libpysal->geosnap) (4.8.2)\n    Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests->libpysal->geosnap) (2020.6.20)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests->libpysal->geosnap) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests->libpysal->geosnap) (2.9)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests->libpysal->geosnap) (1.25.7)\n    Requirement already satisfied: MarkupSafe>=0.23 in /opt/conda/lib/python3.7/site-packages (from jinja2->libpysal->geosnap) (1.1.1)\n    Requirement already satisfied: Werkzeug>=0.15 in /opt/conda/lib/python3.7/site-packages (from Flask>=1.0.2->dash->geosnap) (1.0.1)\n    Requirement already satisfied: itsdangerous>=0.24 in /opt/conda/lib/python3.7/site-packages (from Flask>=1.0.2->dash->geosnap) (1.1.0)\n    Requirement already satisfied: retrying>=1.3.3 in /opt/conda/lib/python3.7/site-packages (from plotly->dash->geosnap) (1.3.3)\n    Requirement already satisfied: brotli in /opt/conda/lib/python3.7/site-packages (from flask-compress->dash->geosnap) (1.0.9)\n    Requirement already satisfied: munch in /opt/conda/lib/python3.7/site-packages (from fiona->geopandas->geosnap) (2.5.0)\n    Requirement already satisfied: numba>=0.38 in /opt/conda/lib/python3.7/site-packages (from quantecon>=0.4.7->giddy>=2.2.1->geosnap) (0.48.0)\n    Requirement already satisfied: sympy in /opt/conda/lib/python3.7/site-packages (from quantecon>=0.4.7->giddy>=2.2.1->geosnap) (1.5.1)\n    Requirement already satisfied: s3transfer<0.4.0,>=0.3.0 in /opt/conda/lib/python3.7/site-packages (from boto3>=1.10.0->quilt3>=3.1.11->geosnap) (0.3.3)\n    Requirement already satisfied: botocore<1.16.0,>=1.15.38 in /opt/conda/lib/python3.7/site-packages (from boto3>=1.10.0->quilt3>=3.1.11->geosnap) (1.15.38)\n    Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in /opt/conda/lib/python3.7/site-packages (from boto3>=1.10.0->quilt3>=3.1.11->geosnap) (0.9.5)\n    Requirement already satisfied: iniconfig in /opt/conda/lib/python3.7/site-packages (from pytest->region>=0.2.1->geosnap) (1.1.1)\n    Requirement already satisfied: py>=1.8.2 in /opt/conda/lib/python3.7/site-packages (from pytest->region>=0.2.1->geosnap) (1.9.0)\n    Requirement already satisfied: importlib-metadata>=0.12; python_version < \"3.8\" in /opt/conda/lib/python3.7/site-packages (from pytest->region>=0.2.1->geosnap) (1.5.0)\n    Requirement already satisfied: toml in /opt/conda/lib/python3.7/site-packages (from pytest->region>=0.2.1->geosnap) (0.10.1)\n    Requirement already satisfied: pluggy<1.0,>=0.12 in /opt/conda/lib/python3.7/site-packages (from pytest->region>=0.2.1->geosnap) (0.13.1)\n    Requirement already satisfied: decorator>=4.3.0 in /opt/conda/lib/python3.7/site-packages (from networkx>=2.0.0->region>=0.2.1->geosnap) (4.4.2)\n    Requirement already satisfied: wrapt<2,>=1.10 in /opt/conda/lib/python3.7/site-packages (from deprecated->mapclassify->geosnap) (1.12.1)\n    Requirement already satisfied: soupsieve>=1.2 in /opt/conda/lib/python3.7/site-packages (from beautifulsoup4->bs4->libpysal->geosnap) (1.9.4)\n    Requirement already satisfied: llvmlite<0.32.0,>=0.31.0dev0 in /opt/conda/lib/python3.7/site-packages (from numba>=0.38->quantecon>=0.4.7->giddy>=2.2.1->geosnap) (0.31.0)\n    Requirement already satisfied: mpmath>=0.19 in /opt/conda/lib/python3.7/site-packages (from sympy->quantecon>=0.4.7->giddy>=2.2.1->geosnap) (1.1.0)\n    Requirement already satisfied: docutils<0.16,>=0.10 in /opt/conda/lib/python3.7/site-packages (from botocore<1.16.0,>=1.15.38->boto3>=1.10.0->quilt3>=3.1.11->geosnap) (0.15.2)\n    Requirement already satisfied: zipp>=0.5 in /opt/conda/lib/python3.7/site-packages (from importlib-metadata>=0.12; python_version < \"3.8\"->pytest->region>=0.2.1->geosnap) (3.1.0)\n\n\n\n```python\n!pip install contextily\n```\n\n    Requirement already satisfied: contextily in /opt/conda/lib/python3.7/site-packages (1.0.1)\n    Requirement already satisfied: rasterio in /opt/conda/lib/python3.7/site-packages (from contextily) (1.1.3)\n    Requirement already satisfied: requests in /opt/conda/lib/python3.7/site-packages (from contextily) (2.23.0)\n    Requirement already satisfied: joblib in /opt/conda/lib/python3.7/site-packages (from contextily) (0.14.1)\n    Requirement already satisfied: pillow in /opt/conda/lib/python3.7/site-packages (from contextily) (7.0.0)\n    Requirement already satisfied: mercantile in /opt/conda/lib/python3.7/site-packages (from contextily) (1.1.6)\n    Requirement already satisfied: matplotlib in /opt/conda/lib/python3.7/site-packages (from contextily) (3.1.3)\n    Requirement already satisfied: geopy in /opt/conda/lib/python3.7/site-packages (from contextily) (1.21.0)\n    Requirement already satisfied: affine in /opt/conda/lib/python3.7/site-packages (from rasterio->contextily) (2.3.0)\n    Requirement already satisfied: cligj>=0.5 in /opt/conda/lib/python3.7/site-packages (from rasterio->contextily) (0.5.0)\n    Requirement already satisfied: click-plugins in /opt/conda/lib/python3.7/site-packages (from rasterio->contextily) (1.1.1)\n    Requirement already satisfied: snuggs>=1.4.1 in /opt/conda/lib/python3.7/site-packages (from rasterio->contextily) (1.4.7)\n    Requirement already satisfied: attrs in /opt/conda/lib/python3.7/site-packages (from rasterio->contextily) (19.3.0)\n    Requirement already satisfied: numpy in /opt/conda/lib/python3.7/site-packages (from rasterio->contextily) (1.18.1)\n    Requirement already satisfied: click<8,>=4.0 in /opt/conda/lib/python3.7/site-packages (from rasterio->contextily) (7.1.1)\n    Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests->contextily) (2020.6.20)\n    Requirement already satisfied: idna<3,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests->contextily) (2.9)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests->contextily) (3.0.4)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests->contextily) (1.25.7)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /opt/conda/lib/python3.7/site-packages (from matplotlib->contextily) (2.4.6)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /opt/conda/lib/python3.7/site-packages (from matplotlib->contextily) (1.1.0)\n    Requirement already satisfied: cycler>=0.10 in /opt/conda/lib/python3.7/site-packages (from matplotlib->contextily) (0.10.0)\n    Requirement already satisfied: python-dateutil>=2.1 in /opt/conda/lib/python3.7/site-packages (from matplotlib->contextily) (2.8.1)\n    Requirement already satisfied: geographiclib<2,>=1.49 in /opt/conda/lib/python3.7/site-packages (from geopy->contextily) (1.50)\n    Requirement already satisfied: setuptools in /opt/conda/lib/python3.7/site-packages (from kiwisolver>=1.0.1->matplotlib->contextily) (45.2.0.post20200209)\n    Requirement already satisfied: six in /opt/conda/lib/python3.7/site-packages (from cycler>=0.10->matplotlib->contextily) (1.14.0)\n\n\n\n```python\n!pip install scikit-plot\n```\n\n    Collecting scikit-plot\n      Downloading scikit_plot-0.3.7-py3-none-any.whl (33 kB)\n    Requirement already satisfied: scipy>=0.9 in /opt/conda/lib/python3.7/site-packages (from scikit-plot) (1.4.1)\n    Requirement already satisfied: scikit-learn>=0.18 in /opt/conda/lib/python3.7/site-packages (from scikit-plot) (0.22.2.post1)\n    Requirement already satisfied: joblib>=0.10 in /opt/conda/lib/python3.7/site-packages (from scikit-plot) (0.14.1)\n    Requirement already satisfied: matplotlib>=1.4.0 in /opt/conda/lib/python3.7/site-packages (from scikit-plot) (3.1.3)\n    Requirement already satisfied: numpy>=1.13.3 in /opt/conda/lib/python3.7/site-packages (from scipy>=0.9->scikit-plot) (1.18.1)\n    Requirement already satisfied: cycler>=0.10 in /opt/conda/lib/python3.7/site-packages (from matplotlib>=1.4.0->scikit-plot) (0.10.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /opt/conda/lib/python3.7/site-packages (from matplotlib>=1.4.0->scikit-plot) (2.4.6)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /opt/conda/lib/python3.7/site-packages (from matplotlib>=1.4.0->scikit-plot) (1.1.0)\n    Requirement already satisfied: python-dateutil>=2.1 in /opt/conda/lib/python3.7/site-packages (from matplotlib>=1.4.0->scikit-plot) (2.8.1)\n    Requirement already satisfied: six in /opt/conda/lib/python3.7/site-packages (from cycler>=0.10->matplotlib>=1.4.0->scikit-plot) (1.14.0)\n    Requirement already satisfied: setuptools in /opt/conda/lib/python3.7/site-packages (from kiwisolver>=1.0.1->matplotlib>=1.4.0->scikit-plot) (45.2.0.post20200209)\n    Installing collected packages: scikit-plot\n    Successfully installed scikit-plot-0.3.7\n\n\n\n```python\n!pip install hdbscan\n```\n\n    Collecting hdbscan\n      Downloading hdbscan-0.8.26.tar.gz (4.7 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4.7 MB 10.4 MB/s eta 0:00:01\ufffd\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f                 | 2.1 MB 10.4 MB/s eta 0:00:01\n    \u001b[?25h  Installing build dependencies ... \u001b[?25ldone\n    \u001b[?25h  Getting requirements to build wheel ... \u001b[?25ldone\n    \u001b[?25h    Preparing wheel metadata ... \u001b[?25ldone\n    \u001b[?25hRequirement already satisfied: cython>=0.27 in /opt/conda/lib/python3.7/site-packages (from hdbscan) (0.29.15)\n    Requirement already satisfied: scikit-learn>=0.17 in /opt/conda/lib/python3.7/site-packages (from hdbscan) (0.22.2.post1)\n    Requirement already satisfied: numpy>=1.16.0 in /opt/conda/lib/python3.7/site-packages (from hdbscan) (1.18.1)\n    Requirement already satisfied: six in /opt/conda/lib/python3.7/site-packages (from hdbscan) (1.14.0)\n    Requirement already satisfied: joblib in /opt/conda/lib/python3.7/site-packages (from hdbscan) (0.14.1)\n    Requirement already satisfied: scipy>=0.9 in /opt/conda/lib/python3.7/site-packages (from hdbscan) (1.4.1)\n    Building wheels for collected packages: hdbscan\n      Building wheel for hdbscan (PEP 517) ... \u001b[?25ldone\n    \u001b[?25h  Created wheel for hdbscan: filename=hdbscan-0.8.26-cp37-cp37m-linux_x86_64.whl size=2401369 sha256=b5632ebf6fb24f0995bd50213bcf1aed7433f821396a3b60bbb418e569501e54\n      Stored in directory: /home/jovyan/.cache/pip/wheels/12/bb/54/7401fdc7883b5975dba5514a185d75d7a0986472df4957637b\n    Successfully built hdbscan\n    Installing collected packages: hdbscan\n    Successfully installed hdbscan-0.8.26\n\n\n### To use LTDB data, you need to download the two datasets below and excute below.\n\nDownload LTDB data at https://s4.ad.brown.edu/projects/diversity/Researcher/LTDB.htm and create the folder, \u201cdownloads\u201d.\nOn the webpage above, <strong>CLICK<a href=\"https://s4.ad.brown.edu/projects/diversity/Researcher/LTBDDload/Default.aspx\"> HERE</a> for the download page</strong> under the section  <strong>\"USE the LTDB\"</strong>. Provide your email address and check for all agreements. On the next page, Two drop-down boxes \u201cSelect a file type:\u201d and \u201cSelect a year\u201d with a button, \u201cDownload Standard Data Files\u201d are available. Download both \u201cFull\u201d and \u201cSample\u201d for \u201cAll Years\u201d. Then, you are going to have two datasets, \u201cLTDB_Std_All_fullcount.zip\u201d and \u201cLTDB_Std_All_Sample.zip\u201d\n\nIn the source code, the command lines below should be executed only for the first run to write LTDB data to your disk. This process takes a few minutes. But you do not need to repeat it from the second run. \n\n\n```python\nfrom geosnap.io import store_ltdb\n\n# if the archives were in my downloads folder, the paths might be something like this\nsample = \"downloads/LTDB_Std_All_Sample.zip\"\nfull = \"downloads/LTDB_Std_All_fullcount.zip\"\n\n# uncomment to run\nstore_ltdb(sample=sample, fullcount=full)\n```\n\n    Hashing: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 300M/300M [00:01<00:00, 264MB/s] \n\n\n\n```python\nfrom geosnap import Community\n```\n\n\n```python\n# this will create a new community using data from Washington DC (which is fips code 11)\ndc = Community.from_census(state_fips=\"11\")\n```\n\n    /opt/conda/lib/python3.7/site-packages/geosnap/_data.py:303: UserWarning: streaming remote data. Use `geosnap.io.store_census() to store the data locally for better performance\n      warn('streaming remote data. Use `geosnap.io.store_census() to store the data locally for better performance')\n    /opt/conda/lib/python3.7/site-packages/pyproj/crs/crs.py:53: FutureWarning: '+init=<authority>:<code>' syntax is deprecated. '<authority>:<code>' is the preferred initialization method. When making the change, be mindful of axis order changes: https://pyproj4.github.io/pyproj/stable/gotchas.html#axis-order-changes-in-proj-6\n      return _prepare_from_string(\" \".join(pjargs))\n    /opt/conda/lib/python3.7/site-packages/geosnap/_data.py:334: UserWarning: streaming remote data. Use `geosnap.io.store_census() to store the data locally for better performance\n      warn('streaming remote data. Use `geosnap.io.store_census() to store the data locally for better performance')\n    /opt/conda/lib/python3.7/site-packages/geosnap/_data.py:364: UserWarning: streaming remote data. Use `geosnap.io.store_census() to store the data locally for better performance\n      warn('streaming remote data. Use `geosnap.io.store_census() to store the data locally for better performance')\n\n\n\n```python\ndc.gdf.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>geoid</th>\n      <th>n_mexican_pop</th>\n      <th>n_cuban_pop</th>\n      <th>n_puerto_rican_pop</th>\n      <th>n_total_housing_units</th>\n      <th>n_vacant_housing_units</th>\n      <th>n_occupied_housing_units</th>\n      <th>n_owner_occupied_housing_units</th>\n      <th>n_renter_occupied_housing_units</th>\n      <th>n_white_persons</th>\n      <th>...</th>\n      <th>p_irish_born_pop</th>\n      <th>p_italian_born_pop</th>\n      <th>p_poverty_rate_children</th>\n      <th>p_poverty_rate_hispanic</th>\n      <th>p_russian_born_pop</th>\n      <th>p_scandanavian_born_pop</th>\n      <th>p_scandanavian_pop</th>\n      <th>n_total_pop_sample</th>\n      <th>p_female_labor_force</th>\n      <th>p_black_persons</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>11001001600</td>\n      <td>4409.0</td>\n      <td>2.0</td>\n      <td>7.0</td>\n      <td>1667.0</td>\n      <td>43.0</td>\n      <td>1624.0</td>\n      <td>1458.0</td>\n      <td>166.0</td>\n      <td>114423.0</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>11001001500</td>\n      <td>5430.0</td>\n      <td>11.0</td>\n      <td>15.0</td>\n      <td>2309.0</td>\n      <td>78.0</td>\n      <td>2231.0</td>\n      <td>1898.0</td>\n      <td>333.0</td>\n      <td>4694102.0</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>11001001701</td>\n      <td>2868.0</td>\n      <td>5.0</td>\n      <td>22.0</td>\n      <td>1287.0</td>\n      <td>50.0</td>\n      <td>1237.0</td>\n      <td>619.0</td>\n      <td>618.0</td>\n      <td>31727.0</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>11001001801</td>\n      <td>694.0</td>\n      <td>5.0</td>\n      <td>28.0</td>\n      <td>10.0</td>\n      <td>1.0</td>\n      <td>9.0</td>\n      <td>0.0</td>\n      <td>9.0</td>\n      <td>35813.0</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>11001001702</td>\n      <td>2516.0</td>\n      <td>6.0</td>\n      <td>12.0</td>\n      <td>1086.0</td>\n      <td>43.0</td>\n      <td>1043.0</td>\n      <td>712.0</td>\n      <td>331.0</td>\n      <td>48917.0</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 195 columns</p>\n</div>\n\n\n", "meta": {"hexsha": "6525a8e77dc05a85b458b3d8d485d595a9cc85f4", "size": 35679, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Install_geosnap.ipynb", "max_stars_repo_name": "spatialucr/MapLinksPlot", "max_stars_repo_head_hexsha": "471dbc328858ad0bafd78d5b4b495379f8e69de9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-02T13:06:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T13:06:42.000Z", "max_issues_repo_path": "Install_geosnap.ipynb", "max_issues_repo_name": "cybergis/CyberGIS-Viz", "max_issues_repo_head_hexsha": "4bffe1a76eb1dc7f1b72fbce1a9059a9a19354f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-21T19:52:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-21T19:52:23.000Z", "max_forks_repo_path": "Install_geosnap.ipynb", "max_forks_repo_name": "spatialucr/MapLinksPlot", "max_forks_repo_head_hexsha": "471dbc328858ad0bafd78d5b4b495379f8e69de9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-12-11T21:30:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-28T18:18:15.000Z", "avg_line_length": 62.3758741259, "max_line_length": 577, "alphanum_fraction": 0.5835645618, "converted": true, "num_tokens": 8789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1602660403494035, "lm_q2_score": 0.05261894777652016, "lm_q1q2_score": 0.008433030407494936}}
{"text": "```python\nfrom google.colab import drive\ndrive.mount('/content/drive',force_remount=True)\n```\n\n    Mounted at /content/drive\n\n\n\n```python\nimport os\nos.chdir('/content/drive/MyDrive/Colab_Notebooks/coursera/coursera_Probabilistic_Deep_Learning_TF2/Week3')\n```\n\n\n```python\n!pip install tensorflow=='2.3.0'\n```\n\n    Collecting tensorflow==2.3.0\n      Downloading tensorflow-2.3.0-cp37-cp37m-manylinux2010_x86_64.whl (320.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 320.4 MB 53 kB/s \n    \u001b[?25hCollecting numpy<1.19.0,>=1.16.0\n      Downloading numpy-1.18.5-cp37-cp37m-manylinux1_x86_64.whl (20.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 20.1 MB 93.2 MB/s \n    \u001b[?25hRequirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.0) (1.0.0)\n    Requirement already satisfied: protobuf>=3.9.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.0) (3.17.3)\n    Requirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.0) (0.37.1)\n    Requirement already satisfied: google-pasta>=0.1.8 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.0) (0.2.0)\n    Requirement already satisfied: astunparse==1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.0) (1.6.3)\n    Collecting h5py<2.11.0,>=2.10.0\n      Downloading h5py-2.10.0-cp37-cp37m-manylinux1_x86_64.whl (2.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.9 MB 61.3 MB/s \n    \u001b[?25hRequirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.0) (1.43.0)\n    Collecting tensorflow-estimator<2.4.0,>=2.3.0\n      Downloading tensorflow_estimator-2.3.0-py2.py3-none-any.whl (459 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 459 kB 50.1 MB/s \n    \u001b[?25hCollecting gast==0.3.3\n      Downloading gast-0.3.3-py2.py3-none-any.whl (9.7 kB)\n    Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.0) (3.3.0)\n    Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.0) (1.13.3)\n    Collecting tensorboard<3,>=2.3.0\n      Downloading tensorboard-2.8.0-py3-none-any.whl (5.8 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5.8 MB 53.9 MB/s \n    \u001b[?25hRequirement already satisfied: six>=1.12.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.0) (1.15.0)\n    Requirement already satisfied: keras-preprocessing<1.2,>=1.1.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.0) (1.1.2)\n    Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.0) (1.1.0)\n    Requirement already satisfied: scipy==1.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.0) (1.4.1)\n    Requirement already satisfied: requests<3,>=2.21.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.0) (2.23.0)\n    Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.0) (0.6.1)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.0) (3.3.6)\n    Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.0) (57.4.0)\n    Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.0) (1.0.1)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.0) (1.8.1)\n    Requirement already satisfied: google-auth<3,>=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.0) (1.35.0)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.0) (0.4.6)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow==2.3.0) (4.2.4)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow==2.3.0) (4.8)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow==2.3.0) (0.2.8)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<3,>=2.3.0->tensorflow==2.3.0) (1.3.1)\n    Requirement already satisfied: importlib-metadata>=4.4 in /usr/local/lib/python3.7/dist-packages (from markdown>=2.6.8->tensorboard<3,>=2.3.0->tensorflow==2.3.0) (4.10.1)\n    Requirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=4.4->markdown>=2.6.8->tensorboard<3,>=2.3.0->tensorflow==2.3.0) (3.10.0.2)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=4.4->markdown>=2.6.8->tensorboard<3,>=2.3.0->tensorflow==2.3.0) (3.7.0)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<3,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow==2.3.0) (0.4.8)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard<3,>=2.3.0->tensorflow==2.3.0) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard<3,>=2.3.0->tensorflow==2.3.0) (2021.10.8)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard<3,>=2.3.0->tensorflow==2.3.0) (2.10)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard<3,>=2.3.0->tensorflow==2.3.0) (1.24.3)\n    Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<3,>=2.3.0->tensorflow==2.3.0) (3.2.0)\n    Installing collected packages: numpy, tensorflow-estimator, tensorboard, h5py, gast, tensorflow\n      Attempting uninstall: numpy\n        Found existing installation: numpy 1.19.5\n        Uninstalling numpy-1.19.5:\n          Successfully uninstalled numpy-1.19.5\n      Attempting uninstall: tensorflow-estimator\n        Found existing installation: tensorflow-estimator 2.1.0\n        Uninstalling tensorflow-estimator-2.1.0:\n          Successfully uninstalled tensorflow-estimator-2.1.0\n      Attempting uninstall: tensorboard\n        Found existing installation: tensorboard 2.1.1\n        Uninstalling tensorboard-2.1.1:\n          Successfully uninstalled tensorboard-2.1.1\n      Attempting uninstall: h5py\n        Found existing installation: h5py 3.1.0\n        Uninstalling h5py-3.1.0:\n          Successfully uninstalled h5py-3.1.0\n      Attempting uninstall: gast\n        Found existing installation: gast 0.2.2\n        Uninstalling gast-0.2.2:\n          Successfully uninstalled gast-0.2.2\n      Attempting uninstall: tensorflow\n        Found existing installation: tensorflow 2.1.0\n        Uninstalling tensorflow-2.1.0:\n          Successfully uninstalled tensorflow-2.1.0\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    tables 3.7.0 requires numpy>=1.19.0, but you have numpy 1.18.5 which is incompatible.\n    datascience 0.10.6 requires folium==0.2.1, but you have folium 0.8.3 which is incompatible.\n    albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Successfully installed gast-0.3.3 h5py-2.10.0 numpy-1.18.5 tensorboard-2.8.0 tensorflow-2.3.0 tensorflow-estimator-2.3.0\n\n\n\n\n\n```python\n!pip install tensorflow_probability=='0.11.1'\n```\n\n    Collecting tensorflow_probability==0.11.1\n      Downloading tensorflow_probability-0.11.1-py2.py3-none-any.whl (4.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4.3 MB 10.6 MB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.13.3 in /usr/local/lib/python3.7/dist-packages (from tensorflow_probability==0.11.1) (1.18.5)\n    Requirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow_probability==0.11.1) (1.15.0)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.7/dist-packages (from tensorflow_probability==0.11.1) (4.4.2)\n    Requirement already satisfied: cloudpickle>=1.3 in /usr/local/lib/python3.7/dist-packages (from tensorflow_probability==0.11.1) (1.3.0)\n    Requirement already satisfied: dm-tree in /usr/local/lib/python3.7/dist-packages (from tensorflow_probability==0.11.1) (0.1.6)\n    Requirement already satisfied: gast>=0.3.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow_probability==0.11.1) (0.3.3)\n    Installing collected packages: tensorflow-probability\n      Attempting uninstall: tensorflow-probability\n        Found existing installation: tensorflow-probability 0.9.0\n        Uninstalling tensorflow-probability-0.9.0:\n          Successfully uninstalled tensorflow-probability-0.9.0\n    Successfully installed tensorflow-probability-0.11.1\n\n\n# Programming Assignment\n\n## RealNVP for the LSUN bedroom dataset\n\n### Instructions\n\nIn this notebook, you will develop the RealNVP normalising flow architecture from scratch, including the affine coupling layers, checkerboard and channel-wise masking, and combining into a multiscale architecture. You will train the normalising flow on a subset of the LSUN bedroom dataset.\n\nSome code cells are provided for you in the notebook. You should avoid editing provided code, and make sure to execute the cells in order to avoid unexpected errors. Some cells begin with the line: \n\n`#### GRADED CELL ####`\n\nDon't move or edit this first line - this is what the automatic grader looks for to recognise graded cells. These cells require you to write your own code to complete them, and are automatically graded when you submit the notebook. Don't edit the function name or signature provided in these cells, otherwise the automatic grader might not function properly.\n\n### How to submit\n\nComplete all the tasks you are asked for in the worksheet. When you have finished and are happy with your code, press the **Submit Assignment** button at the top of this notebook.\n\n### Let's get started!\n\nWe'll start running some imports, and loading the dataset. Do not edit the existing imports in the following cell. If you would like to make further Tensorflow imports, you should add them here.\n\n\n```python\n#### PACKAGE IMPORTS ####\n\n# Run this cell first to import all required packages. Do not make any imports elsewhere in the notebook\n\nimport tensorflow as tf\nimport tensorflow_probability as tfp\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom IPython.display import Image\n\nfrom tensorflow.keras import Model, Input\nfrom tensorflow.keras.layers import Conv2D, BatchNormalization\nfrom tensorflow.keras.optimizers import Adam\n\ntfd = tfp.distributions\ntfb = tfp.bijectors\n\n# If you would like to make further imports from tensorflow, add them here\n\n\n```\n\n#### The LSUN Bedroom Dataset\n\nIn this assignment, you will use a subset of the [LSUN dataset](https://www.yf.io/p/lsun). This is a large-scale image dataset with 10 scene and 20 object categories. A subset of the LSUN bedroom dataset has been provided, and has already been downsampled and preprocessed into smaller, fixed-size images.\n\n* F. Yu, A. Seff, Y. Zhang, S. Song, T. Funkhouser and J. Xia. \"LSUN: Construction of a Large-scale Image Dataset using Deep Learning with Humans in the Loop\". [arXiv:1506.03365](https://arxiv.org/abs/1506.03365), 10 Jun 2015 \n\nYour goal is to develop the RealNVP normalising flow architecture using bijector subclassing, and use it to train a generative model of the LSUN bedroom data subset. For full details on the RealNVP model, refer to the original paper:\n\n* L. Dinh, J. Sohl-Dickstein and S. Bengio. \"Density estimation using Real NVP\". [arXiv:1605.08803](https://arxiv.org/abs/1605.08803), 27 Feb 2017.\n\n#### Import the data\n\nThe dataset required for this project can be downloaded from the following link:\n\nhttps://drive.google.com/file/d/1scbDZrn5pkRjF_CeZp66uHVQC9o1gIsg/view?usp=sharing\n\nYou should upload this file to Drive for use in this Colab notebook. It is recommended to unzip it on Drive, which can be done using the `zipfile` package:\n \n>```\nimport zipfile\nwith zipfile.ZipFile(\"/path/to/lsun_bedroom.zip\",\"r\") as zip_ref:\n   zip_ref.extractall('lsun_bedroom_data')\n```\n\n\n```python\n#import zipfile\n#with zipfile.ZipFile(\"lsun_bedroom.zip\",\"r\") as zip_ref:\n#  zip_ref.extractall('lsun_bedroom_data')\n```\n\n#### Load the dataset\n\nThe following functions will be useful for loading and preprocessing the dataset. The subset you will use for this assignment consists of 10,000 training images, 1000 validation images and 1000 test images.\n\nThe images have been downsampled to 32 x 32 x 3 in order to simplify the training process.\n\n\n```python\n# Functions for loading and preprocessing the images\n\ndef load_image(filepath):\n    raw_img = tf.io.read_file(filepath) \n    img_tensor_int = tf.image.decode_jpeg(raw_img, channels=3)\n    img_tensor_flt = tf.image.convert_image_dtype(img_tensor_int, tf.float32)\n    img_tensor_flt = tf.image.resize(img_tensor_flt, [32, 32])\n    img_tensor_flt = tf.image.random_flip_left_right(img_tensor_flt)\n    return img_tensor_flt, img_tensor_flt\n\ndef load_dataset(split):\n    train_list_ds = tf.data.Dataset.list_files('/content/drive/MyDrive/Colab_Notebooks/coursera/coursera_Probabilistic_Deep_Learning_TF2/Week3/lsun_bedroom_data/{}/*.jpg'.format(split), shuffle=False)\n    train_ds = train_list_ds.map(load_image)\n    return train_ds\n```\n\n\n```python\n# Load the training, validation and testing datasets splits\n\ntrain_ds = load_dataset('train')\nval_ds = load_dataset('val')\ntest_ds = load_dataset('test')\n```\n\n\n```python\n# Shuffle the datasets\n\nshuffle_buffer_size = 1000\ntrain_ds = train_ds.shuffle(shuffle_buffer_size)\nval_ds = val_ds.shuffle(shuffle_buffer_size)\ntest_ds = test_ds.shuffle(shuffle_buffer_size)\n```\n\n\n```python\n# Display a few examples\n\nn_img = 4\nf, axs = plt.subplots(n_img, n_img, figsize=(14, 14))\n\nfor k, image in enumerate(train_ds.take(n_img**2)):\n    i = k // n_img\n    j = k % n_img\n    axs[i, j].imshow(image[0])\n    axs[i, j].axis('off')\nf.subplots_adjust(wspace=0.01, hspace=0.03)\n```\n\n\n```python\n# Batch the Dataset objects\n\nbatch_size = 64\ntrain_ds = train_ds.batch(batch_size)\nval_ds = val_ds.batch(batch_size)\ntest_ds = test_ds.batch(batch_size)\n```\n\n### Affine coupling layer\n\nWe will begin the development of the RealNVP architecture with the core bijector that is called the _affine coupling layer_. This bijector can be described as follows: suppose that $x$ is a $D$-dimensional input, and let $d<D$. Then the output $y$ of the affine coupling layer is given by the following equations:\n\n$$\n\\begin{align}\ny_{1:d} &= x_{1:d} \\tag{1}\\\\\n    y_{d+1:D} &= x_{d+1:D}\\odot \\exp(s(x_{1:d})) + t(x_{1:d}), \\tag{2}\n\\end{align}\n$$\n\nwhere $s$ and $t$ are functions from $\\mathbb{R}^d\\rightarrow\\mathbb{R}^{D-d}$, and define the log-scale and shift operations on the vector $x_{d+1:D}$ respectively.\n\nThe log of the Jacobian determinant for this layer is given by $\\sum_{j}s(x_{1:d})_j$.\n\nThe inverse operation can be easily computed as\n\n$$\n\\begin{align}\nx_{1:d} &= y_{1:d}\\tag{3}\\\\\nx_{d+1:D} &= \\left(y_{d+1:D} - t(y_{1:d})\\right)\\odot \\exp(-s(y_{1:d})),\\tag{4}\n\\end{align}\n$$\n\nIn practice, we will implement equations $(1)$ and $(2)$ using a binary mask $b$:\n\n$$\n\\begin{align}\n\\text{Forward pass:}\\qquad y &= b\\odot x + (1-b)\\odot\\left(x\\odot\\exp(s(b\\odot x)) + t(b\\odot x)\\right),\\tag{5}\\\\\n\\text{Inverse pass:}\\qquad x &= b\\odot y + (1-b)\\odot\\left(y - t(b\\odot x) \\odot\\exp( -s(b\\odot x))\\right).\\tag{6}\n\\end{align}\n$$\n\nOur inputs $x$ will be a batch of 3-dimensional Tensors with `height`, `width` and `channels` dimensions. As in the original architecture, we will use both spatial 'checkerboard' masks and channel-wise masks:\n\n\n```python\n# Run this cell to download and view a figure to illustrate the checkerboard and binary masks\n\n!wget -q -O binary_masks.png --no-check-certificate \"https://docs.google.com/uc?export=download&id=1d_cBjyPGm8i0l5GsRSspPoAlxiPo3HGt\"\nImage(\"binary_masks.png\", width=800)\n```\n\n<center>Figure 1. Spatial checkerboard mask (left) and channel-wise mask (right). From the original paper.</center>\n\n#### Custom model for log-scale and shift\n\nYou should now create a custom model for the shift and log-scale parameters that are used in the affine coupling layer bijector. We will use a convolutional residual network, with two residual blocks and a final convolutional layer. Using the functional API, build the model according to the following specifications:\n\n* The function takes the `input_shape` and `filters` as arguments\n* The model should use the `input_shape` in the function argument to set the shape in the Input layer (call this layer `h0`).\n* The first hidden layer should be a Conv2D layer with number of filters set by the `filters` argument, and a ReLU activation\n* The second hidden layer should be a BatchNormalization layer\n* The third hidden layer should be a Conv2D layer with the same number of filters as the input `h0` to the model, and a ReLU activation\n* The fourth hidden layer should be a BatchNormalization layer\n* The fifth hidden layer should be the sum of the fourth hidden layer output and the inputs `h0`. Call this layer `h1`\n* The sixth hidden layer should be a Conv2D layer with filters set by the `filters` argument, and a ReLU activation\n* The seventh hidden layer should be a BatchNormalization layer\n* The eighth hidden layer should be a Conv2D layer with the same number of filters as `h1` (and `h0`), and a ReLU activation\n* The ninth hidden layer should be a BatchNormalization layer\n* The tenth hidden layer should be the sum of the ninth hidden layer output and `h1`\n* The eleventh hidden layer should be a Conv2D layer with the number of filters equal to twice the number of channels of the model input, and a linear activation. Call this layer `h2`\n* The twelfth hidden layer should split `h2` into two equal-sized Tensors along the final channel axis. These two Tensors are the shift and log-scale Tensors, and should each have the same shape as the model input\n* The final layer should then apply the `tanh` nonlinearity to the log_scale Tensor. The outputs to the model should then be the list of Tensors `[shift, log_scale]`\n\nAll Conv2D layers should use a 3x3 kernel size, `\"SAME\"` padding and an $l2$ kernel regularizer with regularisation coefficient of `5e-5`.\n\n_Hint: use_ `tf.split` _with arguments_ `num_or_size_splits=2, axis=-1` _to create the output Tensors_.\n\nIn total, the network should have 14 layers (including the `Input` layer).\n\n\n```python\n#### GRADED CELL ####\n\n# Complete the following function. \n# Make sure to not change the function name or arguments.\n\ndef get_conv_resnet(input_shape, filters):\n    \"\"\"\n    This function should build a CNN ResNet model according to the above specification,\n    using the functional API. The function takes input_shape as an argument, which should be\n    used to specify the shape in the Input layer, as well as a filters argument, which\n    should be used to specify the number of filters in (some of) the convolutional layers.\n    Your function should return the model.\n    \"\"\"\n    def ConvBlock(hi,filters_i,activation='relu'):\n      h=tf.keras.layers.Conv2D(filters=filters_i,activation=activation,kernel_size=(3,3),padding='SAME',kernel_regularizer=tf.keras.regularizers.l2(5e-5))(hi)\n      h=tf.keras.layers.BatchNormalization()(h)\n      return h\n\n    h0=tf.keras.layers.Input(shape=input_shape)\n    h01=ConvBlock(h0,filters)\n    h02=ConvBlock(h01,input_shape[-1])\n\n    #h1=tf.keras.layers.concatenate([h0,h02],axis=-1)\n    h1=tf.keras.Add()([h0,h02])\n    h11=ConvBlock(h1,filters)\n    h12=ConvBlock(h11,input_shape[-1])\n\n    #h2=tf.keras.layers.concatenate([h1,h12],axis=-1)\n    h2=tf.keras.Add()([h1,h12])\n    h2=ConvBlock(h2,2*input_shape[-1],'linear')\n\n    shift,log_scale=tf.keras.layers.Lambda(lambda value: tf.split(value,num_or_size_splits=2,axis=-1))(h2)\n\n    log_scale=tf.keras.layers.Activation(activation='tanh')(log_scale)\n    conv_resnet=Model(inputs=h0,outputs=[shift,log_scale])\n    return conv_resnet\n\n    \n    \n```\n\n\n```python\n# Test your function and print the model summary\n\nconv_resnet = get_conv_resnet((32, 32, 3), 32)\nconv_resnet.summary()\n```\n\n    Model: \"functional_1\"\n    __________________________________________________________________________________________________\n    Layer (type)                    Output Shape         Param #     Connected to                     \n    ==================================================================================================\n    input_1 (InputLayer)            [(None, 32, 32, 3)]  0                                            \n    __________________________________________________________________________________________________\n    conv2d (Conv2D)                 (None, 32, 32, 32)   896         input_1[0][0]                    \n    __________________________________________________________________________________________________\n    batch_normalization (BatchNorma (None, 32, 32, 32)   128         conv2d[0][0]                     \n    __________________________________________________________________________________________________\n    conv2d_1 (Conv2D)               (None, 32, 32, 3)    867         batch_normalization[0][0]        \n    __________________________________________________________________________________________________\n    batch_normalization_1 (BatchNor (None, 32, 32, 3)    12          conv2d_1[0][0]                   \n    __________________________________________________________________________________________________\n    concatenate (Concatenate)       (None, 32, 32, 6)    0           input_1[0][0]                    \n                                                                     batch_normalization_1[0][0]      \n    __________________________________________________________________________________________________\n    conv2d_2 (Conv2D)               (None, 32, 32, 32)   1760        concatenate[0][0]                \n    __________________________________________________________________________________________________\n    batch_normalization_2 (BatchNor (None, 32, 32, 32)   128         conv2d_2[0][0]                   \n    __________________________________________________________________________________________________\n    conv2d_3 (Conv2D)               (None, 32, 32, 3)    867         batch_normalization_2[0][0]      \n    __________________________________________________________________________________________________\n    batch_normalization_3 (BatchNor (None, 32, 32, 3)    12          conv2d_3[0][0]                   \n    __________________________________________________________________________________________________\n    concatenate_1 (Concatenate)     (None, 32, 32, 9)    0           concatenate[0][0]                \n                                                                     batch_normalization_3[0][0]      \n    __________________________________________________________________________________________________\n    conv2d_4 (Conv2D)               (None, 32, 32, 6)    492         concatenate_1[0][0]              \n    __________________________________________________________________________________________________\n    batch_normalization_4 (BatchNor (None, 32, 32, 6)    24          conv2d_4[0][0]                   \n    __________________________________________________________________________________________________\n    lambda (Lambda)                 [(None, 32, 32, 3),  0           batch_normalization_4[0][0]      \n    __________________________________________________________________________________________________\n    activation (Activation)         (None, 32, 32, 3)    0           lambda[0][1]                     \n    ==================================================================================================\n    Total params: 5,186\n    Trainable params: 5,034\n    Non-trainable params: 152\n    __________________________________________________________________________________________________\n\n\nYou can also inspect your model architecture graphically by running the following cell. It should look something like the following:\n\n\n```python\n# Run this cell to download and view an example model plot\n\n!wget -q -O model_plot.png --no-check-certificate \"https://docs.google.com/uc?export=download&id=1I9MhFGquwyHsJlDgO8hItXnMqAvc5cQg\"\nImage(\"model_plot.png\", width=1400)\n```\n\n\n```python\n# Plot the model graph\n\ntf.keras.utils.plot_model(conv_resnet, show_layer_names=False, rankdir='LR')\n```\n\n\n```python\n# Check the output shapes are as expected\n\nprint(conv_resnet(tf.random.normal((1, 32, 32, 3)))[0].shape)\nprint(conv_resnet(tf.random.normal((1, 32, 32, 3)))[1].shape)\n```\n\n    (1, 32, 32, 3)\n    (1, 32, 32, 3)\n\n\n#### Binary masks\n\nNow that you have a shift and log-scale model built, we will now implement the affine coupling layer. We will first need functions to create the binary masks $b$ as described above. The following function creates the spatial 'checkerboard' mask.\n\nIt takes a rank-2 `shape` as input, which correspond to the `height` and `width` dimensions, as well as an `orientation` argument (an integer equal to `0` or `1`) that determines which way round the zeros and ones are entered into the Tensor.\n\n\n```python\n# Function to create the checkerboard mask\n\ndef checkerboard_binary_mask(shape, orientation=0):\n    height, width = shape[0], shape[1]\n    height_range = tf.range(height)\n    width_range = tf.range(width)\n    height_odd_inx = tf.cast(tf.math.mod(height_range, 2), dtype=tf.bool)\n    width_odd_inx = tf.cast(tf.math.mod(width_range, 2), dtype=tf.bool)\n    odd_rows = tf.tile(tf.expand_dims(height_odd_inx, -1), [1, width])\n    odd_cols = tf.tile(tf.expand_dims(width_odd_inx, 0), [height, 1])\n    checkerboard_mask = tf.math.logical_xor(odd_rows, odd_cols)\n    if orientation == 1:\n        checkerboard_mask = tf.math.logical_not(checkerboard_mask)\n    return tf.cast(tf.expand_dims(checkerboard_mask, -1), tf.float32)\n```\n\nThis function creates a rank-3 Tensor to mask the `height`, `width` and `channels` dimensions of the input. We can take a look at this checkerboard mask for some example inputs below. In order to make the Tensors easier to inspect, we will squeeze out the single channel dimension (which is always 1 for this mask).\n\n\n```python\n# Run the checkerboard_binary_mask function to see an example\n# NB: we squeeze the shape for easier viewing. The full shape is (4, 4, 1)\n\ntf.squeeze(checkerboard_binary_mask((4, 4), orientation=0))\n```\n\n\n\n\n    <tf.Tensor: shape=(4, 4), dtype=float32, numpy=\n    array([[0., 1., 0., 1.],\n           [1., 0., 1., 0.],\n           [0., 1., 0., 1.],\n           [1., 0., 1., 0.]], dtype=float32)>\n\n\n\n\n```python\n# The `orientation` should be 0 or 1, and determines which way round the binary entries are\n\ntf.squeeze(checkerboard_binary_mask((4, 4), orientation=1))\n```\n\n\n\n\n    <tf.Tensor: shape=(4, 4), dtype=float32, numpy=\n    array([[1., 0., 1., 0.],\n           [0., 1., 0., 1.],\n           [1., 0., 1., 0.],\n           [0., 1., 0., 1.]], dtype=float32)>\n\n\n\nYou should now complete the following function to create a channel-wise mask. This function takes a single integer `num_channels` as an input, as well as an `orientation` argument, similar to above. You can assume that the `num_channels` integer is even. \n\nThe function should return a rank-3 Tensor with singleton entries for `height` and `width`. In the channel axis, the first `num_channels // 2` entries should be zero (for `orientation=0`) and the final `num_channels // 2` entries should be one (for `orientation=0`). The zeros and ones should be reversed for `orientation=1`. The `dtype` of the returned Tensor should be `tf.float32`.\n\n\n```python\n#### GRADED CELL ####\n\n# Complete the following function. \n# Make sure to not change the function name or arguments.\n\ndef channel_binary_mask(num_channels, orientation=0):\n    \"\"\"\n    This function takes an integer num_channels and orientation (0 or 1) as\n    arguments. It should create a channel-wise binary mask with \n    dtype=tf.float32, according to the above specification.\n    The function should then return the binary mask.\n    \"\"\"\n    if orientation==0:\n      return tf.cast(tf.keras.layers.concatenate([tf.zeros((1,1,num_channels//2)),\n                                            tf.ones((1,1,num_channels - num_channels//2))],axis=-1),tf.float32)\n    elif orientation==1:\n      return tf.cast(tf.keras.layers.concatenate([tf.ones((1,1,num_channels//2)),\n                                            tf.zeros((1,1,num_channels-num_channels//2))],axis=-1),tf.float32)\n    else:\n      print('Bad input')\n    \n    \n```\n\n\n```python\n# Run your function to see an example channel-wise binary mask\n\nchannel_binary_mask(6, orientation=0)\n```\n\n\n\n\n    <tf.Tensor: shape=(1, 1, 6), dtype=float32, numpy=array([[[0., 0., 0., 1., 1., 1.]]], dtype=float32)>\n\n\n\n\n```python\n#### GRADED CELL ####\n\n# Complete the following functions. \n# Make sure to not change the function names or arguments.\n\ndef forward(x, b, shift_and_log_scale_fn):\n    \"\"\"\n    This function takes the input Tensor x, binary mask b and callable\n    shift_and_log_scale_fn as arguments.\n    This function should implement the forward transformation in equation (5)\n    and return the output Tensor y, which will have the same shape as x\n    \"\"\"\n    t,s=shift_and_log_scale_fn(b*x)\n    return tf.cast(b*x+(1-b)*(x*tf.math.exp(s)+t),tf.float32)\n    \n    \n\n\ndef inverse(y, b, shift_and_log_scale_fn):\n    \"\"\"\n    This function takes the input Tensor x, binary mask b and callable\n    shift_and_log_scale_fn as arguments.\n    This function should implement the forward transformation in equation (5)\n    and return the output Tensor y, which will have the same shape as x\n    \"\"\"\n    t,s=shift_and_log_scale_fn(b*y)\n    return tf.cast(b*y+(1-b)*((y-t)*tf.math.exp(-s)),tf.float32)\n    \n    \n```\n\nThe new bijector class also requires the `log_det_jacobian` methods to be implemented. Recall that the log of the Jacobian determinant of the forward transformation is given by $\\sum_{j}s(x_{1:d})_j$, where $s$ is the log-scale function of the affine coupling layer. \n\nYou should now complete the following functions to define the `forward_log_det_jacobian` and `inverse_log_det_jacobian` methods of the affine coupling layer bijector.\n\n* Both functions `forward_log_det_jacobian` and `inverse_log_det_jacobian` takes an input Tensor `x` (or `y`), a rank-3 binary mask `b`, and the `shift_and_log_scale_fn` callable \n* These arguments are the same as the description for the `forward` and `inverse` functions\n* The `forward_log_det_jacobian` function should implement the log of the Jacobian determinant for the transformation $(5)$\n* The `inverse_log_det_jacobian` function should implement the log of the Jacobian determinant for the transformation $(6)$\n* Both functions should reduce sum over the last three axes of the input Tensor (`height`, `width` and `channels`)\n\n\n```python\n#### GRADED CELL ####\n\n# Complete the following functions. \n# Make sure to not change the function names or arguments.\n\ndef forward_log_det_jacobian(x, b, shift_and_log_scale_fn):\n    \"\"\"\n    This function takes the input Tensor x, binary mask b and callable\n    shift_and_log_scale_fn as arguments.\n    This function should compute and return the log of the Jacobian determinant \n    of the forward transformation in equation (5)\n    \"\"\"\n    t,s=shift_and_log_scale_fn(b*x)\n    return tf.reduce_sum((1-b)*s,axis=[-1,-2,-3])\n    \n    \n\ndef inverse_log_det_jacobian(y, b, shift_and_log_scale_fn):\n    \"\"\"\n    This function takes the input Tensor y, binary mask b and callable\n    shift_and_log_scale_fn as arguments.\n    This function should compute and return the log of the Jacobian determinant \n    of the forward transformation in equation (6)\n    \"\"\"\n    t,s=shift_and_log_scale_fn(b*y)\n    return -tf.reduce_sum((1-b)*s,axis=[-1,-2,-3])\n    \n    \n```\n\nYou are now ready to create the coupling layer bijector, using bijector subclassing. You should complete the class below to define the `AffineCouplingLayer`. \n\n* You should complete the initialiser `__init__`, and the internal class method `_get_mask`\n* The `_forward`, `_inverse`, `_forward_log_det_jacobian` and `_inverse_log_det_jacobian` methods are completed for you using the functions you have written above. Do not modify these methods\n* The initialiser takes the `shift_and_log_scale_fn` callable, `mask_type` string (either `\"checkerboard\"` or `\"channel\"`, `orientation` (integer, either `0` or `1`) as required arguments, and allows for extra keyword arguments\n  * The required arguments should be set as class attributes in the initialiser (note that the `shift_and_log_scale_fn` attribute is being used in the `_forward`, `_inverse`, `_forward_log_det_jacobian` and `_inverse_log_det_jacobian` methods)\n  * The initialiser should call the base class initialiser, and pass in any extra keyword arguments\n  * The class should have a required number of event dimensions equal to 3\n* The internal method `_get_mask` takes a `shape` as an argument, which is the shape of an input Tensor\n  * This method should use the `checkerboard_binary_mask` and `channel_binary_mask` functions above, as well as the `mask_type` and `orientation` arguments passed to the initialiser to compute and return the required binary mask\n  * This method is used in each of the `_forward`, `_inverse`, `_forward_log_det_jacobian` and `_inverse_log_det_jacobian` methods\n\n\n```python\n#### GRADED CELL ####\n\n# Complete the following class. \n# Make sure to not change the class or method names or arguments.\n\nclass AffineCouplingLayer(tfb.Bijector):\n    \"\"\"\n    Class to implement the affine coupling layer.\n    Complete the __init__ and _get_mask methods according to the instructions above.\n    \"\"\"\n\n    def __init__(self, shift_and_log_scale_fn, mask_type, orientation, **kwargs):\n        \"\"\"\n        The class initialiser takes the shift_and_log_scale_fn callable, mask_type,\n        orientation and possibly extra keywords arguments. It should call the \n        base class initialiser, passing any extra keyword arguments along. \n        It should also set the required arguments as class attributes.\n        \"\"\"\n        super(AffineCouplingLayer,self).__init__(forward_min_event_ndims=3,**kwargs)\n        self.shift_and_log_scale_fn=shift_and_log_scale_fn\n        self.mask_type=mask_type\n        self.orientation=orientation\n        \n        \n        \n    def _get_mask(self, shape):\n        \"\"\"\n        This internal method should use the binary mask functions above to compute\n        and return the binary mask, according to the arguments passed in to the\n        initialiser.\n        \"\"\"\n        if self.mask_type!='channel':\n          return checkerboard_binary_mask(shape[1:],self.orientation)\n        elif self.mask_type=='channel':\n          return channel_binary_mask(shape[-1],self.orientation)\n        \n        \n\n    def _forward(self, x):\n        b = self._get_mask(x.shape)\n        return forward(x, b, self.shift_and_log_scale_fn)\n\n    def _inverse(self, y):\n        b = self._get_mask(y.shape)\n        return inverse(y, b, self.shift_and_log_scale_fn)\n\n    def _forward_log_det_jacobian(self, x):\n        b = self._get_mask(x.shape)\n        return forward_log_det_jacobian(x, b, self.shift_and_log_scale_fn)\n\n    def _inverse_log_det_jacobian(self, y):\n        b = self._get_mask(y.shape)\n        return inverse_log_det_jacobian(y, b, self.shift_and_log_scale_fn)\n```\n\n\n```python\n# Test your function by creating an instance of the AffineCouplingLayer class\n\naffine_coupling_layer = AffineCouplingLayer(conv_resnet, 'channel', orientation=1, \n                                            name='affine_coupling_layer')\n```\n\n\n```python\n# The following should return a Tensor of the same shape as the input\n\naffine_coupling_layer.forward(tf.random.normal((16, 32, 32, 3))).shape\n```\n\n\n\n\n    TensorShape([16, 32, 32, 3])\n\n\n\n\n```python\n# The following should compute a log_det_jacobian for each event in the batch\n\naffine_coupling_layer.forward_log_det_jacobian(tf.random.normal((16, 32, 32, 3)), event_ndims=3).shape\n```\n\n\n\n\n    TensorShape([16])\n\n\n\n#### Combining the affine coupling layers\n\nIn the affine coupling layer, part of the input remains unchanged in the transformation $(5)$. In order to allow transformation of all of the input, several coupling layers are composed, with the orientation of the mask being reversed in subsequent layers.\n\n\n```python\n# Run this cell to download and view a sketch of the affine coupling layers\n\n!wget -q -O alternating_masks.png --no-check-certificate \"https://docs.google.com/uc?export=download&id=1r1vASfLOW3kevxRzFUXhCtHN8dzldHve\"\nImage(\"alternating_masks.png\", width=800)\n```\n\n<center>Figure 2. RealNVP alternates the orientation of masks from one affine coupling layer to the next. From the original paper.</center>\n\nOur model design will be similar to the original architecture; we will compose three affine coupling layers with checkerboard masking, followed by a batch normalization bijector (`tfb.BatchNormalization` is a built-in bijector), followed by a squeezing operation, followed by three more affine coupling layers with channel-wise masking and a final batch normalization bijector. \n\nThe squeezing operation divides the spatial dimensions into 2x2 squares, and reshapes a Tensor of shape `(H, W, C)` into a Tensor of shape `(H // 2, W // 2, 4 * C)` as shown in Figure 1.\n\nThe squeezing operation is also a bijective operation, and has been provided for you in the class below.\n\n\n```python\n# Bijector class for the squeezing operation\n\nclass Squeeze(tfb.Bijector):\n    \n    def __init__(self, name='Squeeze', **kwargs):\n        super(Squeeze, self).__init__(forward_min_event_ndims=3, is_constant_jacobian=True, \n                                      name=name, **kwargs)\n\n    def _forward(self, x):\n        input_shape = x.shape\n        height, width, channels = input_shape[-3:]\n        y = tfb.Reshape((height // 2, 2, width // 2, 2, channels), event_shape_in=(height, width, channels))(x)\n        y = tfb.Transpose(perm=[0, 2, 1, 3, 4])(y)\n        y = tfb.Reshape((height // 2, width // 2, 4 * channels),\n                        event_shape_in=(height // 2, width // 2, 2, 2, channels))(y)\n        return y\n\n    def _inverse(self, y):\n        input_shape = y.shape\n        height, width, channels = input_shape[-3:]\n        x = tfb.Reshape((height, width, 2, 2, channels // 4), event_shape_in=(height, width, channels))(y)\n        x = tfb.Transpose(perm=[0, 2, 1, 3, 4])(x)\n        x = tfb.Reshape((2 * height, 2 * width, channels // 4),\n                        event_shape_in=(height, 2, width, 2, channels // 4))(x)\n        return x\n\n    def _forward_log_det_jacobian(self, x):\n        return tf.constant(0., x.dtype)\n\n    def _inverse_log_det_jacobian(self, y):\n        return tf.constant(0., y.dtype)\n\n    def _forward_event_shape_tensor(self, input_shape):\n        height, width, channels = input_shape[-3], input_shape[-2], input_shape[-1]\n        return height // 2, width // 2, 4 * channels\n\n    def _inverse_event_shape_tensor(self, output_shape):\n        height, width, channels = output_shape[-3], output_shape[-2], output_shape[-1]\n        return height * 2, width * 2, channels // 4\n```\n\nYou can see the effect of the squeezing operation on some example inputs in the cells below. In the forward transformation, each spatial dimension is halved, whilst the channel dimension is multiplied by 4. The opposite happens in the inverse transformation.\n\n\n```python\n# Test the Squeeze bijector\n\nsqueeze = Squeeze()\nsqueeze(tf.ones((10, 32, 32, 3))).shape\n```\n\n\n\n\n    TensorShape([10, 16, 16, 12])\n\n\n\n\n```python\n# Test the inverse operation\n\nsqueeze.inverse(tf.ones((10, 4, 4, 96))).shape\n```\n\n\n\n\n    TensorShape([10, 8, 8, 24])\n\n\n\nWe can now construct a block of coupling layers according to the architecture described above. You should complete the following function to chain together the bijectors that we have constructed, to form a bijector that performs the following operations in the forward transformation:\n\n* Three `AffineCouplingLayer` bijectors with `\"checkerboard\"` masking with orientations `0, 1, 0` respectively\n* A `BatchNormalization` bijector\n* A `Squeeze` bijector\n* Three more `AffineCouplingLayer` bijectors with `\"channel\"` masking with orientations `0, 1, 0` respectively\n* Another `BatchNormalization` bijector\n\nThe function takes the following arguments:\n* `shift_and_log_scale_fns`: a list or tuple of six conv_resnet models\n  * The first three models in this list are used in the three coupling layers with checkerboard masking\n  * The last three models in this list are used in the three coupling layers with channel masking\n* `squeeze`: an instance of the `Squeeze` bijector\n\n_NB: at this point, we would like to point out that we are following the exposition in the original paper, and think of the forward transformation as acting on the input image. Note that this is in contrast to the convention of using the forward transformation for sampling, and the inverse transformation for computing log probs._\n\n\n```python\n#### GRADED CELL ####\n\n# Complete the following function. \n# Make sure to not change the function name or arguments.\n\ndef realnvp_block(shift_and_log_scale_fns, squeeze):\n    \"\"\"\n    This function takes a list or tuple of six conv_resnet models, and an \n    instance of the Squeeze bijector.\n    The function should construct the chain of bijectors described above,\n    using the conv_resnet models in the coupling layers.\n    The function should then return the chained bijector.\n    \"\"\"\n    l1=AffineCouplingLayer(shift_and_log_scale_fns[0],'checkerboard',orientation=0)\n    l2=AffineCouplingLayer(shift_and_log_scale_fns[1],'checkerboard',orientation=1)\n    l3=AffineCouplingLayer(shift_and_log_scale_fns[2],'checkerboard',orientation=0)\n    l4=tfb.BatchNormalization()\n    l5=squeeze\n    l6=AffineCouplingLayer(shift_and_log_scale_fns[3],'channel',orientation=0)\n    l7=AffineCouplingLayer(shift_and_log_scale_fns[4],'channel',orientation=1)\n    l8=AffineCouplingLayer(shift_and_log_scale_fns[5],'channel',orientation=0)\n    l9=tfb.BatchNormalization()\n    return tfb.Chain([l9,l8,l7,l6,l5,l4,l3,l2,l1])\n    \n```\n\n\n```python\n# Run your function to create an instance of the bijector\n\ncheckerboard_fns = []\nfor _ in range(3):\n    checkerboard_fns.append(get_conv_resnet((32, 32, 3), 512))\nchannel_fns = []\nfor _ in range(3):\n    channel_fns.append(get_conv_resnet((16, 16, 12), 512))\n    \nblock = realnvp_block(checkerboard_fns + channel_fns, squeeze)\n```\n\n\n```python\n# Test the bijector on a dummy input\n\nblock.forward(tf.random.normal((10, 32, 32, 3))).shape\n```\n\n\n\n\n    TensorShape([10, 16, 16, 12])\n\n\n\n#### Multiscale architecture\n\nThe final component of the RealNVP is the multiscale architecture. The squeeze operation reduces the spatial dimensions but increases the channel dimensions. After one of the blocks of coupling-squeeze-coupling that you have implemented above, half of the dimensions are factored out as latent variables, while the other half is further processed through subsequent layers. This results in latent variables that represent different scales of features in the model.\n\n\n```python\n# Run this cell to download and view a sketch of the multiscale architecture\n\n!wget -q -O multiscale.png --no-check-certificate \"https://docs.google.com/uc?export=download&id=19Sc6PKbc8Bi2DoyupHZxHvB3m6tw-lki\"\nImage(\"multiscale.png\", width=700)\n```\n\n<center>Figure 3. RealNVP creates latent variables at different scales by factoring out half of the dimensions at each scale. From the original paper.</center>\n\nThe final scale does not use the squeezing operation, and instead applies four affine coupling layers with alternating checkerboard masks.\n\nThe multiscale architecture for two latent variable scales is implemented for you in the following bijector.\n\n\n```python\n# Bijector to implement the multiscale architecture\n\nclass RealNVPMultiScale(tfb.Bijector):\n    \n    def __init__(self, **kwargs):\n        super(RealNVPMultiScale, self).__init__(forward_min_event_ndims=3, **kwargs)\n\n        # First level\n        shape1 = (32, 32, 3)  # Input shape\n        shape2 = (16, 16, 12)  # Shape after the squeeze operation\n        shape3 = (16, 16, 6)  # Shape after factoring out the latent variable\n        self.conv_resnet1 = get_conv_resnet(shape1, 64)\n        self.conv_resnet2 = get_conv_resnet(shape1, 64)\n        self.conv_resnet3 = get_conv_resnet(shape1, 64)\n        self.conv_resnet4 = get_conv_resnet(shape2, 128)\n        self.conv_resnet5 = get_conv_resnet(shape2, 128)\n        self.conv_resnet6 = get_conv_resnet(shape2, 128)\n        self.squeeze = Squeeze()\n        self.block1 = realnvp_block([self.conv_resnet1, self.conv_resnet2,\n                                    self.conv_resnet3, self.conv_resnet4,\n                                    self.conv_resnet5, self.conv_resnet6], self.squeeze)\n\n        # Second level\n        self.conv_resnet7 = get_conv_resnet(shape3, 128)\n        self.conv_resnet8 = get_conv_resnet(shape3, 128)\n        self.conv_resnet9 = get_conv_resnet(shape3, 128)\n        self.conv_resnet10 = get_conv_resnet(shape3, 128)\n        self.coupling_layer1 = AffineCouplingLayer(self.conv_resnet7, 'checkerboard', 0)\n        self.coupling_layer2 = AffineCouplingLayer(self.conv_resnet8, 'checkerboard', 1)\n        self.coupling_layer3 = AffineCouplingLayer(self.conv_resnet9, 'checkerboard', 0)\n        self.coupling_layer4 = AffineCouplingLayer(self.conv_resnet10, 'checkerboard', 1)\n        self.block2 = tfb.Chain([self.coupling_layer4, self.coupling_layer3,\n                                 self.coupling_layer2, self.coupling_layer1])\n\n    def _forward(self, x):\n        h1 = self.block1.forward(x)\n        z1, h2 = tf.split(h1, 2, axis=-1)\n        z2 = self.block2.forward(h2)\n        return tf.concat([z1, z2], axis=-1)\n        \n    def _inverse(self, y):\n        z1, z2 = tf.split(y, 2, axis=-1)\n        h2 = self.block2.inverse(z2)\n        h1 = tf.concat([z1, h2], axis=-1)\n        return self.block1.inverse(h1)\n\n    def _forward_log_det_jacobian(self, x):\n        log_det1 = self.block1.forward_log_det_jacobian(x, event_ndims=3)\n        h1 = self.block1.forward(x)\n        _, h2 = tf.split(h1, 2, axis=-1)\n        log_det2 = self.block2.forward_log_det_jacobian(h2, event_ndims=3)\n        return log_det1 + log_det2\n\n    def _inverse_log_det_jacobian(self, y):\n        z1, z2 = tf.split(y, 2, axis=-1)\n        h2 = self.block2.inverse(z2)\n        log_det2 = self.block2.inverse_log_det_jacobian(z2, event_ndims=3)\n        h1 = tf.concat([z1, h2], axis=-1)\n        log_det1 = self.block1.inverse_log_det_jacobian(h1, event_ndims=3)\n        return log_det1 + log_det2\n\n    def _forward_event_shape_tensor(self, input_shape):\n        height, width, channels = input_shape[-3], input_shape[-2], input_shape[-1]\n        return height // 4, width // 4, 16 * channels\n\n    def _inverse_event_shape_tensor(self, output_shape):\n        height, width, channels = output_shape[-3], output_shape[-2], output_shape[-1]\n        return 4 * height, 4 * width, channels // 16\n```\n\n\n```python\n# Create an instance of the multiscale architecture\n\nmultiscale_bijector = RealNVPMultiScale()\n```\n\n#### Data preprocessing bijector\n\nWe will also preprocess the image data before sending it through the RealNVP model. To do this, for a Tensor $x$ of pixel values in $[0, 1]^D$, we transform $x$ according to the following:\n\n$$\nT(x) = \\text{logit}\\left(\\alpha + (1 - 2\\alpha)x\\right),\\tag{7}\n$$\n\nwhere $\\alpha$ is a parameter, and the logit function is the inverse of the sigmoid function, and is given by \n\n$$\n\\text{logit}(p) = \\log (p) - \\log (1 - p).\n$$\n\nYou should now complete the following function to construct this bijector from in-built bijectors from the bijectors module.\n\n* The function takes the parameter `alpha` as an input, which you can assume to take a small positive value ($\\ll0.5$)\n* The function should construct and return a bijector that computes $(7)$ in the forward pass\n\n\n```python\n#### GRADED CELL ####\n\n# Complete the following function. \n# Make sure to not change the function name or arguments.\n\ndef get_preprocess_bijector(alpha):\n    \"\"\"\n    This function should create a chained bijector that computes the \n    transformation T in equation (7) above.\n    This can be computed using in-built bijectors from the bijectors module.\n    Your function should then return the chained bijector.\n    \"\"\"\n    l1=tfb.Scale(1-2*alpha)\n    l2=tfb.Shift(alpha)\n    l3=tfb.Invert(tfb.Sigmoid())\n    return tfb.Chain([l3,l2,l1])\n    \n    \n```\n\n\n```python\n# Create an instance of the preprocess bijector\n\npreprocess = get_preprocess_bijector(0.05)\n```\n\n#### Train the RealNVP model\n\nFinally, we will use our RealNVP model to train\n\nWe will use the following model class to help with the training process.\n\n\n```python\n# Helper class for training\n\nclass RealNVPModel(Model):\n\n    def __init__(self, **kwargs):\n        super(RealNVPModel, self).__init__(**kwargs)\n        self.preprocess = get_preprocess_bijector(0.05)\n        self.realnvp_multiscale = RealNVPMultiScale()\n        self.bijector = tfb.Chain([self.realnvp_multiscale, self.preprocess])\n        \n    def build(self, input_shape):\n        output_shape = self.bijector(tf.expand_dims(tf.zeros(input_shape[1:]), axis=0)).shape\n        self.base = tfd.Independent(tfd.Normal(loc=tf.zeros(output_shape[1:]), scale=1.),\n                                    reinterpreted_batch_ndims=3)\n        self._bijector_variables = (\n            list(self.bijector.variables))\n        self.flow = tfd.TransformedDistribution(\n            distribution=self.base,\n            bijector=tfb.Invert(self.bijector),\n        )\n        super(RealNVPModel, self).build(input_shape)\n\n    def call(self, inputs, training=None, **kwargs):\n        return self.flow\n\n    def sample(self, batch_size):\n        sample = self.base.sample(batch_size)\n        return self.bijector.inverse(sample)\n```\n\n\n```python\n# Create an instance of the RealNVPModel class\n\nrealnvp_model = RealNVPModel()\nrealnvp_model.build((1, 32, 32, 3))\n```\n\n\n```python\n# Compute the number of variables in the model\n\nprint(\"Total trainable variables:\")\nprint(sum([np.prod(v.shape) for v in realnvp_model.trainable_variables]))\n```\n\n    Total trainable variables:\n    411468\n\n\nNote that the model's `call` method returns the `TransformedDistribution` object. Also, we have set up our datasets to return the input image twice as a 2-tuple. This is so we can train our model with negative log-likelihood as normal.\n\n\n```python\n# Define the negative log-likelihood loss function\n\ndef nll(y_true, y_pred):\n    return -y_pred.log_prob(y_true)\n```\n\nIt is recommended to use the GPU accelerator hardware on Colab to train this model, as it can take some time to train. Note that it is not required to train the model in order to pass this assignment. For optimal results, a larger model should be trained for longer.\n\n\n```python\n# Compile and train the model\n\noptimizer = Adam()\nrealnvp_model.compile(loss=nll, optimizer=Adam())\nrealnvp_model.fit(train_ds, validation_data=val_ds, epochs=30)\n```\n\n    Epoch 1/30\n    938/938 [==============================] - 157s 167ms/step - loss: -4198.9170 - val_loss: -6479.9341\n    Epoch 2/30\n    938/938 [==============================] - 155s 165ms/step - loss: -6878.4443 - val_loss: -7294.2310\n    Epoch 3/30\n    938/938 [==============================] - 181s 193ms/step - loss: -7429.2651 - val_loss: -7641.1729\n    Epoch 4/30\n    938/938 [==============================] - 158s 168ms/step - loss: -7658.2246 - val_loss: -7765.8506\n    Epoch 5/30\n    938/938 [==============================] - 154s 164ms/step - loss: -7988.6016 - val_loss: -8165.0649\n    Epoch 6/30\n    938/938 [==============================] - 154s 165ms/step - loss: -8197.5889 - val_loss: -8311.8115\n    Epoch 7/30\n    938/938 [==============================] - 154s 164ms/step - loss: -8205.1367 - val_loss: -8361.0029\n    Epoch 8/30\n    938/938 [==============================] - 154s 164ms/step - loss: -8431.5410 - val_loss: -8531.9053\n    Epoch 9/30\n    938/938 [==============================] - 154s 164ms/step - loss: -8528.5713 - val_loss: -8578.6035\n    Epoch 10/30\n    938/938 [==============================] - 155s 165ms/step - loss: -8611.7568 - val_loss: -8685.4248\n    Epoch 11/30\n    938/938 [==============================] - 155s 165ms/step - loss: -8699.3584 - val_loss: -8798.7529\n    Epoch 12/30\n    938/938 [==============================] - 153s 163ms/step - loss: -8789.7012 - val_loss: -8657.1240\n    Epoch 13/30\n    938/938 [==============================] - 154s 165ms/step - loss: -8840.0957 - val_loss: -8809.8057\n    Epoch 14/30\n    938/938 [==============================] - 153s 163ms/step - loss: -8889.6670 - val_loss: -8928.7236\n    Epoch 15/30\n    938/938 [==============================] - 153s 163ms/step - loss: -8931.1396 - val_loss: -8976.1582\n    Epoch 16/30\n    938/938 [==============================] - 154s 164ms/step - loss: -8956.2129 - val_loss: -9022.7129\n    Epoch 17/30\n    938/938 [==============================] - 155s 165ms/step - loss: -9004.2812 - val_loss: -8862.6758\n    Epoch 18/30\n    938/938 [==============================] - 153s 163ms/step - loss: -9029.0273 - val_loss: -8976.9365\n    Epoch 19/30\n    938/938 [==============================] - 154s 164ms/step - loss: -9052.1084 - val_loss: -9025.9404\n    Epoch 20/30\n    938/938 [==============================] - 154s 164ms/step - loss: -9065.9424 - val_loss: -9100.0156\n    Epoch 21/30\n    938/938 [==============================] - 154s 164ms/step - loss: -9086.8291 - val_loss: -9065.6318\n    Epoch 22/30\n    938/938 [==============================] - 153s 163ms/step - loss: -9112.7607 - val_loss: -9095.4609\n    Epoch 23/30\n    938/938 [==============================] - 154s 164ms/step - loss: -9128.1982 - val_loss: -9161.4229\n    Epoch 24/30\n    938/938 [==============================] - 153s 163ms/step - loss: -9147.2607 - val_loss: -9148.3809\n    Epoch 25/30\n    938/938 [==============================] - 152s 162ms/step - loss: -9157.2627 - val_loss: -9189.7930\n    Epoch 26/30\n    938/938 [==============================] - 153s 163ms/step - loss: -9175.0059 - val_loss: -9199.8809\n    Epoch 27/30\n    938/938 [==============================] - 152s 162ms/step - loss: -9173.3311 - val_loss: -9208.4639\n    Epoch 28/30\n    938/938 [==============================] - 152s 162ms/step - loss: -9192.8428 - val_loss: -9200.8281\n    Epoch 29/30\n    938/938 [==============================] - 152s 162ms/step - loss: -9204.8057 - val_loss: -9239.0176\n    Epoch 30/30\n    938/938 [==============================] - 153s 163ms/step - loss: -9215.8760 - val_loss: -9232.9316\n\n\n\n\n\n    <tensorflow.python.keras.callbacks.History at 0x7fc2a1ae7990>\n\n\n\n\n```python\n# Evaluate the model\n\nrealnvp_model.evaluate(test_ds)\n```\n\n    157/157 [==============================] - 14s 90ms/step - loss: -9226.8008\n\n\n\n\n\n    -9226.80078125\n\n\n\n#### Generate some samples\n\n\n```python\n# Sample from the model\n\nsamples = realnvp_model.sample(8).numpy()\n```\n\n    WARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/tensorflow_probability/python/bijectors/batch_normalization.py:210: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Please use `layer.__call__` method instead.\n\n\n\n```python\n# Display the samples\n\nn_img = 8\nf, axs = plt.subplots(2, n_img // 2, figsize=(14, 7))\n\nfor k, image in enumerate(samples):\n    i = k % 2\n    j = k // 2\n    axs[i, j].imshow(image[0])\n    axs[i, j].axis('off')\nf.subplots_adjust(wspace=0.01, hspace=0.03)\n```\n\nCongratulations on completing this programming assignment! In the next week of the course we will look at the variational autoencoder.\n", "meta": {"hexsha": "8581a4a6d8d60621b674795cde76a36fecb9c662", "size": 660540, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Week3/Week 3 Programming Assignment.ipynb", "max_stars_repo_name": "stevensmiley1989/Prob_TF2_Examples", "max_stars_repo_head_hexsha": "fa022e58a44563d09792070be5d015d0798ca00d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Week3/Week 3 Programming Assignment.ipynb", "max_issues_repo_name": "stevensmiley1989/Prob_TF2_Examples", "max_issues_repo_head_hexsha": "fa022e58a44563d09792070be5d015d0798ca00d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week3/Week 3 Programming Assignment.ipynb", "max_forks_repo_name": "stevensmiley1989/Prob_TF2_Examples", "max_forks_repo_head_hexsha": "fa022e58a44563d09792070be5d015d0798ca00d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 660540.0, "max_line_length": 660540, "alphanum_fraction": 0.9316740848, "converted": true, "num_tokens": 15531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10087863083945883, "lm_q2_score": 0.0826973511528864, "lm_q1q2_score": 0.008342395558353123}}
{"text": "```python\n# code for loading the format for the notebook\nimport os\n\n# path : store the current path to convert back to it later\npath = os.getcwd()\nos.chdir(os.path.join('..', '..', 'notebook_format'))\nfrom formats import load_style\nload_style(css_style = 'custom2.css')\n```\n\n\n\n\n\n<style>\n    html {\n        font-size: 18px !important;\n    }\n\n    body {\n        background-color: #FFF !important;\n        font-weight: 1rem;\n        font-family: 'Source Sans Pro', \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n    }\n\n    body .notebook-app {\n        background-color: #FFF !important;\n    }\n\n    #header {\n        box-shadow: none !important;\n    }\n\n    #notebook {\n        padding-top: 0px;\n    }\n\n    #notebook-container {\n        box-shadow: none;\n        -webkit-box-shadow: none;\n        padding: 10px;\n    }\n\n    div.cell {\n        width: 1000px;\n        margin-left: 0% !important;\n        margin-right: auto;\n    }\n\n    div.cell.selected {\n        border: 1px dashed #CCCCCC;\n    }\n\n    .edit_mode div.cell.selected {\n        border: 1px dashed #828282;\n    }\n\n    div.output_wrapper {\n        margin-top: 8px;\n    }\n\n    a {\n        color: #383838;\n    }\n\n    code,\n    kbd,\n    pre,\n    samp {\n        font-family: 'Menlo', monospace !important;\n        font-size: 0.75rem !important;\n    }\n\n    h1 {\n        font-size: 2rem !important;\n        font-weight: 500 !important;\n        letter-spacing: 3px !important;\n        text-transform: uppercase !important;\n    }\n\n    h2 {\n        font-size: 1.8rem !important;\n        font-weight: 400 !important;\n        letter-spacing: 3px !important;\n        text-transform: none !important;\n    }\n\n    h3 {\n        font-size: 1.5rem !important;\n        font-weight: 400 !important;\n        font-style: italic !important;\n        display: block !important;\n    }\n\n    h4,\n    h5,\n    h6 {\n        font-size: 1rem !important;\n        font-weight: 400 !important;\n        display: block !important;\n    }\n\n    .prompt {\n        font-family: 'Menlo', monospace !important;\n        font-size: 0.75rem;\n        text-align: right;\n        line-height: 1.21429rem;\n    }\n\n    /* INTRO PAGE */\n\n    .toolbar_info,\n    .list-container {\n        ;\n    }\n    /* NOTEBOOK */\n\n    div#header-container {\n        display: none !important;\n    }\n\n    div#notebook {\n        border-top: none;\n        font-size: 1rem;\n    }\n\n    div.input_prompt {\n        color: #C74483;\n    }\n\n    .code_cell div.input_prompt:after,\n    div.output_prompt:after {\n        content: '\\25b6';\n    }\n\n    div.output_prompt {\n        color: #2B88D9;\n    }\n\n    div.input_area {\n        border-radius: 0px;\n        border: 1px solid #d8d8d8;\n    }\n\n    div.output_area pre {\n        font-weight: normal;\n    }\n\n    div.output_subarea {\n        font-weight: normal;\n    }\n\n    .rendered_html pre,\n    .rendered_html table,\n    .rendered_html th,\n    .rendered_html tr,\n    .rendered_html td {\n        border: 1px #828282 solid;\n        font-size: 0.75rem;\n        font-family: 'Menlo', monospace;\n    }\n\n    .rendered_html th,\n    .rendered_html tr,\n    .rendered_html td {\n        padding: 5px 10px;\n    }\n\n    .rendered_html th {\n        font-weight: normal;\n        background: #f8f8f8;\n    }\n\n    a:link{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:visited{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:hover{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:focus{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:active{\n       font-weight: bold;\n       color:#447adb;\n    }\n    .rendered_html :link {\n       text-decoration: underline; \n    }\n\n    div.output_html {\n        font-weight: 1rem;\n        font-family: 'Source Sans Pro', \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n    }\n\n    table.dataframe tr {\n        border: 1px #CCCCCC;\n    }\n\n    div.cell.selected {\n        border-radius: 0px;\n    }\n\n    div.cell.edit_mode {\n        border-radius: 0px;\n        border: thin solid #CF5804;\n    }\n\n    span.ansiblue {\n        color: #00A397;\n    }\n\n    span.ansigray {\n        color: #d8d8d8;\n    }\n\n    span.ansigreen {\n        color: #688A0A;\n    }\n\n    span.ansipurple {\n        color: #975DDE;\n    }\n\n    span.ansired {\n        color: #D43132;\n    }\n\n    span.ansiyellow {\n        color: #D9AA00;\n    }\n\n    div.output_stderr {\n        background-color: #D43132;\n    }\n\n    div.output_stderr pre {\n        color: #e8e8e8;\n    }\n\n    .cm-s-ipython.CodeMirror {\n        background: #F8F8F8;\n    }\n\n    .cm-s-ipython div.CodeMirror-selected {\n        background: #e8e8e8 !important;\n    }\n\n    .cm-s-ipython .CodeMirror-gutters {\n        background: #F8F8F8;\n        border-right: 0px;\n    }\n\n    .cm-s-ipython .CodeMirror-linenumber {\n        color: #b8b8b8;\n    }\n\n    .cm-s-ipython .CodeMirror-cursor {\n        border-left: 1px solid #585858 !important;\n    }\n\n    .cm-s-ipython span.cm-atom {\n        color: #C74483;\n    }\n\n    .cm-s-ipython span.cm-number {\n        color: #C74483;\n    }\n\n    .cm-s-ipython span.cm-property,\n    .cm-s-ipython span.cm-attribute {\n        color: #688A0A;\n    }\n\n    .cm-s-ipython span.cm-keyword {\n        font-weight: normal;\n        color: #D43132;\n    }\n\n    .cm-s-ipython span.cm-string {\n        color: #D9AA00;\n    }\n\n    .cm-s-ipython span.cm-operator {\n        font-weight: normal;\n    }\n\n    .cm-s-ipython span.cm-builtin {\n        color: #2B88D9;\n    }\n\n    .cm-s-ipython span.cm-variable {\n        color: #00A397;\n    }\n\n    .cm-s-ipython span.cm-variable-2 {\n        color: #2B88D9;\n    }\n\n    .cm-s-ipython span.cm-def {\n        color: #00A397;\n    }\n\n    .cm-s-ipython span.cm-error {\n        background: #FFBDBD;\n        color: #D43132;\n    }\n\n    .cm-s-ipython span.cm-tag {\n        color: #D43132;\n    }\n\n    .cm-s-ipython span.cm-link {\n        color: #975DDE;\n    }\n\n    .cm-s-ipython .CodeMirror-matchingbracket {\n        text-decoration: underline;\n         !important;\n    }\n</style>\n\n\n\n\n\n\n```python\nos.chdir(path)\n\n# 1. magic for inline plot\n# 2. magic to print version\n# 3. magic so that the notebook will reload external python modules\n# 4. a ipython magic to enable retina (high resolution) plots\n# https://gist.github.com/minrk/3301035\n%matplotlib inline\n%load_ext watermark\n%load_ext autoreload\n%autoreload 2\n%config InlineBackend.figure_format = 'retina'\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\n\n%watermark -d -t -v -p numpy,pandas,matplotlib,sklearn\n```\n\n    2017-09-30 09:54:48 \n    \n    CPython 3.5.2\n    IPython 6.1.0\n    \n    numpy 1.13.1\n    pandas 0.20.3\n    matplotlib 2.0.0\n    sklearn 0.18.1\n\n\n# Gradient Boosting Machine (GBM)\n\nJust like [Random Forest and Extra Trees](http://nbviewer.jupyter.org/github/ethen8181/machine-learning/blob/master/trees/random_forest.ipynb), Gradient Boosting Machine is also a type of Ensemble Tree method, the only difference is it is stemmed from the the boosting framework. The idea of boosting is to add a weak classifier to the ensemble at a time, and this newly added weak classifier is trained to improve upon the already trained ensemble. Meaning it will pay higher attention on examples which are misclassi\ufb01ed or have higher errors and focus on mitigating those errors. Boosting is a general framework can be applied to any sort of weak learner, although Decision Tree models is by far the commonly used due to the fact that they have the flexibility to be weak learners by simply restricting their depth and they are quite fast to train.\n\nSuppose we are given some dataset $(x_1, y_1), (x_2, y_2), ...,(x_n, y_n)$, and the task is to fit a model $F(x)$ to minimize square loss. After training the model, we discovered the model is good but not perfect.\nThere are some mistakes: $F(x_1) = 0.8$, while $y_1 = 0.9$, and $F(x_2) = 1.4$ while $y_2 = 1.3$ .... Now the question is, how can we improve this model without changing anything from $F(x)$?\n\nHow about we simply add an additional model (e.g. regression tree) $h$ to the already existing $F$, so the new prediction becomes $F(x) + h(x)$. In other words, we wish to improve upon the existing model so that $F(x_1) + h(x_1) = y_1, F(x_2) + h(x_2) = y_2 ...$ or equivalent we wish to find a new model $h$ such that $h(x_1) = y_1 - F(x_1), h(x_2) = y_2 - F(x_2) ...$. The idea is all well and good, but the bad news is probably no model $h$ (e.g. regression tree) will be able to do this perfectly. Fortunately, the good news is, some $h$ might be able to do this approximately.\n\nThe idea is, we fit the model $h$ to the data using $y_1 - F(x_1), y_2 - F(x_2)$ as the response variable. And the intuition for this is: the $y_i - F(x_i)$s are the residuals. These are the areas that the existing\nmodel $F$ cannot do well, so now the role of $h$ is to compensate the shortcoming of existing model $F$. And if the model after adding the new model $h$, $F + h$ is still unsatisfactory, we will just add another new one.\n\nTo make sure we're actually learning the residuals, we'll employ the idea of gradient descent. Say our goal is to minimize $J$, an overall loss function additively calculated from all observations with regard to $F$, a classifier with some parameters. More formally, we're given the formula:\n\n$$J(y, F) = \\sum_i^n L\\big(y_i, F(x_i)\\big)$$\n\nWhere:\n\n- $L$ is a cost/loss function comparing the response variable's value and the prediction of the model for each observation\n\nInstead of trying to solve it directly, gradient descent is an iterative technique that allows us to approach the solution of an optimization problem. At each step of the algorithm, it will perform the following operations:\n\n$$F_b(x_i) = F_{b-1}(x_i) - \\eta \\times \\nabla L\\big(y_i, F(x_i)\\big)$$\n\nWhere:\n\n- $F_b$ is the version of classifier at step/iteration $b$\n- $\\eta$ is the learning rate which controls the size of the learning process\n- $\\nabla$ is the gradient i.e. the first order partial derivative of the cost function with respect to the classifier\n- The formula above actually refers to stochastic gradient descent only computing the function for a single observation, $x_i$\n\nFor example, say we're given, sum of squares errors, a well-known quality indicator for regression model as our loss function. So now our loss function $L\\big(y_i, F(x_i)\\big)$ is defined as: $\\frac{1}{2} \\big( y_i - F(x_i) \\big)^2$ (the 1/2 is simply to make the notation cleaner later). Taking the gradient of this loss function we get:\n\n$$\\frac{ \\partial L\\big(y_i, F(x_i)\\big) }{ \\partial F(x_i) } = \\frac{ \\partial \\frac{1}{2} \\big( y_i - F(x_i) \\big)^2 }{ \\partial F(x_i) } = F(x_i) - y_i$$\n\nTying this back to our original problem, we wish to update our function $F$ at iteration $b$ with a new model $h$:\n\n\\begin{align}\nF_b(x_i) &= F_{b-1}(x_i) + h(x_i) \\nonumber \\\\\n         &= F_{b-1}(x_i) + y_i - F_{b-1}(x_i) \\nonumber \\\\\n         &= F_{b-1}(x_i) - 1 \\times \\frac{ \\partial L\\big(y_i, F_{b-1}(x_i)\\big) }{ \\partial F_{b-1}(x_i) }\n         \\nonumber \\\\\n\\end{align}\n\nAs we can see, the formula above is 99% the same as as the gradient descent formula, $F_b(x_i) = F_{b-1}(x_i) - \\eta \\times \\nabla L\\big(y_i, F(x_i)\\big)$. The only difference is that the learning rate $\\eta$ is  1. Thus, we now have an iterative process constructing the additive model that minimizes our loss function (residuals).\n\nIn practice though, Gradient Boosting Machine is more prone to overfitting, since the week learner is tasked with optimally fitting the gradient. This means that boosting will select the optimal learner at each stage of the algorithm, although this strategy generates an optimal solution at the current stage, it has the drawbacks of not finding the optimal global model as well as overfitting the training data. A remedy for greediness is to constrain the learning process by setting the learning rate $\\eta$ (also known as shrinkage). In the above algorithm, instead of directly adding the predicted value for a sample to next iteration's predicted value, so that only a fraction of the current predicted value is added to the previous iteration's predicted value. This parameter can take values between 0 and 1 and becomes another tuning parameter for the model. Small values of the learning parameter such as 0.1 tends to work better, but the value of the parameter is inversely proportional to the computation time required to find an optimal model, because more iterations is required.\n\nTo sum it all up, the process of training a GBM for regression is:\n\n1. Initialize a predicted value for each observation (e.g. the original response or the average response or a value that minimizes the loss function). This will be our initial \"residuals\", $r$. It can be called the residuals because we're dealing with a regression task, but this quantity is more often referred to as the negative gradient, this terminology makes the $- \\nabla \\times L\\big(y_i, F(x_i) \\big)$ part generalizes to any loss function we might wish to employ. In short, GBM is fitting to the gradient of the loss function\n2. For step = 1 to $B$ (number of iterations that we specify) do:\n    - Fit a regression tree $F_b$ to the training data $(X, r)$, where we use the residuals as the response variable\n    - Update model $F$ by adding a shrunken version of the newly fitted regression tree. Translating it to code, this means we append the new tree to the array of trees we've already stored: \n    $F(X) = F(X) + \\eta F_{b}(X)$\n    - Update each observation's residual by adding the predicted value to it:\n    $r_{b + 1} = r_b - \\eta F_b(X)$\n3. In the end, our final output boosted model becomes $F(x) = \\sum_{b = 1}^B \\eta F_b(x)$, where we sum the values that each individual tree gives (times the learning rate)\n\nTo hit the notion home, let's conside an example using made up numbers. Suppose we have 5 observations, with responses 10, 20, 30, 40, 50. The first tree is built and gives predictions of 12, 18, 27, 39, 54 (these predictions are made up numbers). If our learning rate $\\eta$ = 0.1, all trees will have their predictions scaled down by $\\eta$, so the first tree will instead \"predict\" 1.2, 1.8, 2.7, 3.9, 5.4. The response variable passed to the next tree will then have values 8.8, 18.2, 27.3, 36.1, 44.6 (the difference between the prediction that was scaled down by the prediction and the true response). The second round then uses these response values to build another tree - and again the predictions are scaled down by the learning rate $\\eta$. So tree 2 predicts say, 7, 18, 25, 40, 40, which, once scaled, become 0.7, 1.8, 2.5, 4.0, 4.0. As before, the third tree will be passed the difference between these values and the previous tree's response variable (so 8.1, 16.4, 24.8, 32.1. 40.6). And we keep iterating this process until we finished training all the trees (a parameter that we specify), in the end, the sum of the predictions from all trees will give the final prediction.\n\n## Implementation\n\nHere, we will use the [Wine Quality Data Set](https://archive.ics.uci.edu/ml/datasets/Wine+Quality) to test our implementation. This [link](https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv) should download the .csv file. The task is to predict the quality of the wine (a scale of 1 ~ 10) given some of its features.\n\n\n```python\n# read in the data and shuffle the row order for model stability\nnp.random.seed(4321)\nwine_path = os.path.join('..', 'winequality-white.csv')\nwine = pd.read_csv(wine_path, sep = ';')\nwine = wine.sample(frac = 1)\n\n# train/test split the features and response column\ny = wine['quality'].values\nX = wine.drop('quality', axis = 1).values\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 1234)\n\nprint('dimension of the dataset: ', wine.shape)\nwine.head()\n```\n\n    dimension of the dataset:  (4898, 12)\n\n\n\n\n\n<div>\n<style>\n    .dataframe thead tr:only-child th {\n        text-align: right;\n    }\n\n    .dataframe thead th {\n        text-align: left;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fixed acidity</th>\n      <th>volatile acidity</th>\n      <th>citric acid</th>\n      <th>residual sugar</th>\n      <th>chlorides</th>\n      <th>free sulfur dioxide</th>\n      <th>total sulfur dioxide</th>\n      <th>density</th>\n      <th>pH</th>\n      <th>sulphates</th>\n      <th>alcohol</th>\n      <th>quality</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>857</th>\n      <td>8.2</td>\n      <td>0.40</td>\n      <td>0.48</td>\n      <td>13.70</td>\n      <td>0.042</td>\n      <td>59.0</td>\n      <td>169.0</td>\n      <td>0.99860</td>\n      <td>3.10</td>\n      <td>0.52</td>\n      <td>9.4</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>2325</th>\n      <td>7.0</td>\n      <td>0.35</td>\n      <td>0.17</td>\n      <td>1.10</td>\n      <td>0.049</td>\n      <td>7.0</td>\n      <td>119.0</td>\n      <td>0.99297</td>\n      <td>3.13</td>\n      <td>0.36</td>\n      <td>9.7</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>279</th>\n      <td>7.0</td>\n      <td>0.30</td>\n      <td>0.49</td>\n      <td>4.70</td>\n      <td>0.036</td>\n      <td>17.0</td>\n      <td>105.0</td>\n      <td>0.99160</td>\n      <td>3.26</td>\n      <td>0.68</td>\n      <td>12.4</td>\n      <td>7</td>\n    </tr>\n    <tr>\n      <th>1687</th>\n      <td>7.3</td>\n      <td>0.26</td>\n      <td>0.33</td>\n      <td>17.85</td>\n      <td>0.049</td>\n      <td>41.5</td>\n      <td>195.0</td>\n      <td>1.00000</td>\n      <td>3.06</td>\n      <td>0.44</td>\n      <td>9.1</td>\n      <td>7</td>\n    </tr>\n    <tr>\n      <th>531</th>\n      <td>6.4</td>\n      <td>0.18</td>\n      <td>0.48</td>\n      <td>4.00</td>\n      <td>0.186</td>\n      <td>64.0</td>\n      <td>150.0</td>\n      <td>0.99450</td>\n      <td>3.06</td>\n      <td>0.40</td>\n      <td>9.3</td>\n      <td>5</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nclass GBMReg:\n    \"\"\"\n    Regression gradient boosting machine using scikit learn's \n    decision tree as the base tree\n    \n    Parameters\n    ----------\n    n_estimators: int\n        number of trees to train\n        \n    learning_rate: float\n        learning rate, some calls it shrinkage, \n        shrinks the contribution of each tree\n        to prevent overfitting\n        \n    max_depth: int\n        controls how deep to grow the tree;\n        this is more of a decision tree parameter,\n        it is tune here to make later comparison fair\n    \n    all the other parameters for a decision tree like\n    max_features or min_sample_split also applies to GBM, \n    it is just not used here as that is more\n    related to a single decision tree\n    \"\"\"\n\n    def __init__(self, n_estimators, learning_rate, max_depth):\n        self.max_depth = max_depth\n        self.n_estimators = n_estimators\n        self.learning_rate = learning_rate\n\n    def fit(self, X, y):\n        self.estimators = []\n        \n        # simply use the response as the original residuals\n        # and covert it to float type to prevent error warning\n        # that it's converting from int to float\n        residual = y.astype(np.float)\n        for i in range(self.n_estimators):\n            tree = DecisionTreeRegressor(max_depth = self.max_depth)\n            tree.fit(X, residual)   \n            y_pred = tree.predict(X)\n            self.estimators.append(tree)  \n            residual -= self.learning_rate * y_pred\n            \n        return self\n            \n    def predict(self, X):\n        y_pred = np.zeros(X.shape[0])\n        for tree in self.estimators:\n            y_pred += self.learning_rate * tree.predict(X)\n            \n        return y_pred\n```\n\n\n```python\n# compare the results between a single decision tree,\n# gradient boosting, the lower the mean square\n# error, the better\ntree = DecisionTreeRegressor(max_depth = 6)\ntree.fit(X_train, y_train) \ntree_y_pred = tree.predict(X_test)\nprint('tree: ', mean_squared_error(y_test, tree_y_pred))\n\n# library to confirm result\ngbm_reg = GBMReg(n_estimators = 100, learning_rate = 0.1, max_depth = 6)\ngbm_reg.fit(X_train, y_train)\ngbm_reg_y_pred = gbm_reg.predict(X_test)\nprint('gbm: ', mean_squared_error(y_test, gbm_reg_y_pred))\n\n# gradient boosting for 100 trees and learning rate of 0.1\ngbm = GradientBoostingRegressor(n_estimators = 100, learning_rate = 0.1, max_depth = 6)\ngbm.fit(X_train, y_train)\ngbm_y_pred = gbm.predict(X_test)\nprint('gbm library: ', mean_squared_error(y_test, gbm_y_pred))\n```\n\n    tree:  0.547700721197\n    gbm:  0.420772942612\n    gbm library:  0.422106982302\n\n\nClearly, Gradient Boosting has some similarities to Random Forests and Extra Trees: the final prediction is based on an ensemble of models, and trees are used as the base learner, so all the tuning parameters for the tree model also controls the variability of Gradient Boosting. And for interpretability we can also access the feature importance attribute.\n\n\n```python\ndef viz_importance(model, feature_names, n_features):\n    \"\"\"Visualize the relative importance of predictors\"\"\"\n    # sort the importance in decreasing order\n    importances = model.feature_importances_\n    idx = np.argsort(importances)[-n_features:]\n    names = feature_names[idx]\n    scores = importances[idx]\n    \n    y_pos = np.arange(1, n_features + 1)\n    plt.barh(y_pos, scores, color = 'lightskyblue', align = 'center')\n    plt.yticks(y_pos, names)\n    plt.xlabel('Importance')\n    plt.title('Feature Importance Plot')\n```\n\n\n```python\n# change default figure and font size\nplt.rcParams['figure.figsize'] = 8, 6 \nplt.rcParams['font.size'] = 12\n\nviz_importance(gbm, wine.columns[:-1], X.shape[1])\n```\n\nBut the way the ensembles are constructed differs substantially between each model. In Random Forests and Extra Trees, all trees are created independently and each tree contributes equally to the final model. The trees in Gradient Boosting, however, are dependent on past trees and contribute unequally to the final model. Despite these differences, Random Forests, Extra Trees and Gradient Boosting all offer competitive predictive performance (Gradient Boosting often wins when carefully tuned). As for computation time, Gradient Boosting is often greater than for Random Forests, Extra Trees, since the two former models' procedure can be easily parallel processed given that their individual trees are created independently.\n\n## Classification\n\nGradient Boosting Machine can also be extended to handle classification tasks, as we'll soon see, even in the classification context, the underlying algorithm is still a regression tree. To adapt the algorithm to a classification process, we start by defining a new loss function, cross entropy (also known as multinomial deviance), denoted as:\n\n$$L\\big(y_i, F(x_i)\\big) = -\\sum_k ^ K y_k(x_i) \\log p_k(x_i)$$\n\nThe notation above says:\n\n- We have a total of $K$ output class (categorical response variable) that ranges from $1, ..., K$\n- $y_k(x_i)$ is a dummy indicator of the response variable that takes the value of 1 if the $i_{th}$ observation belongs to class $k$ and 0 otherwise\n- $p_k(x_i)$ is the predicted probability of the $i_{th}$ observation belonging to class $k$\n\nSo the next question is how do we get $p_k(x_i)$?\n\n### Softmax\n\nSoftmax function takes an $N$-dimensional vector of arbitrary real values and produces another $N$-dimensional vector with real values in the range (0, 1) that add up to 1. The function's formula can be written as:\n\n$$p_i = \\frac{e^{o_i}}{\\sum_k^K e^{o_k}}$$\n\nFor example, in the following code chunk, we see that how the softmax function transforms a 3-element vector 1.0, 2.0, 3.0 into probabilities that sums up to 1, while still preserving the relative size of the original elements.\n\n\n```python\ndef compute_softmax(x):\n    \"\"\"compute the softmax of vector\"\"\"\n    exp_x = np.exp(x)\n    softmax = exp_x / np.sum(exp_x)\n    return softmax\n\n# this can be interpreted as the probability\n# of belonging to the three classes\ncompute_softmax([1, 2, 3])\n```\n\n\n\n\n    array([ 0.09003057,  0.24472847,  0.66524096])\n\n\n\nNext, we wish to compute the derivative of this function with respect to the input $o_i$ so we can use it later when computing the derivative of the loss function. To be explicit we wish to find:\n\n$$\\frac{\\partial p_i}{\\partial o_j} = \\frac{\\partial \\frac{e^{o_i}}{\\sum_{k=1}^{N}e^{o_k}}}{\\partial o_j}$$\n\nFor any arbitrary output $i$ and input $j$. To do so, We'll be using the quotient rule of derivatives. The rule tells us that for a function $f(x) = \\frac{g(x)}{h(x)}$:\n\n$$f'(x) = \\frac{g'(x)h(x) - h'(x)g(x)}{[h(x)]^2}$$\n\nIn our case, we have:\n\n\\begin{align*}\ng &= e^{o_i} \\nonumber \\\\\nh &= \\sum_{k=1}^{K}e^{o_k} \\nonumber\n\\end{align*}\n\nIt's important to notice that no matter which $o_j$ we compute the derivative of $h$ for the output will always be $e^{o_j}$. Howewer, this is not the case for $g$. It's derivative will be $e^{o_j}$ only if $i = j$, because only then will it have the term $e^{o_j}$. Otherwise, the derivative is simply 0 (because it's simply taking the derivative of a constant).\n\nSo going back to using our quotient rule, we start with the $i = j$ case. In the following derivation we'll use the $\\Sigma$ (Sigma) sign to represent $\\sum_{k=1}^{K}e^{o_k}$ for simplicity and to prevent cluttering up the notation.\n\n\\begin{align*}\n\\frac{\\partial \\frac{e^{o_i}}{\\sum_{k = 1}^{N} e^{o_k}}}{\\partial o_j} \n&= \\frac{e^{o_i}\\Sigma-e^{o_j}e^{o_i}}{\\Sigma^2} \\nonumber \\\\\n&= \\frac{e^{o_i}}{\\Sigma}\\frac{\\Sigma - e^{o_j}}{\\Sigma} \\nonumber \\\\\n&= p_i(1 - p_j) \\nonumber \\\\\n&= p_i(1 - p_i) \\nonumber\n\\end{align*}\n\nThe reason we can perform the operation in the last line is because we're considering the scenario where $i = j$. Similarly we can do the case where $i \\neq j$.\n\n\\begin{align*}\n\\frac{\\partial \\frac{e^{o_i}}{\\sum_{k = 1}^{N} e^{o_k}}}{\\partial o_j} \n&= \\frac{0-e^{o_j}e^{o_i}}{\\Sigma^2} \\nonumber \\\\\n&= -\\frac{e^{o_j}}{\\Sigma}\\frac{e^{o_i}}{\\Sigma} \\nonumber \\\\\n&= -p_j p_i \\nonumber \\\\\n&= -p_i p_j \\nonumber\n\\end{align*}\n\nJust to sum it up, we now have:\n\n$$\\frac{\\partial p_i}{\\partial o_j} = p_i(1 - p_i),\\quad i = j$$\n\n$$\\frac{\\partial p_i}{\\partial o_j} = -p_i p_j,\\quad i \\neq j$$\n\nGiven this, we can tie this back to the original loss function $-\\sum_k^K y_k \\log p_k$ and compute its negative gradient.\n\n\\begin{align}\n\\frac{\\partial L}{\\partial o_i} \n&= -\\sum_k y_k\\frac{\\partial \\log p_k}{\\partial o_i} \\nonumber \\\\\n&= -\\sum_k y_k\\frac{1}{p_k}\\frac{\\partial p_k}{\\partial o_i} \\nonumber \\\\\n&= -y_i(1-p_i) - \\sum_{k \\neq i}y_k\\frac{1}{p_k}(-p_kp_i) \\nonumber \\\\\n&= -y_i(1 - p_i) + \\sum_{k \\neq i}y_k(p_i) \\nonumber \\\\\n&= -y_i + y_i p_i + \\sum_{k \\neq i}y_k(p_i) \\nonumber \\\\\n&= p_i\\left(\\sum_ky_k\\right) - y_i \\nonumber \\\\\n&= p_i - y_i \\nonumber\n\\end{align} \n\nRemember $\\sum_ky_k=1$ (as $y$ is a vector with only one non-zero element, which is $1$ when the indicating the observation belongs to the $k_{th}$ class. \n\nAfter a long journey, we now see, for every class $k$, the gradient is the difference between the associated dummy variable and the predicted probability of belonging to that class. This is essentially the \"residuals\" from the classification gradient boosting. Given this, we can now implement the algorithm, the overall process of training a regression tree has still not changed, only now we must deal with the dummy variables, $y_k$ and fit a regression tree on the negative gradient for each dummy variable.\n\n## Implementation\n\nFor the dataset, we'll still use the Wine Quality Data Set that was used for the regression task, except we now treat the quality of the wine (a scale of 1 ~ 10) as categorical instead of numeric.\n\n\n```python\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\n```\n\n\n```python\nclass GBMClass:\n    \"\"\"\n    Classification gradient boosting machine using scikit learn's \n    decision tree as the base tree\n    \n    Parameters\n    ----------\n    n_estimators: int\n        number of trees to train\n        \n    learning_rate: float\n        learning rate, some calls it shrinkage, \n        shrinks the contribution of each tree\n        to prevent overfitting\n        \n    max_depth: int\n        controls how deep to grow the tree;\n        this is more of a decision tree parameter,\n        it is tune here to make later comparison fair\n    \n    all the other parameters for a decision tree like\n    max_features or min_sample_split also applies to GBM, \n    it is just not used here as that is more\n    related to a single decision tree\n    \"\"\"\n\n    def __init__(self, n_estimators, learning_rate, max_depth):\n        self.max_depth = max_depth\n        self.n_estimators = n_estimators\n        self.learning_rate = learning_rate\n\n    def fit(self, X, y):\n        # encode labels with value between 0 and n_classes - 1,\n        # so we can easily one-hot encode them\n        self.le = LabelEncoder()\n        labels = self.le.fit_transform(y)\n        Y = self._to_categorical(labels)\n        del labels\n        \n        # the predicted probability starts out with \n        # a value that's uniform over all classes;\n        # then we compute the residuals (negative gradient),\n        # which is the difference between the predicted\n        # probability and the class label\n        y_proba = np.full(Y.shape, 1 / Y.shape[1]) \n        residuals = Y - y_proba\n        \n        # train a base decision tree on the residuals\n        # for every single class, hence we end up with\n        # n_estimators * n_classes base tree models\n        self.estimators = []\n        for i in range(self.n_estimators):\n            for j in range(self.n_classes): \n                tree = DecisionTreeRegressor(max_depth = self.max_depth)\n                tree.fit(X, residuals[:, j])   \n                y_pred = tree.predict(X)\n                self.estimators.append(tree)  \n                residuals[:, j] -= self.learning_rate * y_pred\n                \n        return self\n            \n    def _to_categorical(self, y):\n        \"\"\"one hot encode class vector y\"\"\"\n        self.n_classes = np.amax(y) + 1\n        Y = np.zeros((y.shape[0], self.n_classes))\n        for i in range(y.shape[0]):\n            Y[i, y[i]] = 1.0\n\n        return Y\n    \n    def predict(self, X):\n        # after predicting the class remember to\n        # transform it back to the actual class label\n        y_prob = self.predict_proba(X)\n        y_pred = np.argmax(y_prob, axis = 1)\n        y_pred = self.le.inverse_transform(y_pred)\n        return y_pred\n    \n    def predict_proba(self, X):\n        # add up raw score for every class and convert\n        # it to probability using softmax\n        y_raw = np.zeros((X.shape[0], self.n_classes))\n\n        # obtain the tree for each class and add up the prediction\n        for c in range(self.n_classes):\n            class_tree = self.estimators[c::self.n_classes]\n            for tree in class_tree:\n                y_raw[:, c] += self.learning_rate * tree.predict(X)\n        \n        y_proba = self._compute_softmax(y_raw)\n        return y_proba\n    \n    def _compute_softmax(self, z):\n        \"\"\"\n        compute the softmax of matrix z in a numerically stable way,\n        by substracting each row with the max of each row\n        \"\"\"\n        shift_z = z - np.amax(z, axis = 1, keepdims = 1)\n        exp_z = np.exp(shift_z)\n        softmax = exp_z / np.sum(exp_z, axis = 1, keepdims = 1)\n        return softmax    \n```\n\n\n```python\n# compare the results between a single decision tree,\n# gradient boosting, the higher the accuracy, the better\ntree = DecisionTreeClassifier(max_depth = 6)\ntree.fit(X_train, y_train) \ntree_y_pred = tree.predict(X_test)\nprint('tree: ', accuracy_score(y_test, tree_y_pred))\n\n# gradient boosting for 150 trees and learning rate of 0.2\n# unlike random forest, gradient boosting's base tree can be shallower\n# meaning that there depth can be smaller\ngbm_class = GBMClass(n_estimators = 150, learning_rate = 0.2, max_depth = 3)\ngbm_class.fit(X_train, y_train)\ngbm_class_y_pred = gbm_class.predict(X_test)\nprint('gbm: ', accuracy_score(y_test, gbm_class_y_pred))\n\n# library to confirm results are comparable\ngbm = GradientBoostingClassifier(n_estimators = 150, learning_rate = 0.2, max_depth = 3)\ngbm.fit(X_train, y_train)\ngbm_y_pred = gbm.predict(X_test)\nprint('gbm library: ', accuracy_score(y_test, gbm_y_pred))\n```\n\n    tree:  0.54387755102\n    gbm:  0.601020408163\n    gbm library:  0.616326530612\n\n\n## Understanding Model Complexity\n\nIn the following section, we generate a Sinoide function + random gaussian noise, with 80 training samples (blue points) and 20 test samples (red points).\n\n\n```python\ndef ground_truth(x):\n    \"\"\"Ground truth -- function to approximate\"\"\"\n    return x * np.sin(x) + np.sin(2 * x)\n\ndef gen_data(low, high, n_samples):\n    \"\"\"generate training and testing data from the ground truth function\"\"\"\n    np.random.seed(15)\n    X = np.random.uniform(low, high, size = n_samples)\n    \n    # generate the response from the ground truth function and add\n    # some random noise to it\n    y = ground_truth(X) + np.random.normal(scale = 2, size = n_samples)\n    X_train, X_test, y_train, y_test = train_test_split(\n        X, y, test_size = 0.2, random_state = 3)\n\n    return X_train, X_test, y_train, y_test\n\ndef plot_data(x_plot, X_train, X_test, y_train, y_test):\n    \"\"\"plot training and testing data\"\"\"\n    s = 20\n    alpha = 0.4\n    plt.plot(x_plot, ground_truth(x_plot), alpha = alpha, label = 'ground truth')\n    plt.scatter(X_train, y_train, s = s, alpha = alpha)\n    plt.scatter(X_test, y_test, s = s, alpha = alpha, color = 'red')\n    plt.xlim(( 0, 10 ))\n    plt.ylabel('y')\n    plt.xlabel('x')\n    plt.legend(loc = 'upper left')\n    plt.show()\n```\n\n\n```python\nlow = 0\nhigh = 10\nx_plot = np.linspace(low, high, 500)\nX_train, X_test, y_train, y_test = gen_data(low = low, high = high, n_samples = 100)\nplot_data(x_plot, X_train, X_test, y_train, y_test)\n```\n\nRecall that in a single regression tree, we can use the `max_depth` parameter to control how deep to grow the tree and the deeper the tree the more variance can be explained.\n\n\n```python\n# when using scikit-learn, the training data has to be\n# a 2d-array even if it only has 1 features\ntree1 = DecisionTreeRegressor(max_depth = 1)\ntree1.fit(X_train[:, np.newaxis], y_train)\ntree2 = DecisionTreeRegressor(max_depth = 3)\ntree2.fit(X_train[:, np.newaxis], y_train)\n\nplt.plot(x_plot, tree1.predict(x_plot[:, np.newaxis]),\n         label = 'RT max_depth=1', color = 'g', alpha = 0.9, linewidth = 2)\nplt.plot(x_plot, tree2.predict(x_plot[:, np.newaxis]),\n         label = 'RT max_depth=3', color = 'g', alpha = 0.7, linewidth = 1)\nplot_data(x_plot, X_train, X_test, y_train, y_test)\n```\n\nThe plot above shows that the decision boundaries made by decision trees are always perpendicular to $x$ and $y$ axis (due to the fact that they consists of nested if-else statements). Let's see what happens when we use gradient boosting without tuning the parameters (by specifying a fix `max_depth`).\n\n\n```python\ngbm = GradientBoostingRegressor(n_estimators = 300, max_depth = 6, learning_rate = 0.1)\ngbm.fit(X_train[:, np.newaxis], y_train)\n\nplt.plot(x_plot, gbm.predict(x_plot[:, np.newaxis]),\n         label = 'GBM max_depth=6', color = 'r', alpha = 0.9, linewidth = 2)\nplot_data(x_plot, X_train, X_test, y_train, y_test)\n```\n\nHopefully, it should be clear that compared with decision trees, gradient boosting machine is far more susceptible to overfitting the training data, hence it is common to tune parameters including `max_depth`, `max_features`, `min_samples_leaf`, `subsample` (explained below) to reduce the overfitting phenomenon from  occurring.\n\nThe parameter `subsample` (technically called *stochastic gradient boosting*) borrows some idea from bagging techniques. What it does is: while iterating through each individual tree building process, it randomly select a fraction of the training data. Then the residuals and models in the remaining steps of the current iteration are based only on that sample of data. It turns out that this simple modification improved the predictive accuracy of boosting while also reducing the required computational resources (of course, this is based on the fact that you have enough observations to subsample).\n\nThe following section tunes the commonly tuned parameter and find the best one and draws the decision boundary. The resulting plot should be self-explanatory.\n\n\n```python\nparam_grid = {\n    'max_depth': [4, 6],\n    'min_samples_leaf': [3, 5, 8],\n    'subsample': [0.9, 1]\n    # 'max_features': [1.0, 0.3, 0.1] # not possible in this example (there's only 1)\n}\ngs_gbm = GridSearchCV(gbm, param_grid, scoring = 'neg_mean_squared_error', n_jobs = 4)\ngs_gbm.fit(X_train[:, np.newaxis], y_train)\nprint('Best hyperparameters: %r' % gs_gbm.best_params_)\n\nplt.plot(x_plot, gs_gbm.predict(x_plot[:, np.newaxis]),\n         label = 'GBM tuned', color = 'r', alpha = 0.9, linewidth = 2)\nplot_data(x_plot, X_train, X_test, y_train, y_test)\n```\n\n# Reference\n\n- [Slide: Gradent boosting](http://eric.univ-lyon2.fr/~ricco/cours/slides/en/gradient_boosting.pdf)\n- [Slide: A gentle introduction to gradient boosting](http://www.ccs.neu.edu/home/vip/teach/MLcourse/4_boosting/slides/gradient_boosting.pdf)\n- [Blog: The Softmax function and its derivative](http://eli.thegreenplace.net/2016/the-softmax-function-and-its-derivative/)\n- [Notebook: Regression Trees and Rule-Based Models](http://nbviewer.jupyter.org/github/leig/Applied-Predictive-Modeling-with-Python/blob/master/notebooks/Chapter%208.ipynb)\n- [Notebook: Gradient Boosted Regression Trees in scikit-learn](http://nbviewer.jupyter.org/github/pprett/pydata-gbrt-tutorial/blob/master/gbrt-tutorial.ipynb)\n- [StackExchange: Derivative of Softmax loss function](http://math.stackexchange.com/questions/945871/derivative-of-softmax-loss-function)\n- [StackExchange: How are individual trees added together in boosted regression tree?](http://stats.stackexchange.com/questions/135378/how-are-individual-trees-added-together-in-boosted-regression-tree)\n- [Stackoverflow: How to access weighting of indiviual decision trees in xgboost?](https://stackoverflow.com/questions/32950607/how-to-access-weighting-of-indiviual-decision-trees-in-xgboost/34331573#34331573)\n", "meta": {"hexsha": "be08bd57fea90b75b65ef0a1cefca30cd95f457f", "size": 512728, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "trees/gbm/gbm.ipynb", "max_stars_repo_name": "DEVESHTARASIA/machine-learning", "max_stars_repo_head_hexsha": "ca8a3a108829dca2b883f9196b8dfbb7c280861d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trees/gbm/gbm.ipynb", "max_issues_repo_name": "DEVESHTARASIA/machine-learning", "max_issues_repo_head_hexsha": "ca8a3a108829dca2b883f9196b8dfbb7c280861d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trees/gbm/gbm.ipynb", "max_forks_repo_name": "DEVESHTARASIA/machine-learning", "max_forks_repo_head_hexsha": "ca8a3a108829dca2b883f9196b8dfbb7c280861d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 367.546953405, "max_line_length": 125530, "alphanum_fraction": 0.9086396686, "converted": true, "num_tokens": 10680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.115960721309117, "lm_q2_score": 0.07159119845413339, "lm_q1q2_score": 0.00830176701212545}}
{"text": "# Pytex\n\nUsage examples of pytex package.\n\n\n```python\nimport pytex\n```\n\nCreate a document object and specify the configuration.\n\n\n```python\ndoc = pytex.Document(\n    filename=\"example\",\n    institution=\"Institution Name\",\n    mayor_heading=\"Mayor Heading\",\n    minor_heading=\"Minor Heading\",\n    title=\"Probably a very long title\",\n    author=\"Author's name\",\n    supervisor=\"Supervisor's name\"\n)\n```\n\nAdd a table of contents. \n\n\n```python\ndoc.add_table_of_contents()\n```\n\nYou can add multiple elements secuentially. \n\n\n```python\ndoc.add_section(\"First Section's Title\")\n\ndoc.add_paragraph(\"\"\"\nFirst test paragraph. Lorem ipsum dolor sit amet, consectetur adipiscing elit, \nsed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \nExcepteur sint occaecat cupidatat non proident, \nsunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, \nsed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n\"\"\")\n\n\ndoc.add_paragraph(\"\"\"\nSecond test paragraph. Lorem ipsum dolor sit amet, consectetur adipiscing elit, \nsed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \nExcepteur sint occaecat cupidatat non proident, \nsunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, \nsed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n\"\"\")\n\ndoc.add_paragraph(r\"\"\"\nThis is the black-scholes equation:\n\"\"\")\n\ndoc.add_equation(\n    eq=r\"\\frac{\\partial V}{\\partial t} + \\sigma^2 S^2 \\frac{1}{2} \\frac{\\partial^2V}{\\partial S^2} + rS\\frac{\\partial V}{\\partial S} - rV = 0\",\n    label=\"bs\")\n\ndoc.add_paragraph(r\"\"\"References work! See equation \\ref{bs}.\"\"\")\n\n\ndoc.add_paragraph(\"\"\"\nThese are some items:\n\"\"\")\n\ndoc.add_items([\n        \"item1\",\n        \"item2\",\n        \"item3\"\n    ])\n\n\ndoc.add_paragraph(\"\"\"\nNow let's code some stuff.\n\"\"\")\n\ndoc.add_code(\n    code_string=\"\"\"\n    import pytex\n    import math\n    doc = pytex.Document(filename=\"file\")\n    doc.add_section(\"pytex is great\")\n    doc.add_paragraph(\"The number pi is: {}\".format(math.pi))\n    for i in range(10):\n        doc.add_section(\"Section: \" + str(i+2))\n    \"\"\")\n\ndoc.add_paragraph(\"\"\"\nGreat!\n\"\"\")\n\n```\n\nTake a look to the tex file.\n\n\n```python\nprint(doc.to_tex())\n```\n\n    \n                \\documentclass[11pt]{article}\n                \\usepackage[utf8]{inputenc}\n                \\usepackage[T1]{fontenc}\n                \\usepackage{amsmath}\n                \\usepackage{fancyhdr}\n                \\usepackage{listings}\n                \\usepackage{color}\n    \n    \n                \\definecolor{codegreen}{rgb}{0,0.6,0}\n                \\definecolor{codegray}{rgb}{0.5,0.5,0.5}\n                \\definecolor{codepurple}{rgb}{0.58,0,0.82}\n                \\definecolor{backcolour}{rgb}{0.95,0.95,0.92}\n    \n    \n                \\lstdefinestyle{mystyle}{\n                    backgroundcolor=\\color{backcolour},   \n                    commentstyle=\\color{codegreen},\n                    keywordstyle=\\color{magenta},\n                    numberstyle=\\tiny\\color{codegray},\n                    stringstyle=\\color{codepurple},\n                    basicstyle=\\footnotesize,\n                    breakatwhitespace=false,         \n                    breaklines=true,                 \n                    captionpos=b,                    \n                    keepspaces=true,                 \n                    numbers=left,                    \n                    numbersep=5pt,                  \n                    showspaces=false,                \n                    showstringspaces=false,\n                    showtabs=false,                  \n                    tabsize=2\n                }\n     \n                \\lstset{style=mystyle}\n    \n    \n                \\parindent 0em\n                \\parskip 2ex\n                \\pagestyle{fancy}\n                \\setlength{\\textfloatsep}{5pt}\n                \\begin{document}\n            \n    \n                \\begin{titlepage}\n                \\newcommand{\\HRule}{\\rule{\\linewidth}{0.5mm}}\n                \\center\n    \n                \\textsc{\\LARGE Institution Name}\\\\[1.5cm]\n                \\textsc{\\Large Mayor Heading}\\\\[0.5cm]\n                \\textsc{\\large Minor Heading}\\\\[0.5cm]\n    \n    \n                \\HRule\\\\[0.4cm]\n                {\\huge\\bfseries Probably a very long title}\\\\[0.4cm]\n                \\HRule\\\\[1.5cm]\n    \n                \\begin{minipage}{0.4\\textwidth}\n                    \\begin{flushleft}\n                    \\large\n                    \\textit{Author}\\\\\n                    Author's name\n                    \\end{flushleft}\n                \\end{minipage}\n                ~\n                \\begin{minipage}{0.4\\textwidth}\n                    \\begin{flushright}\n                    \\large\n                    \\textit{Supervisor}\\\\\n                    Supervisor's name\n                    \\end{flushright}\n                \\end{minipage}\n    \n                \\vfill\\vfill\\vfill\n                {\\large\\today}\n                \n                \\vfill\n                \\end{titlepage}\n                \n            \n    \\tableofcontents\\newpage\n    \\section{First Section's Title}\n    \n    First test paragraph. Lorem ipsum dolor sit amet, consectetur adipiscing elit, \n    sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \n    Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \n    Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \n    Excepteur sint occaecat cupidatat non proident, \n    sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, \n    sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \n    Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n    \n    \n    Second test paragraph. Lorem ipsum dolor sit amet, consectetur adipiscing elit, \n    sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \n    Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \n    Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \n    Excepteur sint occaecat cupidatat non proident, \n    sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, \n    sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \n    Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n    \n    \n    This is the black-scholes equation:\n    \n    \n                \\begin{equation} \\label{bs}\n                \\frac{\\partial V}{\\partial t} + \\sigma^2 S^2 \\frac{1}{2} \\frac{\\partial^2V}{\\partial S^2} + rS\\frac{\\partial V}{\\partial S} - rV = 0\n                \\end{equation}\n            \n    References work! See equation \\ref{bs}.\n    \n    These are some items:\n    \n    \n                \\begin{itemize}\n                \\item item1\\item item2\\item item3\n                \\end{itemize}  \n            \n    \n    Now let's code some stuff.\n    \n    \n                \\begin{lstlisting}[language=Python]\n                \n        import pytex\n        import math\n        doc = pytex.Document(filename=\"file\")\n        doc.add_section(\"pytex is great\")\n        doc.add_paragraph(\"The number pi is: {}\".format(math.pi))\n        for i in range(10):\n            doc.add_section(\"Section: \" + str(i+2))\n        \n                \\end{lstlisting}\n            \n    \n    Great!\n    \n    \\end{document}\n\n\nCompile to pdf file.\n\n\n```python\ndoc.compile()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "57a1ffe6dca8652b53c65de8966e3203696b97ee", "size": 12057, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples.ipynb", "max_stars_repo_name": "RHDZMOTA/pytex", "max_stars_repo_head_hexsha": "c0f7cb3a018f6158670e3789f91ed18fea8b91dc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples.ipynb", "max_issues_repo_name": "RHDZMOTA/pytex", "max_issues_repo_head_hexsha": "c0f7cb3a018f6158670e3789f91ed18fea8b91dc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples.ipynb", "max_forks_repo_name": "RHDZMOTA/pytex", "max_forks_repo_head_hexsha": "c0f7cb3a018f6158670e3789f91ed18fea8b91dc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0328767123, "max_line_length": 166, "alphanum_fraction": 0.4914157751, "converted": true, "num_tokens": 1885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14804720179063333, "lm_q2_score": 0.05582314309810017, "lm_q1q2_score": 0.008264460130831836}}
{"text": "# Rich Output\n\nIn Python, objects can declare their textual representation using the `__repr__` method.  IPython expands on this idea and allows objects to declare other, rich representations including:\n\n* HTML\n* JSON\n* PNG\n* JPEG\n* SVG\n* LaTeX\n\nA single object can declare some or all of these representations; all are handled by IPython's *display system*. This Notebook shows how you can use this display system to incorporate a broad range of content into your Notebooks.\n\n## Basic display imports\n\nThe `display` function is a general purpose tool for displaying different representations of objects. Think of it as `print` for these rich representations.\n\n\n```python\nfrom IPython.display import display\n```\n\nA few points:\n\n* Calling `display` on an object will send **all** possible representations to the Notebook.\n* These representations are stored in the Notebook document.\n* In general the Notebook will use the richest available representation.\n\nIf you want to display a particular representation, there are specific functions for that:\n\n\n```python\nfrom IPython.display import (\n    display_pretty, display_html, display_jpeg,\n    display_png, display_json, display_latex, display_svg\n)\n```\n\n## Images\n\nTo work with images (JPEG, PNG) use the `Image` class.\n\n\n```python\nfrom IPython.display import Image\n```\n\n\n```python\ni = Image(filename='../images/ipython_logo.png')\n```\n\nReturning an `Image` object from an expression will automatically display it:\n\n\n```python\ni\n```\n\nOr you can pass an object with a rich representation to `display`:\n\n\n```python\ndisplay(i)\n```\n\nAn image can also be displayed from raw data or a URL.\n\n\n```python\nImage(url='http://python.org/images/python-logo.gif')\n```\n\n\n\n\n\n\n\n\nSVG images are also supported out of the box.\n\n\n```python\nfrom IPython.display import SVG\nSVG(filename='../images/python_logo.svg')\n```\n\n\n\n\n    \n\n    \n\n\n\n### Embedded vs non-embedded Images\n\nBy default, image data is embedded in the notebook document so that the images can be viewed offline. However it is also possible to tell the `Image` class to only store a *link* to the image. Let's see how this works using a webcam at Berkeley.\n\n\n```python\nfrom IPython.display import Image\nimg_url = 'http://www.lawrencehallofscience.org/static/scienceview/scienceview.berkeley.edu/html/view/view_assets/images/newview.jpg'\n\n# by default Image data are embedded\nEmbed      = Image(img_url)\n\n# if kwarg `url` is given, the embedding is assumed to be false\nSoftLinked = Image(url=img_url)\n\n# In each case, embed can be specified explicitly with the `embed` kwarg\n# ForceEmbed = Image(url=img_url, embed=True)\n```\n\nHere is the embedded version. Note that this image was pulled from the webcam when this code cell was originally run and stored in the Notebook. Unless we rerun this cell, this is not todays image.\n\n\n```python\nEmbed\n```\n\n\n\n\n    \n\n    \n\n\n\nHere is today's image from same webcam at Berkeley, (refreshed every minutes, if you reload the notebook), visible only with an active internet connection, that should be different from the previous one. Notebooks saved with this kind of image will be smaller and always reflect the current version of the source, but the image won't display offline.\n\n\n```python\nSoftLinked\n```\n\n\n\n\n\n\n\n\nOf course, if you re-run this Notebook, the two images will be the same again.\n\n## HTML\n\nPython objects can declare HTML representations that will be displayed in the Notebook. If you have some HTML you want to display, simply use the `HTML` class.\n\n\n```python\nfrom IPython.display import HTML\n```\n\n\n```python\ns = \"\"\"<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\"\"\"\n```\n\n\n```python\nh = HTML(s)\n```\n\n\n```python\ndisplay(h)\n```\n\n\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n\n\nYou can also use the `%%html` cell magic to accomplish the same thing.\n\n\n```python\n%%html\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n```\n\n\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n\n\n## JavaScript\n\nThe Notebook also enables objects to declare a JavaScript representation. At first, this may seem odd as  output is inherently visual and JavaScript is a programming language. However, this opens the door for rich output that leverages the full power of JavaScript and associated libraries such as [d3.js](http://d3js.org) for output.\n\n\n```python\nfrom IPython.display import Javascript\n```\n\nPass a string of JavaScript source code to the `JavaScript` object and then display it.\n\n\n```python\njs = Javascript('alert(\"hi\")');\n```\n\n\n```python\ndisplay(js)\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\nThe same thing can be accomplished using the `%%javascript` cell magic:\n\n\n```javascript\n%%javascript\n\nalert(\"hi\");\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\nHere is a more complicated example that loads `d3.js` from a CDN, uses the `%%html` magic to load CSS styles onto the page and then runs ones of the `d3.js` examples.\n\n\n```python\nJavascript(\n    \"\"\"$.getScript('//cdnjs.cloudflare.com/ajax/libs/d3/3.2.2/d3.v3.min.js')\"\"\"\n)\n```\n\n\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n```python\n%%html\n<style type=\"text/css\">\n\ncircle {\n  fill: rgb(31, 119, 180);\n  fill-opacity: .25;\n  stroke: rgb(31, 119, 180);\n  stroke-width: 1px;\n}\n\n.leaf circle {\n  fill: #ff7f0e;\n  fill-opacity: 1;\n}\n\ntext {\n  font: 10px sans-serif;\n}\n\n</style>\n```\n\n\n<style type=\"text/css\">\n\ncircle {\n  fill: rgb(31, 119, 180);\n  fill-opacity: .25;\n  stroke: rgb(31, 119, 180);\n  stroke-width: 1px;\n}\n\n.leaf circle {\n  fill: #ff7f0e;\n  fill-opacity: 1;\n}\n\ntext {\n  font: 10px sans-serif;\n}\n\n</style>\n\n\n\n```javascript\n%%javascript\n\n// element is the jQuery element we will append to\nvar e = element.get(0);\n    \nvar diameter = 600,\n    format = d3.format(\",d\");\n\nvar pack = d3.layout.pack()\n    .size([diameter - 4, diameter - 4])\n    .value(function(d) { return d.size; });\n\nvar svg = d3.select(e).append(\"svg\")\n    .attr(\"width\", diameter)\n    .attr(\"height\", diameter)\n  .append(\"g\")\n    .attr(\"transform\", \"translate(2,2)\");\n\nd3.json(\"data/flare.json\", function(error, root) {\n  var node = svg.datum(root).selectAll(\".node\")\n      .data(pack.nodes)\n    .enter().append(\"g\")\n      .attr(\"class\", function(d) { return d.children ? \"node\" : \"leaf node\"; })\n      .attr(\"transform\", function(d) { return \"translate(\" + d.x + \",\" + d.y + \")\"; });\n\n  node.append(\"title\")\n      .text(function(d) { return d.name + (d.children ? \"\" : \": \" + format(d.size)); });\n\n  node.append(\"circle\")\n      .attr(\"r\", function(d) { return d.r; });\n\n  node.filter(function(d) { return !d.children; }).append(\"text\")\n      .attr(\"dy\", \".3em\")\n      .style(\"text-anchor\", \"middle\")\n      .text(function(d) { return d.name.substring(0, d.r / 3); });\n});\n\nd3.select(self.frameElement).style(\"height\", diameter + \"px\");\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n## LaTeX\n\nThe IPython display system also has builtin support for the display of mathematical expressions typeset in LaTeX, which is rendered in the browser using [MathJax](http://mathjax.org).\n\nYou can pass raw LaTeX test as a string to the `Math` object:\n\n\n```python\nfrom IPython.display import Math\nMath(r'F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx')\n```\n\n\n\n\n$$F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx$$\n\n\n\nWith the `Latex` class, you have to include the delimiters yourself.  This allows you to use other LaTeX modes such as `eqnarray`:\n\n\n```python\nfrom IPython.display import Latex\nLatex(r\"\"\"\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\"\"\")\n```\n\n\n\n\n\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\n\n\n\nOr you can enter LaTeX directly with the `%%latex` cell magic:\n\n\n```latex\n%%latex\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n```\n\n\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n\n\n## Audio\n\nIPython makes it easy to work with sounds interactively. The `Audio` display class allows you to create an audio control that is embedded in the Notebook. The interface is analogous to the interface of the `Image` display class. All audio formats supported by the browser can be used. Note that no single format is presently supported in all browsers.\n\n\n```python\nfrom IPython.display import Audio\nAudio(url=\"http://www.nch.com.au/acm/8k16bitpcm.wav\")\n```\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"http://www.nch.com.au/acm/8k16bitpcm.wav\" type=\"audio/x-wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\nA NumPy array can be auralized automatically. The `Audio` class normalizes and encodes the data and embeds the resulting audio in the Notebook.\n\nFor instance, when two sine waves with almost the same frequency are superimposed a phenomena known as [beats](https://en.wikipedia.org/wiki/Beat_%28acoustics%29) occur. This can be auralised as follows:\n\n\n```python\nimport numpy as np\nmax_time = 3\nf1 = 220.0\nf2 = 224.0\nrate = 8000.0\nL = 3\ntimes = np.linspace(0,L,rate*L)\nsignal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times)\n\nAudio(data=signal, rate=rate)\n```\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"data:audio/wav;base64,UklGRqS7AABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YYC7AAAAADUWvSvyPzdS/WHKbjt4Bn7+fxV+WXj3bjhifVJDQBYslBZiAC/qpdRswCGuU557kf2HJIIcgPWBoIfykKKdTa15v5rTEuk7/2kV8CopP3ZRSmEqbrJ3mH2vf+Z9TXgNb3Bi11K9QK0sQxcmAQPrhNVPwQOvLZ9IkreIxYKggFiC34cLkZOdFq0bvxbTbeh4/o0UASosPnNQSGAwbcd2w3z2fk9923fGblZi7FL/QBwt3hfoAefrg9ZlwiawVqBuk9OJzoOOgSSDg4iAkdadJa31vrvS3ue5/aIT8Sj/PDBP+F7da3t1h3vUfU98BncibuhhuVIJQWQtYRilAtjso9eqw4mxzKHtlE+LPYXkgleEiolTkm6ee60Hv4jSZuf//KsSwyeiO65NXF0zas9z5nlJfOh6zXUhbSdhPlLaQIItzBhbA9Xt39gexSmzjqPCliuNEYeihPKF9YqDk1mfGq5Uv3/SCOdN/KkReCYYOvBLd1szaMVx4HdYehp5MXTDaxNgfFFwQHUtHRkJBNvuN9q9xgW1l6XsmGOPR4nGhvKHwowPlZegAa/bv6LSxOak+58QFCVkOPhJSVnhZV9veXUCeOh2MnIIaqpecVDLPzwtUxmsBOjvp9uFyBm356dmm/aR3otOiVeK8Y73limiMLCewPHSneYG+48PmSOINslH11Y+Y6BssnJJdVF002/yZ+5cHU/rPtYsbBlEBfvwLd11ymO5e6ownuGU1I44jB+NgZE6mQ+kqLGcwW7Tk+Z1+noOCCKGNGVFI1ROYIppj28vcllxFG2CZeBagU3PPUMsZxnOBRHyyN6IzOC7T61GoSGYJZKBj0aQbpTXm0WmZ7PWwhjUp+by+WMNZCBhMtBCMFEUXSFmEWy4bgJu+Gm6YoFYnkt3PIIrQxlJBinzdOC9zo2+YLCkpLKbz5Unk8yTuJfLns2obrVMxPDU2+Z/+UwMsB4dMAxAAU6TWWdiPGjlak9qgWaaX9FVdEnjOpIq/xi0Bj/0L+IQ0WfBq7NHqJKfzpkml6yXXJsVoqSru7f9xffVL+ce+TYL7hy8LR09m0rOVWFeFGS6ZkJmsmImXNNSBEcVOXQpmhgMB1P19+N/02rELbctrL2jH557m+SbVp+zpciuTrroxy3XpefP+CQKIRtAKwY6/0bKURNanF87YuBhjV5gWIlPUEQMNycoFBhRB2P2yeUG1pTH4bpPsC+ovaIioHGgpKOhqTiyJL0OypHYPOiU+BgJSxmuKMo2M0OJTX9V2FpsXStdF1pKVPVLWUHKNKsmbBeCB2v3o+ej2OHKxb6stOOspacYpU6lQ6jdrfG1PMBtzCTa9ehu+BMIbhcHJm0zOT8RSatQzVVRWCdYUVXoTxlIID5PMgIloRadB2z4gulT203O08I+udax0qxXqneqLq1ksvC5k8MDz+Tb0ele+BcHjRVPI/MvFztmRJtLf1DvUtlSQVA9S/dDqTqeLysjtBWiB2P5ZOsS3tXRCccBvgK3P7Lcr+mvYrIytzK+KcfP0dHdz+pl+CYGqxOJIF4szzaMP1RG80pJTUVN6kpNRpQ/9ja3LCghpRSPB076Ru3e4HTVYcvxwmO86beitZ6127dEvLXC+srQ1Orf8OuE+EIFyRG5HbQoZzKIOtpALkVkR29HUUUbQfI6CDOcKfkecxNkByv7Ju+z4yjZ2M8JyPXByb2ju5K7lL2VwXXHA88E2C7iM+27+GsE6w/gGvck4i1eNTI7ND9HQV1BeT+sOxU25C5QJqAcHxIgB/r7AvGO5u3catREzbHH28PbwcHBiMMhx27MQ9No25zkmO4L+aQDEg4DGCshRSkTMGI1DDn2OhQ7aTkENgExiyrVIh4aqhDEBrr82PJt6b/gEdmd0pTNGcpFyCPIs8nlzJ3RtNf63jLnHfB0+e0CQAwkFVUdlCSsKm8vujJ2NJk0JTMnMLkrASYtH3QXEw9NBmj9pvRL7Jrkyt0Q2JfTfdDazrbOENDa0v3WVdy34u/pxPH3+UgCeApGEncZ1B8uJV0pQyzNLfEtsSwaKkImSiFbG6UUXQ2+BQP+aPYo73rokeKY3bXZA9eV1XLVmNb92IrcIeGd5tDsifOT+rYBuwhsD5UVCRueHzMjryUBJyInFCbiI6AgaRxiF7IRiAsVBYz+Hvj/8VzsYOcw4+rfpd1w3FLcSN1I30DiFeap6tTvbvVJ+zcBDAeZDLQRNxYAGvUcAh8YIDIgUx+FHdgaYxdEE54OlQlSBAD/xvnO9DzwNOzS6C/mXeRm41DjGeS25RroLevX7vjyb/cY/M0AbAXPCdYNYhFbFKoWQRgXGScZdBgHF+0UOxIGD2oLhgd3A2D/XvuS9xf0CPF67n/sJOtx6mfqBetD7BPuZfAl8zr2jPkA/XgA3AMRB/8JjwyxDlYQdBEEEgYSfBFuEOcO9QyqChoIWwWDAqr/5PxI+un32PUj9NXy9vGK8ZHxB/Ln8ib0uPWO95j5xPsA/jkAYAJiBDIGwwcKCQAKnwrmCtUKcQq/CcgIlQc0BrAEFwN3Ad7/V/7v/K/7n/rI+Sv5zPis+Mf4Gfme+U/6IvsQ/A79FP4Y/xAA9wDFAXQCAQNpA6sDyAPCA5wDWgMBA5cCIQKnAS4BvABUAPz/tv+D/2X/W/9j/3z/ov/Q/wIANABiAIcAngClAJkAeQBFAP7/pP87/8j+Tv7V/WD99/yg/GD8PPw5/Fn8nvwJ/Zn9S/4c/wMA/gACAgcDBQTxBMEFbgbwBj4HVAcuB8oGKQZMBTgE9QKJAQAAZv7G/C/7rflP+CH3L/aD9Sb1HfVr9RL2Dvdc+PL5x/vN/fb/MAJrBJUGmwhsCvgLLw0HDnQOcQ78DRMNvQsACucHggXiAhoAQP1p+q33IvXe8vXwd+9z7vXtA+6f7sjvd/Gj8zz2Mflq/NH/SgO8BgoKGg3RDxkS3hMOFZ4VhxXFFF0TVRG8DqMLIAhOBEkAMvwl+EX0sfCG7eDq1Oh259Pm9ObZ54Dp3+vk7nzyjPb1+pf/TATyCGQNfBEbFSAYdBoAHLYcjhyFG6EZ7RZ8E2cPzArMBY4APPv99fvwXuxM6OfkTOKR4Mbf9t8h4UHjSeYj6rTu2vNv+Uf/NQUNC58QvxVEGgge7CDXIrYjgSM1ItofgBw9GDITgw1bB+kAYPrx88/tLOg04xHf5NvK2dXYD9l72g/du+Bk5ejqHvHY9+L+BAYKDboT4BlKH8wjQieMKZgqWSrPKAMmCCL6HP8WQhD4CFgBnvkD8sbqHuRC3mHZotUn0wTSRtLt0/DWOduq4BvnW+409mn+ugboDrIW2h0oJGgpby0cMFYxEjFPLxcsgSevIcoaCBOjCtsB9fg18ODnOOB52dvTi8+tzFrLoMt+zenQydX821LjlOuE9N39VQemEIUZrCHaKNYubzN+Nuo3pTetNRAy5ixWJpEe0RVYDHECZ/iH7iDlfNze1IXOpMlixt3EIsUyxwDLcNBc147fyujJ8j791wdDEjEcUSVdLRM0PDmwPFA+DD7lO+k3MjLtKk8imhgXDhgD8/f77Iji7dh10GPJ8cNLwJG+0r4PwTnFMsvP0tbbAuYG8Y78Pgi+E7QeySitMRo50z6rQoFEQ0TyQZw9YTdvLwImYRveD9EDmPeR6xrgjtU/zHjEd75tuny4trgau5q/FcZazivYPuM97837jAgXFQ0hDyzHNec9L0RrSHhKQ0rNRyVDbTzXM6QpIh6pEZgEV/dK6tfdYdJByMm/O7nNtKSy0rJatSi6HMEAypLUgOBw7f76wAhNFjojIi+oOXdCSknqTTBQCFByTX5IUUEhODMt2yB3E24FL/cl6cDbaM9+xFm7QbRwrw2tLa3Sr+m0TbzGxQ7Rzd2i6yL63AhgFzslADJNPcdGIk4lU6VVjVXcUqNNCkZJPKswiCNGFVEGH/ck6NbZpcz4wCu3jK9ZqrunyqeHquCvrLexwaPNJtvU6Tr54AhPGA0nqDS0QNJKs1IXWNJazVoFWI9SkkpLQAg0JyYSFz8HJ/dH5xvYGsqxvUKzIKuNpbSir6J/pRKrPbPDvVTKkNgI6Ef4zAgbGbEoFzfaQ5dO+Va8XLJfw1/qXD1X5k4jREc3tSjbGDYIRveN5o7Wx8esuqKvAacPofud352+oISmBa8CuibHDNZD5kz3owjDGSYqTDm+RhJS8FoRYUJka2SGYapbAVPNR2U6LiueGjQJevf25THVsMXqt0ysMqPknJWZYJlJnDqiCKtwthrEntOF5Er2ZAhJGmsrRjtdSUJVl14RZX5owWjVZdBf31ZFS109jy1XHDkKwveB5QTU08NttUSptZ8PmYWVNJUimDmeSqcSszbBStHR4kP1EgisGoEsBT23SyNY6WG7aGJswWzSaaxjfFqITixA1i8FHkELHvgv5QbTM8I3s4qmjpySlc6RYJFOlIOaz6Psr3y+Ec8p4Tn0rQfuGmcthz7JTbVa5mQLbOtvaHB7bTpn1V2SUdBCADKlH0wMjPj95DjSz8BJsSGkvZlwknOO543RkB2XmqAArfC798yR3y/zNwcPGx0uzT+TT/Vcimf+bhdzs3PMcHhq5mBfVEVFCjQ1IVcNC/ns5JnRp7+jrwqiRpesj3eLy4qujQmUrp1SqpS5/soK3iXysQYQG6Uu1UAUUeJe1GmTceJ1nnbCc2FtrGPtVohH8TWyIl8OmPn75CnRvb5HrkagKZVHjd2IEIjnikyRDpvkp2u3KcmX3B3xHAbzGv4uoUFMUnxgw2vHc0p4KHlZdvJvJGY5WZZJszcaJGQPMvon5efQD74zrdaeaJNDi6eGuIV/iOeOv5i7pXi1e8c62xvwfAW4GikvMUI7U8JhVW2adU96TnuReCpyS2hAW21LTDlrJWMQ2fpw5dLQnr1qrLudBZKiidaExYN5ht2MwZbYo76z9sX22SDv0ARhGigvhELgU7Niim4Jd+17D31legV0H2r+XApNvDqjJloRifvV5enQaL3pq/Sc/pBliGuDOILWhDCLF5U+oj6yncTM2C7uHATvGfsunUI8VE9jYW8UeCN9Z37We4J1nWtzXmpO/ju+J0cSQfxU5izRbb2xq4KcVpCMh2iCE4GYg+OJxJPuoPywcsO/10ftYQNkGaMue0JQVJdj22+7ePJ9WH/gfJ92xWycX41PEj28KCgT//zr5pjRrL3Bq2ScDJAYh86BWIDBgveIyZLsn/qvdsLR1mzsoALBGCMuIEIcVItj92/9eFh+33+EfVt3k214YG9Q9T2aKfsTwv2Y5yzSI74ZrJqcH5AIh5yBBoBRgmyIKJI4nzmvrMED1qHr3AEJGHwtjUGhUyxjtW/beFZ+/H/AfbR3B24EYQ9Rpj5WKr8Uh/5b6ObS0b62rCKdjpBch9OBHYBJgkSI4ZHVnrquFsFZ1ebqFgE9F64sxEDiUntiF29UeOp9r3+Ufap3IG4/YWxRIj/vKnAVTf8w6cbTtL+XrfydWpEUiHKCn4CpgoCI9pHCnn+utMDT1D/qUABfFr4rxz/fUXphHm5rdxd9+H7/fDx33G0pYYRRaD9iKw4WEAAW6sjUy8C7riWfgJIviXmDioFygyCJaJIBn4quicBz1Kvpjv9xFasqlz6aUClgy2wfdt172X0DfGt2PW3AYFZRdz+vK5YW0gAL6+rVE8IgsJyg/5OqiuaE3oKihCOKNpOTn9uulsA61C7pz/51FHkpNz0WT4xeIWt0dD16UXyfejZ1QWwFYOJQTj/TKwgXjgEO7CzXi8PEsWCi1ZWGjLiGmoQ5homLYJR4oHOv3MAq1MnoFv5tEykoqDtUTaNcIGlpcjl4YnrVeJ9z6Gr2XiZQ7D7OK2EXQwIb7YrYMMWks22kAJi+ju6Iu4Y2iFKN5pWwoVKwW8FF1HzoZf1bEr4m7jlXS3Jay2YDcNN1DnimdqVxNGmVXSNPUD6eK6AX8AIx7gHa/8a9tcGmfppSkYWLQYmXinyPyJc6o3mxFMKK1EvovvxBETolCjghSftXJWRCbQxzV3UTdEtvJWfiW9lNej1DK8MXkgNO75Hb98gOuFqpS50/lHqOKYxbjQaSBJoXpeeyCMP71DboIfwiEJ8jADa2RkFVMWEqauhvQHIgcZJsvWTcWUhMaTy7KsoXKARv8DbdE8uTujSsZaCBl8yRcI9+kO2UmZxEp5y0NsSZ1T3okvv/DvAh0TMYREdS8l2+ZmpsyW7NbXxp/GGHV29KHTsHKrMXsQST8e7eU81JvUyvyaMWm3aVFJMAlDGYhZ/CqZe2n8Vk1mToEfvaDS8ggTFLQRFPa1oCY5Ro+Godagxm5V7iVFFIlzklKX4XKgW48rfgss8twKCycqf6nneZEpfcl86bx6KOrNi4Qsdc16nooPq2DGAeEy9QPqFLoFb4Xmpkz2YUZkNieVvvUe5F1jcWKCkXkgXb843iLtI8wyu2Xqspo8mdZpsQnMKfW6anr127H8mC2A7pQfqUC4MciiwtO/xHlFKkWvBfUWK2YSVevFewTkdD3TXZJrMW6AX79G/kxNRzxuq5ia+gp2miDKCZoAmkQKoLsyW+NcvW2ZTp9Pl3Cp0a6SnlNyVES04LVipbg10EXbVZsFMoS15AqjNvJR0WKwYW9lrmcNfNydi97rNarFSnAaVypaGocq63ti7BhM1X2zvqu/lfCa8YMid6NB9AykkxUR1WaFgEWPZUWE9YRzU9QDHYI2UVWQYp90voMNpIzfPBirhTsYSsQaqYqoWt77KqunfECdAE3QPrmPlQCLsWaSTwMPA7FUUbTMtQBVO6Uu1PuEpEQ845oC4UIowUcgY0+D/qAd3f0DbGV72GtvWxxq8GsLKys7ffvv3HxNLe3u3rivlLB8UUkSFMLZs3MUDMRjxLX00pTZ1K0kXuPio2zCslIJITdAY0+Tbs39+P1JzKUsLvu6K3jLW4tSS4urxUw73LstXj4Pjsk/lRBs8Srh6RKSUzITtKQXJFe0dXRwtFqkBaOk0yxCgLHnUSXwYo+ivuyOJV2CLPdceIwYe9jrupu9a9AcIGyLbP0tgS4yXutPlkBdsQwRvCJZEu6zWaO3Q/XEFIQTo/RjuLNTkuiyXHGzgRMwYO+x3wt+Us3MPTvcxOx57Dx8HUwcPDgsfyzOTTI9xr5XPv7fmFBOwOzxjkIeQpkzDBNUY5CjsCOzE5qDWFMPIpJCJaGdoP7gXk+wryq+gQ4HvYI9I6zeHJMcg0yOjJO80S0kXYoN/r5+LwPvq2AwMN2hX5HSIlHyvEL+4yiTSJNPMy1i9LK3olkB7HFlsOkAWr/O7zoOv/40XdpNdH00zQyM7Ezj3QJtNk19TcSeOR6nDyqPr5AiML5hIHGlEgkyWoKXIs3i3kLYcs1CniJdQg0xoOFL0MGQVf/cn1k+705x3iOt1w2djWhdV+1cDWPtni3I7hG+db7R30LPtOAk4J9Q8RFnMb9B9zI9clECcXJ/AlpyNPIAYc7hYzEQELiQQB/pj3gfHr6/7m4eKv34HdY9xc3Gndft+K4nDmEutI8On1yPu1AYUHCg0aEo8WSBoqHSIfJCApIDYfVB2VGhEX5hI2DicJ4QOP/ln5aPTg7+XrkugA5kDkXONZ4zPk4uVV6HbrK+9V89H3ffwxAcwFKQomDqcRkhTTFlsYIBkfGV0Y4Ba5FPsRvQ4aCzAHIAMJ/wv7RPfR88zwSu5c7A/raupu6hrrZOxA7pzwY/N/9tX5Sv3CACMEUwc5CsEM2Q5zEIURChIAEmoRUhDBDscMdgrhBx8FRgJu/6v8E/q697D1A/S+8unxhvGX8Rby/vJF9N31uPfF+fP7MP5oAIwCiwRWBuEHIgkQCqgK6ArQCmUKrQmwCHoHFQaOBPUCVQG9/zj+0vyW+4v6uPkh+cf4rPjL+CP5rPlf+jX7JPwk/Sr+Lf8kAAkB1AGBAgsDcAOvA8kDwAOXA1MD+AKNAhcCnQEkAbIATAD2/7H/gP9j/1v/Zf9//6X/1P8GADgAZQCJAJ8ApQCXAHYAQAD3/5z/Mv++/kT+y/1X/e/8mvxc/Dr8Ovxd/Kb8FP2n/Vz+Lv8YABMBGAIdAxkEAwXRBXsG+AZCB1MHKAe/BhkGNwUfBNgCaQHf/0T+pPwO+475NPgL9x72efUi9SD1dvUj9if3e/gX+vD7+v0kAGACmgTCBsQIkAoVDEUNFA54DmwO7Q37DJsL1gm3B0wFqALe/wP9Lfp19+/0svLQ8FzvZO7x7Qrusu7n76Hx1/N49nP5svwaAJQDBAdOClcNBhBEEv0TIBWjFX0VrRQ3EyMRfg5bC9EH+gPz/9r70ff282nwSe2u6rDoYefO5v/m9ees6RnsLO/O8uf2Vvv7/7EEVAm/Dc8RYRVZGJ0aGBy7HIAcZRtvGaoWKxMKD2QKXgUdAMv6j/WU8AHs/eeo5B7id+DB3wXgReF545Pmfuod70306fnF/7MFhwsRESYWnBpPHh8h9CK8I3AjDSKcHy0c2Re+EgMN0wZeANX5avNR7bvn0+LD3q3bqtnO2CLZp9pT3RXh0eVm66rxbPh6/5wGnA1DFFsatB8hJH4nrymfKkUqoCi6JaYhgxx2FqsPWAizAPn4ZPEx6pnj0N0F2WHVAdP80VzSINQ/16PbK+Gv5/7u4PYa/2sHkw9SF2oeoyTKKbYtRDBfMfswGC/CKxEnJSEsGloS6gkdATj4fu81557f9thy0z/PgsxQy7jLuM1D0UHWjtz6403sSPWm/h8IaRE7Gk8iZilGL8AzrTb1N4s3cDWwMWcsvCXfHQ0ViAubAZH3ue1f5M7bStQOzk7JMcbRxDzFcsdky/bQ/9dK4JnppfMg/rgIHRP8HAkm+i2RNJc55TxdPvE9ojt/N6YxQiqKIcEXMA0rAgb3Fuyy4SzYz8/eyJHDE8CDvu6+VcGnxcXLg9Ol3Obm+PGH/TYJrxSVH5MpWjKlOTg/5kKQRCZEqUEpPcc2sy4qJXMa4A7MApT2luov37rUicvmww2+L7psuNS4ZrsSwLTGHc8M2TbkRfDd/JsJHRYCIuwshTaAPp5ErEiKSiVKf0epQsc7DDO6KCAdlxB+Az32OenY3HvRfMcqv8e4ibSRsvGyqrWousfB0sqE1Yzhje4j/OUJaBdDJBIwdjodQ8NJMk5FUOlPH036R6BASDc4LMYfUBI/BAD2AOit2nDOqMOsusOzJa/3rE2tJ7BwtQO9psYR0uve0uxb+xUKjxhXJgEzKj55R6VOc1O9VW1VhFIYTU5FYzuhL2IiDBQNBdz16+ax2JzLE8BytgWvB6qip+un4KpvsG24nsK1zlXcF+uH+i0Kkhk8KLk1oEGRSz9TbFjsWqxaqlf9Uc1JWD/vMvAkxhXoBdH1++Xj1gDJvrx9spCqNaWYos+i3KWoqwe0vL51y8/ZXemn+SwKcBryKTg41ERiT45XF13QX6JfjFylVhdOJEMgNm0nfhfNBt31L+VG1Z7Gq7nRrmimsaDcnQCeHqEgp9ivBrtUyFvXqOe9+BQKKht3K306xkfpUo9bcmFkZEpkJmELWypSxEYwOdgpMRm7BwD2h+TY03fE3LZwq5CigJxymYCZqpzbouOrf7dVxfvU+eXL9+YJwBvMLIY8ckojVj5feWWjaKFocmUtXwBWMkocPCws2xqwCDn2A+Sc0o3CU7RdqAqfpJhelVOVhZjeniyoKrR8wrPSU+TT9qMJMhzwLVI+10wPWZhiKGmKbKJsbmkFY5dZbE3hPmcufByrCYb2ouOQ0d/AEbKZpdqbIZWkkX6Rs5Qsm7ekDLHMv4bQuOLX9UwJghzjLuE/9U6qW51lfmwXcEtwFm2QZupcblB8QYYwEB6oCuf2Y+O10G+/GLAnowKZ+pFFjgOON5HJl4ehJ65IvXbOLOHY9OIIsBymLzJByVDzXUhod29Gc5dzZnDKafZfNVPoQ4YylR+oC1n3RuML0D2+aK4HoYSWMI9Gi+aKFI64lJ+ef6v0uobMr9/Z82cIvBw4MEVCVFLpX5lqEXIVdoV2W3OxbLhivVUkRmU0CSGmDNz3SuOQz0m9Aq07n2CUxoypiCmITYv8kQOcF6nRuLnKRN7b8t0HqBybMBpDlVOLYY9sSnSBeBB583VBby1lBFgsSB82aSKjDW74beNFz5K856vEnZmSvopvhs+F5IiYj7aZ8abkthLJ79zh8UUHdhzPMLJDi1TXYiduInaIejh7K3h4cVJnCFr/SbM3tCOaDgz5r+Mozxm8FqujnDCRGImahNqD3YaOjbqXEaUttZLHsNvs8KAGJhzVMAxEN1XOY2FvlXcqfPt8AXpUcyVpxFuYSx455iSMD7b5DeQ5z927j6rWmyWQ14csg0uCOYXiixGWeaOxszzGitr/7/EFuhutMCpEmFVwZD1wpHhkfVZ+c3vRdKNqOF33TF46/iV1EGr6h+R3z927U6pgm3iP+oYmgiSB+oOUir6UKqJxshPFgNkb7zoFMxtbMA1EsFW8ZLpwT3k2fkl/gHzvdctrYV4YTnE7+iZTESX7GuXfzxi8X6o+myqPgoaJgWWAIYOmicKTKKFusRjElNhD7nsEkxrdL7VDgFWzZNlwlHmfftJ/JX2tdptsPV/7TlM81yclEub7xuVx0Iy8tKpxmzqPb4ZUgRGAroIZiR+Tc6CssE7Dxtd47bgD3Bk3LyRDCFVXZJtwdHmffvJ/ZH0IdxFtyl+dTwU9lCjoEqv8iOYq0Tm9T6v3m6iPwYaJgSaApILviNaSDKArsLXCGte87PECEBlqLlxCSVSnY/9v8Hg2fqh/O30BdyxtCWD8T4Q9LymcE3P9XucK0h2+MKzPnHKQeIcmgqWAAYMoieiS95/ur1HCkdYR7CoCMBh4LV5BRlOmYgdvCHhlffR+qXyXdu1s9l8YUM49pik9FDr+R+gO0zW/Va35nZiRkYgqg46BxoPDiVWTMqD0ryHCLdZ662MBPxdjLCxAAFJVYbRtvnYtfNd9sHvJdVJskl/vT+I99ynKFAD/QOk01IDAvK5xnxeTDIqWhN+C84TCih+UvqA/sCjC7tX36p4APhYsK8g+eVC2XwlsE3WOelJ8UHqZdFpr3V6BT789IipCFcL/SOp71fzBYrA3oe6U54tnhpiEh4YkjEOVnaHQsGfC19WL6uD/LxXXKTU9s07KXQZqCHOLeGZ6iXgGcwhq1V3NTmU9JSqjFX4AXOvf1qbDRrJHoxuXII6biLeGgIjojcSWzqKosd7C6dU26ib/FhRlKHQ7sUyWW69noXAmdhR4XnYScVpoe1zSTdI8/inrFTQBe+xe2HzFZrSfpZuZtZAxizqJ3YoMkJ+YUKTGso3DJdb76XX+8xLYJok5dkoaWQdl321gc191z3O+blJm0FqRTAU8rikZFuABoe332XvHvbY9qGyco5MnjiCMnI2QktOaJKYqtHfEi9ba6c39yRE0JXY3A0hbVg9ixWo8cEly4HALbPFj1FgKS/86MiksFoICzu6n26HJSrkdq4qf6JZ4kWWPvJBylWCdSKjUtZnFHNfV6TH9mhB6Iz41XUVaU8teV2e9bNVukW37aDlhiFY9ScA5iigiFhgD/+9r3evLCbw9rvOif5ojlQeTOpSvmESgvKrEt/XG2tft6aP8aA+tIeMyhkIcUD5bl2PmaAZr5mmRZSpe7VMrR0c4tyf7FZ8DMvFA31bO976ZsaKmZ54lmQOXEphGnH2jfa34uYvIxNgj6iP8NQ7PH2kwgT+kTG1XiV+8ZN5m4WXPYchaBVHURJU2tya2FRcEZPIl4d/QEsIttZWqmqJ4nVabQpwzoAini7BwvFnK2tl46rP7Aw3kHdItUjz1SFlTMVtAYGFihmG3XRRX0007Qqo0iiVRFX4ElfMW44PTVMX2uMeuFqcbovufxqBzpOOq47Mqv2DMHdvt6lX71AvtGyEr/DgTRQlPk1Z4W5Rd2VxOWRJTVkphP4gyMiTNFNMEwfQS5T/WvMjwvDWz1asHp/Ckm6UEqQyvgrckwp3Oi9yB6wr7qwruGVsogzUCQX9Ks1FoVnpY3VeXVMROlEZHPC8wrSIpFBUF6PUV5xDZRcwXwdq31LA6rC6qvarhrX6zaLtexRHRJt427NL6iAnoF4El6zHHPMFFlkwTURhTllKVTy5KjULvOKEt/CBjE0IFBvcd6fLb7M9mxbG8DravsbOvKLAHsze4j7/UyLrT7d8L7bD6bgjeFZciNy5kONJAQEeAS3JNCU1MSlJFRT5bNd4qIB9+ElkFG/gn6+PerNPaybbBfrtgt3m11rVxuDS998OEzJbW3eEB7qP6XwfUE6EfayrfM7c7t0GyRY1HO0fBRDZAvjmPMeonGx13EVsFJPkx7d7hg9duzuXGIMFJvXu7w7scvnDCm8hs0KPZ+OMY7636XAbKEaAciiY9L3U2/zuwP25BMEH4Ptw6/jSMLcUk7BpQEEUFIfo57+LkbNsf0znM7sZkw7XB68ECxObHeM2I1N/cOuZP8M/6ZgXFD5oZmiKAKhExHTZ9ORs77Tr2OEk1BjBWKXEhlRgJDxcFD/s88evnZN/n16zR48ytySHISMgfypTNidLX2EngpOim8Qj7gATFDZAWnB6uJZArFjAgM5g0dzTAMoIv2yrwJPIdGRaiDdIE7vs48/bqZuPB3DrX+dId0LnO1c5u0HPTzNdU3d3jNOsd81r7qQPNC4UTlhrMIPYl8CmeLOwt1C1aLIspgSVdIEkadxMdDHQEu/wr9f/tb+er4d7cLNmv1njVjNXp1oHZPN384Zrn5+2y9MT75QLgCX0QjBbdG0kgsSP8JRwnCifKJWkj/B+gG3oWshB5Cv4Ddv0S9wTxeuue5pPid99e3VjcaNyL3bbf1eLM5nzrvPBk9kb8MwL/B3sNgBLmFo4aXR1BHy4gHiAXHyEdURq+FoYSzQ24CG8DHv7t+AP0hu+X61To0uUk5FPjY+NP5A/mkejA64DvsvM0+OH8lQEsBoIKdg7sEckU+xZyGCcZFhlEGLkWhBS6EXIOyArbBsgCsv64+vf2jPOR8BvuOuz76mPqduov64bsbe7T8KPzxPYe+pX9CwFpBJQHcwrzDAEPjxCWEQ4S+BFYETUQmw6ZDEEKqAfjBAkCMv9y/N75i/eI9eTzqPLc8YPxnfEm8hbzZPQC9uL38/kj/GD+lwC4ArQEegb/BzkJIAqxCukKygpZCpsJmQheB/UFbQTSAjIBnP8Z/rb8fvt4+qn5F/nD+Kz40fgs+bn5cPpI+zn8Ov0//kL/OAAbAeQBjgIVA3cDswPKA74DkwNMA/AChAINApMBGwGpAEQA7/+s/33/Yv9b/2b/gf+p/9j/CgA8AGkAiwCgAKQAlQByADoA8P+T/yn/tP46/sH9Tv3n/JT8WPw5/Dv8Yvyt/B/9tf1s/kH/LAApAS4CMgMuBBUF4QWHBgAHRgdSByIHtAYIBiIFBgS6AkkBvv8h/oH87fpw+Rn49PYN9m71HvUk9YH1NvZA95v4PPoa/Cf+UwCQAskE7wbtCLMKMgxaDSAOfA5mDt0N4gx5C6wJhgcWBW0Cov/G/PL5Pfe89IbyrfBD71Xu7e0T7sfuB/DM8Qv0tfa2+fn8ZADfA0wHkgqUDTsQbhIbFDEVphVyFZUUERPwEEAOFAuCB6UDnP+D+3z3p/Mi8AvtfeqN6E3ny+YM5xPo2elU7HTvIvND97j7XgAVBbUJGg4gEqcVkRjEGi4cvxxxHEMbOxlnFtkSqw78CfAErf9a+iL1LvCm66/naeTy4V7gvd8W4Gvhs+Pf5trqhu/C9GT6QwAxBgEMgxGMFvMalB5QIQ8jwSNdI+MhXB/ZG3MXSRKDDEwG0/9K+eXy1exL53Tid95324zZydg32dXamd1x4UHm5us28gD5EQA0By8OyxTVGhwgdCS5J9AppSovKm4obiVCIQoc6xUUD7cHDgBV+MbwnukV41/drNgh1d7S9tF00lbUkdcO3K3hROih7473zP8bCD0Q8Bf4HhwlKir6LWowZTHhMN8uayueJpogjRmrETEJXwB798jui+YG33TYC9P2zlnMScvTy/TNoNG71iLdo+QH7Q32cf/oCCoS7xrxIvAptC8ONNk2/TdvNzA1TjHmKx8lKx1IFLcKxAC89uzsoOMj27jTms37yALGyMRaxbbHy8t+0aTYCOFp6oH0Av+ZCfYTxh2+JpQuDDXvORY9Zj7SPVs7EzcXMZQpwyDmFkkMPQEZ9jLr3eBt1yzPXMg0w9+/eL4Ov5/BGcZbzDnUdd3L5+vygP4vCp4VdCBbKgUzLjqaPx5Dm0QFRFxBszwrNvUtTySDGeINyAGR9ZvpRt7p09bKV8OnvfW5X7j1uLW7jMBXx+PP79kw5U7x7f2pCiIX9iLHLUA3FT8JRepIl0oCSixHKkIeOz8yzicdHIMPYwIk9Sno2tuX0LnGjr5XuEi0grIVs/+1LLt2wqfLedaZ4qvvSf0JC4IYSyX+MEA7v0M4SnZOVVDFT8hMckfrP2w2OyuvHikRDwPR9NvmnNl6zdbCBLpKs96u5axxrYCw/LW+vYrHFtMK4APulfxOC70Zcif/MwQ/KEgjT71Tz1VIVSlSiEyORHk6ky45IdESygOZ9LPljdeVyjK/vbWCrrqpjqcQqD6rArExuY7Dys+H3Vvs1Pt5C9MaaSnINohCTEzHU7xYAluHWktXZlEDSWE+0jG2I3kUkQR69LDkrtXpx867vLEEquKkgaL1oj2mQqzWtLm/mMwR27PqB/uMC8QbMCtXOctFKVAfWG1d6V99XylcB1ZETSJC9TQkJiAWZAV19NLj/9N4xa24Ba7TpVigwp0lnoKhwKewsA+8hcms2A7pLvqFC48cxiyrO8pIu1MoXM5hf2QlZMBgaFpOUbZF+TeAKMIXQgaH9BnjgtJCw9G1maryoSGcVZmlmRGdgaPDrJK4k8Za1m/nTPlnCzUdKi7CPYJLAFffX9tlwmh8aAplhV4dVRpJ2TrGKl4ZJwew9IbiNtFKwTyze6dknj+YPZV4le+YiJ8TqUa1xcMf1NflY/gzC7cdXS+bP/RN9llCY5BprWx+bARpWGKtWEtMkz31LPEaEwjv9BbiHdCPv++wrqQtm7eUgJGikR6V2pukpTCyH8H+0UnkdffqChQeXTA3QR1Qm1xOZutsPXAocKts4GX6W0ZPJEAJL3kcBAlC9crhNc8TvuuuMqJNmIqRHo4mjqOReph5olOvpL74z8jigvaNCk4eLDGTQvtR7V4Baepvb3N1c/pvF2kCXwZSiEL/MPMd+Amp9aHhf87WvDGtCqDHlbuOG4sHi4CObJWWn7GsWLwRzlXhjvUdCmYeyjGxQ5BT62BZa4lyQXZkdu9y/GvAYYlUvUTWMl4f7Qoh9pvh+s3Yu8KrNp6dk0yMeohJiLmLspL+nE6qPLpMzPPfmfSdCVweNjKPRNlUlGJVbcd0sXjyeId1i24xZMtWv0aJNLYg4Aup9rXhps0Zu5+quJzQkT6KPYbthVGJT5Czmi2oU7iryqXep/MNCTIecjIvRdZV52PzbqN2vHoce8B3wXBUZstYjUgXNvoh0QxA9+7hgc2ZusepkJtikJSIZYT1g0mHRo65mE+mobYwyWzdufJvCOkdfzKQRYlW5GQycBt4YHzgfJZ5nHImaIVaI0p+NycjvA3k90bijM1WujqpvppSj0+H9IJkgqOFmYwRl7mkKLXex0vc0PHGB4MdXjK0RfBWi2UTcS55nX0+fgp7GnSjafdbf0u7ODwkoQ6T+LvixM1RuvmoQpqhjm6G64E7gWKES4u+lWuj6bO3xkTb8PASBwAdDzKbRQxX22WUcdx5cn4zfxh8OXXLaiBdoEzMOTUlfA9L+UvjKc6IugGpHZpPjvOFS4F6gIeDW4rBlGii57K9xVnaGvBWBmMclTFHRd9W1mW2cSR63n6/f8B8+HWca/1dgk2uOhImTRAK+vXjuM76ulOpTZpcjt6FE4EjgBODzYkclLKhJLLyxIvZT++UBa4b8TC4RGlWfGV6cQd64X7hfwF9VnYVbIxeJk5hO88mERHQ+rbkcc+lu+2p0ZrIji2GRYE1gAWDoInRk0qhobFYxN7Yku7MBOEaJDDwQ6xVzWTgcIV5e36af9p8UnYzbM1eiE7iO2wnxhGY+43lUdCJvM2qqZuQj+KG4IGygGCD1YnfkzChYLHxw1LY5e0DBP8ZMS/xQqhUzWPpb594rH3pfkx863X3a75eqE4wPOcnaxJj/HnmV9GivfOr0py1kPmH44KXgSKEbYpJlGehYrG9w+nXSu04AwsZGS69QWFTe2KXblZ3dXzOfVZ7InVga19ehE5JPD4o/RIt/XbngdLwvlutS540knOJTITmgkuFaIsNle6hqLG+w6XXwexuAgUY3ixWQNhR2mDrbKt12XpMfPp59nNvaq9dHE4tPG8oexP1/YPozNNwwAWvE6AMlE6LHIachNuGxYwtlseiMrL2w4fXTuyoAfEWgyu+Pg5Q7V7naqFz13hiejd4aHIiaa5cb03aO3ko5BO6/p7pNtUfwu6wJqI7loiNT4i5htCIhI6nl/GjArNkxJDX8evmANAVCir4PAhOtVyOaDlxcnYTeBB2eXB7Z1xbfUxQO1woNRR4/8Xqvdb8wxKzgqS9mB2Q5Io6iSmLo5B7mWulF7QKxcLXq+srAKMUdSgGO8ZLNVrjZXZurXNhdYVzKm56ZblZRUuOOhYobhQuAPbrX9gDxnC1JaeRmw2T2Y0djOWNIZOomzancbXpxR3Yf+t5/28TxybqOExJcFfnYlpriXBNcppwfWshY8ZXyEmTOaYnjRTcAC7tGdozyAW4DKq0nlSWK5FgjwCR/JUtnlGpELcAx6LYbuvR/jQSAiWoNp5GaVSfX+lnCm3bbk9tdGhwYIRVBkhgOAsnkBR/AWvu6duHys26M60hou6Z1pQAk3mUM5kIobqr9LhPyFLZeOs1/vQQKCNCNL1DI1ENXCdkM2kNa6hpEGVqXfRSAEb0NkYmeBQVAqzvy93+zMW9lrDXpdmd2Jj7lk2Yw5w4pHCuHLvXyS3an+um/bMPPSG7Ma5Aok01WBVgB2XnZqhlVWESWhhQt0NRNVUlQhScAu7wvt+Uz+rAM7TQqRCiLZ1Mm3mcqaC5p3Kxhr2WyzPb5Osm/XEOQx8XL3M96kkbVLlbimBsYlJhRV1oVvFMLEF1Mzkk7xMUAy/yv+FG0jnEBrgKrpCm0aHwn/mg4qSLq760MsCNzWXcR+y2/DENPB1YLBE6/UXCTxZXwVugXalc41hvUoFJYD5jMfIifBN8A23zy+MR1a7HC7yAslWrwKbjpMqla6mpr1G4HsO6z8LdyexY/PYLKxuBKYo24UEwSzFSrlaHWLFXM1QsTstFVTscL38h6xLQA6b04OXy10bLPcAtt1qw9ashqueqQa4RtCm8R8Yc0krfau0N/MAKExmXJuMymT1oRg1NV1EmU25SOU+gSdJBDTifLOIfOhISBNj1++fl2vvOmsQOvJq1bbGlr02wX7PAuEPArcmz1P3gK+7V+5EJ9habIx8vKjlvQbFHwEuATeZM+EnQRJg9ijTvKRoeaRE+BAL3Gero3czSG8kewRG7Ibdrtfi1wrixvZ3ETc1819niC++z+20I1xSSIEMrlzRKPCBC70WbRxtHdES+PyA5zzANJykceBBWBCH4OOz34LTWvs1YxrrADr1tu+G7Zb7iwjLJI9F22t7kDPCn+1MHuRJ+HVEn5i/9NmA86D99QRNBsz5wOm003Sz8IxAaaA9XBDX5Vu4P5K/afdK3y5HGLsOnwQbCRMRNyADOL9We3QvnLPGx+0cGnRBjGk4jGiuMMXU2sTkpO9Q6uDjoNIQvuSi9IM8XOA5BBDr6b/At57neVdc30Y7Me8kTyF/IWcrvzQPTa9nz4F/pbPLS+0gFhg5DFz4fOCb+K2YwTzOlNGI0iTIsL2gqZSRSHWkV6QwUBDH7g/JN6s7iQNzT1q7S8c+tzunOoNDE0zfY1t1z5NjryvML/FoEdwwjFCQbRSFXJjcqxyz4LcItKyxBKR4l5B++Gd4SewvPAxf8jfRt7evmOuGE3OvYidZt1Z3VFNfF2ZjdbOIa6HTuR/Vc/HwDcQoFEQUXRBycIO0jICYmJ/smoiUqI6gfOhsEFjEQ8AlyA+z8jfaJ8AzrP+ZH4kDfPt1O3HbcsN3w3yLjKufn6zLx4PbF/LECdwjsDeQSPBfSGo8dXx82IBIg9h7uHAwaahYmEmMNSAj+Aq79gfie8yzvS+sW6KblCuRM427jbeQ95s/oC+zV7w/0lvhG/fkBiwbaCsUOLxL/FCIXiRgtGQwZKhiQFk4UeREoDncKhQZxAlz+Zfqq9kjzV/Dt7Rns5+pf6n/qRuup7JzuC/Hj8wr3Z/rf/VQBrwTUB6wKIw0nD6sQpRESEvARRBEXEHMOagwMCm4HpgTMAfb+Ofyq+V33YfXF85Py0PGB8aTxNvIu84P0KPYM+CD6UvyP/sUA5ALcBJ0GHAhPCTAKuQrqCsQKTAqHCYAIQQfWBUsErwIQAXr/+v2b/Gb7ZPqb+Q75v/it+Nb4NvnH+YH6XPtO/E/9Vf5X/0wALQHzAZsCHwN9A7YDygO7A44DRQPnAnoCAwKJAREBoAA8AOn/p/96/2H/W/9o/4T/rP/c/w4AQABsAI4AoQCkAJMAbgA1AOn/i/8f/6r+MP63/UX94PyO/FT8OPw9/Gb8tfwq/cP9ff5U/0EAPgFEAkgDQgQoBfAFkwYIB0kHUAcbB6gG9wUMBewDnQIpAZz//v1f/Mz6Uvn/99/2/fVk9Rz1KPWM9Un2Wve7+GL6RPxV/oMAvwL4BBsHFQnWCk4Mbw0sDn4OXw7MDcgMVwuBCVUH3wQzAmX/ify3+QX3ivRb8orwKu9H7uvtHO7c7ifw9/FA9PL2+vlB/a4AKQSUB9UK0Q1uEJcSOBRCFagVZhV7FOkSvBABDssKMgdQA0X/LPso91jz3O/P7E3qa+g758nmG+cx6Afqkey973bzn/ca/MMAeQUVCnQOcRLrFccY6hpCHMEcYRwgGwcZIhaFEkwOlAmBBDv/6fm19MjvS+ti5y3kx+FH4LvfKeCS4e7jLec36/HvNvXg+sEArwZ6DPQR8RZJG9gefyEoI8MjSCO3IRsfhBsMF9QRAgzDBUj/wPhf8lns3OYW4i3eQ9tx2cfYTtkF2+HdzuGy5mfsw/KV+aoAywfADlIVThuCIMQk8SfuKagqFio6KCAl3SCQG2AVew4WB2r/svcp8AvpkuLw3FTY5NS90vPRj9KO1OXXe9ww4troRvA7+HwAywjmEI0YhB+TJYgqPC6OMGkxxTCjLhErKSYNIOwY+xB3CKL/v/YT7uPlcN7116bSsM4zzEXL8cs0zv/RONe43U7lwu3T9joAsAnrEqIbkSN4Kh8wWTQCNwI4TzftNOkwYiuAJHYcgRPmCe//6PUf7OLiedoo0yjNq8jWxcPEe8X8xzbMCdJM2cfhO+te9eT/eQrOFI8ecSctL4Q1RDpFPWw+sD0RO6M2hTDkKPofChZgC08ALfVP6grgsdaMzt7H28Kuv3G+Mr/swY3G9Mzx1Ejesujf83r/JguMFlEhISuuM7M6+D9SQ6NE4EMMQTk8izU1LXMjkhjkDMMAjvSi6F7dGdMmysvCRL2+uVa4G7kJvAvB/cer0NXaK+ZY8v3+twsmGOgjny74N6c/cEUjSaFK3EnWRqZBcjpuMeAmFxtvDkgBC/Qa597atc/5xfW967cMtHeyPLNYtrS7KcN/zHDXqOPJ8G7+LQybGVAm6DEIPF5EqUq1TmFQnU9tTOZGMz+MNTwqlx0AEN8Bo/O45Y3Yh8wHwl+51LKbrtismq3esIy2fL5wyB7ULOE279D9hwzqGooo+zTaP9NInU8CVN5VH1XJUfRLy0OLOYMtDiCVEYUCV/N85GvWkclUvgy1A65yqX6nOqigq5qx+rmCxOLQut6g7SL9xgwTHJQq1DdtQwNNSlQHWRNbXVrnVspQNUhnPbMweiIrEzoDJfNm43rU1cbiugCxfKmUpG+iH6OjpuCsqbW6wL/NVdwK7Gf86gwWHWwsczq+RutQq1i+XfxfUl/CW2VVbUwbQcgz2CTAFPsDDfN34rvSVMS0tz2tQqUEoK2dUJ7soWWojLEbvbnK/9l26qD79gzzHRIu1jzKSYhUvFwlYpZk+mNVYMBZblCkRL42JSdSFsgEDvOt4S7REMLLtMapWaHHmz2Z0Jl+nSukp62oudTHvNfm6M766AypHoYv+z6PTNhXfGA3ZttoUmidZNddNVT/R5I5XinfF54FJ/MK4dPPCsApsp6mxJ3glyOVopVdmTig/qlnthHFjtVd5/T5www6H8cw4kAMT9ha52PyaclsVGyVaKdhvlcnS0E8gCtlGXwGWPOM4KzOQ77Rr8ejhJpSlGKRzJGOlY6clqZZs3bCeNPc5RP5iAylH9UxiUJAUYZd+2ZTbV1w/m86bCplBVsZTsg+iS3hGmAHnvMz4LfNu7zCrUKhnZcfkf2NT44UkjKZcaODsATAfdFm5C34NwzsH7Ay8UMpU+FftWlXcJJzTXOIb19oCF7SUCRBdi9QHEgI+PP+3/bMc7v+qxGfEZVLjveKL4vyjiaWkqDorb+9n8/94kP30wsPIFgzGUXHVOdhE2z7cmh2PXZ8ckFrwmBPU1FDRDGxHTIJZvTt32fMa7qHqjad4JLXi1OIb4gsjG6T/p2Kq6q74s2k4Vj2XAsPIM4zAUYYVphjFW4+ddp4zXgUdc5tMGONVU5F8DIBHx0K5fT+3wnMo7lcqbGbDZHFiRKGEYbDiQ2Rtpttqce5R8xd4G711QrtHxM0qUYeV/JkuW8ed+h6+HpNdwNwUWWJVxdHeDQ/IAYLdfUw4N3LG7l9qIKamY8XiDeEGIS6hwSPvZmSpxm40soq34b0PgqsHyc0EUfWV/Rl/XCaeJB8v3wled5xIWdBWalI2zVnIewLEvaB4OHL07jqp6uZhI7OhsOChIIUhleNFpj+paK2g8kO3qPzmglLHws0OkdDWKBm4nGxedB9H36aelxznmiyWgNKFDd3IswMvPbx4BTMyLijpyuZz43phbeBWIHShAiMw5axpGW1X8gK3cby6gjMHsEzJkdkWPVmZ3Jjeqh+Fn+qe310xmnaWyNLIzhvI6UNcfd94XXM+7iopwGZeo1rhROBlYD0gxeLxpWuo2S0Zscg3PLxMQgyHkoz1UY6WPNmjXKuehd/pX9UfD11mGq3XAZMBjlKJHUOL/gl4gLNa7n3py6ZhI1ThdmAO4B+g4aKH5X2oqCzmsZT2yjxbwd+HacySEbGV5tmU3KTehx/yn+XfJ51E2tJXatMujkJJTkP9Pjm4rrNFbqPqLGZ7Y2ghQmBS4Bug1eK0ZSMohuz/8Wk2mrwpwaxHNsxgUUKV+5lu3EUerh+hX90fJx1NGuMXQ9NPTqoJfAPvvm+45vO+LpvqYeatY5ShqGBxYDFg4mK3ZRvoteylMUV2rrv2wXOG+YwgUQGVu5kxXAveex91n7oezl1/GqCXTNNjzomJpgQjPqs5KLPE7yVqrGb2Y9oh6GCqIGEhB6LQpWiotSyW8Wo2RvvDQXWGswvS0O+VJxjc2/nd7d8v332enN0amonXRRNrTqCJi8RW/ut5c/QY70ArCudWJHiiAmE9IKqhRSMApYkoxSzV8Ve2Y3uPgTMGY0u4UEyU/phx209dhx7P3ydeUxzfWl9XLJMmDq6JrMRKfzA5h/S576srfSeMZO8iteFqIQ2h22NG5f2o5izh8U42RLucQOxGCwtREBlUQpgwmszdBx5WHred8NxNmiDWw1MTDrMJiQS9fzi55DTnMCZrwqhYZX2jAmIwoYniSaPj5gYpWC07sU52aztpwKIF6wreD5aT89dZ2nLcbl2DHi7ddlvlWY4WiNLyzm4Jn4SvP0R6R/Vf8LDsWuj5peMj56KQIl8iz+RXJqLpmy1isZh2V3t4gFTFg8qfzwSTUpbuWYHb/RzXHU1c5BtnGSeWPVJEzl8JsISfv5M6srWjsQntBKmvZp9kpKNIYwzjreTgpxNqLy2Xsex2SbtJQEUFVcoWjqSSoBYumPqa9FwS3JNcOpqSmK0VoJIIzgYJuwSN/+P647Yx8bDtv+o453FleOQYY9KkYyW/55eqlC4acgq2gjtcADNE4cmDjjbR3JVbWB3aFJt224Hbedno198VMxG/TaLJf0S5//Z7GnaJsmUuSysVaFimY+UAJO+lLyZ0aG9rCm6q8nM2gTtx/+AEqIknjXxRCVS1lyxZHppD2tlaYpkplz3UdJEnzXTJPMSigAo7lncqMuWvJivEKVQnZGY+JaOmEWd+KRor0O8JcuY2xztKP8wEakiCzPXQZxO+FicYE5l62ZpZdZgVlkmT5ZCCjTyI84SIgF571reSs7Hvz6zEKmLoeecR5u1nCShcKhesqC+1syO3FDtmP7fD6AgWTCRPtpK11Q8XNBgcmIYYc1ctlULTBlAPjLmIosSqwHK8GrgCtEiwxq3Ua0Qpo2h6Z8woValN6ydtT7BvM6v3aLtF/6ODokejC0iO+RGeFCUVwRcp11zXHNYyFGoSFw9PDCwISsSJAIa8ofi5NOkxiq7z7HZqn2m26T9pdepS7AjuRrE2dD73hHupv1ADWccpiqON71C3UuqUu9WkFiAV8tTj00ARWA6BS5QIKwRjAJm863k1dZJymi/hbbkr7WrGKoWq6WuqLTuvDTHKtNw4J/uR/33Cz0aqifYM2k+DEeATZZRL1NCUthODkkUQSg3myvGHg8R4QKs9Nvm2tkOztDDb7sqtS+xm694sLyzTLn6wIrKrtUP4kvv+/y0Cg0YnSQFMO05CUIeSPxLik2+TJ9JSUToPLYz/SgTHVMQIwPq9Q3p79zv0V/IicCouue2YLUethe5Mr5GxRjOZNjX4xbww/x6CdoVgSEYLE012TyGQihGpkf3RiNEQz9+OAwwLyY2G3gPUQMf90DrEeDn1RDNzsVZwNe8YrsDvLK+V8PNyd7RStvH5QHxofxKCKYTWh4VKI0wgTe+PB1Ah0H0QGo+ADrbMywsMSMzGX4OaQNJ+HTtPeP02d7ROcs3xvvCnMEjwonEt8iMztfVXt7e5wryk/wnB3QRKhsAJLErBTLLNuI5Mzu4Onc4hDQBLxkoByAIF2YNawNm+aTvb+YQ3sXWxdA9zE3JCch5yJbKTs6A0wLan+Eb6jLznfwRBkYP9hfdH8AmaiyzMHszrzRKNFAy1C70KdcjsRy5FC8MVgN1+s7xpek54sDbbdZm0sfPo87/ztbQFtSk2FreCuV97Hj0vfwKBSANwBSwG7whtiZ6Ku4sAS6uLfkr9Ci4JGkfMhlFEtoKKgN0+/Hz2+xp5szgLNys2GXWZNWw1ULXDNr23d7inOgC79z19fwTBAILixF9F6oc7SAnJEEmLifqJnkl6SJSH9IajRWvD2cJ5wJi/An2DvCe6uLl/eEL3x/dR9yG3NbdK+Bw44jnU+yo8V33RP0uA+8IWw5HE5AXFRu/HXofPSADINMeuBzFGRUWxRH5DNkHjAI+/RX4O/PT7v/q2+d85fLjRuN744zkbeYO6VfsLPBt9Pn4q/1cAuoGMgsTD3ESMxVHF54YMhkAGQ4YZhYXFDYR3A0lCi4GGQIG/hP6XvYF8x7wwO3569bqW+qK6l7rzuzL7kTxI/RQ97H6Kf6dAfUEFAjlClMNTA/FELQRFBLnETAR+A9MDjoM1gk0B2oEjwG6/gD8dvkv9zv1qPN+8sXxgPGs8UfyR/Ok9E72N/hO+oL8v/70ABADAwXABjkIZQk+CsAK6gq9Cj4KdAloCCQHtgUpBI0C7QBZ/9v9f/xP+1H6jfkF+bv4rvjc+EH51fmS+m/7Y/xl/Wv+bP9fAD4BAwKnAigDgwO5A8oDuQOJAz4D3wJwAvkBfwEHAZgANQDj/6P/d/9f/1z/av+H/7D/4f8TAEQAbwCQAKIAowCRAGoALwDi/4L/Fv+g/ib+rf08/dj8iPxR/Df8P/xs/L78Nf3R/Y7+Z/9VAFQBWQJdA1YEOgX/BZ8GEAdMB04HFAebBuYF9gTRA38CCQF6/9z9Pfyr+jT55PfJ9u71W/UZ9S31mfVc9nX32/iI+m/8gv6yAO8CJwVHBz0J+QpqDIINNw6ADlcOuw2tDDMLVgkjB6gE+AEo/0z8fPnO9lj0MPJp8BLvOu7q7Sfu8u5J8CTydvQv9z36if34AHIE2wcYCw0OoRDAElQUUBWpFVkVXxTBEocQwA2CCuIG+wLt/tX61PYK85bvlOwf6kvoKufI5irnUeg36s/sCPDL8/z3fPwnAd0FdQrNDsASLxb8GA8bVRzCHE4c+xrQGNsVMRLrDSoJEgTJ/nj5SfRk7/LqFufx457hMuC63z7gu+Er5Hvnlutd8Kz1XPtAAS0H8gxjElQXnRsZH60hQCPDIzEjiSHXHiwboxZdEYELOwW8/jX42/He62/muuHl3RHbV9nG2GfZN9sq3i7iJOfp7FDzK/pCAWIIUQ/YFcUb5yATJSgoCiqoKvspBCjQJHUgFBvTFOENdAbF/g73jO966BHig9z/16nUn9Ly0azSyNQ72OvctuJy6evw6fguAXsJjxEqGQ8gCCbkKnsurjBqMaYwZS61KrIlfh9KGEsQvQfk/gP2X+085dvdd9dE0mzOD8xEyxLMds5h0rfXUN775X7umfcEAXgKqxNUHC8k/SqIMKE0JzcEOC03pzSCMNwq3yO/G7oSFAkZ/xT1VOsm4tLZmtK5zF7IrsXAxJ/FRsijzJfS9tmI4g3sPPbFAFkLpBVWHyIowi/6NZU6cD1vPoo9xDowNvAvMSgvHywVdwpi/0H0bek53/bV7s1ix4XCgL9uvlm/PMIFx5DNrNUd35rp1PRyAB0MeRctIuUrUzQ1O1NAgkOnRLhDuEC8O+k0cSyVIp8X5Au//4vzqud43E3SeclDwuW8i7lRuEW5YLyNwabId9G82yjnYvMMAMUMKRnYJHUvrTg2QNRFWUmnSrFJfUYgQcI5mzDvJREaWg0tAPLyDebk2dfOPMVgvYO307NwsmiztLY/vN7DWs1p2Ljk6fGU/1ANsxpUJ9AyzDz5RBZL8E5oUHBPDUxXRnc+qjQ6KX0c1g6vAHXyl+SA15fLO8G+uGOyXa7QrMetQLEgtz2/Wcko1U/iavAK/74NFhygKfM1rUB6SRNQQ1TnVfFUZFFcSwRDmzhxLOIeVxBBARXyR+NM1ZHIer1ftImtL6l0p2ioB6w2sse6ecX80e/f5+5w/hEOUh28K904T0S2TchUTVkfWy1aflYrUGNHaTyRLz0h2xHjAdDxHuJJ08TF+rlHsPmoSqRhok+jDqeErYC2vsHozprdY+3H/UgOZx6lLYw7rUepUTJZCl4LYCJfVVu/VJFLEUCXMosjXxOSAqbxHeF50TTDvrZ5rLektZ+dnYCeWqIPqWyyKr7wy1Tb3+sS/WUOVR9cL/09xkpRVUxddmKnZMpj5V8TWYlPj0OANcgl4RRNA5bxQ+Dcz+HAyLP4qMagc5sqmQCa753bpJCuw7oYyR/ZX+pR/GgOGyDfMDBAmE2rWBRhjmbvaCFoKmQlXUlT30ZIOPQnYBYUBKDxkN9zzs6+G7HGpSidhpcNldOV0ZntoO+qi7dhxv/W5OiF+1IOuyAuMiRCIVC1W4ZkT2rgbCRsH2jvYMtW/knsOgkq1xfjBMHxBN8+zfq8t67louGZ85NJkfuRBJZHnY2nhrTQw/XUcOey+iUONCFJM9hDX1JtXqFntW12cM9vw2tvZAxa6ExqPQcsRxm6Bfrxnt49zGa7nqxXoPOWu5DijX6OjJLumW2kt7FowQTTBebY+eENhyExNEtFU1TQYGJqvXCvcx9zEG+gZwldmk+9P+otqxqXBknyXd5vyxO60KoenmCU4o3Zil2La4/mlpOhI68rvzDRp+T5+IgNtiHkNH5G+VXeYsdsZ3OHdhB2BHKAar5fEVLjQa8vAxx3B6zyQd7WygK5UKk7nCmSaYsxiJuIpYwwlAOfyqwcvXrPV+MY+BsNwCFkNW5HU1eWZM9urnX9eKF4m3QLbSliSlTZQ1QxSx1ZCCLzSd5wyjK4HaivmlCQU4nuhTyGPIrQkb6csao/u+bNF+I295wMpyGxNR5IYFj3ZXhwk3cOe8561XY/b0dkQ1adRdcygh47Carzct48yqK3N6d6mdeOoIcPhEGEM4jIj8ea2qiVuXbM6uBU9g0MbCHMNY5IH1n/ZsJxE3m5fJd8rXgZcRZm+FcsRzQ0pB8bCkH0vt45ylO3nqadmL2NU4aYgquCi4YcjiGZSKchuCvL0t929W4LESG2Nb1IkVmwZ6xyLnr8ffl9I3qYcpJnZ1mESGs1sSD3Cub0KN9nykO3U6YZmASNa4WJgX2BR4XLjM+X/KXmtgnK0d6d9MIKlyBwNa1ItlkJaDVz43rXfvN+NXu6c7toj1qiSXg2piHNC5j1sd/EynO3U6bsl6uM6YTjgLiAaITZi9CW+aTltRHJ6d3L8wsK/x/8NF9IkFkKaF1zMXtJf4R/4Xt8dI9pbVuFSlo3gSKbDFT2V+BPy9+3oKYWmLKMzoSmgFuA74NHiyiWQKQgtUbIHN0B80oJTB9bNNRHHlm1ZyZzGXtRf6t/J3zfdAtqAFwrSw84QCNgDRn3F+EGzIi4NqeWmBmNGYXTgGmA3YMVi9iV06OZtKjHa9xC8oIIfx6PMw1HY1gKZ5BynHrvfml/BnzgdC9qR1yTS5U44SMZDuX38OHnzGy5Fqhsmd+NyYVpgeCAMYREi+CVs6NRtDrH2tuQ8bQHmh2ZMg1GYFcKZptxuXklfr1+fnuAdPtpQFy6S+s4YyTEDrX44eLxzYi6PKmVmgKP3oZngsCB7YTUi0GW4aNKtP3GaNvs8OIGnxx8MdZEFla4ZEpwcnjzfKl9j3q/c21p6luhSw45xCRgD4j55uMhz9u7qaoQnIGQVojNgwmDD4bHjPyWXqSFtPPGGNtZ8A4GkBs5MGhDiFQUY51uyXZZeyx8OnmccoZoRltFS/84AiXqD1z6/uR10GK9WKzbnVuSMIqZhbqEl4cajhCYKqUCtRzH7NrX7zoFcBrTLsdBuFIiYZdsv3RbeUd6f3cYcUVnU1qnSrs4HCViEDD7J+bs0Ry/Sa70n4yUaozKh9GGhInOj32ZRabCtXrH5Npp72gEPxlNLfU/p1DjXjtqVnL4dv53YHU0b6tlEFnFSUM4EiXGEAD8XueC0wbBeLBYohOXAY9dikyJ1YvikUObr6fFtg3IAtsQ75kDARinK/Q9Wk5bXIpnkW81dFF13nLxbLljflehSJU34CQUEcz8o+g21R3D4rIEpe6Z85FRjSuMh45UlGGdaakLuNbIR9vN7tECtxbmKcg700uLWYdkc2wScUJy+29Qam9hnlU5R7E2iCRLEZH98ekF117FhrX2pxidPZWikGmPmpEil9afcKuUudXJs9uj7g8CZRULKHI5FEl4VjZh/miTbdVuumxUZ9BecFOORZc1CCRpEU7+SOvr2MfHX7grq4+g3JhNlASTCpVLmqCixK1huwvLSNyR7lcBCxQZJvY2IUYjU5pdNmW8aQxrHGn/Y9xb9VChQ0Y0XyNuEQH/pOzo2lXKa7uerk+kzZxQmPuW1JjNnb2lZLBvvXbMBd2a7qoArBITJFg0/UKST7dZHWGPZepmJWVSYJZYME5yQcAyjSJYEaj/BO733ATNpr5MslWoC6GnnEib9pykoSupTrO+vxjO7N2+7goASxH7IZkxqz/HS49VuVwQYXJi2WBRXABVIUsDPwMxkiEmEUEAZu8X39LPDcIztp2slKVNoeifbaHOpeisgbZNwu/P+9797nj/6Q/UH70uMDzHRyhRDVhDXKpdOVz+Vx1Ry0dUPBIvbSDYEMwAx/BE4bvSnMVMuiKxYqpAptikNaZIqvGw+rkaxfrRNeBa7/T+iQ6hHcgrjziVQ4ZMHlMsV5NYS1deU+9MMERoOe0sHx9tEEcBJvJ847zVT8mWvuG1cq95qxOqSasOr0S1t70kyDnUl+HU74L+LQ1lG7woyzQ1P6xH703RUTRTEVJzTnlIUkBBNpQqqR3kD7EBgPO85dHYI80Kw9S6vrT2sJavprAdtNy5tcFpy6vWIuNs8CH+1gsiGZ0l6DCsOqBChkg0TJBNkkxCSb9DNDzfMgooCRw9DwgC0/QB6PjbE9Gmx/i/Q7qwtlq1R7Zvube+8sXnzk7Z1eQi8dT9hwraFm8i6yz/NWU96EJdRq1H0EbPQ8Q+2TdGL08lQhp4DkwCHfZK6i3fHdVlzEjF+r+kvFu7KbwCv9DDasqb0iDcsOb28Zr9QQmSFDQf1ygwMQI4GD1PQI5B0UAePo05RTN4K2UiVBiVDXsCXveT7G3iOtlB0b7K4MXLwpXBRMLRxCTJGs+C1iHfsejo8nb9BghKEvAbsCRGLHoyHjcPOjs7mTozOB00ei54J08fQBaTDJQCkvjZ7rTlad041lbQ7sshyQLIlsjWyq/O/tOa2k3i2Or582f92QYGEKcYeyBFJ9Ms/TCkM7Y0LzQUMnkufSlIIw4cBxR0C5gCufka8f/opOFD2wrWINKgz5zOGM8O0WvUFNng3qLlI+0n9W/9uQXIDVsVOhwxIhMnvCoTLQguly3FK6UoUSTtHqQYqxE3CoUC0fpU80vs6eVf4Nbbb9hD1l7VxdVy11XaVd5R4x/pkO9y9o39qQSSCxAS8xcPHT0hXyRhJjQn1iZNJaYi+h5oGhUVLQ/eCFsC2PuF9ZTvMuqG5bXh194D3ULcl9z+3Wjgv+Po58DsHvLZ98L9qwNnCckOqRPjF1cb7R2UH0Eg8x+vHoEcfhm+FWMRjwxpBxoCzfyq99jye+616qDnUuXb40LjieOs5J7mTumj7IPwzPRc+Q/+vwJJB4kLYQ+yEmcVaxeyGDUZ9BjyFzsW3xPzEJAN0gnYBcIBsP3B+RP2wvLm75Tt2+vF6ljqlep36/Ps/O5+8WX0l/f6+nP+5gE6BVQIHQuBDXEP3hDBERYS3REbEdkPIw4KDKAJ+gYtBFIBf/7I+0P5AvcW9YvzavK78X/xtfFY8mHzxPR09mL4fPqx/O/+IgE7AysF4gZVCHsJTQrHCuoKtgowCmAJTwgHB5YFBwRqAssAOP+9/WT8N/s++n/5/Pi3+LD44/hL+eP5o/qD+3j8e/2B/oH/cwBQARICswIxA4kDvAPKA7YDgwM3A9YCZwLvAXUB/QCPAC0A3f+e/3T/Xv9c/2z/iv+0/+X/FwBIAHMAkgCjAKMAjwBmACkA2v96/wz/lv4b/qP9M/3Q/IL8Tfw2/EH8cfzG/EH94P2f/nr/agBpAW8CcwNqBEsFDgaqBhcHTgdMBwwHjgbUBd8EtwNhAugAV/+5/Rv8i/oW+cv3tPbf9VP1GPUz9ab1cfaQ9/34rvqa/LD+4gAfA1UFcgdlCRoLhQyVDUEOgQ5ODqkNkgwPCyoJ8AZwBL0B6/4P/EH5l/Yn9AbySPD77i7u6e0y7grvbPBR8qz0bveC+tH9QgG8BCMIWgtIDtMQ5xJvFF4VqRVLFUMUlxJREIANOAqRBqYClv5/+oH2vfJR71rs8eks6BvnyeY753PoaOoO7VPwIPRZ+N78jAFABtUKJQ8PE3EWLxkyG2ccwRw7HNUamRiUFdsRig3BCKIDWP4I+d3zAO+Z6szmt+N34R7gvN9U4ObhaeTM5/bryfAi9tj7vwGqB2oN0hK3F+8bWh/YIVUjwiMYI1ohkh7UGjkW5RD+CrEEMf6s91fxZOsD5l/hnt3h2j/ZyNiC2Wvbdt6P4pjnbO3f88D62wH4COEPXRY7HEkhYCVcKCQqpirdKcsnfiQMIJYaRRRHDdIFIP5r9vDu6ueR4RjcrNdx1IPS9NHL0gXVk9hc3T3jCuqR8Zj54AEqCjYSxBmYIHsmPiu4Ls0waDGEMCQuVyo4Je4epheZDwIHJv5H9avsl+RJ3fzW5NErzu/LRcs1zLvOxtI42OreqeY872D4zwFAC2oUBR3LJIEr7jDnNEo3AjgHN140FzBTKjwjBhvxEUEIQv5A9Inqa+Es2Q/STMwUyInFwcTGxZLIE80n06LaS+Ph7Bv3qAE5DHoWHCDRKFUwbDbkOpc9bz5hPXQ6uzVZL30nYh5NFI0JdP5W84zoad4+1VPN6cYywla/br6Dv5DCgMcuzmnW89+E6sn1bAEUDWUYByOmLPY0tDuqQK5DqESMQ2FAPDtENKwrtSGrFuQKuv6J8rPmlNuC0c7IvsGJvFy5ULhyubq8EsJSyUXSptwm6G30HAHSDSsaxiVIMF85wkA0RotJqUqCSR9GlkAQOcUv/SQIGUQME//a8QHl7Nj7zYLEz7wet5+zbrKYsxW3zryXxDfOZdnL5QnzuQByDskbVii1M409kUV/SydPbFA/T6lLw0W4PcUzNShhG6wNgP9J8XbjddaqynPAIbj2sSSuy6z5raaxuLcCwEbKNdZ0457xRAD1DkAdtSrpNn1BHUqFUH9U7FW+VPxQwEo5Qqc3XCu0HRkP/v/U8BPiLtSTx6O8trMTrfCobqecqHKs1rKXu3TGGdMm4S7wvv9cD5Ae4izjOSxFZE5CVY9ZJlv5WRBWh0+NRmg7bC79H4oQiwB88NjgGtK2xBW5k697qAakWaKEo36nLK5at8XCFNDi3rzuKP+mD7cf3S6hPJhIY1K0WVFeFGDtXuNaE1SxSgQ/ZDE7Iv0RKAFA8MXfOdAXwsy1uqsxpGyfk522ns6ivalQsz6/Ks2s3ErthP7UD7UgozAhP75LFVbWXcNismSUY29fYlihTnZCPzRqJG8T0wEf8Nrejc62v8qyL6g3oCSbHpk2mmaekKV9r+G7XsqF2tnr0/3oD4whNjJjQZxOelmmYeBm/WjrZ7FjblxYUrxF+zaHJt4UigIY8BjeFc2VvRCw8qSSnDKX/pQJlkuap6Hjq7O4tMdy2GzqF/3hDzoikzNkQzBRjVwgZaVq8Wzua6RnM2DSVdFIlDmQKEkWSwMs8H3d0su0u6GtCKJEmZqTN5ExkoCWBp6IqLe1LcV01gXpUfzCD8EiuzQkRXpTTl9CaBBuinCab0ZrrmMNWbNLBzyCKqwXFQRX8ArdxMoVun6rcZ9Oll2QzY2zjgqTsZpvpfCyzsKO1Kbng/uKDyEjrzWiRndVumEKax5xxXPqcpFu3GYFXF5OUj5bLAUZ5gSa8L3c7Mm4uKepMJ20k3+NwYqRi+qPq5eaomKwmcDD0lLmsPo8D1sjbTbeRydX0GN2bcxzoXbddYRxuWm2Xs9QcEAXLlMavAXy8JfcSMmctx6oRZt4kQGLFojOiCSN+JQNoA+ukr4W0Qvl2PnaDm8j9jbYSIpYj2WEbxh2GXlveBx0QmwdYQNTYEK1L5MblQZf8ZXc2cjDtuOmspmZj+eI0IVthruKmZLLnfururyIz9Pj/vhjDl4jTDeQSZ1Z9mYycQF4LnueelZ2dW45Y/hUH0QyMcMccAff8bfcncgttvald5gajjCH74NwhLKIk5DXmyeqFbsdzqziI/jaDSsjbjcGSmNaBWiBcoV523xofC94T3AGZapWqkWLMuAdSghw8vzclMjXtVillZf8jN+FdILZggmH5o4ympeopLnWzJnhSvdBDdUiXjc7Stpaumhvc6R6In7MfaZ5znGCZhhYAEe/M+keIQkR82LdvcjDtQelDJc/jPOEYoGpgcSFlY3fmEynari3y5vgdPaZDGAiHTcwSgRbF2n8c1x7/37Ifrl68HKrZz9ZHUjKNNwf9Qm/8+fdFsnutQSl25bii26EuoDhgOOEoozgl0imarfAyrTfpPXlC8shrDblSeFaHGkodK57c39cf2d7tXN/aB5aAEmsNbYgwQp69IrenslYtk2lA5fni1CEeoCCgGiEDYw3l46lpLb0yefe2/QlCxkhDDZcSXJayWjzc5h7fn+Gf7B7GXT9aLNaqEliNnYhhgs/9UrfVMoAt+KlgZdLjJmEpICNgFKE2Ivklh+lG7ZUyTXeG/RcCkwgQDWWSLhZIGhecx17H39Gf5J7HnQlafxaEkrqNhkiQQwL9iTgNsvjt8GmVZgQjUeFOIEBgaSEBIzplvyk0LXjyKDdZ/OMCWUfSTSWR7RYIWdrcjx6V36efg17wXP0aPlaPUpDN54i7wzf9hfhQcwAueinfpkyjlqGNILegVyFkYxGlyalxbWiyCvdv/K2CGceKjNcRmlXzmUacfd4J32MfSF6BHNraKhaKUpsNwQjkA229yDidc1Wulap+pqxj9GHmIMlg3uGf437l52l+rWSyNXcJvLdB1Qd4zHrRNlVKWRtb053kHsRfNB45nGJZwpa00ljN0kjIQ6Q+D3jzs7huwirx5yLkaqJYoXShP+Hzo4KmWOmcLa0yKLcnfECBy0ceDBGQwVUNWJnbUV1k3kwehl3Z3BOZh1ZPUknN2sjoQ5r+W3kS9Cgvf2s456+k+SLkYfnhuiJfJBxmnanKLcKyZHcJvEoBvUa6i5uQfFR818Ia9xyMnfqd/90iG67ZOJXZEi4NmkjDg9E+q3l6dGQvzGvSqFHlnyOI4pfiTSMipIwnNmoIriTyaXcxPBQBa4ZPS1nP55PZl1VaBZwb3Q/dYFyTGzQYllWSEcUNkMjZg8a+/vmpdOuwaKx+6MkmW+RFo07jOKO9pRGnomqXrlRyt/cdvB9BFoYcisyPRBNkVpPZfZsTXEzcqNvsmmPYIJU60U8NfYiqQ/r+1ToftX5w02086ZSnLqUZpB2j/CRvpeyoIas3LpFyz/dPvCvA/sWjCnTOklKeFf6YYBpz23JbmZsvGb4XV9STEQuNIMi1A+1/LfpcNdsxi+3LqrNn1yYEpQPk1uV4Jpzo9CunLxtzMbdH/DpApQVjidMOE1HHVRZXrVl92kCa85obmMOW/BPa0LrMugh6A92/SLredkFyUS6qK2So0+cFZgDlyCZWp6GpmSxnb7KzXTeGPAtAicUeyWiNR9Eg1BwWpphymXiZtxkyV/RVzZNSkBzMSYh4Q8t/pHsltvBy4q9X7Gep5GgbJxOmz2dKqLrqUK038Bdz0vfLPB8AbYSVCPWMsJAsExDVjJdSmFtYpRgz1tGVDRK6T3HLzsgwA/Y/gPuxd2czvzAT7Xtqx2lE6Hsn6+hTKadrWi3X8Mj0UngWvDYAEQRHiHsLzs9pkjUUYJYfFynXfpbhVdtUOtGSjvmLSgfhA91/3bvA+CU0ZjEc7l5sPCpB6bapHGmvqqcsdS6HcYe03DhpPBCANIP2h7nLIw5aUQqTY5TZFeSWBBX7VJKTF1DbTjSK+0dLA8CAOfwTOKk1FnIx71AtQSvQqsUqoGre6/jtYO+F8lL1cDiC/G8/2IOjBzLKbo1/j9ISFpOB1I1U9xRCk7fR40/VjWLKYoctw6AAFTyn+TL1zvMSMI9ule0wbCUr9mwgbRvunPCS8yq1zfkjvFH//cMNRqbJskxaTsyQ+tIaEySTWFM4kgxQ347BTIUJ/8aJg7tALzz+OYD2zvQ8MZqv+G5frZXtXW2zLk+v6HGuM862tXlLvLk/pML2hdaI7strjbuPUZDjkawR6RGd0NCPjI3fi5sJE0Zdw1GARz1VelL3lTUvMvExJ+/dLxYu1K8Vr9MxArLWtP53Jvn7PKU/jcKfBUNIJcp0jGAOHA9fUCSQapAzj0XOa0ywiqXIXQXqgyMAXP2s+ue4YPYp9BFyozFn8KRwWnCHMWUyavPL9fk34bpx/NY/uUIHxO1HF4l2SztMm43Ojo/O3c67De0M/Et1CaVHncVwAu+Ab/3D+765MTcrdXpz6LL+cj+x7bIGcsSz3/UNdv74pbrwPQx/qAHxBBXGRYhyCc6LUUxyzO7NBE01TEcLgQptyJpG1UTuQraAf74Z/Ba6BLhyNqp1dzRfM+YzjPPSNHC1IXZaN885srt1vUg/mgGbw72FcMcpCJtJ/sqNS0MLn0tjytUKOgjbx4WGBARlQngAS76ufK762rl9N+C2zXYI9Za1dzVpNeg2rfexeOj6R/wCPcl/kAFIQyUEmgYcR2KIZUkfiY4J8EmHyViIqEe/RmcFKkOVAjPAU/7AvUb78fpLOVu4abe6Nw+3KvcKN6m4BHkSegu7ZbyVvhB/igE3gk3DwoUNBiXGxoerB9EIOIfiR5JHDQZZxUAESMM+AaoAV78P/d28iXubOpn5yvlxeM/45njzuTR5o/p8ezb8Cv1wPl0/iIDpwfgC60P8hKYFY0XxRg3GeUY1BcPFqYTrxBDDX8JgQVqAVr9b/nI9YDyr+9p7b3rtepX6qLqkesZ7S3vuPGm9N33RPu+/i8CfgWSCFQLrw2UD/YQzhEXEtIRBRG4D/oN2QtpCb8G8QMVAUP+kPsQ+db28fRu81fysvF/8b/xa/J78+b0m/aO+Kv64fwe/1ABZgNSBQMHcAiPCVoKzQroCq0KIQpMCTUI6gZ1BeUDRwKpABj/n/1J/CH7LPpy+fT4tPiy+On4Vvny+bX6lvuN/JH9l/6W/4YAYQEgAr8COgOPA78DygOzA34DMAPNAl0C5QFqAfQAhgAmANf/mv9x/13/Xf9u/43/uP/p/xsATAB2AJQApACiAIwAYgAjANP/cf8D/4v+Ef6Z/Sr9yfx9/Er8NvxE/Hf8z/xN/e79sP6N/38AfwGFAogDfQRdBR0GtQYdB1AHSQcEB4EGwgXJBJwDQwLIADX/lv35+2r6+fix96D20PVK9Rb1OfWz9YX2q/ce+dX6xfze/hEBTwOEBZ4HjAk8C58MqA1LDoEORQ6WDXUM6gr+CL0GOASBAa7+0/sG+WD29vPd8Sfw5e4j7urtP+4i74/wf/Lj9Kz3xvoa/o0BBgVpCJsLgg4EEQ0TiRRrFagVOxUlFGwSGhA+De0JPwZQAj7+KPou9nDyDe8h7MXpDugM58vmTueV6JnqTu2f8Hf0t/hB/fEBpAY0C30PXROyFmIZVBt3HL4cJRyuGmAYSxWFESgNVggzA+b9l/hx853uQuqC5n/jUeEN4L/fbOAT4qnkHehX7DfxmfZV/D4CJwjiDUATGBhBHJgfAiJpI74j/SIpIUseehrOFWwQewooBKX9IvfT8OvqmOUG4Vrds9oq2czYn9mh28Pe8eIN6PDtbvRX+3MCjglwEOEWrxyrIasljig7KqIqvSmRJyokoR8XGrUTrAwvBXv9yfVV7lznE+Gv21vXO9Rp0vjR7dJE1e3Yz93G46XqOPJH+pEC2QrdEl4aICHsJpUr8i7oMGQxYDDgLfYpvSRcHgEX5g5HBmj9jPT56/LjuNyD1ofR7M3Ry0rLXMwDzy3Tu9iF31nn+u8n+ZkCBwwoFbMdZiUCLFExKjVqN/433zYSNKovyCmXIkwaJxFuB2z9bfPA6bHgiNiG0ePLzcdnxcXE8cXiyIbNutNQ2xDktu3694oCGA1PF98gfinmMNw2Lzu8PWs+NT0gOkI1vy7GJpMdbROiCIX9a/Ks55vdiNS7zHPG4sEvv3K+sb/owv7H0M4p18zgbuu/9mYCCg5QGeAjZS2WNTA8/kDXQ6VEXEMGQLg6mzPjKtMgthXjCbT9iPG+5bHautAnyDzBMbwwuVO4o7kYvZvCAcoV05HdJul59SwC3g4rG7ImGTEOOklBkUa5SaZKUEm9RQhAWjjtLggk/xctC/j9w/D34/bXIc3Mw0G8vrZus3CyzLN6t2C9VMUYz2Pa3uYq9N8BlA/eHFUplzRLPiRG40taT2pQCk9CSyxF9jzdMi8nRBqADE/+HPBX4mzVv8muv4e3jbHvrcysL64RslS4y8A1y0TXm+TT8n4BLBBpHscr3DdJQrxK8lC3VO1Vh1SOUB9KakGxNkQqhBzaDbn+k+/h4BPTmMbQuxGzoqy1qG2n1KjirHqza7xxxzjUX+J38QwBphDLHwYu5joGRg9PuFXLWShbwFmeVd5OtEVkOkUtvB45DzT/KO+T3+7QrMM1uOOuAqjHo1aivaPzp9iuObjQw0PRLOAX8IgAAxEFIREwsz1/SRhTMlqTXhhgs15sWmNTzUnzPS4w6SCaEL//2u5u3v3O/cDftACrr6Mnn46d8J5Ho3GqObRVwGfOBd617vb/QhEUIugxQkCyTNVWXF4KY7hkWWP1XqtXtE1aQfwyCSP8EVgAqO5z3UDNjr7QsWqnrp/bmhaZcZrjnkmmbrADvajL7dtU7Vb/ZhH7IoozkUKcT0NaM2IsZwVpsGczY7FbYlGVRKs1GCVcE/8Aku6h3LrLX7wLrySkAZzklvSURJbKmmai3azfuQrJ59n166n+bxG4I/U0n0Q8UmBdtWX2avxss2skZ3Ff1VShRzk4FSe4FLIBl+7422nKcrqQrDChrJhGkyuRbZICl8qeiKnsto7G9deb6vH9XRFNJCs2bEaQVCpg3mhmbpdwXm/DauhiClh6SqI6+ygPFm8Cte5420/Jx7hiqpGesJUFkL6N7o6Nk3mbdaYttDjEGtZJ6S/9MxG5JCo39UeXVp9irGt5cdVzr3INbhJm/FoeTeM8yipdFzQD7O4g22vIX7eCqEecD5Mija+Ky4tvkHaYpaOmsQzCWdT/52f88BD+JPM3O0lRWL1kHm4rdLR2o3X/cO1oqF2IT/o+fiyiGAAEOu/u2r3HO7bwplWazJCgigKICImqjcWVHaFZrwvAs9LB5pj7lxAcJYY4Pkq7WYNmMnB8di95NniWc3RrDGC3UeRAFC7ZGdAEnu/k2kXHWbWtpbuY6I6BiLmFpYZBi2mT3p5IrTm+LdGQ5cb6KRAUJeQ4/krWWvBn5nFpeEZ7Z3rQdaVtJWKoU55Ciy8CG6QFFvD+2gHHu7S6pHqXZI3GhtSDp4Q3iWOR7Jx4q5i8x89w5PL5pw/oJA05e0uiWwRpOXPxefd8M3yqd39v8GNXVSVE3zAaHHgGoPA82/LGX7QWpJOWQYxxhVeCDYOOh7aPSJvqqSq7hM5h4x75FA+YJAM5tksfXL9pLHQTe0B+mX0ief5wa2XEVnhFDzIfHUsHPPGd2xXHRrTAowWWgIuChEOB24FHhmWO9pmgqPO5Z81m4kz4cA4mJMY4r0tNXCBqvHTPeyB/l343eiFylGbqV5RGGTMQHhsI5/Ef3GvHbbS5o9GVIIv6g5eAEYFkhXCN9pidp/O4ccyB4X73vg2VI1g4Z0stXChq63QjfJd/LX/neudyamfKWHhH+jPpHucIoPLA3PHH1bQApPWVIYvZg1WAr4DnhNqMS5jipiy4pcu04Lb2/wzkIro34ErAW9hpuXQRfKV/Wn8ye05z6mdgWSFIsTSpH6wJZfN/3abIe7WTpHGWhIsfhHyAt4DPhKOM9pdwpqG3BMsB4PX1NQwXIu82G0oHWzBpJ3SYe0h/HX8Xe1VzFGitWY1IPDVPIGgKM/Ra3ojJXrZxpUWXRozLhA2BKYEdhcuM95dKplO3kMpp3z71YwsvIfc1GkkEWjFoNXO5eoN+d36Vevxy52etWb1ImTXYIBoLCfVP35XKfLeZpm6YaI3dhQeCBILShVSNUJhvpkO3Ssrv3pL0igouINU030e4WN9m5HF1eVV9aH2teUNyY2diWa1IxzVCIb8L5fVc4MzL1LgIqOqZ545Th2mDR4Pthj6OAZnhpnK3NMqU3vPzrAkWH4oza0YmVzllOHDNd7978XtgeClxhmbJWF5IxDWOIVYMxfZ+4SnNY7q9qbmbwZAriTKF8oRtiIiPCZqgp+K3T8pZ3mTzygjpHRoywURPVUJjMG7EdcR5EnqtdrBvUWXjV85HkDW3Id4Mp/e14qzOJ7y2q9ed9ZJli1+HA4dSijGRaputqJK4nMpA3uXy6AepHIYw5EI2U/1g0Gtbc2V3z3eXdNdtxWOwVv5GKjW/IVQNifj941HQHb7vrUKggJX8jfCJeYmZjDmTIp0HqoK5HMtK3njyBwdZG9Au1UDdUG1eGmmVcKN0J3UecqBr4mEwVe1FkTSjIbcNaflV5RbSQ8BmsPeiYJjwkOGMUYxDj56VMJ+tq7W6z8t53h/yKAb7GfwsmD5JTpNbEmZ0bYJxHnJFbw1pqV9iU5pEwzNiIQYORvq55vnTlsIYs/SlkZs9lDGQio9Lkl+Yk6GhrSi8t8zM3tvxTgWQGAsrMDx6S3NYuWL8aQVut24NbB9mG11JUQZDwjL8ID8OHfsp6PfVFMUCtjWpEZ/hl9yTIJOxlXqbS6Tfr9y90s1F367xewQcFwEpnzl1SBFVE18vZi1q82p6aNhiOlrlTjJBjTFwIGAO7Pug6QzYuMchubes26LWm9+XEZdymeyeVadostC/Ic/l35jxrwOhFeEm6DY9RXBRJVsRYgBm1maNZDpfCFc4TB8/JDC9H2oOs/wf6zjagMpxvHew7aYboDacWZuKnbSir6o6tQPCpNCr4Jvx7gIhFKwkEDTWQZRN8VamXYBhY2JLYElbh1NCScw8hy7jHloObv2h7HXcac3vv2+0QaurpN6g9Z/2oc6mV65TuHTEW9KZ4bjxOQKdEmYiGDFCPoBJfFLyWLFcn122WwdXuU8GRjw6tyziHTAOHf4l7sPeb9CXw5241a+CqdOl4aSzpjirSrKxuyPHRNSu4u/xkAEZEREgBC6HOjlFyk35U5hXjFjRVndSoUuGQm83tCq5HOsNv/6p7x7hj9Nlx/y8pLScrg+rGaq9q+2vhrZTvw3KYNbq40Ly9gCWD7Ed2CqnNsNA4EjATjlSMFOjUZ1NQkfFPmk0gChpG4sNUf8q8YPjxtZWy4nBqbnzs5CwmK8Qseq0B7s0wzDNrNhN5bDybAAXDkgblyemMiI8wUNMSZhMkE0tTH1IoELEOikxHCbzGQ4N0/+m8u/lEdplzz7G4L6DuU+2WbWntiy6yr9Tx4vQKNvX5jvz9P+eDNgYRCSJLlo3cz6gQ7tGr0d1RhtDvT2HNrMtiCNWGHUMQQAc9GHoa92P0xfLRMRIv0i8Wbt+vK2/y8StyxvU092H6OPzjv8sC2YW4yBUKnAy+zjEPadAkkGAQHs9njgSMgoqxyCTFr8LngCJ9dTq0eDP1xDQ0Mk8xXbCkcGQwmvFBso+0N7XquBc6qf0O//ECfMTeB0KJmktXTO6N2E6QDtSOqI3RzNmLS4m2h2sFOwK5wDs9kbtQeQh3CTVfs9Zy9PI/MfZyF/LeM8D1dHbrONV7Ij1/P5nCIIRBRqwIUkony2KMe4zvDTxM5QxvC2JKCUixBqhEv0JHAFD+LXvtueC4E7aS9Wb0VrPls5Sz4XRHNX42fHf1uZx7oX20v4XBxUPjhZKHRUjxSc4K1QtDi5hLVcrASh9I+8dhhd0EPIIOwGM+R/yLevs5IvfMNv81wXWWNX21djX7doZ3zvkKOqv8J73vv7VBbAMFxPcGNId1iHJJJkmOiepJu8kGyJGHpEZIhQlDssHRAHF+n/0o+5d6dTkKeF33s/cPdzA3FPe5+Bj5Kzone0O89P4wP6kBFQKow9qFIUY1RtFHsIfRiDOH2IeDxzqGA4VnBC3C4gGNwHu+9b2FfLP7SXqMOcF5bLjPuOr4/HkBOfR6UDtM/GL9SP62f6EAwQINQz4DzETyRWvF9YYOBnWGLUX4RVsE2oQ9gwsCSsFEwEF/R75fvVA8nnvP+2h66fqV+qw6qzrQO1f7/Px6PQl+I77CP93AsMF0QiKC9wNtw8OEdkRFhLGEe4Qlw/QDagLMgmEBrQD2AAI/lj73fiq9s30U/NF8qnxgPHJ8X7ylvMH9cP2ufjZ+hH9Tv9+AZEDeAUlB4sIpAlnCtMK5wqlChIKNwkcCMwGVQXDAyQChgD3/oH9L/wK+xr6Zfns+LL4tPjw+GH5AfrG+qr7o/yn/az+q/+ZAHIBLwLLAkIDlAPBA8kDrwN4AygDxAJTAtoBYAHqAH4AHgDR/5b/b/9d/17/cP+R/7z/7f8fAFAAeQCWAKQAoQCJAF0AHQDL/2j/+f6B/gf+kP0h/cL8d/xH/Db8R/x9/Nj8Wf39/cL+of+UAJUBmwKdA5EEbgUrBr8GJAdSB0UH+wZzBq8FsQSBAyUCpwAT/3P91/tK+tz4mPeM9sL1Q/UW9UD1wvWb9sf3QPn9+vD8DP9BAX4DsgXJB7IJXAu5DLkNVA6ADjsOgg1YDMUK0QiKBgAERgFx/pb7zPgq9sbztPEI8NDuGe7s7UzuO++08K3yG/Xs9wv7Y/7XAU8FsAjdC7wONREyE6IUdhWlFSoVBxRAEuIP+wyiCe0F+gHn/dL52/Uk8sru6eua6fLnAOfO5mLnuejN6o/t7fDO9Bb5pP1VAgcHkwvUD6kT8haTGXQbhRy6HA4chBolGAEVLRHFDOsHwgJ0/Sf4B/M77uvpO+ZI4y3h/d/D34bgQeLr5HDoueyl8RH30vy8AqMIWA6tE3gYkBzVHyoieiO5I+Ei9SADHh4aYhXyD/cJngMZ/Zn2UfBz6i7lruAX3YfaFtnS2L/Z2dsT31bjg+h17v707fsLAyQK/hBkFyIdCiL0Jb4oUCqcKpspVCfUIzQflxklEw8MjATW/Cb1u+3O5pfgSNsM1wfUUtL/0RLThtVK2UTeUORA6+Dy9vpDA4gLgxP2GqYhXCfqKyovATFdMTkwmi2TKUAkxx1bFjIOiwWq/NHzR+tP4yncDNYs0bDNtstRy4XMTc+W00DZI+AK6Lrw7/ljA84M5RVhHv4lgCyyMWo1hzf3N7M2wzM7Lzsp8CGRGVwQmgaV/Jry+Oj53+fX/9B8y4nHSMXNxB7GNcn7zU/UANzW5Izu2fhtA/YNIhiiISkqdDFJN3c73T1kPgU9yTnHNCIuDCbDHIwStweX/ILxzebP3NTTJcwAxpbBDL95vuO/QsN/yHPP69em4VrstvdfA/8OORq2JCIuMzapPE5B/UOeRClDpz8yOvAyGSrvH8AU4Qiv/IjwyuTR2fTPgse9wN27CblauNi5er0nw7PK6NN/3ibqhvY9A+oPKRycJ+gxujrOQelG4kmgShlJWEV3P6E3ES4RI/MWFgrd/K3v7eID10rMGMO3u2G2QrN2sgS04rf3vRPG+89j2/PnTPUFA7UQ8R1SKnY1Bj+0RkRMiE9lUNFO1kqRRDA88jEmJiUZVAsf/fHuOuFl1NjI7L7ytiixvq3RrGqugLL0uJfBKMxW2MPlCfS5AmERkB/WLMw4EkNYS1tR6lToVUtUHFB7SZhAtzUrKVMbmgx0/VTusN/70aDFALtxsjWsgKhwpxGpVq0jtEO9csha1ZnjwPJaAu8RBSEnL+Y73Ua1TylWA1olW4NZJ1UxTtZEXDkcLHkd5g3c/dXtUN7Ez6TCWLc4ro2njaNZovyjbKiIrxy53sR00nfhcvHpAV4SUSJEMcI+Y0rJU6pa0F4XYHNe8FmvUuZI3jz2LpYfNg9V/nXtGt3Czee/9bNKqjOj6J6OnTCfxKMpqya1b8Gnz2DfIfBoAbASciMqM2BBok2QV9xeS2O5ZBljdV7wVsJMOUC2MaYhhxDe/jLtDtz2y2q92rCqpiqfl5oVmbKaZJ8Ip2SxKb71zFfd0O7YAOQSaCTbNL1DmFAIW7ticmcIaW9nsGLwWmhQakNYNKcj2BF2/w3tLdthyi67Ca5ao3abm5bxlIaWT5sqo9utD7tiyl7bgO05APwSNCVVNtdFQ1MvXkRmQmsAbXFrnmarXtRTbEbaNpclJxMZAAPtddoDyTS5hKtdoBmY+ZIlka6SiZeTn46qJbjyx3nZM+yQ//gS1iWXN7BHolUBYXRptm6fcB1vO2odYgFXPUk5OXIncRTJABTt6Nndx363TKm2nRaVs4+1jS+PFpRGnICnbrWmxanX7Orb/toSTyaiOERJs1d+Y0lszXHfc25yg21DZe5Z2UtyOzYptBWCAT7thNntxgu2Yqdkm3CSy4ykigyM+ZBHmbak7rKBw/HVreke/qMSnyZ2OZRKdVmkZcFuhHTAdmJ1dHAaaJVcPU6BPeEq7xZEAoLtSNk1xt20yKVrmSeQRYr0h0eJNY6ZljGiprCIwVTUeOhZ/VQSxyYSOqBL6FpxZ9pw2XY+efd3CnOfavZeZ1BkP3AsHhgLA9ztNNm0xfOzfaTKlz2OIoioheSGzYs+lPafm668v9TST+eP/O4RyCZ5OmhMClzlaJNyynhYeyl6RHXPbAxhVFIZQeEtQBnXA03uRtloxU6zg6ODlrSMY4bBg+SEw4k5kgaezqwfvnPRNObC+3MRoiapOuxM3Fz+aexzVnoMffd7HneobtViAFSdQjEvUxqlBNHuftlTxeyy2aKWlY2LCoVBgkmDGYiNkGScQqu1vDTQKuXz+uUQWCalOixNXl2+auJ0fHtYfl99mHgncE9ka1XtQ14wVBt0BWjv2tlxxc2yfqIElceKGIQqgRSC0YY7jxKb+ql/uxrPMuQl+kYQ6yVsOilNkV0ja3d1O3w7f19+rnlLcXllkVYIRWUxQhxCBhDwWNrDxfGydKLMlGSKjIN7gEiB7IVFjhKa9qh/uiXOT+NZ+ZYPXCUBOuVMdF0va6l1kny1f/d+YHoTck9mcVfrRUYyGh0MB8fw99pGxlWzt6LtlGKKaYM2gOSAbYWtjWWZOqi4uVnNguKR+NgOrSRmOWBMCl3hanp1gnzFfyd/rXp8ctJmCViVRv4y2x3RB4vxttv6xvqzSaNolcOKrINbgOmAUoVzjQ2ZxqcrubbMzuHP9w4O4COaOJxLUlw6aul0DHxrf+1+lXqGcv9mWFgFR4szgx6PCFvykdzdx920JqQ6loOLVoTqgFiBnYWZjQuZnKfauD/MNOEW9zoN9iKhN5tKT1s9afhzLnuofkl+F3oxctVmXVg4R+wzDx9ECTTzid3syP21TqVil6SMZoXhgTCCT4YejmCZvafGuPXLteBm9l0M8iF9Nl5JAlrqZ6ly7Hl8fT19Mnl8cVVmFlgtRx80fx/uCRT0md4lyle3v6bfmCKO24ZBg3CDZocDjwyaKqjvuNnLVODC9XoL1iAuNedHblhDZvxwRnjoe8l76XdncH5lg1flRiM00B+LCvr0wd+Iy+m4d6ivmv2Ps4gIhRiF4ohHkA6b4qhXue3LE+Ar9ZIKox+5MzlGk1ZKZPNuPXbvee55O3bzbk9kpFZdRvczAiAbC+P1/+AQzbK6c6rQnDKS7IozhyaHworrkWic6Kn/uTLM8d+k9KgJXB4eMlZEdlQCYpJs1HORd613KXQgbcpieVWVRZkzEyCaC872T+K8zq+8saw+n7+UhI3DiZiJBY3tkxmeOavnuqjM8d8t9L0IAx1hMEFCGFJuX9ppDnHRdAl1tXHvau9gAlSNRAozAiAIDLj3sOOK0Ny+Lq/4oaGXeJCzjG6MqY9Llh+g16wPvFDNFODJ89MHmhuDLvw/fU+PXM5m7G2xcQNy4W5jaL5ePlJFQ0kyzR9iDKD4H+V30jjB57H7pNaaxpMCkKOPrZIFmXqiwK53vSvOW+B48+0GJBqILIo9p0xqWXJjcmo0bp5urmt8ZTlcL1C9QVQxdB+oDIT5m+aA1L/D2bRCqFmea5eskzeTDpYZnCil9LAevznPxuA98wwGoxhyKu86mUkCVshfo2Zeat1qIGg8YmJZ1032Py0w9h7ZDGL6Ieii1m7GAbjLqymiY5uulyWXyZmEnyiocbMFwXrQV+EY8zIFGhdEKCw4WEZZUtVbgmIwZsNmOWSnXjpWNUvwPdIuUx7yDDj7runb2ELJXLuSr0Cmq58GnGqb251Eo3irNrYqw+7RDeIK82AEihUBJkc15UJ0TptXFF6wYVNi/F++WsNSTEisO0UtiR3zDAX8QOso2zjM5b6Ts5uqPqSuoASgQqJVpxWvQrmNxZTT6uIW85kD9hOrI0EyRj9XSiBTXVnhXJFdbFuEVgBPHkUrOYYrmhzbDMb81eyG3U3PmcLLtzavGamjpe2k+aa2q/2yk7wsyGzV7eM6894CYBJGIR4vfjsGRmZOYFTGV4JYjlb9UfRKrEFvNpUphBupDHv9a+7y333SdcY1vAy0N67hqiKq/qtjsC23JsAFy3bXFuV58zACyhDUHuIrkDeEQXRJIk9mUihTZVEsTaFG+T15M3MnSBpdDCH+APBp4sTVdMrNwBq5k7NjsJ+vS7FXtaK7+MMYzrDZZebT85IBNw9YHJAogTPXPExEqEnETIlN9EsVSAtCBzpLMCIl5hj1C7j+kfHp5CDZks6OxVq+Krkktl+13baQulnACMhh0Rjc2udJ9AMBqA3VGSslVS8DOPU+90PlRqpHQka8QjU92jXnLKIiXhdyCz3/HPNu543cy9J1ysfD9L4gvF27rrwIwE3FUszf1K/edOna9IYAIQxOF7ghDysMM3M5FD7OQI9BUkAlPSI4dDFPKfYfsRXTCrH/oPT26QbgHNd7z13J78RQwpTBu8K8xXzK09CP2HHhMuuH9RwAogrFFDketCb3LcozBDiFOj07KjpVN9gy2CyHJR4d4RMYChEAGvZ/7IrjgNue1BfPE8uxyP7H/siny+HPiNVv3F7kFe1Q9sb/LQk+ErIaSCLIKAEuzDEPNLs0zTNQMVotCyiQIR0a7RFBCV4AifcF7xTn89/X2e/UXdE7z5fOcs/E0XjVbdp84HPnGu8194T/xQe6DyYX0B2FIxsocitxLQ0uQy0cK6wnECNuHfUW1w9OCJYA6viF8aDqcOQj3+Daxtfq1VjVEtYP2Dzbft+y5K7qQPE1+Fb/awY9DZkTThkyHh8i+ySyJjknjya9JNMh6h0kGacToQ1AB7gAPfr+8yzu9Oh85OXgSd643D3c2NyB3ijht+QP6QzuhvNR+T//IAXKCg8QyRTTGBIcbh7XH0UguR85HtMbnhi1FDgQSwsXBsUAf/ts9rTxe+3e6fnm4OSf4z/jvuMW5TnnFeqP7Yzx6/WH+j3/5gNhCIoMQxBvE/kVzxflGDcZxRiVF7MVMRMkEKgM2AjUBLsAsPzO+DX1//FE7xftheua6ljqvurI62ntku8v8iv1bPjX+1L/vwIGBg4JwAsJDtkPJBHkERUSuRHWEHYPpQ12C/sISQZ3A5sAzf0h+6v4f/ap9DjzNPKh8YLx1PGR8rLzKvXr9uX4CPtB/X3/qwG8A54FRQemCLcJdArYCuQKnAoDCiEJAQiuBjQFoQMCAmQA1/5j/RT89PoJ+lj55fiw+Lf4+Pht+RD62Pq++7j8vP3C/r//rACDAT0C1gJLA5oDwwPIA6wDcgMgA7sCSQLQAVYB4QB1ABcAy/+S/23/XP9f/3L/lP/A//L/JABUAHwAmAClAJ8AhgBZABcAxP9g/+/+d/79/Yb9Gf27/HL8Rfw2/Er8g/zh/GX9Df7T/rT/qQCrAbECsgOkBH8FOQbKBioHUwdBB/IGZQacBZoEZQMGAoYA8P5R/bX7Kvq/+ID3efa09Tz1FvVH9dD1sfbk92P5JPsc/Tv/cQGuA+AF9AfYCX0L0gzKDVwOfw4wDm0NOwyfCqMIVgbHAwoBNP5a+5L49PWW843x6e+87hDu7u1b7lXv2fDd8lT1LPhR+6z+IQKZBfYIHQz1DmQRVxO6FIEVoRUZFecTExKpD7gMVgmbBaQBj/17+Yn12PGH7rLrcOnW5/Tm0+Z3597oAevR7TvxJvV1+Qf+ugJqB/ELKxD1EzEXwxmTG5IctBz2G1oa6he1FNQQYgx/B1ICAv24953y2u2W6fTlEuMK4e7fyt+h4HHiLuXE6BztFPKJ90/9OwMgCc4OGRTWGN4cECBQIoojsiPCIsAguR3BGfQUdw9zCRQDjvwQ9s/v/OnG5Fjg1txe2gXZ2tjg2RPcZN+84/vo++6P9YT8pAO5CowR5heUHWgiOybsKGMqkyp3KRUnfCPGHhUZkxJzC+kDMfyF9CLtQuYc4OLav9bV0z7SCNI508nVqdm73tzk3euJ86b79QM2DCgUjRsqIsknPCxgLxcxUzEPMFItLSnAIzIdsxV9Dc8E7PsX85fqruKb25jV1NB3zZ7LW8uxzJrPAtTI2cLgveh68bj6LgSUDaEWDR+VJv0sETKnNaE37TeFNnIzyS6rKEch0xiRD8YFv/vI8THoQ99H13zQGMtIxyzF18RPxovJdM7m1LLcneVj77n5TwTUDvUYYiLRKgAysze8O/o9WT7SPG85STSDLVEl8RuqEcsGqfuY8PDlBNwj05PLkMVNwe2+g74YwKDDA8ka0K/YguJH7a34WQT0DyIbiiXdLs42Hj2bQR9Ek0TyQkY/qDlCMkwpCR/IE98HqvuI79fj89gxz+DGQsCMu+W4ZbgRuuC9tsNpy73Ubt8p65P3TQT1ECcdhCizMmM7T0I+RwhKlUrfSO9E4j7lNjQtGCLnFf4IwvuX7ubhEdZ2y2jCMLsIthqzgLJAtE+4kb7WxuHQZdwK6W/2KwTVEQMfTStTNr0/QEehTLNPW1CTTmZK8kNmOwUxGyUFGCgK7vvG7R7gYdPzxy6+YLbHsJKt2qyprvOymLlnwh3Nadnt5kD18wOWErYg5C25OddD70u/URlV31ULVKZP00jDP7o0DiggGloLMPwV7YHe5NCrxDW61LHNq0+oeadSqc+t0LQfvnbJf9bV5Ar0qAM3Ez4iRjDiPK9HV1CVVjZaHVtAWatUgE31Q1I47yo1HJMMhPyE7A7dnc6gwX+2ka0dp1ejYKI/pOqoPrADuu/FqNPE4s/ySgO5E5sjczLOP0JLdVQeWwdfEGAvXnBZ9lH6R8c7ui1BHtEN7PwR7Mfbi8zUvg+zmKm7oq6elJ12n0ek5asWto3C6dC94I/x2gIcFM0kajR6Qo5OR1hXX4djtGTTYvBdMFbNSxY/bDBCIBIPZP2+66var8pJvOiv7qWrnliaGZn5muufy6deslK/Rc7D3k3wWgJhFNMlKTbkRJBRyFs9Y7NnBWkoZydiKVpqTztCAjM1IlQQ6/2I67rZDMkAugytlqLwmliW85TNltmb86PdrkO8vsvY3AzvywGIFK4msTcMR0ZU+F7NZodrAG0qaxJm313NUjNFeTUXJJURgf5w6/XYoMf6t3yqkJ+Ml7GSJZH2kheYYaCXq2K5WMn+2sztLwGSFF4nADnwSK9W02EEagBvoHDVbqxpTGH0VftHzTfnJdISJP9z61rYbcY4tjqo35yDlGaPs413j6aUGZ2QqLS2Fsc52ZHshwCBFOMnFzqPSspYWGTfbBty43MncvNsb2TbWJBK/TmhJwoU0v+S6+rXcsW7tEemhprWkXuMn4pTjIqRHZrLpTq0+sSL113r1f9VFD4o9jrpS5VahWZdb9d0xnYcdeNvQ2d+W+5MBDxDKTsViADL66TXsMSDs6SkhZiHj/CJ7YeOiceOcpdLo/ixCMP21TDqGv8PFHAonDv+TA9cWWh8cTB3R3mxd3hyxWnaXRJP4T3KKmIWRgEc7IfXJsSRslKj3paYjcmHnoUph1+MGZUTofKvQsF91A/pWP6yE3koCjzOTTld02k7cyV5ZHvkebJ09GvtX/tQkD80LH0XCwKF7JHX08PksVGikZUKjAaGtIMnhVWKFZMmnyiuqr8i0/vnkv0/E1soQjxYThJe82qYdLV6Gn20e412zG21YaVSEEF/LYoY0wID7cLXt8N8saGhoJTeiqqEMoKLg6qIaZGFnZ+sQ77n0fXmyPy2EhcoQzyeTplet2uTdd57aX4dfQd4S28uYw1UXkKpLocZnQOV7RnY0MNYsUKhCZQVirSDF4FUgmGHF5AznFirD73P0AHm/fsbEq4nDzygTtBeIWwrdqB8Tn8gfh55cHBXZDNVd0OvL3MaaAQ67pTYHsR4sTOhzZOuiSaDZoCFgXuGII8zm1SqELzczx/lNPtuESInqDtfTrZeL2xgdvt8y3+7ftN5OHEvZRNWW0SPMEobMAXv7jHZn8TasXSh65Oqif+CH4AfgfmFho6EmpepSLsPz1LkbPqxEHUmDjvcTU5e5Gszdu183X/tfiJ6pHGzZa1WBkVIMQsc9gWz7+7ZUsV+sgOiZJQIikCDQYAigdyFSo4qmiGpubprzp3jqvnmD6clQzoZTZhdP2uldXl8hn+1fg16sXHjZf9WeEXXMbUctQaE8MvaNMZgs+CiNZXHiuiDzYCOgSSGbI4lmvSoZbrxzQDj7vgQD7wkSTkXTJVcQmq1dJ57xX4VfpJ5X3G+ZQdXr0U8MkUdbQdf8cTbRceBtAmkXZbmi/aEwoFjgtKG7Y51mhCpTLqizX3iOvgwDrUjIjjYSkdb72hnc116nH0MfbF4rnBCZcZWqkV0MrodHAhE8tncgsjdtXul2pdkjWqGIIOgg+WHzo8cm3epcLqBzRfikfdHDZQi0DZfSbFZR2e6cbd4C3ybe2x3nm9wZDlWZ0V/MhIewAgv8wbe6clztzWnrJk/j0CI5IREhV2JDZEZnCqq0bqOzc7h8/ZZDFshVTWtR9NXTWWxb692E3rDecJ1MG5IY2FV50RaMkseVwkg9Erfd8tBuTWpz5t1kXmKDodPhzmLq5JsnSercbvKzaThY/ZnCw0gtDPERbJVAmNObUd0t3eGd7RzY2zKYT5UKEQGMmUe3wkT9aLgKs1Du3erQJ4ElBGNnIm/iXeNp5QVn3CsT7w2zprh4/VyCqse7zGoQ09TamCUaoBx+XTldEVxOWr2X89SKkOBMV8eVwoI9g3iAc94vfqt/qDplgaQi4yRjBaQ/5YToQWubb3UzrLhc/V+CTgdCDBcQa1Qh12GZ11u2nHicXZus2fOXRVR7UHLMDYevgr89ofj99Dcv7qwBqQgmlWT2I/DjxWTspllo+Ovyb6jz+zhFvWLCLcbAi7hPtBNXFomZOJqXm6Abklr02RSWxFPcUDjL+odEQvt9w/lC9NtwrWzU6eonfyWgpNTk3CWvpwKpgyyZcCj0EnizfSdByka4Ss7PLpK7VZ4YBFniGrDasFnnGGFWMRMtj7KLnodUAvZ+KLmOtUnxea246p7ofaahJc+lyWaIaAAqX60PsLW0cvimfS0BpEYpiltOW5HPVN/XO9iW2arZt9jDl5nVS9Kvjx+LecceQu++T7ogNcHyEq6sq6YpUCf25uBmzKe2KNFrDa3VcQ603Hje/TSBfIWVCd7NvFDUE9AWH5e22E+YqhfLVr7UVNHiDoBLC4ciwuc+uDp3NkLy969vLL5qdejg6AXoJOi4afXrzW6qcbQ1DzkdPT5BE0V7yRoM0dAKku+U8NZC11/XR5b/FVETjJEFzhSKlAbhgtv+4frStwuzp/B/baarrWoeaX+pESnOay0s3i9OMmX1i3lh/QsBKUTeSI2MHI8z0b+TsJU8FdyWEZWflFDSs5AazVzKE0aZws2/C/tx95t0YfFcrt4s9etuKoxqkOs3bDYt/zAAcyO2EPmsvRrA/0R9h/qLHY4QkIESoBPj1IbUyJRtkz8RSo9hjJkJiUZLwvx/NfuUeHF1JTJFcCOuDizO7Crr4qxyLVBvMDEAs+12n7n9/S3AlUQZx2HKVk0ij3URAFK60x+TbhLqUdyQUc5aS8mJNcX3Aqd/X3w4+My2MHN4sTWvdS4/rVptRa397rrwMDIOdIK3d7oV/UTArIO0BoRJh0wqTh0P0tEC0ehRwtGWUKpPCo1Fyy6IWUWbwo4/h7yfeax2wvS1clNw6S++7tlu+K8ZsDSxfvMpdWM32Lq0fWAARUNNRiLIscrpTPnOWE+8kCIQSFAzDykN9QwkygjH84U5wnD/rfzGuk932zW6c7tyKXELsKawerCEcb0ymzRQtk64grsZ/b+AH8LlxX4Hlwngi41NEo4pjo4O/45BTdmMkgs3SRgHBQTRAk8/0n1uOvV4uHaGtSyztDKkcgDyCfJ8stM0BDWD90R5dbtGPePAPMJ+RJdG94iRSlgLgwyLTS3NKczCjH1LIwn+iB1GTgRhQih/8/2Ve5z5mbfYtmV1CHRH8+bzpbPBtLW1eTaCOEQ6MPv5fc0AHIIXxC8F1Me8iNvKKorjC0KLiIt3ypUJ6Ei6xxiFjoPqwfy/0n47PAV6vbjvt6S2pLX0dVb1TDWR9iM2+TfK+U169HxzPjv/wAHyg0aFL8Zjx5nIislySY3J3QmiSSJIYwdtRgrExsNtgYtALT5ffO37Y3oJ+Sk4B3eo9w/3PHcsN5s4Q3ldOl97v/zz/m9/5wFPgt6ECYVIRlNHJUe6h9DIKIfDh6XG1EYWhTSD94KpgVTABD7BPZV8SftmenF5r3kj+NB49LjPOVv51nq4O3m8Uv26/qi/0gEvQjeDIwQrBMnFu0X9Bg1GbMYcxeDFfUS3g9ZDIQIfQRkAFv8fvjs9MDxEO/v7Gvrjupa6s/q5euS7cXvbPJu9bT4Ifyc/wcDSgZLCfULNA75DzkR7RETEqsRvRBTD3oNRAvDCA4GOgNeAJP96vp6+FT2h/Qe8yPymvGE8eDxpvLO8031E/cR+Tf7cP2t/9kB5gPEBWUHwAjKCX8K3AriCpIK8wkMCecHkAYTBX8D3wFCALf+Rv36+976+PlM+d74rvi6+AD5efkf+uv60vvO/NL91/7U/78AlAFLAuECUwOeA8UDxwOoA2wDGQOyAj8CxgFMAdcAbQAQAMb/jv9r/1z/YP91/5f/xP/2/ygAVwB/AJoApQCeAIMAVAARALz/V//l/m3+8/18/RD9tPxt/EL8NvxN/In86/xy/Rz+5f7I/74AwQHGAscDuASQBUcG1AYvB1QHPQfpBlcGiAWCBEoD5wFkAM7+Lv2T+wv6ovhn92X2p/U29Rf1T/Xg9cf2AfiG+Uz7SP1p/6AB3QMNBh4I/gmcC+oM2g1jDn0OJA5YDRwMeAp1CCIGjgPOAPf9HftY+L/1Z/Nl8cvvqO4I7vLtau5x7//wDfON9Wz4l/v1/msC4gU8CV0MLQ+TEXoT0RSKFZ0VBRXGE+URbw90DAkJSAVOATj9Jfk49Y7xRu5860fpvOfq5tnmjucF6TfrFO6K8X711Plr/h8DzAdODIAQQBRvF/EZsRudHK0c3BsuGqwXaRR6EP0LEwfiAZH8SPcz8nrtQumv5d/i6eDi39Lfv+Cj4nLlGumA7YXyAfjN/boDnAlED4QUNBkrHUogdSKYI6gjoiKJIG0dYhmGFPwO7giKAgL8h/VO74bpYOQE4JfcNtr22OTYBNpP3LffI+R06YPvIPYb/TwETgsZEmYYBB7EIn8mFyl0KogqUSnUJiIjVR6RGAES1QpFA4z74/OJ7Lflo99/2nXWptMs0hTSYtMQ1graNN9q5XvsM/RX/KYE4wzMFCMcrCI0KI0ski8rMUcx4y8HLcYoPyOaHAoVyAwSBC77XvLn6Q7iENsl1X7QQM2Jy2jL4Mzqz3DUUtpk4XDpO/KA+/gEWg5cF7cfKSd3LWwy4TW4N983UzYdM1QuGSicIBUYxA7xBOn69/Br54/eqtb6z7fKCscTxeXEg8bjye/OgNVm3WbmO/Ca+jEFsQ/GGSEjeCuIMho4/jsVPks+nDwSOccz4SyUJB4bxxDfBbv6sO8U5TvbdNICyyTFCMHQvpK+UMABxIvJw9B22WDjNu6k+VMF6BAIHF0mlC9lN5A95EE9RIVEt0LgPhs5kjF9KCIezxLcBqX6ie7l4hbYcc5Cxsq/P7vFuHO4TrpJvknEIcyV1V/gLOyh+F0F/xEjHmopfDMJPMxCj0cqSodKoEiCREo+JjZULB0h2RTlB6f6gu3g4CLVpcq7wa66tLX3so6ygLTAuC6/nMfJ0WndIuqS91AF9RITIEYsLDdxQMlH+UzYT01QUU7ySU9DmjoUMA4k4xb6CL76newE31/SEcdzvdK1a7Bqreis7a5qsz+6OcMVzn/aGOh49i4FyhPaIe8uojqYRIJMH1JDVdJVxlMsTyZI6T67M/Am6xgYCuv61+tT3dHPucNsuTyxaasjqIanmKlNroG1/r59yqXXEuZV9fYEfxR1I2Mx3D1+SPRQ/FZlWhBb+VgrVMtMEENEN8Ep7ho/Cy37M+vO23jNn8Cqte6ssqYno2yiiKRtqfew7boEx9/UE+Qs9KsEExXjJKAz1kAdTB1VjVs6XwVg5V3qWDlRCkesOn0s6hxrDIL7r+p22lbLxb0tsuyoSaJ6np+dwJ/PpKesC7euwy7SHOL98k0EiBUmJqc1kEN1T/hYzV++Y6pkiGJmXWtV00ruPSEv2x6cDen7SupJ2WvJLLv7rjilMZ4fmiKZRJt3oJOoXLN/wJfPMeDL8d0D3RU8J3U3CEaDUoNcumPuZ/1o22aZYV5ZZ04JQaoxwCDODmH8BepJ2LnH1bgTrNahb5oalvqUGpdpnMKk5K96vR3NU96Y8F0DExYmKAs5PEhEVbxfUWfGa/ls3WqBZQ1dw1H3QxU0lSIBEOj83ul210DGw7Z4qceeBZdvkiuRQ5OpmDWhpqyjusLKhtxm788CKxbkKGc6LEq4V6BijmpEb5twiG4YaXZg41S2Rl82WSQyEX791OnO1gHF9rQspw+c9ZMgj7eNxI87lfGdpan9t4rIzNo37jMCJhZ1KYk71kvcWS1lcG1kcuBz2XFdbJRjw1dDSYU4CSZfEiD+5+lS1vvDb7Mwpa6ZQpExjKGKoIwhkvma5qaKtXfGKNkN7YsBBRbbKXM8Ok2wW2Fn9G8jdcZ2z3RLb2VmYVqaS4Q6oieFE8z+FeoC1i7DLrKFo6aX7o6iieyH2olfj1GYaqRPs4zEm9fq69oAyhUXKiI9WE4yXTxpGHKAd0l5ZXfgceVouVy6TVo8ISmkFIL/Xerb1ZvCM7EroviV+ox3h5qFdYf4jPqVNqJNscvCKdbR6iAAdRUpKpk9ME9jXr1q3HN5eWh7mXkZdBJryV6eTwQ+hSq4FT4Avure1UHCf7AjoaaUZ4uwha6DcoXtiveTSqCHrzjB1NTC6WL/CRUSKtg9wU9CX+FrPnUNeyF9anv0delsj2BEUYA/zCvAFgABNusJ1h7CEbBuoK6TN4pQhCmC04NCiUySq54ArtS/ndPB6J3+hhTTKd89DFDOX6tsPXY6fHJ+1nxvd2huB2KrUstA8iy5F8YBw+ta1jLC6K8KoBOTaYlXgwyBm4L4h/mQWp26rKK+iNLQ59b97xNvKa89ElAJYBht2Hb/fFt/2n2IeI5vMWPQU+NB9i2iGI0CZOzR1nzCBLD3n9SS/4jFgliAyoEQhwGQWZy3q6S9ltHw5g/9RBPmKEs91U/0XyptEXdcfdp/d34/eVhwCWSxVMdC1i54GVUDGO1s1/vCY7A2oO+S+Iicgg6AYYGMhmWPqZv4qty8ydAk5kj8iBI6KLI8VE+NX+Fs53ZSfe9/rH6RecZwj2RMVXRDjy86GhoE2+0p2K3DBbHDoGWTU4nbgi6AYYFshiePTZuAqku8I9Bt5YX7vRFsJ+g7kk7YXj5sWnbffJt/d35+edZwwmShVehDITDmGtsEre4G2Y/E6LGfoTWUEYqAg7eAyoGxhkaPRJtQqvO7pc/N5Mb65RCAJu06j03WXUJrbHUGfNx+2n0GeYhwoGStVSNEiTB5G5YFi+8C2qLFCbPIol2VL4uNhKqBnIJch8OPkJtoqta7U89G5A/6ARB2JcQ5T0yHXO9pHnTHerV91HwpeNtvKmRxVSNExzDzG0oGdPAa2+LGaLQ8pNuWrIz/hQWD1oNriJ+QMpzJqvS7K8/a42D5FA9QJG4400rvWkZocnIjeSZ8ZnvodtBuXWPqVOdD2DBRHPQGZvFM3E3IAbb4pa6YiI7Vh8iEeIXeidmRKZ11q068Mc+K47v4Hw4RI+42HEkPWUpmaHAcdzF6kXlCdWdtPGIZVG5DuzCTHJIHXfKX3eHJ1Lf8p9Oav5ANivCGf4e2i3GTdZ5rrOa8Zc9Y4yP4JQ28IUc1L0fpVv1jBG6zdNd3V3c6c6BrxWD+UrdCcDC2HCQIWvP33pvL3LlDqkidT5OljHuJ64nvjWeVF6Csrbu9yM9E45n3JwxRIHozDEWBVGFhSGvscRp1unTQcHxp+V6YUcNB9S+6HKcIWPRr4HrNGLzLrAqgNpaaj2mMuoyJkLiXDaI3r86+WtBQ4x73KAvUHooxuELZUXleN2jJbv1xu3EGbv5m2VzoT5FASy+dHBkJWPXw4XrPhL6SrxajcJnqkrWP6Y+Ck2OaVqQLsR/AHdF+47T2KQpIHXovNED0Tklb1GRNa4JuXG7faiZkZ1rvTSE/cC5eHHoJVfaE45nRH8GUsmmm+5ySll6TdpPYlmid8aYps67BENLO4132LQmtG00thD3WS9RXImF7Z61qompcZ/Zgo1etS3M9ZC39G8cJUPcl5dTT5MPOtQCq06COml+XXZeHmsKg3amOtXrDNNNA5Br2NQgHGgUrqzqBSB1UJV1WY4BmjmaAY3BdkFQkSYk7KCx5GwAKRfjP5ijW0MY8udat9aTanrabnJuOnnGkF606uIPFidTW5Oz1QwdYGKUorDf6RChQ4FjiXgBiJGJPX5hZL1FVRmI5uirRGiMKM/mC6JPY4MncvOmxW6l0o16gMKDponKonrAsu8jHDtaQ5dT1WQajFjEmizREQflLWFQkWjFdaF3LWnBVg01CQwA3HSkFGi8KGPo66hDbEc2owDO2A65WqFSlFKWUp8Gsb7RgvkfKxNdu5tP1eQXpFKsjSzFiPZNHkU8gVRVYXlj5VftQjkntP2Q0TycVGSQK8/r0657dX9CdxLK66LJ8rZOqQ6qNrFuxh7jWwf/Mqdlx5+v1pQQuExUh7y1aOf1CkErZT7NSCVPbUD1MVEVYPJAxUyUAGAAKwfuw7TrgyNO4yGC/Brjhshewu6/OsT2247yKxe7PvduY6Bv23QNzEXQefCouNTk+WEVWSg9Nb013SzlH1kCEOIUuKCPHFsMJgvxp7+DiRtf0zDnEV72BuNu1drVUt2K7gMF7yRTT/t3j6WX2IwO7D8ob9CbjMEw57j+aRCxHlEfRRfNBGjx3NEYr0SBqFWwJNP0g8Y3l1tpN0TnJ18JXvtq7cLsavcjAW8amzW3Wa+BR68r2eQIIDhoZWyN9LDs0WTqrPhJBfUHtP288IjcxMNQnTh7qE/oI1f3Q8j/odt6+1VrOgchexA/Co8Ebw2nGb8sG0vfZBOPj7Ej34AFbDGcWth8BKAovnDSOOMQ6LzvPObI28jG2KzIkoRtHEm8IZf549PPqIeJE2pnTUM6QynXIC8hTyUDMutCa1rHdxeWX7uH3WgG4CrMTBhxyI78pvS5IMkg0sDR+M8EwjiwKJ2IgyxiCEMgH4/4W9qbt1OXb3u/YPtTo0AXPoc68z0rSNtZd25bhruht8JX45gAgCQIRURjVHl0kwSjgK6QtBC7/LJ8q+yYwImcczxWcDgcHTf+o91Xwiul941reRtpg17vVYdVR1oLY39tM4KXlvetk8mT5hgCUB1YOmhQvGuserSJZJd4mMidWJlMkPSEtHUUYrxKWDCsGov8t+f3yQu0n6NPjZODz3ZDcRNwM3eHeseFk5drp7+559E36OwAXBrML4xCCFW0Zhxy7HvsfPyCJH+IdWBsDGP8TbA9xCjUF4/+i+pz19vDV7Fbpkeab5IDjRePo42Plp+ef6jHuQfKs9k/7BQCqBBkJMg3UEOcTVBYLGAEZMhmfGFAXUhW3EpcPCgwvCCYEDQAG/C/4pfSC8d3uyexT64PqXerg6gPsvO3676nysvX8+Gz85v9OA40GiAkpDF8OGRBOEfYRDxKcEaQQMA9ODRELiwjTBf0CIgBY/bT6Sfgq9mX0BfMT8pTxiPHs8bvy6/Nw9Tz3Pvlm+6D93P8GAhAE6QWFB9kI3QmKCuAK3gqHCuIJ9QjMB3IG8gRcA7wBIQCX/ij94fvJ+uf5QfnY+K34vvgI+YX5L/r9+uf74/zo/e3+6P/SAKQBWQLsAloDowPGA8YDpANmAxEDqQI1ArwBQgHOAGQACQDA/4r/af9b/2H/d/+b/8j/+v8sAFsAgQCbAKUAnQCAAE8ACgC0/07/3P5j/un9c/0I/a38afxA/Df8UfyQ/PX8f/0s/vf+3P/TANYB3ALcA8sEoQVUBt0GNQdUBzkH3wZIBnUFagQuA8gBQwCr/gv9cvvr+Yb4UPdT9pv1MPUY9Vj18PXe9h/4qvl1+3T9mP/QAQ0EOwZICCMKuwsCDeoNaQ56DhcOQg39C1AKRgjtBVUDkgC6/eH6H/iK9TnzP/Gu75buAO727Xvuje8n8T/zx/Wt+N37Pv+2AisGgQmdDGQPwBGcE+YUkhWWFfEUpBO2ETQPLwy8CPUE9wDg/ND45vRD8QXuR+sg6aPn4ebg5qXnLelu61nu2vHX9TT6z/6DAy8IqwzVEIoUqxceGs0bpxykHMAbABpuFxsUIBCYC6cGcQEf/Nn2yvEa7e/oa+Ws4srg19/c397g1uK45XHp5u328nv4S/44BBcKuA/uFJAZdh2CIJcipCOdI38iUSAfHQIZFRR/DmgI/wF3+//0ze4S6frjsd9Z3BDa6djw2CnajdwM4I3k7+kL8LL2sv3UBOMLpRLlGHIeHiPCJkApgip7KigpkCbGIuMdDBhtETcKoQLn+kPz8ust5SzfHtos1nnTHNIi0o7TWNZt2q/f+eUa7d30B/1YBZANbxW3HCwjnCjaLMMvPDE4MbQvuSxcKLsiARxgFBIMVQNw+qXxOelw4YbatdQq0A3Nd8t3yxLNPNDh1N7aB+Im6v3ySvzCBR4PFRhgILsn7i3FMhg2zDfPNx82xjLdLYUn8B9VF/YNHAQS+ibwpubc3Q7We89Yys/G/sT2xLrGP8ptzxzWHN4x5xTxe/sTBo0QlRrdIxwsDjN+OD08LD45PmI8sjhDMz0s1CNJGuMP8gTN+cjuOeR12sfRdcq6xMbAuL6kvozAZsQVym/RPto/5CXvnPpMBtsR7hwuJ0ow+jf/PSpCV0RyRHlCeD6LON4wqyc4HdUR2AWh+Yvt9eE817PNpsVWv/W6qbiFuI66tr7fxNvMb9ZS4THtr/ltBggTHR9OKkM0rDxGQ9xHSEp0Sl5IEUSuPWQ1cSshIMoTzAaM+W7s29801NbJEsEuumO117KhssS0NLnPv2XItNJv3jvrtfh2BhMUIiE8LQM4IUFNSE5N+k86UAtOekmpQso5IS//IsEVzAeO+XTr7N1g0TLGvLxItROwRq37rDWv5bPruhDEEM+X20XpsPdoBv0U/CL3L4k7VkURTXtSaFW/VXxTrU52Rw0+uDLQJbUX1win+ZvqKNzAzsvCqLiosAqr/KeYp+Opz642tuG/hsvO2FHnofZFBsUVqSR8MtI+SUmOUV9Xjlr/WqxYplMSTChCMzaQKKYZ6gnV+ePpkdpWzKK/2LRQrEum/KJ9otak9am1sdu7G8gX1mPlifUMBmwWKibLNNtB9UzAVfdbZ1/0X5ddYFh3UBZGjTk8K5EbBQsY+k3pJ9kjyrm8ULFEqNuhSp6vnRCgXKVsrQS408R2033jbPS/BfIWfifhNqNEWVClWT5g8GOaZDdi11yiVNVJxDzSLXMdJQxu+tfo6tcqyBK6Ea6HpL2d7JkxmZabCKFgqV+0sMHt0KDhSvNgBVcXpCi+OChHclM5XTJkJGjuaIlmBmGOWGBN0z9OMEkfSA3W+oLo29Zpxq+3HqsbofSZ45UIlWyX/pyVpe+wtb5/ztHfJvLvBJwXnClhOmlJPlZ7YM9nAGzsbIpq6mQ3XLRQt0KtMhIhbQ5P+03o+dXjxJG1eagEnoSWM5I3kZaTQpkOormt6LsvzBDeAfFuBMMXZyrKO2RLvFhnYxNrgm+QcDRuf2ibX8xTbUXtNMoikQ/Y+zboRdWXw7izJKZDm26T4I7AjRiQ1pXPnr+qSrkAymHc3u/fA8oXBSv4PBlN6Vr8ZfptpXLXc4ZxwWu1YqZW8kcJN28kshBu/D3ovdSGwieyHqTbmLWQ7YupivSMvpLbmwWo37b2x8bav+5CA7UXdivsPYdOxlw4aIRwaXW/dnt0rm6CZT9ZQ0oBOf8lzxEQ/WDoYtSwwd2wa6LMlluOWonyhy2K/Y81mY6lqbQSxkLZpe2bAoQXuyulPq5PUF4aaq5yyndFeRJ3QnEAaJNbXEzQOnYn5RK9/Z/oMtQUwdqvCqEYlWGMK4eehceHl43gll2jrLJYxNfXk+zqATcX1iskP41QiF+ga3d0x3lme0h5enMraqBdPE51PNQo8hNy/vjoLdSywB6v+5+/k8qKYYWvg8OFjIvflHSh6rDJwofWi+sxAdIWxitqPyVRbWDKbN11XnsifRp7VnUBbGRf4E/tPRYq9RQu/2rpUdSJwKquQJ/DkpWJ/YMngiOE4Yk1k9efZq9pwVXVj+pyAFUWjSt3P3ZR/2CYbeB2jnx2fod80XaAbdtgRVE1Pzgr6hXw//LpntSYwHyu154kksSIAYMIgemClYjikYaeIa45wELUoemw/8EVLStMP4FRPmEKboB3V31hf4597HembgRiaVJMQDos0BazAJDqEdXewJSuwZ7gkVaIbIJRgBaCrIfpkIWdHq08v1LTw+jq/hoVpyrqPkZRK2Efbrx3t33jfy1+pHhyb95iSlMvQRotpRd5AUHrqtVawfGu/J75kUyIQIIEgKqBJYdLkNScX6xzvoTS9+ck/l8U/SlUPsdQyGDYbZR3r336f2R++Hjhb2Zj51PdQdQtaBg+AgXsZtYLwpGviJ9tkqWIfIIhgKiBA4cJkHWc5Kvgvd3RP+dg/ZQTLymKPQZQFGA3bQl3P32ofzJ+6Hj0b5xjP1RUQmguFRkBA9jsRNfuwnOwZKA7k2GJIIOogA6CRYclkGmcsKuFvV3RnOaf/LkSQSiOPARPEl88bB12aHztfph9dHiqb35jT1STQtQurBm/A7ntQtgCxJaxjaFjlH6KKoSZgd2C7IefkLGcxKtjvQXREebk+9IRNCdjO8JNwl3patB0KnvIfZV8m3cCbwxjF1SYQhcvKxp3BKbuXdlExfayAqPhlfuLm4XxghOE94h2kU2dIKx8vdjQn+Uw++AQCiYKOkJMKFw/aSNzh3k7fCp7Xnb7bUVillNiQi4vkBonBZ3vldq0xpO0wKS1l9aNb4eyhLGFZoqrkj6exazPvdfQSOWE+uUPxiSFOIhKRVpBZxlxgXdIell5vXSYbCphzVLxQRkv2RrOBZzw5ttNyGq2x6bcmQ6Qp4nYhraHOYw9lISftK1fvgLRDeXk+eMOaSPXNpVIHFjyZLRuGXXwdyN3uXLXarpfuVFDQdcuBRtoBqHxTt0Pyni4E6lUnJ+SPoxiiR6KbY4slh6h7K4rv1vR8ORP+dsN9iECNWxGrlVSYvdrUnI1dYl0VHC6aPZdXVBZQGcuFBv1Bqnyy972y7u6oasan4iVNI9NjOmMApF2mAujbbAzwOPR8eTJ+NEMbyAJMxBEAFNmX+NoL28Zco1xkG1DZt9bt04xP8gtAxt0B7TzW+AAzjC9bq4rosaYhZKYjxWQ9ZMam0ulN7J5wZnSEuVT+McL1x7vMIRBFFAxXH1lsmugbjJubmpyY3ZZyUzNPfos0RriB7/0++Eq0NS/eLGEpVScLpY/k56TRZcXnt2nSbT7wn/TVOXu970KLx22Lso+7ky2WMdh3mfMantq8WZLYLxWk0otPPwrfxo+CMf1qeNx0qPCu7QhqTCgK5o/l4KX75ppob6qo7a6xJXUt+Wc97YJextiLOY7kEn4VMZdt2OgZmtmHGPOXLRTFkhQOs8qChqGCMz2YuXS1JvFM7j/rFakep6Vm76b754Qpe6tQrm0xtrVPeZd97QIvRn0Kdo4/kX7UHxZQl8hYgVi8V7/WF5QVEU5OHIpcxm6CMr3JedL17nI3bsascOoFqM9oE6gRKMHqWmxJrzpyE/X5eY097kH+BdwJ6w1PULDTO5UgVpRXUxdc1rgVL5MT0LmNeUnuRjZCMH47ujZ2fjLtb9utXGt+6czpS6l6adNrS61TL9Yy/PYsecg98YGLBbaJF0yTz5USCBQeVU2WEVYp1V0UNVICD9bMyom3BfhCK/5uup43FXPt8P2uV2yJK1zqluq26zesTm5s8IAzsXaoOgk994FXhQzIvIuOjqzQxdLLlDTUvNSkFC/S6dEgjuYMEAk2xbRCJL6iewl383S38evvoK3jrL4r9CvFrK2tom9WMbe0Mbcs+lA9wIFkBKAH24rADbkPthFpkouTVxNM0vFRjdAvzefLSkithWpCGj7V+7e4VzWKcyTw9u8M7i9tYi1lbfRuxnCOcrx0/Pe6ep09zMEwxDCHNUnpjHrOWZA5kRKR4RHk0WJQYg7wTNyKuYfbxRoCC/8IvCf5P7ZkdCfyGTCDr69u3+7Vb0twebGU84310zhQuzC93ID+g7+GSokMS3ONMc68T4uQW9BtT8PPJ02iy8TJ3gdBRMNCOj86fFm57HdE9XOzRfIG8T0wbDBUMPExu3Lo9Kv2s/jve0p+MICNw02F3IgpCiQLwA1zjjeOiM7njlcNnsxIiuEI+AaeRGZB4/9qPMv6m/hqtka0/DNU8pbyBbIgsmRzCrRJtdU3nvmWu+r+CMCfAtsFK4cBCQ3KhcvgjJgNKY0UzN1MCUshybIHyAYyw8LByX+XfX47DblUd5/2OnTsdDuzqrO5M+R0pjW2Nsm4k7pGPFG+ZcBzAmlEeUYVh/HJBApEyy6Lfwt2SxeKp8mviHiGzoV/Q1iBqj+CPe+7wHpBuP43f3ZMden1WjVdNa+2DTctuAg5kbs9vL8+R4BKAjiDhgVnBpFH/EihSXxJisnNiYcJO8gzBzUFzESDwygBRf/pfh98s7sw+eA4ybgy91/3ErcKd0U3/jhvOVB6mHv8/TL+rkAkQYmDEwR3RW3Gb8c3x4KIDogbx+0HRkbtBeiEwUPAwrEBHL/NPo09ZnwhOwT6V/me+Ry40rjAOSM5eDn5eqE7pzyDve0+2kACwV0CYQNHBEhFIAWJxgMGS0ZihgsFyAVehJPD7sL2wfOA7f/svvg9130RPGr7qPsO+t56mLq8uoi7OftL/Dm8vb1RPm2/C8AlgPPBsQJXQyJDjgQYRH9EQsSjRGJEAsPIg3eClMIlwXAAub/Hv1++hn4APZD9O3yBPKP8Yzx+fHR8gj0lPVl92v5lfvQ/QoAMwI5BA4GpAfyCO4JlQrjCtoKfQrRCd8IsQdTBtEEOgOaAQAAd/4L/cj7tPrX+Tb50vis+ML4EPmS+T/6D/v7+/n8/v0C//3/5AC1AWcC9wJiA6cDxwPEA6ADYAMJA6ACKwKyATgBxQBcAAIAu/+H/2f/W/9i/3n/nv/M//7/MABeAIQAnQClAJsAfQBKAAQArP9E/9L+Wf7f/Wn9//ym/GT8Pvw4/FX8l/z//Iz9O/4J//D/6ADsAfIC8APeBLEFYgbnBjkHVAc0B9UGOAZhBVEEEQOpASIAif7p/FD7zPlr+Dj3QfaP9Sv1GvVh9QD29vY9+M75nvug/cf/AAI8BGgGcghICtoLGQ35DW8Odg4KDisN3QsoChcIuAUcA1YAff2l+ub3VvUL8xnxku+E7vrt/O2M7qrvT/Fx8wH27/gk/Ij/AAN0BsYJ2wybD+0RvRP7FJkVjxXcFIEThhH4DukLbgiiBKAAifx6+Jb0+vDF7RPr+eiM59nm6ea/51bppeue7iryMfaU+jP/6AORCAgNKRHTFOYXShrnG7AcmhyjG9EZLhfME8QPMgs6BgABrvtr9mLxvOyd6Cjle+Kt4M7f6N/+4AvjAObJ6UzuZ/P0+Mn+twSSCiwQVxXrGcAduCC4Iq4jkCNbIhYg0BygGKQTAQ7iB3QB6/p49E7unuiX42DfHtzs2d7Y/9hR2s3cYuD35GvqlPBF90r+bQV3DDATYxnfHnYjAydoKY4qayr9KEsmaCJvHYYX2BCYCf0BQvqj8lvrpeS23r7Z5tVP0w/SM9K906PW0tos4Inmuu2I9bj9CQY8DhEWSR2rIwMpJi3wL0oxJjGDL2ks8Cc2ImYbtRNaC5gCs/nt8Izo0+D/2UfU2c/bzGfListGzZHQVNVs26vi3OrA8xP9jAbjD84YBiFMKGMuGzNNNt03uzfnNWwyYy3vJkEfkxYoDUYDPPlW7+LlK9111f/O/MmXxuzECsX0xp7K7c+71tXe/efu8Vz89QZoEWQbmCS9LJIz3zh4PD8+JT4lPE84vDKWKxMjchn+DgYE4Pjh7WDjsNkc0evJVMSHwKO+ub7MwM7Eosoe0gnbIOUV8JX7RQfNEtId/Cf9MIs4az5sQm5EXUQ3Qgs+9zcoMNgmTRzaENUEnPiN7AfhZNb4zA7F5b6vupG4nLjSuia/eMWZzUzXR+I37r76fAcQFBYgMCsGNUs9vEMlSGJKXkoXSJ1DDz2fNIwqIh+6ErIFcfhb69jeSdMKyWzAs7kWtbuyt7INtay5dMAxyaLTd99V7Nr5mwcxFS8iMS7XOM5BzkieTRdQJFDBTf5I/0H3OCsu7iGcFJ0GXvhM6tXcYtBXxQm8w7S/ryetEa2Br2W0mrvpxA3Qsdxz6un4ogcvFhwk/TBtPBBGnE3SUolVqVUuUypOwkYtPbMxrSR+FpQHY/hf6f7asc3gwee3GLCvqtmnr6czqlWv77bHwJPM+dmS6O33kgcLF9wlkzPEPw9KI1K9V7Ja6FpbWB1TVEs7QR81XSddGJUIfviU6FXZNsunvgu0tqvppdWilKIopYGqd7LNvDbJUte15uj2bAfEF28n8jXcQshNX1ZcXI9f3l9DXdFXsU8fRWw4+ik3Gp0Jr/js59nX9Miwu3ewoKdzoSCexZ1koO2lNq4BufrFwNTf5Nz1MQdbGNMoGDiyRThRTVqqYBxkhWThYUNc01PTSJY7gSwJHK0K9Phm54zW68b8uC2t2qNOnb6ZRpnsm5+hMqpltePCRNIS48r04gbRGAkqAzpFSFxU612kZFRo2mgyZm5guVdVTJk+8C7RHcELTPkB527VHcWMti+qZqB/mbGVG5XEl5mdbab/sfS/489Q4bTzgQYlGRArtDuSSjNXNWFIaDRs2Wwxak5kXFugT3NBQzGMH9cMt/m95n7UicNitH+nRp0Ilv6RSJHvk9+Z7KLQrjC9n82c353yDgZZGegrKj2ZTLtZKWSSa7pvf3Dbbd9nul6xUiBEeDM4Ie8NMvqZ5r3TMcJ/siClfprskqeO0Y1xkHaWsp/dq5u6esv43YbxiwVtGZIsZD5YTvFbxmZ/buFyyHMscR9r0GGFVZ1GizXTIgUPvPqU5irTFcHjsBKjDpgtkK+Lt4pOjWCTwpwpqTe4eMln3HHw+gRjGQ8tYj/QT9ddCWkPcal1snYidApummQZWOdIezdZJBgQVPut5sTSNcCPr1ah+JXOjRiJ/oeHiqGQH5q3pgi2nMfs2mHvXAQ8GV4tJUD/UGlf8Wo+cw54Onm5dp1wFGdpWvtKQznJJSUR9/vj5ovSkL+Eru2fPZTPi+aGqIUgiDuOzZeJpBC06MWI2VfuswP4GIEtrEDmUadgfWwLdQ56XnvveNVyPmlyXNdM4johJysSpfw0537SJr/Crdme35IzihiFt4MahjGMzZWkolKyXsQ92FXtAQOaGHgt+UCFUpJhrW12dql7HH3DerF0E2s0XndOVjxdKCgTW/2f55zS975HrRie3pH6iLGDLIJ5hIWKI5QIodCwAcMP117sRwIiGEUtC0HbUipigG59d9x8cn4yfC12kmyqX9pPmz19KRkUGP4i6OTSAb8UraqdOpEliLGCCoE9gzmJ0JK4n42v1MH/1XPriAGTF+os5UDqUm1i9W4heKh9YH87fUl3uG3TYP1QsT58Kv0U2v696FPTQ78prZCd85CzhxqCUYBogk6I1pG2noqu18AQ1ZfqxQDuFmYsh0CzUl5iDm9geAt+5H/cfQN4hW6tYd9RlD9bK9EVnv9s6erTvb+DrcidCZGnh+uBAYD6gcWHNpEDnsmtDsBD1MvpAAA=\" type=\"audio/wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\n## Video\n\nMore exotic objects can also be displayed, as long as their representation supports the IPython display protocol.  For example, videos hosted externally on YouTube are easy to load:\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('sjfsUzECqK0')\n```\n\n\n\n\n\n\n\n\n\n\nUsing the nascent video capabilities of modern browsers, you may also be able to display local\nvideos.  At the moment this doesn't work very well in all browsers, so it may or may not work for you;\nwe will continue testing this and looking for ways to make it more robust.  \n\nThe following cell loads a local file called  `animation.m4v`, encodes the raw video as base64 for http\ntransport, and uses the HTML5 video tag to load it. On Chrome 15 it works correctly, displaying a control bar at the bottom with a play/pause button and a location slider.\n\n\n```python\nfrom IPython.display import HTML\nfrom base64 import b64encode\nvideo = open(\"../images/animation.m4v\", \"rb\").read()\nvideo_encoded = b64encode(video).decode('ascii')\nvideo_tag = '<video controls alt=\"test\" src=\"data:video/x-m4v;base64,{0}\">'.format(video_encoded)\nHTML(data=video_tag)\n```\n\n\n\n\n<video controls alt=\"test\" src=\"data:video/x-m4v;base64,AAAAHGZ0eXBNNFYgAAACAGlzb21pc28yYXZjMQAAAAhmcmVlAAAqiW1kYXQAAAKMBgX//4jcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTE4IC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAxMSAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTMgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MzoweDExMyBtZT1oZXggc3VibWU9NyBwc3k9MSBwc3lfcmQ9MS4wMDowLjAwIG1peGVkX3JlZj0xIG1lX3JhbmdlPTE2IGNocm9tYV9tZT0xIHRyZWxsaXM9MSA4eDhkY3Q9MSBjcW09MCBkZWFkem9uZT0yMSwxMSBmYXN0X3Bza2lwPTEgY2hyb21hX3FwX29mZnNldD0tMiB0aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MyBiX3B5cmFtaWQ9MiBiX2FkYXB0PTEgYl9iaWFzPTAgZGlyZWN0PTEgd2VpZ2h0Yj0xIG9wZW5fZ29wPTAgd2VpZ2h0cD0yIGtleWludD0yNTAga2V5aW50X21pbj0yNSBzY2VuZWN1dD00MCBpbnRyYV9yZWZyZXNoPTAgcmNfbG9va2FoZWFkPTQwIHJjPWNyZiBtYnRyZWU9MSBjcmY9MjMuMCBxY29tcD0wLjYwIHFwbWluPTAgcXBtYXg9NjkgcXBzdGVwPTQgaXBfcmF0aW89MS40MCBhcT0xOjEuMDAAgAAACqVliIQAV/0TAAI/3gU2tIW7KawwaCmQGTGHKmuYAAADACBcshU+yICkgAA14AHowiEeT6ei7v7h3Hu0i2fpUBLGBIkbCMP3Vfz+9BVGCDXnw9Uv5o3iN030tb7eq6rsEEhHs2azbdTiE9Csz5Zm6SiUWRdmB43hbD5i6syATuODUJd7LM3d9cbFpc7zFlu5y3vUmNGd6urpvKKT9iyleIyTuR1sVS431DhevGfkUllVeIznYUe2USoMW1tufETjyRdmGldN6eNlhAOsGAH4z+HkrwKecPPU7Q5T4gDAIxj9hW84jVExMTSTHxkPTq1I4OotgUxURCGTsw60k/ezPNmNg38j1bqaGmPcruDKEIBDsK5qEytFB90Q68s0h2wmlf2KXd5bleBefiK+/p47ZsyUO4IdlW25rRy+HLjt6wQXfYee3IkiQOoOK+U7u/lxcl78zfxwIoEMjUUSKNZjkp8clnmecDDJ3Kz+viF7bPklk7N6QRyizAKPIIpnNJUuMWQmqeL2Or6cr4D0/0tOym+4tficxmhuEONKUtO2pPn3hRjMllkd12tXp70fLTfxy0dwB70ML9iLEcItHb7zVupHlP5RxdvecpREw+OsIPr9KWilIesNE19jgIbT+TkiRBjOoKvUuwcQnKg7fOTHVoLvnKuAfea+oujEdm1Rwd2tEOnkF+ZC11WaNQsiNR/eJ9EnUXjXDYGfhB+Oe7qj8nYTT+eOXg1cuJNgLXEs4vOheWEjQOqfIWMQc3DmTof5s0ksBmUQ3PQ+UHPxZSnmOEZB+j6xT3wbm7HGzDjWtSg1SjTxd1EiJ8xA4SIxxR8WIKLg+TwFxJNS7Laxq7Uglu3AkXe82P1JCdJX5PsbFbxuDbuJgakzRcTwMLLSKCiizS/eCW0uJed/lev9yb80kKlVET4S219cn/zhkpeDV83cHYOr+sJQKDRk/Wh2c7fsuxfxaEH/6reSmvFDsAnXAyPXliJ3G4VG3OkEM5K5WyGGrBizZbTrdGsBnzj5VSGGOJdCKuRrUluw/8es2vYRPs9BcTqAqvHk9M52SSIf+1T6L53EZP8VbtXB+G29CMW4xVCK/B/YDjaNmqMwJ61dapugjnWJfqeXlGGa3Ch3aA7gi30T8PucNRBjLK3lF67ZDDvkWXRQXd+VMnKWHkBbCkQ/F/fMuNpHO3C00Y2pljna1qImBhVMvPe0F7Qx7G/YyxLRzhyUU8e23HGzp0agtNJRbydbrPV+TqJMSifJMNcZIf8wkdnC3/xdpcXnLf2Ye3Kbd0o7utciTG+q5h6WTEk+PaNbXLLA0YyZ2VnLTcyV1QTS76aNCbV9Q1/OQ7QU81Gg0hPa9aSiscGary6jLVwDQaik4zLsi7jPqgPVdup7pwx7uJDqRCVcVi5QoZFp/GHdex5sJTF69A6sja69/NLkFIWNSIeRcuGahXpF+wZeYIrqJv975s1TKYKAvp1WtzgtgWNkcbzCtROqf8rPtlAIxkX8GLcEo9zfExyfimeXQ64qfFxEy0IMy2Hsxau9fSMqUnIjntuVVjCQtBL+94gx1RZLndE6wROVTq/wHwHrQzo9QL9cpPqPFJjiZ/NGZIFuudS+wsBFe6Hu8Oitf5zToLqLdtU4Smwh4ne3JsiT9lOzN+4PPw3VSx9l5FppVwdKUWELw1dYpCOppyVWlJ3YQ8H4FQQM8EcYMG9N3Bxu79y1J1ikuvuhMmLQlehLTbguhbix74hd1VIQC8EjHmOZSSWbssulYwPbr6FF49tifk6PymJvulR9/u+2585HkRfbxveGeWCz0ix1pIVfaNpESKmtLy/0mcbMg9hYDz2werz9oe0lT2BiMV6uAin6RaQcT8Vk9MPctfwae+gkvtnZA/sOBk8MbpylaHqc0KIVHhhLFMNnkOFiucjtGo/JWTa/F6g8wWeow5ZuIJUORaYHWqegZbTgM9dCsYYsfZGjjVMuSlDIvpYvIvFFooGPC7Ye2Jfawmq4Ut7EL/nv/dyAd2HRc5msmUhzeu/XpX3rVlzRmf9/Qan8Dbve3QfW1Ym0o5J/KAc3z1VBho7JBr5PgCL68RiD9jZHN0VvsT4gzsEjNlW3D91Uy4RduaodBFoNTzXwlfUYULBzdiTbH75l/UmVMC4TKeTWhNzw2UezaqeGd8at3WSY7W/VR3+hvZHDpkIjgKuNNH0DsCRa/Kk56XQoHIyvvUH/eNekNvziReqS4qgLnXUT4BRGt2BOtCifI6+X/DGHUOmWlX7TN5b4pw5U7jwfwshtbhGZM49T8JMk15Mzrc7tM6J11TYxb5R3mQhZ8TZumJ0bMJXPM69HFyihr5dJSEJMycxJVUh6NTQALUOoRTHIOwE+FpWI6feTv1SiZ0YpYe5DbkYJJbN7zAHbAKw25XvqR2mAjQmOlsfX/tK8DPjP/8h5/xgAF4EUbj1tOnQCBQL8jk9vHtfsXncsprww4Z+P/Z/UrKifuFyEpBWN8kLpF7yywE2iYdDruV9+/qKR8rC9ozNKyqQNIwtxrzYkWpE5t8K7gG4JFnrHona/Rp8dOX6VW41+jb5LB1LEtE8MwjLp3RCUOq/+6yLzaOEgBTqzvEjDeFpg/u9DMHMr4/2TOchfjg7dl+uQ6Gsx+4Ia9W7vivG95027p25eKL0nHvx/OqmAQEZYJL/JO58lOj0zPdJxrQ5dZksjMISzVZNn7DsxqE3zgBBuNzk50R8lTK3U8P12QiOAQYSTeGlYlkvfeofrfO1AitEj02m9aUkxTFd1ZZJoLQT2d3zEU5PmE4lxMVfL5ttNnIbqfcIU2RJKNWqdw77xfjfrNc/eNpRKPZ/6z50LzBprgjzBHRfKgSWWkDxHrX0aTbgwQFwd51+PoUWH4DkQg26uGslF5Hn3hB58+fkeLTosTANOIBNAeFZtTc4PIaLHw759zae7scY55xcTabzlilYIftst2RZ6ntsRC3zFxduCKvL6wLfYT+TiIWJn5P7sTwZwXuSzXY+9Q3xMZ5o4Xcpz6vD9FtTjzS69iefEYt4pXiDrZUo4ePGiLeoIFIwYB/v6GXdmG5VLLk+eKbOc9AmsX2zmvqtcvDRGQbzugXbH/kTH/lkNPBTmqN3ZJODUEXVohPEJ6th0xna0EVleB73Q3eNvaVUvhlJbjs3D/T17FRCebN7AOXvzzbLE/I5kNfEmJcv4dxtIeo2uQ/z9ohSpiZzbDj1u40nJRyJxUK60wEv0nA9f/NuJ6/PEyU0bkK16z2KH12k3Lc4+1f5fawIzkK2qJRB4wnj8VHhUW9mbJhs9vgfFmU3xrXSShY67Ygb+gYNPxxtn4K/9eTSwIA9fv/nR33lA2lZoXALRUTmOZIl3R0gAM5h6oX1y1thIyqViBK95VZc8Pvy7G3O90M9S4zkpyFQ36jrMazvMveMA4d39fvoaC7p90quiJfjI4yrl+ECVkCJL5MxRSa+iVcIL7Xbl0jVaGhZIcMYmcGOBbLzhJgloM1x1zFnnj3ggJRFAM8yNnXxhavk+mA18JC+y3lqGsp6vPReRxGlGHMou17L4It070LzkoeCzarpv8Apw59smdS5KN9qVN1WgeL7OSN8BHg94ubCvS7DW6H3/PbtRB62jFLsBhUV5YqCIbIN5VZ81AAACpUGaIWxFfwAru8x8uT3FuOjrAeSWXmAWqq9jCNGE+N5AOv//9//xjk4uBAcADN96c97AVGmzRtnWwPsgcCbLrVdQJgbKp4QSmPwQnVhv0hXyBjeFWWlcvx70urEN3FK6/lvk2tQeZgbtlbzXluvTfnSj/Ctz7vZ+O1FjhDzzdpL7uLzewzCIW5VWLAEKUVuS2J6wNk6MR7UblcEd4EtOY+R4/qJgfojCsfRvA0oC5dc41Vd0erZbSkrmPTjLCn815bxlchUJMS8gQD5hJNwoKHvNLNwn7XKuTtYIhH2wVNZvDWgzCjlPeQajnrcMsb6bZYJvNJU8HuGHvm50r7VG8qifEwmuyegAZXojh5Ul5VvjDW7kSAZyw8a7I6mHY3FZHd+OA3V4JZMbNliI3Tj1L6+MKTmilVialmyZagRtEMeKRdtxUPd3vVEtrOBVIVYWdgAGA7HmZiHQUQNxLkWxbLyWVlrh5EM0Do2NdbclHxxArz90d+MSVeUOIXQ/4V9quq8C8qVflo1gPtPMkjO2/UrdOYqhY404ReObOu/fdp4hAEDq6jhy64vOeT7XUK/Onq0rXTldtA6kvgQaJg+mgYSR9hfXtMbOUSLgLj/RmBSO8aAMHuJJZqf1tCM5pZ9eYUsrHmy+/z2NGalon0//uF6+33bQzT/RLRfBbYTjy9QrJqHLlw46lggWPGkHuPKSqk/CB7U4pNPXUbR0DdcJy9Db00wCzVzxVc6h7jfCFgiL2Y0HVqd6bgIaVUqn/gJCEyCDVplnzebv0gg3XwMJAGu639lHu7rEvxTp1smIYjWp9R5L4SspVvS07Nb+Smk1FgsMp1K3EMUT8X2Fty4VG54/Ec6bE8tNVw4/QV1VzBw7Px2/2eEhhUS+FMfbHAlD28x00jRgAAACW0GaQjwhkymEVwArOUkEOhoFqiELtH8wgecFLiUq6WqmwAP7iGEwbYzfnHacfqUNXAfD+CGR2ap0lAHL25ipuYtd5j2O0PU/MpaWPG/n2y5OkfTzaOpotaR5tWjN55B2XblVVqsFfBC/mvsiPvCBWUHFChacdY5whj5mP5rqQ0dqLJCsWjrs4TWnIbL2V/Iwfj3hwI35jfo1JkTOeR+8GhOdma9rgiKWafCbQyhYMTDmVdvhND60Flm97EDSTjF0OC+0gD9b8Yn4tNeHipCa/aWyt0n79bMmjfcjntBCPjrcB5ecRTpfGHbEHy1IRj2cjkGXKC+VYoYJXBp4rd4cMd8ygLCk5nBSd8/cTaKNRjdBscOeTXG6QEjSxj9/2pVwx9DMRVtWQR0BSaAcQcZ8W2KPSaeRC4QwmNMu2xx25CSyrDiq2rFSK/JJtmvoIjAKq0ciEXoOgw+Ke+Ylb7ULKCS3k1p/613UNRp450uSq5b7CAHo7S0b7fBMLfNmwSjRYEhLlo0HUaRe/I+IX2Z6XdZH9Hty/399ZA1PwZGC6EfvUJIf7CBeaxv7cu6IT2/s0zPRGthpvXpYw6A7P4Wwz5C4V98KnIUNUanadqabKP6eXWhvbvcQHxAjiOOiKZgXZplZW2g+B2NNyJSLiR+g48DqvWR6t9S2aGfFjdOW1Gi6oTtZ1d4p5XIslAr8mryeZ6+htSSQe4AcfVt7k+V6mOthBCYtr/LEU4ZHtl0mW9876PK8mRFAaT8DJOUFVz1lPfzRApuPggkkyq+UMvyfKTUbCk7/DpfX8Y4s4QAAAg9BmmNJ4Q8mUwIr/wAsWUPjZw3ksgRsxZ6n4fQjprPbkj2aUh30y0bZJnLmiXnWskvOGnCPwBnG9dEhatwX3hoxk7BNyG+wQ4emZUpcVzcWl2T9nKQB1euucuZWHTg7TCtM/iHyfPO2vbmGsfzs70b/egIbywUH4y4BQSL1nWc1SmpHm2zHMBcUjYLDZ5gL5vdfxn0V8FFw66G88c/LN4I5icUa7xf4fcSBKywU0ajbp1P+aJYjBgWT6Ggu0MDLDNl54tfqd42lKosQtM1aif4WXAZFP5Ww3vrQ1rH9+utSYxqZd6N6gGtNbSNMcViaKn5LcnjsbBi3T3EmGqshEbcme8VHKwR3kSfBOAprrIsv6K8R+X6az+MD23rWka/2v64m1qM69D7Xa+Kcs/n0KLCJdTilyaGadopLeaAn3eYvWTeHcucMM1Fp1KgHD1tiFeO6HvobLkZlRximsA3/7MiohYklLIcJrZL22BH+6W9d6kZsYIsej9RM681nU6mWNjepBAfAfTbrGRrVB/h2DxC5B8YyRjgSIzQjNYrse0rzChqbrsLl7mQ7W+1bsNKze5//9ZIa8rSsF+BXh/vgoRTDkPW/ws95B7VPCZEFChfX0icw+tpcpN/q7NY87tUn4vESdSiMMlyhKklMjQu/G51J69ZRQLs2oUO6YfoJFqliy4qCFCrf8SZE9Fc6DcCagAAAAodBmoRJ4Q8mUwIr/wArPWF/KOw78THwadfPqhJO0CnmR/M74/XYZLqVYKlNcEaYauf+vrRUDJPmu75sMKy2Y+Bnslc/iAISSyWtw/h/3CF8fE5ZrbrwSNst+MSyCoNWP+8imtoX2eyojpdCk8YP5K+cbK4SJPCkZXbYqSXYk7hO8AdSemBHgXKWiZ+UOr802aJo+98ZOIjX9hWL9bo31Gqx7cy4ZG+W/ar/WGlzDa1xPWnPRsEdrIcZlEVGV/jGmbirkxw1lyUYoqj8Vv7Bxube9XPQlBkXOV6Lc1LT2IzNq0V7WwVhF0kA6yxfAsFxc9krNEH8vGGntTWI608ovjatXc/CKKXw7AjJSftlTcLI0hIIGXbRUr0NCYNp7M4cVd/n73Rjetnixz4SAKpcz/P47UsijZG7T3SxzK2D79WS42aEalc12hQwCZ01LfmF/H2mmGEvOzPBie1D0YT7Jh19vxa4Dd3SQ1FrDfmSUpvv4DjbYcZ2PrPpFpWtMjWqHBeoyMiZf6RP3EfYR6z9jsVNIIHxM0bzzBQF8eeYkPgDySydxPXv9Izo+QUY94N8kWi16fI6eZSDc1G0Yo0L91jcRQuDMGGS7B2zuf/0GbJyRhUO48UbMrqnILMrbQg1LF00Q3pH9nbGEK/RRQpRN3T/J/4IZQjwW2Ft2ipWGztg1Jn9I4DmffKS60QC+JQcyakdVON6zDcKttIKlqeTcmAi4xzmo4QXa2dRKleS+fs3EtTdBBtony2wK9T2Imj+NCziOSEL7Q7VuIU8kclUHrJJsSneFcxGRgIgGGUEQM8/pklwTOqab7mMmJeRiaBrjJDEnDpkR4Vz3qXxgyn4/5x24FuTMNVPwQAAAhtBmqVJ4Q8mUwIr/wApcLwPT0/Xh9UdWqWXIs8Wbj5K1hivmN6qIQnq+aolcegdlM/63MbHsdC6xYZC1e/Q8UjQCt9N/Ejqwms8DzeWv2qxskeliZH0kt1QWkErWSEodq7V0ZNksctLkMGWayX33gBT368EehfIeGDolBZoqIbJfb4nqcfU+ev4OzVv9zVqWyLck315GFmXxQKIM8pICQc8Q5es34LH1+DmnMnW8kQpVGrztQcDXhjCU3F0fOgoSsXSVWCjc6XKqGbCwQDfJUxCfXfIT6YmQoPpVp1mpGy1wQypXus9z0bScDpyDu23hViYDntdj1O45ea0znKZkj1+tLHbBtqAGJ1WTcbGlF6Vya6hQhEsiiZUIC2fRxIj8/wEXCICIbr0gZ/m6gcOhE10tenvE7iy+BKY81wLWrnzos3S6FWxYtmCRes+LLhNGOKWRuQo6SyePH2OZ90xZm8oA1MuTe3V59euVNxjAt0FLkAc9TEiFhP/8CB+gA8mF+A8h1U01f4DVX55GzCH51jHI2xUS0L9GtsHoBxLPLK/NNel8zcnwG4X+UusfcfEb5hh+ffnXteCE9vRGbs2n9wYW0xA3ZicklfadmWKUtMiHYBfkMSULWnkBQr4CXxjpYOs6ygeEoA5+5B0B1SZObgZ42wWqddyyYE0NfwQAl75tfdJGqOa7OMHwBYNeatJaJK0zT2+bFaw2qWCWwAAAitBmsZJ4Q8mUwIr/wAstkdsayRXchoFk703izqzduZ5WsyXriI9cfUdMUWvm0iGHwYIrUujvz3Yjou+JLwv9df2kt7MJo8u+3P5CjEKbwlz4vkE5AHTAbgXn3+Xc/MMJLgW5cm7iX3KiGNnBpbphhwJRlb3u91NRDr0d1IR2up/z7lKxE7XPAPFe0siPMYVlIqWNSn5KqLABPeuxxbOsvMEb27/nH1LUVM8I2F95c1I3Lv1SpkhZXjs1JsmS9X7gsoTxkXyShGC2+zRJSGUbhCPo/q1XSFMHQyMWJ79FKPQSL/RpVsacN2bYwdKo4TFBw1SsKq/L1iOmqMI+4Gxnbbjojdk0ek0JIcDb4bHv1czxchF7FX1Ym8H6IpPuE8CeNKjzQ1a1wqhEu+wl1N0x3Y37ZryCCKJRkxj0FT7bOoH3L38/yMUuh/v3aCmxY4eCkykb2p6ZrYMFE044anM/nMjmbErMibfRFuCz58Io1rBlF7JfkIz0R2/5vjUMVskcdbX2mm7DntncOsWDIdg/XVmgsC9CzVzUyq4VsS/sk97lJggcddpWLNw/29egz8iLyzWHOAXCvl2fTIPkviYAOQXfVhZUQdxsyJUNFMTiALrZCmoQLMp2LmDbfbW8JQriDeR3fVz6P1sjT8C2yEDvzkCn7sh0aTBK+sx7BKH1nb4320+caQepQj4TCJtCeNXjdrVcNEnjvwlcRJwFT1pT+Y7HREbHnT71XYNh4EAAAGEQZrnSeEPJlMCK/8AKIjxcI58rm/ML255fOJW1zbznFna7lfgMQrka7OTPPsvVAV4EJXye/Uxiu9dlftmRypJqfDot3xwDe8lX/qAVf6pBkSlUsaLyBYtww/SUSa1bGl1JvrJCN7FXCCXbLd5R4PoYlPiDIm/DQH2puO0StIWmrR77Isc/J1pRvdu5+mQa/n0SEHUeM2KkoRzCznfD9zaaRO7BDtvC9SYIT0uYZxrwTjxQ7N7UERTrYG0P+vRLAhxkfohFIYl3HXyjPOvnlbUFP2oiiy6nkUFuaIyQcJawJv3GU8k4ObcKsC1cNDXjSpsyQRrxLFaCCjke4mikyt7vs0iN0bnrNWv9HXruG9zOFEOer1ggIFTsT1Eos5CXRkgja5HN4QUM6MhWpc5du/HgBIH8ANFcoo2kJpqcadw9r/0qk25X91MQSDJQiH8Hny2dQhqR+LFWEawiW753SJhn0ngZcv/mPj3mwcHv1SL9ErBqAjm4JGiDetPKYtFwANYY11OyQAAAVdBmwhJ4Q8mUwIr/wArOx5HV2505jRePGgMxptW4PGIHEszV1xGZS+flSkF+aq30AaqO7u6XK9jJsuWXTfYCRQTn1bZfFQ22DbO5DXAxK/TUmbQleCflFzeS6/czxkL4PJ8AwOs2U+oehekgCZC8gZyHHaQSaKbNJ46gTjNsLy84ACQ5uNt11TPuCPqPTuh+schdw9S+/lU/6m+EyaqGZ49wDFPiBFBYXglQQBjyP9k/rqq0xL7SiLjpe4riYg8SFUuUtOzPdWHyvxnI7Ug/0VLPGAAhgMISUnqe01d5QFf36yHpwMAHexjAZFIGQHAFautuMuEw6HzUZVzNdeHYxvEYOGkTo007bLwbuf/nxzrywGOxlRTYJLRdYI0mk0SdN3+LeTv1RIJwv21+e9rT5iFOTCgzeQoekEWXLYz0X8YLq5bVCtijP7/T7w1Ck71j0aqfrEn6wtIAAABNUGbKUnhDyZTAiv/ACcySi7VBgOid6qZNXvhh/JsllHkMLLq0yNbQTqv/Wk2EBoSKICZwFwAD0WRzhvvReCGirep1Fe4bxjm49/UR+OYrXRmHR18T0C83AUVeBk7KvDZmb/eHzuzEN4yfXucr/NWFJl+USVMY4r4UQ9CayrfEY9v6AQ6mzAdLy2UMfFxrRJ99g/Rfl8qx+m4jIZNjlrTaThzJ/3OpVmAliDfxVyg8+CVIlI31IykiwQrXcebgajG+av8XU1SfyAG5ibvwbtdSAxkGBcJWL387V+uTdY56w3KN2vBtoQpVKD2zb3yazIcATZ02upwIytNcM/rpaLCdMb1myWcikE25agzLhDhOS+4zwjYz2DnW6VY0gFBAPsphhsUMnauVVdUVHzCTSdvzEve/H8q4AAAAVdBm0pJ4Q8mUwIr/wAo+x5XKuiN1am7SkJKSMonFZDPU3f5XFcDQSs0FLVq2idfsKwuIkt1mxIq8NgMHpzofTnDHqs/WedvAmhBgL0N5azdQa5MNKG2rJ4IAvGQY/uFm3jKQAKzvhSS01gO1oIfizF817z9IShS4QK2WT0PeFPELqLSpED8eNOpVTR96vmwpk/WBKRVJdTQJzjiCQ5pgEwjtvk7KqoS0+lwXSbvIrXkYm8DignEts3DLNoLHrPjXlQmbIop76JZSyJEtB+91GrLwo6Km5GeebyA2E6qGL3xSkpppej/ruoFprSKrH60UMbrq/SK7eCo+1QFoySPQmqDFsMGiQFqvtld5BXDYdVI4yRaoyN7Y7wi83HRC6eVazuHU9OtIY3xJJApBWq1aJOsYwc38aTC3ee863Aa/4n9Lk4DAtyFYHNZjB5m2e2vk8G2Gny9YFlBAAABQEGba0nhDyZTAiv/ACoZSZQfHxhfQxEqOBQrP+L3DmgvHSJQtB1iVkcLTxm+vagLHBLG91OGnopwrr7gT/loDypIhoRxjcwAAOeg/jN4WBbXzCJtnWGGllUCSdtUZQzKOSp9iM4yX18C6jrY4Sq6R9PUV/lEGNveJR4gw4FMve7110XdEPL1O2VTdHvdqeANyaq0nLdEmtXnrzvdrFlBaUvmaR4EdlkqGkvkZKWJej8Vq+msbKa7JdbxjwZtRufiyGfD/NVqMgSrYRzw9z/a8Zwbr+9+19CxlWD5bCuAEfPmjY6kZJE2L/CQI6+tnCBTXOmWZtZMBoCLGOf7G2uAC3+kFlboh9as5WCkO6+iqXq29dyhKnsHInorRYsPlgxIXyU1Om/Kyhj1DJV0Am9WJK3Dln0zNUH0q6ZTOnZcFD36AAABYkGbjEnhDyZTAiv/ACcwdIOLRFfoGK2ZkKsvgMwG0m0qsY0vMLPSzefc+ebp/aztyF7MlsBz/fBeNtxFBcsKgR4pf65GvdfOMHah0ltZ918sMDmXUEZMeRHy/xpnWpTLeGz6uTs/7MATPmU5BgHbT/DkD8QeaZnFAzidyFCXDz2l/jaKhEdgqipbB2pH0+fQ039r05z9axxEWGmaLQjg6x9+po1o24yhkVO7m03YwWmPyCgy8cOwrvRyJkXJpRN4m8ZBS1zwY80HeN/VyMQQJSMwsTo7R1XMerSFuyx0nz+8qOuhiqykc2ohCCsXia/+kIKbJ5Vs+cbWtvkqBKIDSfU7FhAd3GjcY/xar0EVmi6wWFTugAogR3I7mTrQDdlTAqYgqO7Gn5NMXQVHu2i1zhFSdo9GjMbeGnbkJwsFbQ2XkoKRIDpuW7AewC9AEBt0Ox/Ah6dGXfXO1jl8pEApj2RFmgAAAPlBm61J4Q8mUwIr/wAlR+eW/VZ7bSrmwwMA62G05DZ7p/5FUugsSsQdonUq6abtbU5hjFr+I1lPgoiV5c3CkTQZS+K5zivdo+Ti2P4K90xXANp8dSMAu85uJIOCQn2TXbEnNDifLB+3V84ht5tj4lvTaZx317BcliV8D5v2zZQW8RO1mUbuJEBItst8E7hfE+ZXj7tfDxNZPTvtpFyUv0fH1cTg1pr2VLy0d0zQLiA58dg+GkRvR1/hs2LyifBgHcj6eTWz0vsypVn9iPXRH/unJ6i8cfFL69NO24tQ9QQB+nDFhoP2cRhkAvhHwn56n5PppBD/oxni2f8AAAE9QZvOSeEPJlMCK/8AJjAXVGf+Kj2XNJnFeKC/gr7dJDTC2ngpd4WeAHlg04GuJKnn9hAmiECxxo9qM1IYMRiB85t6gALnlm9sRqGmioyzAm18RJndc9Ah8RlpGzr+44a6ntRaPx0cIwNIWAA8buL2JP00dmfjNqEiAlCa8OdV8FQxjp1vDXsGcAGF3Qbd62KEpkimeI3wH2nuXpbDHm8/ZKOR49s5ifUCkxCoJpfp43aC0lTzh2NXpcfVw6h0QnK8G60R4ZAxOxaJB7c0nn8ixXSU2JVY24EtGMF53nxJnHfzUheewUfBOGYSxeo8oK7oUCqX4rztzDwoc2QywNqQUJUkFrqIN+sb5ecYvX24Zujn+ZzTW6UDAF3R6WdNyJyRAremgC8spSflTqygQNGfHyGkfIEEJJaFo/pBCBkAAAEWQZvvSeEPJlMCK/8AKI41fuekXG59Knbw4Y6YJritsh9VtQgc3QKvVmxrzzo7f4aXn8N74eyP4b2lV1Z2Q+rohxps7EHTkOY9jLdqxI3MXe7je4g2qepz71+hY+jYdX+9LO0kA0Zg3NfyAlIRX7k6c/YHAZNtNaGZgTBMqiPgmEjiJH9Luk7shbgr+srfwiYwBX9rdS3fQNNFwcT8orQC+F60LAY9+GbFo2Sw3Ld4Tw9jq9yJtrY8RtHAdzytyek/mv2+j2TbTvAQKbbCYtdC8E/KtR4V5ZTSScr5Wb63vmbw7UpddEXYvl55pARyyvMxWNSh3Li4GF8Jk5JBi5B5ASQwxCMYpX5hkAMc+d8tl2bT+IEvUTsAAAElQZoQSeEPJlMCK/8AJIAzFZs00JJ0yfm8CZiew4xWdArLklEvBVXo/+ukPLu3XP9HFOfsme3T6BJEKmPPgZw/Lxnraq6Sl2kLVW19YU1qmqgfv+80LkZaWU5gRAH4hqyo3bFYcbuY2SC3IW5Wm69gtYyAXOdbAYSEHA16fvCeRQjHEsxKVndJdrRAlrGHsKgUBQ3Up/ZXIy1vkdFOfKSjpuZnswkuqr8NZI5tJ/dnBSErBTNWPaNwWV7nNomC0EYVGo+geGBhLXzaLw0UAOCYGjiPc3803BDw1GLoLIXjrIFJxwRfBNIAXYZAglu30oYzhpAfRWSprkeULMWYJTlWvbUQ5CNewSZssuDWIRAc3w8AcFaywwn+YSGhtR8VI1OGjYkfBbcAAAD8QZoxSeEPJlMCK/8AJdokjCUETRw/nciVPtaZQSBP/VxAQSITASEzlJBl9Na1r0DJhLOz279+KQLtl/xHZ8vAKc528mTMTqtWs4sFbeVgHWyBpHcHEtgTzjIqEinp/MPuUXF5poo8YLSSMFn9Ozx2FbU5/Kh9A39oN9NHQflVxV1NA6yT/84HHyfMtfdSMS8KTvAEE2lDs14VQayNs5ctjXboQT7xMBf5OLj6thhPvgaDrFB2o/PV9ouK147lruWTP2mkoA9oDIMYW1pcBx4yyV/t9GOPZ3aXneMUb2fFmUCX43BjXfUDMaa4GO2/Ankj3UEQwDxA7ZlNUQK2AAAA4UGaUknhDyZTAiv/ACJHv33I08bkhybYiJ/JiiheW5zMPBu4n5CxGr3frhE7TkLh0vPktM8m/AhaDiJisdk5QXNe/4WmxEDSAyaVi4eUVu0iHT2ly/KNTGqiORqA2oKpTjh84nYbrpXwnGv9SOf/34Z06xN6Yo3t35UZrP8nlcs/63GtnEmnUwVZHBYfPM6bs5M5AeBfAQ/9mIqu7vnEst+5O2wpPjzdItjwGCZ2ApHVjGnYYFomlA9nm6AXnxNIWHIsDgxCk3zx+6QbXipu/CWLG1Wf0WIbt4C0JPVl3TEb0QAAAMlBmnNJ4Q8mUwIr/wAVV64OfTKmlktYOqZHH1W1DhPy/X/6sD4T6hRdzfOgNtTOX2IckRJHshfBQVkJIzns079io6kpJFCcS3VD4zrWCn/dNaGV0kWTpFBRuusfn8F0C0R/EhsQeyTsdZftEkLGb5tq+nrir3vfmeb7rjmWJRXkIrTEKu8pIuAd+4FBGp8ARgGe80Jqpp//s1433HqBFqXsIFJTmU8j/toF9HyueI1Ea4uvsQ6NANGcYCbOAKCmbNiwABMCFaiUTMAAAAPSbW9vdgAAAGxtdmhkAAAAAHwlsIB8JbCAAAAD6AAAAyAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAv10cmFrAAAAXHRraGQAAAAPfCWwgHwlsIAAAAABAAAAAAAAAyAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAY4AAAGGAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAMgAAAAAgABAAAAAAJ1bWRpYQAAACBtZGhkAAAAAHwlsIB8JbCAAAAAGQAAABRVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAACIG1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAeBzdGJsAAAAtHN0c2QAAAAAAAAAAQAAAKRhdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAY4BhgBIAAAASAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGP//AAAAMmF2Y0MBZAAV/+EAGWdkABWs2UGQz6mhAAADAAEAAAMAMg8WLZYBAAZo6+PLIsAAAAAcdXVpZGtoQPJfJE/FujmlG88DI/MAAAAAAAAAGHN0dHMAAAAAAAAAAQAAABQAAAABAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAYY3R0cwAAAAAAAAABAAAAFAAAAAIAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAZHN0c3oAAAAAAAAAAAAAABQAAA05AAACqQAAAl8AAAITAAACiwAAAh8AAAIvAAABiAAAAVsAAAE5AAABWwAAAUQAAAFmAAAA/QAAAUEAAAEaAAABKQAAAQAAAADlAAAAzQAAAGBzdGNvAAAAAAAAABQAAAAsAAANZQAAEA4AABJtAAAUgAAAFwsAABkqAAAbWQAAHOEAAB48AAAfdQAAINAAACIUAAAjegAAJHcAACW4AAAm0gAAJ/sAACj7AAAp4AAAAGF1ZHRhAAAAWW1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAALGlsc3QAAAAkqXRvbwAAABxkYXRhAAAAAQAAAABMYXZmNTIuMTExLjA=\">\n\n\n\n## External sites\n\nYou can even embed an entire page from another site in an iframe; for example this is today's Wikipedia\npage for mobile users:\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('http://jupyter.org', width='100%', height=350)\n```\n\n\n\n\n\n\n\n\n\n\n## Links to local files\n\nIPython provides builtin display classes for generating links to local files. Create a link to a single file using the `FileLink` object:\n\n\n```python\nfrom IPython.display import FileLink, FileLinks\nFileLink('Cell Magics.ipynb')\n```\n\n\n\n\n<a href='Cell Magics.ipynb' target='_blank'>Cell Magics.ipynb</a><br>\n\n\n\nAlternatively, to generate links to all of the files in a directory, use the `FileLinks` object, passing `'.'` to indicate that we want links generated for the current working directory. Note that if there were other directories under the current directory, `FileLinks` would work in a recursive manner creating links to files in all sub-directories as well.\n\n\n```python\nFileLinks('.')\n```\n\n\n\n\n./<br>\n&nbsp;&nbsp;<a href='./Animations Using clear_output.ipynb' target='_blank'>Animations Using clear_output.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Background Jobs.ipynb' target='_blank'>Background Jobs.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Beyond Plain Python.ipynb' target='_blank'>Beyond Plain Python.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Capturing Output.ipynb' target='_blank'>Capturing Output.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Cell Magics.ipynb' target='_blank'>Cell Magics.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Custom Display Logic.ipynb' target='_blank'>Custom Display Logic.ipynb</a><br>\n&nbsp;&nbsp;<a href='./example-demo.py' target='_blank'>example-demo.py</a><br>\n&nbsp;&nbsp;<a href='./foo.py' target='_blank'>foo.py</a><br>\n&nbsp;&nbsp;<a href='./Index.ipynb' target='_blank'>Index.ipynb</a><br>\n&nbsp;&nbsp;<a href='./ipython-completion.bash' target='_blank'>ipython-completion.bash</a><br>\n&nbsp;&nbsp;<a href='./ipython-get-history.py' target='_blank'>ipython-get-history.py</a><br>\n&nbsp;&nbsp;<a href='./ipython-qtconsole.desktop' target='_blank'>ipython-qtconsole.desktop</a><br>\n&nbsp;&nbsp;<a href='./ipython.desktop' target='_blank'>ipython.desktop</a><br>\n&nbsp;&nbsp;<a href='./mod.py' target='_blank'>mod.py</a><br>\n&nbsp;&nbsp;<a href='./Plotting in the Notebook.ipynb' target='_blank'>Plotting in the Notebook.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Raw Input in the Notebook.ipynb' target='_blank'>Raw Input in the Notebook.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Rich Output.ipynb' target='_blank'>Rich Output.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Script Magics.ipynb' target='_blank'>Script Magics.ipynb</a><br>\n&nbsp;&nbsp;<a href='./SymPy.ipynb' target='_blank'>SymPy.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Terminal Usage.ipynb' target='_blank'>Terminal Usage.ipynb</a><br>\n&nbsp;&nbsp;<a href='./test.txt' target='_blank'>test.txt</a><br>\n&nbsp;&nbsp;<a href='./Third Party Rich Output.ipynb' target='_blank'>Third Party Rich Output.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Trapezoid Rule.ipynb' target='_blank'>Trapezoid Rule.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Working With External Code.ipynb' target='_blank'>Working With External Code.ipynb</a><br>\n./.ipynb_checkpoints/<br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Animations Using clear_output-checkpoint.ipynb' target='_blank'>Animations Using clear_output-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Background Jobs-checkpoint.ipynb' target='_blank'>Background Jobs-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Beyond Plain Python-checkpoint.ipynb' target='_blank'>Beyond Plain Python-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Capturing Output-checkpoint.ipynb' target='_blank'>Capturing Output-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Cell Magics-checkpoint.ipynb' target='_blank'>Cell Magics-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Custom Display Logic-checkpoint.ipynb' target='_blank'>Custom Display Logic-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Index-checkpoint.ipynb' target='_blank'>Index-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Plotting in the Notebook-checkpoint.ipynb' target='_blank'>Plotting in the Notebook-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Raw Input in the Notebook-checkpoint.ipynb' target='_blank'>Raw Input in the Notebook-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Rich Output-checkpoint.ipynb' target='_blank'>Rich Output-checkpoint.ipynb</a><br>\n./__pycache__/<br>\n&nbsp;&nbsp;<a href='./__pycache__/mod.cpython-34.pyc' target='_blank'>mod.cpython-34.pyc</a><br>\n./data/<br>\n&nbsp;&nbsp;<a href='./data/flare.json' target='_blank'>flare.json</a><br>\n./gui/<br>\n&nbsp;&nbsp;<a href='./gui/gui-glut.py' target='_blank'>gui-glut.py</a><br>\n&nbsp;&nbsp;<a href='./gui/gui-gtk.py' target='_blank'>gui-gtk.py</a><br>\n&nbsp;&nbsp;<a href='./gui/gui-gtk3.py' target='_blank'>gui-gtk3.py</a><br>\n&nbsp;&nbsp;<a href='./gui/gui-pyglet.py' target='_blank'>gui-pyglet.py</a><br>\n&nbsp;&nbsp;<a href='./gui/gui-qt.py' target='_blank'>gui-qt.py</a><br>\n&nbsp;&nbsp;<a href='./gui/gui-tk.py' target='_blank'>gui-tk.py</a><br>\n&nbsp;&nbsp;<a href='./gui/gui-wx.py' target='_blank'>gui-wx.py</a><br>\n\n\n\n## Rich output and security\n\nThe IPython Notebook allows arbitrary code execution in both the IPython kernel and in the browser, though HTML and JavaScript output. More importantly, because IPython has a JavaScript API for running code in the browser, HTML and JavaScript output can actually trigger code to be run in the kernel. This poses a significant security risk as it would allow IPython Notebooks to execute arbitrary code on your computers.\n\nTo protect against these risks, the IPython Notebook has a security model that specifies how dangerous output is handled. Here is a short summary:\n\n* When you run code in the Notebook, all rich output is displayed.\n* When you open a notebook, rich output is only displayed if it doesn't contain security vulberabilities,...\n* ..or if you have trusted a notebook, all rich output will run upon opening it.\n\nA full description of the IPython security model can be found on [this page](http://ipython.org/ipython-doc/dev/notebook/security.html).\n\n## Rich output and nbviewer\n\nMuch of the power of the Notebook is that it enables users to share notebooks with each other using http://nbviewer.ipython.org, without installing IPython locally. As of IPython 2.0, notebooks rendere on nbviewer will display all output, including HTML and JavaScript. Furthermore, to provide a consistent JavaScript environment on the live Notebook and nbviewer, the following JavaScript libraries are loaded onto the nbviewer page, *before* the notebook and its output is displayed:\n\n* [jQuery](http://jquery.com/)\n* [RequireJS](http://requirejs.org/)\n\nLibraries such as [mpld3](http://mpld3.github.io/) use these capabilities to generate interactive visualizations that work on nbviewer.\n", "meta": {"hexsha": "9de1942aca1508533c8fcdf4a2a28f1e894607d1", "size": 300554, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/1 - IPython Notebook Examples/IPython Project Examples/IPython Kernel/Rich Output.ipynb", "max_stars_repo_name": "tylere/docker-tmpnb-ee", "max_stars_repo_head_hexsha": "50056f9a6d66ab4412b230c39b29b587a2f8a431", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2015-06-30T18:56:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-06T23:05:53.000Z", "max_issues_repo_path": "notebooks/1 - IPython Notebook Examples/IPython Project Examples/IPython Kernel/Rich Output.ipynb", "max_issues_repo_name": "tylere/docker-tmpnb-ee", "max_issues_repo_head_hexsha": "50056f9a6d66ab4412b230c39b29b587a2f8a431", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/1 - IPython Notebook Examples/IPython Project Examples/IPython Kernel/Rich Output.ipynb", "max_forks_repo_name": "tylere/docker-tmpnb-ee", "max_forks_repo_head_hexsha": "50056f9a6d66ab4412b230c39b29b587a2f8a431", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-05-26T13:40:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-05T14:46:22.000Z", "avg_line_length": 90.7743884023, "max_line_length": 64152, "alphanum_fraction": 0.8256719258, "converted": true, "num_tokens": 62525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.132964236762076, "lm_q2_score": 0.06187598615612916, "lm_q1q2_score": 0.008227293273150494}}
{"text": "# Example\n\n\n```python\n!python3 -m pip install git+git://github.com/tensortrade-org/tensortrade.git\n```\n\n    Collecting git+git://github.com/tensortrade-org/tensortrade.git\n      Cloning git://github.com/tensortrade-org/tensortrade.git to /private/var/folders/r9/1ph6hh194qj_w8209my99snc0000gn/T/pip-req-build-wu0s93p0\n      Running command git clone -q git://github.com/tensortrade-org/tensortrade.git /private/var/folders/r9/1ph6hh194qj_w8209my99snc0000gn/T/pip-req-build-wu0s93p0\n    Requirement already satisfied: numpy==1.16.4 in /opt/anaconda3/envs/tensortrade/lib/python3.7/site-packages (from tensortrade==0.1.0rc1) (1.16.4)\n    Requirement already satisfied: pandas==0.25.0 in /opt/anaconda3/envs/tensortrade/lib/python3.7/site-packages (from tensortrade==0.1.0rc1) (0.25.0)\n    Requirement already satisfied: gym==0.14.0 in /opt/anaconda3/envs/tensortrade/lib/python3.7/site-packages (from tensortrade==0.1.0rc1) (0.14.0)\n    Requirement already satisfied: pyyaml==5.1.2 in /opt/anaconda3/envs/tensortrade/lib/python3.7/site-packages (from tensortrade==0.1.0rc1) (5.1.2)\n    Requirement already satisfied: sympy==1.4 in /opt/anaconda3/envs/tensortrade/lib/python3.7/site-packages (from tensortrade==0.1.0rc1) (1.4)\n    Requirement already satisfied: pytz>=2017.2 in /opt/anaconda3/envs/tensortrade/lib/python3.7/site-packages (from pandas==0.25.0->tensortrade==0.1.0rc1) (2019.3)\n    Requirement already satisfied: python-dateutil>=2.6.1 in /opt/anaconda3/envs/tensortrade/lib/python3.7/site-packages (from pandas==0.25.0->tensortrade==0.1.0rc1) (2.8.0)\n    Requirement already satisfied: cloudpickle~=1.2.0 in /opt/anaconda3/envs/tensortrade/lib/python3.7/site-packages (from gym==0.14.0->tensortrade==0.1.0rc1) (1.2.2)\n    Requirement already satisfied: pyglet<=1.3.2,>=1.2.0 in /opt/anaconda3/envs/tensortrade/lib/python3.7/site-packages (from gym==0.14.0->tensortrade==0.1.0rc1) (1.3.2)\n    Requirement already satisfied: six in /opt/anaconda3/envs/tensortrade/lib/python3.7/site-packages (from gym==0.14.0->tensortrade==0.1.0rc1) (1.12.0)\n    Requirement already satisfied: scipy in /opt/anaconda3/envs/tensortrade/lib/python3.7/site-packages (from gym==0.14.0->tensortrade==0.1.0rc1) (1.3.1)\n    Requirement already satisfied: mpmath>=0.19 in /opt/anaconda3/envs/tensortrade/lib/python3.7/site-packages (from sympy==1.4->tensortrade==0.1.0rc1) (1.1.0)\n    Requirement already satisfied: future in /opt/anaconda3/envs/tensortrade/lib/python3.7/site-packages (from pyglet<=1.3.2,>=1.2.0->gym==0.14.0->tensortrade==0.1.0rc1) (0.17.1)\n    Building wheels for collected packages: tensortrade\n      Building wheel for tensortrade (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Created wheel for tensortrade: filename=tensortrade-0.1.0rc1-cp37-none-any.whl size=79410 sha256=e9288cb7882925c90f42a7426e59bcfd7380f77ec50651d4f420b726338d7aef\n      Stored in directory: /private/var/folders/r9/1ph6hh194qj_w8209my99snc0000gn/T/pip-ephem-wheel-cache-_vho_1jn/wheels/d4/5f/92/18e058e7f31d59deb14af7ecd3f907093cc894226b1c7abaa3\n    Successfully built tensortrade\n    Installing collected packages: tensortrade\n    Successfully installed tensortrade-0.1.0rc1\n\n\n\n```python\nimport ssl\nimport pandas as pd\n\n\nssl._create_default_https_context = ssl._create_unverified_context # Only used if pandas gives a SSLError\n\n\ndef fetch(exchange_name, symbol, timeframe):\n    url = \"https://www.cryptodatadownload.com/cdd/\"\n    filename = \"{}_{}USD_{}\".format(exchange_name, symbol, timeframe)\n    df = pd.read_csv('https://www.cryptodatadownload.com/cdd/Coinbase_BTCUSD_1h.csv', skiprows=1)\n    df = df[::-1]\n    df = df.drop([\"Symbol\", \"Volume BTC\"], axis=1)\n    df = df.rename({\"Volume USD\": \"volume\"}, axis=1)\n    df.columns = [name.lower() for name in df.columns]\n    df = df.set_index(\"date\")\n    df.columns = [symbol + \":\" + name.lower() for name in df.columns]\n    return df\n```\n\n## Historical Data\n\n\n```python\ncoinbase_data = pd.concat([\n    fetch(\"Coinbase\", \"BTC\", \"1h\"),\n    fetch(\"Coinbase\", \"ETH\", \"1h\")\n], axis=1)\n\nbitstamp_data = pd.concat([\n    fetch(\"Bitstamp\", \"BTC\", \"1h\"),\n    fetch(\"Bitstamp\", \"ETH\", \"1h\"),\n    fetch(\"Bitstamp\", \"LTC\", \"1h\")\n], axis=1)\n```\n\n\n```python\ncoinbase_data.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>BTC:open</th>\n      <th>BTC:high</th>\n      <th>BTC:low</th>\n      <th>BTC:close</th>\n      <th>BTC:volume</th>\n      <th>ETH:open</th>\n      <th>ETH:high</th>\n      <th>ETH:low</th>\n      <th>ETH:close</th>\n      <th>ETH:volume</th>\n    </tr>\n    <tr>\n      <th>date</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2017-07-01 11-AM</th>\n      <td>2505.56</td>\n      <td>2513.38</td>\n      <td>2495.12</td>\n      <td>2509.17</td>\n      <td>287000.32</td>\n      <td>2505.56</td>\n      <td>2513.38</td>\n      <td>2495.12</td>\n      <td>2509.17</td>\n      <td>287000.32</td>\n    </tr>\n    <tr>\n      <th>2017-07-01 12-PM</th>\n      <td>2509.17</td>\n      <td>2512.87</td>\n      <td>2484.99</td>\n      <td>2488.43</td>\n      <td>393142.50</td>\n      <td>2509.17</td>\n      <td>2512.87</td>\n      <td>2484.99</td>\n      <td>2488.43</td>\n      <td>393142.50</td>\n    </tr>\n    <tr>\n      <th>2017-07-01 01-PM</th>\n      <td>2488.43</td>\n      <td>2488.43</td>\n      <td>2454.40</td>\n      <td>2454.43</td>\n      <td>693254.01</td>\n      <td>2488.43</td>\n      <td>2488.43</td>\n      <td>2454.40</td>\n      <td>2454.43</td>\n      <td>693254.01</td>\n    </tr>\n    <tr>\n      <th>2017-07-01 02-PM</th>\n      <td>2454.43</td>\n      <td>2473.93</td>\n      <td>2450.83</td>\n      <td>2459.35</td>\n      <td>712864.80</td>\n      <td>2454.43</td>\n      <td>2473.93</td>\n      <td>2450.83</td>\n      <td>2459.35</td>\n      <td>712864.80</td>\n    </tr>\n    <tr>\n      <th>2017-07-01 03-PM</th>\n      <td>2459.35</td>\n      <td>2475.00</td>\n      <td>2450.00</td>\n      <td>2467.83</td>\n      <td>682105.41</td>\n      <td>2459.35</td>\n      <td>2475.00</td>\n      <td>2450.00</td>\n      <td>2467.83</td>\n      <td>682105.41</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nbitstamp_data.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>BTC:open</th>\n      <th>BTC:high</th>\n      <th>BTC:low</th>\n      <th>BTC:close</th>\n      <th>BTC:volume</th>\n      <th>ETH:open</th>\n      <th>ETH:high</th>\n      <th>ETH:low</th>\n      <th>ETH:close</th>\n      <th>ETH:volume</th>\n      <th>LTC:open</th>\n      <th>LTC:high</th>\n      <th>LTC:low</th>\n      <th>LTC:close</th>\n      <th>LTC:volume</th>\n    </tr>\n    <tr>\n      <th>date</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2017-07-01 11-AM</th>\n      <td>2505.56</td>\n      <td>2513.38</td>\n      <td>2495.12</td>\n      <td>2509.17</td>\n      <td>287000.32</td>\n      <td>2505.56</td>\n      <td>2513.38</td>\n      <td>2495.12</td>\n      <td>2509.17</td>\n      <td>287000.32</td>\n      <td>2505.56</td>\n      <td>2513.38</td>\n      <td>2495.12</td>\n      <td>2509.17</td>\n      <td>287000.32</td>\n    </tr>\n    <tr>\n      <th>2017-07-01 12-PM</th>\n      <td>2509.17</td>\n      <td>2512.87</td>\n      <td>2484.99</td>\n      <td>2488.43</td>\n      <td>393142.50</td>\n      <td>2509.17</td>\n      <td>2512.87</td>\n      <td>2484.99</td>\n      <td>2488.43</td>\n      <td>393142.50</td>\n      <td>2509.17</td>\n      <td>2512.87</td>\n      <td>2484.99</td>\n      <td>2488.43</td>\n      <td>393142.50</td>\n    </tr>\n    <tr>\n      <th>2017-07-01 01-PM</th>\n      <td>2488.43</td>\n      <td>2488.43</td>\n      <td>2454.40</td>\n      <td>2454.43</td>\n      <td>693254.01</td>\n      <td>2488.43</td>\n      <td>2488.43</td>\n      <td>2454.40</td>\n      <td>2454.43</td>\n      <td>693254.01</td>\n      <td>2488.43</td>\n      <td>2488.43</td>\n      <td>2454.40</td>\n      <td>2454.43</td>\n      <td>693254.01</td>\n    </tr>\n    <tr>\n      <th>2017-07-01 02-PM</th>\n      <td>2454.43</td>\n      <td>2473.93</td>\n      <td>2450.83</td>\n      <td>2459.35</td>\n      <td>712864.80</td>\n      <td>2454.43</td>\n      <td>2473.93</td>\n      <td>2450.83</td>\n      <td>2459.35</td>\n      <td>712864.80</td>\n      <td>2454.43</td>\n      <td>2473.93</td>\n      <td>2450.83</td>\n      <td>2459.35</td>\n      <td>712864.80</td>\n    </tr>\n    <tr>\n      <th>2017-07-01 03-PM</th>\n      <td>2459.35</td>\n      <td>2475.00</td>\n      <td>2450.00</td>\n      <td>2467.83</td>\n      <td>682105.41</td>\n      <td>2459.35</td>\n      <td>2475.00</td>\n      <td>2450.00</td>\n      <td>2467.83</td>\n      <td>682105.41</td>\n      <td>2459.35</td>\n      <td>2475.00</td>\n      <td>2450.00</td>\n      <td>2467.83</td>\n      <td>682105.41</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Define Exchanges\n\nAn exchange needs a name, an execution service, and streams of price data in order to function properly.\n\nThe setups supported right now are the simulated execution service using simulated or stochastic data. More execution services will be made available in the future, as well as price streams so that live data and execution can be supported.\n\n\n```python\nfrom tensortrade.exchanges import Exchange\nfrom tensortrade.exchanges.services.execution.simulated import execute_order\nfrom tensortrade.data import Stream\n\ncoinbase = Exchange(\"coinbase\", service=execute_order)(\n    Stream(\"USD-BTC\", list(coinbase['BTC:close'])),\n    Stream(\"USD-ETH\", list(coinbase['ETH:close']))\n)\n\nbitstamp = Exchange(\"bitstamp\", service=execute_order)(\n    Stream(\"USD-BTC\", list(bitstamp['BTC:close'])),\n    Stream(\"USD-ETH\", list(bitstamp['ETH:close'])),\n    Stream(\"USD-LTC\", list(bitstamp['LTC:close']))\n)\n```\n\nNow that the exchanges have been defined we can define our features that we would like to include, excluding the prices we have provided for the exchanges.\n\n## Define External Data Feed\n\nHere we will define the external feed to use whatever data you would like. From financial indicators to datasets that have nothing to do with instrument prices, they will all have to be defined and incorporated into the external data feed provided to the environment. There is also an internal data feed that is used to collect data on all the wallets and the net worth of the portfolio. You can choose to include this or not by using the `use_internal` parameter of the trading environment.\n\n\n```python\nimport ta\n\nfrom tensortrade.data import DataFeed, Namespace\n\n# Add all features for coinbase bitcoin\ncoinbase_btc = coinbase_data.loc[:, [name.startswith(\"BTC\") for name in coinbase_data.columns]]\n\nta.add_all_ta_features(\n    coinbase_btc,\n    colprefix=\"BTC:\",\n    **{k: \"BTC:\" + k for k in ['open', 'high', 'low', 'close', 'volume']}\n)\n\nnodes = []\nfor name in coinbase_btc.columns:\n    nodes += [Stream(name, list(coinbase_btc[name]))]\n\n# Namespaces are used to give context to features so they don't \n# conflict with features of the same name that are being used for\n# different data (e.g. different exchange)\ncoinbase_ns = Namespace(\"coinbase\")(*nodes) \n    \n\n# Add all features for coinbase ethereum\nbitstamp_eth = bitstamp_data.loc[:, [name.startswith(\"ETH\") for name in bitstamp_data.columns]]  \nta.add_all_ta_features(\n    bitstamp_eth,\n    colprefix=\"ETH:\",\n    **{k: \"ETH:\" + k for k in ['open', 'high', 'low', 'close', 'volume']}\n)\n\nnodes = []\nfor name in coinbase_btc.columns:\n    nodes += [Stream(name, list(coinbase_btc[name]))]\n    \nbitstamp_ns = Namespace(\"coinbase\")(*nodes)\n\nfeed = DataFeed([coinbase_ns, bitstamp_ns])\n```\n\n\n```python\nfeed.next()\n```\n\n\n\n\n    {'coinbase:/BTC:open': 2505.56,\n     'coinbase:/BTC:high': 2513.38,\n     'coinbase:/BTC:low': 2495.12,\n     'coinbase:/BTC:close': 2509.17,\n     'coinbase:/BTC:volume': 287000.32,\n     'coinbase:/BTC:volume_adi': 154659.5371741516,\n     'coinbase:/BTC:volume_obv': 287000.32,\n     'coinbase:/BTC:volume_cmf': 0.5388828039430464,\n     'coinbase:/BTC:volume_fi': nan,\n     'coinbase:/BTC:volume_em': nan,\n     'coinbase:/BTC:volume_sma_em': nan,\n     'coinbase:/BTC:volume_vpt': -187654.4252942016,\n     'coinbase:/BTC:volume_nvi': 1000.0,\n     'coinbase:/BTC:volatility_atr': 0.0,\n     'coinbase:/BTC:volatility_bbm': 2509.17,\n     'coinbase:/BTC:volatility_bbh': 2509.17,\n     'coinbase:/BTC:volatility_bbl': 2509.17,\n     'coinbase:/BTC:volatility_bbw': 0.0,\n     'coinbase:/BTC:volatility_bbhi': 0.0,\n     'coinbase:/BTC:volatility_bbli': 0.0,\n     'coinbase:/BTC:volatility_kcc': 2505.89,\n     'coinbase:/BTC:volatility_kch': 2505.89,\n     'coinbase:/BTC:volatility_kcl': 2487.6299999999997,\n     'coinbase:/BTC:volatility_kchi': 0.0,\n     'coinbase:/BTC:volatility_kcli': 0.0,\n     'coinbase:/BTC:volatility_dcl': 2509.17,\n     'coinbase:/BTC:volatility_dch': 2509.17,\n     'coinbase:/BTC:volatility_dchi': 1.0,\n     'coinbase:/BTC:volatility_dcli': 1.0,\n     'coinbase:/BTC:trend_macd': nan,\n     'coinbase:/BTC:trend_macd_signal': nan,\n     'coinbase:/BTC:trend_macd_diff': nan,\n     'coinbase:/BTC:trend_ema_fast': nan,\n     'coinbase:/BTC:trend_ema_slow': nan,\n     'coinbase:/BTC:trend_adx': 0.0,\n     'coinbase:/BTC:trend_adx_pos': 0.0,\n     'coinbase:/BTC:trend_adx_neg': 0.0,\n     'coinbase:/BTC:trend_vortex_ind_pos': nan,\n     'coinbase:/BTC:trend_vortex_ind_neg': nan,\n     'coinbase:/BTC:trend_vortex_ind_diff': nan,\n     'coinbase:/BTC:trend_trix': nan,\n     'coinbase:/BTC:trend_mass_index': 0.0,\n     'coinbase:/BTC:trend_cci': nan,\n     'coinbase:/BTC:trend_dpo': 4750.493965940025,\n     'coinbase:/BTC:trend_kst': -654.3682997212809,\n     'coinbase:/BTC:trend_kst_sig': -654.3682997212809,\n     'coinbase:/BTC:trend_kst_diff': 0.0,\n     'coinbase:/BTC:trend_ichimoku_a': 2504.25,\n     'coinbase:/BTC:trend_ichimoku_b': 2504.25,\n     'coinbase:/BTC:trend_visual_ichimoku_a': 7247.049603784953,\n     'coinbase:/BTC:trend_visual_ichimoku_b': 7236.058519236877,\n     'coinbase:/BTC:trend_aroon_up': 4.0,\n     'coinbase:/BTC:trend_aroon_down': 4.0,\n     'coinbase:/BTC:trend_aroon_ind': 0.0,\n     'coinbase:/BTC:trend_psar': 2509.17,\n     'coinbase:/BTC:trend_psar_up': nan,\n     'coinbase:/BTC:trend_psar_down': nan,\n     'coinbase:/BTC:trend_psar_up_indicator': 0.0,\n     'coinbase:/BTC:trend_psar_down_indicator': 0.0,\n     'coinbase:/BTC:momentum_rsi': 100.0,\n     'coinbase:/BTC:momentum_mfi': nan,\n     'coinbase:/BTC:momentum_tsi': nan,\n     'coinbase:/BTC:momentum_uo': nan,\n     'coinbase:/BTC:momentum_stoch': 76.94414019715232,\n     'coinbase:/BTC:momentum_stoch_signal': 76.94414019715232,\n     'coinbase:/BTC:momentum_wr': -23.055859802847678,\n     'coinbase:/BTC:momentum_ao': 0.0,\n     'coinbase:/BTC:momentum_kama': nan,\n     'coinbase:/BTC:momentum_roc': nan,\n     'coinbase:/BTC:others_dr': -65.4368299721281,\n     'coinbase:/BTC:others_dlr': nan,\n     'coinbase:/BTC:others_cr': 0.0}\n\n\n\n## Portfolio\n\nMake the portfolio using the any combinations of exchanges and intruments that the exchange supports\n\n\n```python\nfrom tensortrade.instruments import USD, BTC, ETH, LTC\nfrom tensortrade.wallets import Wallet, Portfolio\n\nportfolio = Portfolio(USD, [\n    Wallet(coinbase, 10000 * USD),\n    Wallet(coinbase, 10 * BTC),\n    Wallet(coinbase, 5 * ETH),\n    Wallet(bitstamp, 1000 * USD),\n    Wallet(bitstamp, 5 * BTC),\n    Wallet(bitstamp, 20 * ETH),\n    Wallet(bitstamp, 3 * LTC),\n])\n```\n\n## Environment\n\n\n```python\nfrom tensortrade.environments import TradingEnvironment\n\nenv = TradingEnvironment(\n    portfolio=portfolio,\n    action_scheme='managed-risk',\n    reward_scheme='simple',\n    feed=feed,\n    window_size=15,\n    enable_logger=False\n)\n```\n\n\n```python\nenv.feed.next()\n```\n\n\n\n\n    {'coinbase:/BTC:open': 2505.56,\n     'coinbase:/BTC:high': 2513.38,\n     'coinbase:/BTC:low': 2495.12,\n     'coinbase:/BTC:close': 2509.17,\n     'coinbase:/BTC:volume': 287000.32,\n     'coinbase:/BTC:volume_adi': 154659.5371741516,\n     'coinbase:/BTC:volume_obv': 287000.32,\n     'coinbase:/BTC:volume_cmf': 0.5388828039430464,\n     'coinbase:/BTC:volume_fi': nan,\n     'coinbase:/BTC:volume_em': nan,\n     'coinbase:/BTC:volume_sma_em': nan,\n     'coinbase:/BTC:volume_vpt': -187654.4252942016,\n     'coinbase:/BTC:volume_nvi': 1000.0,\n     'coinbase:/BTC:volatility_atr': 0.0,\n     'coinbase:/BTC:volatility_bbm': 2509.17,\n     'coinbase:/BTC:volatility_bbh': 2509.17,\n     'coinbase:/BTC:volatility_bbl': 2509.17,\n     'coinbase:/BTC:volatility_bbw': 0.0,\n     'coinbase:/BTC:volatility_bbhi': 0.0,\n     'coinbase:/BTC:volatility_bbli': 0.0,\n     'coinbase:/BTC:volatility_kcc': 2505.89,\n     'coinbase:/BTC:volatility_kch': 2505.89,\n     'coinbase:/BTC:volatility_kcl': 2487.6299999999997,\n     'coinbase:/BTC:volatility_kchi': 0.0,\n     'coinbase:/BTC:volatility_kcli': 0.0,\n     'coinbase:/BTC:volatility_dcl': 2509.17,\n     'coinbase:/BTC:volatility_dch': 2509.17,\n     'coinbase:/BTC:volatility_dchi': 1.0,\n     'coinbase:/BTC:volatility_dcli': 1.0,\n     'coinbase:/BTC:trend_macd': nan,\n     'coinbase:/BTC:trend_macd_signal': nan,\n     'coinbase:/BTC:trend_macd_diff': nan,\n     'coinbase:/BTC:trend_ema_fast': nan,\n     'coinbase:/BTC:trend_ema_slow': nan,\n     'coinbase:/BTC:trend_adx': 0.0,\n     'coinbase:/BTC:trend_adx_pos': 0.0,\n     'coinbase:/BTC:trend_adx_neg': 0.0,\n     'coinbase:/BTC:trend_vortex_ind_pos': nan,\n     'coinbase:/BTC:trend_vortex_ind_neg': nan,\n     'coinbase:/BTC:trend_vortex_ind_diff': nan,\n     'coinbase:/BTC:trend_trix': nan,\n     'coinbase:/BTC:trend_mass_index': 0.0,\n     'coinbase:/BTC:trend_cci': nan,\n     'coinbase:/BTC:trend_dpo': 4750.493965940025,\n     'coinbase:/BTC:trend_kst': -654.3682997212809,\n     'coinbase:/BTC:trend_kst_sig': -654.3682997212809,\n     'coinbase:/BTC:trend_kst_diff': 0.0,\n     'coinbase:/BTC:trend_ichimoku_a': 2504.25,\n     'coinbase:/BTC:trend_ichimoku_b': 2504.25,\n     'coinbase:/BTC:trend_visual_ichimoku_a': 7247.049603784953,\n     'coinbase:/BTC:trend_visual_ichimoku_b': 7236.058519236877,\n     'coinbase:/BTC:trend_aroon_up': 4.0,\n     'coinbase:/BTC:trend_aroon_down': 4.0,\n     'coinbase:/BTC:trend_aroon_ind': 0.0,\n     'coinbase:/BTC:trend_psar': 2509.17,\n     'coinbase:/BTC:trend_psar_up': nan,\n     'coinbase:/BTC:trend_psar_down': nan,\n     'coinbase:/BTC:trend_psar_up_indicator': 0.0,\n     'coinbase:/BTC:trend_psar_down_indicator': 0.0,\n     'coinbase:/BTC:momentum_rsi': 100.0,\n     'coinbase:/BTC:momentum_mfi': nan,\n     'coinbase:/BTC:momentum_tsi': nan,\n     'coinbase:/BTC:momentum_uo': nan,\n     'coinbase:/BTC:momentum_stoch': 76.94414019715232,\n     'coinbase:/BTC:momentum_stoch_signal': 76.94414019715232,\n     'coinbase:/BTC:momentum_wr': -23.055859802847678,\n     'coinbase:/BTC:momentum_ao': 0.0,\n     'coinbase:/BTC:momentum_kama': nan,\n     'coinbase:/BTC:momentum_roc': nan,\n     'coinbase:/BTC:others_dr': -65.4368299721281,\n     'coinbase:/BTC:others_dlr': nan,\n     'coinbase:/BTC:others_cr': 0.0,\n     'coinbase:/USD-BTC': 2509.17,\n     'coinbase:/USD-ETH': 2509.17,\n     'coinbase:/USD:/free': 10000,\n     'coinbase:/USD:/locked': 0,\n     'coinbase:/USD:/total': 10000,\n     'coinbase:/BTC:/free': 10,\n     'coinbase:/BTC:/locked': 0,\n     'coinbase:/BTC:/total': 10,\n     'coinbase:/BTC:/worth': 25091.7,\n     'coinbase:/ETH:/free': 5,\n     'coinbase:/ETH:/locked': 0,\n     'coinbase:/ETH:/total': 5,\n     'coinbase:/ETH:/worth': 12545.85,\n     'bitstamp:/USD-BTC': 2509.17,\n     'bitstamp:/USD-ETH': 2509.17,\n     'bitstamp:/USD-LTC': 2509.17,\n     'bitstamp:/USD:/free': 1000,\n     'bitstamp:/USD:/locked': 0,\n     'bitstamp:/USD:/total': 1000,\n     'bitstamp:/BTC:/free': 5,\n     'bitstamp:/BTC:/locked': 0,\n     'bitstamp:/BTC:/total': 5,\n     'bitstamp:/BTC:/worth': 12545.85,\n     'bitstamp:/ETH:/free': 20,\n     'bitstamp:/ETH:/locked': 0,\n     'bitstamp:/ETH:/total': 20,\n     'bitstamp:/ETH:/worth': 50183.4,\n     'bitstamp:/LTC:/free': 3,\n     'bitstamp:/LTC:/locked': 0,\n     'bitstamp:/LTC:/total': 3,\n     'bitstamp:/LTC:/worth': 7527.51,\n     'net_worth': 118894.30999999998}\n\n\n", "meta": {"hexsha": "6c4307320e7efba7f547e4ef3a78d09f3be558c4", "size": 32249, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/New_Example.ipynb", "max_stars_repo_name": "Machine-Learning-Labs/tensortrade", "max_stars_repo_head_hexsha": "3fe7793a6c1d3d7bfe772166578f624f3f572eca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-03-05T14:49:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T01:55:50.000Z", "max_issues_repo_path": "examples/New_Example.ipynb", "max_issues_repo_name": "Machine-Learning-Labs/tensortrade", "max_issues_repo_head_hexsha": "3fe7793a6c1d3d7bfe772166578f624f3f572eca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/New_Example.ipynb", "max_forks_repo_name": "Machine-Learning-Labs/tensortrade", "max_forks_repo_head_hexsha": "3fe7793a6c1d3d7bfe772166578f624f3f572eca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0896969697, "max_line_length": 497, "alphanum_fraction": 0.4994883562, "converted": true, "num_tokens": 7470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091278688527247, "lm_q2_score": 0.03258974488347501, "lm_q1q2_score": 0.008177183712592764}}
{"text": "```python\nimport theme\ntheme.load_style()\n```\n\n\n\n\n<style>\n@import url('http://fonts.googleapis.com/css?family=Source+Code+Pro');\n@import url('http://fonts.googleapis.com/css?family=Vollkorn');\n@import url('http://fonts.googleapis.com/css?family=Arimo');\n@import url('http://fonts.googleapis.com/css?family=Arvo:400,700,400italic')\n\n#notebook li { /* More space between bullet points */\n    margin-top:0.8em;\n}\n\n/* draw border around running cells */\ndiv.cell.border-box-sizing.code_cell.running {\n    border: 3px solid #111;\n}\n\ndiv.cell.code_cell {\n    margin-top: 1em;\n    margin-left: auto;\n    margin-right: auto;\n    width: 800px;\n    border: 1px solid rgba(200, 200, 200, 0.8);\n    border-radius: 8px; /* rounded borders */\n}\n\ndiv.text_cell_render{\n    font-family: 'Arvo' sans-serif;\n    /* font-family: 'Arimo',verdana,arial,sans-serif; */\n    line-height: 130%;\n    font-size: 115%;\n    margin-left:0%;\n    margin-right:auto;\n}\n\n.text_cell_render h1 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 300;\n    font-style: bold;\n    font-size: 30pt;\n    line-height: 100%;\n    color:#c76c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h2 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 20pt;\n    line-height: 100%;\n    color:#c76c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h3 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 16pt;\n    line-height: 100%;\n    color:#d77c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h4 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 14pt;\n    font-style: italic;\n    line-height: 100%;\n    color:#d77c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h5 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 12pt;\n    color: #1d3b84;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n}\n\n.rendered_html code{\n    background-color: transparent;\n}\n\nul{\n    margin: 2em;\n}\n\nul li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.5em;\n}\n\nul li li{\n    padding-left: 0.2em;\n    margin-bottom: 0.2em;\n    margin-top: 0.2em;\n}\n\nol{\n    margin: 2em;\n}\n\nol li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.5em;\n}\n\nul li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.2em;\n}\n\na:link{\n    font-weight: bold;\n    color:#447adb;\n}\n\na:visited{\n    font-weight: bold;\n    color: #1d3b84;\n}\n\na:hover{\n    font-weight: bold;\n    color: #1d3b84;\n}\n\na:focus{\n    font-weight: bold;\n    color:#447adb;\n}\n\na:active{\n    font-weight: bold;\n    color:#447adb;\n}\n\n.rendered_html :link {\n    text-decoration: underline;\n}\n\n.rendered_html :hover {\n    text-decoration: none;\n}\n\n.rendered_html :visited {\n    text-decoration: none;\n}\n\n.rendered_html :focus {\n    text-decoration: none;\n}\n\n.rendered_html :active {\n    text-decoration: none;\n}\n\n.warning{\n    color: rgb( 240, 20, 20 )\n}\n\nhr {\n    color: #f3f3f3;\n    background-color: #f3f3f3;\n    height: 1px;\n}\n\nblockquote{\n    display:block;\n    background: #fcfcfc;\n    border-left: 5px solid #c76c0c;\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    width:680px;\n    padding: 10px 10px 10px 10px;\n}\n\nblockquote p {\n    margin-bottom: 0;\n    line-height: 125%;\n    font-size: 100%;\n}\n\ntable#mytable,\ntable#mytable td,\ntable#mytable tr\n{\n    border: none !important;\n}\n\ntable#mytable-1,\ntable#mytable-1 td,\ntable#mytable-1 tr\n{\n    border: none !important;\n    align: center;\n    cellspacing: 10;\n}\n\n.msg {\n    width: 90%;\n    margin-left: auto;\n    margin-right: auto;\n    margin-top: 10px;\n    margin-bottom: 10px;\n    padding: 14px 14px 14px 14px;\n    color: #c09853;\n    text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);\n    background-color: #fcf8e3;\n    border: 1px solid #fbeed5;\n    -webkit-border-radius: 4px;\n    -moz-border-radius: 4px;\n    border-radius: 4px;\n}\n\n.msg-heading {\n    color: inherit;\n}\n\n.msg .close {\n    position: relative;\n    top: -2px;\n    right: -21px;\n    line-height: 18px;\n}\n\n.msg-success {\n    color: #468847;\n    background-color: #dff0d8;\n    border-color: #d6e9c6;\n}\n\n.msg-danger,\n.msg-error {\n    color: #b94a48;\n    background-color: #f2dede;\n    border-color: #eed3d7;\n}\n\n.msg-info {\n    color: #3a87ad;\n    background-color: #d9edf7;\n    border-color: #bce8f1;\n}\n\n.boxed {\n    color: #b94a48;\n    background-color: #f2dede;\n    border-color: #eed3d7;\n    margin-left: auto;\n    margin-right: auto;\n    padding: 14px 14px 14px 14px;\n}\n\n.w-300 { width: 300px; }\n.w-400 { width: 400px; }\n.w-500 { width: 500px; }\n\n</style>\n\n\n\n\n# Introducing the IPython Notebook\n\nThis lecture is an adaptation of the lecture at [Teaching Numerics with Notebooks](http://nbviewer.ipython.org/github/ketch/teaching-numerics-with-notebooks/blob/master/Introducing%20the%20IPython%20Notebook.ipynb) and is covered by the following license\n\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\"></a>\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\">Creative Commons Attribution 4.0 International License</a>.  All code examples are also licensed under the [MIT license](http://opensource.org/licenses/MIT).\n\n## What is this?\n\nThis is a gentle introduction to the IPython Notebook aimed at lecturers who wish to incorporate it in their teaching, written in an IPython Notebook.  This presentation adapts material from the [IPython official documentation](http://nbviewer.ipython.org/github/ipython/ipython/blob/2.x/examples/Notebook).\n\n## What is an IPython Notebook?\n\nAn IPython Notebook is a:\n\n**[A]** Interactive environment for writing and running code  \n**[B]** Weave of code, data, prose, equations, analysis, and visualization  \n**[C]** Tool for prototyping new code and analysis  \n**[D]** Reproducible workflow for scientific research  \n**[E]** All of the above\n\n**[E]** All of the above\n\n## How Do I Open an IPython Notebook?\n\nOpen a command prompt and execute \n\n    ipython notebook\nand an IPython Notebook server will start and launch a viewer in the default web browser.  Notebooks found in the working directory will show up in the list of notebooks.  \n\n## Example\n\nFor example, navigating to the course `Lessons` directory and executing `ipython notebook` will launch a browser window similar to that shown below\n\n\n\n## Writing and Running Code\n\nThe IPython Notebook consists of an ordered list of cells.  \n\nThere are three important cell types:\n\n* **Code**\n* **Markdown**\n* **Raw NBConvert**\n\n### Code Cells\n\n\n```python\n# This is a code cell made up of Python comments\n# We can execute it by clicking on it with the mouse\n# then clicking the \"Run Cell\" button\n```\n\n\n```python\n# A comment is a pretty boring piece of code\n# This code cell generates \"Hello, World\" when executed\n\nprint \"Hello, World\"\n```\n\n    Hello, World\n\n\n### Code Cells\n\n\n```python\n# Code cells can also generate graphical output\n%matplotlib inline\nimport matplotlib\nmatplotlib.pyplot.hist([0, 1, 2, 2, 3, 3, 3, 4, 4, 4, 10]);\n```\n\n## Modal editor\n\nStarting with IPython 2.0, the IPython Notebook has a modal user interface. This means that the keyboard does different things depending on which mode the Notebook is in. There are two modes: edit mode and command mode.\n\n### Edit mode\n\nEdit mode is indicated by a green cell border and a prompt showing in the editor area:\n\n\n\nWhen a cell is in edit mode, you can type into the cell, like a normal text editor.\n\n<div class=\"msg msg-success\" style=\"margin: 10px\">\nEnter edit mode by pressing `enter` or using the mouse to click on a cell's editor area.\n</div>\n\n<div class=\"msg msg-success\" style=\"margin: 10px\">\nWhile in edit mode, tab-completion works for variables the kernel knows about from executing previous cells.\n</div>\n\n### Command mode\n\nCommand mode is indicated by a grey cell border:\n\n\n\nWhen you are in command mode, you are able to edit the notebook as a whole, but not type into individual cells. Most importantly, in command mode, the keyboard is mapped to a set of shortcuts that let you perform notebook and cell actions efficiently. For example, if you are in command mode and you press `c`, you will copy the current cell - no modifier is needed.\n\n<div class=\"msg msg-error\" style=\"margin: 10px\">\nDon't try to type into a cell in command mode; unexpected things will happen!\n</div>\n\n<div class=\"msg msg-success\" style=\"margin: 10px\">\nEnter command mode by pressing `esc` or using the mouse to click *outside* a cell's editor area.\n</div>\n\n## Mouse navigation\n\nAll navigation and actions in the Notebook are available using the mouse through the menubar and toolbar, which are both above the main Notebook area:\n\n\n\n### Cell Clicking\n\nThe first idea of mouse based navigation is that **cells can be selected by clicking on them.** The currently selected cell gets a grey or green border depending on whether the notebook is in edit or command mode. If you click inside a cell's editor area, you will enter edit mode. If you click on the prompt or output area of a cell you will enter command mode.\n\nIf you are running this notebook in a live session (not on http://nbviewer.ipython.org) try selecting different cells and going between edit and command mode. Try typing into a cell.\n\n### Current Selection\n\nThe second idea of mouse based navigation is that **cell actions usually apply to the currently selected cell**. Thus if you want to run the code in a cell, you would select it and click the \"Play\" button in the toolbar or the \"Cell:Run\" menu item. Similarly, to copy a cell you would select it and click the \"Copy\" button in the toolbar or the \"Edit:Copy\" menu item. With this simple pattern, you should be able to do most everything you need with the mouse.\n\n### Markdown Rendering\n\nMarkdown and heading cells have one other state that can be modified with the mouse. These cells can either be rendered or unrendered. When they are rendered, you will see a nice formatted representation of the cell's contents. When they are unrendered, you will see the raw text source of the cell. To render the selected cell with the mouse, click the \"Play\" button in the toolbar or the \"Cell:Run\" menu item. To unrender the selected cell, double click on the cell.\n\n## Keyboard Navigation\n\nThe modal user interface of the IPython Notebook has been optimized for efficient keyboard usage. This is made possible by having two different sets of keyboard shortcuts: one set that is active in edit mode and another in command mode.\n\nThe most important keyboard shortcuts are `enter`, which enters edit mode, and `esc`, which enters command mode.\n\nIn edit mode, most of the keyboard is dedicated to typing into the cell's editor. Thus, in edit mode there are relatively few shortcuts:\n\n## Keyboard Navigation\n\nIn command mode, the entire keyboard is available for shortcuts.\n\nHere the rough order in which the IPython Developers recommend learning the command mode shortcuts:\n\n1. Basic navigation: `enter`, `shift-enter`, `up/k`, `down/j`\n2. Saving the notebook: `s`\n2. Cell types: `y`, `m`, `1-6`, `t`\n3. Cell creation and movement: `a`, `b`, `ctrl+k`, `ctrl+j`\n4. Cell editing: `x`, `c`, `v`, `d`, `z`, `shift+=`\n5. Kernel operations: `i`, `0`\n\nI suggest learning `h` first!\n\n## The IPython Notebook Architecture\n\nSo far, we have learned the basics of using IPython Notebooks.\n\nFor simple demonstrations, the typical user doesn't need to understand how the computations are being handled, but to successfully write and present computational notebooks, **you** will need to understand how the notebook architecture works.\n\nA *live* notebook is composed of an interactive web page (the front end), a running IPython session (the kernel or back end), and a web server responsible for handling communication between the two (the, err..., middle-end)\n\nA *static* notebook, as for example seen on NBViewer, is a static view of the notebook's content.  The default format is HTML, but a notebook can also be output in PDF or other formats.\n\nThe centerpiece of an IPython Notebook is the \"kernel\", the IPython instance responsible for executing all code.  Your IPython kernel maintains its state between executed cells.\n\n\n```python\nx = 0\nprint x\n```\n\n    0\n\n\n\n```python\nx += 1\nprint x\n```\n\n    1\n\n\n### Interacting with the Kernel\n\nThere are two important actions for interacting with the kernel.  The first is to interrupt it.  This is the same as sending a Control-C from the command line.  The second is to restart it.  This completely terminates the kernel and starts it anew.  None of the kernel state is saved across a restart. \n\n## Markdown cells\n\nText can be added to IPython Notebooks using Markdown cells.  Markdown is a popular markup language that is a superset of HTML.  Its specification can be found here:\n\n<http://daringfireball.net/projects/markdown/>\n\n## Markdown basics\n\n### Text formatting\n\nYou can make text *italic* or **bold**.\n\n### Itemized Lists\n\n* One\n    - Sublist\n        - This\n  - Sublist\n        - That\n        - The other thing\n* Two\n  - Sublist\n* Three\n  - Sublist\n\n### Enumerated Lists\n\n1. Here we go\n    1. Sublist\n    2. Sublist\n2. There we go\n3. Now this\n\n### Horizontal Rules\n\n---\n\n---\n\n---\n\n### Blockquotes\n\n> To me programming is more than an important practical art. It is also a gigantic undertaking in the foundations of knowledge. -- Rear Admiral Grace Hopper\n\n### Links\n\n[IPython's website](http://ipython.org)\n\n### Code\n\n    def f(x):\n        \"\"\"a docstring\"\"\"\n        return x**2\n\nYou can also use triple-backticks to denote code blocks.\nThis also allows you to choose the appropriate syntax highlighter.\n\n```C\nif (i=0; i<n; i++) {\n  printf(\"hello %d\\n\", i);\n  x += 4;\n}\n```\n\n### Tables\n\nTime (s) | Audience Interest\n---------|------------------\n 0       | High\n 1       | Medium\n 5       | Facebook\n\n### Images\n\n\n\n### YouTube\n\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('vW_DRAJ0dtc')\n\n### Other HTML\n\n<strong> Be Bold! </strong>\n\n## Mathematical Equations\n\nCourtesy of MathJax, you can beautifully render mathematical expressions, both inline: \n$e^{i\\pi} + 1 = 0$, and displayed:\n\n$$e^x=\\sum_{i=0}^\\infty \\frac{1}{i!}x^i$$\n\n### Equation Environments\n\nYou can also use a number of equation environments, such as `align`:\n\n\\begin{align}\n  x &= 4 \\\\\ny+z &= x\n\\end{align}\n\n[A full list of available TeX and LaTeX commands is maintained by Dr. Carol Burns.](http://www.onemathematicalcat.org/MathJaxDocumentation/TeXSyntax.htm)\n\n### Other Useful MathJax Notes\n\n* inline math is demarcated by `$ $`, or `\\( \\)`\n* displayed math is demarcated by `$$ $$` or `\\[ \\]`\n* displayed math environments can also be directly demarcated by `\\begin` and `\\end`\n* `\\newcommand` and `\\def` are supported, *within* areas MathJax processes (such as in a `\\[ \\]` block)\n* equation numbering is not officially supported, but it can be indirectly enabled\n\n## A Note about Notebook Security\n\nBy default, a notebook downloaded to a new computer is *untrusted*\n\n* HTML and Javascript in Markdown cells is now *never* executed\n* HTML and Javascript code outputs must be explicitly *re-executed*\n* Some of these restrictions can be mitigrated through shared accounts (Sage MathCloud) and secrets\n\nMore information on notebook security is in the [IPython Notebook documentation](http://ipython.org/ipython-doc/stable/notebook/security.html)\n\n## Magics\n\nIPython kernels execute a superset of the Python language.  The extension functions, commonly referred to as *magics*, come in two variants.  \n\n### Line Magics\n\n* A *line magic* looks like a command line call.  The most important of these is `%matplotlib inline`, which embeds all matplotlib plot output as images in the notebook itself.\n\n\n```python\n%matplotlib inline\n```\n\n\n```python\n%whos\n```\n\n    Variable     Type      Data/Info\n    --------------------------------\n    matplotlib   module    <module 'matplotlib' from<...>matplotlib/__init__.pyc'>\n    x            int       1\n\n\n### Cell Magics\n\n* A *cell magic* takes its entire cell as an argument.  Although there are a number of useful cell magics, you may find `%%timeit` to be useful for exploring code performance.\n\n\n```python\n%%timeit\n\nimport numpy as np\nnp.sum(np.random.rand(1000))\n```\n\n    The slowest run took 464.75 times longer than the fastest. This could mean that an intermediate result is being cached \n    100000 loops, best of 3: 17.6 \u00b5s per loop\n\n\n## Interacting with the Command Line\n\nIPython supports one final trick, the ability to interact directly with your  shell by using the `!` operator.\n\n\n```python\n!ls\n```\n\n    \u001b[30mImages\u001b[m\u001b[m                                       Lesson11_HigherOrderShapeFuncs.ipynb\r\n    Lesson01_IPythonNotebookTutorial.ipynb       Lesson12_ThermalConvection.ipynb\r\n    Lesson01_IPythonNotebookTutorial.slides.html Lesson13_AdvectionDiffusion.ipynb\r\n    Lesson02_IntroductionToPython.ipynb          Lesson14_NonlinearMaterials.ipynb\r\n    Lesson03_DirectMethods.ipynb                 Lesson15_ErrorAnalysis.ipynb\r\n    Lesson04_PlaneTruss.ipynb                    Lesson16_MethodOfManufacturedSolutions.ipynb\r\n    Lesson05_StrongForm.ipynb                    Lesson17_EulerBernouliBeamElement.ipynb\r\n    Lesson06_VariationalForms.ipynb              Lesson20_GeneralizedBoundaryConditions.ipynb\r\n    Lesson07_TheWeakForm.ipynb                   MathematicalPreliminaries.ipynb\r\n    Lesson08_DerivationOf1DEquations.ipynb       \u001b[30mstyles\u001b[m\u001b[m\r\n    Lesson09_ExamplesIn1D.ipynb                  theme.py\r\n    Lesson10_NumericalIntegration.ipynb          theme.pyc\r\n\n\n\n```python\nx = !ls\n```\n\n\n```python\nprint x\n```\n\n    ['Images', 'Lesson01_IPythonNotebookTutorial.ipynb', 'Lesson01_IPythonNotebookTutorial.slides.html', 'Lesson02_IntroductionToPython.ipynb', 'Lesson03_DirectMethods.ipynb', 'Lesson04_PlaneTruss.ipynb', 'Lesson05_StrongForm.ipynb', 'Lesson06_VariationalForms.ipynb', 'Lesson07_TheWeakForm.ipynb', 'Lesson08_DerivationOf1DEquations.ipynb', 'Lesson09_ExamplesIn1D.ipynb', 'Lesson10_NumericalIntegration.ipynb', 'Lesson11_HigherOrderShapeFuncs.ipynb', 'Lesson12_ThermalConvection.ipynb', 'Lesson13_AdvectionDiffusion.ipynb', 'Lesson14_NonlinearMaterials.ipynb', 'Lesson15_ErrorAnalysis.ipynb', 'Lesson16_MethodOfManufacturedSolutions.ipynb', 'Lesson17_EulerBernouliBeamElement.ipynb', 'Lesson20_GeneralizedBoundaryConditions.ipynb', 'MathematicalPreliminaries.ipynb', 'styles', 'theme.py', 'theme.pyc']\n\n\n## A Note about Notebook Version Control\n\nThe IPython Notebook is stored using canonicalized JSON for ease of use with version control systems.\n\nThere are two things to be aware of:\n\n* By default, IPython embeds all content and saves kernel execution numbers.  You may want to get in the habit of clearing all cells before committing.\n\n* As of IPython 2.0, all notebooks are signed on save.  This increases the chances of a commit collision during merge, forcing a manual resolution.  Either signature can be safely deleted in this situation.\n", "meta": {"hexsha": "5c7c0b8e6a107fdb36e12c233265ad2ae6f12d1f", "size": 40838, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lessons/Lesson01_IPythonNotebookTutorial.ipynb", "max_stars_repo_name": "jzw0025/fem-with-python", "max_stars_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 148, "max_stars_repo_stars_event_min_datetime": "2015-11-05T16:32:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:42:26.000Z", "max_issues_repo_path": "Lessons/Lesson01_IPythonNotebookTutorial.ipynb", "max_issues_repo_name": "pinkieli/fem-with-python", "max_issues_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lessons/Lesson01_IPythonNotebookTutorial.ipynb", "max_forks_repo_name": "pinkieli/fem-with-python", "max_forks_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": 74, "max_forks_repo_forks_event_min_datetime": "2016-02-17T13:23:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T07:48:27.000Z", "avg_line_length": 30.3854166667, "max_line_length": 807, "alphanum_fraction": 0.5760811009, "converted": true, "num_tokens": 5055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06656918526680433, "lm_q2_score": 0.12252321091611636, "lm_q1q2_score": 0.008156270326958693}}
{"text": "---\nauthor: \"Marc Weber\"\ntitle: \"Markdown template for scientific report using pandoc\"\ndate: 2018.11.14\nlink-citations: \"true\"\n#bibliography: \"bibliography.bib\"\nbibliography: \"/users/lserrano/mweber/Research_cloud/Bibliography/library.bib\"\n\nwordpress_site_url: \"www.wordpress.org/site\"\nwordpress_username: \"username\"\nwordpress_status: \"draft\"\nwordpress_update_post_if_exists: \"true\"\nwordpress_use_quicklatex: \"true\"\nwordpress_toc: \"true\"\n\n---\n\n# Background\n\n## Introduction\n\nThis document is a template for academic writing, science notebook records and reports. It is written in the Markdown format: it\u2019s plain text, human-readable, and can easily be translated into other formats. It allows to write easily structured text with figures, mathematical formulas and bibliographic references without bothering about formatting. One of the biggest advantage is that by separating writing from formatting, I can keep a single source file in a lightweight text format and generate several different output documents in an automatic fashion. These output, for the moment, are: i) a PDF document generated by LaTeX, ii) a stand-alone HTML with integrated images and iii) a Wordpress post on my personal website.\n\nResources:\n\n+ [Writing academic papers in plain text with Markdown and Jupyter notebook | Sylvain Deville](https://sylvaindeville.net/2015/07/17/writing-academic-papers-in-plain-text-with-markdown-and-jupyter-notebook/)\n+ [Writing Workflow 2016, Part 1: Markdown Writing Environment \u00b7 v & r](http://verifyandrepair.com/04-11-2016/writing-workflow-2016-markdown-environment/)\n\n## Citations\n\n### Citations\n\nCitations are managed by the `pandoc-citeproc`  package (see [pandoc manual section about citations](http://pandoc.org/MANUAL.html#citations)). The use is as follows, now I want to insert an inline citation here: @Gillespie1977. A citation in square brackets format it with parenthesis: [@Miller1965]. Then, I could also use a grouped citations to multiple references like this: [@Danino2010;@Prindle2012]. We can also use citations in footnotes ^[Si2017].\n\nCitations go inside square brackets and are separated by semicolons. Each citation must have a key, composed of \u2018@\u2019 + the citation identifier from the database, and may optionally have a prefix, a locator, and a suffix. To make your citations hyperlinks to the corresponding bibliography entries, add `link-citations: true` to your YAML metadata. \n\n# Outline header 1\n\n## Outline header 2\n\n### Outline header 3\n\n#### Outline header 4\n\n##### Outline header 5\n\nThis is the outline text with a short list. This is the outline text with a short list. This is the outline text with a short list. This is the outline text with a short list. This is the outline text with a short list. This is the outline text with a short list. This is the outline text with a short list. This is the outline text with a short list. This is the outline text with a short list.\n\n+ item 1\n+ item 2\n  + subitem 1\n  + subitem 2\n  \n**Important note**: we need an empty line just *before* the list for pandoc markdown. In other markdown flavors this is not necessary.\n\nWe also test here the \"citation\" html tag: <cite>This is a short citation but we probably could use the quote tag for this, so it seems redundant.</cite>.\n\n# Code highlighting\n\nThis is an inline code example in html `<pre class=\"lang:python\">code example</pre>`{.html}.\n\nThis is a code block in python language:\n\n```python\nprint(\"this is a test\")\ndef new_function(var1=23):\n    return [x for x in range(10) if x > 2]\n\nraise SystemExit\n```\n\nThis is a pre block:\n\n```\nprint(\"this is a test\")\ndef new_function(var1=23):\n    return [x for x in range(10) if x > 2]\n\nraise SystemExit\n```\n\nThis is a code cell in jupyter notebook:\n\n\n```python\n# css: \"/users/lserrano/mweber/Research_Dropbox/Python_mwTools/CSS_for_scientific_reports/pandoc.css\"\n# css: \"/users/lserrano/mweber/Research_Dropbox/Python_mwTools/CSS_for_scientific_reports/github-pandoc.css\"\nprint(\"test\")\ndef function(arg):\n    return list([x for x in range(0,10)])\n```\n\n# Latex math\n\nLatex formulas are rendered by different plugins depending on the output file format. The html for wordpress output will use [QuickLatex](http://www.holoborodko.com/pavel/quicklatex/) wordpress plugin. The self-contained html output will use [MathJax](http://docs.mathjax.org/en/latest/index.html) script. And the pdf output will use the xelatex Latex engine.\n\n#### How to write latex expressions in the markdown master file\n\nIn the *markdown master file*, we should wrap latex expression with tags that are understood by both the jupyter latex engine and the pandoc markdown math syntax, namely:\n\n+ inline math `$ ... $`\n+ display math `$$ ... $$`\n+ math environments, e.g. `\\begin{align} .. \\end{align}`\n\nThen, we will have to tweak pandoc to correctly convert these tags to tags compatible with the different latex engines of each output format.\n\n#### Editing the markdown master file with Jupyter notebook\n\nIf using the jupyter notebook as an editing tool for the markdown master file, we would like to use latex tags that are recognized by the the jupyter markdown rendering engine. Note that in the case of editing the markdown master file with a simple text editor, this would not be important. As mentionned in the [documentation](http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Working%20With%20Markdown%20Cells.html#LaTeX-equations), jupyter uses MathJax to render latex, however with some limitations that are not reported in the documentation. \n\n+ inline math `$ ... $`\n+ display math `$$ ... $$`\n+ math environments (at least `align` and `multline`, probably all environments supported by MathJax)\n\n#### Pandoc markdown to pdf using xelatex\n\nFrom the pandoc [documentation](http://pandoc.org/MANUAL.html#math):\n\n> Anything between two \\$ characters will be treated as TeX math. The opening \\$ must have a non-space character immediately to its right, while the closing \\$ must have a non-space character immediately to its left, and must not be followed immediately by a digit. Thus, \\$20,000 and \\$30,000 won\u2019t parse as math. If for some reason you need to enclose text in literal \\$ characters, backslash-escape them and they won\u2019t be treated as math delimiters.\n\n+ inline math `$ ... $` with the whitespace restrictions.\n+ display math `$$ ... $$`\n+ math environments\n\n#### Wordpress post with QuickLatex plugin\n\n[QuickLatex](http://www.holoborodko.com/pavel/quicklatex/) supports many Latex features, as AMS math, and also custom preamble, which makes it very powerful. Also, all equations are rendered as SVG images, which display crisp at every zooming scale. Because all equations are rendered once and included as SVG images in the post, the load on the client browser is null resulting in fast download and display of the webpage, unlike MathJax script. The supported latex tags are the same as for MathJax:\n\n+ inline math `\\( ... \\)` (`$ ... $` is also supported but is deactivated on my wordpress installation!).\n+ display math `\\[ ... \\]` and `$$ ... $$`\n+ math environments: `equation`, `align`, `displaymath`, `eqnarray`, `multline`, `flalign`, `gather`, and `alignat`.\n\nNote: unfortunately quicklatex is parsing inside `<code></code>` block. This is why double dollar syntax was getting displayed as latex display equation with dots `...` inside. This could happend quite often when printing inline code with regex with escaped parenthesis, for example `re.sub(r'\\(test\\)', r'\\1', \"string\")`. There is no problem in seperate code block because these get in a `pre` block, which QuickLatex does not parse. Solution is to enclose inline code in a `span` tag with `crayon-inline` class, which will enable basic syntax highlighting while preventing any latex parser to mess with it: `<span class=\"decode:true crayon-inline\">re.sub(r'\\(test\\)', r'\\1', \"string\")</span>`{.html}.\n\n```python\nimport re\nre.sub(r'\\(test\\)', r'\\1', \"string\")\n0 < 1\nre.sub(r'$$abc$$', r'a$$abcd$$', string) = \"this should not be parsed as latex expression\"\n```\n\nNow we have to choose one particular syntax for inline and block code, because there is no standard in html5 about how to do that. People either use specific tags: `<codeblock>`, `<code>`{.html}, or the more general `<pre>` tag with class attribute that defines if the code is inline or in block. The Crayon plugin for syntax highlighting that I use on the wordpress site prefers 1) for code block the `<pre class=\"lang:python\">` tag with the class defining the language, and 2) for inline code the `<span class=\"lang:python decode:true  crayon-inline \">` tag with the class giving the language attribute and the `crayon-inline` attribute which defines to insert the code inline. We will use these tags in the output for wordpress post.\n\n\n#### Self-contained html with MathJax script\n\n[MathJax](http://docs.mathjax.org/en/latest/index.html) preprocessor can look for whatever markers to define math delimiters. In the default configuration, the latex tags are\n\n+ inline math `\\( ... \\)`. Important: `$ ... $` is **not** supported by default.\n+ display math `$$ ... $$`\n+ math environments\n+ Need spaces around `<` and `>` symbols in order not to interfere with html syntax, example: `$x < y$`\n\nI wish MathJax could render also all equations as SVG and include them as URI images in the self-contained html file. However, is seems [not possible at this time](https://github.com/jgm/pandoc/issues/682). Latex tags get correctly exported with the pandoc tool by passing the `--mathjax` option.\n\n\n### Examples of LaTeX formulas in markdown master file\n\n#### Inline math\n\ninline latex expression examples enclosed by `$ .. $`: $\\exp\\left(e^{\\tau}\\right) < 1$\n\n+ jupyter nbconvert to Markdown: `$\\exp(e^{\\tau)} < 1$` (unchanged)\n+ pandoc markdown to pdf using xelatex: ok\n+ self-contained html with MathJax script: ok. Converted to html code `<span class=\"math inline\">\\(\\exp(e^{\\tau)} &lt; 1\\)</span>`{.html}\n+ wordpress post: ok, enclosed in span class and recognized by QuickLatex `<span class=\"math inline\">\\(\\exp(e^{\\tau)} &lt; 1\\)</span>`{.html}\n\nImportant: inline latex expression examples enclosed by `\\( .. \\)` is **not compatible** with Pandoc markdown math syntax and will result in an error in pandoc conversion to pdf using latex engine, for example.\n\n#### Display math\n\ndisplay latex expression example enclosed by `$$ ... $$`: $$\\exp\\left(e^{\\tau}\\right) < 1$$\n\n+ jupyter nbconvert to Markdown: `$$\\exp(e^{\\tau)} < 1$$` (unchanged)\n+ pandoc markdown to pdf using xelatex: ok\n+ self-contained html with MathJax script: ok. Converted to html code `<span class=\"math display\">\\[\\exp(e^{\\tau)} &lt; 1\\]</span>`{.html}\n+ wordpress post: ok, enclosed in span class and recognized by QuickLatex `<span class=\"math display\">\\[\\exp(e^{\\tau)} &lt; 1\\]</span>`{.html}\n\n#### Math environments\n\n`align` environment:\n\n\\begin{align}\nx + y &< 0 \\\\\n\\int_{i=0}^N e^{\\alpha t} dt &= \\pi\n\\end{align}\n\n+ jupyter nbconvert to Markdown: (unchanged)\n+ pandoc markdown to pdf using xelatex: ok\n+ self-contained html with MathJax script: ok. Left unchanged in html code.\n+ wordpress post: ok, Left unchanged in html code and recognized by QuickLatex.\n\n`multline` environment:\n\n\\begin{multline}\nx + y + c + a + b + d + e + f + g + x + y + c + a + b + d + \\\\\ne + f + g + x + y + c + a + b + d + e + f + g + \\\\\n+ 4 + a + b + d < \\pi\n\\end{multline}\n\n+ jupyter nbconvert to Markdown: (unchanged)\n+ pandoc markdown to pdf using xelatex: ok\n+ self-contained html with MathJax script: ok. Left unchanged in html code.\n+ wordpress post: ok, Left unchanged in html code and recognized by QuickLatex.\n\n#### Latex in code\n\nThe expressions in inline code and code blocks should **not** get parsed as latex expression. Examples inline: `code with latex-like tags inside $s = 1$ and $$x + y < 0$$`. And codeblock,\n\n```python\nprint(\"code with latex-like tags inside\")\n$s = 1$\n$$x + y < 0$$\n```\n\n+ jupyter editor: unfortunately, the latex expressions inside code blocks gets rendered as LateX expression.\n+ jupyter nbconvert to Markdown: ok (unchanged)\n+ pandoc markdown to pdf using xelatex: ok\n+ self-contained html with MathJax script: ok.\n+ wordpress post: ok\n\n### Latex macros\n\nNew Latex commands can be defined by the `\\newcommand` command inside the markdown file. They will be parsed and macros will be replaced every in the file when producing html output. When producing latex pdf output, the macros will be included in the latex header.\n\n<!-- Latex commands -->\n\\newcommand{\\ee}[1]{\\cdot 10^{#1}\\ }\n\n# Images\n\nImages can be inserted into Markdown documents in a variety of ways, each of one is not compatible with the external software that will convert markdown into PDF, html, or other document type. With Pandoc, the syntax is:\n\n**Markdown syntax**\n\n{#fig:isingmodel1 width=60%}[[ *Phase transition in a growing population of toggle switches interfaced by QS leading to the high $u$ state.* (A) Time evolution of concentration $u$ in color code for an exponentially growing population of toggle switches interfaced by QS.]]\n\n**HTML syntax**\n\n[[ *Phase transition in a growing population of toggle switches interfaced by QS leading to the high $u$ state.* (A) Time evolution of concentration $u$ in color code for an exponentially growing population of toggle switches interfaced by QS. ]]\n\n\nNote that in the case of the markdown syntax, the figure is correctly rendered by the Jupyter notebook interface, **however the figure size directive is not taken into account**. The only way to change the image size in the jupyter interface, which uses standard markdown, is to use an HTML tags (see [python - How to Include image or picture in jupyter notebook - Stack Overflow](http://stackoverflow.com/questions/32370281/how-to-include-image-or-picture-in-jupyter-notebook)). However, images inserted by html tag will probably not get parsed correctly by pandoc (to verify).\n\nWe used a custom syntax for the figure captions, both for markdown and html, in order to be able to display the captions below the plot in a markdown rendered cell in the jupyter notebook. These captions will be converted to the pandoc markdown syntax in the parser script, such that:\n\n```\n{#fig:fig_id width=60%}[[figure caption text.]]\n[[ figure caption text. ]]\n```\n\ndisplays the captions below the figure in the jupyter notebook. The markdown master file will be transformed into the correct pandoc markdown syntax:\n\n```\n{#fig:fig_id width=60%}\n```\n\nThe figure number can be automatically referenced using the package `pandoc-fignos` (see [github webpage](https://github.com/tomduck/pandoc-fignos)) this is a reference to the figure @fig:isingmodel1.\n\n##### Other markdown compatible syntaxes for inserting image\n\nHTML tag:\n\n``\n\nGeneral markdown:\n\n``\n\npandoc style:\n\n`{ width=50% }`\n\npandoc style with fignos package:\n\n`{#fig:id}`\n\n# Styling\n\nThe HTML outputs are styled with custom CSS sheet. I used the package MegaType (SCSS template) to create a responsive design and define all font sizes and line heights of the different elements in order to create a (almost perfect) vertical rhythm, aligning the text baseline on a baseline grid.\n\n{width=80%}[[Baseline grid on desktop device, google chrome.]]\n\n{width=50%}[[Baseline grid on mobile\\ device, google chrome.]]\n\nMore information:\n\n+ [Web typography is broken. Here\u2019s how we can fix it \u2013 Thomas Bredin-Grey \u2013 Medium](https://medium.com/@tbredin/a-jolly-web-typesetting-adventure-42948ab0d1dd)\n+ [StudioThick/megatype: Execute typographic structure with ease](https://github.com/StudioThick/megatype)\n+ [cap-height calculator](http://codepen.io/elrumordelaluz/details/ZGpvvE) (useful to calculate the cap height of some common fonts).\n\n# Bibliography\n\nNote: the Bibliography header is not automatically included by pandoc.\n", "meta": {"hexsha": "8a5f97a1d571ec477cc9783e920775fe4a0c7383", "size": 21136, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Example/markdown_report_template.ipynb", "max_stars_repo_name": "webermarcolivier/pandoc-notebook", "max_stars_repo_head_hexsha": "9c19d04a435c72e09c82c801a99c1f0354ed7a7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-09-30T22:02:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T22:47:41.000Z", "max_issues_repo_path": "Example/markdown_report_template.ipynb", "max_issues_repo_name": "webermarcolivier/pandoc-notebook", "max_issues_repo_head_hexsha": "9c19d04a435c72e09c82c801a99c1f0354ed7a7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Example/markdown_report_template.ipynb", "max_forks_repo_name": "webermarcolivier/pandoc-notebook", "max_forks_repo_head_hexsha": "9c19d04a435c72e09c82c801a99c1f0354ed7a7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-04-23T18:09:36.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-23T18:09:36.000Z", "avg_line_length": 48.9259259259, "max_line_length": 749, "alphanum_fraction": 0.6398088569, "converted": true, "num_tokens": 3904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12421301159407334, "lm_q2_score": 0.06560483654561557, "lm_q1q2_score": 0.008148974322467833}}
{"text": "```python\n%load_ext notexbook\n%texify\n```\n\n\n\n\n<style type=\"text/css\">\n    /*\nAuthor: Valerio Maggio < @leriomaggio >\nCode: https://github.com/leriomaggio/notexbook-jupyter-theme\nLicense: Apache License 2.0\n*/\n\n/*\nAuthor: Valerio Maggio < @leriomaggio >\nCode: https://github.com/leriomaggio/notexbook-jupyter-theme\nLicense: Apache License 2.0\n\n ======================================================\n                         FONTS\n\n    FONT WEIGHT MAP:\n    ----------------\n    100: Ultra Light\n    200: Thin\n    300: Light\n    400: Regular (normal)\n    500: Medium\n    600: Semi-bold\n    700: Bold\n    800: Heavy\n    900: Black\n\n    Font faces:\n        - ====================================|=======================\n        -              Scope                  | Font Family Name\n        - ====================================| ======================\n        - Markdown Display (Computer Modern)    (CMU Serif)\n        - Markdown Display monospace            (CMU Typewriter Text)\n        - Markdown Edit    monospace            (Hack)\n        - Source Code      monospace            (Fira Code)\n        - ====================================| =======================\n\n ======================================================  */\n\n/* Roboto Slab */\n@import url(\"https://fonts.googleapis.com/css2?family=Roboto+Slab:wght@100;200;300;400;500;600;700;800;900&display=swap\");\n/*md-display-computer-modern --> CMU Serif*/\n@import url(\"https://fonts.cdnfonts.com/css/cmu-serif?styles=30038,30039,30037,30036\");\n/*md-display-monospace --> CMU Typewriter Text*/\n@import url(\"https://fonts.cdnfonts.com/css/cmu-typewriter-text?styles=24833,24829,24830,24831,24832,24834\");\n/*code-monospace --> Fira Code*/\n@import url(\"https://fonts.googleapis.com/css2?family=Fira+Code:wght@300;400;500&display=swap\");\n/*md-edit-monospace --> Hack*/\n@import url(\"https://fonts.cdnfonts.com/css/hack?styles=20708,20707,20705,20706\");\n/*\nAuthor: Valerio Maggio < @leriomaggio >\nCode: https://github.com/leriomaggio/notexbook-jupyter-theme\nLicense: Apache License 2.0\n\n======================================================\n\n\n    ---------------------------------\n    Code Mirror - Code Cell Highlight\n    ---------------------------------\n\n    Define the Style for Code **and** Markdown editors (Themes)\n    Theme files are all located in the \"themes\" folder, and the\n    different styles for the Code and Markdown editors are\n    distinguished by a common prefix in the file names:\n\n        --> Code editors Themes: \"themes/code_*\"\n        --> Markdown Editor Themes: \"themes/md_*\"\n\n    Styles can be imported as separate CSS modules.\n\n    Current stylesheet (editor.css) defines the CSS rules\n    for notebook tags and classes. These rules are\n    all based to colors defined in external Theme files.\n\n    This would ease the definition of other custom CSS Editor themes\n*/\n\n/* Code Editor theme */\n\n    /*\nAuthor: Valerio Maggio < @leriomaggio >\nCode: https://github.com/leriomaggio/notexbook-jupyter-theme\nLicense: Apache License 2.0\n\n ======================================================\n\nThe color palette is inspired by Light\n Material Design theme\nRepo: https://github.com/JonaDuran/Material-Light-Theme/\n*/\n\n:root {\n    /* Color Palette */\n    --ml-white: #ffffff;\n    --ml-light-white: #FAFAFA;\n    --ml-black: #24292E;\n    --ml-dark-blue : #01579B11;\n    --ml-dark-blue-2: #01579B22;\n    --ml-blue: #1565C0;\n    --ml-green: #2E7D32;\n    --ml-yellow: #A8601A;\n    --ml-cyan: #00838f;\n    --ml-magenta: #9C00B0;\n    --ml-red: #C0392B;\n    --ml-grey: #9E9E9E;\n    --ml-light-blue: #78909c;\n\n\n    /* Editor Theme */\n    --code-background-color: var(--ml-light-white);\n    --gutter-background: var(--ml-light-white);\n    --selection-background-color: var(--ml-dark-blue-2);\n    --line-numbers: var(--ml-grey);\n    --cursor: var(--ml-black);\n    --bracket: var(--ml-black);\n    --matching-bracket: var(--ml-blue);\n    --code-text-color: var(--ml-black);\n    --keywords: var(--ml-magenta);\n    --types: var(--ml-magenta);\n    --variables: var(--code-text-color);\n    --variables2: var(--ml-green);\n    --def: var(--ml-blue);\n    --property: var(--ml-blue);\n    --meta: var(--ml-light-blue);\n    --builtin: var(--ml-blue);\n    --attribute: var(--ml-blue);\n    --strings: var(--ml-yellow);\n    --strings2: var(--ml-grey);\n    --comments: var(--ml-grey);\n    --operator: var(--ml-magenta);\n    --numbers: var(--ml-red);\n    /* Dataframe */\n    --dataframe: var(--code-text-color);\n    --df-bg: var(--ml-light-white);\n    --df-thead: var(--ml-blue);\n    --df-thead-border: var(--ml-black);\n    --df-tr-hover: var(--selection-background-color);\n    --df-border: var(--ml-white);\n    --df-border-right: var(--ml-grey);\n    --df-th-bg: var(--ml-white);\n    /*ANSI Colours*/\n    --ansi-red: var(--ml-red);\n    --ansi-green: var(--ml-green);\n    --ansi-green-intense: var(--ml-grey);\n    --ansi-cyan: var(--ml-cyan);\n    --ansi-blue: var(--ml-blue);\n}\n\n\n\n/* Markdown Editor theme */\n\n    /*\nAuthor: Valerio Maggio < @leriomaggio >\nCode: https://github.com/leriomaggio/notexbook-jupyter-theme\nLicense: Apache License 2.0\n\n ======================================================\n\n    Custom Theme for Markdown Editor\n    based on Material Clear Theme.\n\n */\n\n:root {\n    /* Color Palette */\n    --md-ml-red: #C0392B;\n    --md-ml-yellow: #A8601A;\n    --md-ml-black: #24292E;\n    --md-ml-grey: #9E9E9E;\n    --md-ml-blue: #1565C0;\n    --md-ml-dark-blue: #01579B;\n    --md-ml-light-blue: #78909c;\n\n    /*  Editor Theme  */\n    --editor-text: var(--md-ml-black);\n    --header: var(--md-ml-dark-blue);\n    --quote: var(--md-ml-grey);\n    --link: var(--md-ml-blue);\n    --attribute: var(--md-ml-red);\n    --tag: var(--md-ml-yellow);\n    --string: var(--md-ml-yellow);\n    --delimiter: var(--md-ml-black);\n    --monospace: var(--md-ml-light-blue);\n}\n\n\n\n\n\n\n\n/*\nAuthor: Valerio Maggio < @leriomaggio >\nCode: https://github.com/leriomaggio/notexbook-jupyter-theme\nLicense: Apache License 2.0\n*/\n\n/*\n    =================\n    Code Editor Theme\n    =================\n*/\ndiv.output_error pre,\ndiv.output_result pre,\ndiv.output_stream pre {\n    color: var(--code-text-color) !important;\n}\n\n.cm-s-ipython.CodeMirror,\n.cm-s-jupyter.CodeMirror {\n    background: var(--code-background-color);\n    color: var(--code-text-color);\n}\n\n.cm-s-ipython div.CodeMirror-selected,\n.cm-s-jupyter div.CodeMirror-selected {\n    cursor: pointer;\n    background: var(--selection-background-color);\n}\n\n.cm-s-ipython .CodeMirror-gutters,\n.cm-s-jupyter .CodeMirror-gutters {\n    background: var(--gutter-background);\n    border-right: 0;\n}\n\n.cm-s-ipython .CodeMirror-linenumber,\n.cm-s-jupyter .CodeMirror-linenumber {\n    color: var(--line-numbers);\n}\n\n.cm-s-ipython .CodeMirror-cursor,\n.cm-s-jupyter .CodeMirror-cursor {\n    border-left: 1px solid var(--cursor) !important;\n}\n\n.cm-s-ipython span.cm-bracket,\n.cm-s-jupyter span.cm-bracket {\n    /*color: #828282;*/\n    color: var(--bracket);\n}\n\nspan.CodeMirror-matchingbracket {\n    text-decoration: underline !important;\n    text-decoration-color: var(--matching-bracket) !important;\n    color: var(--matching-bracket) !important;\n}\n\n.cm-s-ipython span.cm-keyword,\n.cm-s-jupyter span.cm-keyword {\n    color: var(--keywords);\n    font-weight: 400;\n}\n\n.cm-s-ipython span.cm-variable,\n.cm-s-jupyter span.cm-variable {\n    color: var(--variables);\n}\n\n.cm-s-ipython span.cm-variable-2,\n.cm-s-jupyter span.cm-variable-2 {\n    color: var(--variables2);\n}\n\n.cm-s-ipython span.cm-def,\n.cm-s-jupyter span.cm-def {\n    color: var(--def);\n}\n\n.cm-s-ipython span.cm-property,\n.cm-s-jupyter span.cm-property {\n    color: var(--property);\n}\n\n.cm-s-ipython span.cm-meta,\n.cm-s-jupyter span.cm-meta {\n    color: var(--meta);\n}\n\n.cm-s-ipython span.cm-attribute,\n.cm-s-jupyter span.cm-attribute {\n    color: var(--attribute);\n}\n\n.cm-s-ipython span.cm-builtin,\n.cm-s-jupyter span.cm-builtin {\n    color: var(--builtin)\n}\n\n.cm-s-ipython span.cm-string,\n.cm-s-jupyter span.cm-string {\n    color: var(--strings);\n}\n\n.cm-s-ipython span.cm-string-2,\n.cm-s-jupyter span.cm-string-2 {\n    color: var(--strings2);\n}\n\n.cm-s-ipython span.cm-comment,\n.cm-s-jupyter span.cm-comment {\n    color: var(--comments);\n    font-style: normal;\n}\n\n.cm-s-ipython span.cm-operator,\n.cm-s-jupyter span.cm-operator {\n    color: var(--operator);\n    font-weight: 400;\n}\n\n.cm-s-ipython span.cm-number,\n.cm-s-jupyter span.cm-number {\n    color: var(--numbers);\n}\n\n.cm-s-ipython span.cm-type,\n.cm-s-jupyter span.cm-type {\n    color: var(--types);\n}\n\n/*\n==============================\nMarkdown MathJax Customisation\n==============================\n*/\n\n/*This customisation only applies to Math Display showing the font bigger than normal*/\n.MathJax_Display {\n    font-size: 2rem;\n}\n\n.MathJax_Display .mjx-char {\n    font-family: var(--txbk-content-font-family) !important;\n}\n\n.MathJax_Display, .MathJax span {\n    color: var(--code-text-color);\n}\n\na .MathJax span {\n    color: var(--link-color);\n}\n\na:hover .MathJax span {\n    text-decoration: underline;\n}\n\n.MathJax span[style*=\"STIXMathJax_Normal\"],\n.MathJax span[style*=\"STIXMathJax_Normal-italic\"],\n.MathJax span[style*=\"STIXMathJax_Main\"],\n.MathJax span[style*=\"STIXMathJax_Variants\"] {\n    font-family: var(--txbk-content-font-family) !important;\n}\n\n\n/*\n    Pygments CSS (replacement) for HTML export\n    ===========================================\n\n    Original Pygments CSS rewrite thanks to @rubik\n    https://github.com/jupyter/nbconvert/issues/447#issuecomment-270766965\n*/\n\n.highlight .hll, div.highlight > pre {\n    background-color: var(--code-background-color);\n    color: var(--code-text-color);\n    font-family: var(--txbk-code-font-family);\n    font-size: var(--txbk-code-font-size);\n    line-height: var(--txbk-code-line-height);\n}\n\n/* Comment */\n.highlight .c {\n    color: var(--comments);\n}\n\n/* Error */\n.highlight .err {\n    color: #960050;\n    background-color: #1e0010;\n}\n\n/* Keyword */\n.highlight .k {\n    color: var(--keywords);\n    font-weight: 400;\n}\n\n/* Literal */\n.highlight .l {\n    color: var(--numbers);\n}\n\n/* Name */\n.highlight .n {\n    color: var(--code-text-color);\n}\n\n/* HACK:\nfix Interpreter mismatch pygments vs codemirror\nmpl.rcParams <- rcParams will be highlighted as property (as in codemirror)\n*/\n.highlight .o + .n {\n    color: var(--property);\n}\n\n/* Operator */\n.highlight .o {\n    color: var(--code-text-color);\n    font-weight: 400;\n}\n\n/* Punctuation */\n.highlight .p {\n    color: var(--code-text-color);\n}\n\n/* Comment.Multiline */\n.highlight .cm {\n    color: var(--comments);\n    font-style: normal;\n}\n\n/* Comment.Preproc */\n.highlight .cp {\n    color: var(--meta);\n    font-style: normal;\n}\n\n.highlight .cpf {\n    color: var(--meta);\n    font-style: normal;\n}\n\n/* Comment.Single */\n.highlight .c1 {\n    color: var(--comments);\n    font-style: normal;\n}\n\n/* Comment.Special */\n.highlight .cs {\n    color: var(--comments);\n    font-style: normal;\n}\n\n/* @ Generic.Deleted */\n.highlight .gd {\n    color: var(--red);\n}\n\n/* Generic.Emph */\n.highlight .ge {\n    font-style: italic\n}\n\n/* @ Generic.Inserted */\n.highlight .gi {\n    color: #a6e22e\n}\n\n/* Generic.Strong */\n.highlight .gs {\n    font-weight: 500 !important;\n}\n\n/* @ Generic.Subheading */\n.highlight .gu {\n    color: #75715e\n}\n\n/* */\n\n/* Keyword.Constant */\n.highlight .kc {\n    color: var(--keywords);\n    font-weight: 400;\n}\n\n/* Keyword.Declaration */\n.highlight .kd {\n    color: var(--keywords);\n    font-weight: 400;\n}\n\n/* Keyword.Namespace */\n.highlight .kn {\n    color: var(--keywords);\n    font-weight: 400;\n}\n\n/* Keyword.Pseudo */\n.highlight .kp {\n    color: var(--keywords);\n    font-weight: 400;\n}\n\n/* Keyword.Reserved */\n.highlight .kr {\n    color: var(--keywords);\n    font-weight: 400;\n}\n\n/* Keyword.Type */\n.highlight .kt {\n    color: var(--types);\n    font-weight: 400;\n}\n\n/* Literal.Date */\n.highlight .ld {\n    color: var(--numbers)\n}\n\n/* Literal.Number */\n.highlight .m {\n    color: var(--numbers);\n}\n\n/* Literal.String */\n.highlight .s {\n    color: var(--string);\n}\n\n/* Name.Attribute */\n.highlight .na {\n    color: var(--property);\n}\n\n/* Name.Builtin */\n.highlight .nb {\n    color: var(--builtin);\n}\n\n/* Name.Class */\n.highlight .nc {\n    color: var(--def);\n    font-weight: normal !important;\n}\n\n/* @ Name.Constant */\n.highlight .no {\n    color: var(--variables2);\n}\n\n/* Name.Decorator */\n.highlight .nd {\n    color: var(--builtin);\n}\n\n/* @ Name.Entity */\n.highlight .ni {\n    color: var(--variables2);\n}\n\n/* Name.Exception */\n.highlight .ne {\n    color: var(--code-text-color);\n    font-weight: normal !important;\n}\n\n/* Name.Function */\n.highlight .nf, .highlight .fm {\n    color: var(--def);\n}\n\n/* @ Name.Label */\n.highlight .nl {\n    color: var(--comments);\n}\n\n/* Name.Namespace */\n.highlight .nn {\n    color: var(--code-text-color);\n    font-weight: normal !important;\n}\n\n/* @ Name.Other */\n.highlight .nx {\n    color: var(--code-text-color);\n}\n\n/* @ Name.Property */\n.highlight .py {\n    color: var(--property);\n}\n\n/* @ Name.Tag */\n.highlight .nt {\n    color: var(--tag);\n}\n\n/* @ Name.Variable */\n.highlight .nv {\n    color:  var(--variables);\n}\n\n/* Operator.Word */\n.highlight .ow {\n    color: var(--operator);\n    font-weight: 400;\n}\n\n/* @ Text.Whitespace */\n.highlight .w {\n    color: var(--code-background-color);\n\n}\n\n/* Literal.Number.Bin */\n/* Literal.Number.Float */\n/* Literal.Number.Hex */\n/* Literal.Number.Integer */\n/* Literal.Number.Oct */\n.highlight .mb,\n.highlight .mf,\n.highlight .mh,\n.highlight .mi,\n.highlight .mo {\n    color: var(--numbers);\n}\n\n/* Literal.String.Backtick */\n.highlight .sb {\n    color: var(--strings2);\n}\n\n.highlight .sc,  /* Literal.String.Char */\n.highlight .sd,  /* Literal.String.Doc */\n.highlight .s2,  /* Literal.String.Double */\n.highlight .sh,  /* Literal.String.Heredoc */\n.highlight .si,  /* Literal.String.Interpol */\n.highlight .sx,  /* Literal.String.Other */\n.highlight .sr,  /* Literal.String.Regex */\n.highlight .s1,  /* Literal.String.Single */\n.highlight .ss  /* Literal.String.Symbol */\n{\n    color: var(--strings);\n    font-style: normal;\n}\n\n/* Literal.String.Escape */\n.highlight .se {\n    color: var(--red);\n}\n\n/* Name.Builtin.Pseudo */\n.highlight .bp {\n    color: var(--variables2);\n}\n\n/* Name.Variable.Class */\n.highlight .vc {\n    color: var(--variables);\n}\n\n/* Name.Variable.Global */\n.highlight .vg {\n    color: var(--variables2);\n}\n\n/* Name.Variable.Instance */\n.highlight .vi {\n    color: var(--code-text-color);\n}\n\n/* Literal.Number.Integer.Long */\n.highlight .il {\n    color: var(--numbers);\n}\n\n/*\n    Dataframe Colors\n    ----------------\n    Adapt Dataframe table to comply with the theme\n*/\n\ntable.dataframe {\n    color: var(--dataframe) !important;\n}\n\ntable.dataframe tbody tr th {\n    background-color: var(--df-bg);\n}\n\ntable.dataframe tbody tr:hover {\n    background-color: var(--df-tr-hover);\n}\n\ntable.dataframe td, table.dataframe th {\n    border: 1px solid var(--df-border);\n}\n\ntable.dataframe > th:not(:empty) {\n    background-color: var(--df-th-bg);\n}\n\ntable.dataframe tr:nth-child(2) th:empty,\ntable.dataframe tr:nth-child(2) th:empty {\n    border-right: 1px dotted var(--df-border-right);\n}\n\ntable.dataframe thead tr th:not(:empty) {\n    color: var(--df-thead);\n    border-bottom:  1px solid var(--df-thead-border);\n}\n\n/* =======================================\n              ANSI colors\n    (stdout / stderr color customisation)\n   =======================================\n*/\n\nspan.ansi-green-fg {\n    color: var(--ansi-green) !important;\n}\n\nspan.ansi-green-intense-fg{\n    color: var(--ansi-green-intense) !important;\n}\n\nspan.ansi-red-fg {\n    color: var(--ansi-red) !important;\n}\n\nspan.ansi-cyan-fg {\n    color: var(--ansi-cyan) !important;\n}\n\nspan.ansi-blue-fg {\n    color: var(--ansi-blue) !important;\n}\n\nspan.ansi-bold {\n    font-weight: 500 !important;\n}\n\n/* ----------------------------------- */\n\n/*\n    ======================\n    Markdown Editor Theme\n    ======================\n*/\n\ndiv.text_cell.unrendered pre {\n    color: var(--editor-text) !important;\n}\n\nspan.cm-header {\n    color: var(--header) !important;\n    font-weight: 500;\n}\n\nspan.cm-quote {\n    color: var(--quote) !important;\n}\n\nspan.cm-string.cm-url {\n    color: var(--link) !important;\n}\n\nspan.cm-string {\n   color: var(--strings) !important;\n}\n/* Sometimes useful in Mono code Highlighting*/\nspan.cm-string-2 {\n    color: var(--strings2) !important;\n}\n\nspan.cm-link {\n    color: var(--link) !important;\n}\n\nspan.cm-attribute {\n    color: var(--attribute) !important;\n}\n\nspan.cm-tag {\n    color: var(--tag) !important;\n}\n\nspan.cm-delimiter {\n    color: var(--delimiter) !important;\n}\n\nspan.cm-comment {\n    color: var(--comments) !important;\n}\n/*\nAuthor: Valerio Maggio < @leriomaggio >\nCode: https://github.com/leriomaggio/notexbook-jupyter-theme\nLicense: Apache License 2.0\n\n   ---------------------------------------\n    CODE CELL OUTPUT (DISPLAY MODE)\n\n    Pandas DataFrame - as HTML Table\n        (includes also HTML tables)\n\n\n   Note: This stylesheet does NOT include\n   any color nor background color for tables,\n   as those are assumed to be part of the\n   Coding colourisation theme.\n\n   ---------------------------------------\n*/\ntable.dataframe {\n    border-collapse: collapse;\n    border: none;\n    margin-left: 20px !important;\n    font-size: var(--txbk-code-font-size) !important;\n}\n\ntable.dataframe thead {\n    padding-bottom: 10px;\n}\n\ntable.dataframe thead tr {\n    font-style: normal;\n    padding: 5px 10px;\n    border-bottom:  1px solid;\n    vertical-align: middle;\n    text-align: center;\n    empty-cells: hide;\n}\n\ntable.dataframe thead tr th,\ntable.dataframe thead tr:only-child th {\n    vertical-align: middle;\n    text-align: center;\n}\n\ntable.dataframe tbody {\n    padding-top:  5px;\n}\n\ntable.dataframe tbody tr {\n}\n\ntable.dataframe tbody tr th {\n    text-align: left !important;\n    font-style: italic;\n    font-weight: normal;\n    margin-right: 5px;\n}\n\ntable.dataframe tbody tr td {\n    padding-left: 1.0rem;\n    padding-right: 1.0rem;\n}\n\ntable.dataframe tr {\n    border: none;\n}\n\ntable.dataframe td,\ntable.dataframe th {\n    padding-left: 0.25em;\n    padding-right: 0.25em;\n}\n\ntable.dataframe > th:not(:empty) {\n    text-align: left;\n    padding: 0 10px;\n    font-style: italic\n}\n\ntable.dataframe tr:nth-child(2) th:empty,\ntable.dataframe tr:nth-child(2) th:empty {\n    border-left: none;\n}\n\ntable.dataframe td {\n    padding: 0.375em 1em;\n}\n\ntable.dataframe thead {\n\tpadding: 10px 0;\n\tfont-weight: bold;\n}\n\ntable.dataframe thead tr th:not(:empty) {\n    text-align: left;\n    font-style: normal;\n    padding: 5px 10px;\n}\n\n/* Hacking Font-weight bold capped at 500 */\n.rendered_html th {\n    font-weight: 500 !important;\n}\n:root {\n    /* Jupyter Lab Integration (Light Theme) */\n\n    --jp-ui-font-family: var(--txbk-ui-font-family);\n    --jp-ui-font-color1: var(--txbk-ui-color);\n    --jp-ui-font-size1: var(--txbk-ui-font-size);\n\n    --jp-content-font-color1: var(--txbk-content-mono-color);\n    --jp-content-font-family: var(--txbk-content-font-family);\n    --jp-content-line-height: var(--txbk-content-line-height);\n    --jp-content-link-color: var(--link-color);\n    --jp-content-font-size: var(--txbk-content-font-size);\n\n    --jp-layout-color3: #efefef;\n    --jp-notebook-multiselected-color: var(--txbk-multiselect-bgcolor);\n\n    --jp-code-font-size: var(--txbk-code-font-size);\n    --jp-code-line-height: var(--txbk-ui-mono-line-height);\n    --jp-code-padding: 5px;\n    --jp-code-font-family-default: var(--txbk-code-font-family);\n    --jp-code-font-family: var(--jp-code-font-family-default);\n    --jp-code-presentation-font-size: var(--txbk-ui-mono-font-size);\n    --jp-content-heading-font-weight: 500;\n    --jp-content-heading-line-height: 1;\n\n    --jp-cell-prompt-font-family: var(--txbk-code-font-family);\n    --jp-cell-prompt-width: 80px;\n\n    --jp-cell-editor-border-color: transparent;\n\n    --jp-layout-color0: var(--code-background-color);\n    --jp-cell-prompt-not-active-font-color: #aba9a9;\n\n    --jp-cell-editor-background: var(--code-background-color);\n    --jp-cell-editor-active-background: var(--code-background-color);\n    --jp-cell-editor-active-border-color: var(--txbk-cell-edit-border-color);\n\n}\n\n/* ================\n    Jupyter Lab UI\n   ================\n*/\n\n.jp-DirListing-item.jp-mod-running .jp-DirListing-itemIcon:before {\n    color: var(--btn-danger);\n}\n\n.jp-DirListing-item.jp-mod-selected {\n    background-color: var(--texbook-blue);\n    color: white;\n}\n\nbutton.jp-RunningSessions-shutdownAll.jp-mod-styled {\n    color: var(--btn-warning)\n}\n\nbutton.jp-RunningSessions-shutdownAll.jp-mod-styled {\n    color: var(--btn-warning);\n}\n\n.jp-icon-warn0[fill] {\n    fill: var(--texbook-turquoise);\n}\n\n#jp-MainLogo .jp-icon-warn0[fill] {\n    /* Set default not to override logo colour */\n    fill: var(--jp-warn-color0);\n}\n\n/* Change Colour only of Icons on the left-hand side toolbar */\n.jp-SideBar.lm-TabBar.jp-mod-left .jp-icon3[fill] {\n    fill: var(--texbook-yellow);\n}\n\n.jp-SideBar.lm-TabBar.jp-mod-left.lm-TabBar-tab.lm-mod-current .jp-icon3[fill] {\n    fill: var(--texbook-orangex);\n}\n\n/*Kernel*/\ndiv.f14jk5uf[title=\"Kernel Busy\"] .jp-icon3[fill] {\n    fill: var(--kernel-busy);\n}\n\ndiv.f14jk5uf[title=\"Kernel Idle\"] .jp-icon3[fill] {\n    fill: var(--kernel-idle);\n}\n\ndiv.f14jk5uf[title=\"Kernel Unknown\"] .jp-icon3[fill],\ndiv.f14jk5uf[title=\"Kernel Restarting\"] .jp-icon3[fill] {\n    fill: var(--kernel-disconnected);\n}\n\n\n/* body class*/\n\nbody[data-jp-theme-light=\"true\"]:not(.jp-Notebook) {\n    font-family: var(--jp-ui-font-family);\n    background: var(--jp-layout-color3) !important;\n    margin: 0;\n    padding: 0;\n    overflow: hidden;\n}\n\n.jp-Notebook {\n    background-color: var(--background-color) !important;\n    font-weight: 300;\n    color: var(--txbk-ui-color);\n    font-size: var(--txbk-ui-font-size);\n}\n\n\n/* -------------------------------------------------\n    HTML Cells output generics\n    (overriding default JupyterLab theme settings)\n   -------------------------------------------------\n*/\n\n.jp-RenderedHTMLCommon :not(pre) > code {\n    background-color: transparent !important;\n    padding: 0 0 !important;\n}\n\n.jp-RenderedHTMLCommon pre, .jp-RenderedHTMLCommon code {\n    background-color: transparent !important;\n}\n\n.jp-RenderedHTMLCommon p {\n    margin-bottom: 0;\n}\n\n.jp-RenderedHTMLCommon * + p {\n    margin-top: 1em;\n}\n\n\n/* ======================================\n    MARKDOWN CELLS DISPLAY MODE\n    (text_cell_render in Notebook HTML)\n   ======================================\n*/\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon {\n    font-family: var(--txbk-content-font-family) !important;\n    font-size: var(--txbk-content-font-size) !important;\n    color: var(--txbk-content-color) !important;\n    font-kerning: auto;\n    text-align: justify !important;\n    display: block;\n    word-break: normal !important;\n    word-wrap: break-word !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon a {\n    color: var(--link-color) !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h1,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h2,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h3,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h4,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h5,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h6 {\n    font-family:  var(--txbk-content-font-family) !important;\n    font-style: normal !important;\n}\n\n/*  Font-sizes for Headers\n    ----------------------*/\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h1 {\n    font-size: 2.2em !important;\n    text-align: center !important;\n    padding-top:  3rem;\n    padding-bottom: 3rem;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h2 {\n    font-size: 1.9em !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h3 {\n    font-size: 1.7em !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h4 {\n    font-size: 1.5em !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h5 {\n    font-size: 1.3em !important;\n    border-bottom: 1px solid rgb(204, 204, 204);\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon h6 {\n    font-size: 1.1em !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon pre,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon code {\n    font-size: 1em !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon pre,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon code {\n    color: var(--txbk-content-mono-color);\n    font-family: var(--txbk-content-mono-font-family);\n}\n\n\n/* Monospace Code - no code syntax highlight*/\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon pre {\n    /* hack: using code background colour here to allow for compatibility */\n    background-color: var(--code-background-color) !important;\n    font-family: var(--txbk-content-mono-font-family);\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p {\n    line-height: var(--txbk-content-line-height);\n    text-align: justify !important;\n}\n\n/* Monospace inline rendered markdown */\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p code {\n    /*Re-defining variables for Mono using Code Editor's settings*/\n    font-size: var(--txbk-content-mono-font-size);\n    color: var(--txbk-content-mono-color);\n    font-family: var(--txbk-content-mono-font-family);\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p strong code {\n    font-weight: bold !important;\n    color: var(--txbk-content-mono-color);\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p em code {\n    font-style: italic !important;\n    color: var(--txbk-content-mono-color);\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon pre code {\n    padding: 1rem 1.5rem;\n    display: block;\n    color: var(--txbk-content-mono-color);\n    font-family: var(--txbk-content-mono-font-family);\n    word-wrap: break-word;\n    word-break: normal;\n    /* Important Override rules */\n    background-color: var(--txbk-content-mono-bgcolor) !important;\n    font-size: var(--txbk-content-mono-font-size) !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon blockquote {\n    --txbk-ui-color: #6f6f6f;\n    margin: .2rem .2rem;\n    padding: .3rem .5rem;\n    border-left: .3rem solid #a7a7a7;\n    background-color: var(--txbk-content-mono-bgcolor);\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon blockquote:not(:first-child) {\n    margin: 2rem .2rem;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon blockquote p {\n    padding: .2rem 1.5rem;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon table {\n    font-size: var(--txbk-content-font-size) !important;\n    border-collapse: collapse;\n    border-spacing: 0;\n    overflow: auto;\n    break-inside: auto;\n    margin-top: 25px;\n    margin-bottom: 15px;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon table thead {\n    display: table-header-group;\n    vertical-align: middle;\n    border-bottom: none;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon table thead tr,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon table thead tr td,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon table tbody tr,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon table tbody tr th,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon table tbody tr td {\n    break-inside: avoid;\n    break-after: auto;\n    vertical-align: middle;\n    padding: 5px 5px;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon table tr th {\n    border-bottom-width: 0;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ul,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ol {\n    position: relative;\n    display: block;\n    margin-bottom: 0 !important;\n    line-height: var(--txbk-content-line-height);\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ul {\n    list-style-type: disc;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ul li,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ol li {\n    /*white-space: pre-wrap;*/\n    padding: .6rem !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ul ul {\n    list-style-type: circle !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ul ul,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ul ol,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ol ul,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ol ol {\n    padding-top: .3rem !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ul li > ul li,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ul li > ol li,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ol li > ul li,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ol li > ol li {\n    padding: .3rem !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ul li > ul li a code,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ul li > ol li a code,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ol li > ul li a code,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ol li > ol li a code {\n    /*font-size: .7em !important;*/\n    color: var(--link-color);\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon ul ul ul {\n    list-style-type: square !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img:only-child,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img:only-child {\n    display: block;\n    margin: auto;\n    max-width: 40%;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img {\n    max-width: 40%;\n}\n\n/* Img MaxW classes */\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw10,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw10 {\n    max-width: 10% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw15,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw15 {\n    max-width: 15% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw20,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw20 {\n    max-width: 20% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw25,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw25 {\n    max-width: 25% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw30,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw30 {\n    max-width: 30% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw35,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw35 {\n    max-width: 35% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw40,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw40 {\n    max-width: 40% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw45,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw45 {\n    max-width: 45% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw50,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw50 {\n    max-width: 50% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw55,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw55 {\n    max-width: 55% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw60,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw60 {\n    max-width: 60% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw65,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw65 {\n    max-width: 65% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw70,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw70 {\n    max-width: 70% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw75,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw75 {\n    max-width: 75% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw80,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw80 {\n    max-width: 80% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw85,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw85 {\n    max-width: 85% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw90,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw90 {\n    max-width: 90% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw95,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw95 {\n    max-width: 95% !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon img.maxw100,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p > img.maxw100 {\n    max-width: 100% !important;\n}\n\n/* FIX Forcing monospace code to adhere with footnotes rules!*/\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p [id^='fn'] > code,\n.jp-Notebook .jp-MarkdownCell .jp-RenderedHTMLCommon p [class^='fn'] > code {\n    font-size: 1em !important;\n}\n\n/* Code Cell Render (HTML output) */\n.jp-CodeCell .jp-RenderedHTMLCommon {\n    color: var(--code-text-color);\n}\n\n.jp-Notebook .jp-CodeCell .jp-RenderedHTMLCommon p {\n    font-family: var(--txbk-code-font-family);\n    font-size: 1.4em;\n    font-weight: normal;\n}\n\n.jp-Notebook .jp-CodeCell .jp-RenderedHTMLCommon .nomono {\n    font-family: var(--txbk-content-font-family);\n    font-size: 1em;\n    margin-top: 0;\n}\n\n.jp-Notebook .jp-Cell:not(.jp-mod-dropTarget) {\n    background: transparent;\n    border: none;\n}\n\n/* Code Cell Editor */\n\n.jp-InputArea-editor {\n    background-color: var(--jp-cell-editor-active-background);\n}\n\n.jp-Notebook .jp-Cell .jp-InputArea-editor,\n.jp-Notebook .jp-MarkdownCell .jp-MarkdownOutput {\n    /* Set default LEFT border as transparent - to avoid change in paddings when selected */\n    border-left: 0.2rem dotted var(--txbk-cell-border-color);\n    box-shadow: none;\n    border-right: none;\n    border-top: none;\n    border-bottom: none;\n    overflow: hidden;\n}\n\n.jp-Notebook .jp-Cell .jp-Cell-inputWrapper {\n    /* Set default RIGHT border as transparent - to avoid change in paddings when selected */\n    border-right: 5px solid var(--txbk-cell-border-color);\n}\n\n.jp-Notebook .jp-Cell.jp-mod-active.jp-mod-selected:not(.jp-mod-multiSelected) .jp-InputArea-editor,\n.jp-Notebook.jp-mod-commandMode .jp-MarkdownCell.jp-mod-active.jp-mod-selected:not(.jp-mod-multiSelected) .jp-MarkdownOutput {\n    /* Force border redefinition to override default Jupyter theme rules */\n    border-left: 0.2rem dotted var(--txbk-cell-selected-border-left-color);\n    box-shadow: none;\n    border-right: none;\n    border-top: none;\n    border-bottom: none;\n    overflow: hidden;\n}\n\n.jp-Notebook.jp-mod-commandMode .jp-Cell.jp-mod-active.jp-mod-selected:not(.jp-mod-multiSelected) .jp-Cell-inputWrapper {\n    border-right-color: var(--txbk-cell-display-border-color);\n}\n\n.jp-Notebook.jp-mod-editMode .jp-Cell.jp-mod-active.jp-mod-selected:not(.jp-mod-multiSelected) .jp-Cell-inputWrapper {\n    border-right-color: var(--txbk-cell-edit-border-color);\n}\n\n/* Cell Multiple Selection */\n.jp-Notebook.jp-mod-commandMode .jp-Cell.jp-mod-selected:not(.jp-mod-active),\n.jp-Notebook.jp-mod-commandMode .jp-Cell.jp-mod-multiSelected {\n    border: 2px dashed var(--texbook-azure);\n    background: var(--txbk-multiselect-bgcolor);\n    margin-top: 10px;\n}\n\n/*\n    Overlay with Shadow for Code Cell Selected !\n    ============================================\n*/\n/* Overlay limited to CodeCells */\n.jp-Notebook .jp-CodeCell.jp-mod-selected {\n    border: none;\n    background: transparent;\n    box-shadow: 0 6px 18px #aaa;\n    z-index: 10;\n    top: -10px;\n    padding-top: 12px;\n    padding-bottom: 12px;\n    margin-top: 18px;\n    margin-bottom: 2px;\n}\n\n.jp-Notebook .jp-CodeCell.jp-mod-active.jp-mod-selected:before {\n    position: absolute;\n    display: none;\n    top: -1px;\n    left: -1px;\n    width: 0;\n    height: calc(100% + 2px);\n    content: '';\n    background: none;\n}\n\n.jp-Notebook .jp-Cell .jp-Collapser {\n    display: none !important;\n}\n\n.jp-Notebook .jp-CodeCell .jp-InputPrompt {\n    color: var(--texbook-light-grey) !important;\n    font-style: normal !important;\n    font-size: 1em;\n    opacity: 1 !important;\n    font-weight: normal;\n    min-width: 9.5ex;\n}\n\n.jp-OutputPrompt {\n    color: transparent !important;\n    min-width: 9.5ex;  /* Aligns with Input Prompt */\n}\n\n.jp-Notebook .jp-CodeCell .jp-InputPrompt bdi,\n.jp-Notebook .jp-CodeCell .jp-OutputPrompt  bdi {\n    line-height: 0;\n    font-size:0;\n    color: transparent;\n    left: -10000px;\n    content: \"\\21E2\";\n}\n\n/*.jp-Notebook .jp-CodeCell.jp-mod-active.jp-mod-selected:not(.jp-mod-multiSelected) .jp-InputPrompt:before {*/\n.jp-Notebook .jp-CodeCell.jp-mod-active.jp-mod-selected:not(.jp-mod-multiSelected) .jp-InputArea:before {\n    display: inline-block;\n    position: absolute;\n    content: \"\\279E\";\n    font-size: 1.75rem;\n    top: 4px;\n    width: 10px;\n    left: 0;\n    font-weight: bold !important;\n}\n\n.jp-Notebook.jp-mod-commandMode .jp-CodeCell.jp-mod-active.jp-mod-selected:not(.jp-mod-multiSelected) .jp-InputArea:before {\n    color: var(--txbk-cell-display-border-color);\n}\n\n.jp-Notebook.jp-mod-editMode .jp-CodeCell.jp-mod-active.jp-mod-selected:not(.jp-mod-multiSelected) .jp-InputArea:before {\n    color: var(--txbk-cell-edit-border-color);\n}\n\n/* =============\n   Code Editors\n   ============= */\n\n.jp-Notebook .jp-Cell .CodeMirror * {\n    line-height: var(--txbk-code-line-height);\n}\n\n.jp-Notebook .jp-CodeCell .CodeMirror * {\n    font-family: var(--txbk-code-font-family) !important;\n    font-size: var(--txbk-code-font-size) !important;\n}\n\n.jp-Notebook .jp-MarkdownCell .CodeMirror * {\n    font-family: var(--txbk-md-font-family) !important;\n    font-size: var(--txbk-md-font-size) !important;\n}\n\n/* Cell Output rendering (.output_area in Notebook HTML) */\n\n.jp-OutputArea-output.jp-RenderedText pre,\n.jp-OutputArea-output.jp-RenderedMarkdown p {\n    padding-bottom: 15px;\n    padding-top: 10px;\n}\n\n.jp-OutputArea-output.jp-RenderedMarkdown p {\n    font-size: var(--txbk-content-font-size);\n}\n\n.jp-OutputArea-output.jp-RenderedMarkdown pre code {\n    font-size: var(--txbk-content-mono-font-size);\n    font-family: var(--txbk-content-mono-font-family);\n    color: var(--txbk-content-mono-color);\n}\n\n.jp-OutputArea-output.jp-RenderedText pre {\n    --txbk-content-mono-font-family: var(--txbk-code-font-family);\n    font-size: var(--txbk-code-font-size);\n    font-weight: normal;\n    word-break: normal;\n    word-wrap: break-word;\n}\n\n/* Standard Error */\n.jp-RenderedText[data-mime-type='application/vnd.jupyter.stderr'] {\n    background: none !important;\n}\n/*\nAuthor: Valerio Maggio < @leriomaggio >\nCode: https://github.com/leriomaggio/notexbook-jupyter-theme\nLicense: Apache License 2.0\n*/\n\n/* HTML Export (Jupyter Light Theme)\n   ================================ */\n\nbody.jp-Notebook .jp-CodeCell .jp-InputPrompt {\n    margin-top: 7px;\n    overflow: initial;\n}\n\nbody.jp-Notebook .CodeMirror-linenumber {\n    --txbk-ui-mono-font-size: 10px !important;\n}\n\nbody.jp-Notebook .jp-RenderedHTMLCommon.jp-MarkdownOutput p > img:only-child,\nbody.jp-Notebook .jp-RenderedHTMLCommon.jp-MarkdownOutput img:only-child {\n    max-width: 30%;\n}\n\nbody.jp-Notebook .jp-CodeCell .jp-InputPrompt {\n    font-size: var(--txbk-code-font-size);\n    padding-top: 4px;\n}\n\n/* ==================================================\n   IMPORTANT NOTE:\n   ALL markdown rules cells needs adapting because of\n   a different structure in exported HTML\n   ===================================================\n*/\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput {\n    font-family: var(--txbk-content-font-family) !important;\n    font-size: var(--txbk-content-font-size) !important;\n    color: var(--txbk-content-color) !important;\n    font-kerning: auto;\n    text-align: justify !important;\n    display: block;\n    word-break: normal !important;\n    word-wrap: break-word !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  a {\n    color: var(--link-color) !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h1,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h2,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h3,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h4,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h5,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h6 {\n    font-family:  var(--txbk-content-font-family) !important;\n    font-style: normal !important;\n}\n\n/*  Font-sizes for Headers\n    ----------------------*/\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h1 {\n    font-size: 2.2em !important;\n    text-align: center !important;\n    padding-top:  3rem;\n    padding-bottom: 3rem;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h2 {\n    font-size: 1.9em !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h3 {\n    font-size: 1.7em !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h4 {\n    font-size: 1.5em !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h5 {\n    font-size: 1.3em !important;\n    border-bottom: 1px solid rgb(204, 204, 204);\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  h6 {\n    font-size: 1.1em !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  p,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  pre,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  code {\n    font-size: 1em !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  pre,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  code {\n    color: var(--txbk-content-mono-color);\n}\n\n\n/* Monospace Code - no code syntax highlight*/\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  pre {\n    /* hack: using code background colour here to allow for compatibility */\n    background-color: var(--code-background-color) !important;\n    font-family: var(--txbk-content-mono-font-family) !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  p {\n    line-height: var(--txbk-content-line-height);\n    text-align: justify !important;\n}\n\n/* Monospace inline rendered markdown */\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  p code {\n\n    /*Re-defining variables for Mono using Code Editor's settings*/\n    --txbk-content-mono-font-family: var(--txbk-code-font-family);\n    --txbk-content-mono-font-size: var(--txbk-code-font-size);\n\n    background-color: var(--txbk-content-mono-bgcolor) !important;\n    font-size: var(--txbk-content-mono-font-size) !important;\n    color: var(--txbk-content-mono-color);\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  p strong code {\n    font-weight: bold !important;\n    color: var(--txbk-content-mono-color);\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  p em code {\n    font-style: italic !important;\n    color: var(--txbk-content-mono-color);\n}\n\nbody.jp-Notebook .jp-CodeCell .jp-RenderedHTMLCommon p.nomono {\n    font-family: var(--txbk-content-font-family);\n    font-size: 1em;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  pre code {\n    padding: 1rem 1.5rem;\n    display: block;\n    color: var(--txbk-content-mono-color);\n    background-color: var(--txbk-content-mono-bgcolor) !important;\n    font-family: var(--txbk-content-mono-font-family);\n    font-size: var(--txbk-content-mono-font-size) !important;\n    word-wrap: break-word;\n    word-break: normal;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  blockquote {\n    --txbk-ui-color: #6f6f6f !important;\n\n    margin: 2rem .2rem !important;\n    padding: .3rem .5rem !important;\n    border-left: .3rem solid #a7a7a7 !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  blockquote p {\n    padding: .2rem 1.5rem;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  table {\n    margin-top: 25px;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  table {\n    font-size: var(--txbk-content-font-size) !important;\n    border-collapse: collapse;\n    border-spacing: 0;\n    width: 100%;\n    overflow: auto;\n    break-inside: auto;\n    text-align: left;\n    margin-top: 25px;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  table thead {\n    display: table-header-group;\n    vertical-align: middle !important;\n    border-bottom: none !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  table thead tr,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  table thead tr td,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  table tbody tr,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  table tbody tr th,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  table tbody tr td {\n    break-inside: avoid;\n    break-after: auto;\n    text-align: left !important;\n    vertical-align: middle !important;\n    padding: 0 !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  table tr th {\n    border-bottom-width: 0;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol {\n    position: relative;\n    display: block;\n    margin-bottom: 0 !important;\n    line-height: var(--txbk-content-line-height);\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul {\n    list-style-type: disc;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul li,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol li {\n    /*white-space: pre-wrap;*/\n    padding: .8rem !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul li > code,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol li > code {\n    font-size: .9em !important\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul li a code,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol li a code {\n    font-size: .9em !important\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul ul {\n    list-style-type: circle !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul ul,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul ol,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol ul,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol ol {\n    padding-top: .5rem !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul li > ul li,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul li > ol li,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol li > ul li,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol li > ol li {\n    padding: .5rem !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul li > ul li code,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul li > ol li code,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol li > ul li code,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol li > ol li code {\n    font-size: .9em !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul li > ul li a code,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul li > ol li a code,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol li > ul li a code,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ol li > ol li a code {\n    font-size: .9em !important;\n    color: var(--link-color);\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  ul ul ul {\n    list-style-type: square !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  p > img:only-child,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  img:only-child {\n    display: block;\n    margin: auto;\n    max-width: 40%;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  img {\n    max-width: 40%;\n}\n\n/* Img MaxW classes */\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  img.maxw10,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  p > img.maxw10 {\n    max-width: 5% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw15,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw15 {\n    max-width: 5% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw20,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw20 {\n    max-width: 10% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw25,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw25 {\n    max-width: 15% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw30,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw30 {\n    max-width: 20% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw35,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw35 {\n    max-width: 25% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw40,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw40 {\n    max-width: 30% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw45,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw45 {\n    max-width: 35% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw50,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw50 {\n    max-width: 40% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw55,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw55 {\n    max-width: 45% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw60,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw60 {\n    max-width: 50% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw65,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw65 {\n    max-width: 55% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw70,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw70 {\n    max-width: 60% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw75,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw75 {\n    max-width: 65% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw80,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw80 {\n    max-width: 70% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw85,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw85 {\n    max-width: 75% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw90,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw90 {\n    max-width: 80% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw95,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw95 {\n    max-width: 85% !important;\n}\n\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput img.maxw100,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput p > img.maxw100 {\n    max-width: 90% !important;\n}\n\n/* FIX Forcing monospace code to adhere with footnotes rules!*/\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  p [id^='fn'] > code,\nbody.jp-Notebook .jp-Cell-inputWrapper .jp-RenderedHTMLCommon.jp-RenderedMarkdown.jp-MarkdownOutput  p [class^='fn'] > code {\n    font-size: 1em !important;\n}\n\n\n/* ======================================================\n              GLOBALS (with vars integration)\n   ======================================================\n*/\n\n\n:root {\n    --template-txbk-content-font-size: 16px;\n    --template-txbk-content-line-height: 1.4;\n    --template-txbk-content-mono-font-family: \"CMU Typewriter Text\", \"Fira Code\", monospace;\n    --template-txbk-code-font-family: \"Fira Code\", \"Fira Code\", monospace;\n    --template-txbk-md-font-family: \"Hack\", \"Hack\", monospace;\n    --template-txbk-code-font-size: 14px;\n    --template-txbk-md-font-size: 14px;\n}\n\n/* ======================================================\n                         GLOBALS\n   ======================================================\n*/\n\n:root {\n    /* Base colors */\n    --texbook-red: #d43133;\n    --texbook-pink: #D14187;\n    --texbook-turquoise: #009489;\n    --texbook-azure: #00afde;\n    --texbook-blue: #2875d9;\n    --texbook-light-grey: #828282;\n    --texbook-dark-grey: rgb(56, 56, 56);\n    --texbook-yellow: #f9ab00;\n    --texbook-orange: #e8710a;\n\n    /* Font formatting */\n    --background-color: #ffffff;\n    --txbk-ui-font-family: \"Roboto Slab\", \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n    --txbk-ui-color: rgb(51, 51, 51);\n    --txbk-ui-font-size: 14px;\n    --txbk-ui-line-height: 1;\n\n    --txbk-ui-header-font-family: \"Roboto Slab\", \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n    --txbk-ui-header-color: rgb(56, 56, 56);\n\n    --txbk-ui-mono-color: #828282;\n    --txbk-ui-mono-font-size: 15px;\n    --txbk-ui-mono-line-height: 1.4;\n\n    /* Cells */\n    --txbk-cell-selected-border-left-color: lightgrey;\n    --txbk-cell-border-color: var(--background-color);\n    --txbk-multiselect-bgcolor: var(--background-color);\n    --txbk-cell-display-border-color: #009489;\n    --txbk-cell-edit-border-color: #d43133;\n\n    /* Content Formatting */\n    --txbk-content-font-family: \"CMU Serif\", \"Times New Roman\", serif;\n    --txbk-content-font-size: var(--template-txbk-content-font-size);\n    --txbk-content-color: rgb(51, 51, 51);\n    --txbk-content-line-height: var(--template-txbk-content-line-height);\n\n    --txbk-content-mono-font-family: var(--template-txbk-content-mono-font-family);\n    --txbk-content-mono-font-size: var(--txbk-content-font-size);\n    --txbk-content-mono-color: var(--texbook-dark-grey);\n    --txbk-content-mono-bgcolor: var(--code-background-color);\n\n    --txbk-code-font-family: var(--template-txbk-code-font-family);\n    --txbk-code-font-size: var(--template-txbk-code-font-size);\n    --txbk-md-font-family: var(--template-txbk-md-font-family);\n    --txbk-md-font-size: var(--template-txbk-md-font-size);\n    --txbk-code-line-height: 1.6;\n    --txbk-code-color: var(--code-text-color);\n    --txbk-code-bgcolor: var(--code-background-color);\n\n    --link-color: var(--texbook-blue);\n    --del-color: var(--texbook-red);\n    --drop-cap-color: var(--texbook-red);;\n\n    --kernel-name-color: var(--texbook-azure);\n    --kernel-idle: var(--texbook-turquoise);\n    --kernel-busy: var(--texbook-pink);\n    --kernel-disconnected: var(--texbook-red);\n    --btn-warning: var(--texbook-pink);\n    --btn-danger: var(--texbook-red);\n    --running-notebook: var(--texbook-turquoise);\n}\n\nhtml {\n    font-size: 10px;\n}\n\nbody {\n\n    background-color: var(--background-color) !important;\n    font-weight: 300;\n    font-family: var(--txbk-ui-font-family);\n    color: var(--txbk-ui-color);\n    overflow: inherit;\n    vertical-align: middle;\n    font-size: var(--txbk-ui-font-size);\n}\n\nh1, h2, h3, h4, h5, h6, label > strong {\n    font-family: var(--txbk-ui-header-font-family);\n    color: var(--txbk-ui-header-color);\n}\n\nh1 img, h2 img , h3 img, h4 img, h5 img, h6 img {\n    display: inline !important;\n}\n\nh1 {\n    font-weight: bold;\n    font-style: normal;\n}\n\nh2 {\n    font-weight: bold;\n    font-style: italic;\n}\n\nh3 {\n    font-weight: 600;\n    font-style: normal;\n}\n\nh4 {\n    font-weight: 500;\n    font-style: normal;\n}\n\nh5, h6 {\n    font-weight: 500;\n    font-style: italic;\n}\n\ncode, kbd, pre, samp {\n    font-family: var(--txbk-code-font-family);\n    color: var(--txbk-ui-mono-color);\n    font-weight: 400;\n    font-size: var(--txbk-ui-mono-font-size);\n    line-height: var(--txbk-ui-mono-line-height);\n}\n\ntable > thead > tr > td.info,\ntable > tbody > tr > td.info,\ntable > tfoot > tr > td.info,\ntable > thead > tr > th.info,\ntable > tbody > tr > th.info,\ntable > tfoot > tr > th.info,\ntable > thead > tr.info > td,\ntable > tbody > tr.info > td,\ntable > tfoot > tr.info > td,\ntable > thead > tr.info > th,\ntable > tbody > tr.info > th,\ntable > tfoot > tr.info > th {\n    background-color: #d9edf7;\n}\n\ndel {\n    color: var(--del-color) !important;\n}\n\n/* ======================================================\n                 Intro/Home Page Server\n   ======================================================\n*/\n\n#ipython-main-app p {\n    text-align: justify !important;\n}\n\n.toolbar_info,\n.list-container {\n    color: #828282;\n}\n\n.list_placeholder {\n    font-family: \"Roboto Slab\", serif !important;\n    font-weight: 300;\n    font-style: normal;\n}\n\na.item_link {\n    color: var(--link-color);\n    font-weight: 300;\n}\n\n.item_buttons .kernel-name {\n    color: var(--kernel-name-color);\n    font-weight: 400;\n}\n\n.btn-warning {\n    background-color: var(--btn-warning) !important;\n    border-color: var(--btn-warning) !important;\n}\n\n.btn-warning:focus {\n    border-color: var(--btn-warning) !important;\n}\n\n.btn-danger {\n    background-color: var(--btn-danger) !important;\n    border-color: var(--btn-danger) !important;\n}\n\n.btn-danger:focus {\n    border-color: var(--btn-danger) !important;\n}\n\n.running-indicator,\n.running_notebook_icon:before {\n    color: var(--running-notebook);\n}\n\n\n\n/* ======================================================\n                         Notebook\n   ======================================================\n*/\n\n/* Modal Dialog */\n\n.modal-header > h4 {\n    font-style: normal !important;\n    text-decoration: none !important;\n    font-family: var(--txbk-ui-font-family) !important;\n    margin: 0 !important;\n}\n\n.notebook_app {\n    background-color: var(--background-color) !important;\n    font-family: \"Helvetica Neue\", Helvetica, Arial, sans-serif !important;\n    font-weight: normal;\n}\n\ndiv#notebook_name {\n    font-family: var(--txbk-ui-font-family) !important;\n    font-weight: normal;\n    font-size: 24px;\n    padding: 1px 7px 1px 1px;\n}\n\ndiv#site {\n\toverflow: inherit;\n    top: 112px;\n    position: absolute;\n}\n\n#header {\n    display: block;\n    position: fixed !important;\n    top: 0;\n    width: 100%;\n    max-width: 100%;\n    height: fit-content;\n    background-color: var(--background-color);\n}\n\n#notebook-container {\n    /* Remove shadow so that it looks like a page of a PDF doc */\n    box-shadow: none !important;\n    -webkit-box-shadow: none !important;\n    padding: 0;\n}\n\ndiv#notebook {\n    border-top: none;\n    font-size: 1rem;\n    padding: 0 !important;\n    padding-top: 30px !important;\n    font-family: var(--txbk-content-font-family) !important;\n}\n\n.kernel_idle_icon:before {\n    color: var(--kernel-idle);\n}\n\n.kernel_busy_icon:before {\n    color: var(--kernel-busy);\n}\n\n.kernel_disconnected_icon:before {\n    color: var(--kernel-disconnected);\n}\n\n#notification_area {\n    font-family: var(--txbk-ui-font-family);\n}\n\n#notification_kernel {\n    color: #fff;\n    background-color: var(--kernel-idle);\n    border-color: var(--kernel-idle);\n}\n\n#notification_kernel.warning {\n    color: #fff;\n    background-color: var(--kernel-disconnected);\n    border-color: var(--kernel-disconnected);\n}\n\n#notification_trusted {\n    border-color: var(--kernel-disconnected);\n}\n\n#notification_trusted[disabled=\"disabled\"] {\n    border-color: var(--kernel-idle);\n}\n\n\n#notification_notebook {\n    border-color: var(--kernel-idle);\n}\n\n/* -----------------------------------\n    CELLS\n   -----------------------------------\n*/\n\ndiv.cell {\n    right: 2px;\n    border:  none;\n    margin-top: 5px;\n}\n\ndiv.cell.selected {\n    /* Reset all - ready for customisation */\n    border-radius: 0;\n    background: none;\n}\n\ndiv.cell .inner_cell {\n    border-right: 5px solid var(--txbk-cell-border-color);\n    border-left:  0.2rem dotted var(--txbk-cell-border-color);\n}\n\ndiv.cell.selected:not(.jupyter-soft-selected) .inner_cell {\n    border-left-color:  var(--txbk-cell-selected-border-left-color);\n}\n\n.command_mode div.cell.selected:not(.jupyter-soft-selected) .inner_cell {\n    border-right-color: var(--txbk-cell-display-border-color);\n}\n\n.edit_mode div.cell.selected:not(.jupyter-soft-selected) .inner_cell {\n    border-right-color: var(--txbk-cell-edit-border-color);\n}\n\n/* Multiple Selection */\n.command_mode div.cell.jupyter-soft-selected {\n    border: 2px dashed var(--texbook-azure);\n    background: var(--txbk-multiselect-bgcolor);\n    margin-top: 10px;\n}\n\n/*\nOverlay with Shadow for Code Cell Selected !\n*/\ndiv.code_cell.selected,\n.command_mode div.code_cell.jupyter-soft-selected {\n    box-shadow: 0 6px 18px #aaa;\n    z-index: 10;\n    top: -10px;\n}\n\ndiv.code_cell.selected {\n    border: none;\n    background: transparent;\n}\n\ndiv.prompt {\n    font-family: var(--txbk-code-font-family) !important;\n    font-style: normal;\n    font-size: 1rem;\n    text-align: right;\n    line-height: 1rem;\n    min-width: 9ex;\n}\n\ndiv.cell.selected:before,\ndiv.cell.jupyter-soft-selected:before {\n    /* Important Needed to Override */\n    width: 0 !important;\n    background: none !important;\n}\n\ndiv.cell.selected:not(.jupyter-soft-selected) div.input:before {\n    display: inline-block;\n    position: relative;\n    content: \"\\279E\";\n    font-size: 1.8rem;\n    top: 11px;\n    width: 10px;\n    left: 3px;\n    color: var(--txbk-cell-display-border-color);\n    font-weight: bold !important;\n}\n\n.edit_mode div.cell.selected div.input:before,\n.edit_mode div.cell.selected.unrendered div.input:before {\n    color: var(--txbk-cell-edit-border-color);\n}\n\n.code_cell div.input_prompt:after,\n.code_cell div.output_prompt:after {\n    display: inline-block;\n    content: '';\n    font-size:  0.75rem;\n    font-style: normal !important;\n}\n\n.edit_mode div.cell.selected:before{\n    width: 0;\n    background: none;\n}\n\n/* ==========================\n    Cell Input and Rendering\n   ==========================\n*/\n\ndiv.input_area {\n    border-radius: 0;\n    border: none;\n    padding: 2px 5px 0 5px;\n}\n\ndiv.input_prompt {\n    color: #aba9a9;\n    font-style: normal;\n    font-size: 1.4rem;\n    padding-top: 14px;\n}\n\n/* FIX:\n   Fixing Empty cell output in HTML export\n*/\ndiv.output_prompt {\n    color: transparent !important;\n}\n\ndiv.input_prompt bdi,\ndiv.output_prompt bdi {\n    line-height: 0;\n    font-size:0;\n    color: transparent;\n    left: -10000px;\n    content: \"\\21E2\";\n\n}\n\ndiv.output_wrapper {\n    margin-top: 8px;\n}\n\ndiv.output_area div.output_text pre,\ndiv.output_area div.output_markdown p {\n    padding-bottom: 15px;\n    padding-top: 10px;\n}\n\ndiv.output_area div.output_markdown p {\n    font-size: var(--txbk-content-font-size);\n}\n\ndiv.output_area div.output_markdown pre code {\n    font-size: var(--txbk-content-mono-font-size);\n    font-family: var(--txbk-content-mono-font-family);\n    color: var(--txbk-content-mono-color);\n}\n\ndiv.output_area div.output_text pre {\n    --txbk-content-mono-font-family: var(--txbk-code-font-family);\n\n    font-weight: normal;\n    word-break: normal;\n    word-wrap: break-word;\n}\n\n/* Output Standard Error  */\ndiv.output_stderr {\n    background-color: #FFFFFF;\n}\n\ndiv.out_prompt_overlay:hover {\n    box-shadow: none;\n    background: none;\n}\n\n/* Output HTML after cell code - e.g. Pandas DataFrame */\ndiv.output_html {\n    color: var(--code-text-color);\n}\n\ndiv.output_html {\n    font-size: 1.4em;\n    font-weight: normal;\n    font-family: var(--txbk-code-font-family);\n}\n\ndiv.output_html .nomono {\n    font-family: var(--txbk-content-font-family);\n    margin-top: 0;\n    font-size: 1em;\n}\n\ndiv.output_html > iframe, div.output_area {\n    margin-left: 2rem;\n}\n\ndiv.output_subarea {\n    margin-left: 0;\n}\n\ndiv.output_svg div {\n    max-width: 98%;\n    margin-left: 0 !important;\n}\n\n/* ----------------------------\n    Override default CSS rules\n   ---------------------------- */\n.rendered_html code {\n    background-color: transparent !important;\n}\n\n.rendered_html h1:first-child,\n.rendered_html h2:first-child,\n.rendered_html h3:first-child,\n.rendered_html h4:first-child,\n.rendered_html h5:first-child,\n.rendered_html h6:first-child {\n    margin-top: 0.25em;\n}\n\n.rendered_html h1 {\n    margin-top: 0.48em;\n}\n\n.rendered_html h2 {\n    margin-top: 0.57em;\n}\n\n.rendered_html h3 {\n    margin-top: 0.85em;\n}\n\n.rendered_html h4 {\n    margin-top: 1.3em;\n}\n\n.rendered_html h5 {\n    margin-top: 1.2em;\n}\n\n.rendered_html h6 {\n    margin-top: 1.1em;\n}\n\n/* ===============\n    CELLS Render\n   =============== */\n\n/*  -------------------------\n    (1) CODE CELLS\n    Display + Edit modes\n    -------------------------\n*/\ndiv.code_cell pre, div.CodeMirror, div.CodeMirror-linenumber {\n    font-family: var(--txbk-code-font-family);\n    font-size: var(--txbk-code-font-size);\n    line-height: var(--txbk-code-line-height);\n}\n\ndiv.CodeMirror-linenumber {\n    --txbk-ui-mono-font-size: 12px !important;\n}\n\n/* -- MARKDOWN CELLS (Edit) -- */\n\n/* md cell */\ndiv.text_cell.unrendered pre {\n    /* general font rule */\n    font-family: var(--txbk-md-font-family);\n    font-size: var(--txbk-md-font-size);\n    line-height: var(--txbk-code-line-height);\n}\n\n/* md cell headers (edit) */\n.cm-header-1, .cm-header-2, .cm-header-3,\n.cm-header-4, .cm-header-5, .cm-header-6 {\n    /* general font rule */\n    font-family: var(--txbk-md-font-family);\n}\n\n/* ------------------------------------------------------------------\n    (2) MARKDOWN CELLS (DISPLAY MODE)\n\n    Notes: Font-families to use here:\n    computer-modern --> general text (Computer Modern Typeface, CMU)\n    md-display-monospace --> Monospace output (CMU Typewriter)\n   ------------------------------------------------------------------\n */\n\ndiv.text_cell_render {\n    font-family: var(--txbk-content-font-family);\n    font-size: var(--txbk-content-font-size);\n    color: var(--txbk-content-color);\n    font-kerning: auto;\n    text-align: justify;\n    display: block;\n    word-break: normal;\n    word-wrap: break-word;\n}\n\ndiv.text_cell_render a {\n    color: var(--link-color);\n}\n\ndiv.text_cell_render h1, div.text_cell_render h2,\ndiv.text_cell_render h3, div.text_cell_render h4,\ndiv.text_cell_render h5, div.text_cell_render h6 {\n    font-family:  var(--txbk-content-font-family);\n    font-style: normal;\n}\n\n/* Font-sizes for headers */\ndiv.text_cell_render h1 {\n    font-size: 2.2em;\n    text-align: center;\n    padding-top:  3rem;\n    padding-bottom: 3rem;\n}\n\ndiv.text_cell_render h2 {\n    font-size: 1.9em;\n}\n\ndiv.text_cell_render h3 {\n    font-size: 1.7em;\n}\n\ndiv.text_cell_render h4 {\n    font-size: 1.5em;\n}\n\ndiv.text_cell_render h5 {\n    font-size: 1.3em;\n    border-bottom: 1px solid rgb(204, 204, 204);\n}\n\ndiv.text_cell_render h6 {\n    font-size: 1.1em;\n}\n\ndiv.text_cell_render p,\ndiv.text_cell_render pre,\ndiv.text_cell_render code {\n    font-size: 1em !important;\n}\n\ndiv.text_cell_render pre,\ndiv.text_cell_render code {\n    color: var(--txbk-content-mono-color);\n}\n\n/* Monospace Code - no code syntax highlight*/\ndiv.text_cell_render pre {\n    /* hack: using code background colour here to allow for compatibility */\n    background-color: var(--code-background-color);\n    font-family: var(--txbk-content-mono-font-family);\n}\n\ndiv.text_cell_render p {\n    line-height: var(--txbk-content-line-height);\n    text-align: justify !important;\n}\n\ndiv.text_cell_render code {\n    font-family: var(--txbk-content-mono-font-family);\n}\n\n/* Monospace inline rendered markdown */\ndiv.text_cell_render p code {\n    /*Re-defining variables for Mono using Code Editor's settings*/\n    /*--txbk-content-mono-font-family: var(--txbk-code-font-family);*/\n    /*--txbk-content-mono-font-size: var(--txbk-code-font-size);*/\n    font-size: var(--txbk-content-mono-font-size) !important;\n    color: var(--txbk-content-mono-color);\n    font-family: var(--txbk-content-mono-font-family);\n}\n\ndiv.text_cell_render p strong code {\n    font-weight: bold !important;\n    color: var(--txbk-content-mono-color);\n}\n\ndiv.text_cell_render p em code {\n    font-style: italic !important;\n    color: var(--txbk-content-mono-color);\n}\n\ndiv.text_cell_render pre code {\n    padding: 1rem 1.5rem;\n    display: block !important;\n    color: var(--txbk-content-mono-color);\n    background-color: var(--txbk-content-mono-bgcolor) !important;\n    font-family: var(--txbk-content-mono-font-family);\n    font-size: var(--txbk-content-mono-font-size) !important;\n    word-wrap: break-word;\n    word-break: normal;\n}\n\ndiv.text_cell_render blockquote {\n    --txbk-ui-color: #6f6f6f;\n    margin: .2rem .2rem;\n    padding: .3rem .5rem;\n    border-left: .3rem solid #a7a7a7;\n    background-color: var(--txbk-content-mono-bgcolor);\n}\n\ndiv.text_cell_render blockquote:not(:first-child) {\n    margin: 2rem .2rem;\n}\n\ndiv.text_cell_render blockquote p {\n    padding: .2rem 1.5rem;\n}\n\ndiv.text_cell_render table {\n    font-size: var(--txbk-content-font-size) !important;\n    border-collapse: collapse;\n    border-spacing: 0;\n    overflow: auto;\n    break-inside: auto;\n    margin-top: 25px;\n    margin-bottom: 15px;\n}\n\ndiv.text_cell_render table thead {\n    display: table-header-group;\n    vertical-align: middle;\n    border-bottom: none;\n}\n\ndiv.text_cell_render table thead tr,\ndiv.text_cell_render table thead tr th,\ndiv.text_cell_render table thead tr td,\ndiv.text_cell_render table tbody tr,\ndiv.text_cell_render table tbody tr th,\ndiv.text_cell_render table tbody tr td {\n    break-inside: avoid;\n    break-after: auto;\n    vertical-align: middle;\n    padding: 5px 5px;\n}\n\ndiv.text_cell_render table tr th {\n    border-bottom-width: 0;\n}\n\ndiv.text_cell_render ul, div.text_cell_render ol {\n    position: relative;\n    display: block;\n    margin-bottom: 0 !important;\n    line-height: var(--txbk-content-line-height);\n}\n\ndiv.text_cell_render ul {\n    list-style-type: disc;\n}\n\ndiv.text_cell_render ul li, div.text_cell_render ol li {\n    /*white-space: pre-wrap;*/\n    padding: .6rem !important;\n}\n\ndiv.text_cell_render ul ul {\n    list-style-type: circle !important;\n}\n\ndiv.text_cell_render ul ul,\ndiv.text_cell_render ul ol,\ndiv.text_cell_render ol ul,\ndiv.text_cell_render ol ol {\n    padding-top: .3rem !important;\n}\n\ndiv.text_cell_render ul li > ul li,\ndiv.text_cell_render ul li > ol li,\ndiv.text_cell_render ol li > ul li,\ndiv.text_cell_render ol li > ol li {\n    padding: .3rem !important;\n}\n\ndiv.text_cell_render ul li > ul li a code,\ndiv.text_cell_render ul li > ol li a code,\ndiv.text_cell_render ol li > ul li a code,\ndiv.text_cell_render ol li > ol li a code {\n    color: var(--link-color);\n}\n\ndiv.text_cell_render ul ul ul {\n    list-style-type: square !important;\n}\n\ndiv.text_cell_render p > img:only-child {\n    display: block;\n    margin: auto;\n    max-width: 70% !important;\n}\n\ndiv.text_cell_render img {\n    max-width: 70%;\n}\n\n/*\n    ===================================\n    New CSS Classes and Styles\n    ===================================\n\n    --------------\n    1. Footnotes\n    --------------\n*/\n[id^='fn'], [class^='fn'] {\n    font-size: small !important;\n    font-weight: normal !important;\n    font-style: normal !important;\n    border-top: 1px solid var(--txbk-ui-mono-color);\n    padding-top: .8rem;\n    display: block;\n}\n\np > [id^='fn']:not(:first-child),\np > [class^='fn']:not(:first-child) {\n    border-top: 0 !important;\n}\n\n[id^='fn'] i, [class^='fn'] i,\n[id^='fn'] b, [class^='fn'] b,\n[id^='fn'] strong, [class^='fn'] strong,\np > strong > strong {\n    background-color: var(--txbk-content-mono-bgcolor);\n    font-style: normal !important;\n    font-weight: bold !important;\n}\n\n/* FIX Forcing monospace code to adhere with footnotes rules!*/\ndiv.text_cell_render p [id^='fn'] > code,\ndiv.text_cell_render p [class^='fn'] > code {\n    font-size: 1em !important;\n}\n\n/* CSS Anchors link as superscript (like footnotes) */\na[target=\"_self\"][href^=\"#fn\"], a[target=\"_self\"][href*=\"fn\"] {\n    font-size: 60%;\n    vertical-align: top;\n}\n/* Surround Footnotes by Square brackets */\na[target=\"_self\"][href^=\"#fn\"]:before, a[target=\"_self\"][href*=\"fn\"]:before {\n    content: \"[\";\n}\n\na[target=\"_self\"][href^=\"#fn\"]:after, a[target=\"_self\"][href*=\"fn\"]:after {\n    content: \"]\";\n}\n\n/* --------------\n    2. Drop cap\n   --------------\n*/\n.drop {\n    color: var(--drop-cap-color);\n    font-size: 75px;\n    line-height: 60px;\n    padding-top: 4px;\n    margin-top: 0.2rem;\n}\n\n/* -----------------------------\n    3. noTeXbook Text colours\n   -----------------------------\n*/\n.texbook-red {\n    color: var(--texbook-red);\n}\n\n.texbook-pink {\n    color: var(--texbook-pink);\n}\n\n.texbook-turquoise {\n    color: var(--texbook-turquoise);\n}\n\n.texbook-azure {\n    color: var(--texbook-azure);\n}\n\n.texbook-blue {\n    color: var(--texbook-blue);\n}\n\n.texbook-light-grey {\n    color: var(--texbook-light-grey);\n}\n\n.texbook-dark-grey {\n    color: var(--texbook-dark-grey);\n}\n\n.texbook-orange {\n    color: var(--texbook-orange);\n}\n\n.texbook-yellow {\n    color: var(--texbook-yellow);\n}\n\n/* ---------------------------------------------------------\n    4. IMG MaxWidthXX\n\n    CSS classes to control the max-width property of images\n    when the default 70% is not enough.\n    This is when images need to be enlarged or shrunk.\n   ---------------------------------------------------------\n*/\n\ndiv.text_cell_render img.maxw10,\ndiv.text_cell_render p > img.maxw10 {\n    max-width: 10% !important;\n}\n\ndiv.text_cell_render img.maxw15,\ndiv.text_cell_render p > img.maxw15 {\n    max-width: 15% !important;\n}\n\ndiv.text_cell_render img.maxw20,\ndiv.text_cell_render p > img.maxw20 {\n    max-width: 20% !important;\n}\n\ndiv.text_cell_render img.maxw25,\ndiv.text_cell_render p > img.maxw25 {\n    max-width: 25% !important;\n}\n\ndiv.text_cell_render img.maxw30,\ndiv.text_cell_render p > img.maxw30 {\n    max-width: 30% !important;\n}\n\ndiv.text_cell_render img.maxw35,\ndiv.text_cell_render p > img.maxw35 {\n    max-width: 35% !important;\n}\n\ndiv.text_cell_render img.maxw40,\ndiv.text_cell_render p > img.maxw40 {\n    max-width: 40% !important;\n}\n\ndiv.text_cell_render img.maxw45,\ndiv.text_cell_render p > img.maxw45 {\n    max-width: 45% !important;\n}\n\ndiv.text_cell_render img.maxw50,\ndiv.text_cell_render p > img.maxw50 {\n    max-width: 50% !important;\n}\n\ndiv.text_cell_render img.maxw55,\ndiv.text_cell_render p > img.maxw55 {\n    max-width: 55% !important;\n}\n\ndiv.text_cell_render img.maxw60,\ndiv.text_cell_render p > img.maxw60 {\n    max-width: 60% !important;\n}\n\ndiv.text_cell_render img.maxw65,\ndiv.text_cell_render p > img.maxw65 {\n    max-width: 65% !important;\n}\n\ndiv.text_cell_render img.maxw70,\ndiv.text_cell_render p > img.maxw70 {\n    max-width: 70% !important;\n}\n\ndiv.text_cell_render img.maxw75,\ndiv.text_cell_render p > img.maxw75 {\n    max-width: 75% !important;\n}\n\ndiv.text_cell_render img.maxw80,\ndiv.text_cell_render p > img.maxw80 {\n    max-width: 80% !important;\n}\n\ndiv.text_cell_render img.maxw85,\ndiv.text_cell_render p > img.maxw85 {\n    max-width: 85% !important;\n}\n\ndiv.text_cell_render img.maxw90,\ndiv.text_cell_render p > img.maxw90 {\n    max-width: 90% !important;\n}\n\ndiv.text_cell_render img.maxw95,\ndiv.text_cell_render p > img.maxw95 {\n    max-width: 95% !important;\n}\n\ndiv.text_cell_render img.maxw100,\ndiv.text_cell_render p > img.maxw100 {\n    max-width: 100% !important;\n}\n\n/*  ------------\n     4. Badges\n    ------------\n*/\n.badges img, .badges p img {\n    margin: 0 !important;  /* Override margins */\n    display: inline !important;\n    padding-right: 7px;\n}\n\n.badges p {\n    display: inline !important;\n}\n\n.badges {\n    display: block;\n    text-align: center;\n}\n\n/*  ----------------\n     5. Inline Math\n    ----------------\n*/\n.inline-math {\n    display: inline-block;\n}\n\n/*  --------------------\n     6. Inline Mono Font\n    --------------------\n*/\n.codemono code, .codemono pre, .codemono pre code {\n    font-family: var(--txbk-code-font-family) !important;\n}\n\n.mdmono code, .mdmono pre, .mdmono pre code {\n    font-family: var(--txbk-md-font-family) !important;\n}\n</style>\n\n\n\n<div class=\"nomono\">\n   The notebook is using\n    <a href=\"https://github.com/leriomaggio/notexbook-jupyter-theme\" title=\"noTeXbook Theme\">\n        <b>no$\\TeX$book</b></a> Jupyter Theme (release <code>2.0.0</code>).\n\n</div>\n\n\n\n# Automatic Differentiation\n\n---\n\n### Perceptron and MLP short recap\n\n\n\n<span id=\"fn1\"> source: [3]</span>\n\n__**source:**_This example has been extracted from Reference [3](#ref3)___\n\n\n\nPerceptron (Adaline algorithm) - **ADAptive LInear Neuron** main features:\n\n- Unit Step function\n- Binary Classification \n- Linear Model\n- Weight Update rule with `learning rate` and Gradient Descent Optimisation\n\n$\n    {\\bf w} = {\\bf w} + \\Delta {\\bf w} \\text{, where } \\Delta {\\bf w} = -\\eta \\nabla J({\\bf w}) \n$ [2](#fn2)\n\n<span id=\"fn2\">2: ${\\bf w}$ (in bold) refers to the **weights vector**. </span>\n\nIn other words, we computed the gradient based on the whole training dataset and updated the weights of the model by taking a step into the opposite direction of the gradient $\\nabla J(w)$. \n\nIn order to find the optimal weights of the model, we optimized an objective function \nthat we defined as the **sum of squared errors** (SSE) cost function $J(w)$. \n\nFurthermore, we multiplied the gradient by a factor, the learning rate $\\eta$, which we had to choose carefully to balance the speed of learning against the risk of overshooting the global minimum of the cost function.\n\n##### Choosing $\\eta$ at a glance\n\n\n\nIn  descent optimization, we updated all weights simultaneously after each epoch, and we defined the partial derivative for each weight $w_j$ in the weight vector ${\\bf w}$ as follows:\n\n$$\n\\begin{equation}\n    \\frac{\\partial}{\\partial w_j} J({\\bf w}) = - \\sum_{i} (y^{(i)} - a^{(i)})x_j^{(i)}\n\\end{equation}\n$$\n\nHere $x_j^{(i)}$ represents the feature $j$ of the $i-th$ sample, whereas $y^{(i)}$ and $a^{(i)}$ are the corresponding target and prediction (i.e. *activation of the neuron*), respectively.\n\nIn the special case of Adaline, we simply defined:\n\n$$\na = \\phi(z) = z = \\displaystyle{\\sum_{j} w_jx_j}\n$$\n\n##### As good as a **Linear Classifier**\n\n\n\n---\n\n\n\n\n\n\n\n\n<span id=\"fn3\"> source: [3] </span>\n\n\n###### Calculating Gradients?\n\n**This is more or less where we left**.\n\nNow the question is: How do we *really* calculate those gradients ?\n\nIn addition, two very compulsory requirements about this calculation: \n- **computationally exact**;  \n- **computationally efficient**.\n\n\n## Introducing Automatic Differentiation\n\n> Methods for the computation of derivatives in computer programs can be classified into four categories: \n>\n> (1) **manually** working out derivatives and coding them; \n>\n> (2) **numerical** differentiation using finite difference approximations; \n>\n> (3) **symbolic** differentiation using expression manipulation in computer algebra > systems; \n>\n> (4) **automatic** differentiation, also called *algorithmic differentiation*\n\n\n\n<span id=\"fn0\">Source: [4]</span>\n\n<ins>**Automatic Differentiation** is the subject matter of this notebook (and section!)</ins>\n\n### Automatic Differentiation in a Nutshell\n\n**TL; DR**: Automatic Differentiation lets you compute **exact** derivatives in **constant time**\n\n_Teaser_\n\nAutomatic Differentiation is the secret ingredient that powers most of the existing Deep Learning frameworks (e.g. Pytorch or TensorFlow). \n\nIn a nutshell, Deep learnin frameworks provide the (technical) infrastructure in which computing the derivative of a function takes as much time as evaluating the function. In particular, the design idea is: \"you define a network with a loss function, and you get a gradient *for free*\".\n\n\n**Differentiation** in general is becoming a **first class citizen** in programming languages with early work started by Chris Lattner of LLVM famework \u2014 see the [Differentiable Programming Manifesto](https://github.com/apple/swift/blob/master/docs/DifferentiableProgramming.md) for more detail.\n\nHowever, if you're still wondering whether any of this is just boring math and how this relates to computer programming, I definitely suggest to have a look at **this** vide0 on YouTube:\n\n[GOTO 2018 - Machine Learning: Alchemy for the Modern Computer Scientist by Erik Meijer](https://www.youtube.com/watch?v=Rs0uRQJdIcg)\n\n### Automatic Differentiation is NOT $\\ldots$\n\nIn the above list, we included automatic differentiation as the fourth item [3](#fn3 \"Manual really?\"), so separated from other differentiation methods such as **symbolic** or **numerical** methods.\n\n<span id=\"fn3\">3: The first was indeed manual, hard coded implementation - not really meant though!</span>\n\n#### Automatic Differentiation $\\neq$ Symbolic Differentiation\n\nThis is the **most** obvious, I presume. \n\nSymbolic differentiation works by breaking apart a complex expression into a bunch of simpler expressions by using various rules \u2014 very similar to a compiler.\n\n(Mathematically and) Technically speaking this is all possible thanks to the [**compositionality**](https://en.wikipedia.org/wiki/Principle_of_compositionality) of derivatives calculation. \n\nExamples of some rules:\n\n**Sum rule**:\n\n$$\n\\begin{equation}\n\\frac{d}{dx} (f(x) + g(x)) = \\frac{d}{dx} f(x) + \\frac{d}{dx} g(x)\n\\end{equation}\n$$\n\n**Derivatives of powers rule**:\n\n$$\n\\begin{equation}\n\\frac{d}{dx} x^r = rx^{r-1}\n\\end{equation}\n$$\n\n\n**Multiplication rule**:\n\n$$\n\\begin{equation}\n\\frac{d(fg)}{dx} = \\frac{df}{dx} g + f\\frac{dg}{dx}\n\\end{equation}\n$$\n\n**Chain rule (!!)**:\n\n$$\n\\begin{equation}\n\\frac{d}{dx}[f(g(x))] = \\frac{df}{dg} \\cdot \\frac{dg}{dx}\n\\end{equation}\n$$\n\n\n**Issue**:\n\n- For complicated functions, the resultant expression can be exponentially large - $O(2^n)$;\n- Could be wasteful to keep around intermediate symbolic expressions if we only need a **numeric value** of the gradient in the end;\n\n**Real world examples**: `theano` (see [doc](http://deeplearning.net/software/theano/tutorial/gradients.html))\n\n\n#### Automatic Differentiation $\\neq$ Numerical Differentiation\n\nNumerical Differentiation is far more intuitive and effectively the (most) natural way to compute derivatives, building on the very definition of derivatives as the **limit of the different quotient**:\n\n$$\n\\begin{equation}\nf'(x) = \\lim_{\\epsilon \\leftarrow 0} \\frac{f(x + \\epsilon) - f(x)}{\\epsilon}\n\\end{equation}\n$$\n\nRecap on (other) notations of derivatives:\n\n- f'(x): **Lagrange's Notation**\n- $\\frac{df}{dx}$: **Leibniz's Notation**\n\nFor **multivariate** functions $f: \\mathbb{R} \\mapsto \\mathbb{R}^n $, we can approximate the gradient \n$\\nabla f = ( \\frac{\\partial f}{\\partial x_1}, \\ldots, \\frac{\\partial f}{\\partial x_n} )$ using:\n\n$$\n\\frac{\\partial f({\\bf x})}{\\partial x_i} \\approx \\frac{f({\\bf x} + h{\\bf e_i}) - f({\\bf x})}{h}\n$$\n\nwhere $\\bf{e_i}$ is the $i-th$ unit vector and $ h > 0$ is a small step size.\n\nThis has the **advantage** of being uncomplicated to implement, but the **disadvantages** of performin $O(n)$\nevaluations of $f$ for a gradient in $n$ dimensions, and requiring **careful considerations** in selecting the step size $h$.\n\nIndeed, Numerical approximations of derivatives are inherently ill-conditioned and unstable[4](#fn4).\n\n\n<span id=\"fn4\">**[4]**: Using the limit definition of the derivative for finite difference approximation commits both cardinal sins of numerical analysis: **\u201cthou shalt not add small numbers to big numbers\u201d, and \u201cthou shalt not subtract numbers which are approximately equal\u201d**.</span>\n\n### Automatic Differentiation $=$ Automatic Differentiation\n\n1. Automatic Differentiation (`AD`) gives exact answers in constant time.\n\n2. AD can be thought of as performing a non-standard interpretation of a computer program where this interpretation involves **augmenting** the standard computation with the calculation of various derivatives. \n\n3. All numerical computations are ultimately compositions of a finite set of elementary operations for which derivatives are known, and combining the derivatives of the constituent operations through the **chain rule** gives the derivative of the overall composition.\n\nThe chain rule above told us what we **wanted**. What it does not say is **how** to compute it efficiently. \n\nAD is **a way** to get these gradients efficiently without having to do anything but write the objective function in <ins>computer code</ins>. \n\nAD is a very broadly applicable technique and it has been studied for decades. Curiously however, it has traditionally only been used in a limited way in machine learning despite the ubiquity of gradient-based optimization problems in ML. \n\nIt has only been recently that serious automatic differentiation (versus na\u00efve hand-coded backprop rules) have started to make their way into mainstream deep learning toolchains. \n\n**TensorFlow**, for example, has the ability to compute gradients of the computational graphs it supports with its limited domain-specific language, but it is not close to a full AD system. \n\nAutomatic differentiation can be implemented in a variety of ways, via **run-time abstractions** and also via **source code transformation**.\n\n##### Example\n\nRather than talking about large neural networks, we will seek to understand automatic differentiation via a small problem borrowed from the book of *Griewank and Walther (2008)*.\n\nIn the following we will adopt their very same **three-part** notation (also used in [4]).\n\nA function $f: \\mathbb{R^n} \\mapsto \\mathbb{R^m}$ is constructed using intermediate variables $v_i$ such that:\n\n- variables $v_{i-n} = x_i$, $i = 1,\\ldots,n$ are the input variables;\n- variables $v_i$, $i = 1,\\ldots,l$ are the working **intermediate** variables;\n- variables $y_{m-i} = v_{l-i}$, $i = m-1,\\ldots,0$ are the output variables.\n\n\n\nThe **traversal** of the graph and the **direction** in which gradients are actually computed defines the two modalities of AD:\n\n* **forward mode** AD;\n* **backward mode** AD.\n\n##### Forward (Tangent) Mode\n\nThe idea of forward mode automatic differentiation is that we can compute derivatives as we go and\nthat the chain rule says the overall derivative that we want is a composition of these incremental\ncomputations.\n\nLet\u2019s imagine that our overall goal is to compute $\\frac{\\partial y}{\\partial x_1}$ for the example above.\n\nWe denote all the intermediate *partial derivatives* (**with respect to $x_1$**) as:\n$$\n\\dot{v}_{i} = \\frac{\\partial v_i}{\\partial x_1}\n$$\n\nThe **very same** applies when we want to compute $\\frac{\\partial y}{\\partial x_2}$\n\n\n\n**Dual Numbers**\n\n\n\nMathematically, **forward mode AD** can be viewed as evaluating a function using **dual numbers** which can be defined as truncated Taylor series of the form:\n$$\nv + \\dot{v}\\epsilon\n$$\n\nwhere $v$ and $\\dot{v} \\in \\mathbb{R}$, and $\\epsilon$ is a *nilpotent* number such as $\\epsilon^2 = 0$, and\n$\\epsilon \\neq 0$.\n\nTherefore:\n$$\nf(v + \\dot{v}\\epsilon) = f(v) + f'(v)\\dot{v}\\epsilon\n$$\n\nand using dual numbers as data structures for carrying the **tangent** value together with the primal.\nIn fact, **forward mode AD** is also known as **tangent mode**.\n\nThe interesting bit is that we can implement this bookkeeping during the *execution trace* just via abstraction.\n\nWe can replace our floating point numbers with `tuples`, and replace primitive functions with the following Python implementation (just using `numpy`)\n\n\n```python\nimport numpy as np\n\ndef add(atuple, btuple):\n    (a, adot) = atuple\n    (b, bdot) = btuple\n    return ( a + b, adot + bdot)\n\ndef subtract(atuple, btuple): \n    (a, adot) = atuple\n    (b, bdot) = btuple\n    return (a - b, adot - bdot)\n\ndef multiply(atuple, btuple):\n    (a, adot) = atuple\n    (b, bdot) = btuple\n    return (a * b, adot * b + bdot * a)\n\ndef divide(atuple, btuple):\n    (a, adot) = atuple\n    (b, bdot) = btuple\n    return (a / b, (adot * b - bdot * a) / (b*b))\n\ndef ln(atuple):\n    (a, adot) = atuple\n    return (np.log(a), (1/a)*adot)\n\ndef sin(atuple):\n    (a, adot) = atuple\n    return (np.sin(a), np.cos(a)*adot)\n```\n\n\n```python\ndef f(x1: tuple, x2: tuple):\n    # ln(x1) + x1x2 - sin(x2)\n    v1 = ln(x1)\n    v2 = multiply(x1, x2)\n    v3 = add(v1, v2)\n    v4 = sin(x2)\n    v5 = subtract(v3, v4)\n    return v5\n```\n\n\n```python\nf(x1=(2, 1), x2=(5, 0))\n```\n\n\n\n\n    (11.652071455223084, 5.5)\n\n\n\n\n```python\nf(x1=(2, 0), x2=(5, 1))\n```\n\n\n\n\n    (11.652071455223084, 1.7163378145367738)\n\n\n\n##### Reverse (Co-Tangent) Mode\n\nAD in the reverse accumulation mode corresponds to a generalized backpropagation algorithm, in that it propagates derivatives backward from a given output. This is done by complementing each intermediate variable $v_i$ with an **adjoint**:\n$$\n\\bar{v}_{i} = \\frac{\\partial y_i}{\\partial v_i} = \\displaystyle{\\sum_{j:\\text{child of i}} \\bar{vj} \\frac{\\partial v_j}{\\partial v_i}}\n$$\n\n\n\nThere are various ways to implement this abstraction in its full generality, but an implementation requires more code than can easily appear here. The three major approaches are:\n\n**source code transformation**: The adjoint backward pass code is generated a priori from the forward computation. A clean Python example of such a system is [**Tangent**](https://colab.research.google.com/drive/1cjoX9GteBymbnqcikNMZP1uenMcwAGDe).\n\n**graph-based**: This approach uses an embedded mini-language to specify a graph of computations that can then be manipulated for function evaluations and gradients. \n\n$\\rightarrow$ The advantage of this approach is that it is amenable to intelligent graph optimizations and use of compilers. The embedded mini-language also makes it possible to build specialized hardware that targets the differentiable primitives. \n\n$\\rightarrow$ The downside of this approach is that you are not coding in the host language (e.g., Python) and so you can\u2019t take advantage of its imperative design and control flow. Generally the mini-language is less expressive than the host language. Also, the lazy execution of the function represented by the graph can make it difficult to debug. TensorFlow 1.x is an example of this kind of automatic differentiation.\n\n**tape-based**: This approach tracks the actual composed functions as they are called during execution of the forward pass. One name for this data structure is the *Wengert list*. \n\n$\\rightarrow$ With the ordered sequence of computations in hand, it is then possible to walk backward through the list to compute the gradient. \n\n$\\rightarrow$ The advantage of this is that it can more easily use all the features of the host language and the imperative execution is easier to understand. \n\n$\\rightarrow$ The downside is that it can be more difficult to optimize the code and reuse computations across executions. \n\n[Autograd](https://github.com/HIPS/autograd) is an example of this. \nThe automatic differentiation in [PyTorch](https://pytorch.org/) also roughly follows this model.\n\n\n\n### Re-inventing the Wheel: Introducing `micrograd`\n\n[`micrograd`](https://github.com/karpathy/micrograd) is:\n\n> a tiny Autograd engine (with a bite! :)). \n> Implements backpropagation (reverse-mode autodiff) over a dynamically built DAG and a small neural networks library on top of it with a PyTorch-like API. \n>\n> Both are tiny, with about 100 and 50 lines of code respectively. \n>\n> The DAG only operates over scalar values, so e.g. we chop up each neuron into all of its individual tiny adds and multiplies. However, this is enough to build up entire deep neural nets doing binary classification. Potentially useful for educational purposes.\n\n\n```python\ndef example(this):\n    for i in range(190):\n        print(map(lambda x: x+2, \n                 iter(range(32))))\n```\n\n(*from the doc*)\n\n```python\nfrom micrograd.engine import Value\n\na = Value(-4.0)\nb = Value(2.0)\nc = a + b\nd = a * b + b**3\nc += c + 1\nc += 1 + c + (-a)\nd += d * 2 + (b + a).relu()\nd += 3 * d + (b - a).relu()\ne = c - d\nf = e**2\ng = f / 2.0\ng += 10.0 / f\nprint(f'{g.data:.4f}') # prints 24.7041, the outcome of this forward pass\ng.backward()\nprint(f'{a.grad:.4f}') # prints 138.8338, i.e. the numerical value of dg/da\nprint(f'{b.grad:.4f}') # prints 645.5773, i.e. the numerical value of dg/db\n```\n\n```python\nfrom micrograd import nn\nn = nn.Neuron(2)\nx = [Value(1.0), Value(-2.0)]\ny = n(x)\ndot = draw_dot(y)\n```\n\n\n\n### References and Futher Reading:\n\n1. [Automatic Differentiation Step by Step](https://medium.com/@marksaroufim/automatic-differentiation-step-by-step-24240f97a6e6)\n\n2. [Deep Learning with PyTorch (**free sample**) - Luca Antiga et. al.](https://pytorch.org/deep-learning-with-pytorch)\n\n3. [Python Machine Learning, 3rd ed. - Sebastian Raschka](https://sebastianraschka.com/books.html)\n\n4. [(*Paper*) Automatic Differentiation in Machine Learning: a Survey](https://arxiv.org/abs/1502.05767)\n\n\n```python\n\n```\n", "meta": {"hexsha": "d141fb1989215184efcdc1cbab037e69eae72d91", "size": 146667, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "1_ANN/extra_autograd.ipynb", "max_stars_repo_name": "leriomaggio/deep-learning-for-data-science", "max_stars_repo_head_hexsha": "1dff9a8a8d09c56f0f1785ed38368c5ea412041c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-02T08:23:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-02T10:51:36.000Z", "max_issues_repo_path": "1_ANN/extra_autograd.ipynb", "max_issues_repo_name": "leriomaggio/deep-learning-for-data-science", "max_issues_repo_head_hexsha": "1dff9a8a8d09c56f0f1785ed38368c5ea412041c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1_ANN/extra_autograd.ipynb", "max_forks_repo_name": "leriomaggio/deep-learning-for-data-science", "max_forks_repo_head_hexsha": "1dff9a8a8d09c56f0f1785ed38368c5ea412041c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-09T18:39:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-09T18:39:03.000Z", "avg_line_length": 38.4851744949, "max_line_length": 432, "alphanum_fraction": 0.5004056809, "converted": true, "num_tokens": 26591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12592277467581975, "lm_q2_score": 0.06465349151015834, "lm_q1q2_score": 0.008141347043438694}}
{"text": "```python\nimport theme\ntheme.load_style()\n```\n\n\n\n\n<style>\n@import url('http://fonts.googleapis.com/css?family=Source+Code+Pro');\n@import url('http://fonts.googleapis.com/css?family=Vollkorn');\n@import url('http://fonts.googleapis.com/css?family=Arimo');\n@import url('http://fonts.googleapis.com/css?family=Arvo:400,700,400italic')\n\n#notebook li { /* More space between bullet points */\n    margin-top:0.8em;\n}\n\n/* draw border around running cells */\ndiv.cell.border-box-sizing.code_cell.running {\n    border: 3px solid #111;\n}\n\ndiv.cell.code_cell {\n    margin-top: 1em;\n    margin-left: auto;\n    margin-right: auto;\n    width: 800px;\n    border: 1px solid rgba(200, 200, 200, 0.8);\n    border-radius: 8px; /* rounded borders */\n}\n\ndiv.text_cell_render{\n    font-family: 'Arvo' sans-serif;\n    /* font-family: 'Arimo',verdana,arial,sans-serif; */\n    line-height: 130%;\n    font-size: 115%;\n    margin-left:0%;\n    margin-right:auto;\n}\n\n.text_cell_render h1 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 300;\n    font-style: bold;\n    font-size: 30pt;\n    line-height: 100%;\n    color:#c76c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h2 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 20pt;\n    line-height: 100%;\n    color:#c76c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h3 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 16pt;\n    line-height: 100%;\n    color:#d77c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h4 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 14pt;\n    font-style: italic;\n    line-height: 100%;\n    color:#d77c0c;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n    display: block;\n}\n\n.text_cell_render h5 {\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    font-weight: 200;\n    font-size: 12pt;\n    color: #1d3b84;\n    margin-top: 0.75em;\n    margin-bottom: 0.05em;\n}\n\n.rendered_html code{\n    background-color: transparent;\n}\n\nul{\n    margin: 2em;\n}\n\nul li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.5em;\n}\n\nul li li{\n    padding-left: 0.2em;\n    margin-bottom: 0.2em;\n    margin-top: 0.2em;\n}\n\nol{\n    margin: 2em;\n}\n\nol li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.5em;\n}\n\nul li{\n    padding-left: 0.5em;\n    margin-bottom: 0.5em;\n    margin-top: 0.2em;\n}\n\na:link{\n    font-weight: bold;\n    color:#447adb;\n}\n\na:visited{\n    font-weight: bold;\n    color: #1d3b84;\n}\n\na:hover{\n    font-weight: bold;\n    color: #1d3b84;\n}\n\na:focus{\n    font-weight: bold;\n    color:#447adb;\n}\n\na:active{\n    font-weight: bold;\n    color:#447adb;\n}\n\n.rendered_html :link {\n    text-decoration: underline;\n}\n\n.rendered_html :hover {\n    text-decoration: none;\n}\n\n.rendered_html :visited {\n    text-decoration: none;\n}\n\n.rendered_html :focus {\n    text-decoration: none;\n}\n\n.rendered_html :active {\n    text-decoration: none;\n}\n\n.warning{\n    color: rgb( 240, 20, 20 )\n}\n\nhr {\n    color: #f3f3f3;\n    background-color: #f3f3f3;\n    height: 1px;\n}\n\nblockquote{\n    display:block;\n    background: #fcfcfc;\n    border-left: 5px solid #c76c0c;\n    font-family: 'Open sans',verdana,arial,sans-serif;\n    width:680px;\n    padding: 10px 10px 10px 10px;\n}\n\nblockquote p {\n    margin-bottom: 0;\n    line-height: 125%;\n    font-size: 100%;\n}\n\ntable#mytable,\ntable#mytable td,\ntable#mytable tr\n{\n    border: none !important;\n}\n\ntable#mytable-1,\ntable#mytable-1 td,\ntable#mytable-1 tr\n{\n    border: none !important;\n    align: center;\n    cellspacing: 10;\n}\n\n.msg {\n    width: 90%;\n    margin-left: auto;\n    margin-right: auto;\n    margin-top: 10px;\n    margin-bottom: 10px;\n    padding: 14px 14px 14px 14px;\n    color: #c09853;\n    text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);\n    background-color: #fcf8e3;\n    border: 1px solid #fbeed5;\n    -webkit-border-radius: 4px;\n    -moz-border-radius: 4px;\n    border-radius: 4px;\n}\n\n.msg-heading {\n    color: inherit;\n}\n\n.msg .close {\n    position: relative;\n    top: -2px;\n    right: -21px;\n    line-height: 18px;\n}\n\n.msg-success {\n    color: #468847;\n    background-color: #dff0d8;\n    border-color: #d6e9c6;\n}\n\n.msg-danger,\n.msg-error {\n    color: #b94a48;\n    background-color: #f2dede;\n    border-color: #eed3d7;\n}\n\n.msg-info {\n    color: #3a87ad;\n    background-color: #d9edf7;\n    border-color: #bce8f1;\n}\n\n.boxed {\n    color: #b94a48;\n    background-color: #f2dede;\n    border-color: #eed3d7;\n    margin-left: auto;\n    margin-right: auto;\n    padding: 14px 14px 14px 14px;\n}\n\n.w-300 { width: 300px; }\n.w-400 { width: 400px; }\n.w-500 { width: 500px; }\n\n</style>\n\n\n\n\n# Lesson 3: Direct Methods\n## 1D Spring Elements\n\n\n\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\"></a>\n\nThis lecture by Tim Fuller is licensed under the\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\">Creative Commons Attribution 4.0 International License</a>.  All code examples are also licensed under the [MIT license](http://opensource.org/licenses/MIT).\n\n<a id='top'></a>\n\n# Topics\n\n- [Introduction to FEA](#intro_to_fea)\n- [Direct Stiffness Method](#dir_stiff_methd)\n  - [Example 1: Tapered Bar](#tapered_bar)\n  - [Example 2: Parallel Spring Network](#multi_spring)\n  - [Example 3: Prescribed Displacements](#presc_disp)\n  - [Example 4: Self Weight](#ex_self_weight)\n- [Computational Implementation](#comp_impl)\n  - [Pre Processing](#preproc)\n  - [Solution Phase](#solphase)\n  - [Example Linear Finite Element Code](#one_d_code)\n- [Exercises](#exercises)\n\n<a id=\"intro_to_fea\"></a> \n# Introduction to FEA[](#top)\n\nThe general steps in solving a problem using FEM:\n\n**Preprocessing Phase**\n\n1. Discretize the problem domain and choose element type\n2. Assume solution that approximates the element behavior\n3. Define the Strain/Displacement and Stress/Strain Relationships\n4. Derive the element stiffness matrix and equations\n5. Assemble element equations into global equations\n6. Introduce boundary conditions\n\n**Solution Phase**\n\n1. Solve for the unknown degrees of freedom\n2. Compute reactions\n\n**Postprocessing Phase**\n\n1. Find element strains and stresses and other important information.\n2. Interpret results\n\n# <a id='dir_stiff_methd'></a> The Direct Stiffness Method[](#top)\n\nWe first demonstrate the discretization process and other steps of the FEM through the direct stiffness method. In future lectures we will discuss other discretization methods. We now demonstrate the direct stiffness method through a number of examples familiar to students of mechanical engineering.\n\n## <a id='tapered_bar'></a>  Example 1: Tapered Bar\n\nConsider the problem of finding the displacement $\\delta$ at the free end of the tapered bar, caused by the axial force $F$.\n\n\n\nFor a small taper angle we can obtain a reasonable approximation for the displacement by\n\n\n$$\n   \\delta_{\\scriptscriptstyle\\mathrm{approx}} = \\frac{PL}{A'E}\n$$\n\n\nwhere $A'=A_0/2$.  Suppose that the angle of the taper is not negligible and that $E$ is not constant but varies along the length of the beam. Let's use the finite element method to find the approximate displacement to this more difficult problem. We will follow the general steps of the FEM already outlined.\n\n### Preprocessing Phase\n\n#### Step 1: Discretize and Select Element Type\n\nDiscretization is accomplished by subdividing the problem domain into *finite elements* connected by *nodes*, as shown below.  The original tapered beam is divided into 4 finite elements with 5 nodes. Each element has a length $l$ and uniform cross-sectional area $A$ represented by the average area of the cross sections at the nodes. We choose for our element type a spring.  The spring element is chosen for its simplicity in understanding and implementing. As the semester progresses we will use other more sophisticated elements. However, for now, the spring element is sufficient in helping us understand the general steps of the FEM.\n\n\n\nWe concentrate now on the chosen spring element.  Let us isolate one element from the global $x$ coordinates shown and put it in its own local coordinate system $\\hat{x}$ and study its properties there.\n\n\n\nTake note of the new syntax.  Hatted quantities ($\\hat{f}$, $\\hat{u}$) are reckoned with respect to the local coordinate $x$.  That is, $\\hat{x}_1=0$ and $\\hat{x}_2=L$, where $L$ is the element length.  Another, alternative notation is also shown - that of explicitly labeling the element number as a superscript to the property.\n\n<div class=\"msg\">\n<b> Properties of the Spring Element </b> <br>\n\n<ul>\n<li> Two nodes per element\n<li> One translational degree of freedom at each node, meaning that each node can displace only along the axis of the spring.\n<li> Each spring element has a total of two degrees of freedom.\n</ul>\n</div>\n\n<div class=\"msg msg-info\">\n<b>Remark</b><br>\nWe distinguish between degrees of the system, degrees of freedom of the element, and degrees of freedom of the node.  In general, a node has $n_{\\text{dof}}^{\\text{n}}$ degrees of freedom; an element has $n_{\\text{dof}}^{\\text{e}} = n \\times n_{\\text{dof}}^{\\text{n}}$ degrees of freedom, where $n$ is the number of nodes defining the element element; and the system has $n_{\\text{dof}}^{\\text{sys}} = N \\times n_{\\text{dof}}^{\\text{n}}$ degrees of freedom, where $N$ is the total number of nodes.  We'll come back to the significance of these statements when discussing computational implementation.\n</div>\n\nFor the following steps we will consider only one of the four elements in our discretized problem domain. Later we will take into account the other elements. Let's choose element two\n\n\n\n#### Step 2: Select a Displacement Function\n\nIn the direct stiffness method that we cover today the selection of a the displacement function is not necessary. Thus, we will skip this step and save it for a later lecture.\n\n#### Step 3: Define the Strain/Displacement and Stress/Strain Relationship\n\nRecall from elementary physics that the force stretch relationship for an ideal spring, assuming small displacements, is given by $F=k\\delta$\n\nwhere $k$ is the spring constant and $\\delta$ is the displacement.\nObserving the stretched spring, the displacement $\\delta$ is\n\n$$\n\\delta = u_2^{(2)}  - u_1^{(2)}\n$$\n\nand \n\n$$\nf = k_2\\left(u_2^{(2)} - u_1^{(2)}\\right)\n$$\n\nwhere $k_{2}$ is the spring constant for element 2.\n\n<div class=\"msg msg-error\">\n<b> Recall </b> <br>\nThe equivalent spring stiffness of a bar is given by k=AE/L\n</div>\n\n#### Step 4: Derive Element Stiffness Matrix and Equations\n\nWe now derive the stiffness matrix for the spring element. The nodal forces are\n\n$$\nf_1^{(2)} = -k_2\\left(u_2^{(2)} - u_1^{(2)}\\right)\n$$\n\n$$\nf_2^{(2)} = k_2\\left(u_2^{(2)} - u_1^{(2)}\\right)\n$$\n\ncombining and putting in matrix form gives\n\n$$\n  \\begin{Bmatrix} f_1^{(2)} \\\\ f_2^{(2)} \\end{Bmatrix} \n= \\begin{bmatrix} k_2 & -k_2 \\\\ -k_2 & k_2 \\end{bmatrix}\n  \\begin{Bmatrix} u_1^{(2)} \\\\ u_2^{(2)} \\end{Bmatrix}\n$$.\n\n#### Step 5: Assemble Element Equations into Global Equations\n\nThe preceding analysis applied only to element two of our example problem. The exact same analysis can be performed on the remaining elements and the conclusions would be the same, namely, for elements 1, 3, and 4\n\n$$\n  \\begin{Bmatrix} f_1^{(1)} \\\\ f_2^{(1)} \\end{Bmatrix} \n= \\begin{bmatrix} k_1 & -k_1 \\\\ -k_1 & k_1 \\end{bmatrix}\n  \\begin{Bmatrix} u_1^{(1)} \\\\ u_2^{(1)} \\end{Bmatrix}\n$$\n\n$$\n  \\begin{Bmatrix} f_1^{(3)} \\\\ f_2^{(3)} \\end{Bmatrix} \n= \\begin{bmatrix} k_3 & -k_3 \\\\ -k_3 & k_3 \\end{bmatrix}\n  \\begin{Bmatrix} u_1^{(3)} \\\\ u_2^{(3)} \\end{Bmatrix}\n$$\n\n$$\n  \\begin{Bmatrix} f_1^{(4)} \\\\ f_2^{(4)} \\end{Bmatrix} \n= \\begin{bmatrix} k_4 & -k_4 \\\\ -k_4 & k_4 \\end{bmatrix}\n  \\begin{Bmatrix} u_1^{(4)} \\\\ u_2^{(4)} \\end{Bmatrix}\n$$\n\nNow that we have developed stiffnesses for individual elements it is our goal to develop a global stiffness for the structure. Before we look at the global stiffness, however, let's look the nodal displacements. Note that elements 1, 2 3, and 4 must remain connected at common nodes 2, 3, and 4. This is called *continuity* or the *compatibility requirement*. This compatibility yields the following relationships:\n\n$$\n   \\begin{split}\n     u_{2}^{(1)} &= u_{1}^{(2)} = u_{2}\\\\\n     u_{2}^{(2)} &= u_{1}^{(3)} = u_{3}\\\\\n     u_{2}^{(3)} &= u_{1}^{(4)} = u_{4}\\\\\n   \\end{split}\n$$\n\n\nalso, since nodes 1 and 5 are only connected to one element each\n\n\n$$\n   \\begin{split}\n     u_{1}^{(1)} &= u_{1}\\\\\n     u_{2}^{(4)} &= u_{5}\n   \\end{split}\n$$\n\n\nFrom the free-body diagrams of each node and the fact that external forces must equal the internal forces at each node, we can write the nodal equilibrium equations for nodes 1, 2, 3, 4, and 5 as\n\n\n$$\n   \\begin{split}\n     f_{1} = f_{1}^{(1)} &= R \\\\\n     f_{2} = f_{2}^{(1)} + f_{1}^{(2)} &= 0 \\\\\n     f_{3} = f_{2}^{(2)} + f_{1}^{(3)} &= 0 \\\\\n     f_{4} = f_{2}^{(3)} + f_{1}^{(4)} &= 0 \\\\\n     f_{5} = f_{2}^{(4)} &= F \\\\\n   \\end{split}\n$$\n\nMaking substitutions we find\n\n\n$$\n   \\begin{split}\n     R &= k_{1}u_{1} - k_{1}u_{2} \\\\\n     0 &= -k_{1}u_{1} + k_{1}u_{2} + k_{2}u_{2}-k_{2}u_{3} \\\\\n     0 &= -k_{2}u_{2} + k_{2}u_{3} + k_{3}u_{3} - k_{3}u_{4} \\\\\n     0 &= -k_{3}u_{3} + k_{3}u_{4} + k_{4}u_{4} - k_{4}u_{5} \\\\\n     F &= -k_{4}u_{4} + k_{4}u_{5}\\\\\n     \\end{split}\n$$\n\n\nIn matrix form\n\n\n$$\n   \\begin{Bmatrix}\n     R \\\\ 0 \\\\ 0 \\\\ 0 \\\\ F\n   \\end{Bmatrix}\n   =\n   \\begin{bmatrix}\n     k_{1} & -k_{1} & 0 & 0 & 0\\\\\n     -k_{1} & k_{1} + k_{2} & -k_{2} & 0 & 0\\\\\n     0 & -k_{2} & k_{2} + k_{3} & -k_{3} & 0 \\\\\n     0 & 0 & -k_{3} & k_{3} + k_{4} & -k_{4} \\\\\n     0 & 0 & 0 & -k_{4} & k_{4}\n   \\end{bmatrix}\n   \\begin{Bmatrix}\n     u_{1} \\\\ u_{2} \\\\ u_{3} \\\\ u_{4} \\\\ u_{5}\n   \\end{Bmatrix}\n$$.\n\n<div class=\"msg\">\n<b> Note: </b> There is more than one way to assemble the global system of equations.  Another method is using superposition, as shown below\n</div>\n\nThese global equations can also be obtained using the superposition. Let's write the local force/displacement equation for element 1 in the following expanded form\n\n\n$$\n   \\begin{Bmatrix}\n     f_{1} \\\\ f_{2} \\\\ f_{3} \\\\ f_{4} \\\\ f_{5}\n   \\end{Bmatrix}\n   =\n   \\begin{Bmatrix}\n     R \\\\ 0 \\\\ 0 \\\\0 \\\\ 0\n   \\end{Bmatrix}\n   =\n   \\begin{bmatrix}\n     k_{1} & -k_{1} & 0 & 0 & 0 \\\\\n     -k_{1} & k_{1} & 0 & 0 & 0 \\\\\n     0 & 0 & 0 & 0 & 0 \\\\\n     0 & 0 & 0 & 0 & 0 \\\\\n     0 & 0 & 0 & 0 & 0\n   \\end{bmatrix}\n   \\begin{Bmatrix}\n     u_{1} \\\\ u_{2} \\\\ u_{3} \\\\ u_{4} \\\\ u_{5}\n   \\end{Bmatrix}\n$$\n\n\nSimilarly,\n\n\n$$\n   \\begin{Bmatrix}\n     f_{1} \\\\ f_{2} \\\\ f_{3} \\\\ f_{4} \\\\ f_{5}\n   \\end{Bmatrix}\n   =\n   \\begin{Bmatrix}\n     0 \\\\ 0 \\\\ 0 \\\\ 0 \\\\ 0\n   \\end{Bmatrix}\n   =\n   \\begin{bmatrix}\n     0 & 0 & 0 & 0 & 0 \\\\\n     0 & k_{2} & -k_{2} & 0 & 0 \\\\\n     0 & -k_{2} & k_{2} & 0 & 0 \\\\\n     0 & 0 & 0 & 0 & 0 \\\\\n     0 & 0 & 0 & 0 & 0\n   \\end{bmatrix}\n   \\begin{Bmatrix}\n     u_{1} \\\\ u_{2} \\\\ u_{3} \\\\ u_{4} \\\\ u_{5}\n   \\end{Bmatrix}\n$$\n\n$$\n   \\begin{Bmatrix}\n     f_{1} \\\\ f_{2} \\\\ f_{3} \\\\ f_{4} \\\\ f_{5}\n   \\end{Bmatrix}\n   =\n   \\begin{Bmatrix}\n     0 \\\\ 0 \\\\ 0 \\\\ 0 \\\\ 0\n   \\end{Bmatrix}\n   =\n   \\begin{bmatrix}\n     0 & 0 & 0 & 0 & 0 \\\\\n     0 & 0 & 0 & 0 & 0 \\\\\n     0 & 0 & k_{3} & -k_{3} & 0 \\\\\n     0 & 0 & -k_{3} & k_{3} & 0 \\\\\n     0 & 0 & 0 & 0 & 0\n   \\end{bmatrix}\n   \\begin{Bmatrix}\n     u_{1} \\\\ u_{2} \\\\ u_{3} \\\\ u_{4} \\\\ u_{5}\n   \\end{Bmatrix}\n$$\n\nand\n\n$$\n   \\begin{Bmatrix}\n     f_{1} \\\\ f_{2} \\\\ f_{3} \\\\ f_{4} \\\\ f_{5}\n   \\end{Bmatrix}\n   =\n   \\begin{Bmatrix}\n     0 \\\\ 0 \\\\ 0 \\\\ 0 \\\\ F\n   \\end{Bmatrix}\n   =\n   \\begin{bmatrix}\n     0 & 0 & 0 & 0 & 0 \\\\\n     0 & 0 & 0 & 0 & 0 \\\\\n     0 & 0 & 0 & 0 & 0 \\\\\n     0 & 0 & 0 & k_{4} & -k_{4} \\\\\n     0 & 0 & 0 & -k_{4} & k_{4}\n   \\end{bmatrix}\n   \\begin{Bmatrix}\n     u_{1} \\\\ u_{2} \\\\ u_{3} \\\\ u_{4} \\\\ u_{5}\n   \\end{Bmatrix}\n$$\n\nThis process can be generalized and the global displacement/force equations written\n\n\n$$\n   \\{F\\}= [K] \\{u\\}\n$$\n\n\nWhere\n\n\n$$\n   [K] = \\sum_{e=1}^N [k]^{(e)}\n   \\quad \\mathrm{and} \\quad\n   \\{F\\} = \\sum_{e=1}^N \\{f\\}^{(e)}\n$$\n\n\nwhere $[k]^{(e)}$ and $\\{f\\}^{(e)}$ are the expanded element stiffness and force, respectively.\n\n##### Degree of Freedom Mapping\n\nThis assembly procedure defines a mapping from local degrees of freedom to global degrees of freedom.  Mathematically, the mapping from local to global degrees of freedom is given by\n\n$$\nn_{\\text{dof}}^{\\text{sys}} = n \\times n_{\\text{dof}}^{\\text{d}} + d\n$$ \n\nwhere $n$ is the global node number and the local degree of freedom $d$ takes values $0, 1, 2$ for the $x, y, z$ degree of freedom, respectively.\n\nGraphically, the mapping looks like\n\n\n\n<div class=\"msg msg-error\">\nThis mapping is true only for node numbering staring at 0!\n</div>\n\n#### Step 6: Apply Boundary Conditions\n\nIt can be shown that $\\det{[K]}=0$, or, $[K]$ is non-invertible. Meaning that, **as is, the system is not stable** and has either no solutions or infinite solutions. Boundary conditions must be supplied to make the system non-singular. This makes sense intuitively, before boundary conditions are specified the structure is free to move without constraint, meaning that there are infinite solutions for the displacement at each node.\n\nFor our tapered bar problem, consider the condition that the origin is fixed. Boundary conditions of this type are called *homogeneous*. In our example, this means that $u_{1}=0$ and \n\n\n$$\n   \\begin{Bmatrix}\n     R \\\\ 0 \\\\ 0 \\\\ 0 \\\\ F \\\\\n   \\end{Bmatrix}\n   =\n   \\begin{bmatrix}\n     k_{1} & -k_{1} & 0 & 0 & \\\\\n     -k_{1} & k_{1} + k_{2} & -k_{2} & 0 & 0 \\\\\n     0 & -k_{2} & k_{2} + k_{3} & -k_{3} & 0 \\\\\n     0 & 0 & -k_{3} & k_{3} + k_{4} & -k_{4} \\\\\n     0 & 0 & 0 & -k_{4} & k_{4}\n   \\end{bmatrix}\n   \\begin{Bmatrix}\n     0 \\\\ u_{2} \\\\ u_{3} \\\\ u_{4} \\\\ u_{5}\n   \\end{Bmatrix}\n$$\n\n\nnote that the displacements $u_{2}, u_{3},$ and $u_{4}$ do not explicitly depend on the reaction force $f_{1}$, this motivates us to write the following partitions:\n\n\n$$\n   \\begin{Bmatrix}\n     R \\\\ \\hline 0 \\\\ 0 \\\\ 0 \\\\ F \\\\\n   \\end{Bmatrix}\n   =\n   \\left[\n     \\begin{array}{c|ccc}\n       k_{1} & -k_{1} & 0 & 0 & 0\\\\\n       \\hline -k_{1} & k_{1}+k_{2} & -k_{2} & 0 & 0 \\\\\n       0 & -k_{2} & k_{2} + k_{3} & -k_{3} & 0 \\\\\n       0 & 0 & -k_{3} & k_{3} + k_{4} & -k_{4} \\\\\n       0 & 0 & 0 & -k_{4} & k_{4}\n     \\end{array}\n   \\right]\n   \\begin{Bmatrix}\n     0 \\\\ \\hline u_{2} \\\\ u_{3} \\\\ u_{4} \\\\ u_{5}\n   \\end{Bmatrix}\n$$\n\n\nor,\n\n\n$$\n   \\begin{Bmatrix}\n     \\{F^1\\} \\\\ \\{F^2\\}\n   \\end{Bmatrix}\n   =\n   \\begin{bmatrix}\n    \\left[K^{11}\\right] & \\left[K^{12}\\right] \\\\\n    \\left[K^{21}\\right] & \\left[K^{22}\\right]\n  \\end{bmatrix}\n  \\begin{Bmatrix}\n    \\{u^1\\} \\\\ \\{u^2\\}\n  \\end{Bmatrix}\n$$\n\n\nwhere\n\n\n$$\n   \\{F^1\\}=[R]^T, \\quad \\{F^2\\}=[0, \\ 0, \\ 0, \\ F]^T\n$$\n\n\n\n\n$$\n   \\left[K^{11}\\right] = \\left[ k_{1} \\right],\n   \\ldots,\n   \\left[K^{22}\\right] =\n   \\begin{bmatrix}\n     k_{1}+k_{2} & -k_{2} & 0 & 0 \\\\\n     -k_{2} & k_{2}+k_{3} & -k_{3} & 0 \\\\\n     0 & -k_{3} & k_{3} + k_{4} & -k_{4} \\\\\n     0 & 0 & -k_{4} & k_{4}\n   \\end{bmatrix}\n$$\n\n\nand\n\n\n$$\n   \\{u^1\\} = [0]^T,\n   \\quad\n   \\{u^2\\} = \\left[u_{2}, \\ u_{3}, \\ u_{4}, \\ u_{5} \\right]^T\n$$\n\n\nIn expanded form,\n\n\n$$\n   \\{F^1\\}=\\left[ K^{11}\\right]\\{u^1 \\} + \\left[ K^{12} \\right] \\{u^2\\}\n$$\n\n$$\n   \\{F^2\\} = \\left[K^{21}\\right]\\{u^1 \\} + \\left[K^{22}\\right]\\{u^2\\}\n$$\n\n<div class=\"msg\">\nThe above method of applying boundary conditions is referred to as a partitioning method.  If combined with re-ordering of the global equations, it is a great way of decreasing the size of the system being solved.  However, it is more difficult to implement computationally.\n</div>\n\n### Solution Phase\n\n#### Step 1: Solve for the Nodal Displacements\n\nSolve for displacements that satisfy\n\n$$\n[K]^*\\{u\\} = \\{F\\}^*\n$$\n\nwhere $[K]^*$ and $\\{F\\}^*$ are the boundary condition modified stiffness and force.\n\nUpon solving for $\\{u\\}$ we find\n\n$$\n  \\begin{Bmatrix} u_1 \\\\ u_2 \\\\ u_3 \\\\ u_4 \\end{Bmatrix}\n  =\n  F \\begin{Bmatrix} 0 \\\\\n                    \\frac{1}{k_1} \\\\\n                    \\frac{1}{k_1} + \\frac{1}{k_2}  \\\\\n                    \\frac{1}{k_1} + \\frac{1}{k_2} + \\frac{1}{k_3} \\\\\n                    \\frac{1}{k_1} + \\frac{1}{k_2} + \\frac{1}{k_3} + \\frac{1}{k_4}\n  \\end{Bmatrix}\n$$.\n\n#### Step 2: Compute Reactions\n\nFinally, the reaction force at the fixed boundary can be found from\n\n$$\n\\{r\\} = [K]\\{u\\} - \\{f\\}\n$$\n\nwhich, for this example, reduces to\n\n$$\n   f_{1}\n   = -k_{1}u_{2} = -F\n$$\n\n\nwhich is not a surprising result.\n\n### Post Processing Phase\n\n#### Step 1: Find element strains and stresses and other important information.\n\n##### General Spring Element\n\nFor spring elements, post processing involves computing resultant element elongation and forces\n\n<table id='mytable'>\n<tr><td>Element Elongation</td><td>Element Forces</td></tr>\n<tr><td>\n$$\\begin{pmatrix}\n\\Delta L^{(1)} \\\\\n\\Delta L^{(2)} \\\\\n\\Delta L^{(3)} \\\\\n\\end{pmatrix} = \n\\begin{pmatrix}\nu_2 - u_1 \\\\\nu_3 - u_2 \\\\\nu_4 - u_3\n\\end{pmatrix} $$</td>\n<td>$$\\begin{pmatrix}\nf^{(1)} \\\\\nf^{(2)} \\\\\nf^{(3)}\n\\end{pmatrix} = \n\\begin{pmatrix}\nk^{(1)}\\Delta L^{(1)} \\\\\nk^{(1)}\\Delta L^{(2)} \\\\\nk^{(1)}\\Delta L^{(3)}\n\\end{pmatrix} $$\n</td></tr>\n</table>\n\n##### Bar Element\n\nFor bar elements, post processing involves computing resulant strains, stresses, and forces.\n\n<table id='mytable-1'>\n<tr><td>Element Elongation</td><td>Element Strains</td></tr>\n<tr><td>$$\\begin{pmatrix}\n\\Delta L^{(1)} \\\\\n\\Delta L^{(2)} \\\\\n\\Delta L^{(3)}\n\\end{pmatrix} = \n\\begin{pmatrix}\nu_2 - u_1 \\\\\nu_3 - u_2 \\\\\nu_4 - u_3\n\\end{pmatrix} $$</td>\n<td>$$\\begin{pmatrix}\n\\epsilon^{(1)} \\\\\n\\epsilon^{(2)} \\\\\n\\epsilon^{(3)}\n\\end{pmatrix} = \n\\begin{pmatrix}\n\\Delta L^{(1)} / L^{(1)} \\\\\n\\Delta L^{(2)} / L^{(2)} \\\\\n\\Delta L^{(3)} / L^{(3)}\n\\end{pmatrix}$$</td></tr>\n</table>\n\n<table id='mytable-1'>\n<tr><td>Element Stresses</td><td>Element Forces</td></tr>\n<tr><td>$$ \\begin{pmatrix}\n\\sigma^{(1)} \\\\\n\\sigma^{(2)} \\\\\n\\sigma^{(3)}\n\\end{pmatrix} =\n\\begin{pmatrix}\nE^{(1)}\\epsilon^{(1)} \\\\\nE^{(2)}\\epsilon^{(2)} \\\\\nE^{(3)}\\epsilon^{(3)}\n\\end{pmatrix}$$ </td>\n<td>$$ \\begin{pmatrix}\nf^{(1)} \\\\\nf^{(2)} \\\\\nf^{(3)}\n\\end{pmatrix} = \n\\begin{pmatrix}\nA^{(1)}\\sigma^{(1)} \\\\\nA^{(2)}\\sigma^{(2)} \\\\\nA^{(3)}\\sigma^{(3)}\n\\end{pmatrix}$$</td>\n</tr>\n</table>.\n\n### <a id='multi_spring'> </a> Example 2: Parallel Spring Network\n\nConsider the following network of springs\n\n\n\n\n\nWith the left and right edges of the plate is fixed as shown, what is the displacement of the rigid bar due to the force $P$?\n\nWe solve the problem using the same steps as above.  However, we solve the problem entirely using sympy.\n\n#### Preprocessing Phase\n\nIndividual element stiffnesses take the same form as in previous examples.  However, when inserting the element stiffnesses in to the appropriate locations in the global stiffness, we must account for the fact that 3 elements have node 2 in common.  Note that\n\n$$\n   \\begin{split}\n     u_{1}^{(1)} &= u_{1} = 0 \\\\\n     u_{2}^{(1)} = u_{1}^{(2)} = u_{1}^{(3)} &= u_{2} \\\\\n     u_{2}^{(3)} &= u_{3} = 0 \\\\\n     u_{2}^{(4)} &= u_{4} = 0 \\\\\n   \\end{split}\n$$\n\nExpansion of element stiffness for insertion in to the global stiffness is demonstrated below.\n\n\n```python\nimport sympy as sp\nimport numpy as np\nfrom sympy import Matrix, symbols, Symbol, zeros as spzeros, init_printing, N\ninit_printing()\n```\n\n\n```python\n# Expand element stiffnesses to have same shape as global stiffness\n# by inserting appropriate columns and rows of zeros.\nk1, k2, k3 = symbols('k1 k2 k3')\nK1 = Matrix(4, 4, lambda i,j: 0)\nK1[0:2, 0:2] = Matrix(2, 2, lambda i,j: k1 if i==j else -k1)\nK2 = Matrix(4, 4, lambda i,j: 0)\nK2[1:3, 1:3] = Matrix(2, 2, lambda i,j: k2 if i==j else -k2)\nK3 = Matrix(4, 4, lambda i,j: 0)\nK3[1, :] = Matrix(1,4,[0,k3, 0, -k3])\nK3[3, :] = Matrix(1,4,[0,-k3, 0, k3])\nKg = K1 + K2 + K3\nKg\n```\n\n##### Apply Boundary Conditions\n\nIn this example, we apply boundary conditions using the \"penalty method\".  The penalty method is easily explained by example.  Consider the global system of equations\n\n$$\n\\begin{bmatrix} \nk_1 & -k_1 & 0 & 0\\\\\n-k_1 & k_1+k_2+k_3 & -k_2 & -k_3 \\\\\n0 & -k_2 & k_2 & 0 \\\\\n0 & -k_3 & 0 & k_3 \n\\end{bmatrix}\n\\begin{Bmatrix} \nu_1 \\\\\nu_2  \\\\\nu_3 \\\\\nu_4\n\\end{Bmatrix}\n=\n\\begin{Bmatrix} \nR_1 \\\\\nP  \\\\\nR_3 \\\\\nR_4\n\\end{Bmatrix}\n$$\n\nWe substitute for the unknown reactions the known boundary conditions times a large number $X$.  In the stiffness matrix, we substitute the appropriate components with $X$, as shown:\n\n$$\n\\begin{bmatrix} \nX & -k_1 & 0 & 0\\\\\n-k_1 & k_1+k_2+k_3 & -k_2 & -k_3 \\\\\n0 & -k_2 & X & 0 \\\\\n0 & -k_3 & 0 & X\n\\end{bmatrix}\n\\begin{Bmatrix} \nu_1 \\\\\nu_2  \\\\\nu_3 \\\\\nu_4\n\\end{Bmatrix}\n=\n\\begin{Bmatrix} \nX u^*_1 \\\\\nP  \\\\\nX u^*_3 \\\\\nX u^*_4\n\\end{Bmatrix}\n$$\n\nInspecting row 1, we see\n\n$$Xu_1 - k_1 u_2 = X u_1^*$$\n\nwhere $u_1^*$ is the known boundary condition ($u_1^*=0$ in this case).  On dividing by $X$ we get\n\n$$u_1 - \\frac{k_1 u_2}{X} = u_1^*$$\n\nif $X$ is chosen large enough $\\frac{k_1 u_2}{X} \\approx 0$ and\n\n$$u_1 \\approx u_1^*$$\n\nGenerally, the penalty method follows as\n\nFor a known displacement $\\delta_m$ applied at node $m$ and $X>>\\text{any} \\ K_{ij}$\n\n$$\\begin{align} K_{mm} &= X \\\\ F_{m} &= X\\delta_m \\end{align}$$\n\n\n\n```python\n# Apply boundary conditions by setting appropriate components of K\n# to 0 or 1.  We form K by making a copy of Kg so that we can retain\n# the original stiffness.\nK = Matrix(Kg)\nX = 1.E+30\nK[0,0] = X\nK[2,2] = X\nK[3,3] = X\n\n# Form the force array F.  Note that f1 and f3 are the unknown reaction\n# forces\nP = symbols('P')\nF = Matrix(4, 1, [0, P, 0, 0])\n\n# Solve for displacements.\nu = K.LUsolve(F)\n\n# At this point, the solution will be messy. \n# Let's substitute some actual numbers\nsubs ={k1: 10, k2: 5, k3: 5, P: 10}\nN(u.subs(subs))\n```\n\n\n```python\n# Solve for reactions by back substituting u in to the global equations\nreact = Kg * u - F\nreact.subs(subs)\n```\n\nWhich is exactly as expected.\n\n<div class=\"msg\">\nThe penalty method is less accurate as the number of nodes & elements increases, but it is algorithmically simple and leads to a general formulation for boundary conditions.\n</div>\n\n### <a id='presc_disp'> </a>  Example 3: Prescribed Displacement\n\nSuppose now, that instead of there being an applied force to the end of our tapered beam we force the displacement at the end of the beam to be some prescribed amount $\\delta$.\n\n\n\nThe solution technique is similar the previous problem. Namely, find element stiffnesses, derive the global stiffness, apply boundary conditions, solve for displacements, and find element forces.\n\nWe'll solve this problem again using sympy.\n\n#### Preprocessing Phase\n\n\n```python\n# Stiffness and force symbols\nk1, k2, d = symbols('k_1 k_2 delta')\n\n# Global stiffness matrix\nKg = Matrix([[ k1,   -k1,     0], \n             [-k1, k1 + k2, -k2], \n             [ 0,    -k2,    k2]])\n```\n\n##### Apply Boundary Conditions\n\nWe've looked at partitioning the system of equations and the penalty method as ways of applying boundary conditions.  In this example we use a substitution method whereby the unknown reactions are substituted with the known boundary conditions and 1s and 0s are substituted in the appropriate locations in the global stiffness.  This is perhaps best shown with an example, consider the global system for this problem\n\n$$\n\\begin{bmatrix}\nk_1 & -k_1 & 0 \\\\ \n-k_1 & k_1 + k_2 & -k2 \\\\ \n0 & -k2 & k2\n\\end{bmatrix}\n\\begin{Bmatrix}\nu_1 \\\\ \nu_2 \\\\ \nu_3\n\\end{Bmatrix}\n=\n\\begin{Bmatrix}\nR_1 \\\\ \n0 \\\\ \nR_3\n\\end{Bmatrix} \\Longrightarrow\n\\begin{bmatrix}\n1 & 0 & 0 \\\\ \n-k_1 & k_1 + k_2 & -k2 \\\\ \n0 & 0 & 1\n\\end{bmatrix}\n\\begin{Bmatrix}\nu_1 \\\\ \nu_2 \\\\ \nu_3\n\\end{Bmatrix}\n=\n\\begin{Bmatrix}\n0 \\\\ \n0 \\\\ \n\\delta\n\\end{Bmatrix}\n$$\n\nIt's easy to see that this system of equations satisfies the boundary conditions.\n\n<div class=\"msg\">\n<b>Note:</b> The substitution method as shown is simple to implement, but has the (severe) disadvantange that the resulting system of equations is not symmetric.  We will later see how to make the system symmetric\n</div>\n\n\n```python\n# Apply boundary conditions to a copy of the global stiffness.  We\n# set appropriate components to the first and last row of K to 0 or 1\n# to strictly enforce the known displacement\nK = Matrix(Kg)\nK[2,1], K[2,2] = 0, 1\n\n# Form the force array - inserting known boundary conditions in to\n# the appropriate locations\nf1 = symbols('f1')\nF = Matrix([[f1], \n            [0], \n            [d]])\n\nu2, u3 = symbols('u2 u3')\nu = Matrix(3, 1, [0, u2, u3])\nu[1:, :] = K[1:, 1:].LUsolve(F[1:, :])\nu\n```\n\nSolve for reactions\n\n\n```python\n# Solve for reactions by back substitution\nreact = Kg * u\nreact\n```\n\n### <a id='ex_self_weight'> </a>  Example 4: Self-Weight\n\n#### Load Types\n\nIn previous examples, forces were applied directly to the model nodes.  There are situations, however, that loads act on a body or a surface.  Body loads have units of force per unit mass and scale with element volume.  Surface tractions have units of force per unit area and scale with element surface area or cross section. \n\n#### Element Body Forces\n\nA *distributed body force* has units of force/length in 1D.  In structural problems, body forces are often the result of gravity.  Body forces can also result from acceleration, e.g., a centripetal force in a centrifuge.\n\nElement force due to a general body load is given by\n\n$$\nb^{(e)} = \\left(\\frac{\\text{force}}{\\text{mass}}\\right)\\rho^{(e)} V^{(e)}\n$$\n\nThe element force due to self-weighted bar:\n\n$$\nw^{(e)}=g\\rho^{(e)}A^{(e)}L^{(e)}\n$$\n\nand the distributed body load is\n\n$$\nb(x) = \\frac{w^{(e)}}{L^{(e)}} = \\frac{m^{(e)}g}{L^{(e)}} \n= \\rho^{(e)}A^{(e)}g\n$$\n\n#### Nodal Forces\n\nBody loads are defined over the element domain, but our FE method admits only forces applied at nodes.  So, body loads and surface tractions (\udbff\udc00point loads)\udbff\udc01 are partitioned to neighboring nodes as shown for element 1.\n\n\n\n\n\n\n# <a id='comp_impl'> </a> Implementing the Direct Stiffness Method Computationally[](#top)\n\nThe steps necessary for implementing a 1D linear finite program computationally are shown in the figure below\n\n\n\nThe computational implementation requires (minimally)\n\n- specification of mesh, loads and constrains, and material properties\n- assembly of element stiffnesses and forces in to the global stiffness and force\n- solution of $[K]\\{F\\}=\\{u\\}$ for unkown displacements\n- post processing results\n\nIn the following sections, we walk through the actual machinery to implement the finite elemenet method computationally with the following example.\n\n\n\n## <a id='preproc'></a> Pre Processing\n\n### <a id='mesh_spec'> </a> Mesh Specification\n\nThe mesh consists of vertices defining nodal coordinates and element connectivity tables specifiying how vertices are connected.\n\n#### Connectivity Tables\n\nFor complex systems, especially in higher dimensions, manually assembling the global stiffness matrix would be tedious and error\u2010prone. To avoid errors in a FEM code we use a connectivity table, a lookup table that contains the nodes associated with each element.\n\nThe element connectivity for our example is\n\n| Element Number  | Node i | Node j |\n| :-------------: |:------:| :-----:|\n| 1               | 1      | 3      | \n| 2               | 3      | 4      |\n| 3               | 4      | 2      |\n\n#### Vertices\n\nNodal coordinates (vertices) are given as an array of nodal coordinates.  For our example we have\n\nIn general, for a 3D mesh we have\n\n|Node|Coordinate|\n|:--:|:--------:|\n| 1  |$0.$|\n| 2  |$3.$|\n| 3  |$1.$|\n| 4  |$2.$|\n\nNode labels in the first column must correspond to the appropriate node labels in the connectivity table.  But, they need not be given in ascending node order as shown.  Alternatively, we could order the nodal coordinates as \n\n|Node|Coordinate|\n|:--:|:--------:|\n| 1  |$0.$|\n| 3  |$1.$|\n| 4  |$2.$|\n| 2  |$3.$|\n\nso long as there is a way for mapping the node label to the appropriate index of the vertices array.  The mechanisim with which this accomplished the use of a node map that maps node labels to the appropriate index in the array of nodal vertices.  For example nodal coordinates in the right column of the above table could be passed and the left column could be passed as the node map.  The finite element program would then use the node map to look up the location of a node's vertices.\n\n### Constraints and Loads\n\nConstraints and loads are specified in such a way that the program can apply the appropriate contraint or load to the correct the node, local degree of freedom, and with the right magnitude.  Several ways exist to pass this information to a program, one way is with an array of the following form\n\n    a = [(node label of constraint/load 1, 'x' 'y' or 'z', magnitude 1),\n         (node label of constraint/load 2, 'x' 'y' or 'z', magnitude 2),\n                                            .\n                                            .\n                                            .\n         (node label of constraint/load n, 'x' 'y' or 'z', magnitude n)]\n         \nEach row contains the necessary information for applying a constraint or load to an appropriate node.  Note, in our 1D examples, the local degree of freedom is restricted to be only '`x`'.  This restriction is relaxed when we move on to more than one dimension.\n\n## <a id='solphase'></a> Solution Phase\n\n### Assemble Global Equations\n\nIndividual element stiffnesses must be \"assembled\" or mapped in to the global stiffness in the appropriate locations.  We can use the information in the system's connectivity table to to generate the appropriate mapping.  First consider the following question\n\n<div class=\"msg\">\n<b>Q</b>: How can we tell by inspection if the stiffness matrix is correct? <br>\n\n<b>A</b>: Look at the ith row and jth column of K <br>\n\n<ul>\n<li> The terms on the ith position of the main diagonal should be the sum of the stiffness for each element connected to the ith degree of freedom.\n<li> The off\u2010diagonal terms in the i,j position should be the negative of the stiffness of the element's connecting degrees of freedom i and j. \n<li> The stiffness should be symmetric\n</ul>\n</div>\n\nWith that in mind, the algorithm for generating the stiffness matrix is:\n\n    K = 0\n    k = [k1, k2, k3, ..., kn]\n    for all elements\n      determine global index I of node i of element\n      determine global index J of node j of element\n      K[I, I] = K[I, I] + k[el]\n      K[J, J] = K[J, J] + k[el]\n      K[I, J] = K[I, J] - k[el]\n      K[J, I] = K[J, I] - k[el]\n    \nIncidentally, the algorithm shown is extremely inefficient and can be optimized, but optimization is the job of computer scientists.  As engineers, we seek the right answer as a learning exercise.  In this algorithm, the `i` and `j` global index are determined by the node mapping, previously discussed.\n\nThe global force is assembled in a similar fashion.\n\n### Apply Boundary Conditions\n\nBelow we implement concepts learned in to a concise code for determining nodal displacements.  Let us first revisit the question of imposing boundary conditions.  In the substitution method we saw that the resulting global stiffness was not symmetric.  For large systems this becomes problematic because solving non-symmetric equations is much more expensive than symmetric.  But, the substitution method is easy to implement and there is not a loss of accuracy as in the penalty method.  Let's modify substitution method so that the system of equations remains symmetric.  We look at Example 3.  We had:\n\n$$\n\\begin{bmatrix}\nk_1 & -k_1 & 0 \\\\ \n-k_1 & k_1 + k_2 & -k2 \\\\ \n0 & -k2 & k2\n\\end{bmatrix}\n\\begin{Bmatrix}\nu_1 \\\\ \nu_2 \\\\ \nu_3\n\\end{Bmatrix}\n=\n\\begin{Bmatrix}\nR_1 \\\\ \n0 \\\\ \nR_3\n\\end{Bmatrix} \\Longrightarrow\n\\begin{bmatrix}\n1 & 0 & 0 \\\\ \n-k_1 & k_1 + k_2 & -k2 \\\\ \n0 & 0 & 1\n\\end{bmatrix}\n\\begin{Bmatrix}\nu_1 \\\\ \nu_2 \\\\ \nu_3\n\\end{Bmatrix}\n=\n\\begin{Bmatrix}\n\\delta_1 \\\\ \n0 \\\\ \n\\delta_3\n\\end{Bmatrix}\n$$\n\nwhere $\\delta_1$ and $\\delta_3$ are the known displacements. \n\nBut, we would like the final system to be symmetric.  We obtain the goal by setting each entry in the first and third columns (apart from the diagonal) to zero, so that the stiffness is symmetric.  Recall that we can add and subtract equations in the system from one another without affecting the solution.  Therefore, to symmetrize the stiffness matrix in our example, we can subtract appropriate multiples of the first and third rows so as to set each entry in the first and thrid columns to zero.\n\n$$\n\\begin{bmatrix}\n1 & 0 & 0 \\\\ \n0 & k_1 + k_2 & 0 \\\\ \n0 & 0 & 1\n\\end{bmatrix}\n\\begin{Bmatrix}\nu_1 \\\\ \nu_2 \\\\ \nu_3\n\\end{Bmatrix}\n=\n\\begin{Bmatrix}\n0 \\\\ \nk_1 \\delta_1 + k_2\\delta_3 \\\\ \n\\delta\n\\end{Bmatrix}\n$$\n\nCompare equations to convince yourself that this is correct.\n\nGenerally, symmetric substitution follows as\n\nFor a known displacement $\\delta_m$ applied at node $m$\n\n$$\n\\begin{align}\nF_i &= F_i \u2212 \\sum_{i=1, i\\neq m}^N K_{im}\\delta_m \\\\\nF_m &= \\delta_m \\\\\nK_{mj} &= 0, \\quad j=1\\ldots{}N \\\\\nK_{im} &= 0, \\quad i=1\\ldots{}N \\\\\nK_{mm} &= 1\n\\end{align}\n$$\n \n\n## <a id='one_d_code'> </a> Linear Finite Element Code\n\nSee `femlib.ifem.solve_system` for the code.\n\n\n```python\n#%load femlib/ifem.py\n```\n\n<div class=\"msg msg-success\">\nCheck out the new function 'enumerate' introduced in the code above.  enumerate(thing), where thing is a sequence, returns a iterator that will return (0, thing[0]), (1, thing[1]), (2, thing[2]), and so forth. <p>\n\nA common idiom to change every element of a list looks like this: <p>\n\nfor i in range(len(L)):<br>\n&emsp;&emsp;    item = L[i] <br>\n&emsp;&emsp;    # ... compute some result based on item ...<br>\n&emsp;&emsp;    L[i] = result<br>\n<p>\nThis can be rewritten using enumerate() as:<br>\n<p>\nfor i, item in enumerate(L):<br>\n&emsp;&emsp;    # ... compute some result based on item ...<br>\n&emsp;&emsp;    L[i] = result<br>\n<p>    \nsee the <a href=\"https://docs.python.org/2/library/functions.html#enumerate\"> enumerate </a> documentation\n</div>\n\n### The Example, Completed\n\nRecall our example problem\n\n\n\nUsing `femlib.ifem.solve_system`, the solution for the unknown displacements and reactions is given by\n\n\n```python\n# Solution of the example problem\nfrom femlib.ifem import solve_system\nvertices = np.array([0., 1., 2., 3.])\nnode_map = [1, 3, 4, 2]\nconnect = np.array([[1, 1, 3],\n                    [2, 3, 4],\n                    [3, 4, 2]])\nk = [1000, 2000, 3000]\nF4x = 5000\ncfs = [(4, 'x', F4x)]\nbcs = [(1, 'x', 0), (2, 'x', 0)]\n\nu, r = solve_system(vertices, connect, k, bcs, cfs, node_map)\nprint 'u =', u\nprint 'r =', r\n```\n\n    u = [ 0.          0.90909091  1.36363636  0.        ]\n    r = [ -9.09090909e+02   0.00000000e+00  -1.81898940e-12  -4.09090909e+03]\n\n\n\n```python\n# sum of reactions and force should be 0\nprint round(np.sum(r) + F4x)\n```\n\n    -0.0\n\n\n## A Uniform Bar Code\n\nAn important part of computational mechanics is using existing libraries/code.  Doing so saves time/resources and allows us to concentrate on more specific parts of our own codes.  Let us use the previous code example to write a special purpose 1D uniform bar code.  See `apps/uniformbar.py` for the implementation.\n\nRe-using the existing code allowed us to write a new application with only 5 or so lines of code.\n", "meta": {"hexsha": "e0929d7c99ae2e29ebfb03314fceb7aa1efea0b7", "size": 70576, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lessons/Lesson03_DirectMethods.ipynb", "max_stars_repo_name": "jzw0025/fem-with-python", "max_stars_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 148, "max_stars_repo_stars_event_min_datetime": "2015-11-05T16:32:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:42:26.000Z", "max_issues_repo_path": "Lessons/Lesson03_DirectMethods.ipynb", "max_issues_repo_name": "pinkieli/fem-with-python", "max_issues_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lessons/Lesson03_DirectMethods.ipynb", "max_forks_repo_name": "pinkieli/fem-with-python", "max_forks_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": 74, "max_forks_repo_forks_event_min_datetime": "2016-02-17T13:23:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T07:48:27.000Z", "avg_line_length": 38.6506024096, "max_line_length": 2704, "alphanum_fraction": 0.5489968261, "converted": true, "num_tokens": 12801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07585818002124356, "lm_q2_score": 0.10669060104662924, "lm_q1q2_score": 0.008093354820769878}}
{"text": "> *This textbook was generated automatically from a [GitHub Repo](https://github.com/Hribek25/IOTA101). Visit the repo for more information.* \n\n\n# IOTA Developer Essentials\n[](https://hribek25.github.io/IOTA101/devlab.html#Language-Coverage)\n[](https://github.com/Hribek25/IOTA101)\n[](https://gist.github.com/search?utf8=%E2%9C%93&q=IOTA101)\n[](https://hribek25.github.io/IOTA101/devlab.html)\n[](https://hribek25.github.io/IOTA101/)\n[](https://ecosystem.iota.org/tutorials/iota-developer-essentials)\n\nThese notebooks provide a self-study introduction to IOTA protocol and are designed for developers and tech enthusiasts who would like to get quickly familiar with the IOTA. Technical-related information is accompanied with interactive code snippets to help you to quickly jump on the platform and be ready to build own solutions based on it.\n\n> Motto of this tutorial: \"Let's start with baby steps before we can try and fly.\"\n\n## Main Goal\nMain goal of this guide is to provide a comprehensive yet well-balanced proportion of deep-dive technical information and essentials.\n\n## Getting Started\nThere are several chapters available. If you are not familiar with IOTA then it is highly recommended to follow them in the particular order to understand all important IOTA concepts properly. Otherwise you may get quickly confused later.\n\n## Code Snippets\nCode snippets are currently based on Python, NodeJs and C#. Since Python is very descriptive language and easy to understand, I believe the tutorial is basically understandable to anyone. Anyway, all important IOTA concepts are described in language-agnostic way and so you would be able to use any language of your choice.\n\nInterested to see what is the overall code base coverage breaked down to a specific language? The following page provides you such an info. Needless to say, we are working hard to be sure there is no language that would be a second-class citizen.\n\n[](https://hribek25.github.io/IOTA101/devlab.html#Language-Coverage)\n\nIOTA Developer Essentials are accompanied by *IOTA Developer Lab* and so you can play with all code snippets directly in your web browser. Feel free to experiment with the prepared code snippets and get your hands dirty. It is a best way how to get familiar quickly.\n\n[](https://hribek25.github.io/IOTA101/devlab.html)\n\nAll *standalone* code snippets are also maintained @ GitHub Gist. It enables you to fork them, comment them, share them, embed them and track all changes to them. See the action panel next to each code snippet.\n\n[](https://gist.github.com/search?utf8=%E2%9C%93&q=IOTA101)\n\n## Viewing and running\n### Interactive Mode\nThere exists a side project called *IOTA Developer Lab* that is built on top of *IOTA Developer Essentials*. The project provides infrastructure services for you to be able to get an interactive experience with all code snippets.\n\n[](https://hribek25.github.io/IOTA101/devlab.html)\n\n### Static Mode\nIf you prefer a static experience (for printing purposes, for instance) you can reach the given notebooks as a Complete Textbook that is compiled from all source materials:\n\n[](https://hribek25.github.io/IOTA101/)\n\nEverything is tightly linked together and so you can easily switch between different languages for instance, or you can share links to specific chapters, code snippets, etc. All links are static so feel free to share them.\n\n\n## Feedback and corrections\nThese notebooks are maintained at [GitHub](https://github.com/Hribek25/IOTA101).\nIssues can be submited via [issue tracker](https://github.com/Hribek25/IOTA101/issues).\n\n## About\nThese notebooks are developed and maintained by Petr Zizka (petr@zizkovi.name). It has been supported by the EDF Grant (https://blog.iota.org/the-5th-cohort-of-iota-ecosystem-development-fund-grantees-5cbf05227525).\n\nIt is ongoing process since IOTA is still under heavy development and rapidly emerging every day. So stay tuned - the plan is to keep adding fresh content on regular basis.\n\nFeel free to follow me at [Twitter](https://twitter.com/petrzizka) or IOTA Discord Channel (@hribek25#2683).\n*(New to Discord? Invitation link: https://discord.gg/fNGZXvh)*\n\nDisclaimer: I am not associated with the IOTA foundation. I am IOTA supporter.\n\n----\n\n\nThe IOTA Developer Essentials and IOTA Developer Lab are long-term projects. The main goal is to provide a comprehensive onboarding information to anybody interested in the IOTA protocol. It will cover much more chapters, more code snippets and it will also cover more languages. Your kind donations will support the vision pushing forward. Thank you.\n\nDonations (IOTA):\nDSZRO9TCIJIKZOKUPVNOJFKVAHFCKL9YMLPVZUAEVZPOFXLIUWLPRQWBMVVSFTKGMGPPHXCYE9MIZEVBXQNFYKYUA9\n\n\n\n\n--- \n\n\n# IOTA 101: Essentials and IOTA Terminology\nIOTA is an open-source Distributed Ledger Technology (DLT) with the following characteristics: *permissionless*, *feeless* and *trustless*. In contrary to the blockchain technology, the IOTA transactions are stored in a form of Directed Acyclic Graph (DAG) called *the Tangle*.\n\n\n## Transactions\nTransactions (TXs) in the tangle can be of two types:\n* **Value transactions** (*IOTA token* represents funds in case of value transactions)\n* **Zero-value transactions** (aka meta transactions)\n\nEvery transaction is attached to a specific *IOTA Address*.\nThere are no miners with IOTA protocol to validate transactions. The *consensus* is achieved by network participants themselves. Each participant that wants to broadcast a new transaction has to approve 2 past transactions and basically attach transaction as a children node. Transactions without children transactions (waiting to be confirmed) are called *tips*.\n\n## Seed, private key and address\nPair of unique IOTA address and corresponding *Private Key* is determistically generated from a *Seed*. You can generate (2<sup>53</sup> - 1) different addresses/private keys based on one Seed. Anybody can send anything to the given address however only Seed owner can send funds from IOTA address since only the Seed owner is able to generate corresponding *Private Key*.\n\nIOTA protocol uses One-Time Signature (OTS) for \"verifying\" whether private key matches to the given address, specifically Winternitz OTS (WOTS). So *Private Key* (specifically *Key Fragments* of the private key) is the key component while signing transactions using WOTS.\n\nThat's the reason why nobody should use IOTA address that have been already funds spent from. New IOTA address (of the given seed) should be generated and used instead. Please note, it applies only to fund-spending. Receiving funds/data is totaly fine even multiple times.\n\nTo summarize the key concept here. Only *Seed* is needed to be stored somewhere. Everything else can be safely generated from it: private key as well as address.\n\n## IOTA nodes\nThe Tangle runs on a *distributed network* of IOTA nodes called *mainnet*. There are also other separate \"Tangles\" serving for specific purposes: Devnet, SPAMnet, etc. You can interact with the network via public nodes using collection of public *API calls*. You can interact with any public node of the given network since all nodes \"gossiping\" all TXs across the whole network. Nodes are powered by a reference piece of software called *IRI* (IOTA Reference Implementation) **as of now**.\n\nIt is also important to mention that you do not exchange any sensitive information such as *Seed* with a node. Every sensitive operation such as TX signing is done on client's side and node is just a \"messenger\" that delivers your TX to the IOTA network.\n\n\n## Custom node\nYou can even run own IOTA node and actively participate to the whole network. There is a big advantage for developers in that case. Actual implementation of IRI  provides an usefull real-time information via messaging platform called ZeroMQ and so developers can leverage that.\n\n## API calls\nThere are ready-made libraries for major programming languages available and so you have more developer-friendly way how to interact with the IOTA network. Anyway, you can interact with IOTA network using pure API calls without any library. It is up to you.\n\n\n## Ternary\nIt is difficult to avoid mentioning *Ternary numeral system* while discussing IOTA at all. IOTA is based on ternary system under the hood and so you have got to be aware of some basic terminology in this respect. You are going to face this fact in any developer-related IOTA guide out there.\n\n### Ternary\nTernary has three as its base (aka base 3) as opposted to *binary* which is base 2. Instead of two states (0 and 1) it recognizes three states (for ex. -1, 0, 1).\n\n### Trit\nOne *Trite* is analogous to one *bit*. It is the smallest digit and has three states. Trit = **Tri**nary dig**it**.\n\n### Tryte\n*Tryte* consists of three *trits* meaning 27 combinations.\n$$3^3=27$$\n\nYou will recognize soon that almost everything is encoded in *Trytes* in the IOTA world. Tryte is visually represented using [A..Z] alphabets and number 9. One character represents one tryte (here comes 27 possible characters again). *Don't get mad, IOTA libraries are going to help us.*\n\nSmall example:\n\n\n```C#\n#r \"Tangle.Net.dll\"\nusing Tangle.Net.Entity;    \n\nvar trytes = new TryteString(\"YZJEATEQ9JKLZ\");\nConsole.WriteLine(trytes.ToString());\nConsole.WriteLine(\"Number of Trytes: \" + trytes.TrytesLength);\n\nvar trits = trytes.ToTrits();\n\nConsole.WriteLine(String.Join(\",\", trits));\nConsole.WriteLine(\"Number of Trits: \" + trits.Length);\n```\n\n\nYZJEATEQ9JKLZ\n\n\n\nNumber of Trytes: 13\n\n\n\n1,-1,0,-1,0,0,1,0,1,-1,-1,1,1,0,0,-1,1,-1,-1,-1,1,-1,0,-1,0,0,0,1,0,1,-1,1,1,0,1,1,-1,0,0\n\n\n\nNumber of Trits: 39\n\n\n# IOTA 101: Basic network interactions\nThe tutorial is based on IOTA libraries called *PyOTA* for Python, *IOTA Javascript Library (@iota/core)* for JavaScript and Tangle.Net for C# (.NET 4.x and .NET Standard). It encapsulates all official IRI API calls and it can be installed via `pip` in Python environment, via `npm` in JS environment and via `NuGet` in case of .NET environment.\n\nReader is also encouraged to try a ready-made environment via *IOTA Developer Lab* project (at lab.iota101.info) where anyone can run a code directly in a web browser. When viewing it interactively then just select a code snippet and hit `ctrl + enter` which executes it.\n\nAnyway, most of the information in the tutorial is language-agnostic and so only particular interfaces slightly differ across different IOTA libraries. Top-level details are the same regardless programming language you are going to use.\n\n## A few words about specific IOTA libraries\n### Python\n*PyOTA* is well maintained and understandable IOTA library that can be reached at https://github.com/iotaledger/iota.lib.py. It is very good starting point for beginners.\nIt can be installed via `pip`:\n```pip install pyota```\n\n### JavaScipt\nOfficial IOTA Javascript library (v1.0) is currently in beta however all main functions are working just fine, please see https://github.com/iotaledger/iota.js/. It is very modular and so you can install only components you really need.\n\nMain component is @iota/core and can be installed via `npm`:\n```npm install @iota/core```\n\nAs with everything in NodeJS, most of the tasks are asynchronous and they are chained via `callbacks` or `promise`. Snippets below leverage `promise` chaining.\n### C# (.NET)\n*Tangle.Net* is well maintained IOTA library for .NET and can be reached at https://github.com/Felandil/tangle-.net.\nIt can be installed via `NuGet`:\n```nuget.exe install tangle.net```\n\nSnippets below uses synchronous functions however the library provides also asynchronous (async postfix) version.\n\n\n## Conneting to IOTA nodes\nBefore you can interact with the IOTA network you need an URL of the running IOTA node. There are dozen of directories of public nodes available, feel free to google them.\n\nFor a sake of this tutorial I use a project *thetangle.org*. It is a load ballancer that provides you an access to a pool of participanting nodes effortlessly.\n* *Advantage:* you do not have to care about public nodes and whether they are running or not\n* *Disadvantage:* you do not know in advance which specific node will process your API call. So in some respect results of API calls may differ since some API calls depend on specific node, such as GetNodeInfo().\n\n### Node is not synced\nEven if a node is up and running it may not be fully prepared to process your API calls correctly. The node should be \"synced\", meaning should be aware of all TXs in the Tangle. It is better to avoid not fully synced nodes.\n\n### Health checking\nOnce you connect to an IOTA node you should be able to send API calls. However it is better to do some checks in advance in order to find out whether the given node is in good condition or not. IOTA nodes can be run by anyone and so health check is always a good practice.\n\nBasic healthcheck can be done via *GetNodeInfo()* API call. It returns a basic information about the given IOTA node.\n\n\n```C#\n#r \"Tangle.Net.dll\"\n#r \"Newtonsoft.Json.dll\"\n#r \"RestSharp.dll\"\n\nusing Tangle.Net.Repository;\nusing Newtonsoft.Json;\nusing RestSharp;\n\nvar NodeURL = \"https://nodes.thetangle.org:443\";\n\nvar repo = new RestIotaRepository(new RestClient(NodeURL)); // ctor initialization of the Tangle.Net library\nvar nodeInfo = repo.GetNodeInfo(); // Getting information about the current node\nConsole.WriteLine(JsonConvert.SerializeObject(nodeInfo, Formatting.Indented)); //Result is printed in JSON notation\n\n// Basic check whether node is in sync or not\n// Elementary rule is that \"latestMilestoneIndex\" should equal to \"latestSolidSubtangleMilestoneIndex\" or be very close\nConsole.WriteLine(\n                  Math.Abs(nodeInfo.LatestMilestoneIndex - nodeInfo.LatestSolidSubtangleMilestoneIndex) > 3 ? \n                            \"Node is probably not synced!\" : \"Node is probably synced!\"\n                );\n```\n\n\n{\n  &quot;AppName&quot;: &quot;IRI&quot;,\n  &quot;AppVersion&quot;: &quot;1.8.1&quot;,\n  &quot;Duration&quot;: 0,\n  &quot;JreAvailableProcessors&quot;: 16,\n  &quot;JreFreeMemory&quot;: 1854364030,\n  &quot;JreMaxMemory&quot;: 20997734400,\n  &quot;JreTotalMemory&quot;: 4585458676,\n  &quot;LatestMilestone&quot;: &quot;UNFVFYFRHCKCYSCSLDAJROUSBEPYTOOHHJOGZGLJXJIBSTXAYTIKDMWEKPMMKHVOSETQJYEFUXLOZ9999&quot;,\n  &quot;LatestMilestoneIndex&quot;: 1178174,\n  &quot;LatestSolidSubtangleMilestone&quot;: &quot;UNFVFYFRHCKCYSCSLDAJROUSBEPYTOOHHJOGZGLJXJIBSTXAYTIKDMWEKPMMKHVOSETQJYEFUXLOZ9999&quot;,\n  &quot;LatestSolidSubtangleMilestoneIndex&quot;: 1178174,\n  &quot;Neighbors&quot;: 24,\n  &quot;PacketsQueueSize&quot;: 0,\n  &quot;Time&quot;: 1568711224721,\n  &quot;Tips&quot;: 7991,\n  &quot;TransactionsToRequest&quot;: 0\n}\n\n\n\nNode is probably synced!\n\n\n*Please note: When using node load balancers then this type of check is quite useless since other API calls of yours may be served by different node that may have not been checked. You should be aware of it and trust that the load balancer participates only with nodes that are in a good condition.*\n\n## Generating IOTA seed and IOTA address\nSince the IOTA network is *permissionless* type of network, anybody is able to use it and interact with it. No central authority is required at any stage. So anybody is able to generate own seed and respective private key/address anytime. It is highly recommended to *NOT* use online generators at all.\n\nThe Seed is the only key to the given addresses. Anyone who owns the Seed owns also all funds related to respective IOTA addresses (all of them).\n\nSeed and addresses only consists of characters [A-Z] and number 9. Length is always 81 charaters. There are usually also used additional 9 characters in IOTA addresses (so total lenght is 90 then) which is a *checksum*. It provides a way how to prevent typos while manipulating with IOTA addresses.\n\n\n### Seed\nA seed generation is a process that is based on random quessing of each character in the seed. Of course, you should always use cryptographically secure pseudo-random generator!\n\n\n```C#\n//based on https://github.com/siqniz/IOTA-Random-Seed-Generator\nusing System.Security.Cryptography;\n\nprivate static string NewRandomSeed()\n{\n    string iotaseed = string.Empty;\n    using (RNGCryptoServiceProvider _ran = new RNGCryptoServiceProvider()) // The class provides crypto-safe random generator\n    {\n        string[] _seed = new string[] { \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\", \"9\" };                \n\n        byte[] _data = new byte[8];  //8 bytes to hold an unsigned bits int\n        for (int i = 0; i <= 80; i++)   //The number times this will run in orde to fill the 81 char requirment\n        {\n            _ran.GetBytes(_data);\n            var gennum = BitConverter.ToUInt64(_data, 0);\n            var _num = (gennum % 27);\n            iotaseed += _seed[_num];\n        }\n    }\n\n    return iotaseed;\n}\n\nConsole.WriteLine(NewRandomSeed());\n\n```\n\n\nU9LYFWEPCQATZ9MNDQJZPMSCVQZMTNTWRWOIIPDCXOORZAPYATQGRZHVHSQ9DL9RYKGP9PAEBOTKAFM9R\n\n\nAlternatively you can leverage also PyOTA library since it has own implementation of the pseudo-random Seed generator (Python 2.7+ compatible). Difference between both methods is very subtle. I just wanted to illustrate both ways: Fully independent and IOTA-library-dependant. *Please note, IOTA Javascript library does not support a seed generation.*\n\n\n```C#\n#r \"Tangle.Net.dll\"\nusing Tangle.Net.Entity;\n\nvar seed = Seed.Random(); // Initializing new random seed\nConsole.WriteLine(seed.ToString());\nConsole.WriteLine(\"Length :\" + seed.ToString().Length);\n```\n\n\n9KCKAMKL9JDWXTQKSEDBKJHZHBBARHBD9HXTDLSWQTGOXWBGDVOKOAFVHYKUYHIJKYCI9AETEKXIYQCAV\n\n\n\nLength :81\n\n\n### Address\nThere is a deterministic function how to get an address from a seed. It is a basically an indexed collection of addresses starting with address at index 0, 1, 2, etc.\n\nWhile generating addresses you should be also aware there are three different so called *Security Levels* (1, 2 and 3). Each security level generates totally independent pool of addresses. Addresses of Security Level 1 are totally different from addresses of Security Level 2, etc.\n\nIn a nutshell, Security Level indicates how difficult is to generate *Private key* from the Seed and also what is its size. The higher security level, the more secure (longer) is the given private key. Default Security Level is 2. Most of IOTA wallets uses Security Level=2 and users are usually not allowed to change it. So be carefull while designing your app.\n\nAs long as *seed, address index and security level* are the same, you always get the same address and corresponding private key:\n\n$$PrivateKey/Address = fce(Seed, AddressIndex, SecurityLevel)$$\n\nGeneral example:\n$$PrivateKey/Address1 = fce(Seed, 1, 2)$$\n$$PrivateKey/Address2 = fce(Seed, 2, 2)$$\n$$PrivateKey/Address3 = fce(Seed, 3, 2)$$\n\n\n\n\n```C#\n// No code snippet available for the selected language: csharp\n```\n\nPlease note, some IOTA libraries may communicate with a IOTA network while generating addresses to double check whether the given address was used or not.\n\nSo it is sometimes better to use directly an address generator component. Outputs are equivalent in both cases but the latter one usually only generates pool of addresses locally:\n\n\n```C#\n#r \"Tangle.Net.dll\"\n#r \"Newtonsoft.Json.dll\"\n    \nusing Tangle.Net.Cryptography;\nusing Tangle.Net.Entity;\nusing Newtonsoft.Json;\n\nvar seed = new Seed(\"WKQDUZTGFKSSLACUCHHLZRKZBHSDSCEBHKUPDLKFBQALEBKDMFRPUQGZRXAADPG9TSRTZGGBZOFRJCFMM\");\nvar addressGenerator = new AddressGenerator();\n\n// Please also see GetAdrress function for a single individual address\nvar addresses = addressGenerator.GetAddresses(seed,\n                                              SecurityLevel.Medium //security level 2\n                                              ,0 // from index\n                                              ,3 // count\n                                              );\n\n// The Address instance is very detailed and provides so many fields - so showing only address in Trytes for better clarity\nConsole.WriteLine(JsonConvert.SerializeObject(from i in addresses select i.ToTrytes(), Formatting.Indented));\n```\n\n\n[\n  &quot;HRLKBQUZAEB9HIVWJEWVDYQ9G9VRQXQAXR9ZWGBFQJKRPOPJYHGAT9LBEIE9RWRMUFSNLCWYHQGYAECHD&quot;,\n  &quot;XEXIDJJTANADOUBPWTCSPPRYYRTITRAHDEOZAEXWDPCYKUPTFMKVQM9KCPPLOCESFRGRVSIYZHXQZNYKC&quot;,\n  &quot;KY9DLZCHET9ATLMADPXGDVDYMPHKRKQPJZ9MB9HEIMMFCRRTNJIJIHPKGZNKKDTFMYPZRRQYAQKVAHMYX&quot;\n]\n\n\n## Validating IOTA address\nAs mentioned earlier, IOTA address consists of 81 trytes ([A..Z9] characters) or 90 trytes including checksum. Checksum is useful when you want to make sure a valid address was given (no typos, etc.) and so it is a good practise to encourage user of your app using IOTA addresses including checksums = 90 trytes.\n\nIOTA libraries are able to help you to deal with some basic patterns such as validating addresses, generating checksums, etc.\n\n\n```C#\n#r \"Tangle.Net.dll\"\nusing Tangle.Net.Entity;\n\nvar myAddr = new Address(\"CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\"); //some IOTA address\n\nConsole.WriteLine(\"Original input excl. checksum address:\");\nConsole.WriteLine(myAddr.ToString());\nConsole.WriteLine(\"Length: \" + myAddr.ToString().Length);\n\nvar AdrIncludingChecksum = new Address(myAddr.ToString() + Checksum.FromAddress(myAddr).ToString()); //generate checksum for the given address and return new address instance that includes checksum\n// There is a function Withchecksum() but it did not work when tested\n            \nConsole.WriteLine(\"Input address including checksum:\");\nConsole.WriteLine(AdrIncludingChecksum.ToString() + AdrIncludingChecksum.Checksum.ToString()); //Library still thinks of the address as 2 separate components\nConsole.WriteLine(\"Length incl checksum: \" + (AdrIncludingChecksum.ToString().Length + AdrIncludingChecksum.Checksum.ToString().Length));\n```\n\n\nOriginal input excl. checksum address:\n\n\n\nCYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\n\n\n\nLength: 81\n\n\n\nInput address including checksum:\n\n\n\nCYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RWTHBIRSXTA\n\n\n\nLength incl checksum: 90\n\n\nYou should always make sure your app is dealing with valid IOTA address. Please note, you should also make sure an address is of correct length and consists only of allowed characters. IOTA libraries may slightly differ in their approaches but differences are very subtle and both libraries provide enough functions to validate IOTA address.\n\nGeneral steps should be:\n* Checks length\n* Checks valid characters\n* Checks address against its checksum\n\n\n```C#\n#r \"Tangle.Net.dll\"\nusing Tangle.Net.Entity;\nusing Tangle.Net.Utils;\n\n//address including checksum\nvar InputAddr = \"CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RWTHBIRSXTA\";\n\nif (!InputValidator.IsTrytes(InputAddr) || InputAddr.Length != 90)\n{\n    Console.WriteLine(\"Not valid input address incl. checksum was given.\");\n} else {\n    var Adr = new Address(InputAddr);                \n\n    Console.WriteLine(\"Input address incl checksum:\");\n    Console.WriteLine(InputAddr);\n    Console.WriteLine(\"Is it valid addr based on checksum? \" + Adr.HasValidChecksum().ToString());\n    Console.WriteLine(\"Input address excl checksum:\");\n    Console.WriteLine(Adr.ToString());\n}\n```\n\n\nInput address incl checksum:\n\n\n\nCYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RWTHBIRSXTA\n\n\n\nIs it valid addr based on checksum? True\n\n\n\nInput address excl checksum:\n\n\n\nCYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\n\n\n# IOTA 101: Transactions\nA transaction is a smallest piece of data that can be broadcasted to the network. Each transaction consists of fixed 2673 trytes. Transactions (TXs) are basically of two types:\n* **Value TXs:** those transactions change ownership of IOTA tokens. Two possible states: spending TXs or receiving TXs\n* **Non-Value TXs:** those transactions include piece of data that can be broadcasted and read from the Tangle\n\nTransactions are broadcasted in an envelope called *Bundle*. Bundle may consist of multiple TXs. Bundle is processed by the Tangle as a single entity; meaning only the whole bundle is confirmed by the network (and all TXs within) or nothing. You have to prepare a bundle even if you broadcast single transaction only. Bundle is also described as *atomic* since every bundle includes all information needed to process it antonomously.\n\nEach transaction includes several fields, let's name the most important ones:\n* **`Value`:** Value can be *positive* number = receiving IOTA tokens, *negative* number = spending IOTA tokens or *zero* = broadcasting only piece of data\n* **`Address`:** It is IOTA address that is associated with the given transaction. *Value* indicates whether it is an address of a receiver or a sender\n* **`Tag`:** It is an user-defined tag that can be used for searching, etc.\n* **`SignatureMessageFragment`:** This is the most lenghty attribute (2187 trytes) and could include: *transaction signature* based on private key in case it is a spending TX or *piece of data (message)* in case it is non-value TX. Alternatively it can be also left blank (in case of non-value TXs)\n* **`TrunkTransaction` / `branchTransaction`:** Those two fields refer to some previous transactions in the Tangle (tips) that the given bundle is going to approve\n* **`Timestamp`:** TX timestamp. It is actually UNIX timestamp (UTC)\n\n\nA process of sending IOTA transaction can be summarized in 5 steps:\n* To create transation(s) with the given attributes: *value*, *address* and potentially also *tag* or *message*\n* To finalize a bundle that includes all transactions. Once the bundle is finalized no new transactions can be added. It basically means to generate a *bundle hash*\n* To search for two tips in the Tangle that you are going to validate. There is not a strict rule how to search them but it is generally recommended to leave it on a *tip selection algorithm* implemented on node's side \n* To do a *Proof-of-Work* for each transaction in the bundle. Result of POW is *Nonce* and *Transaction hash* stored with each transaction\n* Finally you need to *broadcast* the whole bundle to the network\n\n### A secret of a bundle\nThere is a secret to be shared. You have to understand one important thing. Bundle is a top level construct that link all related transactions under one entity however the bundle itself is not broadcasted in fact. You still broadcast \"only\" collection of individual transactions instead. All transactions are recognized to be part of a bundle by the IOTA protocol however any data peering is based on individual transactions (in trytes).\n\nIn other words, a bundle can be reconstructed anytime from a collection of transactions via fields `bundle hash`, `current index` and `last index`.\n\n## Non-value transactions\nLet's start with non-value transactions (meta transactions) first since they are a bit easier for starters.\n\n*Please note, the chapter is divided in two separate sections. In the first section, examples are really close to bare metal (still not too close:) to illustrate the whole process and describing implementation details wherever possible. It is also useful when you want to experiment with different settings at each step (hey \"non-existing tips\", looking at you).*\n\n*In the second section, IOTA-facing libraries are fully levearged since they are capable to hide all implementation details behind a curtain. Needless to say, if you are not interested in such details then you would probably like to start with the second section.*\n\n### Creating and broadcasting transaction in 5 steps (you want to understand the process)\n#### Create a transaction\nFirst of all let's create transactions (offline; in memory) and set main fields.\n\nBTW: `Timestamp` field is defined automatically by the IOTA-facing libraries in the process. It is important field while creating `bundle hash`.\n\nIn the examples within this chapter we are going to broadcast meta transactions (data only) to two different IOTA addresses.\n\n\n```C#\n#r \"Tangle.Net.dll\"\n#r \"Newtonsoft.Json.dll\"\nusing Tangle.Net.Entity;\nusing Newtonsoft.Json;\n\nvar MySeed = \"HGW9HB9LJPYUGVHNGCPLFKKPNZAIIFHZBDHKSGMQKFMANUBASSMSV9TAJSSMPRZZU9SFZULXKJ9YLAIUA\";\nvar TargetAddress1 = \"CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\";\nvar TargetAddress2 = \"CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\";\n\nvar NowIs = DateTime.Now.ToShortDateString(); //this is not important - just to have some meaningful message\n\nvar pt = new Transfer() // creating a first transfer (a proposed transaction)\n{\n    Address=new Address(TargetAddress1),\n    ValueToTransfer=0,\n    Message=TryteString.FromUtf8String(\"Here comes a first message. Now is \" + NowIs),\n    Tag=new Tag(\"HRIBEK999IOTA999TUTORIAL\"),\n    Timestamp = Timestamp.UnixSecondsTimestamp // please note, Tangle.Net library does not enter timestamp for you\n};\n\nvar pt2 = new Transfer() // creating a second transfer (a proposed transaction)\n{\n    Address = new Address(TargetAddress2),\n    ValueToTransfer = 0,\n    Message = TryteString.FromUtf8String(\"Here comes a second message. Now is \" + NowIs),\n    Tag = new Tag(\"HRIBEK999IOTA999TUTORIAL\"),\n    Timestamp = Timestamp.UnixSecondsTimestamp // please note, Tangle.Net library does not enter timestamp for you\n};\n\nConsole.WriteLine(\"Created transaction objects - mandatory fields only:\");\nConsole.WriteLine(JsonConvert.SerializeObject(pt, Formatting.Indented));\nConsole.WriteLine(JsonConvert.SerializeObject(pt2, Formatting.Indented));\n```\n\n\nCreated transaction objects - mandatory fields only:\n\n\n\n{\n  &quot;Address&quot;: {\n    &quot;Balance&quot;: 0,\n    &quot;Checksum&quot;: null,\n    &quot;KeyIndex&quot;: 0,\n    &quot;PrivateKey&quot;: null,\n    &quot;SecurityLevel&quot;: 0,\n    &quot;SpentFrom&quot;: false,\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9&quot;\n  },\n  &quot;Message&quot;: {\n    &quot;TrytesLength&quot;: 88,\n    &quot;Value&quot;: &quot;RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEACBTAVABBTAWAUAVACB&quot;\n  },\n  &quot;Tag&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;HRIBEK999IOTA999TUTORIAL999&quot;\n  },\n  &quot;Timestamp&quot;: 0,\n  &quot;ValueToTransfer&quot;: 0\n}\n\n\n\n{\n  &quot;Address&quot;: {\n    &quot;Balance&quot;: 0,\n    &quot;Checksum&quot;: null,\n    &quot;KeyIndex&quot;: 0,\n    &quot;PrivateKey&quot;: null,\n    &quot;SecurityLevel&quot;: 0,\n    &quot;SpentFrom&quot;: false,\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW&quot;\n  },\n  &quot;Message&quot;: {\n    &quot;TrytesLength&quot;: 90,\n    &quot;Value&quot;: &quot;RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEACBTAVABBTAWAUAVACB&quot;\n  },\n  &quot;Tag&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;HRIBEK999IOTA999TUTORIAL999&quot;\n  },\n  &quot;Timestamp&quot;: 0,\n  &quot;ValueToTransfer&quot;: 0\n}\n\n\n#### Finalizing bundle\nOnce all individual transactions are created it is time to prepare and finalize the bundle. While preparing the bundle you need at least to specify list of prepared transaction(s). In case of non-value transactions it is quite straightforward process. However, it is a bit more complicated in case of value transactions - please see later.\n\nFinalizing the bundle consists of several tasks under the hood:\n* Each transaction is indexed. Attributes `current_index` / `last_index` are set\n* `Bundle hash` is generated (*Sponge function* + normalization) and assigned to each transaction\n* `signatureMessageFragment` is bascially copy of `message` field in case of non-value transactions\n* PyOTA library also checks whether the data in `message` field is larger than transaction allows (2187 trytes). If this is the case then it takes care of it and split your data into several transactions\n\n*Please note, finalizing the bundle also means you are no longer able to add new transactions to the bundle post the finalization process.*\n\nSimply put, `bundle hash` is a cryptographic \"fingerprint\" of all transactions in the bundle. It uniquely represents them and so as long as transactions are the same (incl their particular order) the `bundle hash` is also the same.\n\n$$BundleHash = fce(address, value, legacy tag, timestamp, current index, last index)$$\n\nYou may be wondering what is a difference between `tag` and `legacy_tag`. `Tag` includes actualy the tag that was defined during the transaction creation. `Legacy_tag` is also based on it however it is modified during the normalization process while bundle hashing to be sure that `bundle hash` is can be securely used while TX signing. That's why the `bundle hash` is sometimes refered as `normalized bundle hash`.\n\nThe bundle refers to the first transaction in collection as `tail_transaction`. You can perceive `tail transaction` as an official representative of the whole bundle while checking for confirmation status, etc. Remember, the bundle is an atomic entity and so whatever is done to bundle it applies to ALL transactions within.\n\n\n```C#\n//preparing bundle that consists of both transactions prepared in the previous example\nvar bundle = new Bundle();\n\nbundle.AddTransfer(pt);\nbundle.AddTransfer(pt2);\n\n//generate a bundle hash using sponge/absorb function + normalize bundle hash + copy bundle hash into each transaction / bundle\nbundle.Finalize();\nbundle.Sign();\n\nConsole.WriteLine(\"Generated bundle hash: \" + bundle.Hash.ToString());\nConsole.WriteLine(\"Tail Transaction in the Bundle is a transaction #\" + bundle.TailTransaction.CurrentIndex + \".\");\n\nConsole.WriteLine(\"List of all transactions in the bundle:\");\nConsole.WriteLine(JsonConvert.SerializeObject(bundle.Transactions, Formatting.Indented));\n```\n\n\nGenerated bundle hash: HMCU9CJIIGJLNCJJSYACUYZNFPDREPKLADUU9EHBEZNQUAHWGXJ9BZZHZPBLWXCXBHSLSKSLZZYFLVHZB\n\n\n\nTail Transaction in the Bundle is a transaction #0.\n\n\n\nList of all transactions in the bundle:\n\n\n\n[\n  {\n    &quot;Address&quot;: {\n      &quot;Balance&quot;: 0,\n      &quot;Checksum&quot;: null,\n      &quot;KeyIndex&quot;: 0,\n      &quot;PrivateKey&quot;: null,\n      &quot;SecurityLevel&quot;: 0,\n      &quot;SpentFrom&quot;: false,\n      &quot;TrytesLength&quot;: 81,\n      &quot;Value&quot;: &quot;CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9&quot;\n    },\n    &quot;AttachmentTimestamp&quot;: 999999999,\n    &quot;AttachmentTimestampLowerBound&quot;: 999999999,\n    &quot;AttachmentTimestampUpperBound&quot;: 999999999,\n    &quot;BranchTransaction&quot;: {\n      &quot;TrytesLength&quot;: 81,\n      &quot;Value&quot;: &quot;999999999999999999999999999999999999999999999999999999999999999999999999999999999&quot;\n    },\n    &quot;BundleHash&quot;: {\n      &quot;TrytesLength&quot;: 81,\n      &quot;Value&quot;: &quot;HMCU9CJIIGJLNCJJSYACUYZNFPDREPKLADUU9EHBEZNQUAHWGXJ9BZZHZPBLWXCXBHSLSKSLZZYFLVHZB&quot;\n    },\n    &quot;CurrentIndex&quot;: 0,\n    &quot;Fragment&quot;: {\n      &quot;IsEmpty&quot;: false,\n      &quot;TrytesLength&quot;: 2187,\n      &quot;Value&quot;: &quot;RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEACBTAVABBTAWAUAVACB99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999&quot;\n    },\n    &quot;Hash&quot;: null,\n    &quot;IsTail&quot;: true,\n    &quot;LastIndex&quot;: 1,\n    &quot;Nonce&quot;: {\n      &quot;TrytesLength&quot;: 27,\n      &quot;Value&quot;: &quot;999999999999999999999999999&quot;\n    },\n    &quot;ObsoleteTag&quot;: {\n      &quot;TrytesLength&quot;: 27,\n      &quot;Value&quot;: &quot;LWIBEK999IOTA999TUTORIAL999&quot;\n    },\n    &quot;Tag&quot;: {\n      &quot;TrytesLength&quot;: 27,\n      &quot;Value&quot;: &quot;HRIBEK999IOTA999TUTORIAL999&quot;\n    },\n    &quot;Timestamp&quot;: 0,\n    &quot;TrunkTransaction&quot;: {\n      &quot;TrytesLength&quot;: 81,\n      &quot;Value&quot;: &quot;999999999999999999999999999999999999999999999999999999999999999999999999999999999&quot;\n    },\n    &quot;Value&quot;: 0\n  },\n  {\n    &quot;Address&quot;: {\n      &quot;Balance&quot;: 0,\n      &quot;Checksum&quot;: null,\n      &quot;KeyIndex&quot;: 0,\n      &quot;PrivateKey&quot;: null,\n      &quot;SecurityLevel&quot;: 0,\n      &quot;SpentFrom&quot;: false,\n      &quot;TrytesLength&quot;: 81,\n      &quot;Value&quot;: &quot;CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW&quot;\n    },\n    &quot;AttachmentTimestamp&quot;: 999999999,\n    &quot;AttachmentTimestampLowerBound&quot;: 999999999,\n    &quot;AttachmentTimestampUpperBound&quot;: 999999999,\n    &quot;BranchTransaction&quot;: {\n      &quot;TrytesLength&quot;: 81,\n      &quot;Value&quot;: &quot;999999999999999999999999999999999999999999999999999999999999999999999999999999999&quot;\n    },\n    &quot;BundleHash&quot;: {\n      &quot;TrytesLength&quot;: 81,\n      &quot;Value&quot;: &quot;HMCU9CJIIGJLNCJJSYACUYZNFPDREPKLADUU9EHBEZNQUAHWGXJ9BZZHZPBLWXCXBHSLSKSLZZYFLVHZB&quot;\n    },\n    &quot;CurrentIndex&quot;: 1,\n    &quot;Fragment&quot;: {\n      &quot;IsEmpty&quot;: false,\n      &quot;TrytesLength&quot;: 2187,\n      &quot;Value&quot;: &quot;RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEACBTAVABBTAWAUAVACB999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999&quot;\n    },\n    &quot;Hash&quot;: null,\n    &quot;IsTail&quot;: false,\n    &quot;LastIndex&quot;: 1,\n    &quot;Nonce&quot;: {\n      &quot;TrytesLength&quot;: 27,\n      &quot;Value&quot;: &quot;999999999999999999999999999&quot;\n    },\n    &quot;ObsoleteTag&quot;: {\n      &quot;TrytesLength&quot;: 27,\n      &quot;Value&quot;: &quot;HRIBEK999IOTA999TUTORIAL999&quot;\n    },\n    &quot;Tag&quot;: {\n      &quot;TrytesLength&quot;: 27,\n      &quot;Value&quot;: &quot;HRIBEK999IOTA999TUTORIAL999&quot;\n    },\n    &quot;Timestamp&quot;: 0,\n    &quot;TrunkTransaction&quot;: {\n      &quot;TrytesLength&quot;: 81,\n      &quot;Value&quot;: &quot;999999999999999999999999999999999999999999999999999999999999999999999999999999999&quot;\n    },\n    &quot;Value&quot;: 0\n  }\n]\n\n\nAt this stage you can also see how does our finalized bundle look encoded in Trytes so far. It is also a proof that there is no bundle to be broadcasted itself, only list of transations matter.\n\n\n```C#\nConsole.WriteLine(JsonConvert.SerializeObject(bundle.ToTrytes(), Formatting.Indented)); //bundle as trytes - there is no bundle just transactions\n```\n\n\n[\n  {\n    &quot;TrytesLength&quot;: 2673,\n    &quot;Value&quot;: &quot;RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEACBTAVABBTAWAUAVACB99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9999999999999999999999999999LWIBEK999IOTA999TUTORIAL999999999999999999999A99999999HMCU9CJIIGJLNCJJSYACUYZNFPDREPKLADUU9EHBEZNQUAHWGXJ9BZZHZPBLWXCXBHSLSKSLZZYFLVHZB999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999HRIBEK999IOTA999TUTORIAL9999CGRSPC999CGRSPC999CGRSPC99999999999999999999999999999&quot;\n  },\n  {\n    &quot;TrytesLength&quot;: 2673,\n    &quot;Value&quot;: &quot;RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEACBTAVABBTAWAUAVACB999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW999999999999999999999999999HRIBEK999IOTA999TUTORIAL999999999999A99999999A99999999HMCU9CJIIGJLNCJJSYACUYZNFPDREPKLADUU9EHBEZNQUAHWGXJ9BZZHZPBLWXCXBHSLSKSLZZYFLVHZB999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999HRIBEK999IOTA999TUTORIAL9999CGRSPC999CGRSPC999CGRSPC99999999999999999999999999999&quot;\n  }\n]\n\n\n#### Selecting two tips\nAs mentioned earlier you need to find two tips that you are going to validate together with your bundle for a sake of network participation. This will be outsourced to an IOTA node and so it will be for the first time we interact with the network (via API call `get_transactions_to_approve`).\n\nThere is a `depth` parameter needed. It instructs a node how many milestones it should go in the past while confirming tips. The higher value the better to network however more resources needed. `Depth=3` is considered to be well-balanced compromise. Higher value than `depth=10` will probably throw an exception depending on node's configuration.\n\nIt should return two selected tips as `branch` and `trunk` transactions. Those transactions will be used while broadcasting the bundle.\n\n\n```C#\n#r \"RestSharp.dll\"\nusing RestSharp;\nusing Tangle.Net.Repository;\n\nvar NodeURL = \"https://nodes.thetangle.org:443\";\nvar repo = new RestIotaRepository(new RestClient(NodeURL)); // ctor initialization of the Tangle.Net library\n\nvar gta = repo.GetTransactionsToApprove(3);\nConsole.WriteLine(JsonConvert.SerializeObject(gta, Formatting.Indented));\n```\n\n\n{\n  &quot;BranchTransaction&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;KAIQDBQEOHPOQELQZXIMICACCRPHGAZCZAUAUKZVSRZLKUD9BBKKAMNNBGUTQTKLVMLGGO9ZZLWKA9999&quot;\n  },\n  &quot;Duration&quot;: 190,\n  &quot;TrunkTransaction&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;AZYDOXZLYNILMCSCWBXRPNNXWFZGTHOVSEQBYMKEXBZZRKWTPHSWPZCERVSPHUXPXAEGEILXITVA99999&quot;\n  }\n}\n\n\n#### Performin' POW\n*Proof of work* is a relatively simple cryptograhic puzzle to be solved. It represents energy-based costs of your transaction. It also helps to minimize risks of some attack vectors to the network.\n\nThis task can be also outsourced to IOTA nodes. In order to perform it you need *selected tips*, *finalized bundle* (in trytes) and also `Minimum Weight Magnitude` parameter. This parameter defines how diffciult the given cryptographic puzzle should be to be accepted by the network. As of now, you should set at least `min_weight_magnitude=14` in case of mainnet.\n\nPlease note, POW is performed per each transaction and so it can take some time. That's why it is not recommended to have more than 30 transactions in a bundle.\n\nOnce succesfully performed, the modified bundle (list of all transactions in trytes) is returned in order to be broadcasted.\n\nSpecifically:\n* Fields `nonce` and `transaction hash` are calculated per each transaction\n* `Trunk` and `Branch` tips are correctly mapped among transactions within the bundle. Check that `trunk` of the first TX refers to the second TX, etc.\n\n\n```C#\nConsole.WriteLine(\"Performing POW... Wait please...\");\nvar att = repo.AttachToTangle(branchTransaction: gta.BranchTransaction, //first tip selected\n                              trunkTransaction: gta.TrunkTransaction, //second tip selected\n                              transactions: bundle.Transactions, //our finalized transactions\n                              minWeightMagnitude: 14); // MWMN\n\nConsole.WriteLine(JsonConvert.SerializeObject(att, Formatting.Indented));\n```\n\n\nPerforming POW... Wait please...\n\n\n\n[\n  {\n    &quot;TrytesLength&quot;: 2673,\n    &quot;Value&quot;: &quot;RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEACBTAVABBTAWAUAVACB999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW999999999999999999999999999HRIBEK999IOTA999TUTORIAL999999999999A99999999A99999999HMCU9CJIIGJLNCJJSYACUYZNFPDREPKLADUU9EHBEZNQUAHWGXJ9BZZHZPBLWXCXBHSLSKSLZZYFLVHZBAZYDOXZLYNILMCSCWBXRPNNXWFZGTHOVSEQBYMKEXBZZRKWTPHSWPZCERVSPHUXPXAEGEILXITVA99999KAIQDBQEOHPOQELQZXIMICACCRPHGAZCZAUAUKZVSRZLKUD9BBKKAMNNBGUTQTKLVMLGGO9ZZLWKA9999HRIBEK999IOTA999TUTORIAL99999RERKZOF999999999MMMMMMMMMNYHCWZKAFTLDYXZGUXQN9CGWORG&quot;\n  },\n  {\n    &quot;TrytesLength&quot;: 2673,\n    &quot;Value&quot;: &quot;RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEACBTAVABBTAWAUAVACB99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9999999999999999999999999999LWIBEK999IOTA999TUTORIAL999999999999999999999A99999999HMCU9CJIIGJLNCJJSYACUYZNFPDREPKLADUU9EHBEZNQUAHWGXJ9BZZHZPBLWXCXBHSLSKSLZZYFLVHZBOYHIDWXOYTIDSLXUYVPTYJSYSUYGME9OWRFNKISZGENKAJWCAQTDRJXFCJKXBBNHROIGZBNYRXSY99999AZYDOXZLYNILMCSCWBXRPNNXWFZGTHOVSEQBYMKEXBZZRKWTPHSWPZCERVSPHUXPXAEGEILXITVA99999HRIBEK999IOTA999TUTORIAL999BSWERKZOF999999999MMMMMMMMMNXO9XFRKWJIPJOGSREFDHPHRIJQ&quot;\n  }\n]\n\n\nYou can eventually also preview what specific fields have been modified using transaction objects. The bundle is ready to be broadcasted and so it also show you all fields/values that will be stored in the network.\n\n\n```C#\n// show what has been broadcasted - hash transaction + nonce (POW)\n\nConsole.WriteLine(\"Final bundle including POW and branch/trunk transactions:\");\n\nforeach (var tr in att)\n{\n    Console.WriteLine(JsonConvert.SerializeObject(Transaction.FromTrytes(tr), Formatting.Indented));\n}\n```\n\n\nFinal bundle including POW and branch/trunk transactions:\n\n\n\n{\n  &quot;Address&quot;: {\n    &quot;Balance&quot;: 0,\n    &quot;Checksum&quot;: null,\n    &quot;KeyIndex&quot;: 0,\n    &quot;PrivateKey&quot;: null,\n    &quot;SecurityLevel&quot;: 0,\n    &quot;SpentFrom&quot;: false,\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW&quot;\n  },\n  &quot;AttachmentTimestamp&quot;: 1568818706823,\n  &quot;AttachmentTimestampLowerBound&quot;: 0,\n  &quot;AttachmentTimestampUpperBound&quot;: 3812798742493,\n  &quot;BranchTransaction&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;KAIQDBQEOHPOQELQZXIMICACCRPHGAZCZAUAUKZVSRZLKUD9BBKKAMNNBGUTQTKLVMLGGO9ZZLWKA9999&quot;\n  },\n  &quot;BundleHash&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;HMCU9CJIIGJLNCJJSYACUYZNFPDREPKLADUU9EHBEZNQUAHWGXJ9BZZHZPBLWXCXBHSLSKSLZZYFLVHZB&quot;\n  },\n  &quot;CurrentIndex&quot;: 1,\n  &quot;Fragment&quot;: {\n    &quot;IsEmpty&quot;: false,\n    &quot;TrytesLength&quot;: 2187,\n    &quot;Value&quot;: &quot;RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEACBTAVABBTAWAUAVACB999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999&quot;\n  },\n  &quot;Hash&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;OYHIDWXOYTIDSLXUYVPTYJSYSUYGME9OWRFNKISZGENKAJWCAQTDRJXFCJKXBBNHROIGZBNYRXSY99999&quot;\n  },\n  &quot;IsTail&quot;: false,\n  &quot;LastIndex&quot;: 1,\n  &quot;Nonce&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;NYHCWZKAFTLDYXZGUXQN9CGWORG&quot;\n  },\n  &quot;ObsoleteTag&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;HRIBEK999IOTA999TUTORIAL999&quot;\n  },\n  &quot;Tag&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;HRIBEK999IOTA999TUTORIAL999&quot;\n  },\n  &quot;Timestamp&quot;: 0,\n  &quot;TrunkTransaction&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;AZYDOXZLYNILMCSCWBXRPNNXWFZGTHOVSEQBYMKEXBZZRKWTPHSWPZCERVSPHUXPXAEGEILXITVA99999&quot;\n  },\n  &quot;Value&quot;: 0\n}\n\n\n\n{\n  &quot;Address&quot;: {\n    &quot;Balance&quot;: 0,\n    &quot;Checksum&quot;: null,\n    &quot;KeyIndex&quot;: 0,\n    &quot;PrivateKey&quot;: null,\n    &quot;SecurityLevel&quot;: 0,\n    &quot;SpentFrom&quot;: false,\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9&quot;\n  },\n  &quot;AttachmentTimestamp&quot;: 1568818710254,\n  &quot;AttachmentTimestampLowerBound&quot;: 0,\n  &quot;AttachmentTimestampUpperBound&quot;: 3812798742493,\n  &quot;BranchTransaction&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;AZYDOXZLYNILMCSCWBXRPNNXWFZGTHOVSEQBYMKEXBZZRKWTPHSWPZCERVSPHUXPXAEGEILXITVA99999&quot;\n  },\n  &quot;BundleHash&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;HMCU9CJIIGJLNCJJSYACUYZNFPDREPKLADUU9EHBEZNQUAHWGXJ9BZZHZPBLWXCXBHSLSKSLZZYFLVHZB&quot;\n  },\n  &quot;CurrentIndex&quot;: 0,\n  &quot;Fragment&quot;: {\n    &quot;IsEmpty&quot;: false,\n    &quot;TrytesLength&quot;: 2187,\n    &quot;Value&quot;: &quot;RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEACBTAVABBTAWAUAVACB99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999&quot;\n  },\n  &quot;Hash&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;RBE9XKMLBBTXFTNANSTOTW9VHWSAZJM9FBCALBQESWTOKURWQEAJUJEKQJXUOOSAIDXABSOJXMBB99999&quot;\n  },\n  &quot;IsTail&quot;: true,\n  &quot;LastIndex&quot;: 1,\n  &quot;Nonce&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;NXO9XFRKWJIPJOGSREFDHPHRIJQ&quot;\n  },\n  &quot;ObsoleteTag&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;LWIBEK999IOTA999TUTORIAL999&quot;\n  },\n  &quot;Tag&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;HRIBEK999IOTA999TUTORIAL999&quot;\n  },\n  &quot;Timestamp&quot;: 0,\n  &quot;TrunkTransaction&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;OYHIDWXOYTIDSLXUYVPTYJSYSUYGME9OWRFNKISZGENKAJWCAQTDRJXFCJKXBBNHROIGZBNYRXSY99999&quot;\n  },\n  &quot;Value&quot;: 0\n}\n\n\n#### Broadcasting\nNow it is time to broadcast the given bundle to the network. List of all transations in trytes returned from the previous step is only thing needed.\n\nOnce succesfully broadcasted it returns the same input bundle as a confirmation.\n\n\n```C#\nConsole.WriteLine(\"Broadcasting transactions...\");\nrepo.BroadcastAndStoreTransactions(att);\nConsole.WriteLine(\"Broadcasted.\");      \n```\n\n\nBroadcasting transactions...\n\n\n\nBroadcasted.\n\n\nYou can check the broadcasted bundle via The Tangle Explorer at any of the receiving addresses:\n* Target address 1: https://thetangle.org/address/CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\n* Target address 2: \nhttps://thetangle.org/address/CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\n\n### Creating and broadcasting transaction in a single call (you want send a transaction quickly)\nAs mentioned above, IOTA-facing libraries are able to encapsulate all implementation details and so you do not need to care of them anymore. It is usually based on *extended API calls* that were proposed to be included by IOTA Foundation to make developer's life easier (https://github.com/iotaledger/wiki/blob/master/api-proposal.md).\n\nEven if using extended API calls you can still slightly control a level of your involvement in the whole process. From almost no involvement and fully automatic (`send_transfer()`) to semi-manual approach discussed above.\n\n\n\nThere are some specifics you should consider while designing your app:\n* You are loosing a bit of control of individual steps of the process and you have to rely of some predefined parameters (tip selection algo, etc.)\n* If there is an exception raised during the process then you need to go back at beginning and restart the whole process again\n\nSo it is basically your call to decide what works best for you.\n\nNow back to our exercise. Here comes a code that basically broadcasts transactions in a single call (`send_transfer()`) and you do not have to care of any implemenation details that are hidden under the hood.\n\n\n```C#\n#r \"Tangle.Net.dll\"\n#r \"Newtonsoft.Json.dll\"\n#r \"RestSharp.dll\"\n\nusing Tangle.Net.Entity;\nusing Newtonsoft.Json;\nusing RestSharp;\nusing Tangle.Net.Repository;\nusing Tangle.Net.Utils; //this is needed because of Timestamp function\n\n\nvar MySeed = \"HGW9HB9LJPYUGVHNGCPLFKKPNZAIIFHZBDHKSGMQKFMANUBASSMSV9TAJSSMPRZZU9SFZULXKJ9YLAIUA\";\nvar TargetAddress1 = \"CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\";\nvar TargetAddress2 = \"CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\";\n\nvar NowIs = DateTime.Now.ToShortDateString(); //this is not important - just to have some meaningful message\n\nvar pt = new Transfer() // creating a first transfer (a proposed transaction)\n{\n    Address=new Address(TargetAddress1),\n    ValueToTransfer=0,\n    Message=TryteString.FromUtf8String(\"Here comes a first message. Now is \" + NowIs),\n    Tag=new Tag(\"HRIBEK999IOTA999TUTORIAL\"),\n    Timestamp = Timestamp.UnixSecondsTimestamp // please note, Tangle.Net library does not enter timestamp for you but it is very important since it has impact on bundle hash\n};\n\nvar pt2 = new Transfer() // creating a second transfer (a proposed transaction)\n{\n    Address = new Address(TargetAddress2),\n    ValueToTransfer = 0,\n    Message = TryteString.FromUtf8String(\"Here comes a second message. Now is \" + NowIs),\n    Tag = new Tag(\"HRIBEK999IOTA999TUTORIAL\"),\n    Timestamp = Timestamp.UnixSecondsTimestamp // please note, Tangle.Net library does not enter timestamp for you but it is very important since it has impact on bundle hash\n};\n\nConsole.WriteLine(\"Preparing/Broadcasting... Wait please...\");\nvar bundle = new Bundle();\nbundle.AddTransfer(pt);\nbundle.AddTransfer(pt2);\n\nvar NodeURL = \"https://nodes.thetangle.org:443\";\nvar repo = new RestIotaRepository(new RestClient(NodeURL)); // ctor initialization of the Tangle.Net library\n\n// the whole process initiated in a single call\nvar sentBundle = repo.SendTransfer(seed: new Seed(MySeed),\n                                   bundle: bundle,\n                                   securityLevel: 2,\n                                   depth: 3,\n                                   minWeightMagnitude: 14); //it returns a bundle object\n\nConsole.WriteLine(\"Generated bundle hash: \" + sentBundle.Hash.ToString());\nConsole.WriteLine(\"Tail Transaction in the Bundle is a transaction #\" + sentBundle.TailTransaction.CurrentIndex + \".\");\n\nConsole.WriteLine(\"List of all transactions in the bundle:\");\nforeach (var tx in sentBundle.Transactions)\n{\n    Console.WriteLine(JsonConvert.SerializeObject(tx, Formatting.Indented));\n}\n```\n\n\nPreparing/Broadcasting... Wait please...\n\n\n\nGenerated bundle hash: MJZPGDLCDKOIWFTNKJJZUC9STN9RGXWC9EBRWKBGOCLIGRZCJQEUYUARGPDCFUJXIHI9UKDDVXKBZVFD9\n\n\n\nTail Transaction in the Bundle is a transaction #0.\n\n\n\nList of all transactions in the bundle:\n\n\n\n{\n  &quot;Address&quot;: {\n    &quot;Balance&quot;: 0,\n    &quot;Checksum&quot;: null,\n    &quot;KeyIndex&quot;: 0,\n    &quot;PrivateKey&quot;: null,\n    &quot;SecurityLevel&quot;: 0,\n    &quot;SpentFrom&quot;: false,\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9&quot;\n  },\n  &quot;AttachmentTimestamp&quot;: 1568832066884,\n  &quot;AttachmentTimestampLowerBound&quot;: 0,\n  &quot;AttachmentTimestampUpperBound&quot;: 3812798742493,\n  &quot;BranchTransaction&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;WYLFSDUXVFRYYPDH9GOCHKLASCXTPAFUMAC9JKMPAXZIOZVGCJ9LARVDFFJPCTAXLBIYSSZEYKNHA9999&quot;\n  },\n  &quot;BundleHash&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;MJZPGDLCDKOIWFTNKJJZUC9STN9RGXWC9EBRWKBGOCLIGRZCJQEUYUARGPDCFUJXIHI9UKDDVXKBZVFD9&quot;\n  },\n  &quot;CurrentIndex&quot;: 0,\n  &quot;Fragment&quot;: {\n    &quot;IsEmpty&quot;: false,\n    &quot;TrytesLength&quot;: 2187,\n    &quot;Value&quot;: &quot;RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEACBTAVABBTAWAUAVACB99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999&quot;\n  },\n  &quot;Hash&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;PUM9YUXZWH9TZQKEUKIBIBVAIPWXNGIUEKBQHLM9PRHGGOJPTASEKHMXHHMK9EBXZSJOPXYQUIHRZ9999&quot;\n  },\n  &quot;IsTail&quot;: true,\n  &quot;LastIndex&quot;: 1,\n  &quot;Nonce&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;BSVCUUWALVPHMHXBINNMXAEJ9VA&quot;\n  },\n  &quot;ObsoleteTag&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;ODIBEK999IOTA999TUTORIAL999&quot;\n  },\n  &quot;Tag&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;HRIBEK999IOTA999TUTORIAL999&quot;\n  },\n  &quot;Timestamp&quot;: 1568832063,\n  &quot;TrunkTransaction&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;YBJB9C9T9CFSKTLMHKOMHDRNT9MZTPNZIHTJ9DMNDJSYECMGLAGIIY9RH9PNSTPJXMHUIUCPVLLYZ9999&quot;\n  },\n  &quot;Value&quot;: 0\n}\n\n\n\n{\n  &quot;Address&quot;: {\n    &quot;Balance&quot;: 0,\n    &quot;Checksum&quot;: null,\n    &quot;KeyIndex&quot;: 0,\n    &quot;PrivateKey&quot;: null,\n    &quot;SecurityLevel&quot;: 0,\n    &quot;SpentFrom&quot;: false,\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW&quot;\n  },\n  &quot;AttachmentTimestamp&quot;: 1568832066523,\n  &quot;AttachmentTimestampLowerBound&quot;: 0,\n  &quot;AttachmentTimestampUpperBound&quot;: 3812798742493,\n  &quot;BranchTransaction&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;WYLFSDUXVFRYYPDH9GOCHKLASCXTPAFUMAC9JKMPAXZIOZVGCJ9LARVDFFJPCTAXLBIYSSZEYKNHA9999&quot;\n  },\n  &quot;BundleHash&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;MJZPGDLCDKOIWFTNKJJZUC9STN9RGXWC9EBRWKBGOCLIGRZCJQEUYUARGPDCFUJXIHI9UKDDVXKBZVFD9&quot;\n  },\n  &quot;CurrentIndex&quot;: 1,\n  &quot;Fragment&quot;: {\n    &quot;IsEmpty&quot;: false,\n    &quot;TrytesLength&quot;: 2187,\n    &quot;Value&quot;: &quot;RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEACBTAVABBTAWAUAVACB999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999&quot;\n  },\n  &quot;Hash&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;YBJB9C9T9CFSKTLMHKOMHDRNT9MZTPNZIHTJ9DMNDJSYECMGLAGIIY9RH9PNSTPJXMHUIUCPVLLYZ9999&quot;\n  },\n  &quot;IsTail&quot;: false,\n  &quot;LastIndex&quot;: 1,\n  &quot;Nonce&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;GFSZAC9PCWNJNNWDLG9WZKTAVJX&quot;\n  },\n  &quot;ObsoleteTag&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;HRIBEK999IOTA999TUTORIAL999&quot;\n  },\n  &quot;Tag&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;HRIBEK999IOTA999TUTORIAL999&quot;\n  },\n  &quot;Timestamp&quot;: 1568832063,\n  &quot;TrunkTransaction&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;WYLFSDUXVFRYYPDH9GOCHKLASCXTPAFUMAC9JKMPAXZIOZVGCJ9LARVDFFJPCTAXLBIYSSZEYKNHA9999&quot;\n  },\n  &quot;Value&quot;: 0\n}\n\n\nYou can check the broadcasted bundle via The Tangle Explorer at any of the receiving addresses:\n* Target address 1: https://thetangle.org/address/CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\n* Target address 2: \nhttps://thetangle.org/address/CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\n\nAnd to complete the picture here is addtional code that uses `prepare_transfer()` and `send_trytes()` combo.\n\n\n```C#\n#r \"Tangle.Net.dll\"\n#r \"Newtonsoft.Json.dll\"\n#r \"RestSharp.dll\"\n\nusing Tangle.Net.Entity;\nusing Newtonsoft.Json;\nusing RestSharp;\nusing Tangle.Net.Repository;\nusing Tangle.Net.Utils;\n\nvar MySeed = \"HGW9HB9LJPYUGVHNGCPLFKKPNZAIIFHZBDHKSGMQKFMANUBASSMSV9TAJSSMPRZZU9SFZULXKJ9YLAIUA\";\nvar TargetAddress1 = \"CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\";\nvar TargetAddress2 = \"CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\";\n\nvar NowIs = DateTime.Now.ToShortDateString(); //this is not important - just to have some meaningful message\n\nvar pt = new Transfer() // creating a first transfer (a proposed transaction)\n{\n    Address=new Address(TargetAddress1),\n    ValueToTransfer=0,\n    Message=TryteString.FromUtf8String(\"Here comes a first message. Now is \" + NowIs),\n    Tag=new Tag(\"HRIBEK999IOTA999TUTORIAL\"),\n    Timestamp = Timestamp.UnixSecondsTimestamp // please note, Tangle.Net library does not enter timestamp for you but it is very important since it has impact on bundle hash\n};\n\nvar pt2 = new Transfer() // creating a second transfer (a proposed transaction)\n{\n    Address = new Address(TargetAddress2),\n    ValueToTransfer = 0,\n    Message = TryteString.FromUtf8String(\"Here comes a second message. Now is \" + NowIs),\n    Tag = new Tag(\"HRIBEK999IOTA999TUTORIAL\"),\n    Timestamp = Timestamp.UnixSecondsTimestamp // please note, Tangle.Net library does not enter timestamp for you but it is very important since it has impact on bundle hash\n};\n\nvar bundle = new Bundle();\nbundle.AddTransfer(pt);\nbundle.AddTransfer(pt2);\n\nvar NodeURL = \"https://nodes.thetangle.org:443\";\nvar repo = new RestIotaRepository(new RestClient(NodeURL)); // ctor initialization of the Tangle.Net library\n\nConsole.WriteLine(\"Almost prepared bundle - tips and POW are still missing\");\n\nvar preparedBundle = repo.PrepareTransfer(seed: new Seed(MySeed),\n                                          bundle: bundle,\n                                          securityLevel: 2); // please note, depth and MNWM are not needed since neither GTTA nor ATT is performed\nforeach (var tx in preparedBundle.ToTrytes())\n{\n    Console.WriteLine(tx.ToString());\n}\n\nConsole.WriteLine(\"Searching for tips and performing POW... Wait please...\");\nvar sentBundle = repo.SendTrytes(transactions: preparedBundle.Transactions,\n                                 depth: 3,\n                                 minWeightMagnitude: 14);\n\nConsole.WriteLine(\"Bundle was broadcasted.\");\nConsole.WriteLine(\"Final transactions were returned - including nonce(POW)\");\nforeach (var tx in sentBundle)\n{\n    Console.WriteLine(tx.ToString());\n}\n\n```\n\n\nAlmost prepared bundle - tips and POW are still missing\n\n\n\nRBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEACBTAVABBTAWAUAVACB99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9999999999999999999999999999Z9IBEK999IOTA999TUTORIAL9999KAAIAD99999999999A99999999MJCVGAPSTFRW99JCEBCWHGFXWCZCLTVPWJD9QKYEZX9UIZSIJXTHDBAQFJ9ANVAUOEDY9GIAHBCECJYGX999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999HRIBEK999IOTA999TUTORIAL9999CGRSPC999CGRSPC999CGRSPC99999999999999999999999999999\n\n\n\nRBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEACBTAVABBTAWAUAVACB999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW999999999999999999999999999HRIBEK999IOTA999TUTORIAL9999KAAIAD99A99999999A99999999MJCVGAPSTFRW99JCEBCWHGFXWCZCLTVPWJD9QKYEZX9UIZSIJXTHDBAQFJ9ANVAUOEDY9GIAHBCECJYGX999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999HRIBEK999IOTA999TUTORIAL9999CGRSPC999CGRSPC999CGRSPC99999999999999999999999999999\n\n\n\nSearching for tips and performing POW... Wait please...\n\n\n\nBundle was broadcasted.\n\n\n\nFinal transactions were returned - including nonce(POW)\n\n\n\nRBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEACBTAVABBTAWAUAVACB999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW999999999999999999999999999HRIBEK999IOTA999TUTORIAL9999KAAIAD99A99999999A99999999MJCVGAPSTFRW99JCEBCWHGFXWCZCLTVPWJD9QKYEZX9UIZSIJXTHDBAQFJ9ANVAUOEDY9GIAHBCECJYGXJVEXQTEBULMLJQJCBASUKVGWTANPOOXNQJDWEGMZQKCHCFPXTGRYPWFFETSDYWUIQMNQUSCIQCTFZ9999NGUCOMI9ZIUNMDODGKUP9WHKXN9ECNDRMRKQKMFFNWMVXBUEUS9LJCUYHZZFJD9LEHDBFPMQJHFP99999HRIBEK999IOTA999TUTORIAL999BJIZULZOF999999999MMMMMMMMMBQFMPJJQWUGGIJWJTJQCEJU9BU9\n\n\n\nRBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEACBTAVABBTAWAUAVACB99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9999999999999999999999999999Z9IBEK999IOTA999TUTORIAL9999KAAIAD99999999999A99999999MJCVGAPSTFRW99JCEBCWHGFXWCZCLTVPWJD9QKYEZX9UIZSIJXTHDBAQFJ9ANVAUOEDY9GIAHBCECJYGXEWFEQDYZHSSPGBLOC9XVFBVTIAKLRNNUGHATPCQRQVAXYQHXXIJDZLBXLASF9ZI9SIDUDNJTJ9PWZ9999JVEXQTEBULMLJQJCBASUKVGWTANPOOXNQJDWEGMZQKCHCFPXTGRYPWFFETSDYWUIQMNQUSCIQCTFZ9999HRIBEK999IOTA999TUTORIAL999R9MZULZOF999999999MMMMMMMMMBWSRMLGBWQCDYRPQIXVNLYQYUZR\n\n\nYou can check the broadcasted bundle via The Tangle Explorer at any of the receiving addresses:\n* Target address 1: https://thetangle.org/address/CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\n* Target address 2: \nhttps://thetangle.org/address/CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\n\n## Value transactions\nMeta transactions were discussed in the previous chapter. This chapter describes `value transactions` which are transactions that transfer IOTA tokens between IOTA addresses. Tokens are fully premined and so number of tokens in the network is given. So `transfering tokens` means changing their ownership only.\n\nWhile preparing a bundle with `value transations` it is important to distinguish three different transaction types within a bundle:\n* **Input TXs:** those are transactions that *deducting* (spending) value from address(es). Those transactions have negative `value` field. They usually refer to `senders`\n* **Output TXs:** those are transactions that *adding* (receiving) value to address(es). Those transactions have positive `value` field. They usually refer to `recipients`\n* **Unspent/change TX:** technically speaking it is also *output* transaction that *adding* value however it usually refers to `senders` and so it is better to consider it separated from other output TXs\n\nAll three types have to be part of each bundle otherwise you are under a risk of loosing IOTA tokens. In other words, each bundle should consists of at least one `input` TX, one `output` TX and one `unspent` TX. Total balance of the bundle should be zero since the number of tokens is the same, just token owners have been \"changed\".\n\nExample:\n* Alice owns 100 tokens (*input = 100*)\n* Alice is going to send 20 tokens to John from the address that includes 100 tokens of her (*Alice -100*)\n* John is going to receive 20 tokens from Alice (*output = 20*; *John +20*)\n* Alice still owns 80 tokens after the transaction (*unspent = 80*; *Alice +80*)\n\nAlice's bundle should look like:\n\\begin{align}\nInput - Output & = \\ Unspent \\\\\nInput - Output - Unspent & = \\ 0 \\\\\n100 - 20 - 80 & = \\ 0\n\\end{align}\n\nWhy Alice has to \"put\" all 100 tokens in the bundle while she is going to actually spend only 20 tokens? The reason is that IOTA protocol uses one-time signature scheme (OTS) for transaction signing while spending tokens. And with every signing process a half of a private key of the given address is revealed. That's why no one should ever spend tokens from the same address again.\n\n\n### Spending tokens\n*Please note: for a purpose of this chapter we are going to switch to a test network called `devnet`. It is the testing Tangle. Tokens are not real and everything you do have no implication to the mainnet at all. However it is stil powered by standard node software and so technicaly speaking it behaves like the mainnet. If you need more info regarding devnet please refer to [the official documentation](https://docs.iota.org/introduction/testnet/introduction).*\n\nEverything what has been mentioned in the previous chapter focused on `non-value` transations is still valid also in case of value transactions however there are several additional tasks you should take care of. Needless to say, IOTA libraries (PyOTA and others) are ready to help you and are able to hide all implementation details in case you would like to. In this case I would encourage everyone to prefer a functionality that is offered by extended API calls, such as `send_transfer`. Experimenting with value transactions and trying to tweak them does not seem to be a good idea (on the mainnet).\n\nAnyway, even in this chapter I am going to describe main tasks that are performed under the hood to be able to understand the whole concept.\n\nLet's have the following setup:\n\n\n```C#\n// Sender's side\n// Sender seed\nvar SeedSender = \"HGW9HB9LJPYUGVHNGCPLFKKPNZAIIFHZBDHKSGMQKFMANUBASSMSV9TAJSSMPRZZU9SFZULXKJ9YLAIUA\";\n\n// Receiver's side\n// Recipient's seed - this is actually not needed for the exercise - it is just to have corresponding seed somewhere written\nvar SeedReceiver = \"NVPDKGLESTYNJEH9DTWD9DUBYWHZJDDWTBLKWEYLVZKBKKAZTIZ9CFFJMHPEKIFUWQTXRGAVRXAQZCPHL\";\n\n//This is our target address to which we are going to send tokens to (BTW: it is a first generated address based on recipient's seed)\nvar AddressReceiver = \"BMFSMZMNBGKHAWPIZIOMJGRBXZETVSAYDSTDQCHLYTBWZMIXLNXF9XHLTMOCATFVFOMBQF9IOQGPEBPDC\";\n\n\nvar DevnetNode = \"https://nodes.devnet.iota.org:443\";\nConsole.WriteLine(\"Variables were initialized.\");\n```\n\n\nVariables were initialized.\n\n\nYou may be wondering why only the seed for sender's side is defined. As mentioned above the reason is that the address with tokens is changing with every spending exercise and so you have to find address with tokens that left in a bucket programatically (if any tokens left:).\n\nLet's find out. For this purpose you can use extended API call `get_account_data` which returns a list of used addresses and total sum of all tokens available accross all of them:\n\n\n```C#\n#r \"Tangle.Net.dll\"\n#r \"Newtonsoft.Json.dll\"\n#r \"RestSharp.dll\"\n\nusing Tangle.Net.Entity;\nusing Newtonsoft.Json;\nusing RestSharp;\nusing Tangle.Net.Repository;\nusing Tangle.Net.Utils;\n\nConsole.WriteLine(\"Checking the total balance\");\nConsole.WriteLine(\"Please note, this may take some time if many addresses has been used already...\");\n\nvar repo = new RestIotaRepository(new RestClient(DevnetNode)); // ctor initialization of the Tangle.Net library\n\n// Get the total available balance for the given seed and all related used addresses\nvar accountData = repo.GetAccountData(seed: new Seed(SeedSender),\n                                      includeInclusionStates: false,\n                                      securityLevel: 2,\n                                      addressStartIndex: 29, // Library will start from the address at index 0. please note I increased it to start from index 29 to save time\n                                      addressStopIndex: 0); // it will search until first unused address is found\n\n// Tangle.Net library returns very detailed info including Private Keys and so outputing only some\nConsole.WriteLine(\"Total Balance:\");\nConsole.WriteLine(JsonConvert.SerializeObject(accountData.Balance, Formatting.Indented));\n\nConsole.WriteLine(\"Latest Unused Address:\");\nConsole.WriteLine(JsonConvert.SerializeObject(accountData.LatestUnusedAddress.Value, Formatting.Indented));\n\nConsole.WriteLine(\"Used Addresses:\");\nConsole.WriteLine(JsonConvert.SerializeObject((from adr in accountData.UsedAddresses\n                                               select new {Balance = adr.Balance, Address = adr.Value}).ToList(),\n                                              Formatting.Indented));\n\nif (accountData.Balance>0){\n    Console.WriteLine(\"Yes, there are some token available! Hurray\");\n}\n```\n\n\nChecking the total balance\n\n\n\nPlease note, this may take some time if many addresses has been used already...\n\n\n\nTotal Balance:\n\n\n\n3828\n\n\n\nLatest Unused Address:\n\n\n\n&quot;MHJIRKPUVSXBZWUXKUBNT9MRSEG9CRR9DNKIVNSCBZVGEDIDYTXIAVJLSTKQGVGDBFHRCRHBEMMZXPUFZ&quot;\n\n\n\nUsed Addresses:\n\n\n\n[\n  {\n    &quot;Balance&quot;: 0,\n    &quot;Address&quot;: &quot;SUYDJCMS9XMBKOPIPOXKGXMFVYXQ9YRNZLDYLRFARZFOFJDDH9JZLCQVO9GBRQKBCXHSPHOAPPWFFLMBW&quot;\n  },\n  {\n    &quot;Balance&quot;: 0,\n    &quot;Address&quot;: &quot;NHVGPRAXYTDZJLMLSUMZGVBBMICDQGGAAZ9UJGLIPPOTUEZJXABCSDFUTRTBFOLDOQZIBS9QTRXAB9IUX&quot;\n  },\n  {\n    &quot;Balance&quot;: 0,\n    &quot;Address&quot;: &quot;VZITIWJF99TH9REMKLYZUWELFLEW9FVYXPZPVMVFZVIQHAOEMEDABUUZGFROKKIVMT999PWGGLICKJOAD&quot;\n  },\n  {\n    &quot;Balance&quot;: 0,\n    &quot;Address&quot;: &quot;XPV9CTUC9JEKATOVABXXLICTDAQEOHR9HXXFLHKN9OZFMFAZKKUDZMREOBZJONZAHXCGNN9FHGNFBAKMC&quot;\n  },\n  {\n    &quot;Balance&quot;: 0,\n    &quot;Address&quot;: &quot;NDQMBGBQIBAQURVAQEUVONVMECKXSNYZZNKMMMOHOLPEYHJHDBTFWOZMAPFUAHLHIQUAV9GVZPEMBKL9Z&quot;\n  },\n  {\n    &quot;Balance&quot;: 2979,\n    &quot;Address&quot;: &quot;QYENROHVANIYBSIIMWGFDOUHXTMFOXIHOQXTJZLRFRJMOOINFTWCVVEJUFIITLBIHLVTESPVLUOSCFJDZ&quot;\n  },\n  {\n    &quot;Balance&quot;: 849,\n    &quot;Address&quot;: &quot;SZAVDSKTHNQFWTTINRAYQKJAXTLD9CRFFWWBSEXIEXPLBBEP9FT9IVGICWIXTJCFUKJSTOUFANJGBTPQX&quot;\n  }\n]\n\n\n\nYes, there are some token available! Hurray\n\n\n*Please note: API call `get_account_data` consider only confirmed transactions while calculating total balance. So it is better to wait until all transactions are cleared before you send additional tokens.*\n\nAre there any tokens left (value in `balance` field)? If yes then continue - no action is needed.\nIf not, then you need to obtain some. It can be done visiting [IOTA faucet](http://faucet.devnet.iota.org) and entering an unused address of the given seed:\n\n\n```C#\n// Now let's find a first unused address that can be used as a destination address for unspent/new tokens\n// This step is not required in case of NodeJS/Tangle.Net library, please see result above\nConsole.WriteLine(\"Please note, this may take some time if many addresses has been used already...\");\n\nvar unusedAdr = repo.GetNewAddresses(seed: new Seed(SeedSender),\n                                     addressStartIndex: 29, // please note the index below starts from 29 to save some time. If you would like to start from beginning it should be 0 \n                                     count: 1, // how many new unused addresses we want ?\n                                     securityLevel: 2);\n\nConsole.WriteLine(\"This is the first unused address that can be used for new tokens or unspent tokens:\");\nConsole.WriteLine(unusedAdr[0].Value);\n\n\n```\n\n\nPlease note, this may take some time if many addresses has been used already...\n\n\n\nThis is the first unused address that can be used for new tokens or unspent tokens:\n\n\n\nSZAVDSKTHNQFWTTINRAYQKJAXTLD9CRFFWWBSEXIEXPLBBEP9FT9IVGICWIXTJCFUKJSTOUFANJGBTPQX\n\n\nWhat have just happened behind the curtain?\n* The PyOTA library started to generating addresses from the `index=0` of the given seed and at the same time it also checked whether there are any transactions registered for each address\n* If yes, then in case we are after balances, the balance is saved. In case we are after new unused address then the given address is skipped. First address for which there are not registered transactions is returned\n* That's why it may be quite time consuming. And now you also understand all issues regarding `zero balances` after the snapshot\n\nYou may be also wondering how to get individual balances for each used address? This can be checked using the core API call `get_balances` which provides you with a balance for any address you specify. Let's query for used addresses from the previous exercise:\n\n\n```C#\nif (accountData.UsedAddresses.Count>0)\n{\n    var balances = repo.GetBalances(addresses: accountData.UsedAddresses,\n                                    threshold: 100);\n\n    Console.WriteLine(JsonConvert.SerializeObject(from adr in balances.Addresses\n                                                  select new { Balance = adr.Balance, Address = adr.Value }, Formatting.Indented));\n}\n\n```\n\n\n[\n  {\n    &quot;Balance&quot;: 0,\n    &quot;Address&quot;: &quot;SUYDJCMS9XMBKOPIPOXKGXMFVYXQ9YRNZLDYLRFARZFOFJDDH9JZLCQVO9GBRQKBCXHSPHOAPPWFFLMBW&quot;\n  },\n  {\n    &quot;Balance&quot;: 0,\n    &quot;Address&quot;: &quot;NHVGPRAXYTDZJLMLSUMZGVBBMICDQGGAAZ9UJGLIPPOTUEZJXABCSDFUTRTBFOLDOQZIBS9QTRXAB9IUX&quot;\n  },\n  {\n    &quot;Balance&quot;: 0,\n    &quot;Address&quot;: &quot;VZITIWJF99TH9REMKLYZUWELFLEW9FVYXPZPVMVFZVIQHAOEMEDABUUZGFROKKIVMT999PWGGLICKJOAD&quot;\n  },\n  {\n    &quot;Balance&quot;: 0,\n    &quot;Address&quot;: &quot;XPV9CTUC9JEKATOVABXXLICTDAQEOHR9HXXFLHKN9OZFMFAZKKUDZMREOBZJONZAHXCGNN9FHGNFBAKMC&quot;\n  },\n  {\n    &quot;Balance&quot;: 0,\n    &quot;Address&quot;: &quot;NDQMBGBQIBAQURVAQEUVONVMECKXSNYZZNKMMMOHOLPEYHJHDBTFWOZMAPFUAHLHIQUAV9GVZPEMBKL9Z&quot;\n  },\n  {\n    &quot;Balance&quot;: 2979,\n    &quot;Address&quot;: &quot;QYENROHVANIYBSIIMWGFDOUHXTMFOXIHOQXTJZLRFRJMOOINFTWCVVEJUFIITLBIHLVTESPVLUOSCFJDZ&quot;\n  }\n]\n\n\nIt returns `balances` and you can see how the remaining tokens move to new unused address every time you spend some tokens. Needless to say, used addresses with zero balances should not be used anymore since tokens were already spent from them. So let's spend some tokens:\n\n\n```C#\nusing Tangle.Net.Utils;\nvar bundleMoney = new Bundle();\n\nbundleMoney.AddTransfer(new Transfer()\n{\n    Address = new Address(AddressReceiver),\n    ValueToTransfer = 10,\n    Tag = new Tag(\"HRIBEK999IOTA999TUTORIAL\"),\n    Timestamp = Timestamp.UnixSecondsTimestamp\n});\n\nif (accountData.Balance > 0) // there are some tokens\n{\n    Console.WriteLine(\"Sending iotas... Please wait...\");\n    var sentBundle = repo.SendTransfer(seed: new Seed(SeedSender),\n                                       bundle: bundleMoney,\n                                       securityLevel: 2,\n                                       depth: 3,\n                                       minWeightMagnitude: 9, // MWM; in case of Devnet it is 9\n                                       remainderAddress: accountData.LatestUnusedAddress, // This should be your address where remaining token should go. If null then the client library finds the first unused address itself\n                                       inputAddresses: (from adr in accountData.UsedAddresses\n                                                        where adr.Balance>0\n                                                        select adr).ToList()); // These should be addresses from which your tokens should be spent from\n\n    // you can specify null in remainderAddress or inputAddresses, however it may be quite time consuming then.\n    // It starts to search addresses from the index 0 and searchs until it finds some funds and/or unused address\n    // so it is better to specify it manually as above (using accountData for instance) if you have such info\n    \n    foreach (var tx in sentBundle.Transactions)\n    {\n        Console.WriteLine(JsonConvert.SerializeObject(tx, Formatting.Indented));\n    }\n}\n\n```\n\n\nSending iotas... Please wait...\n\n\n\n{\n  &quot;Address&quot;: {\n    &quot;Balance&quot;: 0,\n    &quot;Checksum&quot;: null,\n    &quot;KeyIndex&quot;: 0,\n    &quot;PrivateKey&quot;: null,\n    &quot;SecurityLevel&quot;: 0,\n    &quot;SpentFrom&quot;: false,\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;BMFSMZMNBGKHAWPIZIOMJGRBXZETVSAYDSTDQCHLYTBWZMIXLNXF9XHLTMOCATFVFOMBQF9IOQGPEBPDC&quot;\n  },\n  &quot;AttachmentTimestamp&quot;: 1568994476124,\n  &quot;AttachmentTimestampLowerBound&quot;: 0,\n  &quot;AttachmentTimestampUpperBound&quot;: 3812798742493,\n  &quot;BranchTransaction&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;ODHVT9ZVBUOOUBKCYUZMFJTZQAGECIMWJKO9ZVAHAPVTEZFOEPDPMKSCTPRAIHWPYLERCOFWAHNYKS999&quot;\n  },\n  &quot;BundleHash&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;POKCELONFRIBFFQAOLKSOQAIGESODBDIXCASS99SCIW9LOHGCZNLGTNKISQISOZOPWIKEYZXDALCJCZ9W&quot;\n  },\n  &quot;CurrentIndex&quot;: 0,\n  &quot;Fragment&quot;: {\n    &quot;IsEmpty&quot;: true,\n    &quot;TrytesLength&quot;: 2187,\n    &quot;Value&quot;: &quot;999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999&quot;\n  },\n  &quot;Hash&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;TVNUVTJMDUQPJTETSUQZDSCNLQEOZVUQBSFCBESFGOVTDQAP9ILCLUXACSBFFNSRX9SGTNBOA9YPCO999&quot;\n  },\n  &quot;IsTail&quot;: true,\n  &quot;LastIndex&quot;: 3,\n  &quot;Nonce&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;QJIHDOADLJORTVSFXQLPVCTWPEF&quot;\n  },\n  &quot;ObsoleteTag&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;VEIBEK999IOTA999TUTORIAL999&quot;\n  },\n  &quot;Tag&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;HRIBEK999IOTA999TUTORIAL999&quot;\n  },\n  &quot;Timestamp&quot;: 1568994271,\n  &quot;TrunkTransaction&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;RLYSXEDFSDOHCZYLXNXZWQRRTUHWNAVUDTWDFKGTTALSVKRUGWO9XHOHXQANXRHAWFPRJWEYGCKWFI999&quot;\n  },\n  &quot;Value&quot;: 10\n}\n\n\n\n{\n  &quot;Address&quot;: {\n    &quot;Balance&quot;: 0,\n    &quot;Checksum&quot;: null,\n    &quot;KeyIndex&quot;: 0,\n    &quot;PrivateKey&quot;: null,\n    &quot;SecurityLevel&quot;: 0,\n    &quot;SpentFrom&quot;: false,\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;OTJSUNSQ9DLJVLKMVVPLDUTRHZAJDISDPZQCEPWNJWUGZOSFWRRBTUJAWCKKXACMZQIUP9NVVFYWRISWA&quot;\n  },\n  &quot;AttachmentTimestamp&quot;: 1568994476100,\n  &quot;AttachmentTimestampLowerBound&quot;: 0,\n  &quot;AttachmentTimestampUpperBound&quot;: 3812798742493,\n  &quot;BranchTransaction&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;ODHVT9ZVBUOOUBKCYUZMFJTZQAGECIMWJKO9ZVAHAPVTEZFOEPDPMKSCTPRAIHWPYLERCOFWAHNYKS999&quot;\n  },\n  &quot;BundleHash&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;POKCELONFRIBFFQAOLKSOQAIGESODBDIXCASS99SCIW9LOHGCZNLGTNKISQISOZOPWIKEYZXDALCJCZ9W&quot;\n  },\n  &quot;CurrentIndex&quot;: 1,\n  &quot;Fragment&quot;: {\n    &quot;IsEmpty&quot;: false,\n    &quot;TrytesLength&quot;: 2187,\n    &quot;Value&quot;: &quot;EOXBAZCKYQGYIDBBIROWQKVMQYMK9CAXTPU9WQBTBUFPNGSLMASPONP9ESRGVRGRQPGPIOFIQKWZOO9M9KTGYBKSNHMMYORIWKAIYLUEQSBGVYNFXCPDUTBJGHDDAFDCOWOUQOUTJHZ9LXWEILFNKECNTELSLFXNWYVGAACPD9MQOUYHQUVCJCJUMHAFMTNTM999DY9AYYSRMKLAKZFNSWGGRNOBU9APRNLHILB9RSE9RK9UPWD9TDLEQFUFAY9SXDHAJLDVGBDTWQGRWGIEWJYXEJZFMPLFJNKXIEYUGJVISCHBLXVSDVNMVQ9ELXZVZGZXHYBSONHJPMKHJXX9E9WYC9LUNREVHYCTFVQOXIKGZJRSNLFUVXZINZNSTSKXCMHXPAKAXQM9OJPHOBCCYHUVQOVJSOGRVTHQJRGQVIZEPROSWCGZEJNAXLUY9SSTOBTUNKFPEZMHNZUCJDJPVOEUHTWEPTWTJUZMWZQOAKGQQBDYDCKHRHFVRJU9OQGK9UUILGKDGUYUNOMZDVNIWGEKSDHJDUXSXJTCPGDPURQOIKVPIOYQGNBAGOYHAOCKCFT9QRLUMYHOUIOWRCBLMZXKHLGWLCCIUNQQEIRVTVFGIDQVFPUHP9JSGTLUVN9Q9CHKSIKCISTCAWBUUFGXKVD9KEAMYWRYDDSCWZNWVNCYYVEZVSJJIHEM99NTQWRWEPJMCFF9NLLLZMIGPJLUYHYRDPPUVJQVABMCUOYB9LOEOBCJ9TYUDHXOPFKBUILCBIXNPCEKOFQVLVFNYUEUPJOOKBKYWEZHIAMRTJPIABKRLJGSLKOOVYOPTSGYPPANE9RYIUFUFQNB9ODGOERVJZEBIRRIRTTHYVRTMWTCMFLZGAXUJVKOKMSWGRCUVDQO9SCEREOLSFVHKHBYG99RPEXM99WZDUIRSBLVRSLJXWKRKY9ABTEIXITZPCNJASZPCWOHAKMYN9RWAMBNEMMTEDZPTTHVHNJWQMECIAPJHUKIIIJACRWMKIPKFIQPPDAFGFMECAGHBEBACCEODHFDNN9R9NXECSYGQYBZBQEPROGMRXMGYBZRIFRDBPGVJRWRGGMOPBELJVUUIZLWWE9EULK9GSAPMSZJIJWNRJMRMTXJTZOJAIJAHYETTFVIMCERPFODWBKRDMXFVMWTZON9FABZRGVACVHMORPPCQSUHFHFOARTYRGUYJDJPKSNXCBIMIFMHGIHRUKFWWSNLNLYTYR9XAODPTJDNRHZPKELRJHXLXNXVBRNLXEPOBHCVLYQBZCLXDPMRZDBWHNW9CNV9OVGLPQQJKCIOPP9MIXANMPRQAJD9FQIDHMEMMLFYONUXRFKRCPCPZXBCQTZUBC9LGEOXPQGUAOM9SKTZHHQYMM9ELECRQESWDW9THZPSQBJB9KFD9KVWOKZJXUFRWYHPSFCLJ9QKUIFRWCEJPUFMTZCBSH9TBNPU9HVRSNDYAPYMZTYTDIPXEVWCBIEUKXSRWIUTX9QAPNUKYMGBOMZGNZRUJYQEJDZ9UJCLHBRWGFAFUARPMFXOTEI9OBRGXFEYZJUDRF9NXELMDGFRJSJLC9FZAXERRYXRXPG9NZQQYUQGJDODQYBRZRBARPU9OKXQYZO9P9JFZYJBPCFFFSIBVTCIOMSOHAUQWKCR9FDQXUKYAYAWHP9NBYSCVWSUHDONUTBLCTKHBBDAHJOA9QBEBYVWBBHXFBXNWHHWGUNDCQBZQRXBAX9AFXU9RKY9OIRZWUSETWYX9JLPZSOEXCLWKMOMKVWFEEREYMFZNYC9EBFDJI9ZAVRFNHVDJK9GGUVRVLVPEVSZRKLGLHUYAP9VSL9QGXKET99OPPUGPEGJQI9EVYVKKDPV9OWKPHFGGAXWPLRBNNZMKCOMDTQAQKEEXBLWZKXMCKWGFHR9FTKKSMIVPOZ9JPBTDZCPAKNLKCVUXXCTZYDHPYQUUVPOPWTTSJPXIU9VFGLWZVKPNEMKRGJKMMZXPMCJXYCOUMWE9BGPRNI9ERKKNNRYOWRZNKMYFEHPCJGW9YVIBGZFGRCDFMWQ9DKCPAMLLRWDCZHDQIRUIWBZ9RENLURTDVCEIEFJYPVEHVBARWWQKBDFAND9JPTNWDIUWXHARRCWQBP9CYSZGACESHDXYVDSOPKNDGHWPKYCOTVVNRENDQYMALGAW9ZICRJXBDGMPD&quot;\n  },\n  &quot;Hash&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;RLYSXEDFSDOHCZYLXNXZWQRRTUHWNAVUDTWDFKGTTALSVKRUGWO9XHOHXQANXRHAWFPRJWEYGCKWFI999&quot;\n  },\n  &quot;IsTail&quot;: false,\n  &quot;LastIndex&quot;: 3,\n  &quot;Nonce&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;9MGJNMEMMYIEIUXMAFQTAAPOCSN&quot;\n  },\n  &quot;ObsoleteTag&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;999999999999999999999999999&quot;\n  },\n  &quot;Tag&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;999999999999999999999999999&quot;\n  },\n  &quot;Timestamp&quot;: 1568994378,\n  &quot;TrunkTransaction&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;QHWMHCGTVIIJOWONJMOHQIMG9XZPPWGQHJFGDAPRSPVZBDI9SBAQNEHWJTHBSWQZUHUUDKKKKHOIUL999&quot;\n  },\n  &quot;Value&quot;: -859\n}\n\n\n\n{\n  &quot;Address&quot;: {\n    &quot;Balance&quot;: 0,\n    &quot;Checksum&quot;: null,\n    &quot;KeyIndex&quot;: 0,\n    &quot;PrivateKey&quot;: null,\n    &quot;SecurityLevel&quot;: 0,\n    &quot;SpentFrom&quot;: false,\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;OTJSUNSQ9DLJVLKMVVPLDUTRHZAJDISDPZQCEPWNJWUGZOSFWRRBTUJAWCKKXACMZQIUP9NVVFYWRISWA&quot;\n  },\n  &quot;AttachmentTimestamp&quot;: 1568994476061,\n  &quot;AttachmentTimestampLowerBound&quot;: 0,\n  &quot;AttachmentTimestampUpperBound&quot;: 3812798742493,\n  &quot;BranchTransaction&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;ODHVT9ZVBUOOUBKCYUZMFJTZQAGECIMWJKO9ZVAHAPVTEZFOEPDPMKSCTPRAIHWPYLERCOFWAHNYKS999&quot;\n  },\n  &quot;BundleHash&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;POKCELONFRIBFFQAOLKSOQAIGESODBDIXCASS99SCIW9LOHGCZNLGTNKISQISOZOPWIKEYZXDALCJCZ9W&quot;\n  },\n  &quot;CurrentIndex&quot;: 2,\n  &quot;Fragment&quot;: {\n    &quot;IsEmpty&quot;: false,\n    &quot;TrytesLength&quot;: 2187,\n    &quot;Value&quot;: &quot;VPHSCOL9LMGTQOSOWTX9FEBYUKS9DIRFUAMVRVBZRY9IPWAFOZUNZIKIDDPIWR9ZC9UTHJUKUWNDMKNNYIYSBPJDONBMCQNWZURV9YRHVUFSARGDSIKTSHFAFZYAF9O9SPGDAZNUJL9RPBOXVXNWIFCX9DLMJCDOQZIEXUHQGYSLTALXRAVXBMXRGZWHNDVVGLBNPSMTJIBBIBKD9ANINQYFMVV9VLBQSHJDYGMCOD9JHDSOTRXFTXYLKWROQBGCKZNLHPJGSCXGWRTMYOVOMYJCW9UTJUBOTZFUCVMWDNAROYMDQGWGL9YVMHF9YRJPKPOXYKEWHIXHQCWPQSRODNPQSAGT9QZPOUIIP9TRVTSVMZQKAIDZQKFBCPDDGCRNSEAXQTSGPDGIMVIOY9XJCRXHSDWGPBRTZXBJPBAWMPMFEBFTWOA9BGUQBXAG9GCDONRJOSEPGCPKYIYWOLIMXGKCQWHFUZSJPHDJGDOLDUTMPADEVSIPSABCQWJESUNSDUULYOEMNQCYZFMYGKBQKHBOFKBCTMXMUCZETYMMKBIJWSKPQQSHLTXWYXTYKJBFVVTYPPQVWFZSVBAFNADVJFPVNEWKVILVTVLGOPKJQFVJVJUPPPIRQVIBRWIQZIVB9OBDSAJZEJEVCOUOEYVMHCVMFOIRRCBBIEMGGXDHGIFAUIADUZIG9NBGDGXJTJN9BICTRNEARWGPPCIMVJVLPMXY9EEOIVEBMVBEFSASFTXINT9AAY9ADF9B9CHFUVAQZYRWLRPEAOUHDTSRHCURPLLBZBBVSEMOKOZOLSXQOXKYWKAQRSUYXYFVHNGY9NTCKPYXVP9TRTJRESLBDQHVSZPPYVAJWAHZUTEYQJRBZOXFJPXMA9PBPEKXCNBQJAFOSQWESFRRZX9XQYZHBQBCAJFYOSYEZXIPPCMVJPIXLLYCLEWALMCFHHYHOGISEYSRLRUTBAWWYLYXBBHUI9PTYBXTXQKAGRRM9DUOCCTSYOPDJSNMRTLEUACAHMQJCDPGNZLWUMTEHQHUIDBOVWATEOGNNUWACUTA9ZNKKHXASCMFIVSHVPYTFWJRAJNZSCACOGSETISRTJEKS9SNAZEIQ9EFPYCVIQESJV9FOURMYAKYNAJXIOHFLQGZEOWOZKXTAPEQRDGHRVR9YLTKXPQL9XJGFZHWCWNAEC9I9RSUWPDLWW9RBWVAGKNBH99LOKBCHJAGOFTSLTI9BBRQJOEYSGFKQJIFFTO9AVJIMNFVONGATUMWGWMFKAKBYYTJHTLZW9GPJCIPTDVJYJDWCKAVVXSROGVANFLCBLXYPVLFNPOGDSTXHJUNTBZDMMVHLQKZJGIVIGHAYB9UJ9NYCQFWGZARPKOMIVFMZCA9NOVUJUPO9REIWSQEHMYCXJJTFNFVXGLPEXGBSAPUK9JNVPYZLOFHNMXCFJUBHPSLJCICLJQNXUKBMZNYBOXNGTOBWNJOOEMANSHHRRKDKASZD9WEDJJAYXITQQYTMMEUQXVRUSYNYSWZQMLEQMKLGTYZXFTAHYCCRNTGPVXUWJXZCCMGUMLTGZBQPIN9EEXKXBZT9YQWHCAWMFRLPPFIDJDUGIQYYWUXEKUHMAOMGTLU9LQD9TUEXRCZPRQCMMGHQUWHEBWLYHQQPVCLTAOYVGPUAFQPQDEFPTCRYXBPNQQHEXENPDLVNMZC9BCURJA9WZFM9UMKFQFVGXCSTORHEMAFXSNYASVSBQEECCEGTPWSHVLGFNSXS9SLPQITOCXHNESF9HQVINAXHZPWYWUMXHC99QLLWLSDEYUXWDMXLFEAQZOLCHO9S9JJRSOWRXCSNGNPSCZPZAUCBQVSO9DHABRUBHYPOUXIPNCZJZWZDRRMDWFMLPZURXTXFTIZWCKVFKAYXBLJLOKXALWCDRLHJ9XYKKEPMEIDVLUTFDRTRK9HKM9QGUNCCZ99BUCOOABSWJLSUQTGGKIPEVHKYMKZNWJIPKSUKDMGXC9ZFPDZP9GKRSQDKEEKTNMRTUJHOYFIHSITYUVEMBFVTULCEXEALNHIPZLLFDIIZRSGBWRWTZUNTIBVTZPOFFSAFIFWVEQVUNCYXWLJCKCQGCYSAEJBTYSYRDOKCVBIVKARKOVQDFNVIFASBXJE9FLSNHO9VSWU9QNWP9IFBCPJNOFX99CQHLEBLYTTVFDYWBCWY9W&quot;\n  },\n  &quot;Hash&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;QHWMHCGTVIIJOWONJMOHQIMG9XZPPWGQHJFGDAPRSPVZBDI9SBAQNEHWJTHBSWQZUHUUDKKKKHOIUL999&quot;\n  },\n  &quot;IsTail&quot;: false,\n  &quot;LastIndex&quot;: 3,\n  &quot;Nonce&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;AGSRO9XBGFMRZCJYRKWXTTEUGFW&quot;\n  },\n  &quot;ObsoleteTag&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;999999999999999999999999999&quot;\n  },\n  &quot;Tag&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;999999999999999999999999999&quot;\n  },\n  &quot;Timestamp&quot;: 1568994378,\n  &quot;TrunkTransaction&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;MRSAOMMNAAQGWHIKN9YBFENJMFMCSXJRWKDGZIWXBRRGIS9HJZGPSXZTD9MCIZORKBCORDUSKUFKBF999&quot;\n  },\n  &quot;Value&quot;: 0\n}\n\n\n\n{\n  &quot;Address&quot;: {\n    &quot;Balance&quot;: 0,\n    &quot;Checksum&quot;: null,\n    &quot;KeyIndex&quot;: 0,\n    &quot;PrivateKey&quot;: null,\n    &quot;SecurityLevel&quot;: 0,\n    &quot;SpentFrom&quot;: false,\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;SZAVDSKTHNQFWTTINRAYQKJAXTLD9CRFFWWBSEXIEXPLBBEP9FT9IVGICWIXTJCFUKJSTOUFANJGBTPQX&quot;\n  },\n  &quot;AttachmentTimestamp&quot;: 1568994476035,\n  &quot;AttachmentTimestampLowerBound&quot;: 0,\n  &quot;AttachmentTimestampUpperBound&quot;: 3812798742493,\n  &quot;BranchTransaction&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;ODHVT9ZVBUOOUBKCYUZMFJTZQAGECIMWJKO9ZVAHAPVTEZFOEPDPMKSCTPRAIHWPYLERCOFWAHNYKS999&quot;\n  },\n  &quot;BundleHash&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;POKCELONFRIBFFQAOLKSOQAIGESODBDIXCASS99SCIW9LOHGCZNLGTNKISQISOZOPWIKEYZXDALCJCZ9W&quot;\n  },\n  &quot;CurrentIndex&quot;: 3,\n  &quot;Fragment&quot;: {\n    &quot;IsEmpty&quot;: true,\n    &quot;TrytesLength&quot;: 2187,\n    &quot;Value&quot;: &quot;999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999&quot;\n  },\n  &quot;Hash&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;MRSAOMMNAAQGWHIKN9YBFENJMFMCSXJRWKDGZIWXBRRGIS9HJZGPSXZTD9MCIZORKBCORDUSKUFKBF999&quot;\n  },\n  &quot;IsTail&quot;: false,\n  &quot;LastIndex&quot;: 3,\n  &quot;Nonce&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;GLKUMZVXVLHZXXFALUYZJHZJJZI&quot;\n  },\n  &quot;ObsoleteTag&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;999999999999999999999999999&quot;\n  },\n  &quot;Tag&quot;: {\n    &quot;TrytesLength&quot;: 27,\n    &quot;Value&quot;: &quot;999999999999999999999999999&quot;\n  },\n  &quot;Timestamp&quot;: 1568994471,\n  &quot;TrunkTransaction&quot;: {\n    &quot;TrytesLength&quot;: 81,\n    &quot;Value&quot;: &quot;ODHVT9ZVBUOOUBKCYUZMFJTZQAGECIMWJKO9ZVAHAPVTEZFOEPDPMKSCTPRAIHWPYLERCOFWAHNYKS999&quot;\n  },\n  &quot;Value&quot;: 849\n}\n\n\nLet's review all transactions that has been prepared and sent eventually:\n* The first transaction `current_index=0` is the `output TX` that basically adds tokens to some address\n* Transactions `current_index=1` and `current_index=2` are two parts of the same transaction - `Input TX`. This transaction deducts tokens from the address(es). You can see negative `value` in the transaction `current_index=1`\n* Why there are two parts? Since the transaction spends tokens it has to be signed in order to validate the ownership. Signature is generated from the private key and the signature can be observed in the field `signature_message_fragment`. Here is the thing. Do you remember when different `security levels` were discussed? There are three security levels available and the given level has the direct impact on length of the signature. Since `signature_message_fragment` is of the fixed size, if `SL>1` then the transaction has to be split to be able to accommodate full signature.\n* The last transaction `current_index=3` moves unspent tokens to the first unused address of the given seed.\n\nThe following tasks have to be done behind the curtain in addition to the standard transaction preparation process:\n* Search for address(es) with some balance until total amount of tokens available is large enough to be spent. You can use more input addresses if needed\n* If there would be some unspent amount of tokens then also search for the first unused address\n* Spending transactions (Input TX) has to be properly signed and split in case of `SL>1`\n* There is also some quick check performed whether resulting number of tokens is zero (no more tokens, no less tokens. Number of tokens has to be balanced).\n\nSo basically all steps we tried in the chapter had to be done also behind the curtain while using `send_transfer` extended API call. You can also see that some of those operations may be quite expensive in terms of time while being completely stateless. In real world applications it would be better to save some states (index of last address, used addresses, etc.) to avoid too many expensive operations.\n\nYou can review the given broadcasted transactions also in the tangle explorer (for devnet):\n* https://devnet.thetangle.org/address/BMFSMZMNBGKHAWPIZIOMJGRBXZETVSAYDSTDQCHLYTBWZMIXLNXF9XHLTMOCATFVFOMBQF9IOQGPEBPDC\n", "meta": {"hexsha": "d674b7f154cf0d0d79e704f0abb0e5d22a2083ab", "size": 237557, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Developer Lab/Allchapters_csharp.ipynb", "max_stars_repo_name": "Hribek25/IOTA101", "max_stars_repo_head_hexsha": "adf5c4cced557d60836bf6ba80a1080b2607c8e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2018-06-28T18:15:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T22:05:53.000Z", "max_issues_repo_path": "Developer Lab/Allchapters_csharp.ipynb", "max_issues_repo_name": "Hribek25/IOTA101", "max_issues_repo_head_hexsha": "adf5c4cced557d60836bf6ba80a1080b2607c8e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-07-01T19:45:20.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-01T18:18:04.000Z", "max_forks_repo_path": "Developer Lab/Allchapters_csharp.ipynb", "max_forks_repo_name": "Hribek25/IOTA101", "max_forks_repo_head_hexsha": "adf5c4cced557d60836bf6ba80a1080b2607c8e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-08-26T20:01:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-26T17:09:56.000Z", "avg_line_length": 67.5645620023, "max_line_length": 2720, "alphanum_fraction": 0.7377766178, "converted": true, "num_tokens": 40587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14414886406287503, "lm_q2_score": 0.055823137600340265, "lm_q1q2_score": 0.008046841873514617}}
{"text": "> *This textbook was generated automatically from a [GitHub Repo](https://github.com/Hribek25/IOTA101). Visit the repo for more information.* \n\n\n# IOTA Developer Essentials\n[](https://hribek25.github.io/IOTA101/devlab.html#Language-Coverage)\n[](https://github.com/Hribek25/IOTA101)\n[](https://gist.github.com/search?utf8=%E2%9C%93&q=IOTA101)\n[](https://hribek25.github.io/IOTA101/devlab.html)\n[](https://hribek25.github.io/IOTA101/)\n[](https://ecosystem.iota.org/tutorials/iota-developer-essentials)\n\nThese notebooks provide a self-study introduction to IOTA protocol and are designed for developers and tech enthusiasts who would like to get quickly familiar with the IOTA. Technical-related information is accompanied with interactive code snippets to help you to quickly jump on the platform and be ready to build own solutions based on it.\n\n> Motto of this tutorial: \"Let's start with baby steps before we can try and fly.\"\n\n## Main Goal\nMain goal of this guide is to provide a comprehensive yet well-balanced proportion of deep-dive technical information and essentials.\n\n## Getting Started\nThere are several chapters available. If you are not familiar with IOTA then it is highly recommended to follow them in the particular order to understand all important IOTA concepts properly. Otherwise you may get quickly confused later.\n\n## Code Snippets\nCode snippets are currently based on Python, NodeJs and C#. Since Python is very descriptive language and easy to understand, I believe the tutorial is basically understandable to anyone. Anyway, all important IOTA concepts are described in language-agnostic way and so you would be able to use any language of your choice.\n\nInterested to see what is the overall code base coverage breaked down to a specific language? The following page provides you such an info. Needless to say, we are working hard to be sure there is no language that would be a second-class citizen.\n\n[](https://hribek25.github.io/IOTA101/devlab.html#Language-Coverage)\n\nIOTA Developer Essentials are accompanied by *IOTA Developer Lab* and so you can play with all code snippets directly in your web browser. Feel free to experiment with the prepared code snippets and get your hands dirty. It is a best way how to get familiar quickly.\n\n[](https://hribek25.github.io/IOTA101/devlab.html)\n\nAll *standalone* code snippets are also maintained @ GitHub Gist. It enables you to fork them, comment them, share them, embed them and track all changes to them. See the action panel next to each code snippet.\n\n[](https://gist.github.com/search?utf8=%E2%9C%93&q=IOTA101)\n\n## Viewing and running\n### Interactive Mode\nThere exists a side project called *IOTA Developer Lab* that is built on top of *IOTA Developer Essentials*. The project provides infrastructure services for you to be able to get an interactive experience with all code snippets.\n\n[](https://hribek25.github.io/IOTA101/devlab.html)\n\n### Static Mode\nIf you prefer a static experience (for printing purposes, for instance) you can reach the given notebooks as a Complete Textbook that is compiled from all source materials:\n\n[](https://hribek25.github.io/IOTA101/)\n\nEverything is tightly linked together and so you can easily switch between different languages for instance, or you can share links to specific chapters, code snippets, etc. All links are static so feel free to share them.\n\n\n## Feedback and corrections\nThese notebooks are maintained at [GitHub](https://github.com/Hribek25/IOTA101).\nIssues can be submited via [issue tracker](https://github.com/Hribek25/IOTA101/issues).\n\n## About\nThese notebooks are developed and maintained by Petr Zizka (petr@zizkovi.name). It has been supported by the EDF Grant (https://blog.iota.org/the-5th-cohort-of-iota-ecosystem-development-fund-grantees-5cbf05227525).\n\nIt is ongoing process since IOTA is still under heavy development and rapidly emerging every day. So stay tuned - the plan is to keep adding fresh content on regular basis.\n\nFeel free to follow me at [Twitter](https://twitter.com/petrzizka) or IOTA Discord Channel (@hribek25#2683).\n*(New to Discord? Invitation link: https://discord.gg/fNGZXvh)*\n\nDisclaimer: I am not associated with the IOTA foundation. I am IOTA supporter.\n\n----\n\n\nThe IOTA Developer Essentials and IOTA Developer Lab are long-term projects. The main goal is to provide a comprehensive onboarding information to anybody interested in the IOTA protocol. It will cover much more chapters, more code snippets and it will also cover more languages. Your kind donations will support the vision pushing forward. Thank you.\n\nDonations (IOTA):\nDSZRO9TCIJIKZOKUPVNOJFKVAHFCKL9YMLPVZUAEVZPOFXLIUWLPRQWBMVVSFTKGMGPPHXCYE9MIZEVBXQNFYKYUA9\n\n\n\n\n--- \n\n\n# IOTA 101: Essentials and IOTA Terminology\nIOTA is an open-source Distributed Ledger Technology (DLT) with the following characteristics: *permissionless*, *feeless* and *trustless*. In contrary to the blockchain technology, the IOTA transactions are stored in a form of Directed Acyclic Graph (DAG) called *the Tangle*.\n\n\n## Transactions\nTransactions (TXs) in the tangle can be of two types:\n* **Value transactions** (*IOTA token* represents funds in case of value transactions)\n* **Zero-value transactions** (aka meta transactions)\n\nEvery transaction is attached to a specific *IOTA Address*.\nThere are no miners with IOTA protocol to validate transactions. The *consensus* is achieved by network participants themselves. Each participant that wants to broadcast a new transaction has to approve 2 past transactions and basically attach transaction as a children node. Transactions without children transactions (waiting to be confirmed) are called *tips*.\n\n## Seed, private key and address\nPair of unique IOTA address and corresponding *Private Key* is determistically generated from a *Seed*. You can generate (2<sup>53</sup> - 1) different addresses/private keys based on one Seed. Anybody can send anything to the given address however only Seed owner can send funds from IOTA address since only the Seed owner is able to generate corresponding *Private Key*.\n\nIOTA protocol uses One-Time Signature (OTS) for \"verifying\" whether private key matches to the given address, specifically Winternitz OTS (WOTS). So *Private Key* (specifically *Key Fragments* of the private key) is the key component while signing transactions using WOTS.\n\nThat's the reason why nobody should use IOTA address that have been already funds spent from. New IOTA address (of the given seed) should be generated and used instead. Please note, it applies only to fund-spending. Receiving funds/data is totaly fine even multiple times.\n\nTo summarize the key concept here. Only *Seed* is needed to be stored somewhere. Everything else can be safely generated from it: private key as well as address.\n\n## IOTA nodes\nThe Tangle runs on a *distributed network* of IOTA nodes called *mainnet*. There are also other separate \"Tangles\" serving for specific purposes: Devnet, SPAMnet, etc. You can interact with the network via public nodes using collection of public *API calls*. You can interact with any public node of the given network since all nodes \"gossiping\" all TXs across the whole network. Nodes are powered by a reference piece of software called *IRI* (IOTA Reference Implementation) **as of now**.\n\nIt is also important to mention that you do not exchange any sensitive information such as *Seed* with a node. Every sensitive operation such as TX signing is done on client's side and node is just a \"messenger\" that delivers your TX to the IOTA network.\n\n\n## Custom node\nYou can even run own IOTA node and actively participate to the whole network. There is a big advantage for developers in that case. Actual implementation of IRI  provides an usefull real-time information via messaging platform called ZeroMQ and so developers can leverage that.\n\n## API calls\nThere are ready-made libraries for major programming languages available and so you have more developer-friendly way how to interact with the IOTA network. Anyway, you can interact with IOTA network using pure API calls without any library. It is up to you.\n\n\n## Ternary\nIt is difficult to avoid mentioning *Ternary numeral system* while discussing IOTA at all. IOTA is based on ternary system under the hood and so you have got to be aware of some basic terminology in this respect. You are going to face this fact in any developer-related IOTA guide out there.\n\n### Ternary\nTernary has three as its base (aka base 3) as opposted to *binary* which is base 2. Instead of two states (0 and 1) it recognizes three states (for ex. -1, 0, 1).\n\n### Trit\nOne *Trite* is analogous to one *bit*. It is the smallest digit and has three states. Trit = **Tri**nary dig**it**.\n\n### Tryte\n*Tryte* consists of three *trits* meaning 27 combinations.\n$$3^3=27$$\n\nYou will recognize soon that almost everything is encoded in *Trytes* in the IOTA world. Tryte is visually represented using [A..Z] alphabets and number 9. One character represents one tryte (here comes 27 possible characters again). *Don't get mad, IOTA libraries are going to help us.*\n\nSmall example:\n\n\n```python\nimport iota #importing PyOTA library to interact with\nfrom pprint import pprint\n\nTrytesAsBytes = b\"YZJEATEQ9JKLZ\" # some data encoded in Trytes (byte string in Python, not unicode string)\nTrytes = iota.TryteString(TrytesAsBytes) # initializing TryteString type from the PyOTA library - great help while dealing with Trytes/Trits, etc.\npprint(Trytes) # getting the same data however using TryteString type of PyOTA library\npprint(\"Number of Trytes: %s\" % len(TrytesAsBytes))\nTrits = Trytes.as_trits() # converting Trytes to Trits\npprint(Trits,compact=True)\npprint(\"Number of trits: %s\" % len(Trits)) # Number of trits is three times the number of trytes obviously\n```\n\n    TryteString(b'YZJEATEQ9JKLZ')\n    'Number of Trytes: 13'\n    [1, -1, 0, -1, 0, 0, 1, 0, 1, -1, -1, 1, 1, 0, 0, -1, 1, -1, -1, -1, 1, -1, 0,\n     -1, 0, 0, 0, 1, 0, 1, -1, 1, 1, 0, 1, 1, -1, 0, 0]\n    'Number of trits: 39'\n\n\n# IOTA 101: Basic network interactions\nThe tutorial is based on IOTA libraries called *PyOTA* for Python, *IOTA Javascript Library (@iota/core)* for JavaScript and Tangle.Net for C# (.NET 4.x and .NET Standard). It encapsulates all official IRI API calls and it can be installed via `pip` in Python environment, via `npm` in JS environment and via `NuGet` in case of .NET environment.\n\nReader is also encouraged to try a ready-made environment via *IOTA Developer Lab* project (at lab.iota101.info) where anyone can run a code directly in a web browser. When viewing it interactively then just select a code snippet and hit `ctrl + enter` which executes it.\n\nAnyway, most of the information in the tutorial is language-agnostic and so only particular interfaces slightly differ across different IOTA libraries. Top-level details are the same regardless programming language you are going to use.\n\n## A few words about specific IOTA libraries\n### Python\n*PyOTA* is well maintained and understandable IOTA library that can be reached at https://github.com/iotaledger/iota.lib.py. It is very good starting point for beginners.\nIt can be installed via `pip`:\n```pip install pyota```\n\n### JavaScipt\nOfficial IOTA Javascript library (v1.0) is currently in beta however all main functions are working just fine, please see https://github.com/iotaledger/iota.js/. It is very modular and so you can install only components you really need.\n\nMain component is @iota/core and can be installed via `npm`:\n```npm install @iota/core```\n\nAs with everything in NodeJS, most of the tasks are asynchronous and they are chained via `callbacks` or `promise`. Snippets below leverage `promise` chaining.\n### C# (.NET)\n*Tangle.Net* is well maintained IOTA library for .NET and can be reached at https://github.com/Felandil/tangle-.net.\nIt can be installed via `NuGet`:\n```nuget.exe install tangle.net```\n\nSnippets below uses synchronous functions however the library provides also asynchronous (async postfix) version.\n\n\n## Conneting to IOTA nodes\nBefore you can interact with the IOTA network you need an URL of the running IOTA node. There are dozen of directories of public nodes available, feel free to google them.\n\nFor a sake of this tutorial I use a project *thetangle.org*. It is a load ballancer that provides you an access to a pool of participanting nodes effortlessly.\n* *Advantage:* you do not have to care about public nodes and whether they are running or not\n* *Disadvantage:* you do not know in advance which specific node will process your API call. So in some respect results of API calls may differ since some API calls depend on specific node, such as GetNodeInfo().\n\n### Node is not synced\nEven if a node is up and running it may not be fully prepared to process your API calls correctly. The node should be \"synced\", meaning should be aware of all TXs in the Tangle. It is better to avoid not fully synced nodes.\n\n### Health checking\nOnce you connect to an IOTA node you should be able to send API calls. However it is better to do some checks in advance in order to find out whether the given node is in good condition or not. IOTA nodes can be run by anyone and so health check is always a good practice.\n\nBasic healthcheck can be done via *GetNodeInfo()* API call. It returns a basic information about the given IOTA node.\n\n\n```python\nimport iota #importing PyOTA library to interact with\nfrom pprint import pprint\n\nNodeURL = \"https://nodes.thetangle.org:443\"\n\napi=iota.Iota(NodeURL) # ctor initialization of the PyOTA library\nresult = api.get_node_info() # basic API call to double check health conditions\npprint(result) # result is printed out\n\n# Basic check whether node is in sync or not\n# Elementary rule is that \"latestMilestoneIndex\" should equal to \"latestSolidSubtangleMilestoneIndex\" or be very close\nif abs(result['latestMilestoneIndex'] - result['latestSolidSubtangleMilestoneIndex']) > 3 :\n    print (\"\\r\\nNode is probably not synced!\")\nelse:\n    print (\"\\r\\nNode is probably synced!\")\n\n```\n\n    {'appName': 'IRI',\n     'appVersion': '1.8.1',\n     'coordinatorAddress': 'EQSAUZXULTTYZCLNJNTXQTQHOMOFZERHTCGTXOLTVAHKSA9OGAZDEKECURBRIXIJWNPFCQIOVFVVXJVD9',\n     'duration': 0,\n     'features': ['loadBalancer', 'snapshotPruning', 'RemotePOW'],\n     'jreAvailableProcessors': 16,\n     'jreFreeMemory': 1590527138,\n     'jreMaxMemory': 20997734400,\n     'jreTotalMemory': 3914679363,\n     'jreVersion': '1.8.0_191',\n     'lastSnapshottedMilestoneIndex': 1193175,\n     'latestMilestone': TransactionHash(b'WODBVHHV9XVGYNDDFQY9WGDLBYEJ9RU9JYDJGELASMJ9KYPPYVGSLPGBMARZRVNYIJZTYEKQTYMAZ9999'),\n     'latestMilestoneIndex': 1193284,\n     'latestSolidSubtangleMilestone': TransactionHash(b'WODBVHHV9XVGYNDDFQY9WGDLBYEJ9RU9JYDJGELASMJ9KYPPYVGSLPGBMARZRVNYIJZTYEKQTYMAZ9999'),\n     'latestSolidSubtangleMilestoneIndex': 1193284,\n     'milestoneStartIndex': 1157888,\n     'neighbors': 24,\n     'packetsQueueSize': 0,\n     'time': 1569876350354,\n     'tips': 4566,\n     'transactionsToRequest': 0}\n    \r\n    Node is probably synced!\n\n\n*Please note: When using node load balancers then this type of check is quite useless since other API calls of yours may be served by different node that may have not been checked. You should be aware of it and trust that the load balancer participates only with nodes that are in a good condition.*\n\n## Generating IOTA seed and IOTA address\nSince the IOTA network is *permissionless* type of network, anybody is able to use it and interact with it. No central authority is required at any stage. So anybody is able to generate own seed and respective private key/address anytime. It is highly recommended to *NOT* use online generators at all.\n\nThe Seed is the only key to the given addresses. Anyone who owns the Seed owns also all funds related to respective IOTA addresses (all of them).\n\nSeed and addresses only consists of characters [A-Z] and number 9. Length is always 81 charaters. There are usually also used additional 9 characters in IOTA addresses (so total lenght is 90 then) which is a *checksum*. It provides a way how to prevent typos while manipulating with IOTA addresses.\n\n\n### Seed\nA seed generation is a process that is based on random quessing of each character in the seed. Of course, you should always use cryptographically secure pseudo-random generator!\n\n\n```python\nimport random\nchars=u'9ABCDEFGHIJKLMNOPQRSTUVWXYZ' #27 characters - max number you can express by one Tryte - do you remember?\nrndgenerator = random.SystemRandom() #cryptographically secure pseudo-random generator\n\nNewSeed = u''.join(rndgenerator.choice(chars) for _ in range(81)) #generating 81-chars long seed. This is Python 3.6+ compatible\nprint(NewSeed)\nprint(\"Length: %s\" % len(NewSeed))\n```\n\n    PYDHTCNKMTVRGORKCKDCHPMIRAIVGB9FZFGUJWZVAQYWUVOEOJUVDEMNGOLWWSOG9QLUHDNVEFYOBFEIK\n    Length: 81\n\n\nAlternatively you can leverage also PyOTA library since it has own implementation of the pseudo-random Seed generator (Python 2.7+ compatible). Difference between both methods is very subtle. I just wanted to illustrate both ways: Fully independent and IOTA-library-dependant. *Please note, IOTA Javascript library does not support a seed generation.*\n\n\n```python\nfrom iota.crypto.types import Seed  #importing PyOTA library to interact with\n\nNewSeed = Seed.random()\nprint(NewSeed)\nprint(\"Length: %s\" % len(NewSeed))\n```\n\n    SVXJAGAMEMBFFXEWZMLEHYXJNUAQQEEPBLWDZOQB9VPDGPWEQMMMXMDYVTNDDPNUHZXKSUXSTSVYIBCTM\n    Length: 81\n\n\n### Address\nThere is a deterministic function how to get an address from a seed. It is a basically an indexed collection of addresses starting with address at index 0, 1, 2, etc.\n\nWhile generating addresses you should be also aware there are three different so called *Security Levels* (1, 2 and 3). Each security level generates totally independent pool of addresses. Addresses of Security Level 1 are totally different from addresses of Security Level 2, etc.\n\nIn a nutshell, Security Level indicates how difficult is to generate *Private key* from the Seed and also what is its size. The higher security level, the more secure (longer) is the given private key. Default Security Level is 2. Most of IOTA wallets uses Security Level=2 and users are usually not allowed to change it. So be carefull while designing your app.\n\nAs long as *seed, address index and security level* are the same, you always get the same address and corresponding private key:\n\n$$PrivateKey/Address = fce(Seed, AddressIndex, SecurityLevel)$$\n\nGeneral example:\n$$PrivateKey/Address1 = fce(Seed, 1, 2)$$\n$$PrivateKey/Address2 = fce(Seed, 2, 2)$$\n$$PrivateKey/Address3 = fce(Seed, 3, 2)$$\n\n\n\n\n```python\nimport iota\nfrom pprint import pprint\n\n# For this particular task the Node URL is not important as it will not be contacted at all\n# However it has to be well-formatted URI\nNodeURL = \"https://nodes.thetangle.org:443\"\nMySeed = b\"WKQDUZTGFKSSLACUCHHLZRKZBHSDSCEBHKUPDLKFBQALEBKDMFRPUQGZRXAADPG9TSRTZGGBZOFRJCFMM\"\n\napi=iota.Iota(NodeURL,\n              seed = MySeed) # if you do not specify a seed, PyOTA library randomly generates one for you under the hood\n    \n# Let's generate 3 addresses using default security level=2.\n# It is deterministic function - it always generates same addresses as long as the Seed, Security Level and Index are the same\nresult = api.get_new_addresses(index=0,\n                               count=3,\n                               security_level=2)\npprint(result)\n```\n\n    {'addresses': [Address(b'HRLKBQUZAEB9HIVWJEWVDYQ9G9VRQXQAXR9ZWGBFQJKRPOPJYHGAT9LBEIE9RWRMUFSNLCWYHQGYAECHD'),\n                   Address(b'XEXIDJJTANADOUBPWTCSPPRYYRTITRAHDEOZAEXWDPCYKUPTFMKVQM9KCPPLOCESFRGRVSIYZHXQZNYKC'),\n                   Address(b'KY9DLZCHET9ATLMADPXGDVDYMPHKRKQPJZ9MB9HEIMMFCRRTNJIJIHPKGZNKKDTFMYPZRRQYAQKVAHMYX')]}\n\n\nPlease note, some IOTA libraries may communicate with a IOTA network while generating addresses to double check whether the given address was used or not.\n\nSo it is sometimes better to use directly an address generator component. Outputs are equivalent in both cases but the latter one usually only generates pool of addresses locally:\n\n\n```python\nfrom iota.crypto.addresses import AddressGenerator\nfrom pprint import pprint\n\nMySeed = b\"WKQDUZTGFKSSLACUCHHLZRKZBHSDSCEBHKUPDLKFBQALEBKDMFRPUQGZRXAADPG9TSRTZGGBZOFRJCFMM\"\n\n#security level is defined during generator init\ngenerator = AddressGenerator(seed=MySeed,\n                             security_level=2)\n\nresult = generator.get_addresses(0, 3) #index, count\npprint(result)\n```\n\n    [Address(b'HRLKBQUZAEB9HIVWJEWVDYQ9G9VRQXQAXR9ZWGBFQJKRPOPJYHGAT9LBEIE9RWRMUFSNLCWYHQGYAECHD'),\n     Address(b'XEXIDJJTANADOUBPWTCSPPRYYRTITRAHDEOZAEXWDPCYKUPTFMKVQM9KCPPLOCESFRGRVSIYZHXQZNYKC'),\n     Address(b'KY9DLZCHET9ATLMADPXGDVDYMPHKRKQPJZ9MB9HEIMMFCRRTNJIJIHPKGZNKKDTFMYPZRRQYAQKVAHMYX')]\n\n\n## Validating IOTA address\nAs mentioned earlier, IOTA address consists of 81 trytes ([A..Z9] characters) or 90 trytes including checksum. Checksum is useful when you want to make sure a valid address was given (no typos, etc.) and so it is a good practise to encourage user of your app using IOTA addresses including checksums = 90 trytes.\n\nIOTA libraries are able to help you to deal with some basic patterns such as validating addresses, generating checksums, etc.\n\n\n```python\nimport iota\nfrom pprint import pprint\n\n# some IOTA address\nAdr = iota.Address(b\"CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\")\n\npprint(\"Original input excl. checksum address:\")\npprint(Adr)\nprint(\"Length: %s\" % len(Adr))\n\nAdrInclCheckSum = Adr.with_valid_checksum()\nprint(\"\\nInput address including checksum:\")\npprint(AdrInclCheckSum) # the last 9 trytes is the checksum\nprint(\"Length incl checksum: %s\" % len(AdrInclCheckSum))\n```\n\n    'Original input excl. checksum address:'\n    Address(b'CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW')\n    Length: 81\n    \n    Input address including checksum:\n    Address(b'CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RWTHBIRSXTA')\n    Length incl checksum: 90\n\n\nYou should always make sure your app is dealing with valid IOTA address. Please note, you should also make sure an address is of correct length and consists only of allowed characters. IOTA libraries may slightly differ in their approaches but differences are very subtle and both libraries provide enough functions to validate IOTA address.\n\nGeneral steps should be:\n* Checks length\n* Checks valid characters\n* Checks address against its checksum\n\n\n```python\nimport iota\nimport sys\nfrom pprint import pprint\n\nInputAddr = b\"CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RWTHBIRSXTA\"\nif len(InputAddr)!=90:\n    print(\"Incorrect lenght of the given address. Please, use an address including checksum.\")\n    exit(2)\n\ntry:\n    # address including checksum\n    Adr2 = iota.Address(InputAddr)\nexcept :\n    print(\"Not valid input address given\")\n    sys.exit(1)\n\npprint(\"Input address incl checksum:\")\npprint(Adr2)\nprint(\"Is it valid addr based on checksum? %s\" % (Adr2.is_checksum_valid()))\n\nprint(\"\\nInput address excl checksum:\")\npprint(Adr2[:81]) # return only first 81 characters\n```\n\n    'Input address incl checksum:'\n    Address(b'CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RWTHBIRSXTA')\n    Is it valid addr based on checksum? True\n    \n    Input address excl checksum:\n    TryteString(b'CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW')\n\n\n# IOTA 101: Transactions\nA transaction is a smallest piece of data that can be broadcasted to the network. Each transaction consists of fixed 2673 trytes. Transactions (TXs) are basically of two types:\n* **Value TXs:** those transactions change ownership of IOTA tokens. Two possible states: spending TXs or receiving TXs\n* **Non-Value TXs:** those transactions include piece of data that can be broadcasted and read from the Tangle\n\nTransactions are broadcasted in an envelope called *Bundle*. Bundle may consist of multiple TXs. Bundle is processed by the Tangle as a single entity; meaning only the whole bundle is confirmed by the network (and all TXs within) or nothing. You have to prepare a bundle even if you broadcast single transaction only. Bundle is also described as *atomic* since every bundle includes all information needed to process it antonomously.\n\nEach transaction includes several fields, let's name the most important ones:\n* **`Value`:** Value can be *positive* number = receiving IOTA tokens, *negative* number = spending IOTA tokens or *zero* = broadcasting only piece of data\n* **`Address`:** It is IOTA address that is associated with the given transaction. *Value* indicates whether it is an address of a receiver or a sender\n* **`Tag`:** It is an user-defined tag that can be used for searching, etc.\n* **`SignatureMessageFragment`:** This is the most lenghty attribute (2187 trytes) and could include: *transaction signature* based on private key in case it is a spending TX or *piece of data (message)* in case it is non-value TX. Alternatively it can be also left blank (in case of non-value TXs)\n* **`TrunkTransaction` / `branchTransaction`:** Those two fields refer to some previous transactions in the Tangle (tips) that the given bundle is going to approve\n* **`Timestamp`:** TX timestamp. It is actually UNIX timestamp (UTC)\n\n\nA process of sending IOTA transaction can be summarized in 5 steps:\n* To create transation(s) with the given attributes: *value*, *address* and potentially also *tag* or *message*\n* To finalize a bundle that includes all transactions. Once the bundle is finalized no new transactions can be added. It basically means to generate a *bundle hash*\n* To search for two tips in the Tangle that you are going to validate. There is not a strict rule how to search them but it is generally recommended to leave it on a *tip selection algorithm* implemented on node's side \n* To do a *Proof-of-Work* for each transaction in the bundle. Result of POW is *Nonce* and *Transaction hash* stored with each transaction\n* Finally you need to *broadcast* the whole bundle to the network\n\n### A secret of a bundle\nThere is a secret to be shared. You have to understand one important thing. Bundle is a top level construct that link all related transactions under one entity however the bundle itself is not broadcasted in fact. You still broadcast \"only\" collection of individual transactions instead. All transactions are recognized to be part of a bundle by the IOTA protocol however any data peering is based on individual transactions (in trytes).\n\nIn other words, a bundle can be reconstructed anytime from a collection of transactions via fields `bundle hash`, `current index` and `last index`.\n\n## Non-value transactions\nLet's start with non-value transactions (meta transactions) first since they are a bit easier for starters.\n\n*Please note, the chapter is divided in two separate sections. In the first section, examples are really close to bare metal (still not too close:) to illustrate the whole process and describing implementation details wherever possible. It is also useful when you want to experiment with different settings at each step (hey \"non-existing tips\", looking at you).*\n\n*In the second section, IOTA-facing libraries are fully levearged since they are capable to hide all implementation details behind a curtain. Needless to say, if you are not interested in such details then you would probably like to start with the second section.*\n\n### Creating and broadcasting transaction in 5 steps (you want to understand the process)\n#### Create a transaction\nFirst of all let's create transactions (offline; in memory) and set main fields.\n\nBTW: `Timestamp` field is defined automatically by the IOTA-facing libraries in the process. It is important field while creating `bundle hash`.\n\nIn the examples within this chapter we are going to broadcast meta transactions (data only) to two different IOTA addresses.\n\n\n```python\nimport iota\nfrom datetime import datetime\nfrom pprint import pprint\n\nMySeed = b\"HGW9HB9LJPYUGVHNGCPLFKKPNZAIIFHZBDHKSGMQKFMANUBASSMSV9TAJSSMPRZZU9SFZULXKJ9YLAIUA\"\nTargetAddress1 = b\"CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\"\nTargetAddress2 = b\"CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\"\n\nNowIs = datetime.now() # get a actual date & time - just to have some meaningfull info\n\n# preparing transactions\npt = iota.ProposedTransaction(address = iota.Address(TargetAddress1), # 81 trytes long address\n                              message = iota.TryteString.from_unicode('Here comes a first message. Now is %s' % (NowIs)),\n                              tag     = iota.Tag(b'HRIBEK999IOTA999TUTORIAL'), # Up to 27 trytes\n                              value   = 0)\n\npt2 = iota.ProposedTransaction(address = iota.Address(TargetAddress2), # 81 trytes long address\n                               message = iota.TryteString.from_unicode('Here comes a second message. Now is %s' % (NowIs)),\n                               tag     = iota.Tag(b'HRIBEK999IOTA999TUTORIAL'), # Up to 27 trytes\n                               value   = 0)\n# besides the given attributes, library also adds a transaction timestamp\n\nprint(\"Created transaction objects:\\n\")\npprint(vars(pt))\nprint(\"\\n\")\npprint(vars(pt2))\n```\n\n    Created transaction objects:\n    \n    {'_legacy_tag': None,\n     'address': Address(b'CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9'),\n     'attachment_timestamp': 0,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 0,\n     'branch_transaction_hash': TransactionHash(b'999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'bundle_hash': None,\n     'current_index': None,\n     'hash': None,\n     'is_confirmed': None,\n     'last_index': None,\n     'message': TryteString(b'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA'),\n     'nonce': Nonce(b'999999999999999999999999999'),\n     'signature_message_fragment': None,\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1530080759,\n     'trunk_transaction_hash': TransactionHash(b'999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'value': 0}\n    \n    \n    {'_legacy_tag': None,\n     'address': Address(b'CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW'),\n     'attachment_timestamp': 0,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 0,\n     'branch_transaction_hash': TransactionHash(b'999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'bundle_hash': None,\n     'current_index': None,\n     'hash': None,\n     'is_confirmed': None,\n     'last_index': None,\n     'message': TryteString(b'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA'),\n     'nonce': Nonce(b'999999999999999999999999999'),\n     'signature_message_fragment': None,\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1530080759,\n     'trunk_transaction_hash': TransactionHash(b'999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'value': 0}\n\n\n#### Finalizing bundle\nOnce all individual transactions are created it is time to prepare and finalize the bundle. While preparing the bundle you need at least to specify list of prepared transaction(s). In case of non-value transactions it is quite straightforward process. However, it is a bit more complicated in case of value transactions - please see later.\n\nFinalizing the bundle consists of several tasks under the hood:\n* Each transaction is indexed. Attributes `current_index` / `last_index` are set\n* `Bundle hash` is generated (*Sponge function* + normalization) and assigned to each transaction\n* `signatureMessageFragment` is bascially copy of `message` field in case of non-value transactions\n* PyOTA library also checks whether the data in `message` field is larger than transaction allows (2187 trytes). If this is the case then it takes care of it and split your data into several transactions\n\n*Please note, finalizing the bundle also means you are no longer able to add new transactions to the bundle post the finalization process.*\n\nSimply put, `bundle hash` is a cryptographic \"fingerprint\" of all transactions in the bundle. It uniquely represents them and so as long as transactions are the same (incl their particular order) the `bundle hash` is also the same.\n\n$$BundleHash = fce(address, value, legacy tag, timestamp, current index, last index)$$\n\nYou may be wondering what is a difference between `tag` and `legacy_tag`. `Tag` includes actualy the tag that was defined during the transaction creation. `Legacy_tag` is also based on it however it is modified during the normalization process while bundle hashing to be sure that `bundle hash` is can be securely used while TX signing. That's why the `bundle hash` is sometimes refered as `normalized bundle hash`.\n\nThe bundle refers to the first transaction in collection as `tail_transaction`. You can perceive `tail transaction` as an official representative of the whole bundle while checking for confirmation status, etc. Remember, the bundle is an atomic entity and so whatever is done to bundle it applies to ALL transactions within.\n\n\n```python\n# preparing bundle that consists of both transactions prepared in the previous example\npb = iota.ProposedBundle(transactions=[pt,pt2]) # list of prepared transactions is needed at least\n\n# generate bundle hash using sponge/absorb function + normalize bundle hash + copy bundle hash into each transaction / bundle is finalized\npb.finalize()\n\n#bundle is finalized, let's print it\nprint(\"\\nGenerated bundle hash: %s\" % (pb.hash))\nprint(\"\\nTail Transaction in the Bundle is a transaction #%s.\" % (pb.tail_transaction.current_index))\n        \nprint(\"\\nList of all transactions in the bundle:\\n\")\nfor txn in pb:\n    pprint(vars(txn))\n    print(\"\")\n\n```\n\n    \n    Generated bundle hash: TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADW\n    \n    Tail Transaction in the Bundle is a transaction #0.\n    \n    List of all transactions in the bundle:\n    \n    {'_legacy_tag': Tag(b'PVIBEK999IOTA999TUTORIAL999'),\n     'address': Address(b'CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9'),\n     'attachment_timestamp': 0,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 0,\n     'branch_transaction_hash': TransactionHash(b'999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'bundle_hash': BundleHash(b'TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADW'),\n     'current_index': 0,\n     'hash': None,\n     'is_confirmed': None,\n     'last_index': 1,\n     'message': TryteString(b'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA'),\n     'nonce': Nonce(b'999999999999999999999999999'),\n     'signature_message_fragment': Fragment(b'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1530080759,\n     'trunk_transaction_hash': TransactionHash(b'999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'value': 0}\n    \n    \n    {'_legacy_tag': None,\n     'address': Address(b'CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW'),\n     'attachment_timestamp': 0,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 0,\n     'branch_transaction_hash': TransactionHash(b'999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'bundle_hash': BundleHash(b'TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADW'),\n     'current_index': 1,\n     'hash': None,\n     'is_confirmed': None,\n     'last_index': 1,\n     'message': TryteString(b'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA'),\n     'nonce': Nonce(b'999999999999999999999999999'),\n     'signature_message_fragment': Fragment(b'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1530080759,\n     'trunk_transaction_hash': TransactionHash(b'999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'value': 0}\n    \n    \n\n\nAt this stage you can also see how does our finalized bundle look encoded in Trytes so far. It is also a proof that there is no bundle to be broadcasted itself, only list of transations matter.\n\n\n```python\nTrytes = pb.as_tryte_strings() # bundle as trytes\npprint(Trytes)\n\n```\n\n    [TransactionTrytes(b'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW999999999999999999999999999HRIBEK999IOTA999TUTORIAL999TFDCQZD99A99999999A99999999TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADW999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999HRIBEK999IOTA999TUTORIAL999999999999999999999999999999999999999999999999999999999'),\n     TransactionTrytes(b'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9999999999999999999999999999PVIBEK999IOTA999TUTORIAL999TFDCQZD99999999999A99999999TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADW999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999HRIBEK999IOTA999TUTORIAL999999999999999999999999999999999999999999999999999999999')]\n\n\n#### Selecting two tips\nAs mentioned earlier you need to find two tips that you are going to validate together with your bundle for a sake of network participation. This will be outsourced to an IOTA node and so it will be for the first time we interact with the network (via API call `get_transactions_to_approve`).\n\nThere is a `depth` parameter needed. It instructs a node how many milestones it should go in the past while confirming tips. The higher value the better to network however more resources needed. `Depth=3` is considered to be well-balanced compromise. Higher value than `depth=10` will probably throw an exception depending on node's configuration.\n\nIt should return two selected tips as `branch` and `trunk` transactions. Those transactions will be used while broadcasting the bundle.\n\n\n```python\napi = iota.Iota(\"https://nodes.thetangle.org:443\") # selecting IOTA node\n\ngta = api.get_transactions_to_approve(depth=3) # get tips to be approved by your bundle\npprint(gta)\n\n\n```\n\n    {'branchTransaction': TransactionHash(b'KQBDDBHWHVLQSJFENGWRBHIOULOMC9GXDW99ECMVFHZXGFZQJOXATSMDLYQJFBZCXA9IJ9SQUXAFZ9999'),\n     'duration': 1700,\n     'fieldName': 'F-Node Montabaur',\n     'fieldPublicId': '1bdeeb759f960554',\n     'fieldVersion': '0.1.6',\n     'trunkTransaction': TransactionHash(b'RRYDZLPS9IWCSWRROPQQJTKBRONOJNLUHVHFXFEOZAVGFEOUAHXWWHJSHAGWSSNSMWHN9SEYNBOEA9999')}\n\n\n#### Performin' POW\n*Proof of work* is a relatively simple cryptograhic puzzle to be solved. It represents energy-based costs of your transaction. It also helps to minimize risks of some attack vectors to the network.\n\nThis task can be also outsourced to IOTA nodes. In order to perform it you need *selected tips*, *finalized bundle* (in trytes) and also `Minimum Weight Magnitude` parameter. This parameter defines how diffciult the given cryptographic puzzle should be to be accepted by the network. As of now, you should set at least `min_weight_magnitude=14` in case of mainnet.\n\nPlease note, POW is performed per each transaction and so it can take some time. That's why it is not recommended to have more than 30 transactions in a bundle.\n\nOnce succesfully performed, the modified bundle (list of all transactions in trytes) is returned in order to be broadcasted.\n\nSpecifically:\n* Fields `nonce` and `transaction hash` are calculated per each transaction\n* `Trunk` and `Branch` tips are correctly mapped among transactions within the bundle. Check that `trunk` of the first TX refers to the second TX, etc.\n\n\n```python\nprint(\"Performing POW... Wait please...\\n\")\natt = api.attach_to_tangle(trunk_transaction=gta['trunkTransaction'], # first tip selected\n                           branch_transaction=gta['branchTransaction'], # second tip selected\n                           trytes=Trytes, # our finalized bundle in Trytes\n                           min_weight_magnitude=14) # MWMN\npprint(att)\n```\n\n    Performing POW... Wait please...\n    \n    {'duration': 12267,\n     'fieldName': 'iota-fn01.sairai.de',\n     'fieldPublicId': '45f52c5a2e829a00',\n     'fieldVersion': '0.1.6',\n     'trytes': [TransactionTrytes(b'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9999999999999999999999999999PVIBEK999IOTA999TUTORIAL999TFDCQZD99999999999A99999999TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADWNNNY9QAGVOOGTCIGBBEPIYISUZKNJYUQMROBTZARQVPHONNLQNQFAHTBNXMYWDFHAHMNRJ9URLKX99999RRYDZLPS9IWCSWRROPQQJTKBRONOJNLUHVHFXFEOZAVGFEOUAHXWWHJSHAGWSSNSMWHN9SEYNBOEA9999HRIBEK999IOTA999TUTORIAL999RLISAKGKE999999999L99999999QRZIERPEJFLKTIVKEBQIHJXTAX9'),\n                TransactionTrytes(b'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW999999999999999999999999999HRIBEK999IOTA999TUTORIAL999TFDCQZD99A99999999A99999999TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADWRRYDZLPS9IWCSWRROPQQJTKBRONOJNLUHVHFXFEOZAVGFEOUAHXWWHJSHAGWSSNSMWHN9SEYNBOEA9999KQBDDBHWHVLQSJFENGWRBHIOULOMC9GXDW99ECMVFHZXGFZQJOXATSMDLYQJFBZCXA9IJ9SQUXAFZ9999HRIBEK999IOTA999TUTORIAL999GDVSAKGKE999999999L99999999OOLRWTCMJMIQIAUVWBY9TVMZAJJ')]}\n\n\nYou can eventually also preview what specific fields have been modified using transaction objects. The bundle is ready to be broadcasted and so it also show you all fields/values that will be stored in the network.\n\n\n```python\n# show what has been broadcasted - hash transaction + nonce (POW)\nprint(\"Final bundle including POW and branch/trunk transactions:\\n\")\nfor t in att['trytes']:\n    pprint(vars(iota.Transaction.from_tryte_string(t)))\n    print(\"\")\n```\n\n    Final bundle including POW and branch/trunk transactions:\n    \n    {'_legacy_tag': Tag(b'PVIBEK999IOTA999TUTORIAL999'),\n     'address': Address(b'CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9'),\n     'attachment_timestamp': 1530081729891,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 12,\n     'branch_transaction_hash': TransactionHash(b'RRYDZLPS9IWCSWRROPQQJTKBRONOJNLUHVHFXFEOZAVGFEOUAHXWWHJSHAGWSSNSMWHN9SEYNBOEA9999'),\n     'bundle_hash': BundleHash(b'TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADW'),\n     'current_index': 0,\n     'hash': TransactionHash(b'SYDECKQB9BHWFUYOZMANREHOCXHCOPY9JCSZSNIZRNDJTZXHHSESCCLQOENGRVFLDMNXYAHHEWRDZ9999'),\n     'is_confirmed': None,\n     'last_index': 1,\n     'nonce': Nonce(b'QRZIERPEJFLKTIVKEBQIHJXTAX9'),\n     'signature_message_fragment': Fragment(b'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1530080759,\n     'trunk_transaction_hash': TransactionHash(b'NNNY9QAGVOOGTCIGBBEPIYISUZKNJYUQMROBTZARQVPHONNLQNQFAHTBNXMYWDFHAHMNRJ9URLKX99999'),\n     'value': 0}\n    \n    {'_legacy_tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'address': Address(b'CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW'),\n     'attachment_timestamp': 1530081719485,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 12,\n     'branch_transaction_hash': TransactionHash(b'KQBDDBHWHVLQSJFENGWRBHIOULOMC9GXDW99ECMVFHZXGFZQJOXATSMDLYQJFBZCXA9IJ9SQUXAFZ9999'),\n     'bundle_hash': BundleHash(b'TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADW'),\n     'current_index': 1,\n     'hash': TransactionHash(b'NNNY9QAGVOOGTCIGBBEPIYISUZKNJYUQMROBTZARQVPHONNLQNQFAHTBNXMYWDFHAHMNRJ9URLKX99999'),\n     'is_confirmed': None,\n     'last_index': 1,\n     'nonce': Nonce(b'OOLRWTCMJMIQIAUVWBY9TVMZAJJ'),\n     'signature_message_fragment': Fragment(b'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1530080759,\n     'trunk_transaction_hash': TransactionHash(b'RRYDZLPS9IWCSWRROPQQJTKBRONOJNLUHVHFXFEOZAVGFEOUAHXWWHJSHAGWSSNSMWHN9SEYNBOEA9999'),\n     'value': 0}\n    \n\n\n#### Broadcasting\nNow it is time to broadcast the given bundle to the network. List of all transations in trytes returned from the previous step is only thing needed.\n\nOnce succesfully broadcasted it returns the same input bundle as a confirmation.\n\n\n```python\nprint(\"Broadcasting transaction...\")\nres = api.broadcast_and_store(att['trytes'])\npprint(res)\n```\n\n    Broadcasting transaction...\n    {'trytes': [TransactionTrytes(b'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9999999999999999999999999999PVIBEK999IOTA999TUTORIAL999TFDCQZD99999999999A99999999TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADWNNNY9QAGVOOGTCIGBBEPIYISUZKNJYUQMROBTZARQVPHONNLQNQFAHTBNXMYWDFHAHMNRJ9URLKX99999RRYDZLPS9IWCSWRROPQQJTKBRONOJNLUHVHFXFEOZAVGFEOUAHXWWHJSHAGWSSNSMWHN9SEYNBOEA9999HRIBEK999IOTA999TUTORIAL999RLISAKGKE999999999L99999999QRZIERPEJFLKTIVKEBQIHJXTAX9'),\n                TransactionTrytes(b'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAWAABEAUA9BDBWAZADBZACBSAXAVAABXAABWA99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW999999999999999999999999999HRIBEK999IOTA999TUTORIAL999TFDCQZD99A99999999A99999999TL9EHBGBIDCTLCARLPKBSUQIG9CKQPDGTLOVNLG9TALAGEWQRBEK9DPLDDBGOAZIREKGYPYFCWJCTOADWRRYDZLPS9IWCSWRROPQQJTKBRONOJNLUHVHFXFEOZAVGFEOUAHXWWHJSHAGWSSNSMWHN9SEYNBOEA9999KQBDDBHWHVLQSJFENGWRBHIOULOMC9GXDW99ECMVFHZXGFZQJOXATSMDLYQJFBZCXA9IJ9SQUXAFZ9999HRIBEK999IOTA999TUTORIAL999GDVSAKGKE999999999L99999999OOLRWTCMJMIQIAUVWBY9TVMZAJJ')]}\n\n\nYou can check the broadcasted bundle via The Tangle Explorer at any of the receiving addresses:\n* Target address 1: https://thetangle.org/address/CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\n* Target address 2: \nhttps://thetangle.org/address/CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\n\n### Creating and broadcasting transaction in a single call (you want send a transaction quickly)\nAs mentioned above, IOTA-facing libraries are able to encapsulate all implementation details and so you do not need to care of them anymore. It is usually based on *extended API calls* that were proposed to be included by IOTA Foundation to make developer's life easier (https://github.com/iotaledger/wiki/blob/master/api-proposal.md).\n\nEven if using extended API calls you can still slightly control a level of your involvement in the whole process. From almost no involvement and fully automatic (`send_transfer()`) to semi-manual approach discussed above.\n\n\n\nThere are some specifics you should consider while designing your app:\n* You are loosing a bit of control of individual steps of the process and you have to rely of some predefined parameters (tip selection algo, etc.)\n* If there is an exception raised during the process then you need to go back at beginning and restart the whole process again\n\nSo it is basically your call to decide what works best for you.\n\nNow back to our exercise. Here comes a code that basically broadcasts transactions in a single call (`send_transfer()`) and you do not have to care of any implemenation details that are hidden under the hood.\n\n\n```python\nimport iota\nfrom datetime import datetime\nfrom pprint import pprint\n\nMySeed = b\"HGW9HB9LJPYUGVHNGCPLFKKPNZAIIFHZBDHKSGMQKFMANUBASSMSV9TAJSSMPRZZU9SFZULXKJ9YLAIUA\"\nTargetAddress1 = b\"CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\"\nTargetAddress2 = b\"CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\"\n\nNowIs = datetime.now() # get a actual date & time - just to have some meaningfull info\n\n# preparing transactions\npt = iota.ProposedTransaction(address = iota.Address(TargetAddress1), # 81 trytes long address\n                              message = iota.TryteString.from_unicode('Here comes a first message. Now is %s' % (NowIs)),\n                              tag     = iota.Tag(b'HRIBEK999IOTA999TUTORIAL'), # Up to 27 trytes\n                              value   = 0)\n\npt2 = iota.ProposedTransaction(address = iota.Address(TargetAddress2), # 81 trytes long address\n                               message = iota.TryteString.from_unicode('Here comes a second message. Now is %s' % (NowIs)),\n                               tag     = iota.Tag(b'HRIBEK999IOTA999TUTORIAL'), # Up to 27 trytes\n                               value   = 0)\n# besides the given attributes, library also adds a transaction timestamp\n\n\napi = iota.Iota(\"https://nodes.thetangle.org:443\")\n\nprint(\"Preparing/Broadcasting... Wait please...\")\n# the whole process initiated in a single call\nFinalBundle = api.send_transfer(depth=3,\n                                transfers=[pt,pt2],\n                                min_weight_magnitude=14)['bundle'] # it returns a dictionary with a bundle object\n    \n#bundle is broadcasted, let's print it\nprint(\"\\nGenerated bundle hash: %s\" % (FinalBundle.hash))\nprint(\"\\nTail Transaction in the Bundle is a transaction #%s.\" % (FinalBundle.tail_transaction.current_index))\n        \nprint(\"\\nList of all transactions in the bundle:\\n\")\nfor txn in FinalBundle:\n    pprint(vars(txn))\n    print(\"\")\n```\n\n    Preparing/Broadcasting... Wait please...\n    \n    Generated bundle hash: AEFTRFKZLIFXSQCBLJOEDKYKPHSJD9UZFFAYVYELHKYVDRKXQKOKQTOCLBLCLEODRGZPUAWOXSFHJEPOW\n    \n    Tail Transaction in the Bundle is a transaction #0.\n    \n    List of all transactions in the bundle:\n    \n    {'_legacy_tag': Tag(b'ECIBEK999IOTA999TUTORIAL999'),\n     'address': Address(b'CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9'),\n     'attachment_timestamp': 1532100908930,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 3812798742493,\n     'branch_transaction_hash': TransactionHash(b'SCVPZOUXDBIV9AJBVEE9SRLWWJZIXRKWHFMI9HDNZ9D9YPRLAFVIJ9OJZQWUXMOTMCQRBTMM9CRK99999'),\n     'bundle_hash': BundleHash(b'AEFTRFKZLIFXSQCBLJOEDKYKPHSJD9UZFFAYVYELHKYVDRKXQKOKQTOCLBLCLEODRGZPUAWOXSFHJEPOW'),\n     'current_index': 0,\n     'hash': TransactionHash(b'SVZ99MALQGVFHPONJTHRPPLIFBJWJWJTEHOGWTFRPZGDSPDKEUCIWLGPNKEFXLAGXEODSBBETKBP99999'),\n     'is_confirmed': None,\n     'last_index': 1,\n     'nonce': Nonce(b'WRMXCTEXLGCMUZJOBSCMHNQD9VS'),\n     'signature_message_fragment': Fragment(b'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUAABRAWAUAEAVAABDBXAZADBUAUASAVABBUAUACBUA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1532100900,\n     'trunk_transaction_hash': TransactionHash(b'CVRWTIPJHU9DOIZUNMEIOCPPMITKILETO9QALYEZCULKRD9ALIUYYQFYWPJEMYGBSNS9WUAHGCHEZ9999'),\n     'value': 0}\n    \n    {'_legacy_tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'address': Address(b'CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW'),\n     'attachment_timestamp': 1532100903056,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 3812798742493,\n     'branch_transaction_hash': TransactionHash(b'XUBGHJCEBSJXQYQJHBFBCVLVFLAM9SXLDFJJRRQISEXJJXCMNCRDXJABTHZEDW9RZWBWALDXAQCRA9999'),\n     'bundle_hash': BundleHash(b'AEFTRFKZLIFXSQCBLJOEDKYKPHSJD9UZFFAYVYELHKYVDRKXQKOKQTOCLBLCLEODRGZPUAWOXSFHJEPOW'),\n     'current_index': 1,\n     'hash': TransactionHash(b'CVRWTIPJHU9DOIZUNMEIOCPPMITKILETO9QALYEZCULKRD9ALIUYYQFYWPJEMYGBSNS9WUAHGCHEZ9999'),\n     'is_confirmed': None,\n     'last_index': 1,\n     'nonce': Nonce(b'FXXJWXQEMJFJMNRIWULHJDPFVRI'),\n     'signature_message_fragment': Fragment(b'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUAABRAWAUAEAVAABDBXAZADBUAUASAVABBUAUACBUA99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1532100900,\n     'trunk_transaction_hash': TransactionHash(b'SCVPZOUXDBIV9AJBVEE9SRLWWJZIXRKWHFMI9HDNZ9D9YPRLAFVIJ9OJZQWUXMOTMCQRBTMM9CRK99999'),\n     'value': 0}\n    \n\n\nYou can check the broadcasted bundle via The Tangle Explorer at any of the receiving addresses:\n* Target address 1: https://thetangle.org/address/CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\n* Target address 2: \nhttps://thetangle.org/address/CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\n\nAnd to complete the picture here is addtional code that uses `prepare_transfer()` and `send_trytes()` combo.\n\n\n```python\nimport iota\nfrom datetime import datetime\nfrom pprint import pprint\n\nMySeed = b\"HGW9HB9LJPYUGVHNGCPLFKKPNZAIIFHZBDHKSGMQKFMANUBASSMSV9TAJSSMPRZZU9SFZULXKJ9YLAIUA\"\nTargetAddress1 = b\"CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\"\nTargetAddress2 = b\"CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\"\n\nNowIs = datetime.now() # get a actual date & time - just to have some meaningfull info\n\n# preparing transactions\npt = iota.ProposedTransaction(address = iota.Address(TargetAddress1), # 81 trytes long address\n                              message = iota.TryteString.from_unicode('Here comes a first message. Now is %s' % (NowIs)),\n                              tag     = iota.Tag(b'HRIBEK999IOTA999TUTORIAL'), # Up to 27 trytes\n                              value   = 0)\n\npt2 = iota.ProposedTransaction(address = iota.Address(TargetAddress2), # 81 trytes long address\n                               message = iota.TryteString.from_unicode('Here comes a second message. Now is %s' % (NowIs)),\n                               tag     = iota.Tag(b'HRIBEK999IOTA999TUTORIAL'), # Up to 27 trytes\n                               value   = 0)\n# besides the given attributes, library also adds a transaction timestamp\n\n\napi = iota.Iota(\"https://nodes.thetangle.org:443\")\n\n# Creating bundle, preparing inputs and finalizing bundle. It returns trytes of prepared TXs\nTrytes = api.prepare_transfer(transfers=[pt,pt2]) \n    \nprint(\"Almost prepared bundle - tips and POW are still missing\")\npprint(Trytes)\n    \nprint(\"\\nSearching for tips and performing POW... Wait please...\")\nResult = api.send_trytes(trytes=Trytes[\"trytes\"],\n                         depth=3) # Searching for tips, performing POW and broadcasting\n\nprint(\"Bundle was broadcasted.\")\n  \nprint(\"\\nFinal transactions were returned - including nonce (POW)\")\npprint(Result)\n```\n\n    Almost prepared bundle - tips and POW are still missing\n    {'trytes': [TransactionTrytes(b'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAXAUAEAUAABDBXAXADBYA9BSAXAYAWAWAZAYA99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW999999999999999999999999999HRIBEK999IOTA999TUTORIAL999JINQRZD99A99999999A99999999CMRQYFTKZ9DANXOBEBKCIX9UBEIAWJJYFOXXSASFGUHOESLINSHF9TYDKTH9YDYLPQHWIUY9HDF9GWLLC999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999HRIBEK999IOTA999TUTORIAL999999999999999999999999999999999999999999999999999999999'),\n                TransactionTrytes(b'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAXAUAEAUAABDBXAXADBYA9BSAXAYAWAWAZAYA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9999999999999999999999999999RTIBEK999IOTA999TUTORIAL999JINQRZD99999999999A99999999CMRQYFTKZ9DANXOBEBKCIX9UBEIAWJJYFOXXSASFGUHOESLINSHF9TYDKTH9YDYLPQHWIUY9HDF9GWLLC999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999HRIBEK999IOTA999TUTORIAL999999999999999999999999999999999999999999999999999999999')]}\n    \n    Searching for tips and performing POW... Wait please...\n    Bundle was broadcasted.\n    \n    Final transactions were returned - including nonce (POW)\n    {'trytes': [TransactionTrytes(b'RBTCFDTCEARCCDADTCGDEAPCEAUCXCFDGDHDEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAXAUAEAUAABDBXAXADBYA9BSAXAYAWAWAZAYA9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9999999999999999999999999999RTIBEK999IOTA999TUTORIAL999JINQRZD99999999999A99999999CMRQYFTKZ9DANXOBEBKCIX9UBEIAWJJYFOXXSASFGUHOESLINSHF9TYDKTH9YDYLPQHWIUY9HDF9GWLLCYLURVDFXJWJRPTUHGRXSW9RPMZKPWBQWSHSSHRKGSJMDMLTPTENNGDBMEOGKUXDPGKFYUHIRTBCPZ9999ALYKPSMJNIXJGKOVORRLEOWGUSERFODOQZFBAHRBHMGWKIJ9WOFOHJCJDTQQPICAKJM9JFIBJAHFZ9999HRIBEK999IOTA999TUTORIAL999HW9HHBHKE999999999L99999999DLOEWKSWVGN9CVDUKAXTTEDBGHR'),\n                TransactionTrytes(b'RBTCFDTCEARCCDADTCGDEAPCEAGDTCRCCDBDSCEAADTCGDGDPCVCTCSAEAXBCDKDEAXCGDEAWAUAVABBRAUA9BRAXAUAEAUAABDBXAXADBYA9BSAXAYAWAWAZAYA99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW999999999999999999999999999HRIBEK999IOTA999TUTORIAL999JINQRZD99A99999999A99999999CMRQYFTKZ9DANXOBEBKCIX9UBEIAWJJYFOXXSASFGUHOESLINSHF9TYDKTH9YDYLPQHWIUY9HDF9GWLLCALYKPSMJNIXJGKOVORRLEOWGUSERFODOQZFBAHRBHMGWKIJ9WOFOHJCJDTQQPICAKJM9JFIBJAHFZ9999WVJQWHI9JHXRIZETFPYTDCZ9LLSSDGUIVVUKSDEFDWUTYJSBNXFFOHTVLFXBENLYVZBARO9WNXOGZ9999HRIBEK999IOTA999TUTORIAL999JDXHHBHKE999999999L99999999ZVTKMTIN9VFLWYQCPBMZVRMBMJE')]}\n\n\nYou can check the broadcasted bundle via The Tangle Explorer at any of the receiving addresses:\n* Target address 1: https://thetangle.org/address/CXDUYK9XGHC9DTSPDMKGGGXAIARSRVAFGHJOCDDHWADLVBBOEHLICHTMGKVDOGRU9TBESJNHAXYPVJ9R9\n* Target address 2: \nhttps://thetangle.org/address/CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW\n\n## Value transactions\nMeta transactions were discussed in the previous chapter. This chapter describes `value transactions` which are transactions that transfer IOTA tokens between IOTA addresses. Tokens are fully premined and so number of tokens in the network is given. So `transfering tokens` means changing their ownership only.\n\nWhile preparing a bundle with `value transations` it is important to distinguish three different transaction types within a bundle:\n* **Input TXs:** those are transactions that *deducting* (spending) value from address(es). Those transactions have negative `value` field. They usually refer to `senders`\n* **Output TXs:** those are transactions that *adding* (receiving) value to address(es). Those transactions have positive `value` field. They usually refer to `recipients`\n* **Unspent/change TX:** technically speaking it is also *output* transaction that *adding* value however it usually refers to `senders` and so it is better to consider it separated from other output TXs\n\nAll three types have to be part of each bundle otherwise you are under a risk of loosing IOTA tokens. In other words, each bundle should consists of at least one `input` TX, one `output` TX and one `unspent` TX. Total balance of the bundle should be zero since the number of tokens is the same, just token owners have been \"changed\".\n\nExample:\n* Alice owns 100 tokens (*input = 100*)\n* Alice is going to send 20 tokens to John from the address that includes 100 tokens of her (*Alice -100*)\n* John is going to receive 20 tokens from Alice (*output = 20*; *John +20*)\n* Alice still owns 80 tokens after the transaction (*unspent = 80*; *Alice +80*)\n\nAlice's bundle should look like:\n\\begin{align}\nInput - Output & = \\ Unspent \\\\\nInput - Output - Unspent & = \\ 0 \\\\\n100 - 20 - 80 & = \\ 0\n\\end{align}\n\nWhy Alice has to \"put\" all 100 tokens in the bundle while she is going to actually spend only 20 tokens? The reason is that IOTA protocol uses one-time signature scheme (OTS) for transaction signing while spending tokens. And with every signing process a half of a private key of the given address is revealed. That's why no one should ever spend tokens from the same address again.\n\n\n### Spending tokens\n*Please note: for a purpose of this chapter we are going to switch to a test network called `devnet`. It is the testing Tangle. Tokens are not real and everything you do have no implication to the mainnet at all. However it is stil powered by standard node software and so technicaly speaking it behaves like the mainnet. If you need more info regarding devnet please refer to [the official documentation](https://docs.iota.org/introduction/testnet/introduction).*\n\nEverything what has been mentioned in the previous chapter focused on `non-value` transations is still valid also in case of value transactions however there are several additional tasks you should take care of. Needless to say, IOTA libraries (PyOTA and others) are ready to help you and are able to hide all implementation details in case you would like to. In this case I would encourage everyone to prefer a functionality that is offered by extended API calls, such as `send_transfer`. Experimenting with value transactions and trying to tweak them does not seem to be a good idea (on the mainnet).\n\nAnyway, even in this chapter I am going to describe main tasks that are performed under the hood to be able to understand the whole concept.\n\nLet's have the following setup:\n\n\n```python\nimport iota\nfrom pprint import pprint\n\n# Sender's side ***********\n# Sender's seed\nSeedSender = b\"HGW9HB9LJPYUGVHNGCPLFKKPNZAIIFHZBDHKSGMQKFMANUBASSMSV9TAJSSMPRZZU9SFZULXKJ9YLAIUA\"\n\n# Receiver's side ***********\n# Recipient's seed - this is actually not needed for the exercise - it is just to have corresponding seed somewhere written\nSeedReceiver = b\"NVPDKGLESTYNJEH9DTWD9DUBYWHZJDDWTBLKWEYLVZKBKKAZTIZ9CFFJMHPEKIFUWQTXRGAVRXAQZCPHL\"\n\n# This is our target address to which we are going to send tokens to (BTW: it is a first generated address based on recipient's seed)\nAddressReceiver = b\"BMFSMZMNBGKHAWPIZIOMJGRBXZETVSAYDSTDQCHLYTBWZMIXLNXF9XHLTMOCATFVFOMBQF9IOQGPEBPDC\"\n\n#DevNet node - Devnet Tangle that is used only for testing/dev purposes - no real tokens here:(\nDevnetNode = \"https://nodes.devnet.iota.org:443\"\n\nprint(\"Variables were initialized.\")\n```\n\n    Variables were initialized.\n\n\nYou may be wondering why only the seed for sender's side is defined. As mentioned above the reason is that the address with tokens is changing with every spending exercise and so you have to find address with tokens that left in a bucket programatically (if any tokens left:).\n\nLet's find out. For this purpose you can use extended API call `get_account_data` which returns a list of used addresses and total sum of all tokens available accross all of them:\n\n\n```python\napi = iota.Iota(DevnetNode,\n                seed=SeedSender # let's use seed of the sender and so library can do all hard work\n               )\n\nprint(\"Checking for total balance. This may take some time...\")\n\n# now we can find out whether there are any tokens left\nSenderBalance = api.get_account_data(start=30, #starting from 30th address to save time\n                                    stop=None) # Get the total available balance for the given seed and all related used addresses\n\nprint(\"\\nPlease note, this may take some time if many addresses has been used already...\")\npprint(SenderBalance)\n\nif SenderBalance['balance']>0:\n    print(\"\\nYes, there are some tokens available! hurray\")\n```\n\n    Checking for total balance. This may take some time...\n    \n    Please note, this may take some time if many addresses has been used already...\n    {'addresses': [Address(b'OTJSUNSQ9DLJVLKMVVPLDUTRHZAJDISDPZQCEPWNJWUGZOSFWRRBTUJAWCKKXACMZQIUP9NVVFYWRISWA'),\n                   Address(b'BGUDHNNYKGZWLBVIFCAGCSBWZRHXZSPT9NWLWFM9KLWCEPUGEDE9XRBOGFJLJCUJKQFILMIPGKZJYUAVW'),\n                   Address(b'AYYUYIMDUGBXQBKMVOA9XBKXICCMLVYZCPAAAUVPSDDBJSOZJIY9RVMPMEVMGJVEROVMDVVYQXXKRANSD'),\n                   Address(b'WHVPRFXYKBSIB9NYHWSGEWHLQYAIPLGIUIPGGIJNQYKKCWRMGLZNUIADZATOBCGBLBI99HYVQOHIFWRS9'),\n                   Address(b'SUYDJCMS9XMBKOPIPOXKGXMFVYXQ9YRNZLDYLRFARZFOFJDDH9JZLCQVO9GBRQKBCXHSPHOAPPWFFLMBW'),\n                   Address(b'NHVGPRAXYTDZJLMLSUMZGVBBMICDQGGAAZ9UJGLIPPOTUEZJXABCSDFUTRTBFOLDOQZIBS9QTRXAB9IUX'),\n                   Address(b'VZITIWJF99TH9REMKLYZUWELFLEW9FVYXPZPVMVFZVIQHAOEMEDABUUZGFROKKIVMT999PWGGLICKJOAD'),\n                   Address(b'XPV9CTUC9JEKATOVABXXLICTDAQEOHR9HXXFLHKN9OZFMFAZKKUDZMREOBZJONZAHXCGNN9FHGNFBAKMC'),\n                   Address(b'NDQMBGBQIBAQURVAQEUVONVMECKXSNYZZNKMMMOHOLPEYHJHDBTFWOZMAPFUAHLHIQUAV9GVZPEMBKL9Z'),\n                   Address(b'QYENROHVANIYBSIIMWGFDOUHXTMFOXIHOQXTJZLRFRJMOOINFTWCVVEJUFIITLBIHLVTESPVLUOSCFJDZ'),\n                   Address(b'SZAVDSKTHNQFWTTINRAYQKJAXTLD9CRFFWWBSEXIEXPLBBEP9FT9IVGICWIXTJCFUKJSTOUFANJGBTPQX')],\n     'balance': 3828,\n     'bundles': [<iota.transaction.base.Bundle object at 0x7f87d8de0390>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8dfc8d0>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8da8160>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8d97860>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8e03cf8>,\n                 <iota.transaction.base.Bundle object at 0x7f87d949b320>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8de4780>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8de2470>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8e06908>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8def048>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8dea6a0>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8dbe198>,\n                 <iota.transaction.base.Bundle object at 0x7f87d8df42e8>]}\n    \n    Yes, there are some tokens available! hurray\n\n\n*Please note: API call `get_account_data` consider only confirmed transactions while calculating total balance. So it is better to wait until all transactions are cleared before you send additional tokens.*\n\nAre there any tokens left (value in `balance` field)? If yes then continue - no action is needed.\nIf not, then you need to obtain some. It can be done visiting [IOTA faucet](http://faucet.devnet.iota.org) and entering an unused address of the given seed:\n\n\n```python\n# Now let's find a first unused address that can be used as a destination address for unspent/new tokens\n\nprint(\"\\nPlease note, this may take some time if many addresses has been used already...\")\nFreeAddressSender = api.get_new_addresses(index=30,\n                                          count=None, # If None is specified, then it identifies a first non-used address\n                                          security_level=2) # Let's generate an address using default security level=2.\n\nprint(\"\\nThis is the first unused address that can be used for new tokens or unspent tokens:\")\npprint(FreeAddressSender)\n\n```\n\n    \n    Please note, this may take some time if many addresses has been used already...\n    \n    This is the first unused address that can be used for new tokens or unspent tokens:\n    {'addresses': [Address(b'MHJIRKPUVSXBZWUXKUBNT9MRSEG9CRR9DNKIVNSCBZVGEDIDYTXIAVJLSTKQGVGDBFHRCRHBEMMZXPUFZ')]}\n\n\nWhat have just happened behind the curtain?\n* The PyOTA library started to generating addresses from the `index=0` of the given seed and at the same time it also checked whether there are any transactions registered for each address\n* If yes, then in case we are after balances, the balance is saved. In case we are after new unused address then the given address is skipped. First address for which there are not registered transactions is returned\n* That's why it may be quite time consuming. And now you also understand all issues regarding `zero balances` after the snapshot\n\nYou may be also wondering how to get individual balances for each used address? This can be checked using the core API call `get_balances` which provides you with a balance for any address you specify. Let's query for used addresses from the previous exercise:\n\n\n```python\n# only if there is any used addresses from the previous steps\n\n# it returns the balances as a list in the same order as the addresses were provided as input.\nif len(SenderBalance['addresses'])>0:\n    print(\"\\nSome positive balance identified. Individual confirmed balances per used addresses:\")\n    pprint(api.get_balances(addresses=SenderBalance['addresses'],\n                           threshold=100) # Confirmation threshold; official docs recommend to set it to 100\n           )\nelse:\n    print(\"\\nNo positive balance identified.\")\n```\n\n    \n    Some positive balance identified. Individual confirmed balances per used addresses:\n    {'balances': [0, 0, 0, 0, 0, 0, 0, 0, 0, 2979, 849],\n     'duration': 1,\n     'milestone': None,\n     'milestoneIndex': 1366125,\n     'references': ['BZXG9BLWNISGNFNUNPAZGPURMJUIAQPUAGAQJFVWOSTHINBVWVNGLWPKHI9WTAORCGUPCBCNHNIEQH999']}\n\n\nIt returns `balances` and you can see how the remaining tokens move to new unused address every time you spend some tokens. Needless to say, used addresses with zero balances should not be used anymore since tokens were already spent from them. So let's spend some tokens:\n\n\n```python\ntx1 = iota.ProposedTransaction( address = iota.Address(AddressReceiver), # 81 trytes long address\n                                message = None,\n                                tag     = iota.Tag(b'HRIBEK999IOTA999TUTORIAL'),\n                                value   = 10) # we are going to spend 10i\n\n# Sending the iotas\nprint(\"\\nSending iotas... Please wait...\")\nSentBundle = api.send_transfer(depth=3,\n                         transfers=[tx1], # one transaction defined above. It is an output TX that adds tokens\n                         inputs=None, # input address(es) that are used to finance the given transaction. Tokens will be deducted from them\n                         change_address=None, # this is the adddress to which unspent amount is sent\n                         min_weight_magnitude=9, # in case of Devnet it is 9\n                         security_level=2) # you need to specify security level to be sure library generate compatible addresses\n\n# you may be wondering why there is imputs=None and change_address=None.\n# It means it will be taken care by library and so make sure correct seed / security level was added while api initialization\n\nprint(\"\\nIt has been sent. Now let's see transactions that were sent:\")\n# let's check transactions that were sent in fact\n\nprint(\"Here is the bundle hash: %s\" % (SentBundle['bundle'].hash))\nfor tx in SentBundle['bundle']:\n    print(\"\\n\")\n    pprint(vars(tx))\n\n\n```\n\n    \n    Sending iotas... Please wait...\n    \n    It has been sent. Now let's see transactions that were sent:\n    Here is the bundle hash: K9CRAOLBJCT9CEAKJVZIKUIIUSVKJIZGHXPJVYRDPJ9IFSUJPGRYECUCLIFKHLHVSE9ZSABLAUTXQ9HPD\n    \n    \n    {'_legacy_tag': Tag(b'LUIBEK999IOTA999TUTORIAL999'),\n     'address': Address(b'BMFSMZMNBGKHAWPIZIOMJGRBXZETVSAYDSTDQCHLYTBWZMIXLNXF9XHLTMOCATFVFOMBQF9IOQGPEBPDC'),\n     'attachment_timestamp': 1570539229755,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 3812798742493,\n     'branch_transaction_hash': TransactionHash(b'FM9BAYPTXRETLTNOZJGDOZDVPNWTDFWHETXN9ALOXBOSJAKJZWCFIMAUNVFNEQHFCLELVBUKFKYIVO999'),\n     'bundle_hash': BundleHash(b'K9CRAOLBJCT9CEAKJVZIKUIIUSVKJIZGHXPJVYRDPJ9IFSUJPGRYECUCLIFKHLHVSE9ZSABLAUTXQ9HPD'),\n     'current_index': 0,\n     'hash': TransactionHash(b'HELRSWQUGBEYVUYDHGHTTQRKHWPGVTTFCOCJUXPKTSTZIVKBNPKTFMUMWAYVRVRHEBBKCFFTWEOPTX999'),\n     'is_confirmed': None,\n     'last_index': 3,\n     'nonce': Nonce(b'WONHBBPEDLHWRLGUPRFAWHDAEXB'),\n     'signature_message_fragment': Fragment(b'999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1570539041,\n     'trunk_transaction_hash': TransactionHash(b'KXBVBYKXCKHNUWAWWINEENG9A9T99ZGRAPPKSZWCASHSENHTBGMHZYLHGLVXFNPYMPOGJUHRQXWLRJ999'),\n     'value': 10}\n    \n    \n    {'_legacy_tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'address': Address(b'QYENROHVANIYBSIIMWGFDOUHXTMFOXIHOQXTJZLRFRJMOOINFTWCVVEJUFIITLBIHLVTESPVLUOSCFJDZ'),\n     'attachment_timestamp': 1570539229722,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 3812798742493,\n     'branch_transaction_hash': TransactionHash(b'FM9BAYPTXRETLTNOZJGDOZDVPNWTDFWHETXN9ALOXBOSJAKJZWCFIMAUNVFNEQHFCLELVBUKFKYIVO999'),\n     'bundle_hash': BundleHash(b'K9CRAOLBJCT9CEAKJVZIKUIIUSVKJIZGHXPJVYRDPJ9IFSUJPGRYECUCLIFKHLHVSE9ZSABLAUTXQ9HPD'),\n     'current_index': 1,\n     'hash': TransactionHash(b'KXBVBYKXCKHNUWAWWINEENG9A9T99ZGRAPPKSZWCASHSENHTBGMHZYLHGLVXFNPYMPOGJUHRQXWLRJ999'),\n     'is_confirmed': None,\n     'last_index': 3,\n     'nonce': Nonce(b'Q9AKQLCRMJCIHIBZCGJEFTFDCOY'),\n     'signature_message_fragment': Fragment(b'FJVNAC9ELWJZKXB99BEWPEAYVWLTCERBQM9AQPLPMYUJTSLARUCASCOSZHMFXAYSMVTYHXFKZZODWCXIZIHOEFYO9YNSVUTIA9SAEMOUIJXIVUPDEAQLZPSP9JCREYPTDWMXTQYRQGDEW9QJJUBBIUEPUCEVMYTYPWPCETJAHHPUCSEGLIWQXNRNNGKEYFMVGTQZUDJJICXLQDUNDCWXIPAGXMAVUBSEYWRRYMFBNLPW9YAZJXXLTZJ9EUJREYMSWTYRHDLNZEIPEDFGYMATPOTAYGTYJVSMJQUFS99JTAPRELWRETRJSBNRCN9JQQFBBXPAGZSRDLPERRWKGCCYLBHWGNRNUYHQXKTMALZNCHFXEQLN9QYQYXJGTDINBGIECFNFQWTKCBELCSJYI9IB9TTNZILAOBKOGNERVGIZCUUNGUYLICKVVREVHEGTCLVCSRXLFUQUAQJUGP9QHOFYGSNLDVLDQKDPFSTOYZQEFFTPUNJQFSWKEWLZUKQTJ9DZHMPHRHY9ABEUMKFZBIS9OPBIU9GQJALZDISKAKWT9I9ZIJSIVMGIAGXYRHEYBQUMSXXZCUEOJKRKCEQWDXZJQRAKBCCVWSRQMSP9RUESTPHEY9XS9NVCHIJYZ9WMNDLKSZQWZHWZOKVRBEQECLOFORIK9DYUDNMXDZRPIEHGEBIORNRQAIFMZKFUYXMXRLTJMNDXEYTWC9OAJLRDFPDB9PVXDHETPFYLARGHCMFRYGKMXFQNCMN9NMNQXTEDLDKPAWCKOEK9KYCLVL9JTNUJCCNHJGDKAUZTJIXSKNFMMDFVGX9JHGDR9DNQQHYH9MEZAVXYJDDJAZWJRGVHBKLIVARKHBDECPH9ZTLSHDMLOWNMHLSFHAESHPACXYDQ9XCOXZGPORYL9DGYDLBDWQI9KYKCCAVB9SUIJIRWOCNWPZDFJLNRMERONTSJTXMRQHWDVERYITAHIF9YILTYDTUAJPAMDLPHNPZYCXYAAMXQUVLIYUKNKBFRBM99IYB9JJAREWYVKEOPPBNZAGHXYD9OVWYHBJKRYLTZLFQRNOBFVFEYSPZYHTEWRPPWMNGCRGVPZOYYDUFDLN9HCEWCFNZCTLFSRKJNPYEKRSDPDBHGHQTFMCRRGE9XSPVMWWHXSBPWNFJJMDLQVRNXLLJACLSWMEEMGDQANJRWPYSTEYYJPTGCVMTAIGZCPKTTZKOAXWYXYWUEUGB9PCCTEIDPLTYLGISOOPDGAHIMQSLPDYKEKWEQILLUPJUGOIT9THGR9LQAJQNAEDCCGEUQWJHDGRPDWNSLFHIU9RNHEUKEADSUMWUFESQTTCGBPYEAHKQLPGTPRQGQCL9BWHZKLFNLAVBIKQADHWNVIFLACAMXEKKSDPTDEW9DISRNXWTNMBRTGDOMZLDJBDKLLKJVCRXNCUBTW9OGF9QJCBQLZTLWDEFJN9EDFTPSYDPKMFUL9VDYYNBXPFDZCVYFLFCXXXOCETLOOUCWNKORHOSLDGLDXPUJRGH9YGWUKZUPHRBEQLLHQFLMZVWQGXXQCQTDYLWUPPSQTVBOHWQNAYZVZ9UAMBOUJEQIVLYPUCHVEEZPPEYIOUVBQJDSMREJS9FSBBNVHOMCASBTXVFINJFPMGQOKCIJZYNKNQFJ9NPQLCPM9BTCIVBUFWPUYYXWDGKDZEQBGEEFAEWWLZXQXASHVGY9BGFMFBGDSAKMZSQFCUJEKVQTEYKZ9TNXAXPWY9PIVGFFZJFDLDDWFALQANBF9BNGISCDUZNEDYVQ9GSIQAANIFCDHDKNPPKGPBATWZDJMTYKZPJFEXFM9EBDAGXPGUPUBXNKVXX9XWXUEVLRFUOVXKXURDK9ZG9FHLZZZ9JIM9HOHSMMRUOIP9AKPZRNAOOGIZYIOIMNPFLIRXURVGJZJVUIYQMNSSPOGEBBSUPEVZMUNDQSQCZCVVFEBIKUUZHMONG9DZMFSKOKENSPRQSKYIEKUXCPQGWVGWJEJNJEUFRRHOZJFFT9WGVUQCOURVLHIUELYFZOEFCCOKWNGDJYXBWNZFATDPZRDCXJD9YT9VRLAAPQXGWFNGFCUAFPUMGSNCJXPNCCGGBAZMWCVTQMEWZUYOVBQKICIWGXBSFWXGQYLPMGWHPHIQUASXNBQOGDXCTSZETRSGURCZJNTVEMTKRPGBKITGPHUXWRVFD'),\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1570539137,\n     'trunk_transaction_hash': TransactionHash(b'DEKVWJZUMYHURTSQRZJMGZVZATELXYOGSUJTSSKNBPETPJZYCSN9WGCXQTANBAJDQQMXFMKJEITRBI999'),\n     'value': -2979}\n    \n    \n    {'_legacy_tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'address': Address(b'QYENROHVANIYBSIIMWGFDOUHXTMFOXIHOQXTJZLRFRJMOOINFTWCVVEJUFIITLBIHLVTESPVLUOSCFJDZ'),\n     'attachment_timestamp': 1570539229704,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 3812798742493,\n     'branch_transaction_hash': TransactionHash(b'FM9BAYPTXRETLTNOZJGDOZDVPNWTDFWHETXN9ALOXBOSJAKJZWCFIMAUNVFNEQHFCLELVBUKFKYIVO999'),\n     'bundle_hash': BundleHash(b'K9CRAOLBJCT9CEAKJVZIKUIIUSVKJIZGHXPJVYRDPJ9IFSUJPGRYECUCLIFKHLHVSE9ZSABLAUTXQ9HPD'),\n     'current_index': 2,\n     'hash': TransactionHash(b'DEKVWJZUMYHURTSQRZJMGZVZATELXYOGSUJTSSKNBPETPJZYCSN9WGCXQTANBAJDQQMXFMKJEITRBI999'),\n     'is_confirmed': None,\n     'last_index': 3,\n     'nonce': Nonce(b'LYQCYVY9MIALVUHHTNQUAOVBZMZ'),\n     'signature_message_fragment': Fragment(b'XJVSTWGWINBVVLAAZNSYQFAHKJIOVBBTHGHSFWXUKYO9QU9JYTXKCFCPLNHGAFHGYNRGP9ZIRLM9QI9JBPVYGGNUGWOO9LIYZRIPFRGQFDJBVPIMTBYDFVOHHAZXEHDY9ROBSOCCQEAMCODVAKJELMDA9SZFHXJWSXKLNXODY9GFGDPTTRSTJNIXRHUHVCJ99KPOVZVGDNBBJYIROBWJYIKKERYDPWLGBOGTPQEULYCD9JGBRQDBICHBNLBCSYFY9IT9PRKXCRGOVAF9XXXDM9ZHWYPNCSLYHMMKNPNBCWHTBAIDPJOZIFXMNPRLZTDHOGAYYBITYOSUQYTDUPLFCBXGQRWFQRPNNFZLGXERTPOORJZXJAXBIWRNOEOJKKKVTC9FLGKUVXQVRXOQQCDKXCEKMIKWWRLTKQBYHZMZZWLTAUHOUHXVFDSEHFTUHUYSLXXEGTZXLHKFUA9KACIQEHCVRVNWBZGFMOFSC9OWGPFATZMLYADGJYRARIRVYANWDVKMQCAAMVUOYDUIGQSZRRAUJSH9MDNIWZDQMTUSF9XGHZVCPBIQEJY9CEDYXROCPOQXF9XPUBYSIPBQDHB9QHJABIPILVIZMNGLWWGSOXLBICSMY9OHPBYKOBSXEFIYPOZLWDUXAWSLADZOF9SILPRYZKQKYKHTGZIJNJ9QBFIVFRNFNZAYYRAHMCHZJBMKUSDSKLEYXDIQASQPXLDAZDNVBXQZDADMQMYNHQQFXENTPRSBLBKFVFPPKNKXYIILMFWXYZZOLDFVAJCKQDDQNVYANQNG9DHKRSKMUOAYDDC9AHENC9RGHJXPH9OYLQZAKVRZFDOEQFQGBXZMKOEZQIYDJNNHHMDQXVEXBNBDDPQAJJDXIWFFGQATSW9WABRSYBPGGILGX9GSTJRXUNOTGPIFAUDATTFMXBCG9SGTIIIUGGMYNGKBDKSJXBIAIBFNR9TFEXLRCXTWWWMJIGCSGFAHRFFYACSWAGM9VZSHL9QZ9SSWMQGUPPFE9HWZWIXGHNACPTXRGPJUVK9DYPWEICZKPMCDAPYYPZJKLPWBKKT99APKTQICCKGZIWYNKPMNRYWVDBTEGJLCCIIXGXQVKOSUBJUPZJFCIMED9ROCOZQBDXEOTZAHJGHWUDGWBXCCUTMSMRREYPWJIQSGOIPHODFTUM9BSZGHPXYRJETJUEFXIICWFTWKXSKGKTWARKCQLYBIQHDDMVJF9LJOGBNZINDNUZQKNDAWZHBIISVCVDJGSJAQ9VASOSCDPMBLFSDHHAXMAKCJXIMVDNRYEPJFKJDICTRZDZWMQIZEPNWZDHZQHWWMMWFSDMRFSYLNNOMTAVKLEINGPYMFANWWLVYBTAGVSPJOMBWBZHEWXPBQUOWPUPACOQHPTA9DAHIRJKWTT9LLARKJIDMWXJNNGRPQQMFREIYXVLPELQAMIOGJ9CLOWRBYXWL9RUTDS9HQQWOFOSVWIQOYZBEDTBYLRL9SXPSCGDZJJWSBYBLKVIVVTTLIPVYZOCWMRYTTRYTA9UAIYMBPZZVJLVBJSRGKTMHCVAOSIFM99BQAUXKEWNCQLHGCUJSXLAJWAUMEYJZEEWATAGAWQPMMVTIPFQHXLORDHLOL9YMBUX9KWAZMFECXOLATKLVNYAOEYFBGTZDAZCJVSXLQIOZTHJXWDLOUBCOJFIVVRUIMXJHSRKPLBCQAAVVFYEHWKXXCMFUUP9VFU9EFFIDYUO9EVLPHIMOFDLTBVNRRLTLBDJOCWBZCSKXSIFZT9UZXQWTM9C9MLGRX9AIVCSAHEBGUBWPCCKBKUHQXDKYUQRK9NDTPPTRCBRGTIFNQCEEFFYNCDWINFPCNTISELIKFEF9CJBFDHOLKBVZNLJJFGLHAWMMURTNFLVJAOAOQEZKM9DQXEVNSPBMXGVCCWNKICEMJNWC9XDFLKVKZWPECGHOTIXG9ENJNBSQFKLKCNPG9LADRSOJIAEXPAQKUNQMMXM9ARQNT9GUWHJEEZNTQDVDNZOE9ABOTUWJTCYYOMSTOXXCBVEMODRKFKO9ANDKBYFRITYZ9LTJKELWSYCEYPOPGMUHJUYFVDLWMDZOKR9WDQLMIMH9IUXQJGQROXDJDJNJHQAYYURURTRHECNGPRUAQIK99YA9EU9MSEABDGJGLIHJDMQUSNTKZRCORVYIXWFPHKVX'),\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1570539137,\n     'trunk_transaction_hash': TransactionHash(b'AYRWHKRNVKYQTPRBEOLHDBTIPEVNNGUJKKFHR9HZYUP9XZPMBTOKEXCJXLAWXODKBXGNGIWEUMEGX9999'),\n     'value': 0}\n    \n    \n    {'_legacy_tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'address': Address(b'MHJIRKPUVSXBZWUXKUBNT9MRSEG9CRR9DNKIVNSCBZVGEDIDYTXIAVJLSTKQGVGDBFHRCRHBEMMZXPUFZ'),\n     'attachment_timestamp': 1570539229688,\n     'attachment_timestamp_lower_bound': 0,\n     'attachment_timestamp_upper_bound': 3812798742493,\n     'branch_transaction_hash': TransactionHash(b'FM9BAYPTXRETLTNOZJGDOZDVPNWTDFWHETXN9ALOXBOSJAKJZWCFIMAUNVFNEQHFCLELVBUKFKYIVO999'),\n     'bundle_hash': BundleHash(b'K9CRAOLBJCT9CEAKJVZIKUIIUSVKJIZGHXPJVYRDPJ9IFSUJPGRYECUCLIFKHLHVSE9ZSABLAUTXQ9HPD'),\n     'current_index': 3,\n     'hash': TransactionHash(b'AYRWHKRNVKYQTPRBEOLHDBTIPEVNNGUJKKFHR9HZYUP9XZPMBTOKEXCJXLAWXODKBXGNGIWEUMEGX9999'),\n     'is_confirmed': None,\n     'last_index': 3,\n     'nonce': Nonce(b'MOFCEZUIRTEEDUOGYSKIQT9JIFC'),\n     'signature_message_fragment': Fragment(b'999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999'),\n     'tag': Tag(b'HRIBEK999IOTA999TUTORIAL999'),\n     'timestamp': 1570539226,\n     'trunk_transaction_hash': TransactionHash(b'FM9BAYPTXRETLTNOZJGDOZDVPNWTDFWHETXN9ALOXBOSJAKJZWCFIMAUNVFNEQHFCLELVBUKFKYIVO999'),\n     'value': 2969}\n\n\nLet's review all transactions that has been prepared and sent eventually:\n* The first transaction `current_index=0` is the `output TX` that basically adds tokens to some address\n* Transactions `current_index=1` and `current_index=2` are two parts of the same transaction - `Input TX`. This transaction deducts tokens from the address(es). You can see negative `value` in the transaction `current_index=1`\n* Why there are two parts? Since the transaction spends tokens it has to be signed in order to validate the ownership. Signature is generated from the private key and the signature can be observed in the field `signature_message_fragment`. Here is the thing. Do you remember when different `security levels` were discussed? There are three security levels available and the given level has the direct impact on length of the signature. Since `signature_message_fragment` is of the fixed size, if `SL>1` then the transaction has to be split to be able to accommodate full signature.\n* The last transaction `current_index=3` moves unspent tokens to the first unused address of the given seed.\n\nThe following tasks have to be done behind the curtain in addition to the standard transaction preparation process:\n* Search for address(es) with some balance until total amount of tokens available is large enough to be spent. You can use more input addresses if needed\n* If there would be some unspent amount of tokens then also search for the first unused address\n* Spending transactions (Input TX) has to be properly signed and split in case of `SL>1`\n* There is also some quick check performed whether resulting number of tokens is zero (no more tokens, no less tokens. Number of tokens has to be balanced).\n\nSo basically all steps we tried in the chapter had to be done also behind the curtain while using `send_transfer` extended API call. You can also see that some of those operations may be quite expensive in terms of time while being completely stateless. In real world applications it would be better to save some states (index of last address, used addresses, etc.) to avoid too many expensive operations.\n\nYou can review the given broadcasted transactions also in the tangle explorer (for devnet):\n* https://devnet.thetangle.org/address/BMFSMZMNBGKHAWPIZIOMJGRBXZETVSAYDSTDQCHLYTBWZMIXLNXF9XHLTMOCATFVFOMBQF9IOQGPEBPDC\n", "meta": {"hexsha": "fc4bc6264b6b8c8bc280bd4038d559784501f6f7", "size": 143258, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Developer Lab/Allchapters_python.ipynb", "max_stars_repo_name": "Hribek25/IOTA101", "max_stars_repo_head_hexsha": "adf5c4cced557d60836bf6ba80a1080b2607c8e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2018-06-28T18:15:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T22:05:53.000Z", "max_issues_repo_path": "Developer Lab/Allchapters_python.ipynb", "max_issues_repo_name": "Hribek25/IOTA101", "max_issues_repo_head_hexsha": "adf5c4cced557d60836bf6ba80a1080b2607c8e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-07-01T19:45:20.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-01T18:18:04.000Z", "max_forks_repo_path": "Developer Lab/Allchapters_python.ipynb", "max_forks_repo_name": "Hribek25/IOTA101", "max_forks_repo_head_hexsha": "adf5c4cced557d60836bf6ba80a1080b2607c8e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-08-26T20:01:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-26T17:09:56.000Z", "avg_line_length": 81.1660056657, "max_line_length": 2720, "alphanum_fraction": 0.7825880579, "converted": true, "num_tokens": 39097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.144148864062875, "lm_q2_score": 0.055823136029551815, "lm_q1q2_score": 0.008046841647087244}}
{"text": "```python\nfrom IPython.core.display import display, HTML\ndisplay(HTML(\"<style>.container { width:100% !important; }</style>\"))\n```\n\n\n<style>.container { width:100% !important; }</style>\n\n\n# Atlanta Police Department \n\n\nThe Atlanta Police Department provides Part 1 crime data at http://www.atlantapd.org/crimedatadownloads.aspx\n\nA recent copy of the data file is stored in the cluster. <span style=\"color: red; font-weight: bold;\">Please, do not copy this data file into your home directory!</span>\n\n\n```python\n### Load libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n```\n\n\n```python\nhelp(plt.legend)\n```\n\n    Help on function legend in module matplotlib.pyplot:\n    \n    legend(*args, **kwargs)\n        Places a legend on the axes.\n        \n        To make a legend for lines which already exist on the axes\n        (via plot for instance), simply call this function with an iterable\n        of strings, one for each legend item. For example::\n        \n            ax.plot([1, 2, 3])\n            ax.legend(['A simple line'])\n        \n        However, in order to keep the \"label\" and the legend element\n        instance together, it is preferable to specify the label either at\n        artist creation, or by calling the\n        :meth:`~matplotlib.artist.Artist.set_label` method on the artist::\n        \n            line, = ax.plot([1, 2, 3], label='Inline label')\n            # Overwrite the label by calling the method.\n            line.set_label('Label via method')\n            ax.legend()\n        \n        Specific lines can be excluded from the automatic legend element\n        selection by defining a label starting with an underscore.\n        This is default for all artists, so calling :meth:`legend` without\n        any arguments and without setting the labels manually will result in\n        no legend being drawn.\n        \n        For full control of which artists have a legend entry, it is possible\n        to pass an iterable of legend artists followed by an iterable of\n        legend labels respectively::\n        \n           legend((line1, line2, line3), ('label1', 'label2', 'label3'))\n        \n        Parameters\n        ----------\n        loc : int or string or pair of floats, default: 'upper right'\n            The location of the legend. Possible codes are:\n        \n                ===============   =============\n                Location String   Location Code\n                ===============   =============\n                'best'            0\n                'upper right'     1\n                'upper left'      2\n                'lower left'      3\n                'lower right'     4\n                'right'           5\n                'center left'     6\n                'center right'    7\n                'lower center'    8\n                'upper center'    9\n                'center'          10\n                ===============   =============\n        \n        \n            Alternatively can be a 2-tuple giving ``x, y`` of the lower-left\n            corner of the legend in axes coordinates (in which case\n            ``bbox_to_anchor`` will be ignored).\n        \n        bbox_to_anchor : :class:`matplotlib.transforms.BboxBase` instance                          or tuple of floats\n            Specify any arbitrary location for the legend in `bbox_transform`\n            coordinates (default Axes coordinates).\n        \n            For example, to put the legend's upper right hand corner in the\n            center of the axes the following keywords can be used::\n        \n               loc='upper right', bbox_to_anchor=(0.5, 0.5)\n        \n        ncol : integer\n            The number of columns that the legend has. Default is 1.\n        \n        prop : None or :class:`matplotlib.font_manager.FontProperties` or dict\n            The font properties of the legend. If None (default), the current\n            :data:`matplotlib.rcParams` will be used.\n        \n        fontsize : int or float or {'xx-small', 'x-small', 'small', 'medium',                   'large', 'x-large', 'xx-large'}\n            Controls the font size of the legend. If the value is numeric the\n            size will be the absolute font size in points. String values are\n            relative to the current default font size. This argument is only\n            used if `prop` is not specified.\n        \n        numpoints : None or int\n            The number of marker points in the legend when creating a legend\n            entry for a line/:class:`matplotlib.lines.Line2D`.\n            Default is ``None`` which will take the value from the\n            ``legend.numpoints`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        scatterpoints : None or int\n            The number of marker points in the legend when creating a legend\n            entry for a scatter plot/\n            :class:`matplotlib.collections.PathCollection`.\n            Default is ``None`` which will take the value from the\n            ``legend.scatterpoints`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        scatteryoffsets : iterable of floats\n            The vertical offset (relative to the font size) for the markers\n            created for a scatter plot legend entry. 0.0 is at the base the\n            legend text, and 1.0 is at the top. To draw all markers at the\n            same height, set to ``[0.5]``. Default ``[0.375, 0.5, 0.3125]``.\n        \n        markerscale : None or int or float\n            The relative size of legend markers compared with the originally\n            drawn ones. Default is ``None`` which will take the value from\n            the ``legend.markerscale`` :data:`rcParam <matplotlib.rcParams>`.\n        \n        *markerfirst*: [ *True* | *False* ]\n            if *True*, legend marker is placed to the left of the legend label\n            if *False*, legend marker is placed to the right of the legend\n            label\n        \n        frameon : None or bool\n            Control whether a frame should be drawn around the legend.\n            Default is ``None`` which will take the value from the\n            ``legend.frameon`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        fancybox : None or bool\n            Control whether round edges should be enabled around\n            the :class:`~matplotlib.patches.FancyBboxPatch` which\n            makes up the legend's background.\n            Default is ``None`` which will take the value from the\n            ``legend.fancybox`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        shadow : None or bool\n            Control whether to draw a shadow behind the legend.\n            Default is ``None`` which will take the value from the\n            ``legend.shadow`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        framealpha : None or float\n            Control the alpha transparency of the legend's frame.\n            Default is ``None`` which will take the value from the\n            ``legend.framealpha`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        mode : {\"expand\", None}\n            If `mode` is set to ``\"expand\"`` the legend will be horizontally\n            expanded to fill the axes area (or `bbox_to_anchor` if defines\n            the legend's size).\n        \n        bbox_transform : None or :class:`matplotlib.transforms.Transform`\n            The transform for the bounding box (`bbox_to_anchor`). For a value\n            of ``None`` (default) the Axes'\n            :data:`~matplotlib.axes.Axes.transAxes` transform will be used.\n        \n        title : str or None\n            The legend's title. Default is no title (``None``).\n        \n        borderpad : float or None\n            The fractional whitespace inside the legend border.\n            Measured in font-size units.\n            Default is ``None`` which will take the value from the\n            ``legend.borderpad`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        labelspacing : float or None\n            The vertical space between the legend entries.\n            Measured in font-size units.\n            Default is ``None`` which will take the value from the\n            ``legend.labelspacing`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        handlelength : float or None\n            The length of the legend handles.\n            Measured in font-size units.\n            Default is ``None`` which will take the value from the\n            ``legend.handlelength`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        handletextpad : float or None\n            The pad between the legend handle and text.\n            Measured in font-size units.\n            Default is ``None`` which will take the value from the\n            ``legend.handletextpad`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        borderaxespad : float or None\n            The pad between the axes and legend border.\n            Measured in font-size units.\n            Default is ``None`` which will take the value from the\n            ``legend.borderaxespad`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        columnspacing : float or None\n            The spacing between columns.\n            Measured in font-size units.\n            Default is ``None`` which will take the value from the\n            ``legend.columnspacing`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        handler_map : dict or None\n            The custom dictionary mapping instances or types to a legend\n            handler. This `handler_map` updates the default handler map\n            found at :func:`matplotlib.legend.Legend.get_legend_handler_map`.\n        \n        Notes\n        -----\n        \n        Not all kinds of artist are supported by the legend command.\n        See :ref:`plotting-guide-legend` for details.\n        \n        Examples\n        --------\n        \n        .. plot:: mpl_examples/api/legend_demo.py\n    \n\n\nLoad data (don't change this if you're running the notebook on the cluster)\n\nWe have two files\n- `/home/data/APD/COBRA083016_2015.xlsx` for 2015\n- `/home/data/APD/COBRA083016.xlsx` from 2009 to current date\n\n\n```python\n%%time\ndf = pd.read_excel('/home/data/APD/COBRA083016_2015.xlsx', sheetname='Query')\n```\n\n    CPU times: user 1min 26s, sys: 882 ms, total: 1min 27s\n    Wall time: 1min 27s\n\n\n\n```python\ndf.shape\n```\n\n\n\n\n    (30011, 23)\n\n\n\n\n```python\nfor c in df.columns:\n    print(c)\n```\n\n    MI_PRINX\n    offense_id\n    rpt_date\n    occur_date\n    occur_time\n    poss_date\n    poss_time\n    beat\n    apt_office_prefix\n    apt_office_num\n    location\n    MinOfucr\n    MinOfibr_code\n    dispo_code\n    MaxOfnum_victims\n    Shift\n    Avg Day\n    loc_type\n    UC2 Literal\n    neighborhood\n    npu\n    x\n    y\n\n\n\n```python\ndf[0:5]\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>MI_PRINX</th>\n      <th>offense_id</th>\n      <th>rpt_date</th>\n      <th>occur_date</th>\n      <th>occur_time</th>\n      <th>poss_date</th>\n      <th>poss_time</th>\n      <th>beat</th>\n      <th>apt_office_prefix</th>\n      <th>apt_office_num</th>\n      <th>...</th>\n      <th>Avg Day</th>\n      <th>loc_type</th>\n      <th>UC2 Literal</th>\n      <th>neighborhood</th>\n      <th>npu</th>\n      <th>x</th>\n      <th>y</th>\n      <th>occur_ts</th>\n      <th>occur_month</th>\n      <th>occur_woy</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>206914</th>\n      <td>1371687</td>\n      <td>150562000</td>\n      <td>05/14/2013</td>\n      <td>05/14/2013</td>\n      <td>09:00:00</td>\n      <td>05/14/2013</td>\n      <td>11:30:00</td>\n      <td>205</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>Tue</td>\n      <td>18.0</td>\n      <td>LARCENY-FROM VEHICLE</td>\n      <td>Woodfield</td>\n      <td>C</td>\n      <td>-84.40912</td>\n      <td>33.82308</td>\n      <td>2013-05-14 09:00:00</td>\n      <td>5.0</td>\n      <td>20.0</td>\n    </tr>\n    <tr>\n      <th>207443</th>\n      <td>4346442</td>\n      <td>150010052</td>\n      <td>01/01/2015</td>\n      <td>12/31/2014</td>\n      <td>22:00:00</td>\n      <td>01/01/2015</td>\n      <td>00:07:00</td>\n      <td>512</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>Wed</td>\n      <td>NaN</td>\n      <td>LARCENY-FROM VEHICLE</td>\n      <td>Downtown</td>\n      <td>M</td>\n      <td>-84.39361</td>\n      <td>33.75246</td>\n      <td>2014-12-31 22:00:00</td>\n      <td>12.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>207444</th>\n      <td>4346443</td>\n      <td>150010079</td>\n      <td>01/01/2015</td>\n      <td>01/01/2015</td>\n      <td>00:03:00</td>\n      <td>01/01/2015</td>\n      <td>00:03:00</td>\n      <td>606</td>\n      <td>NaN</td>\n      <td>3377</td>\n      <td>...</td>\n      <td>Thu</td>\n      <td>26.0</td>\n      <td>ROBBERY-PEDESTRIAN</td>\n      <td>Grant Park</td>\n      <td>W</td>\n      <td>-84.35917</td>\n      <td>33.73991</td>\n      <td>2015-01-01 00:03:00</td>\n      <td>1.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>207445</th>\n      <td>4346444</td>\n      <td>150010151</td>\n      <td>01/01/2015</td>\n      <td>12/31/2014</td>\n      <td>23:45:00</td>\n      <td>01/01/2015</td>\n      <td>00:21:00</td>\n      <td>208</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>Thu</td>\n      <td>18.0</td>\n      <td>LARCENY-NON VEHICLE</td>\n      <td>Buckhead Forest</td>\n      <td>B</td>\n      <td>-84.37462</td>\n      <td>33.84564</td>\n      <td>2014-12-31 23:45:00</td>\n      <td>12.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>207446</th>\n      <td>4346445</td>\n      <td>150010214</td>\n      <td>01/01/2015</td>\n      <td>01/01/2015</td>\n      <td>00:30:00</td>\n      <td>01/01/2015</td>\n      <td>01:05:00</td>\n      <td>407</td>\n      <td>1000</td>\n      <td>1009</td>\n      <td>...</td>\n      <td>Thu</td>\n      <td>26.0</td>\n      <td>AGG ASSAULT</td>\n      <td>Fairburn Mays</td>\n      <td>H</td>\n      <td>-84.50968</td>\n      <td>33.74349</td>\n      <td>2015-01-01 00:30:00</td>\n      <td>1.0</td>\n      <td>1.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 26 columns</p>\n</div>\n\n\n\n\n```python\ndf.describe()\n```\n\n    /usr/lib64/python3.4/site-packages/numpy/lib/function_base.py:3834: RuntimeWarning: Invalid value encountered in percentile\n      RuntimeWarning)\n\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>MI_PRINX</th>\n      <th>offense_id</th>\n      <th>beat</th>\n      <th>MinOfucr</th>\n      <th>MaxOfnum_victims</th>\n      <th>loc_type</th>\n      <th>x</th>\n      <th>y</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>3.001100e+04</td>\n      <td>3.001100e+04</td>\n      <td>30011.000000</td>\n      <td>30011.000000</td>\n      <td>30011.000000</td>\n      <td>26903.000000</td>\n      <td>30011.000000</td>\n      <td>30011.000000</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>4.361347e+06</td>\n      <td>1.518675e+08</td>\n      <td>359.417813</td>\n      <td>594.219886</td>\n      <td>1.194695</td>\n      <td>21.109356</td>\n      <td>-84.408346</td>\n      <td>33.756058</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>1.931052e+04</td>\n      <td>1.029128e+06</td>\n      <td>169.563281</td>\n      <td>114.321851</td>\n      <td>0.799062</td>\n      <td>16.579831</td>\n      <td>0.046894</td>\n      <td>0.045981</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>1.371687e+06</td>\n      <td>1.500101e+08</td>\n      <td>101.000000</td>\n      <td>210.000000</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n      <td>-84.546070</td>\n      <td>33.637450</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>4.353944e+06</td>\n      <td>1.510128e+08</td>\n      <td>208.000000</td>\n      <td>512.000000</td>\n      <td>1.000000</td>\n      <td>NaN</td>\n      <td>-84.432445</td>\n      <td>33.729060</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>4.361446e+06</td>\n      <td>1.518913e+08</td>\n      <td>401.000000</td>\n      <td>640.000000</td>\n      <td>1.000000</td>\n      <td>NaN</td>\n      <td>-84.398210</td>\n      <td>33.756000</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>4.368948e+06</td>\n      <td>1.527329e+08</td>\n      <td>505.000000</td>\n      <td>670.000000</td>\n      <td>1.000000</td>\n      <td>NaN</td>\n      <td>-84.374420</td>\n      <td>33.781470</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>4.376451e+06</td>\n      <td>1.536580e+08</td>\n      <td>709.000000</td>\n      <td>730.000000</td>\n      <td>44.000000</td>\n      <td>99.000000</td>\n      <td>-84.290480</td>\n      <td>33.883250</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf.offense_id.min(), df.offense_id.max()\n```\n\n\n\n\n    (150010052, 153658045)\n\n\n\n\n```python\ndf.groupby(['UC2 Literal']).offense_id.count()\n```\n\n\n\n\n    UC2 Literal\n    AGG ASSAULT             2111\n    AUTO THEFT              4234\n    BURGLARY-NONRES          817\n    BURGLARY-RESIDENCE      3921\n    LARCENY-FROM VEHICLE    9539\n    LARCENY-NON VEHICLE     7092\n    RAPE                     154\n    ROBBERY-COMMERCIAL       235\n    ROBBERY-PEDESTRIAN      1721\n    ROBBERY-RESIDENCE        187\n    Name: offense_id, dtype: int64\n\n\n\n## Exploring Dates\n\n\n```python\ndf[['offense_id', 'occur_date', 'occur_time', 'rpt_date']][1:10]\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>offense_id</th>\n      <th>occur_date</th>\n      <th>occur_time</th>\n      <th>rpt_date</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>207443</th>\n      <td>150010052</td>\n      <td>12/31/2014</td>\n      <td>22:00:00</td>\n      <td>01/01/2015</td>\n    </tr>\n    <tr>\n      <th>207444</th>\n      <td>150010079</td>\n      <td>01/01/2015</td>\n      <td>00:03:00</td>\n      <td>01/01/2015</td>\n    </tr>\n    <tr>\n      <th>207445</th>\n      <td>150010151</td>\n      <td>12/31/2014</td>\n      <td>23:45:00</td>\n      <td>01/01/2015</td>\n    </tr>\n    <tr>\n      <th>207446</th>\n      <td>150010214</td>\n      <td>01/01/2015</td>\n      <td>00:30:00</td>\n      <td>01/01/2015</td>\n    </tr>\n    <tr>\n      <th>207447</th>\n      <td>150010359</td>\n      <td>12/31/2014</td>\n      <td>21:00:00</td>\n      <td>01/01/2015</td>\n    </tr>\n    <tr>\n      <th>207448</th>\n      <td>150010370</td>\n      <td>12/31/2014</td>\n      <td>23:15:00</td>\n      <td>01/01/2015</td>\n    </tr>\n    <tr>\n      <th>207449</th>\n      <td>150010413</td>\n      <td>12/31/2014</td>\n      <td>23:00:00</td>\n      <td>01/01/2015</td>\n    </tr>\n    <tr>\n      <th>207450</th>\n      <td>150010417</td>\n      <td>01/01/2015</td>\n      <td>02:00:00</td>\n      <td>01/01/2015</td>\n    </tr>\n    <tr>\n      <th>207451</th>\n      <td>150010419</td>\n      <td>01/01/2015</td>\n      <td>01:50:00</td>\n      <td>01/01/2015</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nConvert into date-time type\n\n\n```python\ndf['occur_ts'] = pd.to_datetime(df.occur_date+' '+df.occur_time)\n```\n\n\n```python\n#df[['offense_id', 'occur_date', 'occur_time', 'occur_ts', 'rpt_date']][1:10]\n```\n\n\n```python\ndf['occur_ts'] = pd.to_datetime(df.occur_date+' '+df.occur_time)\ndf['occur_month'] = df['occur_ts'].map(lambda x: x.month)\ndf['occur_woy'] = df.occur_ts.dt.weekofyear\n```\n\n\n```python\ndf.describe()\n```\n\n    /usr/lib64/python3.4/site-packages/numpy/lib/function_base.py:3834: RuntimeWarning: Invalid value encountered in percentile\n      RuntimeWarning)\n\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>MI_PRINX</th>\n      <th>offense_id</th>\n      <th>beat</th>\n      <th>MinOfucr</th>\n      <th>MaxOfnum_victims</th>\n      <th>loc_type</th>\n      <th>x</th>\n      <th>y</th>\n      <th>occur_month</th>\n      <th>occur_woy</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>3.001100e+04</td>\n      <td>3.001100e+04</td>\n      <td>30011.000000</td>\n      <td>30011.000000</td>\n      <td>30011.000000</td>\n      <td>26903.000000</td>\n      <td>30011.000000</td>\n      <td>30011.000000</td>\n      <td>10.000000</td>\n      <td>10.000000</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>4.361347e+06</td>\n      <td>1.518675e+08</td>\n      <td>359.417813</td>\n      <td>594.219886</td>\n      <td>1.194695</td>\n      <td>21.109356</td>\n      <td>-84.408346</td>\n      <td>33.756058</td>\n      <td>6.900000</td>\n      <td>2.900000</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>1.931052e+04</td>\n      <td>1.029128e+06</td>\n      <td>169.563281</td>\n      <td>114.321851</td>\n      <td>0.799062</td>\n      <td>16.579831</td>\n      <td>0.046894</td>\n      <td>0.045981</td>\n      <td>5.506562</td>\n      <td>6.008328</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>1.371687e+06</td>\n      <td>1.500101e+08</td>\n      <td>101.000000</td>\n      <td>210.000000</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n      <td>-84.546070</td>\n      <td>33.637450</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>4.353944e+06</td>\n      <td>1.510128e+08</td>\n      <td>208.000000</td>\n      <td>512.000000</td>\n      <td>1.000000</td>\n      <td>NaN</td>\n      <td>-84.432445</td>\n      <td>33.729060</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>4.361446e+06</td>\n      <td>1.518913e+08</td>\n      <td>401.000000</td>\n      <td>640.000000</td>\n      <td>1.000000</td>\n      <td>NaN</td>\n      <td>-84.398210</td>\n      <td>33.756000</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>4.368948e+06</td>\n      <td>1.527329e+08</td>\n      <td>505.000000</td>\n      <td>670.000000</td>\n      <td>1.000000</td>\n      <td>NaN</td>\n      <td>-84.374420</td>\n      <td>33.781470</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>4.376451e+06</td>\n      <td>1.536580e+08</td>\n      <td>709.000000</td>\n      <td>730.000000</td>\n      <td>44.000000</td>\n      <td>99.000000</td>\n      <td>-84.290480</td>\n      <td>33.883250</td>\n      <td>12.000000</td>\n      <td>20.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nresdf = df.groupby(['UC2 Literal', 'occur_month']).offense_id.count()\nresdf\n```\n\n\n\n\n    UC2 Literal         occur_month\n    AGG ASSAULT         1.0            156\n                        2.0            139\n                        3.0            189\n                        4.0            191\n                        5.0            182\n                        6.0            205\n                        7.0            201\n                        8.0            209\n                        9.0            176\n                        10.0           172\n                        11.0           142\n                        12.0           149\n    AUTO THEFT          1.0            351\n                        2.0            279\n                        3.0            359\n                        4.0            332\n                        5.0            408\n                        6.0            452\n                        7.0            396\n                        8.0            405\n                        9.0            334\n                        10.0           369\n                        11.0           262\n                        12.0           284\n    BURGLARY-NONRES     1.0             69\n                        2.0             41\n                        3.0             45\n                        4.0             68\n                        5.0             61\n                        6.0             71\n                                      ... \n    ROBBERY-COMMERCIAL  7.0             23\n                        8.0             16\n                        9.0             20\n                        10.0            26\n                        11.0            21\n                        12.0            22\n    ROBBERY-PEDESTRIAN  1.0            137\n                        2.0            108\n                        3.0            133\n                        4.0            116\n                        5.0            152\n                        6.0            151\n                        7.0            175\n                        8.0            151\n                        9.0            163\n                        10.0           171\n                        11.0           135\n                        12.0           129\n    ROBBERY-RESIDENCE   1.0             19\n                        2.0             12\n                        3.0             20\n                        4.0             19\n                        5.0             18\n                        6.0              8\n                        7.0             17\n                        8.0             23\n                        9.0             17\n                        10.0            10\n                        11.0            11\n                        12.0            13\n    Name: offense_id, dtype: int64\n\n\n\n\n```python\nresdf['BURGLARY-RESIDENCE'].as_matrix()\n```\n\n\n\n\n    array([357, 232, 303, 311, 375, 323, 316, 292, 298, 340, 340, 432])\n\n\n\n\n```python\nresdf['BURGLARY-RESIDENCE'].iloc(0)\n```\n\n\n```python\n%matplotlib inline\nfig = plt.figure(figsize=(10,6)) # 10inx10in\n#plt.plot(resdf['BURGLARY-RESIDENCE'].index, resdf['BURGLARY-RESIDENCE'])\nplt.scatter(resdf['BURGLARY-RESIDENCE'].index, resdf['BURGLARY-RESIDENCE'], marker='x')\nplt.scatter(resdf['BURGLARY-NONRES'].index, resdf['BURGLARY-NONRES'], marker='o')\n\nplt.ylim(0, 500)\nplt.title('BURGLARY-RESIDENCE')\nplt.xticks(range(13), ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])\nfig.savefig('BurglaryResidence_over_month.svg')\nx = 1\n```\n\n\n```python\ndf = pd.read_excel('/home/data/APD/COBRA083016_2015.xlsx', sheetname='Query')\ndf['occur_ts'] = pd.to_datetime(df.occur_date+' '+df.occur_time)\ndf['occur_month'] = df['occur_ts'].map(lambda x: x.month)\ndf['occur_woy'] = df.occur_ts.dt.weekofyear\n```\n\n\n```python\n%matplotlib inline\nresdf = df.groupby(['UC2 Literal', 'occur_month']).offense_id.count()\nfig = plt.figure(figsize=(10,6))\nplt.scatter(resdf['BURGLARY-RESIDENCE'].index, resdf['BURGLARY-RESIDENCE'], marker='x')\nplt.ylim(0, 500)\nplt.title('BURGLARY-RESIDENCE')\nplt.xticks(range(13), ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])\nplt.savefig('quiz3-burglary-residence.png')\n\n''\n```\n\n\n```python\nplt.savefig('quiz3-burglary-residence.png')\n\n```\n\n\n    <matplotlib.figure.Figure at 0x7fe4ed0687b8>\n\n\n# Part 1 - Observations from the data\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n# Part 2 - Seasonal Model\n\n\n```python\n## load complete dataset\ndff = pd.read_excel('/home/data/APD/COBRA083016.xlsx', sheetname='Query')\n```\n\n\n```python\ndff.shape\n```\n\n\n\n\n    (256216, 23)\n\n\n\n\n```python\nfor evt in ['occur', 'poss']:\n    dff['%s_ts'%evt] = pd.to_datetime(dff['%s_date'%evt]+' '+dff['%s_time'%evt])\ndff['rpt_ts'] = pd.to_datetime(dff.rpt_date)\n```\n\n\n```python\n', '.join(dff.columns)\n```\n\n\n\n\n    'MI_PRINX, offense_id, rpt_date, occur_date, occur_time, poss_date, poss_time, beat, apt_office_prefix, apt_office_num, location, MinOfucr, MinOfibr_code, dispo_code, MaxOfnum_victims, Shift, Avg Day, loc_type, UC2 Literal, neighborhood, npu, x, y, occur_ts, poss_ts, rpt_ts, occ_year, occ_month, occ_dayweek'\n\n\n\n\n```python\ndff['occur_year'] = dff.occur_ts.dt.year\ndff['occur_month'] = dff.occur_ts.dt.month\ndff['occur_dayweek'] = dff.occur_ts.dt.dayofweek\n```\n\n### Crime per year\nLet's look at the \n\n\n```python\ncrime_year = dff[dff.occur_year.between(2009, 2015)].groupby(by=['UC2 Literal', 'occur_year']).offense_id.count()\n```\n\n\n```python\n%matplotlib inline\nfig = plt.figure(figsize=(40,30))\ncrime_types = crime_year.index.levels[0]\nyears = crime_year.index.levels[1]\nfor c in range(len(crime_types)):\n    y_max = max(crime_year.loc[crime_types[c]])\n    \n    plt.subplot(4,3,c+1)\n    plt.hlines(crime_year.loc[crime_types[c]].iloc[-1]*100/y_max, years[0], years[-1], linestyles=\"dashed\", color=\"r\")\n    plt.bar(crime_year.loc[crime_types[c]].index, crime_year.loc[crime_types[c]]*100/y_max, label=crime_types[c], alpha=0.5)\n    ##plt.legend()\n    plt.ylim(0, 100)\n    plt.xticks(years+0.4, [str(int(y)) for y in years], rotation=0, fontsize=24)\n    plt.yticks([0,20,40,60,80,100], ['0%','20%','40%','60%','80%','100%'], fontsize=24)\n    plt.title(crime_types[c], fontsize=30)\n    None\n```\n\nLet's look at residential burglary.\n\n\n```python\nc = 3\ncrime_types[c]\n```\n\n\n\n\n    'BURGLARY-RESIDENCE'\n\n\n\n\n```python\ncrime_year_month = dff[dff.occur_year.between(2009, 2015)].groupby(by=['UC2 Literal', 'occur_year', 'occur_month']).offense_id.count()\n```\n\n\n```python\nc = 3 ## 'BURGLARY-RESIDENCE'\nresburglaries = crime_year_month.loc[crime_types[c]]\nfig = plt.figure(figsize=(20,10))\nfor y in years:\n    plt.plot(resburglaries.loc[y].index, resburglaries.loc[y], label=(\"%4.0f\"%y))\nplt.legend()\nplt.title(\"Seasonal Trends - %s\"%crime_types[c], fontsize=20)\nplt.xticks(range(13), ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])\nplt.xlim(0,13)\nNone\n```\n\nNormalized over the annual average\n\n\n```python\nc = 3 ## 'BURGLARY-RESIDENCE'\nfig = plt.figure(figsize=(20,10))\nfor y in years:\n    avg = resburglaries.loc[y].mean()\n    plt.hlines(avg, 1, 13, linestyle='dashed')\n    plt.plot(resburglaries.loc[y].index, resburglaries.loc[y], label=(\"%4.0f\"%y))\nplt.legend()\nplt.title(\"Seasonal Trends - %s (with annuale averages)\"%crime_types[c], fontsize=20)\nplt.xticks(list(range(1,13)), ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])\nplt.xlim(0,13)\nNone\n```\n\n\n```python\nc = 3 ## 'BURGLARY-RESIDENCE'\nfig = plt.figure(figsize=(20,10))\nfor y in years:\n    avg = resburglaries.loc[y].mean()\n    std = resburglaries.loc[y].std()\n    ##plt.hlines(avg, 1, 13, linestyle='dashed')\n    plt.plot(resburglaries.loc[y].index, (resburglaries.loc[y]-avg)/std, label=(\"%4.0f\"%y))\nplt.legend()\nplt.title(\"Seasonal Trends - %s (normalized)\"%crime_types[c], fontsize=20)\nplt.xticks(list(range(1,13)), ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])\nplt.xlim(0,13)\nplt.ylabel(\"Standard deviations $\\sigma_y$\")\nNone\n```\n\n\n```python\n\n```\n\n\n```python\nseasonal_adjust = resburglaries.reset_index().groupby(by=['occur_month']).offense_id.agg('mean')\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n### Fitting the regression line\nSuppose there are $n$ data points {{math|{(''x<sub>i</sub>'', ''y<sub>i</sub>''), ''i'' {{=}} 1, ..., ''n''}.}} The function that describes x and y is:\n\n$$y_i = \\alpha + \\beta x_i + \\varepsilon_i.$$\n\nThe goal is to find the equation of the straight line\n\n$$y = \\alpha + \\beta x,$$\n\nwhich would provide a \"best\" fit for the data points. Here the \"best\" will be understood as in the [[Ordinary least squares|least-squares]] approach: a line that minimizes the sum of squared residuals of the linear regression model. In other words, {{mvar|\u03b1}} (the {{mvar|y}}-intercept) and {{mvar|\u03b2}} (the slope) solve the following minimization problem:\n\n$$\\text{Find }\\min_{\\alpha,\\,\\beta} Q(\\alpha, \\beta), \\qquad \\text{for } Q(\\alpha, \\beta) = \\sum_{i=1}^n\\varepsilon_i^{\\,2} = \\sum_{i=1}^n (y_i - \\alpha - \\beta x_i)^2\\ $$\n\nBy using either [[calculus]], the geometry of [[inner product space]]s, or simply expanding to get a quadratic expression in {{mvar|\u03b1}} and {{mvar|\u03b2}}, it can be shown that the values of {{mvar|\u03b1}} and {{mvar|\u03b2}} that minimize the objective function {{mvar|Q}}<ref>Kenney, J. F. and Keeping, E. S. (1962) \"Linear Regression and Correlation.\" Ch. 15 in ''Mathematics of Statistics'', Pt. 1, 3rd ed. Princeton, NJ: Van Nostrand, pp. 252\u2013285</ref> are\n\n: <math>\\begin{align}\n  \\hat\\beta &= \\frac{ \\sum_{i=1}^{n} (x_i - \\bar{x})(y_i - \\bar{y}) }{ \\sum_{i=1}^n (x_i - \\bar{x})^2 } \\\\[6pt]\n            &= \\frac{ \\sum_{i=1}^{n} (x_i y_i - x_i \\bar{y} - \\bar{x} y_i + \\bar{x} \\bar{y})} { \\sum_{i=1}^n (x_i^2 - 2 x_i \\bar{x} + \\bar{x}^2) } \\\\[6pt]\n            &= \\frac{ \\sum_{i=1}^{n} (x_i y_i) - \\bar{y} \\sum_{i=1}^{n}  x_i  - \\bar{x} \\sum_{i=1}^{n} y_i + n  \\bar{x} \\bar{y}} { \\sum_{i=1}^n (x_i^2) - 2 \\bar{x}  \\sum_{i=1}^n  x_i  + n \\bar{x}^2 } \\\\[6pt]\n            &= \\frac{ \\frac{1}{n} \\sum_{i=1}^{n} x_i y_i - \\bar{x} \\bar{y} }{ \\frac{1}{n}\\sum_{i=1}^n {x_i^2} -   \\overline{x}^2 } \\\\[6pt]\n            &= \\frac{ \\overline{xy} - \\bar{x}\\bar{y} }{ \\overline{x^2} - \\bar{x}^2 } = \\frac{ \\operatorname{Cov}[x, y] }{ \\operatorname{Var}[x] } \\\\\n            &= r_{xy} \\frac{s_y}{s_x}, \\\\[6pt]\n \\hat\\alpha & = \\bar{y} - \\hat\\beta\\,\\bar{x},\n\\end{align}</math>\n\nwhere {{math|''r<sub>xy</sub>''}} is the [[Correlation#Pearson's product-moment coefficient|sample correlation coefficient]] between {{mvar|x}} and {{mvar|y}}; and {{math|''s<sub>x</sub>''}} and {{math|''s<sub>y</sub>''}} are the [[sample standard deviation]] of {{mvar|x}} and {{mvar|y}}. A horizontal bar over a quantity indicates the average value of that quantity. For example:\n\n:<math>\\overline{xy} = \\frac{1}{n} \\sum_{i=1}^n x_i y_i.</math>\n\nSubstituting the above expressions for <math>\\hat{\\alpha}</math> and <math>\\hat{\\beta}</math> into\n\n: <math>f = \\hat{\\alpha} + \\hat{\\beta} x,</math>\n\nyields\n\n: <math>\\frac{ f - \\bar{y}}{s_y} = r_{xy} \\frac{ x - \\bar{x}}{s_x}  </math>\n\nThis shows that {{math|''r<sub>xy</sub>''}} is the slope of the regression line of the [[Standard score|standardized]] data points (and that this line passes through the origin).\n\nIt is sometimes useful to calculate {{math|''r<sub>xy</sub>''}} from the data independently using this equation:\n\n:<math>r_{xy} = \\frac{ \\overline{xy} - \\bar{x}\\bar{y} }{ \\sqrt{ \\left(\\overline{x^2} - \\bar{x}^2\\right)\\left(\\overline{y^2} - \\bar{y}^2\\right)} } </math>\n\nThe [[coefficient of determination]] (R squared) is equal to <math>r_{xy}^2</math> when the model is linear with a single independent variable. See [[Correlation#Pearson's product-moment coefficient|sample correlation coefficient]] for additional details.\n\n===Linear regression without the intercept term===\nSometimes it is appropriate to force the regression line to pass through the origin, because {{mvar|x}} and {{mvar|y}} are assumed to be proportional. For the model without the intercept term, {{math|''y'' {{=}} ''\u03b2x''}}, the OLS estimator for {{mvar|\u03b2}} simplifies to\n\n: <math>\\hat{\\beta} = \\frac{ \\sum_{i=1}^n x_i y_i }{ \\sum_{i=1}^n x_i^2 } = \\frac{\\overline{x y}}{\\overline{x^2}} </math>\n\nSubstituting {{math|(''x'' \u2212 ''h'', ''y'' \u2212 ''k'')}} in place of {{math|(''x'', ''y'')}} gives the regression through {{math|(''h'', ''k'')}}:\n\n: <math>\\begin{align}\n  \\hat\\beta &= \\frac{\\overline{(x - h) (y - k)}}{\\overline{(x - h)^2}} \\\\[6pt]\n            &= \\frac{\\overline{x y} + k \\bar{x} - h \\bar{y} - h k }{\\overline{x^2} - 2 h \\bar{x} + h^2} \\\\[6pt]\n            &= \\frac{\\overline{x y} - \\bar{x} \\bar{y} + (\\bar{x} - h)(\\bar{y} - k)}{\\overline{x^2} - \\bar{x}^2 + (\\bar{x} - h)^2} \\\\[6pt]\n            &= \\frac{\\operatorname{Cov}[x,y] + (\\bar{x} - h)(\\bar{y}-k)}{\\operatorname{Var}[x] + (\\bar{x} - h)^2}\n\\end{align}</math>\n\nThe last form above demonstrates how moving the line away from the center of mass of the data points affects the slope.\n\n\n\n```python\n### in case we want to save a DataFrame\n#writer = pd.ExcelWriter('myresults.xlsx')\n#df.to_excel(writer,'Results')\n#writer.save()\n```\n\n\n```python\nresdf\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "7eaf0df54e5fbf9f35dabb9a0ffab005515ea8a6", "size": 650984, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "DataScienceProgramming/03-NumPy-and-Linear-Algebra/APD-Crime-Data_orig.ipynb", "max_stars_repo_name": "cartermin/MSA8090", "max_stars_repo_head_hexsha": "c8d95fb7c71682b2197a391995b76f6043a905cc", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-08-21T23:23:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-16T23:57:11.000Z", "max_issues_repo_path": "DataScienceProgramming/03-NumPy-and-Linear-Algebra/APD-Crime-Data_orig.ipynb", "max_issues_repo_name": "cartermin/MSA8090", "max_issues_repo_head_hexsha": "c8d95fb7c71682b2197a391995b76f6043a905cc", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DataScienceProgramming/03-NumPy-and-Linear-Algebra/APD-Crime-Data_orig.ipynb", "max_forks_repo_name": "cartermin/MSA8090", "max_forks_repo_head_hexsha": "c8d95fb7c71682b2197a391995b76f6043a905cc", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2017-08-22T00:39:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-09T01:46:29.000Z", "avg_line_length": 344.0718816068, "max_line_length": 156384, "alphanum_fraction": 0.9041543264, "converted": true, "num_tokens": 11371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12592277139559055, "lm_q2_score": 0.0627892125430318, "lm_q1q2_score": 0.00790659165716534}}
{"text": "# Credible Threats - Life of Py(thon)\nBy The Good, The Bad and the Ugly aka. The Three Musketeers. \n\nWelcome to the amazing Credible Threats dataproject Jupyter Notebook. \n\nThis notebook is *our precious*, it is *the stuff that dreams are made of*. It dives into the wonderful world of movies, and we *just keep swimming*, because *where we're going we don't need roads*. \n\nWhat is a movie? A movie is *poetry, beauty, romance, love. These are what we stay alive for*. They are stories of another world, portrayed in such a way, that though *there's no place like home*, the movies are a close second. And though movies are great, *mama always said the movies is like a box of chocolates. You never know what you're gonna get*, and she was right about that. Luckily for you, Credible Threats is at your aid. Through this dataproject, we will help you sort through the best and the worst of thousands of movies. How do we do that you might ask, well it is *elementary, dear Watson*. *We're going to have to science the shit out of this*.\n\nNow, we know what you're thinking, *with great power comes great responsiblity*, but don't worry, *we're wizards, Harry*. In the following, we will look at IMDB data, containing over 14,000 movies, from the 1920's Metropolis to the 2010's Toy Story 3. You might say that we go *to infinity and beyond* in the world of movies.\n\nGiving you access to this *supercalifragilisticexpialidocious* notebook, we're *making you an offer you can't refuse*, as the notebook contains summary statistics by decade, interactive histograms of ratings, and even rainbow colored graphs which will leave thinking, *I am Groot*. \n\nHopefully, you won't have to stop along the way and say, *Houston, we have a problem*. \nSo, *fasten your seatbelts. It's going to be a bumpy ride*. \n\n\n\n\n## Datalicious\n\n### Importing Data\n\n\n```python\n# Importing packages\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport ipywidgets as widgets\nimport numpy as np\nfrom ipywidgets import Layout\nimport seaborn as sns\nimport math\nimport requests\nfrom bs4 import BeautifulSoup as bs\nimport itertools\nfrom ipywidgets import Layout\nimport time\nfrom scipy import linalg\nimport scipy.optimize as optimize\nimport sympy as sm\nfrom IPython.display import clear_output \nsns.set()\n```\n\n\n```python\n## Importing and cleaning the data \n\nfilename = 'imdb.csv'\n\n## Defining the function to import and clean the data\ndef gen_df(filename):\n    \"\"\" Returns a pandas dataframe containing information about movies from the IMDB database \n\n    Args:\n    filename (csv-file): The csv-file have to be the file imdb.csv\n\n    Returns:\n    A pandas dataframe\n\n    Notice:\n    The function will not work if other files than imdb.csv are used as input \"\"\"\n        \n    # Get .csv.file\n    data = pd.read_csv(filename, sep=';', encoding='latin-1', escapechar='\\\\')\n\n    # Read file into pandas dataframe\n    df = pd.DataFrame(data)\n\n    # Drop unwanted columns\n    for i in range(44,48):\n        df.drop(columns=[f'Unnamed: {i}'], inplace=True)\n    df.drop(columns=['fn','wordsInTitle','url'], inplace=True)\n\n    # Keep only observations of 'movie'-type\n    I = df['type'] == 'video.movie'\n    df = df.loc[I]\n    df.drop(columns=['type'], inplace=True)\n\n    # Drop movies with missing observations\n    df.dropna(inplace=True)\n\n    # During the importing process, the first decimal has become 0 for all movies.\n    # Thus, we replace \"0\"'s with \"\"\n    df['imdbRating'] = df['imdbRating'].astype(str)\n    df['imdbRating'].replace(regex=True, inplace=True,to_replace='0',value='')\n    df['imdbRating'] = df['imdbRating'].astype(float)\n\n    # Transform duration from seconds to hours\n    df['duration'] = df['duration']/60**2\n\n    # Drop years before 1920 and the year 2014 because of few obervations\n    I = (df['year']>=1920) & (df['year']<=2013)\n    df = df.loc[I]\n\n    # Change the type of 'year' to integer\n    df['year'] = df['year'].astype(int)    \n    \n    # Sort observations and reset index\n    df.sort_values('year', inplace=True)\n    df.reset_index(inplace=True)\n\n    # Generating a variable that shows the decade (as a string)\n    year_list = [1920, 1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010]\n\n    df['decade'] = ''\n    for i,start in enumerate(year_list):\n        end = start+10\n        df.loc[(df['year'] >= start) & (df['year'] < end), 'decade'] = f'{year_list[i]}s'\n\n    return df\n\ndf = gen_df(filename)\n\n```\n\n### Descriptive Data\n\n In the following we generate summary statistics of year, ratings, duration, and number of ratings and wins. These are turned into an interactive tabel, where the viewer can choose to watch the statistics for the entire sample period, or for a given decade. \n\n\n```python\n# Summary Statistics by Decade  \n# Creating list of decades to choose between\ndecade = [\"all\", \"1920s\", \"1930s\", \"1940s\", \"1950s\", \"1960s\", \"1970s\", \"1980s\", \"1990s\", \"2000s\", \"2010s\"]\ngenre_new = ['Action', 'Adventure', 'Animation', 'Biography',\n         'Comedy', 'Crime', 'Documentary', 'Drama', 'Family', 'Fantasy',\n         'FilmNoir', 'History', 'Horror', 'Music', 'Musical',\n         'Mystery', 'Romance', 'SciFi', 'Short', 'Sport', 'Thriller', 'War', 'Western']\n\n# Defines a Summary Statistics function to call\ndef summ_stat(decade):\n    \"\"\" Generates a Summary Statistics Table \n    \n    Args: \n        decade (string): Decade for which the summary statistics are generated. \n                         These must be written in the format, \"[decade]s\", e.g. \"1920s\".\n        \n    Returns: \n        One table for each element in decade. \n        \n    Notice: The function is generated so that it can be called in the function summ_stat_interactive. Thus, it is not intended to be used on its own. \n    \n    \"\"\"\n    \n    \n    pd.options.display.float_format = \"{:.2f}\".format\n    if decade == \"all\": \n        return df[[\"year\", \"imdbRating\", \"duration\", \"nrOfWins\", \"nrOfNewsArticles\"]].describe() \n    else: \n        df_decade = df.loc[df[\"decade\"] == decade]\n        return df_decade[[\"year\", \"imdbRating\", \"duration\", \"nrOfWins\", \"nrOfNewsArticles\"]].describe() \n    \n# Define function which turns summary statistics function interactive\ndef summ_stat_interactive(): \n    \n    \"\"\" Generates a interactive Summary Statistics Table, using the function summ_stat. \"\"\"\n    \n    \n    widgets.interact(summ_stat, \n    \n    # Decade Dropdown \n    decade = widgets.Dropdown(\n    decription=\"Decade\", \n    options=decade, \n    value=\"all\"));\n\nsumm_stat_interactive()\n\n```\n\n\n    interactive(children=(Dropdown(description='decade', options=('all', '1920s', '1930s', '1940s', '1950s', '1960\u2026\n\n\n\n```python\n# Defining a function which rounds up to next hundred \ndef roundup(x):\n    \"\"\" Returns an integer which is perfectly divided by 100\n\n        Args: \n            x (float): The number to round up to next hundred\n\n        Returns: \n            A number (integer) \"\"\"\n    \n    return int(math.ceil(x / 100.0)) * 100\n\n## Defining a figure which plots the total numbers of movies per year or decade\ndef fig3_J():\n    \"\"\" Generates a figure which plots the total number of movies per decade or year\n    \n    Args: \n        No arguments are needed.\n        \n    Returns: \n        An interactive plot  \n        \n    Notice: \n        It will raise an error if the function is given an argument!\n    \"\"\"\n    \n    ## Copiyng the dataframe to a new dataframe\n    imdb = df.copy()\n    \n    ## Generating list for future use\n    time_var = ['year', 'decade']\n    decades = [1920, 1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010]\n    \n    ## Defining a function which plots the total numbers of movies per year or decade\n    def fig(time_var):   \n        \"\"\" Generates a figure which plots the total number of movies per decade or year\n        \n        Args: \n            time_var (string): Should be either 'year' or 'decade' depending on whether the \n            number of movies should be grouped by year or decade. \n           \n        Returns: \n            An interactive plot.  \n\n        Notice: \n            The function is generated so that it can be called using widgets.interact. \n            Thus, it is not intended to be used on its own. \n            \"\"\"\n        \n        # Generate variable that counts number of observation/movies in each year/decade\n        imdb['temp']=1\n        imdb['tot_film'] = imdb.groupby(time_var)['temp'].transform(lambda x : x.sum())\n        del imdb['temp']\n\n        # Make new dataframe that only take one value per year/decade. \n        # The dataframe only contain the year/decade indicator and number of movies in the given year/decade\n        y = pd.DataFrame(imdb.groupby(time_var)['tot_film'].first())\n        y.reset_index(inplace=True)\n\n        # Setting max value of y-axis to next hundred of max number of movies\n        temp = imdb['tot_film'].max()\n        y_max = roundup(temp)\n\n        # Plotting the number of movies per year\n        fig = plt.figure(figsize=(7,6))\n        ax1 = fig.add_subplot(1,1,1)\n\n        # Set different bar-width depending on the plot is movies per year or decade\n        if time_var == 'year':\n            ax1.bar(y[time_var], y['tot_film'], width=0.55)\n        else:\n            ax1.bar(y[time_var], y['tot_film'])\n\n        ax1.set_ylabel('Numbers of movies')\n        ax1.set_title(f'Figure 1: Numbers of movies, 1920-2013')\n        ax1.set_ylim([0,y_max])\n\n        # Set the ticks on the x-axis to be every 10th year (if the plots is movies per year)\n        if time_var == 'year':            \n            ax1.set_xticks(decades)\n            \n    ## Making the figure interactive so it is optionally to plot the number of movies per year or decade (year is default)\n    widgets.interact(fig,\n        time_var = widgets.Dropdown(description='Time unit', value='year', options=time_var, \n                    layout=Layout(width='175px')),\n    );    \n\nfig3_J()\n```\n\n\n    interactive(children=(Dropdown(description='Time unit', layout=Layout(width='175px'), options=('year', 'decade\u2026\n\n\nThe number of movies per year/decade has, not surprisingly, increased a lot since 1920, cf. figure 1. In the 2000s over 3300 movies were produced. This is 22 times more movies than in the 1920s where only 150 movies were produced. However, in the 2010s there was a huge drop in the numbers of movies (use 'decade' as time unit). The decrease in movies is partly due to the fact that 2010s only contains movies for four years (2010-2013). Additionally, the number of movies per year has also decreased compared to the last half of the 2000s. \n\nAs a final comment, we have to stress that we are not sure how representative our data is. Consequently, the lower number of movies per year in the 2010s could be due to imprecise data. This uncertianty prevails for the entire dataset because not all movies are in the IMDB-database. \n\n## Staring into the Eyes of Genres\n\n### Number of Movies in Each Genre\n\nHere, we summarize each genre varible. Since each of these are dummies, the sum will equal the number of movies in each genre. These sums are then printed through a loop, so the output is a list of genres and the number of movies in each genre. Finally, the list is sorted, such that the genre with the most movies appear at the top. \n\n\n```python\n# Generating genre list\ngenre = list(df)[13:41]\n\n# Counting movies in each genre\nsum_list = []\n\nfor i in genre:\n    sum_list.append(df[i].sum(axis=0))\n    \nsum_genre = pd.DataFrame({'Genre': genre,\n                        'Sum': sum_list}).sort_values('Sum', ascending=False)\n\nfor i, row in sum_genre.iterrows():\n    print(f\"Number of {row['Genre']} movies: {row['Sum']:.0f}\")\n```\n\n    Number of Drama movies: 5109\n    Number of Comedy movies: 3327\n    Number of Action movies: 1772\n    Number of Romance movies: 1707\n    Number of Crime movies: 1638\n    Number of Adventure movies: 1456\n    Number of Thriller movies: 1235\n    Number of Horror movies: 935\n    Number of Documentary movies: 778\n    Number of Mystery movies: 750\n    Number of SciFi movies: 731\n    Number of Family movies: 685\n    Number of Fantasy movies: 679\n    Number of Biography movies: 541\n    Number of Animation movies: 534\n    Number of History movies: 460\n    Number of War movies: 442\n    Number of Short movies: 380\n    Number of Musical movies: 332\n    Number of Western movies: 292\n    Number of Music movies: 269\n    Number of Sport movies: 205\n    Number of FilmNoir movies: 190\n    Number of Adult movies: 16\n    Number of TalkShow movies: 3\n    Number of RealityTV movies: 2\n    Number of GameShow movies: 2\n    Number of News movies: 2\n\n\n### Share of movies pr. genre\n\n\n```python\n# Generate genre list\ngenre_list = list(df)[13:41]\n\ndef genre_share_fig():\n    \"\"\" Returns a figure, which calculates the share of movies in the chosen genre. The share\n        can be calculated by either year or decade\"\"\"\n\n    def _plot_1(df,genre,timevar):\n        \"\"\" Calculates the share of movies in each genre chosen, by the timevariable chose, i.e. year or decade.\n        \n            Args:\n                df (DataFrame): Which dataframe is being used to do the calculation.\n                genre (str): Which genres the shares are calculated for. \n                timevar (str): Which timevariable are the shares calculated over? Can be year or decade\n            \n            Returns:\n                A line plot for all genres chosen.\n            \n            Notice:\n                Does not show plot by itself, but has to be activated through another function, e.g. widgets.interact\"\"\"\n\n        df['count'] = 1\n        df['movies_year'] = df.groupby(timevar)['count'].transform(lambda x: x.sum())  \n\n        # Plot year sum of different genres\n        for i in genre:\n        \n            # Calculate sum of movies by timevariable, and share of movies within time that is of a certain genre\n            df[f'{i}_time'] = df.groupby(timevar)[i].transform(lambda x: x.sum())\n            df[f'{i} share'] = df[f'{i}_time']/df['movies_year']\n\n            # Take first element of each timevariable group\n            y_share = df.groupby(timevar)[f'{i} share'].first()\n\n            # Plot the first elements\n            plt.plot(y_share)\n\n            # Add labels and title\n            plt.xlabel(timevar)\n            plt.ylabel('Share of movies')\n            if len(genre) == 1:\n                plt.title(f'Figure 2: Movies by genre: {i}')\n            elif len(genre) > 1:\n                plt.legend(loc='lower right')\n                plt.title(f'Figure 2: Movies by genres')\n\n    def plot_1(df):\n        \"\"\" Interaction function which interacts with _plot_1. The function activates two widgets,\n            for choosing genres and timevariable for _plot_1.\"\"\"\n\n        widgets.interact(_plot_1,\n                        df = widgets.fixed(df),\n                        genre = widgets.SelectMultiple(\n                            options = genre_list,\n                            description = 'Genres',\n                            value = ['Drama', 'Comedy', 'Action'],\n                            disabled = False),\n                        timevar = widgets.Dropdown(\n                        options = ['year', 'decade'],\n                        description = 'Timevariable',\n                        value = 'decade',\n                        disabled = False))\n\n    plot_1(df)\n\ngenre_share_fig()\n```\n\n\n    interactive(children=(SelectMultiple(description='Genres', index=(8, 5, 0), options=('Action', 'Adult', 'Adven\u2026\n\n\nFigure 2 shows the share of movies in a certain year or decade, which is by a selected genre. In the list above, we see that drama-, comedy-, and actionmovies are the three largest genres, measured by total movies in the dataset. Looking at the evolvement their shares, we see that the share of dramamovies has fallen almost steadily since the 1920's. The share of comedy movies is the same in the 2010's as in the 1920's, but had a relatively low share from the 1940's to the 1970's. The share of actionmovies has increased quite steadily since the 1920's.\n\nAnother interesting observation is the evolvement of westernmovies, which were popular from around the 1950's to 1970's but since then have had quite a low share of the total movies.\n\nLooking at war movies, we see a large increase in the share of movies around the 1940's, i.e. around World War II. Through the following Cold War, war movies held a relatively large though decreasing share of movies. In the 2010's they hold a relatively low share of movies.\n\n## Rated PG 13 - Parents Strongly Cautioned\n\n### Histogram of Number of Movies pr. Rating\n\nThe following code generates an interactive histogram, which shows the number of ratings by genre. \n\n\n```python\n# Interactive Histogram\ndef histogram(variable, genre, bins_num):\n    \"\"\" Generates histogram of variable per genre\n    \n    Args: \n        variable (string): Variable on the vertical axis\n        genre (string): Only movies of this genre is considered\n        bins_num (int): Number of bins in the histogram\n    \n    Notice: \n        Remember quotationmarks around variable \n        bins_num must be an integer, and does not accept floats\n    \n    \"\"\"\n    \n    df_hist = df.loc[df[genre] == 1]\n    plt.hist(df_hist[variable], bins=bins_num)\n    \n    # Labels\n    plt.title(\"Figure 3: Number of Movies pr. Rating\")\n    plt.xlabel(\"Rating\")\n    plt.xticks(range(1,11))\n    \n# histogram(\"imdbRating\", \"Comedy\", 10)   # Remember quote marks around variable names. \n\n\ndef hist_interactive(variable=\"imdbRating\"): \n    \"\"\" Generate interactive histogram of variable by genre\n    \n    Args: \n        variable (string): Variable on the vertical axis.\n        \n    Default variable = \"imdbRating\"\n    \n    \"\"\"\n    \n    \n    widgets.interact(histogram, \n    variable = widgets.fixed(variable), \n    \n    # Genre Dropdown\n    genre = widgets.Dropdown(\n    description=\"Genre\", \n    options=genre_new, \n    value=\"Comedy\"),\n    \n    # Bins slider \n    bins_num=widgets.IntSlider(\n    value=10,\n    description=\"Bins\", \n    min=10,\n    max=50, \n    step=1,\n    disabled=False,\n    continuous_update=False)\n    ); \n\nhist_interactive()\n```\n\n\n    interactive(children=(Dropdown(description='Genre', index=4, options=('Action', 'Adventure', 'Animation', 'Bio\u2026\n\n\nThis histogram show us that most genre ratings are centered around 7 or 8, and slightly scewed to the left. Genres with a lot of movies typically have a wider distribution, and thus more low-rated movies.  \n\n### Ratings over time\n\n\n```python\n## Defining a function which plots the average IMDB rating per year or decade\ndef fig2_J():\n    \"\"\" Generates a figure which plots the average IMDB rating (in levels and normalized) per year or decade\n    \n    Args: \n        No arguments are needed.\n        \n    Returns: \n        Two interactive plots\n        \n    Notice: \n        It will raise an error if the function is given an argument!\n    \"\"\"    \n    \n    ## Copiyng the dataframe to a new dataframe\n    imdb = df.copy()\n    \n    ## Generating list for future use\n    time_var = ['year', 'decade']\n    years = [1920, 1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010]\n    \n    \n    ## Defining function that plots the average IMDB rating (in levels and normalized) per year or decade\n    def fig(time_var):    \n        \"\"\" Generates a figure which plots the average IMDB \n        rating (in levels and normalized) per year or decade\n        \n        Args: \n            time_var (string): Should be either 'year' or 'decade' depending on if the \n            average ratings should be grouped by on year or decade. \n           \n        Returns: \n            Two interactive plot.  \n\n        Notice: \n            The function is generated so that it can be called using widgets.interact. \n            Thus, it is not intended to be used on its own. \n            \"\"\"        \n        # Creating variable that takes the average IMDB rating per year/decade\n        imdb['avg_rat'] = imdb.groupby(time_var)['imdbRating'].transform(lambda x : x.mean())\n        imdb['avg_rat_index'] = imdb['avg_rat'].transform(lambda x : x/x[0]*100)\n        \n        # Make two new dataframes that only take one value per year/decade. \n        # The dataframes only contain the year/decade indicator and average rating or normalized ratings per year/decade\n        y = pd.DataFrame(imdb.groupby(time_var)['avg_rat'].first())\n        y.reset_index(inplace=True)\n        \n        x = pd.DataFrame(imdb.groupby(time_var)['avg_rat_index'].first())\n        x.reset_index(inplace=True)\n\n        # Plotting the figures\n        fig = plt.figure(figsize=(13,6))\n        \n        # 1st Figure (ratings in level)\n        ax1 = fig.add_subplot(1,2,1)\n        ax1.plot(y[time_var], y['avg_rat'])\n        ax1.set_ylabel('Average rating')\n        ax1.set_title(f'Figure 4: Average IMDB rating, 1920-2013')\n        ax1.set_ylim([0,10])\n\n        #2nd Figure (normalized ratings)\n        ax2 = fig.add_subplot(1,2,2)\n        ax2.plot(x[time_var], x['avg_rat_index'])\n        if time_var == 'year':\n            ax2.set_ylabel(f'Index: 1920=100')\n        else:\n            ax2.set_ylabel(f'Index: 1920s=100')\n        ax2.set_title(f'Figure 5: Normalized average of IMDB rating, 1920-2013')\n        ax2.set_ylim([80,105])\n        \n        # Set the ticks on the x-axis to be every 10th year (if the plots are movies per year)\n        if time_var == 'year':            \n            ax1.set_xticks(years)            \n            ax2.set_xticks(years)\n            \n    ## Making the figure interactive so it is optionally to plot the ratings per year or decade (year is default)                    \n    widgets.interact(fig,\n        time_var = widgets.Dropdown(description='Time unit', value='year', options=time_var, \n                    layout=Layout(width='175px')),\n    );    \n\nfig2_J()\n```\n\n\n    interactive(children=(Dropdown(description='Time unit', layout=Layout(width='175px'), options=('year', 'decade\u2026\n\n\nSince the beginning of our dataset in 1920, the ratings have been trending downwards. From the 1920s to the 2010s, the average rating has decreased by one rating-point which is 12-13 percentage points lower, cf. figure 4 and 5. The average ratings have decreased in allmost all decades (use 'decade' as time unit), but the ratings have been quite volatile on a year-to-year basis.\n\nThe following figures try to explain the downwarding trend from the 1920s to the 2010s. \n\n### Do 'good' movies have better ratings?\n\n\n```python\n## Defining a function which plots the distribution of the IMDB rating conditioned on award wins\ndef fig1_J():\n    \"\"\" Generates a figure which plots the distribution of the IMDB rating conditioned on award wins\n    \n    Args: \n        No arguments are needed.\n        \n    Returns: \n        An interactive plots\n        \n    Notice: \n        It will raise an error if the function are given an argument!\n    \"\"\"   \n    \n    ## Copiyng the dataframe to a new dataframe\n    imdb = df.copy()\n    \n    ## Creating variable that groups number of wins and a list with the intervals\n    imdb['nrw'] = 0\n    imdb.loc[(imdb['nrOfWins'] > 0) & (imdb['nrOfWins'] < 10), ['nrw']] = 1\n    imdb.loc[(imdb['nrOfWins'] >= 10) & (imdb['nrOfWins'] < 20), ['nrw']] = 2\n    imdb.loc[(imdb['nrOfWins'] >= 20) & (imdb['nrOfWins'] < 30), ['nrw']] = 3\n    imdb.loc[(imdb['nrOfWins'] >= 30) & (imdb['nrOfWins'] < 40), ['nrw']] = 4\n    imdb.loc[(imdb['nrOfWins'] >= 40), ['nrw']] = 5\n    \n    nrwins = ['0', '1-10', '11-20', '21-30', '31-40', '+40']\n\n    \n    ## Defining a function to plot the distribution of the IMDB rating condition on award wins\n    def fig(win_0, win_110, win_1120, win_2130, win_3140, win_40):\n        \"\"\" Generates a figure which plots which plots the \n        distribution of the IMDB rating conditioned on award wins\n        \n        Args: \n            win_0: Specifies whether to plot the distribution of ratings for movies with 0 wins \n            win_110: Specifies whether to plot the distribution of ratings for movies with 1-10 wins \n            win_1120: Specifies whether to plot the distribution of ratings for movies with 11-20 wins \n            win_2130: Specifies whether to plot the distribution of ratings for movies with 21-30 wins \n            win_3140: Specifies whether to plot the distribution of ratings for movies with 31-40 wins \n            win_40: Specifies whether to plot the distribution of ratings for movies with +40 wins \n           \n        Returns: \n            An interactive plot.  \n\n        Notice: \n            The function is generated so that it can be called using widgets.interact. \n            Thus, it is not intended to be used on its own. \n            \"\"\"         \n        \n        # Make lists to plot the win categories and give them colors\n        wins = [win_0, win_110, win_1120, win_2130, win_3140, win_40]\n        color = ['red', 'orange', 'yellow', 'lime', 'blue', 'purple']\n        \n        # Loop over win category to plot the distribution of their ratings\n        for i,val in enumerate(nrwins):\n            nrwins_i = imdb.loc[(imdb['nrw'] == i)]\n            if wins[i] == True:  # Only plot distribution if box is 'checked'\n                sns.distplot(nrwins_i['imdbRating'], hist = False, kde = True,\n                         kde_kws = {'linewidth': 2}, label = val, color=color[i]\n                     )\n        \n        # Legends and labels        \n        plt.legend(loc='upper left')\n        plt.title('Figure 6: IMDB rating conditioned on numbers of award wins')\n        plt.xlabel('IMDB rating')\n        plt.ylabel('Density')\n    \n    # Making the figure interactive so it is optinally which wins categories to plot\n    widgets.interact(fig,\n        win_0=widgets.Checkbox(description=nrwins[0], value=True, disabled=False),\n        win_110=widgets.Checkbox(description=nrwins[1], value=True, disabled=False),\n        win_1120=widgets.Checkbox(description=nrwins[2], value=True, disabled=False),\n        win_2130=widgets.Checkbox(description=nrwins[3], value=True, disabled=False),\n        win_3140=widgets.Checkbox(description=nrwins[4], value=True, disabled=False),\n        win_40=widgets.Checkbox(description=nrwins[5], value=True, disabled=False),\n    );\n\nfig1_J()\n```\n\n\n    interactive(children=(Checkbox(value=True, description='0'), Checkbox(value=True, description='1-10'), Checkbo\u2026\n\n\nAn obvious hypothesis is that better movies have better ratings. A simple way to meassure the quality of a movie is to use the number of award wins as a proxy for quality. In line with the hypothesis, there is a positive correlation between award wins and ratings, cf. figure 6. Movies with many award wins have better ratings, and they have less variance in the ratings. \n\nHowever, the causality between award wins lead to better ratings may suffer by reverse causality. We are using cross-sectional data and cannot reject that ratings increase as a consequence of award wins. This will be the case if a person's subjective opinion is affected by other people's opinion, i.e. if the movie has won one or several awards. In the case of panel data with ratings for the same movie over time, we could control for this kind of reverse cuasality. \n\n### Average ratings by decade\n\n### Swarm Plot of Ratings pr. Decade\n\n\n```python\n## NB: This peice of code takes a while to run!\n\n# Swarm plot (Consider comparing decades) \ndef swarm_plot(y=\"imdbRating\"): \n    \"\"\" Creates a Swarm plot of y by decade\n    \n    Args:\n    \n        y (string): Variable on vertical axis. \n        \n    Default: y = \"imdbRating\"\n    Remember quotation marks around y. \n    \n    \"\"\"\n    \n    fig = plt.figure(figsize=(10,6))\n    ax1 = fig.add_subplot(1,1,1)\n    ax1 = sns.swarmplot(x = \"decade\", y = y, data=df)\n    if y == \"imdbRating\": \n        ax1.set_title(\"Figure 7: Ratings pr. Decade\")\n        ax1.set_ylabel(\"Ratings\")\n    elif y == \"nrOfWins\": \n        ax1.set_title(\"Figure 7: Wins pr. Decade\")\n        ax1.set_ylabel(\"Nr. of Wins\")\n    elif y == \"nrOfNominations\": \n        ax1.set_title(\"Figure 7: Nominations pr. Decade\")\n        ax1.set_ylabel(\"Nr. of Nominations\")\n    elif y == \"duration\": \n        ax1.set_title(\"Figure 7: Duration pr. Decade\")\n        ax1.set_ylabel(\"Duration\")\n    else: \n        ax1.set_title(f\"Figure 7: {y} pr. Decade\")\n        ax1.set_ylabel(y)\n    ax1.set_xlabel(\"Decade\")\n    \n\nswarm_plot()\n```\n\nFrom this swarm plot, we see that the diversity in ratings has grown across time. This is probably due to the fact, that the number of movies has been increasing since the 1920's. Though more movies are produced today, the quality of each movie is hard to maintain. However, there might be a bias, as people who watch and rate older movies on IMDB might really like these, and thus give them higher ratings, or that only the good movies from the 19020's and 1930's are listed in the IMDB dataset which we use. \n\nThe swarm plot support our theory that a selection bias could be one reason to the decreasing ratings. On the other hand we cannot exclude that there are more bad movies today compared to 1920s.\n\n### Conclusion\n\nWe have reached the climax and heading towards the end. We hope you have enjoyed the journey through the universe of the movies, and we are happy to say: *Chewie, we're home*. We are sorry if you think it has been a completely waste of your time, but just remember *always look on the bright sight of life* and hopefolly there is *no worries for the rest of your day(s)*. However, we admit that you could feel that you did not get the full story, not all the details. And you are completely right, we have not told you everything for the simply reason *you can't handle the truth*. Jokes apart, we will not take any more of your time, and we have nothing else to say than *hasta la vista, baby*. \n\n*The End*.\n\n\n\n# Python's Next Top Model\nBy The Good, The Bad and the Ugly\naka. The Three Musketeers.\n\nWelcome back to the wonderful Python universe of Credible Threats. We will continue the exploration of movies, and we're sure that our data project notebook will look at this notebook and think, *you complete me*. You might want to ask, *Magic mirror on the wall, who's the fairest one of all*, and the answer will be this notebook. This notebook will try to estimate the IMDb ratings of movies. And as a bonus, we even have a live-updating figure, which will leave you thinking, *it's alive, it's alive*. \n\nWe will calculate the utility of each movie, given genres, awards, duration and so forth, and we will try to calculate the IMDb ratings for each movie, based on this utility. Finally, we will minimize the distance between our estimated ratings and the actual IMDb ratings. Now, we're sure you're thinking, *show me the money*, so this is it. \n\nOur utility function is given by: \n$$ U_i = \\sum_{k=1}^{23}(\\alpha_k G_{ik}) + \\sum_{k=1920}^{2010} (\\beta_k D_{ik}) + \\gamma N_i + \\delta W_i + \\rho L_i $$. \n\n$$\\text{Where, } G_{ik} \\text{ is genre } k \\text{, } D_{ik} \\text{ is decade } k \\text{, } N_i \\text{ is award nominations, } W_i \\text{ is award wins, and } L_i \\text{ is duration. } $$ \n\nI think we can agree, it is *beauty kills the beast*. \nNow, based on this utility function, we will estimate the ratings of each movies,\n$$ R_i^{model} = \\frac{\\exp(\\omega x_i')}{1 + \\exp(\\omega x_i')} $$ \n\nwhere, \n$$ x_i = \\big[G_1, G_2, ..., G_{23}, D_{1920}, D_{1930}, ..., D_{2010}, N_i, W_i, L_i \\big] $$\n$$ \\omega = \\big[\\alpha_1, \\alpha_2, ..., \\alpha_{23}, \\beta_{1920}, \\beta_{1930}, ..., \\beta_{2010}, \\gamma, \\delta, \\rho_1 \\big] $$\n\nWe then use optimize methods to solve the following: \n$$ \\min_{\\omega} \\Big\\{ \\sum_{i=1}^{n} \\left( R_i^{model} - R_i^{data} \\right)^2 \\Big\\} $$\n\n$$ \\text{where, } R_i^{data} \\text{ are the true IMDb ratings from the dataset, and} R_i^{model} \\text{are the ratings calculated from the utility function.}$$\n\nThroughout our notebook, you might *feel the need - the need for speed*. But, *patience you must have, my young Padawan*, because optimizing takes time. \n\n*Of all the python notebooks in all the towns in all the world, you walk into ours*. How lucky you are, you'll soon see why. \n\nSo, *say hello to my little friend*, Python's next top model.  \nLet's *get busy coding, or get busy dying*. \n\n\n\n\n\n\n```python\n# List for later use \nvariables = ['Action','Adventure','Animation','Biography','Comedy','Crime','Documentary',\n            'Drama','Family','Fantasy','FilmNoir','History','Horror','Music','Musical',\n            'Mystery','Romance','SciFi','Short','Sport','Thriller','War','Western',\n            'decade_1920','decade_1930','decade_1940','decade_1950','decade_1960',\n            'decade_1970','decade_1980','decade_1990','decade_2000','decade_2010',\n            'nrOfNominations','nrOfWins','duration']\n\nvars_dec = ['Action','Adventure','Animation','Biography','Comedy','Crime','Documentary',\n        'Drama','Family','Fantasy','FilmNoir','History','Horror','Music','Musical',\n        'Mystery','Romance','SciFi','Short','Sport','Thriller','War','Western',\n        'nrOfNominations','nrOfWins','duration']\n\ndecade_list = [1920, 1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010]\n\n\n# Function to calculate squared mean differences \ndef sqr_diff_sum(df_X,pars):\n    \"\"\" Generates a float of the sum of squared differences between the ratings from the data and the model. \n\n    Args: \n        df_X (DataFrame): DataFrame containing the variable in x for all observations.\n        pars (List): List of parameters in omega\n\n    Returns: \n        A float.\n    \"\"\"\n    # Calculate the matrix product between omega and X\n    util = df_X@pars  \n    # Scale the product so it's between 0 and 10. This is the R_model\n    df_Y['rat_model'] = 10*np.exp(util)/(1+np.exp(util)) \n    # Calculate the squared difference between R_data and R_model\n    df_Y['sqr_diff'] = (df_Y['rat_model']-df_Y['rat_data'])**2 \n\n    return df_Y['sqr_diff'].sum() # Returns the sum of the squared differences\n```\n\n\n```python\ndef gen_df(filename):\n\n    # Get .csv.file\n    data = pd.read_csv(filename, sep=';', encoding='latin-1', escapechar='\\\\')\n\n    # Read file into pandas dataframe\n    df = pd.DataFrame(data)\n\n    # Drop unwanted columns\n    for i in range(44,48):\n        df.drop(columns=[f'Unnamed: {i}'], inplace=True)\n\n    # Filters out movies with less than 5000 ratings and drops some genres and other columns\n    df = df.loc[(df['ratingCount']>=5000)]\n    df.drop(columns=['fn','wordsInTitle','url','Adult','GameShow','News','RealityTV','TalkShow'], inplace=True)\n\n    # Keep only observations of movie-type\n    I = df['type'] == 'video.movie'\n    df = df.loc[I]\n    df.drop(columns=['type'], inplace=True)\n\n    # Drop observations with missing data\n    df.dropna(inplace=True)\n\n    # Replace 0's in imdb-ratings\n    df['imdbRating'] = df['imdbRating'].astype(str)\n    df['imdbRating'].replace(regex=True, inplace=True,to_replace='0',value='')\n    df['imdbRating'] = df['imdbRating'].astype(float)\n\n    # Transform duration from seconds to hours\n    df['duration'] = df['duration']/60**2\n\n    # Drop years before 1920 and 2014 because of few obervations\n    I = (df['year']>=1920) & (df['year']<=2013)\n    df = df.loc[I]\n\n    # Change the type of 'year' to integer\n    df['year'] = df['year'].astype(int)    \n    \n    # Sort observations and reset index\n    df.sort_values('year', inplace=True)\n    df.reset_index(inplace=True)\n\n\n    # Generating variable that shows the decade (as a string)\n    year_list = [1920, 1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010]\n\n    df['decade'] = ''\n    for i,start in enumerate(year_list):\n        end = start+10\n        df.loc[(df['year'] >= start) & (df['year'] < end), 'decade'] = f'{year_list[i]}s'\n\n    return df\n```\n\n\n```python\ndef df_s(keep_top=None, decade=None):\n    \"\"\" Prepares data for optimization by creating dummmy-variables for decades, dropping movies with less than 5000 ratings,\n        dropping some variables that we don't wish to use in the model, and splitting the dataset, so we have a data set\n        consisting only of the variables used in the model.\n        \n    Args:\n        keep_top (optional, type: int): When a number (n) is put in this option, only the top n movies a kept in the dataset. This is used to remove movies for a better fit of the model\n\n    Returns:\n        df_X (type: Pandas dataframe): A dataframe consisting only of the varaibles that are used to calculate the rating.\n        df_Y (type: Pandas dataframe): A dataframe consisting of the true ratings from the dataset and an index-variable, used for merging with original dataset, later in the process.\n\n    Notice:\n        The function includes global for 'df', which means that the dataframe 'df' generated, can be called outside the function. This is used so that we won't have to filter the original dataframe everytime we use it.\n    \"\"\"\n    global df\n\n    # Calls the file 'imdb.csv' which is located in the repository, and contains the dataset used\n    filename = 'imdb.csv'\n\n    # A function generated earlier, which cleans the dataset [Should we include this, and do some of the filtering below in that funciton?]\n    df = gen_df(filename)\n            \n    # Keeps only top n movies, if this is specified when calling the function\n    if keep_top != None:\n        df = df.sort_values('imdbRating', ascending=False)\n        df = df.iloc[:keep_top]\n    \n    if decade == None:\n        # Decade dummies\n        for i in decade_list:\n            df[f'decade_{i}'] = 0\n            df.loc[(df['decade'] == f'{i}s'),f'decade_{i}'] = 1\n        \n        # Splits the dataset into two datasets\n        df_X = df.copy()\n        df_Y = pd.DataFrame(df[['imdbRating', 'index']].copy())\n        df_Y = df_Y.rename(columns = {'imdbRating':'rat_data'})\n\n        # Rearrange and keep given columns \n        df_X = df_X.reindex(['Action','Adventure','Animation','Biography','Comedy','Crime','Documentary',\n                              'Drama','Family','Fantasy','FilmNoir','History','Horror','Music','Musical',\n                              'Mystery','Romance','SciFi','Short','Sport','Thriller','War','Western',\n                              'decade_1920','decade_1930','decade_1940','decade_1950','decade_1960',\n                              'decade_1970','decade_1980','decade_1990','decade_2000','decade_2010',\n                              'nrOfNominations','nrOfWins','duration'], axis=1)\n            \n    \n    if decade != None:\n        # Keeps movies from the specified decade\n        df = df.loc[df['decade'] == f'{decade}s'] \n\n        # Splits the dataset into two datasets\n        df_X = df.copy()\n        df_Y = pd.DataFrame(df[['imdbRating', 'index']].copy())\n        df_Y = df_Y.rename(columns = {'imdbRating':'rat_data'})\n\n        # Rearrange columns and keep the specified variables \n        df_X = df_X.reindex(['Action','Adventure','Animation','Biography','Comedy','Crime','Documentary',\n                                  'Drama','Family','Fantasy','FilmNoir','History','Horror','Music','Musical',\n                                  'Mystery','Romance','SciFi','Short','Sport','Thriller','War','Western',\n                                  'nrOfNominations','nrOfWins','duration'], axis=1)\n\n\n    return df_X, df_Y\n```\n\n## Optimization\nWe analyze preferences for movies by minimizing the sum of the squared differences from our model prediction and the true rating, i.e.:\n$$ \n\\min_{\\omega} \\Big\\{ \\sum_{i=1}^{n} \\left( R_i^{model} - R_i^{data} \\right)^2 \\Big\\} \n$$ \nBy doing so, we'll find parameters that best describe movie preferences given our model. As we will discuss later, our model is not necessarily the best model to describe preferences, which might lead to these preferences not being accurate. <br>\nIf the model could predict all movie ratings correctly the parameters would perfectly describe movie preferences. For example if the parameter for action-movies were negative, the prediction would be precise, if action-movies generally had a negative impact on ratings. Of course people have much different preferences, and an interesting analysis would be, to predict preferences for different people, and by this look at a distribution of these parameters. This is not included in this project, though, mainly because of we don't have the data for it. <br>\nTo shorten the length of the optimizing process, and to sort out movies that makes it harder for the model to predict preferences, the optimization can be based on the top n movies, based on IMDb rating. When all movies are included in the optimizer the lowest ranking movies will have ratings around 2. Our rating predictor will in this case not rank any movies under 5. Thereby it is clear that the predictor model is not able to predict movies with very low rating. But it is able to predict movies with higher ratings.\n\n\n```python\ndef optimizer(keep_top=None, live_graph=True):\n    \"\"\" Creates and optimizes the function which calculates rating based on variables in the dataset.\n    \n    Args:\n        keep_top (optional, type: int): When a number (n) is put in this option, only the top n movies a kept in the dataset. This is used to sort out movies for a better fit of the model\n        live_graph(optional, type: boolean): Produces a live graph of the optimization proces, plotting the function values against the iterations. Makes the optimizer slower, but is a good visualization of the process.\n                                             \n    Returns:\n        result (type: scipy optimizer object): An object containing results from the optimizer among other information such as status etc.\n        timer (type: int): Time of running optimizer in seconds.\n                                               \n    Notice:\n        Uses the package scipy.optimize.minimize which optimizes functions based on a given method. Here 'Nelder-Mead' is used.\n        This function defines a set of functions used in the optimizer which are not documented by docstring but comments in code.\n    \"\"\"\n    # \"Initializes\" a timer for printing time of optimization\n    start = time.time()\n    \n    # Set of globals, so variables can be called inside the functions defined in this function\n    global fs\n    global evals\n    global x0\n    global df\n    global df_Y\n        \n    # Plots a live graph of optimization process, if chosen.\n    if live_graph:\n        # The live plot is created by taking the function value for each iteration and saving in a list\n        def live_plot(evals, fs, ymax=10000, figsize=(7,5)):\n            # Clears plot every time a new plot is created\n            clear_output(wait=True)\n            plt.figure(figsize=figsize)\n\n            # Plots values and sets title, grid, labels, etc.\n            plt.plot(evals, fs)\n            plt.title('Figure 8: Optimizing path')\n            plt.grid(True)\n            plt.xlabel('Iterations')\n            plt.ylabel('Function value')\n            plt.xlim(0,17500)\n            plt.ylim(0,ymax)\n\n            plt.show();\n\n    # Function to be called by optimizer each iteration. This returns function values for each iteration and plots live graph\n    def collect(x):\n        # Set of globals to be called in live graph-function\n        global fs\n        global evals\n        global x0\n        global fig\n        global ax\n        global ymax\n        global x_1, x_2, x_3, x_4, x_5, x_6, x_7, x_8, x_9, x_10, x_11, x_12, x_13, x_14, x_15, x_16, x_17, x_18, x_19, x_20\n        global x_21, x_22, x_23, x_24, x_25, x_26, x_27, x_28, x_29, x_30, x_31, x_32, x_33, x_34, x_35, x_36\n\n\n        # Calculates function value for initial guess, for first iteration\n        if evals == 0:\n            fs = []\n            fs.append(obj_fun(x0))\n            # Generates vector of parameter estimates\n            for i in range(1,37): # 1 to 36\n                globals()[f'x_{i}'] = [x0[i-1]]\n\n        # Calculates function values for current parameter values\n        if evals != 0:\n            fs.append(obj_fun(x))\n        \n        # Plots live graph if chosen\n        if live_graph:\n            # Calculates max y-value for axis for first iteration\n            if evals == 1:\n                ymax = math.ceil(obj_fun(x)/2000)*2000\n\n            # Updates plot every 100th iteration for the first 1000 iterations\n            if evals < 1000:\n                if evals > 0 and evals%100 == 0:\n                    live_plot(range(evals+1), fs, ymax)\n            # Updates plot every 500th iteration for the rest of the process\n            if evals >=1000:\n                if evals%500 == 0:\n                    live_plot(range(evals+1), fs, ymax)\n        \n        # Appends esimtates to x_vectors \n        for i in range(1,37):\n            globals()[f'x_{i}'].append(x[i-1])\n\n        # Adds one to the number of iterations each iteration\n        evals += 1\n    \n    # Define datasets to be used using function defined earlier\n    df_X, df_Y = df_s(keep_top=keep_top, decade=None)\n    \n    # Intiial guess\n    x0 = np.zeros(len(variables))\n    \n    # Start iteration number\n    evals = 0\n    \n    # Defines function to be minimized\n    obj_fun = lambda x: sqr_diff_sum(df_X,x)\n    \n    # Run optimizer\n    result = optimize.minimize(obj_fun,x0,\n                               method=\"Nelder-Mead\",\n                               options={\"disp\":True, \"maxiter\":50000}, # display the results\n                               callback=collect\n                               ) \n    \n    # End timer\n    end = time.time()-start\n    \n    # Returns\n    return result, end\n```\n\n\n```python\n# Run optimizer function and print results and time\nresult, timer = optimizer()\nprint(f'{\" \":9s}Time: {timer:.4f} seconds')\n\n# Keep copy of df and df_Y for later purpose\ndf_Y_all = df_Y.copy()\ndf_all = df.copy()\n```\n\n\n```python\n## Convergence of Parameter Estimates \n\n# Constructing dataframe which contains all parameter vectors as variables\npar_dict = {\"Action\": x_1,\n             \"Adventure\": x_2,\n             \"Animation\": x_3,\n             \"Biography\": x_4,\n             \"Comedy\": x_5,\n             \"Crime\": x_6,\n             \"Documentary\": x_7,\n             \"Drama\": x_8, \n             \"Family\": x_9,\n             \"Fantasy\": x_10,\n             \"Film Noir\": x_11,\n             \"History\": x_12,\n             \"Horror\": x_13,\n             \"Music\": x_14,\n             \"Musical\": x_15,\n             \"Mystery\": x_16,\n             \"Romance\": x_17,\n             \"SciFi\": x_18, \n             \"Short\": x_19,\n             \"Sport\": x_20,\n             \"Thriller\": x_21,\n             \"War\": x_22,\n             \"Western\": x_23,\n             \"1920's\": x_24,\n             \"1930's\": x_25,\n             \"1940's\": x_26,\n             \"1950's\": x_27,\n             \"1960's\": x_28,\n             \"1970's\": x_29,\n             \"1980's\": x_30,\n             \"1990's\": x_31,\n             \"2000's\": x_32,\n             \"2010's\": x_33,\n             \"Nr. of Nominations\": x_34, \n             \"Nr. of Wins\": x_35, \n             \"Duration\": x_36\n            }\n\ndf_par = pd.DataFrame(par_dict)\n\n\n##  Interactive graph of parametervalues for each iteration in optimizer \n# Chose which parameter to show \n\n# Interactive graph of parameter estimates\ndef graph(par):\n    \"\"\"\n    Constructs a graph which shows the progress in parameter estimates foreach iteration in\n    the optimizing process. \n    \n    Args: \n        par (type: str): Variable name, for which the graphs shows the parameter estimates. \n                \n    Returns: \n        Graph of progress in parameter estimates. \n        \n    Notice: \n        The function is meant to be called within the graph_int function. \n        The graph_int function turns this graph into an interactive function, where the \n        user can choose between variables. \n        Thus, the graph is not meant to be run on its own. \n    \"\"\"\n    # Generating figure \n    plt.plot(df_par[par])\n    \n    # Grid and axes \n    plt.grid(True)\n    plt.axhline(df_par[par].iloc[-1], linestyle=\"dashed\", color=\"orange\", label=\"Optimum\")\n    \n    # Labels and Titles \n    plt.title(\"Figure 9: Progress in Parameter Estimation\")\n    plt.ylabel(\"Parameter Estimate\")\n    plt.xlabel(\"Nr. of Iterations\")\n    plt.legend()\n\n\n# Interactive part: Choose between parameters \ndef graph_int(): \n    \"\"\"\n    Constructs interactive graph from the graph function. \n    \"\"\"\n    widgets.interact(graph, \n                     par = widgets.Dropdown( \n                     description=\"Variable\", \n                     options=df_par.columns.values, \n                     value=\"Action\"));\ngraph_int()\n\n\n```\n\n\n    interactive(children=(Dropdown(description='Variable', options=('Action', 'Adventure', 'Animation', 'Biography\u2026\n\n\nFrom the above figure, we notice that most parameter estimates are very volatile in the first 10,000-15,000 iterations, following which they converge towards the optimum value. \n\nHowever, this does not appear to be the case for the variables, Nr. of nominations and Nr. of awards, which get quite close to the optimum value at around the 7500th iteration. \nAdditionally, we notice that the variable Duration appears to have the largest effect on ratings, which the optimzer seems to realize after approximately 2500 iterations. \n\nIn the next part of the project we will plot the optimal estimates in a figure. Furthermore, we show how the estimates changes a lot when the sample size is restricted to only the best movies. \n\n\n```python\n## This piece of code solves the model for three different sample size\n\n#### OBS: The code will take a couple of minutes to run because the model is solved three times!! ####\n\n# List to store result for the optimization with the different sample sizes\nresults_list = [result.x]\n\n# This loop solve the model for the top 500, 1000, and 2000 movies\nfor i in [500, 1000, 2000]:\n    res_temp, timer_temp = optimizer(keep_top=i, live_graph=False)\n    temp = res_temp.x\n    print(f'{\" \":9s}Time: {timer_temp:.4f} seconds')\n    results_list.append(temp) # Store the results in the 'results_list'\n```\n\n    Optimization terminated successfully.\n             Current function value: 197.838633\n             Iterations: 13628\n             Function evaluations: 15779\n             Time: 59.2420 seconds\n    Optimization terminated successfully.\n             Current function value: 439.055453\n             Iterations: 21224\n             Function evaluations: 24448\n             Time: 98.0749 seconds\n    Optimization terminated successfully.\n             Current function value: 903.321786\n             Iterations: 16176\n             Function evaluations: 18626\n             Time: 84.8206 seconds\n\n\n\n```python\n## The code creates an interactive plot of the estimated parameters for all variables. \n## In the interactive part you can choose between estimates when the model is solved \n## for all movies or just top top 500, 1000, or 2000 rated movies. \n\ndef fig_2(val):\n    \"\"\" Generates a figure which plots estimated parameters for all variables.\n\n    Args: \n        val (string or int): Should be one of the elements in the options-list\n\n    Returns: \n        One interactive plot.  \n\n    Notice: \n        The function is generated so that it can be called using widgets.interact. \n        Thus, it is not intended to be used on its own. \n    \"\"\"   \n    # Initiates figure\n    fig = plt.figure(figsize=(12,6))\n    ax1 = fig.add_subplot(1,1,1)\n    \n    # Plots the estimated parameters for the chosen sample of movies\n    ax1.bar(variables, results_list[options.index(val)], label=f'Estimates with {options[options.index(val)]} movies')\n    \n    # Scatter plot with the estimated paramters for the entire sample \n    ax1.scatter(variables, results_list[0], marker='D', s=15, zorder=2, label='Estimates with all movies')\n    \n    # Legends and labels \n    ax1.legend(loc=\"lower right\")\n    ax1.set_ylabel('Parameter estimates')\n    ax1.set_title(f'Figure 10: Parameter estimates for {options[options.index(val)]} movies')\n    ax1.set_ylim([-0.7,0.7])\n    ax1.axhline(y=0,color='black',linewidth=1)\n    for tick in ax1.get_xticklabels():\n        tick.set_rotation(90)\n        \noptions = ['All', 500, 1000, 2000] # Option list\n\n# Making the figure interactive so the estimates are shown for the chosen sample size \nwidgets.interact(fig_2,\n    val = widgets.Dropdown(description='Nr. of movies', value='All', options=options, \n                ),\n);   \n```\n\n\n    interactive(children=(Dropdown(description='Nr. of movies', options=('All', 500, 1000, 2000), value='All'), Ou\u2026\n\n\nAs also showed in the list above, duration is the varaible that effects the ratings the most. This is also the case when the model is solved for top 500, 1000, and 2000 rated movies, cf. figure 3. However, it seems like duration is the only estimate which is fairly stable. The sign of the decade dummies is an example. When the model is solved for the entire sample, the estimates are positive for the older decade-dummies, i.e. the 1920s and 1930s, and negative for the newer decade-dummies, the 2000s and 2010s. However, when the sample only contains the top 2000 rated movies we see the opposite picture. We know from figure 10 in our dataproject that the ratings of the younger movies have a larger variance with more high-rated movies but also a lot of poorly rated movies. By restricting the sample to only the best movies we drop all the bad new movies, and this is probably the reason to the positive estimates of the newer movies. \n\n## Heterogeneous agents\nIn the model above, we have only allowed the agents to have some type of preferences. But in reality people have different preferences, and thus we solve the model allowing for two types of preferences. The utility function is still the same, but with two sets of parameters, $\\omega_1$ and $\\omega_2$:\n\n$$ R_i^{model1} = \\frac{\\exp(\\omega_1 x_i')}{1 + \\exp(\\omega_1 x_i')} $$ \n$$ R_i^{model2} = \\frac{\\exp(\\omega_2 x_i')}{1 + \\exp(\\omega_2 x_i')} $$ \n$$ R_i^{model} = \\pi R_i^{model1} + (1-\\pi) R_i^{model2} $$\nwhere $\\pi$ is the share of type 1 agents. \n\nThe rest of the optimization is as stated in the introduction.\n\n\n```python\n# Function to calculate squared mean differences \ndef sqr_diff_sum_het(df_X,pars):\n    \"\"\" Generates a float of the sum of squared differences between the ratings from the data and the model. \n\n    Args: \n        df_X (DataFrame): DataFrame containing the variable in x for all observations.\n        pars (List): List of parameters in omega\n\n    Returns: \n        A float.\n    \"\"\"\n    # Calculate the matrix product between omega and X\n    util1 = df_X@pars[1:1+len(variables)]\n    util2 = df_X@pars[1+len(variables):]\n    # Scale the product so it's between 0 and 10. This is the R_model\n    df_Y['rat_model1'] = 10*np.exp(util1)/(1+np.exp(util1)) \n    df_Y['rat_model2'] = 10*np.exp(util2)/(1+np.exp(util2)) \n    Y = lambda pi: pi*df_Y['rat_model1']+(1-pi)*df_Y['rat_model2']\n    # Calculate the squared difference between R_data and R_model\n    df_Y['sqr_diff'] =  (Y(pars[0])-df_Y['rat_data'])**2 \n\n    return df_Y['sqr_diff'].sum() # Returns the sum of the squared differences\n```\n\n\n```python\ndef optimizer(keep_top=None, live_graph=True):\n    \"\"\" Creates and optimizes the function which calculates rating based on variables in the dataset.\n    \n    Args:\n        keep_top (optional, type: int): When a number (n) is put in this option, only the top n movies a kept in the dataset. This is used to sort out movies for a better fit of the model\n        live_graph(optional, type: boolean): Produces a live graph of the optimization proces, plotting the function values against the iterations. Makes the optimizer slower, but is a good visualization of the process.\n                                             \n    Returns:\n        result (type: scipy optimizer object): An object containing results from the optimizer among other information such as status etc.\n        timer (type: int): Time of running optimizer in seconds.\n                                               \n    Notice:\n        Uses the package scipy.optimize.minimize which optimizes functions based on a given method. Here 'Nelder-Mead' is used.\n        This function defines a set of functions used in the optimizer which are not documented by docstring but comments in code.\n    \"\"\"\n    # \"Initializes\" a timer for printing time of optimization\n    start = time.time()\n    \n    # Set of globals, so variables can be called inside the functions defined in this function\n    global fs\n    global evals\n    global x0\n    global df\n    global df_Y\n        \n    # Plots a live graph of optimization process, if chosen.\n    if live_graph:\n        # The live plot is created by taking the function value for each iteration and saving in a list\n        def live_plot(evals, fs, ymax=10000, figsize=(7,5)):\n            # Clears plot every time a new plot is created\n            clear_output(wait=True)\n            plt.figure(figsize=figsize)\n\n            # Plots values and sets title, grid, labels, etc.\n            plt.plot(evals, fs)\n            plt.title('Figure 11: Optimizing path')\n            plt.grid(True)\n            plt.xlabel('Iterations')\n            plt.ylabel('Function value')\n            plt.xlim(0,125_000)\n            plt.ylim(0,ymax)\n\n            plt.show();\n\n    # Function to be called by optimizer each iteration. This returns function values for each iteration and plots live graph\n    def collect(x):\n        # Set of globals to be called in live graph-function\n        global fs\n        global evals\n        global x0\n        global fig\n        global ax\n        global ymax\n        global x_1, x_2, x_3, x_4, x_5, x_6, x_7, x_8, x_9, x_10, x_11, x_12, x_13, x_14, x_15, x_16, x_17, x_18, x_19, x_20\n        global x_21, x_22, x_23, x_24, x_25, x_26, x_27, x_28, x_29, x_30, x_31, x_32, x_33, x_34, x_35, x_36\n\n\n        # Calculates function value for initial guess, for first iteration\n        if evals == 0:\n            fs = []\n            fs.append(obj_fun(x0))\n            # Generates vector of parameter estimates\n            for i in range(1,37): # 1 to 36\n                globals()[f'x_{i}'] = [x0[i-1]]\n\n        # Calculates function values for current parameter values\n        if evals != 0:\n            fs.append(obj_fun(x))\n        \n        # Plots live graph if chosen\n        if live_graph:\n            # Calculates max y-value for axis for first iteration\n            if evals == 1:\n                ymax = math.ceil(obj_fun(x)/2000)*2000\n\n            # Updates plot every 100th iteration for the first 1000 iterations\n            if evals < 1000:\n                if evals > 0 and evals%100 == 0:\n                    live_plot(range(evals+1), fs, ymax)\n            # Updates plot every 500th iteration for the rest of the process\n            if evals >=1000:\n                if evals%500 == 0:\n                    live_plot(range(evals+1), fs, ymax)\n        \n        # Appends esimtates to x_vectors \n        for i in range(1,37):\n            globals()[f'x_{i}'].append(x[i-1])\n\n        # Adds one to the number of iterations each iteration\n        evals += 1\n    \n    # Define datasets to be used using function defined earlier\n    df_X, df_Y = df_s(keep_top=keep_top, decade=None)\n    \n    # Intiial guess\n    x0 = np.zeros(len(variables)*2+1)\n    \n    # Start iteration number\n    evals = 0\n    \n    # Defines function to be minimized\n    obj_fun = lambda x: sqr_diff_sum_het(df_X,x)\n    \n    # Run optimizer\n    result = optimize.minimize(obj_fun,x0,\n                               method=\"Nelder-Mead\",\n                               options={\"disp\":True, \"maxiter\":1000000}, # display the results\n                               callback=collect\n                               ) \n    \n    # End timer\n    end = time.time()-start\n    \n    # Returns\n    return result, end\n```\n\nBy runing the code below you can see a live-updating graph that shows the value of the sum of the squared difference for each iteration. As you will see, the sqaured difference reaches close to its minimum very quickly so the last 10,000 iterations almost don't change the value of the squard difference. The live-graph slows the optimizer down, so choose option live_graph=False, if you are impacient and don't care about an awesome live-updating graph.\n\n\n```python\n## BE AWARE THAT IT TAKES A LOT OF TIME TO RUN THE CODE!!\n\n# Run optimizer function and print results and time\nresult, timer = optimizer()\nprint(f'{\" \":9s}Time: {timer:.4f} seconds')\n\n# Keep copy of df and df_Y for later purpose\ndf_Y_all = df_Y.copy()\ndf_all = df.copy()\n```\n\n\n```python\n# List of Parameter Estimates \nvariables_all = ['pi','Action1','Adventure1','Animation1','Biography1','Comedy1','Crime1','Documentary1',\n            'Drama1','Family1','Fantasy1','FilmNoir1','History1','Horror1','Music1','Musical1',\n            'Mystery1','Romance1','SciFi1','Short1','Sport1','Thriller1','War1','Western1',\n            'decade_1920_1','decade_1930_1','decade_1940_1','decade_1950_1','decade_1960_1',\n            'decade_1970_1','decade_1980_1','decade_1990_1','decade_2000_1','decade_2010_1',\n            'nrOfNominations1','nrOfWins1','duration1',            \n            'Action2','Adventure2','Animation2','Biography2','Comedy2','Crime2','Documentary2',\n            'Drama2','Family2','Fantasy2','FilmNoir2','History2','Horror2','Music2','Musical2',\n            'Mystery2','Romance2','SciFi2','Short2','Sport2','Thriller2','War2','Western2',\n            'decade_1920_2','decade_1930_2','decade_1940_2','decade_1950_2','decade_1960_2',\n            'decade_1970_2','decade_1980_2','decade_1990_2','decade_2000_2','decade_2010_2',\n            'nrOfNominations2','nrOfWins2','duration2']\n\n# Storing the results in a scalar (pi) and two vectors (omega1 and omega2)\npi = result.x[0]\nbeta1 = result.x[1:1+len(variables)]\nbeta2 = result.x[1+len(variables):]\n```\n\n\n```python\n# Plot the estimates for the two types\nfig = plt.figure(figsize=(16,6))\nax1 = fig.add_subplot(1,1,1)\n\n# Setting to make multiple (two) bars\nbarWidth = 0.5\nr1 = np.arange(len(beta1))\nr2 = [x + barWidth for x in r1]\n\n\n# Plots the estimated parameters for the chosen sample of movies\nax1.bar(r1, beta1, width=barWidth, label=f'Estimates for type 1', edgecolor='white')\nax1.bar(r2, beta2,  width=barWidth, label=f'Estimates for type 2', edgecolor='white')\n\n# Legends and labels \nax1.legend(loc=\"lower right\")\nax1.set_ylabel('Parameter estimates')\nax1.set_title(f'Figure 12: Parameter estimates for the two types of individuals, Pi={pi:.2f}')\nplt.xticks([r + barWidth for r in range(len(beta1))], variables)\n#ax1.set_ylim([-0.7,0.7])\nax1.axhline(y=0,color='black',linewidth=1)\nfor tick in ax1.get_xticklabels():\n    tick.set_rotation(90)\n\n\n```\n\nThe figure shows substantially differences in the pefrerences of the two types. As $\\pi=0.21$, 21 percent of the agents are type 1 and the remaining 79 percent are type 2. \n\n## Conclusion\n\nBased on the above results, it appears that duration increases ratings by quite a lot, while Nr. of nominations and Nr. of wins doesn't appear to play a role. Meanwhile, the effect of different genres and decades are quite different. \n\nWe hope you enjoyed our movie model project, and don't think we are completely idiots. Because as our model we conclude that *much to learn, we still have*. \n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "991c0d982660ddc65c7f9f8c5b9fe7c1613159a9", "size": 368178, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Til Jeppe.ipynb", "max_stars_repo_name": "NumEconCopenhagen/projects-2019-credible-threats", "max_stars_repo_head_hexsha": "17884efb72127475e453b933e10b6a079f5eae9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Til Jeppe.ipynb", "max_issues_repo_name": "NumEconCopenhagen/projects-2019-credible-threats", "max_issues_repo_head_hexsha": "17884efb72127475e453b933e10b6a079f5eae9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2019-04-12T05:41:19.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-14T21:46:01.000Z", "max_forks_repo_path": "Til Jeppe.ipynb", "max_forks_repo_name": "NumEconCopenhagen/projects-2019-credible-threats", "max_forks_repo_head_hexsha": "17884efb72127475e453b933e10b6a079f5eae9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-04-17T07:17:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-01T23:54:04.000Z", "avg_line_length": 187.5588385125, "max_line_length": 208560, "alphanum_fraction": 0.870866809, "converted": true, "num_tokens": 15867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1847675061589216, "lm_q2_score": 0.04208772671409797, "lm_q1q2_score": 0.007776444304862105}}
{"text": "# Homework 3\n### Due Date:  Tuesday, September 20th at 11:59 PM\n\n---\n## Problem 1:  `Git` and recovering from a mistake\nYou will do this problem in the Jupyter notebook so I can see your output.  Once again, you will work with your playground repository.\n\n**NOTE:** At the beginning of each cell, you MUST type `%%bash`.  If you don't do that then you will not be able to work with the necessary bash commands.\n\nFollow the following steps for this problem:\n\n1. First cell:\n  1. Type `cd /tmp` to enter the temporary directory\n  2. git clone url_to_your_playground_repo\n2. Second cell:\n  1. Go into your local `playground` directory (`cd /tmp/playground`)\n  2. Type `git pull origin mybranch1`\n  3. `ls`\n3. Third cell:\n  1. Go into your local `playground` directory (`cd /tmp/playground`)\n  2. Type `git status`\n4. Fourth cell:\n  1. Go into your local `playground` directory (`cd /tmp/playground`)\n  2. Type `git reset --hard origin/master`\n  3. `ls`\n5. Fifth cell:\n  1. Go into your local `playground` directory (`cd /tmp/playground`)\n  2. Type `git status`\n\nThe whole point of this problem was to show you how to get your local repo back to an earlier state.  In this exercise, you accidentally merged something to `master` that you didn't want.  Rather than starting to delete things all over the place, you can simply reset your `HEAD` to a previous commit.\n\n\n```bash\n%%bash\ncd /tmp\nrm -rf playground\ngit clone https://github.com/crystalzhaizhai/playground.git\n\n```\n\n    Cloning into 'playground'...\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit pull origin mybranch1\nls\n```\n\n    Merge made by the 'recursive' strategy.\n     book.md | 1 +\n     1 file changed, 1 insertion(+)\n     create mode 100644 book.md\n    book.md\n    feature.txt\n    intro.md\n    world.md\n\n\n    From https://github.com/crystalzhaizhai/playground\n     * branch            mybranch1  -> FETCH_HEAD\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit status\n```\n\n    On branch master\n    Your branch is ahead of 'origin/master' by 2 commits.\n      (use \"git push\" to publish your local commits)\n    \n    nothing to commit, working tree clean\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit reset --hard origin/master\nls\n```\n\n    HEAD is now at 5b6fdc2 Shared attribution between Joe and Sally\n    feature.txt\n    intro.md\n    world.md\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit status\n```\n\n    On branch master\n    Your branch is up-to-date with 'origin/master'.\n    \n    nothing to commit, working tree clean\n\n\n## Problem 2:  `Git` and checking out a single file\nSometimes you don't want to merge an entire branch from the upstream but just one file from it. There is a direct use case for such a situation. Suppose I've made an error in this homework (or a lecture) and want to correct it. I fix the mistake in the upstream repo. In the meantime you have edited some other files and you really don't want to manually ignore my older copies of those files. Rather, you want to fix just one file from this new branch. This is how you do it.\n\nAs usual, be sure to type in `%%bash` before you write any `bash` commands in a cell.\n\n**Note:** The steps below assume that you have already cloned the `playground` repo in this notebook.\n\n1. First cell:\n  1. Go into the `playground` repo and fetch the changes from the master branch of the `course` remote.\n2. Second cell:\n  1. `git checkout course/master -- README.md`.  The `--` means that `README.md` is a file (as opposed to a `branch`).\n  2. `cat README.md`.  This just looks at the updated file.\n3. Third cell:\n  1. `git status`\n  2. Commit the changes to your local repo with an appropriate commit message.\n  3. `git status`\n  4. Push the changes to your remote repo.\n\n\n```bash\n%%bash\ncd /tmp/playground\ncat .git/config\n```\n\n    [core]\n    \trepositoryformatversion = 0\n    \tfilemode = true\n    \tbare = false\n    \tlogallrefupdates = true\n    \tignorecase = true\n    \tprecomposeunicode = true\n    [remote \"origin\"]\n    \turl = https://github.com/crystalzhaizhai/playground.git\n    \tfetch = +refs/heads/*:refs/remotes/origin/*\n    [branch \"master\"]\n    \tremote = origin\n    \tmerge = refs/heads/master\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit remote add course https://github.com/IACS-CS-207/playground.git\ncat .git/config\n```\n\n    [core]\n    \trepositoryformatversion = 0\n    \tfilemode = true\n    \tbare = false\n    \tlogallrefupdates = true\n    \tignorecase = true\n    \tprecomposeunicode = true\n    [remote \"origin\"]\n    \turl = https://github.com/crystalzhaizhai/playground.git\n    \tfetch = +refs/heads/*:refs/remotes/origin/*\n    [branch \"master\"]\n    \tremote = origin\n    \tmerge = refs/heads/master\n    [remote \"course\"]\n    \turl = https://github.com/IACS-CS-207/playground.git\n    \tfetch = +refs/heads/*:refs/remotes/course/*\n\n\n    fatal: remote course already exists.\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit fetch course master\n```\n\n    From https://github.com/IACS-CS-207/playground\n     * branch            master     -> FETCH_HEAD\n     * [new branch]      master     -> course/master\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit checkout course/master -- README.md\ncat README.md\n```\n\n    # Playground Repo\n    \n    For practicing.\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit add .\ngit commit -m \"playgroundchange\" -a\ngit status\ngit push\n\n```\n\n    On branch master\n    Your branch is up-to-date with 'origin/master'.\n    \n    nothing to commit, working tree clean\n    On branch master\n    Your branch is up-to-date with 'origin/master'.\n    \n    nothing to commit, working tree clean\n\n\n    Everything up-to-date\n\n\n## Problem 3\nThis problem is related to the Lecture 4 exercises.\n1. Open the `languages.txt` file.  This file contains all the languages that students listed as their primary language in the course survey.\n2. Load the language strings from the file into a list.\n3. Use the `Counter` method from the `collections` library to count the number of occurrences of each element of the list.\n  + **NOTE:**  It is not necessary to use the `most_common()` method here.\n4. Create a bar plot to display the frequency of each language.  Be sure to label the x-axis!\n  + Remember, to create plots in the notebook you must put the line `%matplotlib inline` at the beginning of your notebook.\n  + Be sure to import matplotlib:  `import matplotlib.pyplot as plt`.\n  + To generate the bar plot write `plt.bar(x_coords, freqs)`.  You need to define `x_coords` and `freqs`.\n  + **Hint:** You may want to use the `numpy` `arange` function to create `x_coords`.  Remember, `x_coords` is the x-axis and it should have points for each distinct language.\n  + **Hint:** To get `freqs`, you may want to use the `values()` method on your result from step 3.  That is, `freqs = result_from_3.values()`.\n  + **Hint:** To label the x-axis you should use `plt.xticks(x_coords, labels)` where labels can be accessed through the `keys()` method on your result from step 3.\n\n\n```python\nwith open(\"../../lectures/L4/languages.txt\",\"r\") as f:\n    primary_course=f.read().split()\nfrom collections import Counter\ncourse_count=Counter(primary_course)\n```\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nx_coords=np.arange(len(course_count))\ntotal=np.sum(course_count.values())\nfreqs=course_count.values()\nplt.xticks(x_coords,course_count.keys())\nplt.bar(x_coords,freqs)\n\n```\n\n---\n## Problem 4\nIn chemical kinetics, the reaction rate coefficient for a given reaction depends on the temperature of the system.  The functional relationship between the reaction rate coefficient and temperature is given by the Arrhenius rate:\n\\begin{align}\nk\\left(T\\right) = A T^{b}\\exp\\left(-\\frac{E}{RT}\\right)\n\\end{align}\nwhere $A$, $b$, and $E$ are parameters, $R = 8.314 \\dfrac{\\textrm{J}}{\\textrm{mol} \\textrm{ K}}$  is the universal gas constant, and $T$ is the temperature.\n\nWrite a function which returns $k\\left(T\\right)$ given $A$, $b$, $E$, and $T$.  Here are a few requirements:\n* The function should test for exceptions where necessary.\n* Pass the parameters $A$, $b$, and $E$ in as a list.\n* Make $R$ a keyword argument to the function.\n\n\n```python\ndef kinetics(p,T, R=8.314):\n    import numpy as np\n    if len(p)<3:\n        print(\"Error! Less than 3 parameters\")\n        return()\n    try:\n        k=p[0]*(T**p[1])*np.exp(-p[2]/(R*T))\n        return k\n    except ZeroDivisionError:\n        print(\"Error! Divided by 0\")\n        return()\n\n```\n\n\n```python\nkinetics([1,2],0)\n```\n\n    Error! Less than 3 parameters\n\n\n\n\n\n    ()\n\n\n\n---\n## Problem 5\nUsing `numpy` arrays, plot $k\\left(T\\right)$ for $T\\in\\left(0, 5000\\right]$ for three different sets of parameters $\\left\\{A, b, E\\right\\}$.  Make sure all three lines are on the same figure and be sure to label each line.  You may use the function from Problem 2.  You may want to play with the parameters a little bit to get some nice curves but you won't lose points for ugly curves either (as long as they're correct!).\n\n\n```python\nTT=np.arange(1,5000)\nplt.plot(TT,kinetics([3,6,2],TT),'r')\nplt.plot(TT,kinetics([4,5,6],TT),'g')\nplt.plot(TT,kinetics([6,5,4],TT),'b')\nplt.legend([\"A,b,E=[3,6,2]\",\"A,b,E=[4,5,6]\",\"A,b,E=[6,5,4]\"])\nplt.xlabel(\"T\")\nplt.ylabel(\"k\")\nplt.title(\"kinetics\")\n\n```\n\n\n```bash\n%%bash\ngit add \"HW3_final.ipynb\"\n\ngit commit -m \"HW3\" -a\ngit status\ngit remote\ngit push origin master\n\n\n```\n\n    [master b7fbb64] HW3\n     1 file changed, 7 insertions(+), 7 deletions(-)\n    On branch master\n    Your branch is ahead of 'origin/master' by 1 commit.\n      (use \"git push\" to publish your local commits)\n    \n    nothing to commit, working tree clean\n    course\n    origin\n    upstream\n\n\n    To https://github.com/crystalzhaizhai/cs207_yi_zhai.git\n       cffa62f..b7fbb64  master -> master\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "e586ba2d774e4ae5f4d439594767f39af6864ead", "size": 55023, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "homeworks/HW3/HW3_final.ipynb", "max_stars_repo_name": "crystalzhaizhai/cs207_yi_zhai", "max_stars_repo_head_hexsha": "faabdc5dd1171af04eed6639225adddc26402bf1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/HW3/HW3_final.ipynb", "max_issues_repo_name": "crystalzhaizhai/cs207_yi_zhai", "max_issues_repo_head_hexsha": "faabdc5dd1171af04eed6639225adddc26402bf1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/HW3/HW3_final.ipynb", "max_forks_repo_name": "crystalzhaizhai/cs207_yi_zhai", "max_forks_repo_head_hexsha": "faabdc5dd1171af04eed6639225adddc26402bf1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 92.1658291457, "max_line_length": 32614, "alphanum_fraction": 0.8320338767, "converted": true, "num_tokens": 2665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09268778114565464, "lm_q2_score": 0.08389038698317784, "lm_q1q2_score": 0.007775613828921063}}
{"text": "\ufeff# Awesome-python-md-documentation\n\nThis is python user documentation created in markdown so it can be visualized in IDE. How it can look is on this printscreen.\n\n\n\nFeel free to colab...\n\nIt's also in jupyter notebook ipynb version. Markdown is good for finding correct syntax, notebook is good, when you want to learn something and play with code. It's derived from original `README.md` so do not edit jupyter itself.\n\nNote 1: Some cells are commented, because can slow notebook, make errors or save files.\n\nNote 2: Some code is in python language, but many lines are for terminal (like cwd for example). If this is the case, you can run it also in terminal, just add `! ` before every command.\n\nNote 3: Jupyter need some libraries for particular tasks. Install it when reach the error, or if you don't want to install them manually, use chapter 1 Requirements - bulk libraries install, and install all of them from [My requirements](https://github.com/Malachov/mypythontools/tree/master/content/requirements)\n\nNote 4: Table of Content is not working in jupyter, so delete it. Use nbextensions and extension table of content. If you have no nbextensions, than use:\n\n\n```python\n# !  pip install jupyter_contrib_nbextensions && jupyter contrib nbextension install\n\n# I recommend Table Of contents, Variable inspector, ExecuteTime, Code Prettify and Autopep8. Just restart jupyter and choose from tab nbextensions.\n```\n\n# Table of Content\n\n<!-- @import \"[TOC]\" {cmd=\"toc\" depthFrom=1 depthTo=6 orderedList=false} -->\n\n<!-- code_chunk_output -->\n\n- [Awesome-python-md-documentation](#awesome-python-md-documentation)\n- [Table of Content](#table-of-content)\n- [General](#general)\n- [Cookiecutter - Project scaffolding](#cookiecutter---project-scaffolding)\n- [Libraries](#libraries)\n  - [Virtual environment (venv)](#virtual-environment-venv)\n  - [Requirements](#requirements)\n- [Building app - Pyinstaller](#building-app---pyinstaller)\n- [Style guide (linting, formatting)](#style-guide-linting-formatting)\n  - [Multi line code](#multi-line-code)\n- [Comments](#comments)\n- [Documentation - docstrings](#documentation---docstrings)\n- [Logical conditions (and, or, not...)](#logical-conditions-and-or-not)\n  - [None](#none)\n- [Variables](#variables)\n- [Data types](#data-types)\n  - [String](#string)\n  - [List](#list)\n  - [Tuple](#tuple)\n  - [Dictionary](#dictionary)\n  - [Deque](#deque)\n  - [Set](#set)\n  - [Dataframe](#dataframe)\n  - [Numpy Array](#numpy-array)\n  - [HDF5](#hdf5)\n  - [Decimal](#decimal)\n- [Type hinting](#type-hinting)\n- [Iterators](#iterators)\n- [Conditions (if, else...)](#conditions-if-else)\n- [Loops](#loops)\n  - [For](#for)\n  - [WHILE](#while)\n- [Functions](#functions)\n    - [map(), filter(), reduce()\\*\\*](#map-filter-reduce)\n- [Generators](#generators)\n- [Decorators](#decorators)\n- [Modules](#modules)\n- [Classes](#classes)\n  - [Magic methods (dunder methods)](#magic-methods-dunder-methods)\n- [Bitwise operations](#bitwise-operations)\n- [File I/O](#file-io)\n  - [Open file](#open-file)\n  - [Manipulate with files (move, copy)](#manipulate-with-files-move-copy)\n- [Try -- Except](#try----except)\n- [Built in functions](#built-in-functions)\n- [Built in variables](#built-in-variables)\n- [Built in modules](#built-in-modules)\n  - [Sys](#sys)\n  - [io](#io)\n  - [os](#os)\n  - [Pathlib - Work with paths](#pathlib---work-with-paths)\n  - [Warnings](#warnings)\n  - [re - Regular expressions](#re---regular-expressions)\n  - [Subprocess - Run shell comands](#subprocess---run-shell-comands)\n  - [Pickle](#pickle)\n  - [Time and datetime](#time-and-datetime)\n- [Imported libraries](#imported-libraries)\n  - [Tests - pytest](#tests---pytest)\n  - [Command Line Arguments - argparse](#command-line-arguments---argparse)\n  - [Plots, graphs](#plots-graphs)\n    - [Plotly](#plotly)\n    - [Matplotlib](#matplotlib)\n  - [Tables](#tables)\n  - [Web](#web)\n    - [Requests - API - GET, POST](#requests---api---get-post)\n    - [Beautiful soup - web scrapping](#beautiful-soup---web-scrapping)\n  - [Images, pictures](#images-pictures)\n  - [Mathematics, statistics, linear algebra](#mathematics-statistics-linear-algebra)\n  - [Signal processing and controll](#signal-processing-and-controll)\n  - [Database](#database)\n    - [pyodbc, sqlalchemy](#pyodbc-sqlalchemy)\n  - [GUI](#gui)\n  - [Misc](#misc)\n    - [Jupyter](#jupyter)\n- [Performance](#performance)\n  - [Profiling](#profiling)\n    - [Line profiling](#line-profiling)\n  - [Garbage collector](#garbage-collector)\n  - [Threading](#threading)\n  - [Max execution time function](#max-execution-time-function)\n  - [Numba](#numba)\n  - [Dask](#dask)\n- [Miscellaneous](#miscellaneous)\n  - [Push own library to PyPi](#push-own-library-to-pypi)\n  - [CI/CD](#cicd)\n  - [Create documentation - Sphinx](#create-documentation---sphinx)\n  - [Snippets - examples](#snippets---examples)\n    - [Measure time](#measure-time)\n    - [Show bytecode](#show-bytecode)\n    - [Encoding JSON with Python](#encoding-json-with-python)\n\n<!-- /code_chunk_output -->\n\n# General\n\n**Show where python is installed**\n\n\n```python\n# On windows\nwhere python\n\n# On linux\nwhich python\n```\n\n**Python on linux**\n\n**Use python instead of python3**\n\nAdd to source ~/.bashrc\n\n\n```python\nalias python=python3\nalias pip=pip3\n```\n\n**Open terminal in current folder**\n\n\n```python\nsudo apt-get install nautilus-open-terminal\n```\n\n**Set default python on linux**\n\n\n```python\nsudo apt-get install update-alternatives\nsudo update-alternatives --install /usr/bin/python python /usr/bin/python3.8 1\nsudo update-alternatives --install /usr/bin/python python /usr/bin/python3.6 2\nsudo update-alternatives --config python\n```\n\n# Cookiecutter - Project scaffolding\n\nYou can find typical python project structure here\n\n[Starter project](https://github.com/Malachov/mypythontools/tree/master/content/project-starter)\n\nIt contains testing files, files for sphinx auto documentation, licence and more.\n\n# Libraries\n\n**Install library**\n\n\n```python\npip install library_name\n\n# For anaconda\nconda install library_name\n\n# If conda not work\nconda install -c anaconda library_name\n```\n\n**Show installed libraries**\n\n\n```python\npip list\n```\n\n**Show outdated libraries**\n\n\n```python\npip list --outdated\n```\n\n**If pip cannot be installed by SSL errorr**\n\n\n```python\npip install ipykernel --upgrade pip --trusted-host pypi.org\n```\n\n## Virtual environment (venv)\n\n\n```python\n\npip install virtualenv\n\n# Create new virtual environment\nvirtualenv venv\n\n# Activate virtual env\nvevn\\Scripts\\activate.bat\n```\n\n## Requirements\n\nFile that describe all used libraries for some project. You can install all the libraries at once.\n\n\n```python\npip install -r /path/to/requirements.txt\n\n# Create requirements\npipreqs --encoding=utf8 C:\\VSCODE\\Diplomka\n\n# Deprecated\n(pip freeze > requirements.txt)\n```\n\nYou can find much more about libraries in `Modules` section.\n\n# Building app - Pyinstaller\n\nYou can create binaries with pyinstaller, so other user can run an app even with no python installed.\n\nYou don't even need to install pyinstaller and you can use mypythontools build module (you can use VS Code Task to build an app with single click)\n\n[Documentation](https://mypythontools.readthedocs.io/mypythontools.build.html) for how to do it.\n\nBuild bootloader locally to avoid false positive antivirus alert (in tutorial).\n\n# Style guide (linting, formatting)\n\n**pylint** - show you where problems are\n\n**Black** - Strict auto formatting. Setup longer default line length for better user experience\n\nExample for how to use it in VS Code - Add to settings.json:\n\n\n```python\n\"editor.formatOnSave\": true,\n\"python.formatting.blackArgs\": [\"--line-length\", \"110\"],\n```\n\nIf you are not sure how to format code, you can try [pep 8](https://www.python.org/dev/peps/pep-0008/) or [google style guide](https://google.github.io/styleguide/pyguide.html)\n\n## Multi line code\n\n\n```python\npoi = { \"1\": 3,\n        \"2\": 4,\n        \"6\": 8 }\n\na = (   1 + 2\n        + 3 + 4 )\n\nf = range(  1 + 2\n        + 3 - 4)  # Function example\n\n# or use \\\na = 1 + 2 \\\n    + 3\n```\n\n# Comments\n\n\n```python\n# One line comment\n\n## Multiline comment\n\"\"\" V\u00edce\u0159\u00e1dkov\u00e9 koment\u00e1\u0159e pou\u017e\u00edvaj\u00ed t\u0159i uvozovky nebo apostrofy\na jsou \u010dasto vyu\u017e\u00edv\u00e1ny jako dokumenta\u010dn\u00ed koment\u00e1\u0159e k metod\u00e1m\n\"\"\"\n```\n\n# Documentation - docstrings\n\nPosible modes - DocBlockR, ReST, Numpy, Google\n\n**Google**\n[Sphinx example](https://www.sphinx-doc.org/en/master/usage/extensions/example_google.html)\n\n[Google example]\n\n**Numpy**\n[Sphinx example](https://www.sphinx-doc.org/en/master/usage/extensions/example_numpy.html)\n\n**reStructured text**\n\n\n```python\nrestr = ''' # remove the variable - it's just for jupyter\nSection Header\n==============\n\nSubsection Header\n-----------------\n\n- A bullet list item\n\n- A sub item\n\n1) An enumerated list item\n\n.. image:: /path/to/image.jpg\n\nA sentence with links to `Wikipedia`_\n\n.. _Wikipedia: https://www.wikipedia.org/\n\n+------------------------+------------+----------+\n| Header row, column 1   | Header 2   | Header 3 |\n+========================+============+==========+\n| body row 1, column 1   | column 2   | column 3 |\n+------------------------+------------+----------+\n| body row 2             | Cells may span        |\n+------------------------+-----------------------+\n\nLiteral - no linebreaks etc.\n\n::\n\nsome literal text.\n\n\nPython code in docstrings\n\n.. code:: python\n\nprint(\"A literal block directive explicitly marked as python code\")\n'''\n```\n\n**docBlockR**\n\n\n```python\n\"\"\"Function to find optimal parameters of function\n======\nOutput:\n------\n    Optimized parameters {dict}\n\nArguments:\n------\n    model {func} -- Function to be optimized (eg: ridgeregression)\n    kwargs {dict} -- Initial arguments (eg: {\"alpha\": 0.1, \"n_steps_in\": 10})\n    kwargs_limits {dict} -- Bounds of arguments (eg: {\"alpha\": [0.1, 1], \"n_steps_in\":[2, 30]})\n    data {list, array, dataframe col} -- Data on which function is optimized (eg: data1)\n    fragments {int} -- Number of optimized intervals (default: 10)\n    predicts {int} -- Number of predicted values (default: 7)\n\"\"\"\n```\n\n# Logical conditions (and, or, not...)\n\n**Not**\n\n\n```python\nnot True # => False\n'a' is not 1\n'a' != 1\n```\n\n**Greater than, lower than**\n\n\n```python\n>=\n```\n\n**And, or**\n\n\n```python\n0 and 2 # => 0\n-5 or 0 # => -5\n0 == False # => True\nif 2 > 1 and 5 > 6:\n    pass\n\n# Logical conditions can be combined\n\n1 < 2 < 3 # => True\n```\n\n## None\n\n\n```python\n# None is object (NULL, nil, ...)\n\nNone  # => None\n\n# So don't use \"==\" for comparison. Rather use \"is\"\n\nNone is None # => True\n\n# None, 0, and empty string/list/dictionary is False, everything else True\n\nbool(0) # => False\nbool(\"\") # => False\nbool([]) # => False\nbool({}) # => False\n```\n\n# Variables\n\n\n```python\ny = int(2.8)\n\nx = 1\nx += 1 # Zkr\u00e1cen\u00fd z\u00e1pis x = x + 1. Pozor, \u017e\u00e1dn\u00e9 x++ neexisuje\n\n# Int divided by int\n\n3 / 2  # = 1.5\n3 // 2  # = 1\n```\n\n**Declaration of more variables at once**\n\n\n```python\na = b = c = 1  # If i change one, it doesn't affect the others\n\na,b,c = 1,2,\"john\"\n```\n\n**Swap variables values**\n\n\n```python\ne = 2; d = 4\ne, d = d, e # d is now 5, e is now 4\n```\n\n**Bulk create variables**\n\n\n```python\nname = ['mike', 'john', 'steve']\nage = [20, 32, 19]\n\nfor x,y in zip(name, age):\n    globals()[x] = y  # mike = 20 ...\n\nuname = ['u{}'.format(n) for n in range(7)] # [u1, u2, u3...]\n```\n\n**Check if variable exist**\n\n\n```python\nif 'myVar' in locals():\n    pass\n```\n\n**Import variables from other modules**\n\nCreat config.py\n\nThere for example\n\n\n```python\nx = 1\n```\n\nIn main then use\n\nconfig.x = 2 ....\n\n**Find name of variable, list or dictionary**\n\n\n```python\nvar = 3\nmy_var_name = [k for k,v in globals().items() if v == var][0]\n```\n\n# Data types\n\n\n```python\na = type(var)  # Return type\n```\n\n**Type of variable as condition**\n\n\n```python\nif isinstance(var, str):  # Check if it's string (or int etc...)\n    pass\n\n# More types at once\n\nimport numpy as np\ny = np.array([1])\nisinstance(y, (np.ndarray, np.generic))  # pd.DataFrame For dataframe\n\nif a is list: # Zjist\u00ed, zda jde p\u0159\u00edmo o string\n    pass\n\n# Also work if object is includes in class\n```\n\n## String\n\n\n```python\n\na = \"This is string.\"\na = 'This is also string.'\n\n# In python 3\n\nprint('strings are now utf-8 \\u03BCnico\\u0394\u00e9!')  # strings are now utf-8 \u03bcnico\u0394\u00e9!\n\n# Strings can use + but don't use\n\na = \"Hello \" + \"world!\" # => \"Hello world!\"\n\n# Can be concatenated without '+'\n\na = \"Hello \" \"world!\" # => \"Hello world!\"\n\n# String is list of symbols\n\na = \"This is list\"[0] # => 'T'\n```\n\n**Format - depracated**\n\n\n```python\n# Old\n\na = '%s  %s' % ('one', 'two')\n\n# Newer\n\na = '{} {}'.format('one', 'two')\n\n# Format can be used multiple times\n\na = \"{0} {1} st\u0159\u00edka\u010dek st\u0159\u00edkalo p\u0159es {0} {1} st\u0159ech\".format(\"t\u0159i sta t\u0159icet t\u0159i\", \"st\u0159\u00edbrn\u00fdch\")\n\n# You can use named arguments\n\na = \"{jmeno} si dal {jidlo}\".format(jmeno=\"Franta\", jidlo=\"gul\u00e1\u0161\") # => \"Franta si dal gul\u00e1\u0161\"\n```\n\n**f-strings - Correct way to format**\n\n\n```python\nname = 'Peter'\nf\"Hello, {name}. You are {2 * 17}. Also functions {name.lower()}.\"\n\n# You can use raw strings (no escape characters, but still format)\n\na = 15\nprint(fr'Escape is here:\\n but still {a}')  # Escape is here:\\n but still 15\n\n# Keep quotes in f-strings\nprint(f'He said his name is {name!r}.')  # \"He said his name is 'Fred'.\"\n\n# If you use \"\"\" no escape symbols will be used\"\"\"\n# Also can use dictionaries, but \"\" is necesarry\n# Dont use # in f strings\n\n```\n\n**Eval - String to code**\n\n\n```python\nmycode = 'x = 1'\nexec(mycode)\n\n# or\nx = eval(\"2+2\") # number ze stringu\n```\n\n**Join - concatenate**\n\n\n```python\nwords = [\"this\", 'is', 'a', 'list', 'of', \"strings\"]\n' '.join(words)  #returns \"This is a list of strings\"\n```\n\n## List\n\n\n```python\n\nempty_list = []\nlst = [1, 2, 3, 4]\nlst.append(1)  # lst is now [1, 2, 3, 4, 1]\nlst.insert(1, 2)  # insert 2 on index 1\nlst.pop()  # Remove last value\nlst.remove(2)  # Remove first 2 in list\ndel lst[1]  # Delete first element\ndel lst[-2:]  # Range delete - from the last one\nb = [1,2]\nc = lst + b  # Serializes\nlst.extend(b)  # Serializes\n```\n\n**List comprehensions**\n\nWay to create a list\n\n\n```python\nu_list = ['u{}'.format(n) for n in range(1, 6)]\n```\n\n\n```python\n# Print list\nprint(*a, sep = \", \")\n\n# If lst a = lst b and we change one of them, the other also change therefor\n\nlista = [1, 2, 3]\nlistb = lista.copy()\nlistb[2] = 5\nprint(lista)  # [1, 2, 5]\n\n### Access members\n\nlst = [1, 2, 3, 4]\nlst[0]  # => 1\nlst[-1]  # => 3\n\n### Slices\n\nlst[1:3]  # => [2, 4]\nlst[2:]  # => [4, 3]\nlst[:3] # => [1, 2, 4]\n\n# Every second member\n\nlst[::2] # =>[1, 4]\n\n### Minimum\n\nyoungest = min(lst)\n\n### Find maximum and it's index\n\nm = max(lst)\n[i for i, j in enumerate(a) if j == m] # pro a = [1,2,0]  # 1\n\n### Sum\n\nsuma = sum(lst)\n\n### If member exist\n\n1 in lst # => True\n\n### Length of list\n\nlen(lst) # => 6\n\n### Every value just once\n\nt =  [1,  2,  3,  1,  2,  5,  6,  7,  8]\nlst = list(set(t))  # [1,  2,  3,  5,  6,  7,  8]\n\n### Reverse\n\nrev = lst[::-1] # => [3, 4, 2, 1]\n\n# Or\n\nrev = t.reverse()\n\n### Iterate in reverse order\n\nfor i in reversed(lst):\n    pass\n\n### Check if list is empty or not\n\na = 6\nif a:\n    pass\n\nif not a:\n    pass\n\n### Create list from 0 to 10\n\nl = range(10) #  [0,  1,  2,  3,  4,  5,  6,  7,  8,  9]\n\n### Create list - List comprehension\n\n[x*5 for x in range(5)] #[0, 5, 10, 15, 20]\n[x for x in range(5) if x%2 == 0] #[0, 2, 4]\n[a if a else  2  for a in  [0,1,0,3]]\n\n# List comprehension from more entities\n\nlist_1 = [1, 2, 3]\nlist_2 = [2, 3, 4]\n[(i, j) for i, j in zip(list_1, list_2)] # [(1, 'a'), (2, 'b'...]\n\n### Zip lists\n\nzip(list_1, list_2) # {(a1, b1), (a2, b2)}\n\n### Logical condition on lists\n\nj2 = [i for i in list_1 if i >=  5]\n\n### One value more times\n\nlistOfStr = ['Hi'] * 3 # ['Hi', 'Hi', 'Hi']\n\n### Multiple list\n\nmy_list =  [1,  2,  3,  4,  5]\nmy_new_list =  [i *  5  for i in my_list]\n\n### Find index\n\nmy_list.index(3)\n\n### Nested lists\n\nt = [[1,2], [3,4]]\nprint(t[1][1])  # 4\n\n### Every first member of nested lists\n\nL = [[[0,1,2],[3,4,5],[6,7,8]],  [[0,1,2],[3,4,5],[6,7,8]],  [[0,1,2],[3,4,5],[6,7,8]]]\nR = [[x[0]  for x in sl ]  for sl in L ]  # [[0, 3, 6], [0, 3, 6], [0, 3, 6]]\n\n# Or\n\nlst = [[1,2,3],[11,12,13],[21,22,23]]\na = list(zip(*lst))[0]  # [1, 11, 21]\n\n### Add first with first, second with second\n\n[a + b for a, b in zip(list_1, list_2)]\n\n### List of functions\n\ndef func1():return 1\ndef func2():return 2\ndef func3():return 3\nfl = [func1,func2,func3]\n[f() for f in fl] # [1, 2, 3]\n\n### How many times members in list\n\nimport collections\nprint( collections.Counter(['a', 'b', 'c', 'a', 'b', 'b']))\n```\n\n## Tuple\n\nTuple is like list but imutable !!! [] i can change - () i cannot change !!!\n\n\n```python\ntuple = (1, 2, 3)\ntuple[0]  # => 1\n# tuple[0] = 3  # Raise TypeError\n\na, = 5  # (5)\n```\n\n## Dictionary\n\n\n```python\nempty_dic = {}\ndic = {\"jedna\": 1, \"dva\": 2, \"t\u0159i\": 3}\n```\n\n**Dict comprehension**\n\n\n```python\ndic_variable = {key:value for (key,value) in dic.items()}\n```\n\n\n```python\n### Add value\n\ndic['\u010dty\u0159i'] = 4  # If key is already there it's updated\n\n### Add more values at once\n\ndic.update({\"\u010dty\u0159i\": 4, \"p\u011bt\": 5})\n\n\n### Create dictionary from two lists\n\nname = ['mike', 'john', 'steve']\nage = [20, 32, 19]\ndic=dict(zip(name, age))\n\n### Assign multiple keys to one value\n\nmy_dict = dict.fromkeys(['a', 'b', 'c'], 10)\n\n### Miscelanious\n\nthisdict = {'b':1, 'c':2, 'd':3}\ndel thisdict['b']  # delete list\n'e' in thisdict  # returns False\nthisdict.items()  # returns [('a', 1), ('c', 'eggs')]\n\n# All keys\n\ndic.keys()\n\n# You need list sometimes not iterables\n\nlist(dic.keys())\n\n### Last key in dictionary\n\nmax(dic)\n\n### For cycle for all keys\n\nfor s in dic:\n    print(s)\n\n### Maximum value and its index\n\nstats = {'a':1000, 'b':3000, 'c': 100}\nmaxname = max(stats, key=stats.get)\nmaxvalue = stats[maxname]\n\n### Values\n\nlist(dic.values()) # => [3, 2, 1]\n\"jedna\" in dic # => True if value is in dictionary\ndic.get(\"\u010dty\u0159i\") # => None - don't raise error if key not in dic\ndic.setdefault(\"p\u011bt\", 5) # dic[\"p\u011bt\"] default 5\n\n### Find key from value\n\nlist(stats.keys())[list(stats.values()).index(100)]\n\n### For cycle for dictionaries\n\nfor k in stats: # Iteruje p\u0159es v\u0161echny kl\u00ed\u010de\n    print(k)\n\nfor k, v in stats.items(): # Iteruje \u0159es v\u0161echny kl\u00ed\u010de a hodnoty\n    print(k,v)\n\n### Join two dictionaries\n\nc = {**dic, **stats}\n\n### Enumerate in dictionaries\n\nfor i, (j, k) in enumerate(dic.items()):\n    pass\n\n### Dictionary as arguments into function\n\ndef rep(*nonamed, **named):\n    return nonamed, named\n\nt = (47,11)\nd = {'x':'extract','y':'yes'}\nrep(*t, **d) # It's the same as f(47, 11, x=extract, y=yes)\n\n### Nested dictionaries - for examples name of functions and it's parameters\n\ndef rep2(*inp, **inp2):\n    return rep\n\nmodels = {\"AR (Autoregression)\": rep, \"Linear neural unit\": rep2}\nmodelsparameters = {\"AR (Autoregression)\": {\"predicts\":  2}, \"Linear neural unit\": {\"predicts\": 4}}\nmodelscomplet = zip(models.keys(), models.values(),  modelsparameters.values())\nmodelsresults = []\n\nfor i, j, k in modelscomplet:\n    modelsresults.append({i: j(1, **k)})\n\n### Nested dictionaries - Find minimum\n\ntop = 1000000\nfor key, value in modelsparameters.items():\n    for inkey, invalue in value.items():\n        if invalue < top:\n            best_model_name = key\n            best_data = inkey\n            top = invalue\n\n### Dictionary comprehension\n\n{x: x**2 for x in range(1, 5)} # => {1: 1, 2: 4, 3: 9, 4: 16}\n{pismeno for pismeno in \"abeceda\"} # => {\"d\", \"a\", \"c\", \"e\", \"b\"}\n```\n\n**Two dictionaries intersection**\n\n\n```python\nd1 = {'a': 1, 'b': 2}\nd2 = {'b': 2, 'c': 3}\n\nd1.viewkeys() & d2.viewkeys()  # {'b'}\n\n# Or with set\na = { 'x' : 1, 'y' : 2, 'z' : 3 }\nb = { 'u' : 1, 'v' : 2, 'w' : 3, 'x'  : 1, 'y': 2 }\nset( a.keys() ) & set( b.keys() )  # Output set(['y', 'x'])\nset( a.items() ) & set( b.items())  # Output set([('y', 2), ('x', 1)])\n```\n\n## Deque\n\n\n```python\nYou can iterate from both sides\n\nimport collections\nde = collections.deque([1, 2, 3])\nde.append(0)  # Add x to the right side of the deque.\nde.appendleft(6)  # Add x to the left side of the deque.\nde.count(2)  # Count the number of deque elements equal to x.\nlst = [1, 2, 3]\nde.extend(lst)  # Extend the right side of the deque by appending elem   ents from the iterable argument.\nde.pop()  # Remove and return an element from the right side of the deque. If no elements are present, raises an IndexError.\nde.popleft()  # Remove and return an element from the left side of the deque. If no elements are present, raises an IndexError.\nde.remove(2)  # Remove the first occurrence of value. If not found, raises a ValueError.\nde.reverse()  # Reverse the elements of the deque in-place and then return None.\nde.rotate(1)  # Rotate the deque n steps to the right. If n is negative, rotate to the left.\nde.clear()  # Remove all elements from the deque leaving it with length 0.\n```\n\n## Set\n\nIt is not oredered and every value is just once!\n\n\n```python\nempty_set = set()\nsett = {1, 1, 2, 2, 3, 4}  # {1, 2, 3, 4}\nsett.add(5)  # {1, 2, 3, 4, 5}\njina_set = {3, 4, 5, 6}\n\n# Intersect of 2 sets\n\nsett & jina_set # => {3, 4, 5}\n\n# Union\n\nsett | jina_set # => {1, 2, 3, 4, 5, 6}\n\n# Exception\n\n{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}\n\n# If member exist\n\n2 in sett # => True\n9 in sett # => False\n```\n\n## Dataframe\n\nPanda library is necessary\nIf there is a parameter inplace=True, then changes are made on original, otherwise change is only made for new variable assign\n\n\n```python\n### Import from csv\n\nimpt = '''\nimport pandas as pd\ndata = pd.read_csv(\n    \"data/files/complex_data_example.tsv\",\n    sep='\\t',  # Tab-separated value file.\n    quotechar=\"'\",  # single quote allowed as quote character\n    dtype={\"salary\": int},  # Parse the salary column as an integer\n    usecols=['name', 'birth_date'].  # Only columns\n    parse_dates=['birth_date'],  # Intepret the birth_date column as a date\n    skiprows=10,  # Skip the first 10 rows of the file\n    na_values=['.', '??']  # Take any '.' or '??' values as NA\n)\n'''\n\n### Save into CSV\n\n# df.to_csv('newcsv.csv') # bez n\u00e1zv\u016f , header=False\n\n### Create\n\nimport pandas as pd\n# one column dataframe\n\ns2 = pd.Series([1,2,3,4])\n\n# dataframe\n\ns2 = pd.DataFrame([1,2,3,4])\n\n# from list\n\ndata = [['tom', 10, 1], ['nick', 15, 2], ['juli', 14, 3]]\ndf = pd.DataFrame(data, columns = ['name', 'age', 'index'])\n\n# from dictionary\n\ndict = {'a': 1, 'b': 2}\nnewdatf = pd.DataFrame.from_dict(dict, orient='index')\n\n# from array\n\narray = np.array([[1, 2], [2, 3], [3, 4]])\n#df2 = pd.DataFrame(data=array[1:,1:], index=range(len(data)), columns=data[0,1:])\n\n### Access column\n\ndf['name']\n\n### Subset of columns - Access members\n\n# With name\n\ndf1 = df[['name','age']]\n\n# with index\n\ndf2 = df.iloc[:,0:1]  #   # All rows, first and second column\n\ndf3 = df.iloc[0]  # First row\n\n### Column to new dataframe\n\na = df.pop('index')\n\n### Return name of column from index\n\na = df.columns[0]  # Columns return name of column\n\n### Find index from column name\n\na = df.columns.get_loc(\"age\")\n\n### Logical conditions\n\ndf_new = df.loc[df['name'] == 'juli']\n\n### Concat 2 columns\n\ndf['name_and_age'] = df['name'] + str(df['age'])\n\n### Make index from colmn\n\ndf.set_index('name', inplace=True)\ndf.reset_index(level=None, drop=False, inplace=False)\n\n### Convert into array\n\ndf['age'].values\nb=df1.iloc[:,1:].values  # every column separately\n\n### Convert into list\n\nlst = df['age'].values.tolist()\n\n### Miscelaneous\n\ndf.index  # RangeIndex(start=0, stop=x....)\ndf.dtypes  # age  int ...\n\n### Lenght of dataframe\n\nlength = len(df.index)\n\n### Date and time and datetime, range\n\n# Datetime from values\n\nyear = 2020; month = 3; day = 14; hour = 4\nstart = pd.Timestamp(year=year, month=month, day=day, hour=hour)\n\n# Range\n\ndf['EventStart'] = pd.date_range(start=start, periods=length, freq='H')\n\n# Convert from datetime to time, the same to datetime\n\ndf['EventStart_time'] = df['EventStart'].dt.time\n\n### Set index\n\ndf.set_index('EventStart', drop=True, inplace=True)\ndf.index = pd.to_datetime(df.index)\n\n### Sort index\ndata_for_predictions_full.sort_index(inplace=True)\n\n### Resample datetime dataframe\n\ndf_res = df.resample('M').sum() # M\u00e9n\u011b \u0159\u00e1dk\u016f na v\u00fdstupu\n\n### Copy of dataframe\n\n# !!! If you use variables., change in one is also changed in the others, so if you want independent dataframes, use copy() !!!\n\ndf2 = df.copy()\n\n### Add column on index 0\ndf.insert(0, 'New column', df.loc[:, 1])  # (loc, column, value)\n\n### Pop, extract column to variable and drop it from original\ndf.pop(df.columns[0])\n\n### Move column on index 1\ndf.insert(0,'predicted_column_name', df.pop(predicted_column_name.columns[1]))\n\n### Join 2 dataframes\n\n#### Concat\n# possible parameters - axis, join, ignore_index, sort, keys, levels\n\ndf = pd.DataFrame([['a', 1], ['b', 2], ['c', 3]], columns=['letter', 'number'])\n    #         letter  number\n    #    0      a       1\n    #    1      b       2\n    #    2      c       3\n\ndf2 = pd.DataFrame([['c', 1], ['d', 2], ['e', 3]], columns=['letter', 'number2'])\n\n    #        letter  number\n    #    0      c       1\n    #    1      d       2\n    #    2      e       3\n\n# Add rows\n\ndf_rows = pd.concat([df, df2])\n\n    #        letter  number  number2\n    #    0      a     1.0      NaN\n    #    1      b     2.0      NaN\n    #    2      c     3.0      NaN\n    #    0      c     NaN      1.0\n    #    1      d     NaN      2.0\n    #    2      e     NaN      3.0\n\n    # join='inner' means only columns that are in both dfs\n\n# Add columns\n\ndf_columns = pd.concat([df, df2], axis=1)\n\n    #        letter  number letter  number\n    #    0      a       1      c       1\n    #    1      b       2      d       2\n    #    2      c       3      e       3\n\n# or you can use\n\ndf4 = df.append(df2)\n    #         letter  number  number2\n    #    0      a     1.0      NaN\n    #    1      b     2.0      NaN\n    #    2      c     3.0      NaN\n    #    0      c     NaN      1.0\n    #    1      d     NaN      2.0\n    #    2      e     NaN      3.0\n\n### Merge\n# Add database parameters like left join, outer join\n\nresult = pd.merge(df, df2, on='letter', how='left')\n\n    #        letter  number  number2\n    #    0      a       1      NaN\n    #    1      b       2      NaN\n    #    2      c       3      1.0\n\n### Group by\n\ngpd = df4.groupby('letter').agg({'number': np.mean, 'number2': np.size})\n\n    #        number  number2\n    #  letter\n    #    a\t   1.0\t   1.0\n    #    b\t   2.0\t   1.0\n    #    c\t   3.0\t   2.0   # c only once, not twice\n    #    d\t   NaN\t   1.0\n    #    e\t   NaN\t   1.0\n\n#### Get all from one group\n\ngpd = df4.groupby('letter')\nc = gpd.get_group('c')\n\n    #        letter  number  number2\n    #    2      c     3.0      NaN\n    #    0      c     NaN      1.0\n\n### Mean, standard deviation\n\nmean = df['number'].mean()\nstd = df['number'].std()\n\n### Rolling (moving) average and standard deviation\n\nrolling_mean = df['number'].rolling(10).mean()\nrolling_std = df['number'].rolling(10).std()\n\n# Change axis\na = np.zeros((3, 4, 5))\na = np.moveaxis(a, 0, -1).shape\n(4, 5, 3)\n\n### Remove outliers\n\ndf_removed_outliers = df[ (df['number'] < 2 * std) ]\n\n### Remove not a number columns\ngpd = gpd.select_dtypes(['number'])\n\n### Transpose - Rows into columns\n\ndf = df.T\n```\n\n## Numpy Array\n\n\n```python\n\na = ar[1, 2]  # 5 - Access array\na = np.append(a, 3)  # Add element to the end\na = np.insert(a,1,[11,12])  # Into a on index 1 insert [11,12], next parameter can be axis\nnp.roll(a,2) # Posune array o 2 doprava\nwo = np.array([1,2,3]) # Shape (3,)\nwo = np.array([[1,2,3,4,5]]) # Shape (1,5)\nwo = np.array([[1],[2],[3],[4],[5]]) # Shape (5,1)\nshape = np.shape(a) # `(n,m) Number of rows, columns etc.\nar.shape[0]  # How many rows`\n\n## Convert\n\na = np.array([1, 2, 3])\nmy_list = ar.tolist()  # Convert on list\none_dim_list = np.array(ar).reshape(-1).tolist()  # Convert to one-dimensional list\na_scal = a[0].item()  # from np.int convert on int\n\n### Convert to other dtype\n\nb = a.astype(int)  # convert on np.int\n\n\n### Slicing\n\na = np.array([[1,2,3],[3,4,5],[4,5,6]])\n\n    #    [[1 2 3]\n    #     [3 4 5]\n    #     [4 5 6]]\n\n# Only column - not retain shape\n\nb = a[:, 1]  # [2 4 5]\n\n# Columns with same shape\n\nb = a[:, 1:2]  #   [[2]\n                #    [4]\n                #    [5]]\n\n# Only rows\n\nb = a[1, :]\n\n# Fancy indexing - Selecting with boolean mask\n\na = np.array([1, 2, 3, 4, 5, 6, 7])\nmask = (a % 3 == 0)  # [False False True False False True False]\na = a[mask]  # [3, 6]\n\n# Selecting subset of matrix with np.take\n\na = np.array([[4, 3, 5], [5, 7, 4], [6, 5,  8], [6, 5 , 8]])\nb = np.take(a, [1, 2], axis=0)  # Must use axis, else flattened\n            #  [[5 7 4]\n            #   [6 5 8]]\n\nb = np.take(a, [1, 2], axis=1)\n            #  [[3 5]\n            #   [7 4]\n            #   [5 8]\n            #   [5 8]]\n\n# Swap two rows\n\ndata[[0, 2], :] = data[[2, 0], :]\n\n### Join matrixes\n\nnp.vstack([a,a])\n\n    #   [[1, 2, 3],\n    #    [3, 4, 5],\n    #    [4, 5, 6],\n    #    [1, 2, 3],\n    #    [3, 4, 5],\n    #    [4, 5, 6]])\n\nnp.hstack([a,a])\n\n    #    [[1, 2, 3, 1, 2, 3],\n    #     [3, 4, 5, 3, 4, 5],\n    #     [4, 5, 6, 4, 5, 6]]\n\n# Swap two columns\n\na[:,[0, 1]] = a[:,[1, 0]]\n\n# Create matrix from vectors\n\na = np.array([1, 2, 3])\nb = np.array([2, 3, 4])\nc = np.stack((a, b))    # [[1, 2, 3],\n                        #  [2, 3, 4]]\n\n# Concatenate\n\na = np.array([[1, 2], [3, 4]])\nb = np.array([[5, 6]])\nnp.concatenate((a, b), axis=0)\n                                        # array([[1, 2],\n                                        #        [3, 4],\n                                        #        [5, 6]])\nnp.concatenate((a, b.T), axis=1)\n                                        #  array([[1, 2, 5],\n                                        #         [3, 4, 6]])\nnp.concatenate((a, b), axis=None)\n                                        # array([1, 2, 3, 4, 5, 6])\n\n# Append\n# Add column\n\nx = np.array([[10,20,30], [40,50,60]])\ny = np.array([[100], [200]])\nz = np.append(x, y, axis=1)\n\n    #   [[ 10  20  30 100]\n    #    [ 40  50  60 200]]\n\n### Find minimum value\n\nmin = np.amin(c, axis=1)\n\n### Mean\n\nmean = np.mean(x)\n\n### Find maximum or minimum absolute values\naa = max(a.min(), a.max(), key=abs)  # ! Can be the negative one and keep the sign\n\n### Standard deviation\n\nstd = np.std(x)\n\n### Limit array values\n\u200b\naa = np.array([1., 2., 3., -4, 5, 6])\nnp.minimum(aa, 3, out=aa)  # array([ 1.,  2.,  3., -4.,  3.,  3.])\n\n### Find index of smallest value\n\nind = np.unravel_index(np.argmin(a), shape=a.shape)\n\n### Create zero or ones matrix of given shape\n\nzeros = np.zeros_like(a)\n\n# Ones\n\nones = np.ones((3,3))\n\n    #   [[1., 1., 1.],\n    #    [1., 1., 1.],\n    #    [1., 1., 1.]]\n\n### Save slice scope to variable\nthe_slice = np.index_exp[1:]  # the_slice = numpy.index_exp[1:3, 1:3]\n\n### Replace all values with logical condition\n\na[a > .5] = .5\n\n### Delete member\n\na = np.delete(a, 1, axis=0) # There need to be variable before!  axis 0 are rows, 1 are columns\n\n### Numpy negative - invert logic\n# Use ~\n\n### If nan in array\n\nreality_results_matrix[iterated_model_index, data_length_index]\n\n### Delete Nan values\n\na = a[~np.isnan(a)]\n\n### Delete all rows where are Nan\n\na = a[~np.isnan(a).any(axis=1)]\n\n### Replace nan with number\n\na = np.nan_to_num(a, 0)\n\n### Delete all members that are bigger than condition\naa = np.array([1, 2, 3, 4, 1, 0, 0, 0.2])\nb = np.where(aa>=1,aa,1)\n\n### Rolling slides\nwindow = 2\naaa = np.array([1, 2, 3, 4])\nbbb = np.array([[1, 2, 3, 4], [3, 4, 5, 6]])\nshape = aaa.shape[:-1] + (aaa.shape[-1] - window + 1, window)\nshape_b = bbb.shape[:-1] + (bbb.shape[-1] - window + 1, window)\nstrides = aaa.strides + (aaa.strides[-1],)\nstrides_b = bbb.strides + (bbb.strides[-1],)\nppp = np.lib.stride_tricks.as_strided(aaa, shape=shape, strides=strides)  #[[[1 2], [2 3], [3 4]]\nqqq = np.lib.stride_tricks.as_strided(bbb, shape=shape_b, strides=strides_b)\n\n\n            # [[[1 2]\n            #   [2 3]\n            #   [3 4]]\n            #\n            #  [[3 4]\n            #   [4 5]\n            #   [5 6]]]\n\n### Sums\n\n# Axis 0 is for sums on columns\n\nnp.sum([[0, 1], [0, 5]], axis=0)  # array([0, 6])\nnp.sum([[0, 1], [0, 5]], axis=1)  # array([1, 5])\n\n### Dot product / multiplication\n\n# Asterisk means each with each not matrix multiplication\n\n# For vectors\n\nx = np.array([1,2,3])\nw = np.array([1,2,3])\nv = x*w # [1, 4, 9]\nv = np.dot(x, w) # 14\n\nx = np.array([1,2,3])\nw = np.array([[1],[2],[3]])\nv = x*w\n\n    #   [[1 2 3]\n    #    [2 4 6]\n    #    [3 6 9]]\n\nv = np.dot(x, w) # 14\n\n# For matrixes\n\nx = np.array([[1,2,3], [1,2,3], [1,2,3]])\nw = np.array([[1,2,3], [1,2,3], [1,2,3]])\nv = x*w\n\n    #   [[1 4 9]\n    #    [1 4 9]\n    #    [1 4 9]]\n\nv = np.dot(x, w)\n\n    #   [[6 12 18]\n    #    [6 12 18]\n    #    [6 12 18]]\n\n### Shape\n\nz = np.array([[1, 2, 3, 4],\n                [5, 6, 7, 8],\n                [9, 10, 11, 12]])\nz.shape  # (3, 4)\n\n### Number of members - count\n\ncount = z.size\n\n### Cumulative sum\n\ny = np.cumsum(x)\n\n### Set min and max\na = np.array([10, 7, 4, 3, 2, 2, 5, 9, 0, 4, 6, 0])\nprint (np.clip(a,2,6))  # [6 6 4 3 2 2 5 6 2 4 6 2]\n\n### Find members that are not in other array\na = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])\nb = np.array([3,4,7,6,7,8,11,12,14])\nc = np.setdiff1d(a,b)  # array([1, 2, 5, 9])\n\n### Remove non unique values\n\nunique = np.unique(array, axis=0)\n\n### Reshape\n\n# reshape -1 add members automatically\nz_res = z.reshape(-1) # array([ 1,  2,  3,  4,  5,  6])\nz_res2 = z.reshape(-1,1)\n\n    # array([[ 1],\n    #        [ 2],\n    #        [ 3],\n    #        [ 4],\n    #        [ 5],\n    #        [ 6]])\n\nz_res3 = z.reshape(-1, 2)\n    # array([[ 1,  2],\n    #        [ 3,  4],\n    #        [ 5,  6],\n    #        [ 7,  8],\n    #        [ 9, 10],\n    #        [11, 12]])\n\na = np.array([[1,2,3], [4,5,6]])\n\na_res = np.reshape(a, 6, order='F')\n    # array([1, 4, 2, 5, 3, 6])\n\n### Transpose\n\nz = np.array([[[1, 1, 1, 1],\n                [1, 1, 1, 1],\n                [1, 1, 1, 1]],\n\n                [[2, 2, 2, 2],\n                [2, 2, 2, 2],\n                [2, 2, 2, 2]],\n\n                [[3, 3, 3, 3],\n                [3, 3, 3, 3],\n                [3, 3, 3, 3]]\n                ])\n\nz_tran = z.transpose(1, 0, 2)  # From (10, 100, 1000) create (10, 1000, 100)\n\n    #    array([[[1, 1, 1, 1],\n    #            [2, 2, 2, 2],\n    #            [3, 3, 3, 3]],\n    #\n    #           [[1, 1, 1, 1],\n    #            [2, 2, 2, 2],\n    #            [3, 3, 3, 3]],\n    #\n    #           [[1, 1, 1, 1],\n    #            [2, 2, 2, 2],\n    #            [3, 3, 3, 3]]])\n\nz_tran = z.transpose(1, 2, 0)\n\n    #   array([[[1, 2, 3],\n    #           [1, 2, 3],\n    #           [1, 2, 3],\n    #           [1, 2, 3]],\n    #\n    #          [[1, 2, 3],\n    #           [1, 2, 3],\n    #           [1, 2, 3],\n    #           [1, 2, 3]],\n    #\n    #          [[1, 2, 3],\n    #           [1, 2, 3],\n    #           [1, 2, 3],\n    #           [1, 2, 3]]])\n\n### Generate points, arange, linspace, random and generate sin\n\nq = np.random.randn(3, 3)\nt = np.linspace(0,20,1000)  # Generate numbers with the same interval (beginning, end, number)\nt = np.arange(1, 3, 1)  # Start, stop, step - [1, 2]\nt = np.arange(3)  # 0, 1, 2\ny = np.sin(t)\n\n### Find index (one) with max / min value\n\nnp.argmax(x)  # or argmin. Also can use parameter axis\n\n### Iterate more members\n\nA = np.array([1, 2, 3, 4, 5, 6])\nfor i in range(len(A)):\n    indices = range(i-1,i+1)\n    neighbourhood = A.take(indices, mode='clip')  # mode wrap use other end of array on bounds, raise raise error\n    print(neighbourhood)\n                            # [1 1]\n                            # [1 2]\n                            # [2 3]\n                            # [3 4]\n                            # [4 5]\n                            # [5 6]\n\n# Or\nA = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\nneighbourhood = np.zeros(4)\nfor i in range(1, len(A)):\n    if i < len(neighbourhood):\n        neighbourhood[-i:] = A[:i]\n    else:\n        neighbourhood = A[i-4:i]\n    print(neighbourhood)\n\n                            # [0. 0. 0. 1.]\n                            # [0. 0. 1. 2.]\n                            # [0. 1. 2. 3.]\n                            # [1 2 3 4]\n                            # [2 3 4 5]\n                            # [3 4 5 6]\n                            # [4 5 6 7]\n                            # [5 6 7 8]\n                            # [6 7 8 9]\n\n### Eigen values\n\neig = np.linalg.eig(q)\n\neigenvalues, V = np.linalg.eig(A)  # eigenvalues[0] is the first eigenvalue\n# V is a 2D array (matrix) that contains the four eigenvectors as columns, hence, V[:,i] is the eigenvector corresponding to the eigenvalue eigenvalues[i]\n\nplt.scatter(eigenvalues.real, eigenvalues.imag)  # Plot it\n\n### Inverse matrix\n\nq_inv = np.linalg.inv(q)\n\n### Determinant\n\ndet = np.linalg.det(q)\n\n### Fill with Nan values\n\nz = np.zeros((2, 3))\nz.fill(np.nan)\n\n### Check if Nan values\n\nif not np.isnan(np.any(z)):\n    pass\n\n### Zip for arrays\n\ndef azip(*args):\n    iters = [iter(arg) for arg in args]\n    for i in itertools.count():\n        yield tuple([it.next() for it in iters])\n\n# Check which blas / lapack library you use - never use default. Use Intel mkl or atlas\nnp.__config__.show()\n```\n\n## HDF5\n\n\n```python\n'''\n### Create\n\nimport h5py\nimport numpy as np\n\narr = np.random.randn(1000)\n\nwith h5py.File('random.hdf5', 'w') as f:\n    dset = f.create_dataset(\"default\", data=arr)\n\n### Read\n\nwith h5py.File('random.hdf5', 'r') as f:\n    data = f['default']\n    print(min(data))\n\n### Specify Data Types to Optimize Space\n\nwith h5py.File('several_datasets.hdf5', 'w') as f:\n    dset_int_1 = f.create_dataset('integers', (10, ), dtype='i1')\n    dset_int_8 = f.create_dataset('integers8', (10, ), dtype='i8')\n    dset_complex = f.create_dataset('complex', (10, ), dtype='c16')\n    dset_int_1[0] = 1200\n'''\n```\n\n## Decimal\n\n\n```python\n\nIn normal float 1 + 1 is not 2 (but 2.0000000000001...)\nIn decimal it's equal\n\nimport decimal\n# Decimal\na = decimal.Decimal('0.1')\nb = decimal.Decimal('0.2')\nc = a + b # returns a Decimal representing exactly 0.3\n\n# Rounding\n\"%.3f\" % 1.2399 # returns \"1.240\"\n\"%.2f\" % 1.2 # returns \"1.20\"\n```\n\n# Type hinting\n\n\n```python\ndef sentence_has_animal(sentence: str) -> bool:\n    return \"animal\" in sentence\nsentence_has_animal(\"Donald had a farm without animals\")\n```\n\n# Iterators\n\n\n```python\niterable = [1, 2, 3]\niterator = iter(iterable)\n```\n\nNext value\n\n\n```python\nnext(iterator) # => \"one\"\n```\n\n# Conditions (if, else...)\n\n\n```python\nvariable = [10, 20, 30]\nfor i in variable:\n    if variable:\n        print(\"variable exist\")\n    if i > 10:\n        print(\"Something\")\n        pass  # Do nothing\n    elif i < 10:\n        print(\"Variable is smaller than 10\")\n        continue # Jump to other operation\n    else:\n        print(\"Variable is 10 or not a number\")\n        break # Jump out of the cycle\n```\n\n**Ternary operator - If in argument**\n\n\n```python\nvariable = 3\nstate = \"nice\" if variable else \"not nice\"\n```\n\n**Other shortened syntax**\n\n\n```python\na = 4\nb = 3\nx = 77\ny = 66\nresult = (y, x)[a > b]  # y if [True], x if [False]\n```\n\n# Loops\n\n## For\n\n\n```python\nfor zvire in [\"pes\", \"ko\u010dka\", \"my\u0161\"]:\n    print(\"zvire\")\nfor i in range(4):\n    print(i)\nfor i in range(4, 8):\n    print(i)\ncolors  =  [\"red\",  \"green\",  \"blue\",  \"purple\"]\nfor  i  in  range(len(colors)):\n    print(colors[i])\n```\n\n**Return indexes and elements**\n\n\n```python\nints = [8, 23, 45, 12, 78]\nfor idx, val in enumerate(ints):\n    print(idx, val)\n```\n\n**Break out of nested loop**\n\n\n```python\nfor x in xrange(10):\n    for y in xrange(10):\n        print x*y\n        if x*y > 50:\n            break\n    else:\n        continue  # only executed if the inner loop did NOT break\n    break  # only executed if the inner loop DID break\n```\n\n**Generate values with strings**\n\n\n```python\nfor k in range(5):\n    exec(f'cat_{k} = k*2')\n```\n\n**For in list comprehension**\n\n\n```python\n[x*5 for x in range(5)] #[0, 5, 10, 15, 20]\n```\n\n**Generate list with for cycle and if**\n\n\n```python\n[x for x in range(5) if x%2 == 0]  #[0, 2, 4]\n[a if a else  2  for a in  [0,1,0,3]]\n```\n\n**Generate list with more parameters**\n\n\n```python\nlist1 = [1, 2, 3]\nlist2 = [3, 4, 5]\n[a + b for a, b in zip(list1, list2)]\n```\n\n**Nested lists**\n\n\n```python\na = [[1,2,3],[2,3,4],[5,6,7]]\nprint(a[1][1])\n```\n\n## WHILE\n\n\n```python\nx = 0\nwhile x < 4:\n    print(x)\n    x += 1\n\n# You can use it also somewhere where you don't want to stop\n\nwhile True:\n    listen_forever()\n```\n\n# Functions\n\n\n```python\ndef secist(x, y):  # Create new function with def\n    return x + y  # Return values with return\n\nsecist(5, 6)  # Call the function with parameters, return 11\nsecist(y=6, x=5)  # Named arguments\n\ndef return_arguments(*argumenty):  # Variable number of arguments\n    return argumenty\n\nreturn_arguments(1, 2, 3)  # => (1, 2, 3)\n\ndef return_named_arguments(**pojmenovane_argumenty):  # Varaiable number of named arguments\n    return pojmenovane_argumenty\n\nreturn_named_arguments(kdo=\"se boj\u00ed\", nesmi=\"do lesa\")  # {\"kdo\": \"se boj\u00ed\", \"nesmi\": \"do lesa\"}\n\ndef return_all(*args, **kwargs):  # You can use combination\n    print(args, kwargs)  # Return all parameters\n```\n\n**Jump out of function - return**\n\n\n```python\ndef print_var():\n    a = 8\n    if a > 5:\n        return\n    print_var(2)\n```\n\n**Default parameter**\n\n\n```python\ndef funkce(y, lags=50): #If we use lags in call, it will be overwritten\n    return 1\n```\n\n**Unknown number of parameters - \\*args, \\*\\*kwargs**\n\n\n```python\ndef print_all(*args, **kwargs):\n    print(args, kwargs)\n\nprint_all(1, 2, a=3, b=4) # Use: (1, 2) {\"a\": 3, \"b\": 4}\ntuple = (1, 2, 3, 4)\ndic = {\"a\": 3, \"b\": 4}\nprint_all(tuple)  # Is like print_all((1, 2, 3, 4)). One parameter - tuple\nprint_all(*tuple)  # Is like print_all(1, 2, 3, 4)\nprint_all(**dic)  # Is like print_all(a=3, b=4)\nprint_all(*tuple, **dic)  # Is like print_all(1, 2, 3, 4, a=3, b=4)\n```\n\n**Global variables**\n\n\n```python\nx = 5\ndef setx(cislo):  # Local variable override global\n    x = cislo  # => 43\n    print(x)  # => 43\n\n\ndef setglobalx():\n    global x\n    print(x)  # => 5\n    x = cislo  # Set global x on 6, so x = 6 also outside the function !!!\nprint(x)  # => 6\n```\n\n**Functions are objects**\n\n\n```python\ndef adder(pricitane_cislo):\n    def scitacka(x):\n        return x + pricitane_cislo\n    return scitacka\nadd_10 = adder(10)\nadd_10(3)  # => 13\n```\n\n**callable**\n\nIs object function or not\n\n\n```python\nif callable(a):\n    pass\n```\n\n**Function in list generator**\n\n\n```python\n[add_10(i) for i in [1, 2, 3]]  # => [11, 12, 13]\n[x for x in [3, 4, 5, 6, 7] if x > 5]  # => [6, 7]\n```\n\n**Parse function arguments**\n\n\n```python\nimport inspect\nframe = inspect.currentframe()\nargs, _, _, values = inspect.getargvalues(frame)\n```\n\n### map(), filter(), reduce()\\*\\*\n\nFrom the functional programming\n\nMap call funtion (first parameter) on all objects (second parameter)\n\n\n```python\nmap(add_10, [1, 2, 3])\n```\n\nFilter create list (First paratemer), where function is true (second parameter)\n\n\n```python\nnumber_list = range(-5, 5)\nless_than_zero = list(filter(lambda x: x < 0, number_list))\nprint(less_than_zero)  # [-5, -4, -3, -2, -1]\n```\n\nReduce - Input sequention into function\n\n\n```python\nfrom functools import reduce\ndef do_sum(x1, x2): return x1 + x2\nreduce(do_sum, [1, 2, 3, 4]) # 10\n```\n\n# Generators\n\nGenerators are functions, that instead return have yield\n\n\n```python\ndef multiplier_2(sequention):\n    for i in sequention:\n        yield 2 * i\n```\n\nGenerator generate values one after one, when it\\s needed. Instead of been generated all at once\nExample of generator is range(10000)\n\n# Decorators\n\nDekorators are functions, that wrap other functions, by that\nit can change it's behaviour.\n\n\n```python\ndef nekolikrat(puvodni_funkce):\n    def repeat_function(*args, **kwargs):\n        for i in range(3):\n            puvodni_funkce(*args, **kwargs)\n    return repeat_function\n\n@nekolikrat\ndef pozdrav(Name):\n    print(\"Bye {}!\".format(Name))\n\npozdrav(\"Dan\")  # Return 3x: Bye Dan!\n```\n\n**Use decorator with condition**\n\n\n```python\nfrom memory_profiler import profile\nuse_decorator = False\n\ndef empty_decorator(fu):\n    return fu\n\nif use_decorator == False :\n    profile = empty_decorator\n\n@profile\ndef fu():\n    print('content')\n```\n\n# Modules\n\nModule in python is file with .py on the end. It is also imported python library (e.g. numpy...).\n\nYou can create your own and import it.\n\n\n```python\nfrom math import sqrt\n\nhelp(sqrt)  # Help with module\n\ndir(sqrt)  #  Show objects in module\n\n### Manual import\n_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)\neggs = _temp.eggs\nsaus = _temp.sausage\n\n### Import module from path\n\nimport importlib.util\nspec = importlib.util.spec_from_file_location(\"module.name\", \"/path/to/file.py\")\nfoo = importlib.util.module_from_spec(spec)\nspec.loader.exec_module(foo)\n\n### Check if module installed without import\n\nimportlib.find_loader(module_name)\n\n### Reimport module\nimport importlib\nimportlib.reload(config)\n```\n\n**Import all scripts in folder (e.g. in **init**.py)**\n\n\n```python\nimport os\nfrom os.path import dirname, basename, isfile, join\nimport glob\nmodules = glob.glob(join(dirname(__file__), \"*.py\"))\n__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]\n```\n\n# Classes\n\n\n```python\n\n\nclass Clovek(object):  # Class Human is child (it inherits from) class object\n\n    druh = \"H. sapiens\"  # Class variable - it's shared with all objects\n\n    def __init__(self, jmeno):\n        self.jmeno = jmeno  # Add parameter to object\n\n    def rekni(self, hlaska):\n        return \"{jmeno}: {hlaska}\".format(jmeno=self.jmeno, hlaska=hlaska)\n\n    @classmethod  # First parameter is class and can be changed in subclasses\n    def vrat_druh(cls):\n        return cls.druh\n\n    @staticmethod  # Do not depend on object - like a normal function and is immutable\n    def odkaslej_si():\n        return \"*ehm*\"\n\n# If no inheritance, no parenthesses prefered, just class Clovek:\n# Class can inherit from more classes at once...\n# class Clovek(tvor, bytost):\n\nclass DecoratorExample:\n\n    def __init__(self):\n        self.name = 'Decorator_Example'\n\n    def example_function(self):\n        print('I\\'m an instance method!')\n\nde = DecoratorExample()\nde.example_function()\n\n\n# Example of class method\n\nclass Date(object):\n\n    def __init__(self, day=0, month=0, year=0):\n        self.day = day\n        self.month = month\n        self.year = year\n\n    @classmethod\n    def from_string(cls, date_as_string):\n        day, month, year = map(int, date_as_string.split('-'))\n        date1 = cls(day, month, year)\n        return date1\n\n    @staticmethod\n    def is_date_valid(date_as_string):\n        day, month, year = map(int, date_as_string.split('-'))\n        return day <= 31 and month <= 12 and year <= 3999\n\ndate2 = Date.from_string('11-09-2012')\nis_date = Date.is_date_valid('11-09-2012')\n\n### Create object\n\nd = Clovek(jmeno=\"David\")\na = Clovek(\"Ad\u00e9la\")\nprint(d.rekni(\"ahoj\"))  # \"David: ahoj\"\nprint(a.rekni(\"nazdar\"))  # \"Ad\u00e9la: nazdar\"\n\n### Call class method\n\nd.vrat_druh() # => \"H. sapiens\"\n\n### Change atribute of class\n\nd.vrat_druh() # => \"H. neanderthalensis\"\na.vrat_druh() # => \"H. neanderthalensis\"\n\n### Call static method\n\nClovek.odkaslej_si() # => \"*ehm*\"\n\n### Check if class has atribute (method or )\nif hasattr(Clovek, 'rekni'):\n    print('Has David')\n\n### Get all objects and values\n\nprint(Clovek.__dict__)\n\n### Get all instances name\nimport gc\nfor obj in gc.get_objects():\n    if isinstance(obj, Clovek):\n        print (obj.jmeno)\n```\n\n## Magic methods (dunder methods)\n\nYou can overwrite some default functions to have specific feature for your class. For example if your object is vector, you can redefine function for adding to be able to use `vector1 + vector2`, which would otherwise failed.\n\nExample **call** method (Allow input of object to function)\n\nThe \\_\\_call** method can be used to turn the instances of the class into callables. Functions are callable objects. A callable object is an object which can be used and behaves like a function but might not be a function. By using the \\_\\_call** method it is possible to define classes in a way that the instances will be callable objects. The \\_\\_call\\_\\_ method is called, if the instance is called \"like a function\", i.e. using brackets. The following example defines a class with which we can create abitrary polynomial functions:\n\n\n```python\nclass Polynomial:\n\n    def __init__(self, *coefficients):\n\n        self.coefficients = coefficients[::-1]\n\n    def __call__(self, x):\n\n        res = 0\n\n        for index, coeff in enumerate(self.coefficients):\n\n            res += coeff * x** index\n\n            return res\n\np1 = Polynomial(42)\np2 = Polynomial(0.75, 2)\np3 = Polynomial(1, -0.5, 0.75, 2)\n\nfor i in range(1, 10):\n    print(i, p1(i), p2(i), p3(i))\n```\n\nMagic methods (For example for change of + behaviour)\nWhat happens when we create an object in python class ?\n\n\n```python\n'''\nList of magic methods:\nBinary Operators\n\nOperator           Method\\\n+                       object.__add__(self, other)\\\n-                        object.__sub__(self, other)\\\n*                        object.__mul__(self, other)\\\n//                       object.__floordiv__(self, other)\\\n/                        object.__div__(self, other)\\\n%                      object.__mod__(self, other)\\\n**                      object.__pow__(self, other[, modulo])\\\n<<                     object.__lshift__(self, other)\\\n>>                     object.__rshift__(self, other)\\\n&                       object.__and__(self, other)\\\n^                       object.__xor__(self, other)\\\n|                        object.__or__(self, other)\n\nAssignment Operators:\n\nOperator          Method\\\n+=                     object.__iadd__(self, other)\\\n-=                      object.__isub__(self, other)\\\n*=                      object.__imul__(self, other)\\\n/=                      object.__idiv__(self, other)\\\n//=                     object.__ifloordiv__(self, other)\\\n%=                    object.__imod__(self, other)\\\n**=                     object.__ipow__(self, other[, modulo])\\\n<<=                   object.__ilshift__(self, other)\\\n>>=                   object.__irshift__(self, other)\\\n&=                     object.__iand__(self, other)\\\n^=                      object.__ixor__(self, other)\\\n|=                      object.__ior__(self, other)\n\nUnary Operators:\n\nOperator          Method\\\n-                       object.__neg__(self)\\\n+                      object.__pos__(self)\\\nabs()                object.__abs__(self)\\\n~                      object.__invert__(self)\\\ncomplex()        object.__complex__(self)\\\nint()                  object.__int__(self)\\\nlong()               object.__long__(self)\\\nfloat()               object.__float__(self)\\\noct()                object.__oct__(self)\\\nhex()               object.__hex__(self)\n\nComparison Operators\n\nOperator Method\\\n<                      object.__lt__(self, other)\\\n<=                    object.__le__(self, other)\\\n==                    object.__eq__(self, other)\\\n!=                     object.__ne__(self, other)\\\n>=                    object.__ge__(self, other)\\\n>                      object.__gt__(self, other)\n'''\n\n# Let's take an example to override the functionality \"+\" '[__add__]' operator\n\nclass  Vector(object):\n    def __init__(self,  *args):\n        \"\"\" Create a vector, example: v = Vector(1,2) \"\"\"\n        if len(args)  ==  0:\n            self.values =  (0,0)\n        else:\n            self.values = args\n    def __add__(self, other):\n        \"\"\" Returns the vector addition of self and other \"\"\"\n        added = tuple(a + b for a, b in zip(self.values, other.values)  )\n        return  Vector(*added)\n\n# Now use the \"+\" operator with two vectors\n\nv1 =  Vector(1,  2)\nv2 =  Vector(10,  13)\nv3 = v1 + v2\nv3.values  # (11,  15)\n\n# When statement \"v3 = v1 + v2 \" executes \"__add__\" is called and it returns a new Vector object.\n```\n\n**Repr**\n\nclass Pizza:\ndef **init**(self, ingredients):\nself.ingredients = ingredients\n\n\n```python\ndef __repr__(self):\n    return f'Pizza({self.ingredients!r})'\n```\n\nIf Pizza() return **repr**\n\n# Bitwise operations\n\nUnsigned integers can hold bigger values, but cannot be negative!!!\n\n\n```python\n### Convert number to bits\n\nbinn = bin(123)  # 0b1111011\n\n# Or\n\nfour_bytes = 16.to_bytes(4, byteorder='big', signed=True)\nprint(four_bytes)\n\n### Convert with keep bit structure\n\nbin_number = f'{3:08b}'  # 00000011\nbin_number = f'{3:#08b}'  # 0b000011\n\n### Bit length\n\na.bit_length()\n\n# Convert back to int again\n\nint('11111111', 2)  # 255\n\n# Or i = int.from_bytes(some_bytes, byteorder='big')\n\n# Create empty bytes\nempty_bytes = bytes(4)\n\n### And, or etc...\n\na = 60            # 60 = 0011 1100\nb = 13            # 13 = 0000 1101\nc = 0\n\n### Bit and\nc = a & b;        # 12 = 0000 1100\n\n### Bit or\nc = a | b;        # 61 = 0011 1101\n\n### bitwise exclusive or\nc = a ^ b;        # 49 = 0011 0001\n\n### Flip bits\nc = ~a;           # -61 = 1100 0011\n\n# Bit shift (4 bits)\nc = a << 2;       # 240 = 1111 0000\nc = a >> 2;       # 15 = 0000 1111\n\n# Formating\nbin = \"{0:b}\".format(i) # binary: 11111111\nhex = \"{0:x}\".format(i) # hexadecimal: ff\noct = \"{0:o}\".format(i) # octal: 377\n\n```\n\n# File I/O\n\n**Import fuction from other file**\n\n\n```python\nfrom math import sqrt  # First name of file, than function\n```\n\n**Find script's adress**\n\n\n```python\nimport os\n# os.path.dirname(__file__)  # Not working in jupyter !\n```\n\n**Import variables from file in the same folder**\n\n\n```python\n# import file  # Then call file.value\n# from file import * # Now call just variable\n```\n\n**If file or dir exists**\n\n\n```python\nfrom pathlib import Path\nmy_file = Path(\"/path/to/file\")\nif my_file.is_file():  # File exists\n    pass\nif my_file.is_dir():  # Directory exists\n    pass\nif my_file.exists():   # File or dir exists\n    pass\n```\n\n**Create module from folder**\n\nAdd file `__init.py__`\nInside do all imports from .autoregLNU import autoregLNU\nUse relative imports with dots\n\n**Show all files in folder**\n\n\n```python\n# all_files = os.listdir(\"test/\")\n```\n\n**Filter for one type data**\n\n\n```python\n# txt_files = filter(lambda x: x[-4:]  ==  '.txt', all_files)\n```\n\n**Count files with certain suffix**\n\n\n```python\ntifCounter = len(glob.glob1(myPath,\"*.tif\"))\n```\n\n**Load all files with certain suffix**\n\n\n```python\nimport glob\nimgs=glob.glob(\"*.png\")  # V\u0161echny obr\u00e1zky ze slo\u017eky\n\n# Wildcard\n\nfor name in glob.glob('dir/file?.txt'):\n    print (name)\n\nfor name in glob.glob('dir/*[0-9].*'):\n    print (name)\n```\n\n**Add file names from folder to list**\n\ndata_names_list = list(glob.glob((script_dir / '\\*.dat').as_posix()))\n\n**Import txt**\n\n\n```python\nfrom numpy import loadtxt\n# x=loadtxt('realna_data_klapky.txt')\n```\n\n## Open file\n\n\n```python\nf = open(\"test.txt\", \"w+\") # open file in current directory\n\n'r'  Open a file for reading. (default)\n'w'  Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.\n'x'  Open a file for exclusive creation. If the file already exists, the operation fails.\n'a'  Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.\n't'  Open in text mode. (default)\n'b'  Open in binary mode.\n'+'  Open a file for updating (reading and writing)\n\n\nf = open(\"C:/Python33/README.txt\") # specifying full path\nf.close()\n\nwith open(\"test.txt\",'w')  as f:\n    pass\nf.write(\"my first file\\n\")\nf.write(\"This file\\n\\n\")\nf.write(\"contains three lines\\n\")\n\n!!!Use because this will autamatically close the file finally\n\nf = open(\"test.txt\",'r',encoding =  'utf-8')\nf.read(4)  # Read the first 4 data - 'This'\nf.read(4)  # Read the next 4 data - ' is '\nf.read()  # Read in the rest till end of file - 'my first file\\nThis file\\ncontains three lines\\n'\nf.read() # Further reading returns empty sting\n\n# !!! After editing text, jump with cursor to the beginning before read\nf.seek(0)\nf.read()  # Return all\n'''\n```\n\n## Manipulate with files (move, copy)\n\n\n```python\n'''\n### Copy file ###\n\nimport shutil, os\ns.chdir('C:\\\\')\nshutil.copy('C:\\\\spam.txt', 'C:\\\\delicious')\n\n### Copy folder with all files ###\nshutil.copytree('C:\\\\bacon', 'C:\\\\bacon_backup')\n\n### Move files ###\nshutil.move('C:\\\\bacon.txt', 'C:\\\\eggs')\n\n### Remove - move to trash bin ###\nimport send2trash\nsend2trash.send2trash('bacon.txt')\n\n### Remove file ###\nos.unlink(path)\n\n### Remove folder with all content ###\nshutil.rmtree(path)\n\n### File tree - walk ###\nimport os\n\nfor folderName, subfolders, filenames in os.walk('C:\\\\delicious'):\n    print('The current folder is ' + folderName)\n\n    for subfolder in subfolders:\n        print('SUBFOLDER OF ' + folderName + ': ' + subfolder)\n    for filename in filenames:\n        print('FILE INSIDE ' + folderName + ': '+ filename)\n'''\n```\n\n# Try -- Except\n\n\n```python\ntry:\n    print(znam)\nexcept:\n    print('except')\nelse:\n    print('else')\nfinally:\n    print('final')\n\ntry:\n    print(neznam)\nexcept:\n    print('except')\nelse:\n    print('else')\nfinally:\n    print('final')\n```\n\n**Try for all errors and print it**\n\n\n```python\ntry:\n    linux_interaction()\n\nexcept Exception as error:\n    print(error)\n```\n\n**Raise exception**\n\n\n```python\n# if somethingbad:\n#   raise Exception('x should not exceed 5. The value of x was: {}')  # Better concrete error. E.g. ValueError...\n```\n\n**Raise in except block**\n\n\n```python\ntry:\n    1/0\nexcept Exception:\n    raise\n```\n\n**Assert - Require something or error**\n\n\n```python\nx = 5\nassert (x > 4), 'What happened'\n```\n\n**Print error details in except block**\n\n\n```python\nimport traceback\n\ntry:\n    1/0\nexcept Exception as e:\n    print(traceback.format_exc())\n```\n\n# Built in functions\n\n**Print**\n\n\n```python\na = 'hi'\nprint('as', a, 'fegg') # Use comma, you can join strings and variables\n```\n\n**Range**\n\n\n```python\nx=range(3+1) # x = 0, 1, 2, 3\n```\n\n**Reversed**\n\n\n```python\nfor i in reversed(range(5)):\n    print(i) # 4, 3, 2, 1\n```\n\n# Built in variables\n\n**\\_\\_name\\_\\_**\n\nIf file is runned from inside or is imported, code inside condition will not be executed. If file itsel will be started, code will execute.\n\n\n```python\nif __name__ == \"__main__\":\n    pass\n```\n\n# Built in modules\n\n## Sys\n\n**Get size on memory**\n\n\n```python\nimport sys\nx = 2\nsys.getsizeof(x)\n```\n\n**Add path to sys path**\n\nsys.path.insert(0, \"/path/to/your/package_or_module\")\n\n## io\n\n**Capture everything printed plus warnings**\n\n\n```python\nimport sys, io\nstdout = sys.stdout\nsys.stdout = io.StringIO()\n\nwarnings.warn(f\"asdefwefwg\")\nprint(\"aho\")\n\n# get output and restore sys.stdout\noutput = sys.stdout.getvalue()\nsys.stdout = stdout\n\nprint(output)\n```\n\n## os\n\n**Change working directory**\n\n\n```python\nimport os\nos.chdir(r\"C:\\Users\\...\")\n```\n\n**Environment variables**\n\n\n```python\nimport os\nenv_var = os.environ['ENV_VAR']\n```\n\n## Pathlib - Work with paths\n\n\n```python\n\n# Get path of running file\nfrom pathlib import Path\nimport inspect\nimport os\n\n# Get script path\nfile_path = Path(__file__)\n\n# If it has to also work in jupyterm, you cannot use __file__\nfile_path = Path(os.path.abspath(inspect.getframeinfo(inspect.currentframe()).filename))\n\n# Directory path\ndir_path = file_path.parent\n\n# Parents\ndir_path = file_path.parents[2]\n\n# Combining paths\nfile_to_open = data_folder / \"subfolder\" / \"raw_data.txt\"\n\n# Current working directory\npath = pathlib.Path.cwd()\n\n# Pathlib as string\n\npath.as_posix()\n\n# Find full adress\n\npath = pathlib.Path('test.md')  # test.md\npath.resolve() # /home/gahjelle/realpython/test.md'\n\n# Compare paths\npath.resolve().parent == pathlib.Path.cwd() # False\n\n# Work with file\n\nfilename = pathlib.Path(\"source_data/text_files/raw_data.txt\")\n\nprint(filename.name) # prints \"raw_data.txt\"\nprint(filename.suffix) # prints \"txt\"\nprint(filename.stem) # prints \"raw_data\"\n\nif not filename.exists():\n    print(\"Oops, file doesn't exist!\")\nelse:\n    print(\"Yay, the file exists!\")\n\n# Path of Desktop\ndesktop = Path.home() / \"Desktop\"\n\n\n'''\n\n!! Next rows just historical - Do not do it that way !!\n\nfrom os import path\nimport os\n\nfile_path = path.relpath(\"data/data.txt\")\n\n### Absolute path\n\n# os.path.abspath(\\__file__)  # Not working in jupyter\n\n### Add path to files and modules\n\nimport os\ndata_folder = \"folder/nextfolder/\"\nfile_to_open = data_folder + \"data.txt\"\n\n# For example if jupyter do not see some files\n\nscript_dir0 = os.path.abspath('') # C:\\VScode\n\n# Next\n\n# script_path = os.path.abspath(\\__file__)  # i.e. /path/to/dir/foobar.py  - notworking with jupyter\nscript_path = 'C://prog'\nscript_dir = os.path.split(script_path)[0]  #i.e. /path/to/dir/\nrel_path =  \"2091/data.txt\"\nabs_file_path = os.path.join(script_dir, rel_path)  # Result is relative '/path/to/dir/2091/data.txt'\nfilename = os.path.join(script_path,  '../same.txt')  # We can use name of file\n\ndir_path = os.path.dirname(os.path.realpath(__file__))  # We can use adress of file... but not in jupyter\n\n# You can also do\n\n# script_dir = os.path.dirname(\\__file__)\nrel_path = \"test_ data/realna_data_klapky.txt\"\nabs_file_path = os.path.join(script_dir, rel_path)\n'''\n```\n\n## Warnings\n\n\n```python\nimport warnings\nwarnings.warn(\"Warning...........Message\")\n\n# Warnings with word 'HessianInversionWarning' will be caused as errors\n\nwarnings.filterwarnings('error', message=r\"[\\s\\S]*HessianInversionWarning*\")\n\n# Errory of category depracation will be show everytime\n\nwarnings.filterwarnings('always', category=DeprecationWarning)\nwarnings.filterwarnings('ignore')  # Errory budou v\u017edy ignorov\u00e1ny\n\n# \"default\" will print the first occurrence of matching warnings for each location\n# (module + line number) where the warning is issued\n\n# Other possibilities\n\n# \"once\"    |    \"error\"    |    \"ignore\"    |    \"always\"    |    \"module\"\n```\n\nprint the first occurrence of matching warnings for each module where the warning is issued (regardless of line number)\n\n## re - Regular expressions\n\n\n```python\nregs = '''\nimport re\n\n[] \tA set of characters \t\"[a-m]\"\n\\ \tSignals a special sequence (can also be used to escape special characters) \t\"\\d\"\n. \tAny character (except newline character) \t\"he..o\"\n^ \tStarts with \t\"^hello\"\n$ \tEnds with \t\"world$\"\n* \tZero or more occurrences \t\"aix*\"\n+ \tOne or more occurrences \t\"aix+\"\n{} \tExactly the specified number of occurrences \t\"al{2}\"\n| \tEither or \t\"falls|stays\"\n\n\\A \tReturns a match if the specified characters are at the beginning of the string \t\"\\AThe\"\n\\b \tReturns a match where the specified characters are at the beginning or at the end of a word \tr\"\\bain\"\nr\"ain\\b\"\n\n\\B \tReturns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word \tr\"\\Bain\"\nr\"ain\\B\"\n\n\\d \tReturns a match where the string contains digits (numbers from 0-9) \t\"\\d\"\n\\D \tReturns a match where the string DOES NOT contain digits \t\"\\D\"\n\\s \tReturns a match where the string contains a white space character \t\"\\s\"\n\\S \tReturns a match where the string DOES NOT contain a white space character \t\"\\S\"\n\\w \tReturns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character) \t\"\\w\"\n\\W \tReturns a match where the string DOES NOT contain any word characters \t\"\\W\"\n\\Z \tReturns a match if the specified characters are at the end of the string \t\"Spain\\Z\"\n\n[arn] \tReturns a match where one of the specified characters (a, r, or n) are present\n[a-n] \tReturns a match for any lower case character, alphabetically between a and n\n[^arn] \tReturns a match for any character EXCEPT a, r, and n\n[0123] \tReturns a match where any of the specified digits (0, 1, 2, or 3) are present\n[0-9] \tReturns a match for any digit between 0 and 9\n[0-5][0-9] \tReturns a match for any two-digit numbers from 00 and 59\n[a-zA-Z] \tReturns a match for any character alphabetically between a and z, lower case OR upper case\n[+] \tIn sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a match for any + character in the string\n\n'''\n```\n\n## Subprocess - Run shell comands\n\n\n```python\n# Subprocess replace the os.system()\nimport subprocess\n\nsubprocess.run('ls')\np1 = subprocess.run(['ls', '-la']) # with capture_output=True only save to variable\nprint(p1.stdout)\n\n# More general - can define stdout and more here\nsts = subprocess.Popen(\"mycmd\" + \" myarg\", shell=True).wait()\n```\n\n## Pickle\n\nSave file in binary format\n\n\n```python\nimport pickle\nd = {\"a\": 1, \"b\": 2}\n# with open(r\"someobject.pickle\", \"wb\") as output_file: cPickle.dump(d, output_file)\n```\n\nLoad files\n\n\n```python\n# with open(r\"someobject.pickle\", \"rb\") as input_file: e = cPickle.load(input_file)\n```\n\nResult is `e = {\"a\": 1, \"b\": 2}`\n\n## Time and datetime\n\n\n```python\nimport datetime as dt\nimport time\n\n### Print today's date\n\ndate = datetime.datetime.now().strftime('%d-%m-%Y')\n\n### Measure time interval\n\nstart = time.time()\na = 6\nend = time.time()\nprint(end - start)\n\n\n### Wait for some time\n\ntime.sleep(1) # wait 1 second\n```\n\n# Imported libraries\n\n## Tests - pytest\n\n\n```python\n# Write test file\n\n# Use assert functions\n\ndef secti(a, b):\nreturn a + b\n\ndef test_secti():\n    assert secti(1, 2) == 3\n\npip install pytest\n\npip install pytest-benchmark\ndef test_my_function(benchmark):\n    result = benchmark(test)\n\n\n# Run test\n\npython -m pytest -v test_secteni.py\n\n# Run tests in a module\npytest test_mod.py\n\n# Run tests in a directory\npytest testing/\n\n# Paraterize tests\n\n@pytest.mark.parametrize(\n        ['year', 'month', 'day'],\n        [(2015, 12, 24),\n        (2016, 12, 24),\n        (2017, 1, 1),\n        (2033, 7, 5),\n        (2048, 7, 6)],\n)\n\ndef test_some_holidays(year, month, day):\n    \"\"\"Test a few sample holidays\"\"\"\n    holidays = isholiday.getholidays(year)\n    assert (day, month) in holidays\n```\n\n## Command Line Arguments - argparse\n\nIf you want to call a script from terminal like `python myscript.py` and want to add some optional arguments (one letter -a , -b etc. or word with two dashes --var)\n\nNowadays argparse is better and more often used than sys.argv, getopt\n\n\n```python\nimport argparse\n\nparser = argparse.ArgumentParser(description='A tutorial of argparse!')\nparser.add_argument('-l','--list', default=1, type=int, help=\"This is the 'l' variable\")\nparser.add_argument(\"--education\",\n                    choices=[\"highschool\", \"college\", \"university\", \"other\"],\n                    required=True, type=str, help=\"Your name\") # If type list, just append action='append'\n\nargs = parser.parse_args()\n\n# If error with jupyter, then !!!\npar_args = parser.parse_known_args()\nmyarg = par_args[0].myarg\n\ned = args.education\n\nif ed == \"college\" or ed == \"university\":\n    print(\"Has degree\")\nelif ed == \"highschool\":\nprint(\"Finished Highschool\")\nelse:\n    print(\"Does not have degree\")\n```\n\n## Plots, graphs\n\n### Plotly\n\n\n```python\npltl = '''\n\nimport plotly as plo\nimport cufflinks as cf\n\ndef plot_df(df, save_plot=0, save_plot_path=\"plot.html\"):\n\n    cf.go_offline()\n\n    if save_plot:\n        fig = df.iplot(asFigure=True)\n        plo.offline.plot(fig,filename=save_plot_path)\n    else:\n        df.iplot(kind='scatter', filename=\"ploot.html\")\n\n    return\n\n\nimport plotly as py\n# import cufflinks as cf\n\nfig = dict(data=data, layout=layout )\npy.offline.plot(fig, filename='d3-cloropleth-map')\n\n# or\n\ninit_notebook_mode(connected=True)\ncf.go_offline()\n\ndata_ft_date.iplot(xTitle='Dates',yTitle='Returns',title='Returns')\n\n\n### Plotly timeseries\n\npy.plotly.iplot([{\n    'x': data_for_predicts_csv_trimmed.index,\n    'y': data_for_predicts_csv_trimmed[col],\n    'name': col\n}  for col in data_for_predicts_csv_trimmed.columns])\n\n# Or the same with cufflinks\ncf.go_offline()\ndf.iplot(kind='scatter', filename='cufflinks/cf-simple-line')\n\n### From matplotlib to plotly\n\nplot_mpl(fig)\n\n### Save picture\n\nimport plotly.io as pio\nstatic_image_bytes = pio.to_image(fig, format='png')\n'''\n```\n\n### Matplotlib\n\n\n```python\nmtpltlb = ''' Just to not load in jupyter...\n### Simple plot\n\nimport matplotlib.pyplot as plt\nplt.plot(data)\n\n### Load txt and plot it\n\nfrom numpy import loadtxt # For one column txt\nx = loadtxt('realna_data_klapky.txt')\nfigure(figsize=(20,5))\nplot(x,'-o',label=\"x\");xlabel('i');ylabel('x [sec]');grid();title(\"realna_data_klapky.txt\")\nlegend();show()\nplt.savefig('fig1.png', dpi =  300) # ulo\u017e\u00ed graf\n\n### Jupyter plot one after one\n\n# Use not show()\n%matplotlib notebook\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = [1, 2, 3, 4, 5, 6]\n\nfig, axes = plt.subplots()\naxes.plot(range(10))\n#figure one\n\n\nfig, axes = plt.subplots()\naxes.plot(range(10))\n#figure two\n\n\nfig, ((a,b),(c,d)) = plt.subplots(2,2)\na.plot(x, np.sin(x))\nb.plot(x, np.cos(x))\nc.plot(x, np.tan(x))\nd.plot(x, np.tanh(x))\n\n### Histogram\n\nfigure(figsize=(20,5))\nnbins=int(round(1+3.3*log(N))) # Sturge's rule, but depend on data\nxlabel(\"x\");ylabel(\"number_of_bins\"),title(\"number_of_bins  - values x in intervals\");grid()\na=hist(x,bins=nbins) # vraci dve pole a histogram, tj a[0]=number_of_bins, a[1]=intervaly\nprint \"number_of_bins=\",a[0]\nprint \"intervaly =\",a[1]\n\n### Curves and points\n\nx=arange(-600,100) #\nmu=m1;sigma=sqrt(s2);print \"mu=\",mu,\"sigma=\",sigma\nf=1/(sigma*sqrt(2*pi))*exp(-(((x-mu)/sigma)**2)/2)\nfigure(figsize=(20,5))\nplot(x,f,'g',label=\"f(x) spojita\");grid()\nplot(x_i,f_odhad,'o',label=\"f(x) odhad z mereni pro nbin=\"+str(nbins)+\" intervalu\")\nlegend()\n\n### Two graphs\n\nN=1000 # velikost v\u00fdb\u011bru\nx=random.uniform(-10,10,N)\nx=random.randn(N)*1000-300\nx=random.logistic(3, 10, N)\nx=random.standard_t(3, N)\nx=random.poisson(1, N)*.01+1000\nnbins=int(round(1+3.3*log(N)))\nfigure(figsize=(20,5))\nsubplot(121);plot(x,'-o');grid();xlabel('index vzorku dat');ylabel(\"x\")\nsubplot(122)\n\n# First number is how much rows and second how much columns\n# Third number is which graph is it - first, second etc.\n\na = hist(x,nbins,normed=True)\ngrid(); ylabel(\"$\\\\approx f(x)$\"); xlabel(\"x\")\nplt.tight_layout() # Pokud \u010d\u00e1st jednoho p\u0159ekr\u00fdv\u00e1 druh\u00fd\nplt.subplots_adjust(top=0.88)# po tight_layoutu je pot\u0159eba n\u00e1zev um\u00edstit v\u00fd\u0161\nsubplots_adjust(wspace=.3) # V\u011bt\u0161\u00ed rozestupy mezi grafy\n\n### Another way to do more plots\n\nfig = plt.figure()\n\nax1 = plt.subplot(311)\n\nax2 = plt.subplot(312, sharex=ax1)  # Share axis\nplt.ylabel(\"Error\")\n# Or rather  ax.set_ylabel('common ylabel')   - also for x\n\nsetp(ax2.get_xticklabels(), visible=False)  # To hide numbers on xaxis\nax3 = plt.subplot(313)\nplt.ylabel(\"Weights\")\n\n# If interactive add   ax1.clear()\ny_ref_pl, = ax1.plot(t, y_ref, label=\"Skute\u010dnost\"); plt.xlabel('t')\ny_pl, = ax1.plot(t, y, label=\"Identifikovan\u00e1\")\nplt.legend(loc=\"upper right\")\n\ne_pl, = ax2.plot(t, e)\n\nw_all_pl = ax3.plot(t, w_all)\nplt.ylabel(\"Hodnoty vah\")\n\n### More plots with one legend\n\nplt.figure(figsize=(12,7))\nplt.subplot(3, 1, 1)\nplt.plot(t, yy, label='Predikce'); plt.xlabel('t')\nplt.plot(t, data, label='Skute\u010dnost'); plt.xlabel('t')\nplt.legend(loc=\"upper right\")  # prop={'size': 6}   to change size\nplt.ylabel(\"u4 predikovan\u00e9\")\n\n# Or\n\nline_up, = plt.plot([1,2,3], label='Line 2')\nline_down, = plt.plot([3,2,1], label='Line 1')\nplt.legend(handles=[line_up, line_down])\n\n### More plots with for cycle\n\nfor i in range(1,7):\nplt.subplot(3, 2, i)\nplt.plot(oknomean[i]);plt.grid(); plt.xlabel('t')\nplt.ylabel(\"u{}\".format(i))\nplt.suptitle(\"Klouzav\u00fd pr\u016fm\u011br okna\", fontsize=20)\nplt.tight_layout()\nplt.subplots_adjust(top=0.88)\nplt.show()\n\n### Scatterplot\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nN = 60\ng1 = (0.6 + 0.6 * np.random.rand(N), np.random.rand(N))\ng2 = (0.4+0.3 * np.random.rand(N), 0.5*np.random.rand(N))\ng3 = (0.3*np.random.rand(N),0.3*np.random.rand(N))\ndata = (g1, g2, g3)\ncolors = (\"red\", \"green\", \"blue\")\ngroups = (\"coffee\", \"tea\", \"water\")\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1, axisbg=\"1.0\")\nfor data, color, group in zip(data, colors, groups):\nx, y = data\nax.scatter(x, y, alpha=0.8, c=color, edgecolors='none', s=30, label=group)\nplt.title('Matplot scatter plot')\nplt.legend(loc=2)\nplt.show()\n\n### Text plot\n\nimport matplotlib.pyplot as plt\nfig = [plt.figure](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.figure.html#matplotlib.pyplot.figure \"View documentation for matplotlib.pyplot.figure\")(figsize=(5, 1.5))\n\ntext = fig.text(0.5, 0.5, 'Hello path effects world!\\nThis is the normal '\n    'path effect.\\nPretty dull, huh?',\n    ha='center', va='center', size=20)\n\n[plt.show](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.show.html#matplotlib.pyplot.show \"View documentation for matplotlib.pyplot.show\")()\n\n### Log axis\n\nplt.loglog(x, y)  # Both axis are log\n\n'''\n```\n\n## Tables\n\n\n```python\nfrom prettytable import PrettyTable\nmodels_table = PrettyTable()\nmodels_table = PrettyTable().field_names = [\"City name\", \"Area\", \"Population\", \"Annual Rainfall\"]\nmodels_table = PrettyTable().add_row([\"Adelaide\", 1295, 1158259, 600.5])\nprint (models_table)\n```\n\n## Web\n\n### Requests - API - GET, POST\n\n\n```python\nrqsts = '''\nimport getpass\nimport requests\nusername = input('Username: ')\nUsername: hroncok\npassword = getpass.getpass()   # Do not use...\nPassword:\nr = requests.get('https://api.github.com/user', auth=(username, password))\nr.status_code\nr.headers['content-type']  # 'application/json; charset=utf8'\nr.encoding  # 'utf-8'\nr.text  # '{\"login\":\"hroncok\"...'\nr.json()  # {'avatar_url': 'https://avatars.githubusercontent.com/u/2401856?v=3', ...}\n\n# Session\n\nsession = requests.Session()\nsession.get('http://httpbin.org/cookies/set/mipyt/best')  #<Response [200]>\nr = session.get('http://httpbin.org/cookies')\nr.json()  # {'cookies': {'mipyt': 'best'}}\nsession.headers.update({'x-test': 'true'})\nr = session.get('http://httpbin.org/headers', headers={'x-test2': 'true'})\nr.json()  # {'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'close', 'Cookie': 'mipyt=best', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.19.1', 'X-Test': 'true', 'X-Test2': 'true'}}\n'''\n```\n\n### Beautiful soup - web scrapping\n\n\n```python\n# Stuff for soup\nsoup = \"\"\"\nsample_html =  '''\n<html>\n    <head>\n        <title>Test</title>\n    </head>\n    <body>\n        <h1>Heading!</h1>\n        <p class=\"major_content\">Some content.</p>\n        <p class=\"minor_content\">The important information is, that the key number is 23..</p>\n    </body>\n</html>\n'''\n\nfrom bs4 import BeautifulSoup\n\n# path to data\npath = \"data/example1.html\"\n\n# template for printing the output\nsentence = \"{} {} is {} years old.\"\n\n# load data\nwith open(path, 'r') as datafile:\n    sample_html = datafile.read()\n\n# create tree\nsoup = BeautifulSoup(sample_html, \"html.parser\")\n\n# get title and print it\ntitle = soup.find(\"title\")\nprint(title.text, \"\\n\")\n\n# select all rows in table\ntable = soup.find(\"table\",  {\"id\": \"main_table\"})\ntable_rows = table.findAll(\"tr\")\n\n# iterate over table and print results\nfor row in table_rows:\n    first_name = row.find(\"td\", {\"class\": \"first_name\"})\n    last_name = row.find(\"td\", {\"class\": \"last_name\"})\n    age = row.find(\"td\", {\"class\": \"age\"})\n    if first_name and last_name and age:\n        print(sentence.format(first_name.text, last_name.text, age.text))\n\n# Print attributes\nprint(table.attrs)\n{'id': 'main_table'}\n\n### Parse sentence\nimport re\nprint(re.search('the key number is (.*).', sample_html).group(1))  # 23\n\n## Create simplest http server\n\nimport SimpleHTTPServer\nimport SocketServer\n\nPORT = 8000\nADDRESS = \"127.0.0.1\"\n\nHandler = SimpleHTTPServer.SimpleHTTPRequestHandler\n\nhttpd = SocketServer.TCPServer((ADDRESS, PORT), Handler)\n\nprint (\"Serving at port\", PORT)\nhttpd.serve_forever()\n\"\"\"\n```\n\n## Images, pictures\n\n\n```python\npctrs = '''\nfrom PIL import Image\nfrom resizeimage import resizeimage\n\n## Show image\n\nax1.imshow(img)\n\n## Resize\n\nimg = Image.open(im)\nimg = resizeimage.resize_contain(img, [100,100]) # nebo\nimg = img.resize((1250,890),Image.ANTIALIAS) # antialias\n\n## Save\n\nimg.save(soubor[0]+'_resized_'+soubor, img.format)\nimg.close()\n\n## Convert to black and white\n\nimg = img.convert('L') #P\u0159evede na \u010dernob\u00edl\u00fd\n\n## Convert image to matrix\n\nimg=np.array(img)\n'''\n```\n\n## Mathematics, statistics, linear algebra\n\n!! Matrix and liear algebra operations discussed in Numpy aray section !!\n\n\n```python\n### Display nice math\n\nfrom IPython.display import display, Math, Latex\ndisplay(Math(r'F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx'))\n\n### Square root ###\n\ny = 9**(1/2)  # 3\n\n### Round ###\n\nA = round(5.76543, 2)\n\n### Natural log - e ###\n\nfrom math import e\na = e  # 2.71\n\n# Or\n\nimport numpy as np\na = np.exp(1)\n\n### Modulo ###\n\na = 7 % 3 # => 1\n\n### Power (x on y) ###\n\na = 2**4 # => 16\n\n### Describe - Statistical values of list ###\n\nimport pandas as pd\n\ndf = pd.Series([1, 4, 6, 88])\ndf.describe()\n\n    #    count     4.000000\n    #    mean     24.750000\n    #    std      42.216703\n    #    min       1.000000\n    #    25%       3.250000\n    #    50%       5.000000\n    #    75%      26.500000\n    #    max      88.000000\n    #    dtype: float64\n\n### Statistical values of array\n\nfrom scipy import stats\na = np.array([1, 3, 5, 77])\nstats = stats.describe(a)\n\n## Random\n### Random numbers in normal distribution\n\nimport numpy as np\nran = np.random.randn(3)\n\nq = np.random.randn(3, 4)\n\n    #    [[ 1.33262386 -0.88922967 -0.07056098 0.27340112]\n    #     [ 1.00664965 -0.68443807 0.43801295 -0.35874714]\n    #     [ -0.19289416 -0.42746963 -1.80435223 0.02751727]]\n\n### Random number everytime the same\n\nnp.random.seed(5)\n\nw = np.random.randn(3)  # [ 0.44122749 -0.33087015  2.43077119]\nw = np.random.randn(3)  # [ 0.44122749 -0.33087015  2.43077119]\n\n### Random numbers in normal distribution matrix shape\n\ns = np.random.normal(2, 6, 1000)  # Mu, Sigma,\n\n## Points generation\n\nt = np.linspace(0,20,1000)  # Generate numbers with the same interval (beginning, end, number)\n\nt = np.arange(1, 3, 1)  # 1, 2\nt = np.arange(3)  # 0, 1, 2\n\n### Mean\n\nx = np.array([[10,20,30], [40,50,60]])\nnp.mean(x)\n\n### Standard deviation\n\nstd = np.std(x)\n\n# Or\n\nfrom statistics import stdev\nsample = [1, 2, 3, 4, 5]\nstd = stdev(sample)\n\n### Bins\n\nbins = 10\nbinss = np.histogram(x, bins)  # binss[0] hodnoty binss[1]\n    # original = x = np.array([[10,20,30], [40,50,60]])\n    # binss[0] = counts - [1 0 1 0 1 0 1 0 1 1]\n    # binss[1] = values [10. 15. 20. 25. 30. 35. 40. 45. 50. 55. 60.]\n\n### Cumulative sum\n\ny = np.cumsum(x)\n\n### Derivation\n\nsample = [1, 2, 8, 4, 5]\nz = np.diff(y)\n    # [ 1  6 -4  1]\n\n### Latex dislay\n\n# from IPython.display import display, Math, Latex\n# display(Math(r'F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx'))\n\n\n########################################\n####### Symbolic python - sympy #######\n#######################################\n\nimport sympy as sp\n\n#  Nice display\nsp.init_printing()\n\n# Or\n# Or use sp.pprint()\n\n### Display Latex\n\nsp.latex(x**2)\n\n### Create symbols\n\ns = sp.Symbol(\"s\")\nx, y, z = sp.symbols('x,y,z')\nd, e, f = sp.symbols('d:f')\ninf = sp.oo\n\n### Create one member (fraction) from more members\n\nans = sp.together(1/x + 1/y + 1/z)\n    #   x*y + x*z + y*z\n    #   ---------------\n    #        x*y*z\n\n# Imaginary numbers\nx = 1 + 1 * sp.I\n\n### Expand\n\nans = ((x+y)**2).expand()\n    #    x**2 + 2*x*y + y**2\n\n### Substitute\n\nexpr = sp.cos(x)\nexpr.subs(x, 0) # 1\n\n### Compute string\n\nstr_expr = \"x**2 + 3*x - 1/2\"\nexpr = sp.sympify(str_expr)\n\n### Simplify equation\n\nsimplified = sp.simplify((x**3 + x**2 - x - 1)/(x**2 + 2*x + 1))\n    #    \ud835\udc65\u22121\n\n### Evaluate expression\n\nexpr = sp.sqrt(8)\nexpr.evalf() # 2.82842712474619\n\n### Use numerical evaluation\n\nimport numpy\na = numpy.arange(10)\nexpr = sp.sin(x)\nf = sp.lambdify(x, expr, \"numpy\")\nres = f(a)\n    # [ 0.          0.84147098  0.90929743  0.14112001 -0.7568025  -0.95892427\n    #  -0.2794155   0.6569866   0.98935825  0.41211849]\n\n    ### Combine with numpy\n\ny_vec = numpy.array([N(((x + pi)**2).subs(x, xx)) for xx in x_vec])  # But lambdify is faster\n\n### Solve equation\n\nsolve(x**2 - 1, x)  # [-1, 1]\nsolve([x + y - 1, x - y - 1], [x,y])  # {x:1,y:0}\n\n# Exponential\nfrom mpmath import e\ny = sp.exp(x)\n\n# Matrices\n\nm11, m12, m21, m22 = symbols(\"m11, m12, m21, m22\")\nb1, b2 = symbols(\"b1, b2\")\n\nA = Matrix([[m11, m12],[m21, m22]])\n    #   [ m11    m21\n    #     m12    m22 ]\n\nb = Matrix([[b1], [b2]])\n    #   [ b1\n    #     b2 ]\n\n# Matrix operations\n\nsqr_mat = A**2\nmat_mul = A*b\ndet = A.det()\ninv = A.inv()\n\n### Fast fourier transform\n\nfrom numpy.fft import fft, fftfreq, ifft\nimport numpy as np\n\nt = np.arange(0, 10, 0.1)\ny = np.sin(t)\n\nffty = fft(y)\n\nreal_ffty = ffty.real\nimag_ffty = ffty.imag\n\nfreqs = fftfreq(N, dt)  # Frequentions assigned to values - 0, 0.1, 0.2...\n\n### Sympy plotting\n\nfrom sympy.plotting import plot\np1 = plot(sp.exp(t))\n\n\n######################################\n####### Differential equations #######\n######################################\n\nimport sympy as sp\nf = sp.Function('f')\nx = sp.Symbol('x')\neq = f(x).diff(x, x) + f(x)\nres = sp.dsolve(eq, f(x))\n\n###########################\n####### Integration #######\n###########################\n\n### Unbounded integral\n\nimport sympy as sp\nfrom sympy import exp as e\nx = sp.Symbol(\"x\")\nf = e(-x)\ndisp(\"f=\",f)\nintf = sp.integrate(f)\ndisp(\"\\int \" + dfrac(f)+\"dx=\",intf) # po \\int musim byt mezera\n\n### Bounded integral\n\nintf=sp.integrate(f,(x,0,1))\ndisp(\"\\int_0^1\" + dfrac(f)+\" dx=\",intf.evalf())\n\n###########################\n####### Correlation #######\n###########################\n\n### Correlation matrix - values\n\nimport pandas as pd\ndf = pd.DataFrame([[1, 2, 3], [4, 5, 9], [7, 8, 78]], columns=['one', 'two', 'three'])\nx_cor = df.corr()\n\n    #               one      two    three\n    #    one    1.00000  1.00000  0.89977\n    #    two    1.00000  1.00000  0.89977\n    #    three  0.89977  0.89977  1.00000\n\n### Correlation matrix - plot\n\n# a = pd.plotting.scatter_matrix(df, figsize=(16,12), alpha=0.3)\n\n### Correlation (Pearson corr. matrix)\n\nimport matplotlib.pyplot as plt\nscoreTable = df.corr(method='pearson')\ndf.corr(method='pearson').style.format(\"{:.2}\").background_gradient(cmap=plt.get_cmap('coolwarm'), axis=1)\n\n### Correlation coefficent\n\nar = np.array([1, 2, 4, 5, 9])\nar2 = np.array([7, 8, 78, 34, 2])\na = np.corrcoef(ar, ar2)\n\n    #    [[ 1.        -0.0475504]\n    #     [-0.0475504  1.       ]]\n\n##########################\n####### Statistics #######\n##########################\n\n### Create combinations\n\nfrom scipy.special import binom\na = binom(5,2)\n\n### Test of normal distribution\n\nfrom statsmodels.stats.stattools import jarque_bera\nresiduals = [1, 3, 5, 2, 4]\nscore, pvalue, _, _ = jarque_bera(residuals)\nif pvalue < 0.10:\n    print ('We have reason to suspect the residuals are not normally distributed.')\nelse:\n    print ('The residuals seem normally distributed.')\n\n# Machine learning\n\n#################################################\n####### Standardization and normalization #######\n#################################################\n\n### Standardization: mean = 0 and std = 1\n\nfrom sklearn import preprocessing\nimport numpy as np\nX_train = np.array([[ 1., -1.,  2.],\n                    [ 2.,  0.,  0.],\n                    [ 0.,  1., -1.]])\n\nscaler = preprocessing.StandardScaler()\n\nfitted_scaler = scaler.fit(X_train)\nscaled = fitted_scaler.transform(X_train)\n\n    #    [[ 0.  ..., -1.22...,  1.33...],\n    #     [ 1.22...,  0.  ..., -0.26...],\n    #     [-1.22...,  1.22..., -1.06...]]\n\n# inverse transformation\nback = fitted_scaler.inverse_transform(scaled)\n\n### Normalization (-1,1)\n# Just replace one row from standard scaler\nscaler = preprocessing.MinMaxScaler(feature_range=(0, 1))\n\n### The same way you can use preprocessing.RobustScaler, that is not as much influenced by outliers !!\n```\n\n## Signal processing and controll\n\n\n```python\n## Signal\n\nimport scipy.signal as sig\ny = sg.sawtooth(2*pi/100*t,0.5)  # Create sawtooth signal\n\n### Chirp signal\nt = np.linspace(0, 10, 5001)\nw = sig.chirp(t, f0=6, f1=1, t1=10, method='linear') # (t, f0, t1, f1)  # Changing frequency\n\n## Hanning window\n\nw = hanning(N)\n\n## Tuckey window\n\nw = sig.tukey(N)\n\n## Fourier transform\n\ndt = 1./1024\nt = np.arange(0,2,dt)\nN = len(t)\ny = sig.sawtooth(2*np.pi/T1*t,0.5)\n\nfreq = np.fft.fftfreq(N,dt)  # Return frequencies\nffty = np.fft.fft(y)\nrffty = np.real(ffty)  # Real part\niffty = np.imag(ffty)  # Imaginary part\n\n## Inverse Fourier transform\n\ny_back = np.fft.ifft(ffty)\n\n## Power spectral density\n\nPSD = (abs(ffty)**2)/N\n\n## Hilbert transform - Envelope, phase, frequency\n\nanalytic_signal = hilbert(signal)\namplitude_envelope = np.abs(analytic_signal)\ninstantaneous_phase = np.unwrap(np.angle(analytic_signal))\ninstantaneous_frequency = (np.diff(instantaneous_phase) / (2.0*np.pi) * fs)\n\n### Filtering\n\nimport scipy.signal as sig\nfrom scipy.signal import butter,filtfilt\n\nt = np.linspace(0, 10, 501)\nw = sig.chirp(t, f0=6, f1=0.1, t1=10, method='linear') # (t, f0, t1, f1)\n\nWn = 0.1  # zkuste pozorovat efekt nasobici konstanty na cinnost filtru\nfilter_order = 2\nb, a = butter(filter_order, Wn, 'high', analog=False)  #Matlab-style filter design\n\nx_dem = sig.lfilter(b, a, w)\n\n# Or\nx_dem = filtfilt(b, a, w)  # Apply  filtr (forward and backward)\n\n# You can use scipy or you can use controll\n\n####################\n##### Controll #####\n####################\n\n## State-space representation\n\nA = [[0. , 1.], [-1., -1.]]\nB = [[0.], [1.]]\nC = [1. , 0.]\nD = 0.\n\nimport control as ct\n\nsys = ct.ss(A , B, C, D)\n\n\n## Transfer function\n\ng = ct.tf(1 ,[1 ,1, 1])  # Or ct.tf(sys)\n\n    #        1\n    #   -----------\n    #   s^2 + s + 1\n\nsys = ct.ss(g)  # Convert back from transfer to state space\n\n## Convert from continuous to discrete\n\ng = ct.tf(1, [1, 1, 1])\ngd = ct.c2d (g, 0.01)\n\n    #   4.983e-05 z + 4.967e-05\n    #   -----------------------\n    #     z^2 - 1.99 z + 0.99\n\n## Interconnect systems\n\n### Parallel\n\n\n    #      2 s + 3\n    #    -------------\n    #    s^2 + 3 s + 2\n\n\n#################\n##### Scipy #####\n#################\n\n# You have to use float here. Not working for int...\n\nfrom scipy import signal\n\nsys = signal.StateSpace(A, B, C, D)\n\n### Step response\n\nt1, y1 = signal.step(sys)\n\n################\n### Simulate ###\n################\n\nt = np.linspace(0, 100, 101)\nu = np.zeros(len(t))\nu[10:50] = 1.0;  u[50:] = 2.0\n\nt3, y3, x3 = signal.lsim(sys, u, t)\n\nimport numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\n\n# function that returns dy/dt\ndef model(y,t):\n    k = 0.3\n    dydt = -k * y\n    return dydt\n\n# initial condition\ny0 = 5\n\n# time points\nt = np.linspace(0,20)\n\n# solve ODE\ny = odeint(model,y0,t)\n\n# plot results\nplt.plot(t,y)\nplt.xlabel('time')\nplt.ylabel('y(t)')\nplt.show()\n\n### Simulate with time dependent input\n\ndef fdxdt(x,t,u,Omega,eta,b0,b1):    # x=[x1 x2 ... xn]\n        dx1dt=-Omega0**2*x[1]-b0*u\n        dx2dt=-2*eta*Omega0*x[1]-b1*u+x[0]\n        return(dx1dt,dx2dt)\n\n    dt=.21  #[sec]\n    t=arange(0,50,dt) ; N=len(t)  # delka dat\n    Npul=int(N/2)   #konverze na integer\n\n    u=sin(2*pi/10*t) ; u[Npul+1:]=sign(u[Npul+1:])\n\n    u=u*1\n\n    figure(figsize=(12,4));grid()\n    plot(t,u,'-*',label=\"u(t)\");xlabel(\"t\");legend();title(\"$Vstup \\ u(t) \\ se \\ meni  \\ se \\\n            \\ vzorkovaci \\ periodou \\ \\Delta t $=\"+str(dt) +\" [sec] \\n\")\n    show()\n\n    from scipy.integrate import odeint\n\n    Omega0=10  ;  eta=.1  ;   b0=Omega0**2  ;  b1=0\n\n    #===============================\n\n    y=zeros(N)\n    x10=0 ; x20=0  # poc. podm\n\n    x0=[x10,x20]\n\n    for i in range(0,N-1):\n        tt=[t[i],t[i+1]]  # [t1 t2]\n        x=odeint(fdxdt,x0,t,(u[i],Omega0,eta,b0,b1)) #returns x=[ [x1(t1) x2(t1)] [x1(t2) x2(t2)]]\n    #    x=odeint(fdxdt,x0,tt,args=(u[i],)) # <-- pokud je jen jeden extra argument, musi se tak\n        y[i+1]=-x[1,1]\n        x0=x[1,:]  # jako nove poc. podm pro dalsi integraci\n\n    figure(figsize=(14,6))\n    grid()\n    plot(t,y,\"-*\",label=\"y(t)...simulace scipy.integrate.odeint\"),xlabel(\"t [sec]\"),legend()\n    show()\n```\n\n## Database\n\n### pyodbc, sqlalchemy\n\n**Read**\n\n\n```python\nserver = 'SERVER={};'.format(server)\ndatabase = 'DATABASE={};'.format(database)\nsql_params = r'DRIVER={ODBC Driver 13 for SQL Server};' + server + database + 'Trusted_Connection=yes;'\n\nsql_conn = pyodbc.connect(sql_params)\ndf = pd.read_sql(query, sql_conn)\n```\n\n**Write**\n\nfrom sqlalchemy import create_engine\nimport urllib\n\nparams = urllib.parse.quote_plus(r'DRIVER={driver};SERVER={server};DATABASE={database};Trusted_Connection=yes'.format(driver=r'{SQL Server}', server=server, database=database))\nconn_str = 'mssql+pyodbc:///?odbc_connect={}'.format(params)\n\nengine = create_engine(conn_str)\ndataframe_to_sql.to_sql(name='FactProduction', con=engine, schema='Stage', if_exists='append', index=False)\n\n## GUI\n\n**VUE and EEl (Electron JS like library)**\n\nYou can use mypythontools pyvueeel for building an app with graphical interface. It contains working examples.\n\n## Misc\n\n### Jupyter\n\n\n```python\n\"\"\"\n# !  jupyter kernelspec list # Uk\u00e1\u017ee seznam kernel\u016f\n# !  jupyter kernelspec uninstall nazev # Odinstaluje kernel\n## Install jupyter extensions\n\npip install jupyter_contrib_nbextensions && jupyter contrib nbextension install\n\n# Test if running on jupyter\n\nif 'ipykernel' in sys.modules:\n    print('jup')\n\n# Or\n\n# if hasattr(builtins, '__IPYTHON__'):\n#     print('IPython')\n# else:\n#     print('Nope')\n\n## If jupyter and run from normal python\n\ntry:\n    __IPYTHON__\n\n    from IPython.terminal.embed import InteractiveShellEmbed\n    ipshell = InteractiveShellEmbed()\n    ipshell.dummy_mode = True\n    ipshell.magic(\"%load_ext autoreload\")\n    ipshell.magic(\"%autoreload\")\n\nexcept NameError:\n    print('No Jupyter')\n\n## Run ipython in normal python\n\nfrom IPython.terminal.embed import InteractiveShellEmbed\n\nipshell = InteractiveShellEmbed()\nipshell.dummy_mode = True\nipshell.magic(\"%timeit abs(-42)\");\n\n## Autoreload\n\n#Reload all modules imported with %aimport every time before executing the Python code typed, so it is not necessary to reload kernel everytime some other file changed or new library wa installed\n\n%load_ext autoreload\n%autoreload  # Reload all modules (except those excluded by %aimport) automatically now.\n%autoreload 0  # Disable automatic reloading.\n%autoreload 1  # Reload all modules imported with %aimport every time before executing the Python code typed.\n%autoreload 2  # Reload all modules (except those excluded by %aimport) every time before executing the Python code typed.\n%aimport  # List modules which are to be automatically imported or not to be imported.\n%aimport foo  # Import module \u2018foo\u2019 and mark it to be autoreloaded for %autoreload 1\n%aimport -foo  # Mark module \u2018foo\u2019 to not be autoreloaded.\n\n\n## Link\n\n\u201a''\n[Link name](<https://www.youtube.com/>)\n\u201a''\n\n## Image\n\n\u201a''\n\n\u201a''\n\n## Youtube\n\n    # from IPython.display import YouTubeVideo\n    # YouTubeVideo('7VeUPuFGJHk')\n\n## Show all images from folder\n\n    import os\n    from IPython.display import display, Image\n    names = [f for f in os.listdir('../images/ml_demonstrations/') if f.endswith('.png')]\n    for name in names[:5]:\n        display(Image('../images/ml_demonstrations/' + name, width=100))\n\n## Jupyter themes\n\n    pip install jupyterthemes\n    jt -t monokai -T\n\n    # Deactivate\n    jt -r\n\n## Matplotlib widget interactive backend\n\n    %matplotlib widget\n    from matplotlib import pyplot as plt\n    fig, ax = plt.subplots()\n    ax.plot([1,2,3], [4,3,2])\n    # fig.show() is not necessary\n\n    # If not working in jupyterlab, use in terminal\n    #     jupyter labextension install @jupyter-widgets/jupyterlab-manager\n\n    # Instead of magic you can use\n\n    import matplotlib\n    matplotlib.use('module://ipympl.backend_nbagg')\n\n## Dark background of matplotlib for dark themes\n\n    # ! pip install jupyterthemes\n\n    In ~/.ipython/profile_default/startup  create startup.py file with\n\n    import matplotlib.pyplot as plt\n    from jupyterthemes import jtplot\n    jtplot.style(theme='monokai', context='notebook', ticks=True, grid=False)\n\n    # Then in extensions use theme-darcula\n    # And in to ~\\AppcmdData\\Local\\Programs\\Python\\Python37\\Lib\\site-packages\\jupyterthemes\\styles\\monokai.less\n    # Change on\n    /* jtplot figure style */\n    @axisFace:              #2b2b2b;\n    @figureFace:            #2b2b2b;\n\n## Ipywidgets\n\n## Extensions\n\npip install jupyter_contrib_nbextensions\n\njupyter contrib nbextension install --user\n\n### Enable extension (e.g. rise)\njupyter nbextension enable --py rise\n\"\"\"\n```\n\n# Performance\n\n## Profiling\n\n### Line profiling\n\nSimplest and probably best way is to use jupyter, extensions and magic.\nSimple example is in project-starter test profiling.ipynb [here](https://github.com/Malachov/mypythontools/tree/master/content/project-starter/tests)\n\nIf you want to use just python, you can\n\n\n```python\nimport line_profiler\n\ndef hoj():\n    a = 2\n    b = [1,2,3]\n\n    return a * b\n\nlp = line_profiler.LineProfiler()\nlp_wrapper = lp(hoj)()\nlp.print_stats()\n\n# If inner function\n\nfrom line_profiler import LineProfiler\nimport random\n\ndef do_other_stuff(numbers):\n    s = sum(numbers)\n\ndef do_stuff(numbers):\n    do_other_stuff(numbers)\n    l = [numbers[i]/43 for i in range(len(numbers))]\n    m = ['hello'+str(numbers[i]) for i in range(len(numbers))]\n\nnumbers = [random.randint(1,100) for i in range(1000)]\nlp = LineProfiler()\nlp.add_function(do_other_stuff)   # add additional function to profile\nlp_wrapper = lp(do_stuff)\nlp_wrapper(numbers)\nlp.print_stats()\n```\n\n**Other profiling option**\n\n\n```python\n# !  pip install snakeviz\n# !  python -m cProfile -o program.prof my_program.py\n# !  snakeviz program.prof\n```\n\n**Show memory profile to file**\n\n\n```python\nfrom memory_profiler import profile\n\ndef fu(a):\n    print('content')\n\nmemory_profile = open('memory_profiler.log','w+')\nprofile_wrapped_function = profile(fu, stream=memory_profile)\nprofile_wrapped_function()\n\nmemory_profile.seek(0)\nprint(memory_profile.read())  # Or save to variable\nmemory_profile.close()\n```\n\n## Garbage collector\n\n**Force to empty memory**\n\n\n```python\nimport gc\ngc.collect()\n```\n\n## Threading\n\n\n```python\nfrom concurrent.futures import ThreadPoolExecutor\n\nexecutor = ThreadPoolExecutor(max_workers=3)\nexecutor.submit(myFunction())\n\n# Or use\nwith ThreadPoolExecutor(max_workers=3) as executor:\n        future = executor.submit(task, (2))\n        future = executor.submit(task, (3))\n        future = executor.submit(task, (4))\n```\n\n## Max execution time function\n\n\n```python\nimport time, sys\n\ndef watchdog(timeout, code, *args, **kwargs):\n    \"Time-limited execution.\"\n    def tracer(frame, event, arg, start=time.time()):\n        \"Helper.\"\n        now = time.time()\n        if now > start + timeout:\n            raise WatchdogTimeoutError(start, now)\n        return tracer if event == \"call\" else None\n\n    old_tracer = sys.gettrace()\n    try:\n        sys.settrace(tracer)\n        code(*args, **kwargs)\n    finally:\n        sys.settrace(old_tracer)\n\ndef func(a):\n    return 1 + a\n\nwatchdog(5, func, 0.1) # First element is time limit - Last argument 0.1 are *args and **kwargs\n\n# Or\nmx_ex = '''\nfrom contextlib import contextmanager\nimport threading\nimport _thread\n\nclass TimeoutException(Exception):\n    def __init__(self, msg=''):\n        self.msg = msg\n\n@contextmanager\ndef time_limit(seconds, msg=''):\n    timer = threading.Timer(seconds, lambda: _thread.interrupt_main())\n    timer.start()\n    try:\n        yield\n    except KeyboardInterrupt:\n        raise TimeoutException(\"Timed out for operation {}\".format(msg))\n    finally:\n        # if the acti   on ends in specified time, timer is canceled\n        timer.cancel()\n\nimport time\nwith time_limit(5, 'slee'):\n    time.sleep(10)\n'''\n```\n\n## Numba\n\n\n```python\nimport numba as nb\n\n@nb.jit(parallel=True)  # Or use  parallel=True\ndef func():\n    return 1\n\n# More options possible\n@nb.njit()\ndef func():\n    return 1\n\n# Or\n\n@nb.jit(nopython=True)  # Or use  parallel=True, nogil=True, cache=True\ndef func():\n    return 1\n\n# Or\n\n@nb.vectorize\ndef function(a, b):\n    return 1\n\n# Or direct data formats\n\nimport numba as nb\n@nb.jit(nb.int32(nb.int32, nb.int32))\ndef function(a, b):\n    return a + b\n\n### Get numba dtype from other\n\nnumba.typeof(np.empty(3))\narray(float64, 1d, C)\n\n### Evaluate chunk sizes\n\n    i = numba.cuda.grid(1)\n    while i < x.size:\n        # Do something\n        i += numba.cuda.grid(1)\n\n### Cuda in Numba ###\n\nimport math\nimport numpy as np\nfrom numba import cuda\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nlen(cuda.gpus)  # 1\n\ncuda.gpus[0].name  # b'GeForce GTX 980M'\n\n@cuda.jit\ndef mandelbrot_numba(m, iterations):\n    # Matrix index.\n    i, j = cuda.grid(2)\n    size = m.shape[0]\n    # Skip threads outside the matrix.\n    if i >= size or j >= size:\n        return\n    # Run the simulation.\n    c = (-2 + 3. / size * j +\n        1j * (1.5 - 3. / size * i))\n    z = 0\n    for n in range(iterations):\n        if abs(z) <= 10:\n            z = z * z + c\n            m[i, j] = n\n        else:\n            break\n\n    size = 40\n    iterations = 5\n\n    m = np.zeros((size, size))\n\n    # 16x16 threads per block.\n    bs = 16\n    # Number of blocks in the grid.\n    bpg = math.ceil(size / bs)\n    # We prepare the GPU function.\n    f = mandelbrot_numba[(bpg, bpg), (bs, bs)]\n\n    f(m, iterations)\n\n# Or\n\nfrom numba import cuda\n@cuda.jit(device=True)\ndef function(a, b):\n    return a + b\n```\n\n## Dask\n\n\n```python\ndsk = '''\nimport dask\n\n@dask.delayed\ndef inc(x):\n    return x + 1\n\n@dask.delayed\ndef double(x):\n    return x + 2\n\n@dask.delayed\ndef add(x, y):\n    return x + y\n\ndata = [1, 2, 3, 4, 5]\n\noutput = []\nfor x in data:\n    a = inc(x)\n    b = double(x)\n    c = add(a, b)\n    output.append(c)\n\ntotal = dask.delayed(sum)(output)\n# maybe add    total.compute()\n'''\n```\n\n**Dask formats**\n\n\n```python\ndsk_frmts = '''\nimport pandas as pd\nimport dask.array as da\nimport dask.dataframe as dd\nx = da.random.random((20, 20), chunks=(10, 10))\nres = x.dot(x.T).sum()\nres.compute()\n\n# Dataframes implement the Pandas API\n\ndf = pd.DataFrame([[1, 2, 3], [1, 5, 3], [5, 6, 7]], columns = ['one', 'two', 'three'])\ndfdsk = dd.from_pandas(df, npartitions=1)\n\n# Or dd.read_csv('adress')\n\nfrom dask_ml.linear_model import LogisticRegression  # Dask-ML implements the Scikit-Learn API\nlr = LogisticRegression()\nlr.fit(dfdsk, dfdsk)\n\n## Show task structure\n\n.visualize()\n'''\n```\n\n# Miscellaneous\n\n## Push own library to PyPi\n\nMypythontools [deploy](https://mypythontools.readthedocs.io/mypythontools.deploy.html) module can be use for this purpose (it's usually one part of bigger pipeline).\n\n## CI/CD\n\n**mypythontools.utils**\n\nCheck example on mypythontools [deploy module](https://github.com/Malachov/mypythontools/blob/master/mypythontools/utils.py)\n\n**Travis CI - Automatic testing and deploying**\n\nCheck example on mypythontools [project-starter](https://github.com/Malachov/mypythontools/tree/master/content/project-starter/.travis.yml)\n\n## Create documentation - Sphinx\n\n\n```python\n\npip install sphinx\n\n# And\npip install alabaster\n\n# Or\npip install sphinx_rtd_theme\n\n# And if you want to use markdown\npip install recommonmark\npip install sphinxcontrib-napoleon\n\n# Create documentation files\n\nsphinx-quickstart\n\n# Use separate build and source: yes\n```\n\nFill in the `config.py` and `index.rst`\n\nYou can use mypythontools [project-starterexample](https://github.com/Malachov/mypythontools/tree/master/content/project-starter/docs/source)\n\nYou can build it locally with\n\n\n```python\nmake html\n```\n\nOr you can make account on [readthedocs](https://readthedocs.org/) - It's free.\nAnd the documentation will be automatically made on every github push to master.\n\n## Snippets - examples\n\n### Measure time\n\n\n```python\n\"\"\"\nimport timeit\nimport functools\n\ndef func(*args):\n    a = 1\n    return a\nt = timeit.Timer('''\nimport numpy as np\na = 12\n''', 'gc.enable()')\nprint(t.timeit(3))  # 3 - measure three times\n\n# Or you can use\nt = timeit.timeit(func)\n\n# Measure time of function with inputs\nt = timeit.Timer(functools.partial(func, (1, 2)))\nprint (t.timeit(20))\n\"\"\"\n```\n\n### Show bytecode\n\n\n```python\nimport dis\ndis.dis(\"dict()\")\n\n    #              0 LOAD_NAME                0 (dict)\n    #              2 CALL_FUNCTION            0\n    #              4 RETURN_VALUE\n```\n\n### Encoding JSON with Python\n\n\n```python\nimport json\n\ndata =  {\n            'a':  0,\n            'b':  9.6,\n            'c':  \"Hello World\",\n            'd':  {\n                    'a':  4\n            }\n}\n\njson_data = json.dumps(data)\n\n# Notice how the keys are not sorted by default, you would have to add the sort_keys=True\n```\n", "meta": {"hexsha": "849ddaf4cd3a4265db6600a850d24202c98e4651", "size": 170074, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Python/notebook.ipynb", "max_stars_repo_name": "Malachov/Awesome-python-md-ipynb-documentation-cheatsheet", "max_stars_repo_head_hexsha": "87c2598957e3d44c38c534757187549cabac22a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python/notebook.ipynb", "max_issues_repo_name": "Malachov/Awesome-python-md-ipynb-documentation-cheatsheet", "max_issues_repo_head_hexsha": "87c2598957e3d44c38c534757187549cabac22a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/notebook.ipynb", "max_forks_repo_name": "Malachov/Awesome-python-md-ipynb-documentation-cheatsheet", "max_forks_repo_head_hexsha": "87c2598957e3d44c38c534757187549cabac22a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9445500634, "max_line_length": 551, "alphanum_fraction": 0.4788327434, "converted": true, "num_tokens": 31034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09534946489910949, "lm_q2_score": 0.08151975318543449, "lm_q1q2_score": 0.007772864844938655}}
{"text": "# Rich Output\n\nIn Python, objects can declare their textual representation using the `__repr__` method.  IPython expands on this idea and allows objects to declare other, rich representations including:\n\n* HTML\n* JSON\n* PNG\n* JPEG\n* SVG\n* LaTeX\n\nA single object can declare some or all of these representations; all are handled by IPython's *display system*. This Notebook shows how you can use this display system to incorporate a broad range of content into your Notebooks.\n\n## Basic display imports\n\nThe `display` function is a general purpose tool for displaying different representations of objects. Think of it as `print` for these rich representations.\n\n\n```python\nfrom IPython.display import display\n```\n\nA few points:\n\n* Calling `display` on an object will send **all** possible representations to the Notebook.\n* These representations are stored in the Notebook document.\n* In general the Notebook will use the richest available representation.\n\nIf you want to display a particular representation, there are specific functions for that:\n\n\n```python\nfrom IPython.display import (\n    display_pretty, display_html, display_jpeg,\n    display_png, display_json, display_latex, display_svg\n)\n```\n\n## Images\n\nTo work with images (JPEG, PNG) use the `Image` class.\n\n\n```python\nfrom IPython.display import Image\n```\n\n\n```python\nls ../imagens/\n```\n\n    cat_tinted_imshow.png                  numpy_3d_array.svg\r\n    hello_python.png                       numpy_background.jpg\r\n    indexa\u00e7\u00e3o_b\u00e1sica.svg                   python_background.png\r\n    indexing.svg                           python_logo.svg\r\n    install_background.jpg                 question_background.jpeg\r\n    ipython_background.png                 sage_math_cloud.png\r\n    ipython_tab_complete2.png              scientific_stack.png\r\n    ipython_tab_complete.png               scientific_stack.svg\r\n    jupyter_dashboard.png                  sine_cosine_plot.png\r\n    jupyter_notebook_background.png        sine_cosine_subplot.png\r\n    \u001b[0m\u001b[01;32mminiconda_windows_adicionar_path.png\u001b[0m*  sine_plot.png\r\n    numpy_3d_array_manual.svg\r\n\n\n\n```python\ni = Image(filename='../imagens/python_background.png')\n```\n\nReturning an `Image` object from an expression will automatically display it:\n\n\n```python\ni\n```\n\nOr you can pass an object with a rich representation to `display`:\n\n\n```python\ndisplay(i)\n```\n\nAn image can also be displayed from raw data or a URL.\n\n\n```python\nImage(url='http://python.org/images/python-logo.gif')\n```\n\n\n\n\n\n\n\n\nSVG images are also supported out of the box.\n\n\n```python\nfrom IPython.display import SVG\nSVG(filename='../imagens/python_logo.svg')\n```\n\n\n\n\n    \n\n    \n\n\n\n### Embedded vs non-embedded Images\n\nBy default, image data is embedded in the notebook document so that the images can be viewed offline. However it is also possible to tell the `Image` class to only store a *link* to the image. Let's see how this works using a webcam at Berkeley.\n\n\n```python\nfrom IPython.display import Image\nimg_url = 'http://www.lawrencehallofscience.org/static/scienceview/scienceview.berkeley.edu/html/view/view_assets/images/newview.jpg'\n\n# by default Image data are embedded\nEmbed      = Image(img_url)\n\n# if kwarg `url` is given, the embedding is assumed to be false\nSoftLinked = Image(url=img_url)\n\n# In each case, embed can be specified explicitly with the `embed` kwarg\n# ForceEmbed = Image(url=img_url, embed=True)\n```\n\nHere is the embedded version. Note that this image was pulled from the webcam when this code cell was originally run and stored in the Notebook. Unless we rerun this cell, this is not todays image.\n\n\n```python\nEmbed\n```\n\n\n\n\n    \n\n    \n\n\n\nHere is today's image from same webcam at Berkeley, (refreshed every minutes, if you reload the notebook), visible only with an active internet connection, that should be different from the previous one. Notebooks saved with this kind of image will be smaller and always reflect the current version of the source, but the image won't display offline.\n\n\n```python\nSoftLinked\n```\n\n\n\n\n\n\n\n\nOf course, if you re-run this Notebook, the two images will be the same again.\n\n## HTML\n\nPython objects can declare HTML representations that will be displayed in the Notebook. If you have some HTML you want to display, simply use the `HTML` class.\n\n\n```python\nfrom IPython.display import HTML\n```\n\n\n```python\ns = \"\"\"<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\"\"\"\n```\n\n\n```python\nh = HTML(s)\n```\n\n\n```python\ndisplay(h)\n```\n\n\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n\n\nYou can also use the `%%html` cell magic to accomplish the same thing.\n\n\n```python\n%%html\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n```\n\n\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n\n\n## JavaScript\n\nThe Notebook also enables objects to declare a JavaScript representation. At first, this may seem odd as  output is inherently visual and JavaScript is a programming language. However, this opens the door for rich output that leverages the full power of JavaScript and associated libraries such as [d3.js](http://d3js.org) for output.\n\n\n```python\nfrom IPython.display import Javascript\n```\n\nPass a string of JavaScript source code to the `JavaScript` object and then display it.\n\n\n```python\njs = Javascript('alert(\"hi\")');\n```\n\n\n```python\ndisplay(js)\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\nThe same thing can be accomplished using the `%%javascript` cell magic:\n\n\n```javascript\n%%javascript\n\nalert(\"hi\");\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\nHere is a more complicated example that loads `d3.js` from a CDN, uses the `%%html` magic to load CSS styles onto the page and then runs ones of the `d3.js` examples.\n\n\n```python\nJavascript(\n    \"\"\"$.getScript('https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.1/d3.js')\"\"\"\n)\n```\n\n\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n```python\n%%html\n<style type=\"text/css\">\n\ncircle {\n  fill: rgb(31, 119, 180);\n  fill-opacity: .25;\n  stroke: rgb(31, 119, 180);\n  stroke-width: 1px;\n}\n\n.leaf circle {\n  fill: #ff7f0e;\n  fill-opacity: 1;\n}\n\ntext {\n  font: 10px sans-serif;\n}\n\n</style>\n```\n\n\n<style type=\"text/css\">\n\ncircle {\n  fill: rgb(31, 119, 180);\n  fill-opacity: .25;\n  stroke: rgb(31, 119, 180);\n  stroke-width: 1px;\n}\n\n.leaf circle {\n  fill: #ff7f0e;\n  fill-opacity: 1;\n}\n\ntext {\n  font: 10px sans-serif;\n}\n\n</style>\n\n\n\n```javascript\n%%javascript\n\n// element is the jQuery element we will append to\nvar e = element.get(0);\n    \nvar diameter = 600,\n    format = d3.format(\",d\");\n\nvar pack = d3.layout.pack()\n    .size([diameter - 4, diameter - 4])\n    .value(function(d) { return d.size; });\n\nvar svg = d3.select(e).append(\"svg\")\n    .attr(\"width\", diameter)\n    .attr(\"height\", diameter)\n  .append(\"g\")\n    .attr(\"transform\", \"translate(2,2)\");\n\nd3.json(\"data/flare.json\", function(error, root) {\n  var node = svg.datum(root).selectAll(\".node\")\n      .data(pack.nodes)\n    .enter().append(\"g\")\n      .attr(\"class\", function(d) { return d.children ? \"node\" : \"leaf node\"; })\n      .attr(\"transform\", function(d) { return \"translate(\" + d.x + \",\" + d.y + \")\"; });\n\n  node.append(\"title\")\n      .text(function(d) { return d.name + (d.children ? \"\" : \": \" + format(d.size)); });\n\n  node.append(\"circle\")\n      .attr(\"r\", function(d) { return d.r; });\n\n  node.filter(function(d) { return !d.children; }).append(\"text\")\n      .attr(\"dy\", \".3em\")\n      .style(\"text-anchor\", \"middle\")\n      .text(function(d) { return d.name.substring(0, d.r / 3); });\n});\n\nd3.select(self.frameElement).style(\"height\", diameter + \"px\");\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n## LaTeX\n\nThe IPython display system also has builtin support for the display of mathematical expressions typeset in LaTeX, which is rendered in the browser using [MathJax](http://mathjax.org).\n\nYou can pass raw LaTeX test as a string to the `Math` object:\n\n\n```python\nfrom IPython.display import Math\nMath(r'F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx')\n```\n\n\n\n\n$$F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx$$\n\n\n\nWith the `Latex` class, you have to include the delimiters yourself.  This allows you to use other LaTeX modes such as `eqnarray`:\n\n\n```python\nfrom IPython.display import Latex\nLatex(r\"\"\"\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\"\"\")\n```\n\n\n\n\n\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\n\n\n\nOr you can enter LaTeX directly with the `%%latex` cell magic:\n\n\n```latex\n%%latex\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n```\n\n\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n\n\n## Audio\n\nIPython makes it easy to work with sounds interactively. The `Audio` display class allows you to create an audio control that is embedded in the Notebook. The interface is analogous to the interface of the `Image` display class. All audio formats supported by the browser can be used. Note that no single format is presently supported in all browsers.\n\n\n```python\nfrom IPython.display import Audio\nAudio(url=\"http://www.nch.com.au/acm/8k16bitpcm.wav\")\n```\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"http://www.nch.com.au/acm/8k16bitpcm.wav\" type=\"audio/x-wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\nA NumPy array can be auralized automatically. The `Audio` class normalizes and encodes the data and embeds the resulting audio in the Notebook.\n\nFor instance, when two sine waves with almost the same frequency are superimposed a phenomena known as [beats](https://en.wikipedia.org/wiki/Beat_%28acoustics%29) occur. This can be auralised as follows:\n\n\n```python\nimport numpy as np\nmax_time = 3\nf1 = 220.0\nf2 = 224.0\nrate = 8000.0\nL = 3\ntimes = np.linspace(0,L,rate*L)\nsignal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times)\n\nAudio(data=signal, rate=rate)\n```\n\n    /home/darlan/.virtualenvs/pyphysim/lib/python3.5/site-packages/ipykernel/__main__.py:7: DeprecationWarning: object of type <class 'float'> cannot be safely interpreted as an integer.\n\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"data:audio/wav;base64,UklGRqS7AABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YYC7AAAAADUWvSvyPzdS/WHKbjt4Bn7+fxV+WXj3bjhifVJDQBYslBZiAC/qpdRswCGuU557kf2HJIIcgPWBoIfykKKdTa15v5rTEuk7/2kV8CopP3ZRSmEqbrJ3mH2vf+Z9TXgNb3Bi11K9QK0sQxcmAQPrhNVPwQOvLZ9IkreIxYKggFiC34cLkZOdFq0bvxbTbeh4/o0UASosPnNQSGAwbcd2w3z2fk9923fGblZi7FL/QBwt3hfoAefrg9ZlwiawVqBuk9OJzoOOgSSDg4iAkdadJa31vrvS3ue5/aIT8Sj/PDBP+F7da3t1h3vUfU98BncibuhhuVIJQWQtYRilAtjso9eqw4mxzKHtlE+LPYXkgleEiolTkm6ee60Hv4jSZuf//KsSwyeiO65NXF0zas9z5nlJfOh6zXUhbSdhPlLaQIItzBhbA9Xt39gexSmzjqPCliuNEYeihPKF9YqDk1mfGq5Uv3/SCOdN/KkReCYYOvBLd1szaMVx4HdYehp5MXTDaxNgfFFwQHUtHRkJBNvuN9q9xgW1l6XsmGOPR4nGhvKHwowPlZegAa/bv6LSxOak+58QFCVkOPhJSVnhZV9veXUCeOh2MnIIaqpecVDLPzwtUxmsBOjvp9uFyBm356dmm/aR3otOiVeK8Y73limiMLCewPHSneYG+48PmSOINslH11Y+Y6BssnJJdVF002/yZ+5cHU/rPtYsbBlEBfvwLd11ymO5e6ownuGU1I44jB+NgZE6mQ+kqLGcwW7Tk+Z1+noOCCKGNGVFI1ROYIppj28vcllxFG2CZeBagU3PPUMsZxnOBRHyyN6IzOC7T61GoSGYJZKBj0aQbpTXm0WmZ7PWwhjUp+by+WMNZCBhMtBCMFEUXSFmEWy4bgJu+Gm6YoFYnkt3PIIrQxlJBinzdOC9zo2+YLCkpLKbz5Unk8yTuJfLns2obrVMxPDU2+Z/+UwMsB4dMAxAAU6TWWdiPGjlak9qgWaaX9FVdEnjOpIq/xi0Bj/0L+IQ0WfBq7NHqJKfzpkml6yXXJsVoqSru7f9xffVL+ce+TYL7hy8LR09m0rOVWFeFGS6ZkJmsmImXNNSBEcVOXQpmhgMB1P19+N/02rELbctrL2jH557m+SbVp+zpciuTrroxy3XpefP+CQKIRtAKwY6/0bKURNanF87YuBhjV5gWIlPUEQMNycoFBhRB2P2yeUG1pTH4bpPsC+ovaIioHGgpKOhqTiyJL0OypHYPOiU+BgJSxmuKMo2M0OJTX9V2FpsXStdF1pKVPVLWUHKNKsmbBeCB2v3o+ej2OHKxb6stOOspacYpU6lQ6jdrfG1PMBtzCTa9ehu+BMIbhcHJm0zOT8RSatQzVVRWCdYUVXoTxlIID5PMgIloRadB2z4gulT203O08I+udax0qxXqneqLq1ksvC5k8MDz+Tb0ele+BcHjRVPI/MvFztmRJtLf1DvUtlSQVA9S/dDqTqeLysjtBWiB2P5ZOsS3tXRCccBvgK3P7Lcr+mvYrIytzK+KcfP0dHdz+pl+CYGqxOJIF4szzaMP1RG80pJTUVN6kpNRpQ/9ja3LCghpRSPB076Ru3e4HTVYcvxwmO86beitZ6127dEvLXC+srQ1Orf8OuE+EIFyRG5HbQoZzKIOtpALkVkR29HUUUbQfI6CDOcKfkecxNkByv7Ju+z4yjZ2M8JyPXByb2ju5K7lL2VwXXHA88E2C7iM+27+GsE6w/gGvck4i1eNTI7ND9HQV1BeT+sOxU25C5QJqAcHxIgB/r7AvGO5u3catREzbHH28PbwcHBiMMhx27MQ9No25zkmO4L+aQDEg4DGCshRSkTMGI1DDn2OhQ7aTkENgExiyrVIh4aqhDEBrr82PJt6b/gEdmd0pTNGcpFyCPIs8nlzJ3RtNf63jLnHfB0+e0CQAwkFVUdlCSsKm8vujJ2NJk0JTMnMLkrASYtH3QXEw9NBmj9pvRL7Jrkyt0Q2JfTfdDazrbOENDa0v3WVdy34u/pxPH3+UgCeApGEncZ1B8uJV0pQyzNLfEtsSwaKkImSiFbG6UUXQ2+BQP+aPYo73rokeKY3bXZA9eV1XLVmNb92IrcIeGd5tDsifOT+rYBuwhsD5UVCRueHzMjryUBJyInFCbiI6AgaRxiF7IRiAsVBYz+Hvj/8VzsYOcw4+rfpd1w3FLcSN1I30DiFeap6tTvbvVJ+zcBDAeZDLQRNxYAGvUcAh8YIDIgUx+FHdgaYxdEE54OlQlSBAD/xvnO9DzwNOzS6C/mXeRm41DjGeS25RroLevX7vjyb/cY/M0AbAXPCdYNYhFbFKoWQRgXGScZdBgHF+0UOxIGD2oLhgd3A2D/XvuS9xf0CPF67n/sJOtx6mfqBetD7BPuZfAl8zr2jPkA/XgA3AMRB/8JjwyxDlYQdBEEEgYSfBFuEOcO9QyqChoIWwWDAqr/5PxI+un32PUj9NXy9vGK8ZHxB/Ln8ib0uPWO95j5xPsA/jkAYAJiBDIGwwcKCQAKnwrmCtUKcQq/CcgIlQc0BrAEFwN3Ad7/V/7v/K/7n/rI+Sv5zPis+Mf4Gfme+U/6IvsQ/A79FP4Y/xAA9wDFAXQCAQNpA6sDyAPCA5wDWgMBA5cCIQKnAS4BvABUAPz/tv+D/2X/W/9j/3z/ov/Q/wIANABiAIcAngClAJkAeQBFAP7/pP87/8j+Tv7V/WD99/yg/GD8PPw5/Fn8nvwJ/Zn9S/4c/wMA/gACAgcDBQTxBMEFbgbwBj4HVAcuB8oGKQZMBTgE9QKJAQAAZv7G/C/7rflP+CH3L/aD9Sb1HfVr9RL2Dvdc+PL5x/vN/fb/MAJrBJUGmwhsCvgLLw0HDnQOcQ78DRMNvQsACucHggXiAhoAQP1p+q33IvXe8vXwd+9z7vXtA+6f7sjvd/Gj8zz2Mflq/NH/SgO8BgoKGg3RDxkS3hMOFZ4VhxXFFF0TVRG8DqMLIAhOBEkAMvwl+EX0sfCG7eDq1Oh259Pm9ObZ54Dp3+vk7nzyjPb1+pf/TATyCGQNfBEbFSAYdBoAHLYcjhyFG6EZ7RZ8E2cPzArMBY4APPv99fvwXuxM6OfkTOKR4Mbf9t8h4UHjSeYj6rTu2vNv+Uf/NQUNC58QvxVEGgge7CDXIrYjgSM1ItofgBw9GDITgw1bB+kAYPrx88/tLOg04xHf5NvK2dXYD9l72g/du+Bk5ejqHvHY9+L+BAYKDboT4BlKH8wjQieMKZgqWSrPKAMmCCL6HP8WQhD4CFgBnvkD8sbqHuRC3mHZotUn0wTSRtLt0/DWOduq4BvnW+409mn+ugboDrIW2h0oJGgpby0cMFYxEjFPLxcsgSevIcoaCBOjCtsB9fg18ODnOOB52dvTi8+tzFrLoMt+zenQydX821LjlOuE9N39VQemEIUZrCHaKNYubzN+Nuo3pTetNRAy5ixWJpEe0RVYDHECZ/iH7iDlfNze1IXOpMlixt3EIsUyxwDLcNBc147fyujJ8j791wdDEjEcUSVdLRM0PDmwPFA+DD7lO+k3MjLtKk8imhgXDhgD8/f77Iji7dh10GPJ8cNLwJG+0r4PwTnFMsvP0tbbAuYG8Y78Pgi+E7QeySitMRo50z6rQoFEQ0TyQZw9YTdvLwImYRveD9EDmPeR6xrgjtU/zHjEd75tuny4trgau5q/FcZazivYPuM97837jAgXFQ0hDyzHNec9L0RrSHhKQ0rNRyVDbTzXM6QpIh6pEZgEV/dK6tfdYdJByMm/O7nNtKSy0rJatSi6HMEAypLUgOBw7f76wAhNFjojIi+oOXdCSknqTTBQCFByTX5IUUEhODMt2yB3E24FL/cl6cDbaM9+xFm7QbRwrw2tLa3Sr+m0TbzGxQ7Rzd2i6yL63AhgFzslADJNPcdGIk4lU6VVjVXcUqNNCkZJPKswiCNGFVEGH/ck6NbZpcz4wCu3jK9ZqrunyqeHquCvrLexwaPNJtvU6Tr54AhPGA0nqDS0QNJKs1IXWNJazVoFWI9SkkpLQAg0JyYSFz8HJ/dH5xvYGsqxvUKzIKuNpbSir6J/pRKrPbPDvVTKkNgI6Ef4zAgbGbEoFzfaQ5dO+Va8XLJfw1/qXD1X5k4jREc3tSjbGDYIRveN5o7Wx8esuqKvAacPofud352+oISmBa8CuibHDNZD5kz3owjDGSYqTDm+RhJS8FoRYUJka2SGYapbAVPNR2U6LiueGjQJevf25THVsMXqt0ysMqPknJWZYJlJnDqiCKtwthrEntOF5Er2ZAhJGmsrRjtdSUJVl14RZX5owWjVZdBf31ZFS109jy1XHDkKwveB5QTU08NttUSptZ8PmYWVNJUimDmeSqcSszbBStHR4kP1EgisGoEsBT23SyNY6WG7aGJswWzSaaxjfFqITixA1i8FHkELHvgv5QbTM8I3s4qmjpySlc6RYJFOlIOaz6Psr3y+Ec8p4Tn0rQfuGmcthz7JTbVa5mQLbOtvaHB7bTpn1V2SUdBCADKlH0wMjPj95DjSz8BJsSGkvZlwknOO543RkB2XmqAArfC798yR3y/zNwcPGx0uzT+TT/Vcimf+bhdzs3PMcHhq5mBfVEVFCjQ1IVcNC/ns5JnRp7+jrwqiRpesj3eLy4qujQmUrp1SqpS5/soK3iXysQYQG6Uu1UAUUeJe1GmTceJ1nnbCc2FtrGPtVohH8TWyIl8OmPn75CnRvb5HrkagKZVHjd2IEIjnikyRDpvkp2u3KcmX3B3xHAbzGv4uoUFMUnxgw2vHc0p4KHlZdvJvJGY5WZZJszcaJGQPMvon5efQD74zrdaeaJNDi6eGuIV/iOeOv5i7pXi1e8c62xvwfAW4GikvMUI7U8JhVW2adU96TnuReCpyS2hAW21LTDlrJWMQ2fpw5dLQnr1qrLudBZKiidaExYN5ht2MwZbYo76z9sX22SDv0ARhGigvhELgU7Niim4Jd+17D31legV0H2r+XApNvDqjJloRifvV5enQaL3pq/Sc/pBliGuDOILWhDCLF5U+oj6yncTM2C7uHATvGfsunUI8VE9jYW8UeCN9Z37We4J1nWtzXmpO/ju+J0cSQfxU5izRbb2xq4KcVpCMh2iCE4GYg+OJxJPuoPywcsO/10ftYQNkGaMue0JQVJdj22+7ePJ9WH/gfJ92xWycX41PEj28KCgT//zr5pjRrL3Bq2ScDJAYh86BWIDBgveIyZLsn/qvdsLR1mzsoALBGCMuIEIcVItj92/9eFh+33+EfVt3k214YG9Q9T2aKfsTwv2Y5yzSI74ZrJqcH5AIh5yBBoBRgmyIKJI4nzmvrMED1qHr3AEJGHwtjUGhUyxjtW/beFZ+/H/AfbR3B24EYQ9Rpj5WKr8Uh/5b6ObS0b62rCKdjpBch9OBHYBJgkSI4ZHVnrquFsFZ1ebqFgE9F64sxEDiUntiF29UeOp9r3+Ufap3IG4/YWxRIj/vKnAVTf8w6cbTtL+XrfydWpEUiHKCn4CpgoCI9pHCnn+utMDT1D/qUABfFr4rxz/fUXphHm5rdxd9+H7/fDx33G0pYYRRaD9iKw4WEAAW6sjUy8C7riWfgJIviXmDioFygyCJaJIBn4quicBz1Kvpjv9xFasqlz6aUClgy2wfdt172X0DfGt2PW3AYFZRdz+vK5YW0gAL6+rVE8IgsJyg/5OqiuaE3oKihCOKNpOTn9uulsA61C7pz/51FHkpNz0WT4xeIWt0dD16UXyfejZ1QWwFYOJQTj/TKwgXjgEO7CzXi8PEsWCi1ZWGjLiGmoQ5homLYJR4oHOv3MAq1MnoFv5tEykoqDtUTaNcIGlpcjl4YnrVeJ9z6Gr2XiZQ7D7OK2EXQwIb7YrYMMWks22kAJi+ju6Iu4Y2iFKN5pWwoVKwW8FF1HzoZf1bEr4m7jlXS3Jay2YDcNN1DnimdqVxNGmVXSNPUD6eK6AX8AIx7gHa/8a9tcGmfppSkYWLQYmXinyPyJc6o3mxFMKK1EvovvxBETolCjghSftXJWRCbQxzV3UTdEtvJWfiW9lNej1DK8MXkgNO75Hb98gOuFqpS50/lHqOKYxbjQaSBJoXpeeyCMP71DboIfwiEJ8jADa2RkFVMWEqauhvQHIgcZJsvWTcWUhMaTy7KsoXKARv8DbdE8uTujSsZaCBl8yRcI9+kO2UmZxEp5y0NsSZ1T3okvv/DvAh0TMYREdS8l2+ZmpsyW7NbXxp/GGHV29KHTsHKrMXsQST8e7eU81JvUyvyaMWm3aVFJMAlDGYhZ/CqZe2n8Vk1mToEfvaDS8ggTFLQRFPa1oCY5Ro+Godagxm5V7iVFFIlzklKX4XKgW48rfgss8twKCycqf6nneZEpfcl86bx6KOrNi4Qsdc16nooPq2DGAeEy9QPqFLoFb4Xmpkz2YUZkNieVvvUe5F1jcWKCkXkgXb843iLtI8wyu2Xqspo8mdZpsQnMKfW6anr127H8mC2A7pQfqUC4MciiwtO/xHlFKkWvBfUWK2YSVevFewTkdD3TXZJrMW6AX79G/kxNRzxuq5ia+gp2miDKCZoAmkQKoLsyW+NcvW2ZTp9Pl3Cp0a6SnlNyVES04LVipbg10EXbVZsFMoS15AqjNvJR0WKwYW9lrmcNfNydi97rNarFSnAaVypaGocq63ti7BhM1X2zvqu/lfCa8YMid6NB9AykkxUR1WaFgEWPZUWE9YRzU9QDHYI2UVWQYp90voMNpIzfPBirhTsYSsQaqYqoWt77KqunfECdAE3QPrmPlQCLsWaSTwMPA7FUUbTMtQBVO6Uu1PuEpEQ845oC4UIowUcgY0+D/qAd3f0DbGV72GtvWxxq8GsLKys7ffvv3HxNLe3u3rivlLB8UUkSFMLZs3MUDMRjxLX00pTZ1K0kXuPio2zCslIJITdAY0+Tbs39+P1JzKUsLvu6K3jLW4tSS4urxUw73LstXj4Pjsk/lRBs8Srh6RKSUzITtKQXJFe0dXRwtFqkBaOk0yxCgLHnUSXwYo+ivuyOJV2CLPdceIwYe9jrupu9a9AcIGyLbP0tgS4yXutPlkBdsQwRvCJZEu6zWaO3Q/XEFIQTo/RjuLNTkuiyXHGzgRMwYO+x3wt+Us3MPTvcxOx57Dx8HUwcPDgsfyzOTTI9xr5XPv7fmFBOwOzxjkIeQpkzDBNUY5CjsCOzE5qDWFMPIpJCJaGdoP7gXk+wryq+gQ4HvYI9I6zeHJMcg0yOjJO80S0kXYoN/r5+LwPvq2AwMN2hX5HSIlHyvEL+4yiTSJNPMy1i9LK3olkB7HFlsOkAWr/O7zoOv/40XdpNdH00zQyM7Ezj3QJtNk19TcSeOR6nDyqPr5AiML5hIHGlEgkyWoKXIs3i3kLYcs1CniJdQg0xoOFL0MGQVf/cn1k+705x3iOt1w2djWhdV+1cDWPtni3I7hG+db7R30LPtOAk4J9Q8RFnMb9B9zI9clECcXJ/AlpyNPIAYc7hYzEQELiQQB/pj3gfHr6/7m4eKv34HdY9xc3Gndft+K4nDmEutI8On1yPu1AYUHCg0aEo8WSBoqHSIfJCApIDYfVB2VGhEX5hI2DicJ4QOP/ln5aPTg7+XrkugA5kDkXONZ4zPk4uVV6HbrK+9V89H3ffwxAcwFKQomDqcRkhTTFlsYIBkfGV0Y4Ba5FPsRvQ4aCzAHIAMJ/wv7RPfR88zwSu5c7A/raupu6hrrZOxA7pzwY/N/9tX5Sv3CACMEUwc5CsEM2Q5zEIURChIAEmoRUhDBDscMdgrhBx8FRgJu/6v8E/q697D1A/S+8unxhvGX8Rby/vJF9N31uPfF+fP7MP5oAIwCiwRWBuEHIgkQCqgK6ArQCmUKrQmwCHoHFQaOBPUCVQG9/zj+0vyW+4v6uPkh+cf4rPjL+CP5rPlf+jX7JPwk/Sr+Lf8kAAkB1AGBAgsDcAOvA8kDwAOXA1MD+AKNAhcCnQEkAbIATAD2/7H/gP9j/1v/Zf9//6X/1P8GADgAZQCJAJ8ApQCXAHYAQAD3/5z/Mv++/kT+y/1X/e/8mvxc/Dr8Ovxd/Kb8FP2n/Vz+Lv8YABMBGAIdAxkEAwXRBXsG+AZCB1MHKAe/BhkGNwUfBNgCaQHf/0T+pPwO+475NPgL9x72efUi9SD1dvUj9if3e/gX+vD7+v0kAGACmgTCBsQIkAoVDEUNFA54DmwO7Q37DJsL1gm3B0wFqALe/wP9Lfp19+/0svLQ8FzvZO7x7Qrusu7n76Hx1/N49nP5svwaAJQDBAdOClcNBhBEEv0TIBWjFX0VrRQ3EyMRfg5bC9EH+gPz/9r70ff282nwSe2u6rDoYefO5v/m9ees6RnsLO/O8uf2Vvv7/7EEVAm/Dc8RYRVZGJ0aGBy7HIAcZRtvGaoWKxMKD2QKXgUdAMv6j/WU8AHs/eeo5B7id+DB3wXgReF545Pmfuod70306fnF/7MFhwsRESYWnBpPHh8h9CK8I3AjDSKcHy0c2Re+EgMN0wZeANX5avNR7bvn0+LD3q3bqtnO2CLZp9pT3RXh0eVm66rxbPh6/5wGnA1DFFsatB8hJH4nrymfKkUqoCi6JaYhgxx2FqsPWAizAPn4ZPEx6pnj0N0F2WHVAdP80VzSINQ/16PbK+Gv5/7u4PYa/2sHkw9SF2oeoyTKKbYtRDBfMfswGC/CKxEnJSEsGloS6gkdATj4fu81557f9thy0z/PgsxQy7jLuM1D0UHWjtz6403sSPWm/h8IaRE7Gk8iZilGL8AzrTb1N4s3cDWwMWcsvCXfHQ0ViAubAZH3ue1f5M7bStQOzk7JMcbRxDzFcsdky/bQ/9dK4JnppfMg/rgIHRP8HAkm+i2RNJc55TxdPvE9ojt/N6YxQiqKIcEXMA0rAgb3Fuyy4SzYz8/eyJHDE8CDvu6+VcGnxcXLg9Ol3Obm+PGH/TYJrxSVH5MpWjKlOTg/5kKQRCZEqUEpPcc2sy4qJXMa4A7MApT2luov37rUicvmww2+L7psuNS4ZrsSwLTGHc8M2TbkRfDd/JsJHRYCIuwshTaAPp5ErEiKSiVKf0epQsc7DDO6KCAdlxB+Az32OenY3HvRfMcqv8e4ibSRsvGyqrWousfB0sqE1Yzhje4j/OUJaBdDJBIwdjodQ8NJMk5FUOlPH036R6BASDc4LMYfUBI/BAD2AOit2nDOqMOsusOzJa/3rE2tJ7BwtQO9psYR0uve0uxb+xUKjxhXJgEzKj55R6VOc1O9VW1VhFIYTU5FYzuhL2IiDBQNBdz16+ax2JzLE8BytgWvB6qip+un4KpvsG24nsK1zlXcF+uH+i0Kkhk8KLk1oEGRSz9TbFjsWqxaqlf9Uc1JWD/vMvAkxhXoBdH1++Xj1gDJvrx9spCqNaWYos+i3KWoqwe0vL51y8/ZXemn+SwKcBryKTg41ERiT45XF13QX6JfjFylVhdOJEMgNm0nfhfNBt31L+VG1Z7Gq7nRrmimsaDcnQCeHqEgp9ivBrtUyFvXqOe9+BQKKht3K306xkfpUo9bcmFkZEpkJmELWypSxEYwOdgpMRm7BwD2h+TY03fE3LZwq5CigJxymYCZqpzbouOrf7dVxfvU+eXL9+YJwBvMLIY8ckojVj5feWWjaKFocmUtXwBWMkocPCws2xqwCDn2A+Sc0o3CU7RdqAqfpJhelVOVhZjeniyoKrR8wrPSU+TT9qMJMhzwLVI+10wPWZhiKGmKbKJsbmkFY5dZbE3hPmcufByrCYb2ouOQ0d/AEbKZpdqbIZWkkX6Rs5Qsm7ekDLHMv4bQuOLX9UwJghzjLuE/9U6qW51lfmwXcEtwFm2QZupcblB8QYYwEB6oCuf2Y+O10G+/GLAnowKZ+pFFjgOON5HJl4ehJ65IvXbOLOHY9OIIsBymLzJByVDzXUhod29Gc5dzZnDKafZfNVPoQ4YylR+oC1n3RuML0D2+aK4HoYSWMI9Gi+aKFI64lJ+ef6v0uobMr9/Z82cIvBw4MEVCVFLpX5lqEXIVdoV2W3OxbLhivVUkRmU0CSGmDNz3SuOQz0m9Aq07n2CUxoypiCmITYv8kQOcF6nRuLnKRN7b8t0HqBybMBpDlVOLYY9sSnSBeBB583VBby1lBFgsSB82aSKjDW74beNFz5K856vEnZmSvopvhs+F5IiYj7aZ8abkthLJ79zh8UUHdhzPMLJDi1TXYiduInaIejh7K3h4cVJnCFr/SbM3tCOaDgz5r+Mozxm8FqujnDCRGImahNqD3YaOjbqXEaUttZLHsNvs8KAGJhzVMAxEN1XOY2FvlXcqfPt8AXpUcyVpxFuYSx455iSMD7b5DeQ5z927j6rWmyWQ14csg0uCOYXiixGWeaOxszzGitr/7/EFuhutMCpEmFVwZD1wpHhkfVZ+c3vRdKNqOF33TF46/iV1EGr6h+R3z927U6pgm3iP+oYmgiSB+oOUir6UKqJxshPFgNkb7zoFMxtbMA1EsFW8ZLpwT3k2fkl/gHzvdctrYV4YTnE7+iZTESX7GuXfzxi8X6o+myqPgoaJgWWAIYOmicKTKKFusRjElNhD7nsEkxrdL7VDgFWzZNlwlHmfftJ/JX2tdptsPV/7TlM81yclEub7xuVx0Iy8tKpxmzqPb4ZUgRGAroIZiR+Tc6CssE7Dxtd47bgD3Bk3LyRDCFVXZJtwdHmffvJ/ZH0IdxFtyl+dTwU9lCjoEqv8iOYq0Tm9T6v3m6iPwYaJgSaApILviNaSDKArsLXCGte87PECEBlqLlxCSVSnY/9v8Hg2fqh/O30BdyxtCWD8T4Q9LymcE3P9XucK0h2+MKzPnHKQeIcmgqWAAYMoieiS95/ur1HCkdYR7CoCMBh4LV5BRlOmYgdvCHhlffR+qXyXdu1s9l8YUM49pik9FDr+R+gO0zW/Va35nZiRkYgqg46BxoPDiVWTMqD0ryHCLdZ662MBPxdjLCxAAFJVYbRtvnYtfNd9sHvJdVJskl/vT+I99ynKFAD/QOk01IDAvK5xnxeTDIqWhN+C84TCih+UvqA/sCjC7tX36p4APhYsK8g+eVC2XwlsE3WOelJ8UHqZdFpr3V6BT789IipCFcL/SOp71fzBYrA3oe6U54tnhpiEh4YkjEOVnaHQsGfC19WL6uD/LxXXKTU9s07KXQZqCHOLeGZ6iXgGcwhq1V3NTmU9JSqjFX4AXOvf1qbDRrJHoxuXII6biLeGgIjojcSWzqKosd7C6dU26ib/FhRlKHQ7sUyWW69noXAmdhR4XnYScVpoe1zSTdI8/inrFTQBe+xe2HzFZrSfpZuZtZAxizqJ3YoMkJ+YUKTGso3DJdb76XX+8xLYJok5dkoaWQdl321gc191z3O+blJm0FqRTAU8rikZFuABoe332XvHvbY9qGyco5MnjiCMnI2QktOaJKYqtHfEi9ba6c39yRE0JXY3A0hbVg9ixWo8cEly4HALbPFj1FgKS/86MiksFoICzu6n26HJSrkdq4qf6JZ4kWWPvJBylWCdSKjUtZnFHNfV6TH9mhB6Iz41XUVaU8teV2e9bNVukW37aDlhiFY9ScA5iigiFhgD/+9r3evLCbw9rvOif5ojlQeTOpSvmESgvKrEt/XG2tft6aP8aA+tIeMyhkIcUD5bl2PmaAZr5mmRZSpe7VMrR0c4tyf7FZ8DMvFA31bO976ZsaKmZ54lmQOXEphGnH2jfa34uYvIxNgj6iP8NQ7PH2kwgT+kTG1XiV+8ZN5m4WXPYchaBVHURJU2tya2FRcEZPIl4d/QEsIttZWqmqJ4nVabQpwzoAini7BwvFnK2tl46rP7Aw3kHdItUjz1SFlTMVtAYGFihmG3XRRX0007Qqo0iiVRFX4ElfMW44PTVMX2uMeuFqcbovufxqBzpOOq47Mqv2DMHdvt6lX71AvtGyEr/DgTRQlPk1Z4W5Rd2VxOWRJTVkphP4gyMiTNFNMEwfQS5T/WvMjwvDWz1asHp/Ckm6UEqQyvgrckwp3Oi9yB6wr7qwruGVsogzUCQX9Ks1FoVnpY3VeXVMROlEZHPC8wrSIpFBUF6PUV5xDZRcwXwdq31LA6rC6qvarhrX6zaLtexRHRJt427NL6iAnoF4El6zHHPMFFlkwTURhTllKVTy5KjULvOKEt/CBjE0IFBvcd6fLb7M9mxbG8DravsbOvKLAHsze4j7/UyLrT7d8L7bD6bgjeFZciNy5kONJAQEeAS3JNCU1MSlJFRT5bNd4qIB9+ElkFG/gn6+PerNPaybbBfrtgt3m11rVxuDS998OEzJbW3eEB7qP6XwfUE6EfayrfM7c7t0GyRY1HO0fBRDZAvjmPMeonGx13EVsFJPkx7d7hg9duzuXGIMFJvXu7w7scvnDCm8hs0KPZ+OMY7636XAbKEaAciiY9L3U2/zuwP25BMEH4Ptw6/jSMLcUk7BpQEEUFIfo57+LkbNsf0znM7sZkw7XB68ECxObHeM2I1N/cOuZP8M/6ZgXFD5oZmiKAKhExHTZ9ORs77Tr2OEk1BjBWKXEhlRgJDxcFD/s88evnZN/n16zR48ytySHISMgfypTNidLX2EngpOim8Qj7gATFDZAWnB6uJZArFjAgM5g0dzTAMoIv2yrwJPIdGRaiDdIE7vs48/bqZuPB3DrX+dId0LnO1c5u0HPTzNdU3d3jNOsd81r7qQPNC4UTlhrMIPYl8CmeLOwt1C1aLIspgSVdIEkadxMdDHQEu/wr9f/tb+er4d7cLNmv1njVjNXp1oHZPN384Zrn5+2y9MT75QLgCX0QjBbdG0kgsSP8JRwnCifKJWkj/B+gG3oWshB5Cv4Ddv0S9wTxeuue5pPid99e3VjcaNyL3bbf1eLM5nzrvPBk9kb8MwL/B3sNgBLmFo4aXR1BHy4gHiAXHyEdURq+FoYSzQ24CG8DHv7t+AP0hu+X61To0uUk5FPjY+NP5A/mkejA64DvsvM0+OH8lQEsBoIKdg7sEckU+xZyGCcZFhlEGLkWhBS6EXIOyArbBsgCsv64+vf2jPOR8BvuOuz76mPqduov64bsbe7T8KPzxPYe+pX9CwFpBJQHcwrzDAEPjxCWEQ4S+BFYETUQmw6ZDEEKqAfjBAkCMv9y/N75i/eI9eTzqPLc8YPxnfEm8hbzZPQC9uL38/kj/GD+lwC4ArQEegb/BzkJIAqxCukKygpZCpsJmQheB/UFbQTSAjIBnP8Z/rb8fvt4+qn5F/nD+Kz40fgs+bn5cPpI+zn8Ov0//kL/OAAbAeQBjgIVA3cDswPKA74DkwNMA/AChAINApMBGwGpAEQA7/+s/33/Yv9b/2b/gf+p/9j/CgA8AGkAiwCgAKQAlQByADoA8P+T/yn/tP46/sH9Tv3n/JT8WPw5/Dv8Yvyt/B/9tf1s/kH/LAApAS4CMgMuBBUF4QWHBgAHRgdSByIHtAYIBiIFBgS6AkkBvv8h/oH87fpw+Rn49PYN9m71HvUk9YH1NvZA95v4PPoa/Cf+UwCQAskE7wbtCLMKMgxaDSAOfA5mDt0N4gx5C6wJhgcWBW0Cov/G/PL5Pfe89IbyrfBD71Xu7e0T7sfuB/DM8Qv0tfa2+fn8ZADfA0wHkgqUDTsQbhIbFDEVphVyFZUUERPwEEAOFAuCB6UDnP+D+3z3p/Mi8AvtfeqN6E3ny+YM5xPo2elU7HTvIvND97j7XgAVBbUJGg4gEqcVkRjEGi4cvxxxHEMbOxlnFtkSqw78CfAErf9a+iL1LvCm66/naeTy4V7gvd8W4Gvhs+Pf5trqhu/C9GT6QwAxBgEMgxGMFvMalB5QIQ8jwSNdI+MhXB/ZG3MXSRKDDEwG0/9K+eXy1exL53Tid95324zZydg32dXamd1x4UHm5us28gD5EQA0By8OyxTVGhwgdCS5J9AppSovKm4obiVCIQoc6xUUD7cHDgBV+MbwnukV41/drNgh1d7S9tF00lbUkdcO3K3hROih7473zP8bCD0Q8Bf4HhwlKir6LWowZTHhMN8uayueJpogjRmrETEJXwB798jui+YG33TYC9P2zlnMScvTy/TNoNG71iLdo+QH7Q32cf/oCCoS7xrxIvAptC8ONNk2/TdvNzA1TjHmKx8lKx1IFLcKxAC89uzsoOMj27jTms37yALGyMRaxbbHy8t+0aTYCOFp6oH0Av+ZCfYTxh2+JpQuDDXvORY9Zj7SPVs7EzcXMZQpwyDmFkkMPQEZ9jLr3eBt1yzPXMg0w9+/eL4Ov5/BGcZbzDnUdd3L5+vygP4vCp4VdCBbKgUzLjqaPx5Dm0QFRFxBszwrNvUtTySDGeINyAGR9ZvpRt7p09bKV8OnvfW5X7j1uLW7jMBXx+PP79kw5U7x7f2pCiIX9iLHLUA3FT8JRepIl0oCSixHKkIeOz8yzicdHIMPYwIk9Sno2tuX0LnGjr5XuEi0grIVs/+1LLt2wqfLedaZ4qvvSf0JC4IYSyX+MEA7v0M4SnZOVVDFT8hMckfrP2w2OyuvHikRDwPR9NvmnNl6zdbCBLpKs96u5axxrYCw/LW+vYrHFtMK4APulfxOC70Zcif/MwQ/KEgjT71Tz1VIVSlSiEyORHk6ky45IdESygOZ9LPljdeVyjK/vbWCrrqpjqcQqD6rArExuY7Dys+H3Vvs1Pt5C9MaaSnINohCTEzHU7xYAluHWktXZlEDSWE+0jG2I3kUkQR69LDkrtXpx867vLEEquKkgaL1oj2mQqzWtLm/mMwR27PqB/uMC8QbMCtXOctFKVAfWG1d6V99XylcB1ZETSJC9TQkJiAWZAV19NLj/9N4xa24Ba7TpVigwp0lnoKhwKewsA+8hcms2A7pLvqFC48cxiyrO8pIu1MoXM5hf2QlZMBgaFpOUbZF+TeAKMIXQgaH9BnjgtJCw9G1maryoSGcVZmlmRGdgaPDrJK4k8Za1m/nTPlnCzUdKi7CPYJLAFffX9tlwmh8aAplhV4dVRpJ2TrGKl4ZJwew9IbiNtFKwTyze6dknj+YPZV4le+YiJ8TqUa1xcMf1NflY/gzC7cdXS+bP/RN9llCY5BprWx+bARpWGKtWEtMkz31LPEaEwjv9BbiHdCPv++wrqQtm7eUgJGikR6V2pukpTCyH8H+0UnkdffqChQeXTA3QR1Qm1xOZutsPXAocKts4GX6W0ZPJEAJL3kcBAlC9crhNc8TvuuuMqJNmIqRHo4mjqOReph5olOvpL74z8jigvaNCk4eLDGTQvtR7V4Baepvb3N1c/pvF2kCXwZSiEL/MPMd+Amp9aHhf87WvDGtCqDHlbuOG4sHi4CObJWWn7GsWLwRzlXhjvUdCmYeyjGxQ5BT62BZa4lyQXZkdu9y/GvAYYlUvUTWMl4f7Qoh9pvh+s3Yu8KrNp6dk0yMeohJiLmLspL+nE6qPLpMzPPfmfSdCVweNjKPRNlUlGJVbcd0sXjyeId1i24xZMtWv0aJNLYg4Aup9rXhps0Zu5+quJzQkT6KPYbthVGJT5Czmi2oU7iryqXep/MNCTIecjIvRdZV52PzbqN2vHoce8B3wXBUZstYjUgXNvoh0QxA9+7hgc2ZusepkJtikJSIZYT1g0mHRo65mE+mobYwyWzdufJvCOkdfzKQRYlW5GQycBt4YHzgfJZ5nHImaIVaI0p+NycjvA3k90bijM1WujqpvppSj0+H9IJkgqOFmYwRl7mkKLXex0vc0PHGB4MdXjK0RfBWi2UTcS55nX0+fgp7GnSjafdbf0u7ODwkoQ6T+LvixM1RuvmoQpqhjm6G64E7gWKES4u+lWuj6bO3xkTb8PASBwAdDzKbRQxX22WUcdx5cn4zfxh8OXXLaiBdoEzMOTUlfA9L+UvjKc6IugGpHZpPjvOFS4F6gIeDW4rBlGii57K9xVnaGvBWBmMclTFHRd9W1mW2cSR63n6/f8B8+HWca/1dgk2uOhImTRAK+vXjuM76ulOpTZpcjt6FE4EjgBODzYkclLKhJLLyxIvZT++UBa4b8TC4RGlWfGV6cQd64X7hfwF9VnYVbIxeJk5hO88mERHQ+rbkcc+lu+2p0ZrIji2GRYE1gAWDoInRk0qhobFYxN7Yku7MBOEaJDDwQ6xVzWTgcIV5e36af9p8UnYzbM1eiE7iO2wnxhGY+43lUdCJvM2qqZuQj+KG4IGygGCD1YnfkzChYLHxw1LY5e0DBP8ZMS/xQqhUzWPpb594rH3pfkx863X3a75eqE4wPOcnaxJj/HnmV9GivfOr0py1kPmH44KXgSKEbYpJlGehYrG9w+nXSu04AwsZGS69QWFTe2KXblZ3dXzOfVZ7InVga19ehE5JPD4o/RIt/XbngdLwvlutS540knOJTITmgkuFaIsNle6hqLG+w6XXwexuAgUY3ixWQNhR2mDrbKt12XpMfPp59nNvaq9dHE4tPG8oexP1/YPozNNwwAWvE6AMlE6LHIachNuGxYwtlseiMrL2w4fXTuyoAfEWgyu+Pg5Q7V7naqFz13hiejd4aHIiaa5cb03aO3ko5BO6/p7pNtUfwu6wJqI7loiNT4i5htCIhI6nl/GjArNkxJDX8evmANAVCir4PAhOtVyOaDlxcnYTeBB2eXB7Z1xbfUxQO1woNRR4/8Xqvdb8wxKzgqS9mB2Q5Io6iSmLo5B7mWulF7QKxcLXq+srAKMUdSgGO8ZLNVrjZXZurXNhdYVzKm56ZblZRUuOOhYobhQuAPbrX9gDxnC1JaeRmw2T2Y0djOWNIZOomzancbXpxR3Yf+t5/28TxybqOExJcFfnYlpriXBNcppwfWshY8ZXyEmTOaYnjRTcAC7tGdozyAW4DKq0nlSWK5FgjwCR/JUtnlGpELcAx6LYbuvR/jQSAiWoNp5GaVSfX+lnCm3bbk9tdGhwYIRVBkhgOAsnkBR/AWvu6duHys26M60hou6Z1pQAk3mUM5kIobqr9LhPyFLZeOs1/vQQKCNCNL1DI1ENXCdkM2kNa6hpEGVqXfRSAEb0NkYmeBQVAqzvy93+zMW9lrDXpdmd2Jj7lk2Yw5w4pHCuHLvXyS3an+um/bMPPSG7Ma5Aok01WBVgB2XnZqhlVWESWhhQt0NRNVUlQhScAu7wvt+Uz+rAM7TQqRCiLZ1Mm3mcqaC5p3Kxhr2WyzPb5Osm/XEOQx8XL3M96kkbVLlbimBsYlJhRV1oVvFMLEF1Mzkk7xMUAy/yv+FG0jnEBrgKrpCm0aHwn/mg4qSLq760MsCNzWXcR+y2/DENPB1YLBE6/UXCTxZXwVugXalc41hvUoFJYD5jMfIifBN8A23zy+MR1a7HC7yAslWrwKbjpMqla6mpr1G4HsO6z8LdyexY/PYLKxuBKYo24UEwSzFSrlaHWLFXM1QsTstFVTscL38h6xLQA6b04OXy10bLPcAtt1qw9ashqueqQa4RtCm8R8Yc0krfau0N/MAKExmXJuMymT1oRg1NV1EmU25SOU+gSdJBDTifLOIfOhISBNj1++fl2vvOmsQOvJq1bbGlr02wX7PAuEPArcmz1P3gK+7V+5EJ9habIx8vKjlvQbFHwEuATeZM+EnQRJg9ijTvKRoeaRE+BAL3Gero3czSG8kewRG7Ibdrtfi1wrixvZ3ETc1819niC++z+20I1xSSIEMrlzRKPCBC70WbRxtHdES+PyA5zzANJykceBBWBCH4OOz34LTWvs1YxrrADr1tu+G7Zb7iwjLJI9F22t7kDPCn+1MHuRJ+HVEn5i/9NmA86D99QRNBsz5wOm003Sz8IxAaaA9XBDX5Vu4P5K/afdK3y5HGLsOnwQbCRMRNyADOL9We3QvnLPGx+0cGnRBjGk4jGiuMMXU2sTkpO9Q6uDjoNIQvuSi9IM8XOA5BBDr6b/At57neVdc30Y7Me8kTyF/IWcrvzQPTa9nz4F/pbPLS+0gFhg5DFz4fOCb+K2YwTzOlNGI0iTIsL2gqZSRSHWkV6QwUBDH7g/JN6s7iQNzT1q7S8c+tzunOoNDE0zfY1t1z5NjryvML/FoEdwwjFCQbRSFXJjcqxyz4LcItKyxBKR4l5B++Gd4SewvPAxf8jfRt7evmOuGE3OvYidZt1Z3VFNfF2ZjdbOIa6HTuR/Vc/HwDcQoFEQUXRBycIO0jICYmJ/smoiUqI6gfOhsEFjEQ8AlyA+z8jfaJ8AzrP+ZH4kDfPt1O3HbcsN3w3yLjKufn6zLx4PbF/LECdwjsDeQSPBfSGo8dXx82IBIg9h7uHAwaahYmEmMNSAj+Aq79gfie8yzvS+sW6KblCuRM427jbeQ95s/oC+zV7w/0lvhG/fkBiwbaCsUOLxL/FCIXiRgtGQwZKhiQFk4UeREoDncKhQZxAlz+Zfqq9kjzV/Dt7Rns5+pf6n/qRuup7JzuC/Hj8wr3Z/rf/VQBrwTUB6wKIw0nD6sQpRESEvARRBEXEHMOagwMCm4HpgTMAfb+Ofyq+V33YfXF85Py0PGB8aTxNvIu84P0KPYM+CD6UvyP/sUA5ALcBJ0GHAhPCTAKuQrqCsQKTAqHCYAIQQfWBUsErwIQAXr/+v2b/Gb7ZPqb+Q75v/it+Nb4NvnH+YH6XPtO/E/9Vf5X/0wALQHzAZsCHwN9A7YDygO7A44DRQPnAnoCAwKJAREBoAA8AOn/p/96/2H/W/9o/4T/rP/c/w4AQABsAI4AoQCkAJMAbgA1AOn/i/8f/6r+MP63/UX94PyO/FT8OPw9/Gb8tfwq/cP9ff5U/0EAPgFEAkgDQgQoBfAFkwYIB0kHUAcbB6gG9wUMBewDnQIpAZz//v1f/Mz6Uvn/99/2/fVk9Rz1KPWM9Un2Wve7+GL6RPxV/oMAvwL4BBsHFQnWCk4Mbw0sDn4OXw7MDcgMVwuBCVUH3wQzAmX/ify3+QX3ivRb8orwKu9H7uvtHO7c7ifw9/FA9PL2+vlB/a4AKQSUB9UK0Q1uEJcSOBRCFagVZhV7FOkSvBABDssKMgdQA0X/LPso91jz3O/P7E3qa+g758nmG+cx6Afqkey973bzn/ca/MMAeQUVCnQOcRLrFccY6hpCHMEcYRwgGwcZIhaFEkwOlAmBBDv/6fm19MjvS+ti5y3kx+FH4LvfKeCS4e7jLec36/HvNvXg+sEArwZ6DPQR8RZJG9gefyEoI8MjSCO3IRsfhBsMF9QRAgzDBUj/wPhf8lns3OYW4i3eQ9tx2cfYTtkF2+HdzuGy5mfsw/KV+aoAywfADlIVThuCIMQk8SfuKagqFio6KCAl3SCQG2AVew4WB2r/svcp8AvpkuLw3FTY5NS90vPRj9KO1OXXe9ww4troRvA7+HwAywjmEI0YhB+TJYgqPC6OMGkxxTCjLhErKSYNIOwY+xB3CKL/v/YT7uPlcN7116bSsM4zzEXL8cs0zv/RONe43U7lwu3T9joAsAnrEqIbkSN4Kh8wWTQCNwI4TzftNOkwYiuAJHYcgRPmCe//6PUf7OLiedoo0yjNq8jWxcPEe8X8xzbMCdJM2cfhO+te9eT/eQrOFI8ecSctL4Q1RDpFPWw+sD0RO6M2hTDkKPofChZgC08ALfVP6grgsdaMzt7H28Kuv3G+Mr/swY3G9Mzx1Ejesujf83r/JguMFlEhISuuM7M6+D9SQ6NE4EMMQTk8izU1LXMjkhjkDMMAjvSi6F7dGdMmysvCRL2+uVa4G7kJvAvB/cer0NXaK+ZY8v3+twsmGOgjny74N6c/cEUjSaFK3EnWRqZBcjpuMeAmFxtvDkgBC/Qa597atc/5xfW967cMtHeyPLNYtrS7KcN/zHDXqOPJ8G7+LQybGVAm6DEIPF5EqUq1TmFQnU9tTOZGMz+MNTwqlx0AEN8Bo/O45Y3Yh8wHwl+51LKbrtismq3esIy2fL5wyB7ULOE279D9hwzqGooo+zTaP9NInU8CVN5VH1XJUfRLy0OLOYMtDiCVEYUCV/N85GvWkclUvgy1A65yqX6nOqigq5qx+rmCxOLQut6g7SL9xgwTHJQq1DdtQwNNSlQHWRNbXVrnVspQNUhnPbMweiIrEzoDJfNm43rU1cbiugCxfKmUpG+iH6OjpuCsqbW6wL/NVdwK7Gf86gwWHWwsczq+RutQq1i+XfxfUl/CW2VVbUwbQcgz2CTAFPsDDfN34rvSVMS0tz2tQqUEoK2dUJ7soWWojLEbvbnK/9l26qD79gzzHRIu1jzKSYhUvFwlYpZk+mNVYMBZblCkRL42JSdSFsgEDvOt4S7REMLLtMapWaHHmz2Z0Jl+nSukp62oudTHvNfm6M766AypHoYv+z6PTNhXfGA3ZttoUmidZNddNVT/R5I5XinfF54FJ/MK4dPPCsApsp6mxJ3glyOVopVdmTig/qlnthHFjtVd5/T5www6H8cw4kAMT9ha52PyaclsVGyVaKdhvlcnS0E8gCtlGXwGWPOM4KzOQ77Rr8ejhJpSlGKRzJGOlY6clqZZs3bCeNPc5RP5iAylH9UxiUJAUYZd+2ZTbV1w/m86bCplBVsZTsg+iS3hGmAHnvMz4LfNu7zCrUKhnZcfkf2NT44UkjKZcaODsATAfdFm5C34NwzsH7Ay8UMpU+FftWlXcJJzTXOIb19oCF7SUCRBdi9QHEgI+PP+3/bMc7v+qxGfEZVLjveKL4vyjiaWkqDorb+9n8/94kP30wsPIFgzGUXHVOdhE2z7cmh2PXZ8ckFrwmBPU1FDRDGxHTIJZvTt32fMa7qHqjad4JLXi1OIb4gsjG6T/p2Kq6q74s2k4Vj2XAsPIM4zAUYYVphjFW4+ddp4zXgUdc5tMGONVU5F8DIBHx0K5fT+3wnMo7lcqbGbDZHFiRKGEYbDiQ2Rtpttqce5R8xd4G711QrtHxM0qUYeV/JkuW8ed+h6+HpNdwNwUWWJVxdHeDQ/IAYLdfUw4N3LG7l9qIKamY8XiDeEGIS6hwSPvZmSpxm40soq34b0PgqsHyc0EUfWV/Rl/XCaeJB8v3wled5xIWdBWalI2zVnIewLEvaB4OHL07jqp6uZhI7OhsOChIIUhleNFpj+paK2g8kO3qPzmglLHws0OkdDWKBm4nGxedB9H36aelxznmiyWgNKFDd3IswMvPbx4BTMyLijpyuZz43phbeBWIHShAiMw5axpGW1X8gK3cby6gjMHsEzJkdkWPVmZ3Jjeqh+Fn+qe310xmnaWyNLIzhvI6UNcfd94XXM+7iopwGZeo1rhROBlYD0gxeLxpWuo2S0Zscg3PLxMQgyHkoz1UY6WPNmjXKuehd/pX9UfD11mGq3XAZMBjlKJHUOL/gl4gLNa7n3py6ZhI1ThdmAO4B+g4aKH5X2oqCzmsZT2yjxbwd+HacySEbGV5tmU3KTehx/yn+XfJ51E2tJXatMujkJJTkP9Pjm4rrNFbqPqLGZ7Y2ghQmBS4Bug1eK0ZSMohuz/8Wk2mrwpwaxHNsxgUUKV+5lu3EUerh+hX90fJx1NGuMXQ9NPTqoJfAPvvm+45vO+LpvqYeatY5ShqGBxYDFg4mK3ZRvoteylMUV2rrv2wXOG+YwgUQGVu5kxXAveex91n7oezl1/GqCXTNNjzomJpgQjPqs5KLPE7yVqrGb2Y9oh6GCqIGEhB6LQpWiotSyW8Wo2RvvDQXWGswvS0O+VJxjc2/nd7d8v332enN0amonXRRNrTqCJi8RW/ut5c/QY70ArCudWJHiiAmE9IKqhRSMApYkoxSzV8Ve2Y3uPgTMGY0u4UEyU/phx209dhx7P3ydeUxzfWl9XLJMmDq6JrMRKfzA5h/S576srfSeMZO8iteFqIQ2h22NG5f2o5izh8U42RLucQOxGCwtREBlUQpgwmszdBx5WHred8NxNmiDWw1MTDrMJiQS9fzi55DTnMCZrwqhYZX2jAmIwoYniSaPj5gYpWC07sU52aztpwKIF6wreD5aT89dZ2nLcbl2DHi7ddlvlWY4WiNLyzm4Jn4SvP0R6R/Vf8LDsWuj5peMj56KQIl8iz+RXJqLpmy1isZh2V3t4gFTFg8qfzwSTUpbuWYHb/RzXHU1c5BtnGSeWPVJEzl8JsISfv5M6srWjsQntBKmvZp9kpKNIYwzjreTgpxNqLy2Xsex2SbtJQEUFVcoWjqSSoBYumPqa9FwS3JNcOpqSmK0VoJIIzgYJuwSN/+P647Yx8bDtv+o453FleOQYY9KkYyW/55eqlC4acgq2gjtcADNE4cmDjjbR3JVbWB3aFJt224Hbedno198VMxG/TaLJf0S5//Z7GnaJsmUuSysVaFimY+UAJO+lLyZ0aG9rCm6q8nM2gTtx/+AEqIknjXxRCVS1lyxZHppD2tlaYpkplz3UdJEnzXTJPMSigAo7lncqMuWvJivEKVQnZGY+JaOmEWd+KRor0O8JcuY2xztKP8wEakiCzPXQZxO+FicYE5l62ZpZdZgVlkmT5ZCCjTyI84SIgF571reSs7Hvz6zEKmLoeecR5u1nCShcKhesqC+1syO3FDtmP7fD6AgWTCRPtpK11Q8XNBgcmIYYc1ctlULTBlAPjLmIosSqwHK8GrgCtEiwxq3Ua0Qpo2h6Z8woValN6ydtT7BvM6v3aLtF/6ODokejC0iO+RGeFCUVwRcp11zXHNYyFGoSFw9PDCwISsSJAIa8ofi5NOkxiq7z7HZqn2m26T9pdepS7AjuRrE2dD73hHupv1ADWccpiqON71C3UuqUu9WkFiAV8tTj00ARWA6BS5QIKwRjAJm863k1dZJymi/hbbkr7WrGKoWq6WuqLTuvDTHKtNw4J/uR/33Cz0aqifYM2k+DEeATZZRL1NCUthODkkUQSg3myvGHg8R4QKs9Nvm2tkOztDDb7sqtS+xm694sLyzTLn6wIrKrtUP4kvv+/y0Cg0YnSQFMO05CUIeSPxLik2+TJ9JSUToPLYz/SgTHVMQIwPq9Q3p79zv0V/IicCouue2YLUethe5Mr5GxRjOZNjX4xbww/x6CdoVgSEYLE012TyGQihGpkf3RiNEQz9+OAwwLyY2G3gPUQMf90DrEeDn1RDNzsVZwNe8YrsDvLK+V8PNyd7RStvH5QHxofxKCKYTWh4VKI0wgTe+PB1Ah0H0QGo+ADrbMywsMSMzGX4OaQNJ+HTtPeP02d7ROcs3xvvCnMEjwonEt8iMztfVXt7e5wryk/wnB3QRKhsAJLErBTLLNuI5Mzu4Onc4hDQBLxkoByAIF2YNawNm+aTvb+YQ3sXWxdA9zE3JCch5yJbKTs6A0wLan+Eb6jLznfwRBkYP9hfdH8AmaiyzMHszrzRKNFAy1C70KdcjsRy5FC8MVgN1+s7xpek54sDbbdZm0sfPo87/ztbQFtSk2FreCuV97Hj0vfwKBSANwBSwG7whtiZ6Ku4sAS6uLfkr9Ci4JGkfMhlFEtoKKgN0+/Hz2+xp5szgLNys2GXWZNWw1ULXDNr23d7inOgC79z19fwTBAILixF9F6oc7SAnJEEmLifqJnkl6SJSH9IajRWvD2cJ5wJi/An2DvCe6uLl/eEL3x/dR9yG3NbdK+Bw44jnU+yo8V33RP0uA+8IWw5HE5AXFRu/HXofPSADINMeuBzFGRUWxRH5DNkHjAI+/RX4O/PT7v/q2+d85fLjRuN744zkbeYO6VfsLPBt9Pn4q/1cAuoGMgsTD3ESMxVHF54YMhkAGQ4YZhYXFDYR3A0lCi4GGQIG/hP6XvYF8x7wwO3569bqW+qK6l7rzuzL7kTxI/RQ97H6Kf6dAfUEFAjlClMNTA/FELQRFBLnETAR+A9MDjoM1gk0B2oEjwG6/gD8dvkv9zv1qPN+8sXxgPGs8UfyR/Ok9E72N/hO+oL8v/70ABADAwXABjkIZQk+CsAK6gq9Cj4KdAloCCQHtgUpBI0C7QBZ/9v9f/xP+1H6jfkF+bv4rvjc+EH51fmS+m/7Y/xl/Wv+bP9fAD4BAwKnAigDgwO5A8oDuQOJAz4D3wJwAvkBfwEHAZgANQDj/6P/d/9f/1z/av+H/7D/4f8TAEQAbwCQAKIAowCRAGoALwDi/4L/Fv+g/ib+rf08/dj8iPxR/Df8P/xs/L78Nf3R/Y7+Z/9VAFQBWQJdA1YEOgX/BZ8GEAdMB04HFAebBuYF9gTRA38CCQF6/9z9Pfyr+jT55PfJ9u71W/UZ9S31mfVc9nX32/iI+m/8gv6yAO8CJwVHBz0J+QpqDIINNw6ADlcOuw2tDDMLVgkjB6gE+AEo/0z8fPnO9lj0MPJp8BLvOu7q7Sfu8u5J8CTydvQv9z36if34AHIE2wcYCw0OoRDAElQUUBWpFVkVXxTBEocQwA2CCuIG+wLt/tX61PYK85bvlOwf6kvoKufI5irnUeg36s/sCPDL8/z3fPwnAd0FdQrNDsASLxb8GA8bVRzCHE4c+xrQGNsVMRLrDSoJEgTJ/nj5SfRk7/LqFufx457hMuC63z7gu+Er5Hvnlutd8Kz1XPtAAS0H8gxjElQXnRsZH60hQCPDIzEjiSHXHiwboxZdEYELOwW8/jX42/He62/muuHl3RHbV9nG2GfZN9sq3i7iJOfp7FDzK/pCAWIIUQ/YFcUb5yATJSgoCiqoKvspBCjQJHUgFBvTFOENdAbF/g73jO966BHig9z/16nUn9Ly0azSyNQ72OvctuJy6evw6fguAXsJjxEqGQ8gCCbkKnsurjBqMaYwZS61KrIlfh9KGEsQvQfk/gP2X+085dvdd9dE0mzOD8xEyxLMds5h0rfXUN775X7umfcEAXgKqxNUHC8k/SqIMKE0JzcEOC03pzSCMNwq3yO/G7oSFAkZ/xT1VOsm4tLZmtK5zF7IrsXAxJ/FRsijzJfS9tmI4g3sPPbFAFkLpBVWHyIowi/6NZU6cD1vPoo9xDowNvAvMSgvHywVdwpi/0H0bek53/bV7s1ix4XCgL9uvlm/PMIFx5DNrNUd35rp1PRyAB0MeRctIuUrUzQ1O1NAgkOnRLhDuEC8O+k0cSyVIp8X5Au//4vzqud43E3SeclDwuW8i7lRuEW5YLyNwabId9G82yjnYvMMAMUMKRnYJHUvrTg2QNRFWUmnSrFJfUYgQcI5mzDvJREaWg0tAPLyDebk2dfOPMVgvYO307NwsmiztLY/vN7DWs1p2Ljk6fGU/1ANsxpUJ9AyzDz5RBZL8E5oUHBPDUxXRnc+qjQ6KX0c1g6vAHXyl+SA15fLO8G+uGOyXa7QrMetQLEgtz2/Wcko1U/iavAK/74NFhygKfM1rUB6SRNQQ1TnVfFUZFFcSwRDmzhxLOIeVxBBARXyR+NM1ZHIer1ftImtL6l0p2ioB6w2sse6ecX80e/f5+5w/hEOUh28K904T0S2TchUTVkfWy1aflYrUGNHaTyRLz0h2xHjAdDxHuJJ08TF+rlHsPmoSqRhok+jDqeErYC2vsHozprdY+3H/UgOZx6lLYw7rUepUTJZCl4LYCJfVVu/VJFLEUCXMosjXxOSAqbxHeF50TTDvrZ5rLektZ+dnYCeWqIPqWyyKr7wy1Tb3+sS/WUOVR9cL/09xkpRVUxddmKnZMpj5V8TWYlPj0OANcgl4RRNA5bxQ+Dcz+HAyLP4qMagc5sqmQCa753bpJCuw7oYyR/ZX+pR/GgOGyDfMDBAmE2rWBRhjmbvaCFoKmQlXUlT30ZIOPQnYBYUBKDxkN9zzs6+G7HGpSidhpcNldOV0ZntoO+qi7dhxv/W5OiF+1IOuyAuMiRCIVC1W4ZkT2rgbCRsH2jvYMtW/knsOgkq1xfjBMHxBN8+zfq8t67louGZ85NJkfuRBJZHnY2nhrTQw/XUcOey+iUONCFJM9hDX1JtXqFntW12cM9vw2tvZAxa6ExqPQcsRxm6Bfrxnt49zGa7nqxXoPOWu5DijX6OjJLumW2kt7FowQTTBebY+eENhyExNEtFU1TQYGJqvXCvcx9zEG+gZwldmk+9P+otqxqXBknyXd5vyxO60KoenmCU4o3Zil2La4/mlpOhI68rvzDRp+T5+IgNtiHkNH5G+VXeYsdsZ3OHdhB2BHKAar5fEVLjQa8vAxx3B6zyQd7WygK5UKk7nCmSaYsxiJuIpYwwlAOfyqwcvXrPV+MY+BsNwCFkNW5HU1eWZM9urnX9eKF4m3QLbSliSlTZQ1QxSx1ZCCLzSd5wyjK4HaivmlCQU4nuhTyGPIrQkb6csao/u+bNF+I295wMpyGxNR5IYFj3ZXhwk3cOe8561XY/b0dkQ1adRdcygh47Carzct48yqK3N6d6mdeOoIcPhEGEM4jIj8ea2qiVuXbM6uBU9g0MbCHMNY5IH1n/ZsJxE3m5fJd8rXgZcRZm+FcsRzQ0pB8bCkH0vt45ylO3nqadmL2NU4aYgquCi4YcjiGZSKchuCvL0t929W4LESG2Nb1IkVmwZ6xyLnr8ffl9I3qYcpJnZ1mESGs1sSD3Cub0KN9nykO3U6YZmASNa4WJgX2BR4XLjM+X/KXmtgnK0d6d9MIKlyBwNa1ItlkJaDVz43rXfvN+NXu6c7toj1qiSXg2piHNC5j1sd/EynO3U6bsl6uM6YTjgLiAaITZi9CW+aTltRHJ6d3L8wsK/x/8NF9IkFkKaF1zMXtJf4R/4Xt8dI9pbVuFSlo3gSKbDFT2V+BPy9+3oKYWmLKMzoSmgFuA74NHiyiWQKQgtUbIHN0B80oJTB9bNNRHHlm1ZyZzGXtRf6t/J3zfdAtqAFwrSw84QCNgDRn3F+EGzIi4NqeWmBmNGYXTgGmA3YMVi9iV06OZtKjHa9xC8oIIfx6PMw1HY1gKZ5BynHrvfml/BnzgdC9qR1yTS5U44SMZDuX38OHnzGy5Fqhsmd+NyYVpgeCAMYREi+CVs6NRtDrH2tuQ8bQHmh2ZMg1GYFcKZptxuXklfr1+fnuAdPtpQFy6S+s4YyTEDrX44eLxzYi6PKmVmgKP3oZngsCB7YTUi0GW4aNKtP3GaNvs8OIGnxx8MdZEFla4ZEpwcnjzfKl9j3q/c21p6luhSw45xCRgD4j55uMhz9u7qaoQnIGQVojNgwmDD4bHjPyWXqSFtPPGGNtZ8A4GkBs5MGhDiFQUY51uyXZZeyx8OnmccoZoRltFS/84AiXqD1z6/uR10GK9WKzbnVuSMIqZhbqEl4cajhCYKqUCtRzH7NrX7zoFcBrTLsdBuFIiYZdsv3RbeUd6f3cYcUVnU1qnSrs4HCViEDD7J+bs0Ry/Sa70n4yUaozKh9GGhInOj32ZRabCtXrH5Npp72gEPxlNLfU/p1DjXjtqVnL4dv53YHU0b6tlEFnFSUM4EiXGEAD8XueC0wbBeLBYohOXAY9dikyJ1YvikUObr6fFtg3IAtsQ75kDARinK/Q9Wk5bXIpnkW81dFF13nLxbLljflehSJU34CQUEcz8o+g21R3D4rIEpe6Z85FRjSuMh45UlGGdaakLuNbIR9vN7tECtxbmKcg700uLWYdkc2wScUJy+29Qam9hnlU5R7E2iCRLEZH98ekF117FhrX2pxidPZWikGmPmpEil9afcKuUudXJs9uj7g8CZRULKHI5FEl4VjZh/miTbdVuumxUZ9BecFOORZc1CCRpEU7+SOvr2MfHX7grq4+g3JhNlASTCpVLmqCixK1huwvLSNyR7lcBCxQZJvY2IUYjU5pdNmW8aQxrHGn/Y9xb9VChQ0Y0XyNuEQH/pOzo2lXKa7uerk+kzZxQmPuW1JjNnb2lZLBvvXbMBd2a7qoArBITJFg0/UKST7dZHWGPZepmJWVSYJZYME5yQcAyjSJYEaj/BO733ATNpr5MslWoC6GnnEib9pykoSupTrO+vxjO7N2+7goASxH7IZkxqz/HS49VuVwQYXJi2WBRXABVIUsDPwMxkiEmEUEAZu8X39LPDcIztp2slKVNoeifbaHOpeisgbZNwu/P+9797nj/6Q/UH70uMDzHRyhRDVhDXKpdOVz+Vx1Ry0dUPBIvbSDYEMwAx/BE4bvSnMVMuiKxYqpAptikNaZIqvGw+rkaxfrRNeBa7/T+iQ6hHcgrjziVQ4ZMHlMsV5NYS1deU+9MMERoOe0sHx9tEEcBJvJ847zVT8mWvuG1cq95qxOqSasOr0S1t70kyDnUl+HU74L+LQ1lG7woyzQ1P6xH703RUTRTEVJzTnlIUkBBNpQqqR3kD7EBgPO85dHYI80Kw9S6vrT2sJavprAdtNy5tcFpy6vWIuNs8CH+1gsiGZ0l6DCsOqBChkg0TJBNkkxCSb9DNDzfMgooCRw9DwgC0/QB6PjbE9Gmx/i/Q7qwtlq1R7Zvube+8sXnzk7Z1eQi8dT9hwraFm8i6yz/NWU96EJdRq1H0EbPQ8Q+2TdGL08lQhp4DkwCHfZK6i3fHdVlzEjF+r+kvFu7KbwCv9DDasqb0iDcsOb28Zr9QQmSFDQf1ygwMQI4GD1PQI5B0UAePo05RTN4K2UiVBiVDXsCXveT7G3iOtlB0b7K4MXLwpXBRMLRxCTJGs+C1iHfsejo8nb9BghKEvAbsCRGLHoyHjcPOjs7mTozOB00ei54J08fQBaTDJQCkvjZ7rTlad041lbQ7sshyQLIlsjWyq/O/tOa2k3i2Or582f92QYGEKcYeyBFJ9Ms/TCkM7Y0LzQUMnkufSlIIw4cBxR0C5gCufka8f/opOFD2wrWINKgz5zOGM8O0WvUFNng3qLlI+0n9W/9uQXIDVsVOhwxIhMnvCoTLQguly3FK6UoUSTtHqQYqxE3CoUC0fpU80vs6eVf4Nbbb9hD1l7VxdVy11XaVd5R4x/pkO9y9o39qQSSCxAS8xcPHT0hXyRhJjQn1iZNJaYi+h5oGhUVLQ/eCFsC2PuF9ZTvMuqG5bXh194D3ULcl9z+3Wjgv+Po58DsHvLZ98L9qwNnCckOqRPjF1cb7R2UH0Eg8x+vHoEcfhm+FWMRjwxpBxoCzfyq99jye+616qDnUuXb40LjieOs5J7mTumj7IPwzPRc+Q/+vwJJB4kLYQ+yEmcVaxeyGDUZ9BjyFzsW3xPzEJAN0gnYBcIBsP3B+RP2wvLm75Tt2+vF6ljqlep36/Ps/O5+8WX0l/f6+nP+5gE6BVQIHQuBDXEP3hDBERYS3REbEdkPIw4KDKAJ+gYtBFIBf/7I+0P5AvcW9YvzavK78X/xtfFY8mHzxPR09mL4fPqx/O/+IgE7AysF4gZVCHsJTQrHCuoKtgowCmAJTwgHB5YFBwRqAssAOP+9/WT8N/s++n/5/Pi3+LD44/hL+eP5o/qD+3j8e/2B/oH/cwBQARICswIxA4kDvAPKA7YDgwM3A9YCZwLvAXUB/QCPAC0A3f+e/3T/Xv9c/2z/iv+0/+X/FwBIAHMAkgCjAKMAjwBmACkA2v96/wz/lv4b/qP9M/3Q/IL8Tfw2/EH8cfzG/EH94P2f/nr/agBpAW8CcwNqBEsFDgaqBhcHTgdMBwwHjgbUBd8EtwNhAugAV/+5/Rv8i/oW+cv3tPbf9VP1GPUz9ab1cfaQ9/34rvqa/LD+4gAfA1UFcgdlCRoLhQyVDUEOgQ5ODqkNkgwPCyoJ8AZwBL0B6/4P/EH5l/Yn9AbySPD77i7u6e0y7grvbPBR8qz0bveC+tH9QgG8BCMIWgtIDtMQ5xJvFF4VqRVLFUMUlxJREIANOAqRBqYClv5/+oH2vfJR71rs8eks6BvnyeY753PoaOoO7VPwIPRZ+N78jAFABtUKJQ8PE3EWLxkyG2ccwRw7HNUamRiUFdsRig3BCKIDWP4I+d3zAO+Z6szmt+N34R7gvN9U4ObhaeTM5/bryfAi9tj7vwGqB2oN0hK3F+8bWh/YIVUjwiMYI1ohkh7UGjkW5RD+CrEEMf6s91fxZOsD5l/hnt3h2j/ZyNiC2Wvbdt6P4pjnbO3f88D62wH4COEPXRY7HEkhYCVcKCQqpirdKcsnfiQMIJYaRRRHDdIFIP5r9vDu6ueR4RjcrNdx1IPS9NHL0gXVk9hc3T3jCuqR8Zj54AEqCjYSxBmYIHsmPiu4Ls0waDGEMCQuVyo4Je4epheZDwIHJv5H9avsl+RJ3fzW5NErzu/LRcs1zLvOxtI42OreqeY872D4zwFAC2oUBR3LJIEr7jDnNEo3AjgHN140FzBTKjwjBhvxEUEIQv5A9Inqa+Es2Q/STMwUyInFwcTGxZLIE80n06LaS+Ph7Bv3qAE5DHoWHCDRKFUwbDbkOpc9bz5hPXQ6uzVZL30nYh5NFI0JdP5W84zoad4+1VPN6cYywla/br6Dv5DCgMcuzmnW89+E6sn1bAEUDWUYByOmLPY0tDuqQK5DqESMQ2FAPDtENKwrtSGrFuQKuv6J8rPmlNuC0c7IvsGJvFy5ULhyubq8EsJSyUXSptwm6G30HAHSDSsaxiVIMF85wkA0RotJqUqCSR9GlkAQOcUv/SQIGUQME//a8QHl7Nj7zYLEz7wet5+zbrKYsxW3zryXxDfOZdnL5QnzuQByDskbVii1M409kUV/SydPbFA/T6lLw0W4PcUzNShhG6wNgP9J8XbjddaqynPAIbj2sSSuy6z5raaxuLcCwEbKNdZ0457xRAD1DkAdtSrpNn1BHUqFUH9U7FW+VPxQwEo5Qqc3XCu0HRkP/v/U8BPiLtSTx6O8trMTrfCobqecqHKs1rKXu3TGGdMm4S7wvv9cD5Ae4izjOSxFZE5CVY9ZJlv5WRBWh0+NRmg7bC79H4oQiwB88NjgGtK2xBW5k697qAakWaKEo36nLK5at8XCFNDi3rzuKP+mD7cf3S6hPJhIY1K0WVFeFGDtXuNaE1SxSgQ/ZDE7Iv0RKAFA8MXfOdAXwsy1uqsxpGyfk522ns6ivalQsz6/Ks2s3ErthP7UD7UgozAhP75LFVbWXcNismSUY29fYlihTnZCPzRqJG8T0wEf8Nrejc62v8qyL6g3oCSbHpk2mmaekKV9r+G7XsqF2tnr0/3oD4whNjJjQZxOelmmYeBm/WjrZ7FjblxYUrxF+zaHJt4UigIY8BjeFc2VvRCw8qSSnDKX/pQJlkuap6Hjq7O4tMdy2GzqF/3hDzoikzNkQzBRjVwgZaVq8Wzua6RnM2DSVdFIlDmQKEkWSwMs8H3d0su0u6GtCKJEmZqTN5ExkoCWBp6IqLe1LcV01gXpUfzCD8EiuzQkRXpTTl9CaBBuinCab0ZrrmMNWbNLBzyCKqwXFQRX8ArdxMoVun6rcZ9Oll2QzY2zjgqTsZpvpfCyzsKO1Kbng/uKDyEjrzWiRndVumEKax5xxXPqcpFu3GYFXF5OUj5bLAUZ5gSa8L3c7Mm4uKepMJ20k3+NwYqRi+qPq5eaomKwmcDD0lLmsPo8D1sjbTbeRydX0GN2bcxzoXbddYRxuWm2Xs9QcEAXLlMavAXy8JfcSMmctx6oRZt4kQGLFojOiCSN+JQNoA+ukr4W0Qvl2PnaDm8j9jbYSIpYj2WEbxh2GXlveBx0QmwdYQNTYEK1L5MblQZf8ZXc2cjDtuOmspmZj+eI0IVthruKmZLLnfururyIz9Pj/vhjDl4jTDeQSZ1Z9mYycQF4LnueelZ2dW45Y/hUH0QyMcMccAff8bfcncgttvald5gajjCH74NwhLKIk5DXmyeqFbsdzqziI/jaDSsjbjcGSmNaBWiBcoV523xofC94T3AGZapWqkWLMuAdSghw8vzclMjXtVillZf8jN+FdILZggmH5o4ympeopLnWzJnhSvdBDdUiXjc7Stpaumhvc6R6In7MfaZ5znGCZhhYAEe/M+keIQkR82LdvcjDtQelDJc/jPOEYoGpgcSFlY3fmEynari3y5vgdPaZDGAiHTcwSgRbF2n8c1x7/37Ifrl68HKrZz9ZHUjKNNwf9Qm/8+fdFsnutQSl25bii26EuoDhgOOEoozgl0imarfAyrTfpPXlC8shrDblSeFaHGkodK57c39cf2d7tXN/aB5aAEmsNbYgwQp69IrenslYtk2lA5fni1CEeoCCgGiEDYw3l46lpLb0yefe2/QlCxkhDDZcSXJayWjzc5h7fn+Gf7B7GXT9aLNaqEliNnYhhgs/9UrfVMoAt+KlgZdLjJmEpICNgFKE2Ivklh+lG7ZUyTXeG/RcCkwgQDWWSLhZIGhecx17H39Gf5J7HnQlafxaEkrqNhkiQQwL9iTgNsvjt8GmVZgQjUeFOIEBgaSEBIzplvyk0LXjyKDdZ/OMCWUfSTSWR7RYIWdrcjx6V36efg17wXP0aPlaPUpDN54i7wzf9hfhQcwAueinfpkyjlqGNILegVyFkYxGlyalxbWiyCvdv/K2CGceKjNcRmlXzmUacfd4J32MfSF6BHNraKhaKUpsNwQjkA229yDidc1Wulap+pqxj9GHmIMlg3uGf437l52l+rWSyNXcJvLdB1Qd4zHrRNlVKWRtb053kHsRfNB45nGJZwpa00ljN0kjIQ6Q+D3jzs7huwirx5yLkaqJYoXShP+Hzo4KmWOmcLa0yKLcnfECBy0ceDBGQwVUNWJnbUV1k3kwehl3Z3BOZh1ZPUknN2sjoQ5r+W3kS9Cgvf2s456+k+SLkYfnhuiJfJBxmnanKLcKyZHcJvEoBvUa6i5uQfFR818Ia9xyMnfqd/90iG67ZOJXZEi4NmkjDg9E+q3l6dGQvzGvSqFHlnyOI4pfiTSMipIwnNmoIriTyaXcxPBQBa4ZPS1nP55PZl1VaBZwb3Q/dYFyTGzQYllWSEcUNkMjZg8a+/vmpdOuwaKx+6MkmW+RFo07jOKO9pRGnomqXrlRyt/cdvB9BFoYcisyPRBNkVpPZfZsTXEzcqNvsmmPYIJU60U8NfYiqQ/r+1ToftX5w02086ZSnLqUZpB2j/CRvpeyoIas3LpFyz/dPvCvA/sWjCnTOklKeFf6YYBpz23JbmZsvGb4XV9STEQuNIMi1A+1/LfpcNdsxi+3LqrNn1yYEpQPk1uV4Jpzo9CunLxtzMbdH/DpApQVjidMOE1HHVRZXrVl92kCa85obmMOW/BPa0LrMugh6A92/SLredkFyUS6qK2So0+cFZgDlyCZWp6GpmSxnb7KzXTeGPAtAicUeyWiNR9Eg1BwWpphymXiZtxkyV/RVzZNSkBzMSYh4Q8t/pHsltvBy4q9X7Gep5GgbJxOmz2dKqLrqUK038Bdz0vfLPB8AbYSVCPWMsJAsExDVjJdSmFtYpRgz1tGVDRK6T3HLzsgwA/Y/gPuxd2czvzAT7Xtqx2lE6Hsn6+hTKadrWi3X8Mj0UngWvDYAEQRHiHsLzs9pkjUUYJYfFynXfpbhVdtUOtGSjvmLSgfhA91/3bvA+CU0ZjEc7l5sPCpB6bapHGmvqqcsdS6HcYe03DhpPBCANIP2h7nLIw5aUQqTY5TZFeSWBBX7VJKTF1DbTjSK+0dLA8CAOfwTOKk1FnIx71AtQSvQqsUqoGre6/jtYO+F8lL1cDiC/G8/2IOjBzLKbo1/j9ISFpOB1I1U9xRCk7fR40/VjWLKYoctw6AAFTyn+TL1zvMSMI9ule0wbCUr9mwgbRvunPCS8yq1zfkjvFH//cMNRqbJskxaTsyQ+tIaEySTWFM4kgxQ347BTIUJ/8aJg7tALzz+OYD2zvQ8MZqv+G5frZXtXW2zLk+v6HGuM862tXlLvLk/pML2hdaI7strjbuPUZDjkawR6RGd0NCPjI3fi5sJE0Zdw1GARz1VelL3lTUvMvExJ+/dLxYu1K8Vr9MxArLWtP53Jvn7PKU/jcKfBUNIJcp0jGAOHA9fUCSQapAzj0XOa0ywiqXIXQXqgyMAXP2s+ue4YPYp9BFyozFn8KRwWnCHMWUyavPL9fk34bpx/NY/uUIHxO1HF4l2SztMm43Ojo/O3c67De0M/Et1CaVHncVwAu+Ab/3D+765MTcrdXpz6LL+cj+x7bIGcsSz3/UNdv74pbrwPQx/qAHxBBXGRYhyCc6LUUxyzO7NBE01TEcLgQptyJpG1UTuQraAf74Z/Ba6BLhyNqp1dzRfM+YzjPPSNHC1IXZaN885srt1vUg/mgGbw72FcMcpCJtJ/sqNS0MLn0tjytUKOgjbx4WGBARlQngAS76ufK762rl9N+C2zXYI9Za1dzVpNeg2rfexeOj6R/wCPcl/kAFIQyUEmgYcR2KIZUkfiY4J8EmHyViIqEe/RmcFKkOVAjPAU/7AvUb78fpLOVu4abe6Nw+3KvcKN6m4BHkSegu7ZbyVvhB/igE3gk3DwoUNBiXGxoerB9EIOIfiR5JHDQZZxUAESMM+AaoAV78P/d28iXubOpn5yvlxeM/45njzuTR5o/p8ezb8Cv1wPl0/iIDpwfgC60P8hKYFY0XxRg3GeUY1BcPFqYTrxBDDX8JgQVqAVr9b/nI9YDyr+9p7b3rtepX6qLqkesZ7S3vuPGm9N33RPu+/i8CfgWSCFQLrw2UD/YQzhEXEtIRBRG4D/oN2QtpCb8G8QMVAUP+kPsQ+db28fRu81fysvF/8b/xa/J78+b0m/aO+Kv64fwe/1ABZgNSBQMHcAiPCVoKzQroCq0KIQpMCTUI6gZ1BeUDRwKpABj/n/1J/CH7LPpy+fT4tPiy+On4Vvny+bX6lvuN/JH9l/6W/4YAYQEgAr8COgOPA78DygOzA34DMAPNAl0C5QFqAfQAhgAmANf/mv9x/13/Xf9u/43/uP/p/xsATAB2AJQApACiAIwAYgAjANP/cf8D/4v+Ef6Z/Sr9yfx9/Er8NvxE/Hf8z/xN/e79sP6N/38AfwGFAogDfQRdBR0GtQYdB1AHSQcEB4EGwgXJBJwDQwLIADX/lv35+2r6+fix96D20PVK9Rb1OfWz9YX2q/ce+dX6xfze/hEBTwOEBZ4HjAk8C58MqA1LDoEORQ6WDXUM6gr+CL0GOASBAa7+0/sG+WD29vPd8Sfw5e4j7urtP+4i74/wf/Lj9Kz3xvoa/o0BBgVpCJsLgg4EEQ0TiRRrFagVOxUlFGwSGhA+De0JPwZQAj7+KPou9nDyDe8h7MXpDugM58vmTueV6JnqTu2f8Hf0t/hB/fEBpAY0C30PXROyFmIZVBt3HL4cJRyuGmAYSxWFESgNVggzA+b9l/hx853uQuqC5n/jUeEN4L/fbOAT4qnkHehX7DfxmfZV/D4CJwjiDUATGBhBHJgfAiJpI74j/SIpIUseehrOFWwQewooBKX9IvfT8OvqmOUG4Vrds9oq2czYn9mh28Pe8eIN6PDtbvRX+3MCjglwEOEWrxyrIasljig7KqIqvSmRJyokoR8XGrUTrAwvBXv9yfVV7lznE+Gv21vXO9Rp0vjR7dJE1e3Yz93G46XqOPJH+pEC2QrdEl4aICHsJpUr8i7oMGQxYDDgLfYpvSRcHgEX5g5HBmj9jPT56/LjuNyD1ofR7M3Ry0rLXMwDzy3Tu9iF31nn+u8n+ZkCBwwoFbMdZiUCLFExKjVqN/433zYSNKovyCmXIkwaJxFuB2z9bfPA6bHgiNiG0ePLzcdnxcXE8cXiyIbNutNQ2xDktu3694oCGA1PF98gfinmMNw2Lzu8PWs+NT0gOkI1vy7GJpMdbROiCIX9a/Ks55vdiNS7zHPG4sEvv3K+sb/owv7H0M4p18zgbuu/9mYCCg5QGeAjZS2WNTA8/kDXQ6VEXEMGQLg6mzPjKtMgthXjCbT9iPG+5bHautAnyDzBMbwwuVO4o7kYvZvCAcoV05HdJul59SwC3g4rG7ImGTEOOklBkUa5SaZKUEm9RQhAWjjtLggk/xctC/j9w/D34/bXIc3Mw0G8vrZus3CyzLN6t2C9VMUYz2Pa3uYq9N8BlA/eHFUplzRLPiRG40taT2pQCk9CSyxF9jzdMi8nRBqADE/+HPBX4mzVv8muv4e3jbHvrcysL64RslS4y8A1y0TXm+TT8n4BLBBpHscr3DdJQrxK8lC3VO1Vh1SOUB9KakGxNkQqhBzaDbn+k+/h4BPTmMbQuxGzoqy1qG2n1KjirHqza7xxxzjUX+J38QwBphDLHwYu5joGRg9PuFXLWShbwFmeVd5OtEVkOkUtvB45DzT/KO+T3+7QrMM1uOOuAqjHo1aivaPzp9iuObjQw0PRLOAX8IgAAxEFIREwsz1/SRhTMlqTXhhgs15sWmNTzUnzPS4w6SCaEL//2u5u3v3O/cDftACrr6Mnn46d8J5Ho3GqObRVwGfOBd617vb/QhEUIugxQkCyTNVWXF4KY7hkWWP1XqtXtE1aQfwyCSP8EVgAqO5z3UDNjr7QsWqnrp/bmhaZcZrjnkmmbrADvajL7dtU7Vb/ZhH7IoozkUKcT0NaM2IsZwVpsGczY7FbYlGVRKs1GCVcE/8Aku6h3LrLX7wLrySkAZzklvSURJbKmmai3azfuQrJ59n166n+bxG4I/U0n0Q8UmBdtWX2avxss2skZ3Ff1VShRzk4FSe4FLIBl+7422nKcrqQrDChrJhGkyuRbZICl8qeiKnsto7G9deb6vH9XRFNJCs2bEaQVCpg3mhmbpdwXm/DauhiClh6SqI6+ygPFm8Cte5420/Jx7hiqpGesJUFkL6N7o6Nk3mbdaYttDjEGtZJ6S/9MxG5JCo39UeXVp9irGt5cdVzr3INbhJm/FoeTeM8yipdFzQD7O4g22vIX7eCqEecD5Mija+Ky4tvkHaYpaOmsQzCWdT/52f88BD+JPM3O0lRWL1kHm4rdLR2o3X/cO1oqF2IT/o+fiyiGAAEOu/u2r3HO7bwplWazJCgigKICImqjcWVHaFZrwvAs9LB5pj7lxAcJYY4Pkq7WYNmMnB8di95NniWc3RrDGC3UeRAFC7ZGdAEnu/k2kXHWbWtpbuY6I6BiLmFpYZBi2mT3p5IrTm+LdGQ5cb6KRAUJeQ4/krWWvBn5nFpeEZ7Z3rQdaVtJWKoU55Ciy8CG6QFFvD+2gHHu7S6pHqXZI3GhtSDp4Q3iWOR7Jx4q5i8x89w5PL5pw/oJA05e0uiWwRpOXPxefd8M3yqd39v8GNXVSVE3zAaHHgGoPA82/LGX7QWpJOWQYxxhVeCDYOOh7aPSJvqqSq7hM5h4x75FA+YJAM5tksfXL9pLHQTe0B+mX0ief5wa2XEVnhFDzIfHUsHPPGd2xXHRrTAowWWgIuChEOB24FHhmWO9pmgqPO5Z81m4kz4cA4mJMY4r0tNXCBqvHTPeyB/l343eiFylGbqV5RGGTMQHhsI5/Ef3GvHbbS5o9GVIIv6g5eAEYFkhXCN9pidp/O4ccyB4X73vg2VI1g4Z0stXChq63QjfJd/LX/neudyamfKWHhH+jPpHucIoPLA3PHH1bQApPWVIYvZg1WAr4DnhNqMS5jipiy4pcu04Lb2/wzkIro34ErAW9hpuXQRfKV/Wn8ye05z6mdgWSFIsTSpH6wJZfN/3abIe7WTpHGWhIsfhHyAt4DPhKOM9pdwpqG3BMsB4PX1NQwXIu82G0oHWzBpJ3SYe0h/HX8Xe1VzFGitWY1IPDVPIGgKM/Ra3ojJXrZxpUWXRozLhA2BKYEdhcuM95dKplO3kMpp3z71YwsvIfc1GkkEWjFoNXO5eoN+d36Vevxy52etWb1ImTXYIBoLCfVP35XKfLeZpm6YaI3dhQeCBILShVSNUJhvpkO3Ssrv3pL0igouINU030e4WN9m5HF1eVV9aH2teUNyY2diWa1IxzVCIb8L5fVc4MzL1LgIqOqZ545Th2mDR4Pthj6OAZnhpnK3NMqU3vPzrAkWH4oza0YmVzllOHDNd7978XtgeClxhmbJWF5IxDWOIVYMxfZ+4SnNY7q9qbmbwZAriTKF8oRtiIiPCZqgp+K3T8pZ3mTzygjpHRoywURPVUJjMG7EdcR5EnqtdrBvUWXjV85HkDW3Id4Mp/e14qzOJ7y2q9ed9ZJli1+HA4dSijGRaputqJK4nMpA3uXy6AepHIYw5EI2U/1g0Gtbc2V3z3eXdNdtxWOwVv5GKjW/IVQNifj941HQHb7vrUKggJX8jfCJeYmZjDmTIp0HqoK5HMtK3njyBwdZG9Au1UDdUG1eGmmVcKN0J3UecqBr4mEwVe1FkTSjIbcNaflV5RbSQ8BmsPeiYJjwkOGMUYxDj56VMJ+tq7W6z8t53h/yKAb7GfwsmD5JTpNbEmZ0bYJxHnJFbw1pqV9iU5pEwzNiIQYORvq55vnTlsIYs/SlkZs9lDGQio9Lkl+Yk6GhrSi8t8zM3tvxTgWQGAsrMDx6S3NYuWL8aQVut24NbB9mG11JUQZDwjL8ID8OHfsp6PfVFMUCtjWpEZ/hl9yTIJOxlXqbS6Tfr9y90s1F367xewQcFwEpnzl1SBFVE18vZi1q82p6aNhiOlrlTjJBjTFwIGAO7Pug6QzYuMchubes26LWm9+XEZdymeyeVadostC/Ic/l35jxrwOhFeEm6DY9RXBRJVsRYgBm1maNZDpfCFc4TB8/JDC9H2oOs/wf6zjagMpxvHew7aYboDacWZuKnbSir6o6tQPCpNCr4Jvx7gIhFKwkEDTWQZRN8VamXYBhY2JLYElbh1NCScw8hy7jHloObv2h7HXcac3vv2+0QaurpN6g9Z/2oc6mV65TuHTEW9KZ4bjxOQKdEmYiGDFCPoBJfFLyWLFcn122WwdXuU8GRjw6tyziHTAOHf4l7sPeb9CXw5241a+CqdOl4aSzpjirSrKxuyPHRNSu4u/xkAEZEREgBC6HOjlFyk35U5hXjFjRVndSoUuGQm83tCq5HOsNv/6p7x7hj9Nlx/y8pLScrg+rGaq9q+2vhrZTvw3KYNbq40Ly9gCWD7Ed2CqnNsNA4EjATjlSMFOjUZ1NQkfFPmk0gChpG4sNUf8q8YPjxtZWy4nBqbnzs5CwmK8Qseq0B7s0wzDNrNhN5bDybAAXDkgblyemMiI8wUNMSZhMkE0tTH1IoELEOikxHCbzGQ4N0/+m8u/lEdplzz7G4L6DuU+2WbWntiy6yr9Tx4vQKNvX5jvz9P+eDNgYRCSJLlo3cz6gQ7tGr0d1RhtDvT2HNrMtiCNWGHUMQQAc9GHoa92P0xfLRMRIv0i8Wbt+vK2/y8StyxvU092H6OPzjv8sC2YW4yBUKnAy+zjEPadAkkGAQHs9njgSMgoqxyCTFr8LngCJ9dTq0eDP1xDQ0Mk8xXbCkcGQwmvFBso+0N7XquBc6qf0O//ECfMTeB0KJmktXTO6N2E6QDtSOqI3RzNmLS4m2h2sFOwK5wDs9kbtQeQh3CTVfs9Zy9PI/MfZyF/LeM8D1dHbrONV7Ij1/P5nCIIRBRqwIUkony2KMe4zvDTxM5QxvC2JKCUixBqhEv0JHAFD+LXvtueC4E7aS9Wb0VrPls5Sz4XRHNX42fHf1uZx7oX20v4XBxUPjhZKHRUjxSc4K1QtDi5hLVcrASh9I+8dhhd0EPIIOwGM+R/yLevs5IvfMNv81wXWWNX21djX7doZ3zvkKOqv8J73vv7VBbAMFxPcGNId1iHJJJkmOiepJu8kGyJGHpEZIhQlDssHRAHF+n/0o+5d6dTkKeF33s/cPdzA3FPe5+Bj5Kzone0O89P4wP6kBFQKow9qFIUY1RtFHsIfRiDOH2IeDxzqGA4VnBC3C4gGNwHu+9b2FfLP7SXqMOcF5bLjPuOr4/HkBOfR6UDtM/GL9SP62f6EAwQINQz4DzETyRWvF9YYOBnWGLUX4RVsE2oQ9gwsCSsFEwEF/R75fvVA8nnvP+2h66fqV+qw6qzrQO1f7/Px6PQl+I77CP93AsMF0QiKC9wNtw8OEdkRFhLGEe4Qlw/QDagLMgmEBrQD2AAI/lj73fiq9s30U/NF8qnxgPHJ8X7ylvMH9cP2ufjZ+hH9Tv9+AZEDeAUlB4sIpAlnCtMK5wqlChIKNwkcCMwGVQXDAyQChgD3/oH9L/wK+xr6Zfns+LL4tPjw+GH5AfrG+qr7o/yn/az+q/+ZAHIBLwLLAkIDlAPBA8kDrwN4AygDxAJTAtoBYAHqAH4AHgDR/5b/b/9d/17/cP+R/7z/7f8fAFAAeQCWAKQAoQCJAF0AHQDL/2j/+f6B/gf+kP0h/cL8d/xH/Db8R/x9/Nj8Wf39/cL+of+UAJUBmwKdA5EEbgUrBr8GJAdSB0UH+wZzBq8FsQSBAyUCpwAT/3P91/tK+tz4mPeM9sL1Q/UW9UD1wvWb9sf3QPn9+vD8DP9BAX4DsgXJB7IJXAu5DLkNVA6ADjsOgg1YDMUK0QiKBgAERgFx/pb7zPgq9sbztPEI8NDuGe7s7UzuO++08K3yG/Xs9wv7Y/7XAU8FsAjdC7wONREyE6IUdhWlFSoVBxRAEuIP+wyiCe0F+gHn/dL52/Uk8sru6eua6fLnAOfO5mLnuejN6o/t7fDO9Bb5pP1VAgcHkwvUD6kT8haTGXQbhRy6HA4chBolGAEVLRHFDOsHwgJ0/Sf4B/M77uvpO+ZI4y3h/d/D34bgQeLr5HDoueyl8RH30vy8AqMIWA6tE3gYkBzVHyoieiO5I+Ei9SADHh4aYhXyD/cJngMZ/Zn2UfBz6i7lruAX3YfaFtnS2L/Z2dsT31bjg+h17v707fsLAyQK/hBkFyIdCiL0Jb4oUCqcKpspVCfUIzQflxklEw8MjATW/Cb1u+3O5pfgSNsM1wfUUtL/0RLThtVK2UTeUORA6+Dy9vpDA4gLgxP2GqYhXCfqKyovATFdMTkwmi2TKUAkxx1bFjIOiwWq/NHzR+tP4yncDNYs0bDNtstRy4XMTc+W00DZI+AK6Lrw7/ljA84M5RVhHv4lgCyyMWo1hzf3N7M2wzM7Lzsp8CGRGVwQmgaV/Jry+Oj53+fX/9B8y4nHSMXNxB7GNcn7zU/UANzW5Izu2fhtA/YNIhiiISkqdDFJN3c73T1kPgU9yTnHNCIuDCbDHIwStweX/ILxzebP3NTTJcwAxpbBDL95vuO/QsN/yHPP69em4VrstvdfA/8OORq2JCIuMzapPE5B/UOeRClDpz8yOvAyGSrvH8AU4Qiv/IjwyuTR2fTPgse9wN27CblauNi5er0nw7PK6NN/3ibqhvY9A+oPKRycJ+gxujrOQelG4kmgShlJWEV3P6E3ES4RI/MWFgrd/K3v7eID10rMGMO3u2G2QrN2sgS04rf3vRPG+89j2/PnTPUFA7UQ8R1SKnY1Bj+0RkRMiE9lUNFO1kqRRDA88jEmJiUZVAsf/fHuOuFl1NjI7L7ytiixvq3RrGqugLL0uJfBKMxW2MPlCfS5AmERkB/WLMw4EkNYS1tR6lToVUtUHFB7SZhAtzUrKVMbmgx0/VTusN/70aDFALtxsjWsgKhwpxGpVq0jtEO9csha1ZnjwPJaAu8RBSEnL+Y73Ua1TylWA1olW4NZJ1UxTtZEXDkcLHkd5g3c/dXtUN7Ez6TCWLc4ro2njaNZovyjbKiIrxy53sR00nfhcvHpAV4SUSJEMcI+Y0rJU6pa0F4XYHNe8FmvUuZI3jz2LpYfNg9V/nXtGt3Czee/9bNKqjOj6J6OnTCfxKMpqya1b8Gnz2DfIfBoAbASciMqM2BBok2QV9xeS2O5ZBljdV7wVsJMOUC2MaYhhxDe/jLtDtz2y2q92rCqpiqfl5oVmbKaZJ8Ip2SxKb71zFfd0O7YAOQSaCTbNL1DmFAIW7ticmcIaW9nsGLwWmhQakNYNKcj2BF2/w3tLdthyi67Ca5ao3abm5bxlIaWT5sqo9utD7tiyl7bgO05APwSNCVVNtdFQ1MvXkRmQmsAbXFrnmarXtRTbEbaNpclJxMZAAPtddoDyTS5hKtdoBmY+ZIlka6SiZeTn46qJbjyx3nZM+yQ//gS1iWXN7BHolUBYXRptm6fcB1vO2odYgFXPUk5OXIncRTJABTt6Nndx363TKm2nRaVs4+1jS+PFpRGnICnbrWmxanX7Orb/toSTyaiOERJs1d+Y0lszXHfc25yg21DZe5Z2UtyOzYptBWCAT7thNntxgu2Yqdkm3CSy4ykigyM+ZBHmbak7rKBw/HVreke/qMSnyZ2OZRKdVmkZcFuhHTAdmJ1dHAaaJVcPU6BPeEq7xZEAoLtSNk1xt20yKVrmSeQRYr0h0eJNY6ZljGiprCIwVTUeOhZ/VQSxyYSOqBL6FpxZ9pw2XY+efd3CnOfavZeZ1BkP3AsHhgLA9ztNNm0xfOzfaTKlz2OIoioheSGzYs+lPafm668v9TST+eP/O4RyCZ5OmhMClzlaJNyynhYeyl6RHXPbAxhVFIZQeEtQBnXA03uRtloxU6zg6ODlrSMY4bBg+SEw4k5kgaezqwfvnPRNObC+3MRoiapOuxM3Fz+aexzVnoMffd7HneobtViAFSdQjEvUxqlBNHuftlTxeyy2aKWlY2LCoVBgkmDGYiNkGScQqu1vDTQKuXz+uUQWCalOixNXl2+auJ0fHtYfl99mHgncE9ka1XtQ14wVBt0BWjv2tlxxc2yfqIElceKGIQqgRSC0YY7jxKb+ql/uxrPMuQl+kYQ6yVsOilNkV0ja3d1O3w7f19+rnlLcXllkVYIRWUxQhxCBhDwWNrDxfGydKLMlGSKjIN7gEiB7IVFjhKa9qh/uiXOT+NZ+ZYPXCUBOuVMdF0va6l1kny1f/d+YHoTck9mcVfrRUYyGh0MB8fw99pGxlWzt6LtlGKKaYM2gOSAbYWtjWWZOqi4uVnNguKR+NgOrSRmOWBMCl3hanp1gnzFfyd/rXp8ctJmCViVRv4y2x3RB4vxttv6xvqzSaNolcOKrINbgOmAUoVzjQ2ZxqcrubbMzuHP9w4O4COaOJxLUlw6aul0DHxrf+1+lXqGcv9mWFgFR4szgx6PCFvykdzdx920JqQ6loOLVoTqgFiBnYWZjQuZnKfauD/MNOEW9zoN9iKhN5tKT1s9afhzLnuofkl+F3oxctVmXVg4R+wzDx9ECTTzid3syP21TqVil6SMZoXhgTCCT4YejmCZvafGuPXLteBm9l0M8iF9Nl5JAlrqZ6ly7Hl8fT19Mnl8cVVmFlgtRx80fx/uCRT0md4lyle3v6bfmCKO24ZBg3CDZocDjwyaKqjvuNnLVODC9XoL1iAuNedHblhDZvxwRnjoe8l76XdncH5lg1flRiM00B+LCvr0wd+Iy+m4d6ivmv2Ps4gIhRiF4ohHkA6b4qhXue3LE+Ar9ZIKox+5MzlGk1ZKZPNuPXbvee55O3bzbk9kpFZdRvczAiAbC+P1/+AQzbK6c6rQnDKS7IozhyaHworrkWic6Kn/uTLM8d+k9KgJXB4eMlZEdlQCYpJs1HORd613KXQgbcpieVWVRZkzEyCaC872T+K8zq+8saw+n7+UhI3DiZiJBY3tkxmeOavnuqjM8d8t9L0IAx1hMEFCGFJuX9ppDnHRdAl1tXHvau9gAlSNRAozAiAIDLj3sOOK0Ny+Lq/4oaGXeJCzjG6MqY9Llh+g16wPvFDNFODJ89MHmhuDLvw/fU+PXM5m7G2xcQNy4W5jaL5ePlJFQ0kyzR9iDKD4H+V30jjB57H7pNaaxpMCkKOPrZIFmXqiwK53vSvOW+B48+0GJBqILIo9p0xqWXJjcmo0bp5urmt8ZTlcL1C9QVQxdB+oDIT5m+aA1L/D2bRCqFmea5eskzeTDpYZnCil9LAevznPxuA98wwGoxhyKu86mUkCVshfo2Zeat1qIGg8YmJZ1032Py0w9h7ZDGL6Ieii1m7GAbjLqymiY5uulyWXyZmEnyiocbMFwXrQV+EY8zIFGhdEKCw4WEZZUtVbgmIwZsNmOWSnXjpWNUvwPdIuUx7yDDj7runb2ELJXLuSr0Cmq58GnGqb251Eo3irNrYqw+7RDeIK82AEihUBJkc15UJ0TptXFF6wYVNi/F++WsNSTEisO0UtiR3zDAX8QOso2zjM5b6Ts5uqPqSuoASgQqJVpxWvQrmNxZTT6uIW85kD9hOrI0EyRj9XSiBTXVnhXJFdbFuEVgBPHkUrOYYrmhzbDMb81eyG3U3PmcLLtzavGamjpe2k+aa2q/2yk7wsyGzV7eM6894CYBJGIR4vfjsGRmZOYFTGV4JYjlb9UfRKrEFvNpUphBupDHv9a+7y333SdcY1vAy0N67hqiKq/qtjsC23JsAFy3bXFuV58zACyhDUHuIrkDeEQXRJIk9mUihTZVEsTaFG+T15M3MnSBpdDCH+APBp4sTVdMrNwBq5k7NjsJ+vS7FXtaK7+MMYzrDZZebT85IBNw9YHJAogTPXPExEqEnETIlN9EsVSAtCBzpLMCIl5hj1C7j+kfHp5CDZks6OxVq+Krkktl+13baQulnACMhh0Rjc2udJ9AMBqA3VGSslVS8DOPU+90PlRqpHQka8QjU92jXnLKIiXhdyCz3/HPNu543cy9J1ysfD9L4gvF27rrwIwE3FUszf1K/edOna9IYAIQxOF7ghDysMM3M5FD7OQI9BUkAlPSI4dDFPKfYfsRXTCrH/oPT26QbgHNd7z13J78RQwpTBu8K8xXzK09CP2HHhMuuH9RwAogrFFDketCb3LcozBDiFOj07KjpVN9gy2CyHJR4d4RMYChEAGvZ/7IrjgNue1BfPE8uxyP7H/siny+HPiNVv3F7kFe1Q9sb/LQk+ErIaSCLIKAEuzDEPNLs0zTNQMVotCyiQIR0a7RFBCV4AifcF7xTn89/X2e/UXdE7z5fOcs/E0XjVbdp84HPnGu8194T/xQe6DyYX0B2FIxsocitxLQ0uQy0cK6wnECNuHfUW1w9OCJYA6viF8aDqcOQj3+Daxtfq1VjVEtYP2Dzbft+y5K7qQPE1+Fb/awY9DZkTThkyHh8i+ySyJjknjya9JNMh6h0kGacToQ1AB7gAPfr+8yzu9Oh85OXgSd643D3c2NyB3ijht+QP6QzuhvNR+T//IAXKCg8QyRTTGBIcbh7XH0UguR85HtMbnhi1FDgQSwsXBsUAf/ts9rTxe+3e6fnm4OSf4z/jvuMW5TnnFeqP7Yzx6/WH+j3/5gNhCIoMQxBvE/kVzxflGDcZxRiVF7MVMRMkEKgM2AjUBLsAsPzO+DX1//FE7xftheua6ljqvurI62ntku8v8iv1bPjX+1L/vwIGBg4JwAsJDtkPJBHkERUSuRHWEHYPpQ12C/sISQZ3A5sAzf0h+6v4f/ap9DjzNPKh8YLx1PGR8rLzKvXr9uX4CPtB/X3/qwG8A54FRQemCLcJdArYCuQKnAoDCiEJAQiuBjQFoQMCAmQA1/5j/RT89PoJ+lj55fiw+Lf4+Pht+RD62Pq++7j8vP3C/r//rACDAT0C1gJLA5oDwwPIA6wDcgMgA7sCSQLQAVYB4QB1ABcAy/+S/23/XP9f/3L/lP/A//L/JABUAHwAmAClAJ8AhgBZABcAxP9g/+/+d/79/Yb9Gf27/HL8Rfw2/Er8g/zh/GX9Df7T/rT/qQCrAbECsgOkBH8FOQbKBioHUwdBB/IGZQacBZoEZQMGAoYA8P5R/bX7Kvq/+ID3efa09Tz1FvVH9dD1sfbk92P5JPsc/Tv/cQGuA+AF9AfYCX0L0gzKDVwOfw4wDm0NOwyfCqMIVgbHAwoBNP5a+5L49PWW843x6e+87hDu7u1b7lXv2fDd8lT1LPhR+6z+IQKZBfYIHQz1DmQRVxO6FIEVoRUZFecTExKpD7gMVgmbBaQBj/17+Yn12PGH7rLrcOnW5/Tm0+Z3597oAevR7TvxJvV1+Qf+ugJqB/ELKxD1EzEXwxmTG5IctBz2G1oa6he1FNQQYgx/B1ICAv24953y2u2W6fTlEuMK4e7fyt+h4HHiLuXE6BztFPKJ90/9OwMgCc4OGRTWGN4cECBQIoojsiPCIsAguR3BGfQUdw9zCRQDjvwQ9s/v/OnG5Fjg1txe2gXZ2tjg2RPcZN+84/vo++6P9YT8pAO5CowR5heUHWgiOybsKGMqkyp3KRUnfCPGHhUZkxJzC+kDMfyF9CLtQuYc4OLav9bV0z7SCNI508nVqdm73tzk3euJ86b79QM2DCgUjRsqIsknPCxgLxcxUzEPMFItLSnAIzIdsxV9Dc8E7PsX85fqruKb25jV1NB3zZ7LW8uxzJrPAtTI2cLgveh68bj6LgSUDaEWDR+VJv0sETKnNaE37TeFNnIzyS6rKEch0xiRD8YFv/vI8THoQ99H13zQGMtIxyzF18RPxovJdM7m1LLcneVj77n5TwTUDvUYYiLRKgAysze8O/o9WT7SPG85STSDLVEl8RuqEcsGqfuY8PDlBNwj05PLkMVNwe2+g74YwKDDA8ka0K/YguJH7a34WQT0DyIbiiXdLs42Hj2bQR9Ek0TyQkY/qDlCMkwpCR/IE98HqvuI79fj89gxz+DGQsCMu+W4ZbgRuuC9tsNpy73Ubt8p65P3TQT1ECcdhCizMmM7T0I+RwhKlUrfSO9E4j7lNjQtGCLnFf4IwvuX7ubhEdZ2y2jCMLsIthqzgLJAtE+4kb7WxuHQZdwK6W/2KwTVEQMfTStTNr0/QEehTLNPW1CTTmZK8kNmOwUxGyUFGCgK7vvG7R7gYdPzxy6+YLbHsJKt2qyprvOymLlnwh3Nadnt5kD18wOWErYg5C25OddD70u/URlV31ULVKZP00jDP7o0DiggGloLMPwV7YHe5NCrxDW61LHNq0+oeadSqc+t0LQfvnbJf9bV5Ar0qAM3Ez4iRjDiPK9HV1CVVjZaHVtAWatUgE31Q1I47yo1HJMMhPyE7A7dnc6gwX+2ka0dp1ejYKI/pOqoPrADuu/FqNPE4s/ySgO5E5sjczLOP0JLdVQeWwdfEGAvXnBZ9lH6R8c7ui1BHtEN7PwR7Mfbi8zUvg+zmKm7oq6elJ12n0ek5asWto3C6dC94I/x2gIcFM0kajR6Qo5OR1hXX4djtGTTYvBdMFbNSxY/bDBCIBIPZP2+66var8pJvOiv7qWrnliaGZn5muufy6deslK/Rc7D3k3wWgJhFNMlKTbkRJBRyFs9Y7NnBWkoZydiKVpqTztCAjM1IlQQ6/2I67rZDMkAugytlqLwmliW85TNltmb86PdrkO8vsvY3AzvywGIFK4msTcMR0ZU+F7NZodrAG0qaxJm313NUjNFeTUXJJURgf5w6/XYoMf6t3yqkJ+Ml7GSJZH2kheYYaCXq2K5WMn+2sztLwGSFF4nADnwSK9W02EEagBvoHDVbqxpTGH0VftHzTfnJdISJP9z61rYbcY4tjqo35yDlGaPs413j6aUGZ2QqLS2Fsc52ZHshwCBFOMnFzqPSspYWGTfbBty43MncvNsb2TbWJBK/TmhJwoU0v+S6+rXcsW7tEemhprWkXuMn4pTjIqRHZrLpTq0+sSL113r1f9VFD4o9jrpS5VahWZdb9d0xnYcdeNvQ2d+W+5MBDxDKTsViADL66TXsMSDs6SkhZiHj/CJ7YeOiceOcpdLo/ixCMP21TDqGv8PFHAonDv+TA9cWWh8cTB3R3mxd3hyxWnaXRJP4T3KKmIWRgEc7IfXJsSRslKj3paYjcmHnoUph1+MGZUTofKvQsF91A/pWP6yE3koCjzOTTld02k7cyV5ZHvkebJ09GvtX/tQkD80LH0XCwKF7JHX08PksVGikZUKjAaGtIMnhVWKFZMmnyiuqr8i0/vnkv0/E1soQjxYThJe82qYdLV6Gn20e412zG21YaVSEEF/LYoY0wID7cLXt8N8saGhoJTeiqqEMoKLg6qIaZGFnZ+sQ77n0fXmyPy2EhcoQzyeTplet2uTdd57aX4dfQd4S28uYw1UXkKpLocZnQOV7RnY0MNYsUKhCZQVirSDF4FUgmGHF5AznFirD73P0AHm/fsbEq4nDzygTtBeIWwrdqB8Tn8gfh55cHBXZDNVd0OvL3MaaAQ67pTYHsR4sTOhzZOuiSaDZoCFgXuGII8zm1SqELzczx/lNPtuESInqDtfTrZeL2xgdvt8y3+7ftN5OHEvZRNWW0SPMEobMAXv7jHZn8TasXSh65Oqif+CH4AfgfmFho6EmpepSLsPz1LkbPqxEHUmDjvcTU5e5Gszdu183X/tfiJ6pHGzZa1WBkVIMQsc9gWz7+7ZUsV+sgOiZJQIikCDQYAigdyFSo4qmiGpubprzp3jqvnmD6clQzoZTZhdP2uldXl8hn+1fg16sXHjZf9WeEXXMbUctQaE8MvaNMZgs+CiNZXHiuiDzYCOgSSGbI4lmvSoZbrxzQDj7vgQD7wkSTkXTJVcQmq1dJ57xX4VfpJ5X3G+ZQdXr0U8MkUdbQdf8cTbRceBtAmkXZbmi/aEwoFjgtKG7Y51mhCpTLqizX3iOvgwDrUjIjjYSkdb72hnc116nH0MfbF4rnBCZcZWqkV0MrodHAhE8tncgsjdtXul2pdkjWqGIIOgg+WHzo8cm3epcLqBzRfikfdHDZQi0DZfSbFZR2e6cbd4C3ybe2x3nm9wZDlWZ0V/MhIewAgv8wbe6clztzWnrJk/j0CI5IREhV2JDZEZnCqq0bqOzc7h8/ZZDFshVTWtR9NXTWWxb692E3rDecJ1MG5IY2FV50RaMkseVwkg9Erfd8tBuTWpz5t1kXmKDodPhzmLq5JsnSercbvKzaThY/ZnCw0gtDPERbJVAmNObUd0t3eGd7RzY2zKYT5UKEQGMmUe3wkT9aLgKs1Du3erQJ4ElBGNnIm/iXeNp5QVn3CsT7w2zprh4/VyCqse7zGoQ09TamCUaoBx+XTldEVxOWr2X89SKkOBMV8eVwoI9g3iAc94vfqt/qDplgaQi4yRjBaQ/5YToQWubb3UzrLhc/V+CTgdCDBcQa1Qh12GZ11u2nHicXZus2fOXRVR7UHLMDYevgr89ofj99Dcv7qwBqQgmlWT2I/DjxWTspllo+Ovyb6jz+zhFvWLCLcbAi7hPtBNXFomZOJqXm6Abklr02RSWxFPcUDjL+odEQvt9w/lC9NtwrWzU6eonfyWgpNTk3CWvpwKpgyyZcCj0EnizfSdByka4Ss7PLpK7VZ4YBFniGrDasFnnGGFWMRMtj7KLnodUAvZ+KLmOtUnxea246p7ofaahJc+lyWaIaAAqX60PsLW0cvimfS0BpEYpiltOW5HPVN/XO9iW2arZt9jDl5nVS9Kvjx+LecceQu++T7ogNcHyEq6sq6YpUCf25uBmzKe2KNFrDa3VcQ603Hje/TSBfIWVCd7NvFDUE9AWH5e22E+YqhfLVr7UVNHiDoBLC4ciwuc+uDp3NkLy969vLL5qdejg6AXoJOi4afXrzW6qcbQ1DzkdPT5BE0V7yRoM0dAKku+U8NZC11/XR5b/FVETjJEFzhSKlAbhgtv+4frStwuzp/B/baarrWoeaX+pESnOay0s3i9OMmX1i3lh/QsBKUTeSI2MHI8z0b+TsJU8FdyWEZWflFDSs5AazVzKE0aZws2/C/tx95t0YfFcrt4s9etuKoxqkOs3bDYt/zAAcyO2EPmsvRrA/0R9h/qLHY4QkIESoBPj1IbUyJRtkz8RSo9hjJkJiUZLwvx/NfuUeHF1JTJFcCOuDizO7Crr4qxyLVBvMDEAs+12n7n9/S3AlUQZx2HKVk0ij3URAFK60x+TbhLqUdyQUc5aS8mJNcX3Aqd/X3w4+My2MHN4sTWvdS4/rVptRa397rrwMDIOdIK3d7oV/UTArIO0BoRJh0wqTh0P0tEC0ehRwtGWUKpPCo1Fyy6IWUWbwo4/h7yfeax2wvS1clNw6S++7tlu+K8ZsDSxfvMpdWM32Lq0fWAARUNNRiLIscrpTPnOWE+8kCIQSFAzDykN9QwkygjH84U5wnD/rfzGuk932zW6c7tyKXELsKawerCEcb0ymzRQtk64grsZ/b+AH8LlxX4Hlwngi41NEo4pjo4O/45BTdmMkgs3SRgHBQTRAk8/0n1uOvV4uHaGtSyztDKkcgDyCfJ8stM0BDWD90R5dbtGPePAPMJ+RJdG94iRSlgLgwyLTS3NKczCjH1LIwn+iB1GTgRhQih/8/2Ve5z5mbfYtmV1CHRH8+bzpbPBtLW1eTaCOEQ6MPv5fc0AHIIXxC8F1Me8iNvKKorjC0KLiIt3ypUJ6Ei6xxiFjoPqwfy/0n47PAV6vbjvt6S2pLX0dVb1TDWR9iM2+TfK+U169HxzPjv/wAHyg0aFL8Zjx5nIislySY3J3QmiSSJIYwdtRgrExsNtgYtALT5ffO37Y3oJ+Sk4B3eo9w/3PHcsN5s4Q3ldOl97v/zz/m9/5wFPgt6ECYVIRlNHJUe6h9DIKIfDh6XG1EYWhTSD94KpgVTABD7BPZV8SftmenF5r3kj+NB49LjPOVv51nq4O3m8Uv26/qi/0gEvQjeDIwQrBMnFu0X9Bg1GbMYcxeDFfUS3g9ZDIQIfQRkAFv8fvjs9MDxEO/v7Gvrjupa6s/q5euS7cXvbPJu9bT4Ifyc/wcDSgZLCfULNA75DzkR7RETEqsRvRBTD3oNRAvDCA4GOgNeAJP96vp6+FT2h/Qe8yPymvGE8eDxpvLO8031E/cR+Tf7cP2t/9kB5gPEBWUHwAjKCX8K3AriCpIK8wkMCecHkAYTBX8D3wFCALf+Rv36+976+PlM+d74rvi6+AD5efkf+uv60vvO/NL91/7U/78AlAFLAuECUwOeA8UDxwOoA2wDGQOyAj8CxgFMAdcAbQAQAMb/jv9r/1z/YP91/5f/xP/2/ygAVwB/AJoApQCeAIMAVAARALz/V//l/m3+8/18/RD9tPxt/EL8NvxN/In86/xy/Rz+5f7I/74AwQHGAscDuASQBUcG1AYvB1QHPQfpBlcGiAWCBEoD5wFkAM7+Lv2T+wv6ovhn92X2p/U29Rf1T/Xg9cf2AfiG+Uz7SP1p/6AB3QMNBh4I/gmcC+oM2g1jDn0OJA5YDRwMeAp1CCIGjgPOAPf9HftY+L/1Z/Nl8cvvqO4I7vLtau5x7//wDfON9Wz4l/v1/msC4gU8CV0MLQ+TEXoT0RSKFZ0VBRXGE+URbw90DAkJSAVOATj9Jfk49Y7xRu5860fpvOfq5tnmjucF6TfrFO6K8X711Plr/h8DzAdODIAQQBRvF/EZsRudHK0c3BsuGqwXaRR6EP0LEwfiAZH8SPcz8nrtQumv5d/i6eDi39Lfv+Cj4nLlGumA7YXyAfjN/boDnAlED4QUNBkrHUogdSKYI6gjoiKJIG0dYhmGFPwO7giKAgL8h/VO74bpYOQE4JfcNtr22OTYBNpP3LffI+R06YPvIPYb/TwETgsZEmYYBB7EIn8mFyl0KogqUSnUJiIjVR6RGAES1QpFA4z74/OJ7Lflo99/2nXWptMs0hTSYtMQ1graNN9q5XvsM/RX/KYE4wzMFCMcrCI0KI0ski8rMUcx4y8HLcYoPyOaHAoVyAwSBC77XvLn6Q7iENsl1X7QQM2Jy2jL4Mzqz3DUUtpk4XDpO/KA+/gEWg5cF7cfKSd3LWwy4TW4N983UzYdM1QuGSicIBUYxA7xBOn69/Br54/eqtb6z7fKCscTxeXEg8bjye/OgNVm3WbmO/Ca+jEFsQ/GGSEjeCuIMho4/jsVPks+nDwSOccz4SyUJB4bxxDfBbv6sO8U5TvbdNICyyTFCMHQvpK+UMABxIvJw9B22WDjNu6k+VMF6BAIHF0mlC9lN5A95EE9RIVEt0LgPhs5kjF9KCIezxLcBqX6ie7l4hbYcc5Cxsq/P7vFuHO4TrpJvknEIcyV1V/gLOyh+F0F/xEjHmopfDMJPMxCj0cqSodKoEiCREo+JjZULB0h2RTlB6f6gu3g4CLVpcq7wa66tLX3so6ygLTAuC6/nMfJ0WndIuqS91AF9RITIEYsLDdxQMlH+UzYT01QUU7ySU9DmjoUMA4k4xb6CL76newE31/SEcdzvdK1a7Bqreis7a5qsz+6OcMVzn/aGOh49i4FyhPaIe8uojqYRIJMH1JDVdJVxlMsTyZI6T67M/Am6xgYCuv61+tT3dHPucNsuTyxaasjqIanmKlNroG1/r59yqXXEuZV9fYEfxR1I2Mx3D1+SPRQ/FZlWhBb+VgrVMtMEENEN8Ep7ho/Cy37M+vO23jNn8Cqte6ssqYno2yiiKRtqfew7boEx9/UE+Qs9KsEExXjJKAz1kAdTB1VjVs6XwVg5V3qWDlRCkesOn0s6hxrDIL7r+p22lbLxb0tsuyoSaJ6np+dwJ/PpKesC7euwy7SHOL98k0EiBUmJqc1kEN1T/hYzV++Y6pkiGJmXWtV00ruPSEv2x6cDen7SupJ2WvJLLv7rjilMZ4fmiKZRJt3oJOoXLN/wJfPMeDL8d0D3RU8J3U3CEaDUoNcumPuZ/1o22aZYV5ZZ04JQaoxwCDODmH8BepJ2LnH1bgTrNahb5oalvqUGpdpnMKk5K96vR3NU96Y8F0DExYmKAs5PEhEVbxfUWfGa/ls3WqBZQ1dw1H3QxU0lSIBEOj83ul210DGw7Z4qceeBZdvkiuRQ5OpmDWhpqyjusLKhtxm788CKxbkKGc6LEq4V6BijmpEb5twiG4YaXZg41S2Rl82WSQyEX791OnO1gHF9rQspw+c9ZMgj7eNxI87lfGdpan9t4rIzNo37jMCJhZ1KYk71kvcWS1lcG1kcuBz2XFdbJRjw1dDSYU4CSZfEiD+5+lS1vvDb7Mwpa6ZQpExjKGKoIwhkvma5qaKtXfGKNkN7YsBBRbbKXM8Ok2wW2Fn9G8jdcZ2z3RLb2VmYVqaS4Q6oieFE8z+FeoC1i7DLrKFo6aX7o6iieyH2olfj1GYaqRPs4zEm9fq69oAyhUXKiI9WE4yXTxpGHKAd0l5ZXfgceVouVy6TVo8ISmkFIL/Xerb1ZvCM7EroviV+ox3h5qFdYf4jPqVNqJNscvCKdbR6iAAdRUpKpk9ME9jXr1q3HN5eWh7mXkZdBJryV6eTwQ+hSq4FT4Avure1UHCf7AjoaaUZ4uwha6DcoXtiveTSqCHrzjB1NTC6WL/CRUSKtg9wU9CX+FrPnUNeyF9anv0delsj2BEUYA/zCvAFgABNusJ1h7CEbBuoK6TN4pQhCmC04NCiUySq54ArtS/ndPB6J3+hhTTKd89DFDOX6tsPXY6fHJ+1nxvd2huB2KrUstA8iy5F8YBw+ta1jLC6K8KoBOTaYlXgwyBm4L4h/mQWp26rKK+iNLQ59b97xNvKa89ElAJYBht2Hb/fFt/2n2IeI5vMWPQU+NB9i2iGI0CZOzR1nzCBLD3n9SS/4jFgliAyoEQhwGQWZy3q6S9ltHw5g/9RBPmKEs91U/0XyptEXdcfdp/d34/eVhwCWSxVMdC1i54GVUDGO1s1/vCY7A2oO+S+Iicgg6AYYGMhmWPqZv4qty8ydAk5kj8iBI6KLI8VE+NX+Fs53ZSfe9/rH6RecZwj2RMVXRDjy86GhoE2+0p2K3DBbHDoGWTU4nbgi6AYYFshiePTZuAqku8I9Bt5YX7vRFsJ+g7kk7YXj5sWnbffJt/d35+edZwwmShVehDITDmGtsEre4G2Y/E6LGfoTWUEYqAg7eAyoGxhkaPRJtQqvO7pc/N5Mb65RCAJu06j03WXUJrbHUGfNx+2n0GeYhwoGStVSNEiTB5G5YFi+8C2qLFCbPIol2VL4uNhKqBnIJch8OPkJtoqta7U89G5A/6ARB2JcQ5T0yHXO9pHnTHerV91HwpeNtvKmRxVSNExzDzG0oGdPAa2+LGaLQ8pNuWrIz/hQWD1oNriJ+QMpzJqvS7K8/a42D5FA9QJG4400rvWkZocnIjeSZ8ZnvodtBuXWPqVOdD2DBRHPQGZvFM3E3IAbb4pa6YiI7Vh8iEeIXeidmRKZ11q068Mc+K47v4Hw4RI+42HEkPWUpmaHAcdzF6kXlCdWdtPGIZVG5DuzCTHJIHXfKX3eHJ1Lf8p9Oav5ANivCGf4e2i3GTdZ5rrOa8Zc9Y4yP4JQ28IUc1L0fpVv1jBG6zdNd3V3c6c6BrxWD+UrdCcDC2HCQIWvP33pvL3LlDqkidT5OljHuJ64nvjWeVF6Csrbu9yM9E45n3JwxRIHozDEWBVGFhSGvscRp1unTQcHxp+V6YUcNB9S+6HKcIWPRr4HrNGLzLrAqgNpaaj2mMuoyJkLiXDaI3r86+WtBQ4x73KAvUHooxuELZUXleN2jJbv1xu3EGbv5m2VzoT5FASy+dHBkJWPXw4XrPhL6SrxajcJnqkrWP6Y+Ck2OaVqQLsR/AHdF+47T2KQpIHXovNED0Tklb1GRNa4JuXG7faiZkZ1rvTSE/cC5eHHoJVfaE45nRH8GUsmmm+5ySll6TdpPYlmid8aYps67BENLO4132LQmtG00thD3WS9RXImF7Z61qompcZ/Zgo1etS3M9ZC39G8cJUPcl5dTT5MPOtQCq06COml+XXZeHmsKg3amOtXrDNNNA5Br2NQgHGgUrqzqBSB1UJV1WY4BmjmaAY3BdkFQkSYk7KCx5GwAKRfjP5ijW0MY8udat9aTanrabnJuOnnGkF606uIPFidTW5Oz1QwdYGKUorDf6RChQ4FjiXgBiJGJPX5hZL1FVRmI5uirRGiMKM/mC6JPY4MncvOmxW6l0o16gMKDponKonrAsu8jHDtaQ5dT1WQajFjEmizREQflLWFQkWjFdaF3LWnBVg01CQwA3HSkFGi8KGPo66hDbEc2owDO2A65WqFSlFKWUp8Gsb7RgvkfKxNdu5tP1eQXpFKsjSzFiPZNHkU8gVRVYXlj5VftQjkntP2Q0TycVGSQK8/r0657dX9CdxLK66LJ8rZOqQ6qNrFuxh7jWwf/Mqdlx5+v1pQQuExUh7y1aOf1CkErZT7NSCVPbUD1MVEVYPJAxUyUAGAAKwfuw7TrgyNO4yGC/Brjhshewu6/OsT2247yKxe7PvduY6Bv23QNzEXQefCouNTk+WEVWSg9Nb013SzlH1kCEOIUuKCPHFsMJgvxp7+DiRtf0zDnEV72BuNu1drVUt2K7gMF7yRTT/t3j6WX2IwO7D8ob9CbjMEw57j+aRCxHlEfRRfNBGjx3NEYr0SBqFWwJNP0g8Y3l1tpN0TnJ18JXvtq7cLsavcjAW8amzW3Wa+BR68r2eQIIDhoZWyN9LDs0WTqrPhJBfUHtP288IjcxMNQnTh7qE/oI1f3Q8j/odt6+1VrOgchexA/Co8Ebw2nGb8sG0vfZBOPj7Ej34AFbDGcWth8BKAovnDSOOMQ6LzvPObI28jG2KzIkoRtHEm8IZf549PPqIeJE2pnTUM6QynXIC8hTyUDMutCa1rHdxeWX7uH3WgG4CrMTBhxyI78pvS5IMkg0sDR+M8EwjiwKJ2IgyxiCEMgH4/4W9qbt1OXb3u/YPtTo0AXPoc68z0rSNtZd25bhruht8JX45gAgCQIRURjVHl0kwSjgK6QtBC7/LJ8q+yYwImcczxWcDgcHTf+o91Xwiul941reRtpg17vVYdVR1oLY39tM4KXlvetk8mT5hgCUB1YOmhQvGuserSJZJd4mMidWJlMkPSEtHUUYrxKWDCsGov8t+f3yQu0n6NPjZODz3ZDcRNwM3eHeseFk5drp7+559E36OwAXBrML4xCCFW0Zhxy7HvsfPyCJH+IdWBsDGP8TbA9xCjUF4/+i+pz19vDV7Fbpkeab5IDjRePo42Plp+ef6jHuQfKs9k/7BQCqBBkJMg3UEOcTVBYLGAEZMhmfGFAXUhW3EpcPCgwvCCYEDQAG/C/4pfSC8d3uyexT64PqXerg6gPsvO3676nysvX8+Gz85v9OA40GiAkpDF8OGRBOEfYRDxKcEaQQMA9ODRELiwjTBf0CIgBY/bT6Sfgq9mX0BfMT8pTxiPHs8bvy6/Nw9Tz3Pvlm+6D93P8GAhAE6QWFB9kI3QmKCuAK3gqHCuIJ9QjMB3IG8gRcA7wBIQCX/ij94fvJ+uf5QfnY+K34vvgI+YX5L/r9+uf74/zo/e3+6P/SAKQBWQLsAloDowPGA8YDpANmAxEDqQI1ArwBQgHOAGQACQDA/4r/af9b/2H/d/+b/8j/+v8sAFsAgQCbAKUAnQCAAE8ACgC0/07/3P5j/un9c/0I/a38afxA/Df8UfyQ/PX8f/0s/vf+3P/TANYB3ALcA8sEoQVUBt0GNQdUBzkH3wZIBnUFagQuA8gBQwCr/gv9cvvr+Yb4UPdT9pv1MPUY9Vj18PXe9h/4qvl1+3T9mP/QAQ0EOwZICCMKuwsCDeoNaQ56DhcOQg39C1AKRgjtBVUDkgC6/eH6H/iK9TnzP/Gu75buAO727Xvuje8n8T/zx/Wt+N37Pv+2AisGgQmdDGQPwBGcE+YUkhWWFfEUpBO2ETQPLwy8CPUE9wDg/ND45vRD8QXuR+sg6aPn4ebg5qXnLelu61nu2vHX9TT6z/6DAy8IqwzVEIoUqxceGs0bpxykHMAbABpuFxsUIBCYC6cGcQEf/Nn2yvEa7e/oa+Ws4srg19/c397g1uK45XHp5u328nv4S/44BBcKuA/uFJAZdh2CIJcipCOdI38iUSAfHQIZFRR/DmgI/wF3+//0ze4S6frjsd9Z3BDa6djw2CnajdwM4I3k7+kL8LL2sv3UBOMLpRLlGHIeHiPCJkApgip7KigpkCbGIuMdDBhtETcKoQLn+kPz8ust5SzfHtos1nnTHNIi0o7TWNZt2q/f+eUa7d30B/1YBZANbxW3HCwjnCjaLMMvPDE4MbQvuSxcKLsiARxgFBIMVQNw+qXxOelw4YbatdQq0A3Nd8t3yxLNPNDh1N7aB+Im6v3ySvzCBR4PFRhgILsn7i3FMhg2zDfPNx82xjLdLYUn8B9VF/YNHAQS+ibwpubc3Q7We89Yys/G/sT2xLrGP8ptzxzWHN4x5xTxe/sTBo0QlRrdIxwsDjN+OD08LD45PmI8sjhDMz0s1CNJGuMP8gTN+cjuOeR12sfRdcq6xMbAuL6kvozAZsQVym/RPto/5CXvnPpMBtsR7hwuJ0ow+jf/PSpCV0RyRHlCeD6LON4wqyc4HdUR2AWh+Yvt9eE817PNpsVWv/W6qbiFuI66tr7fxNvMb9ZS4THtr/ltBggTHR9OKkM0rDxGQ9xHSEp0Sl5IEUSuPWQ1cSshIMoTzAaM+W7s29801NbJEsEuumO117KhssS0NLnPv2XItNJv3jvrtfh2BhMUIiE8LQM4IUFNSE5N+k86UAtOekmpQso5IS//IsEVzAeO+XTr7N1g0TLGvLxItROwRq37rDWv5bPruhDEEM+X20XpsPdoBv0U/CL3L4k7VkURTXtSaFW/VXxTrU52Rw0+uDLQJbUX1win+ZvqKNzAzsvCqLiosAqr/KeYp+Opz642tuG/hsvO2FHnofZFBsUVqSR8MtI+SUmOUV9Xjlr/WqxYplMSTChCMzaQKKYZ6gnV+ePpkdpWzKK/2LRQrEum/KJ9otak9am1sdu7G8gX1mPlifUMBmwWKibLNNtB9UzAVfdbZ1/0X5ddYFh3UBZGjTk8K5EbBQsY+k3pJ9kjyrm8ULFEqNuhSp6vnRCgXKVsrQS408R2033jbPS/BfIWfifhNqNEWVClWT5g8GOaZDdi11yiVNVJxDzSLXMdJQxu+tfo6tcqyBK6Ea6HpL2d7JkxmZabCKFgqV+0sMHt0KDhSvNgBVcXpCi+OChHclM5XTJkJGjuaIlmBmGOWGBN0z9OMEkfSA3W+oLo29Zpxq+3HqsbofSZ45UIlWyX/pyVpe+wtb5/ztHfJvLvBJwXnClhOmlJPlZ7YM9nAGzsbIpq6mQ3XLRQt0KtMhIhbQ5P+03o+dXjxJG1eagEnoSWM5I3kZaTQpkOormt6LsvzBDeAfFuBMMXZyrKO2RLvFhnYxNrgm+QcDRuf2ibX8xTbUXtNMoikQ/Y+zboRdWXw7izJKZDm26T4I7AjRiQ1pXPnr+qSrkAymHc3u/fA8oXBSv4PBlN6Vr8ZfptpXLXc4ZxwWu1YqZW8kcJN28kshBu/D3ovdSGwieyHqTbmLWQ7YupivSMvpLbmwWo37b2x8bav+5CA7UXdivsPYdOxlw4aIRwaXW/dnt0rm6CZT9ZQ0oBOf8lzxEQ/WDoYtSwwd2wa6LMlluOWonyhy2K/Y81mY6lqbQSxkLZpe2bAoQXuyulPq5PUF4aaq5yyndFeRJ3QnEAaJNbXEzQOnYn5RK9/Z/oMtQUwdqvCqEYlWGMK4eehceHl43gll2jrLJYxNfXk+zqATcX1iskP41QiF+ga3d0x3lme0h5enMraqBdPE51PNQo8hNy/vjoLdSywB6v+5+/k8qKYYWvg8OFjIvflHSh6rDJwofWi+sxAdIWxitqPyVRbWDKbN11XnsifRp7VnUBbGRf4E/tPRYq9RQu/2rpUdSJwKquQJ/DkpWJ/YMngiOE4Yk1k9efZq9pwVXVj+pyAFUWjSt3P3ZR/2CYbeB2jnx2fod80XaAbdtgRVE1Pzgr6hXw//LpntSYwHyu154kksSIAYMIgemClYjikYaeIa45wELUoemw/8EVLStMP4FRPmEKboB3V31hf4597HembgRiaVJMQDos0BazAJDqEdXewJSuwZ7gkVaIbIJRgBaCrIfpkIWdHq08v1LTw+jq/hoVpyrqPkZRK2Efbrx3t33jfy1+pHhyb95iSlMvQRotpRd5AUHrqtVawfGu/J75kUyIQIIEgKqBJYdLkNScX6xzvoTS9+ck/l8U/SlUPsdQyGDYbZR3r336f2R++Hjhb2Zj51PdQdQtaBg+AgXsZtYLwpGviJ9tkqWIfIIhgKiBA4cJkHWc5Kvgvd3RP+dg/ZQTLymKPQZQFGA3bQl3P32ofzJ+6Hj0b5xjP1RUQmguFRkBA9jsRNfuwnOwZKA7k2GJIIOogA6CRYclkGmcsKuFvV3RnOaf/LkSQSiOPARPEl88bB12aHztfph9dHiqb35jT1STQtQurBm/A7ntQtgCxJaxjaFjlH6KKoSZgd2C7IefkLGcxKtjvQXREebk+9IRNCdjO8JNwl3patB0KnvIfZV8m3cCbwxjF1SYQhcvKxp3BKbuXdlExfayAqPhlfuLm4XxghOE94h2kU2dIKx8vdjQn+Uw++AQCiYKOkJMKFw/aSNzh3k7fCp7Xnb7bUVillNiQi4vkBonBZ3vldq0xpO0wKS1l9aNb4eyhLGFZoqrkj6exazPvdfQSOWE+uUPxiSFOIhKRVpBZxlxgXdIell5vXSYbCphzVLxQRkv2RrOBZzw5ttNyGq2x6bcmQ6Qp4nYhraHOYw9lISftK1fvgLRDeXk+eMOaSPXNpVIHFjyZLRuGXXwdyN3uXLXarpfuVFDQdcuBRtoBqHxTt0Pyni4E6lUnJ+SPoxiiR6KbY4slh6h7K4rv1vR8ORP+dsN9iECNWxGrlVSYvdrUnI1dYl0VHC6aPZdXVBZQGcuFBv1Bqnyy972y7u6oasan4iVNI9NjOmMApF2mAujbbAzwOPR8eTJ+NEMbyAJMxBEAFNmX+NoL28Zco1xkG1DZt9bt04xP8gtAxt0B7TzW+AAzjC9bq4rosaYhZKYjxWQ9ZMam0ulN7J5wZnSEuVT+McL1x7vMIRBFFAxXH1lsmugbjJubmpyY3ZZyUzNPfos0RriB7/0++Eq0NS/eLGEpVScLpY/k56TRZcXnt2nSbT7wn/TVOXu970KLx22Lso+7ky2WMdh3mfMantq8WZLYLxWk0otPPwrfxo+CMf1qeNx0qPCu7QhqTCgK5o/l4KX75ppob6qo7a6xJXUt+Wc97YJextiLOY7kEn4VMZdt2OgZmtmHGPOXLRTFkhQOs8qChqGCMz2YuXS1JvFM7j/rFakep6Vm76b754Qpe6tQrm0xtrVPeZd97QIvRn0Kdo4/kX7UHxZQl8hYgVi8V7/WF5QVEU5OHIpcxm6CMr3JedL17nI3bsascOoFqM9oE6gRKMHqWmxJrzpyE/X5eY097kH+BdwJ6w1PULDTO5UgVpRXUxdc1rgVL5MT0LmNeUnuRjZCMH47ujZ2fjLtb9utXGt+6czpS6l6adNrS61TL9Yy/PYsecg98YGLBbaJF0yTz5USCBQeVU2WEVYp1V0UNVICD9bMyom3BfhCK/5uup43FXPt8P2uV2yJK1zqluq26zesTm5s8IAzsXaoOgk994FXhQzIvIuOjqzQxdLLlDTUvNSkFC/S6dEgjuYMEAk2xbRCJL6iewl383S38evvoK3jrL4r9CvFrK2tom9WMbe0Mbcs+lA9wIFkBKAH24rADbkPthFpkouTVxNM0vFRjdAvzefLSkithWpCGj7V+7e4VzWKcyTw9u8M7i9tYi1lbfRuxnCOcrx0/Pe6ep09zMEwxDCHNUnpjHrOWZA5kRKR4RHk0WJQYg7wTNyKuYfbxRoCC/8IvCf5P7ZkdCfyGTCDr69u3+7Vb0twebGU84310zhQuzC93ID+g7+GSokMS3ONMc68T4uQW9BtT8PPJ02iy8TJ3gdBRMNCOj86fFm57HdE9XOzRfIG8T0wbDBUMPExu3Lo9Kv2s/jve0p+MICNw02F3IgpCiQLwA1zjjeOiM7njlcNnsxIiuEI+AaeRGZB4/9qPMv6m/hqtka0/DNU8pbyBbIgsmRzCrRJtdU3nvmWu+r+CMCfAtsFK4cBCQ3KhcvgjJgNKY0UzN1MCUshybIHyAYyw8LByX+XfX47DblUd5/2OnTsdDuzqrO5M+R0pjW2Nsm4k7pGPFG+ZcBzAmlEeUYVh/HJBApEyy6Lfwt2SxeKp8mviHiGzoV/Q1iBqj+CPe+7wHpBuP43f3ZMden1WjVdNa+2DTctuAg5kbs9vL8+R4BKAjiDhgVnBpFH/EihSXxJisnNiYcJO8gzBzUFzESDwygBRf/pfh98s7sw+eA4ybgy91/3ErcKd0U3/jhvOVB6mHv8/TL+rkAkQYmDEwR3RW3Gb8c3x4KIDogbx+0HRkbtBeiEwUPAwrEBHL/NPo09ZnwhOwT6V/me+Ry40rjAOSM5eDn5eqE7pzyDve0+2kACwV0CYQNHBEhFIAWJxgMGS0ZihgsFyAVehJPD7sL2wfOA7f/svvg9130RPGr7qPsO+t56mLq8uoi7OftL/Dm8vb1RPm2/C8AlgPPBsQJXQyJDjgQYRH9EQsSjRGJEAsPIg3eClMIlwXAAub/Hv1++hn4APZD9O3yBPKP8Yzx+fHR8gj0lPVl92v5lfvQ/QoAMwI5BA4GpAfyCO4JlQrjCtoKfQrRCd8IsQdTBtEEOgOaAQAAd/4L/cj7tPrX+Tb50vis+ML4EPmS+T/6D/v7+/n8/v0C//3/5AC1AWcC9wJiA6cDxwPEA6ADYAMJA6ACKwKyATgBxQBcAAIAu/+H/2f/W/9i/3n/nv/M//7/MABeAIQAnQClAJsAfQBKAAQArP9E/9L+Wf7f/Wn9//ym/GT8Pvw4/FX8l/z//Iz9O/4J//D/6ADsAfIC8APeBLEFYgbnBjkHVAc0B9UGOAZhBVEEEQOpASIAif7p/FD7zPlr+Dj3QfaP9Sv1GvVh9QD29vY9+M75nvug/cf/AAI8BGgGcghICtoLGQ35DW8Odg4KDisN3QsoChcIuAUcA1YAff2l+ub3VvUL8xnxku+E7vrt/O2M7qrvT/Fx8wH27/gk/Ij/AAN0BsYJ2wybD+0RvRP7FJkVjxXcFIEThhH4DukLbgiiBKAAifx6+Jb0+vDF7RPr+eiM59nm6ea/51bppeue7iryMfaU+jP/6AORCAgNKRHTFOYXShrnG7AcmhyjG9EZLhfME8QPMgs6BgABrvtr9mLxvOyd6Cjle+Kt4M7f6N/+4AvjAObJ6UzuZ/P0+Mn+twSSCiwQVxXrGcAduCC4Iq4jkCNbIhYg0BygGKQTAQ7iB3QB6/p49E7unuiX42DfHtzs2d7Y/9hR2s3cYuD35GvqlPBF90r+bQV3DDATYxnfHnYjAydoKY4qayr9KEsmaCJvHYYX2BCYCf0BQvqj8lvrpeS23r7Z5tVP0w/SM9K906PW0tos4Inmuu2I9bj9CQY8DhEWSR2rIwMpJi3wL0oxJjGDL2ks8Cc2ImYbtRNaC5gCs/nt8Izo0+D/2UfU2c/bzGfListGzZHQVNVs26vi3OrA8xP9jAbjD84YBiFMKGMuGzNNNt03uzfnNWwyYy3vJkEfkxYoDUYDPPlW7+LlK9111f/O/MmXxuzECsX0xp7K7c+71tXe/efu8Vz89QZoEWQbmCS9LJIz3zh4PD8+JT4lPE84vDKWKxMjchn+DgYE4Pjh7WDjsNkc0evJVMSHwKO+ub7MwM7Eosoe0gnbIOUV8JX7RQfNEtId/Cf9MIs4az5sQm5EXUQ3Qgs+9zcoMNgmTRzaENUEnPiN7AfhZNb4zA7F5b6vupG4nLjSuia/eMWZzUzXR+I37r76fAcQFBYgMCsGNUs9vEMlSGJKXkoXSJ1DDz2fNIwqIh+6ErIFcfhb69jeSdMKyWzAs7kWtbuyt7INtay5dMAxyaLTd99V7Nr5mwcxFS8iMS7XOM5BzkieTRdQJFDBTf5I/0H3OCsu7iGcFJ0GXvhM6tXcYtBXxQm8w7S/ryetEa2Br2W0mrvpxA3Qsdxz6un4ogcvFhwk/TBtPBBGnE3SUolVqVUuUypOwkYtPbMxrSR+FpQHY/hf6f7asc3gwee3GLCvqtmnr6czqlWv77bHwJPM+dmS6O33kgcLF9wlkzPEPw9KI1K9V7Ja6FpbWB1TVEs7QR81XSddGJUIfviU6FXZNsunvgu0tqvppdWilKIopYGqd7LNvDbJUte15uj2bAfEF28n8jXcQshNX1ZcXI9f3l9DXdFXsU8fRWw4+ik3Gp0Jr/js59nX9Miwu3ewoKdzoSCexZ1koO2lNq4BufrFwNTf5Nz1MQdbGNMoGDiyRThRTVqqYBxkhWThYUNc01PTSJY7gSwJHK0K9Phm54zW68b8uC2t2qNOnb6ZRpnsm5+hMqpltePCRNIS48r04gbRGAkqAzpFSFxU612kZFRo2mgyZm5guVdVTJk+8C7RHcELTPkB527VHcWMti+qZqB/mbGVG5XEl5mdbab/sfS/489Q4bTzgQYlGRArtDuSSjNXNWFIaDRs2Wwxak5kXFugT3NBQzGMH9cMt/m95n7UicNitH+nRp0Ilv6RSJHvk9+Z7KLQrjC9n82c353yDgZZGegrKj2ZTLtZKWSSa7pvf3Dbbd9nul6xUiBEeDM4Ie8NMvqZ5r3TMcJ/siClfprskqeO0Y1xkHaWsp/dq5u6esv43YbxiwVtGZIsZD5YTvFbxmZ/buFyyHMscR9r0GGFVZ1GizXTIgUPvPqU5irTFcHjsBKjDpgtkK+Lt4pOjWCTwpwpqTe4eMln3HHw+gRjGQ8tYj/QT9ddCWkPcal1snYidApummQZWOdIezdZJBgQVPut5sTSNcCPr1ah+JXOjRiJ/oeHiqGQH5q3pgi2nMfs2mHvXAQ8GV4tJUD/UGlf8Wo+cw54Onm5dp1wFGdpWvtKQznJJSUR9/vj5ovSkL+Eru2fPZTPi+aGqIUgiDuOzZeJpBC06MWI2VfuswP4GIEtrEDmUadgfWwLdQ56XnvveNVyPmlyXNdM4johJysSpfw0537SJr/Crdme35IzihiFt4MahjGMzZWkolKyXsQ92FXtAQOaGHgt+UCFUpJhrW12dql7HH3DerF0E2s0XndOVjxdKCgTW/2f55zS975HrRie3pH6iLGDLIJ5hIWKI5QIodCwAcMP117sRwIiGEUtC0HbUipigG59d9x8cn4yfC12kmyqX9pPmz19KRkUGP4i6OTSAb8UraqdOpEliLGCCoE9gzmJ0JK4n42v1MH/1XPriAGTF+os5UDqUm1i9W4heKh9YH87fUl3uG3TYP1QsT58Kv0U2v696FPTQ78prZCd85CzhxqCUYBogk6I1pG2noqu18AQ1ZfqxQDuFmYsh0CzUl5iDm9geAt+5H/cfQN4hW6tYd9RlD9bK9EVnv9s6erTvb+DrcidCZGnh+uBAYD6gcWHNpEDnsmtDsBD1MvpAAA=\" type=\"audio/wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\n## Video\n\nMore exotic objects can also be displayed, as long as their representation supports the IPython display protocol.  For example, videos hosted externally on YouTube are easy to load:\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('sjfsUzECqK0')\n```\n\n\n\n\n\n\n\n\n\n\nUsing the nascent video capabilities of modern browsers, you may also be able to display local\nvideos.  At the moment this doesn't work very well in all browsers, so it may or may not work for you;\nwe will continue testing this and looking for ways to make it more robust.  \n\nThe following cell loads a local file called  `animation.m4v`, encodes the raw video as base64 for http\ntransport, and uses the HTML5 video tag to load it. On Chrome 15 it works correctly, displaying a control bar at the bottom with a play/pause button and a location slider.\n\n\n```python\nfrom IPython.display import HTML\nfrom base64 import b64encode\nvideo = open(\"../images/animation.m4v\", \"rb\").read()\nvideo_encoded = b64encode(video).decode('ascii')\nvideo_tag = '<video controls alt=\"test\" src=\"data:video/x-m4v;base64,{0}\">'.format(video_encoded)\nHTML(data=video_tag)\n```\n\n## External sites\n\nYou can even embed an entire page from another site in an iframe; for example this is today's Wikipedia\npage for mobile users:\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('http://jupyter.org', width='100%', height=350)\n```\n\n## Links to local files\n\nIPython provides builtin display classes for generating links to local files. Create a link to a single file using the `FileLink` object:\n\n\n```python\nfrom IPython.display import FileLink, FileLinks\nFileLink('Cell Magics.ipynb')\n```\n\nAlternatively, to generate links to all of the files in a directory, use the `FileLinks` object, passing `'.'` to indicate that we want links generated for the current working directory. Note that if there were other directories under the current directory, `FileLinks` would work in a recursive manner creating links to files in all sub-directories as well.\n\n\n```python\nFileLinks('.')\n```\n\n## Rich output and security\n\nThe IPython Notebook allows arbitrary code execution in both the IPython kernel and in the browser, though HTML and JavaScript output. More importantly, because IPython has a JavaScript API for running code in the browser, HTML and JavaScript output can actually trigger code to be run in the kernel. This poses a significant security risk as it would allow IPython Notebooks to execute arbitrary code on your computers.\n\nTo protect against these risks, the IPython Notebook has a security model that specifies how dangerous output is handled. Here is a short summary:\n\n* When you run code in the Notebook, all rich output is displayed.\n* When you open a notebook, rich output is only displayed if it doesn't contain security vulberabilities,...\n* ..or if you have trusted a notebook, all rich output will run upon opening it.\n\nA full description of the IPython security model can be found on [this page](http://ipython.org/ipython-doc/dev/notebook/security.html).\n\n## Rich output and nbviewer\n\nMuch of the power of the Notebook is that it enables users to share notebooks with each other using http://nbviewer.ipython.org, without installing IPython locally. As of IPython 2.0, notebooks rendere on nbviewer will display all output, including HTML and JavaScript. Furthermore, to provide a consistent JavaScript environment on the live Notebook and nbviewer, the following JavaScript libraries are loaded onto the nbviewer page, *before* the notebook and its output is displayed:\n\n* [jQuery](http://jquery.com/)\n* [RequireJS](http://requirejs.org/)\n\nLibraries such as [mpld3](http://mpld3.github.io/) use these capabilities to generate interactive visualizations that work on nbviewer.\n", "meta": {"hexsha": "3a5fad7ba3b14837062fffd87c4f014eec7ee39b", "size": 648612, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Rich Output.ipynb", "max_stars_repo_name": "darcamo/python-16h-course", "max_stars_repo_head_hexsha": "70c67ff1275d1abfca77ca5f56779c198b81bd0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/Rich Output.ipynb", "max_issues_repo_name": "darcamo/python-16h-course", "max_issues_repo_head_hexsha": "70c67ff1275d1abfca77ca5f56779c198b81bd0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/Rich Output.ipynb", "max_forks_repo_name": "darcamo/python-16h-course", "max_forks_repo_head_hexsha": "70c67ff1275d1abfca77ca5f56779c198b81bd0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 532.0853158326, "max_line_length": 194153, "alphanum_fraction": 0.936996232, "converted": true, "num_tokens": 50280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09670579850281287, "lm_q2_score": 0.08035747102460307, "lm_q1q2_score": 0.007771033401100888}}
{"text": "```python\nfrom memote.support.helpers import find_met_in_model, find_compartment_id_in_model\nimport cobra\nfrom cobra.exceptions import Infeasible\nfrom os.path import join\n\ndata_dir = \"/Users/lizrad/Dev/iVnat\"\nmodel=cobra.io.read_sbml_model(join(data_dir, \"iVnat.xml\"))\n```\n\n\n```python\nwith model:\n    for rxn in model.boundary:\n        rxn.bounds = 0, 0\n        \n    for rxn in model.boundary:\n        print(rxn.name)\n        rxn.bounds = -10, 10\n        sol = model.optimize()\n        print(sol)\n```\n\n    DNA_replication_c0\n    <Solution 0.000 at 0x10d567ef0>\n    RNA_transcription_c0\n    <Solution 0.000 at 0x10d567cf8>\n    Protein_biosynthesis_c0\n    <Solution 0.000 at 0x10d567fd0>\n    EX_H_plus__e0\n    <Solution 0.000 at 0x10d567eb8>\n    EX_Adenosine_e0\n    <Solution 0.000 at 0x10d567ef0>\n    EX_Fumarate_e0\n    <Solution 0.000 at 0x10d567cf8>\n    EX_Nitrite_e0\n    <Solution 0.000 at 0x10d567fd0>\n    EX_Ornithine_e0\n    <Solution 0.000 at 0x10d567c50>\n    EX_4_5_dihydroxy_2_3_pentanedione_c0\n    <Solution 0.000 at 0x10d567ef0>\n    EX_Succinate_e0\n    <Solution 0.000 at 0x10d567e10>\n    EX_L_methionine_R_oxide_e0\n    <Solution 0.000 at 0x10d567fd0>\n    EX_Pb_e0\n    <Solution 0.000 at 0x10d567c50>\n    EX_L_alanylglycine_e0\n    <Solution 0.000 at 0x10d567ef0>\n    EX_Deoxyuridine_e0\n    <Solution 0.000 at 0x10d567e10>\n    EX_ala_L_Thr_L_e0\n    <Solution 0.000 at 0x10d567fd0>\n    EX_PPi_e0\n    <Solution 0.000 at 0x10d567c50>\n    EX_ala_L_glu_L_e0\n    <Solution 0.000 at 0x10d567ef0>\n    EX_Salicin_e0\n    <Solution 0.000 at 0x10d567e10>\n    EX_L_Proline_e0\n    <Solution 0.000 at 0x10d567fd0>\n    EX_Na_plus__e0\n    <Solution 0.000 at 0x10d567c50>\n    EX_Cd2_plus__e0\n    <Solution 0.000 at 0x10d567ef0>\n    EX_Cbl_e0\n    <Solution 0.000 at 0x10d567e10>\n    EX_Inosine_e0\n    <Solution 0.000 at 0x10d567fd0>\n    EX_GLUM_e0\n    <Solution 0.000 at 0x10d567c50>\n    EX_D_Fructose_e0\n    <Solution 0.000 at 0x10d567ef0>\n    EX_H2O_e0\n    <Solution 0.000 at 0x10d567f60>\n    EX_L_Glutamate_e0\n    <Solution 0.000 at 0x10d567fd0>\n    EX_Cytidine_e0\n    <Solution 0.000 at 0x10d5679b0>\n    EX_Cu2_plus__e0\n    <Solution 0.000 at 0x10d567ef0>\n    EX_Glycerol_3_phosphate_e0\n    <Solution 0.000 at 0x10d567f60>\n    EX_L_Leucine_e0\n    <Solution 0.000 at 0x10d567fd0>\n    EX_Thymidine_e0\n    <Solution 0.000 at 0x10d5679b0>\n    EX_D_Mannitol_e0\n    <Solution 0.000 at 0x10d567ef0>\n    EX_Cys_Gly_e0\n    <Solution 0.000 at 0x10d567f60>\n    EX_R_3_Hydroxybutanoate_e0\n    <Solution 0.000 at 0x10d567da0>\n    EX_NH3_e0\n    <Solution 0.000 at 0x10d5679b0>\n    EX_L_Arginine_e0\n    <Solution 0.000 at 0x10d567fd0>\n    EX_Fe2_plus__e0\n    <Solution 0.000 at 0x10d567eb8>\n    EX_Malonate_e0\n    <Solution 0.000 at 0x10d567ef0>\n    EX_Maltose_e0\n    <Solution 0.000 at 0x10d5679b0>\n    EX_Glycerol_e0\n    <Solution 0.000 at 0x10d567da0>\n    EX_Gly_Met_e0\n    <Solution 0.000 at 0x10d567d68>\n    EX_Phosphate_e0\n    <Solution 0.000 at 0x10d5679e8>\n    EX_L_Methionine_e0\n    <Solution 0.000 at 0x10d567cc0>\n    EX_Deoxyadenosine_e0\n    <Solution 0.000 at 0x10d567da0>\n    EX_Zn2_plus__e0\n    <Solution 0.000 at 0x10d567c50>\n    EX_Uridine_e0\n    <Solution 0.000 at 0x10d5679e8>\n    EX_Palmitate_e0\n    <Solution 0.000 at 0x10d567eb8>\n    EX_L_Histidine_e0\n    <Solution 0.000 at 0x10d567da0>\n    EX_ala_L_asp_L_e0\n    <Solution 0.000 at 0x10d5679b0>\n    EX_Deoxycytidine_e0\n    <Solution 0.000 at 0x10d5679e8>\n    EX_Sucrose_e0\n    <Solution 0.000 at 0x10d567d68>\n    EX_L_Isoleucine_e0\n    <Solution 0.000 at 0x10d567da0>\n    EX_Dulcose_e0\n    <Solution 0.000 at 0x10d567e10>\n    EX_Taurine_e0\n    <Solution 0.000 at 0x10d567ef0>\n    EX_glycogenn_1_c0\n    <Solution 0.000 at 0x10d567c50>\n    EX_Gly_Phe_e0\n    <Solution 0.000 at 0x10d5679b0>\n    EX_Spermidine_e0\n    <Solution 0.000 at 0x10d567eb8>\n    EX_L_Serine_e0\n    <Solution 0.000 at 0x10d567ef0>\n    EX_PAN_e0\n    <Solution 0.000 at 0x10d567c50>\n    EX_D_Methionine_e0\n    <Solution 0.000 at 0x10d5679b0>\n    EX_L_Aspartate_e0\n    <Solution 0.000 at 0x10d567dd8>\n    EX_N_Acetyl_D_glucosamine_e0\n    <Solution 0.000 at 0x10d567ef0>\n    EX_L_Alanine_e0\n    <Solution 0.000 at 0x10d567d68>\n    EX_Gly_Cys_e0\n    <Solution 0.000 at 0x10d5679b0>\n    EX_L_Lysine_e0\n    <Solution 0.000 at 0x10d567e10>\n    EX_Ursin_e0\n    <Solution 0.000 at 0x10d567ef0>\n    EX_Deoxyguanosine_e0\n    <Solution 0.000 at 0x10d567eb8>\n    EX_Putrescine_e0\n    <Solution 0.000 at 0x10d567cc0>\n    EX_XAN_e0\n    <Solution 0.000 at 0x10d567c50>\n    EX_Gly_Gln_e0\n    <Solution 0.000 at 0x10d567b00>\n    EX_Allantoin_e0\n    <Solution 0.000 at 0x10d567dd8>\n    EX_Phenylpropanoate_e0\n    <Solution 0.000 at 0x10d567cc0>\n    EX_Deoxyinosine_e0\n    <Solution 0.000 at 0x10d567d68>\n    EX_L_Arabinose_e0\n    <Solution 0.000 at 0x10d567b00>\n    EX_Amylotriose_e0\n    <Solution 0.000 at 0x10d567e10>\n    EX_Citrate_e0\n    <Solution 0.000 at 0x10d567cc0>\n    EX_fe3_e0\n    <Solution 0.000 at 0x10d567eb8>\n    EX_Sorbitol_e0\n    <Solution 0.000 at 0x10d567b00>\n    EX_Vitamin_B12r_e0\n    <Solution 0.000 at 0x10d567c50>\n    EX_D_Alanine_e0\n    <Solution 0.000 at 0x10d567cc0>\n    EX_Mg_e0\n    <Solution 0.000 at 0x10d567dd8>\n    EX_D_Mannose_e0\n    <Solution 0.000 at 0x10d567b00>\n    EX_S_Adenosyl_4_methylthio_2_oxobutanoate_c0\n    <Solution 0.000 at 0x10d567d68>\n    EX_Thyminose_e0\n    <Solution 0.000 at 0x10d567cc0>\n    EX_L_Lactate_e0\n    <Solution 0.000 at 0x10d567e10>\n    EX_BET_e0\n    <Solution 0.000 at 0x10d567b00>\n    EX_L_Tryptophan_e0\n    <Solution 0.000 at 0x10d567eb8>\n    EX_Formate_e0\n    <Solution 0.000 at 0x10d567cc0>\n    EX_Gly_Tyr_e0\n    <Solution 0.000 at 0x10d567c50>\n    EX_Sulfate_e0\n    <Solution 0.000 at 0x10d567b00>\n    EX_Myristic_acid_e0\n    <Solution 0.000 at 0x10d567dd8>\n    EX_Co2_plus__e0\n    <Solution 0.000 at 0x10d567cc0>\n    EX_2_Demethylmenaquinol_8_e0\n    <Solution 0.000 at 0x10d567d68>\n    EX_2_Demethylmenaquinone_8_e0\n    <Solution 0.000 at 0x10d567b00>\n    EX_L_Methionine_S_oxide_e0\n    <Solution 0.000 at 0x10d567e10>\n    EX_Hg2_plus__e0\n    <Solution 0.000 at 0x10d567ef0>\n    EX_Ala_Leu_e0\n    <Solution 0.000 at 0x10d567eb8>\n    EX_Aminoethanol_e0\n    <Solution 0.000 at 0x10d567be0>\n    EX_gly_asp_L_e0\n    <Solution 0.000 at 0x10d567c50>\n    EX_D_Glucose_e0\n    <Solution 0.000 at 0x10d567ef0>\n    EX_FeIIIdicitrate_e0\n    <Solution 0.000 at 0x10d567dd8>\n    EX_Nitrate_e0\n    <Solution 0.000 at 0x10d567be0>\n    EX_TRHL_e0\n    <Solution 0.000 at 0x10d567d68>\n    EX_D_Ribose_e0\n    <Solution 0.000 at 0x10d567b70>\n    EX_HYXN_e0\n    <Solution 0.000 at 0x10d567e10>\n    EX_gly_pro_L_e0\n    <Solution 0.000 at 0x10d567a58>\n    EX_Maltohexaose_e0\n    <Solution 0.000 at 0x10d567eb8>\n    EX_Gly_Leu_e0\n    <Solution 0.000 at 0x10d567b70>\n    EX_Cyanate_e0\n    <Solution 0.000 at 0x10d567c50>\n    EX_L_Tyrosine_e0\n    <Solution 0.000 at 0x10d567a58>\n    EX_K_plus__e0\n    <Solution 0.000 at 0x10d567dd8>\n    EX_O2_e0\n    <Solution 0.000 at 0x10d567b70>\n    EX_Vitamin_B12_e0\n    <Solution 0.000 at 0x10d567d68>\n    EX_Choline_e0\n    <Solution 0.000 at 0x10d567a58>\n    EX_gly_glu_L_e0\n    <Solution 0.000 at 0x10d567e10>\n    EX_L_Valine_e0\n    <Solution 0.000 at 0x10d567b70>\n    EX_Ala_Gln_e0\n    <Solution 0.000 at 0x10d567eb8>\n    EX_Uracil_e0\n    <Solution 0.000 at 0x10d567a58>\n    EX_met_L_ala_L_e0\n    <Solution 0.000 at 0x10d567c50>\n    EX_gly_asn_L_e0\n    <Solution 0.000 at 0x10d567b70>\n    EX_Menaquinol_8_e0\n    <Solution 0.000 at 0x10d567dd8>\n    EX_Menaquinone_8_e0\n    <Solution 0.000 at 0x10d567a58>\n    EX_ocdca_e0\n    <Solution 0.000 at 0x10d567e10>\n    EX_Ala_His_e0\n    <Solution 0.000 at 0x10d567b70>\n    EX_Thiamin_e0\n    <Solution 0.000 at 0x10d567d68>\n    EX_L_Inositol_e0\n    <Solution 0.000 at 0x10d567a58>\n    EX_CO2_e0\n    <Solution 0.000 at 0x10d567eb8>\n    EX_Biomass_c0\n    <Solution 0.000 at 0x10d567b70>\n    EX_Cl__e0\n    <Solution 0.000 at 0x10d567c50>\n    EX_Ca2_plus__e0\n    <Solution 0.000 at 0x10d567a58>\n    EX_Mn2_plus__e0\n    <Solution 10.000 at 0x10d567dd8>\n\n\n\n```python\nblocked_precursors = []\nwith model:\n    for rxn in model.boundary:\n        print(rxn.name)\n        rxn.bounds = -10, 0\n        sol = model.optimize()\n        print(sol)\n\n\n    for precursor in [model.metabolites.ACP_c0, model.metabolites.ADENOSYLCOBALAMIN_c0, model.metabolites.MNXM7630_c0]:\n        dm_rxn = model.add_boundary(precursor, type=\"demand\")\n        model.objective = dm_rxn\n        try:\n            print(\"demand reaction\", dm_rxn)\n            solution = model.optimize()\n\n\n            print(solution)\n            LOGGER.debug(\n                \"%s: demand flux is '%g' and solver status is '%s'\",\n                str(precursor), solution.objective_value, solution.status)\n\n            if solution.objective_value <= 0.0:\n                blocked_precursors.append(precursor)\n                print(\"obj value 0 or negative:\", blocked_precursors)\n        except Infeasible:\n            blocked_precursors.append(precursor)\n\n\n    \n```\n\n\n```python\n\n```\n\n\n```python\nfrom pandas import read_csv, DataFrame\nimport pandas as pd\nimport os\nimport re #Both patterns and strings to be searched can be Unicode strings as well as 8-bit strings.\nimport math\nimport cobra\nimport cobra.test\nfrom __future__ import print_function\nfrom os.path import join\nfrom cobra.io import write_sbml_model\nfrom cobra.flux_analysis import flux_variability_analysis\n#from cobra.medium import minimal_medium\n#from cobra.medium import minimal_medium\nfrom IPython.core.interactiveshell import InteractiveShell\nimport itertools\nimport re\nimport memote\n\nInteractiveShell.ast_node_interactivity = \"all\"\n\n\ndata_dir = \"/Users/lizrad/Dev/iVnat\"\nprint(\"files found: \")\nprint(\", \".join(i for i in os.listdir(data_dir) if i.startswith(\"iVnat\")))\nmodel=cobra.io.read_sbml_model(join(data_dir, \"iVnat.xml\"))\n#model=cobra.io.read_legacy_sbml(\"/Users/lizrad/Documents/Vibrio_folder/iVnat_gapfill_glu.xml\")\nmodel\n```\n\n    files found: \n    iVnat.json, iVnat.xml\n\n\n\n\n\n\n<table>\n    <tr>\n        <td><strong>Name</strong></td>\n        <td>GCF_001456255_1_rast_metabolic_model</td>\n    </tr><tr>\n        <td><strong>Memory address</strong></td>\n        <td>0x010d016e48</td>\n    </tr><tr>\n        <td><strong>Number of metabolites</strong></td>\n        <td>1842</td>\n    </tr><tr>\n        <td><strong>Number of reactions</strong></td>\n        <td>1906</td>\n    </tr><tr>\n        <td><strong>Objective expression</strong></td>\n        <td>-1.0*bio1_reverse_b18f7 + 1.0*bio1</td>\n    </tr><tr>\n        <td><strong>Compartments</strong></td>\n        <td>Cytosol_0, Extracellular_0</td>\n    </tr>\n  </table>\n\n\n\n## Memote biomass and consistency functions\n\n\n```python\nfrom memote.support.biomass import find_blocked_biomass_precursors, sum_biomass_weight, find_biomass_precursors, find_direct_metabolites, gam_in_biomass, detect_false_positive_direct_metabolites, bundle_biomass_components, essential_precursors_not_in_biomass\n```\n\n\n```python\nfrom memote.support.consistency import check_stoichiometric_consistency\nfrom memote.support.helpers import find_compartment_id_in_model\n```\n\n### Finding biomass precursors\n\n\n```python\nbio_precursor=find_biomass_precursors(model, model.reactions.bio1)\n\nprint(\"Number of found biomass precursors:\" , len(bio_precursor))\nbio_precursor\n```\n\n    Number of found biomass precursors: 76\n\n\n\n\n\n    [<Metabolite DEMETHYLMENAQUINONE_c0 at 0x10edb4048>,\n     <Metabolite MNXM81014_c0 at 0x10eea7048>,\n     <Metabolite K+_c0 at 0x10f0cd160>,\n     <Metabolite LEU_c0 at 0x10edf1198>,\n     <Metabolite GLY_c0 at 0x10ec51208>,\n     <Metabolite LYS_c0 at 0x10ecdb208>,\n     <Metabolite CPD0-2271_c0 at 0x10f126240>,\n     <Metabolite SER_c0 at 0x10eca8240>,\n     <Metabolite GLN_c0 at 0x10ed42278>,\n     <Metabolite HIS_c0 at 0x10ed702b0>,\n     <Metabolite MNXM78334_c0 at 0x10ef352b0>,\n     <Metabolite NAD_c0 at 0x10ec6f2e8>,\n     <Metabolite CPD-15815_c0 at 0x10ec75320>,\n     <Metabolite DGTP_c0 at 0x10ee14320>,\n     <Metabolite ACP_c0 at 0x10ecdb390>,\n     <Metabolite VAL_c0 at 0x10ef093c8>,\n     <Metabolite DATP_c0 at 0x10ecc3400>,\n     <Metabolite TTP_c0 at 0x10edf4400>,\n     <Metabolite CA+2_c0 at 0x10f126438>,\n     <Metabolite THIAMINE-PYROPHOSPHATE_c0 at 0x10ec62438>,\n     <Metabolite RIBOFLAVIN_c0 at 0x10edce470>,\n     <Metabolite CPD-12818_c0 at 0x10edc14a8>,\n     <Metabolite GLUTATHIONE_c0 at 0x10ec594a8>,\n     <Metabolite TYR_c0 at 0x10ee614a8>,\n     <Metabolite ASN_c0 at 0x10ed42518>,\n     <Metabolite UNDECAPRENYL-DIPHOSPHATE_c0 at 0x10f07e550>,\n     <Metabolite CTP_c0 at 0x10ec54588>,\n     <Metabolite CO-A_c0 at 0x10eca85c0>,\n     <Metabolite PRO_c0 at 0x10ed6f5f8>,\n     <Metabolite L-ALPHA-ALANINE_c0 at 0x10ed896d8>,\n     <Metabolite MNXM7305_c0 at 0x10f0a0748>,\n     <Metabolite 10-FORMYL-THF_c0 at 0x10ec54780>,\n     <Metabolite DCTP_c0 at 0x10ec637b8>,\n     <Metabolite GLT_c0 at 0x10ec74828>,\n     <Metabolite THF_c0 at 0x10ed908d0>,\n     <Metabolite MNXM51417_c0 at 0x10ec5a940>,\n     <Metabolite GTP_c0 at 0x10ecea9b0>,\n     <Metabolite MNXM5124_c0 at 0x10eda09e8>,\n     <Metabolite CYS_c0 at 0x10ec749e8>,\n     <Metabolite ADENOSYLCOBALAMIN_c0 at 0x10f01b9e8>,\n     <Metabolite PUTRESCINE_c0 at 0x10ed199e8>,\n     <Metabolite ILE_c0 at 0x10ee8ea20>,\n     <Metabolite MG+2_c0 at 0x10efc2a20>,\n     <Metabolite MNXM7630_c0 at 0x10f0d5a20>,\n     <Metabolite CL-_c0 at 0x10edc1a58>,\n     <Metabolite FE+2_c0 at 0x10ed89a58>,\n     <Metabolite S-ADENOSYLMETHIONINE_c0 at 0x10ec7da20>,\n     <Metabolite MNXM7294_c0 at 0x10f08da90>,\n     <Metabolite THR_c0 at 0x10edcea90>,\n     <Metabolite 5-METHYL-THF_c0 at 0x10ed4cac8>,\n     <Metabolite HSO4_c0 at 0x10eceab38>,\n     <Metabolite SPERMIDINE_c0 at 0x10ed19ba8>,\n     <Metabolite CPD-12822_c0 at 0x10ed0abe0>,\n     <Metabolite NADP_c0 at 0x10ec7ebe0>,\n     <Metabolite PHE_c0 at 0x10ed62be0>,\n     <Metabolite ARG_c0 at 0x10ed90c18>,\n     <Metabolite CPD-9728_c0 at 0x10ed89c18>,\n     <Metabolite MET_c0 at 0x10ec83c18>,\n     <Metabolite MNXM6175_c0 at 0x10eda0c18>,\n     <Metabolite FE+3_c0 at 0x10ed89c50>,\n     <Metabolite UBIQUINONE-8_c0 at 0x10ec5ac50>,\n     <Metabolite ATP_c0 at 0x10ec4dc88>,\n     <Metabolite SIROHEME_c0 at 0x10f09fc88>,\n     <Metabolite UTP_c0 at 0x10ee9ecf8>,\n     <Metabolite MNXM5129_c0 at 0x10eda9d30>,\n     <Metabolite FAD_c0 at 0x10ec74d68>,\n     <Metabolite MN+2_c0 at 0x10f11dda0>,\n     <Metabolite MNXM6440_c0 at 0x10ed0ada0>,\n     <Metabolite PYRIDOXAL_PHOSPHATE_c0 at 0x10ed6fda0>,\n     <Metabolite TRP_c0 at 0x10eef2e10>,\n     <Metabolite CU+2_c0 at 0x10ede0e48>,\n     <Metabolite CO+2_c0 at 0x10efd3eb8>,\n     <Metabolite L-ASPARTATE_c0 at 0x10ec75ef0>,\n     <Metabolite ZN+2_c0 at 0x10ee8ef28>,\n     <Metabolite MNXM6297_c0 at 0x10eda9f60>,\n     <Metabolite MNXM78362_c0 at 0x10ef2df98>]\n\n\n\n\n```python\nlen(model.reactions.bio1.metabolites)\nfor not_precursor in model.reactions.bio1.metabolites:\n    if not_precursor not in bio_precursor:\n        print(\"not precursors, products in the biomass right side:\", not_precursor)\nmodel.reactions.bio1.reaction\n\n\n```\n\n    not precursors, products in the biomass right side: ADP_c0\n    not precursors, products in the biomass right side: BIOMASS_c0\n    not precursors, products in the biomass right side: CPD-16459_c0\n    not precursors, products in the biomass right side: DIMETHYLBENZIMIDAZOLE_c0\n    not precursors, products in the biomass right side: MNXM2214_c0\n    not precursors, products in the biomass right side: MNXM5258_c0\n    not precursors, products in the biomass right side: MNXM90619_c0\n    not precursors, products in the biomass right side: PPI_c0\n    not precursors, products in the biomass right side: PROTON_c0\n\n\n\n\n\n    '0.00309646685192537 10-FORMYL-THF_c0 + 0.00309646685192537 5-METHYL-THF_c0 + 0.00309646685192537 ACP_c0 + 0.00309646685192537 ADENOSYLCOBALAMIN_c0 + 0.246696822701341 ARG_c0 + 0.200830806928348 ASN_c0 + 40.1101757365074 ATP_c0 + 0.00309646685192537 CA+2_c0 + 0.00309646685192537 CL-_c0 + 0.00309646685192537 CO+2_c0 + 0.00309646685192537 CO-A_c0 + 0.0106480421341882 CPD-12818_c0 + 0.0106480421341882 CPD-12822_c0 + 35.5403092430435 CPD-15815_c0 + 0.00309646685192537 CPD-9728_c0 + 0.0250105977108944 CPD0-2271_c0 + 0.0841036156544863 CTP_c0 + 0.00309646685192537 CU+2_c0 + 0.0761464922056484 CYS_c0 + 0.0175915886179248 DATP_c0 + 0.0144513778992424 DCTP_c0 + 0.00309646685192537 DEMETHYLMENAQUINONE_c0 + 0.0144513778992424 DGTP_c0 + 0.00309646685192537 FAD_c0 + 0.00309646685192537 FE+2_c0 + 0.00309646685192537 FE+3_c0 + 0.219088153012743 GLN_c0 + 0.219088153012743 GLT_c0 + 0.00309646685192537 GLUTATHIONE_c0 + 0.509869786991038 GLY_c0 + 0.135406821203723 GTP_c0 + 0.0792636000737159 HIS_c0 + 0.00309646685192537 HSO4_c0 + 0.241798510337235 ILE_c0 + 0.00309646685192537 K+_c0 + 0.427934380173264 L-ALPHA-ALANINE_c0 + 0.200830806928348 L-ASPARTATE_c0 + 0.375388847540127 LEU_c0 + 0.285438020490179 LYS_c0 + 0.127801422590767 MET_c0 + 0.00309646685192537 MG+2_c0 + 0.00309646685192537 MN+2_c0 + 0.0106480421341882 MNXM5124_c0 + 0.0106480421341882 MNXM5129_c0 + MNXM51417_c0 + 0.0106480421341882 MNXM6175_c0 + 0.0106480421341882 MNXM6297_c0 + 0.0106480421341882 MNXM6440_c0 + 0.0106480421341882 MNXM7294_c0 + 0.0106480421341882 MNXM7305_c0 + 0.0250105977108944 MNXM7630_c0 + MNXM78334_c0 + 0.00309646685192537 MNXM78362_c0 + MNXM81014_c0 + 0.00309646685192537 NADP_c0 + 0.00309646685192537 NAD_c0 + 0.154519490031345 PHE_c0 + 0.184354665339991 PRO_c0 + 0.00309646685192537 PUTRESCINE_c0 + 0.00309646685192537 PYRIDOXAL_PHOSPHATE_c0 + 0.00309646685192537 RIBOFLAVIN_c0 + 0.00309646685192537 S-ADENOSYLMETHIONINE_c0 + 0.179456352975885 SER_c0 + 0.00309646685192537 SIROHEME_c0 + 0.00309646685192537 SPERMIDINE_c0 + 0.00309646685192537 THF_c0 + 0.00309646685192537 THIAMINE-PYROPHOSPHATE_c0 + 0.211072732780569 THR_c0 + 0.0472019191450218 TRP_c0 + 0.0175915886179248 TTP_c0 + 0.120676604606612 TYR_c0 + 0.00309646685192537 UBIQUINONE-8_c0 + 0.0250105977108944 UNDECAPRENYL-DIPHOSPHATE_c0 + 0.0908319049068452 UTP_c0 + 0.352233189091625 VAL_c0 + 0.00309646685192537 ZN+2_c0 --> 40.0 ADP_c0 + BIOMASS_c0 + 39.9969035331481 CPD-16459_c0 + 0.00309646685192537 DIMETHYLBENZIMIDAZOLE_c0 + 0.00309646685192537 MNXM2214_c0 + 0.0250105977108944 MNXM5258_c0 + 0.00309646685192537 MNXM90619_c0 + 0.484604011306766 PPI_c0 + 40.0 PROTON_c0'\n\n\n\n### Adding exchange reactions to precursors\n\n\n```python\nwith model:\n    ex_reac_list=[]\n    \n    for pre in bio_precursor:\n        \n        try:\n            ex_precursor_reac = model.add_boundary(pre, type=\"exchange\")\n            ex_reac_list.append(ex_precursor_reac)\n        except:\n            pass\n    print(\"growth after adding precursor exchanges:\", model.optimize())     \n    \n    for blocked in (\"EX_ACP_c0\", \"EX_ADENOSYLCOBALAMIN_c0\", \"EX_MNXM7630_c0\"):\n        model.reactions.get_by_id(blocked).bounds=(-1000, 1000)\n        print(model.reactions.get_by_id(blocked))\n        model.objective=model.reactions.get_by_id(blocked)\n        print(\"optimization:\", model.optimize())\n        \n    \n    for reac in ex_reac_list:\n        \n        reac.bounds=(0, 1000)\n        print(reac)\n        model.objective=model.reactions.get_by_id(reac.id)\n        model.optimize()\n        \n#ex_reac_list\n          #  if \"EX_\"+pre.id in reac.name:\n           #     pass\n            #else:\n             #   ex_precursor_reac = model.add_boundary(pre, type=\"exchange\")\n              #  ex_reac_list.append(ex_precursor_reac)\n```\n\n    growth after adding precursor exchanges: <Solution 452.153 at 0x10f2e12e8>\n    EX_ACP_c0: ACP_c0 <=> \n    optimization: <Solution -0.000 at 0x10f2e19e8>\n    EX_ADENOSYLCOBALAMIN_c0: ADENOSYLCOBALAMIN_c0 <=> \n    optimization: <Solution 0.000 at 0x10f2e1e80>\n    EX_MNXM7630_c0: MNXM7630_c0 <=> \n    optimization: <Solution 0.000 at 0x10f2e1860>\n    EX_DEMETHYLMENAQUINONE_c0: DEMETHYLMENAQUINONE_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>2.175501e-13</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-4.189314e+02</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_MNXM81014_c0: MNXM81014_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>2.175501e-13</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-4.189314e+02</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_K+_c0: K+_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>2.142758e-13</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-4.134572e+02</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_LEU_c0: LEU_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>1.992637e-13</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-4.134572e+02</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_GLY_c0: GLY_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>1.992637e-13</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-4.134572e+02</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_LYS_c0: LYS_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>1.732077e-13</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-4.109233e+02</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_CPD0-2271_c0: CPD0-2271_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 34.483</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>-5.653620e-18</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>377.685151</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>-9.360504e-17</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.000000</td>\n      <td>-1.177574e-16</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-500.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_SER_c0: SER_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>229.173409</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-500.000000</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_GLN_c0: GLN_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>-5.456968e-12</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>1.064103e-12</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-5.000000e+02</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_HIS_c0: HIS_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>7.048584e-12</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>2.913225e-13</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-4.557771e+02</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_MNXM78334_c0: MNXM78334_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>7.048584e-12</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>2.913225e-13</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-4.557771e+02</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_NAD_c0: NAD_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-445.307874</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_CPD-15815_c0: CPD-15815_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>176.252112</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-156.234953</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-500.000000</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_DGTP_c0: DGTP_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>176.252112</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-156.234953</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-500.000000</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_ACP_c0: ACP_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value -0.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>176.252112</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>2.206838e-17</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-156.234953</td>\n      <td>6.162976e-33</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-500.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_VAL_c0: VAL_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>165.868440</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-201.211391</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-500.000000</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_DATP_c0: DATP_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>242.034377</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-9.857316</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-448.771892</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_TTP_c0: TTP_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>195.232369</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-314.345823</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-446.363632</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_CA+2_c0: CA+2_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>240.279676</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-117.460797</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-436.691393</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_THIAMINE-PYROPHOSPHATE_c0: THIAMINE-PYROPHOSPHATE_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>476.563435</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>7.175936e-17</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>4.421639e-16</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-59.663693</td>\n      <td>4.166135e-18</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-332.846677</td>\n      <td>0.000000e+00</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_RIBOFLAVIN_c0: RIBOFLAVIN_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 500.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>968.594277</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-487.691192</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-156.355755</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_CPD-12818_c0: CPD-12818_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 500.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>1000.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-379.071419</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-230.139460</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_GLUTATHIONE_c0: GLUTATHIONE_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>1000.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-517.945463</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-213.413591</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_TYR_c0: TYR_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>976.989785</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-640.402555</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-269.416566</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_ASN_c0: ASN_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>1000.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-273.048478</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_UNDECAPRENYL-DIPHOSPHATE_c0: UNDECAPRENYL-DIPHOSPHATE_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 90.909</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>1000.000000</td>\n      <td>1.617781e-32</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>3.081488e-33</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>-1.397941e-16</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>3.826174e-17</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-341.206595</td>\n      <td>0.000000e+00</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_CTP_c0: CTP_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>1000.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-221.197381</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_CO-A_c0: CO-A_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>403.513313</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>7.932007e-16</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>2.554455e-15</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-235.051031</td>\n      <td>0.000000e+00</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_PRO_c0: PRO_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>140.312699</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-261.474023</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_L-ALPHA-ALANINE_c0: L-ALPHA-ALANINE_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>379.190295</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-250.072395</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_MNXM7305_c0: MNXM7305_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 83.333</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>410.272447</td>\n      <td>-1.232595e-32</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>8.628166e-32</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>-3.583589e-15</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>8.456951e-16</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-299.423472</td>\n      <td>0.000000e+00</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_10-FORMYL-THF_c0: 10-FORMYL-THF_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>21.074720</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-317.415439</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_DCTP_c0: DCTP_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.040365</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>-0.040365</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>-0.040365</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>-0.208209</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-373.164833</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_GLT_c0: GLT_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>-5.911217e-14</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1.000000e+03</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-3.282865e+02</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_THF_c0: THF_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>-5.668776e-14</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1.000000e+03</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-3.601955e+02</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_MNXM51417_c0: MNXM51417_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>-5.668776e-14</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1.000000e+03</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-3.601955e+02</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_GTP_c0: GTP_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-341.456743</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_MNXM5124_c0: MNXM5124_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-341.456743</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_CYS_c0: CYS_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-355.708698</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_ADENOSYLCOBALAMIN_c0: ADENOSYLCOBALAMIN_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 0.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-355.708698</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_PUTRESCINE_c0: PUTRESCINE_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-400.898401</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_ILE_c0: ILE_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>41.666667</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-500.000000</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_MG+2_c0: MG+2_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>41.666667</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-500.000000</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_MNXM7630_c0: MNXM7630_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 0.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>41.666667</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-500.000000</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_CL-_c0: CL-_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>41.666667</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-500.000000</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_FE+2_c0: FE+2_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.0</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.0</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.0</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-500.0</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_S-ADENOSYLMETHIONINE_c0: S-ADENOSYLMETHIONINE_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>15.085321</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_MNXM7294_c0: MNXM7294_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 83.333</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>-4.930381e-32</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>3.358084e-18</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>-1.947273e-16</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1.000000e+03</td>\n      <td>-3.953350e-16</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>-4.154926e-15</td>\n      <td>-3.218299e-16</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.000000e+00</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_THR_c0: THR_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.0</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.0</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.0</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_5-METHYL-THF_c0: 5-METHYL-THF_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.0</td>\n      <td>-1.397595e-14</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.0</td>\n      <td>-3.944305e-31</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.0</td>\n      <td>9.156212e-15</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.0</td>\n      <td>-3.944305e-31</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.0</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.0</td>\n      <td>9.328447e-15</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.0</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.0</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>0.0</td>\n      <td>0.000000e+00</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_HSO4_c0: HSO4_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.0</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.0</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.0</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_SPERMIDINE_c0: SPERMIDINE_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.0</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.0</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.0</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_CPD-12822_c0: CPD-12822_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>-0.026315</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>-0.026315</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>-0.135739</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-0.026315</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_NADP_c0: NADP_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.0</td>\n      <td>-2.538210e-16</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.0</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.0</td>\n      <td>-2.000000e+00</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.0</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.0</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.0</td>\n      <td>-3.030739e-16</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.0</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.0</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>0.0</td>\n      <td>0.000000e+00</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_PHE_c0: PHE_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-15.166995</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_ARG_c0: ARG_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1.000000e+03</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-9.152838e-14</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_CPD-9728_c0: CPD-9728_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 125.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>-1.946604e-16</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>7.375342e-17</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>-2.464781e-16</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>2.761701e-16</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-9.524337</td>\n      <td>0.000000e+00</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_MET_c0: MET_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1000.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-35.581683</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_MNXM6175_c0: MNXM6175_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 41.667</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>-3.947718e-15</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>-2.742452e-17</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>-1.412946e-14</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-789.915255</td>\n      <td>-5.999849e-15</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-41.309146</td>\n      <td>0.000000e+00</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_FE+3_c0: FE+3_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-640.439026</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-49.428396</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_UBIQUINONE-8_c0: UBIQUINONE-8_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 125.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>1.023910e-15</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>2.517892e-15</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>1.934107e-15</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>-1.014877e+02</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>2.046363e-12</td>\n      <td>0.000000e+00</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_ATP_c0: ATP_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>1.305124e-16</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_SIROHEME_c0: SIROHEME_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 500.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>-4.664638e-14</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>2.731263e-16</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000e+00</td>\n      <td>-3.155444e-30</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>7.065516e-14</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.000000e+00</td>\n      <td>-5.333180e-14</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>1.136868e-13</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-5.000000e+02</td>\n      <td>0.000000e+00</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_UTP_c0: UTP_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 666.667</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>1.998401e-15</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>3.812323e-15</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-3.839384e-17</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>1.554312e-15</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>4.086556e-17</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.000000</td>\n      <td>4.279208e-15</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-346.482802</td>\n      <td>0.000000e+00</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_MNXM5129_c0: MNXM5129_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>-500.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-402.603684</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_FAD_c0: FAD_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 500.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>-3.892979e-13</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>-1.927171e-13</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>4.038968e-28</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>-9.729654e-14</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.000000</td>\n      <td>3.179869e-13</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>-500.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-438.444265</td>\n      <td>0.000000e+00</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_MN+2_c0: MN+2_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>-500.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-453.512931</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_MNXM6440_c0: MNXM6440_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 250.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>2.355903e-16</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>4.979446e-18</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>1.285083e-13</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.000000</td>\n      <td>-1.805419e-16</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>-500.000000</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-433.675665</td>\n      <td>0.000000e+00</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_PYRIDOXAL_PHOSPHATE_c0: PYRIDOXAL_PHOSPHATE_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.0</td>\n      <td>5.547397e-16</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.0</td>\n      <td>7.494704e-16</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.0</td>\n      <td>3.944305e-31</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.0</td>\n      <td>5.427420e-16</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.0</td>\n      <td>-7.395571e-32</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.0</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.0</td>\n      <td>-1.413828e-15</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.0</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>-500.0</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-500.0</td>\n      <td>0.000000e+00</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_TRP_c0: TRP_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.0</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.0</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>-500.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-500.0</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_CU+2_c0: CU+2_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>-500.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-465.106539</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_CO+2_c0: CO+2_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>1000.000000</td>\n      <td>2.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>-500.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-465.106539</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_L-ASPARTATE_c0: L-ASPARTATE_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>1000.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>1000.000000</td>\n      <td>2.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>-500.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-462.440981</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_ZN+2_c0: ZN+2_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 1000.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>1000.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>1000.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>1000.000000</td>\n      <td>2.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>-500.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-489.976786</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_MNXM6297_c0: MNXM6297_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 41.667</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>1000.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>1000.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>1000.000000</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>41.666667</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>-485.707824</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_MNXM78362_c0: MNXM78362_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 125.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.000000e+00</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>-8.289737e-13</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.000000e+00</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_CO+2_c0</th>\n      <td>1.000000e+03</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_L-ASPARTATE_c0</th>\n      <td>1.000000e+03</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ZN+2_c0</th>\n      <td>1.000000e+03</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM6297_c0</th>\n      <td>-2.122746e-13</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM78362_c0</th>\n      <td>1.250000e+02</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1982 rows \u00d7 2 columns</p>\n</div>\n\n\n\n\n```python\nwith model:\n    for blocked in blocked_bio:\n        ex_precursor_reac = model.add_boundary(model.metabolites.get_by_id(blocked.id), type=\"exchange\")\n    for blocked in \"EX_ACP_c0\", \"EX_ADENOSYLCOBALAMIN_c0\", \"EX_MNXM7630_c0\":\n        \n        model.reactions.get_by_id(blocked).bounds=(0, 1000)\n        print(model.reactions.get_by_id(blocked))\n        model.objective=model.reactions.get_by_id(blocked)\n        model.optimize()\n```\n\n    EX_ACP_c0: ACP_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 0.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.0</td>\n      <td>-1.187292e-15</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.0</td>\n      <td>-4.703436e-16</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.0</td>\n      <td>-7.525211e-17</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.0</td>\n      <td>6.769985e-16</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.0</td>\n      <td>-0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_cpd00063_e0</th>\n      <td>0.0</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_cpd00030_e0</th>\n      <td>0.0</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_ADENOSYLCOBALAMIN_c0</th>\n      <td>0.0</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM7630_c0</th>\n      <td>0.0</td>\n      <td>0.000000e+00</td>\n    </tr>\n    <tr>\n      <th>EX_ACP_c0</th>\n      <td>0.0</td>\n      <td>0.000000e+00</td>\n    </tr>\n  </tbody>\n</table>\n<p>1909 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_ADENOSYLCOBALAMIN_c0: ADENOSYLCOBALAMIN_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 0.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.0</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_cpd00063_e0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_cpd00030_e0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ADENOSYLCOBALAMIN_c0</th>\n      <td>0.0</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM7630_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ACP_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1909 rows \u00d7 2 columns</p>\n</div>\n\n\n\n    EX_MNXM7630_c0: MNXM7630_c0 --> \n\n\n\n\n\n<strong><em>Optimal</em> solution with objective value 0.000</strong><br><div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fluxes</th>\n      <th>reduced_costs</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>H2PTEROATESYNTH-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>GLUTATHIONE-SYN-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>MNXR101695_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>HYPOXANPRIBOSYLTRAN-RXN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>RXN-8641_c0</th>\n      <td>0.0</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>EX_cpd00063_e0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_cpd00030_e0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ADENOSYLCOBALAMIN_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n    <tr>\n      <th>EX_MNXM7630_c0</th>\n      <td>0.0</td>\n      <td>-0.0</td>\n    </tr>\n    <tr>\n      <th>EX_ACP_c0</th>\n      <td>0.0</td>\n      <td>0.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>1909 rows \u00d7 2 columns</p>\n</div>\n\n\n\n### Missing essential precursors\n\n\n```python\nmissing_essential=essential_precursors_not_in_biomass(model, model.reactions.bio1)\nmissing_essential\n\nlen(missing_essential)\nfor_real=[]\nfor bio in model.reactions.bio1.metabolites:\n    if bio.annotation[\"metanetx.chemical\"] in missing_essential:\n        for_real.append(bio.annotation[\"metanetx.chemical\"])\n        print(bio.annotation[\"metanetx.chemical\"])\n        bio.compartment\n    \n        \nlen(for_real)\n\n\nmain_comp = find_compartment_id_in_model(model, 'c')\nmain_comp\n\n\n#memote looks for ids not in the annotation field, my IDs contain c0 \n```\n\n\n```python\n\nlist_not_missing_met=[]  \nlist_missing_met=[] \nfor met in model.metabolites:\n    for mis in missing_essential:\n        if mis in met.annotation.values():\n           \n            list_not_missing_met.append(mis)\n            print(met.id, mis)\n        elif mis not in met.annotation.values():\n            list_missing_met.append(met.id)\n            \nlen(set(list_not_missing_met) )\nlist_missing_met\n#37 vs. 52 missing metabolite--> duplication in e0/c0\n\n\n```\n\n\n```python\nboth=set()      #because of duplicate ids c0 e0  \nfor met in model.metabolites:\n    for mis in missing_essential:\n        if mis in met.annotation.values():\n            both.add(mis)\n            \nlen(both)            \nprint(both)            \n  \n#no missing essential precursors\n```\n\n### Blocked biomass precursors\n\n\n```python\n#blocked=find_blocked_biomass_precursors(model, model.reactions.bio1)\n\nblocked_bio=find_blocked_biomass_precursors(model.reactions.bio1, model)\nblocked_bio\n```\n\n\n\n\n    [<Metabolite ADENOSYLCOBALAMIN_c0 at 0x10d65f2b0>,\n     <Metabolite MNXM7630_c0 at 0x10ea882e8>,\n     <Metabolite ACP_c0 at 0x10e7cc898>]\n\n\n\n### Sum biomass weight\n\n\n```python\nwith model:\n    \n    for met in model.metabolites:\n        \n        met.formula=re.sub(\"(([R])\\d+)\", \"\", met.formula)\n        met.formula=re.sub(\"([R])\" , \"\", met.formula)\n        met.formula=re.sub(\"(MISSING)\" , \"\", met.formula)\n        \n    #sum_bio=sum_biomass_weight(model.reactions.bio1)\n    #sum_bio\n       \n            \n```\n\n\n```python\nsum_bio=sum_biomass_weight(model.reactions.bio1)\nsum_bio\n       \n```\n\n### Growth associated maintenance\n\n\n```python\n#growth-associated maintenance\n#True if the biomass reaction includes ATP and H2O as reactants and ADP,Pi and H as products, False otherwise.\ngam=gam_in_biomass(model, model.reactions.bio1)\ngam\nmodel.reactions.bio1.reaction\n#What does it check(id?)?\n\nmodel.metabolites.MNXM2214_c0\nmodel.metabolites.MNXM5258_c0\nmodel.metabolites.MNXM90619_c0\n\n\n```\n\n### False positive direct metabolites\n\n### Bundle biomass components\n\n\n```python\nbundle=bundle_biomass_components(model, model.reactions.bio1)\nbundle\n```\n\n### Find direct metabolites\n\n\n```python\n\nwith model: \n    #for met in model.metabolites:\n     #   if \"(\" in met.formula:\n      #      print(met.formula, met.id)\n            \n  \n    model.metabolites.MNXM8231_c0.formula=\"C21H33N5O9P2\"\n   \n    model.metabolites.get_by_id(\"DNA-6-O-Methyl-Guanines_c0\").formula=\"C10H16N2NO2O6S\"\n    model.metabolites.MNXM8231_c0.formula\n    model.metabolites.get_by_id(\"DNA-6-O-Methyl-Guanines_c0\").formula\n    direct_met=find_direct_metabolites(model, model.reactions.bio1, tolerance=1e-06)\n    \n    direct_met\n   \n   #     met.formula=re.sub(\"(([R])\\d+)\", \"\", met.formula)\n   #     met.formula=re.sub(\"(([R]))\" , \"\", met.formula)\n   #     met.formula=re.sub(\"(MISSING)\" , \"\", met.formula)\n        \n    sum_bio=sum_biomass_weight(model.reactions.bio1)\n    sum_bio\n    \n```\n\n### Stoichiometric consistency\n\n\n```python\nstoich=check_stoichiometric_consistency(model)\nstoich\n```\n\n### Reset the exchange fluxes to zero\n\nChange the exchange fluxes to zero. Then add the ones that are necessary for minimal media. (What if there is no media that we want? How does the media work ? Where does it show? \nCreate a dictionary where there is a readable format for the medium. Is there an annotation field for medium? \n\n\n```python\n#model.reactions.EX_cpd00009_e0.bounds = (0,1000)\n\n    \nwith model:\n    \n    for reac in model.reactions:\n        if reac.id.startswith(\"EX\") or  [\"MNXR137716_c0\", 'MNXR137717_c0', 'MNXR137715_c0']:\n            reac.bounds=(0,0)\n        \n    model.medium \n    model.reactions.EX_cpd00012_e0.bounds = (-1000,1000) #ppi\n    model.reactions.EX_cpd00009_e0.bounds = (-1000,1000) #pi\n    model.reactions.EX_cpd00209_e0.bounds = (-1000,1000) #NO3\n    model.reactions.EX_cpd00075_e0.bounds = (-1000,1000) #NO2\n    model.reactions.EX_cpd00013_e0.bounds = (-1000,1000) #NH4\n    model.reactions.EX_cpd00048_e0.bounds = (-1000,1000) #SO4\n    model.reactions.EX_cpd00027_e0.bounds = (-1000,1000) #D-glucose\n    model.reactions.EX_cpd00971_e0.bounds = (-1000,1000) #Na+\n    model.reactions.EX_cpd00076_e0.bounds = (-1000,1000) #Sucrose\n    model.reactions.EX_cpd00080_e0.bounds = (-1000,1000) #D-Glycerol 1-phosphate\n    model.reactions.EX_cpd00001_e0.bounds = (-1000,1000) #H2O\n    model.reactions.EX_cpd00011_e0.bounds = (-1000,1000) #CO2\n    model.reactions.EX_cpd00067_e0.bounds = (-1000,1000) #H+\n    model.reactions.EX_cpd00063_e0.bounds = (-1000,1000) #Ca2+\n    model.reactions.EX_cpd00099_e0.bounds = (-1000,1000) #Cl-\n    model.reactions.EX_cpd00205_e0.bounds = (-1000,1000) #K+\n    model.reactions.EX_cpd00254_e0.bounds = (-1000,1000) #Mg2+\n    model.reactions.EX_cpd00030_e0.bounds = (-1000,1000) #Mn2+\n    model.reactions.EX_cpd00007_e0.bounds = (-1000,1000) #O2\n    model.reactions.MNXR137716_c0.bounds = (-1000,1000) #\n    model.reactions.MNXR137715_c0.bounds = (-1000,1000) #\n    model.reactions.MNXR137717_c0.bounds = (-1000,1000) #\n    model.reactions.EX_cpd00058_e0.bounds = (-1000,1000) #Cu2+\n    model.reactions.EX_cpd10515_e0.bounds = (-1000,1000) #Fe2+\n    model.reactions.EX_cpd10516_e0.bounds = (-1000,1000) #Fe2+\n    model.reactions.EX_cpd00034_e0.bounds = (-1000,1000) #Fe2+\n    \n    model.reactions.EX_cpd00035_e0.bounds = (-1000,1000) #Fe2+\n    model.reactions.EX_cpd00039_e0.bounds = (-1000,1000) #Fe2+\n    model.reactions.EX_cpd00041_e0.bounds = (-1000,1000) #Fe2+\n    model.reactions.EX_cpd11580_e0.bounds = (-1000,1000) #Fe2+\n    model.reactions.EX_cpd00023_e0.bounds = (-1000,1000) #Fe2\n    model.slim_optimize()\n    \n\n    model.medium\n    #model.optimize()\n    \n    model.reactions.MNXR137715_c0\n```\n\n### Existing media and their description to dict\n\n\n```python\nchem_xref = read_csv(\"/Users/lizrad/Documents/Vibrio_folder/chem_xref.tsv\" , sep='\\t' , low_memory=False)\nchem_xref\n#499091 530559\n\ndf_seed = chem_xref.loc[499088:530556,'XREF':'Description']\npivoted_seed = df_seed.pivot_table(index='XREF',columns='XREF_ID',values='Description',aggfunc = lambda x: x)\n\n#pivoted_seedd=pivoted_seed.drop(['metanetx'])\npivoted_seed\nchem_xref_MNX_seed_dict = pivoted_seed.to_dict('index')\nchem_xref_MNX_seed_dict2 = chem_xref_MNX_seed_dict['seed']\nprint(chem_xref_MNX_seed_dict2)\n\n```\n\n\n```python\n#MNXR137716_c0','MNXR137717_c0','MNXR137715_c0' dont have seed IDs\nmedium_dict={}\nfor med in model.medium:\n    if med.startswith(\"MNXR\"):\n        continue\n    pre, seed, compartment=med.split(\"_\")\n    print(seed)\n    for k in chem_xref_MNX_seed_dict2.keys():\n        if seed in k: \n            print (chem_xref_MNX_seed_dict2[k])\n            medium_dict[pre+\"_\"+seed+\"_\"+compartment]=chem_xref_MNX_seed_dict2[k]\n            \nprint(medium_dict)\n```\n\n\n```python\n#check every combinations of mediums :(  \n#for L in range(0, len(model.medium)+1):\n#    for subset in itertools.combinations(model.medium, L):\n#        print(subset)\n```\n\nFrom KBase download medium in tsv. Try LB(Lysogeny Broth) and minimal nms(nitrate minimal salts medium). With Edit Media Application in KBase one can modify the existing medium) \n\nResult: No growth (neither).\nCheck for blocked precursors: both blocked with 76 metabolites. \n\n\n\n```python\nmedia_nms = read_csv(\"/Users/lizrad/Documents/Vibrio_folder/LB.tsv\" , sep='\\t' , low_memory=False)\n#media_nms = read_csv(\"/Users/lizrad/Documents/Vibrio_folder/minimal_nms.tsv\" , sep='\\t' , low_memory=False)\nmedia_nms\n\ncomp_list=media_nms[\"compounds\"].tolist()\n\nwith model:\n    for met in model.metabolites: \n        if met.annotation[\"seed.compound\"] in comp_list: \n            print(met.id, met.annotation[\"seed.compound\"])\n\n        \n    #Adding the direct metabolites as exchange reactions\n         \n    for reac in model.reactions:\n        if reac.id.startswith(\"EX\"):\n            \n            reac.bounds=(0,0)\n            reac.id\n            pre, seed, compart =reac.id.split(\"_\")\n            if seed in comp_list: \n                reac.bounds=(-1000,1000)\n            for i in direct_met:\n                meta, compart =i.id.split(\"_\")\n                if meta in seed:\n                    reac.bounds\n                    reac.bounds=(-1000,1000)\n                    reac.bounds\n    for d in direct_met:\n        model.add_boundary(model.metabolites.get_by_id(d.id), type=\"exchange\", reaction_id=None, lb=-1000.0, ub=1000.0)\n    #\n    model.medium\n    len(model.medium)\n    model.optimize().objective_value\n    model.summary()\n    \n   # blocked_precursors=find_blocked_biomass_precursors(model.reactions.bio1, model)\n   # blocked_precursors\n   # len(blocked_precursors)\n#model.reactions.get_by_id['EX_cpd00067_e0'].bounds\n\n    \n```\n\n\n```python\ndirect_list=[]\nwith model:\n    \n    for d in direct_met:\n        metanet,suff =d.id.split(\"_\")\n        direct_list.append(d.id)\n        \ndirect_list\n\n\n```\n\n\n```python\ndirect_met_reaction_dict={}\nfor reac in model.reactions:\n    for rmet in reac.metabolites:\n    \n        if  rmet in direct_met:\n            #direct_met_reaction_dict[direct_met].append(rmet)\n            print(rmet, \"is in the reaction of \", reac)\n            \n            \n\n```\n\nSetting the direct precursors to medium, those that are already in the medium are found, the other direct metabolites cannot be found among the mediums. \n\n\n```python\n \nwith model:\n    \n    for d in direct_list:\n        pre1, suff1 =d.split(\"_\")\n        \n        \n        #create a new metabolite in the e0 compartment\n        mcopy=model.metabolites.get_by_id(\"K+_c0\").copy()\n        mcopy.compartment = 'e0'\n        mcopy.id = pre1+\"_e0\"\n        mcopy.formula=\"\"\n        mcopy.name=\"\"\n        model.add_metabolites(mcopy)\n        \n        mcopy\n        #create a new reaction between the c0 and e0 compartment\n        \n        rcopy=model.reactions.get_by_id(\"TRANS-RXN-143_c0\").copy()\n        rcopy.id=\"TRANS_\"+d\n        for r in rcopy.metabolites:\n            r.remove_from_model\n        #model.reactions.get_by_id(rcopy).subtract_metabolites()   \n        rcopy.name=\"\"\n        rcopy.gene_reaction_rule=\"\"\n        pre, suff=mcopy.id.split(\"_\")\n        rcopy.add_metabolites({\n        model.metabolites.get_by_id(pre+\"_c0\"): -1.0, model.metabolites.get_by_id(mcopy.id): 1.0 })\n        rcopy.reaction\n        \nmodel.reactions.get_by_id(\"TRANS-RXN-143_c0\")   \n\n```\n\n\n```python\nfrom memote.support.helpers import find_transport_reactions\n```\n\n\n```python\nfor rxn in model.metabolites.MNXM5129_c0.reactions:\n    rxn\n    if rxn in find_transport_reactions(model):\n        print(rxn.id)\n```\n\n\n```python\nfor met in model.reactions.MNXR136333_c0.metabolites:\n    print(met.compartment, met.formula)\nmodel.reactions.MNXR136333_c0.copy\n```\n\n\n```python\nfor met in model.reactions.MNXR136261_c0.metabolites:\n    print(met, met.compartment, met.formula, met.annotation)\nmodel.reactions.MNXR136261_c0.reaction\nmodel.reactions.MNXR136261_c0.annotation\n```\n\n\n```python\nfor met in model.reactions.MNXR136333_c0.metabolites:\n    print(met, met.compartment, met.formula)\nmodel.reactions.MNXR136333_c0.reaction\n```\n\n\n```python\nlen(find_transport_reactions(model))\n\n```\n\n\n```python\n\nwith model: \n   # add_ex = model.add_boundary(model.metabolites.MNXM6175_c0, type=\"exchange\")\n    #add_ex.id\n    \n    for d in direct_met:\n        if d not in model.medium:\n            metd=d.id\n            model.metabolites.get_by_id(metd)\n            model.add_boundary(model.metabolites.get_by_id(d.id), type=\"exchange\", reaction_id=\"EX\"+\"_\"+metd, lb=-1000, ub=1000)\n        #model.reactions.add(add_ex)\n        #model.reactions.EX\n    for reac in model.reactions:\n        \n        if reac.id.startswith(\"EX\"):\n            print(reac.id)\n    \n    model.medium\n    model.optimize()\n    model.exchanges\n\n    \n        \n```\n\n\n```python\nfor reac in model.reactions:\n    B=is_boundary_type(reac, \"exchange\", \"c0\")\n    \n    if B :\n        reac.id\n```\n\n\n```python\nfrom memote.support.helpers import find_biomass_reaction\nwith model:\n    model.reactions.bio1.annotation['sbo'] = 'SBO:0000629'\n    #model.reactions.bio1.annotation['SBO'] = 'SBO:0000629'\n    model.reactions.bio1.annotation\n    #model.reactions.bio1.id=\"biomass\"\n\n    biomass_reac=find_biomass_reaction(model)\n    biomass_reac\n\n#write_sbml_model(model, \"/Users/lizrad/Dev/iVnat/iVnat.xml\")\n    \n```\n\n\n```python\n#what is the id for the selected substrates from seed id\nsubstrate=[\"cpd00076\",\"cpd00027\", \"cpd00080\",\"cpd00179\", \"cpd00082\", \"cpd00036\", \"cpd00224\", \"cpd00314\", \"cpd00020\",\"cpd00029\",\"cpd00154\",\n           \"cpd00208\",\"cpd00138\",\"cpd00158\",\"cpd00363\",\"cpd00116\",\"cpd00047\"]\n\nfor met in model.metabolites:\n    if met.annotation[\"seed.compound\"] in substrate and met.compartment==\"c0\":\n        print(met.id, met.annotation[\"seed.compound\"] )\n\n        \n#does the subsrate have exchange reaction        \n\nex_substrate=[]        \nfor exchange in medium_dict.keys():\n    ex, seed, suff=exchange.split(\"_\")\n    if  seed in substrate:\n        print(exchange, medium_dict[exchange])\n        ex_substrate.append(exchange)\n\n\n\n```\n\n### Transport reaction bug\n\n\n```python\nfrom __future__ import absolute_import\n\nimport logging\nimport re\nfrom collections import defaultdict\nfrom operator import itemgetter\n\n\nimport numpy as np\nimport pandas as pd\nfrom six import iteritems, itervalues\nfrom sympy import expand\nfrom importlib_resources import open_text\nfrom cobra.exceptions import Infeasible\nfrom cobra.medium import find_boundary_types\nfrom pylru import lrudecorator\n\nimport memote.utils as utils\nimport memote.support.data\nimport memote.utils as utils\nimport memote.support.data\nfrom memote.support.helpers import find_biomass_reaction\n```\n\n\n```python\nimport memote\nimport cobra\n```\n\n\n```python\nfrom cobra import Model, Reaction, Metabolite\n# Best practise: SBML compliant IDs\nmodel2 = Model('example_model')\n\n#def abc_pump_annotations(base):\n   # \"\"\"Provide a model with an ABC transport reaction.\"\"\"\natp = cobra.Metabolite(\"atp_c\", compartment=\"c\")\nadp = cobra.Metabolite(\"adp_c\", compartment=\"c\")\nh = cobra.Metabolite(\"h_c\", formula=\"H\",compartment=\"c\")\npi = cobra.Metabolite(\"pi_c\", compartment=\"c\")\nh2o = cobra.Metabolite(\"h2o_c\", formula=\"H2O\", compartment=\"c\")\naso_c = cobra.Metabolite(\"aso3_c\", compartment=\"c\")\naso_e = cobra.Metabolite(\"aso3_e\", compartment=\"e\")\n\natp.annotation[\"biocyc\"] = [\"META:ATP\", \"META:CPD0-1634\"]\nadp.annotation[\"biocyc\"] = [\"META:ADP\", \"META:CPD0-1651\"]\nh.annotation[\"biocyc\"] = \"META:PROTON\"\npi.annotation[\"biocyc\"] = [\"META:CPD-16459\", \"META:CPD-9010\"]\nh2o.annotation[\"biocyc\"] = [\"META:CPD-15815\", \"META:HYDROXYL-GROUP\"]\naso_c.annotation[\"biocyc\"] = [\"META:CPD0-2040\", \"META:CPD-763\"]\naso_e.annotation[\"biocyc\"] = [\"META:CPD0-2040\", \"META:CPD-763\"]\n\npump = cobra.Reaction(\"PUMP\")\npump.add_metabolites({aso_c: -1, atp: -1, h2o: -1,\n                          adp: 1, h: 1, pi: 1, aso_e: 1})\nmodel2.add_reactions([pump])\n####################\nMNXM11392_c0 = cobra.Metabolite(\"MNXM11392_c0\", formula=\"C40H78O13P2\", compartment=\"c\" )\nMNXM5129_c0 = cobra.Metabolite(\"MNXM5129_c0\", formula=\"C40H78O10P\", compartment=\"c\" )\nCPD_16459_c0 = cobra.Metabolite(\"CPD_16459_c0\", formula=\"HO4P\", compartment=\"c\" )\n\n#MNXM11392_c0 = cobra.Metabolite(\"MNXM11392_c0\",  compartment=\"c\" )\n#MNXM5129_c0 = cobra.Metabolite(\"MNXM5129_c0\",  compartment=\"c\" )\n#CPD_16459_c0=cobra.Metabolite(\"MNXM5129_c0\",  compartment=\"c\" )\nh2o.annotation['bigg.metabolite']=['h2o', 'oh1']\nh2o.annotation[\"chebi\"]=['CHEBI:15377']\nh2o.annotation['inchi']=['InChI=1S/H2O/h1H2']\nMNXM11392_c0.annotation={'inchi': 'MISSING', 'inchikey': 'MISSING', 'metanetx.chemical': 'MNXM11392', 'seed.compound': 'cpd15716', 'smiles': 'MISSING'}\nCPD_16459_c0.annotation={'bigg.metabolite': 'pi', 'biocyc': ['CPD-16459', 'CPD-9010', 'PHOSPHATE-GROUP', 'Pi'], 'chebi': 'CHEBI:43474', 'inchi': 'InChI=1S/H3O4P/c1-5(2,3)4/h(H3,1,2,3,4)/p-2', 'inchikey': 'NBIIXXVUZAFLBC-UHFFFAOYSA-L', 'kegg.compound': ['C00009', 'C13558'], 'metanetx.chemical': 'MNXM9', 'seed.compound': 'cpd00009', 'smiles': 'OP([O-])([O-])=O'}\nMNXM5129_c0.annotation={'inchi': 'MISSING', 'inchikey': 'MISSING', 'metanetx.chemical': 'MNXM5129', 'seed.compound': 'cpd15722', 'smiles': 'MISSING'}\n\n\n\nMNXR136261_c0=cobra.Reaction(\"MNXR136261_c0\")\nMNXR136261_c0.add_metabolites({ MNXM11392_c0: -1, h2o: -1,\n                           h: 1, CPD_16459_c0: 1, MNXM5129_c0: 1})\n\nmodel2.add_reactions([MNXR136261_c0])\n#'CPD-15815_c0 + MNXM11392_c0 --> CPD-16459_c0 + MNXM5129_c0 + PROTON_c0'\n####################\n\n\nGLYCEROL_c0 = cobra.Metabolite(\"GLYCEROL_c0\", formula=\"C3H8O3\", compartment=\"c\" )\nMNXM6297_c0 = cobra.Metabolite(\"MNXM6297_c0\", formula=\"C77H148O17P2\", compartment=\"c\" )\n\n\nMNXR136333_c0=cobra.Reaction(\"MNXR136333_c0\", lower_bound=-1000)\nMNXR136333_c0.add_metabolites({ MNXM5129_c0: -2, GLYCEROL_c0: 1,\n                           MNXM6297_c0: 1})\n\nmodel2.add_reactions([MNXR136333_c0])\n\n\n\n\nmodel2\n    #return base\nprint('%i reaction' % len(model2.reactions))\nprint('%i metabolites' % len(model2.metabolites))\nprint('%i genes' % len(model2.genes))\npump.reaction\nMNXR136261_c0.reaction\nMNXR136333_c0.reaction\nMNXM5129_c0.annotation\n    \n\n```\n\n\n```python\ndef find_biomass_reaction(model):\n    \"\"\"\n    Return a list of the biomass reaction(s) of the model.\n    This function identifies possible biomass reactions using two steps:\n    1. Return reactions that include the SBO annotation \"SBO:0000629\" for\n    biomass.\n    If no reactions can be identifies this way:\n    2. Look for the ``buzzwords`` \"biomass\", \"growth\" and \"bof\" in reaction IDs.\n    3. Look for metabolite IDs or names that contain the ``buzzword`` \"biomass\"\n    and obtain the set of reactions they are involved in.\n    4. Remove boundary reactions from this set.\n    5. Return the union of reactions that match the buzzwords and of the\n    reactions that metabolites are involved in that match the buzzword.\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model under investigation.\n    Returns\n    -------\n    list\n        Identified biomass reactions.\n    \"\"\"\n    sbo_matches = set([rxn for rxn in model.reactions if\n                       rxn.annotation is not None and\n                       'SBO' in rxn.annotation and\n                       rxn.annotation['SBO'] == 'SBO:0000629'])\n\n    if len(sbo_matches) > 0:\n        return list(sbo_matches)\n\n    buzzwords = ['biomass', 'growth', 'bof']\n\n    buzzword_matches = set([rxn for rxn in model.reactions if any(\n        string in rxn.id.lower() for string in buzzwords)])\n\n    biomass_met = []\n    for met in model.metabolites:\n        if met.id.lower().startswith('biomass') or met.name.lower().startswith(\n            'biomass'\n        ):\n            biomass_met.append(met)\n    if biomass_met == 1:\n        biomass_met_matches = set(\n            biomass_met.reactions\n        ) - set(model.boundary)\n    else:\n        biomass_met_matches = set()\n\n    return list(buzzword_matches | biomass_met_matches)\n\n```\n\n\n```python\ndef is_transport_reaction_formulae(rxn):\n    \"\"\"\n    Return boolean if a reaction is a transport reaction (from formulae).\n    Parameters\n    ----------\n    rxn: cobra.Reaction\n        The metabolic reaction under investigation.\n    \"\"\"\n    # Collecting criteria to classify transporters by.\n    rxn_reactants = set([met.formula for met in rxn.reactants])\n    rxn_products = set([met.formula for met in rxn.products])\n    # Looking for formulas that stay the same on both side of the reaction.\n    transported_mets = \\\n        [formula for formula in rxn_reactants if formula in rxn_products]\n    # Collect information on the elemental differences between\n    # compartments in the reaction.\n    delta_dicts = find_transported_elements(rxn)\n    non_zero_array = [v for (k, v) in iteritems(delta_dicts) if v != 0]\n    # Excluding reactions such as oxidoreductases where no net\n    # transport of Hydrogen is occurring, but rather just an exchange of\n    # electrons or charges effecting a change in protonation.\n    if set(transported_mets) != set('H') and list(\n        delta_dicts.keys()\n    ) == ['H']:\n        pass\n    # All other reactions for which the amount of transported elements is\n    # not zero, which are not part of the model's exchange nor\n    # biomass reactions, are defined as transport reactions.\n    # This includes reactions where the transported metabolite reacts with\n    # a carrier molecule.\n    elif sum(non_zero_array):\n        return True\n```\n\n\n```python\ndef find_transported_elements(rxn):\n    \"\"\"\n    Return a dictionary showing the amount of transported elements of a rxn.\n    Collects the elements for each metabolite participating in a reaction,\n    multiplies the amount by the metabolite's stoichiometry in the reaction and\n    bins the result according to the compartment that metabolite is in. This\n    produces a dictionary of dictionaries such as this\n    ``{'p': {'C': -1, 'H': -4}, c: {'C': 1, 'H': 4}}`` which shows the\n    transported entities. This dictionary is then simplified to only include\n    the non-zero elements of one single compartment i.e. showing the precise\n    elements that are transported.\n    Parameters\n    ----------\n    rxn : cobra.Reaction\n        Any cobra.Reaction containing metabolites.\n    \"\"\"\n    element_dist = defaultdict()\n    # Collecting elements for each metabolite.\n    for met in rxn.metabolites:\n        if met.compartment not in element_dist:\n            # Multiplication by the metabolite stoichiometry.\n            element_dist[met.compartment] = \\\n                {k: v * rxn.metabolites[met]\n                 for (k, v) in iteritems(met.elements)}\n        else:\n            x = {k: v * rxn.metabolites[met] for (k, v) in\n                 iteritems(met.elements)}\n            y = element_dist[met.compartment]\n            element_dist[met.compartment] = \\\n                {k: x.get(k, 0) + y.get(k, 0) for k in set(x) | set(y)}\n    delta_dict = defaultdict()\n    # Simplification of the resulting dictionary of dictionaries.\n    for elements in itervalues(element_dist):\n        delta_dict.update(elements)\n    # Only non-zero values get included in the returned delta-dict.\n    delta_dict = {k: abs(v) for (k, v) in iteritems(delta_dict) if v != 0}\n    return delta_dict\n\n```\n\n\n```python\ndef is_transport_reaction_annotations(rxn):\n    \"\"\"\n    Return boolean if a reaction is a transport reaction (from annotations).\n    Parameters\n    ----------\n    rxn: cobra.Reaction\n        The metabolic reaction under investigation.\n    \"\"\"\n    reactants = set([(k, tuple(v)) for met in rxn.reactants\n                     for k, v in iteritems(met.annotation)\n                     if met.id is not \"H\" and k is not None and v is not None])\n    #print(\"reactants\", reactants)\n    products = set([(k, tuple(v)) for met in rxn.products\n                    for k, v in iteritems(met.annotation)\n                    if met.id is not \"H\" and k is not None and v is not None])\n    #print(\"products\", products)\n    # Find intersection between reactant annotations and\n    # product annotations to find common metabolites between them,\n    # satisfying the requirements for a transport reaction. Reactions such\n    # as those involving oxidoreductases (where no net transport of\n    # Hydrogen is occurring, but rather just an exchange of electrons or\n    # charges effecting a change in protonation) are excluded.\n    transported_mets = reactants & products\n    #print(\"transported_mets\", transported_mets, len(transported_mets))\n    \n    if len(transported_mets) > 0:\n        return True\n\n```\n\n\n```python\ndef find_transport_reactions(model):\n    \"\"\"\n    Return a list of all transport reactions.\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model under investigation.\n    Notes\n    -----\n    A transport reaction is defined as follows:\n    1. It contains metabolites from at least 2 compartments and\n    2. at least 1 metabolite undergoes no chemical reaction, i.e.,\n    the formula and/or annotation stays the same on both sides of the equation.\n    A notable exception is transport via PTS, which also contains the following\n    restriction:\n    3. The transported metabolite(s) are transported into a compartment through\n    the exchange of a phosphate group.\n    An example of transport via PTS would be\n    pep(c) + glucose(e) -> glucose-6-phosphate(c) + pyr(c)\n    Reactions similar to transport via PTS (referred to as \"modified transport\n    reactions\") follow a similar pattern:\n    A(x) + B-R(y) -> A-R(y) + B(y)\n    Such modified transport reactions can be detected, but only when a formula\n    field exists for all metabolites in a particular reaction. If this is not\n    the case, transport reactions are identified through annotations, which\n    cannot detect modified transport reactions.\n    \"\"\"\n    transport_reactions = []\n    transport_rxn_candidates = set(model.reactions) - set(model.boundary) \\\n        - set(find_biomass_reaction(model))\n    #print(\"transport_rxn_candidates\",transport_rxn_candidates)\n    # Add all labeled transport reactions\n    sbo_matches = set([rxn for rxn in transport_rxn_candidates if\n                       rxn.annotation is not None and\n                       'SBO' in rxn.annotation and\n                       rxn.annotation['SBO'] in TRANSPORT_RXN_SBO_TERMS])\n    if len(sbo_matches) > 0:\n        transport_reactions += list(sbo_matches)\n    # Find unlabeled transport reactions via formula or annotation checks\n    for rxn in transport_rxn_candidates:\n        # Check if metabolites have formula field\n        rxn_mets = set([met.formula for met in rxn.metabolites])\n        if (None not in rxn_mets) and (len(rxn_mets) != 0):\n            if is_transport_reaction_formulae(rxn):\n                transport_reactions.append(rxn)\n        elif is_transport_reaction_annotations(rxn): #\n            transport_reactions.append(rxn)\n       # print(\"rxn_mets\",rxn_mets)\n    return set(transport_reactions)\n\n    \n```\n\n\n```python\nfor rxn in model.metabolites.MNXM5129_c0.reactions:\n    \n    if rxn in find_transport_reactions(model):\n        print(rxn.id)\n```\n\n\n```python\nmodel2_trans=memote.support.helpers.find_transport_reactions(model2)\nmodel2_trans\n#find_direct_metabolites(model, bio1)\n```\n\n\n```python\nmodel2_bio=find_biomass_reaction(model2)\nmodel2_bio\n```\n\n\n```python\nfind_transported_elements(MNXR136261_c0)\n```\n\n\n```python\nistranspann=is_transport_reaction_annotations(MNXR136261_c0)\nistranspann\n```\n\n### Blocked precursors bug\n\n\n```python\nmissing_essential=essential_precursors_not_in_biomass(model, model.reactions.bio1)\nmissing_essential\n\n```\n\n\n```python\ndef find_biomass_precursors(model, reaction):\n    \"\"\"\n    Return a list of all biomass precursors excluding ATP and H2O.\n    Parameters\n    ----------\n    reaction : cobra.core.reaction.Reaction\n        The biomass reaction of the model under investigation.\n    model : cobra.Model\n        The metabolic model under investigation.\n    Returns\n    -------\n    list\n        Metabolite objects that are reactants of the biomass reaction excluding\n        ATP and H2O.\n    \"\"\"\n    id_of_main_compartment =find_compartment_id_in_model(model, 'c')\n    print(id_of_main_compartment)\n    gam_reactants = set()\n    try:\n        gam_reactants.update([\n            find_met_in_model(\n                model, \"MNXM3\", id_of_main_compartment)[0]])\n    except RuntimeError:\n        pass\n    try:\n        gam_reactants.update([\n            find_met_in_model(\n                model, \"MNXM2\", id_of_main_compartment)[0]])\n    except RuntimeError:\n        pass\n\n    biomass_precursors = set(reaction.reactants) - gam_reactants\n    print(\"number of gam\", gam_reactants)\n    \n    \n\n    return list(biomass_precursors)\n```\n\n\n```python\nmet = cobra.Metabolite('test')\nrxn = cobra.Reaction(id='test2')\nrxn.add_metabolites({met: 1})\n```\n\n\n```python\nrxn.add_metabolites({met: -1})\n```\n\n\n```python\nrxn\n```\n\n\n```python\n\nimport logging\nLOGGER = logging.getLogger(__name__)\ndef find_blocked_biomass_precursors(reaction, model):\n    \n    LOGGER.debug(\"Finding blocked biomass precursors\")\n    precursors = find_biomass_precursors(model, reaction)\n    precursors\n    blocked_precursors = list()\n    for precursor in precursors:\n        precursor\n        with model:\n            dm_rxn = model.add_boundary(precursor, type=\"demand\")\n            \n            model.objective = dm_rxn\n            try:\n                print(\"demand reaction\", dm_rxn)\n                solution = model.optimize()\n                \n                \n                print(solution)\n                LOGGER.debug(\n                    \"%s: demand flux is '%g' and solver status is '%s'\",\n                    str(precursor), solution.objective_value, solution.status)\n                \n                if solution.objective_value <= 0.0:\n                    blocked_precursors.append(precursor)\n                    print(\"obj value 0 or negative:\", blocked_precursors)\n            except Infeasible:\n                blocked_precursors.append(precursor)\n                \n    return blocked_precursors\n```\n\n\n```python\nfrom memote.support.helpers import find_met_in_model, find_compartment_id_in_model\nx=find_biomass_precursors(model, model.reactions.bio1)\n\nlen(x)\nlen(model.reactions.bio1.reactants)\nmodel.metabolites.ACP_c0\nmodel.metabolites.ADENOSYLCOBALAMIN_c0\nmodel.metabolites.MNXM7630_c0\n```\n\n\n```python\nwith model:\n    rxn=model.add_boundary(model.metabolites.ACP_c0, type=\"exchange\")\n    model.objective = rxn\n    solution = model.optimize()\n    solution\n    lin=linear_reaction_coefficients(model)\n    lin\n    solution.status\n    model.summary()\n    solution.fluxes\n    solution.shadow_prices\n    rxn.bounds\n    model.metabolites.ACP_c0.reactions\n    \n```\n\n\n```python\nfrom cobra.util.solver import linear_reaction_coefficients\nblocked_bio_precursor=find_blocked_biomass_precursors(model.reactions.bio1, model)\n\n```\n\n\n```python\nprint(model.objective)\n```\n\n\n```python\nmodel.optimize()\n```\n\n\n```python\nwith model: \n    #bio_copy=model.reactions.bio1.copy()\n    #bio_copy\n    #model.add_reaction(bio_copy)\n    \n    model.reactions.bio1.metabolites\n    model.reactions.bio1.add_metabolites({model.metabolites.ACP_c0: +0.003096466851925328, model.metabolites.ADENOSYLCOBALAMIN_c0: +0.003096466851925328, model.metabolites.MNXM7630_c0: +0.025010597710894533 })\n    model.reactions.bio1.metabolites\n    #for reac in model.reactions:\n    #    if reac.id.startswith(\"EX\"):\n    #        model.reactions.bio1.bounds=(0,0)\n    \nwith model:\n    reac_list=[]\n    \n    for blo in blocked_bio_precursor:\n        blo\n        dm_rxn = model.add_boundary(blo, type=\"demand\", reaction_id='test')\n        model.objective = dm_rxn.id\n        print(model.objective)\n        reac_list.append(dm_rxn)\n       # dm_rxn.bounds=(0,0)\n        print ('#####'*50)\n        model.optimize()\n        print ('#####'*50)\n        model.summary\n    \n    #model.reactions.bio1.metabolites\n    #model.reactions.bio1.add_metabolites({model.metabolites.ACP_c0: -1, model.metabolites.ADENOSYLCOBALAMIN_c0: -1, model.metabolites.MNXM7630_c0:-1 })\n    #model.add_reactions(reac_list)\n    \nwith model:\n    blocked_fx=find_blocked_biomass_precursors(model.reactions.bio1, model)\n    print ('Blocked Precursors')\n    blocked_fx\n   \n    model.optimize()\n    model.summary\n    \n        \n    model.metabolites.ACP_c0.reactions\n    model.reactions.MNXR109353_c0\n        \n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "c8b305249d8b2b03b82ff9929f47595bc82c8c69", "size": 315864, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ComplementaryScripts/Minimal_media.ipynb", "max_stars_repo_name": "ChristianLieven/iVnat", "max_stars_repo_head_hexsha": "bee94544702b41c51bb026b6cb0694857e69bc81", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-02-22T18:52:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-15T10:59:33.000Z", "max_issues_repo_path": "ComplementaryScripts/Minimal_media.ipynb", "max_issues_repo_name": "biosustain/iVnat", "max_issues_repo_head_hexsha": "bee94544702b41c51bb026b6cb0694857e69bc81", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-03-11T12:45:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-08T07:40:30.000Z", "max_forks_repo_path": "ComplementaryScripts/Minimal_media.ipynb", "max_forks_repo_name": "ChristianLieven/iVnat", "max_forks_repo_head_hexsha": "bee94544702b41c51bb026b6cb0694857e69bc81", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5714285714, "max_line_length": 2634, "alphanum_fraction": 0.3988235443, "converted": true, "num_tokens": 70199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702253786982541, "lm_q2_score": 0.020964238983072696, "lm_q1q2_score": 0.00776149331662879}}
{"text": "```\n!pip install trax\n```\n\n    Collecting trax\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/a8/04/0c04116bbb372f459ad0a73bf306c5000f9fd63a8419bb179381f54773aa/trax-1.3.5-py2.py3-none-any.whl (416kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 419kB 4.0MB/s \n    \u001b[?25hCollecting tensor2tensor\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/d6/7c/9e87d30cefad5cbc390bb7f626efb3ded9b19416b8160f1a1278da81b218/tensor2tensor-1.15.7-py2.py3-none-any.whl (1.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.5MB 10.2MB/s \n    \u001b[?25hRequirement already satisfied: gin-config in /usr/local/lib/python3.6/dist-packages (from trax) (0.3.0)\n    Requirement already satisfied: jax in /usr/local/lib/python3.6/dist-packages (from trax) (0.2.0)\n    Requirement already satisfied: tensorflow-datasets in /usr/local/lib/python3.6/dist-packages (from trax) (2.1.0)\n    Collecting t5\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/32/a4/1188812f1e439bba23f7ceb03879bcdb99744e2e12799aebb93bc0139496/t5-0.7.0-py3-none-any.whl (171kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 174kB 16.1MB/s \n    \u001b[?25hRequirement already satisfied: gym in /usr/local/lib/python3.6/dist-packages (from trax) (0.17.2)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from trax) (1.18.5)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from trax) (1.4.1)\n    Collecting funcsigs\n      Downloading https://files.pythonhosted.org/packages/69/cb/f5be453359271714c01b9bd06126eaf2e368f1fddfff30818754b5ac2328/funcsigs-1.0.2-py2.py3-none-any.whl\n    Collecting tensorflow-text\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/28/b2/2dbd90b93913afd07e6101b8b84327c401c394e60141c1e98590038060b3/tensorflow_text-2.3.0-cp36-cp36m-manylinux1_x86_64.whl (2.6MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.6MB 20.3MB/s \n    \u001b[?25hRequirement already satisfied: jaxlib in /usr/local/lib/python3.6/dist-packages (from trax) (0.1.55)\n    Requirement already satisfied: absl-py in /usr/local/lib/python3.6/dist-packages (from trax) (0.10.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from trax) (1.15.0)\n    Requirement already satisfied: google-api-python-client in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax) (1.7.12)\n    Collecting tf-slim\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/02/97/b0f4a64df018ca018cc035d44f2ef08f91e2e8aa67271f6f19633a015ff7/tf_slim-1.1.0-py2.py3-none-any.whl (352kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 358kB 33.8MB/s \n    \u001b[?25hCollecting gevent\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/3f/92/b80b922f08f222faca53c8d278e2e612192bc74b0e1f0db2f80a6ee46982/gevent-20.9.0-cp36-cp36m-manylinux2010_x86_64.whl (5.3MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5.3MB 34.1MB/s \n    \u001b[?25hRequirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax) (2.10.0)\n    Requirement already satisfied: opencv-python in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax) (4.1.2.30)\n    Requirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax) (2.23.0)\n    Collecting tensorflow-probability==0.7.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/3e/3a/c10b6c22320531c774402ac7186d1b673374e2a9d12502cbc8d811e4601c/tensorflow_probability-0.7.0-py2.py3-none-any.whl (981kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 983kB 28.4MB/s \n    \u001b[?25hRequirement already satisfied: oauth2client in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax) (4.1.3)\n    Requirement already satisfied: flask in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax) (1.1.2)\n    Collecting mesh-tensorflow\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/16/8b/553deb763ce8d00afb17debab7cb14a87b209cd4c6f0e8ecfc8d884cb12a/mesh_tensorflow-0.1.17-py3-none-any.whl (342kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 348kB 29.9MB/s \n    \u001b[?25hRequirement already satisfied: sympy in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax) (1.1.1)\n    Requirement already satisfied: dopamine-rl in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax) (1.0.5)\n    Requirement already satisfied: tensorflow-addons in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax) (0.8.3)\n    Collecting pypng\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/bc/fb/f719f1ac965e2101aa6ea6f54ef8b40f8fbb033f6ad07c017663467f5147/pypng-0.0.20.tar.gz (649kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 655kB 35.9MB/s \n    \u001b[?25hRequirement already satisfied: Pillow in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax) (7.0.0)\n    Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax) (0.16.0)\n    Collecting bz2file\n      Downloading https://files.pythonhosted.org/packages/61/39/122222b5e85cd41c391b68a99ee296584b2a2d1d233e7ee32b4532384f2d/bz2file-0.98.tar.gz\n    Collecting gunicorn\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/69/ca/926f7cd3a2014b16870086b2d0fdc84a9e49473c68a8dff8b57f7c156f43/gunicorn-20.0.4-py2.py3-none-any.whl (77kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 81kB 5.5MB/s \n    \u001b[?25hCollecting kfac\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1c/36/06fe2c757044bb51906fef231ac48cc5bf9a277fc9a8c7e1108d7e9e8cfd/kfac-0.2.3-py2.py3-none-any.whl (191kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 194kB 40.4MB/s \n    \u001b[?25hCollecting tensorflow-gan\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/0c/2e/62922111d7d50e1900e3030764743ea7735540ce103b3ab30fd5cd2d8a2b/tensorflow_gan-2.0.0-py2.py3-none-any.whl (365kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 368kB 36.6MB/s \n    \u001b[?25hRequirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from tensor2tensor->trax) (4.41.1)\n    Requirement already satisfied: opt-einsum in /usr/local/lib/python3.6/dist-packages (from jax->trax) (3.3.0)\n    Requirement already satisfied: protobuf>=3.6.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax) (3.12.4)\n    Requirement already satisfied: wrapt in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax) (1.12.1)\n    Requirement already satisfied: attrs>=18.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax) (20.2.0)\n    Requirement already satisfied: dill in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax) (0.3.2)\n    Requirement already satisfied: promise in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax) (2.3)\n    Requirement already satisfied: termcolor in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax) (1.1.0)\n    Requirement already satisfied: tensorflow-metadata in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->trax) (0.24.0)\n    Requirement already satisfied: torch in /usr/local/lib/python3.6/dist-packages (from t5->trax) (1.6.0+cu101)\n    Requirement already satisfied: nltk in /usr/local/lib/python3.6/dist-packages (from t5->trax) (3.2.5)\n    Requirement already satisfied: scikit-learn in /usr/local/lib/python3.6/dist-packages (from t5->trax) (0.22.2.post1)\n    Requirement already satisfied: babel in /usr/local/lib/python3.6/dist-packages (from t5->trax) (2.8.0)\n    Collecting sacrebleu\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/a3/c4/8e948f601a4f9609e8b2b58f31966cb13cf17b940b82aa3e767f01c42c52/sacrebleu-1.4.14-py3-none-any.whl (64kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 71kB 5.4MB/s \n    \u001b[?25hRequirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from t5->trax) (1.1.2)\n    Collecting transformers>=2.7.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/19/22/aff234f4a841f8999e68a7a94bdd4b60b4cebcfeca5d67d61cd08c9179de/transformers-3.3.1-py3-none-any.whl (1.1MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.1MB 30.7MB/s \n    \u001b[?25hCollecting rouge-score\n      Downloading https://files.pythonhosted.org/packages/1f/56/a81022436c08b9405a5247b71635394d44fe7e1dbedc4b28c740e09c2840/rouge_score-0.0.4-py2.py3-none-any.whl\n    Collecting tfds-nightly\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/8d/75/679a8312490388eb6cb70c8729020a3d7e721e0aefabf2d75a7cbefdb82a/tfds_nightly-4.0.1.dev202010160106-py3-none-any.whl (3.6MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.6MB 29.7MB/s \n    \u001b[?25hCollecting sentencepiece\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/d4/a4/d0a884c4300004a78cca907a6ff9a5e9fe4f090f5d95ab341c53d28cbc58/sentencepiece-0.1.91-cp36-cp36m-manylinux1_x86_64.whl (1.1MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.1MB 43.5MB/s \n    \u001b[?25hRequirement already satisfied: cloudpickle<1.4.0,>=1.2.0 in /usr/local/lib/python3.6/dist-packages (from gym->trax) (1.3.0)\n    Requirement already satisfied: pyglet<=1.5.0,>=1.4.0 in /usr/local/lib/python3.6/dist-packages (from gym->trax) (1.5.0)\n    Requirement already satisfied: tensorflow<2.4,>=2.3.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-text->trax) (2.3.0)\n    Requirement already satisfied: google-auth>=1.4.1 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor->trax) (1.17.2)\n    Requirement already satisfied: google-auth-httplib2>=0.0.3 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor->trax) (0.0.4)\n    Requirement already satisfied: httplib2<1dev,>=0.17.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor->trax) (0.17.4)\n    Requirement already satisfied: uritemplate<4dev,>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor->trax) (3.0.1)\n    Collecting zope.interface\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/c5/89/1eb9dbb9e24f5e2c29ab1a88097b2f1333858aac3cd3cccc6c4c1c8ad867/zope.interface-5.1.2-cp36-cp36m-manylinux2010_x86_64.whl (236kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 245kB 43.4MB/s \n    \u001b[?25hCollecting greenlet>=0.4.17; platform_python_implementation == \"CPython\"\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/80/d0/532e160c777b42f6f393f9de8c88abb8af6c892037c55e4d3a8a211324dd/greenlet-0.4.17-cp36-cp36m-manylinux1_x86_64.whl (44kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 5.8MB/s \n    \u001b[?25hRequirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from gevent->tensor2tensor->trax) (50.3.0)\n    Collecting zope.event\n      Downloading https://files.pythonhosted.org/packages/9e/85/b45408c64f3b888976f1d5b37eed8d746b8d5729a66a49ec846fda27d371/zope.event-4.5.0-py2.py3-none-any.whl\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->tensor2tensor->trax) (2020.6.20)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->tensor2tensor->trax) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->tensor2tensor->trax) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->tensor2tensor->trax) (2.10)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.6/dist-packages (from tensorflow-probability==0.7.0->tensor2tensor->trax) (4.4.2)\n    Requirement already satisfied: rsa>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor->trax) (4.6)\n    Requirement already satisfied: pyasn1>=0.1.7 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor->trax) (0.4.8)\n    Requirement already satisfied: pyasn1-modules>=0.0.5 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor->trax) (0.2.8)\n    Requirement already satisfied: click>=5.1 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor->trax) (7.1.2)\n    Requirement already satisfied: itsdangerous>=0.24 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor->trax) (1.1.0)\n    Requirement already satisfied: Werkzeug>=0.15 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor->trax) (1.0.1)\n    Requirement already satisfied: Jinja2>=2.10.1 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor->trax) (2.11.2)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy->tensor2tensor->trax) (1.1.0)\n    Requirement already satisfied: typeguard in /usr/local/lib/python3.6/dist-packages (from tensorflow-addons->tensor2tensor->trax) (2.7.1)\n    Requirement already satisfied: tensorflow-hub>=0.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gan->tensor2tensor->trax) (0.9.0)\n    Requirement already satisfied: googleapis-common-protos<2,>=1.52.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-metadata->tensorflow-datasets->trax) (1.52.0)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->t5->trax) (0.16.0)\n    Requirement already satisfied: pytz>=2015.7 in /usr/local/lib/python3.6/dist-packages (from babel->t5->trax) (2018.9)\n    Collecting portalocker\n      Downloading https://files.pythonhosted.org/packages/89/a6/3814b7107e0788040870e8825eebf214d72166adf656ba7d4bf14759a06a/portalocker-2.0.0-py2.py3-none-any.whl\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.6/dist-packages (from pandas->t5->trax) (2.8.1)\n    Requirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from transformers>=2.7.0->t5->trax) (0.7)\n    Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.6/dist-packages (from transformers>=2.7.0->t5->trax) (2019.12.20)\n    Collecting sacremoses\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/7d/34/09d19aff26edcc8eb2a01bed8e98f13a1537005d31e95233fd48216eed10/sacremoses-0.0.43.tar.gz (883kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 890kB 44.0MB/s \n    \u001b[?25hRequirement already satisfied: packaging in /usr/local/lib/python3.6/dist-packages (from transformers>=2.7.0->t5->trax) (20.4)\n    Collecting tokenizers==0.8.1.rc2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/80/83/8b9fccb9e48eeb575ee19179e2bdde0ee9a1904f97de5f02d19016b8804f/tokenizers-0.8.1rc2-cp36-cp36m-manylinux1_x86_64.whl (3.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.0MB 42.2MB/s \n    \u001b[?25hRequirement already satisfied: filelock in /usr/local/lib/python3.6/dist-packages (from transformers>=2.7.0->t5->trax) (3.0.12)\n    Collecting importlib-resources; python_version < \"3.9\"\n      Downloading https://files.pythonhosted.org/packages/ba/03/0f9595c0c2ef12590877f3c47e5f579759ce5caf817f8256d5dcbd8a1177/importlib_resources-3.0.0-py2.py3-none-any.whl\n    Requirement already satisfied: typing-extensions; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->t5->trax) (3.7.4.3)\n    Requirement already satisfied: tensorflow-estimator<2.4.0,>=2.3.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (2.3.0)\n    Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (1.32.0)\n    Requirement already satisfied: keras-preprocessing<1.2,>=1.1.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (1.1.2)\n    Requirement already satisfied: google-pasta>=0.1.8 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (0.2.0)\n    Requirement already satisfied: gast==0.3.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (0.3.3)\n    Requirement already satisfied: astunparse==1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (1.6.3)\n    Requirement already satisfied: tensorboard<3,>=2.3.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (2.3.0)\n    Requirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.6/dist-packages (from tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (0.35.1)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth>=1.4.1->google-api-python-client->tensor2tensor->trax) (4.1.1)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.6/dist-packages (from Jinja2>=2.10.1->flask->tensor2tensor->trax) (1.1.1)\n    Requirement already satisfied: pyparsing>=2.0.2 in /usr/local/lib/python3.6/dist-packages (from packaging->transformers>=2.7.0->t5->trax) (2.4.7)\n    Requirement already satisfied: zipp>=0.4; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from importlib-resources; python_version < \"3.9\"->tfds-nightly->t5->trax) (3.2.0)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.6/dist-packages (from tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (0.4.1)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (3.2.2)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (1.7.0)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (1.3.0)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from markdown>=2.6.8->tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (2.0.0)\n    Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<3,>=2.3.0->tensorflow<2.4,>=2.3.0->tensorflow-text->trax) (3.1.0)\n    Building wheels for collected packages: pypng, bz2file, sacremoses\n      Building wheel for pypng (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pypng: filename=pypng-0.0.20-cp36-none-any.whl size=67162 sha256=22e494987352f42fbe63f2ec144ba01401cceb3d3515b2acb1aa5db9453f89a9\n      Stored in directory: /root/.cache/pip/wheels/41/6b/ef/0493b536b6d4722c2ae9486691b1d49b922b9877922beeabb3\n      Building wheel for bz2file (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for bz2file: filename=bz2file-0.98-cp36-none-any.whl size=6884 sha256=cd834ddadde354dd1db3b3e18d98e419d95b79ca7f7ecde48bc676e7576df855\n      Stored in directory: /root/.cache/pip/wheels/81/75/d6/e1317bf09bf1af5a30befc2a007869fa6e1f516b8f7c591cb9\n      Building wheel for sacremoses (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for sacremoses: filename=sacremoses-0.0.43-cp36-none-any.whl size=893257 sha256=40d4b265a7407cb660aba24ec10b2b5cefac8afe76b8f68781d3220ca44823c7\n      Stored in directory: /root/.cache/pip/wheels/29/3c/fd/7ce5c3f0666dab31a50123635e6fb5e19ceb42ce38d4e58f45\n    Successfully built pypng bz2file sacremoses\n    \u001b[31mERROR: kfac 0.2.3 has requirement tensorflow-probability==0.8, but you'll have tensorflow-probability 0.7.0 which is incompatible.\u001b[0m\n    Installing collected packages: tf-slim, zope.interface, greenlet, zope.event, gevent, tensorflow-probability, mesh-tensorflow, pypng, bz2file, gunicorn, kfac, tensorflow-gan, tensor2tensor, portalocker, sacrebleu, sacremoses, tokenizers, sentencepiece, transformers, rouge-score, importlib-resources, tfds-nightly, tensorflow-text, t5, funcsigs, trax\n      Found existing installation: tensorflow-probability 0.11.0\n        Uninstalling tensorflow-probability-0.11.0:\n          Successfully uninstalled tensorflow-probability-0.11.0\n    Successfully installed bz2file-0.98 funcsigs-1.0.2 gevent-20.9.0 greenlet-0.4.17 gunicorn-20.0.4 importlib-resources-3.0.0 kfac-0.2.3 mesh-tensorflow-0.1.17 portalocker-2.0.0 pypng-0.0.20 rouge-score-0.0.4 sacrebleu-1.4.14 sacremoses-0.0.43 sentencepiece-0.1.91 t5-0.7.0 tensor2tensor-1.15.7 tensorflow-gan-2.0.0 tensorflow-probability-0.7.0 tensorflow-text-2.3.0 tf-slim-1.1.0 tfds-nightly-4.0.1.dev202010160106 tokenizers-0.8.1rc2 transformers-3.3.1 trax-1.3.5 zope.event-4.5.0 zope.interface-5.1.2\n\n\n\n```\nimport sys\nimport os\n\nimport numpy as np\n\nimport textwrap\nwrapper = textwrap.TextWrapper(width=70)\n\nimport trax\nfrom trax import layers as tl\nfrom trax.fastmath import numpy as jnp\n\nnp.set_printoptions(threshold=sys.maxsize)\n```\n\n\n```\ntrain_stream_fn = trax.data.TFDS('cnn_dailymail',\n                                 keys=('article', 'highlights'),\n                                 train=True)\n\neval_stream_fn = trax.data.TFDS('cnn_dailymail',\n                                keys=('article', 'highlights'),\n                                train=False)\n```\n\n\n```\ndef tokenize(input_str, EOS=1):\n    inputs =  next(trax.data.tokenize(iter([input_str]),\n                                      # vocab_dir='vocab_dir/',\n                                      vocab_file='en_8k.subword'))\n    \n    return list(inputs) + [EOS]\n\ndef detokenize(integers):  \n    s = trax.data.detokenize(integers,\n                            #  vocab_dir='vocab_dir/',\n                             vocab_file='en_8k.subword')\n    \n    return wrapper.fill(s)\n```\n\n\n```\n# Special tokens\nSEP = 0 # Padding or separator token\nEOS = 1 # End of sentence token\n\n# Concatenate tokenized inputs and targets using 0 as separator.\ndef preprocess(stream):\n    for (article, summary) in stream:\n        joint = np.array(list(article) + [EOS, SEP] + list(summary) + [EOS])\n        mask = [0] * (len(list(article)) + 2) + [1] * (len(list(summary)) + 1) # Accounting for EOS and SEP\n        yield joint, joint, np.array(mask)\n\n# You can combine a few data preprocessing steps into a pipeline like this.\ninput_pipeline = trax.data.Serial(\n    # Tokenizes\n    trax.data.Tokenize(#vocab_dir='vocab_dir/',\n                       vocab_file='en_8k.subword'),\n    # Uses function defined above\n    preprocess,\n    # Filters out examples longer than 2048\n    trax.data.FilterByLength(2048)\n)\n\n# Apply preprocessing to data streams.\ntrain_stream = input_pipeline(train_stream_fn())\neval_stream = input_pipeline(eval_stream_fn())\n\ntrain_input, train_target, train_mask = next(train_stream)\n\nassert sum((train_input - train_target)**2) == 0  # They are the same in Language Model (LM).\n\n```\n\n\n```\nprint(f'Single example mask:\\n\\n {train_mask}')\n```\n\n    Single example mask:\n    \n     [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1\n     1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n     1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n     1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n     1 1 1 1 1 1 1 1 1]\n\n\n\n```\nprint(f'Single example:\\n\\n {detokenize(train_input)}')\n\n```\n\n    Single example:\n    \n     A new study is backing up long held suspicions that Apple slows down\n    older models of its iPhones to encourage users to buy a new release.\n    The U.S. study analysed worldwide searches for 'iPhone slow' and found\n    that the search term spiked significantly around the time of new\n    iPhone launch. It then compared those results with similar searches\n    for the term 'Samsung Galaxy slow', and discovered the term was\n    unaffected by new releases from Samsung. A new study is backing up\n    long held suspicions that Apple slows down older models of iPhones to\n    encourage users to buy its new release. The U.S. study analysed\n    worldwide searches for 'iPhone slow' and found that the search term\n    spiked significantly around the time of new phone releases . The\n    study, compiled by Harvard University PhD student Laura Trucco,\n    follows claims that the Cupertino-based company is deliberately\n    sabotaging its old products. Writing for the New York Times, Sendhil\n    Mullainathan, a professor of economics at Harvard, described the\n    results as 'striking'. 'Wouldn't many business owners love to make\n    their old product less useful whenever they released a newer one?' Mr\n    Mullainathan wrote. \u2018When you sell the device and control the\n    operating system, that's an option'. The study then compared those\n    results with similar searches for the term 'Samsung Galaxy slow', and\n    found the term was unaffected by new releases from Samsung . While\n    some MailOnline readers haven't noticed a slow down, others claim that\n    Apple is sabotaging older phones through software updates. 'This is\n    common knowledge,' one reader wrote. 'If you want to keep your iPhone\n    running at the same pace do not do the software upgrade that comes out\n    within six months of a new iPhone release,' Last year, Catherine\n    Rampell, also writing in the New York Times, raised concerns that\n    Apple could be engineering the new operating system so it only works\n    properly with the newest version of the product. She said her iPhone 4\n    became a lot slower when she downloaded iOS 7 - and that the only\n    solution seemed to be to buy the iPhone 5. Ms Rampell accused Apple of\n    having run out of ideas so was trying to \u2018brainwash\u2019 its customers\n    into buying the new iPhone 5S and 5C because they look nice. Her\n    claims fuelled conspiracy theorists who have long held that Apple\n    engages in \u2018planned obsolescence\u2019, a term which has been around since\n    the Great Depression in the 1930s. The theory states that\n    manufacturers of everything from cars to microwaves build in a certain\n    lifetime to a product and then it will simply stop working, forcing\n    consumers to buy a new one. And Apple has faced allegations that it is\n    guilty of planned obsolescence before. Last year, Catherine Rampell,\n    also writing in the New York Times, raised concerns that Apple could\n    be engineering the new operating system so it only works properly with\n    the newest version of the product . A security expert has warned\n    Apple\u2019s iOS software contains potentially sinister tools that could be\n    used by governments to spy on iPhone and iPad users. Speaking at the\n    'Hackers on planet Earth' conference in New York, Jonathan Zdziarski\n    said that most users are unaware of the lack of protection for iPhone\n    data. He added files found hidden within the firm's software contain a\n    file-relay service that can be used to access the user's address book,\n    photos, voicemail and any accounts configured on the device. However,\n    Apple has denied the claims the backdoor was created deliberately for\n    government or surveillance purposes. His investigation followed\n    earlier reports of the NSA spying on Apple products, which suggested a\n    \u2018backdoor\u2019 in iOS could provide hackers with valuable information. A\n    backdoor is a hidden remote access port that can allow outside sources\n    to access a device with little detection. The conclusion was based on\n    an analysis of 600 million iOS devices, with handsets running the most\n    recent versions of the software at particular risk. When it started\n    using more tamper-resistant screws experts said it was to stop users\n    getting into the phone and fixing it themselves if there was a\n    problem. Meanwhile, in 2012 Apple was sued in Brazil by the Brazilian\n    Institute of Politics and Law Software over the launch of the iPad\n    Air. The organisation claimed that because it had the new retina\n    screen it made the iPad 3 redundant and that Apple was changing its\n    devices too quickly. Ms Rampell said: \u2018When major innovations remain\n    out of reach, and degrading durability threatens to tick off loyal\n    customers, companies like Apple can still take a cue from the fashion\n    industry. \u2018If you can brainwash consumers into developing new tastes\n    that make the old stuff look uncool for aesthetic rather than\n    functional reasons, you still have a shot at harvesting more sales\n    from your existing customer base. Dom Ferkin, managing direction of\n    UK-based iOS experts, Creation Application, told MailOnline that he\n    doesn\u2019t believe Apple are doing this intentionally. \u2018On every hardware\n    release they tend to upgrade the chips and they are faster every time\n    they are released,\u2019 he said. \u2018Each year they release a new iOS. If\n    you\u2019re running an iOS 7 on a 5 chip, for example, it\u2019s comparable to\n    running Windows XP on a Windows 95 machine. \u2018It\u2019s just enough to annoy\n    the users, but it\u2019s needed if you want the slew of new features that\n    Apple releases each year.\u2019 Mr Mullainathan added that the research\n    does not prove that Apple has done anything wrong. No matter how\n    suggestive, he says, the data alone doesn't allow anyone to determine\n    conclusively whether their phone is any slower. There are other\n    explanations for why an older model iPhone may slow down, he claims.\n    For instance, the latest version of the Apple operating system, iOS,\n    is always tailored to the newest device and may therefore not work as\n    efficiently on older models. \u2018Hearing about a new release makes you\n    contemplate getting a new and faster phone,\u2019 he added. \u2018And you\n    suddenly notice how slow your old phone is.\u2019 Apple is yet to respond.\n    But Mr Mullainathan added that the research does not prove that Apple\n    has done anything wrong.No matter how suggestive, he says, the data\n    alone doesn't allow anyone to determine conclusively whether their\n    phone is any slower .<EOS><pad>Thestudy was undertaken by student\n    Laura Trucco at Harvard University . It also compared Apple's results\n    with searches for 'Samsung Galaxy slow' Research found that the term\n    was unaffected by Samsung new releases . Study has fuelled suggestions\n    Apple engages in \u2018planned obsolescence\u2019 Theory states that\n    manufacturers build in a certain lifetime to a product and then it\n    will simply stop working, forcing consumers to buy a new one .<EOS>\n\n\n\n```\n\n# Bucketing to create batched generators.\n\n# Buckets are defined in terms of boundaries and batch sizes.\n# Batch_sizes[i] determines the batch size for items with length < boundaries[i]\n# So below, we'll take a batch of 16 sentences of length < 128 , 8 of length < 256,\n# 4 of length < 512. And so on. \nboundaries =  [128, 256,  512, 1024]\nbatch_sizes = [16,    8,    4,    2, 1]\n\n# Create the streams.\ntrain_batch_stream = trax.data.BucketByLength(\n    boundaries, batch_sizes)(train_stream)\n\neval_batch_stream = trax.data.BucketByLength(\n    boundaries, batch_sizes)(eval_stream)\n```\n\n\n```\n\n# Every execution will result in generation of a different article\n# Try running this cell multiple times to see how the length of the examples affects the batch size\ninput_batch, _, mask_batch = next(train_batch_stream)\n\n# Shape of the input_batch\ninput_batch.shape\n```\n\n\n\n\n    (1, 1111)\n\n\n\n\n```\nprint(input_batch[0])\n```\n\n    [1411 4030   84 4173  900   47  492 5182   57 4030   84  205  262  212\n      289 3849  297  137  274 3536    8  463  113 5396 3319  385    3  479\n      636  388 4030 4352 4030   84  262  205 6355  284  137  274 3536    8\n      619  113 6185 3319  385    3  479  636  388 4030   84   87 4873  513\n     1187  140 4127   23   13 3528 3968 4651   91 5966    6 1546   22   39\n        4 4297    2    5 3304   20 5689  104 1225  118    5    4 2035 3000\n      138 2840 5124    2 3202  409   10 2589    8 1237   29 3389  820    3\n      824    3   51 6596 4579 2438    3  835 2785   39    4 6044  232  861\n       31 1476  619  255   12  282 5273 2152 6309  229    8 3111   36   20\n     5044   20   35   71  172 2440   32  245 4647 1854   36    6 1342   30\n       12 4689    3   43 5273   37  310  245 4127    2   13 1176    4 5273\n      626  484  828 4040   35 5966    6    8 1237   29 3389  820    3  824\n     3779 7021   84  103  245   82 6223   47   58   12 2840 5124    2 3202\n      409  255   12  282 5273 2152 6309  229 3614   20  619 4030   84 3935\n        6 3389  820 5720  245 6236    2   80  595 3329   23   34  245 4880\n        5 4732  121  861  349 5491    6    4  282 4030   84 3935    6 3389\n      820    3 2258  592  481 5242    2    7  656 1241 5886 3663 2048 2547\n       47 1607 1839    2 5952 6342 2299   29    3 1034    3   25  309 2408\n     5437   20   34  245 2499   78    3 5720    4   82 6044 1342  861 2519\n       31  245 4647 1854   36    6  232  861   31  235    8 3111 1125 3536\n       36 5898    2 4438   13  495  115  375   51 1685    3  121  139   31\n     5854   23   13   71 1254  139 2595   13  897  245   10    4  872 2796\n        2    5 2368   47 1202   36  139   31 5632 5293   20   13  643  387\n      245   26    4 4030   84 2626 1986    7 6325  680 4476 3268   22  121\n     5801   67  861 4992   42 1887   47 3286   32  245 2600 1202   36  139\n     5012   23 4030   84 2324   29  266   80  629  911  333 4078   91  292\n        5  245 4806    2    7    4 3379   67   31   37 4030   84  861 1887\n       20 1476 2639  292    5    4 5518 2699    8  139   31 1476   12 4689\n     1254  121    4  520 4030   84  104  307 3578   39  562  961  244 1343\n      246 3935    6 3389  820 5720  861 4972    6   37    4 5974 4763    2\n     1197 4030   84 4078   91   51  245 4647 1854 1887    6 4806    2  449\n       96  133 3284   23   34 4630 2707   32 4030   84    4 1342   10   12\n     2752  379    8 3111 1125 3536   36 3111  449   96 3286   23 4030   84\n     4188    8  179 1887    6 1081   13 6107   71  257 1254  523   37 1887\n        6    4  164  173 4030   84 2090 1887  818  897 1824  118    8  139\n     4127    2  287   13 1005 3154   39 2730 1742   32 4030   84 2061 4275\n        6  961  244 3935    6 3389  820  104  133 2785   35 2840 5124    2\n     3202  409 1084   57 2232   22    7 3278 5374   10 6596 4579 2438   35\n      238   12  130 4030   84 3935    6 3389  820    7  245  592  387    3\n     2840 5124    2 1336  559 1047 2010 3986 2613   64  882  478 2699    3\n       10 4896    5  118    5  124 4687 1611 4030   84 3935    6 3389  820\n       36    6  592  481 5242    2    7  656 1241 5886 3663 2048 2547   47\n     1607 1839    2 5952 6342 2299   29    3 1034    3   25 3600   22  141\n       13  245  309 5456   49 2499   78 4030  916 1158    4  322    5    4\n      288    3 1156 1887  211 3906   32   39 1824  118 1887    6 3304   20\n      118    8  179 1887    6   90 1476   12 1342  961  244   87  130 2663\n        2    3 3935    6 3389  820  835 2785 1642   14  173   58 1084   57\n     2232   22    7 3278 5374 2840 5124    2 3202  409   10 6596 4579 2438\n        8 1210    5    4  759   36    6 2035 3000  138 1000 4824  167    3\n      861 1125  245 4732 4880  595 3329   23  194 1202   36 1574    2 6236\n        2   80  595 3329   23    7 5012   23  151 6420    6    5 6499   67\n     4013    6 6255   84  861 1125 1202   36  755 5012   23  562  442    4\n     6513   44 6366    2  280 4030   84  232  162   80  339 1690  757   23\n      961 7021   84  139 3254   20  335   37   31 1476    4 4030   84 2922\n     4078   91  292    5    4 4724    6  961  244 3951  513 1082   10    4\n      933 2931   42   61 3935    6 3389  820   25 5351 1143   35   12 5324\n       10 2840 5124    2 3209   30  258   30 2785 1642   14  173 4030   84\n     1166  861   25   90 4252   32 2840 5124    6    3 3935    6 3389  820\n     3393    6 5822   22 4054    2    7 1054  193   13  245 1854 3187  852\n     6244    3 4678 4030   84  179 2644 1240   23  245   13 1782  280   12\n     1642   14  173 5504   58 1084   57 2232   22    7 3278 5374 2840 5124\n        2 3202  409   10 6596 4579 2438   12  130 2663    2 1254 6277  118\n        5    4 2035 3000  138 1000 4824  167    8 1343  246  861   25 4253\n       32   12 5141 4902    2   58    4 1336  559 1047    3 3403 3275 3461\n       12 2840 5124    2 3209 3445  123 5324    7   43 4630 2707   32 4902\n        2   58    4  269    5 3707   97    8 3313   20   10  856 4020    2\n        3 1908 5621    2    7  791 1082 1919  193    3 3935    6 3389  820\n     4252   23  245   82 2840 5124    2   10  789  164  130    7  104 5248\n     1066 4423    2  528  350    8   28 6596 4579 2438 4873  513 1187   10\n     1642 2840 5124    2  958   78    3  361    3    7   39 2929  406  363\n       26 2195 3393   29   35   12 6335    2  292    3  257 4030   84 1105\n     3044   32 4687 1611   25  151   10   12  288   36    6  282   35  824\n       14  130   14 1249 1237   29    3  140  538 3669   13 4072  287   36\n        6 3304   20 5689   12  465 4590 3003 1159   20 1016 4030    2    1\n        0 1237   29 3389  820    3  824    3   51 6596 4579 2438    3  104\n     4871   10   12 2840 5124    2 1336  559 1047   35   12  130 4030  210\n     1105 3044   32 4687 1611    3  513 1206   91  933 2931  220    7 4252\n       32 3209  372    5  245 2499   78 4030  210 3111 5720 3536   36  179\n       36    6    4  164  173 2090  897  335 1254   71   36    6 1081   13\n     6107   71  257   36    1]\n\n\n\n```\nprint('Article:\\n\\n', detokenize(input_batch[0]))\n\n```\n\n    Article:\n    \n     By . Harriet Arkell . PUBLISHED: . 11:56 EST, 15 May 2013 . | .\n    UPDATED: . 14:54 EST, 15 May 2013 . A teenager who wanted to help\n    grieving relatives cope with the loss of loved ones has become one of\n    the youngest funeral directors in Britain. Amy Darlow, 19, from\n    Salisbury, began working with the dead when she was just 14 during a\n    work experience placement. She'd applied for it after seeing her\n    grandmother's body as a child, an experience that made her want to\n    make the experience less traumatic for relatives. Amy Darlow, 19,\u00a0 had\n    her first stint at a funeral directors during a work experience\n    placement aged 14 . Miss Darlow says her friends were surprised by her\n    choice of career but she enjoys the work . Miss Darlow, whose\n    boyfriend and childhood sweetheart Declan Spreadbury, 22, is\n    untroubled by her job, says the first dead body she saw was her\n    grandmother's when she was 10. She said: 'People try to hide death\n    from children, but I was exposed to it - I went to see her in the\n    Chapel of Rest. 'I was encouraged to kiss her on the . forehead and\n    say goodbye but sadly she wasn\u2019t looking her best. 'I asked . why\n    there were bubbles coming out of her mouth and the reply was that .\n    she\u2019d just come out of the fridge. I was just a child - but the image\n    . has stayed with me.' Now Miss Darlow says she knows that the gastric\n    air . coming from her grandmother\u2019s mouth could have been prevented by\n    embalming . the body in a certain way. She said: 'She could have\n    looked . better. It\u2019s important to get it right - because that\u2019s the\n    last time . you\u2019ll see someone. I want people to go away with good\n    lasting . memories.' Miss Darlow has been working for funeral\n    directors Will Case and Partners in Salisbury for over a year . Miss\n    Darlow and her boss, funeral parlour manager Christopher Orledge, in\n    front of one of their hearses . Miss Darlow's boyfriend and childhood\n    sweetheart Declan Spreadbury, 22, is quite used to her unusual job .\n    'At the end of the day, we\u2019re dealing with someone\u2019s loved one. It\u2019s\n    not just a body.' A year ago, Miss Darlow began working full-time at\n    Will Case and Partners funeral directors in Salisbury. One of the\n    country's youngest undertakers, she said her career choice surprised\n    some. 'My friends were surprised and asked all sorts of silly\n    questions,' she said. 'They asked me if the bodies sat up . when they\n    were being cremated.\u00a0 I told them that was just the . gas coming out\n    of the organs.' Another nail in the coffin: Miss Darlow is studying\n    for a degree in funeral services as well as working full-time . When\n    she is not conducting funerals, Miss Darlow reads crime fiction and\n    chats to her mother Elizabeth, 53 . It prompted her to take up a full-\n    time post at Will Case and Partners funeral directors in Salisbury a\n    year ago - becoming one of the youngest undertakers. Now she is\n    completing a training course at the parlour, alongside a funeral\n    services foundation degree and an embalming course at the University\n    of Bath. Clad in top hat, cravat and tail coats, Miss Darlow conducted\n    her first funeral in June last year and has completed another nine\n    since then. The Salisbury teenager in full funeral garb, left, and\n    with tattoos on show ready for a night out, right . Polishing hearses\n    is all in a day's work for 19-year-old Amy, who likes to give people's\n    loved ones a dignified send off .<EOS><pad>AmyDarlow, 19, from\n    Salisbury, has worked in a funeral parlour for a year . Polishing\n    hearses, nailing coffins and conducting services part of her job . She\n    says: 'It's the last time you see them - it's important to get it\n    right'<EOS>\n\n\n\n```\ndef create_tensor(t):\n    \"\"\"Create tensor from list of lists\"\"\"\n    return jnp.array(t)\n\n\ndef display_tensor(t, name):\n    \"\"\"Display shape and tensor\"\"\"\n    print(f'{name} shape: {t.shape}\\n')\n    print(f'{t}\\n')\n```\n\n\n```\nq = create_tensor([[1, 0, 0], [0, 1, 0]])\ndisplay_tensor(q, 'query')\nk = create_tensor([[1, 2, 3], [4, 5, 6]])\ndisplay_tensor(k, 'key')\nv = create_tensor([[0, 1, 0], [1, 0, 1]])\ndisplay_tensor(v, 'value')\nm = create_tensor([[0, 0], [-1e9, 0]])\ndisplay_tensor(m, 'mask')\n```\n\n    query shape: (2, 3)\n    \n    [[1 0 0]\n     [0 1 0]]\n    \n    key shape: (2, 3)\n    \n    [[1 2 3]\n     [4 5 6]]\n    \n    value shape: (2, 3)\n    \n    [[0 1 0]\n     [1 0 1]]\n    \n    mask shape: (2, 2)\n    \n    [[ 0.e+00  0.e+00]\n     [-1.e+09  0.e+00]]\n    \n\n\n    /usr/local/lib/python3.6/dist-packages/jax/lib/xla_bridge.py:130: UserWarning: No GPU/TPU found, falling back to CPU.\n      warnings.warn('No GPU/TPU found, falling back to CPU.')\n\n\n\n```\n\nq_dot_k = q @ k.T / jnp.sqrt(3)\ndisplay_tensor(q_dot_k, 'query dot key')\n```\n\n    query dot key shape: (2, 2)\n    \n    [[0.57735026 2.309401  ]\n     [1.1547005  2.8867514 ]]\n    \n\n\n\n```\nmasked = q_dot_k + m\ndisplay_tensor(masked, 'masked query dot key')\n```\n\n    masked query dot key shape: (2, 2)\n    \n    [[ 5.7735026e-01  2.3094010e+00]\n     [-1.0000000e+09  2.8867514e+00]]\n    \n\n\n\n```\ndisplay_tensor(masked @ v, 'masked query dot key dot value')\n\n```\n\n    masked query dot key dot value shape: (2, 3)\n    \n    [[ 2.3094010e+00  5.7735026e-01  2.3094010e+00]\n     [ 2.8867514e+00 -1.0000000e+09  2.8867514e+00]]\n    \n\n\n\n```\nq_with_batch = q[None,:]\ndisplay_tensor(q_with_batch, 'query with batch dim')\nk_with_batch = k[None,:]\ndisplay_tensor(k_with_batch, 'key with batch dim')\nv_with_batch = v[None,:]\ndisplay_tensor(v_with_batch, 'value with batch dim')\nm_bool = create_tensor([[True, True], [False, True]])\ndisplay_tensor(m_bool, 'boolean mask')\n```\n\n    query with batch dim shape: (1, 2, 3)\n    \n    [[[1 0 0]\n      [0 1 0]]]\n    \n    key with batch dim shape: (1, 2, 3)\n    \n    [[[1 2 3]\n      [4 5 6]]]\n    \n    value with batch dim shape: (1, 2, 3)\n    \n    [[[0 1 0]\n      [1 0 1]]]\n    \n    boolean mask shape: (2, 2)\n    \n    [[ True  True]\n     [False  True]]\n    \n\n\n\n```\ndef DotProductAttention(query, key, value, mask):\n    \"\"\"Dot product self-attention.\n    Args:\n        query (jax.interpreters.xla.DeviceArray): array of query representations with shape (L_q by d)\n        key (jax.interpreters.xla.DeviceArray): array of key representations with shape (L_k by d)\n        value (jax.interpreters.xla.DeviceArray): array of value representations with shape (L_k by d) where L_v = L_k\n        mask (jax.interpreters.xla.DeviceArray): attention-mask, gates attention with shape (L_q by L_k)\n\n    Returns:\n        jax.interpreters.xla.DeviceArray: Self-attention array for q, k, v arrays. (L_q by L_k)\n    \"\"\"\n\n    assert query.shape[-1] == key.shape[-1] == value.shape[-1], \"Embedding dimensions of q, k, v aren't all the same\"\n\n    ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###\n    # Save depth/dimension of the query embedding for scaling down the dot product\n    depth = query.shape[-1] \n\n    # Calculate scaled query key dot product according to formula above\n    dots = jnp.matmul(query, jnp.swapaxes(key, -1, -2)) / jnp.sqrt(depth)\n\n    # Apply the mask\n    if mask is not None: # The 'None' in this line does not need to be replaced\n        dots = jnp.where(mask, dots, jnp.full_like(dots, -1e9))\n    \n    # Softmax formula implementation\n    # Use trax.fastmath.logsumexp of dots to avoid underflow by division by large numbers\n    # Hint: Last axis should be used and keepdims should be True\n    # Note: softmax = e^(dots - logsumexp(dots)) = E^dots / sumexp(dots)\n    logsumexp = trax.fastmath.logsumexp(dots, axis=-1, keepdims=True)\n\n    # Take exponential of dots minus logsumexp to get softmax\n    # Use jnp.exp()\n    dots = jnp.exp(dots - logsumexp)\n\n    # Multiply dots by value to get self-attention\n    # Use jnp.matmul()\n    attention = jnp.matmul(dots, value)\n\n    ## END CODE HERE ###\n    \n    return attention\n```\n\n\n```\nDotProductAttention(q_with_batch, k_with_batch, v_with_batch, m_bool)\n```\n\n\n\n\n    DeviceArray([[[0.8496746 , 0.15032545, 0.8496746 ],\n                  [1.        , 0.        , 1.        ]]], dtype=float32)\n\n\n\n\n```\ntensor2d = create_tensor(q)\ndisplay_tensor(tensor2d, 'query matrix (2D tensor)')\n\ntensor4d2b = create_tensor([[q, q], [q, q]])\ndisplay_tensor(tensor4d2b, 'batch of two (multi-head) collections of query matrices (4D tensor)')\n\ntensor3dc = create_tensor([jnp.concatenate([q, q], axis = -1)])\ndisplay_tensor(tensor3dc, 'one batch of concatenated heads of query matrices (3d tensor)')\n\ntensor3dc3b = create_tensor([jnp.concatenate([q, q], axis = -1), jnp.concatenate([q, q], axis = -1), jnp.concatenate([q, q], axis = -1)])\ndisplay_tensor(tensor3dc3b, 'three batches of concatenated heads of query matrices (3d tensor)')\n```\n\n    query matrix (2D tensor) shape: (2, 3)\n    \n    [[1 0 0]\n     [0 1 0]]\n    \n    batch of two (multi-head) collections of query matrices (4D tensor) shape: (2, 2, 2, 3)\n    \n    [[[[1 0 0]\n       [0 1 0]]\n    \n      [[1 0 0]\n       [0 1 0]]]\n    \n    \n     [[[1 0 0]\n       [0 1 0]]\n    \n      [[1 0 0]\n       [0 1 0]]]]\n    \n    one batch of concatenated heads of query matrices (3d tensor) shape: (1, 2, 6)\n    \n    [[[1 0 0 1 0 0]\n      [0 1 0 0 1 0]]]\n    \n    three batches of concatenated heads of query matrices (3d tensor) shape: (3, 2, 6)\n    \n    [[[1 0 0 1 0 0]\n      [0 1 0 0 1 0]]\n    \n     [[1 0 0 1 0 0]\n      [0 1 0 0 1 0]]\n    \n     [[1 0 0 1 0 0]\n      [0 1 0 0 1 0]]]\n    \n\n\n\n```\n\ndef compute_attention_heads_closure(n_heads, d_head):\n    \"\"\" Function that simulates environment inside CausalAttention function.\n    Args:\n        d_head (int):  dimensionality of heads.\n        n_heads (int): number of attention heads.\n    Returns:\n        function: compute_attention_heads function\n    \"\"\"\n\n    def compute_attention_heads(x):\n        \"\"\" Compute the attention heads.\n        Args:\n            x (jax.interpreters.xla.DeviceArray): tensor with shape (batch_size, seqlen, n_heads X d_head).\n        Returns:\n            jax.interpreters.xla.DeviceArray: reshaped tensor with shape (batch_size X n_heads, seqlen, d_head).\n        \"\"\"\n        ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###\n        \n        # Size of the x's batch dimension\n        batch_size = x.shape[0]\n        # Length of the sequence\n        # Should be size of x's first dimension without counting the batch dim\n        seqlen = x.shape[1]\n        \n        \n        # Reshape x using jnp.reshape()\n        # batch_size, seqlen, n_heads*d_head -> batch_size, seqlen, n_heads, d_head\n        x = jnp.reshape(x, (batch_size, seqlen, n_heads, d_head))\n        \n        \n        # Transpose x using jnp.transpose()\n        # batch_size, seqlen, n_heads, d_head -> batch_size, n_heads, seqlen, d_head\n        # Note that the values within the tuple are the indexes of the dimensions of x and you must rearrange them\n        x = jnp.transpose(x, (0, 2, 1, 3))\n        \n        \n        # Reshape x using jnp.reshape()\n        # batch_size, n_heads, seqlen, d_head -> batch_size*n_heads, seqlen, d_head\n        x = jnp.reshape(x, (-1, seqlen, d_head))\n        ### END CODE HERE ###\n        \n        return x\n    \n    return compute_attention_heads\n```\n\n\n```\n\ndisplay_tensor(tensor3dc3b, \"input tensor\")\nresult_cah = compute_attention_heads_closure(2,3)(tensor3dc3b)\ndisplay_tensor(result_cah, \"output tensor\")\n```\n\n    input tensor shape: (3, 2, 6)\n    \n    [[[1 0 0 1 0 0]\n      [0 1 0 0 1 0]]\n    \n     [[1 0 0 1 0 0]\n      [0 1 0 0 1 0]]\n    \n     [[1 0 0 1 0 0]\n      [0 1 0 0 1 0]]]\n    \n    output tensor shape: (6, 2, 3)\n    \n    [[[1 0 0]\n      [0 1 0]]\n    \n     [[1 0 0]\n      [0 1 0]]\n    \n     [[1 0 0]\n      [0 1 0]]\n    \n     [[1 0 0]\n      [0 1 0]]\n    \n     [[1 0 0]\n      [0 1 0]]\n    \n     [[1 0 0]\n      [0 1 0]]]\n    \n\n\n\n```\ndef dot_product_self_attention(q, k, v):\n    \"\"\" Masked dot product self attention.\n    Args:\n        q (jax.interpreters.xla.DeviceArray): queries.\n        k (jax.interpreters.xla.DeviceArray): keys.\n        v (jax.interpreters.xla.DeviceArray): values.\n    Returns:\n        jax.interpreters.xla.DeviceArray: masked dot product self attention tensor.\n    \"\"\"\n    ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###\n    \n    # Hint: mask size should be equal to L_q. Remember that q has shape (batch_size, L_q, d)\n    # NOTE: there is a revision underway with the autograder to tolerate better indexing. \n    # Until then, please index q.shape using negative values (this is equivalent to counting from right to left)\n    mask_size = q.shape[-2]\n\n    # Creates a matrix with ones below the diagonal and 0s above. It should have shape (1, mask_size, mask_size)\n    # Notice that 1's and 0's get casted to True/False by setting dtype to jnp.bool_\n    # Use jnp.tril() - Lower triangle of an array and jnp.ones()\n    mask = jnp.tril(jnp.ones((1, mask_size, mask_size), dtype=jnp.bool_), k=0)\n    \n    ### END CODE HERE ###\n    \n    return DotProductAttention(q, k, v, mask)\n```\n\n\n```\ndot_product_self_attention(q_with_batch, k_with_batch, v_with_batch)\n\n```\n\n\n\n\n    DeviceArray([[[0.        , 1.        , 0.        ],\n                  [0.8496746 , 0.15032543, 0.8496746 ]]], dtype=float32)\n\n\n\n\n```\ndef compute_attention_output_closure(n_heads, d_head):\n    \"\"\" Function that simulates environment inside CausalAttention function.\n    Args:\n        d_head (int):  dimensionality of heads.\n        n_heads (int): number of attention heads.\n    Returns:\n        function: compute_attention_output function\n    \"\"\"\n    \n    def compute_attention_output(x):\n        \"\"\" Compute the attention output.\n        Args:\n            x (jax.interpreters.xla.DeviceArray): tensor with shape (batch_size X n_heads, seqlen, d_head).\n        Returns:\n            jax.interpreters.xla.DeviceArray: reshaped tensor with shape (batch_size, seqlen, n_heads X d_head).\n        \"\"\"\n        ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###\n        \n        # Length of the sequence\n        # Should be size of x's first dimension without counting the batch dim\n        seqlen = x.shape[1]\n        \n        # Reshape x using jnp.reshape() to shape (batch_size, n_heads, seqlen, d_head)\n        x = jnp.reshape(x, ( -1, n_heads, seqlen, d_head))\n\n        # Transpose x using jnp.transpose() to shape (batch_size, seqlen, n_heads, d_head)\n        x = jnp.transpose(x, ( 0, 2, 1 , 3))\n        \n        ### END CODE HERE ###\n        \n        # Reshape to allow to concatenate the heads\n        return jnp.reshape(x, (-1, seqlen, n_heads * d_head))\n    \n    return compute_attention_output\n```\n\n\n```\ndisplay_tensor(result_cah, \"input tensor\")\nresult_cao = compute_attention_output_closure(2,3)(result_cah)\ndisplay_tensor(result_cao, \"output tensor\")\n```\n\n    input tensor shape: (6, 2, 3)\n    \n    [[[1 0 0]\n      [0 1 0]]\n    \n     [[1 0 0]\n      [0 1 0]]\n    \n     [[1 0 0]\n      [0 1 0]]\n    \n     [[1 0 0]\n      [0 1 0]]\n    \n     [[1 0 0]\n      [0 1 0]]\n    \n     [[1 0 0]\n      [0 1 0]]]\n    \n    output tensor shape: (3, 2, 6)\n    \n    [[[1 0 0 1 0 0]\n      [0 1 0 0 1 0]]\n    \n     [[1 0 0 1 0 0]\n      [0 1 0 0 1 0]]\n    \n     [[1 0 0 1 0 0]\n      [0 1 0 0 1 0]]]\n    \n\n\n\n```\n\ndef CausalAttention(d_feature, \n                    n_heads, \n                    compute_attention_heads_closure=compute_attention_heads_closure,\n                    dot_product_self_attention=dot_product_self_attention,\n                    compute_attention_output_closure=compute_attention_output_closure,\n                    mode='train'):\n    \"\"\"Transformer-style multi-headed causal attention.\n\n    Args:\n        d_feature (int):  dimensionality of feature embedding.\n        n_heads (int): number of attention heads.\n        compute_attention_heads_closure (function): Closure around compute_attention heads.\n        dot_product_self_attention (function): dot_product_self_attention function. \n        compute_attention_output_closure (function): Closure around compute_attention_output. \n        mode (str): 'train' or 'eval'.\n\n    Returns:\n        trax.layers.combinators.Serial: Multi-headed self-attention model.\n    \"\"\"\n    \n    assert d_feature % n_heads == 0\n    d_head = d_feature // n_heads\n\n    ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###\n    \n    # HINT: The second argument to tl.Fn() is an uncalled function (without the parentheses)\n    # Since you are dealing with closures you might need to call the outer \n    # function with the correct parameters to get the actual uncalled function.\n    ComputeAttentionHeads = tl.Fn('AttnHeads', compute_attention_heads_closure(n_heads, d_head), n_out=1)\n    \n    \n    return tl.Serial(\n        tl.Branch( # creates three towers for one input, takes activations and creates queries keys and values\n            [tl.Dense(d_feature), ComputeAttentionHeads], # queries\n            [tl.Dense(d_feature), ComputeAttentionHeads], # keys\n            [tl.Dense(d_feature), ComputeAttentionHeads], # values\n        ),\n        \n        tl.Fn('DotProductAttn', dot_product_self_attention, n_out=1), # takes QKV\n        # HINT: The second argument to tl.Fn() is an uncalled function\n        # Since you are dealing with closures you might need to call the outer \n        # function with the correct parameters to get the actual uncalled function.\n        tl.Fn('AttnOutput', compute_attention_output_closure(n_heads, d_head), n_out=1), # to allow for parallel\n        tl.Dense(d_feature) # Final dense layer\n    )\n\n    ### END CODE HERE ###\n```\n\n\n```\nprint(CausalAttention(d_feature=512, n_heads=8))\n```\n\n    Serial[\n      Branch_out3[\n        [Dense_512, AttnHeads]\n        [Dense_512, AttnHeads]\n        [Dense_512, AttnHeads]\n      ]\n      DotProductAttn_in3\n      AttnOutput\n      Dense_512\n    ]\n\n\n\n```\n\ndef DecoderBlock(d_model, d_ff, n_heads,\n                 dropout, mode, ff_activation):\n    \"\"\"Returns a list of layers that implements a Transformer decoder block.\n\n    The input is an activation tensor.\n\n    Args:\n        d_model (int):  depth of embedding.\n        d_ff (int): depth of feed-forward layer.\n        n_heads (int): number of attention heads.\n        dropout (float): dropout rate (how much to drop out).\n        mode (str): 'train' or 'eval'.\n        ff_activation (function): the non-linearity in feed-forward layer.\n\n    Returns:\n        list: list of trax.layers.combinators.Serial that maps an activation tensor to an activation tensor.\n    \"\"\"\n    \n    ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###\n    \n    # Create masked multi-head attention block using CausalAttention function\n    causal_attention = CausalAttention( \n                        d_model,\n                        n_heads=n_heads,\n                        mode=mode\n                        )\n\n    # Create feed-forward block (list) with two dense layers with dropout and input normalized\n    feed_forward = [ \n        # Normalize layer inputs\n        tl.LayerNorm(),\n        # Add first feed forward (dense) layer (don't forget to set the correct value for n_units)\n        tl.Dense(d_ff),\n        # Add activation function passed in as a parameter (you need to call it!)\n        ff_activation(), # Generally ReLU\n        # Add dropout with rate and mode specified (i.e., don't use dropout during evaluation)\n        tl.Dropout(rate=dropout, mode=mode),\n        # Add second feed forward layer (don't forget to set the correct value for n_units)\n        tl.Dense(d_model),\n        # Add dropout with rate and mode specified (i.e., don't use dropout during evaluation)\n        tl.Dropout(rate=dropout,mode=mode)\n    ]\n\n    # Add list of two Residual blocks: the attention with normalization and dropout and feed-forward blocks\n    return [\n      tl.Residual(\n          # Normalize layer input\n          tl.LayerNorm(),\n          # Add causal attention block previously defined (without parentheses)\n          causal_attention,\n          # Add dropout with rate and mode specified\n          tl.Dropout(rate=dropout, mode=mode)\n        ),\n      tl.Residual(\n          # Add feed forward block (without parentheses)\n          feed_forward\n        ),\n      ]\n    ### END CODE HERE ###\n```\n\n\n```\nprint(DecoderBlock(d_model=512, d_ff=2048, n_heads=8, dropout=0.1, mode='train', ff_activation=tl.Relu))\n```\n\n    [Serial[\n      Branch_out2[\n        None\n        Serial[\n          LayerNorm\n          Serial[\n            Branch_out3[\n              [Dense_512, AttnHeads]\n              [Dense_512, AttnHeads]\n              [Dense_512, AttnHeads]\n            ]\n            DotProductAttn_in3\n            AttnOutput\n            Dense_512\n          ]\n          Dropout\n        ]\n      ]\n      Add_in2\n    ], Serial[\n      Branch_out2[\n        None\n        Serial[\n          LayerNorm\n          Dense_2048\n          Relu\n          Dropout\n          Dense_512\n          Dropout\n        ]\n      ]\n      Add_in2\n    ]]\n\n\n\n```\n\ndef TransformerLM(vocab_size=33300,\n                  d_model=512,\n                  d_ff=2048,\n                  n_layers=6,\n                  n_heads=8,\n                  dropout=0.1,\n                  max_len=4096,\n                  mode='train',\n                  ff_activation=tl.Relu):\n    \"\"\"Returns a Transformer language model.\n\n    The input to the model is a tensor of tokens. (This model uses only the\n    decoder part of the overall Transformer.)\n\n    Args:\n        vocab_size (int): vocab size.\n        d_model (int):  depth of embedding.\n        d_ff (int): depth of feed-forward layer.\n        n_layers (int): number of decoder layers.\n        n_heads (int): number of attention heads.\n        dropout (float): dropout rate (how much to drop out).\n        max_len (int): maximum symbol length for positional encoding.\n        mode (str): 'train', 'eval' or 'predict', predict mode is for fast inference.\n        ff_activation (function): the non-linearity in feed-forward layer.\n\n    Returns:\n        trax.layers.combinators.Serial: A Transformer language model as a layer that maps from a tensor of tokens\n        to activations over a vocab set.\n    \"\"\"\n    \n    ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###\n    \n    # Embedding inputs and positional encoder\n    positional_encoder = [ \n        # Add embedding layer of dimension (vocab_size, d_model)\n        tl.Embedding(vocab_size, d_model),\n        # Use dropout with rate and mode specified\n        tl.Dropout(rate=dropout, mode=mode),\n        # Add positional encoding layer with maximum input length and mode specified\n        tl.PositionalEncoding(max_len=max_len, mode=mode)]\n\n    # Create stack (list) of decoder blocks with n_layers with necessary parameters\n    decoder_blocks = [ \n        DecoderBlock(d_model, d_ff, n_heads,\n                    dropout, mode, ff_activation) for _ in range(n_layers)]\n\n    # Create the complete model as written in the figure\n    return tl.Serial(\n        # Use teacher forcing (feed output of previous step to current step)\n        tl.ShiftRight(mode=mode), # Specify the mode!\n        # Add positional encoder\n        positional_encoder,\n        # Add decoder blocks\n        decoder_blocks,\n        # Normalize layer\n        tl.LayerNorm(),\n\n        # Add dense layer of vocab_size (since need to select a word to translate to)\n        # (a.k.a., logits layer. Note: activation already set by ff_activation)\n        tl.Dense(vocab_size),\n        # Get probabilities with Logsoftmax\n        tl.LogSoftmax(),\n    )\n\n    ### END CODE HERE ###\n```\n\n\n```\nprint(TransformerLM(n_layers=1))\n```\n\n    Serial[\n      ShiftRight(1)\n      Embedding_33300_512\n      Dropout\n      PositionalEncoding\n      Serial[\n        Branch_out2[\n          None\n          Serial[\n            LayerNorm\n            Serial[\n              Branch_out3[\n                [Dense_512, AttnHeads]\n                [Dense_512, AttnHeads]\n                [Dense_512, AttnHeads]\n              ]\n              DotProductAttn_in3\n              AttnOutput\n              Dense_512\n            ]\n            Dropout\n          ]\n        ]\n        Add_in2\n      ]\n      Serial[\n        Branch_out2[\n          None\n          Serial[\n            LayerNorm\n            Dense_2048\n            Relu\n            Dropout\n            Dense_512\n            Dropout\n          ]\n        ]\n        Add_in2\n      ]\n      LayerNorm\n      Dense_33300\n      LogSoftmax\n    ]\n\n\n\n```\ndef training_loop(TransformerLM, train_gen, eval_gen, output_dir = \"~/model\"):\n    '''\n    Input:\n        TransformerLM (trax.layers.combinators.Serial): The model you are building.\n        train_gen (generator): Training stream of data.\n        eval_gen (generator): Evaluation stream of data.\n        output_dir (str): folder to save your file.\n        \n    Returns:\n        trax.supervised.training.Loop: Training loop.\n    '''\n    output_dir = os.path.expanduser(output_dir)  # trainer is an object\n    lr_schedule = trax.lr.warmup_and_rsqrt_decay(n_warmup_steps=1000, max_value=0.01)\n\n    ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###\n    train_task = training.TrainTask( \n      labeled_data=train_gen, # The training generator\n      loss_layer=tl.CrossEntropyLoss(), # Loss function \n      optimizer=trax.optimizers.Adam(0.01), # Optimizer (Don't forget to set LR to 0.01)\n      lr_schedule=lr_schedule,\n      n_steps_per_checkpoint=10\n    )\n\n    eval_task = training.EvalTask( \n      labeled_data=eval_gen, # The evaluation generator\n      metrics=[tl.CrossEntropyLoss(), tl.Accuracy()] # CrossEntropyLoss and Accuracy\n    )\n\n    ### END CODE HERE ###\n\n    loop = training.Loop(TransformerLM(d_model=4,\n                                       d_ff=16,\n                                       n_layers=1,\n                                       n_heads=2,\n                                       mode='train'),\n                         train_task,\n                         eval_tasks=[eval_task],\n                         output_dir=output_dir)\n    \n    return loop\n```\n\n\n```\n!rm -f ~/model/model.pkl.gz\nloop = training_loop(TransformerLM, train_batch_stream, eval_batch_stream)\nloop.run(10)\n```\n\n\n```\n\n```\n", "meta": {"hexsha": "cacbe39c17113eb647be4f0dce1c96cdb8b83f50", "size": 97862, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "summarization/f_t5_from_sc.ipynb", "max_stars_repo_name": "fajemila/NLP", "max_stars_repo_head_hexsha": "98f0cd4f5ec117380501ffea2f74aacee87e2335", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "summarization/f_t5_from_sc.ipynb", "max_issues_repo_name": "fajemila/NLP", "max_issues_repo_head_hexsha": "98f0cd4f5ec117380501ffea2f74aacee87e2335", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "summarization/f_t5_from_sc.ipynb", "max_forks_repo_name": "fajemila/NLP", "max_forks_repo_head_hexsha": "98f0cd4f5ec117380501ffea2f74aacee87e2335", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.9556277056, "max_line_length": 1056, "alphanum_fraction": 0.5274570313, "converted": true, "num_tokens": 23964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20689405859634893, "lm_q2_score": 0.03676946436037402, "lm_q1q2_score": 0.007607383713931585}}
{"text": "# \ub370\ubaa8 \uac00\uc774\ub4dc \ubb38\uc11c\n\n## 1) \ud504\ub85c\uc81d\ud2b8 \ub2e4\uc6b4\ub85c\ub4dc\n\n> git clone https://github.com/younhong/COVID19-Mask-Detection-Model \uc73c\ub85c \ub2e4\uc6b4\ub85c\ub4dc\n\n> \ub9cc\uc57d git\uc774 \uc124\uce58\ub418\uc5b4 \uc788\uc9c0 \uc54a\ub2e4\uba74\n>> [\ub9c1\ud06c](https://github.com/younhong/COVID19-Mask-Detection-Model)\ub85c \ub4e4\uc5b4\uac00\uc11c zip \ud30c\uc77c\uc744 \ub2e4\uc6b4\ub85c\ub4dc\n\n## 2) \ud658\uacbd \uc124\uc815\n\n\ud658\uacbd\uc124\uc815: \uac00\uc0c1\ud658\uacbd\uc744 \uc124\uc815   \nWhy?\n> \uac00\uc0c1\ud658\uacbd\uc744 \uc124\uce58\ud558\uc9c0 \uc54a\uc73c\uba74 \uae30\uc874\uc758 \ud30c\uc774\uc36c \uc124\uce58\ub41c \ud658\uacbd\uacfc \ucda9\ub3cc\ud558\uc5ec \uc758\ub3c4\uce58 \uc54a\uc740 \uc5d0\ub7ec\uac00 \ub0a0 \uc218 \uc788\ub2e4.\n\n### Step1) \uac00\uc0c1\ud658\uacbd \uc0dd\uc131\uc5d0 \ud544\uc694\ud55c \ud328\ud0a4\uc9c0 \uc124\uce58\nMac\uc758 \uacbd\uc6b0\n> pip install virtualenv virtualenvwrapper\n\nWindow\uc758 \uacbd\uc6b0\n> pip install virtualenv virtualenvwrapper-win\n\n### Step2) \ud658\uacbd\ubcc0\uc218 \uc124\uc815\nMac\uc758 \uacbd\uc6b0\n> \uc544\ub798 \ucee4\ub9e8\ub4dc\ub85c virtualenvwrapper.sh\uac00 \uc124\uce58\ub41c \uc704\uce58 \ud655\uc778(\uacb0\uacfc\uac12\uc744 \uae30\uc5b5\ud574\ub458 \uac83)\n>> find / -name virtualenvwrapper.sh 2>/dev/null\n>> \n>> (\uacbd\ub85c\uac00 \ub450 \uac00\uc9c0 \uc774\uc0c1 \ub098\uc624\uba74 \ub458 \uc911\uc5d0 \ud558\ub098 \uc120\ud0dd\ud574\uc11c \ubcf5\uc0ac)\n\n> .zshrc \ud30c\uc77c\uc744 \uc5f4\uace0 \ud658\uacbd \ubcc0\uc218\ub97c \ucd94\uac00(\uc544\ub798 \uc774\ubbf8\uc9c0 \ub9c8\uc9c0\ub9c9 3\uc904 \ucc38\uace0)   \n> \ub9c8\uc9c0\ub9c9 \uc904\uc758 source \ub4a4\uc758 \uacbd\ub85c\ub97c \uc704\uc5d0\uc11c \uccb4\ud06c\ud55c \uacbd\ub85c\ub85c \ubcc0\uacbd\n>> \n\n> source ~/.zshrc \uc2e4\ud589 \ud6c4 \uc7ac\ubd80\ud305\n\nWindow\uc758 \uacbd\uc6b0\n> setx WORKON_HOME=\"\ud504\ub85c\uc81d\ud2b8\uac00 \uc124\uce58\ub41c \uacbd\ub85c\"   \n> \uc7ac\ubd80\ud305\n\n### Step3) \uac00\uc0c1\ud658\uacbd \uc0dd\uc131\n> mkvirtualenv test(test \ub300\uc2e0 \ub2e4\ub978 \uc774\ub984 \uc368\ub3c4 \uad1c\ucc2e\uc74c)\n>> \n>> (\ub9e5 \uae30\uc900) \uc774\ubbf8\uc9c0 \ub9e8 \uc544\ub798\uc5d0 \ud45c\uc2dc\ub41c \ubd80\ubd84\uacfc \uac19\uc774 \uc124\uc815\ud55c \ud658\uacbd \uc774\ub984\uc774 \ud45c\uc2dc\ub418\uba74 \uc131\uacf5\n\n### Step4) \uc124\uce58\ub41c \uac00\uc0c1\ud658\uacbd\uc5d0 \ud504\ub85c\uc81d\ud2b8 \uc2e4\ud589\uc5d0 \ud544\uc694\ud55c \ud30c\uc774\uc36c \ubaa8\ub4c8 \uc124\uce58\n> pip install -r requirements.txt\n\n## 3) \ub370\uc774\ud130 \ud559\uc2b5 \ub2e8\uacc4\n\n> python train_mask_detector.py --dataset dataset\n\n> dataset \ud3f4\ub354 \uc548\uc5d0 \uc788\ub294 3800\uac1c\uc758 \uc774\ubbf8\uc9c0\ub97c \uac00\uc838\uc57c 20\ubc88\uc758 epoch \ub3d9\uc548 \uac01\uac01 96\ubc88\uc758 step\uc744 \uac70\uce58\uba70 \ud559\uc2b5\uc744 \uc9c4\ud589\n\n## 4) \ub370\uc774\ud130 \ud559\uc2b5 \uacb0\uacfc\uc5d0 \ub300\ud55c \ucd94\uac00 \uc124\uba85\n\n \n\n> (\ud3b8\uc758\uc0c1 TP, TN, FP, FN\uc73c\ub85c \ud45c\uc2dc\ud569\ub2c8\ub2e4)\n\n### 4-1) Precision\n> \ubaa8\ub378\uc774 True\ub77c\uace0 \uc608\uce21\ud55c \uac12 \uc911 \uc2e4\uc81c \uacb0\uacfc\uac00 True\uc758 \uac12\uc744 \uac00\uc9c0\ub294 \ub2f5\uc758 \ube44\uc728\n\n\\begin{align}\n\\frac{TP}{(TP + FP)}\n\\end{align}\n\n### 4-2) Recall\n> \uc2e4\uc81c True\uc778 \uac12 \uc911 \ubaa8\ub378\uc774 True\ub77c\uace0 \uc633\uac8c \uc608\uce21\ud55c \ub2f5\uc758 \ube44\uc728\n\n\\begin{align}\n\\frac{TP}{(TP + FN)}\n\\end{align}\n\n### 4-3) F1\n> Precision\uacfc Recall\uc758 \uc870\ud654\ud3c9\uade0\n\n\\begin{align}\n\\frac{2 * precision * recall}{(precision + recall)}\n\\end{align}\n\n### 4-4) Accuracy\n> True\ub77c\uace0 \uc633\uac8c \uc608\uce21\ud55c \uac83\uacfc False\ub77c\uace0 \uc62e\uac8c \uc608\uce21\ud55c \uac83\uc758 \ube44\uc728\n\n\\begin{align}\n\\frac{TP + TN}{(TP + FP + TN + FN)}\n\\end{align}\n\n### 4-5) \uc790\ub8cc \ucd9c\ucc98\n> [\ucd9c\ucc98](https://eunsukimme.github.io/ml/2019/10/21/Accuracy-Recall-Precision-F1-score/)\n\n## 5) \ub370\uc774\ud130 \uac80\uc99d \ub2e8\uacc4\n\n### \uc2e4\uc2dc\uac04 \uc6f9\ucea0 \uc601\uc0c1\uc744 \ud1b5\ud55c \uac80\uc99d\n\n> python detect_mask_video.py\n\n# \ubcf4\uc644\ud560 \uc810\n\n## 1) \ud55c\uc815\ub41c \ub370\uc774\ud130\n> \ud604\uc7ac \ud559\uc2b5\uc5d0 \uc0ac\uc6a9\ud55c \uac74 3800\uac1c\uc758 \uc774\ubbf8\uc9c0. \ubaa8\ub4e0 \uc0c1\ud669\uc744 \ucee4\ubc84\ud558\uae30\ub294 \ubd80\uc871\ud558\ub2e4. \ub354 \uc815\ud655\ud55c \uac80\uc99d\uc744 \uc704\ud574\uc11c\ub294 \ub354 \ub9ce\uc740 \ud559\uc2b5 \ub370\uc774\ud130\uac00 \ud544\uc694\ud558\ub2e4.\n\n## 2) \ub9c8\uc2a4\ud06c \ubd88\ub7c9 \ucc29\uc6a9\uc790 \uac10\uc9c0\n> \uc774 \ud504\ub85c\uc81d\ud2b8\ub294 \ub9c8\uc2a4\ud06c \ucc29\uc6a9 \uc5ec\ubd80\ub9cc \uac10\uc9c0\ud55c\ub2e4. \ub9c8\uc2a4\ud06c\ub97c \ucf54 \ub05d\uae4c\uc9c0 \uc62c\ub9ac\uc9c0 \uc54a\uc740 \uc0ac\ub78c\ub4e4\uc744 \ubaa8\ub450 \uac10\uc9c0\ud558\uace0 \uc2f6\ub2e4\uba74 \uadf8 \ubd80\ubd84\uc5d0 \ud574\ub2f9\ud558\ub294 \ub370\uc774\ud130\uc640 \ub808\uc774\ube14\uc774 \ud544\uc694\ud558\ub2e4. \uae30\uc874\uc5d0 \ud559\uc2b5\uc5d0 \uc0ac\uc6a9\ud55c \ub370\uc774\ud130\ub9cc\ud07c \ub9ce\uc740 \uc218\uc758 \ub370\uc774\ud130\uac00 \uc8fc\uc5b4\uc9c4\ub2e4\uba74 \uac00\ub2a5\ud560 \uac83\uc73c\ub85c \ud310\ub2e8\ub41c\ub2e4.\n\n## 3) \uad00\ub9ac\uc790\uc5d0\uac8c \uc54c\ub9bc\n> \ud604\uc7ac\ub294 \ub9c8\uc2a4\ud06c \ubd88\ub7c9\uc790\ub97c \uac10\uc9c0\ud558\uace0 \uacbd\uace0\ub97c \uc8fc\ub294 \uac83\uc5d0 \ub05d\ub09c\ub2e4. \uc790\ub3d9\uc73c\ub85c \uad00\ub9ac\uc790\uc5d0\uac8c \uba54\uc2dc\uc9c0\ub97c \ubcf4\ub0bc \uc218 \uc788\ub3c4\ub85d \ubcf4\uc644\ud558\uba74 \uc88b\uc744 \uac83 \uac19\ub2e4.\n\n# \uae30\ub300\ud6a8\uacfc\n\n> \uc885\uad50\uc2dc\uc124 \ub4f1 \uc9d1\ub2e8 \uac10\uc5fc\uc758 \uc704\ud5d8\uc774 \uc788\ub294 \uc7a5\uc18c\uc5d0\uc11c \ub9c8\uc2a4\ud06c \ubbf8\ucc29\uc6a9\uc790\ub97c \uac10\uc9c0\ud558\uc5ec \uac74\ubb3c\uc758 \ucd9c\uc785\uc774\ub098 \uc774\uc6a9\uc744 \uc81c\ud55c\ud558\uac70\ub098 \uaca9\ub9ac \uc870\ucde8\ub97c \ucde8\ud560 \uc218 \uc788\ub2e4. \n\n> \ub2e4\uc218\uc758 \uc778\uc6d0\uc774 \uac10\uc9c0\ub418\ub354\ub77c\ub3c4 \uc2e4\uc2dc\uac04\uc73c\ub85c \ub9c8\uc2a4\ud06c \ubbf8\ucc29\uc6a9\uc790\uc758 \uc218\ub97c \uad6c\ubd84\ud574\ub0bc \uc218 \uc788\ub2e4.\n", "meta": {"hexsha": "9585a592947ec95197c63d037b9cee7e90144f33", "size": 4880, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": ".ipynb_checkpoints/demo-checkpoint.ipynb", "max_stars_repo_name": "Younhong/COVID19-Mask-Detection-Model", "max_stars_repo_head_hexsha": "5f7478141588073e3984ed8cbd588d0d07d29abd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": ".ipynb_checkpoints/demo-checkpoint.ipynb", "max_issues_repo_name": "Younhong/COVID19-Mask-Detection-Model", "max_issues_repo_head_hexsha": "5f7478141588073e3984ed8cbd588d0d07d29abd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": ".ipynb_checkpoints/demo-checkpoint.ipynb", "max_forks_repo_name": "Younhong/COVID19-Mask-Detection-Model", "max_forks_repo_head_hexsha": "5f7478141588073e3984ed8cbd588d0d07d29abd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8037383178, "max_line_length": 146, "alphanum_fraction": 0.5032786885, "converted": true, "num_tokens": 1391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23651623644570757, "lm_q2_score": 0.03210070729573671, "lm_q1q2_score": 0.007592338476832914}}
{"text": "# High-Level Waste : Policy\n\nIn the United States, high-level readioactive waste is categorized as such not by its constituent material, but by the history of that material. Let's talk about how this came to be. \n\n\n## Learning Objectives\n\nAt the end of this lesson, you will be equipped to:\n\n- Understand the magnitude of the current waste challenge in the US. \n- Recall the history of nuclear waste policy in the United States\n- Understand the legislation in the Nuclear Waste Policy Act\n- Recall the history of the Yucca Mountain Project\n- Recognize the charter and conclusions of the Blue Ribbon Commission\n- Describe the impacts of the Nuclear Waste Confidence ruling\n- Understand the path and current status of the Yucca Mountain license application\n- Recognize the NWPA waste class of various nuclear fuel cycle materials\n\n\n\n## Current Status\n\nThe waste is waiting.\n\n\n<center>The locations of the used nuclear fuel and high level waste in the united states\ncover over a hundred locations and nearly 40 states [5]</center>\n\n\n<center>Spent fuel pools hold recently discharged fuel at reactor sites and elsewhere [2].</center>\n\n\n<center>Vitrified glass logs at reprocessing facilities and elsewhere [7].</center>\n\n\n<center>Dry casks at reactor sites and elsewhere [10].</center>\n\n\n<center>Liquid waste in steel or carbon steel tanks at Hanford and elsewhere[4].</center>\n\n\n<center>The amount of nuclear spent fuel and high level waste now exceeds the proposed legislative capacity of Yucca Mountain [13].</center>\n\n\n<center>An array of options have been considered in the past [13].</center>\n\n\n<center>The current U.S. geologic disposal concept [13].</center>\n\n\n<center>The full history of domestic nuclear waste policy, in eras [13].</center>\n\n## Siting\n\nHow did we get here?\n\n\n### 1940-1970 Preliminary Studies\n- 1940s - first defense waste produced\n- 1950s - first power reactors\n- 1954 - The Atomic Energy Act directs the government to promote the peaceful use of atomic energy, with the understanding that disposal of the highly radioactive waste produced would be the responsibility of the federal government.\n- 1957 - National Academy of Sciences recommends geological disposal.\n\n### 1970 - 1983 National Site Screening\n\n- 1978 - first Yucca Mountain borehole\n- 1982 - Nuclear Waste Policy Act\n\n### 1983 Nuclear Waste Policy Act\n\nPassed through congress in 1982, it was signed into law in January, 1983 by President Ronald Reagan.\n\n> This legislation defined the Federal Governments responsibility to\nprovide permanent disposal in a deep geologic repository for spent fuel\nand high-level radioactive waste from commercial and defense\nactivities. Under amended provisions (1987) of this Act, the\nDepartment of Energy (DOE) has the responsibility to locate, build,\nand operate a repository for such wastes. [11]\n\n### Site Review\n\n\n<center>The siting process began at nine sites and downselected to one [13].</center>\n\n\n<center>The land surrounding and including Yucca Mountain was already owned by the\nfederal government when the site was selected.</center>\n\n### Selection of Yucca Mountain\n\nThe Yucca Mountain Site was selected and accepted by the office of President\nRonald Reagan in 1987.\n\n\n<center>Yucca Mountain is in southern Nevada [12].</center>\n\n### 1988 Viability Assessment\n\nThe 1988 **Viability Assessment** describes the nuclear waste problem and\nexplains why the United States and other nations are considering deep geologic\ndisposal as the solution. It also describes what research must be done to\ncomplete a license application.\n\n**Public hearings** are held about this viability assessment and with this, the\nYucca Mountain site was deemed a viable site for further characterization and\nthe **pursuit of a license application** began.\n\n### 1991-2002 Site Characterization\n\nThe process of researching the suitability of Yucca Mountain began:\n\n- 1991 - surface studies begin\n- 1999 - bills for interim storage at the Nevada Test Site are introduced. Bill Clinton vows to veto them.\n- 2000 - The environmental impact statement is release for public comment.\n- 2001 - EPA proposes radiation standards for Yucca Mountain. The State of Nevada files suit against the EPA concerning the standards.\n\n## Nuclear Waste Fund\n\nThe NWPA established a nuclear waste fund, to be paid into by the commercial\nentities producing nuclear waste domestically.\n\n> In return for 1 mill per kWh, the utilities would gain the assurance that the United States would manage the disposal of that waste.\n\nThough some of the Nuclear Waste Fund has been spent on the Yucca Mountain\nProject, it currently has an unspent balance of $25 billion.\n\nIt receives nearly $750 million each year from the commerical entities that pay\ninto it.\n\n### Nuclear Waste Fund Litigation\n\n- 1983 - Nuclear utilities signed the Standard Contract agreeing to pay the nuclear waste fee.\n- 1998 - The utilities sue the federal government over the delay in used fuel acceptance.\n- 1998 - Courts ruled the DOE is partially liable. DOE settled and DOE developed an amended Standard Contract [3] to address new reactors.\n\n### 2002 - 2008 Site Recommendation\n\n- 2002- The site was deemed appropriately characterized for recommendation in 2002. **Secretary of Energy$\\longrightarrow$President Bush$\\longrightarrow$Congress**\n- 2004 - In the Nevada Lawsuit, the EPA 10,000 year radiation standard is deemed inadequate. The rest of the radiation standards remain.\n\n### 2008 - 2011 License Application and Withdrawal\n\n- The license application was submitted to the NRC in **2008**.\n- The NRC was expected to make a decision within 4 years.\n- In **May 2009**, Secretary Steven Chu stated: \u201cYucca Mountain as a repository is off the table\u201d.\n- **July 2009**, the House of Representatives voted 388 to 30 to not defund the Yucca Mountain repository in the FY2010 budget.\n- On **March 3, 2010**, the DOE filed a motion with the NRC to withdraw its license application.\n- **Lawsuits** erupted from Hanford, WA and Aiken County, SC, among others. Ruled premature.\n- YMP funding was terminated with the Defense and Full-Year Continuing Appropriations Act, passed by Congress on **April 14, 2011.**\n\n### 2012 Blue Ribbon Commission Report\n\nThe goals of the blue ribbon commission were [8]:\n\n- Evaluation of existing fuel cycle technologies and R&D programs.\n-  Options for safe storage of used nuclear fuel while final disposition pathways are selected and deployed.\n- Options for permanent disposal of used fuel and/or high-level nuclear waste,\n- Options to make legal and commercial arrangements for the management of used nuclear fuel and nuclear waste in a manner that takes the current and potential full fuel cycles into account.\n- Options for decision-making processes for management and disposal that are flexible, adaptive, and responsive.\n- Options to ensure that decisions on management of used nuclear fuel and nuclear waste are open and transparent, with broad participation.\n- The possible need for additional legislation or amendments to existing laws, including the Nuclear Waste Policy Act of 1982, as amended.\n\n\nThe BRC came out with a list of recommendations [1] :\n\n- Consentbased siting approach\n- An authoritative organization dedicated solely to implementing the waste management program.\n- Access to the waste fund.\n- Prompt efforts : one or more geologic disposal facilities.\n- Prompt efforts : one or more consolidated storage facilities.\n- Prompt efforts : to prepare for SNF and HLW transportation.\n- Support for continued U.S. innovation in nuclear energy technology and for workforce development;\n- U.S. leadership in international efforts to address safety, waste management, nonproliferation, and security concerns.\n\nThe Senate tried to take action:\n- Senator Jeff Bingaman, before leaving office, introduced a bill called the Nuclear Waste Administration Act of 2011. [Its daughter went before the senate in 2012.]( http://www.energy.senate.gov/public/index.cfm/2012/8/s-3469-the-nuclear-waste-administration-act-of-2012) It died in congress. \n\n\nThe Judicial system tried to take action related to the Waste Confidence Rule:\n\n- To license a reactor or approve a reactor license extension, the NRC requires a Waste Confidence clause. It is a section of the application that assures the NRC that waste produced by the applying facility will be dealt with.\n- Previous to the closing of the Yucca Mountain Project, all applicants for reactor licenses and license extensinos were able to cite the nuclear waste fund and the Yucca Mountain Project.\n- In 2012, the United States Court of Appeals for the District of Columbia Circuit declared that there is no waste confidence.\n\n> \u201cThe commission apparently has no long-term plan other than hoping for a geologic repository... Failing to establish a repository is a possibility thatcannot be ignored.\u201d [14]\n\n### 2013 DOE Response to Blue Ribbon Commission\n\nDOE created four working groups.\n- Governance Framework and Funding\n- System Design & Architecture\n- ConsentBased Siting\n- Transportation Routing, Safety and Security\n\nIn a brief statement [[6]](http://www.energy.gov/downloads/strategy-management-and-disposal-used-nuclear-fuel-and-high-level-radioactive-waste), the DOE agreed in general with the BRC and said that DOE would pursue a timeline :\n\n- Sites, designs and licenses, constructs and begins operations of a pilot interim storage facility by **2021** with an initial focus on accepting used nuclear fuel from shut-down reactor sites.\n- Advances toward the siting and licensing of a larger interim storage facility to be available by **2025**.\n-  Makes **demonstrable progress** on the siting and characterization of repository sites to facilitate the availability of a geologic repository by 2048.\n\n\n### 2013 Legal Decisions\n\n- May: DOE is ordered by a court to stop collecting the waste fee. Representing 750 million a year when it ended, the fund now holds 37 billion.\n- August-October : NRC is ordered by the DC court of appeals to restart the licensing proceeding. The appropriated funds were insufficient to complete the proceeding. \n\n\n### 2014-2015 NRC Conclusions\n\n- NRC report concludes [continued storage in dry casks is safe for 160 years](http://www.yuccamountain.org/pdf/nrc_rule0814.pdf), brushing aside the immediate consequences of the judicial decision concerning waste confidence.\n- December 2014-Jan 2015: NRC releases the final volumes of the reports on the suitability of Yucca Mountain as a disposal spot for nuclear waste, finding that the design met the commission's requirements.\n\n\n### 2016 \n\n- DOE issues [a statement](http://www.yuccamountain.org/pdf/2015-32346.pdf) declaring that it would move forward with a consent-based siting process. \n\n\n### 2017 - 2018\n\n- March 2: Rick Perry becomes Secretary of Energy.\n- White House budget contains \\$120 million for Yucca.\n- April: A hearing to amend the NWPA\n- May: No money in federal spending budget for Yucca.\n- Nov 2: A bill to restart licensing Yucca Mountain did not pass the Senate.\n- [The \u201cConsent-Based Siting\u201d tab on energy.gov](https://www.energy.gov/ne/consent-based-siting)\n\n### 2019-2020\n- The Trump administration made initial budget requests to support pursuit of Yucca Mountain, but Senators Masto (D-Nev.),  Heller (R-Nev.), and others urged the US Energy & Water committee to pursue a consent-based siting approach. \n- The budget ultimately reflected that \"alternative approaches\" would be taken, rather than Yucca Mountain.\n\n### 2021\n- The Biden-Harris administration, including DOE Secretary Granholm have indicated that Yucca Mountain remains off the table and that a consent-based approach is preferred.\n\n## Waste Classification\n\nWaste classification is an area of active discussion. \n\n\n\n<center>[source](https://www.fas.org/sgp/crs/misc/RL32163.pdf)</center>\n\n\n\n<center>[source](https://www.fas.org/sgp/crs/misc/RL32163.pdf)</center>\n\n\n```python\nfrom IPython.display import IFrame\nIFrame(\"https://embed.polleverywhere.com/free_text_polls/JfkmGGnQJfwt8Mr?controls=none&short_poll=true\",width=700, height=700)\n```\n\n\n\n\n\n\n\n\n\n\n## Radioactivity\n\nRecall: The SI unit of activity is the becquerel (Bq), equal to one reciprocal second.\n\n\\begin{align}\nA(i) &= -\\frac{dN_i}{dt}\\\\\n&= \\lambda_iN_i\n\\end{align}\n\n## Toxicity\n\nOne possibility is to use toxicity as a classifying metric. It captures the activity and danger to humans\n\n\\begin{align}\n\\mbox{Toxicity}(i,k) &= \\frac{A(i)}{DAC(i,k)}\\\\\ni &= \\mbox{isotope}\\\\\nk &= \\mbox{medium index, air or water}\\\\\nDAC &= \\mbox{derived air concentration of isotope i in air or water.} \n\\end{align}\n\nWarning : DAC is confusing. It generally is reported in $\\frac{\\mu Ci}{mL}$. From the NRC glossary, the definition is:\n\n> Derived air concentration (DAC) The concentration of a given radionuclide in air which, if breathed by the reference man for a working year of 2,000 hours under conditions of light work (with an inhalation rate of 1.2 cubic meters of air per hour), results in an intake of one annual limit on intake (ALI).\n\nOk, great, so what is ALI?\n\n> ALI is the smaller value of intake of a given radionuclide in a year by the \"reference man\" that would result in a committed effective dose equivalent (CEDE) of 5 rems (0.05 sievert) or a committed dose equivalent (CDE) of 50 rems (0.5 sievert) to any individual organ or tissue. \n\n\n\n<center>[source](https://www.fas.org/sgp/crs/misc/RL32163.pdf)</center>\n\n\n\n\n\n\nA flow chart for improvements is below.\n\n\n<center>[source](http://www.cresp.org/NuclearChemCourse/monographs/12_Viena_Waste%20Forms%20for%20an%20Advanced%20Fuel%20Cycle_3_3_09.pdf)</center>\n\n## Wrap-up\n\n- Understand the magnitude of the current waste challenge in the US. \n- Recall the history of nuclear waste policy in the United States\n- Understand the legislation in the Nuclear Waste Policy Act\n- Recall the history of the Yucca Mountain Project\n- Recognize the charter and conclusions of the Blue Ribbon Commission\n- Describe the impacts of the Nuclear Waste Confidence ruling\n- Understand the path and current status of the Yucca Mountain license application\n- Recognize the NWPA waste class of various nuclear fuel cycle materials\n\n## References\n\nThis section was developed to complement pages 302-373 of [15] as well as the full content of [16].\n\n\n[1] Mark Ayers, Vicky Bailey, Albert Carnesale, Pete Domenici, Susan Eisenhower, Chuck Hagel, Jonathan Lash, Allison Macfarlane, Richard Meserve, Ernest Moniz, Per Peterson, John Rowe, and Phil Sharp.\nReport to the secretary of energy. Technical report, Blue Ribbon Commission on America\u2019s Nuclear Future, January 2012.\n\n[2] DOE. Spent fuel pool at a nuclear power plant.\nhttp://www.ocrwm.doe.gov/curriculum/unit1/lesson3reading.shtml.\n\n[3] DOE. Standard contract amendment for new reactors.\nhttp://energy.gov/gc/downloads/standard-contract-amendment-new-reactors.\n\n[4] DOE. Underground tank farm with 12 of the site\u2019s 177 waste storage tanks.\n\n[5] DOE. Final supplemental environmental impact statement for a geologic repository for the disposal of\nspent nuclear fuel and high-level radioactive waste at yucca mountain, nye county, nevada. Technical Report DOE/EIS-0250F-S1, June 2008.\n\n[6] DOE. Strategy for the management and disposal of used nuclear fuel and high-level radioactive waste. Technical report, United States Department of Energy (DOE), Washington D.C., United States,\nJanuary 2013.\n\n[7] Peter Essick. Photographing the infinity room - timing is everything, April 2012.\n\n[8] Carol Matthews. Blue ribbon commission on americas nuclear future U.S. department of energy - advisory\ncommittee charter, March 2010.\n\n[9] NRC. Nuclear-fuel.jpg.\n\n[10] NRC. Dry cask storage., January 2008.\n\n[11] NRC. Backgrounder on radioactive waste.\nTechnical report, Nuclear Regulatory Commission, February 2011.\n\n[12] OMB. Yucca mountain 2.jpg, August 2006.\n\n[13] Mark Peters. What\u2019s next for used nuclear fuel and nuclear waste management policy?, January 2013.\n\n[14] David B. Sentelle. On petitions for review of orders of the nuclear regulatory commission.\n\n[15] N. Tsoulfanidis, The Nuclear Fuel Cycle. La Grange Park, Illinois, USA: American Nuclear Society, 2013.\n\n[16] Mark Ayers, Vicky Bailey, Albert Carnesale, Pete Domenici, Susan Eisenhower, Chuck Hagel, Jonathan\nLash, Allison Macfarlane, Richard Meserve, Ernest Moniz, Per Peterson, John Rowe, and Phil Sharp.\nReport to the Secretary of Energy. Technical report, Blue Ribbon Commission on America\u2019s Nuclear\nFuture, January 2012. URL: [http://energy.gov/sites/prod/files/2013/04/f0/brc_finalreport_\njan2012.pdf](http://energy.gov/sites/prod/files/2013/04/f0/brc_finalreport_\njan2012.pdf)\n\n\n```python\n\n```\n", "meta": {"hexsha": "638f57a60c6a9dc8b7552f9c4be8e29032d905f8", "size": 22981, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "high-level-waste/high-level-waste.ipynb", "max_stars_repo_name": "abachma2/npre412", "max_stars_repo_head_hexsha": "3f105a15edc07745f1dd65cd791777a01136ec23", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "high-level-waste/high-level-waste.ipynb", "max_issues_repo_name": "abachma2/npre412", "max_issues_repo_head_hexsha": "3f105a15edc07745f1dd65cd791777a01136ec23", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "high-level-waste/high-level-waste.ipynb", "max_forks_repo_name": "abachma2/npre412", "max_forks_repo_head_hexsha": "3f105a15edc07745f1dd65cd791777a01136ec23", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.6233009709, "max_line_length": 317, "alphanum_fraction": 0.6526260824, "converted": true, "num_tokens": 3831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12252321892633068, "lm_q2_score": 0.06187599177845324, "lm_q1q2_score": 0.007581245686955263}}
{"text": "```python\nls\n```\n\n    2021_Cover Letter Oct 9.pdf           figg_ex3_2-eps-converted-to.pdf\r\n    2022_Final_Gompertz_April.aux         figg_ex3_2.eps\r\n    2022_Final_Gompertz_April.log         figg_ex3_22-eps-converted-to.pdf\r\n    2022_Final_Gompertz_April.out         figg_ex3_22.eps\r\n    2022_Final_Gompertz_April.pdf         figg_ex3_4-eps-converted-to.pdf\r\n    2022_Final_Gompertz_April.synctex.gz  figg_ex3_4.eps\r\n    2022_Final_Gompertz_April.tex         figg_ex3_5-eps-converted-to.pdf\r\n    3D_31-eps-converted-to.pdf            figg_ex3_5.eps\r\n    3D_31.eps                             figg_ex4_1-eps-converted-to.pdf\r\n    3D_32-eps-converted-to.pdf            figg_ex4_1.eps\r\n    3D_32.eps                             figg_ex4_1.png\r\n    3D_33-eps-converted-to.pdf            figg_ex4_12.png\r\n    3D_33.eps                             figg_ex4_2-eps-converted-to.pdf\r\n    ex1_3D_1-eps-converted-to.pdf         figg_ex4_2.eps\r\n    ex1_3D_1.eps                          figg_ex5_1-eps-converted-to.pdf\r\n    ex1_3D_2-eps-converted-to.pdf         figg_ex5_1.eps\r\n    ex1_3D_2.eps                          figg_ex5_1.png\r\n    ex1_3D_3-eps-converted-to.pdf         figg_ex5_2-eps-converted-to.pdf\r\n    ex1_3D_3.eps                          figg_ex5_2.eps\r\n    figg_ex1_1-eps-converted-to.pdf       figg_ex6_1-eps-converted-to.pdf\r\n    figg_ex1_1.eps                        figg_ex6_1.eps\r\n    figg_ex1_1.png                        figg_ex6_2-eps-converted-to.pdf\r\n    figg_ex1_2-eps-converted-to.pdf       figg_ex6_2.eps\r\n    figg_ex1_2.eps                        figg_ex6_3-eps-converted-to.pdf\r\n    figg_ex1_2.png                        figg_ex6_3.eps\r\n    figg_ex1_3-eps-converted-to.pdf       figg_ex7_1-eps-converted-to.pdf\r\n    figg_ex1_3.eps                        figg_ex7_1.eps\r\n    figg_ex1_3.png                        figg_ex7_2-eps-converted-to.pdf\r\n    figg_ex2_1.png                        figg_ex7_2.eps\r\n    figg_ex2_2-eps-converted-to.pdf       figg_ex7_3-eps-converted-to.pdf\r\n    figg_ex2_2.eps                        figg_ex7_3.eps\r\n    figg_ex2_2.png                        figg_ex7_4-eps-converted-to.pdf\r\n    figg_ex3_1-eps-converted-to.pdf       figg_ex7_4.eps\r\n    figg_ex3_1.eps                        figg_ex7_5-eps-converted-to.pdf\r\n    figg_ex3_12-eps-converted-to.pdf      figg_ex7_5.eps\r\n    figg_ex3_12.eps                       \u001b[34mfile_used\u001b[m\u001b[m/\r\n    figg_ex3_13-eps-converted-to.pdf      find_included_file_names.ipynb\r\n    figg_ex3_13.eps\r\n\n\n\n```python\nwith open('2022_Final_Gompertz_April.tex', 'r') as f:\n    contents = f.read()\n```\n\n\n```python\n\nimport re\npattern = re.compile(r'\\w.eps') \nmatches = pattern.findall(contents)\nmatches\n```\n\n\n\n\n    ['e{eps',\n     't,eps',\n     't,eps',\n     '1.eps',\n     '2.eps',\n     '3.eps',\n     '1.eps',\n     '2.eps',\n     '3.eps',\n     '2.eps',\n     '1.eps',\n     '2.eps',\n     '3.eps',\n     '1.eps',\n     '2.eps',\n     '3.eps',\n     '4.eps',\n     '5.eps',\n     '1.eps',\n     '2.eps',\n     '1.eps',\n     '2.eps',\n     '3.eps',\n     '1.eps',\n     '2.eps',\n     '1.eps',\n     '2.eps',\n     '3.eps',\n     '4.eps',\n     '5.eps']\n\n\n\n\n```python\npattern = re.compile(r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+')                      \nmatches = pattern.findall(contents)\nmatches\n```\n\n\n\n\n    ['kamrujjaman@du.ac.bd',\n     '_akter@cc.nara-wu.ac.jp',\n     'kkeya@ttu.edu',\n     'mhabiswas@yahoo.com',\n     'rafiul@iastate.edu',\n     '_ariful@math.buet.ac.bd']\n\n\n\n\n```python\npattern = re.compile(r'[a-zA-Z0-9_.+-]+\\.[a-zA-Z0-9-.]+')                      \nmatches = pattern.findall(contents)\nmatches\n```\n\n\n\n\n    ['kern-.2em',\n     '1.5-spacing',\n     'du.ac.bd',\n     'cc.nara-wu.ac.jp',\n     'ttu.edu',\n     'yahoo.com',\n     'iastate.edu',\n     'math.buet.ac.bd',\n     'orcid.org',\n     '-0.5cm',\n     '6.35in',\n     '0.02in',\n     '6.35in',\n     '0.02in',\n     'Species...',\n     '1.0',\n     '0.0',\n     '2.5',\n     '1.2',\n     '1.2',\n     '1.2',\n     '0.3',\n     'figg_ex1_1.eps',\n     '0.3',\n     'figg_ex1_2.eps',\n     '0.3',\n     'figg_ex1_3.eps',\n     '0.0',\n     '2.5',\n     '0.1',\n     '1.1',\n     '2.0',\n     '1.2',\n     '1.2',\n     '1.2',\n     '0.3',\n     'ex1_3D_1.eps',\n     '0.3',\n     'ex1_3D_2.eps',\n     '0.3',\n     'ex1_3D_3.eps',\n     '0.0',\n     '2.5',\n     '1.0',\n     '2.0',\n     '1.2',\n     '1.2',\n     '1.2',\n     '1.0',\n     '0.0',\n     '2.5',\n     '2.0',\n     '1.2',\n     '1.2',\n     '1.2',\n     '0.4',\n     'figg_ex2_1.png',\n     '0.4',\n     'figg_ex2_2.eps',\n     '0.0',\n     '2.5',\n     '1.0',\n     '2.0',\n     '1.2',\n     '1.2',\n     '1.2',\n     '1.2',\n     '0.1',\n     '1.1',\n     '2.0',\n     '2.5',\n     '1.2',\n     '1.1',\n     '0.3',\n     'figg_ex3_1.eps',\n     '0.3',\n     'figg_ex3_12.eps',\n     '0.3',\n     'figg_ex3_13.eps',\n     '2.5',\n     '1.1',\n     '1.2',\n     '0.5',\n     '1.5',\n     '2.0',\n     '0.5',\n     '1.5',\n     '2.5',\n     '0.3',\n     '3D_31.eps',\n     '0.3',\n     '3D_32.eps',\n     '0.3',\n     '3D_33.eps',\n     '2.5',\n     '1.0',\n     '1.2',\n     '2.5',\n     '1.5',\n     '0.5',\n     '0.33',\n     'figg_ex3_4.eps',\n     '0.33',\n     'figg_ex3_5.eps',\n     '2.5',\n     '1.1',\n     '1.2',\n     '0.5',\n     '0.1',\n     '1.1',\n     '2.0',\n     '0.5',\n     '1.2',\n     '1.5',\n     '1.2',\n     '0.33',\n     'figg_ex4_1.eps',\n     '0.33',\n     'figg_ex4_2.eps',\n     '0.0',\n     '2.0',\n     '1.2',\n     '0.2',\n     '0.75',\n     '1.2',\n     '1.5',\n     '0.75',\n     '0.5',\n     '1.1',\n     '1.5',\n     '0.0',\n     '1.3',\n     '2.1',\n     '1.1',\n     '1.3',\n     '1.5',\n     '0.3',\n     '1.1',\n     '1.7',\n     '1.2',\n     '0.33',\n     'figg_ex5_1.eps',\n     '0.33',\n     'figg_ex5_2.eps',\n     '0.0',\n     '2.1',\n     '1.3',\n     '1.1',\n     '1.1',\n     '1.3',\n     '1.5',\n     '1.2',\n     '0.3',\n     '1.1',\n     '1.7',\n     '1.0',\n     '2.5',\n     '0.5',\n     '1.5',\n     '0.75',\n     '0.3',\n     'figg_ex6_3.eps',\n     '0.3',\n     'figg_ex6_1.eps',\n     '0.3',\n     'figg_ex6_2.eps',\n     '1.0',\n     '2.5',\n     '0.5',\n     '1.5',\n     '0.75',\n     '1.0',\n     '2.5',\n     '1.2',\n     '0.75',\n     '1.2',\n     '1.5',\n     '0.3',\n     'figg_ex7_1.eps',\n     '0.3',\n     'figg_ex7_2.eps',\n     '0.3',\n     'figg_ex7_3.eps',\n     '1.0',\n     '2.5',\n     '1.0',\n     '1.2',\n     '0.75',\n     '1.2',\n     '1.5',\n     '0.1',\n     '1.1',\n     '1.0',\n     '0.5',\n     '1.5',\n     '2.5',\n     '2.5',\n     '1.2',\n     '0.75',\n     '1.0',\n     '0.33',\n     'figg_ex7_4.eps',\n     '0.33',\n     'figg_ex7_5.eps',\n     '0.5',\n     '1.5',\n     '2.5',\n     '2.5',\n     '1.0',\n     '1.2',\n     '0.75',\n     'M.K.',\n     'S.I.A.',\n     'M.H.A.B.',\n     'K.M.A.K.',\n     'K.N.K.',\n     'S.I.A.',\n     'M.K.',\n     'M.R.I',\n     'M.H.A.B.',\n     'M.K',\n     'S.I.A.',\n     'K.N.K.',\n     'K.M.A.K.',\n     'K.N.K.',\n     'M.R.I',\n     'S.I.A.',\n     'S.I.A.',\n     'M.K.',\n     'K.M.A.K.',\n     'M.H.A.B',\n     'M.R.I.',\n     'M.K.',\n     'Vol.191',\n     'no.1',\n     'dx.doi.org',\n     '10.1016',\n     'j.na.2009.04.025',\n     'no.2']\n\n\n\n\n```python\nimport os\n```\n\n\n```python\n# pattern\npattern = re.compile(r'[a-zA-Z0-9_.+-]+\\.eps')                      \nmatches = pattern.findall(contents)\nmatches\n# mkdir file_used\n# for match in matches: \n#     os.cp match file_used/ \n    \n\n```\n\n\n\n\n    ['figg_ex1_1.eps',\n     'figg_ex1_2.eps',\n     'figg_ex1_3.eps',\n     'ex1_3D_1.eps',\n     'ex1_3D_2.eps',\n     'ex1_3D_3.eps',\n     'figg_ex2_2.eps',\n     'figg_ex3_1.eps',\n     'figg_ex3_12.eps',\n     'figg_ex3_13.eps',\n     '3D_31.eps',\n     '3D_32.eps',\n     '3D_33.eps',\n     'figg_ex3_4.eps',\n     'figg_ex3_5.eps',\n     'figg_ex4_1.eps',\n     'figg_ex4_2.eps',\n     'figg_ex5_1.eps',\n     'figg_ex5_2.eps',\n     'figg_ex6_3.eps',\n     'figg_ex6_1.eps',\n     'figg_ex6_2.eps',\n     'figg_ex7_1.eps',\n     'figg_ex7_2.eps',\n     'figg_ex7_3.eps',\n     'figg_ex7_4.eps',\n     'figg_ex7_5.eps']\n\n\n\n\n```python\ncontents\n```\n\n\n\n\n    '\\\\documentclass[11pt]{article}\\n\\\\usepackage{graphicx,amscd,amsfonts,amsmath,amsthm,amssymb,latexsym,amsfonts,color}\\n%\\\\usepackage{epsfig,float,epstopdf,array,bm}\\n\\\\usepackage[bookmarksnumbered, colorlinks,plainpages]{hyperref}\\n\\\\usepackage{amsmath,amssymb,graphicx,float,epsf}\\n%\\\\def\\\\RR{\\\\hbox{I\\\\kern-.2em\\\\hbox{R}}}\\n%\\\\newcommand{\\\\qed}{\\\\hbox to 0pt{}\\\\hfill$\\\\rlap{$\\\\sqcap$}\\\\sqcup$ \\\\vspace{3mm}}\\n%\\\\renewcommand{\\\\theequation}{\\\\thesection.\\\\arabic{equation}}\\n\\\\numberwithin{equation}{section}\\n\\\\restylefloat{figure}\\n%\\\\usepackage{lmodern} %Type1-font for non-english texts and characters\\n\\\\usepackage{graphicx} %%For loading graphic files\\n%\\\\usepackage{subfig} %%Subfigures inside a figure\\n%\\\\usepackage{tikz} %%Generate vector graphics from within LaTeX\\n%%======Math Packages=====================================================\\n%\\\\usepackage{amsmath}\\n%\\\\usepackage{amsthm}\\n%\\\\usepackage{amsfonts}\\n%\\\\usepackage[pagewise]{lineno}\\\\linenumbers\\n\\\\usepackage{enumerate}\\n\\\\usepackage{enumitem}\\n\\\\newtheorem{Def}{Definition}\\n\\\\newtheorem{Lemma}{Lemma}\\n\\\\newtheorem{Th}{Theorem}\\n\\\\newtheorem{Cor}{Corollary}\\n\\\\newtheorem{Prop}{Proposition}\\n\\\\newtheorem{Rem}{Remark}\\n%\\\\newtheorem{Ex}{Example}\\n\\\\newtheorem{Ex}{Case}\\n%\\\\newtheorem{Conj}{Example}\\n%%====Line Spacing=====================================================\\n%\\\\usepackage{setspace}\\n%\\\\singlespacing        %% 1-spacing (default)\\n%\\\\onehalfspacing       %% 1.5-spacing\\n%\\\\doublespacing        %% 2-spacing\\n\\\\usepackage{a4wide} %%Smaller margins = more text per page.\\n\\\\usepackage{authblk} % for multiple authors affiliation\\n%\\\\usepackage{fancyhdr} %%Fancy headings\\n%\\\\usepackage{longtable} %%For tables, that exceed one page\\n%\\\\usepackage{cases}\\n\\n\\\\begin{document}\\n\\t% Don\\'t want date printed\\n\\t\\\\date{}\\n\\n%\\\\title{Periodic solutions and steady state of a dispersal Gompertz dynamics and its optimal harvesting policy}\\n%\\\\title{Spatio-temporal Gompertz Dynamics for Single Species Resource Management with Optimal Harvesting Policy}\\n\\\\title{Gompertz dynamics for a single species resource management with optimal harvesting policy}\\n\\n\\\\author[1]{\\\\small Md. Kamrujjaman \\\\thanks{Corresponding author: M. Kamrujjaman, email: kamrujjaman@du.ac.bd}}} \\n\\\\author[2]{\\\\small Sayeda Irin Akter\\\\thanks{E-mail: uas\\\\_akter@cc.nara-wu.ac.jp}}\\n\\\\author[3]{\\\\small Kamrun Nahar Keya\\\\thanks{E-mail: kkeya@ttu.edu}} \\n\\\\author[4]{\\\\small Md. Haider Ali Biswas\\\\thanks{E-mail: mhabiswas@yahoo.com}} \\n\\\\author[5]{\\\\small Md Rafiul Islam\\\\thanks{Corresponding author: M. R. Islam, email: rafiul@iastate.edu}} \\n\\\\author[6]{\\\\small K. M. Ariful Kabir\\\\thanks{E-mail: km\\\\_ariful@math.buet.ac.bd }} \\n\\n\\\\affil[1]{\\\\footnotesize Department of Mathematics, University of Dhaka, Dhaka 1000, Bangladesh} %Nara 630-8506\\n\\\\affil[2]{\\\\footnotesize Department of Environmental Science, Nara Women\\'s University,\\n\\tKita-Uoya Nishimachi, Nara, Japan}\\n%\\\\affil[2]{\\\\footnotesize Department of Mathematics and Statistics, University of Calgary, Calgary, AB, Canada}\\n\\\\affil[3]{\\\\footnotesize Department of Mathematics and Statistics, Texas Tech University, Lubbock, Texas, USA}\\n\\\\affil[4]{\\\\footnotesize Mathematics Discipline, Science Engineering and Technology School, Khulna University, Khulna 9208, Bangladesh}\\n\\\\affil[5]{\\\\footnotesize Department of Mathematics, Iowa State University, Ames, Iowa 50011, USA}\\n\\\\affil[6]{\\\\footnotesize Department of Mathematics, Bangladesh University of Engineering and Technology, Dhaka, Bangladesh}\\n\\n%\\\\\\\\ ORCID ID: \\\\url{https://orcid.org/0000-0002-4892-745X \\n\\\\maketitle\\n\\\\vspace{-0.5cm}\\n\\\\noindent\\\\rule{6.35in}{0.02in}\\\\\\\\\\n{\\\\bf Abstract.} \\nGompertz dynamics offers a significant use for the growth of invasive species, cancer modeling, optimal harvesting policy, sustainable yield, and optimal population level due to its pattern formation of low-density cases. This paper studies a generalized non-homogeneous diffusive single-species Gompertz model incorporated with zero Neumann boundary conditions where all the coefficients are smooth periodic functions. Further, our analytical explanation approach of the global stability of a time-periodic solution and optimal harvesting policy for the Gompertz growth law could substantially generalize the results for many small organisms including plants and wild populations. Our proposed model successfully investigates the ordinary differential equation dynamics in the absence of diffusion. Also, the spatio-temporal equation describes the population\u2019s evolutionary processes more precisely than ordinary differential equations. Finally, we can observe several potential applications as confining the optimal way to real scenarios and related fields where the optimal harvesting is used.\\n\\\\\\\\[-3mm]\\n\\n\\\\noindent{\\\\it \\\\footnotesize Keywords}: {\\\\small Persistence; optimal harvesting; global stability; periodic solution; sustainable yield. }\\\\\\\\\\n\\\\noindent\\n\\\\noindent{\\\\it \\\\footnotesize AMS Subject Classification}: 92D25, 35K57 (primary), 35K50, 35K61, 37N25. \\\\\\\\\\n\\\\noindent\\\\rule{6.35in}{0.02in}\\n\\n%\\\\pagestyle{myheadings}\\\\markboth{Sayeda Irin Akter et. al.}{Spatio-temporal Gompertz Dynamics for Single Species...}\\n%\\\\thispagestyle{empty}\\n\\n\\n\\n%===========New section====Introduction====================================================\\n\\\\section{Introduction}\\\\label{sec_01}\\nA classical reaction diffusion equation consisting of a reaction term and a diffusion term arises in many areas of science and engineering such as in chemistry \\\\cite{AMT}, in ecological invasions \\\\cite{EEHM}, in spread of epidemics \\\\cite{JDM}, in tumor growth \\\\cite{CMAJ} and in many other areas \\\\cite{JSM, JSJ, CC}. % \\\\cite{JSM, JSJ, PCF, ASM, CC}. \\nIf we look into the history, the area of population dynamics is found as the first application of mathematics to biology, such as Malthus predicted the unbounded exponential growth and Verhulst proposed the logistic equation. The first models were either differential or first-order difference equations. However, in many cases, we can not neglect either spatial distribution or dependence on the previous history of the population; thus, the adequate models would be ordinary/partial differential \\\\cite{XQZ}, or fractional  differential equations \\\\cite{YK}.\\n\\nIn ecology, a classical reaction-diffusion equation plays a vital role in the study of different types of dynamics of species \\\\cite{CC}. In theoretical ecology, the determination of distribution (density) of species (or organisms) and the structure of communities is one of the main goals to survive where species (or organisms) interact with each other in a given environment \\\\cite{RSC_2}. To maintain biodiversity in the ecosystems on conservation, the role of spatial effects has become essential in recent decades \\\\cite{MOMS, SFGS, LKB, EBL}. %\\\\cite{MOMS, SFGS, BML, LKB, KKJ, EBL, YJX}.\\nBoth autonomous and non-autonomous population models subject to either impulsive or continuous harvesting were studied in \\\\cite{EBRM}. In \\\\cite{SMH},  Henson and Cushing studied the effect of periodic habitat fluctuations on a nonlinear insect population model. Harvesting in a seasonal environment is studied in \\\\cite{CX}. A general harvesting model with seasonal carrying capacity is presented here, and a theoretical foundation is developed. \\n\\nAs for spatially distributed populations, if at each point the growth of the population size $u$ was described by a specific law, such as logistic, Gompertz, or some other then, the simplest model follows that $\\\\frac{\\\\displaystyle du}{\\\\displaystyle d t}=g\\\\left(u( t)\\\\right)$. Here the growth function can be modified to $f(x,u)$ to involve the space variable, and the diffusion term is added to the right-hand side to describe population movements.\\n\\nThe scientist Benjamin Gompertz studied general growth equations, and those were successfully applied to ecological applications such as actual tumor data, which was published in $1825$ that has become a foundational treatise establishing the concept variously called \"Gompertz\\'s Law\" or \"Gompertzian growth\" \\\\cite{GGG}.  He fitted it to the relationship between increasing death rate and age. Gompertz discussed the two distinct behaviors of the human life table. In some cases, such as countries or range of ages, the function of age decays exponentially. Again as in real-life tables, when age is discrete, it decreases as a geometric series. By the mid$-20^{\\\\text{th}}$ century, in models of population growth, Gompertz\\'s insight was applied that included mechanistic detail \\\\cite{WCP, WSB}. It is frequently used to describe bird growth \\\\cite{SJRR}, fish growth \\\\cite{RWB} and growth of other animals and also used in plant growth \\\\cite{PMVP}. To describe the number of bacteria in bacterial growth \\\\cite{ZJRV, SGLJ} and the volume of cancer cells \\\\cite{LAK} it is also used.\\n\\nIn recent years, bio-economic modeling of the exploitation of biological resources has gained importance in meeting people\\'s needs. Sustainable development and renewable resource management have a direct relationship in which ecologists and economists are interested. There have been much research regarding persistence, global stability, and optimal harvesting strategy for a single organism. The reaction-diffusion equations are well established and used widely for modeling the spatial effects. They support at least the following three types of ecological phenomena which are very essential:\\n%\\\\begin{enumerate}[label=\\\\Roman*.]\\n\\\\begin{itemize}\\n\\t\\t\\\\item the existence of a lowest patch shape necessary to persist a population,\\n\\t\\\\item the extension of wave fronts corresponding to biological invasions, and\\n\\t\\\\item \\tthe  spatial pattern formations in the population distributions in homogeneous environments.\\n\\\\end{itemize}\\t\\n%\\\\end{enumerate}\\n\\n\\n\\\\section{Model and Methods}\\nThis study considers a non-homogeneous diffusive single-species Gompertz model incorporated with the zero Neumann boundary conditions and its optimal harvesting policy where all the coefficients are smooth periodic functions. Let us consider the model below\\n\\\\begin{align}\\\\label{106}\\n\\\\begin{cases}\\n\\\\frac{\\\\displaystyle \\\\partial u}{\\\\displaystyle \\\\partial t}  \\n=D \\\\Delta u+ r(x, t)u(x, t) \\\\ln \\\\left(\\\\frac{\\\\displaystyle \\\\mathcal{K}(x, t)} {\\\\displaystyle u(x, t)}\\\\right) - H(x, t)u(x, t),\\\\; (x, t)\\\\in \\\\Omega\\\\times (0,\\\\infty)\\\\\\\\\\n u(x,0)=u_0>0,\\\\;\\\\; x\\\\in\\\\Omega\\\\\\\\\\n\\\\frac{\\\\displaystyle \\\\partial u}{\\\\displaystyle \\\\partial \\\\eta}=0,  \\\\;\\\\; (x, t)\\\\in \\\\partial\\\\Omega\\\\times (0,\\\\infty) \\n\\\\end{cases}\\n\\\\end{align}\\nwhere $u(x, t)$ is the population density, $r(x, t)$ is the intrinsic growth rate, $H(x, t)$ is harvesting rate, $\\\\mathcal{K}(x, t)$ is the carrying capacity of the environment. The domain $\\\\Omega$ is a bounded region of $\\\\mathbb{R}^n,(1\\\\leq n\\\\leq 3)$ with a small boundary and time $ t\\\\in(0,\\\\infty)$. The boundary $\\\\partial \\\\Omega \\\\in \\\\mathcal{C}^{2+\\\\alpha}$ has the property of an interior contact ball. Here $\\\\Delta$ is the Laplace operator in $\\\\mathbb{R}^n$, the constant $D>0$ is the diffusive coefficient. $\\\\mathcal{K}(x, t), \\\\; r(x, t), \\\\; \\\\frac{\\\\displaystyle \\\\partial \\\\mathcal{K}}{\\\\displaystyle \\\\partial  t}, \\\\; \\\\frac{\\\\displaystyle \\\\partial r}{\\\\displaystyle \\\\partial  t}$ are uniformly bounded from below and from above in $\\\\overline{\\\\Lambda}$ where, $\\\\Lambda\\\\equiv \\\\Omega\\\\times (0,+\\\\infty)$ and $\\\\overline{\\\\Lambda}\\\\equiv \\\\overline{\\\\Omega}\\\\times (0,+\\\\infty)$ (similarly $\\\\partial\\\\Lambda\\\\equiv \\\\partial \\\\Omega\\\\times (0,+\\\\infty)$).\\\\\\\\\\n\\nWhile we are considering the model (\\\\ref{106}), then in the absence of growth function $f(x,t, u,r,K)$, the organism has no change on their density level, which yields a uniform population distribution over the domain. Again if $r=0$ or, $D$ is very large, the solution of (\\\\ref{106}) tends to be uniformly distributed. The assumption is reasonable for uniform resources, which means the carrying capacity $\\\\mathcal{K}$ is not spatially dependent. In the case of nonuniform resource distribution, the model (\\\\ref{106}) suggests that the movement of the population to the areas with lower per capita available resources is contingent and biologically questionable. The idea of this type of diffusion in (\\\\ref{106}) was first considered in \\\\cite{EBL} motivated by choice of optimal harvesting strategies. It is also noted that other diffusion types, specifically nonlinear, were considered in population dynamics which is based on the experimental data \\\\cite{KAMT, JDM2, YWX}.\\n\\nFor further analysis, we have following assumptions on \\n$$f(x,t,u,r,\\\\mathcal{K})= r(x, t)u(x, t) \\\\ln \\\\left(\\\\displaystyle\\\\frac{ \\\\mathcal{K}(x, t)}{u(x, t)}\\\\right)= u\\\\cdot g(x,t,u,r,\\\\mathcal{K}),$$ \\nand $f(x,t,u,r,\\\\mathcal{K})$ satisfies:\\n\\\\begin{enumerate}[label=(h\\\\arabic*)]\\n\\t\\\\item\\\\label{h1} Function $f$ is uniformly H\\\\\"{o}lder continuous in $\\\\overline{\\\\Lambda}\\\\times J$ where $J$ is either a suitable sub-interval of $\\\\mathbb{R}$ or a sector between lower and upper solutions. Moreover, functions $f$ and $\\\\frac{\\\\displaystyle \\\\partial f}{\\\\displaystyle \\\\partial u}$ are $C^1(0, t)$, H\\\\\"{o}lder continuous in $\\\\overline{\\\\Omega}$ in the $x$ variable.\\n\\t\\n\\t\\\\item\\\\label{h2} $f(x,t,u,r,\\\\mathcal{K})=u. g(x,t,u,r,\\\\mathcal{K})$ where $g(x,t,\\\\cdot,r,\\\\mathcal{K})$ is monotonically decreasing in $\\\\mathbb{R}_+$ and $g(x,t,u,r,\\\\mathcal{K})<0$ when $u(x, t)> \\\\mathcal{K}(x, t)$ and $g(x,t,u,r,\\\\mathcal{K})>0$ when $0<g(x,t,u,r,\\\\mathcal{K})<\\\\mathcal{K}(x, t), \\\\; (x, t)\\\\in \\\\Lambda$.\\n\\t\\n\\t\\\\item\\\\label{h3} $g(x,t,\\\\cdot,r,K)\\\\in C^2(\\\\mathbb{R})$.\\n\\\\end{enumerate}\\t\\nWe can easily verify that the Gompertz growth function with positive bounded $r(x, t)$ follows the above \\\\ref{h1}-\\\\ref{h3} assumptions and we assume they hold always.\\n\\nIn our study, the main results are:\\n%\\\\begin{enumerate}[label=$\\\\blacktriangleright$]\\n\\\\begin{enumerate}\\n\\t\\\\item For Gompertz law with time and space variable functions, the behavior of population  is studied with or without diffusion. The existence and uniqueness of a periodic solution is presented;\\n\\t\\\\item For time-independent parameters, there is a positive stationary solution that attracts all positive solutions under certain conditions;\\n\\t\\\\item For periodic parameters, similar  solution patterns have been found;\\n\\t\\\\item The analytical explanation of the global stability of optimal harvesting policy is presented;\\n\\t\\\\item The results are generalized using multiple growth functions with harvesting; and\\n\\t\\\\item The theoretical results are verified in a series of numerical examples.\\n\\\\end{enumerate}\\nThe paper is organized as follows. In Section \\\\ref{ssec_2} we describe the growth and harvesting of the model in absence of diffusion for constant coefficients (in sub-section \\\\ref{subsec_1}) and then for periodic coefficients (sub-section \\\\ref{subsec_2}). Then we discuss in detail the Gompertz growth model with harvesting in Section \\\\ref{ssec_3}. In Section \\\\ref{ssec_4} we present the existence, uniqueness of solutions of the diffusive Gompertz growth model. We present the proof of the existence of periodic solutions in a bounded region. In Section \\\\ref{ssec_5}, the optimal harvesting policy is discussed. In Section \\\\ref{ssec_6} we generalized the results using multiple growth functions with harvesting. A series of examples are presented in Section \\\\ref{ssec_7} for applications. Finally, Section \\\\ref{ssec_8} concludes the summary and discussion of the results.\\n\\n\\n%===========New section====Dynamics in Absence of Diffusion====================================================\\n%=======================================================================================================\\n\\\\section{Dynamics of time periodicity}\\\\label{ssec_2}\\n\\n\\\\subsection{Dynamics for constant coefficients}\\\\label{subsec_1}\\n Clark (1976)  discussed about the optimal strategy for an autonomous single population which  follows the Verhulst (logistic) growth  \\\\cite{CW_1,CW_2}. When the model (\\\\ref{106}) is only time dependent, that is $u$ only depends on time $ t$, it becomes an ordinary differential equations. If diffusion is absent, that is $D\\\\rightarrow 0$ then the model becomes\\n\\\\begin{align}\\\\label{201}\\n\\\\begin{cases}\\n\\\\displaystyle\\\\frac{du}{d t}  \\n=r u( t) \\\\ln \\\\left(\\\\frac{\\\\mathcal{K}}{u( t)}\\\\right)-H u(t), \\\\; t>0\\\\\\\\\\nu(0)=u_0>0\\n\\\\end{cases}\\n\\\\end{align}\\nwhich describes the growth and harvesting of a population, $u$, where the distributive functions $r,\\\\;\\\\mathcal{K},\\\\;H$ all are considered as a constant. Here catch per unit effort is proportional to the population level is the harvesting hypothesis. To investigate the global asymptotic behavior and optimal harvesting policy we take $\\\\displaystyle\\\\frac{du}{d t}=0$ and get\\n$$\\nru\\\\ln\\\\left(\\\\displaystyle \\\\frac{\\\\mathcal{K}}{u}\\\\right)-H u=0\\n$$\\nwhich yields\\n\\\\begin{equation}\\\\label{eq1}\\nu=\\\\mathcal{K}\\\\exp \\\\left[  {- \\\\frac{\\\\displaystyle H}{\\\\displaystyle r}}\\\\right] \\n\\\\end{equation}\\n\\nSummarizing the steady states with the results \\\\eqref{eq1}, following behaviors can be found: \\n\\\\begin{enumerate}[label=$(\\\\roman*$)]\\n\\t\\\\item If $H<r,\\\\; u=\\\\mathcal{K} \\\\exp \\\\left[{- \\\\frac{\\\\displaystyle H}{\\\\displaystyle r}}\\\\right]>0$ is the globally asymptotically stable equilibrium.\\n\\t\\\\item If $H>r,$ then $u$ decreases gradually and when $ t\\\\rightarrow\\\\infty,$ then $u\\\\rightarrow0.$ \\n\\t\\\\item If $H=r$ then $u=\\\\displaystyle\\\\frac{\\\\mathcal{K}}{e}$ which is constant. These indicates that $H=r$ is a critical value and under harvesting exploitation this $H=r$ indicates the persistence or extinction of population. \\n\\t\\\\item When the condition is $H<r,$ the sustainable yield is $h=H u$. \\n\\t\\\\item Here the maximum yield is $h_{\\\\text{max}} =\\\\frac{\\\\displaystyle r \\\\mathcal{K}}{\\\\displaystyle e}$ \\n\\twhen $u^* =\\\\frac{\\\\displaystyle \\\\mathcal{K}}{\\\\displaystyle e}$ and $H^* =r$.\\n\\\\end{enumerate}\\n\\n%===========New section====For periodic coefficients====================================================\\n%======================================================================================================= \\n\\\\subsection{Dynamics for time-periodic coefficients}\\\\label{subsec_2}\\n %The logistic model with periodic coefficients is considered in \\\\cite{MFK}. \\n We consider the model (\\\\ref{201}) for periodic coefficients $r(t),\\\\mathcal{K}(t),H(t)$, which are strictly positive, smooth and \\\\textit{T-periodic} functions in  $(0,\\\\infty)$ \\\\cite{MFK}. Considering this model follows from (\\\\ref{201})\\n \\\\begin{align}\\\\label{202}\\n\\\\begin{cases}\\n\\\\frac{\\\\displaystyle d u}{\\\\displaystyle d t}  \\n=r( t)u( t) \\\\ln \\\\left(\\\\frac{\\\\displaystyle \\\\mathcal{K}( t)}{\\\\displaystyle u( t)}\\\\right) -H( t)u( t),\\\\; t\\\\in{(0, \\\\infty)}\\\\\\\\\\nu( t_0)=u_0>0\\n\\\\end{cases}\\n\\\\end{align}\\nHere $r( t),H( t)$ and $\\\\mathcal{K}( t)$ are $C^1(0, \\\\infty)$ functions. In this case the maximum harvesting yield is $\\\\mathcal{Y}_{\\\\text{max}} (H^*( t)) =\\\\displaystyle\\\\frac{1}{e} \\\\int_{0}^{1} r( t) \\\\mathcal{K}( t) d t$. The above models are simple ODEs and do not include spatial and\\ntemporal environmental effects. Therefore, model (\\\\ref{201}) is extended to a periodic environment in \\\\cite{MFK,HL_1}. A global asymptotic stable periodic solution is obtained and the harvesting policy is stablished. In real evolutionary processes, the density of population depends both on time and space. Considering this point, we get a unique model in the following sections.\\n\\n%===========New section====Classical diffusion with harvesting====================================================\\n%======================================================================================================= \\n\\\\section{Classical diffusion with harvesting}\\\\label{ssec_3}\\nWe consider a non-homogeneous classical diffusive model with Gompertz growth law, in heterogeneous environment. Therefore, we now recall the model (\\\\ref{106}). If we take $r(x, t)\\\\equiv r(x)$, $\\\\mathcal{K}(x, t)\\\\equiv \\\\mathcal{K}(x)$ and $H(x, t)\\\\equiv H(x)$, that is $r(x),\\\\;\\\\mathcal{K}(x),\\\\; H(x)$ are space-dependent with a non-negative initial function $u_0$ then the above model (\\\\ref{106}) redefined as \\n\\\\begin{align}\\\\label{302}\\n\\\\begin{cases}\\n\\\\displaystyle\\\\frac{\\\\partial u}{\\\\partial  t}  \\n=D \\\\Delta u + r(x) u(x, t) \\\\ln\\\\left(\\\\displaystyle\\\\frac{ \\\\mathcal{K}(x)}{u(x, t)}\\\\right) -H(x) u(x, t),\\\\; (x, t)\\\\in \\\\Lambda\\\\\\\\\\nu(x,0)=u_0(x)>0,\\\\;x\\\\in\\\\Omega\\\\\\\\\\n\\\\displaystyle\\\\frac{\\\\partial u}{\\\\partial \\\\eta}=0,\\\\;\\\\;\\\\;\\\\; (x, t)\\\\in\\\\partial \\\\Lambda\\n\\\\end{cases}\\n\\\\end{align}\\nwhere $u(x, t)$ is the population density of the resource population $u$, coefficients $H(x), \\\\; r(x)$ are at least H\\\\\"{o}lder continuous functions for $x\\\\in \\\\Omega$ and independent of time. From the composition theorem and using the upper and lower solution method we get $\\\\lim\\\\limits_{ t\\\\rightarrow\\\\infty} u(x, t;u_0) =u_e(x)$ and it is the equilibrium solution corresponding to \\n\\\\begin{align}\\\\label{303}\\n\\\\begin{cases}\\n-D \\\\Delta u_e=r(x)u_e \\\\ln \\\\left( \\\\frac{\\\\displaystyle \\\\mathcal{K}(x)}{\\\\displaystyle u_e}\\\\right) -H(x)u_e,\\\\;\\\\;\\\\;x\\\\in \\\\Omega\\\\\\\\\\n\\\\frac{\\\\displaystyle \\\\partial u_e}{\\\\displaystyle \\\\partial \\\\eta}=0;\\\\;\\\\;\\\\; x\\\\in\\\\partial\\\\Omega \\n\\\\end{cases}\\n\\\\end{align}\\nFrom the variational calculus method \\\\cite{enid}, here the optimal equilibrium population label is $u_e^*(x)= \\\\frac{\\\\displaystyle \\\\mathcal{K}(x)}{\\\\displaystyle e}$, the corresponding harvesting effort is $H^*(x)=\\\\displaystyle \\\\frac{D \\\\Delta \\\\mathcal{K}(x)}{\\\\mathcal{K}(x)}+r(x) $ and the maximum sustainable yield is $\\\\mathcal{Y}_{max}= \\\\frac{\\\\displaystyle 1}{\\\\displaystyle e}\\\\int_{\\\\Omega}r(x)\\\\mathcal{K}(x) dx$ \\\\cite{HLK}. This result is likewise to the specially homogeneous logistic equation considered in \\\\cite{CW_1,CW_2,MFK}.\\\\\\\\\\n\\n%Following now, consider the case that the population density $u(x, t)$ of this spatially non-homogeneous Gompertz model (\\\\ref{106}) tends to a strictly positive $\\\\mathcal{T}-periodic$ solution $u^*(x, t)$ for $(x,t)\\\\in\\\\Lambda$.\\n\\n\\n\\n%===========New section====Uniqueness and existence of a periodic solution====================================================\\n%======================================================================================================= \\n\\\\section{Uniqueness and existence of a periodic solution}\\\\label{ssec_4}\\nIn this section, we assume that\\n\\\\begin{enumerate}[label=j${\\\\arabic*}$:] %[label=(h\\\\arabic*)]\\n\\t\\\\item $\\\\mathcal{K}(x, t),\\\\; H(x, t)$ and $r(x, t)$ are H\\\\\"{o}lder continuous in $x$, continuously differentiable $\\\\mathcal{T}-periodic$ functions and strictly positive for any $(x, t)\\\\in \\\\overline{\\\\Lambda}$.\\n\\t\\n\\t\\\\item For a given function $\\\\psi(x, t,u,r,\\\\mathcal{K})$ we denote $\\\\psi_m$ and $\\\\psi_l$ be the maximum and minimum of $\\\\psi(x, t,u,r,\\\\mathcal{K})$ on $\\\\overline{\\\\Lambda}$.\\n\\\\end{enumerate}\\n\\n\\\\begin{Th}\\\\label{thor_1}\\n\\tAssume that $\\\\displaystyle \\\\frac{\\\\mathcal{K}_m}{\\\\mathcal{K}_l}>1$,  $H_m r_m-H_l r_l>0$. Then there exists $u^*(x, t)\\\\in \\\\left(\\\\mathcal{K}_l e^{-\\\\frac{H_m}{r_l}}, \\\\mathcal{K}_m e^{-\\\\frac{H_l}{r_m}}\\\\right)$  while $\\\\mathcal{K}_l e^{-\\\\frac{H_m}{r_l}} \\\\leq u_0(x)\\\\leq \\\\mathcal{K}_m e^{-\\\\frac{H_l}{r_m}}$  for $x\\\\in\\\\overline{\\\\Omega}$, the solution of (\\\\ref{106}) $u(x, t)\\\\rightarrow u^*(x, t)$ when $t\\\\rightarrow\\\\infty$.\\n\\\\end{Th}\\n\\n\\\\begin{proof}\\nConsider $u_m$ and $u_l$ as the solutions of \\\\ref{402}\\n\\\\begin{align}\\\\label{402}\\n\\\\begin{cases}\\nr_m\\\\ln\\\\left( \\\\frac{\\\\displaystyle \\\\mathcal{K}_m}{\\\\displaystyle u_m}\\\\right) -H_l=0\\\\\\\\\\nr_l\\\\ln\\\\left( \\\\frac{\\\\displaystyle \\\\mathcal{K}_l}{\\\\displaystyle u_l}\\\\right) -H_m=0 \\n\\\\end{cases}\\n\\\\end{align}\\nWe get a unique positive solution $u_m$ and $u_l$ if $\\\\frac{\\\\displaystyle H_m}{\\\\displaystyle r_l}<0$, which are $u_m=\\\\mathcal{K}_m e^{-\\\\frac{H_l}{r_m}}$ and $u_l=\\\\mathcal{K}_l e^{-\\\\frac{H_m}{r_l}}$.\\n\\nIt is obvious that $u_m>u_l$ and\\n\\\\begin{align}\\n\\\\begin{cases}\\n&\\\\frac{\\\\displaystyle \\\\partial u_m}{\\\\displaystyle \\\\partial  t} -D \\\\Delta u_m=0\\\\nonumber\\\\\\\\\\n&u_m \\\\left(r_m \\\\ln\\\\left( \\\\frac{\\\\displaystyle \\\\mathcal{K}_m}{\\\\displaystyle u_m}\\\\right) -H_l\\\\right)\\\\geq u_m \\\\left(\\\\ln\\\\left(\\\\frac{\\\\displaystyle \\\\mathcal{K}(x, t)}{\\\\displaystyle u}\\\\right)r(x, t) -H(x, t)\\\\right) \\\\nonumber\\\\\\\\\\n\\\\end{cases}\\n\\\\end{align}\\n\\\\begin{align}\\n\\\\begin{cases}\\n&\\\\frac{\\\\displaystyle \\\\partial u_l}{\\\\displaystyle \\\\partial  t} -D \\\\Delta u_l=0\\\\nonumber\\\\\\\\\\n&u_l \\\\left(r_l \\\\ln\\\\left(\\\\frac{\\\\displaystyle \\\\mathcal{K}_l}{\\\\displaystyle u_l}\\\\right) -H_m\\\\right)\\\\leq u_l\\\\left( \\\\ln\\\\left(\\\\frac{\\\\displaystyle \\\\mathcal{K}(x, t)}{\\\\displaystyle u}\\\\right)r(x, t) -H(x, t)\\\\right) \\\\nonumber\\n\\\\end{cases}\\n\\\\end{align}\\nThat is, $u_m$ and $u_l$ are the constant coupled upper and lower solutions of (\\\\ref{106}). Let, $p$ and $q$ are $\\\\mathcal{T}-periodic$ quasi-solutions and for  $\\\\overline{\\\\Omega} \\\\times[0,T]$ they satisfy $u_l\\\\leq q(x, t) \\\\leq p(x, t) \\\\leq u_m$. So\\n\\\\begin{align}\\\\label{403}\\n\\\\begin{cases}\\n\\\\frac{\\\\displaystyle \\\\partial p}{\\\\displaystyle \\\\partial t} -D \\\\Delta p =p \\\\left( \\\\ln\\\\left(\\\\frac{\\\\displaystyle \\\\mathcal{K}}{\\\\displaystyle p}\\\\right)r -H\\\\right),\\\\;(x, t)\\\\in \\\\Lambda\\\\\\\\\\n\\\\frac{\\\\displaystyle \\\\partial q}{\\\\displaystyle \\\\partial  t} -D \\\\Delta q =q \\\\left( \\\\ln\\\\left(\\\\frac{\\\\displaystyle \\\\mathcal{K}}{\\\\displaystyle q}\\\\right)r -H\\\\right),\\\\;(x, t)\\\\in \\\\Lambda\\\\\\\\\\n\\\\displaystyle\\\\frac{\\\\partial p}{\\\\partial\\\\eta} =\\\\displaystyle\\\\frac{\\\\partial q}{\\\\partial\\\\eta} =0,\\\\;\\\\;\\\\; (x, t)\\\\in \\\\partial\\\\Lambda\\n\\\\end{cases}\\n\\\\end{align}\\nNow subtracting the first two equations from (\\\\ref{403}), we can write\\n\\\\begin{align}\\n&(p-q) \\\\frac{\\\\displaystyle \\\\partial (p-q) }{\\\\displaystyle\\\\partial  t} \\\\nonumber\\\\\\\\\\n&=(p-q) D \\\\Delta (p-q) +(p-q) p\\\\left(r\\\\ln \\\\left( \\\\frac{\\\\displaystyle \\\\mathcal{K}}{\\\\displaystyle p}\\\\right) -H\\\\right) -(p-q) q\\\\left(r\\\\ln \\\\left( \\\\frac{\\\\displaystyle \\\\mathcal{K}}{\\\\displaystyle q}\\\\right) -H\\\\right)\\\\nonumber\\\\\\\\\\n&=(p-q) D \\\\Delta(p-q) +(p-q)^2 r\\\\ln\\\\left( \\\\displaystyle\\\\frac{q}{p}\\\\right)  -(p-q)^2H\\\\nonumber\\n\\\\end{align}\\nAs $p$ and $q$ are periodic functions,\\n\\\\begin{align}\\n0 &=\\\\int \\\\limits_{0}^{\\\\mathcal{T}} \\\\int \\\\limits_{\\\\Omega} (p-q) \\\\displaystyle\\\\frac{\\\\partial(p-q)}{\\\\partial t} dx d t\\\\nonumber\\\\\\\\\\n&\\\\leq -\\\\int \\\\limits_{0}^{\\\\mathcal{T}}\\\\int \\\\limits_{\\\\Omega} D |\\\\nabla((p-q)|^2 dx d t +\\\\int\\\\limits_{0}^{\\\\mathcal{T}}\\\\int \\\\limits_{\\\\Omega}(p-q)^2\\\\left(r\\\\ln\\\\displaystyle\\\\frac{q}{p}-H\\\\right) dxd t\\\\nonumber\\\\\\\\\\n&\\\\le -\\\\int \\\\limits_{0}^{\\\\mathcal{T}}\\\\int \\\\limits_{\\\\Omega} D |\\\\nabla(p-q)|^2 dx d t +r_m\\\\left(\\\\ln\\\\left(\\\\displaystyle\\\\frac{\\\\mathcal{K}_l}{\\\\mathcal{K}_m}\\\\right) -\\\\displaystyle\\\\frac{H_m}{r_l}\\\\right)\\\\int \\\\limits_{0}^{\\\\mathcal{T}}\\\\int\\\\limits_{\\\\Omega}(p-q)^2 dx d t\\\\nonumber\\\\\\\\\\n&\\\\leq 0\\\\nonumber\\n\\\\end{align}\\nNow from $\\\\left\\\\lbrace \\\\ln\\\\left( \\\\frac{\\\\displaystyle \\\\mathcal{K}_l}{\\\\displaystyle \\\\mathcal{K}_m}\\\\right) -\\\\frac{\\\\displaystyle H_m}{\\\\displaystyle r_l}\\\\right\\\\rbrace > \\\\frac{\\\\displaystyle H_l}{\\\\displaystyle r_m}$ and $\\\\frac{\\\\displaystyle \\\\mathcal{K}_l}{\\\\displaystyle \\\\mathcal{K}_m}>1$ we get $H_m r_m>H_l r_l$, for which it is obvious that $p=q\\\\equiv u^*$ for a unique $\\\\mathcal{T}-periodic$ solution $u^*$ in the interval $(u_l,\\\\; u_m)$ \\\\cite{ZY}. Therefore for any $u_0(x)\\\\in(\\\\hat{u},\\\\tilde{u})$ the solution of (\\\\ref{106}) satisfies $u(x, t)\\\\rightarrow u^*(x, t)$ as $t\\\\rightarrow\\\\infty$ and $x\\\\in\\\\overline{\\\\Omega}$.\\n\\\\end{proof}\\n\\n\\n%===========New section====Sustainable yield \\\\& optimal population mass====================================================\\n%=======================================================================================================\\n\\\\section{Sustainable yield with optimal policy}\\\\label{ssec_5}\\nAccording to Theorem \\\\ref{thor_1} in section \\\\ref{ssec_4}, under the exploitative condition, the persistence of population is ensured by the condition $\\\\displaystyle\\\\frac{\\\\mathcal{K}_m}{\\\\mathcal{K}_l}>1$ and $H_m r_m-H_l r_l>0$. Therefore for $ t\\\\rightarrow +\\\\infty$ and $u_0(x)>0,x\\\\in\\\\Omega$ we find $u^*(x, t;u_0)$, a unique global asymptotically positive periodic solution. In this section, using the technique of variational calculus \\\\cite{JS,gelfand} we are going to find out the optimal policy.\\\\\\\\\\nIn general, consider $p(x,y)$ be a function of two variables and the functional is\\n\\\\begin{align}\\\\label{501}\\n\\\\Psi [p(x,y)]=\\\\iint \\\\limits \\\\displaystyle\\\\mathcal{G}\\\\left(x,y,p,p_x,p_y,p_{xx},p_{xy},p_{yy}\\\\right) dx dy\\n\\\\end{align}\\nFor the functional $\\\\Psi[p]$, to attain a maximum on a specific solution, the necessary condition is\\n\\\\begin{align}\\\\label{502}\\n\\\\mathcal{G}_p+\\\\left(\\\\displaystyle\\\\frac{\\\\partial^2 \\\\mathcal{G}_{p_{xx}}}{\\\\partial x^2} +\\\\displaystyle\\\\frac{\\\\partial^2 \\\\mathcal{G}_{p_{xy}}}{\\\\partial x \\\\partial y} +\\\\displaystyle\\\\frac{\\\\partial^2 \\\\mathcal{G}_{p_{yy}}}{\\\\partial y^2}\\\\right)-\\\\left(\\\\displaystyle\\\\frac{\\\\partial \\\\mathcal{G}_{p_x}}{\\\\partial x} +\\\\displaystyle\\\\frac{\\\\partial \\\\mathcal{G}_{p_y}}{\\\\partial y}\\\\right)=0\\n\\\\end{align}\\nSimilarly for multivariate functions of two variables we get a functional\\n\\\\begin{align}\\\\label{503}\\n\\\\Psi[p(x,y),q(x,y)]=\\\\iint \\\\limits \\\\displaystyle \\\\mathcal{G}\\\\left(x,y,p,q,p_x,p_y,q_x,q_y,p_{xx},p_{xy},p_{yy},q_{xx},q_{xy},q_{yy}\\\\right)dx dy\\n\\\\end{align}\\nAnd the necessary conditions are \\n\\\\begin{align}\\\\label{504}\\n\\\\begin{cases}\\n\\\\mathcal{G}_p +\\\\left(\\\\frac{\\\\partial^2 \\\\mathcal{G}_{p_{xx}}}{\\\\partial x^2} +\\\\frac{\\\\partial^2 \\\\mathcal{G}_{p_{xy}}}{\\\\partial x\\\\partial y} +\\\\frac{\\\\partial^2 \\\\mathcal{G}_{p_{yy}}}{\\\\partial y^2}\\\\right) -\\\\left(\\\\frac{\\\\partial \\\\mathcal{G}_{p_x}}{\\\\partial x}+\\\\frac{\\\\partial \\\\mathcal{G}_{p_y}}{\\\\partial y}\\\\right)=0\\\\\\\\\\n\\\\mathcal{G}_q +\\\\left(\\\\frac{\\\\partial^2 \\\\mathcal{G}_{q_{xx}}}{\\\\partial x^2} +\\\\frac{\\\\partial^2 \\\\mathcal{G}_{q_{xy}}}{\\\\partial x\\\\partial y} +\\\\frac{\\\\partial^2 \\\\mathcal{G}_{q_{yy}}}{\\\\partial y^2}\\\\right) -\\\\left(\\\\frac{\\\\partial \\\\mathcal{G}_{q_x}}{\\\\partial x}+\\\\frac{\\\\partial \\\\mathcal{G}_{q_y}}{\\\\partial y}\\\\right)=0\\n\\\\end{cases}\\n\\\\end{align}\\nThe functional of three variables generalizes (\\\\ref{503}) and (\\\\ref{504}). Now the spatial case is to maximize the sustainable yield and the optimal $H$ and $p$ is $h=\\\\max\\\\limits_{p,H}\\\\int \\\\limits_{0}^{\\\\mathcal{T}}\\\\int \\\\limits_{\\\\Omega}\\\\displaystyle H(x, t)p(x, t)dxd t$.\\\\\\\\\\nIn addition, $H\\\\;\\\\text{and}\\\\;p$ satisfies \\n\\\\begin{align}\\\\label{510}\\n\\\\begin{cases}\\n\\\\displaystyle\\\\frac{\\\\partial p}{\\\\partial  t} =D \\\\Delta p +r(x, t)p(x,t) \\\\ln\\\\left(\\\\frac{\\\\displaystyle \\\\mathcal{K}(x, t)}{\\\\displaystyle p(x,t)}\\\\right)  -H(x, t)p(x,t),\\\\; (x, t) \\\\in \\\\Lambda \\\\\\\\\\n\\\\displaystyle\\\\frac{\\\\partial p}{\\\\partial \\\\eta} =0, \\\\;\\\\;\\\\; (x, t) \\\\in\\\\partial\\\\Lambda\\\\\\\\\\np(x, t) =p(x, t+\\\\mathcal{T}),\\\\;\\\\;\\\\; x\\\\in\\\\bar{\\\\Omega},\\\\;\\\\;\\\\\\\\\\nH(x, t)\\\\geq 0,\\\\; H(x, t) =H(x, t+\\\\mathcal{T}),\\\\;(x, t)\\\\in \\\\Lambda\\n\\\\end{cases}\\n\\\\end{align}\\nUsing the Lagrange multiplier method, we want to find out the optimal $p$ and $H$ and the objective functional\\n\\\\begin{align}\\n\\\\Psi \\\\left[p(x,y),H(x,y),\\\\lambda(x,y)\\\\right] =\\\\int\\\\limits_{0}^{\\\\mathcal{T}}\\\\int \\\\limits_{\\\\Omega} \\\\left \\\\lbrace H p +\\\\lambda \\\\left(\\\\frac{\\\\partial p}{\\\\partial t} -D \\\\Delta p -r p\\\\ln\\\\left(\\\\frac{\\\\mathcal{K}}{p}\\\\right) +H p\\\\right)\\\\right\\\\rbrace dxdy\\\\nonumber\\n\\\\end{align}\\nWe denote \\n\\\\begin{align}\\n\\\\displaystyle \\\\mathcal{G}\\\\left(x, t,H,\\\\lambda,p,p_ t,\\\\Delta p\\\\right) =H p +\\\\lambda\\\\left(\\\\frac{\\\\partial p}{\\\\partial  t} -D \\\\Delta p -r p\\\\ln\\\\left(\\\\frac{\\\\mathcal{K}}{p}\\\\right) +H p\\\\right) \\\\nonumber\\n\\\\end{align}\\nTo maximize the functional $\\\\Psi[p,H,\\\\lambda]$, necessary condition is\\n\\\\begin{align}\\\\label{505}\\n\\\\begin{cases}\\n\\\\frac{ \\\\partial \\\\mathcal{G}}{ \\\\partial H}=0\\\\\\\\\\n\\\\frac{ \\\\partial \\\\mathcal{G}}{ \\\\partial\\\\lambda}=0\\\\\\\\\\n\\\\frac{\\\\partial \\\\mathcal{G}}{\\\\partial p} -\\\\frac{\\\\partial \\\\mathcal{G}_{p_ t}}{\\\\partial  t} +\\\\sum \\\\limits_{i=1}^{3}\\\\frac{\\\\partial^2 \\\\mathcal{G}_{x_ix_i}}{\\\\partial x_i^2}=0,\\\\;\\\\;\\\\;\\\\;\\\\;\\\\\\\\\\n\\\\left. \\\\frac{\\\\partial p}{\\\\partial \\\\eta}\\\\right| _{\\\\partial\\\\Omega}=0\\n\\\\end{cases}\\n\\\\end{align}\\nhere $\\\\mathcal{G}_{x_ix_i}:=\\\\displaystyle\\\\frac{\\\\partial^2 \\\\mathcal{G}}{\\\\partial x_i^2},\\\\;\\\\; 1\\\\leq i\\\\leq3$. Now from (\\\\ref{505}) it is obvious that $\\\\lambda\\\\equiv -1$, as the first equation gives $p+\\\\lambda p=0$. Again, the third one implies\\n\\\\begin{align}\\\\label{506}\\nH+\\\\displaystyle\\\\frac{\\\\partial\\\\lambda}{\\\\partial  t} -D \\\\Delta\\\\lambda -r\\\\lambda\\\\ln\\\\displaystyle\\\\frac{\\\\mathcal{K}}{p}  +r\\\\lambda+ H\\\\lambda=0 \\n\\\\end{align}\\nIf $\\\\lambda=-1$, from (\\\\ref{506}) we obtain$u^*(x, t)=\\\\frac{\\\\displaystyle \\\\mathcal{K}(x, t)}{\\\\displaystyle e}$ and is the optimal population level. From the second equation of (\\\\ref{505}), we get\\n\\\\begin{align}\\\\label{507}\\n\\\\displaystyle\\\\frac{\\\\partial p}{\\\\partial t} -D \\\\Delta p -r p\\\\ln\\\\left( \\\\displaystyle\\\\frac{\\\\mathcal{K}}{p}\\\\right)  +H p=0\\n\\\\end{align}\\nWe know that $H^*(x, t) =r +\\\\frac{\\\\displaystyle D \\\\Delta \\\\mathcal{K}}{\\\\displaystyle \\\\mathcal{K}} -\\\\frac{\\\\displaystyle 1}{\\\\displaystyle \\\\mathcal{K}}\\\\frac{\\\\displaystyle\\\\partial \\\\mathcal{K}}{\\\\displaystyle\\\\partial  t}$ and the corresponding  maximal sustainable yield for unit time is\\n\\\\begin{align}\\n\\\\frac{1}{\\\\mathcal{T}}\\\\int\\\\limits_{0}^{\\\\mathcal{T}}\\\\int\\\\limits_{\\\\Omega} \\\\displaystyle H^*\\\\displaystyle u^* dxd t &=\\\\frac{1}{\\\\mathcal{T}}\\\\int \\\\limits_{0}^{\\\\mathcal{T}}\\\\int\\\\limits_{\\\\Omega} \\\\frac{\\\\mathcal{K}}{e}\\\\left(\\\\frac{D \\\\Delta \\\\mathcal{K}}{\\\\mathcal{K}} -\\\\frac{1}{\\\\mathcal{K}}\\\\frac{\\\\partial \\\\mathcal{K}}{\\\\partial  t}+r \\\\right)dxd t\\\\nonumber\\\\\\\\\\n&=\\\\frac{1}{\\\\mathcal{T}}\\\\int \\\\limits_{0}^{\\\\mathcal{T}}\\\\int\\\\limits_{\\\\Omega} \\\\left(\\\\frac{D \\\\Delta \\\\mathcal{K}}{e} -\\\\frac{1}{e}\\\\frac{\\\\partial \\\\mathcal{K}}{\\\\partial  t}+\\\\frac{r \\\\mathcal{K}}{e} \\\\right)dxd t\\\\nonumber\\\\\\\\\\n%&=\\\\frac{1}{\\\\mathcal{T}}\\\\int \\\\limits_{0}^{\\\\mathcal{T}}\\\\int \\\\limits_{\\\\Omega} \\\\left(\\\\frac{r \\\\mathcal{K}}{e} +\\\\frac{D }{e}\\\\Delta \\\\mathcal{K}\\\\right)dxd t -\\\\frac{1}{\\\\mathcal{T}}\\\\int \\\\limits_{0}^{\\\\mathcal{T}}\\\\int\\\\limits_{\\\\Omega} \\\\frac{1}{e}\\\\frac{\\\\partial \\\\mathcal{K}}{\\\\partial  t}dxd t\\\\nonumber\\\\\\\\\\n&=\\\\frac{1}{\\\\mathcal{T}}\\\\int \\\\limits_{0}^{\\\\mathcal{T}}\\\\int\\\\limits_{\\\\Omega} \\\\left(\\\\frac{1}{e}\\\\displaystyle r(x, t)\\\\displaystyle \\\\mathcal{K}(x, t) +\\\\frac{D }{e}\\\\Delta \\\\mathcal{K}\\\\right)dxd t\\\\nonumber\\n\\\\end{align} \\nAs $\\\\mathcal{K}(x, t)$ is periodic, we find the last equality valid. Above discussion leads to following Theorem \\\\ref{thor_2}.\\n\\n\\\\begin{Th}\\\\label{thor_2}\\nSuppose $u_l\\\\leq\\\\frac{ \\\\mathcal{K}(x, t)}{e}\\\\leq u_m$ and we denote $\\\\displaystyle H^*(x, t):=D \\\\frac{\\\\Delta \\\\mathcal{K}}{\\\\mathcal{K}} -\\\\frac{1}{\\\\mathcal{K}}\\\\frac{\\\\partial \\\\mathcal{K}}{\\\\partial  t}+r\\\\geq 0$. %for $\\\\left(x, t\\\\right)\\\\in \\\\overline{\\\\Lambda}$ %,\\\\; \\\\left(x, t\\\\right)\\\\in\\\\overline{\\\\Lambda}\\nThen the optimal sustainable yield is\\n\\t\\\\begin{equation}\\n\\t\\\\Phi_{\\\\text{max}}=\\\\max\\\\limits_{u,H}\\\\int \\\\limits_{0}^{\\\\mathcal{T}}\\\\int \\\\limits_{\\\\Omega}\\\\displaystyle H(x, t)\\\\displaystyle u(x, t)dxd t, \\\\; (x, t)\\\\in\\\\Lambda\\\\nonumber\\n\\t\\\\end{equation}\\nHere boundary condition (\\\\ref{106}) and  a differential equation constraint  are satisfied, and we find the optimal harvesting effort \\n\\t\\\\begin{equation}\\n\\tH^*(x, t)=r(x,t)+D\\\\displaystyle\\\\frac{ \\\\Delta \\\\mathcal{K}(x,t)}{\\\\mathcal{K}(x,t)} -\\\\displaystyle\\\\frac{1}{\\\\mathcal{K}(x,t)}\\\\displaystyle\\\\frac{\\\\partial \\\\mathcal{K}(x,t)}{\\\\partial t}\\\\nonumber\\n\\t\\\\end{equation}\\nTherefore the optimal average sustainable yield in a periodic time is\\n\\t\\\\begin{equation} \\n\\t\\\\displaystyle\\\\frac{1}{\\\\mathcal{T}}\\\\int\\\\limits_{0}^{\\\\mathcal{T}}\\\\int\\\\limits_{\\\\Omega} t^*(x, t)u^*(x, t)dx d t =\\\\displaystyle\\\\frac{1}{\\\\mathcal{T}}\\\\int\\\\limits_{0}^{\\\\mathcal{T}}\\\\int\\\\limits_{\\\\Omega}\\\\left(\\\\displaystyle\\\\frac{r(x, t)\\\\mathcal{K}(x, t)}{e} +\\\\displaystyle\\\\frac{D }{e}\\\\Delta \\\\mathcal{K}\\\\right)dxd t\\\\nonumber\\n\\t\\\\end{equation}\\n\\\\end{Th}\\n\\n\\n%===========New section====A generalized form====================================================\\n%=======================================================================================================\\n\\\\section{Classical diffusion with generalized growth function}\\\\label{ssec_6}\\nIn this section our goal is to discuss the problem (\\\\ref{106}) in a more generalized form. Let $\\\\phi(x, t,u)$ is restrictive density function,\\n\\\\begin{align}\\\\label{601}\\n\\\\begin{cases}\\n\\\\displaystyle\\\\frac{\\\\partial u}{\\\\partial  t}  =D \\\\Delta u +ru \\\\phi(x, t,u) -Hu \\\\\\\\\\nu(x,0)=u_0(x),\\\\; x\\\\in\\\\Omega\\\\\\\\\\n\\\\displaystyle\\\\frac{\\\\partial u}{\\\\partial \\\\eta}=0,\\\\; (x, t)\\\\in\\\\partial\\\\Lambda\\n\\\\end{cases}\\n\\\\end{align}\\nThis function $\\\\phi(x, t,u)$ satisfies\\n\\\\begin{enumerate}[label=(s$\\\\arabic*$)]\\n\\t\\\\item\\\\label{H1} Monotonically decreasing continuous function in $ (x, t)\\\\in\\\\overline{\\\\Lambda}$. \\n\\t\\\\item\\\\label{H2} There exists $\\\\mathcal{K}>0$, and for $0<u<\\\\mathcal{K}$ it implies $\\\\phi(x, t,\\\\mathcal{K})=0$; for $u>\\\\mathcal{K},\\\\;\\\\phi(x, t,u)<0$ and  $\\\\phi(x, t,0)=1$.\\n\\t\\\\item\\\\label{H3} $\\\\phi(x, t,u)$ is a H\\\\\"older continuous and $\\\\mathcal{T}-periodic$ function and in some closed interval of $R$ Lipschitz continuous in $u$. There exists $l>0$ such that\\n\\t\\\\begin{align}\\\\label{602}\\n\\t|\\\\phi(\\\\cdot,\\\\cdot,u)-\\\\phi(\\\\cdot,\\\\cdot,v)|\\\\leq l|u-v|\\n\\t\\\\end{align}\\n\\\\end{enumerate}\\t\\nfor all $(x, t)\\\\in\\\\Lambda$ and $u,v\\\\in[L,M]$. We consider \\\\ref{H1}-\\\\ref{H3} are hold. We are going to use a similar method as in Theorem \\\\ref{thor_1} to prove that (\\\\ref{601}) has a unique $\\\\mathcal{T}-periodic$ solution.\\n\\n\\n\\\\begin{Th}\\\\label{thor_3}\\nSuppose $-r_m\\\\ln\\\\left(l\\\\theta \\\\right)<H_l<H_m<r_l$, $l$ is Lipschitz constant that satisfies (\\\\ref{602}), in the interval $(\\\\theta,\\\\omega)$ there exists a unique periodic solution $u^*(x, t)$ . Again for $\\\\theta\\\\leq u_0(x)\\\\leq \\\\omega$ solution of (\\\\ref{601}) satisfies $u(x, t)\\\\rightarrow u^*(x, t)$ when $t\\\\rightarrow\\\\infty$ and $x\\\\in\\\\overline{\\\\Omega}$.\\n\\\\end{Th}\\n\\n\\\\begin{proof}\\n\\tWe assume $\\\\overline{\\\\phi}(u)=\\\\max\\\\limits_{x, t}\\\\phi(x, t,u)$ and $\\\\underline \\\\phi(u)=\\\\min\\\\limits_{x, t}\\\\phi(x, t,u)$ and the constants $\\\\theta$ and $\\\\omega$ satisfy algebraic equations\\n\\t\\\\begin{align}\\n\\t\\\\begin{cases}\\n\\tr_m\\\\overline{\\\\phi}(\\\\omega)-H_l=0\\\\nonumber\\\\\\\\\\n\\tr_l\\\\underline{\\\\phi}(\\\\theta)-H_m=0\\\\nonumber\\n\\t\\\\end{cases}\\n\\t\\\\end{align}\\n\\tor,\\n\\t\\\\begin{align}\\\\label{603}\\n\\t\\\\displaystyle\\\\frac{H_l}{r_m}=\\\\overline{\\\\phi}(\\\\omega),\\\\;\\\\;\\\\;\\\\frac{H_m}{r_l}=\\\\underline{\\\\phi}(\\\\theta)\\n\\t\\\\end{align}\\n\\tIt is easy to see\\n\\t\\\\begin{align}\\n\\t0<\\\\overline{\\\\phi}(\\\\omega)=\\\\displaystyle\\\\frac{H_l}{r_m}\\\\leq\\\\displaystyle\\\\frac{H_m}{r_l}=\\\\underline{\\\\phi}(\\\\theta)<1\\\\nonumber\\n\\t\\\\end{align}\\n\\tFrom assumption \\\\ref{H1} and \\\\ref{H2}, $0<\\\\theta\\\\leq\\\\omega<\\\\mathcal{K}$ and we know that $\\\\theta$ and $\\\\omega$ are unique. Moreover\\n\\t\\\\begin{align}\\\\label{604}\\n    \\\\displaystyle\\\\frac{\\\\partial\\\\omega}{\\\\partial  t} -D \\\\Delta\\\\omega=0 =\\\\omega\\\\left(r_m \\\\overline{\\\\phi}(\\\\omega) -H_l\\\\right)\\\\geq\\\\omega\\\\left(r \\\\phi(x, t,\\\\omega) -H\\\\right)\\\\nonumber\\\\\\\\\\n    \\\\displaystyle\\\\frac{\\\\partial\\\\theta}{\\\\partial  t} -D \\\\Delta\\\\theta=0 =\\\\theta\\\\left(r_l\\\\underline{\\\\phi}(\\\\theta)-H_m\\\\right)\\\\leq\\\\theta\\\\left(r \\\\phi(x, t,\\\\theta) -H\\\\right).\\\\nonumber\\n\\t\\\\end{align}\\n\\tAnd this implies, $\\\\theta$ and $\\\\omega$ are the constant coupled upper and lower solutions of (\\\\ref{601}) respectively. Now there exists $\\\\mathcal{T}-periodic$ quasi-solutions $p$ and $q$ \\\\cite{ZY} and they satisfy\\n\\t\\\\begin{equation}\\\\label{605}\\n\\t\\\\theta\\\\leq q(x, t)\\\\leq p(x, t)\\\\leq \\\\omega,\\\\;\\\\;\\\\; \\\\overline{\\\\Omega}\\\\times\\\\left[0,\\\\mathcal{T}\\\\right] \\\\nonumber \\n\\t\\\\end{equation}\\n\\t\\\\begin{align}\\\\label{606}\\n\\t\\\\begin{cases}\\n\\t\\\\displaystyle\\\\frac{\\\\partial p}{\\\\partial  t} -D \\\\Delta p =p \\\\left(r \\\\phi(x, t,p) -\\\\displaystyle H\\\\right),\\\\; (x,t) \\\\in \\\\Lambda \\\\\\\\\\n\\t\\\\displaystyle\\\\frac{\\\\partial q}{\\\\partial  t} -D \\\\Delta q =q \\\\left(r \\\\phi(x, t,q) -H\\\\right),\\\\;(x,t) \\\\in \\\\Lambda\\\\\\\\\\n\\t\\\\displaystyle\\\\frac{\\\\partial p}{\\\\partial \\\\eta}=\\\\displaystyle\\\\frac{\\\\partial q}{\\\\partial \\\\eta}=0,\\\\;(x,t) \\\\in \\\\partial \\\\Lambda\\n\\t\\\\end{cases}\\n\\t\\\\end{align}\\n\\tFrom (\\\\ref{606}) and the periodicity of $p$ and $q$, we have \\n\\t\\\\begin{align}\\n\\t\\\\left(p-q \\\\right)\\\\displaystyle\\\\frac{\\\\partial}{\\\\partial  t}\\\\left(p-q \\\\right) &=\\\\left(p - q\\\\right)D \\\\Delta\\\\left(p-q\\\\right) +\\\\left(p-q\\\\right)p\\\\left(r \\\\phi(x, t,p)-H\\\\right) -\\\\left(p-q\\\\right)q\\\\left(r \\\\phi(x, t,q)-H\\\\right) \\\\nonumber\\\\\\\\\\n\\t&=\\\\left(p-q\\\\right)D \\\\Delta\\\\left(p-q\\\\right) -H\\\\left(p-q\\\\right)^2 +r\\\\left(p-q\\\\right)\\\\left[p\\\\phi(x, t,p) -q\\\\phi(x, t,q)\\\\right]\\\\nonumber\\n\\t\\\\end{align}\\n\\tWe find $\\\\phi(x, t,u)$ is a decreasing function on $u$ from \\\\ref{H1} and \\\\ref{H2}. Again $0<\\\\phi(x, t,p)<1,$ then $\\\\phi(x, t,p) -\\\\phi(x, t,q) \\\\leq -\\\\left(p-q\\\\right)\\\\ln l$. As $p$ and $q$ are periodic, we have\\n\\t\\\\begin{align}\\n\\t0 &=\\\\int \\\\limits_{0}^{\\\\mathcal{T}}\\\\int\\\\limits_{\\\\Omega}\\\\left(p-q\\\\right)\\\\frac{\\\\partial}{\\\\partial  t}\\\\left(p-q\\\\right)dxd t\\\\nonumber\\\\\\\\\\n\\t& \\\\leq -\\\\int\\\\limits_{0}^{\\\\mathcal{T}}\\\\int\\\\limits_{\\\\Omega}D |\\\\Delta\\\\left(p-q\\\\right)|^2 dxdt -\\\\int\\\\limits_{0}^{\\\\mathcal{T}}\\\\int\\\\limits_{\\\\Omega}H_l\\\\left(p-q\\\\right)^2dxd t \\\\nonumber\\\\\\\\ &\\\\;\\\\;\\\\;+\\\\int\\\\limits_{0}^{\\\\mathcal{T}}\\\\int\\\\limits_{\\\\Omega}r_m\\\\left(p-q\\\\right)\\\\left[p\\\\phi(x, t,p) -q \\\\phi(x, t,q) +p \\\\phi(x, t,p)-q\\\\phi(x, t,q)\\\\right]dxdt \\\\nonumber\\\\\\\\\\n\\t&\\\\leq-\\\\int\\\\limits_{0}^{\\\\mathcal{T}}\\\\int\\\\limits_{\\\\Omega}D |\\\\Delta\\\\left(p-q\\\\right)|^2 dxdt -\\\\int\\\\limits_{0}^{\\\\mathcal{T}}\\\\int\\\\limits_{\\\\Omega}H_l\\\\left(p-q\\\\right)^2 dxd t \\\\nonumber\\\\\\\\\\n\\t&\\\\;\\\\;\\\\;+\\\\int\\\\limits_{0}^{\\\\mathcal{T}}\\\\int\\\\limits_{\\\\Omega}r_M\\\\left(p-q\\\\right) \\\\left[\\\\left(p-q\\\\right)\\\\cdot 0 -\\\\left(p-q\\\\right)\\\\ln\\\\left(l\\\\theta\\\\right)\\\\right]dxd t \\\\nonumber\\\\\\\\\\n\\t&\\\\leq -\\\\int\\\\limits_{0}^{\\\\mathcal{T}}\\\\int\\\\limits_{\\\\Omega}D |\\\\Delta\\\\left(p-q\\\\right)|^2dxd t -\\\\int\\\\limits_{0}^{\\\\mathcal{T}}\\\\int\\\\limits_{\\\\Omega}\\\\left[H_l +r_m\\\\ln\\\\left(l\\\\theta\\\\right)\\\\right] \\\\left(p-q\\\\right)^2dxd t\\\\nonumber\\\\\\\\\\n\\t&\\\\leq 0\\\\nonumber\\n\\t\\\\end{align}\\n\\tIt follows from $H_l+r_m\\\\ln\\\\left(l\\\\theta\\\\right)>0$ that $p=q\\\\equiv u^*$. Hence, according to theorem there is a unique $\\\\mathcal{T}-periodic$ solution $u^*$ in the interval $\\\\left(\\\\theta,\\\\omega\\\\right)$ the correspondent solution $u(x, t)$ of (\\\\ref{601}) satisfies\\n\\t\\\\begin{equation}\\n\\tu(x, t)\\\\rightarrow u^*(x, t)\\\\;\\\\text{as}\\\\;  t\\\\rightarrow\\\\infty\\\\;\\\\text{for}\\\\;x\\\\in\\\\overline{\\\\Omega}\\\\nonumber\\n\\t\\\\end{equation}\\n\\\\end{proof}\\n\\n\\n\\\\begin{Th}\\\\label{thor_4}\\nSuppose we find a unique positive periodic solution $u^*(x, t)$ to the equation\\n\\\\begin{equation}\\n\\\\phi(x, t,u)+u\\\\frac{\\\\partial \\\\phi}{\\\\partial u}=0,\\\\; \\\\left(x, t\\\\right)\\\\in\\\\overline{\\\\Lambda}\\\\nonumber\\n\\\\end{equation}\\nFrom the first equation of (\\\\ref{601}) we denote\\n\\\\begin{equation}\\nH^*(x, t)=D \\\\frac{\\\\Delta u^*}{u^*} +r \\\\phi(x, t,u^*) -\\\\frac{1}{u^*}\\\\frac{\\\\partial u^*}{\\\\partial  t}\\\\geq 0\\\\nonumber\\n\\\\end{equation}\\nthen the problem of optimal sustainable yield  is\\n\\\\begin{equation}\\n\\\\max\\\\limits_{u,H}\\\\int \\\\limits_{0}^{\\\\mathcal{T}}\\\\int\\\\limits_{\\\\Omega}u(x, t)H(x, t)dxdt, \\\\;\\\\;\\\\; (x, t)\\\\in \\\\Lambda \\\\nonumber\\n\\\\end{equation}\\nthat satisfies the differential equation constrain condition similar to (\\\\ref{510}) and boundary  of (\\\\ref{601}). Hence, the optimal average sustainable yield is \\n\\\\begin{equation}\\n\\\\displaystyle\\\\frac{1}{\\\\mathcal{T}}\\\\int\\\\limits_{0}^{\\\\mathcal{T}}\\\\int\\\\limits_{\\\\Omega} u^*(x, t) H^*(x, t)dxdt =\\\\displaystyle\\\\frac{1}{\\\\mathcal{T}}\\\\int\\\\limits_{0}^{\\\\mathcal{T}}\\\\int\\\\limits_{\\\\Omega}\\\\left(r(x, t)u^* \\\\phi(x, t,u^*) +D \\\\Delta u^*\\\\right)dxd t\\\\nonumber\\n\\\\end{equation}\\n\\\\end{Th}\\nThe proof is similar to that of Theorem \\\\ref{thor_2}, so it is omitted here.\\n\\n\\n%===========New section====Examples and Applications====================================================\\n%=======================================================================================================\\n\\\\section{Numerical Simulation}\\\\label{ssec_7}\\nThis section aims to present the numerical simulations\\' results that complement the previous sections\\' theoretical results. In the following series of examples, we observe the behavior by diffusion coefficient $D $, intrinsic growth rate $r$, harvesting rate $H$, and carrying capacity $\\\\mathcal{K}$ of the model (\\\\ref{106}). \\nFirst, let us consider the case of without harvesting, that is $H=0$. \\n\\\\begin{Ex}\\\\label{ex_1}\\n We consider \\\\eqref{106} on $\\\\Omega\\\\equiv x = (0,1)$ with diffusion coefficient $D =1.0$, harvesting $H=0.0$, carrying capacity $\\\\mathcal{K}(x,t)=2.5+\\\\cos(\\\\pi x) \\\\sin(\\\\pi t)$ and different intrinsic growth rates $r=1.2,\\\\; 1.2+\\\\cos(\\\\pi x),\\\\; 1.2+\\\\cos(\\\\pi x)\\\\sin(\\\\pi t)$. \\n  \\t\\\\begin{figure}[h]\\n  \\t\\t\\\\centering\\n  \\t\\t\\\\includegraphics[width=0.3 \\\\linewidth]{figg_ex1_1.eps}~~\\n  \\t\\t\\\\includegraphics[width=0.3 \\\\linewidth]{figg_ex1_2.eps}~~\\n  \\t\\t\\\\includegraphics[width=0.3 \\\\linewidth]{figg_ex1_3.eps}\\n  \\t\\t\\\\caption{Solution of \\\\eqref{106} for $H=0.0$, $\\\\mathcal{K}(x, t)=2.5+\\\\cos(\\\\pi x) \\\\sin(\\\\pi t)$, $D=1,\\\\; u_0=\\\\{0.1,\\\\;1.1,\\\\; 2.0+ \\\\sin(\\\\pi x)\\\\}$, (left) $r=1.2$, (middle) $r(x)=1.2+\\\\cos(\\\\pi x)$ and (right) $r(x, t)=1.2+\\\\cos(\\\\pi x)\\\\sin(\\\\pi t)$.}  \\n  \\t\\t\\\\label{figg1}\\n  \\t\\\\end{figure}\\n The numerical simulation in Fig. \\\\ref{figg1} shows that in the absence of harvesting, we get a unique positive periodic solution whatever the initial density point is. Moreover, the result shows similar behavior in two dimensions (Fig. \\\\ref{figg2}).\\n  \\\\begin{figure}[h]\\n  \\t\\\\centering\\n  \\t\\\\includegraphics[width=0.3 \\\\linewidth]{ex1_3D_1.eps}~~\\n  \\t\\\\includegraphics[width=0.3 \\\\linewidth]{ex1_3D_2.eps}~~\\n  \\t\\\\includegraphics[width=0.3 \\\\linewidth]{ex1_3D_3.eps}\\n   \\t\\\\caption{Solution of \\\\eqref{106} for $H=0.0$,  $\\\\mathcal{K}(x, t)=2.5+\\\\cos(\\\\pi x) \\\\sin(\\\\pi t)$, $D =1.0$, $u_0=2.0+ \\\\sin(\\\\pi x)$ for $r=1.2$ (left), $r(x)=1.2+\\\\cos(\\\\pi x)$ (middle) and  $r(x, t)=1.2+\\\\cos(\\\\pi x)\\\\sin(\\\\pi t)$ (right).}  \\n  \\t\\\\label{figg2}\\n  \\\\end{figure}\\nLet us compare the uniqueness for various initial conditions and different growth rates. The existence and uniqueness of the solution of \\\\eqref{106} are valid as designed in Fig. \\\\ref{figg1} and Fig. \\\\ref{figg2}. These figures justified the result of Theorem \\\\ref{thor_1}.\\n\\\\end{Ex}\\n\\\\begin{Ex}\\\\label{ex_2}\\nConsider \\\\eqref{106} on $\\\\Omega = (0,1)$ with diffusion coefficient $D =1.0$ and $H=0.0$,  time variable carrying capacity $\\\\mathcal{K}(x,t)=2.5+\\\\cos(\\\\pi x) \\\\sin(\\\\pi t)$ and initial population $u_0(x)=2.0+ \\\\sin(\\\\pi x)$. \\nFor time-periodic carrying capacity and  for various growth functions, the numerical simulation shows a positive unique solution. The equilibrium depends on the change of intrinsic growth rates $r=1.2,\\\\; 1.2+\\\\cos(\\\\pi x),\\\\; 1.2+\\\\cos(\\\\pi x)\\\\sin(\\\\pi t)$ which is shown in left figure of Fig. \\\\ref{figg3}. Also in right figure of Fig. \\\\ref{figg3} explains the uniqueness of the positive solution despite of different initial mass.\\n\\t  \\\\begin{figure}[h]\\n\\t\\t\\\\centering\\n\\t\\t\\\\includegraphics[width=0.4 \\\\linewidth]{figg_ex2_1.png}~~~\\n\\t\\t\\\\includegraphics[width=0.4 \\\\linewidth]{figg_ex2_2.eps}\\t\\t\\n\\t\\t\\\\caption{Solution of \\\\eqref{106} for $H=0.0$, $\\\\mathcal{K}(x,t)=2.5+\\\\cos(\\\\pi x) \\\\sin(\\\\pi t)$, $D =1.0$ in $\\\\Omega=(0,1)$. $u_0=2.0+\\\\sin(\\\\pi x)$ and $r=\\\\{1.2, 1.2+\\\\cos(\\\\pi x), 1.2+\\\\cos(\\\\pi x)\\\\sin(\\\\pi t)\\\\}$ (left); $r=1.2+\\\\cos(\\\\pi x)\\\\sin(\\\\pi t)$ and $u_0=\\\\{0.1,\\\\;1.1,\\\\; 2.0+ \\\\sin(\\\\pi x)\\\\}$ (right).}  \\n\\t\\t\\\\label{figg3}\\n\\t\\\\end{figure}\\n\\\\end{Ex}\\nIn both cases (Case \\\\ref{ex_1} and Case \\\\ref{ex_2}), Theorem \\\\ref{thor_1} is verified for random time-periodic carrying capacity functions $\\\\mathcal{K}(x, t)$. In the next example we outline the influence of the diffusion coefficients $D$ on the equilibrium level.\\n\\\\begin{Ex}\\\\label{ex_3}\\nConsider model \\\\eqref{106} with time variable carrying capacity $\\\\mathcal{K}(x,t)=2.5+\\\\cos(\\\\pi x) \\\\sin(\\\\pi t)$ and intrinsic growth rate $r(x,t)=1.2+\\\\cos(\\\\pi x)\\\\sin(\\\\pi t)$. Also consider $H=0$,  initial population density $u_0=1.1$ for $\\\\Omega = (0,1)$. \\nNumerically, it shows that the value of $u(x, t)$ converges to the time periodic positive solution when $ t\\\\rightarrow\\\\infty$. The more we increase the diffusion strategy, that is, increasing of $D $, the more we converge to the limit state for the same initial density and $ t>0$. See the illustration of Fig. \\\\ref{figg4}. \\n\\t\\\\begin{figure}[h]\\n\\t\\t\\\\centering\\n\\t\\t\\\\includegraphics[width=0.3 \\\\linewidth]{figg_ex3_1.eps}~~\\n\\t\\t\\\\includegraphics[width=0.3 \\\\linewidth]{figg_ex3_12.eps}~~\\n\\t\\t\\\\includegraphics[width=0.3 \\\\linewidth]{figg_ex3_13.eps}\\n\\t\\t\\\\caption{Solution of \\\\eqref{106} for $\\\\mathcal{K}(x,t)=2.5+\\\\cos(\\\\pi x)\\\\sin(\\\\pi t)$, $u_0=1.1$ and $r(x,t)=1.2+\\\\cos(\\\\pi x)\\\\sin(\\\\pi t)$ in $\\\\Omega=(0,1)$. Here $D =\\\\{0.5,1.5,2.0\\\\}$ for time $ t=40$ in left; time $ t=400$ in middle and $D =\\\\{0.5,1.5,2.5\\\\}$ for time $ t=300$ in right.}  \\n\\t\\t\\\\label{figg4}\\n\\t\\\\end{figure}\\nThere is a similar illustration in Fig. \\\\ref{figg5} for a two-dimensional scenario.\\n\\\\begin{figure}[h]\\n\\t\\\\centering\\n\\t\\\\includegraphics[width=0.3 \\\\linewidth]{3D_31.eps}~~\\n\\t\\\\includegraphics[width=0.3 \\\\linewidth]{3D_32.eps}~~\\n\\t\\\\includegraphics[width=0.3 \\\\linewidth]{3D_33.eps}\\n\\t\\\\caption{Solution of \\\\eqref{106} for $\\\\mathcal{K}(x,t)=2.5+\\\\cos(\\\\pi x)\\\\sin(\\\\pi t)$, $u_0=1.0+\\\\sin(\\\\pi x)$ and $r=1.2+\\\\cos(\\\\pi x)\\\\sin(\\\\pi t)$ in $\\\\Omega=(0,1)$ and $t=(0,50)$. $D=2.5$ (left); time $D=1.5$ (middle); $D=0.5$ (right).}  \\n\\t\\\\label{figg5}\\n\\\\end{figure}\\nFinally, if we consider $\\\\mathcal{K}(x)$, carrying capacity only dependent on the environment, then we get a unique positive solution as shown in Fig. \\\\ref{figg6}. \\n\\\\begin{figure}[ht]\\n\\t\\\\centering\\n\\t\\\\includegraphics[width=0.33 \\\\linewidth]{figg_ex3_4.eps}~~\\n\\t\\\\includegraphics[width=0.33 \\\\linewidth]{figg_ex3_5.eps}\\n\\t\\\\caption{Solution of  \\\\eqref{106} for $\\\\mathcal{K}(x)=2.5+\\\\cos(\\\\pi x)$, $u_0=1.1$ and $r=1.2+\\\\cos(\\\\pi x)$. $D =0.5$ for time $ t=50$  in $\\\\Omega=(0,1)$ (left); $u_0=\\\\{0.1,1.1,2.0+\\\\sin(\\\\pi x)\\\\}$  (right).}  \\n\\t\\\\label{figg6}\\n\\\\end{figure}\\n\\\\end{Ex}\\nNow we consider the case with harvesting in \\\\eqref{106}. Here first explore the behavior in the absence of diffusion.\\n\\\\begin{Ex}\\\\label{ex_4}\\n\\tLet us consider model \\\\eqref{106} in absence of diffusion, which is equivalent to \\\\eqref{201} over the domain $\\\\Omega=(0,1)$. Since the diffusion is absent, so for $D =0$ and the constant coefficients $\\\\mathcal{K},H,r$ are constant. \\n\\tWe verify the results of subsection \\\\ref{subsec_1}. First we choose different values of harvesting rate $H=\\\\{0.5,\\\\;1.2,\\\\;1.5\\\\}$ with growth rate $r=1.2$ and carrying capacity $\\\\mathcal{K}=2$. This shows that the results found in subsection \\\\ref{subsec_1} is justified.\\n   \\t\\\\begin{figure}[h]\\n \\t\\\\centering\\n \\t\\\\includegraphics[width=0.33 \\\\linewidth]{figg_ex4_1.eps}~~\\n \\t\\\\includegraphics[width=0.33 \\\\linewidth]{figg_ex4_2.eps} \\n \\t\\\\caption{Solution of  \\\\eqref{106} for $D =0.0$, $\\\\mathcal{K}=2.0, \\\\; r=1.2 $, time $ t=10$  in $\\\\Omega=(0,1)$. $u_0=0.2 \\\\; \\\\textit{and} \\\\; H=\\\\{0.75,\\\\;1.2,\\\\;1.5\\\\}$  (left); $H =0.75 \\\\; \\\\textit{and} \\\\; u_0=\\\\{0.5, \\\\; 1.1, \\\\; 1.5\\\\}$ (right).} \\n \\t\\\\label{figg7}\\n \\\\end{figure}\\n We also check for different initial values with a fixed harvesting rate, where the results are justified. See Fig. \\\\ref{figg7}.\\n \\\\end{Ex}\\n%\\n\\\\begin{Ex}\\\\label{ex_5}\\nConsider model \\\\eqref{202} over $\\\\Omega=(0,1)$ and for $D =0.0$. The coefficients $\\\\mathcal{K}( t),H( t),r( t)$ are all time dependent, that is functions of time $ t$. \\nFor growth rates $r(t)=1.3+ \\\\cos  t$, carrying capacity $\\\\mathcal{K}(t)=2.1+ \\\\cos  t$ and different values of harvesting rates ($H=\\\\{1.1+\\\\cos t, \\\\;1.3+\\\\cos t,\\\\;1.5+\\\\cos t\\\\}$ in Fig. \\\\ref{figg8} (left)) and initial densities ($u_0=\\\\{0.3, \\\\; 1.1, \\\\; 1.7\\\\}$ with $H =1.2 + \\\\cos  t$ in Fig. \\\\ref{figg8} (right)), we observe the solution of \\\\eqref{202}. If we take smooth functions in the coefficients we get a unique positive \\\\textit{T-periodic} solution of equation \\\\eqref{202}.\\n\\\\begin{figure}[h]\\n\\t\\\\centering\\n\\t\\\\includegraphics[width=0.33 \\\\linewidth]{figg_ex5_1.eps}~~\\n\\t\\\\includegraphics[width=0.33 \\\\linewidth]{figg_ex5_2.eps}\\n\\t\\\\caption{Solution of  \\\\eqref{106} for $D =0.0$, $\\\\mathcal{K}=2.1+ \\\\cos  t$, $r=1.3+ \\\\cos  t $,  in $\\\\Omega=(0,1)$. $u_0=1.1$ and $H=\\\\{1.1+\\\\cos t, \\\\;1.3+\\\\cos t,\\\\;1.5+\\\\cos t\\\\}$ in left; $H =1.2 + \\\\cos  t$ and $u_0=\\\\{0.3, \\\\; 1.1, \\\\; 1.7\\\\}$ (right).} \\n\\t\\\\label{figg8}\\n\\\\end{figure}\\n\\\\end{Ex}\\nIn the above two cases (Case \\\\ref{ex_4} and Case \\\\ref{ex_5}; Figures \\\\ref{figg7} and  \\\\ref{figg8}), we verify the results in section \\\\ref{ssec_2} for constant coefficients and time dependent coefficients respectively. \\\\\\\\\\nIn both cases, we have a critical value $H = r,$ which leads to persistence or extinction of population under harvesting exploitation. We also get a unique positive solution for $H < r$, whatever the starting point is.\\n\\\\begin{Ex}\\\\label{ex_6}\\nConsider equation \\\\eqref{106} with all coefficients are only spatially distributed that is independent of time $t$, $\\\\mathcal{K}(x)\\\\in C^2\\\\left(\\\\Omega\\\\right)$ which satisfies $\\\\displaystyle\\\\left. \\\\frac{\\\\partial u}{\\\\partial \\\\eta}\\\\right| _{\\\\partial\\\\Omega}=0$, which is discussed with the model (\\\\ref{302}).\\\\\\\\\\nHere, the optimal population level is $u^*=\\\\displaystyle\\\\frac{\\\\mathcal{K}(x)}{e}$. Moreover\\n\\\\begin{align*}\\nH^*(x)&=r(x)+D\\\\displaystyle\\\\frac{\\\\Delta \\\\mathcal{K}(x)}{\\\\mathcal{K}(x)} -\\\\displaystyle\\\\frac{1}{\\\\mathcal{K}(x)}\\\\displaystyle\\\\frac{\\\\partial \\\\mathcal{K}(x)}{\\\\partial  t}\\\\\\\\\\n& =r(x)+D\\\\displaystyle\\\\frac{\\\\Delta \\\\mathcal{K}(x)}{\\\\mathcal{K}(x)}\\n\\\\end{align*}\\nAfter a long time period, $ t\\\\rightarrow +\\\\infty$, for $u_0(x)>0$ the solution $u( t,x;u_0)$ tends to the optimal solution $u^*(x)$. Therefore the corresponding maximal sustainable yield for unit time is  \\n\\\\begin{align}\\n\\\\displaystyle\\\\frac{1}{\\\\mathcal{T}}\\\\int \\\\limits_{0}^{\\\\mathcal{T}}\\\\int \\\\limits_{\\\\Omega}H^*(x, t)u^*(x, t)dxd t &=\\\\displaystyle\\\\frac{1}{\\\\mathcal{T}}\\\\int \\\\limits_{0}^{\\\\mathcal{T}}\\\\int \\\\limits_{\\\\Omega}\\\\left(\\\\displaystyle\\\\frac{1}{e}r(x, t)\\\\mathcal{K}(x, t) +\\\\displaystyle\\\\frac{D }{e}\\\\Delta \\\\mathcal{K}\\\\right)dxd t\\\\nonumber\\\\\\\\\\n&=\\\\int \\\\limits_{\\\\Omega}\\\\displaystyle\\\\frac{\\\\mathcal{K}(x)}{e}\\\\left(r(x) +\\\\displaystyle\\\\frac{D \\\\Delta \\\\mathcal{K}(x)}{\\\\mathcal{K}(x)}\\\\right)dx\\\\nonumber\\\\\\\\\\n&=\\\\displaystyle\\\\frac{1}{e}\\\\int \\\\limits_{\\\\Omega}r(x)\\\\mathcal{K}(x)dx\\\\nonumber\\n\\\\end{align} \\nThe last inequality follows from the Green\\'s Theorem \\\\cite{HL_1}.\\nNow we explore the behavior of equation \\\\eqref{302} in Fig. \\\\ref{figg9} for $ D=1.0$, $\\\\mathcal{K}(x)=2.5+ \\\\cos^2(\\\\pi x)$, $u_0(x)=0.5+ \\\\sin^2(\\\\pi x)$, $r(x)=1.5+\\\\cos(\\\\pi x)\\\\sin(x)$ and $H(x)=0.75+\\\\cos^2(\\\\pi x)$ on $\\\\Omega=(0,1)$ for $ t=(0,100)$ and it verifies the result of Theorem \\\\ref{thor_2}.\\n\\\\begin{figure}[h]\\n\\t\\\\centering\\n\\t\\\\includegraphics[width=0.3 \\\\linewidth]{figg_ex6_3.eps}~~\\n\\t\\\\includegraphics[width=0.3 \\\\linewidth]{figg_ex6_1.eps}~~\\n\\t\\\\includegraphics[width=0.3 \\\\linewidth]{figg_ex6_2.eps}\\n\\t\\\\caption{Solution of  \\\\eqref{302} for $D =1.0, \\\\; \\\\mathcal{K}(x)=2.5+ \\\\cos^2(\\\\pi x), \\\\; u_0(x)=0.5+ \\\\sin^2(\\\\pi x), \\\\; r(x)=1.5+\\\\cos(\\\\pi x)\\\\sin(x), \\\\; H(x)=0.75+\\\\cos^2(\\\\pi x)$ on $\\\\Omega=(0,1)\\\\; \\\\text{and} \\\\; t=(0,100)$ for left and middle figure; for right figure, $r>H,\\\\; r=H,\\\\; r<H$.} \\n\\t\\\\label{figg9}\\n\\\\end{figure}\\n\\\\end{Ex}\\n\\\\begin{Ex}\\\\label{ex_7}\\nConsider model \\\\eqref{106} over the region $\\\\Omega = (0,1)$ with diffusion coefficient $D =1.0$, carrying capacity $\\\\mathcal{K}(x,t)=2.5+\\\\cos(\\\\pi x) \\\\sin(\\\\pi t)$ and intrinsic growth rate $r(x,t)=1.2+\\\\cos(\\\\pi x)\\\\sin(\\\\pi t)$.\\n\\nWe choose different harvesting rates $H(x,t)=0.75+\\\\cos^2(\\\\pi x)\\\\sin(\\\\pi t)<r(x,t),\\\\; 1.2+\\\\cos(\\\\pi x)\\\\sin(\\\\pi t)=r(x,t),\\\\; 1.5+\\\\cos(\\\\pi x)\\\\sin(\\\\pi t)>r(x,t)$. \\n\\nThe numerical simulation shows we get a unique positive periodic solution and explore the equilibrium on the change of intrinsic growth rates and harvesting rates.\\n\\t\\\\begin{figure}[h]\\n\\t\\t\\\\centering\\n\\t\\t\\\\includegraphics[width=0.3 \\\\linewidth]{figg_ex7_1.eps}~~\\n\\t\\t\\\\includegraphics[width=0.3 \\\\linewidth]{figg_ex7_2.eps}~~\\n\\t\\t\\\\includegraphics[width=0.3 \\\\linewidth]{figg_ex7_3.eps}\\n\\t\\t\\n\\t\\t\\\\caption{Solution of  \\\\eqref{106} for $D =1.0$, $\\\\mathcal{K}(x,t)=2.5+ \\\\cos^2(\\\\pi x)\\\\sin(\\\\pi t), \\\\; u_0(x)=1.0+ \\\\sin(\\\\pi x), \\\\; r(x,t)=1.2+\\\\cos(\\\\pi x)\\\\sin(\\\\pi t)$, $H(x,t)=\\\\{0.75+\\\\cos^2(\\\\pi x)\\\\sin(\\\\pi t),\\\\; 1.2+\\\\cos(\\\\pi x)\\\\sin(\\\\pi t),\\\\; 1.5+\\\\cos(\\\\pi x)\\\\sin(\\\\pi t)\\\\}$ for $t=500$ (left), on $\\\\Omega=(0,1)$ (middle) and $u_0=\\\\{0.1,1.1,1.0+\\\\sin(\\\\pi x)\\\\}$ (right).} \\n\\t\\t\\\\label{figg10}\\n\\t\\\\end{figure}\\n\\nIn this example (Figure \\\\ref{figg10}), Theorem \\\\ref{thor_1} is verified for random time-periodic carrying capacity functions $\\\\mathcal{K}(x, t),\\\\; r(x,t) \\\\text{and} \\\\; H(x,t)$.\\n\\nNow we outline the influence of the diffusion coefficients $D$ on the equilibrium level. With the increase of $D $, the convergence of the solution is faster than the limit state for the same initial density and $ t>0$.\\n\\nConsider model \\\\eqref{106} for various diffusion such as $D =\\\\{0.5,1.5,2.5\\\\}$ with time varying carrying capacity $\\\\mathcal{K}(x,t)=2.5+ \\\\cos^2(\\\\pi x)\\\\sin(\\\\pi t)$, intrinsic growth rate $r(x,t)=1.2+\\\\cos(\\\\pi x)\\\\sin(\\\\pi t)$, harvesting rate $H(x,t)=0.75+\\\\cos^2(\\\\pi x)\\\\sin(\\\\pi t)$ with initial population $u_0(x)=1.0+ \\\\sin(\\\\pi x)$. Fig. \\\\ref{figg11} illustrates the speed of convergence clearly.\\n    \\\\begin{figure}[h]\\n    \\t\\\\centering\\n    \\t\\\\includegraphics[width=0.33 \\\\linewidth]{figg_ex7_4.eps}~~\\n    \\t\\\\includegraphics[width=0.33  \\\\linewidth]{figg_ex7_5.eps}\\n    \\n    \\t\\\\caption{Solution of  \\\\eqref{106} for $D =\\\\{0.5,1.5,2.5\\\\}, \\\\; \\\\mathcal{K}(x,t)=2.5+ \\\\cos^2(\\\\pi x)\\\\sin(\\\\pi t), \\\\; u_0(x)=1.0+ \\\\sin(\\\\pi x), \\\\; r(x,t)=1.2+\\\\cos(\\\\pi x)\\\\sin(\\\\pi t), \\\\; H(x,t)=0.75+\\\\cos^2(\\\\pi x)\\\\sin(\\\\pi t)$ for $t=250$ (left) on $\\\\Omega=(0,1)$ (right).} \\n    \\t\\\\label{figg11}\\n    \\\\end{figure}\\n\\\\end{Ex}\\n\\n%===========New section====Examples and Applications====================================================\\n%=======================================================================================================\\n\\\\section{Summary and Discussion}\\\\label{ssec_8}\\nIn this paper, we studied a diffusion model for single species with Gompertz growth law, where carrying capacity $\\\\mathcal{K}$, intrinsic growth rate $r$, and harvesting rate $H$ are both space and time-dependent. In particular, it was demonstrated that a solution of the given model (\\\\ref{106}) exists and is unique. It is positive for a non-negative initial function for a non-empty open domain. For the model with time-dependent carrying capacity, all such solutions of (\\\\ref{106}) converge to the positive equilibrium by using upper and lower solution methods. The model is also valid for time-independent carrying capacity. However, if parameters are positive and periodic in $t$-functions rather than $t$-independent parameters, then certain restrictions on $r(x,t),\\\\; H(x,t)$ and $\\\\mathcal{K}(x,t)$ are imposed in Theorem \\\\ref{thor_3} and we get the optimal sustainable yield. The condition that the intrinsic growth rate exceeds the supremum of the relative change of the carrying capacity in time $\\\\frac{\\\\displaystyle 1}{\\\\displaystyle \\\\mathcal{K}}\\\\frac{\\\\displaystyle \\\\partial \\\\mathcal{K}}{\\\\displaystyle dt}$ means that the growth rate can compensate for the change in the carrying capacity, this restriction frequently occurs in the problems of optimal harvesting. We find the optimal harvesting policy for Gompertz law in this paper. We also generalized the results using multiple growth functions with harvesting. We presented numerical examples to justify the analytic results for various parametric values in a non-empty open domain with different initial conditions. \\n\\n\\n\\n%===================Acknowledgments================================\\n\\\\section*{Acknowledgments}\\nThe research by M. Kamrujjaman  was partially supported by the University Grant Commission (UGC), University of Dhaka, Bangladesh.\\n%The author M. Kamrujjaman research was partially supported by TWAS grant 2019\\\\_19-169\\\\,RG/MATHS/AS\\\\_I.\\n%=========================Conflict of interest======================================\\n\\\\section*{Conflict of interest}\\nThe authors declare no conflict of interest.  \\n\\n\\\\section*{Author contributions}\\nConceptualization,  M.K. and S.I.A.; methodology, M.H.A.B., K.M.A.K. and K.N.K.; software, S.I.A. and M.K.; \\nvalidation, M.R.I and M.H.A.B.; formal analysis, M.K and S.I.A.; investigation, K.N.K.\\nand K.M.A.K.; resources, K.N.K. and M.R.I; data curation, S.I.A.; original draft preparation,  S.I.A. and M.K.; review\\nand editing, K.M.A.K., M.H.A.B and M.R.I.; supervision, M.K. All authors have read and agreed to the\\npublished version of the manuscript.\\n\\n\\\\begin{thebibliography}{01}\\n\\t\\n\\\\bibitem{AMT}\\nA. M. Turing, The Chemical Basis of Morphogenesis, Phillos. Trans. R. Soc. London B 237, (1952), 37-72\\n\\n\\\\bibitem{EEHM}\\nE. E. Holmes, M. A. Lewis, J. E. Banks and R. R. Veit, Partial Differential Equations in Ecology: Spatial Interactions and Population Dynamics, Ecology, 75, No. 1 (1994), 17-29.\\n\\n\\\\bibitem{JDM}\\nJames Dickson Murray, E. A. Stanley , and D. L. Brown, On the Spatial Spread of Rabies Among Foxes, Proc. R. Soc. Lond., Series B, 229, No. 1255 (1986), 111-150.\\n\\n\\\\bibitem{CMAJ}\\nChaplain, M. A. J., Reaction-diffusion Pre-patterning and its Potential Role in Tumor Invasion, Journal of Biological Systems, 3, No. 4 (1995), 929 \u2013 936.\\n\\n\\\\bibitem{JSM}\\n E. Braverman and M. Kamrujjaman, Competitive\u2013cooperative models with various diffusion\\nstrategies,  Computers and Mathematics with Applications, 72 (2016) 653\u2013662.\\n%Jonathan A. Sherratt and Martin A. Nowak, Oncogenes, Anti-oncogenes and the Immune Response to Cancer : A Mathematical model, Proc. R. Soc. Lond., Series B, 248 (1992), 261 \u2013 271.\\n\\n\\\\bibitem{JSJ}\\nE. Braverman and M. Kamrujjaman, Lotka systems with directed dispersal dynamics: Competition and\\ninfluence of diffusion strategies, Mathematical Biosciences, 279 (2016) 1-12.\\n%Jonathan A. Sherratt and James Dickson Murray, Models of Epidermal Wound Healing, Proc. R. Soc. Lond. B 241, (1990), 29 \u2013 41.\\n\\n%\\\\bibitem{PCF} P. C. Fife, Mathematical Aspects of Reacting and Diffusing Systems, Springer 1979.\\n\\n%\\\\bibitem{ASM} A. S. Mikhailov, Foundations of Synergetics I. Distributed Active Systems, Springer 1990.\\n\\n\\\\bibitem{CC}\\nC. Cosner, Reaction-diffusion Equations and Ecological Modeling, Book Chapter of the Book: Tutorials in Mathematical Bioscience IV (Evolution and Ecology), Edited by Avner Friedman, Springer, 1922.\\t\\n\\t\\n\\\\bibitem{XQZ}\\nX. Q. Zhao, Dynamical System in Population Biology, Springer-Verlag New York, Inc., 2003.\\n\\t\\n\\\\bibitem{YK}\\nY. Kuang, Delay differential Equations with Applications in Population Dynamics, Mathematics in Science and Engineering, Vol.191, Academic Press, Boston, 1993.\\n\\n\\\\bibitem{RSC_2}\\nR. S. Centrell and C. Cosner, Spatial Ecology via Reaction-diffusion Equations, Wiley Series in Mathematical and computational Biology, Jhon Wiley and Sons, Chichester, 2003.\\n\\n\\\\bibitem{MOMS}\\nM. Kamrujjaman, Directed vs regular diffusion strategy: evolutionary stability analysis of a competition model and an\\nideal free pair, Differential Equations \\\\& Applications, Volume 11, Number 2 (2019), 267\u2013290\\n\\n%M. Oesterheld, M. Semmartin,  Impact of grazing on species composition: adding complexity to a generalized model, Austral. Ecol. 36 (8) (2011), 881\u2013890.\\n\\n\\\\bibitem{SFGS}\\nM. Kamrujjaman, Interplay of resource distributions and diffusion strategies for spatially heterogeneous populations, Journal of Mathematical Modeling, Vol. 7, No. 2, 2019, pp. 175-198.\\n%S. Follak, G. Strauss, Potential distribution and management of the invasive weed Solanum carolinense in Central Europe, Weed Res. 50 (6) (2010), 544\u2013552.\\n\\n%\\\\bibitem{BML}B. E. Saether, M. Lillegard, et al., Geographical gradients in the population dynamics of North American prairie ducks, J. Animal Ecology 77 (5) (2008), 869\u2013882.\\n\\n\\\\bibitem{LKB}\\nL. Korobenko, M. Kamrujjaman and E. Braverman, Persistence and extinction in spatial models with a carrying capacity\\ndriven diffusion and harvesting, J. Math. Anal. Appl. 399 (2013), 352-368.\\n\\n%\\\\bibitem{KKJ} K. Kurata and J. Shi, Optimal special harvesting strategy and symmetry-breaking, {Appl. Math. Optim.} 58(2008), no.1, 89-110.\\n\\n\\\\bibitem{EBL}\\nE. Braverman and L. Braverman, Optimal harvesting of diffusive models in a non-homogeneous environment,  Nonlinear Anal., DOI http://dx.doi.org/10.1016/j.na.2009.04.025\\n\\n%\\\\bibitem{YJX}\\n%Y. Jin and X. Q. Zhao, Bistable waves for a class of cooperative reaction-diffusion systems, \\\\textit{J. Biol. Dynamics} 2(2008), no.2, 196-207.\\n\\n\\\\bibitem{EBRM}\\nE. Braverman, R. Mamdani, Continuous versus pulse harvesting for population models in constant and variable environment, J. Math. Biol. 57 (2008), 413\u2013434.\\n\\n\\\\bibitem{SMH}\\nS. M. Henson, J. M. Cushing, The effect of periodic habitat fluctuations on a nonlinear insect population model, J. Math. Biol. 36 (1997), 201\u2013226.\\n\\n\\\\bibitem{CX}\\nC. Xu, M. S. Boyce, D. J. Daley, Harvesting in seasonal environments, J. Math. Biol.\\n50 (2005), 663\u2013682.\\n\\n\\\\bibitem{GGG}\\nGompertz B: On the nature of the function expressive of the law of human mortality, and on a new mode of determining the value of life contingencies. Phil Trans Royal Soc London 1825, 115:513\u2013583.\\n\\n\\\\bibitem{WCP}\\nWinsor, CP: The Gompertz curve as a growth curve. Proc Natl Acad Sci USA\\n1932, 18:1\u20138.\\n\\n\\n\\\\bibitem{WSB}\\nWright, S: Book review. J Am Stat Assoc 1926, 21:493\u2013497\\n\\n\\\\bibitem{SJRR}\\nStarck J. M., Ricklefs R. E. Avian growth and development. The evolution within the altricial-precocial spectrum. New York, Oxford: Oxford University Press; 1998. 441 p.\\n\\n\\\\bibitem{RWB}\\nRicker W. E. Growth rates and models. In: Hoar WS, Randall DJ, Brett JR, editors. Fish physiology. London: Academic Press; 1979. p. 677-743.\\n\\n\\\\bibitem{PMVP}\\nPaine C. E. T., Marthews T. R., Vogt D. R., Purves D., Rees M., Hector A., Turnbull L. A. How to fit nonlinear plant growth models and calculate growth rates: and update for ecologists. Methods in Ecology and Evolution. 2012; 3:245-56.\\n\\n\\\\bibitem{ZJRV}\\nZwietering M. H., Jongenburger I., Rombouts F. M., Van\\'T Rie T. K. Modeling of the bacterial growth Curve. Appl. Env. Micriobiol. 1990; 56(6):1975-81.\\n\\n\\\\bibitem{SGLJ}\\nSkinner G. E., Larkin J. W. Mathematical modeling of microbial growth: a review. Journal of Food Safety. 1994; 14:1975-217.\\n\\n\\\\bibitem{LAK}\\nLaird A. K., Dynamics of tumor growth. British Journal of Cancer. 1964; 18:490-502.\\n\\n\\\\bibitem{KAMT}\\nK. Kawasaki, A. Mochizuki, M. Matsushita, T. Umeda and N. Shigesada, Modeling spatio-temporal patterns generated by Baccilus subtilis, J. Theor. Biol., 188 (1997), 177\u2013185.\\n\\n\\\\bibitem{JDM2}\\nJ. D. Murray, Mathematical Biology. II: Spatial models and biomedical applications, 3rd edition, Springer, New York, 2003.\\n\\n\\\\bibitem{YWX}\\nY. Wu and X. Q. Zhao, The existence and stability of traveling waves with transition layers for some singular cross-diffusion systems, Physica D: Nonlinear Phenomena, 200 (2005), 325\u2013358.\\n\\n\\n\\\\bibitem{CW_1}\\nC. W. Clark, Mathematical Bio-economics: The Optimal Management of renewable resources, Wiley, New York, 1976.\\n\\n\\\\bibitem{CW_2}\\nC. W. Clark, Mathematical Bio-economics: The Optimal Management of renewable resources, Second ed., Wiley, New York, 1990.\\n\\n\\\\bibitem{MFK}\\nM. Fan and K. Wang, Optimal harvesting policy for single population with periodic coefficients, \\\\textit{Math. Biocsi}. 152 (1998) 165-177.\\n\\n\\\\bibitem{HL_1}\\nH. Li, A class of single-species models with periodic coefficients and their optimal harvesting policy, \\\\textit{J. Biomath}. 14(4) (1999) 479-483.\\n\\n\\\\bibitem{enid}\\nEnid R. Pinch, \u201cOptimal Control and the Calculus of Variations\u201d, Oxford University Press Inc., New York, 1993.\\n\\n\\n\\\\bibitem{HLK}\\nH. Lu and K. Wang, An autonomous single-species models and their optimal harvesting policy, \\\\textit{J. Syst. Math. Sci}. 24(4) (2004) 200-205.\\n\\n\\\\bibitem{ZY} \\nZ. Li and Y. Fu, Existence and stability of periodic quasisolutions in nonlinear parabolic systems with discrete delays, \\\\textit{J. Math. Anal. Appl.} 250 (2000) 139-161.\\n\\n\\\\bibitem{JS}\\nJ. Su and J. Pan, Functional Analysis and Variational Calculus, Press of Technology and Science University, Hefei, 1993.\\n\\n\\\\bibitem{gelfand}\\nI. M. Gelfand and S. V. Fomin, \u201cCalculus of Variations\u201d, Dover Publications Inc., New York, 1963.\\n\\\\end{thebibliography}\\n%\\\\iffalse \\n% \\\\fi \\n\\n\\\\end{document}     '\n\n\n\n\n```python\nls *.eps\n```\n\n    3D_31.eps        figg_ex1_3.eps   figg_ex3_5.eps   figg_ex7_1.eps\r\n    3D_32.eps        figg_ex2_2.eps   figg_ex4_1.eps   figg_ex7_2.eps\r\n    3D_33.eps        figg_ex3_1.eps   figg_ex4_2.eps   figg_ex7_3.eps\r\n    ex1_3D_1.eps     figg_ex3_12.eps  figg_ex5_1.eps   figg_ex7_4.eps\r\n    ex1_3D_2.eps     figg_ex3_13.eps  figg_ex5_2.eps   figg_ex7_5.eps\r\n    ex1_3D_3.eps     figg_ex3_2.eps   figg_ex6_1.eps\r\n    figg_ex1_1.eps   figg_ex3_22.eps  figg_ex6_2.eps\r\n    figg_ex1_2.eps   figg_ex3_4.eps   figg_ex6_3.eps\r\n\n\n\n```python\nmkdir file_used\n```\n\n    mkdir: file_used: File exists\r\n\n\n\n```python\ncp 3D_31.eps file_used/\n```\n", "meta": {"hexsha": "715c0c24ac2b323902bd67076322b6a844d4eb7e", "size": 90151, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "find_included_file_names.ipynb", "max_stars_repo_name": "m-rafiul-islam/data-science", "max_stars_repo_head_hexsha": "670de5ad6f7136f80e107e5d78c11143ac010e01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "find_included_file_names.ipynb", "max_issues_repo_name": "m-rafiul-islam/data-science", "max_issues_repo_head_hexsha": "670de5ad6f7136f80e107e5d78c11143ac010e01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "find_included_file_names.ipynb", "max_forks_repo_name": "m-rafiul-islam/data-science", "max_forks_repo_head_hexsha": "670de5ad6f7136f80e107e5d78c11143ac010e01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 160.4110320285, "max_line_length": 76120, "alphanum_fraction": 0.5786735588, "converted": true, "num_tokens": 26326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14414884567931802, "lm_q2_score": 0.051845462254755746, "lm_q1q2_score": 0.007473463537733693}}
{"text": "(document-tag-to-refer-to)=\n\n# Creating an Example\n\nThis is an example template file for writing Jupyter Notebooks in markdown, using MyST.\nFor more information on MyST notebooks, see the\n[MyST-NB documentation](https://myst-nb.readthedocs.io/en/latest/index.html).\nIf you want to learn more about the MyST parser, see the\n[MyST documentation](https://myst-parser.readthedocs.io/en/latest/).\n\nMyST is common markdown compliant, so if you can use plain markdown here.\nIn case you need to execute restructured text (`rSt`) directives, you can use `{eval-rst}` to execute the code.\nFor instance, a here's a note written in rSt:\n\n```{eval-rst}\n.. note::\n\n   A note written in reStructuredText.\n```\n\n```{margin}\nYou can create margins with this syntax for smaller notes that don't make it into the main\ntext.\n```\n\nYou can also easily define footnotes.[^example]\n\n[^example]: This is a footnote.\n\n## Adding code cells\n\n\n```\nimport ray\nimport ray.rllib.agents.ppo as ppo\nfrom ray import serve\n\ndef train_ppo_model():\n    trainer = ppo.PPOTrainer(\n        config={\"framework\": \"torch\", \"num_workers\": 0},\n        env=\"CartPole-v0\",\n    )\n    # Train for one iteration\n    trainer.train()\n    trainer.save(\"/tmp/rllib_checkpoint\")\n    return \"/tmp/rllib_checkpoint/checkpoint_000001/checkpoint-1\"\n\n\ncheckpoint_path = train_ppo_model()\n```\n\n## Hiding and removing cells\n\nYou can hide cells, so that they will toggle when you click on the cell header.\nYou can use different `:tags:` like `hide-cell`, `hide-input`, or `hide-output` to hide cell content,\nand you can use `remove-cell`, `remove-input`, or `remove-output` to remove the cell completely when rendered.\nThose cells will still show up in the notebook itself, e.g. when you launch it in binder.\n\n\n```\n# This can be useful if you don't want to clutter the page with details.\n\nimport ray\nimport ray.rllib.agents.ppo as ppo\nfrom ray import serve\n```\n\n:::{tip}\nHere's a quick tip.\n:::\n\n\n:::{note}\nAnd this is a note.\n:::\n\nThe following cell will be removed and not render:\n\n\n```\nray.shutdown()\n```\n\n## Equations\n\n\\begin{equation}\n\\frac {\\partial u}{\\partial x} + \\frac{\\partial v}{\\partial y} = - \\, \\frac{\\partial w}{\\partial z}\n\\end{equation}\n\n\\begin{align*}\n2x - 5y &=  8 \\\\\n3x + 9y &=  -12\n\\end{align*}\n", "meta": {"hexsha": "7136fbf1c2b5c9c8cd855eed3e019b60e8cbda8b", "size": 3990, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/source/_templates/template.ipynb", "max_stars_repo_name": "mgelbart/ray", "max_stars_repo_head_hexsha": "4cec2286572e368a4bd64aae467751a384eff62d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2018-05-08T05:52:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T10:09:55.000Z", "max_issues_repo_path": "doc/source/_templates/template.ipynb", "max_issues_repo_name": "mgelbart/ray", "max_issues_repo_head_hexsha": "4cec2286572e368a4bd64aae467751a384eff62d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 73, "max_issues_repo_issues_event_min_datetime": "2021-09-25T07:11:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T07:10:59.000Z", "max_forks_repo_path": "doc/source/_templates/template.ipynb", "max_forks_repo_name": "mgelbart/ray", "max_forks_repo_head_hexsha": "4cec2286572e368a4bd64aae467751a384eff62d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2018-04-27T10:50:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-24T02:41:43.000Z", "avg_line_length": 25.9090909091, "max_line_length": 120, "alphanum_fraction": 0.5343358396, "converted": true, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14608724704829568, "lm_q2_score": 0.050330627433754126, "lm_q1q2_score": 0.007352662804010567}}
{"text": "```python\n# code for loading the format for the notebook\nimport os\n\n# path : store the current path to convert back to it later\npath = os.getcwd()\nos.chdir( os.path.join('..', 'notebook_format') )\nfrom formats import load_style\nload_style(css_style = 'custom2.css')\n```\n\n\n\n\n\n<style>\n    html {\n        font-size: 18px !important;\n    }\n\n    body {\n        background-color: #FFF !important;\n        font-weight: 1rem;\n        font-family: 'Source Sans Pro', \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n    }\n\n    body .notebook-app {\n        background-color: #FFF !important;\n    }\n\n    #header {\n        box-shadow: none !important;\n    }\n\n    #notebook {\n        padding-top: 0px;\n    }\n\n    #notebook-container {\n        box-shadow: none;\n        -webkit-box-shadow: none;\n        padding: 10px;\n    }\n\n    div.cell {\n        width: 1000px;\n        margin-left: 0% !important;\n        margin-right: auto;\n    }\n\n    div.cell.selected {\n        border: 1px dashed #CCCCCC;\n    }\n\n    .edit_mode div.cell.selected {\n        border: 1px dashed #828282;\n    }\n\n    div.output_wrapper {\n        margin-top: 8px;\n    }\n\n    a {\n        color: #383838;\n    }\n\n    code,\n    kbd,\n    pre,\n    samp {\n        font-family: 'Menlo', monospace !important;\n        font-size: 0.75rem !important;\n    }\n\n    h1 {\n        font-size: 2rem !important;\n        font-weight: 500 !important;\n        letter-spacing: 3px !important;\n        text-transform: uppercase !important;\n    }\n\n    h2 {\n        font-size: 1.8rem !important;\n        font-weight: 400 !important;\n        letter-spacing: 3px !important;\n        text-transform: none !important;\n    }\n\n    h3 {\n        font-size: 1.5rem !important;\n        font-weight: 400 !important;\n        font-style: italic !important;\n        display: block !important;\n    }\n\n    h4,\n    h5,\n    h6 {\n        font-size: 1rem !important;\n        font-weight: 400 !important;\n        display: block !important;\n    }\n\n    .prompt {\n        font-family: 'Menlo', monospace !important;\n        font-size: 0.75rem;\n        text-align: right;\n        line-height: 1.21429rem;\n    }\n\n    /* INTRO PAGE */\n\n    .toolbar_info,\n    .list-container {\n        ;\n    }\n    /* NOTEBOOK */\n\n    div#header-container {\n        display: none !important;\n    }\n\n    div#notebook {\n        border-top: none;\n        font-size: 1rem;\n    }\n\n    div.input_prompt {\n        color: #C74483;\n    }\n\n    .code_cell div.input_prompt:after,\n    div.output_prompt:after {\n        content: '\\25b6';\n    }\n\n    div.output_prompt {\n        color: #2B88D9;\n    }\n\n    div.input_area {\n        border-radius: 0px;\n        border: 1px solid #d8d8d8;\n    }\n\n    div.output_area pre {\n        font-weight: normal;\n    }\n\n    div.output_subarea {\n        font-weight: normal;\n    }\n\n    .rendered_html pre,\n    .rendered_html table,\n    .rendered_html th,\n    .rendered_html tr,\n    .rendered_html td {\n        border: 1px #828282 solid;\n        font-size: 0.75rem;\n        font-family: 'Menlo', monospace;\n    }\n\n    .rendered_html th,\n    .rendered_html tr,\n    .rendered_html td {\n        padding: 5px 10px;\n    }\n\n    .rendered_html th {\n        font-weight: normal;\n        background: #f8f8f8;\n    }\n\n    a:link{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:visited{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:hover{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:focus{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:active{\n       font-weight: bold;\n       color:#447adb;\n    }\n    .rendered_html :link {\n       text-decoration: underline; \n    }\n\n    div.output_html {\n        font-weight: 1rem;\n        font-family: 'Source Sans Pro', \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n    }\n\n    table.dataframe tr {\n        border: 1px #CCCCCC;\n    }\n\n    div.cell.selected {\n        border-radius: 0px;\n    }\n\n    div.cell.edit_mode {\n        border-radius: 0px;\n        border: thin solid #CF5804;\n    }\n\n    span.ansiblue {\n        color: #00A397;\n    }\n\n    span.ansigray {\n        color: #d8d8d8;\n    }\n\n    span.ansigreen {\n        color: #688A0A;\n    }\n\n    span.ansipurple {\n        color: #975DDE;\n    }\n\n    span.ansired {\n        color: #D43132;\n    }\n\n    span.ansiyellow {\n        color: #D9AA00;\n    }\n\n    div.output_stderr {\n        background-color: #D43132;\n    }\n\n    div.output_stderr pre {\n        color: #e8e8e8;\n    }\n\n    .cm-s-ipython.CodeMirror {\n        background: #F8F8F8;\n    }\n\n    .cm-s-ipython div.CodeMirror-selected {\n        background: #e8e8e8 !important;\n    }\n\n    .cm-s-ipython .CodeMirror-gutters {\n        background: #F8F8F8;\n        border-right: 0px;\n    }\n\n    .cm-s-ipython .CodeMirror-linenumber {\n        color: #b8b8b8;\n    }\n\n    .cm-s-ipython .CodeMirror-cursor {\n        border-left: 1px solid #585858 !important;\n    }\n\n    .cm-s-ipython span.cm-atom {\n        color: #C74483;\n    }\n\n    .cm-s-ipython span.cm-number {\n        color: #C74483;\n    }\n\n    .cm-s-ipython span.cm-property,\n    .cm-s-ipython span.cm-attribute {\n        color: #688A0A;\n    }\n\n    .cm-s-ipython span.cm-keyword {\n        font-weight: normal;\n        color: #D43132;\n    }\n\n    .cm-s-ipython span.cm-string {\n        color: #D9AA00;\n    }\n\n    .cm-s-ipython span.cm-operator {\n        font-weight: normal;\n    }\n\n    .cm-s-ipython span.cm-builtin {\n        color: #2B88D9;\n    }\n\n    .cm-s-ipython span.cm-variable {\n        color: #00A397;\n    }\n\n    .cm-s-ipython span.cm-variable-2 {\n        color: #2B88D9;\n    }\n\n    .cm-s-ipython span.cm-def {\n        color: #00A397;\n    }\n\n    .cm-s-ipython span.cm-error {\n        background: #FFBDBD;\n        color: #D43132;\n    }\n\n    .cm-s-ipython span.cm-tag {\n        color: #D43132;\n    }\n\n    .cm-s-ipython span.cm-link {\n        color: #975DDE;\n    }\n\n    .cm-s-ipython .CodeMirror-matchingbracket {\n        text-decoration: underline;\n         !important;\n    }\n</style>\n\n\n\n\n\n\n```python\nos.chdir(path)\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# 1. magic for inline plot\n# 2. magic to print version\n# 3. magic so that the notebook will reload external python modules\n%matplotlib inline\n%load_ext watermark\n%load_ext autoreload \n%autoreload 2\n\n# pip install python-dotenv\n# for the dotenv package, it is\n# for loading personal API key, as we'll \n# see, but you don't have to use it\nimport json\nimport requests\nfrom subprocess import call\nfrom dotenv import load_dotenv\nfrom IPython.display import HTML\nfrom IPython.display import Image\nfrom IPython.display import display\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import pairwise_distances\n\n%watermark -a 'Ethen' -d -t -v -p numpy,pandas,matplotlib,sklearn,requests\n```\n\n    Ethen 2017-03-23 22:10:20 \n    \n    CPython 3.5.2\n    IPython 5.3.0\n    \n    numpy 1.12.1\n    pandas 0.19.2\n    matplotlib 2.0.0\n    sklearn 0.18\n    requests 2.13.0\n\n\n# Alternating Least Squares with Weighted Regularization\n\nRecommedantion system is a popular topic in recent years, what is does (or its goal) is to seek to predict the \"rating\" or \"preference\" that a user would give to an item. Given the rating, the business will then recommend preferable new items to the user for further purchases. The type of recommendation system that we will be discussing is known as **collaborative filtering**, where the features of the user (e.g. age, gender) or the item (e.g. perishable or not) itself do not play any role in the algorithm. Instead, we rely soley on the ratings that a user gave to the item.\n\nWe start by loading some sample data to make this a bit more concrete. For this introduction, we'll be using the [MovieLens dataset](http://grouplens.org/datasets/movielens/). The website has datasets of various sizes, but we just start with the smallest one [MovieLens 100K Dataset](http://files.grouplens.org/datasets/movielens/ml-100k.zip). This dataset consists of 100,000 movie ratings by users (on a 1-5 scale). The main data set `u.data` file consists of four columns (tab-delimited), including user-id (starting at 1), item-id (starting at 1), rating, and timestamp (we won't be using this field).\n\n\n```python\n# download the dataset if it isn't in the same folder\nfile_dir = 'ml-100k'\nfile_path = os.path.join(file_dir, 'u.data')\nif not os.path.isdir(file_dir):\n    call(['curl', '-O', 'http://files.grouplens.org/datasets/movielens/ml-100k.zip'])\n    call(['unzip', 'ml-100k.zip'])\n\nnames = ['user_id', 'item_id', 'rating', 'timestamp']\ndf = pd.read_csv(file_path, sep = '\\t', names = names)\nprint(df.shape)\ndf.head()\n```\n\n    (100000, 4)\n\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>user_id</th>\n      <th>item_id</th>\n      <th>rating</th>\n      <th>timestamp</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>196</td>\n      <td>242</td>\n      <td>3</td>\n      <td>881250949</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>186</td>\n      <td>302</td>\n      <td>3</td>\n      <td>891717742</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>22</td>\n      <td>377</td>\n      <td>1</td>\n      <td>878887116</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>244</td>\n      <td>51</td>\n      <td>2</td>\n      <td>880606923</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>166</td>\n      <td>346</td>\n      <td>1</td>\n      <td>886397596</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nAs we can see, the only data that we have is how each user interacted or rated each item. Given this information, collaborative filtering will start by constructing a user-item matrix with each distinct user being the row, item being the column and the value for each cell will simply be the rating that the user gave to the item. Apart from building the matrix, we will also print out some other information to help us understand our data a bit better.\n\n\n```python\n# create the rating matrix r_{ui}, remember to\n# subract the user and item id by 1 since\n# the indices starts from 0\nn_users = df['user_id'].unique().shape[0]\nn_items = df['item_id'].unique().shape[0]\nratings = np.zeros((n_users, n_items))\nfor row in df.itertuples(index = False):\n    ratings[row.user_id - 1, row.item_id - 1] = row.rating\n\n# compute the non-zero elements in the rating matrix\nmatrix_size = np.prod(ratings.shape)\ninteraction = np.flatnonzero(ratings).shape[0]\nsparsity = 100 * (interaction / matrix_size)\n\nprint('dimension: ', ratings.shape)\nprint( 'sparsity: {:.1f}%'.format(sparsity) )\nratings\n```\n\n    dimension:  (943, 1682)\n    sparsity: 6.3%\n\n\n\n\n\n    array([[ 5.,  3.,  4., ...,  0.,  0.,  0.],\n           [ 4.,  0.,  0., ...,  0.,  0.,  0.],\n           [ 0.,  0.,  0., ...,  0.,  0.,  0.],\n           ..., \n           [ 5.,  0.,  0., ...,  0.,  0.,  0.],\n           [ 0.,  0.,  0., ...,  0.,  0.,  0.],\n           [ 0.,  5.,  0., ...,  0.,  0.,  0.]])\n\n\n\n\n```python\n# change default figure and font size\nplt.rcParams['figure.figsize'] = 8, 6 \nplt.rcParams['font.size'] = 12\n\nplt.hist( np.sum(ratings != 0, axis = 1), histtype = 'stepfilled', bins = 30,\n          alpha = 0.85, label = '# of ratings', color = '#7A68A6', normed = True )\nplt.axvline(x = 10, color = 'black', linestyle = '--')\nplt.legend(loc = \"upper right\")\nplt.show()\n```\n\nFrom the information above, we know there are 943 unique users, 1682 unique items. Within the rating matrix, only 6.3% of the cells have a value, although we filled in empty ratings as 0, we should not assume these values to truly be zero. More appropriately, they are just missing entries. This kind of sparsity is extremely common in recommendation system, where people seldom give ratings to things that they have purchased. One thing to note is that if the sparsity of the matrix is below 1% (rule of thumb), then the dataset might be too sparse to perform any sort of modeling.\n\nNext the histogram tells us that every user has given at least more than 10 ratings, we will use this to perform the train/test split of the data for testing the algorithm that we'll build later.\n\nOne tricky thing about splitting the data into training and testing is that: In supervise machine learning we normally build the trainining and testing holdout set by randomly splitting the rows. In those cases, this idea works, because we have a model with features/target that we are trying to fit a function to. For recommender systems with collaborative filtering (no features), this just won't work anymore, because all of the items/users need to be available when the model is first built. So what we do instead is mask a random sample of the user/item ratings to validate and compare how well the recommender system did in predicting the ratings of those masked values. In our case, given we already know each user has given more than 10 ratings, what we'll do is for every user, we remove 10 of the item ratings and and assign them to the test set. The testing matrix is printed below, as hopefully, you can see that some of the values are indeed different from the original rating matrix.\n\n\n```python\ndef create_train_test(ratings):\n    \"\"\"\n    split into training and test sets,\n    remove 10 ratings from each user\n    and assign them to the test set\n    \"\"\"\n    test = np.zeros(ratings.shape)\n    train = ratings.copy()\n    for user in range(ratings.shape[0]):\n        test_index = np.random.choice( np.flatnonzero(ratings[user]), \n                                       size = 10, replace = False )\n        train[user, test_index] = 0.0\n        test[user, test_index] = ratings[user, test_index]\n        \n    # assert that training and testing set are truly disjoint\n    assert np.all(train * test == 0)\n    return train, test\n\ntrain, test = create_train_test(ratings)\ndel ratings\ntrain\n```\n\n\n\n\n    array([[ 5.,  3.,  4., ...,  0.,  0.,  0.],\n           [ 4.,  0.,  0., ...,  0.,  0.,  0.],\n           [ 0.,  0.,  0., ...,  0.,  0.,  0.],\n           ..., \n           [ 5.,  0.,  0., ...,  0.,  0.,  0.],\n           [ 0.,  0.,  0., ...,  0.,  0.,  0.],\n           [ 0.,  5.,  0., ...,  0.,  0.,  0.]])\n\n\n\n## Matrix Factorization\n\nNow that the data preprocessing part has been taken care of, let's get to the more exciting part, the algorithm. The algorithm that we'll introduce today is Matrix Factorization.\n\nRecall that we had a user-item matrix, $R$ where nonzero elements of the matrix are ratings that a user has given an item. What Matrix Factorization does is it decomposes a large matrix into products of matrices, namely, $R = U \\times V$. See the picture below taken from a quick [google search](https://www.google.com/search?q=matrix+factorization&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiD8Ku02_vQAhXGsVQKHdpSAW4Q_AUICCgB&biw=1433&bih=732#imgrc=aFtUeC0wtJCkgM%3A) for a better understanding:\n\n\n\nMatrix factorization assumes that:\n\n- Each user can be described by $d$ features. For example, feature 1 might be a referring to how much each user likes disney movies.\n- Each item, movie in this case, can be described by an analagous set of $d$ features. To correspond to the above example, feature 1 for the movie might be a number that says how close the movie is to a disney movie.\n\nAfter learning the two smaller matrices, all we have to do is to perform a matrix multiplication of the two matrices and the end result will be a our approximation for the rating the user would give that item (movie).\n\nThe cool thing about this is that, we do not know what these features are nor do we have to determine them beforehand, which is why these features are often refer to as latent features. Next, we also don't know how many latent features are optimal for the task at hand. Thus, we simply have to use random search or grid search or other fancy techniques to perform hyperparameter tuning and determine the best number for $d$. \n\nGiven all those information, the next question is: how do we learn the user matrix, $U$, and item matrix, $V$? Well, like a lot of machine learning algorithm, by minimizing a loss function.\n\nWe start by denoting our $d$ feature user into math by letting a user $u$ take the form of a $1 \\times d$-dimensional vector $\\textbf{x}_{u}$. These for often times referred to as latent vectors or low-dimensional embeddings. Similarly, an item *i* can be represented by a $1 \\times d$-dimensional vector $\\textbf{y}_{i}$. And the rating that we predict user $u$ will give for item $i$ is just the dot product of the two vectors\n\n\\begin{align}\n\\hat r_{ui} &= \\textbf{x}_{u} \\textbf{y}_{i}^{T} = \\sum\\limits_{d} x_{ud}y_{di}\n\\end{align}\n\nWhere $\\hat r_{ui}$ represents our prediction for the true rating $r_{ui}$. Next, we will choose a objective function to minimize the square of the difference between all ratings in our dataset ($S$) and our predictions. This produces a objective function of the form:\n\n\\begin{align}\nL &= \\sum\\limits_{u,i \\in S}( r_{ui} - \\textbf{x}_{u} \\textbf{y}_{i}^{T} )^{2} + \\lambda \\big( \\sum\\limits_{u} \\left\\Vert \\textbf{x}_{u} \\right\\Vert^{2} + \\sum\\limits_{i} \\left\\Vert \\textbf{y}_{i} \\right\\Vert^{2} \\big)\n\\end{align}\n\nNote that we've added on two $L_{2}$ regularization terms, with $\\lambda$ controlling the strength at the end to prevent overfitting of the user and item vectors. $\\lambda$, is another hyperparameter that we'll have to search for to determine the best value. Regularization can a can topic of itself, and if you're confused by this, consider checking out [this documentation](http://nbviewer.jupyter.org/github/ethen8181/machine-learning/blob/master/regularization/regularization.ipynb) that covers it a bit more.\n\nNow that we formalize our objective function, we'll introduce the **Alternating Least Squares with Weighted Regularization (ALS-WR)** method for optimizing it. The way it works is we start by treating one set of latent vectors as constant. For this example, we'll pick the item vectors, $\\textbf{y}_{i}$. We then take the derivative of the loss function with respect to the other set of vectors, the user vectors, $\\textbf{x}_{u}$ and solve for the non-constant vectors (the user vectors).\n\n\\begin{align}\n\\frac{\\partial L}{\\partial \\textbf{x}_{u}} \n&\\implies - 2 \\sum\\limits_{i}(r_{ui} - \\textbf{x}_{u} \\textbf{y}_{i}^{T} ) \\textbf{y}_{i} + 2 \\lambda \\textbf{x}_{u} = 0 \\\\\n&\\implies -(\\textbf{r}_{u} - \\textbf{x}_{u} Y^{T} )Y + \\lambda \\textbf{x}_{u} = 0 \\\\\n&\\implies \\textbf{x}_{u} (Y^{T}Y + \\lambda I) = \\textbf{r}_{u}Y \\\\\n&\\implies \\textbf{x}_{u} = \\textbf{r}_{u}Y (Y^{T}Y + \\lambda I)^{-1}\n\\end{align}\n\nTo clarify it a bit, let us assume that we have $m$ users and $n$ items, so our ratings matrix is $m \\times n$.\n\n- The row vector $\\textbf{r}_{u}$ just represents users *u*'s row from the ratings matrix with all the ratings for all the items (so it has dimension $1 \\times n$)\n-  We introduce the symbol $Y$, with dimensions $n \\times d$, to represent all item row vectors vertically stacked on each other\n- Lastly, $I$ is just the identity matrix which has dimension $d \\times d$ to ensure the matrix multiplication's dimensionality will be correct when we add the $\\lambda$\n\nNow comes the alternating part: With these newly updated user vectors in hand, in the next round, we hold them as constant, and take the derivative of the loss function with respect to the previously constant vectors (the item vectors). As the derivation for the item vectors is quite similar, we will simply list out the end formula:\n\n\\begin{align}\n\\frac{\\partial L}{\\partial \\textbf{y}_{i}}\n&\\implies \\textbf{y}_{i} = \\textbf{r}_{i}X (X^{T}X + \\lambda I)^{-1}\n\\end{align}\n\nThen we alternate back and forth and carry out this two-step process until convergence. The reason we alternate is, optimizing user latent vectors, $U$, and item latent vectors $V$ simultaneously is hard to solve. If we fix $U$ or $V$ and tackle one problem at a time, we potentially turn it into a easier sub-problem. Just to summarize it, ALS works by:\n\n1. Initialize the user latent vectors, $U$, and item latent vectors $V$ with randomly\n2. Fix $U$ and solve for $V$\n3. Fix $V$ and solve for $U$\n4. Repeat step 2 and 3 until convergence\n\nNow that we have our equations, let's program this thing up! We'll set the model to use 20 factors and a regularization value of 0.01 (chosen at random) and train it for 100 iterations and compute the mean square error on the train and test set to assess algorithm convergence.\n\n\n```python\nclass ExplicitMF:\n    \"\"\"\n    Train a matrix factorization model using Alternating Least Squares\n    to predict empty entries in a matrix\n    \n    Parameters\n    ----------\n    n_iters : int\n        number of iterations to train the algorithm\n        \n    n_factors : int\n        number of latent factors to use in matrix \n        factorization model, some machine-learning libraries\n        denote this as rank\n        \n    reg : float\n        regularization term for item/user latent factors,\n        since lambda is a keyword in python we use reg instead\n    \"\"\"\n    def __init__(self, n_iters, n_factors, reg):\n        self.reg = reg\n        self.n_iters = n_iters\n        self.n_factors = n_factors  \n        \n    def fit(self, train, test):\n        \"\"\"\n        pass in training and testing at the same time to record\n        model convergence, assuming both dataset is in the form\n        of User x Item matrix with cells as ratings\n        \"\"\"\n        self.n_user, self.n_item = train.shape\n        self.user_factors = np.random.random((self.n_user, self.n_factors))\n        self.item_factors = np.random.random((self.n_item, self.n_factors))\n        \n        # record the training and testing mse for every iteration\n        # to show convergence later (usually, not worth it for production)\n        self.test_mse_record  = []\n        self.train_mse_record = []   \n        for _ in range(self.n_iters):\n            self.user_factors = self._als_step(train, self.user_factors, self.item_factors)\n            self.item_factors = self._als_step(train.T, self.item_factors, self.user_factors) \n            predictions = self.predict()\n            test_mse  = self.compute_mse(test, predictions)\n            train_mse = self.compute_mse(train, predictions)\n            self.test_mse_record.append(test_mse)\n            self.train_mse_record.append(train_mse)\n        \n        return self    \n    \n    def _als_step(self, ratings, solve_vecs, fixed_vecs):\n        \"\"\"\n        when updating the user matrix,\n        the item matrix is the fixed vector and vice versa\n        \"\"\"\n        A = fixed_vecs.T.dot(fixed_vecs) + np.eye(self.n_factors) * self.reg\n        b = ratings.dot(fixed_vecs)\n        A_inv = np.linalg.inv(A)\n        solve_vecs = b.dot(A_inv)\n        return solve_vecs\n    \n    def predict(self):\n        \"\"\"predict ratings for every user and item\"\"\"\n        pred = self.user_factors.dot(self.item_factors.T)\n        return pred\n    \n    @staticmethod\n    def compute_mse(y_true, y_pred):\n        \"\"\"ignore zero terms prior to comparing the mse\"\"\"\n        mask = np.nonzero(y_true)\n        mse = mean_squared_error(y_true[mask], y_pred[mask])\n        return mse\n```\n\n\n```python\ndef plot_learning_curve(model):\n    \"\"\"visualize the training/testing loss\"\"\"\n    linewidth = 3\n    plt.plot(model.test_mse_record, label = 'Test', linewidth = linewidth)\n    plt.plot(model.train_mse_record, label = 'Train', linewidth = linewidth)\n    plt.xlabel('iterations')\n    plt.ylabel('MSE')\n    plt.legend(loc = 'best')\n```\n\n\n```python\nals = ExplicitMF(n_iters = 100, n_factors = 40, reg = 0.01)\nals.fit(train, test)\nplot_learning_curve(als)\n```\n\nFrom the result, we can see ALS converges after a few sweeps, which is one of the main reason for its popularity. Fast, thus scalable to bigger dataset.\n\n## Validating the Recommendation\n\nAfter training our model, we'll actually look at the recommended result to see if our recommendation algorithm is any good or not. The way we do this is: The MovieLens dataset contains a file called `u.item` with information about each movie. To put the cherry on top, it turns out that there is a website called [themoviedb.org](http://www.themoviedb.org) which has a free API. If we have the IMDB \"movie id\" for a movie, then we can use this API to return the its poster. Note that you will have to sign up and request for an API key if you wish to reproduce the example below.\n\n\n```python\n# Load in movies' information, stored in the u.item (pipe delimited)\n# file, the first element is the id, and the fourth element is the \n# movie's IMDB url\nidx_to_movie = {}\nitem_path = os.path.join(file_dir, 'u.item')\n\nwith open(item_path, encoding = 'latin1') as f:\n    for line in f.readlines():\n        info = line.split('|')\n        idx = int(info[0]) - 1\n        movie = info[4]\n        idx_to_movie[idx] = movie\n        \nidx_to_movie[0]\n```\n\n\n\n\n    'http://us.imdb.com/M/title-exact?Toy%20Story%20(1995)'\n\n\n\nFor example, if we paste the sample url above into our browser, then our url will get redirected. The resulting url contains the IMDB movie ID as the last information in the url starting with \"tt\". For example, the redirected url for Toy Story is http://www.imdb.com/title/tt0114709/, and the corresponding IMDB movie ID is therefore tt0114709.\n\n\n```python\n# stripping the movie id with requests\nresponse = requests.get(idx_to_movie[0])\nmovie_id = response.url.split('/')[-2]\nprint(movie_id)\n```\n\n    tt0114709\n\n\nFrom the API documentation: \n\nTo build an image URL, we will need 3 pieces of data. The base_url, size and file_path. Simply combine them all and you will have a fully qualified URL. Here\u2019s an example URL: \nhttps://image.tmdb.org/t/p/w500/8uO0gUM8aNqYLs1OsTBQiXu0fEv.jpg\n\nSo to get the base_url, we send a request to the https://api.themoviedb.org/3/configuration using our API key as the parameter, after that we load the information into a dictionary and access the `base_url` key under the `images` key (the base_url is nested under images), and we'll also append the poster size at the end of the base_url.\n\n\n```python\n# here I'm simply loading my API key\n# from a .env file, and using dotenv package\n# to obtain the value of the variable, you may\n# simply change the api_key variable to your key\nload_dotenv('.env')\napi_key = os.environ.get('API_KEY')\n\n# request the base_url\nparams = {'api_key': api_key}\nresponse = requests.get('http://api.themoviedb.org/3/configuration', params = params)\n\n# for the poster there are different sizes\n# 'w92', 'w154', 'w185', 'w342', 'w500', 'w780', 'original',\n# simply change it to the one you prefer\nbase_url = json.loads(response.text)['images']['base_url'] + 'w185'\nbase_url\n```\n\n\n\n\n    'http://image.tmdb.org/t/p/w185'\n\n\n\nNext to get the file_path to the poster image, the have to send another request to http://api.themoviedb.org/3/movie/{}/images, where we have to fill in the movie_id for {}. Then the actual path will be stored under the `file_path` key under the `posters` key (accessing the posters key will give you a list of path, we'll simply use the first one).\n\n\n```python\nimage_url = 'http://api.themoviedb.org/3/movie/{}/images'.format(movie_id)\nresponse  = requests.get(image_url, params = params)\nfile_path = json.loads(response.text)['posters'][0]['file_path']\nfile_path\n```\n\n\n\n\n    '/uMZqKhT4YA6mqo2yczoznv7IDmv.jpg'\n\n\n\nAfter that we can simply concatenate the base_url and the file path and display the poster image.\n\n\n```python\nfull_path = base_url + file_path\nImage(full_path)\n```\n\n\n\n\n    \n\n    \n\n\n\nUnfortunately, there are also other edge-cases, where we have to search for the title and grab the poster image there. e.g.\n\n\n```python\nmovie_url = 'http://us.imdb.com/M/title-exact?Fox%20and%20the%20Hound,%20The%20(1981)'\nresponse  = requests.get(movie_url)\n\n# see how the url is different this time,\n# we have to strip out the title between the = sign\n# and pass it to the movie search API using the title\n# as a query parameter\nprint(response.url)\nquery = response.url.split('=')[-2]\nparams['query'] = query\nresponse = requests.get('http://api.themoviedb.org/3/search/movie', params = params)\njson.loads(response.text)\nfile_path = json.loads(response.text)['results'][0]['poster_path']\nfull_path = base_url + file_path\nImage(full_path)\n```\n\n    http://www.imdb.com/find?q=Fox%20and%20the%20Hound,%20The&s=tt\n\n\n\n\n\n    \n\n    \n\n\n\nIn the following section, we'll train the model again, use [themoviedb.org](http://www.themoviedb.org)'s API to grab the movie posters and visualize the top 5 most similar movies (measured by cosine distance) for some input movie. These similar movies will serve as our recommendation for a given input movie.\n\nSide note, the images are displayed using HTML so multiple images can be displayed in one line, idea taken from this [Stackoverflow question](http://stackoverflow.com/questions/19471814/display-multiple-images-in-one-ipython-notebook-cell/27795087#27795087).\n\n\n```python\nclass Recommendation:\n    \"\"\"\n    Train the ALS model to be able to\n    recommend the top-k similar movies for a given query\n    \n    Parameters\n    ----------\n    k: int\n        number of top similar movies to recommend for\n        a given query\n        \n    model: ExplicitMF\n        the recommendation algorithm\n        \n    idx_to_movie: dictionary\n        a dictionary mapping movie id to their imdb url\n    \"\"\"\n    def __init__(self, model, k, idx_to_movie):\n        self.k = k\n        self.model = model\n        self.idx_to_movie = idx_to_movie\n         \n    def fit(self, train, test):\n        # train the model and compute the pairwise cosine distance\n        self.model.fit(train, test)\n        self.sim_mat = pairwise_distances(self.model.item_factors, metric = 'cosine')\n        \n        # also get the base url for the API\n        # assuming API key is stored in .env file\n        load_dotenv('.env')\n        api_key = os.environ.get('API_KEY')\n        self.params = {'api_key': api_key}\n        response = requests.get('http://api.themoviedb.org/3/configuration', \n                                params = self.params)\n        self.base_url = json.loads(response.text)['images']['base_url'] + 'w185'\n        return self\n    \n    def recommend(self, query):\n        movie_url = idx_to_movie[query]\n        input_poster = self._get_poster(movie_url)\n        input_image = ''.format(input_poster)\n        recommended_images = self._get_top_k_recommendation(query)\n        \n        # display query movie and for that movie top-k recommendations\n        display( HTML('<font size=5> Input </font>') )\n        input_image = ''.format(input_poster)\n        display( HTML(input_image) )\n        display( HTML('<font size=5> Recommendation </font>') )\n        display( HTML(recommended_images) )\n\n    def _get_poster(self, movie_url):\n        \"\"\"get the poster image for a given movie url\"\"\"\n        try:\n            response  = requests.get(movie_url)\n            movie_id  = response.url.split('/')[-2]\n            image_url = 'http://api.themoviedb.org/3/movie/{}/images'.format(movie_id)\n            response  = requests.get(image_url, params = self.params)\n            file_path = json.loads(response.text)['posters'][0]['file_path']\n        except KeyError:\n            try:\n                response = requests.get(movie_url)\n                query = response.url.split('=')[-2]\n                self.params['query'] = query\n                response = requests.get('http://api.themoviedb.org/3/search/movie', \n                                        params = self.params)\n                json.loads(response.text)\n                file_path = json.loads(response.text)['results'][0]['poster_path']\n                self.params.pop('query')\n            except KeyError:\n                # sometimes the url just doesn't work\n                # return an empty string to not mess up the display\n                file_path = ''\n\n        full_path = self.base_url + file_path\n        return full_path\n    \n    def _get_top_k_recommendation(self, query):\n        \"\"\"\n        sort the similarity vector to get the most similar,\n        remember the smaller the cosine, the more similar they are\n        but the query item itself will always be the most similar,\n        so exclude that from the output\n        \"\"\"\n        sim = self.sim_mat[query]\n        top_k_item_idx = np.argsort(sim)[1:self.k + 1]\n        recommended_images = ''\n        for item_idx in top_k_item_idx:\n            movie_url = self.idx_to_movie[item_idx]\n            recommended_poster = self._get_poster(movie_url)\n            recommended_images += \"\"\"\n                                  \n                                  \"\"\".format(recommended_poster)\n        return recommended_images\n```\n\n\n```python\nals = ExplicitMF(n_iters = 100, n_factors = 40, reg = 0.01)\nrecsys = Recommendation(model = als, k = 5, idx_to_movie = idx_to_movie)\nrecsys = recsys.fit(train, test)\n```\n\n\n```python\nquery = 1\nrecsys.recommend(query)\n```\n\n\n<font size=5> Input </font>\n\n\n\n\n\n\n\n<font size=5> Recommendation </font>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n```python\nquery = 500\nrecsys.recommend(query)\n```\n\n\n<font size=5> Input </font>\n\n\n\n\n\n\n\n<font size=5> Recommendation </font>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nI'll leave it up to you to determine whether these recommendations are good or not (results will slightly differ across different runs). In practice A/B testing is most likely a better way to judge whether these recommendations are useful, but that's a topic for some other day.\n\n# Reference\n\n- [Blog: Intro to Recommender Systems: Collaborative Filtering](http://blog.ethanrosenthal.com/2015/11/02/intro-to-collaborative-filtering/)\n- [Blog: Explicit Matrix Factorization: ALS, SGD, and All That Jazz](http://blog.ethanrosenthal.com/2016/01/09/explicit-matrix-factorization-sgd-als/)\n- [Quora: What is the Alternating Least Squares method in recommendation systems?](https://www.quora.com/What-is-the-Alternating-Least-Squares-method-in-recommendation-systems)\n", "meta": {"hexsha": "0f533519f90eb9414b0db0f8db25355283b937ff", "size": 156330, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "recsys/1_ALSWR.ipynb", "max_stars_repo_name": "awesome-archive/machine-learning", "max_stars_repo_head_hexsha": "8494f3fe73db511f7b97d082c786097bfbe71463", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-07-05T09:32:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-05T09:32:31.000Z", "max_issues_repo_path": "recsys/1_ALSWR.ipynb", "max_issues_repo_name": "awesome-archive/machine-learning", "max_issues_repo_head_hexsha": "8494f3fe73db511f7b97d082c786097bfbe71463", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "recsys/1_ALSWR.ipynb", "max_forks_repo_name": "awesome-archive/machine-learning", "max_forks_repo_head_hexsha": "8494f3fe73db511f7b97d082c786097bfbe71463", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-08T17:36:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-08T17:36:36.000Z", "avg_line_length": 108.4871616933, "max_line_length": 26943, "alphanum_fraction": 0.7969679524, "converted": true, "num_tokens": 8920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10818896606387246, "lm_q2_score": 0.0675466916088975, "lm_q1q2_score": 0.0073078067262018695}}
{"text": "```python\npip install tensorflow==2.4.1 tensorflow-quantum\n```\n\n    Collecting tensorflow==2.4.1\n      Downloading tensorflow-2.4.1-cp37-cp37m-manylinux2010_x86_64.whl (394.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 394.3 MB 13 kB/s \n    \u001b[?25hCollecting tensorflow-quantum\n      Downloading tensorflow_quantum-0.5.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (7.8 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 7.8 MB 22.7 MB/s \n    \u001b[?25hRequirement already satisfied: termcolor~=1.1.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.4.1) (1.1.0)\n    Collecting wrapt~=1.12.1\n      Downloading wrapt-1.12.1.tar.gz (27 kB)\n    Collecting grpcio~=1.32.0\n      Downloading grpcio-1.32.0-cp37-cp37m-manylinux2014_x86_64.whl (3.8 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.8 MB 41.1 MB/s \n    \u001b[?25hRequirement already satisfied: opt-einsum~=3.3.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.4.1) (3.3.0)\n    Requirement already satisfied: google-pasta~=0.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.4.1) (0.2.0)\n    Collecting flatbuffers~=1.12.0\n      Downloading flatbuffers-1.12-py2.py3-none-any.whl (15 kB)\n    Requirement already satisfied: numpy~=1.19.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.4.1) (1.19.5)\n    Requirement already satisfied: six~=1.15.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.4.1) (1.15.0)\n    Requirement already satisfied: tensorboard~=2.4 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.4.1) (2.7.0)\n    Requirement already satisfied: keras-preprocessing~=1.1.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.4.1) (1.1.2)\n    Requirement already satisfied: absl-py~=0.10 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.4.1) (0.12.0)\n    Requirement already satisfied: astunparse~=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.4.1) (1.6.3)\n    Requirement already satisfied: protobuf>=3.9.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.4.1) (3.17.3)\n    Collecting tensorflow-estimator<2.5.0,>=2.4.0\n      Downloading tensorflow_estimator-2.4.0-py2.py3-none-any.whl (462 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 462 kB 77.7 MB/s \n    \u001b[?25hCollecting typing-extensions~=3.7.4\n      Downloading typing_extensions-3.7.4.3-py3-none-any.whl (22 kB)\n    Requirement already satisfied: wheel~=0.35 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.4.1) (0.37.1)\n    Collecting h5py~=2.10.0\n      Downloading h5py-2.10.0-cp37-cp37m-manylinux1_x86_64.whl (2.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.9 MB 38.3 MB/s \n    \u001b[?25hCollecting gast==0.3.3\n      Downloading gast-0.3.3-py2.py3-none-any.whl (9.7 kB)\n    Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow==2.4.1) (57.4.0)\n    Requirement already satisfied: requests<3,>=2.21.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow==2.4.1) (2.23.0)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow==2.4.1) (1.8.1)\n    Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow==2.4.1) (0.6.1)\n    Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow==2.4.1) (1.0.1)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow==2.4.1) (0.4.6)\n    Requirement already satisfied: google-auth<3,>=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow==2.4.1) (1.35.0)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.4->tensorflow==2.4.1) (3.3.6)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard~=2.4->tensorflow==2.4.1) (4.2.4)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard~=2.4->tensorflow==2.4.1) (4.8)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard~=2.4->tensorflow==2.4.1) (0.2.8)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.4->tensorflow==2.4.1) (1.3.0)\n    Requirement already satisfied: importlib-metadata>=4.4 in /usr/local/lib/python3.7/dist-packages (from markdown>=2.6.8->tensorboard~=2.4->tensorflow==2.4.1) (4.10.0)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=4.4->markdown>=2.6.8->tensorboard~=2.4->tensorflow==2.4.1) (3.7.0)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<3,>=1.6.3->tensorboard~=2.4->tensorflow==2.4.1) (0.4.8)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow==2.4.1) (2021.10.8)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow==2.4.1) (2.10)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow==2.4.1) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow==2.4.1) (3.0.4)\n    Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.4->tensorflow==2.4.1) (3.1.1)\n    Collecting sympy==1.5\n      Downloading sympy-1.5-py2.py3-none-any.whl (5.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5.6 MB 27.2 MB/s \n    \u001b[?25hCollecting google-api-core==1.21.0\n      Downloading google_api_core-1.21.0-py2.py3-none-any.whl (90 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 90 kB 10.6 MB/s \n    \u001b[?25hCollecting protobuf>=3.9.2\n      Downloading protobuf-3.13.0-cp37-cp37m-manylinux1_x86_64.whl (1.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.3 MB 38.5 MB/s \n    \u001b[?25hCollecting googleapis-common-protos==1.52.0\n      Downloading googleapis_common_protos-1.52.0-py2.py3-none-any.whl (100 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 100 kB 9.3 MB/s \n    \u001b[?25hCollecting cirq==0.11.0\n      Downloading cirq-0.11.0-py3-none-any.whl (7.6 kB)\n    Collecting google-auth<3,>=1.6.3\n      Downloading google_auth-1.18.0-py2.py3-none-any.whl (90 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 90 kB 9.8 MB/s \n    \u001b[?25hCollecting cirq-google==0.11.0\n      Downloading cirq_google-0.11.0-py3-none-any.whl (380 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 380 kB 64.0 MB/s \n    \u001b[?25hCollecting cirq-core==0.11.0\n      Downloading cirq_core-0.11.0-py3-none-any.whl (1.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.5 MB 49.6 MB/s \n    \u001b[?25hRequirement already satisfied: sortedcontainers~=2.0 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.11.0->cirq==0.11.0->tensorflow-quantum) (2.4.0)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.11.0->cirq==0.11.0->tensorflow-quantum) (1.4.1)\n    Requirement already satisfied: networkx~=2.4 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.11.0->cirq==0.11.0->tensorflow-quantum) (2.6.3)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.11.0->cirq==0.11.0->tensorflow-quantum) (4.62.3)\n    Requirement already satisfied: matplotlib~=3.0 in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.11.0->cirq==0.11.0->tensorflow-quantum) (3.2.2)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from cirq-core==0.11.0->cirq==0.11.0->tensorflow-quantum) (1.1.5)\n    Requirement already satisfied: google-api-core[grpc]<2.0.0dev,>=1.14.0 in /usr/local/lib/python3.7/dist-packages (from cirq-google==0.11.0->cirq==0.11.0->tensorflow-quantum) (1.26.3)\n    Requirement already satisfied: pytz in /usr/local/lib/python3.7/dist-packages (from google-api-core==1.21.0->tensorflow-quantum) (2018.9)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy==1.5->tensorflow-quantum) (1.2.1)\n    Collecting google-api-core[grpc]<2.0.0dev,>=1.14.0\n      Downloading google_api_core-1.31.5-py2.py3-none-any.whl (93 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 93 kB 1.6 MB/s \n    \u001b[?25h  Downloading google_api_core-1.31.4-py2.py3-none-any.whl (93 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 93 kB 1.6 MB/s \n    \u001b[?25h  Downloading google_api_core-1.31.3-py2.py3-none-any.whl (93 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 93 kB 1.4 MB/s \n    \u001b[?25h  Downloading google_api_core-1.31.2-py2.py3-none-any.whl (93 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 93 kB 1.5 MB/s \n    \u001b[?25h  Downloading google_api_core-1.31.1-py2.py3-none-any.whl (93 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 93 kB 1.2 MB/s \n    \u001b[?25h  Downloading google_api_core-1.31.0-py2.py3-none-any.whl (93 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 93 kB 1.2 MB/s \n    \u001b[?25h  Downloading google_api_core-1.30.0-py2.py3-none-any.whl (93 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 93 kB 1.3 MB/s \n    \u001b[?25h  Downloading google_api_core-1.29.0-py2.py3-none-any.whl (93 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 93 kB 1.3 MB/s \n    \u001b[?25h  Downloading google_api_core-1.28.0-py2.py3-none-any.whl (92 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 92 kB 1.2 MB/s \n    \u001b[?25h  Downloading google_api_core-1.27.0-py2.py3-none-any.whl (93 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 93 kB 1.2 MB/s \n    \u001b[?25h  Downloading google_api_core-1.26.2-py2.py3-none-any.whl (93 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 93 kB 1.2 MB/s \n    \u001b[?25h  Downloading google_api_core-1.26.1-py2.py3-none-any.whl (92 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 92 kB 1.2 MB/s \n    \u001b[?25h  Downloading google_api_core-1.26.0-py2.py3-none-any.whl (92 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 92 kB 1.1 MB/s \n    \u001b[?25h  Downloading google_api_core-1.25.1-py2.py3-none-any.whl (92 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 92 kB 221 kB/s \n    \u001b[?25h  Downloading google_api_core-1.25.0-py2.py3-none-any.whl (92 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 92 kB 164 kB/s \n    \u001b[?25h  Downloading google_api_core-1.24.1-py2.py3-none-any.whl (92 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 92 kB 11.0 MB/s \n    \u001b[?25h  Downloading google_api_core-1.24.0-py2.py3-none-any.whl (91 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 91 kB 9.7 MB/s \n    \u001b[?25h  Downloading google_api_core-1.23.0-py2.py3-none-any.whl (91 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 91 kB 10.6 MB/s \n    \u001b[?25h  Downloading google_api_core-1.22.4-py2.py3-none-any.whl (91 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 91 kB 9.3 MB/s \n    \u001b[?25h  Downloading google_api_core-1.22.3-py2.py3-none-any.whl (91 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 91 kB 9.1 MB/s \n    \u001b[?25h  Downloading google_api_core-1.22.2-py2.py3-none-any.whl (91 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 91 kB 10.1 MB/s \n    \u001b[?25h  Downloading google_api_core-1.22.1-py2.py3-none-any.whl (91 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 91 kB 10.1 MB/s \n    \u001b[?25h  Downloading google_api_core-1.22.0-py2.py3-none-any.whl (91 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 91 kB 8.7 MB/s \n    \u001b[?25hRequirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core==0.11.0->cirq==0.11.0->tensorflow-quantum) (2.8.2)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core==0.11.0->cirq==0.11.0->tensorflow-quantum) (3.0.6)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core==0.11.0->cirq==0.11.0->tensorflow-quantum) (0.11.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib~=3.0->cirq-core==0.11.0->cirq==0.11.0->tensorflow-quantum) (1.3.2)\n    Building wheels for collected packages: wrapt\n      Building wheel for wrapt (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for wrapt: filename=wrapt-1.12.1-cp37-cp37m-linux_x86_64.whl size=68716 sha256=b11797ca1ee6ac2c6d9cbf1cc04efe0c4d8603599985496242fe1a5398b359ef\n      Stored in directory: /root/.cache/pip/wheels/62/76/4c/aa25851149f3f6d9785f6c869387ad82b3fd37582fa8147ac6\n    Successfully built wrapt\n    Installing collected packages: protobuf, googleapis-common-protos, google-auth, typing-extensions, sympy, grpcio, google-api-core, cirq-core, cirq-google, wrapt, tensorflow-estimator, h5py, gast, flatbuffers, cirq, tensorflow-quantum, tensorflow\n      Attempting uninstall: protobuf\n        Found existing installation: protobuf 3.17.3\n        Uninstalling protobuf-3.17.3:\n          Successfully uninstalled protobuf-3.17.3\n      Attempting uninstall: googleapis-common-protos\n        Found existing installation: googleapis-common-protos 1.54.0\n        Uninstalling googleapis-common-protos-1.54.0:\n          Successfully uninstalled googleapis-common-protos-1.54.0\n      Attempting uninstall: google-auth\n        Found existing installation: google-auth 1.35.0\n        Uninstalling google-auth-1.35.0:\n          Successfully uninstalled google-auth-1.35.0\n      Attempting uninstall: typing-extensions\n        Found existing installation: typing-extensions 3.10.0.2\n        Uninstalling typing-extensions-3.10.0.2:\n          Successfully uninstalled typing-extensions-3.10.0.2\n      Attempting uninstall: sympy\n        Found existing installation: sympy 1.7.1\n        Uninstalling sympy-1.7.1:\n          Successfully uninstalled sympy-1.7.1\n      Attempting uninstall: grpcio\n        Found existing installation: grpcio 1.43.0\n        Uninstalling grpcio-1.43.0:\n          Successfully uninstalled grpcio-1.43.0\n      Attempting uninstall: google-api-core\n        Found existing installation: google-api-core 1.26.3\n        Uninstalling google-api-core-1.26.3:\n          Successfully uninstalled google-api-core-1.26.3\n      Attempting uninstall: wrapt\n        Found existing installation: wrapt 1.13.3\n        Uninstalling wrapt-1.13.3:\n          Successfully uninstalled wrapt-1.13.3\n      Attempting uninstall: tensorflow-estimator\n        Found existing installation: tensorflow-estimator 2.7.0\n        Uninstalling tensorflow-estimator-2.7.0:\n          Successfully uninstalled tensorflow-estimator-2.7.0\n      Attempting uninstall: h5py\n        Found existing installation: h5py 3.1.0\n        Uninstalling h5py-3.1.0:\n          Successfully uninstalled h5py-3.1.0\n      Attempting uninstall: gast\n        Found existing installation: gast 0.4.0\n        Uninstalling gast-0.4.0:\n          Successfully uninstalled gast-0.4.0\n      Attempting uninstall: flatbuffers\n        Found existing installation: flatbuffers 2.0\n        Uninstalling flatbuffers-2.0:\n          Successfully uninstalled flatbuffers-2.0\n      Attempting uninstall: tensorflow\n        Found existing installation: tensorflow 2.7.0\n        Uninstalling tensorflow-2.7.0:\n          Successfully uninstalled tensorflow-2.7.0\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    pydata-google-auth 1.3.0 requires google-auth<3.0dev,>=1.25.0; python_version >= \"3.6\", but you have google-auth 1.18.0 which is incompatible.\u001b[0m\n    Successfully installed cirq-0.11.0 cirq-core-0.11.0 cirq-google-0.11.0 flatbuffers-1.12 gast-0.3.3 google-api-core-1.21.0 google-auth-1.18.0 googleapis-common-protos-1.52.0 grpcio-1.32.0 h5py-2.10.0 protobuf-3.13.0 sympy-1.5 tensorflow-2.4.1 tensorflow-estimator-2.4.0 tensorflow-quantum-0.5.1 typing-extensions-3.7.4.3 wrapt-1.12.1\n\n\n\n\n\n```python\n# Update package resources to account for version changes.\nimport importlib, pkg_resources\nimportlib.reload(pkg_resources)\n```\n\n\n\n\n    <module 'pkg_resources' from '/usr/local/lib/python3.7/dist-packages/pkg_resources/__init__.py'>\n\n\n\n\n```python\n#Mounting a google drive\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```python\n#This code part depends where your eecs598 file\nimport sys\nsys.path.append('/content/drive/My Drive')\n```\n\n\n```python\nimport eecs598\nimport torch\nimport torchvision\nimport matplotlib.pyplot as plt\nimport statistics\nimport numpy as np\n```\n\n\n```python\nimport tensorflow as tf\nimport tensorflow_quantum as tfq\n\nimport cirq\nimport sympy\nimport numpy as np\nimport seaborn as sns\nimport collections\n\n# visualization tools\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom cirq.contrib.svg import SVGCircuit\n```\n\n\n```python\n\n# Control qrid size for visualization\nplt.rcParams['figure.figsize'] = (10.0, 8.0)\nplt.rcParams['font.size'] = 16\n```\n\n\n```python\n#Data preparation\nx_train, y_train, x_test, y_test = eecs598.data.cifar10()\n\nprint('Training set:', )\nprint('  data shape:', x_train.shape)\nprint('  labels shape: ', y_train.shape)\nprint('Test set:')\nprint('  data shape: ', x_test.shape)\nprint('  labels shape', y_test.shape)\n```\n\n    Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to ./cifar-10-python.tar.gz\n\n\n\n      0%|          | 0/170498071 [00:00<?, ?it/s]\n\n\n    Extracting ./cifar-10-python.tar.gz to .\n    Training set:\n      data shape: torch.Size([50000, 3, 32, 32])\n      labels shape:  torch.Size([50000])\n    Test set:\n      data shape:  torch.Size([10000, 3, 32, 32])\n      labels shape torch.Size([10000])\n\n\n\n```python\n#Visualize the dataset\nimport random\nfrom torchvision.utils import make_grid\n\nclasses = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\nsamples_per_class = 12\nsamples = []\nfor y, cls in enumerate(classes):\n    plt.text(-4, 34 * y + 18, cls, ha='right')\n    idxs, = (y_train == y).nonzero(as_tuple=True)\n    for i in range(samples_per_class):\n        idx = idxs[random.randrange(idxs.shape[0])].item()\n        samples.append(x_train[idx])\nimg = torchvision.utils.make_grid(samples, nrow=samples_per_class)\nplt.imshow(eecs598.tensor_to_image(img))\nplt.axis('off')\nplt.show()\n#The label data is just a list of 10,000 numbers ranging from 0 to 9, which corresponds to each of the 10 classes in CIFAR-10.\n\n#airplane : 0 automobile : 1 bird : 2 cat : 3 deer : 4 dog : 5 frog : 6 horse : 7 ship : 8 truck : 9\n```\n\n\n```python\nfrom tensorflow.keras.datasets import cifar10\n(train_images, train_labels), (test_images, test_labels) = cifar10.load_data()\n```\n\n    Downloading data from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz\n    170500096/170498071 [==============================] - 11s 0us/step\n\n\n\n```python\ny_train=train_labels.flatten()\ny_test=test_labels.flatten()\n# We have reduced the dimension\n```\n\n\n```python\nx_train=tf.image.rgb_to_grayscale(train_images)\nx_test=tf.image.rgb_to_grayscale(test_images)\n#convert grayscale\n```\n\n\n```python\n#Filter the dataset to keep just the cat  and frog, remove the other classes\ndef filter_36(x, y):\n    keep = (y == 3) | (y == 6)\n    x, y = x[keep], y[keep]\n    y = y == 3\n    return x,y\n```\n\n\n```python\nx_train, y_train = filter_36(x_train, y_train)\nx_test, y_test = filter_36(x_test, y_test)\n\nprint(\"Number of filtered training examples:\", len(x_train))\nprint(\"Number of filtered test examples:\", len(x_test))\n```\n\n    Number of filtered training examples: 10000\n    Number of filtered test examples: 2000\n\n\n\n```python\nplt.imshow(x_train[0, :, :, 0])\nplt.colorbar()\n```\n\n\n```python\n #Resize the image 36x36 to down to 4x4\nx_train_s = tf.image.resize(x_train, (4,4)).numpy()\nx_test_s = tf.image.resize(x_test, (4,4)).numpy()\n```\n\n\n```python\n#Encode the data as quantum circuits\u00b6\n#The first step is to convert to a binary encoding.\nTHRESHOLD = 0.5\n\nx_train_bin = np.array(x_train_s > THRESHOLD, dtype=np.float32)\nx_test_bin = np.array(x_test_s > THRESHOLD, dtype=np.float32)\n#The qubits at pixel indices with values that exceed a threshold, are rotated through an gate.\n```\n\n\n```python\ndef convert_to_circuit(image):\n    \"\"\"Encode truncated classical image into quantum datapoint.\"\"\"\n    values = np.ndarray.flatten(image)\n    qubits = cirq.GridQubit.rect(4, 4)\n    circuit = cirq.Circuit()\n    for i, value in enumerate(values):\n        if value:\n            \n            circuit.append(cirq.X(qubits[i]))\n\n    return circuit\n\n\nx_train_circ = [convert_to_circuit(x) for x in x_train_bin]\nx_test_circ = [convert_to_circuit(x) for x in x_test_bin]\n\n```\n\n\n```python\nSVGCircuit(x_train_circ[0])\n\n```\n\n\n\n\n    \n\n    \n\n\n\n\n```python\n#Convert  Cirq circuits to tensors for tfq\nx_train_tfcirc = tfq.convert_to_tensor(x_train_circ)\nx_test_tfcirc = tfq.convert_to_tensor(x_test_circ)\n```\n\n\n```python\n#Quantum neural network\u00b6\n#add a layer of these gates to a circuit\nclass CircuitLayerBuilder():\n    def __init__(self, data_qubits, readout):\n        self.data_qubits = data_qubits\n        self.readout = readout\n\n    def add_layer(self, circuit, gate, prefix):\n        for i, qubit in enumerate(self.data_qubits):\n            symbol = sympy.Symbol(prefix + '-' + str(i))\n            circuit.append(gate(qubit, self.readout)**symbol)\n\n\n\n\n```\n\n\n```python\ndemo_builder = CircuitLayerBuilder(data_qubits = cirq.GridQubit.rect(4,1),\n                                   readout=cirq.GridQubit(-1,-1))\n\ncircuit = cirq.Circuit()\ndemo_builder.add_layer(circuit, gate = cirq.XX, prefix='xx')\nSVGCircuit(circuit)\n```\n\n\n\n\n    \n\n    \n\n\n\n\n```python\ndef create_quantum_model():\n    \"\"\"Create a QNN model circuit and readout operation to go along with it.\"\"\"\n    data_qubits = cirq.GridQubit.rect(4, 4)  # a 4x4 grid.\n    readout = cirq.GridQubit(-1, -1)         # a single qubit at [-1,-1]\n    circuit = cirq.Circuit()\n\n    # Prepare the readout qubit.\n    circuit.append(cirq.X(readout))\n    circuit.append(cirq.H(readout))\n\n    builder = CircuitLayerBuilder(\n        data_qubits = data_qubits,\n        readout=readout)\n\n    # Then add layers (experiment by adding more).\n    builder.add_layer(circuit, cirq.XX, \"xx1\")\n    builder.add_layer(circuit, cirq.ZZ, \"zz1\")\n\n    # Finally, prepare the readout qubit.\n    circuit.append(cirq.H(readout))\n\n    return circuit, cirq.Z(readout)\n```\n\n\n```python\nmodel_circuit, model_readout = create_quantum_model()\n\n```\n\n\n```python\nmodel = tf.keras.Sequential([\n    # The input is the data-circuit, encoded as a tf.string\n    tf.keras.layers.Input(shape=(), dtype=tf.string),\n    # The PQC layer returns the expected value of the readout gate, range [-1,1].\n    tfq.layers.PQC(model_circuit, model_readout),\n])\n```\n\n\n```python\ny_train_hinge = 2.0*y_train-1.0\ny_test_hinge = 2.0*y_test-1.0\n```\n\n\n```python\ndef hinge_accuracy(y_true, y_pred):\n    y_true = tf.squeeze(y_true) > 0.0\n    y_pred = tf.squeeze(y_pred) > 0.0\n    result = tf.cast(y_true == y_pred, tf.float32)\n\n    return tf.reduce_mean(result)\n```\n\n\n```python\nmodel.compile(\n    loss=tf.keras.losses.Hinge(),\n    optimizer=tf.keras.optimizers.Adam(),\n    metrics=[hinge_accuracy])\n```\n\n\n```python\nprint(model.summary())\n```\n\n    Model: \"sequential_1\"\n    _________________________________________________________________\n    Layer (type)                 Output Shape              Param #   \n    =================================================================\n    pqc_1 (PQC)                  (None, 1)                 32        \n    =================================================================\n    Total params: 32\n    Trainable params: 32\n    Non-trainable params: 0\n    _________________________________________________________________\n    None\n\n\n\n```python\nEPOCHS = 3\nBATCH_SIZE = 128\n\nNUM_EXAMPLES = len(x_train_tfcirc)\n```\n\n\n```python\nx_train_tfcirc_sub = x_train_tfcirc[:NUM_EXAMPLES]\ny_train_hinge_sub = y_train_hinge[:NUM_EXAMPLES]\n\n```\n\n\n```python\nqnn_history = model.fit(\n      x_train_tfcirc_sub, y_train_hinge_sub,\n      batch_size=32,\n      epochs=EPOCHS,\n      verbose=1,\n      validation_data=(x_test_tfcirc, y_test_hinge))\n\nqnn_results = model.evaluate(x_test_tfcirc, y_test)\n```\n\n    Epoch 1/3\n    313/313 [==============================] - 733s 2s/step - loss: 0.9999 - hinge_accuracy: 0.5018 - val_loss: 0.9999 - val_hinge_accuracy: 0.4990\n    Epoch 2/3\n    313/313 [==============================] - 734s 2s/step - loss: 1.0007 - hinge_accuracy: 0.4879 - val_loss: 0.9999 - val_hinge_accuracy: 0.4995\n    Epoch 3/3\n    313/313 [==============================] - 736s 2s/step - loss: 1.0001 - hinge_accuracy: 0.5023 - val_loss: 1.0000 - val_hinge_accuracy: 0.4995\n    63/63 [==============================] - 25s 401ms/step - loss: 1.0000 - hinge_accuracy: 0.4995\n\n\n\n```python\nqnn_accuracy = qnn_results[1]\nqnn_accuracy\n```\n\n\n\n\n    0.4995039701461792\n\n\n\n\n```python\nmodel.predict_classes(x_train_tfcirc[0:7])\n```\n\n    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/sequential.py:450: UserWarning: `model.predict_classes()` is deprecated and will be removed after 2021-01-01. Please use instead:* `np.argmax(model.predict(x), axis=-1)`,   if your model does multi-class classification   (e.g. if it uses a `softmax` last-layer activation).* `(model.predict(x) > 0.5).astype(\"int32\")`,   if your model does binary classification   (e.g. if it uses a `sigmoid` last-layer activation).\n      warnings.warn('`model.predict_classes()` is deprecated and '\n\n\n\n\n\n    array([[0],\n           [0],\n           [0],\n           [0],\n           [0],\n           [0],\n           [0]], dtype=int32)\n\n\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.gridspec import GridSpec\n\ndef format_axes(fig):\n    for i, ax in enumerate(fig.axes):\n        ax.tick_params(labelbottom=False, labelleft=False)\n\nfig = plt.figure(figsize=(10, 10))\n\ngs = GridSpec(3, 3, figure=fig)\nax1 = fig.add_subplot(gs[0, 0])\n# identical to ax1 = plt.subplot(gs.new_subplotspec((0, 0), colspan=3))\n\nfor i in range(3):\n  for j in range(3):\n    ax = fig.add_subplot(gs[i, j])\n    \n    ax.imshow(x_train[i+j, :, :, 0])\n\nfig.suptitle(\"GridSpec\")\nformat_axes(fig)\n\nplt.show()\n```\n\n\n```python\nplt.plot(qnn_history.history['hinge_accuracy'], label='QNN')\n#plt.plot(hybrid_history.history['val_custom_accuracy'], label='Hybrid CNN')\n#plt.title('Quantum vs Hybrid CNN performance')\nplt.xlabel('Epochs')\nplt.legend()\nplt.ylabel('Validation Accuracy')\nplt.show()\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n\n```\n\n\n```python\n\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n\n```\n", "meta": {"hexsha": "bcf7bc37a8b1485df327ca7f43da43f58a484cdb", "size": 796472, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "X_gate.ipynb", "max_stars_repo_name": "WebheadTech/QCourse511-1", "max_stars_repo_head_hexsha": "e8396eb5b292203669eda5d04541d31c3d947803", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "X_gate.ipynb", "max_issues_repo_name": "WebheadTech/QCourse511-1", "max_issues_repo_head_hexsha": "e8396eb5b292203669eda5d04541d31c3d947803", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "X_gate.ipynb", "max_forks_repo_name": "WebheadTech/QCourse511-1", "max_forks_repo_head_hexsha": "e8396eb5b292203669eda5d04541d31c3d947803", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 490.4384236453, "max_line_length": 606978, "alphanum_fraction": 0.9249276811, "converted": true, "num_tokens": 8847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1732882016598637, "lm_q2_score": 0.04208772566276723, "lm_q1q2_score": 0.007293306292054628}}
{"text": "# IPython basics: beyond plain Python\n\nThis short notebook will give you a quick taste of some of IPython's capabilities. IPython is the default \"kernel\" for most Jupyter installations (the kernel is the process that executes the code you type into notebook cells, and it's typically based on a single programming language). \n\nIPython started its life in 2001 as a terminal-based application that offered enhancements over the default Python interactive prompt. You can still use it that way, but here we'll use it through the notebook environment in JupyterLab.\n\nThe focus of IPython is on your Interactive experience, and its features are tailored to the typical workflow of everyday scientific computation and data analysis. In a nutshell, IPython is an interactive Python prompt that:\n\n* Starts by being a strict superset of Python: any valid Python code should behave similarly, at most returning cosmetically improved representations of information, but not different results.\n\n* Offers features to make it easy to run small code fragments (typed directly or as external scripts with the `%run` command) and iterate on their results. Variables from execution stay defined in the kernel and you can incrementally build the state of your analysis.\n\n* Facilitates exploration of your Python environment with the `?` operator and a powerful and extensible tab-completion system.\n\n* Provides direct access to the underlying operating system via a syntax that's not valid Python but is convenient to type: `!cmd arg1 arg2...` is executed by the underlying OS instead of as Python.\n\n* Provides an extensible system of special commands known as \"magics,\" that can perform all manner of transformations on their input, letting you do anything with user input ranging from defining one-off aliases for common operations, to blending multiple programming languages in a single session. Magic commands are marked by one or two `%` characters at their start.\n\nThis notebook is a small introduction to the features of IPython. Our [IPython in depth \ntutorial](https://github.com/ipython/ipython-in-depth) contains many more details on these topics and much more.\n\n## First things first: running code, getting help\n\nIn the notebook, to run a cell of code, hit `Shift-Enter`. This executes the cell and puts the cursor in the next cell below, or makes a new one if you are at the end.  Alternately, you can use:\n    \n- `Alt-Enter` to force the creation of a new cell unconditionally (useful when inserting new content in the middle of an existing notebook).\n- `Control-Enter` executes the cell and keeps the cursor in the same cell, useful for quick experimentation of snippets that you don't need to keep permanently.\n\n## Discovering what you need within IPython itself\n\nIPython tries to make it easy for you to discover things about all your Python tools, objects, variables and libraries (including IPython itself, obviously) with a few keystrokes, and while staying focused on the task at hand. The first key you will want to use is `?`, which can be summoned by itself:\n\n### Asking for help with `?` \n\n\n```python\n?\n```\n\nTyping `object_name?` will print all sorts of details about any object, including docstrings, function definition lines (for call arguments) and constructor details for classes.\n\n\n```python\nimport collections\ncollections.namedtuple?\n```\n\n\n    \u001b[0;31mSignature:\u001b[0m\n    \u001b[0mcollections\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mnamedtuple\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0mtypename\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0mfield_names\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0;34m*\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0mrename\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mFalse\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0mdefaults\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m    \u001b[0mmodule\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n    \u001b[0;31mDocstring:\u001b[0m\n    Returns a new subclass of tuple with named fields.\n    \n    >>> Point = namedtuple('Point', ['x', 'y'])\n    >>> Point.__doc__                   # docstring for the new class\n    'Point(x, y)'\n    >>> p = Point(11, y=22)             # instantiate with positional args or keywords\n    >>> p[0] + p[1]                     # indexable like a plain tuple\n    33\n    >>> x, y = p                        # unpack like a regular tuple\n    >>> x, y\n    (11, 22)\n    >>> p.x + p.y                       # fields also accessible by name\n    33\n    >>> d = p._asdict()                 # convert to a dictionary\n    >>> d['x']\n    11\n    >>> Point(**d)                      # convert from a dictionary\n    Point(x=11, y=22)\n    >>> p._replace(x=100)               # _replace() is like str.replace() but targets named fields\n    Point(x=100, y=22)\n    \u001b[0;31mFile:\u001b[0m      ~/local/conda/lib/python3.9/collections/__init__.py\n    \u001b[0;31mType:\u001b[0m      function\n\n\n\nIf you use _two_ `??` characters, IPython will attempt to dig deeper into the object and show you its source code, if available:\n\n\n```python\ncollections.Counter.most_common??\n```\n\n\n    \u001b[0;31mSignature:\u001b[0m \u001b[0mcollections\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mCounter\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmost_common\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mn\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n    \u001b[0;31mSource:\u001b[0m   \n        \u001b[0;32mdef\u001b[0m \u001b[0mmost_common\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mn\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m        \u001b[0;34m'''List the n most common elements and their counts from the most\u001b[0m\n    \u001b[0;34m        common to the least.  If n is None, then list all element counts.\u001b[0m\n    \u001b[0;34m\u001b[0m\n    \u001b[0;34m        >>> Counter('abracadabra').most_common(3)\u001b[0m\n    \u001b[0;34m        [('a', 5), ('b', 2), ('r', 2)]\u001b[0m\n    \u001b[0;34m\u001b[0m\n    \u001b[0;34m        '''\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m        \u001b[0;31m# Emulate Bag.sortedByCount from Smalltalk\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m        \u001b[0;32mif\u001b[0m \u001b[0mn\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m            \u001b[0;32mreturn\u001b[0m \u001b[0msorted\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mitems\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mkey\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0m_itemgetter\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mreverse\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mTrue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n    \u001b[0;34m\u001b[0m        \u001b[0;32mreturn\u001b[0m \u001b[0m_heapq\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mnlargest\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mn\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mitems\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mkey\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0m_itemgetter\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n    \u001b[0;31mFile:\u001b[0m      ~/local/conda/lib/python3.9/collections/__init__.py\n    \u001b[0;31mType:\u001b[0m      function\n\n\n\nThe `?` character can also be used in conjunction with a shell-like wildcard `*` as a _search_ tool to find names that match a substring in your variables (or the namespace of any library or object):\n\n\n```python\n*int*?\n```\n\n\n    FloatingPointError\n    breakpoint\n    int\n    print\n\n\n### Tab completion\n\nTab completion, especially for attributes, is a convenient way to explore the structure of any object you\u2019re dealing with. Simply type `object_name.<TAB>` to view the object\u2019s attributes. Besides Python objects and keywords, tab completion also works on file and directory names.\n\n\n```python\ncollections.\n```\n\nBefore we move on, this command (whose special `%` syntax we explain below) gives you access to an IPython quick reference card:\n\n\n```python\n%quickref\n```\n\n## Accessing the underlying operating system\n\nAny text prepended with a `!` is sent directly to the underlying OS:\n\n\n```python\n!pwd\n```\n\n    /Users/fperez/research/jupytearth/jupyter-earth/docs/interactive\n\n\nand this syntax can be used in assignments, conveniently capturing command output into a Python variable you can then process further:\n\n\n```python\nfiles = !ls\nprint(\"My current directory's files:\")\nprint(files)\n```\n\n    My current directory's files:\n    ['ipython-beyond-python.ipynb']\n\n\nConversely, Python variables can be expanded when calling system commands. For simple values, `$var` expands the variable into its text form:\n\n\n```python\n!echo $files\n```\n\n    [ipython-beyond-python.ipynb]\n\n\nand more complex expressions can be captured with `{expr}`:\n\n\n```python\n!echo {files[0].upper()}\n```\n\n    IPYTHON-BEYOND-PYTHON.IPYNB\n\n\nNote that all this is available even in multiline blocks. While not as portable as pure Python code to do the same (it will only run in IPython and not as a regular Python script), it can be an extremely convenient way to weave together messy scripting logic that is quite common in data analysis activities:\n\n\n```python\nimport os\nfor i,f in enumerate(files):\n    if f.endswith('ipynb'):\n        !echo {\"%02d\" % i} - \"{os.path.splitext(f)[0]}\"\n    else:\n        print('--')\n```\n\n    00 - ipython-beyond-python\n\n\n## Beyond Python: magic functions\n\nThe IPyhton 'magic' functions are a set of commands, invoked by prepending one or two `%` signs to their name, that live in a namespace separate from your normal Python variables and provide a more command-like interface.  They take flags with `--` and arguments without quotes, parentheses or commas. The motivation behind this system is two-fold:\n    \n- To provide an orthogonal namespace for controlling IPython itself and exposing other system-oriented functionality.\n\n- To expose a calling mode that requires minimal verbosity and typing while working interactively.  Thus the inspiration taken from the classic Unix shell style for commands.\n\n\n```python\n%magic\n```\n\nLine vs cell magics:\n\n\n```python\n%timeit list(range(1000))\n```\n\n    11 \u00b5s \u00b1 122 ns per loop (mean \u00b1 std. dev. of 7 runs, 100000 loops each)\n\n\n\n```python\n%%timeit\nlist(range(10))\nlist(range(100))\n```\n\n    1.01 \u00b5s \u00b1 25.1 ns per loop (mean \u00b1 std. dev. of 7 runs, 1000000 loops each)\n\n\nLike with `!cmd` above, you can capture the return value of any magic by assigning it. For example, with the `-o` flag, `%timeit` returns its output as a data structure in addition to printing the summary, so you can later do computations with it.\n\n\n```python\nt = %timeit -o list(range(100))\nt.best\n```\n\n    786 ns \u00b1 25.6 ns per loop (mean \u00b1 std. dev. of 7 runs, 1000000 loops each)\n\n\n\n\n\n    7.442348900003708e-07\n\n\n\n\n```python\nt.best\n```\n\n\n\n\n    7.325789290007379e-07\n\n\n\n_Note:_ there is no generic mechanism for capturing the output of a cell magic into a variable, though you can work around this if needed by grabbing the `_` variable that automatically stores the last computed result after running a cell magic whose return value you may want.\n\nLine magics can be used even inside code blocks:\n\n\n```python\nfor i in range(1, 5):\n    size = i*100\n    print('size:', size, end=' ')\n    %timeit list(range(size))\n```\n\n    size: 100 100000 loops, best of 3: 1.86 \u00b5s per loop\n    size: 200 100000 loops, best of 3: 2.49 \u00b5s per loop\n    size: 300 100000 loops, best of 3: 4.04 \u00b5s per loop\n    size: 400 100000 loops, best of 3: 6.21 \u00b5s per loop\n\n\nMagics can do anything they want with their input, so it doesn't have to be valid Python. Note that the `bash` magic passes _all_ of its input unmodified to Bash, so `$var` isn't expanded assuming that `var` is a Python variable as `!cmd` does. This lets you paste unmodified Shell scripting code into a cell and you are guaranteed that it will run in a separate Bash process as if it was a script executed at the command line.\n\n\n```bash\n%%bash\necho \"My shell is:\" $SHELL\necho \"My disk usage is:\"\ndf -h\n```\n\n    My shell is: /bin/bash\n    My disk usage is:\n    Filesystem                                                                 Size   Used  Avail Capacity  iused       ifree %iused  Mounted on\n    /dev/disk1s5s1                                                            1.8Ti   14Gi  432Gi     4%   553757 19538475003    0%   /\n    devfs                                                                     199Ki  199Ki    0Bi   100%      690           0  100%   /dev\n    /dev/disk1s4                                                              1.8Ti  1.0Gi  432Gi     1%        3 19539028757    0%   /System/Volumes/VM\n    /dev/disk1s2                                                              1.8Ti  281Mi  432Gi     1%      814 19539027946    0%   /System/Volumes/Preboot\n    /dev/disk1s6                                                              1.8Ti  264Ki  432Gi     1%       19 19539028741    0%   /System/Volumes/Update\n    /dev/disk1s1                                                              1.8Ti  1.4Ti  432Gi    77%  3890131 19535138629    0%   /System/Volumes/Data\n    map auto_home                                                               0Bi    0Bi    0Bi   100%        0           0  100%   /System/Volumes/Data/home\n    /dev/disk2s2                                                              1.8Ti  1.3Ti  481Gi    75% 32911853  4262055426    1%   /Volumes/WD Time Machine Backup\n    /dev/disk2s3                                                              2.7Ti  610Gi  2.1Ti    22%   675768  4294291511    0%   /Volumes/WDSilverData\n    /Library/PreferencePanes/Witch.prefPane/Contents/Helpers/witchdaemon.app  1.8Ti  1.4Ti  385Gi    80%  3730872 19535297888    0%   /private/var/folders/qh/gvcvjg9x2qj0py4gwxt65x3c0010dw/T/AppTranslocation/1A4BB6CE-9FE1-4B38-9920-C49FE0DDAB87\n    /dev/disk3s1                                                              603Mi  396Mi  207Mi    66%      638  4294966641    0%   /Volumes/Slack\n\n\nYou can also capture stdout/err from these subprocesses into Python variables, instead of letting them go directly to stdout/err\n\n\n```bash\n%%bash\necho \"hi, stdout\"\necho \"hello, stderr\" >&2\n```\n\n    hi, stdout\n\n\n    hello, stderr\n\n\n\n```bash\n%%bash --out output --err error\necho \"hi, stdout\"\necho \"hello, stderr\" >&2\n```\n\n\n```python\nprint(error)\nprint(output)\n```\n\n    hello, stderr\n    \n    hi, stdout\n    \n\n\nAnother interesting cell magic: create any file you want locally from the notebook:\n\n\n```python\n%%writefile test.txt\nThis is a test file!\nIt can contain anything I want...\n\nAnd more...\n```\n\n    Writing test.txt\n\n\n\n```python\n!cat test.txt\n```\n\n    This is a test file!\n    It can contain anything I want...\n    \n    And more...\n\n\nMost magic functions have help built into them which you can summon with the usual `?` operator:\n\n\n```python\n%cd?\n```\n\n\n    \u001b[0;31mDocstring:\u001b[0m\n    Change the current working directory.\n    \n    This command automatically maintains an internal list of directories\n    you visit during your IPython session, in the variable _dh. The\n    command %dhist shows this history nicely formatted. You can also\n    do 'cd -<tab>' to see directory history conveniently.\n    \n    Usage:\n    \n      cd 'dir': changes to directory 'dir'.\n    \n      cd -: changes to the last visited directory.\n    \n      cd -<n>: changes to the n-th directory in the directory history.\n    \n      cd --foo: change to directory that matches 'foo' in history\n    \n      cd -b <bookmark_name>: jump to a bookmark set by %bookmark\n         (note: cd <bookmark_name> is enough if there is no\n          directory <bookmark_name>, but a bookmark with the name exists.)\n          'cd -b <tab>' allows you to tab-complete bookmark names.\n    \n    Options:\n    \n    -q: quiet.  Do not print the working directory after the cd command is\n    executed.  By default IPython's cd command does print this directory,\n    since the default prompts do not display path information.\n    \n    Note that !cd doesn't work for this purpose because the shell where\n    !command runs is immediately discarded after executing 'command'.\n    \n    Examples\n    --------\n    ::\n    \n      In [10]: cd parent/child\n      /home/tsuser/parent/child\n    \u001b[0;31mFile:\u001b[0m      ~/local/conda/lib/python3.9/site-packages/IPython/core/magics/osm.py\n\n\n\nThe magic system is easily extensible, you can define your own magic functions with a few lines of code, [as explained in the documentation](https://ipython.readthedocs.io/en/stable/config/custommagics.html).\n\nTo close this section, let's see what other magics are currently defined in the system. You should explore these, as they can be quite useful in everyday work, and they can give you ideas for creating new ones to meet your own needs.\n\n\n```python\n%lsmagic -h\n```\n\n\n\n\n    Available line magics:\n    %alias  %alias_magic  %autoawait  %autocall  %automagic  %autosave  %bookmark  %cat  %cd  %cl  %clear  %colors  %conda  %config  %connect_info  %cp  %d  %dd  %debug  %dhist  %dirs  %dl  %doctest_mode  %dp  %dus  %dx  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %less  %lf  %lk  %ll  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %lx  %macro  %magic  %man  %matplotlib  %mkdir  %more  %mv  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %pip  %popd  %pprint  %precision  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %rep  %rerun  %reset  %reset_selective  %rm  %rmdir  %run  %save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode\n    \n    Available cell magics:\n    %%!  %%HTML  %%SVG  %%bash  %%capture  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%markdown  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile\n    \n    Automagic is ON, % prefix IS NOT needed for line magics.\n\n\n\n## Multi-language integration\n\nThrough the Magic system, IPython makes it possible to create rich integrations with other programming languages. Note that this is separate from the use of entirely separate _kernels_ for Jupyter itself, that are dedicated to executing code in other languages. Here we focus on making calls to other languages from within a mostly-Python, IPython-based session.  \n\nWe've already seen the use of `%%bash` above, and you may want to poke at the `%%script` magic if you'd like to run other arbitrary scripts.  Since this is meant to be a very brief intro we only show one more language integration here, with Fortran. But in [this example](https://nbviewer.jupyter.org/gist/fperez/5b49246af4e340c37549265a90894ce6/polyglot-ds.ipynb) you can see how to interleave within one single session others, including R, Julia and Cython.\n\nTo use the Fortran magic we load an extension we've previously installed:\n\n\n```python\n%load_ext fortranmagic\n```\n\n\n\nAnd with this, we now can type arbitrary Fortran functions that will be compiled, linked and imported for us using the [`f2py`](https://numpy.org/doc/stable/f2py) tool that is central to the SciPy ecosystem:\n\n\n```python\n%%fortran\nsubroutine sinx2(x, y, n)\n    real, intent(in), dimension(n) :: x\n    real, intent(out), dimension(n) :: y\n    !intent(hide) :: n\n    y = sin(x**2)\nend subroutine sinx2\n```\n\nAfter running the above cell, we have a new function in Python called `sinx2` that computes $\\sin(x^2)$ and that understands natively numpy arrays. It even has a docstring!\n\n\n```python\nsinx2?\n```\n\n\n    \u001b[0;31mCall signature:\u001b[0m \u001b[0msinx2\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n    \u001b[0;31mType:\u001b[0m           fortran\n    \u001b[0;31mString form:\u001b[0m    <fortran object>\n    \u001b[0;31mDocstring:\u001b[0m     \n    y = sinx2(x,[n])\n    \n    Wrapper for ``sinx2``.\n    \n    Parameters\n    ----------\n    x : input rank-1 array('f') with bounds (n)\n    \n    Other Parameters\n    ----------------\n    n : input int, optional\n        Default: len(x)\n    \n    Returns\n    -------\n    y : rank-1 array('f') with bounds (n)\n\n\n\nWe can now use it as any other Python function:\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n```\n\n\n```python\nx = np.linspace(0, 2*np.pi, 200)\ny = sinx2(x)\nplt.plot(x, y);\n```\n\n## Rich object displays\n\nIn Python, objects can define how to display themselves both for print statements, via the special `__str__` method, and with a potentially richer representation with `__repr__`.  IPython takes this idea pretty far, allowing you to declare multiple display representations of your objects, that can include images, mathematical representations in LaTeX and arbitrarily rich HTML and JavaScript.\n\nFor example, the [SymPy library for symbolic computing](https://sympy.org) uses this system to display mathematical expressions:\n\n\n```python\nfrom sympy import symbols, I, pi, exp, Rational\n\nx, y = symbols(\"x y\")\nRational(3,2)*pi + exp(I*x) / (x**2 + y)\n```\n\n\n\n\n$\\displaystyle \\frac{3 \\pi}{2} + \\frac{e^{i x}}{x^{2} + y}$\n\n\n\nThis is the system that Pandas takes advantage of to display datframes as a readable, HTML table:\n\n\n```python\nimport pandas as pd\n\npd.DataFrame(dict(x=[3,2,1], y=[10,20,30]))\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>x</th>\n      <th>y</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>3</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2</td>\n      <td>20</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1</td>\n      <td>30</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThe [Xarray library](https://xarray.pydata.org/en/stable/examples/multidimensional-coords.html) makes particularly good use of this system, to provide very informative displays of datasets that describe the structure of the data immediately with a collapsible HTML view. Given the complexity of datasets frequently encountered in the geosciences and that Xarray can read, this can be a very useful feature when interactively exploring data:\n\n\n```python\nimport xarray as xr\n\nxr.tutorial.open_dataset('rasm').load()\n```\n\n\n\n\n<div><svg style=\"position: absolute; width: 0; height: 0; overflow: hidden\">\n<defs>\n<symbol id=\"icon-database\" viewBox=\"0 0 32 32\">\n<path d=\"M16 0c-8.837 0-16 2.239-16 5v4c0 2.761 7.163 5 16 5s16-2.239 16-5v-4c0-2.761-7.163-5-16-5z\"></path>\n<path d=\"M16 17c-8.837 0-16-2.239-16-5v6c0 2.761 7.163 5 16 5s16-2.239 16-5v-6c0 2.761-7.163 5-16 5z\"></path>\n<path d=\"M16 26c-8.837 0-16-2.239-16-5v6c0 2.761 7.163 5 16 5s16-2.239 16-5v-6c0 2.761-7.163 5-16 5z\"></path>\n</symbol>\n<symbol id=\"icon-file-text2\" viewBox=\"0 0 32 32\">\n<path d=\"M28.681 7.159c-0.694-0.947-1.662-2.053-2.724-3.116s-2.169-2.030-3.116-2.724c-1.612-1.182-2.393-1.319-2.841-1.319h-15.5c-1.378 0-2.5 1.121-2.5 2.5v27c0 1.378 1.122 2.5 2.5 2.5h23c1.378 0 2.5-1.122 2.5-2.5v-19.5c0-0.448-0.137-1.23-1.319-2.841zM24.543 5.457c0.959 0.959 1.712 1.825 2.268 2.543h-4.811v-4.811c0.718 0.556 1.584 1.309 2.543 2.268zM28 29.5c0 0.271-0.229 0.5-0.5 0.5h-23c-0.271 0-0.5-0.229-0.5-0.5v-27c0-0.271 0.229-0.5 0.5-0.5 0 0 15.499-0 15.5 0v7c0 0.552 0.448 1 1 1h7v19.5z\"></path>\n<path d=\"M23 26h-14c-0.552 0-1-0.448-1-1s0.448-1 1-1h14c0.552 0 1 0.448 1 1s-0.448 1-1 1z\"></path>\n<path d=\"M23 22h-14c-0.552 0-1-0.448-1-1s0.448-1 1-1h14c0.552 0 1 0.448 1 1s-0.448 1-1 1z\"></path>\n<path d=\"M23 18h-14c-0.552 0-1-0.448-1-1s0.448-1 1-1h14c0.552 0 1 0.448 1 1s-0.448 1-1 1z\"></path>\n</symbol>\n</defs>\n</svg>\n<style>/* CSS stylesheet for displaying xarray objects in jupyterlab.\n *\n */\n\n:root {\n  --xr-font-color0: var(--jp-content-font-color0, rgba(0, 0, 0, 1));\n  --xr-font-color2: var(--jp-content-font-color2, rgba(0, 0, 0, 0.54));\n  --xr-font-color3: var(--jp-content-font-color3, rgba(0, 0, 0, 0.38));\n  --xr-border-color: var(--jp-border-color2, #e0e0e0);\n  --xr-disabled-color: var(--jp-layout-color3, #bdbdbd);\n  --xr-background-color: var(--jp-layout-color0, white);\n  --xr-background-color-row-even: var(--jp-layout-color1, white);\n  --xr-background-color-row-odd: var(--jp-layout-color2, #eeeeee);\n}\n\nhtml[theme=dark],\nbody.vscode-dark {\n  --xr-font-color0: rgba(255, 255, 255, 1);\n  --xr-font-color2: rgba(255, 255, 255, 0.54);\n  --xr-font-color3: rgba(255, 255, 255, 0.38);\n  --xr-border-color: #1F1F1F;\n  --xr-disabled-color: #515151;\n  --xr-background-color: #111111;\n  --xr-background-color-row-even: #111111;\n  --xr-background-color-row-odd: #313131;\n}\n\n.xr-wrap {\n  display: block;\n  min-width: 300px;\n  max-width: 700px;\n}\n\n.xr-text-repr-fallback {\n  /* fallback to plain text repr when CSS is not injected (untrusted notebook) */\n  display: none;\n}\n\n.xr-header {\n  padding-top: 6px;\n  padding-bottom: 6px;\n  margin-bottom: 4px;\n  border-bottom: solid 1px var(--xr-border-color);\n}\n\n.xr-header > div,\n.xr-header > ul {\n  display: inline;\n  margin-top: 0;\n  margin-bottom: 0;\n}\n\n.xr-obj-type,\n.xr-array-name {\n  margin-left: 2px;\n  margin-right: 10px;\n}\n\n.xr-obj-type {\n  color: var(--xr-font-color2);\n}\n\n.xr-sections {\n  padding-left: 0 !important;\n  display: grid;\n  grid-template-columns: 150px auto auto 1fr 20px 20px;\n}\n\n.xr-section-item {\n  display: contents;\n}\n\n.xr-section-item input {\n  display: none;\n}\n\n.xr-section-item input + label {\n  color: var(--xr-disabled-color);\n}\n\n.xr-section-item input:enabled + label {\n  cursor: pointer;\n  color: var(--xr-font-color2);\n}\n\n.xr-section-item input:enabled + label:hover {\n  color: var(--xr-font-color0);\n}\n\n.xr-section-summary {\n  grid-column: 1;\n  color: var(--xr-font-color2);\n  font-weight: 500;\n}\n\n.xr-section-summary > span {\n  display: inline-block;\n  padding-left: 0.5em;\n}\n\n.xr-section-summary-in:disabled + label {\n  color: var(--xr-font-color2);\n}\n\n.xr-section-summary-in + label:before {\n  display: inline-block;\n  content: '\u25ba';\n  font-size: 11px;\n  width: 15px;\n  text-align: center;\n}\n\n.xr-section-summary-in:disabled + label:before {\n  color: var(--xr-disabled-color);\n}\n\n.xr-section-summary-in:checked + label:before {\n  content: '\u25bc';\n}\n\n.xr-section-summary-in:checked + label > span {\n  display: none;\n}\n\n.xr-section-summary,\n.xr-section-inline-details {\n  padding-top: 4px;\n  padding-bottom: 4px;\n}\n\n.xr-section-inline-details {\n  grid-column: 2 / -1;\n}\n\n.xr-section-details {\n  display: none;\n  grid-column: 1 / -1;\n  margin-bottom: 5px;\n}\n\n.xr-section-summary-in:checked ~ .xr-section-details {\n  display: contents;\n}\n\n.xr-array-wrap {\n  grid-column: 1 / -1;\n  display: grid;\n  grid-template-columns: 20px auto;\n}\n\n.xr-array-wrap > label {\n  grid-column: 1;\n  vertical-align: top;\n}\n\n.xr-preview {\n  color: var(--xr-font-color3);\n}\n\n.xr-array-preview,\n.xr-array-data {\n  padding: 0 5px !important;\n  grid-column: 2;\n}\n\n.xr-array-data,\n.xr-array-in:checked ~ .xr-array-preview {\n  display: none;\n}\n\n.xr-array-in:checked ~ .xr-array-data,\n.xr-array-preview {\n  display: inline-block;\n}\n\n.xr-dim-list {\n  display: inline-block !important;\n  list-style: none;\n  padding: 0 !important;\n  margin: 0;\n}\n\n.xr-dim-list li {\n  display: inline-block;\n  padding: 0;\n  margin: 0;\n}\n\n.xr-dim-list:before {\n  content: '(';\n}\n\n.xr-dim-list:after {\n  content: ')';\n}\n\n.xr-dim-list li:not(:last-child):after {\n  content: ',';\n  padding-right: 5px;\n}\n\n.xr-has-index {\n  font-weight: bold;\n}\n\n.xr-var-list,\n.xr-var-item {\n  display: contents;\n}\n\n.xr-var-item > div,\n.xr-var-item label,\n.xr-var-item > .xr-var-name span {\n  background-color: var(--xr-background-color-row-even);\n  margin-bottom: 0;\n}\n\n.xr-var-item > .xr-var-name:hover span {\n  padding-right: 5px;\n}\n\n.xr-var-list > li:nth-child(odd) > div,\n.xr-var-list > li:nth-child(odd) > label,\n.xr-var-list > li:nth-child(odd) > .xr-var-name span {\n  background-color: var(--xr-background-color-row-odd);\n}\n\n.xr-var-name {\n  grid-column: 1;\n}\n\n.xr-var-dims {\n  grid-column: 2;\n}\n\n.xr-var-dtype {\n  grid-column: 3;\n  text-align: right;\n  color: var(--xr-font-color2);\n}\n\n.xr-var-preview {\n  grid-column: 4;\n}\n\n.xr-var-name,\n.xr-var-dims,\n.xr-var-dtype,\n.xr-preview,\n.xr-attrs dt {\n  white-space: nowrap;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  padding-right: 10px;\n}\n\n.xr-var-name:hover,\n.xr-var-dims:hover,\n.xr-var-dtype:hover,\n.xr-attrs dt:hover {\n  overflow: visible;\n  width: auto;\n  z-index: 1;\n}\n\n.xr-var-attrs,\n.xr-var-data {\n  display: none;\n  background-color: var(--xr-background-color) !important;\n  padding-bottom: 5px !important;\n}\n\n.xr-var-attrs-in:checked ~ .xr-var-attrs,\n.xr-var-data-in:checked ~ .xr-var-data {\n  display: block;\n}\n\n.xr-var-data > table {\n  float: right;\n}\n\n.xr-var-name span,\n.xr-var-data,\n.xr-attrs {\n  padding-left: 25px !important;\n}\n\n.xr-attrs,\n.xr-var-attrs,\n.xr-var-data {\n  grid-column: 1 / -1;\n}\n\ndl.xr-attrs {\n  padding: 0;\n  margin: 0;\n  display: grid;\n  grid-template-columns: 125px auto;\n}\n\n.xr-attrs dt,\n.xr-attrs dd {\n  padding: 0;\n  margin: 0;\n  float: left;\n  padding-right: 10px;\n  width: auto;\n}\n\n.xr-attrs dt {\n  font-weight: normal;\n  grid-column: 1;\n}\n\n.xr-attrs dt:hover span {\n  display: inline-block;\n  background: var(--xr-background-color);\n  padding-right: 10px;\n}\n\n.xr-attrs dd {\n  grid-column: 2;\n  white-space: pre-wrap;\n  word-break: break-all;\n}\n\n.xr-icon-database,\n.xr-icon-file-text2 {\n  display: inline-block;\n  vertical-align: middle;\n  width: 1em;\n  height: 1.5em !important;\n  stroke-width: 0;\n  stroke: currentColor;\n  fill: currentColor;\n}\n</style><pre class='xr-text-repr-fallback'>&lt;xarray.Dataset&gt;\nDimensions:  (time: 36, x: 275, y: 205)\nCoordinates:\n  * time     (time) object 1980-09-16 12:00:00 ... 1983-08-17 00:00:00\n    xc       (y, x) float64 189.2 189.4 189.6 189.7 ... 17.65 17.4 17.15 16.91\n    yc       (y, x) float64 16.53 16.78 17.02 17.27 ... 28.26 28.01 27.76 27.51\nDimensions without coordinates: x, y\nData variables:\n    Tair     (time, y, x) float64 nan nan nan nan nan ... 29.8 28.66 28.19 28.21\nAttributes:\n    title:                     /workspace/jhamman/processed/R1002RBRxaaa01a/l...\n    institution:               U.W.\n    source:                    RACM R1002RBRxaaa01a\n    output_frequency:          daily\n    output_mode:               averaged\n    convention:                CF-1.4\n    references:                Based on the initial model of Liang et al., 19...\n    comment:                   Output from the Variable Infiltration Capacity...\n    nco_openmp_thread_number:  1\n    NCO:                       netCDF Operators version 4.7.9 (Homepage = htt...\n    history:                   Fri Aug  7 17:57:38 2020: ncatted -a bounds,,d...</pre><div class='xr-wrap' hidden><div class='xr-header'><div class='xr-obj-type'>xarray.Dataset</div></div><ul class='xr-sections'><li class='xr-section-item'><input id='section-15afd890-f6ed-48e3-8dc5-a3d6956431b6' class='xr-section-summary-in' type='checkbox' disabled ><label for='section-15afd890-f6ed-48e3-8dc5-a3d6956431b6' class='xr-section-summary'  title='Expand/collapse section'>Dimensions:</label><div class='xr-section-inline-details'><ul class='xr-dim-list'><li><span class='xr-has-index'>time</span>: 36</li><li><span>x</span>: 275</li><li><span>y</span>: 205</li></ul></div><div class='xr-section-details'></div></li><li class='xr-section-item'><input id='section-b94413e6-b52a-467d-b6cd-d389aeb73f30' class='xr-section-summary-in' type='checkbox'  checked><label for='section-b94413e6-b52a-467d-b6cd-d389aeb73f30' class='xr-section-summary' >Coordinates: <span>(3)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><ul class='xr-var-list'><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>time</span></div><div class='xr-var-dims'>(time)</div><div class='xr-var-dtype'>object</div><div class='xr-var-preview xr-preview'>1980-09-16 12:00:00 ... 1983-08-...</div><input id='attrs-1a5a357e-50a7-4e8f-8c9d-2df711fe3d89' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-1a5a357e-50a7-4e8f-8c9d-2df711fe3d89' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-c238fda8-5b5a-4006-b5dc-ffaf4d095a6c' class='xr-var-data-in' type='checkbox'><label for='data-c238fda8-5b5a-4006-b5dc-ffaf4d095a6c' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>time</dd><dt><span>type_preferred :</span></dt><dd>int</dd></dl></div><div class='xr-var-data'><pre>array([cftime.DatetimeNoLeap(1980, 9, 16, 12, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1980, 10, 17, 0, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1980, 11, 16, 12, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1980, 12, 17, 0, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1981, 1, 17, 0, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1981, 2, 15, 12, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1981, 3, 17, 0, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1981, 4, 16, 12, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1981, 5, 17, 0, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1981, 6, 16, 12, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1981, 7, 17, 0, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1981, 8, 17, 0, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1981, 9, 16, 12, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1981, 10, 17, 0, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1981, 11, 16, 12, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1981, 12, 17, 0, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1982, 1, 17, 0, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1982, 2, 15, 12, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1982, 3, 17, 0, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1982, 4, 16, 12, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1982, 5, 17, 0, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1982, 6, 16, 12, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1982, 7, 17, 0, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1982, 8, 17, 0, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1982, 9, 16, 12, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1982, 10, 17, 0, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1982, 11, 16, 12, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1982, 12, 17, 0, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1983, 1, 17, 0, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1983, 2, 15, 12, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1983, 3, 17, 0, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1983, 4, 16, 12, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1983, 5, 17, 0, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1983, 6, 16, 12, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1983, 7, 17, 0, 0, 0, 0, has_year_zero=True),\n       cftime.DatetimeNoLeap(1983, 8, 17, 0, 0, 0, 0, has_year_zero=True)],\n      dtype=object)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>xc</span></div><div class='xr-var-dims'>(y, x)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>189.2 189.4 189.6 ... 17.15 16.91</div><input id='attrs-ac254b13-7410-46b0-809f-82cc98b23230' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-ac254b13-7410-46b0-809f-82cc98b23230' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-0834c074-5eeb-40b2-8b3a-4a264c44efef' class='xr-var-data-in' type='checkbox'><label for='data-0834c074-5eeb-40b2-8b3a-4a264c44efef' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>longitude of grid cell center</dd><dt><span>units :</span></dt><dd>degrees_east</dd></dl></div><div class='xr-var-data'><pre>array([[189.22293223, 189.38990916, 189.55836619, ..., 293.77906088,\n        294.0279241 , 294.27439931],\n       [188.96836986, 189.13470591, 189.30253733, ..., 294.05584005,\n        294.30444387, 294.55065969],\n       [188.71234264, 188.87800731, 189.04515208, ..., 294.335053  ,\n        294.58337453, 294.8292928 ],\n       ...,\n       [124.04724025, 123.88362026, 123.71852016, ...,  16.83171831,\n         16.58436953,  16.33949649],\n       [123.78686428, 123.62254238, 123.45672512, ...,  17.11814486,\n         16.87043749,  16.62518298],\n       [123.52798366, 123.36295986, 123.1964407 , ...,  17.40209947,\n         17.1540526 ,  16.90845095]])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>yc</span></div><div class='xr-var-dims'>(y, x)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>16.53 16.78 17.02 ... 27.76 27.51</div><input id='attrs-5d713a9f-2ee3-443f-8535-0d1e7d0f0174' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-5d713a9f-2ee3-443f-8535-0d1e7d0f0174' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-f00cf79a-342c-4fa3-8085-d4cacccabb98' class='xr-var-data-in' type='checkbox'><label for='data-f00cf79a-342c-4fa3-8085-d4cacccabb98' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>long_name :</span></dt><dd>latitude of grid cell center</dd><dt><span>units :</span></dt><dd>degrees_north</dd></dl></div><div class='xr-var-data'><pre>array([[16.53498637, 16.7784556 , 17.02222429, ..., 27.36301592,\n        27.11811045, 26.87289026],\n       [16.69397341, 16.93865381, 17.18364512, ..., 27.5847719 ,\n        27.33821848, 27.0913656 ],\n       [16.85219179, 17.09808909, 17.34430872, ..., 27.80584314,\n        27.55764558, 27.30915621],\n       ...,\n       [17.31179033, 17.56124674, 17.81104646, ..., 28.4502485 ,\n        28.19718339, 27.94384744],\n       [17.15589701, 17.40414034, 17.65272318, ..., 28.23129632,\n        27.97989251, 27.72821596],\n       [16.99919497, 17.24622904, 17.49358736, ..., 28.01160028,\n        27.76185586, 27.51182726]])</pre></div></li></ul></div></li><li class='xr-section-item'><input id='section-419c39c1-b2e4-45d4-bdd0-e7fff31b4e75' class='xr-section-summary-in' type='checkbox'  checked><label for='section-419c39c1-b2e4-45d4-bdd0-e7fff31b4e75' class='xr-section-summary' >Data variables: <span>(1)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><ul class='xr-var-list'><li class='xr-var-item'><div class='xr-var-name'><span>Tair</span></div><div class='xr-var-dims'>(time, y, x)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>nan nan nan ... 28.66 28.19 28.21</div><input id='attrs-4667fadf-5f4b-4a49-adeb-fcfdf51905cf' class='xr-var-attrs-in' type='checkbox' ><label for='attrs-4667fadf-5f4b-4a49-adeb-fcfdf51905cf' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-4ea58b7a-36bb-4c50-a5f6-e60383a263e5' class='xr-var-data-in' type='checkbox'><label for='data-4ea58b7a-36bb-4c50-a5f6-e60383a263e5' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'><dt><span>units :</span></dt><dd>C</dd><dt><span>long_name :</span></dt><dd>Surface air temperature</dd><dt><span>type_preferred :</span></dt><dd>double</dd><dt><span>time_rep :</span></dt><dd>instantaneous</dd></dl></div><div class='xr-var-data'><pre>array([[[        nan,         nan,         nan, ...,         nan,\n                 nan,         nan],\n        [        nan,         nan,         nan, ...,         nan,\n                 nan,         nan],\n        [        nan,         nan,         nan, ...,         nan,\n                 nan,         nan],\n        ...,\n        [        nan,         nan,         nan, ..., 27.03290153,\n         27.03125761, 27.33531541],\n        [        nan,         nan,         nan, ..., 27.2784053 ,\n         26.80261869, 27.08603517],\n        [        nan,         nan,         nan, ..., 27.02344402,\n         26.56473862, 26.73064933]],\n\n       [[        nan,         nan,         nan, ...,         nan,\n                 nan,         nan],\n        [        nan,         nan,         nan, ...,         nan,\n                 nan,         nan],\n        [        nan,         nan,         nan, ...,         nan,\n                 nan,         nan],\n...\n        [        nan,         nan,         nan, ..., 27.8597472 ,\n         27.82928439, 28.09249224],\n        [        nan,         nan,         nan, ..., 27.89704094,\n         27.31104941, 27.67387171],\n        [        nan,         nan,         nan, ..., 27.46837113,\n         27.0088944 , 27.23017976]],\n\n       [[        nan,         nan,         nan, ...,         nan,\n                 nan,         nan],\n        [        nan,         nan,         nan, ...,         nan,\n                 nan,         nan],\n        [        nan,         nan,         nan, ...,         nan,\n                 nan,         nan],\n        ...,\n        [        nan,         nan,         nan, ..., 28.95929072,\n         28.87672039, 29.04890862],\n        [        nan,         nan,         nan, ..., 29.036132  ,\n         28.42273578, 28.68721201],\n        [        nan,         nan,         nan, ..., 28.66381585,\n         28.18595533, 28.20753022]]])</pre></div></li></ul></div></li><li class='xr-section-item'><input id='section-7fd4725f-4017-44df-bcf5-675bdad36f2f' class='xr-section-summary-in' type='checkbox'  ><label for='section-7fd4725f-4017-44df-bcf5-675bdad36f2f' class='xr-section-summary' >Attributes: <span>(11)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><dl class='xr-attrs'><dt><span>title :</span></dt><dd>/workspace/jhamman/processed/R1002RBRxaaa01a/lnd/temp/R1002RBRxaaa01a.vic.ha.1979-09-01.nc</dd><dt><span>institution :</span></dt><dd>U.W.</dd><dt><span>source :</span></dt><dd>RACM R1002RBRxaaa01a</dd><dt><span>output_frequency :</span></dt><dd>daily</dd><dt><span>output_mode :</span></dt><dd>averaged</dd><dt><span>convention :</span></dt><dd>CF-1.4</dd><dt><span>references :</span></dt><dd>Based on the initial model of Liang et al., 1994, JGR, 99, 14,415- 14,429.</dd><dt><span>comment :</span></dt><dd>Output from the Variable Infiltration Capacity (VIC) model.</dd><dt><span>nco_openmp_thread_number :</span></dt><dd>1</dd><dt><span>NCO :</span></dt><dd>netCDF Operators version 4.7.9 (Homepage = http://nco.sf.net, Code = http://github.com/nco/nco)</dd><dt><span>history :</span></dt><dd>Fri Aug  7 17:57:38 2020: ncatted -a bounds,,d,, rasm.nc\nTue Dec 27 14:15:22 2016: ncatted -a dimensions,,d,, rasm.nc rasm.nc\nTue Dec 27 13:38:40 2016: ncks -3 rasm.nc rasm.nc\nhistory deleted for brevity</dd></dl></div></li></ul></div></div>\n\n\n\nAgain, we're only scratching the surface of these capabilities here - you can read more in the IPython docs and in the [IPython in depth tutorial](https://github.com/ipython/ipython-in-depth), particularly in the notebooks that illustrate the [rich output](https://nbviewer.jupyter.org/github/ipython/ipython-in-depth/blob/master/examples/IPython%20Kernel/Rich%20Output.ipynb) and [custom display logic](https://nbviewer.jupyter.org/github/ipython/ipython-in-depth/blob/master/examples/IPython%20Kernel/Custom%20Display%20Logic.ipynb) that powers these capabilities.\n", "meta": {"hexsha": "c354234701b8cf5523b5e37c66047ecbccd9cee1", "size": 103584, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/interactive/ipython-basics.ipynb", "max_stars_repo_name": "espg/jupyter-earth", "max_stars_repo_head_hexsha": "2cc1842516073f1031efa68e7d9ccfc6a338b602", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2021-01-31T21:14:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T18:16:18.000Z", "max_issues_repo_path": "docs/interactive/ipython-basics.ipynb", "max_issues_repo_name": "espg/jupyter-earth", "max_issues_repo_head_hexsha": "2cc1842516073f1031efa68e7d9ccfc6a338b602", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 87, "max_issues_repo_issues_event_min_datetime": "2020-07-28T12:14:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T18:56:59.000Z", "max_forks_repo_path": "docs/interactive/ipython-basics.ipynb", "max_forks_repo_name": "espg/jupyter-earth", "max_forks_repo_head_hexsha": "2cc1842516073f1031efa68e7d9ccfc6a338b602", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-08-08T23:41:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T07:55:09.000Z", "avg_line_length": 56.479825518, "max_line_length": 30224, "alphanum_fraction": 0.6688774328, "converted": true, "num_tokens": 14456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06371499069622688, "lm_q2_score": 0.11436853825632722, "lm_q1q2_score": 0.007286990350942956}}
{"text": "```python\nimport pandas as pd\nfrom PIL import Image, ImageDraw\nfrom pathlib import Path\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2 as cv\n```\n\n\n```python\ndef get_frame_from_video(frame, video):\n    frame = frame - 1\n    !ffmpeg \\\n        -hide_banner \\\n        -loglevel fatal \\\n        -nostats \\\n        -i $video -vf \"select=eq(n\\,$frame)\" -vframes 1 frame.png\n    img = Image.open('frame.png')\n    os.remove('frame.png')\n    return img\n\ndef annotate_frame(img, xc, yc, r, col = (57, 255, 20)):\n    draw = ImageDraw.Draw(img)\n    for x, y in zip(xc, yc):\n        draw.ellipse((x-r, y-r, x+r, y+r), fill=col, outline='black')\n    return img\n\n# code from: https://www.kaggle.com/robikscube/nfl-helmet-assignment-getting-started-guide\ndef add_track_features(tracks, fps=59.94, snap_frame=10):\n    \"\"\"\n    Add column features helpful for syncing with video data.\n    \"\"\"\n    tracks = tracks.copy()\n    tracks[\"game_play\"] = (\n        tracks[\"gameKey\"].astype(\"str\")\n        + \"_\"\n        + tracks[\"playID\"].astype(\"str\").str.zfill(6)\n    )\n    tracks[\"time\"] = pd.to_datetime(tracks[\"time\"])\n    snap_dict = (\n        tracks.query('event == \"ball_snap\"')\n        .groupby(\"game_play\")[\"time\"]\n        .first()\n        .to_dict()\n    )\n    tracks[\"snap\"] = tracks[\"game_play\"].map(snap_dict)\n    tracks[\"isSnap\"] = tracks[\"snap\"] == tracks[\"time\"]\n    tracks[\"team\"] = tracks[\"player\"].str[0].replace(\"H\", \"Home\").replace(\"V\", \"Away\")\n    tracks[\"snap_offset\"] = (tracks[\"time\"] - tracks[\"snap\"]).astype(\n        \"timedelta64[ms]\"\n    ) / 1_000\n    # Estimated video frame\n    tracks[\"est_frame\"] = (\n        ((tracks[\"snap_offset\"] * fps) + snap_frame).round().astype(\"int\")\n    )\n    return tracks\n\ndef add_video_features(videos):\n    videos['game_play'] = videos['video_frame'].apply(lambda x: '_'.join(x.split('_')[:2]))\n    videos['camera'] = videos['video_frame'].apply(lambda x: x.split('_')[2])\n    videos['frame'] = videos['video_frame'].apply(lambda x: x.split('_')[-1])\n    videos['xc'] = (videos['left'] + videos['width']/2).astype(int).values\n    videos['yc'] = (videos['top'] + videos['height']/2).astype(int).values\n    return videos\n\n\ndef annotate_field(xc, yc, player, r = 10, width = 3, col = [(27, 3, 163), (255, 7, 58)], crop = None):\n    field = Image.open('../input/nflhelmet-helper-dataset/field.png')\n    w, h = field.size\n    zero = (68,68)\n    fs = (2424,1100)\n    draw = ImageDraw.Draw(field)\n    xc, yc = xc*fs[0]/120 + zero[0], (1 - yc/53.3)*fs[1] + zero[1]\n    for x, y, p in zip(xc, yc, player):\n        c = col[0] if p[0] == 'H' else col[1]\n        draw.ellipse((x-r, y-r, x+r, y+r), fill=c, width=width, outline = 'black')\n    if isinstance(crop, float):\n#         cp = [xc.min() - crop*w, yc.min() - crop*h, xc.max() + crop*w, yc.max() + crop*h]\n        cp = [xc.min() - crop*w, 0, xc.max() + crop*2*w, h]\n        return field.crop(cp)\n    else:\n        return field\n    \n    \nclass show_play_with_tracking():\n    \n    def __init__(self, video_df = None, track_df = None):\n        if video_df is None:\n            video_df = pd.read_csv('../input/nfl-health-and-safety-helmet-assignment/train_baseline_helmets.csv')\n        self.video_df = add_video_features(video_df)\n        if track_df is None:\n            tracking_df = pd.read_csv('../input/nfl-health-and-safety-helmet-assignment/train_player_tracking.csv')\n            tracking_df = add_track_features(tracking_df)\n        self.tracking_df = tracking_df.query(\"est_frame > 0\")\n       \n    def __call__(self, game_play, frame, img_size = 800, video_folder = '../input/nfl-health-and-safety-helmet-assignment/train/'):\n        \n        camera = 'Sideline'\n        frame_side = get_frame_from_video(frame, video_folder + game_play + '_' + camera + '.mp4')\n        df = self.video_df.query(f\"game_play == '{game_play}' and frame == '{frame}' and camera == '{camera}'\")\n        frame_side = annotate_frame(frame_side, df.xc, df.yc, 10)\n\n        camera = 'Endzone'\n        frame_end = get_frame_from_video(frame, video_folder + game_play + '_' + camera + '.mp4')\n        df = self.video_df.query(f\"game_play == '{game_play}' and frame == '{frame}' and camera == '{camera}'\")\n        frame_end = annotate_frame(frame_end, df.xc, df.yc, 10)\n\n        frames = self.tracking_df['est_frame'].values\n        if frame not in frames:\n            index = np.absolute(frames-frame).argmin()\n            frame = frames[index]\n        df = self.tracking_df.query(f\"game_play == '{game_play}' and est_frame == {frame}\")\n        field = annotate_field(df.x, df.y, df.player, 20, crop = 0.01)\n\n\n        wf, hf = field.size\n        wc, hc = frame_side.size\n        field = field.resize((int(wf*2*hc/hf), 2*hc))\n        wf, hf = field.size\n\n        img = Image.new('RGB', (wf+wc+20, 2*hc+20))\n        img.paste(im=field, box=(5, 10))\n        img.paste(im=frame_side, box=(wf+15, 5))\n        img.paste(im=frame_end, box=(wf+15, hc+15))\n        img.thumbnail((img_size,img_size))\n        return img\n    \nspwt = show_play_with_tracking()\n\n# TODO, add interpolation of tracking_df and replace nearest\nclass get_keypoints():\n    \n    def __init__(self, video_df = None, track_df = None):\n        if video_df is None:\n            video_df = pd.read_csv('../input/nfl-health-and-safety-helmet-assignment/train_baseline_helmets.csv')\n        self.video_df = add_video_features(video_df)\n        if track_df is None:\n            tracking_df = pd.read_csv('../input/nfl-health-and-safety-helmet-assignment/train_player_tracking.csv')\n            tracking_df = add_track_features(tracking_df)\n        self.tracking_df = tracking_df.query(\"est_frame > 0\")\n            \n    def __call__(self, game_play, frame, normalized = True):\n        keypoints = dict()\n        keypoints['Sideline'] = self.video_df.query(\n            f\"game_play == '{game_play}' and frame == '{frame}' and camera == 'Sideline'\")[['xc', 'yc']].values\n        keypoints['Endzone'] = self.video_df.query(\n            f\"game_play == '{game_play}' and frame == '{frame}' and camera == 'Endzone'\")[['xc', 'yc']].values\n        \n        frames = self.tracking_df['est_frame'].values\n        if frame not in frames:\n            index = np.absolute(frames-frame).argmin()\n            frame = frames[index]\n        keypoints['Tracking'] = self.tracking_df.query(\n            f\"game_play == '{game_play}' and est_frame == {frame}\")[['x', 'y']].values\n    \n        if normalized:\n            for k, v in keypoints.items():\n                keypoints[k] = (v - v.min(axis = 0)) / (v.max(axis = 0) - v.min(axis = 0))\n                \n        keypoints['Sideline'][:,1] = 1-keypoints['Sideline'][:,1]\n                \n        self.keypoints = keypoints\n            \n        return keypoints\n    \n    def plot(self, add_no = False):\n        if not hasattr(self, 'keypoints'):\n            print('you must run the function first...')\n        else:\n            kp = self.keypoints\n            plt.figure(figsize=(6, 6))\n            plt.scatter(kp['Endzone'][:,0], kp['Endzone'][:,1], marker = 'x', color = 'red', label = 'Endzone')\n            plt.scatter(kp['Sideline'][:,0], kp['Sideline'][:,1], marker = '^', color = 'red', label = 'Sideline')\n            plt.scatter(kp['Tracking'][:,0], kp['Tracking'][:,1], marker = 'o', color = 'green', label = 'Tracking')  \n            plt.legend();\n    \nget_kp = get_keypoints()\n```\n\n\n```python\nspwt('57583_000082', 10)\n```\n\n\n```python\nvideoframes\n```\n\nWhat I wanted to do is to map each player from tracking data to the camera data like this:\n\n\n\n\nThe same data can be normalized and viewed on the same plot:\n\n\n```python\nk = get_kp('57583_000082', 12)\nget_kp.plot(True)\n```\n\n# Point Cloud Registration\n\nSo, a good portion of this comp comes down to point-cloud registration. There are plenty of methods that perform this taks. For example, OpenCV have `cv.findHomography`. As you can see below, this doesn't perform well. The main reason is that although the function uses Random sample consensus (RANSAC) to filter outliers, the clouds of points must be roughly alinged already.\n\n\n```python\nsrcPoints = k['Tracking'].astype('float32').reshape(-1,1,2)\ndstPoints = k['Sideline'].astype('float32').reshape(-1,1,2)\nM, mask = cv.findHomography(srcPoints, dstPoints, cv.RANSAC)\nprint(mask.sum())\ntfmdPoints = cv.perspectiveTransform(srcPoints,M)\nplt.scatter(srcPoints[:,0,0], srcPoints[:,0,1], marker = 'o', color = 'red', label = 'source')\nplt.scatter(dstPoints[:,0,0], dstPoints[:,0,1], marker = '^', color = 'green', label = 'target')  \nplt.scatter(tfmdPoints[:,0,0], tfmdPoints[:,0,1], marker = 'o', color = 'blue', label = 'result')\nplt.legend();\n```\n\n# Pure Pytorch implementation (using gradient descent)\n\nSo, isntead of using open CV, I decided to do this my won using pytorch. The idea here is to solve the folowing problem:\n\n\\begin{equation}\n\\begin{bmatrix} x^{'} \\\\ y^{'} \\\\ 1 \\end{bmatrix} = H \\begin{bmatrix} x \\\\ y \\\\ 1 \\end{bmatrix} = \\begin{bmatrix} h_{11} & h_{12} & h_{13} \\\\ h_{21} & h_{22} & h_{23} \\\\ h_{31} & h_{32} & h_{33} \\end{bmatrix} \\begin{bmatrix} x \\\\ y \\\\ 1 \\end{bmatrix}\n\\end{equation}\n\nwhere $H$ is a transformation matrix (that I want to find) and $(x', y')$ is the transformed coorinates of a point $(x, y)$.\n\nThe optimization problem is to find $H$ such as $(x', y')$ is as close as possible to some ground truth $(x_t, y_t)$ cloud of points.\n\n\n```python\nimport torch\n```\n\n\n```python\ndef min_mse(preds, targets):\n    d = torch.cdist(preds.squeeze(2), targets.squeeze(2))\n    loss = (d.min(dim = 1).values**2).mean().sqrt()\n    return loss\n```\n\n\n```python\ndef step(src, trg, m, lr = 3e-3, prt = True):\n    preds = torch.matmul(m, src) # Homography transform\n    loss = min_mse(preds, trg)   # mse between the closes pair of points\n    if prt: print(f'loss: {(loss.item()):.5f}')\n    loss.backward()\n    m.data -= lr * m.grad.data\n    m.grad = None\n```\n\n\n```python\ndef fit_predict(src, trg, init_rot = 0, lr = 3e-3, n_steps = 10000, verbose = True):\n    t = np.pi * init_rot / 180\n    m = torch.tensor([[np.cos(t),-np.sin(t), 0],\n                      [np.sin(t), np.cos(t), 0],\n                      [        0,         0, 1]], dtype = torch.double)\n    m.requires_grad_()\n    for i in range(n_steps): \n        if i % (n_steps//10) and verbose:\n            step(src, trg, m, lr=lr, prt=False)\n        else:\n            step(src, trg, m, lr=lr)\n            \n    with torch.no_grad():\n        tfm = torch.matmul(m, src)\n        \n    if verbose:\n        plt.scatter(src[:,0], src[:,1], marker = 'o', color = 'red', label = 'source')\n        plt.scatter(trg[:,0], trg[:,1], marker = '^', color = 'green', label = 'target')  \n        plt.scatter(tfm[:,0], tfm[:,1], marker = 'o', color = 'blue', label = 'result')\n        plt.legend();\n        \n    return tfm\n```\n\n\n```python\nk = get_kp('57583_000082', 1, True)\nsrc = torch.cat([torch.tensor(k['Tracking']), torch.ones(len(k['Tracking'])).unsqueeze(1)], axis = -1).unsqueeze(2)\ntrg = torch.cat([torch.tensor(k['Sideline']), torch.ones(len(k['Sideline'])).unsqueeze(1)], axis = -1).unsqueeze(2)\ntfm = fit_predict(src, trg)\n```\n\n\n```python\nk = get_kp('57597_000658', 1, True)\nsrc = torch.cat([torch.tensor(k['Tracking']), torch.ones(len(k['Tracking'])).unsqueeze(1)], axis = -1).unsqueeze(2)\ntrg = torch.cat([torch.tensor(k['Sideline']), torch.ones(len(k['Sideline'])).unsqueeze(1)], axis = -1).unsqueeze(2)\ntfm = fit_predict(src, trg)\n```\n\n\n```python\nk = get_kp('57781_000252', 1, True)\nsrc = torch.cat([torch.tensor(k['Tracking']), torch.ones(len(k['Tracking'])).unsqueeze(1)], axis = -1).unsqueeze(2)\ntrg = torch.cat([torch.tensor(k['Sideline']), torch.ones(len(k['Sideline'])).unsqueeze(1)], axis = -1).unsqueeze(2)\ntfm = fit_predict(src, trg, 0)\n```\n\n\n```python\nspwt('57781_000252', 1)\n```\n\n\n```python\nspwt\n```\n\n\n```python\nvideo_df = pd.read_csv('../input/nfl-health-and-safety-helmet-assignment/train_baseline_helmets.csv')\nvideo_df = add_video_features(video_df)\nvideo_df.query(f\"game_play == '57781_000252' and frame == '1' and camera == 'Sideline'\").head(10)\n```\n\n\n```python\nvideo_df = pd.read_csv('../input/nfl-health-and-safety-helmet-assignment/train_baseline_helmets.csv')\nvideo_df = video_df.query('conf > 0.8')\nvideo_df = add_video_features(video_df)\nget_kp_highconf = get_keypoints(video_df)\n```\n\n\n```python\nk = get_kp_highconf('57781_000252', 1, True)\nsrc = torch.cat([torch.tensor(k['Tracking']), torch.ones(len(k['Tracking'])).unsqueeze(1)], axis = -1).unsqueeze(2)\ntrg = torch.cat([torch.tensor(k['Sideline']), torch.ones(len(k['Sideline'])).unsqueeze(1)], axis = -1).unsqueeze(2)\ntfm = fit_predict(src, trg, 0)\n```\n\n\n```python\nk = get_kp('57583_000082', 1, True)\nsrc = torch.cat([torch.tensor(k['Tracking']), torch.ones(len(k['Tracking'])).unsqueeze(1)], axis = -1).unsqueeze(2)\ntrg = torch.cat([torch.tensor(k['Endzone']), torch.ones(len(k['Endzone'])).unsqueeze(1)], axis = -1).unsqueeze(2)\nprint(src.shape, trg.shape)\ntfm = fit_predict(src, trg)\n```\n\n\n```python\nk = get_kp('57583_000082', 1, True)\nsrc = torch.cat([torch.tensor(k['Tracking']), torch.ones(len(k['Tracking'])).unsqueeze(1)], axis = -1).unsqueeze(2)\ntrg = torch.cat([torch.tensor(k['Endzone']), torch.ones(len(k['Endzone'])).unsqueeze(1)], axis = -1).unsqueeze(2)\nprint(src.shape, trg.shape)\ntfm = fit_predict(src, trg, 90)\n```\n", "meta": {"hexsha": "b3834ddd195c6ae864acf33ffad477245d303131", "size": 22502, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "mapping/gradient-descent.ipynb", "max_stars_repo_name": "vemodalen-x/ISS_Project", "max_stars_repo_head_hexsha": "85d92d8283e50550a42fc3fe367c61a253ed9730", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mapping/gradient-descent.ipynb", "max_issues_repo_name": "vemodalen-x/ISS_Project", "max_issues_repo_head_hexsha": "85d92d8283e50550a42fc3fe367c61a253ed9730", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mapping/gradient-descent.ipynb", "max_forks_repo_name": "vemodalen-x/ISS_Project", "max_forks_repo_head_hexsha": "85d92d8283e50550a42fc3fe367c61a253ed9730", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2549668874, "max_line_length": 382, "alphanum_fraction": 0.5376410986, "converted": true, "num_tokens": 3815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22815650216092537, "lm_q2_score": 0.0316187688655519, "lm_q1q2_score": 0.007214027706999092}}
{"text": "```python\n!pip install wget\n!apt-get install sox libsndfile1 ffmpeg\n!pip install unidecode\n!pip install matplotlib>=3.3.2\n!pip install ffmpeg-python\n## Install NeMo\nBRANCH = 'r1.1.0'\n!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[all]\n\n## Grab the config we'll use in this example\n!mkdir configs\n!wget -P configs/ https://raw.githubusercontent.com/NVIDIA/NeMo/$BRANCH/examples/asr/conf/config.yaml\n```\n\n    Collecting wget\n      Downloading wget-3.2.zip (10 kB)\n    Building wheels for collected packages: wget\n      Building wheel for wget (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for wget: filename=wget-3.2-py3-none-any.whl size=9673 sha256=721b7d71a3a44cc669954e0be05140fda21345d90179650066ef8865c0e9c7b0\n      Stored in directory: /root/.cache/pip/wheels/a1/b6/7c/0e63e34eb06634181c63adacca38b79ff8f35c37e3c13e3c02\n    Successfully built wget\n    Installing collected packages: wget\n    Successfully installed wget-3.2\n    Reading package lists... Done\n    Building dependency tree       \n    Reading state information... Done\n    libsndfile1 is already the newest version (1.0.28-4ubuntu0.18.04.1).\n    ffmpeg is already the newest version (7:3.4.8-0ubuntu0.2).\n    The following additional packages will be installed:\n      libmagic-mgc libmagic1 libopencore-amrnb0 libopencore-amrwb0 libsox-fmt-alsa\n      libsox-fmt-base libsox3\n    Suggested packages:\n      file libsox-fmt-all\n    The following NEW packages will be installed:\n      libmagic-mgc libmagic1 libopencore-amrnb0 libopencore-amrwb0 libsox-fmt-alsa\n      libsox-fmt-base libsox3 sox\n    0 upgraded, 8 newly installed, 0 to remove and 40 not upgraded.\n    Need to get 760 kB of archives.\n    After this operation, 6,717 kB of additional disk space will be used.\n    Get:1 http://archive.ubuntu.com/ubuntu bionic/universe amd64 libopencore-amrnb0 amd64 0.1.3-2.1 [92.0 kB]\n    Get:2 http://archive.ubuntu.com/ubuntu bionic/universe amd64 libopencore-amrwb0 amd64 0.1.3-2.1 [45.8 kB]\n    Get:3 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libmagic-mgc amd64 1:5.32-2ubuntu0.4 [184 kB]\n    Get:4 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libmagic1 amd64 1:5.32-2ubuntu0.4 [68.6 kB]\n    Get:5 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 libsox3 amd64 14.4.2-3ubuntu0.18.04.1 [226 kB]\n    Get:6 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 libsox-fmt-alsa amd64 14.4.2-3ubuntu0.18.04.1 [10.6 kB]\n    Get:7 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 libsox-fmt-base amd64 14.4.2-3ubuntu0.18.04.1 [32.1 kB]\n    Get:8 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 sox amd64 14.4.2-3ubuntu0.18.04.1 [101 kB]\n    Fetched 760 kB in 0s (6,553 kB/s)\n    Selecting previously unselected package libopencore-amrnb0:amd64.\n    (Reading database ... 160837 files and directories currently installed.)\n    Preparing to unpack .../0-libopencore-amrnb0_0.1.3-2.1_amd64.deb ...\n    Unpacking libopencore-amrnb0:amd64 (0.1.3-2.1) ...\n    Selecting previously unselected package libopencore-amrwb0:amd64.\n    Preparing to unpack .../1-libopencore-amrwb0_0.1.3-2.1_amd64.deb ...\n    Unpacking libopencore-amrwb0:amd64 (0.1.3-2.1) ...\n    Selecting previously unselected package libmagic-mgc.\n    Preparing to unpack .../2-libmagic-mgc_1%3a5.32-2ubuntu0.4_amd64.deb ...\n    Unpacking libmagic-mgc (1:5.32-2ubuntu0.4) ...\n    Selecting previously unselected package libmagic1:amd64.\n    Preparing to unpack .../3-libmagic1_1%3a5.32-2ubuntu0.4_amd64.deb ...\n    Unpacking libmagic1:amd64 (1:5.32-2ubuntu0.4) ...\n    Selecting previously unselected package libsox3:amd64.\n    Preparing to unpack .../4-libsox3_14.4.2-3ubuntu0.18.04.1_amd64.deb ...\n    Unpacking libsox3:amd64 (14.4.2-3ubuntu0.18.04.1) ...\n    Selecting previously unselected package libsox-fmt-alsa:amd64.\n    Preparing to unpack .../5-libsox-fmt-alsa_14.4.2-3ubuntu0.18.04.1_amd64.deb ...\n    Unpacking libsox-fmt-alsa:amd64 (14.4.2-3ubuntu0.18.04.1) ...\n    Selecting previously unselected package libsox-fmt-base:amd64.\n    Preparing to unpack .../6-libsox-fmt-base_14.4.2-3ubuntu0.18.04.1_amd64.deb ...\n    Unpacking libsox-fmt-base:amd64 (14.4.2-3ubuntu0.18.04.1) ...\n    Selecting previously unselected package sox.\n    Preparing to unpack .../7-sox_14.4.2-3ubuntu0.18.04.1_amd64.deb ...\n    Unpacking sox (14.4.2-3ubuntu0.18.04.1) ...\n    Setting up libmagic-mgc (1:5.32-2ubuntu0.4) ...\n    Setting up libmagic1:amd64 (1:5.32-2ubuntu0.4) ...\n    Setting up libopencore-amrnb0:amd64 (0.1.3-2.1) ...\n    Setting up libopencore-amrwb0:amd64 (0.1.3-2.1) ...\n    Setting up libsox3:amd64 (14.4.2-3ubuntu0.18.04.1) ...\n    Setting up libsox-fmt-base:amd64 (14.4.2-3ubuntu0.18.04.1) ...\n    Setting up libsox-fmt-alsa:amd64 (14.4.2-3ubuntu0.18.04.1) ...\n    Setting up sox (14.4.2-3ubuntu0.18.04.1) ...\n    Processing triggers for libc-bin (2.27-3ubuntu1.2) ...\n    /sbin/ldconfig.real: /usr/local/lib/python3.7/dist-packages/ideep4py/lib/libmkldnn.so.0 is not a symbolic link\n    \n    Processing triggers for man-db (2.8.3-2ubuntu0.1) ...\n    Processing triggers for mime-support (3.60ubuntu1) ...\n    Collecting unidecode\n      Downloading Unidecode-1.2.0-py2.py3-none-any.whl (241 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 241 kB 13.5 MB/s \n    \u001b[?25hInstalling collected packages: unidecode\n    Successfully installed unidecode-1.2.0\n    Collecting nemo_toolkit[all]\n      Cloning https://github.com/NVIDIA/NeMo.git (to revision r1.1.0) to /tmp/pip-install-xuul8v87/nemo-toolkit_a9c49a7078624023b946cbf53a5ff419\n      Running command git clone -q https://github.com/NVIDIA/NeMo.git /tmp/pip-install-xuul8v87/nemo-toolkit_a9c49a7078624023b946cbf53a5ff419\n      Running command git checkout -b r1.1.0 --track origin/r1.1.0\n      Switched to a new branch 'r1.1.0'\n      Branch 'r1.1.0' set up to track remote branch 'r1.1.0' from 'origin'.\n    Requirement already satisfied: numpy>=1.18.2 in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (1.19.5)\n    Collecting onnx>=1.7.0\n      Downloading onnx-1.10.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (12.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 12.3 MB 14.7 MB/s \n    \u001b[?25hCollecting pytorch-lightning<1.3.8,>=1.3.0\n      Downloading pytorch_lightning-1.3.7.post0-py3-none-any.whl (810 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 810 kB 55.4 MB/s \n    \u001b[?25hRequirement already satisfied: python-dateutil in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (2.8.1)\n    Requirement already satisfied: torch in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (1.9.0+cu102)\n    Collecting torchmetrics<0.4.0\n      Downloading torchmetrics-0.3.2-py3-none-any.whl (274 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 274 kB 76.0 MB/s \n    \u001b[?25hRequirement already satisfied: wget in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (3.2)\n    Requirement already satisfied: wrapt in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (1.12.1)\n    Collecting ruamel.yaml\n      Downloading ruamel.yaml-0.17.10-py3-none-any.whl (108 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 108 kB 77.4 MB/s \n    \u001b[?25hRequirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (0.22.2.post1)\n    Collecting omegaconf>=2.1.0\n      Downloading omegaconf-2.1.0-py3-none-any.whl (74 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 74 kB 3.4 MB/s \n    \u001b[?25hCollecting hydra-core>=1.1.0\n      Downloading hydra_core-1.1.0-py3-none-any.whl (144 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 144 kB 76.8 MB/s \n    \u001b[?25hCollecting transformers>=4.0.1\n      Downloading transformers-4.9.1-py3-none-any.whl (2.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.6 MB 51.4 MB/s \n    \u001b[?25hCollecting sentencepiece<1.0.0\n      Downloading sentencepiece-0.1.96-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.2 MB 71.5 MB/s \n    \u001b[?25hCollecting webdataset<=0.1.62,>=0.1.48\n      Downloading webdataset-0.1.62-py3-none-any.whl (32 kB)\n    Requirement already satisfied: tqdm>=4.41.0 in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (4.41.1)\n    Collecting opencc\n      Downloading OpenCC-1.1.2-cp37-cp37m-manylinux1_x86_64.whl (765 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 765 kB 57.3 MB/s \n    \u001b[?25hCollecting pangu\n      Downloading pangu-4.0.6.1-py3-none-any.whl (6.4 kB)\n    Requirement already satisfied: jieba in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (0.42.1)\n    Requirement already satisfied: numba in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (0.51.2)\n    Collecting black==19.10b0\n      Downloading black-19.10b0-py36-none-any.whl (97 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 97 kB 7.9 MB/s \n    \u001b[?25hCollecting isort[requirements]<5\n      Downloading isort-4.3.21-py2.py3-none-any.whl (42 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 42 kB 1.1 MB/s \n    \u001b[?25hCollecting parameterized\n      Downloading parameterized-0.8.1-py2.py3-none-any.whl (26 kB)\n    Requirement already satisfied: pytest in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (3.6.4)\n    Collecting pytest-runner\n      Using cached pytest_runner-5.3.1-py3-none-any.whl (7.1 kB)\n    Requirement already satisfied: sphinx in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (1.8.5)\n    Collecting sphinxcontrib-bibtex\n      Downloading sphinxcontrib_bibtex-2.3.0-py3-none-any.whl (35 kB)\n    Collecting wandb\n      Downloading wandb-0.11.2-py2.py3-none-any.whl (1.8 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.8 MB 70.7 MB/s \n    \u001b[?25hCollecting braceexpand\n      Downloading braceexpand-0.1.7-py2.py3-none-any.whl (5.9 kB)\n    Requirement already satisfied: editdistance in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (0.5.3)\n    Collecting frozendict\n      Downloading frozendict-2.0.3-py3-none-any.whl (8.3 kB)\n    Requirement already satisfied: inflect in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (2.1.0)\n    Collecting kaldi-io\n      Downloading kaldi_io-0.9.4-py3-none-any.whl (14 kB)\n    Requirement already satisfied: librosa in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (0.8.1)\n    Collecting marshmallow\n      Downloading marshmallow-3.13.0-py2.py3-none-any.whl (47 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 47 kB 4.9 MB/s \n    \u001b[?25hRequirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (21.0)\n    Requirement already satisfied: soundfile in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (0.10.3.post1)\n    Collecting sox\n      Downloading sox-1.4.1-py2.py3-none-any.whl (39 kB)\n    Requirement already satisfied: unidecode in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (1.2.0)\n    Collecting kaldi-python-io\n      Downloading kaldi-python-io-1.2.2.tar.gz (8.8 kB)\n    Collecting kaldiio\n      Downloading kaldiio-2.17.2.tar.gz (24 kB)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (1.4.1)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (1.1.5)\n    Collecting g2p_en\n      Downloading g2p_en-2.1.0-py3-none-any.whl (3.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.1 MB 63.5 MB/s \n    \u001b[?25hCollecting pydub\n      Downloading pydub-0.25.1-py2.py3-none-any.whl (32 kB)\n    Collecting pyannote.core\n      Downloading pyannote.core-4.1-py3-none-any.whl (56 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 56 kB 5.2 MB/s \n    \u001b[?25hCollecting pyannote.metrics\n      Downloading pyannote.metrics-3.0.1-py3-none-any.whl (49 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 49 kB 6.7 MB/s \n    \u001b[?25hCollecting pyamg\n      Downloading pyamg-4.1.0.tar.gz (749 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 749 kB 40.1 MB/s \n    \u001b[?25hCollecting torch-stft\n      Downloading torch_stft-0.1.4-py3-none-any.whl (6.2 kB)\n    Requirement already satisfied: ipywidgets in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (7.6.3)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (3.2.2)\n    Requirement already satisfied: pillow in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (7.1.2)\n    Requirement already satisfied: torchvision in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (0.10.0+cu102)\n    Collecting boto3\n      Downloading boto3-1.18.13-py3-none-any.whl (131 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 131 kB 68.2 MB/s \n    \u001b[?25hRequirement already satisfied: h5py in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (3.1.0)\n    Collecting matplotlib>=3.3.2\n      Downloading matplotlib-3.4.2-cp37-cp37m-manylinux1_x86_64.whl (10.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 10.3 MB 66.2 MB/s \n    \u001b[?25hCollecting youtokentome>=1.0.5\n      Downloading youtokentome-1.0.6-cp37-cp37m-manylinux2010_x86_64.whl (1.7 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.7 MB 55.1 MB/s \n    \u001b[?25hCollecting rapidfuzz\n      Downloading rapidfuzz-1.4.1-cp37-cp37m-manylinux2010_x86_64.whl (749 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 749 kB 71.1 MB/s \n    \u001b[?25hRequirement already satisfied: gdown in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (3.6.4)\n    Collecting megatron-lm==2.2.0\n      Downloading megatron_lm-2.2.0-py3-none-any.whl (171 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 171 kB 82.8 MB/s \n    \u001b[?25hCollecting sacrebleu[ja]\n      Downloading sacrebleu-1.5.1-py3-none-any.whl (54 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 54 kB 3.1 MB/s \n    \u001b[?25hCollecting sacremoses>=0.0.43\n      Downloading sacremoses-0.0.45-py3-none-any.whl (895 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 895 kB 44.2 MB/s \n    \u001b[?25hCollecting pypinyin\n      Downloading pypinyin-0.42.0-py2.py3-none-any.whl (1.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.3 MB 48.9 MB/s \n    \u001b[?25hCollecting attrdict\n      Downloading attrdict-2.0.1-py2.py3-none-any.whl (9.9 kB)\n    Collecting pystoi\n      Downloading pystoi-0.3.3.tar.gz (7.0 kB)\n    Collecting pesq\n      Downloading pesq-0.0.3.tar.gz (35 kB)\n    Requirement already satisfied: nltk in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (3.2.5)\n    Requirement already satisfied: regex in /usr/local/lib/python3.7/dist-packages (from nemo_toolkit[all]) (2019.12.20)\n    Collecting pathspec<1,>=0.6\n      Downloading pathspec-0.9.0-py2.py3-none-any.whl (31 kB)\n    Requirement already satisfied: attrs>=18.1.0 in /usr/local/lib/python3.7/dist-packages (from black==19.10b0->nemo_toolkit[all]) (21.2.0)\n    Requirement already satisfied: click>=6.5 in /usr/local/lib/python3.7/dist-packages (from black==19.10b0->nemo_toolkit[all]) (7.1.2)\n    Collecting typed-ast>=1.4.0\n      Downloading typed_ast-1.4.3-cp37-cp37m-manylinux1_x86_64.whl (743 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 743 kB 56.6 MB/s \n    \u001b[?25hRequirement already satisfied: toml>=0.9.4 in /usr/local/lib/python3.7/dist-packages (from black==19.10b0->nemo_toolkit[all]) (0.10.2)\n    Requirement already satisfied: appdirs in /usr/local/lib/python3.7/dist-packages (from black==19.10b0->nemo_toolkit[all]) (1.4.4)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from megatron-lm==2.2.0->nemo_toolkit[all]) (1.15.0)\n    Collecting pybind11\n      Using cached pybind11-2.7.1-py2.py3-none-any.whl (200 kB)\n    Collecting antlr4-python3-runtime==4.8\n      Downloading antlr4-python3-runtime-4.8.tar.gz (112 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 112 kB 63.9 MB/s \n    \u001b[?25hRequirement already satisfied: importlib-resources in /usr/local/lib/python3.7/dist-packages (from hydra-core>=1.1.0->nemo_toolkit[all]) (5.2.0)\n    Collecting PyYAML>=5.1.*\n      Downloading PyYAML-5.4.1-cp37-cp37m-manylinux1_x86_64.whl (636 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 636 kB 58.0 MB/s \n    \u001b[?25hCollecting pipreqs\n      Downloading pipreqs-0.4.10-py2.py3-none-any.whl (25 kB)\n    Collecting pip-api\n      Downloading pip_api-0.0.20-py3-none-any.whl (112 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 112 kB 83.0 MB/s \n    \u001b[?25hRequirement already satisfied: typing-extensions>=3.6.2.1 in /usr/local/lib/python3.7/dist-packages (from onnx>=1.7.0->nemo_toolkit[all]) (3.7.4.3)\n    Requirement already satisfied: protobuf in /usr/local/lib/python3.7/dist-packages (from onnx>=1.7.0->nemo_toolkit[all]) (3.17.3)\n    Collecting future>=0.17.1\n      Downloading future-0.18.2.tar.gz (829 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 829 kB 56.2 MB/s \n    \u001b[?25hCollecting tensorboard!=2.5.0,>=2.2.0\n      Downloading tensorboard-2.4.1-py3-none-any.whl (10.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 10.6 MB 57.7 MB/s \n    \u001b[?25hCollecting pyDeprecate==0.3.0\n      Downloading pyDeprecate-0.3.0-py3-none-any.whl (10 kB)\n    Collecting fsspec[http]!=2021.06.0,>=2021.05.0\n      Downloading fsspec-2021.7.0-py3-none-any.whl (118 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 118 kB 75.9 MB/s \n    \u001b[?25hCollecting aiohttp\n      Downloading aiohttp-3.7.4.post0-cp37-cp37m-manylinux2014_x86_64.whl (1.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.3 MB 50.8 MB/s \n    \u001b[?25hRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (2.23.0)\n    Requirement already satisfied: joblib in /usr/local/lib/python3.7/dist-packages (from sacremoses>=0.0.43->nemo_toolkit[all]) (1.0.1)\n    Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (1.32.1)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (0.4.4)\n    Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (57.2.0)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (1.8.0)\n    Requirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.7/dist-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (0.36.2)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (3.3.4)\n    Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (1.0.1)\n    Requirement already satisfied: grpcio>=1.24.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (1.34.1)\n    Requirement already satisfied: absl-py>=0.4 in /usr/local/lib/python3.7/dist-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (0.12.0)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (0.2.8)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (4.7.2)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (4.2.2)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (1.3.0)\n    Requirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from markdown>=2.6.8->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (4.6.1)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (0.4.8)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->fsspec[http]!=2021.06.0,>=2021.05.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (2021.5.30)\n    Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (3.1.1)\n    Collecting huggingface-hub==0.0.12\n      Downloading huggingface_hub-0.0.12-py3-none-any.whl (37 kB)\n    Collecting tokenizers<0.11,>=0.10.1\n      Downloading tokenizers-0.10.3-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (3.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.3 MB 50.4 MB/s \n    \u001b[?25hRequirement already satisfied: filelock in /usr/local/lib/python3.7/dist-packages (from transformers>=4.0.1->nemo_toolkit[all]) (3.0.12)\n    Requirement already satisfied: pyparsing>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->nemo_toolkit[all]) (2.4.7)\n    Collecting multidict<7.0,>=4.5\n      Downloading multidict-5.1.0-cp37-cp37m-manylinux2014_x86_64.whl (142 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 142 kB 62.4 MB/s \n    \u001b[?25hCollecting yarl<2.0,>=1.0\n      Downloading yarl-1.6.3-cp37-cp37m-manylinux2014_x86_64.whl (294 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 294 kB 79.4 MB/s \n    \u001b[?25hCollecting async-timeout<4.0,>=3.0\n      Downloading async_timeout-3.0.1-py3-none-any.whl (8.2 kB)\n    Collecting botocore<1.22.0,>=1.21.13\n      Downloading botocore-1.21.13-py3-none-any.whl (7.8 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 7.8 MB 57.1 MB/s \n    \u001b[?25hCollecting s3transfer<0.6.0,>=0.5.0\n      Downloading s3transfer-0.5.0-py3-none-any.whl (79 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 79 kB 8.6 MB/s \n    \u001b[?25hCollecting jmespath<1.0.0,>=0.7.1\n      Downloading jmespath-0.10.0-py2.py3-none-any.whl (24 kB)\n    Collecting urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1\n      Downloading urllib3-1.25.11-py2.py3-none-any.whl (127 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 127 kB 60.6 MB/s \n    \u001b[?25hCollecting distance>=0.1.3\n      Downloading Distance-0.1.3.tar.gz (180 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 180 kB 67.8 MB/s \n    \u001b[?25hRequirement already satisfied: cached-property in /usr/local/lib/python3.7/dist-packages (from h5py->nemo_toolkit[all]) (1.5.2)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->markdown>=2.6.8->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<1.3.8,>=1.3.0->nemo_toolkit[all]) (3.5.0)\n    Requirement already satisfied: widgetsnbextension~=3.5.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->nemo_toolkit[all]) (3.5.1)\n    Requirement already satisfied: traitlets>=4.3.1 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->nemo_toolkit[all]) (5.0.5)\n    Requirement already satisfied: nbformat>=4.2.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->nemo_toolkit[all]) (5.1.3)\n    Requirement already satisfied: ipykernel>=4.5.1 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->nemo_toolkit[all]) (4.10.1)\n    Requirement already satisfied: jupyterlab-widgets>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->nemo_toolkit[all]) (1.0.0)\n    Requirement already satisfied: ipython>=4.0.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->nemo_toolkit[all]) (5.5.0)\n    Requirement already satisfied: tornado>=4.0 in /usr/local/lib/python3.7/dist-packages (from ipykernel>=4.5.1->ipywidgets->nemo_toolkit[all]) (5.1.1)\n    Requirement already satisfied: jupyter-client in /usr/local/lib/python3.7/dist-packages (from ipykernel>=4.5.1->ipywidgets->nemo_toolkit[all]) (5.3.5)\n    Requirement already satisfied: pickleshare in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets->nemo_toolkit[all]) (0.7.5)\n    Requirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets->nemo_toolkit[all]) (0.8.1)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets->nemo_toolkit[all]) (4.4.2)\n    Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets->nemo_toolkit[all]) (1.0.18)\n    Requirement already satisfied: pygments in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets->nemo_toolkit[all]) (2.6.1)\n    Requirement already satisfied: pexpect in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets->nemo_toolkit[all]) (4.8.0)\n    Requirement already satisfied: jsonschema!=2.5.0,>=2.4 in /usr/local/lib/python3.7/dist-packages (from nbformat>=4.2.0->ipywidgets->nemo_toolkit[all]) (2.6.0)\n    Requirement already satisfied: jupyter-core in /usr/local/lib/python3.7/dist-packages (from nbformat>=4.2.0->ipywidgets->nemo_toolkit[all]) (4.7.1)\n    Requirement already satisfied: ipython-genutils in /usr/local/lib/python3.7/dist-packages (from nbformat>=4.2.0->ipywidgets->nemo_toolkit[all]) (0.2.0)\n    Requirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython>=4.0.0->ipywidgets->nemo_toolkit[all]) (0.2.5)\n    Requirement already satisfied: notebook>=4.4.1 in /usr/local/lib/python3.7/dist-packages (from widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (5.3.1)\n    Requirement already satisfied: terminado>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (0.10.1)\n    Requirement already satisfied: jinja2 in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (2.11.3)\n    Requirement already satisfied: nbconvert in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (5.6.1)\n    Requirement already satisfied: Send2Trash in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (1.7.1)\n    Requirement already satisfied: pyzmq>=13 in /usr/local/lib/python3.7/dist-packages (from jupyter-client->ipykernel>=4.5.1->ipywidgets->nemo_toolkit[all]) (22.1.0)\n    Requirement already satisfied: ptyprocess in /usr/local/lib/python3.7/dist-packages (from terminado>=0.8.1->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (0.7.0)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (2.0.1)\n    Requirement already satisfied: resampy>=0.2.2 in /usr/local/lib/python3.7/dist-packages (from librosa->nemo_toolkit[all]) (0.2.2)\n    Requirement already satisfied: audioread>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from librosa->nemo_toolkit[all]) (2.1.9)\n    Requirement already satisfied: pooch>=1.0 in /usr/local/lib/python3.7/dist-packages (from librosa->nemo_toolkit[all]) (1.4.0)\n    Requirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba->nemo_toolkit[all]) (0.34.0)\n    Requirement already satisfied: cffi>=1.0 in /usr/local/lib/python3.7/dist-packages (from soundfile->nemo_toolkit[all]) (1.14.6)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.0->soundfile->nemo_toolkit[all]) (2.20)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->nemo_toolkit[all]) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->nemo_toolkit[all]) (1.3.1)\n    Requirement already satisfied: bleach in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (3.3.0)\n    Requirement already satisfied: mistune<2,>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (0.8.4)\n    Requirement already satisfied: entrypoints>=0.2.2 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (0.3)\n    Requirement already satisfied: defusedxml in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (0.7.1)\n    Requirement already satisfied: pandocfilters>=1.4.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (1.4.3)\n    Requirement already satisfied: testpath in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (0.5.0)\n    Requirement already satisfied: webencodings in /usr/local/lib/python3.7/dist-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->nemo_toolkit[all]) (0.5.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->nemo_toolkit[all]) (2018.9)\n    Requirement already satisfied: pip in /usr/local/lib/python3.7/dist-packages (from pip-api->isort[requirements]<5->nemo_toolkit[all]) (21.1.3)\n    Collecting yarg\n      Downloading yarg-0.1.9-py2.py3-none-any.whl (19 kB)\n    Requirement already satisfied: docopt in /usr/local/lib/python3.7/dist-packages (from pipreqs->isort[requirements]<5->nemo_toolkit[all]) (0.6.2)\n    Requirement already satisfied: pluggy<0.8,>=0.5 in /usr/local/lib/python3.7/dist-packages (from pytest->nemo_toolkit[all]) (0.7.1)\n    Requirement already satisfied: py>=1.5.0 in /usr/local/lib/python3.7/dist-packages (from pytest->nemo_toolkit[all]) (1.10.0)\n    Requirement already satisfied: atomicwrites>=1.0 in /usr/local/lib/python3.7/dist-packages (from pytest->nemo_toolkit[all]) (1.4.0)\n    Requirement already satisfied: more-itertools>=4.0.0 in /usr/local/lib/python3.7/dist-packages (from pytest->nemo_toolkit[all]) (8.8.0)\n    Requirement already satisfied: sortedcontainers>=2.0.4 in /usr/local/lib/python3.7/dist-packages (from pyannote.core->nemo_toolkit[all]) (2.4.0)\n    Collecting simplejson>=3.8.1\n      Downloading simplejson-3.17.3-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (129 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 129 kB 68.1 MB/s \n    \u001b[?25hRequirement already satisfied: sympy>=1.1 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics->nemo_toolkit[all]) (1.7.1)\n    Collecting pyannote.database>=4.0.1\n      Downloading pyannote.database-4.1-py3-none-any.whl (41 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 41 kB 236 kB/s \n    \u001b[?25hRequirement already satisfied: tabulate>=0.7.7 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics->nemo_toolkit[all]) (0.8.9)\n    Collecting typer[all]>=0.2.1\n      Downloading typer-0.3.2-py3-none-any.whl (21 kB)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.1->pyannote.metrics->nemo_toolkit[all]) (1.2.1)\n    Collecting shellingham<2.0.0,>=1.3.0\n      Downloading shellingham-1.4.0-py2.py3-none-any.whl (9.4 kB)\n    Collecting colorama<0.5.0,>=0.4.3\n      Downloading colorama-0.4.4-py2.py3-none-any.whl (16 kB)\n    Collecting ruamel.yaml.clib>=0.1.2\n      Downloading ruamel.yaml.clib-0.2.6-cp37-cp37m-manylinux1_x86_64.whl (546 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 546 kB 61.0 MB/s \n    \u001b[?25hCollecting portalocker==2.0.0\n      Downloading portalocker-2.0.0-py2.py3-none-any.whl (11 kB)\n    Collecting mecab-python3==1.0.3\n      Downloading mecab_python3-1.0.3-cp37-cp37m-manylinux1_x86_64.whl (487 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 487 kB 65.1 MB/s \n    \u001b[?25hCollecting ipadic<2.0,>=1.0\n      Downloading ipadic-1.0.0.tar.gz (13.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 13.4 MB 56.0 MB/s \n    \u001b[?25hRequirement already satisfied: babel!=2.0,>=1.3 in /usr/local/lib/python3.7/dist-packages (from sphinx->nemo_toolkit[all]) (2.9.1)\n    Requirement already satisfied: docutils>=0.11 in /usr/local/lib/python3.7/dist-packages (from sphinx->nemo_toolkit[all]) (0.17.1)\n    Requirement already satisfied: sphinxcontrib-websupport in /usr/local/lib/python3.7/dist-packages (from sphinx->nemo_toolkit[all]) (1.2.4)\n    Requirement already satisfied: snowballstemmer>=1.1 in /usr/local/lib/python3.7/dist-packages (from sphinx->nemo_toolkit[all]) (2.1.0)\n    Requirement already satisfied: imagesize in /usr/local/lib/python3.7/dist-packages (from sphinx->nemo_toolkit[all]) (1.2.0)\n    Requirement already satisfied: alabaster<0.8,>=0.7 in /usr/local/lib/python3.7/dist-packages (from sphinx->nemo_toolkit[all]) (0.7.12)\n    Collecting pybtex>=0.20\n      Downloading pybtex-0.24.0-py2.py3-none-any.whl (561 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 561 kB 63.2 MB/s \n    \u001b[?25hCollecting sphinx\n      Downloading Sphinx-4.1.2-py3-none-any.whl (2.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.9 MB 55.4 MB/s \n    \u001b[?25hCollecting pybtex-docutils>=1.0.0\n      Downloading pybtex_docutils-1.0.1-py3-none-any.whl (4.8 kB)\n    Collecting latexcodec>=1.0.4\n      Downloading latexcodec-2.0.1-py2.py3-none-any.whl (18 kB)\n    Collecting sphinxcontrib-htmlhelp>=2.0.0\n      Downloading sphinxcontrib_htmlhelp-2.0.0-py2.py3-none-any.whl (100 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 100 kB 9.9 MB/s \n    \u001b[?25hCollecting sphinxcontrib-qthelp\n      Downloading sphinxcontrib_qthelp-1.0.3-py2.py3-none-any.whl (90 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 90 kB 9.4 MB/s \n    \u001b[?25hCollecting sphinxcontrib-applehelp\n      Downloading sphinxcontrib_applehelp-1.0.2-py2.py3-none-any.whl (121 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 121 kB 64.0 MB/s \n    \u001b[?25hCollecting sphinxcontrib-jsmath\n      Downloading sphinxcontrib_jsmath-1.0.1-py2.py3-none-any.whl (5.1 kB)\n    Collecting sphinxcontrib-devhelp\n      Downloading sphinxcontrib_devhelp-1.0.2-py2.py3-none-any.whl (84 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 84 kB 4.0 MB/s \n    \u001b[?25hRequirement already satisfied: sphinxcontrib-serializinghtml>=1.1.5 in /usr/local/lib/python3.7/dist-packages (from sphinx->nemo_toolkit[all]) (1.1.5)\n    Collecting shortuuid>=0.5.0\n      Downloading shortuuid-1.0.1-py3-none-any.whl (7.5 kB)\n    Collecting docker-pycreds>=0.4.0\n      Downloading docker_pycreds-0.4.0-py2.py3-none-any.whl (9.0 kB)\n    Collecting pathtools\n      Downloading pathtools-0.1.2.tar.gz (11 kB)\n    Collecting wandb\n      Downloading wandb-0.11.1-py2.py3-none-any.whl (1.7 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.7 MB 58.9 MB/s \n    \u001b[?25hCollecting graphql-core>=2.3.0\n      Downloading graphql_core-3.1.5-py3-none-any.whl (188 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 188 kB 76.1 MB/s \n    \u001b[?25hCollecting configparser>=3.8.1\n      Downloading configparser-5.0.2-py3-none-any.whl (19 kB)\n    Requirement already satisfied: psutil>=5.0.0 in /usr/local/lib/python3.7/dist-packages (from wandb->nemo_toolkit[all]) (5.4.8)\n    Collecting sentry-sdk>=1.0.0\n      Downloading sentry_sdk-1.3.1-py2.py3-none-any.whl (133 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 133 kB 74.5 MB/s \n    \u001b[?25hCollecting GitPython>=1.0.0\n      Downloading GitPython-3.1.18-py3-none-any.whl (170 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 170 kB 64.5 MB/s \n    \u001b[?25hRequirement already satisfied: promise<3,>=2.0 in /usr/local/lib/python3.7/dist-packages (from wandb->nemo_toolkit[all]) (2.3)\n    Collecting gitdb<5,>=4.0.1\n      Downloading gitdb-4.0.7-py3-none-any.whl (63 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 63 kB 2.0 MB/s \n    \u001b[?25hCollecting smmap<5,>=3.0.1\n      Downloading smmap-4.0.0-py2.py3-none-any.whl (24 kB)\n    Building wheels for collected packages: nemo-toolkit, antlr4-python3-runtime, future, distance, kaldi-python-io, kaldiio, pesq, pyamg, pystoi, ipadic, pathtools\n      Building wheel for nemo-toolkit (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for nemo-toolkit: filename=nemo_toolkit-1.1.0-py3-none-any.whl size=1283955 sha256=b63b0c2b8eb35d8184027b60e399ba77a5c9da45e6c722175f04db589a6ab5ec\n      Stored in directory: /tmp/pip-ephem-wheel-cache-y_ed8bc2/wheels/85/5c/30/9080fc85b551000a7c2068c7be0c34bff0e3b2c57c8da5054f\n      Building wheel for antlr4-python3-runtime (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for antlr4-python3-runtime: filename=antlr4_python3_runtime-4.8-py3-none-any.whl size=141229 sha256=37597532243b25be0965135510b8392d54263aeff7c4393fb1cf0d79152a1c56\n      Stored in directory: /root/.cache/pip/wheels/ca/33/b7/336836125fc9bb4ceaa4376d8abca10ca8bc84ddc824baea6c\n      Building wheel for future (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for future: filename=future-0.18.2-py3-none-any.whl size=491070 sha256=94e94fc3f7cf4ec3932c38f728af7594f30734312b21d20e390fa10ab75860cb\n      Stored in directory: /root/.cache/pip/wheels/56/b0/fe/4410d17b32f1f0c3cf54cdfb2bc04d7b4b8f4ae377e2229ba0\n      Building wheel for distance (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for distance: filename=Distance-0.1.3-py3-none-any.whl size=16275 sha256=6a8943fe4e31455e913f647e6910147b23cf96384829907def7af66b2f388037\n      Stored in directory: /root/.cache/pip/wheels/b2/10/1b/96fca621a1be378e2fe104cfb0d160bb6cdf3d04a3d35266cc\n      Building wheel for kaldi-python-io (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for kaldi-python-io: filename=kaldi_python_io-1.2.2-py3-none-any.whl size=8969 sha256=c8ac28d1479c12df241f9fbe45cbe401056320535cd672f1d222703e870eb1d8\n      Stored in directory: /root/.cache/pip/wheels/a9/26/38/7678d1ff6cd1bbcbfc0d80b0a29d94d917dfa9ad790b4a85a9\n      Building wheel for kaldiio (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for kaldiio: filename=kaldiio-2.17.2-py3-none-any.whl size=24471 sha256=c8bd780555fc792d9a71859a54cac003b173ed8a6ce2496ea01c28f376663089\n      Stored in directory: /root/.cache/pip/wheels/04/07/e8/45641287c59bf6ce41e22259f8680b521c31e6306cb88392ac\n      Building wheel for pesq (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pesq: filename=pesq-0.0.3-cp37-cp37m-linux_x86_64.whl size=209958 sha256=829cf6cf7a88b25de498e87af4359fa432ccd4d9ecc63c1fb8001bf6a6a2ce11\n      Stored in directory: /root/.cache/pip/wheels/4f/67/5b/aa7cf31fe0c7199e35c604bb7bc91c629a13726bf221fedba0\n      Building wheel for pyamg (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pyamg: filename=pyamg-4.1.0-cp37-cp37m-linux_x86_64.whl size=7781672 sha256=8914f6f2da295a2d6af0b91d99c294024cb0f3c33d2a8ee2682477f4de5f90eb\n      Stored in directory: /root/.cache/pip/wheels/64/77/6f/2117a1d8d3c9b2d5e3d0f18476658bd6db1ced0395b251eac0\n      Building wheel for pystoi (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pystoi: filename=pystoi-0.3.3-py2.py3-none-any.whl size=7794 sha256=f5dc83c49451ada4458dba947f0b2557e135ac6536d6571eeae0a97a596a96d1\n      Stored in directory: /root/.cache/pip/wheels/46/4a/ad/3ab460193ed0535430b4b1575f255aa6bae69df17453628e86\n      Building wheel for ipadic (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for ipadic: filename=ipadic-1.0.0-py3-none-any.whl size=13556723 sha256=68dc20c1206ecc53751a5f5a007525333e42f857db07185439e10dec5d9eca1e\n      Stored in directory: /root/.cache/pip/wheels/33/8b/99/cf0d27191876637cd3639a560f93aa982d7855ce826c94348b\n      Building wheel for pathtools (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pathtools: filename=pathtools-0.1.2-py3-none-any.whl size=8806 sha256=24eee281393c0244c45904ffe33b8e5e01d337c4cd26e5666a169ae202ea2550\n      Stored in directory: /root/.cache/pip/wheels/3e/31/09/fa59cef12cdcfecc627b3d24273699f390e71828921b2cbba2\n    Successfully built nemo-toolkit antlr4-python3-runtime future distance kaldi-python-io kaldiio pesq pyamg pystoi ipadic pathtools\n    Installing collected packages: urllib3, multidict, yarl, async-timeout, typer, smmap, simplejson, shellingham, PyYAML, latexcodec, jmespath, fsspec, colorama, antlr4-python3-runtime, aiohttp, yarg, torchmetrics, tokenizers, tensorboard, sphinxcontrib-qthelp, sphinxcontrib-jsmath, sphinxcontrib-htmlhelp, sphinxcontrib-devhelp, sphinxcontrib-applehelp, sacremoses, ruamel.yaml.clib, pyDeprecate, pybtex, pyannote.core, portalocker, omegaconf, huggingface-hub, gitdb, future, braceexpand, botocore, webdataset, typed-ast, transformers, sphinx, shortuuid, sentry-sdk, sentencepiece, sacrebleu, s3transfer, ruamel.yaml, pytorch-lightning, pybtex-docutils, pybind11, pyannote.database, pipreqs, pip-api, pathtools, pathspec, pangu, opencc, onnx, mecab-python3, isort, ipadic, hydra-core, graphql-core, GitPython, docker-pycreds, distance, configparser, youtokentome, wandb, torch-stft, sphinxcontrib-bibtex, sox, rapidfuzz, pytest-runner, pystoi, pypinyin, pydub, pyannote.metrics, pyamg, pesq, parameterized, nemo-toolkit, megatron-lm, marshmallow, kaldiio, kaldi-python-io, kaldi-io, g2p-en, frozendict, boto3, black, attrdict\n      Attempting uninstall: urllib3\n        Found existing installation: urllib3 1.24.3\n        Uninstalling urllib3-1.24.3:\n          Successfully uninstalled urllib3-1.24.3\n      Attempting uninstall: PyYAML\n        Found existing installation: PyYAML 3.13\n        Uninstalling PyYAML-3.13:\n          Successfully uninstalled PyYAML-3.13\n      Attempting uninstall: tensorboard\n        Found existing installation: tensorboard 2.5.0\n        Uninstalling tensorboard-2.5.0:\n          Successfully uninstalled tensorboard-2.5.0\n      Attempting uninstall: future\n        Found existing installation: future 0.16.0\n        Uninstalling future-0.16.0:\n          Successfully uninstalled future-0.16.0\n      Attempting uninstall: sphinx\n        Found existing installation: Sphinx 1.8.5\n        Uninstalling Sphinx-1.8.5:\n          Successfully uninstalled Sphinx-1.8.5\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    tensorflow 2.5.0 requires tensorboard~=2.5, but you have tensorboard 2.4.1 which is incompatible.\n    datascience 0.10.6 requires folium==0.2.1, but you have folium 0.8.3 which is incompatible.\u001b[0m\n    Successfully installed GitPython-3.1.18 PyYAML-5.4.1 aiohttp-3.7.4.post0 antlr4-python3-runtime-4.8 async-timeout-3.0.1 attrdict-2.0.1 black-19.10b0 boto3-1.18.13 botocore-1.21.13 braceexpand-0.1.7 colorama-0.4.4 configparser-5.0.2 distance-0.1.3 docker-pycreds-0.4.0 frozendict-2.0.3 fsspec-2021.7.0 future-0.18.2 g2p-en-2.1.0 gitdb-4.0.7 graphql-core-3.1.5 huggingface-hub-0.0.12 hydra-core-1.1.0 ipadic-1.0.0 isort-4.3.21 jmespath-0.10.0 kaldi-io-0.9.4 kaldi-python-io-1.2.2 kaldiio-2.17.2 latexcodec-2.0.1 marshmallow-3.13.0 mecab-python3-1.0.3 megatron-lm-2.2.0 multidict-5.1.0 nemo-toolkit-1.1.0 omegaconf-2.1.0 onnx-1.10.1 opencc-1.1.2 pangu-4.0.6.1 parameterized-0.8.1 pathspec-0.9.0 pathtools-0.1.2 pesq-0.0.3 pip-api-0.0.20 pipreqs-0.4.10 portalocker-2.0.0 pyDeprecate-0.3.0 pyamg-4.1.0 pyannote.core-4.1 pyannote.database-4.1 pyannote.metrics-3.0.1 pybind11-2.7.1 pybtex-0.24.0 pybtex-docutils-1.0.1 pydub-0.25.1 pypinyin-0.42.0 pystoi-0.3.3 pytest-runner-5.3.1 pytorch-lightning-1.3.7.post0 rapidfuzz-1.4.1 ruamel.yaml-0.17.10 ruamel.yaml.clib-0.2.6 s3transfer-0.5.0 sacrebleu-1.5.1 sacremoses-0.0.45 sentencepiece-0.1.96 sentry-sdk-1.3.1 shellingham-1.4.0 shortuuid-1.0.1 simplejson-3.17.3 smmap-4.0.0 sox-1.4.1 sphinx-4.1.2 sphinxcontrib-applehelp-1.0.2 sphinxcontrib-bibtex-2.3.0 sphinxcontrib-devhelp-1.0.2 sphinxcontrib-htmlhelp-2.0.0 sphinxcontrib-jsmath-1.0.1 sphinxcontrib-qthelp-1.0.3 tensorboard-2.4.1 tokenizers-0.10.3 torch-stft-0.1.4 torchmetrics-0.3.2 transformers-4.9.1 typed-ast-1.4.3 typer-0.3.2 urllib3-1.25.11 wandb-0.11.1 webdataset-0.1.62 yarg-0.1.9 yarl-1.6.3 youtokentome-1.0.6\n    --2021-08-04 09:11:30--  https://raw.githubusercontent.com/NVIDIA/NeMo/r1.1.0/examples/asr/conf/config.yaml\n    Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ...\n    Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 4040 (3.9K) [text/plain]\n    Saving to: \u2018configs/config.yaml\u2019\n    \n    config.yaml         100%[===================>]   3.95K  --.-KB/s    in 0s      \n    \n    2021-08-04 09:11:30 (63.4 MB/s) - \u2018configs/config.yaml\u2019 saved [4040/4040]\n    \n\n\n\n```python\nimport librosa\nimport IPython\nimport pandas as pd\nimport numpy as np\nimport os\nimport glob\n```\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```python\n!unzip small.zip\n```\n\n\n```python\nif not os.path.exists(\"scripts/get_commonvoice_data.py\"):\n  !wget -P scripts/ https://raw.githubusercontent.com/NVIDIA/NeMo/$BRANCH/scripts/dataset_processing/get_commonvoice_data.py\n```\n\n    --2021-08-04 09:17:34--  https://raw.githubusercontent.com/NVIDIA/NeMo/r1.1.0/scripts/dataset_processing/get_commonvoice_data.py\n    Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.109.133, 185.199.108.133, 185.199.110.133, ...\n    Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.109.133|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 6778 (6.6K) [text/plain]\n    Saving to: \u2018scripts/get_commonvoice_data.py\u2019\n    \n    get_commonvoice_dat 100%[===================>]   6.62K  --.-KB/s    in 0s      \n    \n    2021-08-04 09:17:34 (93.1 MB/s) - \u2018scripts/get_commonvoice_data.py\u2019 saved [6778/6778]\n    \n\n\n\n```python\nVERSION = \"cv-corpus-6.1-2020-12-11\"\nLANGUAGE = \"en\"\n```\n\n\n```python\nimport argparse\nimport csv\nimport json\nimport logging\nimport multiprocessing\nimport os\nimport subprocess\nimport sys\nimport tarfile\nfrom multiprocessing.pool import ThreadPool\nfrom pathlib import Path\nfrom typing import List\nimport yaml\n\nimport sox\nfrom sox import Transformer\nfrom tqdm import tqdm\n\nparser = argparse.ArgumentParser(description='Downloads and processes Mozilla Common Voice dataset.')\nparser.add_argument(\"--data_root\", default='small/', type=str, help=\"Directory to store the dataset.\")\nparser.add_argument('--manifest_dir', default='./', type=str,help='Output directory for manifests')\nparser.add_argument(\"--num_workers\", default=multiprocessing.cpu_count(), type=int, help=\"Workers to process dataset.\")\nparser.add_argument('--sample_rate', default=16000, type=int, help='Sample rate')\nparser.add_argument('--n_channels', default=1, type=int, help='Number of channels for output wav files')\nparser.add_argument(\n    '--files_to_process',\n    nargs='+',\n    default=['test.tsv', 'dev.tsv', 'train.tsv'],\n    type=str,\n    help='list of *.csv file names to process',\n    required=False\n)\nparser.add_argument(\n    '--version',\n    default='cv-corpus-5.1-2020-06-22',\n    type=str,\n    required=False,\n    help='Version of the dataset (obtainable via https://commonvoice.mozilla.org/en/datasets',\n)\nparser.add_argument(\n    '--language',\n    default='en',\n    type=str,\n    required=False,\n    help='Which language to download.(default english,'\n    'check https://commonvoice.mozilla.org/en/datasets for more language codes',\n)\nsys.argv = ['-f']\nargs = parser.parse_args(['--version',VERSION,'--files_to_process','validated.tsv'])\n\nCOMMON_VOICE_URL = (\n    f\"https://voice-prod-bundler-ee1969a6ce8178826482b88e843c335139bd3fb4.s3.amazonaws.com/\"\n    \"{}/{}.tar.gz\".format(args.version, args.language)\n)\n\n\n\ndef create_manifest(data: List[tuple], output_name: str, manifest_path: str):\n    output_file = Path(manifest_path) / output_name\n    output_file.parent.mkdir(exist_ok=True, parents=True)\n\n    with output_file.open(mode='w') as f:\n        for wav_path, duration, text in tqdm(data, total=len(data)):\n            if wav_path:\n              f.write(\n                  json.dumps({'audio_filepath': os.path.abspath(wav_path), \"duration\": duration, 'text': text}) + '\\n'\n              )\n\n\ndef process_files(csv_file, data_root, num_workers):\n    \"\"\" Read *.csv file description, convert mp3 to wav, process text.\n        Save results to data_root.\n    Args:\n        csv_file: str, path to *.csv file with data description, usually start from 'cv-'\n        data_root: str, path to dir to save results; wav/ dir will be created\n    \"\"\"\n    wav_dir = os.path.join(data_root, 'wav/')\n    os.makedirs(wav_dir, exist_ok=True)\n    audio_clips_path = os.path.dirname(csv_file) + '/clips/'\n\n    def process(x):\n        file_path, text = x\n        file_name = os.path.splitext(os.path.basename(file_path))[0]\n        text = text.lower().strip()\n        audio_path = os.path.join(audio_clips_path, file_path)\n        output_wav_path = os.path.join(wav_dir, file_name + '.wav')\n        tfm = Transformer()\n        tfm.rate(samplerate=args.sample_rate)\n        tfm.channels(n_channels=args.n_channels)\n        # tfm.build(input_filepath=audio_path, output_filepath=output_wav_path)\n        os.system(\n        f'ffmpeg -i {audio_path} -acodec pcm_s16le -ac 1 -af aresample=resampler=soxr -ar {args.sample_rate} {output_wav_path} -y'\n    )\n        duration = sox.file_info.duration(output_wav_path)\n        return output_wav_path, duration, text\n\n\n    logging.info('Converting mp3 to wav for {}.'.format(csv_file))\n    with open(csv_file) as csvfile:\n        reader = csv.DictReader(csvfile, delimiter='\\t')\n        next(reader, None)  # skip the headers\n        curated = os.listdir(f'{audio_clips_path}')\n        data = [(row['path'], row['sentence']) for row in reader if row['path'] in curated] \n        with ThreadPool(num_workers) as pool:\n            data = list(tqdm(pool.imap(process, data), total=len(data)))\n    return data\n\n\ndef main():\n    data_root = args.data_root\n    os.makedirs(data_root, exist_ok=True)\n\n    target_unpacked_dir = os.path.join(data_root, \"CV_unpacked\")\n\n    if os.path.exists(target_unpacked_dir):\n        logging.info('Find existing folder {}'.format(target_unpacked_dir))\n    else:\n        logging.info(\"Could not find Common Voice, Downloading corpus...\")\n\n        commands = [\n            'wget',\n            '--user-agent',\n            '\"Mozilla/5.0 (Windows NT 10.0; WOW64) '\n            'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36\"',\n            '-P',\n            data_root,\n            f'{COMMON_VOICE_URL}',\n        ]\n        commands = \" \".join(commands)\n        subprocess.run(commands, shell=True, stderr=sys.stderr, stdout=sys.stdout, capture_output=False)\n        filename = f\"{args.language}.tar.gz\"\n        target_file = os.path.join(data_root, os.path.basename(filename))\n\n        os.makedirs(target_unpacked_dir, exist_ok=True)\n        logging.info(\"Unpacking corpus to {} ...\".format(target_unpacked_dir))\n        tar = tarfile.open(target_file)\n        tar.extractall(target_unpacked_dir)\n        tar.close()\n\n    folder_path = os.path.join(target_unpacked_dir, args.version + f'/{args.language}/')\n\n    for csv_file in args.files_to_process:\n        data = process_files(\n            csv_file=os.path.join(folder_path, csv_file),\n            data_root=os.path.join(data_root, os.path.splitext(csv_file)[0]),\n            num_workers=args.num_workers,\n        )\n        logging.info('Creating manifests...')\n        create_manifest(\n            data=data,\n            output_name=f'commonvoice_{os.path.splitext(csv_file)[0]}_manifest.json',\n            manifest_path=args.manifest_dir,\n        )\n\n\nif __name__ == \"__main__\":\n    main()\n\n```\n\n\n```python\nfrom subprocess import call\nr=call('ffmpeg -i \"/content/small/CV_unpacked/cv-corpus-6.1-2020-12-11/en/clips/common_voice_en_1.mp3\" -acodec pcm_u8 -ar 22050 \"test.wav\"',shell=True)\n```\n\n\n```python\ny, sr = librosa.load(\"test.wav\")\n```\n\n\n```python\nimport IPython.display as ipd\nipd.Audio('test.wav')\n```\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"data:audio/x-wav;base64,UklGRkZYBQBXQVZFZm10IBAAAAABAAEAgLsAAAB3AQACABAATElTVBoAAABJTkZPSVNGVA4AAABMYXZmNTcuODMuMTAwAGRhdGEAWAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAA//8AAAAA//8AAAAAAAAAAAAAAAD///////8AAAAA//8AAAAAAAAAAAAAAAAAAP//AAAAAAAA//8AAAAAAAAAAP//AAD//////////wAAAQAAAAEAAQAAAAAAAAAAAAAAAAAAAAAA//8AAAAA//8AAAAAAQABAAEAAQABAAAAAQACAAIAAQD///////8AAAEAAQAAAAAAAAD//wAAAAAAAAEAAAD//wAAAAABAAEAAAD///////8AAAAAAAAAAAAAAAAAAAIAAgABAAEAAQABAAAAAAD/////AAABAAEAAAAAAAAAAAABAAIAAwADAAIAAgABAAEAAQAAAAAAAAAAAAIAAgACAAEAAAAAAAEAAAAAAAEAAQACAAEAAAAAAAEAAQAAAAAAAAD//wAA/////wAAAgADAAMAAAD+//7/AQACAAIAAQD///7//v8AAAEAAAAAAAAAAAD//////////wAA//////7/AAABAAEAAQACAAIAAQD///7/AAAAAP//AAADAAEA///8//z//f///wAAAAAAAAEAAgACAAEAAAABAAIAAQABAAAAAQADAAIA//8AAAQAAgD9//7/AgADAAIAAAAAAAAAAgADAAEA//8AAAAAAAD///7//f/+/////v/+//7///8BAAEAAAD/////AAAAAAEAAAD//wAA/////wEAAAD+//7/////////AAAAAP7///8BAAIAAwADAAYACAAKAAwADQAIAAAA/f8CAAoADwAQAA0ADQARABQAEgAQAAwACgANABEAFQAYABgAEAAIAAQAAwAIAA8AEAAMAAYAAgALABQAEwAIAP//9v/x//L/9v/8/wEAAwAHAAUAAQABAPf/5P/l//j////6//r/+v/4//v/9v/y//v/BgAKAAkAAAD6///////3//r/AgAEAAwADQD8//v/CAAEAPT/8//9/wUABAAAAAcAEQANAAEAAAABAAMACgALAAYAAwD///7/AQD///v/AQALABIAGQAcABkAFwATAA0ADwASAA8ACgAGAAAA+//8/wEACQAMAAkAAQD7////DAASAA8ADwANAAgACAAIAP7/+/8FAAoABAAAAAIABQAIAAkABAD+////BAAEAAEA/f/2//X/AQAKAAUA+//1//b//v8CAPn/9P/6/wAAAwAGAAgABQABAAQADAATABQAFQAXABQADwAKAAMA+//6/wAAAwACAAIABAAKAAkAAwD//wIA///0/+3/8v/3//H/7v/1////AwD/////CAASAA0AAwD7//b/8P/r/+3//f8QAA8AAADz//P///8HAAAA9f/4//7//f/4//f//f8AAPv/9P/1//f/9P/2/wAABAAAAAAAAwAEAAYACwAKAAMABAAKAAUAAQAJAA4ACAAFAAgACQALAA0ABQD1//D/+f////3//P/7//T/7f/z/wEADAASABEACwALABEADQD+//b//v8JAAQA9f/3/wUADAADAPn/+v8AAAMAAgABAP//+f/w/+v/6P/r//f/AAD7//D/6//s/+3/7//2//7//P/2//r/AQABAP3/AgAOABYAEgAJAAUABQAFAAgACgAKAAYAAwD///v/+//+/wUACgAMAAsABAD7//f//v8IAAMA8//1/wwAHgAaAA4ADQAKAAEA+v/8//7/+//6/wEABAD///X/7v/x////BgD+/+z/5v/x////AwABAP//9//r/+b/6f/r/+j/6P/s/+v/5v/j/+n/8P/4//3/+f/z/+7/7v/v//L/8v/u/+z/7//v/+n/6P/u//D/7f/1/woAFQALAAEAAQABAPv/+/8GAA8ADAAAAPr//v8EAAIAAQD///r/9v/0/+//6v/y/wYABgDw/+T/7v/4//X/9P8BAAgA///y/+7/9P///wMAAAD//wEAAgADAAgACQADAAIACgAUABkAGAAQAAUAAAAFAAYAAAD4//T/9//8//3/9f/s//D/9//7/wMAFQAhAB4AFwAVABEADQARABcAGAAQAAgAAQADAA0ADwAJAAEAAQAHAAcAAgD7//r/AAAEAAIA//8AAP3/8//s/+j/5f/n//L//P8GABEAFgAOAAMABAAMAA0ADgASABMADAAHAAgACAACAP7/AAAGABAAEgALAAgACwARAA8ACgAHAAIA+//2//r/AAAAAPz/AQAKAAkA///7/wMACQALAA0ACwD+//D/7//0//n///8AAPr/8f/x//n//P/5//P/7P/p/+r/6//t//j/CAAMAAcAAwABAAAAAwAMABEADgAIAAYAAgD8//3/AgABAP3/BwAYACAAGQATABYAGAAXABcAFwASAA8AEQALAAAAAwAVABwAEQAKABMAHAAXABAADwAOAAsADQAPABMAGwAjACQAIQAeABkAEgAPABkAJwAxADAAIwARAAkAEwAbABAABAADAAEA+P/2//3//f/3//H/7P/m/+r/8f/v//L/BAAFAO7/3P/a/9v/2//f/+P/6v/w/+//6P/o//T/AAAFAAIAAQADAAIA/f/7//3/+v/x/+v/7P/y//r/AQAEAAMAAQD+//r/+f/1/+7/8f/5//f/+P8EAAwABAD8//r/AwAPABIACgD///v/AgAPABsAIAAdABMAAgD2//P/9//8//3/+v/w/+P/5f/z//z/+v/3//L/7P/n/+j/7//8/wQAAgD///3/+P/v/+n/8P/7//r/9f/1//H/6P/m/+3/7//u/+7/8P/y//P/9P/1//b/9//9/wAA/P/3//f/+v/5/+//6P/s//L/9v8BAA0AEwASAAcA+f/0//n/+f/z/+v/5v/r//f/9//y//r/BQAEAPv//P8CAPv/7v/w/////v/2//j/AAACAAMABgAHAA0AFwAbABkAFQASAAkAAwAJABAACwD///3/AAD///v/+v///wQABgAKABIADAD///z//f/3//n//f/+/wUAEAASAA4ADwASABMAEQAMAAUA/v/4//b/+v8AAAIAAAD+/wEACAAMAAcA+v/4/wQABgD7//3/BgAHAAcADAAKAAIA/P/5/wQAEgALAPX/8P/2//r/+//7//D/5v/l/+f/4//a/9j/2v/e/+f/7P/r/+v/9P/5//v//v/+//3/+P/t/+v/9v/3/+//9/8GAAIA9P/v//T//P8BAP//9//w//b/AQD9//D/8P/1//X//f8HAAUAAgAHAAwABAD//wIACQAOABkAJgAoABwAFQAUABAACwADAPr/9P/z//j/AgAJAAUABwANAAoAAQD//wAA///+//3/AAAIAAsABwADAAAA/v/8//v/AQALAAcA+v/0//X/8v/r/+T/4//q//H/8//z//L/9P/4//b/7v/v//f//v/9//r/AQAKAAIA+f8BAAsADAANAA0AAwD7/wMAEgAWAAkA+v/6////AwAIAAcA/v/7/wAA/f/6/wEABAD6//T//v8GAAIA/P/8//3/AAAJAAwABgAGAA4AFQAYABUAFQAjAC8AKwAjABwADQAEAA0AEAANABYAFQACAPn/AgAEAP7//v/+//j/+f8EAAcA/v/7/wMADAAVABUACgACAAQABAAIAA8ADQAJABMAHQAaABcAEQAFAP3//P/+/wMABwADAP3//P/9/////f/1//X//v8EAAQAAwAGAA0AEAAKAAwAEwAWABMADQAHAAcADgAVABwAHAAWAA8ACwAHAAUABAADAAUABgAAAPz//P/0/+j/6//9/w0AFQAYABoAGAAOAA4AFwASAAYAAwAIAA0AEQAQAAgA/P/3//z/BAAAAPX/9P/8/wMAAwABAAUACwAGAP3/AQAGAAEA+v/5/wEABwD+/+7/6v/s/+z/9/8GAAQAAAAGAAgA///9/wkAEAADAPX/+v8GAAQA+P/w//H/8f/x//D/8f/s/9//1v/f/+//9//4//3////0/+3/+P8CAP7//P/8//T/7v/s/+r/7//2//L/7f/4//7///8EAAMA8v/r//X//f/7//j/+P/8/wQACQAIAAgACQAJAAoADQAJAP3//f8IAAcAAQADAP3/7f/l/+z/8v/1//b/9v/4//z/+v/4//v///8GAAgAAgD9//3////6//P/8//6//z/9P/s//L/AwAMAAUA//8DAAIA+v/6//f/7//x//j/9//5/wQABQABAAMACAAHAAMA/P/y/+7/8//4//b/7v/w//n/AAADAAIA+f/t/+3/9P/9/wMAAQD9//7/AgAFABAAFwANAP////8FAAIA//8MABsAGQAOAAUAAwAFAAIA/v8GABMAEQAFAAEAAwAIAAwACAABAAUADQAIAAAAAQAJABMADwACAP//BwAJAAcABAAAAP7//f/7/wMADwAMAP3/+f8CAAoADAALAAYA///8/wQADQAPAA8ADQAIAAcACgAEAP3////9/+n/2v/i//L/8v/o/+b/7P/q/+D/3P/h/+L/3//h/+n/6P/j/+j/9f/6//j/+P/6////AgD8//r/+//5//v/BQAFAP3/AgAEAAMACwAOAAEA+/8FAAwADQAOAA4ACQACAP//AgAKAA4ADQAOABAADgAHAP3/+f8BABAAFAAKAAYAEgAfACAAGAASAA8ADAAMAAsABwADAAMABQAHAAYACgAQABUAEgAJAAUACQAOABAAEgAQAAoABgADAAAACAAOAAYA+v/1//X/+/8EAAMAAwAKAAoA///7/wEACgAOAAIA8P/x/wMAAwDv/+j/7//x/+r/6f/t//D/8//9/wIA/v/4//b/+P/7//n/8f/x//r/+f/r/+r/+/8JAAgAAwABAAEAAgD9//b/9P/3//T/7//v//L/+v////z/8//s/+j/7//8/wgAEAAWAA8A/P/2//v/9f/p/+X/5v/m/+r/6//r//L/9//1//X/9f/v//D/+P/5//H/6//s/+//9/8AAAQAAgD6//L/9v/+//7/9//6/wEA+//s/+b/7f/4/wQAEAARAAsAEAAhAB8AEAAOABsAHwAZABIAEAAQAA0ADAATABwAGAAVAB0AJgAlAB0AFAARABcAGwATAAQA9//1/wUAEAAKAAwAGgAcABUAFwAXAA8ADwAVABAACQAPABYAFwAbAB4AGgAXABoAGwAOAPz/+v8OAB4AGAAMAAkAEAAWABQACQABAAAABAAKAAYA+P/t//H/+v/+/wIABQADAP///P/8//v/9v/s/+r/8P/3/wIABwD5/+v/7P/z//T/+v8EAAMA9v/o/+b/8//8//D/5v/x////AAD3//H/9f8DAAcA//8AAAcAAQD+/wgADQAFAAMACgAPABUAFQAFAPT/8f/1//X/+P8AAAEA/v///wcADQAMAAwADwAJAPz/+v8BAAMA/f/y/+3/8v/7//7//P/1/+r/4//n/+3/8P/v/+v/7P/v/+//9f8CAAUABAAKAAYA9f/0///////9/wIA/P/4/wEABQABAAMABAAEABIAIQAcAA4ABwAGAAEA+f/x//b/BwAOAAsACwAJAAUA///9//r/+v8EABYAGgAJAPz/AQAIAAsACAABAPn/9P/0//r/+P/v/+n/7P/1//r/7//f/9r/2P/X/9//6P/l/+D/5P/w//z//P/x/+3/8v/x/+7/7//y//X/9f/x//j/BgD+//D//P8FAPP/5//s/+r/5P/p//P/8v/s/+3/+f8GAAcA///3//H/9P/9/wcACAD///T/8//8/wQABAABAAIAAwAAAP7/AAD+//z/AgAEAAEACAAKAPz/9v8DAAgA///w/+H/4f/y/wAAAgD+//X/7v/w//b/+v/8//r/9v/3//f/+/8HAA4ACgD//+//4v/i/+H/2v/d/+b/5v/r//b/+v8DAAoA/P/v//j/+v/w/+//7//v//b/+//4////BgACAAUADQALAAYAAQD2//j/DAAVAA4ADgAWABcADAAEAAIABQAHAAkAEAAaAB4AGAARABIAGgAbABIADQAXACYALQAqACQAGwATAA4ACwAQABsAHAARABQAHgAaABgAGgAUAA4AEgASABAAEAALAAsAEwASAA0AGgAmACIAHwAeABoAGAAVAAsACgASABcAGQAZABAAAwAAAAYADgAIAPb/7//7/wEA/v/8//r/9v/4//f/9P/0//f//P8HAA0ACQAHAA4AGwAhABUACQAKABEAHAAkABwAEgAPAAEA7f/t//n//v8FAAYA/P/w/+7/8/8DAAgA9//s//L/+v8AAAEA9f/v//n/AQD///z/9v/v/+7/7v/q/+7/8//6/wIAAgD2/+n/3v/j//j////y/+7/8//5/wYADAD///L/8f/u/+//+f/9//z/+f/u/+f/8v/9//z///8IAAgAAQD///7/+v/0//P/+P///wQACAANAAsAAAD5//v//f/8//7/AAAIABYAFwANAAkABAD8/wYAFgAOAAIABwAIAAEAAwAIAAQA/f/0//L/AgALAAcABgADAPv/AQAQABAAEwAbABQACAAKAA0ADgAXABwAGgAXABIABwABAAAABQAJAAsAEgAdABUAAwABAAIA+//3//X/9P/9/wUA/v/1//b//f8KABQADgACAAIABwALAA8AEAANAAYA///8//z//v8BAP//+P/x/+v/4f/e/+j/8P/0//L/7f/p/+7/7f/o/+b/5P/k/+7/8P/f/8//0//i//D/8v/n/+H/6P/t/+X/4P/s//3//v/3//X/8//r/+T/3P/X/97/7P/x//D/8f/x//D/7v/k/93/5v/x//T/9P/y//T//v8GAAMAAgAGAAUAAQABAAEA+v/z//j/AQAEAAQABwAHAAMA//////z/9f/0//z/AAD3//T/+//5//L/9f/4//r/AgAAAPj/AAARABMAEgAPAAEA9P/y//H//v8MAAsACAAJAAEAAgAXABcABwAQACMAHgATABYAFgATABIAEgAUABwAKAAuACcAFgAMAAYA/v/9/wIABQAJAA0ACgAEAAIA+//2//r/AAABAAEABAAIAAoACQALAA8ACwAAAAcAHQAjABQAAwD9/wYAFAANAPj/8P/8/wsADQAGAAYADwALAPj/7v/z//X/8v/0//3/CAAIAPz/9//+/wIAAgACAP3/+P/5//f/9f/0//X/9//7/wEABgAOABYAFQALAAUABwAHAAQAEAAZAAwA+//+/wkACQAJAAQA8//p/+///f8EAAAA/v8DAP//7v/n//H/+v/+//z/+v/9//7//f///wIA/f/y/+n/6f/0////AgAKABEACwAEAAgABwAEAAUABQACAAMABgAGAAUA+//y//b/BAAIAAUAAQD9//z/AAD///X/8P/1//z//f///wUAAAD7/wIAAQD3//v/BwAGAAUACQAGAAAABgAIAAAA/v8CAAUABgACAPr//f8CAAAAAwAEAP7/BAATAAwA/P/8//7//v8DAAAA8v/z/wQAEQAXAB0AHgAaABEACQAHAAMA/v/+//v/+/8GAAYA9P/u//f/AAAIAAoA///2/+z/3f/X/+H/6//3//r/6//m//L/8v/y//3/9//i/+D/7f/8/xAAFAAEAP7////9//7/BAADAAIAAQAAAAUACAAFAAcACQACAPv/+P/+/w8AEQAAAP//EAASABAAGQAfAB8AFwAHAP3/+//5//j//f8AAAcAFgAhAB4AGwAaABMABwABAAQADAASABUAFwAYABYADgAEAAEABgAGAAEA+//4//n//v/6//L/9f8CAAsACwAJAAEA9//5/wQABwAFAAkADAALAA0ADQAIAAYACAACAPj/9/////7/8v/w//r//v/5//v////+//3//v/+////BAAOABMAEgANABAAFgAcACEAIQAeAB4AHwAdABwAFgAPABIAEwAKAAUACQAKAAcAAQD3//b//v/6//L/7v/0/wMADQADAPP/8v/3//f/9P/x//X/+v/2//H/9f/1/+//6//t//H/8P/r/+7/+v/3/+7/7f/s/+b/5f/p/+b/4P/f/+r/9f/t/97/4f/t//L/8P/v//P/+v/4//X//P/7/+//9P8AAPr/7//r/+X/4f/k/+3/7//v//f/AwD+/+//6v/u//P/8v/s/+n/+P8FAP//9f/z//D/7//t/+j/7/8IABcAFQALAPz/8v/3//7/+v/3//7//v/2//v/BQACAPf/+/8GAAcABQALABAADAADAPj/8//0//X//P8IAAUA8//q/+//8v/t/+n/5//p//L/9v/t/+D/3//m/+z/6//g/9f/3P/k/+j/7P/q/+L/5//y//L/7v/z//n/+f/t/+P/5P/q/+3/9P/0//D/9/8FAAYAAAACAAgABgD7//f/AwAOAAgA+//y//H//v8IAAMABgASABAABgADAAIACAATABQAFAAeABkADAARAB8AIgAkACIAGAAaAC0APAA3AC8AMQA1AC0AIwAhAB0AHwArACYAEQAJAAYAAQALABYADQALABMAFAAYAB4AFAAGAAcACgAMABcAJgAtACwAIQAaAB0AGAAHAPj/+P8AAAoADwALAAEA+v///wMA9v/s//L/9P/u//H/9v/z//b////9//X/8P/t//L/+v/+/wEACQAMAAUAAQABAPj/7//1//z/+P/z/wAAFAAUAAQA/f8AAAEAAwAJAAYA/f/3//L/7v/x//X/9f/+/wUAAwD/////AAD9//j/9v/3//n/+//7//f/+v8JAA0AAwD7//b/8v8CABgAEAD9//z/AAAAAAMABAAEAAgADAAQAAwA+v/u//j//P/v/+b/6v/4/wYACAADAP///P/7//3/+v/9/wsADgAFAAIABAADAAEA+//1//z/BwAJAAgABgABAAAABAD///f/+v8AAAAAAQAEAAQA+//z//L/8P/z/wIADAADAPj/+P/5//n/AAAGAAIABgASABAAAQD8/wcAEgATAAoAAAABAAQA/v///woACgD9//7/EAAaABkAHAAhABkADAAMAA0A/v/3/wIACgAGAAQAAwAAAAEADwAfACAACwD8/wAA/f/t/+T/5v/o/+//9v/y/+r/6P/y/wQAEAAFAPb/8//y/+7/6P/q//b//v/8//7/AAD2/+7/8//0//H/8P/t/+z/8P/t/+v/8P/z/+//9P/7//3/+//4//L/8P/u//D/+f/6//H/7v/t/+X/4f/o/+3/6//m/+v//v8OAAgA8v/l/+b/8P/6//f/7//t//L/8v/r/+v/+P8FAAEA9//z//T/9v/9/wIABAABAPn/8//+/wwACAD2/+r/6v/x//P/8//0//3/BwAOAA4ACQAAAAIACQAEAPz/AAAJAAgAAAD2//H/9v8DAA4ACwD8//H/+P8FAAUA+P/z//7/BwD///r/AQACAPr/AAAOAA0ABAABAAUADAASABEADgASABgAGAASABEAGgAZAAsAAAADAAcACgAOAAcA9//2/wQABQDy/+D/3f/l/+3/8P/x//b///8FAAEA/v8EAAwABgD9//j/9P/4/wcADgAMABAAGAAYABIADwAUABgAFwAQABAAEQAQABMAGQAVAAwABQABAAEAAQD4//X//f8JABIAFQAHAPr/+f/5//f///8DAP3/BAAcAC0AKAAZABYAGgAVABEAEgAGAPn/BwAWAAYA8//5/wQAAgD8//n/+f/7/wMADwARAAgABAAFAAEABAAOAAYA+/8AAAIA+v/7/wgADwAKAPv/9f/8//3/9P/u//D/8v/3//T/6//u//b/+P///wYA///8/wgAEAARAA8AAwD6//j/9P/w/+7/7//5/wIA/v/5//n/7v/f/+D/7P/5/wcAEAARABQAHgAiABwADgAHABEAEwAGAAEAAQD6//z/CQAMAA8AEwALAPz/9f/2/wEACwANAAoABQD+/wIACAD+//b/AAAFAPz/+P/7//3//P/0/+b/4P/l/+//9f/x/+r/6//y//P/8//y//L/8//x//H//P8HAAYABgAIAAgADAAMAP//9f/4/wEACQANAAkAAgD+////AgACAPv/9//7/wEACAAMAAwADAARABMAFAAZABgAEQAVACMAKwAkABwAIQAlABoADgAPABUAGAAaAB4AJAAlABoAEwAXAB8AIgAeABMACgALAAwACQAJAAkA///4//b/8P/t//D/8f/4/wQADAAHAPj/7f/t//H/7//t//X/+f/v/97/1f/c/+L/3//h/+j/7f/1/wQAAgDy/+z/6v/j/+T/7P/x//b/+//9//7/+//8/wEA+v/x//r/AwD9////BwAEAP7/+v/y/+7/7v/r/+z/9f/0/+v/5//k/+D/4v/q//P/+P/1//P/8f/u//P//f/3//D/9v/9/wQACgAIAAYACgAEAPj/+f/3/+v/7v/9/wEA///8//n//v8NABcAFgALAAMABgAGAPz/+f8BAAQACAAQAA8ADQATABIABwAEAAgACQAFAP3/+/8FAAkA/P/w//D/+P/+//v/9v/w/+v/7v/4//v//v8JAAwAAgAIABYAFAAJAAkADAANAAwABgAJAAwA/v/t//H/AAAHAAcA/v/z//L//f8EAAQAAwAGAAgABQD///n/9v/7/wAA9//p/+j/7v/v//L/+//4/+r/4//m/+7/8P/s/+v/7//1//v//f///wYABwAFAAkADgAEAPT/8//6/wAABAABAP3/AQACAPv/+f/3/+v/5P/p/+X/3f/l//j/+//w/+3/8v/1//T/8v/2/wAAAQD1/+7/9P/4//X/9//7//b/8P/x//H/8f/5/wEAAgADAAwAHAAfABIACAAJAAwACwAMAA4ADgAIAAUADgAWABMADgASABAABgAGAA8ADgALABEAEgAMABIAHQAVAAQABAAJAAUABQAUABgADgAFAAQACQAWAB4AHAAbABsAFwAXAB0AHwAbABIABwAHAA8AEgAUABwAHAAOAAcADgARAA0AEgAdAB4AFgASAA4ACQAIAAwADQAQABgAFwAKAAkAGAAaAAkA/v8FAA0ABwD+//z/+//9/wIA///2//L/8v/x//H/7v/k/+L/5P/c/9T/1v/Y/9j/3f/i/+b/8f/3/+r/2v/a/+P/5v/j/9v/0P/P/9n/4v/k/+X/6P/q/+3/8f/2//z//f/1//D/8f/v/+T/3f/g/+b/7P/w//T/+P/7//j/9f/6/wcAEgAMAP7/+P/9/wQABgAFAAQADwAiACYAGAASAB4ALAAyAC8AIwAaACAAKAArADIANAAoABsAHQAeABsAHQAjACgAKwAkABQAEAAbACAAFwASABAACgAJABUAHwAbABMAFAAcACAAHAAYABYAFQAVABoAGQAUABMAFQAMAP3//f8KAAoA///+/wMA/f/y//X//f/4/+3/7P/t/+3/8//8//n/7//w//3/AgD3/+3/7P/v/+r/4v/i/+n/6//s//H/7//i/+H/9P////f/8v/6//7/+f/2//b/9//7//z/+P/5//n/9f/y//f/+P/y//H/9v/2/+//6v/y//r/8f/e/9z/6P/q/+n/7//y/+7/9P/+//r/7v/t//L/9P/4//n/+f/6/wAAAQD4/+n/4v/l/+b/5v/p/+n/4f/j/+7/6v/f/+b/9f/4//P/8v/v/+3/9P/6//j/8v/y//r/AgD///T/9/8JABQAFAATABYAGQAYABUAEQARABAADAAIAAMA/P/+/wwADgAFAAEABAAAAPf/9P/3//j/9f/3/wAABwACAPv/+/8CAAMA/P/3////CgAKAAAA/v8GAA8AGQAeABQABQAFAAwAAwDy/+//9v/7//v/+v/6//3//f/+/wMABgD8//H/8f/u/+L/3f/g/9v/1P/X/+D/3//a/9T/0//S/9L/0f/S/9P/0//K/8L/wf/N/93/5P/i/9z/1v/U/9b/1f/O/8z/0P/T/9n/3//d/9b/2P/g/+H/5v/1//r/8v/x//f/9//z//T//P8FAAsACgAIAAcABQAHAAsACwAKABIAGAAWABUAFwAPAAoAEQAcAB4AHwAhACIAIgAiACYALQAwACwAJgAiACEAKQAyACwAIwAnACwAKAAoAC0AKgAoADEAOgA8ADsAOgA4ADYANAAvAC8AMgAvACsALAAoAB0AGQAgACQAIgAkACgAKAAmACQAHwAWABEAEgALAAAAAAAIAAsAEgAhACgAHgAdACoALgAiABcAFgAVABIAFQAXABIACQAFAAIAAgABAPv/+f///wgACwAHAAAAAAAHAA0ACQACAAMADAAQAAkAAQAKABAA/f/p//b/CgACAPz/CQAQAAcAAwALABEAFQAVABQAGwAaAAoAAAAEAAQAAAAFAAoAAwD4/+v/5f/s//b/9//6//3/7//k//T/CQAJAAUACQAMAAoABAD8//r/+f/0//P/AgALAAQA/v/7//j/+P/1/+v/6v/z//7/AQAAAAEACwAWABEABgAFAAEA/v8HABAABQD7/wAAAQD7//n/+v/2//H/5f/X/9n/5P/n/+v/6//n/+7/+//4//f/BQAGAPD/6P/v/+f/2f/d/+b/6P/q/+f/5P/t//f/7v/g/9//3f/V/9P/3P/l/+j/6P/m/+r/7v/z//r//v/1/+r/8P/9//3/8v/0/wYAEAAKAAcADgANAAIAAQAHAAcAAwADAAUABgAMABMAFgAaABwAFgAHAP//AgAEAP///v8BAPz/7//t//L/9v/7//3/9f/y//v/AQD6//n/BwAMAP3/8f/0//z/9v/n/+H/7P/z/+P/y//F/8//1P/R/8z/y//Y/+v/8f/r/+n/6f/j/+H/6v/t/+T/2//W/9P/1v/e/+D/3//m/+f/5P/n/+r/4f/e/+n/8//1//n/+v/1/+z/6v/x//r/9v/r/+n/7f/m/9z/5/8AAAgA///7/wYAEAAKAPn/7f/t//j/BwANAA4AEAASABAADgARABkAHAAcABsAFgALAAQAAgABAAQAEAAZABcAFwAaABMACAAOABYACwACAA0AEgAJAAoAGgAdAA4AAwADAAIAAQAGAAoABgABAAUADAANAAcACgAXACIAIgAdABoAHQAjACUAGQAMABEAHAAeAB4AHwAbABoAHwAfABkAFwAXABYAHQAnACUAGwAcACUAKAAgABkAGwAkAC0ALgAnACIAIQAmAC8ANAAvACwALgAnAB4AGwAYABIADAAIAAYACgAOAA0ADwAUABUAFgAbABcAFQAdABwADAAHABEAFwARABQAHQAcABIADQAWABsAFgAXACgAMAAiABwAJwAnAB0AGAARAAkACwAOAAkABQAAAPP/8v///wMA+f/q/9j/1P/k/+j/2v/Z/+r/9f/w/+X/4f/s//j/8//k/93/3//f/97/2f/W/9r/4P/f/+H/5//m/+T/5f/a/8T/xf/P/8j/xf/U/93/2v/Z/9v/2v/a/9r/4v/u//H/7v/w//P/9/////r/6v/l/+L/4v/x/wMABAD9//f/7f/r//L/9f/6/wkAEQAMAAgAEAAaABUACAAHAA4ADAANABIADgADAP////8CAAsAFQAaABEAAgD6//f/7P/l//H/AAADAP3/+v8CAAoAAADx//T/8P/f/9v/7P/7//3/9//y//b//P/1/+7/9f8BAPz/6//g/+T/8f/x/+P/4//5/wcA+v/v//H/7//v/wAABgD5//z/DAARABIAFgATABEAEAAOAAwACgAGAAkAEgATABAAFAAZABYADQADAPz/+v/y/+b/5P/r/+n/3v/g/+//+P/2//f/9f/p/+b/8f/3//v//P/3//f/AAD9//b///8SABcAEgAMAAUA/f/9/wcABgD4//H/9//8//r/+P/0//b/AQAEAP7/+P/x//T/BgAOAAwADQAHAPv/BQAUABMACwACAPr/AAAMAA0ADQAMAAYABQAJAAUABQANABMAEQANAA0AEwAOAP7///8TABcACgABAPv/+v/+//r/9f/4//b/8f/1//X/7//s/+n/6v/y//f/8f/z//X/7P/p//L/8P/n/+r/9P/3//X/9v/2//T/9//5//T/7v/k/9v/3//z//3/+f/0//T/+/8BAAIAAAAAAP3/9//7/wIACgARAA0ABAALABcAEwAOAAoA///5/wAABQAGAAsAEwAUABEADQAKAAgABQD8/+//7P/x/+7/5f/l/+n/6//s/+v/4//m/+z/5v/m//D/6f/e/+j/+f/7//b/9v/4//X/7v/u//X///8CAP//+f/z/+z/6f/t//T/9f/6/wQABwAJAA8ACAD7//j/+f/9/wgAEAANAAsACQAGAAcABAABAAgADgAKABIAGwAQAAcACwALAAUAAAD8/wUAFwAbABEAEwAhAC0ALAAjAB0AHQAUAAsACQAMAAwABgD9/wAACAD2/9//5v/0//L/9/8CAAEABgAUABgAFgAcAB8AFAALAAsADwAQAAoA///0//n/BQAHAPv/9P/5/wUACgD///L/+v8LAAYA9f/z//z/AQABAAIAAgADAAkADgARABkAHgAaABsAJgAtACwALwAvACoAJwAjAB0AIwAoACEAJQAvACEACwARACIAIgAbABgAEQAMABAAEQAJAAcADgAQAAMA9v/4//7/+f/s/+j/6//o/+b/8P8AAAUA+//u/+f/7v/6//n/9v/2//H/7//7/wEA+P/2/wAAAAD4//X/9f/5/wEABwALAAwAAQDw//L///8IAAgACQAMAAwABgABAAAA9//s/+//AAAKAAIA+v8CAAkABwANAB0AIAAeACQAKAAjACAAFwAFAAMAEgAXAAsAAgAKABQACgD8/wEACQAHAA0AFQAPAAQA/v/2//L//v8FAP//+f/1//T//P8CAPf/7v/y//j/+f/8//z/9P/v//P/+v/5//T/8f/2/wMABQD4//f/AgADAP3//v8DAAoAEQAOAAYACQAKAAQABQAIAPn/7f/w//L/7P/w//n/+//+/wgADgADAPX/+f8BAPj/7v/x//f/9//4//b/8f/x//P/9v///wIA+f/w/+//7P/s/+3/7f/u/+z/5v/i/+//+//9//f/6f/a/9n/2//a/+D/3//P/8f/0//Z/9L/y//S/9//4v/c/9j/2//h/+j/4v/T/9n/7P/n/9X/1P/Y/9j/2v/b/9r/4P/n/+z/9v/8//r//f8BAAAAAQD9//j/BQAPAP3/8v8JABoAEgAJAAsACAADAAQABgAKABEAEQAMAAsADAAHAAMA///6//r//P/6//f/+f/3//L/7v/x//j//P/8/wIACAAHAAkAEQANAAMABgANAA8AFQAcAB4AHQAQAAcAFgAhAAsA/f8JABAABQAAAAIAAgAGAAsACgAEAAAAAwACAAIABgAFAP3/BAAJAAEA//8HAAIA/v8IAA4AEQAYABAAAwANABIAAQD3//z/AwALABEADgAIAAgACQAFAAAA/v8DAAkADwAOAAUA/v8EAA8ADwANABQAGwAUAAsABgD9//f//f8BAPr/+P8DAAwAEAAVABAACAAMAA0AAgD9/wkAEgARABIAGgAdABwAHgAfABQACgAMABAADgATAB4AHgAVABAADwAKAAUA/v/4//n//v/+/////f/1//n/BgACAPT/9/8HABEAFgAVABMAGAAaABYAEwAUABMAEAAMAAcADAASABIAFQAXABMADwAQABEAFwAeABwAFwAOAAoAFQAfABgAEAAMAAMA+//+/wIABgAIAAQACAARAAsAAQAEAAoABQD9//f/9//2/+3/7P/6/wMA/v/3//P/9//8//r/9f/1//H/7f/z//v/+f/0//D/8//7//f/8P/3//7//P//////9v/1/wAAAgD8//n/+//+//3//f/+//7/+//1/+v/4v/k/+X/4v/m/+//7P/n/+P/3P/b/+X/6f/l/+X/6P/s/+//6f/g/+X/9f/6/+//8f/6//X/6f/n/+n/5//o/+n/7f/z/+7/4f/h/+T/4v/p//L/7f/p/+n/4P/i/+//8v/u/+z/6P/q//L/7f/m/+j/6f/u//j/8f/p//L/+P/4/wQACgAIABAAFAAKAAkAEQAKAAQACAAKAAsACwAFAAYADwALAAQACQAIAP///v8BAP7/AQAPABMADAAGAAcACgAKAAoABgD8//v/BgAIAPn/6v/n/+3/9P/z/+7/7P/w/+z/5P/j/+P/3f/f/+3/9P/w//D/8f/n/+D/5P/p/+X/5//y//b/7P/g/+H/6//x//b//P8BAPz/9P/0////DwAUAAwAAQD///z/9//6/wIABwAGAAQABAAKAAoAAgAAAAgAEAAVABgAFAATABgAGwAXABMAEgAWAB8AJQAoAC8AMgAqACIAHgAaABIACQAJABIAFQAQAAsACAAKABUAHQAaAA0ABgAMABcAGgAVABQAFAAUABIACAD6//r/AwABAPn//f8AAPr/+P/+//7//P/+/wIAAgACAAMAAQD+//7//P/9/wMACQAOABMAGAAXABIADQAJAAMAAAAFAAgA+v/0////BQD9//r/+//4//n/+v/3//3/CAAIAAgADwARAAsABQAEAAUABwABAPr//P8DAAsAEQAPAAQA+//8/wEA/f/5//z/+//7/wAA/P/t/+j/7f/x//j/9v/l/+L/6P/i/+H/8P/0/+3/7v/x//L/8//v/+r/7v/x/+//8f/0//f//v8JAA0ACQD///b/8f/t/+//8v/t/+P/5f/w//T/9v/6//3//v8HABAACQD7//n/9//w//f/BwAGAP3/+v/x/+v/+P8HAAgACAAHAP3//f8DAAEACAAVABAA///7/wAABQAJAAsACQAFAAYACQABAPX//f8QABsAFwARABIAFQARAAoACQANABEAEgAOAAoADQAQAA0ACQAFAAIA/v/8////BgAJAAcAAgD+/wIADgASAAoACQAVABwAFAALAAoADwASABQAGgAWAAoACAALAAkABwAFAP7/+/8CAAQA///3//T//f8IAAgABAAHAA8AEQAMAA4AHgAkABsAFwAZABUAEAASABEAEwAaABQABgAIABQAEAAHAAYAAQD3//v/EAASAP3/8v/z//D/8P/4//f/8//5//7/+v/1//T/+/8QABsADwAJAA0ABAD5/wIADgAJAP//+f/u/+n/9v8GAAcA/f/2//j//P/7//X/8//5////+P/s/+X/6P/v//f/+//5//v//////wQADQAMAAQAAQADAAgADwAEAPb/+/8HAAcABQACAPj/9P/3//j/9//3//X/+f/7/+z/3//l/+v/7//3//j/8P/q/+X/5v/v/+j/2//k/+7/4f/a/9//0v/F/8z/1//c/+j/8P/t/+j/4//b/9j/1P/O/8v/0P/R/83/zv/U/9r/3f/e/+D/7P/5//3//P/6//L/8f/8//z/9v/3//T/6//s/+3/5f/l/+v/6f/t//j/8//p//H/+f/u/+3/+//+//T/8//5//j/+P/6//7/BgAJAAQAAAABAAQACAAJAAUABgAIAAYACAAMAAgAAwAIAAsAEQAhAC0ANAA7ADIAGAAOABkAJwAyADEAIgAcACMAIwAaABoAIgAqACoAHgAVABkAGgAWABUAEAADAAIAFAAjAB4AEAALAAsACAAJAAsACgAJAAcA/f/4/wEABgD9//r/AgAPABgAGgAXABIADwARABIACgD///v///8NABYADwADAP3/9f/0/wEACAD9//X//P8DAAEABAAKAAkA+v/u/+z/7f/u//j/AwAGAAMA///9//7/AwAJAAgAAAD//wUA///0//T/9//4////BgAIAA0AEAAHAPv/9P/t//L//v/5/+z/7f/1//j//v8KAAwAAgDx/+T/4//h/+L/6//z/+3/6//t/+b/4f/n/+j/6v/4//3/9f/6/wUABwAQABkACAD1//r/AQABAAcADgANABAADQADAAAABQAGAAgACwANAA8ACgD+/wAADQAQAAsADwAVABoAHQATABIAHwAkABgAGAAZAAsABwATABUACwAIAA8AFQARAAQAAgAPABMADQARAB4AJwAmABwAGAAgACMAHwAeABkACgAIABQAFQARABUAGQAXABQAFQAYAB0AHgAcABIABAD//wIAAwAHAAwABQD7//n/+v/6////CAAOAAsA///1//b/9v/3//r/9//3//3///8AAAgAAQD2//3////0//H/9P/s/+f/6v/u//L/7f/m//T/AwD3/+3/8P/n/93/4f/d/9f/4f/p/+L/5v/v//D/8v/2//f/9P/y//P/8P/u//X/AAD///z/BwAKAPv/7f/s/+7/7P/n/+H/3f/f/+z/8//o/97/5f/u/+z/6v/y//n/+P/x/+7/8P/r/+f/7f/0/+//4f/Z/+H/6//s/+3/9f/7/wEADAAQAA0ACgAHAAcABgAGAA8AFwAVABYAGgARABEAIAAeABMAGgAfABUAEQASABEAFgAcABkAHwAlACMAJQAmAB4AHgAlACMAIgAlACIAJgApAB8AGwAiABwAEgASAA8ACQAOABQADwALAAgACAAPAA0A///2//L/5v/e/9//3P/a/+T/6v/m/93/1v/T/9j/3f/f/+n/7v/o/+j/7v/p/+j/9//8//P//P8FAPT/4//m/+//6//j/+X/8f/z/+v/8f/+//v/9P/4//z/+v/9//7//P8AAAQAAwABAPv/9f/1//r/+P/4////BQABAPr//f8EAAIA/P/z/+b/4P/n/+7/7f/p/+X/3v/c/+P/6f/m/+j/8f/0//D/7//w//L/8P/u//P/AQAJAAgABgD///X/8//6/wUACAD+//3/CAAIAP//CAARAAkACQANAAkAEAAZABAADAAUAA8ADAAWABIADgATABIADQARAAsAAQALABcAFgARAAwAEgAcABMABQAHAAIA+/8DAAAA8v8AABQAFgAYABYACQAHAAoA/v/0//r//f/+/wEA/P/8/wAA//8AAAAA+f/y/+r/4//p//P/8//z//b/6v/i/+j/5//e/93/5v/y//r/9v/2//v/+f/0//j/+f/4//3/BQAUACUAJwAdABkAEwAOABAAEAAVABsAEQD+//z/BAADAAMAAgD6//P/8f/s/+z/9v/8//v/+//4/+3/6P/t//L/+v8MABIAAwD9/woAEQAOAAwADQAPAA8ACQAGAAkABQD9//j/8//3//7//f/3//7/AwD6/+//6//s/+3/9P8EABIACQD2//T/AgAGAAAA+v/0//P/9P/t/+T/5P/q/+3/8f/+/wgADAAQABEABwD6//z/DAAVAA0ACAASABYADAAEAAgABwACAP///P/7//v/+f/6//r/+/8BAAkABAD5//n///8HAAwABwAHAA4ACAD7/wEACwAEAPv/AgALAA0ABgAAAAIABQD///v//v////3//v8FABAAGAAWABcAHwAhABUACQALAA8ACwAKAA0ADQANABIAEAAKAAoADQAKAAkADwASAA4ABwAGAAsAEAAQAA0ACAAFAAUABAD+//r/+/8AAAQAAwAGAAgA///1//r/AwD///v//P8BAAwADQACAAEABAD8//j/BQAOAA4AEQARAA0ABgD8//b/9P/x//b//v/6//3/FgAYAAQABgAQAAMA9v/9/wUACgAPAAwABgAJABIAFAANAAEA+P/2//D/6v/s//P/+P/2/+r/4f/l/+3/6v/i/9//3v/Y/9P/3P/q/+z/4v/m//T/8//j/9j/2f/b/+D/6v/s/+P/6P/y/+//4//k/+r/6P/i/+H/3f/V/9X/2f/a/9v/5P/n/+D/3v/m/+3/8//3//X/8v/2//3/BAAOAA0A/v/z//b/+f/4//n/+v/1//T//f8MAA4A/v/4/wkAFQARAA8AFQAYABkAGQAVABAACwALABEAEwANAAcABgADAAQABgADAAQACQAJAAcACwAMAAwAEAANAAcACAAAAPP/7v/v//D/9P/4//T/9P/8/wEAAwAAAAEABwAEAP7/CgAVAAoAAgACAPn/9P/8//z/+P/7//3//f8EAAQAAAAEAAsACwAMABAAEAARAAoA/v/+/wsAGQAgABwAFgAWAA4AAQD//wUABgAFAAIAAgALABgAHAAcABUABAD7////CAASABUADAAKAA4ACAAHABMAFgAQABAADQAAAPf/9P/z//3/BgAIAAkABwACAAAA/f/v/+X/6v/x//f/+f/z//X///8AAPv/AwANAAwADgASAAwABgAPABkAGAASAA4ADQAQAAsA///8//3//f8EAA4ACwAFAAgAEAAPAAkACQAUABgAEgATABoAFQAPABQAFgAXACEAKAAtADQAMwAnACAAHQAaABYACQD9/wEABQD///7////7//X/+P8CAA0ADAD+//j//f/3/+r/4v/e/+H/6v/r/+X/5P/i/9v/1//X/9P/0//b/+D/2//T/9P/4P/z//X/4v/U/9j/4P/h/+H/5f/e/8v/xf/U/97/2f/a/+P/5v/p/+3/6f/q//D/8P/z//v/+f/t/+n/7//8/wcABwACAAgADwAKAAQABQACAP//AgAKABAADAACAAMACwALAA8AHwAnACMAIAAeABEACQAQABgAEgAJAAgAEAAaAB0AEwAGAAYADwAWABAACwAaACoAHQANABMAFAAKAAwAFQAPAAoADwASAA0ABAAAAAAABQAKABEAGQAVAAkAAAADAAUA/P/2////CgAJAP//9v/z//r/CAATABUAEAAKAAcABgACAAQACQAHAAMABgAHAPv/7P/o/+7/7//r//T////9//n/BQAKAAIABQAPAAYA+v///wkABQD5//D/7P/v//X/9f/n/9v/4v/w//X/8P/m/+P/7P/4//T/7f/w//f/+P/v/+T/3//k/+z/8v/v/+L/2P/c/97/2//X/9T/1v/g/+n/6f/o/+P/5//y//X/8v/9/wgAAAD5//f/8v/x//f/9//v/+v/7//3//n/9v/4/wEABAAGAAkABAABAAwAGAAbABoAEwAKAA4AEgAOAA0ADAADAP//BgAEAPz/AAADAAEABAAIAAMABAAHAP//+P/7/////f/0//L//v8JAAUAAAAGAAQA9v/y//X/8P/o/+n/9/8EAAMA+//6//3/AgAJAAgABwAFAP//+f/3//j/AAADAPn/9P/+/wMABQAKAAwADgAaACQAKgAwACsAKAAuACsAIAAlACYAFAAOABgAGAARAA8AEQAZAB8AFgATABgAEgAKABYAJAAdABAAFgAmACEAFAAXACEAIwAkACMAHAAZABcAEAAOABEADgALAA4ADQAFAP3//P8FAA0ADAALAAcA+//5////+//z//X/9//+/w0ADwADAPn/9P/y//T/+P/7/wEAAwD+//b/8v/z//L/6f/o/+7/7f/p/+v/8f/v/+r/6f/p/+b/6//z//H/5v/m/+v/5v/j//H/+//3//P/9//5//v/+//5//X/8v/s/+L/3f/n//f/BQAOAAwABAAHAA4ACAD//wIABgD9//b//v8DAPn/8P/y//T/+v8FAAcAAQAHAAsABwAJAAoAAwACAAMAAgAKAA0A/v/7/wMA+P/s//n////2//j/AwAEAAAA+//9/wIAAQABAAQA/f/3/wIADAAKAAoABwACAAYADgAMAAIA/f8EAAgABgAFAP//9v///wwABAD//wkABQD4//3/CAALAA8AEAAKAAkADgAXAB4AFAABAAAABwD9//H/7v/0//3/AQD7//f/9//6////AwAEAAYABwAJABEAFQAQAAwACwAQABMADQAFAAkABwD7//z/AwAAAP//AwAAAP3/BQAPABIADAAHAAoADwALAAgAFAAfAB0AFAAMAAYAAgD8//j/9//1//H/7//s/+f/4//k/+b/6f/s//H/9v/0/+7/8v/6//r/+f8AAAUABQABAPj/8v/7/wYACgARABcAFAATABEABQACAAcAAgD4//b/9v/6/wEABAADAAgACgAJAAoABgACAAEA/f/3//j/9P/s/+f/5v/o/+//9//9//r/8v/1/wQABwABAAAA/f/4/wAABQABAAUABQAAAAUACgD///j//P/7//D/4//Y/9j/2P/S/9v/7f/q/+D/5//u/+n/5v/p/+7/8v/z//T/9//8/wIAAAD2//D/8f/v//L/9P/u/+v/8f/2//f/+f/8//7//P/6////DQATAA4ADwAOAAEA+v/7//r/+P/8//3//f/6//b/9f/8//7/8f/m/+v/9v8BAA8AIQApACIAEwAHAAMAAgAAAAEABQADAPz/+P8AAAgAAQD2//X///8CAPz/8//z//3/CwANAAIA/v8JABIADAAMABEADwANABUAGAAVABQAFQAXABYAEAAPABcAFQAMAAsAEAAZACEAHgAbACIAJAAaABQAFAATABEADgALAAkABgALABIACgD9/wIADgAPAA0ABADy/+z/7P/o/+j/7P/t/+//7//l/97/3P/Z/9b/0f/D/7r/uP+4/7j/sv+v/8D/1v/X/8//1f/c/93/2//R/9H/3P/k/+r/7P/e/9P/3f/f/9X/3f/s//H/+f8BAAMADAARAAsADAARAAoACAAQAA0ACgAVABkADgANABoAIAAeABwAHwAeABgAFgAbAB4AGwAXAA8ACgAPABUAEwALAAEA+P/3/wAACQAIAAEA/v/+//7//v/7/+n/2f/d/+v/7P/u//n/AQAEAAAA9v/0//n/8f/q/+7/7v/l/+v/9P/u//L///8AAP3/BwAIAAMADQAcACEAIAAcABkAHAAgABwAEgALAA8AGQAXABEAGwAoACMAHQAhACUAIgAbABEADgAWABsAHgAdABgAFQAaABsAFwAUABEAEQAXABkAEwAMAAwAEgAYABkAGQAXABIADgAJAAgAFAAgAB8AFgANAAYAAwABAPX/7f/y//T/7f/q/+X/4//p//L/+P/9//r/8P/s/+7/+P8CAP3/7//v//v/AgAAAAEACAAPAA4ABwACAAAAAQAIAA4AEQAUABkAIQAlACQAJAAoACkAKwArAB8AFQAfACAAEwAVABkADgAMABoAHQAbAB8AHQAXABYACwACAAgAEAAVAB4AIAAWAAsABwAJABMAGAAQAAgACQAPABQADgACAPr/+//+//7/+P/0//3/CAAIAP///f/3//H/7f/q/+X/4f/d/93/6////wMA+v/6/wAA/P/3/wMADgAIAAAABAAJAAwAEQAKAP7/AAAGAAYAAgAEAAQABAAAAPf/8//+/wcABgAEAAMA+//x/+7/8P/z//v//v/1/+T/2//e/+H/4v/j/9v/z//R/97/4P/a/93/5f/j/+D/4v/h/9z/2v/V/87/z//Q/9D/1//e/9z/2P/e/+n/8P/x/+7/8f/1//D/7f/6/wUAAwABAAAA/f/8//n/7//r//L/9//6//b/7v/q/+//+f//////AgAMAAgA9//9/w4ADAAGAAsADgAMAAoACQAMABAADAAKAA4ACwAEAAAA+P/z//v/AQD6//j//f8BAAQABAAGAAwADAAMAA4ACwAHAAYA+v/t//X/AQADAAgADwAMAAUAAAD3/+7/6//v//f/+v/5//r/+v/z//D/8v/z//v//v/4//P/9//x/+r/+f8QAA4A/v/8/wYACQAIAAMA9v/u//b/+//3//n/AwAJAAUA/P/4//f/8//v//v/CgAKAAgADQAPAA8AEQASABIAFAAXABAABAD+/wQACgAMAAEA8v/u//r///8BAA4AGAAVABIADgD+//f//P8AAAIABAABAAEADAAWABQADQAFAPv/8f/x//b/+P/2//v////7/wAABwAGAAMAAAD7//z/AQD///v//f/9/wIACQAJAAgADwAWAB4AHgAPAAoAFwAUAAgAEAAdABwAHwAnACMAHAAaABUAEgATABUAFAAPAAcAAwAEAA4AGwAcABEADAAGAPz/+v8DAAkADQAPAAoAAwAGAA4AEgARABQAHgAeABAABAACAAIAAAAAAP7/AwALAAcA+f/0//H/5v/k//H/+f/3//j/+//8/wQACgAHAAYAAQD3//v/BwADAPv/BAANAAoA+v/u/+//9//v/+D/5//7/wEA9f/y/wIADgAEAPz/AgAGAAQACQAMAAcABgAIAAMAAAAEAAMA+//z//P/+/8BAAQAEAAYAA4AAQAAAP3/+P/8//7/+//9/wMA/v/7/wMACQAJABAAEwADAPf/BAASABIAFAAZABQACgAIAAsADQARABUAEwAPAAsABgAIABQAHQAZAA8ACAABAAAABwAMAA4AEQATABMAEgAJAAAAAAACAP7/AQAIAAgABQAJAAgA///4//f/8//t/+b/4//k/+X/5P/m/+f/4f/c/+L/6v/x//j/+//8/////f/w/+L/4v/r/+7/5//k//T//v/3//P/+//6//n/AgAJAA0AEAAMAAQAAAD//wUABgD6//X//P/3/+v/8f/z/+//9v/3/+z/7v/z//L/+v8BAPX/8v/8//7//v/+//z////7/+j/4//r/+n/7f/7//n/8v/7//3/8//y//T/9P/4//j/+v/+//X/5v/q//H/7v/z//j/7v/n/+X/4//n//D/+P/7//n/9P/1//P/7//y//j/8v/z//z/AAAAAAQAAQD6//r//f8AAAAA8f/l//H//v/6//v/AwACAP3/AwAEAP7/AwANAAwABQAGAAsADgAMAAEA/P8HAA8ACQD///3//P/4//r/AQAAAAMADgANAAQACAATAAkA/f8IABIADwAQABUADQD7/+//7//1//z/AQACAP//BAAMAAkA/f/2//j/+P/5/wAAAgD//wAAAAD+/wEACwAMAAgADgAUAA0ABQAHAAcABAAHAAsABgABAP//AAAAAAAA+//3//v/BQAHAP7/9f/y//b/+//8//j//P8HAAoABwAFAP7/9f/z//j//f8CAAQAAwAAAPn/9P/y/+//6P/m/+f/5P/a/83/zP/Y/9//1P/J/9T/5v/o/+H/6P/7/wEA+//4/wAADgAVABEACwAIAAcACgALAAoACwANAA4AFgAbABAADAAXABwAGQAaABwAHAAfABkADgAPAA4ACQAOABAABQD9//7/AwAQABwAHAAXABEADAARABcAFgAYAB8AHwAXABIAFQAfACAAHgAeABkAEQASAA4A///+/wgACgAMAA4AAgAAAA4AEAACAPv//P8BAAkAAwD7/wMADgALAAgADgASAAoA/f/5//7/+P/u/+7/9v/5//f/8v/y//z/BwAAAO3/6//+/wgA/v/9/wcABQD9/////f/3//b/8f/u//b/9v/m/+b/8P/o/+P/8//5/+n/3//m//T//P/6//L/8//4//z///8CAPn/7P/v//7/BQAEAAQABgD+/+z/4f/u//7//P/1/wAAEgAVAA8ADgATABcAFQAPAA8AEgAVABgAEQD+//T/AAAGAPz/+/8HAAUA+v/+/wQAAgAHABAABwD8/wAABQAJABEAFgAaAB4AFQAGAAMABQABAAIABgAGAAYABwAEAAYABwACAAMADAAKAAIAAAACAAEA/f/y/+f/8P8BAAYAAgABAP7/+P/2//X/8P/t//H/8//t/+f/6P/v//f/+P/x/+3/9v/8//r/9P/w//X/BgAQAA4ACgAKAAoADwAWABQAEwAWAA8AAQD5/+//7P/4//n/6f/p//P/8//2////+f/z/wEABAD3//T/+P8BAAcA/f/w//j//P/z/+7/7//v//X/+P/2//z//v/3////BQD7//3/EAAMAP3/CwAZAAoA+/8DAA0ADQARABcADwAGAA8AEQAFAAEABwADAAEABgADAAIAAwD4/+//9v/3//P/+v/7//L/8v/7/wQADQAQAAYA/f/1//L///8NAAsADwAcABUAAgADAA4ACQAEABAAFQALAAoADQABAPr//P/4//P/+/8CAAMACwANAAYABgAGAP////8DAP7//P/9//r/+P/+//3/9P/x//r/AgADAP7//f8AAAIA/v/2//H/9//9/wAA//8BAAYACQACAPn/9//0//T///8EAAAAAwAGAAIABAAKAAIA+v8BAAUA+v/l/9L/0//m/+3/3//U/9v/5f/l/9//4P/o/+3/6v/j/9n/0//U/9f/1//Z/+H/6f/u//T/+v/7//X/9P/v/+T/3v/l//H//P8DAAUADQAVABEADgAYABkADAAKABUAFwAVABkAHgAXAAoAAwACAAoAFwAZABAAFAAZABEAEQAgACEAFQATAB4AJAAiABgAEAAYACIAJAAiAB0AFAAQABEAEgASABEABwD9//X/9f/+/wIA/P/8/wAA/f/4//v//f///wMA/f/+/w8ADwD2/+z/9P/x/+v/6//q/+z/9v/5//X/7f/b/9P/4//s/+n/9P8BAP//AQALAAsAAwAAAPz//P/7//b/+f8IAA8ABwADAAYACAAFAAUAEQAaABMABAD1/+v/7v/2//f/+P/5//f//v8IAAIAAQALAAwAAAD+/wQADgAeAB4ACwAEAAkADgAUABoAHAAfAB0AEgAOABQAGAAXABcAFQALAPr/8v/4/wAA/v/7//3///8DAAUABAAEAAgACwASABMADQAOABcAFQAMAA4AEQALAAYACAAIAAQABwAOABMAGgAeABIAAQAFABIAFwATABUAFwAXABcAFgAPAAwAFwAhAB0AGQAcAA0A9v/0////BAAJAA4ABwD8//z/BAANABAACgAIAAwAEAASABQAFAAXABYADAACAP//+//4//n///8FAAQA9//r/+r/7f/z//j/9//3//v//f/+//r/7v/r//D/5//U/9b/5v/t//L/9//x/+j/5f/q/+v/6f/r/+3/7P/p/+b/6v/y//X/6f/d/9//6P/q/+r/7v/y/+//6f/t//T/7//h/+L/8f/5//L/7v/4/wQAAwD8//X/8f/5/wIA///5//3/+v/u/+b/4//e/+P/7v/x//X//v8AAPn/9v/w/+j/6v/v/+3/7f/t/+T/3//i/+D/4P/p/+z/8f8BAAkAAgD+/wAAAQADAAIA/v8EAAkABgAOABkADAD3//T/AAAJABIADwAFAAMABwALABMAGQARAAUABAAGAAQAAwADAAIAAgAHAAMA/P///wgACQAKABEAGgAfABgACAABAAIAAwAMABgAFAANABcAGgAQAA4ADgAGAAUABgAEAAgACAD7//X////8/+//8v/+/wAA+v/6//3//v/6//L/7P/u//P/8//x//H/8//3//z/+v/0//P/+/8EAAkABAD///v/9P/q/+v/9f/7//7/+//y//L/+v/8/wAABwADAPn/9//z/+//9/////r/9v/3//P/8//9//z/8P/w//f/9v/s/+P/4v/4/xEAEQAIAA0AEQAPABYAHgAaABcAEwAIAAUADgANAAkADgAQAAsACAAIAAkADAATABAAAAD2/wIAEAAMAAIAAgD///b/+f8FAAQA9//v//D/8P/v//H/9//5//n/9P/z//H/7v/y//v//v/4//b/8f/u//j/BgAEAP3//P/4//X//P////z//v8CAP///P/+/wEAAQD///z/BAAOABQAGAAZABEACgAPABEACgAIAAoACgAIAAwAEAAMAAgACgAIAAIAAQAJAAgA//8CAAcABAAFAA0ADAAIAA8AEAAGAAoAFgAQAAAA+//6//b/+/8IAAsACAAPABUADwALAA8ADAAFAAYABQD5//T/8f/q/+//AAABAPL/6P/n/+b/6f/z//T/6v/k/+v/8//z//T//P8DAAYABwAEAAAABgAQAA4AAQD9/wkAEgAHAPv//f8AAAIABwADAPT/7v/z//b/9v/9/wcADAAKAAUAAQD+/wAACwAVABIADAAPABYAGgAcABkAFQAZACIAJAAgAB0AHAAaABYADwAMAA8AFQAWABgAFgAKAPr/+P8DAA4AFgAcABwAGQAbACYAKQAfABAACQACAPf/+f8JABAABwAAAPn/7//u//T/8//v//H/8P/u//T//P/7//b/9f/9/wEA8//n//D/+f/3////DQAMAAgADAAKAAAA/f/6//P/9P/+/wUABAD7//X//f8KAAwABgADAAMAAwD+//r//P/8//b/+P8CAP7/6//b/9X/4P/w//H/5P/d/+H/5P/k/+P/3P/e/+f/6f/k/9//2P/Q/9b/5P/m/+D/4//o/+P/4f/n/+T/3//l/+v/5P/d/9//3//Y/9j/4f/k/+D/4f/l/+T/6P/y//P/8P/0//P/6v/n/+3/8f/x//P/+v8GAA4ADQAOABEADQAHAAMAAAADAAwADQAIAAQA/P/5/wIABwAGABcAKwApACkANAAvACMAJwAyAC8AKwAsACwAKwAoACQAHwAaABsAGwATABIAHgAjAB4AJwAxACYAHwAkACEAGQAbABwAFAAIAAIA/f8CAAcAAQD3//T/9f/3//j/9//z//j/AgAGAAsAFAAcABwAGwAZABIACwAIAAYACAARABgAFAANABIAGwAWAAkABAAFAAQACQATAB0AIAAaABQAHgAsACkAHAAXABoAJgAwACoAIQAiABYABAAGAA8ACwAPABEA+//q/+3/7//y//n/8//j/93/3P/d/+X/4//V/9H/1v/d/+L/2v/M/8//1f/K/8X/0f/T/9H/2f/a/9L/1v/b/9j/3P/k/+L/5P/w//f/8P/l/9j/1P/d/+X/4v/c/9j/0//T/9b/1P/S/93/5//o/+7/8v/p/93/3v/j/+j/8P/0//X/9P/x//T/9//7/wYAEAAGAPr//f/2/+D/3v/t//P//P8CAPb/8P/2/+7/3//j/+3/7f/y//H/4v/g//L//P/4//n/BAAJAAYABAABAP//AQAIAAkABgAJAAgAAgACAAgAEAATAAwABAAKAA4ABAACAA8AEwAOABEAEwAQABMAFQAQAA8AFQAbAB4AHwAeABgAFAAZACQAJQAkAC0ALAAbABIAFAAOAAwAGwAhABUADwAUABcAGAAZABIACgAJAA0AEQAWAB0AIgAiACUAKQAkABsAGwAiACcAJQAdABgAHwAoAB4ADwAQABoAHAAZABUADwANABMAEAAEAAUAEgAcACAAHgAYABsAKQArABwAEwARAAoABQAFAAYACAAMAAgABQAKAAgAAgAHABMAFAAKAAUAAgAAAAAABAACAPb/7f/z//7////2//n/AwAGAAUABwAJAAkACgAFAPr/8f/t/+r/5//j/+P/7f/x/+r/6P/y//T/7//q/+H/3f/h/+X/5//x//7/AgD9//H/6P/x/wIABgAFAAoADwAQAA4ACAACAAQACAADAP3///8BAAUAEQAaABUADQAQABYAGwAcABMACAAMABMAEAANAA0ACAAJABAADwAMABMAEQAIAAYABwAEAAUACwAJAAUACAAQABYACwD+//v/8//o/+v/7P/l//D/AgD5/+z/9P/6//f/+P/z/+//9v/2/+j/5v/r/+r/7v/3/+z/4f/t//7////7//z////9//v/+f/z//D/9//7//f/9v/2/+//8v/9//3/9f/w/+j/3//n/+//6v/l/+b/5v/g/9v/2//k/+3/7//o/+L/5f/s/+X/4v/r//D/8f/8/wMA+v/z//X/8f/z/wQACQD3/+n/8f/8//f/6f/k/+T/5f/r//D/6//n/+f/4P/i/+3/6P/Y/9v/5v/l/+L/5P/l/+j/6v/s//b/AwAGAAgAEAAUABYAGQAWABAADAANAAsACAAGAAMAAgAIAAoAAgD6//3/AgAFAA4AEQAKAAcABwD5//X/BQAOAAMA+f/z//H/9/8BAAIA///6//X/9//+/wIACwAZABYACAAFAAYA+f/z//r/AAD//wAA/f/5/wEACwD9/+n/7P/9/wAA9P/t//D/8v/y//b/9P/p/+b/8P/1/+//7f/6/wwAFAANAAsAGwAhABYAEwAYABYAEwAVABEAEAAWABUAEwAYABwAHQAlACgAHwAcACEAHQAPAAoAFAAeABwAEAAJAAkADwAZACAAIgAkACcAMAA1ACoAGwAcABsACwAHAA8ABwD2//z/CgADAPT/9P8BAAkACQALAAQA9f/w//r//v/1//D/9f/8//v/9P/z//7/BwAHAAQACAARABQADQALAAwABwABAP///v/9//z/9v/4/////P/3/wAACAADAAcADgAJAAEAAQAKABMAEgAIAP///f8BAAsACwABAAQACQD+//b/AAAIAAcABQD7//X//P/+//H/5v/g/9j/1f/Z/+T/7v/r/+T/6//0//X/9P/y//D/9P/2/+7/7v/z/+//7f/t/+X/5f/t/+7/8/////3/8v/w/+3/6f/y//T/5P/b/9z/1f/P/9P/1//b/+f/9f/5//z/AgAJAAYA/v/6//3/AAADAPr/7P/s//j/+f/u/+7/+f8AAP///P/9/wAA/f/2//b//P8CAAEAAgAHAA4ACwADAAEA///5//f//v8FAAsADgAOAA8AEwARAAcA//8CAAgABAD3/+//8//9//z/9v/7/wkACAAEAA4AFwAQAAYAAgD//wMACgANAAoABAD7//n/CAAUAA8ACgATABgAEwARABMAFQAYAB4AIwAmACcAHQARABAAEAAIAAgADgALAAQACAAPAAsACAAKAAgAAQABAAkABQD9/wMAEwAVABAAEQAWABkAFgARABIAEwAKAAAA/v/9//3/AwAGAAAAAAAEAAMACQAOAAkABQAGAAQACQAWABYADwASABQAEwAaABUABAAEABIADgABAAIACwALAAUA///8//7/AwALABIAEgAJAP3/9f/3/wAABgAIAAUAAgAEAAgABwAAAPr/+P/+/wcABQD+/wIAAADt/+n/+v/9//P/9P/2//n/CQAOAPv/8/8FAA4ADgAOAAsACwASAAsA+P/2//7/AgALAAcA9P/n//D/+//8/+7/4v/n/+3/6P/t//P/5//a/+L/7f/t/+r/5f/l/+b/2//Z/+f/6P/g/+X/6v/l/+H/3f/d/+j/6v/h/+n/+P/z/+7/8P/p/+H/6P/x//X/9//3//z/AgD9//v/AQD9//T/8//x/+//+P/3/+3/6//q/+n/+f8KAA4AEQAYABYAEAAHAP7//f/6/+//6f/u//H/+P/+//n/7//q/+v/9v8AAPj/7f/y//b/+P/4/+//7P/2//T/5v/l/+j/5//r//D/8f/5//3/+f8BABIAEQAKAA8ADwAEAP//AwAEAAMABQAGAAIA+//+/wEA+f/x//T/8f/t/+//7P/h/+X/8f/w/+b/2//Y/+X/8//0//T//f/6//X//f8AAPj/8P/m/93/5//w/+v/6P/t//D/9P/9/wIABwAKAAAA/f8HAAgA/v8CAAgA+//x//v/BQD5/+n/7v/9//z/9P/8/wsAEwAXABQADQAJAAgA/v/6/wEAAwAKABkAHwAXAA8ACwAOABcAGgAcACkAMgAqACQAJAAZAA8AFQAgABsAFAAYAB4AEwAGAAoAFgAUAAoACAAMAAsABwAGAA0AEgAPAA4AEQAOAAoADwAXABoAHQAlACYAJQAmACMAGQAVABwAIAAZABQAFwASAAsAEAAdACAAIAAeABwAHwAkACAAFwASABIAFAAYAB0AIwAeABMAEQAQAAkABwAOABgAGAARAA4AEQATABQAHgAjABYACwAPAA8ACwAUACAAIgAfABwAFQARAA4AEQAfAC4AKQAcAB4AJQAfABIAEwAcABwAFgAUABcAHwAnACoAKgAqACEAGAAdACMAHQAWAA4ADAARABAABQAFAAQA9v/x//r/AQACAAUAAQD+/wEA/v/2//r/AQD8//P/8P/z//n/AQALAA4ABwALABIACAD+/wUABAD8/wIAAgDv/+b/6v/p/+n/5v/X/9n/6v/r/+b/7v/u/9z/0//W/9n/2v/Z/9b/2v/d/9f/0f/S/9T/1f/c/+n/5//W/9T/4f/h/+H/8P/2/+v/7//7//n/8P/s/+r/9P8CAPz/8v/y/+z/3P/f/+j/4P/X/9//6//s/+X/3P/d/+b/8P/u/9//1v/c/+f/7f/r/93/0//V/93/5f/q/+b/3v/a/9n/3P/m/+f/4v/m/+P/2f/g//b/BQAKAAYA9f/s/+z/5P/a/9z/5P/o/+//8v/x//P/+P///wIA/f/y/+v/7//9/wcABAABAAEA7//Z/9//8//8/wEAAwD9//j/+f/9//z/8//t//n/CAAJAAIA//8BAAoADQAKAAwAEAAHAPr/9//7//z/9//y/+//8P/v//L/8//r/+j/9v8FAAIA9v/u/+3/9f/3//D/7//0//f//f8CAPn/6//s//r/+//s/+T/8P/+/wIAAQABAAUAAgD0/+r/+f8MAAkA//8JABIACwACAAMAAwADAAcABwAJAA8AEAANABAAGAAVAAoABgANABQAEgASABsAIgAgABYACgANAB0AIwAiACkAKAAcAB0AKgAsAB4AEAAMABAADgAPABoAIQAcAB0AIgAbABUAFwAVAA8ADQAHAAEACwATAAkAAAAHABAADAADAPz/+v8AAAUA/P/y//f/AQACAAQABgABAAAABgALAA8ACQD0/+n/9f/7//L/9f8CAAkACAABAPv/+f/+/wIAAAD8/wIADwAUABIADgAMAA4AFQAaAB8AGwAJAP7/DgAeABkADAAEAAQABAD6//b/AwAJAAMABQALAAQAAAD+//r/+v8AAAAA///+//z/+//7/wAACwAGAP3/BAAKAAAAAQARABQACAAGAAwAEAAJAAMACAAMAAQAAQAGAAoADwASABEADwALAAEAAAALABMAFAAUABQAFAAOAAcACwAUABcAGAASAAkAEQAdABsAHAAgABYAEwAYAA0A/v/+/wAA/v/7//X/9v8AAAEA+v/6//z/AQACAPz//v8AAPT/7f/z/+n/3v/m/+r/6f/x/+v/2v/d/+P/3v/k//D/8v/y/+3/5//x//v/8v/q//H/+//7//L/8f/9//n/6P/w//z/8v/u//T/7//p/+7/7v/x//P/4//d/+n/8P/v/+//6v/n//D/+//4//H/+P8FAAAA9f/9/wAA8P/v/wAAAgD5//f/7v/m/+r/7//3/wgAEAAMABIAGwAXABUAGgAfACEAIgAhACEAIwAjAB0AFAAaACIAIQAfAB8AFgARABcAFwAVABoAEgABAAcAFAAPAAgAFgAlACIAHgAkACsAJQAdABwAFgAOABMAGgAYABUAGAAQAAQAAQAEAAIA+f/1//v/AwAHAAoADgAIAPr/9f/5//r/+v/7////BwANAAgAAAD//wEAAAABAP////8EAAMA/v/+/wIABwAKAAgA/f/y//n/DgAXAAcA9f/7/woABgD7//f/+v/7//f/8f/r/+X/5//0//j/6P/a/97/6P/s/+n/5v/s/+3/5//r//n/+//8//z/7v/e/+b/9v/9//f/7P/q//L/9//1//T/8//v/+7/7//x//P/9//+//r/7f/w//3/+P/u//H/9v/0//L/6v/f/+b/9P/4//D/6v/x/wIABQD9//j/8//o/+D/4P/k/+f/4v/e/+T/4v/U/9H/1f/R/9D/2v/r//P/6f/c/93/3//g/+j/6v/g/93/4f/k/+j/6v/t//P/7//e/97/7//3//r/+P/z//f/AAD6//H/9v/+/wQACQAHAAQABgAAAPf//P8FAAYABQAGAAEA+/8BAAkACQAHAAsACAD7//T/8//t/+f/6//7/w4AEQABAPj///8EAAMACQAPAA4ABwD9////BwAFAAAABgAJAP3/9P/1//P/7//7/wcA+//y/wQAEwACAOv/6P/v//P/+f////n/7f/r//j/CgAYABgAEAAWACEAGAANABYAIwAoADQANgAdAAsAFwAnACUAGgAUABUAHAAgAB4AGAAVABMAEgAYAB8AIQAaAA0ABwALAAoA+//u//D/9//+////+//+/wQA//8BABYAGAD+//3/EgAPAAMACQAJAP//BAASABAACwAQABQACwAEAAkAEAAQAA8ACwAGAAYA///u//P/CAAMAAMAAwAGAAkAEwAYABUADwAIAAkACgABAAYAIAAwACgAHAAaACIALAAqACQAHQAUAA8AGgAfABwAGwAeACEAKQApAB0AFwAdACAAFwAKAAsAGAAdABcAEwASABUAHQAiACoAMwApABcAGAAeABsAIgAkABMAEgAjACAADgANABEACAD4/+v/6//1////AwD5/+v/6//0//b/9v/0/+z/7v/5//T/5//m/+j/5P/l//D/9//6//v/+v/w/+H/3P/p//n//v/z/+P/3P/c/9r/3v/r//L/+v/+//P/8P/9//v/6f/p//b/8v/l/+D/4P/e/9n/1P/a/+3/+f/3/+7/5f/l/+3/8v/2//v/AAAIAAwABAD5//v/AAACAAYACwALAA4AFQAYABYAFQAWABkAHwAgABIAAwAIABUAGgAYABAA/v/z//r/AwAGAAYAAgD6//P/8f/9/w4AEgARABkAFwABAPr/CQATABIAEQAOAAwAFAAWAAoABwAPAA0A/f/y//H/9v8HABkAEgD5/+v/6v/y/wIACADy/9n/1//j/+//9f/0//T/+//8//v/BAALAAoABgAEAPz/9v/5/wEAAQD8//v//P/5//r//v/z/+H/3//m/+n/5//f/9D/yv/S/9//6v/s/+X/3P/X/9b/5f/1//L/5P/a/9z/5v/r/+X/5f/t//L/9v/6//P/6//u//H/8f/1//b/9P/0//H/6v/q//T/+f/8/wIAAAD2//L/9//2//T//P8EAP///f8JABEADQALAAsAAwD6//z/AgAAAPz/AAACAAIABgALAA0AFQAUAAgAAwAHAAgADwAZABIACQAOAAwAAQAEAA8AEgARABMAEQAOAAQA+f/7/wwAEwANAAEA/f8CAAYABwALAA4ABwABAAMABAD9//n/+f/5//r/+//6/wAACQAJAPv/8f/3//////8DABMAHgAcAA8A+//w//f/AQABAAAAAgADAAAA/v/8//v///8HABEAEAAGAP//AAAFAAoADQACAPf/9//6//j//P8HAAkABgAHAAQA/P8EABEABgDv//D//f/9//v/AgAAAPP/9P8CAAUA///+////+v/9/wkADgAJAAgACwAKAAgABgAGAAkAAwD2//L/9//1//P/8v/3/wcAEwAHAPr///8IAAkABgD6/+z/6//3/wMAAgD2//P//P////3//v8BAAEAAwD9//X/+f8DAAQAAQD5/+r/4v/k/+v/9v/+//r/9P/1//P/7v/u//H/9f/3//3/AQD6//L//P8PABIACAAAAPr/9v/z//T/+v8BAAEAAgABAPz/+v8AAAsAEgAOAAIAAwAIAAQAAQALABEADgACAPf//P8IAAMA9v/y/+//7v///xAADgAMABIAFwAcACAAGQAPAAkACAALAA0ADgAPABAADwAKAAwAFQAZAAsA/f8EABQAHQAgAB0ADwAAAAAADAAWABoAGwAUAA0AEQAWAAwADQAhACQAEwAMAAgA/f/6/wAA+//2//j/+f/+/wgACwAHAAgABAD6//D/6v/u//X/+f/9/wQAAQDx/+b/6v/+/wwABwAAAP7/9f/s/+3/6//n/+7/9P/0//j//v/6//P/9P/7/wMABQAGAAwADwAJAP7/9//1//z/AQAFAAsADAABAP//AwD9//j/AAALABQAHAAYAAkA+v/y//H/+/8BAPr/8//3//3/+//1//P/9/8AAAkADAAGAPj/8v/7/wQA/P/w//L///8GAAUAAwACAAAA+v/z//H/+/8GAAcABgAIAAYA9//v//v/AwADAAUAAAD0//n/BwAFAAAAAwAAAPj/+P/3//X//P8DAP//8v/o/+v/8v/x//D/9f/w/+f/6P/o/+H/5f/q/+r/7P/r/+P/6f/6//z/+P/5//T/8/8BAAMA9f/v//P/7//s/+7/5//i/+f/7v/z/wMAEAAFAPb/+/8BAPL/4v/p//f/+v/4//r//P/8//v//P/4//T/+P/7//r/+f/2//L/8v/v/+f/5f/v//X/+v8AAAAA/P/9/wAABAANABIACwAEAAgACwAJAAQAAgAFAAsADgALAAgACgAKAAgAEAAaABkAFgAUAAkA/P8AAAcACAAIAAcACAAWACUAJQAlACgAIQAXABIACgAJABUAGgAQAAgACQAGAAAAAgAJAAkAAAD//wwAFgATAA4ADAAQABsAGwANAAcAFAAeABgACgD+/wAABQD9/+z/7P/2//T/8P/3//3/+//7//z/9v/t/+v/8P/2//7/CAAMAAgABwAIAAEA9v/y//D/6v/r//j////3/+3/7v/8/wMA/P/5//f/9v///woAAADu/+j/3//Z/+n/AAAGAAQAAQD8//r/+v/8/wMADgAQAAMA9f/y//3/AwAAAAAAAAD5//f/+v/4/+//7f/z//X/7v/r//X//P/2//X/+P/x/+n/8P/y/+j/5P/s//P/8//3/wgADwAEAAAACgAHAPv//P8BAAMACgANAAQA/v8BAAUACQAGAPn/+P8EAAIA+P/4//r/7//k/+D/5f/y/wMAEAAOAAMA/v/+//v//v8OABkAFwATABIADwANABAAEAAMAAUAAwANABsAIgAeABQADAAIAAcACAAMABgAJQAnABwAEgAQABMADgAHAA0AGgAcABIACwAJAAcABgAEAAQACgAQABAACAAAAAIABQACAAAADAAbACEAIwAeAAsA+v/4/wEACgALAAMA//8EAAwADgAOAAoACAAOABsAJwAhABAACgARABEADAAOABcAHAAdABwAHQAcABgAFQAXAB0AJgAuACcAFgALAAgABwAJAAoABQAGAAgAAgAAAAgABwD+/wYAFAAOAAQABQADAPv//f8GAAUAAQABAPj/6//0/wMAAwD//wUAAADu/+b/6f/j/9v/5f/4//z/8//w/+7/6f/p//D/+v8EAAIA8//w//n//f/6//v/9P/q/+3/9v/x//D/+//9//L/8v///wcAAgD3/+//8//9//n/6f/g/+n/8v/x/+3/6P/j/+j/+P/+//b/8P/3/wUACgACAP7/AQD8//X/AAAPAAkA/f/5//b/9/8AAAMA+P/y//3/DAAQAAoABgAKAA8AEgARAAoABgAMAA4ACgALAAsACAAQABkAEwAKAAgABAADAAYAAAD4////CgANAA8ADwAFAAAAEAAgABYA/f/z//z/AAD8//f/8v/v//j///8CAAUABgD///z/AQADAAIA/v/s/93/4f/l/9//3f/p//j//f/y/+b/5//q/+3/8//t/9//3v/o/+n/6P/s/+r/6v/y//n/+v/3/+r/3f/b/97/4v/j/9z/2f/n//f/+P/1//P/7v/m/+P/6P/w/+//6v/u//P/8f/x//f/8//x//P/8//0//b/9//2//X/9v/8////+P/x//L/+P/+//3/9f/3/wMAAgD9/wQABwACAAYACwAGAAoAGAAbABQACgACAAQAFAAZABMAFQAcABkAFwAfACYAIAAYABQADwAKAAsACQADAAUAEQAPAAIACAAdACMAFwAKAAAA9f/4/wsAGgAXAAgA/P/z/+z/8v8AAAAA+P/+/wsACQD3/+r/7//+/wIA+P/2//z//P/6//n/8//o/+T/6f/4/wUAAQD4//b/+P/9/woAEQATABgAGgASAA0ADAAKABIAHAARAP///f8CAP3/+f8AAAQA///6//f/8f/v//n/AgD+//z/AAAGAA0AEQAQAAwAAwD8/wcAGgAbAA4ABwAEAAEAAQAEAAwAEgANAAgAEAATAAgAAgANABQAEQAQABQADAD9//r/AwAFAAAA/v8EABMAHgAWAAcACAAXABwAFAAOABIAFAAVABYAEgAGAAUADQAJAAQACAAJAAUACAALAAEA9//1//D/7v/1//z/AAAFAAMA+f/3/wMABgD+/wQAFAAQAAAAAQAHAAEA+P/w/+r/8P8BAAIA9P/s/+//9v8CAAsACAABAAIACAAHAAIA/f/1/+7/9/8GAA4ACwAIAA0AGQAlACEAEwAFAAAABwAUACIAKAAfABAACAAKAAwACAD///3/BgAMAAkACwAIAPP/4v/v/wIA+//r/+z/+v/+//f/+v8BAPv/8f/z//j//P/+//v/+f/7/wMACQAGAPr/8f/1//X/7v/s//X/+//2/+z/6v/w//b/+//7/+3/5P/w//7//P/5//r/+v/7//z/+v/3//T/8//6/wYACwAFAAIABwAOAAgA/v8IABMACQD4//P/9f///woACAD9//T/7f/r//H/8v/3/wUACQD8//j/AgAEAPv/9v/5//r/+P/y/+r/4v/g/+L/7P/1/+7/4v/p//n//v/9//n/8//0//3/AwADAAMABgAEAPr/9v/7//7//P/+/wIAAgAAAAQACgAOAAkA/v/7//z/+P/4//7/CAAMAAoABAAIABMADgACAAQABwAAAP//AAD8//7/BgAFAP3/9v/1//f//P/+//v/9//y/+v/6f/s/+//8P/y//P/5v/Y/9v/6//2//z/BQAOAAwA///5//r/+f/+/w4ADwD8/+3/7f/0//7/AgABAAEA///0//H/9//7/wAAAwD8//f/8v/w//X//P/z/+v/+P8CAPj/6f/h/+T/8f/+//7/8//v//f/AQAHAAkACQAKAA8AEAAJAAAA+//2//L/8f/u/+//9f/z/+X/5P/1//n/6v/q//3/AwD0/+r/7//4//j/7f/k/+n/7//x/wQAGAALAPv/AAAGAAQADQAMAP//AgAMAAEA+v8CAAgACAAIAAQAAAADAAUA///5//v/AwAIAAoACwAGAP7/AwAMAAoABgADAPj/8P/5/wkAEgATABAABgD+//z/AQAJABEADgAFAAgAEgATAAoABAAGAAkACgAJAAcABgAKABMAHQAcABYAGgAbABEACQAIAAQAAwALAA0ABwAHABEAGQAUAAoACgASABYAEwARAAoAAgADAAUAAQAEABEAGAAPAP//+P8DAA8ADQAGAAoAEAARABcAHgAZABEADgAHAAIACQATAA8ABgAAAAEACQAKAP3/+v8HAAoAAwAAAP//+//8/wAA+//7//v/9f/y//P/8v/2/wUAEAALAAQABgAHAAEA/v8EAAEA9P/5/xAAGAASAAgA/v/5//3/AQABAP//+////woAEAAOAA0ABgAEAAwAFgAXABgAEwAFAP3/AQANABwAIgAXAAwADQAQAA4ACAADAAAACQASAAkA9v/2/wcADAACAPr/9P/v//P/9//0//X/9//w/+3/8f/w/+//8f/x//P/9//w/+b/5//v//H/8P/v/+j/4//p//P/9f/z//D/5P/e/+b/6v/d/9P/2v/j/+v/+f8CAAAA/P/9/wMABwAGAP3/7//n/+X/7f/4//v/9f/z//T/6//i/+r/9//4//D/5//q//r/AAD9/wIAAwD6//3/BgACAP7////+/wEAAwDy/+z///8HAAAACQAWAA4AAgD+/wYAEwASAAYABAALAAsACQAGAAEACAATABAAAwAAAAsAFQAOAAIAAgAKAAgACgAaACYAIAASAAkADgAaAB0AGAAZAB8AHAAUABQAFAAOAAsAEQAVABUAFwAQAAAA9P/3/wcAGQAfAB4AJQAoABwADQAKAAwADAAIAAMABwAPAA0ABAD7//P/8v/1/+7/6P/w//P/7v/3/w4AFwAOAAAA9//1//3////6//j/+P/t/+P/4f/i/9v/1v/S/9j/5P/k/9//4//k/9z/3//t//L/8P/r/+H/3f/a/9j/5P/z//L/5v/e/9n/3v/v//f/9v/0//H/9/8BAAMAAgADAAQAAAD4/+z/6v/t/+f/5P/x//P/6//s/+r/5v/u//f/9v/2//T/6f/t//b/8//3/wQAAAD1//T/9P/x//j////8//T/8v/8/wsADwAPAA4ABQD4//b//f8KABMADwAFAAEA/v/3//f/AAAMABEACgAAAAEABQADAP3/+f/1//P/+v8DAAUAAQD///7//v8GABAAFQASAAQA+////wQAAgD9//n/9/8DAA8ABQD5//X/8P/s//f/BQAHAAcACwAPABYAFgAFAPT/8//6////BAAFAP//BQARABMADwAOAAMA9v/6/wEA/v8AAAkABgABAAYACQAIAAUAAAABAAgADgASABIADwAQABcAFwATAA4ABgADAAEAAQAHAAgAAAABAAgAAQD3//b/8//z//n//f/9/////v/+/wMAAgACAAgACgAHAAcABgADAAkADAABAPv//f8GAA4ADQAFAAAA/v8AAAQABgAJABQAFQAEAPT/6v/l/+P/6P/2/wgACAD9/wEADgANAAYADQAWABMABwD7//X/+/8EAAQA+v/u/+r/6P/r//X//v8CAAgACQAFAAkACAABAAIAAgD7//n//////wIABQAAAAIADgANAP7/9P/s/+f/7P/0//z/BAAJABAAHAASAPr/9f/+//r/8//y//H/9/////7//P////z/+f8BAAYAAAD7//v/AwAMAAsABAAHAAwABgD9//z/AgAFAAcABAD8//X/8//9/w0AEwAPABIAGAAYABAABQD5//n/AwADAPv/+f/9////+v/0//f/AwAEAPP/6//z//z/+//9/wMAAgD6//n/BgAOAAkAAgD+//7/BAAEAPz/+f/8/wEACAALAAMA/P/8//v/+P/3//f//P/+//b/9P8BAAkADAAKAAEA+f/5//v/+f/2//P/9/8EAAkABwALAA4ACwAIAAgACQAOABMAEwAKAAEAAQACAAQADQAZABQAEAAXABQABgABAP///f8JABUAFwAVAA4ACQAOAAcA8v/w//3/AgADAAcABQAFAAcAAQD9/wEAAgAHAAkA/P/x//T/9//6////AgACAAQA/P/t/+X/5P/n//b/AwD+/+//6//3/wcABQDu/+L/6f/2//v/AgACAPz//P8GAA0ABgD4/+7/9P////z/+P/6//v//f8HAAYA+P/x//j/AQABAPr/+P/6//P/7v/0/wAACgANAAAA8//0//j//v8GAPz/7P/0/wAA//8BAP//8P/p/+T/3f/r//T/3v/T/+D/4//f/+z//P/+//b/6//v//3/BQAKAAYA8v/u////CAAEAP7/+P/1//D/5//v//3/+v/4/wUABQD+/wcACAADAA8AEwACAP3/CAAMAAoACQAFAAcABQD+//3/AgAFAAsAEgARAAkAAQD4/+//8f///wkA///y//H/9P/1//3////8////AADz//H//P8FAA0AFQAOAP//+P/z//H/9v/5//f/+//8//7/CgAPAAAA+P8BAAMA+v/2//z////3//H/8//y/+//9v////r/8//z/+z/7v/4//j/9f/1/+3/7P/8////+f8EAAkA+v/9/wwACQD///3/AQALABMAEQASABYAEgAOABAAEwATABEAEQATAAwABgAKAAUA9v/0//b/8f/4//3/9v/2//r/+P/+/wgABAACAAYAAQAHABcAHgAbABUACQALABAABgD//wkADAAKAAwADAAHAP7/9v8BAAwAAgD//wIA9P/1/wwADAABAAcA///w//3/BAAAAAkACgD8//3/AQD5/wEAEQAKAAYACgAAAPn////9//j////+//H/6v/v//n/+//y//H/9//z/+7/9f/5//H/9v/8//L/6v/y//j/+/8AAP3/9v/9/wUABAADAPv/9/8BAAwACgAKAAoAAwAEAAoABgAJABIADgAHAAgAAgD+/wkAFwAdABcACAABAAUABgAFAAwADwAPAA8ACgD+//L/8f8AAAwABwADAAYA/v/7/wQAAQD4/wUADAACAAIACQALAA0ACgD//wEACAAFAP7//P///wcADQANABAADgAMABAADAADAAQABwAFABAAGAAJAAAACAAQABUAFQAKAAIABAABAPz//f/2//T/AgANAAwABwD7/+3/6f/q/+7/+P/5/+7/6//w//H//f8OAAkA+P/1//f/+P///wMA/v8BAAgAAgD+////+f/7/wgABwD6//r/BgASABIACQAKABIACwAHABUAGQAPAA4ADgADAAUAEgAVABIAEQAQAA0AAwD5/wAADwALAAIABwAKAP7/9P/3//v/+v/6/wIABwAGAAkACwAJAAwAEgAPAAAA9v/x//D//P8KAAkABgAIAAIA+P/+/wgAAQD6//r/+f/7/wQACAD+/+7/6//6/woACgABAPX/6v/y/wgAGAAWAA0ACAAQABgADwAHAA4AGAAeABsAEAAFAAcADgATABIAEgASAAwAAwAKABUAEwATABgAEQAIAAQA9//r/+//8//u/+v/7v/w/+3/5P/j//L//f/9//r/+P/+/w0ADgADAAIACwAMAAYA/v/z//H/9v/z/+z/7P/v/+f/3P/g/+X/4v/i/9n/zv/Y/+3/7//n/+b/5P/l/+r/5f/g/+j/6f/d/9n/3//o/+//6//h/9//3v/e/+j/9/////v/6v/f/+X/6v/t//n/BQAHAAQAAAD8//z//f8EAAwAAgD6//3/8v/n/+3/6P/b/+3/AADz/+f/5f/X/9D/3P/p//L/9P/t//L//f/6//v/AgD8//H/8v/u/+3/+P/5/+7/7f/4//7//f/1//L/+f/8//X/9f/8//3/+//8//T/6v/r//T/9//w/+z/6v/n/+n/8//1//H/9P/4//r/AwAQABEADgAOAA0ACwAKAAkACQANABAADAAFAAUACgAMAA8ADgADAPn//f8BAP//BAANAAkABwAVACIAHQAQAAwAFgAaABYADgAFAAAACgAOAAIAAAALAAsABgAKABIAFgATAAcAAgANAA8ABgD8//H/7/8BAAoABgAJABAAEQAWAB8AHwAZABMADwAUABwAFQAIAAMACAAOAAsAAwADAAoAEwAeAB8AFAASABkAGwAdAB4ADgD7//n/AQAGAAcACAANABMAEQAOABIAGAAcABoAEwAQABIAFwAdAB4AFwAXACAAJwAjABoADQAIABQAGwAVAA0ADQAQABIADgAIAAkAEAAhAC4AIQAJAAAACwATAAwA+//2//r/8f/m/+7/9v/2//v//f/0//T/+v/3//X/+//7//j/+f/7//v//P8DAA8ADAD+//7/BwAHAAoADAAGAAUADAAIAAAAAgAJAA0ACQD8//H/7v/q/+7/8//y//b/AAD7/+//6//u//f/AgD+/+//5//p//j/BAD+/+//8v/+/wEA9//u//b//f/4//j/BAAFAAUACwADAPP/9/8DAAQABgAMAAgA/P/3/wEADgALAAEABAAQABgAEwACAPr/AwAFAPf/7P/o/+f/8P/7//n/7v/r//X////9//f/+/8CAAYABQD+//v///////z//f/7//n//v/7//L/9//9//b/9/8EAAUAAgAHAA8AFgAaABYAEQATAB0AJAAdAA8ABgAEAA0AHQAfABMADgAOAA0ADwAOAAkABgADAP3/9//y//b/AQAAAPT/8P/y//L//f8CAPj/9P/9/wEA///9//T/8f/7/wUA///x/+v/8f/w/+r/8P/6//z//P/7//j/9f/v/+n/6//n/+H/6v/v/97/0P/T/9j/2v/Z/9H/y//K/8r/1P/i/+L/3//k/+b/6P/x//7/CQADAPL/7P/0////BwAHAP7//P8BAP////8GAAkABQD7//j/AgAIAAEAAgAIAAQABQAPAA4ACwARABUAFQAaABkAEQAOAAkABAAIABEAFgATAAgAAQAGAAcABAAFAAUABgANAAwAAQD6//n/9//y/+X/0v/Y//D/8//m//D/AwD7/+z/9f8FAAIA+f/2//L/7P/u//X//P8FAAcAAQD5//7/DAAUAAwABgAHAAgACgALAP7/7v/t//D/7P/p/+r/8v/+//r/7P/t//f/+f/0/+3/6f/1/xMAJgAlACYANQA9AC0AEADi/6v/oP/O//T/9/8EAAEAy/+S/3H/WP91//D/YABxAFcARAAyAC0AKQATABwAYAChAKcAhABKAAYA4P/c/87/tf/A//T/HQASAOX/wP+u/6z/sP+7/+j/KgA7ACcAQABqAE8ADgDu//X/FQA/AEsAOgA6AD4AGgDe/7f/sP+9/9f/7P/u/+L/3v/Z/7v/mf+k/9P/+f8PAB4AIAAaABAA+//q/+r/6//4/yEAPAApAAoA9f/e/9P/1v/U/9r/6//z//j/BQABAOD/yf/Y//f/BwD///z/AwACAPr//P/2/+7//f8TAA8A///0/+3/6v/l/9n/5f8PACwAIQAIAPj//P8EAPz/9v8CAAMA9P/5/w0ADgAGAAQAAAADABQAGAAIAPT/6v/y/wIACAD4/+L/0v/T/+b/8v/2/wMAFQAXAAYA6f/S/9v/+P8MAB0AMAA4ADMAHwD///H/+v8AAAAADQAaABwAJgAoABAA//8NAB4AGwAXACMANgA4ACYAEgAHAP3/8f/p/+//EAA6AEYANAAkABQAAAD7/wIADAAhADkAQQA1ACEABwDy//D/AAAbADAANQA2ADgALAAPAAAABwAPABAAEQAcACoAIgACAOD/xv+y/7H/wv/U/9//3v/Y/9n/3P/S/8j/1f/z/wsAFQAZABcAFAALAP7//P8LAB8AJgAaAA4AFgAfABEA9P/m//D////+//D/6P/o/+P/2v/T/9b/3f/j/+b/7P/3/wUAEgAYABwAIwArACwAIQAVABEAFAAXAB4AIgAYAAAA6//k/+b/5//o/+//+v/6//X/+f8AAPv/7P/p//j/CgAMAAkADwAXABQABwD3/+n/3v/a/+L/8P/6/wAAAQD4/+f/3//n//L/9f/y//T/9//2//v/CAALAAIA//8JAA4AAwD3/wEAFAASAAEA/v8KABIADQAJAA8AGgAYAAgA8v/g/+T/+f8KAAsABgACAPr/6v/c/9//8v///wQACQALAAgAAwAEAAkADAANABMAIAAgAA8A/f/y//f/BQAFAPr/8v/w//D/6//h/9r/3//n/+7/9f/0//H/8//u/97/1P/g/wAAHAAgABYAGAAZABIACQABAPz/AQAMAA0AAwDv/+b/7v/y/+7/+v8LAAsA/v/3/wAAEwAeACIALgAxACIAGQATAAIA9P/y//j////9//f/+//3/+D/2v/x/wgAFQAVAAwACQAMAAkABwAHAAYAEAAfABwAFAAYABcACAD0/+T/6P/2//T/6f/l/+P/4//s//L//P8IAAEA9P/z//r/AQADAPf/8/8BAAkADAAbACQAIAAZAA0AAAD+//z/+v8BAPz/7v/z//z/9//v/+f/4f/m/+3/7//y/+r/3v/m//L/6P/h/+//AwALAP3/7v/z//z/+f/6/wEABAAOABgADQD6/+v/4f/k/+f/4P/o//v/9f/k/+D/2v/g//j/BwAQABgAEgAHAAkABQD//wsAEgATAB0AFwAAAAIAEAATABkAHwAbABUABQDn/9n/5v/1/wwAKAArAB4AFAAEAPL/7v/6/w0AGgAbACQANgA6AC8AKAApACIAFQAPABgAIgAjAB4AFgAKAAUAAQADAA0ADwAMABcAIAAaABsAFwD9//H/AgAZACsAMAAgABcAGwAPAAIADQAYABUACwACAAUADwAGAPX/7v/g/9X/5P8BABQAHwAiACIAHgALAAAACQASABcAIQAkAB0AFwAKAAAABgABAO7/4f/V/8n/1v/m/+z/+f8JAAYAAAD8//P//P8FAPL/5f/4/wEA9f/3/wQACwASABgAEQANABEABwABABAAHgAXABAACQD+/wUAIQAxAC8AIwAAAOL/6//+/w0AJgA4ACkAFAAEAO7/5f/x/wUAHQAoABsAEAAPAAYA/v8JABQAEQAMAAUA/P/7//r/+f/8//n/5//S/8b/wf/A/9L/8P/+/wIAFwAsACIABADp/9T/zf/V/+v/CwAfABoADQD//+r/2v/M/7b/tP/S/+n/7/8EAB0AEwDv/83/w//T/+r//v8TACYAJAALAPH/4f/e/+P/5//l/+z/AQACAOn/2f/b/93/6P8AAA0ADAAIAAcADQAOAP7/8//9/w0AEQAVABwAHwAgABsACwD6//P/9v/5//z/BwATAAwA+v/v//f/EAAjACwAOwA4AAUA0f/M/9f/5P8GACsAKQAKAOn/zf+7/8P/6f8MABUAHgAkAA4A+f///wIA9v/0/+n/0P/L/9j/4v/x/wEABQD+/+n/zv/V/wEAHQAXAAYA9f/g/9//+v8TABkAGgAZAAYA2/+2/7v/3v/z//T/+P/+/wEADwAfABoAAQDh/8n/0P/k/+b/8f8cADgAMQAiAAwA7v/c/9j/6P8MACYAIwAXABEAFwAcAAUA6//y/+//yP+8/9X/3//u/xkALgAYAAUA/v/p/9D/1P/0/xgALQAyACUACgDu/97/5P/8/wUA9//2/wQACQAOAB0AHAAMAP3/7f/e/+b/+v/9//v/DgAlAC8ALgARANj/tf/B/93/6v/p/+f/9f/8/+r/5f/5//z/8//v/97/zv/p/w4AKgBRAFUAJwASABQA7//e/woAGwAKACIAQwAxABUADgABAPD/8P/0//T///8ZACsANgA9ADIAFgAFAAUAAAD5/wUAJAA5ADAAFAADAAsAEwAIAAEABwABAOn/5v/4//n/9/8LABgAEgAbACgAGAAHAAkA+f/Y/8z/1//q/wcAIwA2AEsAYABSABUA3P/Z//b/+P/d/9n//P8XAPf/tP+E/2L/P/9D/37/u//k/wEADgASABUA9//A/7T/4v8YAEQAfQCrAK4AjwBSAAEAzP/L/9X/7/85AG4APADw/8X/jv9a/1//ef+X/+X/OQBKAEMAUABQADkAHQAEAAsARgB+AIUAbQBLABgA5//M/8H/zf/x/w4AEQANAP//0f+k/67/4/8FAP7///8cACMACgAEAAsA+P/5/ykARAA7AEAAOgALAO7/+f/1/9z/zv/J/8f/4f8IAAcA6P/g/+3/3/+5/6r/v//t/xwANgBJAFYAMADo/9P/4//I/6n/zv/2/9j/uv/g/xAACQDl/8X/sP+k/5n/pP/i/zAARQAsABMA7//b////NABHAFMAYABIABgA+v/q/9T/wv/Q/wMANwBBABYAz/+j/7//AgAjACsAPQA8ACYAJwA2ADAAJwAlAB0AKwBBAB0A4P/l/w8AHwAbAP7/0//h/xAA///g/wsAMwAiAB0AIgAJAAEAGAARAAIAHgBBAEsAUwBMACAA7v/f/+r/7//y/+v/v/+X/73/8v/V/63/z//p/83/w//T/9z/BAA5AD4APgBGAAkAtv/M/w0ABADq//z/AwD+/xUAEwDs/+3/GQARANT/rf+r/7v/8P8qACQABwAYAAgAqv+Y//n/KQAVADMARgAMAO7/+P/Y/8v//P8GABYAiADUAKEAZwAqAKX/bf/Q/yAAHgBEAHEAMwDV/73/xP/E/9X/7f/8/xEAHgAPAAIAEAAbABYAIwA1ABkA3P+6/73/5v80AGcAQgD0/8T/qf+l/9n/IQA+AD4AKgDg/5L/mv/a/wEADwAlACQA8v+8/7v/0P/N/8T/2P/v/+v/2v/Y//D/BwD8/9r/x/+1/5z/qf/m/yQAUwBiADIA9f/w//b/2P/Y/xQASQBQADcAFQAMABoADQDu//j/GwAuADcAOgAoAB4AIgALAOj/8P8OAAwACAAvAFQAQQAWAAYACAAJAAsAFQAmACgA9f+1/8f/DAAZAAcAIwBGAC4ABwADABYAIgAOAOD/v//B/9L/6f8IABgACgDr/9T/zf/Z/wQAOQBGADEAKAAYANj/ov+4//L/HQBDAEsAGwDk/87/1/8ZAHEAbwAmAPn/zf+H/5f//v85ADwAKQDy/8n/2P/T/8f/+/8NAML/rf/6/ycAIQAfAAgA1/+2/6X/tf8AAEYAUQA8ACEA5v+W/3f/pv/m/wsAKQBCAEQARwBCAAQAzP/e//X/4v/w/xkAKQBHAFwAFQC9/7z/uv+X/9r/YABmAPP/pP+i/8X/7/8MACkASgA0AO7/2/8CABQABQD1//v/DQAHAPv/JABUAE8AMADt/4z/kv/4/wAAy/8PAIEAkgBxAD8A3/+R/4v/sf/5/2MAswCYABIAmP+d//H/KwA0ABwAAQD5/9D/l//D/ysASQBKAFoAFACs/77/CwAbAC0AWABEAA4A+f/a/6//xv8VAEsATQAWAKb/V/+C/9v/AQAeAE8ANwDP/7P/EABgAF8ARgAvACgASQBFAOX/vP///w8A8P8iADcA5P/S/wEA3P/I/wkABADT/xQAZwBwAIYAhAAQAIn/Rf8//7v/ngAGAa0AMwDS/1P/Ev+A/zMApQDOAJAA7f+E/5f/r//F/yAAWAAbANb/yf/X/wUAMAApABIAAwDI/3b/aP/L/1sArACkAFEAqv/z/rr+EP+7/5IACwGeANP/ff+R/6//0/8bAGAAUQDr/6//5/89AFYARAAlAO//n/9n/3H/pf/+/3YAogBNAAUA9P+z/3r/1/90AKEARgDO/77/CAADAJ3/kv/4/zMAMABIAGkATwANAM7/of+r/xAAeQBzADkAUAB2ACQAqP+t/xIAOgAmADIAMQAAAP3/MwBPAFMAPwDt/7z/2P+//4P/vf9BAJsApAAzAIT/Of9S/4P/1/8pADIACAC+/4b/uv8UABkA/P/o/9b//v8zABIA/P8hAAMAvP+7/8//3P/v/9D/m/+T/5P/wP9AAHEAKAAAAN//hP9p/6T/wv/f/yQASgBOAE4ANQAVAOr/kv9y/+//iACrAIcATAD2/8j/5/8KAAkAAADz/+v/BAAsADkADwCw/3v/vP8EABAASwCdAJEAcQBZAPT/nP+w/9T/MQDzADoB0gBbALD/4/7N/kf/yP+pAG4BFAErAKH/Y/9q/5T/eP+G//v/DQDY/0EAwQCAAPj/pv9h/0X/ev/K/yQAiwDKAKUANQDH/4j/ev+c/9z/DAAaAPn/mf8+/0L/hv+r/7r/+v82APL/hv/F/0YAIgDD/7X/lP96/9b/KgA3AHIAjwAjALv/nv+O/6P/0f/g/x0AlAC3AH8AQgD1/7r/7f9VAIQAbwAoAMj/nf/Y/zoAaABEAPD/rv/B/yUAowAXATwBnQBp/5f+yf6q/3UAvgClAGkAIgD3/+n/rv9X/yz/Jf9u/ysAmwBkAEIARQDs/5f/nP+h/73/EQA5ACIAHABHAK4A4ABjANP/sP9//2n///+GAEcAzv+4/y0A2ADkAGcAUwBwAP//cP9U/6L/WQAbATYBwAAnAIH/HP9D/53/2P8fAH4AxgDDAFcAxP+G/6r/4P8AAAcA+P8CAEkAWgDZ/1H/Tf+L/+D/cADiAMUALABk/+/+Lv+b/7z/BACEAJYALQDP/5//gf9t/3H/sv8hAJIA6QDbADwAe/8V/y//vf9HAGMAXgBsADAAu/+S/8D/6v8JAIAALwEeASYAgP+K/5T/2P+ZAAkB1ABQAIX/3P7J/gz/r/+0ABsBqwBSAA0Arf/Z/z8A+v+D/4v//f/TAJgBZAFrAH3/x/6T/jz/OQDaAAsBwQALAGn/Nv9T/5r/DAB3AIoAOgDS/4L/Pf8x/67/dQDTAL8AuACAAJj/tf7A/lb/6/+DAMMAbAAfAB8ADQABAAsAx/9q/5H/JwCuAM0AXADD/6T//P85ABMAnf8W//b+mP+PAAUBygA3AIP/K/+h/0kASgAGACwAhgCRACoAsf+x/wQAFAD+/xAAEgAeAIAA+AANAZcAvv8y/07/l//3/6YA+wChAFQAEwBf/9j+NP8uAEsBwAHsALD/Lf8r/3r/VgAWAfcARACS/0//iv/G/+X/MABPAAAAv/+i/4b/0/9aAFsA8P+F/yn/Mv+z/yYAaAB8ABIAjv+P/7j/u//e/+z/vv/H//3/AgAgAHgAmwBmAAgAmv86/+7+Bv8OAHUBvwHUAMf/7/50/hP/iwBzAS0BJwD9/n7+Ef8JAJ0ArgBVAOn/w/+Z/2P/sf8/AEoAEQAYADwAawCbAJwAiQBTAMr/gv/L/+T/zf8hAFUABQAGAGYASgDB/0z/AP8b/8X/ewDOANUAhgDA/+P+jP7j/pz/VwC+AM4AqgAlAGL/Dv8j/z//y/+RAGgAr/+q/wcACQDR/2z/Mf/W/+YAXAHyALv/lf7K/u//sgDhAJ0A5P9l/3f/xP9CAJQAUQA0AHUA+v/m/qL+Wv9AAO8AGQGnAEwAgwCZAMj/vv6J/hb/CgA3Ab0BGgEgAGT/8P5D/yIAfwBUADAABQDq/xgAXwCYAHwA0/9D/1D/m/8XALEAlwC6/wP/+P7J//gAKAFVAOX/5v+P/0D/d//1/4kA1wBxALb/U/92/xkA1QDhABMAOf8Z/7b/awB7AN3/Vf+H/yMAZQDv/wv/mf4w/z8A4AD5AK8A+f9V/1z/yv/5/7r/lP8zADwBiAGkACf/MP60/iYA+QDbAIkAPQAKAAcAvP8r/xf/lf8rAJEAXwCK//b+Tf8fAJsAaADf/5P/uf8wAIAAGQBy/4L/8P/7//7/LgAYAAwAdwCrAC8Aiv/4/of+9/5uAJUBYgFhAIT/Cv/O/gn/BQAfAQwB0/8I/4L/ZACtAEQAsv97/7T/SQD/ADABrwAdAJ7/Lv+N/6MAGwGZAPj/kv9T/1L/zP+0ACABawCk/8v/RQB4AEoApv9e/yUA8wDwAIgAEADC/+//VwCyALwA2f+//gD/JAC8AOAA+gDWAHgA3P8i/9n+Cv9r//T/UgB7ABIBqgH1ADD/6f0A/uD+g/8bAEgBEAKCAXoAuv9J/4r/EQDX/0L///7m/mv/8QB6AgADKQLw/2P9D/yO/KH+MAF+AiECLgFEADf/O/4h/nP/OAHQAe4Ag/+K/sb+OAC5ARAC/wB9/+7+RP9z/6P/KwAsAJn/jP8eALAA6wCFAAkATQBrAGr/jf79/hkACgFPAcMAJQDj/3P/9v4U/3f/zf+HAE8BSgGaANL/Rv+H/4kA/gBJAGr/Rf/e/7oA5QAKAEn/Zf+q/9f/dQAYAeEA5v+5/vn9WP6d/7cAdwEuAhQCcgBo/oP9Av5d/8kAVwHxAHIAWwCMALAASAA+/0f+OP5L/64A8gAZAMH/VgCpADAAY//q/lX/IwAnAMr/HwCSAGEATACLABkAGP/q/r//ngALAboAif/G/rT/NQG2AWoBqgBg/17+Tv7j/t3/BAHTAQQCPQF2//T9wv1v/pf//wDEAXUBdgBK/7f+/P5s/+T/fQCHAOX/dv+P//P/JADM/8H/kQDKAJL/VP5S/mT/lgATASgB9gCh//X98P0p/zoAGAFCAUkAVf/q/sb+fP96AFoAzP+x/3n/fP9OAPAAzQBoAPT/lv9e/xr/bv/KALIB0AA1//T+ZQCAAcoAxP/b/97/Of9L/ycAXgDp//L/rQAuAegAOgBy/7b+rv6F/1wA3gBLAUEBjQDV/43/l/+s/73/JgCkAD0Ahf8wALIB2QFSAMX+a/4a/wkAygA/AUEB1ADN/zL+f/3G/jAAQgBeADIBhgEaAUgA9f4k/uv+OQC8AKIAcACGANoAlwCp/1T/xP/i/6T/3v9yAHkAsv8l/73/gwBaAB8AYADe/67+rf72/+YA8QCjAE4A6/9a/+n+Qf9AAAMBBAFeAK7/jP+l/33/jP/0//X/i/+I//7/OQDg/4v/7/+FAGEA3v+H/xj/7v7J/xIBqQFlAYgAVP9v/m7+QP9GAO8AIgHtADQAW/88//j/yAD0AEUAG/94/gf/GwC8ABkBWQG/AKL/Xv+o/4n/m/8xAFYAFAAtAG8AoACzACwAV/8L/zf/jv/5/zgAngBkAWQBCwCW/ij+Bf+eAGABowCo/33/+f+AAG0A7f+K/9f+H/7s/sQAlQFOAQsBxQAAAM7+Fv7M/kEAAAH/AK8AKQAhALoAoABD/y3+MP+wAY8CnQC2/s/+tf+dAGsBMAEGAPj+Sf6r/n0AqAGkACX/9f6O/5f/A/8d/zcABwFLAVcBOgCQ/sj+SQCwAFQAWABoAFwAFgBj/1b/UADHAGcAQAA0AN3/Yf+m/oD+CQC0AXABFQAj/6z+6f7j/2oACACk/53/xP9fAEkBfQFxADj/Qf8ZACcAmP/Y/6MAtAAEADb/0v5t/6AAIAHIADoARv8p/kD+y/9EAb8BoAH6AMf/Gv+P/9f/d//y/yIB7gBs/7L+cv/hAK4BnwCg/hX+Hv///1YAtgDmAH8Ayv+D/83/5P+A/3f//f+sAIYBuQEuAGH+fv6M/8v/x/9tAFgB1gE0AYf/Wv6a/pv/7wAfAsUBz/8f/u39BP91ANwANgAVAKkAiwBo/yX+3f07/1QBZALgAUEAoP5q/m//VwD5AA8BDwCu//YASwGL/1P+8/41AAkB7wBQABcA7f9t/1v/xP/d/1r/cP5x/m4AQAKeAf//Ef93/l/+Cf/f/x0BbwIaAjIAuv6r/q7/hgAJABv/Wv9jANEALACN/20AeAEAAKz9G/42AA0B1wB/ALT/uf5P/uT+PQDrACkAev/5/3AAsP9s/jf+VP8pAD4AQAG3Au0Bjf+f/tz+lf7V/pwATAJ4AmIBj/+0/RD9XP7MACwCBAH3/sr+IQCIALT/TP/Z/zEAmf8l/xEAYgFmAXMAwf9z/0n/Ov9h/ywAdQHxAdwAC/8h/gz/owDkAAcA1/+HAN0AMwBX/7D/qQAOAHz+qP4WAIwAkABDAc0BVQELAKT+LP6t/kX/BwAjAckBzgF4ASAAHP5b/Yz+cQChAVUBHwB5/6T/AgCoAEEB2QDC/9z+SP5s/qb/MwF1AgEDyQFK/wX+R/49/mr+dADQAtUCDAHQ/3v/wf61/QT+KQBtAukCQQHN/m/9zf0Q/3gAlQG+Ac8Agf+A/lP+Tv/YALcBSAHz/7v+d/4s/3wAHQIpAy8CT////Br9iv7D/zkB5gK0AgYAY/3N/Nj9pv+MAUoCUgH6/07/fv56/TH+zgBtAq8BWwB0/2v+3f3X/m8ASgGJAV8BXwD//lL+jv6N/zQBIALlANn+R/4h/xwA8QCeAZ0BlADL/mP9y/3u/+8BdQIXApoBYQAi/qD8hf0IADQCvgI2AcX+3v0u/6YA6wCTAAAARP9E/wwAaABcAKEAjwACAP3/zf+i/oH+dQDvAWUBCgDb/i7+Z/6B/0IBoQLvAaT/DP4F/g3/VADJAAMBHAJFAhwAGP7S/W3+TQADA00DggDm/Un95f0x//8AegJnAqsABf+c/m7+Tv7M/1cCFAM8Adn+3P2q/kwAiQEKApUBu//L/d39KP/F/48ASwLbAkMBLf9//ZD8i/04ANICFwRQA7wADv57/FH81v1WAG4CjQMlAwwB0P5//Qb9N/6rAKoBsQDI/2z/Tf/W/4gAowB0ABAAVf+3/p3+av8KARICiQFMAC//d/6b/mX/IwDYAEUBxgDW/07/A//N/jv/XQBEAVEB7wBLACr/of7x/6UBigE9AFf/vP5B/ub++QDHAmACAADh/bX9DP9QAM8APAGSAacAIv8x/1gAjgBOAIkALwBW/7///QAaATgAq/+c/6v/wv+i/2z/9/8YAUgBRgB8/0j/Af8E/8b/cAB3AIMAswAyAAj/nf6t/yYBqwEAAdf/Qv+Q/6T/GP8e//X/rAAqAUMBJwCr/l7+4f5b//T/ZwBBAGcAmQFzAisBof5i/eH9nv5h/8kAOwK9At0BzP8T/tz9Lv6//qEAoAJgAmMAxP6m/ur/JQE9AdgAPgA3//v+wv+i/9L+iv82AV8B8f/t/lr/BgDH/57/RQArABv/OP97AMwADwCw/0kAVwFTAa7/hP4r/8v/SP8e/wIA5gAVAaQACgDp/wcAyv+u/zEAdgDY/xb/Hv/8//MAWwFSAdIAgv86/i7+Dv9uACoClALVABX/g/45/rX+PQAGAdkA4QB9AJX/ef+t/1z/Vv+o/wQA6AA3Ae7/O/84AMEAHgCK/yL/3/4e/7f/6gBQArwBK//Z/dD+u/+I/2b/FADtAP8APwBz/wX/Af+K/zQAQgD9/w0AFgDo/yEASgBj/6r+xP8YAX8AHf/p/sX/xABAAdcA//9B/8L+P//KAKABBAFpADcAdP+e/uv+rP+h/5D/lABYAV8AKP9a/wIAMAAfAJT/9f59/4AAqgC9ACYBfQAO/xb/vgCcAWQAu/6c/of/+/9DAEEB/QEPAUb/pP5Y/9L/lP+Z/0QA7wD+AGcAwP9u/yH/8/5K/57/xv+AAEsBKwGZAMv/ff7a/aL+1v8EAQcC1wGfAJr/2/5V/o/+jP8qAZACwQEx/xX+Cv/+/6AAbwFuAScAqv79/ZH++f/XANcAFAFgAVMAp/5u/lP/8f/CANABbwHQ/wX/JP9O/yUAZwESATr/df6C/2IAEgDL/ycAXAA5AA8Asf86/zf/1v/8APYBgwHT/5r+j/5B/y8AwwDlAC8BeAHnAGf/8f3L/fr+AQB8AEoB1wFqAbcArP9A/kf+if+B/xb/pABEAoMB5/9U/1z/fP/9/84AEgElAOr+1/7X/7IA/AARAeYAJQAx/87+Av9u/ycAxgCkAHUA+AAfASYADv+o/sb+Rv8bABUB6AHtAbcA+f74/WH+tP+wALwAfABwAG4AfQCUAP//uv5e/vr/9gEBAhEAHf7L/Tj/JgETAnkB/P/p/t7++f7Y/qX/MgF7AXwA1P+A/+/+3P6q/8oAuQHBAW4AzP5+/qv/5AADAXcA9P9j/wT/Nv+R/yoAOQGUAZEAOP8Q/oP9kv5uAIABQAKSAhIB2v7h/XT9LP1c/toAzwL3AnIBu/+6/rT9Hf18/qUAlgHhAeEBvgA//4z+WP7V/hcArACAAN0A8wDT/y7/zP9GAFoAZwDb/y//rf/rAK8BcgEWAG7+4v1z/lf/fQCtAR4CbQECABj/VP95/xz/HQA1AkQCAABd/pL+kP91AM0AmgA8AND/hv/L/1wAqQCzAIMA6/8J/2T+pf7k/2sBjQLPAmkBof5z/Ez88P2mACEDpgMOAuD/Nf5u/fz9rv89AaYB8wCN/yP+6/1N//IAjgFeAcgAt/+u/oD+Pf9lAD8BKgGBAOD/9P7z/Ub+PABZAhoDxQEA/+388fx0/l4AsQHDATYB0gAhABj/ev5q/vX+LQAGAQABzwAvAB//Mf8PAMn//P4b/97/IQFDAmEBE//H/Z79Sv5yAIACfwKdAQIB+v+g/s79zf3o/pcAjgHAAWwBKgDn/vH+bv9k/4n/QwAYAXEBjADt/nf+Tv8VANoAvgF5ARkA+/5H/kX+0v+NAXYBcADq/5n/pv9xAJ8Ag//Y/qv/vQC8ABIA/f+DAG8At/+M/wkASwA6AFkApwCbAAIAgf+M/3z/EP8c/8//dgDhAA0BswAFAFf/fP7E/WD+kQCNAqkClAGVAHb/Jf6F/aj9X/5FAJUCFAOBAa3/uP5q/kX+f/6p/+kA9wCKAKgAVwAF/yH+xf41AAsBDQFGAZMBZwBY/rj9u/4bAC4BPQFxAD0APQAL/y7+Tv+hAJMAJAAFACkAiABKAF3/hP/eAHoB/QAZAOj+jf64/3EA+P9IAFIBHQHz/yz/1/7S/vb+Hv/x/x4BSQHpAAwB0wDP//n+jf63/t7/2gC6AJEAsQBmAFYAtADz/yP+e/2b/hwAAwEtAb0AMACw/+z+jf6f/wcBAAFmAIsAmQAbAO3/0v9w/4//8//Z/yIAKgGbATQBnABh/5/96/wR/lsAmQKcA/ECIwEa/9/9BP7C/nX/ugAvAhACfwCQ/6r/fv/9/g//nv/1/+P/BQD1ANMBJAF7/6P+qP62/g3/+P8oAU8CeQLAAJb+TP5v/9r/hP8IAEcBoAGyAF7/O/7n/d7+WQBYAckBhQFSAOf+SP7+/nAAzgDS/8f/FwFPARcAZ/97/5L/0f8kAEMAfgCzAFgApf86/2H/t/91/xT/KgAuApUC1QDW/tH91f0G//kAUQIqAgMB0f8L/7L+p/7k/oX/lwDJARwCiwD2/dX8zf35/ov/kwD4AYACLgKSATcAJP68/AP9tf4nAR8D+ALjACH/tf6c/ln+lv6n/wUBjwHHAND/lv9w/zb/p/8xANT/Wf+//2sAjwB5ALEAvgDf/6/+b/4P/9n/xQCEAXwBzACt/yP+Tv1o/osA7gFaAmICuwEzAM3+X/5t/pj+XP/BABYCuQI3AtIAmP8D/8H+6/5x/9f/fACKAWIBXv/7/RD/AgHPAZ0BMQGRALD/zv4e/sf9If6Z/9IBWQMhA8kBRACg/gz9QPy6/KP+SgHrArwCuAGCAPv+0P22/V7+Kf/N/4EAnQEyAgMBKP+M/sH+qP7w/lAAxwEvAsoBOAEgADj++Pzf/dn/DAHPAdkC0wK6AD7+Mv04/dX9r/8uAoADWgOHAsgABf7C+6z7Gv7RAXQEZgQ+ArD/6f00/Wn9tv4PAbMCzwGi/93+lf/3/6D/ev+b/4b/j/9QAAcBfQBi/yD/Gf9v/q7+nAC2AdMALgBLADH/g/3c/RoAFwK2AsIBlf+b/Uf9s/58AB8B0gDeAAkBDgA0/hT9xf09ANgCHwPBAEr+1P3h/iEALwHWAXkBVwDQ/zQAvP+p/ZD8nf6LASECOAEQASwBogA9ALD/7P15/Gv9y//GARkDYwPGAQX/Tf2v/Sv/NQCLALIAjQAlAF0AGQHrAKz/w/7h/qH/XQBkAA4ArwAgAn4C3AAx/nX8bf1RABgC8gHJAckBxgCX///+6v3d/PH9lABBAiYCtACC/j/9SP5QADwBAAGhAEcA1P+k/7//tP+D/3r/Vf/x/h//WQB8AXEBxgA0AIL/2f6w/r3+Dv9LAJABXQF0AAwAnP8H/zT/1/9zAGgB0AGWAHv/5v/e/5P+b/41ANcBQAKIAXn/O/34/Kz+pwBoAswDjAM6Aan+gf1d/Yb9a/5RAB8ClQK/AaYALAA+AOH/0v5I/rX+9f4q/8QAwgKoAgYBIADd/+z+mP0R/UH+/wAoA+oCvQGVAZMBrgDE/9j+Af16+3r80/9VA+4EwgP8AP7+nf6Q/uT9a/1p/rgAqALkAs4BiQDI/8//PQDf/z3+n/zT/Dv/CQLNAogBsAAMAZ8Arv4r/Xb97P6vAEACDgOpAgQBwf48/Ur9Lv7T/kr/SgDOAZ8CpAGo/2X+H/5s/uP/PwItA5wBZf84/uj9/P2a/hAAOwLDAxsDnwDk/e37wvv9/agAbAFuAZYCeQMQAjz/wPyR++781gAYBLUD3gDG/oL+Bf9G/xD/8P66/zcB0wGyAPf+OP7//sMA2wGuAI3+of78AIwC+gFZAJT+o/11/sn/2/+G/wwAnADBAB8BGgEmAJj/0/90/9j+g//aALUBRQLMAVH/Bv2b/YT/GQAKANMAugHkAaUB2wBJ/+n9yP3A/lUAuQGhATQAqf/EAFIBCgCp/r3+nf8fAMX/Gf+7/9wBtgLHALr+lP6t/jv+EP9EAcEC4gI1As0AKP/u/fj8yvxu/qMAegHCAYICKQIGACn+yf0l/ub+wv+y/yP/5v+9AXsChAE6AJz/lv/2/3QAbgCs//f+Jv/Z/wIAi/+c//0AiQIrAqr/Lf1r/EH9+P6XANIABgAvAGkBoAFtAFP/yf5q/mr++v44AG8CdgQhBHUBgv5y/JL7VvxX/nkALwLRApoBcP8O/pn9sf38/n8BiAOfAx0ClAARAPP/Xf8B/5j/AQBd/8z+Uf9aAB0BUQHAAKj/Bv+C/5UAJgEBAdcAlgCN/1f+Jv6W/g7/MgCsAbgBcADE/xIA/P/x/rP9dP2u/nYAmwHHAc4A/v7+/Yr+I/8e/57/rgB1AUQCuQIxAWH+G/33/UL/IACzAB8BmAHSAQYBYv8u/kz+hv+pAJIAm//j/mX+wv2e/Xf+7v/OAaMD+QMIAhv/S/2N/TP//QBVAuMCIwKrALX/zv5b/Sz9iv9CAi8DngLpAIT+eP2o/hsAbgCAAAoBhwE+ASsAev8HAJ4A9v8g/0X/2P+FAF4BeAF/AN//KAAnAFv/pf6s/hf/Rf9C/6D/PwBrAGIAmABrAIj/3P7U/gj/if9fAO4AAwHSAGAANgDXAGEB0wCX/0r+OP1A/c/+AQHWAooDSgKr/5799fxe/fb+jgHUA50EbgOCAJH9ufwR/gcAcgEXAl0CbgJ5AW7/V/5Z/8IAMgFPAUUBVgDo/gn+7P01/rL+aP9QANoAmwBmAMIAYwC6/sf93v6PAGEBjQFUASsAB/4n/OT7/Pzl/Rv+mP62/34AEgDA/uL9fv7I/4cAOAFNAkkCqQCS/zYAOwGvAfgB6AG0AE3+wPvH+iH8Xf7P/4YA2QB/APj/+/8AAL//UwDSAZUCEAKLAbkBDQJJAsICCgMbAvn/DP5+/Qb+q/4F/4H/YQC2AJ7/UP7K/qIA5AE0AisClAGzAMgAwAEiApQB6ABiAOD/pf/T/wYArf++/hP+Yv73/vb+EP/0/2YAP/+a/SD97/2B/5QBRgNyA3MCiAG8AGX/JP4S/tX+hv9EAA8BvgDU/sj8P/w3/ZH+ZP+D/1b/Wv/p/xgBdAIRA4YCngFXAXYBEAEUAD//uP4N/nn9+v3d//sBtQKPAaH/HP4n/cn8df32/n4AKwI0BDsF6QM+ARf/9v3G/d7+DwEjA/0DfQMvAnMANf6n+/r5hfoN/cr/jQHQAugD5wNyAtoAIQDz//H/DgAEAN3/8v8XABgAJwDi//H+Vf7H/kv/Wf++/1UADQAe/4j+sP6l/+gAOAFaAJf/hP+H/43/5/8ZALX/XP/O/6MA0wADANf+FP7v/ST+bf70/hgAagH6AdQBdAFpAM7+XP63/0EBEAKUAnYCIQFa/zL+If4K/7H/2P6S/aX94P6GAGoCTwMNAiAAbP+I/63/KgDpAGMBwgEbAswBoABB/3D+bP7b/iP/A/+t/qP+Sv9MAP0AJAGtAKD//P6M/04AUABXALsAnwALAMf/zP/t/ywAGgDj/xUAwv9C/pD94v46AHAA4ACsAVkB+v/q/rz+Tf8hAJ4A5wA6AQkBEAAo/+z+EP8V/9v+zv5U/9//zP/A/2QAGQEjAXsAV/9N/iP+4f4+AOEBjAKKAU4A+f9N/6/94/wA/gIAkAEBAmcBnAAaAJj/Jf///s3+t/54/5IA2gBjAOr/v/9EAGgBAQJsAWcAn/8p/w3/SP/6/xcBngHiAAsA2f89/1/+AP+hAAQBXACGAI4BCQJCAaj/ZP5i/kv/QADOAMAAXACBACEBJwFfAJn/Mf8N/xL//f7Y/g//eP+3/xIAoQD+AB0B5ADa/3z+6P0w/tn+3//cAEQBTwH5AN//y/6+/g//Hf+u/9MAbgFCAdoALgA1/2P+Df5T/hr/8P+SAOYAkADT/8r/igDqAJUAMQDx/9r/IQBSANz/T/+j/7YAfgFAAVkAuv+G/x7/mP62/p7/yQC2ARUC6gF2Ac0AGgDY//7/8/+t/8j/pQAKAgIDcgKOAKf+Wf2f/O78Uv7e/xoBUAIpA/UC2QGSALD/dP+u/+n/BgBUAOsAVQEBASgAkP9//6f/9f9gAI0AagA7AAoA3//S/67/i/8DALAAdQCM/xH/BP8B/2T/QQD4ADQBEQGWANH/v/6f/Tb92P3H/nL/AQBnAH8AcgA0AKX/LP8Q/yb/kf9lAB0BWAEQASsAGf+s/sj+4v5R/xIAKACM/33/ewCvAR0CbQEwAFH/FP88/6P/CwA3AGMAnwCbAGoANwDX/4f/tv8DABwAZwC4AG0A+f8SAFgAYgBiAGcAjQAMAVkB6gBcADYACwC8/6f/ov9B/8T+tP4a/3D/Y/9o//z/mQB7AMj/LP8j/6v/PwB8AIgANwBO/8b+j/+4AP0AmQAPAFL/rf5s/l3+g/4Z/9j/cgDIAHsAr/8//1j/YP9T/47/AgB4AMcAtQBrAEAAHwDg/5H/KP/h/h7/gv92/0n/VP9h/5//YgAqAXEBXgEcAdsAxQByANb/8v/cADUBqAAnAOf/l/9//9b/XQDaAOoAdgBTAO0AdwF+AWoBQQHbAIMANgC6/27/oP/1/xkABgCz/1f/Kf8H/wX/dP8XAIUAzQDCAAoAH/++/uT+TP/l/18AjQCDABUARv/d/iv/gf+P/7H/1f/C/7L/rf9n/xz/WP8CAIwAoABTABgANgBFAOL/i//B/yMAGwDK/6T/xf/w/9j/hv9V/3D/r//2/0cAgACcALIAqAB+AJ4AFwFRAeoAOADC/+P/cACsAEwA8f/z/+z/r/9r/zH/NP+u/zoAeACZAKUAawAvAC0AIwAjAFwAZQALAMT/mv9L/wj/4v6t/tH+nP9RAGQANQAXAP7/7/+4/1f/av8eAKYApABxACQAn/8W/83+//61/0YAJQC//4n/cv+D/7f/sv+x/y4ApwB8ABsA9P/k//T///+o/2H/zf9dAHEAcwCSAFQA3v+m/4D/Qf8p/0v/f/+1/9H/vv+//wEATgBnAEkAKwBJAJ4A9QA0ARsBZwCB/yL/P/9o/3//Zv8X/xD/gP/M/8L/3v8NAPP/8v9rANcAxgB2ACIA1P/F/wIANQA0ABsA4/+c/5D/qP90/xv/O/+z/7//VP8t/47///8pABsA+//m//L/FQBFAIIAgADn/xz/+f5j/3T/F/8e/73/QwA5AL7/Ov8h/3H/n/+M/6f/1v+2/6n/DABDAMr/Kv8A/zH/WP9L/zf/W/+m/8f/s/+m/7H/pv9h/yD/Nf9n/03/Iv9g/8j/7v/p/83/hf9D/xP/0v7I/h7/Pv/8/vz+TP9U/xj/AP8d/1j/h/+D/4T/pv+c/4T/0f82ABAAev/n/qv+2P7v/oX+QP6m/iT/av/l/24AsADrACcBQwGNAeYBxQGhATEC5wILA9kCkQJCAhECzAF8AdsBzgJFAzgDVANkAzgDPwOFA+0DkgTkBIYEdgQtBcIFAQZ6BsoGjwZCBu4FdwVgBYkFSgUCBTEFQwXxBJ8EJgR4AxgDDQMoA58DAgStA0cDcgOJAzIDwQIMAiwBuQBkAMf/if+i/yz/f/5T/gb+SP23/Cb8Lvtc+uv5mfnV+Zn6w/or+qr5Vfn0+MT4ivgG+Lr30/cC+G343Ph2+Hb31/aq9rn2G/eA99L3lvhe+UH52fj6+Cb5HflO+YT5nfkr+vb6W/u9+2f8wfzj/Er9eP0Q/a78rfwO/f/9B/9q/4//JgDxAI4B5QG+AU4BOQGKAf8BtAJOA0MDDAM1A1wDSwNJAysD4gLeAgYDDQNIA68DlwM0AzoDZQM/A/4CsgJiAnkC1wLWApACYAL9AV0B9QC8AHkAWwBLAAIArv9O/6P+Gf4V/g3+oP00/fX84fwm/ZX92f0m/oT+hv5r/p7+pf4v/tD9xv3K/df90/2k/bP9EP4S/s79/P18/sX+5/4A/xn/i/84AJcA2QBYAb8B+QFiAsICuAKcAqsCwwICA0ADKwM1A84DUQRDBC4EcwQWBRUG/wZXB3cHxwcfCKwIlwk3CjgKOgqLCuUKGwvxClQK/AlJCrMKBguRCxEMPwxxDLwM+gx+DWMOVw9pEJoRUBJtElQSuBEdEMMNHwuECH8GKQUTBE4DIAMTA9QCsQKXAisCfQGUAGD/UP6k/Qb9dfwy/NL79vrv+c/4Svd/9ZvzsfEw8Evvcu567crsTuy/61nrJOvj6rLqquqh6tbqi+tW7Pvsue1P7kTuzu1P7ejs0+wA7f7s5uww7bTtSe5A747w0fEO82H0ovX39oL4AvqJ+2L9Kf9pAGABRQL0AooDHQSLBAsF2gWnBkwHDAjACCEJewn8CWYKtQoQC3kLNwx4DasOZg/jDzYQMRD9D7oPPA+jDh4Ohw3ZDDAMQAvoCaAIogelBqMFugTaAyEDowIaAnwBFgG3AAQAIv9A/lL9ifwO/Kv7S/sF+6T6D/pi+Vr4sPbj9JPz4/K48uTyIfOR84D0ofV79gT3Pfcu9zj3mfcO+HH42vhH+cf5YvrD+r36w/op+7z7V/z3/Jv9cv6c/8YAqgFtAiEDyAOLBFQFzgUIBnIGNQc6CDYJqAlzCQsJuwhrCCEI4webB18HWQduB3wHgQdpBzkHRgelBxAIYAiGCFkI1gcuB2MGcwVlBBADYAGz/2n+k/03/Uv9jv3H/eT9wP1R/bT86/vy+gr6fPk9+TD5MvkO+b/4gPh0+J747vgi+QL5uvij+Mz4FPlP+U75Hfnx+OT4+fhN+e75x/rM++z8+P3U/ov/GgB8AMkALAHtAWgDpgVECN4KXQ37DxYT5BYsG14f5iJGJScmfSV1I1YgmBzJGEwVWxIaEKIOGQ6kDj0QoBJbFeIXnBkeGmcZ0xf4FVkUJRMpEgQRWw/9DPgJiAb1AoL/WvyD+eD2V/Td8YPvWu1d63npreca5vDkQuT44+Dj1+Pb4/zjNORc5DzktOPA4mzhyt/x3QLcMdq12LXXRNdz1z3YjNk82yjdP9+Q4TXkJOcj6ursSO9Q8UXzVPV395b5pvuo/aL/iwE8A6IEzQXPBqUHQwicCMAICAndCWILeQ3YD0QSsxQ/F9MZJRzuHf0eRx/qHiAeBB2xG0ka1BhTF8AV/BPlEZcPUg1IC6EJaAiDB9EGRwbRBWAF+ASNBPgDOANlAn0BgwB7/17+Lf3s+3n6qviT9m30dvL18A/woe9474Xvxe898Ofwj/H88TrygfLy8qvzyPRB9gz4Gfou/AP+cf9bALcAvgC5AL8A0ADmAOMAxwDDABUB5wFWAywF8wZmCIMJWQoJC7wLegxGDSYO+g6FD7YPjg8HDzQONg0DDJoKLgkACEoHNAeQBwQIZQimCKwIagjkBw0H6AWTBCUDqgE8AOH+hP08/Cj7QPps+aH4zffq9gr2MfVL9Fzzb/KN8fXw8/CN8YvysfPI9Kv1Wfa49pD22vW/9HLzR/KM8UzxcfHy8cTy0/MD9SX2Effd98H4xPnW+vD7Cf0k/lL/fABlAesBDgLzAeYBHQKKAgoDogNoBGYFiAaSBz8IkAi0CNMICQlbCaQJxgnPCc8J0QnhCQQKNgqMCgYLiQsDDIoMUw2fDrsQyROuFx4clSBpJAonDSg2J4ckPiC9GogURw6uCFQEmwGJANYAFALQA5IF9ga2B7YHFAckBkMFrgRtBEsE9gMeA5MBP/88/Mz4PvXU8bHu1esy6c3mvOQW49jh4+AO4E7ftt5q3nre396P35XgCuL740nmrOjW6pbs4e257hPv1O767bXsYOtP6q/pgenA6YTqA+xd7n7xF/XM+GD8xf8FAyAGDAnEC1MO0RBCE4UVYxepGEMZNRmIGEQXdxVPExURHQ+mDcoMlQwIDSUO0w/VEcUTSxU9FqkWsBZmFrwVmRT6EvkQxQ53DA0KcQeeBKEBm/6p++r4d/Zj9LbyZ/Fj8JLv6O5p7i/uUe7a7rbvxvDi8eDylvPv8/LzsvM685by4vFI8erw2/AX8YrxG/K58mfzLPQD9eP11vYE+JL5mfsl/j8BwwRpCNwL1Q4cEZQSTBNzEzoTrhLIEZoQUQ8lDkcN0wy/DOsMLg16DdUNRA6+DkQP3g+dEHwRSBKoEkAS7BDUDj0MVgkwBuMCr//r/OL6pfkZ+RH5gPlh+oz7lfwB/ZH8Xvu0+dn38PUH9DHyp/C675vvMPAu8UPyL/Ow84rzq/I+8ZTvEO4L7cDsNe1L7uPv4vET9Bn2nfd8+Mz4t/hn+Aj4uveF9273hPfU91X45Phw+f/5qvqE+4r8qP3C/sr/xACyAYYCNgPKA1AEwgQKBSQFJgUvBUoFdAWfBboFzQUCBnwGKwfXB1oIuQjxCNgIMAjuBloF+QNtAyMEDga/CMcLGw/kEicXohsJIBckfSfHKZUqvCk/J0kjRh7VGIUTog5eCg8HHAW4BLcFuQc5CpkMQA7TDlkOGw2KCy0KeQmDCeAJ5QkbCVwHuARLAUj98fiI9Ebwbuw36azms+RE43ziYeKq4vDi/uLt4vriUeMM5BvlOuYm59nnhuhJ6QLqh+rc6hvrQOs36wPrt+pY6vHpwOkd6ibrreyN7tnwrvPv9lD6l/2sAJUDcQZfCVkMGA9fESQTihSMFQAWxRXoFJgTCxJxEOkOew0pDBMLdwp3CgwLFgx3DQUPgBCoEVcShxI+Eo0RjRBDD5wNggvtCNwFbgLk/of7cPiC9bryS/Bz7kHtnex87M7sb+0s7u7urO9a8Pzwu/HG8g30SfU09qn2ivbE9YP0N/NQ8v3xMPLB8ozzevSO9dL2LPhp+XX6fPvQ/Kn+GAEUBHsHCQtpDlgRtRN+FdMW3BeqGC4ZXhkwGZcYbxeiFVET1RCHDpwMHAv6CTQJ8ghMCSwKQwtODCwNyQ0KDu8Nog09DZsMcAt3CY0GvgJk/hz6dPab84HxN/Do74PwmPGd8jjzSfPb8ifyevH08JnwhfD08A/yrfN89Sf3Ufii+AL4rvYD9TzzffEF8CjvEu+47/XwlvJQ9Nn1Cvf197X4Wfnq+XL6Afuf+1T8K/0d/gH/qf/3/+//q/9F/9D+T/7W/Yz9mf0D/qv+Xv8BAKgAiQG/AikEcAVBBnsGNQagBeYEIARaA6sCSwJlAvQCrgNGBI8EkARjBBYEnQPhAvsBWQGJAd8CSQWLCHwMERE0FqsbISEvJnQqpC1/L7Ev8C1DKiYlSR9WGdQTOA/JC4UJRwjmBy8I1giWCVwKHQuvC+oL9QswDNEMpw1MDl8Olw3AC8cIzQQQAOv61fVB8XPtaOr059/l/uND4sLgf99H3urcgttn2unZKNor2+rcR98S4jrlnujY62Du8u+w8MzwT/BJ7+3tc+z36qLpsuhI6E/ozugN6kfsUu/e8s32I/vC/3MEHgmyDfERiRVdGG4apBvnG2UbeBpFGa0XoBVEE8cQUA4uDMUKMQolClYKsgo1C7oLHAxjDJ8MugysDJcMjQxiDNYL5AqbCeIHfgVjAsj+6voB91fzJ/B77SXrCOk259Xl+uS25CXlYuZd6OfqsO1t8OPy8/SE9nn30/e59273Lvc297n3s/jN+ZT61Pqo+j36pvn/+JL4yPjs+R38Vf9qAx0IIg0lEsYWmRpTHfge1R81ICEgbR8CHggcyBluF/wUfxIcEAIOQgzcCr8J4ghLCCIImAiMCY4KIAsPC2gKOQmJB3gFPgP1AKL+Ufwu+mb4Dfcq9qf1Q/Wm9JnzKfJ68KXuxuwe6/3pmOn96SDr7OxC7/bxz/R494z5uvr1+m36avky+Pr29PU89eT0+/SC9Vz2RPf79234pPi0+LH4v/gM+a35mfrE+yj9pP78/xMBBAL5AtwDegTDBMYEgQTmAxcDYQLiAXkBGAH4AEgB6gGUAisDsgMWBDUEGgTxA9sD8QNRBAQFxgUqBvIFJAXbAyMCGgAA/h38s/oH+kf6ffun/dAA8gTDCeEOHhR/Gece7yMbKBkrrSyzLCQrHyjUI5weGxkbFBcQEA3IChoJ6gcNB14G3wWWBXkFhgXsBdIGLgi+CTELMAxqDKcL4wk4B8oD3//Q+/L3ePR28fPuwOyC6gLoTeWX4u3fVt0A2zjZMtgM2NfYhtrV3HTfQeIx5RfouOoO7TfvKfGm8ozz9vML9MjzJPM+8knxafC771zvau/47y7xQvNI9hr6cv4aA+wHwAx0EdUVnxmHHGMeNx8GH9IdyRtUGdkWfBQ+EjYQlQ5oDZAM6QtYC7wK9wkHCQEI+Ab5BRsFggQuBPwDwQNiA8wC4wGaAAL/Mf0n+9f4RvaN88Tw9e0u64LoBubO4/fhuuBY4APhuuJM5Wrov+v77ujxaPRy9hb4f/nb+kf8zv1y/ygBugLUAzsE8AMdA+sBiQBM/6P+5v4/ALcCNQZyCg4PsRMPGMobmx54IJohNCJSIv8hUiFSINwe3BxyGskX7xTrEeYOEwyBCSMHBwVfA0kCwgGqAc4B5AGvARwBRQBD/yf++vzH+5D6YflY+Jn3IPfE9lD2kvVa9IryMfCP7QfrC+kE6C/ohOnI67Hu+PFO9WH46Pqs/If9f/3U/Oz7Ivu4+sr6Sfv7+5T86/zy/Kr8F/xT+4r64Plz+VT5f/nZ+VD68frH+7j8l/1f/iv//f+sAA4BIwEPAfYA8gAGAR0BLQE6ATkB8wA0ABT/8v0R/XH87/uM+3T74fvz/JX+dAAoAmMD+wPKA78CCQEe/3n9UvyP+/L6W/oN+qb6w/yaAPUFdwzHE2sbpSKkKNEs+S4wL6gtgirfJSogRxpDFcYRzw/5DskOsQ4pDuQM/ArNCMoGVwWqBK4EIAXRBcUG4wfcCFUJHQkgCEcGrAO4ANX9Jvuj+Ev2B/SD8XPu2Oru5u7iFN+x2/rY5NZt1eHUtdX911HbIt8U4+XmWepa7ffvL/Lt8071kfa09234n/iU+In4Y/js9yD3KPY49Zj0s/Td9Sf4Yvtf/+8DvAhgDZ8RZRWGGLwa/BtyHDUcVxsoGiQZeBjxF00XcRZZFfITKhL1D1INTwoNB8UDwwA//mL8UfsO+1D7sfsD/Ef8d/yE/IH8j/yl/Iz8BPze+gv5jfZp86rvh+tb54njfeCd3hre397B4ILjrOa36W3s6e5K8Zrz+fWC+Dj7G/4qAUAECgc7CaEKNgsICzcK3ghBB8YFwwRNBFcE3gToBYEHsglqDGYPXxIdFXsXZhnzGloczB1EH3Mg5CBZIOgesxyxGdgVSBFHDD0HogLS/u77F/p0+e35BPsm/N383/wb/Or6wPni+Hn4qfht+YX6r/u//H39nf3Y/Af7N/i89CzxNu5r7PzruOxL7mzw1fIk9QH3TvgN+Ur5Nfkn+W75I/o/+7D8Xf4JAE8B2AGIAXQAwv67/Lr69PhS9831l/TO80vzB/Mr87zzdPQm9fX1IPe1+KX6xvze/rcAPAJvA2AECQVSBSIFbgQ5A6AB6v92/m39w/xz/Kr8h/3l/mcAxQHrAtkDbARgBIwDIQKXAG3/7v4R/5r/TwARAfQBMAM+BbcICA4GFd8ceyQDK/cv+DKfM7UxcC18J8sgUBrTFNEQhQ7wDcMOMhAVEXwQNw7OCv4GcwPNAH7/l/++AHoCTQS5BVIG8AWZBFkCS//X+6L4H/ZW9ATz4PGG8I7uyutm6KLkoOCg3BbZcNbm1JXUkdW518zahd6K4lXme+nw6/ft2u/E8bTzfPX59i74Kfn2+aj6TPvU+yX8Lvzj+z37g/pA+uz6vfyt/4IDxwcaDFEQThS4Fx0aThtpG6IaKRlHF2IV2hPcEnYSlBLbEsUSDhLHEOUOOgzcCDcFoAFY/sj7SPq/+db5Qvqq+qv6KPpW+Wn4iPfj9pL2c/Zm9l32G/Y/9ZnzJ/H37UrqtObX4ybi+OFr4yPmdemw7FDvFvEr8vjy7vNr9a33svo1/uMBcgWeCDULDw37DeoNHQ0DDAkLhgqhChgLngstDNAMUA2SDc8NQw73DgkQpBGZE5sVpBe1GXYbehyaHL8bzBngFksTTg8YC/MGKAPl/2D90/tC+4P7R/wU/VH9nPzZ+i/4H/Vy8sXwSfAJ8efyhfVs+E37zv1l/53/Uf6y+0j47PRb8vjw6vAs8mX0+vZX+fb6kvtl+/b6kfo++iv6m/qM+9P8T/7V/zkBdAJ/Ax8EMATnA3wD4QLqAXEAVP65+w75p/aQ9O7yCfL88aLy1vN99Xj3uPko/Hb+SQCWAXgC7gL/AsYCRwJ7AZIAuv/j/vj9N/3j/PX8O/2I/an9g/0+/QL9t/wh/Cn7/Pns+DP40fe09/L3wvhp+jj9dQEbB/0N/RWoHvUmyy2BMqw0AzTNMOYrICYKIEoahxUPEuwPIA9pDxAQPhBXDzUNHgqrBoIDRwGBADgBywKABPsFDAdyBxcHJAakBHoC3P9R/Sb7NPlc9631FfQl8mXvw+tw57riHd5a2u/XzNa61s3XGtpK3engsuRW6FLrYu2u7onvSfBw8W/zQvZ5+ZL8F/+pAC4BxwCW/7H9S/vF+KT2fPXC9ZL3vvr6/uoDEQnkDewR3hS+FtQXaRiAGA8YTheeFi8W8xXLFZUVHBUZFGES8A/ZDEIJgQX1Ab/+0vtD+WL3TvbL9Z31rvXb9ev13/UA9o32kPf6+J36DvzG/Fr8nPqc97PzaO9E67XnLOUN5IvklebK6XTtw/Ah82D0kfT58xzzuPJn82X1pvjm/LUBfQawCu8NDhAPERcRdxCJD5IOzQ18DcYNfw5FD9APGBApEA8Q6A/gDw8QeBAyEWgSIRQZFugXMRmeGd4YsxYoE5kOkQmyBJkAtv0w/Oj7m/zq/Uj/DACt//z9Dvsx9/fyM++87B3sbO1Z8FP0q/i2/Mv/XQE5AaT/Gv0Y+h/3uPRD89fyUfN19OL1M/cq+Lb4zPhs+N/3ovcG+AH5a/o3/Fr+oQDOAq4EDwbGBtcGdAavBXAEmgI/AJn96/p1+GX2zPSr8wjz6PI+8+TzxPT59bj3A/qX/DD/qwHuA84FFgeQBxgHzgUBBPIB6P9L/mj9L/1y/Qn+rv7p/on+sv1+/AD7bfn797H2o/Ua9T/1+/Uo97X4mvoL/WIAwwRACiYRbxkWIp8pHS8wMnwy4y/lKl0kMx13FjARwg0ADMoLJw2WD+MR0BLNEf4O7gpcBjcCYf9e/j7/mwGSBDMHFAlRCuQKfwoLCc4GGAQsAVj+w/tf+Qj3iPSB8crtlekq5dLgJt3N2t7ZENpB2zndct+94XPkeuch6hXspe387g/wNPH58nf1cfih+4v+iQBKAfkA3f8V/rX77fgw9gL0vfKL8r/zoPbx+gwAaAWFCsoO4xHxEyMVgBU0FbMUYhRqFMoUaxUtFtgWDhdlFr0UNRLmDhYLVQf+A/sAR/43/OD68Pkn+Xj4rPeQ9lv1b/T48yf0R/VY99L5+fsv/RP9n/v9+Gz1YfGR7Yfqd+iZ5zToKuru7PDvpPJk9Lb0vfMU8nLwg+/c79DxOvWE+f79SQI4BmsJcAtNDIoMiwxnDD8MUgzFDKkN8w5LED8RqxG9EaARaREwEQER7BAjEasRORKZEusSOhMoE2ES6xDnDoMMLQpiCEwH5wY9Bw8ItQisCNQHCwYCA8f+8vk99T/xlu6+7dDug/FV9Zn5dP0kAD0BqACU/mD7lPfa8+bwMO/E7m3v+vAc8zr10Pa99xb42fcr94P2R/Zt9tL2kPe4+Bj6dfvG/PT9vv4H/yT/aP/F//n/BwANAOX/Qv8e/sD8XfsE+tL45fc+98T2h/bO9t/3vfkv/AD/BALMBLUGgAdgB5cGRgWzAzUC+AApADEAOQHQAl8EkQU2BhYGEAUMAwgAc/we+ZP20vTI84Dz+fMk9ez2Hvmn++b+VgP9CJMPvRbVHfgjjihKK7krpymqJcUgrhvyFhwTexAYD/4O+A9BEdgRDBGODoIKlAWlAHj8z/lS+f36Cv6IAc4EbgdDCXIKBQvmCi4KFQmXB5MFIwNuAHz9S/rS9vfywu566nHmAuOc4Hvfc98c4A7h4OFz4hzjIORS5YzmCugE6njsdO8B89H2k/o9/oYBsQNIBGYDUgFg/hv77/f29GXyvPBF8AbxDvM49vv53P2qAQ0FmAdbCcAK+QslDY0OMhDBETITzBR3Fr0XaRiPGC0YMBegFYcT/BBFDr0LcgkpB5kEoAFo/kn7avjf9fTzEfNL8270WfbW+GL7Yv13/nf+V/01+2T4YfW48trw+O8v8F7xAfOB9KX1T/YH9nH07vFJ7xrtwOuN65fsqe6H8ef0TvhF+6T9ff/sACQCVgObBP8FkwdMCfcKYwxwDf0NAw6zDVgNLQ1RDcUNbw40DwMQ0BB9EfsRPRIwEsQR7xCuDyUOrgyxC3ULHgyDDRoPOhByEIAPOg2rCS4FPgBe+yL3GPSL8pfyM/QN9176Mf3W/gX/x/1h+0X4CvVM8oLw4O8+8EDxiPLi8yD1BfZj9jj2pfXh9Cn0o/Nf83Dz6POb9Dz1xfWC9pL31vhA+tz7jv0m/5EAxgGgAgUD7gJdAm4BYQBd/2D+ff3g/JH8ePyQ/Nn8N/3N/fL+rACAAvwDHQX6BYIGmAZBBrYFZQW+BccGDAgbCdwJUgpSCpUJ8gd+BYECVv9B/GL51fbW9JnzHPM7893zAfW39hb5OfweAL8EDgrEDy8VoxnVHKoe/h7kHdgbdBkxF3cVihQzFAIUshMfE+4Rvw+RDKsIYwQ6ANf8r/rw+bj69fwfAG0DTQZ4CMoJUgpgCjkK7Al/CQ0JlQjrB+MGZAVjA/YASP5R+9r34fPL7w/s8+h75nnkruIY4fvfcd9T35vfjuBZ4tLkuOfm6kHuqvEE9SD4q/pc/CX9Jf2C/Gn7GfrZ+Nj3EPdt9g72Nfbq9u/3EflH+nz7gvxM/f79x/7O/0YBXQMTBisJVwxjD0QS3hT3FmcYNRmFGXoZJxmLGJcXTRa3FMISURBiDR4KtQZoA3oADv4l/Lz61/lh+S/5Fvn0+K/4NPhr91H2NfWT9Jn0I/Uc9n738fjk+RD6gflE+FP2z/MN8Xzudewt66LqpOr/6pbrdeyV7anube8P8PjwVPIE9A32kPiA+57+tgGjBE0HsAnPC6QNMg+SEM8R2BKXEwIUFhTZE1ATexJpEUYQQg9oDtANqg0TDgIPeBBvEpQUVRZLF3IX5xaDFQYTmA/2C+AIswaABS8FXQWMBYkFPwVIBCQC3P7/+g73YvNG8O3tdezy603sO+2J7hfwp/Hi8p7z0PNt85fyt/Ea8bTwafAc8KnvJu8B74nvlPDH8ery9PP/9CX2N/fZ9wj4K/iP+Cj5zflv+jD7V/z8/c7/eQECA4EE1QXvBu8H1QhwCbEJnAkSCfYHcQbdBJsD9gL4AoMDlQQ1BgoIgwlnCtQKyAoPCpMIdAb/A6EBoP8H/tD8BvyY+3H7qPsv/NL8nv0M/1QBOwSBBwALVw4MEe0S5hPYE/ESxxHWEF0QiRBbEYQSpBOEFMgUBRQYEh0PQQv0BvwC9f8H/jv9iv23/msAXAIbBEEF3wVmBv0GewfZB0UIyAg2CVwJEAlJCBoHigWIAyMBdv6K+3r4kPXU8vTvyeyZ6ZzmtuPs4KfeYN1I3UreK+C34trlZenl7OzvW/I79Ir1OvZc9iD2w/V69VX1U/WG9QL2uvaQ92j4H/me+eb57/ma+fn4a/hG+K/4xPmX+wL+yADQAwwHUQpxDUYQsRKxFHEWARgtGeAZNxpAGr4ZdRhqFtAT4xDdDfAKRggGBj0ExwJ1ATAA6/6W/S/8xfpj+Rr4Jvfi9n332fi8+vr8Yv+IAeYCQQO/Ao4Bmv/V/Jv5kfYd9Dbyp/BY70rugO3t7GfswusI643qoepK63DsIO5o8C/zTPar+SL9WQAZA2wFgQd+CW8LPQ28DuwP7xC+ERgSxRG+ECYPPw1RC5kJSQimB+gHFwkCC2ENxg/MEUYTGxQdFD4T0hFoEF0P0w7VDlgPNRApEdcR3BHvEPUO8wseCNcDg/9r+8T3uvRV8obwPO9p7g7uRe4S7zzwf/HC8vLz1PQr9fT0WfSR89PyOvK+8WfxZfG98TXyhfKF8jDyk/G98Lrvre7a7XPthe0h7mTvKvEv81/10/du+u78O/9dAUgD+wSBBsUHkwjHCGsIrwflBkcG2wWrBeYFlQZVB8gH3AeiBysHkAbUBdcEsQPQAnsCfQKUAtICUQP7A5wECAUoBQ8FAgVDBeMF3AYqCLwJcgsZDXUOXQ/ID8APZw8GD9IOwA7ADvkOhg8WEDAQqw+oDkkNngu/Cc0H+AWBBJUDHgPxAu4CEQNYA7UD+APrA5sDUQNRA5gDBQSFBBcFrgUoBl8GSAbqBT4FPgT4AogB4//i/Wf7iPh39WTybu+h7BfqBeic5tzlteUa5vXmE+g76UbqIuvb65vsb+097gfvAPA88X7ymfO29Af2bfeO+DP5ZPlI+fz4c/iT93H2W/WT9Cv0EfRG9Or0Ifbl9wH6TfzL/oMBWwQrB9cJTwyZDtAQ7hK7FBsWKRfjFxEYnxfEFrQVXBSmEqkQkg6FDJUKugjfBgMFSgPNAYQAYP9g/qv9dv3K/Xz+bf+fAAsCdwOvBJEF/AXaBUQFYgRNAwwCrAAx/6n9JPyh+vf4C/fy9NDysvCt7uXsf+ug6m3q6+oC7JbtjO/G8Sz0q/Yu+aL7Df5oAIgCSwS3Bd0GrAcPCAwIwAdJB78GIAZsBcUEXgRFBF8EmgTnBDUFhQXNBeoFyQWqBecFlgaaB+gIdAojDNENWA+LEDgRSxHBEJsP9Q3+C90JrgeOBZwD6QFwACz/F/40/YL86vtT+8P6R/rK+Tr5rPgi+Ir39fai9qf24fY497f3S/i7+OD4tPg3+Gr3ZPZN9Uv0dPPL8lryMvJg8tHybvMy9Cb1TPah9w35X/p9+3P8Rv3u/Wr+vP7e/t7+8f4+/7v/WAAdAQYC8ALGA4wERwXgBT0GUAYnBugFsgWHBWUFUAVGBUcFZQWkBd8F4QWnBUYF0wRPBMIDPQPiAswC/gJ2A0UEewX2Bn8I5An2CpALuwujC10L6gpgCugJkAlICfwIoAg+COsHqAdTB9UGRga+BSoFcgSkA9oCGwJkAb0AOADs/+j/LgDCAJwBrALkAz4FlQamB1cIyQgJCeQIOggvB/EFjAQGA3AB4P9s/ij9F/wa+xr6FPkC+Nz2ovVZ9A/z3/Hr8Ejw9O/y70/wFfE78qbzL/W+9jr4dPlE+rX66PrQ+lf6m/nH+OL36fYF9lP1xvRE9NHzevND8yfzI/ND85rzOfQf9Ur2uvdY+QX7tvx0/i4AuwH+AvMDogQZBVUFTgUPBcgEjgRNBN8DPANvApQB1QBEAMz/Y/8f/yD/Yv/N/1EA5QCVAWwCSwMABIgECAWPBRIGjAYFB20HrwfCB50HNgeNBrkFxgSuA3YCNAERACj/b/7n/ab9vv0Y/pv+T/87AE4BbQKOA5EEWQXvBW4GzAbvBtwGrAZtBjgGLgY9BjIG+QWmBUAFsgT4AzMDggLuAX8BTQFwAdkBXQLkAm8D8gNdBK8E6QT0BLwEZgQhBOUDiQMLA30C7QFVAaMAx//a/hT+k/06/fL8wvy1/MP85fwP/Sr9Jv0Q/fj81fyc/FH8Dfzl+9774PvV+7f7g/st+6v6CPpQ+YD4l/ej9sz1PPUO9Tf1ofVN9jz3VviA+bD60fvQ/Lb9jP43/57/3f8gAF8AgACSALYA6QD7AMcAWgDi/4j/Tv8X/9z+vP7a/jT/rP81ANkAqAGRAmgDGgSxBDcFpwUCBkEGXQZbBk4GLgbcBVcFwgQzBJwD+QJXArQBCAFPAJL/3f47/rT9Qf3i/KX8kfyi/Nn8Qf3R/Xv+NP/6/7gAVAG9AfMBDQIcAiECDQLXAYMBFwGrAEwA8v+L/yj/7/7l/vL+Ef9Z/9b/fgA7AfkBpgI9A7cDEgRMBHMElwTMBCYFpAUkBokG2wYtB24HegdEB9sGVwa4BfMEDwQrA2gCyQFDAeAAtQDIABMBlgE9AuoCiAMTBHUEhgQ0BJoD5wI5AowB0AAWAIP/Iv/d/pX+QP7c/W799/xr/ND7UPsa+zT7e/vS+yv8gPzK/P/8Ff0F/dH8hvwu/NL7ePsc+7z6X/oD+pH5//hn+Oj3hvcw9+v20Pbq9jT3pfdA+P34y/mh+nr7SPz4/Hr93v0u/mn+jf6m/rv+wP6x/pb+cf4//vv9pv06/cX8Z/wt/BP8IPxm/OP8gf07/hn/FAAMAfABwwKKAz4E3ARjBc8FIAZoBq0G3wbmBs4GtAaSBkkG0QVGBbgEFgRgA7gCQwIJAgcCPAKsAlADGwTwBLgFYQbeBiQHOgcwBwkHtwY8BrwFRgXJBDIEhwPQAgkCNAFVAGz/d/6K/cr8P/zS+3b7QPtB+2n7nfvS+wr8Tfyd/Pf8Sv2J/cD9+v0l/i/+Fv7d/XH9y/wC/DL7XvqP+d74Zfgl+B74V/jG+Ev51vlr+gn7mfsX/JT8Hf2v/Uz+Cf/o/9QAuQGKAjkDtQP/AygELgQMBMsDiANQAyoDGgMiAzgDUANnA3sDgQNyA18DVgNnA5kD6ANOBMUETgXaBU8GmwbABrkGhwYyBtIFcAUABYUEEgSsAzcDmQLZAQ8BRgCE/9T+R/7j/a79qf3A/d399/0I/gT+1P2A/SL9zfx8/Db8A/zj+8n7s/uh+477d/tg+0T7H/vy+tH6y/rd+vv6IPtL+3X7n/vU+xn8avzC/CH9jP3//XT+7P5q/+3/ZwDZAD4BlQHUAfQB9gHbAaYBaAE4AScBPwGCAfEBkQJaAzUEBQXDBWwG8gZHB2MHVwc9ByUHEwf9BuMG0wbRBtAGwwaoBoAGSgYOBtwFswWEBUoFCQXFBH8EOwQABMcDggMtA9gCngKBAmgCOwICAsIBbQHvAE8Apv/6/j7+af2Q/MT7BPtF+pL5Bvmr+HT4VPhJ+F/4k/je+C35avmP+av5yPnf+d/50fnI+cj5x/m9+Zz5XvkG+Zr4IPil90P3Bvfn9ub2DPdY97j3KPi4+Gn5LPrw+sL7rfyq/aX+lv9/AFsBGQK2Ai8DfgOtA9kDDAQsBCMECQT5A+kDxgOTA2IDRQNLA30D2ANQBNwEegUZBrEGQQe2B/sHFAggCDYIUQhdCE4IJAjlB5sHQAfEBikGhQXnBEQEjAPEAgYCWwG8ACEAjf8C/3z++P1//RT9uvx+/GP8XfxX/FT8VfxJ/CT86/uc+yv7nfoL+n/58fhy+B74//cG+Cz4YviX+L/45fgJ+Rn5EPkH+Rr5R/mK+e35evol+9z7nPxl/Sz+4f6F/yIAoQDwACABVQGNAbABvQHaARQCXAKcAtUCFgNlA8ADGwR3BOUEZwXpBVUGswYJB1EHige5B9MHzge2B54HiAdnB0MHJgcNB+cGogY+BsMFRgXOBF0E9gOZA0kDAwPIApECXgIoAuYBmgFLAQIBtQBbAAAAtP9o/w//sv5m/iP+4f2i/Wv9Ov0T/fT8z/yR/EP89vul+0r79frA+q/6ufrV+gT7SPuV+9r7Dfw4/F38bPxm/FL8NfwH/Mz7mvuA+3b7fvue+937O/y0/EP94v2L/i3/sv8XAG4AvwADATABVAF9AbEB5AEDAhUCNAJrAqUC0QIBAz4DcAOGA44DmwOmA54DiAN3A3cDkAO8A/kDSgSoBAQFVAWcBdcF6gXHBYIFLAXJBFcE3gNnA/UCiwIiArgBWQEQAdUAlwBUABcA5f+4/4z/Yf8+/yX/Df/5/vD+9P7y/uL+0P67/pX+V/4M/qv9J/2L/PT7a/vl+mX69PmR+Ur5Mfk/+Vf5bvmY+ef5Sfqr+gb7X/u0+wH8Tfye/PX8S/2e/fX9Wf7C/iL/c/+6//v/NABdAHYAiwCuAN8AEwFTAa4BHQKDAt8CPwOmAwoEagTJBCAFeAXYBTIGcAacBsUG4AbcBsAGmQZoBi0G8AWvBV4FAgWqBFEE4ANXA84CVQLlAXUBEQHJAJsAcQBGACIA///K/4D/LP/P/mT+7/17/QP9ifwX/LH7R/vc+n76Mvrn+Z75WfkY+db4lvha+CL48/fX98731vfy9yr4e/je+Ev5uvkf+nr6z/oc+1r7kPvC+/H7IPxS/Iv8wPzu/Bv9Uv2Z/e79Qv6T/vL+af/q/2oA5QBUAbMBCAJXApYCzgIYA28DuAPpAx4EYwSrBOUEEQUzBUUFTgVRBVIFVAVNBT4FKwUfBRUFCAX6BO4E4QTUBMIEqASKBHcEZAQ8BAEEzQOsA5ADbgNAAwQDyAKUAlsCEAK2AVsBAwGyAGsAMgAGAOf/0f+9/6f/jv9x/0//LP8J/+z+yf6M/jn+6P2s/W79G/3D/HH8Jfzp+8z7y/vf+wf8Ofxd/Hf8mfzG/Of8/PwR/ST9Nv1R/Xb9of3T/Qf+Lf5O/n7+tP7l/hL/Qf9g/3b/jv+n/7X/yP/x/yIASwCAAMkAGAFsAcsBKAJ1Ar4CBgNDA3ADkwOxA8gD1wPbA9MD0APSA8IDmgNzA1cDNQMLA+sCzAKnAo0CgQJtAk4CNgIfAvIBvwGiAY0BaQE8ARUB7QC6AH8AMwDR/23/EP+u/kX+8/27/Yj9V/03/ST9Bv3d/Lf8jPxe/Dr8Kvwq/Dv8Y/yO/LP85vwt/Wv9k/25/eb9Bf4S/hz+Lv5E/mH+iv69/vr+Pv+F/8//HQBuAMEAGgFtAa0B5QEpAmsCnwLYAhoDSQNlA5IDxwPlA/wDHQQrBCAEKgRFBD8EGwQJBPEDnwM6AwMD4wKwAn0CXAI5AhsCGwIpAh0C/gHXAZUBOQHnAKEASwDt/6L/Zf8i/+L+tP6S/mf+KP7g/Z/9Yv0a/df8pfxw/Cn87fvO+6z7ePtg+3j7lvus+9b7E/w+/F78hfyd/Jb8lPyj/Kf8nPyk/L78yfzM/Nr85/zj/OT89/wG/Qv9Jf1c/ZX9xP3u/Qr+Gv41/mP+jv64/vX+Mf9R/2j/kv+//9b/6v8LACcALwA2AFAAeACfALQAuwDHAN4A6QDsAAEBHAEiASgBQAFHATABKgE+AUIBLgE0AVkBfgGkAdoBCQIoAkkCZAJhAlYCZAJ7ApACqALCAtAC3wLxAvAC5ALnAuUCxAKcAogCXwIYAuABvQGDATkB/gDBAHIAOAAiABAAAgAWADAALwAsAD0ASABGAFEAXgBQAD0AQwBJADYAGgAMAP7/5P/J/7n/uP+2/5//eP9a/0X/Kf8L//b+5P7Q/tH+7/4c/1H/iv+6/+n/KABlAIMAlgC3AM4AxQC3ALwAwwDCAMYAygDAALQAvQDSAOEA6gD4AAMB/ADnAM8AtwCbAIkAhQB/AG8AdgCYALEAtQDEANsAygCcAIMAbAAsAOP/uv+T/0//EP/w/tb+t/6j/pH+df5g/ln+Q/4e/gL+7f3S/bz9vP3L/d397/0A/hL+IP4m/jL+Yf6Y/qr+rv7O/vL+9f78/if/Uf9c/23/kf+x/9H/BwBDAHIAoADTAAYBQgGDAaIBqAG8AdgB3AHjAQ8COAI9AkQCZwKLAqUCxQLdAt4CzgK2ApICcwJfAkYCIwIOAg8CGAIqAjUCKAIcAiwCNAIWAvwB9wHXAZcBbQFaATMB/wDRAJQARgAOAPH/zf+d/2b/J//q/rv+i/5g/lP+U/5A/i/+S/55/ov+lv6z/sj+zP7T/tr+yf6s/pj+gv5r/mX+ZP5N/jr+Pf5C/kf+YP52/mr+V/5X/lX+V/55/qH+pf6n/sH+0f7Z/vf+FP8S/xL/Iv8i/xb/Gv8a/wb/Af8U/xf/Cv8I/wn/A/8M/yD/Jf8k/yv/Kf8Z/xD/Ef8J//7++P7q/s7+xP7T/tr+zP7K/tn+2v7Q/tP+3f7f/un+//4M/x7/Sv9//6j/0P/3/w4AHgAxADcALAAXAAQAAgD+/8j/cv9c/4L/g/9g/23/kf+E/2X/Yv9j/2j/iP+h/5j/oP/K/93/zv/U//3/OAByAJAAjQCRAKYAoQCGAIIAiQBzAFUAVABfAGgAggClAK4ArwDVAAEBBwELATABTQFPAVwBdgGGAaIBxQHGAfEBkAIhAyIDBwMpA/ICQgLfAesBrgEoAeoA4gC9ALcAAAFGAUwBSAFjAY4BoQGMAW8BWAEQAYUAKgBDAGkAPgD///f/BQAIAAoA///J/3z/OP/e/nD+N/4z/vP9bf0U/Qz9IP1X/bT93v3J/dz9GP4Y/vL99v0H/vj98/0E/g7+JP5N/lr+Uf5z/qr+tv6q/rz+2f7W/sj+7v5T/5z/lP+G/7D/1f/p/0MAzgAPAR0BaQHXAQkCMwKmAgQDywJGAh0CTwJWAjYCeAIMAzsD3gKeAsEC2wKYAjgCDgIMAu8BtgGnAdgBBAL/Ad4BwAHHARICZQJiAg8CtwF6AWIBXgEwAeIA0QDpAL4AgAClAOYAvgBVAAkAx/94/zX/Cv/r/tb+xv7T/ir/sv8HABMAGwBBAFsAQwAVAPf/zv93/yz/Nf9v/6X/4/8lAEEAQwBeAI0AogCOAFoAJQAQAP7/2v/Y/wIABQDm/wwAWQBlAEYATABnAHEAfgCLAHwAWAAqAPf/zP+1/6//tP+n/3j/Xv+Q/+X/HAA3ADkAEgDX/6n/ff82/8/+Zf4y/jf+I/7t/fz9V/6H/nL+Zf53/oH+Zf4Y/sL9rP3D/an9Zf1L/WP9kv3Y/Sz+e/7N/hL/Ev/O/nH+H/7m/b39df0P/cz8uPyy/Ln83vwG/S79bv2x/c79wf2d/YH9fv10/VT9UP13/ab93/1C/q3++/41/0n/Lf8j/07/d/+L/5z/iP9O/zn/Sv8z/xT/Pf+P/8//GACGAAABaAGnAcUB4wH4AeQBzAHwASgCNQIqAjACTwKOAusCPQNqA4ADogPSA8oDZgMJAxADJgPfAoACbAKJAq8C4wIVA0YDlQPOA7EDdwNcAzUD8AKzAl4CzAFNASsBMgEmAR4BMQE8AR0B2gCaAGUAIgDc/6n/bv8d/+f+2v7E/qn+r/7F/tn++f4O//f+0v6p/nf+cP6X/ob+Qf46/kn+BP7C/ff9OP4f/gH+GP4j/hz+Sv6y/gr/Iv/3/sb+zv70/vb+4/4A/z//Xf9o/7j/LQBLAB8ANgB9AHUATQB9AMAArACFAI8AkwCFAJcAwADyADABSQE8AVkBhwFhAS0BXAGHAU8BNwF1AXwBLAEQAT4BTwEsAQsB+gDpANAAsAChALUAtwBwAAgA2f/p/+7/1P/T//L/9f/l/+3/6v/F/8f/+f8DAOD/0v+2/1//Ef/7/u7+3/7T/rj+qf7F/sv+ov6l/tn+2v68/sr+1v6+/tT+GP8n/xD/Kf9e/3D/cv+N/8T/AQAeAA8ACAAtAFgAYABYAGgAjACeAIwAdwCEALEA7gAqAUoBWgF7AZ4BrAHSASACUgJWAlwCVwI2AjACQwI9AjYCSgI5AgMCDAI6Ai0CJAJmApACawJUAl4CQQIPAgMC+AHNAagBjQFjAT0BNAEyARwB7QCoAGQAPgAlAPP/pP9l/0L/Fv/L/o3+aP4z/vf96P3i/bn9qP3H/c/9vP3L/dr9rf18/WH9Nf0L/Qj96vyj/J38wvyX/DT8HvxT/H/8kvyM/GL8Rfxg/Iv8jPxt/Gf8ivyw/L/83fwr/Yj9yf3w/Q3+Kv5V/nn+hv6T/rH+zv73/jb/TP8j/w3/J/8v/yz/YP+z/+j/CwAuAFIAhAC0ALgAqQC/ANkAxgC0ANMA8ADcALwAzQAKATQBQgFhAZABngGOAYYBbQErAfYA4QDCAKUAtQDhAAYBGgEKAeIA7wAwAUUBGwEDAQsBBAHwAOkA6wD4ABQBJAEdARQBCgH5AO4A3wC+AJ4AlwCUAHsAVwBQAGUAZAA9ACUAOABLAFIAdACsAM8A4wDnAMEAmgCwAMgAkgBOAEQAWQBtAIUAkgCWALkA5ADkAM8A1gDmAN4AyACpAIMAcAB2AIgAqADUAOQAzAC6ANoAEAEbAe4AzADlAAUB5wCdAGwAXgBHABEA8v8qAHwAewBOAHoA2ADNAFoAGgBJAJkAngA7AM7/zv8dACsA4/+0/9P/+v/c/4n/Y/+l//f/4f9//07/Wf9B//b+0/4R/2j/dP85/xz/Qf9m/1b/MP8r/zf/I//v/tX+6f7z/tX+wv7f/gD/Bv/3/ub+9/44/13/M/8R/0z/mf+O/0j/Jf8+/1//Uf8s/0H/of/w//X/6/8OADgAMwADANX/y//c/+//AAAcAFAAigCoAKUAqQDLAPAA/wARAToBagGKAYUBZQFeAY0BugHCAdIB/wEPAvQB3gHTAbsBqgGtAaMBewFNAScBGQEsAUsBVwFaAXUBpAHGAccBqgGEAXcBhQGHAV8BLQEfASUBDQHkANsA9wACAeIArQCGAHkAawA5APn/3f/X/63/Wv8S//L+/P4T/wP/zP67/vT+LP8k/wb/C/8n/yr/B//X/rn+sf6u/qz+q/6h/oj+dv57/oD+cv5a/kv+PP4m/hL+Df4K/vn94/3f/fD9+f3v/en99/0F/gT+BP4M/gT+6v3Y/d799f0V/i/+Jf4D/vj9E/4h/hL+Bv4a/jr+OP4L/u79H/50/ob+Wf5I/nD+lf6l/rn+1v7t/v3+/P7s/vn+Lv9N/zX/JP9L/4j/sP+//73/wf/d/+//1//L//b/IAAfACwAXgB3AGUAYAB0AH0AggCWAKoAvQDdAPIA5QDYAN8A2QDHAM0A3ADWAOAAEwE4AUABWwF+AXcBawGTAbcBogGPAbIB2QHZAcsBwAHFAeoBFAIJAuMB4wHzAeEByAHKAc4BzgHfAeABtAGfAcMB1AGnAYIBnQHTAf0BDQLxAccBwwHOAbUBmgGiAZ4BcgFQAUUBKAESASMBHQHYAK0AxQDMAKIAiwCLAGQALAATAAwAEwBEAIMAkgCIAIcAbwBFAEcAVAAXALH/d/9S/xn/+v4E/w7/Hv9G/zD/xv61/n//sgCMAcYBaAGqAOP/Nf+T/jz+bP6x/nz+Ev73/f39uf1B/d38uvz2/Gr9rf26/eb9B/6f/fj87Pye/WL+pP5f/gj+Nv7W/jL/GP8e/1//Ov+1/pr+EP9v/17/CP+v/pj+4/4m/w3/Av9c/5f/U/8T/1b/z/8QAAsA7v/2/0EAfwBRAP////8pAC0AQwCnAAsBJAEgAUMBmQEEAkACIQLnAeEB8QHxAQ0CTwJwAmMCZQJ0AnYCkQLRAvIC5ALsAhMDLwNWA5QDoANfAzcDUQNeAzMDDgMnA3MDxAPsA+sD/AMuBDAE5AOdA4QDUAPgAoACcgKUApwCZwINAswBsAGIAUABBwH3AOgAvgCKAF4APwAbANv/cv8J/7X+ZP4e/hD+JP4Q/tT9uf3O/bv9Sf2r/Ej8Pvw1/NP7R/sH+xf7Evvd+sf67/ob+xf75Pqs+pH6g/pI+vf58vlM+pn6l/p8+pL6yfrs+uH6xPra+i/7bftj+2P7sPsK/DL8UvyO/L/8y/zX/P78QP2T/dn95/3d/QT+aP7J/gz/Qf9s/4P/g/99/4j/vf8MAEwAfAC4AP0ALgFKAV4BZAFfAV0BZwGFAcUBCQIfAh8CTQKbAsQCzwLpAgwDMANoA5MDeANLA10DewNYAzgDdAPMA+cD6AP6A/0D4wPBA44DSgM1A2QDhQNfAy0DKQM/A0gDMAP/AtQCywLZAtwCwwKUAl4CMQINAuQBwAGnAYEBQAEOAfsA3gC2AKgAnABqADsAMgAcAOn/2f/r/8z/h/9w/37/c/9V/z7/H/8O/yb/Of8T/+P+1f7F/p/+iP6C/oD+j/6l/pD+aP5k/mf+R/4//m3+kv6R/p7+yf7r/gj/F//8/tz+8f4L/+r+z/7p/vr+2v69/q/+p/7N/gb/7/6g/o7+ov6I/nf+q/7K/qz+pP6v/pL+kP7e/gv/8/4f/5T/s/+M/6b/zf+l/4X/rv+6/5z/uf/j/7D/c/+X/8//1P/i//j/3P++/+r/MQBpAKcAzACzAKkA4AAQARkBKwEqAe0AzAD0AAMB7QAWAVoBUgFAAXcBjAFRAUIBbQFIAe0A4ADwAMwAxwABAQQB3AAWAZgB2AHkARICQQJaApwCBgNOA34DtgPOA7wDtwO8A6UDjwOcA6sDsQPQA+4D7wMJBD8EOAT1A9sD3wOcAzED9gLdAsgC3gIWAyoDKwNbA5YDngOYA6QDfgMHA5kCfgKUAo8CSQLVAWYBEQG/AFYA4f91/xz/z/5z/gD+p/2A/Uj9x/w0/Lr7MvuR+ib6Bfrr+cX5t/m9+cj59vlH+nH6Wfos+v35qflK+TL5VflW+RT5xPiW+In4kPio+LH4jPhd+Fj4gvi6+PT4LPlK+VL5cvmz+ef5BvpM+sr6QfuV+/X7evwO/Zf9Bv5K/m/+pP7y/ij/H/8A//7+Ef8g/zj/YP+K/7L/4/8YADYAVAChABMBcAGoAcwB6wEdAnoC5AImA1EDmAPwAz0EkgT2BDwFWwV2BZoFtwXPBcwFkQVMBUUFWQUyBeMEswScBIIEdwR+BH4EgASUBIkEUAQxBEwEYgRJBCkEIQQvBEwEYgRRBDEELwQ3BBQEvANPA+YClgJaAg4CuAF6ATIBpQD4/3P/BP+J/ir+9f3B/aL9wv3t/ez9/f1H/nP+Yf5m/p7+vv62/qr+fv4s/gn+Nv5d/lT+V/5w/mH+J/71/dT9q/1//U79C/3C/Jv8nfy//Pz8Uf2q/fT9L/5p/qf+1/7p/vf+Jv9q/6X/0//u/+X/w/+5/9H/3v/L/6//mf+E/3D/Xv9J/z7/Sv9f/2f/Yv9i/2T/Vv8+/zP/RP9n/5H/zf8dAG0ArgDnABUBJgEdAQ0B9ADOALYAuQC/ALoAtwCqAH0ARAAlABgADwAMAAAA1v+r/6D/nP+H/4X/tv8AAEUAgwC3AOAAFQFcAY0BogGsAaIBdwFQAUgBOgEPAeoA3ADFAJ0AfABhAEoAQQAyAAoA7P8IAD8AYwCQAOQARwGwATcC2gKBAzUEBwXRBXAG5gY4B1kHXAdaBzcH3QZzBiQG4wWcBVgFIwX/BPkEDwUTBeEEkQRIBBAE5gPQA9kDCgRUBI8EqgS7BNwEAgUUBREF7wSlBEYE6gOCA/gCRwJtAWoAY/9r/lX9FPzt+iL6l/ki+c34kfhK+P731/fA94b3KffP9nr2NPYf9jH2QPZR9n/2q/aw9rH20fbt9uD2v/ai9nv2OPbh9Yf1PfUT9QP18vTb9Nj0DPV99Rn2yvaP92f4Ovn3+a36cPs1/N/8X/22/f39Xv7W/jz/iv/x/3wA/wBiAbYBAgI0AkkCVQJfAmcCZgJRAi8CHQIsAk8ChQLgAmQDAASpBFsFBgaZBgQHSQd4B5sHpwebB4MHagdGBxsH+QbYBqMGWgYVBuAFvQWfBW8FMwUQBQsF/gTMBIEEIAS3A2kDTgNOA2ADkgPUAwYELARcBIcEhgRMBNYDMAOQAhoCswE1AbcAUQDw/4z/L//V/mn+9/2b/Vj9JP3w/L78oPym/K/8kfxZ/Dj8NPwt/Bb8+fvu+xr8gPz2/Fb9nP2+/bT9mP2A/Uv96/yU/HT8ePyE/Kr89fxb/c39N/50/or+nv65/sr+2v77/ij/Y/++/y0AiADGAPsAIwE5AUEBQQE/AVUBjgHMAfQBCAIBAtcBnAFiARoBxQCKAHcAcABoAHEAiQCgALAArgCQAGUAPgAQAN3/yP/X/+T/4P/r/wYAFwAZAB8AJQAlABcA9P/D/6L/kf9u/zf/Ef8H/wD/Af8a/zX/OP8q/yL/KP8+/13/c/+Q/9T/NAB5AJkApwCwALYA1gARAUoBeAGnAcwB3AHcAdABsgGIAVwBGwG+AGoAPAAsAC8AQwBUAGEAlwAXAb8BawIWA8cDhgRlBWcGeAeCCHAJEQpOClIKTAovCt8JXAmuCN8HHgecBloGPwY3BjMGLQY8BlYGRQb1BZYFXAVJBV8FogUABlcGjgaNBlAG+gWmBTgFiQSrA7YCtQG9AOT/C/8A/sL8dvs7+hn5APjW9qz1x/RM9Bn0CvQc9D30V/Rv9Ij0g/RO9AD0sPNj8yLz8fLG8p/yiPJy8lDyLPIP8t/xnfFr8VLxRfFS8ZnxC/KI8hHzt/N49ET1Cva+9nT3T/hD+Tj6OvtT/Fv9Mf7v/rj/dAABAV4BmgG/AdgB6AH0ARUCVwKkAvYCbQMQBLQEQAXGBUoGugYaB3QHywcaCG4IvQgCCUUJhQmpCawJpAmNCVMJ/AiTCBkIngdCBwAHvgZ6BkYGGQbkBaMFWAULBdwE3ATzBAMFCQUJBQIF/QT2BLwEMgRxA6gC8AFLAbIAGgCW/0X/IP/3/rP+Zv4U/rj9X/0a/ev80fzV/PL8G/1L/Wz9Y/08/RL93PyP/Er8Lfwq/CX8Hvwi/DH8QPw4/An8wvuB+0j7F/sL+z/7qPs0/OL8pf1h/gr/n/8UAFsAiQCtANUAEAFbAZUBsQHEAd0B8AHwAd0BrQFyAU4BRgFDAT8BUAF9AbsBBAJMAoYCugLzAh8DMwNAA1MDXwNZA0UDFgPCAloC+QGeAToBxwBKANz/oP+M/3D/O/8O//n+7v7m/u3+9v70/u7+7v76/gv/Ff8H/+z+3/7W/rr+l/6C/nD+WP5K/lX+af5i/jX+5P2F/T39Gv0N/Qr9HP1R/bj9WP4Q/6r/GgB2AMoACwE7AV0BaAFuAY8BygH1AfEBzAGsAakBugGzAYsBYQFQAVIBXwGIAdUBSQLxAtADwASTBU0GCwfmB9cI0gnPCt4L/wwFDqwO0g6RDhcOiw3kDPILnwopCQIIYAcmByEHNQdhB7QHNAi4CP4I4giDCC8IIwhKCFoIMgjnB4MH4wbyBcwEkAM7AswAU//n/ZP8XPtF+kH5NvgQ9+f18vQ79IbzpPK18QPxuvDT8C3xnfEA8kzyifKl8mvyt/Gt8Kbv1+427prt/ux/7DHsJOxo7PPsk+0h7rPube9J8CfxAvL48hj0SPVp9nr3hvh2+S76tvo4+8f7WPzq/In9K/6+/kb/3v+QAEMB2wFfAu0ClQNMBPkEkwUjBrQGYQc7CDEJHArmCpQLGgxgDFwMHAy0CzALoQoWCpkJJAm2CGAIMwgkCA0I3AekB3gHWwdJB04HaAeEB44HggdjByQHsAYDBjIFXwSbA+gCRgLDAWMBIQHpAJ4AHwBr/5r+1v02/cP8b/wz/BX8LvyB/PD8Sf1z/XL9Wf0v/ev8j/wv/OP7uPuk+5H7YPv/+nv68fl++Sj57PjX+P74cPkt+iX7O/xU/Vb+Iv+W/6j/cf8j/+j+0f7l/ib/lP8aAJ4AEAFtAaoBuwGrAZQBiAGEAZIByQE7AtICZQPgA0kEqgT7BDQFUgVZBUgFKQUUBREFDQXpBJ0EOgTPA10D6AJ0AgoCqwFnAUcBQwFAATEBJAEpATwBSgFFASkB8QCkAFkAGQDP/13/0f5X/gj+0f2Z/Vz9Jv31/Mj8q/ym/K38pfyX/Kb81/wP/TP9Uf2A/bz97P0F/gf+9f3H/YT9PP37/Mz8wfzu/E79wv0u/pL+9f5T/6P/3/8JACMANwBfAJ8A5gAZAUEBgQHmAVICpgLgAgkDJwMyAzMDOQNPA4ID3gNjBPgEfAX0BZAGbweBCI8JggpyC30Mog29DpkPDxAZENQPZg/bDhcOAA2wC3IKiAkICdoI4wgaCW8JzAkRCisKEgrICVoJzwgzCJUHBgeFBvQFJQUKBMcCiAFXABb/qP0X/I/6P/lA+H33vfbP9cP02PMr84nyqvGS8JTv9+687rjuzO7t7hbvRe9w73LvGO9b7nrtvOwp7KPrK+vw6hTriesw7AHtAu4i70zwbfFx8kHz8fO89Mb14Pa+91P41/h4+Sn6xvpJ+7v7Nvzc/Mz98f4PAAkBBgIpA1AEOgXoBZQGWwcUCJ4I/QhKCY0J0AkvCrQKOAubC+4LSAyJDHYMAwxmC9EKQAqfCfIITwjJB4AHiAfTBygIWgh3CJMInQhwCA4IlgcRB24GqQXdBBAELgMuAjABUgCb/wX/nf5u/mn+c/6O/sL+8/7p/oz+/P1o/eL8bPwH/Lf7dPs5+xr7JPtF+1/7Z/tn+1z7Mfvd+oP6UPpS+nj6pvrG+s76wvqx+qn6rvrG+gP7dPsV/NP8mf1k/ij/zv8+AGwAWgAKAJP/KP/8/iT/i/8dANEAoQF4AjMDtQP7AwgE7QPJA78D3QMaBGoEywQ/BbAF8wXuBagFRwXxBLcEkwR1BFoEUwRrBJMEoAR7BDQE5wOcAzoDtAIdAqIBYgFUAVEBNAH2ALYAjABoAB0Amf8C/47+Vv47/gz+t/1T/Q399vzx/ML8VPzQ+3T7Tvs5+xP77/r5+kf7uPsc/Fv8hvy3/O38//zP/HH8Jfwa/EL8Zvxj/Er8SvyD/PH8bf3T/SP+hP4Q/6//KABmAIwAxAAQAVYBgwGkAckB/wFAAoICvgIHA28D6QNFBGAEUQRPBHQEqwTYBAMFQQWeBRAGkQYkB9YHtwjLCe0K5QucDD4N/w3bDo0P2g+7D1IPwQ4ODi0NEAzJCpQJswgzCO4HzAfuB3QINwnYCQsK1QlmCd4IPAhsB2oGUAVOBHgDrQK0AX0AN/8Q/vr8vPtD+sH4hPe69k328fVe9Yb0ovPq8lTynvGl8Jzv1u527l7uXu5l7n/ute7q7uruke7x7Uzt3uyo7IrsduyT7Art4e3u7v7v/fDv8eTy3/PH9IH1C/aK9ir3+Pfb+LL5c/op+9r7gvwX/Z/9O/4K/w8AMQFNAl0DbgSLBagGpAdrCPoIWwmhCdYJ+wkSCikKSwp6CrIK7wowC2wLmAu2C7wLmQs8C68KEAp5CewIZwjwB5MHVwc/B0IHSgc4B/cGiQb4BUsFhwS5A+0CKAJpAbEAAQBM/4P+sv0D/ZP8XPxH/FH8f/zL/Br9U/1l/Tf9uvz5+xr7QvqM+RD51vjO+Nz4/PhA+ab5Bvo5+jz6Lvor+jz6avq4+hf7evvj+1/84vxE/XX9if2h/cb9+f1M/tH+fP81AOYAfQHjAQ4CGAIcAhUCAgICAksC6AKwA3wEPgX3BZQG+wYTB9wGZwbgBXwFWwVyBagF8AVPBrYG+QbxBqAGIwaaBRsFtARiBB0E5wPUA+ID6gO5A0YDvQJFAtkBZwH0AJUAUAAjAAcA4v+Q/xL/kf4f/qn9HP2H/Ab8qPty+1z7Rvsg+/P60/q9+qb6ivpq+k36QvpI+kv6QvpK+n360Poo+3r7xfsL/E78ivyq/KL8hfxt/F38UvxC/CX8GfxM/Nn8nv1s/ir/1/9zABQBuQFGAqIC3QIgA24DvAP+AzUEbwS5BAsFPwVDBTsFPgVDBT4FPQVIBWQFoQX8BUYGWgZaBn0GywYsB5EH9QdoCAsJ4AmxCkALfguEC4MLuAssDJ8M0gzTDL4MdwzcCwEL+wnKCIsHfgaxBRAFqgSuBBMFpQU9BroG7gbABj8GeQV+BHwDpAL0AVABogC//4P+Cf2W+zT6vfgz99b13vRb9EH0XPRk9Ef0IPT9873zQPOD8qLx0/A+8NHvfe9l76TvCfBV8HTwXPAI8JzvVu847x3vJO+N71XwRfE+8jbzHfQG9R72Uvdg+DP58fmv+nT7UvxD/R3+yv5k/+3/SwCOAOEARwGtASMCwwKHA2EEVwVTBiwH3weHCCMJoQkKCl8KhApvCjgK6wl/CQUJkQgfCK4HWQcsBxAH9AbhBssGmQZIBugFbgXRBCYEeAPCAhICiAEbAaIACwBp/8v+Ov7F/WD97Pxj/Ob7kftp+1v7Pfvm+nD6E/rr+eT57vn++RD6Mfp2+s369PrQ+oX6Nfrg+Zb5cfly+Yv50PlP+vL6oftY/An9mf0L/oL+DP+g/0YAAQGxATcCmALtAi0DPAMQA64CMgLjAQIClAJXAxkE2QSrBYUGOweoB8AHlgdRBx0HEgcuB2YHuQccCHYIrwi/CJkIKQhvB4wGpAXMBB4EtQOVA5sDqwO4A7cDpgOEA0gD2AIzAowBFwHXAKUAYwAPAK7/TP/o/nj+6/0//Yn86ftz+yz7Bvvr+s76ufq2+sT6z/rJ+rb6ofqU+or6ePpc+kP6Ovo7+jn6Pvpm+r36J/uE+9X7KvyO/PP8Rf15/Z/9zf0N/lb+pP73/kj/lP/V/wsAOABtAKwA4wACASIBbwHlAVsCvwIbA34D4QNEBKIE5QQDBQ8FJgVCBVAFTAU4BR0FDwUjBUgFWwVFBRMF2QSdBGQENQQWBA4EKARgBJkExATwBCgFTQU+BQMFwASIBFwEUQR1BLsEFwWMBRYGnQYQB3YHzQf6B/IHxAd5BwYHZAanBeYEKgR7A+YCdwI8AksCowIlA6MDBAQ3BCsE2gNRA6YC5gEZAU4Ai//M/gv+U/2s/An8VPuU+t/5PPm2+GH4PPgh+PX3wveU91n3+/Z49t31NvWg9DP08PPJ88zz+/NA9IL0s/TC9Kj0ffRZ9Db0FPQS9EP0nPQQ9az1d/Zp93n4lPmZ+nf7Pfzx/IT9/f1r/rz+4P70/hj/QP9U/2L/e/+Y/87/RAD6AMMBgwJCAwQExwR9BREGcgalBsAGxQarBnkGMgbQBU8FwgQ5BL8DWQP+AqMCUgIhAg4CBgL5AdcBjAESAX8A4f81/5D+Ev6//Yj9ef2j/d/99f3q/dj9rv1O/c78TvzN+0v74PqZ+mP6Q/pN+m/6fvqB+pj6yPoA+z77gvvH+xv8kvwU/YX98/1y/u3+QP+D/93/UADKAEABrAERAngC3QItA2QDkAO9A+sDHQRUBIoEywQnBZIF7gUzBnYGsgbcBgQHQQeOB9wHJQhhCIYIjwh+CEoI7gd8BwcHmAY+BgwGBwYTBhcG/gW3BUIFrAT6AyYDSQKcAT0BFwELAQkBCQH7AM4AcgDd/wn/Ev4h/U38ofsq+/D65Pr1+hD7Ivsb++/6oPow+rn5Xfkb+d34sfjD+BX5b/m2+QD6VPqa+r/6zvrS+tX63Prp+v76MPuS+xr8rfw4/bD9C/5R/o3+tv7B/sD+3f4y/7P/QQDIAEsBzAFFAq4CBAM8A0YDMAMoA0EDcAOwA/4DQwR1BKcE5gQVBSEFHgUbBRsFHwUuBToFLgUVBQMF+gTjBLEEcQRCBDQELgQVBPID3wPZA9IDxQOqA3UDJQPEAlcC5gGIAT0B9gDEAMMA3wD0ABUBYAG4AfQBKgJ6AtkCOAOgAwUEWAShBO8EKgUzBQoFugRKBNMDbAMQA7wCkQKXAqwCtgK9ArkCjAI0Ar4BMAGfADMA9f/N/7X/wf/n/wIAEgAiABMAvP8p/3/+0f0r/aH8MfzF+1/7Gfv5+tn6l/ol+pP5/vh4+Pb3efca9/b2/PYT90D3j/fn9yn4Tvhe+GL4Z/h1+IT4mfjL+Br5bfnC+ST6fPqy+tj6Bvsn+yn7M/tf+4/7w/sa/Iz84PwV/Vv9tP0E/kb+i/7K/gX/TP+b/+b/NgCKAMgA6QAGARsBEgH0ANwAugCEAFkASwA0AAsA+v8OACIAHgALAPv/9v/1/9//rv+F/3b/Xf8h/+f+xv6f/mj+Sf5O/lT+Sf5K/m/+p/7N/sr+qf6H/mX+N/4U/ib+av60/vj+Sf+d/9z/+//+/9n/kP9B/xL/FP9G/6b/NgDxAMABggIkA6YDDARSBHIEbwRbBFkEjQToBEsFogXyBTAGUwZgBl0GPwYLBtAFoQWBBXQFcwV5BYkFqwXNBdoF0gW4BYUFPAX8BNQEuwSqBKIEmgSMBHIETAQTBMMDTAOfAtcBKAGcABQAjf8u//j+zf6d/oH+df5W/g3+rf1G/dj8ZPzz+5X7Uvsq+yj7U/uZ+9j7DPxQ/Kf86fz2/OL8yvyr/Hv8UvxR/HH8kvyr/Mv8//w6/WP9eP2H/af95v06/pv+B/95/+r/YwDrAGMBowGrAZ8BjAFxAWEBbQGGAaEB3AFHAsMCKANsA54DugOvA24DBwOnAmMCLwIRAicCawK2AgUDdgPxAzAEJwT/A8oDdwMIA5ACIwLVAbEBmAF6AWEBSwETAbsAaAAmAN3/m/+A/4L/gf98/37/f/9u/z7/5f5x/vv9gv0B/ZX8WPw2/Bj8GvxP/If8nfyh/KX8mvx8/Fn8MvwI/Pb7DfxA/If86/xm/er9ev4Y/7H/MwClAAwBYwGqAeYBCQILAgsCIwJLAnECjQKoAtgCMwO1A0cE0wRSBb4FDwZBBk4GOAYSBvAF1wW6BZgFhwWZBcYF8QUJBhoGMgZABjAGEAb3BeUFyAWZBVsFBgWaBBwEiAPZAiECfQEAAakAZgAxAAYA6//Z/8f/qP9r/wL/e/72/X799vxT/Kf7D/uO+hb6l/kT+Z/4TvgO+MT3dfc99x73Avfa9qr2d/ZA9gn22PWp9Xz1ZfV79bj1/vU/9or25PY493P3n/fD98/3ufeM91L3FPfl9tf27vYk92/3yfcs+Jf4B/lr+br5APpQ+qz6E/t9++v7Yvzj/GX93/1S/rf+Df9o/97/ZQDrAHEB+gF/AvMCXQO9AwEEIAQpBDUEUQSEBMMEBgVZBcMFNgaoBhoHgQfGB+4HFQg2CEMIRghQCFQITQhGCEEINggrCCYIEQjsB9cH1Qe7B4gHZwdfB00HJQf5BsoGkwZYBh8G5QW1BZMFcgVKBSQF/ATABHgEPgQBBKQDMgPIAl4C7AGAAR4BtABHAPT/uf98/0D/E//z/tH+r/6M/lz+I/7t/a79Vv32/Kn8b/w//B78EPwI/Af8H/xO/HT8f/yB/JL8r/zM/Oz8EP0w/UL9S/1T/V/9aP1k/Vf9Vf1r/ZT9wf33/TD+Y/6K/rb+5P75/un+zf7B/sb+0P7k/gf/Mf9X/3b/l/+7/9n/6f/0/wgAJQBBAGEAiQCvAM4A7gAQASEBHgEPAfoA3QDKANYA/wAuAVgBgQGpAdAB6wHpAcMBjAFPAQwBwgCFAF8ARAAoABkAIAAyADcALgAfAAkA5P+5/5n/gP9X/yH/+/7q/tT+sv6U/nn+Tv4W/vD96/33/Q3+OP51/rP+8/4//5n/9f9JAJAAxwAAAVsB3QFmAuACVQPNA0MEtgQpBYEFnQWHBWoFXgVYBVUFVgVaBWgFlgXrBUoGmAbUBv4GEgccBygHKAcJB+EGywa4Bo0GTQYKBskFegUYBbEEUQQABLUDbAMrA+cChwIRAp8BMAGaANX/Ev91/vr9lP1D/fj8nvw+/Oj7lfs2+8H6N/qp+TH51Ph2+Bf40fee91H34/Z79h72qvUm9cv0qfSg9Kn02PQj9Vv1d/WI9Yv1afUl9eL0tvSn9Lz0AvWD9Tf2+fah9zH4vPg5+Y35tfnL+dX5yvnD+ev5Q/qa+tz6JvuO+//7Xfyr/Pz8Vf2w/Rr+of48/8n/OACgAAUBSAFZAVgBYQFuAXoBpAEOAqsCWQMCBKgEQwXJBTkGiQa0BrcGnAZzBlIGRAZDBkEGQQZKBlMGVQZZBmIGZAZXBksGSgZJBkMGPAYwBhEG1wWSBVMFGgXkBLoEpwSrBLgEywTfBOoE4wTMBK0EhARBBOYDhQMvA+cCrwKMAn8CfAJyAlkCPwIyAiUCBQLXAaYBdgFCARIB7gDMAJcASwD//8L/k/9w/1z/Uf9M/1b/dP+d/7//z//G/6L/bP8t/+P+lf5d/kn+Tv5i/pL+3f4s/27/o//M/+f//P8RAB4AGQAKAPn/6v/c/87/rf9v/yf/+f7m/uH+4/7o/uj+7f4A/xr/IP8K/+L+tP6D/k/+Hf7x/db90f3c/e79Df44/mD+ev6P/p3+pP6o/rH+uf6u/pX+gf50/lr+Of4p/iz+MP43/kr+aP6R/sL+7/4N/x//Jv8W//P+0f6y/oL+Sf4v/jv+Vf50/qv+8v4u/2P/pv/j//n/7f/h/+D/3v/U/7z/kv9m/0//UP9c/2v/eP94/3//ov/X/wcALABOAHoAqgDMANcA3gDwAA0BNwFyAbsBEwKIAhsDvwNnBBAFuwVbBugGWgewB+QH7wfVB6kHfAdaB0oHSgdSB1wHdAerB+gHEggsCDsINAgUCPIH1AefB0kH7wanBl0G+wWRBSwFwgRXBPgDmgMxA8QCWQLmAWoB4ABBAJj/8/5D/n39tvwB/Gj77vqR+kf6DPrY+ZP5QPn7+L/4Zfjo92/3AveB9vL1e/Ub9br0XfQc9P/z/fMF9Bb0PPRp9Ij0rPTr9DX1afWA9ZD1o/W89dX19PUr9n325PZf9/b3q/hn+RH6qvo8+7z7EPxG/Hr8rPzS/PL8I/1p/b79E/5o/sH+If+G/+r/WADOADgBjgHkAT8ChQK3AuMCAAMEAwYDEQMhA0oDmAP0A1MEvgQyBZsF8QUyBlQGUAYpBvIFtAVwBSUF3wSfBGIELQQKBPED1gOzA5QDeANZAzgDFwPmAqECYgI2AgkCzwGUAWIBOAEVAfoA6QDsAP8AHgE8AUsBSgFDAS4BBgHZALIAkAB8AIYAqADdACABagGyAfQBKAJLAl4CYQJWAkoCSwJRAk8CRgJGAkgCOgIgAg8CCgIIAhECJQI9Al8CmwLkAhwDNQM0AyUDCgPdAp4CVAIGAsQBmwGLAYgBiQGVAbIB3AH0AewB1wHAAaQBfgFJAQABsQBxAEAAEgDl/7j/hv9X/yz/Av/W/q3+jf53/mL+RP4g/v391P2b/Vn9Hv3q/LL8hfyA/Jn8rvzC/Oz8G/09/VP9Yv1n/Wb9aP1o/WP9YP1m/XT9ef19/Yz9p/3H/e79Fv45/l7+iv65/uL++v4D/wn/D/8H//f++v4O/yX/RP9t/5r/yf/3/xcALwBOAHAAhACLAJMAmgCQAHgAZgBZAEsAQQBFAFcAcQCJAJ0AuQDcAPYACAEdATMBQAFDAUMBSwFcAWEBUwFQAXEBpAHZARICTQKKAswCHgOFA/gDYQTDBC4FnwUABksGjAbFBuAGwAZvBhoG3AWkBV8FHQX2BOwE8QT8BAwFEAX2BMkEngR5BFAEFgTSA5wDdQNHAwcDvwJhAuQBUgHIAFcA7v9v/+r+kf5e/h/+2P2w/ZX9Wf3+/KP8UvwE/Lf7dPs++wn7w/p5+kX6J/r++b75evlE+Q/50viQ+FX4L/gU+AH4Bvgy+Fr4V/hP+Gf4f/iB+IP4lPir+Mf48vg2+YP5wfnr+Rr6Xfqn+uz6MPt++9L7GvxT/JP84Pwe/T/9U/1p/Yb9qf3P/ff9Jf5b/o/+vP7l/gv/KP9C/2T/i/+p/8H/3f/2/wgAHAAvAEIATwBJADQAMgBRAHIAkgDHAAQBLQFIAWYBhQGhAbgBwQG6AawBoQGaAY4BdwFbAUIBLQEfARkBDgH1ANgAxgDCAL4AvwDWAP0AIgFBAWsBnwHZARECPwJgAn8CowLKAvICFgMvAzsDPQNDA1oDbQNsA3QDmgPRAxYEdwTkBD4FhgXIBfcFDQYTBgMG3AWrBYIFWQU1BSIFGQX9BM0EpASPBH4EbARaBEMEIgT8A9sDwgOgA2QDFwPWApcCRgLlAYsBQgEEAc8AnwB1AFMAOgAiAAIA4//J/5z/WP8U/9f+gv4b/sv9lP1X/RD91vym/Hb8Rfwc/Pv72Pu1+5/7ovut+6r7m/uX+6X7rfug+437gft++4T7l/u9+/b7NPxl/Jb81/wT/Tj9Xf2S/cT97v0h/lv+kP67/uT+B/8j/0D/Yv+B/6f/4P8eAEoAbgCaAMIA3ADrAPMA8gDuAPQACwEqAUEBRwFSAXEBlgGsAbEBqAGXAYwBigGDAXABUwE5ASIBGQEjASgBEAHrANMAwQCmAIkAbABGACIAFQAdACEAFQAAAO3/2f+//6b/lP+J/4r/oP/K/wgAVQCmAPUAQgGKAdgBOQKkAgUDYgPGAysEgAS+BN8E1wSgBFcEHwT0A8ADhwNqA3YDnAPGA+4DFQQoBBkE9APZA80DvgOoA5UDiAN2A1gDNAMCA7ACTQL4AbUBcQEuAf4A5ADYANEAxQC3AKgAhAA1AMr/ZP8H/6L+O/7s/bf9gv1S/Tj9Kf3//Kz8S/zy+5n7QPvv+q76fPpb+kv6O/oh+gP63Pme+VD5DPna+Lv4t/jN+PD4GvlL+Xr5m/mi+Y35avlM+UD5TPl2+bz5Ffpz+s76H/tc+377i/uR+5P7lPui+8T77PsS/D38bPyP/J38oPyc/Jz8qvzH/Of8DP1C/YX9yP0H/jn+Vf5k/nr+m/65/tr+Ef9j/8X/LwCdAAYBZgG4AfUBHQI5AlMCawJ6AocCnAK9AuMCAgMQAxIDFgMZAxMDCgMSAywDUQOGA80DGwRfBJwEzwTrBOcE0wTCBLoEuQTEBOMECAUlBTIFOAU1BSEF/wTVBK8EmASeBMUEAwVNBZQFwwXcBeUF2wWxBXAFLwXxBK0EbwRDBCQEBwTvA9oDvgOMA1IDHwPvArcCeAJFAiAC+wHGAY8BYgEsAd8AjgBNABAAwf9v/zT/E//9/uL+y/6//rD+i/5S/hf+5/27/Yv9WP0o/QH94/zL/LH8l/x+/F38M/wQ/Pv78Pvo++n79fsI/B/8N/xF/EL8PPw7/Dj8NvxL/Hz8tPzs/C/9ev29/fP9I/5P/m3+ff6W/sX+Af83/2r/ov/S//H/DgA3AFMAWABcAHQAjgCkAMoABQE1AUsBWgFvAXwBewF3AW4BWgFAASsBIAEjATEBPwFKAVQBXAFWAT0BIAEFAeIAugCdAJAAgwBtAFMAPAAiAP//1/+q/3//Xf9D/yv/HP8h/zD/M/8o/x7/GP8G/+v+1P7H/r7+uv7H/u/+Kf9j/5T/xP8BAEUAiADaAFMB6QF4Av4CkAMfBIoEzwQCBRwF/wSyBGYEOQQcBP0D7gMIBDsEawSUBMsE/gQKBfYE7QT3BPIE2ATEBL0EqgSABE4EGQTMA2ID9AKPAjgC7AG0AaABqQG3AbABpgGqAaABXgHqAHAA/v+B/wX/sP6A/kr+B/7N/aL9av0U/aT8J/ym+yT7p/o9+vH5u/mF+VD5M/kj+fj4rPhe+CT4+vfe99v37vcQ+Dz4cvim+MD4vfik+Ij4bPhY+FT4bPij+Pn4avnw+Xb65foz+2r7lPuw+7f7s/u7+9r7CPw4/Gn8kvys/Ln8xvza/PL8C/0u/Vz9j/3P/Sj+h/7K/uz+Av8T/xv/JP9C/3X/tP8MAIsAIwG0AS0ClgL2AjwDXwNoA2oDaQNeA1cDbQOcA8MD1QPjA/kDBwT5A+ED1QPcA+wDCQQ9BIkE0AT9BBQFHAUQBd8EnQRmBEEEJQQfBD4EegS4BOUE+QT9BPQE1gScBGAEQQQ8BD4EVASHBL8E6QQPBS4FLQUABcUEjwRZBCQE+gPbA78DpgOKA2MDKAPgApUCUwIcAu4BygGwAZ4BjAFyAVEBJQHpAJwAQgDd/3j/Hv/V/qL+iP55/mT+U/5R/lP+Qv4e/vb91v22/ZT9av0//SH9Cf3s/M38uPyd/Gn8K/wC/PL77vv2+w38Mfxd/IP8lvyk/Lb8vPyt/KX8wPzp/BH9Sv2g/fT9Mf5i/o3+rP7C/tn+7/4J/zf/dv+2//b/MQBaAHEAgQCKAHwAZgBfAGwAggCfAM0ABwFAAWMBaQFcAUsBKQH2AMsAtgClAJkAqQDTAPMA/QAHARIBCgHoALkAgwBJAA8A2/+x/5T/f/9q/1r/Vf9W/0v/OP8j/wv/9P7q/u/+/v4Q/x//JP8j/yL/F//z/sL+m/6A/mb+Wf5p/o3+uf71/kT/lf/V/w8AWACyABsBmwEzAtMCcwMYBLYELwV8BacFqAVrBREFzAShBHcEUARKBGUEkgTGBPgEGQUkBSMFHQUWBRIFDgUHBRIFLgU9BScF8QSlBD4EwQM4A7ICPgLuAcIBqQGlAbUByQHSAcwBqwFYAeEAYgDe/1T/3v6O/lT+I/4B/uL9rP1X/ev8Y/zF+yn7nfof+rn5ePlP+Sn5FPkO+fb4tvhc+AD4rPdo9z/3O/dd95b30/cM+Eb4c/h5+Fv4Ofgf+A34FvhZ+ND4XPnw+Y36K/uu+wb8QPxs/In8l/yk/MH86PwP/Tj9av2O/ZX9jP2D/X39fv2M/aX9yf0H/l/+r/7l/hL/Pv9T/0z/O/83/z//U/+D/9f/RQDEAEcBxgE7AqEC8gInA0ADRwNHA0kDVQNuA4oDmQObA50DoAOQA2gDQQMuAyoDNANPA38DvQMDBEIEZQRpBFMEIwTXA4kDTwMvAywDSwN8A6oD2QMTBEUEUQRGBD0EMAQXBAsEKARdBIkEqQTJBO4ECwUNBekEtgSIBF8EMAQIBPMD2gOvA4UDZAM3A/kCxAKbAmcCMAIPAgYCAwL9AfQB4gHIAaMBZwEOAbMAXQACAKn/aP88/xb//P78/gD/+P7w/ur+1v65/qb+lv57/mX+Vf45/gr+1f2W/UH95PyR/E38HvwO/Bf8NPxr/LD84vz7/BH9IP0J/dL8o/yK/IT8mfzO/A/9U/2h/fP9Nf5g/n7+lP6t/tL+9f4T/zv/df+h/7D/s/+x/5//f/9j/07/PP9D/3H/tP/0/ywAWwB6AIEAcQBNABgA2v+Z/2b/Uv9Z/2v/iP+6//P/FwAlADAAMwAiAAsA/v/u/9H/uP+0/7T/of+D/27/W/86/xv/Ef8Z/yX/P/9y/7D/4f/8/wMA+P/a/6T/Xv8R/8f+iv5t/nT+j/61/vH+TP+s/wEATgCaAOMALgGFAekBYwL/Aq4DUQToBIQFCAZOBmgGbQZCBtwFdAUyBfgEsgSGBIgEngSxBMcE3wTqBOQE1ATEBL8EwwS9BLYEwQTPBL8EjgRPBPIDZgPCAi4CtwFYARsBBQESATEBUwFsAXwBhAFvATEB2gB0AAAAhP8Y/8f+hP5D/v39sf1g/QL9iPz3+2378Ppx+vD5kPlZ+Tv5JPkQ+f746fjL+Jz4XPgj+Ar4B/gQ+C74Zvil+Nj4/PgT+RD59fjd+Nz49vgs+YL5+/mL+ib7w/tc/N/8QP2B/aT9rv2o/Z39jf11/V/9TP0u/Qb94vzH/LD8pvyv/MX85/wj/YH95P0v/mD+iv60/sj+r/52/k/+V/6H/sz+I/+P/xQApwA3AbgBKwKOAssC4ALmAu4C5QLNAscC3ALxAvoCCwMoA0IDWgNuA3YDdQOKA8QDCQRCBGMEdAR+BHoEVAQLBL8DjwN2A2cDZgOGA8ADCARRBJMEwwTaBNsEzwTDBLoEtwTDBN0E9QQIBSYFSgVUBUAFKwUlBRwFBwX1BOkE0QSoBHMEMgTmA5kDTQP/ArYCfgJaAj8CJwIYAhMCCgL0AdABnwFOAdoAWQDg/3H/CP+y/nn+Uf40/i7+Ov4//jT+If4R/vz93f25/ZX9cv1O/Sz9Df3t/L38ePwy/P372fvD+8P74/sh/G38tPzn/Av9Jf0o/Qn93/zE/Lf8sPy6/N78Fv1Y/aj9A/5a/pz+yf7v/hj/OP9E/0v/Xf9w/3f/ev9//3T/Wf9E/0D/R/9b/5L/1v8PAD4AcgCfALAAqQCUAGoALgD2/8//uv+w/7n/3v8gAHEAvwD9ACUBNAEyAScBEQHkAK8AiABwAFoAPwAeAPr/2P+9/57/ef9d/1H/UP9U/2b/gf+T/5v/n/+X/3f/RP8H/8f+k/5x/l7+Vf5d/n3+sf73/k//pP/l/xQATACVAOwASQG3AUoC+QKjAzwE2ARzBeUFHwYyBh4GzwVaBe8EmQRFBPYDxAOxA7UDzAPrAwAEDAQaBDMEWASJBLMEygTiBAUFGgUDBckEcwQBBHgD7QJsAvkBowF5AXIBfQGYAcUB/gEpAicC8wGgAT8ByABDAMX/WP/0/p3+Vv4P/rj9Yv0M/aD8GPyP+xD7l/ot+uf5vvmd+Xz5XPk1+f34vviB+E34I/gI+AH4E/g4+GX4kfit+LL4qPig+JT4evhj+HH4pfj0+GH58PmH+gn7dvvO+xD8O/xN/E38TPxU/Ff8T/xI/Ev8Rfwt/BX8D/wS/CD8RPx5/Lv8Df1w/dn9Pf6Q/sb+4f7r/uX+y/60/rz+4f4S/1z/zf9iAAUBpwE5ArECDgNNA3EDiQOhA7ADtAO5A8MDzgPfA/QD+gPsA+cD+QMLBBsEQQR+BLUE2wT/BBsFIQUVBQEF3ASnBHcEXgRZBF4EbQSQBMEE7wQOBSYFPAU/BSsFFgUIBfkE7AT1BA0FGQUWBREFCwX+BO4E1QSjBGkESAQ4BBwE8wPKA5YDTAPzApICKgLDAW8BMwEQAQ4BMAFeAYEBjgF9AUcB6gBqANb/R//G/lT+9f2+/bD9u/3P/eH96f3l/d390v29/af9mP2L/XP9XP1X/VP9Pf0S/d38qfx5/Er8G/z8+wf8PPx6/K384fwm/Wb9iv2X/Z39m/2L/Xn9cv16/Zr91f0Y/kr+cP6e/sv+3/7e/t3+3/7a/tX+3f7t/vv+CP8X/yT/Mf9F/2T/kf+//+P/CwBLAIgApgCuALwAvACVAGAAOQAbAAIAAwAfAEUAcgCmAMsA1wDXAMoAnQBfAC0AAQDH/4f/RP/2/qP+TP7R/Sf9hvwL/Iv77fpw+j/6Qfpr+sj6QPup+wr8dvza/CT9bf3U/Vr+6f5w//H/fQAUAaEBLwLjAqADKgSeBFcFUQY4BxsISAmsCvwLOQ2ADpEPJBBSEFgQNhDODyUPWQ6PDeMMWgzvC5oLQAu8Cg0KTAlzCGsHVwZfBW4EZwN0AsEBLAGEAN//Vv/G/gL+F/0m/Cv7DvrQ+Kr3w/YK9mH14/S39LH0kfRd9D30DvSa8wjzoPJf8hby0PG38b3xvPG78ebxOvKP8tLyFPNh87jzJPS49HL1OfYR9xX4TPmZ+uL7Iv1l/p//twChAWkCHgOzAyQEjgQUBbMFRQbABjgHvAdECLAI6AjiCKwIXQj2B3gH7wZlBtsFSQWxBCQEsANLA9sCVALAAR4BYwCd/+v+UP67/Tz97/zO/L38rfyk/KH8m/x9/Db8x/tK+876V/r6+db55vkK+jX6cvqt+r/6rPqW+or6bfo9+iz6Xvq++jP70Pul/Iz9VP77/pX/IQCSAPMAXQHZAXACIwP3A/EEDQYuBzsIHwnPCTUKVwpWCkQKHArtCdoJ7AkUCjgKQgooCuwJignpCAoIHAdBBnwF2ARkBA8ExQOSA3UDTAP9Ao4C/AFKAZIA3P8Y/2D+6f2o/Wv9Pf0//Un9I/3o/LX8b/wF/KT7Z/s6+xX7A/v++v/6Dvsh+x/7BfvP+nD6BPrG+bn5tPnG+SP6w/p1+yn85Pyd/VT+BP+Q/+n/NwCUAOcAJwF1AdgBNQKTAg8DlwMNBHcE1wQWBToFWQVjBToF/ATUBMAEnwRtBDME+APGA50DYgMDA5sCRAL2AZ4BPgHdAHYACgCp/17/If/j/qT+b/5C/gr+xv2L/WH9OP0L/e388PwN/TD9Vf2E/bX91v3P/Z/9Wf0P/cj8hfxb/GL8qPwS/X393P00/nL+gP5i/jj+CP7L/ZL9eP19/Zb9x/0N/lT+f/6F/nT+YP5R/jj+Fv4Q/kb+rv4q/7n/VQDfAEABgwGnAZwBawE0AQ8B7wDSAM4A/gBZAdMBcQI9AyEE+wTHBaAGiQd4CH4JtgocDKENOw/ZEFESgBNPFJQUNhRCE9oRDRD8De4LEwpnCOQGpwXMBDEEjQOwApYBUgDb/if9Xfu++WH4Tvee9l72avae9vP2UveJ9333O/fK9h72QvVh9KvzO/MK8/fy+PIS8y7zF/PA8j3ylfHQ8BTwi+9D71Hv1u/L8APyafP59Jn2IviH+dL6C/w5/Wn+o//5AHICAwSgBU0H9whsCpYLegwCDQkNqAwNDDoLIQrpCMcHvAbDBeIEHARgA7QCGgJ+AdoAOgCc//3+fv42/gz+7P3w/Rf+Of5C/kj+Qf4C/or9/Pxg/LD7/fpc+s75V/n6+Kv4XfgL+Kf3I/eB9sv1CPVL9MPzhvOX8w/0FfWU9lj4S/pk/HP+PwDHARgDGgTSBHkFOQYKB+AH1AjkCeQKsAs9DHEMOAycC78KtQmZCJkH1AZTBhkGLgaDBu0GPgdjB10HNgfrBnsGDgbhBQQGWAbVBowHYAgICWgJkglxCcgIjQf/BVsEuAItAdz/3/40/sD9W/3t/Gv8xPvq+u/5BPlG+Mj3nvfW92f4QPlZ+pX7x/zH/Yn+E/9t/6D/sv+0/8n/AwBEAGsAcQBSAPb/Tv9t/m39Vfwt+xn6QvnE+Kj48vid+Yz6mfu7/Oz9Cv/k/4QADQGSAQwCiQIXA6UDKgSuBCcFdwWYBZAFVAXZBDoEmAPrAikCaQHHAEYA3P97/xz/zv6i/pD+kf6s/uD+F/9Q/6L/CgBlALoAKgGqARgCdQLYAjMDawN+A2sDIQOmAhECbgG6APf/Nv+B/uH9Wv3X/FT83Pt3+w37mfo4+gD66/n++Uz60/qH+2L8W/1J/gT/hv/R/9b/k/8l/7b+Xf4j/gr+Dv4s/k/+YP5O/hP+qf0L/Uf8gvvf+nb6WfqP+hf76Pvx/BP+Jf8GAKUABgE0AT0BMgEkASMBRAGXASMC3AKzA6UEoQWKBk8HBAi3CFQJzAlQCiQLWgzRDXMPMRHgEkAUGhVMFb8UcROCETEPzgyeCsUIVAddBuMFvwW1BZEFIgVABOQCJAEi/xD9Pvvh+fr4hfiJ+Oj4WPmg+ar5W/ml+K/3qvaY9Xj0dPO58kXyDPIC8hPyI/Ii8vfxhPHQ8Bbwhu8v7xrvYO8U8D7xzfKT9GP2Nfj++Yv7xPzM/cH+l/9WAC0BLAI4A0gEbgWbBqUHdQgECUIJJAm2CAgIIwclBjQFYASpAwwDjwI3AgMC6QHQAakBawEYAbgAVgDv/3z/Cv+u/mf+KP7o/Zz9OP24/CT8f/u++uH5/Pgj+Fn3nPb19Xz1S/Vj9bD1HPaW9gT3XPeq9+v3D/gl+GP46vi1+cb6LPzh/cf/tAF6A+cE6QWQBtwGzAaSBn0GqgYLB5cHXAhMCT8KCwuRC7wLjQsVC2wKrgkECZYIgAjQCHAJKwrcCnkL7wsFDKQL7Qr/CeEIsgepBtgFLgW7BIcEUQTLAwIDJAIiAdL/WP73/Mr7yPoS+s758/la+uP6efsB/Fz8dfxQ/P37jfsd+9363foE+0/73/uu/HH9+/1c/pv+mv5d/gb+oP0u/d/83PwL/T/9fP3S/SX+Q/4l/uP9nf1q/VP9Yv2t/U/+QP9hAIkBlQJ2AyEEgwSFBCwEpgMWA4IC8QF/AUMBNgFEAWABhwGwAbYBiQEyAc4AbAASANX/x//k/x8AcADFAA4BSQGDAbUB1QHpAecBwAF3ASYB0QBrAPT/gP8b/8j+fv42/vv9zv2V/UH96vyd/EP82PuG+3H7iPu5+wz8ePzg/Dj9fv2h/ZT9af0t/eb8uPzF/AT9Vv2//UH+r/7j/uL+vv5t/vD9Xv3N/FH8CvwM/EP8ovw//Rv+Cf/V/3YA9ABIAXEBgwGaAdUBPgLJAmQDEATOBHUFywXCBXQF8AQoBCsDHgIZAS4AjP9Y/4j/7P94AEABRAJfA3kEogXuBkgIqQk3CxgNLA8vEQoTuhQLFq4WgxaHFbETDxH1DbQKegd3BPMBGwDX/gr+sP23/d/91/18/d/8H/xO+4T68/nG+fT5ZvoF+7D7OvyH/IT8EPwf+9T5UPie9tf0LvPC8ZnwvO8l77PuUe4B7qztRe367AHtVe3z7QTvmfCL8sP0Rffp+Wn8tf7aAKoCAQT8BL0FKAYtBvkFvAVvBf8EewQCBJwDSwMRA+oCywKnAoICZgJHAhoC+wEYAm4C1QJKA+gDqARYBdUFIAYuBuQFNQUuBOwCigEdAL7+fv1n/HL7mPrP+QT5M/hc92/2W/VD9Gfz7PLQ8hzz4vMl9dP2tPhv+sv70/yY/f797f2X/UX9Iv1D/bn9eP5l/2sAbQE3AqwC1QLEAoMCKQLwARQCtgLKAykFvAaBCFAK3gv3DIsNnQ05DX8MlAuiCuAJgAl/CbcJFQqOCvYKFAvLCh0KHAnjB4IGHAXsAycDywKuArICzQLpAu8CzgJwAswBCwFaALr/Hv+i/mH+Vf5a/mD+Xf4+/vb9gf3m/C78afu++lH6MfpP+qb6Ofv0+7D8Vf3Z/Sj+Pf4p/vP9nP0//Qj9A/0j/V79nP24/bX9rf2P/UH96vy9/Lf8z/wm/cH9fv5G/xsA4QB7AfIBTQJyAmUCSgIrAvYBtwF+AUsBJgEgAScBGQEKAQ4B/gC+AG8AMwD+/83/sf+m/67/5/9ZANYARQHCAVYC4gJNA4oDfwMmA5QC2AH3AAoANP98/uH9dP0z/Q799/zc/Kj8U/z1+5v7Svsh+0j7wvt5/GD9Yf5R/wwAiQC4AIoAFgB+/9r+SP7p/cr91f3y/Qv+A/7H/WH93PxA/J77FPu/+r76Jvvh+8P8uv3O/u3/4ACMAfUBJAIlAhYCCwIIAiQChwImA7cD/gP/A8UDRQNrAjkB0P9l/jD9VPzV+7H7+Pux/Mr9H/+SAA0CjAMWBa4GOwi2CTELxgxyDh8QyBFRE38UIxVJFfEUzxOoEcAOiwtDCAAFBQKh/wH+Pv1i/Tr+Yv+SAKwBjALtArACBQJHAbUAUQANAP7/OwCXAMIAlQD0/73+7vzC+lz4vvUR87Pw5u6t7QDt1uwS7ZPtNu7L7jjvn+8f8LjwgvGz8k30I/Y6+KH6FP0l/7gA2QFwAlwCuwHAAIr/Pf4L/SP8k/tO+0n7jfsq/Az9Df4s/2YAkwGbAqADsgSdBU4G8AaRBxAIZwikCLcIhQgMCEQHHga3BDUDkAHT/z7++/zp+/76W/r4+az5bflI+SP58PjK+Ln4rviu+Nv4Qvnr+dj67/sG/QH+vv4L/9j+Pf5A/eT7XPry+M/3GPf29nP3bfjI+WT7Af1v/p7/iAAqAbcBaQJSA3oE+AW4B3sJFwt3DGMNqA1SDYEMRQvICUkI+gYBBokFkAXnBX8GXgdLCPcITQlbCSYJ0QiPCHIIewjWCJMJbwomC6wL3Qt2C2oK5ggFB+QEvgK9AOX+Vv1E/JP7AfuN+k76Ivrl+Zz5Wvk3+Wn5EPoM+yv8aP26/u3/0gBRAVYB4gAQAPf+nP0c/KH6Sfkx+HL3DPfq9gv3Y/fM9zL4sPhK+ez5pvqv+wP9Z/7N/0MBtgL8A/sEpgXwBeMFlQX9BBEE8wLeAeAA7/8K/0T+v/2P/a/9AP51/hr/5P+hADIBqgEdAo4C+wJxA/0DmwQ6BckFNgZmBkcGzwUABeUDiQL9AGf/7P2k/Jv76PqP+nP6fvq4+iL7lPvx+038v/xB/c79c/4r/+L/nABVAe8BQwJDAucBHwH1/47+Hv3T+8f6Cfqo+cL5SPr0+on7+ftI/GL8Sfwd/AX8JPyW/GH9cP6u//oAGwLnAlsDdAMdA2ECbQFqAIf/+f7S/vD+Rv/Z/4gAFAFlAX4BSwHEABAAXf/H/mj+T/53/t/+lP98AGgBVwJgA2sEWgVGBkoHXAh2CZsKswumDJENjg6ED0wQ3hAyETMR2BAGEJMOhgwlCqMHGgXLAgwBCADL/2MAsgFoAy8FuQamB74HFwfnBVcEoAIQAdj/Bf+M/kL+2/04/VP8AvsZ+b/2R/Tk8bfv/u3j7HDspexz7Z7u4u8J8eHxUPJ38pXyvPL98oHzWfRp9Zv26fcw+TL6z/oC+8r6QfqX+eD4LPip95L3+/fO+PX5VPvR/G3+FQCkARIDewTjBSUHLQgDCaEJ9An6CcQJYAnZCDsIhAe2BtgF4wTGA4kCSwEeABD/P/67/X39hP3c/XP+G/+x/yUAaABsACMAlP/b/hv+Zf2//EH8EPwp/Fz8cfxE/Mb79frV+WX4uvYM9abzx/KP8hTzWPRF9qD4Gvtv/Xr/FgEVAmsCTwIVAvYBBAJKAtgCtQPGBMgFeAa0BnIGvAW1BJoDoQIBAu8BlgLzA+cFSgjfClgNZg/UEJARshFcEaQQoA+LDrkNVg1NDWINSw3SDPALqQrkCJ4GGAStAab/Mv50/Wz9/P31/iMASwE9AtkC/QKkAvwBPgGFAOf/e/8y/+L+df7m/RX93/tJ+m34bPZ19L3yY/F18ArwLPDV8PnxcvMB9YH2/vd6+cT6wPuO/FT9EP68/k7/tv/6/zoAfgCbAHYAIQCw/zj/v/4+/r39bf1z/bP9FP7B/uL/SwHMAmEE+QVoB4sIVwm7CbIJXAnKCBYIcAf3BpIGKgbSBYYFEgVnBJEDigJWASUAD/8L/jr93fzi/An9Rv2w/Tb+sv4L/yT//P7B/or+Of7P/X79SP0N/d38yPyd/DX8s/sg+1j6evnQ+GL4Ffj/9z/4yfiP+XP6Nfu8+zH8hfx7/DL8Efwt/GX80/yU/YP+g/+WAI0BKAJ9ArACqgJjAhgC6QHHAb8B1wH1ASACeALVAvoCDgNBA1EDCQOsAnACLgLVAYwBZAFhAaoBOwLqAr8DzQTrBfMGBggdCf8JqQpBC68L6QtTDCoNHg7fDnUP4g/8D6IPqQ7mDIYK/QeIBUkDigGEACkAggCvAWkDMAXKBhIIrwh3CKcHcgbkBDkDwAGBAGb/Zv5k/Tz88fp6+az3kfWL88PxLfDi7hbute2i7fvtyu7M78vwuPF98hXznPMa9Hj0u/Tu9P/08PTw9AP18/S39H30TfQf9Aj0FfQ19HL09fS+9cr2Lvj4+QP8MP51ALECyASxBk8IbAkDCjYKAgpeCXYIegd1BoAFvwQ3BOADywPwAxQECwTqA8cDrgOjA6sDzAMrBN4EsgVvBhoHsQfvB6AH1QarBSgEXwJqAHP+rvxK+z36X/ms+CH4mvf39jX2WfVz9LTzSPM385zzs/R99rn4Hvt5/Y3/GwH4Af4BKQG+/xz+hvwq+0T69/k4+u368/sP/Qv+0/5b/6f/7P9xAFIBlgJjBMoGkglgDPEOGBGpEoITjRPQEo4RIxDKDpQNnQwGDNYL8gstDEQM+AtVC40KqwmsCL8HOQdHB9kHzwj8CTQLQQzmDOYMMQzeCgIJvgZZBBgCCgAj/nP8Bvu6+W34FPex9VL0E/MW8mHxBfEa8ZfxWfJM82v0kfWa9nf3E/hZ+Fj4KfjH9yX3Zfat9QX1ffQy9Cr0Z/T59NT1yfbD99T46vna+qT7cvxU/VH+eP/JAEIC8gPQBaAHMQlzCkcLfwsbC0EK/AhvB+wFtgTPA0EDKgOBAxMErQQsBW0FcgU8BbsE8gMqA6YCZwJnArACKQObA+oDBAS/AwYD9QGxAFr/Iv4u/Xj89/vC+937F/w8/Cz8zfse+zf6JvkB+Av3jfaW9hf3GPiQ+TH7pvy//V/+fP4h/nj9pvzW+0D7Gft8+2H8lf3Q/un/xgBBATYBvQAdAIT/Ef/r/j3/CAAiAVECXgMdBH0EhwRGBMQDFwNxAvwBvgGpAbYB5QE0AogCtwK8AsUC9gJMA7kDVAQnBRsGJgdGCFkJLQqzChALcgsDDM8MuA2VDmEPFxCKEIgQ9A+6DuwM2grUCAsHsAUFBRQFvAXqBoIIEwoYC1ILuwpcCV0HDgWyApAA7v7h/VD9IP0t/SP9uPzl+6L61Pib9l30WPKd8E/vmu5/7uHuj+828J7wyPCy8DTwX++P7vztnO117ZvtBu6g7lXv+O9R8FrwL/De74XvXu+L7x3wP/Ec84T1JPjR+mz9xf+zAR0D5QMVBO0DjQPwAjMClAEuAQUBKgGfAUYCGgMsBF8FdQZOB+0HYAiyCOMI5wjOCMwIAQlZCb0JHQpjCnYKTwrZCe4IkQfyBTgEdwLSAHL/ZP6s/Un9J/0j/R79+/yh/BL8Zvuy+hX6tvmu+RD66fou/J796f7V/zUA4f/O/hj97fqV+HL24vQp9Fz0aPUK9wP5IfsU/Yb+Uv+S/3r/SP9E/6v/qABWApQEBwdRCTQLgQwLDb4MqQsFCkgI9AZFBkEG9gZmCFIKVgwlDoAPMxA3ELYP4Q7zDTsN9Qw3De8N3A6uDzQQVhDrD8EO6wykCiwIzQXkA5UCwAFAAQsBAAHqAJkA6P/J/lz92vtn+hX5Afg+98z2l/aG9nP2UPYf9sv1KfU59CzzKfJA8Xbw1e9l7zbvWO/K73nwV/FL8kPzRPRW9WL2SfcN+Mb4c/kU+rn6d/tW/Ez9VP5n/3sAhgF5AkMDzQMLBA4E/wP/AxAEPQSoBF4FUAZfB3YIbgkcCmkKWwr+CVcJdgiRB+MGhQZiBmoGmgbeBhMHGQfTBioGJAXuA7oCoQGzAAEAoP+W/87/DQAWANb/UP9w/iv9qPss+u34Efiy98/3YfhV+Xz6jvtH/H78Jvxl+3L6ZflL+F/38fYV97P3sPjd+e/6t/s1/HH8ZPwe/L/7dftx+9b7nvyq/eb+MQBEAewBJQL4AW0BoQC7/+P+SP4U/kb+w/5+/2IARAH+AZEC/AJFA5cDIATcBMQF8gZvCA4KlgvoDOYNiA7tDkMPlg/ZDwwQQxCXEAIRPRH3ECYQ7w54De8LmQqfCQUJ5gh7CcEKXgziDfsOcA8oDyoOhwxpCh0I+QU4BP4CVQIYAgYC5wGBAYgAy/5l/JL5j/af8xLxLe8Z7tntR+4o7zPwGPGO8Xjx6vD076zuWe1O7JjrIOvu6hnrc+um64DrDetp6qvp9+h46F7oz+jp6a/rEe7M8JDzK/aR+KD6Ivz//Fj9U/0W/cb8gPxQ/FD8pvxQ/Sj+H/9CAI4B5wIxBFwFbAZ1B3gIWgkQCrkKZAv7C20MzAwtDYgN1g0TDi8OEg6tDQMNLwxPC14KTAkyCEwHsAZHBvwFvwVpBeUESASrAwoDZQLWAYABewHZAYYCRgPZAxkE3AMBA4sBn/9h/Qn78/h699T2A/fY9xD5efrx+y39zf2p/dz8oPs++gz5RvgU+J/47vm2+5L9S/+4AKMB7gG7AT4BoQAeAP7/dQCBAewCbgTQBfcGywcqCBEIpgccB6YGlAYRBwEIJwloCrIL3AyfDcQNPQ00DPsKyQmxCMAHGgfeBg0HlAdGCOEILAkZCagIyQeGBv4ESAN+AdP/gv6V/fL8hfxM/ED8PvwS/J775/oJ+gn58Pfn9g/2YvXe9Jv0nvS99NX03fTI9Ib0N/QK9AX0GfRW9N30tvXG9uD30viJ+Rj6gPqu+pf6WPoT+vX5Jvqo+mT7Tvxo/Z3+2P8aAVECQwPiA10EzQQiBUIFMgUABc0EwwTvBD4FrgU/BtQGWQfWBzYISQj/B3gH0wYjBpAFMQUCBQcFRgWkBfQFCwbDBQAFzwNdAtAAWP82/of9Of1K/c/9nf5b/8b/x/9U/4H+eP1Y/C/7M/qt+az5Cvqh+lb7BvyC/Jj8Pvya++X6NPqW+Tv5UPm++V76Gfva+2j8mvxv/Pf7SPuJ+uP5ePln+dD5o/qs+7D8kP1P/u3+YP+c/6z/x/8pAOkA9QEzA4cE0wX2BtMHXwihCLwI4QgwCb0JnArTC0kNwg7zD6YQuxAxEBoPng0ODMwKHgofCucKgQy1Dv0Q3RIKFGgU4xNzEigQTQ14CjIIpQbGBZUFBgbGBl0HdQfiBpsFpAMfAVv+0PvS+XH4rveg9x74qvjR+HD4ivcg9kX0GfLL77vtV+zH69rrV+wG7ajtAO7o7UXtEuyC6ujok+fO5tLmpOcY6QbrMO1E7wnxafI18zbzivKd8bzwBfCL72Dvk+8y8DnxgfLo82D1y/YX+GX53fpp/M/9/v4SACABHwLwAnwD3ANNBOYEkAVCBhAH+wflCK0JNgp1CoQKdgpECvgJvgm5Ce0JUwrnCo4LIwyVDO0MLg1WDWYNbA2NDdwNQQ6QDrUOqg5dDrENjwwDCzsJiQcmBjEFxATsBIsFbgZnB0sI1gjCCPsHowb3BC0DZAHX/9H+eP6n/jX/DAAEAc8BLwIVApIBzADo/wL/MP6a/Vz9Zf2b/eb9Hv4a/tv9dv0C/Zz8Zfx0/NL8hP1+/pP/ngCFARYCGwKjAd0A7//1/h3+j/1n/bD9Yv5Z/3UAlgF9AvAC7gKIArgBjQBA/wn+BP1N/P77FPyD/Db9Bf69/kX/iP9s//L+Mv5A/Tj8UPu1+mP6UfqB+uT6WfvI+yL8T/xO/DX8Efzl+8f71PsL/FP8l/zQ/P38G/0V/dr8g/xB/B38GfxP/M/8gP1D/hH/7P+8AGYB0AH3AfMB5AHSAbQBiwFlAVABXgGRAdMBIAKQAh8DnwP0AysESgRHBBUEtwNAA9YCmwKcAtkCVQPsA3wE9gRUBXAFLAWQBLEDqwKyAe8AagAgACMAdADwAGUBsAG+AZYBSAHPADAAnP9F/y7/Ov9b/4z/0f8oAGsAYwALAJr/J/+f/gn+lf1Y/T39Kf0a/SH9Rf1q/Wn9SP0d/dT8WfzX+4n7ZvtJ+zL7Svut+1H8CP2m/TH+xP5S/7X/6v8IABgAGwAZAB0AMQBcAJ8A9ABmAQACrAJTA/4DuARgBdgFJgZZBmAGKQbJBXkFcgXSBYMGbweTCNgJ/wrSCzIM/QsbC7cJFAhnBukE2wNpA50DbwSqBQAHIgjNCMoIEwjBBvYE7QIAAXL/ZP7s/Rn+x/6j/2AA0gDaAFwAUP/K/QP8SPrN+Kn36faY9qv2BPd/9/z3TfhM+Pr3dffb9kf2yvVj9SL1MPWJ9ff1T/aC9n72N/at9ev0CvQ685DyCPLM8RTyx/Kp87H02fX79vD3rfgp+WH5Xvky+ff41Pjb+AH5Pvmk+TT61fp2+xL8oPwc/Xz9sv3C/cf94P0Q/kX+jf4A/5D/KwDWAI0BLAKiAvMCGgMfAyEDMANTA7ADVQQRBbkFUAbMBgoHBQfDBkEGlQXxBH8EYQS1BG8FYQZmB1kIDAlwCXgJBgkdCA4HLAaYBVEFaAXsBcQGtAeUCEkJqAmBCdsI7gfsBvcFJQWFBDoEbAQOBd8FsAZwBwEIQwguCMcHPQe7BjYGnwUkBfYEEQVPBZEFvQXQBdcFvAVlBfAEhAQiBNADrAO1A88D4gPjA9QDsQNWA54CnAF7AFL/SP6K/Rj93PzZ/Av9TP12/Xb9Pf3K/Cr8a/ui+vH5dPk5+TH5Qflw+cr5Jvo9+gf6t/lc+ez4a/jv9573j/ei97739fdL+Jf40fgP+Ur5ePmr+eH5C/pK+qv6Dvts++L7Y/zV/EL9sv0M/lP+oP7k/gL/Af/7/gH/Dv8e/z//j/8JAJMAJQG9AUICqgL1AiwDUANhA1QDOgMnAxYDAQP+Av4C4gK7AqICfAJFAiACCgLrAdoB5AHrAegB+gEVAiACHwIWAv8B5wHVAb4BpAGQAXkBYwFgAWIBVQFAAScBBwHlAMAAhgA3AOf/nv9n/1D/V/93/6v/2/8CADUAZABhAC4A5/+B/wb/m/5G/vT9vP3A/fP9RP6j/vn+Nf9b/1//P/8I/7X+P/67/Tb9pvwc/Lj7cPtG+1n7sfss/Lz8W/3//aP+Kf9q/3P/aP9B/+v+f/4i/uz99f06/pb+Bv+a/y8AngD0AEMBgQGrAc0B7wElAn0C6wJhA9YDRQSnBPAE/gTSBJ0EcQQ2BP0D7AMQBFsEwwQuBZYFAgZbBoAGfgZbBv8FcwXjBF0E7AO5A8YD8AMvBIQE1gQXBUIFLAW2BAoEVQOYAtABDgFuAAIAwf+h/6r/0v/o/8T/dv8U/6b+Kv6b/QP9jfxA/Pz7vvub+4j7bftR+zP7Dfv2+vb69frz+v36BPsC+w77GvsC+9H6pfp1+jX69Pm7+Y/5efl8+ZP5wvkC+kr6mPrr+iz7Wvt++5L7l/uc+537o/vH+wX8Tvyp/Bj9ef3C/fr9C/7q/a79b/04/R39Mf1i/bb9OP7S/mH/3/9DAHoAjwCZAJoAmACdALQA5QAxAYEBxwH/AR0CEQLqAbwBmAGKAY0BmQHDAR8CkAL4AlsDsQPlAwUEIAQjBAwE9APcA70DpwOdA5YDpAPMA/UDDwQkBDMEMQQdBPsD0AOgA2IDDAOzAnICTQI3AioCGAIDAu4B0gGqAXoBOAHgAJEAWwAyABIAAwDz/+T/6v/6//L/2P/B/6b/gf9h/0j/M/8p/yv/Mf82/zv/Qv9S/27/hv+Q/5b/o/+2/8f/yf/B/8j/7P8lAGgAqgDjABUBOwFQAV0BbgF4AXUBewGMAZsBtgH0AT4CcgKXAr8C2gLaAscCrQKRAngCYwJVAlECWAJfAmQCZwJjAkwCGwLcAZ4BXgENAa8AWQAVANj/mv9i/0D/Nv82/z7/U/9o/2j/WP9C/xP/sP4x/sL9Z/0W/dj8uvyz/L382/wA/ST9Rv1Y/Un9Iv39/N78uvyU/Hv8evyR/LX85/wq/XD9rf3n/Sb+Wf55/or+lf6e/q7+zP78/jT/af+i/+f/KwBiAJYAxADSAMEAtwC7AMUA1QDsAP0ACQEZASYBGwH9ANYApgB3AFgATgBVAGcAhwC7APMADwENAQUB8wDDAHcAKADo/7b/jf9z/3X/iv+i/77/3//1//P/6f/U/6f/af8n/9/+of5+/mL+OP4g/jz+d/6t/tT+9P4Q/yT/Lv84/0H/Pv8+/1L/cv+L/5j/oP+c/43/df9Z/0H/L/8i/yj/Tf+M/9v/NwCZAOgAIQFDAUUBMwEjAQwB5QDIAMoA3QD3AB4BUwGCAaYBxgHpAfwB7QHGAaQBggFYATYBJwEmATMBUAF7AbAB7gEmAk0CZwJzAmwCVQIyAggC4AG8AY8BYQFEASwBDAHxAOYA1QC0AJAAeQByAG8AZQBWAEoAQQAxAAcAv/9w/zz/F//m/rP+j/5t/kL+Gf71/c39nP1j/S/9Df32/OD81Pza/OT87fz5/AX9D/0Z/R39D/34/Oj82/zU/NT81PzR/Mz8y/zX/Oz8+vwH/Sn9Wv2J/cH9CP5M/oj+xv4B/zr/fv/M/w8ASwCFAL8A9QAnAVABfgGtAcgB1QH2ATECbwKqAu0CNwODA8cD+gMkBE0EYARdBFcEVwRQBDoEFATqA9gD2QPKA60DlQN3A0YDEwPkAqgCYQIeAuQBswGFAVQBLAEbARQB/gDaAJ8ATQD5/6v/WP8H/8b+kf5q/l3+Yf5l/mP+TP4a/t/9of1e/Rv94/yz/Jv8r/zb/Af9Nf1g/YP9pv3R/e/9/f0G/gb+/P36/QX+G/4z/kf+Zv6p/gf/T/98/6b/0v/5/xgAKQAzAE0AdACXALgA5QAbAVQBgwGVAZgBpAG1AbgBugHJAeYBEgI6AkwCVAJoAngCbQJSAjYCIQINAvYB2AHJAccBygHPAdoB0wG5AaMBkQFyAUIBEAHgALoAlQBsAEgANgAsACUAIAAYAAoA+//l/8P/n/9//17/Rf89/zj/MP8u/zb/Pf88/yr/Bv/i/sX+qP6T/ob+d/5t/nX+hP6I/oL+df5g/lX+Xf5k/l7+T/5F/lD+cv6W/rP+1/77/hb/MP9K/1r/Xf9W/0L/Mv86/1X/cv+U/77/5/8NAC8ASwBnAHwAfABxAHgAigCUAJkAowCyAMcA2wDeANsA3QDSALMAjABpAE8AOwAkABAAEgAhACUAIwAqACsAGwAHAPb/1/+p/3X/UP9E/zv/JP8S/xj/If8Y/wf/8v7Z/r7+pP6T/pr+rf6y/rr+3f4N/yn/K/8f/xX/FP8O//n+6f7j/uL+7P4G/yL/Pv9r/6X/2f/9/xQAKgBDAFkAZgB7AJ4AwgDiAAEBGgEtAUgBYQFkAWABZAFwAYIBlwGlAbMB0AH5ARsCNQJQAmMCaAJcAkoCSAJSAkMCHQL7AeYB1AHFAbwBswGoAZsBjAGHAYUBeQFpAWQBWgFDASsBEQHoAMEAqACRAHgAXwBFACQACwD6/+b/x/+b/2z/Rv8j//v+1f6x/oj+Yv5K/jv+L/4t/iv+H/4R/gP+7/3e/dz93f3W/c79xv3B/cT9wv23/bP9uP25/bj9wP3H/cT9x/3c/fz9GP4r/kP+Z/6L/qb+wP7W/tj+zv7G/r7+tv68/sz+2/7w/g//MP9Q/3L/hv+J/4v/lv+n/7X/wf/W////KwBJAGYAkwC8AMwAyQC+ALAApACbAJgAogCwALYAugC/AMMAyQDZAOIA4ADlAPMABAEdAUUBbwGUAa8BuwHAAccByAG6AaQBkAGBAXUBawFjAWgBdQF6AXwBggGDAXsBdQF0AWkBWwFTAVUBVwFbAWkBgwGaAZsBlgGkAb8BywHHAb0BrQGgAZgBiAFsAVABOQEpASEBHAEQAQAB8ADiANoA1ADJALsAtAC2ALoAwQDAALIAnwCLAHYAXgBHACgABgDl/7//mP91/1n/Qf87/0H/RP9I/1b/af91/4D/if+N/43/hv9w/1L/Nv8f/wj/7/7Z/sr+wv67/rH+pf6T/ob+gf56/mf+XP5h/mH+UP48/jD+L/47/kb+S/5T/mL+bv5z/nv+hf6P/pb+m/6W/ob+cv5d/kn+Ov46/kv+Y/59/qT+1P7//iH/RP9j/3b/hf+Q/5H/i/+P/5z/sP/G/9P/2//v/wcABQDs/9v/3f/b/83/xP/K/93/+/8qAGAAjACqAMIAzwDMAL4ArQCbAI8AiQB7AGsAaABpAFoAPAAgAAgA8P/Z/8X/uv+7/8T/yP/O/+H//f8TACAAJAAdAAkA6f/E/53/d/9j/17/WP9P/0v/S/9H/0P/Pf8q/xr/Iv88/0//W/9n/3T/hv+f/7T/vv/G/9D/0//T/+L/BwAwAEsAYgB+AJgArgDGAN0A5wDhANkA1ADRAM0A0ADgAAABJgFGAWoBkgG4Ad8BEQJAAl4CawJzAnsCgQKGAoMCcQJYAlACVwJaAlACTAJaAnMChwKOAoYCeQJxAmoCWQI9Ah4C/wHpAeEB3gHUAcgBxgHMAckBuwGuAaQBkgFzAU4BJwH6AMgAoACLAH4AbABRADMAGAADAPT/4v/I/6T/gP9f/0P/Lf8c/wf/7f7V/r7+pP6G/mv+Vf44/hj++f3g/cr9uf20/bj9uP2u/Z/9k/2G/XH9Vf05/R79C/0D/f/8+fz3/AD9Df0U/Rf9HP0f/Rr9Ev0T/Rz9K/1B/V/9gv2r/dH98P0I/hv+Iv4a/gv+/v3t/db9zf3f/f39IP5R/pX+2P4Q/0X/ef+f/6z/p/+h/6P/qv+w/7b/wf/R/+T//f8YAC8AQABRAFoAVwBWAGoAjQCuAMoA6gAHARsBKwE3ATwBPQFDAUQBPgE7AUcBWgFvAYMBlQGjAbMBxQHJAb4BuwHIAcsBuAGeAZEBlAGcAZ8BlQGLAZMBqQG7Ab8BuAGjAY4BhQGKAYwBhAF6AXgBgAGTAakBtwG8Ab8BxgHTAeIB5wHaAckBxgHBAasBkgGHAYcBhQGDAYUBhQGNAaEBsAGmAZABgQFsAUYBIQEMAQIB+ADuAOEAzgC7AK4AogCWAIgAdQBhAFEAQwAtABEA///u/8//qv+T/4v/g/94/3H/bP9m/1j/RP8s/xD/6P6y/n/+Wv5B/i/+L/5A/lT+Z/5+/o/+j/6B/nX+bf5f/lH+RP44/jL+Pv5W/mj+df6C/oz+jf6K/oP+cv5e/lf+X/5x/oj+of69/tz++/4V/yP/I/8f/xj/Ef8L/wz/Gv87/2P/hP+b/6//wf/U/+H/5//d/8T/rv+i/57/mf+O/4b/hv+Q/5n/lv+K/4D/gf+N/53/rP+v/6z/sP+5/77/tf+l/5P/g/93/3b/fv+J/5b/qv/B/8//0//R/8L/pv+I/3H/XP9B/yn/Jf81/0v/Xv92/5H/rP/F/9z/8f/8/wAABAAKABIAEQAJAAQACQARABoAJwA7AEwAUgBQAFQAYABuAH0AjgCeAK8AwgDeAAMBJQE6AUUBUQFlAXkBiwGcAawBuAG/Ab8BvAG5Ab8BzgHiAfoBEgIhAioCOwJTAmQCbQJ0AnwCfAJ2Am8CZgJYAkwCQwI0AhoC/AHgAdABzwHaAecB7gHuAekB3AHFAakBiAFiATkBFAH2AOEAywCsAIMAWQA2ABQA9P/X/7j/lv98/23/aP9m/2f/Zv9d/0n/LP8N/+/+0P6t/oj+av5V/kb+Nv4r/iX+I/4u/l3+t/4o/5H/1P/V/43/G/+f/ir+tf1A/dX8gvxO/Dz8S/x8/M38NP2l/R3+mf4M/2v/q//G/7H/c/8Z/7r+Yv4V/tT9pv2X/bD97P09/pX+5/4v/3L/vf8GADYARQA7ACMA/f/M/5b/Zf8+/x7/A//s/uP+7P4F/yz/XP+W/9D/DwBXAJsAzQDhANsAvwCQAFMADQDC/3r/RP8o/yr/Rf9q/5H/u//w/ysAXgCEAJ0ArACtAJ4AgwBhAD0AGgD6/+b/4f/u/w0AQgCDALsA3QDvAP8ADgEVAQ4B9gDMAJkAaABDACkAEwAAAPv/DgA4AHAArADqACYBVAFyAX0BcwFWASwBBQHpANkAzwDQAN8A+wAaATQBRwFOAUwBQwE7ATkBOAE0ATABLwE0ATcBMgEmARIB+QDkANcA2QDhAOUA4gDdAOEA7gAHASkBTwFpAXABZAFNASwBBgHeALkAlABsAD8AFgD7/+7/7f/2/wkAIgA5AE4AYQBqAF4APwAYAP3/9v8AAA4AFQAIAOP/sP+F/3H/cv99/4f/if9//2//Xv9Y/1//a/9q/1T/Kf/x/rn+kP5//oT+k/6k/rD+t/63/rX+tf68/sb+0f7h/v3+Kf9Z/4D/mv+l/5//jP93/2j/Xf9I/yf/Af/s/vH+Bv8k/0X/Z/+F/5//vv/c//H/+//2/+f/0v/B/7b/rv+c/3b/R/8q/zT/Vv+A/6b/y//u/xMAPABiAHQAaAA6APX/sP98/13/UP9K/z7/Kv8k/zv/av+h/93/HQBeAJUAtwC5AKIAgABbADMABgDM/4X/Pv8T/xD/Mv9y/77/BwBAAGcAfQCHAJUArwDKANEAvgCPAFAAGQD6//r/BQAHAO//zP/F/+z/LgBpAJUAtQDNAOIA7QDuAOcA1wC8AJcAcwBSADAABgDa/7X/of+w/+f/MAB6ALwA9QAkAVQBgQGcAZsBgwFWARkB2wCgAGcANgAUAAAA+f///xQAMQBWAIcAuQDdAPgAEgEpATkBRAFIAUABIwHoAJYARAAGANn/sv+Z/5H/kf+V/6f/xv/l/wAAGQArACsAFgD6/+z/+/8WABgA9/++/3r/Of8P/wv/GP8l/yz/L/8v/zD/Nv9G/2j/lP+r/5v/dP9S/0X/Sv9Q/z3/B//I/qD+k/6g/sj+/f4v/1H/Yf9h/1//ZP9v/3v/if+J/27/Qf8e/wn/9f7e/s/+0v7s/h3/S/9n/3r/kP+p/87/BAA8AFgAQQD2/5P/Uv9c/6H/8P8qADgAHgD9//3/IwBVAIMArADMAOIA6QDZALwAqwCoAJoAbwArAN3/o/+j/9f/DQAkACYALgBMAHoAoQCzALoAwwDLAMcAuQCmAJcAkwCTAHcANADu/9T/8f84AIwAywDkAN4AxQCcAGwAQAAoACcALwAWAMj/cf9W/5H/AgB6AMMAwgCLAFIAOgBLAIUA3wA+AXUBUAG4AOP/Kv/K/s/+Nv/q/6YAHwFLAUgBMQEJAdAAkQBjAEsAJgDh/6j/uf8mAMoAbgHUAdIBeQEPAdIA1gAIATYBNwEAAZgADACD/z7/UP+J/6T/ff8h/8T+pP7O/iH/ev/A//D/JQCJABcBnwH3AQ0C1wFWAagA6v84/7T+gP6r/hX/hP+p/27/DP/D/pr+gv6L/sv+Mf+U/8n/s/9d//r+vP60/tD+6/70/gj/Rf+U/7//xf+7/6H/af8k//b+7v4E/yf/Q/9V/2H/Yv9h/3j/of+z/5L/W/8v/yH/Qf+N/9r/+P/a/5X/Q//+/tr+5f4f/3D/m/97/zf/CP8H/zH/i/8EAGkAjABjAA0AyP/C//T/MwBnAIUAigCNAKcA1QDwAN0ApgBkADcAMQBGAG4ArQD6ADABPQE2ATIBKgEfARYBEwEaASsBNgE1ASQB/gC8AIMAjwD4AJUBIQJcAiACiAHfAGYAMwBMAKEADAFjAYABUwHyAJMAVAAlAPT/yf+v/7f/9v9vAAQBnQEoAoECdgIAAlABrABDABgACAADAAYA/P+2/zf/w/6S/rD+D/+O/wAASABsAIEAkACkALwA0ADXALgATwCt/xr/xv6j/pX+m/6s/rP+sf7B/vj+S/+U/7H/pf+J/1v/Bv+m/m3+cv6X/sH+z/6p/lT+/P3P/ef9Pf6r/hD/av+z/8n/k/8w/9r+rv6q/rn+vv6z/qL+lv6I/oX+lf6t/rT+qf6M/mT+Uf56/uH+bf/7/2EAegA+ANP/bP84/0r/ff+i/6v/pv+T/3X/a/+T/+j/UACvAN8AywB4AP//hf80/xz/Nf98//X/egDLAMIAZwDJ/xX/n/64/mT/XgA7AawBqwFZAdkARwDU/6L/pf/C//D/JgBIAE8ASQBDAEEAPwA5ADsAZQDNAFcByQHvAaMB/gBdAB0AUwDUAGABvAHBAXgBBgGYAFoAZwCuAP4ANAEyAfEAlgBxALQAQAHDAekBlwEGAZAAXABpALYAOgHEARAC6QFKAXQA4P/r/4kAUgHAAYsB4QBJACYAaQDHAAIB9AChACwAw/+K/6f/KwDkAHABiwE3AbkAdQCnAC4BsQHdAYoBwQDD/+r+bP5j/tX+m/9eAMwAzAB5AAgAt/+c/6j/wv/h/wEAMAB7AM4A9QDaAIgABgBa/6n+JP7t/Q/+cv7d/iX/RP9Q/2D/hf/G/xEAUABtAD0AmP+X/o/91/ys/Cj9Iv42/wsAdgB4ACcApP8X/6/+pP71/l7/kv95/yX/rf49/gT+Dv5a/t/+hP8SAFkATgD+/5D/Kv/g/sb+9v52/xgAngDnANwAbwC0/+/+Z/5O/qn+QP+z/8j/kP9H/zr/kv8qALEA8wDmAJIAFgCj/2X/d//c/2wA2wD3ANwAvwC8AM4A4ADcALcAbwAMALH/m//p/3EA+QBbAXcBPAHKAHIAdQDcAH8BCgIrAtIBLQGXAG8AzgB0Af0BPAIsAtEBQwG+AIEApAARAY4B1wHXAakBcwFQAVMBcwGTAY8BWgHxAHQAJAA3AKkARAHMAfcBrQEaAYUAEwDL/6n/mf9//0v/Af+6/qH+xv4D/zf/YP96/2n/Jf/W/qT+l/6o/sD+wv6c/lL+9v2k/Xn9eP2a/db9FP4X/sL9VP0d/S/9av2i/cL9uv2N/U79Iv06/aD9HP5t/nv+U/4P/uP9/f1Z/sn+F/8b/8j+Sf7s/eL9If55/q7+n/5p/kL+UP6f/i//1/9dAJ8AnwBuADAADwAXADIATQBuAJEApQCfAIEAXwBVAGMAaQBaAFkAgwDZAEkBtAHwAegBsgFyATkBGAEfAU4BjQGzAZABIgGqAIAAyAB0AVMCFANpA0UD0QI/ArgBYgFHAVYBcwF9AV0BGwHvAP4AQgGSAbgBhAEEAX0AKwAhAF4AygApAUYBEQGlADUA/P8UAF8AtADsAPEAwAB7AD4AEADz/+v/4v+5/23/FP+5/mr+RP5f/rn+MP+U/8v/8f8qAHQAtQDrABgBJAH1AJQAIAC9/3//Xv8r/8L+Lv6c/Uz9ff0+/mj/uwDrAZ0CjgLXAdYA9P+D/6L/JwCqANAAZQCF/5f+EP4v/uL+6v/qAIcBpQFrARgB2gDFAMcAtgCCADwA8v+i/1r/Ov9S/5L/0f/k/83/uv/T/xoAjQAmAcQBLwJHAgMCbwG8ADYA/f/0/+D/kf8C/2D+8f3k/Uv+Ev/y/48AvgCbAFsAKAAlAF4AqwDaAMIAWQDD/0b/Df8S/z//dv+O/2j/Ev+z/mr+T/5q/qv+8P4w/2j/i/+M/2f/J//u/u3+M/+e////MQAaAMP/Wv8E/8f+pv6w/tz+Ff9N/3n/g/9n/zz/Iv8p/0r/bf+N/8T/IAB+ALsA4AAKAUIBdAGEAVsBEAHpAB0BnAEpAo4CtwK4AqMCdQInAtsBtQGqAYUBMAHGAHwAewDQAGgBKgL3ApADqQM+A5oCHQL7ATgClwLYAuICuQJjAu0BiQFpAYIBlwFjAdIAFgB9/zb/NP9e/5z/0//r/97/r/98/3D/oP/e//P/0/+O/yX/nf4c/tL91/0V/kz+PP7M/Rj9Tfyt+2v7h/vQ+xH8L/we/O/72Pv9+1j8y/wz/W39bv1R/TL9Hf0Y/Rn9Av26/Ev80vtp+yn7IvtE+3H7kvuq+8/7IPyi/Cz9ov3//Uz+fv6Q/of+af5M/lL+e/6o/sL+zv7T/tf+3f7r/gD/Gv9A/3b/yP8yAKUAEwGCAe8BPAJTAkECIAIGAhACSAKLAqcClgJ5AnQCkgLCAugC/gINAyADNgNXA4oDxgP2AxAECQTuA9sD6QMQBDYETARDBBcE3QOnA3YDTQM7A0EDRAMsA+4CjgIVAqEBVwFTAZYB/QFRAnECXAIpAu8BwQGmAZkBmwGrAasBeAETAZcAHQCw/2L/P/8z/yD/9f61/nX+U/5g/p3+8v49/2X/cf93/37/g/+J/5D/gv9R/xD/1f6l/n3+Wf47/ir+Lf5B/lP+W/5d/mD+af54/of+gP5c/iz+D/4o/nL+wP7f/sH+ev4u/gz+Nv6f/hT/X/9o/zX//f4G/2v//v9kAFgAyf/g/uv9Qf0k/Zn9Zf4m/5X/nf9d/w7/9v4//+T/ygC2AVACSwK9ARABtQDNACQBYgE+Aa0A1/8I/4z+kv4T/9z/qAAzAWkBagFtAZYB6wFYArQCygJ4AskB9AA6ANr/7P9IAK8A6QDYAHUA4P9T/wf/FP9k/8v/IQBaAHYAjgC/ABIBbQGkAZYBQAGyABwAqf9m/z//Jv8T//n+z/6l/pv+0/5E/8H/DAD9/5f/D/+k/oL+rP4T/6T/RQDGAAMBBAHuAO0AGgF6AfkBcALJAgEDIwM0AzoDLwMHA7ICLQKHAeAAWgASABMARwCBAKYAxgAOAZ0BcgJoA0EExATfBLAEaQQvBBYEGwQjBAgEvANLA8cCLAJtAYkAlf+s/u39c/1N/Xr97v2V/kz/6f9WAJ8A0gD4AA0BEwEBAcQASwCm//P+S/69/UP9zfxM/Ln7IPuM+gr6tPmf+cX5A/o9+nj6zvpL++L7f/wP/X79sf2L/f/8I/w6+436M/oP+vT51Pm5+aX5lfmO+aL53/k3+pD6zvrs+v36Iftm+8P7M/y3/EP9sP3b/cv9of14/VD9Gf3N/HX8Mvwn/GD82fyG/VH+Dv+C/4j/O//i/sX+B/+a/00A4gA0AUsBUAFwAcgBUALhAj0DPwPuAnQCCwLiARkCpAJLA9QDJgROBG4EogTxBEoFlAW8BcUFxAXOBf8FawYKB64HHwg7CAYImwcjB8gGpwaxBsIGsQZrBvoFggU3BTgFfQXmBUgGeQZcBvQFbQUBBc4EzgTmBPgE9ATXBKgEbwQnBNEDdQMXA6wCJQKEAdkANwCy/1f/KP8L/+H+lP4r/rz9ZP04/Tv9U/1f/Uz9Hv3f/J/8dPxp/HP8efxc/Aj8dPuv+uD5PPng+NT4Cvlq+dP5Mfp7+rb65foN+zH7UPtj+2v7dvuO+6z7uvuv+5r7kvun+9j7F/xR/IT8vvwK/Vv9m/3H/e79Hf5X/pf+2f4W/0T/W/9R/yn//v4K/3f/OgATAbQB8AHCAU4BygBsAFMAhgDtAF4BogGYAVkBJQE5Aa0BbAI7A9MDCATeA4YDOwMkA0sDjgOzA4UD/AJGAqwBbwGYAfwBSQJGAgACtAGZAbYB8wExAmACfQKNApQCmwKxAuMCKgNRAyADiQKzAeUAVQAXABQAIAARANX/ev8d/+L+5v4l/3X/oP+N/1T/K/9B/57/JwCtAA0BSAF3AbYBFwKkAk8D9QNkBHYEKQSXA+MCKwJ9AdkAPgC6/1//Ov9S/6v/QgADAc0BgAISA4YD6gNTBMQEOQWeBeMFAQbwBa0FOAWTBMADwAKeAW8ASP89/mT91PyZ/LL8HP3M/a7+ov+KAFEB6QFFAlMCAwJTAV0AV/9y/sL9Qf3Y/HL8+PtS+3P6c/l5+Lf3S/c69333BvjL+Lv5vvq8+6P8Zf3n/QP+nv3H/Kb7ePpw+a34MPjl9673f/dc91b3ePe59/73K/hG+Gn4tPg4+fj56frp+8L8SP10/V/9Mv0E/db8lvw2/Lv7NvvC+nv6gvrp+pz7aPwX/Y390P30/RH+QP6R/gX/hf/y/z8AfQDPAEsB3AFYAp0CpwKFAksCDwLpAfIBLgKKAuYCKQNSA3EDmgPPAw0ESgSFBLoE5QQLBTsFhAXuBXMGCAegBysInQjwCCgJSAlUCUYJEQmwCCsInwcjB8UGhAZVBjQGJgYvBlEGfwakBrQGtgbBBuEGGAdVB4QHmgeZB4AHUQcEB5AG8gUrBUMETANeAosB4gBrAC8ALgBgAKMA0wDQAJIAKACx/0X/8v63/o/+av48/vv9p/1A/cT8NfyR+9z6Gvpd+b34VPgz+Fr4ufgu+Zf52/n5+f75//kK+h36KPoe+vv5yPmW+XX5c/mT+cz5AvoU+vL5qPlZ+ST5HPlH+az5SfoN+9T7d/zu/Ef9m/3v/Tb+ZP6E/qX+zf72/hr/Rv+K/+n/SQCOAK8AuwDCAMgAxwC+AL4A2QAPAVIBjwHFAfoBOQKHAuUCUAPAAycEcASSBIwEZwQvBPADqwNnAxkDvgJWAvIBrgGcAb4BBAJVApkCxwLoAgwDQQOJA9UDGQRIBGEEWAQcBKMD9wI8ApQBDwGjAD0A2/+R/3v/pf8JAJoARAHwAYAC5wIyA34D4gNkBPcEkgUhBpkG6wYJB+oGiAbnBQwFBQTeArwBxQAZAM//8v+JAIIBtgL4Ax8FFQbTBl4HuQflB98HrgdcB+oGXwbDBRkFWARxA14CJQHT/4T+Vf1b/KD7Nfs1+7L7oPzU/Rz/TgBAAckBzQFFAUUA9f6M/TT8//rs+fn4J/hu98L2KPat9Vv1MPUd9Rz1MPVq9df1cfYu9/33x/hv+dH53/mn+UP5w/gp+Hn3ufb69VH10PSD9Gv0ivTi9HD1IPbj9q33dPgm+bv5OPqq+hX7cvu/+/z7MPxZ/Hn8j/ye/KX8oPyH/GD8NPwV/AX8Cvwv/IT8Dv29/X3+Pf/3/6cAQQGwAegB/AEUAlACqwIKA2cDywM9BLMEFwVZBXEFXQUbBbEEMAS1A18DPANLA4QD4wNhBPAEfQX7BWgGvwYDBz8HgwfYB0IItwgtCZgJ+QlPCoYKfwoqCpUJ1gj7BxMHOQaOBSYFAQUVBVQFpwX9BUcGfQaaBqkGuwbVBuwG8wbpBtgGwQadBmQGCAZ8BbkEvwOiAn0BegC7/03/I/8p/0z/d/+T/5v/lf+M/4L/bv9E//v+lf4r/uD9vf21/af9eP0V/Xb8q/vO+v75Ufna+Jr4i/ia+Mn4G/mL+Qf6ffrk+i/7UftA+wX7tvpv+lH6X/p/+ov6d/pT+jH6GPoM+gr6C/oK+gv6Evop+lr6uvpL+/f7mfwY/Wj9j/2j/b798P0s/mH+iP6l/rj+yP7j/hH/S/+C/67/yf/O/7//sf+9/+f/IgBjAKMA3gAXAVsBuQEyAq8CGQNgA38DfANoA1QDRwNDA0wDXwNzA3oDcANXAzkDIQMWAxID/wLdArwCuALaAh0DeQPeAzsEhQS5BMwEsARmBAcErQNbAwUDswKFAqUCIAPiA7kEeQURBpMGHAe2B1MI2AgzCV0JSgnqCDAIJwf3BckEugPhAlYCLAJgAukCvwPKBOUF7QbTB5EIFglVCU8JDwmjCBkIgQfjBi0GTQU9BAkDuAFNANj+hv2L/Bf8Lfyt/Gf9RP45/y8A+QBqAWYB4ADX/17+ofzL+gf5g/dn9qv1K/XF9HD0HPSq8xPzfvId8gTyO/LL8rbz2vQK9hz37fdU+DH4ivd89hv1hPPn8X/we+/17vfudu9V8HLxtPID9D31UfY09+H3Wfix+A35f/kF+pf6LPux+wn8Lfwq/AT8tPtB+9X6kvqG+rT6MfsD/Av9G/4f/yAAHwEOAt0CfgPsAyoETwR0BJYEogSZBJYEtQT3BEoFmgXfBRUGOQZGBksGVwZtBoAGggZ5BnoGnAbmBlUH2AdaCMwILwl9CaUJlglSCfsIswiECGgIYQh7CL4IGglyCacJpwlrCfkIXwiyBwIHawYJBvUFGAZEBl0GeAaiBsAGpQZGBrcFCgVMBJID+wKKAjYCAALmAdMBrAFzATUB6wCBAPX/af/4/qr+fv5+/q3+9v44/0z/FP+J/rv9xvy7+7j64/li+T35ZfnM+Vr67fpj+7H71/vR+5n7RPv9+tr62Pr5+j37ifu2+8T7zfvG+4P7+fpT+sT5Z/lK+XX53vlt+hL7zfuU/Ev93P1I/o3+nv5z/h/+yf2T/Yj9of3M/fz9MP5r/qv+6/4j/1T/fP+h/9D/EgBeAKsA/QBfAckBFgItAhgC8wHDAZABXQEzAQMByACSAHAAaACBAMoARgHeAXAC6QJCA3IDawMwA9sCjAJRAhsC4wGuAYcBcQFtAXsBkwGcAXsBLgG9ADgAsv9O/yH/MP+K/zsAJwEZAu4CmQMJBD0ESwRKBEcEVgSZBCQF7wXmBu8H5AiYCeIJoAnLCHYHyAX3A1MCKgGqAOYA6gGTA48Fjwd0CR8LVwzzDPgMgQyzC8gK+glhCecIYgi2B80GkAX8AzUCbQC5/ir9+vtu+6f7mvwx/jkAXQJRBOEFzwbZBuwFKQS+AeH+1/vf+Cn24PMk8vnwTvAO8BXwQ/CP8PbwavH58c7y8/M/9ZP23ffz+Jb5pvkd+e/3Jfb085nxQe8a7VzrNOrA6RLqI+vK7NHuBPE28z31Avd6+KL5g/oj+3z7iPtS+/D6d/ry+Wv55vhv+B34Bfgx+Jr4M/n/+Qn7Q/yQ/eL+RwC9ASgDZQRnBSsGqgbnBuMGoQYmBoMF1wRTBCMEWATrBMYFwwauB2kI8QhOCXsJeglUCR8J8AjjCA0Jbwn6CaUKXQv5C1EMVQwNDH4LrwrJCQUJfAgjCAgIOgiiCBIJdQnACdEJjwkMCWoIvwcoB8QGpAbABgkHYQesB9UHwAc+B0kGAwWOA/wBgwBb/5r+SP53/hj/5f+nAE8BugG3AUoBnADD/8v+2/0Y/Y38Qfw4/FH8Vvwf/KP75fr4+fj4CvhW9/f29/Ze9zP4WfmO+pv7bPzm/Oj8dvys+7H6rfnR+D34//cW+HD46fhv+fv5fvrp+j37ffue+6/71fsj/JL8Jf3W/X3+/v5b/4b/av8T/6f+Iv6E/fr8t/y5/PL8fv1s/pb/xQDbAcMCaQPBA8wDkAMoA7QCQwLXAYMBaAGJAc8BIgJ0ArACuwKaAmACEwKwAVABGAEfAWEB1QFoAvsCdgPPA/wD7QOlAysDjQLmAVwB/ADFAMgACwFqAb0B+AETAv4BswE5AZ8AAgCY/4j/xv83AN0AwwHTAuUD2QSlBTgGiQa6BgAHaAfcB0kIsQj+CA8J4gh7CMAHngZBBeADowLKAZ4BPQJ7AyQFDQcQCQoL0gwdDrAOkQ7oDc4McQsaCt4IpAdpBj8FEwTQAoYBRwAG/9b9+fya/Mf8if3R/mYABgKDA6UEKAXtBO4DJAKp/8T81fke98P01PJa8Vzw2O+s777vAfBp8N7wXfHy8ZfySfMF9LD0KPVg9V31/fQh9OTycPHc70nu/Ows7Nrr9etz7Ejta+7P71Xx2vJJ9I31lPZv9z34+/iM+e/5Ofpd+kf6DPra+bn5o/mj+dX5SfoC+/37Mf2B/sr/8gDzAcwCfwMTBI4E7wQ+BZUFAQZ0BtsGMwd8B6YHrgegB5sHtQf6B2gI9QiaCUcK5QpdC6ULsguGCzQL3gqiCpEKtgoSC5wLOgy+DAIN9QyIDKwLewooCd8Hvwb0BZ4FtAUUBqgGVQfvB04IXggSCHsHvAbzBTkFrQRXBBcE2AOXAzQDbgJDAef/d/73/KD7t/pO+lX61/rP+/78Iv4K/47/jv8E/wb+xPxz+zr6KPlT+Nb3q/ez99z3Dfgi+Af4y/d/9zr3Jfdd99/3oPie+b/6zfui/Cf9P/3f/B38G/v++QT5XPgS+Db46Pgc+pH7EP16/p7/UQCiAK4AggAvAN//qP+Q/5//3/8zAHwAqgCwAHkAFAC2/3v/Yv94/9r/jABxAWsCZQNABM4E/QTaBHMEzQMJA1UCygFmASwBLAFXAZYB3QEjAk8CVAI7Ag8C0wGUAWIBQwE/AVcBeAGQAawB3wETAjICPwI3AgICoAExAckAWwDz/6z/gv9Y/z7/W/+r/wMAWAC9AC0BigHbATkCsgI8A+EDpwSFBXIGXQcvCOEIigklCoEKiwpXCuEJGAkfCC0HRAZlBdQE0gRNBSUGdgdFCUgLLQ3RDhYQ2RD+EHUQRQ+hDdEL9gksCKwGjQWnBNcDLAOqAjICtwFVARUB9wASAYMBNwIGA9ADbAScBCUE+gIvAdT++PvC+Hr1dfID8GbutO3E7V/uYe+p8AHyMPMJ9HH0VfTO8wHz//He8Mvv5e4j7nrt5+xb7MbrL+uk6irq0OnB6SHq9uo77NPtkO9T8QjzgvR99eT11fVq9br0+/Nw8z7zbfMK9B71i/Ye+LL5O/um/NT9tf5c/+3/fgAYAcIBdgIsA+QDpARjBRAGowYbB3oH0wc7CKsIEQlyCeIJZArsCnsLGwzIDHQNEw6UDuoOEQ8PD+YOmw5CDvYNww2tDb4NAg5vDuQONg9CD/oOXQ5gDf8LZgrtCNIHFQe9BusGnweeCLYJzgq2CyIM9gtACwQKQAgnBgAE+wEvAKb+aP1y/MX7TPvr+pn6Yfo7+h76KfqB+hn70/ut/Jr9W/6j/lP+Zv3Z+735Q/ej9CHyD/C27j3uqu7h76vxu/PN9ar3Gfn0+Tv6Ffqz+Tz5z/h/+GL4f/i++On40vh1+OT3NPeM9iX2MPbB9t/3k/nO+07+yADwAokEXwVuBc0EqAM6AtYAwP8W/9/+Kf/y/xcBYQKeA6QEXQXGBeUFyQWWBW8FbAWaBfEFSQZ/BpoGrQadBkAGmwXdBCgEkwM/A0MDiQP6A48EOgXFBfwFzQVPBY8ElQNqAjEBJwBz/xD/8f4W/3n//P+EAAoBgAHMAeEBxAF6AQQBbADE/xT/ZP7F/Uf98Pze/DL97/30/iEAYgGsAu0DFAUEBrIGNgfBB2EIBwmfCRoKYApfCg8KaglkCBIHtgWaBP0DEQT6BMAGSwlcDI4PcBKnFOkVAhbrFNQSBBDUDK8JCAcXBdkDPwNKA9MDkwRTBfEFTwZcBjMGBgb1BQEGIAZCBkcG8QX1BC4DsQCp/Tv6i/bn8rrvau0+7EbsUu0H7xvxWPNh9cn2WfcU9w32V/Qp8tTvlO2K6+Xpzeg56PLnz+fK5+jnI+h16PDovuno6kzsxe1C76rw0PGT8vLy6PJg8nbxgvDN72rvY+/Y79XwSfIZ9Cj2Rvg3+tP7Hv0k/vT+k/8OAHgA4QBEAZQB5gFeAgkD3wPaBPwFMwdwCLYJ/wolDAgNnQ3lDd4NmA06DdgMggxNDFwMwAxrDT0OGQ/zD8wQjxEfEncSrRLKErYScBIPEpgR6RDqD6AOFA1aC54JIAgIB1wGIgZxBmAH4wi4Cn8M6A23DsIO6Q02DMoJyAZsAxUAHP2u+t74wfdZ93v39fep+Hj5Ovra+mH70vse/Dz8Lvzx+3X7qPp1+dj35vXG86Pxs+8r7j7tEe207RTv+/Ap83b1qPd0+aP6MPsq+5b6jflJ+AT33vXr9ET0+fMN9Hn0NfU79of3B/me+jL8xP1Y/9sAMQJEA/0DTgRDBPgDcwOqAq4BsQDk/2f/Sv+R/zIAKwF/AhsE0wVxB9YI7AmeCs8Kegq/CdQI1Ae4BocFagSLA/AClQKAAqMC4wJCA9gDngRmBRcGugZDB4wHegceB4UGoQVsBAcDogFXACb/H/5j/QL95/wI/Xv9Rv4x/wgAzACKAR0CVwI4As4BDgHx/6j+dP1s/Jb7E/se+8/7Bv2T/lgAMgL1A4UF6wYrCB4JngnECb0JfQnlCBAIMAdBBiYFDARRAyQDewNrBB4Gggg9CwMOsxANE6IUIxWWFCIT2BDnDcYK+Ae0BfoD4gKQAu0CswPDBBMGXwdGCLII4AjkCJsI9wcVBwAGmwTWAsgAdP7M++T4BfaC84jxLfCM77bvlPDy8Z/zZPXz9v33Ufjl97X2zPRd8q/v/exw6kPosubS5YrlxuVw5m/npugE6njr5Owu7k3vPPDy8GTxjvFs8QrxgvDu71Tvye5v7mvuzO6P76zwHvLa88f1x/fB+Z77SP2x/uL/6wDKAXMC4wIgAy8DJQMmA1UDrQMoBNQEywUFB2UI0Ak5C4gMnQ1lDuIOIQ9AD2APlw/sD1kQ2hBzERcSpBLxEvISqhIkEmcRjRC4DwIPgw5RDmAOiw6uDr4OsA5sDuoNQw2eDAsMjws7CxAL/QrnCrsKYAqsCXYIuQaUBDgC2P+o/dT7ePqh+WD5rvlc+hj7qfv++w38w/sU+wz6yfhp9xD23fTQ89zy/vFA8Z/wB/B47wvv3e7/7nPvNvBC8ZDyCfSD9cD2jffT95f37/bw9b30gPNv8sDxmPH78dPyDPSY9Vn3I/nO+kf8h/2K/l7/IgDiAI8BHAKaAhADYQNzA0wDBgOoAjoC5AHGAesBVwIjA1IEtgUZB2kIowmuCmMLvAvDC30L8Ao1CmwJmgi9B/AGRwa4BTMFxgSKBHsEhwSrBOwEPAWKBdQFEwYpBgkGyQWBBRwFigTcAyQDTgJWAWAAhP+x/tz9Lf3Q/L384/xQ/QT+t/4x/4H/xf/X/4X/7f5P/rr9L/3s/EL9H/4z/2wA3QFbA5UEfQU8BsQG2waQBkEGGgbzBb0FrQXaBREGPwakBmIHRgghCRkKWQvDDCUOew+3EIMRlBH+EPoPkw62DJQKigjSBmwFcgQYBG0EPQVNBoIHuwi3CUoKdwpFCpwJZQi7BtEEvgJ2APr9cfsH+c72z/Q18y7yt/G48SryDvM59Gj1dfZK9673Y/dg9t30DPP58MLuqOzj6njpZujQ58jnHOiP6Bvp1Omt6ozrcuxn7VruK+/a72/w4/Ac8Rbx3/CK8CLww++W78DvRfAW8SryefPp9Fr2r/fb+N35wfqJ+0X8C/3y/QP/NQCAAckC7gPjBLYFaAbfBhEHHgc4B3EHyQdNCAkJ8AnfCsgLugypDXYOIA/KD4EQKxHCEWMSDRORE8wTyROGE+QS6RG/EIkPTA4iDUIM1AvEC/4LiQxZDSsOyg5AD5oPrQ9QD6cO4w34DMULYArgCDkHXgVsA38Bmv/I/Ub8S/vR+rz6CvvA+7D8kP0z/oj+av6s/Vj8pfq8+K72o/TT8k3xBvAF72PuHu4X7j3uj+4X787vsvC/8fDyJPQ09Qr2kva19mj2u/XJ9KbzcvJj8aTwRPBX8PDwAfJc89z0d/Yg+Lz5N/uS/M/94/7I/4gANAHGAScCVgJVAh8CuAFIAfkA0wDXACABwwGtAsUDAQVQBpEHnAhpCQgKfAq1CqoKgApgCkUKBwqfCS0JuAgmCHcHxwYkBosFDQXVBPwEZgXpBXEG8QZJB2IHTQceB7YG8wX8BBIEOgNYAn0B1ABZAOj/ef8a/8/+jf5c/lD+Yv51/nf+fv6n/t7+9v7s/vT+Mf+g/zEA4ACuAYcCUgMMBLsEUgWtBb8FrQWMBUIFzwR3BHEEmQTDBAsFogWNBrUHGwmyCk0MwQ0WD1UQQRF6EesQ3Q+ADrsMlwpuCJYGFwUCBJYD4QOPBFwFZAbBBykJKgqiCrgKdwrACYYI6AbuBI4C5v87/aT6C/iR9Y3zLvJr8UXx0PHt8lP0zPU993f4P/lr+ef4sPfZ9Yvz/vBy7hvsIOqY6JPnJedW5w/oGelG6pDr8exK7n/vl/CB8RTyT/Jc8kfy5vE18Wrwr+8J74LuQu507iDvPfC68YHzcfVa9xf5lPq9+4T89vw//X79wP0a/pz+Tv8sAC0BPAI6AxcE1gR+BQ8GjAb4BmwHCgjaCLEJZwoEC6sLXQwDDYoNAw6PDkQPFxDuELwRcBLqEhMT9RKSEtwR2RC6D60OwQ0EDY0MbAydDAcNiQ0NDo4ODg+DD90P/w/QD1sPvg73DeQMbwufCYwHXQU/A1IBqv9m/p39Q/1O/bn9Zf4R/4z/yf+1/y3/N/78/Ir71Pnv9x32hPQP86rxbvCC79ruXe4o7mDu7e6a723wfPGj8qfzdPQI9UH1BfVt9JvzmPJ08V3wfu/r7q3u1+5y72vwlPHW8jf0rPUN9z74UPlc+mD7Tfwh/dv9f/4E/1n/bP9L/w3/uv5b/hL+Cf5U/vv+/f9QAdkCewQNBm0HhAhHCasJtwmMCUUJ7wicCGMIQQgqCB8IIQgeCAUI2weuB4AHWwdYB4gH5QdVCMAIGAlPCVQJIAmzCA8INwdABkwFbwSwAyQD3gLPAtsC7gLyAs8CjQI/AtMBLwFtAMr/Vv/8/sz+7P5j/xsABwEmAl4DcgQ/BdgFVgawBs0GsAZlBvUFewUXBcAEWwTuA6MDlAO+AykE5AT2BV4HGAkRCxcN7Q5bEC4RSxGvEFUPQQ2kCuYHZAVMA6gBlQA9AKoAsAEJA4oECAZVB04I6ggVCbsI5Qe+BlUFlQNnAd7+LPx7+ej2jPSO8h3xW/Bb8CDxgPIu9PD1rfc3+Tj6d/r0+cn4Cffi9I/yOvAF7iLszOoQ6tHp7ulq6kzre+zG7RjvZ/Cl8cHytfN49PD0GfX89Jv0/PNH86PyC/KA8THxT/Hh8c3yCPR79QT3ifgB+lX7Zfwo/aj99v0g/j/+cv7D/iL/hf8IALgAeQEtAuICqANgBO8EawXwBXkG9AZhB8YHIwiECPwInAlkCkoLNgwjDRUO/A65DzsQcBA7EJkPxg4CDlINoQz7C4QLVQtuC8QLOAygDOQMHQ1vDd0NNw5hDnAOeQ5lDhMOdg18DAkLMQksByoFQgOWAVAAif9H/3r//v+oAFgB5wEfAt8BLAEdANf+hP0x/Nn6hflf+HL3ofbO9fr0LPRn87vyRPIT8iLyYfLe8rDzvPSq9Tz2efZw9hr2dfWU9IPzYvJ98Q/xC/FL8crxlPKc87/0zPWd9i/3nfcA+F/4xfg6+cT5dfpg+2/8av0p/q/+Df9G/07/JP/q/tT+A/91/ygAGgEtAkUDXARiBSkGmwbUBvYGBQcGBw4HLAdoB8IHIghmCIkIkAhwCB4IrQc4B9EGkQaLBrkGBAdeB7sHCgg9CEcIGAisBxMHXwaYBc8EGAR8AwgDwgKZAm8CPQIUAvMBywGLASEBmAAaALb/Vv/x/q3+pf7X/kj/BwD2AOABuwKSA1gE9ARhBaUFwwXHBcAFtwWqBZgFgAVlBU8FOgUtBUQFkQUMBsYG4wdoCSIL6AyPDtYPgBCHEPMPvw70DMkKdwg3BkQE0wL8AcMBDgKyAokDhASKBWIG5QYOB+MGaAauBbcEaQOwAaP/af0c+834hvZf9IjyO/GV8JXwMvFN8q3zIPWD9qj3WPh4+AD4+/aA9bDzrPGy7wruz+zq613rSuuu61XsKu0s7jnvJ/AF8fXx5PKi8yH0dvSx9NH01vTF9Jn0RvTg86jzzPNA9Oj0z/X49kT4kfna+gj88/yP/e39FP4Q/gv+J/5u/un+m/+BAIgBsgLsAw8F/gW8BlIHvwcNCD8ITAg4CBgI/AfwBwIILghtCMoITwn2CbcKlwuIDFkN9A1gDqEOrQ6BDiIOlA3iDCQMdAvcClgK1glgCR8JIwlNCYoJ9QmLChMLcgu9C+ILpwsACxYK9QiKB+kFXAQLA+sB8QAxALv/ef9C/xD/6v62/lP+1P1j/fz8e/zq+2L74vpL+pL5tvjC98L2yPXk9DX0x/OD81/zffPr83f06vRF9Yz1nfVt9Rz1yPRy9B707/P58zT0jfT/9JP1Nva69hP3XPeh98734ff79zf4l/gr+fr55/rX+8L8pP1v/hP/j//h/xsAWgCuAA8BfQEAAo8CFwODA8oD7wMBBBUEKAQxBEUEigQWBeIFxgaWBzEIlgjRCOQIvAhUCMUHOgfQBocGWQZHBk8GYAZoBlkGIwbIBWYFFgXQBIQEQAQSBP0D+QP8A+MDkwMkA8ECawIBAn0B+ACDACkA7f/I/5r/V/8Z/wD/F/9W/7H/KgDOAKMBkQJ/A2kETwUfBsEGMgeAB7YH1QfaB8sHoAdLB9wGjAZ1BmgGRQZHBrsGlweiCNcJMQt3DHgNQg7cDgcPiw6NDVoMDQuRCe0HbgZNBW4EpQMFA6kCagIXAskBlgFYAfkArQCVAIAAJACA/8T+Bv4Y/cf7Jfpn+J322vRm83Xy3PFt8U3xlvEJ8lryfPJ58kHyz/Ez8Yzw8u927yLvAe8e72bvtO8A8EXwaPBR8B7w/O/47wrwOPCG8Pzwi/Ea8pjyEfN+87/z5PMq9Kf0RfUK9hn3Z/jS+Uv7xvwP/gX/sP8ZADwAIADi/6r/lv+p/9f/LQDDAJABeQJvA24EaAVZBk0HRQgyCQkKyQpoC+oLUwySDJEMXwwaDMcLXwvvCpMKWwpRCnYKtwr+CkoLoQsDDGEMmAyVDH0McgxdDBMMnwswC8sKUArHCVEJ7Ah3CPMHjwdUBxEHpgY8BukFgQXhBCoEgQPSAgYCSAG8ADwAp/8d/8f+gP4J/mr93fxr/OD7MPuH+gD6hPn9+HT47/dh98L2Jfac9SX1s/RH9Ar0GvRl9ML0J/WV9fr1SvaG9q72svaK9k32IfYU9hL2CfYQ9kf2mfbZ9g/3ZffT9z/4r/g6+eP5pvqH+338dP1Z/iH/yf9jAPMAWAGEAZUBoQGwAdMBGQJsArQC/wJdA8YDMgSnBBgFfAXgBUoGqwYFB14HrgfkB/cH5we2B3UHGAeWBhIGtwV5BT8FJQU+BVwFYgVpBXsFbgU4BfYEtQRtBBkEuANTA/0CsQJMAs0BTwHNADcArv9W/x7/9P7w/iP/bv+v/8//yP+i/2b/Df+e/kT+Iv42/oP+Gv/j/8IAtgHDAs4DwQSRBToG1QaCBy4IrQgNCXcJzQneCb8JkglHCc8ITwj6B+YHBwhYCOQIrQmECi8LtAszDIQMagwJDKELHgtgCqIJHQmgCOoHFAdSBpUFrgSfA5ECjQF8AF3/Yv6i/e/8Kfxw+9b6Nfp4+bj4APg793H2yPVB9cX0VfQI9N7ztvNn8/Dyb/Lv8VLxifC47/fuUO7U7ZLtcO1U7VftiO3W7S/ul+4N74PvAPCW8D7x6PGK8iXzvPNQ9NX0PfWE9bv19/VA9pD26vZq9xf40/h/+Sj63PqM+zH82PyS/Vz+OP8sADIBQAJSA2EEWAUuBt8GbAfeBzwIeQibCMgIGQl4CcYJCApFCnYKlAqnCrsK2QoGCzwLggvpC24M8AxXDaIN1Q3eDbINVA3gDGIM2QtRC+UKlgpLCv8JyAmUCT0J0Qh4CBcIkAcGB64GfAZMBhgG5QWuBWQF9AROBH8DngKmAZYAjP+b/sD9CP2C/Bf8qfs7+9H6XPrd+WH56Phq+Pb3lfdM9xz3/vbe9rj2kvZj9hv2vfVX9fT0rPSN9Ib0nvTs9GH11PVG9sf2PveP99H3EPhA+Gr4sPgE+Uz5nvkP+on69Ppf+9j7VvzU/Fn95f2D/jj/9/+zAGcBBwKGAvICUgOQA5gDjQOPA6ADtQPWAwYERQSPBOEEQQWlBQEGSwaVBuIGFQceBxoHHAcKB84GbwbyBWIF4gR5BBAEpgNfAz4DNANBA2MDcANfA1gDYQNHA/wCoQJDAtcBYAHqAHAA8f93/w3/uf58/kn+F/7//RD+Mf5M/nP+pP7D/sf+wf6v/n3+Mf7k/aj9hP11/X79r/0V/qP+Tf8WAPAAyQGwAqsDpASKBXIGWQcnCOMIlwkoCoUKywoQCzoLPQskC/kKwwqZCnoKXgpFCisK/gnHCZsJcwk5Cf8I1giwCIUIZghgCGQIYwhICAIIngcrB54G4QX7BPID0gK5AbcAuf+1/q39pfyb+6b60fkH+Tj4aPee9uH1RPXQ9HT0IvTZ85LzRfP48rzykfJj8h3yxvGB8VrxRPEw8SLxEvH/8PfwBPES8R7xLfE/8VbxgvHK8SHyffLg8kTzrPMw9Mj0T/XA9Tj2uPYr95f3Fvic+Bj5lvki+r/6cftB/Cr9Gv4L//v/4gC8AYYCPQPSA0AElgTpBEAFoQUQBokG/AZzB/0HiwgFCWYJtQnuCQwKGwopCkIKdgq7CvAKCgsoC1ELYgtDCwELrApHCuEJiglGCQ8J6gjXCMsIuwijCG8IBgh0B9gGNgZ8BbQE+gNeA+oCpgJ7AkoCFALdAZEBGgGGAOf/O/+O/vL9Z/3l/Hf8GvzH+3/7OfvZ+lb6xfk3+aj4Hvis9133OvdN93z3pfe+99X38/cY+DD4KfgU+Bj4QPiB+N/4YPnv+YL6GPuc+//7S/yJ/LD8zPzs/BD9Nf1z/dT9P/6o/hP/cv/E/xkAcwDGACEBlwEiArgCVAPiA1MEsgQABScFLgUkBQUFywSTBHQEZwRjBG4EfgSKBJkEpwSnBJcEgARbBC4EAwTYA6UDcQM5A+QCcgL4AX4B/gCHACMAzP+E/2H/Zf95/4H/dv9u/2//Z/9A/wr/2/6r/nP+Qf4W/t39kP07/e/8qvxf/AT8pvtg+z37N/tP+4v74PtB/K38Gf18/d39Of6F/sj+E/9k/7X/CABZAJgAxgDvABsBRAFuAZ0B1wErAqQCQQMEBOgE3QXWBtkH4AjPCZEKJwudC/sLOwxUDEIMFQzZC5ULTgsRC90Kqwp4CkYKJQohCiwKKQoiCikKIgrvCa4JeAk0CcIILAiKB+QGKwZYBXMEmwPSAgACLgGMABsAsv9C/+7+sv5v/hH+m/0T/Xn8x/sG+0b6kfnb+B/4a/fR9k722vVk9ej0bfTz83Tz/fKp8nryXvJX8mfyh/Kx8uryIvNI81zzWPM68x/zJfM8807za/Om8+vzN/SZ9Az1cvXJ9SD2gvYC96D3R/js+Kb5e/pU+x783fyL/Q/+Y/6h/uf+Nf94/7n/DwB9AO0AWgHPAUQCoQLdAgQDLANnA6wD7QM7BJ4E+wQ/BYAFxAXtBfcF+QX3BeUF2gXrBQkGGQYjBjMGRgZPBjgG9AWPBRwFoQQpBNQDqQOLA2gDTAM7AykDDAPfAqACUAL+AbMBcAE5ARQBAgHpALcAewBPACAAzP9b//D+l/5R/hv+8f3U/dX96/3x/eL93f3l/ef94v3i/ez9EP5Z/rD++/4//3//rP+9/8H/uf+Z/2j/PP8l/x//H/8e/yz/YP+s//X/LABbAJYA4gA0AYMB1AEpAm4CmwLBAuoCAwMFA/YC4gLUAtECzwLFArgCtgK8As0C5wLzAucC2QLMAqkCawInAt4BggEZAbQAVAD7/7X/hf9e/0L/M/8v/zL/Nv8u/wr/xP5m/gP+sP1m/Rv91fyk/Iz8jfyf/LT8vvzB/MD8u/y3/Lr8vPy6/MH81Pzm/PX8A/0K/QL97/zQ/Kn8j/yP/KP8yvwT/YX9FP6u/j7/uf8pAJIA3gD9AP0A+QD8AA0BKgFRAZEB8wFpAtwCTwPPA0kErQQGBWwF5QVjBtoGUQfSB1MIyghBCb8JOAqXCt8KDgsfCywLTAtsC24LVAtBCz4LOQscC+gKqApaCvoJmglOCQ4JuAg/CL4HSgftBp4GTwbsBXoFAwWMBBEEggPSAgkCQwGLANb/K/+W/hb+mf0s/dn8nfxj/Br8svsi+3b6w/kZ+Xr43/dB96L2FPap9WD1JPXf9JT0T/QN9MXzifN584jzmPOn88zzCfRF9HL0i/SN9HP0PvQI9O7z8vMB9CT0avTV9FX17vWa9kP30vdK+Lr4Mfm3+UH6wvpA+8X7R/y8/DL9q/0N/kn+cf6c/tL+D/9V/6f/BABpANQASgHCASMCVwJjAmICdAKUAqoCsAK+AtsC/AImA3ID1AMZBDAEPARkBKME4AQKBSkFTAVwBYUFhAV0BU8FCQWqBEQE5AOHAzAD4wKuAo8ChgKRArUC4AL1AvIC9AL9AvQC1wK8ArACpAKFAlkCKwL4Ab8BhQFMARIB2gCzAKMAoACsAM8ABAE/AXUBngGxAbgBvwHBAa4BjgFxAWABTgE5ASUBHAEeAR4BFwEVASABJgEPAewA4wD5ABcBLAE7AUQBOAEkASIBNAE7ASMB/wDgAL0AjwBmAEoALQD//9H/t/+1/7v/vf+y/5z/f/9r/2T/YP9R/zr/I/8R/wf/Av/3/tv+sP56/jf+6f2W/UT97Pyb/Gv8Y/xp/G38ffyd/Lv8yPzK/ND81vzJ/Kr8lfya/Lb82Pz8/CT9R/1f/W/9gP2Q/Zb9m/2o/bv90P31/Tn+h/62/sD+zf7s/gT/Bf8F/xj/N/9b/4//4v8+AI0AzwAVAVoBlQHBAeQBAQIjAk4CgAKvAtEC5gLxAv8CGgM4A0kDRgNMA3UDvwMfBIsE/wRuBc8FLQaUBgIHagfPBzwItAgtCZcJ8QlHCpUKvwqrCmAK/AmVCTIJ1Ah8CCUI1AeWB4AHgwd5B1AHFAfaBqIGaAYwBv0FywWSBVkFKgX8BLEENgSTA9YCCQI5AXsA5/92/w//r/5x/l/+V/4q/tX9av3x/GL8xvsp+5P6Avp0+er4cPgV+ND3fPf+9m72+vWs9W/1PfUk9Sb1NfVO9W/1jvWc9Zj1h/Vh9SH14fTE9NH07/QR9Uf1nvUJ9nH20PYo93v3x/cG+Ef4mPj1+Er5n/kF+nr64fot+237rvvf+/v7Hfxh/Ln8EP1n/cj9LP57/qz+zf7o/vn++/70/vn+G/9Q/5H/7P9qAPgAcAHRASsCgAK+AukCFgNCA2QDhQPAAwUEMQQ+BEgEVwRWBEQEMgQjBAgE5gPXA+kDCAQiBDYESQRTBEcEJwQEBOgD0AOzA5IDfAN5A44DtgPkAwUEDAQGBP8D8wPjA9EDsQNtAxADxwKpAqEClgKKApECnwKsAsMC5QL8AvwC7gLZArgCkQJwAkgCCAK4AXsBVwE8ARoB8AC/AIsAYwBRAEoAQwBBAEUASgBRAGAAaQBTAB0A2f+L/y3/wv5i/hf+3v28/bz92f0F/j3+ff63/tr+4f7S/rX+kv5t/kX+Fv7l/cD9rf2f/Yz9bv1K/Sv9HP0c/SP9Kv02/Ur9Zf2F/an90f3w/fX91v2i/Xf9Xv1R/UT9Qv1Z/Yn9x/0V/nf+3P4y/3P/pP/G/9z/8P8GABQADQD5/+v/6f/t//H/8P/p/+b/8v8XAE4AkADOAAEBLQFiAZ4BzwHpAfIB8AHhAc4BzwHuARICKAI6AlkCfwKgArgCzwLjAvIC+QL9AgkDIQNDA2QDgQOkA9QDEARYBKUE8QQ6BY0FAQaXBj4H4wd2COoIPAlwCYsJfwk6CcAIMgiyB00H/AayBmoGJwb3BegFBwZIBoEGkQZ6Bl0GVwZrBn0GbgYzBtsFdQUDBYAE4AMdAzoCUgGKAPD/df8R/83+oP51/kv+Nv4y/gr+oP0I/WD8qvvj+hz6W/mL+K/38/Z09hr2w/Vt9Sv1+vTS9MD0zPTn9PT07vTo9Pf0FfUr9Sf1DPXk9LD0evRV9Ez0UfRY9Hf0x/RC9cb1TPba9mn35PdL+LL4IvmL+d75HfpX+o76xPoB+0f7kPvW+x38fPz1/G/92f00/ob+w/7n/gP/Mf9k/4f/nP+7//D/QQCnAB0BkQH8AWICxgIlA4ED2gMkBF0EkgTRBAkFKAU2BTwFMAUKBdgErgSOBHMEZwRxBIUElgSsBMwE5wTvBOcE0gSxBIIERQT2A58DWAMuAxQD+gLoAukC8wL7AgoDIAMkAxED/AL7AvsC7wLfAtACuQKSAmsCUwJAAiYCBwL1AfYBAwITAhwCHwIlAisCKgIYAu4BqAFQAfwAuQCGAFoANAASAO7/zP+5/8D/2v/5/xIAKQBHAHEAmQClAIsAWQAdANf/jf9E//z+uf6J/n3+k/6//v7+Sv+S/77/0v/b/9//1P+3/4n/UP8W/+3+0f6r/nf+Q/4W/ub9vf2n/Z79kf2Q/ar91v0A/jD+b/6v/tP+3v7W/rf+eP4v/vL9xf2h/Yz9kf24/fn9TP6l/vL+LP9T/2//f/9//3L/Vf8t/wf/6P7U/sX+wf7B/sf+3P4D/zH/Wv+E/7L/5f8hAGgAsQDoAAsBKwFMAWoBhwGnAcIBzwHRAdoB9gEkAlYCggKtAt8CFgNIA3IDkQOeA5MDegNnA14DWANgA4kD0AMXBF4EwAQ/BbQFEQZ5BvgGaQe1B/EHJgg+CDoIKQgACKcHLQe7BmUGIQbpBb0FpwWwBdsFEgY+Bl8GcgZmBjMG7AWpBVsF9QR9BAcEiwP8AmMCygEkAWcArf8V/53+M/7Y/Zv9ff1t/V79TP0y/QL9oPz9+zT7Zfqa+dX4K/ii9y73y/aX9pL2nPab9pL2iPZ29l72SfZD9kr2WPZj9m/2ifan9rX2r/ae9oH2V/Y09jD2T/aG9tr2U/fp9474L/m5+Sn6e/qt+s367/oV+zn7XvuW+9/7J/xx/Mz8Nv2d/fT9PP50/qf+6P49/5P/2/8WAE4AhACrAL8AvwCpAIUAcwCAAJ8AyAADAVcBsgEOAnQC0QICAwsDDAMUAx0DKwM7A0kDUgNfA24DeAN5A24DVQMvA/8CwQJ8AkgCLAIVAv0B7wHuAewB4wHVAcUBtwGyAbEBrwGzAcMB5AESAkICZQJ5ApQCtgLKAsQCqAKDAl4CRQI2AisCIwItAkMCXAJ8AqkC2QIEAywDRQM6AxgD+ALfArwCigJPAhAC1wGzAa4BswGuAZkBgAFvAWkBbAFyAW4BYwFhAWwBdAFvAWIBRwEOAcgAjgBXABEA0P+m/4X/Zf9l/5D/xP/s/xIAMQAwABIA4/+g/0j/8f6r/nT+TP4w/gv+2/20/Zj9e/1b/UP9LP0P/f/8CP0c/TT9Xv2T/bn9xv3B/av9g/1e/U/9TP1O/WL9mP3o/T/+nP4D/2r/s//Z/+z/8v/k/8j/rv+b/4//jv+e/73/4P/8/xQANgBmAI4AowDIABgBcwG3AfgBQwJ4AocCjQKQAnQCNwIGAvsBBgIWAioCTgKDArwC6wITAzgDRAMtAw4D/gLhAqACVgIlAgUC5wHPAb4BrQGgAagB1gErApIC9wJcA9IDUATDBCsFiQXCBcQFowV5BUYFBQW+BHYELQT1A+AD5wP9Ax8ETgSFBL0E9gQsBUYFOAUFBcMEeQQYBJ8DJQOyAjUCtwFOAfkAlgAmAML/c/8t//H+0P7L/tD+yv66/qn+lP5X/t/9QP2X/Ov7Qfut+jL6vflY+SD5HPk2+VD5XPlh+Wr5bflW+TP5J/kk+Qj55vjh+OL4zvi4+LP4ofhs+Dj4HfgR+BT4Ofh7+MT4Fvl1+dn5Pvqf+un6A/v6+vX6/voF+xL7Nvtu+6b74/sy/Iz81/wP/T/9X/1j/WD9a/19/YX9jf2i/bz92P34/Qv+Af7z/f79GP4u/kz+dP6W/rn+8/4+/37/rP/O/+v/DQA/AHQAowDVAAsBNAFbAY8BxQHoAQgCMAJRAl4CZQJvAnECaAJaAkECIwIVAhgCHgIuAloClQLKAgkDWgOnA90DDAQ/BGcEdwR9BIUEigSEBHwEfAR/BHkEcgSDBKgEzQTnBAQFJwVSBYYFvwXmBfMF7gXcBbIFfgVIBQIFqARMBPkDqwNrA0QDLAMNA+0C4QLoAvIC8gLhAr8CmQJ7AloCJgLYAXsBHgHDAGIAAQCo/1P//f62/oX+Wv4u/hf+F/4P/vv97P3c/bj9h/1e/Tj9DP3s/N/8z/yz/Jr8hPxk/ED8JvwR/Pn77fv7+x/8T/yK/NP8GP1S/X39of20/bb9rv2v/bn9yv3q/R/+XP6W/tD+Cf8y/0f/Uf9Q/0z/UP9k/3z/nP/L/wAALwBhAJkAyADfAOoA6wDhANEAwgC5ALgAwgDRAOUABQEjAScBJAFCAXUBnAG+AeEB4AGwAYoBkAGnAcYBBwJQAmECOwIUAusBoQFKAQ8B6wDDAJkAegBcAEEAOwBSAHkAnAC0AMwAAgFdAcMBEAJMApMC6AI6A40D7ANMBJUE1QQgBWUFdgVPBRkF6gS7BJQEjQSeBJ0EhAR3BIYEmAScBJ4EnwR5BCMEyQOSA2oDPgMgAyADIAMFA+gCzAKOAh0CmwEpAcAAZQArABwALwBSAHAAfwB7AF4ADQCG/9/+J/5o/bj8LPy9+2H7KPsT+wb75/qp+kn6yflE+dP4gPhK+C74H/ge+Db4Vfhg+Fj4Svgq+Pj32PfW99T3xvfW9xf4Zviu+P/4YPm2+fn5MPpY+m36dPp3+nf6efqE+pz6uvrX+uv6+foW+0X7d/ud+7n72vsK/FP8sfwE/Tn9Vv1q/Xj9ff1+/Yf9m/2z/dL9BP5R/qH+2/4A/yj/Vv+H/8f/GABqALYACwFyAdcBJwJkAocCiAJvAloCVQJXAloCWQJPAj4CNwI9AkQCRQJFAkkCUwJtApgCwwLyAj0DnwP9A0oEmgTkBAcFBQUDBREFHAUcBSAFJwUiBRIF/QTlBM8EugSoBJ0EmASRBIwEpwTvBEQFgwWeBYsFOwXEBEgEzgNYA/MCnwJAAtoBigFTARcB1wCnAIMAYgBbAG4AgQCOAKkAywDWAM4AwgCeAEwA2v9x/xH/tf5g/hv+3P2p/Y/9nf3G/ev97/3e/dD9x/2z/Z39nP2w/c799v0u/mP+iP6i/q/+rv6z/sv+7P4H/yz/Zv+o/+r/MwByAI4AjACAAGEAHQDG/37/R/8i/xv/Nv9Z/3f/l/+1/77/rv+c/57/t//i/xsAZACyAO4ADwErAVEBagFeATUBCQHZAKMAdgBcAEcAOgA/AE4AUwBIACsA+v/D/57/iP9u/13/bf+N/6P/uv/e//3/AwD//wYAGAAxAFMAeQCXALEA0ADvAAQBCwEHAf8A/AAAARgBWQHHAUsC0gJvAykE+ATcBeEG7wfhCLkJjwpiCxsMrQwPDSgN9wyKDOcLGQs7CmEJjAjOB1QHKgcmBx4HEQcEB+kGsgZbBtwFLAVZBIcD3QJpAhoC2QGWAUwB6ABhALf/6/7p/bz8j/t9+on5s/j690L3cvaY9cT03/PO8p3xZ/A87y3uXO3Y7KTsxewy7crtdu4v7+Tvd/Dn8EvxqfH78U3ytfIw867zNvTP9Hb1Gfan9if3ofcV+H746Phv+RH6rPo0+7z7TvzX/FT91f1Z/uP+i/9WAC0BBgL6Ag0EHwUlBiYHDQi6CDUJjwnKCeMJ6QncCaUJSAniCHMI6wdOB60GDQZ0BfgEogRpBEcEQARQBGcEbwRWBB0E1QODAxsDuAKDAnkCdgJ8AqQC3AL6AvcC4AKjAjACngEBAVsAtv8h/5P+9f1Z/dL8UPzE+0P71fpx+hz6+vkY+m36AvvV+8T8sv2Z/mr/AABXAI4AvwDmAPkAAQEPATYBfgHYASoCXwJnAjsC7wGaAT8B7wDHANcACgFWAdABdwIZA5cD9gNGBIEEsQToBCkFcgXTBUgGswYGB0kHagc8B8EGKAaKBdYEBAQuA2QCrwETAZMAIQC0/1b/Cf++/mj+Dv6//YH9Tv0q/R39Kv1G/Wj9l/3T/Q3+Pv5o/oD+c/47/u/9of1U/QP9rfxb/A78yfuR+2/7Zvty+4f7oPvB++v7HPxc/Lj8Mv28/U3+5f6O/z4A5QCGAScCtgISAzwDUQNcA1EDMgMLA9QCjAJUAkACOAIlAhoCGQIHAuEBwAGhAW8BMQEPARgBSAGZAQACXgKgAssC3wLUAqYCVgLkAWYB/gC5AIEATwAmAP3/wv9t//P+UP6c/fb8Zfzv+6/7p/uz+8H79ftS/K787vwZ/S39Gf3x/M38pPx5/HL8mfzV/B/9h/37/V3+uP4g/4j/6/9UAMQANAHUAdoCLQSTBQUHkggjCpcL2gzCDQ8OwQ0aDUQMUQtdCoQJxwg7CAMIJwiJCP8IXAl+CWoJOQnmCF8IzQdlBxoH2AbHBgsHeAfLB+MHpAf4BvsFzwRZA38Bff+i/QT8qPqn+fj4Yfi69/r2GPYF9dHzg/IW8ajvgO7F7WftZO3G7X/uce+G8JXxbPL18jrzOfPw8ozySPI18lTyqvI68+nzrPR09SD2jvbJ9uH24/bd9v72X/f898z4wPnJ+uX7Ff03/h7/0v+AADIB2wGLAlkDNgQNBesFzQaRByEIiAjACLAIXwjyB34H9AZTBqkFBwVyBPIDkQNWA0QDVAN7A6sD1APvAwMEFQQWBPYDvgOKA14DMgMKA+oCygKaAlgCCAKjASMBhADH//n+N/6Q/QH9jfxB/Bz8CPzu+8P7jvte+zr7F/v1+vb6Q/vq+9T85v0L/zIAPwEbArUCBwMVA+oClAIqAr8BZAE0ATwBcgHBASACgwLMAvACCgMiAyMDBwP5AhoDaQPsA7AEowWbBoQHYQghCaYJ6wn7CdYJiQk9CQ8J8AjHCJAIUggCCI0H3wb8BfIE1QOuAo0BjACz/wb/jf5Q/jf+Jf4R/vD9tv1n/Rb9w/xm/BP85vvY+8/7zfvd+/n7CPzy+6/7S/vp+pL6JfqQ+fH4b/gM+MP3n/et9+f3T/je+H75G/q6+lf73ftI/Lb8M/2w/ST+q/5k/0oAOQEQAsoCZgPUAwIE/APXA6kDgwN7A44DtQMFBIYEDwVqBZUFrgWpBWoF9gR0BAAErwOUA7YDDgSNBB0FlQXUBdkFsAVNBZ0EoQOGAogBuwALAG//Bf/d/tH+uP6C/iv+p/31/CH8NftT+q75YPlY+Y75CPq0+l/77PtJ/Fv8GPyh+x37m/o1+gf6Cvot+oj6LPvt+478CP1g/Y/9pP3C/fH9Mv68/sr/UAEbAxAFKQdMCV0LLg2JDksPeg8cDz0OGA36C/4KIgqDCUMJXgnPCYYKPAudC6ELaAvmChgKQAmSCO0HRAfZBtgGJwegBxsITAj2By0HHQa+BBQDSAGA/9f9g/yq+yf7s/on+mL5QfjR9j71ifOr8cfvFu687OPrtOsf7Ojs9e0774TwkvFU8r3yrPIw8pDxCvG68LHw7fBf8Q7yCvMm9Av1nvUA9jX2NvYr9jz2a/a59jv3+fff+Of5FvtQ/HH9dP5a/w8AlwAmAeoB0wK/A7EEyAULB1YIcgk4CqIKsgprCtMJ+QjlB6wGcwVkBJAD+QKjAo0CsAIAA2gDxQP9Ax4EPgReBGgEUwQvBBgEFAQVBBIEBATiA6wDZwMKA34CxQEEAVgAuP8g/5n+Nv77/d79wv2C/Rj9oPwm/Kf7PfsJ+wv7Q/vZ++z8Yv4IALUBPgOCBHkFJAZtBlMG/wWPBQAFbAQUBA8ELQRCBEIELQQABLkDWgPtApcCdgKIAtMCbQNNBD0FFAbTBm8H1Af7B+0HrgdjB0IHUQduB5gH5Qc8CGoIYwgiCI8HnAZ3BUYECAO0AV4AHP8C/in9mvwz/N/7n/tv+z37C/vm+sn6rvqf+qT6tPrL+vP6IvtD+0j7Lfvx+pn6Nvq++Sb5iPgR+Mr3nfeF94r3svfy9zr4e/i7+An5Y/m2+Q76jPo1++n7l/xO/R7+CP8GAA0BDwL5As4DjgQ7BcgFGgYfBt4FhwVGBRwF9QTLBMAE6QQuBWQFgQWQBZIFegVJBQsFxgSDBFYESwRdBIAEpwTCBMYEpgRPBLED4QIKAjsBdwDI/0b/+/7b/sb+lf45/r/9If1N/E37Svpp+bz4XfhY+Jn4AvmL+Sj6vfox+3X7gfti+0D7Lfsf+x77Svum+xT8hPzj/Br9Iv0V/QX97PzO/L782vw8/fr9Cv9LALkBdwN8BYwHdQkuC78MKA5ZDzUQsRDdEMMQWBCbD7UOzg33DEYM0QuUC3MLYgtgC1wLOAvfCkkKjwnzCJEIQAjVB2QHHAcEB/AGsgYtBm8FnQTCA8UClQFMABH/+v0R/Tz8Tvsu+u34kPf/9Sb0E/Ls7+DtJOzP6tvpUulC6ZzpQOoR6+zrpuwr7Y/t4+0j7ljune4H753vX/A48Q/y5vK883H04fQc9Un1d/Wv9QH2dvYJ97r3hvhm+VH6PvsS/LH8Nv3R/Zb+ef+AALgBIAOrBEQGywcoCVgKVAsCDGUMnQyzDJYMQgzPC0cLrgoSCnkJ0QgXCFkHpQYFBpEFTgUqBRYFFAUbBRAF8QTFBIkEQAT4A7cDdgNAAyUDIQMeAxgDBQPUAocCLAK/ATEBjgDr/0r/qP4I/m390fw1/Jn79fpd+vT5wvm2+dT5Nvrg+sH7yfzl/fb+8P/GAGkB1QEnAnICpQKzAroC1gIIA0UDgQOhA5MDZQMsA/cC1ALGAr4CvwLvAmID6QNaBLQEBwVQBZEFywXxBQcGLQZ7BuMGWQfbB14IvgjnCNQIhAj7B0EHYwZkBV8EbgOUAs4BEgFWAJT/1f4a/lf9kPzd+0f7zvp0+j36GPoF+hf6Rvp1+pH6m/qT+oH6hPqW+ov6WPoo+hb6BPrg+bL5hPla+Uj5U/ld+VX5S/lN+Vn5e/m9+RT6bvrV+lv7D/zw/Or92/69/6oAqwGmAnwDJASgBPQELgVVBW4FgAWOBZEFjwWVBZsFhQVSBREFyARqBAwEwgOGA00DMgNCA20DpgPsAyAEKwQbBAkE6AOcAzYD2AKVAnUCbwJrAlMCJgLdAWwBzwASAD3/Yf6V/eT8WvwK/Pf7//sC/AP8D/wW/Av88PvM+6v7qfvQ+w78V/y3/CT9h/3U/Qv+Gf7r/ZT9Kf2w/Cr8pfsp+8j6ofq8+vL6MPuF+/77lfxO/S3+IP8XACMBVwKgA+kELgZmB4MIgQlkCiMLoQvDC40LHQucChYKfgnUCDEIqAdCBxAHEgcuB0MHPgcXB8YGWAbiBWcF6wR6BCIE7APoAxoEYASKBI0EeARJBPcDdQOwAq0BmgCh/73+2/0A/TD8Xft7+o75i/hm9y329vTG86LyrPEK8b/wwvAT8afxXvIZ88rzafTw9FP1jfWp9b713/Uc9oL2E/e793T4Nvnf+T/6Uvo9+gv6tvlX+RP57fjc+PH4PPmr+Sv6vfpU+9X7Ovye/Bb9qf1W/hb/5f/FALYBoQJtAx0EugQ0BXgFigV7BVYFJAX1BNYEuASEBDkE9AO5A3IDFgO6AnECIwLOAZABbAFMATgBVgGqARgCmQI1A9cDbAT8BIIF2wULBkQGiQa2BrsGrgaTBmMGKQbrBY8FCQV2BOYDQQOBAsMBHQGRACYA8f/l/+f//f9AAKwAIQGMAe8BSQKKArkC+AJRA6sD9wNBBIYEsAS9BLgElQQ2BKgDDwN/AgACnQFUARkB8wDoAOgA3QDFAKEAaAAuABcAGwAfADAAbgDMAC4BkAHzAT8CaQKDAosCaQIhAsoBYgHaAD8Apv8E/07+j/3X/Cb8fvvx+oP6MPr2+dn52/n5+Sv6bvrB+if7j/vp+z/8lfzg/Aj9E/0c/S39MP0V/fr8Av0l/UT9XP1+/aH9uP3e/SD+Wf5l/mf+g/6i/q3+u/7c/vv+H/9x/+3/agDkAHwBKwLFAj4DnwPkAwYEEgQSBAoE/APrA8oDlQNWAxIDxQJ0AisC3gGIAUIBIwEbARMBGAE5AWIBcwFwAWoBXAE7ARMBAwENARYBEQEKAQYB+gDcALYAjQBXAAwAuf9j/xL/0v6t/qT+pf6g/oT+UP4a/vX90/2v/Zz9nP2a/Z/9wP3q/Qn+Nf57/rH+sP6F/kb+8/2g/Vz9FP3B/ID8YvxK/C78Kfwz/DH8Jfwh/CL8LPxX/KT88Pww/YH96/1a/sf+PP+4/zAApwAxAdIBeQIaA8IDgwRNBQYGpAYjB3gHpgfAB8UHqAdiBwYHqwZeBiEG7wXEBZkFbwVXBWAFgAWlBdIFBgY3BmkGqgblBvYG5QbFBocGJQa/BVkF1gQ/BL4DWAP+Aq8CYQL+AYsBGgGQANv/Iv94/r39/PxS/LT7CPtu+gD6mvkz+eP4n/hV+Cz4NfhE+En4ZfiU+LT4z/jl+Mj4dfgp+PL3ovc79+L2kfY89gb2APYD9v/1DPYt9kn2Z/ak9vf2NPdR92v3n/fq9zH4c/i/+A75TvmT+fj5bvri+mf7EPzP/I/9Sf7v/n7/+f9jAL8AFgFgAYoBmAGsAdgBDgJBAncCtwIAA1IDqAP/A1YEswQZBX8F2QUWBkIGdAa1BvgGKQdFB1YHZwd1B3oHgwegB8EH0wfZB+MH7AfvB90HowdJB+sGhAYCBnMF7QRjBN8DlwOTA5gDkQOeA7cDvAPNA/sDEwT0A8wDuAOhA4QDZQMqA8sCeQJEAv0BnAFGAQABvACOAIIAeABoAGQAbQBnAEwAJgD0/7X/cP8k/8/+cf4f/uz93P3g/fD9Hv5g/pj+wf7n/vr+5f7H/rz+tP6w/sX+6P7y/t/+uv52/hP+sv1V/eb8evw0/BH8CPwd/Dz8T/xz/MP8I/11/bD9zP3J/cX90P3K/a39pf3J/f79Q/6i/gL/Of9N/1D/RP8v/yT/Kf8s/yD/Cv/v/sv+pP6U/p7+qP6m/qr+s/6q/qr+2P4c/1r/v/9eAPEASgGYAe4BFAIFAvcB7QG8AXwBWQFEASIBBgH/APUA2ACwAIcAaQBtAJsAyQDQAL8AtgCzAKEAnwDMAPwADQE4AZ0B4AHSAcQB5gH0AeYBCAJDAkQCHgIPAvwBygGLATwB0wCAAEoA6/9s/x7/3f5m/gD+9v3+/er9Bf5L/ln+Of43/jz+G/70/cv9gP1G/UX9Nf0C/f38Ef3j/KD8m/yM/EL8JPxX/Gf8PPwj/Bn88fvd+/X7/vvz+w78Qvxt/Kj88/wf/VX91/16/vv+kf9aABkBugF7AkoD6gNqBPsEggXVBQAGHQYuBjgGOgYyBi8GOwZIBlAGXQZuBnoGgQaKBpsGvwbwBiYHdwfeBxMICwgQCDIIIgjZB50HWAfTBkQG6gWPBREFrQR4BDUE3AOFAxYDigIRAqcBBwEyAF//nf7m/Vj99fyM/Aj8fPvw+mD60PlE+cr4dPgs+Nb3ifdd90D3Ivcb9xf39fbV9tb21/bP9ur2H/c590r3e/ek9633zvcd+Fv4efik+Oj4Kfln+Z/5xfns+Sv6b/qr+uX6D/sj+1D7qvsE/EX8j/z1/GX93v1O/p3+5P5H/7T/FQCCAPAANgFnAbQB9wEDAgUCLQJcAnoCmwK2ArkCwwLhAvkCDAM0A1kDZwN9A50DmQODA5MDuQPGA88D9gMcBDAEUQSDBKUEvwTwBCgFQAU/BUUFXQV2BY0FpAWvBaYFngWtBb4FrgWFBWgFXQVLBSwFAgW9BG4EOAQXBPkD5APWA7QDiQNsA1MDKAMKAw4DBwPSAo4CWwIoAvsB5wHgAcsBrQGQAXABPQHxAJEAOAD4/8X/l/91/1n/MP8B/9j+pf5j/iX++f3Q/ar9kP18/XD9dv2E/Yj9d/1I/fb8lvxA/Pv7y/u5+7j7sful+6D7nPua+6/7z/vg++b76PvU+7r7xvv++zr8cvyv/OH89vwI/Sr9Sf1V/Vf9aP2a/eL9Lf5//uP+PP94/7H/7v8JAPn/3P+1/4P/bP+G/7b/+v9YAKQAxADuADMBVwFlAaYBCgJGAmgCkgKZAnkCcgKHAoUCfAKGAocCgwKrAtQCuQKNApYCpAKLAoACnQK5As0C5ALfAq4CZAIWAuUB9wEOAswBWgEUAdYAcgA2AEUAUABHAGcAmACfAIkAWwD//6v/hf87/8b+nv63/of+Pv5l/pr+Uv73/fD91v17/Ur9P/0A/bL8kvxs/Ej8Zvx8/ED8Kvx0/Hf8FPz9+zr8L/wd/J38Tf2W/cn9Ov6F/n7+ff6S/pH+m/7A/sn+vv7Z/vr+//4n/4L/t/+3/9T/EAAuADUAUABvAIAAlQC5AOoAOAGWAeoBRQK3AgYDHQNBA44D0gMCBFIEsgToBP4EGAUdBfUEvQSIBEkECgTfA8ADogOPA4gDdANZA1QDbwOQA6gDtwPDA8ADsgOuA8MD0wO7A4oDXgM1A/cCuwKjApQCZQIsAgoC6AGrAWoBPgEMAbwAXwD9/4v/F/+9/nL+KP7f/Yv9E/2R/Cz82Pt6+y77Dvv0+sX6n/qW+on6cfpy+on6lfqJ+nD6SfoW+uP5t/mU+YX5hfl3+Vz5Wflz+Yf5jPmX+Z/5lPmU+cL5B/o7+m36wPob+2L7o/vm+xj8TPy1/EL9sf0O/oL+8/4//5f/EgBqAI8A0AA3AXEBfQGeAc4B3AHuATACeQKhAscC+QIhA0cDhAPIA/0DMARhBIUEoAS+BNME2QTbBNoE2gTnBPkEAQUTBT4FWwVeBWwFjAWUBYIFfAV3BVQFHwX0BMsEmARpBEIEGgTyA7gDZAMTA9wCqAJoAjQCEwLoAa0BdQFAAQQBwwCHAFkAMwADALr/df9G/wf/sf5+/n7+fv50/oP+kf5v/jn+Hf4B/tH9sv2x/bD9pf2j/ab9ov2c/ZL9ff1Z/S79Fv0x/W/9kv2h/cX95/3e/dz9D/4w/hL+AP4i/jf+J/49/oL+vf7l/hj/Uv+I/7j/3P8IAFoApwC0ALYA3wDqAK0AjgC0AKsAYQBQAH8AggBiAHEAiQBxAGAAdgCBAHwAlQCxAK8AuADSAMAAkgCSAKAAeABLAFkAbwBpAHkArwDQANoA9wAVARgBGAEjASUBKQE5ATEBAAHTALsAlgBnAE8ASgA/AEAAUwBZAEkANAAeAA4AGQAyADoAOABMAGEATwAnAAcA6P+5/5X/kf+Z/4//hf+d/9D/5//P/7H/qf+m/6r/xf/i/9X/qP+C/2j/Tf80/xv/BP8A/wn/+P7X/tf+6v7a/r/+1P72/u7+5v4P/zf/LP8Y/x7/FP/h/q/+pP62/sr+0P7K/sj+wf6m/o7+lf6f/oj+fv6i/sj+xv7B/tb+4f7Q/sT+xf65/qP+n/6w/sj+6P4U/0P/cP+T/6r/xf/u/xsAPQBVAHAAlADIAP0AFAEQARkBNgFVAXQBpQHaAQQCNQJ2AqkCvALGAuICAAMHA/0C9gLwAt4CwwKzArECpQKVApgCqAKaAnICWwJcAlYCSwJQAlkCUAJAAjECEgLeAaMBbQFDASQBBQHZALAAlwB+AFcANQAiAAMA0P+g/3f/Rf8Q/+f+uv5+/kf+Kf4Z/gb+7/3b/cr9tP2T/Wj9Pf0c/RD9IP1J/XX9lv2z/cv90v3N/dD90f3E/bn9wf3N/dT96v0R/i3+Nf4+/kH+PP5D/lv+Zv5W/lD+af6B/ob+hf6H/ov+lv6x/s7+4P7u/vz+Dv8s/1T/e/+i/9n/GQBFAF0AbwB+AH4AdwB4AHoAdwBvAGwAawBmAF0AUQBEADQAKAAhACEAIgAhACcALwAuACAAEgAUACsASgBhAGoAbwB/AJsAtQDIANYA2gDQAMEAuACyAK4AtwDKAM0AsgCYAJQAkQB7AGcAZgBfAEMALgA7AFEAVwBhAHoAlACiALQAzgDiAOYA4ADXANIA1wDmAP4AIAE7ATwBLgEwAUABQwE2ATEBMgEvASgBJgElASEBHgEfAR4BGgEXAREBBgH9APUA7wDtAO0A8AD2AAABCQEKAQcB/QDuAOgA7QDyAOgA2QDNAMUAwQC/ALUApQCaAJgAiQBrAFQASAA1ABAA6//P/7//uf+z/6P/kv+O/5D/hv9w/1z/Sf8y/yb/L/80/yj/Hf8n/zP/Mv84/0v/VP9S/17/fP+M/4f/if+W/5P/ef9g/1b/Wv9q/4P/lP+a/53/n/+c/5T/jv+L/47/mf+n/7f/xv/L/77/tP+1/7//yv/b/+v/9f/+/xQAKQAzAD4AVABrAHgAeQBtAGEAaQB3AGYAOQAXAAoAAwAGABcAHwAWABEADgD6/9//1//U/8D/qf+o/63/p/+g/5z/k/+I/37/a/9O/zb/J/8Y/wv/Df8Z/xz/FP8E//j++P4E/w3/B//2/ub+2v7P/sH+r/6g/pj+kP6D/nj+ef5//oj+kP6N/oX+h/6T/pn+l/6h/rj+y/7W/ub++v4N/yX/Q/9P/0f/Rv9i/4f/of+5/97/CAAqAEkAbACQAKwAygDrAAgBHgE1AU8BYQFsAXkBkQGzAdkB9QEHAiICRwJiAmQCYgJpAmYCVgJPAlkCZQJxAoICjgKGAnICYgJYAk8CSQJGAkECOwI2AikCGAIKAvoB4AHDAakBgwFKAQ4B3wC8AKAAhQBnAEkAOgA1ACgAFAD//+n/yv+u/5n/iP9z/17/Sf86/zj/O/8s/xX/Cv8N/wz/B/8B//f+8v75/gD/9/7t/u/+5f7C/qP+nf6V/n/+df57/nj+av5o/nv+jf6Q/pD+lP6d/qv+u/7M/tf+2f7b/uX+8v72/vT++v4J/xP/F/8c/x7/G/8U/wb/9/71/v/+AP/1/ub+2/7P/sP+uf63/rf+rf6h/qb+uP7E/sX+xf7N/tz+5/7t/vT+/P4G/xX/J/8x/zf/P/9G/0n/SP9M/1n/Z/9s/2z/c/+D/5L/m/+k/6z/rv+6/9n/8v/7/wkAKABKAGgAiwCuAMsA5gD1APgACgEtAUsBXwF2AY0BngGqAbwB0AHgAewB9wH5AfEB7QH7AQwCEwIZAhsCHwIsAj0COAIoAh8CHQIbAhUCBwL2AfAB7QHeAc0BywHNAcABsQGuAaYBlAGLAYoBfgFtAWkBaAFUATMBEwH8AOwA1gCxAIcAXAAyABIA+v/l/9H/wf+4/7P/qv+e/5L/g/9v/1z/Tv86/yP/Fv8a/yb/Nf8+/0H/R/9L/0b/Q/9G/0r/Tv9V/1b/VP9X/1r/V/9Q/0j/Rf9I/07/Vv9d/1r/VP9b/2f/cf+B/5H/of+8/97/7//y//z/DAAVABcAFgARABYAIwAoAB4AGAAfAC4AOwBEAEEAOQA4ADwANAAlABsADQD+//f/8P/i/87/vP+r/5T/cf9O/z3/Mf8a/wf//v7v/uH+1f7D/q7+pP6S/nP+Xv5T/kX+PP4z/iD+FP4Z/hv+Fv4Y/h7+KP4u/in+H/4k/jP+O/46/jj+QP5R/mT+bv5z/n/+l/6w/s7++v4t/1P/af93/4v/tP/u/xcALQBKAG8AigCeALAAxADZAOgA8AAEASMBOQFGAVYBYwFuAYABjwGcAbMBxwHVAeYB+gEJAhQCGwIXAhICEQIRAhQCGAIUAhACDQIIAgUCAALwAdwBzwG+AacBmgGSAYMBbQFUATkBHgEHAfUA7gDpAOIA3QDdANkA1gDPALcAnQCUAJAAhQB7AHQAbwBoAFoAPgAmAB8AHwAYAAoABQD9/+n/1P/D/7D/p/+x/7X/qf+d/5D/e/9z/3X/cP9p/2j/Yv9c/1j/UP9L/03/TP9X/3X/gf9s/1X/Tv9L/0n/PP8i/xT/FP8N/wL/AP/x/tT+v/64/rT+t/61/qj+o/6r/qz+pf6e/pj+kv6U/pn+mf6b/qj+rf6k/qP+rv6p/pr+n/6z/sT+zP7F/rX+uP7J/sj+uP60/rX+vP7K/tj+4P7o/vf+CP8T/xP/G/88/1j/ZP91/4n/j/+a/63/uv/L/+f/+f8CABkALwA2ADsASABQAFkAbwCCAIIAfgCMAKIArgC4ANAA5gDvAPgABAENARsBKgE1AUQBUwFUAVUBaAF4AXkBfQGPAaABpQGjAagBuQHEAcIBwQHJAdYB3wHjAekB8AHqAeYB8gH9AfgB7wHiAcsBwAHEAcIBtgGlAZMBhQF6AWgBVAFGATUBHwEMAQIBAgH9AOEAwQC5AK4AkACBAH8AbQBXAEwANAATAAgAAADt/9//1f+//63/of+F/2D/Uf9R/0L/KP8Z/xP/B//6/vH+6/7m/uX+4v7a/tf+2/7d/t/+5f7q/vX+AP8E/wT//f7y/u/+6f7e/uT+9v73/u/+9f74/vH++v4F/wT/Cf8U/xn/Jf81/zb/Of9R/13/WP9f/3P/g/+O/5P/kP+Y/6r/s/+t/6b/oP+a/53/qf+w/6L/i/+B/4D/h/+e/7b/tv+o/5//mf+c/7D/yf/W/97/5v/s//X/BwAcACQAIgAqADcANQAtACkAFQD5//X//P/x/97/zv+2/5n/hP90/2X/Y/9n/2b/W/9Q/03/Tv9V/2n/fv+A/4D/jP+R/5P/pv+4/7b/s/+4/8L/2v/0//T/5f/i/+j/7//3//j/8v/u/+v/7/8AAA4AEwAeADcAVABvAIYAkgCeALsA4wADARoBMQFKAWABcAF4AX4BiQGSAZIBjwGXAZ8BmgGTAY0BiQGHAYMBfQGAAYEBbwFfAWMBYAFKATMBIgEZAR8BIQENAfgA6gDVAMcAxgC3AJgAhQB3AGEATgA8ACAAAwDv/+T/3v/Q/67/lf+V/5j/hv9q/1n/Uf9C/zP/K/8s/yT/Ff8H//j+5f7Y/tb+1/7P/sT+wf69/q7+oP6m/rD+q/6e/pv+rv7C/sD+sv62/sD+vf7C/tb+5/7r/ur+5/7s/gP/Hf8w/zr/O/9C/1P/YP9j/2n/f/+Y/6b/pP+l/7D/uf+//87/3P/d/+H/7f/z//L/9P/2//v/CgAbACYAKgAtADUAQwBMAE0ASQBAAD0ARABDADEAJwAvADYAMwAvACcAHwAeAB8AGQAWAB0AIQAbACAANgBDAEAARABOAFEAVgBnAHAAbgBsAHEAdwB/AIkAlQCeAKEAowCpAKcAowCkAKYAowCkAKcAqQC5ANIA2ADRANgA3wDfAPIADQEQAQgBEQEiASgBJQEhASMBKQErASYBIAEgAR8BFwEMAQMB+ADjANAAyQDMANAAzwDGALwAuQDAALwApQCNAIAAdgBhAE0AQQA3AC8AKgAfABEACAD+/+j/2f/W/87/vv+v/5n/gP92/3X/bP9Y/0D/LP8c/w7/Bv8L/xP/Ff8S/xL/Ff8c/x3/Fv8P/wn/Bv8Q/yb/M/8w/zP/Q/9Q/0r/Pf87/0r/Yv93/3//df9x/4L/lf+Z/5v/qP+3/73/wv/N/9b/1v/Q/8z/1P/h/+j/5//p//j/BwAOABEAFQATAAwABwAHAAgABQD+//L/6f/l/+P/3P/X/9T/0P/B/7L/rP+q/6r/sf+4/7L/qP+k/53/kv+J/4P/fv9z/2j/Yf9i/2X/Yv9f/2L/Y/9k/2b/Zv9h/17/Yv9l/2L/Yf9o/3D/cP9q/2r/b/91/3j/df91/37/j/+e/7D/wv/L/8//3v/4/wgACAAQAB8AIwAkADcAVABiAGYAcwCMAKEAsQC8ALwAtQC3AMgA1gDWANgA5gD1APYA8gD3AAUBFQEcAR8BIAEjASgBKQEkARkBFgEfASgBIQERAQwBEQENAQAB+gD7AO8A0QC7ALQArQCgAJcAjwB2AFsAVQBVAEcAMgAlABoABwD7//j/7P/W/9L/4P/j/9b/yf/F/8H/wf/B/7v/sP+v/7D/qv+l/6f/pv+b/5j/nP+X/4n/hv+I/3v/Zv9f/2n/bv9v/3L/df9w/2X/Y/9s/3z/hP+A/3b/bv9t/3P/e/9//4L/i/+X/5j/i/+E/4z/lP+N/4L/gv+O/5r/mv+U/4//jf+H/4L/iP+S/5b/lv+W/5P/kf+a/6b/pf+h/7D/xP/E/73/xP/U/+L/6f/l/9b/zv/b/+v/8v/3/wIAAgD9/wsAIgAgABIAGQAtADEALgAyADUANgBEAFoAYQBdAF4AXwBZAFwAagBrAFYASgBPAFYAVwBfAGgAaQBmAGgAawBsAHIAegCDAI4AlACQAIgAiACNAJMAmgCkAKsAsAC1AKwAlwCKAI4AkACLAIgAhgB7AHAAeACHAIEAcgByAHwAfQByAGQAXQBdAGMAYwBcAFkAXABfAGAAZABlAF8AWABYAFkAUwBIAD4APABDAEcAQAA4ADgAOAAtAB4AFgAKAAEACwAaABcACgALABYAEwACAPf/9f/4/wMACgACAPH/6//q/+L/2P/X/9r/1P/K/8P/w//G/8f/v/+2/7n/xP/J/8v/0v/V/8r/wf++/7v/tP+2/7//vv+x/6r/rP+0/7v/vf+0/6v/pv+i/5r/lP+V/5X/jP+I/4z/i/+A/3f/df9z/3L/d/99/4L/jP+a/6H/nf+X/5f/nP+h/6f/rf+x/7H/rv+t/63/q/+m/6L/n/+X/4j/eP91/3n/gf+E/4P/gv+I/4//kP+Q/5L/kv+J/4P/jf+V/5L/kf+a/6D/nv+h/67/tf+x/67/rP+n/6v/v//M/8P/uf/A/8b/wf+9/8D/wf+//8f/2P/e/9n/1//c/+X/8f/5//z///8HAAoACgASACEAJQAdAB0ALAA/AEsAUwBbAGMAZwBqAG0AcgB5AHwAegB8AIMAjQCYAKQAqgCqAKYAqACvALIAsgCxALMAtwC3ALIArwCvALIAtAC2ALcAtQCyAK8ArQCwALcAtQClAJIAiwCKAIEAdQByAHIAagBfAFsAUQA8ACgAIAAgAB4AGwAWAAoAAAD9//j/7v/f/9T/yv/C/77/uP+t/6j/rP+t/6b/of+h/53/lf+R/5L/kv+N/4z/kv+a/6H/oP+a/5T/mP+l/67/rf+r/7H/vv/F/73/tv+9/8//2P/S/8r/yf/S/9//5v/l/+X/8/8CAAkABgAEAAYACwASABYAFAATABgAHQAYAA8ADQASABsAIwAmACIAIgAsADYAMwAoACcAMQA6AD0APQA2ACoAIAAfACQAIwAbABUAFwAYABEAAwD5//j/AAD///P/5P/d/9r/1//U/9D/x/+8/7n/vf+6/7X/uv/E/8X/vv++/8X/yf/K/8j/yP/N/9j/3P/T/8r/zP/N/8n/w//C/8X/xf/C/7r/sP+y/7v/wf/D/83/3v/p/+3/7P/r/+z/8v/7/wMADwAgAC4ANQA1ADMANAA9AEMAPgBAAFIAYQBYAEwAUABeAGIAYQBeAFoAVgBZAFgAUABQAFkAWgBTAFMAWwBjAGwAdQBwAGYAcgCJAIwAeQByAHsAfgB4AHQAbwBqAGoAawBgAE8ARQA8AC8AKwAvAC0AJQAkACkAJwAiAB0AFAALAAgACAADAAEABgAFAPv/9v/4//r//v8FAAIA9P/q/+z/7f/s/+r/4v/Y/9r/3//S/8D/w//K/77/rf+x/7v/tv+u/6v/q/+t/7r/xP+7/7D/rf+u/7f/zP/Y/8n/uv/C/8z/xv/A/8n/z//K/8X/wv+7/7r/wv/D/7r/u//J/9P/1P/S/8//zP/U/97/3P/W/9j/3f/e/9//5P/n/+n/7f/p/9v/1f/e/+P/3P/Z/93/4P/d/9r/1f/P/9D/zv/C/8H/0v/d/87/wf/M/9z/4f/g/9z/1f/Z/+7/+P/t/+b/7f/u/+X/4v/m/+f/5f/k/+L/4//2/woACgD9//j/9P/s/+z/9v////3/+//3/+7/8f8DABEADQADAAYAFQAlACoAIwAhAC4AOQA2ADEANAAzACUAHQAhACsAMQAxACoAJAAsADsAQgBAAEMAQwA4AC8AMQA0AC8ALgAvAC0ALAA0ADgAMwAxADYANQAuADAANQAzADQAOgA7ACoAHwAjACcAIQAXABIAEAARABIADwALAAcAAwD//wkAGgAfABUAEAAaACYAJgAeABwAIQAjABgACwAGAAoACAD+//f/+v8DAAcA///v/+P/5f/x//f/8f/q/+r/7f/v/+v/5v/l/+j/7P/r/+n/7f/z/+3/4f/d/+b/8f/0/+3/5v/l/+n/6P/f/9f/3P/h/9f/xv+8/8D/zP/X/93/2v/W/9v/4//i/9n/0//U/9n/3//h/9r/1f/b/+X/6P/k/+H/3//f/+P/5f/g/9//5P/l/+D/2v/b/9n/1f/O/8r/yP/P/9v/3//e/+P/6v/n/+D/2//Y/93/7P/5//v/+P/6//3//P/7//3//f/+/wYACAD+//f/+/8CAAUABwALAAoAEAAfACgAJwAkACUAJwAuAD4ARwA9ADUAPgBQAF0AYgBgAFgAVwBkAG4AbwBqAGIAUAA+AEEAUwBaAFQASwBGAEcAUQBYAE8AQwBBAEYASQBOAFoAYABfAF8AXgBSAEEAOgA+AEAAPQA2ACsAJAApACsAIQATAA8AEAAHAPn/8//0//P/7v/l/9z/2//h/+b/4v/a/9X/0//S/9f/3f/Y/83/yv/X/+T/5P/a/9L/0P/O/8n/uf+p/6X/qf+o/5//nP+j/6j/pv+k/6f/rP+x/7f/u/+1/6//sf+6/8f/1P/a/9f/0//c/+T/3P/M/8v/1//f/9//2f/Q/8j/yf/P/9P/1v/f/+T/2v/R/9L/1f/U/9b/4v/p/+T/5P/q//H/9v/5//T/6//p/+z/4//U/9f/5P/k/9X/yP/H/87/2P/h/+L/3P/a/93/3f/f/+n/7v/n/+L/6//2//f/+f8AAAkADQAPABEADwANABAAEQARABgAIAAbAA8AEgAfACcAIgAeAB8AIQAkACsAMwA7AEQASQBCADwAQgBLAFIAVwBeAF4AVgBUAFwAYgBgAFwAWgBXAFcAWABaAFwAYQBiAFYARwBGAE4ASgA8ADMALwArACcAJwAqACsALAAsACcAJgAtADEALgAtAC8AKwAgAB8AKgAxACUAEgAFAAIABgAGAPv/8P/y//z//f/3//f/AAABAPr/9//4//X/8f/z//v/BwAQABAABwACAAsAEAAEAPX/8f/x/+v/5v/r//H/7v/e/8r/wP/H/9b/1f/F/7r/vf/A/77/w//Q/93/4P/c/9b/0v/U/9f/1f/V/+H/7v/o/9n/0P/O/8f/wP/E/8v/x/+//7v/vf/C/8f/x//F/8X/y//K/73/uv/J/9v/4P/c/9j/1f/R/9H/0//U/9f/2//Z/8//x//H/8X/xv/O/9f/1f/O/9D/1v/X/9H/zv/M/8v/zP/S/9b/3P/p/+//7v/5/xUAKAAiABgAGwAaAAkA+////wYACQAaADMAOwArAB0AGwARAAQABQAWACAAGwAZAB0AJAAqADEANwA6ADwAPQA/AEYATwBQAEgARgBLAEgAPAA5AEMATQBJADwAMgAuADIANAApABoAGAAgAB8AGgAlADcANwAqACsAOgA+ADYAMAAuACYAGAAOAAoACgARABoAGgAdACkAMAAeAAAA+f8IABQADQABAAAACwAaACEAHAAPAP//7v/i/+L/7P/u/+P/2v/l//f//v/2/+r/5v/u//T/7v/9/2AAMAEwAvgCOAPdAgkCCgEoAHz/9/6a/nr+j/6u/rn+xv7m/gX/D/8P/xb/Gf8W/zf/lf/2/wMAzP+s/8H/wf9//zj/Jf8r/x3/D/8c/yX/Bv/g/ur+Gf8s/wz/1v64/rH+qv6e/qr+4P4n/17/h/+2/93/6//5/yIATgBXAGQAwABhAekBHAIIAsUBYwESAQMBGgEWAfcA8QACAeUAgQALALD/bf9F/1b/nv/k/wQAHABTAJgAywDrAAUBDQHmAJsAZABgAHwAkQCWAIAAQQDi/4//ZP9C/wL/s/55/l3+Sf5C/k/+V/5K/kL+Z/6l/tH+8P4f/1L/c/+V/8z//v8JAAgAIABGAFEAQwA2ADAAIAAEAN//qv9v/1X/df+4/wUAXAC2AAUBQgFrAWwBRAEfAR8BKQEPAeYA2ADeANEAvgDIAN4A1QC/AMoA9AAOARQBKgFXAX0BhwGBAXQBYgFHAR4B5gCkAGYALQD2/9H/1/8AACsASABZAF4AWABSAE4AOgAWAAUAFwAuAC4ALAA8AEEAHwD1//P/FwA3AD8APgA6ADIAHgD3/8T/of+m/7v/vv+t/6b/nf9s/x3/7f7z/gD/8f7i/vf+Jf9R/3z/sP/i//n/+//8/wMACwABAOP/v/+l/5v/jv9w/1D/Rv9U/2v/d/9z/2D/Rf82/z7/Tf9U/1j/av+I/6P/s/+3/7b/sv+8/97/BQAcACQANABNAFcASgA1AB8AAQDg/9D/1f/V/77/mP9x/0r/H////vr+E/9D/4b/0v8UAD8AVgBYAEYAKQAYAB0AKAAtAC0ALwApABIA9P/k/+D/2v/S/9X/6P/y/+j/2v/n/w8AOABLAE4ATABHAEIATQBnAHkAcQBhAGkAiQCnALMAtwDBANQA8AALAQUB0gCMAGIAZwCBAI4AggBfADQACgDf/67/h/+F/6j/1f///zQAcACdAK4AuwDQANkAxwCfAGsAKgDv/9L/x/+0/6P/uf/o//3/8//0/w8AHgAUABAAHQAeAAcA9//8//3/7//n/+X/0f+x/6b/r/+y/63/vP/e//j/DwBAAHgAgQBUAB0A9P/O/6f/l/+a/5L/ev9v/3z/iP+Q/6D/t//B/7v/v//b/wIAGAAbABUAEwATAAgA8//r//7/FgATAPj/5P/b/8v/s/+x/83/8P8DAA0AEwARAAoABQAHAA4AFwAaABEAAwAAAA0AGwAiACoANgA9AD4APAA1ACEACAACAAgA/v/c/8L/u/+0/6r/t//c//7/BwABAP7//f8AABAAMABVAG8AeQBxAFQAJQD0/8//q/+A/1z/Sv9C/0D/TP9p/5L/vP/g//3/FQAtAD0AQgA9ADUALAAnACsANgBDAE0AQwAjAAMA7//V/6n/kP+h/8L/1f/h//n/HAA5AFAAXABaAEQAHQD3/+H/2P/R/83/0//Y/8v/vP/L//j/IAArACIAFQALAAYADQAaABkAAwDl/8H/nf+R/5v/l/98/2//g/+f/63/v//b//H//f8IABoAKwA3ADgANQA5ADsAJAD6/+P/5P/d/8T/s/++/9T/3//h/+z/+//5/+3/8v8BAPv/5//n//X/+//+/woAFAAaACoAOQAxACoAPgBjAHcAbQBFAAwA1/+w/5D/hf+V/6j/rv/C/+j/AwAIAAkAAwD4////HAAmABIAAgADAAkADwAVAAkA8//l/+L/2f/M/7v/rP+u/8f/1P/H/8b/4/8AAAsAGgAsADIAMAAxAC4AKAAlACIAFAAIAAgADwAZACYAOQBSAHIAjACcAKsAuwC2AJsAewBfAEwATgBoAIUAoAC/ANIA1ADiAAABDQEMAScBWAFsAVkBSgFGAT0BNAE2AToBNgE6AUQBSQFIAUoBVwFpAXgBfQF7AXkBcwFiAVYBXQFvAXEBYAFUAV0BagFxAXoBjAGUAY0BjgGdAaABjgGKAaMBwAHJAcQBwQHFAccBswGLAXMBfAF+AVgBHwH8AOoA0gC0AJ8AnQCnALYAxQDTAN0A4gDfAM0ApgBwADsABwDQ/5n/ZP8r//z+4v7N/qT+dP5P/if+6v2w/ZH9iP2H/YL9dv1w/XP9Z/04/f/80vyn/HH8O/wH/NH7qPuX+4z7gvt7+2r7S/s0+yv7Ffvv+uH68voK+yT7Rfta+1j7VPtg+3f7kfuj+637v/vp+wv8EfwX/DX8U/xa/Fz8a/yE/Kj85Pww/YD9z/0T/kf+cf6W/rf+3f4P/0L/dP+r/9//BQAhADsASQBaAHwAogC+AOgAMgF+AbwBAQJKAn0CpQLOAtkCuAKWApMCmQKbAq8C1AL/AjMDcAOkA8YD4QPxA/QD8APkA8gDrwOqA7ADsQOsA58DiQNtA0MDAwO/ApcChwJ8AnICcQJ2AoACjQKRAooCiAKLAnoCVgIwAgoC1gGgAXQBTAErARgB+AC9AIMAXQA6ABIAAQAGAAkADQAkAD0APAAsACMAIwAbAAUA5//H/6z/kP9y/1n/Sf8+/zb/Of9C/0j/Tv9h/3z/jv+V/6H/sf+3/7P/sf+8/83/5f8HADUAXwByAGoAYABgAFcAMQAIAP3////z/+z/BgAyAFUAdwCsAPYATQGwAR4CkwIKA3wD3gM2BHwEogSxBMkE8gQfBVYFowXxBTIGaAaCBmcGFQaaBfwEUATFA38DgAPKA10EMAUvBjEH8AdHCE8IFAh1B3cGZgV5BK8DCgOVAj0C+AHGAY0BKQGqADIAwP9U/xz/IP8//2z/sP/n/9T/b//A/rv9XfzN+j752Pe79vf1ifVp9ZP17/Vb9rT25Pbn9sf2gfYO9oj1EvWt9Ez0+/O+84DzNvPt8p3yQPLs8cHxtvHF8fnxVfLU8mjz+/Nv9M/0LPV69az11fX89RT2NvaG9vH2S/ea9wL4ffjy+GP51PlB+rT6NPu7+z38vPw1/av9M/7M/l3/6v+SAFkBJALoAqYDUATYBEgFqAXpBQcGEQYWBigGXga4BioHuwdyCDYJ7AmVCjALoQvfCwgMLgxLDGAMfQyhDMEM2wzzDP0M5wysDFkM/AupC3QLbwuTC9YLLwyeDBUNcg2bDZYNcg0kDZkM2wsMCzoKaAmVCMgHBQdMBpsF9QRwBBkE3wOuA5UDmAOWA3UDQAPxAnMC0gEzAYoAtf/B/tr9Bf0y/Fv7ffqp+Q35x/i++Mv48Pg1+Y756Pko+iT6xvkm+WL4j/e/9gn2f/Ux9Sv1XfWh9eH1F/Y89k/2U/ZW9nD2rvYA91333/eD+A75X/mK+Zb5ZvkJ+bn4hvhn+HD4u/hD+fz5yfp6+/37dfzn/C79WP2T/dT9B/5R/sv+Vf/O/zgAjQDMABYBZAF+AWYBXQF2AZIBtwH2ATECXQKdAvcCRwOGA7sD2QPnAwEEGQQJBN4DwAO1A7kD1wMBBCAERwSABJkEdAQyBOMDfAMZA+ICzQLCAswC7QIOAzgDdwObA3gDIwPCAloC9wG6AZ8BjgGEAX4BeAF/AZkBngF3AUoBQAFYAZkBCQKIAgcDpgNzBEcFEQbbBnoHsQeMByIHXAY1BdkDYALeAJz/7P7b/mX/lQBFAiUEFwYRCMQJ1go1C+0KBQq0CFcHCwa7BHMDTAJGAWEAuP9C/9/+l/6U/ur+pf/DAB0CeQO9BMwFYwZVBpkFLwQfAqz/Kv3F+qf4GfdA9v/1Pfbz9vv3JPlK+lL7E/x9/KD8evwK/Gb7n/qw+aD4ivd49nD1ivTe81vzA/MA82TzFfTq9M71sfaH90T41/gr+Un5Rvkc+cD4QvjG91z3AvfD9q32xvYM94T3Kvju+Lz5hfo9+9b7R/yQ/LT8ufyx/Lf82vwm/Zb9J/7N/nv/HACWANoA8QDmAMIAjABbAEsAawC3ACgBxwGTAnMDRQT+BJ0FFwZlBpQGsgbJBuIG/QYJBwQH+wboBrAGVAbpBX0FEgXBBJ4EpATWBFYFKwYpByMICgnRCVYKhgpiCugJIwkuCCgHJwY3BW8E6gOzA9EDPQTnBKEFSQbYBlEHpge+B48HIweLBuAFMAVyBK8D/AJbAsEBNwHNAG0ADwDX/+L/FABdAMgARQGlAdABwgFpAboAyf+q/nD9SfxZ+6P6K/oJ+jr6k/ry+kT7dft9+277Q/vu+oX6Lfro+a75kfmU+aD5p/mn+aH5m/mb+Y/5Xvkb+eD4q/h7+Gf4dPiN+MH4I/mg+Rz6lPr0+if7Q/tr+5T7qPvB+/T7Mvx4/NX8N/2A/bL9zf25/Xr9SP1B/WP9qf0m/t/+vv+tAIkBNgKmAtECvwKBAicCtgFKARQBKQFyAeIBhQJQAxIEqQQXBWgFlAWMBVwFIwX2BM0EpQSEBGsEXwR4BLgE+AQfBTsFYgWCBY0FiQV6BVwFOgUrBTcFRgU2BQYF0gSnBHYELwTVA3cDJAP0AusC7gICAz0DiwPAA9UDyQODA/8CbALeAT0BpQBIACgAQQCwAGMBIQLzAgIEIQX8BYoG0galBgYGLwUoBMoCMQGr/2P+dv0O/S79vf3P/mMANgL/A58F2waBB6EHVQeQBmsFNwQGA7oBbwBX/1j+X/2U/BD8xPu7+xT8yPzV/UT/2AA0AkkDFAREBJIDJQI0AN39XfsO+SP3tfXr9ND0PvUe9lT3qfj++Un7W/zx/Bn9Bv2p/PL7DvsX+vr4xve39tD1AfVv9Dj0P/R79A/18/X19gD4IPk8+iv71/tE/Gf8LPyL+6D6lvmS+Kj3+/ao9rD2Fffr9yf5jvro+xn9CP6l/vL+7f6U/gz+h/0a/dn84Pwp/Yr99/1z/un+Pf92/5j/of+q/9P/FgBfAL4ANAGdAeoBJAJEAkYCNQIbAvkB5QHqAfgBDwJRArsCKwOZAwkEYgSTBLgE2QTRBKAEZAQiBM0DfgNYA18DnQMdBMIEZAX7BYkG7QYFB8oGRwaUBdYELASxA3kDjQPvA5wEhgWBBlUH3AcJCOgHlwcmB5EG9gV+BSkF5QTABLwErAR2BDIE/wPpAxAEegT+BIEFEgajBg0HSQdKB9oG6gWzBF4D6wGNAIb/1f5u/nn+/P65/4YAXAEPAncCpgKvAmoCwwHfAM3/lP5d/Vb8ffvL+lD6Gvon+nf69fp1++f7SPyE/Jf8kvxy/Cv82fuQ+zz70vpu+g76jvnz+F740PdW9yn3Zffs96n4pPnA+sv7p/xA/Xf9Rv26/Oz7EPti+vL5sfm6+R/6tvpY+wj8tvwq/Vr9c/2P/bb99f1O/q7+FP+L/wQAbADEAAYBFQH/APAA9wACAQQBAQH6AAMBMwGUAQcCbQK7AgsDaAO/A/sDJwRABDIECgTtA9oDsQOAA2oDagNxA4IDlQOJA18DMAP/AtECwgLrAkMDsQMXBFgEfgSaBJMEOgSaA9sCDAJEAaIAMgDp/9b/+f8xAGIAiwCUAG4APQAjABYAHgBVAKQA4AAbAWYBmAGdAacBwQG5AZYBiQGMAXIBPAH2AJYAEwCR/zH/DP8v/57/XwB4Ab0C5QPVBI8F5gWiBewEFwQ3A1ECjgEFAa8AkQCsAOIAEgE6AVsBewGzAQACTgKzAk8D/AN4BLwEyQRnBIIDUwIJAaj/TP4y/XX8FvwY/GL82Px3/Tv+9v6H//b/PABNAC4A5/9p/77+Af43/VT8cPug+t35MvnG+KT4tvj6+G35/fmj+lD74vtA/ID8qPya/FX8+Pt9+9H6C/pR+af4Dvif9173TfeA9wf4zPit+Y/6TPvV+zb8ZvxO/AP8qvtB+8P6XPot+hP68PnW+dX57fkf+mb6tPoP+4b7D/ye/C/9sP0Q/l3+pf7Q/sj+of5z/kj+M/5D/mz+mv7E/u/+Lf+W/yAAqwBDAQsC5QKTAxYEdwScBH4ESAQABJIDKAMUA1EDrwMjBLAEQAW/BScGZAZxBn4GqAbfBhwHbgfPBywIhAjCCLoIcAgMCJoHGge1BocGeQZ7BrQGPQftB4MI5QgjCUkJRwkECYII4Qc9B6YGOwYCBuAFxgW0BaAFdQU7BQIFvQRjBBUE6QPMA6kDeQM2A9cCXQLEAQUBNQB4/9z+W/71/aj9c/1j/Xz9n/2o/Zn9hP1o/Tr97fx9/O/7Uful+u/5Pfmi+Cj43ffU9w74b/jZ+Dz5mPnz+Uf6cfpU+gv6x/mX+XP5Xfld+WT5Y/lg+XT5nPnK+fL5Ivpo+s76Vfv0+5P8F/1y/bP95/0G/gb+2/2V/VL9M/1G/YP93/1T/tz+ev8kAMAANQGBAbgB8wE1Al8CWwI+AisCIwISAgUCFAIyAksCaQKSAqwCsALAAvQCMANoA7MDGQRvBJYElwR/BEYE7gOIAxoDoQI3AgUCEgJIApsC+QI/A18DcwOCA20DLwPyAsoCmQJKAugBiAExAfMA3wDvAAQBBgH5APcABAEGAfcA7ADtAO0AAgFDAYkBgQEnAa0AGwBb/4P+y/0//eD8yvwT/aP9Vf4M/67/MgCxAEEBygEqAlQCWAI1AuoBdwHaAA0AGf8g/lT90fyX/KP8+fya/Xf+f/+jAMYB0QKyA1QElQRlBN4DEwP4AZcALv8B/hn9dfwq/EP8nvwd/dD9zv76/x8BIAL6AqED/gMHBL4DGwMWAr0APP/I/YD8fvvW+pD6pfoZ++z7Bf0z/lT/XAA9AecBWAKYApMCKgJSASUAz/5u/Qz8u/qm+fb4v/gH+c/59vpB/JH93f4JAOUAWQFxATcBsgD0/xP/G/4Z/Rn8J/tX+rv5bfl6+ev5t/rE++n8Ef4t/x8AwAACAfYAoQADAC7/UP59/a386vta+xX7FftP+8L7XfwT/d39tP6F/zgAswDxAAcBBQHaAHUA8P9o/93+V/72/dL93P0I/lr+xP44/7f/QQDIAEgBwQEeAlICZwJyAmICKALQAWwBBQGrAGcAQgBZALkAQgHSAWwCEgOhA/8DNQRWBGUEbARyBHMEagReBE8EOgQ1BE0EaARpBGMEbgSFBKwE7gQ/BYAFrgXMBdIFxAWyBZkFZwUoBfUE3QTaBOQE+gQKBf0E1QSpBHwEQATzA6wDewNZAzoDHgMMA/QCywKdAmUCEAKoAVQBIAHzAMAAfAApANb/i/88/+n+qf6H/n/+kP6x/sf+tf6E/kH+3f1Q/cH8Svzh+4r7Zvtr+3D7dPuF+5j7nfui+7X7y/vV+9T70fvM+7r7lPte+x374/q/+q/6svrK+vH6Ivtq+8X7H/x0/Mf8Df02/T79Lv0e/RX9Cf39/Af9Mv1r/aH90v31/Qv+Hv44/mv+tv4V/4b/AQByAMUA8ADxAOEA1QDHALkAxQDlAAcBNQFsAY8BlAGYAawB2QEjAooC7QIvA1sDhwOkA5IDZANBAyUD/gLcAscCsgKdAo4CggJ+Ao4CqgLIAugCAQMIAwMD9gLaAqYCWAL+AasBZwEoAeYAoABmAEcANwAhABQAJQBHAGwAlACmAI4AWgAfAN7/kv8x/7T+Lf6//YT9c/1o/VT9S/1k/Zb91/0Z/kb+YP6C/q3+zf7c/sn+hP4i/rv9Tv3e/ID8Rfw1/D/8VPx6/L78I/2n/Tr+wv5F/9X/WwCvAMwAuQBuAP//kf81//P+0P7C/sj+6/4o/2z/rP/y/0wAvAAtAaQBNQLKAjcDagNiAyMD0AJ+AhoCnwEwAekA0wDvABsBOgFXAYgB0gEyApkC9QJCA4EDsAPIA7MDZgPyAmsC1QFDAcgAYgAeAAUA+f/q//f/JgBOAG8ApgDsACkBTwFYAUYBIQHmAJMAHwCS/wz/nf4y/sz9if1s/Wb9d/2P/an93f0s/mr+k/66/tD+vf6O/lj+Jv70/bj9d/08/QX90vyz/KT8n/yj/LD8yPwC/Vn9o/3c/SH+bP6k/sH+v/6d/nL+SP4X/uL9tf2f/aL9s/3R/Q7+WP6P/sX+Cf9F/2v/kv+6/9P/8P8YADsAUABgAHIAjgCpAKUAgQBbAE0AXQB+AKMA2QAdAV8BqgEBAjICNQI4AkcCRAI1AiwCHwIWAiwCVgJ0AogCogLLAvQCBgMLAw8DDgMLAw4DCgP8Au8C1QKoAogCgQJwAk0CKwIQAgUCGgJEAnQCogK7AsACxwLJAqoCXgLsAXcBJAHtAK4AYgAkAAQAAgAaADsAZQCXALsAyADLALUAfgA4AOz/mv9R/xH/z/6d/of+ev5v/nP+ef5z/mv+av5w/ob+qP7U/gX/Mf9J/0f/HP/R/oP+Of7r/a/9lP2F/YX9rv3z/TP+Yv58/or+pP7D/tz++/4i/zr/Tf9o/3f/Yv8s/+v+wf6s/pP+d/5y/on+uf4G/13/rP/5/0QAfQCwAOAA9wDtANEAqQB8AFAAJgAMAAMA9P/n////MwBiAJEAzAD6ABkBNwFZAXIBdQFjAVIBSgE3AQ8B1wCZAGYASwA3ACgAKgAxADwAZACaALQAuwDUAPUACQEMAfIAtwB0ADQA6/+Z/07/I/8O//X+6v4I/zP/Sv9r/6X/3f8EACAAJgAQAOn/qv9V///+oP4+/vz97/39/Q7+Hv48/nT+tv7k/g3/Pf9o/3//hf99/27/XP8v/+z+o/5S/gH+y/2m/X39dv23/R3+gf7k/kv/sf8KAEcAXwBNAA4Awf+H/1P/Df/C/ob+af5o/nD+fP6q/gD/Yf/I/zcAlQDXAAcBJQErASUBCgHHAHUAMAAIAPL/1P+s/6D/tv/X/wcAXwDOADQBjAHYAR4CXAJ8AnUCTwIEAqIBSgEHAc8AogB8AGEAcgC1APwAMgFqAagB4QERAi4CMQIiAgEC0gGnAXkBMQHgAKIAdgBQADEAKQA8AGAAjgDTACgBbAGaAcYB2AG8AYEBMAHQAHwAPAD2/7P/h/9t/2H/cP+d/9P/AAAiAEIAbQCgAM0A7QDxANUApQBjABkA1P+O/0L/Dv8C/wf/EP8m/0j/ef+6//L/EQAmADUAOABCAFAASgAtAAwA8f/a/8X/pv98/1T/N/8t/z7/Zf+Y/8H/2/8GAFAAkACiAKIAmwB/AF0ASQAnAPD/w/+n/47/fP9+/4z/nP+u/8f/5v/8/wYAFwA0AEwAWABcAFUASAA0ABEA5/+6/4L/R/8f/wf/+f72/v/+Ev8//4X/zf8JADEAQQA8ACMA8/+5/3r/KP/J/oX+YP4//ir+Mf5J/lz+bf6S/s7+CP8v/1L/bv9v/1n/Pv8o/xD/7P61/nv+Uv4t/gr+Bv4g/jj+Vf6U/uT+Lf9o/5b/tf/J/8//wP+g/3T/S/8q/wr/8P7n/un+9v4U/0D/cv+3/xMAZQCiANUA/gAXASQBKAEcAQEB3AC9AKgAjQBoAFYAYwB+AKMA3AAgAWkBtQH8ATUCZgKRArICtgKVAl4CLgIHAtoBpQFyAUwBQwFMAVsBdwGnAd8BFwJLAmgCcAJuAl4CMwL/AdQBsQGKAV8BOAEhARAB9gDZAMgAvgC1ALIAugDIANMA1QDSAM4AxgC2AKEAfABIABYA7P/I/6b/ev88/wv/AP8F/wH/AP8Q/yn/QP9P/1L/S/85/xv/+/7d/sD+pP6K/m3+Sf4n/hL+B/7z/dn90P3e/ev99f0R/j3+aP6Q/rL+wf6//rn+s/6n/o/+Z/5D/jf+Nv4p/h7+J/5G/mv+l/7Q/gz/Of9e/4r/uf/b/+7/+v////7/8f/V/7n/p/+d/5v/p/++/97/EQBNAIUAvQD7ADIBVAFqAXwBfgFtAVABLQEHAdgAowB0AF4AXgBlAHMAjwC6AOYADgExAUUBTgFaAWMBTwEjAfoA1gCrAHcARQAaAPX/1f+9/7X/uf+//8n/5P8DABEAEwAdACoAIQAEAOT/wf+Y/2//Tv8w/xX///7w/u3+/f4S/yb/QP9h/33/lP+q/7r/t/+q/57/l/+U/4r/cv9T/0L/Q/9G/0r/W/98/57/xf/3/ykATgBpAIYAqwDPAN8A2gDRAMYAsgCZAJIAnQCgAJsAoQC+AOgAEwE2AVIBbwGSAa8BuwG3Aa0BngGOAXUBUQEuARgBCgH7APkACgEfAS4BPgFSAV8BYgFZAUkBOgEyASgBDQHeAKcAdQBQADQAFQD0/+b/6//v/+z/7/8BABEADwD8/+X/3f/W/77/kv9n/z3/Df/a/rT+mP56/mH+U/5P/kv+TP5W/nD+kv6r/rf+xv7b/uT+3P7P/r7+pP6F/mP+Qv4o/hv+E/4N/hb+M/5V/nP+mf7H/vH+Ff86/1//f/+V/57/nf+Z/4n/Zf9A/yj/Hf8V/yD/Rf9w/5T/v//9/z8AcQCcAM0A/gAXARYBCwEBAeIArQB9AGQAVABEAEAATwBnAIUArQDhABwBVgGIAbIB1gHsAekBzwGeAV0BHQHrALoAgABUAEkATQBOAF4AiQC5ANwA+gAZATgBTgFPATgBFQHxAMEAhwBWAC4A///X/8v/yf/C/8L/zv/Y/+b/AwAfAC8ARQBpAIEAfABrAE0AFgDZ/63/hP9W/zT/K/8y/0P/XP99/6n/3v8GABYAHgApACwAGwADAOv/0f+2/57/h/92/2v/Yf9b/2T/eP+C/4j/o//M/+r/+v8IAA8ADQACAPD/1/++/6r/of+k/6v/rP+p/6z/uv/G/8//0//S/83/zP/O/8z/x//E/8D/tP+i/5H/jv+f/6//rf+t/8f/6P/s/9r/yv/A/7j/tv+0/6T/jf+E/4X/hf+E/4v/lv+c/6L/rf+8/8v/1//i//L/AAAEAPn/5f/L/7H/m/+I/3f/bv92/4r/o/+9/9f/7v8BABQAJAAxAD4ARAA9ADMAMAAsACEAFAACAOj/1//d//H//f8HABwAOABRAG4AkACuALgAtACvALEArwCmAJsAkQCLAIcAiwCNAHsAXABJAE4AVgBZAGMAdQCIAKYA0gDyAPMA5gDgANMAtgCXAIIAbwBiAGgAcQBnAFIATwBdAG0AdgB6AH8AlQC4AMoAxAC6AK8AlQB5AG4AZgBKACsAHAASAAQABQATABoAGQAmADcAPAA7AEkAYQBxAGYASAAxAC4AHgDv/8P/vv/H/8L/wP/J/8f/sv+o/7X/xf/K/8L/tf+s/63/qv+W/3//cv9k/07/QP87/zT/L/8y/zb/Nf86/0j/WP9h/2T/YP9Q/0f/T/9V/0v/Nf8i/xP/Av/1/vL+9P7v/ub+7P4E/yD/Kv8l/yH/K/87/z//Mv8q/zH/NP8q/yf/Mf83/zr/SP9Z/17/Xv9t/4f/lf+e/6//wv/J/8L/uv+8/73/sv+n/7H/yv/e/+z/CAAsAEEASwBSAFIATwBXAGwAewCAAIoAmACiAKQApgCuALUAtQC1AMQA3wDrAOIA4gD2AAMB+QD0AAcBIAExAUEBVQFhAWUBYgFXAT4BJQEYAR4BKQEhAQMB8AD3AAQBBwEGAQgBCAEEAQEBAAH+APcA5wDWANIA1QDKALUArACrAJ0AjACCAHIAWgBZAHkAmQCvAMYAzwC8ALAArwCQAFAAGgD4/93/zv/K/6z/b/9C/0H/Rv8w/xX/Ev8e/yr/Pf9Z/2z/df99/4b/gv9o/0P/Kv8i/xH/6v7F/rL+q/6y/sn+zv60/qr+z/70/gP/Gv86/0T/TP9y/47/gf9q/23/hf+b/5f/eP9f/13/Wf9R/1f/Zv+C/6//0P/Q/83/1P/W/9n/3P/H/6b/n/+q/6j/m/+L/3v/df9z/2v/Y/9g/2n/jv/D/97/1f/N/93/8P/g/77/tv/B/73/wf/h/+r/y/+7/8j/1P/d/+7//f8MAB0ALAA5ADsAIwAPABAACAD//x8AQgBDAFQAfgCGAHIAawBnAHMArADhAOUA5ADxAO4A2QC8AIsAZQBhAFwAVgB4AKQApACaALQA0ADGAKQAjgCOAJUAkQCEAH8AgAB6AHIAbQBgAFMAUABNAEsAVgBgAGAAZgByAHYAdgB2AHMAdQB5AGEAOwArAB4AAgD7/xIAJAA1AEwAVgBoAJEAmgCEAJgAvgCsAIwAlQCbAIUAZwA+ABcABwD2/+X/8v/6/+r/CABUAHYAbgBrAFIAIQAFAPH/zv/B/9D/zf/A/8T/wv+h/3H/Uv9W/3b/lv+u/8D/z//l//b/6f/W/9H/w/+s/6T/kv9t/2v/hP+B/3P/g/+Y/6b/u/+8/57/mv+4/8H/s/+3/77/pv+O/5f/nv+G/3X/h/+U/4//lf+f/5f/iv9//3H/df+C/3j/dv+P/47/bP9p/4P/j/+K/33/d/+H/5T/ff9v/4r/mP+F/3z/gv+J/5T/jv9v/23/lv+y/7L/wf/c/9z/0f/g/+7/4v/e//r/CgAFABgAMQATAN7/yf+4/6H/rv/h/xIAQwB3AKQAwAC0AIUAawBsAFsAQAAzAB4AEQAwAE4APQAuAEQAWwBRAEUAYQCLAIUAcQCbAMIAnAB6AJQAqQC5ANoA0ACQAGUARwAhACcARQBFAE8AYwBPAE8AfABrADYAVAB3AEoAPwByAG4ARgBTAGUATgBAAD0ALQAnABoA/P8BACMAIwAQAA8ABADs//D/EgAwADUAIQAIAAsAFwANAP3/9v/v//D/9//v//D/HgA6ABQA4v/P/7v/rf+z/6P/jP+y/+P/2//Y//L/+v8eAHEAdwAqAA4ADQDc/7//yv+1/6//2P/V/7f/zv/X/8L/8f81ACoAEAAKAOL/3f8WAA0Ax//C/+L/1//C/67/kf+U/6L/jf+V/8v/1f+//9T//f8WAC0ALgALAPT/8//b/6f/g/+J/4r/YP9M/4L/qf+g/8X/AQD1/97/+v/5/9z/4P/j/9z/8P/p/8v/6P/t/5n/j//T/57/Tv+e//L/1f/v/zAA///J//j/AQDY//n/LQAqAD8AXgAmAMj/mv+A/3b/of/Y//7/MgBiAGwAbwB6AGYAPgAjAP//3f/r/xEAFwATACQAJgASABYAMgA6ACQAFQA7AH8AlwBuAFAATwA2ABIAGQA2AD4ASwBsAI4AlQBxADYAFQAUABcAFAAYADwAhAC5AKoAjgCEAGQAQgBJAEoANgBJAF8AQAA2AF4AaABPAEoATAA9ACcAGQAlADQAAgC4/6z/vf/H//f/PwBkAHQAcwBjAHIAgABJAAMA8P/f/8j/2f8BABgAEQDe/6n/sP+3/5z/qP/D/6f/v/9IALUAvwCSAD4AEgBBACIAgP8r/0P/TP+E/9z/wP+f//v/GADa//f/8v9g/0//8/8tAPf/4/+3/3n/iP+M/1v/Wf9a/0//xv9PAAoAtP8QADUAvv+V/7P/f/9s/7v/yv+N/3b/kf/g/0gAUwAUAPn/1P+n/9L/7f+I/1v/1v86ACQAEwAyABoAuP9v/2f/Tf8m/3r/IABdAEAAZwCXAFoAKgBlAGIA4P/F/zoATwD2//H/GADh/5//tP/O/7X/wP8xAJUAaAAvAIoA0AB5AEgAgwB1ADkAZwCjAHQALAAqAEkAKQDK/6b/3f8BACAAhAC3AIQAnwD0ALQAHADt/+b/sf+w/9j/rP9q/53/FwBbAFAAOwBLAEcALABYAHYAAACv//3/7v9o/4j/BQD8/+z/IgDu/2H/JP80/1//g/9s/1b/e/+l/+v/VQBAAJj/UP+l/9L/o/+h/93/2f+g/7L/5v+q/0b/YP+n/3j/SP/G/1sAPQAIADQA9f9l/6//WQBAAAkASwBcAE0AhQBQAJn/UP9t/5H/8f9QAEUARABpADoA9P8DABYAHQCBANoAoAB2AOYAEwGHABsAKAAmAD4AugDwAH4AFAAXACcA///S/9L/7P8YAHQA0gDnAO8AIgEoAd0AkgBIAPj/+v89ADcA8//j//f/CwA+AFAA9v/N/zsAlQCMAH4ANwDY/0AA6gClAP7/zP+1/7X//P8DANj/9P/2/9b/DAAOAHz/OP9s/1n/Lv9m/5//ov/i/1wAVwDM/6r/DwANAJ7/kf/D/7//u/++/2f/5v6+/gP/b/+//+D/rP85/1H/GABMAKL/Wv+L/2v/bv/w/x4A3v/u/y4AFwDR/7X/vP+g/1f/RP+Y/+f/CwBeAK4AdAD5/8X/wv/z/3AAfgDR/6D/YwDTAHAAFQDu/6T/e/+6/xoAQQBTAMIAWAFoATABNQHYAOX/Vf9L/xb/A/+V/0oAiQBfACMAIwBMAEkACADJ/9j/SAC0AMQAtQDTANEAOQBl/yT/Qv/3/rj+Qf/h//n/DwBXAJwA3gC7AAgAff9q/3v/jP+L/7z/YwCmACoANgC4AHYAMwClAH8A2f8PAFgA5//w/4EAVgDM/7r/ov9Q/zz/Mf8g/5n/PwA7ABwAngDfAEUA3f8FAK//3f7Q/of/x/+A/4r/p/9R/1f/4f+W/8D+Bv+7/43/hP8vAGsAkgB8AdcB+wBmAGgAGgDf/0IAhABjAIEAwwC7AJMAVQDb/5H/e//3/of+C/+5/+L/VADxALgAMwBQAH0AEABp/x//Mf82/03/2v8vANf/w//9/4T/3/7R/qn+h/4f/6T/sP8eAKYAjQBEAA4AvP+S/27/BP/y/nf/2P/2/0AAcgAkAKX/Xf9E/1X/yP9qAKoArwAOAXUBSwHmAKoAQACW/zj/Vv+L/8n/NwB9AHQAnADuANYAngCvAJgARgBMAJ4A6gAvASsB1ACyAKgAGQBw/3b/2f/x/wEAagC6AIwARQAjAPD/zP/n//r//f8/AIkAfgBUAGAAdQBEAO3/v/+c/2//kv/W/7n/kv+q/4j/S/9g/3//l//b/+7/6v9EAHkATgBZAG0ANwAsACMAyf+m/7v/kf+J/7v/rP+h/9j/4//Q/9v/zf+8/9b/zv/N/xsAWwBcAFEAGgDU/+b/9P+k/47/2v/m/9z/UQC6AIMASABFAPf/t/8AACAA3/8PAIoAowCyAOMAuwCDAJ0AjgBFAFEAmAChAJ0AywDrAMoAiwA0ALr/d/+h/8L/r//V/xAA5v+7/wkAWgAtANn/zv/W/6L/fP+c/6r/n/+j/27/I/9B/0n/vv5s/rr++f4F/zj/fv+7/+D/0P+4/7n/qf99/07/O/9u/9P/HAAwABQACABCAD8Ayf+s/wEAEgAKAEEAXwCbACABKAGzAHUATAAmAHYAuQBwAF4AwwDcAKEAgABGANz/s//Z/+L/wf/D/+X/+v8RABgA2f+Y/53/p/+P/57/0v/q//n/KQA/AOv/fv+G/8r/r/9c/1r/ov/s/xYA9f+X/1r/YP98/4z/fv9U/1n/t//0/8j/xv9AAHYAFQC1/3//UP9y/8H/2f8AAFsAewB3AIMAZgA9ACYA0v9//5L/uv/i/0EAYAAeABwATAA7ACcASABcAFoAYAB5AI8AgQB0AJQAjwBUAEEAJwDP/7X/AQA1AD8ASgA0AAsAAgADAA0AQgCpACABXQEwAQYBSgFoAbYAz/99/17/Bv/w/kb/k//l/1kAeQBKAEYAPAADAAEAJgASAPT/CQAiAAIApP9M/0r/V/9A/3D/7v83AFsAhgBpABUA+f/y/7j/hf+C/4T/cv9K/yj/Nv80/9n+pP74/k3/df8CALsACQFEAZABVgHaALoAfQDV/2b/Of/1/gL/p/9QAJcAvAAJAVgBegHMAYkCIAM3AxMDmQKpAcAAFQB9/yb/AP+2/oD+if6T/rr+Cf8d/yf/jP/l//b/KgB6AJoAnQB1APT/Q/+s/l/+cv6g/rX+7/5F/0b/+f63/ov+kf70/mD/f/+Z/9P/6f/R/7H/iP9Z/zb/Lf9c/5n/hf9x/8X/5P9s/xj/I/8O/xL/iP/m//H/HQBoAHkAiQD8AIYBlwFKAQEBkwDj/4X/nf98/xv/Hv9q/3j/fv+5/7//c/9M/3T/qv8UAP8AGQLUAjADUAMUA5YCIgKbAdwASQA8AF0AWQBYAGoAZQBaAFoAQQAyAIAAAAFrAckB/gHQAYEBYQE5Ad0AgQBEAAsA3P/V/+H/2v/1/2oA3gAPAXIBLAKpAr8CqQIvAk0BlAAUAG//zv5t/vX9QP2z/Ir8jPyS/MX8PP2s/dj9Gv6r/iT/Uf9z/4n/Zv8h/8b+TP4B/h3+Y/6a/s/+DP8l/93+Vf72/a/9OP3r/CL9W/1n/dv9sP5E/43/vf+i/27/jv/h/ykAjQAEAUQBOAH+AJQA5/8q/8b+wP7G/v3+v/+tAEUBlwG1AZABbAFjAVEBeAHzASYC8AHfAdUBYAHZAKMAgABPADkANQBIAJ0AHQGGAeYBWwKyApoCVQJdAngCLALJAbgBngFPATEBKgHqAK0AjgBMAB8AOwBAABcAGwA5ADUAOQBUAGgAdgBkABwA1P+s/4L/X/9Z/1P/SP9b/4r/pv+E/zn/Bv/f/pr+ef6s/sj+qP6p/sH+s/7E/vb+5P68/tP+3P6+/uv+Z/+y/6//ov+T/17/IP8e/0//Zf99/8P/+/8FAB8AQQBKAHQAtAC4AKUAsACkAIgAlQCDADUAFQAhABQALABwAIEAhQCvAJ4AWABtAL8AyAC1ANkA8QDUAOkAWgG/AcwBpwFyASUBzgBrANX/Uv82/yj/4v7e/jb/Sv8U/xD/Nv9Y/4v/uP/W/ygAhQCbAKgA4wDkAHkA/v+q/1T/6v6t/tb+Gv8R//P+Av/7/tP+2/7v/uD+BP9a/4b/vP8SAPb/gP95/8D/m/8w/w//Jv8y/0j/av9r/0n/Rf97/8v/FABGAGUAmwDlAOIAkABwAJYAkgBZACwABgDy//L/z/+h/8T/DgBDAKIAJwFqAXcBhwF7AVIBNAH9AK0AewBHAPz/6v8bAEcAbACUAI0AdwCHAI8AawBCADAAKQAfAAAAyv+I/z//DP8Q/yL/Fv8a/0j/ff/C/zMAlQC4AMgA0QB8AMn/VP9a/27/bP+U/7z/sv/Z/yYACwDA/8b/tP9g/2P/g/8j/9H+Bv8M/8D+0P4i/1b/sP8XABQABQBMAHcAYgCDALIAewAqACIAEQC7/33/h/+T/47/xv9OAN8APwFmAWEBQQECAZMAIAD8/yYAYwCQALYA7QArATQBCQHvANQAfgA+AFQAYAA6AEYAgAB+ADYA2f+J/2f/Zf9l/43/7f9IAIsAswChAIYAoQCWACsAzv+a/0n/Iv9i/43/bP9c/0z/DP/8/kD/aP9z/8T/LwBZAGkAeABVADAAQQAkAJj/Ff/c/rX+r/7v/g7/9f4B/wr/vf6L/sv+Hf9k/9z/UwCVANcACAH3ANoAzACdAGMAOgAJAPr/QwB+AGMAQgBBADUALQAwAA4A+P9DALgAAAEeARIBzgCNAIUAjwCAAF4AOwAvAFEAfgCIAJQAuAC4AIEASQASANj/3/8eAB4A5v/k//3/8v/y/woA9v/d//7/GAAJABcAKwD4/6L/bv9a/1z/ZP9c/2j/q//1/yQAVwCKAKgAxwDfAMIAegA5AAkA4P+4/4j/Zf9s/4//v/8HAFIAagBVAEEAOQBGAGEAYAA4ABkA+v+o/1f/S/9O/y7/KP9N/1r/Yf+o/xIAWgB6AG0ASgBTAIUAqAC5AKQAJQCZ/6b////u/5L/Uf8l/wv/HP8e/xj/e/8lAHUAbABkAEUAGwBQAMsA/wDqAOkA4wCkAFoANwAoAA8A2/+F/y7/8P7L/un+Yf/b/wIA+f/5/wMAJgBqAJQAhgBzAHEAXgBRAHUApwCrAH0APQAKAAkAKgAiANX/lf+l/9D/xP+P/3L/bv9u/4X/rv+//8P/7/80AF8AbwB/AIcAawAVAJD/Gf/e/r3+kf6A/qj+5P4T/0v/kf/O/wIAIgAbAAQAAAADAPv/8v/p/9P/tf+b/3H/Jf/T/rb+4f4y/3X/pP/W/xIASQBsAHAAWgA7ABQA4//M/wEAaACzAMgAvACdAG4ASwA4ABQA2P+u/7z/4//w/+//CQAuAC0ADAD3////IQBgALEA+gA1AVkBRAEPAfkACQEQAREBKAE0ARAB1QCfAGMALgAgACQAGgAbAEMAhQDSAC4BdgF/AV8BNQH8ALUAeABIABsA8v/J/5b/a/9O/yH/6f7m/hv/PP82/0L/eP+2/9//4v/K/8L/yv+s/2n/N/8h/xL/Ev8Q/+z+x/7W/v3+Ev8h/yn/I/80/1//af9a/3r/tP/H/8z/3f/X/8T/2P/0/+r/2//i/97/3f8FADYAQgAuAPv/mP8p/+X+zf7P/vH+Pv+n/xEAZACdAM0A8ADwANkAzgDUAN4A6QDwAOwA4ADFAJAAUgAjAAgAAAAPACUAMwBNAIAAtQDWAPQAJAFbAXYBYgErAegApwBzAE4AGADI/4//nP/g/zEAdACRAIAAVgAgAOf/yP/K/8f/xv/p/xQABADO/6v/iP80/73+Yf5A/lb+lv71/mb/y/8ZAFIAcwCCAJUApQCOAFAAGwD5/9n/t/+N/1b/L/8i/wb/3/77/l7/wP8UAHgAyQDhANAAnwBDANr/fP8x/wn/C/8f/1f/wv8VABIAEgBWAJIAiQBvAG0AfQClAMMAnwBbACAA0/+B/3P/kv+W/6H/5/85AGwApADdAP0AHwE/ASEB2QCpAH4APAAEANb/hf8v/xb/G/8l/1z/tf/n/wAAQgCUAL0A0ADfAM0ApgCQAH0AUQAfAPb/y/+k/5X/kv+Z/77/+f8wAGcApQDGANAA5gD6ANkAmgBsAFAARABBABkAxv+d/7P/uv+l/7T/1//R/83/9P8TABMAFwD//53/If++/mP+I/4c/if+N/6T/jb/w/8oAJMA6wAEAeAAhAALAML/n/9E/9f+2/5C/5z/4f81AHMAlQDCAOEA0gC9ALMAhgBEACYAEADc/7b/sf+R/zr/4f6z/s/+Pf/W/3kAOAEAAoUCtgK7AoEC8QE0AWgAif/R/m3+Gv60/Y39wf32/Q/+N/5c/mT+kf7+/l7/mv/v/1MAigCZAKMAjwBWABcA3f+h/2v/O/8H/+f+8v4N/x3/J/8w/0D/TP8m/77+bP5z/qX+2/40/6T/8f8uAIYAygDUANkA4gCzAFUADADg/7P/lP+D/0//Av/N/qL+Zf5A/mb+w/4x/6n/MwDXAH0B+gFGAnoCjwJgAv4BoQFNAf0AvgCGAEsANABRAGkAZQB+AK4AtwCvANMACAEgAUABewGvAd8BKwJ4ApgCmAJ7AioCwQFvASgB2wCjAI8AkACmANAA8QADARIBEQH8APEA3wCoAHcAfQCUAKIAvQDfAOAAtgBnAOr/Zf8Y//z+4v7f/hj/aP+b/8T/5f/X/6f/f/9b/zn/Mf8s/xL/Ef9M/5T/yP/y/w8AEwAVAB0AEwD2/93/vf+P/3r/iv+p/9f/DQAhABAA///1//j/HQBVAHgAiwChAKwAngCDAGIAMwD//9b/pf9h/0P/ZP+C/4f/tf8HADUAQgA/ABYA5f/U/67/Tf/2/tL+z/7Z/vD+Cf8U/wr/+f73/gf/EP8O/xP/Kv8y/xf/8/7N/pL+Yf5P/iv+/v0I/jb+TP5q/q/+8P4p/4b/7v8YAPn/yP+c/1P/+f7J/rP+j/5y/mb+V/50/tr+O/9j/37/n/+7/9f/8v8PAEUAcwBgACYA/f/V/6v/pP+m/4r/gP+d/6H/m//d/0wAmADOAAEBFAEQARIBCwHrAMYAtgDEAMwAygD3AEIBXgFqAZABkgFuAW0BZwE0ARUBCwHgALIAiABNACQAGgAJAAAAAgDp/+H/IQBlAIEAqQDrABwBLgEfAd8AcgATAPT/8//S/7P/wP/P/83/4f/2//L/9v8bAEIAVQBmAIAAggBLAAQA3f+1/3H/Nv8Q/w7/Tv+0/wYANgBUAH0AwwD2APIA7QD6AOgAuQCTAFAA7/+x/5T/Xv8l/xb/Gf8Q/x7/Vv+T/8n/BgA8AGMAigCZAIIAYwBNADcAJQAMAOH/vv+p/6T/yP/8/xQACQDW/4v/b/91/1n/Q/9g/4L/tP/9/x0ALAB3AMMA3ADuAOgAwQDGAO4A+QAPATkBPgERAcYAawAgAOj/r/+E/1H/Ev8Z/1n/cf+K/9j/CgASABsA+f+q/47/ov+0/9r/DwA0AFwAdwBcADUAIwD0/6D/V/8h//H+4/4D/zD/U/+H/8H/yf+d/3X/Zf9l/3v/rv/q/yEAZgC4ANsAvACfAJIAcwBgAHUAiQCuAPUAGAEIARkBPwFKAVkBYgFHAUkBfwGbAZgBpwG2AbUBsQGeAXEBRgE7AUABLgEYAR8BHAEHARsBMQEQAQABFQH8ANQAvQBdAL//R//s/pP+Wf4//lf+rv7//jz/h/+t/6r/t/+O/xz/7/4I//z+9f4A/+z++v4u/wn/qv5z/jb+F/5r/sn+8/5b/+3/KwBDAG4AXAAQANn/nP89//z+9/4a/23/yP/6/x0AQgBSAGcAhwBjAAQA0P+q/2D/NP8w/xn/A//t/qv+cv50/pL+1v4p/zr/Rf+V/8n/vP/H/8T/of+w/8L/g/9T/2n/fv+T/6L/cP82/0P/Xf9e/3b/pf/K//j/MwBJABgA1f+t/3n/OP8p/0b/bv/K/0QAgwCmAOEADwEkATQBHwHzAN4AxwCmAJMAgwBuAE0ABQC9/6j/pf++/xUAVgBmAKgA7QDdAMYAwwB/ACwAGgAJAOT/6f8BAAMABAABANv/pP9t/yv/5v6y/pH+gP6K/qb+r/6g/o/+ff5l/lr+Xv5w/of+pf7g/jj/ff+r/9r/6//Y/97/5P+p/17/KP/5/uD+2/7F/sD+3f7s/gX/M/9E/2T/sf/J/6f/pf+r/6P/xf/n/+3/HABcAGUAcACQAI8AhQCGAF0AJAASAAoA+P/j/9n/8/8UAAkA8f/f/6z/ef+D/5//tv/0/0MAawCJAMgAAwEWAR4BLAEhAQgB+wDRAJMAjwCUAFYAKQAsABAADQBdAI0AkwDaACIBHAEkAVQBcQGIAZwBmwGrAb4BsgGvAa0BlwGlAcABmgF0AZMBuwHeAQkC+wHFAbgBpgFqAU8BVQE4ARgBIwEtAS8BawHJAfUBEgJYAogChwKUAqkCmAJ8AlECAgLFAZ4BYgE6ATgBLAFUAcsBLwKQAjkDywMLBDkEMATSA2ADvQK9AcwAHwCI/yL/8f68/pv+rP67/qj+i/5s/lX+Lf7m/bj9vf3T/Qb+Y/6m/rT+w/7d/tn+0/4T/3v/sP/b/ygAMgD1/9v/qP8Y/7P+if4c/sz96v38/Qv+cP66/sT+Cf9p/4//p/+6/5//gP94/4P/l/+M/4P/xf8FACIAiAAMATcBZgGxAYIBEgEGAQ8B3QDXAP4A9wADAVsBlwGNAZoBuAGaAWwBXgE6ARsBNAE3AfMAsACAADsA4/9h/7b+H/63/ZL9r/2y/aP98f1N/lH+ZP51/hT+0P3c/YX9Bv3y/Oj85vw9/W39cP25/db9p/2y/Zj9P/1q/a/9dv2H/dv9q/2V/df9nv1o/cH9tP1g/an99P0K/rT+Xv9W/2X/k/83/+T+3P6B/hz+Cv7E/X39pP2q/ZD94/0W/tj95/0U/sj9q/3v/cP9dP2b/Zr9U/12/br9v/3+/VH+Nf4v/oX+oP6I/pn+kv6C/sz+F//5/sz+yP7E/r3+tP62/gD/if8DAFUAiACnAO4AUAFeARcB3wDCAKEAjAB+AIQA1wBKAXsBgwGPAZcBxAESAhgC5AHkAfYB5AHjAfUB/gE3ApgC4wInA1UDUANOA0QDAQPMArYCdgJNAl0CQAInAmMChAKJAsYCvwJfAlQCagIvAiICTgI6AjQCZgJLAvcByAGeAW8BVgE1AR4BNAFOAXMBoQGlAakB2gHwAewB/gHeAY0BaQFSAQ8B5gDpAOoADwF6AekBIAI1AkECKgLnAaoBewE9ARYBEQH9AO8ADgEtAT4BRgETAbwAjABcACMAKQBoALoALAGAAYcBdAFGAfEArgBtABEA//9QAKYABQGFAeQBHAJKAlACKwLvAZMBOwEKAeIAzQDtABkBFwEDAQMB8gCoAGEAUgA5ABEAMQBlAGoAnwAfAX0BvAHzAdoBkAFJAdcAYAAiAN3/jP+D/6v/3f85ALgAPAGtAewBIgJVAjgCBAIaAhgCyQGpAagBVQHQAFgA4P9a/9b+gP5J/ur9ov2r/Xn97PyV/Fn8C/z+++D7dftW+1/7H/sr+3P7S/tJ+7r7uPtk+2X7TPsJ+/76zfp/+nP6LvrC+c35vflI+VL5nvlr+WT55fk++oP6IvvI+zH8hvzd/Dr9eP1w/Ur9Mf0o/Uf9h/3U/Tv+qP4e/6X/0P91/zn/Ov/+/qz+kf6H/qf+/v5R/6X/9v8bAGsA3gDJAI0A3QANAbkAqgDhANIA2AArATYB/ADwAP8A7wDKAKAAhACCAIoAgABxAJUA1wDqAPkANQEnAb4AogCwAGMATQDCAPYA3AAnAY4BjwFyAVUB/gCYAEkACQD9/ywAfQAXAdYBVgKtAggDLgMKA9ECmQJvAk0CDgLXAdgB0gGzAbsBuwF0AVABdwFgAfMAqQCWAGwANgA7AFgARwBEAIoAugCgALQA+gD+AO4AAwHmAMMA9QADAdUA/wAbAbYAeABeAMf/Vf+H/4f/Uf+V/+b//v9dAM0A6wAQAUIBTQF2AZQBXwFXAYUBYgEwAT8BHQHOALwAoQBKAA4A7f+s/3P/Yv9O/z3/Qf8w/wn/BP8O//b+6f7//gX/Hv98/+f/QwC5AB8BVQF4AV4BFgH6AL8AMQDz/w0A9f/n/w4A///2/0UAXQAmADkAjwDvAHAB5wEvAnICtQLmAuoCmAI1AhAC5AGCATEB/gD0ADABWAEpAQsBJAEdAdUAcQAgAOb/uv+o/6L/hv+U//L/OQBGAFQAUAA1ADQAIwDk/77/xv/S/9//BABRAJ0ArwDLADUBrwFVAmsDqwQpBjYIRArjCz8NIg5yDm4Oqg0lDMAKcQkKCCoHdAZpBfUE5wQIBPMCNQLsAIf/zP7X/bD8fPy9/NP8Pv2V/Uf9Cf3s/Db8Pvuo+kn6Gvo7+ln6Yvp8+lH6tPkc+WP4A/eq9fP0HvQ48y/zVfMp89/zH/WU9Uz2tvcq+E34g/k/+hj62frr+0H8Bv30/ev9IP75/v7+mP7M/tv+rP7s/iP/Fv9N/5n/xf8FAPP/df9U/5P/h/9N/0v/e//Y/14AuQDCAOUAXAGpAY4BbwFRAeYAdwAfAD///v05/b/8Bfxs+yn78PoH+5b72PvJ+zz89Pw6/Wf9uv3H/dj9Wf6q/oL+hf7T/h7/f//q/y8AnwBVAdYB+gEIAvwBxQGhAaABhAFrAa8BKwKpAlQDBQRxBAMFzAUQBv0FNgYpBqMFgQV9BfYEngSmBFQE+APNAwUDAQK5AYUB2QB6AIsAlADNAB4B9ACMAFEA5/8s/27+kf2c/Db8Yfx2/Hj8yPxK/dn9Rv4r/s/92v3+/c39tv3o/Sf+m/5C/7f/GACxAF4B/wGKAtwC/QIPAwoDzgJUAuMB2gH/AfsB+AH8AdsBsQFTAYMAyf9p//T+kf6M/pr+vP4i/1z/Uv9e/1f/KP8Z//z+yv7v/lH/mv/w/1kAoQDcABUBEAHJAIkAaQA/AO7/qv+M/3z/iv+x/9j/OgDRADQBhAH/AU8CeQLEAucC2QL/AhYD7QLeArcCTAIYAhACzgGiAboBygH/AV0CYAItAjcCKQK/AVwBIQHZALMA2AD6AAQBOQFyAXYBiwGdAV0BNAFbAV0BRwFnAVEBEwEXAfcAgQA2APb/ov+p/8P/nv+1/+7//P9VAM4A7ABXAWMClwMvBTMHFAlOCyMOgxAsEowTNRQlFNEToBJ4EGQOcQxKCoYIEQdCBbwD6QLbAUIAjv6n/Mn6kPlx+A/3iPYp9+z3wvjg+Yn60fpc+3377/qb+l365/kN+nP68vk++fP4Mvjo9oj1vfP78fvwEPAN79PuQu/d7wLxkfL480z1qPbY99j4l/kB+mP6DPvj+6P8SP0q/kL/GgCtACIBOQEIAegAqABGABUA6v/I/xkAbgA7APX/1f+M/zr/AP+y/qP+Ff+t/zcA0ABNAagBIgKMAnMCAgKjAUQBmwCt/4X+VP2F/AH8YPvb+q76k/qi+vb6/fql+pL6wPrq+hL7Dfv8+nL7Mfyl/BL9w/2V/pH/owCQAV4CFwPFA44EJwUyBfUExQS3BLgEdAQGBC8E2gRmBfQFmgb/BlgHzAfzB+QH1QeJB1AHlge6B1EH8wbiBrwGVwa7BfMEPQS8AzMDiQISAtQBfQE0ASgBwgDK/+z+LP4V/db7mvpl+c744vjZ+OT4ofmI+iv70vtD/Dn8Nfxe/G78lvwN/aX9bv6O/5EAFAGAARsCagJWAlMCVAJAAm8CpgJ/AnwCwwK+AqUCwgKOAh0C/AHAARgBfQDx/1j/IP9C/2P/uP9pACMBuAEhAkUCFwLEAX4BLAG1AG8AgwCXAKMAvACLADAAEQDI/zD/2/6p/kz+L/5C/gD+xv3e/d/93P0X/jv+Uv64/iH/Ov9f/7L/8f86AKoA/gAtAWUBegFJARQB2wByACEADQDm/7X/sP+v/7T/3P/2/wsAYgDIACQBsAFPAtsCZAO4A9kDGwRABAMExQOkA5cD5gNSBGYEeASgBHkEKgS6A8ECpgH8AHcA3/9g/+H+lf7J/gf/9P4D/33/UQB4Ae0CugQKB8YJqwyBDwYSCxR4FSoWDhYgFWsTUBFKD0kNGwv+CDoHtQU6BKACuACk/qv8v/ra+Fr3afbZ9ef1wvbQ97n4vvmw+jz7kft9++n6lPqp+oX6Zvql+rb6ePou+mT5+Pdo9pz0kfLa8GfvAO4q7Rrtbe0P7gLvHfBc8a3yz/PG9LP1ovat99n4F/pr+8j8HP5o/2UA4wA1AZUBzwHRAb0BsgHlAWECwQLMArMCjQI6Ar8BGgFFAIb/Nf8z/zv/Zv/S/2kAIAHRAUAClAL/AkgDUgNOAzcD/ALBAokCNwLVAWABzgAxAIT/t/7g/RL9XvzI+0H72fqe+l/6Jfoq+jr6GPru+dT54flZ+hb7xPuh/NH9Av8rAEwBAQJaAsACNQOdAw8EegTyBMgFzwaAB88H/AcECNEHVQeGBocFuwQ/BN4DiANcA1QDbQOlA7MDbAMdA/gCyQKBAj0CCgIUAnIC1AL8Ag0DCwPMAl0CxQHnAOL//f4+/pH9Fv3I/Ib8ePym/LT8kfx4/Fr8M/w8/Er8Mfxh/P78qP1c/h//qP8pAOYAdAGtAfQBOQJeArMCFgNCA4ID6wMVBA0E9gOTA+4CRgJxAWoAjf/c/hj+av36/Lf8uvwI/Vf9lv0H/qj+UP/5/48A9QBhAQMCowICAzIDPwMxAyUDAgOQAvQBeAEAAWMAuP8E/0z+x/1m/d38UvwQ/P37CfxG/In8zvxh/SH+rP4t/87/bAAVAc8BTAKgAhQDcQN+A3ADQQPHAkQCxwEjAYsAKwDO/4j/kP+u/8H/7/8WAAkAAgAQAA4AJgCFAAsBtQGGAkwD+gO0BFIFlwWKBUYF1ARTBNcDVAPPAmgCIgLlAbUBkAFMAeIAfQAYAJb/Fv+w/nP+mP5G/08AuAGmA94FJQh6CowMBg4ND6wPrQ8uD1oOJQ3MC5IKNgm7B3YGSgX5A6oCXwHo/4T+Yv1g/JH7A/t3+gf6//kf+g767fnP+a35pfmt+Zj5ifmm+dD5AvpE+mP6VvpT+kz6BPp5+eP4VfjC9w73P/Z99ff0o/RY9Cf0QPSY9An1ifUH9m/21PZH96T33fcD+BD4Mfir+Fz5FfoO+1b8s/0j/5cA1AHkAuEDkwT9BGQFrwXLBfgFOQZUBlUGQAb+BaoFPQV+BKED+wJsAuEBowGzAdYBBQI1AkoCQAIDAnIBsADn/wr/Mf6c/Vn9VP2L/fX9cv7Z/gj//f7H/mH+wv0H/V380vtO++L6yvr7+iP7M/tV+4n7t/vT+8f7qvu4+/X7TvzW/ID9K/76/vX/1QB+AfsBMwIrAgsCxwFrATkBJAEJARsBbAG8AQACRwJ/ArIC7AIHAwMDEQMqA0EDbgOzAwQEbQTgBEQFqAX+BRYG7gWqBU0FzwRDBMYDYAMHA7wCjgJzAkoCCgKyAT4BsgAaAI//Of8X/wP/Bf9B/6T//f87AFAAOwAHAKf/Jf/D/oz+ZP5w/sT+L/+W/w8AcgCSAHkAJQCf/wn/Yv6r/Rz9y/yY/In8sfwA/WT9zf0V/kf+iP7A/tv+Bv9X/7X/EgByAN0ATAGsAe0BFwIlAgwC0QGNAVkBOwEjARUBKgFhAZcBxQHuAQ8CGgIJAuYBzgG6AZoBkgG5AdcB4AESAmoCoAKhAoMCWgI3AgYCqQFPARoB6QC8AKwAogCRAJ0AzQAGATYBQwE2AUYBbAFkATkBGwECAeAA0ADcAPEABgEVARoBDgHvAMwAugCxAJwAigCTALIAywDWANEAuACPAFsADACU/xT/uf6E/mb+Zf6L/ub+iP9eAEUBOQI2AxkE4wSmBUMGogbdBgsHJQceB+sGnwZfBhoGrgVCBeoEeATtA4kDRQPvAoQCFQKwAV8BCAGYACwA1v+B/yf/1f6I/kb+Cf6v/TX9wPxk/BT8w/t3+z/7QPt4+7n74/sL/DT8SvxB/B38zvtM+8H6Vvr6+Yb5CPmp+HL4Qvj696f3VPf09o/2TfYp9gr2DPZd9vH2pPdn+C75/PnW+pz7O/zL/Ff90f1J/tP+Wf/U/1YA4gBjAcEB7wEGAhUCBgLbAb8BvgG4AbMBzQHvAQECEQIsAjQCEQLVAaQBjgF5AVMBLQESAfkA4ADLALIAhQBLABMA6P/G/53/ef9y/4n/mf+M/3v/gP+K/4r/iP+G/4X/j/+l/7D/o/+f/7T/yP+//63/vv/p/wkAHAAxAEIANwAQANj/if8m/8D+aP4j/uv9wf3A/QX+gv4Q/6D/QQDwAIcB8gFDApkC7AIyA3kDzAMcBF8ElgS+BMsEugSLBDsE1gN2AyoD3AKAAigC5wG7AZoBcwE3Ae4ArgCBAF0ANAAXAB0ARwCFAMoABAEnATkBRgFBASYBAQHmANcA2wACAUwBmQHLAesBAAIBAtsBgAH3AFQAr/8S/4b+H/7p/cr9rf2b/Z39n/2T/Yz9kP2I/XT9fP2y/fH9Ev4s/m3+0P4o/1D/Uv9W/3H/mv/A/+T/EABPAJsA7QA1AV4BZwFhAVEBHwHIAG8ANAAJANj/qf+O/5T/tP/b/+z/7v8BACsAQQAzACgAQgBtAIkAkQCUAJ0AswDTAOUA5wDrAAEBHwEsASQBHwEuAUUBQAEVAekA3wDtAO8A2AC+ALIAtwDJANwA5ADkAPEADAETAfQAzgC6AKEAYgAHAKf/RP/e/n/+Jv7G/Wn9MP0d/SH9Nf1g/aL9/P1t/uf+Yf/i/3oAJgHcAY8CMQO0AxcEWgRrBD4E5AN4AwQDkQIrAtkBmgFvAVcBWAFzAa4B/AFHAoICyAIoA5MD8ANFBKoEEgVhBZMFsgWtBX4FQAUSBfAExgSdBI8EpwTbBBEFNAVCBTkFAgWWBAgEbAO2AuIBFQFoANL/Rf/F/k3+x/0x/Zz8EPyI+wv7r/p7+mL6VvpX+mD6Z/pb+jr6C/rJ+Wj58Ph9+CD42Pee93f3a/eA96z34/cd+E34Zvh6+J/4x/jd+Oj4+fgP+Sf5Tfl5+Zv5t/nn+Rz6M/ox+jv6XfqJ+qr6vPrC+sr63vr8+h77Rvt3+7P7BPxm/Mj8JP19/df9Jf5k/p3+2v4Y/1D/if/P/yQAfADSACoBgAHMARICWAKTAr0C2gL2AgkDCgP7AtgCpgJtAjcCBQLmAecBAwImAlYCoAL2AkUDkwPZAwoELQRgBKQE5AQfBV0FoAXlBSwGZwZ9BmwGSQYsBgkGzgV/BUEFJwUfBRIFBgX/BPIEzwSSBDsEzANVA+sCigIpAssBiQF6AZABogGaAYsBhwF9AVcBJgH8AN4A1QDtABMBKQEtASwBJAEKAdQAdwD1/2v/9f6L/hz+r/1b/Sj9D/0C/fb86/zt/Ab9Mv1r/aj96P0x/oj+2f4R/y//Nf8j/wj/8P7V/rH+iP5r/mH+av54/oH+if6Z/qX+n/6T/o7+iv58/m3+a/58/p3+xv7r/gf/J/9L/2n/iP+y/+D/DgBFAIQAtwDXAPEABQEDAeoAwgCTAGoAUABHAEkAUABXAF4AagB4AIIAjwCqANMABAE7AXgBvQEKAmICsQLjAvwCBwMAA+QCvgKTAl8CKQL2AcMBhwFEAfkAqABPAO7/hv8o/97+lP5E/hL+G/5I/oL+z/48/8r/cgAuAfABqgJYA/IDbgTGBPcE/QTVBIgEIQSuAzsDzQJpAiAC/gH0AfkBEQJBAnoCuAL5AjkDdgO/AxIEVgR6BIgEhARhBBQEoQMXA4sCDwKhAUsBIwErAVYBoAECAmICpgLBArECdQIXAp8BAwFIAIv/3f41/pH9AP18/Pr7dfvz+nj6CPqo+VP5FPns+ND4svib+I74gPhi+Cz40vdg9/b2sfaF9l/2T/Zo9qr2CPdr98P3HviR+A75dPmv+dP59/kl+lT6efqR+rD63foS+0j7ffuq+8378/sf/Eb8ZfyP/Mj8//ww/WX9nv3a/Rf+U/6P/s/+Gf9p/8H/HAB0AMEADgFlAb4BEwJaApYC0gIaA2UDowPVAwoEOQRaBHQEjgSfBKIEoASXBIUEbARHBAwEtgNSA/QCpQJgAhgC0QGlAaUBwwHvATACiALqAk8DsgMHBEYEcQSLBI4EhAR1BF8EPwQlBBEE9gPLA6EDhwN5A2wDWANAAzIDLAMeAwYD7gLPApgCTQL5AaMBTQH9ALYAcQA7ACgANQBJAFYAWgBfAG8AhACTAJQAkQCIAH4AfwCNAJAAcgA3APj/v/+K/03/Bf/H/qX+mf6N/oL+hf6V/qP+qf6j/pP+fv5s/mL+ZP5u/n3+kf6u/sf+y/7B/rz+vv67/q3+nf6V/pn+pP6o/qz+u/7M/sv+uf6l/pf+jf6K/or+jv6c/rz+6/4e/0//d/+b/73/zv+4/4z/c/9u/2T/Vf9R/1b/V/9T/03/Qf80/yv/L/9L/3b/mv+2/+r/OwCLAL0A3QD7ABoBOgFZAWwBdQGJAagByAHnAf8BBAL/AQUCEQIFAugB0gHBAZ8BagErAekArgCAAFEAIQD4/9n/vf+s/6r/sP+3/8v/3v/d/9T/3P/3/xMAMwBkAKUAAAF/ARUCrAJBA8sDNARqBHAEUAQSBMYDhANZA0kDTwNZA2YDhgO8A/ADHgRJBGwEewSBBJcEvgTyBDcFhAXCBdgFwQV3BQIFcQTcA1ED3AKHAlACMQIlAi8CTAJxAo4CgwIwAo8BwgDs/x3/Vf6Y/fr8gPwY/LD7T/sC+7f6TfrI+Uv56fiT+EX4FPgI+A74Hfgs+Cb49vem91D3Afe29nX2TvZW9o724PY696P3H/ib+Pb4M/la+Xn5mPm8+ev5Ivpm+rb6D/tv+8/7IPxe/J783vwJ/SD9Qf14/an9yv3k/fv9Cv4W/iD+H/4R/gn+HP5X/q3+B/9h/8z/UgDZAEcBnAHlASkCawKkAs8C/QJCA4wDvQPeAwoENwQ8BB8E/gPjA70DhQNLAxkD7gLAAo0CXgIzAgACwwGJAV0BPQEoASkBQQFqAaUB7wE4An4CxQILA0ADXQNkA1cDOwMYA+0CvAKMAmECLgLqAaYBeAFiAU0BMQEXARQBIgEtASgBIgEqAT0BSgFCASQB+wDcAMYAsACYAIUAeABxAHUAhQCcAL4A8gAzAXMBsQHuASkCUgJlAmICUwIzAvcBqAFXAQwBwwCJAG0AZABbAFEAUQBXAFwAYABhAFQAOwAmAB8AHgAYAAYA5P+1/4D/Uf8l//H+sv57/mb+dP6M/qP+yP4D/z//Yv9o/1j/Q/8x/x7/Af/r/vP+F/89/1z/gv+t/9D/6f/5//X/2v+y/4z/cv9j/1T/Qv8v/x7/BP/k/s/+yv7G/sT+2v4P/1X/of/r/zUAfwDKAAkBKwE4AT8BRQFOAVwBagF0AYYBpwHFAdMB2wHiAdMBpgF0AUsBGQHWAIkAQAD+/73/f/9L/yb/B//m/s3+zP7c/uz++f4L/xv/Lf9P/2v/aP9c/2X/e/99/3z/l//P/xMAZADRAF0BAAKvAl0DAgSTBAEFSQVzBXwFUgX+BKAETQT7A7EDdgNHAyIDFgMhAy4DNgNFA2MDiQO1A+UDHARmBLoE9AQABewExQR0BO4DTAOjAv0BXwHZAHIAKwD//+D/w/+p/43/Vv/6/of+B/6C/Qn9pvxQ/AP80fu6+6H7dvtA+/z6p/pM+vH5lPlG+RT5+fjr+Pf4JPlW+Xb5kPmu+bv5rPmN+XP5afl0+Yz5sfnt+Tv6i/rc+jP7ifvI+/f7J/xV/HP8jPyv/Nn8Cf1H/Yf9sv3L/ej9AP4C/vH94/3b/dH9v/2t/ar9uv3Z/fn9Hv5F/mj+iP62/vD+Jf9U/4f/vf/u/x8AXQCnAO0AJgFWAYcBwgH/ATACWQKBAqECrwKxAqwCmAJ1AlUCPAIaAukBtgGMAWYBOwEOAeMAwQCdAHYAWwBjAIcAswDlACUBeAHZATwClALUAggDNQNQA0cDKwMSA/gC0AKnAogCbQJQAj4CPQJJAl8CgwK1AuIC/AIHAxsDPwNaA1UDMwMSA/UC0AKdAmgCNwIIAtwBswGQAX0BgQGZAcIB/gFPAqkC+wI9A2sDewNkAysD2AJuAvUBggEoAesAwACgAJMAnQCyALkApwCCAFYAIwDi/5j/U/8Y/+T+wP6q/oz+VP4L/sH9df0e/cr8kvyA/Iv8rfzp/Dr9jP3M/fv9Iv49/jX+D/7i/b39nf2N/Zj9vv3v/R/+Tv57/pz+pf6Z/oT+ev6A/of+if6P/qf+xf7c/uz+A/8a/yP/Jv88/2z/pf/b/xwAbgDHABoBZgGtAd0B6QHaAcUBtAGoAaEBnAGXAZYBmwGrAb0BvwGvAZ0BjQF5AVcBMAEGAdUAogB7AFwAPgAiAA4A/f/u/+T/4//j/93/2f/a/9z/2//T/8D/pv+E/1D/Ef/d/rz+of6L/ov+pf7V/ir/vv+CAE8BGgLrArkDZwThBCgFPgUcBb8ENgSoAywDwAJbAg8C7AHsAQkCRAKWAuUCJQNlA6gD6AMlBGgEqATUBN4EyASVBEMEzgM0A4IC0wE+Ac8AjQB9AKAA7QBOAbEBAQIsAh0C1AFeAcgAHABn/8H+Of7N/Xj9OP0J/d78pPxX/Pr7lvst+8n6ffpR+j/6PvpP+mn6dPpf+jX6Avq9+Wb5Fvni+NH44fgX+XL54vlU+rb6/voj+x/79fq0+nP6PfoQ+vz5EPpE+oD6wPoQ+2b7qvvX+/X7CvwW/B/8J/wu/D38Wvx5/Ir8jfyN/JP8ovy7/Nv8A/08/Y/98/1g/tb+Tf+4/wsARgB1AKQA0wD5AA4BIAFHAYMBxAEFAkkCiQK2As8C5QL8AgoDCQP2AtYCrgKMAnQCXQI/AiACDAINAicCUAKCArkC/gJWA7gDHQR4BMAE8AQKBQsF8wTIBI8ETQQCBLsDhANYAy8DEwMLAxUDJwNDA2oDkQOvA8kD5wP/AwkEBgT4A9gDpgNnAygD7wK5AnoCNAL/AeABzwHFAckB3AH1AQsCIQIzAjsCOQItAhcC8wHFAYoBQQHyALIAfgBJABUA7P/O/7f/pv+Y/4P/Xv8y/wj/5P7C/p7+fP5h/k/+Ov4a/vD9w/2P/VP9Hv35/Nv8xPy//M/87PwO/Tf9ZP2E/ZL9lP2P/YX9ev15/Yb9pv3a/SL+dP7J/hz/Yv+R/6//w//R/9P/yf+7/7P/t/++/77/uP+0/7b/uf/B/9P/6f/9/xwAUgCXANcACQEtAUQBUAFaAWMBYgFUAUoBTgFcAW0BhAGeAa8BtQG2AbcBsQGZAW0BPAEWAfkA2wCyAH4APQDw/6f/af8r/+b+r/6T/oj+gf6N/rT+2f7k/tv+1P7M/rb+kv5p/kD+Fv7s/cz9v/3E/dP96/0b/mL+tf4Z/6X/YQA0AQgC4AK4A34EGgWFBbkFuAWGBSYFoAQUBKIDUwMbA/gC8wIMAz0DggPLAwUEMQRmBKAEyQTeBPAEAgUDBeMEoARCBMkDNAOCAssBLAGxAFEAGAAeAFcAogDpACgBSgE7AQEBqgAxAJn/AP+F/iT+z/2H/U79I/38/Mj8ffwf/Lr7Vfv2+qb6b/pK+jn6QfpQ+k76NfoQ+tj5gfkg+dn4sfie+K347PhR+cH5JPpy+q362vrv+tj6nfpg+jz6M/pF+nb6w/oq+6b7Lfym/Aj9Xf2j/c/95f3t/e396f3q/fL98/3o/db9v/2l/ZD9iP2I/Y39ov3O/RH+a/7W/j//mf/u/0MAjQC4ANAA5gADASYBTgF8AbYBAgJbArgCEQNiA6MDzQPkA+gD0gOhA2sDOAMCA80CqQKdApoCmwKiArQCzwLxAhUDNANOA2EDaQNrA3UDhwOYA50DlwOFA2UDQgMiA/0CzQKfAogCjgKsAtUCBANAA48D4QMfBEQEUgRHBBsE3wOoA3cDPQP+As0CswKpAqICmAKFAmkCQgIWAu4B0wG6AaIBkgGZAbABvQGsAXwBMgHdAHkAAQB8/wj/tf57/k/+P/5Q/nr+qf7W/vv+Df8J//b+2v67/p7+h/5w/lL+LP4D/tz9r/10/Sz97PzE/K38pfyz/Nv8C/0z/Vr9f/2Y/Zz9iv1u/Uv9Lf0h/Sv9Rf1x/bX9Dv5x/sz+Hv9r/7D/6f8TADkAXwB9AJMAqADBANkA7gAEARQBHAErAUwBdQGSAaIBuQHbAfYB9gHkAdUBzwG+AZQBXAEnAQEB6ADYAMoAvAC1ALQAtQC1ALsAyQDTANIAxwC8AK4AlgBtADEA6v+n/3D/Qv8c///+8/75/gv/I/9E/2z/jv+c/5P/f/9b/x7/0/6Q/lD+Cf7G/Zv9if18/Wj9XP1t/aT9Af51/v7+pf9yAGIBWgJBAwcEpgQaBV8FbgVPBQYFlAQGBIoDRgMtAyQDKANNA48D3AMvBIMEyAT3BB4FTAV3BZUFmgWEBVIFCAWhBBoEeQPFAgYCUwHFAGIAIgAIABoARABvAJIAsAC9AKYAawAXALD/Pv/R/nP+HP7J/X79PP0A/cT8f/wp/NH7iPtN+xX73Pqt+ov6avpD+hP62/mg+Wb5I/nV+I/4Xvg++Cv4M/hV+Hv4mvi6+Nz4+/gX+S75PflO+XP5svn9+V363Ppw+wf8o/xB/dP9TP6t/vf+I/83/zf/Kf8Z/xX/Ev8B/+/+7/75/vz+Av8V/yv/QP9m/53/0/8BADEAWwBxAHcAcgBbAC4A9/++/4//ff+T/8b/DQBtAOAAUwHFATgCmgLZAv0CGQMsAzADLQMqAxwDCgMCAwYDCAMFAwIDBgMWAzkDZAOMA7ED2AP7Aw0EEgQKBOsDsgNxAzUD+gLDAp4CjAKHApICrgLSAvgCJANTA34DpgPQA/sDHQQuBCsEGwQOBAgE9APFA4wDYAM6Aw4D3AKwAogCXAIpAvQBxQGbAWwBPgEfARIBAwHoAMMAlwBiACkA7/+u/2X/I//t/r7+nf6V/pz+of6g/qD+of6a/oz+fv50/mz+Yf5T/kn+Rv47/hj+5v2w/X39TP0j/fv81/zH/NL89vwo/V39kf3B/ff9Nf5s/pX+uv7j/gn/Lv9c/4v/tf/k/x8AVwB9AJsAvADTANkA0wDKALgAmABuADkA/v/K/6b/if93/3T/gf+H/4T/iv+m/8n/5/8NAD8AZQB3AIUAnACwALUArgCbAIMAdwB7AH4AeQB5AIoApgC2AK8AlABuAEYAEQDE/3P/Lf/o/pr+T/4T/uf90P3V/ej9+v0U/kX+g/66/uv+Hf9E/03/O/8c//f+y/6Z/mj+S/5L/mv+p/78/mf/5v+AADsBHgIfAygEKAUjBhgH9QevCEAJlQmcCWkJIwnLCFgI2QdnB/UGegYaBt4FnQVCBeUEkAQxBNcDoQODA2oDXwNzA5ADogOoA5cDYAMEA4sC8QFHAaYAEQB+//b+h/4i/rX9Q/3D/B/8Uvtw+oP5k/i89w/3gfYG9rD1gvVr9Wb1bfVt9Vr1QfU09Tr1WPWa9f71fPYa9973sviA+Tv62fpJ+5b72PsQ/DT8UvyC/ML8Af1D/Zf95f0K/g3+D/4U/g/+Cf4S/jT+cv7T/lr/9v+eAE0B7wF0AuACNANlA3QDdgN0A2oDWwNTA1EDSAM4Ax8D9wLJApwCXwIKArEBbAEtAeoAtACVAHcATQArABgABwDu/9T/vv+p/57/pv+9/9b/7/8NADQAYQCJAKIAqgCkAIYATQAIAM3/kv9C/+X+nP54/nT+jP6+/gX/Wf+8/ywAnQAMAXkB2gEwAooC+QJ/AxUEqQQsBZQF5wUiBjgGIQbcBW4F7AR5BCAE0wOTA3oDhwOYA6IDqgOkA34DPwP9ArwChwJuAnMCjAK6AvMCJANKA2sDdQNRAw8DyAKAAjwCHAIcAhwCEQIEAukBogEtAZQA0v/q/vD98/wB/Dv7sPpR+hj6FfpH+oz61foi+2/7rfve+wr8NPxf/Iv8sfzX/Ab9Mf1G/UH9Mf0V/fv88Pzs/OL85/wN/UX9fP3F/ST+e/69/vb+IP8w/z3/Wf95/5v/2P81AJYA+QBpAdYBJwJlApwCugK1ApgCZwIiAtcBkwFFAeEAgAA8ABUA+P/j/+D/9/8cADsASgBUAFgAUgBEADYAKAAZABUAKABHAG4AmQDAANQA1gDPAL4AmQBtAEAAEwDi/6z/ef9H/xD/yP5s/gb+of1H/Qb96fzv/CH9h/0P/pT+D/+F/+b/HgAwACYA+P+s/2L/Kf/v/rH+f/5i/lr+Zv58/oL+gf6Z/tD+Ff9r/+L/ewAoAeUBsgJ+A0wEHgXdBW0G4AZXB88HKAhcCHkIhwiECHsIbQhOCBoI0gd+BywH6ga4BosGbAZlBmkGbgaCBqoGyAbIBrgGnQZgBgQGnwUqBYcEvwP3AikCRgFjAJv/2f4R/lP9rPwI/Gb7zvo3+pD55/hT+ND3Vffr9pf2WvZB9lf2i/bH9gH3MPdM92b3i/e69+b3E/hJ+If4xvgC+Tv5Z/l9+Xf5YvlO+Tn5Gfn++Ab5N/l++d/5X/rl+lX7sPsH/Fb8kvzK/Az9Wv23/SH+jv75/mb/0/8sAGUAiACfAKAAjAByAGgAcQCJAK8A3QALATQBXAGCAZoBmAGAAVcBJQH1AMYAmgBxAFQAPAAgAAoACAAWACgAPABRAF4AaQCFALoA+AA1AXABoQHIAewBCQIMAvMB0gGxAY0BcgFtAXQBewGLAa0B3gEWAlQCiwK4AuECDQM9A3MDrAPbA/8DLARsBKwE2AT5BBcFMwVFBUwFRwU2BR8F/gTRBJ4EcgRSBD4EOARCBF4EjATJBPwEBwXrBL0EhQQ6BNwDeQMcA8YCegJDAiECAwLfAagBVwHxAIcAJQDK/33/Tf81/yL/D//2/sD+WP7K/SP9aPyr+w/7ofpf+lX6lfoD+4P7CvyO/Oz8EP0N/fH8wfyM/Gf8VvxU/Gb8ivys/MX82vzl/OL86fwJ/Tj9bP22/SX+rf5D/+P/dQDiACMBSQFYAVUBVwFqAYQBogHXASYCgALMAggDMgM/AyoDAwPZAqcCXgIDAqMBVAEXAekAwwCvALEAvADAAMQA0QDdANcAwQCoAIsAZgA9ABIA3v+h/2P/J//j/pv+W/4p/vr9x/2X/Xj9bf1l/Vj9T/1R/VL9Qf0n/Q799/zg/M38x/zN/Nv88fwK/SX9Uf2L/cH97P0S/jD+NP4f/gD+1f2d/WP9Nv0Q/fP88vwS/UP9ff3G/R3+df7R/jb/nv8KAIoAIwHAAVMC6wKQAzIEwgQ7BZEFyQX2BSsGbAaxBvoGPgdvB5sHzgf9BxEIDAj9B+sH3QflBwQIIQg4CFYIgwi3COUIBAkNCfwI2gipCGIIAAh7B9QGFwZRBXoEiwOOApwBugDj/x//ev7r/WH93fxr/Af8o/s9++b6qfp9+lL6J/oB+tz5pflX+f34m/gp+LT3Xvcy9xj3APf49gr3Ivcs9yn3IfcP9+/2zfbB9uP2K/d49733C/hm+Lb47/gk+Vr5hvmn+dX5Gvpm+rb6D/tn+7D77vso/Fb8cvyH/J/8v/zy/ED9of0N/oj+D/+K//L/UwC0AAUBQwF9AbkB8gEjAlACbgJ4AngCbwJaAj8CKAITAvsB7wEBAiQCPwJUAnQCnQLCAuICAgMZAxwDFgMaAywDPQM3AxsDAgMEAxEDDwP9AusC0wKmAnECTQI2Ag0C1QGmAZcBmwGjAa0ByAH2AScCVgKNAtACEgNNA4oDzwMMBDAEQwRSBFwEWgRGBCEE7gO5A4QDTAMWA+wCzgK8Ar0CygLWAuEC8gICAwAD7gLaAsoCswKRAm4CUgI3AhgC8AG+AYYBSQEDAbMAZgAcAND/g/8+/wj/1P6Z/mD+L/72/a79af0y/f/81PzF/NX8+vws/WP9lP26/dj96f3o/dz9yv2q/YL9ZP1Z/Ub9Hv37/PL88/zz/P38GP03/V/9of36/Vn+tv4N/1//rP/s/xsAPgBaAGgAZwBoAHkAlQCmAKQAnwCiAKwAuADAAL8AtwCzALgAwgDOANQA1ADRANQA3ADxAA4BJAEwATkBRgFTAVcBRgEfAe4AwgCbAHMAPwAAAML/kv9y/1n/SP85/yn/Gf8Q/w3/Cv/7/uP+0v7O/sr+v/6t/qH+ov6q/rT+xf7e/ub+3/7p/gv/JP8t/z3/Vv9b/0L/IP8C/+X+u/6I/lj+Mv4W/v796/3p/QD+IP47/l7+kP7G/vz+NP9f/33/pP/f/yIAYACZAMwA+QAfAUcBfgHHARcCcALeAmYDAQSiBDQFrQURBmIGpgbiBg0HHAcPBwEHAgcRBxkHDwf8BuMGwQapBq0GvgbBBsAGxgbCBqIGYwYGBooF8gRDBIcD1gIxApsBGAGoAD0A0v9x/x//0f5+/iz+7f2+/ZT9bf1J/RT9wPxQ/M37RvvK+k36wPk++ej4t/ib+JT4oPi4+Nj4+/gV+ST5JPkR+fP42PjE+LH4nPiJ+ID4gPh/+IP4i/iP+JH4pvjI+PH4Kflz+cP5C/pD+mz6lPrD+vP6H/tJ+3X7rvsA/F78vfwn/aH9Hv6P/vX+Sv+P/8X/6f/7//7/+f/6////BQAZAEYAeACjANMAEwFTAY8BxgH3ASQCUgJ3ApgCxALrAvoC/QIAA/gC2QK0ApgCiwKKApYCrgLNAukCCgMmAykDDgPkAroCkgJ1AlgCPAIxAkMCZQKWAt4CKgN7A9MDJgRiBJQEzAT+BBMF/gTRBK4EmwSABEoECgTWA70DsgOrA7QD1wP7AxIEMARfBI4EqgSwBKYEigRVBAYEtgNmAwEDjAIwAvMBwQGSAW8BUwE8ASkBDQHnALUAcwAiANT/kf9V/xn/2P6X/lH+Bf64/Xf9QP0Q/fT86Pzg/Oz8Ef01/UP9Rv1E/Tf9JP0J/d78r/yU/In8gfyB/JH8rPzM/On8Ev1Q/Zj93/0g/lz+k/7P/hD/Tf9//5r/nf+g/7H/uv+1/7r/zP/k//7/FgAkAC8ANwA9AEoAaACJAKwA0QD2ABgBOAFWAXEBkAGhAZcBegFnAWEBWQFHATcBMwE0ASoBHwEVAf0A2QC/AKgAggBeAE4ASwBLAEYANgArADQANgAfAP7/2/+v/3v/S/8f/+/+wP6b/oH+Zv5J/jb+Jv4F/uT91f3L/bv9qP2W/Yz9lv2t/bb9u/3E/cP9tf2l/Zb9gP1n/Vn9Xf1v/X79hf2V/bD9w/3P/eD9/P0Z/i3+Nf5C/lb+YP5q/oz+w/75/i7/dP/Z/1sA6QB8ARwCxwJtAxUEygR4BQkGiAb8Bl8HtQf9ByUIJQgNCOsHxQefB3kHZAdkB3sHpQfoBzsIkwjZCPMI6gjNCI8IHQiIB+QGNAaCBeAEQgSdA/cCWgK/ASkBlAD3/13/2/51/hb+uf1p/TT9CP3F/Gf8+vuB+wT7ivoS+p75PPnz+MP4s/jB+NX44vjw+P34BvkN+f34zPiM+E34Efjh98P3sPel9573mPeb96f3q/es97z32vf+9y74efjg+FT5xvk0+p368vox+237qPvX+wb8Svyc/Pb8Yf3V/UD+oP77/kn/h/+w/8L/x//R/97/5f/q//v/FwA4AFoAfgCkAMgA5wAIASQBMwFJAW0BlQG+AeYBBgIiAlECggKUApECjgKTApsCpQKxArkCwgLVAvcCHQMsAyQDGwMRA/4C6QLfAt4C3QLaAuICBQM6A3IDsAP7A0IEhATJBAsFOAVKBU8FVQVnBX4FiAWHBXsFWgUwBREF+gTcBLoElgRyBF0EYwR4BI0EmASNBGsEOQQDBNIDmwNVAwwDzgKaAncCaAJPAhMCzQGQAVIBAAGgADUA0v+C/zv/8/6i/kf+4v2I/Tz96fyL/Db8//vl+9P7xPvE+9X76vsF/Cb8PPxE/Ev8VPxY/FT8Tfw//Dn8QPxS/Gf8fPyL/JX8q/zV/Af9Of1i/Yb9s/3n/RT+OP5W/m/+iP6q/tL+9/4X/zj/a/+o/+D/DAA4AGMAiACvAN8AEQFCAXEBlgGxAcEBwwG/AcEByAHEAbwBvAHEAdEB6QELAioCQQJSAmACZgJdAkkCNAIiAhICAQLrAc4BrgF/ATcB6wCqAGgAJQDw/8v/rP+S/4D/fP9+/3n/bP9Y/zv/Ev/p/sf+pv56/kr+I/4G/u/91/2//az9nP2Q/Yn9gf1z/Wj9aP1p/WH9Tv00/Rn9//zh/ML8rfyi/Jz8mPya/Kj8zvwE/T39dv2w/en9Iv5i/qj+3v4F/zL/ev/W/zMAlQAKAY0BEgKfAjoD3gN/BCEFyAVnBvkGeAfkBzwIdgiNCIgIbghBCA4I4wfBB58HhweMB64H3wcPCDEIRAhICEQIMwj9B5QHBwd0BuYFXgXQBCoEbwO1AhECegHoAFgA0P9U/+b+j/5Q/iL+9P3F/ZX9WP3//JD8Gfyb+xL7hPoC+pb5Pfny+Lb4h/hp+Gb4fvid+Kv4qPib+Iv4dfhW+DD4Cfjv9+b37Pfy9+335/fq9/T3APgV+DX4YPiR+Mb4//g++Yz57PlQ+qL62foB+yH7P/ti+5D7xPv5+zb8gvzc/D79oP37/Uj+hv66/uj+C/8h/zP/U/+D/7//AgBDAH0ArQDYAP8AIQE8AVcBcgGNAa8B4gEkAmYCoALRAv0CHQMwAzgDPANAA00DZgOAA5ADmwOxA9MD8QMCBA4EHgQzBEcEVQRaBFgEXwR8BKgE1gQABTAFaQWfBcgF3QXjBeIF3QXVBcIFpgWLBXYFZwVVBT0FHQX7BN8EygS0BJgEfQRtBGoEagRmBFoERAQjBPgDwgN8Ax0DrAI9AtUBbAH9AJYARgAKANv/uv+a/2n/Jv/n/rX+h/5X/i7+AP7B/Xj9NP30/LH8afwg/Nr7mvtl+z/7K/ss+0L7Z/uS+8X7//s5/Gr8hfyF/HH8XfxS/E38RPw5/Db8Sfxu/JT8uPzg/A79Ov1l/Zr90P39/Sj+W/6Q/rz+6f4i/1P/ZP9d/1//c/+O/63/1/8LAEoAlADoADkBfAGxAd0BBAIiAjECNgI4AjQCKgIXAgQC+QH6Af4BBAINAhcCHgIkAi8CNgIwAiACGAIaAhYCAQLfAbcBiwFgAT0BHAHvALYAgABdAEwANQAQAOr/0f+7/5z/df9E/wH/t/56/kv+Ff7b/bH9l/2C/XD9af1k/Vr9Uv1T/VT9UP1J/Tv9J/0X/Qz9+vze/Lj8jfxe/Df8HPwG/Pb7/Psb/Ef8fvzA/AP9P/13/a794v0W/kf+b/6d/uH+Mv97/8z/PgDIAEwB0wFvAhcDvANqBCgF4AWFBiEHsAchCG8IoAi8CMMIuwioCIwIcQhcCEUIKggYCBYIIgg8CGUIkgi1CMwI2QjWCLcIdggRCJAH+wZNBoQFtQT0AzoDfQLHASQBjQABAIj/H/+2/lr+HP7v/bz9gP1D/QX9u/xe/PH7efsJ+5z6IPqT+Q75nfg6+OX3ofdm9zT3GfcY9x33IPck9yP3F/cN9xP3H/cj9yb3MPc690L3UPdh93L3gveQ95b3o/fP9xf4aPjA+CX5jPnz+WH61/o++4/70/sW/Fv8p/zy/Df9fP3P/Sn+g/7e/jj/f/+4//n/QQB6AKIA0wAMAUABbgGfAc0B8wEQAiMCKgIuAj0CWAJ8AqoC4wIbA1IDjgPVAxsEUwSEBLEE1ATrBPQE7gTUBLUEnwSSBIEEagRcBGIEdQSIBJoEqwS5BM4E8AQZBUMFbAWUBbUFyQXSBcsFtgWeBZAFfAVeBUAFKAUIBeQEyAS8BLkEtASmBIkEZwRTBEwEQgQrBAgE1gObA2QDMQP0AqcCVgIIArsBawEWAbgAXQAOAMf/ev80/wL/1/6q/nn+Qv79/bb9ff1H/Qj9xPyG/En8E/zv+877mftg+zb7FPvx+uj6APse+zX7Xvuf+977EvxG/HX8kfyk/LL8tfyy/Lv80/zp/AD9JP1K/WL9cv2J/aX9vv3g/RP+UP6O/s/+GP9m/7H/9f8sAEkASwBFAEsAXgBzAJIAyAASAVsBmwHYAQwCKwI2AjsCRQJUAmQCcgJ4An4CkQKlAqQCjQJtAkgCIAICAvQB6QHVAb8BsgGhAYsBewF4AW0BTQEnAQQB4QC7AJ4AjAB0AEwAHADq/7n/k/94/1v/Mv8J/+n+yP6b/m3+Rv4d/ur9vf2i/Zj9j/2G/YD9ff16/XL9X/1C/ST9Dv34/N78y/zE/Lj8nvx//G38W/w8/B38DvwS/CT8TfyH/L/88fws/XD9qf3S/QD+NP5j/o/+vv7u/iT/af+0//n/QQCfAAwBgAH+AYsCHgO7A24EMgXtBZIGKQeuBx4Idwi3CN0I7gj1CO4I2gjGCLAIkgh6CHgIeQhpCGQIeQiRCJ4IswjKCMgIrgiMCFgIBgicBxcHagadBdAEAwQoA0kCegG5AAIAb/8K/6/+S/7p/Yn9JP3D/G/8FPyr+z770vpa+uP5ffkX+aP4Kfi09z731PZ/9j72Cvbk9cz1ufWy9cP14fXr9d/12/Xn9fT1A/YY9iz2RfZ29rz2/vY69333zfcm+I74+PhZ+bH5DPpw+tT6LfuG++r7VPy5/Bf9bP2y/fn9VP61/gH/Qv+M/+P/NwCBAMkAEgFbAZ8B3QESAjkCVgJ1ApICowKsArgCygLgAvYCCAMfA0ADZgOQA78D5AP5AxEEKwQ+BE4EYwR2BIMElASmBK0ErwSzBK8EnASBBHAEbARpBGcEaQRrBGoEdASOBKkEtQS7BMUEygTNBNME0wTNBMkEzgTQBMwExwTJBNUE1wTJBLEElgR2BFcENwT9A7IDdgNPAygD/ALYArgCngKPAnwCSwL6AaUBZQEwAekAjQA8AP//xf+M/17/M//1/qf+Vf4N/sv9jP1V/Sr9A/3i/NH8wvym/IL8UvwD/Kn7aPs0+/L6s/qS+o36n/rN+gL7JvtJ+3f7p/vT+wH8LfxK/F/8d/yU/Lb83fz9/An9Dv0l/U/9gf3A/Q/+Xf6l/gH/Zv/A/x8AgwDLAP0APQGBAa4B2AEIAhUCBAIHAhwCHgIdAjsCZAJ+AqAC2AIPAzMDTQNbA00DMQMdA/4CyQKjAqECngKGAncCdwJ2Am8CVwInAvoB5gHSAa0BlgGSAYABYgFYAVIBMQH6ALsAdAAqAOP/o/9r/0H/Mf8p/xP/9P7d/sT+m/5r/jv+//3C/ZX9aP0u/f382/y4/Jf8hfx3/GD8TPxF/EL8P/wx/Br8Bfz++/z79Pvj+9P70vvd+9v70vvX++T77fsA/Cr8Yfyb/Nf8Ff1i/b39FP5d/qH+5v4h/1r/mv/c/xgAVQCjAAQBcAHuAYcCLgPMA2gEFgXLBXIGFAeuBzAIoggSCWcJmAm6CcgJrQl6CUgJDwnFCHsIPQgWCBQIKQg5CEYIYgiICJsIjAhxCE8IFwjHB28HCAeMBg0GkAXvBCkEYQOZAr0B3QALADn/bP6+/S/9tfxd/BD8pfse+5v6G/qN+fn4afjj93L3Ivfw9sP2kfZj9jn2BvbH9Y71V/Uf9fj05/TY9NH07PQa9T31WfV59Zb1ufXp9Rn2TfaV9vn2bff595T4JPmj+SD6pPoi+5L7+vtr/N/8SP2x/ST+jv7n/j//mP/p/zwAlADfAB4BYQGkAeEBHwJYAokCvgL6AjUDcQO4AwMERgR1BI4ElQSUBIcEcgRXBDcEFwQIBAsEDQQSBB0EIAQaBBcEDgT2A+AD2QPWA9UD3wP5AyEERwRQBEIEMgQaBOkDqANzA1EDQgM5AzADKQMnAyMDIAMkAywDMwM+A0sDVQNfA20DeAOCA4gDiAOLA5cDpwO2A8IDvwOwA6MDjgNTA/4CswJxAiwC5gGiAWMBQAE1ARwB6wC0AH0AOwD4/8D/lv99/23/Xf9R/1f/Yv9R/xf/yf58/iH+rf09/ez8rfx0/Ev8JPz2+8n7l/tM+/76w/qL+lb6SPpp+p762vog+2r7s/v9+zb8V/x5/K786vwe/VL9k/3b/RD+Kv4u/iP+Hf4w/lj+gf6z/gL/Xf+z/wkAWwCeANoAFwFRAZAB4wE1AnICqALeAgMDDQMJA/kC2AKwApICjQKdAr0C6gIZAzQDNgMtAxsD+wLTAqECaAI/AjQCNwJEAmMCgAKKAogCewJVAhoC3QGeAWIBNQEWAfYA1wC8AJ8AdQA+AAMAy/+N/0b/B//j/s7+t/6X/m/+Sf4y/iH+BP7W/aj9f/1Y/Sv99fy//I/8X/wr/AP88Pvm+9373Pvm+/P79fvs++n75/vU+777xvvg+/D7APwj/FD8hfzB/PP8D/0t/U79aP2N/c/9G/5k/q3+7P4f/1b/lv/G/+L//f8gAEsAjADuAF8BzwFOAugChwMgBMgEgAUmBrwGUgfVBz8IrggoCZMJ7Ak6CmMKagplCkIK7QmNCUIJ8giYCFEIHwj9BwIIKwhECD0INwg3CBwI4geVBzUHwAZQBuYFYwXFBCsEkwPfAg4CKwE5AEn/Z/59/X78mvvq+lH6x/lZ+fH4c/jx93X36fZN9sj1W/X59Kr0e/Rn9Gf0d/SJ9JD0lvSa9If0XPQ49Cn0F/T28+zzFPRd9K30//RQ9aH1+/Vi9tn2cvcl+Mv4Wvn5+bP6cPsq/On8nP0x/rf+N/+n//3/SQCbAPIAQwGQAdwBMgKbAhIDfAPWAyoEbwSTBK4E2AQBBRsFOgVnBZ4F2gUTBjkGVAZoBlwGIwbYBYoFMAXOBIEERQQLBNwDyAPBA7UDoQOGA1oDIAPhAqgCewJnAmcCZwJhAmYCdgKFAoACYgIvAvUBtQFhAQsB2gDPAMoAxwDaAAoBRQGBAa8BxwHKAcQBtwGpAZ0BkwGUAagBxQHrASICaAKwAu0CGQMlAxQD7gKxAlwCBgLJAaYBkAGCAXYBZwFVATYBAQG0AGQAHADg/7n/pv+h/7H/3P8GAAsA+P/Y/5X/Jf+x/kf+2P1q/Rf9z/yD/Ef8IPz0+7/7jftf+zz7Lvsk+xD7CPsa+yj7Mvth+6778fsq/IL88fxg/cv9KP5f/nn+jP6D/lr+O/5C/lj+dv6t/vT+Nv+D/+T/PAB9ALEA2QD2ACMBcAHMATECqQIlA4oD2QMHBP0D1gO8A6IDZgMjAxcDRAN7A6EDsQOnA40DagMqA8gCXAIGAskBpQGcAa4BzQH0ARUCJQInAiQCFQLrAa0BcwE4AfUArwBoABUAsf9Q//3+tv57/kT+A/68/Yn9Y/0s/eb8uvyw/Kb8lvyQ/J/8ufzS/NL8tPyI/Fv8HfzR+5n7hPuJ+6D7xvvm+/j7/vvs+7f7d/tC+wz71frH+ur6JPtw+9v7Tfyt/AX9Xf2u/fH9Mv5t/qD+1f4O/0//nP/v/yUAPgBZAHsAiwCMAKQA2wApAY8BDgKpAmEDJwThBI8FSgYPB74HYAgNCbkJRAqvChcLhgvuCz8MegyuDNsM3wyuDGEMBgyPC/cKTwqlCf8IeggeCN0Htge1B9MH7gfuB8cHgAcnB7wGLAZ/BdYEPAShA/QCKwI7ATIAGf/n/Zn8V/s0+hz5Dfgs94P2+PV89RT1s/RV9Ab0vvNx8yfz7/LA8pbyffJv8mXyb/KX8sLy2PLi8uXy4fLk8vLy9fLs8vXyIvNn88nzWPQF9b31kfaG9374Xvkz+g375/ut/Fj9/P2u/m3/IQDCAGEB/gGIAvcCSAN7A5gDtAPhAxgEVwSlBAMFaQXHBRcGWQaCBokGdAZWBkAGNQY0BkAGVwZ8Bq4G2AblBs4GlgY9BsoFTgXQBFEE2gNpA/cCgwIjAuMBuAGJAUoBCgHhAM4AuACaAI0AmwCuALsAyADRANgA6QD9AAYB+wDjALoAggBIABIA3P+z/5//lf+Y/8D/EAB6APQAeQHxAVMCpQLhAu8C3gLJArMCmQKKAooCjQKdArMCqQJuAh8CxwFSAc8AawAnAPf/5f8BADsAfgC3ANMAyQCqAHUAIADF/4n/aP9W/1z/cv95/2v/Vv8t/9r+av71/X79BP2b/Ez8FfwB/BD8LfxO/Hn8q/zQ/N383fzg/PT8Ff08/XX9z/1A/p/+6v4z/3n/rP/M/97/3//S/8H/uv/C/9r//P8gAEsAgAC4AOUADAEyAVkBiwHJAQsCSwKRAtoCIQNvA8QDEQRHBG4EfQRXBAAEnwNGA+YChAJAAicCJAIkAikCMwI6Ai4CBwLOAZcBZAEuAQMB8QDsAOIA4wDzAPMA1ACpAIEATAD6/5r/N//U/m/+BP6V/Tz9D/30/MX8jfxp/Fj8Qvwb/O37wvug+4r7gPuN+7n7+fsz/GX8mPy6/Lb8jvxa/CT87Pu9+6H7oPu8++r7HfxO/Hv8mvye/Iz8evx0/HP8dPyE/LP8/PxU/b39Nv62/i//m//1/0AAfwC2AOIACwE2AWUBmQHQAQACGAIjAjkCXwKFAq0C5wItA3oD3wNvBCUF7wXDBpgHZAgpCecJlgouC58L5QsQDDQMPAwHDJ8LKQurCg4KXgm4CCwItwdQB/AGnwZjBjoGHwYLBvMFygWUBV8FIwXMBGEE9QOHAxADhgLjASUBWwB5/3j+af1t/H37f/qC+Z34yvf89j72k/Xv9E/0tvMt89DyrfKs8rTy1fIa82XzpvPs8yj0NPQV9O3zyvOw87fz4PML9Dn0f/Tc9DX1iPXe9Tz2rvY599H3dfg7+R/6AfvV+6r8dP0f/rn+X/8FAKEAQwH0AawCXgMGBJwEGgV+BcEF4AXsBfkFAAb7BfIF7gXoBdgFxwXCBcsF3QXtBQEGJgZcBosGpAapBp0GfgZJBv0FmwUrBbIEPwTQA2AD6gJ0AgoCpwE8AdkAmwB7AGAARwBFAFgAcACEAJcAowCtALwAygDEAKMAcgBHACwAHgAWABYAJgBBAFkAdQCSAKIAmACJAI8AqgDPAP4APQGEAcMB+QEuAlgCagJXAigC7gG7AY8BZwFFATUBKgERAecAuwCIADoA2P+F/1D/Mv8o/zb/U/90/47/n/+s/7j/tf+R/1z/PP8s/xH/7v7g/uj+9/7//vH+yf6T/l7+Hf7L/Yj9av1j/WT9bP18/ZL9tf3W/d795P0E/jj+bv66/iv/mv/q/zEAdwCnALAAnQB0AD8AHQAbADIAXACTAMcA7AAJARoBEAHuANkA5AADATcBhQHpAVECrALsAhcDOQNRA04DPgM4A0ADSQNMA0wDSQM4AwwDyQJ/AjsC7wGTAT0BCAHpANQAwgCvAJ0AmgCrALsAxADSAOEA3wDTAMoAswB6ADUA7P+Y/z7/7P6e/kb+6v2T/Ub9Dv3u/M78nvx2/GX8U/wz/CP8K/wy/C78M/xE/E78R/w7/DX8PfxR/Gn8fvyU/LX85vwf/VL9b/1y/V39NP0A/dH8ovxx/Ej8PvxV/Hr8nvzB/Ov8I/1y/dz9YP7v/n7/DACdAB8BfAG7AesBAALsAcMBqgGaAX0BcAGYAfQBXwLGAikDgwPJA/cDEwQgBBsEAgTjA9UD3wP8AygEaQTDBDIFsQUzBrcGOwe4Bx8Ibgi3CP4IKgkkCeoIgwjwBzkHcgavBQAFbgT7A6UDcANjA3ADegN1A2wDWQMuA/ACrAJRAsgBKwGoAEYA3v9b/8r+Nv6k/Rj9jvwE/Iv7Ivuz+i76p/kn+aL4Hfie9xf3ifYY9s/1lfVp9Wf1hPWh9cT1//U89mH2g/a59vj2MPdm95r3yPf+9zH4Ufhl+IT4tfjq+C35i/n8+X/6HvvV+4z8NP3S/W/+C/+X/wIAVgCnAPsARgGRAeMBKwJdAowCwAL0AiUDXAORA70D7AMdBEQEXwSABKIEtgS+BMUExgS9BK0EkwRnBDwEHAQHBPcD7APWA6wDfwNjA0gDEgPOApoCewJeAj8CKgIbAg4CBQIKAhwCMwJEAlcCdgKkAtkC/QIAA/cC8QLgAq4CaQImAuMBngFpAUwBMQEUAf8A8gDjANwA5wD6ABQBPAFeAWEBVwFQAS4B4ACQAGEAOwAIAN7/zv+8/4//VP8b/9b+fv4m/un9zv3E/cD9w/3O/dz95/3x/QD+H/5R/or+sv7H/tn+8/4Q/yv/RP9W/13/ZP9z/4H/ff9n/1j/Xv9q/23/cf+F/57/rv/B/9z/8v/9/wUACAABAAAAGQBBAHUAvwAQAUsBdgGoAdIB1gHDAbcBqgGLAWEBOQENAd0AqQBtADUACQDj/8D/tP/G/+H/AQAvAF4AfwCfAMwA9wAVATMBUAFaAVsBagF7AXgBZgFTAT4BLAEnASEBDAH1AOEAvwCLAFoANQAYAAwAGAAvAE8AegCcAK0AtAC8ALkArAChAJoAigBwAFAAJgDz/7b/b/8l/+v+vP6E/kb+GP72/dL9t/20/bb9qf2Z/Y39g/2A/Yv9kf2B/WP9Sf0y/S79TP2H/cb9Cf5f/rb+7P77/vL+2f6y/o7+ef5k/j3+Cf7h/dj96P33/f79Ff5J/pD+2P4d/2j/vv8YAGgArADnABUBNAFBAT0BMQEzATwBMAEGAdUArwCYAJAAkACWAKQAxgD5ADABYwGIAZIBiwGNAaEBrQGqAakBqQGwAc0B7QHmAdsBAAI8AlsCZAJjAkECCgLjAcgBpAGHAYEBfgFxAWkBaAFcAT8BLAEzAUABOgExATkBRgFSAV0BXQFEARgB5wCxAG8AKQD0/+b/8//8//r//v8NABgAFgAJAPH/1P+//7X/pv+J/2z/Xv9b/1j/Tf84/x3/A//0/vv+FP8i/x3/KP9G/03/RP9L/0H/H/8j/0j/NP/y/s7+uf6Q/oX+sP7X/un+Ev9I/2L/cf+K/5H/d/9g/13/S/8g/wX//f7U/o7+ZP5V/i/+9f3P/cz94/35/QD+Fv5K/nD+aP5Y/lL+PP4c/gP+4f24/aj9pf2U/Y39ov2n/ZL9of3j/Sj+W/6c/t/+Af8J/wX/4f6o/pH+k/5+/mr+fv6a/qL+tf7c/v3+E/8p/zn/Q/9U/2j/e/+R/6n/vP/D/77/t/+w/6X/nP+l/7v/3P8TAEkAZwB9AJsAsgDJAO0AAQH8AAUBEQH+AOsA/gASAR8BSAF8AYsBiwGgAbcBvgHMAesBBAIPAhgCLQI+Aj0CMgIfAvgBzwHFAcwB3gESAlYChgKwAuYCBQMDA/oC5gK1AogCcQJUAjUCLwIvAhoCAALxAeABwgGnAZsBpwHQAQUCLgJGAlQCSgIiAv0B9QH7AQgCIQIlAgUC4QHGAZABSAEYAQ4BKwFtAa8BwwG4AaUBewFDARcB9wDaANEA5QAQAUEBVgElAasAFwC0/6X/yP/7/zsAdgCHAHQASgDr/23/Ev/1/hb/e//m/xAAGwAmAPj/j/87/wT/yP6v/t3+EP8M/+b+y/7Q/u/+Cf/8/sr+lv6W/tn+Iv85/x//3/6B/jr+Lv5A/m/+3P5W/2//H/+0/mD+MP45/nj+yv4f/3L/o/+M/yz/ov4l/gP+OP5u/nz+iv6e/p3+t/76/vz+gP79/df99/0r/lz+ev6G/nf+Nf7X/ZD9ZP1P/Yr9NP4S/8n/AgCO/5/+qv0V/Rv9rf1p/v/+bP+r/7X/o/9r/9/+K/7R/Qn+pv5o/ykAyAAjAQ4BjwDS//3+Qf78/U/+5f5x/wAAlgD7AP0AnwAaALP/nf/Q/wkABgD1/0kABwGnAcIBXgGqAPH/bv8i/wH/Hv92/+H/WADRABIB7gBwAMn/Ov/v/tX+1/7+/k7/pf/7/2YAxwDaAIQA+v97/yP/CP9K/9b/TABZABIA2v/V/7v/Z/8o/zj/d//N/0gAsgDjAAQBHgH8ALwAqACoALEABwGgASACewLBArACPwK7AUMB0gCkAO4AjwE8AskCJwNVAzkDygI7AsMBdAFqAbwBPwLFAlYD3QMfBAMEkAPUAgACYgEsAXABJAIGA70DFATzA1gDkALqAVgBugBDABAAFABoAAgBigGiAXIBHQGfABgAmv8T/6L+kP7R/hz/W/+c/7n/jv8v/7L+Ff6H/UT9Ov0v/Qj92vzm/En9tP3c/cH9cP31/Jb8bvw+/Az8JPyA/NP8HP19/dn9FP4j/uP9Yf0E/fr8Bf0m/Yf9//1o/uP+Uv9e///+ev4b/jL+yv5+/9//8P/6/xIAEQD0//H/KABxAKcAxADPAMMAlABsAI8A6QA/Aa0BRwK1Aq0CVgLTASUBkQBbAGAAgAAIARQCIwO9A7oDDAP1AfYAJgBx/y//of+JAJ8BogJBA2QDEAMoAuMAyP/n/hj+vv1d/rz/LQFSAuECggJRAdj/YP4d/Zn8Hv0r/kv/cQBVAY4BFQEnAPX+0v0S/dH8FP3M/bD+lP+LAGYBnQEAAen/xv7L/Rf90fwZ/fr9T//HAO0BSQLEAcAAwP8N/73+wv7//mr/BwDZAPUBLQPUA2UDNQLlALb/+/4P/6f/WgBUAY8CjAMHBN0D0QJAAfb/Sv9L/wgAPAF1Al0DnwMyA4wC5gEkAVsAyv+c/+P/hABLAfIBOwIgArcB8QDw/zf/GP+G/yQAfACUALIAYQBH/yv+zP0A/qT+qf9kAD0Aif/z/qL+Tf7W/UX9r/x//CD9D/6d/tT+tv4h/oz9MP2u/DD8Ofyh/Cv97f2s/vj+oP7W/S39/Pwn/Z39Nv52/k/+EP7K/dP9ov66/zUA7f9e/w3/Cf/O/k/+If5O/qP+d/++AK4B4gGIAdQANgArAHoAewAyAEgA6wCiAR8CUAIvAhICFAKuAQEB6gBKAWQBfAHgAQgCxgGfAbkB3QHwAc0BVgG/AIAAzgBBAYsB6wFLAigCmwEdAYwAyv9i/7T/aADgALUANwA2ANsASAHKALf/z/56/qP+EP+N/+P/5f+0/5P/YP/y/qr+6P5z/+L/DgAAAMH/WP/p/sn+Dv9o/8v/UQCJAAEAM//T/v/+k/9mAP4A6gBRAMD/j//O/0cAmACmAMEABAE4AT4BEwHTAMQAzwCSAE0AoQBxAQ8CEAKTAf4AnAB8AJsArwB1AHQAMgEXAmgCHQIoAeD/Qf9x/47/ZP+O/zgA/QBoAUYBzQBDALT/Q/8U//7+4v7u/lj/7v8aAIz/4f7u/pj//v/A/0r/+P7W/vX+Ef/A/mD+lf4a/2L/eP9q/1H/mv8mACoAVv8Y/jL9cv3f/k4AngDk/zH/Sf/W/zIAXgB0AE4AEQDj/47/Jv8w/7f/aQAFAUYBGAHvADkBjAFLAY0Axv9X/6L/kQBjAcUBBgIpAhsCDgK4AdQABADY/zoADAHyAWYCgAKAAi8CkwH8AIcAWwCJANgAPgG5AQECGQIiAs8B9QDl/w7/6v6j/64AawGfATkBgQDj/2b/Dv8q/7X/RgCDADYAdv+G/q/9UP2b/VH+Bf9l/2z/X/8Z/zH+Gv2w/PL8bf3C/Zz9OP08/cL9rf6p/7D/YP7M/Nb7sful/Fz+sv8HAIH/rf5N/nn+jf5i/ib+nf3+/Br9Kf6u/yQB8gGaAUoAwP7Q/RD+bP/+ALIBQQF4ADMAZwCYAKoAqwB0ABYAOQAWAdkBxwEvAZQAFwDo/zsACwEYArUCSAJcAQoBWwGtAccBZgFvAKP/tP9GAPIAwQFrAqECkQINApsAtP6L/bX9zP4DANEASwG7AfMBRwFm/zr9Zvyf/QEA3gHWASgAsf7M/uv/kACp/4L9CPzI/Aj/1QDsAGX/rP1Y/Vb+R/9b/+z+uv4N/3T/R/9Q/j79R/25/mEAGAHZAB4AYf/p/pz+Sv4R/l/+ov9tAWMCywFDAMj+QP7l/un/uABMAU0B7gAmAbcBowE9AQgBpwA/AFMAtQBXAW4CfgPeA1oDCwJmACb/y/6d/4MBnwPYBK4EXAOfAUsAzv8sAAoB6AGCAqECDwIMAScA4/+HAKEBNQLaAeUA2f9i/8T/WACEAIsAvwAEARcB1AB3AGMAeAA1AGP/Q/6F/fT9fv8FAXwB1ACn/5r+K/5t/sb+t/6C/pL+8v6Z/0AAdQBTAEIAKADF/zL/kP44/rn+4P+nAK4AlwC0AHoAfv8f/iX9Vv3P/oMAOAH+AKAAXwAYAIv/cf5D/Sv9gv5/ABECWgJNARUArP+f/xD/Av4z/V79h/7d/7wATAGeATUBDAC7/pL9zPwM/XX+KwA4AU4BzABQAPz/kv8X/7H+cf6q/nz/WgC6AKIAZQBWAEYApf+c/gT+If7K/vb/DgEmAXQAAgAWAPj/B/+Q/cr85P2EAKcCxgKGAT8ASf+o/qz+Gf9P/0X/Vv+//3gAAgHkAHUAPQAbAMP/PP+1/pP+HP/l/2QApwC/AHYAGABpAH0BdAJQAtwA+f7t/Uf+nP82AYQCDgOJAk4BXwBXAJwAaQDi/4X/if8VAOkAewHIASwCggJ2AuwB1gBm/1D+M/74/hwAVAGsAuYDaQTkAz0Cyf/X/XL9B/7o/loA4QF6ApIC/wIgAw0C8P+G/e37Z/zc/oUBwgKUAvQBpAGtAUcBsv+f/cH8vP2l/1AB8gFUAU8A/P87ABYAav/u/v/+Vf+8/ycAhwDhAPEALwDu/lj+s/5V/yEAGQFzAbMAq/9F/2T/Wv+y/rj9d/2i/mMAawG3AegBmgE9AET+hPyx+3b8b/43AA8BRAEkAe0AygBeAC3/kP2W/P38Qf4I/8z+af7m/kQAVAHZADX/Df42/gj/YP+Q/jX92fwu/jgAjwF9AV0AhP/N/04Agf9R/Vz7bvu//agAMgLLAVoAW/+Z/1EABABe/p/8WPzm/QoALgEAAWYATADcADYBVwC9/gn+1/46AOsATAAV//D+dABKAsYCXAHt/kn9tf17/8wA3ABjAF8A4QA0AfoAhwBEAE8AdwB3ADEAn//1/gf/cABFAvQCOgIdAYYAkwClAD4A4P9LADoB5gEZAgYC4gHiAQQC0AHjAJn/5/55/wgBfQLDArgBfwBzAKoBBgNYAyACDwDi/rD/tAFQA1YDhQEo/27+9/8dAi0DBgNUAnkBgAB0/3f+1f3//QD/HgCtANAA9QAVARUB5QAoAK7+Kf2+/On94/9GAXUBAgGaAHIAkACVAOD/hf5W/ef8Pf0Y/v3+nP84ACkBDgL6AXwAUf7J/J78jv2t/gz/uv7d/hQAoAFhAsIBBwB3/i7+tf7h/nn+PP7c/jwAgQEFAssBAgHx/xz/pv4z/nz9z/wp/Tj/9QF4AzsDJgIFAf7/2P5//Y/8y/w+/mgAhgK8A6oDhQKjAHX+o/zr+9z8I/9ZAUcC9AEdAX0AbACHABMA6f6p/SX9wf0M/xYAUQAfAE4AEQGjASwBs/8p/qr9k/7z/08AXf+F/gn/YQBKAXABKQGMAJ7/hv59/Qn92/3z/zUCDQO1AUP/3/29/t8AyAEeAHP9f/wq/h4BEgNuAv//PP5m/rb/9ABiAeMAIADd/yMASADX/1L/dv/z////ov9y/woAkwHqAoAChACk/gf+s/7m/5wAiQBvADUBygK1A2MCL/9b/MX7Wf16/7YA7ADtAF8BLwKVAtABNgDs/qH+G/+s/8b/pP80ANkBhwPFAyoCoP+e/Uf9hv7t/2oAhwAuAS4CnQK4AZ7/rP1h/dr+uwCHAfYAEwDw/5sAPAHwAMv/Ev+f//AADQIkAu4AYP/B/i7/BACYAGcAw/+l/yoAhgBYAOX/s////4cA6ADLAOT/qv4h/qz+6P8TAUwBogBFAKYA8QCKAKf/1P6c/vj+Sv9d/6P/egCaATQCzgGlACf/0v1E/Z39Uv7y/nP//f+fAOgAdADH/6v/FABFAJ7/JP6X/A38MP2D/3cB/gF2Ab8AVQA8AOL/u/4p/f77qvtd/Bv+oQB3A4QFZwWuAj3+//kg+Gb5sPwyAHcCAAOzAn0CPgKKASAA7v3W+0n7p/z5/uYAsgHOAfcBKQIEAhkBLf83/bf82v21/1oBBgKsATIBLAFiAXQBKwGIAL7///6h/sf+Jv/O/xYBcALsAnwCmAGvACUA3/9w/wL/Lv8mAHMBUwJTApABhgDu/zEArACAAJz/pf6Y/vD/nQEkAosB0wB8AGYAGQAi/839U/3A/mkBIAOuAvkAav+8/v7+TP/h/pn+t//7AeED1QOIAbT+d/0X/hT/9v70/bD9M//VAfUD3wNdAZj+lP3d/fv9dv0I/Qv+8wAsBGYFvQNpANP9av16/oL/m//S/jv+4P6kAMACaAS0BDADPgD6/Ar7e/uq/S4AEgLJAnQC4gGFASQBdACG/8P+d/6U/hj/6f+iAEoBIALFAukCvgL+AUQAN/7f/L383P3R/6wBcwIWAq0B9QEYAiEBOf///Gb7jvtg/bf/1QFrAyUE1QNcAsf/9vxQ+8X76v0cAC8BcgF5AYQBqgFEAZH/YP1K/Pf81P6jAEYBoQBl/4X+oP4y/0D/9v4d/8z/qAAzAdoAmv8l/mP91f3z/t7/nABoAe8BAgKZAUsATf6y/ED8D/3B/ooAtwEVAuYBjgH4AOn/0v4Y/o79gv1y/tX/AAEEAr4CywI2AjEBzv9E/ij9Mf1u/iIApAFrAgICCAGJAGgAMAAaABcA3v+7//n/RAAvAMP/hv/v/+MAEALzArQCJQEr/6n9N/0t/sH/yQAfAUMBeAG8AbMBAwHV/6D+6/0K/q7+V//8/78AqwGPAscC7gFdAIz+D/3E/L39J/9vAF0B0gHcAYIBsgB4//L9qfyM/Ob9HAAZApECLQE9/yX+I/7g/q////8nALkAgAHNATMB2/+X/hD+MP5z/nb+rf79/xcCewMoAxAB+/2Y+zf7h/x7/nQAKgJNA1gDLwJ3AO7+/v3y/Yz+Rf8wAFMBFQIwAs0BBQFJACEAWgBlAPj/JP93/mz+4v6o/6oAkgH8Aa8BtgCo/wX/f/7Z/Vr9K/2b/TT/pQHDA5oE7wMlAu3/6/2z/KL8hv36/pEAuAEiAgoCqwFAAd4A/P88/oT8Cfz0/IL+1P+XAAgBegHzAf0ByQBf/mX8gvym/kwBsgIWAlYAA//o/tD/2wAmAY8Au/8+/yD/5/5A/rX9Lv6+/50BvwJDAlgAof6w/hwA+AAPACn+Cf3O/TwAyAKJA0ACuwBjAKIANwDo/pD9bv0a/6kBSwMUA8MBggCc/+D+Vf4R/kH+UP8RAXICqALTAZQAj/8U/+P+oP6C/hD/VwDRAeoCNgNkArUACP/v/XL9tf3Z/mIAugGpAu8COgK8AFb/x/4R/+D/ygAdAXoAjP9i/1QAngHVAUwAJf4j/dv9iP/qAFYBLQE+AawBzgHmADz/F/4i/tr+i//e//3/rQAXAjUDFAOsAZ3/+v1P/SP9If23/V//8wFOBBUFDATCAeX+rfwG/IP8a/2Y/vH/ewEHA7sDMAPvAY4AmP9L//3+Iv4v/fb8LP7AAFQDgQTgA98B1/8s/5L/vP/P/qf8fPqL+qD9SwIEBpAG1wNHAD7+C/5R/qX9ZfxB/OH9igAPAwEEHAPdASIBagCC/5P+dv1X/LX7/fuE/TgAfQP8BcEFMgJX/c75B/kr+6b+CwGEARMB2wBGAdMBhAHf/5j9Yvxo/bv/ZwGWAboA3P/3/9gAgwF4AacARf8V/sr9jf4aAIEBzAH8ALP/0P4w/5AAuwHqARIBz/8P//X++/4v/9r/9gBgAmADBwN4AbH/hv5S/tD+if80AGQAKQB7ALIB+gJqA2gCJADr/Zf8HvyW/O793P9hAs4EnAUiBAEBmv2v+9D7Af2Q/j0ApQGbAs0C6AHFADAAmP+X/mv9ZPyU/N3+CwLwA5IDeQET/6v9xv00/50AawDt/q/9i/23/rUADAIPAlcBTgAs/2D+Cf7T/YX9kf36/rMBUgTJBUYFygF2/K74lPij+7//ZQK3AhEC9AF+ArcCiwER/5T8Qfuj+4j93P/EARwDsQNTA2ACOQHZ/zL+lvze+8D8+f6HAS4DNgMbAgUBqgD2AAUB+f+K/jb+Lv9uAN0AKQBH/z//AgBVAdsCHwNGAan+IP0l/Qv+CP/x/9IAaAHFAfcBaAEVAB7/+P4i/zr/IP8A/2X/gwDQAX8CUQLOAS4B6/80/gn9AP1C/mUA/wFAArYB3ADq/2z/dv+j/7n/cP/g/sH+d//lAHMCxAJpAeP/NP/+/h7/cv9K/57+Sf4u/28BtwMoBFsCYf+n/Ib7a/wh/h//O/+n/3MB9wNFBfwDdwDE/Cf79fvG/XL/mwAmAUwBgQHzAUUC2wGtAE7/If5l/Zb9lv6t/5MASAGmAfgBdgJ6AnMBq/+I/Wb7Mfr9+tn9oAGeBIcFNwTMAb3/hv5x/eT7ivrn+q396gGaBeAGOAXwAdH+yfwR/FL81fyv/an/ZgJZBFsEegIMAL3+t/64/g7+OP1I/Qb/0wG7A1MDKQE1/+n+oP+X/3D+kP0d/qP/yQDqALgANAFcAhMDIwKI/7X8d/t9/N/+8QDMAdYB2QE7ApICxAFr/7f8HPtc+5v99ADCAw8FwQTiAuv/+fwx+0P7+/w1/+0AHwIsA/wDzgPuAej+cPyz+5r8UP7L/6EAuQHBA2AFoAScASH+oPuR+uj6lfyB//gCoQVFBl0EjgAK/ev75vz+/Qr+s/2P/k8BmAQoBvQEvQFc/mz8T/xG/VL+8P5+/+EAMwNSBcQF4gNkAPb8RPvM+3f9y/6d/6YAFQKDAz0EdgNPAev+Hv0g/AL8zfyr/ncBIASgBaEFwwNJAP78dvvO+4P9sf9GAQYCbgLNAt0C8wH//z3+m/2b/av9F/5N/ygBtALJAk8BY/83/ln+ev+UAMMAFQBD/7j+b/64/hAA0QGqAkICNQEhAE//fv5c/WX8s/zi/j4CtwR8BNoBlP4e/DH76/vl/Z4AWAMMBRgFYAM6ANT8xvq4+kv8wv48Ad0CNwN1AiAB3v8v/xn/Av9f/mT9xPxT/af/IgPSBeoFGwML/0D84fsf/bj+9P/eAAsCRQNRA54BLv+w/SP+o/9FAIr/h/5G/jH/0gD6ASYC4AFmAWYAz/4r/ZH81P2BABQD9QOVAhkAKv5v/bv9iv4k/3z/agBMAiMEEAQcAfv8o/o0+3H9av8IABAA+gDLAh8ErgNOAWn+pPwP/A787Pz9/tYBWgTvBAYDNQB4/kX+wv7e/m/+Qv7c/ub/0QA6AUcBeAF9AXkAef6J/Mv77PyO/1UC1QN6A9MB+v+T/uL9B/6T/iD/9/8gAfIB+gFsAdkAvwDvANIA9/8v/jH8rPtq/XUAcQN1BfkF2gQyAnT+7voq+fX53/xMAIcCJAPDAh4CuQGtAY0BtwDM/kf8ffqW+u786QCrBD8GhQXdA1kC9QAX/7z84vqp+pL87/+wAicD6QG4ALUA+gEqA0MCDP+H+/j5HPvB/fD/0QAIAcABVQOCBNkD1AHc/2r+ZP3u/ED9jv6bAFoCsAKGAR8AFQBsAX0CEwI7ALb9svsT++z7xf3s/6gBlgKcAhEC9QGYAtsC0wHC/3r98vvK+8P8XP5PAHkCqwQyBvwFzANtAP78qfr/+Zv6F/xF/qcA4AK8BIoFqgQ+AvH+zfv++TT6MPzG/sYAGQIeA8wDJwQcBAsD0QBd/qH8FvzY/HP++v+kAHgAawAEAYsBMgEJAMz+hf6b/wEBXAFkAOf+IP6K/kv/hP9w/8T/zwAQAo0C3QFuAN7+2v23/Rn+uP65//4AFgKLAisCYQHUAJEAQgCP/0D+0Pxg/IP9tf/CAa4CjgLsAe8A4/9b/1D/RP8D/43+G/4q/hr/4gC+ArkD6QP7A5cDDAKQ//j8Pvs9+//8of/pAfkC6QJBAh4Bzv8J/8T+cP74/aj94P3//tEAnAKYA0QD5QFgAB//K/6m/Y/9+/1Q/2QBNwPAA5sCdQCV/p79gf36/Xn+tP5D/5oAPwI8A9cCBgGC/l/8sPul/B3+Hv/b/5QABQEIAbUATgBAAIwApQD4/2z+DP1m/Wf/TgGmAWIAu/4z/jL/9QBgAoECggFxAJz/ov7I/YX98v0y//0AVgKWAtoBtgDI/w3/KP45/Yr8XfwO/YL+RwBQAlQEewVBBZ4D4wAN/iP8ifta/Db+KgCgAbkCtAOXBOUEzAMUAaH9Kvvw+kX8c/3n/VL+cP+CAa0DXwQeAwUBMv/O/XD8NPsL+6X8r/8NAzsFawVvBHEDpgKyAQgAa/3t+iT6efsz/g4B3QJvAzsDjAKAARUAfv6R/Z/95P3o/eb95v05/mn//gDmAbsB0wDl/3j/rv+VAMwBRQKWAVUAEv9r/vz+ZgC3AYoC5gL0AusCiwJaAWf/TP3i+8X72fyM/k8AtwG8AmADCgNJAcr+qfyA+1r7/ftL/Tv/ewGIA9cE5QSzA+oBGACR/qj9ev3i/bz+/v+vAXYDhwRgBAkDugBb/gX9rvyw/An9sv1S/vn+7f/3AIwBXwGqANr/Pv9K/zEA/gC+ABYACwCqAH8B/wHfAa4BKAIaA6wDBAPyAF3+fPzw+7L8Cv7i/vD+2P4E/2T/1f8VAOX/av/1/qH+Vv47/sv+GABZAe8BIQJfArACAAMNA2sCGAG3/8v+Of6k/Sr9f/0h/04BhwIQAmMAj/6T/bv9Uv6A/kr+Tv7p/tH/YABSADYA1wBDAosDrgOTAvgAtv86/zX/9P6D/sP+5/8lAf4BhQKOAuUBzQCJ/xr+q/yl+0f7wvsx/T//PgGTAvYCfAKCAW0Ad/+k/vv9xv1G/k7/rQBYAv8DJQV1BawEwQI9ALP9jPtY+nb6xvv0/UcA2wFsAkICmwG9AM//sv58/Wn8kft5+7b86P4zARgDQwR0BLMDPAKtAMD/iv+d/4j/Ev+V/tL+6f9iAbwCTAOuAkIBjf/N/Yv8M/yV/EP99f2A/vb+iP9FAPMANgHyAGUA8f/e/zkAvAAfAUgBOwExAXwB+AEYAqsBGQHpACQBWAEjAXoAgf+S/gP+6f00/p3+qf5//q7+Lf+t/ygAWAAVAOH/+P/p/4L//f6r/vj+AgBwAbUCQQPrAjsClQH7AHcAz//X/i7+XP4M//z/CwGmAYwBFAFiAHn/if7G/YT95f10/t/+Yv8XAOQAmwHwAdYBhgH5ACQAXP/0/gb/iP87ANUATwG5AQgCEwKrAe0AOgCi//f+Tv7N/Wb9O/2s/eD+cgC+AUkC5QHJAIT/jf4k/mf+Bf9h/47/AwCwAFoB/AFAArsBtwDM/yr/r/5I/hj+Sv7s/gAADwE7AYwA8f+m/2v/aP+Q/5L/pP8EAGwAvQAJASEB2wBAAJH/Xv+3/ygAqQBZAc8BuQE+AXgAi/+v/hD+8v1P/qX+3v5G/8H/LgCiANAAeAD3/5D/Nv8B/wj/Uv/1/8MAUQFhAfcAbABZANMANgHkAOb/7v65/l//RACpAD0AYf/C/qD+6f57//z/7v9d/+b++P5j/73/1v+q/0P/Bv9b/yoAEwGeAWIBkQDt/+3/bQDkALAA3v83/zP/x/+oADIB5gAoAJ//gv+9//b/1v+A/17/jv/T/7v/Q//6/h//if80ALgAcADO/8H/OQCvAO4AzABmAD8AbAB+AEQA/f8CAFUAoAC3AKMASADC/3T/af9q/33/oP+7/+f/HwA1ADQAOQAxAP3/lP8G/63+3/5z/wkAigD9AEMBQAEUAeoAvABrAP3/lf9B/x//dv9EAP8AJgHeAJAAZwBrAIcAWgDG/zv/D/8B/8j+nv7e/oD/QwAMAZ8BnwEpAaAA9f8Y/2/+M/5K/uX++//kAEsBhgHXASICHQKGAXgAWf95/vH9s/2+/Tb+C//g/6IAZwHnAfEBnQHRAJL/ZP6n/WH9rP14/m3/XAAtAb0BCwIEAokBzAACACX/Wf7s/fT9dP5K/yoA4QBhAZgBgAERATgAOP+L/mD+pf4Y/1n/cv/S/5EATAGnAX0B7ABFANr/zP/0//L/l/8i/wX/Zf/+/3AAqgDHAN4A8ADPAFAAsP86/+v+tP6j/rz+HP/K/5AANwGXAYMBDgF+AP//k/8Y/5X+g/4l/wgAygBeAaYBtAGrATABFwDy/kj+L/6X/i//qP8YAJ0ALwGYAWYBggCO/zD/iP8+AI0AFgBy/0H/of9oAA0BDAGzAIwAngDBAMcAbADA/y7/Af86/5f/3P8TAEcAaACLALwAxgCXADgAr/8z/wT/Gv9i/9L/SQCqANsA1QCuAHYALAD6//H/5//K/67/tv/+/2QAmwCgAIMARQAOAAkAKwBfAIQAbgAoAMT/UP8Z/zf/U/9a/4r/4v9MAMoAIAEIAYQAxv8q/+X+2/7//k3/nv8HAJ8ABgEEAc8AcwD0/6j/r//Z/wIAEAD9//D/AgAzAHcAmgB3ACwA1/+G/0X/F/8M/zn/hf/T/ywAbABkAEAAKQAAAK7/Vv8c/xL/Ov+W/w4AgwDkABgB8gCJACQA1/+c/4P/gP9y/2//ov8AAFkAiwCGAEYA7f/M//b/AQCp/y7/2/7W/i//s/8JACcAJwAgABkAHAAoABEArf84/yn/e//L//3/HQApACgALwBFAF8AWgAdAMf/gP9l/3//q/+4/6b/oP/P/ykAcAB0AE0AFADa/7v/wv/O/8j/t//A//L/JQAsABQA9P/W/8X/u/+z/7L/vv/u/0AAdwB8AIIAmgCeAIMAVgAfAAEAEQA7AFUAOwAGAAAAQQCdANAAlwAHAJf/i/+///X/AADT/6b/rv/p/zoAcQBqADgACQACACYAOgAYAOb/zf/Y/xIAcQC4AM4AvACIAEwAHwAIAPf/xP9w/07/gv/U/xAAMgBIAF4AagBWACAAxv9S/wP/Av9C/6X/+f8TAAkAFgA9AGMAaQBGAAgAxf+F/2T/bf+X/9//LQBYAHMAmQCjAHEABQB9/yP/Ov+t/ywAcQBhACYA+P/0/xMAFADB/1f/N/96//r/cwCSAF0AKQAdABwA+P+r/2L/Rf9j/8f/VQC2AMcAowB1AGIAYQBIABwAAgDm/8H/uv/m/ycAUQBQAD8AMgAtADsATgA8ABEA+f/t/+P/5//f/7f/k/+h//n/eADQANgAngBNAAcA0v+f/3v/df+F/7P/CQBOAFkAPwAcAAEADgA/AF8AQgDz/67/l/+W/7D/7v8ZABUACwAQABYAGQAOAOn/tv+G/3r/mv+3/7f/rf+y/9n/HgBSAEkAFgDY/7f/1f8RADAAKAAPAAUAGwA9AEcAIQDT/5n/qv/d/+j/1P/F/87/+/80AEEABACW/z//PP+A/9j/HwAwABQABgAZADIAQQA9ACoAKQBIAGUAWAAdANz/wv/S/wMASwB/AHkAVAAsAA4ABgAAANv/ov+F/6L/5v8pAFIAagBmAEcANQA6ADAABQDD/5D/kf/C/wIAQQBvAIAAhgCNAIIAVQAJALX/e/9u/4z/zf8QAD0AWwBiADgA8/+//6L/n/+5/+H/9v/l/8r/1f8GADIARAA1ABUADgAeACAACQD6//7/DQAUAAcA9P/g/8z/0//0/wUA7f/I/7z/2/8JABoABADc/7//y//o/+f/5v8TAFUAdABkADkAAwDR/8L/6v8hADoAQABOAFcASgAiANj/kP9z/4H/mv+u/7r/y//n/wAACQAIAAQACQARABAACwACAPP/9/8SABoABwAEACgAWwB5AGUAJgDl/8X/zP/a/9L/uv+r/7T/6f8mACEAz/97/17/fP+9//f////b/7v/x//0/x4AMgAqAAQA4v/q/w8ALgA1ACMADwAXADwAYwBzAFwAMAAPAP7/9v/s/+D/2f/k//z/EAALAOL/tP+p/8L/4//5//r/9/8QAEAAVAAwAOv/vf/L/wMASQCBAI8AcgBLADYAMgAvABgA9f/b/93//f8tAEYAMgANAO7/2v/Y/+n/AQAFAPf/9f8RACgAHAD9/+z/+v8dADYAKQALAP3/DwAoACQA/P/N/7X/vP/c//v/AwD6//v/EQAmABQA3v+u/6b/u//X/+T/2//a//7/OQBnAHAAYABMADQAGQABAOr/0//R/+//HAA6ADoAIwD9/9L/rP+S/3v/af9t/4b/qf/b/xoASABIACsAEQAKAA0AEgAPAP3/7f/0/w4AKgBDAEwAPgAwAEAAZQB5AGoARQAdAP//8//w/+z/6f/4/xcANwBMAEQAIQD9/+//+/8UABoA+P/G/7j/3v8UADgASwBLADwANQA+AD4AHgD2/9z/zf/L/+P/CQAbABsAIwA7AE8ATgA2AA0A4f/A/7D/p/+k/63/v//a//v/GAAgAA4A8P/W/8f/vv+1/6j/ov+1/93//P8AAP3/AAD///D/5//w//f/7v/h/+L/6//y//T/6//U/8T/0P/z/xEAGAALAPT/5f/k//T/AQD2/9z/2f/7/yMAMQAtACgAHgARAA8AGgAkACoAOQBGAEIAMAAZAAUA/P8FABQAGQAXABsAJgAuACoAFwD6/9n/wf+7/9T/CgBAAFMAQwAuAB0ACgDs/8j/qv+k/8H//f89AF0AVwA9ACwALAAsABYA6P+9/7P/yP/W/9D/0f/l//j/+v/r/9L/uP+k/5H/f/9+/6P/2P/8/w8AHgAsAC8AJwAPAOr/x/+8/9H///8yAEsANgAKAPD/+v8jAEgATwA/ADIANQA/AEQAQAAjAO7/uP+U/3z/bf9m/2j/fv+y/+///v/Q/5n/jf+z/+7/EwAFANX/uf/O/wYAOgBNAEAALAAvAFEAgACeAJ8AjgCFAIYAfQBvAGgAXQA0AAMA8v8JADUAXgBkADsABgD1/wIAEwAfAB0A+f/A/5L/g/+b/9z/IwBFAEcARAAyAAYA2P+6/6X/p//S/wYAEAAAAP3/CAARABkAFAD3/9b/zf/Q/9X/6P8DABIAFAAKAPH/2//j//b/+v8AABcAIwAYABQAEgDv/8D/sf+9/8n/1v/c/8T/ov+m/8n/5P/v//D/4//V/9n/4//i/+T/7v/z//X/AQAPABYAJQA5ADYAHQAJAPb/4P/e//j/DgAWACgAQwBYAGkAcQBRABUA7//t//v/EgAqADAAIQAWABcAFwAdACsAMgAyADYAMQATAPr/9//1/+H/y/+x/5f/m//I/+//+/8JACMAJAAGAOj/0v/G/8//5v/q/93/6f8SADsAUQBOADYAJQAmACkAHQASABAABgD9/wsAJwA1AC8AEwDa/5//jP+c/6b/qP+0/8T/zv/Y/+r//f8QABwAEQDs/8P/o/+Q/5f/vf/r/w0AJgA4AEIARQBDACsA+f/O/8P/0v/s/wkAHgAqADcAUQBqAHAAYABFAC8AHAAEAOn/2P/d/+j/6v/g/+T/DgBZAJcAlgBWAAsA2//B/6f/h/9z/4D/qv/V/+b/5f/s//v/AADm/7f/iP9t/2D/Uv9A/0P/bf+7/xAASwBfAFkASwBCADwAMgAkABUADwAbADQAUgByAI0AnACcAJQAjQCKAIkAegBSABYA5P/V/+L/8v/v/+D/4v8KAEQAZgBSABwA6//Q/7n/nf+J/5f/xf/y/wMA+P/2/xMAPwBMACgA8f/L/8H/xf/M/9T/5v/+/xQAHgAfACIAKQA0ADwAQAA8ADMAIwAPAAAA/f8EAA4AGQAqADoAPAAnAAAA2v/J/9j/+P8OAAkA9v/w//v/CwAHAO7/zf+7/7r/vf+4/7P/wf/q/xgALwAqACIAJgAzADcAIwAFAOz/4f/h/+D/5//+/yQAQABDADMAHQAKAPH/z/+u/6X/wP/v/xYAIAAVAAQA+v/1//T/9f/0/+z/2f/B/7f/vv/V/+7/BQAaADAAQgBDAC8AEAD0/+H/zv+8/63/r//J//b/IgA9AEEANwAmAA0A8//e/9r/6f8AAA8AEwAeADwAYQB3AG0ASgAkABAACAAGAAYADgAaACIAIwAhACMALgA5ADEAEADy/+z/+/8CAPT/2f/G/83/7P8QACEAHAALAPr/9f/+/wYABAACAA4AJQA5AD8AOgAuACwANAA5AC8AJgAuAD0ANAAPAPH//P8qAFcAXwA9ABEA+f/8/wAA9f/k/+P/9f8OACIALwA5ADsALgAPAN7/pv9x/0r/OP8+/1f/c/+F/4j/hf+I/4z/h/96/23/Yf9P/0P/U/96/6j/zv/p//n/AgAGAAAA7P/k/wAAOwB5ALAA3AD3AA4BKQE3AR8B5wCvAH4AVAAxABUA/f/w//n/DgAhACgAEwDU/4D/Qf8f/wX/9P7v/vH++f4b/1T/fv+D/2n/P/8d/xn/MP9H/1b/cP+c/9H/BQA1AFgAaQBrAF4ARwA2ADQANgA6AFIAfwCmALoAvgC4AKwApwCvALUApACGAG0AXwBSAEUASwBwAJ8AtgCsAJcAgABnAFUATQBCACUAAQDs/+P/5f/0/wcAEwAcACcALgAnABIA+P/k/+T/9P/6//L/8/8NAC0ASABhAHAAZgA/ABEA9f/u/+//4v/T/9X/4//s//L/+f/1/97/zv/K/7X/hP9e/1b/W/9V/07/Uv9o/4f/pf+9/8z/zP+3/5j/gf99/4T/lP+s/8n/4P/t/+//6v/s//T/9//1//7/EwAhABsACQD7/wAAFgAqACgAHAAKAPj/9f8IABQACAADABkAKgAVAPb/9P8CAAcAAQD3//D/7v/v/+r/3P/K/7b/qP+t/7n/u/+//97/BwATAP//7P/o/+//9//0/+P/3f/x/xIALwBJAFoAYABsAIgAlAB6AFIANQAaAAIAAwAdADAALwArADAALAAPANz/sP+a/5T/k/+l/8v/6P/u//b/BwAKAAIACgAXABEA/P/w/+T/1v/a//T/HgBeALEA8wATAScBNgEuAR0BFAH8AMUAkgCEAJIAsQDRAMgAiwBXAFUATgAZANb/o/9z/0z/Qv9D/zn/Nv9B/z//Kv8V//b+wP6Q/oH+ff6C/qr+4/4B/w7/N/9s/4D/fP99/4P/iv+d/7r/0v/r/w0AKAA5AF0AlgC1AKsAngClALgAywDfAPMABgEbAS0BNQEpARQBCQERARcBAQHTAKYAhgBwAGYAXwBQAEEAQgBHADUADgDv/+L/2P/Q/8r/tv+F/1L/Qf9S/2L/Zf9r/3z/ff9x/3X/h/+N/4T/hv+W/6X/vP/i//r/8v/n//T/BwALAAEA5//D/7f/zv/q/wAAHAA1ADEAKQA6AEwAQQA3AD8ANwAVAAAACwAXABAACgAMABAAEgALAPz/8//4//X/2f/A/7r/vf/H/9b/1v/D/7r/yf/b/9b/vf+f/5P/sf/o/woACwAJAA8ADAAKACEAQwBOAEYAQQBEAEsAUQBTAEwAQQA9AEEAPwA1ADEANAAuACUAMgBNAEYAFADw//H/8P/V/8P/vv+m/5j/0f8zAHAAhgCrANYA5QDkAN8AwwCVAHwAgwCTAKYAsACaAH0AkwDHAMcAhgBBABMA/P8MADAAJADi/7r/0P/o/9T/qP98/1X/Nf8q/zD/N/8z/yv/N/9Z/27/Wv82/yn/MP8x/yf/GP8H//7+Dv80/1r/bv9t/3D/iv+l/5v/g/+V/8n/6v/y/wYAIQAmACYAPwBmAHMAYgBRAFUAYQBfAFMAPgAoABoAIgA/AFkAVgA0AAsA9P/v//L/8//o/8H/j/99/43/lv+F/3j/hf+Z/63/xP/P/8L/r/+q/6j/pP+o/7z/4f8LABoABAD0/wcAIgAmACQAIwAWAA0AGgAsACgAFAAGAAcAGgBBAGYAbABaAEIAMQAkABwAFwAPAAIAAwAoAF4AcgBdAD8AMgA7AFsAhQCQAHcAagBzAG4AawCHAJwAiwB/AJIAmQCHAIwApgCjAIQAbwBrAHQAjACbAJIAlQCsAK0AkQCHAIUAYwBDAFUAdABrAEkAMAAiABsAGgALAOv/0//H/7z/vf/D/67/gP9t/3z/gf+C/5j/pP+G/2r/fv+h/6z/qf+r/67/tP/E/8//1v/y/yAANQAnAB4AJQApADEASABNAC8AGQAnADYAKAAVABAADAD//+//1f+q/3X/Pf8R/wn/Gf8Q/+b+x/7E/rr+nP59/m3+aP5j/lP+PP42/k3+a/6A/pj+uv7i/gj/Mv9X/3H/eP95/5H/x//2/w4AKwBcAIIAmgC+AN4A1QCxAJ4AngCoAL0AxgC7AMEA5wD/APgAAAEPAesArgCrAM8AwQCPAIcAngCUAIAAjwCbAIIAagCAAJ0AlgB9AG8AagBsAHAAYgBHAD0APwAiAO//4v8FACsAVACiAAcBUgGIAdIBKAJRAlYCgQLaAhMDDgMXA1cDiAN4A1YDRgMgA9cClAJVAgMCtwGGAV8BNwEJAaEA+P9r/xz/uP4k/rX9dP0b/cH8pfyk/Hz8Svws/AX8xvuK+2H7Wft9+637yPvt+zD8afyH/LL87fwM/RP9Lv1n/bH9A/5S/qX+B/9k/5//z/8LACUAHQA0AHYAsQDbABIBQwFiAY4BvgHCAa0BqwGpAZEBigGkAbIBtgHIAdYB0gHWAfAB9gHXAa4BjAF2AWoBXwFQAUQBNAEgARUBDAHpALsAqgCaAGoARQBIAEIAGQAIABwAJAATAAUA7v/H/6X/jf9u/17/af9h/zP/Fv8p/0T/Qv8w/x7/Gf8l/zb/Qv9M/1j/aP+E/6T/sP+m/6f/t//C/8v/5P8KADUAXgBuAGYAaAB5AH4AfwCWAKMAiQBzAHoAewBmAGAAZABTADgANAA4AC8AKAAmAB4AIQA5AEUAKgAKAAYABgD2/+D/0v++/6P/oP+9/9X/zf+8/7n/u/+v/6L/pf+z/8b/3f/2/xEALQBNAGkAeQB5AG4AaQB7AJ0AuwDPANwA8QAYATYBLAEKAfUA5wDGAKAAiQBxAE8ANwAsABkABgD6/+X/v/+k/5X/b/8z/w//E/8l/yn/H/8K//v+9v7z/ur+4v7h/uD+3P7i/vH+Bf8b/zj/Uv9d/2D/b/+H/5D/kv+j/8n/8/8SAB8AFwAWADUAXwBzAHsAkgCvAMcA6gAOARUBBwEBAfYA1gCyAKAAmQCXAJcAkQCEAH4AdgBSABoA6f/P/8v/0//M/7b/tP/N/+P/4//Y/73/kP9x/3D/eP9//5X/s//I/9X/3v/g/+D/5v/k/9H/xv/N/+D/9v8EAP3/8v/6/wEA8f/h/97/2P/N/8v/xP+8/9T///8DAOL/0P/N/7r/of+K/23/W/9l/2H/P/8q/zH/Mv8y/0L/Sf8z/yD/Iv8r/z7/Y/+D/5v/tf/B/73/z//6/wsAAgALACIALgA/AGcAjgCqAMMA0ADVAOUA7wDcAMkAzADNAMcA3QAAAQsBCwEPAQUB9QD1AOgAvACqAMMAxgCkAJMAlQCGAHEAaABQADEAJgAUAOz/6P8OABsAEAAlAD0AIwACAAsAFQAGAP7/AADy/+3//v/8/+n/8/8PABAAAAAAAAQA/f///wwADwAPACAAOQBDADgAIgAPAAQA9//f/8f/w//I/8j/yv/c/+3/5//P/7v/sP+l/5z/mP+R/4P/gf+P/5v/nf+f/5z/kf+P/5f/n/+r/9D/+v8HAAAABQAXACEAFQD+/+7/6P/f/9D/zv/Z/9//3//i/+H/1//L/8L/t/+x/6//nf+H/5X/vf/P/8v/0v/i/+L/2//U/8//1//u/wIAFAA6AGIAbgB1AJQApwCTAHoAeQB9AH4AjwCbAJQAkQCgAKUAmQCXAJEAawBEAEMAUQA/ACcAJAAjAA8AAgAFAOz/uP+U/47/ff9T/y7/Hf8f/y//P/9G/1L/Zv9u/2b/av+A/4v/iv+S/6P/sf/C/9b/4v/n/+r/1/+7/7r/0f/X/8r/yf/N/8r/1f/v//H/0//A/8f/0v/a/+L/5//n//D///8JAA0AEQAXACEAKAAlACMALQA9AEcAVgBoAG8AbwB8AIsAjgCTAKUArgCiAJgAnACbAIoAdABmAGUAcQCBAI8AmgCjAKUAowCnALAAswCoAJwAmACYAJQAigCIAJUAnQCNAHgAbwBgAEcAQABEADAACAD9/wIA7f/O/8z/yv+v/5n/m/+P/2j/Uf9Y/17/Wf9U/1f/Wf9U/0n/Pv85/y//IP8j/zf/Qf85/zL/Nv9E/13/d/95/2z/aP9n/2L/av+L/67/wv/D/7n/tf/J/+T/6//n/+j/4//d/+v/BQAMAAoAEQAYAA8ACgASABMAEgAZACQAKgAzAD4AQAA4ADAAKAAcAAsAAgAHABMAHgAxAE4AYABZAFMAVgBKAC4AKAA3ADgALQAxAD4APgA7AEQAUABSAEsAOwAgAAwADAAcADEARgBTAFEATgBYAGcAZQBQAD4AOAAxAC0ANgBCAD8APQBMAFIAQAAwADgARABCADoALQAbABIAEQACAOz/5f/k/9//1//I/6r/i/9//3v/dP9x/3L/a/9o/2z/Z/9j/23/ev9z/2j/c/9+/37/jf+2/9b/3f/l//7/EwASAAoADAARAAkA+//8/wcABAD1//b/DwAnADAANAA4ADMAHgAKABIALwA/ADYAKwAqACgAKAAyAD8ARgBOAF4AawB0AHQAaABbAF4AcACAAIsAkQCKAHwAeQCAAIMAgAB8AHoAdABlAEoANQAwAC4AHQACAOr/3P/X/9H/xv/C/8T/uv+o/6D/nf+O/4L/jv+f/6D/nP+k/7D/wP/Q/9b/2P/q/wAABgAIABgAGAD+/+7//P8IAAMA+//w/+D/1//Y/9X/yv/P/+n/AgAOABcAHgAhAB4AHwApADcAQABEAEkATwBOAEUAQABLAGMAdwB8AHsAegBzAGsAaABjAFYASwBHADsAIAAHAPn/8f/r/+T/1//I/8P/vf+x/6T/nv+b/5v/pv+v/6v/o/+k/6v/s/+6/77/yP/Z/+P/4v/r/wUAGgAdABMABAD4//P/7P/i/9//4P/R/7v/uv/F/8L/sv+s/6n/m/+B/2b/V/9Z/17/V/9N/1X/YP9X/0T/QP9H/0//Xv91/4v/k/+W/6P/t//D/8L/y//g//P//P8KACAAMQA/AFgAbgBxAGsAbQB3AIMAjACNAIQAdgBwAHIAfgCMAJQAkgCFAHcAbgBmAFwAUwBPAE4AUQBZAF0AVQBPAFYAWwBWAFcAWwBSAFEAZwB8AHMAYABiAG0AagBgAGAAZwBoAGIAUQBAADUAMAAqACMAHAAYABYACwD5//H/8P/g/8X/sP+h/5H/jf+Z/5v/i/+G/47/iP9y/2L/Yf9h/17/X/9j/2b/bf9y/3P/cP9y/3z/jP+T/43/hf+L/5n/nv+c/57/qv+9/8v/1f/c/+T/7v/9/w0AEQAQABgAKAA4AEcAXABrAG0AaABmAGkAawBqAGAAWABZAGEAcQCGAJMAjwCBAHUAbwBsAGsAZABXAE0ATABOAE4ATABKAEMAOwAyACgAKQA2AD0ANgA0ADoAOQAqABYABwD7//f//f/+//X/7P/r//b/BQALAPz/6f/h/+X/5//a/8j/vv+//73/tf+y/7T/s/+w/67/qv+c/5T/mP+i/6b/q/+w/7X/u//C/8j/zP/U/9v/3P/Z/9r/4v/r/+//+f8LAB8ALgA0ADUAMAArADAAPAA/ADIAJgAkACYAHgANAAIABgANAA8AEQAVABMADQANABkAJwAuACgAHQAZACEALAAvADMAOgA6AC8AJgAkACAAFwASABEAEgAXAB8AJQAlACAAHAAYABYAFQAPAAYAAQAEAAEA9v/s//H/+//4/+n/2//S/8b/tf+l/5z/l/+W/5D/hP9z/2j/Zf9j/1//W/9Z/1f/U/9R/1H/Wf9p/3j/gv+H/5L/of+r/6r/p/+s/7T/uf+5/77/yv/Z/+f/7v/q/+j/7v/4//r/9v/0//T/9P/2/wAAEAAbAB8AHQAWABAADAAKAP//8P/r//H//f8HABEAFQASAA4AFwAqAD8ATABTAFYAWABcAGQAbAB0AHsAhgCSAJkAnACZAJQAkgCVAJUAigB7AHgAggCKAIcAeABiAEoAOwA1AC8AIgAUAAQA9//y//v/AwAAAO//3v/N/77/tP+w/7H/s/+0/7X/uP+5/7b/q/+d/5j/mf+b/5v/o/+1/8X/xf+8/77/zv/Y/9P/zf/V/+L/6P/m/+P/5P/j/+D/3P/j//X/BgAOABcAJQA0ADoAOwA8ADgALQAkACsAPABFAEYASwBcAGwAbQBeAFMAUgBbAGUAbQByAHkAfwCDAIMAhgCIAH8AcABrAHQAfACBAIoAkQCVAJwAqQCxALEAtQC8AMAAyADbAPMA/QD8APwAAgEFAQMB/AD4APsAAAH9APEA6gDrAOgA2wDRANQA3ADbAM4AxADAALwAtQCzALkAugCuAJ8AnACjAK0AtgC7AL0AuwCzAKgApgCrAKkApACrAL0AwACpAIoAfgCMAJsAmQCGAHQAZABPADgALAAoABsA/v/b/73/rP+k/5T/df9U/0T/PP8o/wn/6P7L/rf+sP6q/pf+fv5t/mD+T/5A/jb+Jf4R/gX+AP7u/dT9w/28/bH9of2O/X39cP1o/V/9Uf1D/Tf9KP0Y/RT9GP0X/Qz9Bv0P/Rz9G/0U/Rv9NP1L/VL9VP1j/Xr9jv2c/av9vv3W/e/9A/4g/kf+af6B/pv+vf7c/vH+Cv8u/1X/c/+I/53/vf/r/xYAMwBKAGYAhACfAL0A4QD+ABYBNgFUAW4BiQGqAcEBygHTAdsB3gHmAfgBAwIFAg0CGgIaAgsC/wH6AfIB7gHwAeoB3AHQAcgBtQGcAYYBbgFPATEBFwH1AMwApgCJAG4AUgA0ABEA6P/F/63/n/+W/4r/e/9u/2P/Xf9g/27/gv+V/57/nv+f/67/zf/m//H//v8aADUARwBTAGEAbgB6AIcAjwCdALgA0wDaANgA4ADrAPEA9AD7AP4ACAEbASkBJAEbAR0BJAEnASoBKgEnATABQgFDATMBMAE/AUsBTgFSAVUBUwFXAWIBZwFlAXEBiAGZAakBuwHNAeYBEQJCAl0CbwKTAsYC8AIOAy4DWQONA8oDBgQ+BHUEqgTfBBoFYgWpBegFIwZmBq8G9QYxB2gHmQe1B6sHjgd9B3UHVQcSB8gGjQZeBiwG5QWJBSIFvARPBNADSgPEAjECkwH/AHQA2v80/5n+B/5v/cv8FvxM+4L6yPkV+Vz4r/cf9572Ivay9UT1zvRk9BP0zfN98zHz8vK58onybPJc8k/yTvJe8mnybvJ+8p3yv/Lo8h3zVPOH88TzEvRj9LX0EfV19dX1M/aZ9gb3dPfg90D4nfgF+Xv57flP+q76G/uT+wj8efz1/Iv9K/7A/k//5/+KACYBtwFCAswCWQPlA2ME4ARyBRYGrgYzB7sHTgjgCHEJ/AlxCs8KNwu0CzgMtgwmDXYNqw3cDQsOIA4dDhkODw7qDbENeA05De8MogxRDO0LfgsNC48K/QloCdMILwiAB94GSAaoBfsEQQR2A50CzwERAVIAkv/X/iT+f/3u/HP8+Pt7+wH7i/oS+p/5NfnU+IH4PvgK+N/3u/ed94j3evdr91X3Q/dC91L3a/eM97v39fc0+Hn4w/ga+Xv51PkV+lD6pvoS+3/75/tP/LX8G/2G/e/9Tv6s/hH/cP/I/ycAhQDLAAoBYgHJASQCdwLHAgIDKgNSA3kDkwOiA7UDwQPBA8cDzgPHA78DzAPjA+UD1gPFA7EDkwN1A1oDPQMiAwMD2AKmAoICaQJEAgcCvAFzATIB/gDNAJAATAASAOL/tf+L/2P/Qf8c//D+sv5z/kr+Qf5C/jb+G/72/dH9sf2b/Zb9of2v/bL9sv3B/eD9B/4v/lH+bv6b/u/+Xf/M/zMAlgAAAYYBMgLrApoDVwQ5BScGBQflB+AI7wn6CuYLkgz2DD0NkQ3rDTQOaw6SDrAO4w43D4APiw9UD/kOgw72DV8NwQwTDE0LcQqMCb4IFwh2B6gGlQVRBPYCmQFIAPz+p/1L/Pb6s/mR+Jr3v/bp9Qz1KPQ981zynvEF8Xbw0O8c73vuB+6/7Y/tWe0L7arsUOwY7AzsFOwT7AXs9+sD7DjshuzQ7BftcO3X7Tjumu4S75nvFvCM8ALxdvHp8Wvy8fJq897zY/T19JX1WfZE9zT4G/kV+i/7Vvxz/X7+bf9LAC0BHwIVAw8EEAUTBgkH8AfVCLsJoAp8Cz4M4gxzDQcOqw5gDxgQuBA0EaARARJHEmwSgxKVEpYSdxI3EusRqhF8EUQR4RBaENUPXQ/jDmYO+Q2aDTMNtww6DNkLiwsuC7AKGAp3CdUIMQiOB/AGYwbnBWkF5QRwBAQEdgOuAtAB/AAmAEv/fP68/fX8Jfxn+8T6Nvqn+fj4F/gb9yz2Q/VM9FrzkfLr8Uvxt/BO8B/wF/AO8OrvsO+A73bvne/q70nwofD/8InxU/JF8zb0E/Xk9b72ovd9+Ev5L/o++1P8R/0t/i3/QQBCARQCwgJiA/4DigTpBB4FSwWKBc0F+gUPBhcGFQYABt4FuQWRBVwFJAX2BNEEqAR6BFEEKQT9A9ADnANaAxAD1AKrAoYCZAJVAkwCNQIiAiwCSgJjAnECdAJoAlUCUgJfAmcCYAJLAiUC8QHAAZYBZQEfAc8AfgAqANL/gv9F/wz/vP5A/rP9O/3k/KL8Yvwb/M77jftq+1/7Xvtd+1j7PvsW+wX7GPs/+237rfsC/Fj8qvwL/ZD9KP6//j3/pP8TALYAkQF5AlEDLAQnBUgGgQfTCDwKpAvtDBAOJg9NEJERyhK4EzAUXhSbFA8VjBXJFaIVLBWoFFcUNxQBFG8TihKAEW4QWg9HDj0NNQwjC/gJqghPBxEG/wTwA6ECCAFM/6D9IvzJ+nz5Gvio9lT1S/SI89jyHfJX8ZPw2u8076ruNO697TXtm+wO7LnrpOuV60jrxepR6g3q2emT6T7p8Oiy6IvofuiN6LXo9+hK6aDp9elV6sHqL+uk6yvsuew77b7tYe4o7/fvv/CX8ZDypPPG9Pn1SPe7+Fn6FPzQ/XX/AQGEAgQEhQX9BlMIdQmCCrALCA1UDmcPShAeEesRshJxExwUmhTlFBYVTRWeFQEWThZbFigW2hWQFUgV8RSGFPMTIRMnEkkRrBArEIQPpQ63DeYMRgzACzELiArVCS8JnwgjCLcHRweyBvQFNgWcBBoEjwP1AlgCtwEMAWQAyv80/5X+4/0d/UH8YPuT+t35J/le+IP3oPbD9fn0OPRb81byTPFi8I/vue7j7TDttext7EbsNuw+7GrsuOwT7XDt4u187jTv+O/S8NTx+fIw9H313PYw+Gb5kvrW+yj9aP6N/6gA0QESA1sEjwWfBpQHgAhZCf0JZwqpCtEK4QrXCr8KnQpyCjwK/wm4CW4JJwngCIoIIwi6B18HDAe8Bm4GKAbwBcgFpQVzBSYF0ASNBFsEIgTWA4gDRgMMA90CwgK5ArICpwKZAoUCYQIuAu4BoQFPAQYBwABsAAUAov9B/8v+OP6e/Qz9ePzf+0z7xPo++sT5Y/kY+dj4p/iL+Hv4cPh0+Iv4s/jo+DD5hPnW+SL6dPrR+j37wPtT/Nv8WP3y/bn+lP9iACEB1AGAAicD0wN9BBIFngU0BtYGegcpCOsIsglxCjILDgwNDR4OJA8XEAURBhIVEwoUxRQ9FWwVYxVLFT0VGhW3FBUUZhPIEjsSshEYEVQQZg9nDl4NPgwNC+MJywi2B5YGZwUvBAID7gHaAIj/5v0X/Ev6kvj39nL14/M/8rXweO9/7qPt0ez76w/rJepw6e7oZOi75xHneObo5XLlH+XU5HDkAOSf40rj/eLP4sPiu+LC4gXjjuMt5NjkqeWX5oHnc+iO6cjqA+w37Wbuje+88BjylvP+9EX2k/f5+G/6BfzH/ZT/TwEWAwsFEQcCCe0K0wyMDgcQZBG1EuQT8BT7FQYX6BeYGDUZyBlAGpka0RrbGq8abBonGt8ZkhlPGREZwxheGOEXPxd6Fq8V6RQHFO8SuBF5EDAP5g23DJ8LdQoxCfYH4wbyBRgFVwSlA+sCHwJRAYoAxv/y/vz94Pys+3z6Y/ld+F73W/Zd9X30vvMK8z7yVPFi8IPvxu4q7p3tFe2Y7D/sG+wl7EXsYexd7DvsDOzl683rzOvo6yXshOwR7dnt2O4D8E/xqPL+81H1r/YX+IT5+/qD/BL+l/8YAaECLASmBQUHPAg9CRIK3wqmC04M1wxqDRcOyQ5pD/kPbhC4ENsQ7BDuEM4QhBAWEJIPAw9vDtYNNg2TDPMLUQuuChYKgQndCCwIjAcHB4oGCAaLBQ8FiQT+A4ADAwNmAqkB8QBOAK7//v5F/oz91Pwi/IL78Ppc+sP5K/mh+Cz4z/eF90D36/Z99gj2r/V/9VH1/fSG9BX0yPOg85jzpvO8883z4vMa9IX0GvXE9XH2E/es90r4Bfnh+dH6vPud/HX9S/4g//z/4ADCAZUCUwP4A4EE/gSIBSgGyQZTB8IHIQiHCAYJmAkfCoQK1AoZC08LcguTC8kLDAxMDIcM4Ax6DXEOrg/+EDMSSxNfFHMVcRY1F48XcxcJF5EWJBa2FT0VrxT0ExITOhKFEcgQvg9aDq8M0QrfCA4HbwXcAy0CbAC5/iD9ovs0+rH46/bW9JLyTfA17mXsyOo+6cfnieaf5QvlxOSe5GDkAeS747jj0uPa49fj6eMR5EvkquQx5bjlIOZt5q3m4+Yd53Tn5edY6MfoS+n96ePq+es07XzuwO8J8XDy/vOs9V738PhM+ob7v/wI/l7/xQA0AqADCgWKBj4IIgokDDUORRAxEusTgxUOF4kY3hkCG+obkhwUHZUdHh6IHqsegR4YHowd+xxoHK8bqxpyGS8Y9BbAFZUUcRM1EskQRQ/ODWMM8QpsCc8HHgZsBNECUAHd/3T+Ev23+236U/l1+L73FveB9gH2j/Us9db0dfTu807zp/Lz8SnxZfDB7y/vlu4F7pTtNe3X7IbsROz364/rLuv66vbqEOtF65zrGuzG7J/tke6B72DwJ/Hb8Zbyc/Nu9HP1iPbK9zf5wPpr/Ef+OwAgAvEDtQVbB9gIQwqyCx0Ncw64D+kQ/BEEExgUExW5FQUWFhYBFsoVkhVnFS8V0RRkFP4TmxM2E9gSaBK7EcgQqQ94DksNNQwoCwYK3wjgBwMHEwYKBQ8EJwM4AkkBaQB+/3X+e/2//C38n/sZ+5b68vkr+Wb4qPfR9t/17PT68wjzN/Ki8THxxfBY8O/vju9F7x7vAO/k7vPuQO+d7+DvJ/Cc8DTx2vGQ8kDzyvM/9NH0ifVN9iL3Kvhm+a769Ps2/XH+pP/WAAkCNQNUBGYFYgZOBzoIKwkLCsoKagvmCzsMhAzaDC4NXA1iDV4NZQ1yDX8Nfw1nDTkNCA3TDJMMSQwDDMoLlgtfCxkLygqKCnMKeQqCCogKrQoKC60LlgyxDc4Oxw+XEFURCxKqEg4T/BJVEjoRABDsDgQOGA3xC4MK9Qh6Bx0GwARNA78B+//m/aX7m/n796D2RfXX81byyPBP7yHuMO0h7LnqI+nD58rmMebO5YblZeWR5RXm1ea256PogOk86vHqu+uH7Dvt3O1z7uDuKO+C7wvwifDQ8PfwH/FA8WXxvfFS8vfylPMy9Nf0jfV39qb34fjt+dT6zPvz/Ej+wP87AZYC2AMZBWAGqQftCCMKRQt4DOMNdw8AEXwSFxTHFU0XhBh/GT8aqRqxGnEa/hlXGYEYjheOFoIVXxQgE8gRXhDfDk0NrgsDCkUIewbDBDsD3wGeAGL/I/7o/MH7s/qt+aX4n/eg9qX1v/QF9H7zJ/P88vbyBfMp83Xz4vNN9KX07/Qj9S/1HPUB9dT0dPTq81jz0vJU8tvxa/ET8eDw0/Da8O3wI/F58dPxJvKl8nTzdvSG9aX26fdN+cz6bPwh/sT/NAF2AqwD8ARFBp4H8Ag+CpEL8AxnDvIPchHDEtwTyBSJFSMWohYGFzcXJhfmFpYWPhbZFV4VvRT1ExcTLxI/ET8QNA8oDh8NHgwqCzgKQglLCEwHOQYiBR0EHQMCAtcAxP/K/sX9vvzZ+xX7SPpn+Y74yfcO91r2tvUh9Yv06/NI86vyF/J/8dbwH/Bq78LuKO6i7TLt1uyV7ITspOzX7ArtTe237UXu4O6A7yjw3fCl8ZDyrfPr9Cb2R/dl+J756vol/Ev9dv6r/9cA7AH3AgAEDwU3BngHrwi7CaYKiAtzDFsNIQ6cDsYO3g4XD2IPiQ+GD20PSQ8fDwIP/Q76Dt0OoA5BDs0NWw34DJUMHAyMC+cKLwp/CfgIhQjtBxgHJwZIBX4EvQP0AiECUAGWAAMAnv9w/3H/hv+c/8X/IAC9AIsBawIyA8gDOwSxBDkFuQX1BbkFDgU9BJADEwObAv8BLgFEAHr//v61/ln+wP33/Bj8Nftm+rf5G/l++Oj3Y/fq9nX2DPar9UL1y/RG9LnzSPMk81TzqfMK9JD0UvVA9kX3RfgK+W75ofnm+TH6Tvo2+g362/mY+V75RPkn+dz4Zfju94n3KffR9qL2xPY198/3Zfjx+I/5SPoJ+737Uvy+/Ab9T/3I/Yj+cf9bADQBCgLpAtADtgSQBV0GGwfNB3oIMAkACu4K3wunDC0NdA19DTsNowzJC7wKgwk+CBsHKgZOBW0EiwO6AgICZwHZADoAbv98/ov90fxp/EL8Jvzr+537YPtK+1D7Vvs4++r6h/o++i/6X/q7+ib7gPvK+yL8i/zw/DT9Rf0a/cf8ePw7/O/7evvs+mP66vmB+Sv5zPhT+Nv3m/ep9+73XPjx+LL5n/qu+8v86v0Z/2QAqQHBArUDrAS4BdQG+AcXCRYK7gq2C4UMWA0iDs0ORA+ND8AP6A8BEA4QEhDzD48P8Q49DooN2wwsDGsLfApvCXoItAcAB0YGjwXcBB4EZwPcAnEC/QF8AQ4BswBMAM7/Sf+8/h/+ff3f/DH8YPt9+q75APlk+M/3NveI9sb1CvVu9OHzSvOm8gTybPHh8HLwIPDS73zvMu8M7wLvAu8M7zHvf+//767wgPFy8orzuvTn9RP3Xfi7+f76Gfww/Vz+jf+9APYBJgMnBPoExwWmBoEHNQi3CBkJgQkCCpAKEAuDC/gLYgyyDPMMLQ1UDWINXw1NDSEN9AzsDA4NMQ00DRQN3AyjDHYMSwwMDLcLVQvbCkgKxgl1CS0JtwgJCDYHQQYyBSYEIgMJAtAAkP9Z/in9B/wE+xj6LvlN+HD3gPZ99Zn0AvS285TzkfO38xn0wvS19er2XvgE+q/7K/18/uH/ggE/A80E8gWrBiwHswdTCOsITgljCTAJ3QiPCEgI6wdvB+AGPAZsBYMEsAMLA3gC4gFGAaAA8P9V/+z+m/4n/n/9zPw4/NL7mfuL+5j7svvc+yb8lfwT/Xz9u/3U/d/94P3N/ZT9NP3D/FT85/tg+6L6sPmr+LD3wvbI9bT0mvOu8hXyvfGC8VnxVvGD8cLx9vEf8l7yz/Jn8wX0mvQ/9Rf2K/db+Hz5dfpL+xz8Av0B/gr/CwAOAS8CeQPUBBMGHgf7B60IHgkuCdcIOwh7B6oG3wU1BbMEQATGA0gD3wKTAk4C8gF4AecAXAABAPX/JwBvALcADQF7Af4BhAL7Ak8DcwNvA1cDRANSA44D1wMDBBsESASNBMEEwgSRBEAE2gNqA/QCbgLPARsBVQCE/7b+7v0k/Vz8r/sf+6L6S/pE+pn6Hvut+0b88vy5/Zz+iv9iAB8B3AGoAnoDUQQ5BSUG+AauB0oIvAgBCTkJdQmeCZ4JfQlPCRIJzgiKCEAI3wdVB5sGtwXLBAEEWAOrAu0BLwGHAAUAsv98/zb/0v5z/jf+Gf4K/gb+Bf4A/gL+Ef4T/vL9tP1m/f/8fvz8+477I/ur+jH6zvmF+Uf5/fiT+Aj4avfL9jv2u/VG9dz0kfR99KP08fRQ9bD1DfZz9vL2fvcJ+KD4ZPlX+mH7dvyh/eL+KQBkAYgCgwNJBN0ESwWkBf8FZAa+BvoGIwddB60H+QckCCMIBQjaB7MHmAeMB5EHnAesB8oH/wdACH8IsAjJCMQIrwiZCHgIQggICOIHywevB5AHdwdNB/gGggYOBpoFAAUpBCQDEwIKAQgACP8A/uT8rftp+kH5Tfhu93X2XfVM9GPzp/IV8q3xXfEV8eHw7PBK8dfxaPIG8+bzGPVy9sP3FPmO+mP8qP4zAacDwQWeB5QJyQsEDugPLRHDEfMRIhJ4EsMStBI7EoUR1BBLENAPKQ9NDlwNWwwpC88JjwibB+UGUwbQBT4FkgT5A7EDogNxA94CAwIsAZoATgAWAMf/aP8d///+E/8t//3+Yf6Q/dX8Ifw0+wv60fiQ90H29PSn8zbykPDZ7ibtauuy6Sro6ebm5S/l2+TZ5BflpOV75mHnLuj86O7pBetD7KrtGO928PXx4PMb9kb4JPrG+0f9uP4rAJoB5AL5A/wEFgZXB6oI5gndCoML8gs1DDIM0gsjC1MKiQnnCGcI8weDBzwHNQdiB6UH7AcnCEsIZQiPCM4IGQl1CeoJbwryCmkL0wsqDG4MpQy8DI4MEAxtC9UKTQq9CRIJRwhgB3QGmwXSBPUD7AK3AWQA+/6Q/Sv8wfpG+c73fPZU9Vv0p/M88/vy1fLx8l7z/fOu9IH1dvZy93f4o/nw+jD8Wv2I/sL/9AAQAggDvwM9BLEELQWOBb8F0QXbBeYF/AUYBhsG9AW5BXYFHAWoBCQElwMGA40CPgL6Aa0BawFQAVIBZQGCAZsBrwHZATECngISA6MDTwTvBHIF6gVFBl0GMgbiBWMFpQTSAxUDXgKNAa0A4P8s/47+/f1N/Vr8Ovsw+lj5r/gk+KT3Gvee9mD2dfbA9hb3Vvd495j3zfcT+Gv48fi3+Zr6evtj/F/9Y/5s/4IAgwExAooCtwLYAvcCIAM+AzED/QLQArcClgJuAk4CHQLJAXABMAEAAdYAywDkAAUBKwFxAdIBKQJgAoIClgKoAsUC6AL6AvYC8AL7AiEDZwOwA84DwAOlA4ADNgPDAkICrgEAAUoAn//l/g7+Pf2X/BD8gvvU+gT6HvlM+Kz3MffB9lT29fW79cL1FvaY9if3w/d/+E75F/rX+rD7vvz5/UH/hQDYAWcDUwWsB0sKzgzuDsgQrxKzFIYW1hd/GJIYVBgaGPAXhxerFocVWRQ4EyESAhGxDyUOkgwkC8QJUQjhBp0FmATYA0YDogLIAecALgB3/4v+cP1A/AT71fnS+Oj3+/Yt9q31ZPUV9aT0BPQ2823y0/Ew8Snwzu587UzsJ+sJ6unooudD5g7lEOQY4yfiguFH4XPhCuL/4hLkNeWy5qnoxOqq7Fvu/e+Z8UnzH/UJ9+L4rfqC/GP+SgA2AgUEmQUFB2gIvAnxChwMWA2UDrkP0BDaEcMSeRPpE/kTpBMRE2QSnxHFEPIPPQ+iDicO4Q3NDdUN7g0HDgMO1g2NDTENwwxPDO0LigsDC14KxAk+CaYI5AcBBwMG1wR2AwQCqwBw/z/+Fv0A/AX7Gfo4+Wz4tPfy9gn2/PTk88zyrvGH8G3vfO7F7VDtG+0q7XrtBu7M7tnvM/HF8ln0y/Ul95D4Kfrq+7L9Uv+zAOwBJwN2BLwFzwaQB/UHFggwCGwIuAjuCBwJawnkCWIK0QpDC7QLBQwdDP0LsAtDC9AKdAo6ChcK/AniCdUJ9Ak0CmQKXwo+CiwKLAooCiMKIwonCiwKNwowCuoJPwkwCNkGVgWzA+IB3f/R/fX7XPr8+NT33/b29fX08PMG8y/yYvGp8Azwi+847znvkO8Z8Lzwb/Ec8rryU/Pa8zP0dfTp9LL1rPax98T46Pki+4H89P0v/+z/OQBaAGsAbABfAEkAKAAHAAMAJgBZAJQA2wAsAXoBvQH1ATACkwI0A/0DxASDBUwGIgfvB6IINQmfCdoJ/AkVCh0KBArWCaoJkwmFCWwJLAm5CCMIfgfLBv0FDwUDBOACwAG8ANb/7/79/SL9dPza+zX7f/q9+fH4QPjO94z3UPcf9xf3Sfeq9zz46/iK+Qv6kPoi+5f74/sy/Kn8Qf3z/cD+ov+iAOUBgQNbBVQHTAkZC6UMIQ61DzURXRIcE3gTZxMAE4cSFxKJEb0QxQ+6DrkN6AxBDJQLywr9CSsJSgh4B9AGLwZmBY4EwgPoAvoBIwFcAFj///2G/Bj7vPmI+ID3fPZj9Wj0w/Nw80rzH/Ot8tjx3/AE8C7vJ+7p7ITrCeqz6L3nEudy5tzlfeVX5V/louUi5r3mfOeK6OvpcusN7cTuhfBC8gT0u/VE96n4GfqS+/H8Sv7N/30BPQMFBcoGaQjeCVYL0wwgDi4PJhAdEQsS4hKdEysUhBSuFKIUTxS2E+US8BH0EBsQbA/LDjAOvw2MDXwNYw0uDcoMKQxICzgKDAnQB5AGTQUCBLQCfAFwAIf/n/6Z/X78avtt+nb5dfhs93L2nfXx9Gb06PNq89/yUPLL8U7xuPD27yPvaO7R7VjtCe337B/th+1L7nDv1fBd8gn02PW194r5RvvW/Db+f//NACgCkgMDBWEGpgf9CIwKOgzIDQwP/A+eEBwRpxFCEscSIxNnE6IT2BMVFE8UURTwEy0TJhL6EMsPsA6sDcIMCQyGCysL8wrjCtwKqAo0CowJtwi7B7sG0AXqBOwD3ALaAesA8P/C/kT9g/uo+eD3Nvap9D/z/PHq8Bjwju8w787uSO6h7ezsNOx969fqYuo66mfq2+qL63rspe367lbwovHX8vTz9/Ty9QX3S/i6+T77yfxH/qj/7gAuAlsDQQTABO4EBQUvBXoF4gVaBtcGWAfVB1kI9QiXCQIKFAryCdMJwgm+CdoJFApHCmEKfgrACh8LdwumC5sLZwsyCwwL6Aq5CngKIQq2CUoJ3QhhCMgHFQcvBvgEfgP4AX4ABP+H/Rb8uPpv+Un4Wfer9j72+vWz9UT1uvQy9L3zXfML87jyavJF8mvy2PJz8y/09/Sz9Vn2+vag90X46vii+YH6i/u5/BH+of9zAXsDnAW5B7sJiwseDZEOARBlEZ8SjBMUFDkUMRQ+FFsUPxS7E/MSLhKYES8RxBAtEGYPig6iDaMMjgtcCgIJkwcvBtEEVwPUAYIAav9R/gX9i/sF+p34c/dz9m31U/RO85TyQfI08hXynfHk8DnwnO/N7rbth+xh61TqhukJ6bXoc+hi6Jno+OhV6avp/ulV6sPqWesN7OTs9e0775Pw/PGC8w31f/bh90z5sfoJ/H/9Lv8IAfoCAgUJB/kI1AqbDDgOnQ/PENgRtxJ9EzsU3RRSFbMV/BUHFsUVThWkFLUTnRKYEa4Qvw/IDtoN7gz8CxALIQr+CI4H4gUYBFcCygCD/1f+IP3y+/j6QfrF+WH52/gc+EX3gPbK9Rb1efQG9LfzffNR8y/zFvMS8xbz/PKy8k3y5vGP8V/xY/GJ8cfxMvLY8qjzpPTZ9TT3fvis+eH6Kvxw/a/+/P9QAZsC5wNJBcEGSgjiCYYLMg3jDocQ9xEeExUU+BS3FTIWYxZXFiMW6xXNFcEVoRVNFbYU4hPpEuARwxCIDy4OxQxoCz8KagncCFoIuAfoBuQFqwRPA+IBVACY/s78LPvQ+cD4+Pdd97z2+/Uk9Tf0IfPt8b3wo++Y7p/t1+xY7CHsD+z067braes26yjrNutb66nrNewJ7S7une8o8aryGPR89dH2BvgY+Rz6LPtP/Ij94v5xACYCyAMxBXAGnQetCIkJMgqxCgsLVQuyCyIMgwy6DNUM7QwHDRkNCw3MDGAM6Qt9CyML4wrMCtAKzQqzCpMKcwpDCvMJgAnkCCUIWAecBvEFRQWOBNgDNQOqAisClwHNAND/vf60/b38zPvX+tr53fjs9xv3bvbP9SL1aPS78yvzq/Iz8tfxqfGS8XTxXfFs8a/xIPK48mrzHfTS9KL1nvau9674hPkp+qv6Kfu0+078+/zQ/dT+/P9NAd0CqwSjBs0INAu4DRgQOBIvFBgW6xeAGaUaOBtFGwAbmxonGpQZ0xj+F0oX0xZ6Fg4WfhXGFOATyBKCEQkQWA6GDK4KvwiiBnYEbQKFAJv+l/x3+kf4M/Zv9PXym/FV8D3vY+7K7XHtPO3x7Hbs4es663bqn+nK6Ovn3Oax5abk5uN+427jqOMT5KLkY+Vg5pvnAela6nnrZ+xT7UXuMu8n8DfxUvJy88L0X/Y0+Cn6TPyZ/u8ARwOuBRkIbgqoDLgOehDyEVAToBS2FYAWFRd+F7UXzBfQF58XIhdtFqUVxxTaE+0SARL/EOoPzA6dDVAM3Ao1CUsHNgUfAyABPf+E/fT7lPqC+dr4fvg2+PH3tvdw9wr3ovZR9gD2mvU19ef0pPRt9FH0UPRS9Fj0avSC9Jn0xPQE9Uv1mfX/9W72y/Yp97P3X/gD+ZT5Mfrt+sT7rPyf/Zn+o//AAOsBFwM9BGoFswYnCLYJLwt/DL0NAg8/EFgRPxLyEm8TwhP4ExUUFxQNFAYU9xPKE38THROhEgASLhEeEMwOTA3BC0MKzQheB/oFqQRqAz8CHQHv/6X+S/3++8L6ivlc+Ez3ZPam9RP1oPQm9IPzzfIe8mXxhPCN77PuGu6+7Y3te+2N7dXtW+4G77HvRfDN8GrxOPI18zn0K/Ue9i73X/ik+eP6BvwB/eb90P7O/+MABgIeAyIEJAU4BkkHPQgZCeIJiAr+ClkLpwvUC9sL0Au7C40LRAv0CqEKPwrSCWkJCAmtCFMI9geIBwcHfAbrBVUFuwQhBIID4wJSAtsBewEqAdIAZwDx/4H/G/+1/kr+1P1F/aT8C/yN+x37nfoA+kz5jfjV9yb3cfas9en0Q/S680/zEfMD8xHzJ/NP85jz+/Nn9Nb0R/W59Tj23Pao94T4Vvki+vj64vvV/Lj9dP4J/47/IADOAJQBbAJbA3EEugUkB5UIAwqACyMN9A7qEPIS8xTYFpgYLBqQG8AcpR0FHr4d8RzlG9Ea0hn4GDsYjBf3FpwWXBbwFSgV9RNIEiIQpw31Cg8IDAUeAl//xPxR+if4RvaU9PbyTfGQ79jtWOwZ6wTqD+lE6KbnQ+cp5ybn3OYy5nLl1+RS5Ljj9OIV4lzhFuFM4czhjOKj4wHleuYC6JPpCutU7IftnO5i7+nvlfCg8fPyaPT79bn3v/ky/Pv+zAFrBOAGPgmIC7oNwA91EdUSDxQ5FTwWEBfKF3QY/xhqGbkZ5BnoGcUZchnlGCwYTRc3FugUhBMbEpoQ8g4wDV8LegmIB40FgwN2AYf/wf0X/JP6VPlf+Jv37/ZF9pr19/Rk9NDzLPOC8uLxUPHZ8IrwXfBJ8GPwtfAq8bDxV/In8wn07fTK9ZD2OPfR92H40fgi+XT50vk0+rX6f/t6/Hb9d/6h//IATgKeA8wE1QXTBuIH7AjUCa0KhAtGDOMMbg3yDW0O8w6VDzYQthArEbkRWxLuElATZhM4E/cSvBJYEpoRlRB1D00OIQ34C7YKRQm8B00G/gSyA24CTQFSAHT/of7B/cD8sPui+n75K/i69lH1APTN8sTx4/Aj8IPvFe/c7szu1+7u7g7vQe+U7/zvbvDw8I7xQvLy8pLzLPTY9KP1gvZY9yn4GvlE+pD73/wm/mz/qgDSAdwCygOfBF0F/gWFBvYGTweKB7UH7Qc2CHUIiwiCCHQIaQhaCDoIAwi+B3MHKAfgBp0GWQYBBpAFGAWoBDYEqgMEA1sCwgFEAeYAngBlAEUASABeAGIAQwALAMP/bf8H/5T+F/6r/WP9OP0R/eT8sfxq/Pz7bvvL+hH6R/mA+Mj3HfeV9kv2NfY29k32gvbP9iP3fvff90r4xvhT+dv5UfrR+m/7E/yu/FT9GP7q/rr/jABiATEC9AKaAwkERARzBLUEBAVfBdcFeAY8ByIIJgkyCkkLigwEDpwPLBGXEsoTyRS7FbgWkxf5F8gXIxdSFowV4hQ8FI8TABO5Eq8SnhI+EmQRFxB8DqQMcQrEB8UE0QEm/778bfow+C32j/RH8w7yrPAk76ntcOx966DqpOmL6I7n4uZ75iDmouUR5aPkgOST5Ljk7uRU5f/l9OYe6F3pnurw62bt8e5g8JLxjfJj8yT0zPRT9cr1afZd96D4EPqp+3n9fv+qAeED/AXaB3UJ3QobDC4NIA7vDpwPOhDjEJMRNRLMEnYTQxQVFcQVPBaPFssW3RaLFr4VkxQsE4gRoA+QDY0LrQnaB/0FJQR5AgABmf8i/pv8FPuT+SD4xfaK9Wz0YfNZ8ljxcvC27x7vn+5A7hfuKe537v7ure958HPxovLn8xf1NvZk96H40vnf+sb7mfxq/S/+t/76/jT/mP8cAKMAMwHjAbcCrwO4BLIFkwZoBy0ItQjvCAUJFAkjCUIJgAnLCREKbAr/Cs4Lwwy3DX8ODg+PDxsQjBC5EMEQxxDDEJwQUxD2D5EPLQ+7DhIOJg0dDA8L6gmqCGIHGQbTBJ0DcQIvAcb/P/6b/Nr6CPlG94/14fNW8gvxDPBU79vuku5i7j7uEO7C7WrtPu1M7Wjtfu2u7S/uF+9Q8JvxyfLq8yf1gPbE99X4wfml+qH7vvzm/fz+CwAkATgCNAMYBOMEfgXkBTAGfQbYBkMHsgcUCGkIyQgzCYcJrgmsCX4JKQnECGEI7QdgB9wGfAZEBiIGCAbeBZMFOQXgBHwE/QNtA9ECKAKDAfYAegD+/4z/Mf/g/oj+Lf7U/YD9Of0H/dT8lPxZ/ED8QvxI/EL8Ifzh+4n7KvvB+kP6tfkm+aP4P/gM+AX4Jfhs+Nn4VPm7+QP6Pvp4+qT6s/qp+qD6uvr/+l77yvtG/Nf8fP0p/s/+XP/K/x8AbwC/AP0AHQEsAVMBpwEWAn0C3gJeAxsEEgUlBi4HKQg5CYIKCgy6DW0P/hBgEpoTsxSgFUwWqRayFmcW1hUnFYcUDhTDE5sTjBONE44TXxO7EnQRlA9JDcMKFwhKBWUCgv/T/IP6pPgl9+T1vPSV817yEPGu70nu/+zb68nqq+mI6Ivn4eaK5l3mNuYT5hjmZ+b75r3nkOhv6Wbqeuud7LTtru6W74PwgvGK8ojzdfRh9Vb2UfdG+Db5MvpJ+3r8tP3l/hQAWwHHAjsEigWaBnYHOAjwCJcJLQrGCncLQAwRDeMNyg7TD+kQ4RGVEv8SJxMQE60S8RHsEMEPiw5SDSgMHgs/Cn4JwQj3BycHVQZ0BWUEGAOZAf7/U/6W/NH6IPma90L2DvX98yDzhfIt8gHy+PEY8mny3/Jb88fzJfSC9OT0P/WO9d31P/bF9m73NPgX+Rr6PPtq/Iz9j/5v/zQA7ACcAUQCzwIyA3EDnwPKA+8DBQQOBB4EQgR7BMIEHwWlBWUGTwc6CAcJsglMCuEKZwvOCxEMPQxhDIsMyQwiDZQNDw6LDgIPZg+gD5QPOQ+hDu0NKg1LDEYLLAocCSEIHwf+Bb4EewM7AugAZv+6/Qr8fPoQ+a/3TvYC9fLzJvOB8t/xNfGU8ATwhO8e7+7u/u5H77XvRvAF8ezx6/Ln89T0u/Wn9pH3YPgI+Zb5LPru+t/78PwT/kT/hQDFAfEC9AO2BCwFYgV3BXgFaAVABREF9AT9BC8FcwWyBd0F9gX8BekFtQVmBQ4FvwR3BCoE0wOBA0IDEQPcApcCRQLzAbEBhQFtAV8BVgFKATABBwHUAJYATQD2/5X/Lf+9/lT+BP7V/cL9u/2z/aj9pP2g/Yv9Vf0J/bv8dvw6/Pr7qPs9+836ffpb+lj6W/pf+nT6q/r1+jb7ZPuN+7379fs3/Ir83vwk/WL9rP0E/l7+uv4g/5T/CQBvAMAA9wAZATABRgFgAXwBkAGcAbgB/wF7AiID3wOlBG4FPwYXB/cH8ggqCqkLRg3KDhoQNBEgEuwSmBMKFBcUvxM0E7MSYBJGEmsSzxJeE+YTJRTXE9YSGRG3DuML2AjEBdACHgDI/cz7K/rm+On3BvcR9vL0jvPa8ebv3e3q6y7qveic58HmMOb15Q7mXebD5jfnzees6OHpReuj7N3t9e7x783whvEb8o7y8fJg8/Xzu/Sx9cf27vcp+Yf6+ftT/Xr+c/9MAAwBuAFTAuECZgPkA0sEjQS7BPsEbAUUBucG2QflCBEKXguzDOcN5w6wDzcQZhAuEJ4P3g4aDmUNvAwqDMkLpAulC6wLqQuICzMLmwq5CX4I5AYFBQED6wDR/tL8CvuH+Uj4Rvd39sn1NfW39En02vNc89HyT/Lr8ZrxTvET8QjxLvF58e3xn/KI85z04vVm9xj5zvpp/NH96P6j/xAAUgCOAOAAUAHUAW0CKAMIBAQFCQYHB+MHigjrCAgJ9QjZCMoIyAjYCAMJPAlcCWMJeAmnCdQJ8QkeCncK+gqVCzoM2gxaDaYNvw2zDYkNMA2kDAYMgQsVC6QKJAqvCUsJ5QhnCMEH5QbYBa8EdgMoArsAN/+p/Sf8wvpn+f33j/ZP9WL0vfM988fySfLG8U7x5/CL8EHwHvAo8F3wwPBS8Qjy1vK68630ofWN9nf3ZPhO+Sz6Afvh+9388/3//u3/wgCAARMCbAKfAsEC4QIRA2EDwwMbBGsEvgQNBTwFRwU9BSUF+gS6BGcEBQSaAzsDBAP6AgYDCAMDAwsDHAMRA+ACoQJeAgYCoQFPAREB1QCgAJEApQDCANwA+QAMAf8AywCDADwA/f/A/4P/T/8x/yH/D//1/s7+mf5j/jb++v2U/RP9mvw2/N77lPtc+yj77Pqy+or6Yvor+vj55/kK+lb6svoK+177vvss/KH8Ff2D/eD9L/6A/s3+CP81/3X/1v9GALEACwFWAZ8B9AFKAokCsALeAjIDrAM1BLgEMAWyBV0GOQdHCI4J/wpwDLUNwg6VDy4QoBAJEWARehFXETkRXhG+ESMScxLGEjATjhOME+4SqhHcD74NjAtnCTgHAAUBA4UBdQB2/0/+B/24+1n6y/jv9sT0e/JS8F7uhOy56iDp+edh5zrnROdS527nwOdi6DrpCuqq6jDr1Oue7Fbt1e087sTufu9p8JbxB/Of9Ef2+/en+SD7VfxX/Tr+7v5k/67/9v9ZAM8ANwGPAfEBbgL6AooDHQSqBDYF0QV/BiEHqgczCN0IkwkvCpUKvgq6CqwKpQqiCqoK1QouC6QLHwyNDNwMGA1XDYQNYg3PDN0LqAo/CaoH9wU7BJUCKAH3/+D+0v3P/OD7C/tJ+nr5evhS9xz21fRv8/vxmPBg73Du3+2n7bvtNO4y75zwLvK48yb1efa69+b44/mO+uv6L/ui+378xv1M/+8AswKSBGAG9QdHCU0K/gp0C9ELEwwmDBMM+wvqC9sLzQvFC8gL2gsADDYMcQyqDNsMBw0yDUoNMQ3eDGIMywskC4wKJQrwCd0J6AkJCiAKCQq7CT0JmQjYB/4GDAYGBe4DyQKdAW4AMf/b/Wr88Pp7+Qn4nfZC9Q30DvM98nnxqfDJ7+fuEO5R7bHsNuzk69LrEeya7FTtKe4U7x3wRfF+8rjz+PRP9sD3Pfm5+ib8ev23/uj/DgEgAiIDFwT8BNQFqQZzBxsImgj3CCUJHAnsCLYIgQhJCBQI6Ae9B4wHSAfuBosGMAbZBYYFRAUWBeUEowRhBCQE1ANvAw8DvAJwAjYCIQIzAlsCjgLCAusCAQPwAp8CCAJQAZwA+/95/yD/4v60/qH+pP6S/kX+xP0g/W/8y/s/+7f6Lvq2+Vf5+vid+FP4I/j/9+f33vfb9+r3Ivh6+N34Rfm/+Uv64vp8+wP8aPzJ/E397P19/u3+Rf+O/9r/KwBpAIYAngDWACgBhAHfAS4CYgKLArcC1QLSAsYC1AL7AjMDfQPaA00E+QT8BV0HFQkBC+cMiQ7ZD+YQtBFEEpkSrxKREnoSqxIjE7UTTxT4FKgVRRaeFmYWZRWpE3URCg+UDDQKBAgXBnIE9gJoAab/xv3Z+9r5w/eZ9WHzMPEu72btvusn6rnoj+ex5iDm0eXB5fHla+Ya59TneOgE6Xvp4elD6qTqCOuR62fsnO0o7wHxCPMI9dX2TvhZ+e/5NPpf+pr6C/vJ+9D8Bf5P/5IApgF1Av4CRgNfA28DnAPoA0sExgRUBe8FlwZIB+0HcAjTCCIJZgmzCRsKlwocC6wLSAzbDFcNuQ32DQEO7w3mDegN5A3JDYkNDQ1ZDHgLaQouCdwHjwZVBTUEKAMTAt4Aj/8w/rT8HPuE+fb3bPbx9JTzYvJn8bfwTfAG8N3v4+8d8Hrw5/BS8bPxJfLL8p3zd/RO9TX2QPd9+PH5g/sU/a7+VQDnATgDPwQJBaEFIgarBkEH8wfaCPIJBwvsC54MLw2pDQkOOg4gDtUNmw2ODZMNhw1pDUwNTw18DbANtg2JDVQNLA0EDckMbgz0C2oL1wohCi4JGggeB1EGqQUQBW4EugMIA1QCbQEjAH3+pfzH+g35h/ck9tr0wPPh8ijyfPHQ8BjwUO+J7tvtQ+3E7HbsZOyI7Ozsl+1y7mPvaPB78Y7yoPO/9Ob1EfdW+Lj5IPt8/NT9LP95ALcB5wLyA9cErgWFBk0H9gd6CNMIEQlPCZUJzgnnCeUJzAmhCXAJMwnSCE4IvgczB7AGRQb2Ba0FWgUDBakEQATNA1wD4wJeAt0BcQEdAeYAzAC6AKQAkAB8AFkALQACANL/j/9N/x//+/7W/qz+b/4L/o/9Ef2R/A38mftM+yP7Hfsy+0n7SPs0+xb75vqd+kT65fmQ+WP5a/md+fL5bfoC+5X7GvyJ/NX8Cf1C/Yb9wv30/TH+dv60/uT+Bv8U/xj/KP9A/1f/e/++/xUAZgCiALsAqwCAAEsADgDN/57/mv/M/zgA1QCWAX8CngPwBHEGJgj/CcALOA1fDkMP7g93EOsQQBFzEagRFBLGErQTzRTxFQIX5xd0GGAYeRfJFY4TExGWDjgMCQohCJ4GcAVVBBgDpAH1/wv+9Pu++W/3IfX38vbwDO8p7Vbroekq6AbnMOaQ5SXlBOU35a7lUeb/5pvnGehw6JDohOh36J3oG+kK6m3rKe0c7y7xK/PT9Aj26van92P4MvkV+v367vv3/Av+/v6z/zIAlgD0AF8B4QF9AkEDQQRyBaQGrAdyCP0IYgmiCakJgwlyCb0JbQpqC5oM4A0fD0MQOxHiESMSFBLhEZ4RUBHvEGMQrA/mDiIOUQ1vDJMLywr8CR0JNwhDBygG0wREA3IBa/9W/Uj7UPmB9/H1q/S48xvzufJz8j/yHvL88c3xlvFX8Rbx8fAD8TfxfPHe8WLy9/Kl84T0l/XK9iX4qvlC+8z8Pv6I/5AAWQH9AYwCEgOxA38EfgWuBv8HQglXCkkLLwwGDcANUg63DvUOJA9ND1kPUg9YD3YPlQ+0D80PzA+rD4QPbQ9ZDzAP5Q5nDrkN7QwCDOUKnglQCBgHBgYaBTgEOgMiAgEBy/9q/ur8VPua+d73X/Ym9fXzrPJh8SXw/+4K7k/tu+xI7A3sFexJ7JXs8uxc7cntPu617ibvo+9H8BTxCPIv85L0L/b699n5o/s2/Yj+mP9zADcBAwLVAqkDjwSTBaIGoAd5CBkJewm0CeQJDgonCjAKKgoUCukJsAlwCSsJ3Ah0CPEHXAfABiQGkAULBZMEJgTKA3UDDQOSAhgCqAE4AdcAmwB4AFAAHQDn/6f/R//S/mP+Bf69/ZH9fv1//YD9cP09/e/8m/xL/Ab82fvJ+9L76vsQ/Dr8YPyI/Lz87vz6/Nb8nPxv/GL8fPy1/Pv8Qf2V/e39JP4k/hD+GP46/lj+Zv5u/nL+av5P/hP+rf0t/bz8cfxU/Gf8sfwl/aT9C/5D/kX+G/7P/WH96vye/LX8N/0M/hr/SQCIAdICJgRsBYoGlAfMCE8K9wt/DdgOHhBqEa4SsRM/FGAUYBSEFNgUQhXDFX4WfReBGB0Z/BgMGHEWYhQVErcPYg0yC1QJ6gfOBqkFVAToAncB3v/y/az7Lvmv9lf0LfIn8D7ugOz06pzpdeh/57vmMObr5e3lJOZu5q/m4ebz5s7mduYe5vHlB+Zs5jTnaugH6vfr/+3S70DxT/IX87PzO/TB9En15vXC9uz3Qfmi+hD8iv36/k0AfAGEAnIDXwRTBS8G5QaIByQIvwhjCQ0Kpgo3C+8L3gzbDcIOlw9RENoQKhFCESQR3xCMEEQQDxDrD9APqQ9uDyIPwA5EDqsN+ww2DGELfAqKCY0IjgeEBmAFJwTkApUBOwD2/uD96Pzz+wX7Lfpr+bj4Ffh89+T2VPbY9WL15PRq9Af0xPOX82DzD/O+8qfy1PIt86zzV/Qu9SX2Nvcv+OH4Vvm4+Qz6Tvqd+hT7xfvE/Bf+oP8zAcMCRASiBccGrAdUCNMIPgmfCQQKjgpTC0wMWQ1lDlsPHxCjEOIQ5BCyEFoQ8g+UD0EP5A6FDkAODg69DSkNZAyIC5oKkAlfCAkHpwVQBAwDyQFvAP/+jv08/Bj7DPr/+O738PYb9mP1r/Tx8yvzXPKE8anw2+8v78buse7u7mvvEPDL8IvxQfLQ8jPze/PF8yL0ovRI9Qz29vYd+Hz56vpB/HL9c/5F//f/mAA1AeABngJjAyoE9gTDBYUGPAfZB0EIdwiYCMII9AgdCTcJRglNCUYJKgn3CKgIOAi/B10HFgfPBn8GMgbyBbEFUgXGBBcEVQOHArUB7gAzAIT///62/on+S/4J/tn9sf1z/RL9jfz6+3v7FvvB+or6f/qZ+tb6Nfuc++n7H/xR/HD8aPxC/BP88/vy+w78N/xr/LL8Bv1b/aL9xP2y/X79QP39/Ln8i/yI/Kj80/zy/Pr85/y9/Ij8Vfwy/Bb8BPwJ/DL8ffzd/EL9nf3q/Sz+Xf57/pP+xf4p/9H/tgDDAdoC6wPuBN8FuQZ/B0cILglKCpkL/gxTDoIPjBBxERgSahJxEkgSGBICEhMSSBKkEi4TyxNDFG0UKBRbEwoSXBB8DpUMzgo3CeAH5gY8BpcFvQS0A4cCKQGW/8n9wPui+bX3C/Z99PnyjvFE8CfvOe5b7W7sg+u56hLqk+k76fXoreh36FfoLOjj56Hnjeev5wDoeOgZ6evp4ero6/Ls+O3x7tzvzPDP8eDy+vMo9W32vvcT+Wv6y/sh/Vn+df+TAMEB7wIUBDAFQQZRB2kIggmECmQLIwzJDFwN2Q0xDm0Orw4CD1IPjg+5D9YP5A/sD+MPwQ+PD1IPBA+iDjcOvw0zDaQMJgyqCxELWwqcCeIIMgiSBwQHgwYKBpQFFwV/BMID4ALjAdUAuv+P/mT9afzC+1/7Ifv8+uP6t/pl+uf5MflH+Ej3T/Zf9Yz09fOs87fzEfST9Bf1mvUW9mT2ivaz9uj2EPc794r3+feH+EX5L/oy+1X8l/3V/vn/BAHtAbUCdgMxBMUEOAWsBSYGnQYtB+IHnQhDCd0JZQq+Ct8K1Aq8CqkKlQpyCkgKOwpFCjsKDQrFCWUJ5AhLCKsHDAdxBugFhAUwBdEEWgTPAyMDSAI7AQ4A2f68/bv83fsq+6v6TvoD+r/5ZvnY+B/4Yves9vL1QvW49FT0D/Tl887zx/PZ8wb0SvSj9BH1hvX+9Yr2LffT92r49/iC+Rf6vPpk+w78zvy8/dP+8P/3AOoB0QKcAzsEsQQPBWUFxwU9BrwGOAeuBxgIXQh3CG8ITwgjCPwH0gedB20HRAcAB5gGIQafBQAFTwSeA+sCQgLCAW4BMgEIAegAugB0AB0Asf8n/5b+Fv6g/T/9Ev0X/T39gv3T/Qb+Ff4c/iL+Hv4X/hH+/f3b/b79ov13/Uj9Lv0u/Uf9cf2c/cj9Bv5H/l3+Qf4J/rz9T/3I/Dn8uvtq+1b7a/uT+7375vsX/E78efyO/Iv8fvx5/IX8mvy0/Nv8B/0w/Vj9ef2U/bf9+/1p/vX+mP9NAA8B3gGqAlADwgMhBJEEGAXDBZcGhQd7CHcJagpHCwYMnwwWDYMN5w09DpQOBA+GD/0PWhCnEO4QHBEMEa4QFRBfD6cO8Q0/DYgMyAsJC1IKiQmSCHIHQQYIBcgDfQIXAaP/M/6//D37tfkl+JP2GPXJ85bybvFa8Gfvke7O7RDtTeyI693qUOrP6WDpFens6N/o/ehC6a/pT+oV69jrluxg7TjuFe/479DwqPGc8q7zxvTY9e32D/g/+XP6mPui/Jn9iv54/1cAJgHtAbcCjwNvBE0FIgbiBoEHCwiRCAMJUgmTCeAJSwrKCjELegvECxYMZAysDOwMFg00DVoNew2GDXUNRg0FDb8MagwFDKoLaQs9Cx0LCQvzCsUKegoYCowJwAjHB7gGoQWKBIMDnwL5AZMBRgH2AKMAPACs//T+Hv45/Vb8fvum+tD5Dfl5+B345fe696H3oPej96H3mPeC92T3PPcH99f2t/ak9qX2z/Yj95L3Fvi0+GX5Ffqt+iH7dfu2+/37UPyf/Oz8Uf3i/Zr+YP8dANMAiAErArQCMAOqAxQEbgTGBC0FqAUmBpMG9QZPB6AH7gczCGUIjgi9COQI8QjdCLMIgghGCO4HgAcWB7AGPQbBBUUFzQRjBPcDeAPhAi8CZQGRAL3/5/4Y/mb93fx1/Br8wvto+xP7y/qB+hD6e/nq+HX4JvgE+AP4F/hK+JP45/hJ+a75+vkw+mL6iPqv+uz6P/ug+xP8mvw0/dX9Wv67/hn/gf/f/zMAjADkADIBcwGsAeABCwIpAjoCSQJlAowCugL3Aj0DbwONA6sDuAOkA4EDWAMrAwoD/ALyAvcCFwM7A1IDVgM5AwUDzwKLAi8C1AGMAVYBMQERAe0AyACnAIYAZAAxAOv/mf9M/wb/zf6g/nv+U/4e/vH95P3p/eL90/3N/dL91v3B/Yj9Qf0A/cL8jfxh/D38MfxJ/Hn8rvzc/PP8+fzx/Nb8qPxn/BX8y/ui+5H7hPuE+5v7yfv++x38I/wo/Dj8UPxx/Jb8wfwM/YT9DP6V/iL/xv+IAFEBEALdAtID2wTXBbkGkgdrCEAJCwrMCnoLEAyjDD0N2Q1yDgYPjQ8QEIsQ3RD4EN0QiRASEJ0PHg+CDtQNGw1fDLELBgtECm0Jggh3B0UG8gSGAxkCwABw/xz+0vye+3r6XflF+DP3IPYQ9Qn0EPMm8lbxpfAN8JDvGO+k7knuC+7I7YTtXe1U7Wntm+3b7Sbuh+707mbv4O9U8LbwIfGi8SzyxPJ580X0H/X49cX2hPc6+Oz4n/lh+iv7+vvU/MT9x/7B/60AlAFuAiwD0ANeBNUESgXNBWAG/wauB2MIHAnWCXUK8ApRC5oLyAvlC+8L7gvoC9oLzAvMC9cL6AsBDBkMHwwaDBAM9gvIC4oLOgvaCmQK2AlOCdAIUQjQB1kH7waMBi0G0QVzBQ0FlQQRBIMD3wIlAmYBnwDH/+b+Fv5q/df8R/y++0377vqU+jP6w/lJ+c34R/i79zf3vfZT9gn22/W79bH1vvXW9f71MvZg9o72yfYH9073q/cM+Gj40/hR+c/5R/rG+lH77/uk/GT9H/7X/pz/agAuAecBlgI7A90DfQQKBYcF/wVpBswGPQesB/0HOwh6CMAICQlGCWQJZwlLCRAJxQh0CA8ImwcuB8QGVQbxBZcFPgXhBHUE+ANwA9wCOAKIAeEATgDN/1X/3v5g/tn9VP3W/E78wvtK+/D6tfqO+mf6Rvow+hD64/m7+ZD5Vvko+ST5Qflu+af58vlX+sn6Kftu+6376fsh/GD8rvwM/Xr9+P2B/v/+Xv+s//X/NABsAKoA7wA/AaIBCwJmArAC8AIdAyoDGwP/AucC2ALcAvUCGQM+A18DcwN4A28DUAMYA9oCnAJWAhcC7gHdAdcBzQG5AakBmwF/AVoBNgETAfQA2gDCAKQAgQBcAEQAPwAxAAsA5v/I/6D/af8p/+X+oP5d/iD+6f23/ZD9fP11/Wj9R/0W/eH8qPxc/AH8p/tb+yj7Dfv5+uP60/rB+qP6ivp/+mz6WPpc+nb6mfrC+u/6HvtX+5b70vsT/HH86Pxu/Qf+vv6O/2QAPAESAt8ClgM2BMgEYgULBr4GcQcpCOIIigkbCp0KEAt3C9sLSwy8DBsNbg3CDQAOEA77Dc4NgQ0ZDbAMTAzpC4gLLQvaCokKGgp3CakIvwe/BrAFnQSMA4gCmQHBAPP/Fv8g/hr9Cfzm+q35dPhe93/2yPUj9Y70AvR18+jyWvLB8RvxefDy75fvZ+9V71vvee+q7+LvIvBm8KXw4/Au8ZrxGvKl8kLz9fOp9Fb1Afar9lH3BPjN+J/5fPpq+2L8Wv1M/iz/4/9yAOwAZAHYAVMC3AJuAwEEmwQ4BcwFTwbABiIHegfEBwAINghxCKoI0wjoCPcIAQn8COkI1wjPCMoIygjOCNAI0gjOCL0Ingh0CDEIzgdoBxQHxwZ0BiEG3AWgBWUFJgXpBKsEZAQbBNoDmwNRA/gClgImAqoBMgHNAG8ACQCj/0v/Bv/S/qH+Xv4O/r39Yv34/Iv8LPza+5D7UPsX++b6vfqZ+nX6WPpK+kP6N/oy+kP6Wvps+nv6jvqk+rn6xfrM+ur6K/t++9z7TvzU/Ff91P1T/sr+JP9u/8T/JQCCAOUAXAHkAW0C7QJiA9MDQQShBO0ELAVmBZgFwQXmBQkGIgYjBgkG3wW0BYsFXgUrBf0E3AS8BJEEVAT/A5sDLQO5Aj0CugE3AbsASgDr/5n/S//4/pv+NP7O/W79Ef27/HD8M/wB/Nv7wfuz+7L7sfuf+377aPtg+1r7WPto+4T7nPvB+/v7N/xq/KH84fwi/WD9nf3V/QH+K/5S/nr+qv7n/in/dv/P/y0AhQDdAC4BawGOAakBxAHXAeAB5QHvAQsCPgJ0ApwCvgLiAvoC/ALuAtgCvQKgAocCcgJjAlgCRgIlAgQC5wHLAakBhAFgAToBFgH9AO0A1ACsAH8AUwAdAN//qP99/0//Fv/k/sH+m/5t/kH+G/7u/bf9jv15/W39Wv1B/Sv9F/37/NT8q/yF/Fn8KPwE/PH74PvS+9f77Pv9+wL8AvwH/A78D/wG/AT8H/xM/HL8jfyx/OX8Hf1a/aT99f1R/sD+Pf++/0cA5ACEARwCpAIdA40D/QNzBOAEPwWhBRkGowYwB7oHQQjDCEMJuAkdCm8KsArdCvkKAgv2Ct4KyQq1CpsKcgo+CgQKyAmKCUIJ3AhYCMkHPgerBgMGSwWOBM4DDANMApMB1QAQAE7/mf7d/Q/9RfyT+/X6VPqr+QD5X/jI9zT3nvYN9ov1FfWt9Fz0HfTg86fzg/Nz82vzaPNq83HzffOb88rzBPRN9Kr0FPWD9fr1f/YN95v3Ivim+DL5yvln+gf7qvtR/Pj8pv1Z/vz+fv/1/3kA/QBwAdcBOwKZAvUCVwO/AyIEdgS4BOwEFwU7BVUFYgVjBVYFRQU6BTcFNQUnBRQFAAXtBNYEvgSoBJsEigRwBFAELwQMBOMDsQN7A0YDFwP0AtsCzgLJAsgCyALLAs4CxQKqAoYCZgJGAiEC9wHZAcgBvAGrAZwBmgGfAZQBdgFVAToBIwEQAQQB9wDlAM4ArQCAAFYANAALANL/lv9p/07/Qf88/zb/LP8i/xf/A//q/tT+v/6o/pP+g/55/nb+gv6e/sL+5v4B/xn/Of9j/4z/rf/K/+b/AQAeAEAAawCdAM4A9QARAS0BWAGMAbYBygHSAd4B9gEWAjECRAJTAmQCcwJ4AmsCTgIoAgAC1QGkAXEBSAEuARkB+gDPAJwAYAAZAMf/cP8S/7D+WP4O/sv9iv1X/TP9Ev3n/Lr8kPxi/Cv89fvN+7D7lft8+3T7gvuU+6D7rvvG++r7E/xD/HL8nfzO/Av9Tf2G/bj98f02/n3+uf7z/jT/gf/R/x0AYgCbAM8ACQFQAZUBygH5ASoCXQKGAqMCuQLNAtsC5QLwAvsCBQMOAxUDEQMBA+sC2ALBAp0CbAI7AhUC+AHbAbUBiAFmAVcBUgE8AQ8B2QCrAIMAVQAjAPP/xf+T/13/Lf8E/9n+qP57/lj+OP4V/vT93f3Q/cX9sf2Q/Wv9Rv0j/QP95fzJ/Kf8gvxl/GH8b/x8/H78f/yP/LL81/z5/Bf9MP1B/U39Xf18/aX90P35/SX+WP6Q/sf+//44/3X/sv/r/yMAXgCWAMoA/gA5AXsBvwECAkYCkALdAjEDigPkAzQEfATGBBMFWAWQBcIF8QUaBkAGawagBtUGCgc/B3gHqwfPB+QH6gfeB78HlwdxB0wHIgfvBrcGfgZIBhcG5AWhBU0F8ASRBCgEqwMkA6ICIAKPAfMAXADK/zj/rP4x/sb9W/3r/IL8Ivy9+1P76Pp++g76m/kw+dL4f/g3+P331fe/97f3t/fA98331vfb9+H37/cH+CX4SPhz+Kb44/gm+Wb5pvnr+Tj6ivrj+kH7oPv8+1f8vPwn/Yn92f0l/nX+wf7+/i3/X/+U/8j/+/84AHsAuADtAB8BSgFmAXoBjgGdAZwBkAGIAYgBigGFAXgBZgFTAUgBQAE1ASUBFgEKAfwA6gDRALsAqgCZAH8AYABHADUAJwAcABwAJQA4AFgAewCRAJcAmgCkALEAvADDAM0A2ADhAO4ABgErAVEBaQF1AYgBpwHGAdQB0wHSAdkB3gHgAeAB4wHmAeoB8QH8AQcCCgIIAgsCFgIiAiECGAIOAgkCDQIYAh0CGQIaAioCPQJJAlICYQJxAnkCfQKHApkCqQK3AsECywLWAuMC8QL/Ag4DKANFA1YDVgNQA00DRAMrAwcD5QLBApYCaAI6Ag4C5QHFAaQBdgE7AQEBxgCAADQA7P+j/07/8v6e/lf+F/7U/Y39Qv35/LX8evxH/BX81/uT+137N/sR++f6zfrG+r36pvqX+p/6rfq5+s367voR+yv7RPto+5T7xvv3+yn8Yvym/O/8Nf15/cL9Bv5B/nn+t/78/j//hP/N/xgAYQClAOkAKgFmAaEB2wEVAkcCbgKOArEC0wL0AhEDKwNDA14DfQOUA5wDmwOYA5ADfwNmA0kDKAMLA/AC1AK2ApgCdQJAAgICzwGoAXgBNQHrAKMAWwATANP/m/9k/yj/5v6o/nD+N/7y/aT9XP0i/fP8x/yb/HD8SPwn/A388/vc+877xPu3+7H7vPvM+9b72/vp+wH8G/wz/Er8YPx+/Kb80Pz4/Cf9Yf2p/fn9Uv6l/u3+MP9z/7T/6/8fAFgAlgDZACMBbwG7AQkCXQKyAvsCOgNuA5sDvwPZA+oD+gMNBCUEPARRBGsEhASTBJ0ErwTLBN4E4gTgBOEE5ATkBOYE5ATUBLgEnASGBGcENwQABM8DpgOAA2EDSQMuAw8D9wLgAr0CjgJgAjMC/gHEAYsBTAEKAdYArgCAAEoAHwACAOL/uv+Q/2f/Pf8V/+/+yP6e/nT+Tv4o/gT+6v3Y/cX9tf2s/aH9lv2R/ZP9kv2L/YT9gf1+/YD9hv2K/Yz9k/2c/aP9pP2m/af9qf2z/cT90P3X/d797v3+/Qj+D/4W/h3+Jf40/kj+W/5n/nH+ff6I/on+hv6N/qH+uv7N/t3+6/73/gX/Ef8W/xD/Av/y/uL+1f7L/r3+rP6j/qf+rP6k/pP+hf53/mf+Wf5O/kH+Lf4Z/gz+BP79/fH93/3R/cv9yf29/ar9nf2f/an9sf2x/a79sf21/bL9r/2w/bT9sf2v/bj9y/3n/RH+RP5x/pb+yf4K/0f/ev+p/9r/CQBBAIAAxAAEAUkBlwHoAToCjwLcAh0DXwOqA/QDOQR7BL0E9gQhBUgFcQWRBaUFtgXJBdgF6AX1BfsF/gUBBvoF6QXNBasFhwVeBS8F+gS8BHYENwQCBMgDhgNBA/4CugJ0AioC3gGTAUwBEAHaAJsAVQAWANv/mv9V/xb/3P6k/nD+Q/4Y/ur9xf2z/aX9jP1z/Wn9Zv1m/Wj9aP1h/V79ZP1u/XH9b/12/YP9kP2m/cn96/0K/i3+UP5t/oj+pv7C/tT+3/7s/gD/F/8s/0P/Wv90/47/pf+5/9H/7v8KACQAOABCAEgAUQBbAF4AYQBqAHcAfwCAAIcAmACpALcAvQC5ALIAuADCAMMAtACcAIgAfwB4AGsAXQBSAEkAPwAuABcABADw/9X/sv+L/2f/S/8t/wH/z/6o/ob+ZP5E/iP+/v3W/az9hv1n/Un9L/0Y/f384/zS/ML8qPyO/Hf8Zvxb/FT8T/xL/Ej8SfxY/HD8hfyX/Kz8w/zh/AP9J/1R/Xn9n/3T/RH+Q/5s/p7+2/4b/17/p//1/z0AfgDMACQBbgGrAecBIgJeAqMC6AIkA2EDpwPlAxIEMgRYBIUEowS0BMsE4gTkBNwE1wTSBMwEyQTFBLcEmgR3BFwEOwQJBNgDswOIA00DFAPhAq0CcQIsAuUBoAFhASwB+gC5AHgASAAaAN//qf98/0n/FP/j/rj+jf5k/kj+Qf46/if+FP4K/gj+GP4u/jb+OP5J/mP+e/6Q/qD+sf7B/s3+4v4F/y3/Vf+A/6j/1v8QAEcAdACgAMkA6AAEASEBPQFcAX8BpAHKAesBBwIgAjMCOwJDAkoCSgJVAm4CgQKFAn0CbgJgAlMCOwIdAgEC5gHLAaoBggFdAUUBKQEBAdgAqwB6AEoAFQDf/67/ff9I/xb/6P66/pb+cv5K/ib+BP7h/cf9sv2a/YP9bf1R/Tv9Lf0a/QL95fzH/Kv8kfxw/FT8Qvwr/BD8/Pvq+9n7y/u++7T7qvub+4v7iPuM+5L7mfub+5j7pvu++8/74vv8+xX8MfxX/In8xPz4/B/9UP2M/cn9Cv5J/nz+sv74/kH/fv+5//n/PwCEALwA9AA5AYEBxwELAkECcAKnAtkCAAMqA1MDdAOUA7UD1APyAwwEIQQ3BEcETARTBFkEVgRVBFgEUQQ/BCoECQTpA9EDtQOMA18DNQMSA/ACwgKYAn8CYwI7Ag8C3gGmAW0BLwHsAK4AfgBUACsA///Y/7z/nv9z/03/L/8O//H+1v63/qL+oP6d/o/+gP5//pL+pf6p/rH+yf7f/u7+/v4P/yz/Wv+H/6v/0P/1/xMALQBHAGQAgwCZAK8A1wD9ABEBKAFLAWkBfAGGAYsBlQGfAaABnQGZAZEBkwGWAY0BggF8AWwBWAFMAUUBOAEkAQYB7QDaAMMAqgCSAG0APwAhAAkA5v++/5z/gv9r/07/L/8Z///+2P68/qb+h/5l/kz+Ov4t/iP+Ef73/dr9wv2z/aP9gf1h/U/9N/0b/Rb9Gv0S/f/87vzn/OD8zPy8/Lf8q/ya/Jj8oPyl/LD8ufy0/Lf80Pzx/Aj9EP0e/UP9aP2D/ar93P0F/iv+Wv6N/sX+Af84/2n/nv/Z/xwAXgCVAMkABAE8AWwBnwHMAfkBLwJmAo8CsgLVAvwCKQNQA2sDggOVA6YDuAPFA8YDxAPAA7sDwgPJA7cDlgOBA3EDWgM7AxYD7wLEApACZAI/AhEC3wGyAYcBXAE4AQgBzQCXAGsAQgAWAOD/rv+J/1//K/8F/+f+vv6V/nT+VP42/h3+Cv4A/vr97/3l/eD93f3i/er96P3j/eb97/0B/hj+JP4s/jr+Uv52/p7+u/7T/vn+Iv9D/2j/kv+7/+T/DQA5AGkAlACzANUA/QAjAUwBdwGjAdAB9gEXAkMCdQKhAsYC5wICAyADQANQA1gDbAOGA5YDnQOhA6wDuQO4A68DqwOkA5MDfANfAz4DHAP4AssCnAJrAjcCBALEAXYBKgHnAKMAYAAdAND/hP9A//n+r/5k/hD+vP1z/S797Pyz/H38RPwN/OL7yPuv+4r7cPtv+3D7YvtY+1L7T/tS+1P7Ufte+3b7ivuX+6j7xPvt+xL8MfxX/H78mvy7/O38Hf1A/Wb9mf3O/fz9J/5e/pf+xv74/i3/V/9//7X/6f8ZAFAAhwCvANYAAwEsAUoBYQGAAaoB0QHuAQcCHgIyAkoCYgJxAnkCfwKFAowCigJ6Am0CZwJhAl8CXgJTAj4CJwIMAvYB6QHYAbsBngGKAXkBYAE9ARwBBgHqAMcAqwCXAH0AXgBDADQALAAeABAABwD2/9n/yP/B/6//lv+A/2r/VP9K/0b/Rv9L/07/Rv84/zP/Pv9M/0v/Rf9L/1r/aP9u/3D/fP+R/6P/rf+8/8v/1v/q/wUAHwA6AFAAXwBzAI4ApgC7ANUA9wAcAT0BUwFrAYkBpgG/AdMB4wHzAQMCFQIfAh4CFQIVAhkCEwIPAhkCHQIPAgEC+QHoAdIBvAGmAYwBbwFNASQB/QDfAMUAnwByAEkAHwDv/8T/of+C/1//Of8N/+H+tv6G/lX+K/4H/uP9uf2N/XH9aP1e/Uz9Pf0y/SH9Ev0O/Q79B/3//AX9D/0Q/RL9Iv05/VD9af2E/Zr9rf2//dD97P0O/in+Qf5k/on+p/7E/uj+EP8z/07/av+N/7f/3f/5/xUAPABmAIYAogDAAN4A+gAXATABQwFWAWsBggGTAaEBrQG/AdEB2QHhAewB8wHyAfIB9QH5Af4BAQL1AeAB1AHMAbkBoQGVAYkBbwFWAU0BRgExARQB+gDkAM8AtgCYAIAAcgBgAEkANAAhAAgA7P/b/9D/wf+m/4P/Zf9Q/0H/Nf8o/xr/B//w/t3+zP6//rv+vP6z/qX+nv6f/p/+mf6R/or+jf6W/qP+sP6//sn+0f7g/vj+Cv8V/yP/MP8+/1P/b/+C/5P/rP/F/9D/2f/u/w0AKwBFAFcAYgB1AJIAqQC6ANAA7QAKASYBQgFeAXgBlQG4AdkB8gEEAhwCMwJFAlACXwJzAoQClQKpArQCtwK/AsoCzwLRAtkC3QLOArkCqwKlAp8ClwKIAm4CUwI8AiQCBwLnAcABlwFzAU0BGwHmALMAgABNAB4A7f+t/2j/LP/7/s3+mP5Y/hj+5P2z/Xn9Pv0R/fH8y/yh/Hr8XPxD/C/8I/wf/Bz8GPwY/Bj8HPwo/EL8W/xp/Hr8m/zA/N78AP0t/V39iP22/eD9Bf4x/mb+kP6w/tj+Cf81/1X/cv+P/7H/2/8DACIAQABfAHwAkACnAMMA2QDkAOcA7wD+AAoBDAEPARoBJQEqASgBJgElASgBLQEtASgBJQEgARUBDAEGAfwA6gDaANAAygC+AK8ApACgAJgAhwB9AIYAkQCKAH0AdwBxAGYAZQBvAHkAewB2AGkAYQBlAG4AcQB0AHkAeQB0AHoAiQCOAIgAgAB+AHcAagBfAFwAXgBeAFsAVABNAE4AWABfAFgATwBRAFQASwA9ADgAOAA4ADoAPgBAAEUATQBUAFwAbgCEAI0AjgCZAKwAvgDIAM0A1wDqAPkA+gD2APoAAAH6AO8A5wDoAPMABAENAQYB+QDqAN4A1gDMALQAlQB9AGkAUAA0ABwACQD0/93/xv+s/4z/bP9Q/zf/GP/0/t3+0v7E/qz+kf53/mX+YP5f/lD+Of4w/jX+NP4s/ib+JP4k/iX+Jf4j/iP+J/4o/if+M/5M/mX+eP6M/p/+sf7D/tr+9f4S/zH/T/9q/3//k/+s/8r/5v///xsAPABWAGcAdwCQAKwAxQDUANsA4gDwAAABBwEGAf8A+QD3APgA9wD2APUA9QD7AAYBDAEFAfcA7QDmAN8A3ADXAMsAwADCAMYAwgC0AKgAoACdAJsAlACKAIQAhACCAHkAcABjAFYASgBFAD8ANQArACUAIQAXAAkA/v/6//L/5f/c/9j/z//B/7T/p/+b/5L/iv99/3D/av9t/2//af9c/1H/UP9S/0//TP9Q/1r/X/9d/1f/U/9V/1n/Vf9K/0L/Q/9E/0T/Q/9F/0n/Uf9c/2T/a/96/4r/kP+P/5H/m/+o/7L/uv/C/9H/5v///xgALwBHAF4AdACOAK8A2QABASkBTwFvAYQBmwHAAegBBQIZAjACSgJfAnMCiAKjAsIC4AL4AhIDMwNQA14DYgNpA3EDbwNbAzwDIgMSAwED5gLHAqoCjAJpAkICFgLkAawBcgE4Af4AuwBvACEA3v+d/0//9/6n/mP+If7X/Yn9SP0O/dX8mfxk/DX8CPze+7z7n/uA+2P7TvtC+zz7OPs3+zz7Svta+2L7aft7+5f7tvvU+/n7I/xM/HT8nPzE/OP8/vwd/UL9Zv2J/bD93f0O/j/+bv6Z/sL+7P4Z/0D/X/93/4r/nf+y/8z/5P/9/xgANQBNAF8AcQCJAKQAwgDiAAIBHAEzAU0BZwF9AY4BpAG/AdkB9AERAjECSwJjAnwCnAK+At4C/QIXAzADSgNiA3YDigOcA6sDsQO0A7gDugO6A7kDtAOlA44DfQNyA10DOwMXA/oC3wK/ApwCeAJQAikCAgLYAacBcAE8AQ0B4wC7AJQAawBEACAA/f/V/6f/e/9V/zf/Hv8C/+D+wf60/rf+tv6l/pT+kv6X/pb+jP6G/oT+gv6B/oP+h/6N/pn+qf63/r3+u/68/sP+0P7Y/tj+2/7k/uv+7P7q/uX+1/7A/q7+q/6t/qT+l/6U/pr+m/6T/ov+i/6R/pv+p/6w/rb+wv7T/uL+7v76/gL/CP8T/yT/OP9M/2r/i/+g/7L/z//3/xYAIgAiACQAKwA0AD0AQQA/ADwAQQBOAF0AZQBoAGkAawBvAHUAdgBtAGAAWwBaAFUAUABRAFQAUwBNAEYAQwBIAFIAVgBVAFcAYQBoAGYAYwBnAHQAiACYAKAAogCqALEAsACqAKoArgCuAKoApQCiAKIAoQCbAJEAiAB5AGQASwA2ACcAHAATAAcA+f/q/9j/xP+0/6n/mf+G/37/fv94/2//df+H/5H/iv+B/37/f/+H/5X/oP+i/6T/q/+9/97///8RABAADAARABsAHgAWAAoAAQD7//T/7f/l/9b/wv+1/63/nv+I/3v/ev94/23/Xf9L/zv/Mf8q/yH/E/8E//j+8v72/v3+/P73/vr+AP8F/w3/H/89/2L/jv/A//3/SQCfAPIAQgGWAesBNwJ3ArIC8AI4A4oD2AMbBFQEjATIBAIFOAVfBYAFogXCBdoF7gUBBggGAAbxBdsFrAVlBRkFzwSEBDsE9gOsA1oDDAPFAnYCEwKjATQBzQBkAPD/dP8B/57+P/7c/Xz9IP3H/Gv8Dfyv+1z7Gfvh+q76iPpn+j76EPrv+dv5u/mQ+XD5YPlV+Ur5PPkv+Sf5KPkw+T35TPlY+WD5bfmG+Z/5tvnP+eb59PkB+hb6LPo4+kX6XvqD+qz61voG+0H7ifvR+wz8QfyB/M78G/1i/aj99P1S/rz+JP+F/+b/SgCqAAsBbwHPASsCiwLzAlEDpQP+A1wEugQWBXIFvQXwBRkGRgZ0BpoGugbbBv4GIQc6B0UHRwdDBzgHKAcYB/4G1waxBpQGdAZJBhcG5AWwBX8FUAUVBdIEmgRsBDoEAQTOA6ADbwM4AwEDywKbAm8CQAILAtYBnwFmATQBCgHdAKYAcgBFABcA5P+x/33/Q/8J/9P+mP5g/jH+A/7O/Zf9Yf0o/en8rvx6/Ez8JPz8+9b7tvua+3z7YvtY+1L7QPsq+yX7MvtD+1f7b/uC+5n7vfvn+xD8Ovxx/Kn81/wI/Un9kP3Q/QX+Ov57/r/+9P4f/1P/mP/W/wMAJwBLAGsAiAChALMAxADYAOcA7QD2AAkBGgEeAR8BIgEgARcBCwH8AOsA3wDhAOYA5gDiAN8A4wDsAOsA4gDcAOEA4gDeAOIA6wDuAPEAAQESARYBFAEXARUBCwH9APUA8gDvAOYA1QDFALkArACYAIIAagBNADIAJgAfAA8A+P/h/8b/p/+G/2D/Of8f/wz/9P7f/uT++P4E/wT/Bv8H/wb/CP8T/yP/Nf9I/2L/hv+x/9X/7P/9/wwAFAAeADAARgBaAHEAkQCpALYAwQDMAMgAtgCfAIMAYAA9ACQAEQAAAO//4P/O/7f/lv9y/1r/T/89/x3//v7s/uT+3/7V/sH+qf6X/o7+iP6G/or+kf6e/rf+2v7x/v3+EP8s/0b/Vv9j/3j/lP+y/83/7f8bAFEAhwDIAB0BfAHdAUcCtAIoA6kDOQTBBDUFnwUCBlUGlgbTBgwHNwdSB2gHgQeZB6wHuQfFB9UH3gfWB8oHvgecB1YH+wahBjkGugUoBY8E+QNyA/MCcALvAXoBCwGTABwAsf9G/8z+T/7Z/Wb97fx1/Aj8o/tE+976b/oD+qT5T/kC+b74f/hE+Bj4/fff97D3gvdd9zf3CPfT9pX2TfYN9uf10PWy9Y/1ePV59YX1jvWU9a313vUa9lj2nPbq9jf3fPe/9wv4ZPjC+CD5fvnp+WX68fqM+z38+/yy/V3+Cv+5/2AA9wCHARICmQIYA48D/wNoBMsEKQWJBeIFIgZXBpoG6QYrB10HigeyB8gH0gfaB+QH6gftB+oH5AfdB8kHnwdrB0YHLwcZBwEH6wbcBtkG4wbsBuMGzAayBpgGfgZdBicG3AWYBWYFMgX1BMAElARjBCoE8wO3A2cDCQOtAlcCAwKrAUkB1wBjAPL/fv8J/5L+Ev6N/Rb9tfxj/BX81fun+4T7ZvtF+yH7BPv4+vD62fq/+rr60Pr3+iv7bfu1+wH8Ufyi/Oj8Jv1m/aj95f0Y/kj+gP7A/vj+Jv9O/3D/hP+H/4L/gv+N/57/rv+3/7n/uP+4/7f/rf+X/37/Zf9S/0H/Of8//0//Zv+H/6n/w//U/+X/+v8OACUAQQBgAIQAsQDaAO8A+gADAQcBAgH/AAEBAgH/AP4ABQEQAR0BIgEXAf4A2wCpAGwAMgD+/8z/n/9+/2b/T/8//zb/I/8H//b++P72/u7+6/73/gX/D/8Y/x//KP8y/zj/Pv9V/4H/rv/W/wYAPABnAIUAngCzAMEAyADHAMIAwgDNANsA5ADiANYAwQCvAKoAoACBAFUAMwAiAB4AHQAYAAQA7f/j/+T/2//A/5n/dP9S/zX/Gf8E//L+4v7U/sn+xv7G/r7+r/6g/pH+fv5k/k7+P/41/jH+Mf4v/iz+Mv5E/lf+X/5k/mr+eP6T/rb+z/7b/uf+/P4Y/y//Pf8+/0D/Uf90/5z/yf/5/ycARwBnAI0AsQDQAP4ATAG4ATMCvgJhAxkE1gR9BQ8GowZBB9QHUAjICEgJvwkoCp8KKQueC9QLyQuWC1ULCwuxCkYK3QmPCV0JNAkBCbIIRAi9BygHeAaZBZkEnQO5Au0BPAGkAB4ApP82/8n+S/66/SX9m/we/KL7I/uq+k/6C/q9+Vb54/hv+On3T/ey9ib2ofUk9bv0bvQu9OzzofNR8wTzuvJr8hTywvGD8VTxNvEo8SfxLvFD8XHxsPEA8m/yA/Ou82P0H/Xo9bz2nPeB+Ff5GPrM+on7U/wd/eL9pf5x/0UADwG+AVoC8wKHAwoEiQQTBZwFCwZjBrQG+wYqBzkHNAcnBx4HGgchBzwHbgexB/UHOQh/CL0I6AgKCSYJOQlJCWoJngnOCesJBwolCjkKNgoeCu4JqglgCSEJ6wiwCGQICgiyB2AH9wZcBp8F5AQuBGUDjwLIARwBfQDc/zz/o/4Q/of9EP2x/Gn8K/zz+8z7wPu6+6b7iPtt+0/7KPsA++P62vrw+ij7dvvG+xT8XvyZ/MD80fzO/L78uPzF/NX85fz//Cb9UP16/Z79r/2q/ab9rf22/cb98/1C/qb+FP+B/+H/LQBnAJQAtQDTAPQAEwE2AXABvwEQAloCogLgAgMDDgMHA+wCwAKSAmsCQgIcAv8B5wHFAZoBbAE3AfoAtABrACIA4P+n/3L/Rf8t/x//Dv/4/uv+4/7Y/s/+zf7J/rr+pP6Q/oT+gv6J/pH+l/6d/qf+tP7D/s7+w/6f/nb+YP5V/kH+I/4P/hP+Jv46/kr+Vv5i/nL+f/6J/pT+qf7U/hH/Vf+V/9P/HgB1AMcAAQEoAUwBeQGoAdMB+AEdAkQCbQKRAqgCrQKqAqcCoAKLAmECLgICAt0BswF6AToB+AC4AHsARQATAOT/u/+Z/3n/Xf9E/yv/B//R/pH+VP4j/v794v3I/bX9qv2f/YX9XP0w/Qf95fzI/K/8n/yT/If8d/xx/H38h/x1/E38L/wn/C38N/xE/Fn8e/yv/PP8PP2D/cf9Df5d/rb+Df9d/7f/LACyADwBzgF1AjQDBwTsBNcFuQaXB3MIQgn4CZcKJguqCzIMwAw8DZIN0A0SDlQOcw5RDukNSg2QDMgL+AosCoMJDwnHCJcIawgsCM0HVQfEBgEGDQUGBBgDTgKvATsB6wC9AK4AnwBhAOj/Rf+H/qr9vPzW+/76OvqN+fH4Ufig9972/fX99Ozz2PK58ZPwgu+q7hzuz+2h7Xztau167Z/ttu297c/t/e077obu6u587zbwBfHh8dTy3fPp9O318Pb49+j4q/lS+vb6lvso/LH8O/3P/W7+Dv+n/zAAqQAVAX0B4gE9ApQC/QKGAyEEwgR3BUoGLAf7B6UILAmhCRgKmwobC48LAQx5DPMMZw3ODRoORQ5YDlgOPA4GDsENcw0SDaAMFwxqC5oKvwnxCC8IdAe8BhIGhgUfBcUEVQTHAy0DjALeAS4BjAD8/4b/Ov8e/xn/Cf/h/qb+Wv7z/Wn9xvwm/Kj7YftQ+1z7a/t0+3b7Zvss+8X6N/qV+e/4WPjn97T3yvcX+Hj44PhW+cP5AvoZ+i76Tfpz+rH6Fvuf+0f8Ev3r/bb+b/8fAK0ACQFLAZAB1QEQAk0CmwL2AlkDvgMSBFQEjQS0BK4EfwRFBA0E0AOYA3gDbgNuA3gDlQPBA+gD8wPjA8IDlwNbAw4DvgJ5AkkCLwIjAhAC9wHgAcABggEkAbMAMwCq/zL/0v57/if+7v3X/cT9pv2F/Vv9H/3W/JD8Uvwe/Pn77Pv1+xb8SPyB/Lz88fwX/TD9Sv1l/XT9ff2H/ZT9o/2//ef9A/4N/hv+Mf5J/mj+m/7S/vf+Dv8n/0b/cf+r/+3/NwCOAO8ATQGkAfsBTgKSAsYC6QL3Av8CFAMwA0oDZwONA7IDxQPCA5wDVwMEA6kCMQKiASQB0ACUAGIAPwApABQA9//Q/5L/Ov/U/mn++P2K/TX9Cv0M/Sz9WP18/Y79g/1c/Sn97vyh/ET89PvD+6r7ovuw+8v75Pv++x78MPwn/BD8/Pvp+9P7xvvP++/7J/x6/N38Of2L/d/9SP63/hj/aP/E/zYAuwBfATACGQMOBB8FTgZvB2IIQQkWCswKYAv4C5YMJQ2pDTYOuw4ZD1UPfQ+AD0APtA7iDd4M1wv4Cj0KmQkfCecI4QjrCOsIzgh4COAHHQdQBoIFsgT1A2MD/QKwAnUCQAL4AYMB4QATABP/4f2X/FP7JPoM+f/39Pbw9f70D/QO8wbyC/EX8BvvJu5S7absJOzT67jrzusY7I3sFu2f7TDuw+5F77DvEvBu8MHwIPGc8SryuvJe8yb0BPXd9a72dPcc+J/4Cvl1+eX5Yvr4+rL7ivx0/W/+ef+CAHsBZgJLAyQE7wS6BZQGeAdjCFoJVQo/CwwMtgw7DZ8N8A0pDjwOJw73DboNdg0yDfEMrQxrDDoMIwwaDAwM6gutC1UL5QpcCrkJCQlbCMcHYwc1BycHHQcOB/QGvQZUBqoFxgTBA74CzgHzADQAoP8w/8z+Xv7e/UH9fPyW+6L6tvnr+Fv4Dfj69xn4Wviw+A35Zvmh+az5g/k++fj4yPi7+NP4GPmE+f75a/rG+hL7RvtR+z77Lfso+yv7NPtX+6r7LfzJ/Gz9Iv79/t//lAAWAY0BFgKjAigDpwMpBKgEKAWyBUgG1QY9B3QHfgdiBxoHoAb/BVEFtwQ8BOUDtgO0A8oD0QO3A4sDUgP9Ao0CIwLXAZwBbAFXAWYBlAHRAQoCJQIaAvABqgFDAcQARADW/4D/P/8L/9L+jv48/tL9Rf2m/Ar8d/vn+mT6+Pmp+Xv5cvmK+a350Pn8+T76kvrr+jf7ffvR+z/8t/wm/ZL9CP6A/uL+Jv9m/6//9P8kAEUAWwBcAEcALAAaABIAGgA/AHcAtADuACcBWgF6AYMBcgFTAUIBVQGAAbAB7gFIArUCIwOGA88D6APKA4oDOQPUAmkCDALMAZ4BdgFRATEBDAHWAIcAJQC2/zr/tv4//ur9uf2c/YL9af1V/UP9JP3t/KX8YPwb/Mv7cfsi+/H64vrt+gn7MPta+3/7nvu3+8f7xvuz+5v7kvuY+6T7t/vk+0D8wfxM/cj9Ov6y/jP/sP8aAHEAtwABAWwBCALHApIDcARuBYMGhwddCAwJqAk3CqoK/gpUC80LcQwrDeANgQ4BD1gPgQ9wDxAPWw5iDU8MSgtuCs0JdQlwCa0JEQp9CtIK6wqsChEKLgkTCNEGgQVPBF4DtAI+AuMBkwE3Aa8A3f+2/kP9m/vh+TT4svZt9XP0yPNe8xLzvPJF8qPx0fDR77vuue3s7GXsJ+w47JbsMu3s7ajuSe+y79fvv++G70jvFO/37gXvT+/c75/wivGP8ozzZPQU9bb1XfYC96P3TfgP+fL57vr9+x/9TP5t/4AAigGRAowDdARTBTUGHQf8B8QIcgkNCpcKFAuOCwMMZAybDLEMuAzADMAMrAyIDGYMVQxeDH0MqQzaDBANUw2dDdcN2g2bDSkNkgziCyMLZgrBCUIJ4AiPCEMI8QeHB/AGIQYdBe8DqQJcASsALv9s/t79gf1N/TX9Hv3m/HL8zfsb+4D6Ffrg+dn5+fk2+or66fo2+0X7+/pr+sD5Evls+Of3nfef9+T3VPjT+FH5uvkB+iT6Lfoe+vX5yvnR+S36zfqK+178UP1W/lz/SgAPAaMBAQIzAlMCgQLCAhMDaQO4AwEEVQSyBAAFLgU4BR4F8gTCBIkERQQLBOwD7gMKBDcEcASrBNAEygSdBFsEEQTKA4QDNgPyAtAC3AIIAyoDIQPuAp8CMAKVAdIA+v8k/23+4f2D/U/9M/0k/R39E/39/N78s/x+/FX8RPw5/CP8CPz4+/j7AfwK/BL8I/w5/Fz8mvzj/BT9Lf07/Tv9LP0d/Rr9LP1V/ZL93/09/qn+GP9u/5j/mv+M/3//jP/I/y8AswBVARECzgJrA9QDCQQYBAUExgNqAwQDoQJXAj8CUQJzApMCqAK1ArwCpQJlAg4CvAFyASoB4wC2ALQA1wAFASgBNQEsARAB2wB6APD/Tv+o/hj+sf1y/UH9Ff33/PT89PzF/FD8qPvz+kv6ufk7+eP4y/j5+Fr56PmQ+i77o/vl+/f77vvl++T76/sE/C78afy9/Cn9nP37/TD+QP5S/oT+u/7Z/ub+Bf9I/6X/DwB8AOEARwHGAWECAwO2A5cEqgXiBjYIfgmYCpQLkwyUDXwOMg+nD+8PHxAwEBkQzQ9AD4UOtQ23DIMLVwp5CfcIvAi5COoISQm3CRYKUwpICsoJ6QjfB90G7AUHBTIEiwMwAwMDzgJnArUBtgCC/yP+mPzv+kz51Pek9rP14vQj9HDzvvIG8j3xVvBn75zuBO6s7Z/tze0i7q7ubO8c8JDwzPDf8MPwZ/DL7yPvq+5v7nXux+5a7xDw3/DE8azyh/NH9O/0hfUe9sX2dPcg+Nj4uvnF+t379vwL/hT/GAAdARYCBQP4A+wEygWRBkUH2wdOCKgI9AgzCVwJdgmVCc0JFApdCq0KCAtsC+ULdgwHDYUN6g0zDloOYA5HDgwOtg1HDcQMLAyAC84KKgqeCSsJ2gipCIAIRwj6B4MH1gYDBjAFZgSgA9MCDAJlAfQAsgCNAG0AOADk/3//Hv/N/nv+Gf6w/U/97/yM/Cr8tfsh+3762vk4+bD4Xvg/+Ef4dvi/+BX5Zvme+b/52Pnb+cP5u/nU+e35Afos+m76vPoe+5z7Jfyp/Cj9rv08/sH+O/+r/wAANgBhAIwAuADyAEEBlgHzAWEC2gJMA6QDzwPVA8EDnAOHA5ADnQOgA7cD7wMkBD8EMwQKBOEDwwOqA5kDkQOEA4IDoQPRA/YD/wPkA6wDZwMCA3ACyQEvAaoAQgDh/2j/5v6H/k7+IP7r/aj9Wf0D/bD8aPwo/OT7rfug+7z76vsZ/EX8d/y5/Of86vza/Nn88PwZ/Uf9Yv1x/Yf9p/3D/cX9lv1Q/S39O/1g/ZX94f1F/sH+T//U/zgAfAC1APcAQQGAAakBywENAnsC6QIeAyoDMwM8AzEDFQPsAq8CYwIoAhYCHQIPAuwB2wHkAfAB8gHoAc4BqgGMAXYBZAFRATMBBgHJAIoAWgA/ABoA2f+J/yv/w/5m/hv+z/1w/Qr9p/xU/A/81fuq+5P7lfup+7/70Pvn+w/8RvyK/M38A/09/YP9wP3n/QT+Ef4Q/hr+Jf4O/uD9xf3N/en9Ff5G/n7+xf4q/7j/WADYAC4BeQHCAf8BSAK+Am0DRgQfBc8FSgagBuEGDAcHB70GRQbNBYcFlwX3BXkGDwfZB8wIqAkvCkgKEgq9CVsJ3whICKcHJAfjBuEG7wbtBtcGrwaFBlYG4wUNBRUEUAPMAmUC+wGOAS8B4wCWACYAbP9n/mf9rvwt/MD7Y/se+/f69Pr8+tr6avqv+cP4vve39sb1/PRp9CH0I/RI9HT0ufQQ9UD1JfXf9Kf0n/TB9O70HvVp9cP1E/Za9qD2zfbc9gD3WvfV90f4qvgV+ZP5DPpi+pT6tfrc+hL7Sfty+5778Ptt/Pv8ff3x/Wv++/6i/1gAGQHcAaUCdQMxBK4E3ATZBMYEvATIBNoE5AT5BEsF2wVqBsMG9AYcBz0HTgdIByEH6Aa+BqcGhAZMBiEGFAYiBkUGeQasBt4GHAd3B9QH7geYB/wGbgYJBq4FRQXgBK0EvATtBA8FCAXLBFcEyQMsA3UCpQHpAHAAWgCVAOAABQECAegAtQBUAMH/D/9c/tH9jv2N/a796P1M/rb+6v7W/pL+K/6w/Tz92PyC/ED8I/w8/Ij87/xS/aP92v3v/e793P23/ZL9iP2U/ar9z/0O/l7+of7F/tH+1P7T/s/+zv7J/tH+Df92/8//BAAqAEsAWABVAEoAMAAMAAYAOwCBAKUApgCgAKUAvwDgAOQAwACpAMAA5ADhAKkAVwALAOD/zP+//6X/if+H/6j/x//F/7H/rf+//9z/9f8NAC8AWwCMALgAzwDLAMUA2QD/ABEB+gDOALwA0wD5AAgB/wD2APkA+ADeALEAhwBqAGAAagB/AJMAnwCuAMUA1gDHAIsAQwAXAAgAAQD1/+7/8f///xQALAA8AD8ALwAJANb/q/+V/5D/if94/1L/Ev/F/oP+UP4m/gn+AP4E/g3+Gf4r/jX+Nv47/kj+SP4r/vH9qP1h/TP9Lv1R/YL9rv3M/d/96/34/RD+NP5i/q/+Iv+W/9f/1v+o/2D/Dv/S/sn+7P4k/2//2f9IAJkAxgDbAN8A0wDDAL0AxgDcAPkAFgEoASwBKwEtATgBUQF4AagB3QEYAlYClQLhAjwDmQPoAx8EMAQPBMsDiANTAxgDywJ1AiEC1wGoAawB6QE8AnsCmwKiAo0CTQLrAXwBDwGkAEcACwD7/xEAOwBfAG0AWwAvAPX/tP9u/zL/F/8p/0r/Yf9i/0b/Fv/7/hf/U/+A/5//yv/6/xAAAgDT/3X//f6b/mr+WP5T/mX+kf7K/vH+5/6i/jb+0P2K/XD9gP20/Qn+gP4R/5z/7v/v/7r/f/9T/z3/RP9t/6v/6f8gAEUAQgAIAKj/Of/K/m3+Nv4r/k/+nf4J/3X/yf/8/w0A+v/O/5z/Zv8i/9n+s/7C/uj+AP/6/tT+iv4u/tz9nv1z/Wf9gf2v/dz9Bv4r/j/+Qv40/gf+uP1w/Vj9dv2//S/+tv4z/4n/r/+l/3f/Jv+v/h7+p/1x/Xj9nv3U/RT+Uv52/nb+Yf5M/kT+Tf51/sT+LP+V//f/RQBxAIAAhgCFAH0AgQCfANIAGQFwAcIB+wEcAiIC/gHEAaoBwwEAAlwC1AJBA4cDuAPpAxEEKwQwBBcE8wP1AzcEmgT8BEwFbgVPBQMFqAREBNMDYgMSA/kCEgM/A2MDbwNcAzgDKAM9A2ADaQNPAx8D5wKzAnwCLgLGAVsBBwHZAOIACQEbAfMAnwAtAKb/Gv+m/mr+dv60/uT+2v6h/j/+tf0y/fr8Ff1Q/ZP93/0h/kz+ZP5O/uT9UP3v/O78Nf2V/en9Jf5P/mb+Tf76/Zn9WP1V/ZH98/1Q/p/+7/48/3b/jv+J/4D/nP/W/wEAGQBAAG4AjADDAEQB2AEiAhsC9AG5AWQBCgG+AJEAmgDtAIgBPwLDAs8CdwL+AXIBwgASAKj/sv9jAMUBUQNEBEcEhQMsAnoA2/6q/Sr9pP0l/wABSwKhAi8CQwEBAGr+k/zt+iL6lfoP/Nj9/f77/kn+uP1g/b38xPsK+/n6dfsk/Jn8gvzv+0f79/pF+wX8jfxu/Af83/u/+zf7jPpT+qz6ffvN/Ez+Nv8m/5P+Bf50/cz8evzx/Pz9Gf8qADwBBAIfArsBTwHnAFoA9f9YAJMB+ALxA3gEwgS8BDwEeAPgAp0CoAL7ArsDjQQJBS4FRAVkBWgFSQUyBT0FRAUdBe0E9AQSBekEjQRYBCgEnQP1Ar0C0wKsAkwCJQI1AhcCvgF1AV0BSgEaAdMAfQABAF3/yv5x/iv+1v2i/bH9uf1w/QD9xvzj/Br9B/14/LL7KvsC+wn7FfsQ+wX7P/vp+5n8vfxl/O/7hftQ+5j7P/zG/BL9bv3O/eP9x/3W/Q/+N/5G/kz+TP5e/qn+GP9r/4v/of/8/8wA2QGcAtECvALEAv0CQQNsA2oDPwMfA0gDtQMmBH8E0QQLBfQEfgToA3kDVQOKAwsEkQTBBH0E/wOUA1MDLAMuA3sD+QNKBEkECARuA2wCbAH+ACUBhwH3AU4CQQLOATcBdwBc/yj+Xf0W/RX9KP08/V79sP3y/Zb9kPyI+wf7APtD+5/7yfuv+6L7xvvp+/v7Gfwv/Cv8NvxX/E38+vuJ+y77HvuD+yf8mvy+/Mz83/zm/ND8k/xg/K/8tP3y/tr/RgBWAD4ASQB0AGEAEAAUALYAowF2AvcC+QKcAlECPQI2Al4C+wLxA+0EwQUgBqkFmwS8A3cDkAO2A+ADNATTBJoFBgbBBf0EMQS4A6oDxwOwA4MDrwMqBFsEzgOJAu8AsP9j/+//tgBeAdgB/AGOAYYACP9w/V38Nvy//IL9S/7r/ij/8/5T/kX9DPw1+wD7KPtv+8n7A/zx+9P7//tO/FP81PsB+1X6Tvr++ur7lvzc/Nv8vfy2/OH8KP1d/WX9O/39/AX9sv3X/sX/8f+I/x3/Dv9e/+X/aACuAMcABwGLARcCZwJnAhkCrQF/AcUBVQLpAmgDwAPYA8QDygMTBG4EgwQuBJ8DKgP9AicDlAP+AwIEpgNiA4kDrgMlA+0BzwCEAA8B6gGOAqsCPwK9AYoBYwHTABAAp/+B/zT/6/4D/zb/I/8C/wH/pf6h/Xn83Pvi+y/8bvxr/Cz89/v1+//7x/s7+7b6yPqL+0/8WvzB+zz7VPv6+5n8kvzh+0L7avsz/OD8DP34/CL9qv09/nb+TP4K/g7+g/5O/wIATABVAJ0AXgFNAtEChwKbAbIAZwDlAOwBCgPrA5IEIgV5BUwFvARDBBYE/QPDA34DdAPuA/YEIgbLBpYGuAWsBNsDZwMrA/gC2wIcA+oD/QSWBS8F+wOnArEBMAHqAJcAQABjAEMBTgLFAnQCdQHF/839dPw9/Nz81v3R/m3/Yf/O/gD+K/1v/L/7//qA+vf6ffwd/tL+ff6i/cz8WfxE/AH8D/vT+XD5n/rZ/Lr+H//9/VD8Tftf+wD8g/zN/Dj93f2U/jj/p/+u/0H/lv4J/gD+wf4BAPsARwE8AT8BPQEaAQkBMgF3AcQBKgKfAtcCgwK6AQ4BHwEOAmQDWgRWBHwDpgKAAtQCGgM2AzcD8AJjAhMCbAIlA5EDRANVAlkB8gBTASoCzgKMAlUBIgASABMB/AHoAf4AFADt/4kA6gAOACb+f/w+/HX9RP+PALwAAgD+/jL+z/2X/Rb9TfzQ+/v7lvxo/XH+cf/o/5f/hv4A/eT7Bfz2/GT97PyW/Fn9Ev/XAKIB7AAz/6X9DP0+/ZL9n/3J/Qf/jQEKBMEEVQPuAA3/kf5V/1sA1ADvAGcBhQLqA90EtwR3AxsCnQHnATICEAK+Ac8B0wKWBNwFoQVQBPIC0QHSAGUACwFbAnkD+QPeA1MDxwKgArYCcAKIAVYAi/+6/7oAlgF8AagA///s/yAA+/8S/6P9mPy3/Lr9qv7w/rH+Tf4S/g7+7/1X/WD8m/ti+7L7a/xf/TX+mP5l/qb9i/yG+yD7fvtA/Nn8EP0b/Vj92/1O/kr+vP3k/Br80ftr/Lj97v5j/zn//P7f/rL+ZP4z/mb+Ev/x/10A6P8a/w7/BwADAQEBLwCS/+T/BQEnAn0C7AE3ATgB3wFNAu0BNQEUAdsB4wI+A7wCCQLmAWMCzwJwAmwByAA0ASsCsAKRAmECdQKBAhECCAGp/4v+Yf5s/xwBcAK7AiQCWQHTAHgA/v9g/7f+Lv5H/l3/vAA8AcAADAB2/77+8v1y/Uz9Tf15/Qf+8v7F/xAA7v+y/0f/aP5V/b788fyT/Tr+xP4o/3P/2P8yAAYAav8W/zT/Ov/8/qv+VP5V/mT/TgG/ArwCkwFSAOb/SQBpAIX/cv7B/tUAawPOBFEEtwJ8AXUB7QF4AfH/7/7O/yQCYwRWBcsEdAM9Ap4BWwHUANj/T/9aAIAC+wP/A1wD0gJCAm8BVwAL/zD+7v5PAW4DgQP3AZUAQwCYAJcAmf8a/pD9tP6hAOcBxwGEABz/W/4g/vL96P07/sr+Sv95/yX/k/5y/u3+If8t/pn8+/sZ/QD/MQD8/8r+nf0k/S/9XP2f/er9EP5M/uf+hv+C/9P+Jf4d/r/+i/9HAOYA7ADV/yn+NP3A/UP/WgBcAC0A0AC3AbIBnAAv/w7+rf1s/hQAoAE9AkYCiALJAgkCIAAI/uz8bP07/1gBAAP0A9oDkgLeAKT/K/9m/woAXgACALD/RAB9AVECEgLPABX/yP25/d7+OQDUAJIAKgBtACAB6QBR/9b92v3Z/s3/gQDdAKUAFQBl/3D+ff1i/VX+g/8TAO7/jf9s/63/8/+j/5D+W/0B/f391P9BAX0BGQHbAHQAYf81/sT9FP6+/of/dQC0Af8CWQMNArb/wP1Y/aD+nAD5ARcCYQH4AKABkQI5AngAA/9L/yUBDgNtAyMCvABrAOIAXQGKAVoBJwF4AQIC3gEPAY0A5gCsAeYB9ACG/0j/5QAEA8EDkwJwAPD+Hv9UANQA9P/4/j7/kQC5AdsB/QDw/6X/JAByAN3/yP4X/mL+hP+BAIcAIwAvABwAGP/l/az9UP4o/8L/ov/h/n7+3v5M/2j/Sv/f/mL+cP7h/gb/wP51/pP+U/8nAP//3P75/TP+Ov8tAFMArv/6/rL+h/4+/mT+VP9RAGQAxf9W/0f/XP/E/2kAkQAPAKb/1f9cALoAdgCL/9H+H/8gAKgAPgCy/97/cgCGAOb/Cf9//rb+mv+UADEBSQG2AMf/Pf8x/xf/Cv+A/0AAmABiAAkAAgBmAOIA8QBFACL/Rv4h/oz+Z/+cAJkBsQHoALX/qP43/l/+6/7N/3oAFAD9/q/+of8AAfYB+AHsAJL/0/6h/nH+Rf7R/mQAEQKjAjsCpgHpAAMAl//D/7b/CP91/h7/LgFJAw8EpAOlAugAt/5y/eb9eP8kAUoCtwJ/AuwBjAGcAYcB0gAPANP/+P9dAPUAXwGaARgCggL3AXkAEP/T/vH/bAE0AjwC2wFCAdEApwAmAB//e/4N/4sA3gEZAkgBJQAr/7f+K/8YAFgAuf8h/xL/Hv8B/z//MADQAP7/dv7X/V3+Gf80/33+0v1T/p7/gwDFAGAAHv/e/c39g/67/ur9rfyq/MD+UAFiAtEBEQDN/bX8S/3//Vb+Ov9JAMUAPwGvATIBFwAp/1T+v/0Q/jD/cQBJAZEBpQGkAREBFwB9/zH///5b/wgASgBnAJoAhgCxAKoBYAL7ARIBBQD1/qD+Iv/2/yYBMALlAccAeADiAA4B3AAdAMD+Av7l/pYA2QEtAmYB6//i/tD+C/8V/1D/AgCtALsAIgAf/yT+AP74/hIAUgDs/6P/mP85/0n+mP0J/hv/yf/9/9L/Kf+8/kr/9P+w///+pf7L/o//jACtAOH/RP9Q/2z/Dv9u/mH+df8UAe8BLgFV/3L+9/8lAi8CSgCS/u79rv77AAoDugLxAP//SQDnAFcBOQFwALH/5P8gAUQCJQJWAU8BxQGNASYBXAFxAewAYADq/7L/awCgAR8C+QGQAbEAJgDDAFABpwC1/2//sv9TAMYAjgB+AB4BaAENAa4Aw/8d/mX9PP5V/zsAQwHlAb8BDAGN/3f9J/x2/PL90v8cAUUB4wCSABIAP/9Q/oj9c/04/vz+S/+f/wIAMQBmAHkA3P/V/hb+6f2G/rH/dgB7AC0AoP84/7r/eQANABb/Bv+M/+v/kwBvAUYBFgBw/9r/SwAvAOP/o//d/xQBQwLGASsARP9a//H/8ABqAYIAff/P//QA+gFrAqAB8f8H/2X/5f/a/4X/S/+r/8EA1gEhAloB6f/Z/s7+Pf99/1f/4f7N/qD/mgAeAZEBkwFdANv+O/4i/l3+GP+D/1H/m/96AO8A5QB2ADH/vv0w/Wf9Iv5v/1sAMwDe/97/qP9s/4X/IP/i/fP8TP2o/k0ApAEuAogBuv/c/Vv9Vv6h/zcA9f9+/7//0QChAVoBTgBc/zz/FAAVASwBTACL/8X/wgC1ASoCGwKSAcIA9P9l/3//fwCqAS0CZAKfAvQBKwDl/lH/rwDSARkCXwFWABsAzACKAdEBogH/AE8AOgBvAP7/Q/+f/zMBpgLqArgBcf+e/cb9bv/uAHMB3gBu/2r+2f7d/0EAMwD1/2n/Qf/u/zAA//5a/a/8aP1G/ygBewFMACz/ov4I/oz9w/1A/mT+Yv6x/on/uABPAYwACf/n/X/9zf2G/tv+nP7G/sz/6gBuAQUBrP9R/iz+J/9OACMBVgG1APb/5/8NALL/b/8zAJIBTgL9ARwBLQCY/8P/agDMAN4AOQHdASwCtQGTAKz/KQDBAcQCPQLGAJH/iP9rAPIAyQDjAEYBMAENATQBnQBS/+r+eP+q/5r/+v9jAKEAFwE4AWUAVP+6/lv+Sv7E/j7/Xv+3/2oApgAPAD//yP63/tX+6v75/iH/Pf/2/nT+Wf7F/if/VP+i/93/fP+2/hT+vf0J/iL////h/8b/MwAUAGX/m/9/AGcATv+U/pj+2f40/9v/0wCnAbwBTAEMAeQAUwCq/2//av9P/3D/ZQBjAmgEnARrAnn/vv3j/XD/OgEWAu8ByAFUAgoDpwLMAOv+1v5UAG8B/QDY/5f/ygB2Ag4D/QEtAA3/Sv9qAG0BkwHtAHAAxQACAQIA2v5r//gAHQGe/1r+Rf7e/qP/ZADTAK8AGgCG/z//8v4Q/vr8/PyM/p0A3wHTAacAHf9b/pH+sv4s/q/93v28/v3/7AAIAcQARwDe/vD8MPwC/V7+x//qAAABUQArAIMAJAAQ/3f+1f6L/9L/jP80/1z/LABBAdIBeQGmABUACgAwAPH/Wv9Y/1cAdwHyAdwBVAGeAGIAtQD9AO0AZwB8/y3/EAD3AAoBTwE9ArQCFgLiAKT/1v6w/tD+Ef/Z/x4BXAIVA5YCoQCC/sn9bP4y/0D/5/5f/zcBRAPVA2ACwP+b/ST94v1l/k7+nv4zAGkCWgMWAhAA5f5F/of9Gf1I/Qj+nP+VAYkC7gF0AMv+x/0U/vz+df+8/y0ASwAdAB4A9f9c/xH/e//5/x4A9v+R/2v/EADMAGgARP/L/jz/xv8VAFAAaAByALkA+wChANb/Tv9P/57/w/9s/0L/XQA6AvMCIQIXASwAv/6U/fL9Rf9DAAQB7QGUArsCVAINAVj/Zv5e/tT+EACIAaUBxQC1AB8BsgAhADgABwBi/33/TgCnADAAbf8s/wUACAG2AJj/Wf/O/+f/6v81AO//3P5E/tX+kP+6/+r/eADLALkAqAA/ABn/1/0E/Zr8Gf3K/qEA5QHIAqECzQCx/rT9RP3l/Bn9yf23/kkA/gGKAt8BsAAq/+/94/2f/lX/MwAsAWkB2QA7ANf/yv9LAL0AMQAx/xz/AgDGAPIAzwB9ABwANQDoAIABdAEGAZoAQADh/3P/G/8j/5n/TQAsARgCqwJ8Al8Bgf/R/af9CP9eAHwA5P+2/10AcwEFAkYBnv9w/n/+Tv8RAFsALwAVAG0AkQDy/2P/w/9rAGcA4v8x/17+AP7K/kIAAQFEAOv+z/4+ACgBJgCm/on+wP8yAdABwABz/sz8E/3B/nMA/wByAFQAfgFnAmoBlP/h/jX/NP/Z/jT/QQDwAMYAPgDP/6z/GAD7AHsB2QCC/8j+Vv9TALEAmgC+ABwBXAF3AUUBbAAt/yz+vP3//Qv/bwCNAVUCzAJ0AjEB2/8D/1/+2/0K/i//4gCQAn4D6gIFART/E/4I/pz+cP8XAFYAfwAOAdIBzwGhAGL/If9i/1v/TP+I/7b/qP+N/3f/kP8dAMsA+AB8AKj/9P7Q/ib/g//E//L/5f+y/5b/Qv+E/ib+7P5oAIUBggFSAM7+Hf5//iL/Sf8i/23/jwD1AWcCHQHk/rP9av6V/53/G/9u/4oAaAFNARkAqf51/r//FgEzAVIAqf8vAGgBrAFZAJ7+mv1//Yv+qACpAnADCgPDAeb/bf4W/lf+gv7u/iAA8wGzAzIErAISADv+tP26/e/9Wf7Q/rv/0gFMBC0F6QOuAWL/KP2O+3P7Bf2l/z0CqQOQA4ICEgGm/9v+4P71/qX+g/4h/2YAzAFVAiYBK/9m/jb/TwDaAL8ABABf/67/UwAAAM7+5v0O/or/yAEcA58CVQE5AAT/0f2Q/WX+dP8tAIAAcQBKAHQA3wA1ATUBpQCq/wD/3f6q/oT+V/+/ABkBKQBW/zP/RP+h/7oAAQJUAlsBuv9e/rH9dP2l/df+1wBSAnsC3gEhAXMAFgAEALv/FP+Z/pz++P6I/x0AhAD0AJEBzAE0ATUARf+G/lT+//7s/1YAcgDVAFYBWwGnAJ3/5P7L/hL/eP8RAK4A0QCIAEkACACD/+v+nf7Q/rz/OQFFAgMCuQA3/yX+Bv60/jL/Ev8o/xAAQwEmAosCEAKEALr+y/3Z/VD+0f5m/ysA/wCNAbMBcgGYADb/OP5n/jv/wf/j/wgAVwDYAG4BsAGHASoBSQCd/h39E/1J/sb/MAFQAnkCegEtAH3/pP8kABoAMP88/hb+pf6H/6sAqAH9AfgBBwKXAQsAGv4M/Vb9qf5rAMoBIgKNAboASQA4AOX/2/6h/Tv9CP6g/10BoQIFA6UCxAFgAKj+aP1b/Vz+sv+8ACgB4AA5AAwAAAFjAo8CBQEX/wP+uP3P/UD+2f5u/1oAwQHXAssCmgHV/2P+Af5Y/oj+t/6w/xsB8AEOAuIBfgHzAGEAgv9j/ub9Yf4I/3f/KQAEAU8B7wBSANP/2/+HAPcAXABE/7X+2v5R/7b/wv+5/zEA0wC0ABUAJAAPAeYBAAJKAdj/IP7w/NX82P1r/4gAuwC2ABwBbgEMARkADv9u/q3+iP/7/57/Bv/0/uX/twEBAz0CEwCv/s3+UP9P/9X+TP5r/o7/zAAJAZgAbwCNAGgA7P9D/5j+P/5K/mv+oP5B/ykA3wBKAYABVAHJAGIAXwBpABEAXv+9/qH+Af9z/9r/bAD5AP8AkgBjAKoAwwAkACr/wv5Z/3IAMAEgAXgA2v/D/xYATQAeALH/X/+h/6AAlgFrATAAFP/l/ob/ZwDAACkAXv9b/8r/z/+o/+7/QAAqABEAMwAsAP3/+f/8/8//tP/F/9X/IgDBANgA2P+v/oX+Lf+s/3X/vP5V/ib/GAHpAl0DSwJjALX+FP55/v3+6P6l/kv/+wBNAvwBtgAiAIkAwwAQANX+9v0c/iT/GQBcAIAAOgEzAp4CKALbABD/l/0y/dj9+/4IALwAYgGBAq8DqgMYAiMA6/54/lP+Mf4E/g7+xv4oAIgBGwLCAT8BVwGaAcgAtv7f/Kj88v2n/9QAQwGNAUUC0gIOAhsAcf7+/UD+d/6V/ur+fP8IAF0AuQBmAQUCvQFoABL/w/44/2//Ff++/vX+x//yANQBnwGKAOn/UgC/AGEAxv+W/43/Xv9D/4L/JgD9AHMBEAFEAMD/dv8Y/9X+4f4e/5b/QgCXAGYAeQAmAWQBgwB4/2H/8f8rANT/gP+h//j/8P90//v+3v4R/4//UAD6ACoB9QCzAGoA2/8O/5H+4/6u/woAuv96/9X/dADJALUAVgDn/8//UgAmAZ8BPwEeAOz+b/7C/ln/r/+n/5D/3P+IAMEAAgAe/z//PADmALsANADV/8D/+P9mAKcAXAC9/33/zv/U/9X+m/2Z/QD/ngCEAbEBXAHGAF8AXwBnAA0AY/++/l3+df4R/9D/QABcAJkAMwGsATIBwv+K/qT+t/9/AIAAQwA/AFkAYgBMAPv/fv9T/9b/pgD/AJcA9v/T/zAATQCr//H+Lf98AOUBawLRAZUAdP/s/tz+0f6z/tf+jf/EAPYBYAKnAVUAbf9l/8X/0P9h/wb/P//E//7/9f8nAJsAzQCJADkARwChAMwAWABm/6X+o/4w/8P/JABlAIcAcgAjAL7/bP85/x7/P/+//0oAUADa/3v/YP8u/+L+9f6b/4MAVwHcAb8B1QB3/1L+2/3y/TL+af7C/nr/lQDOAZwCbAI7Aer/VP85/8j+8v1x/dP9Ff/KADsCtgI/ApUBRgEIAUUAH/93/tn+wf8zAPj/6v+uAMIBEgJBAfj/Nv89/2r/L//a/h7/EwD/ACIBnABcAPIAvAGTAVsALf/S/vz+G/8h/z//m/8fAH4AigBEAKD/xv54/i//PgCfAE0A//8JAGAA9QBUAcIAhP/S/hr/hP9r/yf/Uv/w/28ASQCl/yz/Vv/z/34AvAC5AIMAOADl/1b/rP6d/lL/zv9y/wX/df9qAOMAmgA2AFMAzgACAZUA9//U/xEA9v8j//n9V/34/Yn/swDGAIwABAH/AYAC8QGYADD/Y/6H/l//OACAAFoAbwAYAcEBoAHwAHQAJACL/wT/M//H/+7/wv8TAOgAjQHoAWMC4QLTAvcBiQAw/5L+wP5b/wsAggCnAPYA7QESA0oDQgLbAPr/xf/+/0EACwBe//H+Ov/W/yYAIgBDAKoA3QCaAEEACACx/zz/Df9u/zQA0QC5AOn/Af+k/sn+8v73/v/++P7S/tb+Jf92/6b/u/+Z/zX/1f6u/or+R/5B/tv+1v+bALAA3/+v/jL+q/5L/6L/3P/b/27/Bv8Y/27/qf/R/+v/pv8J/5X+hf6w/hD/lf/+/zUAQAALAKz/Zf9C/zv/cf/m/1sAeAAfAK//m//s/1EAbQAfAL7/sv/X/9z/zP/o/0AAlgCtAJkAoADfAB0B7gAvAFX/4v7a/h//nf8dAJgAPAGzAYgB+ACRAFkA+/9d/9L+w/5H/wMAcwBtAGYAsQDcAIEABgDM/8T/6v9JAIoAQgCc/zr/bf/v/20AsgCAABUAFQBfAD0Axv+h/9//JABFAE0AVABoAHYAcQBrAIIAkwBmADAASgBsACUAx//U/yYAWwBYAEoAVABkAFUAQAA7ADkARgBcADcA+v8OAFgATADf/5j/z/9PAK4AvgB2APb/wP8sAOEAMwHaACUAuv+7/6v/Wf89/7D/mQCNAfABdgFzAKr/mv/m/7D/Af/X/p3/hwC6AGEASQC7ABcB0QAlAJb/Yv96/7b/+P8cAPf/sf+4/zIAywD2AF4AdP8S/1L/tP/p/93/of+i/x0ArgDOAGkA6f+1/7v/ov9s/3L/1/9EAF4ATQBvAKIAnwB5AFgAMADr/4H/Jf84/6L/6f8UAFYAfQBoAFIAVQBGABMA0f+V/2n/cf/K/z4AfQBzAB8Aov97/9z/OwAzAPn/1P/X//L/+v/b/7j/zP8WACYAu/9i/4z/yv+1/43/lf/A/+f/1P+Q/37/vf/4//T/2f/m/xAAJAATAMv/UP8E/yb/Xv9u/4D/nf+0/93/EwA7AEYAFQCw/2//cP94/2b/U/9j/57/zP/G/7D/tv/S/9L/oP96/6r//f/7/57/X/+m/zcAZQAOAMf/2v8bAHQApgBsABMAAgAMAOH/nP+E/7b/DQBOAGYAbgCCAKwAvACeAHcAPQDm/8H/8f8NANr/mf+T/97/WQDPABMBAQGuAGcAMwDs/9X/HgBlAGkAWwBQADcAIgArAFEAbQBHAPT/0//4/xYA+f/m/zEAnQC5AJgAgQBjAEEAOAAmAPL/uP+K/4f/w//0/+v/7/8hAEIAQwBTAGsAPgCu/yT/Hf+U/xgAUAAvAPn/2v+v/3n/bv+D/5H/r//o/ysAVAAmAKz/X/+E/9n/GgArABkADgAOAPz/0v+w/7X/4v/6/+L/1f/3/xUAFgAJAAUAGQAzADIAEQDi/9H/8P/1/7b/lP/C//v/DAD7/9D/x/8CAEEASwA2ABQA6v/V/+j/EQApAB0AFwAnACYACgDz//f/GQA6ADwAMAAiAAMA7P/6/yUAdgDGAKMAHwDO/87/0v/T//7/SQCQAKsAiwBFAAIA2v++/5r/kv/G/xAAVAB4AFAA/P/Z/+7/AQAAAN3/qP+W/8H//v8TAOr/yP/+/2kAlwBaAOf/nP+0//v/EgDq/6v/lP/R/y0AJwCz/1D/Xv+o/8f/y//0/xoADAD1//D/7P/7/wgA2v+P/4H/uf8IAD0AQAAsABwADADs/8T/sv/Y/xQALQAoADYAUgBRACIA6P/E/6P/jf++/xsAQQAwACsAOQBYAIMAhABUADIAOABKAFQASgAdAN//wP/x/1IAjQB3ACEAzP/a/1YAyADUAIoAKADl/+H/EgBTAHsAYAAjAAsAKABcAHoAYQAtAB0ALAAxACkAHQANAAoAEQASABsAKgAuACQAGwAVAAcA9P/+/yEAIAD7/+3/+f/9/wQADAADAAAACwAPAAIA6//d/+//AgDo/73/vP/Y/+P/z/+t/5r/m/+t/8j/3P/m/+//9P8EACoAKADV/4X/fv+T/5f/jf+C/5X/1P8LAAcA2f+4/8H/1P/C/4//bv96/6v/1P/b/9D/xP+0/6//xf/Y/9z/3f/e/9j/1f/k/wMACgDY/6r/wP8BADEARwA/ABoA6v++/6D/nv+s/7P/uP/S/woATQBoAE0ALQAwAEEAMAD3/8T/sP+n/6n/y//0/wkADAAEAPv/DwA1ADkAEwDp/83/v/+8/7r/w//l/xEAJAAYABQALQA8ABwA5f++/7v/1//9/w8ACwD///7/DAAQAPn/3v/g//r/FAAkADEARwBXADwA9v+2/6T/w//4/x8ALwA6AEoAYABqAFoAPgAmABUADAAQAB4AMAAzACgAKgA6ADsAJwAlAEQAXABNACUADgARABwALAA5ACsAEAAMACAAJgAeABkAFAACAPv/EAAiABsAEwAfACYAGgD//93/x//c/wwAMQA2ACQACgD4//X/9f/o/9b/0f/W/87/xf/a/wYAIAAQAOj/wP+l/6D/vv/u/wAA5//K/8L/yv/M/7z/p/+m/73/4P/9/wsACgAEAPv/8f/y/wEACwD9/97/1P/r/wgACQD8//v/CAAJAOv/zv/d/xEAKAABAMv/0f8WAEsAPgALAO3/+f8XACUAGQAMABQAIwAgABQADgAIAAEACAAhADsASABKADcADwDu//T/FgA0AD0ANAAfABQAFgATAP3/7P/7/xwAKAAkACoAOgA2ABkA+//4/w4AHAAMAOv/2f/g//D//P/4/+T/zP/O/+r/CQAWABgADADv/8X/qf+t/8f/4//5/wcACAD8/+v/3P/W/9T/0//T/9D/yP/E/9X/9/8LAAEA7P/o//T////4/9//yP/L/+j/AgAGAP7//f8FABMAFAABAPT/CwA0ADsAGgD+/wMAFAAbAB4AJQA3AFYAbQBeAC4AEAAWACEAHQAiAD0AWwBhAFwAYgBvAGsASQAfAA0AGwA3AEYAQAAtABcABgADAAsACgDy/9b/2v8DADEAQAAxABUA+//t/+z/7v/r/+3/BAAlADEAHQD7/9//zf/C/8n/4f/6//3/8v/x/wYAJAAyABsA7P/H/8L/zf/V/9r/7P8MACsALwAPAN7/wv/E/9D/1//g//L/AwAHAPn/6//o/+f/0/+6/7z/3v///wYA9//u//b/AQDv/7v/mf+8/w0AQgA+ACgAHwAYAAUA5v+8/5v/p//m/zUAWgBKACoAFAAJAAIAAQABAPz/+f8JAC0ATABMACsAAQDp//L/BAABAOj/1P/Z//H/BQAAAOT/xf+7/8//9f8cACsAFgDt/8z/xv/Q/9v/4//s//f////9//P/7P/x//v//P/t/9D/uP+3/8f/1v/i//D/9v/p/9X/0f/b/+P/4v/k/+n/7f/p/97/z//H/9L/7v8HAAoABAAGABMAGQASAPv/1/+4/8X/+/8lACQAGAAeACMAEgD9//n/9//t/+v/+/8PABgAFwAcACoANQAxACQAGQAWABsAJQAlABAA8//u/wgAKgA8AD8AQwBKAE0AOwAVAOv/z//O//D/HwA+AEQAPwA3AB8A/P/i/9X/zP/M/+H/CgAuADgAIwAFAPL/7P/m/9f/y//F/8z/4P/z//X/6f/c/9f/2P/b/9j/z//V//L/FAAcAAEA4f/W/97/5f/d/8z/wv/P/+n//f/+//v/CgAjACkAFgAFAP//9//n/93/2P/V/9z/9v8QABQADgAVACIAJQAYAAQA9f/z//r/BgAVACMAJQAeACQAMAAtABMA+P/p/+P/6v/6/wUABgAEAAkADgAVACAAKwAvACcAFgANABMAFwAKAPT/7/8DACAAMwAxAB4ADAABAPn/6f/W/83/1//t//v/+P/3/////v/n/8r/u/+2/7X/uv/F/8//3P/v//r/8v/e/9D/y//J/8b/xv/J/83/yv/B/8X/2//p/97/yP/B/87/3P/j/+v/9/8AAPj/6f/n//b/CQAVABYADwADAAAABQAHAAkAFQAjACYAJAAlACIAGQAXACsATgBkAFgAMgAXACMAPgBGAD0APwBLAFMAWQBfAFsATgBMAGEAdwB5AGgAVgBNAEYAPQA5AEAASABDADsAQABVAGUAZgBcAE4AQAA3ADMANgA2ACwAIAAdABgAAADj/+D/+/8eADkARAA4ABgA9v/c/8z/yv/W/+H/5P/o//j/DgAbAA8A7f/L/8P/xP+7/7D/uv/U/+z/+P/4/+r/0//G/9L/4//j/9P/yP/L/8//yv/I/9f/6//0//b/9P/y//D/8P/n/8//tv+t/7T/wf/O/9r/5//4/wkADwAJAP//7v/c/9v/8P8JABYAHAASAPL/zP++/8j/2f/l//T/BgAWACIAJAAWAAEA/v8VACsAJQADAOn/8v8IABAADAAKAAIA8P/o//L/AgARAB4AKgAtABoA+f/p/+//+P/v/+D/3//l/+f/7v/+/woACgAHAAMA/P/+/xEAIQAbABQAHgArAB4A/P/q//7/HwApABgABgAHAAwACgAKABAAFAALAP///P8EABEAFAALAAMAAwABAO7/0v/E/8z/2//b/9b/6P8TADUAOgAsABkAAADp/97/3v/f/93/3P/i//P/BgAJAPf/5//u/wIABwAAAPP/5P/e/+T/5f/Z/8v/yP/T/+7/CQAVABEAAADu/+n/8f8BABMAGwAUAAwAAwD9//v//P8AAAUAAADx/+n/7P/q/+f/6v/t//T/AQADAPv/+P/3/+z/2f/N/9r/8f/x/+f/8P8HABcAHAAQAP7/8v/p/+z/CgAlABwABwAGABMAFwADAOr/7v8KAB8AKQAqAB4AFgAUAAgA/P8CABcALQAwACIAJgA/AD8AHwD7/9//1//z/xkAJQAaAAsADAAbAB8AEgACAPP/7v8GAB4AFwD//+3/4f/n//z/CwAXACMAJwAhABIA9f/h/+D/4P/f/+7/CAAeACQAFAAHAA0ADgD5/+P/2f/m/wUAFQAMAAkAEwAZACAAKQAnABsACwD2/+7/9P/3//v/BgASABwAIQAXAAUA9f/l/+L/7//s/+D/5f/x//b/9//0/+v/6f/v//j/+f/q/9X/2f/u//n//P8DABAAHAAaAAkA+v/y/+b/4f/r//T//P8GAAcABAAHAAEA8f/n/+v//P8TAB8AFQADAPj/AQAQAAcA7f/f/+n/+v8GAAUA+f/4/wIACgAMAAsACQAPABwAGwAHAO//5P/q//b/AwANAA0AAQD7//3/9f/k/+P/8v/+//7/+v/7//3/8P/e/9n/5P/v/+n/3v/b/+X/8//+//n/6v/p//b/AQAAAPj/8f/z/wEACwAIAPz/9v/8/wIA///7/wEACwAbAB4ACADx//X/BgAOAAkA/f/3//r//v////////8CAAgACAAAAPn/7v/p//T//////wMADwAYABkAFQAWAB8AGgD///D//f8MABIAGQAaABkAHAAdAB0AEQD7//T///8HABMAMAA7ACwAIAAaABUAEAAFAPj/+v8AAP///v/9//3/DAAeACMAHwAUAAEA/v8GAAAA+f/7//v///8LABEAGAAfAA8A9//x//j/BQAYABwAEAANABMAHgAsACgAFwAUABUACwAIAAYABQASAB8AGAAXACMAKAAuADYAKQAQAAIA/P/6//P/7f/9/xoAHwAWABAA///t//D/9P/s/+r/6//t//v/AAD4//z/AQD9//3//f/0//P/+P/2//H/6P/m////IQAvADIALwAbAA0ABwDz/+X/9P8AAPv///8QACQALwAbAPn/6P/m/+r/9f/1//D//f8NAAwABAD+//n//P/1/+X/6//+//z/6//n/+r/8P/8/wUABwD+/+z/4//h/9z/3v/m/+L/1v/Z/+T/7f/w/+f/3//o/+//6v/k/97/2P/h//D/6P/R/8L/wv/M/9z/7P/+/wcAAgABAAIA9f/s//T//v8BAAAA8v/j/+b/+P8AAAMAAwD8/+3/4f/j/+//9v/0/+7/7P/z//7/AAD8//7/BgAJAAcAAgD7//T/7//u//b/BAAKAAIA9f/x//T/9f/0//j//P/5//H/7f/3/xMAKAAgAAgA/f8EAAcAAgD6//f/+/8GAAoAAgABAAkACAACAAoADwALAAoAEgAPAP7/7//v//n/+//4/wAAEAAXAB0AIgAeABoAEwAIAAIACAAIAAoAGAAkACcAKgAfAAcA/v8DAAQAAQD//wEAAgD//wUADgAGAO3/4//w/wIAEAAJAPj/+f8DAP7/9v/2//j/+v/6//T/9P/w/+L/3v/r//D/6f/k/+L/5f/q/+H/1P/V/9X/2//w//z/+/8GAAoA9f/k/+b/5v/o//r/DAASAAsAAQD///z/8//1//7/+//7/wgADQAGAP7/+P/3//r/+/8DABMAGwAYABIABwD6//n/+//6//f/8f/4/w0AFgANAAYA/f/y//r/AQD2//T/AwAEAP7/BgANAAcA/P/4/wAAAwD0/+z/+/8DAPb/6f/l/+r//f8NABAAEAALAAAA+P/1//T/7//k/9//8f8HAAkA+v/u/+v/7f/q/+b/6f/x//r/CAAQAA0AFAAeABgAFAAeABsAEgAWABsADQACAAYAEgAXABEADQAVABUAEQAWABoAFgAZACAAFgAIAAkAEQAUABQADQAAAP7/BgAJAAkADAAWAB8AGgANAAYACgAMAAMA+P/7/wUACgANABIAFQAZABwAEwADAPr/9v/x//X/BQAaACgAIwAVAAsABQD+/wIADQAPAA8AEAAMAAkADAANAAkABwAGAAYAEQAbABQABAAAAA4AGwAZAA0ACQATABcACwACAAYABwAHABMAIAAbAAoAAgAEAAUA+//z//n/AgAEAAcADAANAAwACwAFAAAABAD6/+H/3//2/wgABwAEAAEA8P/e/+f/AwAQAAcA+//8/wIAAwAFAA4ADQD+//b//v8IAAoABQABAAIABQAHAAwAEwALAPr/9/8CAAUAAgD///r/9f/z//T/AQATABcADwAOAAkAAAD//wkADQAKAAUA/f/2//n/BgARABEABAD7//7/CgALAAAA9P/s/+X/5P/q/+//7P/j/+D/5//s/+r/5v/g/83/wf/T/+7/9P/o/9z/2f/i/+v/5P/W/9H/0P/Q/9r/3P/Q/8r/2//z//v/+f/8/wcACAD3/+X/4//v//n/AgABAPj/7f/s//b/BQAIAP7/9v/7//z/9P/1////AQD9/wAABAADAAoAFgAXAAwABQANABkAEgD//wIAGgAkACEAJQAqACAAEAAIAAMABgAVACQAIQARAP//9//5/wYAEwAUAAYA//8FAAYA9//r/+3/8P/2/woAFQAMAAAABAAOABUAEAACAPv/CQAbAB8AFgAFAPr/AQARABEABQD8//n/+f/9//7/+v/1//r/CAAXABgACwD+//X/7v/t//P/9P/x//H/8f/y//X/7f/Y/83/2//p/+z/7P/r/+f/5P/k/+T/5//m/+P/4//j/9r/zv/Q/9v/5f/v//j/9//1//L/5f/U/9D/2v/g/+H/4f/k/+j/5v/g/9v/2v/k//P/+f/r/+H/6f/t/+r/8f/3/+n/2P/Z/+b/7v/z//H/8v/5//3/9P/r/+v/7//y//j//P/7//j/+P/5//X/7P/o//L/AQAJAA4AEgAPAAgABAD8//z/BgANAAUA/f/9/wIABQAHAAsAFwAlACgAIgAkACYAHQAXABMACgAEABAAHgAcAA0ACAAVACgAMAAsACkAJwAfABsAJQAtACwAKwAtACcAHQAZAB8AJAAkACQAKQAuACYAHgAcABgAFQAeACgALwA8AEYAPAAvADIANAAmAB0AIwAjABkAGQApADUAMAAlACkAMAArACQAKwAxACQAEAAGAAYACAAGAAEA//8FAA0AEwARAAIA7v/p//T/AwAMAAoA+//1/wAACwAFAPT/6P/j/+X/5f/l/+z/+P/5/+//5v/k/+n/9P/9//7/+f/5//v/+v/2//L/7//s/+j/6P/t//P/8v/s/+j/6f/v//P/9//7//v/7//l//D/BQAPAAoAAQD5//P/8f/r/+X/5P/m/+j/7v/z//H/7v/z//T/6P/b/9//7P/v/+j/5f/r/+7/7//3//v/8//n/+n/8//1/+7/6v/q/+X/3v/h/+v/7//r/+3/9P/y/+3/8P/2//L/8P/9/w0ACgAAAAYAFQAWAAUA/f8CAAYAAQACAA4AFwAVAAkA/P/3//j//P/8//b/9f/+/wMA/P/y//f/AwAEAPz/+v8HABIAEQAHAAQABQADAAEABgAJAAEA9f/1/woAIQAoACMAGwAUABIAFwAhACMAGAAHAP//AgAIAAsADQALAAYACAAUAB0AFgAHAP3/+v/5/wEADgAOAP3/8f8CABsAHQALAAEACgAQAA0ACwAQABEADAAKAAkAAgD9/wMADgAKAPz/+P/+/wEA+//9/wUACQAHAAQAAQD1/+j/6P/x//T/7//s/+//7//s/+z/8P/v/+r/6//x/+7/4f/Y/9v/3f/V/8v/yv/T/9r/3f/e/93/3P/b/97/5v/w//T/7f/j/+L/7P/2//X/6v/f/9z/3v/g/+H/5//r/+v/6f/u//j//v/5//T//P8KAA8ABgD6//r/AwAKAAcAAgD//wEABwAJAAoADQASABcAFQANAAUAAwACAP///v8CAAkAEAAUABYAEwAOAAYA/v/4//v/BAAOABIAFAAVABUAEAAKAA0AFQAaABMABwD+//7/AgAFAAkADAAQABAACAAAAP7/AQD///r/9v/2//v/BAAMAA0ACwAJAAcACQAQABkAGQANAAQABgALAA4ADwAOAAwADQAVABsAGgAWABkAHwAdABUAFQAbAB0AGQAYABgAFQAXACIAKQAiABcAFQAWABkAHgAgABQACQAMABgAGgATAAsAAwD+//3/AgADAAIA/v/8//z/+v/4//X/8//y//b/+///////+f/x/+b/4//p/+z/5P/f/+T/5//h/+D/5f/m/+b/6//o/9j/0f/d/+r/6v/r//L/8//u/+3/8P/o/93/3P/k/+f/5P/m/+//9v/2//T/9v/3//P/8v/2//b/7//v//z/CgARABUAEwAFAP//BwAJAP7/+v8GAAwABgACAAYACQALAA4ACQABAAEAAQD0/+v/+v8NABQAFgAZABkAFAAMAAYABQAFAAEA/v8AAAAAAQAMABYAEAAHAAYACgANABEAEgAOAAcABgANAA8AAgACABMAFQAMABAAGwATAAcADgAVABIAEQAXABYADgAGAAAAAAACAAUAAgAFABEAHwAcAA0ACAANAAwABgACAAIACQATABEACgADAPn//P8OAAgA7//z/wQA9P/q/wYACADs//H/CAD7/+v/8//3//v/GAApABUABwATABYA///s//T/DAASAP7/6f/g/+v/BAASAAgACAAUAAoA/f8SACcADwD0//v/AwD7//n/CwAmADIAGwACAAsAJgAyADQARABMADYAVgArAWgCMwNdA1QDAwMsAk0BzABDAIr/Df/g/rr+kf5l/iv+Ff4w/jj+If4m/kD+WP6b/g3/Wf9a/1H/f//C/8X/jv99/5//pv+A/1T/Jf/m/rn+vf7y/i//K//c/pz+m/6n/pr+kv6f/rf+1/4K/0r/df+B/4//qf/D//D/MQBIADoAVgChANkAAAEfAREB7QDmAOcA4QDwAAkBEgEkAUUBUAFIAUMBOAEvAScBBwHgAOwAGQErAR4B/wDFAJcAlgClAJ8AlgCNAHwAbwBtAGYAVgBIAE0AWgBdAFQARQAoABEAGgAxACgABADq/+X/5f/l/+T/4//m/9//wv+a/2//R/83/zT/J/8m/0b/ef+x/+n/+v/Q/5f/d/9g/0b/Nv9B/27/rP/k/xQAOQAzAAEA4f/w/wEA8P/J/6P/l/+p/8D/wv/I//D/KwBMAEoAQwBUAHAAhACTAJwAkQB+AIMAmQCiAJwAmACRAH4AaQBYAD0AIQAhAD0ASwA6ACgAJwAjAB0AIQAmACsAPwBaAFsASABGAFgAagB8AJQArQC2AKUAiQB5AHAARgACANb/1//f/9j/yv++/6z/k/9v/0r/PP9L/0z/Kf8O/y7/cf+Z/5z/l/+X/6H/wf/f/9v/vf+n/6z/x//g/+r/5P/g/+P/5f/f/9H/wP+w/6T/lf+F/4D/hP99/2r/af+D/5//tv/T/+//+f/8/wYACwABAPz/CQAQAA0ADgALAPf/6f/0/wQADwAZABkABQDm/8n/rP+V/5H/nP+y/9X/7//t/+X/8v8GAAgA/v/y/9r/xv/R//P/DQAXABwAGQATAB4ALwAkAP7/2v+6/6D/pP/K/+z/9f/8/xEAJAAxADsAQgBEADoAHgAIAB0ASgBaAEsAPwA4ACsAIwAcAAMA6//3/xcAHAAFAPP/8v/4//T/4P/G/8f/5v/7//T/9v8lAGoAoQC4ALcAsQDBAOAA6gDTALcAqwCgAJQAjwCKAHUASwAgACAAcADsAEMBbAGRAacBkQFtAVsBOQHoAIwATQAqAAwA4v+q/3X/Tv8r/xf/KP9Q/3D/kP/I/xAAUACHALUAyQC5AJUAfQB0AFgAGQDe/8n/zP/D/6z/lP98/1v/NP8j/y7/Jv/1/sj+w/7C/q7+r/7M/tr+xf6q/qz+0v4L/y//QP9h/43/p//C//D/EAANAAcAEQAXABUADgD9/+f/2v/Q/83/2v/e/8X/rP+u/7T/rv+0/8n/4P/z/wUAEQAgADEANAA2AE4AcQCWAMMA7wD/AAEBDwEnAUYBbQGIAYUBewFxAVoBOwElAQsB5QC7AIcATwA0ADIAIQABAPz/EwAzAFEAXgBTAE0AUwBXAGAAegCNAIcAhgCWAJwAjABkACsA/////xEAEgALAP3/2/+4/6//rf+d/4D/Xv88/zP/P/9O/1f/V/9J/z//Tv9X/0P/Nf9F/0//R/9I/13/df+J/4//kP+f/7X/tP+l/6X/qP+Y/3//a/9Z/1L/W/9h/2H/Z/91/4H/kf+f/6z/vP/J/73/p/+m/7H/tf/A/8//zP/B/83/3P/R/7T/l/+A/3D/bP9w/4D/mf+o/7T/0f/4/w4AFgAWAA8ADAAWAB0AGgAZACMAOQBUAGIASQAbAAMAAQAAAP3/+v/x/+v/9P8BAAAA7f/X/8//3f/0//v/7//b/87/2v/5/xMAJQBAAGIAdwBzAGIATAA8ADkANwAtACAAGQAPAAkACgAJAP//+v8NACoALwAbAAcA/f/o/8H/pP+o/8L/3v/5/xEAGwAcACIAMQA7AC4AEQD5//f/BwASAA8ACAAKABsALwAzABsA+v/n/+j/5v/X/83/0//c/9f/zf/M/9T/4v/5/wQA9P/a/9X/4//l/9b/zf/T/93/8P8RACsAHQD0/9r/4v/y/+//5f/n//L/+P/0//n/DwAjACAABQDq/+H/6//5////+P/u//T/BgARAAkA+//w/+j/6f/5/w0AFwAaACEAJgAdABUAIwBDAFsAZQBrAHAAcwB6AIMAfQBiAEwATgBgAGYAVgBBAD8AUABdAFMAOgAnACMAKAA1AEEAQQAvACAAKABBAFQAXgBqAIEAnQC4ANEA3QDaAM0AwwDDAMsA0ADNAMoAzwDZANgAyQC7ALYAsACjAI8AgQCDAJMAoQCeAI0AgQCDAJEAqQDIAN0A2wDWAOEA9AD4AO4A6ADqAOcA5gDxAPoA9gDsAO4A9wD/AAsBIgE9AUYBQgFEAU4BVQFIASsBFwEYAR4BGAEDAegAzAC2AKoAogCXAIsAhAB4AF4ARAA7ADsAMAAfABcAEQADAOz/1v/A/6n/ov+r/67/mv+D/3b/ZP85/wP/1v61/pf+ef5c/jv+FP7t/c/9uv2m/Yn9Zv1O/UT9N/0b/fb82vzS/Nb83PzR/MD8v/zW/Oj84PzN/ND86PwB/RT9KP1D/WL9eP2C/YP9iv2e/bn9z/3c/ev9/v0S/ib+OP5G/k3+VP5f/mj+bv53/oL+lf6y/t7+Cv8q/0T/Zv+M/67/y//n////EQApAEkAcQCYAMAA5QAHASoBTAFkAXEBeAF6AXcBdAF3AXoBeQF3AXQBagFXAUoBSwFeAX0BlgGWAXsBZQFtAYIBhQFyAWYBYgFYAUcBRgFZAWwBcgFwAW4BbAFtAXABaQFbAVEBSgE5ASABEAENAQUB8gDgANkA2ADSAMIApwCMAHYAaABmAGoAagBpAG8AeAB2AGoAYQBaAEsAPwBAAEgARQA1ACwALwAzAC4AJgAkACcAKgAtADAAOwBSAGsAcwBmAGAAcACCAIIAfAB6AHcAdwCHAJ8AoQCOAIIAhgCJAIEAfwCLAJwAmQB/AGEAWgBkAGAARAAmABkAFQAOAAQA+P/o/93/4f/y/wIA///v/+b/6P/r/+r/7v/3//f/6v/b/9H/y//E/7j/r/+o/6T/oP+g/6P/mv+H/33/jP+k/6j/n/+a/6b/vf/Q/97/8P8VAEMAYwBvAIEApADLAOgA/AALARwBPAFoAY8BrAHEAdkB6gH+ARMCIwI1AlECeQKnAtsCEAM9A1gDcQOfA+MDHwREBF0EfQSjBMsE+AQlBUYFWQV0BZIFmgWKBXAFUQUpBfoEywSJBCUEswNKA+QCbwLiAUcBqQASAHn/1v4y/p/9KP3B/F/89/uG+xr7ufpp+iT64fmb+Vz5MfkR+eT4q/h6+FX4LPj898z3mPdf9yX38fa69nb2J/bi9a31gPVV9Tf1LvUu9Sv1MfVI9WX1gfWs9ez1NPaA9uH2X/fq93r4Dfmh+Tn63PqC+xb8nvwv/c39ZP7n/mb/8P+BAAsBjQEQApYCGwOYAwMEZAS+BBUFYQWhBeQFOAaSBt0GHQdlB60H4QcJCDAITwhdCGIIaQhvCHgIiAicCKgIrgi3CL4IwAi7CK8IngiFCF8ILwj9B8YHigdMBxMH1gaDBiUGwgVTBc0EPwS1Ay0DoAIWApwBMAHNAGoADgC//3n/MP/b/ob+Pf4B/tL9sP2Y/Yj9gP2B/Yf9iP2A/XP9bv1x/WT9RP0o/R79GP0J/fv88vzk/Nj83/z0/Pz87vza/M78y/zF/Ln8s/y+/Nb88PwL/S/9WP2B/a794v0a/k7+ff6s/uP+H/9d/5//7P9DAJEAzwAJAUYBeAGdAbkBzAHTAdABxAGnAYEBWwE0Af8AxgCUAGoAPAAMAOD/t/+N/2v/WP9X/1r/XP9n/4P/p//I/+X///8JAAkAEAAdABYA+f/i/9r/yf+q/4r/bP9E/w//2v6t/oT+Uv4b/vD93P3Y/dX90/3d/fD9Cf4h/jf+U/56/qT+xP7k/hT/Rv9v/5j/zv8JAEIAeACmAMcA5QAJASgBOAFEAV8BggGiAbUBwQHQAeQB8gHvAeABzwHEAcEBvgGzAaQBmwGTAX4BZQFbAVUBPgEeAQcB9ADXAK8AjQB0AGsAbQBvAGIARQAkAA0A+v/c/7b/m/+O/37/Yv9M/0H/Nf8f/wv/+f7d/sD+qf6S/nT+Tv4q/g/+BP4F/gf+EP4p/lX+l/7v/k3/rf8eAL0AfQFIAhcDAQQQBTYGVwdtCHkJfwpqCyYMtgwqDYANrw2xDXsNEA2JDPoLWQuKCo8JeAhaBzoGFwXxA9YC1wH+AEoAuv9O/wb/4/7j/vb+E/9B/3n/o/+2/73/wf+//6z/i/9a/w7/mv4C/kv9d/x9+1T6D/nB93j2OPUH9O/y6PH08CnwmO8w79vul+5v7l7uW+517rvuKO+k7zXw5/C38ZLybfNF9A/1xPVp9g73rPc7+Lr4OfnD+VT64/py+wn8oPwt/bL9Nv6x/hz/gP/k/0MAmwD1AFgBwgEsApAC8QJUA8EDLQSLBOIEPgWgBQUGcQbqBm4H9geECBwJvAlaCuoKZwvOCx8MXwyJDJYMiQxxDFYMJwzcC3UL9wpdCqoJ5AgOCCUHMgZIBXEEqgP0AlICygFaAfYAoABdACYA5/+v/5P/hf9w/1//bP+M/6f/tv++/7z/rv+S/1//Ef+x/kT+yv1R/er8jvw6/PL7tft2+zn7AfvM+pn6b/pK+in6IPo8+mn6oPr0+mr77ft1/A39p/01/rr+QP/P/2YAAQGTAR8CtQJVA+cDYATEBB0FZAWNBYkFXgUmBewEnQQ3BMkDXAPuAowCPgLzAZcBKQG/AGcAKQD2/8L/nv+d/7n/6v8wAIIA0wAmAX0ByQEFAjgCWgJhAlMCOwIRAtYBlAFDAdQAVQDY/03/qf4C/mz91/w9/K77O/vq+rr6m/qH+pb6zPoK+0H7kfv8+2b8wvwk/Y399/1o/tv+Ov+H/9b/IwBgAIwApgCoAJ0AlgCSAIYAcwBjAF0AZQBrAGMAWgBlAH0AhgCAAIQAmgC8AOIACgEwAVsBiAGxAdYB+gERAhoCHgIgAiACJgI4AkQCQAJAAlICYAJVAjgCDwLgAawBbQEfAdEAiwA9AOb/lv9K/+r+e/4S/qL9Fv15/N/7TPvI+lb67PmI+Tz5EPn2+OT43vjh+PD4G/le+ar5/flY+rj6HPuS+xT8ifzp/Dz9if3R/Q7+Lv4z/jr+Tv5j/nL+j/7A/gL/YP/p/4sAOwEFAvMC/wMkBV0GrAcSCY0KBwxyDcwODxAsESAS7BJ9E8gT4BPOE4MT+hJDEmcRXRAwD+0Nmgw3C84Jcwg0BxYGFAUrBGkD1wJxAi0CAQLfAccBwwHGAboBnwGDAV8BIQHLAFYAsv/c/uz95fy8+3H6CPmD9/f1cPTo8l3x7u+t7o/tj+y36wTrdOoU6tnprume6b3p+ek86p7qN+vv66zsee1Y7jDvA/DZ8KjxZfIf8+HzpPRg9SL28PbM9634jvlr+kT7FfzW/I/9Tv4L/7b/UwDyAJYBNALFAlED3gNrBO8EagXgBUoGpgYBB2oH4QdiCOkIcQn/CbQKjAtbDA0Nvg2BDkIP9g+VEAgRVhGgEd0R4hGnEVsREhGwECEQYg9xDmENSQwpC/YJugiBB08GOwVOBG4DjgLIATcBwwBcAAcAyf+O/1r/PP80/z3/UP9f/1v/VP9Q/0b/G//Q/nL+Cv6W/RH9e/ze+z/7oPoK+oD5/PiB+BX4rvdA99f2hPZG9hH28vX39Rj2Ufag9v/2cfcH+LT4WPn0+Zz6T/sG/Mn8n/2C/m7/XQBBARUC8ALIA3EE5QQ6BXsFnQWpBaIFegU2BfQEtQRhBOkDWAPFAj4CvgE5AbQASgAMAPD/6////zMAiQAAAYgBBwJ6AuoCagP4A30E1wQGBSwFUAVVBSgF3AR/BAYEbgO5AucBBgElAEL/Tv5W/Xn8vvsf+5j6JvrK+Y35fPmI+aH5xfn3+UD6p/oo+6z7JPyc/CH9pf0W/m/+u/77/i3/Uf9r/27/X/9T/1f/YP9m/27/gf+Y/6v/vv/N/9f/4//1/wYAGgA8AGYAkQDLAA8BQwFiAYIBrgHRAeEB6QH1AQwCLQJLAmUCigLBAu0CCAMrA1oDeAN+A34DeANfAzwDFAPdApkCWgIXAroBRQHIADkAjv/N/gD+MP1s/MD7G/t0+uD5gflS+TP5D/n4+P74HPlB+XH5v/kq+qj6MvvB+1H85Px2/fX9Vf6b/sr+4v7k/tT+sv6L/mX+OP4B/tb9wf20/a39v/3m/R3+eP4E/6r/YQBAAVEChAPfBGgGAAiGCQcLkgwWDnUPnBCBETYSzhI9E2UTShMNE68SIRJkEXUQSw/3DZkMLgumCREIkgY0BfUD2gLuAS8BmAAoAN//uv+n/5f/iv+Q/53/pP+n/6X/jf9n/0D/Cv+h/gb+Rv1d/Er7G/rM+Fr31/Vc9OLyafEQ8N3uxe3M7AjsdOv76pXqSeoc6h/qUuqi6gXrketS7DjtNO5L73LwoPHL8unz8PTn9d/21/fF+KP5b/o0+//7yfx//Rn+pf4h/4X/2P8fAFcAeACVAMUAFgF8AeEBOgKZAhcDsANEBMsEVwX5BakGWQcQCNcIrQmJCmkLUQw1DQwO0g6GDx4QkhDoECMRNhEjEf8Q0xCNEB4Qiw/oDjsOdA2BDGcLPwolCRoIEAcDBv8EFARFA4cC1AE3AbgASQDh/4j/S/8d//f+5P7t/gf/IP85/1n/df9//3f/Y/82/+3+k/43/s/9Sv21/Bn8d/vP+i76mfkG+Wz40/dA97j2R/bw9af1bvVX9WX1jfXS9Tz2zfZ19yX43vip+Yb6bPtb/Fj9Xf5d/1gAUAE+AhYD2gOMBBsFhgXbBRcGKAYLBtAFggUkBcEEXATrA2wD5gJdAtEBRAG8AEQA5P+k/4X/i/+8/w0AbgDoAH8BHAKtAjkDxgNGBLEECAVEBWQFdwV9BV8FGQWxBB8EYQOKAqcBrACi/5v+mv2X/K/7/fpo+tX5XfkZ+fr47vj/+C/5c/nJ+Tv6xvpd+/n7nPxG/ez9gP4G/4v/AABIAGEAcQB5AGQAOwAZAPr/0f+s/4z/Wf8b//P+4v7Q/rn+qP6Z/on+jv6k/rf+zf73/i3/Wv+B/6f/yP/m/wsAKQA/AGAAlQDQAAABMgFqAacB5AEeAk4CdQKXArQCxwLIArEChQJZAjcCAQKoATsBygBMALn/IP+G/uf9Rf2t/Cf8rvs9+936nvqD+nr6e/qZ+tz6MvuM+/H7Z/zo/HT9EP6t/j//yf9MAL8AGQFiAZMBowGWAXQBPAHuAJkARwD5/6D/QP/q/q3+ef5E/iD+If5B/nf+zf5O/+n/lgBgAU4CXAOEBLsF9QYyCHUJswrbC/EMAQ4AD+APpBBOEcsRChISEvARqRE1EYcQqQ+oDpANYAwjC+UJnQhHB/kFxASfA3wCaQF0AJ3/6f5f/vz9uv2g/ar9yP30/S7+bf6b/rP+uP6h/mX+Gf7I/WH9xvzz+/n66/nG+IH3Gvab9BDzgPH1733uJe356wLrO+qi6T3pGeky6Xnp5+l/6kTrMuxL7X3uv+8V8YzyGPSa9fn2QPh5+Zf6h/tG/OD8WP2z/ff9Iv40/jP+MP41/kD+Tv5V/lr+dP6p/u3+N/+Y/xoAtwB4AV8CVwNFBEMFbAabB6kIpAmbCnwLPwzyDJQNFQ6CDvEOTQ9+D44Pjw93DzUP0w5WDsINIA11DMMLBgtCCnkJuAgOCGoHtQb2BUEFkgTiAzwDpwIVAooBIQHZAKAAcwBbAFAATABTAFwAWgBPAEYAPgAtABQA8P/B/4//XP8W/7P+Qf7A/Sj9efzD+wb7P/p0+bj4Dvh89wn3tPZs9jH2DPYJ9i32bfa89iL3qfdT+B75CvoL+xH8Iv1D/lr/UAA0ARYC5QKQAyAEpQQUBWcFpQXOBdgFywWwBXgFGgWfBCMEtQNOA+ECbQIFArUBeQFNATEBHgEMAQ8BNAFqAZ8B3wEzAo0C7gJhA90DRASaBO4ENgVhBXQFbAU8BeIEdATzA1cDpgLqARwBOgBT/2j+dv2E/Jv7vPrq+TX5pPgz+Nv3o/ea98X3Ffh1+OH4ZPn/+af6UvsB/Kz8V/0H/q/+N/+n/xQAagCRAIsAcgBGAP7/nv83/8z+Y/4C/qX9T/0C/cf8ofyT/Jj8ofyv/NT8GP11/eT9Xf7Z/lr/7/+VADcBygFOAsECIAN3A8UD9wMHBAwEHgQxBDAEFATnA7cDgQM9A+UCggIUApgBFQGaACkAu/9S//f+ov5I/u79nP1S/QX9tvxp/Cf8+/vq++n77/sG/Dz8ifzT/BP9T/2O/cz9B/49/mT+fv6g/tf+Ev83/0P/P/8y/x//Cv/q/rj+gP5O/iz+HP4Z/hT+Df4c/k/+lv7a/iT/hv/9/3oA/gCPAT4CDAPnA7gEgAVXBkYHNwgUCd0JngpkCzEM7QyIDQcOeQ7iDj0PhA+mD5QPWw8VD7oOMQ6CDcYM/gsiCzkKSwlLCDoHMgY8BUIEPwNEAmIBnQD+/4f/Kf/Y/p7+iv6L/oz+hv6E/oX+gP5l/jD+7/2g/S/9m/z6+037ffqF+W34MffP9WH0B/O+8XbwOu8d7iPtVuzK63DrM+sZ6zzrmOsS7KbsZO1O7lXva/CW8dnyLfSB9cT27vf8+PD5y/qF+xD8aPyl/Nn8BP0b/ST9KP0p/Sv9Mv1A/U39X/2A/bX9Av5i/tv+cv8sAAgB/QH7AvYD+wQYBkEHTAgoCe0JtwqCCzQMwAwqDXsNuw3pDQEO+w3PDX8NGA2kDBIMWAuQCtYJIQleCJ4H9wZlBtcFTAW9BCYEmAMiA70CWAL7AbIBdwFPAUUBVQFlAWgBbQF7AYcBgQFrAVABNQEVAe8AzACsAIcAWAAmAOj/l/82/8f+R/68/TP9qvwd/Jf7KfvM+nb6L/oD+uX5zfnD+cn51/ns+Rf6W/q7+jn70/t+/Dj9AP7W/rb/lgBcAf8BkQIhA54D/wNPBJoE3AQTBT0FRQUkBegElwQjBJQD+QJWAqwBEQGQABsAsf9g/yv/Bf/p/tv+1v7W/uf+Df8//3f/uf8GAGAA0gBPAbgB/wEwAlICWQJIAiIC4QGBAREBoAAiAJP/A/99/vL9Vf25/Df8wftG+9L6dfo0+g36Bvoi+lX6nvoC+4H7Dvyh/DH9tf0v/qf+Iv+g/x4AlQD7AFUBogHcAf4BDAIHAuoBvgGVAWsBOQEIAd8AuwCbAIUAawBLAD0ASwBWAFIAWABzAI8ApgDGAO0ADAEwAWABiwGpAccB4AHkAdQBxAGvAYYBVAEqAQkB6ADEAJ4AdwBIABEA0v+M/z3/5P6K/jj+4f2C/TH9+fzB/IH8Q/wL/NP7mvtj+y779/rM+rL6qfqy+s367/oc+1n7mvvN+wP8TPyc/Nz8E/1G/X/9w/0O/lH+j/7P/hD/TP+G/7v/2//o//3/HAAwAD4AXQCHALMA7wA6AXwBrwHlASYCaQKsAvECLQNrA8QDLgSWBAUFigUXBqYGPAfWB2cI9giNCSAKowonC7cLSQzZDGIN1w0vDnUOqg7BDrIOfQ4bDoUNzwwPDEgLcwqNCZIIjweVBp4FmgSMA30CbwFuAIz/zv4v/rj9c/1O/Tj9Pf1g/YX9nv2w/bP9mv1r/TL96fyI/BD8gfvm+j36ePmI+Hv3aPZI9Qv0xfKJ8V3wSe9j7qztF+217JvsuOz57Fzt5e2H7kDvFfAB8fjx/PIM9CT1SPZ295D4fvlP+hH7q/sK/DT8P/wv/BL89PvV+7T7ovur+8H71vvt+xr8Y/zE/DH9p/01/uf+uv+kAKgBwwLlA/wEDAYYBxII6wilCUgKzAogC1ILdQuSC5wLkAtzC0kLDAu7ClsK6wltCeMIUgjIB1IH7QaWBlEGJQYJBvMF3QXCBZwFdQVbBTwFCAXGBI8EbgRdBFIEQAQkBAkE8wPSA5YDSAP1AqICUgIHAsMBhQFOASMB/gDSAJQASwD//63/Rf/D/jf+tf0+/dP8dvwm/N/7oPtr+0D7IfsK+/36/PoG+xL7Kftr+9r7Xvzg/Gj9//2d/j//3f9hAMIAEgFbAZEBsQHKAeEB9wENAhsCDgLuAcgBkAE0AcEAVADs/4//Rf8M/9z+wP7I/uH++/4b/0H/Y/+O/83/DAA4AGgAqQDsACkBbAG0Ae4BEwIlAiACDALrAbABVAHrAIcAIgC6/1v//f6b/j/+8P2h/Un9+Pyy/Gn8IPzv++r7Cfw1/GL8ofwF/YX9A/52/ub+Uf+x/xUAgADcAB0BUwGLAb8B3wHnAdwBxgGmAWkBCgGbAC4AwP9T/+j+eP4M/r/9mP19/Vn9Rv1M/Vv9af1+/Zn9uP3u/T3+lf7m/jH/eP/F/xoAYQB+AHkAbQBdADsADQDg/7H/fP9M/x//6P6q/nP+PP4C/s79qP2H/WX9R/0z/S39M/1J/Wz9mf3N/fj9F/42/lr+e/6Q/qP+u/7c/gX/Nv9r/53/yf/6/y0AVQBpAHUAiwCrANAA9AAZAUsBiwHMAf0BGwIyAkkCVwJbAl8CYQJlAm8CdwJyAmECUgJTAl4CawJ1AnkCeAKAAo4CnQKxAtAC/wJCA5gD9ANPBLkEPwXTBVsG2AZXB90HXwjbCFgJ1QlTCscKLQt9C60LuQurC4gLQgvEChYKSwl5CKgH3AYLBiwFPgRKA14CfgGlAMr/Af9Y/sj9Sf3t/Mv81vzv/A79M/1f/ZX90P36/QH+6P28/Xz9Lv3U/GT80/sp+2r6lPmq+LT3qvaM9Wz0W/NU8lrxh/Dm72rvE+/y7gbvR++x7zjw0PB88UPyGfPr88H0qvWf9pH3ffhf+TL67/qL+/n7Ovxe/GL8Rvwb/PL7yPue+4X7hvuQ+5j7pfvI+wb8Wvy7/CT9of06/vP+xv+sAJkBiQKAA4EEfQVlBjMH5Qd6CPkIaAm/CfQJBAr8CewJ2gm8CYgJPwnuCJgIOgjXB3EHBgekBlkGHwbnBbsFsgXOBfQFCwYPBg8GHwY4BkEGMwYjBiUGMQY9BkUGQgYvBhMG8wXKBY0FPQXdBHEECQSmA0AD1AJyAh8CzwFzAQkBjwAKAIX/CP+K/gj+h/0M/Z38Qfz6+8D7jvtq+1H7Ofsg+xD7FPsn+0D7WPuB+877Ovym/Pz8S/2s/Rz+hP7T/gf/Lf9I/2D/dP+K/53/p/+p/6//tf+v/5H/Xv8k//P+zP6l/nj+VP5J/lL+Y/59/qj+4/4m/2P/lv/J/wYATQCUANsAKAF4AcoBHAJjApUCsQLAArwCnQJrAjMC+gG8AXoBLgHaAH8AIwDD/2b/FP/I/n3+Of4H/uT9z/3Q/ev9G/5c/qn++f5I/6H//f9QAJcA3QAlAWUBmAHBAdsB4QHQAacBcQE7AfoAlAANAIb/DP+V/hD+iv0U/b38g/xP/Bf87/vq+/77Fvws/EX8avym/Pr8Uv2p/QL+X/61/vz+Nv9f/3z/kP+Q/2z/Mf/8/tr+tv6D/j7+9f2//aH9fv1G/Qz95fzR/Mb8w/zJ/Nr8BP1F/Y793P0x/oX+zP4R/1v/ov/e/xcARwBqAIwAtwDlABUBRQFvAYQBkgGmAb4B0wHqAf4BDQIdAjwCYwKIArEC1wLwAgEDEgMYAxEDCgMFA/sC7wLnAtsCxgKwApwCgAJgAkQCKAIGAvAB7AHpAeIB4wH1ARwCXQKmAuECGgNyA+kDXwTLBDIFoQUkBrcGPQegB/MHUwjACCYJdAmfCacJnwmRCWcJDQmPCP0HXwe8BhoGbgWxBPcDSAOdAvQBTAGiAPr/aP/x/oz+Pf4U/gz+Gv44/l7+hP6n/sf+2f7U/sH+of5k/gz+qv1E/c38PvyT+836/Pkn+Tn4JfcH9gD1DfQh80Tyi/EC8a3wffBc8FrwkvD68G/x6PFy8hHzvfN59EL1DPbU9pv3WfgL+bv5XvrV+hr7QvtV+0/7NfsL+9P6lfpn+kn6M/oq+jb6UPp/+s36N/un+xj8m/xA/Q/+Av8GAAwBGAI4A1oEZQVRBh8H2QeDCBoJjwnVCfoJFQosCjQKGgraCYgJOgnwCI8IGgilB0MH7waiBlwGKQYSBhkGMgZYBpEG0QYJBzoHeQfBB/oHGgguCEAIUgheCFoIQQgeCPUHsQdOB9oGXQbPBTMFmAQDBG4D4AJXAsgBNAGqACgAo/8e/5v+Fv6Z/TX95PyP/Dv8/PvV+7f7mvt4+1b7R/tO+1L7Qfsx+zf7Tftr+4/7uPvi+xL8TvyR/NT8C/0v/UT9Xf16/Yz9mP2s/cv95P31/Qf+I/5C/lL+SP45/kD+V/5k/mr+hf67/vr+Of92/7b/BABfALIA8AAlAVkBhgG3AfUBMgJdAoACqwLOAuAC5wLbArECfQJLAhMC0wGZAWABGQHLAIsAVAAcAOv/wf+P/2D/Rf84/yr/Kv9A/1v/df+f/9n/EgBIAHsAoAC/AOMABAEPAQ0BCAH1ANAAowB1AD8A/P+t/0z/3v51/hH+p/05/dP8ffw5/Ar83/uz+5z7pPu7+8/74/sB/Cr8Zvyr/Ov8KP1x/b/9AP44/mv+jf6i/rP+tv6g/oP+c/5i/kH+Gv7z/cj9p/2c/Zb9iP16/XL9af1u/ZT9xf3y/S3+hf7n/kf/s/8kAIgA5ABAAZMB1gETAkYCcwKnAt8CAQMHAxADJwM1Ay8DHgMRAwoDBQP9Au4C6wL5Ag0DFwMcAx8DJAM1A08DXwNYA0cDNgMrAyQDFgP8AuACygKtAoACUQIpAv4BzAGXAV4BIQH1AN4A0QDHAMUAwwDFAOAAHQFhAZ8B4gE3ApoCCwOBA+YDPgSkBBkFiAXyBV8GywYnB3sHzgcSCDEIKQj3B6UHSQfjBmMG0AVABbUEIwSKA/ICVwK4ARwBigACAH3/Af+e/mf+Wf5j/nn+ov7g/ij/Zv+L/5P/hP9s/0v/Hv/i/oj+Df6F/fz8Yvyf+7760vnV+Mf3sPaZ9Yv0nPPU8i/ytvF18V/xXvFw8aTx8fFT8s/yZfMF9K30ZfUf9tT2j/dP+P34gvnm+S/6ZfqL+pr6i/pn+kX6K/oN+u752fnF+bH5p/nA+QT6afrd+lb73vuD/Eb9H/4I//r/8ADpAd4CyQOxBJgFeQZHB/0HlAgJCWAJmwm1CaoJiwlnCT0JFAn0CNMIqAh5CE8IGQjVB5UHZAdABywHKgczB0gHdAewB+kHHghOCGcIXwhOCEQINggWCPIH1ge8B5QHVgf7BosGDAZ7BdUELASMA+wCRQKnASABpwAoAKT/H/+W/gL+ZP3Q/Fn8+Pug+037CfvX+rH6j/pw+l36Wvpa+lf6Wfpz+qH60fr9+ir7XfuZ+977HfxJ/Gv8l/zH/PH8Fv01/UL9T/1q/Y/9rP3D/dn96f30/Q3+L/5S/nj+o/7L/uv+F/9g/7n/EABmALYAAAFNAaAB7gEyAnUCuALzAiIDSwNpA3IDcgNzA20DUwMuAwQD2AKlAnICRAIUAuUBuAGEAUEB+QC4AIUAWwA3ABgA/f/w//n/BgALAA8AGgAkACYALQA5AD4APgBEAEoARAA0ACUAEgDz/8f/lf9i/y//9v6v/mL+Hf7c/ZD9OP3t/LX8hvxW/Cr8D/wH/An8DfwQ/Bj8K/xJ/HP8oPzS/Af9Ov1m/Zj91P0J/in+QP5b/m3+af5X/kT+Mf4j/hn+C/79/ff97f3W/cX90P3p/fv9EP46/nH+tP4M/3P/1/86AJ8A/ABQAa0BEQJrAroCAQM0A0sDWgNpA28DaQNbAzsDCgPYArAChQJWAiwCBwLjAccBtgGoAZsBmAGqAcwB9AEVAjECVQJ/ApwCqQKwArgCvAK3AqgCigJhAjAC8gGmAVkBDgG5AFsACADF/4n/Vv8p//n+zv7E/tL+3f7r/hb/Zf/P/1AA3ABoAfsBlgIqA7ADQQTiBHwFDQajBjsHwgc2CJsI4wgHCQUJ3AiWCEUI4wdhB80GQwbFBUIFuAQrBJgDAQNwAuUBXAHnAIsASAAhABAABgAEAB4ASwBsAHkAhACLAIEAbQBLAAcAoP8t/7H+HP5n/ZH8mfuW+qL5rPil96D2qPWt9Lzz8vJN8q3xIfHL8Kbwm/Cy8PDwTfHJ8Vby4vJy8xn0x/Rb9eT1hfYt98X3Vfjc+ET5h/m1+dX55Pns+en50vmz+av5t/nL+e/5Jvpg+qj6FPuf+zX83fyY/Vf+Hv8BAPcA6gHkAugD4gTKBa0GhQc7CM8ISwmnCekJIQpKCk8KOwomCggK2wmsCXsJOQnzCLoIggg+CAkI+gf8BwYIIQhUCI0Ixgj3CB0JPwlkCYAJjQmVCZ4JkgltCUMJFwnTCGsI6AdTB7EGAwZJBYEEugP+Ak0CoQHwADsAjf/2/nH+5/1X/df8cfwl/Or7ufuF+0z7GPv2+uD6yPqq+or6efp++or6ivqE+n/6gfqI+pT6nPqY+pD6mfq2+tf69voW+zz7YfuE+6f7y/vs+wz8Nvxw/Lf8Af1L/Zj96P0+/pP+4f4q/3L/uv8IAGEAvQAIAUkBlAHnATICcgKoAsoC2QLoAv8CDgMSAxgDJAMsAykDFgP0AtMCwwK8Aq4CqQKvAqkCiQJjAj8CCwLHAY4BcAFcAUMBHgH0AN0A2QDEAIsARwAcAAkA+f/m/9D/tv+e/5H/hv97/2r/R/8P/9H+of55/k/+G/7g/ab9c/04/eP8gfw1/AP81Puk+377a/tj+2D7X/tv+5772fv8+wz8Mvxw/Kr84/ws/Xz9v/3y/R3+PP5R/mX+av5k/mj+e/6K/pP+oP6u/rL+tv7C/sn+zf7k/hL/RP98/8b/GwBzANQAQgGtAQkCWQKbAs8C/gIuA1kDeAOJA40DiAN+A2UDMQPrAqoCdwI9AvUBqAFrAUUBNQEsASUBHgEcASEBMQFKAV4BbwGGAaIBxwH3ASUCLgITAvsB9AHmAbkBdwE0AfMAqwBVAPr/rP9w/y7/5/6x/pP+dP5L/i7+Lf5B/mv+sv4N/3P/4f9XANoAdwErAt8ChgMrBNUEfAUbBrsGWwfyB3wI/AhwCdYJIwpECj0KKQoLCtMJdAnzCFkItwcbB4UG6QVHBaAE8gNEA64CLAKsAS8BxQBxADkAKwAxAC4AKQA7AFYAWwBUAE0APAAVANL/bf/k/kb+lP23/MT71vrZ+bD4efdl9mL1T/Q/80jyafGh8PjvcO8L79Xuz+7s7jjvwO9l8ArxvfGF8kfz/vO79HT1E/an9kL31fdO+Ln4FPlO+WT5aflt+XL5c/li+Ub5S/mC+c/5G/p4+u76efsm/AD97/3d/tj/7AAPAjkDYQR3BXUGawdVCCYJ3gmMCh4LigvaCxYMKwwbDPULvQt2CzEL8QqgCkAK7wmtCWkJKQn5CNMIrwiVCIgIgQiICJ8IuwjSCOwIBgkKCewIuQh9CEMIEAjVB4IHGQeoBjAGqQURBWsEtgP6AkECjgHeACoAdP/B/hj+gf35/Hz8/vt5+//6n/pR+gj6zPmk+YH5Wvk5+Sr5Jvkt+UH5YPmG+bX57fkr+nL6u/r1+iT7X/uo++z7IvxP/HX8nfzX/B79YP2X/c79Bf45/m/+rf7t/i7/cf+3/w0AfAD6AGsBygEoAooC7AJEA4gDuAPmAxgEOAQ9BDgEOQQ2BCYEAgTHA34DNQPuAp0CSQIEAssBlwFuAVYBQwEtARgBDAENARYBDgHnAMAAtwC7AKwAigBmAD0ACwDc/6z/a/8V/7n+Y/4Q/r39cP0x/f/8y/yN/Fj8Pfwv/Bf8/fv3+wX8Hfw6/Fr8ePyR/Kn8wfzc/Pn8Ef0o/T79Uv1d/Wf9dv2H/ZD9jv2C/XX9df2L/Z/9ov2k/bb90P3m/fr9EP4f/in+N/5Q/nP+lP6y/tH+/v43/2X/h/+s/9f/AAAmAFcAjgDEAAEBSgGSAc0BAQI4AnMCqgLQAuAC7QIGAyADIAMJA/YC7wLkAsoCowJtAioC6AG0AY0BaQFCARsBAwEHARcBIQE3AWQBlQG5AdwBAgIYAhwCKAI/AkgCPwIwAiICCgLkAaMBSwH1AKYASwDb/23/Cf+o/lj+Iv7y/b/9pP2h/Zr9j/2h/cj97v0g/mj+tf4G/3L/7P9aAMQANgGkARYCnAIlA5oDFwSrBC0FiwX0BXgG/AZ9BwcIiwgCCYUJBApQCnUKmgquCpUKaAowCs0JSwnXCGcI2wc5B48GygX9BEsEngPVAg8CbwHlAG8AJQDt/6f/dv93/3f/Tf8d/wL/4P6v/nv+J/6j/Q/9c/yy+9H67Pnr+Mf3ovaN9WT0MfMc8h/xH/Az73Xuz+1H7QPt+ewJ7Untze127ijv8+/S8KrxffJc8zX0/fTJ9ZP2Rffo94j4AflC+Xn5ufno+fv5DPoe+if6Q/qF+tj6Nvuy+078/vzK/bT+qv+uANQBDAM3BF4Fjga0B78ItwmfCmkLGwy/DEINmQ3TDfUN+Q3bDaoNYA3/DJwMQwzlC4QLNwv7CroKbQojCuEJrgmRCYUJeAliCUIJGQn7CPEI4QiqCFgIDAjEB2YH7QZoBtgFOQWZBPgDSgOKAsMBAQE9AHf/rv7t/UD9qPwU/Hn75Ppe+tv5Xfnz+Jv4Sfj/99H3sfeQ93H3Y/dn93n3lve39973Fvhk+Ln4E/l6+eb5Rfqc+vn6X/vI+y38j/zx/Fn9yf01/pT+8/5N/5j/3v80AJkA/QBbAbkBHQKJAvsCbQPWAzAEfQTBBAQFSAWBBawF0gX2BRAGFQYIBuwFwwWTBVYFDQW7BGYECASoA08D/QKpAlUCDwLYAaUBcgE8AQ8B+ADmAMYAmgB4AF8AOgANAOL/rf9q/yj/8/6z/l3++f2Q/SX9w/xl/AX8qvtX+wn7xvqY+nv6W/pA+j76SfpR+l/6hPqz+uL6GPtY+5b70fsI/Df8XPyD/Kn8w/zT/OX8AP0d/Tb9TP1j/Xz9lP2e/Zz9of24/db99/0h/lT+h/65/u/+Mv97/8L/AQA/AH8AvQD1ACMBTgGIAdEBFgJPAoYCxwIJA0MDegOwA9oD9wMSBC0EQwRPBEsEQAQ5BDUEJwQKBOQDtQN6Az0DAwO9AmMCEALQAZABSgELAeEAwwCrAJcAhgB3AG0AaABkAF8AVwBIADkAMwAtABsAAwDv/9f/tv+J/0f/8f6b/lH+CP60/WL9Hv3n/L/8qPyd/Jr8o/y4/NL87vwE/RX9PP2E/dP9Ev5V/q3+Ef96/+j/UwC2ACIBnAEYApACEAObAy8E1gSNBTkG0wZ0ByUI2giOCTUKxQpNC+ILbAy+DNkM1QyzDHQMKAzJCzsLhgrMCQ0JPAheB38GlwWsBNEDBQM+AoUB5wBlAAMAwP+I/1L/Of88/zD//v6//of+SP72/Y79Bv1W/I77tfrB+a74iPdT9hL10vOa8mnxQfAq7yvuTe2Y7AfsmOtb61zrk+vt623sGe3u7eLu5O/p8Ovx6PLa87P0dfUq9t32kPcy+LX4Hfl5+cv5B/o4+m36nPrG+gH7XvvU+178Bv3M/ab+lP+bALUB4AIhBGcFmga6B9EI4QnoCuELtwxmDQQOng4YD1wPeQ98D2UPOw8ID8IOWg7oDYgNNw3nDJUMQgzqC50LawtDCxALzwqMCk8KFQrVCYEJHAm5CFsI8Qd3B/MGZwbOBSsFhATLAwADNQJ2Ab0A/f89/3/+w/0R/XD83ftP+8T6QfrH+VD52fho+Pz3l/c79+v2p/Zr9jT2BPbg9dD11/Xv9Rf2TPaH9sn2GfeA9/D3Y/jj+HX5Dvqn+kP72/tl/O78fv0G/n/+9/55//v/cgDhAE0BtAEdAooC9wJjA88DNgSYBP8EbAXTBS8GhgbXBhkHTgd4B5EHmgeeB5gHeAdGBxUH5gajBkUG1AVcBeYEcgT9A4gDFwOwAlUCDQLPAZUBWwEiAe4AwgCbAHMARQAVAOn/uf93/x//v/5e/gD+m/0k/aX8Lvy++0n72fp2+hj6vPlx+Tz5Dvnt+OH43vjX+N/4A/k0+Wn5rPn++Uv6kfrW+hX7SPt2+577t/vQ+/r7KPxU/Ij8xfz0/BL9Lv1G/V39iv3K/QP+Mv53/tb+OP+f/wwAbgC6AAcBYwG/ARUCYgKgAtICFANiA6EDxwPrAxMEOQRjBJEEtgTRBPEEEQUeBSMFKgUpBRMF/ATrBNYEuASYBHkEUQQfBOUDnwNNA+4CgQISArIBXQEFAaoAVQAMANL/pf96/0T/DP/i/sH+nf52/lL+Lf4F/ub90v27/ZT9Y/0y/Qv95/y//JD8Yfwy/AP82Puz+5L7ePtr+237ffuW+7v75/sd/GH8r/zz/Cv9Y/2q/Qb+cv7n/lz/1f9XAOMAcwEKAqwCUgP9A7IEcAUsBuUGqQd8CFUJLAr6CrYLXQz1DIgNCQ5iDowOlQ6CDk8O8w1tDbsM7QsdC08KdwmQCKMHuQbQBesEDgQ8A3cCygE6AccAawAcAN7/xP/P/9n/wv+L/0f/9v6S/hb+eP2z/Nj77/rk+bD4afcV9q70QvPp8aLwYe847jjtWOyW6/zqi+pO6lrqrOoc65zrTOw57UPuU+9k8GfxWfJG8y/0//Sw9U724PZh99T3OfiE+Lf45/gY+UT5a/mX+dT5Mfq/+nD7OPwd/SL+Ov9lALIBGQOABOMFSAejCOkJIwtRDF4NPA7yDocP+g9WEJoQvhC9EKMQdxA2EN8Peg8SD6YONg7FDV8NCg3CDH0MPwwLDNkLpAtlCxsL0AqFCjMK0AljCfIIcgjVBy4HiwboBTwFggS1A9gC/QEvAWUAmP/P/g3+S/2P/Nj7Iftq+r75Jvmb+BH4fffl9mD2+/Wh9Tv10/R89D70HfQd9C/0QfRd9Jn06PRC9bP1OvbE9lD37/eg+Ff5FPrT+nr7CPyU/Cn9tv00/qL+BP9q/+H/WwDJACsBjgHuAVMCxwJEA8EDRgTWBG8FDQatBkIHwAc0CKII9ggxCWkJmAmsCaUJjAlZCQUJpAg2CLUHKwemBhgGdQXUBEkExQNBA80CbQIZAs4BigFJAQsB3QCxAHsAPwAGAMj/gf8w/9L+X/7k/WX92vxI/Lv7MPuZ+gL6d/n1+Hz4JPjt98P3oPeN94b3h/eZ98L38fco+HX40/gs+X/51/ky+oP6yPoC+zD7WPuG+7H7zfvh+/z7JPxW/Iz8wfz7/D79jv3k/T3+lf7t/k3/u/82ALIALAGjARECdwLZAjUDhwPWAykEcwSlBMYE5gQLBS4FSgVfBXMFiQWpBckF4AXpBewF9gUDBgsGCAb0Bc4FogWCBWYFOQX2BKoEXQQHBKkDRgPUAlQC2QFpAfYAfwAVAL7/b/8n/+z+t/6C/lT+Lf4H/uP9xf2s/Y79bv1N/Sz9Bf3X/J78X/wg/Nr7ivtB+wz73fqo+nb6U/o7+jT6Rfpg+oD6sPr1+kb7ofsF/Gb8v/wg/ZT9Cv56/ur+YP/Y/1wA6QBwAfABeQIMA54DNgTdBIkFKAbIBnsHRwgnCQsK3QqbC1cMFg3IDWUO3w4nDz8PNw8RD78ORg6zDf4MKQxIC2YKcwlxCHUHdQZnBWIEgwO7AvwBWgHeAHMAFADQ/6L/ef9c/0n/Kf/m/or+Hv6c/QP9Sfxg+0/6LfkE+Mb2aPX184LyKPHu78ruqO2Y7LbrDeuU6kjqLOo96nvq5+p86zrsI+0l7ibvJ/Ax8T3yMvMJ9M/0hfUk9qr2Gfd598/3I/h0+MH4Evlx+df5Pfqu+jz74fuc/Hr9iP63//AAOQKkAyIFkAbbBw4JNApTC2YMXw0rDsgOTQ/CDxsQThBkEGEQQhAWEOoPtQ9lDwEPow5HDt4NdQ0nDe8MugyCDE8MFwzPC4gLSgsBC5wKIgqfCQ8JegjlB0YHjQbABfAEIwRYA4wCuAHeABIAW/+v/gP+V/2p/PX7Sfuw+iD6jfn++H74C/iY9x/3o/Yy9tL1dfUS9bv0ffRL9B/0DvQh9Ev0hfTe9Ej1ufU89tv2gvcr+On4tfl2+iv76/uw/GX9CP6d/iP/mf8FAGIAswAMAW4BwwEPAmcCxQIUA2EDvAMdBIIE9AR1BfYFdQb5BnsH8gdfCLwI+QghCUQJXQleCUwJJAncCIIIJQizBx4HgAbrBUsFoQQGBIMDBAOEAhkCvwFlAQ8BvwBzACoA6v+u/3f/UP8o/+n+m/5Y/g3+oP0l/bX8Qvy5+y/7tfo9+sT5VPnv+I34M/js97H3gPdl92X3c/eF96n35/cy+Hz4yvgj+YH51fkm+nn6zfoZ+2X7tfv9+zf8Z/yS/Lb83vwW/Vr9lv3H/fz9Rv6i/gH/VP+j/wMAbgDYAD0BqwEkAqQCIQOUA/YDTwStBAEFPwVzBa4F5QUPBjkGbQaaBrIGwQbKBsYGwAbFBskGuQaYBnkGXwY+Bg0GzAWABS0F0wRtBAQEoAMxA68CJwKsATUBsQAkAKH/LP+7/kz+7f2j/WP9Kf31/Mz8rPyT/Hz8YvxI/Df8KPwJ/Nv7rvuI+2L7Pvsf+/j6t/pm+iH68vnU+b/5s/mx+b/54fkX+l76svoH+1r7wPtA/Mr8Tv3V/WL+7f6D/y4AywBKAdcBjQI+A88DZgQhBdsFgQYyB/AHmwg+CfgJvwpzCx0Mzwx+DRgOng4ND1kPgw+JD2QPHw/EDkcOmQ3WDBwMUQtgCmAJZghoB2cGdwWSBKsD2QIzAqABCgGPADoA7/+c/1n/J//q/pX+Mv7A/TT9iPy6+8z6yvm0+H73L/bl9KLzUfL48Lrvmu6F7YbstesU65PqMuoG6hzqY+rE6kDr8evW7Mztt+6n76fwpPGP8mvzO/T09Jb1J/am9hf3hPfp9zn4hfjj+FD5uPki+qD6Nvvk+638kf2M/qH/0wAaAmsDygQxBpIH3AgQCjQLRgw6DQAOow41D7UPGxBoEJsQqRCVEHUQThAHEKQPQg/oDogOKg7kDaENSA3sDKoMcAwjDNMLkAtLC/EKkQotCrsJOwmxCBkIbge4BvwFNwVqBJoDzwIFAj8BeAC0//b+Pv6C/br88vtA+6P6B/po+dz4X/je91v36PaG9iT2uvVW9f70r/Rt9EP0OfRG9Fv0efSr9Pv0bPXs9W72//aw93H4KPnV+Yn6RvsD/L/8cP0H/pH+G/+g/w4AZQC4AAsBVQGcAecBMAJyArkCFwODA+sDXQTmBHIF8AVvBvcGdgflB1AIswj4CCMJUAl5CYYJdAlRCRsJwghQCNUHSgejBu4FPQWLBNsDPgO0AjUCwQFWAe0AjABFAAoAzv+Y/2j/Of8G/9f+qv51/jf+9P2u/WT9CP2R/Az8jfsQ+4v6BPqE+Qb5jvg7+Af4x/d190z3Wvds93f3p/fw9yT4YvjT+Ef5jvnm+Xb68/ot+3b79Ptb/Ib8tvwM/U39X/17/cD9BP4o/kX+eP6+/gn/TP+B/73/GwCKAOkAQwG0ATQCqgIWA34D5ANIBKcE+gQ9BX0FvwX8BSQGQAZnBpIGmAZ/BnUGgAZ0Bk4GNAYgBvYFuQWBBUYF+gSqBGIEEwStA0MD5wKTAjMCywFpAQoBpQA5AMn/W//0/pf+P/7y/bD9cP02/Q395/zA/KD8hfxQ/Av83/vF+6H7ffts+137PfsY+/X6z/qn+on6dPpk+mD6Z/p1+on6rvrf+hL7R/uO+977IPxk/MH8Kv2I/ej9Wv7J/i//nP8XAIkA8wBiAeIBcAIJA6sDVgQABaMFSwYPB9cHigg7CQAKzwqZC2UMJQ29DTMOpQ4RD1cPYg9EDxIPxA5LDq4NAg1DDG4LiQqdCaQIoAeSBo8FqATZAwwDQAKMAfYAfAAeAMn/df81/xD/4/6R/i7+z/1n/eL8Ofxn+4D6l/mp+Jn3YfYd9enzx/Kd8XDwV+9g7oTtw+wg7KDrTusy6z3raOu76zbsyex+7WXuaO9c8DjxE/L/8ufzrvRT9e31gPYQ96r3Q/jB+Db5wPlP+sv6Rvvd+3n8Ev3E/ZT+bf9UAFwBewKeA8UE8gUZBzIIRglMCigL5AujDFsN4A0+DqYOCQ8yDzEPOw9GDy0P9g6+DokOUQ4SDtUNlw1XDQ8NxwyHDEUM/wvJC48LMgvACmAKAgp9CdcINQiTB9oGCwZABYEEvAPtAiUCZwGoAO//QP+V/uv9Uf3B/C78nfsZ+576L/rM+Wn5/viX+Db42Pd79xj3ofYq9sz1gvU39fD0ufSW9I30ofTR9CD1jfUB9mr23PZx9yT45fiq+W76Lvvy+8b8nP1V/uj+cP/7/3EA1QA/AaQB5gEeAnEC1AIjA2QDqAP0A0kEowT3BEoFrQUpBrUGPweoB/EHOAiHCL0IyAi7CLAIogiJCF0IJAjbB3UH8wZjBtMFQgWqBAgEbAPqAoQCIwK+AWMBDQG3AGwAKQDY/3//O/8G/8T+gv5L/gf+p/02/b/8QPy5+zD7qPon+qv5OPnU+H74M/j599T3uPed94b3f/eT98X3DPha+LT4GfmA+eH5OPqL+uv6Vvuy+/H7Lfx0/Lf87Pwf/VP9f/2h/bz94P0Y/ln+lv7b/jX/lP/y/1YAugAWAX0B+gF0AtYCMwOdAwkEZgS5BBIFZwWoBdoFDgY4Bk8GYwaBBpgGmgaTBogGeAZtBmIGRQYdBvEFwAWIBVQFFwXIBG8EEwS1A1kD/gKTAhYCngE6AdcAZQDl/2j/7/52/gr+vP1+/TT95/yr/Hr8Svwp/A784Pui+3n7bfth+0r7M/sr+yz7JPsT+wD76frK+rH6o/qN+m76Yvpz+pL6tfrV+vb6Ifta+5L7y/sZ/Hj81/w8/bL9K/6S/vj+dv8BAIIAAAGSATUC3AKKAz4E3QRuBR0G7AalB0QI6gidCUEK4QqGCx8MqQwzDbMNFg5eDo8Onw6MDlwOFw6+DUkNtQwHDFULoQrbCQEJIQhNB4IGtAXgBBMEUQOeAgECcwHnAGEA8v+W/0H/8f6h/kH+yf1A/a78E/xj+4r6jfmO+Jj3nPaU9Yv0ffNr8l/xXvBu75/u7e1B7avsTewf7P/r9usc7Gns1Oxh7Qvuue5y70rwMvH/8bbye/NE9Or0ffUh9tH2cvcG+Jz4L/nB+Vr68fqF+yf81Px1/RT+zP6g/4QAdwF4An4DjQSlBbcGtwenCIsJZwpACw4MxwxhDd4NSQ60DhwPaw+WD7APwQ/BD6cPfA9LDxsP4w6ZDkMO6w2cDVAN9AyBDAwMows3C7sKOAqzCSUJjgjtBz0HgwbVBSkFcwS5AwQDTAKVAecAPACJ/9n+OP6b/fv8XfzG+y77lvoN+pL5Dfl0+OH3Zvf89pb2NPbV9Xz1NfX/9Mf0i/Rl9F30ZvSE9MP0GPV49e31e/YZ98L3dvgs+dX5dPoe+937l/w9/dj9bf70/mz/3P9FAJ8A6gAtAXcBzAEgAnACyQIvA5AD8gNnBOcEYQXgBXYGDQeLBwAIdwjrCFEJpAnTCdwJygmxCZEJXwkQCaIIIQiaBwUHYQa6BRMFZQS2Ax0DoAImArEBUQEBAa8AawBCABMAyv+E/07/Ff/U/pv+Yf4O/rX9YP3//IT8+/tq+876OPqr+Rj5iPgS+LP3XvcZ9+n2vPaT9ob2lfal9rj27/ZN97v3KfiY+P34XvnK+T36nvru+j37kfvj+zP8f/zH/Bn9c/3F/Q3+Xv6y/vz+RP+Y//D/SQCzAC0BogETAo4CCwN4A9oDRASqBP8ESgWcBfQFSQaVBtYGBQclB0kHdAeWB6EHngefB6MHmAd6B1YHNgcSB+UGrwZoBggGmwU0BcwEVQTbA20DBAOLAgcCjgEbAZ8AFwCR/wz/if4W/r79cP0a/cr8jvxb/CH85/uy+3v7P/sH+9n6sPqH+lv6LvoG+u354PnX+c35u/mf+Yr5hvmH+YH5gvmX+br54fkZ+mL6r/r8+k77ovv3+1X8xvxH/c79U/7T/lb/5P93AAcBnAE7AtoCewMzBPoEtgVpBioH9gexCFoJ/wmZCh4LngsoDLIMKw2RDegNKg5VDnEOfA5nDigOyg1nDQYNmgwODGsLwAoWCm4JyQgfCGQHmQbLBQUFTgSjAwQDaQLPATUBoAAWAJH/BP9o/sb9Gv1j/KP75/oq+l/5gviW96f2tvXE9NLz4/L38Q/xO/CG7+TuQu6t7Tnt4eya7HPsceyD7KPs6Oxb7eTteO4k79/vkPA48e7xr/Jn8xn0z/SM9U72EPfO9434T/kG+rP6Yvsb/NH8gv09/vv+uP+CAGQBSQIgA/0D7ATcBcEGoAd6CEMJAwrHCoQLNAzZDGwN6A1ODrQOFw9nD58PvQ/HD8gPxg+xD30PPA/7DrAOUw7rDX0NCQ2ODA8MhgvzCmMK1gk7CZAI3gcxB4gG4QU8BZcE8gNSA7ICCgJjAccAJQB5/9D+N/6f/QT9bfzT+yb7dvra+Ur5sfgY+JD3EfeT9iX2yPVp9Qv1vfSA9E/0O/RI9GD0dvSf9Or0RfWk9RL2kvYW95r3J/i/+GP5Dfqv+kf72/tr/Pj8i/0c/pj+A/9//wgAhgAAAYoBFwKRAg4DnwMpBJsEEAWVBRcGlgYlB7EHIgiACN8ILgliCYsJrgm5CbIJnwl6CUAJBAnLCIcINgjYB2sH9AaIBhwGoAUiBbgEVgTqA4MDJwPDAlAC5AF/AQ8BlAAbAKT/Kv+y/jj+uP01/bP8Kvye+xr7nPof+qX5MPm7+Ez4+ffH9573cfdE9xr3//YC9xn3LPc+92b3qPfs9yf4YPif+Oj4OvmM+dH5Efpg+rv6FPtj+7X7Efxy/ND8Kf2F/eT9P/6Y/vj+ZP/a/04AtgAYAX0B6QFZAsoCPgOvAxcEfgTkBDoFfgXGBRsGbAawBuwGHQc/B1oHeAeSB6YHtAezB5wHeQdWBywH8AaoBmAGFAa/BV0F8QSMBCsEuAMuA58CGAKUARUBoAAnAJ//IP+4/lH+3v10/R39x/xz/Db8CfzW+5/7cftG+x379vrN+qT6iPp1+lb6LPoM+vj53fm/+aD5fPlb+VL5YPlp+Wr5gfmv+eP5G/pe+qv6Bftu+9/7TvzD/En91v1e/uT+dv8VALcAUAHkAYQCLwPVA3sEMwXtBY0GIAfBB24IDQmfCS8Ktgo4C8ILTQy7DA0NWg2hDdAN6g36DfINyg2ODUkN9QyLDA8MgQvjCjYKgQnECAUISQeSBtoFHAVbBKQD+wJSAqYBDQGRABoAlP8N/5H+E/6F/e/8Vfy0+wn7Tvp7+Zj4uPfa9vL1BPUa9DTzUPJw8ZPwv+8C72Xu1u1J7djsm+yH7IDsguyg7O7sbu0F7pXuJO/N75TwZ/E08vryuvN59Dn1/PW/9oL3QPj1+KX5V/r/+pj7LfzL/Gz9Bv6d/jn/6P+uAIUBWwIuAxgEFQUPBvQGxQeOCFgJJQrpCp8LVQwQDbkNPw60Dh8Pbg+jD9cPCRAgEBQQ+g/bD7APeQ84D+kOjA4nDsENUA3RDEoMyAtOC84KOwqcCfcIVgjABzEHlgbdBR8FeATbAzEDggLbATEBfgDT/yz/dv62/Qj9afy++wf7XPrC+S35m/gP+Ir3Dveb9jL20vV59SL10/SQ9GL0RvQ+9Ev0ZvSO9Mr0HfV09cj1JPaX9hv3o/cm+Kn4Pvns+aP6Svvm+4L8G/2o/Sr+rv44/8v/XQDnAGoB8AFuAt0CRwO2AyIEhATpBFgFwgUkBo0G/gZlB7kH/gc0CFsIdgiHCI0IjAiOCIoIfAhlCEQIEAjIB3cHJAfLBmcG+gWKBSIFxARoBAQEkgMSA5MCHwKrASIBjQAEAI7/E/+U/iD+uP1M/dn8XfzW+1P73/p4+hb6xvmH+Uv5DPna+K34d/hF+Cv4HvgK+Pr3B/gm+EL4W/h7+KH4xfjq+Br5Tvl3+Zn5yPkP+lv6m/ri+j37nPv0+038p/z//Gf96/13/vb+af/d/0wAuAAtAbABMgKsAhYDdAPYA0oEtgQIBU4FlgXdBR0GVwaNBrkG4wYNBycHNAdHB1wHYwdbB00HNgcVB/MG0QafBlgGCwa8BWYFCAWkBD0E1gNqA/ACcALzAXAB5wBhAOr/dP8D/5v+OP7X/Yz9Wv0n/er8svyC/En8Dvzi+737lPtu+1P7MfsI++b6y/qn+nr6S/oc+vH51PnE+bH5mPmB+Xv5kvm/+er5D/pD+oP6vfr3+kn7svse/If89Pxt/fj9jP4X/5v/LgDLAFsB5gGGAjoD6QOXBE0FAQaoBkoH6weDCBgJtAlPCt4KZwvpC1kMuQwRDVQNeA2FDYINbw1LDRANuQxNDNQLUwvICjwKqQn8CDsIggfWBh4GXAWlBAQEawPVAj4CrgEsAboATgDj/3X//P5y/uL9Vv3A/Bf8ZPup+uD5FvlW+Iv3pPa59eX0FfQr8zbyXvGw8BTwd+/g7mfuEu7T7Z7tge2M7b3tBO5b7snuTu/j737wGPGz8VTy//Kv82P0FfXC9XT2LPfi95T4Qvns+YP6CfuQ+yH8r/xB/eP9kf5F/wkA6gDYAa8CcwM+BBUF6QWxBnMHNgjyCKcJWgoGC6QLMQyxDC4Nnw31DTIObw6wDt8O8Q76DgoPEA/8DtIOpw58DkYO+w2gDUAN2gxpDOcLVwvACiQKgwncCDMIjgfvBkUGkAXgBD4EmAPlAjkCoQEPAXAAxv8d/4H++f16/fH8XPzG+zv7ufpG+tz5bvn9+JD4KPjA92T3GffU9on2SPYd9vz13fXM9dX18vUe9lb2nvb19lT3uPco+Kj4Kvmm+Sn6vfpW+/D7i/wi/a79Nv7C/lH/2f9XAMUAKgGSAfoBVAKkAv0CVwOhA+UDNgSMBNMEDQVOBZQF0gX7BREGJAZCBmoGhgaOBpAGlAaWBo4GdQZJBg4GzwWPBU8FCQW3BFsEAASqA08D6wKFAhsCqQE1AccAUQDS/1X/4f5w/gD+l/0x/cn8Y/wH/LT7bPsu+/H6svp/+lv6OvoW+vn54/nM+bn5rvmp+aT5ovmj+aj5sPm++dX58vkK+h36Ofpg+oj6r/rn+jD7dfup++f7Qfys/Bf9f/3l/Uj+q/4L/2v/1/9NALwAIQGDAeYBRwKuAhcDcwO2A/IDOgSABKwEwgThBA4FNQVNBWIFgQWgBa0FrwW7Bc0F1gXZBdcFzgXDBbsFqwWKBWQFQAUWBeIEpARYBP8DnwM6A80CYgIDAqsBSAHTAFkA5P93/xz/zP51/hj+xv2B/Uv9I/34/ML8jvxk/ED8J/wS/PP71vvG+7j7nPuB+3X7a/tY+0X7PPsx+yT7LPtN+2r7d/uE+5v7wfv0+xr8KvxB/HP8qvzi/Cn9d/29/Qr+bP7Y/jz/mf8BAHYA8QBxAf8BngJDA98DbgQIBbQFUwbbBmoHAwiOCBAJkgkGCmMKuwoECzQLWQt/C5ALewtOCxYL1QqMCj4K4AljCdQIRgi1Bx8HlgYUBoEF7ARiBNMDQAO9AkkC2gFnAe0AbQAAAK3/U//b/lr+5v14/fr8ZvzB+wb7QfqK+d34Jfhi95v20vUS9WP0u/MX84fyBPKE8Rfx0PCf8HLwT/BF8Fbwg/DL8Cbxi/H68XTy9fJ78xL0tvRb9fz1nfY99973h/gt+cP5WPr3+pb7Kvy2/EL90v1c/tb+VP/k/38AEwGfATMCzQJfA+sDeAQEBYgFCwaRBhAHfQfhB0gItAgfCXwJygkWCmcKpQrFCuAKCQszC0YLSQtHCzkLHQv7CtgKqQpuCiUK0Al1CR4JxQhaCOAHYwfrBnAG7QVnBeQEYQTjA2cD6gJtAvQBeAEEAZ8APgDP/1j/5/6D/ij+zv1v/Qz9q/xP/Pj7pftU+wX7tfpm+iL65Pml+W75Sfkn+QT57/jp+Of46vj7+Bb5OPlo+aH53vkY+lX6nvrv+j/7mPsA/Gn8z/w8/av9HP6a/hX/gf/i/0kAuQAqAY4B6QFFAp0C6AI1A4YDxAPyAyUEWASBBKMEwQTcBPME9gTuBO4E9QT+BAUF/wTqBN4E3wTWBL4EngR7BF8EQgQYBOwDyAOWA1UDGQPbApACSQIIAr8BawEVAbwAXwD6/5T/O//r/pf+Rv75/aX9XP0j/eD8kPxO/BX84Pu3+5X7dPtf+037M/sm+yr7Kvsj+x77I/s5+1T7ZPtx+4f7lfuf+7H7x/vk+wn8I/wy/E/8b/yF/Kf80vz3/CD9VP1//a396/0p/mD+nf7n/jj/h//M/xgAdQDOAB4BcwHAAf8BRwKQAsgC/wI4A2IDggOqA9ED9wMXBCAEHQQfBBkECAT4A+kD2gPUA84DwQOvA5gDgQNyA1UDGQPlAsgCngJkAjEC/wHFAYsBUQEVAdMAhAAyAOn/lv9B//b+q/5V/hn+9P3E/Yn9X/1F/TX9Jv0L/e384fzj/PD8+vz5/Pb8+fzy/Ob84vzZ/MT8wfzS/N385Pzy/AP9Gf00/Uf9W/14/ZP9r/3f/R3+WP6O/sv+Hv95/8n/FAByANcANgGeAQwCcQLcAlIDvAMeBIsE/QRkBcUFJgZ/BtAGFwdWB4gHqwfTBwAIHAghCCgIKggdCBEICwjzB8MHkwdtB0kHHAfhBqAGZAYjBtUFhAUwBdoEhgQzBNIDYAPmAnECBQKWARoBnAAnALf/Qf/A/jX+sv0//cf8Qvy9+zz7uPo1+rf5O/m6+Dj4uPdD99v2gfYs9tT1fPU09fj0vPSJ9Gj0U/Q39Bn0EPQp9Fn0i/TC9AH1PPV29b/1HfZ69sv2J/eU9wX4fPgH+Zv5Ivqj+jH7vvtA/ML8SP3G/T7+uf47/7X/JQCVAAwBhAH6AW4C2wJBA6gDEARzBNYEOQWaBfQFSAaYBu0GQweIB7wH8wcnCFMIewicCK0IsQi5CMwI1QjBCKIIkQiACFgIKAgBCNEHjAc8B+0GpgZcBgIGnAU9BeAEeAQMBJwDKgO5Ak4C5wGEASEBuwBeAAIAlv8o/8r+cf4W/sP9fP1A/QT9w/yM/Gf8QvwX/Pb71/us+4n7evtw+2L7U/tI+0v7Wvtl+2r7dfuH+6f7zPvh+/H7Evw8/Gf8mfzU/Aj9Pf2B/dD9I/5y/sD+Fv9q/7H/CQB6ANkAGQFcAbMBDQJfAqQC4gIjA1sDjAO9A+YDAgQcBDAEMQQrBCgEIgQfBBwECgTuA9MDsgOJA2gDRAMdA/kC1AKjAnYCVAI0AhMC7wHFAZ4BfAFYATAB/wDGAJgAcwA7APL/qP9b/xP/3v6n/l3+Gv7n/a79b/01/f/8yPyS/Fv8J/z7+9r7xvu4+6X7nPuk+6P7ovu0+8r71fvq+wz8Ifwy/FL8ePyg/MX85fwG/S/9Yf2X/cn9+P0m/lD+c/6d/tr+EP84/2b/lv/A//b/OAB0AKcA1wAFATQBbAGpAeUBHAJJAngCqgLTAvUCGQM2A1IDewOrA8oD1QPZA90D5APqA+YD1wPFA68DmAN8A1IDIQPzAr0CfwI8AvQBqAFiASIB4ACcAFMACgDH/4z/UP8U/97+qP5y/jv+B/7d/b/9ov2D/WX9Tf08/Tf9Kv0R/fn86vza/MT8qfyS/Iz8kPyN/Hr8Y/xW/FL8T/xF/Dv8Nfwy/Dz8WPx5/Jb8uvzk/BL9SP2S/en9PP6H/tf+OP+j/xAAeQDlAFQBxAEwApMC8AJHA5kD5QMzBIQEzwQPBUgFdAWOBZ8FtQXUBesF8QX1Bf0FAwYKBhgGKQY3BkYGVQZdBloGVwZaBl4GVQY9BhsGAgb5Be0FxwWFBT8FAAXBBHsEKQTGA18DBwO4AlcC6wGEASIBtgBHAOP/hv8l/8H+Y/4K/rH9YP0M/aX8Nvzb+5n7W/sQ+8P6g/pN+hT61Pmb+XL5VPkz+Q759vjy+O/45Pjb+OX4+fgH+Qr5DvkW+SL5NPlP+Wr5gfmg+cz58/kK+ij6X/qs+u/6IPtQ+4T7vPv4+z78i/zX/CH9dP3X/Tr+jf7Y/in/ff/J/w8AVQCdAOIAHgFVAYgBtgHZAfwBJwJRAm0CggKYAqwCuALFAtgC6ALrAvAC/AIGAwsDEwMdAx4DGwMlAzQDOQMyAyMDDAPwAt4C0gK3AokCYQJCAhgC4QGtAYoBZwE1AfYAvQCVAHYATwAeAPz/7P/c/8H/qP+e/5n/i/95/23/Z/9k/2H/X/9d/17/Yf9m/2//ef+C/4//qv/P/+z/AAAYADkAVQBtAI8AvgDnAAcBJwFHAWMBfwGlAc8B8wEVAjUCUAJoAokCqgLEAtcC9wIjA0gDYAN3A5ADpwO2A8ID0gPgA+cD5wPiA9UDvwOfA38DZgNOAysDBQPkAsACjQJSAhgC3QGdAVwBIQHjAJgATgANANf/n/9n/yv/6f6l/mz+Ov4D/sj9k/1o/T39Ef3t/M/8sPyJ/GL8Qfwi/AT86fvV+8P7rfuP+3X7aftl+177T/tD+0b7TvtJ+z/7RPtc+3f7i/ud+7b71Pv3+yT8VfyB/Kr83/we/Vf9if3D/Qv+WP6l/u/+M/9v/6r/6v8oAGEAnADgACQBYAGVAcUB7AEOAjICVwJ5ApYCtgLdAv8CFAMlA0IDaQOHA5EDlgOeA6QDogOhA6IDmgOKA4ADegNsA08DLgMJA98CtwKcAn8CVAIgAvMBywGcAWABJAHuALYAdgA0APv/x/+M/0f/Bf/R/qP+dP5I/h7+7/27/Y79cf1a/T79I/0O/fr85fzU/M38yvzC/Lb8q/yp/K78sfyv/Kr8qvyx/Lz8zfzf/Ov8+vwV/UD9bf2U/br95f0V/k7+k/7c/iL/av+5/wkAUACXAOgAQAGNAdIBGgJfApwC1AITA1ADgAOuA+kDKQRYBHcEnATNBPgEFgU0BVwFgAWXBaYFsgW9BccFzwXQBcgFvQWxBaAFjwWBBW4FUAUqBQUF3wS5BJoEegRQBBwE5wOvA20DKAPtArICawIaAskBdgEcAcYAcwAaALn/X/8N/7j+Xf4G/rP9Yv0X/c/8hfw+/Ab83vu1+4n7XPs1+xP79vri+s36svqf+pv6nPqU+oP6cfpg+lX6T/pO+k36SvpF+kH6QvpJ+lP6Wvpj+mz6dfqB+qD6zPr0+hP7N/tl+5b7yPsB/Dv8avyS/MH89vws/V39h/2n/c39CP5H/nP+kv67/un+B/8j/1D/f/+b/6z/yf/2/ycAWwCHAKUAvgDgAAQBIQE5AVMBbgGKAaYBvAHHAdUB7QH+Af8BBgIgAjoCQgJGAlMCYQJrAnwCmAKuArICswK+AtMC4wLmAuIC6AL1AvoC9gL1Av0CAAPuAtICwQK+Ar0CswKnAp8CmgKWApkCoQKfAo8CiAKRApsCngKmArACsAKjAqECqgKvAqoCqQKrAqQCkwKBAnACZgJiAlsCRgItAiECGgIJAvcB9AHxAdwBxgHFAcgBsAGOAX4BfwF1AV0BQwEvARcB9wDaAL4AmQBrAEIAHgD3/8r/nf94/1r/O/8T/+z+z/65/p7+e/5X/jr+F/7x/dH9tv2Y/Xb9WP1A/Sj9Fv0M/f385PzR/Mz8zvzL/ML8vfzD/M/82Pzb/N/85vzt/O788fz4/P78//wA/Qf9FP0j/S79Mv08/VP9b/2G/Zz9uf3c/QL+NP5p/pH+tf7l/hv/Rf9r/53/yf/b/+z/FgBSAIMAngCvAL4A1wD8ABkBLQFCAVkBaAF1AYwBpQGtAbMBywHlAesB6wH6AQ0CFQIWAhUCBALnAdEByQG+AbEBpwGbAYoBegFqAVABLwEUAfoA0QCpAJAAgABnAEsAMgAbAP7/4P/F/6z/lP96/1r/Of8i/xX/AP/d/rr+pP6Y/oz+ff5u/mL+VP5J/kT+Rf5E/kD+O/4//kn+Vf5b/mP+cf6J/qD+s/7A/s7+3f7u/gf/JP8+/1f/bP+C/6P/2f8SADgAVwCDAL0A9QApAVoBhgGyAecBGQI6Al8CngLlAhEDLgNcA5oDyQPjA/oDGgQ3BEcEUAReBHMEfgR8BHcEdQRxBGoEZwRhBE4ENwQpBBkE+gPeA84DuwOeA4UDeANqA1QDOgMdA/gCzAKaAmACKQL5AcQBgAE8AQEBwgByAB8A2f+a/1P/Cf/E/n/+M/7q/a79fP1I/Q391/yt/Iz8afw//Bb89PvU+7D7i/tk+0T7K/sV+/v64frO+r76qPqV+oz6hfp2+mj6ZPph+l76Yvps+nD6e/qX+rL6vvrE+tP65vr3+g37KPtC+177fPuU+6X7wfvk+wP8IvxN/ID8qfzT/AT9NP1j/Zv92v0R/kD+cP6f/s3+Bv9M/43/wP/v/yIAWACRAMcA+AAjAUwBbwGPAbUB3AHzAQACGwJLAnwCogLGAvACGwM9A1MDZAN+A6IDwQPTA+cDDAQ5BFgEZwR0BIsEoQSpBKsEtQTEBMgEvQSqBJYEiQSDBH8EdARjBFkESwQqBPYDxgOoA5YDfwNdAzYDGgMHA/UC3wLPAsMCsQKaAoQCbQJMAigCCALyAeUB1wG/AZoBdQFZAUEBGwHqALsAkwByAFAALgALAOL/uf+Z/4X/cf9S/y//EP/3/uD+yP60/qT+k/6D/nT+Y/5M/jj+MP4r/hv+Bv76/fX98P3n/eH93/3k/e398v3w/e/98P3r/eL96f3z/er93f3k/e/96/3o/fn9Bf78/fn9Cf4Z/h3+J/41/kH+T/5n/nn+gf6O/qT+u/7L/tT+2P7c/uj+7v7m/ub++/4Q/xP/Fv8i/yr/Lv89/1X/Xf9T/1L/YP9y/4D/hv+M/5j/qP+6/8//4v/q/+3/+P8JAAwA/////xYALgA7AEMASwBRAFYAXABiAF8AWgBZAFoAWgBhAGgAZgBcAFwAXgBTAD0AMQAsAB4ACwAEAAEA8v/j/9//2v/K/7v/u/+//7v/t/+0/67/qf+p/6n/pP+g/6n/tP+4/7n/vP++/7r/uP/C/87/zv/J/9H/3P/f/+P/8v/7/+7/5f/4/w0ACwAHABkALwA2AD4AVQBsAHcAgQCWAKwAugDDANEA8QAbAT0BWgF4AZgBswHPAfEBEQItAksCZAJ0AoMCnQK+AtwC9gILAxsDMgNRA2oDdgOBA4wDjQOFA4QDigOPA5ADjgOHA4EDhAOEA3cDYgNNAzoDJAMNA/gC5QLZAtICxgKyAp4CigJpAj4CFwL1Ac0BlQFdAS0B/ADEAIwAYQA+ABMA1v+O/03/F//o/rT+ev5C/hD+3v2t/Yj9b/1O/Rz97PzF/J/8ePxU/Cv89/vJ+6/7oPuC+1r7QPs5+y37Dvvx+uj65PrW+sX6vvq5+qz6o/qm+q36svq2+rf6s/q2+sf63vry+gL7C/sQ+xz7M/tO+2v7lPu++9r77fsL/Df8Y/yG/Kv81vwF/TT9Yf2P/bz95f0R/kn+e/6c/r/+9v40/2T/kP/J/wkARAB+ALEA2AAEAUIBfAGgAcIB+QEyAlwCiAK9Au0CFAM8A2UDhQOkA8QD3APwAw4ELwRJBF8EfgSgBL4E2ATyBAoFHgUvBTYFNgU2BTQFMAUyBTMFKgUbBRUFEAX3BNEEsQSOBGUEPAQgBAwE8wPZA74DoQOFA3IDZwNXAzoDGgP9AtwCtwKSAmsCPgISAvIBzAGTAVMBFgHaAJgAVwAYANz/qv+D/2L/Q/8s/xb//v7p/tf+vv6e/oT+bf5U/jz+Kf4R/uv9wf2e/YP9bP1Y/Tz9Fv35/Pb8BP0H/QD9/vwH/RL9Iv0z/T/9R/1Y/XD9gf2M/Zr9qv2z/bv9yf3c/fH9BP4S/iL+Nf5K/l3+fP6e/rP+vf7S/vP+Fv83/1T/Zf9r/3L/gv+U/5v/mf+b/57/nf+c/6X/rf+p/6j/tv/F/8j/xf/M/9z/5//s/+v/7f/5/wgADgAQABMAEwAUAB4AJQAYAP//7//q/+3/9f///wQABQAHAAcABQAEAAQA/f/1//H/7//n/97/1//T/8j/tf+k/53/mv+Q/4L/df9m/1b/TP9N/1P/Vv9W/1P/T/9L/0f/SP9K/1L/Wv9a/1D/SP9N/1n/Y/9q/3H/df93/37/iv+T/5f/l/+X/57/q/+4/8b/2v/s/+7/7P/+/xcAIAAoAD0AUQBfAHMAjQChALYA1ADwAAYBHwE7AVYBdQGaAb0B3wEJAjACSAJlApQCvgLTAt4C8gIGAxIDHQMvA0MDVwNqA30DlQOsA7wDwAPDA8sD0APSA9kD5QPqA+ID2gPXA9EDxQPAA70DqQOHA2oDWQNDAyED/gLoAtoCzAKyAo8CbAJGAhoC7QHCAZQBXwEpAfMAvACFAE8AGgDn/7j/g/9L/xX/4P6j/mb+NP4D/s39nf15/Vj9Of0c/fr80Pyj/Hn8Uvwr/AD80fuj+4D7Y/tI+y/7Ffv7+uL6zfq4+p36fvpj+k/6Q/pB+kn6Wfpi+l36Wvpk+nH6e/qF+oz6kPqc+rX60Prj+vb6DPso+037dPuS+637zPvr+wj8K/xX/ID8p/zV/An9Of1n/Z391/0Q/kL+bf6S/rf+4P4P/0T/eP+o/9//HwBYAI0AygAJATgBXQGNAcYBAQI9AncCqALVAgYDOgNqA5IDtgPcAwMEKgRLBGEEdASMBK4E0ATpBPoEDAUdBSwFNwU+BUcFVwVkBWMFXgVgBWYFawVwBWUFQgUcBQsFAAXmBMYEsASTBHEEWgRRBEMELAQPBO8D0gPDA7YDnAN0A00DKQMJA+cCvwKQAlsCHwLcAZsBYwErAewAqwBwADwACwDg/7z/nv+A/1v/Nf8R/+3+0v6//qT+dP5D/ij+G/4D/t39tP2M/Wf9Q/0k/Q39Av3//Pv86/zX/ND82/zn/Oj85fzq/O/88/z7/AH9Af0B/Qj9Df0S/Rn9Hv0m/Tr9Vv1p/Xr9l/24/dL97/0a/kP+Y/6B/p7+s/7H/t7+8f77/gP/CP8O/xv/K/8u/yv/NP9M/2H/bP92/4z/o/+t/7T/xP/b/+z/+f8CAAQACwAeADAAMgAzADwARgBFADkAKgAlAC4APgBKAFEAXABqAHIAcABtAGkAZQBoAGsAZgBhAF8AVgBFADYAKwAeABQACwAGAAcACQD+/+n/2f/T/9D/xv+x/6H/of+l/5X/f/91/27/XP9J/zz/Lv8e/xf/F/8V/wz/B/8N/xL/Ev8X/yH/J/8n/y3/Ov9O/2L/bP9u/3T/f/+J/5D/mv+p/77/1f/o//L//v8SACQALAA2AFMAeACSAKgAzADsAP8AGQFIAXkBoQHJAfMBHAJCAmYCiwKyAtUC8AINAzEDTwNsA4YDnQOzA8sD3APkA/kDHgQ8BE4EXQRiBF0EWgRkBHIEegR8BHcEZQRPBD8ENQQlBBEE8wPHA5wDhgNxA04DLQMaA/8C1QKpAn0CSQIPAtIBlgFaARsB3AChAGcAIwDi/6r/cP8q/+D+lf5N/hb+4v2f/Vv9LP0K/ef8v/yU/GX8OvwN/Nv7oPtq+zn7C/vg+rf6kfpw+ln6S/o2+hf6/vnv+df5uPmt+bb5u/m5+bv5xfnd+fr5E/oh+in6LPo2+kn6Wfpe+mv6hfqi+rb6z/r1+iP7U/t++6r71Pv2+xr8S/yA/LL84vwT/Ur9jv3Q/f79KP5g/pj+yf78/iz/V/+G/73/8f8oAGgAowDWABABVQGbAd4BFAI/AmECiAK3AugCGQNHA3IDkAOqA8cD5AMBBCkEVgRyBIIEmwSxBL0EywTjBPsEFQUxBT4FPQU+BUgFUQVOBT0FKgUiBRYFAgXyBOQEzASxBKMEmASGBHQEYQRFBCcEDgQABP0D/APtA9MDwQO1A6IDhANnA0oDIwP2AtECqAJqAjACDgLuAcABkwFuAUABEQHyANMAowBvAEgALwAaAPz/4P/T/8D/jf9K/x3//P7Y/rL+k/5w/kn+Jv4P/vz94f3E/bH9pv2Q/XX9X/1S/VP9Wf1W/U/9Uf1S/Uv9Rf1B/TT9J/0e/Rj9Gv0o/TD9Mv1C/V39Z/1l/XD9kf2y/cf92v31/Qz+FP4W/iH+MP48/kf+TP5H/kT+S/5Y/mb+cf50/nj+ff6M/qz+0f7l/uz++/4R/yv/SP9c/2T/cv+F/4b/gf+N/5v/nP+f/63/uv/F/9T/4f/o/+f/4//u/wcAFwAWABgAJAAxADIALgAxADkAQABDAEIAOAAyAD0ARwBAADsAQwBFAD4AQwBMAEkARwBMAEMALgAcAA8ABgD+/+3/1f/B/7T/pf+a/5L/g/9t/1j/UP9a/2r/cv9y/3L/dv99/4b/if+L/5T/mP+Q/47/k/+X/5v/of+m/67/uP/B/8//4//y//7/EgAqADsAVAB4AJoAuwDjAAwBLwFQAXIBlQHGAQECLwJOAnECpQLdAgcDIwNAA2IDfQOYA70D5gMIBCUERgRxBKEExQTYBOQE6ATmBO0E/AT3BOUE3QTbBNQE2wTnBN0EwwStBJYEcQRLBDQEHgT5A8oDoAN9A1wDPQMZA98CkAJJAgYCuAFfAQ4BwwB7ADcA8v+t/2n/Jf/m/qb+VP76/bX9gf0+/fb8x/yi/G78MPz9+9P7qPt5+0r7HPvl+p76XPon+u/5tfmQ+Yf5hvl7+WD5Qfkw+Sn5GvkD+fX49/j++AT5CfkZ+Tb5Uvlq+Yb5nPmi+aL5rvnI+en5APoT+jr6dfqr+tz6F/tR+4X7uvvw+xv8RvyA/MD8/vw7/XX9qv3h/SH+Y/6e/tH+Cf9K/33/nv/I/wAAOABrAKgA7AA6AY4B3QEeAl4CngLPAvkCJgNZA5ADvwPfAwEEMARgBIEEmgS1BMsE2wTqBPkEBwUYBS0FQQVJBVIFbAWEBYUFfgWABX4FbwVZBUAFJAUOBf0E5gTKBKoEgwRhBEkELwQMBO4D0wO5A6cDmAOAA2wDYQNPAzsDNQMvAxMD8ALWAroCkQJnAkECEwLYAZgBXgEmAfMA0AC0AJEAaQBGACsAEgD+/+//4//V/8D/pv+X/4z/ef9m/1f/Pv8U/+v+y/6u/pL+bP45/gn+6v3T/b39rf2i/Zn9kv2S/Zv9pv2t/bX9vf3A/b79vf29/b/9yP3I/bP9o/2v/cP9x/3N/d398P0E/iD+N/5F/lT+cf6P/qH+qf6s/q/+sv60/rH+rf6s/rD+rf6f/o3+g/5//nv+dv52/oT+oP7D/uL++v4H/xT/If8o/yn/Lv80/zL/Lv8z/zT/M/86/0X/RP9C/0v/Vv9h/23/dP98/47/oP+s/7r/zf/a/+H/6f/n/9v/1v/U/8n/u/+3/7T/rf+q/7D/t//D/9T/3f/a/9z/6f/w//T/9//q/83/vf+4/6X/if97/3j/bv9h/1T/Sf9D/0T/QP85/0D/Tv9e/3P/f/96/33/mf+s/6P/mv+l/7b/uf+z/6n/of+g/6n/uf/J/9b/5f/9/xsANgBIAFwAewCkANAA9QAUATcBawGkAdYBBAI7AnICnALAAukCEgM0A1YDfQOlA80D+QMmBFMEfwSnBM0E8QQMBR8FJgUpBSoFKAUfBRoFHAUdBRMFBwUCBQYFDgUKBfYE4ATKBK0EjAR0BF8EPgQVBPYD2QOyA4MDTwMUA80CfAIhAscBcgEhAdYAlQBcAB8A2/+T/07/D//N/oH+MP7l/aL9Z/0w/fv8xPyc/IP8Y/wm/N37nftZ+wb7sPpp+iz68fm8+ZX5fPls+VX5Pvkw+Rj56/jD+LD4ofiD+G/4cfiA+JH4ofiz+Mr45fj4+Ar5H/ko+Sb5Nvld+X35k/m8+fr5M/pr+q368/o3+3z7tvve+xD8VPyO/Lv89fw9/YD9vf0F/kz+iv7D/vr+Lf9m/6f/5P8cAFYAmADfACUBZgGoAfIBOwJ2Aq8C7gIpA1gDhgO5A+sDGgRMBHQEmATDBPAEDAUjBUAFYQV7BZMFqgW8BcwF3QXvBf8FCgYMBgYG/wXzBeIF0wXFBbIFmAV7BV0FPgUlBQkF5QTBBKYEjQR0BGQEVQQ/BCQEEwQFBPAD2QPCA6oDlQOBA2QDOgMTA/QCzAKTAloCJgLtAaoBaAEwAf4AzQCYAGcAQgApAAwA6//J/6r/kf97/2P/Qf8b//f+0/62/qX+lP54/lz+Uf5D/h3+7P3M/bT9mv1//WL9Rv03/TP9NP03/Tj9L/0h/ST9LP0j/RP9F/0h/Rv9E/0a/Sj9Of1Q/Wn9e/2N/Z/9r/3K/en9/P0E/hn+L/41/jz+V/5z/oH+jv6g/rL+vP63/qD+lf6e/p3+hP53/oX+lP6g/rv+2/7r/vP+Av8S/xb/Gv8g/yT/KP80/0T/Uf9c/27/iv+l/6//r/+t/6X/mP+V/5P/hf9+/5T/rP+w/7b/yf/V/9L/zP/C/7H/qf+t/6z/pf+p/7X/xP/Q/9T/0P/O/8//y//F/8H/s/+h/6L/sP+1/7P/tv+v/57/m/+h/5T/gP94/23/Vf9O/2P/df97/4X/kP+Y/6T/tf/B/8j/0v/Y/93/6f/5/wEABgASABsAGwAgADQASABOAFEAYgB9AJQApAC9AOAABQErAVwBkQG7Ad8BDwJGAm8ChwKjAswC8gIOAysDVgOCA6QDxAPvAyQEVAR6BJ0ExATwBBkFNwVIBUUFMgUdBRgFGQUPBQQFAQX8BOgE2ATVBNEEvwSyBLAEqAScBJ4EqwSuBKIElQSIBGkENQT4A70DgQMvA8QCVgLwAYoBHwG9AGEA/P+Y/0b///6o/kv+8f2d/Uz9/vyq/Fb8Ffzo+7b7fftR+yz78vqp+mj6J/rg+Z/5avkx+fT4xfio+JT4iviN+I/4gvhu+Gf4ZfhV+DT4EPjw99n31vfo9/r3AfgO+Cr4RPhg+Iz4v/jl+A/5Vfmv+Qj6ZPrL+jX7o/sU/Hr8z/wb/WT9nv3D/d39A/44/m7+mf7J/g//WP+W/9z/LgB2AK0A5wAhAVgBmwHpASoCWwKaAugCNQN/A8QD9QMWBD8EZwSBBJ4EyQTyBBQFOwVlBYgFoQWsBa0FswW1BZ8FfwVwBWIFPgUZBf0E1wStBJUEgARZBD0EQgRHBDMEGgQOBBAEGAQXBAME7wPpA98DxwOsA4oDWQMrAwsD6QLJArwCsQKPAnECYwJEAggC1wG+AaYBiwFuAUQBFgH1AMoAfwAyAAIA0v+R/2T/Tf8x/xn/I/84/zn/Mv80/zb/Lf8f/xD/Af/w/tj+sf6H/l3+Jv7p/cH9qf16/TH98/zT/L/8qvyi/Lv86vwb/U/9kv3P/fP9E/5H/nr+kP6S/pP+kv6Z/q3+u/61/qz+n/6D/nH+gf6W/o7+hP6d/sj+6P4O/0X/gv/C/wcARQByAJwAvADCAL0AxQDVANoA2ADaANkA0QDMAMUAqwCIAG8AXwBEABsA9f/Y/77/qf+c/6P/wv/i//H/+P8EAAkA///1//H/2f+r/4j/e/9u/1r/TP9G/zn/JP8G/97+rf55/kb+H/4H/uf9s/2T/aH9w/3V/dX9yv23/av9qf2W/XP9Xf1a/Vn9Xf16/Z79sP28/dH94v3o/e397/3t/fP9Bf4e/kn+mP70/jv/Z/+W/9D/BQAwAEwATgA+ADwAVwB2AIoAtAADAVABfgGoAewBLAJOAl4CfALCAjgDwwNUBAgF7gXUBqIHdwhICcgJ+wkgCkAKQAo+ClAKVwpUCm0KnArDCu8KBgu1CgMKSQmRCKAHlga4BfoESwTjA9ID3gPtAwgEEQTsA6cDOQOSAs8BEQFBAGD/pv4m/rv9Sf3H/Cn8e/u5+r/5i/hZ9zv2GPUN9FDz2vKj8tDyTvPF8yT0n/Qh9XT1p/XT9ef17vUR9j72Y/az9kH3zfc0+Jj4+fg2+Vr5evmL+Zv50fkt+qL6Pvv6+7D8av1A/hH/t/9RAOwAYQG1ARwClQICA2IDugP4AzQEiwTXBOQEzQS3BIwEPQTkA5ADOwPzAr0CgQJGAjACNQItAh0CHgIkAhoCBwLvAckBlgFeASMB7wDJAJ8AYgAlAOb/hf8F/5r+Sv7Z/Uj90PyE/E78Lvwy/ET8ZPyo/An9Yv23/Rz+gP7O/hH/TP9z/6L/9/9cAKsA+wBeAawB0QH0AR4CMAIsAjcCTAJhApQC9QJbA7kDLgTFBFwF3AU/BnsGmAauBsoG3wbxBgIHDwcXByoHQQc+BxIHyQZnBuUFTwW/BEIE1gOLA28DfQOSA6YDxAPkA90DngM9A9QCXgLUAUQBxQBhAAsAtf9V/+r+av7C/e78//sQ+zj6hvn/+Kj4ivig+NT4Fvlb+Zv51vkK+jX6Ufpk+ob6vPr4+i77V/t0+5j7xPvl++v76Pvz+w78KfxA/Fr8hPy+/Ab9Xv3S/WD++f6e/04A/QCdAS0CrwIfA4MD4wM5BHwErwTWBOwE6gTWBKwEagQXBMYDegMzA/oC2wLOAsICswKnApkCeAJIAiACAwLkAbwBkwFmATIBAQHQAIwAMwDT/2n/7/5w/vP9bP3l/Hz8L/zn+6b7h/uB+3/7e/t++437pfu9+8r70vvo+wT8E/wf/DT8Uvx5/J38svy6/MT82fzy/Ar9Ff0G/fX8/fwQ/Rb9Jf1X/aH97/1B/pT+2v4R/zb/P/8+/1L/df+S/7r/+f87AHUAtwDwAA0BJAFCAUwBPAE1AUABQwFJAV4BbAFrAW8BbwFaAUsBXgF6AZQBxgESAlwCqwIEA0sDdwOhA8sD3QPmA/sDBQT2A+cD3AO/A5QDawMzA/oC7wIhA3MD4QN2BCQF5QXBBqQHYQgECZ8JEAoyChcK2Al9CSEJ1giLCEcIMwhPCGcIXwg8CPIHfAfuBj8GXAVkBI8D4gJcAh0CKQJXAowCuQKxAmMC4gE1AUAAHf8B/vz8DvxN+7z6QPrb+Y35K/mQ+NL3BPcR9v708fP/8kXy7PHt8RbyZPLq8pPzNPTB9Cv1XPVt9YX1m/Wf9a713vUa9mX2yfYp93H3vfca+HD4vfgW+XP5zvlL+vb6rftj/Cv99v24/n//SwD0AHkB9gFtAtQCOAOYA9YD+wMlBE8EbQSSBMAE2gTlBPkEDwUKBfQE1QSaBFIEGATqA7kDmAOMA30DZwNiA10DRAMfA+sCjQISApoBJgGvAEcA+f+5/4j/bf9P/xr/7P7M/pr+Vf4a/vD91v3Z/fr9I/5d/sL+OP+Q/8n/5v/f/7n/k/9r/z//M/9b/6X/BwCHABIBigH4AVQCggKFAoACgQKKArgCEwN+A+0DbQTsBFIFlwWzBZQFVgUmBf0ExASSBIcEnATLBA0FSgVsBYAFgwVYBf4EmQQ1BM8DhANfA0wDRgNnA6sD7wMcBCUE+QOaAxwDhQLZASsBjQD3/33/M/8E/8r+gf47/vj9sv1k/QX9o/xf/En8VvyH/NX8Kv1t/aD9s/2K/Sv9u/xF/MT7TPvy+rv6rfrK+vn6Mft4+8n7FPxe/K/87/wb/VP9ov3o/SD+av7J/i3/jf/c/w4ALQBJAFMAPQAjABoAFwASABwANwBSAG0AkACwAM0A8AAYATEBMAElAR8BIAEYAfoA0QCyAJwAewBRACcA+P+9/4P/S/8F/7D+X/4f/u39zP2z/Zz9k/2j/bv9zf3d/e/99v3w/ef91f22/ZL9cf1U/Tb9GP39/PP8+Pz2/On86vwD/Rz9Lf1R/ZP93/0t/o3+Af99//T/UgCDAIsAdwBNABQA1/+i/33/gP+q/+b/IgBdAJAAqACXAGQAJQD2/+H/2v/j/xgAfQDxAFoBtgH5AQ0C9AHDAXYBBAGKACsA9//w/xYAYQC7ABcBewHaARsCMAIpAiACHAIOAu8B2AHjARQCVAKGAq8C5QImA1MDZAN5A6cD7gNQBNwEgwUuBtgGiwc4CMAIDwkjCQkJ3gi8CKIIkwiXCKwI0wgMCTcJFwmfCP0HSQdrBlsFQARIA5sCSwJUApIC7QJNA5gDtwOYAycDVwJGASkAGv8Q/hH9OfyW+yD7wvpd+tv5LPlc+IT3t/bs9SH1e/Qr9Dv0g/Tb9Db1nfUO9m/2nvae9or2bvZE9hL27/Xf9eb1DfZX9rX2G/eJ9/73efj9+H357PlZ+tn6Zfvx+338Ev2n/T3+0f5e/9n/RQCiAPYASgGYAdMB+wEdAjUCPQJFAmACiQKzAt8CCAMnA0YDYQNcAzoDHAMLA/ECzAK/AtgCAQMuA1QDZgNZAycDwAIcAlkBjgDC/wH/c/4w/jL+Yv6p/vf+P/95/5X/h/9U/w//zf6m/qD+rv7S/iL/of8rAJcA0QDPAJkAOwDK/1v/B//o/gn/fP8vAP0AxwGCAiEDjQPBA70DfgMlA/YCAQMpA2wD6wOWBDEFoQXlBfUFyAVwBfQEXgTaA4oDXwNUA4MD4gMvBE0EVQROBBQEpAMfA6kCRwL3Ac0B4gE1AqACAQNVA48DjAM0A5sC3AEHAToAi/8C/6P+fP6E/p3+rP6k/oP+T/4T/s/9hP1Q/Un9aP2d/eL9NP53/pb+h/5V/hL+xv11/TP9H/03/V79iv2//fD9Dv4p/kL+Sf5A/kX+Y/6O/sr+JP+I/9n/FABCAF8AXwBEACAACwAJAA8AFwAwAF4AkwC/AOAA7gDiAMgApQBxAC0A7/+//5n/iP+N/5b/ov+7/8//wP+Z/3f/Uf8Q/77+af4P/rn9fP1P/Rn92/yn/Ib8bfxW/EP8O/xH/Gv8m/zQ/Av9Rv17/aT9uP2v/Y79Yf0u/fb8uvyH/G/8hPzF/Cn9o/0j/pv+Bf9i/6z/2P/7/yMATABuAJAAsADFAM4A0gDJALAAkwB4AGYAbwCoAP4AWAG2ARoCbwKjAq8CggIcAq0BWwEaAdcArwDCAAsBcQHPAQkCGwIhAh0C8QGZATMB3wCoAI0AhwCAAHoAgwCXAJ0AiwBmADgACADm/+D/+P8kAGEAtwAoAZEB1AH0AQAC8wHKAaIBlgGtAe0BZAIPA+MD2ATLBYkGAwdOB2oHRgf2BqoGfAZ0BqAG/wZ9Bw8IsQg3CWkJMAmUCKQHggZlBWoEnwMgAw0DZwMHBLoETgWkBbEFZgWyBJ8DVgIBAbr/nP64/Qn9iPw3/Af8yftn++r6Wvqv+e/4NPiO9wT3mvZj9mD2gfao9sP2zPa+9pj2X/Yf9tr1mfVw9W71k/XP9RH2UPaW9u32Q/eJ98b3GviC+O74a/kE+qT6L/u0+0n81vw6/YX93f1B/pH+0P4R/1b/k//I//f/HAA8AGIAlgDfAEIBuQEwAqUCFQNoA4IDcANQAyUD7gLAArMCvwLUAvACDgMjAyUDCAO6AjYClwHzAE4AsP85//3+A/9Q/9T/ZgDvAG8BzAHlAbgBXwHlAFkA6f+1/6r/vP8DAIEACgFwAaABkQFMAfUApgBXABcAGQBtAPwAswGIAlED7ANbBJwElgRJBOEDfgMzAxYDNwOBA+YDagTzBE4FawVeBScFwQRBBMkDaQMrAxADDAMVAzYDZwOFA3kDTgMEA4wC+gF3ARIBxQCdAK4A8gBKAZMBvQHGAaoBWgHQAB0Abf/d/nL+LP4I/gX+LP5z/rH+x/63/o3+Qv7Y/WH9+Pyt/Ir8hfyW/MT8DP1d/af96f0b/jb+Rv5X/l/+Wv5d/nT+lv6x/sL+y/7X/uj+6f7V/tH+9/4x/2n/p//2/0kAmgDwADgBYwGDAa0B1wHtAe4B4QHSAdAB0QG+AZgBeQFhAUUBLAEeAQ0B+wD/ABABBgHaAKIAZgAgANr/m/9c/yH/7/69/oT+Rf79/aH9O/3k/Jj8Q/zy+8H7r/uv+7v70fvd+9j7xfus+4j7Yfs0+xP7G/tW+7H7HPyb/CH9g/2k/ZX9bP0h/bD8L/zT+8L7A/yO/F/9Zf55/3gATAHcAQ0C5AGNATMB3ACeAJQAygAsAacBLgKnAvECBAPpAqkCWgIYAusB0gHeAR0CfwLdAiEDUQNkA04DFwPPAnYCGQLdAc0BxgGyAaYBrAGeAWoBLgEEAdcAnABpAEsAQgBcAJgAzwDoAP8AJAEvAQcBygCWAGcAOgAfACIAPQCAAPMAhgEmAtcCowN4BDsF0gUwBmQGjwaoBoUGKQbXBccF4gUIBkUGuAZRB+gHXwicCH8IAQhEB2QGZAVVBHQD+gLmAhoDiQMmBNAEWAWZBYIFDgU/BCED2AGGAEb/Lv5Z/dT8gPwv/NX7h/tA+9j6L/pi+af4FfiW9x/3zfa39tP2Bfc892T3ZPc+9wP3rPYs9pb1IPXk9NH02PQH9Wj15PVe9sr2MPeQ9+z3Rvil+BX5lvki+q76Nfu0+yf8ifzS/Pz8Ev0t/Vb9h/3E/Rv+gf7p/lP/wv8vAJwAFwGXAQkCcgLSAhcDNAM/A0UDNAMGA9ICugLHAvECIANAA1YDbgN2A1ED9QJyAuoBeAEdAcwAmACjAO8AWAHBASECbAKYAp0CbAILAp0BPAHmAJ4AeAB+AKkA8AA8AXIBjAGSAXsBPAHtALMAmgCnAOgAWgHxAZ8CTAPSAxoEKgQEBK8DQAPWAnsCOAIiAksCpwIgA6cDJgSEBL4E1gTHBIYEIwTAA3QDRQMwAygDLwNTA4QDmQNxAx8DtgIzApYB9gBoAAQA5/8dAJIALQHgAYsC/wIoAwsDpALuAQIBCwAw/4L+DP7Q/cf95f0N/ir+Mf4S/sj9cf0t/fz81/zZ/Br9i/0O/oj+3/78/uH+lv4k/pX9Af2I/Eb8PvxY/Ir82/xF/av9/P07/mP+ev6a/s/+D/9b/7T/BgBMAJgA1wDcALMAkwCJAH4AdgCGAKgAzQD0ABoBMQFBAVABWAFiAYEBsAHaAQACHQIhAhAC7wGrATcBtAA/ANn/e/8t//T+zf62/p/+bv4j/t39pP1l/SP9+fzy/P78DP0W/Rz9Hf0J/dX8gfwe/Lr7Vvv1+qn6hvqX+tj6QPvB+1H84vxc/aH9pf2G/WL9Rf0l/Q79Gv1p/ff9nP4u/6f/BwA+ADoACAC3/2L/Pf9o/83/UQAEAeABswJWA78D3QOjAzsD0AJoAgoC1wHYAfcBLwKCAtgCCgMOA+0CrgJYAv4BuAGWAaEB1wEkAnQCuwL6AiMDJQP/Ar0CZgIEArcBiwFgAS0BEwEaARsBCQEAAQIBAwEOATQBdAHeAXwCLQPZA5cEXwXqBSUGQQZKBiAG0QWGBUAFCgUKBUQFlgX7BX4GBQdqB58HkQcyB6EG/QU/BXIExQNWAx0DJQNxA88DEAQ+BFwEPwTKAwoDFQIGAQUAJP9X/qH9Hf3D/Gn8/fuO+x/7n/oV+pn5M/nc+Jj4bPhL+CX49/fC94T3Ovfn9pD2PPb39cL1mPV69XT1gPWQ9aP1xvUD9mX25vZ99x/4x/hg+d35QvqM+qr6qfqq+rn6zPrz+kr7yPtS/OT8e/0H/nX+x/4E/zT/ZP+f/+v/TgDIAFYB8gGGAvQCOwNmA2wDRQMPA+ICsQJ/AmkCdAKSAs0CIANjA4YDmwOaA2sDJAPhApoCRQIHAvIB7gH0ARECMQI5AigCBwLTAYoBLAHEAHMAUgBVAGoAlADVABkBVgGBAYABTAEQAeUAwwCqALcA+ABkAeUBXgK5Av4CJwMTA7ICMgK9AU4B7AC6ANEAJgGvAVkCDwO/A1cExwT9BPkEvgRcBOkDcgP9Ap8CbwJxAo4CsgLVAvYCBgPwAqgCTQIDAtIBtwG8AfMBVgLJAiwDaANvAz4D1gI6AnEBlwDL/yL/oP5H/h/+If46/lf+df6T/qr+uf6//r/+wP6//qT+X/4N/sf9ef0a/cX8kvx//Ib8mPym/LT8yfzU/M38yfzU/OL8B/1a/cT9Jf6J/vb+Qv9Z/07/JP/W/oT+V/5I/k/+fP7S/kL/wP87AJQAzgD+ACABIQENAQEBAgEJAR4BRAF2AaIBtQGxAaQBhAE4AdUAgQA9APj/xv+6/73/xP/a//L/8v/c/8P/mf9W/wz/xP6B/lL+MP4N/un90/2z/XP9Lf36/Mv8ivxG/Bz8Gvw+/Gv8kfzG/B39b/2T/Zj9lP1//VT9JP3//Oz8+/w1/Y/9//2E/gn/ev/L/+//2f+R/z3/8/67/qf+zf4s/7n/ZwAnAdgBUwKJAo4CfAJRAv8BmAFHASkBLQE8AV4BogH2AToCYAJ2AocClAKYAooCZAIzAgwC/wEEAgMC/gEPAkQCfAKTApACfwJXAgwCqgFCAeIAogCSAK0A8QBgAekBdgILA5gD9gMpBFsEiQSXBJQErQTTBOwE+gQFBf0E6wTXBLwEoQS6BBYFkwUjBssGcAfqBzEIMgjGB/kGAwYEBQYEJwOGAiYCDgJCAqMCBwNiA6IDpQNgA+gCSAKDAbIA6/82/47++P13/Qj9mPwW/In7Cfua+iv6vvlh+RL5yfiJ+E74DPjG94X3Qvf59rT2fPZV9kX2S/ZS9lz2e/ah9rH2t/bT9vz2G/c492n3pvfg9xX4TfiW+PH4SfmW+ez5WfrC+hr7dfvj+1H8tvwe/YP91v0W/lH+kP7R/hX/Xf+u/xMAiQACAXAB1QEoAmQCjQKmArECvwLdAgYDKQNQA5ED5wMwBFcEXARGBBoE2QODAyADyQKVAoIChwKpAuUCJANgA48DpAOQA1cDBgOfAjgC6wHCAbABsQHBAdUB6AH0AeoBwAGEAUcBFAHyAO0ACQFCAZcB+AFKAoQCogKXAl8CEwLAAV0B/QDJANEAAgFUAcUBQwK7AiUDcAOJA3kDWAMjA9ACbgIRAsUBkwGBAYUBmAHIARQCYQKiAtwCCAMRA/gC1gKuAn4CVgJDAkACQAI/AjcCGwLmAZEBHAGfADUA3f+J/1L/U/92/6L/0P/6/wwAAwDp/7r/d/81//z+uP5s/jH+Av7L/ZD9Xv0t/f382fzC/L783vwf/Vn9hv29/fX9FP4e/iT+IP4M/v79+v33/fz9D/4a/hH+C/4T/iH+O/5r/qj+9v5e/8X/BQAtAFkAeQByAFcAQQAoAA4AAwAEAAwAIQA8AEsAUwBgAGcAWABHAEEANAAYAPX/z/+j/4j/hP96/1z/Pf8j///+zf6X/l7+Lf4V/gX+4v24/Z79l/2W/ZT9kP2I/Yn9kf2Q/YL9d/1v/Vj9Nv0W/fn84fzf/Pf8G/1B/XL9sP33/T/+e/6h/rz+2P7r/vH+9/73/ub+0f7V/vX+I/9e/63/CABoAMYAGwFXAXcBfgFxAVUBMAEBAdgAzwDuACYBZgGpAfABMQJeAmUCRQIVAvAB4AHcAecBCwJQAqMC3wL2Au4C0wKYAj8C5wGsAYQBaAFeAXEBngHYARcCUwKOAtICGQNjA7kDGgR0BLoE8QQaBSwFKQURBd8EngRtBFoEXQR5BL0EIgWdBSoGwwZVB8MH9gfrB6kHOgeaBskF7QQ3BLIDUQMQA/kCGANnA8YDDQQtBCwEDAS4AyQDYAKGAbAA8P9I/7P+M/7N/Xj9Kf3N/Fb8xvs2+736UPrb+Wz5FPnX+KD4Z/go+N/3jfcz99r2i/ZN9iT2C/YH9hj2NfZX9nn2kvaU9n/2ZfZS9lD2aPad9ub2PPei9xf4mfge+Zr5A/pc+qz6+vpF+4X7vfvv+xz8Sfx5/Kr84fwv/aD9Nf7s/rL/cQAfAb0BPgKFApICiwKJAo4CmAKtAs4C/QJHA6kDCgRTBIQEnwSlBJoEdgQ2BPUD0gPLA8sD4AMZBGAElQS7BNAEwgSRBFEEBASmA0UD+wLRAsICxQLIAsECuAKvAosCSAIDAs8BqAGSAaEB1QEgAm8CqgK+AqsCcwINAoIB6wBhAPf/vv++//f/aQABAZwBHwKGAsICvgKJAj8C6gGFASUB3QClAIIAgwCcALcA4gArAXwBxQEOAkkCXgJRAj4CGQLbAaEBdgFLAS0BOwFjAX4BiQGQAYIBVgEdAdwAiwBBABQA/f/x//v/IABDAFMATQAsAO3/nv9K//f+sf6G/nb+fP6P/pz+jf5q/kf+KP4I/uX90P3X/fz9Lf5c/ov+tv7A/pr+Wv4U/sn9h/1n/W79jP2+/Qn+Yv6+/hH/Tv9y/4j/nf+p/6X/mP+J/33/ff+K/5L/kf+f/8T/7/8OACcARQBiAHMAdgBzAHQAdQBnAEgAJQAGAOr/0f+6/6L/jv97/2H/P/8e/wX/7P7R/rf+nf6A/mL+RP4m/gz+9/3n/eL96v33/f39/v3+/fL90f2q/Yv9cv1Z/Tf9Fv0M/R39O/1f/Zb94f0p/mj+ov7M/tf+zv6+/pv+Zv4w/gT+6/35/TD+df7B/iz/r/8cAF8AgwCLAH0AdQBvAFIAKAAcADEATwBwAJsAzAD+ADgBdAGtAeQBHwJNAmwChQKWAo0CcQJSAjAC/AG7AYMBbwF+AZwBwQH6AUUChgK0AtgC8AL3AvkCBgMQAxMDGgMnAzQDTQN3A6IDzwMXBG4EsgTqBCsFXgVmBVwFTwUqBfQE2gTwBCEFdwUBBqsGTgfbBzUIOQjgBzoHUAY7BTQEXgO/AnACkQIVA8gDggQ0BboF7QW8BSwFSQQqA/QB1wD2/1D/2f6L/mf+Uv4v/u/9kf0V/Yj88ftW+8T6VPoH+s35nvlv+Sb5uvg/+L/3KveQ9hX2wPWD9Wv1g/W29ez1IPZG9kz2MvYF9s/1nvWD9YT1nvXb9Tr2rfYn96/3Ovit+AH5Rfl8+aD5tfnI+ef5FvpN+o765/ph+/T7mPxX/Sj+7v6i/04A7ABdAZ8BwQHSAd0B6gH4ARUCWQK8AiEDgQPtA1UEowTaBP4EFQUtBVMFdwWYBc4FFAZPBnQGfQZZBhYG1AWHBR4FuwSFBGwEaQSNBMcE8gQPBSEFDwXPBHsEEASGAwYDtgKIAngClwLZAhUDRQNuA28DMwPOAksCpwH0AFEA0P98/2j/j//j/1gA3QBVAagB0wHMAY8BKgGvACwAsf9S/xL/7v7s/gf/Mv9o/6f/4f8JACsAWACNAMwAGAFgAYgBmwGrAaIBYQH9AJYALQDH/4D/X/9f/4r/5f9PALkANAGmAdwB5wHvAdMBdAEFAbQAZAALAM7/p/93/1f/Xf9v/3v/lf+u/7X/wf/f/+P/v/+a/4H/X/8+/yz/HP8U/yX/O/89/zz/Pf8t/wn/5P6u/mb+M/4l/iz+Uf6h/gX/Zv/J/yIAUQBcAE0AFAC4/2D/Fv/P/pv+j/6c/rn+9f5D/3z/m/+y/7b/o/+P/4r/hP9+/4X/j/+G/2v/RP8E/6v+WP4W/tP9jP1n/Xf9q/3u/Tj+gP61/tb+4P7L/pT+SP7u/Zv9Z/1S/Uf9Tf1x/aT9yf3b/d790f3B/b79w/3M/eL9Av4j/kz+hP64/tj+6P7o/sr+oP53/k/+Lv43/mz+s/77/k//of/d/wgAKgA3AC8AIAAPAPX/4v/d/+b//f8vAG8AogDTAAcBLAE0ATQBOgE4ATQBQgFMATcBIAEiATIBPAFEAVABcAGuAekB6wHPAdIB6wHyAfgBDgIcAiYCWwKsAuMCCANCA4oDzwMLBC0EMARGBHsEqgTPBA8FUQVsBYgFywX6Bf0FDQZMBpoG8wZeB70H8gcICPsHrwcoB4EGxwUOBXwEIAT8AyMEnQREBe0FfwbhBvoGuQYZBiUF/wPQArABugD+/3f/If/+/vr+6P60/nD+J/7J/UL9qvwh/Kv7NPvA+lf64vlT+cL4NfiP99j2P/bW9ZD1a/Vo9YD1sPXk9fH12vXK9bH1Y/UN9er03fTE9Mj0BPVZ9b31KvaB9sT2Ffdh94D3kfey98f31fcL+Ff4k/jk+Gf5/PmY+lP7E/zH/I/9Yf4D/3n/5P8oADgATABsAHQAgADCACABgwEOArcCSgPaA4IEDwVgBZ0F1wX6BRIGKAYrBi4GVAZ/Bo0GlAamBqEGkwaYBpkGfwZpBmkGaAZqBnkGfgZwBmYGWgYwBvAFqQVRBfIEtASUBHYEWgRJBEIENQQaBOkDoQM5A7MCJwKsATsB2wCyAMYA8gAsAYABygHqAecBuAFBAaAACQBy/9X+Yf4z/ir+Pf58/tj+Mf+C/7b/uP+h/4X/Uv8N/9z+xP6y/q3+uv7H/tj+8/4E/wj/EP8U//7+8P4H/yb/Mf8+/1f/dv+j/9X/7P/3/xcAMwAwAC0ANAAjAP//8f/m/8n/sP+v/7D/tP/U/wAAIQA9AF0AdwCLAKQAswC1ALEApgCVAIYAaQAzAAMA9v/q/8f/rv+5/9D/6P8NADcAXwCJAKgAqQChAKAAiABIAAMA1P+s/4D/Wv9J/1L/bP+H/53/sv/C/7z/nv9y/0H/DP/h/s3+x/7K/tv++v4a/zP/RP9C/xv/0P53/iT+3P2h/Xv9bP11/Zb9u/3R/eD98/39/fH93v3Q/cf91f0A/ij+Nv4z/iz+Ff7p/a79bP0p/fP84Pz7/ED9pv0j/p/+BP9C/1v/S/8O/7L+U/78/a79f/2L/cz9L/6s/jT/rf8UAGUAggBkACcA6P+p/2P/Mf8u/0r/d/+5/xAAagC9AAcBRAFsAYABfQFoAVUBUgFHASsBGgEkAS0BHwEnAVYBewGGAacB5wEPAhsCKgJBAloCbwJtAlwCZAKJAqsCxwLoAgUDIQNAA14DgQOxA9wD9wMjBHQEwQTqBAoFKwUtBRgFGAUXBfAE6gRABbMFHgaiBi0HjQfGB9gHmAcSB3wG0wUQBW4EFgT3AwsEYgTgBFwFzwUoBj8GAAaEBdAE6APvAg4CUwG8AEMA3f+T/2T/Nf/w/p/+Qf7K/Un9yfxJ/ND7avsD+5H6I/q8+Uv5zPhI+Lv3MPfM9pD2XfY09if2KfYh9gz26/W/9Y31TfX29Kj0fvRb9E70ffTN9Az1VPXE9Tf2mfbt9if3QfdU92f3dPeG96D3uPff9zX4t/hJ+e35vPqr+478Xf0O/pD+7v4+/2j/av9y/4z/r////4IABwGYAVgCHAO5A0EEtgQBBS4FVAVzBZgF0QUXBmUGwgYdB1wHdwd/B4EHgAd/B3QHXAdMB2UHngfVBwAIFwgGCNsHrAduBxgHxQZ5BjkGIgY7BlwGbgZ6BnsGVAYDBpAF/gRRBJ4D+AJqAvgBsQGdAbcB6QEeAlQChAKNAlYC8QFtAcwAJACE/+v+cP4f/u796v0j/nT+tP7u/h7/I//+/sf+h/41/tj9gv1D/Rz9Cv0V/TT9Vf12/Zb9tv3Y/fT9+f37/RT+NP5X/oP+mP6O/o3+lv6S/pD+mP6X/p3+v/7m/gv/Qf97/6v/3P8GACYASQBrAHMAZQBSAEMAQgBQAF4AYwBlAHgAnwDBANIA6AALARwBEwH5AM8AqgCXAH0AZQB2AKsA4QAXAUoBZAFgAUwBIwHeAIoAOwD2/8H/nf+S/6P/yf/z/w4AGwAmAB8A8/+v/2r/L/8H//X+5v7Q/r7+uf6w/pD+Y/48/gT+u/2R/Y/9h/16/ZL9vf3b/f39Gf4M/uD9vP2Y/WH9Jv0I/Qn9E/0m/Un9cf2Z/c798P3a/bX9qv2h/Zj9rf3R/fv9Q/6W/s7+9P4M/wD/4P7F/qT+gP5y/oL+uP4R/3n/4f9FAI0AsAC1AJkAaAA/AB0AAwAMAD8AgQDQAC8BigHJAeIB4wHfAdMBtAGaAY0BhgGdAd4BBQL4AfYBEwIWAvQB1gHHAcYB2AH1AQkCHwJAAmICdAJ+AnkCYAJGAjcCHgICAgsCKgIuAjACYAKdArgCwgLhAg4DOQNlA5ADqAOqA5oDeQNUA0ADNAMrA0UDjgPcAzYEuwRIBacF3QX4BeMFpAVHBcwESgTkA6QDgwOFA7UDFgR8BMEE9AQXBf0EuQR6BCIEiwP0AogCJgK6AV8BHAHZAIEAJQDm/6//Tf/W/nv+NP7q/Z/9R/3f/G786ftH+6P6E/qY+S/51/iX+Hn4Yfg5+Bv4BPjP94f3Qfff9mL2+/W09W31PPU89VP1afV+9aH10fUF9ib2MvZC9mz2mva09sn26fYG9x73Rvd897b3C/h6+Ob4W/kB+rf6SvvD+0T8vvwX/V39of3o/TT+j/7o/j7/qP8qAK4ANQG3ASAChQL9AnID1QM+BKYE+ARQBbgFDwZKBoAGtAbcBv4GKgdmB6YH1wcBCCwISwhgCG8IbQhiCF0IVAhACDQIKwggCCkIPAg+CDoIOwgjCO8HrAdSB+oGjAYwBs8FeAUjBc4EjQRmBEsENwQaBOkDrwNqAwYDjQITAp0BNwHZAHQAFwDV/5b/Uv8i//7+xf57/jb+9v2u/WT9Kf0A/eD8yvzH/Mn8vfyn/Ij8VPwc/Pb72vu8+6T7m/un+877Bfw5/Gf8ovzn/Bf9JP0c/RX9G/0n/S/9O/1i/Zr91f0h/n/+0P4P/0n/ev+e/8f/5P/r//v/JABPAGsAiwCxANcA+QAfAUABSwFDAUcBWAFgAWkBhAGnAccB6AH3AfkBAAIAAusBzAGkAXYBVgE9ARsBAwEBAfsA9gAHARkBEQH8AOEAtAB5AEEAEwDr/7//k/98/2//Xf9Q/07/QP8j///+2f6y/oL+Sf4e/g7+/v3g/cX9t/2l/Yn9aP1L/Tv9Mf0q/S39Ov1L/WL9df1r/U79Ov0e/eT8rPyd/Kf8u/zl/Cf9Zf2i/ff9RP5f/lz+Yf5c/kL+N/5L/mb+gv6t/ub+G/9W/5z/2/8HADkAbwCPAKQAzQD1AAEBBAEQARwBJAEtATQBQQFnAaMB4wEYAkoCfwKtAs0C3wLeAsACnQKFAmMCOAIeAgoC5gHEAbYBrAGvAcQB3AH0AR8CVAJ3An4CagI9AgECwQGFAVABKgEfASkBOAFOAXwBtgHfAfQB+wH6AfwB9AHYAcYB3gEDAh4CRQJ9ArEC1QLwAgEDCQMRAx0DIQMeAxwDHgMdAxoDGQMYAxcDGwMlAywDNQNLA2ADZANUAzgDEwPuAssCnwJrAjoCFwLyAcYBnAFvATgB/wDSAKUAbgA0AAIAzv+V/1r/H//W/oP+NP7l/Yz9PP0H/eH8ufya/ID8Wfwf/Nb7hPsr+9H6dvog+tn5p/mK+X75e/l6+Xr5cflb+T75Ifn/+NP4qPiE+Gr4VfhF+EL4R/hN+Fj4bfiH+KX40PgG+Tv5bPme+dj5FvpJ+mT6d/qZ+sv6APs0+3H7wvsc/Gn8sfwC/WP9xv0g/nn+z/4j/3H/uP8CAF0AwwAmAXoBxAEMAloCswIRA2YDrQPyAzkEewSvBOUEJQVnBacF5AUYBkEGaAaPBrEG0wb9BicHRgdeB3gHkAecB5cHewdMBx4H/QbfBrMGiQZzBm0GawZwBncGcgZYBi8G9AWoBVcFCQWwBEkE7QOuA4EDUgMkA/kCyQKKAjsC5wGPATYB4ACSAEYA+/+z/3L/P/8c//r+zf6j/oP+YP4t/vf9xP2S/WH9OP0S/e/81vzI/Ln8rvyu/Lb8ufy6/Lz8vfy8/Mb81Pza/OD89PwN/Rr9Jf06/Vb9dP2T/a/9yv3x/SL+U/6B/rP+4v4J/zL/W/9z/3T/bP9o/2n/d/+U/7P/yf/q/xwARABfAH4AogCxAK0ApwCfAIwAegB2AHgAegB3AHcAfQCHAIoAgABtAFoARwAyACIAGQAKAO7/1P/H/7v/rP+g/4b/Wv8v/xf/B//s/sn+rP6g/pz+k/6E/m/+X/5P/jn+Gf78/en93/3Z/dj90v3K/cr9zv3P/dL92P3Y/dX91P3V/dj95P37/RD+KP5J/nT+mf6y/sT+0f7W/tf+2P7Z/uL+//4m/0v/cv+q/+3/LgBsAKUA0ADsAPwACAETARcBGgEoAUMBWwFsAYYBqwHLAd0B7QEHAiACLwI4AkgCVgJWAk0CQwI+Aj0CNAIhAgkC7QHRAbwBswGmAZMBhwF/AXQBbQFmAVUBPwE1AS8BHgEGAfAA2wDEALUAsgC2AL4A0gDuAAYBIAFBAVoBZgF1AYwBnAGrAcMB3gEBAi4CWwJ/AqYC1wIQA0kDcwN9A3gDfwOOA5UDkQOOA4wDhgOIA6EDxAPeA/QDDgQeBB4EGAQHBOQDugOOA2ADOQMbA/ECvwKVAm8CQQISAtwBlgFLAQsBzgCHAEQAEgDo/7L/fP9S/x3/zv55/in+z/1y/R79yvx0/C789vu1+277MPv4+rn6d/o3+v75yPmS+Vr5Ifnr+Lv4kvhm+DL4Bfjp99b3v/ek95D3kfec9533mfea9533nvel96/3vvfb9wb4Mvhd+Iz4wfj6+DL5ZPmY+dD5//kt+m76vvoN+1/7uPsO/F38qvz7/Ez9mv3r/Uj+qf4F/2j/0f83AKAACQFoAbsBEAJoArgCBgNUA6ED9QNXBLcECwVYBaAF4QUjBmQGnQbIBu4GHgdXB4gHrgfPB+wHAQgWCCkILQgqCCoIJAgVCAwICQgCCPQH5QfUB7kHkAdeBy0H/QbMBp8GbwYtBu0FwwWZBVkFDQXBBG0EFATDA4ADQwP+Ar4CkgJuAkUCGALjAZ0BTwEGAbsAaAASAMP/hP9V/yn//v7g/sn+rf6O/nX+Wv44/hf+9v3P/aP9ef1X/T39I/0N/QT9+fzn/Nz83fzc/NX81vzg/Ov88vz0/P38Ev0k/Sr9Kv0z/Ub9Wf1k/W79hv2Z/Zz9o/25/cj9zP3b/e79+P0J/i7+Uf5m/nb+kf6n/q/+tf7G/tP+1/7i/vL++f4E/x3/Lf8k/xX/Ef8V/xz/H/8b/xz/KP80/0P/V/9k/2L/VP8//yj/Ev/8/vH+9v4B/wr/Ef8Z/x3/Hf8X/wr/AP/2/tv+wP62/rb+r/6v/rv+wf65/qn+nf6b/p3+mf6V/pL+kf6Y/qD+mf6H/oP+jv6b/qX+rf60/r7+1/75/hP/Hf8m/0L/Xf9g/1r/Zf+C/6f/zP/b/97/8v8ZADYAQQBOAGIAdACGAJYApAC3ANEA8QAIARABGAEqAToBPwFGAVIBXAFhAWABZAF2AYwBlgGcAagBrgGwAbkBvwG6AcgB7QEOAiECNQJPAm8ClQLCAu0CDAMeAzIDSwNiA30DmwOyA8sD8wMfBEAEXAR6BJcEtwTRBNUEzgTPBMgErwSdBJwEnQSZBJoEpASwBLEEpgSeBKAEnASFBFsELAQBBNIDlwNcAy0D+gLDApICXgIaAtoBpgFwATIB/ADJAJcAYgApAO3/t/+H/1H/Df+z/lL+AP68/W79FP3C/In8Xfww/AP83vu1+3z7PvsF+8T6d/oz+vb5uPmE+V75OfkT+e/4zPiq+I74dfhd+En4MfgU+Pr35/fY99H31ffk9/b3Cfgf+Dr4TfhU+F74dPiH+Jf4r/jO+PH4I/lk+az5+flE+on6zvoU+1P7ifu7++37Jfxn/LD8+vxK/aP9A/5m/sr+LP+G/9X/GwBmALgADAFlAbwBCQJYAqwC+QI/A40D2gMcBFcElATSBBIFVgWOBbwF8AUoBlIGcAaRBroG4Ab8BhEHKAc8B1IHcgeLB5wHrge7B7kHtQeyB54HewddB0EHIgcGB/AG2Qa9BqkGlAZ4BlcGNgYUBu0FxQWfBXkFTAUfBekEowRWBBgE4AOgA1wDGAPTApgCZAIpAuUBoQFoATQBAAHFAIQAOwDt/6X/Zv8o/+n+sv6F/lj+Kf76/c79rP2S/XD9Q/0V/fL82fy8/Jv8gfx3/G38W/xR/FL8VfxX/F78YPxY/FH8S/xK/FD8Wvxh/Gf8cvyH/KD8sfy4/MX83vz4/BD9Lf1H/Vj9Y/14/Zv9uf3B/cX93v35/QD+Af4R/if+Ov5W/nn+mf60/tX++f4O/xX/H/82/0j/T/9U/1j/WP9g/3b/kP+g/6n/tf/I/9j/3P/d/+T/5//h/9n/2P/c/9//4P/a/9D/zP/R/9T/z/+9/6n/l/+B/2j/Vf9M/0j/Rf8+/zX/MP8z/zT/Kv8R//X+5f7h/tT+tP6Z/pH+kv6L/n7+d/55/oD+gv5+/nz+hv6a/qv+tv7G/t/+8/4C/xX/K/86/0P/U/9o/3j/if+n/8r/5v/6/xYAPABeAHQAhQCRAJwArQDIAOUA+gASATcBYwGKAbcB9AEyAl0CggK5AvkCNQNnA5kDyQP4AyoEZASdBNAE+QQhBU8FfAWgBbUFvwXHBcoFxAXGBdUF3wXYBdQF4wX0BfgF+AUEBhMGEgYFBvUF3AWnBV8FGgXgBKYEYgQbBNgDmgNeAyYD7QKuAm0CNwIHAtIBlwFbARsB1wCVAFUADgC//2j/Dv+2/mL+Ev7A/W39Jf3z/NT8tvyO/Fz8Jfzr+6j7XvsX+9L6iPo6+u/5qvlw+U75Pfkn+Q75//j5+O341/i6+JT4bPhQ+EH4LPgM+PX37/fy9/b3BPga+C74OvhI+GX4jPiu+Mn45/gR+T75bPmd+dL5APos+lr6ifqx+tr6C/tM+5r76fs0/ID83fxE/aP99/1L/p7+6/43/37/t//u/zgAkADkADEBgwHZAS0CgQLOAgwDQAN1A6UDywP3AysEXASEBLME6wQkBVgFhAWqBdEF/wUtBlEGZQZ3Bo8GsQbSBukG9wYEBwsHBgf+BvUG3AaxBowGdgZiBk4GQQY4BikGHQYZBhAG/gXwBdwFuAWHBVsFMAUCBdEElgROBAoE2AOrA3IDOAMKA9wCowJoAjUCAwLLAZEBWgEpAfYAugB3ADYA+/+9/4P/Tf8V/9T+lf5n/kn+M/4a/v/94f3D/aD9e/1e/UL9Hf36/PD88/zl/M38zvzc/Nr8y/zD/Lv8qvyc/J78p/yw/Lz8zvzg/PT8DP0j/TL9Pf1E/Ur9U/1g/XL9hv2V/aT9vP3b/fn9Dv4i/jb+RP5O/l/+fP6R/pL+kf6e/rb+xv7G/sT+zf7j/vv+Ef8m/zT/Pf9M/2H/c/9+/4f/lP+d/6L/qf+u/63/rf+z/7n/vf+9/7n/uP/C/9P/2P/S/9P/5P/y//b/8//o/83/sP+j/5v/hf9p/2H/Z/9l/1z/V/9Q/0H/Nf86/0L/Pv8v/x7/Dv8A//P+4P7E/qj+kP58/m3+af5p/mT+Y/5v/oT+m/6z/s3+4f7y/gL/C/8K/w7/HP8o/yn/Mf9N/2z/e/+E/5b/rf+8/8z/6/8PADIAWQCPAM4ADQFRAZkB1AEBAjMCawKcAsAC5gIQAz4DdwO/AwcESASLBNIEEgVJBXgFkQWSBZMFmQWTBYIFfgWIBYoFhgWQBakFvgXNBd0F6AXfBcsFtgWeBXcFPgUCBcwEoARzBD4EAwTHA40DVQMVA8oCfAI6AgICywGOAVUBIgH6ANgAsABxACcA4P+Y/0b/7v6d/lX+Ev7T/Zv9av08/Qz92vys/Ib8VfwS/M77mPtr+zz7DPvc+rD6ivpq+k36Ovou+hr6/fng+cf5p/mG+W35Vvk6+ST5Ifkh+Rb5D/kc+S/5N/kx+TH5Q/lg+Xv5jfmf+b/56fkR+i76QfpU+mr6hPqc+rX60/ry+hX7Q/t8+7f78Psx/Hv8xvwK/U39kv3V/RT+Uv6S/tb+Hv9r/7z/DABWAJwA3AAUAUcBegGyAecBFwJLAoYCwgL+AkADhQPHAwIENgRjBIsEqwTIBOwEGQVFBWMFfgWhBccF5gX8BQ0GFwYbBh4GIAYYBhUGIQY2BkAGOAYnBhIG9gXWBbsFpQWKBWkFVAVVBVkFUAVEBUQFQwUxBRwFBgXeBKUEdQRLBBgE3wOtA3wDRAMTA/ICzwKcAmcCQAIkAgICzAGEAUABBwHNAJAAVgAXAMn/fv9L/yH/5v6v/o/+cv5I/iP+Cf7r/cX9q/2c/YD9V/0x/RT9+vzj/Mj8qPyO/If8jfyQ/Iz8ivyW/K78xfzS/Nn84fzn/Of87vwB/Rb9If0p/Tj9S/1i/Xn9kP2p/cf95P37/Qv+Hv4u/j/+UP5e/mD+Yv5v/n7+hP6H/pP+n/6l/rX+1/75/g7/IP87/1T/ZP9y/3//gP99/4T/jv+O/4H/ff+I/5r/rf+8/8T/x//N/9H/zf/A/7X/sP+u/6X/mP+T/5z/qf+t/6b/n/+Z/4r/d/9w/3P/cf9j/1X/Tf9G/zj/Jv8b/xr/Ef/z/s3+r/6b/oz+ff5q/lT+S/5X/mj+bv5x/nb+cv5t/nf+iv6R/pb+o/6w/rD+u/7a/vH+8/73/hL/Mf9F/1v/ff+l/9P/EABXAKgAAAFbAbIBBQJRApcC0wIKA0MDeAOlA9MDEARXBJoEzwQFBUEFewWmBcYF3QXnBe8FBAYiBjIGMgY5BlMGcwaEBocGfwZuBlMGNQYQBt8FpQVuBUIFFgXjBK8EeQQ8BPkDvAOAAzkD6wKhAlYC/gGsAW8BOgH+AMkAoABxADUA9v+4/3D/H//P/oL+Mv7l/aT9cv1J/ST9AP3Y/Kv8d/xB/Ar81Puj+3z7Xfs7+xb79/re+sn6uvq0+qn6jvpr+kT6H/oO+hH6D/r9+fL5/PkC+vz5+vkH+g/6Bfr6+fn5A/oX+ij6MfpC+mX6h/qb+rD60Prt+gD7G/s7+0/7X/t3+437mfux+9z7CPwr/Fb8jfzC/PP8J/1Y/Yb9tv3w/Sn+Yv6o/vT+Nv9x/7L/8/8kAEYAawCXAMEA7AAhAVwBkAG/AfIBKgJcAoUCrALVAvoCGQM7A2MDjgO9A+0DGgRDBHIEnASxBLIEugTKBM8ExQTEBNIE2gTYBN4E7wT8BP4E/AT6BPAE6AToBOkE4QTXBNME2ATeBOME5ATkBOME2gTHBLQEowSNBG4EVwROBEMEJgT9A9QDqgN4A0EDCgPeAsACqgKLAl4CLQL/AdUBqgF1ATUB9AC4AIAAUAAxABUA6/+5/47/aP89/xP/7/7D/o3+Xf4//iP+Bf7k/cL9of2H/Xj9YP1A/Sn9Hv0V/Q39Cv0L/Q79Gf0m/SL9Ef0M/Rr9Jv0m/SP9Jf0v/UD9XP1z/X/9iP2V/aH9qv21/cn92/3i/ej99v0L/h7+LP41/jn+PP5J/mT+gP6T/qT+v/7j/gr/Jv8z/zj/Q/9Q/1L/T/9X/2j/ev+P/67/zv/e/+n/+v8HAAYA///9/wUADwAbACQAJAAjACkAMQA0ADwAUABbAEwALQAVAAQA8v/e/9L/y//A/7H/pP+V/4L/a/9R/zT/F//9/uH+y/6+/rr+rv6c/pX+lP6L/nj+a/5g/k7+Ov4w/jD+Lf4k/hz+Gf4a/hv+GP4X/iD+Nf5Q/mX+d/6Y/sr+//4z/3P/xf8YAGgAvAAUAWQBrQH7AU0ClQLRAggDPANpA5wD3AMdBFIEgASyBOIECgUqBUsFaAV9BZQFuQXjBQkGKAZIBmoGfAZ4BmEGQwYhBvYFvwWJBVgFLQUABdIEpAR4BE4EJAT0A7gDdQMwA+sCpgJoAjcCBgLLAYsBUQEdAeMApABhABgAyf+C/0v/Hf/p/rP+gf5L/gv+xf2C/UD9/fzA/Ij8Uvwd/O37y/u1+6H7iPtv+1j7PfsY+/H60Pq1+pr6gvpu+lT6MPoZ+hr6Jfod+gv6CfoX+h/6Ivow+kP6SfpH+lb6c/qF+on6lfqv+s767foQ+zL7R/ta+3j7n/vE++f7DPwz/F/8kvzJ/Pf8G/1A/W39mv3E/fP9KP5e/pH+yP4G/0n/if/F//b/HwBHAGoAgACQAK0A2QAEASUBQAFiAY8BxAHyARICLgJZAokCrALHAvICJQNIA1wDdwOZA64DtQPDA9wD6wPkA9oD3APoA+8D7gPxA/0DDQQXBB0EJgQxBDIEJwQhBCkENgQ2BCcEGgQYBBcECATzA+ED1APGA74DugO4A7IDqAOZA4cDgQOBA3QDUwM2AyQDDAPfAq0CjQJ1AlMCKQIEAuIBuwGMAWEBQgEoAQoB5gDDAKMAiABwAFoAQwAjAPz/z/+g/2//Qf8d//7+3P60/pH+dv5g/kb+Jf4D/uf91/3M/cH9tf2u/ar9oP2N/Xr9c/11/XL9bP1r/Wz9av1w/X79h/1//XT9fP2L/ZH9kf2d/bH9vP29/cX91/3h/eP97f0F/h7+MP5D/mD+ff6S/qX+wf7d/uz+9v4K/yL/MP83/0f/Wv9l/23/f/+Y/6r/tP/B/9b/6//5/wAAAwAFAAsAFgAVAAUA+P8DABgAJQAnAC4ANAAyADAAMQAxACoAIgAWAP3/4//X/9D/vv+f/3//X/9D/y//JP8U/wL/8v7h/tH+x/69/qr+mP6V/pb+if51/mr+X/5J/jT+Kf4d/gT+6v3Z/c39xv3L/db92P3X/eP9/v0e/jz+Wf54/qD+0P4B/zH/aP+r//H/OAB/AMgAEAFfAbYBBgJJAoMCvQL0AikDXwOSA7sD4QMMBDoEYwSMBLsE6QQWBUwFigXABeMF/wUYBigGKgYqBioGHgYGBvAF3wW9BYcFVAUxBRAF4gSvBHsERwQcBPkD1AOiA2sDNwMCA8UCiwJWAhwC3gGjAWMBGQHRAJsAbAAvAOr/rf96/03/Jf/3/rb+aP4j/uv9tf14/Tv9Bf3P/J38cvxP/DH8F/wA/OP7xPuu+6b7lvt0+0/7Ovsr+w/78vrh+tH6tPqY+ov6hfp6+nT6efp++n/6h/qU+pr6oPq0+tD66Pr8+hL7Hvsi+yn7PPtW+3b7mPu0+8779fso/Fz8hvyo/Mn88vwn/Vz9fP2S/bf97/0o/ln+iv7B/vr+Nv9n/4v/sP/k/xsARABkAIUApQDAAOEABwEpAUMBYwGIAa0B1QH+AR8CPwJoApgCxQLtAhcDPgNXA2oDfQOIA4QDfQN/A4UDigOLA4oDjgOZA6QDqgOvA7wDzQPcA+oD+QMDBAYEAgT5A+sD4QPcA9IDvQOsA6oDrgOpA54DlwOVA5IDjQOIA4cDiQOFA3gDYQNIAy8DEwPyAtACtAKbAnoCUgIqAgkC7gHUAbUBjgFmAUUBJwEBAdcAtACSAGcAOgATAO//xf+V/2X/M/8F/+T+yf6p/or+ef5w/mP+Tv42/hz+BP7x/eH90/3N/c79yf27/az9nf2K/YD9hf2H/Xr9c/18/Yn9lf2q/cH9xf3B/cj90v3T/dX93/3h/dn92/3t/QD+Dv4e/i7+M/46/kn+V/5h/nL+if6a/qb+u/7Z/uv+9P4A/xL/I/8w/0H/Vv9s/37/j/+c/6H/pv+3/8r/0P/M/9L/4//r/+v/8f/6//j/9/8CAA8ADQAHAAkADgAWACcAMwAuAB4AGgAaAA4A9f/Y/7b/kv92/2L/Tf82/yX/FP8B//f++v76/uz+3P7U/sj+sv6d/oz+d/5d/kr+PP4l/gr+9/3n/db9zP3T/eL96v3z/Qn+J/5F/mX+jf68/ur+Gf9N/4v/0v8bAF8ApwDzAEQBkwHdARwCUwKKAsQC9wIbAzQDVAODA68D0gPzAxoERAR0BLEE7QQTBSsFSgV3BaQFxQXYBdcFxQWwBZoFegVRBSkF/gTMBJ8EdgRMBCQEBgToA7oDgwNUAyUD7gK6AosCWQIkAvkBzwGXAVsBLAEBAcwAkABTABkA5f+9/5H/X/8t/wT/1v6Y/lb+Ff7V/Zr9a/06/QP91Py5/J/8ePxO/DX8JPwN/O770fuz+5D7cPtY+0X7Nvss+yP7Evv6+u/67/ro+tb6xvrB+r76ufrB+tf65/rr+vD6B/si+zj7T/tq+4D7kfuq+8z75fv1+xL8PPxg/HX8kfy5/OH8BP0q/Vr9jP2+/fT9Kf5d/oz+vf70/jH/bP+i/9j/DQA3AFcAgwC7AN8A6wD8ACEBSAFhAXcBkQGlAbQB0QEBAi8CSwJiAooCuQLcAvkCIANBA0QDOQM8A0oDTQNKA04DUgNSA14DeAOGA3sDbwNxA3gDfAODA5MDoQOjA5cDiQN9A3YDcANyA3gDcwNkA1wDXQNdA1oDVQNKAz0DPAM+AzADDgPuAtkCyQK7Aq0CkgJuAlECQAInAgIC4gHTAcgBuAGcAXwBXwFFASgBBAHjAMUAoQB1AE8AMAARAPb/2v+2/4r/Yv8//xz/+v7d/sH+pf6P/nz+ZP5I/jT+Lf4p/iP+Gf4Q/gj+AP72/eH9x/21/a39o/2Q/YX9j/2m/bn9y/3b/eT94v3e/dv91P3N/db96v38/QP+BP4G/hL+JP4v/in+JP4t/j7+T/5d/mz+fP6U/rT+zv7Z/t/+7v4D/xH/GP8o/0b/Yf9t/3P/h/+o/8f/3v/q/+n/4//u/wgAGAATABAAFAAWABcAIwA4AEkAWQBlAGsAagBuAH0AiACAAGYAUgBRAFAANgAMAOj/0f/A/7j/rP+K/2T/Vv9Y/0z/NP8l/xj///7m/tX+wv6m/o/+gf5x/lj+Qf4x/iT+FP77/eP92f3U/c39yv3Z/fH9CP4i/kH+Xf53/p7+z/4A/zL/af+k/9v/EwBOAJMA6AA6AXgBtAECAk8CigLDAgQDOwNfA4sDyAP6AxsEOwRjBIwEuwTtBBoFQAViBYMFpQXHBdwF3gXQBbYFjgVrBV4FTwUlBfcE3gTLBKkEhQRnBEAECgTVA6QDcwNHAxwD5gKqAnYCPgL1AasBZgEZAcsAiQBUAB4A6f+5/4H/S/8o/wv/3f6o/nf+RP4G/sj9jv1X/SH97fy3/In8bPxQ/C38G/wW/AD82fvB+7b7mvt4+2r7YftG+y37JvsW++/6xfqw+qj6n/qQ+n/6ePp7+nr6dPp5+oD6fPqB+p36vvrO+uL6Avsb+yr7Qftc+2r7d/uY+8T77PsY/E/8ify9/Ob8A/0f/Un9c/2Q/bX99P01/mj+n/7k/ir/Zf+Z/87/BQA6AGAAeACaAM8AAQEmAVYBjgGzAb4BzgHtARQCPwJuApcCuQLdAgIDIQNCA2sDlAO5A9wD9AP5A+8D3QPHA78D0APfA9wD2wPxAwgEAQTpA9sD2APQA8QDvwPIA9oD5APnA+4D8wPjA8UDtgOyA6EDigOGA48DigNxA1oDTQNBAzMDIwMTAwkDBAP8AuoCzQKnAn8CXQJBAiAC9AHOAbUBpgGUAXkBWgE+ASMBAgHdALsAmgBuAEAAIAAJAOP/rf9+/1b/Kv8B/+b+z/6x/pr+lf6L/m3+Vf5V/lb+QP4k/hT+//3b/bj9pv2Z/YP9cP1z/Yf9k/2P/Yz9lf2c/Zv9of2w/br9tv2s/aL9nP2h/av9p/2V/ZP9qv3H/eD9+v0O/hD+EP4Y/iP+Kf41/kH+Q/5J/lr+ZP5o/oH+sP7Y/u3+Bf8r/1X/eP+P/5z/rP/H/+D/8f/9/wAA9v/0/wIACgAIABMAMQBMAFwAawBzAHgAjACmAKsApACwAL8AuwCtAKIAhgBhAE8ARwAmAPv/5v/U/6//jf94/2H/SP8//zv/J/8N//z+7/7X/rL+kP5+/nn+ZP4+/iv+J/4E/tH9uP2M/fb8CPwk+2n64vnT+Xn6pPsG/Wr+l/9NAIkAegBMACQALwB/AAYBrgFPArQC0AK6AnwCJALiAdcB8AE6AtgCtAOGBDkF7gWqBkoHsgfkB/0HJghXCGQIWghnCHUISgj9B74HawfdBkcG3gV/BRIFxgStBKIEhARbBC4EEwQZBCsEKQQOBNcDeQMCA4oCCQJzAeEAXwDV/zP/jv7h/Sf9d/zn+277EPvX+qn6bfo9+i36Gfr7+QP6MfpP+mX6mfrJ+rj6c/og+rz5PvnI+HH4NvgU+Az4C/gA+Ob3w/ez99f3J/iC+Ov4bvn8+YH6Dvug+xL8Yfym/Nf85Pzn/P/8Gv0y/WL9oP3K/d/95v3R/Zv9b/1s/ZH97P2J/kX/8v+PABkBdAGfAcAB7QEkAnEC4wJvA+wDOARFBCQE7wOlA08DEAP7AvEC5wL2AiADOwNEA1sDewOJA5cDugPtAyAEVwSGBJMEhgR0BFMEEAS9A20DIAPYAp4CbgI8AvoBowFBAeQAlwBVACgAJQBIAHMAoQDdABwBNQEYAdwAmgBbABgAzv+X/4H/d/9h/1X/Yv9q/1X/O/80/yn/EP8N/zv/gP/B/xEAgwAEAXEBuwHlAe0B0wGlAWkBIQHLAHUANAAFAOT/zf/D/8D/vv/E/+D/DgBEAHUAnQC8ANIA5gD3AAEBAAHpALkAdAAmANL/c/8O/7T+df5X/lj+cP6L/pv+n/6h/qP+of6Z/ov+ev5y/n3+nv7T/hj/Yf+Y/7H/sf+c/2f/Dv+l/kP+9v3M/cr98f05/pT+7P4u/1n/e/+i/9n/FwBSAI0A0wAVATwBQwEtAfwAuAB7AFQANQAcABMAHwAxAEMAWwB6AJ8AzQAGAUYBjAHVARoCUAJ0AoECcgJIAggCvQFyATUBBgHgAM4A2gD1APoA1ACSAFIAIAD6/9//0f/P/9n/7/8LABwACQDQ/33/Iv/G/m7+Fv67/WD9D/3J/I38YPxC/CD88vvK+7f7rPuX+3v7Zvtc+1L7R/tF+1H7XPtP+y77EfsP+yr7b/vp+6T8lP2t/tr/BQEYAgsD5AOsBGMF/wV2BsAG4QbaBrUGeAYjBr4FWAUHBd8E9QRgBSgGQgecCCEKogvcDJ4N3w2lDfwMAQzuCvgJMgmQCAIIfQf4BmMGsAXfBPcDBQMYAkgBowArANr/pv+I/3f/XP8Z/4/+v/2+/Jv7bfpi+an4P/gJ+PD31veE99j23/XD9J7zi/Kx8SzxAfEz8bfxc/JJ8yj0+vSs9UH2wPYb91n3mvfh9wn4BPjx9+b31ve09433efeF98/3afhR+Xj6x/si/W/+lf+FADoBxwFHAskCVwPxA4ME+wRIBWgFVgUkBfEEygSnBI4EnQTtBGwF+gV6BtYGBwcZByEHHAcDB9oGvgbEBu4GLgdxB6EHqQeCByEHgQalBaYErQPbAjgCugFeASkBGQEcASMBLAEuASEBBgHqANYAvgCOAEUA+P+s/1f/7/6B/hv+uv1a/Qz92/y8/Kz8t/zY/PL8/vwF/RH9Hf0x/U/9cP2e/fP9af7c/jv/jf/Y/xsAXACQAKoArwC7ANgAAwE7AXkBsgHrATYCkQLqAkwDxgNQBNYEUgXLBT4GqAb2Bg8H5gaNBhgGlgULBXIEywMoA7ACbAJGAhwC6AG/AasBjgFQAfQAlgBAAO3/oP9S//r+oP5R/v79k/0P/YD86vtT+8n6TPrc+Y75Z/lP+Tv5OvlB+T35Pflf+Zr52Pkj+oT64vos+2r7ofvM++v79Pvj+9T74vsD/C38dfzf/FX91/19/jn/5/9+AA0BmQEeApAC3AIFAyMDQANNA1EDaAONA6wD2QMkBHYEvQQIBVoFjwWdBZMFggVwBVMFGwXQBKAEmgScBJkEnwSfBH8EQwT6A48DBQOEAhEClAERAbMAdgA+AAgA2v+m/2P/G//I/mb+CP64/Wn9JP0B/e/8v/xh/N/7PPt5+q759PhX+N73o/e29w74jPgS+Z/5Mfqv+gH7MftS+2P7Vfsi+836c/o5+hv69Pm9+Zz5pPnH+f/5V/rP+nP7S/w8/Sv+Hv8pADkBOAItAyUEHAUYBi4HZgi0CfkKHAwvDWwO1Q8PEdcRRxJ1EkwSuBHCEHAP2A1LDBwLago6CpoKjQsCDdEOsBA9EjYTfhMGE9ERABDEDU4L7wj6BnMFFAS3AnIBVQA3/9r9Nvx/+u74nveW9uH1fPVC9Rj1A/Xq9Ij0tPN+8hLxle837hftPey565zrxevp69zrpetH68TqN+rK6Y/poeki6iDrfewX7t/vyvHD87L1fPcI+U36U/sr/M38MP1g/YH9p/3U/Qv+W/7j/rn/2wAwApgDDAV7BskH6QjeCagKSwvhC4gMPg3gDV4Ouw7sDtkOaA6XDX4MOgvjCZUIdgejBiMG8gUKBkkGdwZ8BlkGCQaIBeoEQwSSA+oCcwIoAsoBLgF5AMr/+/7e/X/8FPvA+Y/4kvfb9m/2UvaL9hD3yvea+GP5BvqB+uv6Rfty+3T7dPuH+6T70fsZ/HD8z/xQ/eX9Vv6L/rP+6f4W/zP/Wv+r/zgAEQEvAm8DvgQfBnIHiQhPCckJ+QnWCXcJDgm9CIQIZwh4CMMIIQlhCYYJogmiCXQJLgnrCKYIaAhLCEYIMQgCCMwHlgdLB9oGKwY7BSwEEQPRAV8A5P6I/U38OftQ+oP5xvg/+Af4BPgR+CX4PPhF+Db4CPit9yb3iPbt9W31H/X69Nj0sfSd9J70mvSU9Kn07vRm9RL28fYL+GX56vpd/JL9kP5i/+//JQAoAC0ASACCAPIApAF/AlkDLAQGBdcFeAbfBiAHRQdPB1IHbAesBxcIsQhnCRQKkwrLCqQKIApVCWAIWAdfBpIF+ASKBEIECwTYA7IDowOPA1AD3gJQArYBFAFkAK7/Cv+X/lP+Iv7Z/VP9gvyE+376cPlj+Ib3/Pa+9sD2FPep90/46fh4+ef5FvoC+rz5UvnT+FT42/d991z3i/fw93L4//iM+RL6jvrv+h77K/s2+1D7efu7+xb8gPwH/b79k/5o/0EAIQHtAZ8COgOcA6YDgwN2A3kDWwMgAwADLAOpA1MEAAWyBZQGvQcTCY0KOQwcDisQcRL9FJYX2RlyGzUc9BuBGt8XURQxENkLwQd3BFkCbgGuASADkwV7CEkLnA0oD6MP/g5lDRYLZwjCBXYDnAExAAn/2P1w/Mz6zvhK9mXzk/At7kzsB+t46pHqIOv46+bsr+0q7kruB+557eDsduxV7ITsBe3N7cDusu9f8JLwUfDF7wbvKO5Y7dTs0ux67c7usPAK89P15fgI/B3/CwKiBMYGlwgXCgkLTAsMC3UKmgmcCKIHwgYWBsIFygUcBrUGjQd0CFkJYgqWC8cM5Q0IDxMQyhAhER4RohCWDxYONQz1CX0HFgXgAuIAQf8h/oD9RP1O/Wn9av1I/fv8Yfx6+3z6jvm++C74CPhG+Mv4ivl4+mD76/vq+2T7d/on+XH3ffWq81LymvGR8UPyoPN39Zb3z/nv+8H9Hv8EAKEALwHBAU4C7gLWAwoFSwZaBwwISQgMCHoHwQb8BVEFDQVnBWUG3QebCW8LJg2DDloPsQ+pD2YPAg+hDnUOnA4AD2EPgA80D2kOCw0WC6YI6AUZA5kAyv7K/Xz90P26/v7/PAEyAsEC0wJdAmgBCgBs/sT8KfuH+dX3H/Zm9KPy7PBu70Lufe1C7Z/tce6H78Pw/vEL897zivQt9db1i/ZL9xr4CvkH+tf6SPtg+zX7z/pF+sn5jvmw+Uj6avsa/TX/fwGyA5YFHAdECAwJgwnaCUkK4gqdC2oMKA2lDboNYg2eDGwL4Qk0CJ4GTQVqBA4EMATCBKcFpAZoB9EH3geOB+0GIQZEBVMEXwOSAukBMgFZAHj/nf7D/eX88vvb+rf5rfjB9/L2cvZz9u72zvf6+ET6ZPs4/LP8sfwf/Cj7BPrh+Oz3TvcU90/3EPg4+Wf6TfvH+877bvvQ+h36fPk1+Yb5Z/q3+2f9UP8mAaQCpwMIBLQDzwKJARIAtP65/Sb94vz2/FD9m/2j/Zr9wP01/gr/RQC/AVcD/wR6BmUHpgdqB8QGwAWYBI4DrQLyAYIBgQEHAi8D+QQ6B8oJogy/DwcTYxaoGXocZB4fH5IeqxxfGdUUkg9YCtIFagJXAKn/QQDkAUgEAQeNCX0LkAymDNELUgpnCD8GNASrAqQBvwCy/2H+rPyG+gr4VPV78tnv2O2G7KHr8+pn6uzpmOmD6YLpV+kB6b3orOjl6HvpZ+qV6xTt7+7z8Lvy+POH9Hj0/PMk8+XxV/DC7nLtoeyC7Cztne7n8Bf06Pfw++//uwMdB/EJLgyzDWcOfg4wDnoNbQxcC20KhQm8CE4IJQgJCAUIRAi/CGkJUgptC4gMkg15DvQO3A5kDqkNhQz7ClUJuAcRBmkE6AKdAY8Azf9I/7r+Av4y/Uf8GvuT+cP32vUk9OzyQPIN8l3yWvMI9Sz3Z/lf+9T8sf0B/tD9Hv33+4P6Efn091z3Ovdn99z3mviY+bL6u/uU/E39Jf5E/6gAUAJVBLgGVgkDDIAOeRC7EVkSahLjEcgQVg/TDXkMgQv8CskKygoKC34L6gslDDMMDQy3C2MLTAt4C88LRgzRDFINug3mDY8Negy8CowIAAYdAw4AJf2p+rb4SPdI9qL1RvUj9Rb19vSz9F/0F/Tk88bzuvOz86Pzi/Nt80Dz+fKc8ifyjfHq8HHwJfDl77vv3u9w8G/x0fJ+9FH2Ovg++kj8MP7U/x0BAQKfAhwDfwPKAxkEhgQSBckFsAaXBzoIiQidCIsIXAgWCMMHjwe9B2IIUwlqCqIL1QzGDWQOng43DhoNfwuhCYsHaAV6A+EBmgCv/yD/w/58/k7+Lv4B/tP9tP2X/Xb9bP1x/VX9AP2K/PP7HPsG+sb4bvcZ9gT1Z/RJ9Jb0TPVs9un3jPkF+wf8dfxr/B38ovsE+1767vn7+Z36sPvi/PH92P6f/ysATQD+/3D/4/6F/m3+lP7u/nL/HQDYAI4BIQJ4AowCbgIuAsMBKQFtAJX/sf7l/U796vzF/AX9rP2S/qv/AwF1AsYD2QSnBRUGDwanBegE4APLAu8BYAEfATsBrAFYAmkDJAWGB2oK8w1jEn4XmRwJIVAkCSb0JQIkQyDzGrMUVg6MCNADfgDA/n7+lv/BAW0E2waXCJMJ1QlgCWAIKAf8BQcFVASqA68CMgE2/7/8xflm9t/yc+9t7Bjqjeig5xjnzOaZ5lzm4uXi5EjjbeHi3wPf6t6i3yvhfeOF5gPqiu3C8JrzAvbc9xL5mflf+XD4Dfdw9bLzEvLx8Hrws/DH8eLz0fZb+ob+NgP5B20MaRC3EygWyhevGM0YRhhoF0IWvxQAE00Rqg/9DWAMBQv0CS4JxgiwCL8I7ghOCb0J+AneCV0JVwjhBkUFpwMFAn8AWf+j/j/+Cf7H/T/9avxd+wT6Ivir9eLyIfCe7Wrrnelm6Avox+iD6svsN++q8SX0kvbJ+JP64/v3/B3+T/9YAC8B0gElAh8CxgEUARMA6v7C/dD8Z/zK/O/9xv9yAvUF+wkKDssRERWyF5QZpRrhGnAaqxnVGO4X+RYSFioVDBS3EjsRgw+aDbYL4gkiCNEGPwY0BmUG0gZ7BzQIzQgICZkIfgf0BSwEKQIHAPD9APxY+gT57vfk9sD1dfQK84Px6O9M7sTsfuu26nXqiuru6tHrMu3X7pHwQ/LR8y71RPbm9g/36vaM9gj2nfV59ZT16/WX9p338/iK+i38qP0H/1kAeAFjAkUDNwRCBYIGAQilCUQLsQy8DUAONw6tDc0MvguZCpAJ1giBCI0I4QhXCdgJTApwCgwKQQk7CPkGlwVhBHcD0gKDAoUCqALEArwCXgKfAaQAdf8U/qP8Sfsl+mX5FPkC+RD5Pflv+Xf5RvnP+Br4UPem9jz2KfZ59iT3Jvhm+bP63/vC/CX99/xl/JH7gPpg+Xz4Bvgm+OD48PkU+0D8Wv02/s7+Jf8q/wj/Gf+B/yQA9ADzAR4DTgQvBXMFGgVHBAQDZQGW/8z9Uvx0+zH7Yfv5+9n8x/27/sT/ugB0AQkCmgIvA8cDSQSmBPsETgV9BYYFhAVvBTgFAQXyBBMFgQVfBskH4QmrDP8PuROhF0UbPx5oIIghVSHBH/McKxnTFF4QHAxfCHkFhgOaArgCdwMmBHcEdwQkBHYDcwIiAcP/1f6U/r3+9P77/qj+8/3M/O/6O/ju9HzxTO6V61DpZucC5j7l6uS25GTkt+O94r/h8OBi4C7gaeA24c7iMOUN6DDrju7e8dL0YfeC+Q/7APxp/GL8H/zC+zf7kvog+vP5/Plf+kP7m/xh/pAA+QJ/BTAI8AqGDeIPCBLvE4MVmxYmF0oXJxehFqQVWRTnEm8REhDEDnINNgwhCyIKNwlPCCkHswUhBHUCqQDv/mb98Pur+tj5cflb+Zb5Cvqh+lr7CfxV/Bf8W/sy+r74EfcV9ePy4vBn73Tu7u2g7Xvts+1j7lHvRfBA8V7y2PPc9UL40fqE/UwA/gKJBcAHOAnMCcEJXQm8CP0HOQedBo4GQweHCBUKtQsrDXAOlw9mEJcQZBBJEHsQ8BCVEWISZBN+FE0VlBVqFc0UhhOjEWoPFg3cCvIIXAccBjkFoQQkBKAD7wLsAZ0AGP9x/ef7r/rN+Uz5QPl1+Z35l/kz+T740PYN9eLydfAz7lLs6uoo6gHqQer06hvsXO127nvvavAq8djxifI88w30IfVo9r73C/k9+lr7bPxh/Sj+zf5Z/9z/cwAXAa8BPQLZAo8DdgSGBYYGgQexCPkJGAsjDB4Nxw0UDioO9w14DfMMdAzUCzoL1gqGCh8KpgkMCVEImgfOBrkFjgSnA/kCUQKtAR4BmwAOAHT/0f4d/kj9Z/yg+/v6fPo0+hH6/fkQ+j36QfoS+tz5h/n++HT45fcx95/2h/a19vb2Yfft94D4Nvnh+RP63vm4+ab5eflf+Zn5JvoO+1b82P1Y/6kApwFFApACiQIpAoQB3gB9AGsAiADUAFcB3wFBAn4CYwKtAZQAhv+i/g3+IP7P/s3/MwEEA8MEBQbABt4GXgaOBZUEbANkAuMB1gEfAtUC0QO0BHIFLQbLBjgHpAdnCMwJ9wvLDvURGhURGL0auxx7HdEcAhtbGB4VmhH9DYUKtgfdBbEE5ANUA78CBQJpAesAJwAq/3L+Mf5a/uf+i//f//b/AAC0/7L+6/yD+sv3OfXz8svwvu4T7fvrWOvY6ivqNekU6Ovmy+Wy5KTjz+JS4i7ieuJS43zkveVD5zbpP+sh7Q/vMfGL8xz2ufgg+0z9Nf+aAG4B4gHxAYwB/gCHABYAtf+g/+L/ZAA1AVoCvANFBfEGuQiYCngMSQ4cEPsRvxM5FU8W8RYWF74W7RXPFJkTQxKwEBkPsA1dDAULpQkhCGkGkwSgAokAff6h/Or6dvmS+DP4D/gB+An4KPhr+MH4APkl+Uj5b/mn+fz5Ofo0+g369vnV+WD5bvgh99L1sfS28/HyhfJw8rHydPO19Bv2Y/eY+OP5Xvvq/E/+lP8CAawCcQQ4Bv0HrglOC9YMGQ73DnsPtQ+1D5UPTA/LDjcOvg1mDSoNAg3ZDLMMogyDDDIM1AuTC3ILeQu7CyYMsAxeDRYOnw7XDqcOCg4TDcYLBwrnB68FkgOXAbz/+v1Y/Ob6nflX+Pb2avXS83TycvGs8Ajwo++V793vX/Dk8DnxcvGs8dXx5fHg8bvxifGO8eHxT/Kz8gjzUPOt80D06vR+9RL21vba9xH5U/pt+1n8Nv0e/hT/FQAXARgCHwM1BFYFcAZmBy0I1wh8CRkKnQr6CjYLgAv8C3IMmgx4DDcM2QtUC6UKwAm1CLIH1AYgBqMFTQXwBIcEIgSxAxIDSQJoAYMAvP8l/6r+P/7x/c39vP2g/Wb9DP2V/Pz7Vfu++jj6svk7+ez4yvjC+L74sviu+Lr4yPjc+Ar5O/lH+VL5kfn1+VP6rfof+7L7R/y3/Pn8Nf2J/eL9Mf6I/u3+V//M/1MA4gBZAZYBlwF4AUgB8wBuAOD/bP8N/7X+a/5N/mb+pf7z/l3/7/+EAAoBmgFDAucCaAPcA1cExAT4BPwEDAVABXcFmwXRBUQG7AasB3kIZwmICskLCA1ADnUPlhCREVgS2BL9Es8SVRKSEZMQcw8tDskMdgtYCloJXwhjB2sGbgVjBFIDRwJYAZEA9f+H/1H/Rf9D/y3/8f5x/pj9hPxc+xn6rfg79/L14vQD9FLzsPIK8nTx/fCE8OjvL+9z7sXtO+3Q7G3sDOy162PrE+vg6tXq3ery6jPruOuA7JTt7e5v8Avy0fOs9Wr3APmK+gD8SP1u/of/iwBpASACuAI+A7AD6gPNA4UDSAMNA8ACeAJSAlACfQL3ArIDiAR8BZUGugfRCOUJ8wrcC5wMTQ3xDXgOyw7ODncO4A0fDRcMvAovCZUHAAaSBGsDeAKoAQoBoQBDAOz/u/+h/4X/eP+Y/9P/GQB7APgAbgHKAQ8CNwJKAlQCOwLlAXoBMgEVAfwAwgBVAML/Ov/G/jP+av2a/On7WPv7+vH6IPtr++z7vfy0/Zr+XP8SAOEAzgGlAjoDuwNUBN4ELwVvBbcFxgV0BfgEdATIA/YCKgKIASEB+ADtAOoAEgGEAQUCWQKPArsCuwKQAm4CbAJ3ApECvALwAiUDWgNtAz0DzgIlAjwBKgAf/yD+L/15/BX80/ua+4D7hft6+1f7Ofss+yr7Qftw+7H7EfyM/AL9Zv3F/QX+/v3K/Z79gf13/aD96/0h/lP+v/5P/7//EwBkAJoApgCsALwAwQC9AMMA0gDyADIBbAF5AYABtQH7ASMCSgKPAtQCBwM0A1QDTgMsAwADwQJ6AkkCGgLHAV8BCQG8AGIADwDZ/83/2P/c/8T/rP+q/6T/fP9S/z3/Hv/p/rT+g/5I/hP+3/2N/Tf9If0m/eb8dfw7/ED8Ovws/FH8qPwA/U/9uf1O/vz+f/+s/73/AgBeAIAAbQBiAFMAHQDq//H/GgApAB0AIwBLAGoATQACAMr/t/+M/yn/v/56/lP+S/5s/p7+uf7D/s7+4P4A/yz/Rv9I/1n/g/+Y/5D/kv+N/07/7/6y/nv+Cv6C/Tz9R/1d/VT9Sf14/fr9qv5J/8r/SwDZAGcB4AE9AnkCnQKxArEClQJYAv8BoAFZASUB4QCLAFQARgA9ACkAJAA3AGAAqgAXAYsBAQKUAjsDzAM/BKME6wQMBR8FMQUpBQAF3wTQBKsEXQT+A5wDKgOiAgYCYwHWAHsASwAoAAoACwA5AH8AvgDwABkBQAFrAY8BnAGFAWABQwEeAdoAggAoALz/Jf9//vz9nv1H/ff8y/zV/Ab9Sv2b/Qj+jv4N/2P/lP+n/4n/NP/T/on+Rv7f/Vv94vyd/JH8nfya/IT8gfyj/MH8wfzF/PH8Mv1e/Xj9l/3B/ez9Ff45/j/+G/7c/af9if19/YL9nv3P/RP+Zf63/gT/Vv+o/+H/9v/y/9n/uP+j/5f/fv9o/4P/vv/O/7j/1P8sAHMAkwC/AAUBOgFXAXkBmQGbAX8BXgE6AQoBxQBtABcA6//m/+v/5v/u/xMAVgC1ACMBhAHPARICWgKPApgCgQJkAkEC9gF+AQIBqQBrADQABgDf/67/fP9s/3f/df9Y/0H/SP9g/3L/df9z/3n/i/+Y/6H/vv/o/wEABAAOABYA9f+t/2f/Nv8P/+v+y/7A/tb+/P4O/xf/O/9t/3r/bf9+/6v/0f/4/zYAdwCpAOQAJQFKAVwBiQHMAfcBDAIwAnECvQIKA1ADiAPBA/wDFAT6A9gDzgO7A4YDUQM2AxUD4AK9AsECvwKeApACtQLdAucCAANWA7ID1gPQA7wDkANJAwMDsgI0AqMBRQEMAbcAUQAQAOv/t/97/07/M/8s/zr/O/8i/yL/Vv97/2n/Tf86/wH/pv5w/lP+BP6l/Yb9hf1T/Rz9Of17/YD9Uv07/Tb9Ef3F/ID8ZPxg/FL8LfwO/Bb8OPxU/Gz8kPy1/Mr86fw6/af9+f0m/mP+uv7w/uj+3f76/hT/+v61/mL+Bf62/YL9Rv3x/Lv8z/z8/Br9SP2Q/c79Cf5z/vr+Wf+d/wAAgQD0AFABkgGtAbkB1wHhAZwBLAHgAMkAvQCiAH0AXQBeAIIAoQCdAJEAkQCMAIgApADXAPQACgFSAccBIgJBAkkCVgJbAkUCGQLiAZ4BSQHxAK4AkwCJAGgAHwDE/3//Vf8r/+3+u/66/uX+H/9X/5D/yP8CAEQAfACDAFgAEQDF/4b/ZP9C//b+iv4x/uz9kv00/QP97/zD/Jn8t/wd/YT9w/3s/Sb+dP60/rv+oP6h/sn+4v7f/ur+Ef9B/3f/uP/1/ygAbwDBAPQADgFGAY8BpgGQAaAB/AFbAmoCOQIXAiICKgIMAuABxQGwAZ4BrgHjAQ4CIQJGAqMCJwOnAxUEewTjBDsFbwWTBcIF1QWVBSsF9wQABe0EnARBBAwE+QPtA8cDaQP1ArcCtQKgAk4C+QHeAe8B8QHcAdIB1wHKAaQBjAGRAZEBdwFYATcB/gC0AHkAOgDT/1D/4f6L/jv+7v2c/Tr90vx+/EL8CvzY+7f7pPuf+7H70vvw+wz8L/xP/GX8ePyD/Gr8Pfwq/DX8K/wN/Az8Pvxu/HP8XvxT/Fj8W/xG/Br87PvL+7H7k/uP+8f7NPyj/Pj8Rf2r/R3+jf79/nr/6P8wAGoAswABATUBUQFfAVUBOQEWAdsAgwA4ABgAAADW/8//CQBHAG0AtQA4AacByAHKAewBIgJDAj4CJAIRAg4CBgLgAZ8BSwH0AMcA0wDXAJEAIwDd/8P/mf9D/9z+kv50/mT+O/4Z/jn+i/7O/vv+Mv9v/5P/pP+u/6f/qv/Z/wYA9f/P/+T/FwAQAMv/i/9T/wj/yP69/sP+qv6Z/tj+SP96/2j/jP8eAKwAzAC/AAMBjgH4ASUCWQK+AiwDcwOLA4sDjQOfA7YDqANbA/wC0QLcAsYCaAIXAhYCMQIZAvYBBQITAt8BsQH0AWICdAJAAkECjgLOAuIC6QLwAvUCBgMKA9MCeAI2AgsC1gGbAV4BBAGbAF0ATAAtAOf/i/8x/wH/D/8T/8X+Yf5b/qL+1P7U/sv+y/7Z/gP/Nf82/+7+f/4p/g/+Bv61/Sj90vzX/Mj8Yvzr+6r7j/uF+4j7k/ui+7775fsb/IP8Ev1y/Xz9d/2v/Qb+Kv4C/tP99P1D/kH+5P3O/Uv+2f4F//7+Bf8U/zb/dP+T/37/g//I/wcAOgCdAAoBJwEUAU4B2QFUAoICegJ7Ar0CNgOEA3EDNwMeAyYDNANHA1kDUQMiA+cCxAKqAmAC5QGHAXkBhgFoARoBuwB8AIsAwgDDAH8ARwAzACkANwBgAFcA///G/9v/3v+J/wT/hP4h/vv96/2M/fn8sfy8/K78hPyA/I78bvxA/Ev8jPzM/OT86fww/d39g/6v/pr+s/73/jX/Yf91/2r/eP/E/x0AWACOAL4A1gAbAa0BHwIpAiYCaQLAAvYCBgPhAqACmwLTAuECxALMAuMC3wIAA2gDrQOdA48DrwPdAxcEQgQGBJEDewO4A6IDMAPqAs8CggITAsIBeQEkAeEApABPACMAQwBLAPP/kP97/3v/QP/b/or+W/4s/vH9z/3z/Sz+FP6l/Un9QP1c/VH9+vx//ED8X/yC/Fj8GfwS/CD8GPwu/Hr8r/yr/LD86fwk/Ub9ef3E/QD+Hf4x/kb+Yv6V/tD+7/4A/y//b/+N/5n/xv8EABwAFQAqAGkAqQDGAL0AvwACAV8BfAFxAbABKQJfAkkCWAKnAvMCKQNIAzMDDAMzA4IDcwMKA8YCugKZAlECDwLoAeYB7QHFAYEBgwHEAcQBZwEHAc0ApwCnALUAdAD1/8v/AgAXANz/mP9j/xz/3v7Q/tb+p/4t/rf9tv0b/i7+lP3r/NX8IP1f/W39O/3X/LX8Bv09/fn8qvy1/On8FP08/Tj98vzI/O78Ev0J/fj82/y1/O78if3N/Xr9Vf3V/W3+nP6L/n7+jf7m/pT/KAA6AAMAFgCWABsBPAEaASwBmgEUAkkCLALmAecBggI0Ax0DYwIjAsACXgNiAyUDHgNCA2YDkQOqA4gDPgMhA3AD7QMLBKADKgMlA3gDyAPaA5IDFwPcAgQDGwPJAk4C9QGvAXYBUgEdAbkAYQBGAEgAMQDt/3j/G/87/53/iv8A/8T+Ef88//L+lv52/m3+XP5J/ij+6P2k/Yv9rP3g/ev9xv2z/cv91P2j/Wf9T/1c/XT9dv1W/Ub9bP2J/WX9SP2C/eD9Gf44/lr+i/7w/nH/n/99/7v/fQDvALEAdAC5ABYBHgEAAf0ABwECAe0A6wAvAZYBngEuAesAQwG7Ab0BcQFWAYsB0AHlAcIBoQGzAdoB5QHOAakBggFwAYIBkQF7AWABSgETAegAFQE9AccAHQA1ANUA1wAPAI//1v87AC8A+v/0//f/3v/R/9z/xf9x/xb/7P7v/gL/Bv/c/pT+if7m/kT/L//L/qP+8f5m/5j/X/8M/xj/ff+n/13/JP9Q/4P/eP91/5f/hf81/y3/kP/W/6n/XP9U/4T/rf+2/6z/ov+x/+P/GgAsABoAFQA7AG0AcwBOACwAJgAwAC4AFADt/73/if94/6z/3/+k/y3/Lv+6/xMA1P9z/2j/pP/u/xsA9P+B/y7/PP9s/2r/Lf/d/rj+3f4f/zv/PP81/wb/xf7W/i7/Qf/6/tj+Df9e/6f/0f+x/3n/mP/k/9L/fP9q/5b/o/+U/37/Rv8l/2L/nf9w/0P/i//W/6H/Tf9t/9L/CQAHAAkAKwBrAKIApwCWAK4A8wAmARkB3AC6ANYA5QCpAH4AuQDuALQAcACWANIAzwDVAAAB/wDhAAABMgEuAUEBmwHCAYQBaQG8AQMC4gGWAWsBcAGSAa0BlQFaAScB+wDnACABcQFOAcoAkwDRAAQB8QC4AGMAGQAqAH0AkQBJABMAMABcAFIAEgDJ/5f/hf+F/53/z//m/7L/bv9r/33/SP/w/tL+4/7V/rP+vP7c/tL+uP7M/vj+D/8R/xD/Hv9T/5L/ov+E/2H/Uv9s/5n/rv+t/6//rf+x/8//7P/6/wcACAD8/xMARQBDAAUA0f/V//3/AADR/8j/EQBbAHIAawBaAGwAwQAGAeoAmwBzAJcA3ADiAJMAVgBUAF0AhAC0AGsAv/9+/7z/2f+p/2z/Nf8a/0z/qP+7/2r/L/9U/3f/WP9B/0r/MP8P/zX/df9t/x//zv7c/k3/b//X/kX+e/7v/sf+VP5J/oD+hv6J/q7+p/5//qr++f79/uX+Bf82/13/kv/G//f/NQA8APb/5/9AAFwA9/+4/+7/EgDo/+j/MABJABMA8P8NAE0AggCNAIgAsgD3ACIBOgE2Af8A1AARAZgB2AGKAS4BWgHEAd0BvQGYAWoBigH/AQcChwErAfYA2ABEAcUBbAHNANYAJAFkAb8BmgGyADQAzwCIAVgBfgAHAHcACgH4AKsAlgCAAGMAWAAkAPH/BAD4/7H/yv8cAOf/Z/9e/7T/6//R/3L/Jf9g//b/IQCh/x7/N/+0//z/x/9C/+T+Cv9s/3//Mv/W/rr+Av9b/2D/Rf9b/1z/Ov9k/8n/8f/Q/6r/t//6/wYAo/9e/5n/4f/o/97/yv+t/7L/wv+q/5j/rP+q/4P/e/+k/8//4f/d/83/zv/z/xEAAADp/+P/3/8DAFAATQD1/8n/zv/U/w0ARwAGAKP/mf/E/wsAQQDo/0z/Tv/O/zUATwDq/2b/tv9bABEAYv9g/5//oP+s/8X/2/8DANT/Wv9Y/6T/ff8u/0n/m//q//X/cv8T/5b/NgAHAH//U/97/8L/7v/J/4z/mf/S/8r/fv9R/1//Vv8v/0H/hP+V/3b/eP+2/wgAMQAZAAIAQgDPACEB1ABbAHcABAFNAR0BswBgAHcAzwDIAI4ArQDPAJEAewC0AL0AtADeANAAbABXALAAxgB1AFUAjgClAJYAtgDPALQAzwDxAJAAPwCgANcASADR/+P//f/+//b/wP+K/6D/wf+B/wX/+v6d/xwA5v+w/+H/6f/Q//f//P/S/+H/y/94/7L/HACx/yT/hf8kAB0Awv+1/ycAjQBDAL7/1/87AEgAMQAjAAEA+f8vAIAAyADPAJsAnADVAPAAFAFOASABtQC+ACgBfAF0AewAaADAAGwBLQFVAB0AigDBAIQAOQApADwARABEAEAAIQD+/w4AOwA2AOX/iv9u/5T/0f/f/3//+/74/oH/2P+S/xL/7/5C/4H/Wv8o/xX/2f6r/tP+9f7l/rv+Ov7W/X/+Rf+4/ur9XP44/1z/Cf+w/o/+1/4W/wH/D/9B/yf/8/7w/vz+Af/l/rn+/f6K/4b/If85/6f/0//C/7v/7/9JAEAA2//d/zUAMAAOAFcAoQBkAAMAHwCLAKEAYQBTAF4AMQARAAcA3f/4/20AewBWANIASQHtAJgAAQF6AXcBLgHqANwA5gDUANAAygCRAI8A3wC8AE4AgQDSAFUA1v8rALcA9AAEAc4AewCgAAYB/AC6AKwAaADG/4P/6/9PADUA4v/B/+//EQDK/3//sv/2/9v/rf+b/4r/nf+x/4r/kv/g/9b/n/+2/5P/MP9e/7b/df9M/5X/nf9z/3r/Yf9v//b/EwCR/4r/BQAUANX/0/8cAIwAogAXAKv/0//z/+H/EgBYAE8ANABQAJQAugCHAEYAhwAPAR0BrABmAKQAEwEwARQBIgEzAQwB7gDnAL0AigCGAJMAqADGANgA6ADIAFIAHQCQAOYAmQA3AC0AeQDpAOYAYgBNALoAowAXAPj/FADk/7L/m/9S//X+zv7L/tr+7f7o/uj+Cf8B/7r+uf4x/3//Nf+//pb+v/4N/zT/Af/B/rn+sP6S/p7+uf6//tH+5v7d/tH+yv7f/jz/c/81/0v/6f8FAIr/a/+a/7P/+P8nANv/y/9CAG0AKAAFAAUADAAnABEA2f/w/0oAlgC5AIkALgAwAGUAVAA/AHQAtADdAPYA8ADuAOcAowB4ALgA5ACnAIEAsgD2AA4B0QBlAD0AWgBuAIoAsgCPABQAuP/f/20AwQBtAOX/x//z/xEAEgD7/+z/EQBEAFsAUAAMALr/1/9KAGgAHQD1/xYANQAoAPL/qP+I/8z/KwAcAJr/Nv81/1n/cv9z/2b/df+e/6H/hv+X/8L/xf+p/7D/9v88ACoA8f/+/ysAGQDr/9z/5v8VAH0A9gBcAYwBcgElAbkAPwAHADEAWABFACIAAQDm/+T/4P/p/yQANwDc/5T/qf+7/7T/7f9dAK8AqABqAHUA0QDcAHAAKABNAJoApgA0AK3/nP+e/1j/cP/y/9z/J//S/vn+Lf91/8f/7P8SAFIAZgBAABQA/v/4/+//yP+g/5z/s//S/9T/if8v/yj/T/9M/z//W/9z/2j/Y/9g/0P/Vf/d/2sAZgDr/5X/qf/l/93/mP+U/+H/9v+9/8P/HABYAE0AGADb/8H/tP+S/5v/2f/k/7z/0f8gAFkAcgBsADwAAwDp//z/RwCRAIQASgBFAFwAPwD+/+f/BgAUAOT/sP+7/+3/GAA0AEwAbACZAL8A4wARAQsBnAAHAMH/5/8gABkA8/8XAHgAqwB+AA8Ao/+e//v/OgA5AD8ASQBSAJgA9AD7ALwAlQCZALAAsQBnAP3/3v8gAIMAuwCWACUAyP/E/woAZQB/ADYA6f/q/woAAwDy//v/EgAfAA0Ay/9//2v/lf/X/yMAbACTAJoAjQB3AHQAjQCOAE0ABwAMAFMAiABwADIAMwCIANYA2gClAGoAUABVAFIANwAaAPv/2v/j/yEAYQB/AHkAQgDu/7r/w//m/wgALABLAEMAIgArAHYAtQCvAIYAcgB9AJcAnQB6AEoALQAcAAEA2/+o/2L/Lv85/27/e/9N/zH/Yv+s/8P/mf9T/zD/ZP/T/wkAzv9r/z//U/9x/2//V/9N/13/Zv9Z/2T/mP+w/2//E//4/h//R/9X/1L/NP8J//b+Bv8l/0n/av99/3//dP9a/0L/Vf+Z/9X/3//R/8z/1P/w/yMARwApAOL/uf/J//D/BQD+/+3/+/8hACwADQD7/xUAJAAHAO//CQBCAG0AfAB1AF8APwAUAPb/CABEAF4ANQALABkAMwAqACAAMQAzAAoA5f/1/xgADQDE/4L/mf/+/0gANwAMABQAOwBDACoACwDv/9//7/8EAPv/3f/W/+H/3f/E/7H/qf+r/7P/tf+x/7j/yP/W/+v/DwAZAOv/tv+v/7f/mf9w/3z/s//V/8T/nP+G/5X/pf+S/3f/i//G/+L/1f/Z/wsARABQACgA6P/E/9X/8v/f/5//YP85/zT/XP+W/6j/jf+P/9T/JwBFADEAKQBbALMA5gDWAL4A3AASAR8BCAHwANIAnQBqAFQAUABEAC4AFgAIABIAJgApAB4AHgAkACIAJwA/AFMAVgBhAHwAgQBjAE8AbACrAOgABAH9AO8A8ADqAMMAmQCQAJcAfAA/AAMA4v/j//H/4f+i/2z/cP+O/4r/cP9x/5//2f8BABQAGAAdACYAPwCAAOMAFwHfAHsAWACDALEArACCAFMAPABaAJkAugCVAEsAGgAiAEEANwD2/8T/4f8pAEsAOAAnAEEAeQClAKEAdQBlAI8AsAB/ACkAGABWAIIAXgAcABEAQQBNAPj/gP9S/3n/oP+U/3j/Z/9b/1D/Tf9E/yn/Gv8t/0j/S/8+/0b/bv+Z/5z/df9a/3P/oP+i/4D/af9p/2v/af9w/3z/f/95/2r/Z/+C/7X/0//K/8X/5v8SACgALgA/AGEAhgCgALgA5gArAVkBVgFGAVgBfgGMAYQBfwF+AXIBXwFRAVMBZAGCAacB0AECAjACRAJCAkMCSAJKAksCWgJ0ApECrwLCAsQCxQLXAugC3wLHAr4CwwLCArgCpwKVAnwCUgISAtMBrAGKAUsB+QC6AIcAMwC//1v/I//3/qz+Q/7i/aP9df0y/eD8nfxl/BX8svtw+2j7cPti+0H7I/sL+/v69vrz+uL6vPqR+n76jPqa+oH6Ufo9+lL6ZPpd+lD6U/pc+lz6Wvpf+m/6h/qh+sT6A/tc+6374PsQ/Fv8w/wr/Yb94P1I/sf+R/+p//P/RwC3AC0BigHGAfgBNQKAAsoC+AIMAyEDQQNeA24DgQOeA7sDzQPXA+ID9gMRBCQEMARCBGEEfgSTBKsExgTiBPwEEwUXBfgExQSiBJoElQR5BEYEDgTUA4wDLwPRAokCSwL1AX4BCgG0AHsASgATAND/hf9A/xD/8v7d/s/+zf7e/vb+//7w/tr+2f7o/uz+2v7A/q3+m/59/lj+N/4d/gP+5f3N/cj9yf3A/a39q/3F/eP98v37/Rb+UP6X/tX+A/8w/2X/nv/T//3/IgBFAGsAlQDFAPYAGwEnARoBBwEAAQcBCgH9AO4A8wAQATABOwEtARwBGAEgASoBMQE5AUYBUQFOAT4BMAE0AT8BOQEWAeYAyAC/ALsAqwCPAHEAVQA2ABAA5v/D/6//sv/F/9T/y/+z/6r/tv++/6X/ev9k/3P/hf93/1P/Rf9l/5j/sP+d/3D/RP8r/yv/Ov9J/0r/Qf9C/0//XP9g/2L/aP9w/3L/c/94/4H/ff9h/zb/DP/y/ur+7v70/u3+3P7P/tT+5v73/gr/Mv91/7b/1v/U/8z/0v/h//P/CwAvAE0AVQBKAEEASABVAF4AZABoAGQAVgBIAEYATABTAGEAgACqAMkA0gDUAN0A6wDvAPQADwFBAXMBmAHAAfcBLwJZAoECwAISA18DowP8A3wEBwV1BdEFQwbRBlkHwQcjCJ4IKQmeCe8JMAppCnwKUwr/CaYJSwnLCBQINQdKBlsFaAR1A4gCmgGcAJX/nP6//fn8QPyZ+w37ofpR+h76Bvr++fn59fn++Rr6O/pL+j36C/q6+Vn5+fiY+Bz4cPes9vf1XvXF9BH0TPOU8vfxZPHY8GbwHvDz79zv4u8b8IvwG/G98XbyTvM69C/1LPY190D4Pfkw+iz7Mvwr/QT+wf5y/xoAsAA2Aa8BFwJgAosCswLwAkUDpAMHBHEE3AQ2BYEF2QVRBtUGQQeIB8gHHwiHCOcIMAloCZwJ0An4CQwKDQoHCgMKAgr7CecJxQmZCWUJIwnWCIoISAgECLAHRwfVBl0G1gU5BZIE7wNRA6cC9QFPAb8ANwCk/wr/g/4c/sT9av0S/dH8tPyy/Lz80/z6/C39Yv2Z/dj9IP5g/on+mv6d/pn+iP5h/iz+8P2s/Vr9//yp/GL8IPzX+4v7Ufs3+zb7QPtY+5X7APyG/Ar9hf0C/pH+Mf/S/3EADQGhASAChQLQAgsDOANXA2sDfAOKA4sDcwNEAw4D3gKzAokCXQI7AikCJQIlAigCLgIzAi8CIAIQAgcCAwL2AdgBtgGaAXwBTQEDAaMAPADX/3b/GP+7/lj+8P2N/T39Af3G/H/8NfwE/Pf7/Pv8++773/vZ+9375fvs++/77Pvn++f79PsI/Bz8Kvw6/Ff8gfyy/OP8FP1T/aT9/f1O/o/+1P41/6//JAB/AMUAEQFqAbwB9gEbAjkCVgJzApkC0QIVA1EDdwOXA8cDBwRCBGgEhQSsBNoEBgUsBU4FZgVnBVMFMgUOBeQEowRIBOADeQMTA6cCMAK0ATsBxwBbAPX/k/88//b+w/6c/nn+Wf5C/i3+Ff72/dn9yf3C/bL9jP1O/QH9svxq/Cb82/t8+w37oPpH+v/5vPl6+T35E/n5+PD4+PgO+TH5Yvmt+Rb6lvoc+6v7TfwG/cb9ff41/wMA6ADRAbACkgOJBJoFtQbRB/IIGQo7C1YMcA2PDqkPphB5ESwSxxI+E34TfhNDE9sSShKOEZ4Qfg8xDskMVwveCVoIzAZDBc8DgAJdAWwAsP8h/7f+dv5o/oT+sv7Y/vX+F/88/1P/Qv8H/6b+IP5p/Xn8Ufv6+XH4vfbq9APzEvEX7yLtR+uY6RToveak5d3kdeRl5KPkIuXe5dfmEuiL6S3r2uyK7j/w/PGx80f1vfYe+Gn5kvqI+1D89Px5/dX9CP4l/j7+V/5w/o/+yf4j/5H/DACdAEwBEwLjAroDpASlBa4Gswe1CLUJsAqeC3UMMQ3VDWQO4A4+D3gPjQ+KD3cPTw8QD7oOVQ7hDWANzQwsDIQL1wofClMJcQiGB5YGnwWlBLcD3gIQAkQBgQDT/zz/tv5A/t79kP1M/RT97/zq/P/8Iv1I/XP9qv3o/ST+VP53/ob+ef5S/ib+//3P/YH9IP3F/Hb8IPy3+0779/q1+oD6Y/px+qv6CPt9+xL8zfyr/aT+q/+6AMkB0QK/A5IESwX2BYsG+wZHB3oHlQeMB1QH/AaTBiAGnwUMBWwEzANBA9MCcAIOArwBjgGDAXwBcAFyAY8BsgHCAb8BtgGpAYcBSwEAAagAOQCp///+T/6l/fb8L/xW+4z65PlY+df4Wvj09673jPeL96v35fcv+IT45vhZ+dz5afr0+nn79/t2/Pn8ev3v/Vj+tf4M/2P/uv/4/xEAGQAxAGMAlQC2ANMA/wA1AWwBngHOAfUBGAJGAoYCxQL3AioDawOsA9wD/wMmBFAEbAR6BIgEmwSqBKwEpQSgBJ4ElAR0BD8EBwTWA5kDNgOzAikCqQEjAZEAAQB9//j+Zv7Q/Uf9zfxa/Pf7rPt6+1X7Pfsz+zv7VPt3+5n7u/vl+xf8QfxY/GH8aPxp/FD8Hfzi+637d/s3+/H6rfpu+jj6CPrU+aL5hPmE+Zf5rfnW+Sz6pvon+6P7LfzX/Jj9W/4O/7P/TgDlAHcBAAKAAvwCaAO2A/EDNgSYBPkEQQV+BdIFRwbMBmAHDAjaCNUJAgtdDMsNPw/AEFcS6xNbFZgWohdwGPEYJRkFGYYYqBeCFiMVeBOAEVoPIw3PCk8IugVDA/oA0f7O/Az7qPmn+AP4uvfE9xP4nPhP+Q/6yvp4+xf8ivyz/Iz8Ivx2+3v6LPmZ9831x/OG8Rvvoewx6tLnheVe44HhBuDy3kPeDN5a3h/fSuDc4dbjH+aO6BPrue1y8BzzofUI+FP6cfxU/gUAhwHNAs8DkQQYBWcFjAWYBYwFZAU2BSEFMgVdBaAFCQaYBjwH6wevCIYJYAoxC/sLvwxyDRMOog4XD2kPoQ/TD/QP7A+yD1MP3A5QDrANAA0+DGkLjgq4CdkI3QfQBs8F4QTnA9ACqQF/AFj/Lv4J/en7z/rE+dP4+fcu93r27vWQ9Vb1OfU79WH1qvUX9qz2Zfc4+Bz5Cvr7+uf7xPyP/Ub+4/5k/8D/+P8hAEkAZQBfAEcAOwBGAFMAWgBpAI8AyAATAYQBHgLPAo4DZARdBWcGagdfCD8JAgqlCjALoQvjC+sLyguQCzYLsQoKCk4JhQiuB9UGAAYnBU4EhgPTAi0ClAEXAbgAbwAvAPv/2P+2/4j/S////p/+Lf6r/RD9VPyD+7b69fkt+VX4evew9vX1SvW39EL03/OU83HzfvOz8wv0jfQ29f/13PbL98X4wPm6+rb7s/yh/XL+K//W/3YABwGFAfUBVAKdAtcCEANJA3gDlAOeA6oDxgP3Ay8EYASSBMoEBwVPBa0FFAZtBrUG/gZPB5cH0AcDCDIIUghcCFIINwgHCMAHaQcEB4YG6QVBBZkE5wMcA0oChwHMAAcAQv+L/t/9O/2q/DH8wPtQ+/z61PrB+qD6bfpQ+lb6Y/pc+kj6P/pD+kn6Qfoq+gv67vnR+aj5ZvkV+cL4d/g0+Pb3vveR93r3f/eZ97v33fcA+C34Zvim+Oj4Ofme+Q/6f/rn+kv7u/tB/NH8Wf3Z/V/+6f5s/+r/aADeAEEBmwH4AVgCsgIIA2EDxwM3BKMEAwVeBbwFEQZYBp8G+QZmB9kHVwjsCKcJjAqLC5EMpA3TDhUQXhGzEhUUbhWxFuYXABnUGU0adxpWGtQZ5RiQF+oVBBTjEYUP9AxJCpcH5QRJAtD/e/1W+4H5CPjh9hL2rvWv9fP1ZfYG98n3k/hQ+e/5YfqZ+o36Lvp0+V749PY79UbzJfHe7n7sJern58flx+MD4pXgi9/s3rze9d6Y36zgNuIt5IXmJenu68LukvFS9PL2XvmR+4f9Q//KABoCMAMOBMQEWAXCBfwFEQYUBg8GCgYLBh0GTgalBiIHuQdsCEMJLwoPC88LeQweDbUNJg5wDqEOwA7GDrEOhg5SDg8OtA1HDdEMSwyfC98KKwqCCccI8wcYBzgGSAVEBDcDKgIbAQIA1f6Y/VT8Cvuz+VX4AffK9cb0AvR38xXz4fLx8kDzvPNX9BL14/XK9tX3BvlG+n37qPzE/cP+kf8gAHwAsQC+AJwAUgAEAML/jP9k/1b/Yv95/6P/9/9+ACsB9QHgAu8DHgVpBtAHQwmsCv8LMw1FDikP0Q8uEEEQCxCRD88Oxw2KDCcLpgkZCJEGGgW+A4QCZgFpAJ7/E/+6/nv+Xf5x/rD+EP+J/xAAjAD0AEIBZwFUAQoBhQC+/8L+n/1S/N76YPnu94z2PPUK9O/y7fEh8aLwY/Bc8JvwI/H08RXzgfQX9rj3bvk8+xD91/6AAO8BGwMbBPcElgXxBRUGAQa8BWEFAAV+BNYDJwN+AtUBPgHMAGwAEwDg/+v/KwCSAB8BywGVAngDWwQjBdkFiQYZB3gHvgfrB+AHowdaB/8GbAajBb4EyQPGAsEBwAC9/8T+2v37/DT8lPsW+6P6SfoT+vv5/fki+l/6n/rl+j/7mfvi+yH8YvyW/Lj8z/zb/Nj8xvys/Iv8Zvw6/Pb7q/t0+1b7OPsd+x/7QPtr+5T7wfv5+z38iPzS/B39af2p/dv9Ev5U/n/+gf5q/k/+MP4N/u391f3M/d/9A/4r/mj+yP4y/5j/AwB+AAQBmAE2AsgCQgOtAwkEUASOBMQE0ASxBIgEXQQXBLwDawMkA+ACrQKWAogCjAK7AhIDiAMmBPQE4wX9BlMI0wlhCwcNwg55ECgS2RNhFYsWWxflFwoYtRf6FuAVUhRkEkEQ9g2CC/0Idwb3A5gBcv9v/Y/7+fm9+MT3Hffr9hb3dvcU+PL45PnM+rP7gfwI/Tn9G/2k/NP7tPpD+Xv3h/WG83DxTe9K7W3rpukQ6M/m0uX55F3kJORL5NLkueX25oDoXep/7Lvu/fBE83b1efdO+ff6W/yF/ZX+lP94AEgBEALPAooDUwQgBdoFhAYoB74HOQimCBAJeQnfCToKfgquCtYK7AriCsYKlwpKCt8JcgkVCcAIcAgtCAQI+wcNCC0IUQiFCMII8AgBCfMIvAhLCKAHvgalBVsE6QJDAW3/iP2p+9X5Fvh/9gn1rfN98pnxCPHM8OrwYfEu8lXzvvRG9uP3nflX+/L8bf7H/+QAvQFlAuACDQPlAnkC1AEGASkARv9f/pb9Df3F/Mf8J/3l/ej+KwCuAVcDCgXRBqoIeAoyDOANZA+XEHcRFBJhEkoSzxHqEJkP+g0mDCQKBgjtBeoDAAJMAOL+sv25/B386vsA/Ej8yPx6/VD+Qf84ABMBxgFiAuICMwNIAx0DqAL2ARsBDgDF/k39vPsW+mn41fZt9TL0MPN/8h/yBfIz8q/ycfNw9KH19/Zs+AH6r/tf/QH/mgApApcD0gTLBX0G8gYxBzcH9wZ7BtsFKgVyBLgD/QI8AngBxwA5AMb/Yv8S/+j+7v4f/3L/5P9xAA0BswFZAv4CnQMpBJgE6wQjBTcFHwXhBH0E7wM4A2kCjQGlALX/wv7K/db8/ftE+5v6/vmF+UT5L/kt+Tr5aPnJ+VT67/qK+yr8x/xP/b/9Lv6Z/ub+EP8u/0r/V/9K/yn/+/7L/qH+d/5L/hz+8/3b/d39+f0c/j7+aP6c/sr+5v7//iH/R/9l/3v/hP99/2r/Uf8y/wb/zf6I/jv+9P24/Yj9ZP1M/Uv9Z/2g/er9PP6U/vn+af/Y/z0AnQD8AE4BhgGrAcUB1QHZAdQBzQHCAbYBqgGaAYUBbgFcAVcBZgGIAa0B0gEHAlMCogLkAh0DTwN7A6EDwwPgA/kDGQRRBLAEQwX8BcUGqAfECBkKegvODBwOYQ+JEIAROxKkErISaRLWEQMR7g+IDtEM6gr5CAAH8ATSArkAq/6//Bz70vnM+Af4ovep9wv4qfhv+VL6TvtL/Cr90/07/lf+Hv6c/eL85/uh+iH5fvew9bnzuPHE7+ftIuyJ6jPpL+iK50LnTuer52foiekO6+Xs7e4R8VbztfUH+DT6RvxE/g4AkAHbAgEE+gS0BT8GtwYkB2cHawdGBxUH2gaFBh8GwQVlBf0ElARSBEAESAReBI4E3gRIBb4FOAa5BkAHxAdFCMoISwmwCfEJFwoiCgUKuAk9CZEIqgeFBi4FtAMWAk4AW/5Y/Fz6cfiY9t30XvMv8lTxxPBx8F7wlfAf8erx4PL48y/1hPbr91X5svr7+y79Rv42//b/ewDHAOAA0QCcAEUA3f9z/xT/z/60/s3+H/+k/1oARAFZAosD0QQsBpsHCQlWCnwLkQyiDaAObQ8KEIgQ4xAHEeIQhBAFEGUPkg6KDWIMKgvmCZ4IZQdMBkUFPwQ9A1oCpQEPAY4AJADO/37/Mf/2/tL+v/6k/oT+b/5o/lv+Qf4W/tn9fP39/GT8s/vk+vP5/Pgb+FX3mfbt9Wr1FPXf9Mj02/Qc9X317PVz9if3DPgV+UH6jPvf/Cb+YP+VALkBrgJfA9IDFgQtBCEE8wOjAzEDqAIZAogB9gBnAOf/iP9N/zT/O/9j/6D/7v9fAPgAngEsAp4CFAObAxAEXQSMBK4EtwSbBFoEBwSYA/sCPQKNAewAPQCA/9f+Tv7Q/Vb98Pyv/ID8T/ww/Dv8WPxm/G/8jvzG/AP9M/1a/Y/90v0L/j3+ef65/vj+Of93/6n/1P8AACsATQBNACYABgD8/+H/pf9a/wj/p/41/rX9NP29/Ef82fuI+1X7MPss+077hfvN+zL8pfwb/Y/98/1J/qb+9v4j/zn/Qf8v/wz/8f7a/r/+of6N/o3+mP6U/pP+wv4N/0f/dv+7/x8AoQAnAZYB+AFnAtwCSwOxA/wDLQRjBJwExQToBB4FZwW/BRUGSwZoBpQG0gYDBw4H9gbNBrIGoQaEBmAGRAYzBiwGJQYIBuwF9QUbBkoGlAYLB6AHRwgICeUJ0wrGC6MMUg28DdMNmA0dDWEMVgsOCp8IBgdABWYDkAHL/yr+sPxZ+yv6H/k2+JT3TPdG9233w/dA+NL4afnv+WT6zfoM+//6uvpR+q35yfiy9232DfXB85TydfFq8IXv4+6b7qTu3e5F7+/vyvDA8cXy0PPi9Ar2Ovdq+KH5z/rh++/88v26/kL/t/8eAGMAigCXAKQA0wAnAYYB9gF2AvUCaAPXAzUEgQS9BOAE5QTXBLoEnASLBHIEPAQMBPkD5QO5A4sDZgNPA08DXgNwA4gDlgOJA2oDPgPuAnoC8gFSAY0Arf/A/s/92vza+9H64fkQ+Ub4h/f69qb2ffaL9tf2WPcM+OT4zPm8+qv7ifxg/TT+6/6E/xoAogALAX4BFAK5AmQDGwTEBF4F/QWMBvkGVgetB/AHIQhGCGkImAjKCOgIFwljCZ4JtQnNCd0J0wnJCcMJrgmgCaUJpwmzCdEJ6QkECiUKDAqoCTAJnwjAB6IGUQXHAyECdACz/vv8bfvz+ZH4b/eV9hD26vX29SD2oPZo9zz4LflE+k/7Sfw//QH+hf71/jj/Kf/i/mT+pP3K/Ob76Prq+Qn5R/jK96P3pPfW9274SflJ+oL72vwf/mP/qADFAb4CngNUBOQETQVqBU0FHQXMBE8EyQM3A5ECBwKwAWYBNAErATcBTwGNAeUBRAKTAsMC4QIAAwMD3gKyAoACMQLYAYMBGgGZAB4Asf9O//X+n/5c/jv+MP4t/kb+fv68/u/+E/8x/0n/Wv9j/1r/Lv/h/pP+RP7r/Zj9UP0H/cP8j/xa/Cv8EPwL/BL8EPwJ/Bn8PvxS/GT8jPyh/In8dfx1/HL8bfxm/FD8Svxk/HX8dPx6/Ij8qPzj/Ar9G/1E/Xn9ov3h/TX+e/7R/kf/uP8wAMoAYgHvAYYCEAOSAywEpwTiBBUFMgUEBbUEZQTqA1kD1QI1AogBBQGSACcA+P/1//3/MACMAP0AsAGSAk4DAQTbBJ4FNAa6BgIHAwf9BuIGjAYYBnsFnQS2A+IC8wEKAU8Ahv+2/i7+4P20/c/9FP5U/q/+JP+H/+7/YgC1AOgADAECAd0AwwCQADwA9v+v/03/Cv/3/vD+A/9A/43/+P+bAE0B9AGqAnMDQAQJBdQFqwaWB2wIDQmLCesJGQoPCsMJIAk2CDQHIAbqBJEDLwLvAOL/9v4U/kn9sfxi/Ej8QPxP/In82fwy/Zb98P0q/j/+LP7v/ZP9Df1V/I77xPrV+dX46/cY91H2p/Uc9cL0n/SW9Lb0L/XZ9XT2Fffa96D4Tfnd+VP6vPoG+wz7//oX+yL7Bvv0+uj6zfrL+vH6HPtR+5r76vtf/Pv8j/0p/vP+zv+cAGcBKALwAsEDSARpBIgErQSIBDME2QNZA78CLwKVAQUBnQAvAMT/nP90/xD/1f7z/iH/R/9u/4//2/9YALEA9QBZAagB2wE4Ao0CowLNAh8DUQNyA4QDZwNjA5oDkwNBAx0DGgMEAwQDCQPyAvcCGgMvA3ID9ANXBKwEJwWBBaoF7gVKBpQGzAbEBm4GKwYHBqoFIwWcBPUDOgOVAtsB/gBLAM//av8m//j+1f7v/jz/X/9J/0j/bv+K/3f/K/+9/l3+D/6y/T39vPwt/JH7//qE+iL66fno+RD6Tfqn+iz70PuI/EX96P18/g3/hv/v/2QAxAACAVUBtQHrAQsCJAIXAggCJAIxAiACPQJ1AqIC7QJNA4gDwAMEBBgEBATpA6EDSQMTA8MCQwLhAYoBDgGzAH0AJgDV/7X/lP96/43/i/9u/33/kf96/2z/Xv8k//j+3/6Z/kv+Kv76/bv9l/1j/RH98fz3/OP80PzS/Nb86/wV/TP9Vf1//YD9av1x/Xz9cP1b/TT99Py8/I78V/wu/Bv8DPwI/Bb8NPxw/Mb8Ff1f/bf9FP5v/r/++/45/4z/2f8OACoAJwAUAPz/tv9B/+T+qf5m/jH+F/4K/iX+ev7U/jD/pv8UAH0ADwGtATsC3AJ8A/kDdATvBCkFOwVQBUgFKAUTBewEuAShBIYETgQ6BEQEMgQWBPQDsAOBA40DiwNgAzAD7wKeAlsC+QFgAd0AkQBIAPf/pP9Q/yj/QP9j/2v/X/89/yD/Jf8g//n+1v7G/sX+yf6k/lb+HP72/b79hv1g/UP9Of0//TT9N/1w/bn9AP46/kH+Ov5r/rT+4v4V/z//S/9g/3H/Uf9N/37/gf9e/13/Uv9N/6f/IAB4AO4AdQHUAV4CGgOhAyQE5gSEBfkFkAbwBvQGCQcNB7oGbQYpBpMFBwW0BDAEvwPSA+gDzAPtAyMERwTDBFEFggXdBYcGzgbNBtAGYgamBS8FiQRYAz8CUAEvACf/LP7W/LX7Iftt+pP5F/mt+ET4VviK+Hv4o/j0+Oz44fjz+JX4HvgX+PX3hPc+9/T2evY99gb2f/VB9Wb1UfVI9bD1DvZg9iT3+PeC+CD5zflQ+vD6gPu5+yf8/vyf/Qf+lP78/jP/lf/u/xwAhQAKAWQB7gGoAhwDhgMuBLIE/wRGBVgFQgVUBVgFNQVZBZYFegVPBUwFIQXWBJ8EYAQkBO4DgwMeAxwDFAPBAosCbQIrAgYCAALWAcQB5wHoAeEBBgIGAvABFQIOApoBLgHsAKcAewBLAOf/u//X/6f/SP8x/zL/G/8S//f+3v4T/1L/Zv+n//f//f8TAFMANQDj/9j/0v+1/7n/oP9V/0L/OP/q/sX+5v7X/sj+Bf84/17/w/8pAHIA5gBQAXABmQHYAdYBwgHgAfEB4wHXAa0BdQFsAWMBOAEsAUEBNgE6AWwBhwGEAZ0BxQHcAfEB9AHlAf0BKgI3AksCiQK8AtMC7QL/Ag0DPQNqA10DNwMcA/UCzAKhAkQCzAF7ASEBhADh/2L/8v6i/l3+6v2D/X/9mv2M/X/9df1g/Wv9hv1i/Rn98vzI/IL8N/zZ+277L/sN+8j6e/pR+j76MPoz+jv6R/pu+rT6A/tN+5D73Ps8/Jn83/wX/Un9cf2R/aX9rv3L/Rj+gf7q/k//uf8zALoANQGQAeYBUgK2AvUCKQNoA5gDtwPUA9wDygO/A6gDYwMrAzEDRwNFA0YDSANTA34DnAN9A18DbQN4A3UDgQOOA54DwAO9A3MDJwMAA8YCbAIOAqABJQHDAHcAJgDQ/4P/QP8E/8r+nf6j/uX+NP9l/5L/4P84AG0AeABsAFIAOgAmAOn/dP/7/qb+ZP4a/r39Vv0C/dX8t/yh/Lr8EP2D/db98v37/RT+LP4x/iT+7f2I/TH9C/0G/R39SP2E/fH9dP60/t/+Xv/1/zwAYAB/AHwAngACAS0BDgEHAQoBAwEjAS4B6QDRAA8BJwEjAV8BrAHrAVECrgLoAlQD1gMaBF4EwATtBPgEHgUvBSAFHgUJBeME0wSzBIgEqATrBAwFXAX0BXYG8gaFB+4HPgiVCJUIIgh0B1QGsQQXA3kBa/9R/aH7Kfrb+NX37PZD9if2MfYG9gr2evYi9//3BPnm+aL6W/vw+zD8HPzE+z37k/rQ+Qj5a/gl+DT4Vfha+Gr4jfii+Nf4Tfm/+Sr67Pr8+yD9Vf59/4cAnwGKAuMC+gI2A2UDcQN5A3EDbQOJA44DZgMtA7gCCQJ/AQ0BhAAoAP3/2P/8/2EAlAC3AAkBMQE2AWUBcgFWAaQBFAL8AboBrAGHAU4B+wA5AG7/M/8L/4b+JP4c/if+R/50/n/+mv78/mT/r/8AAFsAvAApAW4BVwH/ALMAkABwACsA0P92/y//Gf8z/zz/Jv8e/zX/Zf+c/8X///92AP8AYQGdAbgBvwHBAaIBYAEkAdQAawBKAGEASwAuADoALAAaACAA5/+c/8f/CQAIAD4AlACdALcA+gDWAJEAnACCACcABwDy/9T/GwBzAGoAdAC2ALcAlQCRAHsAdACjALwAvQDkAPIA3wDsAPwA8gAMATcBXQHAATYCdgLBAioDbQPAAyQEHgTUA78DrwNyAzED0wJbAhwC4gFMAaMANwDs/77/qf+G/1//V/9c/1L/Iv/J/nT+L/7W/Xf9LP3s/OT8Fv0e/Qz9QP2P/cb9Cf41/ir+XP7P/vn+6/72/vv++/4F/8L+Nf7j/cn9mP1s/Wb9dP2z/R/+hf7q/mj/6v9xAAABewHZAS4CdAK/AgsDFQPcAqQCbwInAtoBbgHVAF8AKADy/8D/tf+5/8v/AAAqACsAPgCLAOwAOwFtAYABgwGTAa0BpQF2AVsBTQESAccAmQBpAEMARwAnANL/uv/W/7v/iv9r/zL/Fv9B/zv/+f4A/yz/Nf9Z/4H/Z/9c/4D/fP9g/0r/Bf/F/s7+yP6L/mD+O/4P/vv9v/1R/Sn9O/0o/RL9+/y0/Kv8C/1L/WP9rP34/VD+C/+9/yEAtAB7AfkBTwKcAp4CjAKnAoEC9gGAAUEBFgEEAfQA1ADxAGsB3AEKAicCXgKRAqMCngKLAm8CZgJ4ApcC1AIsA18DYQNSAxYDqgJJAvsBrAFhAQgBpwB5AH4AggBtAAgASP+R/v79WP3S/Jv8evyJ/Oz8T/22/Uz+h/45/vv9wv1E/fj8Af38/Bj9Zf2M/br99/2r/fz8ivwz/NP7tvvJ+xL8vPxk/d/9if4f/1j/iv+b/2P/hv8OAHMA+ACpAf4BYQL/Av8CogKqAnkC4wG4Aa8BcQGjAfsB8wE5AqECVAIUAl4CTAIFAhMC6gG7AQwCFgLQAQoCIAKiAXQBSwGIABQA/P9w/xT/I/+0/l3+pf5s/u39Mf5V/vH9Dv4x/sL9yf0x/iv+ff4w/yf/Av98/6P/gf/b//z/sP/I/+j/tv/y/1AANABOAKgAfgBIAGMAMwD7/zEANAAMAEUAZQBSAK4ABwHiAPMANgEBAbYAoQBJAP7/GQD2/5X/k/+R/1b/df+w/3f/Sv9g/0f/Mv9Y/1T/Tf+P/6X/f/+f/87/uf+0/67/Y/85/03/Sv9m/7P/wv+8/9r/rP9N/0X/Ov/n/sD+r/5y/nb+mv5x/nH+rv5+/jP+ZP6R/p3+Df+V/+3/awDBALQA7QBbAVsBTgGIAZIBhAGtAbUBpAHDAaUBLgHVAHUA+v/a/+v/wf+8/wYAOABVAHEAYwB4ANQA6gDEAOgAKQFBAXYBxAHlAfAB7QHCAasBuwGmAXcBcwFwATcB+gDXAKMAXwAzAA0A0v+e/4n/hv+f/7L/hP9c/5f/5f8DADIAdQCjAOkAMgE6AT4BVQE3ARQBHQH4AMQA2ADVAJkAhQBwACEA8f/E/3L/a/+S/2n/X//C/wgAOQCfANUA5gAtATsB8gDkAN4AiwBXADkA0P97/2P/JP/6/hj/C//e/u7+FP9C/53/y/+8/+b/NABPAGEAewCAAIgAeQAtAPX/+P/o/7H/cf8j/+L+xv6i/mf+M/4Q/gD+CP4c/kH+jP72/mv/2/85AJUA4QD0AO4A5wDDAJEAXwD//4r/QP8A/8f+y/7V/sj+7/45/27/2P9tANMAPQG/AQMCMwJ8AoQCcAKRAo8CUQI3AgUCkwFFAQABmQB9AIsASgAbAEQAZQCCAJ4AVwABAAQA0v88/8r+hP5X/nT+gf49/iT+OP4X/v39Bf7c/bv91P3H/Zr9mv2n/b797/3c/XL9LP0c/Qb98vzY/K/8sPzk/BL9SP2V/dn9Bf4b/hn+Hf5A/nn+uP79/lj/1f9aANAAPAGMAb0BAQJIAmECXwJaAm4C1QJjA5oDngPGA+cD6gPiA60DiAPCA9wDiwNMA1UDhwPkAwcEowNSA0YD/wKfAnwCRQLyAaoBIwGWAGIADwBz/yX/+v6G/jX+M/4z/kP+P/7w/df9E/7s/Xv9S/0c/cn8ofyA/FH8WPxb/D78Z/yw/Mz8Hv2x/Qr+Pf6a/gL/Yv+r/6r/kf+Z/4f/YP9u/3j/Qf8Z/z7/kP/U/+//DwBaAIkAcQBtALsADAESAeYA2wD3ANwAhQBjAHQATQDk/3//UP9X/1D/J/9A/5H/p/+c/7T/w/++/7z/m/9x/37/hf9y/3z/df9d/5n/7P/N/4n/d/90/4n/qf+V/57/8P8QAAEALABOAEoAeACwAKwAqQC2AL8A+QAxARIBCQFNAV8BNAElASsBOQFQAS8B7wD8ACYBHwEXASABIgE/AWsBYAE5ASoBGQH3AMgAdgAZAOv/2f+2/4r/Z/9N/0j/S/8r/+T+sf6v/r7+yf7M/s7+5P4S/yL/Cf/7/vP+0P67/sb+2f4G/0L/U/9g/6b/7f8XAEAASQBGAIYA0gDnAAYBLAEgARQBIQELAQIBKAEyATwBeAGhAb4BHwJ7ApMCswLRAsoC1wLgArMCoAKpAmcCDALfAaQBWAEgAcwAdABXACwA3v/N/+H/5/8AABwAFAAiADsAIQAIABMACQD2/+z/zf+0/77/tf+e/6f/rf+a/4z/ef9m/3H/gP+D/5n/qv+g/5v/nv+R/47/h/9r/17/X/9Y/3D/ov+7/9L/CQBBAIMAwQDAAKMAqACjAIMAawA9AAMA+P/p/6f/cf9K/xX/Cv8Y//3+9P4b/y//Rf90/37/ev+a/5T/Yv9Y/1v/Uv98/7v/4f8gAF0AXgBxAK4AvQC3ANIA3ADOAL0AbQACAM//nf87//X+z/6g/pD+n/6r/un+YP+7//b/LABFAGMAtgD5AAAB/QDqAKoAVADo/17/6P6A/vv9iP1Z/Uf9Rf1v/bT9/f1I/oP+sP7i/gL///4M/zz/SP8U/9H+o/57/jT+vP1V/U/9g/2h/bn9Cf6J/hH/f//K/xQAagCjALkA3gAfAWUBswECAkMCgwK9AuAC/wI0A2gDkAOkA5EDZgNFAxYDtwIyApcBBQGqAIAAYgBQAGIAtQBbARQCjALRAi0DowPxA+cDnQNpA1cDCANPAnIBsQAGAEr/aP6L/fv8pvxo/FD8afy2/D/94P1c/rT+A/9E/3P/fv9N/xj/DP///sn+fv4n/tD9jf1E/e78wPy9/M78Cf1f/bH9If7B/lb/vf/6/wYADgAwAEIARgB2ALkA4gD0AOgAvgCXAGEABACr/2v/H//N/pP+XP46/kD+Q/42/iP+9v29/bn95/0p/o7+AP9U/5P/wf/T/+f/+P/j/7//r/+K/0f/Gf8V/zP/XP9h/0z/Xv+N/7H/4/83AI8A4AArAWkBrQHvAQkCFgI+AloCSQIsAgsC3QGqAWkBIgEIARUBHAEkATMBNAFBAW8BlQGiAZ4BdAE1ARAB/gDsAOAAxgCYAH4AZQAjANn/rv+R/3z/Y/80/xX/If8w/zn/Y/+X/7v/4v/7//v/AQAMABMALwBMAD0AIwAjAB0ACQD4/9L/l/9p/0L/Lv9C/17/df+7/xwAXACMAMEA5gD4AAEBAAEbAVIBZAFOAUwBUQE8ARcB4ACmAJEAhQBYAC8AMABKAIAAvADJALkAuwDBAMYA3gD1AA8BRAF2AYMBfwFjASMB7gDKAJEAUAAxACkALwA4ADEANABWAF0ALgD+/+b/2P/e//b/DwA8AHcAiABxAE4AJgANAAMA6f/U//P/IwA1ADUALwAWAOz/tf94/0j/Fv/K/o3+jf6s/sb+2P7p/gP/NP9u/7H/DwBwAK8AzwDhAN8AuwBwAA0Awf+X/2H/Av+d/l/+Uf5f/nn+qf4C/37/BACKAAsBggHlAScCOQIOAqoBNAHZAKAAcQAnAMD/Xf8Z/9f+gv42/hL+FP4r/kn+df67/vb+A/8E/xH/CP/V/pL+Vv5C/mX+mP68/s/+y/6+/sv+0f6x/qf+1/4P/zH/Sv9Z/3X/qv/T/+//HABCAGQAtQAQATsBWgF7AXUBXQFQAS8B+QC1AFgAIQBHAH0AjACnAM8AAwGAAS8CygJoAxoEnwTpBAAF4wTVBOcEoAT1A2MD8gJqAuwBcQHgAGEA7P9h//7+0P6k/q7+Bf8o///+8f7z/sn+e/4S/rz9vf3E/Wr9CP3g/L38qvyq/Gz8BvzV+8X7xPv1+zH8d/wK/af98P0z/qP+Dv99/+T/CgAcAEQAMQDu/9T/wv+T/4T/fv9c/1r/cv9y/4f/rv+w/8X/BgAMAOr/DABWAIQAlwB4ADUAEgDf/3b/Mv8i//n+3P7w/uH+o/5t/jv+E/4H/uv90f3u/fb9vf3A/ST+df6R/p/+sf7j/hn/G/8u/53/FwBWAHwAegBXAGMAmACtAKEAigB0AIoAsAClAJsA3wA5AWcBdQFzAYcB0QEJAv4B+gEiAkICSQI0AggC9AEJAg4C6gG0AW8BQgFDATcBDQEQAUwBeAF2AWEBXgGDAaQBhQFFARkBAQH6APoA5QDBALkAvQCjAHQAUABBADwAJADz/9b/1v/M/6r/jP+J/6L/wP++/6z/uP/k/xkASAByAKAAzADqAPMA7QDiAOcACwEuASoBFwESARUBCQHyAOcAAAEpAUUBVQFiAWMBbQGEAX8BXAE+ARsBxwBCALv/Z/9L/yz/7P68/rT+vP7V/gD/G/8o/z//Tf9F/zH/D//t/ur+8P7f/sf+tv6o/qz+r/6U/o/+yv4L/yz/S/97/8T/LQCIAK4AugC8ALMAvwDUANEA4AAMARAB3QCwAJoAiQB7AE8ADgD4/wkAEwAjACsABgDd/9D/pf9W/xb/7v7m/gD/Bf/3/if/bf9r/zj/C//m/t3+6/7r/v/+R/+F/6v/5f8ZADUAXQB0AF0AWwB6AHgAZQBiAFIAQAA5AAUAsf97/1f/Uv+Y/+n/FABbALsA4QDwAB4BTAFwAXwBRQHwALcAYgDk/37/JP/G/pb+X/7a/WP9Uv1x/Y/9nf2P/aP97/0O/gL+O/6s/gf/VP+M/63/AAB9ANUAHAFXAUcBHgEoARABpQBEABYABQD7/9r/3v9yAEYB0AFbAjgDEgS/BGIF1AUMBkAGYQZJBgMGdwXGBEEEtAPcAicCygFdAdoAhwBDAO7/sP+J/3z/nf+w/6D/o/+Q/yr/w/6I/kX+Cf7k/ZL9KP32/Ob85/wh/WL9Wf0Q/Z78K/z8++D7k/tv+6H7rvt/+3z7tvsD/FD8jPzX/Fj9zv0R/nn+DP96/9L/JgAfAK//KP++/on+ef5S/jn+eP7M/uL+Af9e/8f/JwBqAGoASgBCAEcAXQCCAIIAaAByAGwAHgDN/6n/l/+Y/6r/rf+4/9P/1f+9/6D/Xv8C/7j+Z/72/aX9lv2y/fj9T/6P/tH+Jf9j/4D/jv+B/2v/Zv9a/0T/S/9U/zr/Jv83/1D/aP+T/9b/LgCFAMoALgHOAWICtgLrAhYDKAM1A1IDdgOUA5ADXwMlA/gCxgKdAp0CuQLGArgCmwKQAqICrAKhAqACngJpAhQC4wHjAfIB9QHxAesBygGBATQB/QDBAGoAHADg/5r/Sv8P/+/+3P7U/tv+3f6//qX+zf4y/4z/yv8SAGMAkgCTAI4AnQCpAJwAjgCQAIsAeQB/AK8A5gAFAQoBGgFMAXwBgwF8AZcBywHmAc8BowGIAW8BJwHBAHUARgAbAPf/4P/H/6n/m/+l/7X/rv+V/43/mf+Q/3r/f/+U/5j/l/+Y/5n/o/+5/8T/wf+0/6f/pv+h/4L/bv93/2//P/8P/+f+uf6P/mn+QP4r/jn+Wv6C/qr+0P4B/zL/Qf89/0T/Q/85/0X/U/9G/zn/Uv93/4f/c/9H/yn/Fv/u/sf+zv7s/gL/Ff8x/17/o//c/wMARgCrAPQAIAFUAYkBpQGcAW0BJwHSAF4A0f9O/8/+Sf7Z/Yn9Wv1u/cX9Jf6D/gj/pv8tAJAA5QA8AX0BhAFfAUABIwH7AOoA5wC8AGwAJgDa/2z/9v6g/oH+iv6M/nT+Vf4//j3+V/5h/kD+Jv4w/j7+Tf6P/hv/1/+YACgBaAFsAV8BWwFVASwB9wD/ADsBaQGfATQCIgMbBPYEwgWMBjIHlwfaByMIVwhWCDkIBQh/B6EGtgXxBDQETgNVAo8B9gA+AHL/A/8V/0H/Jf/N/mz+Dv6X/RD9r/xy/Bj8l/sp+9z6l/pe+l76lPqv+nv6PfpW+qj62Pry+jX7ifuT+0r7C/sS+0D7YvuI+9D7I/x3/Of8c/3u/VP+yv5S/6j/qv+m/+3/TABPAPv/vv+8/6T/Sf/y/vD+MP9w/6n/+/9ZAKMA4gAXARYB2gC0AOUALgEeAbsAfACQAKEAYwAJAOL/2P+b/yL/x/7F/vz+H/8a//z+yP6D/kj+If73/c390P0L/jb+Iv4X/nP+Bv9R/0T/Qv9v/33/RP8W/0L/of/b/+f/+P8mAG4AzQAzAYUBtgHnAS8CgQLEAv8CTQOlA9gDywOcA4oDmwOeA3MDNQMSAwkD/QLwAvcCCAMAA98CuwKZAm0CSgJOAmMCVAIiAvgB2AGaAT8B9wDSAKIAVQANAOL/xf+k/4z/gP9s/0T/Ev/h/rT+lf6a/sn+CP8v/zz/Sf9o/43/r//c/yIAagCYAK4AwwDdAPcAEQEqATMBIgETAS4BcAGiAbgB2QEaAkoCNwL0AbwBmwFuASEBygCCAEIA7v+L/0P/KP8Z///+8P4I/zn/b/+r/+3/HQAqACAAEAD1/8r/m/94/1//RP8v/zf/ZP+Y/7L/xv/z/zQAaACKAKgAywDrAAQBCQHnAKYAbAA/AP//mf8y//L+0P6p/oD+ef6f/s7+6/4B/x7/Pv9c/3z/lP+N/3D/YP9a/zr/8/6n/mT+Ef6g/Tv9Hv1K/YX9sf3u/Vf+0P40/5X/DQB6ALEAtwClAIUAXwBJAEcANQD9/6r/WP8X/9/+ov5v/mn+jf6j/o3+gP6s/un+Av8R/03/qP/s/w0AIgA3AEoAYAB7AIMAbABDAA4Avv9Y/wv/6v7G/nL+CP66/Yb9Xf1L/WX9pP3//Xj+8P48/23/u/8nAHMAgQCPAPAArwGLAloDRQR/BdgG4weLCCMJ1QleCoYKZwo0CgUK7AneCZ0J+ggZCD4HWAYzBd4DqQLCAQQBNgBd/6j+Rf4Z/tf9TP2f/Cn87fuV+/z6iPqg+gb7Gfu6+lr6RPo3+uH5XPn2+Mv4rviJ+Hv4rfgi+b/5U/qs+rr6xPoc+6j7A/wj/G/8E/23/Rb+Y/7a/ln/nv+Y/2X/P/9X/6H/1v/S/8r/+f9EAFwANAAMAA8AFgDw/8H/1v88AKUA1gDkAAMBLAE4ASUBEgEMAfsAyQCGAFEAKwALAPH/1f+S/xz/q/54/nD+a/51/qf+2/7i/sz+xf7Y/vn+I/9C/0L/Jv8V/yf/Sf9g/3L/lP+2/7j/o/+y//v/VACaANsAHQFFAVsBjQHXAQgCHQJOArQCHgNsA7oDLASpBPcEBAXxBN8EtgRfBPcDswOMA1gDCgO/Ao4CdAJjAlMCQgI2AikCGAIFAgECCwILAvMBvwFvAQwBowAvAJ//Av9+/iD+zf1y/R/96PzO/Lz8oPyP/LP8Bv1O/W79kf3l/VT+s/79/kz/tv8uAI8AwgDmACwBlAHpAQkCDwIjAkkCVAIdAs8BtQHSAdoBowFdATQBEgHZAIoAPAD8/9H/sf93/x7/z/6v/qH+gP5Q/jb+OP45/iH+C/4e/lX+jP64/uP+Bf8Z/y//UP9m/2X/bP+P/7T/0v/3/yQAQgBYAIMAyAATAV4BsAEHAlcCmgLRAvwCFQMFA8YCagIUAssBgAErAdMAhABAAAIAuv9x/z7/Gf/o/rL+mf6m/sz+AP8+/2f/cv9v/2f/Pf///t/+7v76/t3+s/6p/r7+xf6t/pf+pf65/qD+Yv45/kn+fP67/vb+Gv8s/zn/Nf8I/87+wP7i/gT/BP///ir/j/8HAGEAmwDdADUBeQGGAXIBagF4AYIBYAEBAY4ANgDm/2L/qf4J/rT9kf1s/UL9Of1p/bP94v3y/Qv+Rv6J/qv+ov58/l/+df6w/s/+yf7h/jn/pP8AAIcAeQHJAi4EfwXMBj4I2QltC8IMzQ2QDgAP/A6HDrYNqAxoC/AJMQg4BjQEWQK7AEn/7v2z/MD7LPvH+l36C/oO+kz6bfpn+oP60/oY+yP7Gvsl+zX7K/sB+8j6hfos+sf5bvkm+eX4tfiq+LP4qPiQ+J745/hW+dz5fvow++f7p/x7/Vz+QP8jAPAAeQGwAbIBpgGTAWwBKwHdAI0ALQCw/zT/3v62/q/+zv4Q/1r/if+t//D/XwDLAAABBAEGAQEBwABKAPb/9/8IAOX/r/+f/6f/nv+A/2H/QP8Y/+7+tf5Q/sb9SP39/NL8pPx4/Hv8rfzX/N78+vxd/fL9hf4F/2//u//7/0oAogDtADIBhQHLAdUBtAGvAfIBYAK/AgIDQAOCA7YD4wMuBJ8ECwVhBbkFHAZtBq4G9wZHB38HlQeDB0EH0wZcBu0FdgXxBH8ELQTnA4sDEwOWAjQC6gGRARwBqwBEAMn/PP/F/nD+Jf7d/Z39Sv3b/Hf8R/wq/Pz72/v0+y78TfxN/GP8qvwC/U/9nf0F/nf+4v5S/9v/agDvAHIB7QE7AlICXAJvAmQCJQLbAbkBqwGIAUwBFgH5AOgAxQCKAEgAFADn/7T/d/81//L+r/5q/hv+y/2D/UP9+fyk/Fz8NPwt/Ef8b/yP/Jz8rvzT/AD9IP0+/Xj9zf0o/oH+3P4//7T/OAC8ACUBdAHCARQCVAJ4ApoCygL8AiQDRQNhA3cDjwO1A98D8APkA8kDpgNxAxoDpQIrAsIBYgHqAGQA8/+i/1f/Bf/J/q7+oP6Q/on+lP6u/tn+E/9E/03/Nv8s/0D/Sv8r/wL/A/8Z/wv/1/6t/pr+fP5P/i7+Ef7i/ar9hP1g/Sn9Av0a/WP9lv2d/bH9//1u/sb+Dv96/wUAYgBtAFUAUABaAFgAQgARAMD/X//5/oH+EP7Y/dn9z/2c/Xr9j/3A/f/9a/4D/4r/4P8mAHIAqQC4ALwAzwDXAK4AXAAaAPX/xP95/1D/a/+Q/4H/Xv9t/6f/3/8oAMkA4gFAA64EMwb1B/wJIwxDDlwQYxItFH8VMxZKFtwV/hSmE7QRLA8xDOIIUgW9AXn+svtg+X73IvY89aT0VvR59Av11fWk9nv3Xvgy+dD5Q/q6+jf7cPs0+6r6Ffpn+X34hffP9ln24/Vf9fj0u/SQ9IH0rPQV9Z71Q/YX9yv4d/nw+pH8VP4lANgBRwNmBD4F0wUnBkgGRQYVBqsFEgVgBKMD3QIeAmgBsQABAG7/Af+v/nz+gP7D/ir/i//b/xkAPAAzAAsA3/+5/4r/Q//u/pH+Kv7A/VT92fxN/MX7TfvS+kr62Pmb+Xv5W/lI+VH5c/mo+Qf6ofpm+0f8Tv13/qz/0ADaAc8CpwNHBKsE9wRFBXcFdAVfBWUFcQVZBS8FGwUTBfcE1ATOBOUECAU0BWUFlQXOBRcGUAZWBjwGMQYxBhMGygVzBSYF0ARgBMsDHQN2AugBbwH7AI8AQQAlAC0AOgBBAEYASQA/ACIA+v/Q/5v/Uf/x/oL+DP6f/Tv9zvxU/OP7ivtC+xj7LPuD+/n7cfzu/H/9Hv69/mH/DQC/AGcB9AFpAtwCUwPBAxkEWgSABIQEbwRHBPoDeQPjAlsCyAEKATgAgf/z/nL++P2T/VP9NP0m/Rv9HP04/WP9hv2o/dz9FP40/kr+bv6M/oX+b/5y/oL+cP5A/h7+Gf4a/hj+Kv5h/qn+5P4U/03/lv/Y/wYAMQBtALQA/ABKAa4BKwK1AjoDqAP6AzMEXQR4BH8EYwQdBLgDRgPDAiUCdQHMACoAe//K/jP+z/2Y/X79cf1s/YH9v/0V/mn+xv41/6T/+f89AIAAugDXANYAvQCIAD4A8v+v/2j/HP/M/nn+GP6r/UT9/fzk/OL83fzX/PD8K/1z/cL9Lv6r/g7/Sv98/7L/1//i/93/0v+//53/bf8v/+f+mf5C/uT9gf0a/ab8Jvyr+zX7r/oj+r75oPmp+bn54PlQ+gr72/uj/Hv9c/5r/z0A6wCFAQQCXwKYArICrQKbApICjwKCAnYChAKqAt0CIwN6A8cDBQRPBLMEDAVbBecF5AYjCFUJewrUC2sN8w42EFQRcxJzExoUcRSTFGEUnhNIEocQRg5mCxcItQRWAeD9gfqu96T1OPQu843yc/LJ8kzz1PNv9Db1Hvb99rX3UPjR+CT5MPn5+Iz48/cz9132kvX69Kn0mPS+9BX1l/Ux9s/2avcD+KT4W/kl+vz65vv6/Ef+v/9IAcoCPQSUBcIGrgdVCM4ILAlcCT4JywgaCDUHGAbFBFAD1gFwAC3/Df4f/Xv8KvwW/CT8UPyU/Nb8Av0d/Sf9D/3U/JD8UPwJ/KL7HvuM+gT6lPlF+RP5/PgI+T/5l/n2+Vb6wfpA+7v7G/xj/Lb8JP2b/RP+lv4z/+r/tQCUAYcCigOcBLkFyQaxB20I9AgtCQ0JrAgkCHUHpAbaBUAFywReBAoE+QMoBF8EhQSrBNgE7ATdBMwExwSzBIAEQATzA28DsgLvAUIBhgCy//z+jP5H/gL+x/21/cH9yP3K/eP9Ev40/jf+Lf4r/iX+E/4F/gv+Fv4V/hb+LP5Y/pX+7f5Y/7X/9/8yAHYArQDHANUA8gAWAScBJQEwAWABqQHvASoCbQLHAiwDiQPWAxgETQRoBGIEPATzA5MDJQOrAhgCaQG0AA0Abv/K/ib+nP06/fL8vPyg/Jv8nfye/Kr8xPzj/A39Vv3E/Tb+mv4B/4T/DABuAKYAzgDpAN4AnQBAAN7/ef8M/5v+Jv61/Vz9M/0z/UX9a/3C/Uj+2f5k/wUA0wCxAXICDAOSAwUEVARzBGcELgTPA1ADswL4AS4BbQC7/wf/Sv6i/Sz95fy8/Lb80vwK/VL9rP0h/qb+Jf+T/+//LQBOAF0AagBkAD8A9/+U/wv/Zf7E/Ub93/xu/AX8yPu6+8j78vtO/N78kP1S/iT/DAD/APIB5QK/A2AEywQcBVEFTQX+BIAE9ANPA3cCdAFpAF7/S/4w/RT8AvsS+ln53/ig+Jj4zfhH+e35k/ow+9r7ovx//VT+Fv/X/5EAHAFlAX0BcgFLAQkBrwBHAPH/sv+J/37/jv+y/+L/EwA6AFkAcACLAL4ABQFWAcMBVALaAjIDZwOQA6YDmANzA1MDPgMbA/gCCwNpAwsE/QRJBtkHlAl5C5oNBBCLEtoUvRYHGHoY9BeAFjkUNxGiDaYJawUbAe78Rflx9lX0tPKO8QDx6fAS8WTx7/HO8uDz3vSn9Uj23/aK90X43fhB+aL5D/po+oz6j/qx+gz7WftI++z6ePrq+Tb5X/iL9/b2tfaw9un2hfei+EH6PPxU/oQA5gJaBaIHrQmBCxUNTQ7vDuwOdw6pDWAMoAqcCJIGqQTTAu4AD/9g/ej7pvqS+aP4/fe39473RPcB9/j2Jfdu9773HPih+E75Ffrx+tH7rfyb/Xb+9/4l/zf/KP/g/mb+vf31/C/8gvv9+rv6wPoR+7b7lvyl/e3+XgDYAWUD9wRZBnkHVwjgCB8JJQnkCGgI1gc+B5QG3wUpBY8EJQTAA0kD1gJoAvkBpgFyAUEBIgEsAT8BOgEeAfgA6ADlAMQAjABjADsACADl/+P/BgBOAJoA2QANASQBDQHnAKgAKgCC/9r+LP52/c78UfwU/P/74PvL++/7Lfxn/LD8D/2G/R7+xP5q/yQA4wCSAUIC7QJsA9ADOwSRBLoEuQSsBLsE1QTEBJcEfARcBCsEAQTQA4wDUgMfA9oCkQJSAhQC3AGmAV4BCwGrADoAzP9U/7b+Hf6s/TP9pvw1/NT7bfse+wH7B/sj+0f7d/vB+//7Gvw4/GX8jvyw/L38nPyE/KL80vwJ/WP91P1E/rX+Hf98/+D/TADJAGkBDAKlAl8DLQTbBG8F9QVkBsQGAQfqBo0GFgaEBdkEFAQXA+0BxQCf/3v+ev2k/AL8oftZ+xX7B/tD+6r7Lfyv/Bb9ev3Z/QX+C/4Z/iL+Ev7n/Zz9Q/35/Lb8kPyl/Mn84fwc/YP98f1n/u3+e/8WAJ4A8QA3AY4B1wEXAmkCwwIbA3YDvgP3AyYEKwQPBPIDrQMkA44C+gFEAXIAnP+9/tf95vzp+wj7Tvqz+V/5cvnO+Wz6UvtX/HX9tv7j/9oArgE9AkoC8AFcAaMA1f8E/1H+5v2l/WT9Sf1m/Z799/18/gD/i/9HAAwBtQFYAvMCdQPXA/sDzANqA+oCVAK8ARQBZQDy/8T/ov+O/53/uv/l/x0AOwBsAA0BMgLDA64F0QcuCu8M8g/eEnkVoxc7GRYa2Rl8GHYW+xPKENUMUgiEA9X+mvrM9oPzCPFd71ju3O3X7V3uiO8i8dzykfQi9o739fg3+jL7Fvzq/HL9sv3Q/b79i/1e/SP9v/w4/IP7p/rB+dL44PcQ93P2JfY69o72Hvcx+Mj5qvvh/WQA3QI9BZ4HzQmaCxINRg4pD5APUg+IDlUNpwuMCToHrwQAAmj/2vw5+tX39PWG9H3z0/Jw8lfyjvL48o/zX/Rh9Zb24/cP+S/6evvB/NH9xv6o/2gADAF4AZEBfAFFAc8AIABF/0X+U/2C/Lv7FvvF+sf6I/vg+9X88P1J/78AJAJwA5gEngWTBlMHyAceCF8IaQhSCCkI0AdiB/4GgwblBUIFnQT3A1UDqgL9AWYB2QBdAAIApv9K/yz/OP82/1T/tv8mAIcA8wBvAQACpAJNA/IDcwSnBKcEfwQCBDwDdAKdAZMAfv9z/nv9w/xU/Aj85Pv++038w/xJ/d39l/5X/93/QwC5ACEBcQHOASkCaQKsAvwCPwNlA2ADOwMXA98CgQI3AhQC9QHoAfoBDAIZAiUCEgLiAa0BaAEcAeoAygCqAJAAeQBvAHkAZQAWALv/WP/N/jj+sP0r/b38hPxs/G38g/ya/Lr86fwD/QL9Bv0R/Sf9Rv1H/Sz9Hv0R/eP8tfyU/Hv8fPya/Lz8+Pxx/Rv+5/7Q/8EAsgGaAl0DBgSwBEcFywVFBo0GlQaCBlEG6QVnBdIECwQdAyICFwEMABj/N/5n/ab88fto+x/7+fr6+iL7Sftp+6D71vv2+yv8d/yt/Mf82Pzl/Pz8F/0t/U79d/2L/Yf9d/1Y/UL9QP06/TL9TP1+/bz9Ef5m/rT+H/+k/yQAsQBXAf0BowJIA9MDPwSTBM0E8QT1BMkEgAQyBM4DYwP+AnECuQEEAUAAQv8o/ib9RfyB+9j6RPrh+dH5Hfq2+nT7Pfwq/TL+Hv/s/7QAWAHHARQCMwIHAq0BUgEQAecAtABnACoADwD+//P/AwA7AI4AzgDXAM0A2gD2ABsBOgEoAeEAngB4AHkA0gCqAQYD3wQYB4cJKAz9DvkR+BS4F/UZgRseHJYbAxqPF0IURhDfCw8H6AHg/Hj45/Qu8j7wGu+27tXuRe/67+Hw6vEc81j0Y/Uz9uL2gPcm+Of4uPmg+q37xPy3/Xz+G/+k/xMAMwDX///+uP0S/Df6T/h69vL05/Nl82nz+vMk9Qn3m/mN/Kn/4AIABssIIwv5DE8OMQ+QD1kPmw5xDeYLCArrB8AFvQPYAe//FP5o/OT6ivlc+Ev3RvZM9Vb0Y/OF8trxe/F28crxdvJ588f0UPYV+PX51Pus/WX/wQCsATECSwL/AXMBxQDt/97+rP2C/Ir75Pq3+iH7//sm/YH+8f9nAfICjAQCBjkHLgjYCCwJQgk4CRsJ5wiSCBwIgwfRBiYGiAXSBAsEXwPJAiQCeAHnAHsAMQAMAAMAAQADAB4AXACtAAcBZwG+AfwBPgKjAiADpQM+BOMEaAW6Bd4F0QWNBRUFagR/A1QCDQHO/6D+j/3E/Ev8Gfwc/Ej8ifzW/D39sv0H/i7+Qv5e/nr+mf7Y/kf/0v9qABwB8AHLAo0DKwSoBA8FXgWLBZQFiAVmBRkFkgTVA/cCBwIHAf3/7v7i/er8Fvxr++v6rPq0+uj6I/th+777OPy5/DX9vf1P/tf+P/+N/87/EABRAHgAcQBEAAsAyf9t//f+e/4M/qf9Qf3e/JX8hfyw/Pn8S/2w/TX+y/5j/wAAogA6AcsBYwL2AmQDrwP4A0AEawRzBGgESgQKBKADDwNaApMB0AANAD3/bP61/Rr9j/wb/NT7v/vY+wz8S/yR/PD8Z/3Y/S7+c/69/gH/Jv8e/+3+qv5x/j/+/f2g/TT9y/xh/PP7h/s4+xr7Jvs8+1L7ifsF/ML8qf2t/sL/3ADsAekCwQNrBPUEYgWpBcAFqwVvBRUFsQRMBNoDVQPJAisCXwFpAGb/Wv4z/Qv8FPth+t75mfm7+VT6Sft4/NP9Uf/RACUCOgMSBK0E8gTUBG4E3AMTA/0BsgBq/0f+R/1x/Nv7lfud++j7bvwn/Rf+Pf+DAMAB3wLkA8AETwVwBTUFzARSBLQD3wL3ATkBpQAPAHX/Cv/o/uz+9v4D/wj//P7u/vn+KP+c/5oAPgJrBA8HPwr7DQgSDRaiGV4cCB6RHuEd4Ru2GKQUww85Cn0EDv8P+qP1KfLM70TuTe387GvtZO6r7ybxv/JW9NL1HPcq+Bb5A/re+n778/ti/Mn8C/0q/TH9D/2//F385Psm+w36uPhb9xT2CvVZ9AX0B/Rx9F71z/a4+BH70v3SANEDlwYWCVgLZA0pD3wQNRE+EYsQDA/BDNYJnQZOA/3/tfyR+b72cPTS8uTxgvGU8QryxPKS82f0UvVZ9mb3XfhC+TD6O/tW/Gv9hP66//cABwLZAnUDxgOvAzoDdQJRAcn/Dv5V/K/6L/kC+FX3PPe497f4F/rG+8H98f8xAm0EkAZrCN0J8gqvC/sL2guHCyMLmQrSCdoIxwerBqIFtATCA8ACygECAWUA8//E/9z/GgBmAMAAHQFcAW8BawFgAU4BPQFIAX8B2wFdAgUDyQOOBDkFpwWxBUgFfwRtAyICuABL/+D9gfxO+3P6/Pnf+Qr6YvrY+nv7R/wN/a79Pf7V/lv/sP/i//7//v/u/+3/AQAVADIAfgATAesB/AIuBGIFewZcB+4HMQgzCPQHaAeaBp0FdwQ7AxQCIgFZALD/KP+2/kj+5f2c/W79U/1M/Uv9O/0h/RH9Bf3z/O78Cf0s/Tf9LP0f/R/9KP0p/RL96vzG/Kn8gvxX/DT8Hvwi/E78nvz3/GD98P2f/kj/3v9yAAgBmwEnAqwCKgOlAyEEmQQHBWkFugXqBe4FvQVcBeUEZgTNAwYDJwJNAWoAbv95/q39/vxJ/JH76vpo+hX67vng+dn50PnE+bj5wPnn+Sb6e/rn+mD70vtB/Ln8OP2s/Q7+Xv6S/q/+wv7S/t3+6v78/gv/Gf85/3n/z/80AKEAEAGMASICyAJjA+sDagTpBGUF2QVEBqQG7AYCB8QGNQaFBcsE8gPqArwBdAAd/9f9wfzf+zP7zfq3+ub6VPsC/OP80v2x/mj/7v9EAHUAgwBvADoA5P9q/+v+h/5B/hD+/P0G/g3+/v32/RP+RP5v/pH+qv61/qz+nf6a/rH+5/4y/4r/6/9MAKQA+gBXAa8B/AFJApwC5gIsA5EDLwQJBS0GpgddCSgL+gzpDv4QHhMVFZ0Whhe7FzcX/xU3FAwSiA+bDEQJqgUDApH+g/vp+Lf25vRv80fycfEC8frwPPGs8T3y1fJg8+jzhfQ09er1n/ZU9/33lfgT+XL5u/kC+kf6c/py+kv6B/qw+VT5APnD+LT43Pgj+X/5B/rU+uH7J/2q/l8AIwLjA6MFVwfxCG0KygvrDKENyw1qDZIMXwvgCSMINQYZBMABQv/d/MD67fhh9yb2L/VU9I3z9/Kq8qPy2PJK8+rztfSl9a/2z/cS+YH6CPyC/c7+2f+mAEkBuwHrAdEBfgHwACEALP9F/oP97vyJ/E/8OPxQ/K38Vf03/k7/nAANAoUD7AQ/Bo8H6gg/CmcLVQwNDYUNog1mDfYMXQyTC4sKSQniB3QGEwXDA48CjQG2APD/P/+6/l7+Ev7V/cD91f35/Rn+PP57/uD+X//k/2YA5gBTAZsBxwHmAfAB0QGGAQwBVwB1/4L+jf2W/Kj71Pod+o/5RflJ+ZH5GPrZ+s375vwY/lX/gwCPAXMCMgPaA3AE6QRDBZQF8wVNBpcG2QYiB18HfAd9B14HBgdrBqUFxQTEA50CYgE9AEj/g/7p/Yf9bf2F/ab9zf0R/nH+yv4I/y//Q/8+/xr/2P59/hz+s/06/a78Kvy6+1f7/Pqy+n/6Y/pe+mv6ePqD+qD62/ow+5H79Pti/Ov8iP0o/sX+fP9WADIB8QGZAj4D4ANtBOAEOQWABbEFtgWCBScFwAREBJwDxwLiAQgBOgB1/77+If6m/Ub99vy4/Jb8hvxv/Er8HPzi+5v7UvsR+9j6tvq7+ub6Ivtk+7H7BvxX/KT87/w6/Xf9mf2e/ZX9kP2Y/bT96f0s/mH+hP6w/v/+cP///7sApQGrArMDqwSQBWgGOAf3B5II8QgICdIIVgiqB+EGCQYcBREE4QKfAWcATf9R/nv92fxo/B/8Afwe/H/8F/3U/aH+af8WAJIAxgC2AHIADACD/+L+QP6r/Sj9vvyG/JT85vxj/en9av7f/jv/cP+D/4j/h/9x/zz/9f6u/oL+ff6e/tj+I/+A/+j/VADKAE0B0gFAAoECiwJZAvABYAHGAEwAGQBOAPQACQKIA2oFrQdVClQNfBCRE0oWZBirGRcauhmmGOYWhxSSERwOSgpYBosCHf8u/ML5wPcQ9qz0pfMO89zy6fIS80bzgPOp87DzpvOo883zE/R39Pz0pPVu9ln3ZPiN+b76zfuK/Nn8vfxA/Hj7efpU+Rj42va29cb0KvQH9IP0nvU/90P5lPsf/s4AhwMvBrYIAgvtDEsOCw81D9kOAw7HDDkLaAlkB0MFKAMyAW3/2f10/EH7L/ok+RP4C/co9nD11/Rc9AX00fPM8w30s/TK9Tr34/ir+ob8XP4SAJIB0ALAA0UESgTXA/4C0gFqAOj+cP0c/PX6BPpe+R75Uvn4+Qz7ffw1/hQABAL6A+0F1wesCWAL4AwYDv8Omg/vD/sPvg9AD4cOkQ1ZDPQKiAksCNQGdAUOBLICXwEIAK3+Yf0+/EL7XfqW+Qv51fj2+Gf5J/oq+1b8j/3D/ub/6gDDAWICvwLNAoAC2AHmAMX/kv5f/T78NPs/+mT5uvhc+FL4kPj++Jf5XfpI+0j8W/2K/tv/RAGzAhwEdgXABvsHIQkuCh0L6AuKDOwM+wyrDAEMBAu/CTEIaAaDBJ8CyQAO/4j9T/xh+7H6PPoH+hT6WPrF+lz7H/z4/MP9ZP7X/ib/Uf9T/yz/4v6B/hf+tP1c/RX93fys/H78T/we/On7rftx+zz7G/sR+xv7Nvti+6X7APxt/PD8j/1M/hr/6v+4AIABPQLsAo0DIwSgBO4EAQXWBHgE+ANhA7UC8AETASYAO/9n/rv9NP3J/HH8J/zp+7f7mfuQ+5r7qfu1+7/7y/vo+yX8jfwa/cH9b/4P/47/7f87AH4ArwDKAM4AtABxABIApf87/9v+i/4//vH9tP2p/dn9OP7C/oP/egCRAa0CvgPBBLcFlgZKB8oHIwhgCH8IewhTCAEIdwetBq0FhAQ/A+UBhwA1/wD+8PwL/Ev7tfpR+in6NPpd+or6rvrQ+vr6Lvth+4P7nPu/+/H7J/xh/LT8Kf2v/TX+wv5Q/7//AAAcACgAHQD1/7//kP9n/zb//v7U/tD+8f4n/2z/uv8KAF4AwgA7AcMBTwLSAjUDbwN7A2cDRgM3A18DvwNKBAIF8QULB04I2QnLCwUOQxBREhgUghV7FvsWAheJFngVuBNMEV4ONwsUCBEFQQK0/379m/v3+Yn4YfeI9t71OPWF9MjzAfMw8mnxwfBD8PzvA/Be8Pzwy/HR8hL0hPUM95D48vkL+8H7Gfwn/Pb7h/vb+v75+/jl9+D2EPaK9Vf1hvUh9ib3i/g/+jb8ZP7DADQDkgW7B5kJDgsFDI0M0gzmDLgMPgx+C48KiQl8CGEHNgYCBckDewIKAYH/6v07/Hr6ufgQ94X1JPQF8zny1fHr8YfyivPQ9ET26/e0+X77K/2t/u7/2gBkAZIBfAE1AccAKwBr/6H+5P0//bv8avxe/Jr8DP2m/WH+Q/9RAIUBxgL8Ax8FOQZNB1cIWAlRCjsLBgy4DFgN4w1GDoAOlQ6HDk0O3Q0mDRkMuQoSCT8HSgU7AxgB+P77/D771PnG+Bn4yPfA9+/3Uvji+Ib5HPqZ+gD7U/uM+577iftY+xz74vqw+o/6gfqJ+rD69PpK+6/7Kvy7/FD94P1z/g3/qv9QAA8B5wHKAqoDfwRHBQ0G3AaqB2IIAgmYCSMKoQoJC1MLbwtdCxULgAqWCW8IKwfOBVYE3QJ1ARUAtP5l/T78Pvtd+pz5BPmY+FL4M/g9+Gz4rfj9+FP5qfn4+Ur6pfoK+3v7+fty/Nf8N/2b/fD9I/5Q/oP+ov6b/oP+bv5V/jv+K/4f/g7+Bf4U/kH+k/4X/8b/hQBLARICzwJ7AxgElgTbBOUExwSFBBQEewPJAg8CWAGoAPv/WP+//jL+vv1y/Ub9Hf30/OD81Pyz/If8Z/xM/B/87/vU+8772/sI/Fz81Pxm/Q7+vf5h/+//ZwDGAA8BPQFGATQBEwHnAK8AegBLACQAFQAxAHUA1gBZAQMCvwJ9A0EE+wSVBQgGXAaEBnoGWgYpBtUFUgW4BBMEYgOgAtUBCQFMAK7/Mv/W/qD+if54/mX+Tf4n/ub9l/02/bT8G/yP+x/7v/pw+kL6NPo++m76zvpK+8/7Z/wR/bz9W/7m/lv/vf8MAEsAgACuANMA+AAqAW8BtgHqAQ0CKQI+AkwCWAJaAlECSgI+AhsC6AG1AXoBLwHcAJEATwAMAMn/lf98/43/1f9MAOcAmgFIAvACuQOtBKQFiAZnB0IIBQm1CWcKDAuAC7kLzwvGC4sLIAuKCtAJBwkyCEQHRgZEBT8EMwMqAicBLAA2/0n+cP2p/PH7Sfu0+i76wvlr+Rf5xvh9+DX49/fK95n3V/cZ9+720faz9pr2mPan9rL2v/bk9hz3XfeP96X3t/fZ9//3IvhT+JT41PgR+VH5kfnJ+fz5Mvpq+pX6x/oa+4j7D/yx/Gv9Pf4u/zEAMwEwAiYDDgTdBJIFOQbeBnEH6QdPCKcI8QggCSYJFAn6CMEIUgi3B/oGHAYkBRsEEAMGAvQA3v/U/t/9Dv13/BX83vvR++L7B/xE/KD8IP2//WP++f6B/+3/NwBqAIoAlQCOAHAAMwDq/6n/cP8//xn/E/8t/z//QP9W/4//0f8WAF4AmgDKAPUAIgFSAX8BrQHlARcCMgJFAlcCagKGAqACnwKIAmMCLQLnAYwBGwGmADIAs/82/9H+lf6E/pz+1P4o/4T/3v9NANEASQGvAQcCRwJsAoACggJ3AmMCSAIxAiMCFwILAvEBywG0AbQBswG0AbsBugGzAb8B4wEcAlgChQKlAscC5ALqAtACnQJtAj4C8gGNAScBwwBiAAUAoP80/9D+bf4J/qj9P/3N/F78+fuo+2v7NPsI+/X67Prp+gT7PPuL++/7V/zC/ED9zv1q/gX/h//y/1wAvgAKAUYBbwGMAaEBoQF/AUwBDQHMAJYAYgAuAAAA0P+d/37/cv9q/2//g/+d/8L/4P/u//z/HABMAHYAewBhAEgAJwD0/8j/rv+U/3f/Xv9L/0H/Of80/0H/Xf90/3//eP9i/07/Mv/9/rz+ef4w/uv9qv1o/UD9Rf1j/ZL92P07/rj+MP+e/xoAogAVAWsBpwHPAfABCQIIAvsB9wH8AQoCHAIhAikCPgJiApACuALLAtUC0AKhAlAC7AFvAeQAWAC8/xv/jv4W/qb9NP3P/JP8ffxu/Gv8hfyx/OX8G/1H/Wz9k/2s/bX9tv2x/a/9uv3M/eb9F/5i/s3+Tf/F/z8AzABQAbkBEQJWAn4CggJcAhwC1QGIATUB5gCYAF0APgAlABAAFwA2AF8AjwDDAAEBTQGWAdIBCwI/AmgChQKWAqMCtQK9ArkCvALDAsACwQLMAtgC4ALaAroCigJNAgQCsQFJAdUAbAAHAJT/Jv/G/nn+TP42/iv+NP5Q/nn+uP4H/1z/tv8LAE8AhACfAKQAoACKAEkA8v+k/1//If/n/q7+gv5m/ln+Yf54/pL+tf7Z/un+9f4G/xP/Hf8j/x3/F/8Y/xv/Hf8i/y7/Sf9u/4r/qP/F/9b/4f/n/93/w/+e/2P/F//N/of+Q/4A/sj9sP20/cX96/0s/nv+2/5K/7j/JQCSAOsAMwF2AacBwgHKAboBogGHAWMBPQEhAQkBBQEYASkBQAFuAagB3AESAk4CiAKtArACpwKgAosCWgISAr0BcQE2AfIAqgB2AFMAQQBJAF0AeACgAMoA8AAUASgBKgEgAfoAvQCEAE8AIQAGAOf/vP+d/5b/lf+P/3v/Xf88/wf/wf54/iL+tP1D/dX8bPwN/K37Uvsa+wD77fry+h37ZvvA+xn8c/zo/G396/1w/vf+Yv+//yAAfQDOAAsBMwFcAY4BrgG1AaoBlQF9AVkBJgH7AOIAyQCvAJcAiACLAJYAmgCsANMA+gAZAToBYgGOAbQBzgH3ATsCgAK8AvYCIgM+A1oDcwN8A3EDTwMeA+sCsQJqAhsCzAF9ASYBwgBjABMAxv94/zf/B//d/rf+pP6m/q3+rP62/sv+0f7P/tT+1/7R/sj+vP6u/qf+oP6O/m/+S/4u/h3+DP7w/c79rf2Y/Yn9hP2L/Zf9of28/ez9IP5W/pj+5/41/3P/pv/h/x4ARgByAKgA0ADlAAEBHwE2AUUBTgFaAWsBeAF7AXsBcgFbAUABLAEiASABGQEXASIBMQFGAWQBfgGUAawBsgGoAZ4BiAFfAS8B+gDIAJMAQQDb/4r/Sv8J/97+xv6m/n/+YP5V/mL+bP5l/mr+iP6t/tb+//4o/2D/pP/b/wUALQBdAJIAtgDCAMUAvQCpAKEAoACHAF8ANQAGANn/rv99/1X/OP8R//f+/f4Q/yH/PP9k/53/3v8KAB0AMwBLAF0AZwBeAEUAKwAIAN3/vf+p/47/b/9V/zf/CP/I/pL+b/5K/h7+9f3K/Zz9gP14/Xv9jP2i/bP9y/3z/R7+VP6Z/uj+Pv+K/8j/FAB6ANkAIQFhAaEB3gETAjQCRAJTAl8CVgJBAjICKwIhAhAC/QHuAeYB2QHGAbkBrwGdAXwBXgFKAT0BKgEOAeQAsACDAGIAPwAQAOD/vv+s/6P/mf+Y/5z/lv+R/53/q/+u/6//rf+c/4n/ef9i/0v/N/8e/wX/9v7n/uD+6v7w/u7+8/4C/xL/F/8U/xT/Gv8Y/wr//f74/v3+CP8R/x7/Ov9k/5z/3f8bAGAAtAAFAUkBgwGtAc0B6gH8AQcCEgIIAuwB4QHgAdQBywHNAcwB0AHYAdYB1AHZAdIBwwG5Aa8BmQF6AVkBOAEOAeEAxQC2AJsAfwByAHQAfACAAH4AgwCSAJoAmQCPAIEAfgCIAIMAcABjAF8AVwBEACgAHgAlABcA8//d/8X/lf9m/0P/D//L/pP+YP4j/uT9sv2M/W39VP1O/WD9gP2q/dn9EP5O/pP+1f4P/zv/Wf9y/4P/gv9+/4X/iP99/3b/eP98/3n/bP9n/23/bf9r/2f/UP8w/yT/Hv8M/wX/A//q/tL+1/7o/vP+/f4N/yb/S/9z/5z/zv8HADQATgBiAHwAlACfAJsAiABqAFYATgBAAC4AKAAnACcAOQBcAIkAuQDoABoBUAF/AakB1AHsAfMB/gEBAvMB5QHTAbYBmwGEAV8BOgEjAf4AxwCaAHcASQAQANr/ov9g/xv/2f6X/lr+Lf4E/tP9qv2Y/Y39gf2B/Yj9jP2Z/bL91f39/Sn+WP6K/rn+6f4X/z3/Xf+C/6T/wP/h/wMAJABUAIQAoQDEAPUAGAE0AVQBZwFpAXIBgwGJAYkBkwGnAcEB4QEIAi4CUAJ1AqACvQLHAtIC5AL2AvcC3QK6Ap0CeAJBAgECuwF1ATEB4ACBACYA2v+Z/1//Jf/w/sX+lP5g/kr+Sf43/iD+Iv4r/jH+Rf5g/nP+i/6w/tz+Cv8z/1D/bv+R/67/wf/b//z/EwAaACAAJAAZABYAIQAeAAgAAgAKAAwACQAOABoAMQBOAGQAdwCJAJkAqQC5AMYA3QD2AAQBCAEEAe4A0wC5AIsASwANANH/kf9U/xT/yv56/jf+Bf7h/cP9pv2H/W79aP11/YL9jP2a/an9xP31/S7+Yf6a/t7+I/9n/6P/1P8MAEkAfACgALkAxgDLANEA1ADQAMoAyADSANkA0ADPAOIA8wD+ABEBIgEhARYBDAECAf8A+QDnAM0AsgCZAIkAgQBwAFgASgBIAEEAMQAlABoAAADp/97/x/+a/3H/Uf8t/wb/3/63/pf+ff5m/l/+aP5v/nP+fv6M/pr+q/61/rv+yf7c/uL+4v7s/gP/HP8v/0T/bP+l/9v/CwA8AHQArwDmABoBSgF3AZ8BuwHCAcMBzQHQAb8BrQGkAZ4BlwGMAYEBhQGMAYYBgAGCAXsBagFmAWIBRQEYAfcA3QDIALQAnwB+AFYALwAMAO7/2v/O/8b/xP/K/8r/xv/I/8n/xf/I/9D/0//Y/+r/9v/4/wUAIQA4AD8ATABpAIAAgQCAAIoAjgCDAHEAWwBDADEAJgAVAPj/1//H/8T/vv/A/9b/7P/4/wcAHwAuADEAMAA4AEgATAA+ADkAQQA7ACMAEwAOAAEA5//K/6v/iv9w/1b/Kv/q/rL+i/5m/jz+Ef7q/dD9xP2+/b39w/3O/ef9D/46/mf+nf7X/hP/Tv9//6n/3v8OACYALgAyACsAIwAnACkAIAAfACkAKAAkADgAUwBdAGEAdQCBAHsAgACTAKYAugDSAOIA5wDuAAABGgExATwBQAFNAVMBQAEdAf4A3QCqAG4ANwAGAM//kv9e/zH/Af/H/pH+av5Q/kT+Qf4+/jj+Qf5g/nv+hf6U/rf+5f4L/yv/S/9t/4//r//R//T/FAAyAFEAZwBqAGkAcAB2AHUAdgB8AH8AhACRAKYAwgDkAAgBKgFKAW4BlwG4AckB1AHsAQEC/wH2AfYB6wHHAakBlwF7AVYBPwEuARMB9gDbALQAiQBhADUABQDh/8L/m/92/2L/Vf9K/0f/Qf84/0H/Zf9+/4H/iP+e/67/sP+v/7b/u/+w/5//lv+X/5f/mv+n/7f/x//e//n/DwAjAEAAXgByAIMAlQCjAKkAqgCoAKEAmgCbAKUApwCZAIwAkQCXAJMAhABuAE0AMAAfAAkA5f+8/5H/Zf8//yj/Gv8M//3+8v70/gj/Iv8w/zb/Qf9O/1f/X/9d/1H/S/9L/0z/Uf9X/1X/Tv9U/2b/eP+L/53/o/+v/83/5v/p/+3//f8EAP3/9v/y/+v/6v/r/+T/3f/h/+n/7f/z//z////4/+f/1v/M/8b/u/+r/5z/j/+C/3v/eP94/4H/kv+i/7H/wv/P/9L/1f/i/+v/4v/S/8n/xv/D/77/s/+d/4z/jv+f/6f/p/+u/7T/tP+4/8n/1//f/+z/9//9/wwAJgAwACoANgBWAGwAcwBxAHAAeACOAJsAlgCPAI8AiAB4AGoAXQBQAEwAUABPAEkARQBGAFUAcACFAJEApwDHANUA0gDTANsA5ADqAOUAzQC1AKcAlgB2AFcAQgAxABoABwD7/+3/1//F/8D/wv/C/8H/vf+x/6L/pf+2/8T/0//t/woAGQAkADYASABcAHIAgwCDAHgAdQB1AGwAWABHADkAKwAaAAoA/P/w/+j/5//q//P/+//6//X//P8KABQAHgArADAAMQA+AFAAVQBYAGkAdQB5AIcAlwCYAJgApACmAJAAegBtAFgAPAAmABIA+v/f/8L/o/+K/37/df9p/1j/R/8+/0H/PP8s/yX/Lf8x/yn/KP80/zP/JP8Z/xr/F/8M/wb/BP/8/vD+7f7t/u3++f4W/yz/L/8w/0P/Yf97/43/n/+//+r/CQASACAAOwBPAFQAYgB8AI8AlgCfAKcAoQCVAJEAkgCNAIIAdQBgAEQALwAoACEADAD3/+v/5//n//H/AQAKAA0AFQAhAC4AQQBUAGIAbgB2AHYAcABkAFMAOwAfAAMA7f/e/87/s/+Y/4f/dv9k/2T/cf92/27/b/96/4P/j/+t/87/5v/4/xEALwBNAGQAegCVAKwAvQDKANMA0QDLAMkAxQC0AKEAlwCPAHwAXQBAAC0AIAASAAYABAACAPL/2//V/+H/6f/h/9T/1f/h/+H/0//J/83/0f/N/8f/xf/E/8f/1P/h/+T/5P/r//j/BAAMABgAJgAyADgAPgBEAEgARQBDAEYAUABgAG8AeQCBAJMApQCtAKYAnACYAJ4AowCZAIIAaABVAEsAQgAzACYAHwAcABgAEwAPAAoAAwD6/+v/2P/T/9b/0v/H/8T/vf+p/5P/iv+J/3//b/9g/1n/Vv9W/1j/ZP92/3//ev92/3f/ef96/4D/hv+L/5T/m/+W/43/jv+T/5X/mv+k/6D/kv+Y/67/uP+0/7j/wv/B/7z/wv/P/93/8f8MACQAOABGAFAAXABxAH4AfwCDAI8AlgCRAI4AkQCSAJIAkwCMAHQAVAA3ACEACADu/9T/xv/C/7v/qv+a/5v/qf+//9v/9P/+/wQAFgAxAEwAYgBtAGkAXgBXAE4AMwAXAAcA9P/U/7X/ov+O/3P/Yv9h/2b/ZP9g/2L/bP97/47/o/+//+P/BAAXACAAMQBOAHAAiwCWAJYAkwCTAJMAjwCEAHIAXQBHADMAGwACAO3/2//I/7j/sv+v/6T/lf+Q/5f/nv+e/6P/sv/E/9L/2v/d/9z/3v/j/+T/6P/w//f//v8DAAkADwAaACoAKAAWAAsAFgAhABwADgABAPn/8v/p/+T/6f/8/wwAEwAhAD0AWABqAHwAjACWAKAAqwCyALIAsgCxAKwAsQC6ALUAoACQAI0AjACKAIkAhgB9AHUAagBWADsAHwAEAOj/0f+9/6f/kP97/27/Zv9f/1b/Tf9S/2D/a/9r/2X/Xv9d/1//Wv9N/0T/Pv8t/xn/Ef8Z/x//Jv81/0b/Uv9i/3X/gf+L/5//tP+8/8L/0//k//D/+P8CAAcADAAdADkAUgBiAG0AegCFAIcAggCEAJMAowClAJoAkQCMAIYAfQB3AHMAbQBmAGEAXgBYAFUAVgBZAFkAVwBRAEcAOwAuAB4AFAARABAACQABAPr/8//s/+n/5P/k/+r/9P/5//3/BQACAPT/7//8/wUA/v/y/+j/3f/Z/9r/2f/X/9//7P/3//7/BgAKAAYAAAD7//n/+/8BAAgADwAYABoAGQAgACsALQAqAC8AOAA+AD4AMwAdAA4ACQAAAO3/2v/I/7P/oP+S/4H/cf9u/3D/a/9x/47/q/+1/77/1f/t/wIAFQAmAC8AOgBEAEQAPwBIAFoAXwBXAFYAWgBWAEgAPAA7ADkAKwAaAAwAAAD0//L/8P/m/9r/2//e/9z/4//x//b/+f8IABgAHwAmADUAPQA/AEQASgBHAEwAVABPAEAAOwA1AB4ADgATAA4A9v/m/+j/5v/f/+b/9P/1/+z/5v/o/+7/7f/h/93/6P/r/9v/0v/b/9//0//N/9T/1v/O/8r/z//R/8n/vf+0/7L/s/+0/7T/tv+0/7L/uf/G/87/z//b//T/BQADAAEADAAaAB4AHwAqADMAMgA6AFAAWwBRAEgATwBUAEsAQgA8ADYALQAoACYAKQAwADQANQA6AD8AOgA3AD0APwAxACgAKgApAB0AEwALAPT/1f/F/8v/z//D/7f/tv+0/6T/nP+o/7P/sP+z/8b/0//Q/9H/2//a/9P/0v/c/+b/8P/x/+v/6P/u/+z/5//v//r/8//o/+7/9P/u/+r/8f/z//D/7//y//L/9//9/wAAAAAHABIAGwAlACwAJQAXAA0ADgATABIACQD+//v/9//u/+n/4//U/83/3P/u/+b/0f/L/87/yf+7/6v/pf+p/6j/of+l/7z/yf/C/8H/zv/X/97/6v/x/+z/8v8EAAkABgARAB0AGQASABgAGwAXABEACQACAAwAIgAqACkANQBEAEkAUwBmAHMAdwB+AH8AcgBuAHcAdABfAE8ASwBDADoANQAuAB4ACwD8//D/4//S/8D/uf+6/7X/rf+w/7L/p/+a/57/rf+7/8T/zP/Q/9f/4f/n/+j/6f/p/+n/7v/x/+z/6P/u//n///8AAPz/9P/z/wAACgAMABAAGQAgACAAIQAkACUAJgAyAEoAXwBoAGUAZABmAGYAawB6AIoAiQCAAHwAhQCQAI4AfQBqAF8AVAA9ACUAFAAGAPv/+P/z/+X/2f/U/8//z//X/9f/yP++/8X/xf+z/6X/o/+h/6D/p/+t/6j/pf+q/7D/t//A/8b/xv/H/8r/yf/Q/+L/8f/v/+v/9P8FABQAGgAZABgAHwAqADMANQAzADYAQABGAEAAOAA5ADkALwAgAAkA7//g/+T/6P/f/9j/1//S/83/2//u//b//v8OAB4AKAAsACgAIgAmAC0AJwAdAB0AIAAbAA4A///z//L/+f/5//T/+P/4/+//8P/9//3/6P/X/9r/4P/l/+f/6f/v//v//v/5/wgAJAAlABQAEwAfABsAEQAUABkAFwAVABYAEgARABsAHwAbABwAJAAqACoAJwAmAC0AOwA+ADMAMQA8AEMAPwA7ADIAJQAbABEA/v/s/+j/4f/P/8X/xP+6/6b/lf+K/4P/hP+I/4r/kv+i/6//tP+//9L/3f/m//v/GAAtADoARwBMAEMANwA7AEUARAA4AC8ALAAeAAUA9P/t/+b/5f/r/+z/4v/U/9D/2P/o//v/BgAFAAIA/v/9/wQAFAAaABUAEwAZABYAEAAUAB8AHwAYAA8ACgABAPX/6f/f/9b/zf/E/7//v//E/9D/2f/V/9D/2f/s//f/+/8BAAwAFAAYABgAFQAVABwAIgAkACcAKwAnACAAGwAYABIAFAAbABsAFwAaACAAHwAYABsAKAA3ADsAOAA2ADYANgAyAC0AIAATAAwACgAFAP3/+P/4//n/+v/5//b/8v/t/9//yv+4/7D/sP+0/7n/uf+y/67/r/+x/6//r/+x/7H/r/+u/7D/sf+z/7n/wf/F/8n/0P/W/9f/0v/P/83/z//T/9r/3//h/+H/3v/g/+z///8QABoAGQASAA8AFAAXABcAGwAmAC4ALgAqACQAIQAiAB8AEwAFAPv/9v/1//b/8v/p/+r/9P/2//D/8v///w0AGAAkAC0ALQAxADsAQwBCADsANQAyAC8AKgAjABoADgACAPr/9//2//T/7f/j/+L/7P/x/+n/4v/j/+T/4f/h/+P/6f/7/woABgD+/wEABAAIABoALAArAC8ARABPAEUAQQBCADkAMgA7ADYAHQAPABMACQD+/wEA/v/u/+7/+//8//7/EwAfABcAFAAZAA4ABAASACgALQAnABgAAQDw//H/8v/u/+z/5f/T/8v/2v/o/+P/2v/X/9n/3P/Z/9f/3v/r/+v/3P/S/9n/5f/s/+P/1v/T/9n/2f/i//n/AADw//D/BwAEAOv/6//6//D/6f8AABIABwD7//3/AgAKABAAAgDv//D/+P/8/xIAKwAfAAUADAAPAOf/yP/X/+n/4f/Z/93/2v/Y/9//2//L/8H/tv+q/7P/zv/W/8z/z//f/+T/6f/9/w8ABwDy//P/EQApACcAJwA8AEgANwAoADIAPQA2AC4ALwAyAD0ATABSAEUALgAbABIADQAdAJkA1AFvA4gEqAQZBDsDRAJ2AfIAmQBNAA0Ap//v/ir+vv2V/W/9S/1F/WX9t/04/s7+Yf/X/wYA7v/U/8z/kv8Z/7X+mf6h/qv+u/7M/tL+0/7m/ij/mP/h/67/MP/y/hT/O/81/zf/bv+4/+P/+/8iAE0AWQBWAG8AlQCgAKoA5gA/AXoBogH7AZwCPQOAA1MD6gJ5AhICwwGlAacBoQGUAX8BRQHlAKAAhgBUAO7/nf+i/9z/DAAeABYA7P+T/yL/0P6l/m3+Gv7s/QT+Hf71/cP9y/36/R/+Qv56/rv+5P7m/sn+lf5U/hP+5f3X/fL9Kv5t/qr+6v4+/5T/wf/G/9P/DgBtANsAUAG6AQkCOwJVAkQC6QFUAcgAdgA+AP7/1//8/1wAwQATAUoBTQEgAQwBRQGiAc4BrwFzAUUBLQEaAf4A3ADMAOAA+ADdAKAAlQDXAAQByABlAEgAZQBeACwAHQAvAA4Anv8z/wf//v7j/rX+g/5g/nD+w/4i/0z/Qv9D/2f/i/+j/83/BAASAPf/+v87AHoAgABpAFIAJgDY/5b/i/+g/6n/oP+U/4//kf+g/8P/8P8TAB0ACADa/6z/oP+k/4T/Ov8J/yf/fv/e/zcAgQC6AOsAIQFGAUABIQEJAesAqwBXACEAFAD+/7H/Sf/+/tv+yP7E/uP+I/95//f/ngA3AYkBigFKAdwAbgA6AEcAZwBzAHAAcABxAF4ALgDy/8b/sP+w/8X/3P/i/+T/8f/n/6b/Uf8Z//b+xf6c/pz+tv6+/rT+tv7J/tr+4f7//lD/rf/g/+r/8P/s/8f/mv+O/5H/ev9Y/1L/YP9Z/zb/Ef8H/xT/LP9U/6D/BwBkAKgA4AAIAQ0B+wDrANQArgCSAJoAtADAAL4AvgDIANoA4gDkAPYAHgE/AUABJAHzAK4AUwDl/2n//P7K/tH+3v7j/gb/XP/H/yEAWgB8AJcArwC8AMAAvgCjAGIAGQDr/9L/qP9r/zP/F/8k/1H/gv+n/83/+f8NAAYA+f/0/+//6//1/xEAIgAOANn/sP+t/7T/nv+J/6j/9f9DAIcA0AAXAUIBQgEZAdYAnACEAIQAgABbABQAxv+Q/27/SP8u/zz/aP+U/8b/EABiAJoAsACyAK8AqgCXAHEATAAxAA8A3P+w/5//nP+f/67/wP/K/+X/LgCOANEA2QC6AJYAgABtAFgASQBEADAA///R/7v/sv+o/6v/wv/j/w4APABZAF0AXQBjAG4AeAB4AF0AJgDw/8v/sv+Z/37/bf9r/37/m/++/+z/DgAOAP//CAAeACAAEgALAAEA1v+c/3b/av9p/2n/bP95/5L/s//S//D/CwAhADwAWQBqAG0AeACLAIIAYABKAEAAIAD5//j/GgArABYA/f/7/wgAEQAXACwAUABpAGwAYAA/AAYAy/+x/6H/ef9K/zT/K/8c/yL/Tf+B/6D/uv/f/wgAIwAyAEUAYABpAFEAJgADAOH/t/+U/4b/ff9t/2n/cv93/3z/oP/a/wUAEAAOABQAJwBAAFEAUwBHACoAAADh/9r/1v/N/8n/0v/b/+X/8v/7////DwApADYANAA2AEEATABKADYADgDk/8b/qv+N/3//h/+Z/7T/2////xEAIAA+AGEAcQBpAGAAagB5AGsAPAARAP3/5//G/7j/wP/E/8D/1P8DACsAQQBcAIMAogCsAKYAmAB+AFgAOAAzADMAFgDf/8L/0f/t//r/AwARABcAEQAGAPX/3v/K/8D/t/+o/5b/k/+f/63/ov+I/4r/sv/Y/+T/8f8PACkAMQA3AE4AbgB+AHAASQAhAAkA+v/4/wIAAgDn/9X/4//9/woAIABIAGcAZgBVAE4AXwB2AHoAZgBLAC8ACwDv/+n/6//W/7T/mv+I/4L/jP+a/6f/xf/5/xsAHAAbACMAHwAIAPj/7//S/5P/Vv9H/2D/Y/82/w//G/8+/0z/Tv9m/47/tf/S/9n/yf+2/7P/t/+3/6//ov+Y/5v/q/+3/8P/2f/1/wsAHAAwAEUATwBMAEgAVABpAG4AWQBNAGcAhQB/AFUAMQAnACgAIAATAAkACQAKAA0AEQAUABYAHQAuADUAJgANAAUADAARABMAFAAPAAIA//8OABcADgAGABEAGAANAAMADgAbABwAGAAiADIALgANAOr/2//d/+L/9P8RAC0ASwByAI4AhgByAHMAeQBqAE4APwBBAEQAOgAwADoAVABjAGYAewCfAK0AnQCKAHoAXAA3ACUAJgAoACAAEwASACEAKQAfABwAMQA9ACEA9P/h/+//BwAQAAMA9f/6/wIA9v/k/97/3f/X/9z/6//x//P/+/8DAAAA/P8DAAgA///q/9T/x//M/9z/7/8CAA4ADgAEAOz/x/+u/7f/x/+9/7H/0P8EABsAEgAMABkAKQAoABcABAD+////AAAAAAQAFAAmAC0AKgAtADwASQBSAF4AZgBQACEA///+/wYA///0//X/+P/t/9n/0f/d/+n/7P/u//f/+v/t/9n/0P/V/9X/t/+D/2T/Zf9p/2j/d/+X/7D/tf+y/7j/yf/T/83/x//K/8X/p/+G/3H/YP9O/0r/V/9j/2v/ev+P/6T/uf/N/9z/4//c/83/vv+u/5z/k/+f/6b/lv+M/5v/qf+m/7P/3v///wIA+////wYACwARABIAAwDm/8//zP/K/7X/of+s/8X/xP+1/7z/2P/r//X/AAARACcAOgA8ADEAKgAwADAAJwAgAB4AFgAFAPP/6P/l/9v/yv/D/83/3P/t/wYAIQArACYAHQAWABMAFAAPAAAA9v/3//b/8v/6/w0AIAAwAEgAYgB3AIUAhwB8AG4AXgBRAEQAMAAJANr/sv+Y/5H/oP+u/6f/l/+c/7b/1P/y/wwAGAAgADIATgBkAG4AcABuAG8AbQBpAGoAdAB4AHAAbABrAGMAWgBcAGQAZgBlAGUAaQBwAGwAVQA7ADQANgA3AEMAYwCCAJEAnACyAM0A2wDTAL0AtADDANIAzgC/ALIApwCaAIQAZQBJADQAIwAbACIALAAoACUAOgBbAGsAaABcAFIAUgBTAEQAMAAxAEMAQAAdAP7//v8HAPr/3P/P/9n/1P+2/6P/uP/W/9z/0v/I/7r/rf+t/7D/q/+q/7b/xv/W/+b/+/8TAC4AQgBJAEYAPAAyADEAOQA8ADYAMQAvACkAGQAAAOj/6f/8//3/4//P/9X/5//z/wMAGgAxAEEASQBJAEoAVQBhAF4AUgBJAEMAMwAXAPr/7P/m/9r/xP+1/7H/pv+V/47/i/94/2L/Wv9d/2P/bP9x/23/Zv9i/2D/X/9b/1n/Z/+B/4v/gv+C/5L/nP+X/4v/ff9r/1j/RP82/zT/Mf8m/xL/+/7l/t7+6/70/uX+zv7L/tj+2v7e/vH+BP8D/wj/I/9B/1H/W/9g/1v/UP9P/1f/Xf9X/0//Vv9h/1z/Xf9z/4X/hP+I/5r/o/+j/6z/wv/W/9//3//m//b/AgAAAPz/AAALABkAIgAkACcANwBHAEwAVABsAIEAeABcAFAAUgBKAD8AQwBIAEMAQwBTAFcASgA+AEcAXgBlAFIAQgBWAHIAdABnAGYAbQBrAF4ATwBQAFMARAAoABYADQABAP3/AwAEAAEABQAFAP//AwAVACkAMgA3ADkANAAqACYAMAAzACQAEwASAB0AJgAlAB8AHgAjACYAKgAwACsAIQAqADgAMAAgACMANABCAE4AVwBeAGIAaQB1AIsAnwChAJcAiwB+AHwAhwCMAIEAdwB0AHUAgACTAKUAuQDNAM8AvQCyALoAxADAALcAsAClAJQAiQCNAJMAmACeAJ4AjQB9AHcAawBUAEkATgBRAEwARwBPAGUAbwBoAGgAdABzAGgAcQCOAKAAnwCcAJwAoQCbAIUAdAB6AIkAkwCUAIoAiACeALwAzADbAPUADgEjATwBVgFlAXYBmgHQAQMCLwJcAoQCkgKJAn8CeAJoAlQCOwIeAgUC9gHhAcIBpwGRAXkBXwFAARIB4gDDALEAoQCLAGUAOQADAL3/cv87/xT/7/7L/qP+bP46/hr+9/3E/Yz9W/0q/fP8tfx6/FD8MPwO/PH73vvI+6v7l/ub+677uvu6+8D71vvw+wr8KfxF/FT8Zfx//KD8yvz5/BL9F/0x/Wn9of3P/QD+Ov51/qT+yv75/i3/Vf95/6b/1/8DAC0ASABZAHEAkQCrAMcA8AANARMBFwEpAT8BUQFbAVsBVQFEASoBGwEaAR4BIgEiARwBEAEJAQEB9QDmANQAxgDFAMQAtQChAJAAdABRADsAMgAzADgAOgAzADAANgA5ADUAMAAnABoABQDs/+f/8v/2//T/BQAiADQARgBeAHEAfgCIAIwAjgCdALMAvgC+AMEA0gDsAAUBGgEuATkBPQFRAXcBmAGvAcgB1gHNAbsBpwGOAXcBYwFPAUABMwEgAQgB/gACAQkBCgEAAfIA7gDwAOoA3gDOALcAlwByAEsALgAeAAwA9//x/+//4//X/8z/t/+d/4j/b/9Q/zr/Mv8t/yT/Gf8Q/wn/+f7d/sT+s/6m/qj+sv64/r3+0v7l/u/+AP8c/yn/Jf8j/zP/Tv9r/3z/if+c/7P/y//i//H/+/8MABsAIgAsAEIAWgByAIwAnACkALEAugC/AMoA1QDWANoA4wDnAOkA9AAFARwBMwE9ATQBKwErATIBNAEnAQsB8ADYAL8ArgCfAIQAawBmAGQAVgBOAE8ASQA7ADAAKAAhABkACwD6/+v/6P/s/+P/v/+Y/5D/l/+K/3D/Xv9Z/1z/Y/9h/1L/Rf9E/0r/VP9Y/1f/Xv9r/2r/Xf9W/1f/Yv9x/3z/gf+G/47/nf+2/8L/tv+p/67/uP+2/6X/j/+F/4j/hP9t/2H/d/+Q/5L/hv+L/6j/vv+6/7f/y//g/+L/2P/K/8b/0v/i/9//1f/W/9n/4f/3/wkABADw/+v//f8WAB0AFwAcADIARABMAE8AUwBdAGwAcwB0AHsAgAB7AHoAgQCGAIgAiwCJAIgAjgCVAJwAogCdAIsAfgB+AH0AcQBdAEkARQBLAEcAOgAxACkAHQARAAUA+v/8/wEA+f/r/+b/6P/m/93/yP+z/6T/lP+K/5H/mP+M/3f/bf9p/2f/YP9Y/1H/Tv9B/zT/N/9G/0r/Qv87/z3/Q/9G/0X/SP9U/17/Yf9i/2H/Yf9c/0//P/9C/1D/Wf9i/3P/gP+D/4b/i/+N/47/j/+S/6D/tP/C/8n/0v/b/+X/6P/l/9//2//W/9D/yP/E/8v/2f/d/9T/0P/T/9L/0f/U/83/wf/E/8z/zP/S/+P/6f/c/9r/5//p/9H/vf/F/9P/0//X/+X/7v/w//3/EwAeACIALAA3ADsAQgBEADwAMAAtADIAPQBLAFoAZwBsAGkAawB0AHkAdwB8AI0AnwCuALcAvgDCAMIAvQC2AKYAiwB2AHUAeQB1AHYAgQCMAI0AhwB9AHcAdQB1AHIAbQBtAHQAdgBuAGcAaQBjAFQAVQBjAF0AQQAzADsAQQA9AEMAUABSAEMANQAyADsARwBRAE0AQwBHAFMAVABRAFgAYgBlAG0AfwCGAH0AcwBzAHkAfQB8AIAAiQCKAIEAgwCSAJsAmQCdAKMAnwCUAJgAsADHAM0A0QDZAOMA7wAAAQYB+gDwAO4A6wDpAPUABQETASYBQAFdAXgBiwGYAaYBvgHPAcoBwQHGAdABzgHGAcYBwAGuAaQBrAGsAaMBpgGwAa4BoAGbAZcBgAFeAUUBNQEiAQEB1wCwAI0AZAA5ABYA/v/j/7r/kv90/1L/Jf/7/tr+sf54/kb+J/4R/vL9yP2c/Xj9W/1D/Sv9FP3//O/84/za/M78vvyv/KD8kfyK/In8ifyJ/Iv8l/ym/K78tPzB/M78zvzM/Nn86Pzj/Nv87fwN/Rj9Ev0a/S79OP1D/WP9iP2g/bb91/3y/QD+GP5A/l3+Zv5y/o3+rP7H/uT+BP8g/zX/Sf9i/4H/o//F/+L/9/8HABoANABQAGkAgACXAK0AxwDrAAoBGwEuAVUBgAGXAaABsAHOAeYB7AHnAeUB7wH3AfEB7AH6AQYC+gHoAegB7QHiAc8BxgHGAcUBxgHDAboBsgGwAagBlwGKAYIBdwFqAWYBZgFXAUIBLwElAR8BFAH8AOEA1gDWAMkAtQCwALgAtgCrAKkAsgC4ALoAvgC8ALwAzADmAPAA5QDgAOkA7gDmAOcA+wANAQYB7wDoAPkACAEFAf0A/gD7AOoA3ADlAPMA7ADUAMQAvgCvAJYAgwB9AHYAZQBUAEkARABBADsALgAhAB4AJAAgABIACAADAPP/3P/G/7f/qP+e/5r/kP9//3X/c/90/3n/hv+S/4//hv+G/5L/m/+g/6D/oP+p/7f/uv+0/7X/wP/C/7b/sv/D/9v/5//j/+X/8P/w/+D/1v/a/9r/z//K/9P/0//J/8b/zP/M/8X/wf+9/7z/xv/P/8b/sf+t/7z/wf+z/6D/l/+Y/6D/oP+W/43/lP+b/5X/jf+V/6D/oP+a/5T/jv+J/4b/gf92/3D/cv92/3T/dv+C/47/hv93/3X/gf+C/2v/U/9U/1n/S/87/z3/Rv87/yH/F/8k/yz/Hv8K/wf/Fv8d/xf/Gf8s/zj/L/8m/yv/M/80/zf/R/9X/2L/av9z/3z/hv+R/5n/of+v/8X/3P/q/+3/8v8EACMAPwBRAGIAewCSAKMAuADYAPgACAEHAQgBGgE0AUABQgFOAVsBWwFNAU4BYAFsAWUBXgFiAWkBbQFoAWEBXAFdAV4BWQFTAVMBVQFNAUEBQwFOAUoBMAEVAQsBBAHtAM0AvQC3AKYAhQBrAGsAdABuAFgATgBYAGEAXABZAFoASgAsAB4AIAATAPn/6//l/8//tf+w/7T/pP+K/4L/jf+U/43/fP9o/13/V/9J/zL/Jv8h/xD///4E/w//Cf8A/wr/Gv8Z/xX/IP8v/zT/NP81/zT/N/89/zX/I/8e/yT/IP8X/xv/Jf8l/yf/O/9Q/1T/Vf9h/3D/cv9t/2n/Zv9k/2X/af9o/2j/bP94/4v/oP+q/6X/nf+e/6f/rf+u/6//r/+v/7T/tf+o/5n/nP+t/7b/rf+h/6L/rv+1/7T/rv+r/63/s/+2/7X/tf+4/8P/zf/R/87/x//D/73/s/+r/63/sP+v/67/s/+5/7X/r/+4/9H/4//i/97/5//x/+j/3f/o//n/+f/3/wIADAACAPL/8v/3//H/6//w//n/+//+/wUADQAOAAcAAAACAA4AGAAaABkAFAANAAcAEgAiACMAIAAoADkAQQA9ADsAQwBPAFgAWwBYAFkAXwBnAHAAfwCPAJkAnQCgAKAAoQCvAMwA5ADqAOMA3wDqAAABEAEPAQwBFAEjASkBLAEzATcBNAEzAToBRAFNAVYBWQFVAVUBWQFQATgBIAESAQwBCgELAQEB7ADlAPAA9gDvAO0A9QDxAOEA2gDjAOIA0AC+ALYArgCjAJYAjgCMAIUAdgBsAHcAjACRAIsAkwCcAIwAcgBsAHMAbABfAFcARAAlABcAIwAqAB4AFAAUABAAAQDy/+3/8P/x/+P/x/+1/7H/qv+U/33/c/9x/2z/av9m/1v/VP9c/2H/V/9R/1b/Vf9D/zv/RP9N/1H/Wv9n/2v/af90/4X/i/+M/5L/mf+a/5T/jf+J/4//nP+b/4z/hP+O/5n/m/+b/5j/j/+L/5b/mf+E/2X/WP9Y/1H/QP8z/zD/MP8p/xn/CP/9/vL+5P7Y/tH+yP67/rb+t/6z/qf+n/6d/pf+iv58/nX+cv5v/mj+Yv5n/m/+cP5t/nb+g/6K/or+iP6H/o/+nv6i/p/+sP7Y/vT+9f77/gv/E/8T/x7/K/8s/zL/S/9b/1L/Sv9Z/2r/bv9x/3v/hf+V/63/vP/A/83/6v8HABsALgA5ADEAIwAfABgACQAEABcALAAyADIAOQBCAFEAaAB1AG0AawCEAJsAjgCAAJUAtQC3AKkAqgCwAKkAogCmAKgArADAAN4A7wD4AAEBCgENAQ8BDQEEAQEBCAEIAfsA+AAEAQgBAAEGARUBFwESAR4BMwE7ATcBOQE+AT8BPAE2AS4BKgEtASkBHQEYARsBGAEKAQMBDgEaARoBHgEtATsBNwExATMBNAEvATUBRgFHATQBMAFDAUwBQAE6AUgBUgFPAUQBOgEwASoBJQEaAQ0BAAHyAOcA4QDWAMEAsgCyAK0AlQB/AHcAbwBlAGIAXQBIACwAHQAVAAgA///6/+3/4P/b/9b/yv/H/87/zf+9/7D/qP+e/5D/i/+L/4n/h/+H/4z/l/+c/5T/j/+g/8D/2v/u/wkAJAA7AFgAjQDNAAABJQFTAYoBswG9AbwBvgG4AaEBjAF9AWQBRQE8AUYBSAE8ATgBQAFMAV4BbAFkAUcBKAEIAdoAngBdABMAyP+M/1v/Jv/w/sX+nf55/lv+Ov4L/uD9w/2d/Wf9Rv06/R795vzC/Lz8rvyO/Hz8hfyM/Ib8fvx8/H/8g/yF/IT8fvx1/Gz8bfx1/H78gvyO/Kb8xvzk/Pz8E/03/V79dP2A/ZT9sP2//cX91v3p/fD9Af4m/k3+Y/58/qP+y/7q/gr/LP9P/3H/jv+h/7P/x//T/9n/7/8OAB4AJgA9AGAAegCWAL4A2wDjAO8ACQEdASUBKAEnASEBKAE6AUkBUgFbAVwBUwFSAWYBewGDAYoBlgGeAZoBlAGYAaEBpAGcAY8BigGLAYUBfAGBAZABmAGYAZIBiwGFAYIBfQF1AXABcQFwAWwBbQF0AX0BgQGBAYEBjwGlAakBlwGMAY8BjgGAAXMBbAFfAU4BRgFIAU8BWAFgAWQBbQF9AYcBjgGZAZoBhgFtAV4BTgE3ASYBHAEFAesA3gDXAMgAvgDBAL0ArQCmAKkApQCaAJgAlACBAGcAVgBKADcAGQD2/9r/yP+2/5//hv9t/07/NP8s/y3/J/8a/w//Bf/8/vT+6v7Y/sz+y/7H/rb+qf6p/q/+r/6u/rT+vf7E/sb+y/7d/vX++/7y/vb+Cv8b/yP/I/8h/yj/RP9g/2b/aP+C/6b/sv+z/8D/zf/Q/9T/3//k/9//3//l/+n/6f/r/+//+P8FAAoAAwADAAwADAD+//P/8v/r/9X/wf+8/8D/v/+5/7b/uf+9/8D/zv/i/+v/7P/0//3/9v/h/9L/yv/C/77/v/+6/63/oP+b/5z/nP+Y/4z/gf9+/37/e/98/3j/bP9i/2v/fP9//3n/dv9u/2L/Yv9u/3r/f/95/2X/T/9P/2H/av9j/2L/av91/4X/oP+6/8X/xf/I/9D/1v/W/9b/3//r/+j/1//Y//b/GwAxADwATQBvAJsAyADsAAUBGAEsAT0BRAE/ATgBOAE6ATQBKwErATcBQwFMAVIBVgFhAXgBiQGEAXMBcwGEAYkBewFuAWkBaAFfAVMBSQFEAT8BMwEnASUBIwEeARcBCAHrAM0AwwC9AJ4AcwBfAFoASwA6ADgAOwAyACkAKgAqACIAHQAmACYADgDq/9f/z//A/6z/oP+U/33/Yv9S/1H/VP9W/1X/S/86/yv/Hv8U/xH/Dv///uT+0P7Q/tj+1f7H/r7+yP7a/uP+5P7t/vz+A/8E/xD/IP8k/yb/L/80/yv/If8e/xf/Cf///gH/CP8K/w//Gv8n/zT/Q/9K/0P/Nf8r/yz/Nf9C/0n/SP9L/1v/bv9z/3P/f/+S/5n/lP+Q/5X/mv+g/6P/oP+a/5v/nf+W/5H/mf+g/5v/m/+t/73/uv+x/7L/u//C/8z/1f/Z/9z/4//m/9//2f/i//X/AQADAAIABAAAAPT/6P/p//X/AgAEAPn/7v/x////BgABAAAAAwAAAPn/AQAUACQALQA6AEgATQBNAE4ATwBPAFIAVQBPAD0ALwAxADcALAAVAA8AJQA2AC4AIQAhACQAHgAYABoAGgAXABgAHQAgACUAMAA9AEgAUgBfAGsAcABtAGsAcQB6AHkAcgBzAH8AjwCiALgAxQDIANAA3gDnAOcA8AAEARMBGQEaAR8BKwE5AUMBRgFFAUkBUwFhAWoBZwFgAV8BXgFYAVEBTQFJAUQBPwE7ATYBMgEwASQBFgESARQBDAH7APEA8QDrAN4A0wDOAMwAxAC0AKkArgC4ALAAngCYAJYAiwB9AH4AhQCEAH0AdgBxAHAAdwCAAH0AbABaAFYAVgBJAC4AGAARAAkA9//i/9H/wP+v/6r/sP+z/6n/lP+B/3f/bv9i/1f/Uv9O/0T/Nf8m/xf/CP8H/wz/Cv/7/uz+4f7c/uL+6P7i/tf+1/7Z/tX+1v7k/vD+7/7w/vr+/f71/vD+9P7z/u3+8v7//gH/+f4A/xj/KP8k/yT/MP88/z7/SP9d/2v/bP9w/3n/e/95/3//iP+I/4X/g/+D/4T/iP+H/33/d/99/4f/hv9//3v/fP99/33/ev93/3b/c/9p/2D/Y/9q/2X/UP9I/1v/cP9r/1P/Sf9W/2D/Wf9P/0b/OP8u/y3/L/8u/y3/Lv8o/yb/Ov9W/2D/Wf9X/2L/bv90/23/YP9c/2r/e/98/3b/e/+L/5r/of+m/7T/v/++/7j/w//X/9//3P/d/+b/7P/w//n/AAADAAsAHAAwAD8ASQBVAGUAeQCGAIkAiACJAIoAjACTAJoAnwCoALIAsQCoAKcArACqAKQAqQC0AL0AwQC+ALcAtQC6AL0AtgCzAL0AzQDcAOYA5QDXAMcAuwC9AMcAzgDOANAA1QDQAMAAugDAAMMAvgC/AMEAuwCyALEAuQDAAMEAwgC/ALgAsQCyALwAxQDHAMYAywDOAMUAvQDDAMsAyQDEAMUAwQC5AL0AxgC+AKgApwC5AMIAwADCAMYAvgCoAJUAlACcAJsAjwCMAJIAkQCGAH0AcgBiAFgAWgBbAFcAUABLAEsASwBDADEAIgAbABsAIwAuADAAIQAPAAwADgAFAPv//P/5/+n/4v/s/+3/3f/Z/+L/3P/J/8j/2v/j/+H/5P/x//b/6//o//n/AAD0//H/CQAYAA8AFgA8AGEAdwCXAMQA6gABARQBIgEpATIBOQEyAR4BEQENAQUB8ADjAOoA9wD7APcA+AD9AP8A+gDyAOwA4ADDAJoAbwA9AAUA0/+m/37/X/9G/yb//v7Y/rz+qv6b/oL+XP5B/jX+Jv4S/gj+/P3g/cn9yf3J/br9q/2p/ab9mf2K/YT9gf12/Wv9bP1y/Wj9W/1k/Xn9g/2H/Zj9s/3F/cf9zf3d/en95f3h/eb96/3s/fP9/v0K/hr+Lf5C/lz+eP6P/p7+sf7F/tv++f4X/yr/Pf9S/1v/Yv96/5v/sf/D/9v/8P/8/wgAGgAzAFAAZABnAGgAdQCKAJcAlwCPAJAAoACuALIAuADHANYA4ADnAOoA7QDvAPIA+gACAQcBDAESARABDgEcATQBPwFBAUUBSwFQAV0BZwFlAVoBSwFAAUUBTwFIATgBOwFRAWcBdgGDAYgBjAGUAZcBmgGfAZ8BlAGGAX0BcgFhAVMBSwFFAUEBPQE+AUABOgEqASMBJgEkARoBEwEWARoBFwELAfwA8gDnANgA0QDQAMwAwQCxAKMAoACnAJ8AgwB1AIAAiwB/AGIARgA4ADMAJwAQAP//8P/V/7r/sP+p/5T/fv9v/2r/b/9z/2b/Uf9K/1L/Wf9T/0D/OP9D/07/Q/83/zz/Rf9F/0f/Uf9h/27/dv+B/5L/p/+6/8j/zv/U/+v/BQAHAPj/+/8LABAAEAAcAC8AQABKAE8AUwBWAFQATwBRAFQATQBIAEgAPAAoABwAEwADAPP/6v/o/+v/8v/s/97/2P/W/8z/wf+5/63/nf+Q/4z/iv+G/4D/fv99/3L/Yv9e/1//Wv9T/1H/Uf9K/zz/Kf8b/xn/Gv8Q/wP//f4A/wf/EP8S/xH/EP8M/wT/AP/3/vH+//4U/wn/6v7t/gj/Df/6/vL+/P4F/wf/B/8K/w3/Cv8O/yb/QP9H/1D/b/+S/6n/vP/O/+D/9P8LABoAIQApADEAOgBFAFsAdwCNAJIAngC+AOAA9gAGARgBJwE4AU0BVwFWAVgBXwFmAXABdgFvAWcBbQFwAW0BbgFxAXIBcwF1AW4BaAFmAVgBQgE2AS0BGgEJAQEB+gDxAOsA4wDZANQA0wDPAMQAtQCoAKAAmgCLAH4AcgBhAEsANgAlABoAFwAPAAAA+f8BAAsADAACAO3/1//O/9D/zv/E/7f/q/+k/5v/h/98/4H/fv9r/2f/ef9+/23/X/9Z/1j/Wf9V/0z/RP89/zT/Lf8o/x3/HP8u/z//Qf9H/1f/Xv9W/1D/W/9t/3X/cP9w/3j/fv+B/4n/jf+B/3P/c/98/4H/gP+A/4T/iP+F/4D/gv+F/4L/ff9//3r/dP90/3H/Z/9t/3v/df9i/2P/cv91/3P/dv+A/4j/fv9t/3X/kf+Y/4z/kP+d/6D/mf+Z/6D/pv+r/7X/vP+8/7//zv/f/+P/4P/m//f/BAADAPz//P8FAAcAAwAEABMAGwAUABIAIgAvADYAQABCADgAMwA2AD4ARgBOAE4ATgBRAEwASQBXAGMAYABZAFQAUQBaAGsAawBcAFQAWwBnAG4AbABiAFAAQwA+AEAAQwBFAD4AMAAoAC4AMwAvACMAIgArACsAHAAPAA4AEgAUAA8ACAAGAAkACwAZACsAKwAeACAAKAAhACEALQAzADUARABTAFgAYwB5AIwAjgCJAI4ApAC4AL4AwADGAMkAxwDGAMsA1QDkAPUAAgEDAQMBCwEXAR8BJQElAR0BFQEHAfUA7ADvAPQA9gDtANsA0wDVAM4AwACxAKcApQCkAJIAeAB2AHwAcABcAFUAWABYAEwAPQA7ADwAJwAVAB0AJgATAPn/7//s/93/yv/G/9D/1P/M/77/sv+z/7T/qf+h/6v/tf+o/5T/hv9//3f/bP9k/2P/ZP9j/2f/aP9i/2f/cP9p/1n/Uv9O/0r/Q/8//0L/Tf9K/0b/TP9O/0L/Q/9V/1b/S/9V/2//c/9g/1f/Y/9m/1n/X/94/4P/fv+E/5L/kP97/3j/l/+1/7X/rv+4/8f/zf/O/9D/1//e/9r/2//u//f/5//b/+X/+P8CAAMA+//0//D/6v/s/+//6//o/+7/6v/c/9b/2P/V/9H/0//Z/9r/0//L/9T/4//n/+H/3P/a/9b/zf/K/9D/0P/E/8L/yv/N/8b/tv+k/6H/r/+5/7f/rv+k/53/lv+L/4n/lv+Y/4v/gv9//3z/h/+c/6X/nf+P/4b/i/+T/5X/mP+b/5r/nv+p/7D/tf++/8T/xf/K/9H/2P/Z/9X/1v/h/+j/4v/m//f/BQD//+z/8P8IABYAFgAiADEALAAnADIAQgBJAEcAQAA9AD8APQA/AEwAVQBMAD0AOABBAEYAPwA+AFQAZgBiAF8AZwBsAGoAawBzAHsAdQBlAGMAbgBrAGEAZwB1AHcAbgBpAGsAaABZAFEAVwBfAGUAaABjAF0AYABWAEUASQBcAF8AUwBHAEAAPwBDAD4ANQAxAC8ALAApAC8APwBEADQAJwAwADkANwA2ADMAMAAxAC4AIwAiACkAJwAbABkAHAAaAA8ADAAWAB0AGgAiAC8AMgAwADQANQA6AEQARQA8ADcANQAxACsAIwAaABsAHwAiACUAHwATAAMA9f/s//H/+P/2//X/9P/v/+//9//0/+3/9P8AAPz/7P/l/+//9f/q/+X/8v/3/+j/4P/r//b/+f/7/wMABwD///7/EwAnACIAIAA6AFcAWQBCAC0AMAA/AEEARgBYAFsASAA6AEIASwBDADUAOABDAD0ANwBJAGIAYwBfAG8AhACJAIAAfgCHAIgAdwBnAGIAVwBLAEoAUABTAE8ARgBCAEYARAA/AEIAPAAmABAACQAOABAA///l/93/5P/k/9v/1f/U/9j/2f/W/9T/1f/S/87/w/+0/7T/wP+2/5j/gv90/2X/Yv9q/2z/YP9V/1n/Yv9j/2L/cP93/2z/ZP9t/3T/ef+A/4r/kP+O/4z/of+9/77/rP+k/6P/lf+F/4T/i/+G/3T/eP+Z/7D/q/+j/67/xv/b/9j/yf/K/9X/1P/G/8H/wv/B/7z/tv+z/7H/tv/L/+D/3P/U/97/6v/q/+v/7//s/+j/6v/p/+H/3v/m/+//7P/q//P/9v/v//H/9//y/+r/6//u/+v/5//c/9P/3P/u//j/8//n/9z/2P/f/+X/3//O/8X/yf/D/7b/tf+0/6b/nP+h/6X/pf+q/7D/tf+3/7X/uP/E/8n/vv+u/67/vP/F/73/r/+v/7P/t//E/9T/2f/R/8n/0P/h/+T/2v/a/9//3f/i//P//P/z//D/+/8DAAEA+v/8/wUACwALAAoABQD///n/9v/9/wsAEQAPAA0ACQAHABAAHAAhACsAOwA7ADEALwA6AEEARQBLAFIAVABMAEoAWABqAHYAeQB4AHYAcgBrAGsAcgBzAGoAYABaAFwAbAB0AGQAUgBMADsAHwASABQAFQARAAsAAwAAAAUADwAVAB4ANQBKAE8AVgBmAGwAaQBsAGQATwBMAGEAaQBaAFEAVABVAFMAXgBxAIQAkwCbAJsAmACeAKgApQCZAI4AgwCBAIsAlACbAKoAuQC/AMMAzADQAMkAuwCrAJwAjgB8AGwAYgBeAFQASABCAEgATgBRAFcAXwBdAFsAYgBmAGIAWABVAGMAdwB4AGMAWgBmAGwAaABtAHMAagBgAGsAfQB9AGwAYgBiAGMAaABrAGIAWQBcAFsAVQBVAFQASQA8AD0AQQA5AB4ABQD6//v/+f/t/9v/1v/W/8v/t/+w/7D/nP+C/3//hP93/2j/aP9l/1H/Pf8+/0z/Tv89/yr/Jf8r/yr/Gv8X/yP/IP8M/wr/GP8U/wX/Ev8s/yj/Ef8N/yH/Mf8v/x7/EP8V/yT/I/8d/yP/JP8U/xL/Mf9C/zP/K/9B/1r/Zf9m/2P/bP+I/5j/if98/4n/k/+A/23/cP90/3f/if+W/43/g/+F/4v/lP+n/67/pP+l/7X/uP+2/8X/1P/M/8D/zf/g/97/0v/R/9b/1f/K/8v/4f/u/9L/rP+w/8v/zP+//8r/2f/T/9H/5f/3//b/9P/9/wgADgALAAwAGQAhABEA+f/8/wgA///1/wIAEwAUABcAIQAgAB4AJwAtACsANQBJAEsASQBbAGwAZQBgAGwAbgBkAGQAcAByAG8AagBfAF0AdQCKAIgAgwCOAJAAhgCPAKUApACPAI0AnACZAIYAgQCOAJYAkQCGAH8AfgB1AGsAbAB7AHwAagBhAGsAbABXAEMARQBNAEkARABJAFIATAA4ACcAJgArACsAJwAtADkAOgAvACcAJgAZAAUA/P8EAAwABQABABEAJQAqAB0ADgAJAAoADAAKAAkADQAOAAYA//8DABQAIAAcABIAEwAcACEAIAAdAAsA8P/p//n/AgD5//r/BgACAPP/9P8BAAQAAQAEAAgACgANAA4ACwAOABAAAwDv/+//AQAKAAIA8//q/+7/9P/r/+D/5//4//P/4f/h/+3/8P/t//P/9f/w//f/DQAbABcAEQARABIAEgANAAEA9P/s/+n/5//p/+7/9//7//n/9f/6/wUACAAIAA4ACgD0/+X/8P8DAAUA/f/7/wMADQATABYAIAApAB4ABwAFABYAGAARABoAJAATAPv/+P/8//P/7////wwACgAJABIAFwASAAwAEwAeABgACAALACcAOQAyADEASQBhAGkAcQCAAIMAdQBoAGQAYgBdAFYAVwBfAGMAUwBBAD0APQAxACUAKQAwACwAIAAfAC8APwA3AB8AFQAcABkABgDy/+P/1P/P/9j/1//C/7L/sP+o/5v/mf+e/6L/pP+d/43/hf+R/5r/jv+K/5v/qP+d/5D/mv+t/7H/p/+j/6r/rP+X/37/fv+I/33/Z/9t/4D/fv9z/37/j/+L/3z/f/+L/5D/j/+W/6L/rP+z/7X/uP+4/7H/qv+r/6z/o/+d/6P/qf+m/6b/t//E/77/sv+0/8X/2f/u//7/AgAFABAAFAAQABAAGgAbABMAEgAZABcAEQAVABoADQD1/+L/2//Z/9f/0v/S/9f/1v/O/9P/7v8BAPn/7v/z//n/+P8AAAwACgD4/+f/1//N/9j/5f/e/8z/1P/m/+b/2v/g//X//f/y/+v/6//s/+z/8P/4//r/7//k/+//AAD8/+r/4v/m/+f/7f/8/wMA8//m//T/DAASABEAHwA1ADsALAAgACUANgA/AD4AOQA6AEAAQAA9AEAASABBAC4AJgAsACwAJQAoADEAKQAeACwASwBXAFEASQBFAD8APgBFAEIANAAuADQANgArACgALgAuACQAJAA1AEgAUABSAFcAWgBVAFIAXQBsAG0AXQBOAEcARgBMAFgAYgBmAG4AeAByAGQAagCCAIMAaABTAFgAWwBSAFAAWABTADwAKgAmACsAMAAwACsAJgAhABsAFQARAAsA/f/u/+f/5f/q//P/8f/d/8z/1//t/+3/2P/H/8T/wf+5/7P/sf+w/63/r/+y/7H/rv+3/8f/x/+4/7T/vv+//7r/wP/O/9L/zv/P/9T/2//n//X/+v/z/+b/2//g//b/AgD0/+b/7v/2//L/9P////3/7//y/wYAEQAMAAYACAARABgADgD9//3/DQAMAPj/6P/m/+D/3P/b/9b/y//N/9v/4P/e/+z/AwAMAA0AGAAlACgAKAAqACoAKQAkABwAFQAaACQAJAAfABwAGwAXABgAIQAhABsAIAAvADcANAAyADMANAA7AEkATAA8ACoAKQAqAB4AEAANAAwA/P/l/9z/4f/h/9b/zv/Q/9b/2P/W/9f/4P/p/+b/3//i/+n/6P/i/+L/4//Z/8v/yv/U/9j/1v/Z/9//2f/Q/9b/5//x/+j/4v/t//n/+f/0//r////2/+z/8f/9//z/7//r//n/AgD//wAACAAMAAwADgASABEADQAQABQAEgARABgAGgAVABsALAAvACUAHwAhAB8AFgASABQAGAAZABoAHgAhAB0AEQAGAAUAAQD0/+n/7P/t/+L/1f/L/8T/wv/F/8P/wv/J/9D/zf/E/87/5f/s/+P/3v/Z/8r/u//A/8//2P/S/8L/uf+7/8D/wf/E/8X/u/+s/6b/sf++/8T/yf/N/77/qv+y/87/3f/J/6v/pP+v/63/n/+f/7H/vv+5/6//sf/C/9T/5P/y//L/5//l/+r/6//n/+X/5P/d/9L/0f/p/wEAAwD8/wUAFwAhAB0AGAAfACYAGAAJAA4AHgApAC8AMgAvACoAMQBDAEkAOwA8AFgAagBjAFwAYQBlAGIAYABiAGcAcAB9AIoAhwB/AIcAlQCRAIQAewB3AHUAdgB7AIUAhgCDAIcAiAB+AIIAnACqAKMAoACnAKoApgClAKIAlAB8AG4AaQBfAFcAXgBeAEwAOwA0ADQAQABNAEwANwAdABIAEwASAAUA/v8AAAEA9v/h/8//z//U/9L/zf/D/7b/sP+r/5z/kv+X/5X/gP9v/3P/fP90/2T/Z/+A/5D/jf+I/4P/fP9z/2r/af90/4L/jf+V/5H/iv+a/7f/wv+7/7j/uv+9/77/w//G/77/s/+y/7j/vP/I/9X/0P/H/8n/z//S/9P/0f/P/9H/0v/U/9D/y//M/9v/4//h/+H/5//s/+v/3v/W/9v/4P/e/+L/6P/n/+b/6f/o/+j/8P/7/wYADAALABAAFwAYABQADAD6/+3/6v/r//L///8HAAsADgAPABkAJQAlACcAOQBEADUAJQAtAEEAQAAmABMAEgALAPz/9v/w/+T/5f/y//j/9v/y//D/9v/6//X/7f/u/wQAJAAxACYAJQAwADIALwAxAC4AJQAaAA8ABgD+//b/7v/o/9v/1v/j//j/BQAMAAwAEAAcACEAHwAlAC0ALwAlAA4A+//9/wMA/P/1//f//f/+////CAAZACEAGAASABIADQAIAAoADwAaAB8AFwAUACIANAA7AEAAQgBAAD0AOwBCAEkARwBAADwAMwAwAD4ARAA6ADQAPQBFAEkARAA6ADQALgAoACYAJQAhABoACwD7//z/CQAPABYAHgAiACYALgA2AEAARwA9AC4AJAAdABoAGQAVAAsA///2//P/9P/s/+P/5f/k/+D/4v/j/+P/6P/r/+X/4v/n//L/AQAIAP3/6f/b/9f/2P/U/8//2f/c/8P/pv+k/7f/yv/K/7f/r/+3/77/wP/M/+H/7P/p/97/3v/r//j/AwALAP//6//m/+f/5//s/+3/5P/Y/87/xf/B/7r/r/+n/6D/nf+j/6z/sv+7/8L/v//C/8//2f/l//X//v/4/+3/5//o/+X/1f/N/9T/2P/Z/+D/6f/u//X/AgASAB0AIAAsAEIATQBRAGEAcQBwAG0AcgB6AHwAegB8AIYAiwCEAHoAagBWAFEAUABAAC4AKgAmACAAGwAXABMAEAAWACoAOwA7ADkAQQBGAEUAPAAsACAAIgAbAAUA+P/6/wAAAADy/+L/2f/S/83/0f/S/8f/uv+1/7z/yv/P/8//2v/q//T/BQAcACkAMAA0AC8AJQAYAAkA+v/x/+b/1v/C/6z/pf+x/8X/1f/a/9T/2P/w/woAGQAlACYAGwASAAsA///v/+P/1v/G/7j/t//J/9H/yf/B/7//vv/A/83/4P/r/+j/3//j/+z/8/8FAB0AHwAYACEANQBAAD4AMQAhABUADwAQAAgA9v/n/+b/6P/s//f/AwAWAC4ANgAvADAAOwA7ADYAMAAkAA0A8//m/+//9v/t/+D/4f/t//T/8f/w/wAABgDz/+f/7v/q/9T/zf/T/9D/xv/N/+T/7//n/+P/6//l/9r/5v/6//j/3//F/7v/wP/J/8z/x/+8/7r/yv/U/9b/4P/r/+n/4v/l/+z/8P/y//H/9P/1//b/+/8GABEAFQAQAAQA/f/8//r//v8CAPT/2//Q/9X/4P/i/9z/1v/Y/9v/4//z/wIAAADw/9//3P/o//f/BAAMAAgA+f/v/+7/9v8HAA8ABQDx/97/1v/l//r/9P/a/8//3P/u//f//f8AAP////8MABMACgABAAEA+f/o/97/1f/N/9H/2//f/9//4P/k//X/EQAmACoAKgAzADwAQQBLAFwAXwBWAFIATgBGAFAAZQBnAFgAVQBeAGUAbgB7AIAAdwBwAHgAiQCaAKoArwClAJ0AnwClALEAxQDPAMUAuwC8ALQAnwCIAHsAaQBQAD4AOAAwACEAHAAkACUAIQAkACsAKwAnACsAMQAnABUAEAAPAAMA7v/d/9X/2P/h/+D/1P+//6P/kv+T/5T/iP97/3j/dv9x/2//dv9+/4X/kv+l/63/t//N/+P/8f/8//v/7f/r//z/CAAEAPr/6f/N/7b/t//E/8j/wv+//7//wf/E/8T/wv/L/9j/2//j//T/9v/p/+n/9//+//7/CAAUABQACwADAPP/4f/Y/9L/wP+w/6z/pf+c/6P/tv/B/8v/3//0/wMADgAbACUALAAwAC8AMAA3ADsANwA4ADkALAAYABQAGQASAAoAEAAZABUADAAJAAAA8//x//7/CwAPABEAFQAXABMADQAKAAgAAwABAAIA///v/9v/zf/E/7v/uP+8/7n/q/+f/5//pP+p/6v/rf+s/6b/of+h/6j/rv+x/7r/0f/v/wcAFgAfACIAHQAYABwAJgAlABcACQD+//T/7P/r//L/8//v/+//+P8CAAcABgAJABsAMgA7ADsAQgBMAEoARwBTAF4AUQA+ADwAOQAiAAkABAAIAAQA/f/7//z/9//0//b//P8CAAQADgAhADAALQAiACUAMwA4ADIAKgAlABwADwACAPr/8//q/+X/6v/v/+T/0//Z/+v/8v/x//v/CQAOABEAIAAuAC4ALAAvAC0AHAAOAA0AEwAQAAUA8v/g/9b/1P/O/8T/wf/M/9v/5v/p/+b/3f/d/+r/9v/z/+7/8//+/wYABwAEAPz/9v/9/w4AGAAUAAkAAAD9//z/AQAJAAwABgABAAAA/P/x/+3/9//+//z/AAAOABoAIgAqACkAHAAZACgANAAzADQANQAjAAUA9P/0/+7/4v/d/9r/0v/P/+H/+v8EAPj/8P/6/wcACQAIAA4ACwD+//r/AwAMAA0ADQARABMAEAAJAAQACwAcABsABADz//D/7P/l/+b/5f/W/8//3P/u//b//v8DAP///v8KABMADAD7/+n/2v/d/+r/6v/a/87/0f/Z/+L/7f/p/9j/0f/U/9X/1f/a/9b/yf/D/8v/0f/T/9z/5f/n//D/AgANAA8AGQAmACkAJgAjABwAEQANABAAEgANAAUA/P/0/+//7f/v//T/+P/1//L/9f/7////BQANABcAJwA8AEgATQBQAFQAVQBRAEwARQA6ADQAKwAcAAoA/f/3//r/AgAEAAIADQAmADoAQQBBAEEASABXAGEAXABUAE8ARQA2ADAAMAAjABAABwADAPT/6f/q/+f/1//M/8z/z//S/9v/5v/z/wMAEQAbACgAMwA1AC8AMQA+AEUAOgAmABcADQADAP/////2/9v/xv/O/+T/6//n//D/AQAIAAkADgAOAAgACwAWABwAGgAYABYAEAAQAAoA9P/f/9z/3P/Q/8b/xP/A/7n/vP/F/8f/zP/Y/97/3v/u/wIABAD6//v/AQD+//v/AAD8/+3/4//j/+H/1v/O/8n/v/+z/7H/wP/U/9b/wv+u/7P/yf/X/87/uP+s/7H/v//H/87/3P/r//H/8v/1//b/8f/t//L/9//w/9v/yP/I/8//y/+//7r/v//E/8n/1f/k/+z/8P/1//j//f8KABwAJQAfABQACwASACcANgAwACEAHQAmACoAJAAXAAgA9//p/+z//f8JAAYAAAAKAB4AMAA6AEcAXABxAHYAbgBoAGsAbgBwAG8AYwBLAEEATgBUAEQAMgA3AEYATgBRAE8AQwA2ADcANwArAB8AIgAlACEAHQAdABkAEQALAAAA8P/p//D/8v/n/97/4P/i/9z/0//Q/9L/0f/O/9H/2f/b/9T/0v/Z/+L/6v/w//T/9v/2//L/5v/W/87/zv/O/87/0v/X/9r/3P/d/9n/2f/g/+f/5v/l/+b/5f/g/9//5v/y//3/AgD+//7/BgAGAPj/8/8BAA4ACQD/////AgD///v/+P/4//7/CgAZAB4AGAAMAAEA/f/7//z/BQANAAQA8P/k/+f/6f/j/9j/yf+5/7X/xf/b/+n/6//n/+X/6v/u/+7/8v/8/wEA+v/2//r/+//7/wEABQADAAQADAAKAPz/8v/1//n/AAANABkAGwAYABYAFAATABoAHAAQAAAA+P/z/+f/3v/g/9//1f/O/83/zP/M/9j/6//1/+7/4v/i/+///v8IAAoACAAFAAYADAATABIACQACAAQABAD5/+z/6v/z//T/6v/m/+n/5f/Z/+D/+f8GAPr/8v/9/wsACwAFAAYACAD//+v/3//i/9//zv/E/8v/0P/I/8D/xv/S/9j/2P/Z/+L/8//8//b/8f/7/wQAAQD//wwAGQAeACQAMAA3ADEAMAA/AE0ARgA3ADYAQgBMAEsARAA8ADQAMAAqACgALgA7AEMAQQA6ADcAOQA+AEQAQwA5ADAALgAuACoAKAApACYAHgAeAC0AOAA2ADIANAAzAC4AKAAdABAADwATABAACAALAA8ACQAGAA8AGwAlADEAOQA3ACwAIgAZABoAIAAgABUACgAKABYAJwAvAC4AKgAmABsAEQAVABsAEQACAAMACgADAPn/+f/8//r/+v8BAAQAAgD+//n/9P/y//T/7//k/+H/7v/5//L/4v/c/+L/6v/o/9z/0//T/9H/wv+x/6z/qv+m/6b/qv+u/7L/vP/G/8r/0P/S/8z/yf/W/+T/3//L/73/uf+6/7//yv/b/+L/1P/E/8j/1//a/9j/1v/Q/8f/xv/M/9f/6P/z/+n/3f/p////BAD+/wEAAgD0/+H/3P/l//P//f/8//P/8f/2//7/BQAQABgAGQAZAB8AJwAlACIAHgAbAB0AKAAwACgAGwAbACYALAAxAD0ASgBQAFIAUwBRAFEASwA6AC4AOABGAEkARgBDADgALgAxADoAPAA4ADgAMgAlABoAGgAgACUAJwAmACQAHwAYABIAFAAXABkAGgAVAAoAAQD+//r/+v8AAP3/7//o//H/+P/0/+7/5v/Z/9P/3v/r/+z/6f/n/93/0f/N/9D/x/+1/7H/wP/N/8r/yv/P/9D/zf/S/97/5f/t//v/AQD8//z/BwAPAA0ADAAOAA8ACwACAPf/8f/0//b/9f/x/+//7//z//X/+/8JABcAGQAWACEALwAwACgAKQAzADEAIAALAAoAFgAYAAYA+/8GABUAHAAeACIAJQAjAB4AHwArADgAOQA2ADsAQgBFAEsASgA5ACUAHwAfABsAGAATAAUA9f/x//D/6//o/+f/4v/c/93/3//b/9b/2P/f/+X/5//l/+D/1v/G/7r/uP+7/7r/tv+0/7H/rP+l/6H/rP++/8v/zv/V/+H/6//1/wAABgALAAwACQD///n/+f/1//L/8//t/9//1//X/9T/1P/X/9P/0f/h//X/+P/t/+n/5//n/+//+//3/+f/2f/S/87/zf/O/8z/v/+w/6z/tv+8/7P/qf+s/7f/wf/D/7//vf/H/9v/6//2/wEAAQD3//X//v8BAAAABwAVABoAEQAJAAsADgAIAP7/AwAVAB8AIwAqADMAOQBAAEYARABIAFIAVgBSAFkAYQBSADsAOgBDADsAKgAjAB4AEwAGAAIAAgACAAoAGQApAC8AKgAvAEIAUgBRAEcAQABAAEYASABCADQAJwAVAAYAAwAJAAUA9v/s//T/AgD+/+7/6f/3/wIAAgAMAB8AKAAoACoAJAAXABcAIQAfABQAFQAZABMAEwAhACYAHQAXABoAHwAkACUAHwAaACIALAAtAC4AMAApABgADQALAA0AEAAQAAgA/f/2//r/AgAIAAoACwAIAP7/8f/p/+P/2P/P/83/yP/C/77/wf/F/8//1v/Y/9j/2v/h/+j/7f/s/+z/8f/z/+7/8f8FABMADAD+//r//v/5/+//6//w//b/+v/8//v/9v/4/wgAEgAGAPf/AQAUABgAGQAhACAADgD8//z/AQD8//P/8f/w/+z/7//2//P/6P/q//v/BgADAAIABwAJABAAHAAjAB4AHgAjACMAHgAaABMACwAJAAIA+////woABQD2//H/9//8/wgAFgAZABcAKAA+AEMAOwAxACYAGgAYABsAFQAGAPn/9f/9/wEA9v/p/+T/3P/T/9b/4//l/9n/z//R/9z/7P/9/wYAAgD3//X/BAAVAA0A9f/p/+b/4f/V/8r/x//L/8n/vf+w/7T/wP/J/9b/5P/p/+z/9/8DAAQAAgADAAIAAQAAAPf/6P/k/+b/4//i/+3/9//1//D/9f8BAAoAEAAPAAgAAAD//wcAGQArADMAMQAyAD8ASQBFADoANgA3AC8AHQAOAAgACAAHAAEA9//w//L/9v/z//b/AgALAAoABwAFAAIA//8BAAMA///3//L/7//o/+D/3v/j/+f/4P/Y/9j/2//f/+f/9f/9//7/+v/2//v/EQAkACEAEQAOABYAHAAmADQANwArACoAMQAsABgACwALAAkABwALAAkABAAGABEAEwAKAAUACwAVAB8AJAAZAAwAEAAdAB0AFQAZAB8AGQALAAEA/P/2/+z/4P/V/9H/zv/F/7j/uP+//8L/uf+u/6z/tf/B/8r/yv/E/8j/2//v//P/6v/m/+j/6P/g/9P/zv/b//H/+f/x/+//9//5//X/9v/2//b//v8LAA8ACgAKAAwADwAXAB8AIQAkADAAMwApABsAEQAGAAEABQAGAAUACAAKAAcABAAEAP3/9//7//z/8f/m/+L/3//k//L/9P/k/9z/5//x//f/AAABAPn/+P/5//P/6//t/+7/6//w//X/6v/e/+n//f8DAP//AQAHAAwAFQAfACUAJwAjABgAEwAYABsAFwAaAB0AEwAIAAgAEgAZAB0AIQAeABkAHQAlACUAGwAWAB4AKwAtACcAJwA1AEUARAAvABsAGAAhACMAGgAYABwAFAD8/+//8//0/+f/3v/j/+z/7v/s//L/+v/+//7/AgALABIAGAAjAC4AKwAjABkACQD5//j//v/5/+//8//8//7//f8CAP//+P/+/wkABQD+/wEACAAJAAwAEQAPAAoABQD9//b/+P/7//T/6f/m/+v/9v/9//r/7v/q//D/9P/t/+T/4v/o//P/9f/v/+v/7//z//b/8v/p/+H/4f/g/9f/0v/a/9z/1//d/+z/8P/o/+n/9P/3//X/AAANABIADgAHAP3/8//w//v/DgAYAA8A/v/3////DAAXABkAEwATAB4AKgAoACIAJwAqAB8AGAAeABkACAAAAAUACQAKAAwADQAJAAkADgAJAP///P8AAP3/+P/7//z/8f/m/+X/7P/w/+z/4f/U/8z/0P/T/8//z//Y/97/4f/i/+D/2v/e/+j/8f/1//n/AwAJAAYABAAKAA0ABgABAAcACwAGAAIACwAUAA4A/v/1//v/DwAiACMAGwAeACQAHQASABcAIQAhAB8AHAAJAPD/7//9//v/9P/8/wUAAgAFAAkABAACABEAIgAoACkAKQAjABoAGAATAAYA/f////z/7P/e/9f/0v/U/9r/2v/Z/+H/5//m/+n/+P/7/+7/7v8EAAwA+//u//H/9v/4//n/+v/3//L/8f/w/+r/5//u/+7/5P/n//L/9P/z//r/AQAIAA4AEQAOAAoACwALAAoADwAVAA4AAAD6//n/+P/9/wEA+//w/+7/8//5//z///////j//P8NABUABwD2//P//f8GAAQAAAALABUAEgAPABUAEwANABIAGQAWAAgA+//z//H/8P/n/9v/3f/l/+X/5P/1/wkAEQASAA0A/v/4/wYAGgAeABIABwAEAAEABAAMAAsAAwD5/+r/2P/U/93/4f/g/93/3P/h/+r/7v/1/wAAAQD+/w4AJgAnABYAEQAPAPv/6P/z/wUA/P/k/9b/1v/c/+P/5v/o/+//+f8AAAIABwATABwAGQAdACgAMQA3ADoAMQAkABcADwAKAAEA8f/m/+X/5P/l/+7/9v/0//P/+P8CAAoAEgAVABUAFwAfACMAHwAYABEACgAHAAcACAAMAA0AAQDy/+z/6v/o/+z/7v/p/+L/3f/i/+f/4v/g/+f/7P/1/wYAEAASABoAJgAnACEAHAAUAAoAAwAEAAYAAgADAAcAAwD5//X/+P/5//j/+v/+//v/8//1//7/AQAEAAcAAAD6//7/BAAHABEAGgAcACAAJQAhABcADQAIAAUA+P/j/9L/yf/H/8z/zv/Q/9X/1f/P/9z/9/8EAP3/AAARABcADgARABcADAD9////AwACAAMAAAD2/+//8f/z//L/7v/s//P/9v/y//D/8P/7/xUAJQAeABQAFAAUABkAJwAwAC4AJgAiACYAKwAnABwAEQASABUACAD3//f/AwALAAoABgADAAAA/v/8//7//f/8/wIA///t/97/1f/S/9b/2f/V/9j/4f/g/9r/1f/W/+L/8v/7//7//f/3//v/DAAaABkADAD+//r//P//////+v/z//P/9P/4/wIACgAMAA0ADQALABEAGwAjACoAMAAxADIAKQAaABkAIwAjABkAEAAGAAUADwAXABQACQD+////BgADAPP/5P/l//X/AQD9//v/BgAUABgAFAANAAUA/P/9/wcABQD5//n/AQABAP7//f/0//D/+/8HAAYA/f/+/wgABwDy/+r//P8DAPT/6P/w/wEACwAFAPr/9//7/wAACAAOABQAGQAcABsAFwAVABMADAAEAAMAAgD8/wQAFQATAAUAAwARAB4AGQAHAP3/AAD8//X/8f/r/+b/6v/p/97/1//U/9T/4//0//T/7P/x////AgD8//3/CgAUABYAFgATAA4ACQADAAUABgD7//P/7v/n/+H/4//j/+L/5P/n//L/AwAHAAYADgATAA0ADgATABUAGwAiABsADAAKAA8ACgD6//D/8P/s/+P/3P/a/9T/0//Z/+H/5v/r/+//7f/l/+b/8//7//7/AADz/+P/5v/v/+b/2P/R/8//z//R/9X/0v/M/8j/zv/Q/8v/y//P/9X/4f/v//D/5//m//D//P/9/wAABgAGAAAA//8CAAMA/v/y//D/AAALAP3/7P/u//r/AAD0/+3//v8TABcADAACAAIADQAXABgAFwAQAAMA//8LABIADAADAAEABgAFAP7/AAAMABYAFgAOAAsAEgATAAcA/v8EABAAEgAPABQAHwAdABIAFQAjACIAFQAMABEAGwAZAA4ACwALAAYACQAQAA4ACgAPABYAFgAVABAABwAHABMAHQAaABIAGQAoACkAIAAfACUAKAAoAC8ANwA1ACoAIwAgACAAHQAUAAUAAQD8//T/+P8IAAgA/P/9/xIAKgAyACcAGQARAAgABAAHAAMA+P/w/+z/6v/m/97/0v/M/83/0f/U/9n/3v/h/+X/6v/s/+j/6//w//T/9v/6//X/8P/r/9//1//b/+P/4v/Y/9b/5f/x/+b/3v/u/wMACgAJAAsACwALAAgABQAFAAgADQATABgAGwAcABkAGAAcABoADwAHAAwAEgAMAAQACgAWABgAFwAZAB0AIAAcAA8AAQD2//D/8v/7//7/+v/2//D/7//8/wkADwATABQADQAJAAsACwATACQAKgAdAA4ACAAHAAIA/f8DAA8ADgAFAAEA///v/+T/8f/6//H/7f/y/+v/4f/n//L/9//6//j/7f/h/97/6v/5//n/7v/s/+7/5P/e/9//3P/c/+n/8f/u/+z/8P/u/+//9f/4//n/+f/0//L//f8CAP7/AgAIAAQABQARABIACgAQAB0AIQAcABAABwAJAAoAAgD7//v//P8GABIADQAAAAUADgAPABUAGQASABQAIwAmABUABgABAAAA///6//r/CQATAAQA9v8AAA0ADAAKABAAGgAkACIAGgAdACMAHgAcACMAHQAMAA8AHwAmACEAFQANABQAGQARAA0AFgAeACEAKQAqABwAHAAsADIAJQAZABMAFAAYABoAFgASAAoAAAACAAIA+f/z//H/4//X/9z/5P/h/9z/4P/l/+j/5f/i/+r/8//s/9z/2f/i/+r/9f/4/+v/0//I/8j/x//I/87/z//I/73/v//O/9n/1v/S/9f/2//c/93/4P/j/+n/8P/y//L/9f/0/+//7f/x//j/AQADAPf/7//2//v/8//t/+//8P/y//r//////wIABwAFAP//+/8AAAsAEgAMAAQAAQAAAAEABQAFAAEAAQD7//T/+f8BAPz/+/8IAAoA/f/5//r/9P/z//f/9v/1//3/AQAFABAAFgAPAAMA/f8HAB0AIAAPAAkAGAAiACEAHgAaAB0ALAAtABkACwANAA0ACQAJAAYAAgACAP3/9//8/wcABAD+//z/+f/7/wEAAQD//wIA+v/s//D/+P/s/+P/8f/5//P/8/8AAAUA/f/w//H/BQAQAAcA/v/z/+n/9/8PAAgA7v/q//H/8P/1//v/8//u//3/CQACAPj/9//8/wcADAAIAP///v8NACEAHwAOAAwAFQAOAAEABgAPAAgAAAAAAPv/+f8HABUAFgAUABEAEgAYACEAIAAcAB4AIAAjACcAHgARAAkABAD7//j/+f/1//X/8//s/+r/6v/g/9T/1P/b/+X/7v/z//X//P8BAAIAAQD///3/BQAKAAMA/f8BAAMA/P/2//r/+P/q/97/6v8DAA4ACgAIAA4AEQATABkAJQApAB4AEgAOAAwACAAJABEAEgAGAPr/+/8EAAQAAAD6//D/6//5/wwACwABAP3/+//v/+H/4v/x//j/8//u/+7/8f/8/woABwD8//L/5//a/9n/4P/n/+v/4//U/9D/1P/W/9r/4f/m/+r/5//h/+X/8f/1//b//v////j/8//x//L/+/8EAAQABgALAAcA/////wcAEgASABIAIgA0ADYAMAAuAC0AJAAZABYAGwAgACMAJwAnAB4AGAAeACcALgAxAC0AHwASAAoACwAMAAcABgANAA4ACQAMAAsA+f/o/+b/6//1/wAABwAIAAkADAAYAB0AEgAIAAcABwAGAAMA/f/8/wMABwAEAAQAAQD8/wUAEwARAAcAAwAKABMAFgARABAADgAIAA4AGgAYAAwACQAJAAUABQAKAA8ADwAJAAkAEgASAAYA/P/4//T/9v8BAAcAAQD5//n/BAAPABAADQALAA0AEAAMAAgADQAVAAwAAAD7//X/7f/q/+z/8P/z/+z/5P/n/+//+f8BAAIABQATABsAFQAZAB4ADwAAAP///f/y/+f/5P/p/+v/5f/j/+T/2//V/+X/9P/r/+b/8/////v/8P/t//D/7v/n/+b/6//0/wYAFAAKAPj/9f/4//X/6//f/9j/0//S/9n/3P/T/8n/xv/G/8n/zv/O/8n/yv/M/9b/5//x/+3/6v/l/93/4v/r/+z/7//7/wAA/v8DAAwAEAAKAAAA+//8//z/BAARAA0AAAD8//n/7v/t//n//v/+/wQADwAVABUAFQAZABoAFQATABUAFgAVABAABQABAAQA/f/z//n/CAAPAAcA/P8AABIAGQAQAAoACAADAAQACgAJAAAA+f/7/wAA///7/wIABwAFAAwAHAAdABIACwAGAAoAGQAhAB4AGwAcABcADAAGAA0AIAApACMAHwAmADAANgAqABkAGwAiABoAGQAlACMADAAAAAgAFQAZABQAEwANAPz/9v8EAAoAAQD1/+//7P/t//D/9P/2//D/5//u//X/9f/3//3////+//3/8//r/+//9P/u/+T/4P/p//D/7f/r/+j/2f/M/9L/2v/V/9b/4//r/+3/7f/r/+v/7P/l/+H/5//t/+z/6//v//P/7//j/+L/6v/n/9//3//i/9//3P/a/9n/4P/i/9//4f/k/9//1v/W/9//7P/w/+3/7//v/+//9//+//r//P8IAAUA+//9//7/+P/v/+j/6P/z//r//f8FAAgAAgAGABUAHgAmACUAHAAbAB0AGgAhAC4ALwArACoAJgAjACYAHwAVABMAFgAbACUAKgAmACIAIQAnAC4AJgAZABsAJAAsADEALQAiAB4AGQARAA4ACQD+//7/BAAAAPv//f8BAAkAEAAHAP///P/3//r/AQAAAAQAFQAaAAwABwANABIAFgAUABQAGwAfABsAHgAgABMACwAPABAAEAAQABAAFgAgACQAIwAlACYAJAAZAA4AEQAZAAwA+f/8/wwAEgAGAPj/+P/9//X/5f/e/+H/5//r/+n/6f/s/+n/4//i/+D/2f/e/+v/7f/m/+b/7f/x//L/+/8LABUADgAIAA8AEgAOABQAHgAaAA0AAwD///3//f/+////+//3//7/DQAQAAYA//8BAAcADAALAAgACgAGAPv/+v8HAAoA+P/m/+b/9v8AAP3/+v///wQABgAAAPf/+P8DAAYAAgABAAAA+P/z//H/8f/0//n/+//+//z/9P/z//r/+f/4//z/AAABAP3/9//7////+f/7/wwAGQAZABAABwAIAAwABAD5//3/BwAKAAAA9f/4/wQABQACAAoADQAGAAAA/P/7//7/+P/t//L/9//v/+z/8f/0//v/BAAFAAQACQAPABUAEgABAPz/CQATABUAEwANAA4AHAAfABQACQD8//D/8P/2//P/6f/i/+T/5//o/+7/+P/2//f/AQAEAP7//P/7//f/AQAMAAsABQADAAUAAwDz/+T/5//r/9//2v/l/+v/6P/e/9L/1v/n/+f/4P/o/+//8v/5//////8GAAkAAAD9/wkADwACAPr/AgAIAAEA//8JAAgA9//0/wcADQADAP//DAAOAAAA//8MAA0ABAABAAAA/v////b/6//z/wMABgAJABAACgABAP///P/8/wQABgD9//X/8v/4/////P/2//r//P/y/+n/7f/4/wMACwAHAAMACwAUABAADQARABUAFQATAAsACAANAAoA+v/0//r/8//g/9v/5P/v//P/7v/p/+f/5P/m//f//v/x/+7/+P/7//T/8v/2//z/AgABAPf/5//f/+X/9P/4/+r/2f/Q/9D/2v/n/+P/2P/f/+//7//r//P/+////wMA/f/r/9//3f/e/+T/6//p/+v/8v/9/wYAAQDx//P/AwACAPn/AgAPABMAFAAWABsAIwAhABUAFgAfACEAGgAXACIALwAqAB0AGAAiACkAJAAVABQAIAAkAB0AIAAiAB4AGwAWAAoA///9/wsAIwAoABwAFwAOAP3///8PABIAEQAaABsAGQAaABoAGQAeABoADQAAAPn/AQAVABsADwACAPj/9P/6//////8EAAkABgAEAAUAAAD0/+n/6v/2/wAA/P/2/+3/6//1//r/6//l/+7/+P/8//v/8v/t//P//f8FAAkABwAHAAoADAAOAA8AAwD6//3//P/0//v/BwAOABQAEgAEAPz/BAAOABAADQARABwAGwAUABgAHQATAA8AFQAYABUADwAFAAEACAAMAAcA///9//7//P/5//b/9//4/wAAEwAbABcAFQATAAYA/P/+////+//2//P/+/8JAA8ADQANAAcA9//q//L/BwARAA0ACAAFAP3/9v/y/+z/7f/3////AAABAAcAEQAXABoAGQAXABUAGAAXAAwACQAZACMAGQALAAYABAAHAAgAAAD6//z/9f/t//P/+v/z/+v/+P8GAAYA//8CAAsACQAEAAUABQD5//L//v8HAAAA+f/5//3/AAD+//P/7f/z//j/9f/3//r/+//8//v/+v8CAAoAAAD4/wQAEgANAAUADwAdABsADAAFAAcACwANABAAEQASABUAEQAFAPj/9f/6//3///8GAAgABQD//+v/1//l/wMABwD6//L/6f/l/+z/6v/f/93/4f/n//D/8//v/+3/6//m/+T/4//d/+D/4v/X/9D/zf/K/9L/4v/k/+D/5f/l/9n/0//b/+P/4P/f/+r/8P/n/9v/1v/U/9b/2v/f/+n/7v/i/93/5v/o/+X/6v/y//b/9P/n/9v/2v/Z/97/7v/z/+7/+f8CAPj/7v/x//v/AgD9/+//8/8BAP3/+f8BAAEA//8GAA0ACgAIAA8AFwAPAP////8GAAIAAgANAA4ACQARABkAFwAWACIAMgAvAB0AFQAcABsAGgAeABkADwALAAgABAAJAAYA/P/7/wIAAwAGAAgAAwABAAEA//8AAAcACwANAAkABwAPABoAHQAaAA0A/P/6/wYACQABAP////8AAAQACwAQAAwACAARABgAFgAVABEABQAAAAMA/v/6//3/+//v/+3/9P/6//j/8v/5/wcADwAXAB8AGgAJAP3/9v/+/w4AEAAFAAAAAAD+//7//f/z/+f/5//w//X/8v/4/wUA/f/r//H/AQACAP7//v/7//T/7P/t//f/+f/v/+z/7//v/+//7P/n/+n/7//0/wAABwD///z/AAD7//H/8//8////+P/z/wEADwAGAP7/AwAHAAYABgAAAPf/8v/2////CgAIAAIAAAD6//7/DQATAA0ADQAKAP//+P/5//v//P/4//z/CgAMAAMAAQAEAAUACQAKAAIA//8BAAEAAwAFAAgAEQAXAA8ACwAMAA4ADgALAP//+/8HABcAIQAZAAgACwAjAC8AKwAmAB8AGwAaABUAEAARABMAHAAkABoACwAKAA8AEgAOAAQA/f/8//f/9f8AAAoACwANAA4ADwATABAAAwD3//n/AwAOABIAEgAWAA8ACgAQAA8AAgD+/wYABAAAAP7/+//4//j//P8AAPr/8f/8/wwACgADAP//+//6//3//f/8//r/+f8FABYAGgAVABMADwALAAwAEQATAA8ABwAQACQAIAAOAA0AHAArADAAKQAjAB0ADwAIABQAGQAMAAUACgASABkAFgALAAQA/P/3//z/+//p/9z/2P/a/+P/5//h/97/2v/Q/9X/5//t/+j/4//h/+b/7//2//7/+//1//b/8//i/93/4//j/+v///8CAPn/9//4//3//P/1//D/7f/n/+n/7P/g/9v/6//w/+b/6v/5/wcACgD9//D/7//w//H/+v8CAAUABwACAPn/+f/5//r/+//1//L/+f/4/+//9f8CAAAA+f/x/+f/7f/6//3/+f/y/+v/5//j/+v///8HAPr/8//z/+r/5v/n/93/2v/q//3/AQD0/+X/6P/v//H/+f8CAPn/8////wkADAANAAUAAQAKAAsABgAGAA8AGQAaAA8ACAAPABAADgASAA8AAgD6//f/+P8DAA4AEQARABAAEQAPAAYAAQAEAAYACgASAA0AAgABAP7/+/8IABMACwACAAEAAwAMAA8ACgAKAAkA///+/wcADAAPAA4ABAD//wYAEQAcAB0ADwADAAIACAAOABAACwAJAAQA/P///wMAAQACAAgAAwD//wEA/f8AAAcABQD///z/8v/p//T/AgD///H/6P/v//r//P/2//T/7//s/+r/5v/r//z/AgD7//3/CAAHAPn/8f/4////+f/v/+z/4v/i//L/+//0//f/AQAHAAkAAwD3//j/AQAAAP3/+//1//P//P8CAAMABQAGAAUABgAPABUACwD9////AwAAAAAAAQD8//v/AwAJAAsACQAEAP//+f/4/wEAAwD5//z/BQAAAPv/AgABAP7/CQASAAcA9//4/wEABgAHAAYA///1//L/9v/3//v/BAAIAAcACgASABoAGwARAAcABgAMABEADwAQABUAFAAOABIAGQASAAsADQAIAP//BAAQAAwA///2//H/8f/3////AAD6//f/9//0/+3/8P/+//3/6f/c/+j/+//+/wMAEQAUAAcA/v8BAAEAAQACAAIA/v/6/wAACQALAAoAFQAdABEA/f8BAA8ABwD0//z/DQAEAPj///8LAA8AEAAGAPT/8f8CAA8ADQAIAA4AFgAVAA8AEAAQAAYAAwANAAkA/v8AAAgA/f/1/wIAEgARAA8ACgD9//f/AwALAA8AEgAJAP3/BAAOAA0AEQAZABkAGAAaABYADQAJABAAGQASAP//+v/8//L/6//y//z/BQANAAoAAwAKAA8AAADv//D/7v/g/9//7f/t/+f/7v/u/+L/3v/l/+r/8f/2//L/9P/6//7/AwABAPX/8P/1//T/9f/+////AAAGAP//8v/x//L/8P/6/wwAEwAPAAgAAAD+//7/+P/v/+3/7//q/+f/9f8FAP///P8KABYAEwAOAAoACgAOAA8ADwANAAcACQAYACAAHgAdABQABwAGAAsABwAGAAsADgAWAB0AGwASABAAFwAeABAA+P/z/wEADAAOAAsA///x/+//+/8JAAkA+v/2//7/AwADAAQAAAD7////CQAKAAUA///6//X/8//y/+z/6v/u/+j/5f/2/wEA+v8FABkAEwAIAAcA/v/3/wYAEAANAA0ACAD7//n///////n/7v/p//f/AQDz/+f/9/8LAAoABQAMAA4ABgAEAAUA/P/1//z/BAADAAEABQAIAPj/5f/s//n/6P/a/+r/+P/x/+7/7f/s//L/8v/o/+P/4v/i/+r/7v/r//f/BAD5/+r/5v/e/+X/BQASAPj/5P/q//f/CAAeACAADQACAAUAAgACAAUA/P/0//n/9//u//r/CAAIAAEA1v+H/2r/mf/J/+H/BAAtAFUAiQCuAKUAjACQAKAAmQCEAHoAbQBPAC8AEgDx/9X/zv/a/+b/2v+3/5z/mv+W/4j/gv+C/4T/j/+a/5T/iv+O/5X/k/+N/5T/nf+l/7L/wv/P/9v/5v/u//n/9f/c/9f/7//6//f/AwAJAAEABAAGAPT/7P/w/+b/1v/V/9j/1//d/+H/2//Z/93/1//O/9b/4v/g/+D/8/8BAAEAAgALAA4ADAAQABYAFQASABsAIgAeACAALgA8AEgAXQBlAF0AWQBbAFgAVQBNAEIARQBFADkAOwBOAEkAOgBAAEgARQBLAFAARAA/AEoARwA9AD8APwAxACYAGQAEAP7/CgAIAP3/AgAFAPr//v8JAAIA+f/8//j/+/8MABIACQAMABIADAAGAAgADwAZACUAKQAuADIALwAoACUAJAAiACcANgA6ACYAFgAZABwAGwAgABwADwAQABoAHAAgAC4AMQAsACcAHwAUABYAJwAsACQAKQA1ADsAPgBCADgALwAyADAAKAAqACwAJAAnADAAJgAVAA8ACgAGAAkADAAHAAAA+f/x/+r/3v/Q/83/0f/V/9f/1f/H/7b/qv+l/6n/s/+3/67/qv+t/6T/mP+o/8L/wf+z/7T/vf/B/8P/xv/H/8L/vf+9/77/v//K/9X/zf/D/8j/zP/I/8v/1v/e/+X/7v/x//L/9v/3//L/8v/4//z/9P/v//v/EAAWAA0ADwAgACYAHwAcACAAIAAlADQANwAvACwAKwAlACEAIAAVAAsAEAAeACMAHAAUABQAGAAeAB8AFAAKAAMA+v/1//7/CAAGAAAA/P/3//X/+f/4//b/9//7//7////9//3/AQAFAAcACQAEAPT/7v/9/wgABQD///3/9P/p/+j/6v/n/+X/5//y//z/8//e/9X/2//k/+//7P/a/9H/4v/w/+7/6//v//b/AAALAAwACgAJAAcABQAMABcAHAAYABQAFgAgACYAHAAJAP3/9f/u//H/+////wEABAD9//D/6//w//b/9//z//P/+v/6//P/9f/7//X/8P/5//z/6//c/9z/3//e/+H/4v/Z/83/zv/a/+P/3v/V/9f/2v/S/8v/zP/H/8D/yf/U/87/yf/S/9P/xf+//8P/yP/K/9D/2v/o//H/7f/l/+T/6v/0//v/+v/3//3/AgD6//b///8JAAoACwANAAwABwAHAA8AGQAcABMADQALAAgACgASAAoA9f/x//3/AAD9/wAA+f/r/+3//P8CAPr/8//0//3/CAAMAAoACwALAAUAAgABAP7/AAAOABUADAD9//b/9////wUABAAEAAcACwASABUADQADAAQABwABAAIACgALAAkAEAAVAA4ACAAMABUAGAAXABkAHAAcABwAJAArACcAHwAgACMAIQAhACYAIwAbABcAEgAPABoAKAAqACkALAAqACoAMwA1ACoAJgAuADAAJQAeACQAKQAnACYAKgAlABcAFAAhACYAGQARABEADwAOABUAEwAGAAIAAAD7//7/DAARABEAGwAiABkADAAEAP3/+P/4//n/9v/5//r/8//u//P/9//z/+j/3//k//H/9//x/+b/4P/j/+7/9f/2//b/9f/v/+//9v/6//X/9f/3//r///8AAPn/9//+/wMAAwABAP7/+/8AAAMA/v/3//b/+f8EABEAEwANABAAFwATAAwACwAKAAMAAQAIABEAGgAbABYAFgAgACEAEwAGAP7/+v///wMAAwAFAA0ADAAIAA4AGAAUAAoAAwAFAAgACwAJAAYABAABAPz/+v/6//b/7v/n/+j/8//8//v/7//m/+T/6v/v//H/8//3//X/8P/x//f/9P/r/+n/5//r//r/BAD7//D/8f/y//P//f8HAP3/7f/s//P/+f/8/wUAEwAdABwAFgATABEACgANABUADwABAAMAEQAYABMACgACAP//AwAGAP//9//4//7////9////BAD9/+//7P/1//j/8v/y//f//P////z/9v/1/wAACgANAAsACAAIAAoABAD5//T/+P/2//D/9P8AAAQA+//0//n//v/7//z/BQAEAPH/5v/p/+j/5P/o//b/AAALABEAAwDw/+z/8//z//f/AwAJAAIA+v/8/wIABwAIAAcACAAKAAcACAAKAAQA/v8CAAoACwAGAAMAAwAGAA4AEAAHAPz/+v/5//T/7f/t//b/BAAMAAcA+//2//v//f/8/wUAFAAVAAsAAQD9//z//v8CAAAAAQAGAAkABgAFAAQAAAD//wQACQAJAAoADgAKAAEA9//y//v/CQAMAAMA/f8DAA0AFAATAAoAAgAKABMAEwANAAwAEAAUABAABAD4//j///8CAAAA+//6//7/AQAAAP///P/6/wIAEwAWAAQA9/8BAA8ADgAFAAAA+P/v/+3/6//e/9T/3v/t//P/8//y//L/+/8KAA8ABAD7////AgAGABEAFgARABAAEwANAAEAAgAJAAkABwAJAAUAAAABAAIA9f/o/+f/8////wkADAAGAPz/+f///wYABwAIAA0AEAAHAAIADQAYABYAEgAXABsAFgASAA4ACQAHAAsACQABAAAABwAEAPr/9f/z/+3/6v/v//X/9//2//H/5v/g/+j/9v/4/+7/5P/l/+r/7P/w//j//P/3/+7/6f/s//L/+P/6//b/8f/q/+T/4v/l/+///P8IAAQA+v/7/wAA/P/z/+3/6f/o//P/AwAEAPf/9P/3//T/9/////n/4v/a/+j/7f/j/+H/6v/u/+r/5//n/+f/6v/t/+n/5v/p/+z/6//p/+j/6f/v//H/7//0/wQAEQAPAAYAAQD8//b/7//o/+f/7//3//T/8P/w//b/AQAMABIADwANAA0AEwAdACMAHQAVABgAHAAaABwAJAAmAB4AFQATABMAFgAZABcAFwAfACYAIQAZABcAIQApACsAKgAuAC8AKAAZAAwACwAXACIAHgAKAP7/BgARABAAEAAUABAADAARABYAEwAKAAYAAgD+//3/+v/3//T/9P/1//X/+P8CAAgACAABAPb/8P/1////BQAGAAQAAQD+//7//P/4//n/AwAIAAEA/f8CAAYABQD///D/4v/s/wIACAD9//X/9f/8/wkAEAAKAAIABwAOAA4ADAAMAAYAAgAKAA4ABQD8////CwAUAA8AAwD8////AgABAP3/+f/9/wcADAAEAP//AAD///f/9f/8//3//f8AAAIABAAIAAcA+//5/wgAEAAHAP//AAAAAPz/9f/w/+v/6P/s//T//P8CAAEA/P/7//v/+f/y/+j/5f/s//D/6f/p//D/8v/u/+z/6f/k/+f/7//v/+b/4//n/+b/4f/g/97/3//w/wQAAwD4//n//v/6//v/BAAFAPn/8//7/wIABgAUABwAFgATABwAHwAUAAsAEAAeACAAFgAMAAYABQAJAA4ACQAJABoAJgAgABMAEgAZABUACgAHAAsACwAJAAYACAAUABoADQD///3/AgAFAAoADwAMAAQAAQD///3/+P/7/wcAEgAZABgACQD5//b//P8BAP///f8CAAQAAAAAAAIA/f/7/wIAAwD+//z//f/8//3/AQAGAAUA///7////AAD6//H/6v/u//T/9//3//r/+//3/+3/5//s//P/7P/l/+b/5//p/+//9v/3/wEACgADAPX/7//y//b/8v/o/+P/6v/2//b/7v/u//j/9v/u/+n/5v/s//r//P/z//T//P/8//n/+f/6//j/+P/6//n/9//0//P/6//k/+X/7f/v/+f/3P/c/+f/7f/r/+n/6//x//r/+v/y//P/+P/2//X/+P/4//r/AwAJAAMA9v/2/wEABwALABMAGAAUABAADQAHAAQABwAMAAsAAgD//wQACQALAA4ACAD5//L/9f/3////DgAVABIADgAPABAAEAARABIAEAAPABAADQAIAAgABgADAAMAAQD8//3//v/3/+7/6//r//D/8f/w//j/BgAHAAAAAQAIAAYA+//z/+//7f/y/wAACQAPABYAFAAIAAoADAD+//L/+P/9//X/8//9/wUAAwD+/wAA///3//L/9v8CAAgAAQDz//H/9v/y/+3/7P/s//L/+v/+//3/+f/u/+f/8v8HAA8ACQADAAQAAwD+//7/BAADAP///v8FABIAEQACAPv/BgAOABEAGgAhABgADAAKAA0ADAAHAAIA/v///woACwD///z/AwADAAQABwD///v/BgAQAA4ACwANAAkAAAAAAAkADgAKAAgACQAIAAsAEQAQAA4ADgANAAwACwAJABEAHgAaAAsAAgD4/+3/9f8HAAQA8//s//D/8f/z/wYAFQAPAAUABgAKAAsAAQDu/+v/AAAMAAkACAANAA8AEAASABQAEQAHAAMAEAAiACkAHAALAAwAHAAhABIABAAGABEAEQAKAA4AGQAWAAkABAAGAA0ADwAJAAUAEgAgACAAEwAEAAEABAD9//P/8v/z//f/BAAQAA4ABQABAP7/+//2//b/9//5//v/9//q/+f/9f/6//X/9v/9//7/9f/u/+//9v/0/+7/7f/1//j/8f/p//D/+//7//r//v////3//f/4/wAAFQAdAA4ACAATABkADQAAAP7/AQD3/+X/4f/v//r/+P/0//v/CAASABYACwD3//f/CQAKAAAAAwAKAAoACwAHAAEAAwAIAAQA//8AAP///P/7//7//v/9/wEADQAQAAUA/P/+/wUABgD6/+//8//6////AAD7//j///8GAPz/8P/u//H/7P/l/+7/+//3/+7/8v/x/+z/8f/4//P/9/8GABEAEgALAAQAAwAAAPr/+/8DAAcA/v/v/+f/6f/t//T/+////wQACwAJAP3/8//z//n/AAACAAIAAwABAAIABwABAO//7P/0//7/AgD9//X/+f8AAPz/8//s/+r/8//9//j/7//v//b/9f/r/+L/4v/q//H/9P/u/+j/7f/0//v/AQD6/+3/6//y//b/+v/6//L/8//8//7/+//5//n/+//6//n/AwAPABAACwAJAAcABAD9//L/8/8CAAoAAwD6//z////1/+3/8//6//z/AAD+//f/+f/3/+b/3f/n//P/9v/w/+f/7P///wUA/f/4//v/AAAEAAYABwAEAAYAFwAgABYAEQAUAA4ABgANABQADwACAPv/+v/6//r/9//y//T/+f/x/+b/7P/z/+j/4P/o//T//f/9//L/7v/u/+v/8/8IAA8ABQABAAAA+v/4//z/AQD///f/9//6//n/9v/z//H/9f/0/+v/5//w//z/AQD0/9//2v/o//b//v8AAPn/9P/w/+v/8/8GAA0AEAAYABYAEAATABEACgALAA4ADgASABQACwD//wEADQAQAAsACwAPAA0ACwAPABMAGQAeABwAGAASAAgABQAJAAsADgAaAB4AFQANAA4AFgAVAAkACAAXAB0AGwAdABUACwARABwAGAAQABAADgAGAAYAEAAZABYAEAAHAAAABAAQABEAEgATAA4ACgALAAsACgANAAgAAAACAAYABAAEAAUACgANAAQA+f/5//z/+P/4//P/8f8AABEADAD9//n/+f/4//f/+//+//n/+P/+//3/+/8BAAoACgADAPf/+/8EAPz/7//z//n/9//+/wgAEAAXABEA/v/2////CgAOAAkAAQACAAYABwACAPv/9f/7/wUABgAEAAQAAQD8/wAADAATAAwACQAQABEACgAEAPz/+P///wYACgAOAAYA+/8CAAwACAAIABAAEAAMAAgABAAFAAcA///3//f/+v/3/+7/5//m/+X/4f/k/+n/7f/2//z/+v/1/+//6f/m/+7/+v8AAPv/+f/+//r/9P/8/wMA/P/9/wMA+v/1//3////8//3/+P/x//H/8v/v/+v/6f/v//f/+//8//3/AAAFAAgABwAGAP7/9f/5/wMAAQD6//z/AwAHAAUABgAQABMACgAKABIAFQAWABcADAAEAAsAEAAQABEADgAIAAUABgAIAAQA9v/u//f/BQAMAAwACwANAA0ADgAQAAYA8f/m/+//+v8AAAMACAALAAYA//8AAAUABgAHAAUA+f/z//v/BAAMABQADwAFAAMABQAGAA8AGwAdABIACAAJABMAFwASAAwACgAKAA4AEAAMAAMA/P8AAAQAAQAFAA0ABgD7//z//P/5//z/AgACAAUACQAKAAIA/P8CAAkABAD+/wMACgAIAP//9v/5/wcABAD2//T/+//5//L/8//9//7/9v/y//L/7f/u//T/8f/r//b//v/2//L/9f/4//z/AQAFAAoABgD7//P/9v8AAAcABAD5/+//6f/n/+n/6f/m/+f/7//6/wEAAAD8//X/6//p//D/8//u//D/8//0//f/9//z//H/7//v//T/8v/t//L//P/8//3/+f/q/+H/6f/w/+v/6v/z//z///8AAP3/9//x/+v/4f/f/+j/6//k/+X/7//8/wMA/v/0//L/+/8JABgAFQAIAAYACAAHABMAJAAmACEAHAAUABAAEwARAAsAAwD//wIACgAIAAMABQAKAAsADQARAA4AAAD0//D/9f/8/////P/9/wYABgD8//r/+//5//7/AQD6//f//f////z/9P/r/+j/6f/m/+n/8P/v//D/9v/w/+P/5//x//D/7P/z//f/9f/0//r//P/8//n/+P/9/wUAAwD7//n//f8CAA0AEgAHAPv/+f/7//n/+P/9/wcACgAEAAkAEwANAAcACQAHAAkAEwASAAQAAQAJAA8AGAAiABsACwAKABcAGwAYABUAFQAVABYAEgAJAAQABQANABcAFgAOAAsACAACAAAAAgADAAsAGAAaABQAEgARABIAGAAXAAgA/P8DABcAHwAVAAwAEwAaABUAEQANAAMA/P/+/wEAAgAIAA4ADgALAAkACQAPAA0AAwABAAoADAAHAAkABwD0/+3/+f8CAAAA/f/0/+z/9P8BAAEA+v/2//D/6v/l/+T/6//y//T/7P/k/+X/7v/z//D/9P/9/wAA//8DAAgABQACAAoAEQAMAAQAAQAEAAYAAwACAAEA/P/3//j/+//+/wcADgAGAPr/9//4//z////5//P/+/8GAAQABAAIAAMA/P/4//L/8v/+/wsACwAOAA8AAgDz//n/BQACAP3//f8AAAMABwAIAAQAAgAHAAcA/f/6/wUACwAEAPz/+v///wMAAQD1/+7/8//2//f///8DAAEAAgAEAP3/+P/6//z/AQAMABEADwARABkAIwAoAB8ADwAMABUAFwATABAADQAOABkAHwAYABYAHAAYAAsACAAHAP///v8LABUAEwALAAIAAQAIAAwACAAEAAYABAD2//H/+v8AAPz/AQAMAAkA+//1//b/9P/z//v/BAACAPT/6P/p/+7/6f/o/+//7//n/+//+v/3//T//f////j/9f/y/+f/6v/7/wQABAALAAsAAwAAAAEA/P/9/wEAAgADAAgABwADAAIAAwAHAAkACAAJAAwACAACAAEABAABAPz/+v/3//D/6f/w//z/9//n/+X/5//g/93/5//u/+z/6v/r/+z/8P/t/+b/6f/t/+L/2P/j/+z/6P/u//b/6f/h/+3/9v/2//r/+v/2//j/+P/y//H/+//7//P/8f/9/wcABwAEAAgACQAEAAYADgAPAAkA///5////DAASAA4ABwAFAAcACAALABMAFwARAAkADAAPAAkABAAFAP//9P/5/wUAAQD6/////v/0//b/+f/0//v/CAADAPj/+v/8//v/AQACAPz///8KAA4ACAADAAIAAgADAAUA/v/z/+3/8P/2//n/+v/5//f/8//x//T/+f/+//z/+v///wYABgAJAA4ACgABAP7/9//v//X/+//5//b/9v/y//T//P/9//7/AgAAAP3/AgACAP7/AAD9//X//f8MAAwABQAHAA4ADgAHAP3/9//7/wUABwAAAP3//v/6//f//P/9//T/9P/7//n/7//q/+r/6//t//D/7f/v//f//f/5//j/+//7/wAACgAGAPz///8JAAgAAgD///3//P/1/+r/6f/0//f/8P/u//j//v/3//P//v8MABUAGwAWAAIA9f/4/wgAGQAdAA4A/v/7////BgAKAAkABQAEAAAA/v8EAAsADAAHAAAA/v///wAABgATABgAFAAOAAkACgAOABAADwANAAsAEAAYABkAFQAcACAAFwANAA8AEgAMAAUABgAMAA4ADgAPABEADQADAPj//f8LABIAEwAZABMAAAD4/wEABgACAAcAEwAYABQACgADAAkAFgAbABkAHQAlACAAFQARABEAEgATABMADwANAA0AEAAVABYAEgANAAcAAwADAAMAAgADAP3/9////wUA+v/6/wgACwAEAAAA/P/4//b/7f/k/+r/9//8//D/5f/w/woADwADAAYAEwAYABgAEwAGAAEABwAHAAQACAAFAP//BQAQAA4ABAD+//z/+v/6//f/9//9/wMAAQD5//X//f8LAAcA+/8CAAUA8P/g/+3///8BAP3/+/8CAAkAAQD2//f/9f/w//T/9v/z//L/8P/s//P/+//3//H/7P/m/+v/8v/t/+f/6//t/+z/8f/0//b/+v/8//n/9f/1//3/BAD///v/AQACAPb/8v/+/wMA9f/q/+//+v/9//b/8P/4/wEA/v/+/woAEQAIAP7/+P/2//n/+v/0/+7/7//0//7/CQAMAAgAAAD7////AAD4//r/BQADAPb/7v/u//P/+P/4//r//v/5/+//7//v//H/8//t/+P/6f/y//D/7f/w/+//7v/0//7/AgD9//b/7//s//T/AwADAPr//P8CAP7/AAAHAAAA9v/9/wkAAgD2//X/+//7/wAABQD+//L/8//2//P/8v/4/wEABAAFAAgADQAKAAQABgAEAPj/8//5//v/+f/9/wIA/P/w//P/AwAEAPX/8P/z//X//v8CAP7/BgAVABAAAwAJAA4AAQD5/wcAEQAKAP//AAAEAAYABQD///n//f8EAAIA/v8AAAAA+v/w/+v/8/8CAAYABgAIAAMA+v/9/wkADAAGAAQACQALAAUAAwAHAAsAEAAXABcADAAIAAgADAATABYAFAAOAAQA/P8BAAoADAAOABAACgANAB4AJAAbABIAEQAOABEAGgAbABEADwATAAkA/v/+//7/9P/t//H/9v/4//z/AwANABEACwD9//P/9/8DAAYAAQD9//r/+/8EAAMA+f/6/wMAAQD6//L/6//q/+3/5v/g/+T/7f/y/+7/5//s//f/+f/6/wIABAD9//v/+//8//v/+/8EABMADwD6//n/DwAYAA4AAwAAAP7/9v/s/+7/AAAMAAUAAwARABsAFQAPABEAFgAUAAwABgAEAAEAAAALABoAHgAeABkADwAOAA8ABAD8/wAACwAQAAkA9//q/+v/8P/5/wAA+P/y//v/+v/r/+r/8v/w//b/AwAAAPj/AQAKAAcAAAD1/+//9v8AAAEA/f/2//L//f8IAAMA+//6//3//P/5//H/7//2//n/8//y//r/BAAKAAcAAQAEAAgA/P/x//T/+v///xAAGQAMAAIABwAOAA0ABAAAAAkADgADAPn//v8HABEAFQAPAA4AFQAWABsAJgAeAAsADwAbABYAFQAcABUABgAEAAcACgASABcAEwAUABgADQD5//L/8//z//b/9v/v/+v/7//y//T/+P/4//P/8v/4//3/+v/9/woADwACAPX/+v8FAAgACQAKAAYA/f/2/wAAEwAWAAQA+f8AAAYACgAQABAACQAIAAsADAARABgAFgAQAA8ADAAEAP3//f8EAAkABgD+//3/AQD9//X/8f/w/+3/6P/n/+7/9//2//L/9v/4//b/+v/+//X/8P/1//b/8f/y//T/8v/t/+7/9f/5//H/6P/z/wMA/v/y//X/+P/y//b/AAD2/+T/5f/0//3/+//3//T/8f/x/+z/4f/j//b////x/+H/4f/i/9r/1f/c/+T/5//o/+z/9v/3/+3/6f/0//n/8v/t/+n/5f/m/+L/2f/Y/97/2//T/9X/3//p/+7/7f/n/+z/9P/0//D/6v/j/+b/8//9//v/+P/1/+7/6P/p/+//9P/x/+v/7v/2//r/AgARAA8A/f/9/xQAHgAZABEADQAQABcAEgAEAAQAEAARAAgACgATAA8A/f/1/wEAEQAVABMAFAAaAB0AFwAQAA8AEQATABgAFwALAAIABAAGAAcAEAAaABkAFgAbACUALgAwACQAGAAbAB0ADwAGAAoADwAPABAAEAAPABIAEwAXAB4AGwAKAP//AwALAA8AEwAZAB8AHwAVAA4AEwAZABMACwALAA8AEwAYABIABgD//wAACQAOAAYA9//4/wcADAAJAAYA///3//b/+f/4//j//f8EAAUAAQD0/+L/2f/j//P/9P/v//L/+P/3//D/7v/0//r/8v/n/+3//v////n//P/9//f/+v8CAP3/9f/2//P/7v/w//P/8v/4//3/+P/6/wkADgAHAAUAAwD5//r/BwAMAAMA/f8EAA8AEQAHAP3///8IAAwACgAFAAgADAAEAP7/BwARAAoAAQADAA4AEQAKAAAA/P/+//n/8v/z//X/8f/w//L/8P/v//X/+P/z//D/8//3//j/+f///wQAAwADAAoAFgAdABkADQACAAMACQAEAPj/9f/9/wUACgACAPj/+f8GABIAFAAHAPD/6v/8/wkABwAIABUAHwAeABoAGQAYABgAGwAeABcADgAQABAABgABABQAJgAiABEACAAOABcAGwAaABkAFAAKAA0AGQAWAAgABAAEAAEABAAJAAQA/f////z/9//9/wgABgABAP7/+f/4/wAAAgD+/wUACgD2/+H/5f/y//P/8//1//X/+/8HAP7/3//P/97/7f/s/+X/5v/v//r////4//D/7v/z/wIADAADAPr//f////r///8LAAkA/v/9/wQACQAOAA0ABQAAAAIAAQABAP7/9//6/wkACwD///f/+/8DAAoABgD0/+////8KAAwAFgAZAAUA9////wMA9//w/+7/7f/0/wEAAQD1/+//9f/9/wEA/v/4//r/BAADAPr/9f/5////BQD8/+z/7v/+//z/7v/w//X/6v/q/wIAEQAGAP3/AQAKAA8ADAAEAAcAEwAPAAEAAAAHAAgAAAD7/wAABwD8/+X/5f///wIA7P/v/wUABgD3//T/9f/w//b/AQACAP///f/0/+b/4v/r//X/9//2//f/8v/r/+n/9P/8//n/9v/6//n/7//r//X/AwAMAAwAAgD8/wAAAgD5//X/AQAMAA8AEgAVAA4AAADy/+j/6f/3////AQAHAAsABAAAAAwADwAHAAcADQAKAP7/9//1//j/AAADAPz/8f/p/+H/4f/o/+7/8v/6/wMAAQD2//L/8//y//H/8v/2//r//v/7//L/7f/v//P/+P8AAAQABgAOABgAGQAWABkAGwAUAAoA///2//v/BAADAPv//f8DAP//8//y//v//f/x/+3/AgAbABcAAAD1//3/BQAEAP////8FAAgACAANABMADwAGAAkAEQAPAAgAAQD3//H/8P/u/+v/8P/0/+z/5f/s//L/7//r/+n/4P/b/+X/7v/w//P/9v/w/+z/8v/4//b/8f/s/+3/7v/r/+z//P8LAAAA8P/z/wIACQAIAP3/8f/4/wcAAgD5/wEACQABAP//BAD9//P/+P///wEACgAQAAYA/f///wMACAARABAAAgD9/wMAAQD8/wQADgALAAcABgAEAAIABwARABYAFQANAAYABgAKAAwAEAAUABQAFQAQAAQAAgAOABgAEwANABAADwANAAwACAAFAAYAAgD4//T/+P/1/+7/8v8DABAAEQAGAAAAAAD+//v/BwASAAcA+f8DAAoA/f/7/w4AFAAKABMAKgAzADAALwArACgAJgAaAAoACgAUABYAFgAeAB0AFQAbACkAJQARAAoAFAAhACQAIQAgACIAIQAcABYAEgAOAAoABgAAAPz/+f/y/+z/8f/6////AQAFAAcABwAGAP//9//3//r/9f/t/+//8v/v/+j/5//r/+r/3v/Z/+b/+/8AAPj/9v/+/wAA/P/8//z/9v/u/+z/7P/k/93/3//k/97/2P/o//j/9f/s/+//8f/v//T/9v/m/9v/4v/o/+P/6f/6//7/8f/q/+r/6f/o/+f/4//d/9//6f/w/+v/5v/s//j/AQACAAIAAQD+//v/+f/4//r///8FAAgABwD///f/+v8IAA8AAgDy/+//9P/4//v/AAADAAEABgANAAkA/v8CAAwACwAFAAIA/f/2//3/BwAFAAQAFAAdABIACAANABEADgALAAkAAwD/////AQAEAAYACAARABoAFwAFAPn/9v/3//3/BQAFAPn/9f8BABYAJQApACEAFQAQABoAKQArAB0ADAD///n//v8KAAwABwAMABUADgABAAYAFwAWAAMA+/8FAAsACgAHAAMA+P/t/+//+v/9//P/7P/z//n/+f/4//z/AAADAAUACwAPAA0ACAAIAAsADQAQABsAHwASAAQABAAIAAcACQATABkAFQALAP7/+P///woACgAFAAgADwATABIACgAAAAEADAASAAgA9f/r//H//f8CAAAAAQANABcAEQAAAPL/8f/2//f/+f8DAAoABQD6//j//P/+/wAA/v/2//H/+P8DAAAA9v/2//z/+P/r/+D/2//Z/9//5//o/97/1P/P/9n/7v/+/wIAAQAGAAoABgAHAAgA/f/y//b/AAD8//D/7P/x//f/9f/p/93/3f/n/+f/3//Y/9f/2//l/+j/3//a/+L/5//d/9T/2P/g/+D/5P/v//X/8v/w//j/AwACAP7/+//6//P/6//u//n/AQACAAIA/v/v/+D/5f/0//f/9f/6////AgALABYAEQAEAAEABAACAAEAAwACAPr/9P/v/+//+P/8//D/4v/q//v/+//0//f/BAAMAA8AEwAUAA4ACwAOAA4ABAD7//3/CgAVABcAEQAPABoAKgAxACsAHgATABMAGAAXAA8ADwAXABsAEgABAPj//f8HAAkABQAMABgAFQACAPj//f/+//3//v/8//j/+v8DAAUAAAD9//3//f8AAAYACQAOABYAGQARAA8AGQAaAAcA9v/4////+v/w//X/BwATAA8AAwD6//z/CQAbACcAIgAWABYAGQAPAPr/9/8JABAACQALABYAGQAXABwAIAAXAAwADAASABMAEAAMAAgACAALAAkABAAHAA0ACQD///r/+v/5//T/9P/3//j/9P/x//H/9//5//X/8P/0////BAD+//X/8P/y//r/AgD+//P/9f8GABUAEgANABEAEQAFAPz/+//2//H/9P8AAAYABgAJAA0ACgACAP//AwAJAA8AFAAbACEAHwAUAAkABgABAPj/8//2//z/AAAEAAkACQAFAP//+/8AAAsADQD+/+7/7P/0//3/AgD+//j/+v/+//z/+P/0//H/8v/6/wQADQATABgAGAARAAgAAQD7////DgARAAEA8v/y//H/6//l/+P/7P/6////8//p//T/AwACAPj//f8JAAgAAgADAAEA+/8AAAcAAwAFABYAHwAWAAUA+v/3////BgAEAP3/AAAOABYAEgAUAB4AHAARAAMA+f/5/woAFgARAA0AEgAYABwAGgAUAA4ABgDz/+L/4//w//f/8P/p//D//P8AAPz/9//w/+7/7f/r/+v/8f/x/+r/5f/i/+L/6f/1//3////5/+f/3f/n//j//P/0//D/8//0//H/9P/4//f/9f/x/+r/5P/s//f/+v/y/+3/7v/0//j/9P/q/+v/+f8GAAQAAgAHAAIA9P/y//z////5//f/+f/2//b/+v/3/+z/7//5//f/8f/3////AAABAAIAAAABAAsAEgAKAAEAAwAJAAQA//8DAAsACgAFAAMABgAEAPf/8P/8/wkABwD8//b/9P/2//3/AQD+//f/7//v//T/9v/5////BAABAPj/8P/z//7/BwALAAwABgD9//r//f/9//b/9v8CAA4ABQD0//H//f8CAP3/+f/8//z/9f/v//b//v////v/+v/4//b/+/8FAAoABAD6//P/8v/9/wcABwAGAAkABAD3//P/+f/4//n/AgAIAAIA/f//////+P/4/wMACAAAAPb/9P/2//f/9v/7/wgADQAIABIAIgAZAAQAAgAMAA4ADQAMAAUA+v/z//P/9//9/wQACQAEAP3/+f/2//v/CQAJAPf/9/8IAAoABAAHAAEA7f/g/93/4v/q//D/+/8BAPT/6//0//f/7//y//v/+v/5/wQADgAPAAQA+v///wUAAAAEAA0AEwAcACIAEQD//wEACgANAAwABgAEAAwACQABAAUACQAGAAQA///5//v//P/4//n//f8CAAwAFgATAA8ABgD0/+3/8//3//X/9v/7/wYAGAAhAB0ADwADAAIABwD9/+//8//5//T/9P/5//j//f8HAAYAAAD//wEABAAHAAcAAAD0//P/AAAHAP///P8BAAMACQASABQAEwAcACEAFgAGAAEABQAPABsAIQAaAA0ABwAQABoAGQATABEADwAIAAQACQAUAB4AJQAkABYACQAJAA4AEgAbACQAJAAaAAwAAAD//w0AGQATAAMA/v8EAAoAEgAUAAYA+f///wQA+//6/wcACwABAPn/9//2//P/+f8AAPz/7f/p//D/8f/2/wEABgD6//D/7f/m/97/4//x//T/6P/j/+r/6v/q//P/9//1//r////1//H//f8EAPz/+v8FAA0ABQD9//7/BgAJAAoACwAKAAYAAQD8////AgD9//r/BAAKAAIA/v8DAAQA+//5/wAAAwD/////BQAGAAQABQAJAAwADAALAAkABQD9//n///8GAAIA+v8AAA0ACgD4//b//v/9////DwAQAAMABwAWAA8A/v///wkABwD6//P/9v/z/+3/9f8BAAUABQAEAPr/8v/z//b//v8AAPH/6v/0//b/6//l/+j/9P8GAA0ACgAEAP7/+/8DAAwADwALAAQAAAAFAAQAAgAMAAsA+//5/wIA//8BAAgAAAD+/w0AEQAMABkAIQAQAAEA/v/6//X/+f8IABQADgABAAMA/v/t/+z//f8CAAUADQAOAAYAAQAAAP///P/1//n//f/3//T/+P/4//z/BQD9/+7/7//x/+3/+f8FAAAA+P/3//r/+f/1//P/9v/r/9n/4P/1//n/9f/2//T/8P/r/+X/6P/u/+f/3//g/97/3v/q//X/+f///wcACAD9/+7/6f/y//f/8//u/+f/6f/z//n/+v/9//3/9//2//n/9f/v/+3/+P8GAAgABQAIAAoACQANAA0ACgAHAP//9v/7/wUAAgD4//f//f8AAPz/+v/8//j/9//+//7/9//7/wQABAABAAYABwAFAAcACQAFAAAABQAQABYAFAAQAAgABAALAA0AAwACAAwAEAAQABAACgAEAA4AFwAUAA8AEwAZABoAFQAKAP7//v8OABYACwACAAYACAACAAUACwAJAAMABAAJAAcAAgADAAUAAQD6//z/AwAIAAgABwAIAAoADQAUABIABQAFABYAHgAYABAABAD8/wYAFgAeABkADAAFAAsADwAKAAQAAwAGAA0ADQAFAAMABQAGAAYAAQD3//n/BgAKAAQAAAACAAIA/v8AAA0AFQAPAAsACgABAPv/AAAFAAkADgATAA0AAAD4//n//f/8//b/8P/x/wAACwD9//H/+/8FAAAA+f/2//P/8v/1//3/AgD6/+j/3//o//T/+f/+/wIAAgD8//X/7P/v//z////7//3/BwANABUAFQAIAAAABQACAPn/9//5//3/BgACAP3/BQAKAAEA+v/+//3/9v/1//X/8P/q/+f/7P/0//n/+P/8/wUABAD6//3/CAANAA4AEQAMAAUABwALAAkABwAFAAgAEgANAP3/+P8BAAIAAQAFAAEA+P/9/wQA/f/4//z/+f/v//H/+f/9//r/9P/z/wAACQADAAIADAASABYAGgAWAA8AEAAUABYAFwAUAA0ABwAGAAwAEwAOAAoADgAQAAgABAAAAPv//v8CAAUACQAKAAsAFAAVAAkABQAMABEAEgALAAAA9//x/+7/9P/3//H/9f/6//n/+//7//b/+/8GAAYABQACAPn//f8HAP//+f/7//T/8///////+P/9/wEA+/8AAAAA9P/x//v/AAD//wAAAwAHAAIA/f/6//j///8HAP3/8P/v/+b/2v/f/+H/2f/b/+j/8f/z/+v/5P/u//D/5P/q//L/4v/W/+D/3v/W/97/5//r//X/9//x//T///8BAPX/8v///wQA9v/u//L/7v/s//H/7//v//b/8v/u//H/7f/i/+D/5v/w//v/+P/v//T/8//k/+D/4//k/+//BQAMAAUA/v/2//T/+f/4/+7/5//x//v/9v/w//v/AwD9//v//v/4//X//v8IAAwABgD3//D/+v8EAAEA/P/4//j/+//8//b/9v8BAAMA+//7/wMABAD/////AwAKABAAFgAcABoAFAATABwAIQAbABMAEQARABAAEQAOAAcAAwAFAAIA/f8BAAUABAAHAAcAAQADAA0ADwAVACAAGQAKAAoADQAEAPz/BAARAA4AAQACABAADwAJABUAIAAgAB0AGQAXABYAFgAPAAoABgAGAAkACQAMABgAGgAPAA8ADwAIAAYAEAAUABQAGAAVAA0AAgD+/wIA///z//b/AAD/////BAAAAPj/9P/x//L/+//9//r/+P/z//T/AQAGAAcAEQAZABQAEwAQAAQAAgARABUACAAAAAcACAD9//v/AgAAAPf/8P/n/+D/5P/v//P/8P/t//L/8//q/+b/7v/0//P/9v/z/+z/8P/5//j/9f/5////BQAMAA0ACgAIAA4AEwAQABEAFwAUAAgAAwACAP7/+//8/wEACAAIAAgADQAPAAYA/////wQABQD8//f///8FAAIABQAFAPz/AAANAA4ABwALABEAFQAcABkACwAFABUAJgAkABUADQALAA4AFwAZAA4AAgABAAIA/v/2//f/CAANAAYACQAJAP////8CAPD/5P/x//f/8f/4/wMA/v/6//z//f/9//v/9//1//n/+v/5//P/8f/2//v//v/7//T/8P/5////AAABAAQABgAEAPz/9f/4//r/8v/s/+z/7f/0//r/9P/s//P///8EAAMA+v/y//X/9f/v//P/AgAEAPf/9v8GABAACAAAAAUADQAJAAIA+v/v/+f/8P/+/wMAAwADAAMAAAABAAUADgAUAAwAAgD8//j/9v/+/wgACQAEAP7/9//y//P//f8LABIADQAGAAYACAAIAAwAFAAaABUABgD1//H//f8PABUAEgAQABAADwAHAPv/9v/9/wIAAgAHABAAFgAWABEADAAMAAwAEAAUAA0AAwAGAA0ABwD8//f/9//7/wIABQAEAAMAAgAEAAUAAQD5//r/AgADAPr/8//2//b/7//r/+z/8P/0//L/8P/3//r/8v/4/wcACQADAAEA///6//7//v/1//T/+f/y/+j/6f/w//f/AQAHAAgADgAWABYAFAAQAAIA+/8EAAcAAAD///7/9//3//T/5//s/wMABgD//wMACQAFAP/////+//v/+P/6//3//v/9////AgD+//P/5//g/97/4//r/+3/6//w//z//P/5////AQAAAAIAAgD9//r/9f/y//T/+P/5//3//f/5//v//f/z/+7/9v/9//7/AQAGAAcACgAMAAgABgAEAAAA+f/x/+3/9f8CAAQA/v/9//v/8v/y//7/CAANAAsAAAD3//v/AAD////////9//7/+//z//D/8//2//r/AgABAPv//P8AAPv/9f/5/wEABgALAA4ABgD9//z//f/9/wAAAgAEAAQA/P/1//f/9f/y//b/+v/4//X/9f/1//f/+P/3//f/+f8AAAUA///1//X/+//7//P/5v/h/+r/8f/v//L/+f///wIA+P/o/+L/5f/q//D/9f/4//v/+//1//n/AQABAAEAAQD6//f/+//0/+n/6//v/+7/8//8/wQACwAPAA4AEQAQAAkABwAFAPz/+/8JABIADgAGAAMA//8CAAoAEAARABMADAD6//P/AAARABkAGwAWABAADAANABIAFAASAA8AFQAcABsAEwATABkAEwAFAP//BgAMAAwABQD//wMACgAPABcAIAAeABkAFwAQAA4AFAAUAA4ADAAQABIAFgAUAA8AEAAXABcADwAIAA4AFwAYABIAEAAKAAMAAQACAAQACQAKAAMA9//s/+z/8//3//T/8v/x//P//P8BAAAAAgAGAAUAAgD+////AAD9//r//P/+/wEABAABAPz/AAACAAEAAwAEAAEAAQAAAP3//v8CAAIA/v/8//z////+//v//v8EAP//+v///wIA/f/7//3//v////7//f8BAAUAAwD/////AAD+//3///////3//f///wEAAwAEAAQAAgD9//3/AAD///v/+//+/wAAAQABAAAAAAD//wAAAwACAAEA/v/7//3/AQABAAEABQABAPr//v8FAAAA/v8BAAAAAAABAAAAAQADAAIAAAD///z//f8DAAEA/f///wAA//8AAAIA///9////AgABAAAAAQAAAP7/AQAEAAAA/f8AAAEAAAACAAEA/v/9/wAAAQABAP7/AAADAAMAAQAAAAEAAAABAAEAAAABAAIAAgAAAP//AAACAAMAAwAEAAAA/v8DAAQAAAD+/wAAAQD///3//P8BAAUAAwAAAP//AQAAAAAA////////AgACAAAA/v/+/wEAAgADAP///v///wAA/f/+/wEAAwACAP///v////7//v////////8BAAEA///9////AQABAP///v8AAP//AAACAAEAAAADAAEA/v8AAAIAAQD+////AQADAAEA/v8BAAIAAQACAAIAAAABAAMAAQAAAAEAAQABAAIAAAD+//7//v///wAAAgACAAEA//8AAAIAAQAAAAEAAgABAP////8DAAMAAAABAAMAAgACAAIAAQABAAIAAQAAAP//AQABAAEAAQAAAAAAAgADAAIAAAD///7//v//////AQAAAP////8AAAAA/f/+/wAA/////wEAAAD+////AQABAAAA////////AAABAP///f/+/wAAAQABAAAAAQABAAEAAAAAAAEA//8AAAAA///+//7/AAABAAIAAQD//wAAAAAAAAAAAAACAAEA/////wAA//8AAAIAAAD/////AAACAAIAAAD+///////+//7//////wEAAAAAAAAAAAABAAIAAAAAAAIAAgADAAIAAAABAAEA///+////////////AAAAAP////8AAAEA//8AAP////8AAAAA/////wEAAQAAAAEAAAD//wAAAAD//////v/9/wAAAQD/////AAABAAEA//8AAAAAAAAAAP///////wEAAAD//wAAAQABAAEAAAAAAAAA/////wAAAAAAAAAAAAD+////AAABAAAA//8AAAAAAAAAAAAAAAAAAAAAAAD//wAA//8AAAAA/////wAAAAAAAAEAAgABAAAA///+////AAAAAP///////wAA/////////////wAAAAD//wAAAAAAAP////8BAAEAAAD//wAAAQAAAP//AAAAAP//AAAAAAEAAQABAAEAAQABAAEAAQAAAP//AAAAAAAAAQABAAAAAAAAAAAAAQD/////AAABAAAAAQABAAEAAQAAAP////8BAAEA//8AAP///////wAAAQABAAAAAQABAAEAAQABAP//AAAAAAEAAAAAAAAAAQABAAAAAAAAAAAAAAD//////////wAAAAAAAAAA/////wAAAAD//wAAAAABAAAAAAAAAP//AAAAAAEAAAABAAEAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAAEAAQD//wAAAAD/////AAABAAAA////////AAABAAEAAAD//wAAAQAAAP////8AAP////8AAAAAAAAAAAEAAAD//wAAAQAAAP///////wAAAAAAAAEAAAAAAAAAAAABAAEAAQAAAAAAAAAAAAEAAQAAAAAAAAAAAAAAAAAAAAEAAQAAAAAA/////wAAAAAAAP//AAAAAAAAAAD//wAAAAAAAAAAAAAAAAAA////////AAAAAAEAAQABAAEAAQABAAEAAAAAAAAAAAABAAAAAAAAAAAAAQAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAA//8AAP///////wAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAP//AAAAAP//AAD/////AAAAAAAAAAAAAAAAAAD//wAAAAAAAP////8AAAAAAAD//wAAAAD/////AAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAABAAAAAAD//wAAAAD//wAAAQABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AAAAAP////8AAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////AQAAAAAAAAAAAAAAAAAAAAAAAAAAAP////8BAAEAAAAAAAAAAQABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" type=\"audio/x-wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\n\n```python\nimport json\nimport ast\nimport nemo\nimport nemo.collections.asr as nemo_asr\n```\n\n\n```python\nvalidated = pd.read_csv('/content/small/CV_unpacked/cv-corpus-6.1-2020-12-11/en/validated.tsv',sep='\\t')\ncurated_wav = os.listdir('/content/small/validated/wav')\n```\n\n\n```python\nnemo_asr.models.EncDecCTCModelBPE.list_available_models()\n```\n\n\n```python\nquartznet = nemo_asr.models.EncDecCTCModel.from_pretrained(model_name=\"QuartzNet15x5Base-En\")\n```\n\n\n```python\nasr_model = nemo_asr.models.EncDecCTCModelBPE.from_pretrained(model_name=\"stt_en_conformer_ctc_small_ls\")\n```\n\n    [NeMo I 2021-08-04 13:19:05 cloud:56] Found existing object /root/.cache/torch/NeMo/NeMo_1.1.0/stt_en_conformer_ctc_small_ls/cf1b6bbcc08433257c12442c92b9996a/stt_en_conformer_ctc_small_ls.nemo.\n    [NeMo I 2021-08-04 13:19:05 cloud:62] Re-using file from: /root/.cache/torch/NeMo/NeMo_1.1.0/stt_en_conformer_ctc_small_ls/cf1b6bbcc08433257c12442c92b9996a/stt_en_conformer_ctc_small_ls.nemo\n    [NeMo I 2021-08-04 13:19:05 common:676] Instantiating model from pre-trained checkpoint\n    [NeMo I 2021-08-04 13:19:06 mixins:149] Tokenizer SentencePieceTokenizer initialized with 128 tokens\n\n\n    [NeMo W 2021-08-04 13:19:06 modelPT:139] If you intend to do training or fine-tuning, please call the ModelPT.setup_training_data() method and provide a valid configuration file to setup the train data loader.\n        Train config : \n        manifest_filepath: /data/Librispeech_SP_Tarred/tarred_audio_manifest.json\n        sample_rate: 16000\n        batch_size: 32\n        shuffle: true\n        num_workers: 8\n        pin_memory: true\n        use_start_end_token: false\n        trim_silence: false\n        max_duration: 16.7\n        min_duration: 0.1\n        shuffle_n: 2048\n        is_tarred: true\n        tarred_audio_filepaths: /data/Librispeech_SP_Tarred/audio__OP_0..511_CL_.tar\n        \n    [NeMo W 2021-08-04 13:19:06 modelPT:146] If you intend to do validation, please call the ModelPT.setup_validation_data() or ModelPT.setup_multiple_validation_data() method and provide a valid configuration file to setup the validation data loader(s). \n        Validation config : \n        manifest_filepath:\n        - /manifests/librispeech/librivox-dev-other.json\n        - /manifests/librispeech/librivox-dev-clean.json\n        - /manifests/librispeech/librivox-test-other.json\n        - /manifests/librispeech/librivox-test-clean.json\n        sample_rate: 16000\n        batch_size: 32\n        shuffle: false\n        num_workers: 8\n        pin_memory: true\n        use_start_end_token: false\n        is_tarred: false\n        tarred_audio_filepaths: /data/LibriSpeech/eval__OP_0..1023_CL_.tar\n        \n    [NeMo W 2021-08-04 13:19:06 modelPT:153] Please call the ModelPT.setup_test_data() or ModelPT.setup_multiple_test_data() method and provide a valid configuration file to setup the test data loader(s).\n        Test config : \n        manifest_filepath:\n        - /manifests/librispeech/librivox-dev-other.json\n        - /manifests/librispeech/librivox-dev-clean.json\n        - /manifests/librispeech/librivox-test-other.json\n        - /manifests/librispeech/librivox-test-clean.json\n        sample_rate: 16000\n        batch_size: 32\n        shuffle: false\n        num_workers: 8\n        pin_memory: true\n        use_start_end_token: false\n        is_tarred: false\n        tarred_audio_filepaths: /data/LibriSpeech/eval__OP_0..1023_CL_.tar\n        \n\n\n    [NeMo I 2021-08-04 13:19:06 features:252] PADDING: 0\n    [NeMo I 2021-08-04 13:19:06 features:269] STFT using torch\n    [NeMo I 2021-08-04 13:19:07 modelPT:439] Model EncDecCTCModelBPE was successfully restored from /root/.cache/torch/NeMo/NeMo_1.1.0/stt_en_conformer_ctc_small_ls/cf1b6bbcc08433257c12442c92b9996a/stt_en_conformer_ctc_small_ls.nemo.\n\n\n\n```python\nfiles = [f'/content/small/validated/wav/{a}' for a in curated_wav]\nfor fname, transcription in zip(files, quartznet.transcribe(paths2audio_files=files)):\n  print(f\"{transcription}, real: {validated.set_index('path').loc[fname.split('/')[-1].replace('wav','mp3')]['sentence']}\")\n```\n\n\n    HBox(children=(FloatProgress(value=0.0, description='Transcribing', max=8.0, style=ProgressStyle(description_w\u2026\n\n\n    \n    three armed tribesmen approached and asked what the boy and the alchemist were doing there, real: Three armed tribesmen approached, and asked what the boy and the alchemist were doing there.\n    he thought of all the married shepherds he had known, real: He thought of all the married shepherds he had known.\n    he lives at the al fayoum oasis his friend had said, real: \"He lives at the Al-Fayoum oasis,\" his friend had said.\n    it didn't bring with it the smell of the desert nor the threat of moorish invasion, real: It didn't bring with it the smell of the desert, nor the threat of Moorish invasion.\n    sadly my dream of becoming a squirrel whisperer may never happen, real: Sadly, my dream of becoming a squirrel whisperer may never happen.\n    but the merchant understood what the boy had said, real: But the merchant understood what the boy had said.\n    some of those who saw its flight say it travelled with a hissing sound, real: Some of those who saw its flight say it travelled with a hissing sound.\n    first they tried to find him on their own, real: First, they tried to find him on their own.\n    and they had understood each other perfectly well, real: And they had understood each other perfectly well.\n    the boy looked out at the horizon, real: The boy looked out at the horizon.\n    i don't know the desert that well yet, real: I don't know the desert that well yet.\n    other servants maintained the fires in the hookahs, real: Other servants maintained the fires in the hookahs.\n    he had always believed that the sheep were able to understand what he said, real: He had always believed that the sheep were able to understand what he said.\n    he must know how to deal with the snakes of the desert, real: He must know how to deal with the snakes of the desert.\n    thank you said the boy, real: \"Thank you,\" said the boy.\n    the boy was surprised, real: The boy was surprised.\n    everything in life is an omen said the englishman now closing the journal he was reading, real: \"Everything in life is an omen,\" said the Englishman, now closing the journal he was reading.\n    he took back his books and packed them away again in their bags, real: He took back his books and packed them away again in their bags.\n    the dunes are changed by the wind but the desert never changes, real: The dunes are changed by the wind, but the desert never changes.\n    or a man into the wind, real: or a man into the wind.\n    it was the first time either had touched the other, real: It was the first time either had touched the other.\n    but he had to move on, real: But he had to move on.\n    the boy turned to the hand that wrote all, real: The boy turned to the hand that wrote all.\n    he knew how to shear them and how to slaughter them, real: He knew how to shear them, and how to slaughter them.\n    the caravan moved toward the east, real: The caravan moved toward the east.\n    i'm a woman of the desert she said averting her face, real: \"I'm a woman of the desert,\" she said, averting her face.\n    because i've always heard about them the boy answered saying nothing about his dream, real: \"Because I've always heard about them,\" the boy answered, saying nothing about his dream.\n    well usually i learn more from my sheep than from books he answered, real: \"Well, usually I learn more from my sheep than from books,\" he answered.\n    they were looking only for gold his companion answered, real: \"They were looking only for gold,\" his companion answered.\n    i'm interested only in the present, real: I'm interested only in the present.\n\n\n\n```python\nfiles = [f'/content/small/validated/wav/{a}' for a in curated_wav]\nfor fname, transcription in zip(files, asr_model.transcribe(paths2audio_files=files)):\n  print(f\"{transcription}, real: {validated.set_index('path').loc[fname.split('/')[-1].replace('wav','mp3')]['sentence']}\")\n```\n\n\n    HBox(children=(FloatProgress(value=0.0, description='Transcribing', max=8.0, style=ProgressStyle(description_w\u2026\n\n\n    \n    three armed tribes been approached and asked what the boy and the alchemists were doing there, real: Three armed tribesmen approached, and asked what the boy and the alchemist were doing there.\n    he thought of all the merry shepherds he had known, real: He thought of all the married shepherds he had known.\n    he lives at the alpoyum goyces his friend had said, real: \"He lives at the Al-Fayoum oasis,\" his friend had said.\n    it didn't bring with it the smell of the desert nor the threat of maorsh invasion, real: It didn't bring with it the smell of the desert, nor the threat of Moorish invasion.\n    sadly my dream of becoming a squirrel whisperer may never happen, real: Sadly, my dream of becoming a squirrel whisperer may never happen.\n    but the merchant understood what the boy had said, real: But the merchant understood what the boy had said.\n    some of those who saw its flight said it travelled with a hissing sound, real: Some of those who saw its flight say it travelled with a hissing sound.\n    first they tried to find him on the rone, real: First, they tried to find him on their own.\n    and they had understood each other perfectly well, real: And they had understood each other perfectly well.\n    the boy looked out at the horizon, real: The boy looked out at the horizon.\n    i don't know the desert that well yet, real: I don't know the desert that well yet.\n    other servants maintain the fires in the hocaus, real: Other servants maintained the fires in the hookahs.\n    he had always believed that the sheep were able to understand what he said, real: He had always believed that the sheep were able to understand what he said.\n    he must know how to deal with the snakes of the desert, real: He must know how to deal with the snakes of the desert.\n    thank you said the boy, real: \"Thank you,\" said the boy.\n    the boy was surprised, real: The boy was surprised.\n    everything in life is an omen said the englishman now closing the journal he was reading, real: \"Everything in life is an omen,\" said the Englishman, now closing the journal he was reading.\n    he took back his books and packed them away again in their bags, real: He took back his books and packed them away again in their bags.\n    the dunes are changed by the wind but the de desert never changes, real: The dunes are changed by the wind, but the desert never changes.\n    ore a man into the wind, real: or a man into the wind.\n    it was the first time either had touched the other, real: It was the first time either had touched the other.\n    but he had to move on, real: But he had to move on.\n    the boy turned to the hand that rode all, real: The boy turned to the hand that wrote all.\n    he knew how to shear them and had a slot of them, real: He knew how to shear them, and how to slaughter them.\n    the caravan moved toward the east, real: The caravan moved toward the east.\n    i'm a woman of the desert she said averting her face, real: \"I'm a woman of the desert,\" she said, averting her face.\n    because i've always heard about them the boy answered saying nothing about his dream, real: \"Because I've always heard about them,\" the boy answered, saying nothing about his dream.\n    well usually i learn more from my sheep than from books he answered, real: \"Well, usually I learn more from my sheep than from books,\" he answered.\n    they were looking only for gold his companion answered, real: \"They were looking only for gold,\" his companion answered.\n    i interested only in the present, real: I'm interested only in the present.\n\n\n\n```python\nfrom nemo.collections.asr.metrics.wer import word_error_rate\n```\n\n\n```python\nhypothesis = asr_model.transcribe(paths2audio_files=files)\nactual =  [validated.set_index('path').loc[a.split('/')[-1].replace('wav','mp3')]['sentence'] for a in curated_wav]\n```\n\n\n    HBox(children=(FloatProgress(value=0.0, description='Transcribing', max=8.0, style=ProgressStyle(description_w\u2026\n\n\n    \n\n\n\n```python\n# clean up reference transcripts\nref = [a.replace(',',\" \").replace('\"',' ').replace('.','') for a in actual]\n```\n\n\n```python\nwer = word_error_rate(hypotheses=hypothesis, references=ref)\nprint(wer)\n```\n\n    0.16887417218543047\n\n\n\n```python\n\n```\n\n# record audio from colab\n\n\n```python\n\"\"\"\nTo write this piece of code I took inspiration/code from a lot of places.\nIt was late night, so I'm not sure how much I created or just copied o.O\nHere are some of the possible references:\nhttps://blog.addpipe.com/recording-audio-in-the-browser-using-pure-html5-and-minimal-javascript/\nhttps://stackoverflow.com/a/18650249\nhttps://hacks.mozilla.org/2014/06/easy-audio-capture-with-the-mediarecorder-api/\nhttps://air.ghost.io/recording-to-an-audio-file-using-html5-and-js/\nhttps://stackoverflow.com/a/49019356\n\"\"\"\nfrom IPython.display import HTML, Audio\nfrom google.colab.output import eval_js\nfrom base64 import b64decode\nimport numpy as np\nfrom scipy.io.wavfile import read as wav_read\nimport io\nimport ffmpeg\n\nAUDIO_HTML = \"\"\"\n\n\"\"\"\n\ndef get_audio():\n  display(HTML(AUDIO_HTML))\n  data = eval_js(\"data\")\n  binary = b64decode(data.split(',')[1])\n  \n  process = (ffmpeg\n    .input('pipe:0')\n    .output('pipe:1', format='wav')\n    .run_async(pipe_stdin=True, pipe_stdout=True, pipe_stderr=True, quiet=True, overwrite_output=True)\n  )\n  output, err = process.communicate(input=binary)\n  \n  riff_chunk_size = len(output) - 8\n  # Break up the chunk size into four bytes, held in b.\n  q = riff_chunk_size\n  b = []\n  for i in range(4):\n      q, r = divmod(q, 256)\n      b.append(r)\n\n  # Replace bytes 4:8 in proc.stdout with the actual size of the RIFF chunk.\n  riff = output[:4] + bytes(b) + output[8:]\n\n  sr, audio = wav_read(io.BytesIO(riff))\n\n  return audio, sr\n```\n\n\n```python\naudio, sr = get_audio()\n\n```\n\n\n\n\n\n\n", "meta": {"hexsha": "b0292c065a41988d87204ebc51b4dd61504ddfaf", "size": 579145, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/sound_play.ipynb", "max_stars_repo_name": "stevenMevans/welsummer", "max_stars_repo_head_hexsha": "7992b4c39fea9c8c697726502434fe16cafd05c9", "max_stars_repo_licenses": ["FTL"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-15T02:24:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-15T02:24:35.000Z", "max_issues_repo_path": "notebooks/sound_play.ipynb", "max_issues_repo_name": "stevenMevans/welsummer", "max_issues_repo_head_hexsha": "7992b4c39fea9c8c697726502434fe16cafd05c9", "max_issues_repo_licenses": ["FTL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/sound_play.ipynb", "max_forks_repo_name": "stevenMevans/welsummer", "max_forks_repo_head_hexsha": "7992b4c39fea9c8c697726502434fe16cafd05c9", "max_forks_repo_licenses": ["FTL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 251.3650173611, "max_line_length": 467144, "alphanum_fraction": 0.8005110983, "converted": true, "num_tokens": 345248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15405756269148543, "lm_q2_score": 0.04672496177877961, "lm_q1q2_score": 0.007198333728491601}}
{"text": "```python\n!pip install pyannote.metrics\n!pip install torchaudio\n```\n\n    Collecting pyannote.metrics\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/76/44/39e79594474eb99a23b26cb0104d78f6f20e4f8de3a26d67f24d2ea9ef28/pyannote.metrics-3.0.1-py3-none-any.whl (49kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 2.7MB/s \n    \u001b[?25hCollecting pyannote.core>=4.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/ba/09/64e64cedccf764be513405d1ff3d3d2bbcbea60d18fb6a6d9e815aedcd79/pyannote.core-4.1-py3-none-any.whl (56kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 61kB 4.1MB/s \n    \u001b[?25hRequirement already satisfied: pandas>=0.19 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics) (1.1.5)\n    Requirement already satisfied: scipy>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics) (1.4.1)\n    Requirement already satisfied: matplotlib>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics) (3.2.2)\n    Requirement already satisfied: sympy>=1.1 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics) (1.7.1)\n    Requirement already satisfied: scikit-learn>=0.17.1 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics) (0.22.2.post1)\n    Requirement already satisfied: docopt>=0.6.2 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics) (0.6.2)\n    Requirement already satisfied: tabulate>=0.7.7 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics) (0.8.9)\n    Collecting pyannote.database>=4.0.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/f8/cb/82d8035dbc3dc9aac80b5475fcac63125fc3669e4d8d07261ee3d8507f57/pyannote.database-4.1-py3-none-any.whl (41kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 4.4MB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.10.4 in /usr/local/lib/python3.7/dist-packages (from pyannote.core>=4.1->pyannote.metrics) (1.19.5)\n    Requirement already satisfied: sortedcontainers>=2.0.4 in /usr/local/lib/python3.7/dist-packages (from pyannote.core>=4.1->pyannote.metrics) (2.3.0)\n    Collecting simplejson>=3.8.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/a8/04/377418ac1e530ce2a196b54c6552c018fdf1fe776718053efb1f216bffcd/simplejson-3.17.2-cp37-cp37m-manylinux2010_x86_64.whl (128kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 133kB 8.7MB/s \n    \u001b[?25hRequirement already satisfied: typing-extensions>=3.7.4.1 in /usr/local/lib/python3.7/dist-packages (from pyannote.core>=4.1->pyannote.metrics) (3.7.4.3)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.19->pyannote.metrics) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.19->pyannote.metrics) (2.8.1)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.0.0->pyannote.metrics) (1.3.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.0.0->pyannote.metrics) (0.10.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.0.0->pyannote.metrics) (2.4.7)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.1->pyannote.metrics) (1.2.1)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.17.1->pyannote.metrics) (1.0.1)\n    Requirement already satisfied: pyYAML>=3.12 in /usr/local/lib/python3.7/dist-packages (from pyannote.database>=4.0.1->pyannote.metrics) (3.13)\n    Collecting typer[all]>=0.2.1\n      Downloading https://files.pythonhosted.org/packages/90/34/d138832f6945432c638f32137e6c79a3b682f06a63c488dcfaca6b166c64/typer-0.3.2-py3-none-any.whl\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas>=0.19->pyannote.metrics) (1.15.0)\n    Requirement already satisfied: click<7.2.0,>=7.1.1 in /usr/local/lib/python3.7/dist-packages (from typer[all]>=0.2.1->pyannote.database>=4.0.1->pyannote.metrics) (7.1.2)\n    Collecting colorama<0.5.0,>=0.4.3; extra == \"all\"\n      Downloading https://files.pythonhosted.org/packages/44/98/5b86278fbbf250d239ae0ecb724f8572af1c91f4a11edf4d36a206189440/colorama-0.4.4-py2.py3-none-any.whl\n    Collecting shellingham<2.0.0,>=1.3.0; extra == \"all\"\n      Downloading https://files.pythonhosted.org/packages/76/94/7a764d57d0f46534e0022e651da6547bc5cfe7b6372e7e0ed1dde6f5cb67/shellingham-1.4.0-py2.py3-none-any.whl\n    Installing collected packages: simplejson, pyannote.core, colorama, shellingham, typer, pyannote.database, pyannote.metrics\n    Successfully installed colorama-0.4.4 pyannote.core-4.1 pyannote.database-4.1 pyannote.metrics-3.0.1 shellingham-1.4.0 simplejson-3.17.2 typer-0.3.2\n    Collecting torchaudio\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/aa/55/01ad9244bcd595e39cea5ce30726a7fe02fd963d07daeb136bfe7e23f0a5/torchaudio-0.8.1-cp37-cp37m-manylinux1_x86_64.whl (1.9MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.9MB 5.1MB/s \n    \u001b[?25hRequirement already satisfied: torch==1.8.1 in /usr/local/lib/python3.7/dist-packages (from torchaudio) (1.8.1+cu101)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from torch==1.8.1->torchaudio) (1.19.5)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch==1.8.1->torchaudio) (3.7.4.3)\n    Installing collected packages: torchaudio\n    Successfully installed torchaudio-0.8.1\n\n\n\n```python\n# load_data.py \nimport numpy as np\nimport pandas as pd\nimport IPython.display as ipd\nimport soundfile as sf\n\n%load_ext autoreload\n%autoreload 2\n\n# ! git clone https://github.com/yistLin/dvector.git\n%cd dvector\n\nfrom google.colab import drive\ndrive.mount('/content/drive')\nDATA_BASE_DIR = \"/content/drive/MyDrive\"\n```\n\n    [Errno 2] No such file or directory: 'dvector'\n    /content\n    Mounted at /content/drive\n\n\n\n```python\nimport glob\nfrom scipy.io import wavfile\nfrom pyannote.database.util import load_rttm\n\nclass DataLoader():\n    \"\"\"docstring for DataLoader\"\"\"\n    def __init__(self, audio_folder, labels_folder, names_only=False):\n        # Audio files are assumed to have .wav extension,\n        # Label files are assumed to have .rttm extension\n        self.audio_files = sorted(glob.glob(audio_folder + \"/*.wav\"))\n        self.label_files = sorted(glob.glob(labels_folder + \"/*.rttm\"))\n        self.names_only = names_only\n\n        assert len(self.audio_files) == len(self.label_files)\n    \n\n    def __len__(self):\n        return len(self.label_files)\n\n\n    def __getitem__(self, idx):\n        # Extract labels from rttm file\n        label_dict = load_rttm(self.label_files[idx])\n        label = list(label_dict.values())\n        label = label[0]\n\n        if self.names_only:\n          return (self.audio_files[idx], label)\n\n        # Extract audio and sample rate from wav file\n        samplerate, wav_data = wavfile.read(self.audio_files[idx])\n\n        return ((samplerate, wav_data), label)\n        \nfile_loader = DataLoader(audio_folder = f\"{DATA_BASE_DIR}/voxconverse_dev_wav\", labels_folder = f\"{DATA_BASE_DIR}/voxconverse_dev_labels/dev\", names_only=True)\n```\n\n## Trying to split\n\n\n```python\n## Mel-filterbank\nmel_window_length = 25  # In milliseconds\nmel_window_step = 10    # In milliseconds\nmel_n_channels = 40\n\n## Audio\nsampling_rate = 16000\n# Number of spectrogram frames in a partial utterance\npartials_n_frames = 40     # 400 ms\n```\n\n\n```python\ndef compute_partial_slices(n_samples: int, rate, min_coverage):\n        \"\"\"\n        Computes where to split an utterance waveform and its corresponding mel spectrogram to\n        obtain partial utterances of <partials_n_frames> each. Both the waveform and the\n        mel spectrogram slices are returned, so as to make each partial utterance waveform\n        correspond to its spectrogram.\n        The returned ranges may be indexing further than the length of the waveform. It is\n        recommended that you pad the waveform with zeros up to wav_slices[-1].stop.\n        :param n_samples: the number of samples in the waveform\n        :param rate: how many partial utterances should occur per second. Partial utterances must\n        cover the span of the entire utterance, thus the rate should not be lower than the inverse\n        of the duration of a partial utterance. By default, partial utterances are 1.6s long and\n        the minimum rate is thus 0.625.\n        :param min_coverage: when reaching the last partial utterance, it may or may not have\n        enough frames. If at least <min_pad_coverage> of <partials_n_frames> are present,\n        then the last partial utterance will be considered by zero-padding the audio. Otherwise,\n        it will be discarded. If there aren't enough frames for one partial utterance,\n        this parameter is ignored so that the function always returns at least one slice.\n        :return: the waveform slices and mel spectrogram slices as lists of array slices. Index\n        respectively the waveform and the mel spectrogram with these slices to obtain the partial\n        utterances.\n        \"\"\"\n        assert 0 < min_coverage <= 1\n\n        # Compute how many frames separate two partial utterances\n        samples_per_frame = int((sampling_rate * mel_window_step / 1000))\n        n_frames = int(np.ceil((n_samples + 1) / samples_per_frame))\n        frame_step = int(np.round((sampling_rate / rate) / samples_per_frame))\n        assert 0 < frame_step, \"The rate is too high\"\n        assert frame_step <= partials_n_frames, \"The rate is too low, it should be %f at least\" % \\\n            (sampling_rate / (samples_per_frame * partials_n_frames))\n\n        # Compute the slices\n        wav_slices, mel_slices = [], []\n        steps = max(1, n_frames - partials_n_frames + frame_step + 1)\n        for i in range(0, steps, frame_step):\n            mel_range = np.array([i, i + partials_n_frames])\n            wav_range = mel_range * samples_per_frame\n            mel_slices.append(slice(*mel_range))\n            wav_slices.append(slice(*wav_range))\n\n        # Evaluate whether extra padding is warranted or not\n        last_wav_range = wav_slices[-1]\n        coverage = (n_samples - last_wav_range.start) / (last_wav_range.stop - last_wav_range.start)\n        if coverage < min_coverage and len(mel_slices) > 1:\n            mel_slices = mel_slices[:-1]\n            wav_slices = wav_slices[:-1]\n\n        return wav_slices, mel_slices\n```\n\n\n```python\nimport torch\nimport torchaudio\n\nwav2mel = torch.jit.load(\"wav2mel.pt\")\ndvector = torch.jit.load(\"dvector.pt\").eval()\n\nwav_file_name, reference = file_loader[1]\nwav_tensor, sample_rate = torchaudio.load(wav_file_name)\nmel_tensor = wav2mel(wav_tensor, sample_rate)  # shape: (frames, mel_dim)\nemb_tensor = dvector.embed_utterance(mel_tensor)  # shape: (emb_dim)\n```\n\n\n```python\nprint(mel_tensor.shape)\nprint(emb_tensor.shape)\n```\n\n    torch.Size([10201, 40])\n    torch.Size([256])\n\n\n## Loading model\n\n\n```python\n% cd /content\n```\n\n    /content\n\n\n\n```python\nimport torch\nimport torchaudio\n\n# from data.wav2mel import Wav2Mel\ntorchaudio.set_audio_backend(\"sox_io\")\n\n# wav2mel = Wav2Mel()\n# wav2mel = torch.jit.script(wav2mel)\n# wav2mel.save(\"wav2mel.pt\")\n# wav2mel = torch.jit.load(\"log_melspectrogram.pt\")\ndvector = torch.jit.load(\"dvector.pt\").eval()\n\n# audio_file_name, reference = file_loader[1]\n\n# wav_tensor, sample_rate = torchaudio.load(audio_file_name)\n# mel_tensor = wav2mel(wav_tensor, sample_rate)  # shape: (frames, mel_dim)\n# emb_tensor = dvector.embed_utterance(mel_tensor)  # shape: (emb_dim)a\n# emb_tensor.shape\n```\n\n\n```python\n# wav_tensor.shape, mel_tensor.shape, emb_tensor.shape\n```\n\n\n```python\nimport os\nif os.path.exists(\"/content/Speaker-Diarization-System\"):\n   % cd /content/Speaker-Diarization-System\n   ! git pull \nelse:\n  % cd /content\n  ! git clone https://gitlab.com/vaithak/Speaker-Diarization-System.git\n  % cd /content/Speaker-Diarization-System\n\n!pip install -r requirements.txt\n```\n\n    /content/Speaker-Diarization-System\n    Already up to date.\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 1)) (1.19.5)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 2)) (3.2.2)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 3)) (1.1.5)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 4)) (1.4.1)\n    Requirement already satisfied: pyannote.metrics in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 5)) (3.0.1)\n    Collecting resemblyzer\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/e0/21/f0a22ee4afd9e5d9790b04329accdb71d2cf89ffaf5bb0611fb37cd91782/Resemblyzer-0.1.1.dev0-py3-none-any.whl (15.7MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 15.7MB 254kB/s \n    \u001b[?25hCollecting spectralcluster\n      Downloading https://files.pythonhosted.org/packages/24/a7/12c567ed32165ccaa0a40bd55384958751a2049891c109fb9a1d3996e7a0/spectralcluster-0.1.0-py3-none-any.whl\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r requirements.txt (line 2)) (1.3.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r requirements.txt (line 2)) (2.4.7)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r requirements.txt (line 2)) (2.8.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r requirements.txt (line 2)) (0.10.0)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->-r requirements.txt (line 3)) (2018.9)\n    Requirement already satisfied: sympy>=1.1 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics->-r requirements.txt (line 5)) (1.7.1)\n    Requirement already satisfied: tabulate>=0.7.7 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics->-r requirements.txt (line 5)) (0.8.9)\n    Requirement already satisfied: pyannote.database>=4.0.1 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics->-r requirements.txt (line 5)) (4.1)\n    Requirement already satisfied: docopt>=0.6.2 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics->-r requirements.txt (line 5)) (0.6.2)\n    Requirement already satisfied: scikit-learn>=0.17.1 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics->-r requirements.txt (line 5)) (0.22.2.post1)\n    Requirement already satisfied: pyannote.core>=4.1 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics->-r requirements.txt (line 5)) (4.1)\n    Requirement already satisfied: torch>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from resemblyzer->-r requirements.txt (line 6)) (1.8.1+cu101)\n    Collecting typing\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/05/d9/6eebe19d46bd05360c9a9aae822e67a80f9242aabbfc58b641b957546607/typing-3.7.4.3.tar.gz (78kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 81kB 8.2MB/s \n    \u001b[?25hRequirement already satisfied: librosa>=0.6.1 in /usr/local/lib/python3.7/dist-packages (from resemblyzer->-r requirements.txt (line 6)) (0.8.0)\n    Collecting webrtcvad>=2.0.10\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/89/34/e2de2d97f3288512b9ea56f92e7452f8207eb5a0096500badf9dfd48f5e6/webrtcvad-2.0.10.tar.gz (66kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 71kB 6.8MB/s \n    \u001b[?25hRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.1->matplotlib->-r requirements.txt (line 2)) (1.15.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.1->pyannote.metrics->-r requirements.txt (line 5)) (1.2.1)\n    Requirement already satisfied: typing-extensions>=3.7.4; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from pyannote.database>=4.0.1->pyannote.metrics->-r requirements.txt (line 5)) (3.7.4.3)\n    Requirement already satisfied: typer[all]>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from pyannote.database>=4.0.1->pyannote.metrics->-r requirements.txt (line 5)) (0.3.2)\n    Requirement already satisfied: pyYAML>=3.12 in /usr/local/lib/python3.7/dist-packages (from pyannote.database>=4.0.1->pyannote.metrics->-r requirements.txt (line 5)) (3.13)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.17.1->pyannote.metrics->-r requirements.txt (line 5)) (1.0.1)\n    Requirement already satisfied: simplejson>=3.8.1 in /usr/local/lib/python3.7/dist-packages (from pyannote.core>=4.1->pyannote.metrics->-r requirements.txt (line 5)) (3.17.2)\n    Requirement already satisfied: sortedcontainers>=2.0.4 in /usr/local/lib/python3.7/dist-packages (from pyannote.core>=4.1->pyannote.metrics->-r requirements.txt (line 5)) (2.3.0)\n    Requirement already satisfied: audioread>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from librosa>=0.6.1->resemblyzer->-r requirements.txt (line 6)) (2.1.9)\n    Requirement already satisfied: soundfile>=0.9.0 in /usr/local/lib/python3.7/dist-packages (from librosa>=0.6.1->resemblyzer->-r requirements.txt (line 6)) (0.10.3.post1)\n    Requirement already satisfied: decorator>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from librosa>=0.6.1->resemblyzer->-r requirements.txt (line 6)) (4.4.2)\n    Requirement already satisfied: resampy>=0.2.2 in /usr/local/lib/python3.7/dist-packages (from librosa>=0.6.1->resemblyzer->-r requirements.txt (line 6)) (0.2.2)\n    Requirement already satisfied: pooch>=1.0 in /usr/local/lib/python3.7/dist-packages (from librosa>=0.6.1->resemblyzer->-r requirements.txt (line 6)) (1.3.0)\n    Requirement already satisfied: numba>=0.43.0 in /usr/local/lib/python3.7/dist-packages (from librosa>=0.6.1->resemblyzer->-r requirements.txt (line 6)) (0.51.2)\n    Requirement already satisfied: click<7.2.0,>=7.1.1 in /usr/local/lib/python3.7/dist-packages (from typer[all]>=0.2.1->pyannote.database>=4.0.1->pyannote.metrics->-r requirements.txt (line 5)) (7.1.2)\n    Requirement already satisfied: colorama<0.5.0,>=0.4.3; extra == \"all\" in /usr/local/lib/python3.7/dist-packages (from typer[all]>=0.2.1->pyannote.database>=4.0.1->pyannote.metrics->-r requirements.txt (line 5)) (0.4.4)\n    Requirement already satisfied: shellingham<2.0.0,>=1.3.0; extra == \"all\" in /usr/local/lib/python3.7/dist-packages (from typer[all]>=0.2.1->pyannote.database>=4.0.1->pyannote.metrics->-r requirements.txt (line 5)) (1.4.0)\n    Requirement already satisfied: cffi>=1.0 in /usr/local/lib/python3.7/dist-packages (from soundfile>=0.9.0->librosa>=0.6.1->resemblyzer->-r requirements.txt (line 6)) (1.14.5)\n    Requirement already satisfied: appdirs in /usr/local/lib/python3.7/dist-packages (from pooch>=1.0->librosa>=0.6.1->resemblyzer->-r requirements.txt (line 6)) (1.4.4)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from pooch>=1.0->librosa>=0.6.1->resemblyzer->-r requirements.txt (line 6)) (20.9)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pooch>=1.0->librosa>=0.6.1->resemblyzer->-r requirements.txt (line 6)) (2.23.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from numba>=0.43.0->librosa>=0.6.1->resemblyzer->-r requirements.txt (line 6)) (56.1.0)\n    Requirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba>=0.43.0->librosa>=0.6.1->resemblyzer->-r requirements.txt (line 6)) (0.34.0)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.0->soundfile>=0.9.0->librosa>=0.6.1->resemblyzer->-r requirements.txt (line 6)) (2.20)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pooch>=1.0->librosa>=0.6.1->resemblyzer->-r requirements.txt (line 6)) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pooch>=1.0->librosa>=0.6.1->resemblyzer->-r requirements.txt (line 6)) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pooch>=1.0->librosa>=0.6.1->resemblyzer->-r requirements.txt (line 6)) (2020.12.5)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pooch>=1.0->librosa>=0.6.1->resemblyzer->-r requirements.txt (line 6)) (3.0.4)\n    Building wheels for collected packages: typing, webrtcvad\n      Building wheel for typing (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for typing: filename=typing-3.7.4.3-cp37-none-any.whl size=26308 sha256=e1895b732b00493d7c1529c501589bbcb8fa5a670fceed91c0eb0dc5c6674698\n      Stored in directory: /root/.cache/pip/wheels/2d/04/41/8e1836e79581989c22eebac3f4e70aaac9af07b0908da173be\n      Building wheel for webrtcvad (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for webrtcvad: filename=webrtcvad-2.0.10-cp37-cp37m-linux_x86_64.whl size=72295 sha256=e5172e95daec0131758c3346c60407df183710942c1cc1a5183604d97b4671e6\n      Stored in directory: /root/.cache/pip/wheels/44/2a/18/bd1aec41cac7c3051fe95d92a6ed446122ea31dc713c432fa1\n    Successfully built typing webrtcvad\n    Installing collected packages: typing, webrtcvad, resemblyzer, spectralcluster\n    Successfully installed resemblyzer-0.1.1.dev0 spectralcluster-0.1.0 typing-3.7.4.3 webrtcvad-2.0.10\n\n\n\n\n\n```python\nls\n```\n\n    \u001b[0m\u001b[01;34mClustering\u001b[0m/  \u001b[01;34mEmbedding\u001b[0m/  __init__.py  model.model     README.md         \u001b[01;34mUtils\u001b[0m/\n    \u001b[01;34mconfig\u001b[0m/      hparam.py   LICENSE      \u001b[01;34mPreprocessing\u001b[0m/  requirements.txt\n\n\n\n```python\n# !pip install resemblyzer\n# !pip install spectralcluster\nfrom Utils import DataLoader\nfrom Preprocessing import VAD_chunk\nfrom Clustering import SpectralClustering\nfrom Embedding import concat_segs, get_STFTs, align_embeddings, SpeechEmbedder\nimport torch\n```\n\n\n```python\ndef create_labelling(labels, continuos_times, seg_length_ms = 0.4):\n    labelling = []\n    \n    time_idx = 0\n    start_time = continuos_times[0][0]\n    end_time = start_time + seg_length_ms\n\n    for i in range(len(labels)):\n        if end_time >= continuos_times[time_idx][1]:\n            temp = [str(labels[i]), start_time, continuos_times[time_idx][1]]\n            labelling.append(tuple(temp))\n            time_idx += 1\n            start_time = continuos_times[time_idx][0]\n            end_time = start_time + seg_length_ms\n\n        elif i==len(labels)-1:\n            temp = [str(labels[i]), start_time, end_time]\n            labelling.append(tuple(temp))\n\n        elif labels[i] != labels[i+1]:\n            temp = [str(labels[i]), start_time, end_time]\n            labelling.append(tuple(temp))\n            start_time = end_time\n            end_time = start_time + seg_length_ms\n\n        else:\n            end_time += seg_length_ms\n\n    return labelling\n```\n\n\n```python\n# from sklearn.cluster import SpectralClustering, KMeans\nfrom Clustering import SpectralClustering\n\ndef get_hypothesis(audio_file_name, embedder_net):\n  times, segs = VAD_chunk(2, audio_file_name)\n  concat_seg, continuos_times = concat_segs(times, segs)\n  \n  STFT_frames = get_STFTs(concat_seg)\n  STFT_frames = np.stack(STFT_frames, axis=2)\n  STFT_frames = torch.tensor(np.transpose(STFT_frames, axes=(2,1,0)))\n  print(STFT_frames.shape)\n  embeddings = []\n  for STFT_frame in STFT_frames:\n    embeddings.append((dvector.embed_utterance(STFT_frame.reshape(-1,40))).detach().numpy())\n  print(len(embeddings), embeddings[0].shape)\n  # embeddings = torch.tensor(embeddings)\n  # embeddings = embedder_net(STFT_frames)\n  aligned_embeddings = align_embeddings(embeddings)\n\n  # Ger cluster ids for embedding\n  clusterer = SpectralClustering(\n    min_clusters=4,\n    max_clusters=20,\n    p_percentile=0.90,\n    gaussian_blur_sigma=1\n  )\n  # labels = clusterer.predict(aligned_embeddings)\n  labels = clusterer.predict(aligned_embeddings)\n\n  # Get labelling from cluster assignment\n  labelling = create_labelling(labels, continuos_times)\n  return labelling, labels, aligned_embeddings\n```\n\n\n```python\n(wav_data), reference = file_loader[2]\nlabelling, labels, embeddings = get_hypothesis(wav_data, 16000)\n```\n\n    torch.Size([5513, 24, 40])\n    5513 (256,)\n\n\n\n```python\nlen(labelling), len(labels), len(embeddings)\n```\n\n\n\n\n    (368, 1651, 1651)\n\n\n\n\n```python\nfrom __future__ import print_function\nimport time\nimport numpy as np\nimport pandas as pd\n# from sklearn.datasets import fetch_mldata\nfrom sklearn.decomposition import PCA\nfrom sklearn.manifold import TSNE\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport seaborn as sns\n\ntsne = TSNE(n_components=2, verbose=1, perplexity=40, n_iter=300)\ntsne_results = tsne.fit_transform(embeddings)\n\ndf = pd.DataFrame(tsne_results, columns = {\"one\", \"two\"})\ndf[\"y\"] = (labels)\ndf.head()\n```\n\n    [t-SNE] Computing 121 nearest neighbors...\n    [t-SNE] Indexed 1651 samples in 0.032s...\n    [t-SNE] Computed neighbors for 1651 samples in 1.532s...\n    [t-SNE] Computed conditional probabilities for sample 1000 / 1651\n    [t-SNE] Computed conditional probabilities for sample 1651 / 1651\n    [t-SNE] Mean sigma: 0.184096\n    [t-SNE] KL divergence after 250 iterations with early exaggeration: 69.869026\n    [t-SNE] KL divergence after 300 iterations: 1.771355\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>two</th>\n      <th>one</th>\n      <th>y</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>5.514346</td>\n      <td>-3.630972</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>14.042770</td>\n      <td>6.848162</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>9.613286</td>\n      <td>-3.144570</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>11.382989</td>\n      <td>-5.070907</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>6.550267</td>\n      <td>-5.768169</td>\n      <td>2</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nnp.unique(labels)\n```\n\n\n\n\n    array([0, 1, 2, 3], dtype=int32)\n\n\n\n\n```python\n# df_subset['tsne-2d-one'] = tsne_results[:,0]\n# df_subset['tsne-2d-two'] = tsne_results[:,1]\n\nplt.figure(figsize=(16,10))\nsns.scatterplot(\n    x=\"one\", y=\"two\",\n    hue=\"y\",\n    palette=sns.color_palette(\"hls\", len(np.unique(labels))),\n    data=df,\n    legend=\"full\",\n    alpha=0.3\n)\n```\n\n\n```python\nfrom pyannote.core import Segment, Timeline, Annotation\nfrom pyannote.metrics.diarization import DiarizationErrorRate\nimport webrtcvad\nimport warnings\ndef Annotation_from_tuple_arr(labels_arr):\n  annotate = Annotation()\n  for label in labels_arr:\n    annotate[Segment(label[1], label[2])] = str(int(label[0]))\n  return annotate\n\nhypothesis = Annotation_from_tuple_arr(labelling)\nmetric = DiarizationErrorRate()\nabs(metric(reference, hypothesis))\n```\n\n    /usr/local/lib/python3.7/dist-packages/pyannote/metrics/utils.py:184: UserWarning: 'uem' was approximated by the union of 'reference' and 'hypothesis' extents.\n      \"'uem' was approximated by the union of 'reference' \"\n\n\n\n\n\n    0.511478674558818\n\n\n\n\n```python\nprint(reference)\n```\n\n    [ 00:00:00.040 -->  00:00:19.040] 39 spk03\n    [ 00:00:19.040 -->  00:00:19.520] 2 spk01\n    [ 00:00:20.440 -->  00:00:34.800] 40 spk03\n    [ 00:00:34.840 -->  00:01:04.840] 3 spk01\n    [ 00:01:04.840 -->  00:01:05.640] 41 spk03\n    [ 00:01:05.440 -->  00:01:07.840] 4 spk01\n    [ 00:01:07.480 -->  00:01:11.760] 42 spk03\n    [ 00:01:08.800 -->  00:01:10.720] 5 spk01\n    [ 00:01:11.720 -->  00:01:44.400] 6 spk01\n    [ 00:01:22.480 -->  00:01:22.920] 43 spk03\n    [ 00:01:30.160 -->  00:01:32.160] 45 spk03\n    [ 00:01:32.920 -->  00:01:33.360] 46 spk03\n    [ 00:01:43.520 -->  00:02:12.440] 47 spk03\n    [ 00:02:12.320 -->  00:02:27.320] 16 spk02\n    [ 00:02:20.120 -->  00:02:21.320] 48 spk03\n    [ 00:02:27.000 -->  00:02:34.160] 49 spk03\n    [ 00:02:34.320 -->  00:02:53.680] 17 spk02\n    [ 00:02:52.040 -->  00:03:03.040] 50 spk03\n    [ 00:02:57.480 -->  00:02:59.000] 18 spk02\n    [ 00:02:59.640 -->  00:03:00.440] 19 spk02\n    [ 00:03:02.520 -->  00:03:17.800] 20 spk02\n    [ 00:03:17.200 -->  00:03:21.520] 51 spk03\n    [ 00:03:20.560 -->  00:03:34.200] 21 spk02\n    [ 00:03:32.320 -->  00:03:40.800] 52 spk03\n    [ 00:03:39.360 -->  00:03:43.160] 23 spk02\n    [ 00:03:41.960 -->  00:03:42.480] 53 spk03\n    [ 00:03:42.920 -->  00:04:12.120] 54 spk03\n    [ 00:03:44.360 -->  00:03:45.560] 24 spk02\n    [ 00:04:12.320 -->  00:04:59.000] 0 spk00\n    [ 00:04:56.920 -->  00:05:06.400] 56 spk03\n    [ 00:05:06.400 -->  00:05:06.800] 11 spk00\n    [ 00:05:06.800 -->  00:06:15.080] 57 spk03\n    [ 00:06:15.080 -->  00:06:33.960] 7 spk01\n    [ 00:06:31.440 -->  00:06:32.000] 58 spk03\n    [ 00:06:32.680 -->  00:06:35.680] 59 spk03\n    [ 00:06:35.680 -->  00:06:36.680] 25 spk02\n    [ 00:06:36.640 -->  00:07:03.080] 8 spk01\n    [ 00:06:41.760 -->  00:06:42.240] 60 spk03\n    [ 00:07:01.400 -->  00:07:28.920] 61 spk03\n    [ 00:07:28.120 -->  00:07:42.440] 26 spk02\n    [ 00:07:42.160 -->  00:07:43.240] 62 spk03\n    [ 00:07:43.320 -->  00:07:44.240] 27 spk02\n    [ 00:07:43.880 -->  00:07:44.680] 63 spk03\n    [ 00:07:44.760 -->  00:07:45.520] 28 spk02\n    [ 00:07:45.200 -->  00:07:45.720] 64 spk03\n    [ 00:07:45.920 -->  00:08:03.440] 29 spk02\n    [ 00:08:03.120 -->  00:08:04.800] 65 spk03\n    [ 00:08:04.800 -->  00:08:09.240] 30 spk02\n    [ 00:08:04.920 -->  00:08:07.080] 9 spk01\n    [ 00:08:05.520 -->  00:08:07.080] 67 spk03\n    [ 00:08:09.040 -->  00:08:09.480] 68 spk03\n    [ 00:08:09.240 -->  00:08:16.800] 22 spk00\n    [ 00:08:15.240 -->  00:08:18.120] 31 spk02\n    [ 00:08:18.440 -->  00:08:19.760] 10 spk01\n    [ 00:08:19.120 -->  00:08:20.600] 69 spk03\n    [ 00:08:19.400 -->  00:08:21.080] 32 spk02\n    [ 00:08:20.600 -->  00:08:27.640] 33 spk00\n    [ 00:08:25.600 -->  00:08:31.960] 70 spk03\n    [ 00:08:30.000 -->  00:08:33.480] 44 spk00\n    [ 00:08:32.880 -->  00:08:33.640] 34 spk02\n    [ 00:08:34.960 -->  00:08:35.920] 71 spk03\n    [ 00:08:35.240 -->  00:08:59.120] 55 spk00\n    [ 00:08:44.360 -->  00:08:45.480] 72 spk03\n    [ 00:08:59.000 -->  00:09:06.080] 73 spk03\n    [ 00:09:06.360 -->  00:09:36.840] 66 spk00\n    [ 00:09:34.120 -->  00:09:34.760] 74 spk03\n    [ 00:09:34.800 -->  00:09:36.440] 12 spk01\n    [ 00:09:35.360 -->  00:09:40.760] 75 spk03\n    [ 00:09:37.600 -->  00:09:47.480] 13 spk01\n    [ 00:09:41.600 -->  00:09:42.160] 76 spk03\n    [ 00:09:44.280 -->  00:09:44.800] 78 spk03\n    [ 00:09:45.520 -->  00:09:46.280] 35 spk02\n    [ 00:09:46.040 -->  00:09:53.120] 79 spk03\n    [ 00:09:49.120 -->  00:09:49.680] 14 spk01\n    [ 00:09:52.640 -->  00:10:03.160] 15 spk01\n    [ 00:09:57.120 -->  00:09:58.120] 36 spk02\n    [ 00:10:01.200 -->  00:10:01.640] 80 spk03\n    [ 00:10:01.440 -->  00:10:01.880] 77 spk00\n    [ 00:10:02.360 -->  00:10:03.160] 81 spk03\n    [ 00:10:03.000 -->  00:10:17.640] 37 spk02\n    [ 00:10:16.360 -->  00:10:34.240] 82 spk03\n    [ 00:10:30.360 -->  00:10:30.880] 86 spk00\n    [ 00:10:34.200 -->  00:10:46.120] 38 spk02\n    [ 00:10:39.080 -->  00:10:40.320] 83 spk03\n    [ 00:10:44.280 -->  00:10:45.880] 84 spk03\n    [ 00:10:46.280 -->  00:10:56.520] 1 spk00\n    [ 00:10:54.680 -->  00:11:04.280] 85 spk03\n\n\n\n```python\nprint(hypothesis)\n```\n\n    [ 00:00:00.140 -->  00:00:03.740] _ 0\n    [ 00:00:03.740 -->  00:00:03.880] _ 1\n    [ 00:00:05.220 -->  00:00:08.820] _ 1\n    [ 00:00:08.820 -->  00:00:12.520] _ 3\n    [ 00:00:12.660 -->  00:00:13.860] _ 3\n    [ 00:00:13.860 -->  00:00:14.660] _ 1\n    [ 00:00:14.660 -->  00:00:15.060] _ 2\n    [ 00:00:15.060 -->  00:00:18.660] _ 3\n    [ 00:00:18.660 -->  00:00:19.060] _ 2\n    [ 00:00:19.060 -->  00:00:21.420] _ 3\n    [ 00:00:21.440 -->  00:00:25.040] _ 3\n    [ 00:00:25.040 -->  00:00:25.060] _ 2\n    [ 00:00:25.180 -->  00:00:25.980] _ 1\n    [ 00:00:25.980 -->  00:00:29.640] _ 3\n    [ 00:00:29.800 -->  00:00:31.800] _ 3\n    [ 00:00:31.840 -->  00:00:33.440] _ 1\n    [ 00:00:33.440 -->  00:00:34.400] _ 3\n    [ 00:00:34.700 -->  00:00:35.900] _ 3\n    [ 00:00:35.900 -->  00:00:37.500] _ 2\n    [ 00:00:37.500 -->  00:00:38.300] _ 1\n    [ 00:00:38.300 -->  00:00:39.920] _ 2\n    [ 00:00:40.420 -->  00:00:40.820] _ 2\n    [ 00:00:40.820 -->  00:00:41.080] _ 1\n    [ 00:00:41.100 -->  00:00:43.900] _ 1\n    [ 00:00:43.900 -->  00:00:45.100] _ 2\n    [ 00:00:45.100 -->  00:00:45.520] _ 1\n    [ 00:00:45.600 -->  00:00:47.600] _ 1\n    [ 00:00:47.600 -->  00:00:49.180] _ 2\n    [ 00:00:49.360 -->  00:00:50.560] _ 1\n    [ 00:00:50.560 -->  00:00:51.720] _ 2\n    [ 00:00:51.780 -->  00:00:52.980] _ 1\n    [ 00:00:52.980 -->  00:00:53.380] _ 2\n    [ 00:00:53.380 -->  00:00:53.820] _ 3\n    [ 00:00:53.900 -->  00:00:57.100] _ 1\n    [ 00:00:57.100 -->  00:00:57.900] _ 2\n    [ 00:00:57.900 -->  00:00:58.600] _ 1\n    [ 00:00:58.760 -->  00:01:03.960] _ 1\n    [ 00:01:03.960 -->  00:01:05.160] _ 2\n    [ 00:01:05.160 -->  00:01:05.420] _ 1\n    [ 00:01:05.480 -->  00:01:06.860] _ 1\n    [ 00:01:06.980 -->  00:01:07.880] _ 1\n    [ 00:01:07.960 -->  00:01:09.160] _ 2\n    [ 00:01:09.160 -->  00:01:09.960] _ 3\n    [ 00:01:09.960 -->  00:01:12.500] _ 1\n    [ 00:01:12.560 -->  00:01:14.560] _ 2\n    [ 00:01:14.560 -->  00:01:14.960] _ 1\n    [ 00:01:14.960 -->  00:01:15.760] _ 3\n    [ 00:01:15.760 -->  00:01:16.560] _ 2\n    [ 00:01:16.560 -->  00:01:16.680] _ 1\n    [ 00:01:16.740 -->  00:01:17.540] _ 1\n    [ 00:01:17.540 -->  00:01:20.340] _ 2\n    [ 00:01:20.340 -->  00:01:20.700] _ 3\n    [ 00:01:20.820 -->  00:01:23.820] _ 3\n    [ 00:01:24.860 -->  00:01:26.240] _ 3\n    [ 00:01:27.040 -->  00:01:28.180] _ 3\n    [ 00:01:28.680 -->  00:01:29.420] _ 3\n    [ 00:01:29.700 -->  00:01:32.900] _ 3\n    [ 00:01:32.900 -->  00:01:32.960] _ 2\n    [ 00:01:33.100 -->  00:01:33.900] _ 2\n    [ 00:01:33.900 -->  00:01:34.600] _ 3\n    [ 00:01:35.060 -->  00:01:37.860] _ 3\n    [ 00:01:37.860 -->  00:01:38.220] _ 2\n    [ 00:01:38.640 -->  00:01:39.440] _ 3\n    [ 00:01:39.440 -->  00:01:40.660] _ 2\n    [ 00:01:41.120 -->  00:01:42.720] _ 2\n    [ 00:01:42.720 -->  00:01:44.820] _ 3\n    [ 00:01:45.400 -->  00:01:45.800] _ 3\n    [ 00:01:45.800 -->  00:01:46.940] _ 2\n    [ 00:01:47.160 -->  00:01:47.820] _ 2\n    [ 00:01:48.160 -->  00:01:50.940] _ 2\n    [ 00:01:51.040 -->  00:01:51.840] _ 2\n    [ 00:01:51.840 -->  00:01:52.100] _ 1\n    [ 00:01:52.200 -->  00:01:52.600] _ 1\n    [ 00:01:52.600 -->  00:01:53.440] _ 2\n    [ 00:01:53.800 -->  00:01:56.760] _ 2\n    [ 00:01:56.840 -->  00:02:00.240] _ 2\n    [ 00:02:00.320 -->  00:02:02.600] _ 2\n    [ 00:02:02.940 -->  00:02:03.740] _ 1\n    [ 00:02:03.740 -->  00:02:04.440] _ 2\n    [ 00:02:05.200 -->  00:02:06.000] _ 2\n    [ 00:02:06.000 -->  00:02:07.200] _ 3\n    [ 00:02:07.200 -->  00:02:08.000] _ 2\n    [ 00:02:08.000 -->  00:02:08.300] _ 3\n    [ 00:02:08.500 -->  00:02:10.300] _ 3\n    [ 00:02:10.900 -->  00:02:11.300] _ 3\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "eeca576cae2462bc343d3298b9f7822b5d6d8af0", "size": 256447, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Basic_Diarization.ipynb", "max_stars_repo_name": "vaithak/Speaker-Diarization-System", "max_stars_repo_head_hexsha": "40956a3ee2a73218f2e1342fa30b2728e1c4bb00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-22T07:47:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T07:48:11.000Z", "max_issues_repo_path": "notebooks/Basic_Diarization.ipynb", "max_issues_repo_name": "vaithak/Speaker-Diarization-System", "max_issues_repo_head_hexsha": "40956a3ee2a73218f2e1342fa30b2728e1c4bb00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/Basic_Diarization.ipynb", "max_forks_repo_name": "vaithak/Speaker-Diarization-System", "max_forks_repo_head_hexsha": "40956a3ee2a73218f2e1342fa30b2728e1c4bb00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 223.1914708442, "max_line_length": 201934, "alphanum_fraction": 0.8711546635, "converted": true, "num_tokens": 13229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22000709974589316, "lm_q2_score": 0.03210070498082264, "lm_q1q2_score": 0.007062383002629336}}
{"text": "# Text-to-Speech\n\n\n# Installing and Importing the Dependencies\n\n\n```python\n# run the following from the terminal\n#sudo apt-get install sox libsndfile1 ffmpeg\n```\n\n\n```python\n# Installing the Dependencies\n!pip install wget unidecode\n!pip3.8 install pytorch_lightning\n```\n\n    Defaulting to user installation because normal site-packages is not writeable\n    Requirement already satisfied: wget in /home/ubuntu/.local/lib/python3.8/site-packages (3.2)\n    Requirement already satisfied: unidecode in /home/ubuntu/.local/lib/python3.8/site-packages (1.3.2)\n    Defaulting to user installation because normal site-packages is not writeable\n    Requirement already satisfied: pytorch_lightning in /home/ubuntu/.local/lib/python3.8/site-packages (1.1.5)\n    Requirement already satisfied: future>=0.17.1 in /home/ubuntu/.local/lib/python3.8/site-packages (from pytorch_lightning) (0.18.2)\n    Requirement already satisfied: torch>=1.3 in /home/ubuntu/.local/lib/python3.8/site-packages (from pytorch_lightning) (1.7.1)\n    Requirement already satisfied: tqdm>=4.41.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from pytorch_lightning) (4.62.3)\n    Requirement already satisfied: tensorboard>=2.2.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from pytorch_lightning) (2.7.0)\n    Requirement already satisfied: PyYAML>=5.1 in /home/ubuntu/.local/lib/python3.8/site-packages (from pytorch_lightning) (6.0)\n    Requirement already satisfied: fsspec[http]>=0.8.1 in /home/ubuntu/.local/lib/python3.8/site-packages (from pytorch_lightning) (2021.11.1)\n    Requirement already satisfied: numpy>=1.16.6 in /home/ubuntu/.local/lib/python3.8/site-packages (from pytorch_lightning) (1.20.3)\n    Requirement already satisfied: aiohttp in /home/ubuntu/.local/lib/python3.8/site-packages (from fsspec[http]>=0.8.1->pytorch_lightning) (3.8.1)\n    Requirement already satisfied: requests in /home/ubuntu/.local/lib/python3.8/site-packages (from fsspec[http]>=0.8.1->pytorch_lightning) (2.26.0)\n    Requirement already satisfied: grpcio>=1.24.3 in /home/ubuntu/.local/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch_lightning) (1.43.0)\n    Requirement already satisfied: absl-py>=0.4 in /home/ubuntu/.local/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch_lightning) (1.0.0)\n    Requirement already satisfied: werkzeug>=0.11.15 in /home/ubuntu/.local/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch_lightning) (2.0.2)\n    Requirement already satisfied: wheel>=0.26 in /home/ubuntu/.local/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch_lightning) (0.36.2)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /home/ubuntu/.local/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch_lightning) (0.4.6)\n    Requirement already satisfied: markdown>=2.6.8 in /home/ubuntu/.local/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch_lightning) (3.3.6)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch_lightning) (1.8.0)\n    Requirement already satisfied: protobuf>=3.6.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch_lightning) (3.17.3)\n    Requirement already satisfied: setuptools>=41.0.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch_lightning) (59.6.0)\n    Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch_lightning) (0.6.1)\n    Requirement already satisfied: google-auth<3,>=1.6.3 in /home/ubuntu/.local/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch_lightning) (2.3.3)\n    Requirement already satisfied: typing-extensions in /home/ubuntu/.local/lib/python3.8/site-packages (from torch>=1.3->pytorch_lightning) (4.0.1)\n    Requirement already satisfied: six in /usr/lib/python3/dist-packages (from absl-py>=0.4->tensorboard>=2.2.0->pytorch_lightning) (1.11.0)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /home/ubuntu/.local/lib/python3.8/site-packages (from google-auth<3,>=1.6.3->tensorboard>=2.2.0->pytorch_lightning) (4.8)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/lib/python3/dist-packages (from google-auth<3,>=1.6.3->tensorboard>=2.2.0->pytorch_lightning) (0.2.1)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from google-auth<3,>=1.6.3->tensorboard>=2.2.0->pytorch_lightning) (4.2.2)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard>=2.2.0->pytorch_lightning) (1.3.0)\n    Requirement already satisfied: importlib-metadata>=4.4 in /home/ubuntu/.local/lib/python3.8/site-packages (from markdown>=2.6.8->tensorboard>=2.2.0->pytorch_lightning) (4.9.0)\n    Requirement already satisfied: idna<4,>=2.5 in /usr/lib/python3/dist-packages (from requests->fsspec[http]>=0.8.1->pytorch_lightning) (2.6)\n    Requirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/lib/python3/dist-packages (from requests->fsspec[http]>=0.8.1->pytorch_lightning) (1.22)\n    Requirement already satisfied: charset-normalizer~=2.0.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from requests->fsspec[http]>=0.8.1->pytorch_lightning) (2.0.9)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/lib/python3/dist-packages (from requests->fsspec[http]>=0.8.1->pytorch_lightning) (2018.1.18)\n    Requirement already satisfied: aiosignal>=1.1.2 in /home/ubuntu/.local/lib/python3.8/site-packages (from aiohttp->fsspec[http]>=0.8.1->pytorch_lightning) (1.2.0)\n    Requirement already satisfied: frozenlist>=1.1.1 in /home/ubuntu/.local/lib/python3.8/site-packages (from aiohttp->fsspec[http]>=0.8.1->pytorch_lightning) (1.2.0)\n    Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /home/ubuntu/.local/lib/python3.8/site-packages (from aiohttp->fsspec[http]>=0.8.1->pytorch_lightning) (4.0.1)\n    Requirement already satisfied: yarl<2.0,>=1.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from aiohttp->fsspec[http]>=0.8.1->pytorch_lightning) (1.7.2)\n    Requirement already satisfied: multidict<7.0,>=4.5 in /home/ubuntu/.local/lib/python3.8/site-packages (from aiohttp->fsspec[http]>=0.8.1->pytorch_lightning) (5.2.0)\n    Requirement already satisfied: attrs>=17.3.0 in /usr/lib/python3/dist-packages (from aiohttp->fsspec[http]>=0.8.1->pytorch_lightning) (17.4.0)\n    Requirement already satisfied: zipp>=0.5 in /home/ubuntu/.local/lib/python3.8/site-packages (from importlib-metadata>=4.4->markdown>=2.6.8->tensorboard>=2.2.0->pytorch_lightning) (3.6.0)\n    Requirement already satisfied: oauthlib>=3.0.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard>=2.2.0->pytorch_lightning) (3.1.1)\n    Requirement already satisfied: pyasn1>=0.1.3 in /usr/lib/python3/dist-packages (from rsa<5,>=3.1.4->google-auth<3,>=1.6.3->tensorboard>=2.2.0->pytorch_lightning) (0.4.2)\n\n\n\n```python\n# Upgrading pip and cloning the NVIDIA\n!pip3.8 install --upgrade pip\n!pip3.8 install torch\nBRANCH = 'r1.0.0rc1'\n!python3.8 -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[tts]\n```\n\n    Defaulting to user installation because normal site-packages is not writeable\n    Requirement already satisfied: pip in /home/ubuntu/.local/lib/python3.8/site-packages (21.3.1)\n    Defaulting to user installation because normal site-packages is not writeable\n    Requirement already satisfied: torch in /home/ubuntu/.local/lib/python3.8/site-packages (1.7.1)\n    Requirement already satisfied: numpy in /home/ubuntu/.local/lib/python3.8/site-packages (from torch) (1.20.3)\n    Requirement already satisfied: typing-extensions in /home/ubuntu/.local/lib/python3.8/site-packages (from torch) (4.0.1)\n    Defaulting to user installation because normal site-packages is not writeable\n    Collecting nemo_toolkit[tts]\n      Cloning https://github.com/NVIDIA/NeMo.git (to revision r1.0.0rc1) to /tmp/pip-install-2uc9vwai/nemo-toolkit_6f1b61c1834f467aabb86c7f87e07660\n      Running command git clone --filter=blob:none -q https://github.com/NVIDIA/NeMo.git /tmp/pip-install-2uc9vwai/nemo-toolkit_6f1b61c1834f467aabb86c7f87e07660\n      Running command git checkout -b r1.0.0rc1 --track origin/r1.0.0rc1\n      Switched to a new branch 'r1.0.0rc1'\n      Branch 'r1.0.0rc1' set up to track remote branch 'r1.0.0rc1' from 'origin'.\n      Resolved https://github.com/NVIDIA/NeMo.git to commit 977b9a2c8bee5f0575935cde9527b9fe2b7badfe\n      Preparing metadata (setup.py) ... \u001b[?25ldone\n    \u001b[?25hRequirement already satisfied: numpy>=1.18.2 in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (1.20.3)\n    Requirement already satisfied: onnx>=1.7.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (1.10.2)\n    Requirement already satisfied: pytorch-lightning==1.1.5 in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (1.1.5)\n    Requirement already satisfied: python-dateutil in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (2.8.2)\n    Requirement already satisfied: torch<=1.7.1 in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (1.7.1)\n    Requirement already satisfied: torchvision==0.8.2 in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (0.8.2)\n    Requirement already satisfied: torchaudio==0.7.2 in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (0.7.2)\n    Requirement already satisfied: torchtext==0.8.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (0.8.0)\n    Requirement already satisfied: wget in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (3.2)\n    Requirement already satisfied: wrapt in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (1.13.3)\n    Requirement already satisfied: ruamel.yaml in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (0.17.17)\n    Requirement already satisfied: scikit-learn in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (0.24.2)\n    Requirement already satisfied: omegaconf>=2.0.5 in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (2.1.1)\n    Requirement already satisfied: hydra-core>=1.0.4 in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (1.1.1)\n    Requirement already satisfied: transformers>=4.0.1 in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (4.14.1)\n    Requirement already satisfied: sentencepiece<1.0.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (0.1.96)\n    Requirement already satisfied: webdataset>=0.1.48 in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (0.1.103)\n    Requirement already satisfied: tqdm>=4.41.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (4.62.3)\n    Requirement already satisfied: opencc in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (1.1.3)\n    Requirement already satisfied: pangu in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (4.0.6.1)\n    Requirement already satisfied: jieba in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (0.42.1)\n    Requirement already satisfied: matplotlib in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (3.5.0)\n    Requirement already satisfied: pypinyin in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (0.44.0)\n    Requirement already satisfied: attrdict in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (2.0.1)\n    Requirement already satisfied: pystoi in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (0.3.3)\n    Requirement already satisfied: pesq in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (0.0.3)\n    Requirement already satisfied: g2p_en in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (2.1.0)\n    Requirement already satisfied: braceexpand in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (0.1.7)\n    Requirement already satisfied: editdistance in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (0.6.0)\n    Requirement already satisfied: frozendict in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (2.1.1)\n    Requirement already satisfied: inflect in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (5.3.0)\n    Requirement already satisfied: kaldi-io in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (0.9.4)\n    Requirement already satisfied: librosa in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (0.8.1)\n    Requirement already satisfied: marshmallow in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (3.14.1)\n    Requirement already satisfied: packaging in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (21.0)\n    Requirement already satisfied: soundfile in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (0.10.3.post1)\n    Requirement already satisfied: sox in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (1.4.1)\n    Requirement already satisfied: torch-stft in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (0.1.4)\n    Requirement already satisfied: unidecode in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (1.3.2)\n    Requirement already satisfied: kaldi-python-io in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (1.2.2)\n    Requirement already satisfied: kaldiio in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (2.17.2)\n    Requirement already satisfied: scipy in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (1.7.1)\n    Requirement already satisfied: pandas in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (1.3.1)\n    Requirement already satisfied: pydub in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (0.25.1)\n    Requirement already satisfied: pyannote.core in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (4.3)\n    Requirement already satisfied: pyannote.metrics in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (3.1)\n    Requirement already satisfied: spectralcluster in /home/ubuntu/.local/lib/python3.8/site-packages (from nemo_toolkit[tts]) (0.2.4)\n    Requirement already satisfied: fsspec[http]>=0.8.1 in /home/ubuntu/.local/lib/python3.8/site-packages (from pytorch-lightning==1.1.5->nemo_toolkit[tts]) (2021.11.1)\n    Requirement already satisfied: tensorboard>=2.2.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from pytorch-lightning==1.1.5->nemo_toolkit[tts]) (2.7.0)\n    Requirement already satisfied: PyYAML>=5.1 in /home/ubuntu/.local/lib/python3.8/site-packages (from pytorch-lightning==1.1.5->nemo_toolkit[tts]) (6.0)\n    Requirement already satisfied: future>=0.17.1 in /home/ubuntu/.local/lib/python3.8/site-packages (from pytorch-lightning==1.1.5->nemo_toolkit[tts]) (0.18.2)\n    Requirement already satisfied: typing-extensions in /home/ubuntu/.local/lib/python3.8/site-packages (from torch<=1.7.1->nemo_toolkit[tts]) (4.0.1)\n    Requirement already satisfied: requests in /home/ubuntu/.local/lib/python3.8/site-packages (from torchtext==0.8.0->nemo_toolkit[tts]) (2.26.0)\n    Requirement already satisfied: pillow>=4.1.1 in /home/ubuntu/.local/lib/python3.8/site-packages (from torchvision==0.8.2->nemo_toolkit[tts]) (8.3.1)\n    Requirement already satisfied: antlr4-python3-runtime==4.8 in /home/ubuntu/.local/lib/python3.8/site-packages (from hydra-core>=1.0.4->nemo_toolkit[tts]) (4.8)\n    Requirement already satisfied: importlib-resources in /home/ubuntu/.local/lib/python3.8/site-packages (from hydra-core>=1.0.4->nemo_toolkit[tts]) (5.4.0)\n    Requirement already satisfied: six in /usr/lib/python3/dist-packages (from onnx>=1.7.0->nemo_toolkit[tts]) (1.11.0)\n    Requirement already satisfied: protobuf in /home/ubuntu/.local/lib/python3.8/site-packages (from onnx>=1.7.0->nemo_toolkit[tts]) (3.17.3)\n    Requirement already satisfied: tokenizers<0.11,>=0.10.1 in /home/ubuntu/.local/lib/python3.8/site-packages (from transformers>=4.0.1->nemo_toolkit[tts]) (0.10.3)\n    Requirement already satisfied: sacremoses in /home/ubuntu/.local/lib/python3.8/site-packages (from transformers>=4.0.1->nemo_toolkit[tts]) (0.0.46)\n    Requirement already satisfied: huggingface-hub<1.0,>=0.1.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from transformers>=4.0.1->nemo_toolkit[tts]) (0.2.1)\n    Requirement already satisfied: filelock in /home/ubuntu/.local/lib/python3.8/site-packages (from transformers>=4.0.1->nemo_toolkit[tts]) (3.0.12)\n    Requirement already satisfied: regex!=2019.12.17 in /home/ubuntu/.local/lib/python3.8/site-packages (from transformers>=4.0.1->nemo_toolkit[tts]) (2021.11.10)\n    Requirement already satisfied: pyparsing>=2.0.2 in /home/ubuntu/.local/lib/python3.8/site-packages (from packaging->nemo_toolkit[tts]) (2.4.7)\n    Requirement already satisfied: nltk>=3.2.4 in /home/ubuntu/.local/lib/python3.8/site-packages (from g2p_en->nemo_toolkit[tts]) (3.6.5)\n    Requirement already satisfied: distance>=0.1.3 in /home/ubuntu/.local/lib/python3.8/site-packages (from g2p_en->nemo_toolkit[tts]) (0.1.3)\n    Requirement already satisfied: numba>=0.43.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from librosa->nemo_toolkit[tts]) (0.54.0)\n    Requirement already satisfied: pooch>=1.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from librosa->nemo_toolkit[tts]) (1.4.0)\n    Requirement already satisfied: decorator>=3.0.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from librosa->nemo_toolkit[tts]) (5.0.9)\n    Requirement already satisfied: resampy>=0.2.2 in /home/ubuntu/.local/lib/python3.8/site-packages (from librosa->nemo_toolkit[tts]) (0.2.2)\n    Requirement already satisfied: joblib>=0.14 in /home/ubuntu/.local/lib/python3.8/site-packages (from librosa->nemo_toolkit[tts]) (1.0.1)\n    Requirement already satisfied: audioread>=2.0.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from librosa->nemo_toolkit[tts]) (2.1.9)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from scikit-learn->nemo_toolkit[tts]) (2.2.0)\n    Requirement already satisfied: cffi>=1.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from soundfile->nemo_toolkit[tts]) (1.14.6)\n    Requirement already satisfied: fonttools>=4.22.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from matplotlib->nemo_toolkit[tts]) (4.28.2)\n    Requirement already satisfied: setuptools-scm>=4 in /home/ubuntu/.local/lib/python3.8/site-packages (from matplotlib->nemo_toolkit[tts]) (6.3.2)\n    Requirement already satisfied: cycler>=0.10 in /home/ubuntu/.local/lib/python3.8/site-packages (from matplotlib->nemo_toolkit[tts]) (0.11.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /home/ubuntu/.local/lib/python3.8/site-packages (from matplotlib->nemo_toolkit[tts]) (1.3.2)\n    Requirement already satisfied: pytz>=2017.3 in /home/ubuntu/.local/lib/python3.8/site-packages (from pandas->nemo_toolkit[tts]) (2021.1)\n    Requirement already satisfied: simplejson>=3.8.1 in /home/ubuntu/.local/lib/python3.8/site-packages (from pyannote.core->nemo_toolkit[tts]) (3.17.6)\n    Requirement already satisfied: sortedcontainers>=2.0.4 in /home/ubuntu/.local/lib/python3.8/site-packages (from pyannote.core->nemo_toolkit[tts]) (2.4.0)\n    Requirement already satisfied: tabulate>=0.7.7 in /home/ubuntu/.local/lib/python3.8/site-packages (from pyannote.metrics->nemo_toolkit[tts]) (0.8.9)\n    Requirement already satisfied: pyannote.database>=4.0.1 in /home/ubuntu/.local/lib/python3.8/site-packages (from pyannote.metrics->nemo_toolkit[tts]) (4.1.1)\n    Requirement already satisfied: docopt>=0.6.2 in /home/ubuntu/.local/lib/python3.8/site-packages (from pyannote.metrics->nemo_toolkit[tts]) (0.6.2)\n    Requirement already satisfied: sympy>=1.1 in /home/ubuntu/.local/lib/python3.8/site-packages (from pyannote.metrics->nemo_toolkit[tts]) (1.9)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2 in /home/ubuntu/.local/lib/python3.8/site-packages (from ruamel.yaml->nemo_toolkit[tts]) (0.2.6)\n    Requirement already satisfied: pycparser in /home/ubuntu/.local/lib/python3.8/site-packages (from cffi>=1.0->soundfile->nemo_toolkit[tts]) (2.20)\n    Requirement already satisfied: aiohttp in /home/ubuntu/.local/lib/python3.8/site-packages (from fsspec[http]>=0.8.1->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (3.8.1)\n    Requirement already satisfied: click in /home/ubuntu/.local/lib/python3.8/site-packages (from nltk>=3.2.4->g2p_en->nemo_toolkit[tts]) (7.1.2)\n    Requirement already satisfied: setuptools in /home/ubuntu/.local/lib/python3.8/site-packages (from numba>=0.43.0->librosa->nemo_toolkit[tts]) (59.6.0)\n    Requirement already satisfied: llvmlite<0.38,>=0.37.0rc1 in /home/ubuntu/.local/lib/python3.8/site-packages (from numba>=0.43.0->librosa->nemo_toolkit[tts]) (0.37.0)\n    Requirement already satisfied: appdirs in /home/ubuntu/.local/lib/python3.8/site-packages (from pooch>=1.0->librosa->nemo_toolkit[tts]) (1.4.4)\n    Requirement already satisfied: typer[all]>=0.2.1 in /home/ubuntu/.local/lib/python3.8/site-packages (from pyannote.database>=4.0.1->pyannote.metrics->nemo_toolkit[tts]) (0.4.0)\n    Requirement already satisfied: tomli>=1.0.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from setuptools-scm>=4->matplotlib->nemo_toolkit[tts]) (1.2.2)\n    Requirement already satisfied: mpmath>=0.19 in /home/ubuntu/.local/lib/python3.8/site-packages (from sympy>=1.1->pyannote.metrics->nemo_toolkit[tts]) (1.2.1)\n    Requirement already satisfied: grpcio>=1.24.3 in /home/ubuntu/.local/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (1.43.0)\n    Requirement already satisfied: werkzeug>=0.11.15 in /home/ubuntu/.local/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (2.0.2)\n    Requirement already satisfied: markdown>=2.6.8 in /home/ubuntu/.local/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (3.3.6)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /home/ubuntu/.local/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (0.4.6)\n    Requirement already satisfied: absl-py>=0.4 in /home/ubuntu/.local/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (1.0.0)\n    Requirement already satisfied: google-auth<3,>=1.6.3 in /home/ubuntu/.local/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (2.3.3)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (1.8.0)\n    Requirement already satisfied: wheel>=0.26 in /home/ubuntu/.local/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (0.36.2)\n    Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from tensorboard>=2.2.0->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (0.6.1)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/lib/python3/dist-packages (from requests->torchtext==0.8.0->nemo_toolkit[tts]) (2018.1.18)\n    Requirement already satisfied: charset-normalizer~=2.0.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from requests->torchtext==0.8.0->nemo_toolkit[tts]) (2.0.9)\n    Requirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/lib/python3/dist-packages (from requests->torchtext==0.8.0->nemo_toolkit[tts]) (1.22)\n    Requirement already satisfied: idna<4,>=2.5 in /usr/lib/python3/dist-packages (from requests->torchtext==0.8.0->nemo_toolkit[tts]) (2.6)\n    Requirement already satisfied: zipp>=3.1.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from importlib-resources->hydra-core>=1.0.4->nemo_toolkit[tts]) (3.6.0)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from google-auth<3,>=1.6.3->tensorboard>=2.2.0->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (4.2.2)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /home/ubuntu/.local/lib/python3.8/site-packages (from google-auth<3,>=1.6.3->tensorboard>=2.2.0->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (4.8)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/lib/python3/dist-packages (from google-auth<3,>=1.6.3->tensorboard>=2.2.0->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (0.2.1)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard>=2.2.0->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (1.3.0)\n    Requirement already satisfied: importlib-metadata>=4.4 in /home/ubuntu/.local/lib/python3.8/site-packages (from markdown>=2.6.8->tensorboard>=2.2.0->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (4.9.0)\n    Requirement already satisfied: shellingham<2.0.0,>=1.3.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from typer[all]>=0.2.1->pyannote.database>=4.0.1->pyannote.metrics->nemo_toolkit[tts]) (1.4.0)\n    Requirement already satisfied: colorama<0.5.0,>=0.4.3 in /home/ubuntu/.local/lib/python3.8/site-packages (from typer[all]>=0.2.1->pyannote.database>=4.0.1->pyannote.metrics->nemo_toolkit[tts]) (0.4.4)\n    Requirement already satisfied: aiosignal>=1.1.2 in /home/ubuntu/.local/lib/python3.8/site-packages (from aiohttp->fsspec[http]>=0.8.1->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (1.2.0)\n    Requirement already satisfied: frozenlist>=1.1.1 in /home/ubuntu/.local/lib/python3.8/site-packages (from aiohttp->fsspec[http]>=0.8.1->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (1.2.0)\n    Requirement already satisfied: attrs>=17.3.0 in /usr/lib/python3/dist-packages (from aiohttp->fsspec[http]>=0.8.1->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (17.4.0)\n    Requirement already satisfied: multidict<7.0,>=4.5 in /home/ubuntu/.local/lib/python3.8/site-packages (from aiohttp->fsspec[http]>=0.8.1->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (5.2.0)\n    Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /home/ubuntu/.local/lib/python3.8/site-packages (from aiohttp->fsspec[http]>=0.8.1->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (4.0.1)\n    Requirement already satisfied: yarl<2.0,>=1.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from aiohttp->fsspec[http]>=0.8.1->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (1.7.2)\n    Requirement already satisfied: oauthlib>=3.0.0 in /home/ubuntu/.local/lib/python3.8/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard>=2.2.0->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (3.1.1)\n    Requirement already satisfied: pyasn1>=0.1.3 in /usr/lib/python3/dist-packages (from rsa<5,>=3.1.4->google-auth<3,>=1.6.3->tensorboard>=2.2.0->pytorch-lightning==1.1.5->nemo_toolkit[tts]) (0.4.2)\n\n\n\n```python\n# Imorting the libraries\nimport os\nimport pandas as pd\nimport re\nimport librosa\nfrom datasets import Dataset\n```\n\n# Loading the Dataset\n\n\n```python\n# defining the root directory\ndata_directory = \"../Badaga_Corpus-v.0.1.0/\"\ntagged_file = \"Badaga-v0.1.0.xlsx\"\n```\n\n\n```python\n# loading the data\ntagged_file_path = os.path.join(data_directory, tagged_file)\ndata_frame = pd.read_excel(tagged_file_path)\n\n# droping the missing values\ndata_frame.dropna(inplace=True)\n\ngender = \"F\" # \"M\", \"F\"\n\n# loading the audio files\ndata_frame[\"audio_file_name\"] = data_frame[\"audio_file_name\"].apply(lambda x: os.path.join(data_directory, \"clips\", x))\ndata_frame = data_frame[data_frame[\"gender\"]==gender]\n\n# splitting the data to train and test using the aplit_index from transcription\ntrain_df = data_frame[data_frame[\"split_label\"]!=\"test\"]\ntest_df = data_frame[data_frame[\"split_label\"]==\"test\"]\n```\n\n\n```python\n# printing the data\ntrain_df\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>items</th>\n      <th>translated_transcript</th>\n      <th>audio_file_name</th>\n      <th>translterated_script</th>\n      <th>user_id</th>\n      <th>gender</th>\n      <th>locale</th>\n      <th>split_label</th>\n      <th>duration</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1.0</td>\n      <td>what is the recipe in home</td>\n      <td>../Badaga_Corpus-v.0.1.0/clips/F002_1_1.mp3</td>\n      <td>manaya aena udhaka</td>\n      <td>F002</td>\n      <td>F</td>\n      <td>ba</td>\n      <td>train</td>\n      <td>2.377187</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2.0</td>\n      <td>who is there near you</td>\n      <td>../Badaga_Corpus-v.0.1.0/clips/F002_1_2.mp3</td>\n      <td>pakka dhara edhdharae</td>\n      <td>F002</td>\n      <td>F</td>\n      <td>ba</td>\n      <td>train</td>\n      <td>2.377187</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>3.0</td>\n      <td>what did you prepare for lunch</td>\n      <td>../Badaga_Corpus-v.0.1.0/clips/F002_1_3.mp3</td>\n      <td>hagulu hasuga aena maditha</td>\n      <td>F002</td>\n      <td>F</td>\n      <td>ba</td>\n      <td>train</td>\n      <td>2.351062</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>4.0</td>\n      <td>did you brush</td>\n      <td>../Badaga_Corpus-v.0.1.0/clips/F002_1_4.mp3</td>\n      <td>hallu ujjithaya</td>\n      <td>F002</td>\n      <td>F</td>\n      <td>ba</td>\n      <td>train</td>\n      <td>2.194313</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>5.0</td>\n      <td>did you eat</td>\n      <td>../Badaga_Corpus-v.0.1.0/clips/F002_1_5.mp3</td>\n      <td>nee thindhubutaya</td>\n      <td>F002</td>\n      <td>F</td>\n      <td>ba</td>\n      <td>train</td>\n      <td>2.272687</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>9830</th>\n      <td>593.0</td>\n      <td>i dont cheat anybody</td>\n      <td>../Badaga_Corpus-v.0.1.0/clips/F004_593.mp3</td>\n      <td>na tharuvavu aemaathathu ellae</td>\n      <td>F004</td>\n      <td>F</td>\n      <td>ba</td>\n      <td>train</td>\n      <td>2.011437</td>\n    </tr>\n    <tr>\n      <th>9831</th>\n      <td>594.0</td>\n      <td>today it is so windy</td>\n      <td>../Badaga_Corpus-v.0.1.0/clips/F004_594.mp3</td>\n      <td>gaai jaasthi endhdhu</td>\n      <td>F004</td>\n      <td>F</td>\n      <td>ba</td>\n      <td>train</td>\n      <td>1.358375</td>\n    </tr>\n    <tr>\n      <th>9834</th>\n      <td>597.0</td>\n      <td>today is my birthday</td>\n      <td>../Badaga_Corpus-v.0.1.0/clips/F004_597.mp3</td>\n      <td>endhdhu aenna utti jaenna</td>\n      <td>F004</td>\n      <td>F</td>\n      <td>ba</td>\n      <td>train</td>\n      <td>1.541250</td>\n    </tr>\n    <tr>\n      <th>9835</th>\n      <td>598.0</td>\n      <td>we are coming tomorrow.</td>\n      <td>../Badaga_Corpus-v.0.1.0/clips/F004_598.mp3</td>\n      <td>enga naaiga bannaeyo</td>\n      <td>F004</td>\n      <td>F</td>\n      <td>ba</td>\n      <td>train</td>\n      <td>1.724125</td>\n    </tr>\n    <tr>\n      <th>9836</th>\n      <td>599.0</td>\n      <td>two o clock we will go</td>\n      <td>../Badaga_Corpus-v.0.1.0/clips/F004_599.mp3</td>\n      <td>aeradu manniga oppa</td>\n      <td>F004</td>\n      <td>F</td>\n      <td>ba</td>\n      <td>train</td>\n      <td>1.306125</td>\n    </tr>\n  </tbody>\n</table>\n<p>4193 rows \u00d7 9 columns</p>\n</div>\n\n\n\n\n```python\n# creating the dictionary for both train and test and storing it as a json file\nimport json\n\naudio_paths = list(train_df[\"audio_file_name\"])\ndurations = list(train_df[\"duration\"])\nlabels = list(train_df[\"translterated_script\"])\n\n\nmy_dict = dict()\ni = 0\nwith open(\"files/tts_train.json\", \"w\") as outfile:\n    for path, dur, label in zip(audio_paths, durations, labels):\n        my_dict = {\"audio_filepath\": path,\n                \"duration\": dur,\n                \"text\": label}\n        json_object = json.dumps(my_dict)\n        outfile.write(json_object + \"\\n\")\n        \n\n\naudio_paths = list(test_df[\"audio_file_name\"])\ndurations = list(test_df[\"duration\"])\nlabels = list(test_df[\"translterated_script\"])\n\n\nmy_dict = dict()\ni = 0\nwith open(\"files/tts_test.json\", \"w\") as outfile:\n    for path, dur, label in zip(audio_paths, durations, labels):\n        my_dict = {\"audio_filepath\": path,\n                \"duration\": dur,\n                \"text\": label}\n        json_object = json.dumps(my_dict)\n        outfile.write(json_object + \"\\n\")\n```\n\n# Loading the Model\n\n\n```python\n# loading the Tactron model and training\ndirectory = \"tactron2-rbg-badaga-tts-\"+gender.lower()\n\nif os.path.exists(directory):\n    pass\nelse:\n    os.makedirs(directory)\n\n!python3.8 tacotron2.py sample_rate=16000 train_dataset=files/tts_train.json validation_datasets=files/tts_test.json exp_manager.exp_dir=$directory trainer.max_epochs=20 trainer.accelerator=null trainer.check_val_every_n_epoch=1\n\n```\n\n    [NeMo W 2021-12-18 15:16:08 experimental:27] Module <class 'nemo.collections.asr.data.audio_to_text_dali.AudioToCharDALIDataset'> is experimental, not ready for production and is not fully supported. Use at your own risk.\n    ################################################################################\n    ### WARNING, path does not exist: KALDI_ROOT=/mnt/matylda5/iveselyk/Tools/kaldi-trunk\n    ###          (please add 'export KALDI_ROOT=<your_path>' in your $HOME/.profile)\n    ###          (or run as: KALDI_ROOT=<your_path> python <your_script>.py)\n    ################################################################################\n    \n    [NeMo W 2021-12-18 15:16:08 nemo_logging:349] /home/ubuntu/.local/lib/python3.8/site-packages/torchaudio/backend/utils.py:53: UserWarning: \"sox\" backend is being deprecated. The default backend will be changed to \"sox_io\" backend in 0.8.0 and \"sox\" backend will be removed in 0.9.0. Please migrate to \"sox_io\" backend. Please refer to https://github.com/pytorch/audio/issues/903 for the detail.\n          warnings.warn(\n        \n    GPU available: True, used: True\n    GPU available: True, used: True\n    TPU available: None, using: 0 TPU cores\n    TPU available: None, using: 0 TPU cores\n    LOCAL_RANK: 0 - CUDA_VISIBLE_DEVICES: [0]\n    LOCAL_RANK: 0 - CUDA_VISIBLE_DEVICES: [0]\n    [NeMo I 2021-12-18 15:16:09 exp_manager:208] Experiments will be logged at tactron2-rbg-badaga-tts-f/Tacotron2/2021-12-18_15-16-09\n    [NeMo I 2021-12-18 15:16:09 exp_manager:548] TensorboardLogger has been set up\n    [NeMo I 2021-12-18 15:16:09 collections:173] Dataset loaded with 4193 files totalling 2.81 hours\n    [NeMo I 2021-12-18 15:16:09 collections:174] 0 files were filtered totalling 0.00 hours\n    [NeMo I 2021-12-18 15:16:09 collections:173] Dataset loaded with 735 files totalling 0.48 hours\n    [NeMo I 2021-12-18 15:16:09 collections:174] 0 files were filtered totalling 0.00 hours\n    [NeMo I 2021-12-18 15:16:09 features:240] PADDING: 16\n    [NeMo I 2021-12-18 15:16:09 features:249] STFT using conv\n    {'labels': '${labels}', 'train_ds': {'dataset': {'_target_': 'nemo.collections.asr.data.audio_to_text.AudioToCharDataset', 'manifest_filepath': '${train_dataset}', 'max_duration': None, 'min_duration': 0.1, 'trim': False, 'int_values': False, 'load_audio': True, 'normalize': False, 'sample_rate': '${sample_rate}'}, 'dataloader_params': {'drop_last': False, 'shuffle': True, 'batch_size': 8, 'num_workers': 4}}, 'validation_ds': {'dataset': {'_target_': 'nemo.collections.asr.data.audio_to_text.AudioToCharDataset', 'manifest_filepath': '${validation_datasets}', 'max_duration': None, 'min_duration': 0.1, 'int_values': False, 'load_audio': True, 'normalize': False, 'sample_rate': '${sample_rate}', 'trim': False}, 'dataloader_params': {'drop_last': False, 'shuffle': False, 'batch_size': 8, 'num_workers': 8}}, 'preprocessor': {'_target_': 'nemo.collections.asr.parts.features.FilterbankFeatures', 'dither': 0.0, 'nfilt': '${n_mels}', 'frame_splicing': 1, 'highfreq': '${fmax}', 'log': True, 'log_zero_guard_type': 'clamp', 'log_zero_guard_value': 1e-05, 'lowfreq': 0, 'mag_power': 1.0, 'n_fft': '${n_fft}', 'n_window_size': 1024, 'n_window_stride': '${n_stride}', 'normalize': None, 'pad_to': 16, 'pad_value': '${pad_value}', 'preemph': None, 'sample_rate': '${sample_rate}', 'stft_conv': True, 'window': 'hann'}, 'encoder': {'_target_': 'nemo.collections.tts.modules.tacotron2.Encoder', 'encoder_kernel_size': 5, 'encoder_n_convolutions': 3, 'encoder_embedding_dim': 512}, 'decoder': {'_target_': 'nemo.collections.tts.modules.tacotron2.Decoder', 'decoder_rnn_dim': 1024, 'encoder_embedding_dim': '${model.encoder.encoder_embedding_dim}', 'gate_threshold': 0.5, 'max_decoder_steps': 1000, 'n_frames_per_step': 1, 'n_mel_channels': '${n_mels}', 'p_attention_dropout': 0.1, 'p_decoder_dropout': 0.1, 'prenet_dim': 256, 'prenet_p_dropout': 0.5, 'attention_dim': 128, 'attention_rnn_dim': 1024, 'attention_location_kernel_size': 31, 'attention_location_n_filters': 32, 'early_stopping': True}, 'postnet': {'_target_': 'nemo.collections.tts.modules.tacotron2.Postnet', 'n_mel_channels': '${n_mels}', 'p_dropout': 0.5, 'postnet_embedding_dim': 512, 'postnet_kernel_size': 5, 'postnet_n_convolutions': 5}, 'optim': {'name': 'adam', 'lr': 0.001, 'weight_decay': 1e-06}}\n    [NeMo I 2021-12-18 15:16:13 modelPT:685] Optimizer config = Adam (\n        Parameter Group 0\n            amsgrad: False\n            betas: (0.9, 0.999)\n            eps: 1e-08\n            lr: 0.001\n            weight_decay: 1e-06\n        )\n    [NeMo I 2021-12-18 15:16:13 lr_scheduler:492] Scheduler not initialized as no `sched` config supplied to setup_optimizer()\n    \n      | Name                       | Type               | Params\n    ------------------------------------------------------------------\n    0 | audio_to_melspec_precessor | FilterbankFeatures | 0     \n    1 | text_embedding             | Embedding          | 35.3 K\n    2 | encoder                    | Encoder            | 5.5 M \n    3 | decoder                    | Decoder            | 18.3 M\n    4 | postnet                    | Postnet            | 4.3 M \n    5 | loss                       | Tacotron2Loss      | 0     \n    ------------------------------------------------------------------\n    28.2 M    Trainable params\n    0         Non-trainable params\n    28.2 M    Total params\n    \n      | Name                       | Type               | Params\n    ------------------------------------------------------------------\n    0 | audio_to_melspec_precessor | FilterbankFeatures | 0     \n    1 | text_embedding             | Embedding          | 35.3 K\n    2 | encoder                    | Encoder            | 5.5 M \n    3 | decoder                    | Decoder            | 18.3 M\n    4 | postnet                    | Postnet            | 4.3 M \n    5 | loss                       | Tacotron2Loss      | 0     \n    ------------------------------------------------------------------\n    28.2 M    Trainable params\n    0         Non-trainable params\n    28.2 M    Total params\n    Validation sanity check:   0%|                            | 0/2 [00:00<?, ?it/s][NeMo W 2021-12-18 15:16:21 tacotron2:366] Reached max decoder steps 1000.\n    Validation sanity check:  50%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588          | 1/2 [00:07<00:07,  7.96s/it][NeMo W 2021-12-18 15:16:22 tacotron2:366] Reached max decoder steps 1000.\n    Training: 0it [00:00, ?it/s][NeMo W 2021-12-18 15:16:25 nemo_logging:349] /home/ubuntu/.local/lib/python3.8/site-packages/pytorch_lightning/utilities/distributed.py:49: RuntimeWarning: You are using `LearningRateMonitor` callback with models that have no learning rate schedulers. Please see documentation for `configure_optimizers` method.\n          warnings.warn(*args, **kwargs)\n        \n    Epoch 0:   0%|                                          | 0/617 [00:00<?, ?it/s][NeMo W 2021-12-18 15:16:29 nemo_logging:349] /home/ubuntu/.local/lib/python3.8/site-packages/pytorch_lightning/utilities/distributed.py:49: UserWarning: The {progress_bar:dict keyword} was deprecated in 0.9.1 and will be removed in 1.0.0\n        Please use self.log(...) inside the lightningModule instead.\n        \n        # log on a step or aggregate epoch metric to the logger and/or progress bar\n        # (inside LightningModule)\n        self.log('train_loss', loss, on_step=True, on_epoch=True, prog_bar=True)\n          warnings.warn(*args, **kwargs)\n        \n    Epoch 0:  85%|\u258a| 525/617 [07:47<01:21,  1.12it/s, loss=2, v_num=6-09, training_l\n    Validating: 0it [00:00, ?it/s]\u001b[A\n    Validating:   0%|                                        | 0/92 [00:00<?, ?it/s]\u001b[A[NeMo W 2021-12-18 15:24:20 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  85%|\u258a| 527/617 [07:55<01:21,  1.11it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:24:22 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:   2%|\u258b                               | 2/92 [00:09<06:34,  4.39s/it]\u001b[A[NeMo W 2021-12-18 15:24:24 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  86%|\u258a| 529/617 [07:59<01:19,  1.10it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:24:25 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:   4%|\u2588\u258d                              | 4/92 [00:13<03:48,  2.59s/it]\u001b[A[NeMo W 2021-12-18 15:24:27 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  86%|\u258a| 531/617 [08:02<01:18,  1.10it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:24:29 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:   7%|\u2588\u2588                              | 6/92 [00:16<02:53,  2.02s/it]\u001b[A[NeMo W 2021-12-18 15:24:30 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  86%|\u258a| 533/617 [08:05<01:16,  1.10it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:24:31 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:   9%|\u2588\u2588\u258a                             | 8/92 [00:19<02:23,  1.71s/it]\u001b[A[NeMo W 2021-12-18 15:24:33 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  87%|\u258a| 535/617 [08:08<01:14,  1.10it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:24:34 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  11%|\u2588\u2588\u2588\u258e                           | 10/92 [00:22<02:09,  1.57s/it]\u001b[A[NeMo W 2021-12-18 15:24:36 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  87%|\u258a| 537/617 [08:11<01:13,  1.09it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:24:37 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  13%|\u2588\u2588\u2588\u2588                           | 12/92 [00:25<02:00,  1.50s/it]\u001b[A[NeMo W 2021-12-18 15:24:39 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  87%|\u258a| 539/617 [08:14<01:11,  1.09it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:24:40 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  15%|\u2588\u2588\u2588\u2588\u258b                          | 14/92 [00:28<01:54,  1.47s/it]\u001b[A[NeMo W 2021-12-18 15:24:42 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  88%|\u2589| 541/617 [08:16<01:09,  1.09it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:24:43 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  17%|\u2588\u2588\u2588\u2588\u2588\u258d                         | 16/92 [00:31<01:50,  1.46s/it]\u001b[A[NeMo W 2021-12-18 15:24:44 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  88%|\u2589| 543/617 [08:19<01:08,  1.09it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:24:46 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  20%|\u2588\u2588\u2588\u2588\u2588\u2588                         | 18/92 [00:33<01:47,  1.45s/it]\u001b[A[NeMo W 2021-12-18 15:24:47 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  88%|\u2589| 545/617 [08:22<01:06,  1.08it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:24:49 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  22%|\u2588\u2588\u2588\u2588\u2588\u2588\u258b                        | 20/92 [00:36<01:43,  1.44s/it]\u001b[A[NeMo W 2021-12-18 15:24:50 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  89%|\u2589| 547/617 [08:25<01:04,  1.08it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:24:52 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  24%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d                       | 22/92 [00:39<01:40,  1.44s/it]\u001b[A[NeMo W 2021-12-18 15:24:53 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  89%|\u2589| 549/617 [08:28<01:02,  1.08it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:24:54 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  26%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588                       | 24/92 [00:42<01:37,  1.44s/it]\u001b[A[NeMo W 2021-12-18 15:24:56 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  89%|\u2589| 551/617 [08:31<01:01,  1.08it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:24:57 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  28%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a                      | 26/92 [00:45<01:35,  1.44s/it]\u001b[A[NeMo W 2021-12-18 15:24:59 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  90%|\u2589| 553/617 [08:34<00:59,  1.08it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:25:00 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  30%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d                     | 28/92 [00:48<01:32,  1.44s/it]\u001b[A[NeMo W 2021-12-18 15:25:02 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  90%|\u2589| 555/617 [08:37<00:57,  1.07it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:25:03 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  33%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588                     | 30/92 [00:51<01:29,  1.44s/it]\u001b[A[NeMo W 2021-12-18 15:25:05 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  90%|\u2589| 557/617 [08:39<00:56,  1.07it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:25:06 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  35%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a                    | 32/92 [00:54<01:26,  1.44s/it]\u001b[A[NeMo W 2021-12-18 15:25:07 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  91%|\u2589| 559/617 [08:42<00:54,  1.07it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:25:09 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  37%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d                   | 34/92 [00:56<01:23,  1.44s/it]\u001b[A[NeMo W 2021-12-18 15:25:10 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  91%|\u2589| 561/617 [08:45<00:52,  1.07it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:25:12 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  39%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f                  | 36/92 [00:59<01:22,  1.47s/it]\u001b[A[NeMo W 2021-12-18 15:25:13 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  91%|\u2589| 563/617 [08:48<00:50,  1.06it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:25:15 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  41%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a                  | 38/92 [01:02<01:18,  1.46s/it]\u001b[A[NeMo W 2021-12-18 15:25:16 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  92%|\u2589| 565/617 [08:51<00:48,  1.06it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:25:18 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  43%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258d                 | 40/92 [01:05<01:15,  1.45s/it]\u001b[A[NeMo W 2021-12-18 15:25:19 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  92%|\u2589| 567/617 [08:54<00:47,  1.06it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:25:21 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  46%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f                | 42/92 [01:08<01:12,  1.44s/it]\u001b[A[NeMo W 2021-12-18 15:25:22 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  92%|\u2589| 569/617 [08:57<00:45,  1.06it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:25:23 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  48%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a                | 44/92 [01:11<01:09,  1.44s/it]\u001b[A[NeMo W 2021-12-18 15:25:25 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  93%|\u2589| 571/617 [09:00<00:43,  1.06it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:25:26 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  50%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c               | 46/92 [01:14<01:06,  1.44s/it]\u001b[A[NeMo W 2021-12-18 15:25:28 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  93%|\u2589| 573/617 [09:03<00:41,  1.05it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:25:29 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  52%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f              | 48/92 [01:17<01:03,  1.44s/it]\u001b[A[NeMo W 2021-12-18 15:25:31 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  93%|\u2589| 575/617 [09:06<00:39,  1.05it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:25:32 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  54%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a              | 50/92 [01:20<01:00,  1.44s/it]\u001b[A[NeMo W 2021-12-18 15:25:33 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  94%|\u2589| 577/617 [09:08<00:38,  1.05it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:25:35 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  57%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c             | 52/92 [01:23<00:57,  1.44s/it]\u001b[A[NeMo W 2021-12-18 15:25:36 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  94%|\u2589| 579/617 [09:11<00:36,  1.05it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:25:38 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  59%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f            | 54/92 [01:25<00:54,  1.44s/it]\u001b[A[NeMo W 2021-12-18 15:25:39 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  94%|\u2589| 581/617 [09:14<00:34,  1.05it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:25:41 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  61%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a            | 56/92 [01:28<00:52,  1.45s/it]\u001b[A[NeMo W 2021-12-18 15:25:42 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  94%|\u2589| 583/617 [09:17<00:32,  1.05it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:25:44 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  63%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c           | 58/92 [01:31<00:49,  1.45s/it]\u001b[A[NeMo W 2021-12-18 15:25:45 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  95%|\u2589| 585/617 [09:20<00:30,  1.04it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:25:47 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  65%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f          | 60/92 [01:34<00:46,  1.45s/it]\u001b[A[NeMo W 2021-12-18 15:25:48 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  95%|\u2589| 587/617 [09:23<00:28,  1.04it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:25:49 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  67%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589          | 62/92 [01:37<00:43,  1.45s/it]\u001b[A[NeMo W 2021-12-18 15:25:51 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  95%|\u2589| 589/617 [09:26<00:26,  1.04it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:25:52 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  70%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c         | 64/92 [01:40<00:40,  1.46s/it]\u001b[A[NeMo W 2021-12-18 15:25:54 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  96%|\u2589| 591/617 [09:29<00:25,  1.04it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:25:55 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  72%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258f        | 66/92 [01:43<00:37,  1.45s/it]\u001b[A[NeMo W 2021-12-18 15:25:57 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  96%|\u2589| 593/617 [09:32<00:23,  1.04it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:25:58 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  74%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589        | 68/92 [01:46<00:34,  1.45s/it]\u001b[A[NeMo W 2021-12-18 15:26:00 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  96%|\u2589| 595/617 [09:34<00:21,  1.03it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:26:01 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  76%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c       | 70/92 [01:49<00:31,  1.45s/it]\u001b[A[NeMo W 2021-12-18 15:26:02 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  97%|\u2589| 597/617 [09:37<00:19,  1.03it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:26:04 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  78%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e      | 72/92 [01:51<00:28,  1.45s/it]\u001b[A[NeMo W 2021-12-18 15:26:05 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  97%|\u2589| 599/617 [09:40<00:17,  1.03it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:26:07 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  80%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589      | 74/92 [01:54<00:26,  1.44s/it]\u001b[A[NeMo W 2021-12-18 15:26:08 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  97%|\u2589| 601/617 [09:43<00:15,  1.03it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:26:10 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  83%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c     | 76/92 [01:57<00:23,  1.44s/it]\u001b[A[NeMo W 2021-12-18 15:26:11 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  98%|\u2589| 603/617 [09:46<00:13,  1.03it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:26:13 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  85%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e    | 78/92 [02:00<00:20,  1.44s/it]\u001b[A[NeMo W 2021-12-18 15:26:14 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  98%|\u2589| 605/617 [09:49<00:11,  1.03it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:26:15 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  87%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589    | 80/92 [02:03<00:17,  1.43s/it]\u001b[A[NeMo W 2021-12-18 15:26:17 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  98%|\u2589| 607/617 [09:52<00:09,  1.02it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:26:18 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  89%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b   | 82/92 [02:06<00:14,  1.43s/it]\u001b[A[NeMo W 2021-12-18 15:26:20 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  99%|\u2589| 609/617 [09:55<00:07,  1.02it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:26:21 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  91%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e  | 84/92 [02:09<00:11,  1.43s/it]\u001b[A[NeMo W 2021-12-18 15:26:23 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  99%|\u2589| 611/617 [09:57<00:05,  1.02it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:26:24 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  93%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589  | 86/92 [02:12<00:08,  1.42s/it]\u001b[A[NeMo W 2021-12-18 15:26:25 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0:  99%|\u2589| 613/617 [10:00<00:03,  1.02it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:26:27 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  96%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258b | 88/92 [02:14<00:05,  1.42s/it]\u001b[A[NeMo W 2021-12-18 15:26:28 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0: 100%|\u2589| 615/617 [10:03<00:01,  1.02it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:26:30 tacotron2:366] Reached max decoder steps 1000.\n    \n    Validating:  98%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258e| 90/92 [02:17<00:02,  1.42s/it]\u001b[A[NeMo W 2021-12-18 15:26:31 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0: 100%|\u2588| 617/617 [10:06<00:00,  1.02it/s, loss=2, v_num=6-09, training_l\u001b[A[NeMo W 2021-12-18 15:26:32 tacotron2:366] Reached max decoder steps 1000.\n    \n    Epoch 0: 100%|\u2588| 617/617 [10:08<00:00,  1.01it/s, loss=2, v_num=6-09, training_l\u001b[A\n                                                                                    \u001b[AEpoch 0, global step 524: val_loss reached 19.76913 (best 19.76913), saving model to \"/home/ubuntu/CoRePooL/benchmarks/badaga/notebooks/tactron2-rbg-badaga-tts-f/Tacotron2/2021-12-18_15-16-09/checkpoints/Tacotron2---val_loss=19.77-epoch=0.ckpt\" as top 3\n    Epoch 0, global step 524: val_loss reached 19.76913 (best 19.76913), saving model to \"/home/ubuntu/CoRePooL/benchmarks/badaga/notebooks/tactron2-rbg-badaga-tts-f/Tacotron2/2021-12-18_15-16-09/checkpoints/Tacotron2---val_loss=19.77-epoch=0.ckpt\" as top 3\n    Epoch 1:  77%|\u258a| 478/617 [07:10<02:05,  1.11it/s, loss=1.6, v_num=6-09, training\n", "meta": {"hexsha": "5e51e81e104f01d9c37cc20b576763e359ece87c", "size": 69370, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "benchmarks/badaga/notebooks/text-to-speech.ipynb", "max_stars_repo_name": "Jairam-RBG/CoRePooL", "max_stars_repo_head_hexsha": "e61757d3d8e1c8aab046e2a503a7b3c994980884", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmarks/badaga/notebooks/text-to-speech.ipynb", "max_issues_repo_name": "Jairam-RBG/CoRePooL", "max_issues_repo_head_hexsha": "e61757d3d8e1c8aab046e2a503a7b3c994980884", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmarks/badaga/notebooks/text-to-speech.ipynb", "max_forks_repo_name": "Jairam-RBG/CoRePooL", "max_forks_repo_head_hexsha": "e61757d3d8e1c8aab046e2a503a7b3c994980884", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-21T07:38:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T07:38:39.000Z", "avg_line_length": 75.1570964247, "max_line_length": 2277, "alphanum_fraction": 0.6004036327, "converted": true, "num_tokens": 20527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18476751064799998, "lm_q2_score": 0.03732688573777281, "lm_q1q2_score": 0.006896795758010617}}
{"text": "```python\nfrom google.colab import drive\ndrive.mount('/content/drive',force_remount=True)\n```\n\n    Mounted at /content/drive\n\n\n\n```python\nimport os\nos.chdir('/content/drive/MyDrive/Colab_Notebooks/coursera/coursera_Probabilistic_Deep_Learning_TF2/Week4')\n```\n\n\n```python\n!pip install tensorflow=='2.2.0'\n```\n\n    Collecting tensorflow==2.2.0\n      Downloading tensorflow-2.2.0-cp37-cp37m-manylinux2010_x86_64.whl (516.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 516.2 MB 3.5 kB/s \n    \u001b[?25hRequirement already satisfied: numpy<2.0,>=1.16.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.2.0) (1.19.5)\n    Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.2.0) (1.13.3)\n    Requirement already satisfied: google-pasta>=0.1.8 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.2.0) (0.2.0)\n    Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.2.0) (3.3.0)\n    Requirement already satisfied: six>=1.12.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.2.0) (1.15.0)\n    Requirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.2.0) (1.0.0)\n    Requirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.2.0) (0.37.1)\n    Requirement already satisfied: scipy==1.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.2.0) (1.4.1)\n    Requirement already satisfied: protobuf>=3.8.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.2.0) (3.17.3)\n    Requirement already satisfied: astunparse==1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.2.0) (1.6.3)\n    Requirement already satisfied: keras-preprocessing>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.2.0) (1.1.2)\n    Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.2.0) (1.1.0)\n    Collecting tensorboard<2.3.0,>=2.2.0\n      Downloading tensorboard-2.2.2-py3-none-any.whl (3.0 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.0 MB 62.5 MB/s \n    \u001b[?25hCollecting gast==0.3.3\n      Downloading gast-0.3.3-py2.py3-none-any.whl (9.7 kB)\n    Collecting tensorflow-estimator<2.3.0,>=2.2.0\n      Downloading tensorflow_estimator-2.2.0-py2.py3-none-any.whl (454 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 454 kB 85.7 MB/s \n    \u001b[?25hCollecting h5py<2.11.0,>=2.10.0\n      Downloading h5py-2.10.0-cp37-cp37m-manylinux1_x86_64.whl (2.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.9 MB 76.9 MB/s \n    \u001b[?25hRequirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.2.0) (1.43.0)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (3.3.6)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (1.8.1)\n    Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (1.35.0)\n    Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (1.0.1)\n    Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (57.4.0)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (0.4.6)\n    Requirement already satisfied: requests<3,>=2.21.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (2.23.0)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (0.2.8)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (4.2.4)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (4.8)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (1.3.1)\n    Requirement already satisfied: importlib-metadata>=4.4 in /usr/local/lib/python3.7/dist-packages (from markdown>=2.6.8->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (4.10.1)\n    Requirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=4.4->markdown>=2.6.8->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (3.10.0.2)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=4.4->markdown>=2.6.8->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (3.7.0)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (0.4.8)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (1.24.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (2021.10.8)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (3.0.4)\n    Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (3.2.0)\n    Installing collected packages: tensorflow-estimator, tensorboard, h5py, gast, tensorflow\n      Attempting uninstall: tensorflow-estimator\n        Found existing installation: tensorflow-estimator 2.7.0\n        Uninstalling tensorflow-estimator-2.7.0:\n          Successfully uninstalled tensorflow-estimator-2.7.0\n      Attempting uninstall: tensorboard\n        Found existing installation: tensorboard 2.7.0\n        Uninstalling tensorboard-2.7.0:\n          Successfully uninstalled tensorboard-2.7.0\n      Attempting uninstall: h5py\n        Found existing installation: h5py 3.1.0\n        Uninstalling h5py-3.1.0:\n          Successfully uninstalled h5py-3.1.0\n      Attempting uninstall: gast\n        Found existing installation: gast 0.4.0\n        Uninstalling gast-0.4.0:\n          Successfully uninstalled gast-0.4.0\n      Attempting uninstall: tensorflow\n        Found existing installation: tensorflow 2.7.0\n        Uninstalling tensorflow-2.7.0:\n          Successfully uninstalled tensorflow-2.7.0\n    Successfully installed gast-0.3.3 h5py-2.10.0 tensorboard-2.2.2 tensorflow-2.2.0 tensorflow-estimator-2.2.0\n\n\n\n```python\n!pip install tensorflow_probability=='0.10.0'\n```\n\n    Collecting tensorflow_probability==0.10.0\n      Downloading tensorflow_probability-0.10.0-py2.py3-none-any.whl (3.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.5 MB 14.2 MB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.13.3 in /usr/local/lib/python3.7/dist-packages (from tensorflow_probability==0.10.0) (1.19.5)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.7/dist-packages (from tensorflow_probability==0.10.0) (4.4.2)\n    Requirement already satisfied: gast>=0.3.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow_probability==0.10.0) (0.3.3)\n    Requirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow_probability==0.10.0) (1.15.0)\n    Requirement already satisfied: cloudpickle>=1.2.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow_probability==0.10.0) (1.3.0)\n    Installing collected packages: tensorflow-probability\n      Attempting uninstall: tensorflow-probability\n        Found existing installation: tensorflow-probability 0.15.0\n        Uninstalling tensorflow-probability-0.15.0:\n          Successfully uninstalled tensorflow-probability-0.15.0\n    Successfully installed tensorflow-probability-0.10.0\n\n\n# Programming Assignment\n\n## VAE for the CelebA dataset\n\n### Instructions\nIn this programming assignment, you will implement the variational autoencoder algorithm for an image dataset of celebrity faces. You will use the trained encoder and decoder networks to reconstruct and generate images. You will also see how the latent space encodes high-level information about the images.\n\nSome code cells are provided for you in the notebook. You should avoid editing provided code, and make sure to execute the cells in order to avoid unexpected errors. Some cells begin with the line: \n\n`#### GRADED CELL ####`\n\nDon't move or edit this first line - this is what the automatic grader looks for to recognise graded cells. These cells require you to write your own code to complete them, and are automatically graded when you submit the notebook. Don't edit the function name or signature provided in these cells, otherwise the automatic grader might not function properly.\n\n### How to submit\n\nComplete all the tasks you are asked for in the worksheet. When you have finished and are happy with your code, press the Submit Assignment button at the top of this notebook.\n\n### Let's get started!\n\nWe'll start running some imports, and loading the dataset. Do not edit the existing imports in the following cell. If you would like to make further Tensorflow imports, you should add them here.\n\n\n```python\n#### PACKAGE IMPORTS ####\n\n# Run this cell first to import all required packages. Do not make any imports elsewhere in the notebook\n\nimport tensorflow as tf\nimport tensorflow_probability as tfp\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport os\n\nfrom tensorflow.keras import Sequential, Model\nfrom tensorflow.keras.layers import (Dense, Flatten, Reshape, Concatenate, Conv2D, \n                                     UpSampling2D, BatchNormalization)\ntfd = tfp.distributions\ntfb = tfp.bijectors\ntfpl = tfp.layers\n\n# If you would like to make further imports from tensorflow, add them here\n\n\n```\n\n#### The Large-scale CelebFaces Attributes (CelebA) Dataset\n\nFor this assignment you will use a subset of the CelebFaces Attributes (CelebA) dataset. The full dataset contains over 200K images CelebA contains thousands of colour images of the faces of celebrities, together with tagged attributes such as 'Smiling', 'Wearing glasses', or 'Wearing lipstick'. It also contains information about bounding boxes and facial part localisation. CelebA is a popular dataset that is commonly used for face attribute recognition, face detection, landmark (or facial part) localization, and face editing & synthesis. \n\n* Z. Liu, P. Luo, X. Wang, and X. Tang. \"Deep Learning Face Attributes in the Wild\", Proceedings of International Conference on Computer Vision (ICCV), 2015.\n\nYou can read about the dataset in more detail [here](http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html). \n\nYour goal is to implement the variational autoencoder algorithm for a subset of the CelebA dataset. For practical reasons we will keep the dataset and the network size relatively small.\n\n#### Import the data\n\nThe dataset required for this project can be downloaded from the following link:\n\nhttps://drive.google.com/file/d/1qzbcYRjxO6yU_usb4CXyGObUEjIVYWAp/view?usp=sharing\n\nYou should unzip this file and store in Drive for use in this Colab notebook.\n\n\n```python\n#import zipfile\n#with zipfile.ZipFile(\"/content/drive/MyDrive/Colab_Notebooks/coursera/coursera_Probabilistic_Deep_Learning_TF2/Week4/CelebA subset.zip\",\"r\") as zip_ref:\n#  zip_ref.extractall('CeleAsubset')\n```\n\n\n```python\n# Run this cell to connect to your Drive folder\n\n#from google.colab import drive\n#drive.mount('/content/gdrive')\n```\n\n#### Load the dataset\n\nThe following functions will be useful for loading and preprocessing the dataset. The subset you will use for this assignment consists of 10,000 training images, 1000 validation images and 1000 test images. These examples have been chosen to respect the original training / validation / test split of the dataset.\n\n\n```python\n# Functions for loading and preprocessing the images\n\ndef load_image(filepath):\n    raw_img = tf.io.read_file(filepath) \n    img_tensor_int = tf.image.decode_jpeg(raw_img, channels=3)\n    img_tensor_flt = tf.image.convert_image_dtype(img_tensor_int, tf.float32)\n    return img_tensor_flt, img_tensor_flt\n\ndef load_dataset(split):\n    train_list_ds = tf.data.Dataset.list_files('/content/drive/MyDrive/Colab_Notebooks/coursera/coursera_Probabilistic_Deep_Learning_TF2/Week4/CeleAsubset/{}/*.jpg'.format(split), shuffle=False)\n    train_ds = train_list_ds.map(load_image)\n    return train_ds\n```\n\n\n```python\n# Load the training, validation and testing datasets splits\n\ntrain_ds = load_dataset('train')\nval_ds = load_dataset('val')\ntest_ds = load_dataset('test')\n```\n\n\n```python\n# Display a few examples\n\nn_examples_shown = 6\nf, axs = plt.subplots(1, n_examples_shown, figsize=(16, 3))\n\nfor j, image in enumerate(train_ds.take(n_examples_shown)):\n    axs[j].imshow(image[0])\n    axs[j].axis('off')\n```\n\n\n```python\n# Batch the Dataset objects\n\nbatch_size = 32\ntrain_ds = train_ds.batch(batch_size)\nval_ds = val_ds.batch(batch_size)\ntest_ds = test_ds.batch(batch_size)\n```\n\n#### Mixture of Gaussians distribution\n\nWe will define a prior distribution that is a mixture of Gaussians. This is a more flexible distribution that is comprised of $K$ separate Gaussians, that are combined together with some weighting assigned to each. \n\nRecall that the probability density function for a multivariate Gaussian distribution with mean $\\mu\\in\\mathbb{R}^D$ and covariance matrix $\\Sigma\\in\\mathbb{R}^{D\\times D}$ is given by\n\n$$\n\\mathcal{N}(\\mathbf{z}; \\mathbf{\\mu}, \\Sigma) = \\frac{1}{(2\\pi)^{D/2}|\\Sigma|^{1/2}}\n\\exp\\left(-\\frac{1}{2}(\\mathbf{z}-\\mathbf{\\mu})^T\\Sigma^{-1}(\\mathbf{z}-\\mathbf{\\mu})\\right).\n$$\n\nA mixture of Gaussians with $K$ components defines $K$ Gaussians defined by means $\\mathbf{\\mu}_k$ and covariance matrices $\\Sigma_k$, for $k=1,\\ldots,K$. It also requires mixing coefficients $\\pi_k$, $k=1,\\ldots,K$ with $\\sum_{k} \\pi_k = 1$. These coefficients define a categorical distribution over the $K$ Gaussian components. To sample an event, we first sample from the categorical distribution, and then again from the corresponding Gaussian component.\n\nThe probability density function of the mixture of Gaussians is simply the weighted sum of probability density functions for each Gaussian component:\n\n$$\np(\\mathbf{z}) = \\sum_{k=1}^K \\pi_k \\mathcal{N}(\\mathbf{z}; \\mathbf{\\mu}_k, \\Sigma_k)\n$$\n\n#### Define the prior distribution\n\nYou should now complete the following function to define the mixture of Gaussians distribution for the prior, for a given number of components and latent space dimension. Each Gaussian component will have a diagonal covariance matrix. This distribution will have fixed mixing coefficients, but trainable means and standard deviations. \n\n* The function takes `num_modes` (number of components) and `latent_dim` as arguments\n* Use the `tfd.MixtureSameFamily` for the prior distribution. Take a look at [the documentation](https://www.tensorflow.org/probability/api_docs/python/tfp/distributions/MixtureSameFamily) for this distribution\n  * The constructor takes a `mixture_distribution` and `components_distribution` as required arguments\n  * The `mixture_distribution` should be fixed to a uniform `tfd.Categorical` distribution, so that $pi_k = 1/K$ in the above equation. This argument will therefore not contain any trainable variables\n  * The `components_distribution` should be a `tfd.MultivariateNormalDiag` distribution batch shape equal to `[num_modes]` and event shape equal to `[latent_dim]`. \n    * The `tfd.MultivariateNormalDiag` distribution should have trainable `loc` parameter (initialised with a random normal distribution)  and trainable `scale_diag` parameter (initialised to ones)\n    * The `scale_diag` variable should be enforced to be positive using `tfp.util.TransformedVariable` and the `tfb.Softplus` bijection\n\nThe function should return the instance of the `tfd.MixtureSameFamily` distribution. \n\n\n```python\n#### GRADED CELL ####\n\n# Complete the following function. \n# Make sure to not change the function name or arguments.\n\ndef get_prior(num_modes, latent_dim):\n    \"\"\"\n    This function should create an instance of a MixtureSameFamily distribution \n    according to the above specification. \n    The function takes the num_modes and latent_dim as arguments, which should \n    be used to define the distribution.\n    Your function should then return the distribution instance.\n    \"\"\"\n    mixture_distribution=tfd.Categorical(probs=(1./num_modes)*tf.ones([num_modes,]))\n    components_distribution=tfd.MultivariateNormalDiag(loc=tf.Variable(tf.random.normal([num_modes,latent_dim]),trainable=True,dtype=tf.float32),\n                                                       scale_diag=tfp.util.TransformedVariable(initial_value=tf.ones([num_modes,latent_dim]),\n                                                                                               bijector=tfb.Softplus()))\n    prior=tfp.distributions.MixtureSameFamily(\n    mixture_distribution, components_distribution, reparameterize=False,\n    validate_args=False, allow_nan_stats=True, name='MixtureSameFamily'\n    )\n    return prior\n\n    \n    \n    \n```\n\n\n```python\n# Run your function to get the prior distribution with 2 components and latent_dim = 50\n\nprior = get_prior(num_modes=2, latent_dim=50)\n```\n\n#### Define the encoder network\n\nWe will now define the encoder network as part of the VAE. First, we will define the `KLDivergenceRegularizer` to use in the encoder network to add the KL divergence part of the loss. This should be defined according to the following specification:\n\n* The function takes the `prior_distribution` as an argument\n* The function should use the `tfpl.KLDivergenceRegularizer` object to add the KL loss term\n* The `tfpl.KLDivergenceRegularizer` should use a weight factor of 1.0 for the KL loss (standard ELBO objective)\n* The KL loss cannot be computed exactly, so the `tfpl.KLDivergenceRegularizer` should compute a Monte Carlo approximation by drawing 3 samples from the posterior, and then averaging over the sample and batch axes\n\nYour function should then return the `tfpl.KLDivergenceRegularizer` object.\n\n\n```python\n#### GRADED CELL ####\n\n# Complete the following function. \n# Make sure to not change the function name or arguments.\n\ndef get_kl_regularizer(prior_distribution):\n    \"\"\"\n    This function should create an instance of the KLDivergenceRegularizer \n    according to the above specification. \n    The function takes the prior_distribution, which should be used to define \n    the distribution.\n    Your function should then return the KLDivergenceRegularizer instance.\n    \"\"\"\n    divergence_regularizer = tfpl.KLDivergenceRegularizer(prior_distribution,\n                                                          use_exact_kl=False,\n                                                          test_points_fn=lambda q: q.sample(3),\n                                                          test_points_reduce_axis=(0,1),\n                                                          weight=1.0)\n    return divergence_regularizer\n    \n    \n```\n\n\n```python\n# Run your function to get the KLDivergenceRegularizer\n\nkl_regularizer = get_kl_regularizer(prior)\n```\n\nYou should now complete the following function to define the encoder network, according to the following specification:\n\n* The function takes the `latent_dim` and `kl_regularizer` as arguments\n* Use the `Sequential` class to define the model\n  * The first layer should be a Conv2D layer with 32 filters, 4x4 kernel size, ReLU activation, stride of 2x2, and 'SAME' padding. It should also set the `input_shape` to `(64, 64, 3)`\n  * The second layer should be a BatchNormalization layer\n  * The third layer should be a Conv2D layer with 64 filters, 4x4 kernel size, ReLU activation, stride of 2x2, and 'SAME' padding\n  * The fourth layer should be a BatchNormalization layer\n  * The fifth layer should be a Conv2D layer with 128 filters, 4x4 kernel size, ReLU activation, stride of 2x2, and 'SAME' padding\n  * The sixth layer should be a BatchNormalization layer\n  * The seventh layer should be a Conv2D layer with 256 filters, 4x4 kernel size, ReLU activation, stride of 2x2, and 'SAME' padding\n  * The eighth layer should be a BatchNormalization layer\n  * The ninth layer should be a Flatten layer\n  * The tenth layer should be a Dense layer with no activation function, and the right number of units to parameterise a `MultivariateNormalTriL` layer with event size equal to `latent_dim`\n  * The final layer should be a `MultivariateNormalTriL` layer with event size equal to `latent_dim`, and it should use the `kl_regularizer` passed in as the argument as the activity regularizer\n\nIn total, your model should have 11 layers.\n\nThe function should then return the encoder model.\n\n\n```python\n#### GRADED CELL ####\n\n# Complete the following function. \n# Make sure to not change the function name or arguments.\n\ndef get_encoder(latent_dim, kl_regularizer):\n    \"\"\"\n    This function should build a CNN encoder model according to the above specification. \n    The function takes latent_dim and kl_regularizer as arguments, which should be\n    used to define the model.\n    Your function should return the encoder model.\n    \"\"\"\n    encoder=Sequential([\n                    Conv2D(32,(4,4),strides=(2,2),activation='relu',padding='SAME',input_shape=(64,64,3)),\n                    BatchNormalization(),\n                    Conv2D(64,(4,4),strides=(2,2),activation='relu',padding='SAME'),\n                    BatchNormalization(),  \n                    Conv2D(128,(4,4),strides=(2,2),activation='relu',padding='SAME'),\n                    BatchNormalization(),     \n                    Conv2D(256,(4,4),strides=(2,2),activation='relu',padding='SAME'),\n                    BatchNormalization(),  \n                    Flatten(),              \n                    Dense(tfpl.MultivariateNormalTriL.params_size(latent_dim)),\n                    tfpl.MultivariateNormalTriL(latent_dim,activity_regularizer=kl_regularizer)])\n    return encoder\n    \n    \n```\n\n\n```python\n#\u00a0Run your function to get the encoder\n\nencoder = get_encoder(latent_dim=50, kl_regularizer=kl_regularizer)\n```\n\n    WARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/linalg/linear_operator_lower_triangular.py:158: calling LinearOperator.__init__ (from tensorflow.python.ops.linalg.linear_operator) with graph_parents is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Do not pass `graph_parents`.  They will  no longer be used.\n\n\n\n```python\n# Print the encoder summary\n\nencoder.summary()\n```\n\n    Model: \"sequential\"\n    _________________________________________________________________\n    Layer (type)                 Output Shape              Param #   \n    =================================================================\n    conv2d (Conv2D)              (None, 32, 32, 32)        1568      \n    _________________________________________________________________\n    batch_normalization (BatchNo (None, 32, 32, 32)        128       \n    _________________________________________________________________\n    conv2d_1 (Conv2D)            (None, 16, 16, 64)        32832     \n    _________________________________________________________________\n    batch_normalization_1 (Batch (None, 16, 16, 64)        256       \n    _________________________________________________________________\n    conv2d_2 (Conv2D)            (None, 8, 8, 128)         131200    \n    _________________________________________________________________\n    batch_normalization_2 (Batch (None, 8, 8, 128)         512       \n    _________________________________________________________________\n    conv2d_3 (Conv2D)            (None, 4, 4, 256)         524544    \n    _________________________________________________________________\n    batch_normalization_3 (Batch (None, 4, 4, 256)         1024      \n    _________________________________________________________________\n    flatten (Flatten)            (None, 4096)              0         \n    _________________________________________________________________\n    dense (Dense)                (None, 1325)              5428525   \n    _________________________________________________________________\n    multivariate_normal_tri_l (M ((None, 50), (None, 50))  200       \n    =================================================================\n    Total params: 6,120,789\n    Trainable params: 6,119,829\n    Non-trainable params: 960\n    _________________________________________________________________\n\n\n#### Define the decoder network\n\nYou should now define the decoder network for the VAE, using the `Sequential` API. This should be a neural network that returns an IndependentBernoulli distribution of `event_shape=(64, 64, 3)`.\n\n* The function takes the `latent_dim` as an argument\n* Use the `Sequential` class to define the model\n  * The first layer should be a Dense layer with 4096 units and ReLU activation. It should also set the `input_shape` to `(latent_dim,)`\n  * The second layer should be a Reshape layer, that reshapes its input to `(4, 4, 256)`\n  * The third layer should be an UpSampling2D layer with upsampling factor of `(2, 2)`\n  * The fourth layer should be a Conv2D layer with 128 filters, 3x3 kernel size, ReLU activation, and 'SAME' padding\n  * The fifth layer should be an UpSampling2D layer with upsampling factor of `(2, 2)`\n  * The sixth layer should be a Conv2D layer with 64 filters, 3x3 kernel size, ReLU activation, and 'SAME' padding\n  * The seventh layer should be an UpSampling2D layer with upsampling factor of `(2, 2)`\n  * The eighth layer should be a Conv2D layer with 32 filters, 3x3 kernel size, ReLU activation, and 'SAME' padding\n  * The ninth layer should be an UpSampling2D layer with upsampling factor of `(2, 2)`\n  * The tenth layer should be a Conv2D layer with 128 filters, 3x3 kernel size, ReLU activation, and 'SAME' padding\n  * The eleventh layer should be a Conv2D layer with 3 filters, 3x3 kernel size, no activation function, and 'SAME' padding\n  * The twelfth layer should be a Flatten layer\n  * The final layer should be a `IndependentBernoulli` layer with event size equal to `(64, 64, 3)`\n\nIn total, your model should have 13 layers.\n\nThe function should then return the decoder model.\n\n\n```python\nfrom tensorflow_probability.python.layers.distribution_layer import IndependentBernoulli\n #### GRADED CELL ####\n\n# Complete the following function. \n# Make sure to not change the function name or arguments.\n\ndef get_decoder(latent_dim):\n    \"\"\"\n    This function should build a CNN decoder model according to the above specification. \n    The function takes latent_dim as an argument, which should be used to define the model.\n    Your function should return the decoder model.\n    \"\"\"\n    decoder=Sequential([\n                    Dense(4096,activation='relu',input_shape=(latent_dim,)),\n                    Reshape(target_shape=(4,4,256)),\n                    UpSampling2D(size=(2,2)),\n                    Conv2D(128,(3,3),activation='relu',padding='SAME'),\n                    UpSampling2D(size=(2,2)),\n                    Conv2D(64,(3,3),activation='relu',padding='SAME'),\n                    UpSampling2D(size=(2,2)),\n                    Conv2D(32,(3,3),activation='relu',padding='SAME'),\n                    UpSampling2D(size=(2,2)),\n                    Conv2D(128,(3,3),activation='relu',padding='SAME'),\n                    Conv2D(3,(3,3),padding='SAME'),\n                    Flatten(), \n                    tfpl.IndependentBernoulli(event_shape=(64,64,3))])             \n    return decoder    \n    \n```\n\n\n```python\n# Run your function to get the decoder\n\ndecoder = get_decoder(latent_dim=50)\n```\n\n\n```python\n# Print the decoder summary\n\ndecoder.summary()\n```\n\n    Model: \"sequential_1\"\n    _________________________________________________________________\n    Layer (type)                 Output Shape              Param #   \n    =================================================================\n    dense_1 (Dense)              (None, 4096)              208896    \n    _________________________________________________________________\n    reshape (Reshape)            (None, 4, 4, 256)         0         \n    _________________________________________________________________\n    up_sampling2d (UpSampling2D) (None, 8, 8, 256)         0         \n    _________________________________________________________________\n    conv2d_4 (Conv2D)            (None, 8, 8, 128)         295040    \n    _________________________________________________________________\n    up_sampling2d_1 (UpSampling2 (None, 16, 16, 128)       0         \n    _________________________________________________________________\n    conv2d_5 (Conv2D)            (None, 16, 16, 64)        73792     \n    _________________________________________________________________\n    up_sampling2d_2 (UpSampling2 (None, 32, 32, 64)        0         \n    _________________________________________________________________\n    conv2d_6 (Conv2D)            (None, 32, 32, 32)        18464     \n    _________________________________________________________________\n    up_sampling2d_3 (UpSampling2 (None, 64, 64, 32)        0         \n    _________________________________________________________________\n    conv2d_7 (Conv2D)            (None, 64, 64, 128)       36992     \n    _________________________________________________________________\n    conv2d_8 (Conv2D)            (None, 64, 64, 3)         3459      \n    _________________________________________________________________\n    flatten_1 (Flatten)          (None, 12288)             0         \n    _________________________________________________________________\n    independent_bernoulli (Indep ((None, 64, 64, 3), (None 0         \n    =================================================================\n    Total params: 636,643\n    Trainable params: 636,643\n    Non-trainable params: 0\n    _________________________________________________________________\n\n\n#### Link the encoder and decoder together\n\nThe following cell connects `encoder` and `decoder` to form the end-to-end architecture.\n\n\n```python\n# Connect the encoder and decoder\n\nvae = Model(inputs=encoder.inputs, outputs=decoder(encoder.outputs))\n```\n\n#### Define the average reconstruction loss\n\nYou should now define the reconstruction loss that forms the remaining part of the negative ELBO objective. This function should take a batch of images of shape `(batch_size, 64, 64, 3)` in the first argument, and the output of the decoder after passing the batch of images through `vae` in the second argument. \n\nThe loss should be defined so that it returns\n\\begin{equation}\n    -\\frac{1}{n}\\sum_{i=1}^n \\log p(x_i|z_i)\n\\end{equation}\nwhere $n$ is the batch size and $z_i$ is sampled from $q(z|x_i)$, the encoding distribution a.k.a. the approximate posterior. The value of this expression is always a scalar.\n\nExpression (1) is, as you know, is an estimate of the (negative of the) batch's average expected reconstruction loss:\n\n\\begin{equation}\n    -\\frac{1}{n}\\sum_{i=1}^n \\mathrm{E}_{Z\\sim q(z|x_i)}\\big[\\log p(x_i|Z)\\big]\n\\end{equation}\n\n_Hints_ : \n- _You may find the `log_prob` method of the decoding distribution helpful._\n- _The code you add does not need to be more than one line._\n\n\n```python\n #### GRADED CELL ####\n\n# Complete the following function. \n# Make sure to not change the function name or arguments.\n\ndef reconstruction_loss(batch_of_images, decoding_dist):\n    \"\"\"\n    This function should compute and return the average expected reconstruction loss,\n    as defined above.\n    The function takes batch_of_images (Tensor containing a batch of input images to\n    the encoder) and decoding_dist (output distribution of decoder after passing the \n    image batch through the encoder and decoder) as arguments.\n    The function should return the scalar average expected reconstruction loss.\n    \"\"\"\n    return -tf.reduce_mean(decoding_dist.log_prob(batch_of_images))\n    \n```\n\n####\u00a0Compile and fit the model\n\nIt's now time to compile and train the model. This may take some time, so as an alternative, you can also load a pre-trained model below if you wish.\n\nThe pre-trained model can be downloaded from the following link:\n\nhttps://drive.google.com/file/d/15JMM4Pw4lnYvgR_5WOjW8ttkhglTGOGq/view?usp=sharing\n\nYou should unzip this file and store in Drive for use in this Colab notebook.\n\n\n```python\n# Compile the model\n\noptimizer = tf.keras.optimizers.Adam(learning_rate=0.0005)\nvae.compile(optimizer=optimizer, loss=reconstruction_loss)\n```\n\n\n```python\n# EITHER... compile and fit the model\n\nvae.fit(train_ds, validation_data=val_ds, epochs=1000)\n```\n\n    Epoch 1/1000\n    313/313 [==============================] - 23s 74ms/step - loss: 7140.3750 - val_loss: 7029.6094\n    Epoch 2/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6717.7231 - val_loss: 6613.9370\n    Epoch 3/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6590.0298 - val_loss: 6562.4009\n    Epoch 4/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6516.4360 - val_loss: 6494.5234\n    Epoch 5/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6465.1475 - val_loss: 6452.4707\n    Epoch 6/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6427.2642 - val_loss: 6425.9302\n    Epoch 7/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6397.0498 - val_loss: 6392.1162\n    Epoch 8/1000\n    313/313 [==============================] - 15s 47ms/step - loss: 6368.1182 - val_loss: 6368.2822\n    Epoch 9/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6346.4595 - val_loss: 6357.8218\n    Epoch 10/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6327.4053 - val_loss: 6337.4731\n    Epoch 11/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6308.6318 - val_loss: 6321.9810\n    Epoch 12/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6292.5845 - val_loss: 6318.3760\n    Epoch 13/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6278.9614 - val_loss: 6299.2368\n    Epoch 14/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6266.1343 - val_loss: 6296.1660\n    Epoch 15/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6255.6631 - val_loss: 6280.7544\n    Epoch 16/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6245.7036 - val_loss: 6280.8354\n    Epoch 17/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6238.1211 - val_loss: 6285.6343\n    Epoch 18/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6231.7163 - val_loss: 6275.7300\n    Epoch 19/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6228.1724 - val_loss: 6275.6265\n    Epoch 20/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6228.5156 - val_loss: 6297.8242\n    Epoch 21/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6235.7964 - val_loss: 6281.5566\n    Epoch 22/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6235.5366 - val_loss: 6317.9849\n    Epoch 23/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6226.6670 - val_loss: 6311.0986\n    Epoch 24/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6217.8613 - val_loss: 6300.5801\n    Epoch 25/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6211.6577 - val_loss: 6322.3906\n    Epoch 26/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6209.3193 - val_loss: 6309.4238\n    Epoch 27/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6206.9287 - val_loss: 6325.4648\n    Epoch 28/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6209.3843 - val_loss: 6300.6548\n    Epoch 29/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6213.9863 - val_loss: 6283.5161\n    Epoch 30/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6215.8965 - val_loss: 6304.6445\n    Epoch 31/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6214.6631 - val_loss: 6320.8872\n    Epoch 32/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6209.1494 - val_loss: 6334.1738\n    Epoch 33/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6203.8086 - val_loss: 6321.6738\n    Epoch 34/1000\n    313/313 [==============================] - 14s 46ms/step - loss: 6196.0234 - val_loss: 6292.6641\n    Epoch 35/1000\n    313/313 [==============================] - 13s 43ms/step - loss: 6189.5342 - val_loss: 6291.5796\n    Epoch 36/1000\n    313/313 [==============================] - 13s 43ms/step - loss: 6183.7935 - val_loss: 6281.3398\n    Epoch 37/1000\n    313/313 [==============================] - 14s 44ms/step - loss: 6179.5591 - val_loss: 6272.2119\n    Epoch 38/1000\n    313/313 [==============================] - 14s 46ms/step - loss: 6176.8130 - val_loss: 6267.2437\n    Epoch 39/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6176.3193 - val_loss: 6266.9087\n    Epoch 40/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6177.6309 - val_loss: 6272.8877\n    Epoch 41/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6181.6309 - val_loss: 6295.2065\n    Epoch 42/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6183.2510 - val_loss: 6318.3550\n    Epoch 43/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6185.4077 - val_loss: 6330.8203\n    Epoch 44/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6186.2783 - val_loss: 6322.1548\n    Epoch 45/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6179.8442 - val_loss: 6313.3364\n    Epoch 46/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6174.6846 - val_loss: 6309.3560\n    Epoch 47/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6172.1235 - val_loss: 6320.8379\n    Epoch 48/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6172.0786 - val_loss: 6327.1216\n    Epoch 49/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6175.9722 - val_loss: 6351.2905\n    Epoch 50/1000\n    313/313 [==============================] - 14s 44ms/step - loss: 6184.7207 - val_loss: 6351.1255\n    Epoch 51/1000\n    313/313 [==============================] - 14s 45ms/step - loss: 6188.4492 - val_loss: 6326.7153\n    Epoch 52/1000\n    313/313 [==============================] - 14s 44ms/step - loss: 6181.8267 - val_loss: 6303.0356\n    Epoch 53/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6172.1777 - val_loss: 6290.7500\n    Epoch 54/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6163.7764 - val_loss: 6290.8345\n    Epoch 55/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6158.3560 - val_loss: 6287.3027\n    Epoch 56/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6153.9995 - val_loss: 6279.5537\n    Epoch 57/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6150.7461 - val_loss: 6274.3340\n    Epoch 58/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6149.0977 - val_loss: 6278.8081\n    Epoch 59/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6148.7275 - val_loss: 6288.4390\n    Epoch 60/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6151.4736 - val_loss: 6300.9014\n    Epoch 61/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6155.4170 - val_loss: 6331.1392\n    Epoch 62/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6158.7246 - val_loss: 6299.7129\n    Epoch 63/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6156.1382 - val_loss: 6279.1250\n    Epoch 64/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6150.3462 - val_loss: 6266.8984\n    Epoch 65/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6146.7417 - val_loss: 6264.8916\n    Epoch 66/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6146.3750 - val_loss: 6266.9521\n    Epoch 67/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6147.6421 - val_loss: 6264.5151\n    Epoch 68/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6150.6821 - val_loss: 6270.8301\n    Epoch 69/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6152.2710 - val_loss: 6269.8765\n    Epoch 70/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6150.0942 - val_loss: 6269.8516\n    Epoch 71/1000\n    313/313 [==============================] - 16s 53ms/step - loss: 6150.1060 - val_loss: 6269.8794\n    Epoch 72/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6148.9746 - val_loss: 6263.8096\n    Epoch 73/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6148.8643 - val_loss: 6265.8423\n    Epoch 74/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6147.1958 - val_loss: 6269.2285\n    Epoch 75/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6147.0928 - val_loss: 6270.7910\n    Epoch 76/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6149.8550 - val_loss: 6273.5718\n    Epoch 77/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6152.3237 - val_loss: 6266.6294\n    Epoch 78/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6160.7632 - val_loss: 6284.1421\n    Epoch 79/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6163.1079 - val_loss: 6315.7388\n    Epoch 80/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6161.0195 - val_loss: 6309.1323\n    Epoch 81/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6156.5850 - val_loss: 6294.1973\n    Epoch 82/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6153.6094 - val_loss: 6294.2925\n    Epoch 83/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6151.6919 - val_loss: 6278.0176\n    Epoch 84/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6150.2002 - val_loss: 6289.6396\n    Epoch 85/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6147.9590 - val_loss: 6299.0947\n    Epoch 86/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6145.6855 - val_loss: 6293.3506\n    Epoch 87/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6141.9165 - val_loss: 6282.4233\n    Epoch 88/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6138.6030 - val_loss: 6289.2754\n    Epoch 89/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6134.6636 - val_loss: 6286.0894\n    Epoch 90/1000\n    313/313 [==============================] - 14s 45ms/step - loss: 6131.2637 - val_loss: 6282.8174\n    Epoch 91/1000\n    313/313 [==============================] - 14s 45ms/step - loss: 6128.5205 - val_loss: 6283.8696\n    Epoch 92/1000\n    313/313 [==============================] - 13s 43ms/step - loss: 6127.3721 - val_loss: 6284.3804\n    Epoch 93/1000\n    313/313 [==============================] - 14s 43ms/step - loss: 6125.6738 - val_loss: 6273.6494\n    Epoch 94/1000\n    313/313 [==============================] - 13s 43ms/step - loss: 6124.3828 - val_loss: 6277.0518\n    Epoch 95/1000\n    313/313 [==============================] - 13s 42ms/step - loss: 6124.3809 - val_loss: 6283.6787\n    Epoch 96/1000\n    313/313 [==============================] - 13s 42ms/step - loss: 6125.7705 - val_loss: 6294.7388\n    Epoch 97/1000\n    313/313 [==============================] - 13s 43ms/step - loss: 6128.0410 - val_loss: 6299.2021\n    Epoch 98/1000\n    313/313 [==============================] - 13s 43ms/step - loss: 6131.1665 - val_loss: 6309.3286\n    Epoch 99/1000\n    313/313 [==============================] - 13s 43ms/step - loss: 6134.6631 - val_loss: 6337.6514\n    Epoch 100/1000\n    313/313 [==============================] - 13s 43ms/step - loss: 6135.8198 - val_loss: 6362.9028\n    Epoch 101/1000\n    313/313 [==============================] - 13s 43ms/step - loss: 6133.8472 - val_loss: 6356.4429\n    Epoch 102/1000\n    313/313 [==============================] - 13s 43ms/step - loss: 6130.3452 - val_loss: 6350.0244\n    Epoch 103/1000\n    313/313 [==============================] - 13s 43ms/step - loss: 6126.9609 - val_loss: 6337.3896\n    Epoch 104/1000\n    313/313 [==============================] - 13s 43ms/step - loss: 6123.6265 - val_loss: 6332.4775\n    Epoch 105/1000\n    313/313 [==============================] - 14s 44ms/step - loss: 6121.3608 - val_loss: 6326.9121\n    Epoch 106/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6120.0186 - val_loss: 6327.9805\n    Epoch 107/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6120.0908 - val_loss: 6328.5557\n    Epoch 108/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6121.7910 - val_loss: 6331.7114\n    Epoch 109/1000\n    313/313 [==============================] - 15s 50ms/step - loss: 6124.1899 - val_loss: 6303.8950\n    Epoch 110/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6122.0674 - val_loss: 6295.1211\n    Epoch 111/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6118.8838 - val_loss: 6294.1519\n    Epoch 112/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6117.2158 - val_loss: 6303.8198\n    Epoch 113/1000\n    313/313 [==============================] - 17s 53ms/step - loss: 6117.1006 - val_loss: 6298.1206\n    Epoch 114/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6118.1157 - val_loss: 6305.1318\n    Epoch 115/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6119.5391 - val_loss: 6324.6792\n    Epoch 116/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6122.9077 - val_loss: 6331.9414\n    Epoch 117/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6127.1816 - val_loss: 6317.9229\n    Epoch 118/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6132.6338 - val_loss: 6318.0762\n    Epoch 119/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6137.3921 - val_loss: 6328.0186\n    Epoch 120/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6139.7998 - val_loss: 6332.6919\n    Epoch 121/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6134.3726 - val_loss: 6346.2271\n    Epoch 122/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6128.2988 - val_loss: 6347.9385\n    Epoch 123/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6122.3638 - val_loss: 6346.8125\n    Epoch 124/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6116.8286 - val_loss: 6346.8804\n    Epoch 125/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6112.5659 - val_loss: 6337.7192\n    Epoch 126/1000\n    313/313 [==============================] - 14s 45ms/step - loss: 6109.2075 - val_loss: 6333.7329\n    Epoch 127/1000\n    313/313 [==============================] - 15s 47ms/step - loss: 6107.4912 - val_loss: 6339.3950\n    Epoch 128/1000\n    313/313 [==============================] - 15s 46ms/step - loss: 6105.3076 - val_loss: 6338.2837\n    Epoch 129/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6104.0493 - val_loss: 6351.4238\n    Epoch 130/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6102.7754 - val_loss: 6352.1201\n    Epoch 131/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6102.2769 - val_loss: 6340.5039\n    Epoch 132/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6101.8018 - val_loss: 6330.2881\n    Epoch 133/1000\n    313/313 [==============================] - 17s 53ms/step - loss: 6102.6758 - val_loss: 6330.8784\n    Epoch 134/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6103.3672 - val_loss: 6348.7744\n    Epoch 135/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6103.2417 - val_loss: 6325.5396\n    Epoch 136/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6102.2402 - val_loss: 6326.9902\n    Epoch 137/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6101.6294 - val_loss: 6376.2935\n    Epoch 138/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6103.4458 - val_loss: 6381.8120\n    Epoch 139/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6106.4170 - val_loss: 6353.1934\n    Epoch 140/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6111.9102 - val_loss: 6316.3467\n    Epoch 141/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6116.5654 - val_loss: 6305.2573\n    Epoch 142/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6119.1509 - val_loss: 6309.3574\n    Epoch 143/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6121.6934 - val_loss: 6305.6284\n    Epoch 144/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6124.8638 - val_loss: 6303.7803\n    Epoch 145/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6128.2363 - val_loss: 6297.8135\n    Epoch 146/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6128.3394 - val_loss: 6299.2114\n    Epoch 147/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6125.8394 - val_loss: 6294.3530\n    Epoch 148/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6124.3979 - val_loss: 6300.8999\n    Epoch 149/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6121.8682 - val_loss: 6301.8730\n    Epoch 150/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6118.3301 - val_loss: 6302.2290\n    Epoch 151/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6115.4922 - val_loss: 6297.4209\n    Epoch 152/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6113.1738 - val_loss: 6295.7061\n    Epoch 153/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6109.9590 - val_loss: 6295.1035\n    Epoch 154/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6107.4258 - val_loss: 6296.6064\n    Epoch 155/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6105.0698 - val_loss: 6294.8345\n    Epoch 156/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6103.1328 - val_loss: 6294.6299\n    Epoch 157/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6101.4131 - val_loss: 6292.7632\n    Epoch 158/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6100.1323 - val_loss: 6291.3120\n    Epoch 159/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6100.1362 - val_loss: 6293.4507\n    Epoch 160/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6100.9458 - val_loss: 6290.7964\n    Epoch 161/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6103.9810 - val_loss: 6293.7788\n    Epoch 162/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6107.8838 - val_loss: 6301.3770\n    Epoch 163/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6111.0566 - val_loss: 6310.9604\n    Epoch 164/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6112.9922 - val_loss: 6297.4258\n    Epoch 165/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6110.0430 - val_loss: 6301.3105\n    Epoch 166/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6107.2119 - val_loss: 6299.4868\n    Epoch 167/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6105.0259 - val_loss: 6304.7417\n    Epoch 168/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6104.8262 - val_loss: 6309.3691\n    Epoch 169/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6105.3755 - val_loss: 6333.4644\n    Epoch 170/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6107.6982 - val_loss: 6343.9146\n    Epoch 171/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6109.7886 - val_loss: 6338.2080\n    Epoch 172/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6111.3955 - val_loss: 6324.7197\n    Epoch 173/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6111.4272 - val_loss: 6325.1216\n    Epoch 174/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6110.8154 - val_loss: 6308.8408\n    Epoch 175/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6109.8584 - val_loss: 6297.2544\n    Epoch 176/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6108.4487 - val_loss: 6296.0337\n    Epoch 177/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6107.0742 - val_loss: 6292.4141\n    Epoch 178/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6105.6182 - val_loss: 6292.6890\n    Epoch 179/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6104.3662 - val_loss: 6289.9604\n    Epoch 180/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6101.7720 - val_loss: 6290.2900\n    Epoch 181/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6099.5654 - val_loss: 6289.8638\n    Epoch 182/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6097.8433 - val_loss: 6287.5854\n    Epoch 183/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6097.0435 - val_loss: 6291.4561\n    Epoch 184/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6096.9839 - val_loss: 6289.8369\n    Epoch 185/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6098.0254 - val_loss: 6289.6304\n    Epoch 186/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6099.1855 - val_loss: 6289.4834\n    Epoch 187/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6099.2930 - val_loss: 6286.3687\n    Epoch 188/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6098.1382 - val_loss: 6291.2515\n    Epoch 189/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6098.1670 - val_loss: 6292.0039\n    Epoch 190/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6098.7593 - val_loss: 6293.9185\n    Epoch 191/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6098.3696 - val_loss: 6297.3398\n    Epoch 192/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6097.4580 - val_loss: 6298.1006\n    Epoch 193/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6096.9214 - val_loss: 6300.0605\n    Epoch 194/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6095.4434 - val_loss: 6296.1934\n    Epoch 195/1000\n    313/313 [==============================] - 15s 50ms/step - loss: 6094.6152 - val_loss: 6301.3208\n    Epoch 196/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6094.8354 - val_loss: 6304.2153\n    Epoch 197/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6095.9180 - val_loss: 6297.9932\n    Epoch 198/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6096.8516 - val_loss: 6297.3350\n    Epoch 199/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6098.3574 - val_loss: 6295.2510\n    Epoch 200/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6100.2656 - val_loss: 6296.2559\n    Epoch 201/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6103.4868 - val_loss: 6300.9365\n    Epoch 202/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6106.9111 - val_loss: 6304.4727\n    Epoch 203/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6112.8887 - val_loss: 6328.5376\n    Epoch 204/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6120.2725 - val_loss: 6339.1558\n    Epoch 205/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6122.3882 - val_loss: 6322.9536\n    Epoch 206/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6119.5669 - val_loss: 6309.6577\n    Epoch 207/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6115.9014 - val_loss: 6306.4434\n    Epoch 208/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6112.4912 - val_loss: 6308.3813\n    Epoch 209/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6110.1118 - val_loss: 6314.6108\n    Epoch 210/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6107.4751 - val_loss: 6313.9814\n    Epoch 211/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6104.4380 - val_loss: 6311.8452\n    Epoch 212/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6102.4106 - val_loss: 6310.7012\n    Epoch 213/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6100.3779 - val_loss: 6309.4697\n    Epoch 214/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6099.0049 - val_loss: 6304.8296\n    Epoch 215/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6097.8364 - val_loss: 6312.6133\n    Epoch 216/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6097.4106 - val_loss: 6326.9321\n    Epoch 217/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6097.4741 - val_loss: 6341.0371\n    Epoch 218/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6099.1577 - val_loss: 6351.4648\n    Epoch 219/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6103.2939 - val_loss: 6327.0762\n    Epoch 220/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6105.2246 - val_loss: 6323.5571\n    Epoch 221/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6103.4541 - val_loss: 6348.4585\n    Epoch 222/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6098.4253 - val_loss: 6338.0547\n    Epoch 223/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6093.9614 - val_loss: 6325.2153\n    Epoch 224/1000\n    313/313 [==============================] - 15s 50ms/step - loss: 6089.8228 - val_loss: 6319.9414\n    Epoch 225/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6087.8530 - val_loss: 6322.7959\n    Epoch 226/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6086.3242 - val_loss: 6331.5723\n    Epoch 227/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6085.5708 - val_loss: 6326.0762\n    Epoch 228/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6084.6680 - val_loss: 6324.3110\n    Epoch 229/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6083.9937 - val_loss: 6313.2661\n    Epoch 230/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6083.4526 - val_loss: 6305.2490\n    Epoch 231/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6082.6309 - val_loss: 6303.6328\n    Epoch 232/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6082.4941 - val_loss: 6303.0356\n    Epoch 233/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6082.0195 - val_loss: 6307.1870\n    Epoch 234/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6082.3384 - val_loss: 6307.1284\n    Epoch 235/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6083.2588 - val_loss: 6306.9883\n    Epoch 236/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6085.6172 - val_loss: 6312.2520\n    Epoch 237/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6086.9912 - val_loss: 6308.8179\n    Epoch 238/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6087.5889 - val_loss: 6369.4541\n    Epoch 239/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6086.1416 - val_loss: 6323.0337\n    Epoch 240/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6084.6880 - val_loss: 6299.8921\n    Epoch 241/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6085.2534 - val_loss: 6302.7988\n    Epoch 242/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6086.8257 - val_loss: 6313.2798\n    Epoch 243/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6088.5332 - val_loss: 6324.4341\n    Epoch 244/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6090.6143 - val_loss: 6334.6440\n    Epoch 245/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6092.0898 - val_loss: 6347.8887\n    Epoch 246/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6093.3481 - val_loss: 6354.3418\n    Epoch 247/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6094.0952 - val_loss: 6353.2358\n    Epoch 248/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6094.9082 - val_loss: 6351.5449\n    Epoch 249/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6095.6089 - val_loss: 6342.7690\n    Epoch 250/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6097.3242 - val_loss: 6337.7637\n    Epoch 251/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6097.7876 - val_loss: 6348.3281\n    Epoch 252/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6098.5933 - val_loss: 6385.6406\n    Epoch 253/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6097.7090 - val_loss: 6384.7656\n    Epoch 254/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6095.2520 - val_loss: 6370.0068\n    Epoch 255/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6092.8438 - val_loss: 6361.6284\n    Epoch 256/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6090.9136 - val_loss: 6364.9663\n    Epoch 257/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6089.7734 - val_loss: 6362.8931\n    Epoch 258/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6089.0557 - val_loss: 6353.2769\n    Epoch 259/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6088.3926 - val_loss: 6346.7261\n    Epoch 260/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6087.9590 - val_loss: 6336.1724\n    Epoch 261/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6087.5269 - val_loss: 6327.9795\n    Epoch 262/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6086.0469 - val_loss: 6324.3721\n    Epoch 263/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6085.3750 - val_loss: 6325.2466\n    Epoch 264/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6085.4297 - val_loss: 6325.3472\n    Epoch 265/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6085.6230 - val_loss: 6331.4224\n    Epoch 266/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6086.4424 - val_loss: 6334.2202\n    Epoch 267/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6087.9336 - val_loss: 6342.9419\n    Epoch 268/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6090.5933 - val_loss: 6354.9883\n    Epoch 269/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6095.0498 - val_loss: 6362.0054\n    Epoch 270/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6103.1372 - val_loss: 6372.9121\n    Epoch 271/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6109.6909 - val_loss: 6352.0659\n    Epoch 272/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6107.7773 - val_loss: 6349.0708\n    Epoch 273/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6101.4146 - val_loss: 6357.5830\n    Epoch 274/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6096.1392 - val_loss: 6382.7788\n    Epoch 275/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6092.7705 - val_loss: 6384.2559\n    Epoch 276/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6089.8774 - val_loss: 6393.9053\n    Epoch 277/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6087.6484 - val_loss: 6406.7168\n    Epoch 278/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6086.2852 - val_loss: 6402.5703\n    Epoch 279/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6084.6138 - val_loss: 6395.9233\n    Epoch 280/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6083.0400 - val_loss: 6391.6548\n    Epoch 281/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6081.0278 - val_loss: 6389.3799\n    Epoch 282/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6079.4355 - val_loss: 6394.6909\n    Epoch 283/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6077.9365 - val_loss: 6385.1040\n    Epoch 284/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6076.5469 - val_loss: 6385.6484\n    Epoch 285/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6075.3828 - val_loss: 6378.2407\n    Epoch 286/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6074.3613 - val_loss: 6378.0337\n    Epoch 287/1000\n    313/313 [==============================] - 15s 47ms/step - loss: 6073.7900 - val_loss: 6368.2979\n    Epoch 288/1000\n    313/313 [==============================] - 15s 47ms/step - loss: 6073.0859 - val_loss: 6370.9829\n    Epoch 289/1000\n    313/313 [==============================] - 15s 46ms/step - loss: 6072.7349 - val_loss: 6364.8643\n    Epoch 290/1000\n    313/313 [==============================] - 15s 50ms/step - loss: 6073.8706 - val_loss: 6358.0142\n    Epoch 291/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6077.9023 - val_loss: 6350.0737\n    Epoch 292/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6084.1118 - val_loss: 6354.0449\n    Epoch 293/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6080.3574 - val_loss: 6352.8389\n    Epoch 294/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6075.0615 - val_loss: 6355.2588\n    Epoch 295/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6072.1680 - val_loss: 6344.7339\n    Epoch 296/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6071.0400 - val_loss: 6344.9033\n    Epoch 297/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6069.9912 - val_loss: 6341.6465\n    Epoch 298/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6069.4233 - val_loss: 6342.9072\n    Epoch 299/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6069.0454 - val_loss: 6340.4922\n    Epoch 300/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6068.9917 - val_loss: 6338.9663\n    Epoch 301/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6068.7568 - val_loss: 6345.9966\n    Epoch 302/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6068.8579 - val_loss: 6356.5649\n    Epoch 303/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6068.8442 - val_loss: 6350.7856\n    Epoch 304/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6069.7651 - val_loss: 6351.0967\n    Epoch 305/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6072.2720 - val_loss: 6345.2310\n    Epoch 306/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6074.9692 - val_loss: 6322.2891\n    Epoch 307/1000\n    313/313 [==============================] - 16s 53ms/step - loss: 6076.7319 - val_loss: 6320.7500\n    Epoch 308/1000\n    313/313 [==============================] - 17s 53ms/step - loss: 6076.6650 - val_loss: 6332.6880\n    Epoch 309/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6076.0249 - val_loss: 6345.1284\n    Epoch 310/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6077.9258 - val_loss: 6348.8071\n    Epoch 311/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6079.4590 - val_loss: 6340.8071\n    Epoch 312/1000\n    313/313 [==============================] - 17s 55ms/step - loss: 6079.8730 - val_loss: 6331.7642\n    Epoch 313/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6080.5269 - val_loss: 6325.9502\n    Epoch 314/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6081.2910 - val_loss: 6323.6138\n    Epoch 315/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6082.3369 - val_loss: 6330.3862\n    Epoch 316/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6083.9590 - val_loss: 6329.4858\n    Epoch 317/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6086.1060 - val_loss: 6336.9600\n    Epoch 318/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6088.3906 - val_loss: 6344.5571\n    Epoch 319/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6090.8774 - val_loss: 6347.9302\n    Epoch 320/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6092.3267 - val_loss: 6334.9531\n    Epoch 321/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6093.0649 - val_loss: 6340.9053\n    Epoch 322/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6092.1426 - val_loss: 6334.4331\n    Epoch 323/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6089.9360 - val_loss: 6327.0537\n    Epoch 324/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6086.8330 - val_loss: 6322.0527\n    Epoch 325/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6083.6387 - val_loss: 6321.4053\n    Epoch 326/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6081.7178 - val_loss: 6325.2964\n    Epoch 327/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6080.3042 - val_loss: 6326.9917\n    Epoch 328/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6079.1875 - val_loss: 6326.3257\n    Epoch 329/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6078.3516 - val_loss: 6337.4883\n    Epoch 330/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6077.7285 - val_loss: 6332.5781\n    Epoch 331/1000\n    313/313 [==============================] - 17s 54ms/step - loss: 6077.1465 - val_loss: 6337.2192\n    Epoch 332/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6076.3013 - val_loss: 6343.5825\n    Epoch 333/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6075.4575 - val_loss: 6338.0688\n    Epoch 334/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6075.3198 - val_loss: 6335.9878\n    Epoch 335/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6074.7358 - val_loss: 6332.3252\n    Epoch 336/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6075.6694 - val_loss: 6323.2212\n    Epoch 337/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6077.2173 - val_loss: 6315.8525\n    Epoch 338/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6081.5601 - val_loss: 6329.9702\n    Epoch 339/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6088.4595 - val_loss: 6333.5132\n    Epoch 340/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6093.4233 - val_loss: 6330.6279\n    Epoch 341/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6092.6919 - val_loss: 6321.0151\n    Epoch 342/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6089.8169 - val_loss: 6316.9863\n    Epoch 343/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6084.7910 - val_loss: 6315.7485\n    Epoch 344/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6080.9102 - val_loss: 6313.2578\n    Epoch 345/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6078.9863 - val_loss: 6315.1396\n    Epoch 346/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6077.8013 - val_loss: 6314.7334\n    Epoch 347/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6076.6895 - val_loss: 6317.0430\n    Epoch 348/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6076.0972 - val_loss: 6318.2935\n    Epoch 349/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6074.9600 - val_loss: 6316.3848\n    Epoch 350/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6073.7041 - val_loss: 6318.5146\n    Epoch 351/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6072.4321 - val_loss: 6320.1196\n    Epoch 352/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6071.1626 - val_loss: 6322.3896\n    Epoch 353/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6070.3164 - val_loss: 6322.7866\n    Epoch 354/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6069.4287 - val_loss: 6323.4458\n    Epoch 355/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6069.1343 - val_loss: 6325.6587\n    Epoch 356/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6069.9502 - val_loss: 6319.7339\n    Epoch 357/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6071.2075 - val_loss: 6325.8979\n    Epoch 358/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6073.5190 - val_loss: 6322.5278\n    Epoch 359/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6072.7197 - val_loss: 6314.2778\n    Epoch 360/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6070.6636 - val_loss: 6321.7476\n    Epoch 361/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6069.4443 - val_loss: 6333.7998\n    Epoch 362/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6069.4565 - val_loss: 6336.5908\n    Epoch 363/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6070.6826 - val_loss: 6320.9487\n    Epoch 364/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6073.3896 - val_loss: 6317.7012\n    Epoch 365/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6076.7534 - val_loss: 6323.6475\n    Epoch 366/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6078.4453 - val_loss: 6332.7402\n    Epoch 367/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6080.0439 - val_loss: 6334.5205\n    Epoch 368/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6083.1738 - val_loss: 6372.8184\n    Epoch 369/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6087.4307 - val_loss: 6376.2554\n    Epoch 370/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6089.8521 - val_loss: 6333.3765\n    Epoch 371/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6088.3140 - val_loss: 6322.2427\n    Epoch 372/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6084.9028 - val_loss: 6330.3721\n    Epoch 373/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6082.4248 - val_loss: 6335.7979\n    Epoch 374/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6081.0952 - val_loss: 6338.0098\n    Epoch 375/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6080.2378 - val_loss: 6340.5557\n    Epoch 376/1000\n    313/313 [==============================] - 15s 50ms/step - loss: 6079.5234 - val_loss: 6347.1313\n    Epoch 377/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6078.6274 - val_loss: 6341.5391\n    Epoch 378/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6077.9097 - val_loss: 6346.6602\n    Epoch 379/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6077.2734 - val_loss: 6349.0713\n    Epoch 380/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6076.3843 - val_loss: 6351.5894\n    Epoch 381/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6075.8838 - val_loss: 6345.3687\n    Epoch 382/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6076.4502 - val_loss: 6343.1299\n    Epoch 383/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6077.9702 - val_loss: 6352.0542\n    Epoch 384/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6082.0630 - val_loss: 6367.6436\n    Epoch 385/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6089.0229 - val_loss: 6317.0259\n    Epoch 386/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6096.5698 - val_loss: 6310.0269\n    Epoch 387/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6092.9077 - val_loss: 6311.4326\n    Epoch 388/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6084.7593 - val_loss: 6313.6655\n    Epoch 389/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6079.6133 - val_loss: 6313.9424\n    Epoch 390/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6076.3853 - val_loss: 6316.3086\n    Epoch 391/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6074.7090 - val_loss: 6319.7754\n    Epoch 392/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6073.3384 - val_loss: 6315.9932\n    Epoch 393/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6072.3794 - val_loss: 6314.3511\n    Epoch 394/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6070.9873 - val_loss: 6318.0615\n    Epoch 395/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6070.1802 - val_loss: 6321.0947\n    Epoch 396/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6069.2666 - val_loss: 6320.5527\n    Epoch 397/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6068.3823 - val_loss: 6322.0474\n    Epoch 398/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6068.0562 - val_loss: 6321.2095\n    Epoch 399/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6067.6182 - val_loss: 6321.5488\n    Epoch 400/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6067.7510 - val_loss: 6324.4976\n    Epoch 401/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6069.1704 - val_loss: 6314.5317\n    Epoch 402/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6071.7056 - val_loss: 6322.2852\n    Epoch 403/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6072.6807 - val_loss: 6321.1919\n    Epoch 404/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6071.2432 - val_loss: 6321.8574\n    Epoch 405/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6069.8716 - val_loss: 6319.1812\n    Epoch 406/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6069.1748 - val_loss: 6317.4126\n    Epoch 407/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6069.4297 - val_loss: 6324.1064\n    Epoch 408/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6070.3130 - val_loss: 6343.0469\n    Epoch 409/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6071.4360 - val_loss: 6332.6909\n    Epoch 410/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6073.0371 - val_loss: 6325.4048\n    Epoch 411/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6074.5317 - val_loss: 6324.8408\n    Epoch 412/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6076.1045 - val_loss: 6324.0825\n    Epoch 413/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6077.8384 - val_loss: 6332.4375\n    Epoch 414/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6079.1816 - val_loss: 6346.4888\n    Epoch 415/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6081.3838 - val_loss: 6342.7100\n    Epoch 416/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6084.5508 - val_loss: 6351.2510\n    Epoch 417/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6086.7554 - val_loss: 6377.0425\n    Epoch 418/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6087.6978 - val_loss: 6383.2456\n    Epoch 419/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6087.4678 - val_loss: 6356.1836\n    Epoch 420/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6087.4600 - val_loss: 6357.2998\n    Epoch 421/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6087.9756 - val_loss: 6362.1060\n    Epoch 422/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6088.5117 - val_loss: 6384.5049\n    Epoch 423/1000\n    313/313 [==============================] - 17s 55ms/step - loss: 6088.7334 - val_loss: 6390.8940\n    Epoch 424/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6088.6611 - val_loss: 6374.7153\n    Epoch 425/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6088.2998 - val_loss: 6339.9526\n    Epoch 426/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6088.0659 - val_loss: 6328.9224\n    Epoch 427/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6086.2446 - val_loss: 6339.2388\n    Epoch 428/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6083.6318 - val_loss: 6331.8745\n    Epoch 429/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6081.1084 - val_loss: 6336.5098\n    Epoch 430/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6078.7563 - val_loss: 6344.2939\n    Epoch 431/1000\n    313/313 [==============================] - 15s 47ms/step - loss: 6076.4609 - val_loss: 6344.0259\n    Epoch 432/1000\n    313/313 [==============================] - 14s 46ms/step - loss: 6075.0132 - val_loss: 6342.4404\n    Epoch 433/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6073.1567 - val_loss: 6343.0020\n    Epoch 434/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6071.4155 - val_loss: 6339.8838\n    Epoch 435/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6069.8042 - val_loss: 6340.8423\n    Epoch 436/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6068.4707 - val_loss: 6334.6206\n    Epoch 437/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6067.1982 - val_loss: 6333.6304\n    Epoch 438/1000\n    313/313 [==============================] - 13s 43ms/step - loss: 6065.7324 - val_loss: 6329.0752\n    Epoch 439/1000\n    313/313 [==============================] - 14s 46ms/step - loss: 6064.2158 - val_loss: 6330.7183\n    Epoch 440/1000\n    313/313 [==============================] - 15s 46ms/step - loss: 6063.1353 - val_loss: 6328.0396\n    Epoch 441/1000\n    313/313 [==============================] - 15s 47ms/step - loss: 6062.3462 - val_loss: 6326.4263\n    Epoch 442/1000\n    313/313 [==============================] - 14s 46ms/step - loss: 6061.8950 - val_loss: 6324.1123\n    Epoch 443/1000\n    313/313 [==============================] - 14s 46ms/step - loss: 6062.0254 - val_loss: 6325.0547\n    Epoch 444/1000\n    313/313 [==============================] - 14s 46ms/step - loss: 6063.9141 - val_loss: 6332.2842\n    Epoch 445/1000\n    313/313 [==============================] - 15s 46ms/step - loss: 6067.0142 - val_loss: 6330.8447\n    Epoch 446/1000\n    313/313 [==============================] - 15s 47ms/step - loss: 6067.5039 - val_loss: 6346.4048\n    Epoch 447/1000\n    313/313 [==============================] - 14s 46ms/step - loss: 6065.1567 - val_loss: 6334.5322\n    Epoch 448/1000\n    313/313 [==============================] - 14s 46ms/step - loss: 6063.5117 - val_loss: 6325.9033\n    Epoch 449/1000\n    313/313 [==============================] - 14s 46ms/step - loss: 6062.8691 - val_loss: 6335.9067\n    Epoch 450/1000\n    313/313 [==============================] - 15s 46ms/step - loss: 6062.8906 - val_loss: 6326.4409\n    Epoch 451/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6062.7231 - val_loss: 6325.5078\n    Epoch 452/1000\n    313/313 [==============================] - 15s 47ms/step - loss: 6063.1831 - val_loss: 6325.4316\n    Epoch 453/1000\n    313/313 [==============================] - 15s 47ms/step - loss: 6064.0112 - val_loss: 6326.8140\n    Epoch 454/1000\n    313/313 [==============================] - 14s 46ms/step - loss: 6064.6250 - val_loss: 6325.1689\n    Epoch 455/1000\n    313/313 [==============================] - 15s 47ms/step - loss: 6065.8066 - val_loss: 6323.5771\n    Epoch 456/1000\n    313/313 [==============================] - 15s 47ms/step - loss: 6065.9458 - val_loss: 6322.4502\n    Epoch 457/1000\n    313/313 [==============================] - 14s 46ms/step - loss: 6065.7939 - val_loss: 6336.4072\n    Epoch 458/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6065.6968 - val_loss: 6332.0908\n    Epoch 459/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6064.8735 - val_loss: 6333.9736\n    Epoch 460/1000\n    313/313 [==============================] - 14s 46ms/step - loss: 6064.4658 - val_loss: 6333.2354\n    Epoch 461/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6064.6895 - val_loss: 6336.2310\n    Epoch 462/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6065.2588 - val_loss: 6340.0298\n    Epoch 463/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6066.5396 - val_loss: 6353.9312\n    Epoch 464/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6067.4688 - val_loss: 6369.2227\n    Epoch 465/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6068.9414 - val_loss: 6378.3945\n    Epoch 466/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6070.9668 - val_loss: 6416.3335\n    Epoch 467/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6074.5469 - val_loss: 6430.8286\n    Epoch 468/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6075.7148 - val_loss: 6401.3892\n    Epoch 469/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6072.5210 - val_loss: 6403.8877\n    Epoch 470/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6067.4390 - val_loss: 6408.2930\n    Epoch 471/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6063.4619 - val_loss: 6397.0396\n    Epoch 472/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6061.2285 - val_loss: 6393.9380\n    Epoch 473/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6059.5576 - val_loss: 6389.8325\n    Epoch 474/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6058.2529 - val_loss: 6390.6704\n    Epoch 475/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6057.5859 - val_loss: 6389.1519\n    Epoch 476/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6057.1201 - val_loss: 6381.9888\n    Epoch 477/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6056.6987 - val_loss: 6381.9233\n    Epoch 478/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6056.4048 - val_loss: 6386.8652\n    Epoch 479/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6055.9946 - val_loss: 6384.1274\n    Epoch 480/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6055.3203 - val_loss: 6393.3579\n    Epoch 481/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6055.1802 - val_loss: 6382.3682\n    Epoch 482/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6055.1104 - val_loss: 6381.0049\n    Epoch 483/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6055.9414 - val_loss: 6378.2549\n    Epoch 484/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6059.2529 - val_loss: 6369.9697\n    Epoch 485/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6060.8926 - val_loss: 6408.4351\n    Epoch 486/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6058.4639 - val_loss: 6385.9429\n    Epoch 487/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6057.2217 - val_loss: 6368.4878\n    Epoch 488/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6057.3647 - val_loss: 6374.9097\n    Epoch 489/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6057.8687 - val_loss: 6375.9888\n    Epoch 490/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6059.3330 - val_loss: 6380.4238\n    Epoch 491/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6061.3486 - val_loss: 6401.0356\n    Epoch 492/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6064.2944 - val_loss: 6404.3428\n    Epoch 493/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6066.5430 - val_loss: 6414.8374\n    Epoch 494/1000\n    313/313 [==============================] - 15s 50ms/step - loss: 6067.7085 - val_loss: 6396.7261\n    Epoch 495/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6068.0586 - val_loss: 6397.2153\n    Epoch 496/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6068.3306 - val_loss: 6411.6382\n    Epoch 497/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6069.8926 - val_loss: 6423.4751\n    Epoch 498/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6071.9595 - val_loss: 6431.6660\n    Epoch 499/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6072.6982 - val_loss: 6435.7529\n    Epoch 500/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6072.7222 - val_loss: 6446.6499\n    Epoch 501/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6072.1450 - val_loss: 6447.0195\n    Epoch 502/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6071.3970 - val_loss: 6439.4736\n    Epoch 503/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6070.9673 - val_loss: 6436.6118\n    Epoch 504/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6070.5137 - val_loss: 6434.4585\n    Epoch 505/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6070.2778 - val_loss: 6449.8467\n    Epoch 506/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6070.1211 - val_loss: 6427.5850\n    Epoch 507/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6070.3486 - val_loss: 6417.9185\n    Epoch 508/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6070.9487 - val_loss: 6415.7056\n    Epoch 509/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6071.4233 - val_loss: 6418.4165\n    Epoch 510/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6070.5776 - val_loss: 6405.9443\n    Epoch 511/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6069.7378 - val_loss: 6405.5010\n    Epoch 512/1000\n    313/313 [==============================] - 16s 53ms/step - loss: 6068.3379 - val_loss: 6395.9873\n    Epoch 513/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6066.8096 - val_loss: 6401.3765\n    Epoch 514/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6064.6338 - val_loss: 6401.3320\n    Epoch 515/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6063.6782 - val_loss: 6398.4629\n    Epoch 516/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6063.1299 - val_loss: 6397.7661\n    Epoch 517/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6062.5283 - val_loss: 6391.7900\n    Epoch 518/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6061.5918 - val_loss: 6394.8369\n    Epoch 519/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6060.9443 - val_loss: 6387.8960\n    Epoch 520/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6061.0215 - val_loss: 6382.3730\n    Epoch 521/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6060.8696 - val_loss: 6384.1929\n    Epoch 522/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6060.7832 - val_loss: 6381.1982\n    Epoch 523/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6060.9346 - val_loss: 6384.0005\n    Epoch 524/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6061.9409 - val_loss: 6385.9453\n    Epoch 525/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6063.9810 - val_loss: 6388.3071\n    Epoch 526/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6067.3970 - val_loss: 6381.7007\n    Epoch 527/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6072.3374 - val_loss: 6363.0903\n    Epoch 528/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6075.4341 - val_loss: 6351.6025\n    Epoch 529/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6073.1196 - val_loss: 6355.8286\n    Epoch 530/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6069.1641 - val_loss: 6356.7822\n    Epoch 531/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6065.7095 - val_loss: 6350.0190\n    Epoch 532/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6062.8447 - val_loss: 6346.4951\n    Epoch 533/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6060.4268 - val_loss: 6346.2192\n    Epoch 534/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6059.3828 - val_loss: 6347.7988\n    Epoch 535/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6058.2754 - val_loss: 6345.6255\n    Epoch 536/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6057.2012 - val_loss: 6342.3799\n    Epoch 537/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6056.5234 - val_loss: 6340.9824\n    Epoch 538/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6056.0522 - val_loss: 6340.3696\n    Epoch 539/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6055.5142 - val_loss: 6338.8198\n    Epoch 540/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6054.9253 - val_loss: 6338.1421\n    Epoch 541/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6054.4194 - val_loss: 6337.4185\n    Epoch 542/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6054.3613 - val_loss: 6339.4517\n    Epoch 543/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6054.4404 - val_loss: 6335.9678\n    Epoch 544/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6055.0845 - val_loss: 6335.4053\n    Epoch 545/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6057.2466 - val_loss: 6333.9082\n    Epoch 546/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6058.5542 - val_loss: 6332.2324\n    Epoch 547/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6058.4590 - val_loss: 6341.6230\n    Epoch 548/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6059.2207 - val_loss: 6336.5977\n    Epoch 549/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6063.0894 - val_loss: 6332.4111\n    Epoch 550/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6066.8008 - val_loss: 6334.6045\n    Epoch 551/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6065.7026 - val_loss: 6332.0864\n    Epoch 552/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6064.1948 - val_loss: 6332.0654\n    Epoch 553/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6065.7798 - val_loss: 6335.7944\n    Epoch 554/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6069.9297 - val_loss: 6342.3579\n    Epoch 555/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6074.6460 - val_loss: 6357.7480\n    Epoch 556/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6081.7114 - val_loss: 6394.1099\n    Epoch 557/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6084.4126 - val_loss: 6389.5586\n    Epoch 558/1000\n    313/313 [==============================] - 15s 47ms/step - loss: 6080.8794 - val_loss: 6364.8301\n    Epoch 559/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6077.7549 - val_loss: 6358.5044\n    Epoch 560/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6075.4263 - val_loss: 6357.5669\n    Epoch 561/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6074.6802 - val_loss: 6357.7690\n    Epoch 562/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6073.7227 - val_loss: 6358.3574\n    Epoch 563/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6073.9473 - val_loss: 6364.7129\n    Epoch 564/1000\n    313/313 [==============================] - 16s 52ms/step - loss: 6073.3008 - val_loss: 6360.5693\n    Epoch 565/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6072.5464 - val_loss: 6361.8232\n    Epoch 566/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6071.7930 - val_loss: 6364.0098\n    Epoch 567/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6070.5059 - val_loss: 6366.6577\n    Epoch 568/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6070.3809 - val_loss: 6358.4297\n    Epoch 569/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6069.1318 - val_loss: 6363.7949\n    Epoch 570/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6068.2295 - val_loss: 6357.0752\n    Epoch 571/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6068.4985 - val_loss: 6357.0967\n    Epoch 572/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6069.4478 - val_loss: 6349.6152\n    Epoch 573/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6074.7793 - val_loss: 6364.8735\n    Epoch 574/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6083.9482 - val_loss: 6333.8018\n    Epoch 575/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6086.2310 - val_loss: 6342.3188\n    Epoch 576/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6078.5063 - val_loss: 6346.2202\n    Epoch 577/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6070.8618 - val_loss: 6347.0488\n    Epoch 578/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6066.5054 - val_loss: 6346.2534\n    Epoch 579/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6063.3921 - val_loss: 6343.7969\n    Epoch 580/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6061.5918 - val_loss: 6344.6689\n    Epoch 581/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6060.4604 - val_loss: 6347.9185\n    Epoch 582/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6058.9502 - val_loss: 6346.4390\n    Epoch 583/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6057.7100 - val_loss: 6348.1143\n    Epoch 584/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6056.7241 - val_loss: 6351.1982\n    Epoch 585/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6055.8013 - val_loss: 6351.8940\n    Epoch 586/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6054.4194 - val_loss: 6354.2344\n    Epoch 587/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6053.9966 - val_loss: 6359.3213\n    Epoch 588/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6053.4810 - val_loss: 6346.2266\n    Epoch 589/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6053.5942 - val_loss: 6346.4409\n    Epoch 590/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6056.4736 - val_loss: 6357.8813\n    Epoch 591/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6059.5547 - val_loss: 6334.5552\n    Epoch 592/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6057.7549 - val_loss: 6338.7520\n    Epoch 593/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6054.4502 - val_loss: 6349.6650\n    Epoch 594/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6052.6934 - val_loss: 6346.4927\n    Epoch 595/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6052.0972 - val_loss: 6340.0801\n    Epoch 596/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6052.4111 - val_loss: 6342.8770\n    Epoch 597/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6053.1118 - val_loss: 6344.4033\n    Epoch 598/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6054.2485 - val_loss: 6334.7515\n    Epoch 599/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6056.6689 - val_loss: 6344.5635\n    Epoch 600/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6058.1934 - val_loss: 6362.6792\n    Epoch 601/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6059.2798 - val_loss: 6350.1035\n    Epoch 602/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6057.5054 - val_loss: 6338.0601\n    Epoch 603/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6054.6577 - val_loss: 6334.3960\n    Epoch 604/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6052.9810 - val_loss: 6335.0781\n    Epoch 605/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6052.2969 - val_loss: 6337.3999\n    Epoch 606/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6052.1470 - val_loss: 6339.9224\n    Epoch 607/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6052.0889 - val_loss: 6332.6196\n    Epoch 608/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6053.6870 - val_loss: 6330.5815\n    Epoch 609/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6055.9419 - val_loss: 6332.6348\n    Epoch 610/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6060.9619 - val_loss: 6326.4819\n    Epoch 611/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6065.8101 - val_loss: 6348.4155\n    Epoch 612/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6063.0752 - val_loss: 6356.5020\n    Epoch 613/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6056.4575 - val_loss: 6352.9443\n    Epoch 614/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6052.8354 - val_loss: 6353.9429\n    Epoch 615/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6051.2100 - val_loss: 6354.7598\n    Epoch 616/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6050.2842 - val_loss: 6360.0889\n    Epoch 617/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6049.8423 - val_loss: 6364.5386\n    Epoch 618/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6050.0142 - val_loss: 6366.6304\n    Epoch 619/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6049.7480 - val_loss: 6367.3330\n    Epoch 620/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6049.7183 - val_loss: 6364.9595\n    Epoch 621/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6049.6313 - val_loss: 6365.4404\n    Epoch 622/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6049.6812 - val_loss: 6371.2671\n    Epoch 623/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6049.4575 - val_loss: 6365.8462\n    Epoch 624/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6049.9062 - val_loss: 6352.6299\n    Epoch 625/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6050.3955 - val_loss: 6359.6841\n    Epoch 626/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6052.4761 - val_loss: 6380.2876\n    Epoch 627/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6053.9736 - val_loss: 6336.6377\n    Epoch 628/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6055.5327 - val_loss: 6359.6680\n    Epoch 629/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6056.3037 - val_loss: 6360.1084\n    Epoch 630/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6056.5137 - val_loss: 6361.6646\n    Epoch 631/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6055.7490 - val_loss: 6379.4600\n    Epoch 632/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6055.3613 - val_loss: 6378.8887\n    Epoch 633/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6055.8574 - val_loss: 6369.7998\n    Epoch 634/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6056.8052 - val_loss: 6383.9922\n    Epoch 635/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6058.6294 - val_loss: 6417.1938\n    Epoch 636/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6060.3154 - val_loss: 6435.5146\n    Epoch 637/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6061.1792 - val_loss: 6449.0591\n    Epoch 638/1000\n    313/313 [==============================] - 15s 50ms/step - loss: 6061.0942 - val_loss: 6427.7046\n    Epoch 639/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6060.4834 - val_loss: 6400.1377\n    Epoch 640/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6060.0894 - val_loss: 6386.7217\n    Epoch 641/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6059.4771 - val_loss: 6381.3809\n    Epoch 642/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6060.2129 - val_loss: 6371.6401\n    Epoch 643/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6060.1514 - val_loss: 6370.6685\n    Epoch 644/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6058.8950 - val_loss: 6357.1582\n    Epoch 645/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6057.2373 - val_loss: 6349.4360\n    Epoch 646/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6054.8232 - val_loss: 6352.0029\n    Epoch 647/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6053.6802 - val_loss: 6348.2080\n    Epoch 648/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6053.3066 - val_loss: 6349.8369\n    Epoch 649/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6053.4395 - val_loss: 6364.2051\n    Epoch 650/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6054.0449 - val_loss: 6384.1880\n    Epoch 651/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6055.3384 - val_loss: 6382.5908\n    Epoch 652/1000\n    313/313 [==============================] - 16s 51ms/step - loss: 6057.7729 - val_loss: 6369.3281\n    Epoch 653/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6060.6543 - val_loss: 6356.5454\n    Epoch 654/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6063.0264 - val_loss: 6343.4814\n    Epoch 655/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6062.0391 - val_loss: 6340.6846\n    Epoch 656/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6058.4707 - val_loss: 6338.6001\n    Epoch 657/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6055.5020 - val_loss: 6343.6069\n    Epoch 658/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6052.5825 - val_loss: 6345.9058\n    Epoch 659/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6050.5415 - val_loss: 6345.1421\n    Epoch 660/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6049.6606 - val_loss: 6342.4771\n    Epoch 661/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6049.0044 - val_loss: 6344.1289\n    Epoch 662/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6048.6050 - val_loss: 6344.2471\n    Epoch 663/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6048.2129 - val_loss: 6343.6138\n    Epoch 664/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6047.9805 - val_loss: 6340.1934\n    Epoch 665/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6048.0605 - val_loss: 6338.5771\n    Epoch 666/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6048.0933 - val_loss: 6348.1367\n    Epoch 667/1000\n    313/313 [==============================] - 15s 48ms/step - loss: 6048.5137 - val_loss: 6372.9238\n    Epoch 668/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6050.5723 - val_loss: 6387.2954\n    Epoch 669/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6052.4258 - val_loss: 6335.6006\n    Epoch 670/1000\n    313/313 [==============================] - 15s 49ms/step - loss: 6052.4536 - val_loss: 6334.3223\n    Epoch 671/1000\n    313/313 [==============================] - 16s 50ms/step - loss: 6052.0928 - val_loss: 6335.8418\n    Epoch 672/1000\n    251/313 [=======================>......] - ETA: 2s - loss: 6056.5859\n\n\n```python\n# OR... load the pre-trained model\n\n#ckpt = tf.train.Checkpoint(model=vae)\n#ckpt.restore(tf.train.latest_checkpoint('/path/to/model'))\n```\n\n\n```python\n# Evaluate the model on the test set\n\ntest_loss = vae.evaluate(test_ds)\nprint(\"Test loss: {}\".format(test_loss))\n```\n\n#### Compute reconstructions of test images\n\nWe will now take a look at some image reconstructions from the encoder-decoder architecture.\n\nYou should complete the following function, that uses `encoder` and `decoder` to reconstruct images from the test dataset. This function takes the encoder, decoder and a Tensor batch of test images as arguments. The function should be completed according to the following specification:\n\n* Get the mean of the encoding distributions from passing the batch of images into the encoder\n* Pass these latent vectors through the decoder to get the output distribution\n\nYour function should then return the mean of the output distribution, which will be a Tensor of shape `(batch_size, 64, 64, 3)`.\n\n\n```python\n #### GRADED CELL ####\n\n# Complete the following function. \n# Make sure to not change the function name or arguments.\n\ndef reconstruct(encoder, decoder, batch_of_images):\n    \"\"\"\n    This function should compute reconstructions of the batch_of_images according\n    to the above instructions.\n    The function takes the encoder, decoder and batch_of_images as inputs, which\n    should be used to compute the reconstructions.\n    The function should then return the reconstructions Tensor.\n    \"\"\"\n    return  decoder(encoder(batch_of_images).mean()).mean() \n    \n```\n\n\n```python\n# Run your function to compute reconstructions of random samples from the test dataset\n\nn_reconstructions = 7\nfiles = [f for f in os.listdir('/content/drive/MyDrive/Colab_Notebooks/coursera/coursera_Probabilistic_Deep_Learning_TF2/Week4/CeleAsubset/test/') if f.endswith('.jpg')]\nnum_test_files = len(files)\ntest_ds_for_reconstructions = load_dataset('test')\nfor all_test_images, _ in test_ds_for_reconstructions.batch(num_test_files).take(1):\n    all_test_images_np = all_test_images.numpy()\nexample_images = all_test_images_np[np.random.choice(num_test_files, n_reconstructions, replace=False)]\n\nreconstructions = reconstruct(encoder, decoder, example_images).numpy()\n```\n\n\n```python\n# Plot the reconstructions\n\nf, axs = plt.subplots(2, n_reconstructions, figsize=(16, 6))\naxs[0, n_reconstructions // 2].set_title(\"Original test images\")\naxs[1, n_reconstructions // 2].set_title(\"Reconstructed images\")\nfor j in range(n_reconstructions):\n    axs[0, j].imshow(example_images[j])\n    axs[1, j].imshow(reconstructions[j])\n    axs[0, j].axis('off')\n    axs[1, j].axis('off')\n    \nplt.tight_layout();\n```\n\n#### Sample new images from the generative model\n\nNow we will sample from the generative model; that is, first sample latent vectors from the prior, and then decode those latent vectors with the decoder.\n\nYou should complete the following function to generate new images. This function takes the prior distribution and decoder network as arguments, as well as the number of samples to generate. This function should be completed according to the following:\n\n* Sample a batch of `n_samples` images from the prior distribution, to obtain a latent vector Tensor of shape `(n_samples, 50)`\n* Pass this batch of latent vectors through the decoder, to obtain an Independent Bernoulli distribution with batch shape equal to `[n_samples]` and event shape equal to `[64, 64, 3]`.\n\nThe function should then return the mean of the Bernoulli distribution, which will be a Tensor of shape `(n_samples, 64, 64, 3)`.\n\n\n```python\n #### GRADED CELL ####\n\n# Complete the following function. \n# Make sure to not change the function name or arguments.\n\ndef generate_images(prior, decoder, n_samples):\n    \"\"\"\n    This function should compute generate new samples of images from the generative model,\n    according to the above instructions.\n    The function takes the prior distribution, decoder and number of samples as inputs, which\n    should be used to generate the images.\n    The function should then return the batch of generated images.\n    \"\"\"\n    return decoder(prior.sample(n_samples)).mean()\n```\n\n\n```python\n# Run your function to generate new images\n\nn_samples = 10\nsampled_images = generate_images(prior, decoder, n_samples)\n\nf, axs = plt.subplots(1, n_samples, figsize=(16, 6))\n\nfor j in range(n_samples):\n    axs[j].imshow(sampled_images[j])\n    axs[j].axis('off')\n    \nplt.tight_layout();\n```\n\n### Modify generations with attribute vector\n\nThis final section is ungraded, but you will hopefully find it to be an interesting extension. We will see how the latent space encodes high-level information about the images, even though it has not been trained with any information apart from the images themselves.\n\nAs mentioned in the introduction, each image in the CelebA dataset is labelled according to the attributes of the person pictured.\n\nRun the cells below to load these labels, along with a subset of the training data.\n\n\n```python\n# Function to load labels and images as a numpy array\n\ndef load_labels_and_image_arrays(split):\n    dataset = load_dataset(split)\n    files = [f for f in os.listdir('/content/drive/MyDrive/Colab_Notebooks/coursera/coursera_Probabilistic_Deep_Learning_TF2/Week4/CeleAsubset/{}/'.format(split)) if f.endswith('.jpg')]\n    \n    for all_images, _ in dataset.batch(len(files)).take(1):\n        all_images_np = all_images.numpy()\n\n    labels = pd.read_csv('/content/drive/MyDrive/Colab_Notebooks/coursera/coursera_Probabilistic_Deep_Learning_TF2/Week4/CeleAsubset/list_attr_celeba_subset.csv')\n    labels = labels[labels['image_id'].isin(files)]\n    return labels, all_images_np\n```\n\n\n```python\n# Load labels in a pandas DataFrame, training_subset is a numpy array\n\ntrain_labels, training_subset = load_labels_and_image_arrays('train')\n```\n\n\n```python\n# List the attributes contained in the DataFrame\n\ntrain_labels.columns[2:]\n```\n\nEach image is labelled with a binary indicator (1 is True, -1 is False) according to whether it possesses the attribute. \n\n\n```python\n# View a sample from the labels data\n\ntrain_labels.sample(5)\n```\n\n\n```python\n# Select an attribute\n\nattribute = 'Smiling'\n```\n\n\n```python\n# Separate the images into those that have the attribute, and those that don't\n\nattribute_mask = (train_labels[attribute] == 1)\nimages_with_attribute = training_subset[attribute_mask]\n\nnot_attribute_mask = (train_labels[attribute] == -1)\nimages_without_attribute = training_subset[not_attribute_mask]\n```\n\n#### Get the 'attribute vector'\n\nWe will now encode each of the images that have the chosen attribute into the latent space by passing them through the encoder. We then average the latent codes obtained for all of these images to obtain a single latent code.\n\nWe then do the same for the images that do not have the chosen attribute. This gives an average latent code for images with the attribute, and an average latent code for images without the attribute. Intuitively speaking, the difference between these two vectors then gives us the 'direction' in latent space that corresponds to the presence of the attribute.\n\n\n```python\n# Encode the images with and without the chosen attribute\n\nencoded_images_with_attribute = encoder(images_with_attribute)\nencoded_images_without_attribute = encoder(images_without_attribute)\n```\n\n\n```python\n# Average the latent vectors for each batch of encodings\n\nmean_encoded_images_with_attribute = tf.reduce_mean(encoded_images_with_attribute.mean(), \n                                                    axis=0, keepdims=True)\nmean_encoded_images_without_attribute = tf.reduce_mean(encoded_images_without_attribute.mean(), \n                                                    axis=0, keepdims=True)\n```\n\n\n```python\n# Get the attribute vector\n\nattribute_vector = mean_encoded_images_with_attribute -  mean_encoded_images_without_attribute\n```\n\nWe can view this attribute vector by decoding it:\n\n\n```python\n# Display the decoded attribute vector\n\ndecoded_a = decoder(attribute_vector).mean()\nplt.imshow(decoded_a.numpy().squeeze())\nplt.axis('off');\n```\n\n#### Modify reconstructions using the attribute vector\n\nWe can now use the attribute vector to add the attribute to an image reconstruction, where that attribute wasn't present before. To do this, we can just add the attribute vector to the latent vector encoding of the image, and then decode the result. We can also adjust the strength of the attribute vector by scaling with a multiplicative parameter.\n\n\n```python\n# Add the attribute vector to a sample of images that don't have the attribute\n\nn_examples = 7\nsampled_inx = np.random.choice(images_without_attribute.shape[0], n_examples, replace=False)\nsample_images_without_attribute = images_without_attribute[sampled_inx]\nsample_images_encodings = encoder(sample_images_without_attribute)\nsample_images_reconstructions = decoder(sample_images_encodings).mean()\n\nk = 2.5  # Weighting of attribute vector\nmodified_sample_images_encodings = sample_images_encodings + (k * attribute_vector)\nmodified_reconstructions = decoder(modified_sample_images_encodings).mean()\n```\n\n\n```python\n# Display the original images, their reconstructions, and modified reconstructions\n\nf, axs = plt.subplots(3, n_examples, figsize=(16, 6))\naxs[0, n_examples // 2].set_title(\"Original images\")\naxs[1, n_examples // 2].set_title(\"Reconstructed images\")\naxs[2, n_examples // 2].set_title(\"Images with added attribute\")\nfor j in range(n_examples):\n    axs[0, j].imshow(sample_images_without_attribute[j])\n    axs[1, j].imshow(sample_images_reconstructions[j])\n    axs[2, j].imshow(modified_reconstructions[j])\n    for ax in axs[:, j]: ax.axis('off')\n    \nplt.tight_layout();\n```\n\nYou could also try removing the attribute from images that possess the attribute, or experiment with a different attribute.\n\n---\n\nCongratulations for completing this programming assignment! You're now ready to move on to the capstone project for this course.\n\n\n```python\n\n```\n", "meta": {"hexsha": "b0a46a1808c52443490cd014089fd45dc07f9e2d", "size": 359020, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Week4/Week 4 Programming Assignment.ipynb", "max_stars_repo_name": "stevensmiley1989/Prob_TF2_Examples", "max_stars_repo_head_hexsha": "fa022e58a44563d09792070be5d015d0798ca00d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Week4/Week 4 Programming Assignment.ipynb", "max_issues_repo_name": "stevensmiley1989/Prob_TF2_Examples", "max_issues_repo_head_hexsha": "fa022e58a44563d09792070be5d015d0798ca00d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week4/Week 4 Programming Assignment.ipynb", "max_forks_repo_name": "stevensmiley1989/Prob_TF2_Examples", "max_forks_repo_head_hexsha": "fa022e58a44563d09792070be5d015d0798ca00d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 359020.0, "max_line_length": 359020, "alphanum_fraction": 0.8177371734, "converted": true, "num_tokens": 41872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08269733815352048, "lm_q2_score": 0.08269733815352048, "lm_q1q2_score": 0.006838849737677714}}
{"text": "```python\nfrom IPython.core.display import display, HTML\ndisplay(HTML(\"<style>.container { width:100% !important; }</style>\"))\n```\n\n\n<style>.container { width:100% !important; }</style>\n\n\n# Atlanta Police Department \n\n\nThe Atlanta Police Department provides Part 1 crime data at http://www.atlantapd.org/i-want-to/crime-data-downloads\n\nA recent copy of the data file is stored in the cluster. <span style=\"color: red; font-weight: bold;\">Please, do not copy this data file into your home directory!</span>\n\n\n```python\n### Load libraries\n%matplotlib inline\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n```\n\n\n```python\nhelp(plt.legend)\n```\n\n    Help on function legend in module matplotlib.pyplot:\n    \n    legend(*args, **kwargs)\n        Places a legend on the axes.\n        \n        To make a legend for lines which already exist on the axes\n        (via plot for instance), simply call this function with an iterable\n        of strings, one for each legend item. For example::\n        \n            ax.plot([1, 2, 3])\n            ax.legend(['A simple line'])\n        \n        However, in order to keep the \"label\" and the legend element\n        instance together, it is preferable to specify the label either at\n        artist creation, or by calling the\n        :meth:`~matplotlib.artist.Artist.set_label` method on the artist::\n        \n            line, = ax.plot([1, 2, 3], label='Inline label')\n            # Overwrite the label by calling the method.\n            line.set_label('Label via method')\n            ax.legend()\n        \n        Specific lines can be excluded from the automatic legend element\n        selection by defining a label starting with an underscore.\n        This is default for all artists, so calling :meth:`legend` without\n        any arguments and without setting the labels manually will result in\n        no legend being drawn.\n        \n        For full control of which artists have a legend entry, it is possible\n        to pass an iterable of legend artists followed by an iterable of\n        legend labels respectively::\n        \n           legend((line1, line2, line3), ('label1', 'label2', 'label3'))\n        \n        Parameters\n        ----------\n        loc : int or string or pair of floats, default: 'upper right'\n            The location of the legend. Possible codes are:\n        \n                ===============   =============\n                Location String   Location Code\n                ===============   =============\n                'best'            0\n                'upper right'     1\n                'upper left'      2\n                'lower left'      3\n                'lower right'     4\n                'right'           5\n                'center left'     6\n                'center right'    7\n                'lower center'    8\n                'upper center'    9\n                'center'          10\n                ===============   =============\n        \n        \n            Alternatively can be a 2-tuple giving ``x, y`` of the lower-left\n            corner of the legend in axes coordinates (in which case\n            ``bbox_to_anchor`` will be ignored).\n        \n        bbox_to_anchor : :class:`matplotlib.transforms.BboxBase` instance                          or tuple of floats\n            Specify any arbitrary location for the legend in `bbox_transform`\n            coordinates (default Axes coordinates).\n        \n            For example, to put the legend's upper right hand corner in the\n            center of the axes the following keywords can be used::\n        \n               loc='upper right', bbox_to_anchor=(0.5, 0.5)\n        \n        ncol : integer\n            The number of columns that the legend has. Default is 1.\n        \n        prop : None or :class:`matplotlib.font_manager.FontProperties` or dict\n            The font properties of the legend. If None (default), the current\n            :data:`matplotlib.rcParams` will be used.\n        \n        fontsize : int or float or {'xx-small', 'x-small', 'small', 'medium',                   'large', 'x-large', 'xx-large'}\n            Controls the font size of the legend. If the value is numeric the\n            size will be the absolute font size in points. String values are\n            relative to the current default font size. This argument is only\n            used if `prop` is not specified.\n        \n        numpoints : None or int\n            The number of marker points in the legend when creating a legend\n            entry for a line/:class:`matplotlib.lines.Line2D`.\n            Default is ``None`` which will take the value from the\n            ``legend.numpoints`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        scatterpoints : None or int\n            The number of marker points in the legend when creating a legend\n            entry for a scatter plot/\n            :class:`matplotlib.collections.PathCollection`.\n            Default is ``None`` which will take the value from the\n            ``legend.scatterpoints`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        scatteryoffsets : iterable of floats\n            The vertical offset (relative to the font size) for the markers\n            created for a scatter plot legend entry. 0.0 is at the base the\n            legend text, and 1.0 is at the top. To draw all markers at the\n            same height, set to ``[0.5]``. Default ``[0.375, 0.5, 0.3125]``.\n        \n        markerscale : None or int or float\n            The relative size of legend markers compared with the originally\n            drawn ones. Default is ``None`` which will take the value from\n            the ``legend.markerscale`` :data:`rcParam <matplotlib.rcParams>`.\n        \n        *markerfirst*: [ *True* | *False* ]\n            if *True*, legend marker is placed to the left of the legend label\n            if *False*, legend marker is placed to the right of the legend\n            label\n        \n        frameon : None or bool\n            Control whether a frame should be drawn around the legend.\n            Default is ``None`` which will take the value from the\n            ``legend.frameon`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        fancybox : None or bool\n            Control whether round edges should be enabled around\n            the :class:`~matplotlib.patches.FancyBboxPatch` which\n            makes up the legend's background.\n            Default is ``None`` which will take the value from the\n            ``legend.fancybox`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        shadow : None or bool\n            Control whether to draw a shadow behind the legend.\n            Default is ``None`` which will take the value from the\n            ``legend.shadow`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        framealpha : None or float\n            Control the alpha transparency of the legend's frame.\n            Default is ``None`` which will take the value from the\n            ``legend.framealpha`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        mode : {\"expand\", None}\n            If `mode` is set to ``\"expand\"`` the legend will be horizontally\n            expanded to fill the axes area (or `bbox_to_anchor` if defines\n            the legend's size).\n        \n        bbox_transform : None or :class:`matplotlib.transforms.Transform`\n            The transform for the bounding box (`bbox_to_anchor`). For a value\n            of ``None`` (default) the Axes'\n            :data:`~matplotlib.axes.Axes.transAxes` transform will be used.\n        \n        title : str or None\n            The legend's title. Default is no title (``None``).\n        \n        borderpad : float or None\n            The fractional whitespace inside the legend border.\n            Measured in font-size units.\n            Default is ``None`` which will take the value from the\n            ``legend.borderpad`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        labelspacing : float or None\n            The vertical space between the legend entries.\n            Measured in font-size units.\n            Default is ``None`` which will take the value from the\n            ``legend.labelspacing`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        handlelength : float or None\n            The length of the legend handles.\n            Measured in font-size units.\n            Default is ``None`` which will take the value from the\n            ``legend.handlelength`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        handletextpad : float or None\n            The pad between the legend handle and text.\n            Measured in font-size units.\n            Default is ``None`` which will take the value from the\n            ``legend.handletextpad`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        borderaxespad : float or None\n            The pad between the axes and legend border.\n            Measured in font-size units.\n            Default is ``None`` which will take the value from the\n            ``legend.borderaxespad`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        columnspacing : float or None\n            The spacing between columns.\n            Measured in font-size units.\n            Default is ``None`` which will take the value from the\n            ``legend.columnspacing`` :data:`rcParam<matplotlib.rcParams>`.\n        \n        handler_map : dict or None\n            The custom dictionary mapping instances or types to a legend\n            handler. This `handler_map` updates the default handler map\n            found at :func:`matplotlib.legend.Legend.get_legend_handler_map`.\n        \n        Notes\n        -----\n        \n        Not all kinds of artist are supported by the legend command.\n        See :ref:`plotting-guide-legend` for details.\n        \n        Examples\n        --------\n        \n        .. plot:: mpl_examples/api/legend_demo.py\n    \n\n\nLoad data (don't change this if you're running the notebook on the cluster)\n\nWe have two files\n- `/home/data/APD/COBRA083016_2015.xlsx` for 2015\n- `/home/data/APD/COBRA083016.xlsx` from 2009 to current date\n\n\n```python\n%%time\ndf = pd.read_excel('/home/data/APD/COBRA083016_2015.xlsx', sheetname='Query')\n```\n\n    CPU times: user 12.6 s, sys: 21.5 ms, total: 12.7 s\n    Wall time: 39.6 s\n\n\n\n```python\ndf.shape\n```\n\n\n\n\n    (30011, 23)\n\n\n\n\n```python\nfor c in df.columns:\n    print(c)\n```\n\n    MI_PRINX\n    offense_id\n    rpt_date\n    occur_date\n    occur_time\n    poss_date\n    poss_time\n    beat\n    apt_office_prefix\n    apt_office_num\n    location\n    MinOfucr\n    MinOfibr_code\n    dispo_code\n    MaxOfnum_victims\n    Shift\n    Avg Day\n    loc_type\n    UC2 Literal\n    neighborhood\n    npu\n    x\n    y\n\n\n\n```python\ndf.head()\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>MI_PRINX</th>\n      <th>offense_id</th>\n      <th>rpt_date</th>\n      <th>occur_date</th>\n      <th>occur_time</th>\n      <th>poss_date</th>\n      <th>poss_time</th>\n      <th>beat</th>\n      <th>apt_office_prefix</th>\n      <th>apt_office_num</th>\n      <th>...</th>\n      <th>loc_type</th>\n      <th>UC2 Literal</th>\n      <th>neighborhood</th>\n      <th>npu</th>\n      <th>x</th>\n      <th>y</th>\n      <th>Zone</th>\n      <th>occur_ts</th>\n      <th>occur_month</th>\n      <th>occur_woy</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>206914</th>\n      <td>1371687</td>\n      <td>150562000</td>\n      <td>05/14/2013</td>\n      <td>05/14/2013</td>\n      <td>09:00:00</td>\n      <td>05/14/2013</td>\n      <td>11:30:00</td>\n      <td>205</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>18.0</td>\n      <td>LARCENY-FROM VEHICLE</td>\n      <td>Woodfield</td>\n      <td>C</td>\n      <td>-84.40912</td>\n      <td>33.82308</td>\n      <td>2</td>\n      <td>2013-05-14 09:00:00</td>\n      <td>5.0</td>\n      <td>20.0</td>\n    </tr>\n    <tr>\n      <th>207443</th>\n      <td>4346442</td>\n      <td>150010052</td>\n      <td>01/01/2015</td>\n      <td>12/31/2014</td>\n      <td>22:00:00</td>\n      <td>01/01/2015</td>\n      <td>00:07:00</td>\n      <td>512</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>LARCENY-FROM VEHICLE</td>\n      <td>Downtown</td>\n      <td>M</td>\n      <td>-84.39361</td>\n      <td>33.75246</td>\n      <td>5</td>\n      <td>2014-12-31 22:00:00</td>\n      <td>12.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>207444</th>\n      <td>4346443</td>\n      <td>150010079</td>\n      <td>01/01/2015</td>\n      <td>01/01/2015</td>\n      <td>00:03:00</td>\n      <td>01/01/2015</td>\n      <td>00:03:00</td>\n      <td>606</td>\n      <td>NaN</td>\n      <td>3377</td>\n      <td>...</td>\n      <td>26.0</td>\n      <td>ROBBERY-PEDESTRIAN</td>\n      <td>Grant Park</td>\n      <td>W</td>\n      <td>-84.35917</td>\n      <td>33.73991</td>\n      <td>6</td>\n      <td>2015-01-01 00:03:00</td>\n      <td>1.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>207445</th>\n      <td>4346444</td>\n      <td>150010151</td>\n      <td>01/01/2015</td>\n      <td>12/31/2014</td>\n      <td>23:45:00</td>\n      <td>01/01/2015</td>\n      <td>00:21:00</td>\n      <td>208</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>18.0</td>\n      <td>LARCENY-NON VEHICLE</td>\n      <td>Buckhead Forest</td>\n      <td>B</td>\n      <td>-84.37462</td>\n      <td>33.84564</td>\n      <td>2</td>\n      <td>2014-12-31 23:45:00</td>\n      <td>12.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>207446</th>\n      <td>4346445</td>\n      <td>150010214</td>\n      <td>01/01/2015</td>\n      <td>01/01/2015</td>\n      <td>00:30:00</td>\n      <td>01/01/2015</td>\n      <td>01:05:00</td>\n      <td>407</td>\n      <td>1000</td>\n      <td>1009</td>\n      <td>...</td>\n      <td>26.0</td>\n      <td>AGG ASSAULT</td>\n      <td>Fairburn Mays</td>\n      <td>H</td>\n      <td>-84.50968</td>\n      <td>33.74349</td>\n      <td>4</td>\n      <td>2015-01-01 00:30:00</td>\n      <td>1.0</td>\n      <td>1.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 27 columns</p>\n</div>\n\n\n\n\n```python\ndf.describe()\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>MI_PRINX</th>\n      <th>offense_id</th>\n      <th>beat</th>\n      <th>MinOfucr</th>\n      <th>MaxOfnum_victims</th>\n      <th>loc_type</th>\n      <th>x</th>\n      <th>y</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>3.001100e+04</td>\n      <td>3.001100e+04</td>\n      <td>30011.000000</td>\n      <td>30011.000000</td>\n      <td>30011.000000</td>\n      <td>26903.000000</td>\n      <td>30011.000000</td>\n      <td>30011.000000</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>4.361347e+06</td>\n      <td>1.518675e+08</td>\n      <td>359.417813</td>\n      <td>594.219886</td>\n      <td>1.194695</td>\n      <td>21.109356</td>\n      <td>-84.408346</td>\n      <td>33.756058</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>1.931052e+04</td>\n      <td>1.029128e+06</td>\n      <td>169.563281</td>\n      <td>114.321851</td>\n      <td>0.799062</td>\n      <td>16.579831</td>\n      <td>0.046894</td>\n      <td>0.045981</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>1.371687e+06</td>\n      <td>1.500101e+08</td>\n      <td>101.000000</td>\n      <td>210.000000</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n      <td>-84.546070</td>\n      <td>33.637450</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>4.353944e+06</td>\n      <td>1.510128e+08</td>\n      <td>208.000000</td>\n      <td>512.000000</td>\n      <td>1.000000</td>\n      <td>13.000000</td>\n      <td>-84.432445</td>\n      <td>33.729060</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>4.361446e+06</td>\n      <td>1.518913e+08</td>\n      <td>401.000000</td>\n      <td>640.000000</td>\n      <td>1.000000</td>\n      <td>18.000000</td>\n      <td>-84.398210</td>\n      <td>33.756000</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>4.368948e+06</td>\n      <td>1.527329e+08</td>\n      <td>505.000000</td>\n      <td>670.000000</td>\n      <td>1.000000</td>\n      <td>21.000000</td>\n      <td>-84.374420</td>\n      <td>33.781470</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>4.376451e+06</td>\n      <td>1.536580e+08</td>\n      <td>709.000000</td>\n      <td>730.000000</td>\n      <td>44.000000</td>\n      <td>99.000000</td>\n      <td>-84.290480</td>\n      <td>33.883250</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf.offense_id.min(), df.offense_id.max()\n```\n\n\n\n\n    (150010052, 153658045)\n\n\n\n\n```python\ndf.columns\n```\n\n\n\n\n    Index([u'MI_PRINX', u'offense_id', u'rpt_date', u'occur_date', u'occur_time',\n           u'poss_date', u'poss_time', u'beat', u'apt_office_prefix',\n           u'apt_office_num', u'location', u'MinOfucr', u'MinOfibr_code',\n           u'dispo_code', u'MaxOfnum_victims', u'Shift', u'Avg Day', u'loc_type',\n           u'UC2 Literal', u'neighborhood', u'npu', u'x', u'y'],\n          dtype='object')\n\n\n\n\n```python\ncrime_summary = df.groupby(['UC2 Literal', 'neighborhood']).offense_id.count()\n```\n\n\n```python\ncrime_summary.index\n```\n\n\n\n\n    MultiIndex(levels=[[u'AGG ASSAULT', u'AUTO THEFT', u'BURGLARY-NONRES', u'BURGLARY-RESIDENCE', u'LARCENY-FROM VEHICLE', u'LARCENY-NON VEHICLE', u'RAPE', u'ROBBERY-COMMERCIAL', u'ROBBERY-PEDESTRIAN', u'ROBBERY-RESIDENCE'], [u'Adair Park', u'Adams Park', u'Adamsville', u'Almond Park', u'Amal Heights', u'Ansley Park', u'Arden/Habersham', u'Ardmore', u'Argonne Forest', u'Arlington Estates', u'Ashley Courts', u'Ashview Heights', u'Atkins Park', u'Atlanta Industrial Park', u'Atlanta University Center', u'Atlantic Station', u'Audobon Forest', u'Audobon Forest West', u'Baker Hills', u'Bakers Ferry', u'Bankhead', u'Bankhead Courts', u'Bankhead/Bolton', u'Beecher Hills', u'Ben Hill', u'Ben Hill Acres', u'Ben Hill Forest', u'Ben Hill Pines', u'Ben Hill Terrace', u'Benteen Park', u'Berkeley Park', u'Betmar LaVilla', u'Blair Villa/Poole Creek', u'Blandtown', u'Bolton', u'Bolton Hills', u'Boulder Park', u'Boulevard Heights', u'Brandon', u'Brentwood', u'Briar Glen', u'Brookhaven', u'Brookview Heights', u'Brookwood', u'Brookwood Hills', u'Browns Mill Park', u'Buckhead Forest', u'Buckhead Heights', u'Buckhead Village', u'Bush Mountain', u'Butner/Tell', u'Cabbagetown', u'Campbellton Road', u'Candler Park', u'Capitol Gateway', u'Capitol View', u'Capitol View Manor', u'Carey Park', u'Carroll Heights', u'Carver Hills', u'Cascade Avenue/Road', u'Cascade Green', u'Cascade Heights', u'Castleberry Hill', u'Castlewood', u'Center Hill', u'Chalet Woods', u'Channing Valley', u'Chastain Park', u'Chosewood Park', u'Collier Heights', u'Collier Hills', u'Collier Hills North', u'Colonial Homes', u'Cross Creek', u'Custer/McDonough/Guice', u'Deerwood', u'Dixie Hills', u'Downtown', u'Druid Hills', u'East Ardley Road', u'East Atlanta', u'East Chastain Park', u'East Lake', u'Edgewood', u'Elmco Estates', u'English Avenue', u'English Park', u'Fairburn', u'Fairburn Heights', u'Fairburn Mays', u'Fairburn Road/Wisteria Lane', u'Fairburn Tell', u'Fairway Acres', u'Fernleaf', u'Florida Heights', u'Fort McPherson', u'Fort Valley', u'Garden Hills', u'Georgia Tech', u'Glenrose Heights', u'Grant Park', u'Green Acres Valley', u'Green Forest Acres', u'Greenbriar', u'Greenbriar Village', u'Grove Park', u'Hammond Park', u'Hanover West', u'Harland Terrace', u'Harris Chiles', u'Harvel Homes Community', u'Heritage Valley', u'High Point', u'Hills Park', u'Home Park', u'Horseshoe Community', u'Hunter Hills', u'Huntington', u'Inman Park', u'Ivan Hill', u'Joyland', u'Just Us', u'Kings Forest', u'Kingswood', u'Kirkwood', u'Knight Park/Howell Station', u'Lake Claire', u'Lake Estates', u'Lakewood', u'Lakewood Heights', u'Laurens Valley', u'Leila Valley', u'Lenox', u'Lincoln Homes', u'Lindbergh/Morosgo', u'Lindridge/Martin Manor', u'Loring Heights', u'Magnum Manor', u'Margaret Mitchell', u'Marietta Street Artery', u'Mays', u'Meadowbrook Forest', u'Mechanicsville', u'Mellwood', u'Memorial Park', u'Midtown', u'Midwest Cascade', u'Monroe Heights', u'Morningside/Lenox Park', u'Mozley Park', u'Mt. Gilead Woods', u'Mt. Paran Parkway', u'Mt. Paran/Northside', u'Niskey Cove', u'Niskey Lake', u'North Buckhead', u'Norwood Manor', u'Oakcliff', u'Oakland', u'Oakland City', u'Old Fairburn Village', u'Old Fourth Ward', u'Old Gordon', u'Orchard Knob', u'Ormewood Park', u'Paces', u'Peachtree Battle Alliance', u'Peachtree Heights East', u'Peachtree Heights West', u'Peachtree Hills', u'Peachtree Park', u'Penelope Neighbors', u'Peoplestown', u'Perkerson', u'Peyton Forest', u'Piedmont Heights', u'Pine Hills', u'Pittsburgh', u'Pleasant Hill', u'Polar Rock', u'Pomona Park', u'Poncey-Highland', u'Princeton Lakes', u'Randall Mill', u'Rebel Valley Forest', u'Regency Trace', u'Reynoldstown', u'Ridgecrest Forest', u'Ridgedale Park', u'Ridgewood Heights', u'Riverside', u'Rockdale', u'Rosedale Heights', u'Rue Royal', u'Sandlewood Estates', u'Scotts Crossing', u'Sherwood Forest', u'South Atlanta', u'South River Gardens', u'South Tuxedo Park', u'Southwest', u'Springlake', u'Summerhill', u'Swallow Circle/Baywood', u'Sweet Auburn', u'Sylvan Hills', u'Tampa Park', u'The Villages at Carver', u'The Villages at Castleberry H', u'The Villages at East Lake', u'Thomasville Heights', u'Tuxedo Park', u'Underwood Hills', u'Venetian Hills', u'Vine City', u'Virginia Highland', u'Washington Park', u'Wesley Battle', u'West End', u'West Highlands', u'West Lake', u'West Manor', u'West Paces Ferry/Northside', u'Westhaven', u'Westminster/Milmar', u'Westover Plantation', u'Westview', u'Westwood Terrace', u'Whitewater Creek', u'Whittier Mill Village', u'Wildwood (NPU-C)', u'Wildwood (NPU-H)', u'Wildwood Forest', u'Wilson Mill Meadows', u'Wisteria Gardens', u'Woodfield', u'Woodland Hills', u'Wyngate']],\n               labels=[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [0, 1, 2, 3, 8, 9, 10, 11, 14, 15, 18, 20, 22, 23, 24, 26, 27, 28, 29, 30, 31, 32, 33, 34, 40, 41, 42, 44, 45, 46, 47, 48, 49, 52, 54, 55, 56, 57, 58, 59, 60, 62, 63, 65, 67, 69, 70, 72, 73, 74, 75, 76, 77, 78, 81, 83, 84, 85, 86, 87, 88, 89, 90, 91, 95, 96, 97, 98, 100, 101, 102, 103, 104, 105, 106, 107, 109, 110, 112, 113, 114, 115, 117, 119, 121, 122, 123, 125, 129, 130, 132, 133, 134, 135, 136, 137, 138, 140, 141, 142, 143, 144, 146, 148, 149, 150, 156, 157, 158, 160, 161, 162, 163, 164, 165, 166, 167, 169, 171, 173, 174, 176, 177, 178, 180, 181, 182, 183, 185, 187, 188, 191, 193, 194, 195, 196, 198, 199, 200, 201, 203, 204, 205, 206, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 219, 220, 221, 222, 223, 224, 227, 228, 230, 232, 234, 235, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 20, 22, 24, 25, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 65, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 93, 95, 96, 97, 98, 99, 100, 101, 102, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 132, 133, 134, 135, 136, 137, 138, 140, 141, 142, 143, 144, 146, 147, 148, 149, 150, 151, 153, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 180, 181, 182, 183, 184, 185, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 219, 220, 221, 222, 223, 224, 225, 227, 228, 229, 230, 231, 232, 233, 234, 235, 237, 0, 1, 2, 3, 5, 7, 10, 11, 12, 13, 14, 15, 20, 22, 23, 28, 30, 31, 32, 33, 34, 42, 44, 45, 46, 47, 48, 51, 52, 53, 55, 57, 58, 59, 60, 63, 65, 67, 69, 70, 73, 75, 77, 78, 81, 82, 83, 84, 85, 86, 87, 89, 90, 93, 95, 97, 98, 100, 101, 102, 104, 106, 107, 109, 114, 115, 117, 119, 120, 121, 123, 124, 125, 126, 129, 130, 132, 133, 135, 136, 137, 140, 143, 146, 148, 149, 150, 156, 157, 160, 162, 165, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 180, 181, 182, 183, 187, 191, 193, 198, 199, 200, 201, 203, 205, 206, 208, 209, 210, 213, 214, 215, 216, 218, 219, 221, 222, 223, 227, 228, 231, 237, 0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 94, 95, 97, 98, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 146, 147, 148, 149, 150, 151, 153, 154, 155, 156, 157, 159, 160, 161, 162, 163, 164, 165, 166, 167, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 92, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 145, 146, 147, 148, 149, 150, 151, 153, 154, 156, 157, 158, 159, 160, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22, 24, 25, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 38, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 67, 68, 69, 70, 71, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 95, 97, 98, 100, 101, 102, 103, 104, 105, 106, 107, 109, 110, 111, 112, 113, 114, 115, 117, 119, 120, 121, 122, 123, 125, 126, 127, 129, 130, 131, 132, 133, 134, 135, 136, 137, 139, 140, 141, 142, 143, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 156, 157, 158, 159, 160, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 180, 181, 182, 183, 184, 185, 187, 188, 189, 190, 191, 192, 193, 196, 198, 199, 200, 201, 202, 203, 204, 205, 206, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 227, 228, 230, 231, 232, 233, 234, 235, 236, 237, 238, 0, 3, 7, 11, 14, 18, 19, 20, 22, 30, 42, 45, 46, 48, 52, 54, 57, 63, 65, 70, 77, 78, 83, 84, 86, 90, 91, 95, 100, 101, 104, 106, 107, 115, 125, 130, 133, 134, 135, 136, 141, 143, 146, 150, 156, 160, 162, 164, 170, 171, 173, 174, 176, 177, 180, 185, 191, 192, 193, 196, 199, 200, 201, 203, 205, 206, 208, 210, 213, 215, 216, 221, 232, 0, 1, 2, 11, 15, 20, 25, 30, 33, 34, 42, 48, 52, 54, 60, 63, 65, 70, 75, 78, 81, 82, 83, 84, 85, 86, 95, 98, 100, 101, 104, 106, 107, 109, 115, 123, 125, 127, 130, 133, 135, 136, 143, 146, 156, 162, 165, 169, 171, 173, 174, 176, 177, 182, 183, 191, 201, 203, 206, 211, 213, 214, 215, 217, 219, 221, 227, 231, 237, 0, 1, 2, 3, 4, 5, 7, 8, 10, 11, 12, 14, 15, 19, 20, 22, 23, 24, 27, 28, 29, 30, 31, 32, 33, 34, 37, 38, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 51, 52, 53, 54, 55, 56, 57, 58, 60, 62, 63, 65, 68, 69, 70, 74, 75, 76, 77, 78, 80, 81, 83, 84, 85, 86, 87, 88, 89, 90, 93, 95, 97, 98, 100, 101, 104, 106, 107, 109, 110, 112, 115, 117, 119, 120, 121, 123, 125, 126, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 143, 146, 147, 148, 149, 150, 156, 157, 160, 162, 163, 164, 165, 166, 169, 170, 171, 172, 173, 174, 176, 177, 178, 180, 182, 183, 185, 187, 192, 193, 195, 196, 198, 199, 200, 201, 202, 203, 204, 205, 206, 208, 209, 210, 211, 213, 214, 215, 216, 217, 219, 220, 221, 222, 223, 224, 227, 228, 230, 231, 232, 234, 237, 0, 2, 3, 10, 11, 14, 15, 20, 24, 27, 34, 35, 38, 41, 45, 51, 52, 55, 57, 63, 65, 69, 70, 75, 77, 78, 81, 82, 83, 84, 86, 90, 95, 97, 100, 101, 107, 109, 113, 117, 123, 129, 134, 135, 136, 141, 143, 146, 149, 150, 158, 160, 162, 163, 165, 169, 172, 173, 174, 176, 177, 178, 179, 180, 183, 184, 187, 191, 198, 199, 201, 203, 206, 208, 209, 211, 212, 213, 214, 215, 219, 220, 223, 227, 228, 234]],\n               names=[u'UC2 Literal', u'neighborhood'])\n\n\n\n\n```python\ncrime_summary.reset_index().head(20)\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>UC2 Literal</th>\n      <th>neighborhood</th>\n      <th>offense_id</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>AGG ASSAULT</td>\n      <td>Adair Park</td>\n      <td>23</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>AGG ASSAULT</td>\n      <td>Adams Park</td>\n      <td>13</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>AGG ASSAULT</td>\n      <td>Adamsville</td>\n      <td>22</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>AGG ASSAULT</td>\n      <td>Almond Park</td>\n      <td>8</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>AGG ASSAULT</td>\n      <td>Argonne Forest</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>AGG ASSAULT</td>\n      <td>Arlington Estates</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>AGG ASSAULT</td>\n      <td>Ashley Courts</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>AGG ASSAULT</td>\n      <td>Ashview Heights</td>\n      <td>15</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>AGG ASSAULT</td>\n      <td>Atlanta University Center</td>\n      <td>21</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>AGG ASSAULT</td>\n      <td>Atlantic Station</td>\n      <td>7</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>AGG ASSAULT</td>\n      <td>Baker Hills</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>AGG ASSAULT</td>\n      <td>Bankhead</td>\n      <td>28</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>AGG ASSAULT</td>\n      <td>Bankhead/Bolton</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>AGG ASSAULT</td>\n      <td>Beecher Hills</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>AGG ASSAULT</td>\n      <td>Ben Hill</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>AGG ASSAULT</td>\n      <td>Ben Hill Forest</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>AGG ASSAULT</td>\n      <td>Ben Hill Pines</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>AGG ASSAULT</td>\n      <td>Ben Hill Terrace</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>AGG ASSAULT</td>\n      <td>Benteen Park</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>AGG ASSAULT</td>\n      <td>Berkeley Park</td>\n      <td>6</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\ndf[\"Zone\"] = df.beat // 100\n```\n\n\n```python\ndf\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>MI_PRINX</th>\n      <th>offense_id</th>\n      <th>rpt_date</th>\n      <th>occur_date</th>\n      <th>occur_time</th>\n      <th>poss_date</th>\n      <th>poss_time</th>\n      <th>beat</th>\n      <th>apt_office_prefix</th>\n      <th>apt_office_num</th>\n      <th>...</th>\n      <th>MaxOfnum_victims</th>\n      <th>Shift</th>\n      <th>Avg Day</th>\n      <th>loc_type</th>\n      <th>UC2 Literal</th>\n      <th>neighborhood</th>\n      <th>npu</th>\n      <th>x</th>\n      <th>y</th>\n      <th>Zone</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>206914</th>\n      <td>1371687</td>\n      <td>150562000</td>\n      <td>05/14/2013</td>\n      <td>05/14/2013</td>\n      <td>09:00:00</td>\n      <td>05/14/2013</td>\n      <td>11:30:00</td>\n      <td>205</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Day</td>\n      <td>Tue</td>\n      <td>18.0</td>\n      <td>LARCENY-FROM VEHICLE</td>\n      <td>Woodfield</td>\n      <td>C</td>\n      <td>-84.40912</td>\n      <td>33.82308</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>207443</th>\n      <td>4346442</td>\n      <td>150010052</td>\n      <td>01/01/2015</td>\n      <td>12/31/2014</td>\n      <td>22:00:00</td>\n      <td>01/01/2015</td>\n      <td>00:07:00</td>\n      <td>512</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Morn</td>\n      <td>Wed</td>\n      <td>NaN</td>\n      <td>LARCENY-FROM VEHICLE</td>\n      <td>Downtown</td>\n      <td>M</td>\n      <td>-84.39361</td>\n      <td>33.75246</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>207444</th>\n      <td>4346443</td>\n      <td>150010079</td>\n      <td>01/01/2015</td>\n      <td>01/01/2015</td>\n      <td>00:03:00</td>\n      <td>01/01/2015</td>\n      <td>00:03:00</td>\n      <td>606</td>\n      <td>NaN</td>\n      <td>3377</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>26.0</td>\n      <td>ROBBERY-PEDESTRIAN</td>\n      <td>Grant Park</td>\n      <td>W</td>\n      <td>-84.35917</td>\n      <td>33.73991</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>207445</th>\n      <td>4346444</td>\n      <td>150010151</td>\n      <td>01/01/2015</td>\n      <td>12/31/2014</td>\n      <td>23:45:00</td>\n      <td>01/01/2015</td>\n      <td>00:21:00</td>\n      <td>208</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>18.0</td>\n      <td>LARCENY-NON VEHICLE</td>\n      <td>Buckhead Forest</td>\n      <td>B</td>\n      <td>-84.37462</td>\n      <td>33.84564</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>207446</th>\n      <td>4346445</td>\n      <td>150010214</td>\n      <td>01/01/2015</td>\n      <td>01/01/2015</td>\n      <td>00:30:00</td>\n      <td>01/01/2015</td>\n      <td>01:05:00</td>\n      <td>407</td>\n      <td>1000</td>\n      <td>1009</td>\n      <td>...</td>\n      <td>2</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>26.0</td>\n      <td>AGG ASSAULT</td>\n      <td>Fairburn Mays</td>\n      <td>H</td>\n      <td>-84.50968</td>\n      <td>33.74349</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>207447</th>\n      <td>4346446</td>\n      <td>150010359</td>\n      <td>01/01/2015</td>\n      <td>12/31/2014</td>\n      <td>21:00:00</td>\n      <td>01/01/2015</td>\n      <td>00:15:00</td>\n      <td>512</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Eve</td>\n      <td>Wed</td>\n      <td>18.0</td>\n      <td>AUTO THEFT</td>\n      <td>Downtown</td>\n      <td>M</td>\n      <td>-84.39303</td>\n      <td>33.75094</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>207448</th>\n      <td>4346447</td>\n      <td>150010370</td>\n      <td>01/01/2015</td>\n      <td>12/31/2014</td>\n      <td>23:15:00</td>\n      <td>01/01/2015</td>\n      <td>01:47:00</td>\n      <td>505</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>13.0</td>\n      <td>LARCENY-FROM VEHICLE</td>\n      <td>Midtown</td>\n      <td>E</td>\n      <td>-84.38882</td>\n      <td>33.77511</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>207449</th>\n      <td>4346448</td>\n      <td>150010413</td>\n      <td>01/01/2015</td>\n      <td>12/31/2014</td>\n      <td>23:00:00</td>\n      <td>01/01/2015</td>\n      <td>02:00:00</td>\n      <td>303</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>3</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>13.0</td>\n      <td>LARCENY-FROM VEHICLE</td>\n      <td>Mechanicsville</td>\n      <td>V</td>\n      <td>-84.39903</td>\n      <td>33.73631</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>207450</th>\n      <td>4346449</td>\n      <td>150010417</td>\n      <td>01/01/2015</td>\n      <td>01/01/2015</td>\n      <td>02:00:00</td>\n      <td>01/01/2015</td>\n      <td>02:03:00</td>\n      <td>304</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>14.0</td>\n      <td>LARCENY-NON VEHICLE</td>\n      <td>Summerhill</td>\n      <td>V</td>\n      <td>-84.38686</td>\n      <td>33.74229</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>207451</th>\n      <td>4346450</td>\n      <td>150010419</td>\n      <td>01/01/2015</td>\n      <td>01/01/2015</td>\n      <td>01:50:00</td>\n      <td>01/01/2015</td>\n      <td>02:00:00</td>\n      <td>403</td>\n      <td>NaN</td>\n      <td>A</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>20.0</td>\n      <td>AGG ASSAULT</td>\n      <td>Oakland City</td>\n      <td>S</td>\n      <td>-84.42831</td>\n      <td>33.71759</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>207452</th>\n      <td>4346451</td>\n      <td>150010442</td>\n      <td>01/01/2015</td>\n      <td>01/01/2015</td>\n      <td>00:30:00</td>\n      <td>01/01/2015</td>\n      <td>01:45:00</td>\n      <td>302</td>\n      <td>NaN</td>\n      <td>4347</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>26.0</td>\n      <td>AUTO THEFT</td>\n      <td>Pittsburgh</td>\n      <td>V</td>\n      <td>-84.40177</td>\n      <td>33.73396</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>207453</th>\n      <td>4346452</td>\n      <td>150010468</td>\n      <td>01/01/2015</td>\n      <td>01/01/2015</td>\n      <td>02:15:00</td>\n      <td>01/01/2015</td>\n      <td>02:30:00</td>\n      <td>509</td>\n      <td>ROOM</td>\n      <td>702</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>NaN</td>\n      <td>AGG ASSAULT</td>\n      <td>Downtown</td>\n      <td>M</td>\n      <td>-84.38406</td>\n      <td>33.76139</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>207454</th>\n      <td>4346453</td>\n      <td>150010565</td>\n      <td>01/01/2015</td>\n      <td>12/31/2014</td>\n      <td>22:00:00</td>\n      <td>01/01/2015</td>\n      <td>03:09:00</td>\n      <td>508</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>2</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>18.0</td>\n      <td>LARCENY-FROM VEHICLE</td>\n      <td>Downtown</td>\n      <td>M</td>\n      <td>-84.38840</td>\n      <td>33.76444</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>207455</th>\n      <td>4346454</td>\n      <td>150010601</td>\n      <td>01/01/2015</td>\n      <td>01/01/2015</td>\n      <td>03:00:00</td>\n      <td>01/01/2015</td>\n      <td>07:00:00</td>\n      <td>509</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>2</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>13.0</td>\n      <td>AGG ASSAULT</td>\n      <td>Downtown</td>\n      <td>M</td>\n      <td>-84.38554</td>\n      <td>33.76929</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>207456</th>\n      <td>4346455</td>\n      <td>150010604</td>\n      <td>01/01/2015</td>\n      <td>12/31/2014</td>\n      <td>19:45:00</td>\n      <td>01/01/2015</td>\n      <td>03:20:00</td>\n      <td>104</td>\n      <td>NaN</td>\n      <td>8201</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Morn</td>\n      <td>Wed</td>\n      <td>26.0</td>\n      <td>BURGLARY-RESIDENCE</td>\n      <td>Ashview Heights</td>\n      <td>T</td>\n      <td>-84.42057</td>\n      <td>33.74647</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>207457</th>\n      <td>4346456</td>\n      <td>150010608</td>\n      <td>01/01/2015</td>\n      <td>01/01/2015</td>\n      <td>02:48:00</td>\n      <td>01/01/2015</td>\n      <td>03:26:00</td>\n      <td>305</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>NaN</td>\n      <td>ROBBERY-PEDESTRIAN</td>\n      <td>South Atlanta</td>\n      <td>Y</td>\n      <td>-84.38374</td>\n      <td>33.71730</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>207458</th>\n      <td>4346457</td>\n      <td>150010661</td>\n      <td>01/01/2015</td>\n      <td>01/01/2015</td>\n      <td>02:00:00</td>\n      <td>01/01/2015</td>\n      <td>02:40:00</td>\n      <td>207</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>21.0</td>\n      <td>ROBBERY-PEDESTRIAN</td>\n      <td>Underwood Hills</td>\n      <td>D</td>\n      <td>-84.41623</td>\n      <td>33.80076</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>207459</th>\n      <td>4346458</td>\n      <td>150010872</td>\n      <td>01/01/2015</td>\n      <td>01/01/2015</td>\n      <td>05:40:00</td>\n      <td>01/01/2015</td>\n      <td>06:00:00</td>\n      <td>611</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>2</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>26.0</td>\n      <td>BURGLARY-RESIDENCE</td>\n      <td>The Villages at East Lake</td>\n      <td>O</td>\n      <td>-84.31650</td>\n      <td>33.74577</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>207460</th>\n      <td>4346459</td>\n      <td>150010893</td>\n      <td>01/01/2015</td>\n      <td>01/01/2015</td>\n      <td>04:30:00</td>\n      <td>01/01/2015</td>\n      <td>05:00:00</td>\n      <td>304</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>13.0</td>\n      <td>AGG ASSAULT</td>\n      <td>Summerhill</td>\n      <td>V</td>\n      <td>-84.38909</td>\n      <td>33.74245</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>207461</th>\n      <td>4346460</td>\n      <td>150010977</td>\n      <td>01/01/2015</td>\n      <td>01/01/2015</td>\n      <td>06:30:00</td>\n      <td>01/01/2015</td>\n      <td>06:45:00</td>\n      <td>602</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>13.0</td>\n      <td>LARCENY-NON VEHICLE</td>\n      <td>Old Fourth Ward</td>\n      <td>M</td>\n      <td>-84.37191</td>\n      <td>33.76728</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>207462</th>\n      <td>4346461</td>\n      <td>150010989</td>\n      <td>01/01/2015</td>\n      <td>12/31/2014</td>\n      <td>21:00:00</td>\n      <td>01/01/2015</td>\n      <td>08:22:00</td>\n      <td>108</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>2</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>20.0</td>\n      <td>LARCENY-FROM VEHICLE</td>\n      <td>Dixie Hills</td>\n      <td>J</td>\n      <td>-84.45890</td>\n      <td>33.75336</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>207463</th>\n      <td>4346462</td>\n      <td>150011005</td>\n      <td>01/01/2015</td>\n      <td>12/31/2014</td>\n      <td>15:00:00</td>\n      <td>01/01/2015</td>\n      <td>06:00:00</td>\n      <td>303</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Eve</td>\n      <td>Wed</td>\n      <td>NaN</td>\n      <td>LARCENY-FROM VEHICLE</td>\n      <td>Mechanicsville</td>\n      <td>V</td>\n      <td>-84.39806</td>\n      <td>33.73833</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>207464</th>\n      <td>4346463</td>\n      <td>150011023</td>\n      <td>01/01/2015</td>\n      <td>01/01/2015</td>\n      <td>08:18:00</td>\n      <td>01/01/2015</td>\n      <td>08:48:00</td>\n      <td>409</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Day</td>\n      <td>Thu</td>\n      <td>20.0</td>\n      <td>AGG ASSAULT</td>\n      <td>Southwest</td>\n      <td>R</td>\n      <td>-84.49750</td>\n      <td>33.69867</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>207465</th>\n      <td>4346464</td>\n      <td>150011124</td>\n      <td>01/01/2015</td>\n      <td>01/01/2015</td>\n      <td>02:00:00</td>\n      <td>01/01/2015</td>\n      <td>02:30:00</td>\n      <td>112</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>3.0</td>\n      <td>ROBBERY-PEDESTRIAN</td>\n      <td>Collier Heights</td>\n      <td>I</td>\n      <td>-84.49110</td>\n      <td>33.78520</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>207466</th>\n      <td>4346465</td>\n      <td>150011131</td>\n      <td>01/01/2015</td>\n      <td>12/31/2014</td>\n      <td>11:00:00</td>\n      <td>01/01/2015</td>\n      <td>05:00:00</td>\n      <td>508</td>\n      <td>NaN</td>\n      <td>637</td>\n      <td>...</td>\n      <td>4</td>\n      <td>Unk</td>\n      <td>Wed</td>\n      <td>14.0</td>\n      <td>LARCENY-NON VEHICLE</td>\n      <td>Downtown</td>\n      <td>M</td>\n      <td>-84.39003</td>\n      <td>33.75896</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>207467</th>\n      <td>4346466</td>\n      <td>150011181</td>\n      <td>01/01/2015</td>\n      <td>12/31/2014</td>\n      <td>20:30:00</td>\n      <td>01/01/2015</td>\n      <td>10:45:00</td>\n      <td>103</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>NaN</td>\n      <td>AUTO THEFT</td>\n      <td>English Avenue</td>\n      <td>L</td>\n      <td>-84.40498</td>\n      <td>33.76527</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>207468</th>\n      <td>4346467</td>\n      <td>150011209</td>\n      <td>01/01/2015</td>\n      <td>01/01/2015</td>\n      <td>10:15:00</td>\n      <td>01/01/2015</td>\n      <td>10:15:00</td>\n      <td>603</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>0</td>\n      <td>Day</td>\n      <td>Thu</td>\n      <td>18.0</td>\n      <td>LARCENY-NON VEHICLE</td>\n      <td>Old Fourth Ward</td>\n      <td>M</td>\n      <td>-84.37140</td>\n      <td>33.77097</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>207469</th>\n      <td>4346468</td>\n      <td>150011234</td>\n      <td>01/01/2015</td>\n      <td>12/31/2014</td>\n      <td>22:30:00</td>\n      <td>01/01/2015</td>\n      <td>03:00:00</td>\n      <td>302</td>\n      <td>NaN</td>\n      <td>1423</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>18.0</td>\n      <td>AUTO THEFT</td>\n      <td>Pittsburgh</td>\n      <td>V</td>\n      <td>-84.40177</td>\n      <td>33.73396</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>207470</th>\n      <td>4346469</td>\n      <td>150011237</td>\n      <td>01/01/2015</td>\n      <td>12/31/2014</td>\n      <td>22:30:00</td>\n      <td>01/01/2015</td>\n      <td>11:30:00</td>\n      <td>410</td>\n      <td>NaN</td>\n      <td>C17</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>26.0</td>\n      <td>LARCENY-NON VEHICLE</td>\n      <td>Fort Valley</td>\n      <td>R</td>\n      <td>-84.45149</td>\n      <td>33.70055</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>207471</th>\n      <td>4346470</td>\n      <td>150011253</td>\n      <td>01/01/2015</td>\n      <td>12/31/2014</td>\n      <td>23:47:00</td>\n      <td>01/01/2015</td>\n      <td>11:38:00</td>\n      <td>501</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>26.0</td>\n      <td>LARCENY-NON VEHICLE</td>\n      <td>Atlantic Station</td>\n      <td>E</td>\n      <td>-84.39541</td>\n      <td>33.79231</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>237423</th>\n      <td>4376422</td>\n      <td>153651689</td>\n      <td>12/31/2015</td>\n      <td>11/01/2015</td>\n      <td>12:00:00</td>\n      <td>12/31/2015</td>\n      <td>15:45:00</td>\n      <td>402</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Unk</td>\n      <td>Unk</td>\n      <td>20.0</td>\n      <td>BURGLARY-RESIDENCE</td>\n      <td>Oakland City</td>\n      <td>S</td>\n      <td>-84.42550</td>\n      <td>33.72696</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>237424</th>\n      <td>4376423</td>\n      <td>153651697</td>\n      <td>12/31/2015</td>\n      <td>12/18/2015</td>\n      <td>12:00:00</td>\n      <td>12/20/2015</td>\n      <td>12:00:00</td>\n      <td>612</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Unk</td>\n      <td>Unk</td>\n      <td>18.0</td>\n      <td>LARCENY-NON VEHICLE</td>\n      <td>East Atlanta</td>\n      <td>W</td>\n      <td>-84.33524</td>\n      <td>33.73099</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>237425</th>\n      <td>4376424</td>\n      <td>153651707</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>15:45:00</td>\n      <td>12/31/2015</td>\n      <td>16:15:00</td>\n      <td>509</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>9.0</td>\n      <td>LARCENY-NON VEHICLE</td>\n      <td>Downtown</td>\n      <td>M</td>\n      <td>-84.38702</td>\n      <td>33.76044</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>237426</th>\n      <td>4376425</td>\n      <td>153651745</td>\n      <td>12/31/2015</td>\n      <td>12/23/2015</td>\n      <td>22:00:00</td>\n      <td>12/31/2015</td>\n      <td>14:00:00</td>\n      <td>310</td>\n      <td>NaN</td>\n      <td>34C</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Unk</td>\n      <td>Unk</td>\n      <td>26.0</td>\n      <td>BURGLARY-RESIDENCE</td>\n      <td>Browns Mill Park</td>\n      <td>Z</td>\n      <td>-84.39417</td>\n      <td>33.68294</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>237427</th>\n      <td>4376426</td>\n      <td>153651751</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>15:30:00</td>\n      <td>12/31/2015</td>\n      <td>16:00:00</td>\n      <td>306</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>4</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>18.0</td>\n      <td>LARCENY-FROM VEHICLE</td>\n      <td>Sylvan Hills</td>\n      <td>X</td>\n      <td>-84.41113</td>\n      <td>33.69731</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>237428</th>\n      <td>4376427</td>\n      <td>153651774</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>06:00:00</td>\n      <td>12/31/2015</td>\n      <td>13:30:00</td>\n      <td>202</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Day</td>\n      <td>Thu</td>\n      <td>20.0</td>\n      <td>LARCENY-FROM VEHICLE</td>\n      <td>Randall Mill</td>\n      <td>A</td>\n      <td>-84.42172</td>\n      <td>33.85375</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>237429</th>\n      <td>4376428</td>\n      <td>153651776</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>01:00:00</td>\n      <td>12/31/2015</td>\n      <td>16:45:00</td>\n      <td>401</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Day</td>\n      <td>Thu</td>\n      <td>23.0</td>\n      <td>AUTO THEFT</td>\n      <td>West End</td>\n      <td>T</td>\n      <td>-84.41435</td>\n      <td>33.74042</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>237430</th>\n      <td>4376429</td>\n      <td>153651836</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>14:00:00</td>\n      <td>12/31/2015</td>\n      <td>16:30:00</td>\n      <td>213</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>NaN</td>\n      <td>LARCENY-NON VEHICLE</td>\n      <td>Piedmont Heights</td>\n      <td>F</td>\n      <td>-84.37101</td>\n      <td>33.79789</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>237431</th>\n      <td>4376430</td>\n      <td>153651969</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>17:45:00</td>\n      <td>12/31/2015</td>\n      <td>18:15:00</td>\n      <td>210</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>8.0</td>\n      <td>LARCENY-NON VEHICLE</td>\n      <td>Lenox</td>\n      <td>B</td>\n      <td>-84.36212</td>\n      <td>33.84676</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>237432</th>\n      <td>4376431</td>\n      <td>153651972</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>18:18:00</td>\n      <td>12/31/2015</td>\n      <td>18:18:00</td>\n      <td>611</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>20.0</td>\n      <td>BURGLARY-RESIDENCE</td>\n      <td>East Lake</td>\n      <td>O</td>\n      <td>-84.30354</td>\n      <td>33.74624</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>237433</th>\n      <td>4376432</td>\n      <td>153652007</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>18:20:00</td>\n      <td>12/31/2015</td>\n      <td>18:38:00</td>\n      <td>403</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>31.0</td>\n      <td>AGG ASSAULT</td>\n      <td>Oakland City</td>\n      <td>S</td>\n      <td>-84.42892</td>\n      <td>33.71896</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>237434</th>\n      <td>4376433</td>\n      <td>153652008</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>18:30:00</td>\n      <td>12/31/2015</td>\n      <td>18:38:00</td>\n      <td>101</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>NaN</td>\n      <td>ROBBERY-PEDESTRIAN</td>\n      <td>Atlanta University Center</td>\n      <td>T</td>\n      <td>-84.40436</td>\n      <td>33.75323</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>237435</th>\n      <td>4376434</td>\n      <td>153652014</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>16:45:00</td>\n      <td>12/31/2015</td>\n      <td>17:00:00</td>\n      <td>503</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>13.0</td>\n      <td>AUTO THEFT</td>\n      <td>Midtown</td>\n      <td>E</td>\n      <td>-84.38387</td>\n      <td>33.78305</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>237436</th>\n      <td>4376435</td>\n      <td>153652081</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>19:00:00</td>\n      <td>12/31/2015</td>\n      <td>19:20:00</td>\n      <td>303</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>26.0</td>\n      <td>AGG ASSAULT</td>\n      <td>Mechanicsville</td>\n      <td>V</td>\n      <td>-84.39741</td>\n      <td>33.74116</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>237437</th>\n      <td>4376436</td>\n      <td>153652105</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>19:05:00</td>\n      <td>12/31/2015</td>\n      <td>19:20:00</td>\n      <td>303</td>\n      <td>NaN</td>\n      <td>6</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>26.0</td>\n      <td>AGG ASSAULT</td>\n      <td>Mechanicsville</td>\n      <td>V</td>\n      <td>-84.40200</td>\n      <td>33.74187</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>237438</th>\n      <td>4376437</td>\n      <td>153652157</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>19:10:00</td>\n      <td>12/31/2015</td>\n      <td>19:45:00</td>\n      <td>207</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>2</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>18.0</td>\n      <td>LARCENY-FROM VEHICLE</td>\n      <td>Berkeley Park</td>\n      <td>D</td>\n      <td>-84.41575</td>\n      <td>33.79835</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>237439</th>\n      <td>4376438</td>\n      <td>153652170</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>18:06:00</td>\n      <td>12/31/2015</td>\n      <td>18:12:00</td>\n      <td>208</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>8.0</td>\n      <td>LARCENY-NON VEHICLE</td>\n      <td>North Buckhead</td>\n      <td>B</td>\n      <td>-84.36235</td>\n      <td>33.85166</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>237440</th>\n      <td>4376439</td>\n      <td>153652249</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>19:45:00</td>\n      <td>12/31/2015</td>\n      <td>20:00:00</td>\n      <td>412</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>13.0</td>\n      <td>ROBBERY-PEDESTRIAN</td>\n      <td>Heritage Valley</td>\n      <td>P</td>\n      <td>-84.50263</td>\n      <td>33.70432</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>237441</th>\n      <td>4376440</td>\n      <td>153652313</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>11:30:00</td>\n      <td>12/31/2015</td>\n      <td>20:00:00</td>\n      <td>113</td>\n      <td>NaN</td>\n      <td>B313</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>26.0</td>\n      <td>BURGLARY-RESIDENCE</td>\n      <td>Carey Park</td>\n      <td>G</td>\n      <td>-84.47292</td>\n      <td>33.78810</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>237442</th>\n      <td>4376441</td>\n      <td>153652478</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>19:00:00</td>\n      <td>12/31/2015</td>\n      <td>20:30:00</td>\n      <td>204</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>2</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>18.0</td>\n      <td>LARCENY-FROM VEHICLE</td>\n      <td>Underwood Hills</td>\n      <td>D</td>\n      <td>-84.42161</td>\n      <td>33.80224</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>237443</th>\n      <td>4376442</td>\n      <td>153652499</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>09:00:00</td>\n      <td>12/31/2015</td>\n      <td>09:00:00</td>\n      <td>208</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Day</td>\n      <td>Thu</td>\n      <td>18.0</td>\n      <td>LARCENY-FROM VEHICLE</td>\n      <td>Buckhead Forest</td>\n      <td>B</td>\n      <td>-84.37291</td>\n      <td>33.84286</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>237444</th>\n      <td>4376443</td>\n      <td>153652534</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>21:26:00</td>\n      <td>12/31/2015</td>\n      <td>22:28:00</td>\n      <td>313</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>20.0</td>\n      <td>AUTO THEFT</td>\n      <td>Blair Villa/Poole Creek</td>\n      <td>Z</td>\n      <td>-84.37888</td>\n      <td>33.66185</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>237445</th>\n      <td>4376444</td>\n      <td>153652703</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>22:00:00</td>\n      <td>12/31/2015</td>\n      <td>22:30:00</td>\n      <td>107</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>20.0</td>\n      <td>BURGLARY-RESIDENCE</td>\n      <td>Grove Park</td>\n      <td>J</td>\n      <td>-84.44629</td>\n      <td>33.77318</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>237446</th>\n      <td>4376445</td>\n      <td>153652724</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>22:00:00</td>\n      <td>12/31/2015</td>\n      <td>22:30:00</td>\n      <td>508</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>NaN</td>\n      <td>AGG ASSAULT</td>\n      <td>Downtown</td>\n      <td>M</td>\n      <td>-84.39152</td>\n      <td>33.75700</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>237447</th>\n      <td>4376446</td>\n      <td>153652840</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>22:10:00</td>\n      <td>12/31/2015</td>\n      <td>22:30:00</td>\n      <td>612</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>18.0</td>\n      <td>AUTO THEFT</td>\n      <td>East Atlanta</td>\n      <td>W</td>\n      <td>-84.33588</td>\n      <td>33.73126</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>237448</th>\n      <td>4376447</td>\n      <td>153652866</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>22:30:00</td>\n      <td>12/31/2015</td>\n      <td>23:00:00</td>\n      <td>610</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>23.0</td>\n      <td>LARCENY-NON VEHICLE</td>\n      <td>Kirkwood</td>\n      <td>O</td>\n      <td>-84.32665</td>\n      <td>33.74774</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>237449</th>\n      <td>4376448</td>\n      <td>153652876</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>17:00:00</td>\n      <td>12/31/2015</td>\n      <td>23:00:00</td>\n      <td>303</td>\n      <td>NaN</td>\n      <td>1408</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>26.0</td>\n      <td>BURGLARY-RESIDENCE</td>\n      <td>Mechanicsville</td>\n      <td>V</td>\n      <td>-84.40649</td>\n      <td>33.74005</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>237450</th>\n      <td>4376449</td>\n      <td>153652888</td>\n      <td>01/01/2016</td>\n      <td>12/31/2015</td>\n      <td>23:05:00</td>\n      <td>01/01/2016</td>\n      <td>00:50:00</td>\n      <td>313</td>\n      <td>NaN</td>\n      <td>22</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Morn</td>\n      <td>Thu</td>\n      <td>13.0</td>\n      <td>AGG ASSAULT</td>\n      <td>South River Gardens</td>\n      <td>Z</td>\n      <td>-84.36187</td>\n      <td>33.67102</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>237451</th>\n      <td>4376450</td>\n      <td>153653047</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>21:30:00</td>\n      <td>12/31/2015</td>\n      <td>23:47:00</td>\n      <td>603</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>2</td>\n      <td>Eve</td>\n      <td>Thu</td>\n      <td>13.0</td>\n      <td>LARCENY-FROM VEHICLE</td>\n      <td>Old Fourth Ward</td>\n      <td>M</td>\n      <td>-84.36450</td>\n      <td>33.77073</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>237452</th>\n      <td>4376451</td>\n      <td>153658045</td>\n      <td>12/31/2015</td>\n      <td>12/31/2015</td>\n      <td>13:02:00</td>\n      <td>12/31/2015</td>\n      <td>13:15:00</td>\n      <td>704</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>...</td>\n      <td>1</td>\n      <td>Day</td>\n      <td>Thu</td>\n      <td>NaN</td>\n      <td>LARCENY-NON VEHICLE</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>-84.44824</td>\n      <td>33.63751</td>\n      <td>7</td>\n    </tr>\n  </tbody>\n</table>\n<p>30011 rows \u00d7 24 columns</p>\n</div>\n\n\n\n## Exploring Dates\n\n\n```python\ndf[['offense_id', 'occur_date', 'occur_time', 'rpt_date']][1:10]\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>offense_id</th>\n      <th>occur_date</th>\n      <th>occur_time</th>\n      <th>rpt_date</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>207443</th>\n      <td>150010052</td>\n      <td>12/31/2014</td>\n      <td>22:00:00</td>\n      <td>01/01/2015</td>\n    </tr>\n    <tr>\n      <th>207444</th>\n      <td>150010079</td>\n      <td>01/01/2015</td>\n      <td>00:03:00</td>\n      <td>01/01/2015</td>\n    </tr>\n    <tr>\n      <th>207445</th>\n      <td>150010151</td>\n      <td>12/31/2014</td>\n      <td>23:45:00</td>\n      <td>01/01/2015</td>\n    </tr>\n    <tr>\n      <th>207446</th>\n      <td>150010214</td>\n      <td>01/01/2015</td>\n      <td>00:30:00</td>\n      <td>01/01/2015</td>\n    </tr>\n    <tr>\n      <th>207447</th>\n      <td>150010359</td>\n      <td>12/31/2014</td>\n      <td>21:00:00</td>\n      <td>01/01/2015</td>\n    </tr>\n    <tr>\n      <th>207448</th>\n      <td>150010370</td>\n      <td>12/31/2014</td>\n      <td>23:15:00</td>\n      <td>01/01/2015</td>\n    </tr>\n    <tr>\n      <th>207449</th>\n      <td>150010413</td>\n      <td>12/31/2014</td>\n      <td>23:00:00</td>\n      <td>01/01/2015</td>\n    </tr>\n    <tr>\n      <th>207450</th>\n      <td>150010417</td>\n      <td>01/01/2015</td>\n      <td>02:00:00</td>\n      <td>01/01/2015</td>\n    </tr>\n    <tr>\n      <th>207451</th>\n      <td>150010419</td>\n      <td>01/01/2015</td>\n      <td>01:50:00</td>\n      <td>01/01/2015</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nConvert into date-time type\n\n\n```python\ndf['occur_ts'] = pd.to_datetime(df.occur_date+' '+df.occur_time)\n```\n\n\n```python\n#df[['offense_id', 'occur_date', 'occur_time', 'occur_ts', 'rpt_date']][1:10]\n```\n\n\n```python\n\n```\n\n\n```python\ndf['occur_ts'] = pd.to_datetime(df.occur_date+' '+df.occur_time)\n```\n\n\n```python\ndf['occur_month'] = df['occur_ts'].map(lambda x: x.month)\ndf['occur_woy'] = df.occur_ts.dt.weekofyear\n```\n\n\n```python\ndf.describe()\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>MI_PRINX</th>\n      <th>offense_id</th>\n      <th>beat</th>\n      <th>MinOfucr</th>\n      <th>MaxOfnum_victims</th>\n      <th>loc_type</th>\n      <th>x</th>\n      <th>y</th>\n      <th>Zone</th>\n      <th>occur_month</th>\n      <th>occur_woy</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>3.001100e+04</td>\n      <td>3.001100e+04</td>\n      <td>30011.000000</td>\n      <td>30011.000000</td>\n      <td>30011.000000</td>\n      <td>26903.000000</td>\n      <td>30011.000000</td>\n      <td>30011.000000</td>\n      <td>30011.000000</td>\n      <td>29997.000000</td>\n      <td>29997.000000</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>4.361347e+06</td>\n      <td>1.518675e+08</td>\n      <td>359.417813</td>\n      <td>594.219886</td>\n      <td>1.194695</td>\n      <td>21.109356</td>\n      <td>-84.408346</td>\n      <td>33.756058</td>\n      <td>3.527307</td>\n      <td>6.654399</td>\n      <td>27.453312</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>1.931052e+04</td>\n      <td>1.029128e+06</td>\n      <td>169.563281</td>\n      <td>114.321851</td>\n      <td>0.799062</td>\n      <td>16.579831</td>\n      <td>0.046894</td>\n      <td>0.045981</td>\n      <td>1.700308</td>\n      <td>3.365509</td>\n      <td>14.700785</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>1.371687e+06</td>\n      <td>1.500101e+08</td>\n      <td>101.000000</td>\n      <td>210.000000</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n      <td>-84.546070</td>\n      <td>33.637450</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>4.353944e+06</td>\n      <td>1.510128e+08</td>\n      <td>208.000000</td>\n      <td>512.000000</td>\n      <td>1.000000</td>\n      <td>13.000000</td>\n      <td>-84.432445</td>\n      <td>33.729060</td>\n      <td>2.000000</td>\n      <td>4.000000</td>\n      <td>15.000000</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>4.361446e+06</td>\n      <td>1.518913e+08</td>\n      <td>401.000000</td>\n      <td>640.000000</td>\n      <td>1.000000</td>\n      <td>18.000000</td>\n      <td>-84.398210</td>\n      <td>33.756000</td>\n      <td>4.000000</td>\n      <td>7.000000</td>\n      <td>28.000000</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>4.368948e+06</td>\n      <td>1.527329e+08</td>\n      <td>505.000000</td>\n      <td>670.000000</td>\n      <td>1.000000</td>\n      <td>21.000000</td>\n      <td>-84.374420</td>\n      <td>33.781470</td>\n      <td>5.000000</td>\n      <td>10.000000</td>\n      <td>40.000000</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>4.376451e+06</td>\n      <td>1.536580e+08</td>\n      <td>709.000000</td>\n      <td>730.000000</td>\n      <td>44.000000</td>\n      <td>99.000000</td>\n      <td>-84.290480</td>\n      <td>33.883250</td>\n      <td>7.000000</td>\n      <td>12.000000</td>\n      <td>53.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndf.shape\n```\n\n\n\n\n    (30011, 27)\n\n\n\n\n```python\ndf.columns\n```\n\n\n\n\n    Index([         u'MI_PRINX',        u'offense_id',          u'rpt_date',\n                  u'occur_date',        u'occur_time',         u'poss_date',\n                   u'poss_time',              u'beat', u'apt_office_prefix',\n              u'apt_office_num',          u'location',          u'MinOfucr',\n               u'MinOfibr_code',        u'dispo_code',  u'MaxOfnum_victims',\n                       u'Shift',           u'Avg Day',          u'loc_type',\n                 u'UC2 Literal',      u'neighborhood',               u'npu',\n                           u'x',                 u'y',              u'Zone',\n                    u'occur_ts',       u'occur_month',         u'occur_woy'],\n          dtype='object')\n\n\n\n\n```python\ndf.iloc[9]\n```\n\n\n\n\n    MI_PRINX                            4346450\n    offense_id                        150010419\n    rpt_date                         01/01/2015\n    occur_date                       01/01/2015\n    occur_time                         01:50:00\n    poss_date                        01/01/2015\n    poss_time                          02:00:00\n    beat                                    403\n    apt_office_prefix                       NaN\n    apt_office_num                            A\n    location             1231 CAMPBELLTON PL SW\n    MinOfucr                                430\n    MinOfibr_code                          1315\n    dispo_code                               10\n    MaxOfnum_victims                          1\n    Shift                                  Morn\n    Avg Day                                 Thu\n    loc_type                                 20\n    UC2 Literal                     AGG ASSAULT\n    neighborhood                   Oakland City\n    npu                                       S\n    x                                  -84.4283\n    y                                   33.7176\n    occur_ts                2015-01-01 01:50:00\n    Name: 207451, dtype: object\n\n\n\n\n```python\n#resdf.index\n```\n\n\n```python\nresdf.loc[['AUTO_THEFT', 6]]\n```\n\n\n```python\nresdf = df.groupby(['UC2 Literal', 'occur_date']).offense_id.count()\nresdf\n```\n\n\n\n\n    UC2 Literal        occur_date\n    AGG ASSAULT        01/01/2009    1\n                       01/01/2015    6\n                       01/02/2015    6\n                       01/03/2015    7\n                       01/04/2015    4\n                       01/05/2015    3\n                       01/06/2015    4\n                       01/07/2015    6\n                       01/08/2015    5\n                       01/09/2015    7\n                       01/10/2015    3\n                       01/11/2015    9\n                       01/12/2015    3\n                       01/13/2015    1\n                       01/14/2015    7\n                       01/15/2015    2\n                       01/16/2015    3\n                       01/17/2015    3\n                       01/18/2015    7\n                       01/19/2015    9\n                       01/20/2015    5\n                       01/21/2015    2\n                       01/22/2015    6\n                       01/23/2015    3\n                       01/24/2015    3\n                       01/25/2015    3\n                       01/26/2015    8\n                       01/27/2015    6\n                       01/28/2015    5\n                       01/29/2015    9\n                                    ..\n    ROBBERY-RESIDENCE  10/02/2015    1\n                       10/03/2015    1\n                       10/04/2015    1\n                       10/08/2015    1\n                       10/10/2015    1\n                       10/18/2015    1\n                       10/20/2015    1\n                       10/21/2015    1\n                       10/24/2015    1\n                       11/01/2015    1\n                       11/02/2015    2\n                       11/09/2015    2\n                       11/11/2015    1\n                       11/13/2015    1\n                       11/20/2015    1\n                       11/23/2014    1\n                       11/27/2015    1\n                       11/28/2015    1\n                       12/02/2015    1\n                       12/04/2015    1\n                       12/06/2015    1\n                       12/10/2015    1\n                       12/11/2015    2\n                       12/19/2015    1\n                       12/21/2015    1\n                       12/22/2015    1\n                       12/27/2015    1\n                       12/29/2015    1\n                       12/30/2015    1\n                       12/31/2015    1\n    Name: offense_id, dtype: int64\n\n\n\n\n```python\nresdf['BURGLARY-RESIDENCE'].as_matrix()\n```\n\n\n\n\n    array([13,  1,  6, 12,  7,  9, 12,  6,  1, 11, 10,  1, 10,  7, 17, 16, 10,\n           18, 15, 18, 10,  7, 16,  1,  8, 10,  9, 11, 11, 16,  8, 15, 16, 10,\n            9, 11, 14,  4, 13,  9,  8, 13,  8,  3,  6, 10, 10, 16,  5,  2,  6,\n            3,  3,  7, 10,  4,  8, 13,  9,  5,  7, 13, 13, 12,  9,  6, 12, 12,\n           13,  5,  8,  9,  7,  9,  9, 14,  6,  8, 15,  9, 12,  7, 13,  8,  5,\n           10, 16, 15,  9,  6, 13,  3, 14,  9, 17, 15, 17, 12,  4, 18,  9, 14,\n            9, 15,  5, 11, 11, 13, 11,  7,  8,  6,  6, 16, 11,  9,  8,  6, 10,\n            3,  7, 13,  8, 12, 12,  8,  9, 11, 17,  7, 17, 15,  8,  4,  9, 23,\n            1, 20, 12, 10,  1,  7,  6, 21, 11, 12,  1, 12, 14, 13,  6,  5, 18,\n           18, 15, 13, 13,  6, 11, 14, 13,  8, 15, 10,  6, 11,  6,  4,  7,  7,\n           12,  5,  8, 10, 14, 15, 12, 12,  9, 11, 17, 11, 17, 22,  9,  6, 10,\n           11, 10, 19, 14, 11,  2, 13, 10,  4, 11, 16,  9,  6, 12, 16,  9, 14,\n           13,  8,  6, 11,  5, 13,  6,  7,  9,  8, 19,  9, 10,  7, 10,  9,  3,\n            9,  9, 12,  4, 12,  6,  5, 13,  7,  1,  9, 10,  1,  9, 11,  4, 10,\n           10,  8, 14,  7,  8,  5,  9, 14, 14,  8, 17,  8, 13, 13, 13, 13,  8,\n            9,  7,  6,  8, 21, 10, 11, 17,  6, 10,  6, 12, 10,  6,  8, 10,  8,\n           13, 13,  7,  8, 11,  7,  5, 12, 15,  8, 17, 12, 10,  1,  9, 10, 14,\n           10, 10, 12,  7,  8, 12,  9, 14,  5,  8,  7,  6,  9, 10,  7, 20, 13,\n            1, 19,  7, 12, 16,  1, 11,  9, 13, 11,  8, 16,  8, 11,  7,  8, 11,\n            4, 12,  1, 18,  9, 15, 12,  3,  2,  4, 15, 17, 12,  1,  8,  2, 16,\n           14, 11, 13, 11, 15,  9, 15,  6, 11,  1, 14, 19, 18, 12, 18,  1, 17,\n            8,  1, 14,  1, 14, 13,  2, 18, 19,  1,  8, 13, 21,  1, 10,  1, 20,\n           14,  1, 21,  8,  2, 20, 13,  1,  9,  1,  8,  2, 10, 10,  1,  8,  6,\n           12,  1,  6,  2, 15,  2,  9])\n\n\n\n\n```python\nresdf['BURGLARY-RESIDENCE'].iloc(0)\n```\n\n\n\n\n    <pandas.core.indexing._iLocIndexer at 0x7f73610>\n\n\n\n\n```python\nresdf['BURGLARY-RESIDENCE']\n```\n\n\n\n\n    occur_date\n    01/01/2015    13\n    01/02/2014     1\n    01/02/2015     6\n    01/03/2015    12\n    01/04/2015     7\n    01/05/2015     9\n    01/06/2015    12\n    01/07/2015     6\n    01/08/2014     1\n    01/08/2015    11\n    01/09/2015    10\n    01/10/2014     1\n    01/10/2015    10\n    01/11/2015     7\n    01/12/2015    17\n    01/13/2015    16\n    01/14/2015    10\n    01/15/2015    18\n    01/16/2015    15\n    01/17/2015    18\n    01/18/2015    10\n    01/19/2015     7\n    01/20/2015    16\n    01/21/2014     1\n    01/21/2015     8\n    01/22/2015    10\n    01/23/2015     9\n    01/24/2015    11\n    01/25/2015    11\n    01/26/2015    16\n                  ..\n    12/13/2015    13\n    12/14/2015    21\n    12/15/2014     1\n    12/15/2015    10\n    12/16/2014     1\n    12/16/2015    20\n    12/17/2015    14\n    12/18/2014     1\n    12/18/2015    21\n    12/19/2015     8\n    12/20/2014     2\n    12/20/2015    20\n    12/21/2015    13\n    12/22/2014     1\n    12/22/2015     9\n    12/23/2014     1\n    12/23/2015     8\n    12/24/2014     2\n    12/24/2015    10\n    12/25/2015    10\n    12/26/2014     1\n    12/26/2015     8\n    12/27/2015     6\n    12/28/2015    12\n    12/29/2014     1\n    12/29/2015     6\n    12/30/2014     2\n    12/30/2015    15\n    12/31/2014     2\n    12/31/2015     9\n    Name: offense_id, dtype: int64\n\n\n\n\n```python\n%matplotlib inline\nfig = plt.figure(figsize=(10,6)) # 10inx10in\n#plt.plot(resdf['BURGLARY-RESIDENCE'].index, resdf['BURGLARY-RESIDENCE'])\nplt.scatter(resdf['BURGLARY-RESIDENCE'].index, resdf['BURGLARY-RESIDENCE'].values, marker='x')\n# plt.scatter(resdf['BURGLARY-NONRES'].index, resdf['BURGLARY-NONRES'], marker='o')\n\n# plt.ylim(0, 500)\n# plt.title('BURGLARY-RESIDENCE')\n# plt.xticks(range(13), ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])\n# fig.savefig('BurglaryResidence_over_month.svg')\n# x = 1\n```\n\n\n```python\ndef getTheMonth(x):\n    return x.month\n\ndf['occur_month'] = df['occur_ts'].map(getTheMonth)\n```\n\n\n```python\ndf = pd.read_excel('/home/data/APD/COBRA083016_2015.xlsx', sheetname='Query')\ndf['occur_ts'] = pd.to_datetime(df.occur_date+' '+df.occur_time)\ndf['occur_month'] = df['occur_ts'].map(lambda x: x.month)\ndf['occur_woy'] = df.occur_ts.dt.weekofyear\n```\n\n\n```python\n%matplotlib inline\nresdf = df.groupby(['UC2 Literal', 'occur_month']).offense_id.count()\nfig = plt.figure(figsize=(10,6))\nplt.scatter(resdf['BURGLARY-RESIDENCE'].index, resdf['BURGLARY-RESIDENCE'], marker='x')\nplt.ylim(0, 500)\nplt.title('BURGLARY-RESIDENCE')\nplt.xticks(range(13), ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])\nplt.savefig('quiz3-burglary-residence.png')\n\n''\n```\n\n\n```python\nplt.savefig('quiz3-burglary-residence.png')\n\n```\n\n# Part 1 - Observations from the data\n\n\n\n```python\npd.unique(df) # how to get duplicate records?\n```\n\n\n```python\npd.unique(df['UC2 Literal'])\n```\n\n\n\n\n    array([u'LARCENY-FROM VEHICLE', u'ROBBERY-PEDESTRIAN',\n           u'LARCENY-NON VEHICLE', u'AGG ASSAULT', u'AUTO THEFT',\n           u'BURGLARY-RESIDENCE', u'ROBBERY-RESIDENCE', u'BURGLARY-NONRES',\n           u'ROBBERY-COMMERCIAL', u'RAPE'], dtype=object)\n\n\n\n\n```python\nlen(pd.unique(df.MI_PRINX))\n```\n\n\n\n\n    30011\n\n\n\n# Part 2 - Seasonal Model\n\n\n```python\n## load complete dataset\ndff = pd.read_excel('/home/data/APD/COBRA083016.xlsx', sheetname='Query')\n```\n\n\n```python\ndff.shape\n```\n\n\n```python\nfor evt in ['occur', 'poss']:\n    dff['%s_ts'%evt] = pd.to_datetime(dff['%s_date'%evt]+' '+dff['%s_time'%evt])\ndff['rpt_ts'] = pd.to_datetime(dff.rpt_date)\n```\n\n\n```python\n', '.join(dff.columns)\n```\n\n\n```python\ndff['occur_year'] = dff.occur_ts.dt.year\ndff['occur_month'] = dff.occur_ts.dt.month\ndff['occur_dayweek'] = dff.occur_ts.dt.dayofweek\n```\n\n### Crime per year\nLet's look at the \n\n\n```python\ncrime_year = dff[dff.occur_year.between(2009, 2015)].groupby(by=['UC2 Literal', 'occur_year']).offense_id.count()\n```\n\n\n```python\n%matplotlib inline\nfig = plt.figure(figsize=(40,30))\ncrime_types = crime_year.index.levels[0]\nyears = crime_year.index.levels[1]\nfor c in range(len(crime_types)):\n    y_max = max(crime_year.loc[crime_types[c]])\n    \n    plt.subplot(4,3,c+1)\n    plt.hlines(crime_year.loc[crime_types[c]].iloc[-1]*100/y_max, years[0], years[-1], linestyles=\"dashed\", color=\"r\")\n    plt.bar(crime_year.loc[crime_types[c]].index, crime_year.loc[crime_types[c]]*100/y_max, label=crime_types[c], alpha=0.5)\n    ##plt.legend()\n    plt.ylim(0, 100)\n    plt.xticks(years+0.4, [str(int(y)) for y in years], rotation=0, fontsize=24)\n    plt.yticks([0,20,40,60,80,100], ['0%','20%','40%','60%','80%','100%'], fontsize=24)\n    plt.title(crime_types[c], fontsize=30)\n    None\n```\n\nLet's look at residential burglary.\n\n\n```python\nc = 3\ncrime_types[c]\n```\n\n\n```python\ncrime_year_month = dff[dff.occur_year.between(2009, 2015)].groupby(by=['UC2 Literal', 'occur_year', 'occur_month']).offense_id.count()\n```\n\n\n```python\nc = 3 ## 'BURGLARY-RESIDENCE'\nresburglaries = crime_year_month.loc[crime_types[c]]\nfig = plt.figure(figsize=(20,10))\nfor y in years:\n    plt.plot(resburglaries.loc[y].index, resburglaries.loc[y], label=(\"%4.0f\"%y))\nplt.legend()\nplt.title(\"Seasonal Trends - %s\"%crime_types[c], fontsize=20)\nplt.xticks(range(13), ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])\nplt.xlim(0,13)\nNone\n```\n\nNormalized over the annual average\n\n\n```python\nc = 3 ## 'BURGLARY-RESIDENCE'\nfig = plt.figure(figsize=(20,10))\nfor y in years:\n    avg = resburglaries.loc[y].mean()\n    plt.hlines(avg, 1, 13, linestyle='dashed')\n    plt.plot(resburglaries.loc[y].index, resburglaries.loc[y], label=(\"%4.0f\"%y))\nplt.legend()\nplt.title(\"Seasonal Trends - %s (with annuale averages)\"%crime_types[c], fontsize=20)\nplt.xticks(list(range(1,13)), ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])\nplt.xlim(0,13)\nNone\n```\n\n\n```python\nc = 3 ## 'BURGLARY-RESIDENCE'\nfig = plt.figure(figsize=(20,10))\nfor y in years:\n    avg = resburglaries.loc[y].mean()\n    std = resburglaries.loc[y].std()\n    ##plt.hlines(avg, 1, 13, linestyle='dashed')\n    plt.plot(resburglaries.loc[y].index, (resburglaries.loc[y]-avg)/std, label=(\"%4.0f\"%y))\nplt.legend()\nplt.title(\"Seasonal Trends - %s (normalized)\"%crime_types[c], fontsize=20)\nplt.xticks(list(range(1,13)), ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])\nplt.xlim(0,13)\nplt.ylabel(\"Standard deviations $\\sigma_y$\")\nNone\n```\n\n\n```python\n\n```\n\n\n```python\nseasonal_adjust = resburglaries.reset_index().groupby(by=['occur_month']).offense_id.agg('mean')\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n### Fitting the regression line\nSuppose there are $n$ data points {{math|{(''x<sub>i</sub>'', ''y<sub>i</sub>''), ''i'' {{=}} 1, ..., ''n''}.}} The function that describes x and y is:\n\n$$y_i = \\alpha + \\beta x_i + \\varepsilon_i.$$\n\nThe goal is to find the equation of the straight line\n\n$$y = \\alpha + \\beta x,$$\n\nwhich would provide a \"best\" fit for the data points. Here the \"best\" will be understood as in the [[Ordinary least squares|least-squares]] approach: a line that minimizes the sum of squared residuals of the linear regression model. In other words, {{mvar|\u03b1}} (the {{mvar|y}}-intercept) and {{mvar|\u03b2}} (the slope) solve the following minimization problem:\n\n$$\\text{Find }\\min_{\\alpha,\\,\\beta} Q(\\alpha, \\beta), \\qquad \\text{for } Q(\\alpha, \\beta) = \\sum_{i=1}^n\\varepsilon_i^{\\,2} = \\sum_{i=1}^n (y_i - \\alpha - \\beta x_i)^2\\ $$\n\nBy using either [[calculus]], the geometry of [[inner product space]]s, or simply expanding to get a quadratic expression in {{mvar|\u03b1}} and {{mvar|\u03b2}}, it can be shown that the values of {{mvar|\u03b1}} and {{mvar|\u03b2}} that minimize the objective function {{mvar|Q}}<ref>Kenney, J. F. and Keeping, E. S. (1962) \"Linear Regression and Correlation.\" Ch. 15 in ''Mathematics of Statistics'', Pt. 1, 3rd ed. Princeton, NJ: Van Nostrand, pp. 252\u2013285</ref> are\n\n: <math>\\begin{align}\n  \\hat\\beta &= \\frac{ \\sum_{i=1}^{n} (x_i - \\bar{x})(y_i - \\bar{y}) }{ \\sum_{i=1}^n (x_i - \\bar{x})^2 } \\\\[6pt]\n            &= \\frac{ \\sum_{i=1}^{n} (x_i y_i - x_i \\bar{y} - \\bar{x} y_i + \\bar{x} \\bar{y})} { \\sum_{i=1}^n (x_i^2 - 2 x_i \\bar{x} + \\bar{x}^2) } \\\\[6pt]\n            &= \\frac{ \\sum_{i=1}^{n} (x_i y_i) - \\bar{y} \\sum_{i=1}^{n}  x_i  - \\bar{x} \\sum_{i=1}^{n} y_i + n  \\bar{x} \\bar{y}} { \\sum_{i=1}^n (x_i^2) - 2 \\bar{x}  \\sum_{i=1}^n  x_i  + n \\bar{x}^2 } \\\\[6pt]\n            &= \\frac{ \\frac{1}{n} \\sum_{i=1}^{n} x_i y_i - \\bar{x} \\bar{y} }{ \\frac{1}{n}\\sum_{i=1}^n {x_i^2} -   \\overline{x}^2 } \\\\[6pt]\n            &= \\frac{ \\overline{xy} - \\bar{x}\\bar{y} }{ \\overline{x^2} - \\bar{x}^2 } = \\frac{ \\operatorname{Cov}[x, y] }{ \\operatorname{Var}[x] } \\\\\n            &= r_{xy} \\frac{s_y}{s_x}, \\\\[6pt]\n \\hat\\alpha & = \\bar{y} - \\hat\\beta\\,\\bar{x},\n\\end{align}</math>\n\nwhere {{math|''r<sub>xy</sub>''}} is the [[Correlation#Pearson's product-moment coefficient|sample correlation coefficient]] between {{mvar|x}} and {{mvar|y}}; and {{math|''s<sub>x</sub>''}} and {{math|''s<sub>y</sub>''}} are the [[sample standard deviation]] of {{mvar|x}} and {{mvar|y}}. A horizontal bar over a quantity indicates the average value of that quantity. For example:\n\n:<math>\\overline{xy} = \\frac{1}{n} \\sum_{i=1}^n x_i y_i.</math>\n\nSubstituting the above expressions for <math>\\hat{\\alpha}</math> and <math>\\hat{\\beta}</math> into\n\n: <math>f = \\hat{\\alpha} + \\hat{\\beta} x,</math>\n\nyields\n\n: <math>\\frac{ f - \\bar{y}}{s_y} = r_{xy} \\frac{ x - \\bar{x}}{s_x}  </math>\n\nThis shows that {{math|''r<sub>xy</sub>''}} is the slope of the regression line of the [[Standard score|standardized]] data points (and that this line passes through the origin).\n\nIt is sometimes useful to calculate {{math|''r<sub>xy</sub>''}} from the data independently using this equation:\n\n:<math>r_{xy} = \\frac{ \\overline{xy} - \\bar{x}\\bar{y} }{ \\sqrt{ \\left(\\overline{x^2} - \\bar{x}^2\\right)\\left(\\overline{y^2} - \\bar{y}^2\\right)} } </math>\n\nThe [[coefficient of determination]] (R squared) is equal to <math>r_{xy}^2</math> when the model is linear with a single independent variable. See [[Correlation#Pearson's product-moment coefficient|sample correlation coefficient]] for additional details.\n\n===Linear regression without the intercept term===\nSometimes it is appropriate to force the regression line to pass through the origin, because {{mvar|x}} and {{mvar|y}} are assumed to be proportional. For the model without the intercept term, {{math|''y'' {{=}} ''\u03b2x''}}, the OLS estimator for {{mvar|\u03b2}} simplifies to\n\n: <math>\\hat{\\beta} = \\frac{ \\sum_{i=1}^n x_i y_i }{ \\sum_{i=1}^n x_i^2 } = \\frac{\\overline{x y}}{\\overline{x^2}} </math>\n\nSubstituting {{math|(''x'' \u2212 ''h'', ''y'' \u2212 ''k'')}} in place of {{math|(''x'', ''y'')}} gives the regression through {{math|(''h'', ''k'')}}:\n\n: <math>\\begin{align}\n  \\hat\\beta &= \\frac{\\overline{(x - h) (y - k)}}{\\overline{(x - h)^2}} \\\\[6pt]\n            &= \\frac{\\overline{x y} + k \\bar{x} - h \\bar{y} - h k }{\\overline{x^2} - 2 h \\bar{x} + h^2} \\\\[6pt]\n            &= \\frac{\\overline{x y} - \\bar{x} \\bar{y} + (\\bar{x} - h)(\\bar{y} - k)}{\\overline{x^2} - \\bar{x}^2 + (\\bar{x} - h)^2} \\\\[6pt]\n            &= \\frac{\\operatorname{Cov}[x,y] + (\\bar{x} - h)(\\bar{y}-k)}{\\operatorname{Var}[x] + (\\bar{x} - h)^2}\n\\end{align}</math>\n\nThe last form above demonstrates how moving the line away from the center of mass of the data points affects the slope.\n\n\n\n```python\n### in case we want to save a DataFrame\n#writer = pd.ExcelWriter('myresults.xlsx')\n#df.to_excel(writer,'Results')\n#writer.save()\n```\n\n\n```python\n#resdf\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "3afda219f3d0e83e754811370955645df0003735", "size": 190558, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "04-Pandas-Data-Tables/APD-Crime-Data_class.ipynb", "max_stars_repo_name": "peterbengkui/DataProgramming", "max_stars_repo_head_hexsha": "90ee1181acaaae754b2f2fd028638e07c4c6cde7", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-07T19:00:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-07T19:00:10.000Z", "max_issues_repo_path": "04-Pandas-Data-Tables/APD-Crime-Data_class.ipynb", "max_issues_repo_name": "peterbengkui/DataProgramming", "max_issues_repo_head_hexsha": "90ee1181acaaae754b2f2fd028638e07c4c6cde7", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "04-Pandas-Data-Tables/APD-Crime-Data_class.ipynb", "max_forks_repo_name": "peterbengkui/DataProgramming", "max_forks_repo_head_hexsha": "90ee1181acaaae754b2f2fd028638e07c4c6cde7", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-12T17:44:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-12T17:44:10.000Z", "avg_line_length": 43.8265869365, "max_line_length": 11739, "alphanum_fraction": 0.4500414572, "converted": true, "num_tokens": 40170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10521053950871516, "lm_q2_score": 0.06465348114723148, "lm_q1q2_score": 0.006802227632616768}}
{"text": "## Uncomment & Run the below cell if you're using Colab\n\n\n```python\n# !git clone https://github.com/mayahq/g-index-benchmark\n# %cd /content/g-index-benchmark/notebooks/\n```\n\n    fatal: destination path 'g-index-benchmark' already exists and is not an empty directory.\n    [Errno 2] No such file or directory: '/content/g-index-benchmark/notebooks/'\n    /home/atlas/dagbert-code/g-index-benchmark/notebooks\n\n\n## Imports\n\n\n```python\nimport glob\nimport json\nimport os\nimport sys\nfrom collections import defaultdict\nfrom os import PathLike\nfrom pprint import pprint\nfrom statistics import mean\nfrom typing import Union\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom tqdm import tqdm\n\nmodule_path = os.path.abspath(os.path.join(\"..\"))\nif module_path not in sys.path:\n    sys.path.append(module_path)\n\nimport ipywidgets as widgets\nfrom ipywidgets import Dropdown, FloatLogSlider, FloatSlider, IntSlider, interact\n\nfrom g_index import Experiment\nfrom node_utils import node_divergence\nfrom utils import *\n\n# Experiment Settings\nEXP_ROOT = \"../experiments/\"\nEXP_FILES = glob.glob(EXP_ROOT + \"/*.json\")\nDD_CACHE = cache_dd()\nDOMAIN_LENGTHS = get_domain_lengths(AVAILABLE_DOMAINS)\n\n##Plot Settings\nALPHA, S = 0.90, 240\nFIGSIZE = (16,9)\nLABEL_SIZE = 24\nTICK_SIZE = 20\nTITLE_SIZE = 24\nLEGEND_SIZE = 20\n\ncolors = [\"#375E97\", \"#FB6542\", \"#FFBB00\", \"#3F681C\"]\nsim_colors = [\"#C03221\", \"#A049AB\", \"#3C28B8\", \"#545E75\", \"#3F826D\"]\nmodels = [\"gpt2-774M\", \"gpt2-345M\", \"gpt2-1.5B\", \"gptneo-2.7B\"]\nmodel_colormap = {model: color for color, model in zip(colors, models)}\nmodel_name_correction = {\n    \"gpt2-medium\": \"gpt2-345M\",\n    \"gpt2-large\": \"gpt2-774M\",\n    \"gpt2-xl\": \"gpt2-1.5B\",\n    \"EleutherAI gpt-neo-2.7B\": \"gptneo-2.7B\",\n}\n```\n\n## 1. Domains\n\n### What are domains\n\nA set of tasks \\$C$ can be clustered into `Task Domains`. <br>\nTasks within the same domain are <i>closer</i> to each other than tasks in different domains.\n\n### List of Available Domains\n\n\n```python\nfor i, domain in enumerate(AVAILABLE_DOMAINS):\n    print(i, \" \", domain)\n```\n\n    0   template-slider\n    1   template-form\n    2   url-skill\n    3   cron-schedule\n    4   gmail-send\n    5   telegram-3-reply\n    6   telegram-2-reply\n    7   youtube-pause\n    8   youtube-resume\n    9   http\n    10   cron-reminder\n    11   google-search\n    12   twitter\n    13   youtube-play\n    14   facebook\n    15   googlesearch-to-csv\n\n\n### What is Domain Distance ( $\\Omega$ )\n\nDomain Distance of a Task $T'$ from a set of tasks $C$ is the \nsimilarity between optimal DAG program for $T'$ and it's nearest neighbour in $C$.\n\n\\begin{equation}\n\t\\label{domain-distcalc}\n\t\\begin{aligned}\n\t\t \\Omega(T', C) & = \\min\\limits_{T \\in C} \\Delta(G_{P'_{opt}}, G_{P_T})                                          &   & \\\\\n\t\t              & \\text{where }  G_{P'_{opt}} \\text{denotes the DAG of the optimal solution $P'_{opt}$ of $T'$} &   & \\\\\n\t\t              & \\text{and }    G_{P'_T} \\text{ denotes the DAG for a program $P_T$ that solves\n\t\t $T \\in C$}    &                                                                                                &\n\t\\end{aligned}\n\\end{equation}\n\nDomain distance can be calculated for a set of tasks $T'$ by averaging over all tasks.\n\n### Calculating domain distance between two domains\n\nDomain distance can be calculated between any two domains in `AVAILABLE_DOMAINS`\n\n\n```python\ndomain_1 = Dropdown(options=AVAILABLE_DOMAINS, description=\"Domain 1\")\ndomain_2 = Dropdown(options=AVAILABLE_DOMAINS, description=\"Domain 2\")\n\n@interact(domain_1=domain_1, domain_2=domain_2)\ndef get_dd_i(domain_1, domain_2):\n    print(calculate_dd(domain_1, domain_2))\n```\n\n\n    interactive(children=(Dropdown(description='Domain 1', options=('template-slider', 'template-form', 'url-skill\u2026\n\n\n### Calculating Domain Distance between two JSON files\n\nTreating each file as it's own domain with a single sample Domain Distance can be calculated between two domain files.\n\n\n```python\ndomain_1 = widgets.Text(\n    value=\"../domains/youtube-pause/youtube-pause-6e696d.json\",\n    placeholder=\"Enter Relative File Path\",\n    description=\"Domain 1 :\",\n    disabled=False,\n)\ndomain_2 = widgets.Text(\n    value=\"../domains/facebook/facebook-b4ee9a.json\",\n    placeholder=\"Enter Relative File Path \",\n    description=\"Domain 2 :\",\n    disabled=False,\n)\n\n\n@interact(domain_1=domain_1, domain_2=domain_2)\ndef get_dd_files_i(domain_1, domain_2):\n    dd = calculate_dd(domain_1, domain_2)\n    if dd is not None:\n        print(f\"DD: {dd}\")\n```\n\n\n    interactive(children=(Text(value='../domains/youtube-pause/youtube-pause-6e696d.json', description='Domain 1 :\u2026\n\n\n### Plotting the Domain Distance Matrix\n\nDomain Distance between various domain can easily be visualised with the following heatmap.\n\n\n\n```python\nsns.set(rc={\"figure.figsize\": (16, 12)})\ngenerate_dd_matrix()\n```\n\n## 2. Experiments\n\n### Components of an experiment\n\nThe Major Components of an experiment are:\n1. Intelligent System (`IS`)\n2. Curricula Domains ($C$) \n3. Task Domains ($\\{T'\\}$)\n4. Experience (`E`) \n5. Generalization Difficulty (GD)\n6. Performance Details\n7. AveragePerformance ($\\theta$)\n\nNote: Uncheck `truncate_domains` to view full domain data\n\n\n```python\nexperiments = Dropdown(options=EXP_FILES, description=\"Experiments\")\n@interact(exp_file=experiments,truncate_domains=True)\ndef print_exp_components_i(exp_file, truncate_domains=False):\n    exp = Experiment(exp_file)\n    exp.get_exp_components(truncate_domains=truncate_domains, print_members=True)\n```\n\n\n    interactive(children=(Dropdown(description='Experiments', options=('../experiments/GPT2_1_5B_2.json', '../expe\u2026\n\n\n## 3. g-index\n\n### What is `g-index`?\n\n<em>`g-index`</em> is used to measure skill-acquisition efficiency of any intelligence system on a set of real-world tasks.\n\n\n\n### Calculating `g-index` from an experiment files\n\nSteps:\n1. Select an Experiment file in the Experiment Class\n2. Run `calculate_g_index` function\n\n\n```python\nexperiments = Dropdown(options=EXP_FILES, description=\"Experiments\")\n@interact(exp_file=experiments)\ndef get_g_index_i(exp_file):\n    exp = Experiment(exp_file)\n    print(f\"g-index: {exp.calculate_g_index()}\")\n```\n\n\n    interactive(children=(Dropdown(description='Experiments', options=('../experiments/GPT2_1_5B_2.json', '../expe\u2026\n\n\n### Calculating `g-index` from Values\n\n\n```python\nstyle = {\"description_width\": \"100px\"}\nn_tasks_domain = IntSlider(value=5,min=1,max=100,step=1,description=\"Samples per Task domain\",style=style)\nn_curricula_domain = IntSlider(value=5,min=1,max=100,step=1,description=\"Samples per Curricula domain\",style=style)\nsim_dd = FloatSlider(value=0.0,min=0.0,max=1.00,step=0.01,description=\"Generalization Difficulty\",style=style)\nsim_P = FloatLogSlider(value=-3, min=-10, max=10, step=1, description=\"Prior\", style=style)\nsim_E = FloatLogSlider(value=1, min=1, max=12, step=1, description=\"Experience\", style=style)\nsim_PTheta = FloatSlider(value=0.1,min=0.00,max=1.00,step=0.01,description=\"Performance \u03b8\",style=style)\n\n\n@interact(n_tasks_domain= n_tasks_domain,n_curricula_domain = n_curricula_domain,sim_dd = sim_dd,sim_P= sim_P,sim_E = sim_E,sim_PTheta = sim_PTheta)\ndef get_g_index_sim_i(n_tasks_domain,n_curricula_domain,sim_dd,sim_P,sim_E,sim_PTheta):\n    exp = Experiment()\n    g_index =  exp.simulate_g_index(n_tasks_domain= n_tasks_domain,n_curricula_domain = n_curricula_domain,sim_dd = sim_dd,sim_P= sim_P,sim_E = sim_E,sim_PTheta = sim_PTheta)\n    print(f\"g-index: {g_index}\")\n```\n\n\n    interactive(children=(IntSlider(value=5, description='Samples per Task domain', min=1, style=SliderStyle(descr\u2026\n\n\n## 4. Reproducing results mentioned in the paper\n\n## Disclaimer\n\n\nThe experiments data & the domain samples provided are a small fraction of the data used during the research. \nDue to this, your results might vary from the reported results. <br>\nInterested people can go to the section 5 to get more info.\n\n### Section-4.1 Simulation Plots\n\n#### g-index vs Training Samples ( for varying $\\theta$ ) \n\n<big> Setting up the following Simulation variables</big>\n\n1. Number of samples per curricula domain (Varying) \n2. Average performance (Varying) \n3. Number of samples per task domain (Fixed) \n4. Iterations per domain  \n5. Raw experience (compute) \n6. Priors\n\n\n```python\nns_curricula_domain = [ 20 * i for i in range(1, 33)]# No of Samples per domain from 20 to 640\nsim_PthetaValues = np.around( np.arange(0.2, 1.2, 0.2), 2).tolist()  # Average Performance Values from 0.2 to 1.0\nnum_domains = len(AVAILABLE_DOMAINS)\nn_tasks_domain = 5\niters_per_domain = 20\nsim_E = 1e2\nsim_P = 1e-3\nsim_dd = None \ndd_cache = cache_dd() # To speed up the simulations by using precalculated domain distances across domains.\n```\n\n\n```python\nresults_gt = defaultdict(dict) \nfor sim_Ptheta in tqdm(sim_PthetaValues):\n    dummy_exp = Experiment(dd_cache=dd_cache) # Setup a dummy experiment to simulate values\n    ns_gi = {\"samples_per_domain\": [], \"g_index\": []}\n    for ns_per_domain in ns_curricula_domain:\n        for _ in range(iters_per_domain):\n            # Randomly distribute samples across domains\n            CurriculaDistribution = dict(zip(AVAILABLE_DOMAINS, resplit(ns_per_domain, num_domains)))\n            # Get the value of g-index from simulations \n            g_index = dummy_exp.simulate_g_index(n_tasks_domain=n_tasks_domain,sim_P=sim_P,sim_E=sim_E,sim_PTheta=sim_Ptheta,\n                                                 CurriculaDistribution=CurriculaDistribution,sim_dd=sim_dd)\n            ns_gi[\"samples_per_domain\"].append(ns_per_domain)\n            ns_gi[\"g_index\"].append(g_index)\n    results_gt[sim_Ptheta] = ns_gi\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5/5 [00:56<00:00, 11.25s/it]\n\n\n\n```python\nfig, axes = plt.subplots(figsize=FIGSIZE)\nxlabel = \"Training Samples (per domain)\"\nylabel = \"g-index\"\nplt.xlabel(xlabel, fontsize=LABEL_SIZE)\nplt.ylabel(ylabel, fontsize=LABEL_SIZE)\naxes.tick_params(labelsize=TICK_SIZE)\naxes.tick_params(labelsize=TICK_SIZE)\nplt.xlim(20, 640)\nplt.ylim(0,13000)\nset_axes() # Fix axes spines & ticks, see utils.py for more details\n\nfor idx, sim_Ptheta in enumerate(results_gt.keys()):\n    vals = results_gt[sim_Ptheta]\n    x = vals[\"samples_per_domain\"]\n    y = vals[\"g_index\"]\n    # Curve Smoothing with 3 degree polynomial\n    fx = np.poly1d(np.polyfit(np.array(x), np.array(y), 3))\n    z = fx(x)\n    # Plot the confidence interval\n    sns.lineplot(x=x, y=y, ax=axes, legend=False,linewidth=0, color=sim_colors[idx])\n    # Plot against the smoothed value\n    sns.lineplot(x=x,y=z,ax=axes,legend=False,linewidth=2,label=f\"$\\\\theta$ = {sim_Ptheta}\",color=sim_colors[idx])\nplt.legend(loc=\"upper right\", labelcolor=\"black\",fontsize=LEGEND_SIZE)\nplt.tight_layout()\nplt.title(f\"{ylabel} vs {xlabel}\", loc=\"center\", fontsize=TITLE_SIZE)\nplt.show()\n```\n\n#### g-index vs Compute ( for varying $\\theta$ ) \n\n<big> Setting up the following Simulation variables</big>\n\n1. Compute steps (varying)\n2. Average performance (varying)\n3. Number of samples per curricula domain (fixed)\n4. Number of samples  per task domain (fixed)\n5. Iterations per domain (fixed) \n6. Priors (fixed)\n\n\n```python\nsim_compute_steps = [50 * i for i in range(1, 31)] # Compute from 50-1500\nsim_PthetaValues = np.around(np.arange(0.2, 1.2, 0.2), 2).tolist()  # Average Performance Values from 0.2 to 1.0\nn_samples_per_domain = 40\nn_tasks_domain = 5\nnum_domains = len(AVAILABLE_DOMAINS)\nsim_P = 1e-2\niters_per_compute_step = 5\ndd_cache = cache_dd()\nsim_dd = None\n```\n\n\n```python\nresults_gcp = defaultdict(dict)\n\nfor sim_Ptheta in tqdm(sim_PthetaValues):\n    dummy_exp = Experiment(dd_cache=dd_cache) # Setup a dummy experiment to simulate values\n    gi = {\"compute\": [], \"g_index\": []}\n    for sim_E in sim_compute_steps:\n        for itp in range(iters_per_compute_step):\n            \n            CurriculaDistribution = dict(zip(AVAILABLE_DOMAINS, resplit(n_samples_per_domain, num_domains)))\n            g_index = dummy_exp.simulate_g_index(\n                n_tasks_domain=n_tasks_domain,\n                sim_P=sim_P,\n                sim_E=sim_E,\n                sim_PTheta=sim_Ptheta,\n                CurriculaDistribution=CurriculaDistribution,\n                sim_dd=sim_dd)\n            gi[\"compute\"].append(sim_E)\n            gi[\"g_index\"].append(g_index)\n\n    results_gcp[sim_Ptheta] = gi\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5/5 [00:51<00:00, 10.21s/it]\n\n\n\n```python\nfig, axes = plt.subplots(figsize=FIGSIZE)\nxlabel = \"Compute\"\nylabel = \"g-index\"\nplt.xlim(50, 1500)\nplt.xlabel(xlabel, fontsize=LABEL_SIZE)\nplt.ylabel(ylabel, fontsize=LABEL_SIZE)\naxes.tick_params(labelsize=TICK_SIZE)\naxes.tick_params(labelsize=TICK_SIZE)\nset_axes() # Fix axes spines & ticks, see utils.py for more details\n\nfor idx, sim_Ptheta in enumerate(results_gcp.keys()):\n    vals = results_gcp.get(sim_Ptheta)\n    x = vals[\"compute\"]\n    y = vals[\"g_index\"]\n    # Plot the confidence interval\n    sns.lineplot(x=x, y=y, ax=axes, legend=False, linewidth=0, color=sim_colors[idx])\n    #Plot the actual non-smoothed line\n    sns.lineplot(x=x,y=y,ax=axes,legend=False,linewidth=2,label=f\"$\\\\theta$ = {sim_Ptheta}\",color=sim_colors[idx])\n\nplt.legend(loc=\"upper right\", labelcolor=\"black\",fontsize=LEGEND_SIZE)\nplt.tight_layout()\nplt.title(f\"{ylabel} vs {xlabel}\", loc=\"center\",fontsize=LEGEND_SIZE)\nplt.show()\n```\n\n#### G-index vs $\\theta$ ( for varying $\\Omega$ ) HeatMap\n\n<big> Setting up the following Simulation variables</big>\n\n1. Average performance (varying)\n2. Domain distance between domains (varying)\n3. Number of samples per curricula domain (fixed)\n4. Number of samples  per task domain (fixed)\n5. Raw Experience ( compute, fixed )\n6. Priors (fixed)\n7. Iterations per domain (fixed) \n\n\n```python\nsim_PthetaValues = np.around(np.linspace(0.00, 1, 50), 2) # Average Performance Values from 0.2 to 1.0\nn_curricula_domain = 40\nn_tasks_domain = 5\nnum_domains = len(AVAILABLE_DOMAINS)\nsim_E = 1e2\nsim_P = 1e-2\nn_iters_per_temp = 10\ndd_cache = cache_dd()\nsim_dd = None\n```\n\n\n```python\nresults_gt = defaultdict(dict)\n\nfor sim_PTheta in tqdm(sim_PthetaValues):\n    gi_dd = {\"theta\": [], \"g_index\": [], \"domain_distance\": []}\n    dummy_exp = Experiment() # Setup a dummy experiment to simulate values\n    for _ in range(n_iters_per_temp):\n        #Randomly sample domain_distance values for every two domains from a normal distribution\n        random_dd = {tA: {tB: val for tB, val in zip(AVAILABLE_DOMAINS,np.clip(np.random.normal(0.5, 0.4, 16), 0, 1).tolist())} for tA in AVAILABLE_DOMAINS}\n        g_index = dummy_exp.simulate_g_index(\n            n_tasks_domain=n_tasks_domain,\n            n_curricula_domain=n_curricula_domain,\n            sim_P=sim_P,\n            sim_E=sim_E,\n            sim_PTheta=sim_PTheta,\n            sim_dd=random_dd,\n        )\n        gi_dd[\"theta\"].append(sim_PTheta)\n        gi_dd[\"g_index\"].append(g_index)\n        # get random row and just get it's domain_dist average\n        gi_dd[\"domain_distance\"].append(random_row_mean(random_dd))\n    results_gt[sim_PTheta] = gi_dd\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 50/50 [00:25<00:00,  2.00it/s]\n\n\n\n```python\nylabel = \"g-index\"\nxlabel = \"$\\\\theta$\"\nfig, axes = plt.subplots(figsize=FIGSIZE)\nplt.xlabel(xlabel, fontsize=LABEL_SIZE)\nplt.ylabel(ylabel, fontsize=LABEL_SIZE)\naxes.tick_params(labelsize=TICK_SIZE)\naxes.tick_params(labelsize=TICK_SIZE)\nplt.xlim(0, 1.01)\nplt.ylim(0, 4000)\nset_axes() # Fix axes spines & ticks, see utils.py for more details\n\nxtotal, ytotal = [], []\nfor sim_PTheta in results_gt.keys():\n    vals = results_gt.get(sim_PTheta)\n    x = vals[\"theta\"]\n    y = vals[\"g_index\"]\n    h = vals[\"domain_distance\"]\n    xtotal.extend(x)\n    ytotal.extend(y)\n    #Plot the points x & y \n    sns.scatterplot(x=x, y=y, hue=h, ax=axes, legend=False, s=S, alpha=ALPHA, palette=\"rocket\")\n#Gather all points x & y  & apply polynomial smoothing \nfx = np.poly1d(np.polyfit(np.array(xtotal), np.array(ytotal), 3))\nz = fx(xtotal)\n#Plot the smoothed line\nsns.lineplot(x=xtotal, y=z, ax=axes, legend=False, linewidth=1, color=\"black\")\n# Add the colorbar for heatmap\nsm = plt.cm.ScalarMappable(cmap=\"rocket\")\naxes.figure.colorbar(sm).set_label(label=\"Domain Distance\",size=LEGEND_SIZE)\n\nplt.tight_layout()\nplt.title(f\"{ylabel} vs {xlabel}\", loc=\"center\",fontsize=TITLE_SIZE)\nplt.show()\n```\n\n### Section-4.2 Experiment Plots\n\n#### Average Performance ( $\\theta$ )  vs Training Samples\n\n\n```python\nresults = {\"IS\": [], \"avg_perf\": [], \"total_samples\": [], \"g_index\": []}\n\nfor exp_file in EXP_FILES:\n    exp = Experiment(exp_file)\n    exp_c = exp.get_exp_components() # Get components of an experiment\n    avg_perf = exp_c.AveragePerformance # Average Performance of an experiment \n    IS = exp_c.IS # Get the IS name of an experiment \n    CurriculaDomains = exp_c.CurriculaDomains # Get Curricula domains for an experiment \n    total_samples = sum([domain[\"num_samples\"] for domain in CurriculaDomains]) # Total curricula samples for an experiment\n    g_index = exp.calculate_g_index() # Get the g-index for an experiment \n\n    results[\"IS\"].append(IS)\n    results[\"avg_perf\"].append(avg_perf)\n    results[\"total_samples\"].append(total_samples)\n    results[\"g_index\"].append(g_index)\n```\n\n\n```python\ngi = results[\"g_index\"] \ng_i_dots_scales = [scale_dots(min(gi), c) for c in gi] #Calculate the scatterplot dots sizes based on g-index values\n#Create a data list of (Total Samples,Avg Performance, IS name, gindex_dot_sizes)\ndata_list = [[x, y, model_name, marker_size] for (x, y, model_name, marker_size) in zip(results[\"total_samples\"], results[\"avg_perf\"], results[\"IS\"], g_i_dots_scales)]\n```\n\n\n```python\nfig, axes = plt.subplots()\nylabel = \"$\\\\theta$\"\nxlabel = \"Training Samples\"\nplt.xlabel(xlabel, fontsize=LABEL_SIZE)\nplt.ylabel(ylabel, fontsize=LABEL_SIZE)\naxes.tick_params(labelsize=TICK_SIZE)\naxes.tick_params(labelsize=TICK_SIZE)\nplt.ylim(0, 1)\nset_axes(disable_ticks=False) # Fix axes spines & ticks, see utils.py for more details\n\ncolor_name = \"black\"\naxes.spines[\"top\"].set_color(color_name)\naxes.spines[\"bottom\"].set_color(color_name)\naxes.spines[\"left\"].set_color(color_name)\naxes.spines[\"right\"].set_color(color_name)\n\n#plot the points step by step\nfor entry in data_list:\n    color = model_colormap[model_name_correction[entry[2]]] # Get color value for a specified model\n    sns.scatterplot(x=[entry[0]], y=[entry[1]], color=color, s=entry[3], alpha=ALPHA) # plot every point on the axes\n\nplt.tight_layout()\n# Dummy plot to generate legend\nmarkers = [plt.Line2D([0, 0], [0, 0], color=color, marker=\"o\", linestyle=\"\") for color in model_colormap.values()]\nplt.legend(markers, model_colormap.keys(),fontsize=LEGEND_SIZE)\nplt.title(f\"{ylabel} vs {xlabel}\", loc=\"center\",fontsize=TITLE_SIZE)\nplt.show()\n```\n\n#### Average Domain Performance ( $\\theta$ ) vs Program Size\n\n\n```python\ndomains_considered = AVAILABLE_DOMAINS\nresults_pst = {\"IS\": [], \"domain_name\": [], \"program_size\": [], \"theta\": []}\n\nfor exp_file in EXP_FILES:\n    exp = Experiment(exp_file) # Setup a dummy experiment to simulate values\n    for domain in domains_considered:\n        exp_c = exp.get_exp_components() # Get components of an experiment\n        IS = exp_c.IS # Get the IS name of an experiment \n        perf_details = exp_c.PerformanceDetails # Per domain performance of an experiment \n        perf_details = next(item for item in perf_details if item[\"name\"] == domain)\n        program_size = DOMAIN_LENGTHS[domain]\n\n        exp_c = exp.get_exp_components() # Get components of an experiment\n        results_pst[\"IS\"].append(IS)\n        results_pst[\"domain_name\"].append(domain)\n        results_pst[\"program_size\"].append(program_size)\n        results_pst[\"theta\"].append(perf_details[\"performance\"])\ndf = pd.DataFrame(results_pst).groupby(by=[\"domain_name\", \"IS\"]).mean()\n```\n\n\n```python\nfig, axes = plt.subplots()\nxlabel = \"Program size\"\nylabel = \"$\\\\theta$\"\nplt.xlabel(xlabel, fontsize=LABEL_SIZE)\nplt.ylabel(ylabel, fontsize=LABEL_SIZE)\naxes.tick_params(labelsize=TICK_SIZE)\naxes.tick_params(labelsize=TICK_SIZE)\nplt.ylim(0, 1)\nset_axes(disable_ticks=False) # Fix axes spines & ticks, see utils.py for more details\n\nfor temp in domains_considered:\n    tdf = df.loc[temp] \n    tdf = tdf.reindex(list(model_name_correction.keys()))\n    x = tdf[\"program_size\"]\n    y = tdf[\"theta\"]\n    for model in model_name_correction.keys():\n        x = tdf.loc[model][\"program_size\"]\n        y = tdf.loc[model][\"theta\"]\n        color = model_colormap[model_name_correction[model]]\n        sns.scatterplot(x=[x], y=[y], color=color, s=S, alpha=ALPHA) \n\nplt.tight_layout()\n# Dummy Plot to Generate Legend\nmarkers = [\n    plt.Line2D([0, 0], [0, 0], color=color, marker=\"o\", linestyle=\"\")\n    for color in model_colormap.values()\n]\nplt.legend(markers, model_colormap.keys(),fontsize=LEGEND_SIZE)\nplt.title(f\"{ylabel} vs {xlabel}\", loc=\"center\",fontsize=TITLE_SIZE)\nplt.show()\n```\n\n#### Skill level vs Program Size \n\n\n```python\nresults_def = {\"IS\": [], \"domain_name\": [], \"program_size\": [], \"skill_level\": []}\nfor exp_file in EXP_FILES:\n    exp = Experiment(exp_file)\n    for domain in domains_considered:\n        exp_c = exp.get_exp_components() # Get components of an experiment\n        IS = exp_c.IS # Get the IS name of an experiment \n        perf_details = exp_c.PerformanceDetails # Per domain performance of an experiment \n        \n        perf_details = next(item for item in perf_details if item[\"name\"] == domain)\n        program_size = DOMAIN_LENGTHS[domain]\n        results_def[\"IS\"].append(IS)\n        results_def[\"domain_name\"].append(domain)\n        results_def[\"program_size\"].append(program_size)\n        results_def[\"skill_level\"].append(perf_details[\"perfects\"])\ndf = pd.DataFrame(results_def).groupby(by=[\"domain_name\", \"IS\"]).mean()\n```\n\n\n```python\nfig, axes = plt.subplots()\nxlabel = \"Program size\"\nylabel = \"Skill level\"\nplt.xlabel(xlabel, fontsize=LABEL_SIZE)\nplt.ylabel(ylabel, fontsize=LABEL_SIZE)\naxes.tick_params(labelsize=TICK_SIZE)\naxes.tick_params(labelsize=TICK_SIZE)\nplt.ylim(0, 1)\nset_axes(disable_ticks=False) # Fix axes spines & ticks, see utils.py for more details\n\n#plotting the points domain-wise\nfor domain in domains_considered:\n    tdf = df.loc[domain] #temporary_df for the domain\n    tdf = tdf.reindex(model_name_correction.keys()) #reindex by model names\n    x = tdf[\"program_size\"]\n    y = tdf[\"skill_level\"]\n    for model in model_name_correction.keys(): #plot individual points per domain\n        x = tdf.loc[model][\"program_size\"]\n        y = tdf.loc[model][\"skill_level\"]\n        color = model_colormap[model_name_correction[model]] # get the color for a model.\n        sns.scatterplot(x=[x], y=[y], color=color, s=S, alpha=ALPHA)\n\nplt.tight_layout()\n# Dummy Plot to Generate Legend\nmarkers = [plt.Line2D([0, 0], [0, 0], color=color, marker=\"o\", linestyle=\"\") for color in model_colormap.values()]\nplt.legend(markers, model_colormap.keys(),fontsize=LEGEND_SIZE)\nplt.title(f\"{ylabel} vs {xlabel}\", loc=\"center\",fontsize=TITLE_SIZE)\nplt.show()\n```\n\n#### Compute Vs Average Performance ( $\\theta$ ) \n\n\n```python\nresults_ct = {\"IS\": [], \"avg_perf\": [], \"compute\": [], \"g_index\": []}\nfor exp_file in EXP_FILES:\n    exp = Experiment(exp_file)\n    exp_c = exp.get_exp_components(return_raw_experience=True) # Get components of an experiment with raw compute\n    IS = exp_c.IS # Get the IS name of an experiment \n    avg_perf = exp_c.AveragePerformance # Average Performance of an experiment \n    compute = exp_c.E # Get compute for an experiment\n    g_index = exp.calculate_g_index() #Calculate g-index for the experiment\n    results_ct[\"IS\"].append(model_name_correction[IS])\n    results_ct[\"avg_perf\"].append(avg_perf)\n    results_ct[\"compute\"].append(compute)\n    results_ct[\"g_index\"].append(g_index)\n```\n\n\n```python\ng_i_dots_scales = [scale_dots(min(gi), c) for c in results_ct[\"g_index\"]]#Calculate the scatterplot dots sizes based on g-index values\n#Create a data list of (Total Samples,Avg Performance, IS name, gindex_dot_sizes)\ndata_list = [[x,y,marker_size,model_name] for (x,y,marker_size,model_name) in zip(results_ct[\"compute\"], results_ct[\"avg_perf\"], g_i_dots_scales, results_ct[\"IS\"])]\n```\n\n\n```python\nfig, axes = plt.subplots()\nylabel = \"Performance\"\nxlabel = \"Compute\"\nplt.xlabel(xlabel, fontsize=LABEL_SIZE)\nplt.ylabel(ylabel, fontsize=LABEL_SIZE)\naxes.tick_params(labelsize=TICK_SIZE)\naxes.tick_params(labelsize=TICK_SIZE)\nplt.ylim(0, 1.01)\nset_axes(disable_ticks=False) # Fix axes spines & ticks, see utils.py for more details\n\n#plot the points step by step\nfor entry in data_list:\n    sns.scatterplot(x=[entry[0]],y=[entry[1]],color=model_colormap[entry[3]],s=entry[2],alpha=ALPHA) # plot every point on the axes\n    \nmarkers = [plt.Line2D([0, 0], [0, 0], color=color, marker=\"o\", linestyle=\"\") for color in model_colormap.values()]\nplt.legend(markers, model_colormap.keys(),fontsize=LEGEND_SIZE)\nplt.tight_layout()\nplt.title(f\"{ylabel} vs {xlabel}\", loc=\"center\",fontsize=TITLE_SIZE)\nplt.show()\n```\n\n## 5. Request the data\n\nPlease send us a mail at the [humans@mayahq.com](mailto:humans@mayahq.com) with the following details to get the data.<br>\nEmail Subject: `g-index data request`\n\n```markdown\nName:\nI/We are an : [Individual/Organisation]\nOur use case : [Brief Description]\n```\n\n## 6. Cite us!\n\nIf this repository, the paper or any of its content is useful for your research, please cite:\n\n```\n@misc{venkatasubramanian2021measure,\n      title={Towards A Measure Of General Machine Intelligence}, \n      author={Gautham Venkatasubramanian and Sibesh Kar and Abhimanyu Singh and Shubham Mishra and Dushyant Yadav and Shreyansh Chandak},\n      year={2021},\n      eprint={2109.12075},\n      archivePrefix={arXiv},\n      primaryClass={cs.AI}\n}\n```\n", "meta": {"hexsha": "a2c33191559242457dfef2040ebfe4fa74d9d752", "size": 786914, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/reference.ipynb", "max_stars_repo_name": "mayahq/g-index-benchmark", "max_stars_repo_head_hexsha": "41aa8291c8bebb88b0c05a10ee4974dbaec09c05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-09-27T01:14:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T21:04:58.000Z", "max_issues_repo_path": "notebooks/reference.ipynb", "max_issues_repo_name": "mayahq/g-index-benchmark", "max_issues_repo_head_hexsha": "41aa8291c8bebb88b0c05a10ee4974dbaec09c05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-26T21:30:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-26T21:30:28.000Z", "max_forks_repo_path": "notebooks/reference.ipynb", "max_forks_repo_name": "mayahq/g-index-benchmark", "max_forks_repo_head_hexsha": "41aa8291c8bebb88b0c05a10ee4974dbaec09c05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-09-29T08:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T21:10:07.000Z", "avg_line_length": 544.2005532503, "max_line_length": 174808, "alphanum_fraction": 0.9408156419, "converted": true, "num_tokens": 7024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15817434481176185, "lm_q2_score": 0.042722194499425874, "lm_q1q2_score": 0.006757555123867344}}
{"text": "## **Prerequisites**\n\n### **Check what GPU you got**\nIf you didn't get the P100-PCIE GPU, click on the Runtime dropdown at the top of the page and Factory Reset Runtime \n\n\n```\n!nvidia-smi\n```\n\n    Sat Apr 25 17:11:55 2020       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 440.64.00    Driver Version: 418.67       CUDA Version: 10.1     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |===============================+======================+======================|\n    |   0  Tesla P100-PCIE...  Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   36C    P0    26W / 250W |      0MiB / 16280MiB |      0%      Default |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                       GPU Memory |\n    |  GPU       PID   Type   Process name                             Usage      |\n    |=============================================================================|\n    |  No running processes found                                                 |\n    +-----------------------------------------------------------------------------+\n\n\n### **Mount and Install Packages**\nMount the data and set up Spacy\n\n\n```\nfrom google.colab import drive\ndrive.mount('/content/drive', force_remount=True)\n\nimport os\nos.chdir(\"/content/drive/My Drive/English-to-French-Translation\")\n!ls\n\n!python -m spacy download en_core_web_sm\n!python -m spacy download fr_core_news_sm\n\n!pip3 install 'torchtext==0.5.0'\n\n!pip3 install torch torchvision\n```\n\n    Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly\n    \n    Enter your authorization code:\n    \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\n    Mounted at /content/drive\n    data  embeddings  experiments  models  README.md  scripts  src\n    Requirement already satisfied: en_core_web_sm==2.2.5 from https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.2.5/en_core_web_sm-2.2.5.tar.gz#egg=en_core_web_sm==2.2.5 in /usr/local/lib/python3.6/dist-packages (2.2.5)\n    Requirement already satisfied: spacy>=2.2.2 in /usr/local/lib/python3.6/dist-packages (from en_core_web_sm==2.2.5) (2.2.4)\n    Requirement already satisfied: plac<1.2.0,>=0.9.6 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_sm==2.2.5) (1.1.3)\n    Requirement already satisfied: murmurhash<1.1.0,>=0.28.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_sm==2.2.5) (1.0.2)\n    Requirement already satisfied: catalogue<1.1.0,>=0.0.7 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_sm==2.2.5) (1.0.0)\n    Requirement already satisfied: preshed<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_sm==2.2.5) (3.0.2)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_sm==2.2.5) (46.1.3)\n    Requirement already satisfied: srsly<1.1.0,>=1.0.2 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_sm==2.2.5) (1.0.2)\n    Requirement already satisfied: blis<0.5.0,>=0.4.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_sm==2.2.5) (0.4.1)\n    Requirement already satisfied: numpy>=1.15.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_sm==2.2.5) (1.18.3)\n    Requirement already satisfied: thinc==7.4.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_sm==2.2.5) (7.4.0)\n    Requirement already satisfied: requests<3.0.0,>=2.13.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_sm==2.2.5) (2.21.0)\n    Requirement already satisfied: tqdm<5.0.0,>=4.38.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_sm==2.2.5) (4.38.0)\n    Requirement already satisfied: cymem<2.1.0,>=2.0.2 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_sm==2.2.5) (2.0.3)\n    Requirement already satisfied: wasabi<1.1.0,>=0.4.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_sm==2.2.5) (0.6.0)\n    Requirement already satisfied: importlib-metadata>=0.20; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from catalogue<1.1.0,>=0.0.7->spacy>=2.2.2->en_core_web_sm==2.2.5) (1.6.0)\n    Requirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0,>=2.13.0->spacy>=2.2.2->en_core_web_sm==2.2.5) (2.8)\n    Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0,>=2.13.0->spacy>=2.2.2->en_core_web_sm==2.2.5) (1.24.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0,>=2.13.0->spacy>=2.2.2->en_core_web_sm==2.2.5) (2020.4.5.1)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0,>=2.13.0->spacy>=2.2.2->en_core_web_sm==2.2.5) (3.0.4)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata>=0.20; python_version < \"3.8\"->catalogue<1.1.0,>=0.0.7->spacy>=2.2.2->en_core_web_sm==2.2.5) (3.1.0)\n    \u001b[38;5;2m\u2714 Download and installation successful\u001b[0m\n    You can now load the model via spacy.load('en_core_web_sm')\n    Collecting fr_core_news_sm==2.2.5\n    \u001b[?25l  Downloading https://github.com/explosion/spacy-models/releases/download/fr_core_news_sm-2.2.5/fr_core_news_sm-2.2.5.tar.gz (14.7MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 14.7MB 82.6MB/s \n    \u001b[?25hRequirement already satisfied: spacy>=2.2.2 in /usr/local/lib/python3.6/dist-packages (from fr_core_news_sm==2.2.5) (2.2.4)\n    Requirement already satisfied: blis<0.5.0,>=0.4.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->fr_core_news_sm==2.2.5) (0.4.1)\n    Requirement already satisfied: preshed<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->fr_core_news_sm==2.2.5) (3.0.2)\n    Requirement already satisfied: catalogue<1.1.0,>=0.0.7 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->fr_core_news_sm==2.2.5) (1.0.0)\n    Requirement already satisfied: murmurhash<1.1.0,>=0.28.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->fr_core_news_sm==2.2.5) (1.0.2)\n    Requirement already satisfied: wasabi<1.1.0,>=0.4.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->fr_core_news_sm==2.2.5) (0.6.0)\n    Requirement already satisfied: srsly<1.1.0,>=1.0.2 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->fr_core_news_sm==2.2.5) (1.0.2)\n    Requirement already satisfied: thinc==7.4.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->fr_core_news_sm==2.2.5) (7.4.0)\n    Requirement already satisfied: numpy>=1.15.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->fr_core_news_sm==2.2.5) (1.18.3)\n    Requirement already satisfied: plac<1.2.0,>=0.9.6 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->fr_core_news_sm==2.2.5) (1.1.3)\n    Requirement already satisfied: requests<3.0.0,>=2.13.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->fr_core_news_sm==2.2.5) (2.21.0)\n    Requirement already satisfied: tqdm<5.0.0,>=4.38.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->fr_core_news_sm==2.2.5) (4.38.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->fr_core_news_sm==2.2.5) (46.1.3)\n    Requirement already satisfied: cymem<2.1.0,>=2.0.2 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->fr_core_news_sm==2.2.5) (2.0.3)\n    Requirement already satisfied: importlib-metadata>=0.20; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from catalogue<1.1.0,>=0.0.7->spacy>=2.2.2->fr_core_news_sm==2.2.5) (1.6.0)\n    Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0,>=2.13.0->spacy>=2.2.2->fr_core_news_sm==2.2.5) (1.24.3)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0,>=2.13.0->spacy>=2.2.2->fr_core_news_sm==2.2.5) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0,>=2.13.0->spacy>=2.2.2->fr_core_news_sm==2.2.5) (2020.4.5.1)\n    Requirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0,>=2.13.0->spacy>=2.2.2->fr_core_news_sm==2.2.5) (2.8)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata>=0.20; python_version < \"3.8\"->catalogue<1.1.0,>=0.0.7->spacy>=2.2.2->fr_core_news_sm==2.2.5) (3.1.0)\n    Building wheels for collected packages: fr-core-news-sm\n      Building wheel for fr-core-news-sm (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for fr-core-news-sm: filename=fr_core_news_sm-2.2.5-cp36-none-any.whl size=14727027 sha256=bc524effefb3b44f33181423a635fcb6c95e02919693673c20e5de7544918ab4\n      Stored in directory: /tmp/pip-ephem-wheel-cache-5h8iojyw/wheels/46/1b/e6/29b020e3f9420a24c3f463343afe5136aaaf955dbc9e46dfc5\n    Successfully built fr-core-news-sm\n    Installing collected packages: fr-core-news-sm\n    Successfully installed fr-core-news-sm-2.2.5\n    \u001b[38;5;2m\u2714 Download and installation successful\u001b[0m\n    You can now load the model via spacy.load('fr_core_news_sm')\n    Collecting torchtext==0.5.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/79/ef/54b8da26f37787f5c670ae2199329e7dccf195c060b25628d99e587dac51/torchtext-0.5.0-py3-none-any.whl (73kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 81kB 4.4MB/s \n    \u001b[?25hRequirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from torchtext==0.5.0) (1.12.0)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from torchtext==0.5.0) (1.18.3)\n    Requirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from torchtext==0.5.0) (2.21.0)\n    Requirement already satisfied: torch in /usr/local/lib/python3.6/dist-packages (from torchtext==0.5.0) (1.4.0)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from torchtext==0.5.0) (4.38.0)\n    Collecting sentencepiece\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/98/2c/8df20f3ac6c22ac224fff307ebc102818206c53fc454ecd37d8ac2060df5/sentencepiece-0.1.86-cp36-cp36m-manylinux1_x86_64.whl (1.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.0MB 12.6MB/s \n    \u001b[?25hRequirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->torchtext==0.5.0) (1.24.3)\n    Requirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->torchtext==0.5.0) (2.8)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->torchtext==0.5.0) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->torchtext==0.5.0) (2020.4.5.1)\n    Installing collected packages: sentencepiece, torchtext\n      Found existing installation: torchtext 0.3.1\n        Uninstalling torchtext-0.3.1:\n          Successfully uninstalled torchtext-0.3.1\n    Successfully installed sentencepiece-0.1.86 torchtext-0.5.0\n    Requirement already satisfied: torch in /usr/local/lib/python3.6/dist-packages (1.4.0)\n    Requirement already satisfied: torchvision in /usr/local/lib/python3.6/dist-packages (0.5.0)\n    Requirement already satisfied: pillow>=4.1.1 in /usr/local/lib/python3.6/dist-packages (from torchvision) (7.0.0)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from torchvision) (1.18.3)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from torchvision) (1.12.0)\n\n\n### **Important: Reset Runtime**\n\nNote: there is a slight bug with Google Colab. After installing Spacy, you need to restart the Jupyter Notebook runtime.\n\nThere are two ways:\n1. Click on the Runtime dropdown, and select \"Restart Runtime\". Once that is done, proceed to the next step (no need to remount the drive).\n2. Run the code below. It will kill the current process, effectively restarting the runtime.\n\n\n```\nimport os\nos.kill(os.getpid(), 9)\n```\n\n##Get the data\n\n### **Get a list of vocabs:**\nThe list of vocabs are already stored in the Google Drive folder; thus, we just have to load it.\n\n\n```\nimport sys\nsys.path.append('/content/drive/My Drive/English-to-French-Translation/src/dataloader/')\n\nimport vocabs\n\nmodels_dir = \"/content/drive/My Drive/English-to-French-Translation/models/Multi30k/\"\nsource_vocabs = vocabs.load_vocabs_from_file(models_dir + 'vocab.english.gz')\ntarget_vocabs = vocabs.load_vocabs_from_file(models_dir + 'vocab.french.gz')\n```\n\n    Loaded 9757 words\n    Loaded 11137 words\n\n\n### **Tokenize and split the dataset**\nWe will have three types of datasets:\n1. Training data: it is the data used to train our model\n2. Validation (val) data: it is the data used to test our model at each step of the training process\n3. Test data: it is the data used to test our model after all the training is done\n\nHow to get the three types of data?\n* The test set is already in the `Test` folder\n* The validation set is a piece of the data in the `Train`` folder\n\nThe code to get our three types of datasets is:\n\n\n```\nimport sys\nsys.path.append('/content/drive/My Drive/English-to-French-Translation/src/dataloader')\n\nimport os\nfrom tqdm.notebook import tqdm\n\nimport torch\nimport numpy as np\nimport utils\nimport vocabs\n\nclass Seq2SeqDataset(torch.utils.data.Dataset):\n  def __init__(\n    self,\n    dir_: str,\n    source_vocabs: vocabs.VocabDataset,\n    target_vocabs: vocabs.VocabDataset,\n    source_lang: str,\n    target_lang: str,\n  ):\n\n    \"\"\" Initialize the Hansard dataset from a directory of parallel texts\n        Note:\n            The parallel text in 'dir_' must contain source and target transcriptions\n            with the file extension 'source_lang' and 'target_lang'\n\n        Parameters\n        ----------\n        dir_ : str\n            A path to the directory of parallel text\n        source_vocabs : VocabDataset\n            A vocab dataset of the source text\n        target_vocabs : VocabDataset\n            A vocab dataset of the target text\n        source_lang : { 'en', 'fr' }\n            The source language\n        target_lang : { 'en', 'fr' }\n            The target language\n    \"\"\"\n\n    # Get the spacy instances\n    source_spacy = utils.get_spacy_instance(source_lang)\n    target_spacy = utils.get_spacy_instance(target_lang)\n\n    # Get all the files with the text\n    transcriptions = utils.get_parallel_text(dir_, [source_lang, target_lang])\n\n    source_filepaths = [os.path.join(dir_, trans[0]) for trans in transcriptions]\n    target_filepaths = [os.path.join(dir_, trans[1]) for trans in transcriptions]\n\n    source_l = utils.read_transcription_files(source_filepaths, source_spacy)\n    target_l = utils.read_transcription_files(target_filepaths, target_spacy)\n\n    source_word2id = source_vocabs.get_word2id()\n    target_word2id = target_vocabs.get_word2id()\n\n    src_unk, src_pad = range(len(source_word2id), len(source_word2id) + 2)\n    trg_unk, trg_sos, trg_eos, trg_pad = range(len(target_word2id), len(target_word2id) + 4)\n\n    corpus_iterator = zip(target_l, source_l)\n    corpus_size = utils.get_size_of_corpus(source_filepaths)\n\n    pairs = []\n    src_lens = []\n    trg_lens = []\n\n    for (trg, trg_filename, _), (src, src_filename, _) in tqdm(corpus_iterator, total=corpus_size):\n      assert trg_filename[:-2] == src_filename[:-2]\n\n      if not src or not trg:\n        continue\n\n      # Skip sentences > 50 words\n      if len(src) > 50 or len(trg) > 50:\n        continue\n\n      # Skip sentences with no words\n      if len(src) <= 0 or len(trg) <= 0:\n        print(\"Found a sentence with no words in it!\")\n        continue\n\n      src_tensor = torch.tensor([source_word2id.get(word, src_unk) for word in src])\n      trg_tensor = torch.tensor(\n        [trg_sos] + [target_word2id.get(word, trg_unk) for word in trg] + [trg_eos]\n      )\n\n      # Validate the contents of E and F\n      if torch.any(src_tensor < 0) or torch.any(src_tensor > src_unk):\n        print(\"src_unk:\", src_unk)\n        print(\"src_tensor:\", src_tensor)\n        raise ValueError(\"Contents of src_tensor should be <= src_unk and >= 0!\")\n\n      if torch.any(trg_tensor < 0) or torch.any(trg_tensor > trg_eos):\n        print(\"trg_eos:\", trg_eos)\n        print(\"trg_tensor:\", trg_tensor)\n        raise ValueError(\"Contents of trg_tensor should be <= trg_eos and >= 0!\")\n\n      # Skip sentences that don't have any words in the vocab\n      if torch.all(src_tensor == src_unk) and torch.all(trg_tensor[1:-1] == trg_unk):\n        continue\n\n      pairs.append((src_tensor, trg_tensor))\n      src_lens.append(src_tensor.size()[0])\n      trg_lens.append(trg_tensor.size()[0])\n\n    print(\"Number of sentence pairs:\", len(pairs))\n\n    print(\"Avg. num words in source text:\", np.mean(src_lens))\n    print(\"Std. num words in source text:\", np.std(src_lens))\n    print(\"Max. num words in source text:\", np.max(src_lens))\n    print(\"Min. num words in source text:\", np.min(src_lens))\n\n    print(\"Avg. num words in target text:\", np.mean(trg_lens))\n    print(\"Std. num words in target text:\", np.std(trg_lens))\n    print(\"Max. num words in target text:\", np.max(trg_lens))\n    print(\"Min. num words in target text:\", np.min(trg_lens))\n    \n    self.source_unk = src_unk\n    self.source_pad_id = src_pad\n    self.source_vocab_size = len(source_word2id) + 2  # pad id and unk\n\n    self.target_unk = trg_unk\n    self.target_sos = trg_sos\n    self.target_eos = trg_eos\n    self.target_pad_id = trg_pad\n    self.target_vocab_size = len(target_word2id) + 4  # unk, sos, eos, and pad id\n    \n    self.dir_ = dir_\n    self.pairs = pairs\n\n  def __len__(self):\n    \"\"\" Returns the number of parallel texts in this dataset \"\"\"\n    return len(self.pairs)\n\n  def __getitem__(self, i):\n    \"\"\" Returns the i-th parallel texts in this dataset \"\"\"\n    return self.pairs[i]\n\n\nclass Seq2SeqDataLoader(torch.utils.data.DataLoader):\n  def __init__(self, dataset, source_pad_id, target_pad_id, batch_first=False, **kwargs):\n    \"\"\" Loads the dataset for the model\n        It can load the dataset in parallel by setting 'num_workers' param > 0\n\n        Parameters\n        ----------\n        dataset : Seq2SeqDataset\n            The parallel text dataset\n        source_pad_id : int\n            An ID used to pad the source text for batching\n        target_pad_id : int\n            An ID used to pad the target text for batching\n    \"\"\"\n    super().__init__(dataset, collate_fn=self.collate, **kwargs)\n\n    self.source_pad_id = source_pad_id\n    self.target_pad_id = target_pad_id\n    self.batch_first = batch_first\n\n  def collate(self, batch):\n    \"\"\" Given a batch of source and target texts, it will pad it\n        Specifically, it pads F with self.source_pad_id and E with self.target_eos\n\n        Parameters\n        ----------\n        batch : A set of sequences F and E where F is torch.tensor and E is torch.tensor\n\n        Returns\n        -------\n        (F, F_lens, E, E_lens) : tuple\n            F is a torch.tensor of size (S, N)\n            E is a torch.tensor of size (S, N)\n    \"\"\"\n    src_batch, trg_batch = zip(*batch)\n    src_lens = torch.tensor([src_seq.size()[0] for src_seq in src_batch])\n    trg_lens = torch.tensor([trg_seq.size()[0] for trg_seq in trg_batch])\n\n    src = torch.nn.utils.rnn.pad_sequence(src_batch, batch_first=self.batch_first, padding_value=self.source_pad_id)\n    trg = torch.nn.utils.rnn.pad_sequence(trg_batch, batch_first=self.batch_first, padding_value=self.target_pad_id)\n\n    return src, src_lens, trg, trg_lens\n\n\ntrain_dir = \"/content/drive/My Drive/English-to-French-Translation/data/Multi30k/Training\"\ntest_dir = \"/content/drive/My Drive/English-to-French-Translation/data/Multi30k/Testing\"\n\nsource_lang = \"en\"\ntarget_lang = \"fr\"\ntrain_val_ratio = 0.75\nbatch_size = 64\n\ndataset = Seq2SeqDataset(\n  train_dir,\n  source_vocabs,\n  target_vocabs,\n  source_lang,\n  target_lang\n)\n\nnum_training_data = int(len(dataset) * train_val_ratio)\nnum_val_data = len(dataset) - num_training_data\n\ntrain_dataset, val_dataset = torch.utils.data.random_split(\n  dataset, [num_training_data, num_val_data]\n)\n\ntrain_dataloader = Seq2SeqDataLoader(\n  train_dataset,\n  dataset.source_pad_id,\n  dataset.target_pad_id,\n  batch_first=True,\n  batch_size=batch_size,\n  shuffle=True,\n  pin_memory=True,\n  num_workers=10\n)\nval_dataloader = Seq2SeqDataLoader(\n  val_dataset,\n  dataset.source_pad_id,\n  dataset.target_pad_id,\n  batch_first=True,\n  batch_size=batch_size,\n  shuffle=True,\n  pin_memory=True,\n  num_workers=10\n)\n\ntest_dataset = Seq2SeqDataset(\n  test_dir,\n  source_vocabs,\n  target_vocabs,\n  source_lang,\n  target_lang\n)\ntest_dataloader = Seq2SeqDataLoader(\n  test_dataset,\n  test_dataset.source_pad_id,\n  test_dataset.target_pad_id,\n  batch_first=True,\n  batch_size=batch_size,\n  shuffle=True,\n  pin_memory=True,\n  num_workers=10\n)\n\n```\n\n\n    HBox(children=(IntProgress(value=0, max=29461), HTML(value='')))\n\n\n    \n    Number of sentence pairs: 29460\n    Avg. num words in source text: 13.082416836388322\n    Std. num words in source text: 4.061960254692422\n    Max. num words in source text: 41\n    Min. num words in source text: 4\n    Avg. num words in target text: 16.268940936863544\n    Std. num words in target text: 4.730511458726377\n    Max. num words in target text: 49\n    Min. num words in target text: 6\n\n\n\n    HBox(children=(IntProgress(value=0, max=1014), HTML(value='')))\n\n\n    \n    Number of sentence pairs: 1014\n    Avg. num words in source text: 13.241617357001973\n    Std. num words in source text: 4.056529028481095\n    Max. num words in source text: 32\n    Min. num words in source text: 4\n    Avg. num words in target text: 16.357988165680474\n    Std. num words in target text: 4.777396885525875\n    Max. num words in target text: 38\n    Min. num words in target text: 7\n\n\n##**Our Model**\n\n###**The Intuition behind Attention**\n\nIdea behind attention:\n* Suppose we have a sentence like \"Mary gave roses to Susan\"\n* We want our ML model to focus on the fact that the **giving** is being done by Mary to Susan with a rose. \n* The model should not give much attention that Mary came before Susan.\n* This is called attention\n* The attention layer will allow the ML model to focus on certain aspects that are more important than others\n\nBuilding our self-attention layer:\n* Let $x_1, x_2, ..., x_t \\in R^k$ be our sequence of inputs represented with word embeddings of dimension $k$. \n* Attention is basically:\n\n  \\begin{align*}\n    y_i &= \\sum_{j = 0}^{t} w_{i, j} x_j\n  \\end{align*}\n\n  where:\n  \\begin{align*}\n    w'_{i, j} &= x_i^T x_j\n  \\end{align*}\n\n* But the dot product will give a value anywhere between $[-\\infty, \\infty]$\n* Solution:\n  * We apply softmax to map the values to $[0, 1]$:\n\n    \\begin{align}\n      w_{i, j} = \\frac{exp(w'_{i, j})}{\\sum_{j}^{t} exp(w'_{i, j})}\n    \\end{align}\n\n* That is the basics of self-attention.\n\nThe problem:\n* There is no parameters in our attention formula.\n* We need parameters so that it can attend to different areas of the inputs.\n\nThe solution:\n* If we want to add weights, we just apply a linear transformation on each of the $x_i \\in X$ that we use in our attention equation:\n\n  \\begin{align}\n    q_i &= W_q x_i \\text{ with } W_q \\in R^{k x k} \\\\\n    k_i &= W_k x_i \\text{ with } W_k \\in R^{k x k} \\\\\n    v_i &= W_v x_i \\text{ with } W_v \\in R^{k x k} \\\\\n  \\end{align}\n\n\n* We then use it on these formulas: \\\\\n\n  \\begin{align}\n    w'_{i, j} &= q_i^T k_j \\\\\n    w_{i, j} &= softmax(w'_{i, j}) \\\\\n    y_i &= \\sum_{j}^{t} w_{i, j} v_j \\\\\n  \\end{align}\n\nAnother problem:\n* The softmax function is very sensitive to very large inputs\n* It will squeeze all the inputs to 0 if there is an input that is very large.\n\nThe solution:\n* We scale the dot product by $\\sqrt{k}$. \n* Now, our formula is:\n\n  \\begin{align}\n    w'_{i, j} = \\frac{q_i^T k_j}{\\sqrt{k}}\n  \\end{align}\n\nGeneralizing attention to Queries, Keys, and Values\n* Recall our attention model:\n\n  \\begin{align}\n    y_i &= \\sum_{j}^{t} w_{i, j} v_j \\\\\n    w_{i, j} &= softmax(w'_{i, j}) \\\\\n    w'_{i, j} &= q_i^T k_j \\\\\n    \\text{where:} & \\\\\n    q_i &= W_q x_i \\text{ with } W_q \\in R^{k x k} \\\\\n    k_i &= W_k x_i \\text{ with } W_k \\in R^{k x k} \\\\\n    v_i &= W_v x_i \\text{ with } W_v \\in R^{k x k} \\\\\n  \\end{align}\n\n* We can generalize it to: \\\\\n\n  \\begin{align}\n    y_i &= \\sum_{j}^{t} w_{i, j} v_j \\\\\n    w_{i, j} &= softmax(w'_{i, j}) \\\\\n    w'_{i, j} &= q_i^T k_j \\\\\n    \\text{where:} & \\\\\n    q_i &= W_q q'_i \\text{ with } W_q \\in R^{k x k} \\\\\n    k_i &= W_k k'_i \\text{ with } W_k \\in R^{k x k} \\\\\n    v_i &= W_v v'_i \\text{ with } W_v \\in R^{k x k} \\\\\n  \\end{align}\n\n* We are going to use this in our Transformer model\n\n\n###**The multi-headed attention layer**\nNote that a word can mean different things to different neighbours.\n* For instance, consider the example:\n\n  F = [mary, gave, roses, to, susan]\n\n* The word \"gave\" has different relations to different parts of the sentnece. Mary is the one whose giving, and Susan is the one who is receiving\n* In a normal Seq2Seq model with RNNs, the attention layer was not able to determine which is which and would confuse Susan giving the roses to Mary instead\n* The solution to this is to have multiple attention heads\n\nLet `h` = number of heads\n\nTo give additional attention heads, we can do one of the following ways:\n1. Split the hidden dimension of each word evenly by `h`\n2. Create `h` different weight matrixes\n\n**Split the hidden dimension of each word evenly by `h`**:\n\nThis is where we split the word embeddings by `h`:\n* Let $x'_i = [x_i[0], x_i[1], ..., x_i[h]]$\n* Now, apply each row in $x'_i$ to $W_k, W_q, W_v$, i.e,\n\n  * $q_i[j] = W_q * x'_i[j]$\n  * $k_i[j] = W_k * x'_i[j]$\n  * $v_i[j] = W_v * x'_i[j]$\n\n* Now, we combine it together:\n\n  * $q_i = [q_i[0], q_i[1], ..., q_i[h]]$\n  * $k_i = [k_i[0], k_i[1], ..., k_i[h]]$\n  * $v_i = [v_i[0], v_i[1], ..., v_i[h]]$\n\nIn lin algebra, the stuff above is the same as the formulas below:\n\n  * $q_i = W_q * x_i$\n  * $k_i = W_k * x_i$\n  * $v_i = W_v * x_i$\n\nWe will be using this ^\n\n**Create `h` different weight matrixes**:\n\nTo give additional attention heads, we do:\n* Make additional weight matrixes:\n\n  $W^{\\rho}_{q}, W^{\\rho}_{k}, W^{\\rho}_{v}$\n\n  where ${\\rho}$ is the attention head index\n\n* For each input $x_i$, we pass it through each head attention weight matrixes, concatenate all of them (so our output becomes $k\\rho \\cdot k$), and we do one last linear transformation with another weight matrix to reduce the dimension back to k.\n\nIn CUDA, it is more efficient to concatenate the different heads of one type of weight matrix as one matrix.\n\nSo:\n\n* $W_q = [W^0_q, W^1_q, W^2_q, ..., W^h_q] \\in R^{kh \\times k}$\n* $W_k = [W^0_k, W^1_k, W^2_k, ..., W^h_k] \\in R^{kh \\times k}$\n* $W_v = [W^0_v, W^1_v, W^2_v, ..., W^h_v] \\in R^{kh \\times k}$\n\nSo now, if we apply $W_q, W_k, W_v$ to $x_i$, we get:\n\n* $q_i = W_q x_i \\in R^{kh \\times 1}$ \n* $k_i = W_k x_i \\in R^{kh \\times 1}$ \n* $v_i = W_v x_i \\in R^{kh \\times 1}$ \n\nIn our code, we will use option (1), and our self-attention module is now:\n\n\n```\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\nclass MultiHeadedSelfAttention(nn.Module):\n  def __init__(self, hidden_size, device, num_heads=10, dropout_value=0.1):\n    ''' Constructs the MultiHeadedSelfAttention layer\n\n        Parameters\n        ----------\n        hidden_size : int\n          The hidden size\n        device : torch.device\n          The device running the model\n        num_heads : int (optional)\n          The number of heads to self-attend to\n        dropout_value : float (optional)\n          The dropout rate for the output layer\n    '''\n    super().__init__()\n\n    self.hidden_size = hidden_size\n    self.num_heads = num_heads\n    self.head_dim = hidden_size // num_heads\n\n    assert hidden_size % num_heads == 0\n\n    # Our weight matrixes\n    self.to_keys = nn.Linear(self.hidden_size, self.hidden_size, bias=False)\n    self.to_queries = nn.Linear(self.hidden_size, self.hidden_size, bias=False)\n    self.to_values = nn.Linear(self.hidden_size, self.hidden_size, bias=False)\n\n    # The scale\n    self.scale = torch.sqrt(torch.FloatTensor([self.head_dim])).to(device)\n\n    # The final linear transformation\n    self.unify_heads = nn.Linear(self.hidden_size, self.hidden_size)\n\n    # The dropout\n    self.dropout = nn.Dropout(dropout_value)\n\n  def forward(self, value, key, query, mask=None):\n    ''' Performs a forward prop of the multi-headed attention layer\n\n        Parameters\n        ----------\n        value : torch.Tensor(b, v_t, d)\n        key : torch.Tensor(b, k_t, d)\n        query : torch.Tensor(b, q_t, d)\n        mask : torch.Tensor(b, 1, 1, d)\n    '''\n    b, q_t, d = query.size()\n    _, k_t, _ = key.size()\n    _, v_t, _ = value.size()\n    h = self.num_heads\n\n    # Apply the weight matrix to x (Size: (b, t, h * k))\n    queries = self.to_queries(query)\n    keys = self.to_keys(key)\n    values = self.to_values(value)\n\n    assert queries.size() == query.size()\n    assert keys.size() == key.size()\n    assert values.size() == value.size()\n\n    # Transform the matrix from (b, t, k) to (b, t, h, k // h)\n    queries = queries.view(b, -1, self.num_heads, self.head_dim).permute(0, 2, 1, 3)\n    keys = keys.view(b, -1, self.num_heads, self.head_dim).permute(0, 2, 1, 3)\n    values = values.view(b, -1, self.num_heads, self.head_dim).permute(0, 2, 1, 3)\n\n    # assert queries.size() == (b, h, t, k // h)\n    # assert keys.size() == (b, h, t, k // h)\n    # assert values.size() == (b, h, t, k // h)\n\n    # Perform the dot product (Size: (b, h, t, t))\n    w_prime = torch.matmul(queries, keys.permute(0, 1, 3, 2)) / self.scale    \n    # assert w_prime.size() == (b, h, t, t)\n\n    # Perform a mask (if needed)\n    if mask is not None:\n      w_prime = w_prime.masked_fill(mask == 0, -1e10)\n\n    # assert w_prime.size() == (b, h, t, t)\n\n    # Perform the softmax\n    w = torch.nn.functional.softmax(w_prime, dim=-1)\n    # assert w.size() == (b, h, t, t)\n\n    # Apply dropout to the attention\n    dropped_w = self.dropout(w)\n\n    # Perform the self-attention\n    y = torch.matmul(dropped_w, values)\n    # assert y.size() == (b, h, t, k // h)\n\n    # Perform the last linear transformation from (b, t, h, k) to (b, t, k)\n    y = y.permute(0, 2, 1, 3).contiguous().view(b, -1, self.hidden_size)\n    unified_y = self.unify_heads(y)\n\n    # assert unified_y.size() == (b, t, k)\n\n    return unified_y\n      \n\n```\n\n###**Our Translator Model**\n\nOur model will look like this:\n\n\n\nwhere:\n* We will be applying the encoder and decoder layers N times.\n* We apply a positional encoding to our inputs so that it can know the time sequence of things\n* We apply normalization so that we normalize things. In Pytorch, it is the nn.LayerNorm\n\n\n\n\n\n\n####**Our Encoder**\n\nThe input:\n* Let $X = [x_0, x_1, x_2, ..., x_t] \\in N^t$ be our inputs, where each number in $X$ represents a word.\n\nThe Encoder will do the following:\n\n1. It will map each word ID in $X$ to word embeddings ($R^t \\rightarrow R^{t \\times k}$)\n\n2. It will map the position (i.e, index) of each word to a position embedding ($R^{t} \\rightarrow R^{t \\times k}$)\n\n3. It will multiply each element in the matrix from (1) by a scalar value, and add it with the matrix from (2) ( ($R^{t \\times k}, R^{t \\times k}) \\rightarrow R^{t \\times k}$)\n\n4. It will apply the values from (3) multiple times through the various Encoder layers, passing the output of the previous Encoder layer as inputs to the next Encoder layer ($R^{t \\times k} \\rightarrow R^{t \\times k}$)\n\n\nIn code:\n* We want to handle batches of sequences. \n* So our inputs become $X \\in N^{b \\times t}$ where $b$ is the batch size.\n* The code will look like:\n\n\n```\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\nclass Encoder(nn.Module):\n  def __init__(self, \n               source_vocab_size : int, \n               word_embedding_size : int, \n               num_layers : int, \n               num_heads : int, \n               pf_dim : int, \n               dropout_value : float, \n               device : torch.device, \n               max_length : int = 100):\n    ''' Constructs the Encoder\n\n        Parameters\n        ----------\n        source_vocab_size : int\n          The vocab size in the source language\n        word_embedding_size : int\n          The word embedding size\n        num_layers : int\n          The number of DecoderLayer layers\n        num_heads : int\n          The number of heads for each attention layer\n        pf_dim : int\n          The dimension for the Positional layer\n        dropout_value : float\n          The dropout value for the outputs\n        device : torch.device\n          The device to run the model on\n        max_length : int (optional)\n          The max. length of each target sequence\n\n    '''\n    \n    super().__init__()\n    self.device = device\n\n    # Create our word and position embeddings\n    self.word_embedding = nn.Embedding(source_vocab_size, word_embedding_size)\n    self.pos_embedding = nn.Embedding(max_length, word_embedding_size)\n\n    # Create our layers of Encoder layers\n    self.encoder_layers = nn.ModuleList(\n      [EncoderLayer(word_embedding_size, num_heads, pf_dim, dropout_value, device) for _ in range(num_layers)]\n    )\n\n    # Create our dropout and scaler\n    self.dropout = nn.Dropout(dropout_value)\n    self.scale = torch.sqrt(torch.FloatTensor([word_embedding_size])).to(device)\n\n  def forward(self, src, src_mask):\n    ''' Performs a forward propagation on the Encoder\n\n        Parameters\n        ----------\n        src : torch.LongTensor(N, S)\n          A batch of source sequences\n        src_mask : torch.LongTensor(N, 1, 1, S)\n          The masks of each source sequence in the current batch\n\n        Returns\n        -------\n        encoded_src : torch.FloatTensor(N, S)\n          A batch of encoded source sequences\n    '''\n    batch_size, seq_len = src.size()\n\n    # Get the position embeddings for each src seq.\n    src_pos = torch.arange(0, seq_len).unsqueeze(0).repeat(batch_size, 1).to(self.device)\n    src_pos = self.pos_embedding(src_pos)\n\n    # Get word embeddings for each src seq\n    src = self.word_embedding(src)\n    \n    # Combine the word and position embeddings\n    src = src * self.scale + src_pos\n    \n    # Apply dropout\n    src = self.dropout(src)\n\n    # Obtain the encoded src seq\n    encoded_src = src\n    for layer in self.encoder_layers:\n      encoded_src = layer(encoded_src, src_mask)\n\n    return encoded_src\n\n```\n\n####**Our Encoder Layer:**\n\nThe encoder layer is responsible for handling the gray part of the encoder:\n\n\n\nLet $X = [x_0, x_1, x_2, ..., x_t] \\in R^{t \\times k}$ be the word embeddings of our input.\n\nWe then do the following:\n1. Pass $X$ into the attention layer. It will output another matrix $X'$ with the same size as $X$\n\n2. Apply a dropout to the attended $X$ matrix ($X'$) add it with the original word embeddings ($X$), and apply a normalization to the added matrix\n\n3. Send the matrix from (2) into a Position-Wise Feed-Forward Neural Net that will output a matrix with the same size as its input.\n\n4. Lastly, apply a dropout to the matrix from (3), add it with the matrix from (2), and apply the matrix from (2) + (3) with a normalization layer. It will output a matrix with the same size as its inputs.\n\nIn code, it looks like:\n\n\n\n\n```\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\nclass EncoderLayer(nn.Module):\n  def __init__(self, \n               hidden_size : int, \n               num_heads : int, \n               pf_dim : int, \n               dropout_value : float, \n               device : torch.device):\n    ''' Constructs the EncoderLayer\n\n        Parameters\n        ----------\n        hidden_size : int\n          The hidden size\n        num_heads : int\n          The number of heads in the self-attention layer\n        pf_dim : int\n          The dimension for the PositionwiseFeedforwardLayer\n        dropout_value : float\n          The dropout value\n        device : torch.device\n          The device to run the model on\n    '''\n    super().__init__()\n\n    self.attention_layer = MultiHeadedSelfAttention(\n      hidden_size, device, num_heads=num_heads, dropout_value=dropout_value\n    )\n\n    self.norm_layer = nn.LayerNorm(hidden_size)\n    self.positionwise_feedforward = PositionwiseFeedforwardLayer(hidden_size, pf_dim, dropout_value)\n    self.dropout = nn.Dropout(dropout_value)\n\n  def forward(self, src, src_mask):\n    ''' Performs a forward propagation of the Encoder layer\n\n        Parameters\n        ----------\n        src : torch.Longtensor(N, S, H)\n          A batch of source sequences\n        src_mask : torch.LongTensor(N, 1, 1, S)\n          The masks of each source sequence in the current batch\n\n        Returns\n        -------\n        encoded_src : torch.Tensor(N, S, H)\n          A batch of source sequences from this EncoderLayer\n    '''\n\n    # Apply attention\n    attended_src = self.attention_layer(src, src, src, src_mask)\n\n    # Apply dropout and normalization\n    new_src = self.norm_layer(src + self.dropout(attended_src))\n\n    # Apply positionalwise feedforward layer\n    pos_src = self.positionwise_feedforward(new_src)\n\n    # Apply dropout and layer normalization\n    encoded_src = self.norm_layer(new_src + self.dropout(pos_src))\n\n    assert encoded_src.size() == src.size()\n\n    return encoded_src\n\n\n```\n\n####**Our Positionwise Feedforward Layer**\nThis is a three-layer neural net that takes an input of (t, k), expand it to (t, pf), and compress it back to (t, k).\n\nIn math, it will look like:\n\n* $R^{t \\times k} \\rightarrow R^{t \\times pf} \\rightarrow R^{t \\times k}$\n\nIn code, it will look like:\n\n\n\n```\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\n\nclass PositionwiseFeedforwardLayer(nn.Module):\n  def __init__(self, hidden_size : int, pf_dim : int, dropout_value : float):\n    ''' Constructs the PositionwiseFeedforwardLayer\n\n        Parameters\n        ----------\n        hidden_size : int\n          The hidden size\n        pf_dim : int\n          The dimension for the hidden layer\n        dropout_value : float\n          The dropout value for the output layer\n    '''\n    super().__init__()\n\n    self.fc_1 = nn.Linear(hidden_size, pf_dim)\n    self.fc_2 = nn.Linear(pf_dim, hidden_size)\n    self.dropout = nn.Dropout(dropout_value)\n\n  def forward(self, x):\n    ''' Performs forward prop of the PositionwiseFeedforwardLayer\n\n        Parameters\n        ----------\n        x : torch.FloatTensor(N, S, H)\n          A batch of sequences with word embeddings\n\n        Returns\n        -------\n        x : torch.FloatTensor(N, S, H)\n          A batch of transformed sequences with word embeddings\n    '''\n    new_x = self.fc_1(x)\n    new_x = torch.relu(new_x)\n    new_x = self.dropout(new_x)\n    new_x = self.fc_2(new_x)\n\n    assert new_x.size() == x.size()\n\n    return x\n\n```\n\n####**Our Decoder**\nThis will encapsulate a set of decoder layers, passing the outputs of the previous decoder layer as inputs to the next decoder layer\n\nIn code, it looks like:\n\n\n\n```\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\n\nclass Decoder(nn.Module):\n  def __init__(self, \n               target_vocab_size : int, \n               word_embedding_size : int, \n               num_layers : int, \n               num_heads : int, \n               pf_dim : int, \n               dropout_value : float, \n               device : torch.device, \n               max_length : int = 100):\n    ''' Constructs the Decoder\n\n        Parameters\n        ----------\n        target_vocab_size : int\n          The vocab size in the target language\n        word_embedding_size : int\n          The word embedding size\n        num_layers : int\n          The number of DecoderLayer layers\n        num_heads : int\n          The number of heads for each attention layer\n        pf_dim : int\n          The dimension for the Positional layer\n        dropout_value : float\n          The dropout value for the outputs\n        device : torch.device\n          The device to run the model on\n        max_length : int (optional)\n          The max. length of each target sequence\n    '''\n    super().__init__()\n    self.device = device\n    \n    # Create the word and length embedding\n    self.word_embedding = nn.Embedding(target_vocab_size, word_embedding_size)\n    self.pos_embedding = nn.Embedding(max_length, word_embedding_size)\n\n    # Create our list of decoder layers\n    self.decoder_layers = nn.ModuleList(\n      [ DecoderLayer(word_embedding_size, num_heads, pf_dim, dropout_value, device) for _ in range(num_layers) ]\n    )\n\n    self.scale = torch.sqrt(torch.FloatTensor([word_embedding_size])).to(device)\n\n    # The last linear layer for the decoder\n    self.fc_out = nn.Linear(word_embedding_size, target_vocab_size)\n    self.dropout = nn.Dropout(dropout_value)\n\n  def forward(self, trg, enc_src, trg_mask, src_mask):\n    ''' Performs a forward prop. on the Decoder\n\n        Parameters\n        ----------\n        trg : torch.LongTensor(N, S')\n          A batch of target sequences\n        enc_src : torch.LongTensor(N, S, H)\n          A batch of source sequences that were encoded from the Encoder\n        trg_mask : torch.LongTensor(N, S')\n          The masks of each target sequence in the current batch\n        src_mask : torch.LongTensor(N, S)\n          The masks of each source sequence in the current batch\n\n        Returns\n        -------\n        logits : torch.FloatTensor(N, target_vocab_size)\n          The output probabilities that are not softmaxed\n    '''\n    batch_size, trg_seq_len = trg.size()\n    _, _, hidden_dim = enc_src.size()\n\n    pos = torch.arange(0, trg_seq_len).unsqueeze(0).repeat(batch_size, 1).to(self.device)\n    assert pos.size() == (batch_size, trg_seq_len)\n\n    trg = self.dropout((self.word_embedding(trg) / self.scale) + self.pos_embedding(pos))\n    assert trg.size() == (batch_size, trg_seq_len, hidden_dim)\n\n    for layer in self.decoder_layers:\n      trg = layer(trg, enc_src, trg_mask, src_mask)\n\n    logits = self.fc_out(trg)\n\n    return logits\n\n```\n\n####**Our Decoder layer:**\nOur decoder layer is going to look like:\n\n\n\n\n\n```\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\n\nclass DecoderLayer(nn.Module):\n  def __init__(self, \n               hidden_size : int, \n               num_heads : int, \n               pf_dim : int, \n               dropout_value : float, \n               device : torch.device):\n    ''' Creates a decoder layer. It should only be used in the Decoder class\n\n        Parameter\n        ---------\n        hidden_size : int\n          The hidden size\n        num_heads : int\n          The number of heads for the self-attention layers\n        pf_dim : int\n          The dimension for the PositionwiseFeedforward layer\n        dropout_value : float\n          The dropout value\n        device : torch.Device\n          The device to run the model\n    '''\n    super().__init__()\n\n    self.norm_layer = nn.LayerNorm(hidden_size)\n\n    self.attention_layer_1 = MultiHeadedSelfAttention(\n      hidden_size, device, num_heads=num_heads, dropout_value=dropout_value\n    )\n    self.attention_layer_2 = MultiHeadedSelfAttention(\n      hidden_size, device, num_heads=num_heads, dropout_value=dropout_value\n    )\n\n    self.positionwise_feedforward = PositionwiseFeedforwardLayer(hidden_size, pf_dim, dropout_value)\n\n    self.dropout = nn.Dropout(dropout_value)\n\n  def forward(self, trg, encoder_src, trg_mask, src_mask):\n    ''' Performs a forward prop on the Decoder layer\n\n        Paremeters\n        ----------\n        trg : torch.LongTensor(N, S', H)\n          A batch of expected target sequences with embeddings\n        encoder_src : torch.LongTensor(N, S, H)\n          A batch of source sequence outputted from the Encoder\n        trg_mask : torch.LongTensor(N, S')\n          The masks for each target sequence in the current batch\n        src_mask : torch.LongTensor(N, S)\n          The masks for each source sequence in the current batch\n\n        Returns\n        -------\n        decoded_trg : torch.tensor(N, S', H)\n          A batch of decoded target sequences with embeddings\n    '''\n    assert trg.size()[0] == encoder_src.size()[0]\n    assert trg.size()[2] == encoder_src.size()[2]\n\n    # Apply attention\n    attended_trg = self.attention_layer_1(trg, trg, trg, trg_mask)\n\n    # Apply dropout and layer norm\n    trg = self.norm_layer(trg + self.dropout(attended_trg))\n\n    # Apply attention\n    attended_trg = self.attention_layer_2(encoder_src, encoder_src, trg, src_mask)\n\n    # Apply dropout and layer norm\n    trg = self.norm_layer(trg + self.dropout(attended_trg))\n\n    # Apply positionwise feedforward\n    poswise_trg = self.positionwise_feedforward(trg)\n\n    # Apply dropout and layer norm\n    decoded_trg = self.norm_layer(trg + self.dropout(poswise_trg))\n\n    return decoded_trg\n\n\n```\n\n####**Our final Seq2Seq model:**\n\nOur final model will combine the Encoder and Decoder\n\nThe code looks like:\n\n\n\n```\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\n\nclass Seq2Seq(nn.Module):\n  def __init__(self, \n               encoder : nn.Module, \n               decoder : nn.Module, \n               source_pad_idx : int, \n               target_sos : int, \n               target_eos : int, \n               target_pad_idx : int,\n               device):\n    ''' Constructs the Seq2Seq model\n\n        Parameters\n        ----------\n        encoder : nn.Module\n          The encoder\n        decoder : nn.Module\n          The decoder\n        source_pad_idx : int\n          The padding ID in the source language\n        target_sos : int\n          The SOS token in the target language\n        target_eos : int\n          The EOS token in the target language\n        target_pad_idx : int\n          The padding ID in the target language\n        device: torch.device\n          The device to run the model on\n    '''\n    super().__init__()\n\n    self.encoder = encoder\n    self.decoder = decoder\n\n    self.source_pad_idx = source_pad_idx\n\n    self.target_sos = target_sos\n    self.target_eos = target_eos\n    self.target_pad_idx = target_pad_idx\n\n    self.device = device\n\n  def get_source_padding_mask(self, src, src_lens):\n    ''' Makes a mask for our source sequences, where src_mask[i, 0, 0, j] = 1 \n        if src[i, j] is not a padding token; else 0\n\n        Parameters\n        ----------\n        src : torch.Longtensor(N, S)\n          A batch of source sequences\n        src_lens : torch.LongTensor(N, )\n          The lengths of each source sequence in the current batch\n\n        Returns\n        -------\n        src_mask : torch.LongTensor(N, 1, 1, S)\n          The masks of each source sequence in the current batch\n    '''\n    batch_size, seq_len = src.size()\n\n    # Extend src_lens from (N, ) to (N, S)\n    src_lens = src_lens.unsqueeze(1).repeat(1, seq_len)\n\n    # Make a mask where src_mask[i, j] = 1 if src[i, j] == src padding token; else 0\n    src_mask = torch.arange(seq_len).to(self.device)\n    src_mask = src_mask.unsqueeze(0).repeat(batch_size, 1)\n    src_mask = src_mask < src_lens\n\n    # Extend src_mask from (N, S) to (N, 1, 1, S)\n    src_mask = src_mask.unsqueeze(1).unsqueeze(2)\n    \n    batch_size, seq_len = src.size()\n    assert src_mask.size() == (batch_size, 1, 1, seq_len)\n\n    return src_mask\n\n  def get_target_padding_mask(self, trg, trg_lens):\n    ''' Makes a mask for our target sequences, where trg_mask[i, j] = 1 \n        if a word exists in sequence i; else 0\n\n        It relies on self.trg_pad_idx to see if the j-th spot of sequence i \n        in trg[] is a valid word or not\n\n        Parameters\n        ----------\n        trg : torch.LongTensor(N, S')\n          A batch of target sequences\n        trg_lens : torch.LongTensor(N, )\n          The lengths of each target sequence in the current batch\n\n        Returns\n        -------\n        trg_mask : torch.LongTensor(N, 1, S', S')\n          The mask of each target sequence in the current batch\n    '''\n    batch_size, seq_len = trg.size()\n\n    # Extend src_lens from (N, ) to (N, S')\n    trg_lens = trg_lens.unsqueeze(1).repeat(1, seq_len)\n\n    # Make a mask where trg_pad_mask[i, j] = 1 if trg[i, j] == trg padding token; else 0\n    trg_pad_mask = torch.arange(seq_len).to(self.device)\n    trg_pad_mask = trg_pad_mask.unsqueeze(0).repeat(batch_size, 1)\n    trg_pad_mask = trg_pad_mask < trg_lens\n\n    # Extend the mask from (N, S') to (N, 1, S', 1)\n    trg_pad_mask = trg_pad_mask.unsqueeze(1).unsqueeze(3)\n    \n    # Apply a sub mask on the lower triangular matrix (Size: (S', S'))    \n    trg_sub_mask = torch.tril(torch.ones((seq_len, seq_len), device=self.device)).bool()\n    \n    assert trg_sub_mask.size() == (seq_len, seq_len)\n\n    # Apply a mask on the inputs (Size: (N, 1, S', S'))      \n    trg_mask = trg_pad_mask & trg_sub_mask\n\n    assert trg_mask.size() == (batch_size, 1, seq_len, seq_len) \n    \n    return trg_mask\n\n  def forward(self, src, src_lens, trg=None, trg_lens=None):\n    ''' Performs forward propogation of our model\n        If trg == None, it will get the logits from the greedy search\n\n        Parameters\n        ----------\n        src : torch.Longtensor(N, S)\n          A batch of source sequences\n        src_lens : torch.LongTensor(N, )\n          The lengths of each source sequence in the current batch\n        trg : torch.Longtensor(N, S')\n          A batch of target sequences\n        trg_lens : torch.LongTensor(N, )\n          The lengths of each target sequence in the current batch\n\n        Returns\n        -------\n        logits : torch.LongTensor(N, S', target_vocab_size)\n          The set of logits for the target sequence\n    '''\n    if self.training and trg is None:\n      raise ValueError(\"Expected target sequence (trg) must be set!\")\n\n    if trg is not None:\n      return self.get_logits_from_teacher_forcing(src, src_lens, trg, trg_lens)\n    \n    else:\n      return self.get_logits_from_greedy_search(src, src_lens)\n\n  def get_logits_from_teacher_forcing(self, src, src_lens, trg, trg_lens):\n    ''' Translates a batch of sequences in the source language to a target language\n        with the help of its expected translated sequences.\n\n        NOTE: This should only be used in training\n\n        Parameters\n        ----------\n        src : torch.Longtensor(N, S)\n          A batch of source sequences\n        src_lens : torch.LongTensor(N, )\n          The lengths of each source sequence in the current batch\n        trg : torch.Longtensor(N, S')\n          A batch of target sequences\n        trg_lens : torch.LongTensor(N, )\n          The lengths of each target sequence in the current batch\n\n        Returns\n        -------\n        logits : torch.LongTensor(N, S', target_vocab_size)\n          The set of logits for the predicted target sequence\n    '''\n    assert src.size()[0] == trg.size()[0]\n\n    src_mask = self.get_source_padding_mask(src, src_lens)\n    encoded_src = self.encoder(src, src_mask)\n    \n    trg_mask = self.get_target_padding_mask(trg, trg_lens)\n    logits = self.decoder(trg, encoded_src, trg_mask, src_mask)\n    \n    return logits\n\n  def get_logits_from_greedy_search(self, src, src_lens, max_len=50):\n    ''' Translates a batch of sentences in a source language to a target language\n\n        Parameters\n        ----------\n        src : torch.Longtensor(N, S)\n          A batch of source sequences\n        src_lens : torch.LongTensor(N, )\n          The lengths of each source sequence in the current batch\n        max_len : int (optional)\n          The max length of the target sequence\n\n        Returns\n        -------\n        logits : torch.LongTensor(N, S', target_vocab_size)\n          The set of logits for the target sequence\n    '''\n    batch_size = src.size()[0]\n\n    # All inputs to the decoder starts with SOS\n    trg = torch.tensor([[self.target_sos] for _ in range(batch_size)]).to(self.device)\n    logits = None\n\n    # Encode the source sequences\n    src_mask = self.get_source_padding_mask(src, src_lens)\n    encoded_src = self.encoder(src, src_mask)\n\n    # The lengths of each target sequence\n    # where trg_lens[i] = the length of sequence i from index 0 to its first EOS inclusive\n    trg_lens = torch.tensor([max_len + 100 for _ in range(batch_size)]).to(self.device)\n\n    # Decode the target sequences\n    cur_len = 1\n    while cur_len < max_len and torch.any(trg_lens == max_len + 100):\n\n      trg_mask = self.get_target_padding_mask(trg, trg_lens * 0 + cur_len)      \n      cur_logits = self.decoder(trg, encoded_src, trg_mask, src_mask)     # (N, cur_len, self.target_vocab_size)\n      last_logits = cur_logits[:, cur_len - 1, :]                         # (N, self.target_vocab_size)\n\n      # Get the best tokens\n      best_tokens = last_logits.argmax(1)                # (N, )\n\n      # See which has newly ended and update trg_lens (Size: (N, ))\n      new_trg_lens = (best_tokens == self.target_eos).long() * cur_len\n      condition = (new_trg_lens < trg_lens) & (best_tokens == self.target_eos)\n      trg_lens = torch.where(condition, new_trg_lens, trg_lens)\n\n      trg = torch.cat([trg, best_tokens.unsqueeze(-1)], dim=1)\n      logits = cur_logits\n      cur_len += 1\n\n      assert trg.size() == (batch_size, cur_len)\n\n    return logits\n\n  def get_logits_from_beam_search(self, src, src_lens, max_len=50, beam_width=3):\n    ''' Translates a batch of sentences in a source language to a target language\n\n        Parameters\n        ----------\n        src : torch.Longtensor(N, S)\n          A batch of source sequences\n        src_lens : torch.LongTensor(N, )\n          The lengths of each source sequence in the current batch\n        max_len : int (optional)\n          The max length of the target sequence\n        beam_width : int (optional)\n          The beam width\n\n        Returns\n        -------\n        logits : torch.LongTensor(N, beam_width, S', target_vocab_size)\n          The set of logits for the target sequence per beam width\n    '''\n    raise NotImplementedError()\n\n```\n\n## **Training:**\nWe are going to train our model and see if for each epoch it improves its predictions on the validation set\n\nHow we train it:\n* It uses teacher forcing:\n  1. First, we have the source and target sentences\n  2. Then, we feed the source sentence into the Encoder. The encoder returns the attended source sentence.\n  3. Next, we feed the attended source sentence and the target sentence into the decoder\n  4. We check if the output of the decoder is the same as the target sentence\n\nHow we make predictions:\n* It is similar to RNNs, where we feed in the source input to the encoder, feed in an SOS in the decoder, and we take the outputs of the previous decoder as inputs to the next decoder\n* In more detail:\n  1. First, we have the source sentence\n  2. Then, we feed the source sentence into the Encoder to get an attended version of the source sentence\n  3. Next, we feed an SOS token and the attended source sentence in the Decoder as the first input to our decoder\n  4. We get the outputs of the decoder and use it as the next token to feed as the second input to our decoder\n  5. Repeat 3-4 until we get an EOS token\n\n\n\n### **How to build our model:**\n\n\n```\nfrom torchtext.data.metrics import bleu_score\nfrom tqdm.notebook import tqdm\nimport torch.nn.functional as F\n\n\ndef make_model(source_vocab_size : int, \n               target_vocab_size : int, \n               source_pad_id : int, \n               target_sos_id : int, \n               target_eos_id : int, \n               target_pad_id : int, \n               device : torch.device):\n  ''' Builds our Transformer Seq2Seq model\n\n      Parameters\n      ----------\n      source_vocab_size : int\n        The vocab size in the source language\n      target_vocab_size : int\n        The vocab size in the target language\n      source_pad_id : int\n        The ID of a padding token in the source language\n      target_sos_id : int\n        The ID of a start-of-sequence token in the target language\n      target_eos_id : int\n        The ID of an end-of-sequence token in the target language\n      target_pad_id : int\n        The ID of a padding token in the target language\n      device : torch.device\n        The device to run the model on\n        \n      Returns\n      -------\n      model : Seq2Seq\n        The model\n  '''\n  word_embedding_size = 256\n\n  num_encoder_layers = 3\n  num_encoder_heads = 8\n  encoder_pf_dim = 512\n  encoder_dropout = 0.1\n\n  num_decoder_layers = 3\n  num_decoder_heads = 8\n  decoder_pf_dim = 512\n  decoder_dropout = 0.1\n  \n  encoder = Encoder(source_vocab_size, \n                    word_embedding_size, \n                    num_encoder_layers, \n                    num_encoder_heads, \n                    encoder_pf_dim, \n                    encoder_dropout, \n                    device)\n  \n  decoder = Decoder(target_vocab_size, \n                    word_embedding_size, \n                    num_decoder_layers, \n                    num_decoder_heads, \n                    decoder_pf_dim, \n                    decoder_dropout, \n                    device)\n  \n  model = Seq2Seq(encoder, \n                  decoder,\n                  source_pad_id, \n                  target_sos_id, \n                  target_eos_id, \n                  target_pad_id, \n                  device)\n  model.to(device)\n\n  return model\n```\n\n### **How to train our model for one epoch:**\n\n\n```\nfrom torchtext.data.metrics import bleu_score\nfrom tqdm.notebook import tqdm\nimport torch.nn.functional as F\n\n\ndef train_for_one_epoch(model, loss_function, optimizer, train_dataloader, device):\n  ''' Trains the model on the training set\n\n      Parameters\n      ----------\n      model : Seq2Seq\n        The model\n      loss_function : torch.nn.LossFunction\n        The loss function (ex: torch.nn.CrossEntropyLoss)\n      optimizer : torch.nn.Optimizer\n        The optimizer (ex: SGD, AdamOptimizer, etc)\n      train_dataloader : Seq2SeqDataLoader\n        The dataloader for the training set\n      device : torch.device\n        The device to run predictions on\n\n      Returns\n      -------\n      loss : float\n        The loss for the training set\n  '''\n  \n  model.train()\n  train_loss = 0.0\n\n  for _, (src, src_lens, trg, trg_lens) in tqdm(enumerate(train_dataloader), total=len(train_dataloader)):\n\n    # Send the data to the specified device\n    src = src.to(device)\n    src_lens = src_lens.to(device)\n    trg = trg.to(device)\n    trg_lens = trg_lens.to(device)\n\n    # Zeros out the model's previous gradient\n    optimizer.zero_grad()\n\n    # Get the logits\n    logits = model(src, src_lens, trg=trg[:, : -1], trg_lens=trg_lens)\n\n    # Flatten the logits so that it is (b * (t - 1), target_vocab_size)\n    flattened_logits = logits.contiguous().view(-1, logits.shape[2])\n\n    # Remove the SOS and flatten it so that it is (b * (t - 1))\n    flattened_trg = trg[:, 1:].contiguous().view(-1)\n\n    # Compute loss\n    loss = loss_function(flattened_logits, flattened_trg)\n    train_loss += loss.item()\n\n    # Backward prop\n    loss.backward()\n    optimizer.step()\n\n    del src, src_lens, trg, trg_lens, loss, logits\n\n  return train_loss / len(train_dataloader)\n```\n\n### **How to evaluate our model:**\n\n\n```\nfrom torchtext.data.metrics import bleu_score\nfrom tqdm.notebook import tqdm\nimport torch.nn.functional as F\n\n\ndef evaluate_model(model, \n                   loss_function, \n                   test_dataloader, \n                   device, \n                   target_sos, \n                   target_eos, \n                   target_pad_id, \n                   target_id2word):\n  ''' Evaluates the model on the test set\n\n      Parameters\n      ----------\n      model : Seq2Seq\n        The model\n      loss_function : torch.nn.LossFunction\n        The loss function (ex: torch.nn.CrossEntropyLoss)\n      test_dataloader : Seq2SeqDataLoader\n        The dataloader for the test set\n      device : torch.device\n        The device to run predictions on\n      target_sos : int\n        The ID of a SOS token in the target language\n      target_eos : int\n        The ID of an EOS token in the target language\n      target_pad_id : int\n        The ID of a padding token in the target language\n      target_id2word : { int : str }\n        A mapping of word IDs in the target language to its string representative\n\n      Returns\n      -------\n      loss, bleu_score : float, float\n        The loss and bleu score for the test set\n  '''\n  \n  model.eval() \n  bleu = 0\n  eval_loss = 0\n\n  with torch.no_grad():\n    for _, (src, src_lens, trg, trg_lens) in tqdm(enumerate(test_dataloader), total=len(test_dataloader)):\n\n      # Send the data to the specified device\n      src = src.to(device)\n      src_lens = src_lens.to(device)\n      trg = trg.to(device)\n      trg_lens = trg_lens.to(device)\n\n      # Get the logits\n      logits = model(src, src_lens, trg=trg[:, : -1], trg_lens=trg_lens)\n\n      # Flatten the logits so that it is (b * (t - 1), model.target_vocab_size)\n      flattened_logits = logits.contiguous().view(-1, logits.shape[2])\n\n      # Remove the SOS and flatten it so that it is (b * (t - 1))\n      flattened_trg = trg[:, 1:].contiguous().view(-1)\n\n      # Compute loss\n      loss = loss_function(flattened_logits, flattened_trg)\n      eval_loss += loss.item()\n\n      # Compute BLEU score\n      bleu += compute_batch_bleu_score(model, src, src_lens, trg, target_id2word, target_sos, target_eos, target_pad_id, device)\n\n      del src, src_lens, trg, trg_lens, loss, logits\n      \n  eval_loss /= len(test_dataloader)\n  bleu /= len(test_dataloader)\n\n  return eval_loss, bleu\n\ndef compute_batch_bleu_score(model, src, src_lens, trg, target_id2word, target_sos, target_eos, target_pad_id, device):\n  ''' Computes the BLEU score on a batch of sequences\n\n      Parameters\n      ----------\n      src : torch.tensor(N, S)\n        A batch of source sequences\n      src_lens : torch.LongTensor(N, )\n        The lengths of each source sequence in the current batch\n      trg : torch.tensor(N, S')\n        A batch of expected target sequences\n      target_id2word : { int : str }\n        A mapping of word IDs in the target language to its string representative\n      target_sos : int\n        The ID of a SOS token in the target language\n      target_eos : int\n        The ID of an EOS token in the target language\n      target_pad_id : int\n        The ID of a padding token in the target language\n      device : torch.device\n        The device to run predictions on\n\n      Returns\n      -------\n      bleu_score : float\n        The bleu score for the batch of sequences\n  '''\n  # Get predicted output and add EOS to the end of each sequence (in case any seq doesn't have an EOS)\n  logits = model(src, src_lens)\n  predicted_trg = logits.argmax(2)\n\n  # Remove SOS token\n  expected_trg = trg[:, 1:]\n\n  # Move to the CPU\n  predicted_trg = predicted_trg.cpu().tolist()\n  expected_trg = expected_trg.cpu().tolist()\n\n  # Populate lst for bleu score\n  predicted_seqs = []\n  expected_seqs = []\n\n  for i in range(len(predicted_trg)):\n\n    predicted_seq = predicted_trg[i]\n    expected_seq = expected_trg[i]\n\n    # Remove the EOS\n    if target_eos in predicted_seq:\n      predicted_seq = predicted_seq[: predicted_seq.index(target_eos)]\n    if target_eos in expected_seq:\n      expected_seq = expected_seq[: expected_seq.index(target_eos)]\n\n    # Convert IDs to words\n    predicted_seq = [target_id2word.get(id_, \"NAN\") for id_ in predicted_seq]\n    expected_seq = [target_id2word.get(id_, \"NAN\") for id_ in expected_seq]\n\n    predicted_seqs.append(predicted_seq)\n    expected_seqs.append([expected_seq])\n\n  return bleu_score(predicted_seqs, expected_seqs)\n\n```\n\n### **How to train our model for many epochs:**\n\n\n```\nfrom tqdm.notebook import tqdm\n\ndef train():\n  ''' The main function to train and test our model.\n      It can perform early-stopping instead of hard-coding the number of epochs to run for\n\n      Returns\n      -------\n      model : Seq2Seq\n        The trained Seq2Seq model\n  '''\n  global source_vocabs, target_vocabs\n  global dataset, train_dataset, val_dataset\n  global train_dataloader, val_dataloader\n\n  device = torch.device(\"cuda\")\n\n  model = make_model(dataset.source_vocab_size, \n                     dataset.target_vocab_size,\n                     dataset.source_pad_id, \n                     dataset.target_sos,\n                     dataset.target_eos,\n                     dataset.target_pad_id,\n                     device)\n  \n  patience = 3 #float(\"inf\")\n  num_epochs = float(\"inf\")\n\n  best_val_loss = float(\"inf\")\n\n  num_poor = 0\n  epoch = 1\n  \n  optimizer = torch.optim.Adam(model.parameters(), lr=0.0005)\n\n  while epoch <= num_epochs and num_poor < patience:\n      \n    # Train\n    loss_function = torch.nn.CrossEntropyLoss(ignore_index=dataset.target_pad_id)\n    train_loss = train_for_one_epoch(model, \n                                     loss_function, \n                                     optimizer, \n                                     train_dataloader, \n                                     device)\n    \n    # Evaluate the model\n    val_loss, val_bleu = evaluate_model(model, \n                                        loss_function, \n                                        val_dataloader, \n                                        device, \n                                        dataset.target_sos, \n                                        dataset.target_eos,\n                                        dataset.target_pad_id,\n                                        target_vocabs.get_id2word())\n\n    print(f\"Epoch {epoch}: Train loss={train_loss}, Val loss={val_loss}, Val BLEU={val_bleu}\")\n\n    if val_loss > best_val_loss:\n      num_poor += 1\n\n    else:\n      num_poor = 0\n      best_val_loss = val_loss\n\n    epoch += 1\n\n  return model\n\ntrained_model = train()\n\n\n```\n\n\n    HBox(children=(IntProgress(value=0, max=346), HTML(value='')))\n\n\n    \n\n\n\n    HBox(children=(IntProgress(value=0, max=116), HTML(value='')))\n\n\n    \n    Epoch 1: Train loss=4.829797588331851, Val loss=4.019924899627423, Val BLEU=0.07824927062354849\n\n\n\n    HBox(children=(IntProgress(value=0, max=346), HTML(value='')))\n\n\n    \n\n\n\n    HBox(children=(IntProgress(value=0, max=116), HTML(value='')))\n\n\n    \n    Epoch 2: Train loss=3.7660733261549404, Val loss=3.377837306466596, Val BLEU=0.13099991108494288\n\n\n\n    HBox(children=(IntProgress(value=0, max=346), HTML(value='')))\n\n\n    \n\n\n\n    HBox(children=(IntProgress(value=0, max=116), HTML(value='')))\n\n\n    \n    Epoch 3: Train loss=3.243533132393236, Val loss=3.008571817957122, Val BLEU=0.16806063581843336\n\n\n\n    HBox(children=(IntProgress(value=0, max=346), HTML(value='')))\n\n\n    \n\n\n\n    HBox(children=(IntProgress(value=0, max=116), HTML(value='')))\n\n\n    \n    Epoch 4: Train loss=2.872940674682573, Val loss=2.74376511984858, Val BLEU=0.20142291382050853\n\n\n\n    HBox(children=(IntProgress(value=0, max=346), HTML(value='')))\n\n\n    \n\n\n\n    HBox(children=(IntProgress(value=0, max=116), HTML(value='')))\n\n\n    \n    Epoch 5: Train loss=2.5676805504484674, Val loss=2.5586785324688615, Val BLEU=0.2306284617083488\n\n\n\n    HBox(children=(IntProgress(value=0, max=346), HTML(value='')))\n\n\n    \n\n\n\n    HBox(children=(IntProgress(value=0, max=116), HTML(value='')))\n\n\n    \n    Epoch 6: Train loss=2.310778110358067, Val loss=2.4027339466686906, Val BLEU=0.24768150766502692\n\n\n\n    HBox(children=(IntProgress(value=0, max=346), HTML(value='')))\n\n\n    \n\n\n\n    HBox(children=(IntProgress(value=0, max=116), HTML(value='')))\n\n\n    \n    Epoch 7: Train loss=2.1018241240799083, Val loss=2.285192982903842, Val BLEU=0.27027300271563864\n\n\n\n    HBox(children=(IntProgress(value=0, max=346), HTML(value='')))\n\n\n    \n\n\n\n    HBox(children=(IntProgress(value=0, max=116), HTML(value='')))\n\n\n    \n    Epoch 8: Train loss=1.9187282844085913, Val loss=2.1851467839602767, Val BLEU=0.29221272883658145\n\n\n\n    HBox(children=(IntProgress(value=0, max=346), HTML(value='')))\n\n\n    \n\n\n\n    HBox(children=(IntProgress(value=0, max=116), HTML(value='')))\n\n\n    \n    Epoch 9: Train loss=1.7561732602946332, Val loss=2.1181903337610177, Val BLEU=0.30411030188321037\n\n\n\n    HBox(children=(IntProgress(value=0, max=346), HTML(value='')))\n\n\n    \n\n\n\n    HBox(children=(IntProgress(value=0, max=116), HTML(value='')))\n\n\n    \n    Epoch 10: Train loss=1.621830485459697, Val loss=2.0600934090285468, Val BLEU=0.3158219502714136\n\n\n\n    HBox(children=(IntProgress(value=0, max=346), HTML(value='')))\n\n\n    \n\n\n\n    HBox(children=(IntProgress(value=0, max=116), HTML(value='')))\n\n\n    \n    Epoch 11: Train loss=1.5022827094000888, Val loss=2.019174390825732, Val BLEU=0.32712729654684874\n\n\n\n    HBox(children=(IntProgress(value=0, max=346), HTML(value='')))\n\n\n    \n\n\n\n    HBox(children=(IntProgress(value=0, max=116), HTML(value='')))\n\n\n    \n    Epoch 12: Train loss=1.407898038797985, Val loss=2.0036077838519524, Val BLEU=0.33240368932356235\n\n\n\n    HBox(children=(IntProgress(value=0, max=346), HTML(value='')))\n\n\n    \n\n\n\n    HBox(children=(IntProgress(value=0, max=116), HTML(value='')))\n\n\n    \n    Epoch 13: Train loss=1.3210895230315325, Val loss=1.9749235079206269, Val BLEU=0.34271181671609086\n\n\n\n    HBox(children=(IntProgress(value=0, max=346), HTML(value='')))\n\n\n    \n\n\n\n    HBox(children=(IntProgress(value=0, max=116), HTML(value='')))\n\n\n    \n    Epoch 14: Train loss=1.2502033064475637, Val loss=1.9576816291644656, Val BLEU=0.35236664130812395\n\n\n\n    HBox(children=(IntProgress(value=0, max=346), HTML(value='')))\n\n\n    \n\n\n\n    HBox(children=(IntProgress(value=0, max=116), HTML(value='')))\n\n\n    \n    Epoch 15: Train loss=1.1891738300378611, Val loss=1.950673339695766, Val BLEU=0.3528871710238762\n\n\n\n    HBox(children=(IntProgress(value=0, max=346), HTML(value='')))\n\n\n    \n\n\n\n    HBox(children=(IntProgress(value=0, max=116), HTML(value='')))\n\n\n    \n    Epoch 16: Train loss=1.1325603864785563, Val loss=1.9223674268558109, Val BLEU=0.36831577589328\n\n\n\n    HBox(children=(IntProgress(value=0, max=346), HTML(value='')))\n\n\n    \n\n\n\n    HBox(children=(IntProgress(value=0, max=116), HTML(value='')))\n\n\n    \n    Epoch 17: Train loss=1.0868108026209595, Val loss=1.9321869560356797, Val BLEU=0.36434273806268097\n\n\n\n    HBox(children=(IntProgress(value=0, max=346), HTML(value='')))\n\n\n    \n\n\n\n    HBox(children=(IntProgress(value=0, max=116), HTML(value='')))\n\n\n    \n    Epoch 18: Train loss=1.0412763961822311, Val loss=1.922632688078387, Val BLEU=0.3740773429587025\n\n\n\n    HBox(children=(IntProgress(value=0, max=346), HTML(value='')))\n\n\n    \n\n\n\n    HBox(children=(IntProgress(value=0, max=116), HTML(value='')))\n\n\n    \n    Epoch 19: Train loss=1.0011622173593224, Val loss=1.9348515395460457, Val BLEU=0.3740988789128009\n\n\n## **Testing**\nWe are going to test our model on the test set\n\n\n```\ndef test():\n  ''' Used to test the model on the testing data'''\n  \n  global source_vocabs, target_vocabs\n  global dataset, test_dataset, test_dataloader\n  global trained_model\n\n  device = torch.device(\"cuda\")\n    \n  # The loss function\n  loss_function = torch.nn.CrossEntropyLoss(ignore_index=test_dataset.target_pad_id)\n\n  # Evaluate the model\n  test_loss, test_bleu = evaluate_model(trained_model, \n                                        loss_function, \n                                        test_dataloader, \n                                        device, \n                                        test_dataset.target_sos, \n                                        test_dataset.target_eos,\n                                        test_dataset.target_pad_id,\n                                        target_vocabs.get_id2word())\n\n  print(f\"Test loss={test_loss}, Test Bleu={test_bleu}\")\n\ntest()\n```\n\n\n    HBox(children=(IntProgress(value=0, max=16), HTML(value='')))\n\n\n    \n    Test loss=1.5746025443077087, Test Bleu=0.42946506908385707\n\n", "meta": {"hexsha": "46a2e3d308294384d73ba162e296a7da4a384ffc", "size": 503242, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Translator/notebooks/NMT using Transformers.ipynb", "max_stars_repo_name": "EKarton/English-French-Translator", "max_stars_repo_head_hexsha": "da9cecce49498c4f79946a631206985f99daaed3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-10T04:49:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-10T04:49:23.000Z", "max_issues_repo_path": "Translator/notebooks/NMT using Transformers.ipynb", "max_issues_repo_name": "EKarton/English-French-Translator", "max_issues_repo_head_hexsha": "da9cecce49498c4f79946a631206985f99daaed3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2022-01-13T02:37:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T01:00:11.000Z", "max_forks_repo_path": "Translator/notebooks/NMT using Transformers.ipynb", "max_forks_repo_name": "EKarton/English-French-Translator", "max_forks_repo_head_hexsha": "da9cecce49498c4f79946a631206985f99daaed3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-05T10:45:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-05T10:45:52.000Z", "avg_line_length": 36.9976474048, "max_line_length": 483, "alphanum_fraction": 0.4892357951, "converted": true, "num_tokens": 19855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10521053109182894, "lm_q2_score": 0.06278921473524327, "lm_q1q2_score": 0.006606086629133836}}
{"text": "# Make a copy of this template\n\nYou will need to have access to Quantum Computing Service before running this colab.\n\nThis notebook can serve as a starter kit for you to run programs on Google's quantum hardware.  You can download it using the directions below, open it in colab (or Jupyter), and modify it to begin your experiments.\n\n## How to download iPython notebooks from github\n\nYou can retrieve ipython notebooks in the cirq repository by\ngoing to the [doc directory](https://github.com/quantumlib/Cirq/tree/master/docs).  For instance, this colab template can be found [here](https://github.com/quantumlib/Cirq/blob/master/docs/tutorials/google/colab.ipynb).  Select the file that you would like to download and then click the \"Raw\" button in the upper right part of the window:\n\n\n\nThis will show the entire file contents.  Right-click and select \"Save as\" to save this file to your computer.  Make sure to save to a file with a \".ipynb\" extension.  (Note: you may need to select \"All files\" from the format dropdown instead of \"text\").   You can also get to this colab's [raw contenti directly](https://raw.githubusercontent.com/quantumlib/Cirq/master/docs/tutorials/google/colab.ipynb)\n\nYou can also retrieve the entire cirq repository by running the following command in a terminal that has git installed.  `git checkout https://github.com/quantumlib/Cirq.git` \n\n## How to open colab\n\nYou can open a new colab from your Google Drive window or by visiting the [colab site](https://colab.research.google.com/notebooks/intro.ipynb).  From the colaboratory site, you can use the menu to upload an ipython notebook:\n\n\n\nThis will upload the ipynb file that you downloaded before.  You can now run all the commands, modify it to suit your goals, and share it with others.\n\n### More Documentation Links\n\n* [Quantum Engine concepts](../../google/concepts.md)\n* [Quantum Engine documentation](../../google/engine.md)\n* [Cirq documentation](https://cirq.readthedocs.io)\n* [Colab documentation](https://colab.sandbox.google.com/notebooks/welcome.ipynb)\n\n\n## Authenticate and install cirq\n\nFor details of authentication and installation, please see [go/quantum-engine-quickstart](https://go/quantum-engine-quickstart). \n\nNote:  The below code will install the latest stable release of cirq.  If you need the latest and greatest features and don't mind if a few things aren't quite working correctly, you can install `cirq-unstable` instead of `cirq` to get the most up-to-date features of cirq.\n\n1. Enter the cloud project_id you'd like to use in the 'project_id' field.\n\n2. Then run the cell below (and go through the auth flow for access to the project id you entered).\n\n\n\n\n```\n# The Google Cloud Project id to use.\nproject_id = 'quantum-cloud-client' #@param {type:\"string\"}\n\n\ndef setup_auth():\n  \"\"\"Runs the user through the Colab OAuth process.\n  \n  Sets the local Application Default Credentials. For more information on on \n  using Application Default Credentials see \n  https://cloud.google.com/docs/authentication/production\n  \"\"\"\n  from google.colab import auth\n  auth.authenticate_user(clear_output=False)\n\n\nprint(\"Getting OAuth2 credentials.\")\nprint(\"Press enter after entering the verification code.\")\nsetup_auth()\nprint(\"Authentication complete.\")\n\n!pip install cirq\nprint(\"Cirq installed.\")\n```\n\n    Getting OAuth2 credentials.\n    Press enter after entering the verification code.\n    Authentication complete.\n    Requirement already satisfied: cirq in /usr/local/lib/python3.6/dist-packages (0.8.2)\n    Requirement already satisfied: freezegun~=0.3.15 in /usr/local/lib/python3.6/dist-packages (from cirq) (0.3.15)\n    Requirement already satisfied: google-api-core[grpc]<2.0.0dev,>=1.14.0 in /usr/local/lib/python3.6/dist-packages (from cirq) (1.16.0)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.6/dist-packages (from cirq) (3.7.4.3)\n    Requirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from cirq) (0.7)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.6/dist-packages (from cirq) (1.1.1)\n    Requirement already satisfied: networkx~=2.4 in /usr/local/lib/python3.6/dist-packages (from cirq) (2.5)\n    Requirement already satisfied: protobuf~=3.12.0 in /usr/local/lib/python3.6/dist-packages (from cirq) (3.12.4)\n    Requirement already satisfied: sortedcontainers~=2.0 in /usr/local/lib/python3.6/dist-packages (from cirq) (2.2.2)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from cirq) (1.4.1)\n    Requirement already satisfied: numpy~=1.16 in /usr/local/lib/python3.6/dist-packages (from cirq) (1.18.5)\n    Requirement already satisfied: requests~=2.18 in /usr/local/lib/python3.6/dist-packages (from cirq) (2.23.0)\n    Requirement already satisfied: matplotlib~=3.0 in /usr/local/lib/python3.6/dist-packages (from cirq) (3.2.2)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from cirq) (1.0.5)\n    Requirement already satisfied: python-dateutil!=2.0,>=1.0 in /usr/local/lib/python3.6/dist-packages (from freezegun~=0.3.15->cirq) (2.8.1)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from freezegun~=0.3.15->cirq) (1.15.0)\n    Requirement already satisfied: setuptools>=34.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (49.6.0)\n    Requirement already satisfied: pytz in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (2018.9)\n    Requirement already satisfied: googleapis-common-protos<2.0dev,>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (1.52.0)\n    Requirement already satisfied: google-auth<2.0dev,>=0.4.0 in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (1.17.2)\n    Requirement already satisfied: grpcio<2.0dev,>=1.8.2; extra == \"grpc\" in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (1.31.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy->cirq) (1.1.0)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx~=2.4->cirq) (4.4.2)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (2.10)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (2020.6.20)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq) (0.10.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq) (2.4.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq) (1.2.0)\n    Requirement already satisfied: rsa<5,>=3.1.4; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from google-auth<2.0dev,>=0.4.0->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (4.6)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth<2.0dev,>=0.4.0->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (4.1.1)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.6/dist-packages (from google-auth<2.0dev,>=0.4.0->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (0.2.8)\n    Requirement already satisfied: pyasn1>=0.1.3 in /usr/local/lib/python3.6/dist-packages (from rsa<5,>=3.1.4; python_version >= \"3\"->google-auth<2.0dev,>=0.4.0->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (0.4.8)\n    Cirq installed.\n\n\n## Create an Engine variable\n\nThe following creates and engine variable which can be used to run programs under the project id you entered. above\n\n\n```\nimport cirq\n\n# Create an Engine object to use, providing the project id and the args\n# used for authentication (produced by running the authentication above).\nengine = cirq.google.Engine(project_id=project_id)\n```\n\n## Example\n\n\n```\n\n# A simple example.\nq = cirq.GridQubit(5, 2)\ncircuit = cirq.Circuit(cirq.X(q)**0.5, cirq.measure(q, key='m'))\n\njob = engine.run_sweep(\n    program=circuit,\n    repetitions=10000,\n    processor_ids=['rainbow'],\n    gate_set=cirq.google.SYC_GATESET)\n\nresults = [str(int(b)) for b in job.results()[0].measurements['m'][:, 0]]\nprint('Success!  Results:')\nprint(''.join(results))\n```\n\n    Success!  Results:\n    0000001111010100111111000100000000011100001000000011110011101011101101100000101000000110010110011100001001000110001110100101010010101100011010110000010001011001111001111001110011111001100011110110001001101010000000000111101101010110101010011011011111110010111010000010001000101110101100111111111101110100100100000011110010010000110111100111010010101111010001111100011100100101010011111011100000000100100001001100110001000101000011010101010111110001000000011100100000001011011111111001001011000001100110101000000001100110000111000100110101110111101010100110001101001000010110011001011010000111111000111010101111100101100001011101100101000110001100001100010001001001110010000010001011111101101101111011101101100010110001000111001010101001011111011111100011001110001110010111000011010011101101000011100111011000001001010101010010001101011010101011001001010001000111100101000011000101011011110111011101001011001001011011001101111010010011110010011101011011010111001110110101010101010101010001100101000001000101101001010000101110101011011111101010001011111010111110011101111111010100000001100000001100100011001011110111011111110011101010111000011101100111111101100001111100001110100100001010011001110111010000011101110011010001111011110101010011010111011001000101111010000110000111010111110001101011010010100010111111100001011111000001010000001001101100110011001100001000101101001100101011101100011011000111100111000001001100001110100010110011101001111101011000100111010001111001111000110000101001000100010110110001011111001100110101110001110110101101010001010101110100100110100000101101000101010011000110101010101011110111011111110010111011111100000001000000011110101010100111110000010001000101000111011001100100011001101101010000101010001100000001010001110110000000000111100110000010101100001000101110101100010110000010101000110110100010110101001001010010001010111010001001100000000011101110110010111100000000010011001010010010111111010100001011010100101001001110101100000001011001100011100111110011001101111000001001101111100111010100111111101000011100100110111010100010010000001101111111100101111101000101101010000010010100000100111000000110101111101000101001010010001111101000000001011011000111110001111100111010000110000100000110010101110011010100110010010111111010101100101101001111001001000000000100011111000101101001011010110010100100000011001111100111101111111011010110010000111001000110000011001111111010010010100110000011100101011001000111011010101000001011100010001011001111001101000111011000110110001001110010000010111010110100100110000010011101001000100010010011100000010010110100100011011010111000110110110000001001011000000000100111000101110010110001111001001111001011011110010110010101010001100010101000100000110111010111001111000111000010000100101011001001100111100011111000001010110011110111000101000010000110011010110110101110100000101011011001011001110011001001101010001000000111110000101100001100101000110000011110001110000101001001100010101010000000100101100001101001111001001101000010100001011110011100000100000000100010101100111101100011101101010100010110000101010011011101011010100110111100110011001011001000110100001000100010111011011110111011011110100010010011100001011001111001010111000000010110110100001010111010000111110101000000110101100110001010001101110101001110100110110110011111100111101111111001010011011001101111000000110110111110111000010001011001011011010110000000010010100101000110110000100011011010011110100010101101101001001001100001100001011000110011011011110100100000010001011011111000010110010111010011110011110010000101111011100010010011101011110000101010010000011001110101111000001011110010111110001110110100101001001100000011001010010100011101001100110111000001011111011010000111100010111100000011000110001111010100000111000101100000011100100101111100101111100111011110100110011100011110100111010000010111000110100011001000010011100101111010010100110100100011101100111001100101111111110101101001010111100000110010000111100010100100110001010000010011101110111010110010100000110001111100001001000100001010001010110101110110110111100101110001110010010001010110000001000101010111110001100011111011100010110111011000000010101110111101100110000010000000010100111110011000010000001010101111010100000110001001011000010101111100001111110001101100011110110010010110011110110010001011100010010000000010000101010010111101001010101011001011110100000101111100111010010110010001110001010101000111001101110011100000010101101011000100010110011011011111100010110111110100111111101100001100000000000101000101011100111000000100110000010110110010001111000011000101110000010101110011011000010111110111110101101000000100000110101010001000100100000010000101010000011010001000001111001001010011101101001001100100101011111011010100101010001011110111110011101100001010111111110110111010000011111100001101101000010111010000110001111000101110010110110101110000100000111101001101100111100000110100011101101111011111010010001110010011011110101101100100001001000110100110110001010111011101101100101101000111001000110111101000000001011000100110100010011001000111110010101110010010011011011011001111110010000111011011101010001011011000011010111011100001011000111100101000011010101010010001000010000100001000101100111111111110000111110010011001000110110111010000000110110100100111101101011001111110011010100000111000100100110110000000001110110010000010100010100101001000001101101100101001111101000111100001111110011110001000110000011011100100110100000010111011011000000011000000001011101010110100111101001101100100001111000011101110011001111111011101011000100010011001101010100110000001100111000001011001010110100111001101111101101000100111110001111100001110010110000000100101011010111001001100011101110111011100111011111111111111010010101100111111100101011101101011011010111110011011110111011111100110101010000000000101111000010100100100000100001110011010011001001110111111110001101010001010000010110111111111011010000110101001010111111110110111000111011000101100001000011010111010010000111110110100110010111000011011100000110011000110100011111100110000101101111101001100101001010101001011111100010110110000100110111110010111100011010110000011001100111010010000111111011000010110100111111101000101101100110000001010011000011111101010000000010011101101101111000101100010100001100011011100001101111101011101010110001110000101011011100010100110011001100110001100001101001000000010101100001000000110101110111000110100100101000001110110111001000001101100011011000010101110011100001111000011101011001011010100001101101011111001000101001011101000010111011000101011101110110100011110111101110110011101111010111010111001001101110001011000100011101000111000001000000100100000101000100001001010101110111010010011000100000010000111101011000010100100111001111101111011001110101000000100001111111000111100100011101111111000001111111101100000110010001110110001111010100010000000010000010101010010101000001001000000011001101100001110111010001000101011001010000000100111101001111010010001011011101011011011101110100000110110001100001010010111000111010010011110010001001010001001000011110000001000001111001101001111011011100010110010010101000001011000000100000101000111110010001000100000000110111100001011100010011100001011100110100001000010101101010100001000000100100010101001000101110110111010111111000110000100010000011110100100111010100000011111101010110100110110100001000001001001010101011010101011110011111000011000000111101110100000100101111100111110110000100110100000011111110111110100001011010111010000100101010101110001100100101000101101101001011101010101100111001001101001000110101111111001111011110101011101001110100000010010001101101100000010110000011001100001110110010100000000011110111100000100001101011001100110110000001001000001101111001101101111001110011101101101010001101100110111110011110010001000110110010100100010100111000000100010111011100100110100100110111000110001010010000110000001101000010100011101110010110101100001101001101000000100100010000010000011110110101100000011110010101010010001100110101001100101000101100010101001010000111000111000000000001001100100110001111000110100001000000010001110011011001110000011001000011101010011110000101001101111100110000111110101111111111101011100101011001001010101101001100110110111000111110111011101000011001100101010111101100111010001001000001011001101101111110001001111111111110001000100011100101100110110101101100110110010110011111001101001011011111110001011110110000100010000101011110011001000100010100011101111100010011011010011100111110111000111100110000010011100111011100011001011001101101011001000001001010011101111010000101011010100011010011001111011010001111010010111001111000001000001111100100010110001000100011011110001010011101000110000100110010111110111110011000101001000111000001100001110010000011100010001111100011001110011100001100011010010000001000001100010100100110101001101110011001001010100011010110011111010101100111110010011100101101111001110001011001000101101100111010000100111101010101010100001100011001101011111111110010001111100111001001110010101100111001010000001000100000111101110111001110111100100110101000110000001100000101001010001111000001110110100000011100011011100011011100101010100110011111110110011110100100111100110110100111010100001011101010001000010011010011101010001010101000100011111110001010000000100100111101110100000100100110100000101001111011011011110011111101001011100010111110110100011001100000101000110100101101011001010111100000000111010101011101110101100100101001001111010001111100101010011011000101000111100010010010000001111001001100011110001000110011010110110100100111011100111010110111010110011010101010111100110000101101111101110010001010011000010111001110110000100100101010001001010110110001001001011001000010100111100010110110101000111100110010110001010010010000110010101111000010001100111010100010111100110000000010001101001011100110001011000100101000011101000010110100001110011010101111011101111110110011111111000111010010010100010011100100100100011111111011111110100110001100110\n\n", "meta": {"hexsha": "0b9dbf6b8362f2175de914ea4c43aaac739263a8", "size": 23206, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/google/colab.ipynb", "max_stars_repo_name": "yourball/Cirq", "max_stars_repo_head_hexsha": "984a428b3ab5ecaf4078a7d264ab915517042e5a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-26T03:56:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-27T13:21:04.000Z", "max_issues_repo_path": "docs/tutorials/google/colab.ipynb", "max_issues_repo_name": "yourball/Cirq", "max_issues_repo_head_hexsha": "984a428b3ab5ecaf4078a7d264ab915517042e5a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/tutorials/google/colab.ipynb", "max_forks_repo_name": "yourball/Cirq", "max_forks_repo_head_hexsha": "984a428b3ab5ecaf4078a7d264ab915517042e5a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 92.0873015873, "max_line_length": 10016, "alphanum_fraction": 0.7689821598, "converted": true, "num_tokens": 5932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11124121829336078, "lm_q2_score": 0.05921024825110538, "lm_q1q2_score": 0.0065866201509052974}}
{"text": "# Configuration\n\n\n```python\nfrom traitlets.config.manager import BaseJSONConfigManager\npath = \"/home/ucl/nbconfig\"\ncm = BaseJSONConfigManager(config_dir=path)\n\ncm.update('livereveal', {\n        'theme': 'sky',\n        'transition': 'zoom',\n        'start_slideshow_at': 'selected',\n        'controls': True\n})\n```\n\n\n\n\n    {'controls': True,\n     'start_slideshow_at': 'selected',\n     'theme': 'sky',\n     'transition': 'zoom'}\n\n\n\n\n```javascript\n%%javascript\nrequire(['base/js/utils'],\nfunction(utils) {\n   utils.load_extensions('calico-spell-check', 'calico-document-tools', 'calico-cell-tools');\n});\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n```python\n%load_ext tikzmagic\n```\n\n\n```python\n%%html\n<style>\n.red { color: #E41A1C; }\n.orange { color: #FF7F00 }\n.yellow { color: #FFC020 }         \n.green { color: #4DAF4A }                  \n.blue { color: #377EB8; }\n.purple { color: #984EA3 }       \n       \nh1 {\n    color: #377EB8;\n}\n       \nctb_global_show div.ctb_hideshow.ctb_show {\n    display: inline;\n} \n         \ndiv.tabContent {\n    padding: 0px;\n    background: #ffffff;     \n    border: 0px;                        \n}  \n         \n.left {\n    float: left;\n    width: 50%;\n    vertical-align: text-top;\n}\n\n.right {\n    margin-left: 50%;\n    vertical-align: text-top;                            \n}    \n               \n.small {         \n    zoom: 0.9;\n    -ms-zoom: 0.9;\n    -webkit-zoom: 0.9;\n    -moz-transform:  scale(0.9,0.9);\n    -moz-transform-origin: left center;  \n}          \n         \n.verysmall {         \n    zoom: 0.75;\n    -ms-zoom: 0.75;\n    -webkit-zoom: 0.75;\n    -moz-transform:  scale(0.75,0.75);\n    -moz-transform-origin: left center;  \n}         \n   \n        \n.tiny {         \n    zoom: 0.6;\n    -ms-zoom: 0.6;\n    -webkit-zoom: 0.6;\n    -moz-transform:  scale(0.6,0.6);\n    -moz-transform-origin: left center;  \n}         \n         \n         \n.rendered_html blockquote {\n    border-left-width: 0px;\n    padding: 15px;\n    margin: 0px;    \n    width: 100%;                            \n}         \n         \n.rendered_html th {\n    padding: 0.5em;  \n    border: 0px;                            \n}         \n         \n.rendered_html td {\n    padding: 0.25em;\n    border: 0px;                                                        \n}    \n     \n#for reveal         \n.aside .controls, .reveal .controls {\n    display: none !important;                            \n    width: 0px !important;\n    height: 0px !important;\n}\n    \n.rise-enabled .reveal .slide-number {\n    right: 25px;\n    bottom: 25px;                        \n    font-size: 200%;     \n    color: #377EB8;                        \n}         \n         \n.rise-enabled .reveal .progress span {\n    background: #377EB8;\n}     \n         \n.present .top {\n    position: fixed !important;\n    top: 0 !important;                                   \n}                  \n    \n.present .rendered_html * + p, .present .rendered_html p, .present .rendered_html * + br, .present .rendered_html br {\n    margin: 0.5em 0;                            \n}  \n         \n.present tr, .present td {\n    border: 0px;\n    padding: 0.35em;                            \n}      \n         \n.present th {\n    border: 1px;\n}\n         \npresent .prompt {\n    min-width: 0px !important;\n    transition-duration: 0s !important;\n}     \n         \n.prompt {\n    min-width: 0px !important;\n    transition-duration: 0s !important;                            \n}         \n         \n.rise-enabled .cell li {\n    line-height: 135%;\n}\n         \n</style>\n\n%load_ext tikzmagic\n```\n\n\n<style>\n.red { color: #E41A1C; }\n.orange { color: #FF7F00 }\n.yellow { color: #FFC020 }         \n.green { color: #4DAF4A }                  \n.blue { color: #377EB8; }\n.purple { color: #984EA3 }       \n\nh1 {\n    color: #377EB8;\n}\n\nctb_global_show div.ctb_hideshow.ctb_show {\n    display: inline;\n} \n\ndiv.tabContent {\n    padding: 0px;\n    background: #ffffff;     \n    border: 0px;                        \n}  \n\n.left {\n    float: left;\n    width: 50%;\n    vertical-align: text-top;\n}\n\n.right {\n    margin-left: 50%;\n    vertical-align: text-top;                            \n}    \n\n.small {         \n    zoom: 0.9;\n    -ms-zoom: 0.9;\n    -webkit-zoom: 0.9;\n    -moz-transform:  scale(0.9,0.9);\n    -moz-transform-origin: left center;  \n}          \n\n.verysmall {         \n    zoom: 0.75;\n    -ms-zoom: 0.75;\n    -webkit-zoom: 0.75;\n    -moz-transform:  scale(0.75,0.75);\n    -moz-transform-origin: left center;  \n}         \n\n\n.tiny {         \n    zoom: 0.6;\n    -ms-zoom: 0.6;\n    -webkit-zoom: 0.6;\n    -moz-transform:  scale(0.6,0.6);\n    -moz-transform-origin: left center;  \n}         \n\n\n.rendered_html blockquote {\n    border-left-width: 0px;\n    padding: 15px;\n    margin: 0px;    \n    width: 100%;                            \n}         \n\n.rendered_html th {\n    padding: 0.5em;  \n    border: 0px;                            \n}         \n\n.rendered_html td {\n    padding: 0.25em;\n    border: 0px;                                                        \n}    \n\n#for reveal         \n.aside .controls, .reveal .controls {\n    display: none !important;                            \n    width: 0px !important;\n    height: 0px !important;\n}\n\n.rise-enabled .reveal .slide-number {\n    right: 25px;\n    bottom: 25px;                        \n    font-size: 200%;     \n    color: #377EB8;                        \n}         \n\n.rise-enabled .reveal .progress span {\n    background: #377EB8;\n}     \n\n.present .top {\n    position: fixed !important;\n    top: 0 !important;                                   \n}                  \n\n.present .rendered_html * + p, .present .rendered_html p, .present .rendered_html * + br, .present .rendered_html br {\n    margin: 0.5em 0;                            \n}  \n\n.present tr, .present td {\n    border: 0px;\n    padding: 0.35em;                            \n}      \n\n.present th {\n    border: 1px;\n}\n\npresent .prompt {\n    min-width: 0px !important;\n    transition-duration: 0s !important;\n}     \n\n.prompt {\n    min-width: 0px !important;\n    transition-duration: 0s !important;                            \n}         \n\n.rise-enabled .cell li {\n    line-height: 135%;\n}\n\n</style>\n\n%load_ext tikzmagic\n\n\n<center><h1>Recurrent Neural Networks</h1></center><br>\n\n<center><b>Pasquale Minervini</b></center><p>\n<center><a href=\"mailto:p.minervini@cs.ucl.ac.uk\">p.minervini@cs.ucl.ac.uk</a></center><p>\n<!--\n<p>\n-->\n<p>\n<center>University College London</center>\n<br>\n\n<center>Statistical Natural Language Processing Course, UCL<center>\n<center>9th December 2016<center>\n\n\n\n# Language Models (LMs)\n\nA LM computes a **probability** for a **sequence of words**\n\n$$p(w_{1}, \\ldots, w_{d})$$\n\nUseful in a miriad of NLP tasks, such as machine translation:\n\n$$p(\\text{I}, \\text{go}, \\text{home}) > p(\\text{I}, \\text{go}, \\text{house})$$\n\n# $n$-Gram Language Models\n\nIn *$n$-gram language models*, the probability $p(w_{1}, \\ldots, w_{d})$ of observing the sentence $(w_{1}, \\ldots, w_{d})$ is **approximated** as:\n\n$$p(w_{1}, \\ldots, w_{d}) = \\prod_{i=1}^{d} p(w_{i} \\mid w_{1}, \\ldots, w_{i - 1}) \\\\ \\approx \\prod_{i=1}^{d} p(w_{i} \\mid w_{i - (n - 1)}, \\ldots, w_{i - 1})$$\n\nExample with a **bigram** ($n = 2$) **language model**:\n\n$$p(\\text{I}, \\text{go}, \\text{home}) \\approx p(\\text{I} \\mid \\text{[START]}) \\; p(\\text{go} \\mid \\text{I}) \\; p(\\text{home} \\mid \\text{go})$$\n\n# A Recurrent Neural Network LM\n\nGiven a sequence of **word vectors** (e.g. one-hot, word2vec, GloVe), each representing a word $w \\in V$ in the vocabulary $V$:\n\n$$(\\mathbf{x}_{1}, \\ldots, \\mathbf{x}_{t - 1}, \\mathbf{x}_{t}, \\mathbf{x}_{t + 1}, \\ldots, \\mathbf{x}_{d})$$\n\nAt each single time step $t$, the hidden state $\\mathbf{h}_t$ and output $\\hat{\\mathbf{y}}_t$ are calculated as follows:\n\n$$\n\\begin{aligned}\n\\mathbf{h}_t & = \\text{sigmoid}(\\mathbf{W}^h \\mathbf{h}_{t-1}+ \\mathbf{W}^x \\mathbf{x}_t) \\in \\mathbb{R}^{d_{h}}\\\\\n\\hat{\\mathbf{y}}_{t} & = \\text{softmax}(\\mathbf{W}^o \\mathbf{h}_{t}) \\in \\mathbb{R}^{|V|}\\\\\n\\end{aligned}\n$$\n\nwhere $\\mathbf{y}_{t} \\in \\mathbb{[0, 1]}^{|V|}$ is a **probability distribution** over words in $V$.\n\nThe probability that the $t$-th word in the sequence is $w_{j}$ is given by:\n\n$$p(w_{j} \\mid x_{t}, \\ldots, x_{1}) = \\hat{\\mathbf{y}}_{t, j}$$\n\n# Example\n\nConsider the word sequence $(\\text{I}, \\text{go}, \\text{home}) \\rightarrow (x_{1}, x_{2}, x_{3})$\n\nReminder: $\\mathbf{h}_t = \\text{sigmoid}(\\mathbf{W}^h \\mathbf{h}_{t-1}+ \\mathbf{W}^x \\mathbf{x}_t + \\mathbf{b})$\n\n$$\n\\begin{aligned}\n\\mathbf{h}_1 = \\text{sigmoid}(\\mathbf{W}^h \\mathbf{h}_{0} + \\mathbf{W}^x \\mathbf{x}_1) &\\;& \\hat{\\mathbf{y}}_{1} = \\text{softmax}(\\mathbf{W}^o \\mathbf{h}_{1}) \\\\\n\\mathbf{h}_2 = \\text{sigmoid}(\\mathbf{W}^h \\mathbf{h}_{1} + \\mathbf{W}^x \\mathbf{x}_2) &\\;& \\hat{\\mathbf{y}}_{2} = \\text{softmax}(\\mathbf{W}^o \\mathbf{h}_{2}) \\\\\n\\mathbf{h}_3 = \\text{sigmoid}(\\mathbf{W}^h \\mathbf{h}_{2} + \\mathbf{W}^x \\mathbf{x}_3) &\\;& \\hat{\\mathbf{y}}_{3} = \\text{softmax}(\\mathbf{W}^o \\mathbf{h}_{3}) \\\\\n\\end{aligned}\n$$\n\n$$p(\\text{I}, \\text{go}, \\text{home}) = \\hat{\\mathbf{y}}_{1, [\\text{I}]} \\; \\hat{\\mathbf{y}}_{2, [\\text{go}]} \\; \\hat{\\mathbf{y}}_{3, [\\text{home}]}$$\n\n- Initial state: $\\mathbf{h}_{0} \\in \\mathbb{R}^{d_{h}}$\n- Input matrix: $\\mathbf{W}^x \\in \\mathbb{R}^{d_{h} \\times d_{x}}$\n- Transition matrix: $\\mathbf{W}^h \\in \\mathbb{R}^{d_{h} \\times d_{h}}$\n- Output matrix: $\\mathbf{W}^o \\in \\mathbb{R}^{|V| \\times d_{h}}$\n\n# Recurrent Neural Networks\n\n\n```python\n%%tikz -l arrows -s 1000,400 -sc 0.65\n\n\\newcommand{\\lstm}{\n\\definecolor{nice-red}{HTML}{E41A1C}\n\\definecolor{nice-orange}{HTML}{FF7F00}\n\\definecolor{nice-yellow}{HTML}{FFC020}\n\\definecolor{nice-green}{HTML}{4DAF4A}\n\\definecolor{nice-blue}{HTML}{377EB8}\n\\definecolor{nice-purple}{HTML}{984EA3}\n\n%lstm first step\n\n%lstm module box\n\\draw[line width=3pt, color=black!50] (0,0) rectangle (3,3);\n}\n\n\\lstm    \n\\node[] at (0.5,-1.25) {$\\mathbf{x}_t$};\n\\node[] at (-1.5,2) {$\\mathbf{h}_{t-1}$};\n\\node[] at (4.25,2) {$\\mathbf{h}_t$};\n\\node[] at (2.5,5) {$\\mathbf{h}_t$};\n\n\\draw[ultra thick, ->, >=stealth'] (0.5,-0.75) -- (0.5,0);\n\\draw[ultra thick, ->, >=stealth'] (-0.75,2) -- (0,2);      \n\\draw[ultra thick, ->, >=stealth'] (3,2) -- (3.75,2); \n\\draw[ultra thick, ->, >=stealth'] (2.5,3) -- (2.5,4.75);      \n\n\\path[line width=3pt, ->, >=stealth', color=nice-red] (4, 2.5) edge[bend right=0, in=-110, out=-70] (-1.75, 2.5);      \n      \n\\node[] at (1.5,2) {$f_\\theta(\\mathbf{x}_t, \\mathbf{h}_{t-1})$};\n\n```\n\n<div class=right><div class=top><div class=small>\n<div style=\"margin-bottom: 40%;\"></div>\n\\begin{align}\n\\mathbf{h}_t &= f_{\\theta}(\\mathbf{x}_{t}, \\mathbf{h}_{t - 1}) \\\\\n    f_{\\theta} \\; & \\text{is a } \\textbf{transition function} \\text { with parameters } \\theta\\\\\n    \\theta \\; & \\text{can be } \\textbf{learned from data}\\\\\n\\\\\n\\\\\n& \\text{Remind - Simple Recurrent Neural Network} \\\\\n\\mathbf{h}_t &= \\text{sigmoid}(\\mathbf{W}^h \\mathbf{h}_{t-1}+ \\mathbf{W}^x \\mathbf{x}_t)\n\\end{align}\n</div></div></div>\n\n# Objective Function\n\nRecall that $\\mathbf{y}_{t} \\in \\mathbb{R}^{|V|}$ is a probability distribution over the vocabulary $V$.\n\nWe can train a RNN by minimizing the **cross-entropy loss**, predicting **words** instead of classes:\n\n$$\n\\begin{aligned}\nJ_{t} = - \\sum_{i = 1}^{|V|} \\mathbf{y}_{t, i} \\log \\hat{\\mathbf{y}}_{t, i}, \\quad \\mathbf{y}_{t, i} = \\left\\{\\begin{array}{ll}1 \\; \\text{if the $t$-th word is $w_{i}$,}\\\\0 \\, \\text{otherwise.}\\end{array} \\right.\n\\end{aligned}\n$$\n\n# Evaluating Language Models\n\nEvaluation - negative of average log-probability over corpus:\n\n$$J = - \\frac{1}{T} \\sum_{t = 1}^{T} \\sum_{j = 1}^{|V|} \\mathbf{y}_{t, j} \\log \\hat{\\mathbf{y}}_{t, j} = \\frac{1}{T} J_{t}$$\n\nOr also **perplexity**:\n\n$$PP(w_1,\\ldots,w_T) = \\sqrt[T]{\\prod_{i = 1}^T \\frac{1}{p(w_i | w_{1}, \\ldots, w_{i-1})}}$$\n\n# Sequence-to-Sequence Models\n\nRecurrent Neural Networks are extremely powerful and flexible\n- They can also learn to **generate** sequences\n\nSeq2Seq models are composed by:\n- **Encoder** - Gets the input and outputs $\\mathbf{v} \\in \\mathbb{R}^{d}$\n- **Decoder** - Gets $\\mathbf{v}$ and generates the output sequence\n\nSeq2Seq models are widely popular in e.g.:\n- *Neural Machine Translation*\n- *Text Summarization*\n- *Learning to Execute*\n\n\n```python\n%%tikz -l arrows -s 1000,400 -sc 0.65\n\n\\definecolor{nice-red}{HTML}{E41A1C}\n\\definecolor{nice-orange}{HTML}{FF7F00}\n\\definecolor{nice-yellow}{HTML}{FFC020}\n\\definecolor{nice-green}{HTML}{4DAF4A}\n\\definecolor{nice-blue}{HTML}{377EB8}\n\\definecolor{nice-purple}{HTML}{984EA3}\n\n\\newcommand{\\lstm}{\n\n%lstm first step\n\n%lstm module box\n\\draw[line width=3pt, color=black!50] (0,0) rectangle (3,3);\n    \n\\draw[ultra thick, ->, >=stealth'] (0.5,-0.75) -- (0.5,0);\n\\draw[ultra thick, ->, >=stealth'] (-0.75,2) -- (0,2);      \n\\draw[ultra thick, ->, >=stealth'] (3,2) -- (3.75,2); \n\\draw[ultra thick, ->, >=stealth'] (2.5,3) -- (2.5,3.75);      \n}\n\n%\\lstm    \n      \n%\\node[] at (0.5,-1.25) {$\\mathbf{x}_t$};\n%\\node[] at (-1.5,2) {$\\mathbf{h}_{t-1}$};\n%\\node[] at (4.25,2) {$\\mathbf{h}_t$};\n%\\node[] at (2.5,5) {$\\mathbf{h}_t$};    \n%\\path[line width=3pt, ->, >=stealth', color=nice-blue] (4, 2.5) edge[bend right=0, in=-110, out=-70] (-1.75, 2.5);            \n%\\node[] at (1.5,2) {$f_\\theta(\\mathbf{x}_t, \\mathbf{h}_{t-1})$};\n\n\\foreach \\x/\\w in {0/I, 1/like, 2/neural, 3/networks} {\n    \\begin{scope}[shift={(\\x*3.75,0)}]\n        \\lstm    \n        \\node[font=\\LARGE, text height=1.5ex, color=nice-red] at (0.5,-1.5) {\\bf\\w};                                                                                    \n    \\end{scope}    \n}\n\n\\foreach \\x/\\w/\\t in {4/EOS/Ich, 5/Ich/mag, 6/mag/neuronale, 7/neuronale/Netze, 8/Netze/EOS} {\n    \\begin{scope}[shift={(\\x*3.75,0)}]\n        \\lstm    \n        \\node[font=\\LARGE, text height=1.5ex] at (0.5,-1.5) {\\bf\\w};  \n        \\node[font=\\LARGE, text height=1.5ex, color=nice-blue] at (2.5,4.5) {\\bf\\t};                                                                                                                \n    \\end{scope}    \n}       \n\n\\node[font=\\Huge, color=nice-red] at (16.5,1.5) {$\\mathbf{v}$};   \n```\n\n# Problem - Training RNNs is Hard\n\n- **Vanishing** and **exploding** gradients [<span class=blue>Pascanu et al. 2013</span>].\n\nWhy? Multiply the same matrix $\\mathbf{W}^{h}$ at each time step during forward propagation. The norm of the gradient might either tend to 0 (**vanish**) or be too large (**explode**).\n\n<center>\n\n</center>\n\n# Related Problem - Long-Term Dependencies\n\nWords from time steps far away are hardly considered when training to predict the next word.\n\nExample:\n- John walked to the hallway.\n- Mary walked in too.\n- Daniel moved to the garden.\n- John said \"Hi\" to \\_\\_\\_\\_.\n\nA RNN is very likely to e.g. put an uniform probability distributions over nouns in $V$, and a low probability everywhere else.\n\nIt's an issue with language modeling, question answering, and many other tasks.\n\n# Vanishing/Exploding Gradients - Solutions\n\nSeveral solutions in the literature:\n\n- Bound the gradient to a threshold (**Gradient Clipping**)<br>[<span class=blue>Pascanu et al. 2013</span>]\n\n- Use $\\text{ReLU}(x) = \\max(0, x)$ (**Re**ctified **L**inear **U**nits) or similar non-linearities instead of $\\text{sigmoid}(x)$ or $\\text{tanh}(x)$<br>[<span class=blue>Glorot et al. 2011</span>].\n\n- Clever Initialization of the Transition Matrix ($\\mathbf{W}^h = \\mathbf{I}$)<br>[<span class=blue>Socher et al. 2013</span>, <span class=blue>Le et al. 2015</span>].\n\n- Use different recurrent models that favour backpropagation<br>LSTM[<span class=blue>Hochreiter et al. 1997</span>], GRU[<span class=blue>Chung et al. 2014</span>].\n\n# Long Short-Term Memory (LSTM) Networks\n\n- Can adaptively learn what to **keep** (store) into memory (gate $\\mathbf{i}_{t}$), **forget** (gate $\\mathbf{f}_{t}$) and **output** (gate $\\mathbf{o}_{t}$)\n\n\n```python\n%%tikz -l arrows -s 1000,400 -sc 0.65\n\n\\newcommand{\\lstm}{\n\\definecolor{nice-red}{HTML}{E41A1C}\n\\definecolor{nice-orange}{HTML}{FF7F00}\n\\definecolor{nice-yellow}{HTML}{FFC020}\n\\definecolor{nice-green}{HTML}{4DAF4A}\n\\definecolor{nice-blue}{HTML}{377EB8}\n\\definecolor{nice-purple}{HTML}{984EA3}\n\n%lstm first step\n\n%lstm module box\n\\draw[line width=3pt, color=black!50] (-6,-3) rectangle (1.5,5.25);\n\\draw[ultra thick] (0,0) rectangle (1,2);\n\n%memory ct\n\\draw[ultra thick, color=nice-purple, fill=nice-purple!10] (0,0) rectangle (1,2);\n\n%non-linearities\n\\foreach \\w/\\h/\\color in {-2/4.25/nice-blue,-2/1/nice-red,-2/-1/nice-green,0.5/-2/nice-yellow,0.5/3/black} {\n    \\begin{scope}[shift={(\\w,\\h)},scale=0.5]\n        \\draw[ultra thick, yshift=-0.5cm, color=\\color] plot [domain=-0.3:0.3](\\x, {(0.8/(1+exp(-15*\\x))+0.1)});\n        \\draw[ultra thick, color=\\color] (0,0) circle (0.5cm);\n    \\end{scope}\n}\n\n%tanh\n\\draw[thick, color=black] (0.25,3) -- (0.75,3);\n\\draw[thick, color=nice-yellow] (0.25,-2) -- (0.75,-2);\n    \n    \n%component-wise multiplications\n\\foreach \\w/\\h in {-1/1,0.5/-1,0.5/4.25} {\n    \\begin{scope}[shift={(\\w,\\h)},scale=0.5]\n        \\draw[ultra thick, color=black] (0,0) circle (0.05cm);\n        \\draw[ultra thick, color=black] (0,0) circle (0.5cm);\n    \\end{scope}\n}\n\n%vector concat\n\\begin{scope}[shift={(-4,1)},scale=0.5]\n    \\draw[ultra thick,yshift=0.2cm] (0,0) circle (0.05cm);\n    \\draw[ultra thick,yshift=-0.2cm] (0,0) circle (0.05cm);\n    \\draw[ultra thick] (0,0) circle (0.5cm);\n\\end{scope}\n\n\n\\foreach \\fx/\\fy/\\tx/\\ty in {\n    -5/-3.5/-5/0.85, %xt\n    -5/0.85/-4.2/0.85,\n    -6.5/4.25/-5/4.25, %ht1\n    -5/4.25/-5/1.15,\n    -5/1.15/-4.2/1.15,\n    -3.75/1/-3/1, %H\n    -3/4.25/-3/-2,\n    -3/-2/0.25/-2, %i\n    0.5/-1.75/0.5/-1.25,\n    -3/-1/-2.25/-1, %it\n    -1.75/-1/0.25/-1,\n    -3/1/-2.25/1, %ft\n    -1.75/1/-1.25/1,\n    -0.75/1/0/1,\n    -3/4.25/-2.25/4.25, %ot\n    -1.75/4.25/0.25/4.25,\n    0.5/2/0.5/2.75, %ct\n    -5.5/2/-5.1/2, %ct1\n    -5.5/2/-5.5/1,\n    -6.5/1/-5.5/1,\n    -4.9/2/-3.1/2,\n    -2.9/2/-1/2,\n    -1/2/-1/1.25   \n} {\n    \\draw[ultra thick] (\\fx,\\fy) -- (\\tx,\\ty);\n}\n\n\\foreach \\fx/\\fy/\\tx/\\ty in {\n    0.5/-0.75/0.5/0, %it\n    -0.75/1/0/1, %ft\n    1/1/2.25/1,\n    0.5/3.25/0.5/4,\n    0.75/4.25/2.25/4.25, %ht    \n    0.5/4.5/0.5/6    \n} {\n    \\draw[->, >=stealth', ultra thick] (\\fx,\\fy) -- (\\tx,\\ty);\n}\n}\n\n%\\begin{scope}[scale=0.8]                    \n%\\foreach \\d in {0,1} {                    \n%\\foreach \\t in {0,1,2,3,4} {          \n%\\begin{scope}[shift={(\\t*8.5+\\d*5.5,\\d*9.5)}]          \n%    \\lstm\n%\\end{scope}   \n%}\n%}\n%\\end{scope}          \n\n          \n\\lstm \n          \n%annotations\n\\node[] at (-5,-3.75) {$\\mathbf{x}_t$};\n\\node[anchor=east] at (-6.5,4.25) {$\\mathbf{h}_{t-1}$};\n\\node[anchor=east] at (-6.5,1) {$\\mathbf{c}_{t-1}$};\n\\node[] at (0.5,6.25) {$\\mathbf{h}_t$};\n\\node[anchor=west] at (2.25,4.25) {$\\mathbf{h}_t$};\n\\node[anchor=west] at (2.25,1) {$\\mathbf{c}_t$};          \n\\node[xshift=0.4cm,yshift=0.25cm] at (-4,1) {$\\mathbf{H}_t$};\n\\node[xshift=0.35cm,yshift=0.25cm] at (-2,-1) {$\\mathbf{i}_t$};\n\\node[xshift=0.35cm,yshift=0.25cm] at (-2,1) {$\\mathbf{f}_t$};\n\\node[xshift=0.35cm,yshift=0.25cm] at (-2,4.25) {$\\mathbf{o}_t$};     \n          \n%dummy node for left alignment\n\\node[] at (17,0) {};          \n```\n\n<div class=right><div class=top><div class=small>\n<div style=\"margin-bottom: 40%;\"></div>\n\\begin{align}\n\\\\\n\\mathbf{H}_t &= \\left[\n \\begin{array}{*{20}c}\n        \\mathbf{x}_t \\\\\n        \\mathbf{h}_{t-1}\n      \\end{array}\n\\right]\\\\\n\\mathbf{i}_t &= \\text{sigmoid}(\\mathbf{W}^i\\mathbf{H}+\\mathbf{b}^i)\\\\\n\\mathbf{f}_t &= \\text{sigmoid}(\\mathbf{W}^f\\mathbf{H}+\\mathbf{b}^f)\\\\\n\\mathbf{o}_t &= \\text{sigmoid}(\\mathbf{W}^o\\mathbf{H}+\\mathbf{b}^o)\\\\\n\\mathbf{c}_t &= \\mathbf{f}_t \\odot \\mathbf{c}_{t-1} + \\mathbf{i}_t \\odot \\tanh(\\mathbf{W}^c\\mathbf{H}+\\mathbf{b}^c)\\\\\n\\mathbf{h}_t &= \\mathbf{o}_t \\odot \\tanh(\\mathbf{c}_t)\n\\end{align}\n</div></div></div>\n\n# Sentence Encoding\n\n\n```python\n%%tikz -l arrows -s 1000,400 -sc 0.65\n\n\\newcommand{\\lstm}{\n\\definecolor{nice-red}{HTML}{E41A1C}\n\\definecolor{nice-orange}{HTML}{FF7F00}\n\\definecolor{nice-yellow}{HTML}{FFC020}\n\\definecolor{nice-green}{HTML}{4DAF4A}\n\\definecolor{nice-blue}{HTML}{377EB8}\n\\definecolor{nice-purple}{HTML}{984EA3}\n\n%lstm first step\n\n%lstm module box\n\\draw[line width=3pt, color=black!50] (-6,-3) rectangle (1.5,5.25);\n\\draw[ultra thick] (0,0) rectangle (1,2);\n\n%memory ct\n\\draw[ultra thick, color=nice-purple, fill=nice-purple!10] (0,0) rectangle (1,2);\n\n%non-linearities\n\\foreach \\w/\\h/\\color in {-2/4.25/nice-blue,-2/1/nice-red,-2/-1/nice-green,0.5/-2/nice-yellow,0.5/3/black} {\n    \\begin{scope}[shift={(\\w,\\h)},scale=0.5]\n        \\draw[ultra thick, yshift=-0.5cm, color=\\color] plot [domain=-0.3:0.3](\\x, {(0.8/(1+exp(-15*\\x))+0.1)});\n        \\draw[ultra thick, color=\\color] (0,0) circle (0.5cm);\n    \\end{scope}\n}\n\n%tanh\n\\draw[thick, color=black] (0.25,3) -- (0.75,3);\n\\draw[thick, color=nice-yellow] (0.25,-2) -- (0.75,-2);\n    \n    \n%component-wise multiplications\n\\foreach \\w/\\h in {-1/1,0.5/-1,0.5/4.25} {\n    \\begin{scope}[shift={(\\w,\\h)},scale=0.5]\n        \\draw[ultra thick, color=black] (0,0) circle (0.05cm);\n        \\draw[ultra thick, color=black] (0,0) circle (0.5cm);\n    \\end{scope}\n}\n\n%vector concat\n\\begin{scope}[shift={(-4,1)},scale=0.5]\n    \\draw[ultra thick,yshift=0.2cm] (0,0) circle (0.05cm);\n    \\draw[ultra thick,yshift=-0.2cm] (0,0) circle (0.05cm);\n    \\draw[ultra thick] (0,0) circle (0.5cm);\n\\end{scope}\n\n\n\\foreach \\fx/\\fy/\\tx/\\ty in {\n    -5/-3.5/-5/0.85, %xt\n    -5/0.85/-4.2/0.85,\n    -6.5/4.25/-5/4.25, %ht1\n    -5/4.25/-5/1.15,\n    -5/1.15/-4.2/1.15,\n    -3.75/1/-3/1, %H\n    -3/4.25/-3/-2,\n    -3/-2/0.25/-2, %i\n    0.5/-1.75/0.5/-1.25,\n    -3/-1/-2.25/-1, %it\n    -1.75/-1/0.25/-1,\n    -3/1/-2.25/1, %ft\n    -1.75/1/-1.25/1,\n    -0.75/1/0/1,\n    -3/4.25/-2.25/4.25, %ot\n    -1.75/4.25/0.25/4.25,\n    0.5/2/0.5/2.75, %ct\n    -5.5/2/-5.1/2, %ct1\n    -5.5/2/-5.5/1,\n    -6.5/1/-5.5/1,\n    -4.9/2/-3.1/2,\n    -2.9/2/-1/2,\n    -1/2/-1/1.25   \n} {\n    \\draw[ultra thick] (\\fx,\\fy) -- (\\tx,\\ty);\n}\n\n\\foreach \\fx/\\fy/\\tx/\\ty in {\n    0.5/-0.75/0.5/0, %it\n    -0.75/1/0/1, %ft\n    1/1/2.25/1,\n    0.5/3.25/0.5/4,\n    0.75/4.25/2.25/4.25, %ht    \n    0.5/4.5/0.5/6    \n} {\n    \\draw[->, >=stealth', ultra thick] (\\fx,\\fy) -- (\\tx,\\ty);\n}\n}\n\n\\begin{scope}[scale=0.8]                    \n\\foreach \\d in {0} {                    \n\\foreach \\t/\\word in {0/A,1/wedding,2/party,3/taking,4/pictures} {  \n    \\node[font=\\Huge, anchor=west] at (\\t*8.5-5.75,-4.5) {$\\mathbf{v}$\\_\\word};                                                                                \n    \\begin{scope}[shift={(\\t*8.5+\\d*5.5,\\d*9.5)}]  \n        \\lstm                    \n    \\end{scope}   \n}\n}\n\\end{scope}          \n\n\\node[font=\\Huge, anchor=west] at (27,5.75) {$\\mathbf{v}$\\_Sentence};                                                                                \n          \n          \n%dummy node for left alignment\n\\node[] at (17,0) {};          \n```\n\n# Gating\n\n\n```python\n%%tikz -l arrows -s 1000,400 -sc 0.65\n\n\\definecolor{nice-red}{HTML}{E41A1C}\n\\definecolor{nice-orange}{HTML}{FF7F00}\n\\definecolor{nice-yellow}{HTML}{FFC020}\n\\definecolor{nice-green}{HTML}{4DAF4A}\n\\definecolor{nice-blue}{HTML}{377EB8}\n\\definecolor{nice-purple}{HTML}{984EA3}\n\n\\newcommand{\\lstm}{\n%lstm first step\n\n%lstm module box\n\\draw[line width=3pt, color=black!50] (-6,-3) rectangle (1.5,5.25);\n\\draw[ultra thick] (0,0) rectangle (1,2);\n\n%memory ct\n\\draw[ultra thick, color=nice-purple, fill=nice-purple!10] (0,0) rectangle (1,2);\n\n%non-linearities\n\\foreach \\w/\\h/\\color in {-2/4.25/nice-blue,-2/1/nice-red,-2/-1/nice-green,0.5/-2/nice-yellow,0.5/3/black} {\n    \\begin{scope}[shift={(\\w,\\h)},scale=0.5]\n        \\draw[ultra thick, yshift=-0.5cm, color=\\color] plot [domain=-0.3:0.3](\\x, {(0.8/(1+exp(-15*\\x))+0.1)});\n        \\draw[ultra thick, color=\\color] (0,0) circle (0.5cm);\n    \\end{scope}\n}\n\n%tanh\n\\draw[thick, color=black] (0.25,3) -- (0.75,3);\n\\draw[thick, color=nice-yellow] (0.25,-2) -- (0.75,-2);\n    \n    \n%component-wise multiplications\n\\foreach \\w/\\h in {-1/1,0.5/-1,0.5/4.25} {\n    \\begin{scope}[shift={(\\w,\\h)},scale=0.5]\n        \\draw[ultra thick, color=black] (0,0) circle (0.05cm);\n        \\draw[ultra thick, color=black] (0,0) circle (0.5cm);\n    \\end{scope}\n}\n\n%vector concat\n\\begin{scope}[shift={(-4,1)},scale=0.5]\n    \\draw[ultra thick,yshift=0.2cm] (0,0) circle (0.05cm);\n    \\draw[ultra thick,yshift=-0.2cm] (0,0) circle (0.05cm);\n    \\draw[ultra thick] (0,0) circle (0.5cm);\n\\end{scope}\n\n\n\\foreach \\fx/\\fy/\\tx/\\ty in {\n    -5/-3.5/-5/0.85, %xt\n    -5/0.85/-4.2/0.85,\n    -6.5/4.25/-5/4.25, %ht1\n    -5/4.25/-5/1.15,\n    -5/1.15/-4.2/1.15,\n    -3.75/1/-3/1, %H\n    -3/4.25/-3/-2,\n    -3/-2/0.25/-2, %i\n    0.5/-1.75/0.5/-1.25,\n    -3/-1/-2.25/-1, %it\n    -1.75/-1/0.25/-1,\n    -3/1/-2.25/1, %ft\n    -1.75/1/-1.25/1,\n    -0.75/1/0/1,\n    -3/4.25/-2.25/4.25, %ot\n    -1.75/4.25/0.25/4.25,\n    0.5/2/0.5/2.75, %ct\n    -5.5/2/-5.1/2, %ct1\n    -5.5/2/-5.5/1,\n    -6.5/1/-5.5/1,\n    -4.9/2/-3.1/2,\n    -2.9/2/-1/2,\n    -1/2/-1/1.25   \n} {\n    \\draw[ultra thick] (\\fx,\\fy) -- (\\tx,\\ty);\n}\n\n\\foreach \\fx/\\fy/\\tx/\\ty in {\n    0.5/-0.75/0.5/0, %it\n    -0.75/1/0/1, %ft\n    1/1/2.25/1,\n    0.5/3.25/0.5/4,\n    0.75/4.25/2.25/4.25, %ht    \n    0.5/4.5/0.5/6    \n} {\n    \\draw[->, >=stealth', ultra thick] (\\fx,\\fy) -- (\\tx,\\ty);\n}\n}\n\n\\begin{scope}[scale=0.8]                    \n\\foreach \\d in {0} {                    \n\\foreach \\t/\\word in {0/A,1/wedding,2/party,3/taking,4/pictures} {  \n    \\node[font=\\Huge, anchor=west] at (\\t*8.5-5.75,-4.5) {$\\mathbf{v}$\\_\\word};                                                                                \n    \\begin{scope}[shift={(\\t*8.5+\\d*5.5,\\d*9.5)}]  \n        \\lstm                    \n    \\end{scope}   \n}\n}\n\\end{scope}          \n\n\\node[font=\\Huge, anchor=west] at (27,5.75) {$\\mathbf{v}$\\_Sentence};                                                                                \n          \n\n\\draw[line width=10pt, color=nice-red, opacity=0.8] (27.6,5) -- (27.6,0.75);\n\\draw[line width=10pt, color=nice-red, opacity=0.8] (27.5,0.75) -- (3,0.75);\n\\draw[->, >=stealth', line width=10pt, color=nice-red, opacity=0.8] (2.75,0.75) -- (2.75,-3);\n          \n          \n%dummy node for left alignment\n\\node[] at (17,0) {};          \n```\n\n# Visualizing Gradients\n\nRNN vs. LSTM gradients on the input matrix $\\mathbf{W}^x$\n\n- Error is generated at 128th step and propagated back, no error from other steps.\n\n\n```python\n%%html\n\n<center>\n\n</center>\n```\n\n\n\n<center>\n\n</center>\n\n\n# Stacking (Deep LSTMs)\n\n\n```python\n%%tikz -l arrows -s 1100,500 -sc 0.65\n\n\\definecolor{nice-red}{HTML}{E41A1C}\n\\definecolor{nice-orange}{HTML}{FF7F00}\n\\definecolor{nice-yellow}{HTML}{FFC020}\n\\definecolor{nice-green}{HTML}{4DAF4A}\n\\definecolor{nice-blue}{HTML}{377EB8}\n\\definecolor{nice-purple}{HTML}{984EA3}\n\n\\newcommand{\\lstm}{\n%lstm first step\n\n%lstm module box\n\\draw[line width=3pt, color=black!50] (-6,-3) rectangle (1.5,5.25);\n\\draw[ultra thick] (0,0) rectangle (1,2);\n\n%memory ct\n\\draw[ultra thick, color=nice-purple, fill=nice-purple!10] (0,0) rectangle (1,2);\n\n%non-linearities\n\\foreach \\w/\\h/\\color in {-2/4.25/nice-blue,-2/1/nice-red,-2/-1/nice-green,0.5/-2/nice-yellow,0.5/3/black} {\n    \\begin{scope}[shift={(\\w,\\h)},scale=0.5]\n        \\draw[ultra thick, yshift=-0.5cm, color=\\color] plot [domain=-0.3:0.3](\\x, {(0.8/(1+exp(-15*\\x))+0.1)});\n        \\draw[ultra thick, color=\\color] (0,0) circle (0.5cm);\n    \\end{scope}\n}\n\n%tanh\n\\draw[thick, color=black] (0.25,3) -- (0.75,3);\n\\draw[thick, color=nice-yellow] (0.25,-2) -- (0.75,-2);\n    \n    \n%component-wise multiplications\n\\foreach \\w/\\h in {-1/1,0.5/-1,0.5/4.25} {\n    \\begin{scope}[shift={(\\w,\\h)},scale=0.5]\n        \\draw[ultra thick, color=black] (0,0) circle (0.05cm);\n        \\draw[ultra thick, color=black] (0,0) circle (0.5cm);\n    \\end{scope}\n}\n\n%vector concat\n\\begin{scope}[shift={(-4,1)},scale=0.5]\n    \\draw[ultra thick,yshift=0.2cm] (0,0) circle (0.05cm);\n    \\draw[ultra thick,yshift=-0.2cm] (0,0) circle (0.05cm);\n    \\draw[ultra thick] (0,0) circle (0.5cm);\n\\end{scope}\n\n\n\\foreach \\fx/\\fy/\\tx/\\ty in {\n    -5/-3.5/-5/0.85, %xt\n    -5/0.85/-4.2/0.85,\n    -6.5/4.25/-5/4.25, %ht1\n    -5/4.25/-5/1.15,\n    -5/1.15/-4.2/1.15,\n    -3.75/1/-3/1, %H\n    -3/4.25/-3/-2,\n    -3/-2/0.25/-2, %i\n    0.5/-1.75/0.5/-1.25,\n    -3/-1/-2.25/-1, %it\n    -1.75/-1/0.25/-1,\n    -3/1/-2.25/1, %ft\n    -1.75/1/-1.25/1,\n    -0.75/1/0/1,\n    -3/4.25/-2.25/4.25, %ot\n    -1.75/4.25/0.25/4.25,\n    0.5/2/0.5/2.75, %ct\n    -5.5/2/-5.1/2, %ct1\n    -5.5/2/-5.5/1,\n    -6.5/1/-5.5/1,\n    -4.9/2/-3.1/2,\n    -2.9/2/-1/2,\n    -1/2/-1/1.25   \n} {\n    \\draw[ultra thick] (\\fx,\\fy) -- (\\tx,\\ty);\n}\n\n\\foreach \\fx/\\fy/\\tx/\\ty in {\n    0.5/-0.75/0.5/0, %it\n    -0.75/1/0/1, %ft\n    1/1/2.25/1,\n    0.5/3.25/0.5/4,\n    0.75/4.25/2.25/4.25, %ht    \n    0.5/4.5/0.5/6    \n} {\n    \\draw[->, >=stealth', ultra thick] (\\fx,\\fy) -- (\\tx,\\ty);\n}\n}\n\n\\begin{scope}[scale=0.8]                    \n\\foreach \\d in {0,1,2} {                    \n\\foreach \\t/\\word in {0/A,1/wedding,2/party,3/taking,4/pictures} {  \n    \\node[font=\\Huge, anchor=west] at (\\t*8.5-5.75,-4.5) {$\\mathbf{v}$\\_\\word};                                                                                \n    \\begin{scope}[shift={(\\t*8.5+\\d*5.5,\\d*9.5)}]  \n        \\lstm                    \n    \\end{scope}   \n}\n}\n\\end{scope}          \n\n\\node[font=\\Huge, anchor=west] at (34,20.75) {$\\mathbf{v}$\\_Sentence};                                                                                \n\n\\draw[line width=10pt, color=nice-red, opacity=0.8] (36.4,16) -- (36.4,20);                    \n\\draw[line width=10pt, color=nice-red, opacity=0.8] (25.25,16) -- (36.5,16);          \n\\draw[line width=10pt, color=nice-red, opacity=0.8] (25.25,8.5) -- (25.25,16);          \n\\draw[line width=10pt, color=nice-red, opacity=0.8] (14,8.5) -- (25.25,8.5);\n\\draw[line width=10pt, color=nice-red, opacity=0.8] (14,8.5) -- (14,0.75);\n\\draw[line width=10pt, color=nice-red, opacity=0.8] (14,0.75) -- (3,0.75);\n\\draw[->, >=stealth', line width=10pt, color=nice-red, opacity=0.8] (2.75,0.75) -- (2.75,-3);\n          \n          \n%dummy node for left alignment\n\\node[] at (17,0) {};          \n```\n\n# Applications\n- Language Modeling\n- Machine Translation\n- Question Answering\n- Dialog Modeling\n- Language Generation\n- Sentence Summarization\n- Paraphrasing\n- Sentiment Analysis\n- Recognizing Textual Entailment\n- ...\n\n# Learning to Execute\n\nRNNs are **Turing-Complete** [<span class=blue>Siegelman, 1995</span>] - they can simulate arbitrary programs, given the proper parameters.\n\nLearning to Execute [<span class=blue>Zaremba and Sutskever, 2014</span>]\n\n\n\n\n# Implementing LSTM (TensorFlow)\n\n```python\nlstm = rnn_cell.BasicLSTMCell(lstm_size)\n# Initial state of the LSTM memory.\nstate = tf.zeros([batch_size, lstm.state_size])\nprobabilities = []\nloss_val = 0.0\nfor batch_of_words in words_in_dataset:\n  # State is updated after processing each batch\n  output, state = lstm(batch_of_words, state)\n  # Output is used to make next word predictions\n  scores = tf.matmul(output, out_w) + out_b\n  probabilities.append(tf.nn.softmax(scores))\n  loss_val += loss(probabilities, target_words)\n```\n\n- Pay attention to **batching**, **bucketization** and **padding**\n\n# Levels of Granularity\n\nChar-Level Language Models: Char-RNN - see e.g. [<span class=blue>Karpathy, 2015</span>]\n\n<center>\n  \n</center>\n\n# Neural \"Lego Blocks\"\n\nWe can combine models! Example: Show and Tell [<span class=blue>Vinyals, 2015</span>]\n\n<center>\n  \n</center>\n\n# Bidirectional RNNs\n\nProblem - for word classification, you may need to incorporate information from both the **left** and **right** contexts of the word.\n\n<div align=\"left\" class=left>\n\n</div>\n\n<div class=right><div class=top>\n\\begin{align}\n\\\\\n\\\\\n\\\\\n\\\\\n\\\\\n\\\\\n\\overleftarrow{\\mathbf{h}}_t &= f_{\\overleftarrow{\\theta}}(\\mathbf{x}_t, \\overleftarrow{\\mathbf{h}}_{t-1})\\\\\n\\overrightarrow{\\mathbf{h}}_t &= f_{\\overrightarrow{\\theta}}(\\mathbf{x}_t, \\overrightarrow{\\mathbf{h}}_{t+1})\\\\\n\\hat{\\mathbf{y}}_t & = g(\\overleftarrow{\\mathbf{h}}_t, \\overrightarrow{\\mathbf{h}}_t)\n\\end{align}\n</div></div></div>\n\n- $\\overleftarrow{\\mathbf{h}}_t$ and $\\overrightarrow{\\mathbf{h}}_t$ represent (summarize) both the **past** and the **future** around a given sequence element.\n\n\n```python\n\n```\n", "meta": {"hexsha": "6a8a4fe9328e20a6ff051d7b971e9ed7d34b87ba", "size": 893588, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Recurrent_Neural_Networks.ipynb", "max_stars_repo_name": "pminervini/rnn-slides", "max_stars_repo_head_hexsha": "f7b601c2768618478001970201c083fc0af28170", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-12-06T23:43:50.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-17T09:27:09.000Z", "max_issues_repo_path": "Recurrent_Neural_Networks.ipynb", "max_issues_repo_name": "pminervini/rnn-slides", "max_issues_repo_head_hexsha": "f7b601c2768618478001970201c083fc0af28170", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Recurrent_Neural_Networks.ipynb", "max_forks_repo_name": "pminervini/rnn-slides", "max_forks_repo_head_hexsha": "f7b601c2768618478001970201c083fc0af28170", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 535.4032354703, "max_line_length": 306397, "alphanum_fraction": 0.9210452692, "converted": true, "num_tokens": 12331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07585817584273653, "lm_q2_score": 0.08632347306042909, "lm_q1q2_score": 0.00654834119877376}}
{"text": "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Setup\" data-toc-modified-id=\"Setup-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Setup</a></span></li><li><span><a href=\"#Information-Retrieval\" data-toc-modified-id=\"Information-Retrieval-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Information Retrieval</a></span><ul class=\"toc-item\"><li><ul class=\"toc-item\"><li><span><a href=\"#Practical-Example\" data-toc-modified-id=\"Practical-Example-2.0.1\"><span class=\"toc-item-num\">2.0.1&nbsp;&nbsp;</span>Practical Example</a></span></li><li><span><a href=\"#Boolean-Search-Queries\" data-toc-modified-id=\"Boolean-Search-Queries-2.0.2\"><span class=\"toc-item-num\">2.0.2&nbsp;&nbsp;</span>Boolean Search Queries</a></span></li><li><span><a href=\"#Examples-of-Documents-That-Would-Satisfy-the-Above-Document-Term-Matrix\" data-toc-modified-id=\"Examples-of-Documents-That-Would-Satisfy-the-Above-Document-Term-Matrix-2.0.3\"><span class=\"toc-item-num\">2.0.3&nbsp;&nbsp;</span>Examples of Documents That Would Satisfy the Above Document-Term Matrix</a></span><ul class=\"toc-item\"><li><span><a href=\"#Query-Example-(nuclear-AND-treaty)\" data-toc-modified-id=\"Query-Example-(nuclear-AND-treaty)-2.0.3.1\"><span class=\"toc-item-num\">2.0.3.1&nbsp;&nbsp;</span>Query Example <code>(nuclear AND treaty)</code></a></span></li><li><span><a href=\"#Query-Example-(nuclear-AND-treaty)-OR-((NOT-treaty)-AND-(nonproliferation-OR-Iran))\" data-toc-modified-id=\"Query-Example-(nuclear-AND-treaty)-OR-((NOT-treaty)-AND-(nonproliferation-OR-Iran))-2.0.3.2\"><span class=\"toc-item-num\">2.0.3.2&nbsp;&nbsp;</span>Query Example <code>(nuclear AND treaty) OR ((NOT treaty) AND (nonproliferation OR Iran))</code></a></span></li></ul></li></ul></li></ul></li><li><span><a href=\"#Tokenizing-Sentences\" data-toc-modified-id=\"Tokenizing-Sentences-3\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>Tokenizing Sentences</a></span><ul class=\"toc-item\"><li><span><a href=\"#Definition-of-a-Token\" data-toc-modified-id=\"Definition-of-a-Token-3.1\"><span class=\"toc-item-num\">3.1&nbsp;&nbsp;</span>Definition of a Token</a></span></li><li><span><a href=\"#Examples-of-Tokens/Words-Not-Being-the-Identical-Concepts\" data-toc-modified-id=\"Examples-of-Tokens/Words-Not-Being-the-Identical-Concepts-3.2\"><span class=\"toc-item-num\">3.2&nbsp;&nbsp;</span>Examples of Tokens/Words Not Being the Identical Concepts</a></span></li><li><span><a href=\"#Definition-of-a-Document\" data-toc-modified-id=\"Definition-of-a-Document-3.3\"><span class=\"toc-item-num\">3.3&nbsp;&nbsp;</span>Definition of a Document</a></span></li><li><span><a href=\"#Why-Is-Tokenization-Hard?\" data-toc-modified-id=\"Why-Is-Tokenization-Hard?-3.4\"><span class=\"toc-item-num\">3.4&nbsp;&nbsp;</span>Why Is Tokenization Hard?</a></span><ul class=\"toc-item\"><li><span><a href=\"#Sentence-Boundary-Detection\" data-toc-modified-id=\"Sentence-Boundary-Detection-3.4.1\"><span class=\"toc-item-num\">3.4.1&nbsp;&nbsp;</span>Sentence Boundary Detection</a></span></li><li><span><a href=\"#Approaches-to-Sentence-Boundary-Detection\" data-toc-modified-id=\"Approaches-to-Sentence-Boundary-Detection-3.4.2\"><span class=\"toc-item-num\">3.4.2&nbsp;&nbsp;</span>Approaches to Sentence Boundary Detection</a></span><ul class=\"toc-item\"><li><span><a href=\"#Rules-Based\" data-toc-modified-id=\"Rules-Based-3.4.2.1\"><span class=\"toc-item-num\">3.4.2.1&nbsp;&nbsp;</span>Rules-Based</a></span></li><li><span><a href=\"#Supervised/Unsupervised-Learning\" data-toc-modified-id=\"Supervised/Unsupervised-Learning-3.4.2.2\"><span class=\"toc-item-num\">3.4.2.2&nbsp;&nbsp;</span>Supervised/Unsupervised Learning</a></span></li></ul></li><li><span><a href=\"#NLTK's-PunktSentenceTokenizer\" data-toc-modified-id=\"NLTK's-PunktSentenceTokenizer-3.4.3\"><span class=\"toc-item-num\">3.4.3&nbsp;&nbsp;</span>NLTK's <code>PunktSentenceTokenizer</code></a></span></li></ul></li><li><span><a href=\"#Stemming\" data-toc-modified-id=\"Stemming-3.5\"><span class=\"toc-item-num\">3.5&nbsp;&nbsp;</span>Stemming</a></span></li><li><span><a href=\"#Lemmatization\" data-toc-modified-id=\"Lemmatization-3.6\"><span class=\"toc-item-num\">3.6&nbsp;&nbsp;</span>Lemmatization</a></span><ul class=\"toc-item\"><li><span><a href=\"#Why-Stemming?\" data-toc-modified-id=\"Why-Stemming?-3.6.1\"><span class=\"toc-item-num\">3.6.1&nbsp;&nbsp;</span>Why Stemming?</a></span></li><li><span><a href=\"#Differences-Between-Stemming-and-Lemmatization\" data-toc-modified-id=\"Differences-Between-Stemming-and-Lemmatization-3.6.2\"><span class=\"toc-item-num\">3.6.2&nbsp;&nbsp;</span>Differences Between Stemming and Lemmatization</a></span></li></ul></li><li><span><a href=\"#Scoring-Metrics\" data-toc-modified-id=\"Scoring-Metrics-3.7\"><span class=\"toc-item-num\">3.7&nbsp;&nbsp;</span>Scoring Metrics</a></span><ul class=\"toc-item\"><li><span><a href=\"#Precision/Recall\" data-toc-modified-id=\"Precision/Recall-3.7.1\"><span class=\"toc-item-num\">3.7.1&nbsp;&nbsp;</span>Precision/Recall</a></span></li><li><span><a href=\"#F1-Score\" data-toc-modified-id=\"F1-Score-3.7.2\"><span class=\"toc-item-num\">3.7.2&nbsp;&nbsp;</span>F1 Score</a></span></li><li><span><a href=\"#Exercises\" data-toc-modified-id=\"Exercises-3.7.3\"><span class=\"toc-item-num\">3.7.3&nbsp;&nbsp;</span>Exercises</a></span></li></ul></li><li><span><a href=\"#Removing-Stopwords\" data-toc-modified-id=\"Removing-Stopwords-3.8\"><span class=\"toc-item-num\">3.8&nbsp;&nbsp;</span>Removing Stopwords</a></span><ul class=\"toc-item\"><li><span><a href=\"#When-Should-You-Avoid-Removing-Stopwords?\" data-toc-modified-id=\"When-Should-You-Avoid-Removing-Stopwords?-3.8.1\"><span class=\"toc-item-num\">3.8.1&nbsp;&nbsp;</span>When Should You Avoid Removing Stopwords?</a></span></li></ul></li><li><span><a href=\"#Exercises\" data-toc-modified-id=\"Exercises-3.9\"><span class=\"toc-item-num\">3.9&nbsp;&nbsp;</span>Exercises</a></span></li></ul></li><li><span><a href=\"#Vectorization-Techniques\" data-toc-modified-id=\"Vectorization-Techniques-4\"><span class=\"toc-item-num\">4&nbsp;&nbsp;</span>Vectorization Techniques</a></span><ul class=\"toc-item\"><li><span><a href=\"#Count-Vectorization\" data-toc-modified-id=\"Count-Vectorization-4.1\"><span class=\"toc-item-num\">4.1&nbsp;&nbsp;</span>Count Vectorization</a></span></li></ul></li></ul></div>\n\n# Setup\n\nYou'll need to download/install `nltk`, and then also download several of `nltk`'s modules.\n\n\n```python\n!pip install nltk\n```\n\n    Requirement already satisfied: nltk in c:\\users\\ballwang\\anaconda3.3\\lib\\site-packages (3.4.5)\n    Requirement already satisfied: six in c:\\users\\ballwang\\anaconda3.3\\lib\\site-packages (from nltk) (1.14.0)\n\n\n\n```python\nimport nltk\nnltk.download('punkt') # A popular NLTK sentence tokenizer\nnltk.download('stopwords') # library of common English stopwords\n```\n\n    [nltk_data] Downloading package punkt to\n    [nltk_data]     C:\\Users\\ballwang\\AppData\\Roaming\\nltk_data...\n    [nltk_data]   Unzipping tokenizers\\punkt.zip.\n    [nltk_data] Downloading package stopwords to\n    [nltk_data]     C:\\Users\\ballwang\\AppData\\Roaming\\nltk_data...\n    [nltk_data]   Unzipping corpora\\stopwords.zip.\n\n\n\n\n\n    True\n\n\n\n# Information Retrieval\n\n> **Information retrieval (IR)** is finding material (usually documents) of an unstructured nature (usually text) that **satisfies an information need** from within large collections (usually stored on computers).\n\n### Practical Example\n\nA mobile app contains a gallery of about **8,000** pieces of artwork that they'd like to sell to users. Each artwork contains artwork name, artist name, and some descriptions + keywords. Produce a search algorithm that will allow users to enter in a string text and return relevant pieces of artwork.\n\n### Boolean Search Queries\n\nExample of a **document-term matrix**, from [Northeastern University, Fall 2006 Information Retrieval](http://www.ccs.neu.edu/home/jaa/CSG339.06F/Lectures/boolean.pdf):\n\n\n\n### Examples of Documents That Would Satisfy the Above Document-Term Matrix\n\n* **Document 1**\n\n\"The new cookbook was a huge hit with younger millenials.\"\n* **Document 2**\n\n\"Iran has significant nuclear production capabilities.\"\n* **Document 3**\n\n\"The treaty that ended the American Revolution was signed soon thereafter.\"\n\n#### Query Example `(nuclear AND treaty)`\n\n`D7` would get returned since it is the only document that contains both `nuclear` and `treaty`.\n\n#### Query Example `(nuclear AND treaty) OR ((NOT treaty) AND (nonproliferation OR Iran))`\n\n* `D7`: satisfies LHS (left-hand side of expression) - contains `nuclear` and `treaty`\n* `D5`: satisfied RHS - contains `nonproliferation` and not `treaty`)\n* `D2`: satisfies RHS - contains `Iran` and not `treaty`)\n\n# Tokenizing Sentences\n\n## Definition of a Token\n\n> A token is an instance of a sequence of characters in some particular document that are grouped together as a useful semantic unit for processing. ([Stanford NLP](https://nlp.stanford.edu/IR-book/html/htmledition/tokenization-1.html)):\n\n\n\n\n## Examples of Tokens/Words Not Being the Identical Concepts\n\n* Multi-word entities: `San Francisco`, `New York City`\n* Phone numbers / dates: `(800) 123-4564` and `Apr. 30th, 2020`\n\n\nAt first, the task of tokenizing seems simple:\n1. Split apart `corpus` into `documents`.\n2. Split apart `documents` into `tokens`.\n\n## Definition of a Document\n\nA document is a distinct group of tokens. For example, in the Amazon toy product review dataset, each review can be considered a document. In *Tale of Two Cities*, a document could be either a sentence, or a paragraph, or a chapter - it all depends on the task at hand.\n\n* **Sentiment Analysis**: each document is a review/comment/tweet\n* **Authorship Classification** (determining if a piece of text was written by Person A or Person B): the entire text is a document\n\n## Why Is Tokenization Hard?\n\n### Sentence Boundary Detection\n\nDeciding where one sentence ends and another sentence begins is easy for humans, but extremely complex for machines. A prime cause of this is ambiguity of punctuation marks. Particularly in English, periods can mean many things beyond denoting the end of a sentence:\n* abbreviations\n* decimal points\n* domain names and email addresses\n\nFurthermore, other \"obvious\" sentence boundaries like question marks and exclamation marks are becoming increasingly ambiguous due to slang, emoticons, or just emphasis (`\"What are you doing???\"` should not be split into 3 separate sentences).\n\n### Approaches to Sentence Boundary Detection\n\n#### Rules-Based\n\n* Using regex: `((?<=[a-z0-9][.?!])|(?<=[a-z0-9][.?!]\\\"))(\\s|\\r\\n)(?=\\\"?[A-Z])` (don't worry if you can't understand this yet- it includes usage of several advanced techniques such as **lookahead/behind references** which we have not covered).\n\n#### Supervised/Unsupervised Learning\n\n* Maximum entropy models ([UC Berkeley's SATZ Adaptive Sentence Boundary Detector](https://web.archive.org/web/20070922132340/http://elib.cs.berkeley.edu/src/satz/))\n* NLTK's `Punkt` sentence tokenizer\n\n\n\n```python\n# Why not just tokenize myself?\ntext = \"I made two purchases today! I bought a bag of grapes for $4.99, \\\nbut then... realized John Francis already bought some at the Y.M.C.A!\"\n```\n\n\n```python\n# trying to write our own tokenizer\ntext.split(\".\")\n\n```\n\n\n\n\n    ['I made two purchases today! I bought a bag of grapes for $4',\n     '99, but then',\n     '',\n     '',\n     ' realized John Francis already bought some at the Y',\n     'M',\n     'C',\n     'A!']\n\n\n\nWhat are some of the issues you notice with the above approach?\n\n### NLTK's `PunktSentenceTokenizer`\n\n> `PunktSentenceTokenizer` is an **sentence boundary detection algorithm** that must be trained to be used. NLTK already includes a pre-trained version of the `PunktSentenceTokenizer` ([StackOverflow](https://stackoverflow.com/questions/35275001/use-of-punktsentencetokenizer-in-nltk))\n\n\n```python\n# Using NLTK sent_tokenize()\nnltk.sent_tokenize(text)\n```\n\n\n\n\n    ['I made two purchases today!',\n     'I bought a bag of grapes for $4.99, but then... realized John Francis already bought some at the Y.M.C.A!']\n\n\n\n## Stemming\n\nStemming is the process of reducing inflection in words to their root forms such as mapping a group of words to the same stem even if the stem itself is not a valid word in the language [Source](https://www.datacamp.com/community/tutorials/stemming-lemmatization-python)\n\n\n\nIn Python, we can use **`nltk.stem.porter.PorterStemmer`** stem our words:\n\n```python\nstemmer = PorterStemmer()\nprint(stemmer.stem(\"caressed\"))  # caress\nprint(stemmer.stem(\"athlete\"))  # athlet\nprint(stemmer.stem(\"athletics\"))  # athlet\nprint(stemmer.stem(\"media\"))  # media\nprint(stemmer.stem(\"photography\"))  # photographi\nprint(stemmer.stem(\"sexy\"))  # sexi\nprint(stemmer.stem(\"journalling\"))  # journal\nprint(stemmer.stem(\"Slovakia\")) # slovakia\nprint(stemmer.stem(\"corpora\")) # corpora\nprint(stemmer.stem(\"thieves\")) # thiev\nprint(stemmer.stem(\"rocks\")) # rock\n```\n\n\n```python\nstemmer = PorterStemmer()\nprint(stemmer.stem(\"caressed\"))  # caress\nprint(stemmer.stem(\"athlete\"))  # athlet\nprint(stemmer.stem(\"athletics\"))  # athlet\nprint(stemmer.stem(\"media\"))  # media\nprint(stemmer.stem(\"photography\"))  # photographi\nprint(stemmer.stem(\"sexy\"))  # sexi\nprint(stemmer.stem(\"journalling\"))  # journal\nprint(stemmer.stem(\"Slovakia\")) # slovakia\nprint(stemmer.stem(\"corpora\")) # corpora\nprint(stemmer.stem(\"thieves\")) # thiev\nprint(stemmer.stem(\"rocks\")) # rock\n```\n\n## Lemmatization\n\nLemmatization is closely related to stemming. However, while stemming looks only at the individual word itself, and considers the usage of the word (ie. part of speech, is this word a noun, a verb, etc.). For example, if we compared the [outputs of stemming and lemmatization certain ambiguous French words](https://blog.bitext.com/lemmatization-vs-stemming):\n\n\n\n```python\nfrom nltk.stem import WordNetLemmatizer\nlemmatizer = WordNetLemmatizer()\nprint(lemmatizer.lemmatize(\"caressed\")) #caressed\nprint(lemmatizer.lemmatize(\"athlete\")) #athlete\nprint(lemmatizer.lemmatize(\"athletics\")) #athletics\nprint(lemmatizer.lemmatize(\"media\"))\nprint(lemmatizer.lemmatize(\"photography\")) #photography\nprint(lemmatizer.lemmatize(\"sexy\")) #sexy\nprint(lemmatizer.lemmatize(\"journalling\")) #journalling\nprint(lemmatizer.lemmatize(\"Slovakia\")) #Slovakia\nprint(lemmatizer.lemmatize(\"corpora\")) # corpus\nprint(lemmatizer.lemmatize(\"thieves\")) # thief\nprint(lemmatizer.lemmatize(\"rocks\")) #rock\n```\n\n### Why Stemming?\n- smaller and faster\n- simplicity in \"good enough\"\n- can often **provide higher recall (coverage)** if you are using it for text searching: `drives` and `drivers` will likely shorten to `driv`, which may be useful if your search engine wants to make sure to get all relevant documents, even at the cost of surfacing a few irrelevant documents\n- could potentially be more useful for predictive models that tend to overfit\n\n### Differences Between Stemming and Lemmatization\n> **Stemming** usually refers to a crude heuristic process that chops off the ends of words in the hope of achieving this goal correctly most of the time, and often includes the removal of derivational affixes. **Lemmatization** usually refers to doing things properly with the use of a vocabulary and morphological analysis of words, normally aiming to remove inflectional endings only and to return the base or dictionary form of a word, which is known as the lemma . If confronted with the token `saw`, stemming might return just `s`, whereas lemmatization would attempt to return either `see` or `saw` depending on whether the use of the token was as a verb or a noun. ([Stanford NLP Group](https://nlp.stanford.edu/IR-book/html/htmledition/stemming-and-lemmatization-1.html)) \n\n## Scoring Metrics\n\n\n\n### Precision/Recall\n\n**Recall:** What percent of the positive classes did the model successfully predict?\n**Precision:** When a model predicted a positive class, what percentage of the time was it correct?\n\nIn terms of NLP / stemming / lemmatization:\n\n**Recall**: After processing (tokenizing, stemming/lemmatizing) the data, what percent of the relevant search results were surfaced? Ie. - when a user searches for `blue jeans`, did all the results returned include all the relevant items (blue-ish colored denim pants)?\n\n**Precision**: After processing (tokenizing, stemming/lemmatizing) the data, what percent of the results returned were relevant?\n\n\n\n\n### F1 Score\n\nThe F1 score of a model represents the harmonic mean between precision and recall, and is defined as \n\n$$\n\\begin{equation}\nF_{1} = 2 * \\frac{P * R}{P + R}\n\\end{equation}\n$$\n\nAn F1 score is often a good measure \n* our dataset target is class imbalanced (ie. 96% positive, 4% negative)\n* when we want to balance optimizing for both precision and recall\n\n### Exercises\n\nCalculate:\n\n1. Overall **accuracy**: $\\frac{?}{?}$\n\n\n```python\naccuracy = (10+20)/(10+4+2+20)\naccuracy\n```\n\n\n\n\n    0.8333333333333334\n\n\n\n2. **Precision:** $\\frac{?}{?}$\n\n\n```python\nprecision = 10/12\nprecision\n```\n\n\n\n\n    0.8333333333333334\n\n\n\n3. **Recall:** $\\frac{?}{?}$\n\n\n```python\nrecall = 10/(10+4)\nrecall\n```\n\n\n\n\n    0.7142857142857143\n\n\n\n4. **F1 Score**\n\n\n```python\n#good F1 score: 0-1 depend on use case, whether it's 80% or 90%\n#if customer churn, this is good score\n#if it's for internet security, this is not a good score\n#auc > 0.7, it's workable\nf1 = 2 * precision*recall / (precision + recall)\nf1\n```\n\n\n\n\n    0.7692307692307692\n\n\n\n## Removing Stopwords\n\nIt's your call ultimately if you want to remove stopwords. There are advantages and disadvantages to both approaches. You will first need to run `nltk.download(\"stopwords\")` to download the set of stopwords for NLTK:\n\n\n```python\n# see the set of words NLTK considers stopwords\nfrom nltk.corpus import stopwords\nprint(set(stopwords.words(\"english\")))\n```\n\n    {\"you've\", \"isn't\", 'that', \"you're\", 'ain', 'any', 'an', 'will', \"it's\", 'own', 'ours', \"wasn't\", 'this', \"hadn't\", \"aren't\", 'won', 'who', 'doing', \"she's\", 'few', \"doesn't\", 'further', 'her', \"hasn't\", 'our', 'you', 'll', 'until', 've', 'other', \"you'd\", 'his', 'your', 'into', 'yourselves', \"shouldn't\", 'doesn', \"you'll\", 'is', 'there', 'he', 'am', 'most', 's', 'should', 'being', 'them', 'does', 'up', 'some', 'against', 'was', 'we', 'having', 're', 'those', 'about', 'haven', 'down', \"don't\", 'weren', 'shouldn', 'if', 'above', 'me', \"mustn't\", 'did', 'had', 'hers', 'between', 'again', \"didn't\", 'under', 'before', 'all', 'now', 'as', 'she', 'were', 'aren', \"weren't\", \"that'll\", 'from', 'same', 'through', 'don', 'here', 'nor', 't', 'd', 'off', 'while', \"couldn't\", 'o', 'their', 'its', 'the', 'than', \"mightn't\", 'been', 'shan', 'can', 'such', \"needn't\", 'i', 'at', 'yours', 'how', 'to', 'or', 'just', 'both', 'm', 'wouldn', 'couldn', 'after', 'himself', 'needn', 'over', 'out', \"should've\", 'no', 'why', 'but', 'where', 'below', 'by', 'has', 'because', 'didn', 'and', 'him', 'so', 'very', 'ourselves', 'more', 'not', 'during', 'yourself', 'are', 'have', 'mustn', 'wasn', 'itself', 'do', 'for', 'a', 'in', 'on', \"shan't\", 'only', 'isn', \"wouldn't\", 'myself', 'theirs', 'themselves', 'too', 'y', \"won't\", 'hadn', 'when', 'they', 'my', 'what', 'of', 'with', 'once', 'these', 'each', 'ma', 'mightn', 'hasn', \"haven't\", 'then', 'be', 'which', 'whom', 'it', 'herself'}\n\n\n\n```python\n# iterate through the Pandas dataframe, and drop the columns that reflect stopwords\n\n```\n\n### When Should You Avoid Removing Stopwords?\n\nThe below example is taken from a Medium article by Gagandeep Singh, [\"Why you should avoid removing STOPWORDS\"](https://towardsdatascience.com/why-you-should-avoid-removing-stopwords-aa7a353d2a52).\n\n\n```python\nreviews = [\n    (\"The product is really very good\", \"Positive\"),\n    (\"The products seems to be good\", \"Positive\"),\n    (\"Good product. I really liked it\", \"Positive\"),\n    (\"I didn\u2019t like the product\", \"Negative\"),\n    (\"The product is not good.\", \"Negative\")\n]\n```\n\n\n```python\ncleaned_reviews = []\nnltk_stopwords = set(stopwords.words('english'))\n\n# This iterates through each of the reviews, splitting the review into distinct tokens\n# Then it checks each token for whether or not it is a stopword, before adding them back into a \"cleaned_review\"\nfor review in reviews:\n    words = review[0].split()\n    new_words = []\n    for word in words:\n        if word in nltk_stopwords:\n            continue\n        new_words.append(word)\n    cleaned_review = \" \".join(new_words)\n    cleaned_reviews.append((cleaned_review, review[1]))\n```\n\n\n```python\ncleaned_reviews\n```\n\n\n\n\n    [('The product really good', 'Positive'),\n     ('The products seems good', 'Positive'),\n     ('Good product. I really liked', 'Positive'),\n     ('I didn\u2019t like product', 'Negative'),\n     ('The product good.', 'Negative')]\n\n\n\nSingh:\n> If you are working with **basic NLP techniques like BOW, Count Vectorizer or TF-IDF(Term Frequency and Inverse Document Frequency)** then removing stopwords is a good idea because stopwords act like noise for these methods. If you working with **LSTMs or other models which capture the semantic meaning and the meaning of a word depends on the context of the previous text**, then it becomes important not to remove stopwords.\n\n## Exercises\n\n##### 1. For each of the following statements, label them True or False. If False, briefly explain why:\n\n\nA. *If the **F1 score** of a model is **1.0 (100%)**, then the accuracy of your model must also be **100%**.*\n\nB. *Stemming **increases the size of the vocabulary** (the vocabulary is the set of all tokens found inside the corpus)*\n\nC. *Texts processed using lemmatization will typically have higher recall than stemming.*\n\n##### 2. Calculate precison and recall given the following results from a confusion matrix:\n\n\n\n##### 3. Provide an example of how stemming can improve recall.\n\n##### 4. Provide an example of when stemming might reduce precision.\n\n# Vectorization Techniques\n\n## Count Vectorization\n\n\nYou can use **`sklearn.feature_extraction.text.CountVectorizer`** to easily convert your corpus into a bag of words matrix:\n\n```python\nfrom sklearn.feature_extraction.text import CountVectorizer\nvectorizer = CountVectorizer()\ndata_corpus = [\"John likes to watch movies. Mary likes movies too.\", \n\"John also likes to watch football games. Mary does not like football much.\"]\nX = vectorizer.fit_transform(data_corpus) \n```\nNote that the output `X` here is not your traditional Numpy matrix! Calling **`type(X)`** here will yield **`<class 'scipy.sparse.csr.csr_matrix'>`**, which is a **CSR ([compressed sparse row format matrix](https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.sparse.csr_matrix.html))**. To convert it into an actual matrix, call the `toarray()` method:\n\n```python\nX.toarray()\n```\nYour output will be \n\n```\narray([[0, 0, 0, 0, 1, 0, 2, 1, 2, 0, 0, 1, 1, 1],\n       [1, 1, 2, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1]], dtype=int64)\n```\nNotice that using **`X.shape`** $\\rightarrow$ `(2,14)`, indicating a total vocabulary size $V$ of 14. To get what word each of the 14 columns corresponds to, use **`vectorizer.get_feature_names()`**:\n```\n['also', 'does', 'football', 'games', 'john', 'like', 'likes', 'mary', 'movies', 'much', 'not', 'to', 'too', 'watch']\n```\n\nNotice, however, that as the vocabulary size $V$ increases, the percent of the matrix taken up by zero values increases:\n\n```python\ncorpus = [\n    \"Some analysts think demand could drop this year because a large number of homeowners take on remodeling projectsafter buying a new property. With fewer homes selling, home values easing, and mortgage rates rising, they predict home renovations could fall to their lowest levels in three years.\", \n    \n          \"Most home improvement stocks are expected to report fourth-quarter earnings next month.\",\n    \n         \"The conversation boils down to how much leverage management can get out of its wide-ranging efforts to re-energize operations, branding, digital capabilities, and the menu\u2013and, for investors, how much to pay for that.\",\n    \n    \"RMD\u2019s software acquisitions, efficiency, and mix overcame pricing and its gross margin improved by 90 bps Y/Y while its operating margin (including amortization) improved by 80 bps Y/Y. Since RMD expects the slower international flow generator growth to continue for the next few quarters, we have lowered our organic growth estimates to the mid-single digits.\"\n]\n\nX = vectorizer.fit_transform(corpus).toarray() \n```\n\n\n\n```python\nfrom sklearn.feature_extraction.text import CountVectorizer\n# list of text documents\ntext = [\"It's still early, so box-office disappointments are still among the highest-grossing movies of the year.\", \n        \"That movie was terrific\", \"You love cats\", \n        \"Pay for top executives at big US companies is vastly higher than what everyday workers make, and a new report from The Wall Street Journal has found that CEOs have hit an eye-popping milestone in the size of their monthly paychecks.\"]\n```\n\n\n```python\n# see the outputted vectors\n```\n\n\n```python\n# load vectorized corpus into Pandas dataframe\n```\n", "meta": {"hexsha": "1d6304d60ac0cc81db2617553421563fb1344118", "size": 37733, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "week2/Text Preprocessing Techniques.ipynb", "max_stars_repo_name": "twang526001/dso-560-nlp-and-text-analytics", "max_stars_repo_head_hexsha": "58f9766344bb48e1dfa3ad244550b66c0f88101b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "week2/Text Preprocessing Techniques.ipynb", "max_issues_repo_name": "twang526001/dso-560-nlp-and-text-analytics", "max_issues_repo_head_hexsha": "58f9766344bb48e1dfa3ad244550b66c0f88101b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week2/Text Preprocessing Techniques.ipynb", "max_forks_repo_name": "twang526001/dso-560-nlp-and-text-analytics", "max_forks_repo_head_hexsha": "58f9766344bb48e1dfa3ad244550b66c0f88101b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.9737783075, "max_line_length": 6418, "alphanum_fraction": 0.6095460207, "converted": true, "num_tokens": 7022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1480471867548583, "lm_q2_score": 0.04336579984571784, "lm_q1q2_score": 0.006420184668532795}}
{"text": "<a href=\"https://colab.research.google.com/github/kalz2q/mycolabnotebooks/blob/master/temp.ipynb\" target=\"_parent\"></a>\n\n# \u30e1\u30e2\n\n\u5b9f\u9a13\u5834\u3001\u30e1\u30e2\u7f6e\u304d\u5834\u3001\u3067\u3059\n\n\n```\n# \u5b9f\u9a13 \u30d5\u30a1\u30a4\u30eb\u3092\u4e00\u5ea6\u5168\u90e8\u8aad\u307f\u8fbc\u3080\n%%writefile temp.cpp\n# include <bits/stdc++.h>\nusing namespace std;\n\nconst string  str = R\"(\u307e\u3060\u3042\u3052\u521d\u3081\u3057\u524d\u9aea\u306e\n\u6797\u6a8e\u306e\u3082\u3068\u306b\u898b\u3048\u3057\u3068\u304d\n\u524d\u306b\u3055\u3057\u305f\u308b\u82b1\u6adb(\u306f\u306a\u3050\u3057)\u306e\n\u82b1\u3042\u308b\u541b\u3068\u601d\u3072\u3051\u308a)\";\n\nint main () {\n  ofstream ofs(\"temp.txt\"); \n  string line;\n  stringstream ss(str);\n  while (getline(ss, line)) {\n      ofs << line << endl;\n  }\n\n  ifstream ifs(\"temp.txt\");\n\n  string myStream((istreambuf_iterator<char>(ifs)), istreambuf_iterator<char>());\n  cout << myStream;\n\n  // stringstream myStream;\n  // myStream << ifs.rdbuf();\n  // cout << myStream.str() << endl;\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; ./a.out\n```\n\n    \u307e\u3060\u3042\u3052\u521d\u3081\u3057\u524d\u9aea\u306e\n    \u6797\u6a8e\u306e\u3082\u3068\u306b\u898b\u3048\u3057\u3068\u304d\n    \u524d\u306b\u3055\u3057\u305f\u308b\u82b1\u6adb(\u306f\u306a\u3050\u3057)\u306e\n    \u82b1\u3042\u308b\u541b\u3068\u601d\u3072\u3051\u308a\n\n\n\n```\n# \u521d\u604b\u3067\u5b9f\u9a13\n%%writefile temp.cpp\n# include <bits/stdc++.h>\nusing namespace std;\n\nconst string  str = R\"(\u307e\u3060\u3042\u3052\u521d\u3081\u3057\u524d\u9aea\u306e\n\u6797\u6a8e\u306e\u3082\u3068\u306b\u898b\u3048\u3057\u3068\u304d\n\u524d\u306b\u3055\u3057\u305f\u308b\u82b1\u6adb(\u306f\u306a\u3050\u3057)\u306e\n\u82b1\u3042\u308b\u541b\u3068\u601d\u3072\u3051\u308a)\";\n\nint main () {\n  ofstream ofs(\"temp.txt\"); \n  string line;\n  stringstream ss(str);\n  while (getline(ss, line)) {\n      ofs << line << endl;\n  }\n\n  ifstream ifs(\"temp.txt\");\n  while (getline (ifs, line)) {\n    cout << line << endl;\n  }\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; ./a.out\n```\n\n    \n        \u307e\u3060\u3042\u3052\u521d\u3081\u3057\u524d\u9aea\u306e\n    \u6797\u6a8e\u306e\u3082\u3068\u306b\u898b\u3048\u3057\u3068\u304d\n    \u524d\u306b\u3055\u3057\u305f\u308b\u82b1\u6adb(\u306f\u306a\u3050\u3057)\u306e\n    \u82b1\u3042\u308b\u541b\u3068\u601d\u3072\u3051\u308a\n\n\n\n```\n# How to convert vector to set?\n%%writefile temp.cpp\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main () {\n    vector<int> vec = {1, 2, 3, 1, 2};\n    set<int> s(vec.begin(), vec.end());\n    for (auto item : s) {\n        cout << item << endl;\n    }\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; ./a.out\n```\n\n    1\n    2\n    3\n\n\n\n```\n# words \u3092\u4f5c\u308b\u3002words(str) => vector<str>\n# string \u3092\u5358\u8a9e\u306b\u5206\u89e3\u3059\u308b\n# stringstream \u3092\u4f7f\u3063\u3066\u76f4\u63a5 words \u306b\u3059\u308b\n%%writefile temp.cpp\n#include <bits/stdc++.h>\nusing namespace std;\n\nconst string str = R\"(  Now I need a drink.\nthis is a pen. pen pen)\";\n\nvector<string> words(const string &str) {\n    string str02;\n    str02 = regex_replace(str, regex(\"[ .,\\n]+\"), \" \");\n    string item;\n    vector<string> elems = {};\n    stringstream ss(str02);\n    while (getline(ss, item, ' ')) {\n        if (item == \"\") continue;\n        elems.push_back(item);\n    }\n    return elems;\n}\n\nstring formatVecStr(vector<string> vec){\n    if (vec.empty()) return \"\";\n    string str = \"\";\n    str +=\"{\";\n    bool isFirst = true;\n    for (auto item : vec){\n        if(!isFirst) str += \", \";\n        str = str + '\"' + item + '\"';\n        isFirst = false;\n    };\n    str += \"}\";\n    return str;\n}\n\nint main() {\n    vector<string> wordvec;\n    wordvec = words(str);\n    cout << formatVecStr(wordvec) << endl;\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; ./a.out\n```\n\n    {\"Now\", \"I\", \"need\", \"a\", \"drink\", \"this\", \"is\", \"a\", \"pen\", \"pen\", \"pen\", \"\u3053\u308c\u306f\u672c\u3067\u3059\u3002\"}\n\n\n\n```\n# \u3068\u308a\u3042\u3048\u305a\u52d5\u3044\u3066\u5165\u308b\u304c\u3001\u30c0\u30e1\u306a\u306e\u3067\u66f8\u304d\u76f4\u3059\n# stringstream \u3092\u4f7f\u3063\u3066\u76f4\u63a5 words \u306b\u3059\u308b\u3088\u3046\u306b\u66f8\u304d\u76f4\u3059\n# \u5358\u8a9e\u306b\u5206\u89e3\u3059\u308b\n%%writefile temp.cpp\n#include <bits/stdc++.h>\nusing namespace std;\n\nconst string str = R\"(   Now I need a drink.\nthis\nis a\npen. pen pen)\";\n\nvoid split(const string &s, char delim, vector<string> &elems) {\n    stringstream ss(s);\n    string item;\n    while (getline(ss, item, delim)) {\n        elems.push_back(item);\n    }\n} \n\nvector<string> split(const string &s, char delim) {\n    vector<string> elems;\n    split(s, delim, elems);\n    return elems;\n}\n\nstring formatVecStr(vector<string> vec){\n    string str = \"\";\n    str +=\"{\";\n    bool isFirst = true;\n    for (auto item : vec){\n        if(!isFirst) str += \", \";\n        str = str + '\"' + item + '\"';\n        isFirst = false;\n    };\n    str += \"}\";\n    return str;\n}\n\nint main() {\n  string str02;\n  str02 = regex_replace(str, regex(\"[ .,\\n]+\"), \" \");\n  vector<string> words = split(str02, ' ');\n  for (auto& item : words){\n      cout << item << \" \";\n  }\n  cout << endl;\n  cout << formatVecStr(words) << endl;\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; ./a.out\n```\n\n     Now I need a drink this is a pen pen pen \n    {\"\", \"Now\", \"I\", \"need\", \"a\", \"drink\", \"this\", \"is\", \"a\", \"pen\", \"pen\", \"pen\"}\n\n\n\n```\n# \u30a2\u30a4\u30c7\u30a2 lines \u3092\u4f5c\u308b\n# \u8907\u6570\u306e\u884c\u304b\u3089\u306a\u308b\u30c6\u30ad\u30b9\u30c8\u3067\u4e91\u3005\u3002\n# vector<str> lines() \u3068\u8a00\u3046\u95a2\u6570\u3067\u3082\u3068\u306e\u30c6\u30ad\u30b9\u30c8\u3092\u884c\u5358\u4f4d\u306e\n# \u8fd4\u308a\u5024\u304c {\"this is a pen.\", \"\u3053\u308c\u306f\u672c\u3067\u3059\u3002\"}\n# \u5143\u306e\u30c6\u30ad\u30b9\u30c8\u304c\n# const string  str = R\"(this is a pen.\n# \u3053\u308c\u306f\u672c\u3067\u3059\u3002)\";\n%%writefile temp.cpp\n# include <bits/stdc++.h>\nusing namespace std;\n\nstring formatVecStr(vector<string> vec){\n    string str = \"\";\n    str +=\"{\";\n    bool isFirst = true;\n    for (auto item : vec){\n        if(!isFirst) str += \", \";\n        str = str + '\"' + item + '\"';\n        isFirst = false;\n    };\n    str += \"}\";\n    return str;\n}\n\nvector<string> lines(string str){\n    vector<string> vec = {};\n    stringstream ss(str);\n    string line = \"\";\n    while (getline(ss, line)){\n        vec.push_back(line);\n    }\n    return vec;\n}\n\nint main () {\n    const string  str = R\"(this is a pen.\n\u3053\u308c\u306f\u672c\u3067\u3059\u3002)\";\n    vector<string> vec = lines(str);\n    cout << formatVecStr(vec) << endl;\n}\n```\n\n\n```\n# heredocument \u304b\u3089\u5909\u6570\u3078\u306e\u5165\u529b\n%%writefile temp.cpp\n# include <bits/stdc++.h>\nusing namespace std;\nconst string  str = R\"(\n2 3\ntiis is a \u30da\u30f3\n)\";\nint main(){\n    stringstream ss(str);\n    int N, M;\n    ss >> N >> M;\n    vector<string> vec(4);\n    for (int i = 0; i < 4; i++) {\n        ss >> vec.at(i);\n    }\n    cout << N << \" \" << M << endl;\n    for (int i = 0; i < 4; i++) {\n        cout << vec.at(i) << \" \";\n    }\n    cout << endl;\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; ./a.out\n```\n\n    2 3\n    tiis is a \u30da\u30f3 \n\n\n\n```\n# \u5b9f\u9a13 vector \u306e\u9023\u7d50\n%%writefile temp.cpp\n#include <bits/stdc++.h>\nusing namespace std;\n\nstring formatVecStr(vector<string> vec){\n    string str = \"\";\n    str +=\"{\";\n    bool isFirst = true;\n    for (auto item : vec){\n        if(!isFirst) str += \", \";\n        str = str + '\"' + item + '\"';\n        isFirst = false;\n    };\n    str += \"}\";\n    return str;\n}\n\nint main(){\n    vector<string> vec = {\"this\", \"is\", \"a\", \"pen\"};\n    vector<string> vec02 = {\"that\", \"is\", \"not\", \"a\", \"pen\"};\n    vec.insert(vec.end(), vec02.begin(), vec02.end());\n    cout << formatVecStr(vec) << endl;\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; ./a.out\n```\n\n    {\"this\", \"is\", \"a\", \"pen\", \"that\", \"is\", \"not\", \"a\", \"pen\"}\n\n\n\n```\n# c++ formatVecStr \u3092\u4f5c\u308b\n%%writefile temp.cpp\n#include <bits/stdc++.h>\nusing namespace std;\n\nstring formatVecStr(vector<string> vec){\n    string str = \"\";\n    str +=\"{\";\n    bool isFirst = true;\n    for (auto item : vec){\n        if(!isFirst) str += \", \";\n        str += item;\n        isFirst = false;\n    };\n    str += \"}\";\n    return str;\n}\n\nint main(){\n    vector<string> vec = {\"this\", \"is\", \"a\", \"pen\"};\n    cout << formatVecStr(vec) << endl;\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; ./a.out\n```\n\n    {this, is, a, pen}\n\n\n\n```\n# tail recursion \u672b\u5c3e\u518d\u5e30\n# fact :: Int -> Int\n# fact n = fact' n 1\n#     where\n#         fact' 0 y = y\n#         fact' x y = fact' (x - 1) (x * y)\n%%writefile temp.cpp\n#include <bits/stdc++.h>\nusing namespace std;\n\nunsigned long  fact02 (unsigned long  n, unsigned long  acc){\n    if (n==0) return acc;\n    else {\n        return fact02((n-1), n*acc);\n    }\n}\n\nunsigned long  fact (unsigned long  n) {\n    return fact02(n, 1);\n}\n\nint main () {\n    unsigned long  n; cin >> n;\n    cout << fact (n) << endl;\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; echo 50 |./a.out\n```\n\n    15188249005818642432\n\n\n\n```\n# heredocument\n# \u96a3\u63a5\u3059\u308b\u6587\u5b57\u5217\u306e\u9023\u7d50\u3092\u5229\u7528\u3057\u305f\u65b9\u6cd5\n%%writefile temp.cpp\n#include <bits/stdc++.h>\nusing namespace std;\n/*\nconst char *str = \"1\"\n                  \"  2\\n\"\n                  \"    3\"; */\nconst string str = \n\"1\"\n\"  2\\n\"\n\"    3\";\nint main(){\n    cout << str << endl;\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; ./a.out\n```\n\n    1  2\n        3\n\n\n\n```\n# heredocument\n# c++ \u306e R\"( \u3092\u5229\u7528\u3057\u305f\u65b9\u6cd5\n%%writefile temp.cpp\n#include <bits/stdc++.h>\nusing namespace std;\nconst string  str = R\"(\n\u307e\u3060\u3042\u3052\u521d\u3081\u3057\u524d\u9aea\u306e\n\u6797\u6a8e\u306e\u3082\u3068\u306b\u898b\u3048\u3057\u3068\u304d\n\u524d\u306b\u3055\u3057\u305f\u308b\u82b1\u6adb(\u306f\u306a\u3050\u3057)\u306e\n\u82b1\u3042\u308b\u541b\u3068\u601d\u3072\u3051\u308a\n)\";\nint main(){\n    cout << str << endl;\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; ./a.out\n```\n\n    \n    \u307e\u3060\u751f\u3048\u305d\u3081\u3057\u524d\u9aea\u306e\n    \u307e\u3060\u3042\u3052\u521d\u3081\u3057\u524d\u9aea\u306e\n    \u6797\u6a8e\u306e\u3082\u3068\u306b\u898b\u3048\u3057\u3068\u304d\n    \u524d\u306b\u3055\u3057\u305f\u308b\u82b1\u6adb(\u306f\u306a\u3050\u3057)\u306e\n    \u82b1\u3042\u308b\u541b\u3068\u601d\u3072\u3051\u308a\n    \n\n\n\n```\n# \u6570\u5b57\u306e\u6841\u8aad\u307f\n%%writefile temp.cpp\n#include <bits/stdc++.h>\nusing namespace std;\n\nstring conv2en(long num){\n    string result = \"\";\n    if (num == 0) return \"0\";\n    if (num > 999999999999) {\n        result += to_string(num / 1000000000000);\n        result += \"trillion\";\n        num = (num % 1000000000000);\n    }\n    if (num > 999999999) {\n        result += to_string(num / 1000000000);\n        result += \"billion\";\n        num = (num % 1000000000);\n    }\n    if (num > 999999) {\n        result += to_string(num / 1000000);\n        result += \"million\";\n        num = (num % 1000000);\n    }\n    if (num > 999) {\n        result += to_string(num / 1000);\n        result += \"thousand\";\n        num = (num % 1000);\n    }\n    if (num > 0) {\n        result += to_string(num);\n    }\n    return result;\n}\nstring conv2ja(long num){\n    string result = \"\";\n    if (num == 0) return \"0\";\n    if (num > 9999999999999999) {\n        result += to_string(num / 10000000000000000);\n        result += \"\u4eac\";\n        num = (num % 10000000000000000);\n    }\n    if (num > 999999999999) {\n        result += to_string(num / 1000000000000);\n        result += \"\u5146\";\n        num = (num % 1000000000000);\n    }\n    if (num > 99999999) {\n        result += to_string(num / 100000000);\n        result += \"\u5104\";\n        num = (num % 100000000);\n    }\n    if (num > 9999) {\n        result += to_string(num / 10000);\n        result += \"\u4e07\";\n        num = (num % 10000);\n    }\n    if (num > 0) {\n        result += to_string(num);\n    }\n    return result;\n}\n\nint main() {\n    long num;\n    cin >> num;\n    cout << conv2ja(num) << endl;\n    cout << conv2en(num) << endl; \n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; echo 12345678901234567 | ./a.out\n!g++ temp.cpp; echo 0000 | ./a.out\n!g++ temp.cpp; echo 10000 | ./a.out\n!g++ temp.cpp; echo 100000000 | ./a.out\n!g++ temp.cpp; echo 1000000000000 | ./a.out\n!g++ temp.cpp; echo 10000000000000000 | ./a.out\n!g++ temp.cpp; echo 100000000000000000000 | ./a.out\n!g++ temp.cpp; echo 1000000000000000000 | ./a.out\n```\n\n    1\u4eac2345\u51466789\u5104123\u4e074567\n    12345trillion678billion901million234thousand567\n    0\n    0\n    1\u4e07\n    10thousand\n    1\u5104\n    100million\n    1\u5146\n    1trillion\n    1\u4eac\n    10000trillion\n    922\u4eac3372\u5146368\u51045477\u4e075807\n    9223372trillion36billion854million775thousand807\n    100\u4eac\n    1000000trillion\n\n\n\n```\n# how to cout a vector in c++ answer\n# printVectorElements \u306f template<typename T> \u3068\u3057\u3066\u3044\u308b\n# \u3053\u308c\u3067 int \u3068 string \u306b\u5bfe\u5fdc\u3067\u304d\u3066\u3044\u308b\u304c\u3001cout \u51fa\u6765\u306a\u3044\u578b\u306b\u5bfe\u5fdc\u3067\u304d\u3066\u3044\u308b\u308f\u3051\u3067\u306f\u306a\u3044\n# \u3042\u3068\u672b\u5c3e\u306b\u4f59\u8a08\u306a `;` \u304c\u4ed8\u304f\n# \u79c1\u306e vecIntToStr \u306e\u65b9\u304c\u826f\u3044\u304c\u540d\u79f0\u304c\u9055\u3046\u306d => formatVecInt2Str\n%%writefile temp.cpp\n#include <iostream>\n#include <vector>\n\nusing std::cout; using std::cin;\nusing std::endl; using std::string;\nusing std::vector;\n\ntemplate<typename T>\nvoid printVectorElements(vector<T> *vec)\n{\n    for (auto i = 0; i < vec->size(); ++i) {\n        cout << vec->at(i) << \"; \";\n    }\n    cout << endl;\n}\n\nint main() {\n    /* vector<string> str_vec = {\"bit\", \"nibble\",\n                              \"byte\", \"char\",\n                              \"int\", \"long\",\n                              \"long long\", \"float\",\n                              \"double\", \"long double\"}; */\n    // vector<int> str_vec = {1,2,3}; //=> 1; 2; 3; \u3068\u51fa\u529b\u3055\u308c\u305f\n    // vector<vector<int>> str_vec = {vector<int>{1,2},vector<int>{3,4}}; // \u30a8\u30e9\u30fc\n\n    printVectorElements(&str_vec);\n\n    return EXIT_SUCCESS;\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; ./a.out\n```\n\n\n```\n# c++ formatVecInt2Str \u3092\u4f5c\u308b\n%%writefile temp.cpp\n#include <bits/stdc++.h>\nusing namespace std;\n\nstring formatVecInt2Str(vector<int> vec){\n    string str = \"\";\n    str +=\"{\";\n    bool isFirst = true;\n    for (auto item : vec){\n        if(!isFirst) str += \", \";\n        str += to_string(item);\n        isFirst = false;\n    };\n    str += \"}\";\n    return str;\n}\n\nint main(){\n    vector<int> vec = {1,2,3,4,5,6};\n    string str;\n    str = formatVecInt2Str(vec);\n    cout << str << endl;\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; ./a.out\n```\n\n    {1, 2, 3, 4, 5, 6}\n\n\n\n```\n# reverseVec \u3092\u4f5c\u308b c++\n# \u5fc5\u8981\u306a\u3044\u307f\u305f\u3044 \u30d6\u30e9\u30f3\u30af\u3067\u3082\u901a\u308b\n%%writefile temp.cpp\n#include <bits/stdc++.h>\nusing namespace std;\n\nvoid vecCout(vector<int> vec){\n    cout << \"{\";\n    bool isFirst = true;\n    for (auto item : vec){\n        if(!isFirst) cout << \", \";\n        cout << item;\n        isFirst = false;\n    };\n    cout << \"}\" << endl;\n}\n\nint main() {\n    vector<int> vec = {3,2,1};\n    vecCout(vec);\n    cout << endl;\n    reverse(vec.begin(),vec.end());\n    vecCout(vec);\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; ./a.out\n```\n\n    {3, 2, 1}\n    \n    {1, 2, 3}\n\n\n\n```\n# bitset \u3092 vector<int> \u306b\u3059\u308b\n# vector \u3092\u51fa\u529b\u3059\u308b\n%%writefile temp.cpp\n#include <bits/stdc++.h>\nusing namespace std;\n\nvoid vecCout(vector<int> vec){\n    cout << \"{\";\n    bool isFirst = true;\n    for (auto item : vec){\n        if(!isFirst) cout << \", \";\n        cout << item;\n        isFirst = false;\n    };\n    cout << \"}\" << endl;\n}\n\nvector<int> toNumVec(bitset<4> bs) {\n    vector<int> vec;\n    for (int i = 0; i < bs.size(); i++){\n        if(bs.test(i)) vec.push_back(i);\n    }\n    return vec;\n}\n\nint main() {\n    bitset<4> bs(\"1110\");\n    vector<int> vec;\n    vec = toNumVec(bs);\n    reverse(vec.begin(),vec.end());\n    vecCout(vec);\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; ./a.out\n```\n\n    {3, 2, 1}\n\n\n\n```\n# vector \u3092\u51fa\u529b\u3059\u308b\n%%writefile temp.cpp\n#include <bits/stdc++.h>\nusing namespace std;\n\nvoid vecCout(vector<int> vec){\n    cout << \"{\";\n    bool isFirst = true;\n    for (auto item : vec){\n        if(!isFirst) cout << \", \";\n        cout << item;\n        isFirst = false;\n    };\n    cout << \"}\" << endl;\n}\n \nint main() {\n    vector<int> vec = {1,2,3};\n    vecCout(vec);\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; ./a.out\n```\n\n    {1, 2, 3}\n\n\n\n```\n# \u95a2\u6570\u3067 vector \u3092\u8fd4\u308a\u5024\u306b\u3059\u308b\n# str2vec \u3067\u6587\u5b57\u5217\u3092 vector \u306b\u3059\u308b\n# \u6587\u5b57\u5217\u306f utf-8 \u304c\u524d\u63d0\n%%writefile temp.cpp\n# include <bits/stdc++.h>\nusing namespace std;\n\nint count_byte(char c){\n    if ((c & 0x80) == 0) return 1;\n    else if ((c & 0xe0) == 0xc0) return 2;\n    else if ((c & 0xf0) == 0xe0) return 3;\n    else return 4;\n}\n\nvector<string> str2vec(string &str){\n    vector<string> vec;\n    for (int i = 0 ; i < str.size(); i += count_byte(str.at(i))){\n        vec.push_back(str.substr(i,count_byte(str.at(i))));\n    }    \n    return vec;\n}\n\nint main() {\n    string str;\n    getline(cin, str);\n    vector<string> vec;\n    vec = str2vec(str);\n    for (auto& item : vec) {\n        cout << item;\n    };\n    cout << endl;\n    cout << \"\u6587\u5b57\u5217\u306e\u9577\u3055\u306f \" << vec.size() << \" \u3067\u3059\u3002\" << endl;\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; echo \"This is \u672c\" | ./a.out\n```\n\n    This is \u672c\n    \u6587\u5b57\u5217\u306e\u9577\u3055\u306f 9 \u3067\u3059\u3002\n\n\n\n```\n# \u30b3\u30fc\u30c9\u8868\u793a\n%%writefile temp.cpp\n# include <bits/stdc++.h>\nusing namespace std;\nint main(){\n    string str1 = \"a\u3042\";\n    for (int i=0; i < str1.size(); i++){\n      cout << \"0x\" << hex << (str1[i] & 0xff) << endl; // 0xff \u306f 2\u6841\u306b\u3059\u308b\u304a\u307e\u3058\u306a\u3044\u304b?\n    }\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; ./a.out\n```\n\n    0x61\n    0xe3\n    0x81\n    0x82\n\n\n\n```\n# qiita c++\u3067\u3001UTF-8\u306ebyte\u6570\u3092\u5224\u5b9a\u3059\u308b\u3053\u3068\u3067\u30de\u30eb\u30c1\u30d0\u30a4\u30c8\u306e\u6587\u5b57\u5217\u3092\u30ab\u30a6\u30f3\u30c8\u3059\u308b\n%%writefile temp.cpp\n# include <bits/stdc++.h>\nusing namespace std;\nint count_byte(char c){\n    if ((c & 0x80) == 0) return 1;\n    else if ((c & 0xe0) == 0xc0) return 2;\n    else if ((c & 0xf0) == 0xe0) return 3;\n    else return 4;\n}\nint main(){\n    string str4 = \"b\";\n    string str5 = \"\u00a9\";\n    string str6 = \"\u4e9c\";\n    printf(\"%s\u306ebyte\u6570\u306f%d\\n\",str4.c_str(),count_byte(str4[0]));\n    printf(\"%s\u306ebyte\u6570\u306f%d\\n\",str5.c_str(),count_byte(str5[0]));\n    printf(\"%s\u306ebyte\u6570\u306f%d\\n\",str6.c_str(),count_byte(str6[0]));\n}\n\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; ./a.out\n```\n\n    b\u306ebyte\u6570\u306f1\n    \u00a9\u306ebyte\u6570\u306f2\n    \u4e9c\u306ebyte\u6570\u306f3\n\n\n\n```\n# \u6587\u5b57\u6570\u30ab\u30a6\u30f3\u30c8\n%%writefile temp.cpp\n# include <bits/stdc++.h>\nusing namespace std;\nint count_byte(char c){\n    if ((c & 0x80) == 0) return 1;\n    else if ((c & 0xe0) == 0xc0) return 2;\n    else if ((c & 0xf0) == 0xe0) return 3;\n    else return 4;\n}\nint count_char(string str){\n    int count = 0;\n    /*\n    char c = *strings;\n    while(c != '\\0'){\n        count += 1;\n        strings += count_byte(c);\n        c = *strings;\n    } *//*\n    for (int i = 0 ; i < str.size(); i++){\n        count += 1;\n        i += count_byte(str.at(i)) -1;\n    }*/\n    for (int i = 0 ; i < str.size(); i += count_byte(str.at(i))){\n        count += 1; \n//        cout << i << \":\" << count_byte(str.at(i)) << endl;\n    }\n    return count;\n}\nint main (){\nstring strs2 = \"\u8457\u4f5c\u6a29\u30de\u30fc\u30af\uff08\u3061\u3087\u3055\u304f\u3051\u3093\u30de\u30fc\u30af\uff09\u307e\u305f\u306f\u30b3\u30d4\u30fc\u30e9\u30a4\u30c8\u30de\u30fc\u30af\uff08copyright mark\uff09\u3068\u306f\u3001\u5927\u6587\u5b57\u306eC\u3092\u4e38\u3067\u56f2\u3093\u3060\u8a18\u53f7\uff08\u00a9\uff09\u3067\u3042\u308a\u3001\u97f3\u58f0\u9332\u97f3[1]\u4ee5\u5916\u306e\u4f5c\u54c1\u306e\u8457\u4f5c\u6a29\u8868\u793a\u306b\u4f7f\u7528\u3055\u308c\u308b\u8a18\u53f7\u3067\u3042\u308b\u3002\";\nprintf(\"strs2 \u306e\u6587\u5b57\u6570\u306f%d\\n\",count_char(strs2)); // 98 \u306b\u306a\u3063\u305f\u3089\u6210\u529f\u3089\u3057\u3044\nstring str = \"a\u4e9c\";\ncout << str << \"\u306e\u6587\u5b57\u6570\u306f\" <<  count_char(str) << endl; // 2 \u304c\u6b63\u89e3\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; ./a.out\n```\n\n    strs2 \u306e\u6587\u5b57\u6570\u306f98\n    a\u4e9c\u306e\u6587\u5b57\u6570\u306f2\n\n\n\n```\n# C++: UTF-8 \u306e\u6587\u5b57\u5217\u30921\u6587\u5b57\u305a\u3064\u8868\u793a\u3059\u308b (std::string)\n# \u3068\u8a00\u3046\u8a18\u4e8b\n%%writefile temp.cpp\n# include <bits/stdc++.h>\nusing namespace std;\n\nvoid print_each_char(std::string);\n\nint main()\n{\n    string str = \"wats\ud842\udfb7\u91ce\u5bb6\";\n    print_each_char(str);\n}\n\nvoid print_each_char(std::string str)\n{\n    using namespace std;\n\n    int pos;\n    unsigned char lead; \n    int char_size;\n\n   for (pos = 0; pos < str.size(); pos += char_size) {\n   \n        lead = str[pos];\n\n        if (lead < 0x80) {\n            char_size = 1;\n        } else if (lead < 0xE0) {\n            char_size = 2;\n        } else if (lead < 0xF0) {\n            char_size = 3;\n        } else {\n            char_size = 4;\n        }\n\n        cout << str.substr(pos, char_size) << '\\n';\n    }\n\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; ./a.out\n```\n\n    w\n    a\n    t\n    s\n    \ud842\udfb7\n    \u91ce\n    \u5bb6\n\n\n\n```\n# iterator version\n#include <iostream>\n#include <string>\n\nvoid print_each_char(std::string);\n\nint main(void)\n{\n    using namespace std;\n    string str = u8\"\ud842\udfb7\u91ce\u5bb6\u306e\u30b3\u30d4\u30da\";\n    print_each_char(str);\n\n    return 0;\n}\n\nvoid print_each_char(std::string str)\n{\n    using namespace std;\n\n    unsigned char lead; \n    int char_size = 0;\n\n    for (string::iterator it = str.begin(); it != str.end(); it += char_size) {\n\n        lead = *it;\n\n        if (lead < 0x80) {\n            char_size = 1;\n        } else if (lead < 0xE0) {\n            char_size = 2;\n        } else if (lead < 0xF0) {\n            char_size = 3;\n        } else {\n            char_size = 4;\n        }\n\n        cout << str.substr(distance(str.begin(), it), char_size) << '\\n';\n\n    }\n\n}\n```\n\n\n```\n# tuple version\n#include <iostream>\n#include <string>\n\nstd::tuple<std::string, int> utf8_next_char(std::string str, int str_size, int pos);\n\nint main(void)\n{\n    using namespace std;\n\n    string str = u8\"\u3042\u3044\u3046\u3048\u304a\";\n    tuple<string, int> t;\n    int str_size = str.size();\n\n    int pos = 0;\n    string buf;\n    int buf_size = 0;\n\n    for (int pos = 0; pos < str_size; pos += buf_size) {\n        t = utf8_next_char(str, str_size, pos);\n        buf = get<0>(t);\n        buf_size = get<1>(t);\n        cout << buf << '\\n';\n    }\n\n    return 0;\n}\n\nstd::tuple<std::string, int> utf8_next_char(std::string str, int str_size, int pos)\n{\n    using namespace std;\n    unsigned char c;\n\n    string buf;\n    int buf_size;\n\n    if (pos >= str_size) {\n        return make_tuple(u8\"?\", pos);\n    }\n\n    c = str[pos];\n\n    if (c < 0x80) {\n        buf_size = 1;\n    } else if (c < 0xE0) {\n        buf_size = 2;\n    } else if (c < 0xF0){\n        buf_size = 3;\n    } else {\n        buf_size = 4;\n    }\n\n    buf = str.substr(pos, buf_size);\n\n    return  make_tuple(buf, buf_size);\n}\n```\n\n\n```\n# \u3053\u306e\u8a18\u4e8b\u3092\u66f8\u3044\u305f\u4eba\u306f constexpr \u306e\u7df4\u7fd2\u3001\u3068\u8a00\u3063\u3066\u3044\u308b\u304c const \u306b\u3057\u3066\u3082\u52d5\u304f\n# https://qiita.com/Kogia_sima/items/fc5094776ba9761e186f\n# \u6587\u5b57\u5217\u3092\u308f\u3056\u308f\u3056 `u\"\"` \u3068\u3057\u306a\u304f\u3066\u3082\u52d5\u304f\n# wchar \u3092\u4f7f\u3063\u3066\u3044\u306a\u3044\n%%writefile temp.cpp\n# include <bits/stdc++.h>\nusing namespace std;\n\nconst size_t utf8_strlen(const char* str) {\n  size_t count = 0;\n\n  while (*str != '\\0') {\n    uint8_t lead = static_cast<uint8_t>(*(str++));\n    ptrdiff_t secondary_chars =\n        (lead < 0x80) ? 0 :\n        ((lead >> 5) == 0b110) ? 1 :\n        ((lead >> 4) == 0b1110) ? 2 :\n        ((lead >> 3) == 0b11110) ? 3 :\n        throw std::out_of_range(\"invalid UTF code point was detected.\");\n\n    while (secondary_chars) {\n      if (-65 < *(str++)) {\n        throw std::out_of_range(\"invalid UTF code point was detected.\");\n      }\n\n      --secondary_chars;\n    }\n\n    ++count;\n  }\n\n  return count;\n}\n\nint main() {\n  // constexpr const char str[] = u8\"UTF-8\u3060\u3088\u301c\u3093\";\n  const char str[] = \"UTF-8\u3060\u3088\u301c\u3093\";\n  const size_t length = utf8_strlen(str);\n\n  printf(\"%lu\\n\", length);\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n# const \u3092\u53d6\u3063\u305f\u3089\u3069\u3046\u306a\u308b\u304b\u5b9f\u9a13  => \u52d5\u3044\u305f\n# \u3053\u306e\u8a18\u4e8b\u3092\u66f8\u3044\u305f\u4eba\u306f constexpr \u306e\u7df4\u7fd2\u3001\u3068\u8a00\u3063\u3066\u3044\u308b\u304c const \u306b\u3057\u3066\u3082\u52d5\u304f\n# https://qiita.com/Kogia_sima/items/fc5094776ba9761e186f\n# \u6587\u5b57\u5217\u3092\u308f\u3056\u308f\u3056 `u\"\"` \u3068\u3057\u306a\u304f\u3066\u3082\u52d5\u304f\n# wchar \u3092\u4f7f\u3063\u3066\u3044\u306a\u3044\u3002size_t \u306f\u4f7f\u3063\u3066\u3044\u308b\n%%writefile temp.cpp\n# include <bits/stdc++.h>\nusing namespace std;\n\nsize_t utf8_strlen(const char* str) {\n  size_t count = 0;\n\n  while (*str != '\\0') {\n    uint8_t lead = static_cast<uint8_t>(*(str++));\n    ptrdiff_t secondary_chars =\n        (lead < 0x80) ? 0 :\n        ((lead >> 5) == 0b110) ? 1 :\n        ((lead >> 4) == 0b1110) ? 2 :\n        ((lead >> 3) == 0b11110) ? 3 :\n        throw std::out_of_range(\"invalid UTF code point was detected.\");\n\n    while (secondary_chars) {\n      if (-65 < *(str++)) {\n        throw std::out_of_range(\"invalid UTF code point was detected.\");\n      }\n\n      --secondary_chars;\n    }\n\n    ++count;\n  }\n\n  return count;\n}\n\nint main() {\n  // constexpr const char str[] = u8\"UTF-8\u3060\u3088\u301c\u3093\";\n  char str[] = \"UTF-8\u3060\u3088\u301c\u3093\";\n  size_t length = utf8_strlen(str);\n\n  printf(\"%lu\\n\", length);\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n# char* str \u3092 string str \u306b\u3057\u305f\u3089\u3069\u3046\u304b #=> \u30a8\u30e9\u30fc\u306f\u51fa\u305f\u304c\u30a2\u30a6\u30c8\u30d7\u30c3\u30c8\u306f\u5408\u3063\u3066\u3044\u308b\n# const \u3092\u53d6\u3063\u305f\u3089\u3069\u3046\u306a\u308b\u304b\u5b9f\u9a13  => \u52d5\u3044\u305f\n# \u3053\u306e\u8a18\u4e8b\u3092\u66f8\u3044\u305f\u4eba\u306f constexpr \u306e\u7df4\u7fd2\u3001\u3068\u8a00\u3063\u3066\u3044\u308b\u304c const \u306b\u3057\u3066\u3082\u52d5\u304f\n# https://qiita.com/Kogia_sima/items/fc5094776ba9761e186f\n# \u6587\u5b57\u5217\u3092\u308f\u3056\u308f\u3056 `u\"\"` \u3068\u3057\u306a\u304f\u3066\u3082\u52d5\u304f\n# wchar \u3092\u4f7f\u3063\u3066\u3044\u306a\u3044\u3002size_t \u306f\u4f7f\u3063\u3066\u3044\u308b\n%%writefile temp.cpp\n# include <bits/stdc++.h>\nusing namespace std;\n\nsize_t utf8_strlen(const char* str) {\n  size_t count = 0;\n\n  while (*str != '\\0') {\n    uint8_t lead = static_cast<uint8_t>(*(str++));\n    ptrdiff_t secondary_chars =\n        (lead < 0x80) ? 0 :\n        ((lead >> 5) == 0b110) ? 1 :\n        ((lead >> 4) == 0b1110) ? 2 :\n        ((lead >> 3) == 0b11110) ? 3 :\n        throw std::out_of_range(\"invalid UTF code point was detected.\");\n\n    while (secondary_chars) {\n      if (-65 < *(str++)) {\n        throw std::out_of_range(\"invalid UTF code point was detected.\");\n      }\n\n      --secondary_chars;\n    }\n\n    ++count;\n  }\n\n  return count;\n}\n\nint main() {\n  // constexpr const char str[] = u8\"UTF-8\u3060\u3088\u301c\u3093\";\n  // char str[] = \"UTF-8\u3060\u3088\u301c\u3093\";\n  string str = \"UTF-8\u3060\u3088\u301c\u3093\";\n  size_t length = utf8_strlen(str);\n\n  printf(\"%lu\\n\", length);\n}\n```\n\n    Overwriting temp.cpp\n\n\n\n```\n!g++ temp.cpp; ./a.out\n```\n\n    \u001b[01m\u001b[Ktemp.cpp:\u001b[m\u001b[K In function \u2018\u001b[01m\u001b[Kint main()\u001b[m\u001b[K\u2019:\n    \u001b[01m\u001b[Ktemp.cpp:34:34:\u001b[m\u001b[K \u001b[01;31m\u001b[Kerror: \u001b[m\u001b[Kcannot convert \u2018\u001b[01m\u001b[Kstd::__cxx11::string {aka std::__cxx11::basic_string<char>}\u001b[m\u001b[K\u2019 to \u2018\u001b[01m\u001b[Kconst char*\u001b[m\u001b[K\u2019 for argument \u2018\u001b[01m\u001b[K1\u001b[m\u001b[K\u2019 to \u2018\u001b[01m\u001b[Ksize_t utf8_strlen(const char*)\u001b[m\u001b[K\u2019\n       size_t length = utf8_strlen(str\u001b[01;31m\u001b[K)\u001b[m\u001b[K;\n                                      \u001b[01;31m\u001b[K^\u001b[m\u001b[K\n    9\n\n\n\n```\n%%html\n<style>\n    tr td:nth-child(2) {\n        color: red;\n    }\n</style>\n\n<table border=\"1\">\n<thead>\n<tr><th>\u57fa\u672c\u7684\u306a\u578b </th><th> \u5024\u306e\u4f8b</th></tr>\n</thead>\n<tbody>\n<tr><td>\u6574\u6570 </td><td> 1</td></tr>\n<tr><td>\u6574\u6570(16\u9032\u6570) </td><td> 0x1F</td></tr>\n<tr><td>\u5c0f\u6570 </td><td> 1.0</td></tr>\n<tr><td>\u8ad6\u7406\u5024 </td><td> true</td></tr>\n<tr><td><span style=\"color: red;\">\u30a2\u30c8\u30e0</span></td><td> :atom</td></tr>\n<tr><td>\u6587\u5b57\u5217 </td><td> \"elixir\"</td></tr>\n<tr><td>\u30ea\u30b9\u30c8 </td><td> [1, 2, 3]</td></tr>\n<tr><td>\u30bf\u30d7\u30eb </td><td> {1, 2, 3}</td></tr>\n</tbody>\n</table>\n```\n\n\n<style>\n    tr td:nth-child(2) {\n        color: red;\n    }\n</style>\n\n<table border=\"1\">\n<thead>\n<tr><th>\u57fa\u672c\u7684\u306a\u578b </th><th> \u5024\u306e\u4f8b</th></tr>\n</thead>\n<tbody>\n<tr><td>\u6574\u6570 </td><td> 1</td></tr>\n<tr><td>\u6574\u6570(16\u9032\u6570) </td><td> 0x1F</td></tr>\n<tr><td>\u5c0f\u6570 </td><td> 1.0</td></tr>\n<tr><td>\u8ad6\u7406\u5024 </td><td> true</td></tr>\n<tr><td><span style=\"color: red;\">\u30a2\u30c8\u30e0</span></td><td> :atom</td></tr>\n<tr><td>\u6587\u5b57\u5217 </td><td> \"elixir\"</td></tr>\n<tr><td>\u30ea\u30b9\u30c8 </td><td> [1, 2, 3]</td></tr>\n<tr><td>\u30bf\u30d7\u30eb </td><td> {1, 2, 3}</td></tr>\n</tbody>\n</table>\n\n\n\n```\nimport matplotlib.pyplot as plt\nfig = plt.figure(figsize=(6,4))\nax = fig.add_subplot()\nx = [0,6,7,8,9,11,12,13,14,15,16,17,22]\ny = [0,22,26,29.5,33,40.5,44,47.5,51,54.5,59,62,80]\nax.plot(x,y)\nplt.show()\n```\n\n\n```\n# \u4e09\u89d2\u95a2\u6570 trigonometry\nimport math\nmath.tan(24/180*math.pi)\n```\n\n\n\n\n    0.4452286853085361\n\n\n\n15.5. A bit of number theory with SymPy\n\nhttps://ipython-books.github.io/155-a-bit-of-number-theory-with-sympy/\n\n\u3092\u306a\u305e\u3063\u3066\u307f\u3088\u3046\u3002\n\n\u5408\u540c\u7b97\u8853\u3092 sypy \u3067\u3067\u304d\u308b\u304b\u3002 \u3068\u3044\u3046\u8ab2\u984c\u3002 number theory \u306b\u9053\u5177\u7acb\u3066\u306f\u3042\u308b\u307f\u305f\u3044\u306a\u306e\u3060\u304c\u3001\u5408\u540c $\\equiv$ \u304c\u8868\u793a\u3067\u304d\u306a\u3044\u3057\u3001\u3088\u304f\u308f\u304b\u3089\u306a\u3044\u306e\u3067\u30a6\u30ed\u30a6\u30ed\u3057\u3066\u3044\u308b\u3068\u3053\u308d\n\nchinese remainder theorem\n\n\u3068\u8a00\u3046\u554f\u984c\u3092\u89e3\u3044\u3066\u3044\u308b\u3002\n\n\n\n\n# \u30c1\u30a7\u30c3\u30af\u30de\u30fc\u30af check mark\n$\\checkmark$\n$\u2713$\n\n\u2713\n\n\n\n\n\n```\nfrom sympy.ntheory.modular import *\nimport sympy.ntheory\ndir(sympy.ntheory)\n```\n\n\n```\nfrom sympy import *\nprint(isprime (2017))\nprint(nextprime(2017))\nprint(nextprime(8))\n#=> from sympy.ntheory \u3068\u3057\u306a\u3044\u3067\u3082 nextprime \u3068\u304b\u304c\u5165\u308b\u3002\n```\n\n    True\n    2027\n    11\n\n\n\n```\nfrom sympy import *\n# prime(n) \u306f n \u756a\u76ee\u306e\u7d20\u6570\nprint(prime(1000))\nprint(prime(1))\n# primepi \u306f n \u4ee5\u4e0b\u306e\u7d20\u6570\u306e\u6570\nprint(primepi(2017))\nprint(primepi(3)) #=> {2,3} => 2 \u500b\nprint(primepi(10)) #=> 2,3,5,7 => 4\u500b\n\n```\n\n    7919\n    2\n    306\n    2\n    4\n\n\n\n```\nimport numpy as np\nimport matplotlib.pyplot as plt\nx = np.arange(2, 10000)\nfig, ax = plt.subplots(1, 1, figsize=(6, 4))\nax.plot(x, list(map(primepi, x)), '-k',\n        label='$\\pi(x)$')\nax.plot(x, x / np.log(x), '--k',\n        label='$x/\\log(x)$')\nax.legend(loc=2)\n```\n\n\n```\nprint(factorint(1998))\n```\n\n    {2: 1, 3: 3, 37: 1}\n\n\n8.  Finally, a small problem. A lazy mathematician is counting his marbles. When they are arranged in three rows, the last column contains one marble. When they form four rows, there are two marbles in the last column, and there are three with five rows. How many marbles are there? (Hint: The lazy mathematician has fewer than 100 marbles.)\n\n\n```\nfrom sympy.ntheory.modular import solve_congruence\nsolve_congruence((1, 3), (2, 4), (3, 5))\n```\n\n\n\n\n    (58, 60)\n\n\n\n(58,60) \u306e\u610f\u5473\u306f congruence \u3092\u6e80\u8db3\u3055\u305b\u308b\u306e\u306f 58 \u3092\u59cb\u3081\u3068\u3057\u3066\u3001\u305d\u308c\u306b 60 \u3092\u8db3\u3057\u305f\u6570\u306f\u3059\u3079\u3066\u3002\n\n\n```\n# \u8ab2\u984c\n# y= ax*b \u306b\u306a\u308b\u3088\u3046\u306a\u6563\u5e03\u56f3\u3092\u63cf\u304f\n# \u305d\u306e\u305f\u3081\u306b\n# 1. y=ax+b \u306e\u30b0\u30e9\u30d5\u3092 matplotlib\u3067\u63cf\u304f => \u30d9\u30fc\u30b9\n# random\u306e\u4f7f\u3044\u65b9\u3092\u8003\u3048\u308b\n\n```\n\n\n```\nimport matplotlib.pyplot as plt\nimport numpy as np\nfig, ax = plt.subplots() \n\ndata = {'a': np.arange(50),\n        'c': np.random.randint(0, 50, 50),\n        'd': np.random.randn(50)}\ndata['b'] = data['a'] + 10 * np.random.randn(50)\ndata['d'] = np.abs(data['d']) * 100\n\n# ax.scatter('a', 'b', c='c', s='d', data=data)\nax.scatter(data['a'], data['b'], c=data['c'], s=data['d'])\n# ax.set_xlabel('entry a')\n# ax.set_ylabel('entry b')\n# ax.axis('scaled')\n# ax.set_axis_off()\nplt.show()\n```\n\n\n```\nimport matplotlib.pyplot as plt\nimport numpy as np\n# fig, ax = plt.subplots() \n\ndata = {'a': np.arange(3),\n        'c': np.random.randint(0, 50, 3),\n        'd': np.random.randn(3)}\ndata['b'] = data['a'] + 10 * np.random.randn(3)\ndata['d'] = np.abs(data['d']) * 100\n\nprint(data['a'])\n# ax.scatter('a', 'b', c='c', s='d', data=data)\n# ax.set_xlabel('entry a')\n# ax.set_ylabel('entry b')\n# plt.show()\n```\n\n    [0 1 2]\n\n\n\n```\nimport matplotlib.pyplot as plt\nimport numpy as np\n# fig, ax = plt.subplots() \n\nprint (10*np.random.randn(3))\n\n# x = [1,2,3]\n# y = x + np.random.randn(3)\n\n# ax.scatter(x,y)\n# plt.show()\n```\n\n    [-4.72102573  8.84976573  2.39627047]\n\n\n\n```\nfrom sympy.abc import *\nfrom sympy import *\nexpr = 5 * sqrt(2) - 7\nexpr = expr**Rational(1,3)\ndisplay(expr)\nsolve((sqrt(2)*x +y)**3 - (expr)**3)\n```\n\n\n$\\displaystyle \\sqrt[3]{-7 + 5 \\sqrt{2}}$\n\n\n\n\n\n    [{x: nan}]\n\n\n\n# \u3053\u306e\u30ce\u30fc\u30c8\u306e\u8aad\u307f\u65b9\n1. colab \u3067\u958b\u304f\n1. \u4e0a\u306e\u65b9\u306e\u30e1\u30cb\u30e5\u30fc\u3067\u30c9\u30e9\u30a4\u30d6\u306b\u30b3\u30d4\u30fc\u3092\u62bc\u3059\n1. \u30bb\u30eb\u3092\u5b9f\u884c\u3057\u306a\u304c\u3089\u8aad\u3080\n\n&nbsp;\n\n# \u5a92\u4ecb\u5909\u6570\n\n\u5a92\u4ecb\u5909\u6570 matplotlib \u30b0\u30e9\u30d5\n\n\u5a92\u4ecb\u5909\u6570 Parameter\n\nhttp://www.yamamo10.jp/yamamoto/comp/Python/library/Matplotlib/implicit/index.php\n\n\u9670\u95a2\u6570 implicit function\n\n---\n\u96c6\u5408\u3068\u4f4d\u76f8\u3092\u306a\u305c\u5b66\u3076\u306e\u304b\u3000\n\n\u6570\u5b66\u306e\u57fa\u790e\u3068\u3057\u3066\u6839\u3065\u304f\u307e\u3067\u306e\u6b74\u53f2\u3000\n\n\u85e4\u7530\u535a\u53f8\n\n\u306a\u304b\u306a\u304b\u3044\u3044\u984c\u540d\u3060\u304c\u4e91\u3005\u3002\n\n\u3059\u3053\u3057\u8aad\u3093\u3067\u307f\u3088\u3046\u3002\n\n\n\n\u30d5\u30fc\u30ea\u30a8\u7d1a\u6570\u304b\u3089\u59cb\u307e\u3063\u3066\u3044\u308b\n\n\u71b1\u4f1d\u5c0e\u65b9\u7a0b\u5f0f\n\n\u504f\u5fae\u5206\u65b9\u7a0b\u5f0f\n\n$$\n\\frac{\\partial u}{\\partial t} = \\frac{\\partial^2 u}{\\partial^2 x} \\tag {1.1}\n$$\n\n\u3053\u308c\u306f\u3044\u3044\u304c\u3001\u305d\u306e\u3042\u3068\u306e\u30d5\u30fc\u30ea\u30a8\u7d1a\u6570\u306e\u8aac\u660e\u304c\u8aad\u3081\u306a\u3044\u3002 \n\n\u3042\u3001\u308f\u304b\u3089\u306a\u3044\u3001\u3068\u8a00\u3046\u3088\u308a\u3001\u8aad\u3081\u306a\u3044\u3001\u306f\u3044\u3044\u306d!!!!\n\n\u305d\u308c\u306b\u3057\u3088\u3046\u3002\n\n\n```\n# sympy \u30d5\u30fc\u30ea\u30a8 \u3067\u691c\u7d22\nfrom sympy import *\nimport mpmath\n# fourier 5\u56de\u7d1a\u6570\u5c55\u958b\nl = [-mpmath.pi, mpmath.pi]\nf0 = lambda x:sign(sin(x))\ncs = mpmath.fourier(f0, l, 5)\nf1 = lambda x: mpmath.fourierval(cs, l, x)\nmpmath.plot([f0, f1], xlim=l)\n```\n\n# \u6570\u5f0f\u756a\u53f7\u3092\u632f\u308b\nmarkdown \u6570\u5f0f\u756a\u53f7\n\n[Jupyter Notebook]Markdown \u306e\u6570\u5f0f\u306b\u6570\u5f0f\u756a\u53f7\u3092\u632f\u3063\u3066\u3001\u53c2\u7167\u3059\u308b\n\n\u30e1\u30e2 \u8a18\u4e8b\u306b\u306f `\\label{a}` \u304c\u4f7f\u3048\u308b\u3068\u66f8\u3044\u3066\u3042\u308b\u304c\u3001\u5b9f\u969b\u306b\u306f\u4f7f\u3048\u306a\u3044\u3002\n\n\n$$y'+ f(x)y = g(x) \\tag {1.5}$$\n\n$$y'+ f(x)y = g(x) \\tag{1.2}$$\n\n$\\ref{a}$ \u306f\u30e9\u30d9\u30eb\u3067\u3059\u3002\n\n$$\n\\frac{\\partial u}{\\partial t} = \\alpha \\nabla ^2 u \\tag{1}\n$$\n\n$(\\ref{a})$\u306f\u71b1\u62e1\u6563\u65b9\u7a0b\u5f0f\u3067\u3059\u3002\n\n$\n\\begin{equation}\n\\frac{\\partial u}{\\partial t} = \\alpha \\nabla ^2 u \\tag{2}\n\\end{equation}\n$\n\n$(\\ref{b})$\u3082\u71b1\u62e1\u6563\u65b9\u7a0b\u5f0f\u3067\u3059\u3002\n\n$$ x \\tag {8.5}$$\n\n$(\\ref{c})$\u3082\u71b1\u62e1\u6563\u65b9\u7a0b\u5f0f\u3067\u3059\u3002\n\n\n$$\n\\frac{\\partial u}{\\partial t} = \\alpha \\nabla ^2 u tag{1}\n$$\n$(\\ref{d})$\u306f\u71b1\u62e1\u6563\u65b9\u7a0b\u5f0f\u3067\u3059\u3002\n\n# \u5927\u6ce2\u62ec\u5f27\u306b\u3088\u308b\u9023\u7acb\u65b9\u7a0b\u5f0f cases, align, array\n\n$$\\begin{cases}\nx = u + 1 \\\\\ny = v + 2\n\\end{cases}$$ \n\n$$\n\\left \\{\n\\begin{align}\n  x &=& y \\\\\n  y &=& this is a  pen\n\\end{align}\n\\right .\n$$\n\n$\n\\left \\{\n\\begin{array}{rrrr}\n    3 x + & y+& 2z=& 9 \\\\\n    x - & 2 y + & + z =& 8\\\\\n    -2x-& y+& z=& -3\n\\end{array}\n\\right . \\\\\n$\n\n\n```\n# 3\u5143\u9023\u7acb1\u6b21\u65b9\u7a0b\u5f0f p.89\n%%latex\n\\displaystyle\n\\left \\{\n\\begin{array}{rrrr}\n    3 x + & y+& 2z=& 9 \\\\\n    x - & 2 y + & + z =& 8\\\\\n    -2x-& y+& z=& -3\n\\end{array}\n\\right . \\\\\n\u3092\u89e3\u304f\u3002\n```\n\n\n\\displaystyle\n\\left \\{\n\\begin{array}{rrrr}\n    3 x + & y+& 2z=& 9 \\\\\n    x - & 2 y + & + z =& 8\\\\\n    -2x-& y+& z=& -3\n\\end{array}\n\\right . \\\\\n\u3092\u89e3\u304f\u3002\n\n\n# \u30b9\u30da\u30fc\u30b9\u5b9f\u9a13\n$A\\;{}\\;{}\\;{}\\;{}\\;{}\\;{}\\;{}\\;{}\\;{}\\;{}B$  \n$A\\ {}\\ {}\\ {}\\ {}\\ {}\\ {}\\ {}\\ {}\\ {}\\ {}B$\n\n$A\\;{}\\;{}\\;{}\\;{}\\;{}\\;{}\\;{}\\;{}\\;{}\\;{}B$  \n$A\\:{}\\:{}\\:{}\\:{}\\:{}\\:{}\\:{}\\:{}\\:{}\\:{}B$  \n\n$A\\quad{}\\quad{}B$  \n$A\\qquad B$  \n$A\\quad\\quad B$  \n\n\n\n# \u30a4\u30d7\u30b7\u30ed\u30f3\u30c7\u30eb\u30bf\u8ad6\u6cd5\n\nlatex \u3067\u8ad6\u7406\u5f0f\u3001\u8ad6\u7406\u8a18\u53f7\u6587\u3092\u66f8\u3044\u3066\u3044\u3066\u3001\u30c6\u30ad\u30b9\u30c8\u306b\u3088\u3063\u3066\u62ec\u5f27 (\u4e38\u62ec\u5f27 parenthesis\u3001\u89d2\u62ec\u5f27 bracket\u3001\u6ce2\u62ec\u5f27 braces) \u306e\u4f7f\u3044\u65b9\u306b\u63fa\u308c\u304c\u3042\u3063\u305f\u308a\u3057\u3066\u3001\u3042\u3068\u30ab\u30f3\u30de\u306e\u4f7f\u3044\u65b9\u3001\u3069\u3046\u3044\u3046\u5834\u5408\u306b\u7701\u7565\u3059\u308b\u306e\u304b\u3002 \u3068\u8003\u3048\u3066\u3044\u3066\u30a4\u30d7\u30b7\u30ed\u30f3\u30c7\u30eb\u30bf\u8ad6\u6cd5\u306e\u6570\u5f0f\u3067\u6bd4\u3079\u3088\u3046\u3001\u3068\u601d\u3044\u3064\u304d\u307e\u3057\u305f\u3002\n\n\u65e5\u672c\u306e\u96e2\u6563\u6570\u5b66\u306a\u3069\u306e\u30c6\u30ad\u30b9\u30c8\u3067\u306f\u6b21\u306e\u3088\u3046\u306a\u8868\u793a\u306b\u306a\u3063\u3066\u3044\u308b\u3002\n\n$\\forall\\varepsilon \\gt 0 \\;\\;\\exists\\delta \\gt 0 \\;\\; \\forall x \\in \\mathbf R \\;\\;(0 \\lt |x - a| \\lt \\delta\\implies |f(x) - f(a)| \\lt \\varepsilon)$\n\n\u65e5\u672c\u8a9e\u306e\u30a6\u30a3\u30ad\u30da\u30c7\u30a3\u30a2\u3067\u306f\u6b21\u306e\u3088\u3046\u306a\u8868\u793a\u306b\u306a\u3063\u3066\u3044\u305f\u3002\n\n${}^{\\forall} \\varepsilon \\gt 0,\\;^{\\exists} \\delta \\gt 0 ;\\;^{\\forall} x \\in \\mathbf R\\;[0 \\lt |x - a| \\lt \\delta\\implies |f(x) - f(a)| \\lt \\varepsilon]$\n\n\u82f1\u8a9e\u3067\u306f epsilon-delta definition of limit \u3068\u8a00\u3046\u305d\u3046\u3067\u3059\u3002\n\n\u82f1\u8a9e\u306e\u30a6\u30a3\u30ad\u30da\u30c7\u30a3\u30a2\u3067\u306f\u6b21\u306e\u3088\u3046\u306a\u8868\u793a\u306b\u306a\u3063\u3066\u3044\u305f\u3002\n\n$\\forall\\varepsilon \\gt 0,\\;\\exists\\delta \\gt 0 ;\\;\\forall x \\in \n\\mathbf R,\\;0 \\lt |x - a| \\lt \\delta\\implies |f(x) - f(a)| \\lt \\varepsilon$\n\n\u305f\u3076\u3093\u3069\u308c\u3082\u6b63\u3057\u3044\u306e\u3060\u3068\u3057\u3066\u3001\u81ea\u5206\u306e\u597d\u307f\u3068\u308f\u304b\u308a\u3084\u3059\u3055\u3067\u306f\u65e5\u672c\u306e\u30c6\u30ad\u30b9\u30c8\u306e\u8868\u793a\u304c\u3088\u3044\u3068\u601d\u3046\u3002 \u30ab\u30f3\u30de\u3084\u30bb\u30df\u30b3\u30ed\u30f3\u3067\u660e\u78ba\u306b\u533a\u5225\u3067\u304d\u308b\u306e\u304b\u3082\u3057\u308c\u306a\u3044\u304c\u3001\u30ab\u30f3\u30de\u3084\u30bb\u30df\u30b3\u30ed\u30f3\u306f\u8ad6\u7406\u8a18\u53f7\u5f0f\u4ee5\u5916\u3067\u3082\u4f7f\u308f\u308c\u308b\u306e\u3067\u3001\u3044\u305a\u308c\u306b\u3057\u3066\u3082\u6587\u8108\u3067\u78ba\u8a8d\u3057\u306a\u304f\u3066\u306f\u3044\u3051\u306a\u3044\u306e\u3067\u3001\u305d\u308c\u306a\u3089\u3070\u30b9\u30da\u30fc\u30b9\u304c\u3088\u3044\u3002 \u547d\u984c\u3092\u89d2\u62ec\u5f27 bracket \u3067\u56f2\u3080\u306e\u306f\u8a71\u3068\u3057\u3066\u306f\u308f\u304b\u308b\u304c\u901a\u5e38\u306e\u4e38\u62ec\u5f27 parenthesis \u3067\u5341\u5206\u3060\u3068\u601d\u3046\u3002 \u305d\u306e\u8a3c\u62e0\u306b\u82f1\u8a9e\u306e\u30a6\u30a3\u30ad\u30da\u30c7\u30a3\u30a2\u3067\u306f\u56f2\u3063\u3066\u3082\u3044\u306a\u3044\u3002 \u56f2\u307e\u306a\u3044\u30eb\u30fc\u30eb\u306f\u308f\u304b\u308a\u306b\u304f\u304f\u306a\u308b\u3068\u601d\u3046\u306e\u3067\u306a\u3093\u3089\u304b\u306e\u65b9\u6cd5\u3067\u56f2\u3063\u305f\u65b9\u304c\u3088\u3044\u3068\u601d\u3046\u3002\n\n\u3042\u3068\u3001\u5168\u79f0\u8a18\u53f7 $\\forall$ \u3068 \u5b58\u5728\u8a18\u53f7 $\\exists$ \u3092\u5c0f\u3055\u304f\u524d\u4e0a\u4ed8\u304d\u306b\u3059\u308b\u306e\u306f\u307f\u3093\u306a\u304c\u540c\u3058\u30eb\u30fc\u30eb\u306a\u3089\u3070\u308f\u304b\u308a\u3084\u3059\u3044\u3068\u306f\u601d\u3046\u304c\u63fa\u308c\u304c\u3042\u308b\u306e\u3060\u3063\u305f\u3089\u666e\u901a\u306e\u5927\u304d\u3055\u3067\u5909\u6570\u306e\u524d\u306b\u3064\u3051\u3066\u554f\u984c\u306a\u3044\u3068\u601d\u3046\u3002\n\nlatex \u3067\u306e\u30bd\u30fc\u30b9\u306f\u4ee5\u4e0b\u3067\u3042\u308b\u3002\n\n&nbsp;\n\n\u65e5\u672c\u306e\u306e\u30c6\u30ad\u30b9\u30c8\n```\n$\\forall\\varepsilon \\gt 0 \\;\\;\\exists\\delta \\gt 0 \\;\\; \\forall x \\in \\mathbf R \\;\\;(0 \\lt |x - a| \\lt \\delta\\implies |f(x) - f(a)| \\lt \\varepsilon)$\n```\n\u65e5\u672c\u8a9e\u306e\u30a6\u30a3\u30ad\u30da\u30c7\u30a3\u30a2\n```\n${}^{\\forall} \\varepsilon \\gt 0,\\;^{\\exists} \\delta \\gt 0 ;\\;^{\\forall} x \\in \\mathbf R\\;[0 \\lt |x - a| \\lt \\delta\\implies |f(x) - f(a)| \\lt \\varepsilon]$\n```\n\u82f1\u8a9e\u306e\u30a6\u30a3\u30ad\u30da\u30c7\u30a3\u30a2\n```\n$\\forall\\varepsilon \\gt 0,\\;\\exists\\delta \\gt 0 ;\\;\\forall x \\in \n\\mathbf R,\\;0 \\lt |x - a| \\lt \\delta\\implies |f(x) - f(a)| \\lt \\varepsilon$\n```\n\n\n\n\n\n\n\n\n\n$\\forall \\varepsilon > 0,\\  \\exists \\delta > 0 ;\\; \\forall x \\in \\mathbf R \\ (0 < |\\:x - a\\:| < \\delta \\: \\Rightarrow \\: |\\:f(x) - f(a)\\:| < \\epsilon)$\n\n\n```\nimport matplotlib.pyplot as plt\nfrom matplotlib_venn import venn3\nA = set([9,3,6])\nB = set([2,4,6,8])\nC = set([0,5,1,7])\nv = venn3([A,B,C], ('P', 'Q', 'U'))\n\nv.get_label_by_id('100').set_text('\\n'.join(map(str,A-B)))\nv.get_label_by_id('110').set_text('\\n'.join(map(str,A&B)))\nv.get_label_by_id('010').set_text('\\n'.join(map(str,B-A)))\nv.get_label_by_id('001').set_text('\\n'.join(map(str,C)))\nv.get_patch_by_id('001').set_color('white')\nplt.axis('on')\nplt.show()\n```\n\n\n```\nimport matplotlib.pyplot as plt\nfrom matplotlib_venn import venn3\nA = set([9,3,6])\nB = set([2,4,6,8])\nC = set([0,5,1,7])\nvenn3([A,B,C], ('P', 'Q', 'U'))\n\n# v.get_label_by_id('100').set_text('\\n'.join(map(str,A-B)))\n# v.get_label_by_id('110').set_text('\\n'.join(map(str,A&B)))\n# v.get_label_by_id('010').set_text('\\n'.join(map(str,B-A)))\n# v.get_label_by_id('001').set_text('\\n'.join(map(str,C)))\n# v.get_patch_by_id('001').set_color('white')\n# plt.axis('on')\nplt.show()\n```\n\n\n\n\n```\n# \u30d9\u30f3\u56f3 venn diagram\nfrom matplotlib_venn import venn3\nimport matplotlib.pyplot as plt\n\n\nA = set([1, 2])\nB = set([2, 3, 4])\nC = set([1,2,3,4,5,6,7,8,9,10,11])\n\nvenn3(subsets=(A,B,C))\nplt.show()\n\n```\n\n\n```\n# sin 3\u03b1 \u3092 sin \u03b1 \u306e\u5f0f\u306b\u5909\u5f62\u3059\u308b\n# \u5f0f\u5909\u5f62\u306b\u3088\u308b\u8a3c\u660e\u30d5\u30a9\u30fc\u30de\u30c3\u30c8\u306f\u6b21\u306e\u3088\u3046\u306b\u3059\u308b\n# \u307e\u305a latex \u3067\u3001 \u6b21\u306b sympy \u3067\u66f8\u3044\u3066\u307f\u308b\n%%latex\n\\displaystyle\n\n\\sin 3 \u03b1\\\\\n= \\{\u5358\u7d14\u5909\u5f62\u306b\u3088\u308a\\}\\\\\n\\quad \\sin(2\u03b1 + \u03b1)\\\\\n= \\{\u52a0\u6cd5\u5b9a\u7406~ \\sin(\u03b1 + \u03b2) = \\sin \u03b1 \\cos \u03b2 + \\cos \u03b1 \\sin \u03b2 ~\u306b\u3088\u308a\\}\\\\\n\\quad \\sin 2\u03b1 \\cos \u03b1 + \\cos 2\u03b1 \\sin \u03b1 \\\\\n= \\{\u516c\u5f0f \\sin 2\u03b1 = 2 \\sin \u03b1 \\cos \u03b1 ~\u306b\u3088\u308a\\}\\\\\n\\quad 2 \\sin \u03b1 \\cos^2 \u03b1 + \\cos 2\u03b1 \\sin \u03b1 \\\\\n= \\{\u516c\u5f0f \\cos 2\u03b1 = \\cos^2 \u03b1 \u2212 \\sin^2 \u03b1 ~\u306b\u3088\u308a\\}\\\\\n\\quad 2 \\sin \u03b1 \\cos^2 \u03b1 + (\\cos^2 \u03b1 \u2212 \\sin^2 \u03b1) \\sin \u03b1 \\\\\n= \\{\\sin \u03b1~\u3067\u62ec\u3063\u3066\\}\\\\\n\\quad \\sin \u03b1 (2 \\cos^2 \u03b1+ \\cos^2\u03b1 - \\sin^2 \u03b1)\\\\\n= \\{\u5358\u7d14\u8a08\u7b97\\}\\\\\n\\quad \\sin \u03b1 (3 \\cos^2 \u03b1 - \\sin^2 \u03b1)\\\\\n= \\{\u516c\u5f0f \\sin^2 \u03b1+ \\cos^2 \u03b1= 1 \\Longrightarrow \\cos^2 \u03b1 = 1 - \\sin^2 \u03b1~ \u306b\u3088\u308a\\}\\\\\n\\quad \\sin \u03b1 (3 - 3 \\sin^2 \u03b1 - \\sin^2 \u03b1)\\\\\n= \\{\u5358\u7d14\u8a08\u7b97\\}\\\\\n\\quad \\sin \u03b1 (3 - 4 \\sin^2 \u03b1)\\\\\n```\n\n\n\\displaystyle\n\n\\sin 3 \u03b1\\\\\n= \\{\u5358\u7d14\u5909\u5f62\u306b\u3088\u308a\\}\\\\\n\\quad \\sin(2\u03b1 + \u03b1)\\\\\n= \\{\u52a0\u6cd5\u5b9a\u7406~ \\sin(\u03b1 + \u03b2) = \\sin \u03b1 \\cos \u03b2 + \\cos \u03b1 \\sin \u03b2 ~\u306b\u3088\u308a\\}\\\\\n\\quad \\sin 2\u03b1 \\cos \u03b1 + \\cos 2\u03b1 \\sin \u03b1 \\\\\n= \\{\u516c\u5f0f \\sin 2\u03b1 = 2 \\sin \u03b1 \\cos \u03b1 ~\u306b\u3088\u308a\\}\\\\\n\\quad 2 \\sin \u03b1 \\cos^2 \u03b1 + \\cos 2\u03b1 \\sin \u03b1 \\\\\n= \\{\u516c\u5f0f \\cos 2\u03b1 = \\cos^2 \u03b1 \u2212 \\sin^2 \u03b1 ~\u306b\u3088\u308a\\}\\\\\n\\quad 2 \\sin \u03b1 \\cos^2 \u03b1 + (\\cos^2 \u03b1 \u2212 \\sin^2 \u03b1) \\sin \u03b1 \\\\\n= \\{\\sin \u03b1~\u3067\u62ec\u3063\u3066\\}\\\\\n\\quad \\sin \u03b1 (2 \\cos^2 \u03b1+ \\cos^2\u03b1 - \\sin^2 \u03b1)\\\\\n= \\{\u5358\u7d14\u8a08\u7b97\\}\\\\\n\\quad \\sin \u03b1 (3 \\cos^2 \u03b1 - \\sin^2 \u03b1)\\\\\n= \\{\u516c\u5f0f \\sin^2 \u03b1+ \\cos^2 \u03b1= 1 \\Longrightarrow \\cos^2 \u03b1 = 1 - \\sin^2 \u03b1~ \u306b\u3088\u308a\\}\\\\\n\\quad \\sin \u03b1 (3 - 3 \\sin^2 \u03b1 - \\sin^2 \u03b1)\\\\\n= \\{\u5358\u7d14\u8a08\u7b97\\}\\\\\n\\quad \\sin \u03b1 (3 - 4 \\sin^2 \u03b1)\\\\\n\n\n\n```\n# sympy \u3067\u66f8\u3044\u3066\u307f\u308b\u5b9f\u9a13\nfrom sympy import *\nfrom IPython.display import Markdown\ninit_printing()\n\u03b1, \u03b2 = symbols('\u03b1 \u03b2')\ndisplay (sin (3*\u03b1))\ndisplay(Markdown(\"$\\sin (3\u03b1)$ \u3092 $\\sin(\u03b1)$ \u3060\u3051\u3067\u8868\u793a\u3059\u308b\u3002\"))\ndisplay(Markdown(\"\u307e\u305a\u516c\u5f0f\"))\ndisplay (Eq(sin(\u03b1+\u03b2),expand(sin(\u03b1+\u03b2),trig=True)))\ndisplay(Markdown(\"\u3088\u308a\u3001$\u03b1 = 2\u03b1,~\u03b2 = \u03b1$ \u3068\u304a\u304f\u3068\"))\ndisplay(Eq(sin (3*\u03b1),(sin(2*\u03b1)*cos(\u03b1)+cos(2*\u03b1)*sin(\u03b1))))\ndisplay(Markdown(\"\u9805\u306e\u9806\u5e8f\u306f\u3068\u308a\u3042\u3048\u305a\u6c17\u306b\u3057\u306a\u3044\u3002\"))\ndisplay(Markdown(\"\u307e\u305f\u540c\u3058\u516c\u5f0f\"))\ndisplay (Eq(sin(\u03b1+\u03b2),expand(sin(\u03b1+\u03b2),trig=True)))\ndisplay(Markdown(\"\u3067\u3001$\u03b2 = \u03b1$ \u3068\u304a\u304f\u3068\"))\ndisplay (Eq(sin(2*\u03b1),expand(sin(2*\u03b1),trig=True)))\ndisplay(Markdown(\"\u3092\u7528\u3044\u3066 $\\sin(2\u03b1)$ \u3092\u6d88\u53bb\u3059\u308b\u3068\"))\ndisplay(Eq(sin (3*\u03b1),(expand(sin(2*\u03b1)*cos(\u03b1),trig=True)+cos(2*\u03b1)*sin(\u03b1))))\ndisplay(Markdown(\"$\\cos(2\u03b1)$\u306b\u3064\u3044\u3066\u516c\u5f0f\"))\ndisplay (Eq(cos(2*\u03b1),expand(cos(2*\u03b1),trig=True)))\ndisplay(Markdown(\"\u3092\u7528\u3044\u3066 $\\cos(2\u03b1)$ \u3092\u6d88\u53bb\u3059\u308b\u3068\"))\ndisplay(Eq(sin (3*\u03b1),(expand(sin(2*\u03b1)*cos(\u03b1)+cos(2*\u03b1)*sin(\u03b1),trig=True))))\ndisplay(Markdown(\"\u6b21\u306b\u516c\u5f0f\u3092\u4f7f\u3063\u3066 $\\cos^2(\u03b1)$ \u3092\u6d88\u3059\u305f\u3081\u306b\u516c\u5f0f\u3092\u5909\u5f62\u3059\u308b\u3002\"))\ndisplay(Eq((sin(\u03b1))**2+(cos(\u03b1))**2,1))\ndisplay(Eq((cos(\u03b1))**2,1-(sin(\u03b1))**2))\ndisplay(Markdown(\"\u3092\u4ee3\u5165\u3059\u308b\"))\ndisplay(Eq(sin (3*\u03b1),4*sin(\u03b1)*(1-(sin(\u03b1))**2) - sin(\u03b1)))\ndisplay(Eq(sin (3*\u03b1),expand(4*sin(\u03b1)*(1-(sin(\u03b1))**2) - sin(\u03b1))))\n\n```\n\n\n```\nfrom IPython.display import Math, display\nimport sympy as sy\nx = sy.symbols('x')\nexpression = sy.sin(x)\ndisplay(Math('f(x) =' + sy.latex(expression)))\ndisplay(Math('\\\\left[ \\\\frac{3 \\\\mu_2^2+\\\\sigma_2^2\\\\log(2)}{2\\\\mu_2} \\\\right]'))\n```\n\n\n$$f(x) =\\sin{\\left (x \\right )}$$\n\n\n\n$$\\left[ \\frac{3 \\mu_2^2+\\sigma_2^2\\log(2)}{2\\mu_2} \\right]$$\n\n\n\n```\nfrom sympy import *\ninit_printing()\n\nx, f = symbols('x, f')\nmu = symbol\ndisplay(sin(x))\ndisplay(Eq(f(x), sin(x)))\nmu = symbols(r'\\mu')\ndisplay(3*mu)\n# expression = sy.sin(x)\n# display(Math('f(x) =' + sy.latex(expression)))\n# display(Math('\\\\left[ \\\\frac{3 \\\\mu_2^2+\\\\sigma_2^2\\\\log(2)}{2\\\\mu_2} \\\\right]'))\n```\n\n\n```latex\n%%latex\n\\left[ \\frac{3 \\mu_2^2+ \\sigma_2^2 \\log(2)}{ 2\\mu_2} \\right]\n```\n\n\n\\left[ \\frac{3 \\mu_2^2+ \\sigma_2^2 \\log(2)}{ \\mu_2} \\right]\n\n\n$$\n\\left[ \\frac{3 \\mu_2^2+ \\sigma_2^2 \\log(2)}{ 2 \\mu_2} \\right]\n$$\n\n# sympy \u306e latex output display \u3068\u304b\n\n\n```\nfrom sympy import *\ninit_printing()\na, b = symbols('a, b')\na\n```\n\n\n```\nfrom sympy import *\ndisplay(a**3)\n```\n\n\n```\nfrom sympy import *\ninit_printing()\na, b = symbols('a_{i-1} n_3')\ndisplay (a)\ndisplay (b)\n```\n\n\n\n\n```\nxx = [\"even\" if i % 2 == 0 else \"odd\" for i in range(10)]\n\nprint(xx)\n```\n\n    ['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']\n\n\n\u30de\u30fc\u30af\u30c0\u30a6\u30f3\u3067\u30c9\u30eb\u30de\u30fc\u30af\u3092\u8868\u793a\u3059\u308b\u65b9\u6cd5\n\n`&#36;` => &#36;5 \u30c9\u30eb\n\n\u304c\u78ba\u5b9f\u304b\u3002\n\n`&dollar;` => &dollar;10 \u30c9\u30eb\n\n\u3082\u3068\u308a\u3042\u3048\u305a colab \u3067\u306f\u4f7f\u3048\u308b\u3002\u3053\u3061\u3089\u306f\u899a\u3048\u3084\u3059\u3044\u3002\n\n&pound;4\u30dd\u30f3\u30c9\n\n\u306f `&pound;` \u3068\u3057\u305f\u3089\u51fa\u305f\u3002\n\n&euro;20\u30e6\u30fc\u30ed\n\n&yen;100\u5186\n\nhttps://dev.w3.org/html5/html-author/charref  \n\ncharacter entity reference chart  \n\u3068\u3044\u3046\u30da\u30fc\u30b8\u304c\u3042\u3063\u305f\u3002\n\n\n&dollar; T &dollar;&dollar;\n\n\u3053\u308c\u306f &dollar; \u30de\u30fc\u30af\u3067\u56f2\u3080\u3068\u30a4\u30f3\u30e9\u30a4\u30f3\u3001&dollar;&dollar; \u3067\u56f2\u3080\u3068\u6bb5\u843d\u3092\u5909\u3048\u3066\u3001\u30bb\u30f3\u30bf\u30ea\u30f3\u30b0\u3057\u3066\u8868\u793a\u3059\u308b\u3002\n\n\n$$\nx = 3\n$$\n\n\u3068\u304b\u3002\n\n\u3053\u308c\u306f \\\\$ \u30de\u30fc\u30af\u3067\u56f2\u3080\u3068\u30a4\u30f3\u30e9\u30a4\u30f3\u3001\\\\$\\\\$ \u3067\u56f2\u3080\u3068\u6bb5\u843d\u3092\u5909\u3048\u3066\u3001\u30bb\u30f3\u30bf\u30ea\u30f3\u30b0\u3057\u3066\u8868\u793a\u3059\u308b\u3002\n\n\u3053\u308c\u306f &dollar; \u30de\u30fc\u30af\u3067\u56f2\u3080\u3068\u30a4\u30f3\u30e9\u30a4\u30f3\u3001&dollar;&dollar; \u3067\u56f2\u3080\u3068\u6bb5\u843d\u3092\u5909\u3048\u3066\u3001\u30bb\u30f3\u30bf\u30ea\u30f3\u30b0\u3057\u3066\u8868\u793a\u3059\u308b\u3002\n\n&nbsp;\n\n\n#  Decision Tree\nhttps://medium.com/@rnbrown/creating-and-visualizing-decision-trees-with-python-f8e8fa394176\n\n\n```\n\n```\n\n\n```\nimport sklearn.datasets as datasets\nimport pandas as pd\niris=datasets.load_iris()\ndf=pd.DataFrame(iris.data, columns=iris.feature_names)\ny=iris.target\n```\n\n\n```\nfrom sklearn.tree import DecisionTreeClassifier\ndtree=DecisionTreeClassifier()\ndtree.fit(df,y)\n```\n\n\n\n\n    DecisionTreeClassifier(ccp_alpha=0.0, class_weight=None, criterion='gini',\n                           max_depth=None, max_features=None, max_leaf_nodes=None,\n                           min_impurity_decrease=0.0, min_impurity_split=None,\n                           min_samples_leaf=1, min_samples_split=2,\n                           min_weight_fraction_leaf=0.0, presort='deprecated',\n                           random_state=None, splitter='best')\n\n\n\n\n```\nfrom sklearn.externals.six import StringIO  \nfrom IPython.display import Image  \nfrom sklearn.tree import export_graphviz\nimport pydotplus\ndot_data = StringIO()\nexport_graphviz(dtree, out_file=dot_data,  \n                filled=True, rounded=True,\n                special_characters=True)\ngraph = pydotplus.graph_from_dot_data(dot_data.getvalue())  \nImage(graph.create_png())\n```\n\n# meshgrid \u3092\u7406\u89e3\u3059\u308b\u3002\n\n\n```\nimport numpy as np\nx=np.linspace(-1,1,100)\ny=np.linspace(-1,1,100)\nx, y = np.meshgrid(x, y)\n# print(x)\nz = np.exp(-4*(x**2+y**2))\n# print(z)\n\nimport matplotlib.pyplot as plt\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.plot_surface(x,y,z, cmap=cm.jet)\nplt.show()\n```\n\n\n```\nimport numpy as np\nZ = np.zeros((5,5), [('x',float),('y',float)])\nZ['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5),\n                             np.linspace(0,1,5))\nprint(Z)\n```\n\n    [[(0.  , 0.  ) (0.25, 0.  ) (0.5 , 0.  ) (0.75, 0.  ) (1.  , 0.  )]\n     [(0.  , 0.25) (0.25, 0.25) (0.5 , 0.25) (0.75, 0.25) (1.  , 0.25)]\n     [(0.  , 0.5 ) (0.25, 0.5 ) (0.5 , 0.5 ) (0.75, 0.5 ) (1.  , 0.5 )]\n     [(0.  , 0.75) (0.25, 0.75) (0.5 , 0.75) (0.75, 0.75) (1.  , 0.75)]\n     [(0.  , 1.  ) (0.25, 1.  ) (0.5 , 1.  ) (0.75, 1.  ) (1.  , 1.  )]]\n\n\n\n```\n# import for colormaps\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n\nx=np.linspace(-10,10, num=50)\ny=np.linspace(-10,10, num=50)\n\nx, y = np.meshgrid(x, y)\n\nz = np.exp(-0.1*x**2-0.1*y**2)\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.plot_surface(x,y,z, cmap=cm.jet)\nplt.show()\n\n```\n\n\n```\n# \u5b9f\u9a13\n\n# import for colormaps\nfrom matplotlib import cm\n\n# x=np.linspace(-10,10, num=100)\n# y=np.linspace(-10,10, num=100)\nx=np.linspace(-1,1, 100)\ny=np.linspace(-1,1, 100)\nx, y = np.meshgrid(x, y)\n\n# D = np.sqrt(X*X+Y*Y)\n# z = np.exp(-0.1*x**2-0.1*y**2)\n# sigma, mu = 1.0, 0.0\n# G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )\nz = np.exp(-(x**2+y**2)**2/2.0)\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.plot_surface(x,y,z, cmap=cm.jet)\nplt.show()\n```\n\n\n```\n# \u5b9f\u9a13\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\n\ndef f(x):\n    return (math.exp(-x**2/2)) / math.sqrt(2*math.pi)\n\n\nn = np.linspace(-5.0, 5.0, 50)\n\np = []\nfor i in range(len(n)):\n    p.append(f(n[i]))\n\n# \u30b0\u30e9\u30d5\u306b\u8868\u793a\nplt.plot(n, p)\nplt.show()\n\n```\n\n# html \u3067\u5909\u6570\u3092\u6271\u3046\n\n\n```\n# css \u3092\u4f7f\u3063\u3066html\u3067\u5909\u6570\u3092\u4f7f\u3046\u3002\n# span \u3092\u4f7f\u3048\u3070\u81ea\u7531\u306a\u4f4d\u7f6e\u306b\u6c7a\u307e\u3063\u305f\u6587\u5b57\u5217\u3092\u5165\u308c\u308b\u3053\u3068\u304c\u3067\u304d\u308b\u3002\n%%html\n<style>\n    .parson1:before {\n        content: \"\u7530\u4e2d\";\n    }\n\n    p.age1:after {\n        content: \"36\u6b73\";\n    }\n</style>\n<h1>\u30b5\u30f3\u30d7\u30eb</h1>\n<p class=\"parson1\">\u306f\u7537\u306e\u5b50</p>\n<p class=\"parson1 age1\">\u306e\u5e74\u9f62\u306f</p>\n<p>\u79c1\u306e\u5f7c\u6c0f\u306f<span class=\"parson1\"></span>\u541b\u3060\u3088</p>\n```\n\n\n<style>\n    .parson1:before {\n        content: \"\u7530\u4e2d\";\n    }\n\n    p.age1:after {\n        content: \"36\u6b73\";\n    }\n</style>\n<h1>\u30b5\u30f3\u30d7\u30eb</h1>\n<p class=\"parson1\">\u306f\u7537\u306e\u5b50</p>\n<p class=\"parson1 age1\">\u306e\u5e74\u9f62\u306f</p>\n<p>\u79c1\u306e\u5f7c\u6c0f\u306f<span class=\"parson1\"></span>\u541b\u3060\u3088</p>\n\n\n\n```\n# javascript \u3092\u4f7f\u3063\u3066 html \u3067\u5909\u6570\u3092\u4f7f\u3046\n%%html\n<span class=\"name1\u2033></span>\u306f\u7537\u3067\u3059<br />\n<span class=\"name1\u2033></span>\u306e\u5e74\u9f62\u306f30\u6b73\u3067\u3059\n\n```\n\n\n<span class=\"name1\u2033></span>\u306f\u7537\u3067\u3059<br />\n<span class=\"name1\u2033></span>\u306e\u5e74\u9f62\u306f30\u6b73\u3067\u3059\n\n\n\n\n```\n# \u5b9f\u9a13\n%%html\n<!-- <button>Click me</button> -->\n<div>\n<!-- <span class=\"name1\"></span>\u306f\u7537\u3067\u3059<br> -->\n<span class=\"name1\"></span>\u306e\u5e74\u9f62\u306f30\u6b73\u3067\u3059\n<div>\n\n```\n\n\n<!-- <button>Click me</button> -->\n<div>\n<!-- <span class=\"name1\"></span>\u306f\u7537\u3067\u3059<br> -->\n<span class=\"name1\"></span>\u306e\u5e74\u9f62\u306f30\u6b73\u3067\u3059\n<div>\n\n\n\n\n```\n# \u3053\u3053\u3067 for loop \u3092\u4f7f\u3044\u305f\u304f\u306a\u3044\u306e\u3067\u3001for loop \u3092 reduce \u306b\u3059\u308b\u7814\u7a76\u3092\u59cb\u3081\u308b\n```\n\n# \u3053\u3053\u3067 for loop \u3092\u4f7f\u3044\u305f\u304f\u306a\u3044\u306e\u3067\u3001for loop \u3092 reduce \u306b\u3059\u308b\u7814\u7a76\u3092\u59cb\u3081\u308b\n\n\n\n\n```\n# 0-9 \u306e\u5408\u8a08 45 \u3092 for loop \u3092\u4f7f\u308f\u305a\u306b\u8a08\u7b97\u3059\u308b\n%%script node\nconst add = (a, b) => a + b;\nsum = Array.from(Array(10),(a,b) => b).reduce(add)\n\nconsole.log(sum) \n```\n\n    45\n\n\n\n```\n# 1-0 \u306e\u5408\u8a08 55 \u3092 for loop \u3092\u4f7f\u308f\u305a\u306b\u8a08\u7b97\u3059\u308b\n%%script node\nconst add = (a, b) => a + b;\nsum = Array.from(Array(10),(a,b) => b+1).reduce(add)\n\nconsole.log(sum) \n```\n\n    55\n\n\n\n```\n# \u8aac\u660e\n# const add = (a, b) => a + b;\n# \u306f function \u3092\u4f7f\u308f\u305a\u306b\u95a2\u6570\u3092\u5b9a\u7fa9\u3057\u3066\u3044\u308b\n%%script node\nconst add = (a, b) => a + b;\nconsole.log(add(1,2));\nfunction add2 (a, b) {return a + b};\nconsole.log(add2(2,3));\n\n```\n\n    3\n    5\n\n\n\n```\n# \u5b9f\u9a13 \u8907\u6570\u884c\n%%script node\nconst addmult = (a, b) => {\n    sum = a+b;\n    product = a*b;\n    return sum * product\n};\nconsole.log(addmult(2,3)); // 30\n```\n\n    30\n\n\n\n```\n# Array.from \u306f Array \u3092\u4f5c\u308b\n%%script node\nconsole.log(Array.from('foo'));\nconsole.log(Array.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], x => x + x));\nconsole.log(Array.from(Array(10), (a, b) => b));\n```\n\n    [ 'f', 'o', 'o' ]\n    [\n       2,  4,  6,  8, 10,\n      12, 14, 16, 18, 20,\n      22\n    ]\n    [\n      0, 1, 2, 3, 4,\n      5, 6, 7, 8, 9\n    ]\n\n\n\n```\n# colab \u3067 Array \u3092 console.log \u3067\u51fa\u529b\u3059\u308b\u3068\u4e00\u884c\u306b\u51fa\u529b\u3055\u308c\u306a\u3044\n# JSON.stringify\u3092\u4f7f\u3048\u3070\u3068\u308a\u3042\u3048\u305a\u4e00\u884c\u306b\u306a\u308b\n%%script node\nconsole.log(Array.from(Array(10), (a, b) => b));\nconsole.log(JSON.stringify(Array.from(Array(10), (a, b) => b)));\nconsole.log(JSON.stringify(Array.from({length:10}, (a, b) => b)));\nconsole.log(Array.from({length: 10}));\n```\n\n\n```\n%%script node\n//reduce\nconst  initModel = 0\nconst update = ( model, msg) =>  model + msg\nconst sum = msgs => msgs.reduce(update,  initModel)\n\nconst items = [0, 1, 2]\nconsole.log(sum(items))  //  3\n```\n\n    3\n\n\n\n```\nconst range = (start, stop) => Array.from({ length: (stop - start) + 1}, (_, i) => start + i);\n```\n\n# JavaScript\u3067JSON\u304b\u3089\u30c6\u30fc\u30d6\u30eb\u3092\u52d5\u7684\u306b\u751f\u6210\n\n\n```\n%%html\n\n<style>\n    div#paging {\n        text-align: center;\n        /* \u30b9\u30af\u30ed\u30fc\u30eb\u306b\u5bfe\u3057\u3066\u30da\u30fc\u30b8\u30f3\u30b0\u30dc\u30c3\u30af\u30b9\u306e\u4f4d\u7f6e\u3092\u56fa\u5b9a */\n        position: fixed;\n        /* \u4f4d\u7f6e\u3092\u6307\u5b9a */\n        bottom: 0;\n        right: 45%;\n    }\n\n    div#pagingbox {\n        background: #FFF;\n    }\n\n    th {\n        /* \u30d8\u30c3\u30c0\u80cc\u666f\u5857\u308a\u3064\u3076\u3057 */\n        background: #eee;\n    }\n\n    th,\n    td {\n        /* \u67a0\u7dda\u30921\u672c\u7dda\u6307\u5b9a */\n        border: solid 1px;\n        width: auto;\n    }\n\n    table {\n        /* \u67a0\u7dda\u30921\u672c\u7dda\u6307\u5b9a */\n        border: solid 1px;\n        border-collapse: collapse;\n        white-space: nowrap;\n    }\n\n    footer {\n        position: fixed;\n        width: 100%;\n        background-color: #C0C0C0;\n        padding: 15px 0;\n        bottom: 0;\n        /*\u4e0b\u306b\u56fa\u5b9a*/\n    }\n</style>\n\n<!--\u30c6\u30fc\u30d6\u30eb\u751f\u6210\u4f4d\u7f6e-->\n<div id='maintable'></div>\n\n\n\n<!--\u30da\u30fc\u30b8\u30f3\u30b0\u30dc\u30bf\u30f3\u914d\u7f6e-->\n<footer>\n    <div id=\"paging\">\n        <table>\n            <tr>\n                <tb><button id=\"prevbtn\" type=\"button\">\n                        << /button>\n                </tb>\n                <tb>\n                    <span id=\"currentpage\">currentpage</span>\n                    /\n                    <span id=\"lastpage\">lastpage</span>\n                </tb>\n                <tb><button id=\"nextbtn\" type=\"button\">></button></tb>\n            </tr>\n        </table>\n    </div>\n</footer>\n\n\n\n\n\n\n```\n\n\n\n<style>\n    div#paging {\n        text-align: center;\n        /* \u30b9\u30af\u30ed\u30fc\u30eb\u306b\u5bfe\u3057\u3066\u30da\u30fc\u30b8\u30f3\u30b0\u30dc\u30c3\u30af\u30b9\u306e\u4f4d\u7f6e\u3092\u56fa\u5b9a */\n        position: fixed;\n        /* \u4f4d\u7f6e\u3092\u6307\u5b9a */\n        bottom: 0;\n        right: 45%;\n    }\n\n    div#pagingbox {\n        background: #FFF;\n    }\n\n    th {\n        /* \u30d8\u30c3\u30c0\u80cc\u666f\u5857\u308a\u3064\u3076\u3057 */\n        background: #eee;\n    }\n\n    th,\n    td {\n        /* \u67a0\u7dda\u30921\u672c\u7dda\u6307\u5b9a */\n        border: solid 1px;\n        width: auto;\n    }\n\n    table {\n        /* \u67a0\u7dda\u30921\u672c\u7dda\u6307\u5b9a */\n        border: solid 1px;\n        border-collapse: collapse;\n        white-space: nowrap;\n    }\n\n    footer {\n        position: fixed;\n        width: 100%;\n        background-color: #C0C0C0;\n        padding: 15px 0;\n        bottom: 0;\n        /*\u4e0b\u306b\u56fa\u5b9a*/\n    }\n</style>\n\n<!--\u30c6\u30fc\u30d6\u30eb\u751f\u6210\u4f4d\u7f6e-->\n<div id='maintable'></div>\n\n\n\n<!--\u30da\u30fc\u30b8\u30f3\u30b0\u30dc\u30bf\u30f3\u914d\u7f6e-->\n<footer>\n    <div id=\"paging\">\n        <table>\n            <tr>\n                <tb><button id=\"prevbtn\" type=\"button\">\n                        << /button>\n                </tb>\n                <tb>\n                    <span id=\"currentpage\">currentpage</span>\n                    /\n                    <span id=\"lastpage\">lastpage</span>\n                </tb>\n                <tb><button id=\"nextbtn\" type=\"button\">></button></tb>\n            </tr>\n        </table>\n    </div>\n</footer>\n\n\n\n\n\n\n\n\n\n```\n# \u5b9f\u9a13 \u30a2\u30e9\u30d3\u30a2\u8a9e 1. temp.ipynb \u306e\u738b\u8c9e\u6cbb\n# css.ipynb \u306e w3schools\n# header\u306f\u3069\u3046\u3067\u3082\u3088\u3044\n# \u30a2\u30e9\u30d3\u30a2\u8a9e\u306e\u30d5\u30a9\u30f3\u30c8\u3092\u5927\u304d\u304f\u3059\u308b\u3002 \u30d5\u30a9\u30f3\u30c8\u3092\u81ea\u7531\u306b\u5909\u3048\u308b\u3002\n# json\u3092\u4f7f\u3046\n# \u5c02\u7528\u306e\u30b5\u30a4\u30c8\u306b\u3059\u308b\u304b => arabic table\n# arabic01\u306f duolingo \u5c02\u7528\u306b\u3067\u304d\u308b\u306e\u3067\u306f\u306a\u3044\u304b\n%%html\n\n<style>\n    div#paging {\n        text-align: center;\n        /* \u30b9\u30af\u30ed\u30fc\u30eb\u306b\u5bfe\u3057\u3066\u30da\u30fc\u30b8\u30f3\u30b0\u30dc\u30c3\u30af\u30b9\u306e\u4f4d\u7f6e\u3092\u56fa\u5b9a */\n        position: fixed;\n        /* \u4f4d\u7f6e\u3092\u6307\u5b9a */\n        bottom: 0;\n        right: 45%;\n    }\n\n    div#pagingbox {\n        background: #FFF;\n    }\n\n    th {\n        /* \u30d8\u30c3\u30c0\u80cc\u666f\u5857\u308a\u3064\u3076\u3057 */\n        background: #eee;\n    }\n\n    th,\n    td {\n        /* \u67a0\u7dda\u30921\u672c\u7dda\u6307\u5b9a */\n        border: solid 1px;\n        width: auto;\n    }\n\n    table {\n        /* \u67a0\u7dda\u30921\u672c\u7dda\u6307\u5b9a */\n        border: solid 1px;\n        border-collapse: collapse;\n        white-space: nowrap;\n    }\n</style>\n\n<!--\u30c6\u30fc\u30d6\u30eb\u751f\u6210\u4f4d\u7f6e-->\n<div id='maintable'></div>\n\n\n```\n\n\n\n<style>\n    div#paging {\n        text-align: center;\n        /* \u30b9\u30af\u30ed\u30fc\u30eb\u306b\u5bfe\u3057\u3066\u30da\u30fc\u30b8\u30f3\u30b0\u30dc\u30c3\u30af\u30b9\u306e\u4f4d\u7f6e\u3092\u56fa\u5b9a */\n        position: fixed;\n        /* \u4f4d\u7f6e\u3092\u6307\u5b9a */\n        bottom: 0;\n        right: 45%;\n    }\n\n    div#pagingbox {\n        background: #FFF;\n    }\n\n    th {\n        /* \u30d8\u30c3\u30c0\u80cc\u666f\u5857\u308a\u3064\u3076\u3057 */\n        background: #eee;\n    }\n\n    th,\n    td {\n        /* \u67a0\u7dda\u30921\u672c\u7dda\u6307\u5b9a */\n        border: solid 1px;\n        width: auto;\n    }\n\n    table {\n        /* \u67a0\u7dda\u30921\u672c\u7dda\u6307\u5b9a */\n        border: solid 1px;\n        border-collapse: collapse;\n        white-space: nowrap;\n    }\n</style>\n\n<!--\u30c6\u30fc\u30d6\u30eb\u751f\u6210\u4f4d\u7f6e-->\n<div id='maintable'></div>\n\n\n\n\n# \u3044\u307e\u3053\u3053\n\nhttps://qiita.com/ttatsf/items/846ff861bd45fca0832c\n\n\n```\n# you may be able to define a subclass of sympy.Symbol that implements subs() properly for summations\n# \u6dfb\u5b57\u3092\u3064\u3051\u305f\u3044\u306e\u3067 subscription \u3092\u691c\u7d22\u3057\u3066\u3066\u95a2\u4fc2\u306a\u3044\u306e\u304c\u3072\u3063\u304b\u304b\u3063\u305f\u3051\u3069\u9762\u767d\u3044\u306e\u3067\u3068\u3063\u3066\u304a\u304f\nimport sympy\na_seq = [-1, 3, 23, 8]\nn, r = sympy.symbols('n, r')\na_n = sympy.Function('a')(n)\nterms = 4\nshort_expr = sympy.Sum(a_n * r**n, (n, 0, terms - 1))\ncoeffed_short_expr = short_expr.doit().subs(\n    (a_n.subs(n, i), a_seq[i]) for i in range(terms)) # 8*r**3 + 23*r**2 + 3*r - 1\nfunc_short_expr = sympy.lambdify(r, coeffed_short_expr, 'numpy')\ndisplay(short_expr)\ndisplay(coeffed_short_expr)\nfunc_short_expr(1)\n```\n\n# \u3044\u307e\u3053\u3053\n\n$$\n\\require{AMScd}\n\\begin{CD}\n    A @>{f}>> B \\\\\n@V{g}VV    @VVV \\\\\n    C   @>>>  D\n\\end{CD}\n$$\n\n$$\n\\begin{array}{ccccccccc}\n0 & \\xrightarrow{i} & A & \\xrightarrow{f} & B & \\xrightarrow{q} & C & \\xrightarrow{d} & 0\\\\\n\\downarrow & \\searrow & \\downarrow & \\nearrow & \\downarrow & \\searrow & \\downarrow & \\nearrow & \\downarrow\\\\\n0 & \\xrightarrow{j} & D & \\xrightarrow{g} & E & \\xrightarrow{r} & F & \\xrightarrow{e} & 0\n\\end{array}\n$$\n\n$$\n\\begin{array}{}\n1 & \\xrightarrow{i} & A \\\\\n\\downarrow & \\searrow{i} & \\downarrow \\\\\n0 & \\xrightarrow{j} & D & \\xrightarrow{g} & E \n\\end{array}\n$$\n\n```\n\\begin{array}{ccccccccc}\n0 & \\xrightarrow{i} & A & \\xrightarrow{f} & B & \\xrightarrow{q} & C & \\xrightarrow{d} & 0\\\\\n\n\\downarrow & \\searrow & \\downarrow & \\nearrow & \\downarrow & \\searrow & \\downarrow & \\nearrow & \\downarrow\\\\\n\n0 & \\xrightarrow{j} & D & \\xrightarrow{g} & E & \\xrightarrow{r} & F & \\xrightarrow{e} & 0\n\\end{array}\n```\n\n$$\n\\begin{array}{ccccccccc}\n0 & \\xrightarrow{i} & A & \\xrightarrow{f} & B & \\xrightarrow{q} & C & \\xrightarrow{d} & 0 \\\\\n\\downarrow & \\searrow & \\downarrow & \\nearrow & \\downarrow & \\searrow & \\downarrow & \\nearrow & \\downarrow \\\\\n0 & \\xrightarrow{j} & D & \\xrightarrow{g} & E & \\xrightarrow{r} & F & \\xrightarrow{e} & 0\n\\end{array} \n$$\n\n**\u30e1\u30e2**\n\ngithub \u3068 colab \u3067\u306f begin{array} \u306e\u66f8\u304d\u65b9\u306e\u53b3\u5bc6\u3055\u3068\u3044\u3046\u304b\u30eb\u30fc\u30eb\u306e\u9069\u7528\u306b\u5dee\u304c\u3042\u308b\u304c\u3001\u304d\u3063\u3061\u308a\u66f8\u3051\u3070\u3069\u3061\u3089\u3082\u901a\u308b\u3002\n\ncolab \u3067\u306f \\require{AMScd} \u306f\u901a\u308b\u304c\u3001github \u3067\u306f\u30a8\u30e9\u30fc\u306b\u306a\u3063\u3066\u305d\u308c\u3092\u542b\u3080 latex \u306f\u5e73\u6587\u306b\u306a\u308b\u3002\n\ncolab \u3067\u306f array \u306e\u4e2d\u306b\u7a7a\u884c\u304c\u3042\u3063\u305f\u308a\u3001\u6700\u7d42\u884c\u306b \\\\ \u304c\u3064\u3044\u3066\u3044\u308b\u3068\u5bfe\u5fdc\u305b\u305a rendering \u305b\u305a\u5e73\u6587\u306b\u306a\u308b\u304c\u3001github\u3067\u306f\u51e6\u7406\u3059\u308b\u3002\n\n\u9006\u306b array \u306b {ccc} \u304c\u3064\u3044\u3066\u3044\u306a\u304b\u3063\u305f\u308a\u3001{ccc} \u306e\u6570\u3088\u308a\u591a\u304f & \u304c\u632f\u3089\u308c\u3066\u3044\u308b\u3068 colab \u3067\u306f\u305d\u306e\u307e\u307e\u9069\u5f53\u306b rendering \u3057\u3066\u304f\u308c\u308b\u304c\ngithub \u3067\u306f rendering \u3057\u306a\u3044\u3002\n\n\n\n```\n\n```\n", "meta": {"hexsha": "035909ea9b1ae873a8936c96c693bdb0ea5d429f", "size": 588336, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "temp.ipynb", "max_stars_repo_name": "kalz2q/-yjupyternotebooks", "max_stars_repo_head_hexsha": "ba37ac7822543b830fe8602b3f611bb617943463", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "temp.ipynb", "max_issues_repo_name": "kalz2q/-yjupyternotebooks", "max_issues_repo_head_hexsha": "ba37ac7822543b830fe8602b3f611bb617943463", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "temp.ipynb", "max_forks_repo_name": "kalz2q/-yjupyternotebooks", "max_forks_repo_head_hexsha": "ba37ac7822543b830fe8602b3f611bb617943463", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 111.1956151956, "max_line_length": 148258, "alphanum_fraction": 0.8117079356, "converted": true, "num_tokens": 19688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09268778615821206, "lm_q2_score": 0.06853749350763608, "lm_q1q2_score": 0.00635258854205562}}
{"text": "<a href=\"https://colab.research.google.com/github/juanesarango/rep-net-model/blob/main/RepNetColab.ipynb\" target=\"_parent\"></a>\n\nCopyright 2020 Google LLC.\n\nLicensed aunder the Apache License, Version 2.0 (the \"License\");\n\n\n```\n#@title License\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# RepNet\n\nThis colab contains a pre-trained [RepNet](https://sites.google.com/view/repnet) model. It can be used to predict the rate at which repetitions are happening in a video in a class-agnostic manner. These estimates can be used to count the number of repetitions in videos.\n\nThis model is able to count repetitions in many domains: counting the number of reps while exercising, measuring the rate of biological events like heartrates etc. \n\nEnsure you are running the Colab with a GPU runtime.\n\n\n# Setup\n\n\n\n\n```\n!pip install kora\nimport kora.install.py38\n```\n\n    Collecting kora\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/5b/0d/3d9ab9ee747f0925b038e8350ce137276a7a4730a96a3516485dc1b87ba3/kora-0.9.19-py3-none-any.whl (57kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 61kB 3.3MB/s \n    \u001b[?25hRequirement already satisfied: ipython in /usr/local/lib/python3.7/dist-packages (from kora) (5.5.0)\n    Collecting fastcore\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/0c/98/60404e2817cff113a6ae4023bc1772e23179408fdf7857fa410551758dfe/fastcore-1.3.19-py3-none-any.whl (53kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 61kB 6.5MB/s \n    \u001b[?25hRequirement already satisfied: pygments in /usr/local/lib/python3.7/dist-packages (from ipython->kora) (2.6.1)\n    Requirement already satisfied: traitlets>=4.2 in /usr/local/lib/python3.7/dist-packages (from ipython->kora) (5.0.5)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.7/dist-packages (from ipython->kora) (4.4.2)\n    Requirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.7/dist-packages (from ipython->kora) (0.8.1)\n    Requirement already satisfied: setuptools>=18.5 in /usr/local/lib/python3.7/dist-packages (from ipython->kora) (54.2.0)\n    Requirement already satisfied: pickleshare in /usr/local/lib/python3.7/dist-packages (from ipython->kora) (0.7.5)\n    Requirement already satisfied: pexpect; sys_platform != \"win32\" in /usr/local/lib/python3.7/dist-packages (from ipython->kora) (4.8.0)\n    Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.7/dist-packages (from ipython->kora) (1.0.18)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from fastcore->kora) (20.9)\n    Requirement already satisfied: pip in /usr/local/lib/python3.7/dist-packages (from fastcore->kora) (19.3.1)\n    Requirement already satisfied: ipython-genutils in /usr/local/lib/python3.7/dist-packages (from traitlets>=4.2->ipython->kora) (0.2.0)\n    Requirement already satisfied: ptyprocess>=0.5 in /usr/local/lib/python3.7/dist-packages (from pexpect; sys_platform != \"win32\"->ipython->kora) (0.7.0)\n    Requirement already satisfied: six>=1.9.0 in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython->kora) (1.15.0)\n    Requirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython->kora) (0.2.5)\n    Requirement already satisfied: pyparsing>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->fastcore->kora) (2.4.7)\n    Installing collected packages: fastcore, kora\n    Successfully installed fastcore-1.3.19 kora-0.9.19\n    https://0c22fb6119b5.ngrok.io\n\n\n\n```\n#@title\n\nimport base64\nimport io\nimport os\nimport time\n\nimport cv2\n\nfrom IPython.display import display\nfrom IPython.display import HTML\nfrom IPython.display import Javascript\n\nimport matplotlib\nfrom matplotlib.animation import FuncAnimation\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nfrom PIL import Image\nfrom scipy.signal import medfilt\n\nimport tensorflow.compat.v2 as tf\n\n! pip install youtube_dl\nimport youtube_dl\n\nfrom google.colab import drive\nfrom google.colab import output\nfrom google.colab.output import eval_js\n\n# Model definition\nlayers = tf.keras.layers\nregularizers = tf.keras.regularizers\n\n\nclass ResnetPeriodEstimator(tf.keras.models.Model):\n  \"\"\"RepNet model.\"\"\"\n\n  def __init__(\n      self,\n      num_frames=64,\n      image_size=112,\n      base_model_layer_name='conv4_block3_out',\n      temperature=13.544,\n      dropout_rate=0.25,\n      l2_reg_weight=1e-6,\n      temporal_conv_channels=512,\n      temporal_conv_kernel_size=3,\n      temporal_conv_dilation_rate=3,\n      conv_channels=32,\n      conv_kernel_size=3,\n      transformer_layers_config=((512, 4, 512),),\n      transformer_dropout_rate=0.0,\n      transformer_reorder_ln=True,\n      period_fc_channels=(512, 512),\n      within_period_fc_channels=(512, 512)):\n    super(ResnetPeriodEstimator, self).__init__()\n\n    # Model params.\n    self.num_frames = num_frames\n    self.image_size = image_size\n\n    self.base_model_layer_name = base_model_layer_name\n\n    self.temperature = temperature\n\n    self.dropout_rate = dropout_rate\n    self.l2_reg_weight = l2_reg_weight\n\n    self.temporal_conv_channels = temporal_conv_channels\n    self.temporal_conv_kernel_size = temporal_conv_kernel_size\n    self.temporal_conv_dilation_rate = temporal_conv_dilation_rate\n\n    self.conv_channels = conv_channels\n    self.conv_kernel_size = conv_kernel_size\n    # Transformer config in form of (channels, heads, bottleneck channels).\n    self.transformer_layers_config = transformer_layers_config\n    self.transformer_dropout_rate = transformer_dropout_rate\n    self.transformer_reorder_ln = transformer_reorder_ln\n\n    self.period_fc_channels = period_fc_channels\n    self.within_period_fc_channels = within_period_fc_channels\n\n    # Base ResNet50 Model.\n    base_model = tf.keras.applications.ResNet50V2(\n        include_top=False, weights=None, pooling='max')\n    self.base_model = tf.keras.models.Model(\n        inputs=base_model.input,\n        outputs=base_model.get_layer(self.base_model_layer_name).output)\n\n    # 3D Conv on k Frames\n    self.temporal_conv_layers = [\n        layers.Conv3D(self.temporal_conv_channels,\n                      self.temporal_conv_kernel_size,\n                      padding='same',\n                      dilation_rate=(self.temporal_conv_dilation_rate, 1, 1),\n                      kernel_regularizer=regularizers.l2(self.l2_reg_weight),\n                      kernel_initializer='he_normal')]\n    self.temporal_bn_layers = [layers.BatchNormalization()\n                               for _ in self.temporal_conv_layers]\n\n    # Counting Module (Self-sim > Conv > Transformer > Classifier)\n    self.conv_3x3_layer = layers.Conv2D(self.conv_channels,\n                                        self.conv_kernel_size,\n                                        padding='same',\n                                        activation=tf.nn.relu)\n\n    channels = self.transformer_layers_config[0][0]\n    self.input_projection = layers.Dense(\n        channels, kernel_regularizer=regularizers.l2(self.l2_reg_weight),\n        activation=None)\n    self.input_projection2 = layers.Dense(\n        channels, kernel_regularizer=regularizers.l2(self.l2_reg_weight),\n        activation=None)\n\n    length = self.num_frames\n    self.pos_encoding = tf.compat.v1.get_variable(\n        name='resnet_period_estimator/pos_encoding',\n        shape=[1, length, 1],\n        initializer=tf.compat.v1.truncated_normal_initializer(stddev=0.02))\n    self.pos_encoding2 = tf.compat.v1.get_variable(\n        name='resnet_period_estimator/pos_encoding2',\n        shape=[1, length, 1],\n        initializer=tf.compat.v1.truncated_normal_initializer(stddev=0.02))\n\n    self.transformer_layers = []\n    for d_model, num_heads, dff in self.transformer_layers_config:\n      self.transformer_layers.append(\n          TransformerLayer(d_model, num_heads, dff,\n                           self.transformer_dropout_rate,\n                           self.transformer_reorder_ln))\n\n    self.transformer_layers2 = []\n    for d_model, num_heads, dff in self.transformer_layers_config:\n      self.transformer_layers2.append(\n          TransformerLayer(d_model, num_heads, dff,\n                           self.transformer_dropout_rate,\n                           self.transformer_reorder_ln))\n\n    # Period Prediction Module.\n    self.dropout_layer = layers.Dropout(self.dropout_rate)\n    num_preds = self.num_frames//2\n    self.fc_layers = []\n    for channels in self.period_fc_channels:\n      self.fc_layers.append(layers.Dense(\n          channels, kernel_regularizer=regularizers.l2(self.l2_reg_weight),\n          activation=tf.nn.relu))\n    self.fc_layers.append(layers.Dense(\n        num_preds, kernel_regularizer=regularizers.l2(self.l2_reg_weight)))\n\n    # Within Period Module\n    num_preds = 1\n    self.within_period_fc_layers = []\n    for channels in self.within_period_fc_channels:\n      self.within_period_fc_layers.append(layers.Dense(\n          channels, kernel_regularizer=regularizers.l2(self.l2_reg_weight),\n          activation=tf.nn.relu))\n    self.within_period_fc_layers.append(layers.Dense(\n        num_preds, kernel_regularizer=regularizers.l2(self.l2_reg_weight)))\n\n  def call(self, x):\n    # Ensures we are always using the right batch_size during train/eval.\n    batch_size = tf.shape(x)[0]\n    # Conv Feature Extractor.\n    x = tf.reshape(x, [-1, self.image_size, self.image_size, 3])\n    x = self.base_model(x)\n    h = tf.shape(x)[1]\n    w = tf.shape(x)[2]\n    c = tf.shape(x)[3]\n    x = tf.reshape(x, [batch_size, -1, h, w, c])\n\n    # 3D Conv to give temporal context to per-frame embeddings. \n    for bn_layer, conv_layer in zip(self.temporal_bn_layers,\n                                    self.temporal_conv_layers):\n      x = conv_layer(x)\n      x = bn_layer(x)\n      x = tf.nn.relu(x)\n\n    x = tf.reduce_max(x, [2, 3])\n\n    # Reshape and prepare embs for output.\n    final_embs = x\n\n    # Get self-similarity matrix.\n    x = get_sims(x, self.temperature)\n\n    # 3x3 conv layer on self-similarity matrix.\n    x = self.conv_3x3_layer(x)\n    x = tf.reshape(x, [batch_size, self.num_frames, -1])\n    within_period_x = x\n\n    # Period prediction.\n    x = self.input_projection(x)\n    x += self.pos_encoding\n    for transformer_layer in self.transformer_layers:\n      x = transformer_layer(x)\n    x = flatten_sequential_feats(x, batch_size, self.num_frames)\n    for fc_layer in self.fc_layers:\n      x = self.dropout_layer(x)\n      x = fc_layer(x)\n\n    # Within period prediction.\n    within_period_x = self.input_projection2(within_period_x)\n    within_period_x += self.pos_encoding2\n    for transformer_layer in self.transformer_layers2:\n      within_period_x = transformer_layer(within_period_x)\n    within_period_x = flatten_sequential_feats(within_period_x,\n                                               batch_size,\n                                               self.num_frames)\n    for fc_layer in self.within_period_fc_layers:\n      within_period_x = self.dropout_layer(within_period_x)\n      within_period_x = fc_layer(within_period_x)\n\n    return x, within_period_x, final_embs\n\n  @tf.function\n  def preprocess(self, imgs):\n    imgs = tf.cast(imgs, tf.float32)\n    imgs -= 127.5\n    imgs /= 127.5\n    imgs = tf.image.resize(imgs, (self.image_size, self.image_size))\n    return imgs\n\n\ndef get_sims(embs, temperature):\n  \"\"\"Calculates self-similarity between batch of sequence of embeddings.\"\"\"\n  batch_size = tf.shape(embs)[0]\n  seq_len = tf.shape(embs)[1]\n  embs = tf.reshape(embs, [batch_size, seq_len, -1])\n\n  def _get_sims(embs):\n    \"\"\"Calculates self-similarity between sequence of embeddings.\"\"\"\n    dist = pairwise_l2_distance(embs, embs)\n    sims = -1.0 * dist\n    return sims\n\n  sims = tf.map_fn(_get_sims, embs)\n  sims /= temperature\n  sims = tf.nn.softmax(sims, axis=-1)\n  sims = tf.expand_dims(sims, -1)\n  return sims\n\n\ndef flatten_sequential_feats(x, batch_size, seq_len):\n  \"\"\"Flattens sequential features with known batch size and seq_len.\"\"\"\n  x = tf.reshape(x, [batch_size, seq_len, -1])\n  return x\n\n\n# Transformer from https://www.tensorflow.org/tutorials/text/transformer .\ndef scaled_dot_product_attention(q, k, v, mask):\n  \"\"\"Calculate the attention weights.\n\n  q, k, v must have matching leading dimensions.\n  k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.\n  The mask has different shapes depending on its type(padding or look ahead)\n  but it must be broadcastable for addition.\n\n  Args:\n    q: query shape == (..., seq_len_q, depth)\n    k: key shape == (..., seq_len_k, depth)\n    v: value shape == (..., seq_len_v, depth_v)\n    mask: Float tensor with shape broadcastable\n          to (..., seq_len_q, seq_len_k). Defaults to None.\n\n  Returns:\n    outputs: shape == (..., seq_len_q, depth_v)\n    attention_weights: shape == (..., seq_len_q, seq_len_k)\n  \"\"\"\n\n  matmul_qk = tf.matmul(q, k, transpose_b=True)  # (..., seq_len_q, seq_len_k)\n\n  # scale matmul_qk.\n  dk = tf.cast(tf.shape(k)[-1], tf.float32)\n  scaled_attention_logits = matmul_qk / tf.math.sqrt(dk)\n\n  # add the mask to the scaled tensor.\n  if mask is not None:\n    scaled_attention_logits += (mask * -1e9)\n\n  # softmax is normalized on the last axis (seq_len_k) so that the scores\n  # add up to 1.\n  # (..., seq_len_q, seq_len_k)\n  attention_weights = tf.nn.softmax(scaled_attention_logits, axis=-1)\n\n  outputs = tf.matmul(attention_weights, v)  # (..., seq_len_q, depth_v)\n\n  return outputs, attention_weights\n\n\ndef point_wise_feed_forward_network(d_model, dff):\n  return tf.keras.Sequential([\n      tf.keras.layers.Dense(dff, activation='relu'),\n      tf.keras.layers.Dense(d_model)\n  ])\n\n\nclass MultiHeadAttention(tf.keras.layers.Layer):\n  \"\"\"Multi-headed attention layer.\"\"\"\n\n  def __init__(self, d_model, num_heads):\n    super(MultiHeadAttention, self).__init__()\n    self.num_heads = num_heads\n    self.d_model = d_model\n\n    assert d_model % self.num_heads == 0\n\n    self.depth = d_model // self.num_heads\n\n    self.wq = tf.keras.layers.Dense(d_model)\n    self.wk = tf.keras.layers.Dense(d_model)\n    self.wv = tf.keras.layers.Dense(d_model)\n\n    self.dense = tf.keras.layers.Dense(d_model)\n\n  def split_heads(self, x, batch_size):\n    \"\"\"Split the last dimension into (num_heads, depth).\"\"\"\n    x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth))\n    return tf.transpose(x, perm=[0, 2, 1, 3])\n\n  def call(self, v, k, q, mask):\n    batch_size = tf.shape(q)[0]\n\n    q = self.wq(q)  # (batch_size, seq_len, d_model)\n    k = self.wk(k)  # (batch_size, seq_len, d_model)\n    v = self.wv(v)  # (batch_size, seq_len, d_model)\n\n    q = self.split_heads(\n        q, batch_size)  # (batch_size, num_heads, seq_len_q, depth)\n    k = self.split_heads(\n        k, batch_size)  # (batch_size, num_heads, seq_len_k, depth)\n    v = self.split_heads(\n        v, batch_size)  # (batch_size, num_heads, seq_len_v, depth)\n\n    # scaled_attention.shape == (batch_size, num_heads, seq_len_q, depth)\n    # attention_weights.shape == (batch_size, num_heads, seq_len_q, seq_len_k)\n    scaled_attention, attention_weights = scaled_dot_product_attention(\n        q, k, v, mask)\n\n    scaled_attention = tf.transpose(\n        scaled_attention,\n        perm=[0, 2, 1, 3])  # (batch_size, seq_len_q, num_heads, depth)\n\n    concat_attention = tf.reshape(\n        scaled_attention,\n        (batch_size, -1, self.d_model))  # (batch_size, seq_len_q, d_model)\n\n    outputs = self.dense(concat_attention)  # (batch_size, seq_len_q, d_model)\n\n    return outputs, attention_weights\n\n\nclass TransformerLayer(tf.keras.layers.Layer):\n  \"\"\"Implements a single transformer layer (https://arxiv.org/abs/1706.03762).\n  \"\"\"\n\n  def __init__(self, d_model, num_heads, dff,\n               dropout_rate=0.1,\n               reorder_ln=False):\n    super(TransformerLayer, self).__init__()\n\n    self.mha = MultiHeadAttention(d_model, num_heads)\n    self.ffn = point_wise_feed_forward_network(d_model, dff)\n\n    self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-6)\n    self.layernorm2 = tf.keras.layers.LayerNormalization(epsilon=1e-6)\n\n    self.dropout1 = tf.keras.layers.Dropout(dropout_rate)\n    self.dropout2 = tf.keras.layers.Dropout(dropout_rate)\n\n    self.reorder_ln = reorder_ln\n\n  def call(self, x):\n    inp_x = x\n\n    if self.reorder_ln:\n      x = self.layernorm1(x)\n\n    # (batch_size, input_seq_len, d_model)\n    attn_output, _ = self.mha(x, x, x, mask=None)\n    attn_output = self.dropout1(attn_output)\n\n    if self.reorder_ln:\n      out1 = inp_x + attn_output\n      x = out1\n    else:\n      # (batch_size, input_seq_len, d_model)\n      out1 = self.layernorm1(x + attn_output)\n      x = out1\n\n    if self.reorder_ln:\n      x = self.layernorm2(x)\n\n    # (batch_size, input_seq_len, d_model)\n    ffn_output = self.ffn(x)\n    ffn_output = self.dropout2(ffn_output)\n\n    if self.reorder_ln:\n      out2 = out1 + ffn_output\n    else:\n      # (batch_size, input_seq_len, d_model)\n      out2 = self.layernorm2(out1 + ffn_output)\n\n    return out2\n\n\ndef pairwise_l2_distance(a, b):\n  \"\"\"Computes pairwise distances between all rows of a and all rows of b.\"\"\"\n  norm_a = tf.reduce_sum(tf.square(a), 1)\n  norm_a = tf.reshape(norm_a, [-1, 1])\n  norm_b = tf.reduce_sum(tf.square(b), 1)\n  norm_b = tf.reshape(norm_b, [1, -1])\n  dist = tf.maximum(norm_a - 2.0 * tf.matmul(a, b, False, True) + norm_b, 0.0)\n  return dist\n\n\ndef get_repnet_model(logdir):\n  \"\"\"Returns a trained RepNet model.\n\n  Args:\n    logdir (string): Path to directory where checkpoint will be downloaded.\n\n  Returns:\n    model (Keras model): Trained RepNet model.\n  \"\"\"\n  # Check if we are in eager mode.\n  assert tf.executing_eagerly()\n\n  # Models will be called in eval mode.\n  tf.keras.backend.set_learning_phase(0)\n\n  # Define RepNet model.\n  model = ResnetPeriodEstimator()\n  # tf.function for speed.\n  model.call = tf.function(model.call)\n\n  # Define checkpoint and checkpoint manager.\n  ckpt = tf.train.Checkpoint(model=model)\n  ckpt_manager = tf.train.CheckpointManager(\n      ckpt, directory=logdir, max_to_keep=10)\n  latest_ckpt = ckpt_manager.latest_checkpoint\n  print('Loading from: ', latest_ckpt)\n  if not latest_ckpt:\n    raise ValueError('Path does not have a checkpoint to load.')\n  # Restore weights.\n  ckpt.restore(latest_ckpt).expect_partial()\n\n  # Pass dummy frames to build graph.\n  model(tf.random.uniform((1, 64, 112, 112, 3)))\n  return model\n\n\ndef unnorm(query_frame):\n  min_v = query_frame.min()\n  max_v = query_frame.max()\n  query_frame = (query_frame - min_v) / max(1e-7, (max_v - min_v))\n  return query_frame\n\n\ndef create_count_video(frames,\n                       per_frame_counts,\n                       within_period,\n                       score,\n                       fps,\n                       output_file,\n                       delay,\n                       plot_count=True,\n                       plot_within_period=False,\n                       plot_score=False):\n  \"\"\"Creates video with running count and within period predictions.\n\n  Args:\n    frames (List): List of images in form of NumPy arrays.\n    per_frame_counts (List): List of floats indicating repetition count for\n      each frame. This is the rate of repetition for that particular frame.\n      Summing this list up gives count over entire video.\n    within_period (List): List of floats indicating score between 0 and 1 if the\n      frame is inside the periodic/repeating portion of a video or not.\n    score (float): Score between 0 and 1 indicating the confidence of the\n      RepNet model's count predictions.\n    fps (int): Frames per second of the input video. Used to scale the\n      repetition rate predictions to Hz.\n    output_file (string): Path of the output video.\n    delay (integer): Delay between each frame in the output video.\n    plot_count (boolean): if True plots the count in the output video.\n    plot_within_period (boolean): if True plots the per-frame within period\n      scores.\n    plot_score (boolean): if True plots the confidence of the model along with\n      count ot within_period scores.\n  \"\"\"\n  if output_file[-4:] not in ['.mp4', '.gif']:\n    raise ValueError('Output format can only be mp4 or gif')\n  num_frames = len(frames)\n\n  running_counts = np.cumsum(per_frame_counts)\n  final_count = running_counts[-1]\n\n  def count(idx):\n    return int(np.round(running_counts[idx]))\n\n  def rate(idx):\n    return per_frame_counts[idx] * fps\n\n  if plot_count and not plot_within_period:\n    fig = plt.figure(figsize=(10, 12), tight_layout=True)\n    im = plt.imshow(unnorm(frames[0]))\n    if plot_score:\n      plt.suptitle('Pred Count: %d, '\n                   'Prob: %0.1f' % (int(np.around(final_count)), score),\n                   fontsize=24)\n\n    plt.title('Count 0, Rate: 0', fontsize=24)\n    plt.axis('off')\n    plt.grid(b=None)\n    def update_count_plot(i):\n      \"\"\"Updates the count plot.\"\"\"\n      im.set_data(unnorm(frames[i]))\n      plt.title('Count %d, Rate: %0.4f Hz' % (count(i), rate(i)), fontsize=24)\n\n    anim = FuncAnimation(\n        fig,\n        update_count_plot,\n        frames=np.arange(1, num_frames),\n        interval=delay,\n        blit=False)\n    if output_file[-3:] == 'mp4':\n      anim.save(output_file, dpi=100, fps=24)\n    elif output_file[-3:] == 'gif':\n      anim.save(output_file, writer='imagemagick', fps=24, dpi=100)\n\n  elif plot_within_period:\n    fig, axs = plt.subplots(1, 2, figsize=(12, 6))\n    im = axs[0].imshow(unnorm(frames[0]))\n    axs[1].plot(0, within_period[0])\n    axs[1].set_xlim((0, len(frames)))\n    axs[1].set_ylim((0, 1))\n\n    if plot_score:\n      plt.suptitle('Pred Count: %d, '\n                   'Prob: %0.1f' % (int(np.around(final_count)), score),\n                   fontsize=24)\n\n    if plot_count:\n      axs[0].set_title('Count 0, Rate: 0', fontsize=20)\n\n    plt.axis('off')\n    plt.grid(b=None)\n\n    def update_within_period_plot(i):\n      \"\"\"Updates the within period plot along with count.\"\"\"\n      im.set_data(unnorm(frames[i]))\n      axs[0].set_xticks([])\n      axs[0].set_yticks([])\n      xs = []\n      ys = []\n      if plot_count:\n        axs[0].set_title('Count %d, Rate: %0.4f Hz' % (count(i), rate(i)),\n                         fontsize=20)\n      for idx in range(i):\n        xs.append(idx)\n        ys.append(within_period[int(idx * len(within_period) / num_frames)])\n      axs[1].clear()\n      axs[1].set_title('Within Period or Not', fontsize=20)\n      axs[1].set_xlim((0, num_frames))\n      axs[1].set_ylim((-0.05, 1.05))\n      axs[1].plot(xs, ys)\n\n    anim = FuncAnimation(\n        fig,\n        update_within_period_plot,\n        frames=np.arange(1, num_frames),\n        interval=delay,\n        blit=False,\n    )\n    if output_file[-3:] == 'mp4':\n      anim.save(output_file, dpi=100, fps=24)\n    elif output_file[-3:] == 'gif':\n      anim.save(output_file, writer='imagemagick', fps=24, dpi=100)\n\n  plt.close()\n\n\ndef show_video(video_path):\n  mp4 = open(video_path, 'rb').read()\n  data_url = 'data:video/mp4;base64,' + base64.b64encode(mp4).decode()\n  return HTML(\"\"\"\n  \"\"\" % data_url)\n\n\ndef viz_reps(frames,\n             count,\n             score,\n             alpha=1.0,\n             pichart=True,\n             colormap=plt.cm.PuBu,\n             num_frames=None,\n             interval=30,\n             plot_score=True):\n  \"\"\"Visualize repetitions.\"\"\"\n  if isinstance(count, list):\n    counts = len(frames) * [count/len(frames)]\n  else:\n    counts = count\n  sum_counts = np.cumsum(counts)\n  tmp_path = '/tmp/output.mp4'\n  fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(5, 5),\n                         tight_layout=True,)\n\n  h, w, _ = np.shape(frames[0])\n  wedge_x = 95 / 112 * w\n  wedge_y = 17 / 112 * h\n  wedge_r = 15 / 112 * h\n  txt_x = 95 / 112 * w\n  txt_y = 19 / 112 * h\n  otxt_size = 62 / 112 * h\n\n  if plot_score:\n    plt.title('Score:%.2f' % score, fontsize=20)\n  im0 = ax.imshow(unnorm(frames[0]))\n\n  if not num_frames:\n    num_frames = len(frames)\n\n  if pichart:\n    wedge1 = matplotlib.patches.Wedge(\n        center=(wedge_x, wedge_y),\n        r=wedge_r,\n        theta1=0,\n        theta2=0,\n        color=colormap(1.),\n        alpha=alpha)\n    wedge2 = matplotlib.patches.Wedge(\n        center=(wedge_x, wedge_y),\n        r=wedge_r,\n        theta1=0,\n        theta2=0,\n        color=colormap(0.5),\n        alpha=alpha)\n\n    ax.add_patch(wedge1)\n    ax.add_patch(wedge2)\n    txt = ax.text(\n        txt_x,\n        txt_y,\n        '0',\n        size=35,\n        ha='center',\n        va='center',\n        alpha=0.9,\n        color='white',\n    )\n\n  else:\n    txt = ax.text(\n        txt_x,\n        txt_y,\n        '0',\n        size=otxt_size,\n        ha='center',\n        va='center',\n        alpha=0.8,\n        color=colormap(0.4),\n    )\n\n  def update(i):\n    \"\"\"Update plot with next frame.\"\"\"\n    im0.set_data(unnorm(frames[i]))\n    ctr = int(sum_counts[i])\n    if pichart:\n      if ctr%2 == 0:\n        wedge1.set_color(colormap(1.0))\n        wedge2.set_color(colormap(0.5))\n      else:\n        wedge1.set_color(colormap(0.5))\n        wedge2.set_color(colormap(1.0))\n\n      wedge1.set_theta1(-90)\n      wedge1.set_theta2(-90 - 360 * (1 - sum_counts[i] % 1.0))\n      wedge2.set_theta1(-90 - 360 * (1 - sum_counts[i] % 1.0))\n      wedge2.set_theta2(-90)\n\n    txt.set_text(int(sum_counts[i]))\n    ax.grid(False)\n    ax.set_xticks([])\n    ax.set_yticks([])\n    plt.tight_layout()\n\n  anim = FuncAnimation(\n      fig,\n      update,\n      frames=num_frames,\n      interval=interval,\n      blit=False)\n  anim.save(tmp_path, dpi=80)\n  plt.close()\n  return show_video(tmp_path)\n\n\ndef record_video(interval_in_ms, num_frames, quality=0.8):\n  \"\"\"Capture video from webcam.\"\"\"\n  # https://colab.research.google.com/notebooks/snippets/advanced_outputs.ipynb.\n\n  # Give warning before recording.\n  for i in range(0, 3):\n    print('Opening webcam in %d seconds'%(3-i))\n    time.sleep(1)\n    output.clear(output_tags='status_text')\n\n  js = Javascript('''\n    async function recordVideo(interval_in_ms, num_frames, quality) {\n      const div = document.createElement('div');\n      const video = document.createElement('video');\n      video.style.display = 'block';\n      const stream = await navigator.mediaDevices.getUserMedia({video: true});\n\n      // show the video in the HTML element\n      document.body.appendChild(div);\n      div.appendChild(video);\n      video.srcObject = stream;\n      await video.play();\n\n      google.colab.output.setIframeHeight(document.documentElement.scrollHeight,\n        true);\n\n      for (let i = 0; i < num_frames; i++) {\n        const canvas = document.createElement('canvas');\n        canvas.width = video.videoWidth;\n        canvas.height = video.videoHeight;\n        canvas.getContext('2d').drawImage(video, 0, 0);\n        img = canvas.toDataURL('image/jpeg', quality);\n        google.colab.kernel.invokeFunction(\n        'notebook.get_webcam_video', [img], {});\n        await new Promise(resolve => setTimeout(resolve, interval_in_ms));\n      }\n      stream.getVideoTracks()[0].stop();\n      div.remove();\n    }\n    ''')\n  display(js)\n  eval_js('recordVideo({},{},{})'.format(interval_in_ms, num_frames, quality))\n\n\ndef data_uri_to_img(uri):\n  \"\"\"Convert base64image to Numpy array.\"\"\"\n  image = base64.b64decode(uri.split(',')[1], validate=True)\n  # Binary string to PIL image.\n  image = Image.open(io.BytesIO(image))\n  image = image.resize((224, 224))\n  # PIL to Numpy array.\n  image = np.array(np.array(image, dtype=np.uint8), np.float32)\n  return image\n\n\ndef read_video(video_filename, width=224, height=224):\n  \"\"\"Read video from file.\"\"\"\n  cap = cv2.VideoCapture(video_filename)\n  fps = cap.get(cv2.CAP_PROP_FPS)\n  frames = []\n  if cap.isOpened():\n    while True:\n      success, frame_bgr = cap.read()\n      if not success:\n        break\n      frame_rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)\n      frame_rgb = cv2.resize(frame_rgb, (width, height))\n      frames.append(frame_rgb)\n  frames = np.asarray(frames)\n  return frames, fps\n\n\ndef get_webcam_video(img_b64):\n  \"\"\"Populates global variable imgs by converting image URI to Numpy array.\"\"\"\n  image = data_uri_to_img(img_b64)\n  imgs.append(image)\n\n\ndef download_video_from_url(url_to_video,\n                            path_to_video='/tmp/video.mp4'):\n  if os.path.exists(path_to_video):\n    os.remove(path_to_video)\n  ydl_opts = {\n      'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/mp4',\n      'outtmpl': str(path_to_video),\n  }\n  with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n    ydl.download([url_to_video])\n\n\ndef get_score(period_score, within_period_score):\n  \"\"\"Combine the period and periodicity scores.\"\"\"\n  within_period_score = tf.nn.sigmoid(within_period_score)[:, 0]\n  per_frame_periods = tf.argmax(period_score, axis=-1) + 1\n  pred_period_conf = tf.reduce_max(\n      tf.nn.softmax(period_score, axis=-1), axis=-1)\n  pred_period_conf = tf.where(\n      tf.math.less(per_frame_periods, 3), 0.0, pred_period_conf)\n  within_period_score *= pred_period_conf\n  within_period_score = np.sqrt(within_period_score)\n  pred_score = tf.reduce_mean(within_period_score)\n  return pred_score, within_period_score\n\n\ndef get_counts(model, frames, strides, batch_size,\n               threshold,\n               within_period_threshold,\n               constant_speed=False,\n               median_filter=False,\n               fully_periodic=False):\n  \"\"\"Pass frames through model and conver period predictions to count.\"\"\"\n  seq_len = len(frames)\n  raw_scores_list = []\n  scores = []\n  within_period_scores_list = []\n\n  if fully_periodic:\n    within_period_threshold = 0.0\n\n  frames = model.preprocess(frames)\n\n  for stride in strides:\n    num_batches = int(np.ceil(seq_len/model.num_frames/stride/batch_size))\n    raw_scores_per_stride = []\n    within_period_score_stride = []\n    for batch_idx in range(num_batches):\n      idxes = tf.range(batch_idx*batch_size*model.num_frames*stride,\n                       (batch_idx+1)*batch_size*model.num_frames*stride,\n                       stride)\n      idxes = tf.clip_by_value(idxes, 0, seq_len-1)\n      curr_frames = tf.gather(frames, idxes)\n      curr_frames = tf.reshape(\n          curr_frames,\n          [batch_size, model.num_frames, model.image_size, model.image_size, 3])\n\n      raw_scores, within_period_scores, _ = model(curr_frames)\n      raw_scores_per_stride.append(np.reshape(raw_scores.numpy(),\n                                              [-1, model.num_frames//2]))\n      within_period_score_stride.append(np.reshape(within_period_scores.numpy(),\n                                                   [-1, 1]))\n    raw_scores_per_stride = np.concatenate(raw_scores_per_stride, axis=0)\n    raw_scores_list.append(raw_scores_per_stride)\n    within_period_score_stride = np.concatenate(\n        within_period_score_stride, axis=0)\n    pred_score, within_period_score_stride = get_score(\n        raw_scores_per_stride, within_period_score_stride)\n    scores.append(pred_score)\n    within_period_scores_list.append(within_period_score_stride)\n\n  # Stride chooser\n  argmax_strides = np.argmax(scores)\n  chosen_stride = strides[argmax_strides]\n  raw_scores = np.repeat(\n      raw_scores_list[argmax_strides], chosen_stride, axis=0)[:seq_len]\n  within_period = np.repeat(\n      within_period_scores_list[argmax_strides], chosen_stride,\n      axis=0)[:seq_len]\n  within_period_binary = np.asarray(within_period > within_period_threshold)\n  if median_filter:\n    within_period_binary = medfilt(within_period_binary, 5)\n\n  # Select Periodic frames\n  periodic_idxes = np.where(within_period_binary)[0]\n\n  if constant_speed:\n    # Count by averaging predictions. Smoother but\n    # assumes constant speed.\n    scores = tf.reduce_mean(\n        tf.nn.softmax(raw_scores[periodic_idxes], axis=-1), axis=0)\n    max_period = np.argmax(scores)\n    pred_score = scores[max_period]\n    pred_period = chosen_stride * (max_period + 1)\n    per_frame_counts = (\n        np.asarray(seq_len * [1. / pred_period]) *\n        np.asarray(within_period_binary))\n  else:\n    # Count each frame. More noisy but adapts to changes in speed.\n    pred_score = tf.reduce_mean(within_period)\n    per_frame_periods = tf.argmax(raw_scores, axis=-1) + 1\n    per_frame_counts = tf.where(\n        tf.math.less(per_frame_periods, 3),\n        0.0,\n        tf.math.divide(1.0,\n                       tf.cast(chosen_stride * per_frame_periods, tf.float32)),\n    )\n    if median_filter:\n      per_frame_counts = medfilt(per_frame_counts, 5)\n\n    per_frame_counts *= np.asarray(within_period_binary)\n\n    pred_period = seq_len/np.sum(per_frame_counts)\n\n  if pred_score < threshold:\n    print('No repetitions detected in video as score '\n          '%0.2f is less than threshold %0.2f.'%(pred_score, threshold))\n    per_frame_counts = np.asarray(len(per_frame_counts) * [0.])\n\n  return (pred_period, pred_score, within_period,\n          per_frame_counts, chosen_stride)\n```\n\n    Collecting youtube_dl\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/4a/cb/829848d3f15e63e51f1a1c874c2151690c2365dd95d7507c995531a28efb/youtube_dl-2021.4.7-py2.py3-none-any.whl (1.9MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.9MB 18.8MB/s \n    \u001b[?25hInstalling collected packages: youtube-dl\n    Successfully installed youtube-dl-2021.4.7\n\n\n## Load trained RepNet\n\n\n```\nPATH_TO_CKPT = '/tmp/repnet_ckpt/'\n!mkdir $PATH_TO_CKPT\n!wget -nc -P $PATH_TO_CKPT https://storage.googleapis.com/repnet_ckpt/checkpoint\n!wget -nc -P $PATH_TO_CKPT https://storage.googleapis.com/repnet_ckpt/ckpt-88.data-00000-of-00002\n!wget -nc -P $PATH_TO_CKPT https://storage.googleapis.com/repnet_ckpt/ckpt-88.data-00001-of-00002\n!wget -nc -P $PATH_TO_CKPT https://storage.googleapis.com/repnet_ckpt/ckpt-88.index\n\nmodel = get_repnet_model(PATH_TO_CKPT)\n```\n\n    --2021-04-08 22:34:45--  https://storage.googleapis.com/repnet_ckpt/checkpoint\n    Resolving storage.googleapis.com (storage.googleapis.com)... 172.217.164.144, 142.250.73.240, 172.253.62.128, ...\n    Connecting to storage.googleapis.com (storage.googleapis.com)|172.217.164.144|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 922 [application/octet-stream]\n    Saving to: \u2018/tmp/repnet_ckpt/checkpoint\u2019\n    \n    checkpoint          100%[===================>]     922  --.-KB/s    in 0s      \n    \n    2021-04-08 22:34:45 (22.3 MB/s) - \u2018/tmp/repnet_ckpt/checkpoint\u2019 saved [922/922]\n    \n    --2021-04-08 22:34:45--  https://storage.googleapis.com/repnet_ckpt/ckpt-88.data-00000-of-00002\n    Resolving storage.googleapis.com (storage.googleapis.com)... 142.250.31.128, 172.217.8.16, 172.217.13.80, ...\n    Connecting to storage.googleapis.com (storage.googleapis.com)|142.250.31.128|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 93435 (91K) [application/octet-stream]\n    Saving to: \u2018/tmp/repnet_ckpt/ckpt-88.data-00000-of-00002\u2019\n    \n    ckpt-88.data-00000- 100%[===================>]  91.25K  --.-KB/s    in 0.001s  \n    \n    2021-04-08 22:34:45 (102 MB/s) - \u2018/tmp/repnet_ckpt/ckpt-88.data-00000-of-00002\u2019 saved [93435/93435]\n    \n    --2021-04-08 22:34:45--  https://storage.googleapis.com/repnet_ckpt/ckpt-88.data-00001-of-00002\n    Resolving storage.googleapis.com (storage.googleapis.com)... 172.253.62.128, 172.253.115.128, 142.250.31.128, ...\n    Connecting to storage.googleapis.com (storage.googleapis.com)|172.253.62.128|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 328985260 (314M) [application/octet-stream]\n    Saving to: \u2018/tmp/repnet_ckpt/ckpt-88.data-00001-of-00002\u2019\n    \n    ckpt-88.data-00001- 100%[===================>] 313.74M   169MB/s    in 1.9s    \n    \n    2021-04-08 22:34:47 (169 MB/s) - \u2018/tmp/repnet_ckpt/ckpt-88.data-00001-of-00002\u2019 saved [328985260/328985260]\n    \n    --2021-04-08 22:34:47--  https://storage.googleapis.com/repnet_ckpt/ckpt-88.index\n    Resolving storage.googleapis.com (storage.googleapis.com)... 172.217.13.240, 172.217.2.112, 142.250.65.80, ...\n    Connecting to storage.googleapis.com (storage.googleapis.com)|172.217.13.240|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 13172 (13K) [application/octet-stream]\n    Saving to: \u2018/tmp/repnet_ckpt/ckpt-88.index\u2019\n    \n    ckpt-88.index       100%[===================>]  12.86K  --.-KB/s    in 0s      \n    \n    2021-04-08 22:34:47 (112 MB/s) - \u2018/tmp/repnet_ckpt/ckpt-88.index\u2019 saved [13172/13172]\n    \n\n\n    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/backend.py:434: UserWarning: `tf.keras.backend.set_learning_phase` is deprecated and will be removed after 2020-10-11. To update it, simply pass a True/False value to the `training` argument of the `__call__` method of your layer or model.\n      warnings.warn('`tf.keras.backend.set_learning_phase` is deprecated and '\n\n\n    Loading from:  /tmp/repnet_ckpt/ckpt-88\n\n\n## Set Params\n\n\n\n\n```\n##@title \n\n# FPS while recording video from webcam.\nWEBCAM_FPS = 16#@param {type:\"integer\"}\n\n# Time in seconds to record video on webcam. \nRECORDING_TIME_IN_SECONDS = 8. #@param {type:\"number\"}\n\n# Threshold to consider periodicity in entire video.\nTHRESHOLD = 0.2#@param {type:\"number\"}\n\n# Threshold to consider periodicity for individual frames in video.\nWITHIN_PERIOD_THRESHOLD = 0.5#@param {type:\"number\"}\n\n# Use this setting for better results when it is \n# known action is repeating at constant speed.\nCONSTANT_SPEED = False#@param {type:\"boolean\"}\n\n# Use median filtering in time to ignore noisy frames.\nMEDIAN_FILTER = True#@param {type:\"boolean\"}\n\n# Use this setting for better results when it is \n# known the entire video is periodic/reapeating and\n# has no aperiodic frames.\nFULLY_PERIODIC = False#@param {type:\"boolean\"}\n\n# Plot score in visualization video.\nPLOT_SCORE = False#@param {type:\"boolean\"}\n\n# Visualization video's FPS.\nVIZ_FPS = 30#@param {type:\"integer\"}\n```\n\n# Get input video\n\nWe provide 3 ways to get input video:\n1. upload video to your Google Drive.\n2. provide URL of a video.\n3. record video using webcam.\n\n## Get Video from Drive\n\nIf you have uploaded an input video to your Drive, update `PATH_TO_VIDEO_ON_YOUR_DRIVE` below.\n\nThis step needs your authorization in order to access the videos from your Google Drive. Running the next code cell will ask for that permission.\n\n\n```\n# Uncomment and run these lines to load videos from Google Drive.\n\n# drive.mount('/content/gdrive')\n\n# PATH_TO_VIDEO_ON_YOUR_DRIVE = \"gdrive/My Drive/<PATH_TO_VIDEO>.mp4\"\n# imgs, vid_fps = read_video(PATH_TO_VIDEO_ON_YOUR_DRIVE)\n# show_video(PATH_TO_VIDEO_ON_YOUR_DRIVE)\n```\n\n## Get Video from URL\n\nProvide a link to mp4/gif hosted online.\n\n\n```\n# Hummingbird flying.\nVIDEO_URL = 'https://imgur.com/t/hummingbird/m2e2Nfa'\n\n# Cheetah running.\n# VIDEO_URL = 'https://www.reddit.com/r/gifs/comments/4qfif6/cheetah_running_at_63_mph_102_kph/'\n\n# Exercise repetition counting.\n# VIDEO_URL = 'https://www.youtube.com/watch?v=5g1T-ff07kM'\n\n# Kitchen activities repetition counting. Tough example with many starts and\n# stops and varying speeds of action.\n# VIDEO_URL = 'https://www.youtube.com/watch?v=5EYY2J3nb5c'\n\ndownload_video_from_url(VIDEO_URL)\nimgs, vid_fps = read_video(\"/tmp/video.mp4\")\nshow_video(\"/tmp/video.mp4\")\n```\n\n    [imgur:gallery] m2e2Nfa: Downloading JSON metadata\n    [Imgur] m2e2Nfa: Downloading webpage\n    [download] Destination: /tmp/video.mp4\n    [download] 100% of 324.79KiB in 00:00\n\n\n\n\n\n\n\n\n\n\n## Get Video from Webcam\n\nYou will be asked for permission for this page to access your webcam.\n\n### Run following code to capture webcam video\n\n\n```\n# Uncomment and run these lines to record video using webcam.\n\nINTERVAL_IN_MS = 1000//WEBCAM_FPS\nvid_fps = WEBCAM_FPS\nimgs = []\noutput.register_callback('notebook.get_webcam_video', get_webcam_video)\nrecord_video(INTERVAL_IN_MS, int(RECORDING_TIME_IN_SECONDS*1000/INTERVAL_IN_MS))\n```\n\n    Opening webcam in 3 seconds\n    Opening webcam in 2 seconds\n    Opening webcam in 1 seconds\n\n\n\n    <IPython.core.display.Javascript object>\n\n\n# Run RepNet\n\n\n```\nprint('Running RepNet...') \n(pred_period, pred_score, within_period,\n per_frame_counts, chosen_stride) = get_counts(\n     model,\n     imgs,\n     strides=[1,2,3,4],\n     batch_size=20,\n     threshold=THRESHOLD,\n     within_period_threshold=WITHIN_PERIOD_THRESHOLD,\n     constant_speed=CONSTANT_SPEED,\n     median_filter=MEDIAN_FILTER,\n     fully_periodic=FULLY_PERIODIC)\nprint('Visualizing results...') \nviz_reps(imgs, per_frame_counts, pred_score, interval=1000/VIZ_FPS,\n         plot_score=PLOT_SCORE)\n\n```\n\n    Running RepNet...\n    Visualizing results...\n\n\n\n\n\n\n\n\n\n\n\n```\n# Debugging video showing scores, per-frame frequency prediction and \n# within_period scores.\ncreate_count_video(imgs,\n                   per_frame_counts,\n                   within_period,\n                   score=pred_score,\n                   fps=vid_fps,\n                   output_file='/tmp/debug_video.mp4',\n                   delay=1000/VIZ_FPS,\n                   plot_count=True,\n                   plot_within_period=True,\n                   plot_score=True)\nshow_video('/tmp/debug_video.mp4')\n\n```\n\n# Citation\n\nIf you found our paper/code useful in your research, consider citing our paper:\n\n\n```\n@InProceedings{Dwibedi_2020_CVPR,\nauthor = {Dwibedi, Debidatta and Aytar, Yusuf and Tompson, Jonathan and Sermanet, Pierre and Zisserman, Andrew},\ntitle = {Counting Out Time: Class Agnostic Video Repetition Counting in the Wild},\nbooktitle = {IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)},\nmonth = {June},\nyear = {2020}\n}\n```\n\n\n\n\n\n\n```\n!pip install --upgrade coremltools\n# !pip install -U tensorflow==2.4.1 keras==2.4.3\n#!pip install -U tensorflow==2.3.1 keras==2.2.4 scikit-learn==0.19.2\n```\n\n    Collecting coremltools\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/32/b0/14c37edf39a9b32c2c9c7aa3e27ece4ef4f5b2dd2c950102661a106520f1/coremltools-4.1-cp37-none-manylinux1_x86_64.whl (3.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.4MB 8.3MB/s \n    \u001b[?25hRequirement already satisfied, skipping upgrade: six>=1.10.0 in /usr/local/lib/python3.7/dist-packages (from coremltools) (1.15.0)\n    Requirement already satisfied, skipping upgrade: sympy in /usr/local/lib/python3.7/dist-packages (from coremltools) (1.7.1)\n    Requirement already satisfied, skipping upgrade: packaging in /usr/local/lib/python3.7/dist-packages (from coremltools) (20.9)\n    Requirement already satisfied, skipping upgrade: attrs in /usr/local/lib/python3.7/dist-packages (from coremltools) (20.3.0)\n    Requirement already satisfied, skipping upgrade: numpy<1.20,>=1.14.5 in /usr/local/lib/python3.7/dist-packages (from coremltools) (1.19.5)\n    Requirement already satisfied, skipping upgrade: scipy in /usr/local/lib/python3.7/dist-packages (from coremltools) (1.4.1)\n    Requirement already satisfied, skipping upgrade: protobuf>=3.1.0 in /usr/local/lib/python3.7/dist-packages (from coremltools) (3.12.4)\n    Requirement already satisfied, skipping upgrade: tqdm in /usr/local/lib/python3.7/dist-packages (from coremltools) (4.41.1)\n    Collecting attr\n      Downloading https://files.pythonhosted.org/packages/de/be/ddc7f84d4e087144472a38a373d3e319f51a6faf6e5fc1ae897173675f21/attr-0.3.1.tar.gz\n    Requirement already satisfied, skipping upgrade: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->coremltools) (1.2.1)\n    Requirement already satisfied, skipping upgrade: pyparsing>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->coremltools) (2.4.7)\n    Requirement already satisfied, skipping upgrade: setuptools in /usr/local/lib/python3.7/dist-packages (from protobuf>=3.1.0->coremltools) (54.2.0)\n    Building wheels for collected packages: attr\n      Building wheel for attr (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for attr: filename=attr-0.3.1-cp37-none-any.whl size=2458 sha256=8d4dd1ad587833ae98c0f1294827b205567dae96b9964b84b0c349ecb6d6c2f0\n      Stored in directory: /root/.cache/pip/wheels/f0/96/9b/1f8892a707d17095b5a6eab0275da9d39e68e03a26aee2e726\n    Successfully built attr\n    Installing collected packages: attr, coremltools\n    Successfully installed attr-0.3.1 coremltools-4.1\n\n\n\n```\n# Convert to .mlmodel file \nimport coremltools as ct\n\n# convert model to CoreML\n# mlmodel = ct.convert('/content/repNetModel/saved_model.pb')\n# mlmodel = ct.converters.keras.convert('/content/repNetModel/saved_model.pb')\n# mlmodel = ct.converters.keras.convert('/content/repNetModel/')\n# mlmodel = ct.converters.keras.convert(model)\n# mlmodel = ct.convert(model=model, minimum_deployment_target=ct.target.iOS13)\nmodel = ResnetPeriodEstimator()\n# tf.function for speed.\n# model.call = tf.function(model.call)\n\n# Define checkpoint and checkpoint manager.\nckpt = tf.train.Checkpoint(model=model)\nckpt_manager = tf.train.CheckpointManager(\n    ckpt, directory=PATH_TO_CKPT, max_to_keep=10)\nlatest_ckpt = ckpt_manager.latest_checkpoint\nprint('Loading from: ', latest_ckpt)\nif not latest_ckpt:\n  raise ValueError('Path does not have a checkpoint to load.')\n# Restore weights.\nckpt.restore(latest_ckpt).expect_partial()\n\n# Pass dummy frames to build graph.\nmodel(tf.random.uniform((1, 64, 112, 112, 3)))\n# mlmodel = ct.convert(model=model, source='tensorflow')\n\n\n\n# convert to a .h5 --> only for tensorflow 1.X, .tf (SavedModel folder) is for 2.X \n\n#mlmodel = ct.convert(PATH_TO_CKPT, source='tensorflow')\n\n\n\n\n\n\n\n```\n\n\n```\nimport tensorflow as tf\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\ntf.saved_model.save(model, \"repNetModel3\")\n# tf.saved_model.save(model, \"repNetModel2\")\n\n# model.save(\"repNetModel\", save_format='tf')\n# /content/testModelFolder\n# !zip -r /content/testModelFolder.zip /content/testModelFolder\n\n# # from google.colab import files\n# files.download(\"/content/testModelFolder.zip\")\n```\n", "meta": {"hexsha": "0a5b4f9d8baaabc0d421b8485a57301afd92f5e1", "size": 821939, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "RepNetColab.ipynb", "max_stars_repo_name": "juanesarango/rep-net-model", "max_stars_repo_head_hexsha": "e3cf8dc625d3e289f6795d727d4c7621587aaf92", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RepNetColab.ipynb", "max_issues_repo_name": "juanesarango/rep-net-model", "max_issues_repo_head_hexsha": "e3cf8dc625d3e289f6795d727d4c7621587aaf92", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RepNetColab.ipynb", "max_forks_repo_name": "juanesarango/rep-net-model", "max_forks_repo_head_hexsha": "e3cf8dc625d3e289f6795d727d4c7621587aaf92", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 483.7781047675, "max_line_length": 443547, "alphanum_fraction": 0.9088642831, "converted": true, "num_tokens": 12364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17781087819190095, "lm_q2_score": 0.035678553825659445, "lm_q1q2_score": 0.006344034988357513}}
{"text": "# Rich Output\n\nIn Python, objects can declare their textual representation using the `__repr__` method.  IPython expands on this idea and allows objects to declare other, rich representations including:\n\n* HTML\n* JSON\n* PNG\n* JPEG\n* SVG\n* LaTeX\n\nA single object can declare some or all of these representations; all are handled by IPython's *display system*. This Notebook shows how you can use this display system to incorporate a broad range of content into your Notebooks.\n\n## Basic display imports\n\nThe `display` function is a general purpose tool for displaying different representations of objects. Think of it as `print` for these rich representations.\n\n\n```python\nfrom IPython.display import display\n```\n\nA few points:\n\n* Calling `display` on an object will send **all** possible representations to the Notebook.\n* These representations are stored in the Notebook document.\n* In general the Notebook will use the richest available representation.\n\nIf you want to display a particular representation, there are specific functions for that:\n\n\n```python\nfrom IPython.display import (\n    display_pretty, display_html, display_jpeg,\n    display_png, display_json, display_latex, display_svg\n)\n```\n\n## Images\n\nTo work with images (JPEG, PNG) use the `Image` class.\n\n\n```python\nfrom IPython.display import Image\n```\n\n\n```python\ni = Image(filename='../images/ipython_logo.png')\n```\n\nReturning an `Image` object from an expression will automatically display it:\n\n\n```python\ni\n```\n\nOr you can pass an object with a rich representation to `display`:\n\n\n```python\ndisplay(i)\n```\n\nAn image can also be displayed from raw data or a URL.\n\n\n```python\nImage(url='http://python.org/images/python-logo.gif')\n```\n\n\n\n\n\n\n\n\nSVG images are also supported out of the box.\n\n\n```python\nfrom IPython.display import SVG\nSVG(filename='../images/python_logo.svg')\n```\n\n\n\n\n    \n\n    \n\n\n\n### Embedded vs non-embedded Images\n\nBy default, image data is embedded in the notebook document so that the images can be viewed offline. However it is also possible to tell the `Image` class to only store a *link* to the image. Let's see how this works using a webcam at Berkeley.\n\n\n```python\nfrom IPython.display import Image\nimg_url = 'http://www.lawrencehallofscience.org/static/scienceview/scienceview.berkeley.edu/html/view/view_assets/images/newview.jpg'\n\n# by default Image data are embedded\nEmbed      = Image(img_url)\n\n# if kwarg `url` is given, the embedding is assumed to be false\nSoftLinked = Image(url=img_url)\n\n# In each case, embed can be specified explicitly with the `embed` kwarg\n# ForceEmbed = Image(url=img_url, embed=True)\n```\n\nHere is the embedded version. Note that this image was pulled from the webcam when this code cell was originally run and stored in the Notebook. Unless we rerun this cell, this is not today's image.\n\n\n```python\nEmbed\n```\n\n\n\n\n    \n\n    \n\n\n\nHere is today's image from same webcam at Berkeley, (refreshed every minutes, if you reload the notebook), visible only with an active internet connection, that should be different from the previous one. Notebooks saved with this kind of image will be smaller and always reflect the current version of the source, but the image won't display offline.\n\n\n```python\nSoftLinked\n```\n\n\n\n\n\n\n\n\nOf course, if you re-run this Notebook, the two images will be the same again.\n\n## HTML\n\nPython objects can declare HTML representations that will be displayed in the Notebook. If you have some HTML you want to display, simply use the `HTML` class.\n\n\n```python\nfrom IPython.display import HTML\n```\n\n\n```python\ns = \"\"\"<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\"\"\"\n```\n\n\n```python\nh = HTML(s)\n```\n\n\n```python\ndisplay(h)\n```\n\n\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n\n\nYou can also use the `%%html` cell magic to accomplish the same thing.\n\n\n```python\n%%html\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n```\n\n\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n\n\n## JavaScript\n\nThe Notebook also enables objects to declare a JavaScript representation. At first, this may seem odd as  output is inherently visual and JavaScript is a programming language. However, this opens the door for rich output that leverages the full power of JavaScript and associated libraries such as [d3.js](http://d3js.org) for output.\n\n\n```python\nfrom IPython.display import Javascript\n```\n\nPass a string of JavaScript source code to the `JavaScript` object and then display it.\n\n\n```python\njs = Javascript('alert(\"hi\")');\n```\n\n\n```python\ndisplay(js)\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\nThe same thing can be accomplished using the `%%javascript` cell magic:\n\n\n```javascript\n%%javascript\n\nalert(\"hi\");\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\nHere is a more complicated example that loads `d3.js` from a CDN, uses the `%%html` magic to load CSS styles onto the page and then runs ones of the `d3.js` examples.\n\n\n```python\nJavascript(\n    \"\"\"$.getScript('//cdnjs.cloudflare.com/ajax/libs/d3/3.2.2/d3.v3.min.js')\"\"\"\n)\n```\n\n\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n```python\n%%html\n<style type=\"text/css\">\n\ncircle {\n  fill: rgb(31, 119, 180);\n  fill-opacity: .25;\n  stroke: rgb(31, 119, 180);\n  stroke-width: 1px;\n}\n\n.leaf circle {\n  fill: #ff7f0e;\n  fill-opacity: 1;\n}\n\ntext {\n  font: 10px sans-serif;\n}\n\n</style>\n```\n\n\n<style type=\"text/css\">\n\ncircle {\n  fill: rgb(31, 119, 180);\n  fill-opacity: .25;\n  stroke: rgb(31, 119, 180);\n  stroke-width: 1px;\n}\n\n.leaf circle {\n  fill: #ff7f0e;\n  fill-opacity: 1;\n}\n\ntext {\n  font: 10px sans-serif;\n}\n\n</style>\n\n\n\n```javascript\n%%javascript\n\n// element is the jQuery element we will append to\nvar e = element.get(0);\n    \nvar diameter = 600,\n    format = d3.format(\",d\");\n\nvar pack = d3.layout.pack()\n    .size([diameter - 4, diameter - 4])\n    .value(function(d) { return d.size; });\n\nvar svg = d3.select(e).append(\"svg\")\n    .attr(\"width\", diameter)\n    .attr(\"height\", diameter)\n  .append(\"g\")\n    .attr(\"transform\", \"translate(2,2)\");\n\nd3.json(\"data/flare.json\", function(error, root) {\n  var node = svg.datum(root).selectAll(\".node\")\n      .data(pack.nodes)\n    .enter().append(\"g\")\n      .attr(\"class\", function(d) { return d.children ? \"node\" : \"leaf node\"; })\n      .attr(\"transform\", function(d) { return \"translate(\" + d.x + \",\" + d.y + \")\"; });\n\n  node.append(\"title\")\n      .text(function(d) { return d.name + (d.children ? \"\" : \": \" + format(d.size)); });\n\n  node.append(\"circle\")\n      .attr(\"r\", function(d) { return d.r; });\n\n  node.filter(function(d) { return !d.children; }).append(\"text\")\n      .attr(\"dy\", \".3em\")\n      .style(\"text-anchor\", \"middle\")\n      .text(function(d) { return d.name.substring(0, d.r / 3); });\n});\n\nd3.select(self.frameElement).style(\"height\", diameter + \"px\");\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n## LaTeX\n\nThe IPython display system also has builtin support for the display of mathematical expressions typeset in LaTeX, which is rendered in the browser using [MathJax](http://mathjax.org).\n\nYou can pass raw LaTeX test as a string to the `Math` object:\n\n\n```python\nfrom IPython.display import Math\nMath(r'F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx')\n```\n\n\n\n\n$$F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx$$\n\n\n\nWith the `Latex` class, you have to include the delimiters yourself.  This allows you to use other LaTeX modes such as `eqnarray`:\n\n\n```python\nfrom IPython.display import Latex\nLatex(r\"\"\"\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\"\"\")\n```\n\n\n\n\n\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\n\n\n\nOr you can enter LaTeX directly with the `%%latex` cell magic:\n\n\n```latex\n%%latex\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n```\n\n\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n\n\n## Audio\n\nIPython makes it easy to work with sounds interactively. The `Audio` display class allows you to create an audio control that is embedded in the Notebook. The interface is analogous to the interface of the `Image` display class. All audio formats supported by the browser can be used. Note that no single format is presently supported in all browsers.\n\n\n```python\nfrom IPython.display import Audio\nAudio(url=\"http://www.nch.com.au/acm/8k16bitpcm.wav\")\n```\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"http://www.nch.com.au/acm/8k16bitpcm.wav\" type=\"audio/x-wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\nA NumPy array can be auralized automatically. The `Audio` class normalizes and encodes the data and embeds the resulting audio in the Notebook.\n\nFor instance, when two sine waves with almost the same frequency are superimposed a phenomena known as [beats](https://en.wikipedia.org/wiki/Beat_%28acoustics%29) occur. This can be auralised as follows:\n\n\n```python\nimport numpy as np\nmax_time = 3\nf1 = 220.0\nf2 = 224.0\nrate = 8000.0\nL = 3\ntimes = np.linspace(0,L,rate*L)\nsignal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times)\n\nAudio(data=signal, rate=rate)\n```\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"data:audio/wav;base64,UklGRqS7AABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YYC7AAAAADUWvSvyPzdS/WHKbjt4Bn7+fxV+WXj3bjhifVJDQBYslBZiAC/qpdRswCGuU557kf2HJIIcgPWBoIfykKKdTa15v5rTEuk7/2kV8CopP3ZRSmEqbrJ3mH2vf+Z9TXgNb3Bi11K9QK0sQxcmAQPrhNVPwQOvLZ9IkreIxYKggFiC34cLkZOdFq0bvxbTbeh4/o0UASosPnNQSGAwbcd2w3z2fk9923fGblZi7FL/QBwt3hfoAefrg9ZlwiawVqBuk9OJzoOOgSSDg4iAkdadJa31vrvS3ue5/aIT8Sj/PDBP+F7da3t1h3vUfU98BncibuhhuVIJQWQtYRilAtjso9eqw4mxzKHtlE+LPYXkgleEiolTkm6ee60Hv4jSZuf//KsSwyeiO65NXF0zas9z5nlJfOh6zXUhbSdhPlLaQIItzBhbA9Xt39gexSmzjqPCliuNEYeihPKF9YqDk1mfGq5Uv3/SCOdN/KkReCYYOvBLd1szaMVx4HdYehp5MXTDaxNgfFFwQHUtHRkJBNvuN9q9xgW1l6XsmGOPR4nGhvKHwowPlZegAa/bv6LSxOak+58QFCVkOPhJSVnhZV9veXUCeOh2MnIIaqpecVDLPzwtUxmsBOjvp9uFyBm356dmm/aR3otOiVeK8Y73limiMLCewPHSneYG+48PmSOINslH11Y+Y6BssnJJdVF002/yZ+5cHU/rPtYsbBlEBfvwLd11ymO5e6ownuGU1I44jB+NgZE6mQ+kqLGcwW7Tk+Z1+noOCCKGNGVFI1ROYIppj28vcllxFG2CZeBagU3PPUMsZxnOBRHyyN6IzOC7T61GoSGYJZKBj0aQbpTXm0WmZ7PWwhjUp+by+WMNZCBhMtBCMFEUXSFmEWy4bgJu+Gm6YoFYnkt3PIIrQxlJBinzdOC9zo2+YLCkpLKbz5Unk8yTuJfLns2obrVMxPDU2+Z/+UwMsB4dMAxAAU6TWWdiPGjlak9qgWaaX9FVdEnjOpIq/xi0Bj/0L+IQ0WfBq7NHqJKfzpkml6yXXJsVoqSru7f9xffVL+ce+TYL7hy8LR09m0rOVWFeFGS6ZkJmsmImXNNSBEcVOXQpmhgMB1P19+N/02rELbctrL2jH557m+SbVp+zpciuTrroxy3XpefP+CQKIRtAKwY6/0bKURNanF87YuBhjV5gWIlPUEQMNycoFBhRB2P2yeUG1pTH4bpPsC+ovaIioHGgpKOhqTiyJL0OypHYPOiU+BgJSxmuKMo2M0OJTX9V2FpsXStdF1pKVPVLWUHKNKsmbBeCB2v3o+ej2OHKxb6stOOspacYpU6lQ6jdrfG1PMBtzCTa9ehu+BMIbhcHJm0zOT8RSatQzVVRWCdYUVXoTxlIID5PMgIloRadB2z4gulT203O08I+udax0qxXqneqLq1ksvC5k8MDz+Tb0ele+BcHjRVPI/MvFztmRJtLf1DvUtlSQVA9S/dDqTqeLysjtBWiB2P5ZOsS3tXRCccBvgK3P7Lcr+mvYrIytzK+KcfP0dHdz+pl+CYGqxOJIF4szzaMP1RG80pJTUVN6kpNRpQ/9ja3LCghpRSPB076Ru3e4HTVYcvxwmO86beitZ6127dEvLXC+srQ1Orf8OuE+EIFyRG5HbQoZzKIOtpALkVkR29HUUUbQfI6CDOcKfkecxNkByv7Ju+z4yjZ2M8JyPXByb2ju5K7lL2VwXXHA88E2C7iM+27+GsE6w/gGvck4i1eNTI7ND9HQV1BeT+sOxU25C5QJqAcHxIgB/r7AvGO5u3catREzbHH28PbwcHBiMMhx27MQ9No25zkmO4L+aQDEg4DGCshRSkTMGI1DDn2OhQ7aTkENgExiyrVIh4aqhDEBrr82PJt6b/gEdmd0pTNGcpFyCPIs8nlzJ3RtNf63jLnHfB0+e0CQAwkFVUdlCSsKm8vujJ2NJk0JTMnMLkrASYtH3QXEw9NBmj9pvRL7Jrkyt0Q2JfTfdDazrbOENDa0v3WVdy34u/pxPH3+UgCeApGEncZ1B8uJV0pQyzNLfEtsSwaKkImSiFbG6UUXQ2+BQP+aPYo73rokeKY3bXZA9eV1XLVmNb92IrcIeGd5tDsifOT+rYBuwhsD5UVCRueHzMjryUBJyInFCbiI6AgaRxiF7IRiAsVBYz+Hvj/8VzsYOcw4+rfpd1w3FLcSN1I30DiFeap6tTvbvVJ+zcBDAeZDLQRNxYAGvUcAh8YIDIgUx+FHdgaYxdEE54OlQlSBAD/xvnO9DzwNOzS6C/mXeRm41DjGeS25RroLevX7vjyb/cY/M0AbAXPCdYNYhFbFKoWQRgXGScZdBgHF+0UOxIGD2oLhgd3A2D/XvuS9xf0CPF67n/sJOtx6mfqBetD7BPuZfAl8zr2jPkA/XgA3AMRB/8JjwyxDlYQdBEEEgYSfBFuEOcO9QyqChoIWwWDAqr/5PxI+un32PUj9NXy9vGK8ZHxB/Ln8ib0uPWO95j5xPsA/jkAYAJiBDIGwwcKCQAKnwrmCtUKcQq/CcgIlQc0BrAEFwN3Ad7/V/7v/K/7n/rI+Sv5zPis+Mf4Gfme+U/6IvsQ/A79FP4Y/xAA9wDFAXQCAQNpA6sDyAPCA5wDWgMBA5cCIQKnAS4BvABUAPz/tv+D/2X/W/9j/3z/ov/Q/wIANABiAIcAngClAJkAeQBFAP7/pP87/8j+Tv7V/WD99/yg/GD8PPw5/Fn8nvwJ/Zn9S/4c/wMA/gACAgcDBQTxBMEFbgbwBj4HVAcuB8oGKQZMBTgE9QKJAQAAZv7G/C/7rflP+CH3L/aD9Sb1HfVr9RL2Dvdc+PL5x/vN/fb/MAJrBJUGmwhsCvgLLw0HDnQOcQ78DRMNvQsACucHggXiAhoAQP1p+q33IvXe8vXwd+9z7vXtA+6f7sjvd/Gj8zz2Mflq/NH/SgO8BgoKGg3RDxkS3hMOFZ4VhxXFFF0TVRG8DqMLIAhOBEkAMvwl+EX0sfCG7eDq1Oh259Pm9ObZ54Dp3+vk7nzyjPb1+pf/TATyCGQNfBEbFSAYdBoAHLYcjhyFG6EZ7RZ8E2cPzArMBY4APPv99fvwXuxM6OfkTOKR4Mbf9t8h4UHjSeYj6rTu2vNv+Uf/NQUNC58QvxVEGgge7CDXIrYjgSM1ItofgBw9GDITgw1bB+kAYPrx88/tLOg04xHf5NvK2dXYD9l72g/du+Bk5ejqHvHY9+L+BAYKDboT4BlKH8wjQieMKZgqWSrPKAMmCCL6HP8WQhD4CFgBnvkD8sbqHuRC3mHZotUn0wTSRtLt0/DWOduq4BvnW+409mn+ugboDrIW2h0oJGgpby0cMFYxEjFPLxcsgSevIcoaCBOjCtsB9fg18ODnOOB52dvTi8+tzFrLoMt+zenQydX821LjlOuE9N39VQemEIUZrCHaKNYubzN+Nuo3pTetNRAy5ixWJpEe0RVYDHECZ/iH7iDlfNze1IXOpMlixt3EIsUyxwDLcNBc147fyujJ8j791wdDEjEcUSVdLRM0PDmwPFA+DD7lO+k3MjLtKk8imhgXDhgD8/f77Iji7dh10GPJ8cNLwJG+0r4PwTnFMsvP0tbbAuYG8Y78Pgi+E7QeySitMRo50z6rQoFEQ0TyQZw9YTdvLwImYRveD9EDmPeR6xrgjtU/zHjEd75tuny4trgau5q/FcZazivYPuM97837jAgXFQ0hDyzHNec9L0RrSHhKQ0rNRyVDbTzXM6QpIh6pEZgEV/dK6tfdYdJByMm/O7nNtKSy0rJatSi6HMEAypLUgOBw7f76wAhNFjojIi+oOXdCSknqTTBQCFByTX5IUUEhODMt2yB3E24FL/cl6cDbaM9+xFm7QbRwrw2tLa3Sr+m0TbzGxQ7Rzd2i6yL63AhgFzslADJNPcdGIk4lU6VVjVXcUqNNCkZJPKswiCNGFVEGH/ck6NbZpcz4wCu3jK9ZqrunyqeHquCvrLexwaPNJtvU6Tr54AhPGA0nqDS0QNJKs1IXWNJazVoFWI9SkkpLQAg0JyYSFz8HJ/dH5xvYGsqxvUKzIKuNpbSir6J/pRKrPbPDvVTKkNgI6Ef4zAgbGbEoFzfaQ5dO+Va8XLJfw1/qXD1X5k4jREc3tSjbGDYIRveN5o7Wx8esuqKvAacPofud352+oISmBa8CuibHDNZD5kz3owjDGSYqTDm+RhJS8FoRYUJka2SGYapbAVPNR2U6LiueGjQJevf25THVsMXqt0ysMqPknJWZYJlJnDqiCKtwthrEntOF5Er2ZAhJGmsrRjtdSUJVl14RZX5owWjVZdBf31ZFS109jy1XHDkKwveB5QTU08NttUSptZ8PmYWVNJUimDmeSqcSszbBStHR4kP1EgisGoEsBT23SyNY6WG7aGJswWzSaaxjfFqITixA1i8FHkELHvgv5QbTM8I3s4qmjpySlc6RYJFOlIOaz6Psr3y+Ec8p4Tn0rQfuGmcthz7JTbVa5mQLbOtvaHB7bTpn1V2SUdBCADKlH0wMjPj95DjSz8BJsSGkvZlwknOO543RkB2XmqAArfC798yR3y/zNwcPGx0uzT+TT/Vcimf+bhdzs3PMcHhq5mBfVEVFCjQ1IVcNC/ns5JnRp7+jrwqiRpesj3eLy4qujQmUrp1SqpS5/soK3iXysQYQG6Uu1UAUUeJe1GmTceJ1nnbCc2FtrGPtVohH8TWyIl8OmPn75CnRvb5HrkagKZVHjd2IEIjnikyRDpvkp2u3KcmX3B3xHAbzGv4uoUFMUnxgw2vHc0p4KHlZdvJvJGY5WZZJszcaJGQPMvon5efQD74zrdaeaJNDi6eGuIV/iOeOv5i7pXi1e8c62xvwfAW4GikvMUI7U8JhVW2adU96TnuReCpyS2hAW21LTDlrJWMQ2fpw5dLQnr1qrLudBZKiidaExYN5ht2MwZbYo76z9sX22SDv0ARhGigvhELgU7Niim4Jd+17D31legV0H2r+XApNvDqjJloRifvV5enQaL3pq/Sc/pBliGuDOILWhDCLF5U+oj6yncTM2C7uHATvGfsunUI8VE9jYW8UeCN9Z37We4J1nWtzXmpO/ju+J0cSQfxU5izRbb2xq4KcVpCMh2iCE4GYg+OJxJPuoPywcsO/10ftYQNkGaMue0JQVJdj22+7ePJ9WH/gfJ92xWycX41PEj28KCgT//zr5pjRrL3Bq2ScDJAYh86BWIDBgveIyZLsn/qvdsLR1mzsoALBGCMuIEIcVItj92/9eFh+33+EfVt3k214YG9Q9T2aKfsTwv2Y5yzSI74ZrJqcH5AIh5yBBoBRgmyIKJI4nzmvrMED1qHr3AEJGHwtjUGhUyxjtW/beFZ+/H/AfbR3B24EYQ9Rpj5WKr8Uh/5b6ObS0b62rCKdjpBch9OBHYBJgkSI4ZHVnrquFsFZ1ebqFgE9F64sxEDiUntiF29UeOp9r3+Ufap3IG4/YWxRIj/vKnAVTf8w6cbTtL+XrfydWpEUiHKCn4CpgoCI9pHCnn+utMDT1D/qUABfFr4rxz/fUXphHm5rdxd9+H7/fDx33G0pYYRRaD9iKw4WEAAW6sjUy8C7riWfgJIviXmDioFygyCJaJIBn4quicBz1Kvpjv9xFasqlz6aUClgy2wfdt172X0DfGt2PW3AYFZRdz+vK5YW0gAL6+rVE8IgsJyg/5OqiuaE3oKihCOKNpOTn9uulsA61C7pz/51FHkpNz0WT4xeIWt0dD16UXyfejZ1QWwFYOJQTj/TKwgXjgEO7CzXi8PEsWCi1ZWGjLiGmoQ5homLYJR4oHOv3MAq1MnoFv5tEykoqDtUTaNcIGlpcjl4YnrVeJ9z6Gr2XiZQ7D7OK2EXQwIb7YrYMMWks22kAJi+ju6Iu4Y2iFKN5pWwoVKwW8FF1HzoZf1bEr4m7jlXS3Jay2YDcNN1DnimdqVxNGmVXSNPUD6eK6AX8AIx7gHa/8a9tcGmfppSkYWLQYmXinyPyJc6o3mxFMKK1EvovvxBETolCjghSftXJWRCbQxzV3UTdEtvJWfiW9lNej1DK8MXkgNO75Hb98gOuFqpS50/lHqOKYxbjQaSBJoXpeeyCMP71DboIfwiEJ8jADa2RkFVMWEqauhvQHIgcZJsvWTcWUhMaTy7KsoXKARv8DbdE8uTujSsZaCBl8yRcI9+kO2UmZxEp5y0NsSZ1T3okvv/DvAh0TMYREdS8l2+ZmpsyW7NbXxp/GGHV29KHTsHKrMXsQST8e7eU81JvUyvyaMWm3aVFJMAlDGYhZ/CqZe2n8Vk1mToEfvaDS8ggTFLQRFPa1oCY5Ro+Godagxm5V7iVFFIlzklKX4XKgW48rfgss8twKCycqf6nneZEpfcl86bx6KOrNi4Qsdc16nooPq2DGAeEy9QPqFLoFb4Xmpkz2YUZkNieVvvUe5F1jcWKCkXkgXb843iLtI8wyu2Xqspo8mdZpsQnMKfW6anr127H8mC2A7pQfqUC4MciiwtO/xHlFKkWvBfUWK2YSVevFewTkdD3TXZJrMW6AX79G/kxNRzxuq5ia+gp2miDKCZoAmkQKoLsyW+NcvW2ZTp9Pl3Cp0a6SnlNyVES04LVipbg10EXbVZsFMoS15AqjNvJR0WKwYW9lrmcNfNydi97rNarFSnAaVypaGocq63ti7BhM1X2zvqu/lfCa8YMid6NB9AykkxUR1WaFgEWPZUWE9YRzU9QDHYI2UVWQYp90voMNpIzfPBirhTsYSsQaqYqoWt77KqunfECdAE3QPrmPlQCLsWaSTwMPA7FUUbTMtQBVO6Uu1PuEpEQ845oC4UIowUcgY0+D/qAd3f0DbGV72GtvWxxq8GsLKys7ffvv3HxNLe3u3rivlLB8UUkSFMLZs3MUDMRjxLX00pTZ1K0kXuPio2zCslIJITdAY0+Tbs39+P1JzKUsLvu6K3jLW4tSS4urxUw73LstXj4Pjsk/lRBs8Srh6RKSUzITtKQXJFe0dXRwtFqkBaOk0yxCgLHnUSXwYo+ivuyOJV2CLPdceIwYe9jrupu9a9AcIGyLbP0tgS4yXutPlkBdsQwRvCJZEu6zWaO3Q/XEFIQTo/RjuLNTkuiyXHGzgRMwYO+x3wt+Us3MPTvcxOx57Dx8HUwcPDgsfyzOTTI9xr5XPv7fmFBOwOzxjkIeQpkzDBNUY5CjsCOzE5qDWFMPIpJCJaGdoP7gXk+wryq+gQ4HvYI9I6zeHJMcg0yOjJO80S0kXYoN/r5+LwPvq2AwMN2hX5HSIlHyvEL+4yiTSJNPMy1i9LK3olkB7HFlsOkAWr/O7zoOv/40XdpNdH00zQyM7Ezj3QJtNk19TcSeOR6nDyqPr5AiML5hIHGlEgkyWoKXIs3i3kLYcs1CniJdQg0xoOFL0MGQVf/cn1k+705x3iOt1w2djWhdV+1cDWPtni3I7hG+db7R30LPtOAk4J9Q8RFnMb9B9zI9clECcXJ/AlpyNPIAYc7hYzEQELiQQB/pj3gfHr6/7m4eKv34HdY9xc3Gndft+K4nDmEutI8On1yPu1AYUHCg0aEo8WSBoqHSIfJCApIDYfVB2VGhEX5hI2DicJ4QOP/ln5aPTg7+XrkugA5kDkXONZ4zPk4uVV6HbrK+9V89H3ffwxAcwFKQomDqcRkhTTFlsYIBkfGV0Y4Ba5FPsRvQ4aCzAHIAMJ/wv7RPfR88zwSu5c7A/raupu6hrrZOxA7pzwY/N/9tX5Sv3CACMEUwc5CsEM2Q5zEIURChIAEmoRUhDBDscMdgrhBx8FRgJu/6v8E/q697D1A/S+8unxhvGX8Rby/vJF9N31uPfF+fP7MP5oAIwCiwRWBuEHIgkQCqgK6ArQCmUKrQmwCHoHFQaOBPUCVQG9/zj+0vyW+4v6uPkh+cf4rPjL+CP5rPlf+jX7JPwk/Sr+Lf8kAAkB1AGBAgsDcAOvA8kDwAOXA1MD+AKNAhcCnQEkAbIATAD2/7H/gP9j/1v/Zf9//6X/1P8GADgAZQCJAJ8ApQCXAHYAQAD3/5z/Mv++/kT+y/1X/e/8mvxc/Dr8Ovxd/Kb8FP2n/Vz+Lv8YABMBGAIdAxkEAwXRBXsG+AZCB1MHKAe/BhkGNwUfBNgCaQHf/0T+pPwO+475NPgL9x72efUi9SD1dvUj9if3e/gX+vD7+v0kAGACmgTCBsQIkAoVDEUNFA54DmwO7Q37DJsL1gm3B0wFqALe/wP9Lfp19+/0svLQ8FzvZO7x7Qrusu7n76Hx1/N49nP5svwaAJQDBAdOClcNBhBEEv0TIBWjFX0VrRQ3EyMRfg5bC9EH+gPz/9r70ff282nwSe2u6rDoYefO5v/m9ees6RnsLO/O8uf2Vvv7/7EEVAm/Dc8RYRVZGJ0aGBy7HIAcZRtvGaoWKxMKD2QKXgUdAMv6j/WU8AHs/eeo5B7id+DB3wXgReF545Pmfuod70306fnF/7MFhwsRESYWnBpPHh8h9CK8I3AjDSKcHy0c2Re+EgMN0wZeANX5avNR7bvn0+LD3q3bqtnO2CLZp9pT3RXh0eVm66rxbPh6/5wGnA1DFFsatB8hJH4nrymfKkUqoCi6JaYhgxx2FqsPWAizAPn4ZPEx6pnj0N0F2WHVAdP80VzSINQ/16PbK+Gv5/7u4PYa/2sHkw9SF2oeoyTKKbYtRDBfMfswGC/CKxEnJSEsGloS6gkdATj4fu81557f9thy0z/PgsxQy7jLuM1D0UHWjtz6403sSPWm/h8IaRE7Gk8iZilGL8AzrTb1N4s3cDWwMWcsvCXfHQ0ViAubAZH3ue1f5M7bStQOzk7JMcbRxDzFcsdky/bQ/9dK4JnppfMg/rgIHRP8HAkm+i2RNJc55TxdPvE9ojt/N6YxQiqKIcEXMA0rAgb3Fuyy4SzYz8/eyJHDE8CDvu6+VcGnxcXLg9Ol3Obm+PGH/TYJrxSVH5MpWjKlOTg/5kKQRCZEqUEpPcc2sy4qJXMa4A7MApT2luov37rUicvmww2+L7psuNS4ZrsSwLTGHc8M2TbkRfDd/JsJHRYCIuwshTaAPp5ErEiKSiVKf0epQsc7DDO6KCAdlxB+Az32OenY3HvRfMcqv8e4ibSRsvGyqrWousfB0sqE1Yzhje4j/OUJaBdDJBIwdjodQ8NJMk5FUOlPH036R6BASDc4LMYfUBI/BAD2AOit2nDOqMOsusOzJa/3rE2tJ7BwtQO9psYR0uve0uxb+xUKjxhXJgEzKj55R6VOc1O9VW1VhFIYTU5FYzuhL2IiDBQNBdz16+ax2JzLE8BytgWvB6qip+un4KpvsG24nsK1zlXcF+uH+i0Kkhk8KLk1oEGRSz9TbFjsWqxaqlf9Uc1JWD/vMvAkxhXoBdH1++Xj1gDJvrx9spCqNaWYos+i3KWoqwe0vL51y8/ZXemn+SwKcBryKTg41ERiT45XF13QX6JfjFylVhdOJEMgNm0nfhfNBt31L+VG1Z7Gq7nRrmimsaDcnQCeHqEgp9ivBrtUyFvXqOe9+BQKKht3K306xkfpUo9bcmFkZEpkJmELWypSxEYwOdgpMRm7BwD2h+TY03fE3LZwq5CigJxymYCZqpzbouOrf7dVxfvU+eXL9+YJwBvMLIY8ckojVj5feWWjaKFocmUtXwBWMkocPCws2xqwCDn2A+Sc0o3CU7RdqAqfpJhelVOVhZjeniyoKrR8wrPSU+TT9qMJMhzwLVI+10wPWZhiKGmKbKJsbmkFY5dZbE3hPmcufByrCYb2ouOQ0d/AEbKZpdqbIZWkkX6Rs5Qsm7ekDLHMv4bQuOLX9UwJghzjLuE/9U6qW51lfmwXcEtwFm2QZupcblB8QYYwEB6oCuf2Y+O10G+/GLAnowKZ+pFFjgOON5HJl4ehJ65IvXbOLOHY9OIIsBymLzJByVDzXUhod29Gc5dzZnDKafZfNVPoQ4YylR+oC1n3RuML0D2+aK4HoYSWMI9Gi+aKFI64lJ+ef6v0uobMr9/Z82cIvBw4MEVCVFLpX5lqEXIVdoV2W3OxbLhivVUkRmU0CSGmDNz3SuOQz0m9Aq07n2CUxoypiCmITYv8kQOcF6nRuLnKRN7b8t0HqBybMBpDlVOLYY9sSnSBeBB583VBby1lBFgsSB82aSKjDW74beNFz5K856vEnZmSvopvhs+F5IiYj7aZ8abkthLJ79zh8UUHdhzPMLJDi1TXYiduInaIejh7K3h4cVJnCFr/SbM3tCOaDgz5r+Mozxm8FqujnDCRGImahNqD3YaOjbqXEaUttZLHsNvs8KAGJhzVMAxEN1XOY2FvlXcqfPt8AXpUcyVpxFuYSx455iSMD7b5DeQ5z927j6rWmyWQ14csg0uCOYXiixGWeaOxszzGitr/7/EFuhutMCpEmFVwZD1wpHhkfVZ+c3vRdKNqOF33TF46/iV1EGr6h+R3z927U6pgm3iP+oYmgiSB+oOUir6UKqJxshPFgNkb7zoFMxtbMA1EsFW8ZLpwT3k2fkl/gHzvdctrYV4YTnE7+iZTESX7GuXfzxi8X6o+myqPgoaJgWWAIYOmicKTKKFusRjElNhD7nsEkxrdL7VDgFWzZNlwlHmfftJ/JX2tdptsPV/7TlM81yclEub7xuVx0Iy8tKpxmzqPb4ZUgRGAroIZiR+Tc6CssE7Dxtd47bgD3Bk3LyRDCFVXZJtwdHmffvJ/ZH0IdxFtyl+dTwU9lCjoEqv8iOYq0Tm9T6v3m6iPwYaJgSaApILviNaSDKArsLXCGte87PECEBlqLlxCSVSnY/9v8Hg2fqh/O30BdyxtCWD8T4Q9LymcE3P9XucK0h2+MKzPnHKQeIcmgqWAAYMoieiS95/ur1HCkdYR7CoCMBh4LV5BRlOmYgdvCHhlffR+qXyXdu1s9l8YUM49pik9FDr+R+gO0zW/Va35nZiRkYgqg46BxoPDiVWTMqD0ryHCLdZ662MBPxdjLCxAAFJVYbRtvnYtfNd9sHvJdVJskl/vT+I99ynKFAD/QOk01IDAvK5xnxeTDIqWhN+C84TCih+UvqA/sCjC7tX36p4APhYsK8g+eVC2XwlsE3WOelJ8UHqZdFpr3V6BT789IipCFcL/SOp71fzBYrA3oe6U54tnhpiEh4YkjEOVnaHQsGfC19WL6uD/LxXXKTU9s07KXQZqCHOLeGZ6iXgGcwhq1V3NTmU9JSqjFX4AXOvf1qbDRrJHoxuXII6biLeGgIjojcSWzqKosd7C6dU26ib/FhRlKHQ7sUyWW69noXAmdhR4XnYScVpoe1zSTdI8/inrFTQBe+xe2HzFZrSfpZuZtZAxizqJ3YoMkJ+YUKTGso3DJdb76XX+8xLYJok5dkoaWQdl321gc191z3O+blJm0FqRTAU8rikZFuABoe332XvHvbY9qGyco5MnjiCMnI2QktOaJKYqtHfEi9ba6c39yRE0JXY3A0hbVg9ixWo8cEly4HALbPFj1FgKS/86MiksFoICzu6n26HJSrkdq4qf6JZ4kWWPvJBylWCdSKjUtZnFHNfV6TH9mhB6Iz41XUVaU8teV2e9bNVukW37aDlhiFY9ScA5iigiFhgD/+9r3evLCbw9rvOif5ojlQeTOpSvmESgvKrEt/XG2tft6aP8aA+tIeMyhkIcUD5bl2PmaAZr5mmRZSpe7VMrR0c4tyf7FZ8DMvFA31bO976ZsaKmZ54lmQOXEphGnH2jfa34uYvIxNgj6iP8NQ7PH2kwgT+kTG1XiV+8ZN5m4WXPYchaBVHURJU2tya2FRcEZPIl4d/QEsIttZWqmqJ4nVabQpwzoAini7BwvFnK2tl46rP7Aw3kHdItUjz1SFlTMVtAYGFihmG3XRRX0007Qqo0iiVRFX4ElfMW44PTVMX2uMeuFqcbovufxqBzpOOq47Mqv2DMHdvt6lX71AvtGyEr/DgTRQlPk1Z4W5Rd2VxOWRJTVkphP4gyMiTNFNMEwfQS5T/WvMjwvDWz1asHp/Ckm6UEqQyvgrckwp3Oi9yB6wr7qwruGVsogzUCQX9Ks1FoVnpY3VeXVMROlEZHPC8wrSIpFBUF6PUV5xDZRcwXwdq31LA6rC6qvarhrX6zaLtexRHRJt427NL6iAnoF4El6zHHPMFFlkwTURhTllKVTy5KjULvOKEt/CBjE0IFBvcd6fLb7M9mxbG8DravsbOvKLAHsze4j7/UyLrT7d8L7bD6bgjeFZciNy5kONJAQEeAS3JNCU1MSlJFRT5bNd4qIB9+ElkFG/gn6+PerNPaybbBfrtgt3m11rVxuDS998OEzJbW3eEB7qP6XwfUE6EfayrfM7c7t0GyRY1HO0fBRDZAvjmPMeonGx13EVsFJPkx7d7hg9duzuXGIMFJvXu7w7scvnDCm8hs0KPZ+OMY7636XAbKEaAciiY9L3U2/zuwP25BMEH4Ptw6/jSMLcUk7BpQEEUFIfo57+LkbNsf0znM7sZkw7XB68ECxObHeM2I1N/cOuZP8M/6ZgXFD5oZmiKAKhExHTZ9ORs77Tr2OEk1BjBWKXEhlRgJDxcFD/s88evnZN/n16zR48ytySHISMgfypTNidLX2EngpOim8Qj7gATFDZAWnB6uJZArFjAgM5g0dzTAMoIv2yrwJPIdGRaiDdIE7vs48/bqZuPB3DrX+dId0LnO1c5u0HPTzNdU3d3jNOsd81r7qQPNC4UTlhrMIPYl8CmeLOwt1C1aLIspgSVdIEkadxMdDHQEu/wr9f/tb+er4d7cLNmv1njVjNXp1oHZPN384Zrn5+2y9MT75QLgCX0QjBbdG0kgsSP8JRwnCifKJWkj/B+gG3oWshB5Cv4Ddv0S9wTxeuue5pPid99e3VjcaNyL3bbf1eLM5nzrvPBk9kb8MwL/B3sNgBLmFo4aXR1BHy4gHiAXHyEdURq+FoYSzQ24CG8DHv7t+AP0hu+X61To0uUk5FPjY+NP5A/mkejA64DvsvM0+OH8lQEsBoIKdg7sEckU+xZyGCcZFhlEGLkWhBS6EXIOyArbBsgCsv64+vf2jPOR8BvuOuz76mPqduov64bsbe7T8KPzxPYe+pX9CwFpBJQHcwrzDAEPjxCWEQ4S+BFYETUQmw6ZDEEKqAfjBAkCMv9y/N75i/eI9eTzqPLc8YPxnfEm8hbzZPQC9uL38/kj/GD+lwC4ArQEegb/BzkJIAqxCukKygpZCpsJmQheB/UFbQTSAjIBnP8Z/rb8fvt4+qn5F/nD+Kz40fgs+bn5cPpI+zn8Ov0//kL/OAAbAeQBjgIVA3cDswPKA74DkwNMA/AChAINApMBGwGpAEQA7/+s/33/Yv9b/2b/gf+p/9j/CgA8AGkAiwCgAKQAlQByADoA8P+T/yn/tP46/sH9Tv3n/JT8WPw5/Dv8Yvyt/B/9tf1s/kH/LAApAS4CMgMuBBUF4QWHBgAHRgdSByIHtAYIBiIFBgS6AkkBvv8h/oH87fpw+Rn49PYN9m71HvUk9YH1NvZA95v4PPoa/Cf+UwCQAskE7wbtCLMKMgxaDSAOfA5mDt0N4gx5C6wJhgcWBW0Cov/G/PL5Pfe89IbyrfBD71Xu7e0T7sfuB/DM8Qv0tfa2+fn8ZADfA0wHkgqUDTsQbhIbFDEVphVyFZUUERPwEEAOFAuCB6UDnP+D+3z3p/Mi8AvtfeqN6E3ny+YM5xPo2elU7HTvIvND97j7XgAVBbUJGg4gEqcVkRjEGi4cvxxxHEMbOxlnFtkSqw78CfAErf9a+iL1LvCm66/naeTy4V7gvd8W4Gvhs+Pf5trqhu/C9GT6QwAxBgEMgxGMFvMalB5QIQ8jwSNdI+MhXB/ZG3MXSRKDDEwG0/9K+eXy1exL53Tid95324zZydg32dXamd1x4UHm5us28gD5EQA0By8OyxTVGhwgdCS5J9AppSovKm4obiVCIQoc6xUUD7cHDgBV+MbwnukV41/drNgh1d7S9tF00lbUkdcO3K3hROih7473zP8bCD0Q8Bf4HhwlKir6LWowZTHhMN8uayueJpogjRmrETEJXwB798jui+YG33TYC9P2zlnMScvTy/TNoNG71iLdo+QH7Q32cf/oCCoS7xrxIvAptC8ONNk2/TdvNzA1TjHmKx8lKx1IFLcKxAC89uzsoOMj27jTms37yALGyMRaxbbHy8t+0aTYCOFp6oH0Av+ZCfYTxh2+JpQuDDXvORY9Zj7SPVs7EzcXMZQpwyDmFkkMPQEZ9jLr3eBt1yzPXMg0w9+/eL4Ov5/BGcZbzDnUdd3L5+vygP4vCp4VdCBbKgUzLjqaPx5Dm0QFRFxBszwrNvUtTySDGeINyAGR9ZvpRt7p09bKV8OnvfW5X7j1uLW7jMBXx+PP79kw5U7x7f2pCiIX9iLHLUA3FT8JRepIl0oCSixHKkIeOz8yzicdHIMPYwIk9Sno2tuX0LnGjr5XuEi0grIVs/+1LLt2wqfLedaZ4qvvSf0JC4IYSyX+MEA7v0M4SnZOVVDFT8hMckfrP2w2OyuvHikRDwPR9NvmnNl6zdbCBLpKs96u5axxrYCw/LW+vYrHFtMK4APulfxOC70Zcif/MwQ/KEgjT71Tz1VIVSlSiEyORHk6ky45IdESygOZ9LPljdeVyjK/vbWCrrqpjqcQqD6rArExuY7Dys+H3Vvs1Pt5C9MaaSnINohCTEzHU7xYAluHWktXZlEDSWE+0jG2I3kUkQR69LDkrtXpx867vLEEquKkgaL1oj2mQqzWtLm/mMwR27PqB/uMC8QbMCtXOctFKVAfWG1d6V99XylcB1ZETSJC9TQkJiAWZAV19NLj/9N4xa24Ba7TpVigwp0lnoKhwKewsA+8hcms2A7pLvqFC48cxiyrO8pIu1MoXM5hf2QlZMBgaFpOUbZF+TeAKMIXQgaH9BnjgtJCw9G1maryoSGcVZmlmRGdgaPDrJK4k8Za1m/nTPlnCzUdKi7CPYJLAFffX9tlwmh8aAplhV4dVRpJ2TrGKl4ZJwew9IbiNtFKwTyze6dknj+YPZV4le+YiJ8TqUa1xcMf1NflY/gzC7cdXS+bP/RN9llCY5BprWx+bARpWGKtWEtMkz31LPEaEwjv9BbiHdCPv++wrqQtm7eUgJGikR6V2pukpTCyH8H+0UnkdffqChQeXTA3QR1Qm1xOZutsPXAocKts4GX6W0ZPJEAJL3kcBAlC9crhNc8TvuuuMqJNmIqRHo4mjqOReph5olOvpL74z8jigvaNCk4eLDGTQvtR7V4Baepvb3N1c/pvF2kCXwZSiEL/MPMd+Amp9aHhf87WvDGtCqDHlbuOG4sHi4CObJWWn7GsWLwRzlXhjvUdCmYeyjGxQ5BT62BZa4lyQXZkdu9y/GvAYYlUvUTWMl4f7Qoh9pvh+s3Yu8KrNp6dk0yMeohJiLmLspL+nE6qPLpMzPPfmfSdCVweNjKPRNlUlGJVbcd0sXjyeId1i24xZMtWv0aJNLYg4Aup9rXhps0Zu5+quJzQkT6KPYbthVGJT5Czmi2oU7iryqXep/MNCTIecjIvRdZV52PzbqN2vHoce8B3wXBUZstYjUgXNvoh0QxA9+7hgc2ZusepkJtikJSIZYT1g0mHRo65mE+mobYwyWzdufJvCOkdfzKQRYlW5GQycBt4YHzgfJZ5nHImaIVaI0p+NycjvA3k90bijM1WujqpvppSj0+H9IJkgqOFmYwRl7mkKLXex0vc0PHGB4MdXjK0RfBWi2UTcS55nX0+fgp7GnSjafdbf0u7ODwkoQ6T+LvixM1RuvmoQpqhjm6G64E7gWKES4u+lWuj6bO3xkTb8PASBwAdDzKbRQxX22WUcdx5cn4zfxh8OXXLaiBdoEzMOTUlfA9L+UvjKc6IugGpHZpPjvOFS4F6gIeDW4rBlGii57K9xVnaGvBWBmMclTFHRd9W1mW2cSR63n6/f8B8+HWca/1dgk2uOhImTRAK+vXjuM76ulOpTZpcjt6FE4EjgBODzYkclLKhJLLyxIvZT++UBa4b8TC4RGlWfGV6cQd64X7hfwF9VnYVbIxeJk5hO88mERHQ+rbkcc+lu+2p0ZrIji2GRYE1gAWDoInRk0qhobFYxN7Yku7MBOEaJDDwQ6xVzWTgcIV5e36af9p8UnYzbM1eiE7iO2wnxhGY+43lUdCJvM2qqZuQj+KG4IGygGCD1YnfkzChYLHxw1LY5e0DBP8ZMS/xQqhUzWPpb594rH3pfkx863X3a75eqE4wPOcnaxJj/HnmV9GivfOr0py1kPmH44KXgSKEbYpJlGehYrG9w+nXSu04AwsZGS69QWFTe2KXblZ3dXzOfVZ7InVga19ehE5JPD4o/RIt/XbngdLwvlutS540knOJTITmgkuFaIsNle6hqLG+w6XXwexuAgUY3ixWQNhR2mDrbKt12XpMfPp59nNvaq9dHE4tPG8oexP1/YPozNNwwAWvE6AMlE6LHIachNuGxYwtlseiMrL2w4fXTuyoAfEWgyu+Pg5Q7V7naqFz13hiejd4aHIiaa5cb03aO3ko5BO6/p7pNtUfwu6wJqI7loiNT4i5htCIhI6nl/GjArNkxJDX8evmANAVCir4PAhOtVyOaDlxcnYTeBB2eXB7Z1xbfUxQO1woNRR4/8Xqvdb8wxKzgqS9mB2Q5Io6iSmLo5B7mWulF7QKxcLXq+srAKMUdSgGO8ZLNVrjZXZurXNhdYVzKm56ZblZRUuOOhYobhQuAPbrX9gDxnC1JaeRmw2T2Y0djOWNIZOomzancbXpxR3Yf+t5/28TxybqOExJcFfnYlpriXBNcppwfWshY8ZXyEmTOaYnjRTcAC7tGdozyAW4DKq0nlSWK5FgjwCR/JUtnlGpELcAx6LYbuvR/jQSAiWoNp5GaVSfX+lnCm3bbk9tdGhwYIRVBkhgOAsnkBR/AWvu6duHys26M60hou6Z1pQAk3mUM5kIobqr9LhPyFLZeOs1/vQQKCNCNL1DI1ENXCdkM2kNa6hpEGVqXfRSAEb0NkYmeBQVAqzvy93+zMW9lrDXpdmd2Jj7lk2Yw5w4pHCuHLvXyS3an+um/bMPPSG7Ma5Aok01WBVgB2XnZqhlVWESWhhQt0NRNVUlQhScAu7wvt+Uz+rAM7TQqRCiLZ1Mm3mcqaC5p3Kxhr2WyzPb5Osm/XEOQx8XL3M96kkbVLlbimBsYlJhRV1oVvFMLEF1Mzkk7xMUAy/yv+FG0jnEBrgKrpCm0aHwn/mg4qSLq760MsCNzWXcR+y2/DENPB1YLBE6/UXCTxZXwVugXalc41hvUoFJYD5jMfIifBN8A23zy+MR1a7HC7yAslWrwKbjpMqla6mpr1G4HsO6z8LdyexY/PYLKxuBKYo24UEwSzFSrlaHWLFXM1QsTstFVTscL38h6xLQA6b04OXy10bLPcAtt1qw9ashqueqQa4RtCm8R8Yc0krfau0N/MAKExmXJuMymT1oRg1NV1EmU25SOU+gSdJBDTifLOIfOhISBNj1++fl2vvOmsQOvJq1bbGlr02wX7PAuEPArcmz1P3gK+7V+5EJ9habIx8vKjlvQbFHwEuATeZM+EnQRJg9ijTvKRoeaRE+BAL3Gero3czSG8kewRG7Ibdrtfi1wrixvZ3ETc1819niC++z+20I1xSSIEMrlzRKPCBC70WbRxtHdES+PyA5zzANJykceBBWBCH4OOz34LTWvs1YxrrADr1tu+G7Zb7iwjLJI9F22t7kDPCn+1MHuRJ+HVEn5i/9NmA86D99QRNBsz5wOm003Sz8IxAaaA9XBDX5Vu4P5K/afdK3y5HGLsOnwQbCRMRNyADOL9We3QvnLPGx+0cGnRBjGk4jGiuMMXU2sTkpO9Q6uDjoNIQvuSi9IM8XOA5BBDr6b/At57neVdc30Y7Me8kTyF/IWcrvzQPTa9nz4F/pbPLS+0gFhg5DFz4fOCb+K2YwTzOlNGI0iTIsL2gqZSRSHWkV6QwUBDH7g/JN6s7iQNzT1q7S8c+tzunOoNDE0zfY1t1z5NjryvML/FoEdwwjFCQbRSFXJjcqxyz4LcItKyxBKR4l5B++Gd4SewvPAxf8jfRt7evmOuGE3OvYidZt1Z3VFNfF2ZjdbOIa6HTuR/Vc/HwDcQoFEQUXRBycIO0jICYmJ/smoiUqI6gfOhsEFjEQ8AlyA+z8jfaJ8AzrP+ZH4kDfPt1O3HbcsN3w3yLjKufn6zLx4PbF/LECdwjsDeQSPBfSGo8dXx82IBIg9h7uHAwaahYmEmMNSAj+Aq79gfie8yzvS+sW6KblCuRM427jbeQ95s/oC+zV7w/0lvhG/fkBiwbaCsUOLxL/FCIXiRgtGQwZKhiQFk4UeREoDncKhQZxAlz+Zfqq9kjzV/Dt7Rns5+pf6n/qRuup7JzuC/Hj8wr3Z/rf/VQBrwTUB6wKIw0nD6sQpRESEvARRBEXEHMOagwMCm4HpgTMAfb+Ofyq+V33YfXF85Py0PGB8aTxNvIu84P0KPYM+CD6UvyP/sUA5ALcBJ0GHAhPCTAKuQrqCsQKTAqHCYAIQQfWBUsErwIQAXr/+v2b/Gb7ZPqb+Q75v/it+Nb4NvnH+YH6XPtO/E/9Vf5X/0wALQHzAZsCHwN9A7YDygO7A44DRQPnAnoCAwKJAREBoAA8AOn/p/96/2H/W/9o/4T/rP/c/w4AQABsAI4AoQCkAJMAbgA1AOn/i/8f/6r+MP63/UX94PyO/FT8OPw9/Gb8tfwq/cP9ff5U/0EAPgFEAkgDQgQoBfAFkwYIB0kHUAcbB6gG9wUMBewDnQIpAZz//v1f/Mz6Uvn/99/2/fVk9Rz1KPWM9Un2Wve7+GL6RPxV/oMAvwL4BBsHFQnWCk4Mbw0sDn4OXw7MDcgMVwuBCVUH3wQzAmX/ify3+QX3ivRb8orwKu9H7uvtHO7c7ifw9/FA9PL2+vlB/a4AKQSUB9UK0Q1uEJcSOBRCFagVZhV7FOkSvBABDssKMgdQA0X/LPso91jz3O/P7E3qa+g758nmG+cx6Afqkey973bzn/ca/MMAeQUVCnQOcRLrFccY6hpCHMEcYRwgGwcZIhaFEkwOlAmBBDv/6fm19MjvS+ti5y3kx+FH4LvfKeCS4e7jLec36/HvNvXg+sEArwZ6DPQR8RZJG9gefyEoI8MjSCO3IRsfhBsMF9QRAgzDBUj/wPhf8lns3OYW4i3eQ9tx2cfYTtkF2+HdzuGy5mfsw/KV+aoAywfADlIVThuCIMQk8SfuKagqFio6KCAl3SCQG2AVew4WB2r/svcp8AvpkuLw3FTY5NS90vPRj9KO1OXXe9ww4troRvA7+HwAywjmEI0YhB+TJYgqPC6OMGkxxTCjLhErKSYNIOwY+xB3CKL/v/YT7uPlcN7116bSsM4zzEXL8cs0zv/RONe43U7lwu3T9joAsAnrEqIbkSN4Kh8wWTQCNwI4TzftNOkwYiuAJHYcgRPmCe//6PUf7OLiedoo0yjNq8jWxcPEe8X8xzbMCdJM2cfhO+te9eT/eQrOFI8ecSctL4Q1RDpFPWw+sD0RO6M2hTDkKPofChZgC08ALfVP6grgsdaMzt7H28Kuv3G+Mr/swY3G9Mzx1Ejesujf83r/JguMFlEhISuuM7M6+D9SQ6NE4EMMQTk8izU1LXMjkhjkDMMAjvSi6F7dGdMmysvCRL2+uVa4G7kJvAvB/cer0NXaK+ZY8v3+twsmGOgjny74N6c/cEUjSaFK3EnWRqZBcjpuMeAmFxtvDkgBC/Qa597atc/5xfW967cMtHeyPLNYtrS7KcN/zHDXqOPJ8G7+LQybGVAm6DEIPF5EqUq1TmFQnU9tTOZGMz+MNTwqlx0AEN8Bo/O45Y3Yh8wHwl+51LKbrtismq3esIy2fL5wyB7ULOE279D9hwzqGooo+zTaP9NInU8CVN5VH1XJUfRLy0OLOYMtDiCVEYUCV/N85GvWkclUvgy1A65yqX6nOqigq5qx+rmCxOLQut6g7SL9xgwTHJQq1DdtQwNNSlQHWRNbXVrnVspQNUhnPbMweiIrEzoDJfNm43rU1cbiugCxfKmUpG+iH6OjpuCsqbW6wL/NVdwK7Gf86gwWHWwsczq+RutQq1i+XfxfUl/CW2VVbUwbQcgz2CTAFPsDDfN34rvSVMS0tz2tQqUEoK2dUJ7soWWojLEbvbnK/9l26qD79gzzHRIu1jzKSYhUvFwlYpZk+mNVYMBZblCkRL42JSdSFsgEDvOt4S7REMLLtMapWaHHmz2Z0Jl+nSukp62oudTHvNfm6M766AypHoYv+z6PTNhXfGA3ZttoUmidZNddNVT/R5I5XinfF54FJ/MK4dPPCsApsp6mxJ3glyOVopVdmTig/qlnthHFjtVd5/T5www6H8cw4kAMT9ha52PyaclsVGyVaKdhvlcnS0E8gCtlGXwGWPOM4KzOQ77Rr8ejhJpSlGKRzJGOlY6clqZZs3bCeNPc5RP5iAylH9UxiUJAUYZd+2ZTbV1w/m86bCplBVsZTsg+iS3hGmAHnvMz4LfNu7zCrUKhnZcfkf2NT44UkjKZcaODsATAfdFm5C34NwzsH7Ay8UMpU+FftWlXcJJzTXOIb19oCF7SUCRBdi9QHEgI+PP+3/bMc7v+qxGfEZVLjveKL4vyjiaWkqDorb+9n8/94kP30wsPIFgzGUXHVOdhE2z7cmh2PXZ8ckFrwmBPU1FDRDGxHTIJZvTt32fMa7qHqjad4JLXi1OIb4gsjG6T/p2Kq6q74s2k4Vj2XAsPIM4zAUYYVphjFW4+ddp4zXgUdc5tMGONVU5F8DIBHx0K5fT+3wnMo7lcqbGbDZHFiRKGEYbDiQ2Rtpttqce5R8xd4G711QrtHxM0qUYeV/JkuW8ed+h6+HpNdwNwUWWJVxdHeDQ/IAYLdfUw4N3LG7l9qIKamY8XiDeEGIS6hwSPvZmSpxm40soq34b0PgqsHyc0EUfWV/Rl/XCaeJB8v3wled5xIWdBWalI2zVnIewLEvaB4OHL07jqp6uZhI7OhsOChIIUhleNFpj+paK2g8kO3qPzmglLHws0OkdDWKBm4nGxedB9H36aelxznmiyWgNKFDd3IswMvPbx4BTMyLijpyuZz43phbeBWIHShAiMw5axpGW1X8gK3cby6gjMHsEzJkdkWPVmZ3Jjeqh+Fn+qe310xmnaWyNLIzhvI6UNcfd94XXM+7iopwGZeo1rhROBlYD0gxeLxpWuo2S0Zscg3PLxMQgyHkoz1UY6WPNmjXKuehd/pX9UfD11mGq3XAZMBjlKJHUOL/gl4gLNa7n3py6ZhI1ThdmAO4B+g4aKH5X2oqCzmsZT2yjxbwd+HacySEbGV5tmU3KTehx/yn+XfJ51E2tJXatMujkJJTkP9Pjm4rrNFbqPqLGZ7Y2ghQmBS4Bug1eK0ZSMohuz/8Wk2mrwpwaxHNsxgUUKV+5lu3EUerh+hX90fJx1NGuMXQ9NPTqoJfAPvvm+45vO+LpvqYeatY5ShqGBxYDFg4mK3ZRvoteylMUV2rrv2wXOG+YwgUQGVu5kxXAveex91n7oezl1/GqCXTNNjzomJpgQjPqs5KLPE7yVqrGb2Y9oh6GCqIGEhB6LQpWiotSyW8Wo2RvvDQXWGswvS0O+VJxjc2/nd7d8v332enN0amonXRRNrTqCJi8RW/ut5c/QY70ArCudWJHiiAmE9IKqhRSMApYkoxSzV8Ve2Y3uPgTMGY0u4UEyU/phx209dhx7P3ydeUxzfWl9XLJMmDq6JrMRKfzA5h/S576srfSeMZO8iteFqIQ2h22NG5f2o5izh8U42RLucQOxGCwtREBlUQpgwmszdBx5WHred8NxNmiDWw1MTDrMJiQS9fzi55DTnMCZrwqhYZX2jAmIwoYniSaPj5gYpWC07sU52aztpwKIF6wreD5aT89dZ2nLcbl2DHi7ddlvlWY4WiNLyzm4Jn4SvP0R6R/Vf8LDsWuj5peMj56KQIl8iz+RXJqLpmy1isZh2V3t4gFTFg8qfzwSTUpbuWYHb/RzXHU1c5BtnGSeWPVJEzl8JsISfv5M6srWjsQntBKmvZp9kpKNIYwzjreTgpxNqLy2Xsex2SbtJQEUFVcoWjqSSoBYumPqa9FwS3JNcOpqSmK0VoJIIzgYJuwSN/+P647Yx8bDtv+o453FleOQYY9KkYyW/55eqlC4acgq2gjtcADNE4cmDjjbR3JVbWB3aFJt224Hbedno198VMxG/TaLJf0S5//Z7GnaJsmUuSysVaFimY+UAJO+lLyZ0aG9rCm6q8nM2gTtx/+AEqIknjXxRCVS1lyxZHppD2tlaYpkplz3UdJEnzXTJPMSigAo7lncqMuWvJivEKVQnZGY+JaOmEWd+KRor0O8JcuY2xztKP8wEakiCzPXQZxO+FicYE5l62ZpZdZgVlkmT5ZCCjTyI84SIgF571reSs7Hvz6zEKmLoeecR5u1nCShcKhesqC+1syO3FDtmP7fD6AgWTCRPtpK11Q8XNBgcmIYYc1ctlULTBlAPjLmIosSqwHK8GrgCtEiwxq3Ua0Qpo2h6Z8woValN6ydtT7BvM6v3aLtF/6ODokejC0iO+RGeFCUVwRcp11zXHNYyFGoSFw9PDCwISsSJAIa8ofi5NOkxiq7z7HZqn2m26T9pdepS7AjuRrE2dD73hHupv1ADWccpiqON71C3UuqUu9WkFiAV8tTj00ARWA6BS5QIKwRjAJm863k1dZJymi/hbbkr7WrGKoWq6WuqLTuvDTHKtNw4J/uR/33Cz0aqifYM2k+DEeATZZRL1NCUthODkkUQSg3myvGHg8R4QKs9Nvm2tkOztDDb7sqtS+xm694sLyzTLn6wIrKrtUP4kvv+/y0Cg0YnSQFMO05CUIeSPxLik2+TJ9JSUToPLYz/SgTHVMQIwPq9Q3p79zv0V/IicCouue2YLUethe5Mr5GxRjOZNjX4xbww/x6CdoVgSEYLE012TyGQihGpkf3RiNEQz9+OAwwLyY2G3gPUQMf90DrEeDn1RDNzsVZwNe8YrsDvLK+V8PNyd7RStvH5QHxofxKCKYTWh4VKI0wgTe+PB1Ah0H0QGo+ADrbMywsMSMzGX4OaQNJ+HTtPeP02d7ROcs3xvvCnMEjwonEt8iMztfVXt7e5wryk/wnB3QRKhsAJLErBTLLNuI5Mzu4Onc4hDQBLxkoByAIF2YNawNm+aTvb+YQ3sXWxdA9zE3JCch5yJbKTs6A0wLan+Eb6jLznfwRBkYP9hfdH8AmaiyzMHszrzRKNFAy1C70KdcjsRy5FC8MVgN1+s7xpek54sDbbdZm0sfPo87/ztbQFtSk2FreCuV97Hj0vfwKBSANwBSwG7whtiZ6Ku4sAS6uLfkr9Ci4JGkfMhlFEtoKKgN0+/Hz2+xp5szgLNys2GXWZNWw1ULXDNr23d7inOgC79z19fwTBAILixF9F6oc7SAnJEEmLifqJnkl6SJSH9IajRWvD2cJ5wJi/An2DvCe6uLl/eEL3x/dR9yG3NbdK+Bw44jnU+yo8V33RP0uA+8IWw5HE5AXFRu/HXofPSADINMeuBzFGRUWxRH5DNkHjAI+/RX4O/PT7v/q2+d85fLjRuN744zkbeYO6VfsLPBt9Pn4q/1cAuoGMgsTD3ESMxVHF54YMhkAGQ4YZhYXFDYR3A0lCi4GGQIG/hP6XvYF8x7wwO3569bqW+qK6l7rzuzL7kTxI/RQ97H6Kf6dAfUEFAjlClMNTA/FELQRFBLnETAR+A9MDjoM1gk0B2oEjwG6/gD8dvkv9zv1qPN+8sXxgPGs8UfyR/Ok9E72N/hO+oL8v/70ABADAwXABjkIZQk+CsAK6gq9Cj4KdAloCCQHtgUpBI0C7QBZ/9v9f/xP+1H6jfkF+bv4rvjc+EH51fmS+m/7Y/xl/Wv+bP9fAD4BAwKnAigDgwO5A8oDuQOJAz4D3wJwAvkBfwEHAZgANQDj/6P/d/9f/1z/av+H/7D/4f8TAEQAbwCQAKIAowCRAGoALwDi/4L/Fv+g/ib+rf08/dj8iPxR/Df8P/xs/L78Nf3R/Y7+Z/9VAFQBWQJdA1YEOgX/BZ8GEAdMB04HFAebBuYF9gTRA38CCQF6/9z9Pfyr+jT55PfJ9u71W/UZ9S31mfVc9nX32/iI+m/8gv6yAO8CJwVHBz0J+QpqDIINNw6ADlcOuw2tDDMLVgkjB6gE+AEo/0z8fPnO9lj0MPJp8BLvOu7q7Sfu8u5J8CTydvQv9z36if34AHIE2wcYCw0OoRDAElQUUBWpFVkVXxTBEocQwA2CCuIG+wLt/tX61PYK85bvlOwf6kvoKufI5irnUeg36s/sCPDL8/z3fPwnAd0FdQrNDsASLxb8GA8bVRzCHE4c+xrQGNsVMRLrDSoJEgTJ/nj5SfRk7/LqFufx457hMuC63z7gu+Er5Hvnlutd8Kz1XPtAAS0H8gxjElQXnRsZH60hQCPDIzEjiSHXHiwboxZdEYELOwW8/jX42/He62/muuHl3RHbV9nG2GfZN9sq3i7iJOfp7FDzK/pCAWIIUQ/YFcUb5yATJSgoCiqoKvspBCjQJHUgFBvTFOENdAbF/g73jO966BHig9z/16nUn9Ly0azSyNQ72OvctuJy6evw6fguAXsJjxEqGQ8gCCbkKnsurjBqMaYwZS61KrIlfh9KGEsQvQfk/gP2X+085dvdd9dE0mzOD8xEyxLMds5h0rfXUN775X7umfcEAXgKqxNUHC8k/SqIMKE0JzcEOC03pzSCMNwq3yO/G7oSFAkZ/xT1VOsm4tLZmtK5zF7IrsXAxJ/FRsijzJfS9tmI4g3sPPbFAFkLpBVWHyIowi/6NZU6cD1vPoo9xDowNvAvMSgvHywVdwpi/0H0bek53/bV7s1ix4XCgL9uvlm/PMIFx5DNrNUd35rp1PRyAB0MeRctIuUrUzQ1O1NAgkOnRLhDuEC8O+k0cSyVIp8X5Au//4vzqud43E3SeclDwuW8i7lRuEW5YLyNwabId9G82yjnYvMMAMUMKRnYJHUvrTg2QNRFWUmnSrFJfUYgQcI5mzDvJREaWg0tAPLyDebk2dfOPMVgvYO307NwsmiztLY/vN7DWs1p2Ljk6fGU/1ANsxpUJ9AyzDz5RBZL8E5oUHBPDUxXRnc+qjQ6KX0c1g6vAHXyl+SA15fLO8G+uGOyXa7QrMetQLEgtz2/Wcko1U/iavAK/74NFhygKfM1rUB6SRNQQ1TnVfFUZFFcSwRDmzhxLOIeVxBBARXyR+NM1ZHIer1ftImtL6l0p2ioB6w2sse6ecX80e/f5+5w/hEOUh28K904T0S2TchUTVkfWy1aflYrUGNHaTyRLz0h2xHjAdDxHuJJ08TF+rlHsPmoSqRhok+jDqeErYC2vsHozprdY+3H/UgOZx6lLYw7rUepUTJZCl4LYCJfVVu/VJFLEUCXMosjXxOSAqbxHeF50TTDvrZ5rLektZ+dnYCeWqIPqWyyKr7wy1Tb3+sS/WUOVR9cL/09xkpRVUxddmKnZMpj5V8TWYlPj0OANcgl4RRNA5bxQ+Dcz+HAyLP4qMagc5sqmQCa753bpJCuw7oYyR/ZX+pR/GgOGyDfMDBAmE2rWBRhjmbvaCFoKmQlXUlT30ZIOPQnYBYUBKDxkN9zzs6+G7HGpSidhpcNldOV0ZntoO+qi7dhxv/W5OiF+1IOuyAuMiRCIVC1W4ZkT2rgbCRsH2jvYMtW/knsOgkq1xfjBMHxBN8+zfq8t67louGZ85NJkfuRBJZHnY2nhrTQw/XUcOey+iUONCFJM9hDX1JtXqFntW12cM9vw2tvZAxa6ExqPQcsRxm6Bfrxnt49zGa7nqxXoPOWu5DijX6OjJLumW2kt7FowQTTBebY+eENhyExNEtFU1TQYGJqvXCvcx9zEG+gZwldmk+9P+otqxqXBknyXd5vyxO60KoenmCU4o3Zil2La4/mlpOhI68rvzDRp+T5+IgNtiHkNH5G+VXeYsdsZ3OHdhB2BHKAar5fEVLjQa8vAxx3B6zyQd7WygK5UKk7nCmSaYsxiJuIpYwwlAOfyqwcvXrPV+MY+BsNwCFkNW5HU1eWZM9urnX9eKF4m3QLbSliSlTZQ1QxSx1ZCCLzSd5wyjK4HaivmlCQU4nuhTyGPIrQkb6csao/u+bNF+I295wMpyGxNR5IYFj3ZXhwk3cOe8561XY/b0dkQ1adRdcygh47Carzct48yqK3N6d6mdeOoIcPhEGEM4jIj8ea2qiVuXbM6uBU9g0MbCHMNY5IH1n/ZsJxE3m5fJd8rXgZcRZm+FcsRzQ0pB8bCkH0vt45ylO3nqadmL2NU4aYgquCi4YcjiGZSKchuCvL0t929W4LESG2Nb1IkVmwZ6xyLnr8ffl9I3qYcpJnZ1mESGs1sSD3Cub0KN9nykO3U6YZmASNa4WJgX2BR4XLjM+X/KXmtgnK0d6d9MIKlyBwNa1ItlkJaDVz43rXfvN+NXu6c7toj1qiSXg2piHNC5j1sd/EynO3U6bsl6uM6YTjgLiAaITZi9CW+aTltRHJ6d3L8wsK/x/8NF9IkFkKaF1zMXtJf4R/4Xt8dI9pbVuFSlo3gSKbDFT2V+BPy9+3oKYWmLKMzoSmgFuA74NHiyiWQKQgtUbIHN0B80oJTB9bNNRHHlm1ZyZzGXtRf6t/J3zfdAtqAFwrSw84QCNgDRn3F+EGzIi4NqeWmBmNGYXTgGmA3YMVi9iV06OZtKjHa9xC8oIIfx6PMw1HY1gKZ5BynHrvfml/BnzgdC9qR1yTS5U44SMZDuX38OHnzGy5Fqhsmd+NyYVpgeCAMYREi+CVs6NRtDrH2tuQ8bQHmh2ZMg1GYFcKZptxuXklfr1+fnuAdPtpQFy6S+s4YyTEDrX44eLxzYi6PKmVmgKP3oZngsCB7YTUi0GW4aNKtP3GaNvs8OIGnxx8MdZEFla4ZEpwcnjzfKl9j3q/c21p6luhSw45xCRgD4j55uMhz9u7qaoQnIGQVojNgwmDD4bHjPyWXqSFtPPGGNtZ8A4GkBs5MGhDiFQUY51uyXZZeyx8OnmccoZoRltFS/84AiXqD1z6/uR10GK9WKzbnVuSMIqZhbqEl4cajhCYKqUCtRzH7NrX7zoFcBrTLsdBuFIiYZdsv3RbeUd6f3cYcUVnU1qnSrs4HCViEDD7J+bs0Ry/Sa70n4yUaozKh9GGhInOj32ZRabCtXrH5Npp72gEPxlNLfU/p1DjXjtqVnL4dv53YHU0b6tlEFnFSUM4EiXGEAD8XueC0wbBeLBYohOXAY9dikyJ1YvikUObr6fFtg3IAtsQ75kDARinK/Q9Wk5bXIpnkW81dFF13nLxbLljflehSJU34CQUEcz8o+g21R3D4rIEpe6Z85FRjSuMh45UlGGdaakLuNbIR9vN7tECtxbmKcg700uLWYdkc2wScUJy+29Qam9hnlU5R7E2iCRLEZH98ekF117FhrX2pxidPZWikGmPmpEil9afcKuUudXJs9uj7g8CZRULKHI5FEl4VjZh/miTbdVuumxUZ9BecFOORZc1CCRpEU7+SOvr2MfHX7grq4+g3JhNlASTCpVLmqCixK1huwvLSNyR7lcBCxQZJvY2IUYjU5pdNmW8aQxrHGn/Y9xb9VChQ0Y0XyNuEQH/pOzo2lXKa7uerk+kzZxQmPuW1JjNnb2lZLBvvXbMBd2a7qoArBITJFg0/UKST7dZHWGPZepmJWVSYJZYME5yQcAyjSJYEaj/BO733ATNpr5MslWoC6GnnEib9pykoSupTrO+vxjO7N2+7goASxH7IZkxqz/HS49VuVwQYXJi2WBRXABVIUsDPwMxkiEmEUEAZu8X39LPDcIztp2slKVNoeifbaHOpeisgbZNwu/P+9797nj/6Q/UH70uMDzHRyhRDVhDXKpdOVz+Vx1Ry0dUPBIvbSDYEMwAx/BE4bvSnMVMuiKxYqpAptikNaZIqvGw+rkaxfrRNeBa7/T+iQ6hHcgrjziVQ4ZMHlMsV5NYS1deU+9MMERoOe0sHx9tEEcBJvJ847zVT8mWvuG1cq95qxOqSasOr0S1t70kyDnUl+HU74L+LQ1lG7woyzQ1P6xH703RUTRTEVJzTnlIUkBBNpQqqR3kD7EBgPO85dHYI80Kw9S6vrT2sJavprAdtNy5tcFpy6vWIuNs8CH+1gsiGZ0l6DCsOqBChkg0TJBNkkxCSb9DNDzfMgooCRw9DwgC0/QB6PjbE9Gmx/i/Q7qwtlq1R7Zvube+8sXnzk7Z1eQi8dT9hwraFm8i6yz/NWU96EJdRq1H0EbPQ8Q+2TdGL08lQhp4DkwCHfZK6i3fHdVlzEjF+r+kvFu7KbwCv9DDasqb0iDcsOb28Zr9QQmSFDQf1ygwMQI4GD1PQI5B0UAePo05RTN4K2UiVBiVDXsCXveT7G3iOtlB0b7K4MXLwpXBRMLRxCTJGs+C1iHfsejo8nb9BghKEvAbsCRGLHoyHjcPOjs7mTozOB00ei54J08fQBaTDJQCkvjZ7rTlad041lbQ7sshyQLIlsjWyq/O/tOa2k3i2Or582f92QYGEKcYeyBFJ9Ms/TCkM7Y0LzQUMnkufSlIIw4cBxR0C5gCufka8f/opOFD2wrWINKgz5zOGM8O0WvUFNng3qLlI+0n9W/9uQXIDVsVOhwxIhMnvCoTLQguly3FK6UoUSTtHqQYqxE3CoUC0fpU80vs6eVf4Nbbb9hD1l7VxdVy11XaVd5R4x/pkO9y9o39qQSSCxAS8xcPHT0hXyRhJjQn1iZNJaYi+h5oGhUVLQ/eCFsC2PuF9ZTvMuqG5bXh194D3ULcl9z+3Wjgv+Po58DsHvLZ98L9qwNnCckOqRPjF1cb7R2UH0Eg8x+vHoEcfhm+FWMRjwxpBxoCzfyq99jye+616qDnUuXb40LjieOs5J7mTumj7IPwzPRc+Q/+vwJJB4kLYQ+yEmcVaxeyGDUZ9BjyFzsW3xPzEJAN0gnYBcIBsP3B+RP2wvLm75Tt2+vF6ljqlep36/Ps/O5+8WX0l/f6+nP+5gE6BVQIHQuBDXEP3hDBERYS3REbEdkPIw4KDKAJ+gYtBFIBf/7I+0P5AvcW9YvzavK78X/xtfFY8mHzxPR09mL4fPqx/O/+IgE7AysF4gZVCHsJTQrHCuoKtgowCmAJTwgHB5YFBwRqAssAOP+9/WT8N/s++n/5/Pi3+LD44/hL+eP5o/qD+3j8e/2B/oH/cwBQARICswIxA4kDvAPKA7YDgwM3A9YCZwLvAXUB/QCPAC0A3f+e/3T/Xv9c/2z/iv+0/+X/FwBIAHMAkgCjAKMAjwBmACkA2v96/wz/lv4b/qP9M/3Q/IL8Tfw2/EH8cfzG/EH94P2f/nr/agBpAW8CcwNqBEsFDgaqBhcHTgdMBwwHjgbUBd8EtwNhAugAV/+5/Rv8i/oW+cv3tPbf9VP1GPUz9ab1cfaQ9/34rvqa/LD+4gAfA1UFcgdlCRoLhQyVDUEOgQ5ODqkNkgwPCyoJ8AZwBL0B6/4P/EH5l/Yn9AbySPD77i7u6e0y7grvbPBR8qz0bveC+tH9QgG8BCMIWgtIDtMQ5xJvFF4VqRVLFUMUlxJREIANOAqRBqYClv5/+oH2vfJR71rs8eks6BvnyeY753PoaOoO7VPwIPRZ+N78jAFABtUKJQ8PE3EWLxkyG2ccwRw7HNUamRiUFdsRig3BCKIDWP4I+d3zAO+Z6szmt+N34R7gvN9U4ObhaeTM5/bryfAi9tj7vwGqB2oN0hK3F+8bWh/YIVUjwiMYI1ohkh7UGjkW5RD+CrEEMf6s91fxZOsD5l/hnt3h2j/ZyNiC2Wvbdt6P4pjnbO3f88D62wH4COEPXRY7HEkhYCVcKCQqpirdKcsnfiQMIJYaRRRHDdIFIP5r9vDu6ueR4RjcrNdx1IPS9NHL0gXVk9hc3T3jCuqR8Zj54AEqCjYSxBmYIHsmPiu4Ls0waDGEMCQuVyo4Je4epheZDwIHJv5H9avsl+RJ3fzW5NErzu/LRcs1zLvOxtI42OreqeY872D4zwFAC2oUBR3LJIEr7jDnNEo3AjgHN140FzBTKjwjBhvxEUEIQv5A9Inqa+Es2Q/STMwUyInFwcTGxZLIE80n06LaS+Ph7Bv3qAE5DHoWHCDRKFUwbDbkOpc9bz5hPXQ6uzVZL30nYh5NFI0JdP5W84zoad4+1VPN6cYywla/br6Dv5DCgMcuzmnW89+E6sn1bAEUDWUYByOmLPY0tDuqQK5DqESMQ2FAPDtENKwrtSGrFuQKuv6J8rPmlNuC0c7IvsGJvFy5ULhyubq8EsJSyUXSptwm6G30HAHSDSsaxiVIMF85wkA0RotJqUqCSR9GlkAQOcUv/SQIGUQME//a8QHl7Nj7zYLEz7wet5+zbrKYsxW3zryXxDfOZdnL5QnzuQByDskbVii1M409kUV/SydPbFA/T6lLw0W4PcUzNShhG6wNgP9J8XbjddaqynPAIbj2sSSuy6z5raaxuLcCwEbKNdZ0457xRAD1DkAdtSrpNn1BHUqFUH9U7FW+VPxQwEo5Qqc3XCu0HRkP/v/U8BPiLtSTx6O8trMTrfCobqecqHKs1rKXu3TGGdMm4S7wvv9cD5Ae4izjOSxFZE5CVY9ZJlv5WRBWh0+NRmg7bC79H4oQiwB88NjgGtK2xBW5k697qAakWaKEo36nLK5at8XCFNDi3rzuKP+mD7cf3S6hPJhIY1K0WVFeFGDtXuNaE1SxSgQ/ZDE7Iv0RKAFA8MXfOdAXwsy1uqsxpGyfk522ns6ivalQsz6/Ks2s3ErthP7UD7UgozAhP75LFVbWXcNismSUY29fYlihTnZCPzRqJG8T0wEf8Nrejc62v8qyL6g3oCSbHpk2mmaekKV9r+G7XsqF2tnr0/3oD4whNjJjQZxOelmmYeBm/WjrZ7FjblxYUrxF+zaHJt4UigIY8BjeFc2VvRCw8qSSnDKX/pQJlkuap6Hjq7O4tMdy2GzqF/3hDzoikzNkQzBRjVwgZaVq8Wzua6RnM2DSVdFIlDmQKEkWSwMs8H3d0su0u6GtCKJEmZqTN5ExkoCWBp6IqLe1LcV01gXpUfzCD8EiuzQkRXpTTl9CaBBuinCab0ZrrmMNWbNLBzyCKqwXFQRX8ArdxMoVun6rcZ9Oll2QzY2zjgqTsZpvpfCyzsKO1Kbng/uKDyEjrzWiRndVumEKax5xxXPqcpFu3GYFXF5OUj5bLAUZ5gSa8L3c7Mm4uKepMJ20k3+NwYqRi+qPq5eaomKwmcDD0lLmsPo8D1sjbTbeRydX0GN2bcxzoXbddYRxuWm2Xs9QcEAXLlMavAXy8JfcSMmctx6oRZt4kQGLFojOiCSN+JQNoA+ukr4W0Qvl2PnaDm8j9jbYSIpYj2WEbxh2GXlveBx0QmwdYQNTYEK1L5MblQZf8ZXc2cjDtuOmspmZj+eI0IVthruKmZLLnfururyIz9Pj/vhjDl4jTDeQSZ1Z9mYycQF4LnueelZ2dW45Y/hUH0QyMcMccAff8bfcncgttvald5gajjCH74NwhLKIk5DXmyeqFbsdzqziI/jaDSsjbjcGSmNaBWiBcoV523xofC94T3AGZapWqkWLMuAdSghw8vzclMjXtVillZf8jN+FdILZggmH5o4ympeopLnWzJnhSvdBDdUiXjc7Stpaumhvc6R6In7MfaZ5znGCZhhYAEe/M+keIQkR82LdvcjDtQelDJc/jPOEYoGpgcSFlY3fmEynari3y5vgdPaZDGAiHTcwSgRbF2n8c1x7/37Ifrl68HKrZz9ZHUjKNNwf9Qm/8+fdFsnutQSl25bii26EuoDhgOOEoozgl0imarfAyrTfpPXlC8shrDblSeFaHGkodK57c39cf2d7tXN/aB5aAEmsNbYgwQp69IrenslYtk2lA5fni1CEeoCCgGiEDYw3l46lpLb0yefe2/QlCxkhDDZcSXJayWjzc5h7fn+Gf7B7GXT9aLNaqEliNnYhhgs/9UrfVMoAt+KlgZdLjJmEpICNgFKE2Ivklh+lG7ZUyTXeG/RcCkwgQDWWSLhZIGhecx17H39Gf5J7HnQlafxaEkrqNhkiQQwL9iTgNsvjt8GmVZgQjUeFOIEBgaSEBIzplvyk0LXjyKDdZ/OMCWUfSTSWR7RYIWdrcjx6V36efg17wXP0aPlaPUpDN54i7wzf9hfhQcwAueinfpkyjlqGNILegVyFkYxGlyalxbWiyCvdv/K2CGceKjNcRmlXzmUacfd4J32MfSF6BHNraKhaKUpsNwQjkA229yDidc1Wulap+pqxj9GHmIMlg3uGf437l52l+rWSyNXcJvLdB1Qd4zHrRNlVKWRtb053kHsRfNB45nGJZwpa00ljN0kjIQ6Q+D3jzs7huwirx5yLkaqJYoXShP+Hzo4KmWOmcLa0yKLcnfECBy0ceDBGQwVUNWJnbUV1k3kwehl3Z3BOZh1ZPUknN2sjoQ5r+W3kS9Cgvf2s456+k+SLkYfnhuiJfJBxmnanKLcKyZHcJvEoBvUa6i5uQfFR818Ia9xyMnfqd/90iG67ZOJXZEi4NmkjDg9E+q3l6dGQvzGvSqFHlnyOI4pfiTSMipIwnNmoIriTyaXcxPBQBa4ZPS1nP55PZl1VaBZwb3Q/dYFyTGzQYllWSEcUNkMjZg8a+/vmpdOuwaKx+6MkmW+RFo07jOKO9pRGnomqXrlRyt/cdvB9BFoYcisyPRBNkVpPZfZsTXEzcqNvsmmPYIJU60U8NfYiqQ/r+1ToftX5w02086ZSnLqUZpB2j/CRvpeyoIas3LpFyz/dPvCvA/sWjCnTOklKeFf6YYBpz23JbmZsvGb4XV9STEQuNIMi1A+1/LfpcNdsxi+3LqrNn1yYEpQPk1uV4Jpzo9CunLxtzMbdH/DpApQVjidMOE1HHVRZXrVl92kCa85obmMOW/BPa0LrMugh6A92/SLredkFyUS6qK2So0+cFZgDlyCZWp6GpmSxnb7KzXTeGPAtAicUeyWiNR9Eg1BwWpphymXiZtxkyV/RVzZNSkBzMSYh4Q8t/pHsltvBy4q9X7Gep5GgbJxOmz2dKqLrqUK038Bdz0vfLPB8AbYSVCPWMsJAsExDVjJdSmFtYpRgz1tGVDRK6T3HLzsgwA/Y/gPuxd2czvzAT7Xtqx2lE6Hsn6+hTKadrWi3X8Mj0UngWvDYAEQRHiHsLzs9pkjUUYJYfFynXfpbhVdtUOtGSjvmLSgfhA91/3bvA+CU0ZjEc7l5sPCpB6bapHGmvqqcsdS6HcYe03DhpPBCANIP2h7nLIw5aUQqTY5TZFeSWBBX7VJKTF1DbTjSK+0dLA8CAOfwTOKk1FnIx71AtQSvQqsUqoGre6/jtYO+F8lL1cDiC/G8/2IOjBzLKbo1/j9ISFpOB1I1U9xRCk7fR40/VjWLKYoctw6AAFTyn+TL1zvMSMI9ule0wbCUr9mwgbRvunPCS8yq1zfkjvFH//cMNRqbJskxaTsyQ+tIaEySTWFM4kgxQ347BTIUJ/8aJg7tALzz+OYD2zvQ8MZqv+G5frZXtXW2zLk+v6HGuM862tXlLvLk/pML2hdaI7strjbuPUZDjkawR6RGd0NCPjI3fi5sJE0Zdw1GARz1VelL3lTUvMvExJ+/dLxYu1K8Vr9MxArLWtP53Jvn7PKU/jcKfBUNIJcp0jGAOHA9fUCSQapAzj0XOa0ywiqXIXQXqgyMAXP2s+ue4YPYp9BFyozFn8KRwWnCHMWUyavPL9fk34bpx/NY/uUIHxO1HF4l2SztMm43Ojo/O3c67De0M/Et1CaVHncVwAu+Ab/3D+765MTcrdXpz6LL+cj+x7bIGcsSz3/UNdv74pbrwPQx/qAHxBBXGRYhyCc6LUUxyzO7NBE01TEcLgQptyJpG1UTuQraAf74Z/Ba6BLhyNqp1dzRfM+YzjPPSNHC1IXZaN885srt1vUg/mgGbw72FcMcpCJtJ/sqNS0MLn0tjytUKOgjbx4WGBARlQngAS76ufK762rl9N+C2zXYI9Za1dzVpNeg2rfexeOj6R/wCPcl/kAFIQyUEmgYcR2KIZUkfiY4J8EmHyViIqEe/RmcFKkOVAjPAU/7AvUb78fpLOVu4abe6Nw+3KvcKN6m4BHkSegu7ZbyVvhB/igE3gk3DwoUNBiXGxoerB9EIOIfiR5JHDQZZxUAESMM+AaoAV78P/d28iXubOpn5yvlxeM/45njzuTR5o/p8ezb8Cv1wPl0/iIDpwfgC60P8hKYFY0XxRg3GeUY1BcPFqYTrxBDDX8JgQVqAVr9b/nI9YDyr+9p7b3rtepX6qLqkesZ7S3vuPGm9N33RPu+/i8CfgWSCFQLrw2UD/YQzhEXEtIRBRG4D/oN2QtpCb8G8QMVAUP+kPsQ+db28fRu81fysvF/8b/xa/J78+b0m/aO+Kv64fwe/1ABZgNSBQMHcAiPCVoKzQroCq0KIQpMCTUI6gZ1BeUDRwKpABj/n/1J/CH7LPpy+fT4tPiy+On4Vvny+bX6lvuN/JH9l/6W/4YAYQEgAr8COgOPA78DygOzA34DMAPNAl0C5QFqAfQAhgAmANf/mv9x/13/Xf9u/43/uP/p/xsATAB2AJQApACiAIwAYgAjANP/cf8D/4v+Ef6Z/Sr9yfx9/Er8NvxE/Hf8z/xN/e79sP6N/38AfwGFAogDfQRdBR0GtQYdB1AHSQcEB4EGwgXJBJwDQwLIADX/lv35+2r6+fix96D20PVK9Rb1OfWz9YX2q/ce+dX6xfze/hEBTwOEBZ4HjAk8C58MqA1LDoEORQ6WDXUM6gr+CL0GOASBAa7+0/sG+WD29vPd8Sfw5e4j7urtP+4i74/wf/Lj9Kz3xvoa/o0BBgVpCJsLgg4EEQ0TiRRrFagVOxUlFGwSGhA+De0JPwZQAj7+KPou9nDyDe8h7MXpDugM58vmTueV6JnqTu2f8Hf0t/hB/fEBpAY0C30PXROyFmIZVBt3HL4cJRyuGmAYSxWFESgNVggzA+b9l/hx853uQuqC5n/jUeEN4L/fbOAT4qnkHehX7DfxmfZV/D4CJwjiDUATGBhBHJgfAiJpI74j/SIpIUseehrOFWwQewooBKX9IvfT8OvqmOUG4Vrds9oq2czYn9mh28Pe8eIN6PDtbvRX+3MCjglwEOEWrxyrIasljig7KqIqvSmRJyokoR8XGrUTrAwvBXv9yfVV7lznE+Gv21vXO9Rp0vjR7dJE1e3Yz93G46XqOPJH+pEC2QrdEl4aICHsJpUr8i7oMGQxYDDgLfYpvSRcHgEX5g5HBmj9jPT56/LjuNyD1ofR7M3Ry0rLXMwDzy3Tu9iF31nn+u8n+ZkCBwwoFbMdZiUCLFExKjVqN/433zYSNKovyCmXIkwaJxFuB2z9bfPA6bHgiNiG0ePLzcdnxcXE8cXiyIbNutNQ2xDktu3694oCGA1PF98gfinmMNw2Lzu8PWs+NT0gOkI1vy7GJpMdbROiCIX9a/Ks55vdiNS7zHPG4sEvv3K+sb/owv7H0M4p18zgbuu/9mYCCg5QGeAjZS2WNTA8/kDXQ6VEXEMGQLg6mzPjKtMgthXjCbT9iPG+5bHautAnyDzBMbwwuVO4o7kYvZvCAcoV05HdJul59SwC3g4rG7ImGTEOOklBkUa5SaZKUEm9RQhAWjjtLggk/xctC/j9w/D34/bXIc3Mw0G8vrZus3CyzLN6t2C9VMUYz2Pa3uYq9N8BlA/eHFUplzRLPiRG40taT2pQCk9CSyxF9jzdMi8nRBqADE/+HPBX4mzVv8muv4e3jbHvrcysL64RslS4y8A1y0TXm+TT8n4BLBBpHscr3DdJQrxK8lC3VO1Vh1SOUB9KakGxNkQqhBzaDbn+k+/h4BPTmMbQuxGzoqy1qG2n1KjirHqza7xxxzjUX+J38QwBphDLHwYu5joGRg9PuFXLWShbwFmeVd5OtEVkOkUtvB45DzT/KO+T3+7QrMM1uOOuAqjHo1aivaPzp9iuObjQw0PRLOAX8IgAAxEFIREwsz1/SRhTMlqTXhhgs15sWmNTzUnzPS4w6SCaEL//2u5u3v3O/cDftACrr6Mnn46d8J5Ho3GqObRVwGfOBd617vb/QhEUIugxQkCyTNVWXF4KY7hkWWP1XqtXtE1aQfwyCSP8EVgAqO5z3UDNjr7QsWqnrp/bmhaZcZrjnkmmbrADvajL7dtU7Vb/ZhH7IoozkUKcT0NaM2IsZwVpsGczY7FbYlGVRKs1GCVcE/8Aku6h3LrLX7wLrySkAZzklvSURJbKmmai3azfuQrJ59n166n+bxG4I/U0n0Q8UmBdtWX2avxss2skZ3Ff1VShRzk4FSe4FLIBl+7422nKcrqQrDChrJhGkyuRbZICl8qeiKnsto7G9deb6vH9XRFNJCs2bEaQVCpg3mhmbpdwXm/DauhiClh6SqI6+ygPFm8Cte5420/Jx7hiqpGesJUFkL6N7o6Nk3mbdaYttDjEGtZJ6S/9MxG5JCo39UeXVp9irGt5cdVzr3INbhJm/FoeTeM8yipdFzQD7O4g22vIX7eCqEecD5Mija+Ky4tvkHaYpaOmsQzCWdT/52f88BD+JPM3O0lRWL1kHm4rdLR2o3X/cO1oqF2IT/o+fiyiGAAEOu/u2r3HO7bwplWazJCgigKICImqjcWVHaFZrwvAs9LB5pj7lxAcJYY4Pkq7WYNmMnB8di95NniWc3RrDGC3UeRAFC7ZGdAEnu/k2kXHWbWtpbuY6I6BiLmFpYZBi2mT3p5IrTm+LdGQ5cb6KRAUJeQ4/krWWvBn5nFpeEZ7Z3rQdaVtJWKoU55Ciy8CG6QFFvD+2gHHu7S6pHqXZI3GhtSDp4Q3iWOR7Jx4q5i8x89w5PL5pw/oJA05e0uiWwRpOXPxefd8M3yqd39v8GNXVSVE3zAaHHgGoPA82/LGX7QWpJOWQYxxhVeCDYOOh7aPSJvqqSq7hM5h4x75FA+YJAM5tksfXL9pLHQTe0B+mX0ief5wa2XEVnhFDzIfHUsHPPGd2xXHRrTAowWWgIuChEOB24FHhmWO9pmgqPO5Z81m4kz4cA4mJMY4r0tNXCBqvHTPeyB/l343eiFylGbqV5RGGTMQHhsI5/Ef3GvHbbS5o9GVIIv6g5eAEYFkhXCN9pidp/O4ccyB4X73vg2VI1g4Z0stXChq63QjfJd/LX/neudyamfKWHhH+jPpHucIoPLA3PHH1bQApPWVIYvZg1WAr4DnhNqMS5jipiy4pcu04Lb2/wzkIro34ErAW9hpuXQRfKV/Wn8ye05z6mdgWSFIsTSpH6wJZfN/3abIe7WTpHGWhIsfhHyAt4DPhKOM9pdwpqG3BMsB4PX1NQwXIu82G0oHWzBpJ3SYe0h/HX8Xe1VzFGitWY1IPDVPIGgKM/Ra3ojJXrZxpUWXRozLhA2BKYEdhcuM95dKplO3kMpp3z71YwsvIfc1GkkEWjFoNXO5eoN+d36Vevxy52etWb1ImTXYIBoLCfVP35XKfLeZpm6YaI3dhQeCBILShVSNUJhvpkO3Ssrv3pL0igouINU030e4WN9m5HF1eVV9aH2teUNyY2diWa1IxzVCIb8L5fVc4MzL1LgIqOqZ545Th2mDR4Pthj6OAZnhpnK3NMqU3vPzrAkWH4oza0YmVzllOHDNd7978XtgeClxhmbJWF5IxDWOIVYMxfZ+4SnNY7q9qbmbwZAriTKF8oRtiIiPCZqgp+K3T8pZ3mTzygjpHRoywURPVUJjMG7EdcR5EnqtdrBvUWXjV85HkDW3Id4Mp/e14qzOJ7y2q9ed9ZJli1+HA4dSijGRaputqJK4nMpA3uXy6AepHIYw5EI2U/1g0Gtbc2V3z3eXdNdtxWOwVv5GKjW/IVQNifj941HQHb7vrUKggJX8jfCJeYmZjDmTIp0HqoK5HMtK3njyBwdZG9Au1UDdUG1eGmmVcKN0J3UecqBr4mEwVe1FkTSjIbcNaflV5RbSQ8BmsPeiYJjwkOGMUYxDj56VMJ+tq7W6z8t53h/yKAb7GfwsmD5JTpNbEmZ0bYJxHnJFbw1pqV9iU5pEwzNiIQYORvq55vnTlsIYs/SlkZs9lDGQio9Lkl+Yk6GhrSi8t8zM3tvxTgWQGAsrMDx6S3NYuWL8aQVut24NbB9mG11JUQZDwjL8ID8OHfsp6PfVFMUCtjWpEZ/hl9yTIJOxlXqbS6Tfr9y90s1F367xewQcFwEpnzl1SBFVE18vZi1q82p6aNhiOlrlTjJBjTFwIGAO7Pug6QzYuMchubes26LWm9+XEZdymeyeVadostC/Ic/l35jxrwOhFeEm6DY9RXBRJVsRYgBm1maNZDpfCFc4TB8/JDC9H2oOs/wf6zjagMpxvHew7aYboDacWZuKnbSir6o6tQPCpNCr4Jvx7gIhFKwkEDTWQZRN8VamXYBhY2JLYElbh1NCScw8hy7jHloObv2h7HXcac3vv2+0QaurpN6g9Z/2oc6mV65TuHTEW9KZ4bjxOQKdEmYiGDFCPoBJfFLyWLFcn122WwdXuU8GRjw6tyziHTAOHf4l7sPeb9CXw5241a+CqdOl4aSzpjirSrKxuyPHRNSu4u/xkAEZEREgBC6HOjlFyk35U5hXjFjRVndSoUuGQm83tCq5HOsNv/6p7x7hj9Nlx/y8pLScrg+rGaq9q+2vhrZTvw3KYNbq40Ly9gCWD7Ed2CqnNsNA4EjATjlSMFOjUZ1NQkfFPmk0gChpG4sNUf8q8YPjxtZWy4nBqbnzs5CwmK8Qseq0B7s0wzDNrNhN5bDybAAXDkgblyemMiI8wUNMSZhMkE0tTH1IoELEOikxHCbzGQ4N0/+m8u/lEdplzz7G4L6DuU+2WbWntiy6yr9Tx4vQKNvX5jvz9P+eDNgYRCSJLlo3cz6gQ7tGr0d1RhtDvT2HNrMtiCNWGHUMQQAc9GHoa92P0xfLRMRIv0i8Wbt+vK2/y8StyxvU092H6OPzjv8sC2YW4yBUKnAy+zjEPadAkkGAQHs9njgSMgoqxyCTFr8LngCJ9dTq0eDP1xDQ0Mk8xXbCkcGQwmvFBso+0N7XquBc6qf0O//ECfMTeB0KJmktXTO6N2E6QDtSOqI3RzNmLS4m2h2sFOwK5wDs9kbtQeQh3CTVfs9Zy9PI/MfZyF/LeM8D1dHbrONV7Ij1/P5nCIIRBRqwIUkony2KMe4zvDTxM5QxvC2JKCUixBqhEv0JHAFD+LXvtueC4E7aS9Wb0VrPls5Sz4XRHNX42fHf1uZx7oX20v4XBxUPjhZKHRUjxSc4K1QtDi5hLVcrASh9I+8dhhd0EPIIOwGM+R/yLevs5IvfMNv81wXWWNX21djX7doZ3zvkKOqv8J73vv7VBbAMFxPcGNId1iHJJJkmOiepJu8kGyJGHpEZIhQlDssHRAHF+n/0o+5d6dTkKeF33s/cPdzA3FPe5+Bj5Kzone0O89P4wP6kBFQKow9qFIUY1RtFHsIfRiDOH2IeDxzqGA4VnBC3C4gGNwHu+9b2FfLP7SXqMOcF5bLjPuOr4/HkBOfR6UDtM/GL9SP62f6EAwQINQz4DzETyRWvF9YYOBnWGLUX4RVsE2oQ9gwsCSsFEwEF/R75fvVA8nnvP+2h66fqV+qw6qzrQO1f7/Px6PQl+I77CP93AsMF0QiKC9wNtw8OEdkRFhLGEe4Qlw/QDagLMgmEBrQD2AAI/lj73fiq9s30U/NF8qnxgPHJ8X7ylvMH9cP2ufjZ+hH9Tv9+AZEDeAUlB4sIpAlnCtMK5wqlChIKNwkcCMwGVQXDAyQChgD3/oH9L/wK+xr6Zfns+LL4tPjw+GH5AfrG+qr7o/yn/az+q/+ZAHIBLwLLAkIDlAPBA8kDrwN4AygDxAJTAtoBYAHqAH4AHgDR/5b/b/9d/17/cP+R/7z/7f8fAFAAeQCWAKQAoQCJAF0AHQDL/2j/+f6B/gf+kP0h/cL8d/xH/Db8R/x9/Nj8Wf39/cL+of+UAJUBmwKdA5EEbgUrBr8GJAdSB0UH+wZzBq8FsQSBAyUCpwAT/3P91/tK+tz4mPeM9sL1Q/UW9UD1wvWb9sf3QPn9+vD8DP9BAX4DsgXJB7IJXAu5DLkNVA6ADjsOgg1YDMUK0QiKBgAERgFx/pb7zPgq9sbztPEI8NDuGe7s7UzuO++08K3yG/Xs9wv7Y/7XAU8FsAjdC7wONREyE6IUdhWlFSoVBxRAEuIP+wyiCe0F+gHn/dL52/Uk8sru6eua6fLnAOfO5mLnuejN6o/t7fDO9Bb5pP1VAgcHkwvUD6kT8haTGXQbhRy6HA4chBolGAEVLRHFDOsHwgJ0/Sf4B/M77uvpO+ZI4y3h/d/D34bgQeLr5HDoueyl8RH30vy8AqMIWA6tE3gYkBzVHyoieiO5I+Ei9SADHh4aYhXyD/cJngMZ/Zn2UfBz6i7lruAX3YfaFtnS2L/Z2dsT31bjg+h17v707fsLAyQK/hBkFyIdCiL0Jb4oUCqcKpspVCfUIzQflxklEw8MjATW/Cb1u+3O5pfgSNsM1wfUUtL/0RLThtVK2UTeUORA6+Dy9vpDA4gLgxP2GqYhXCfqKyovATFdMTkwmi2TKUAkxx1bFjIOiwWq/NHzR+tP4yncDNYs0bDNtstRy4XMTc+W00DZI+AK6Lrw7/ljA84M5RVhHv4lgCyyMWo1hzf3N7M2wzM7Lzsp8CGRGVwQmgaV/Jry+Oj53+fX/9B8y4nHSMXNxB7GNcn7zU/UANzW5Izu2fhtA/YNIhiiISkqdDFJN3c73T1kPgU9yTnHNCIuDCbDHIwStweX/ILxzebP3NTTJcwAxpbBDL95vuO/QsN/yHPP69em4VrstvdfA/8OORq2JCIuMzapPE5B/UOeRClDpz8yOvAyGSrvH8AU4Qiv/IjwyuTR2fTPgse9wN27CblauNi5er0nw7PK6NN/3ibqhvY9A+oPKRycJ+gxujrOQelG4kmgShlJWEV3P6E3ES4RI/MWFgrd/K3v7eID10rMGMO3u2G2QrN2sgS04rf3vRPG+89j2/PnTPUFA7UQ8R1SKnY1Bj+0RkRMiE9lUNFO1kqRRDA88jEmJiUZVAsf/fHuOuFl1NjI7L7ytiixvq3RrGqugLL0uJfBKMxW2MPlCfS5AmERkB/WLMw4EkNYS1tR6lToVUtUHFB7SZhAtzUrKVMbmgx0/VTusN/70aDFALtxsjWsgKhwpxGpVq0jtEO9csha1ZnjwPJaAu8RBSEnL+Y73Ua1TylWA1olW4NZJ1UxTtZEXDkcLHkd5g3c/dXtUN7Ez6TCWLc4ro2njaNZovyjbKiIrxy53sR00nfhcvHpAV4SUSJEMcI+Y0rJU6pa0F4XYHNe8FmvUuZI3jz2LpYfNg9V/nXtGt3Czee/9bNKqjOj6J6OnTCfxKMpqya1b8Gnz2DfIfBoAbASciMqM2BBok2QV9xeS2O5ZBljdV7wVsJMOUC2MaYhhxDe/jLtDtz2y2q92rCqpiqfl5oVmbKaZJ8Ip2SxKb71zFfd0O7YAOQSaCTbNL1DmFAIW7ticmcIaW9nsGLwWmhQakNYNKcj2BF2/w3tLdthyi67Ca5ao3abm5bxlIaWT5sqo9utD7tiyl7bgO05APwSNCVVNtdFQ1MvXkRmQmsAbXFrnmarXtRTbEbaNpclJxMZAAPtddoDyTS5hKtdoBmY+ZIlka6SiZeTn46qJbjyx3nZM+yQ//gS1iWXN7BHolUBYXRptm6fcB1vO2odYgFXPUk5OXIncRTJABTt6Nndx363TKm2nRaVs4+1jS+PFpRGnICnbrWmxanX7Orb/toSTyaiOERJs1d+Y0lszXHfc25yg21DZe5Z2UtyOzYptBWCAT7thNntxgu2Yqdkm3CSy4ykigyM+ZBHmbak7rKBw/HVreke/qMSnyZ2OZRKdVmkZcFuhHTAdmJ1dHAaaJVcPU6BPeEq7xZEAoLtSNk1xt20yKVrmSeQRYr0h0eJNY6ZljGiprCIwVTUeOhZ/VQSxyYSOqBL6FpxZ9pw2XY+efd3CnOfavZeZ1BkP3AsHhgLA9ztNNm0xfOzfaTKlz2OIoioheSGzYs+lPafm668v9TST+eP/O4RyCZ5OmhMClzlaJNyynhYeyl6RHXPbAxhVFIZQeEtQBnXA03uRtloxU6zg6ODlrSMY4bBg+SEw4k5kgaezqwfvnPRNObC+3MRoiapOuxM3Fz+aexzVnoMffd7HneobtViAFSdQjEvUxqlBNHuftlTxeyy2aKWlY2LCoVBgkmDGYiNkGScQqu1vDTQKuXz+uUQWCalOixNXl2+auJ0fHtYfl99mHgncE9ka1XtQ14wVBt0BWjv2tlxxc2yfqIElceKGIQqgRSC0YY7jxKb+ql/uxrPMuQl+kYQ6yVsOilNkV0ja3d1O3w7f19+rnlLcXllkVYIRWUxQhxCBhDwWNrDxfGydKLMlGSKjIN7gEiB7IVFjhKa9qh/uiXOT+NZ+ZYPXCUBOuVMdF0va6l1kny1f/d+YHoTck9mcVfrRUYyGh0MB8fw99pGxlWzt6LtlGKKaYM2gOSAbYWtjWWZOqi4uVnNguKR+NgOrSRmOWBMCl3hanp1gnzFfyd/rXp8ctJmCViVRv4y2x3RB4vxttv6xvqzSaNolcOKrINbgOmAUoVzjQ2ZxqcrubbMzuHP9w4O4COaOJxLUlw6aul0DHxrf+1+lXqGcv9mWFgFR4szgx6PCFvykdzdx920JqQ6loOLVoTqgFiBnYWZjQuZnKfauD/MNOEW9zoN9iKhN5tKT1s9afhzLnuofkl+F3oxctVmXVg4R+wzDx9ECTTzid3syP21TqVil6SMZoXhgTCCT4YejmCZvafGuPXLteBm9l0M8iF9Nl5JAlrqZ6ly7Hl8fT19Mnl8cVVmFlgtRx80fx/uCRT0md4lyle3v6bfmCKO24ZBg3CDZocDjwyaKqjvuNnLVODC9XoL1iAuNedHblhDZvxwRnjoe8l76XdncH5lg1flRiM00B+LCvr0wd+Iy+m4d6ivmv2Ps4gIhRiF4ohHkA6b4qhXue3LE+Ar9ZIKox+5MzlGk1ZKZPNuPXbvee55O3bzbk9kpFZdRvczAiAbC+P1/+AQzbK6c6rQnDKS7IozhyaHworrkWic6Kn/uTLM8d+k9KgJXB4eMlZEdlQCYpJs1HORd613KXQgbcpieVWVRZkzEyCaC872T+K8zq+8saw+n7+UhI3DiZiJBY3tkxmeOavnuqjM8d8t9L0IAx1hMEFCGFJuX9ppDnHRdAl1tXHvau9gAlSNRAozAiAIDLj3sOOK0Ny+Lq/4oaGXeJCzjG6MqY9Llh+g16wPvFDNFODJ89MHmhuDLvw/fU+PXM5m7G2xcQNy4W5jaL5ePlJFQ0kyzR9iDKD4H+V30jjB57H7pNaaxpMCkKOPrZIFmXqiwK53vSvOW+B48+0GJBqILIo9p0xqWXJjcmo0bp5urmt8ZTlcL1C9QVQxdB+oDIT5m+aA1L/D2bRCqFmea5eskzeTDpYZnCil9LAevznPxuA98wwGoxhyKu86mUkCVshfo2Zeat1qIGg8YmJZ1032Py0w9h7ZDGL6Ieii1m7GAbjLqymiY5uulyWXyZmEnyiocbMFwXrQV+EY8zIFGhdEKCw4WEZZUtVbgmIwZsNmOWSnXjpWNUvwPdIuUx7yDDj7runb2ELJXLuSr0Cmq58GnGqb251Eo3irNrYqw+7RDeIK82AEihUBJkc15UJ0TptXFF6wYVNi/F++WsNSTEisO0UtiR3zDAX8QOso2zjM5b6Ts5uqPqSuoASgQqJVpxWvQrmNxZTT6uIW85kD9hOrI0EyRj9XSiBTXVnhXJFdbFuEVgBPHkUrOYYrmhzbDMb81eyG3U3PmcLLtzavGamjpe2k+aa2q/2yk7wsyGzV7eM6894CYBJGIR4vfjsGRmZOYFTGV4JYjlb9UfRKrEFvNpUphBupDHv9a+7y333SdcY1vAy0N67hqiKq/qtjsC23JsAFy3bXFuV58zACyhDUHuIrkDeEQXRJIk9mUihTZVEsTaFG+T15M3MnSBpdDCH+APBp4sTVdMrNwBq5k7NjsJ+vS7FXtaK7+MMYzrDZZebT85IBNw9YHJAogTPXPExEqEnETIlN9EsVSAtCBzpLMCIl5hj1C7j+kfHp5CDZks6OxVq+Krkktl+13baQulnACMhh0Rjc2udJ9AMBqA3VGSslVS8DOPU+90PlRqpHQka8QjU92jXnLKIiXhdyCz3/HPNu543cy9J1ysfD9L4gvF27rrwIwE3FUszf1K/edOna9IYAIQxOF7ghDysMM3M5FD7OQI9BUkAlPSI4dDFPKfYfsRXTCrH/oPT26QbgHNd7z13J78RQwpTBu8K8xXzK09CP2HHhMuuH9RwAogrFFDketCb3LcozBDiFOj07KjpVN9gy2CyHJR4d4RMYChEAGvZ/7IrjgNue1BfPE8uxyP7H/siny+HPiNVv3F7kFe1Q9sb/LQk+ErIaSCLIKAEuzDEPNLs0zTNQMVotCyiQIR0a7RFBCV4AifcF7xTn89/X2e/UXdE7z5fOcs/E0XjVbdp84HPnGu8194T/xQe6DyYX0B2FIxsocitxLQ0uQy0cK6wnECNuHfUW1w9OCJYA6viF8aDqcOQj3+Daxtfq1VjVEtYP2Dzbft+y5K7qQPE1+Fb/awY9DZkTThkyHh8i+ySyJjknjya9JNMh6h0kGacToQ1AB7gAPfr+8yzu9Oh85OXgSd643D3c2NyB3ijht+QP6QzuhvNR+T//IAXKCg8QyRTTGBIcbh7XH0UguR85HtMbnhi1FDgQSwsXBsUAf/ts9rTxe+3e6fnm4OSf4z/jvuMW5TnnFeqP7Yzx6/WH+j3/5gNhCIoMQxBvE/kVzxflGDcZxRiVF7MVMRMkEKgM2AjUBLsAsPzO+DX1//FE7xftheua6ljqvurI62ntku8v8iv1bPjX+1L/vwIGBg4JwAsJDtkPJBHkERUSuRHWEHYPpQ12C/sISQZ3A5sAzf0h+6v4f/ap9DjzNPKh8YLx1PGR8rLzKvXr9uX4CPtB/X3/qwG8A54FRQemCLcJdArYCuQKnAoDCiEJAQiuBjQFoQMCAmQA1/5j/RT89PoJ+lj55fiw+Lf4+Pht+RD62Pq++7j8vP3C/r//rACDAT0C1gJLA5oDwwPIA6wDcgMgA7sCSQLQAVYB4QB1ABcAy/+S/23/XP9f/3L/lP/A//L/JABUAHwAmAClAJ8AhgBZABcAxP9g/+/+d/79/Yb9Gf27/HL8Rfw2/Er8g/zh/GX9Df7T/rT/qQCrAbECsgOkBH8FOQbKBioHUwdBB/IGZQacBZoEZQMGAoYA8P5R/bX7Kvq/+ID3efa09Tz1FvVH9dD1sfbk92P5JPsc/Tv/cQGuA+AF9AfYCX0L0gzKDVwOfw4wDm0NOwyfCqMIVgbHAwoBNP5a+5L49PWW843x6e+87hDu7u1b7lXv2fDd8lT1LPhR+6z+IQKZBfYIHQz1DmQRVxO6FIEVoRUZFecTExKpD7gMVgmbBaQBj/17+Yn12PGH7rLrcOnW5/Tm0+Z3597oAevR7TvxJvV1+Qf+ugJqB/ELKxD1EzEXwxmTG5IctBz2G1oa6he1FNQQYgx/B1ICAv24953y2u2W6fTlEuMK4e7fyt+h4HHiLuXE6BztFPKJ90/9OwMgCc4OGRTWGN4cECBQIoojsiPCIsAguR3BGfQUdw9zCRQDjvwQ9s/v/OnG5Fjg1txe2gXZ2tjg2RPcZN+84/vo++6P9YT8pAO5CowR5heUHWgiOybsKGMqkyp3KRUnfCPGHhUZkxJzC+kDMfyF9CLtQuYc4OLav9bV0z7SCNI508nVqdm73tzk3euJ86b79QM2DCgUjRsqIsknPCxgLxcxUzEPMFItLSnAIzIdsxV9Dc8E7PsX85fqruKb25jV1NB3zZ7LW8uxzJrPAtTI2cLgveh68bj6LgSUDaEWDR+VJv0sETKnNaE37TeFNnIzyS6rKEch0xiRD8YFv/vI8THoQ99H13zQGMtIxyzF18RPxovJdM7m1LLcneVj77n5TwTUDvUYYiLRKgAysze8O/o9WT7SPG85STSDLVEl8RuqEcsGqfuY8PDlBNwj05PLkMVNwe2+g74YwKDDA8ka0K/YguJH7a34WQT0DyIbiiXdLs42Hj2bQR9Ek0TyQkY/qDlCMkwpCR/IE98HqvuI79fj89gxz+DGQsCMu+W4ZbgRuuC9tsNpy73Ubt8p65P3TQT1ECcdhCizMmM7T0I+RwhKlUrfSO9E4j7lNjQtGCLnFf4IwvuX7ubhEdZ2y2jCMLsIthqzgLJAtE+4kb7WxuHQZdwK6W/2KwTVEQMfTStTNr0/QEehTLNPW1CTTmZK8kNmOwUxGyUFGCgK7vvG7R7gYdPzxy6+YLbHsJKt2qyprvOymLlnwh3Nadnt5kD18wOWErYg5C25OddD70u/URlV31ULVKZP00jDP7o0DiggGloLMPwV7YHe5NCrxDW61LHNq0+oeadSqc+t0LQfvnbJf9bV5Ar0qAM3Ez4iRjDiPK9HV1CVVjZaHVtAWatUgE31Q1I47yo1HJMMhPyE7A7dnc6gwX+2ka0dp1ejYKI/pOqoPrADuu/FqNPE4s/ySgO5E5sjczLOP0JLdVQeWwdfEGAvXnBZ9lH6R8c7ui1BHtEN7PwR7Mfbi8zUvg+zmKm7oq6elJ12n0ek5asWto3C6dC94I/x2gIcFM0kajR6Qo5OR1hXX4djtGTTYvBdMFbNSxY/bDBCIBIPZP2+66var8pJvOiv7qWrnliaGZn5muufy6deslK/Rc7D3k3wWgJhFNMlKTbkRJBRyFs9Y7NnBWkoZydiKVpqTztCAjM1IlQQ6/2I67rZDMkAugytlqLwmliW85TNltmb86PdrkO8vsvY3AzvywGIFK4msTcMR0ZU+F7NZodrAG0qaxJm313NUjNFeTUXJJURgf5w6/XYoMf6t3yqkJ+Ml7GSJZH2kheYYaCXq2K5WMn+2sztLwGSFF4nADnwSK9W02EEagBvoHDVbqxpTGH0VftHzTfnJdISJP9z61rYbcY4tjqo35yDlGaPs413j6aUGZ2QqLS2Fsc52ZHshwCBFOMnFzqPSspYWGTfbBty43MncvNsb2TbWJBK/TmhJwoU0v+S6+rXcsW7tEemhprWkXuMn4pTjIqRHZrLpTq0+sSL113r1f9VFD4o9jrpS5VahWZdb9d0xnYcdeNvQ2d+W+5MBDxDKTsViADL66TXsMSDs6SkhZiHj/CJ7YeOiceOcpdLo/ixCMP21TDqGv8PFHAonDv+TA9cWWh8cTB3R3mxd3hyxWnaXRJP4T3KKmIWRgEc7IfXJsSRslKj3paYjcmHnoUph1+MGZUTofKvQsF91A/pWP6yE3koCjzOTTld02k7cyV5ZHvkebJ09GvtX/tQkD80LH0XCwKF7JHX08PksVGikZUKjAaGtIMnhVWKFZMmnyiuqr8i0/vnkv0/E1soQjxYThJe82qYdLV6Gn20e412zG21YaVSEEF/LYoY0wID7cLXt8N8saGhoJTeiqqEMoKLg6qIaZGFnZ+sQ77n0fXmyPy2EhcoQzyeTplet2uTdd57aX4dfQd4S28uYw1UXkKpLocZnQOV7RnY0MNYsUKhCZQVirSDF4FUgmGHF5AznFirD73P0AHm/fsbEq4nDzygTtBeIWwrdqB8Tn8gfh55cHBXZDNVd0OvL3MaaAQ67pTYHsR4sTOhzZOuiSaDZoCFgXuGII8zm1SqELzczx/lNPtuESInqDtfTrZeL2xgdvt8y3+7ftN5OHEvZRNWW0SPMEobMAXv7jHZn8TasXSh65Oqif+CH4AfgfmFho6EmpepSLsPz1LkbPqxEHUmDjvcTU5e5Gszdu183X/tfiJ6pHGzZa1WBkVIMQsc9gWz7+7ZUsV+sgOiZJQIikCDQYAigdyFSo4qmiGpubprzp3jqvnmD6clQzoZTZhdP2uldXl8hn+1fg16sXHjZf9WeEXXMbUctQaE8MvaNMZgs+CiNZXHiuiDzYCOgSSGbI4lmvSoZbrxzQDj7vgQD7wkSTkXTJVcQmq1dJ57xX4VfpJ5X3G+ZQdXr0U8MkUdbQdf8cTbRceBtAmkXZbmi/aEwoFjgtKG7Y51mhCpTLqizX3iOvgwDrUjIjjYSkdb72hnc116nH0MfbF4rnBCZcZWqkV0MrodHAhE8tncgsjdtXul2pdkjWqGIIOgg+WHzo8cm3epcLqBzRfikfdHDZQi0DZfSbFZR2e6cbd4C3ybe2x3nm9wZDlWZ0V/MhIewAgv8wbe6clztzWnrJk/j0CI5IREhV2JDZEZnCqq0bqOzc7h8/ZZDFshVTWtR9NXTWWxb692E3rDecJ1MG5IY2FV50RaMkseVwkg9Erfd8tBuTWpz5t1kXmKDodPhzmLq5JsnSercbvKzaThY/ZnCw0gtDPERbJVAmNObUd0t3eGd7RzY2zKYT5UKEQGMmUe3wkT9aLgKs1Du3erQJ4ElBGNnIm/iXeNp5QVn3CsT7w2zprh4/VyCqse7zGoQ09TamCUaoBx+XTldEVxOWr2X89SKkOBMV8eVwoI9g3iAc94vfqt/qDplgaQi4yRjBaQ/5YToQWubb3UzrLhc/V+CTgdCDBcQa1Qh12GZ11u2nHicXZus2fOXRVR7UHLMDYevgr89ofj99Dcv7qwBqQgmlWT2I/DjxWTspllo+Ovyb6jz+zhFvWLCLcbAi7hPtBNXFomZOJqXm6Abklr02RSWxFPcUDjL+odEQvt9w/lC9NtwrWzU6eonfyWgpNTk3CWvpwKpgyyZcCj0EnizfSdByka4Ss7PLpK7VZ4YBFniGrDasFnnGGFWMRMtj7KLnodUAvZ+KLmOtUnxea246p7ofaahJc+lyWaIaAAqX60PsLW0cvimfS0BpEYpiltOW5HPVN/XO9iW2arZt9jDl5nVS9Kvjx+LecceQu++T7ogNcHyEq6sq6YpUCf25uBmzKe2KNFrDa3VcQ603Hje/TSBfIWVCd7NvFDUE9AWH5e22E+YqhfLVr7UVNHiDoBLC4ciwuc+uDp3NkLy969vLL5qdejg6AXoJOi4afXrzW6qcbQ1DzkdPT5BE0V7yRoM0dAKku+U8NZC11/XR5b/FVETjJEFzhSKlAbhgtv+4frStwuzp/B/baarrWoeaX+pESnOay0s3i9OMmX1i3lh/QsBKUTeSI2MHI8z0b+TsJU8FdyWEZWflFDSs5AazVzKE0aZws2/C/tx95t0YfFcrt4s9etuKoxqkOs3bDYt/zAAcyO2EPmsvRrA/0R9h/qLHY4QkIESoBPj1IbUyJRtkz8RSo9hjJkJiUZLwvx/NfuUeHF1JTJFcCOuDizO7Crr4qxyLVBvMDEAs+12n7n9/S3AlUQZx2HKVk0ij3URAFK60x+TbhLqUdyQUc5aS8mJNcX3Aqd/X3w4+My2MHN4sTWvdS4/rVptRa397rrwMDIOdIK3d7oV/UTArIO0BoRJh0wqTh0P0tEC0ehRwtGWUKpPCo1Fyy6IWUWbwo4/h7yfeax2wvS1clNw6S++7tlu+K8ZsDSxfvMpdWM32Lq0fWAARUNNRiLIscrpTPnOWE+8kCIQSFAzDykN9QwkygjH84U5wnD/rfzGuk932zW6c7tyKXELsKawerCEcb0ymzRQtk64grsZ/b+AH8LlxX4Hlwngi41NEo4pjo4O/45BTdmMkgs3SRgHBQTRAk8/0n1uOvV4uHaGtSyztDKkcgDyCfJ8stM0BDWD90R5dbtGPePAPMJ+RJdG94iRSlgLgwyLTS3NKczCjH1LIwn+iB1GTgRhQih/8/2Ve5z5mbfYtmV1CHRH8+bzpbPBtLW1eTaCOEQ6MPv5fc0AHIIXxC8F1Me8iNvKKorjC0KLiIt3ypUJ6Ei6xxiFjoPqwfy/0n47PAV6vbjvt6S2pLX0dVb1TDWR9iM2+TfK+U169HxzPjv/wAHyg0aFL8Zjx5nIislySY3J3QmiSSJIYwdtRgrExsNtgYtALT5ffO37Y3oJ+Sk4B3eo9w/3PHcsN5s4Q3ldOl97v/zz/m9/5wFPgt6ECYVIRlNHJUe6h9DIKIfDh6XG1EYWhTSD94KpgVTABD7BPZV8SftmenF5r3kj+NB49LjPOVv51nq4O3m8Uv26/qi/0gEvQjeDIwQrBMnFu0X9Bg1GbMYcxeDFfUS3g9ZDIQIfQRkAFv8fvjs9MDxEO/v7Gvrjupa6s/q5euS7cXvbPJu9bT4Ifyc/wcDSgZLCfULNA75DzkR7RETEqsRvRBTD3oNRAvDCA4GOgNeAJP96vp6+FT2h/Qe8yPymvGE8eDxpvLO8031E/cR+Tf7cP2t/9kB5gPEBWUHwAjKCX8K3AriCpIK8wkMCecHkAYTBX8D3wFCALf+Rv36+976+PlM+d74rvi6+AD5efkf+uv60vvO/NL91/7U/78AlAFLAuECUwOeA8UDxwOoA2wDGQOyAj8CxgFMAdcAbQAQAMb/jv9r/1z/YP91/5f/xP/2/ygAVwB/AJoApQCeAIMAVAARALz/V//l/m3+8/18/RD9tPxt/EL8NvxN/In86/xy/Rz+5f7I/74AwQHGAscDuASQBUcG1AYvB1QHPQfpBlcGiAWCBEoD5wFkAM7+Lv2T+wv6ovhn92X2p/U29Rf1T/Xg9cf2AfiG+Uz7SP1p/6AB3QMNBh4I/gmcC+oM2g1jDn0OJA5YDRwMeAp1CCIGjgPOAPf9HftY+L/1Z/Nl8cvvqO4I7vLtau5x7//wDfON9Wz4l/v1/msC4gU8CV0MLQ+TEXoT0RSKFZ0VBRXGE+URbw90DAkJSAVOATj9Jfk49Y7xRu5860fpvOfq5tnmjucF6TfrFO6K8X711Plr/h8DzAdODIAQQBRvF/EZsRudHK0c3BsuGqwXaRR6EP0LEwfiAZH8SPcz8nrtQumv5d/i6eDi39Lfv+Cj4nLlGumA7YXyAfjN/boDnAlED4QUNBkrHUogdSKYI6gjoiKJIG0dYhmGFPwO7giKAgL8h/VO74bpYOQE4JfcNtr22OTYBNpP3LffI+R06YPvIPYb/TwETgsZEmYYBB7EIn8mFyl0KogqUSnUJiIjVR6RGAES1QpFA4z74/OJ7Lflo99/2nXWptMs0hTSYtMQ1graNN9q5XvsM/RX/KYE4wzMFCMcrCI0KI0ski8rMUcx4y8HLcYoPyOaHAoVyAwSBC77XvLn6Q7iENsl1X7QQM2Jy2jL4Mzqz3DUUtpk4XDpO/KA+/gEWg5cF7cfKSd3LWwy4TW4N983UzYdM1QuGSicIBUYxA7xBOn69/Br54/eqtb6z7fKCscTxeXEg8bjye/OgNVm3WbmO/Ca+jEFsQ/GGSEjeCuIMho4/jsVPks+nDwSOccz4SyUJB4bxxDfBbv6sO8U5TvbdNICyyTFCMHQvpK+UMABxIvJw9B22WDjNu6k+VMF6BAIHF0mlC9lN5A95EE9RIVEt0LgPhs5kjF9KCIezxLcBqX6ie7l4hbYcc5Cxsq/P7vFuHO4TrpJvknEIcyV1V/gLOyh+F0F/xEjHmopfDMJPMxCj0cqSodKoEiCREo+JjZULB0h2RTlB6f6gu3g4CLVpcq7wa66tLX3so6ygLTAuC6/nMfJ0WndIuqS91AF9RITIEYsLDdxQMlH+UzYT01QUU7ySU9DmjoUMA4k4xb6CL76newE31/SEcdzvdK1a7Bqreis7a5qsz+6OcMVzn/aGOh49i4FyhPaIe8uojqYRIJMH1JDVdJVxlMsTyZI6T67M/Am6xgYCuv61+tT3dHPucNsuTyxaasjqIanmKlNroG1/r59yqXXEuZV9fYEfxR1I2Mx3D1+SPRQ/FZlWhBb+VgrVMtMEENEN8Ep7ho/Cy37M+vO23jNn8Cqte6ssqYno2yiiKRtqfew7boEx9/UE+Qs9KsEExXjJKAz1kAdTB1VjVs6XwVg5V3qWDlRCkesOn0s6hxrDIL7r+p22lbLxb0tsuyoSaJ6np+dwJ/PpKesC7euwy7SHOL98k0EiBUmJqc1kEN1T/hYzV++Y6pkiGJmXWtV00ruPSEv2x6cDen7SupJ2WvJLLv7rjilMZ4fmiKZRJt3oJOoXLN/wJfPMeDL8d0D3RU8J3U3CEaDUoNcumPuZ/1o22aZYV5ZZ04JQaoxwCDODmH8BepJ2LnH1bgTrNahb5oalvqUGpdpnMKk5K96vR3NU96Y8F0DExYmKAs5PEhEVbxfUWfGa/ls3WqBZQ1dw1H3QxU0lSIBEOj83ul210DGw7Z4qceeBZdvkiuRQ5OpmDWhpqyjusLKhtxm788CKxbkKGc6LEq4V6BijmpEb5twiG4YaXZg41S2Rl82WSQyEX791OnO1gHF9rQspw+c9ZMgj7eNxI87lfGdpan9t4rIzNo37jMCJhZ1KYk71kvcWS1lcG1kcuBz2XFdbJRjw1dDSYU4CSZfEiD+5+lS1vvDb7Mwpa6ZQpExjKGKoIwhkvma5qaKtXfGKNkN7YsBBRbbKXM8Ok2wW2Fn9G8jdcZ2z3RLb2VmYVqaS4Q6oieFE8z+FeoC1i7DLrKFo6aX7o6iieyH2olfj1GYaqRPs4zEm9fq69oAyhUXKiI9WE4yXTxpGHKAd0l5ZXfgceVouVy6TVo8ISmkFIL/Xerb1ZvCM7EroviV+ox3h5qFdYf4jPqVNqJNscvCKdbR6iAAdRUpKpk9ME9jXr1q3HN5eWh7mXkZdBJryV6eTwQ+hSq4FT4Avure1UHCf7AjoaaUZ4uwha6DcoXtiveTSqCHrzjB1NTC6WL/CRUSKtg9wU9CX+FrPnUNeyF9anv0delsj2BEUYA/zCvAFgABNusJ1h7CEbBuoK6TN4pQhCmC04NCiUySq54ArtS/ndPB6J3+hhTTKd89DFDOX6tsPXY6fHJ+1nxvd2huB2KrUstA8iy5F8YBw+ta1jLC6K8KoBOTaYlXgwyBm4L4h/mQWp26rKK+iNLQ59b97xNvKa89ElAJYBht2Hb/fFt/2n2IeI5vMWPQU+NB9i2iGI0CZOzR1nzCBLD3n9SS/4jFgliAyoEQhwGQWZy3q6S9ltHw5g/9RBPmKEs91U/0XyptEXdcfdp/d34/eVhwCWSxVMdC1i54GVUDGO1s1/vCY7A2oO+S+Iicgg6AYYGMhmWPqZv4qty8ydAk5kj8iBI6KLI8VE+NX+Fs53ZSfe9/rH6RecZwj2RMVXRDjy86GhoE2+0p2K3DBbHDoGWTU4nbgi6AYYFshiePTZuAqku8I9Bt5YX7vRFsJ+g7kk7YXj5sWnbffJt/d35+edZwwmShVehDITDmGtsEre4G2Y/E6LGfoTWUEYqAg7eAyoGxhkaPRJtQqvO7pc/N5Mb65RCAJu06j03WXUJrbHUGfNx+2n0GeYhwoGStVSNEiTB5G5YFi+8C2qLFCbPIol2VL4uNhKqBnIJch8OPkJtoqta7U89G5A/6ARB2JcQ5T0yHXO9pHnTHerV91HwpeNtvKmRxVSNExzDzG0oGdPAa2+LGaLQ8pNuWrIz/hQWD1oNriJ+QMpzJqvS7K8/a42D5FA9QJG4400rvWkZocnIjeSZ8ZnvodtBuXWPqVOdD2DBRHPQGZvFM3E3IAbb4pa6YiI7Vh8iEeIXeidmRKZ11q068Mc+K47v4Hw4RI+42HEkPWUpmaHAcdzF6kXlCdWdtPGIZVG5DuzCTHJIHXfKX3eHJ1Lf8p9Oav5ANivCGf4e2i3GTdZ5rrOa8Zc9Y4yP4JQ28IUc1L0fpVv1jBG6zdNd3V3c6c6BrxWD+UrdCcDC2HCQIWvP33pvL3LlDqkidT5OljHuJ64nvjWeVF6Csrbu9yM9E45n3JwxRIHozDEWBVGFhSGvscRp1unTQcHxp+V6YUcNB9S+6HKcIWPRr4HrNGLzLrAqgNpaaj2mMuoyJkLiXDaI3r86+WtBQ4x73KAvUHooxuELZUXleN2jJbv1xu3EGbv5m2VzoT5FASy+dHBkJWPXw4XrPhL6SrxajcJnqkrWP6Y+Ck2OaVqQLsR/AHdF+47T2KQpIHXovNED0Tklb1GRNa4JuXG7faiZkZ1rvTSE/cC5eHHoJVfaE45nRH8GUsmmm+5ySll6TdpPYlmid8aYps67BENLO4132LQmtG00thD3WS9RXImF7Z61qompcZ/Zgo1etS3M9ZC39G8cJUPcl5dTT5MPOtQCq06COml+XXZeHmsKg3amOtXrDNNNA5Br2NQgHGgUrqzqBSB1UJV1WY4BmjmaAY3BdkFQkSYk7KCx5GwAKRfjP5ijW0MY8udat9aTanrabnJuOnnGkF606uIPFidTW5Oz1QwdYGKUorDf6RChQ4FjiXgBiJGJPX5hZL1FVRmI5uirRGiMKM/mC6JPY4MncvOmxW6l0o16gMKDponKonrAsu8jHDtaQ5dT1WQajFjEmizREQflLWFQkWjFdaF3LWnBVg01CQwA3HSkFGi8KGPo66hDbEc2owDO2A65WqFSlFKWUp8Gsb7RgvkfKxNdu5tP1eQXpFKsjSzFiPZNHkU8gVRVYXlj5VftQjkntP2Q0TycVGSQK8/r0657dX9CdxLK66LJ8rZOqQ6qNrFuxh7jWwf/Mqdlx5+v1pQQuExUh7y1aOf1CkErZT7NSCVPbUD1MVEVYPJAxUyUAGAAKwfuw7TrgyNO4yGC/Brjhshewu6/OsT2247yKxe7PvduY6Bv23QNzEXQefCouNTk+WEVWSg9Nb013SzlH1kCEOIUuKCPHFsMJgvxp7+DiRtf0zDnEV72BuNu1drVUt2K7gMF7yRTT/t3j6WX2IwO7D8ob9CbjMEw57j+aRCxHlEfRRfNBGjx3NEYr0SBqFWwJNP0g8Y3l1tpN0TnJ18JXvtq7cLsavcjAW8amzW3Wa+BR68r2eQIIDhoZWyN9LDs0WTqrPhJBfUHtP288IjcxMNQnTh7qE/oI1f3Q8j/odt6+1VrOgchexA/Co8Ebw2nGb8sG0vfZBOPj7Ej34AFbDGcWth8BKAovnDSOOMQ6LzvPObI28jG2KzIkoRtHEm8IZf549PPqIeJE2pnTUM6QynXIC8hTyUDMutCa1rHdxeWX7uH3WgG4CrMTBhxyI78pvS5IMkg0sDR+M8EwjiwKJ2IgyxiCEMgH4/4W9qbt1OXb3u/YPtTo0AXPoc68z0rSNtZd25bhruht8JX45gAgCQIRURjVHl0kwSjgK6QtBC7/LJ8q+yYwImcczxWcDgcHTf+o91Xwiul941reRtpg17vVYdVR1oLY39tM4KXlvetk8mT5hgCUB1YOmhQvGuserSJZJd4mMidWJlMkPSEtHUUYrxKWDCsGov8t+f3yQu0n6NPjZODz3ZDcRNwM3eHeseFk5drp7+559E36OwAXBrML4xCCFW0Zhxy7HvsfPyCJH+IdWBsDGP8TbA9xCjUF4/+i+pz19vDV7Fbpkeab5IDjRePo42Plp+ef6jHuQfKs9k/7BQCqBBkJMg3UEOcTVBYLGAEZMhmfGFAXUhW3EpcPCgwvCCYEDQAG/C/4pfSC8d3uyexT64PqXerg6gPsvO3676nysvX8+Gz85v9OA40GiAkpDF8OGRBOEfYRDxKcEaQQMA9ODRELiwjTBf0CIgBY/bT6Sfgq9mX0BfMT8pTxiPHs8bvy6/Nw9Tz3Pvlm+6D93P8GAhAE6QWFB9kI3QmKCuAK3gqHCuIJ9QjMB3IG8gRcA7wBIQCX/ij94fvJ+uf5QfnY+K34vvgI+YX5L/r9+uf74/zo/e3+6P/SAKQBWQLsAloDowPGA8YDpANmAxEDqQI1ArwBQgHOAGQACQDA/4r/af9b/2H/d/+b/8j/+v8sAFsAgQCbAKUAnQCAAE8ACgC0/07/3P5j/un9c/0I/a38afxA/Df8UfyQ/PX8f/0s/vf+3P/TANYB3ALcA8sEoQVUBt0GNQdUBzkH3wZIBnUFagQuA8gBQwCr/gv9cvvr+Yb4UPdT9pv1MPUY9Vj18PXe9h/4qvl1+3T9mP/QAQ0EOwZICCMKuwsCDeoNaQ56DhcOQg39C1AKRgjtBVUDkgC6/eH6H/iK9TnzP/Gu75buAO727Xvuje8n8T/zx/Wt+N37Pv+2AisGgQmdDGQPwBGcE+YUkhWWFfEUpBO2ETQPLwy8CPUE9wDg/ND45vRD8QXuR+sg6aPn4ebg5qXnLelu61nu2vHX9TT6z/6DAy8IqwzVEIoUqxceGs0bpxykHMAbABpuFxsUIBCYC6cGcQEf/Nn2yvEa7e/oa+Ws4srg19/c397g1uK45XHp5u328nv4S/44BBcKuA/uFJAZdh2CIJcipCOdI38iUSAfHQIZFRR/DmgI/wF3+//0ze4S6frjsd9Z3BDa6djw2CnajdwM4I3k7+kL8LL2sv3UBOMLpRLlGHIeHiPCJkApgip7KigpkCbGIuMdDBhtETcKoQLn+kPz8ust5SzfHtos1nnTHNIi0o7TWNZt2q/f+eUa7d30B/1YBZANbxW3HCwjnCjaLMMvPDE4MbQvuSxcKLsiARxgFBIMVQNw+qXxOelw4YbatdQq0A3Nd8t3yxLNPNDh1N7aB+Im6v3ySvzCBR4PFRhgILsn7i3FMhg2zDfPNx82xjLdLYUn8B9VF/YNHAQS+ibwpubc3Q7We89Yys/G/sT2xLrGP8ptzxzWHN4x5xTxe/sTBo0QlRrdIxwsDjN+OD08LD45PmI8sjhDMz0s1CNJGuMP8gTN+cjuOeR12sfRdcq6xMbAuL6kvozAZsQVym/RPto/5CXvnPpMBtsR7hwuJ0ow+jf/PSpCV0RyRHlCeD6LON4wqyc4HdUR2AWh+Yvt9eE817PNpsVWv/W6qbiFuI66tr7fxNvMb9ZS4THtr/ltBggTHR9OKkM0rDxGQ9xHSEp0Sl5IEUSuPWQ1cSshIMoTzAaM+W7s29801NbJEsEuumO117KhssS0NLnPv2XItNJv3jvrtfh2BhMUIiE8LQM4IUFNSE5N+k86UAtOekmpQso5IS//IsEVzAeO+XTr7N1g0TLGvLxItROwRq37rDWv5bPruhDEEM+X20XpsPdoBv0U/CL3L4k7VkURTXtSaFW/VXxTrU52Rw0+uDLQJbUX1win+ZvqKNzAzsvCqLiosAqr/KeYp+Opz642tuG/hsvO2FHnofZFBsUVqSR8MtI+SUmOUV9Xjlr/WqxYplMSTChCMzaQKKYZ6gnV+ePpkdpWzKK/2LRQrEum/KJ9otak9am1sdu7G8gX1mPlifUMBmwWKibLNNtB9UzAVfdbZ1/0X5ddYFh3UBZGjTk8K5EbBQsY+k3pJ9kjyrm8ULFEqNuhSp6vnRCgXKVsrQS408R2033jbPS/BfIWfifhNqNEWVClWT5g8GOaZDdi11yiVNVJxDzSLXMdJQxu+tfo6tcqyBK6Ea6HpL2d7JkxmZabCKFgqV+0sMHt0KDhSvNgBVcXpCi+OChHclM5XTJkJGjuaIlmBmGOWGBN0z9OMEkfSA3W+oLo29Zpxq+3HqsbofSZ45UIlWyX/pyVpe+wtb5/ztHfJvLvBJwXnClhOmlJPlZ7YM9nAGzsbIpq6mQ3XLRQt0KtMhIhbQ5P+03o+dXjxJG1eagEnoSWM5I3kZaTQpkOormt6LsvzBDeAfFuBMMXZyrKO2RLvFhnYxNrgm+QcDRuf2ibX8xTbUXtNMoikQ/Y+zboRdWXw7izJKZDm26T4I7AjRiQ1pXPnr+qSrkAymHc3u/fA8oXBSv4PBlN6Vr8ZfptpXLXc4ZxwWu1YqZW8kcJN28kshBu/D3ovdSGwieyHqTbmLWQ7YupivSMvpLbmwWo37b2x8bav+5CA7UXdivsPYdOxlw4aIRwaXW/dnt0rm6CZT9ZQ0oBOf8lzxEQ/WDoYtSwwd2wa6LMlluOWonyhy2K/Y81mY6lqbQSxkLZpe2bAoQXuyulPq5PUF4aaq5yyndFeRJ3QnEAaJNbXEzQOnYn5RK9/Z/oMtQUwdqvCqEYlWGMK4eehceHl43gll2jrLJYxNfXk+zqATcX1iskP41QiF+ga3d0x3lme0h5enMraqBdPE51PNQo8hNy/vjoLdSywB6v+5+/k8qKYYWvg8OFjIvflHSh6rDJwofWi+sxAdIWxitqPyVRbWDKbN11XnsifRp7VnUBbGRf4E/tPRYq9RQu/2rpUdSJwKquQJ/DkpWJ/YMngiOE4Yk1k9efZq9pwVXVj+pyAFUWjSt3P3ZR/2CYbeB2jnx2fod80XaAbdtgRVE1Pzgr6hXw//LpntSYwHyu154kksSIAYMIgemClYjikYaeIa45wELUoemw/8EVLStMP4FRPmEKboB3V31hf4597HembgRiaVJMQDos0BazAJDqEdXewJSuwZ7gkVaIbIJRgBaCrIfpkIWdHq08v1LTw+jq/hoVpyrqPkZRK2Efbrx3t33jfy1+pHhyb95iSlMvQRotpRd5AUHrqtVawfGu/J75kUyIQIIEgKqBJYdLkNScX6xzvoTS9+ck/l8U/SlUPsdQyGDYbZR3r336f2R++Hjhb2Zj51PdQdQtaBg+AgXsZtYLwpGviJ9tkqWIfIIhgKiBA4cJkHWc5Kvgvd3RP+dg/ZQTLymKPQZQFGA3bQl3P32ofzJ+6Hj0b5xjP1RUQmguFRkBA9jsRNfuwnOwZKA7k2GJIIOogA6CRYclkGmcsKuFvV3RnOaf/LkSQSiOPARPEl88bB12aHztfph9dHiqb35jT1STQtQurBm/A7ntQtgCxJaxjaFjlH6KKoSZgd2C7IefkLGcxKtjvQXREebk+9IRNCdjO8JNwl3patB0KnvIfZV8m3cCbwxjF1SYQhcvKxp3BKbuXdlExfayAqPhlfuLm4XxghOE94h2kU2dIKx8vdjQn+Uw++AQCiYKOkJMKFw/aSNzh3k7fCp7Xnb7bUVillNiQi4vkBonBZ3vldq0xpO0wKS1l9aNb4eyhLGFZoqrkj6exazPvdfQSOWE+uUPxiSFOIhKRVpBZxlxgXdIell5vXSYbCphzVLxQRkv2RrOBZzw5ttNyGq2x6bcmQ6Qp4nYhraHOYw9lISftK1fvgLRDeXk+eMOaSPXNpVIHFjyZLRuGXXwdyN3uXLXarpfuVFDQdcuBRtoBqHxTt0Pyni4E6lUnJ+SPoxiiR6KbY4slh6h7K4rv1vR8ORP+dsN9iECNWxGrlVSYvdrUnI1dYl0VHC6aPZdXVBZQGcuFBv1Bqnyy972y7u6oasan4iVNI9NjOmMApF2mAujbbAzwOPR8eTJ+NEMbyAJMxBEAFNmX+NoL28Zco1xkG1DZt9bt04xP8gtAxt0B7TzW+AAzjC9bq4rosaYhZKYjxWQ9ZMam0ulN7J5wZnSEuVT+McL1x7vMIRBFFAxXH1lsmugbjJubmpyY3ZZyUzNPfos0RriB7/0++Eq0NS/eLGEpVScLpY/k56TRZcXnt2nSbT7wn/TVOXu970KLx22Lso+7ky2WMdh3mfMantq8WZLYLxWk0otPPwrfxo+CMf1qeNx0qPCu7QhqTCgK5o/l4KX75ppob6qo7a6xJXUt+Wc97YJextiLOY7kEn4VMZdt2OgZmtmHGPOXLRTFkhQOs8qChqGCMz2YuXS1JvFM7j/rFakep6Vm76b754Qpe6tQrm0xtrVPeZd97QIvRn0Kdo4/kX7UHxZQl8hYgVi8V7/WF5QVEU5OHIpcxm6CMr3JedL17nI3bsascOoFqM9oE6gRKMHqWmxJrzpyE/X5eY097kH+BdwJ6w1PULDTO5UgVpRXUxdc1rgVL5MT0LmNeUnuRjZCMH47ujZ2fjLtb9utXGt+6czpS6l6adNrS61TL9Yy/PYsecg98YGLBbaJF0yTz5USCBQeVU2WEVYp1V0UNVICD9bMyom3BfhCK/5uup43FXPt8P2uV2yJK1zqluq26zesTm5s8IAzsXaoOgk994FXhQzIvIuOjqzQxdLLlDTUvNSkFC/S6dEgjuYMEAk2xbRCJL6iewl383S38evvoK3jrL4r9CvFrK2tom9WMbe0Mbcs+lA9wIFkBKAH24rADbkPthFpkouTVxNM0vFRjdAvzefLSkithWpCGj7V+7e4VzWKcyTw9u8M7i9tYi1lbfRuxnCOcrx0/Pe6ep09zMEwxDCHNUnpjHrOWZA5kRKR4RHk0WJQYg7wTNyKuYfbxRoCC/8IvCf5P7ZkdCfyGTCDr69u3+7Vb0twebGU84310zhQuzC93ID+g7+GSokMS3ONMc68T4uQW9BtT8PPJ02iy8TJ3gdBRMNCOj86fFm57HdE9XOzRfIG8T0wbDBUMPExu3Lo9Kv2s/jve0p+MICNw02F3IgpCiQLwA1zjjeOiM7njlcNnsxIiuEI+AaeRGZB4/9qPMv6m/hqtka0/DNU8pbyBbIgsmRzCrRJtdU3nvmWu+r+CMCfAtsFK4cBCQ3KhcvgjJgNKY0UzN1MCUshybIHyAYyw8LByX+XfX47DblUd5/2OnTsdDuzqrO5M+R0pjW2Nsm4k7pGPFG+ZcBzAmlEeUYVh/HJBApEyy6Lfwt2SxeKp8mviHiGzoV/Q1iBqj+CPe+7wHpBuP43f3ZMden1WjVdNa+2DTctuAg5kbs9vL8+R4BKAjiDhgVnBpFH/EihSXxJisnNiYcJO8gzBzUFzESDwygBRf/pfh98s7sw+eA4ybgy91/3ErcKd0U3/jhvOVB6mHv8/TL+rkAkQYmDEwR3RW3Gb8c3x4KIDogbx+0HRkbtBeiEwUPAwrEBHL/NPo09ZnwhOwT6V/me+Ry40rjAOSM5eDn5eqE7pzyDve0+2kACwV0CYQNHBEhFIAWJxgMGS0ZihgsFyAVehJPD7sL2wfOA7f/svvg9130RPGr7qPsO+t56mLq8uoi7OftL/Dm8vb1RPm2/C8AlgPPBsQJXQyJDjgQYRH9EQsSjRGJEAsPIg3eClMIlwXAAub/Hv1++hn4APZD9O3yBPKP8Yzx+fHR8gj0lPVl92v5lfvQ/QoAMwI5BA4GpAfyCO4JlQrjCtoKfQrRCd8IsQdTBtEEOgOaAQAAd/4L/cj7tPrX+Tb50vis+ML4EPmS+T/6D/v7+/n8/v0C//3/5AC1AWcC9wJiA6cDxwPEA6ADYAMJA6ACKwKyATgBxQBcAAIAu/+H/2f/W/9i/3n/nv/M//7/MABeAIQAnQClAJsAfQBKAAQArP9E/9L+Wf7f/Wn9//ym/GT8Pvw4/FX8l/z//Iz9O/4J//D/6ADsAfIC8APeBLEFYgbnBjkHVAc0B9UGOAZhBVEEEQOpASIAif7p/FD7zPlr+Dj3QfaP9Sv1GvVh9QD29vY9+M75nvug/cf/AAI8BGgGcghICtoLGQ35DW8Odg4KDisN3QsoChcIuAUcA1YAff2l+ub3VvUL8xnxku+E7vrt/O2M7qrvT/Fx8wH27/gk/Ij/AAN0BsYJ2wybD+0RvRP7FJkVjxXcFIEThhH4DukLbgiiBKAAifx6+Jb0+vDF7RPr+eiM59nm6ea/51bppeue7iryMfaU+jP/6AORCAgNKRHTFOYXShrnG7AcmhyjG9EZLhfME8QPMgs6BgABrvtr9mLxvOyd6Cjle+Kt4M7f6N/+4AvjAObJ6UzuZ/P0+Mn+twSSCiwQVxXrGcAduCC4Iq4jkCNbIhYg0BygGKQTAQ7iB3QB6/p49E7unuiX42DfHtzs2d7Y/9hR2s3cYuD35GvqlPBF90r+bQV3DDATYxnfHnYjAydoKY4qayr9KEsmaCJvHYYX2BCYCf0BQvqj8lvrpeS23r7Z5tVP0w/SM9K906PW0tos4Inmuu2I9bj9CQY8DhEWSR2rIwMpJi3wL0oxJjGDL2ks8Cc2ImYbtRNaC5gCs/nt8Izo0+D/2UfU2c/bzGfListGzZHQVNVs26vi3OrA8xP9jAbjD84YBiFMKGMuGzNNNt03uzfnNWwyYy3vJkEfkxYoDUYDPPlW7+LlK9111f/O/MmXxuzECsX0xp7K7c+71tXe/efu8Vz89QZoEWQbmCS9LJIz3zh4PD8+JT4lPE84vDKWKxMjchn+DgYE4Pjh7WDjsNkc0evJVMSHwKO+ub7MwM7Eosoe0gnbIOUV8JX7RQfNEtId/Cf9MIs4az5sQm5EXUQ3Qgs+9zcoMNgmTRzaENUEnPiN7AfhZNb4zA7F5b6vupG4nLjSuia/eMWZzUzXR+I37r76fAcQFBYgMCsGNUs9vEMlSGJKXkoXSJ1DDz2fNIwqIh+6ErIFcfhb69jeSdMKyWzAs7kWtbuyt7INtay5dMAxyaLTd99V7Nr5mwcxFS8iMS7XOM5BzkieTRdQJFDBTf5I/0H3OCsu7iGcFJ0GXvhM6tXcYtBXxQm8w7S/ryetEa2Br2W0mrvpxA3Qsdxz6un4ogcvFhwk/TBtPBBGnE3SUolVqVUuUypOwkYtPbMxrSR+FpQHY/hf6f7asc3gwee3GLCvqtmnr6czqlWv77bHwJPM+dmS6O33kgcLF9wlkzPEPw9KI1K9V7Ja6FpbWB1TVEs7QR81XSddGJUIfviU6FXZNsunvgu0tqvppdWilKIopYGqd7LNvDbJUte15uj2bAfEF28n8jXcQshNX1ZcXI9f3l9DXdFXsU8fRWw4+ik3Gp0Jr/js59nX9Miwu3ewoKdzoSCexZ1koO2lNq4BufrFwNTf5Nz1MQdbGNMoGDiyRThRTVqqYBxkhWThYUNc01PTSJY7gSwJHK0K9Phm54zW68b8uC2t2qNOnb6ZRpnsm5+hMqpltePCRNIS48r04gbRGAkqAzpFSFxU612kZFRo2mgyZm5guVdVTJk+8C7RHcELTPkB527VHcWMti+qZqB/mbGVG5XEl5mdbab/sfS/489Q4bTzgQYlGRArtDuSSjNXNWFIaDRs2Wwxak5kXFugT3NBQzGMH9cMt/m95n7UicNitH+nRp0Ilv6RSJHvk9+Z7KLQrjC9n82c353yDgZZGegrKj2ZTLtZKWSSa7pvf3Dbbd9nul6xUiBEeDM4Ie8NMvqZ5r3TMcJ/siClfprskqeO0Y1xkHaWsp/dq5u6esv43YbxiwVtGZIsZD5YTvFbxmZ/buFyyHMscR9r0GGFVZ1GizXTIgUPvPqU5irTFcHjsBKjDpgtkK+Lt4pOjWCTwpwpqTe4eMln3HHw+gRjGQ8tYj/QT9ddCWkPcal1snYidApummQZWOdIezdZJBgQVPut5sTSNcCPr1ah+JXOjRiJ/oeHiqGQH5q3pgi2nMfs2mHvXAQ8GV4tJUD/UGlf8Wo+cw54Onm5dp1wFGdpWvtKQznJJSUR9/vj5ovSkL+Eru2fPZTPi+aGqIUgiDuOzZeJpBC06MWI2VfuswP4GIEtrEDmUadgfWwLdQ56XnvveNVyPmlyXNdM4johJysSpfw0537SJr/Crdme35IzihiFt4MahjGMzZWkolKyXsQ92FXtAQOaGHgt+UCFUpJhrW12dql7HH3DerF0E2s0XndOVjxdKCgTW/2f55zS975HrRie3pH6iLGDLIJ5hIWKI5QIodCwAcMP117sRwIiGEUtC0HbUipigG59d9x8cn4yfC12kmyqX9pPmz19KRkUGP4i6OTSAb8UraqdOpEliLGCCoE9gzmJ0JK4n42v1MH/1XPriAGTF+os5UDqUm1i9W4heKh9YH87fUl3uG3TYP1QsT58Kv0U2v696FPTQ78prZCd85CzhxqCUYBogk6I1pG2noqu18AQ1ZfqxQDuFmYsh0CzUl5iDm9geAt+5H/cfQN4hW6tYd9RlD9bK9EVnv9s6erTvb+DrcidCZGnh+uBAYD6gcWHNpEDnsmtDsBD1MvpAAA=\" type=\"audio/wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\n## Video\n\nMore exotic objects can also be displayed, as long as their representation supports the IPython display protocol.  For example, videos hosted externally on YouTube are easy to load:\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('sjfsUzECqK0')\n```\n\n\n\n\n\n\n\n\n\n\nUsing the nascent video capabilities of modern browsers, you may also be able to display local\nvideos.  At the moment this doesn't work very well in all browsers, so it may or may not work for you;\nwe will continue testing this and looking for ways to make it more robust.  \n\nThe following cell loads a local file called  `animation.m4v`, encodes the raw video as base64 for http\ntransport, and uses the HTML5 video tag to load it. On Chrome 15 it works correctly, displaying a control bar at the bottom with a play/pause button and a location slider.\n\n\n```python\nfrom IPython.display import HTML\nfrom base64 import b64encode\nwith open(\"../images/animation.m4v\", \"rb\") as f:\n    video = f.read()\nvideo_encoded = b64encode(video).decode('ascii')\nvideo_tag = '<video controls alt=\"test\" src=\"data:video/x-m4v;base64,{0}\">'.format(video_encoded)\nHTML(data=video_tag)\n```\n\n\n\n\n<video controls alt=\"test\" src=\"data:video/x-m4v;base64,AAAAHGZ0eXBNNFYgAAACAGlzb21pc28yYXZjMQAAAAhmcmVlAAAqiW1kYXQAAAKMBgX//4jcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTE4IC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAxMSAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTMgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MzoweDExMyBtZT1oZXggc3VibWU9NyBwc3k9MSBwc3lfcmQ9MS4wMDowLjAwIG1peGVkX3JlZj0xIG1lX3JhbmdlPTE2IGNocm9tYV9tZT0xIHRyZWxsaXM9MSA4eDhkY3Q9MSBjcW09MCBkZWFkem9uZT0yMSwxMSBmYXN0X3Bza2lwPTEgY2hyb21hX3FwX29mZnNldD0tMiB0aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MyBiX3B5cmFtaWQ9MiBiX2FkYXB0PTEgYl9iaWFzPTAgZGlyZWN0PTEgd2VpZ2h0Yj0xIG9wZW5fZ29wPTAgd2VpZ2h0cD0yIGtleWludD0yNTAga2V5aW50X21pbj0yNSBzY2VuZWN1dD00MCBpbnRyYV9yZWZyZXNoPTAgcmNfbG9va2FoZWFkPTQwIHJjPWNyZiBtYnRyZWU9MSBjcmY9MjMuMCBxY29tcD0wLjYwIHFwbWluPTAgcXBtYXg9NjkgcXBzdGVwPTQgaXBfcmF0aW89MS40MCBhcT0xOjEuMDAAgAAACqVliIQAV/0TAAI/3gU2tIW7KawwaCmQGTGHKmuYAAADACBcshU+yICkgAA14AHowiEeT6ei7v7h3Hu0i2fpUBLGBIkbCMP3Vfz+9BVGCDXnw9Uv5o3iN030tb7eq6rsEEhHs2azbdTiE9Csz5Zm6SiUWRdmB43hbD5i6syATuODUJd7LM3d9cbFpc7zFlu5y3vUmNGd6urpvKKT9iyleIyTuR1sVS431DhevGfkUllVeIznYUe2USoMW1tufETjyRdmGldN6eNlhAOsGAH4z+HkrwKecPPU7Q5T4gDAIxj9hW84jVExMTSTHxkPTq1I4OotgUxURCGTsw60k/ezPNmNg38j1bqaGmPcruDKEIBDsK5qEytFB90Q68s0h2wmlf2KXd5bleBefiK+/p47ZsyUO4IdlW25rRy+HLjt6wQXfYee3IkiQOoOK+U7u/lxcl78zfxwIoEMjUUSKNZjkp8clnmecDDJ3Kz+viF7bPklk7N6QRyizAKPIIpnNJUuMWQmqeL2Or6cr4D0/0tOym+4tficxmhuEONKUtO2pPn3hRjMllkd12tXp70fLTfxy0dwB70ML9iLEcItHb7zVupHlP5RxdvecpREw+OsIPr9KWilIesNE19jgIbT+TkiRBjOoKvUuwcQnKg7fOTHVoLvnKuAfea+oujEdm1Rwd2tEOnkF+ZC11WaNQsiNR/eJ9EnUXjXDYGfhB+Oe7qj8nYTT+eOXg1cuJNgLXEs4vOheWEjQOqfIWMQc3DmTof5s0ksBmUQ3PQ+UHPxZSnmOEZB+j6xT3wbm7HGzDjWtSg1SjTxd1EiJ8xA4SIxxR8WIKLg+TwFxJNS7Laxq7Uglu3AkXe82P1JCdJX5PsbFbxuDbuJgakzRcTwMLLSKCiizS/eCW0uJed/lev9yb80kKlVET4S219cn/zhkpeDV83cHYOr+sJQKDRk/Wh2c7fsuxfxaEH/6reSmvFDsAnXAyPXliJ3G4VG3OkEM5K5WyGGrBizZbTrdGsBnzj5VSGGOJdCKuRrUluw/8es2vYRPs9BcTqAqvHk9M52SSIf+1T6L53EZP8VbtXB+G29CMW4xVCK/B/YDjaNmqMwJ61dapugjnWJfqeXlGGa3Ch3aA7gi30T8PucNRBjLK3lF67ZDDvkWXRQXd+VMnKWHkBbCkQ/F/fMuNpHO3C00Y2pljna1qImBhVMvPe0F7Qx7G/YyxLRzhyUU8e23HGzp0agtNJRbydbrPV+TqJMSifJMNcZIf8wkdnC3/xdpcXnLf2Ye3Kbd0o7utciTG+q5h6WTEk+PaNbXLLA0YyZ2VnLTcyV1QTS76aNCbV9Q1/OQ7QU81Gg0hPa9aSiscGary6jLVwDQaik4zLsi7jPqgPVdup7pwx7uJDqRCVcVi5QoZFp/GHdex5sJTF69A6sja69/NLkFIWNSIeRcuGahXpF+wZeYIrqJv975s1TKYKAvp1WtzgtgWNkcbzCtROqf8rPtlAIxkX8GLcEo9zfExyfimeXQ64qfFxEy0IMy2Hsxau9fSMqUnIjntuVVjCQtBL+94gx1RZLndE6wROVTq/wHwHrQzo9QL9cpPqPFJjiZ/NGZIFuudS+wsBFe6Hu8Oitf5zToLqLdtU4Smwh4ne3JsiT9lOzN+4PPw3VSx9l5FppVwdKUWELw1dYpCOppyVWlJ3YQ8H4FQQM8EcYMG9N3Bxu79y1J1ikuvuhMmLQlehLTbguhbix74hd1VIQC8EjHmOZSSWbssulYwPbr6FF49tifk6PymJvulR9/u+2585HkRfbxveGeWCz0ix1pIVfaNpESKmtLy/0mcbMg9hYDz2werz9oe0lT2BiMV6uAin6RaQcT8Vk9MPctfwae+gkvtnZA/sOBk8MbpylaHqc0KIVHhhLFMNnkOFiucjtGo/JWTa/F6g8wWeow5ZuIJUORaYHWqegZbTgM9dCsYYsfZGjjVMuSlDIvpYvIvFFooGPC7Ye2Jfawmq4Ut7EL/nv/dyAd2HRc5msmUhzeu/XpX3rVlzRmf9/Qan8Dbve3QfW1Ym0o5J/KAc3z1VBho7JBr5PgCL68RiD9jZHN0VvsT4gzsEjNlW3D91Uy4RduaodBFoNTzXwlfUYULBzdiTbH75l/UmVMC4TKeTWhNzw2UezaqeGd8at3WSY7W/VR3+hvZHDpkIjgKuNNH0DsCRa/Kk56XQoHIyvvUH/eNekNvziReqS4qgLnXUT4BRGt2BOtCifI6+X/DGHUOmWlX7TN5b4pw5U7jwfwshtbhGZM49T8JMk15Mzrc7tM6J11TYxb5R3mQhZ8TZumJ0bMJXPM69HFyihr5dJSEJMycxJVUh6NTQALUOoRTHIOwE+FpWI6feTv1SiZ0YpYe5DbkYJJbN7zAHbAKw25XvqR2mAjQmOlsfX/tK8DPjP/8h5/xgAF4EUbj1tOnQCBQL8jk9vHtfsXncsprww4Z+P/Z/UrKifuFyEpBWN8kLpF7yywE2iYdDruV9+/qKR8rC9ozNKyqQNIwtxrzYkWpE5t8K7gG4JFnrHona/Rp8dOX6VW41+jb5LB1LEtE8MwjLp3RCUOq/+6yLzaOEgBTqzvEjDeFpg/u9DMHMr4/2TOchfjg7dl+uQ6Gsx+4Ia9W7vivG95027p25eKL0nHvx/OqmAQEZYJL/JO58lOj0zPdJxrQ5dZksjMISzVZNn7DsxqE3zgBBuNzk50R8lTK3U8P12QiOAQYSTeGlYlkvfeofrfO1AitEj02m9aUkxTFd1ZZJoLQT2d3zEU5PmE4lxMVfL5ttNnIbqfcIU2RJKNWqdw77xfjfrNc/eNpRKPZ/6z50LzBprgjzBHRfKgSWWkDxHrX0aTbgwQFwd51+PoUWH4DkQg26uGslF5Hn3hB58+fkeLTosTANOIBNAeFZtTc4PIaLHw759zae7scY55xcTabzlilYIftst2RZ6ntsRC3zFxduCKvL6wLfYT+TiIWJn5P7sTwZwXuSzXY+9Q3xMZ5o4Xcpz6vD9FtTjzS69iefEYt4pXiDrZUo4ePGiLeoIFIwYB/v6GXdmG5VLLk+eKbOc9AmsX2zmvqtcvDRGQbzugXbH/kTH/lkNPBTmqN3ZJODUEXVohPEJ6th0xna0EVleB73Q3eNvaVUvhlJbjs3D/T17FRCebN7AOXvzzbLE/I5kNfEmJcv4dxtIeo2uQ/z9ohSpiZzbDj1u40nJRyJxUK60wEv0nA9f/NuJ6/PEyU0bkK16z2KH12k3Lc4+1f5fawIzkK2qJRB4wnj8VHhUW9mbJhs9vgfFmU3xrXSShY67Ygb+gYNPxxtn4K/9eTSwIA9fv/nR33lA2lZoXALRUTmOZIl3R0gAM5h6oX1y1thIyqViBK95VZc8Pvy7G3O90M9S4zkpyFQ36jrMazvMveMA4d39fvoaC7p90quiJfjI4yrl+ECVkCJL5MxRSa+iVcIL7Xbl0jVaGhZIcMYmcGOBbLzhJgloM1x1zFnnj3ggJRFAM8yNnXxhavk+mA18JC+y3lqGsp6vPReRxGlGHMou17L4It070LzkoeCzarpv8Apw59smdS5KN9qVN1WgeL7OSN8BHg94ubCvS7DW6H3/PbtRB62jFLsBhUV5YqCIbIN5VZ81AAACpUGaIWxFfwAru8x8uT3FuOjrAeSWXmAWqq9jCNGE+N5AOv//9//xjk4uBAcADN96c97AVGmzRtnWwPsgcCbLrVdQJgbKp4QSmPwQnVhv0hXyBjeFWWlcvx70urEN3FK6/lvk2tQeZgbtlbzXluvTfnSj/Ctz7vZ+O1FjhDzzdpL7uLzewzCIW5VWLAEKUVuS2J6wNk6MR7UblcEd4EtOY+R4/qJgfojCsfRvA0oC5dc41Vd0erZbSkrmPTjLCn815bxlchUJMS8gQD5hJNwoKHvNLNwn7XKuTtYIhH2wVNZvDWgzCjlPeQajnrcMsb6bZYJvNJU8HuGHvm50r7VG8qifEwmuyegAZXojh5Ul5VvjDW7kSAZyw8a7I6mHY3FZHd+OA3V4JZMbNliI3Tj1L6+MKTmilVialmyZagRtEMeKRdtxUPd3vVEtrOBVIVYWdgAGA7HmZiHQUQNxLkWxbLyWVlrh5EM0Do2NdbclHxxArz90d+MSVeUOIXQ/4V9quq8C8qVflo1gPtPMkjO2/UrdOYqhY404ReObOu/fdp4hAEDq6jhy64vOeT7XUK/Onq0rXTldtA6kvgQaJg+mgYSR9hfXtMbOUSLgLj/RmBSO8aAMHuJJZqf1tCM5pZ9eYUsrHmy+/z2NGalon0//uF6+33bQzT/RLRfBbYTjy9QrJqHLlw46lggWPGkHuPKSqk/CB7U4pNPXUbR0DdcJy9Db00wCzVzxVc6h7jfCFgiL2Y0HVqd6bgIaVUqn/gJCEyCDVplnzebv0gg3XwMJAGu639lHu7rEvxTp1smIYjWp9R5L4SspVvS07Nb+Smk1FgsMp1K3EMUT8X2Fty4VG54/Ec6bE8tNVw4/QV1VzBw7Px2/2eEhhUS+FMfbHAlD28x00jRgAAACW0GaQjwhkymEVwArOUkEOhoFqiELtH8wgecFLiUq6WqmwAP7iGEwbYzfnHacfqUNXAfD+CGR2ap0lAHL25ipuYtd5j2O0PU/MpaWPG/n2y5OkfTzaOpotaR5tWjN55B2XblVVqsFfBC/mvsiPvCBWUHFChacdY5whj5mP5rqQ0dqLJCsWjrs4TWnIbL2V/Iwfj3hwI35jfo1JkTOeR+8GhOdma9rgiKWafCbQyhYMTDmVdvhND60Flm97EDSTjF0OC+0gD9b8Yn4tNeHipCa/aWyt0n79bMmjfcjntBCPjrcB5ecRTpfGHbEHy1IRj2cjkGXKC+VYoYJXBp4rd4cMd8ygLCk5nBSd8/cTaKNRjdBscOeTXG6QEjSxj9/2pVwx9DMRVtWQR0BSaAcQcZ8W2KPSaeRC4QwmNMu2xx25CSyrDiq2rFSK/JJtmvoIjAKq0ciEXoOgw+Ke+Ylb7ULKCS3k1p/613UNRp450uSq5b7CAHo7S0b7fBMLfNmwSjRYEhLlo0HUaRe/I+IX2Z6XdZH9Hty/399ZA1PwZGC6EfvUJIf7CBeaxv7cu6IT2/s0zPRGthpvXpYw6A7P4Wwz5C4V98KnIUNUanadqabKP6eXWhvbvcQHxAjiOOiKZgXZplZW2g+B2NNyJSLiR+g48DqvWR6t9S2aGfFjdOW1Gi6oTtZ1d4p5XIslAr8mryeZ6+htSSQe4AcfVt7k+V6mOthBCYtr/LEU4ZHtl0mW9876PK8mRFAaT8DJOUFVz1lPfzRApuPggkkyq+UMvyfKTUbCk7/DpfX8Y4s4QAAAg9BmmNJ4Q8mUwIr/wAsWUPjZw3ksgRsxZ6n4fQjprPbkj2aUh30y0bZJnLmiXnWskvOGnCPwBnG9dEhatwX3hoxk7BNyG+wQ4emZUpcVzcWl2T9nKQB1euucuZWHTg7TCtM/iHyfPO2vbmGsfzs70b/egIbywUH4y4BQSL1nWc1SmpHm2zHMBcUjYLDZ5gL5vdfxn0V8FFw66G88c/LN4I5icUa7xf4fcSBKywU0ajbp1P+aJYjBgWT6Ggu0MDLDNl54tfqd42lKosQtM1aif4WXAZFP5Ww3vrQ1rH9+utSYxqZd6N6gGtNbSNMcViaKn5LcnjsbBi3T3EmGqshEbcme8VHKwR3kSfBOAprrIsv6K8R+X6az+MD23rWka/2v64m1qM69D7Xa+Kcs/n0KLCJdTilyaGadopLeaAn3eYvWTeHcucMM1Fp1KgHD1tiFeO6HvobLkZlRximsA3/7MiohYklLIcJrZL22BH+6W9d6kZsYIsej9RM681nU6mWNjepBAfAfTbrGRrVB/h2DxC5B8YyRjgSIzQjNYrse0rzChqbrsLl7mQ7W+1bsNKze5//9ZIa8rSsF+BXh/vgoRTDkPW/ws95B7VPCZEFChfX0icw+tpcpN/q7NY87tUn4vESdSiMMlyhKklMjQu/G51J69ZRQLs2oUO6YfoJFqliy4qCFCrf8SZE9Fc6DcCagAAAAodBmoRJ4Q8mUwIr/wArPWF/KOw78THwadfPqhJO0CnmR/M74/XYZLqVYKlNcEaYauf+vrRUDJPmu75sMKy2Y+Bnslc/iAISSyWtw/h/3CF8fE5ZrbrwSNst+MSyCoNWP+8imtoX2eyojpdCk8YP5K+cbK4SJPCkZXbYqSXYk7hO8AdSemBHgXKWiZ+UOr802aJo+98ZOIjX9hWL9bo31Gqx7cy4ZG+W/ar/WGlzDa1xPWnPRsEdrIcZlEVGV/jGmbirkxw1lyUYoqj8Vv7Bxube9XPQlBkXOV6Lc1LT2IzNq0V7WwVhF0kA6yxfAsFxc9krNEH8vGGntTWI608ovjatXc/CKKXw7AjJSftlTcLI0hIIGXbRUr0NCYNp7M4cVd/n73Rjetnixz4SAKpcz/P47UsijZG7T3SxzK2D79WS42aEalc12hQwCZ01LfmF/H2mmGEvOzPBie1D0YT7Jh19vxa4Dd3SQ1FrDfmSUpvv4DjbYcZ2PrPpFpWtMjWqHBeoyMiZf6RP3EfYR6z9jsVNIIHxM0bzzBQF8eeYkPgDySydxPXv9Izo+QUY94N8kWi16fI6eZSDc1G0Yo0L91jcRQuDMGGS7B2zuf/0GbJyRhUO48UbMrqnILMrbQg1LF00Q3pH9nbGEK/RRQpRN3T/J/4IZQjwW2Ft2ipWGztg1Jn9I4DmffKS60QC+JQcyakdVON6zDcKttIKlqeTcmAi4xzmo4QXa2dRKleS+fs3EtTdBBtony2wK9T2Imj+NCziOSEL7Q7VuIU8kclUHrJJsSneFcxGRgIgGGUEQM8/pklwTOqab7mMmJeRiaBrjJDEnDpkR4Vz3qXxgyn4/5x24FuTMNVPwQAAAhtBmqVJ4Q8mUwIr/wApcLwPT0/Xh9UdWqWXIs8Wbj5K1hivmN6qIQnq+aolcegdlM/63MbHsdC6xYZC1e/Q8UjQCt9N/Ejqwms8DzeWv2qxskeliZH0kt1QWkErWSEodq7V0ZNksctLkMGWayX33gBT368EehfIeGDolBZoqIbJfb4nqcfU+ev4OzVv9zVqWyLck315GFmXxQKIM8pICQc8Q5es34LH1+DmnMnW8kQpVGrztQcDXhjCU3F0fOgoSsXSVWCjc6XKqGbCwQDfJUxCfXfIT6YmQoPpVp1mpGy1wQypXus9z0bScDpyDu23hViYDntdj1O45ea0znKZkj1+tLHbBtqAGJ1WTcbGlF6Vya6hQhEsiiZUIC2fRxIj8/wEXCICIbr0gZ/m6gcOhE10tenvE7iy+BKY81wLWrnzos3S6FWxYtmCRes+LLhNGOKWRuQo6SyePH2OZ90xZm8oA1MuTe3V59euVNxjAt0FLkAc9TEiFhP/8CB+gA8mF+A8h1U01f4DVX55GzCH51jHI2xUS0L9GtsHoBxLPLK/NNel8zcnwG4X+UusfcfEb5hh+ffnXteCE9vRGbs2n9wYW0xA3ZicklfadmWKUtMiHYBfkMSULWnkBQr4CXxjpYOs6ygeEoA5+5B0B1SZObgZ42wWqddyyYE0NfwQAl75tfdJGqOa7OMHwBYNeatJaJK0zT2+bFaw2qWCWwAAAitBmsZJ4Q8mUwIr/wAstkdsayRXchoFk703izqzduZ5WsyXriI9cfUdMUWvm0iGHwYIrUujvz3Yjou+JLwv9df2kt7MJo8u+3P5CjEKbwlz4vkE5AHTAbgXn3+Xc/MMJLgW5cm7iX3KiGNnBpbphhwJRlb3u91NRDr0d1IR2up/z7lKxE7XPAPFe0siPMYVlIqWNSn5KqLABPeuxxbOsvMEb27/nH1LUVM8I2F95c1I3Lv1SpkhZXjs1JsmS9X7gsoTxkXyShGC2+zRJSGUbhCPo/q1XSFMHQyMWJ79FKPQSL/RpVsacN2bYwdKo4TFBw1SsKq/L1iOmqMI+4Gxnbbjojdk0ek0JIcDb4bHv1czxchF7FX1Ym8H6IpPuE8CeNKjzQ1a1wqhEu+wl1N0x3Y37ZryCCKJRkxj0FT7bOoH3L38/yMUuh/v3aCmxY4eCkykb2p6ZrYMFE044anM/nMjmbErMibfRFuCz58Io1rBlF7JfkIz0R2/5vjUMVskcdbX2mm7DntncOsWDIdg/XVmgsC9CzVzUyq4VsS/sk97lJggcddpWLNw/29egz8iLyzWHOAXCvl2fTIPkviYAOQXfVhZUQdxsyJUNFMTiALrZCmoQLMp2LmDbfbW8JQriDeR3fVz6P1sjT8C2yEDvzkCn7sh0aTBK+sx7BKH1nb4320+caQepQj4TCJtCeNXjdrVcNEnjvwlcRJwFT1pT+Y7HREbHnT71XYNh4EAAAGEQZrnSeEPJlMCK/8AKIjxcI58rm/ML255fOJW1zbznFna7lfgMQrka7OTPPsvVAV4EJXye/Uxiu9dlftmRypJqfDot3xwDe8lX/qAVf6pBkSlUsaLyBYtww/SUSa1bGl1JvrJCN7FXCCXbLd5R4PoYlPiDIm/DQH2puO0StIWmrR77Isc/J1pRvdu5+mQa/n0SEHUeM2KkoRzCznfD9zaaRO7BDtvC9SYIT0uYZxrwTjxQ7N7UERTrYG0P+vRLAhxkfohFIYl3HXyjPOvnlbUFP2oiiy6nkUFuaIyQcJawJv3GU8k4ObcKsC1cNDXjSpsyQRrxLFaCCjke4mikyt7vs0iN0bnrNWv9HXruG9zOFEOer1ggIFTsT1Eos5CXRkgja5HN4QUM6MhWpc5du/HgBIH8ANFcoo2kJpqcadw9r/0qk25X91MQSDJQiH8Hny2dQhqR+LFWEawiW753SJhn0ngZcv/mPj3mwcHv1SL9ErBqAjm4JGiDetPKYtFwANYY11OyQAAAVdBmwhJ4Q8mUwIr/wArOx5HV2505jRePGgMxptW4PGIHEszV1xGZS+flSkF+aq30AaqO7u6XK9jJsuWXTfYCRQTn1bZfFQ22DbO5DXAxK/TUmbQleCflFzeS6/czxkL4PJ8AwOs2U+oehekgCZC8gZyHHaQSaKbNJ46gTjNsLy84ACQ5uNt11TPuCPqPTuh+schdw9S+/lU/6m+EyaqGZ49wDFPiBFBYXglQQBjyP9k/rqq0xL7SiLjpe4riYg8SFUuUtOzPdWHyvxnI7Ug/0VLPGAAhgMISUnqe01d5QFf36yHpwMAHexjAZFIGQHAFautuMuEw6HzUZVzNdeHYxvEYOGkTo007bLwbuf/nxzrywGOxlRTYJLRdYI0mk0SdN3+LeTv1RIJwv21+e9rT5iFOTCgzeQoekEWXLYz0X8YLq5bVCtijP7/T7w1Ck71j0aqfrEn6wtIAAABNUGbKUnhDyZTAiv/ACcySi7VBgOid6qZNXvhh/JsllHkMLLq0yNbQTqv/Wk2EBoSKICZwFwAD0WRzhvvReCGirep1Fe4bxjm49/UR+OYrXRmHR18T0C83AUVeBk7KvDZmb/eHzuzEN4yfXucr/NWFJl+USVMY4r4UQ9CayrfEY9v6AQ6mzAdLy2UMfFxrRJ99g/Rfl8qx+m4jIZNjlrTaThzJ/3OpVmAliDfxVyg8+CVIlI31IykiwQrXcebgajG+av8XU1SfyAG5ibvwbtdSAxkGBcJWL387V+uTdY56w3KN2vBtoQpVKD2zb3yazIcATZ02upwIytNcM/rpaLCdMb1myWcikE25agzLhDhOS+4zwjYz2DnW6VY0gFBAPsphhsUMnauVVdUVHzCTSdvzEve/H8q4AAAAVdBm0pJ4Q8mUwIr/wAo+x5XKuiN1am7SkJKSMonFZDPU3f5XFcDQSs0FLVq2idfsKwuIkt1mxIq8NgMHpzofTnDHqs/WedvAmhBgL0N5azdQa5MNKG2rJ4IAvGQY/uFm3jKQAKzvhSS01gO1oIfizF817z9IShS4QK2WT0PeFPELqLSpED8eNOpVTR96vmwpk/WBKRVJdTQJzjiCQ5pgEwjtvk7KqoS0+lwXSbvIrXkYm8DignEts3DLNoLHrPjXlQmbIop76JZSyJEtB+91GrLwo6Km5GeebyA2E6qGL3xSkpppej/ruoFprSKrH60UMbrq/SK7eCo+1QFoySPQmqDFsMGiQFqvtld5BXDYdVI4yRaoyN7Y7wi83HRC6eVazuHU9OtIY3xJJApBWq1aJOsYwc38aTC3ee863Aa/4n9Lk4DAtyFYHNZjB5m2e2vk8G2Gny9YFlBAAABQEGba0nhDyZTAiv/ACoZSZQfHxhfQxEqOBQrP+L3DmgvHSJQtB1iVkcLTxm+vagLHBLG91OGnopwrr7gT/loDypIhoRxjcwAAOeg/jN4WBbXzCJtnWGGllUCSdtUZQzKOSp9iM4yX18C6jrY4Sq6R9PUV/lEGNveJR4gw4FMve7110XdEPL1O2VTdHvdqeANyaq0nLdEmtXnrzvdrFlBaUvmaR4EdlkqGkvkZKWJej8Vq+msbKa7JdbxjwZtRufiyGfD/NVqMgSrYRzw9z/a8Zwbr+9+19CxlWD5bCuAEfPmjY6kZJE2L/CQI6+tnCBTXOmWZtZMBoCLGOf7G2uAC3+kFlboh9as5WCkO6+iqXq29dyhKnsHInorRYsPlgxIXyU1Om/Kyhj1DJV0Am9WJK3Dln0zNUH0q6ZTOnZcFD36AAABYkGbjEnhDyZTAiv/ACcwdIOLRFfoGK2ZkKsvgMwG0m0qsY0vMLPSzefc+ebp/aztyF7MlsBz/fBeNtxFBcsKgR4pf65GvdfOMHah0ltZ918sMDmXUEZMeRHy/xpnWpTLeGz6uTs/7MATPmU5BgHbT/DkD8QeaZnFAzidyFCXDz2l/jaKhEdgqipbB2pH0+fQ039r05z9axxEWGmaLQjg6x9+po1o24yhkVO7m03YwWmPyCgy8cOwrvRyJkXJpRN4m8ZBS1zwY80HeN/VyMQQJSMwsTo7R1XMerSFuyx0nz+8qOuhiqykc2ohCCsXia/+kIKbJ5Vs+cbWtvkqBKIDSfU7FhAd3GjcY/xar0EVmi6wWFTugAogR3I7mTrQDdlTAqYgqO7Gn5NMXQVHu2i1zhFSdo9GjMbeGnbkJwsFbQ2XkoKRIDpuW7AewC9AEBt0Ox/Ah6dGXfXO1jl8pEApj2RFmgAAAPlBm61J4Q8mUwIr/wAlR+eW/VZ7bSrmwwMA62G05DZ7p/5FUugsSsQdonUq6abtbU5hjFr+I1lPgoiV5c3CkTQZS+K5zivdo+Ti2P4K90xXANp8dSMAu85uJIOCQn2TXbEnNDifLB+3V84ht5tj4lvTaZx317BcliV8D5v2zZQW8RO1mUbuJEBItst8E7hfE+ZXj7tfDxNZPTvtpFyUv0fH1cTg1pr2VLy0d0zQLiA58dg+GkRvR1/hs2LyifBgHcj6eTWz0vsypVn9iPXRH/unJ6i8cfFL69NO24tQ9QQB+nDFhoP2cRhkAvhHwn56n5PppBD/oxni2f8AAAE9QZvOSeEPJlMCK/8AJjAXVGf+Kj2XNJnFeKC/gr7dJDTC2ngpd4WeAHlg04GuJKnn9hAmiECxxo9qM1IYMRiB85t6gALnlm9sRqGmioyzAm18RJndc9Ah8RlpGzr+44a6ntRaPx0cIwNIWAA8buL2JP00dmfjNqEiAlCa8OdV8FQxjp1vDXsGcAGF3Qbd62KEpkimeI3wH2nuXpbDHm8/ZKOR49s5ifUCkxCoJpfp43aC0lTzh2NXpcfVw6h0QnK8G60R4ZAxOxaJB7c0nn8ixXSU2JVY24EtGMF53nxJnHfzUheewUfBOGYSxeo8oK7oUCqX4rztzDwoc2QywNqQUJUkFrqIN+sb5ecYvX24Zujn+ZzTW6UDAF3R6WdNyJyRAremgC8spSflTqygQNGfHyGkfIEEJJaFo/pBCBkAAAEWQZvvSeEPJlMCK/8AKI41fuekXG59Knbw4Y6YJritsh9VtQgc3QKvVmxrzzo7f4aXn8N74eyP4b2lV1Z2Q+rohxps7EHTkOY9jLdqxI3MXe7je4g2qepz71+hY+jYdX+9LO0kA0Zg3NfyAlIRX7k6c/YHAZNtNaGZgTBMqiPgmEjiJH9Luk7shbgr+srfwiYwBX9rdS3fQNNFwcT8orQC+F60LAY9+GbFo2Sw3Ld4Tw9jq9yJtrY8RtHAdzytyek/mv2+j2TbTvAQKbbCYtdC8E/KtR4V5ZTSScr5Wb63vmbw7UpddEXYvl55pARyyvMxWNSh3Li4GF8Jk5JBi5B5ASQwxCMYpX5hkAMc+d8tl2bT+IEvUTsAAAElQZoQSeEPJlMCK/8AJIAzFZs00JJ0yfm8CZiew4xWdArLklEvBVXo/+ukPLu3XP9HFOfsme3T6BJEKmPPgZw/Lxnraq6Sl2kLVW19YU1qmqgfv+80LkZaWU5gRAH4hqyo3bFYcbuY2SC3IW5Wm69gtYyAXOdbAYSEHA16fvCeRQjHEsxKVndJdrRAlrGHsKgUBQ3Up/ZXIy1vkdFOfKSjpuZnswkuqr8NZI5tJ/dnBSErBTNWPaNwWV7nNomC0EYVGo+geGBhLXzaLw0UAOCYGjiPc3803BDw1GLoLIXjrIFJxwRfBNIAXYZAglu30oYzhpAfRWSprkeULMWYJTlWvbUQ5CNewSZssuDWIRAc3w8AcFaywwn+YSGhtR8VI1OGjYkfBbcAAAD8QZoxSeEPJlMCK/8AJdokjCUETRw/nciVPtaZQSBP/VxAQSITASEzlJBl9Na1r0DJhLOz279+KQLtl/xHZ8vAKc528mTMTqtWs4sFbeVgHWyBpHcHEtgTzjIqEinp/MPuUXF5poo8YLSSMFn9Ozx2FbU5/Kh9A39oN9NHQflVxV1NA6yT/84HHyfMtfdSMS8KTvAEE2lDs14VQayNs5ctjXboQT7xMBf5OLj6thhPvgaDrFB2o/PV9ouK147lruWTP2mkoA9oDIMYW1pcBx4yyV/t9GOPZ3aXneMUb2fFmUCX43BjXfUDMaa4GO2/Ankj3UEQwDxA7ZlNUQK2AAAA4UGaUknhDyZTAiv/ACJHv33I08bkhybYiJ/JiiheW5zMPBu4n5CxGr3frhE7TkLh0vPktM8m/AhaDiJisdk5QXNe/4WmxEDSAyaVi4eUVu0iHT2ly/KNTGqiORqA2oKpTjh84nYbrpXwnGv9SOf/34Z06xN6Yo3t35UZrP8nlcs/63GtnEmnUwVZHBYfPM6bs5M5AeBfAQ/9mIqu7vnEst+5O2wpPjzdItjwGCZ2ApHVjGnYYFomlA9nm6AXnxNIWHIsDgxCk3zx+6QbXipu/CWLG1Wf0WIbt4C0JPVl3TEb0QAAAMlBmnNJ4Q8mUwIr/wAVV64OfTKmlktYOqZHH1W1DhPy/X/6sD4T6hRdzfOgNtTOX2IckRJHshfBQVkJIzns079io6kpJFCcS3VD4zrWCn/dNaGV0kWTpFBRuusfn8F0C0R/EhsQeyTsdZftEkLGb5tq+nrir3vfmeb7rjmWJRXkIrTEKu8pIuAd+4FBGp8ARgGe80Jqpp//s1433HqBFqXsIFJTmU8j/toF9HyueI1Ea4uvsQ6NANGcYCbOAKCmbNiwABMCFaiUTMAAAAPSbW9vdgAAAGxtdmhkAAAAAHwlsIB8JbCAAAAD6AAAAyAAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAv10cmFrAAAAXHRraGQAAAAPfCWwgHwlsIAAAAABAAAAAAAAAyAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAY4AAAGGAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAMgAAAAAgABAAAAAAJ1bWRpYQAAACBtZGhkAAAAAHwlsIB8JbCAAAAAGQAAABRVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAACIG1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAeBzdGJsAAAAtHN0c2QAAAAAAAAAAQAAAKRhdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAY4BhgBIAAAASAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGP//AAAAMmF2Y0MBZAAV/+EAGWdkABWs2UGQz6mhAAADAAEAAAMAMg8WLZYBAAZo6+PLIsAAAAAcdXVpZGtoQPJfJE/FujmlG88DI/MAAAAAAAAAGHN0dHMAAAAAAAAAAQAAABQAAAABAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAYY3R0cwAAAAAAAAABAAAAFAAAAAIAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAZHN0c3oAAAAAAAAAAAAAABQAAA05AAACqQAAAl8AAAITAAACiwAAAh8AAAIvAAABiAAAAVsAAAE5AAABWwAAAUQAAAFmAAAA/QAAAUEAAAEaAAABKQAAAQAAAADlAAAAzQAAAGBzdGNvAAAAAAAAABQAAAAsAAANZQAAEA4AABJtAAAUgAAAFwsAABkqAAAbWQAAHOEAAB48AAAfdQAAINAAACIUAAAjegAAJHcAACW4AAAm0gAAJ/sAACj7AAAp4AAAAGF1ZHRhAAAAWW1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAALGlsc3QAAAAkqXRvbwAAABxkYXRhAAAAAQAAAABMYXZmNTIuMTExLjA=\">\n\n\n\n## External sites\n\nYou can even embed an entire page from another site in an iframe; for example this is today's Wikipedia\npage for mobile users:\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('https://jupyter.org', width='100%', height=350)\n```\n\n\n\n\n\n\n\n\n\n\n## Links to local files\n\nIPython provides builtin display classes for generating links to local files. Create a link to a single file using the `FileLink` object:\n\n\n```python\nfrom IPython.display import FileLink, FileLinks\nFileLink('Cell Magics.ipynb')\n```\n\n\n\n\n<a href='Cell Magics.ipynb' target='_blank'>Cell Magics.ipynb</a><br>\n\n\n\nAlternatively, to generate links to all of the files in a directory, use the `FileLinks` object, passing `'.'` to indicate that we want links generated for the current working directory. Note that if there were other directories under the current directory, `FileLinks` would work in a recursive manner creating links to files in all sub-directories as well.\n\n\n```python\nFileLinks('.')\n```\n\n\n\n\n./<br>\n&nbsp;&nbsp;<a href='./Animations Using clear_output.ipynb' target='_blank'>Animations Using clear_output.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Background Jobs.ipynb' target='_blank'>Background Jobs.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Beyond Plain Python.ipynb' target='_blank'>Beyond Plain Python.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Capturing Output.ipynb' target='_blank'>Capturing Output.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Cell Magics.ipynb' target='_blank'>Cell Magics.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Custom Display Logic.ipynb' target='_blank'>Custom Display Logic.ipynb</a><br>\n&nbsp;&nbsp;<a href='./example-demo.py' target='_blank'>example-demo.py</a><br>\n&nbsp;&nbsp;<a href='./foo.py' target='_blank'>foo.py</a><br>\n&nbsp;&nbsp;<a href='./Index.ipynb' target='_blank'>Index.ipynb</a><br>\n&nbsp;&nbsp;<a href='./ipython-completion.bash' target='_blank'>ipython-completion.bash</a><br>\n&nbsp;&nbsp;<a href='./ipython-get-history.py' target='_blank'>ipython-get-history.py</a><br>\n&nbsp;&nbsp;<a href='./ipython-qtconsole.desktop' target='_blank'>ipython-qtconsole.desktop</a><br>\n&nbsp;&nbsp;<a href='./ipython.desktop' target='_blank'>ipython.desktop</a><br>\n&nbsp;&nbsp;<a href='./mod.py' target='_blank'>mod.py</a><br>\n&nbsp;&nbsp;<a href='./Plotting in the Notebook.ipynb' target='_blank'>Plotting in the Notebook.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Raw Input in the Notebook.ipynb' target='_blank'>Raw Input in the Notebook.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Rich Output.ipynb' target='_blank'>Rich Output.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Script Magics.ipynb' target='_blank'>Script Magics.ipynb</a><br>\n&nbsp;&nbsp;<a href='./SymPy.ipynb' target='_blank'>SymPy.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Terminal Usage.ipynb' target='_blank'>Terminal Usage.ipynb</a><br>\n&nbsp;&nbsp;<a href='./test.txt' target='_blank'>test.txt</a><br>\n&nbsp;&nbsp;<a href='./Third Party Rich Output.ipynb' target='_blank'>Third Party Rich Output.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Trapezoid Rule.ipynb' target='_blank'>Trapezoid Rule.ipynb</a><br>\n&nbsp;&nbsp;<a href='./Working With External Code.ipynb' target='_blank'>Working With External Code.ipynb</a><br>\n./.ipynb_checkpoints/<br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Animations Using clear_output-checkpoint.ipynb' target='_blank'>Animations Using clear_output-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Background Jobs-checkpoint.ipynb' target='_blank'>Background Jobs-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Beyond Plain Python-checkpoint.ipynb' target='_blank'>Beyond Plain Python-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Capturing Output-checkpoint.ipynb' target='_blank'>Capturing Output-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Cell Magics-checkpoint.ipynb' target='_blank'>Cell Magics-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Custom Display Logic-checkpoint.ipynb' target='_blank'>Custom Display Logic-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Index-checkpoint.ipynb' target='_blank'>Index-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Plotting in the Notebook-checkpoint.ipynb' target='_blank'>Plotting in the Notebook-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Raw Input in the Notebook-checkpoint.ipynb' target='_blank'>Raw Input in the Notebook-checkpoint.ipynb</a><br>\n&nbsp;&nbsp;<a href='./.ipynb_checkpoints/Rich Output-checkpoint.ipynb' target='_blank'>Rich Output-checkpoint.ipynb</a><br>\n./__pycache__/<br>\n&nbsp;&nbsp;<a href='./__pycache__/mod.cpython-34.pyc' target='_blank'>mod.cpython-34.pyc</a><br>\n./data/<br>\n&nbsp;&nbsp;<a href='./data/flare.json' target='_blank'>flare.json</a><br>\n./gui/<br>\n&nbsp;&nbsp;<a href='./gui/gui-glut.py' target='_blank'>gui-glut.py</a><br>\n&nbsp;&nbsp;<a href='./gui/gui-gtk.py' target='_blank'>gui-gtk.py</a><br>\n&nbsp;&nbsp;<a href='./gui/gui-gtk3.py' target='_blank'>gui-gtk3.py</a><br>\n&nbsp;&nbsp;<a href='./gui/gui-pyglet.py' target='_blank'>gui-pyglet.py</a><br>\n&nbsp;&nbsp;<a href='./gui/gui-qt.py' target='_blank'>gui-qt.py</a><br>\n&nbsp;&nbsp;<a href='./gui/gui-tk.py' target='_blank'>gui-tk.py</a><br>\n&nbsp;&nbsp;<a href='./gui/gui-wx.py' target='_blank'>gui-wx.py</a><br>\n\n\n\n## Rich output and security\n\nThe IPython Notebook allows arbitrary code execution in both the IPython kernel and in the browser, though HTML and JavaScript output. More importantly, because IPython has a JavaScript API for running code in the browser, HTML and JavaScript output can actually trigger code to be run in the kernel. This poses a significant security risk as it would allow IPython Notebooks to execute arbitrary code on your computers.\n\nTo protect against these risks, the IPython Notebook has a security model that specifies how dangerous output is handled. Here is a short summary:\n\n* When you run code in the Notebook, all rich output is displayed.\n* When you open a notebook, rich output is only displayed if it doesn't contain security vulberabilities, ...\n* ... or if you have trusted a notebook, all rich output will run upon opening it.\n\nA full description of the IPython security model can be found on [this page](https://ipython.org/ipython-doc/dev/notebook/security.html).\n\n## Rich output and nbviewer\n\nMuch of the power of the Notebook is that it enables users to share notebooks with each other using http://nbviewer.ipython.org, without installing IPython locally. As of IPython 2.0, notebooks rendered on nbviewer will display all output, including HTML and JavaScript. Furthermore, to provide a consistent JavaScript environment on the live Notebook and nbviewer, the following JavaScript libraries are loaded onto the nbviewer page, *before* the notebook and its output is displayed:\n\n* [jQuery](http://jquery.com/)\n* [RequireJS](http://requirejs.org/)\n\nLibraries such as [mpld3](http://mpld3.github.io/) use these capabilities to generate interactive visualizations that work on nbviewer.\n", "meta": {"hexsha": "5e1d6cd006db8eabb3bf7fb63adb3c07d7183c72", "size": 281827, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/Rich Output.ipynb", "max_stars_repo_name": "qiaoyafeng/learn-jupyter", "max_stars_repo_head_hexsha": "74fd341cb94c114157f896eb7e1e353d4663f79a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/Rich Output.ipynb", "max_issues_repo_name": "qiaoyafeng/learn-jupyter", "max_issues_repo_head_hexsha": "74fd341cb94c114157f896eb7e1e353d4663f79a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/Rich Output.ipynb", "max_forks_repo_name": "qiaoyafeng/learn-jupyter", "max_forks_repo_head_hexsha": "74fd341cb94c114157f896eb7e1e353d4663f79a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 182.5304404145, "max_line_length": 120083, "alphanum_fraction": 0.8836591242, "converted": true, "num_tokens": 62531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09947020854296806, "lm_q2_score": 0.06371499514089998, "lm_q1q2_score": 0.006337743853979518}}
{"text": "##### Copyright 2020 The Cirq Developers\n\n\n```\n#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# Notebook template\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n  <td>\n    <a target=\"_blank\" href=\"https://www.example.org/cirq/tutorials/google/colab\">View on QuantumLib</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/Cirq/blob/master/docs/tutorials/google/colab.ipynb\">Run in Google Colab</a>\n  </td>\n  <td>\n    <a target=\"_blank\" href=\"https://github.com/quantumlib/Cirq/blob/master/docs/tutorials/google/colab.ipynb\">View source on GitHub</a>\n  </td>\n  <td>\n    <a href=\"https://storage.googleapis.com/tensorflow_docs/Cirq/docs/tutorials/google/colab.ipynb\">Download notebook</a>\n  </td>\n</table>\n\n\n```\ntry:\n    import cirq\nexcept ImportError:\n    print(\"installing cirq...\")\n    !pip install --quiet cirq\n    print(\"installed cirq.\")\n```\n\n## Make a copy of this template\n\nYou will need to have access to Quantum Computing Service before running this colab.\n\nThis notebook can serve as a starter kit for you to run programs on Google's quantum hardware.  You can download it using the directions below, open it in colab (or Jupyter), and modify it to begin your experiments.\n\n## How to download iPython notebooks from GitHub\n\nYou can retrieve iPython notebooks in the Cirq repository by\ngoing to the [docs/ directory](https://github.com/quantumlib/Cirq/tree/master/docs).  For instance, this Colab template is found [here](https://github.com/quantumlib/Cirq/blob/master/docs/tutorials/google/colab.ipynb). Select the file that you would like to download and then click the *Raw* button in the upper-right part of the window:\n\n\n\nThis will show the entire file contents.  Right-click and select *Save as* to save this file to your computer.  Make sure to save to a file with a `.ipynb` extension (you may need to select *All files* from the format dropdown instead of *text*). You can also get to this Colab's [raw content directly](https://raw.githubusercontent.com/quantumlib/Cirq/master/docs/tutorials/google/colab.ipynb)\n\nYou can also retrieve the entire Cirq repository by running the following command in a terminal that has `git` installed:\n\n```\ngit checkout https://github.com/quantumlib/Cirq.git\n```\n\n## How to open Google Colab\n\nYou can open a new Colab notebook from your Google Drive window or by visiting the [Colab site](https://colab.research.google.com/notebooks/intro.ipynb).  From the Colaboratory site, you can use the menu to upload an iPython notebook:\n\n\n\nThis will upload the ipynb file that you downloaded before.  You can now run all the commands, modify it to suit your goals, and share it with others.\n\n### More Documentation Links\n\n* [Quantum Engine concepts](../../google/concepts.md)\n* [Quantum Engine documentation](../../google/engine.md)\n* [Cirq documentation](https://cirq.readthedocs.io)\n* [Colab documentation](https://colab.research.google.com/notebooks/welcome.ipynb)\n\n\n## Authenticate and install Cirq\n\nFor details of authentication and installation, please see [go/quantum-engine-quickstart](http://go/quantum-engine-quickstart). \n\nNote:  The below code will install the latest stable release of cirq.  If you need the latest and greatest features and don't mind if a few things aren't quite working correctly, you can install `cirq-unstable` instead of `cirq` to get the most up-to-date features of cirq.\n\n1. Enter the Cloud project ID you'd like to use in the `project_id` field.\n2. Then run the cell below (and go through the auth flow for access to the project id you entered).\n\n\n\n\n```\n# The Google Cloud Project id to use.\nproject_id = '' #@param {type:\"string\"}\n\nif project_id == '':\n    raise Exception(\"Please setup project_id in this cell!\")\n\ndef setup_auth():\n  \"\"\"Runs the user through the Colab OAuth process.\n  \n  Sets the local Application Default Credentials. For more information on on \n  using Application Default Credentials see \n  https://cloud.google.com/docs/authentication/production\n  \"\"\"\n  from google.colab import auth\n  auth.authenticate_user(clear_output=False)\n\nprint(\"Getting OAuth2 credentials.\")\nprint(\"Press enter after entering the verification code.\")\nsetup_auth()\nprint(\"Authentication complete.\")\n```\n\n    Getting OAuth2 credentials.\n    Press enter after entering the verification code.\n    Authentication complete.\n    Requirement already satisfied: cirq in /usr/local/lib/python3.6/dist-packages (0.8.2)\n    Requirement already satisfied: freezegun~=0.3.15 in /usr/local/lib/python3.6/dist-packages (from cirq) (0.3.15)\n    Requirement already satisfied: google-api-core[grpc]<2.0.0dev,>=1.14.0 in /usr/local/lib/python3.6/dist-packages (from cirq) (1.16.0)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.6/dist-packages (from cirq) (3.7.4.3)\n    Requirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from cirq) (0.7)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.6/dist-packages (from cirq) (1.1.1)\n    Requirement already satisfied: networkx~=2.4 in /usr/local/lib/python3.6/dist-packages (from cirq) (2.5)\n    Requirement already satisfied: protobuf~=3.12.0 in /usr/local/lib/python3.6/dist-packages (from cirq) (3.12.4)\n    Requirement already satisfied: sortedcontainers~=2.0 in /usr/local/lib/python3.6/dist-packages (from cirq) (2.2.2)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from cirq) (1.4.1)\n    Requirement already satisfied: numpy~=1.16 in /usr/local/lib/python3.6/dist-packages (from cirq) (1.18.5)\n    Requirement already satisfied: requests~=2.18 in /usr/local/lib/python3.6/dist-packages (from cirq) (2.23.0)\n    Requirement already satisfied: matplotlib~=3.0 in /usr/local/lib/python3.6/dist-packages (from cirq) (3.2.2)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from cirq) (1.0.5)\n    Requirement already satisfied: python-dateutil!=2.0,>=1.0 in /usr/local/lib/python3.6/dist-packages (from freezegun~=0.3.15->cirq) (2.8.1)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from freezegun~=0.3.15->cirq) (1.15.0)\n    Requirement already satisfied: setuptools>=34.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (49.6.0)\n    Requirement already satisfied: pytz in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (2018.9)\n    Requirement already satisfied: googleapis-common-protos<2.0dev,>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (1.52.0)\n    Requirement already satisfied: google-auth<2.0dev,>=0.4.0 in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (1.17.2)\n    Requirement already satisfied: grpcio<2.0dev,>=1.8.2; extra == \"grpc\" in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (1.31.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy->cirq) (1.1.0)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx~=2.4->cirq) (4.4.2)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (2.10)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (1.24.3)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq) (2020.6.20)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq) (0.10.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq) (2.4.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq) (1.2.0)\n    Requirement already satisfied: rsa<5,>=3.1.4; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from google-auth<2.0dev,>=0.4.0->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (4.6)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth<2.0dev,>=0.4.0->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (4.1.1)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.6/dist-packages (from google-auth<2.0dev,>=0.4.0->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (0.2.8)\n    Requirement already satisfied: pyasn1>=0.1.3 in /usr/local/lib/python3.6/dist-packages (from rsa<5,>=3.1.4; python_version >= \"3\"->google-auth<2.0dev,>=0.4.0->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq) (0.4.8)\n    Cirq installed.\n\n\n## Create an Engine variable\n\nThe following creates and engine variable which can be used to run programs under the project ID you entered above.\n\n\n```\nimport cirq\n\n# Create an Engine object to use, providing the project id and the args\n# used for authentication (produced by running the authentication above).\nengine = cirq.google.Engine(project_id=project_id)\n```\n\n## Example\n\n\n```\n# A simple example.\nq = cirq.GridQubit(5, 2)\ncircuit = cirq.Circuit(cirq.X(q)**0.5, cirq.measure(q, key='m'))\n\njob = engine.run_sweep(\n    program=circuit,\n    repetitions=10000,\n    processor_ids=['rainbow'],\n    gate_set=cirq.google.SYC_GATESET)\n\nresults = [str(int(b)) for b in job.results()[0].measurements['m'][:, 0]]\nprint('Success!  Results:')\nprint(''.join(results))\n```\n\n    Success!  Results:\n    0000001111010100111111000100000000011100001000000011110011101011101101100000101000000110010110011100001001000110001110100101010010101100011010110000010001011001111001111001110011111001100011110110001001101010000000000111101101010110101010011011011111110010111010000010001000101110101100111111111101110100100100000011110010010000110111100111010010101111010001111100011100100101010011111011100000000100100001001100110001000101000011010101010111110001000000011100100000001011011111111001001011000001100110101000000001100110000111000100110101110111101010100110001101001000010110011001011010000111111000111010101111100101100001011101100101000110001100001100010001001001110010000010001011111101101101111011101101100010110001000111001010101001011111011111100011001110001110010111000011010011101101000011100111011000001001010101010010001101011010101011001001010001000111100101000011000101011011110111011101001011001001011011001101111010010011110010011101011011010111001110110101010101010101010001100101000001000101101001010000101110101011011111101010001011111010111110011101111111010100000001100000001100100011001011110111011111110011101010111000011101100111111101100001111100001110100100001010011001110111010000011101110011010001111011110101010011010111011001000101111010000110000111010111110001101011010010100010111111100001011111000001010000001001101100110011001100001000101101001100101011101100011011000111100111000001001100001110100010110011101001111101011000100111010001111001111000110000101001000100010110110001011111001100110101110001110110101101010001010101110100100110100000101101000101010011000110101010101011110111011111110010111011111100000001000000011110101010100111110000010001000101000111011001100100011001101101010000101010001100000001010001110110000000000111100110000010101100001000101110101100010110000010101000110110100010110101001001010010001010111010001001100000000011101110110010111100000000010011001010010010111111010100001011010100101001001110101100000001011001100011100111110011001101111000001001101111100111010100111111101000011100100110111010100010010000001101111111100101111101000101101010000010010100000100111000000110101111101000101001010010001111101000000001011011000111110001111100111010000110000100000110010101110011010100110010010111111010101100101101001111001001000000000100011111000101101001011010110010100100000011001111100111101111111011010110010000111001000110000011001111111010010010100110000011100101011001000111011010101000001011100010001011001111001101000111011000110110001001110010000010111010110100100110000010011101001000100010010011100000010010110100100011011010111000110110110000001001011000000000100111000101110010110001111001001111001011011110010110010101010001100010101000100000110111010111001111000111000010000100101011001001100111100011111000001010110011110111000101000010000110011010110110101110100000101011011001011001110011001001101010001000000111110000101100001100101000110000011110001110000101001001100010101010000000100101100001101001111001001101000010100001011110011100000100000000100010101100111101100011101101010100010110000101010011011101011010100110111100110011001011001000110100001000100010111011011110111011011110100010010011100001011001111001010111000000010110110100001010111010000111110101000000110101100110001010001101110101001110100110110110011111100111101111111001010011011001101111000000110110111110111000010001011001011011010110000000010010100101000110110000100011011010011110100010101101101001001001100001100001011000110011011011110100100000010001011011111000010110010111010011110011110010000101111011100010010011101011110000101010010000011001110101111000001011110010111110001110110100101001001100000011001010010100011101001100110111000001011111011010000111100010111100000011000110001111010100000111000101100000011100100101111100101111100111011110100110011100011110100111010000010111000110100011001000010011100101111010010100110100100011101100111001100101111111110101101001010111100000110010000111100010100100110001010000010011101110111010110010100000110001111100001001000100001010001010110101110110110111100101110001110010010001010110000001000101010111110001100011111011100010110111011000000010101110111101100110000010000000010100111110011000010000001010101111010100000110001001011000010101111100001111110001101100011110110010010110011110110010001011100010010000000010000101010010111101001010101011001011110100000101111100111010010110010001110001010101000111001101110011100000010101101011000100010110011011011111100010110111110100111111101100001100000000000101000101011100111000000100110000010110110010001111000011000101110000010101110011011000010111110111110101101000000100000110101010001000100100000010000101010000011010001000001111001001010011101101001001100100101011111011010100101010001011110111110011101100001010111111110110111010000011111100001101101000010111010000110001111000101110010110110101110000100000111101001101100111100000110100011101101111011111010010001110010011011110101101100100001001000110100110110001010111011101101100101101000111001000110111101000000001011000100110100010011001000111110010101110010010011011011011001111110010000111011011101010001011011000011010111011100001011000111100101000011010101010010001000010000100001000101100111111111110000111110010011001000110110111010000000110110100100111101101011001111110011010100000111000100100110110000000001110110010000010100010100101001000001101101100101001111101000111100001111110011110001000110000011011100100110100000010111011011000000011000000001011101010110100111101001101100100001111000011101110011001111111011101011000100010011001101010100110000001100111000001011001010110100111001101111101101000100111110001111100001110010110000000100101011010111001001100011101110111011100111011111111111111010010101100111111100101011101101011011010111110011011110111011111100110101010000000000101111000010100100100000100001110011010011001001110111111110001101010001010000010110111111111011010000110101001010111111110110111000111011000101100001000011010111010010000111110110100110010111000011011100000110011000110100011111100110000101101111101001100101001010101001011111100010110110000100110111110010111100011010110000011001100111010010000111111011000010110100111111101000101101100110000001010011000011111101010000000010011101101101111000101100010100001100011011100001101111101011101010110001110000101011011100010100110011001100110001100001101001000000010101100001000000110101110111000110100100101000001110110111001000001101100011011000010101110011100001111000011101011001011010100001101101011111001000101001011101000010111011000101011101110110100011110111101110110011101111010111010111001001101110001011000100011101000111000001000000100100000101000100001001010101110111010010011000100000010000111101011000010100100111001111101111011001110101000000100001111111000111100100011101111111000001111111101100000110010001110110001111010100010000000010000010101010010101000001001000000011001101100001110111010001000101011001010000000100111101001111010010001011011101011011011101110100000110110001100001010010111000111010010011110010001001010001001000011110000001000001111001101001111011011100010110010010101000001011000000100000101000111110010001000100000000110111100001011100010011100001011100110100001000010101101010100001000000100100010101001000101110110111010111111000110000100010000011110100100111010100000011111101010110100110110100001000001001001010101011010101011110011111000011000000111101110100000100101111100111110110000100110100000011111110111110100001011010111010000100101010101110001100100101000101101101001011101010101100111001001101001000110101111111001111011110101011101001110100000010010001101101100000010110000011001100001110110010100000000011110111100000100001101011001100110110000001001000001101111001101101111001110011101101101010001101100110111110011110010001000110110010100100010100111000000100010111011100100110100100110111000110001010010000110000001101000010100011101110010110101100001101001101000000100100010000010000011110110101100000011110010101010010001100110101001100101000101100010101001010000111000111000000000001001100100110001111000110100001000000010001110011011001110000011001000011101010011110000101001101111100110000111110101111111111101011100101011001001010101101001100110110111000111110111011101000011001100101010111101100111010001001000001011001101101111110001001111111111110001000100011100101100110110101101100110110010110011111001101001011011111110001011110110000100010000101011110011001000100010100011101111100010011011010011100111110111000111100110000010011100111011100011001011001101101011001000001001010011101111010000101011010100011010011001111011010001111010010111001111000001000001111100100010110001000100011011110001010011101000110000100110010111110111110011000101001000111000001100001110010000011100010001111100011001110011100001100011010010000001000001100010100100110101001101110011001001010100011010110011111010101100111110010011100101101111001110001011001000101101100111010000100111101010101010100001100011001101011111111110010001111100111001001110010101100111001010000001000100000111101110111001110111100100110101000110000001100000101001010001111000001110110100000011100011011100011011100101010100110011111110110011110100100111100110110100111010100001011101010001000010011010011101010001010101000100011111110001010000000100100111101110100000100100110100000101001111011011011110011111101001011100010111110110100011001100000101000110100101101011001010111100000000111010101011101110101100100101001001111010001111100101010011011000101000111100010010010000001111001001100011110001000110011010110110100100111011100111010110111010110011010101010111100110000101101111101110010001010011000010111001110110000100100101010001001010110110001001001011001000010100111100010110110101000111100110010110001010010010000110010101111000010001100111010100010111100110000000010001101001011100110001011000100101000011101000010110100001110011010101111011101111110110011111111000111010010010100010011100100100100011111111011111110100110001100110\n\n", "meta": {"hexsha": "909baa2d0a4fb404dcbc1a8ce1c474eb8837cf7d", "size": 24491, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/google/colab.ipynb", "max_stars_repo_name": "lilies/Cirq", "max_stars_repo_head_hexsha": "519b8b70ba4d2d92d1c034c398161ebdbd23e2e7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-06T17:06:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-06T17:06:10.000Z", "max_issues_repo_path": "docs/tutorials/google/colab.ipynb", "max_issues_repo_name": "lilies/Cirq", "max_issues_repo_head_hexsha": "519b8b70ba4d2d92d1c034c398161ebdbd23e2e7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/tutorials/google/colab.ipynb", "max_forks_repo_name": "lilies/Cirq", "max_forks_repo_head_hexsha": "519b8b70ba4d2d92d1c034c398161ebdbd23e2e7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-14T15:29:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T15:29:29.000Z", "avg_line_length": 77.9968152866, "max_line_length": 10010, "alphanum_fraction": 0.7836756359, "converted": true, "num_tokens": 6299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05749328203023058, "lm_q2_score": 0.10818895887524603, "lm_q1q2_score": 0.006220138325171538}}
{"text": "# Homework 3\n### Due Date:  Tuesday, September 20th at 11:59 PM\n\n---\n## Problem 1:  `Git` and recovering from a mistake\nYou will do this problem in the Jupyter notebook so I can see your output.  Once again, you will work with your playground repository.\n\n**NOTE:** At the beginning of each cell, you MUST type `%%bash`.  If you don't do that then you will not be able to work with the necessary bash commands.\n\nFollow the following steps for this problem:\n\n1. First cell:\n  1. Type `cd /tmp` to enter the temporary directory\n  2. git clone url_to_your_playground_repo\n2. Second cell:\n  1. Go into your local `playground` directory (`cd /tmp/playground`)\n  2. Type `git pull origin mybranch1`\n  3. `ls`\n3. Third cell:\n  1. Go into your local `playground` directory (`cd /tmp/playground`)\n  2. Type `git status`\n4. Fourth cell:\n  1. Go into your local `playground` directory (`cd /tmp/playground`)\n  2. Type `git reset --hard origin/master`\n  3. `ls`\n5. Fifth cell:\n  1. Go into your local `playground` directory (`cd /tmp/playground`)\n  2. Type `git status`\n\nThe whole point of this problem was to show you how to get your local repo back to an earlier state.  In this exercise, you accidentally merged something to `master` that you didn't want.  Rather than starting to delete things all over the place, you can simply reset your `HEAD` to a previous commit.\n\n\n```bash\n%%bash\ncd /tmp\nrm -rf playground #remove if it exists\ngit clone https://github.com/syj19950301/playground.git\n```\n\n    Cloning into 'playground'...\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit pull origin mybranch1\nls\n```\n\n    Merge made by the 'recursive' strategy.\n     books.md | 1 +\n     1 file changed, 1 insertion(+)\n     create mode 100644 books.md\n    README.md\n    books.md\n    feature.txt\n    intro.md\n    world.md\n\n\n    From https://github.com/syj19950301/playground\n     * branch            mybranch1  -> FETCH_HEAD\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit status\n```\n\n    On branch master\n    Your branch is ahead of 'origin/master' by 2 commits.\n      (use \"git push\" to publish your local commits)\n    nothing to commit, working directory clean\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit reset --hard origin/master\nls\n```\n\n    HEAD is now at 07a6807 HW3 Problem 2 practice\n    README.md\n    feature.txt\n    intro.md\n    world.md\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit status\n```\n\n    On branch master\n    Your branch is up-to-date with 'origin/master'.\n    nothing to commit, working directory clean\n\n\n## Problem 2:  `Git` and checking out a single file\nSometimes you don't want to merge an entire branch from the upstream but just one file from it. There is a direct use case for such a situation. Suppose I've made an error in this homework (or a lecture) and want to correct it. I fix the mistake in the upstream repo. In the meantime you have edited some other files and you really don't want to manually ignore my older copies of those files. Rather, you want to fix just one file from this new branch. This is how you do it.\n\nAs usual, be sure to type in `%%bash` before you write any `bash` commands in a cell.\n\n**Note:** The steps below assume that you have already cloned the `playground` repo in this notebook.\n\n1. First cell:\n  1. Go into the `playground` repo and fetch the changes from the master branch of the `course` remote.\n2. Second cell:\n  1. `git checkout course/master -- README.md`.  The `--` means that `README.md` is a file (as opposed to a `branch`).\n  2. `cat README.md`.  This just looks at the updated file.\n3. Third cell:\n  1. `git status`\n  2. Commit the changes to your local repo with an appropriate commit message.\n  3. `git status`\n  4. Push the changes to your remote repo.\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit remote add course https://github.com/IACS-CS-207/playground.git\ngit fetch course\n```\n\n    From https://github.com/IACS-CS-207/playground\n     * [new branch]      master     -> course/master\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit checkout course/master -- README.md\ncat README.md\n```\n\n    # Playground Repo\n    \n    For practicing.\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit status\ngit add README.md\ngit commit -m \"HW3 Problem 2 practice\"\ngit push\n```\n\n    On branch master\n    Your branch is up-to-date with 'origin/master'.\n    nothing to commit, working directory clean\n    On branch master\n    Your branch is up-to-date with 'origin/master'.\n    nothing to commit, working directory clean\n\n\n    warning: push.default is unset; its implicit value has changed in\n    Git 2.0 from 'matching' to 'simple'. To squelch this message\n    and maintain the traditional behavior, use:\n    \n      git config --global push.default matching\n    \n    To squelch this message and adopt the new behavior now, use:\n    \n      git config --global push.default simple\n    \n    When push.default is set to 'matching', git will push local branches\n    to the remote branches that already exist with the same name.\n    \n    Since Git 2.0, Git defaults to the more conservative 'simple'\n    behavior, which only pushes the current branch to the corresponding\n    remote branch that 'git pull' uses to update the current branch.\n    \n    See 'git help config' and search for 'push.default' for further information.\n    (the 'simple' mode was introduced in Git 1.7.11. Use the similar mode\n    'current' instead of 'simple' if you sometimes use older versions of Git)\n    \n    Everything up-to-date\n\n\n## Problem 3\nThis problem is related to the Lecture 4 exercises.\n1. Open the `languages.txt` file.  This file contains all the languages that students listed as their primary language in the course survey.\n2. Load the language strings from the file into a list.\n3. Use the `Counter` method from the `collections` library to count the number of occurrences of each element of the list.\n  + **NOTE:**  It is not necessary to use the `most_common()` method here.\n4. Create a bar plot to display the frequency of each language.  Be sure to label the x-axis!\n  + Remember, to create plots in the notebook you must put the line `%matplotlib inline` at the beginning of your notebook.\n  + Be sure to import matplotlib:  `import matplotlib.pyplot as plt`.\n  + To generate the bar plot write `plt.bar(x_coords, freqs)`.  You need to define `x_coords` and `freqs`.\n  + **Hint:** You may want to use the `numpy` `arange` function to create `x_coords`.  Remember, `x_coords` is the x-axis and it should have points for each distinct language.\n  + **Hint:** To get `freqs`, you may want to use the `values()` method on your result from step 3.  That is, `freqs = result_from_3.values()`.\n  + **Hint:** To label the x-axis you should use `plt.xticks(x_coords, labels)` where labels can be accessed through the `keys()` method on your result from step 3.\n\n\n```python\nimport collections\nimport numpy as np\nimport os\n# cwd = os.getcwd()\n# print(cwd)\nf = open(\"/Users/shenyijun/Desktop/GitHub/cs207_yijun_shen/lectures/L4/languages.txt\", \"r\")\nlanguages = f.read()\nf.close()\n```\n\n\n```python\nlanguages_list = languages.split('\\n')[:-1]\nprint(languages_list)\n```\n\n    ['Python', 'C++', 'Java', 'Python', 'Python', 'Python', 'Python', 'C++', 'Python', 'C', 'Other', 'Python', 'Python', 'Python', 'C++', 'Other', 'Python', 'Python', 'Python', 'Java', 'Python', 'Python', 'C#', 'Python', 'SQL', 'C++', 'C++', 'Python', 'Java', 'Java', 'Java', 'Python', 'Python', 'Python', 'SQL', 'Java', 'Python', 'Python', 'C++', 'Java', 'Python', 'Python', 'VB', 'Python', 'Python']\n\n\n\n```python\nlanguages_counter = collections.Counter(languages_list)\nprint(languages_counter)\n```\n\n    Counter({'Python': 25, 'Java': 7, 'C++': 6, 'Other': 2, 'SQL': 2, 'C': 1, 'C#': 1, 'VB': 1})\n\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfreqs = languages_counter.values()\nx_coords = np.arange(1,9)\nplt.bar(x_coords,freqs)\nlabels = languages_counter.keys()\nplt.xticks(x_coords,labels)\n```\n\n---\n## Problem 4\nIn chemical kinetics, the reaction rate coefficient for a given reaction depends on the temperature of the system.  The functional relationship between the reaction rate coefficient and temperature is given by the Arrhenius rate:\n\\begin{align}\nk\\left(T\\right) = A T^{b}\\exp\\left(-\\frac{E}{RT}\\right)\n\\end{align}\nwhere $A$, $b$, and $E$ are parameters, $R = 8.314 \\dfrac{\\textrm{J}}{\\textrm{mol} \\textrm{ K}}$  is the universal gas constant, and $T$ is the temperature.\n\nWrite a function which returns $k\\left(T\\right)$ given $A$, $b$, $E$, and $T$.  Here are a few requirements:\n* The function should test for exceptions where necessary.\n* Pass the parameters $A$, $b$, and $E$ in as a list.\n* Make $R$ a keyword argument to the function.\n\n\n```python\nimport math\ndef reaction_rate(AbE, T, R=8.314):\n    if T <= 0:\n        print(\"Warning: Temperature must be greater than zero\")\n    else:\n        return AbE[0]*(T**AbE[1])*(math.exp(AbE[2]/(R*T)))\n```\n\n# ---\n## Problem 5\nUsing `numpy` arrays, plot $k\\left(T\\right)$ for $T\\in\\left(0, 5000\\right]$ for three different sets of parameters $\\left\\{A, b, E\\right\\}$.  Make sure all three lines are on the same figure and be sure to label each line.  You may use the function from Problem 2.  You may want to play with the parameters a little bit to get some nice curves but you won't lose points for ugly curves either (as long as they're correct!).\n\n\n```python\ncase1 = [1, 1, 3]\ncase2 = [2, 0.1, 5]\ncase3 = [10, 0.5, 10]\n```\n\n\n```python\nT_coords = np.array(range(1,5001))\nk1 = np.array([0] * T_coords.shape[0])\nk2 = np.array([0] * T_coords.shape[0])\nk3 = np.array([0] * T_coords.shape[0])\nfor i in T_coords:\n    k1[i-1] = (reaction_rate(case1, i))\n    k2[i-1] = (reaction_rate(case2, i))\n    k3[i-1] = (reaction_rate(case3, i))\n\nplt.ylabel(\"Reaction Coefficient Rate\")\nplt.xlabel(\"Temperature\")\nplt.plot(T_coords,k1, label=\"case1\")\nplt.plot(T_coords,k2, label=\"case2\")\nplt.plot(T_coords,k3, label=\"case3\")\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "13efbc3c041d0de207831ac8db94d71c6cba1ca6", "size": 43029, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "homeworks/HW3/HW3-final.ipynb", "max_stars_repo_name": "syj19950301/cs207_yijun_shen", "max_stars_repo_head_hexsha": "410d6ce1ee7ad684be0eee6a635b5697b561daf7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/HW3/HW3-final.ipynb", "max_issues_repo_name": "syj19950301/cs207_yijun_shen", "max_issues_repo_head_hexsha": "410d6ce1ee7ad684be0eee6a635b5697b561daf7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/HW3/HW3-final.ipynb", "max_forks_repo_name": "syj19950301/cs207_yijun_shen", "max_forks_repo_head_hexsha": "410d6ce1ee7ad684be0eee6a635b5697b561daf7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 81.8041825095, "max_line_length": 20944, "alphanum_fraction": 0.806618792, "converted": true, "num_tokens": 2747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06371499780770398, "lm_q2_score": 0.09670579329612157, "lm_q1q2_score": 0.00616160940785466}}
{"text": "## *Descripci\u00f3n e instrucciones*\n\nLa implementaci\u00f3n est\u00e1 dise\u00f1ada para ser ejecutada desde google colab, pero puede ejecutarse de forma local siempre que se tengan instalados los requisitos preestablecidos.\n\nEs necesario establecer un conjunto de directorios para interacturar con las funciones. Ya que al segmentar o aplicar filtros, los resultados se guardan en distintas carpetas y se leen por el siguiente m\u00e9todo correspondiente. Se aplicaron dos preprocesos para un mejor control en la calidad de la salida.\n\nHay que adaptar estos directorios a las rutas adecuadas seg\u00fan el usuario que utilice el notebook.\n\nLos directorios necesarios son:\n\n- *im_dir*: contiene las im\u00e1genes a procesar. \n- *imagenes_segmentadas*: contiene las im\u00e1genes despu\u00e9s de extraer las regiones que contienen texto\n- *imagenes_Preproceso1*: contiene las im\u00e1genes despu\u00e9s de aplicar un primer preproceso\n- *imagenes_Preproceso2*: contiene las im\u00e1genes despu\u00e9s de aplicar un segundo preproceso\n- *archivos_texto*: contiene los archivos de texto de las transcripciones obtenidas\n\nPor otra parte, se debe especificar las rutas de acceso a los archivos .csv que contienen informaci\u00f3n sobre las transcripciones (para medir la calidad de la extracci\u00f3n) y las entidades conocidas.\n\n- *JusticIA_DatosTranscripciones.csv*\n- *civilservants.csv*\n- *organizations.csv*\n- *places.csv*\n- *prosecuted.csv*\n\n# Instalaci\u00f3n de librerias necesarias \nEstas librerias se mencionan en el archivo `requirements.txt`. \n\n**NOTA:** Si se usa colab, se debe reiniciar el entorno de ejecuci\u00f3n despu\u00e9s de la instalaci\u00f3n.\n\n\n```python\n# Pre-requisitos para instalar Kraken\n!pip uninstall tensorflow -y\n!pip install  tensorflow==2.3.1\n!pip uninstall Keras -y\n!pip install Keras==2.2.4\n!pip uninstall scikit-learn -y\n!pip install scikit-learn==0.19.2\n!pip uninstall scikit-image -y\n!pip install scikit-image==0.18.2\n\n#Kraken para segmentaci\u00f3n de im\u00e1genes\n!pip install kraken\n\n#paquetes necesarios en linux para usar tesseract\n! apt install tesseract-ocr\n! apt install libtesseract-dev\n\n\n#bibliotecas para python\n\n#Extracci\u00f3n de texto\n! pip install pytesseract\n# Manipular im\u00e1genes\n! pip install Pillow\n! pip install opencv-python\n\n#Indentificaci\u00f3n de entidades\n!pip install rapidfuzz\n#Indentificaci\u00f3n de fechas\n!pip install datefinder\n#Para evaaluaci\u00f3n de la calidad de la extracci\u00f3n\n!pip install python-Levenshtein\n\n```\n\n    Found existing installation: tensorflow 2.6.0\n    Uninstalling tensorflow-2.6.0:\n      Successfully uninstalled tensorflow-2.6.0\n    Collecting tensorflow==2.3.1\n      Downloading tensorflow-2.3.1-cp37-cp37m-manylinux2010_x86_64.whl (320.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 320.4 MB 24 kB/s \n    \u001b[?25hRequirement already satisfied: protobuf>=3.9.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (3.17.3)\n    Requirement already satisfied: google-pasta>=0.1.8 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (0.2.0)\n    Collecting h5py<2.11.0,>=2.10.0\n      Downloading h5py-2.10.0-cp37-cp37m-manylinux1_x86_64.whl (2.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.9 MB 43.3 MB/s \n    \u001b[?25hRequirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (1.1.0)\n    Collecting numpy<1.19.0,>=1.16.0\n      Downloading numpy-1.18.5-cp37-cp37m-manylinux1_x86_64.whl (20.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 20.1 MB 1.3 MB/s \n    \u001b[?25hRequirement already satisfied: keras-preprocessing<1.2,>=1.1.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (1.1.2)\n    Requirement already satisfied: astunparse==1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (1.6.3)\n    Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (3.3.0)\n    Requirement already satisfied: tensorboard<3,>=2.3.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (2.6.0)\n    Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (1.39.0)\n    Collecting tensorflow-estimator<2.4.0,>=2.3.0\n      Downloading tensorflow_estimator-2.3.0-py2.py3-none-any.whl (459 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 459 kB 57.2 MB/s \n    \u001b[?25hRequirement already satisfied: six>=1.12.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (1.15.0)\n    Collecting gast==0.3.3\n      Downloading gast-0.3.3-py2.py3-none-any.whl (9.7 kB)\n    Requirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (0.37.0)\n    Requirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (0.12.0)\n    Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow==2.3.1) (1.12.1)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.1) (0.4.5)\n    Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.1) (0.6.1)\n    Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.1) (57.4.0)\n    Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.1) (1.34.0)\n    Requirement already satisfied: requests<3,>=2.21.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.1) (2.23.0)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.1) (1.8.0)\n    Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.1) (1.0.1)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard<3,>=2.3.0->tensorflow==2.3.1) (3.3.4)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (4.2.2)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (0.2.8)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (4.7.2)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (1.3.0)\n    Requirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from markdown>=2.6.8->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (4.6.4)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (0.4.8)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (2021.5.30)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (3.0.4)\n    Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (3.1.1)\n    Requirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->markdown>=2.6.8->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (3.7.4.3)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->markdown>=2.6.8->tensorboard<3,>=2.3.0->tensorflow==2.3.1) (3.5.0)\n    Installing collected packages: numpy, tensorflow-estimator, h5py, gast, tensorflow\n      Attempting uninstall: numpy\n        Found existing installation: numpy 1.19.5\n        Uninstalling numpy-1.19.5:\n          Successfully uninstalled numpy-1.19.5\n      Attempting uninstall: tensorflow-estimator\n        Found existing installation: tensorflow-estimator 2.6.0\n        Uninstalling tensorflow-estimator-2.6.0:\n          Successfully uninstalled tensorflow-estimator-2.6.0\n      Attempting uninstall: h5py\n        Found existing installation: h5py 3.1.0\n        Uninstalling h5py-3.1.0:\n          Successfully uninstalled h5py-3.1.0\n      Attempting uninstall: gast\n        Found existing installation: gast 0.4.0\n        Uninstalling gast-0.4.0:\n          Successfully uninstalled gast-0.4.0\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    datascience 0.10.6 requires folium==0.2.1, but you have folium 0.8.3 which is incompatible.\n    albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Successfully installed gast-0.3.3 h5py-2.10.0 numpy-1.18.5 tensorflow-2.3.1 tensorflow-estimator-2.3.0\n\n\n\n\n    Found existing installation: keras 2.6.0\n    Uninstalling keras-2.6.0:\n      Successfully uninstalled keras-2.6.0\n    Collecting Keras==2.2.4\n      Downloading Keras-2.2.4-py2.py3-none-any.whl (312 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 312 kB 5.0 MB/s \n    \u001b[?25hCollecting keras-applications>=1.0.6\n      Downloading Keras_Applications-1.0.8-py3-none-any.whl (50 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 50 kB 5.7 MB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.9.1 in /usr/local/lib/python3.7/dist-packages (from Keras==2.2.4) (1.18.5)\n    Requirement already satisfied: six>=1.9.0 in /usr/local/lib/python3.7/dist-packages (from Keras==2.2.4) (1.15.0)\n    Requirement already satisfied: scipy>=0.14 in /usr/local/lib/python3.7/dist-packages (from Keras==2.2.4) (1.4.1)\n    Requirement already satisfied: keras-preprocessing>=1.0.5 in /usr/local/lib/python3.7/dist-packages (from Keras==2.2.4) (1.1.2)\n    Requirement already satisfied: pyyaml in /usr/local/lib/python3.7/dist-packages (from Keras==2.2.4) (3.13)\n    Requirement already satisfied: h5py in /usr/local/lib/python3.7/dist-packages (from Keras==2.2.4) (2.10.0)\n    Installing collected packages: keras-applications, Keras\n    Successfully installed Keras-2.2.4 keras-applications-1.0.8\n    Found existing installation: scikit-learn 0.22.2.post1\n    Uninstalling scikit-learn-0.22.2.post1:\n      Successfully uninstalled scikit-learn-0.22.2.post1\n    Collecting scikit-learn==0.19.2\n      Downloading scikit_learn-0.19.2-cp37-cp37m-manylinux1_x86_64.whl (4.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4.9 MB 5.2 MB/s \n    \u001b[?25hInstalling collected packages: scikit-learn\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    yellowbrick 0.9.1 requires scikit-learn>=0.20, but you have scikit-learn 0.19.2 which is incompatible.\n    imbalanced-learn 0.4.3 requires scikit-learn>=0.20, but you have scikit-learn 0.19.2 which is incompatible.\u001b[0m\n    Successfully installed scikit-learn-0.19.2\n    Found existing installation: scikit-image 0.16.2\n    Uninstalling scikit-image-0.16.2:\n      Successfully uninstalled scikit-image-0.16.2\n    Collecting scikit-image==0.18.2\n      Downloading scikit_image-0.18.2-cp37-cp37m-manylinux1_x86_64.whl (29.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 29.2 MB 49 kB/s \n    \u001b[?25hRequirement already satisfied: tifffile>=2019.7.26 in /usr/local/lib/python3.7/dist-packages (from scikit-image==0.18.2) (2021.8.8)\n    Requirement already satisfied: networkx>=2.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image==0.18.2) (2.6.2)\n    Requirement already satisfied: numpy>=1.16.5 in /usr/local/lib/python3.7/dist-packages (from scikit-image==0.18.2) (1.18.5)\n    Requirement already satisfied: matplotlib!=3.0.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image==0.18.2) (3.2.2)\n    Requirement already satisfied: pillow!=7.1.0,!=7.1.1,>=4.3.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image==0.18.2) (7.1.2)\n    Requirement already satisfied: scipy>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from scikit-image==0.18.2) (1.4.1)\n    Requirement already satisfied: PyWavelets>=1.1.1 in /usr/local/lib/python3.7/dist-packages (from scikit-image==0.18.2) (1.1.1)\n    Requirement already satisfied: imageio>=2.3.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image==0.18.2) (2.4.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib!=3.0.0,>=2.0.0->scikit-image==0.18.2) (0.10.0)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib!=3.0.0,>=2.0.0->scikit-image==0.18.2) (2.8.2)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib!=3.0.0,>=2.0.0->scikit-image==0.18.2) (2.4.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib!=3.0.0,>=2.0.0->scikit-image==0.18.2) (1.3.1)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from cycler>=0.10->matplotlib!=3.0.0,>=2.0.0->scikit-image==0.18.2) (1.15.0)\n    Installing collected packages: scikit-image\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Successfully installed scikit-image-0.18.2\n    Collecting kraken\n      Downloading kraken-3.0.4-py3-none-any.whl (5.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5.4 MB 5.0 MB/s \n    \u001b[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from kraken) (1.18.5)\n    Collecting python-bidi\n      Downloading python_bidi-0.4.2-py2.py3-none-any.whl (30 kB)\n    Requirement already satisfied: protobuf>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from kraken) (3.17.3)\n    Collecting torch<=1.7.0,>=1.5.0\n      Downloading torch-1.7.0-cp37-cp37m-manylinux1_x86_64.whl (776.7 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 776.7 MB 3.6 kB/s \n    \u001b[?25hRequirement already satisfied: shapely in /usr/local/lib/python3.7/dist-packages (from kraken) (1.7.1)\n    Collecting coremltools>=3.3\n      Downloading coremltools-4.1-cp37-none-manylinux1_x86_64.whl (3.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.4 MB 39.8 MB/s \n    \u001b[?25hRequirement already satisfied: jsonschema in /usr/local/lib/python3.7/dist-packages (from kraken) (2.6.0)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from kraken) (0.16.0)\n    Requirement already satisfied: jinja2 in /usr/local/lib/python3.7/dist-packages (from kraken) (2.11.3)\n    Requirement already satisfied: click>=7.0 in /usr/local/lib/python3.7/dist-packages (from kraken) (7.1.2)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from kraken) (1.4.1)\n    Requirement already satisfied: Pillow>=6.2.2 in /usr/local/lib/python3.7/dist-packages (from kraken) (7.1.2)\n    Collecting scikit-image<=0.17.2\n      Downloading scikit_image-0.17.2-cp37-cp37m-manylinux1_x86_64.whl (12.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 12.5 MB 14 kB/s \n    \u001b[?25hRequirement already satisfied: torchvision>=0.5.0 in /usr/local/lib/python3.7/dist-packages (from kraken) (0.10.0+cu102)\n    Requirement already satisfied: regex in /usr/local/lib/python3.7/dist-packages (from kraken) (2019.12.20)\n    Collecting pyvips\n      Downloading pyvips-2.1.15.tar.gz (622 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 622 kB 59.8 MB/s \n    \u001b[?25hRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from kraken) (2.23.0)\n    Requirement already satisfied: lxml in /usr/local/lib/python3.7/dist-packages (from kraken) (4.2.6)\n    Requirement already satisfied: attrs in /usr/local/lib/python3.7/dist-packages (from coremltools>=3.3->kraken) (21.2.0)\n    Collecting attr\n      Downloading attr-0.3.1.tar.gz (1.7 kB)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from coremltools>=3.3->kraken) (4.62.0)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from coremltools>=3.3->kraken) (1.7.1)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from coremltools>=3.3->kraken) (21.0)\n    Requirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.7/dist-packages (from coremltools>=3.3->kraken) (1.15.0)\n    Requirement already satisfied: imageio>=2.3.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image<=0.17.2->kraken) (2.4.1)\n    Requirement already satisfied: PyWavelets>=1.1.1 in /usr/local/lib/python3.7/dist-packages (from scikit-image<=0.17.2->kraken) (1.1.1)\n    Requirement already satisfied: matplotlib!=3.0.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image<=0.17.2->kraken) (3.2.2)\n    Requirement already satisfied: networkx>=2.0 in /usr/local/lib/python3.7/dist-packages (from scikit-image<=0.17.2->kraken) (2.6.2)\n    Requirement already satisfied: tifffile>=2019.7.26 in /usr/local/lib/python3.7/dist-packages (from scikit-image<=0.17.2->kraken) (2021.8.8)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib!=3.0.0,>=2.0.0->scikit-image<=0.17.2->kraken) (0.10.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib!=3.0.0,>=2.0.0->scikit-image<=0.17.2->kraken) (2.4.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib!=3.0.0,>=2.0.0->scikit-image<=0.17.2->kraken) (1.3.1)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib!=3.0.0,>=2.0.0->scikit-image<=0.17.2->kraken) (2.8.2)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch<=1.7.0,>=1.5.0->kraken) (3.7.4.3)\n    Collecting dataclasses\n      Downloading dataclasses-0.6-py3-none-any.whl (14 kB)\n    Collecting torchvision>=0.5.0\n      Downloading torchvision-0.10.0-cp37-cp37m-manylinux1_x86_64.whl (22.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 22.1 MB 1.3 MB/s \n    \u001b[?25h  Downloading torchvision-0.9.1-cp37-cp37m-manylinux1_x86_64.whl (17.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 17.4 MB 106 kB/s \n    \u001b[?25h  Downloading torchvision-0.9.0-cp37-cp37m-manylinux1_x86_64.whl (17.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 17.3 MB 23 kB/s \n    \u001b[?25h  Downloading torchvision-0.8.2-cp37-cp37m-manylinux1_x86_64.whl (12.8 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 12.8 MB 22 kB/s \n    \u001b[?25h  Downloading torchvision-0.8.1-cp37-cp37m-manylinux1_x86_64.whl (12.7 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 12.7 MB 82 kB/s \n    \u001b[?25hRequirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2->kraken) (2.0.1)\n    Requirement already satisfied: cffi>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from pyvips->kraken) (1.14.6)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.0.0->pyvips->kraken) (2.20)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->kraken) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->kraken) (2.10)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->kraken) (1.24.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->kraken) (2021.5.30)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->coremltools>=3.3->kraken) (1.2.1)\n    Building wheels for collected packages: attr, pyvips\n      Building wheel for attr (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for attr: filename=attr-0.3.1-py3-none-any.whl size=2457 sha256=ab211245f0e610f6b6bf30d14a8e9569ce019a1affe71887c7c0d1cf83798762\n      Stored in directory: /root/.cache/pip/wheels/3b/5d/58/41fbe92f47031641008bd8559ee89e58bf0f123f9c18dea1cb\n      Building wheel for pyvips (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pyvips: filename=pyvips-2.1.15-py2.py3-none-any.whl size=47219 sha256=8cdcf4fcb17d83a5a1ca4e3d8efde0534d043b2b92c52223d293885a80aace8d\n      Stored in directory: /root/.cache/pip/wheels/58/56/33/e5defc8dfdc135f6fb198e5035bbca9bebb95776e28746a09f\n    Successfully built attr pyvips\n    Installing collected packages: dataclasses, torch, attr, torchvision, scikit-image, pyvips, python-bidi, coremltools, kraken\n      Attempting uninstall: torch\n        Found existing installation: torch 1.9.0+cu102\n        Uninstalling torch-1.9.0+cu102:\n          Successfully uninstalled torch-1.9.0+cu102\n      Attempting uninstall: torchvision\n        Found existing installation: torchvision 0.10.0+cu102\n        Uninstalling torchvision-0.10.0+cu102:\n          Successfully uninstalled torchvision-0.10.0+cu102\n      Attempting uninstall: scikit-image\n        Found existing installation: scikit-image 0.18.2\n        Uninstalling scikit-image-0.18.2:\n          Successfully uninstalled scikit-image-0.18.2\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    torchtext 0.10.0 requires torch==1.9.0, but you have torch 1.7.0 which is incompatible.\n    albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Successfully installed attr-0.3.1 coremltools-4.1 dataclasses-0.6 kraken-3.0.4 python-bidi-0.4.2 pyvips-2.1.15 scikit-image-0.17.2 torch-1.7.0 torchvision-0.8.1\n    Reading package lists... Done\n    Building dependency tree       \n    Reading state information... Done\n    The following package was automatically installed and is no longer required:\n      libnvidia-common-460\n    Use 'apt autoremove' to remove it.\n    The following additional packages will be installed:\n      tesseract-ocr-eng tesseract-ocr-osd\n    The following NEW packages will be installed:\n      tesseract-ocr tesseract-ocr-eng tesseract-ocr-osd\n    0 upgraded, 3 newly installed, 0 to remove and 40 not upgraded.\n    Need to get 4,795 kB of archives.\n    After this operation, 15.8 MB of additional disk space will be used.\n    Get:1 http://archive.ubuntu.com/ubuntu bionic/universe amd64 tesseract-ocr-eng all 4.00~git24-0e00fe6-1.2 [1,588 kB]\n    Get:2 http://archive.ubuntu.com/ubuntu bionic/universe amd64 tesseract-ocr-osd all 4.00~git24-0e00fe6-1.2 [2,989 kB]\n    Get:3 http://archive.ubuntu.com/ubuntu bionic/universe amd64 tesseract-ocr amd64 4.00~git2288-10f4998a-2 [218 kB]\n    Fetched 4,795 kB in 1s (4,328 kB/s)\n    Selecting previously unselected package tesseract-ocr-eng.\n    (Reading database ... 148486 files and directories currently installed.)\n    Preparing to unpack .../tesseract-ocr-eng_4.00~git24-0e00fe6-1.2_all.deb ...\n    Unpacking tesseract-ocr-eng (4.00~git24-0e00fe6-1.2) ...\n    Selecting previously unselected package tesseract-ocr-osd.\n    Preparing to unpack .../tesseract-ocr-osd_4.00~git24-0e00fe6-1.2_all.deb ...\n    Unpacking tesseract-ocr-osd (4.00~git24-0e00fe6-1.2) ...\n    Selecting previously unselected package tesseract-ocr.\n    Preparing to unpack .../tesseract-ocr_4.00~git2288-10f4998a-2_amd64.deb ...\n    Unpacking tesseract-ocr (4.00~git2288-10f4998a-2) ...\n    Setting up tesseract-ocr-osd (4.00~git24-0e00fe6-1.2) ...\n    Setting up tesseract-ocr-eng (4.00~git24-0e00fe6-1.2) ...\n    Setting up tesseract-ocr (4.00~git2288-10f4998a-2) ...\n    Processing triggers for man-db (2.8.3-2ubuntu0.1) ...\n    Reading package lists... Done\n    Building dependency tree       \n    Reading state information... Done\n    The following package was automatically installed and is no longer required:\n      libnvidia-common-460\n    Use 'apt autoremove' to remove it.\n    The following additional packages will be installed:\n      libleptonica-dev\n    The following NEW packages will be installed:\n      libleptonica-dev libtesseract-dev\n    0 upgraded, 2 newly installed, 0 to remove and 40 not upgraded.\n    Need to get 2,755 kB of archives.\n    After this operation, 13.8 MB of additional disk space will be used.\n    Get:1 http://archive.ubuntu.com/ubuntu bionic/universe amd64 libleptonica-dev amd64 1.75.3-3 [1,308 kB]\n    Get:2 http://archive.ubuntu.com/ubuntu bionic/universe amd64 libtesseract-dev amd64 4.00~git2288-10f4998a-2 [1,447 kB]\n    Fetched 2,755 kB in 1s (2,567 kB/s)\n    Selecting previously unselected package libleptonica-dev.\n    (Reading database ... 148533 files and directories currently installed.)\n    Preparing to unpack .../libleptonica-dev_1.75.3-3_amd64.deb ...\n    Unpacking libleptonica-dev (1.75.3-3) ...\n    Selecting previously unselected package libtesseract-dev.\n    Preparing to unpack .../libtesseract-dev_4.00~git2288-10f4998a-2_amd64.deb ...\n    Unpacking libtesseract-dev (4.00~git2288-10f4998a-2) ...\n    Setting up libleptonica-dev (1.75.3-3) ...\n    Setting up libtesseract-dev (4.00~git2288-10f4998a-2) ...\n    Collecting pytesseract\n      Downloading pytesseract-0.3.8.tar.gz (14 kB)\n    Requirement already satisfied: Pillow in /usr/local/lib/python3.7/dist-packages (from pytesseract) (7.1.2)\n    Building wheels for collected packages: pytesseract\n      Building wheel for pytesseract (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pytesseract: filename=pytesseract-0.3.8-py2.py3-none-any.whl size=14072 sha256=d67fcbe6ae47ede18bf52f61c89827b6d78ed2cc8c4bbad49586958da0ddc5b9\n      Stored in directory: /root/.cache/pip/wheels/a4/89/b9/3f11250225d0f90e5454fcc30fd1b7208db226850715aa9ace\n    Successfully built pytesseract\n    Installing collected packages: pytesseract\n    Successfully installed pytesseract-0.3.8\n    Requirement already satisfied: Pillow in /usr/local/lib/python3.7/dist-packages (7.1.2)\n    Requirement already satisfied: opencv-python in /usr/local/lib/python3.7/dist-packages (4.1.2.30)\n    Requirement already satisfied: numpy>=1.14.5 in /usr/local/lib/python3.7/dist-packages (from opencv-python) (1.18.5)\n    Collecting rapidfuzz\n      Downloading rapidfuzz-1.5.0-cp37-cp37m-manylinux2010_x86_64.whl (1.4 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.4 MB 4.7 MB/s \n    \u001b[?25hInstalling collected packages: rapidfuzz\n    Successfully installed rapidfuzz-1.5.0\n    Collecting datefinder\n      Downloading datefinder-0.7.1-py2.py3-none-any.whl (10 kB)\n    Requirement already satisfied: python-dateutil>=2.4.2 in /usr/local/lib/python3.7/dist-packages (from datefinder) (2.8.2)\n    Requirement already satisfied: regex>=2017.02.08 in /usr/local/lib/python3.7/dist-packages (from datefinder) (2019.12.20)\n    Requirement already satisfied: pytz in /usr/local/lib/python3.7/dist-packages (from datefinder) (2018.9)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.4.2->datefinder) (1.15.0)\n    Installing collected packages: datefinder\n    Successfully installed datefinder-0.7.1\n    Collecting python-Levenshtein\n      Downloading python-Levenshtein-0.12.2.tar.gz (50 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 50 kB 3.1 MB/s \n    \u001b[?25hRequirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from python-Levenshtein) (57.4.0)\n    Building wheels for collected packages: python-Levenshtein\n      Building wheel for python-Levenshtein (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for python-Levenshtein: filename=python_Levenshtein-0.12.2-cp37-cp37m-linux_x86_64.whl size=149862 sha256=a23a3973d90db6537bcb2f832f0d9935288692444ed9e70b3f2d2291f6c07e46\n      Stored in directory: /root/.cache/pip/wheels/05/5f/ca/7c4367734892581bb5ff896f15027a932c551080b2abd3e00d\n    Successfully built python-Levenshtein\n    Installing collected packages: python-Levenshtein\n    Successfully installed python-Levenshtein-0.12.2\n\n\n# Montando en colab las carpetas necesarias\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```python\n! git clone https://github.com/Hackaton-JusticIA-2021/gato-encerrado-Hackathon-RIIAA-2021\n```\n\n    Cloning into 'gato-encerrado-Hackathon-RIIAA-2021'...\n    remote: Enumerating objects: 328, done.\u001b[K\n    remote: Counting objects: 100% (328/328), done.\u001b[K\n    remote: Compressing objects: 100% (314/314), done.\u001b[K\n    remote: Total 328 (delta 122), reused 18 (delta 5), pack-reused 0\u001b[K\n    Receiving objects: 100% (328/328), 128.10 MiB | 21.41 MiB/s, done.\n    Resolving deltas: 100% (122/122), done.\n\n\n\n```python\nimport importlib\n\n# se cargan los modulos desde sus rutas\nspec = importlib.util.spec_from_file_location(\"extraccion_texto\", \"/content/gato-encerrado-Hackathon-RIIAA-2021/modules/extraccion_texto.py\")\nextraccion_texto = importlib.util.module_from_spec(spec)\nspec.loader.exec_module(extraccion_texto)\n\nspec = importlib.util.spec_from_file_location(\"fuzzy_search\", \"/content/gato-encerrado-Hackathon-RIIAA-2021/modules/fuzzy_search.py\")\nfuzzy_search = importlib.util.module_from_spec(spec)\nspec.loader.exec_module(fuzzy_search)\n\nspec = importlib.util.spec_from_file_location(\"proceso_imagen\", \"/content/gato-encerrado-Hackathon-RIIAA-2021/modules/preproceso_imagen.py\")\npreproceso_imagen = importlib.util.module_from_spec(spec)\nspec.loader.exec_module(preproceso_imagen)\n```\n\nClonamos el repositorio de Github para poder acceder a las librerias creadas en python.\n\n**Nota**: Las carpetas se guardan en drive de forma temporal.\n\nAcceso a las im\u00e1genes que vamos a procesar.\n\n\n```python\nin_dir='/content/gato-encerrado-Hackathon-RIIAA-2021/Evaluacion/Reto2'\n```\n\nSi no existen las carpetas se crean usando pathlib.\n\n\n```python\n#nombre de carpetas\n\n#carpeta donde guardamos imagenes_bloques\nimagenes_segmentadas = '/content/drive/My Drive/Hackaton/Hackathon RIIAA 2021 (CNB)/Implementacion/ImagenesSegmentadas'\n#carpeta donde guardamos primer preproceso\nimagenes_Preproceso1 = '/content/drive/My Drive/Hackaton/Hackathon RIIAA 2021 (CNB)/Implementacion/Preproceso1'\n#carpeta donde guardamos segundo preproceso\nimagenes_Preproceso2 = '/content/drive/My Drive/Hackaton/Hackathon RIIAA 2021 (CNB)/Implementacion/Preproceso2'\n#carpeta donde guardamos los archivos de texto\narchivos_texto = '/content/drive/My Drive/Hackaton/Hackathon RIIAA 2021 (CNB)/Implementacion/TextFiles'\n#Carpeta donde guradaremos la base de datos resultante\noutput_dir = '/content/drive/My Drive/Hackaton/Hackathon RIIAA 2021 (CNB)/Implementacion/extraccion.csv'\n```\n\n\n```python\nfrom pathlib import Path\nPath(imagenes_segmentadas).mkdir(parents=True, exist_ok=True)\nPath(imagenes_Preproceso1).mkdir(parents=True, exist_ok=True)\nPath(imagenes_Preproceso2).mkdir(parents=True, exist_ok=True)\nPath(archivos_texto).mkdir(parents=True, exist_ok=True)\n```\n\n# Pipeline para extracci\u00f3n de texto sobre imagenes de evaluaci\u00f3n.\n\nEn este bloque de c\u00f3digo se realiza el preproceso y ectracci\u00f3n de texto a las imagenes del conjunto de evaluaci\u00f3n.\n\n\n```python\nimport pandas as pd\nimport os \n\nfiles_0=os.listdir(in_dir)\n  \nfiles=[]\nfor file in files_0:\n  if file[-4:]=='.JPG':\n    files.append(file)\n\nresultado={}\nfor i,file in enumerate(files):\n    name=str(Path(in_dir)/file)\n    output_path=preproceso_imagen.segmentar_orientar(img_path=name,output_dir=imagenes_segmentadas)\n    output_path=preproceso_imagen.guardar_imagen(output_path, filtro=preproceso_imagen.pillow_image_detail, filtro_name=\"\", output_dir=imagenes_Preproceso1, pillow=True)\n    output_path=preproceso_imagen.guardar_imagen(output_path, filtro=preproceso_imagen.noise_removal, filtro_name=\"\", output_dir=imagenes_Preproceso2, pillow=False)\n    texto=extraccion_texto.guardar_texto(output_path,archivos_texto)\n    key=Path(name).name\n    resultado[key]=texto\n    print(i)\ndf_transcripciones=pd.DataFrame(resultado,index=['texto']).T\n\ndf_transcripciones.to_csv(output_dir)\nprint(df_transcripciones)\n\n```\n\n    Boundary tracing failed in baseline elongation: index 1 is out of bounds for axis 0 with size 1\n    Polygonizer failed on line 0: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 3 has 1 dimension(s)\n    Polygonizer failed on line 0: all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index 1 has 2 dimension(s)\n\n\n    0\n    1\n    2\n    3\n    4\n    5\n    6\n    7\n    8\n    9\n                                                                                                    texto\n    Ficheros_FAR,_concentrado_general_FAR,_concentr...                                                  \f\n    Ficheros_UAG_73-10-29_a_73-12-07_UAG,_fichas-13...  an eS et\\nOr Dic 43 LEF\\n\\n~30-Nov=73.8E1 dia ...\n    Ficheros_ACNR_militantes_Olea_Castaneyra_Rafel_...                                                  \f\n    Ficheros_Detenidos_Desaparecidos_Perez_Lopez_Ma...                                       LIZ / Aus\\n\f\n    Ficheros_Detenidos_Desaparecidos_Morales_Lopez_...  CMs\\n\u201cMORALES LOPEZ,D\u00e9lia bxp.l1=-235-75 ~\\npy...\n    Ficheros_PPUA_Fichas_PPUA,_Fichas-98-.JPG           Tambi\u00e9n se supo que el niimero telef\u00e9nico est4...\n    Ficheros_Represores_Martinez_Adame_Arturo_Marti...  GQ]\\nWI\\n&)\\n\u2014\\nMARTINEZ ADAME Arturo Lic Ex-1...\n    Ficheros_Brigada_Campesina_de_Ajusticiamiento_B...                                                  \f\n    Ficheros_UAG_76-11-16_a_77-03-19_UAG,_fichas-11...  VAC TX /o ro TL\\n\\n[Sng a\\n\\nron a conocer la ...\n    Ficheros_Union_Campesina_Independiente,_fichas_...  NT) DS CAMPUS DIOS INDEPSIDIEIES Uxp-l00-19-1-...\n\n\n# Evaluaci\u00f3n\nLa siguiente funci\u00f3n sirve para medir el desempe\u00f1o de la extracci\u00f3n de texto en relaci\u00f3n  con las transcripciones manuales. \nEs necesario especificar la direcci\u00f3n de la base de transcripciones.\nEvalua sobre una  muestras  aleatoria de im\u00e1genes de tama\u00f1o n.\nToma como par\u00e1metros de entrada los siguientes argumentos:\n\n#inputs:\n\n**main_root**: Ruta donde se encuentra el conjunto de im\u00e1genes sobre el que vamos a evaluar.\n\n**output_dir**: Ruta donde se gurad\u00e1n los archivos obtenidos.\n\n**df_root**: Ruta donde se encuentra nuetsra base de transcripciones.\n\n**n_samples**: Tama\u00f1o de la muestra sobre la que se va a evaluar el proceso.\n\n**psm**: Par\u00e1metro del extractor del texto.\n\n**random_state** Semilla para controlar el muestreo.\n\n# output:\n\nLa funci\u00f3n devuelve un n\u00famero entre 0 y 1, donde 0 corresponde a una transcripci\u00f3n perfecta (comparando con la transcripci\u00f3n etiquetada) y 1 una transcripci\u00f3n que no corresponde para nada con la real.\n\n**Nota:** La prueba que aqu\u00ed se presenta corresponde a la evaluaci\u00f3n de las transcripciones manuales.\n\n\n\n\n```python\nimport random \nfrom PIL import Image, ImageFilter\nfrom PIL import ImageEnhance\nfrom Levenshtein import distance\nimport pandas as pd\nimport numpy as np\n\ndef evalua(main_root,output_dir,df_root,n_samples=10,psm=6,random_state=0,):\n  #Leer base de transcripciones\n  df_transcripciones=pd.read_csv(df_root)\n  df_transcripciones.index=df_transcripciones.NombreArchivo\n  #carpeta donde guardamos imagenes_bloques\n  imagenes_segmentadas = str(Path(output_dir)/'ImagenesSegmentadas')\n  #carpeta donde guardamos primer preproceso\n  imagenes_Preproceso1 = str(Path(output_dir)/'Preproceso1')\n  #carpeta donde guardamos segundo preproceso\n  imagenes_Preproceso2 = str(Path(output_dir)/'Preproceso2')\n  #carpeta donde guardamos los archivos de texto\n  archivos_texto = str(Path(output_dir)/'ArchivosTexto')\n\n  Path(imagenes_segmentadas).mkdir(parents=True, exist_ok=True)\n  Path(imagenes_Preproceso1).mkdir(parents=True, exist_ok=True)\n  Path(imagenes_Preproceso2).mkdir(parents=True, exist_ok=True)\n  Path(archivos_texto).mkdir(parents=True, exist_ok=True)\n\n  files_0=os.listdir(main_root)\n  #Validamos que los archivos sean imagenes .JPG\n  files=[]\n  for file in files_0:\n    if file[-4:]=='.JPG':\n      files.append(file)\n  print('Por evaluar sobre ',len(files),' de ',len(files_0),' im\u00e1genes')\n\n  random.seed(random_state)\n  sub_set=random.choices(files,k=n_samples)\n  resultado={}\n  distances=[]\n  for i,file in enumerate(sub_set):\n    name=str(Path(main_root)/file)\n    #Pipeline de proceso\n    output_path=preproceso_imagen.segmentar_orientar(img_path=name,output_dir=imagenes_segmentadas)\n    output_path=preproceso_imagen.guardar_imagen(output_path, filtro=preproceso_imagen.pillow_image_detail, filtro_name=\"\", output_dir=imagenes_Preproceso1, pillow=True)\n    output_path=preproceso_imagen.guardar_imagen(output_path, filtro=preproceso_imagen.noise_removal, filtro_name=\"\", output_dir=imagenes_Preproceso2, pillow=False)\n    texto=extraccion_texto.guardar_texto(output_path,archivos_texto)\n    key=Path(name).name\n    resultado[key]=texto\n    #Texto real\n    try:\n      texto_real=df_transcripciones.loc[key]['Texto']\n      distances.append(distance(texto,texto_real)/len(texto_real))\n      print(i)\n    except:\n      print('Archivo no encontrado en la base de datos')\n  df=pd.DataFrame(resultado,index=['texto']).T\n  df.to_csv(str(Path(output_dir)/'valuate_data.csv'))\n  return np.mean(distances)\n```\n\n\n```python\nin_dir=\"/content/drive/My Drive/Hackathon RIIAA 2021 (CNB)/Datos - Hackathon JusticIA/Fichas_manual/\"\nsave_dir='/content/drive/My Drive/Hackaton/Hackathon RIIAA 2021 (CNB)/Implementacion/'\ndf_dir='/content/drive/My Drive/Hackathon RIIAA 2021 (CNB)/Datos - Hackathon JusticIA/JusticIA_DatosTranscripciones.csv'\n\nevalua(in_dir,save_dir,df_dir,n_samples=1)\n```\n\n    Por evaluar sobre  1000  de  1000  im\u00e1genes\n    0\n\n\n\n\n\n    0.07267441860465117\n\n\n\n#Pipeline para identificaci\u00f3n de entidades.\n\nLos siguientes bloques de c\u00f3digo corresponden al m\u00e9todo propuesto para el reto 2A que consiste en encontrar coincidencias de entidades (personas, lugares, fechas y organizaciones) en los textos obtenidos de las transcripciones de im\u00e1genes. \n\nPara correr esto se necesitan el m\u00f3dulo fuzzy_search de la carpeta de modulos del repositorio maestro. En este m\u00f3dulo se encuentran algunas funciones  que utilizan la distancia de Levenshtein para encontrar coincidencias entre cadenas de texto.\n\nEl objeto df_salida corresponde a la salida \n\n\n\n\n```python\nimport pandas as pd\nimport numpy as np\n\n### Si se quiere leer este dataframe del disco, descom\u00e9ntese la siguiente linea\n#df_transcripciones=pd.read_csv('/content/drive/MyDrive/Hackaton/Hackathon RIIAA 2021 (CNB)/Implementacion/extraccion.csv')\ndf_transcripciones.columns=['NombreArchivo','Texto']\n\n### Leyendo las listas de las organizaciones (Nota:Es importante que las listas tengan el mismo formato, es decir nombres de las columnas, con el que se nos proporcionaron al inicio)\norganizaciones = pd.read_csv(\"/content/gato-encerrado-Hackathon-RIIAA-2021/Evaluacion/organizations.csv\", error_bad_lines=False)\norganizaciones.columns = [\"Organizaci\u00f3n\"]\nlugares = pd.read_csv(\"/content/gato-encerrado-Hackathon-RIIAA-2021/Evaluacion/places.csv\", error_bad_lines=False).drop([\"PLACES \"],axis=1)\nlugares[\"Lugar\"] = lugares.index\nlugares = lugares.reset_index(drop=True)\nservidores = pd.read_csv(\"/content/gato-encerrado-Hackathon-RIIAA-2021/Evaluacion/civilservants.csv\", error_bad_lines=False)\nservidores.columns = [\"Servidor P\u00fablico\"]\nenjuiciados =  pd.read_csv(\"/content/gato-encerrado-Hackathon-RIIAA-2021/Evaluacion/prosecuted.csv\", error_bad_lines=False)\nenjuiciados.columns = [\"Enjuiciados\"]\n\n### Si se quiere hacer un muestreo sobre una peque\u00f1a muestra de las listas descomente la siguiente linea, si se quiere generar la base completa no haga nada.\n\n#listas = [organizaciones.loc[0:100],lugares.loc[0:100],servidores.loc[0:100],enjuiciados.loc[0:100]]\nlistas = [organizaciones,lugares,servidores,enjuiciados]\n\n## P\u00e1rametro para regular la rigidez de la b\u00fasqueda\nthreshold = 70\ndf_salida = fuzzy_search.obtener_matchs_df(df_transcripciones, listas,threshold ).sort_values(\"NombreArchivo\").append(fuzzy_search.obtener_df_expedientes_fechas(df_transcripciones)).sort_values('NombreArchivo').reset_index(drop=True)\ndf_salida.to_csv('/content/drive/My Drive/Hackaton/Hackathon RIIAA 2021 (CNB)/Implementacion/Entidades_identificadas.csv')\n\ndf_salida\n```\n\n    b'Skipping line 90: expected 1 fields, saw 3\\nSkipping line 108: expected 1 fields, saw 10\\nSkipping line 110: expected 1 fields, saw 3\\nSkipping line 113: expected 1 fields, saw 4\\nSkipping line 127: expected 1 fields, saw 3\\nSkipping line 195: expected 1 fields, saw 5\\nSkipping line 196: expected 1 fields, saw 2\\nSkipping line 199: expected 1 fields, saw 9\\nSkipping line 206: expected 1 fields, saw 8\\nSkipping line 251: expected 1 fields, saw 2\\nSkipping line 261: expected 1 fields, saw 2\\nSkipping line 381: expected 1 fields, saw 3\\nSkipping line 384: expected 1 fields, saw 2\\nSkipping line 401: expected 1 fields, saw 2\\nSkipping line 403: expected 1 fields, saw 2\\nSkipping line 408: expected 1 fields, saw 2\\nSkipping line 426: expected 1 fields, saw 4\\nSkipping line 439: expected 1 fields, saw 2\\nSkipping line 440: expected 1 fields, saw 2\\nSkipping line 445: expected 1 fields, saw 3\\nSkipping line 446: expected 1 fields, saw 2\\nSkipping line 449: expected 1 fields, saw 2\\nSkipping line 452: expected 1 fields, saw 2\\nSkipping line 455: expected 1 fields, saw 2\\nSkipping line 460: expected 1 fields, saw 2\\nSkipping line 477: expected 1 fields, saw 4\\nSkipping line 482: expected 1 fields, saw 2\\nSkipping line 504: expected 1 fields, saw 2\\nSkipping line 562: expected 1 fields, saw 2\\nSkipping line 600: expected 1 fields, saw 2\\nSkipping line 642: expected 1 fields, saw 2\\nSkipping line 659: expected 1 fields, saw 2\\nSkipping line 660: expected 1 fields, saw 3\\nSkipping line 661: expected 1 fields, saw 3\\nSkipping line 671: expected 1 fields, saw 3\\nSkipping line 677: expected 1 fields, saw 3\\nSkipping line 686: expected 1 fields, saw 2\\nSkipping line 687: expected 1 fields, saw 2\\nSkipping line 688: expected 1 fields, saw 2\\nSkipping line 689: expected 1 fields, saw 2\\nSkipping line 693: expected 1 fields, saw 2\\nSkipping line 696: expected 1 fields, saw 2\\nSkipping line 697: expected 1 fields, saw 2\\nSkipping line 699: expected 1 fields, saw 3\\nSkipping line 715: expected 1 fields, saw 2\\nSkipping line 723: expected 1 fields, saw 3\\nSkipping line 749: expected 1 fields, saw 4\\nSkipping line 750: expected 1 fields, saw 2\\nSkipping line 755: expected 1 fields, saw 2\\nSkipping line 757: expected 1 fields, saw 3\\nSkipping line 760: expected 1 fields, saw 3\\nSkipping line 787: expected 1 fields, saw 3\\nSkipping line 810: expected 1 fields, saw 3\\nSkipping line 812: expected 1 fields, saw 3\\nSkipping line 818: expected 1 fields, saw 3\\nSkipping line 852: expected 1 fields, saw 3\\nSkipping line 864: expected 1 fields, saw 3\\nSkipping line 885: expected 1 fields, saw 2\\nSkipping line 888: expected 1 fields, saw 2\\nSkipping line 900: expected 1 fields, saw 2\\nSkipping line 901: expected 1 fields, saw 2\\nSkipping line 916: expected 1 fields, saw 4\\nSkipping line 919: expected 1 fields, saw 2\\nSkipping line 920: expected 1 fields, saw 2\\nSkipping line 922: expected 1 fields, saw 2\\nSkipping line 939: expected 1 fields, saw 2\\nSkipping line 944: expected 1 fields, saw 2\\nSkipping line 947: expected 1 fields, saw 2\\nSkipping line 950: expected 1 fields, saw 2\\nSkipping line 951: expected 1 fields, saw 2\\nSkipping line 964: expected 1 fields, saw 2\\nSkipping line 967: expected 1 fields, saw 2\\nSkipping line 970: expected 1 fields, saw 4\\nSkipping line 971: expected 1 fields, saw 2\\nSkipping line 981: expected 1 fields, saw 3\\nSkipping line 982: expected 1 fields, saw 2\\nSkipping line 986: expected 1 fields, saw 2\\nSkipping line 1013: expected 1 fields, saw 3\\nSkipping line 1014: expected 1 fields, saw 2\\nSkipping line 1015: expected 1 fields, saw 2\\nSkipping line 1018: expected 1 fields, saw 2\\nSkipping line 1023: expected 1 fields, saw 2\\nSkipping line 1024: expected 1 fields, saw 2\\nSkipping line 1026: expected 1 fields, saw 2\\nSkipping line 1039: expected 1 fields, saw 6\\nSkipping line 1044: expected 1 fields, saw 3\\nSkipping line 1046: expected 1 fields, saw 2\\nSkipping line 1050: expected 1 fields, saw 2\\nSkipping line 1051: expected 1 fields, saw 6\\nSkipping line 1054: expected 1 fields, saw 2\\nSkipping line 1065: expected 1 fields, saw 2\\nSkipping line 1079: expected 1 fields, saw 2\\nSkipping line 1092: expected 1 fields, saw 4\\nSkipping line 1098: expected 1 fields, saw 2\\nSkipping line 1099: expected 1 fields, saw 2\\nSkipping line 1100: expected 1 fields, saw 2\\nSkipping line 1116: expected 1 fields, saw 2\\nSkipping line 1128: expected 1 fields, saw 2\\nSkipping line 1129: expected 1 fields, saw 2\\nSkipping line 1131: expected 1 fields, saw 2\\nSkipping line 1132: expected 1 fields, saw 2\\nSkipping line 1133: expected 1 fields, saw 2\\nSkipping line 1135: expected 1 fields, saw 2\\nSkipping line 1145: expected 1 fields, saw 2\\nSkipping line 1161: expected 1 fields, saw 2\\nSkipping line 1165: expected 1 fields, saw 2\\nSkipping line 1171: expected 1 fields, saw 3\\nSkipping line 1178: expected 1 fields, saw 3\\nSkipping line 1206: expected 1 fields, saw 2\\nSkipping line 1209: expected 1 fields, saw 2\\nSkipping line 1224: expected 1 fields, saw 2\\nSkipping line 1243: expected 1 fields, saw 2\\nSkipping line 1283: expected 1 fields, saw 2\\nSkipping line 1319: expected 1 fields, saw 2\\nSkipping line 1399: expected 1 fields, saw 2\\nSkipping line 1400: expected 1 fields, saw 2\\nSkipping line 1401: expected 1 fields, saw 2\\nSkipping line 1404: expected 1 fields, saw 3\\nSkipping line 1417: expected 1 fields, saw 2\\nSkipping line 1438: expected 1 fields, saw 2\\nSkipping line 1450: expected 1 fields, saw 2\\nSkipping line 1454: expected 1 fields, saw 2\\nSkipping line 1459: expected 1 fields, saw 2\\nSkipping line 1463: expected 1 fields, saw 2\\nSkipping line 1465: expected 1 fields, saw 2\\nSkipping line 1466: expected 1 fields, saw 2\\nSkipping line 1472: expected 1 fields, saw 2\\nSkipping line 1473: expected 1 fields, saw 2\\nSkipping line 1474: expected 1 fields, saw 3\\nSkipping line 1475: expected 1 fields, saw 2\\nSkipping line 1482: expected 1 fields, saw 2\\nSkipping line 1497: expected 1 fields, saw 2\\nSkipping line 1498: expected 1 fields, saw 2\\nSkipping line 1520: expected 1 fields, saw 4\\nSkipping line 1532: expected 1 fields, saw 2\\nSkipping line 1533: expected 1 fields, saw 4\\nSkipping line 1534: expected 1 fields, saw 3\\nSkipping line 1536: expected 1 fields, saw 2\\nSkipping line 1538: expected 1 fields, saw 2\\nSkipping line 1541: expected 1 fields, saw 2\\nSkipping line 1542: expected 1 fields, saw 2\\nSkipping line 1547: expected 1 fields, saw 2\\nSkipping line 1548: expected 1 fields, saw 2\\nSkipping line 1602: expected 1 fields, saw 2\\nSkipping line 1603: expected 1 fields, saw 2\\nSkipping line 1604: expected 1 fields, saw 3\\nSkipping line 1624: expected 1 fields, saw 2\\nSkipping line 1625: expected 1 fields, saw 2\\nSkipping line 1626: expected 1 fields, saw 2\\nSkipping line 1627: expected 1 fields, saw 2\\nSkipping line 1631: expected 1 fields, saw 2\\nSkipping line 1688: expected 1 fields, saw 3\\nSkipping line 1689: expected 1 fields, saw 2\\nSkipping line 1690: expected 1 fields, saw 2\\nSkipping line 1691: expected 1 fields, saw 2\\nSkipping line 1692: expected 1 fields, saw 2\\nSkipping line 1693: expected 1 fields, saw 2\\nSkipping line 1696: expected 1 fields, saw 2\\nSkipping line 1697: expected 1 fields, saw 2\\nSkipping line 1699: expected 1 fields, saw 2\\nSkipping line 1700: expected 1 fields, saw 2\\nSkipping line 1702: expected 1 fields, saw 3\\nSkipping line 1721: expected 1 fields, saw 2\\nSkipping line 1722: expected 1 fields, saw 2\\nSkipping line 1724: expected 1 fields, saw 2\\nSkipping line 1726: expected 1 fields, saw 2\\nSkipping line 1732: expected 1 fields, saw 2\\nSkipping line 1763: expected 1 fields, saw 2\\nSkipping line 1775: expected 1 fields, saw 5\\nSkipping line 1828: expected 1 fields, saw 2\\nSkipping line 1852: expected 1 fields, saw 3\\nSkipping line 1865: expected 1 fields, saw 2\\nSkipping line 1875: expected 1 fields, saw 2\\nSkipping line 1890: expected 1 fields, saw 2\\nSkipping line 1893: expected 1 fields, saw 2\\nSkipping line 1903: expected 1 fields, saw 3\\nSkipping line 1916: expected 1 fields, saw 2\\nSkipping line 1925: expected 1 fields, saw 2\\nSkipping line 1948: expected 1 fields, saw 2\\nSkipping line 1949: expected 1 fields, saw 2\\nSkipping line 1987: expected 1 fields, saw 2\\nSkipping line 1988: expected 1 fields, saw 2\\nSkipping line 2024: expected 1 fields, saw 2\\nSkipping line 2100: expected 1 fields, saw 2\\nSkipping line 2161: expected 1 fields, saw 2\\nSkipping line 2243: expected 1 fields, saw 2\\nSkipping line 2244: expected 1 fields, saw 2\\nSkipping line 2246: expected 1 fields, saw 2\\nSkipping line 2247: expected 1 fields, saw 2\\nSkipping line 2283: expected 1 fields, saw 2\\nSkipping line 2411: expected 1 fields, saw 2\\nSkipping line 2412: expected 1 fields, saw 2\\nSkipping line 2500: expected 1 fields, saw 2\\nSkipping line 2517: expected 1 fields, saw 3\\nSkipping line 2841: expected 1 fields, saw 2\\nSkipping line 2842: expected 1 fields, saw 2\\nSkipping line 2843: expected 1 fields, saw 2\\nSkipping line 2844: expected 1 fields, saw 2\\nSkipping line 2845: expected 1 fields, saw 2\\nSkipping line 2846: expected 1 fields, saw 2\\nSkipping line 2847: expected 1 fields, saw 2\\nSkipping line 2863: expected 1 fields, saw 2\\nSkipping line 2864: expected 1 fields, saw 2\\nSkipping line 2869: expected 1 fields, saw 2\\nSkipping line 2888: expected 1 fields, saw 3\\nSkipping line 2957: expected 1 fields, saw 2\\nSkipping line 3017: expected 1 fields, saw 2\\nSkipping line 3018: expected 1 fields, saw 2\\nSkipping line 3058: expected 1 fields, saw 2\\nSkipping line 3122: expected 1 fields, saw 2\\nSkipping line 3178: expected 1 fields, saw 2\\nSkipping line 3186: expected 1 fields, saw 2\\nSkipping line 3204: expected 1 fields, saw 2\\nSkipping line 3292: expected 1 fields, saw 2\\nSkipping line 3376: expected 1 fields, saw 2\\nSkipping line 3377: expected 1 fields, saw 2\\nSkipping line 3390: expected 1 fields, saw 2\\nSkipping line 3396: expected 1 fields, saw 2\\nSkipping line 3423: expected 1 fields, saw 2\\nSkipping line 3437: expected 1 fields, saw 2\\nSkipping line 3441: expected 1 fields, saw 2\\nSkipping line 3443: expected 1 fields, saw 4\\nSkipping line 3466: expected 1 fields, saw 2\\nSkipping line 3493: expected 1 fields, saw 2\\nSkipping line 3519: expected 1 fields, saw 2\\nSkipping line 3529: expected 1 fields, saw 2\\nSkipping line 3536: expected 1 fields, saw 2\\nSkipping line 3547: expected 1 fields, saw 2\\nSkipping line 3551: expected 1 fields, saw 2\\nSkipping line 3555: expected 1 fields, saw 3\\nSkipping line 3556: expected 1 fields, saw 2\\nSkipping line 3562: expected 1 fields, saw 2\\nSkipping line 3574: expected 1 fields, saw 3\\nSkipping line 3578: expected 1 fields, saw 2\\nSkipping line 3588: expected 1 fields, saw 2\\nSkipping line 3659: expected 1 fields, saw 2\\nSkipping line 3674: expected 1 fields, saw 2\\nSkipping line 3679: expected 1 fields, saw 2\\nSkipping line 3692: expected 1 fields, saw 2\\nSkipping line 3694: expected 1 fields, saw 2\\nSkipping line 3729: expected 1 fields, saw 2\\nSkipping line 3730: expected 1 fields, saw 2\\nSkipping line 3734: expected 1 fields, saw 2\\nSkipping line 3754: expected 1 fields, saw 2\\nSkipping line 3759: expected 1 fields, saw 2\\nSkipping line 3763: expected 1 fields, saw 2\\nSkipping line 3777: expected 1 fields, saw 3\\nSkipping line 3793: expected 1 fields, saw 2\\nSkipping line 3797: expected 1 fields, saw 2\\nSkipping line 3811: expected 1 fields, saw 2\\nSkipping line 3817: expected 1 fields, saw 2\\nSkipping line 3823: expected 1 fields, saw 2\\nSkipping line 3826: expected 1 fields, saw 2\\nSkipping line 3827: expected 1 fields, saw 2\\nSkipping line 3832: expected 1 fields, saw 4\\nSkipping line 3836: expected 1 fields, saw 2\\nSkipping line 3855: expected 1 fields, saw 2\\nSkipping line 3889: expected 1 fields, saw 3\\nSkipping line 3906: expected 1 fields, saw 2\\nSkipping line 3909: expected 1 fields, saw 2\\nSkipping line 3913: expected 1 fields, saw 2\\nSkipping line 3914: expected 1 fields, saw 2\\nSkipping line 3923: expected 1 fields, saw 2\\nSkipping line 3926: expected 1 fields, saw 2\\nSkipping line 3948: expected 1 fields, saw 2\\nSkipping line 3960: expected 1 fields, saw 3\\nSkipping line 3983: expected 1 fields, saw 2\\nSkipping line 3994: expected 1 fields, saw 2\\nSkipping line 4003: expected 1 fields, saw 2\\nSkipping line 4004: expected 1 fields, saw 2\\nSkipping line 4010: expected 1 fields, saw 2\\nSkipping line 4012: expected 1 fields, saw 2\\nSkipping line 4014: expected 1 fields, saw 2\\nSkipping line 4018: expected 1 fields, saw 3\\nSkipping line 4021: expected 1 fields, saw 3\\nSkipping line 4023: expected 1 fields, saw 2\\nSkipping line 4039: expected 1 fields, saw 2\\nSkipping line 4040: expected 1 fields, saw 2\\nSkipping line 4041: expected 1 fields, saw 3\\nSkipping line 4059: expected 1 fields, saw 2\\nSkipping line 4071: expected 1 fields, saw 2\\nSkipping line 4093: expected 1 fields, saw 3\\nSkipping line 4094: expected 1 fields, saw 2\\nSkipping line 4127: expected 1 fields, saw 2\\nSkipping line 4130: expected 1 fields, saw 2\\nSkipping line 4147: expected 1 fields, saw 2\\nSkipping line 4150: expected 1 fields, saw 2\\nSkipping line 4152: expected 1 fields, saw 3\\nSkipping line 4156: expected 1 fields, saw 3\\nSkipping line 4158: expected 1 fields, saw 2\\nSkipping line 4165: expected 1 fields, saw 2\\nSkipping line 4168: expected 1 fields, saw 2\\nSkipping line 4172: expected 1 fields, saw 2\\nSkipping line 4211: expected 1 fields, saw 2\\nSkipping line 4217: expected 1 fields, saw 2\\nSkipping line 4381: expected 1 fields, saw 3\\nSkipping line 4382: expected 1 fields, saw 2\\nSkipping line 4408: expected 1 fields, saw 3\\nSkipping line 4409: expected 1 fields, saw 2\\nSkipping line 4410: expected 1 fields, saw 2\\nSkipping line 4412: expected 1 fields, saw 2\\nSkipping line 4423: expected 1 fields, saw 3\\nSkipping line 4458: expected 1 fields, saw 4\\nSkipping line 4481: expected 1 fields, saw 2\\nSkipping line 4490: expected 1 fields, saw 2\\nSkipping line 4493: expected 1 fields, saw 2\\nSkipping line 4517: expected 1 fields, saw 2\\nSkipping line 4520: expected 1 fields, saw 2\\nSkipping line 4541: expected 1 fields, saw 2\\nSkipping line 4542: expected 1 fields, saw 3\\nSkipping line 4580: expected 1 fields, saw 2\\nSkipping line 4618: expected 1 fields, saw 2\\nSkipping line 4903: expected 1 fields, saw 2\\nSkipping line 4912: expected 1 fields, saw 2\\nSkipping line 4919: expected 1 fields, saw 2\\nSkipping line 4923: expected 1 fields, saw 2\\nSkipping line 4948: expected 1 fields, saw 2\\nSkipping line 4957: expected 1 fields, saw 3\\n'\n    b'Skipping line 14: expected 2 fields, saw 3\\nSkipping line 15: expected 2 fields, saw 4\\nSkipping line 17: expected 2 fields, saw 3\\nSkipping line 20: expected 2 fields, saw 5\\nSkipping line 23: expected 2 fields, saw 4\\nSkipping line 26: expected 2 fields, saw 3\\nSkipping line 27: expected 2 fields, saw 4\\nSkipping line 28: expected 2 fields, saw 5\\nSkipping line 29: expected 2 fields, saw 3\\nSkipping line 46: expected 2 fields, saw 3\\nSkipping line 61: expected 2 fields, saw 3\\nSkipping line 66: expected 2 fields, saw 3\\nSkipping line 67: expected 2 fields, saw 3\\nSkipping line 70: expected 2 fields, saw 4\\nSkipping line 72: expected 2 fields, saw 3\\nSkipping line 73: expected 2 fields, saw 3\\nSkipping line 74: expected 2 fields, saw 3\\nSkipping line 75: expected 2 fields, saw 3\\nSkipping line 79: expected 2 fields, saw 3\\nSkipping line 83: expected 2 fields, saw 3\\nSkipping line 85: expected 2 fields, saw 3\\nSkipping line 88: expected 2 fields, saw 3\\nSkipping line 89: expected 2 fields, saw 4\\nSkipping line 107: expected 2 fields, saw 3\\nSkipping line 108: expected 2 fields, saw 3\\nSkipping line 111: expected 2 fields, saw 3\\nSkipping line 116: expected 2 fields, saw 3\\nSkipping line 132: expected 2 fields, saw 3\\nSkipping line 133: expected 2 fields, saw 4\\nSkipping line 162: expected 2 fields, saw 4\\nSkipping line 171: expected 2 fields, saw 3\\nSkipping line 194: expected 2 fields, saw 4\\nSkipping line 195: expected 2 fields, saw 3\\nSkipping line 196: expected 2 fields, saw 3\\nSkipping line 204: expected 2 fields, saw 4\\nSkipping line 206: expected 2 fields, saw 3\\nSkipping line 207: expected 2 fields, saw 4\\nSkipping line 208: expected 2 fields, saw 3\\nSkipping line 209: expected 2 fields, saw 3\\nSkipping line 210: expected 2 fields, saw 3\\nSkipping line 222: expected 2 fields, saw 3\\nSkipping line 227: expected 2 fields, saw 3\\nSkipping line 228: expected 2 fields, saw 3\\nSkipping line 229: expected 2 fields, saw 3\\nSkipping line 230: expected 2 fields, saw 3\\nSkipping line 231: expected 2 fields, saw 3\\nSkipping line 233: expected 2 fields, saw 3\\nSkipping line 234: expected 2 fields, saw 3\\nSkipping line 235: expected 2 fields, saw 3\\nSkipping line 247: expected 2 fields, saw 3\\nSkipping line 248: expected 2 fields, saw 3\\nSkipping line 249: expected 2 fields, saw 3\\nSkipping line 266: expected 2 fields, saw 3\\nSkipping line 268: expected 2 fields, saw 3\\nSkipping line 269: expected 2 fields, saw 3\\nSkipping line 270: expected 2 fields, saw 3\\nSkipping line 271: expected 2 fields, saw 3\\nSkipping line 272: expected 2 fields, saw 3\\nSkipping line 278: expected 2 fields, saw 3\\nSkipping line 280: expected 2 fields, saw 3\\nSkipping line 281: expected 2 fields, saw 3\\nSkipping line 284: expected 2 fields, saw 3\\nSkipping line 285: expected 2 fields, saw 3\\nSkipping line 286: expected 2 fields, saw 3\\nSkipping line 287: expected 2 fields, saw 3\\nSkipping line 288: expected 2 fields, saw 3\\nSkipping line 299: expected 2 fields, saw 3\\nSkipping line 300: expected 2 fields, saw 3\\nSkipping line 301: expected 2 fields, saw 3\\nSkipping line 304: expected 2 fields, saw 3\\nSkipping line 305: expected 2 fields, saw 3\\nSkipping line 306: expected 2 fields, saw 3\\nSkipping line 307: expected 2 fields, saw 3\\nSkipping line 309: expected 2 fields, saw 3\\nSkipping line 310: expected 2 fields, saw 3\\nSkipping line 314: expected 2 fields, saw 3\\nSkipping line 316: expected 2 fields, saw 3\\nSkipping line 318: expected 2 fields, saw 3\\nSkipping line 319: expected 2 fields, saw 4\\nSkipping line 320: expected 2 fields, saw 3\\nSkipping line 323: expected 2 fields, saw 3\\nSkipping line 324: expected 2 fields, saw 3\\nSkipping line 325: expected 2 fields, saw 3\\nSkipping line 329: expected 2 fields, saw 3\\nSkipping line 331: expected 2 fields, saw 4\\nSkipping line 333: expected 2 fields, saw 3\\nSkipping line 334: expected 2 fields, saw 4\\nSkipping line 335: expected 2 fields, saw 3\\nSkipping line 336: expected 2 fields, saw 5\\nSkipping line 344: expected 2 fields, saw 3\\nSkipping line 346: expected 2 fields, saw 3\\nSkipping line 351: expected 2 fields, saw 3\\nSkipping line 352: expected 2 fields, saw 3\\nSkipping line 353: expected 2 fields, saw 3\\nSkipping line 355: expected 2 fields, saw 3\\nSkipping line 357: expected 2 fields, saw 4\\nSkipping line 362: expected 2 fields, saw 3\\nSkipping line 388: expected 2 fields, saw 3\\nSkipping line 392: expected 2 fields, saw 3\\nSkipping line 394: expected 2 fields, saw 3\\nSkipping line 396: expected 2 fields, saw 3\\nSkipping line 397: expected 2 fields, saw 3\\nSkipping line 399: expected 2 fields, saw 3\\nSkipping line 400: expected 2 fields, saw 3\\nSkipping line 401: expected 2 fields, saw 3\\nSkipping line 404: expected 2 fields, saw 3\\nSkipping line 405: expected 2 fields, saw 3\\nSkipping line 406: expected 2 fields, saw 3\\nSkipping line 408: expected 2 fields, saw 3\\nSkipping line 411: expected 2 fields, saw 3\\nSkipping line 413: expected 2 fields, saw 3\\nSkipping line 429: expected 2 fields, saw 3\\nSkipping line 432: expected 2 fields, saw 3\\nSkipping line 433: expected 2 fields, saw 3\\nSkipping line 450: expected 2 fields, saw 3\\nSkipping line 451: expected 2 fields, saw 3\\nSkipping line 452: expected 2 fields, saw 3\\nSkipping line 467: expected 2 fields, saw 3\\nSkipping line 468: expected 2 fields, saw 3\\nSkipping line 470: expected 2 fields, saw 3\\nSkipping line 473: expected 2 fields, saw 3\\nSkipping line 477: expected 2 fields, saw 3\\nSkipping line 478: expected 2 fields, saw 4\\nSkipping line 479: expected 2 fields, saw 3\\nSkipping line 485: expected 2 fields, saw 3\\nSkipping line 495: expected 2 fields, saw 3\\nSkipping line 496: expected 2 fields, saw 3\\nSkipping line 499: expected 2 fields, saw 3\\nSkipping line 500: expected 2 fields, saw 3\\nSkipping line 501: expected 2 fields, saw 3\\nSkipping line 507: expected 2 fields, saw 3\\nSkipping line 508: expected 2 fields, saw 3\\nSkipping line 509: expected 2 fields, saw 3\\nSkipping line 510: expected 2 fields, saw 3\\nSkipping line 516: expected 2 fields, saw 3\\nSkipping line 542: expected 2 fields, saw 3\\nSkipping line 545: expected 2 fields, saw 3\\nSkipping line 547: expected 2 fields, saw 3\\nSkipping line 548: expected 2 fields, saw 3\\nSkipping line 549: expected 2 fields, saw 3\\nSkipping line 550: expected 2 fields, saw 3\\nSkipping line 551: expected 2 fields, saw 3\\nSkipping line 553: expected 2 fields, saw 3\\nSkipping line 554: expected 2 fields, saw 4\\nSkipping line 559: expected 2 fields, saw 3\\nSkipping line 560: expected 2 fields, saw 3\\nSkipping line 561: expected 2 fields, saw 3\\nSkipping line 562: expected 2 fields, saw 3\\nSkipping line 565: expected 2 fields, saw 3\\nSkipping line 566: expected 2 fields, saw 3\\nSkipping line 576: expected 2 fields, saw 3\\nSkipping line 577: expected 2 fields, saw 3\\nSkipping line 578: expected 2 fields, saw 3\\nSkipping line 580: expected 2 fields, saw 3\\nSkipping line 582: expected 2 fields, saw 3\\nSkipping line 583: expected 2 fields, saw 3\\nSkipping line 584: expected 2 fields, saw 3\\nSkipping line 585: expected 2 fields, saw 3\\nSkipping line 586: expected 2 fields, saw 4\\nSkipping line 587: expected 2 fields, saw 3\\nSkipping line 588: expected 2 fields, saw 3\\nSkipping line 594: expected 2 fields, saw 3\\nSkipping line 595: expected 2 fields, saw 3\\nSkipping line 597: expected 2 fields, saw 3\\nSkipping line 599: expected 2 fields, saw 3\\nSkipping line 600: expected 2 fields, saw 3\\nSkipping line 604: expected 2 fields, saw 3\\nSkipping line 605: expected 2 fields, saw 3\\nSkipping line 606: expected 2 fields, saw 3\\nSkipping line 607: expected 2 fields, saw 3\\nSkipping line 608: expected 2 fields, saw 3\\nSkipping line 612: expected 2 fields, saw 3\\nSkipping line 613: expected 2 fields, saw 3\\nSkipping line 625: expected 2 fields, saw 3\\nSkipping line 626: expected 2 fields, saw 3\\nSkipping line 627: expected 2 fields, saw 3\\nSkipping line 628: expected 2 fields, saw 3\\nSkipping line 629: expected 2 fields, saw 3\\nSkipping line 636: expected 2 fields, saw 3\\nSkipping line 637: expected 2 fields, saw 3\\nSkipping line 638: expected 2 fields, saw 3\\nSkipping line 656: expected 2 fields, saw 3\\nSkipping line 657: expected 2 fields, saw 3\\nSkipping line 659: expected 2 fields, saw 3\\nSkipping line 661: expected 2 fields, saw 3\\nSkipping line 662: expected 2 fields, saw 3\\nSkipping line 663: expected 2 fields, saw 3\\nSkipping line 664: expected 2 fields, saw 3\\nSkipping line 665: expected 2 fields, saw 3\\nSkipping line 666: expected 2 fields, saw 3\\nSkipping line 667: expected 2 fields, saw 3\\nSkipping line 669: expected 2 fields, saw 4\\nSkipping line 697: expected 2 fields, saw 4\\nSkipping line 699: expected 2 fields, saw 3\\nSkipping line 703: expected 2 fields, saw 3\\nSkipping line 704: expected 2 fields, saw 3\\nSkipping line 705: expected 2 fields, saw 3\\nSkipping line 710: expected 2 fields, saw 3\\nSkipping line 711: expected 2 fields, saw 3\\nSkipping line 713: expected 2 fields, saw 3\\nSkipping line 714: expected 2 fields, saw 3\\nSkipping line 719: expected 2 fields, saw 3\\nSkipping line 723: expected 2 fields, saw 3\\nSkipping line 727: expected 2 fields, saw 3\\nSkipping line 728: expected 2 fields, saw 3\\nSkipping line 729: expected 2 fields, saw 3\\nSkipping line 731: expected 2 fields, saw 3\\nSkipping line 732: expected 2 fields, saw 3\\nSkipping line 735: expected 2 fields, saw 3\\nSkipping line 736: expected 2 fields, saw 3\\nSkipping line 737: expected 2 fields, saw 3\\nSkipping line 742: expected 2 fields, saw 3\\nSkipping line 745: expected 2 fields, saw 3\\nSkipping line 746: expected 2 fields, saw 3\\nSkipping line 747: expected 2 fields, saw 3\\nSkipping line 751: expected 2 fields, saw 3\\nSkipping line 756: expected 2 fields, saw 3\\nSkipping line 768: expected 2 fields, saw 3\\nSkipping line 772: expected 2 fields, saw 3\\nSkipping line 773: expected 2 fields, saw 3\\nSkipping line 775: expected 2 fields, saw 3\\nSkipping line 781: expected 2 fields, saw 3\\nSkipping line 787: expected 2 fields, saw 3\\nSkipping line 788: expected 2 fields, saw 3\\nSkipping line 789: expected 2 fields, saw 3\\nSkipping line 815: expected 2 fields, saw 3\\nSkipping line 819: expected 2 fields, saw 3\\nSkipping line 823: expected 2 fields, saw 3\\nSkipping line 824: expected 2 fields, saw 3\\nSkipping line 829: expected 2 fields, saw 4\\nSkipping line 834: expected 2 fields, saw 3\\nSkipping line 835: expected 2 fields, saw 3\\nSkipping line 836: expected 2 fields, saw 3\\nSkipping line 838: expected 2 fields, saw 3\\nSkipping line 848: expected 2 fields, saw 3\\nSkipping line 878: expected 2 fields, saw 3\\nSkipping line 879: expected 2 fields, saw 3\\nSkipping line 883: expected 2 fields, saw 3\\nSkipping line 887: expected 2 fields, saw 3\\nSkipping line 890: expected 2 fields, saw 4\\nSkipping line 893: expected 2 fields, saw 3\\nSkipping line 895: expected 2 fields, saw 3\\nSkipping line 898: expected 2 fields, saw 3\\nSkipping line 899: expected 2 fields, saw 3\\nSkipping line 906: expected 2 fields, saw 3\\nSkipping line 907: expected 2 fields, saw 3\\nSkipping line 908: expected 2 fields, saw 3\\nSkipping line 909: expected 2 fields, saw 3\\nSkipping line 910: expected 2 fields, saw 3\\nSkipping line 911: expected 2 fields, saw 3\\nSkipping line 939: expected 2 fields, saw 3\\nSkipping line 942: expected 2 fields, saw 3\\nSkipping line 944: expected 2 fields, saw 3\\nSkipping line 947: expected 2 fields, saw 3\\nSkipping line 948: expected 2 fields, saw 3\\nSkipping line 971: expected 2 fields, saw 3\\nSkipping line 972: expected 2 fields, saw 3\\nSkipping line 973: expected 2 fields, saw 3\\nSkipping line 977: expected 2 fields, saw 3\\nSkipping line 982: expected 2 fields, saw 4\\nSkipping line 983: expected 2 fields, saw 3\\nSkipping line 985: expected 2 fields, saw 3\\nSkipping line 988: expected 2 fields, saw 3\\nSkipping line 990: expected 2 fields, saw 3\\nSkipping line 991: expected 2 fields, saw 3\\nSkipping line 992: expected 2 fields, saw 3\\nSkipping line 993: expected 2 fields, saw 3\\nSkipping line 994: expected 2 fields, saw 4\\nSkipping line 996: expected 2 fields, saw 3\\nSkipping line 997: expected 2 fields, saw 3\\nSkipping line 998: expected 2 fields, saw 3\\nSkipping line 1001: expected 2 fields, saw 3\\nSkipping line 1002: expected 2 fields, saw 3\\nSkipping line 1003: expected 2 fields, saw 3\\nSkipping line 1006: expected 2 fields, saw 3\\nSkipping line 1008: expected 2 fields, saw 3\\nSkipping line 1015: expected 2 fields, saw 3\\nSkipping line 1017: expected 2 fields, saw 3\\nSkipping line 1018: expected 2 fields, saw 3\\nSkipping line 1019: expected 2 fields, saw 3\\nSkipping line 1020: expected 2 fields, saw 3\\nSkipping line 1021: expected 2 fields, saw 3\\nSkipping line 1024: expected 2 fields, saw 3\\nSkipping line 1032: expected 2 fields, saw 4\\nSkipping line 1033: expected 2 fields, saw 3\\nSkipping line 1034: expected 2 fields, saw 3\\nSkipping line 1035: expected 2 fields, saw 3\\nSkipping line 1036: expected 2 fields, saw 3\\nSkipping line 1041: expected 2 fields, saw 3\\nSkipping line 1042: expected 2 fields, saw 3\\nSkipping line 1043: expected 2 fields, saw 3\\nSkipping line 1044: expected 2 fields, saw 3\\nSkipping line 1046: expected 2 fields, saw 3\\nSkipping line 1048: expected 2 fields, saw 3\\nSkipping line 1049: expected 2 fields, saw 3\\nSkipping line 1051: expected 2 fields, saw 3\\nSkipping line 1055: expected 2 fields, saw 3\\nSkipping line 1056: expected 2 fields, saw 3\\nSkipping line 1058: expected 2 fields, saw 3\\nSkipping line 1071: expected 2 fields, saw 3\\nSkipping line 1074: expected 2 fields, saw 3\\nSkipping line 1075: expected 2 fields, saw 3\\nSkipping line 1076: expected 2 fields, saw 3\\nSkipping line 1079: expected 2 fields, saw 3\\nSkipping line 1080: expected 2 fields, saw 3\\nSkipping line 1085: expected 2 fields, saw 3\\nSkipping line 1088: expected 2 fields, saw 3\\nSkipping line 1089: expected 2 fields, saw 3\\nSkipping line 1090: expected 2 fields, saw 3\\nSkipping line 1096: expected 2 fields, saw 3\\nSkipping line 1097: expected 2 fields, saw 3\\nSkipping line 1101: expected 2 fields, saw 3\\nSkipping line 1102: expected 2 fields, saw 4\\nSkipping line 1103: expected 2 fields, saw 3\\nSkipping line 1106: expected 2 fields, saw 3\\nSkipping line 1108: expected 2 fields, saw 3\\nSkipping line 1109: expected 2 fields, saw 3\\nSkipping line 1110: expected 2 fields, saw 3\\nSkipping line 1111: expected 2 fields, saw 3\\nSkipping line 1112: expected 2 fields, saw 3\\nSkipping line 1116: expected 2 fields, saw 3\\nSkipping line 1117: expected 2 fields, saw 4\\nSkipping line 1118: expected 2 fields, saw 3\\nSkipping line 1119: expected 2 fields, saw 3\\nSkipping line 1120: expected 2 fields, saw 3\\nSkipping line 1122: expected 2 fields, saw 3\\nSkipping line 1123: expected 2 fields, saw 4\\nSkipping line 1124: expected 2 fields, saw 3\\nSkipping line 1125: expected 2 fields, saw 3\\nSkipping line 1128: expected 2 fields, saw 3\\nSkipping line 1129: expected 2 fields, saw 3\\nSkipping line 1131: expected 2 fields, saw 6\\nSkipping line 1133: expected 2 fields, saw 5\\nSkipping line 1136: expected 2 fields, saw 3\\nSkipping line 1138: expected 2 fields, saw 3\\nSkipping line 1140: expected 2 fields, saw 3\\nSkipping line 1142: expected 2 fields, saw 3\\nSkipping line 1144: expected 2 fields, saw 3\\nSkipping line 1145: expected 2 fields, saw 3\\nSkipping line 1149: expected 2 fields, saw 3\\nSkipping line 1150: expected 2 fields, saw 3\\nSkipping line 1155: expected 2 fields, saw 4\\nSkipping line 1159: expected 2 fields, saw 3\\nSkipping line 1160: expected 2 fields, saw 3\\nSkipping line 1162: expected 2 fields, saw 4\\nSkipping line 1163: expected 2 fields, saw 3\\nSkipping line 1164: expected 2 fields, saw 3\\nSkipping line 1165: expected 2 fields, saw 3\\nSkipping line 1166: expected 2 fields, saw 3\\nSkipping line 1167: expected 2 fields, saw 3\\nSkipping line 1168: expected 2 fields, saw 3\\nSkipping line 1169: expected 2 fields, saw 3\\nSkipping line 1171: expected 2 fields, saw 3\\nSkipping line 1173: expected 2 fields, saw 3\\nSkipping line 1174: expected 2 fields, saw 3\\nSkipping line 1175: expected 2 fields, saw 4\\nSkipping line 1176: expected 2 fields, saw 3\\nSkipping line 1177: expected 2 fields, saw 3\\nSkipping line 1178: expected 2 fields, saw 3\\nSkipping line 1179: expected 2 fields, saw 3\\nSkipping line 1181: expected 2 fields, saw 3\\nSkipping line 1182: expected 2 fields, saw 3\\nSkipping line 1183: expected 2 fields, saw 3\\nSkipping line 1185: expected 2 fields, saw 3\\nSkipping line 1189: expected 2 fields, saw 3\\nSkipping line 1190: expected 2 fields, saw 3\\nSkipping line 1191: expected 2 fields, saw 3\\nSkipping line 1194: expected 2 fields, saw 3\\nSkipping line 1195: expected 2 fields, saw 3\\nSkipping line 1213: expected 2 fields, saw 3\\nSkipping line 1214: expected 2 fields, saw 4\\nSkipping line 1226: expected 2 fields, saw 3\\nSkipping line 1231: expected 2 fields, saw 3\\nSkipping line 1243: expected 2 fields, saw 3\\nSkipping line 1245: expected 2 fields, saw 3\\nSkipping line 1246: expected 2 fields, saw 3\\nSkipping line 1248: expected 2 fields, saw 3\\nSkipping line 1253: expected 2 fields, saw 3\\nSkipping line 1254: expected 2 fields, saw 3\\nSkipping line 1255: expected 2 fields, saw 3\\nSkipping line 1256: expected 2 fields, saw 3\\nSkipping line 1258: expected 2 fields, saw 3\\nSkipping line 1264: expected 2 fields, saw 3\\nSkipping line 1266: expected 2 fields, saw 3\\nSkipping line 1267: expected 2 fields, saw 3\\nSkipping line 1271: expected 2 fields, saw 3\\nSkipping line 1273: expected 2 fields, saw 3\\nSkipping line 1280: expected 2 fields, saw 3\\nSkipping line 1282: expected 2 fields, saw 3\\nSkipping line 1284: expected 2 fields, saw 3\\nSkipping line 1286: expected 2 fields, saw 3\\nSkipping line 1289: expected 2 fields, saw 3\\nSkipping line 1291: expected 2 fields, saw 3\\nSkipping line 1295: expected 2 fields, saw 3\\nSkipping line 1296: expected 2 fields, saw 3\\nSkipping line 1298: expected 2 fields, saw 3\\nSkipping line 1299: expected 2 fields, saw 3\\nSkipping line 1300: expected 2 fields, saw 3\\nSkipping line 1301: expected 2 fields, saw 3\\nSkipping line 1302: expected 2 fields, saw 3\\nSkipping line 1304: expected 2 fields, saw 3\\nSkipping line 1305: expected 2 fields, saw 3\\nSkipping line 1306: expected 2 fields, saw 3\\nSkipping line 1309: expected 2 fields, saw 3\\nSkipping line 1311: expected 2 fields, saw 3\\nSkipping line 1312: expected 2 fields, saw 3\\nSkipping line 1313: expected 2 fields, saw 3\\nSkipping line 1314: expected 2 fields, saw 4\\nSkipping line 1317: expected 2 fields, saw 3\\nSkipping line 1318: expected 2 fields, saw 3\\nSkipping line 1319: expected 2 fields, saw 3\\nSkipping line 1320: expected 2 fields, saw 3\\nSkipping line 1321: expected 2 fields, saw 3\\nSkipping line 1322: expected 2 fields, saw 3\\nSkipping line 1324: expected 2 fields, saw 4\\nSkipping line 1325: expected 2 fields, saw 3\\nSkipping line 1326: expected 2 fields, saw 5\\nSkipping line 1328: expected 2 fields, saw 3\\nSkipping line 1329: expected 2 fields, saw 3\\nSkipping line 1330: expected 2 fields, saw 3\\nSkipping line 1332: expected 2 fields, saw 3\\nSkipping line 1334: expected 2 fields, saw 3\\nSkipping line 1335: expected 2 fields, saw 3\\nSkipping line 1337: expected 2 fields, saw 3\\nSkipping line 1338: expected 2 fields, saw 3\\nSkipping line 1341: expected 2 fields, saw 3\\nSkipping line 1354: expected 2 fields, saw 3\\nSkipping line 1359: expected 2 fields, saw 3\\nSkipping line 1367: expected 2 fields, saw 3\\nSkipping line 1371: expected 2 fields, saw 3\\nSkipping line 1372: expected 2 fields, saw 3\\nSkipping line 1373: expected 2 fields, saw 3\\nSkipping line 1374: expected 2 fields, saw 3\\nSkipping line 1377: expected 2 fields, saw 3\\nSkipping line 1378: expected 2 fields, saw 3\\nSkipping line 1379: expected 2 fields, saw 3\\nSkipping line 1380: expected 2 fields, saw 3\\nSkipping line 1388: expected 2 fields, saw 4\\nSkipping line 1390: expected 2 fields, saw 3\\nSkipping line 1391: expected 2 fields, saw 3\\nSkipping line 1392: expected 2 fields, saw 3\\nSkipping line 1394: expected 2 fields, saw 3\\nSkipping line 1397: expected 2 fields, saw 3\\nSkipping line 1399: expected 2 fields, saw 3\\nSkipping line 1404: expected 2 fields, saw 3\\nSkipping line 1405: expected 2 fields, saw 3\\nSkipping line 1406: expected 2 fields, saw 3\\nSkipping line 1411: expected 2 fields, saw 3\\nSkipping line 1412: expected 2 fields, saw 3\\nSkipping line 1413: expected 2 fields, saw 3\\nSkipping line 1414: expected 2 fields, saw 3\\nSkipping line 1416: expected 2 fields, saw 3\\nSkipping line 1417: expected 2 fields, saw 4\\nSkipping line 1418: expected 2 fields, saw 3\\nSkipping line 1422: expected 2 fields, saw 3\\nSkipping line 1425: expected 2 fields, saw 3\\nSkipping line 1426: expected 2 fields, saw 3\\nSkipping line 1427: expected 2 fields, saw 3\\nSkipping line 1428: expected 2 fields, saw 3\\nSkipping line 1429: expected 2 fields, saw 4\\nSkipping line 1430: expected 2 fields, saw 3\\nSkipping line 1431: expected 2 fields, saw 3\\nSkipping line 1433: expected 2 fields, saw 4\\nSkipping line 1434: expected 2 fields, saw 3\\nSkipping line 1435: expected 2 fields, saw 3\\nSkipping line 1436: expected 2 fields, saw 3\\nSkipping line 1437: expected 2 fields, saw 3\\nSkipping line 1441: expected 2 fields, saw 3\\nSkipping line 1445: expected 2 fields, saw 3\\nSkipping line 1450: expected 2 fields, saw 3\\nSkipping line 1457: expected 2 fields, saw 4\\nSkipping line 1461: expected 2 fields, saw 3\\nSkipping line 1462: expected 2 fields, saw 3\\nSkipping line 1463: expected 2 fields, saw 3\\nSkipping line 1464: expected 2 fields, saw 3\\nSkipping line 1465: expected 2 fields, saw 3\\nSkipping line 1468: expected 2 fields, saw 3\\nSkipping line 1470: expected 2 fields, saw 3\\nSkipping line 1471: expected 2 fields, saw 3\\nSkipping line 1472: expected 2 fields, saw 3\\nSkipping line 1473: expected 2 fields, saw 3\\nSkipping line 1474: expected 2 fields, saw 3\\nSkipping line 1476: expected 2 fields, saw 3\\nSkipping line 1481: expected 2 fields, saw 3\\nSkipping line 1487: expected 2 fields, saw 3\\nSkipping line 1488: expected 2 fields, saw 3\\nSkipping line 1492: expected 2 fields, saw 4\\nSkipping line 1493: expected 2 fields, saw 4\\nSkipping line 1496: expected 2 fields, saw 3\\nSkipping line 1497: expected 2 fields, saw 3\\nSkipping line 1498: expected 2 fields, saw 3\\nSkipping line 1499: expected 2 fields, saw 3\\nSkipping line 1500: expected 2 fields, saw 3\\nSkipping line 1501: expected 2 fields, saw 3\\nSkipping line 1503: expected 2 fields, saw 3\\nSkipping line 1504: expected 2 fields, saw 3\\nSkipping line 1505: expected 2 fields, saw 3\\nSkipping line 1506: expected 2 fields, saw 3\\nSkipping line 1507: expected 2 fields, saw 3\\nSkipping line 1508: expected 2 fields, saw 3\\nSkipping line 1511: expected 2 fields, saw 3\\nSkipping line 1512: expected 2 fields, saw 3\\nSkipping line 1513: expected 2 fields, saw 3\\nSkipping line 1514: expected 2 fields, saw 3\\nSkipping line 1517: expected 2 fields, saw 3\\nSkipping line 1521: expected 2 fields, saw 3\\nSkipping line 1529: expected 2 fields, saw 3\\nSkipping line 1530: expected 2 fields, saw 4\\nSkipping line 1532: expected 2 fields, saw 3\\nSkipping line 1549: expected 2 fields, saw 3\\nSkipping line 1552: expected 2 fields, saw 3\\nSkipping line 1569: expected 2 fields, saw 3\\nSkipping line 1575: expected 2 fields, saw 3\\nSkipping line 1586: expected 2 fields, saw 4\\nSkipping line 1587: expected 2 fields, saw 4\\nSkipping line 1588: expected 2 fields, saw 3\\nSkipping line 1602: expected 2 fields, saw 3\\nSkipping line 1604: expected 2 fields, saw 3\\nSkipping line 1606: expected 2 fields, saw 3\\nSkipping line 1607: expected 2 fields, saw 3\\nSkipping line 1608: expected 2 fields, saw 3\\nSkipping line 1609: expected 2 fields, saw 3\\nSkipping line 1633: expected 2 fields, saw 4\\nSkipping line 1635: expected 2 fields, saw 3\\nSkipping line 1642: expected 2 fields, saw 3\\nSkipping line 1645: expected 2 fields, saw 3\\nSkipping line 1646: expected 2 fields, saw 3\\nSkipping line 1647: expected 2 fields, saw 3\\nSkipping line 1648: expected 2 fields, saw 4\\nSkipping line 1663: expected 2 fields, saw 3\\nSkipping line 1672: expected 2 fields, saw 3\\nSkipping line 1673: expected 2 fields, saw 3\\nSkipping line 1677: expected 2 fields, saw 3\\nSkipping line 1679: expected 2 fields, saw 4\\nSkipping line 1686: expected 2 fields, saw 3\\nSkipping line 1687: expected 2 fields, saw 3\\nSkipping line 1689: expected 2 fields, saw 3\\nSkipping line 1690: expected 2 fields, saw 3\\nSkipping line 1691: expected 2 fields, saw 3\\nSkipping line 1692: expected 2 fields, saw 3\\nSkipping line 1693: expected 2 fields, saw 3\\nSkipping line 1694: expected 2 fields, saw 3\\nSkipping line 1710: expected 2 fields, saw 3\\nSkipping line 1711: expected 2 fields, saw 4\\nSkipping line 1712: expected 2 fields, saw 3\\nSkipping line 1716: expected 2 fields, saw 3\\nSkipping line 1722: expected 2 fields, saw 3\\nSkipping line 1727: expected 2 fields, saw 3\\nSkipping line 1729: expected 2 fields, saw 4\\nSkipping line 1741: expected 2 fields, saw 3\\nSkipping line 1744: expected 2 fields, saw 3\\nSkipping line 1747: expected 2 fields, saw 3\\nSkipping line 1750: expected 2 fields, saw 3\\nSkipping line 1751: expected 2 fields, saw 3\\nSkipping line 1752: expected 2 fields, saw 3\\nSkipping line 1759: expected 2 fields, saw 3\\nSkipping line 1762: expected 2 fields, saw 4\\nSkipping line 1766: expected 2 fields, saw 3\\nSkipping line 1767: expected 2 fields, saw 3\\nSkipping line 1769: expected 2 fields, saw 3\\nSkipping line 1770: expected 2 fields, saw 3\\nSkipping line 1771: expected 2 fields, saw 3\\nSkipping line 1773: expected 2 fields, saw 3\\nSkipping line 1776: expected 2 fields, saw 3\\nSkipping line 1781: expected 2 fields, saw 3\\nSkipping line 1782: expected 2 fields, saw 3\\nSkipping line 1783: expected 2 fields, saw 3\\nSkipping line 1786: expected 2 fields, saw 3\\nSkipping line 1787: expected 2 fields, saw 3\\nSkipping line 1788: expected 2 fields, saw 3\\nSkipping line 1789: expected 2 fields, saw 3\\nSkipping line 1791: expected 2 fields, saw 3\\nSkipping line 1792: expected 2 fields, saw 3\\nSkipping line 1794: expected 2 fields, saw 3\\nSkipping line 1795: expected 2 fields, saw 3\\nSkipping line 1796: expected 2 fields, saw 3\\nSkipping line 1800: expected 2 fields, saw 3\\nSkipping line 1801: expected 2 fields, saw 3\\nSkipping line 1803: expected 2 fields, saw 3\\nSkipping line 1810: expected 2 fields, saw 3\\nSkipping line 1811: expected 2 fields, saw 3\\nSkipping line 1813: expected 2 fields, saw 3\\nSkipping line 1816: expected 2 fields, saw 3\\nSkipping line 1818: expected 2 fields, saw 3\\nSkipping line 1823: expected 2 fields, saw 3\\nSkipping line 1829: expected 2 fields, saw 3\\nSkipping line 1832: expected 2 fields, saw 3\\nSkipping line 1833: expected 2 fields, saw 3\\nSkipping line 1834: expected 2 fields, saw 3\\nSkipping line 1836: expected 2 fields, saw 3\\nSkipping line 1839: expected 2 fields, saw 3\\nSkipping line 1844: expected 2 fields, saw 3\\nSkipping line 1846: expected 2 fields, saw 3\\nSkipping line 1847: expected 2 fields, saw 3\\nSkipping line 1850: expected 2 fields, saw 3\\nSkipping line 1855: expected 2 fields, saw 3\\nSkipping line 1856: expected 2 fields, saw 3\\nSkipping line 1858: expected 2 fields, saw 3\\nSkipping line 1860: expected 2 fields, saw 3\\nSkipping line 1861: expected 2 fields, saw 3\\nSkipping line 1862: expected 2 fields, saw 3\\nSkipping line 1863: expected 2 fields, saw 3\\nSkipping line 1865: expected 2 fields, saw 3\\nSkipping line 1866: expected 2 fields, saw 3\\nSkipping line 1867: expected 2 fields, saw 4\\nSkipping line 1868: expected 2 fields, saw 3\\nSkipping line 1869: expected 2 fields, saw 3\\nSkipping line 1871: expected 2 fields, saw 3\\nSkipping line 1872: expected 2 fields, saw 3\\nSkipping line 1874: expected 2 fields, saw 3\\nSkipping line 1879: expected 2 fields, saw 3\\nSkipping line 1883: expected 2 fields, saw 3\\nSkipping line 1884: expected 2 fields, saw 3\\nSkipping line 1887: expected 2 fields, saw 3\\nSkipping line 1888: expected 2 fields, saw 3\\nSkipping line 1889: expected 2 fields, saw 3\\nSkipping line 1894: expected 2 fields, saw 3\\nSkipping line 1895: expected 2 fields, saw 3\\nSkipping line 1896: expected 2 fields, saw 3\\nSkipping line 1897: expected 2 fields, saw 3\\nSkipping line 1898: expected 2 fields, saw 3\\nSkipping line 1899: expected 2 fields, saw 3\\nSkipping line 1905: expected 2 fields, saw 3\\nSkipping line 1906: expected 2 fields, saw 3\\nSkipping line 1907: expected 2 fields, saw 3\\nSkipping line 1908: expected 2 fields, saw 3\\nSkipping line 1909: expected 2 fields, saw 3\\nSkipping line 1911: expected 2 fields, saw 3\\nSkipping line 1912: expected 2 fields, saw 3\\nSkipping line 1919: expected 2 fields, saw 3\\nSkipping line 1925: expected 2 fields, saw 3\\nSkipping line 1931: expected 2 fields, saw 3\\nSkipping line 1932: expected 2 fields, saw 3\\nSkipping line 1933: expected 2 fields, saw 3\\nSkipping line 1934: expected 2 fields, saw 3\\nSkipping line 1935: expected 2 fields, saw 3\\nSkipping line 1936: expected 2 fields, saw 3\\nSkipping line 1937: expected 2 fields, saw 3\\nSkipping line 1938: expected 2 fields, saw 3\\nSkipping line 1939: expected 2 fields, saw 3\\nSkipping line 1940: expected 2 fields, saw 4\\nSkipping line 1941: expected 2 fields, saw 3\\nSkipping line 1942: expected 2 fields, saw 3\\nSkipping line 1943: expected 2 fields, saw 3\\nSkipping line 1945: expected 2 fields, saw 3\\nSkipping line 1947: expected 2 fields, saw 3\\nSkipping line 1949: expected 2 fields, saw 3\\nSkipping line 1954: expected 2 fields, saw 3\\nSkipping line 1955: expected 2 fields, saw 3\\nSkipping line 1956: expected 2 fields, saw 3\\nSkipping line 1961: expected 2 fields, saw 3\\nSkipping line 1963: expected 2 fields, saw 3\\nSkipping line 1964: expected 2 fields, saw 3\\nSkipping line 1972: expected 2 fields, saw 4\\nSkipping line 1974: expected 2 fields, saw 3\\nSkipping line 1978: expected 2 fields, saw 3\\nSkipping line 1985: expected 2 fields, saw 3\\nSkipping line 1988: expected 2 fields, saw 3\\nSkipping line 1991: expected 2 fields, saw 3\\nSkipping line 1993: expected 2 fields, saw 3\\nSkipping line 1994: expected 2 fields, saw 4\\nSkipping line 1995: expected 2 fields, saw 4\\nSkipping line 1996: expected 2 fields, saw 3\\nSkipping line 1997: expected 2 fields, saw 3\\nSkipping line 2000: expected 2 fields, saw 3\\nSkipping line 2001: expected 2 fields, saw 3\\nSkipping line 2002: expected 2 fields, saw 4\\nSkipping line 2005: expected 2 fields, saw 3\\nSkipping line 2006: expected 2 fields, saw 3\\nSkipping line 2008: expected 2 fields, saw 3\\nSkipping line 2009: expected 2 fields, saw 3\\nSkipping line 2012: expected 2 fields, saw 3\\nSkipping line 2015: expected 2 fields, saw 4\\nSkipping line 2016: expected 2 fields, saw 3\\nSkipping line 2017: expected 2 fields, saw 3\\nSkipping line 2019: expected 2 fields, saw 3\\nSkipping line 2024: expected 2 fields, saw 3\\nSkipping line 2026: expected 2 fields, saw 3\\nSkipping line 2028: expected 2 fields, saw 3\\nSkipping line 2030: expected 2 fields, saw 3\\nSkipping line 2032: expected 2 fields, saw 3\\nSkipping line 2034: expected 2 fields, saw 3\\nSkipping line 2040: expected 2 fields, saw 3\\nSkipping line 2041: expected 2 fields, saw 4\\nSkipping line 2042: expected 2 fields, saw 3\\nSkipping line 2044: expected 2 fields, saw 3\\nSkipping line 2048: expected 2 fields, saw 3\\nSkipping line 2050: expected 2 fields, saw 3\\nSkipping line 2051: expected 2 fields, saw 3\\nSkipping line 2055: expected 2 fields, saw 3\\nSkipping line 2060: expected 2 fields, saw 3\\nSkipping line 2063: expected 2 fields, saw 4\\nSkipping line 2065: expected 2 fields, saw 3\\nSkipping line 2069: expected 2 fields, saw 3\\nSkipping line 2081: expected 2 fields, saw 3\\nSkipping line 2085: expected 2 fields, saw 3\\nSkipping line 2092: expected 2 fields, saw 3\\nSkipping line 2096: expected 2 fields, saw 3\\nSkipping line 2106: expected 2 fields, saw 3\\nSkipping line 2107: expected 2 fields, saw 3\\nSkipping line 2109: expected 2 fields, saw 3\\nSkipping line 2114: expected 2 fields, saw 3\\nSkipping line 2115: expected 2 fields, saw 3\\nSkipping line 2119: expected 2 fields, saw 5\\nSkipping line 2131: expected 2 fields, saw 3\\nSkipping line 2132: expected 2 fields, saw 3\\nSkipping line 2141: expected 2 fields, saw 3\\nSkipping line 2159: expected 2 fields, saw 4\\nSkipping line 2160: expected 2 fields, saw 3\\nSkipping line 2161: expected 2 fields, saw 3\\nSkipping line 2162: expected 2 fields, saw 3\\nSkipping line 2163: expected 2 fields, saw 3\\nSkipping line 2164: expected 2 fields, saw 3\\nSkipping line 2166: expected 2 fields, saw 3\\nSkipping line 2171: expected 2 fields, saw 3\\nSkipping line 2173: expected 2 fields, saw 3\\nSkipping line 2179: expected 2 fields, saw 3\\nSkipping line 2185: expected 2 fields, saw 4\\nSkipping line 2188: expected 2 fields, saw 3\\nSkipping line 2204: expected 2 fields, saw 3\\nSkipping line 2205: expected 2 fields, saw 3\\nSkipping line 2206: expected 2 fields, saw 3\\nSkipping line 2218: expected 2 fields, saw 3\\nSkipping line 2220: expected 2 fields, saw 3\\nSkipping line 2221: expected 2 fields, saw 3\\nSkipping line 2224: expected 2 fields, saw 3\\nSkipping line 2226: expected 2 fields, saw 3\\nSkipping line 2229: expected 2 fields, saw 3\\nSkipping line 2230: expected 2 fields, saw 3\\nSkipping line 2231: expected 2 fields, saw 3\\nSkipping line 2234: expected 2 fields, saw 3\\nSkipping line 2235: expected 2 fields, saw 3\\nSkipping line 2240: expected 2 fields, saw 4\\nSkipping line 2242: expected 2 fields, saw 4\\nSkipping line 2243: expected 2 fields, saw 4\\nSkipping line 2244: expected 2 fields, saw 3\\nSkipping line 2257: expected 2 fields, saw 3\\nSkipping line 2258: expected 2 fields, saw 3\\nSkipping line 2262: expected 2 fields, saw 3\\nSkipping line 2263: expected 2 fields, saw 3\\nSkipping line 2272: expected 2 fields, saw 3\\nSkipping line 2273: expected 2 fields, saw 3\\nSkipping line 2274: expected 2 fields, saw 4\\nSkipping line 2275: expected 2 fields, saw 3\\nSkipping line 2279: expected 2 fields, saw 3\\nSkipping line 2282: expected 2 fields, saw 3\\nSkipping line 2290: expected 2 fields, saw 4\\nSkipping line 2291: expected 2 fields, saw 3\\nSkipping line 2292: expected 2 fields, saw 3\\nSkipping line 2293: expected 2 fields, saw 3\\nSkipping line 2294: expected 2 fields, saw 3\\nSkipping line 2295: expected 2 fields, saw 3\\nSkipping line 2296: expected 2 fields, saw 3\\nSkipping line 2302: expected 2 fields, saw 4\\nSkipping line 2304: expected 2 fields, saw 3\\nSkipping line 2316: expected 2 fields, saw 3\\nSkipping line 2319: expected 2 fields, saw 3\\nSkipping line 2321: expected 2 fields, saw 3\\nSkipping line 2322: expected 2 fields, saw 4\\nSkipping line 2323: expected 2 fields, saw 3\\nSkipping line 2344: expected 2 fields, saw 3\\nSkipping line 2345: expected 2 fields, saw 3\\nSkipping line 2351: expected 2 fields, saw 3\\nSkipping line 2356: expected 2 fields, saw 3\\nSkipping line 2358: expected 2 fields, saw 3\\nSkipping line 2359: expected 2 fields, saw 3\\nSkipping line 2363: expected 2 fields, saw 3\\nSkipping line 2364: expected 2 fields, saw 3\\nSkipping line 2365: expected 2 fields, saw 3\\nSkipping line 2367: expected 2 fields, saw 3\\nSkipping line 2369: expected 2 fields, saw 3\\nSkipping line 2376: expected 2 fields, saw 3\\nSkipping line 2377: expected 2 fields, saw 3\\nSkipping line 2382: expected 2 fields, saw 3\\nSkipping line 2383: expected 2 fields, saw 3\\nSkipping line 2385: expected 2 fields, saw 3\\nSkipping line 2386: expected 2 fields, saw 4\\nSkipping line 2388: expected 2 fields, saw 3\\nSkipping line 2405: expected 2 fields, saw 3\\nSkipping line 2406: expected 2 fields, saw 3\\nSkipping line 2408: expected 2 fields, saw 3\\nSkipping line 2409: expected 2 fields, saw 3\\nSkipping line 2427: expected 2 fields, saw 3\\nSkipping line 2435: expected 2 fields, saw 3\\nSkipping line 2436: expected 2 fields, saw 3\\nSkipping line 2438: expected 2 fields, saw 3\\nSkipping line 2445: expected 2 fields, saw 3\\nSkipping line 2446: expected 2 fields, saw 3\\nSkipping line 2449: expected 2 fields, saw 3\\nSkipping line 2460: expected 2 fields, saw 3\\nSkipping line 2461: expected 2 fields, saw 3\\nSkipping line 2462: expected 2 fields, saw 4\\nSkipping line 2463: expected 2 fields, saw 3\\nSkipping line 2465: expected 2 fields, saw 4\\nSkipping line 2466: expected 2 fields, saw 3\\nSkipping line 2467: expected 2 fields, saw 3\\nSkipping line 2468: expected 2 fields, saw 3\\nSkipping line 2470: expected 2 fields, saw 3\\nSkipping line 2471: expected 2 fields, saw 3\\nSkipping line 2475: expected 2 fields, saw 3\\nSkipping line 2480: expected 2 fields, saw 3\\nSkipping line 2483: expected 2 fields, saw 3\\nSkipping line 2484: expected 2 fields, saw 3\\nSkipping line 2486: expected 2 fields, saw 3\\nSkipping line 2487: expected 2 fields, saw 3\\nSkipping line 2488: expected 2 fields, saw 3\\nSkipping line 2489: expected 2 fields, saw 3\\nSkipping line 2490: expected 2 fields, saw 3\\nSkipping line 2492: expected 2 fields, saw 4\\nSkipping line 2493: expected 2 fields, saw 3\\nSkipping line 2494: expected 2 fields, saw 3\\nSkipping line 2495: expected 2 fields, saw 3\\nSkipping line 2496: expected 2 fields, saw 3\\nSkipping line 2497: expected 2 fields, saw 3\\nSkipping line 2498: expected 2 fields, saw 3\\nSkipping line 2499: expected 2 fields, saw 3\\nSkipping line 2500: expected 2 fields, saw 3\\nSkipping line 2503: expected 2 fields, saw 3\\nSkipping line 2504: expected 2 fields, saw 3\\nSkipping line 2505: expected 2 fields, saw 3\\nSkipping line 2530: expected 2 fields, saw 3\\nSkipping line 2542: expected 2 fields, saw 4\\nSkipping line 2543: expected 2 fields, saw 4\\nSkipping line 2544: expected 2 fields, saw 3\\nSkipping line 2545: expected 2 fields, saw 3\\nSkipping line 2546: expected 2 fields, saw 3\\nSkipping line 2547: expected 2 fields, saw 3\\nSkipping line 2548: expected 2 fields, saw 3\\nSkipping line 2549: expected 2 fields, saw 3\\nSkipping line 2550: expected 2 fields, saw 3\\nSkipping line 2556: expected 2 fields, saw 3\\nSkipping line 2558: expected 2 fields, saw 3\\nSkipping line 2559: expected 2 fields, saw 4\\nSkipping line 2560: expected 2 fields, saw 3\\nSkipping line 2561: expected 2 fields, saw 4\\nSkipping line 2563: expected 2 fields, saw 3\\nSkipping line 2564: expected 2 fields, saw 3\\nSkipping line 2566: expected 2 fields, saw 3\\nSkipping line 2567: expected 2 fields, saw 3\\nSkipping line 2568: expected 2 fields, saw 3\\nSkipping line 2574: expected 2 fields, saw 3\\nSkipping line 2579: expected 2 fields, saw 3\\nSkipping line 2581: expected 2 fields, saw 3\\nSkipping line 2582: expected 2 fields, saw 3\\nSkipping line 2583: expected 2 fields, saw 4\\nSkipping line 2584: expected 2 fields, saw 3\\nSkipping line 2595: expected 2 fields, saw 3\\nSkipping line 2596: expected 2 fields, saw 3\\nSkipping line 2597: expected 2 fields, saw 3\\nSkipping line 2602: expected 2 fields, saw 3\\nSkipping line 2612: expected 2 fields, saw 3\\nSkipping line 2615: expected 2 fields, saw 3\\nSkipping line 2616: expected 2 fields, saw 3\\nSkipping line 2617: expected 2 fields, saw 3\\nSkipping line 2621: expected 2 fields, saw 3\\nSkipping line 2624: expected 2 fields, saw 3\\nSkipping line 2639: expected 2 fields, saw 3\\nSkipping line 2647: expected 2 fields, saw 4\\nSkipping line 2648: expected 2 fields, saw 3\\nSkipping line 2649: expected 2 fields, saw 4\\nSkipping line 2652: expected 2 fields, saw 3\\nSkipping line 2653: expected 2 fields, saw 3\\nSkipping line 2655: expected 2 fields, saw 3\\nSkipping line 2657: expected 2 fields, saw 4\\nSkipping line 2663: expected 2 fields, saw 3\\nSkipping line 2665: expected 2 fields, saw 3\\nSkipping line 2667: expected 2 fields, saw 3\\nSkipping line 2668: expected 2 fields, saw 3\\nSkipping line 2671: expected 2 fields, saw 3\\nSkipping line 2673: expected 2 fields, saw 4\\nSkipping line 2675: expected 2 fields, saw 3\\nSkipping line 2677: expected 2 fields, saw 3\\nSkipping line 2678: expected 2 fields, saw 3\\nSkipping line 2679: expected 2 fields, saw 5\\nSkipping line 2680: expected 2 fields, saw 3\\nSkipping line 2682: expected 2 fields, saw 4\\nSkipping line 2686: expected 2 fields, saw 4\\nSkipping line 2704: expected 2 fields, saw 3\\nSkipping line 2705: expected 2 fields, saw 3\\nSkipping line 2706: expected 2 fields, saw 3\\nSkipping line 2707: expected 2 fields, saw 3\\nSkipping line 2709: expected 2 fields, saw 3\\nSkipping line 2710: expected 2 fields, saw 3\\nSkipping line 2711: expected 2 fields, saw 3\\nSkipping line 2713: expected 2 fields, saw 3\\nSkipping line 2714: expected 2 fields, saw 3\\nSkipping line 2715: expected 2 fields, saw 4\\nSkipping line 2716: expected 2 fields, saw 3\\nSkipping line 2717: expected 2 fields, saw 3\\nSkipping line 2719: expected 2 fields, saw 3\\nSkipping line 2720: expected 2 fields, saw 4\\nSkipping line 2721: expected 2 fields, saw 3\\nSkipping line 2722: expected 2 fields, saw 3\\nSkipping line 2723: expected 2 fields, saw 3\\nSkipping line 2725: expected 2 fields, saw 3\\nSkipping line 2726: expected 2 fields, saw 3\\nSkipping line 2727: expected 2 fields, saw 4\\nSkipping line 2728: expected 2 fields, saw 3\\nSkipping line 2729: expected 2 fields, saw 3\\nSkipping line 2730: expected 2 fields, saw 3\\nSkipping line 2731: expected 2 fields, saw 3\\nSkipping line 2732: expected 2 fields, saw 3\\nSkipping line 2733: expected 2 fields, saw 3\\nSkipping line 2734: expected 2 fields, saw 3\\nSkipping line 2735: expected 2 fields, saw 3\\nSkipping line 2736: expected 2 fields, saw 3\\nSkipping line 2739: expected 2 fields, saw 3\\nSkipping line 2742: expected 2 fields, saw 3\\nSkipping line 2744: expected 2 fields, saw 3\\nSkipping line 2746: expected 2 fields, saw 3\\nSkipping line 2747: expected 2 fields, saw 3\\nSkipping line 2749: expected 2 fields, saw 3\\nSkipping line 2750: expected 2 fields, saw 3\\nSkipping line 2751: expected 2 fields, saw 3\\nSkipping line 2752: expected 2 fields, saw 3\\nSkipping line 2753: expected 2 fields, saw 3\\nSkipping line 2754: expected 2 fields, saw 3\\nSkipping line 2755: expected 2 fields, saw 3\\nSkipping line 2756: expected 2 fields, saw 3\\nSkipping line 2759: expected 2 fields, saw 3\\nSkipping line 2760: expected 2 fields, saw 3\\nSkipping line 2761: expected 2 fields, saw 3\\nSkipping line 2763: expected 2 fields, saw 3\\nSkipping line 2764: expected 2 fields, saw 3\\nSkipping line 2765: expected 2 fields, saw 3\\nSkipping line 2766: expected 2 fields, saw 3\\nSkipping line 2775: expected 2 fields, saw 4\\nSkipping line 2778: expected 2 fields, saw 3\\nSkipping line 2779: expected 2 fields, saw 3\\nSkipping line 2781: expected 2 fields, saw 3\\nSkipping line 2782: expected 2 fields, saw 3\\nSkipping line 2783: expected 2 fields, saw 3\\nSkipping line 2784: expected 2 fields, saw 3\\nSkipping line 2787: expected 2 fields, saw 3\\nSkipping line 2790: expected 2 fields, saw 3\\nSkipping line 2792: expected 2 fields, saw 3\\nSkipping line 2794: expected 2 fields, saw 3\\nSkipping line 2796: expected 2 fields, saw 3\\nSkipping line 2797: expected 2 fields, saw 3\\nSkipping line 2805: expected 2 fields, saw 3\\nSkipping line 2807: expected 2 fields, saw 3\\nSkipping line 2809: expected 2 fields, saw 3\\nSkipping line 2810: expected 2 fields, saw 3\\nSkipping line 2811: expected 2 fields, saw 3\\nSkipping line 2812: expected 2 fields, saw 3\\nSkipping line 2813: expected 2 fields, saw 3\\nSkipping line 2814: expected 2 fields, saw 3\\nSkipping line 2818: expected 2 fields, saw 4\\nSkipping line 2819: expected 2 fields, saw 3\\nSkipping line 2820: expected 2 fields, saw 3\\nSkipping line 2822: expected 2 fields, saw 3\\nSkipping line 2823: expected 2 fields, saw 3\\nSkipping line 2824: expected 2 fields, saw 3\\nSkipping line 2825: expected 2 fields, saw 3\\nSkipping line 2826: expected 2 fields, saw 3\\nSkipping line 2827: expected 2 fields, saw 4\\nSkipping line 2828: expected 2 fields, saw 3\\nSkipping line 2829: expected 2 fields, saw 3\\nSkipping line 2830: expected 2 fields, saw 3\\nSkipping line 2836: expected 2 fields, saw 3\\nSkipping line 2839: expected 2 fields, saw 3\\nSkipping line 2840: expected 2 fields, saw 3\\nSkipping line 2842: expected 2 fields, saw 3\\nSkipping line 2845: expected 2 fields, saw 3\\nSkipping line 2846: expected 2 fields, saw 3\\nSkipping line 2847: expected 2 fields, saw 3\\nSkipping line 2848: expected 2 fields, saw 3\\nSkipping line 2853: expected 2 fields, saw 3\\nSkipping line 2854: expected 2 fields, saw 4\\nSkipping line 2856: expected 2 fields, saw 3\\nSkipping line 2857: expected 2 fields, saw 3\\nSkipping line 2858: expected 2 fields, saw 3\\nSkipping line 2863: expected 2 fields, saw 3\\nSkipping line 2864: expected 2 fields, saw 3\\nSkipping line 2866: expected 2 fields, saw 3\\nSkipping line 2874: expected 2 fields, saw 3\\nSkipping line 2875: expected 2 fields, saw 3\\nSkipping line 2877: expected 2 fields, saw 3\\nSkipping line 2879: expected 2 fields, saw 3\\nSkipping line 2880: expected 2 fields, saw 3\\nSkipping line 2881: expected 2 fields, saw 3\\nSkipping line 2882: expected 2 fields, saw 3\\nSkipping line 2883: expected 2 fields, saw 3\\nSkipping line 2884: expected 2 fields, saw 3\\nSkipping line 2885: expected 2 fields, saw 3\\nSkipping line 2886: expected 2 fields, saw 3\\nSkipping line 2887: expected 2 fields, saw 3\\nSkipping line 2889: expected 2 fields, saw 3\\nSkipping line 2890: expected 2 fields, saw 3\\nSkipping line 2891: expected 2 fields, saw 3\\nSkipping line 2892: expected 2 fields, saw 3\\nSkipping line 2893: expected 2 fields, saw 3\\nSkipping line 2894: expected 2 fields, saw 3\\nSkipping line 2895: expected 2 fields, saw 3\\nSkipping line 2897: expected 2 fields, saw 3\\nSkipping line 2899: expected 2 fields, saw 3\\nSkipping line 2901: expected 2 fields, saw 3\\nSkipping line 2902: expected 2 fields, saw 3\\nSkipping line 2903: expected 2 fields, saw 3\\nSkipping line 2904: expected 2 fields, saw 3\\nSkipping line 2905: expected 2 fields, saw 3\\nSkipping line 2907: expected 2 fields, saw 3\\nSkipping line 2910: expected 2 fields, saw 3\\nSkipping line 2911: expected 2 fields, saw 3\\nSkipping line 2913: expected 2 fields, saw 3\\nSkipping line 2914: expected 2 fields, saw 3\\nSkipping line 2915: expected 2 fields, saw 3\\nSkipping line 2916: expected 2 fields, saw 3\\nSkipping line 2918: expected 2 fields, saw 3\\nSkipping line 2919: expected 2 fields, saw 3\\nSkipping line 2920: expected 2 fields, saw 3\\nSkipping line 2921: expected 2 fields, saw 3\\nSkipping line 2923: expected 2 fields, saw 3\\nSkipping line 2925: expected 2 fields, saw 3\\nSkipping line 2928: expected 2 fields, saw 3\\nSkipping line 2929: expected 2 fields, saw 3\\nSkipping line 2930: expected 2 fields, saw 3\\nSkipping line 2936: expected 2 fields, saw 3\\nSkipping line 2941: expected 2 fields, saw 3\\nSkipping line 2942: expected 2 fields, saw 3\\nSkipping line 2943: expected 2 fields, saw 3\\nSkipping line 2944: expected 2 fields, saw 3\\nSkipping line 2948: expected 2 fields, saw 3\\nSkipping line 2949: expected 2 fields, saw 3\\nSkipping line 2951: expected 2 fields, saw 3\\nSkipping line 2952: expected 2 fields, saw 4\\nSkipping line 2954: expected 2 fields, saw 3\\nSkipping line 2955: expected 2 fields, saw 3\\nSkipping line 2956: expected 2 fields, saw 3\\nSkipping line 2957: expected 2 fields, saw 3\\nSkipping line 2958: expected 2 fields, saw 3\\nSkipping line 2964: expected 2 fields, saw 3\\nSkipping line 2968: expected 2 fields, saw 3\\nSkipping line 2969: expected 2 fields, saw 3\\nSkipping line 2970: expected 2 fields, saw 4\\nSkipping line 2971: expected 2 fields, saw 3\\nSkipping line 2972: expected 2 fields, saw 3\\nSkipping line 2974: expected 2 fields, saw 4\\nSkipping line 2975: expected 2 fields, saw 3\\nSkipping line 2976: expected 2 fields, saw 3\\nSkipping line 2977: expected 2 fields, saw 3\\nSkipping line 2979: expected 2 fields, saw 3\\nSkipping line 2980: expected 2 fields, saw 4\\nSkipping line 2982: expected 2 fields, saw 3\\nSkipping line 2984: expected 2 fields, saw 4\\nSkipping line 2986: expected 2 fields, saw 3\\nSkipping line 2988: expected 2 fields, saw 3\\nSkipping line 2989: expected 2 fields, saw 3\\nSkipping line 2990: expected 2 fields, saw 3\\nSkipping line 2991: expected 2 fields, saw 3\\nSkipping line 2992: expected 2 fields, saw 3\\nSkipping line 2993: expected 2 fields, saw 3\\nSkipping line 2998: expected 2 fields, saw 3\\nSkipping line 3000: expected 2 fields, saw 3\\nSkipping line 3001: expected 2 fields, saw 3\\nSkipping line 3003: expected 2 fields, saw 3\\nSkipping line 3004: expected 2 fields, saw 3\\nSkipping line 3006: expected 2 fields, saw 3\\nSkipping line 3007: expected 2 fields, saw 3\\nSkipping line 3012: expected 2 fields, saw 3\\nSkipping line 3014: expected 2 fields, saw 4\\nSkipping line 3015: expected 2 fields, saw 3\\nSkipping line 3016: expected 2 fields, saw 3\\nSkipping line 3018: expected 2 fields, saw 3\\nSkipping line 3019: expected 2 fields, saw 3\\nSkipping line 3022: expected 2 fields, saw 3\\nSkipping line 3024: expected 2 fields, saw 3\\nSkipping line 3025: expected 2 fields, saw 4\\nSkipping line 3027: expected 2 fields, saw 3\\nSkipping line 3028: expected 2 fields, saw 3\\nSkipping line 3030: expected 2 fields, saw 3\\nSkipping line 3033: expected 2 fields, saw 3\\nSkipping line 3035: expected 2 fields, saw 3\\nSkipping line 3039: expected 2 fields, saw 3\\nSkipping line 3045: expected 2 fields, saw 3\\nSkipping line 3051: expected 2 fields, saw 3\\nSkipping line 3060: expected 2 fields, saw 3\\nSkipping line 3061: expected 2 fields, saw 3\\nSkipping line 3062: expected 2 fields, saw 3\\nSkipping line 3065: expected 2 fields, saw 3\\nSkipping line 3067: expected 2 fields, saw 3\\nSkipping line 3071: expected 2 fields, saw 4\\nSkipping line 3072: expected 2 fields, saw 3\\nSkipping line 3073: expected 2 fields, saw 3\\nSkipping line 3074: expected 2 fields, saw 3\\nSkipping line 3078: expected 2 fields, saw 4\\nSkipping line 3081: expected 2 fields, saw 3\\nSkipping line 3082: expected 2 fields, saw 4\\nSkipping line 3083: expected 2 fields, saw 3\\nSkipping line 3085: expected 2 fields, saw 4\\nSkipping line 3087: expected 2 fields, saw 3\\nSkipping line 3089: expected 2 fields, saw 4\\nSkipping line 3090: expected 2 fields, saw 3\\nSkipping line 3091: expected 2 fields, saw 3\\nSkipping line 3103: expected 2 fields, saw 3\\nSkipping line 3105: expected 2 fields, saw 3\\nSkipping line 3106: expected 2 fields, saw 3\\nSkipping line 3107: expected 2 fields, saw 3\\nSkipping line 3109: expected 2 fields, saw 4\\nSkipping line 3110: expected 2 fields, saw 3\\nSkipping line 3111: expected 2 fields, saw 3\\nSkipping line 3112: expected 2 fields, saw 3\\nSkipping line 3113: expected 2 fields, saw 3\\nSkipping line 3114: expected 2 fields, saw 3\\nSkipping line 3125: expected 2 fields, saw 3\\nSkipping line 3127: expected 2 fields, saw 3\\nSkipping line 3129: expected 2 fields, saw 3\\nSkipping line 3130: expected 2 fields, saw 3\\nSkipping line 3139: expected 2 fields, saw 3\\nSkipping line 3140: expected 2 fields, saw 3\\nSkipping line 3141: expected 2 fields, saw 3\\nSkipping line 3145: expected 2 fields, saw 3\\nSkipping line 3148: expected 2 fields, saw 3\\nSkipping line 3149: expected 2 fields, saw 3\\nSkipping line 3150: expected 2 fields, saw 3\\nSkipping line 3152: expected 2 fields, saw 3\\nSkipping line 3153: expected 2 fields, saw 3\\nSkipping line 3154: expected 2 fields, saw 3\\nSkipping line 3155: expected 2 fields, saw 3\\nSkipping line 3156: expected 2 fields, saw 3\\nSkipping line 3157: expected 2 fields, saw 3\\nSkipping line 3159: expected 2 fields, saw 3\\nSkipping line 3160: expected 2 fields, saw 3\\nSkipping line 3163: expected 2 fields, saw 3\\nSkipping line 3164: expected 2 fields, saw 3\\nSkipping line 3165: expected 2 fields, saw 3\\nSkipping line 3167: expected 2 fields, saw 3\\nSkipping line 3171: expected 2 fields, saw 3\\nSkipping line 3175: expected 2 fields, saw 3\\nSkipping line 3179: expected 2 fields, saw 3\\nSkipping line 3182: expected 2 fields, saw 3\\nSkipping line 3186: expected 2 fields, saw 3\\nSkipping line 3188: expected 2 fields, saw 3\\nSkipping line 3194: expected 2 fields, saw 3\\nSkipping line 3196: expected 2 fields, saw 4\\nSkipping line 3201: expected 2 fields, saw 4\\nSkipping line 3202: expected 2 fields, saw 4\\nSkipping line 3203: expected 2 fields, saw 3\\nSkipping line 3205: expected 2 fields, saw 3\\nSkipping line 3207: expected 2 fields, saw 3\\nSkipping line 3208: expected 2 fields, saw 3\\nSkipping line 3211: expected 2 fields, saw 3\\nSkipping line 3213: expected 2 fields, saw 3\\nSkipping line 3214: expected 2 fields, saw 3\\nSkipping line 3215: expected 2 fields, saw 3\\nSkipping line 3216: expected 2 fields, saw 3\\nSkipping line 3217: expected 2 fields, saw 3\\nSkipping line 3226: expected 2 fields, saw 3\\nSkipping line 3238: expected 2 fields, saw 4\\nSkipping line 3240: expected 2 fields, saw 3\\nSkipping line 3241: expected 2 fields, saw 3\\nSkipping line 3245: expected 2 fields, saw 3\\nSkipping line 3249: expected 2 fields, saw 3\\nSkipping line 3259: expected 2 fields, saw 3\\nSkipping line 3260: expected 2 fields, saw 3\\nSkipping line 3270: expected 2 fields, saw 3\\nSkipping line 3271: expected 2 fields, saw 3\\nSkipping line 3283: expected 2 fields, saw 3\\nSkipping line 3287: expected 2 fields, saw 3\\nSkipping line 3288: expected 2 fields, saw 4\\nSkipping line 3289: expected 2 fields, saw 4\\nSkipping line 3294: expected 2 fields, saw 4\\nSkipping line 3295: expected 2 fields, saw 4\\nSkipping line 3296: expected 2 fields, saw 3\\nSkipping line 3301: expected 2 fields, saw 3\\nSkipping line 3302: expected 2 fields, saw 4\\nSkipping line 3303: expected 2 fields, saw 3\\nSkipping line 3304: expected 2 fields, saw 4\\nSkipping line 3305: expected 2 fields, saw 3\\nSkipping line 3308: expected 2 fields, saw 3\\nSkipping line 3309: expected 2 fields, saw 3\\nSkipping line 3314: expected 2 fields, saw 5\\nSkipping line 3316: expected 2 fields, saw 4\\nSkipping line 3317: expected 2 fields, saw 3\\nSkipping line 3320: expected 2 fields, saw 3\\nSkipping line 3328: expected 2 fields, saw 3\\nSkipping line 3329: expected 2 fields, saw 4\\nSkipping line 3349: expected 2 fields, saw 3\\nSkipping line 3350: expected 2 fields, saw 3\\nSkipping line 3351: expected 2 fields, saw 3\\nSkipping line 3353: expected 2 fields, saw 4\\nSkipping line 3354: expected 2 fields, saw 3\\nSkipping line 3355: expected 2 fields, saw 3\\nSkipping line 3357: expected 2 fields, saw 3\\nSkipping line 3358: expected 2 fields, saw 3\\nSkipping line 3359: expected 2 fields, saw 4\\nSkipping line 3361: expected 2 fields, saw 3\\nSkipping line 3363: expected 2 fields, saw 3\\nSkipping line 3369: expected 2 fields, saw 3\\nSkipping line 3374: expected 2 fields, saw 4\\nSkipping line 3376: expected 2 fields, saw 4\\nSkipping line 3377: expected 2 fields, saw 3\\nSkipping line 3379: expected 2 fields, saw 3\\nSkipping line 3380: expected 2 fields, saw 3\\nSkipping line 3381: expected 2 fields, saw 3\\nSkipping line 3382: expected 2 fields, saw 3\\nSkipping line 3384: expected 2 fields, saw 3\\nSkipping line 3385: expected 2 fields, saw 3\\nSkipping line 3388: expected 2 fields, saw 3\\nSkipping line 3389: expected 2 fields, saw 3\\nSkipping line 3392: expected 2 fields, saw 3\\nSkipping line 3394: expected 2 fields, saw 3\\nSkipping line 3395: expected 2 fields, saw 3\\nSkipping line 3403: expected 2 fields, saw 3\\nSkipping line 3404: expected 2 fields, saw 5\\nSkipping line 3407: expected 2 fields, saw 3\\nSkipping line 3409: expected 2 fields, saw 3\\nSkipping line 3410: expected 2 fields, saw 3\\nSkipping line 3411: expected 2 fields, saw 3\\nSkipping line 3412: expected 2 fields, saw 3\\nSkipping line 3421: expected 2 fields, saw 3\\nSkipping line 3440: expected 2 fields, saw 3\\nSkipping line 3446: expected 2 fields, saw 3\\nSkipping line 3447: expected 2 fields, saw 3\\nSkipping line 3450: expected 2 fields, saw 3\\nSkipping line 3457: expected 2 fields, saw 3\\nSkipping line 3458: expected 2 fields, saw 3\\nSkipping line 3459: expected 2 fields, saw 3\\nSkipping line 3460: expected 2 fields, saw 3\\nSkipping line 3461: expected 2 fields, saw 3\\nSkipping line 3462: expected 2 fields, saw 3\\nSkipping line 3463: expected 2 fields, saw 3\\nSkipping line 3464: expected 2 fields, saw 3\\nSkipping line 3465: expected 2 fields, saw 3\\nSkipping line 3466: expected 2 fields, saw 3\\nSkipping line 3467: expected 2 fields, saw 3\\nSkipping line 3468: expected 2 fields, saw 3\\nSkipping line 3469: expected 2 fields, saw 3\\nSkipping line 3473: expected 2 fields, saw 3\\nSkipping line 3477: expected 2 fields, saw 3\\nSkipping line 3478: expected 2 fields, saw 3\\nSkipping line 3479: expected 2 fields, saw 3\\nSkipping line 3480: expected 2 fields, saw 3\\nSkipping line 3481: expected 2 fields, saw 3\\nSkipping line 3484: expected 2 fields, saw 3\\nSkipping line 3485: expected 2 fields, saw 3\\nSkipping line 3487: expected 2 fields, saw 3\\nSkipping line 3488: expected 2 fields, saw 3\\nSkipping line 3498: expected 2 fields, saw 3\\nSkipping line 3499: expected 2 fields, saw 3\\nSkipping line 3504: expected 2 fields, saw 3\\nSkipping line 3505: expected 2 fields, saw 3\\nSkipping line 3508: expected 2 fields, saw 3\\nSkipping line 3509: expected 2 fields, saw 3\\nSkipping line 3510: expected 2 fields, saw 3\\nSkipping line 3511: expected 2 fields, saw 3\\nSkipping line 3512: expected 2 fields, saw 3\\nSkipping line 3522: expected 2 fields, saw 3\\nSkipping line 3523: expected 2 fields, saw 3\\nSkipping line 3525: expected 2 fields, saw 3\\nSkipping line 3526: expected 2 fields, saw 3\\nSkipping line 3527: expected 2 fields, saw 3\\nSkipping line 3532: expected 2 fields, saw 3\\nSkipping line 3533: expected 2 fields, saw 3\\nSkipping line 3537: expected 2 fields, saw 3\\nSkipping line 3541: expected 2 fields, saw 3\\nSkipping line 3544: expected 2 fields, saw 3\\nSkipping line 3581: expected 2 fields, saw 3\\nSkipping line 3584: expected 2 fields, saw 3\\nSkipping line 3586: expected 2 fields, saw 4\\nSkipping line 3595: expected 2 fields, saw 3\\nSkipping line 3596: expected 2 fields, saw 3\\nSkipping line 3597: expected 2 fields, saw 4\\nSkipping line 3599: expected 2 fields, saw 3\\nSkipping line 3601: expected 2 fields, saw 3\\nSkipping line 3603: expected 2 fields, saw 3\\nSkipping line 3606: expected 2 fields, saw 3\\nSkipping line 3611: expected 2 fields, saw 3\\nSkipping line 3612: expected 2 fields, saw 3\\nSkipping line 3615: expected 2 fields, saw 4\\nSkipping line 3616: expected 2 fields, saw 3\\nSkipping line 3624: expected 2 fields, saw 3\\nSkipping line 3626: expected 2 fields, saw 3\\nSkipping line 3629: expected 2 fields, saw 3\\nSkipping line 3630: expected 2 fields, saw 4\\nSkipping line 3631: expected 2 fields, saw 4\\nSkipping line 3633: expected 2 fields, saw 3\\nSkipping line 3641: expected 2 fields, saw 3\\nSkipping line 3645: expected 2 fields, saw 3\\nSkipping line 3646: expected 2 fields, saw 3\\nSkipping line 3647: expected 2 fields, saw 3\\nSkipping line 3648: expected 2 fields, saw 3\\nSkipping line 3652: expected 2 fields, saw 3\\nSkipping line 3657: expected 2 fields, saw 3\\nSkipping line 3659: expected 2 fields, saw 3\\nSkipping line 3664: expected 2 fields, saw 3\\nSkipping line 3671: expected 2 fields, saw 3\\nSkipping line 3672: expected 2 fields, saw 4\\nSkipping line 3673: expected 2 fields, saw 3\\nSkipping line 3674: expected 2 fields, saw 3\\nSkipping line 3693: expected 2 fields, saw 3\\nSkipping line 3694: expected 2 fields, saw 3\\nSkipping line 3696: expected 2 fields, saw 3\\nSkipping line 3698: expected 2 fields, saw 3\\nSkipping line 3700: expected 2 fields, saw 3\\nSkipping line 3708: expected 2 fields, saw 3\\nSkipping line 3726: expected 2 fields, saw 3\\nSkipping line 3727: expected 2 fields, saw 3\\nSkipping line 3730: expected 2 fields, saw 3\\nSkipping line 3731: expected 2 fields, saw 3\\nSkipping line 3756: expected 2 fields, saw 3\\nSkipping line 3762: expected 2 fields, saw 3\\nSkipping line 3768: expected 2 fields, saw 3\\nSkipping line 3769: expected 2 fields, saw 3\\nSkipping line 3770: expected 2 fields, saw 4\\nSkipping line 3772: expected 2 fields, saw 3\\nSkipping line 3784: expected 2 fields, saw 3\\nSkipping line 3785: expected 2 fields, saw 3\\nSkipping line 3786: expected 2 fields, saw 4\\nSkipping line 3788: expected 2 fields, saw 3\\nSkipping line 3802: expected 2 fields, saw 3\\nSkipping line 3825: expected 2 fields, saw 3\\nSkipping line 3829: expected 2 fields, saw 3\\nSkipping line 3837: expected 2 fields, saw 4\\nSkipping line 3839: expected 2 fields, saw 3\\nSkipping line 3841: expected 2 fields, saw 3\\nSkipping line 3879: expected 2 fields, saw 3\\nSkipping line 3892: expected 2 fields, saw 3\\nSkipping line 3893: expected 2 fields, saw 3\\nSkipping line 3895: expected 2 fields, saw 3\\nSkipping line 3896: expected 2 fields, saw 3\\nSkipping line 3897: expected 2 fields, saw 3\\nSkipping line 3898: expected 2 fields, saw 3\\nSkipping line 3899: expected 2 fields, saw 3\\nSkipping line 3900: expected 2 fields, saw 3\\nSkipping line 3901: expected 2 fields, saw 3\\nSkipping line 3904: expected 2 fields, saw 3\\nSkipping line 3905: expected 2 fields, saw 3\\nSkipping line 3906: expected 2 fields, saw 3\\nSkipping line 3909: expected 2 fields, saw 3\\nSkipping line 3910: expected 2 fields, saw 3\\nSkipping line 3911: expected 2 fields, saw 3\\nSkipping line 3916: expected 2 fields, saw 3\\nSkipping line 3917: expected 2 fields, saw 3\\nSkipping line 3920: expected 2 fields, saw 3\\nSkipping line 3921: expected 2 fields, saw 3\\nSkipping line 3923: expected 2 fields, saw 3\\nSkipping line 3924: expected 2 fields, saw 3\\nSkipping line 3925: expected 2 fields, saw 3\\nSkipping line 3926: expected 2 fields, saw 3\\nSkipping line 3927: expected 2 fields, saw 3\\nSkipping line 3928: expected 2 fields, saw 3\\nSkipping line 3929: expected 2 fields, saw 3\\nSkipping line 3930: expected 2 fields, saw 3\\nSkipping line 3931: expected 2 fields, saw 3\\nSkipping line 3933: expected 2 fields, saw 3\\nSkipping line 3935: expected 2 fields, saw 3\\nSkipping line 3936: expected 2 fields, saw 3\\nSkipping line 3938: expected 2 fields, saw 3\\nSkipping line 3941: expected 2 fields, saw 3\\nSkipping line 3942: expected 2 fields, saw 3\\nSkipping line 3943: expected 2 fields, saw 3\\nSkipping line 3944: expected 2 fields, saw 3\\nSkipping line 3945: expected 2 fields, saw 3\\nSkipping line 3946: expected 2 fields, saw 3\\nSkipping line 3948: expected 2 fields, saw 3\\nSkipping line 3949: expected 2 fields, saw 3\\nSkipping line 3950: expected 2 fields, saw 3\\nSkipping line 3951: expected 2 fields, saw 3\\nSkipping line 3952: expected 2 fields, saw 3\\nSkipping line 3953: expected 2 fields, saw 3\\nSkipping line 3954: expected 2 fields, saw 3\\nSkipping line 3997: expected 2 fields, saw 3\\nSkipping line 3998: expected 2 fields, saw 3\\nSkipping line 4006: expected 2 fields, saw 3\\nSkipping line 4007: expected 2 fields, saw 3\\nSkipping line 4019: expected 2 fields, saw 3\\nSkipping line 4020: expected 2 fields, saw 3\\nSkipping line 4021: expected 2 fields, saw 3\\nSkipping line 4022: expected 2 fields, saw 3\\nSkipping line 4023: expected 2 fields, saw 3\\nSkipping line 4024: expected 2 fields, saw 3\\nSkipping line 4025: expected 2 fields, saw 3\\nSkipping line 4026: expected 2 fields, saw 3\\nSkipping line 4027: expected 2 fields, saw 3\\nSkipping line 4028: expected 2 fields, saw 3\\nSkipping line 4029: expected 2 fields, saw 3\\nSkipping line 4030: expected 2 fields, saw 3\\nSkipping line 4031: expected 2 fields, saw 3\\nSkipping line 4032: expected 2 fields, saw 3\\nSkipping line 4033: expected 2 fields, saw 3\\nSkipping line 4034: expected 2 fields, saw 3\\nSkipping line 4035: expected 2 fields, saw 3\\nSkipping line 4036: expected 2 fields, saw 3\\nSkipping line 4037: expected 2 fields, saw 3\\nSkipping line 4038: expected 2 fields, saw 3\\nSkipping line 4039: expected 2 fields, saw 3\\nSkipping line 4040: expected 2 fields, saw 3\\nSkipping line 4041: expected 2 fields, saw 3\\nSkipping line 4042: expected 2 fields, saw 3\\nSkipping line 4043: expected 2 fields, saw 3\\nSkipping line 4044: expected 2 fields, saw 3\\nSkipping line 4045: expected 2 fields, saw 3\\nSkipping line 4046: expected 2 fields, saw 3\\nSkipping line 4047: expected 2 fields, saw 3\\nSkipping line 4048: expected 2 fields, saw 3\\nSkipping line 4049: expected 2 fields, saw 3\\nSkipping line 4050: expected 2 fields, saw 3\\nSkipping line 4051: expected 2 fields, saw 3\\nSkipping line 4052: expected 2 fields, saw 3\\nSkipping line 4053: expected 2 fields, saw 3\\nSkipping line 4054: expected 2 fields, saw 3\\nSkipping line 4055: expected 2 fields, saw 3\\nSkipping line 4056: expected 2 fields, saw 3\\nSkipping line 4057: expected 2 fields, saw 3\\nSkipping line 4058: expected 2 fields, saw 3\\nSkipping line 4059: expected 2 fields, saw 3\\nSkipping line 4060: expected 2 fields, saw 3\\nSkipping line 4061: expected 2 fields, saw 3\\nSkipping line 4062: expected 2 fields, saw 3\\nSkipping line 4063: expected 2 fields, saw 3\\nSkipping line 4064: expected 2 fields, saw 3\\nSkipping line 4065: expected 2 fields, saw 3\\nSkipping line 4066: expected 2 fields, saw 3\\nSkipping line 4067: expected 2 fields, saw 4\\nSkipping line 4068: expected 2 fields, saw 3\\nSkipping line 4069: expected 2 fields, saw 3\\nSkipping line 4070: expected 2 fields, saw 3\\nSkipping line 4071: expected 2 fields, saw 3\\nSkipping line 4072: expected 2 fields, saw 3\\nSkipping line 4073: expected 2 fields, saw 3\\nSkipping line 4074: expected 2 fields, saw 3\\nSkipping line 4075: expected 2 fields, saw 3\\nSkipping line 4076: expected 2 fields, saw 3\\nSkipping line 4077: expected 2 fields, saw 3\\nSkipping line 4078: expected 2 fields, saw 3\\nSkipping line 4079: expected 2 fields, saw 3\\nSkipping line 4080: expected 2 fields, saw 3\\nSkipping line 4081: expected 2 fields, saw 3\\nSkipping line 4082: expected 2 fields, saw 3\\nSkipping line 4083: expected 2 fields, saw 3\\nSkipping line 4084: expected 2 fields, saw 3\\nSkipping line 4085: expected 2 fields, saw 3\\nSkipping line 4086: expected 2 fields, saw 3\\nSkipping line 4087: expected 2 fields, saw 3\\nSkipping line 4088: expected 2 fields, saw 3\\nSkipping line 4089: expected 2 fields, saw 3\\nSkipping line 4090: expected 2 fields, saw 3\\nSkipping line 4091: expected 2 fields, saw 3\\nSkipping line 4092: expected 2 fields, saw 3\\nSkipping line 4093: expected 2 fields, saw 3\\nSkipping line 4094: expected 2 fields, saw 3\\nSkipping line 4095: expected 2 fields, saw 3\\nSkipping line 4096: expected 2 fields, saw 3\\nSkipping line 4097: expected 2 fields, saw 3\\nSkipping line 4098: expected 2 fields, saw 3\\nSkipping line 4099: expected 2 fields, saw 4\\nSkipping line 4100: expected 2 fields, saw 3\\nSkipping line 4101: expected 2 fields, saw 3\\nSkipping line 4102: expected 2 fields, saw 3\\nSkipping line 4103: expected 2 fields, saw 3\\nSkipping line 4104: expected 2 fields, saw 3\\nSkipping line 4105: expected 2 fields, saw 3\\nSkipping line 4106: expected 2 fields, saw 3\\nSkipping line 4107: expected 2 fields, saw 3\\nSkipping line 4108: expected 2 fields, saw 3\\nSkipping line 4109: expected 2 fields, saw 3\\nSkipping line 4110: expected 2 fields, saw 3\\nSkipping line 4111: expected 2 fields, saw 3\\nSkipping line 4112: expected 2 fields, saw 3\\nSkipping line 4113: expected 2 fields, saw 3\\nSkipping line 4114: expected 2 fields, saw 3\\nSkipping line 4115: expected 2 fields, saw 3\\nSkipping line 4116: expected 2 fields, saw 3\\nSkipping line 4117: expected 2 fields, saw 3\\nSkipping line 4118: expected 2 fields, saw 3\\nSkipping line 4119: expected 2 fields, saw 3\\nSkipping line 4120: expected 2 fields, saw 3\\nSkipping line 4121: expected 2 fields, saw 3\\nSkipping line 4122: expected 2 fields, saw 3\\nSkipping line 4123: expected 2 fields, saw 3\\nSkipping line 4124: expected 2 fields, saw 3\\nSkipping line 4125: expected 2 fields, saw 3\\nSkipping line 4126: expected 2 fields, saw 3\\nSkipping line 4127: expected 2 fields, saw 3\\nSkipping line 4128: expected 2 fields, saw 3\\nSkipping line 4129: expected 2 fields, saw 3\\nSkipping line 4130: expected 2 fields, saw 3\\nSkipping line 4131: expected 2 fields, saw 3\\nSkipping line 4132: expected 2 fields, saw 3\\nSkipping line 4133: expected 2 fields, saw 3\\nSkipping line 4134: expected 2 fields, saw 3\\nSkipping line 4135: expected 2 fields, saw 3\\nSkipping line 4136: expected 2 fields, saw 3\\nSkipping line 4137: expected 2 fields, saw 3\\nSkipping line 4138: expected 2 fields, saw 3\\nSkipping line 4139: expected 2 fields, saw 3\\nSkipping line 4140: expected 2 fields, saw 3\\nSkipping line 4141: expected 2 fields, saw 4\\nSkipping line 4142: expected 2 fields, saw 3\\nSkipping line 4143: expected 2 fields, saw 3\\nSkipping line 4144: expected 2 fields, saw 3\\nSkipping line 4145: expected 2 fields, saw 3\\nSkipping line 4146: expected 2 fields, saw 3\\nSkipping line 4147: expected 2 fields, saw 3\\nSkipping line 4148: expected 2 fields, saw 3\\nSkipping line 4149: expected 2 fields, saw 3\\nSkipping line 4150: expected 2 fields, saw 3\\nSkipping line 4151: expected 2 fields, saw 3\\nSkipping line 4152: expected 2 fields, saw 3\\nSkipping line 4153: expected 2 fields, saw 3\\nSkipping line 4154: expected 2 fields, saw 3\\nSkipping line 4155: expected 2 fields, saw 3\\nSkipping line 4156: expected 2 fields, saw 3\\nSkipping line 4157: expected 2 fields, saw 3\\nSkipping line 4158: expected 2 fields, saw 3\\nSkipping line 4159: expected 2 fields, saw 3\\nSkipping line 4160: expected 2 fields, saw 3\\nSkipping line 4161: expected 2 fields, saw 3\\nSkipping line 4162: expected 2 fields, saw 3\\nSkipping line 4163: expected 2 fields, saw 3\\nSkipping line 4164: expected 2 fields, saw 3\\nSkipping line 4165: expected 2 fields, saw 3\\nSkipping line 4166: expected 2 fields, saw 3\\nSkipping line 4167: expected 2 fields, saw 3\\nSkipping line 4168: expected 2 fields, saw 3\\nSkipping line 4169: expected 2 fields, saw 3\\nSkipping line 4170: expected 2 fields, saw 3\\nSkipping line 4171: expected 2 fields, saw 3\\nSkipping line 4172: expected 2 fields, saw 3\\nSkipping line 4173: expected 2 fields, saw 3\\nSkipping line 4174: expected 2 fields, saw 3\\nSkipping line 4175: expected 2 fields, saw 3\\nSkipping line 4176: expected 2 fields, saw 3\\nSkipping line 4177: expected 2 fields, saw 3\\nSkipping line 4178: expected 2 fields, saw 3\\nSkipping line 4179: expected 2 fields, saw 3\\nSkipping line 4180: expected 2 fields, saw 3\\nSkipping line 4181: expected 2 fields, saw 3\\nSkipping line 4182: expected 2 fields, saw 3\\nSkipping line 4183: expected 2 fields, saw 3\\nSkipping line 4184: expected 2 fields, saw 3\\nSkipping line 4185: expected 2 fields, saw 3\\nSkipping line 4186: expected 2 fields, saw 3\\nSkipping line 4187: expected 2 fields, saw 3\\nSkipping line 4188: expected 2 fields, saw 3\\nSkipping line 4189: expected 2 fields, saw 3\\nSkipping line 4190: expected 2 fields, saw 3\\nSkipping line 4191: expected 2 fields, saw 3\\nSkipping line 4192: expected 2 fields, saw 3\\nSkipping line 4193: expected 2 fields, saw 3\\nSkipping line 4194: expected 2 fields, saw 3\\nSkipping line 4195: expected 2 fields, saw 3\\nSkipping line 4196: expected 2 fields, saw 3\\nSkipping line 4197: expected 2 fields, saw 3\\nSkipping line 4198: expected 2 fields, saw 3\\nSkipping line 4199: expected 2 fields, saw 3\\nSkipping line 4200: expected 2 fields, saw 3\\nSkipping line 4201: expected 2 fields, saw 3\\nSkipping line 4202: expected 2 fields, saw 3\\nSkipping line 4203: expected 2 fields, saw 3\\nSkipping line 4204: expected 2 fields, saw 3\\nSkipping line 4205: expected 2 fields, saw 3\\nSkipping line 4206: expected 2 fields, saw 3\\nSkipping line 4207: expected 2 fields, saw 3\\nSkipping line 4208: expected 2 fields, saw 3\\nSkipping line 4209: expected 2 fields, saw 3\\nSkipping line 4210: expected 2 fields, saw 3\\nSkipping line 4211: expected 2 fields, saw 3\\nSkipping line 4212: expected 2 fields, saw 3\\nSkipping line 4213: expected 2 fields, saw 3\\nSkipping line 4214: expected 2 fields, saw 3\\nSkipping line 4215: expected 2 fields, saw 3\\nSkipping line 4216: expected 2 fields, saw 3\\nSkipping line 4217: expected 2 fields, saw 3\\nSkipping line 4218: expected 2 fields, saw 3\\nSkipping line 4219: expected 2 fields, saw 3\\nSkipping line 4220: expected 2 fields, saw 3\\nSkipping line 4221: expected 2 fields, saw 3\\nSkipping line 4222: expected 2 fields, saw 3\\nSkipping line 4239: expected 2 fields, saw 3\\nSkipping line 4240: expected 2 fields, saw 3\\nSkipping line 4241: expected 2 fields, saw 3\\nSkipping line 4242: expected 2 fields, saw 3\\nSkipping line 4243: expected 2 fields, saw 3\\nSkipping line 4244: expected 2 fields, saw 3\\nSkipping line 4245: expected 2 fields, saw 3\\nSkipping line 4246: expected 2 fields, saw 3\\nSkipping line 4247: expected 2 fields, saw 3\\nSkipping line 4248: expected 2 fields, saw 3\\nSkipping line 4249: expected 2 fields, saw 3\\nSkipping line 4250: expected 2 fields, saw 3\\nSkipping line 4251: expected 2 fields, saw 3\\nSkipping line 4253: expected 2 fields, saw 3\\nSkipping line 4254: expected 2 fields, saw 3\\nSkipping line 4255: expected 2 fields, saw 3\\nSkipping line 4256: expected 2 fields, saw 3\\nSkipping line 4257: expected 2 fields, saw 3\\nSkipping line 4258: expected 2 fields, saw 3\\nSkipping line 4259: expected 2 fields, saw 3\\nSkipping line 4260: expected 2 fields, saw 3\\nSkipping line 4261: expected 2 fields, saw 3\\nSkipping line 4262: expected 2 fields, saw 3\\nSkipping line 4263: expected 2 fields, saw 4\\nSkipping line 4264: expected 2 fields, saw 3\\nSkipping line 4265: expected 2 fields, saw 3\\nSkipping line 4266: expected 2 fields, saw 3\\nSkipping line 4268: expected 2 fields, saw 3\\nSkipping line 4269: expected 2 fields, saw 3\\nSkipping line 4270: expected 2 fields, saw 3\\nSkipping line 4276: expected 2 fields, saw 3\\nSkipping line 4277: expected 2 fields, saw 3\\nSkipping line 4278: expected 2 fields, saw 3\\nSkipping line 4279: expected 2 fields, saw 3\\nSkipping line 4285: expected 2 fields, saw 3\\nSkipping line 4287: expected 2 fields, saw 3\\nSkipping line 4288: expected 2 fields, saw 4\\nSkipping line 4289: expected 2 fields, saw 3\\nSkipping line 4290: expected 2 fields, saw 3\\nSkipping line 4291: expected 2 fields, saw 4\\nSkipping line 4292: expected 2 fields, saw 3\\nSkipping line 4293: expected 2 fields, saw 3\\nSkipping line 4294: expected 2 fields, saw 3\\nSkipping line 4301: expected 2 fields, saw 4\\nSkipping line 4302: expected 2 fields, saw 3\\nSkipping line 4313: expected 2 fields, saw 4\\nSkipping line 4317: expected 2 fields, saw 3\\nSkipping line 4318: expected 2 fields, saw 3\\nSkipping line 4340: expected 2 fields, saw 3\\nSkipping line 4341: expected 2 fields, saw 3\\nSkipping line 4379: expected 2 fields, saw 4\\nSkipping line 4384: expected 2 fields, saw 3\\nSkipping line 4389: expected 2 fields, saw 3\\nSkipping line 4390: expected 2 fields, saw 4\\nSkipping line 4394: expected 2 fields, saw 3\\nSkipping line 4395: expected 2 fields, saw 3\\nSkipping line 4414: expected 2 fields, saw 3\\nSkipping line 4418: expected 2 fields, saw 3\\nSkipping line 4422: expected 2 fields, saw 3\\nSkipping line 4425: expected 2 fields, saw 3\\nSkipping line 4429: expected 2 fields, saw 3\\nSkipping line 4430: expected 2 fields, saw 3\\nSkipping line 4475: expected 2 fields, saw 3\\nSkipping line 4476: expected 2 fields, saw 4\\nSkipping line 4477: expected 2 fields, saw 4\\nSkipping line 4478: expected 2 fields, saw 3\\nSkipping line 4479: expected 2 fields, saw 3\\nSkipping line 4480: expected 2 fields, saw 4\\nSkipping line 4481: expected 2 fields, saw 4\\nSkipping line 4482: expected 2 fields, saw 3\\nSkipping line 4483: expected 2 fields, saw 3\\nSkipping line 4484: expected 2 fields, saw 3\\nSkipping line 4485: expected 2 fields, saw 3\\nSkipping line 4486: expected 2 fields, saw 3\\nSkipping line 4487: expected 2 fields, saw 3\\nSkipping line 4489: expected 2 fields, saw 3\\nSkipping line 4490: expected 2 fields, saw 3\\nSkipping line 4491: expected 2 fields, saw 3\\nSkipping line 4493: expected 2 fields, saw 3\\nSkipping line 4499: expected 2 fields, saw 3\\nSkipping line 4500: expected 2 fields, saw 3\\nSkipping line 4501: expected 2 fields, saw 3\\nSkipping line 4502: expected 2 fields, saw 3\\nSkipping line 4503: expected 2 fields, saw 3\\nSkipping line 4504: expected 2 fields, saw 3\\nSkipping line 4505: expected 2 fields, saw 3\\nSkipping line 4506: expected 2 fields, saw 3\\nSkipping line 4508: expected 2 fields, saw 3\\nSkipping line 4509: expected 2 fields, saw 3\\nSkipping line 4531: expected 2 fields, saw 3\\nSkipping line 4532: expected 2 fields, saw 3\\nSkipping line 4533: expected 2 fields, saw 3\\nSkipping line 4534: expected 2 fields, saw 3\\nSkipping line 4535: expected 2 fields, saw 3\\nSkipping line 4536: expected 2 fields, saw 3\\nSkipping line 4537: expected 2 fields, saw 3\\nSkipping line 4538: expected 2 fields, saw 3\\nSkipping line 4542: expected 2 fields, saw 4\\nSkipping line 4545: expected 2 fields, saw 3\\nSkipping line 4547: expected 2 fields, saw 3\\nSkipping line 4548: expected 2 fields, saw 3\\nSkipping line 4549: expected 2 fields, saw 3\\nSkipping line 4550: expected 2 fields, saw 3\\nSkipping line 4557: expected 2 fields, saw 3\\nSkipping line 4558: expected 2 fields, saw 3\\nSkipping line 4559: expected 2 fields, saw 3\\nSkipping line 4560: expected 2 fields, saw 3\\nSkipping line 4562: expected 2 fields, saw 3\\nSkipping line 4563: expected 2 fields, saw 3\\nSkipping line 4564: expected 2 fields, saw 3\\nSkipping line 4565: expected 2 fields, saw 3\\nSkipping line 4566: expected 2 fields, saw 3\\nSkipping line 4567: expected 2 fields, saw 3\\nSkipping line 4569: expected 2 fields, saw 3\\nSkipping line 4570: expected 2 fields, saw 3\\nSkipping line 4580: expected 2 fields, saw 3\\nSkipping line 4581: expected 2 fields, saw 3\\nSkipping line 4588: expected 2 fields, saw 3\\nSkipping line 4589: expected 2 fields, saw 3\\nSkipping line 4594: expected 2 fields, saw 3\\nSkipping line 4596: expected 2 fields, saw 3\\nSkipping line 4599: expected 2 fields, saw 3\\nSkipping line 4601: expected 2 fields, saw 3\\nSkipping line 4602: expected 2 fields, saw 3\\nSkipping line 4603: expected 2 fields, saw 3\\nSkipping line 4604: expected 2 fields, saw 3\\nSkipping line 4605: expected 2 fields, saw 3\\nSkipping line 4606: expected 2 fields, saw 3\\nSkipping line 4607: expected 2 fields, saw 4\\nSkipping line 4608: expected 2 fields, saw 3\\nSkipping line 4609: expected 2 fields, saw 3\\nSkipping line 4610: expected 2 fields, saw 3\\nSkipping line 4611: expected 2 fields, saw 3\\nSkipping line 4614: expected 2 fields, saw 3\\nSkipping line 4616: expected 2 fields, saw 3\\nSkipping line 4617: expected 2 fields, saw 3\\nSkipping line 4620: expected 2 fields, saw 3\\nSkipping line 4625: expected 2 fields, saw 3\\nSkipping line 4627: expected 2 fields, saw 3\\nSkipping line 4632: expected 2 fields, saw 3\\nSkipping line 4635: expected 2 fields, saw 3\\nSkipping line 4637: expected 2 fields, saw 3\\nSkipping line 4638: expected 2 fields, saw 3\\nSkipping line 4640: expected 2 fields, saw 3\\nSkipping line 4641: expected 2 fields, saw 3\\nSkipping line 4644: expected 2 fields, saw 3\\nSkipping line 4646: expected 2 fields, saw 3\\nSkipping line 4647: expected 2 fields, saw 3\\nSkipping line 4650: expected 2 fields, saw 3\\nSkipping line 4651: expected 2 fields, saw 3\\nSkipping line 4652: expected 2 fields, saw 3\\nSkipping line 4653: expected 2 fields, saw 3\\nSkipping line 4655: expected 2 fields, saw 3\\nSkipping line 4658: expected 2 fields, saw 3\\nSkipping line 4659: expected 2 fields, saw 3\\nSkipping line 4661: expected 2 fields, saw 3\\nSkipping line 4665: expected 2 fields, saw 3\\nSkipping line 4666: expected 2 fields, saw 3\\nSkipping line 4707: expected 2 fields, saw 3\\nSkipping line 4723: expected 2 fields, saw 3\\nSkipping line 4725: expected 2 fields, saw 3\\nSkipping line 4726: expected 2 fields, saw 3\\nSkipping line 4728: expected 2 fields, saw 3\\nSkipping line 4730: expected 2 fields, saw 3\\nSkipping line 4731: expected 2 fields, saw 3\\nSkipping line 4733: expected 2 fields, saw 3\\nSkipping line 4734: expected 2 fields, saw 3\\nSkipping line 4740: expected 2 fields, saw 3\\nSkipping line 4742: expected 2 fields, saw 3\\nSkipping line 4743: expected 2 fields, saw 3\\nSkipping line 4745: expected 2 fields, saw 3\\nSkipping line 4746: expected 2 fields, saw 3\\nSkipping line 4747: expected 2 fields, saw 3\\nSkipping line 4748: expected 2 fields, saw 3\\nSkipping line 4749: expected 2 fields, saw 3\\nSkipping line 4750: expected 2 fields, saw 3\\nSkipping line 4754: expected 2 fields, saw 3\\nSkipping line 4782: expected 2 fields, saw 3\\nSkipping line 4784: expected 2 fields, saw 3\\nSkipping line 4800: expected 2 fields, saw 3\\nSkipping line 4801: expected 2 fields, saw 3\\nSkipping line 4802: expected 2 fields, saw 3\\nSkipping line 4803: expected 2 fields, saw 4\\nSkipping line 4804: expected 2 fields, saw 3\\nSkipping line 4805: expected 2 fields, saw 3\\nSkipping line 4806: expected 2 fields, saw 3\\nSkipping line 4807: expected 2 fields, saw 3\\nSkipping line 4808: expected 2 fields, saw 3\\nSkipping line 4809: expected 2 fields, saw 3\\nSkipping line 4810: expected 2 fields, saw 3\\nSkipping line 4811: expected 2 fields, saw 4\\nSkipping line 4812: expected 2 fields, saw 3\\nSkipping line 4813: expected 2 fields, saw 3\\nSkipping line 4814: expected 2 fields, saw 3\\nSkipping line 4815: expected 2 fields, saw 4\\nSkipping line 4816: expected 2 fields, saw 3\\nSkipping line 4817: expected 2 fields, saw 3\\nSkipping line 4818: expected 2 fields, saw 3\\nSkipping line 4819: expected 2 fields, saw 3\\nSkipping line 4820: expected 2 fields, saw 3\\nSkipping line 4821: expected 2 fields, saw 3\\nSkipping line 4822: expected 2 fields, saw 3\\nSkipping line 4823: expected 2 fields, saw 3\\nSkipping line 4824: expected 2 fields, saw 3\\nSkipping line 4827: expected 2 fields, saw 3\\nSkipping line 4852: expected 2 fields, saw 3\\nSkipping line 4860: expected 2 fields, saw 3\\nSkipping line 4869: expected 2 fields, saw 3\\nSkipping line 4871: expected 2 fields, saw 3\\nSkipping line 4891: expected 2 fields, saw 3\\nSkipping line 4892: expected 2 fields, saw 3\\nSkipping line 4893: expected 2 fields, saw 3\\nSkipping line 4894: expected 2 fields, saw 3\\nSkipping line 4903: expected 2 fields, saw 3\\nSkipping line 4905: expected 2 fields, saw 3\\nSkipping line 4906: expected 2 fields, saw 3\\nSkipping line 4907: expected 2 fields, saw 3\\nSkipping line 4908: expected 2 fields, saw 3\\nSkipping line 4913: expected 2 fields, saw 3\\nSkipping line 4915: expected 2 fields, saw 4\\nSkipping line 4916: expected 2 fields, saw 3\\nSkipping line 4917: expected 2 fields, saw 4\\nSkipping line 4918: expected 2 fields, saw 3\\nSkipping line 4919: expected 2 fields, saw 3\\nSkipping line 4920: expected 2 fields, saw 3\\nSkipping line 4921: expected 2 fields, saw 3\\nSkipping line 4922: expected 2 fields, saw 3\\nSkipping line 4923: expected 2 fields, saw 3\\nSkipping line 4924: expected 2 fields, saw 3\\nSkipping line 4925: expected 2 fields, saw 3\\nSkipping line 4926: expected 2 fields, saw 3\\nSkipping line 4927: expected 2 fields, saw 3\\nSkipping line 4928: expected 2 fields, saw 3\\nSkipping line 4929: expected 2 fields, saw 3\\nSkipping line 4931: expected 2 fields, saw 3\\nSkipping line 4932: expected 2 fields, saw 3\\nSkipping line 4933: expected 2 fields, saw 3\\nSkipping line 4934: expected 2 fields, saw 3\\nSkipping line 4935: expected 2 fields, saw 3\\nSkipping line 4936: expected 2 fields, saw 3\\nSkipping line 4937: expected 2 fields, saw 3\\nSkipping line 4939: expected 2 fields, saw 3\\nSkipping line 4942: expected 2 fields, saw 3\\nSkipping line 4943: expected 2 fields, saw 3\\nSkipping line 4945: expected 2 fields, saw 3\\nSkipping line 4949: expected 2 fields, saw 3\\nSkipping line 4950: expected 2 fields, saw 3\\nSkipping line 4957: expected 2 fields, saw 3\\nSkipping line 4958: expected 2 fields, saw 3\\nSkipping line 4959: expected 2 fields, saw 3\\nSkipping line 4960: expected 2 fields, saw 3\\nSkipping line 4961: expected 2 fields, saw 3\\nSkipping line 4963: expected 2 fields, saw 3\\nSkipping line 4966: expected 2 fields, saw 3\\nSkipping line 4967: expected 2 fields, saw 3\\nSkipping line 4968: expected 2 fields, saw 3\\nSkipping line 4970: expected 2 fields, saw 3\\nSkipping line 4976: expected 2 fields, saw 4\\nSkipping line 4978: expected 2 fields, saw 3\\nSkipping line 4984: expected 2 fields, saw 3\\nSkipping line 4986: expected 2 fields, saw 3\\nSkipping line 4989: expected 2 fields, saw 3\\nSkipping line 4990: expected 2 fields, saw 3\\nSkipping line 4991: expected 2 fields, saw 3\\nSkipping line 4992: expected 2 fields, saw 3\\nSkipping line 4994: expected 2 fields, saw 3\\nSkipping line 4995: expected 2 fields, saw 4\\nSkipping line 4996: expected 2 fields, saw 3\\nSkipping line 4997: expected 2 fields, saw 3\\nSkipping line 4998: expected 2 fields, saw 4\\nSkipping line 4999: expected 2 fields, saw 3\\nSkipping line 5000: expected 2 fields, saw 3\\nSkipping line 5001: expected 2 fields, saw 3\\nSkipping line 5002: expected 2 fields, saw 3\\nSkipping line 5003: expected 2 fields, saw 3\\nSkipping line 5004: expected 2 fields, saw 3\\nSkipping line 5006: expected 2 fields, saw 3\\nSkipping line 5007: expected 2 fields, saw 3\\nSkipping line 5008: expected 2 fields, saw 3\\nSkipping line 5009: expected 2 fields, saw 3\\nSkipping line 5010: expected 2 fields, saw 3\\nSkipping line 5011: expected 2 fields, saw 3\\nSkipping line 5012: expected 2 fields, saw 3\\nSkipping line 5013: expected 2 fields, saw 3\\nSkipping line 5014: expected 2 fields, saw 3\\nSkipping line 5015: expected 2 fields, saw 3\\nSkipping line 5016: expected 2 fields, saw 3\\nSkipping line 5017: expected 2 fields, saw 3\\nSkipping line 5018: expected 2 fields, saw 3\\nSkipping line 5019: expected 2 fields, saw 3\\nSkipping line 5020: expected 2 fields, saw 3\\nSkipping line 5021: expected 2 fields, saw 3\\nSkipping line 5022: expected 2 fields, saw 3\\nSkipping line 5023: expected 2 fields, saw 3\\nSkipping line 5030: expected 2 fields, saw 3\\nSkipping line 5031: expected 2 fields, saw 3\\nSkipping line 5032: expected 2 fields, saw 3\\nSkipping line 5034: expected 2 fields, saw 3\\nSkipping line 5040: expected 2 fields, saw 3\\nSkipping line 5043: expected 2 fields, saw 3\\nSkipping line 5045: expected 2 fields, saw 3\\nSkipping line 5046: expected 2 fields, saw 3\\nSkipping line 5048: expected 2 fields, saw 3\\nSkipping line 5050: expected 2 fields, saw 3\\nSkipping line 5056: expected 2 fields, saw 3\\nSkipping line 5057: expected 2 fields, saw 4\\nSkipping line 5058: expected 2 fields, saw 3\\nSkipping line 5059: expected 2 fields, saw 3\\nSkipping line 5060: expected 2 fields, saw 3\\nSkipping line 5061: expected 2 fields, saw 3\\nSkipping line 5062: expected 2 fields, saw 3\\nSkipping line 5063: expected 2 fields, saw 3\\nSkipping line 5064: expected 2 fields, saw 3\\nSkipping line 5065: expected 2 fields, saw 4\\nSkipping line 5066: expected 2 fields, saw 3\\nSkipping line 5067: expected 2 fields, saw 3\\nSkipping line 5068: expected 2 fields, saw 3\\nSkipping line 5070: expected 2 fields, saw 3\\nSkipping line 5072: expected 2 fields, saw 3\\nSkipping line 5073: expected 2 fields, saw 3\\nSkipping line 5074: expected 2 fields, saw 4\\nSkipping line 5076: expected 2 fields, saw 3\\nSkipping line 5078: expected 2 fields, saw 3\\nSkipping line 5079: expected 2 fields, saw 3\\nSkipping line 5080: expected 2 fields, saw 3\\nSkipping line 5082: expected 2 fields, saw 3\\nSkipping line 5083: expected 2 fields, saw 3\\nSkipping line 5088: expected 2 fields, saw 3\\nSkipping line 5089: expected 2 fields, saw 3\\nSkipping line 5096: expected 2 fields, saw 3\\nSkipping line 5097: expected 2 fields, saw 3\\nSkipping line 5100: expected 2 fields, saw 3\\nSkipping line 5101: expected 2 fields, saw 3\\nSkipping line 5102: expected 2 fields, saw 3\\nSkipping line 5104: expected 2 fields, saw 3\\nSkipping line 5105: expected 2 fields, saw 3\\nSkipping line 5106: expected 2 fields, saw 3\\nSkipping line 5109: expected 2 fields, saw 3\\nSkipping line 5111: expected 2 fields, saw 3\\nSkipping line 5112: expected 2 fields, saw 3\\nSkipping line 5116: expected 2 fields, saw 3\\nSkipping line 5117: expected 2 fields, saw 3\\nSkipping line 5119: expected 2 fields, saw 3\\nSkipping line 5126: expected 2 fields, saw 3\\nSkipping line 5127: expected 2 fields, saw 3\\nSkipping line 5128: expected 2 fields, saw 3\\nSkipping line 5129: expected 2 fields, saw 3\\nSkipping line 5130: expected 2 fields, saw 3\\nSkipping line 5131: expected 2 fields, saw 3\\nSkipping line 5132: expected 2 fields, saw 4\\nSkipping line 5133: expected 2 fields, saw 3\\nSkipping line 5134: expected 2 fields, saw 4\\nSkipping line 5135: expected 2 fields, saw 3\\nSkipping line 5137: expected 2 fields, saw 3\\nSkipping line 5138: expected 2 fields, saw 3\\nSkipping line 5139: expected 2 fields, saw 3\\nSkipping line 5140: expected 2 fields, saw 3\\nSkipping line 5143: expected 2 fields, saw 3\\nSkipping line 5144: expected 2 fields, saw 3\\nSkipping line 5145: expected 2 fields, saw 3\\nSkipping line 5146: expected 2 fields, saw 3\\nSkipping line 5147: expected 2 fields, saw 3\\nSkipping line 5148: expected 2 fields, saw 3\\nSkipping line 5149: expected 2 fields, saw 3\\nSkipping line 5150: expected 2 fields, saw 3\\nSkipping line 5151: expected 2 fields, saw 4\\nSkipping line 5152: expected 2 fields, saw 3\\nSkipping line 5153: expected 2 fields, saw 3\\nSkipping line 5154: expected 2 fields, saw 3\\nSkipping line 5155: expected 2 fields, saw 3\\nSkipping line 5156: expected 2 fields, saw 5\\nSkipping line 5157: expected 2 fields, saw 3\\nSkipping line 5159: expected 2 fields, saw 3\\nSkipping line 5160: expected 2 fields, saw 4\\nSkipping line 5161: expected 2 fields, saw 3\\nSkipping line 5162: expected 2 fields, saw 3\\nSkipping line 5164: expected 2 fields, saw 3\\nSkipping line 5165: expected 2 fields, saw 3\\nSkipping line 5166: expected 2 fields, saw 3\\nSkipping line 5167: expected 2 fields, saw 3\\nSkipping line 5168: expected 2 fields, saw 3\\nSkipping line 5170: expected 2 fields, saw 3\\nSkipping line 5173: expected 2 fields, saw 3\\nSkipping line 5178: expected 2 fields, saw 3\\nSkipping line 5179: expected 2 fields, saw 4\\nSkipping line 5181: expected 2 fields, saw 3\\nSkipping line 5182: expected 2 fields, saw 3\\nSkipping line 5183: expected 2 fields, saw 3\\nSkipping line 5185: expected 2 fields, saw 3\\nSkipping line 5186: expected 2 fields, saw 3\\nSkipping line 5191: expected 2 fields, saw 3\\nSkipping line 5194: expected 2 fields, saw 3\\nSkipping line 5196: expected 2 fields, saw 3\\nSkipping line 5200: expected 2 fields, saw 3\\nSkipping line 5203: expected 2 fields, saw 3\\nSkipping line 5206: expected 2 fields, saw 3\\nSkipping line 5209: expected 2 fields, saw 3\\nSkipping line 5214: expected 2 fields, saw 3\\nSkipping line 5221: expected 2 fields, saw 3\\nSkipping line 5222: expected 2 fields, saw 3\\nSkipping line 5223: expected 2 fields, saw 3\\nSkipping line 5224: expected 2 fields, saw 3\\nSkipping line 5225: expected 2 fields, saw 3\\nSkipping line 5229: expected 2 fields, saw 3\\nSkipping line 5230: expected 2 fields, saw 3\\nSkipping line 5232: expected 2 fields, saw 3\\nSkipping line 5237: expected 2 fields, saw 3\\nSkipping line 5238: expected 2 fields, saw 4\\nSkipping line 5240: expected 2 fields, saw 3\\nSkipping line 5241: expected 2 fields, saw 3\\nSkipping line 5243: expected 2 fields, saw 3\\nSkipping line 5244: expected 2 fields, saw 3\\nSkipping line 5245: expected 2 fields, saw 3\\nSkipping line 5246: expected 2 fields, saw 3\\nSkipping line 5247: expected 2 fields, saw 3\\nSkipping line 5248: expected 2 fields, saw 3\\nSkipping line 5249: expected 2 fields, saw 3\\nSkipping line 5250: expected 2 fields, saw 3\\nSkipping line 5251: expected 2 fields, saw 3\\nSkipping line 5252: expected 2 fields, saw 3\\nSkipping line 5253: expected 2 fields, saw 3\\nSkipping line 5254: expected 2 fields, saw 3\\nSkipping line 5255: expected 2 fields, saw 3\\nSkipping line 5256: expected 2 fields, saw 3\\nSkipping line 5257: expected 2 fields, saw 3\\nSkipping line 5258: expected 2 fields, saw 3\\nSkipping line 5259: expected 2 fields, saw 3\\nSkipping line 5260: expected 2 fields, saw 3\\nSkipping line 5261: expected 2 fields, saw 3\\nSkipping line 5262: expected 2 fields, saw 3\\nSkipping line 5263: expected 2 fields, saw 3\\nSkipping line 5264: expected 2 fields, saw 3\\nSkipping line 5265: expected 2 fields, saw 3\\nSkipping line 5266: expected 2 fields, saw 3\\nSkipping line 5267: expected 2 fields, saw 3\\nSkipping line 5268: expected 2 fields, saw 3\\nSkipping line 5269: expected 2 fields, saw 3\\nSkipping line 5270: expected 2 fields, saw 3\\nSkipping line 5271: expected 2 fields, saw 3\\nSkipping line 5272: expected 2 fields, saw 3\\nSkipping line 5273: expected 2 fields, saw 3\\nSkipping line 5274: expected 2 fields, saw 3\\nSkipping line 5275: expected 2 fields, saw 3\\nSkipping line 5276: expected 2 fields, saw 3\\nSkipping line 5277: expected 2 fields, saw 3\\nSkipping line 5278: expected 2 fields, saw 3\\nSkipping line 5279: expected 2 fields, saw 3\\nSkipping line 5280: expected 2 fields, saw 3\\nSkipping line 5281: expected 2 fields, saw 3\\nSkipping line 5282: expected 2 fields, saw 3\\nSkipping line 5283: expected 2 fields, saw 3\\nSkipping line 5284: expected 2 fields, saw 3\\nSkipping line 5285: expected 2 fields, saw 3\\nSkipping line 5286: expected 2 fields, saw 3\\nSkipping line 5287: expected 2 fields, saw 3\\nSkipping line 5288: expected 2 fields, saw 3\\nSkipping line 5289: expected 2 fields, saw 3\\nSkipping line 5290: expected 2 fields, saw 3\\nSkipping line 5291: expected 2 fields, saw 3\\nSkipping line 5292: expected 2 fields, saw 3\\nSkipping line 5293: expected 2 fields, saw 3\\nSkipping line 5294: expected 2 fields, saw 3\\nSkipping line 5295: expected 2 fields, saw 3\\nSkipping line 5296: expected 2 fields, saw 3\\nSkipping line 5297: expected 2 fields, saw 3\\nSkipping line 5298: expected 2 fields, saw 3\\nSkipping line 5299: expected 2 fields, saw 3\\nSkipping line 5300: expected 2 fields, saw 3\\nSkipping line 5301: expected 2 fields, saw 3\\nSkipping line 5302: expected 2 fields, saw 3\\nSkipping line 5303: expected 2 fields, saw 4\\nSkipping line 5304: expected 2 fields, saw 4\\nSkipping line 5305: expected 2 fields, saw 4\\nSkipping line 5306: expected 2 fields, saw 4\\nSkipping line 5307: expected 2 fields, saw 4\\nSkipping line 5308: expected 2 fields, saw 4\\nSkipping line 5309: expected 2 fields, saw 4\\nSkipping line 5310: expected 2 fields, saw 4\\nSkipping line 5311: expected 2 fields, saw 4\\nSkipping line 5312: expected 2 fields, saw 4\\nSkipping line 5313: expected 2 fields, saw 4\\nSkipping line 5314: expected 2 fields, saw 3\\nSkipping line 5315: expected 2 fields, saw 3\\nSkipping line 5317: expected 2 fields, saw 3\\nSkipping line 5318: expected 2 fields, saw 3\\nSkipping line 5319: expected 2 fields, saw 3\\nSkipping line 5320: expected 2 fields, saw 3\\nSkipping line 5321: expected 2 fields, saw 3\\nSkipping line 5322: expected 2 fields, saw 3\\nSkipping line 5323: expected 2 fields, saw 3\\nSkipping line 5324: expected 2 fields, saw 3\\nSkipping line 5325: expected 2 fields, saw 3\\nSkipping line 5326: expected 2 fields, saw 3\\nSkipping line 5327: expected 2 fields, saw 4\\nSkipping line 5328: expected 2 fields, saw 4\\nSkipping line 5329: expected 2 fields, saw 3\\nSkipping line 5330: expected 2 fields, saw 3\\nSkipping line 5331: expected 2 fields, saw 3\\nSkipping line 5332: expected 2 fields, saw 3\\nSkipping line 5333: expected 2 fields, saw 3\\nSkipping line 5334: expected 2 fields, saw 3\\nSkipping line 5335: expected 2 fields, saw 3\\nSkipping line 5336: expected 2 fields, saw 3\\nSkipping line 5337: expected 2 fields, saw 3\\nSkipping line 5338: expected 2 fields, saw 3\\nSkipping line 5339: expected 2 fields, saw 3\\nSkipping line 5340: expected 2 fields, saw 3\\nSkipping line 5341: expected 2 fields, saw 3\\nSkipping line 5342: expected 2 fields, saw 3\\nSkipping line 5343: expected 2 fields, saw 3\\nSkipping line 5344: expected 2 fields, saw 3\\nSkipping line 5345: expected 2 fields, saw 3\\nSkipping line 5346: expected 2 fields, saw 3\\nSkipping line 5347: expected 2 fields, saw 3\\nSkipping line 5348: expected 2 fields, saw 3\\nSkipping line 5349: expected 2 fields, saw 3\\nSkipping line 5350: expected 2 fields, saw 3\\nSkipping line 5352: expected 2 fields, saw 4\\nSkipping line 5353: expected 2 fields, saw 3\\nSkipping line 5354: expected 2 fields, saw 4\\nSkipping line 5355: expected 2 fields, saw 4\\nSkipping line 5356: expected 2 fields, saw 4\\nSkipping line 5357: expected 2 fields, saw 4\\nSkipping line 5358: expected 2 fields, saw 3\\nSkipping line 5359: expected 2 fields, saw 3\\nSkipping line 5360: expected 2 fields, saw 3\\nSkipping line 5361: expected 2 fields, saw 3\\nSkipping line 5362: expected 2 fields, saw 3\\nSkipping line 5363: expected 2 fields, saw 3\\nSkipping line 5364: expected 2 fields, saw 3\\nSkipping line 5365: expected 2 fields, saw 3\\nSkipping line 5366: expected 2 fields, saw 3\\nSkipping line 5367: expected 2 fields, saw 3\\nSkipping line 5368: expected 2 fields, saw 3\\nSkipping line 5369: expected 2 fields, saw 3\\nSkipping line 5370: expected 2 fields, saw 3\\nSkipping line 5371: expected 2 fields, saw 3\\nSkipping line 5372: expected 2 fields, saw 3\\nSkipping line 5373: expected 2 fields, saw 3\\nSkipping line 5374: expected 2 fields, saw 3\\nSkipping line 5375: expected 2 fields, saw 3\\nSkipping line 5376: expected 2 fields, saw 3\\nSkipping line 5377: expected 2 fields, saw 3\\nSkipping line 5378: expected 2 fields, saw 3\\nSkipping line 5380: expected 2 fields, saw 3\\nSkipping line 5381: expected 2 fields, saw 3\\nSkipping line 5383: expected 2 fields, saw 3\\nSkipping line 5384: expected 2 fields, saw 3\\nSkipping line 5385: expected 2 fields, saw 3\\nSkipping line 5386: expected 2 fields, saw 3\\nSkipping line 5388: expected 2 fields, saw 3\\nSkipping line 5390: expected 2 fields, saw 4\\nSkipping line 5391: expected 2 fields, saw 3\\nSkipping line 5394: expected 2 fields, saw 3\\nSkipping line 5395: expected 2 fields, saw 3\\nSkipping line 5403: expected 2 fields, saw 3\\nSkipping line 5407: expected 2 fields, saw 3\\nSkipping line 5409: expected 2 fields, saw 3\\nSkipping line 5410: expected 2 fields, saw 3\\nSkipping line 5411: expected 2 fields, saw 3\\nSkipping line 5418: expected 2 fields, saw 3\\nSkipping line 5419: expected 2 fields, saw 3\\nSkipping line 5420: expected 2 fields, saw 3\\nSkipping line 5421: expected 2 fields, saw 3\\nSkipping line 5422: expected 2 fields, saw 3\\nSkipping line 5423: expected 2 fields, saw 3\\nSkipping line 5424: expected 2 fields, saw 3\\nSkipping line 5425: expected 2 fields, saw 3\\nSkipping line 5426: expected 2 fields, saw 3\\nSkipping line 5427: expected 2 fields, saw 3\\nSkipping line 5428: expected 2 fields, saw 3\\nSkipping line 5429: expected 2 fields, saw 3\\nSkipping line 5430: expected 2 fields, saw 3\\nSkipping line 5431: expected 2 fields, saw 3\\nSkipping line 5432: expected 2 fields, saw 3\\nSkipping line 5433: expected 2 fields, saw 3\\nSkipping line 5434: expected 2 fields, saw 3\\nSkipping line 5435: expected 2 fields, saw 3\\nSkipping line 5436: expected 2 fields, saw 3\\nSkipping line 5437: expected 2 fields, saw 3\\nSkipping line 5438: expected 2 fields, saw 3\\nSkipping line 5439: expected 2 fields, saw 3\\nSkipping line 5440: expected 2 fields, saw 3\\nSkipping line 5441: expected 2 fields, saw 3\\nSkipping line 5442: expected 2 fields, saw 4\\nSkipping line 5443: expected 2 fields, saw 3\\nSkipping line 5444: expected 2 fields, saw 3\\nSkipping line 5445: expected 2 fields, saw 4\\nSkipping line 5446: expected 2 fields, saw 4\\nSkipping line 5447: expected 2 fields, saw 4\\nSkipping line 5448: expected 2 fields, saw 4\\nSkipping line 5449: expected 2 fields, saw 4\\nSkipping line 5450: expected 2 fields, saw 4\\nSkipping line 5451: expected 2 fields, saw 4\\nSkipping line 5452: expected 2 fields, saw 4\\nSkipping line 5453: expected 2 fields, saw 4\\nSkipping line 5454: expected 2 fields, saw 4\\nSkipping line 5455: expected 2 fields, saw 4\\nSkipping line 5456: expected 2 fields, saw 4\\nSkipping line 5457: expected 2 fields, saw 4\\nSkipping line 5458: expected 2 fields, saw 4\\nSkipping line 5459: expected 2 fields, saw 4\\nSkipping line 5460: expected 2 fields, saw 4\\nSkipping line 5461: expected 2 fields, saw 4\\nSkipping line 5462: expected 2 fields, saw 4\\nSkipping line 5463: expected 2 fields, saw 4\\nSkipping line 5464: expected 2 fields, saw 4\\nSkipping line 5465: expected 2 fields, saw 4\\nSkipping line 5466: expected 2 fields, saw 3\\nSkipping line 5467: expected 2 fields, saw 4\\nSkipping line 5468: expected 2 fields, saw 3\\nSkipping line 5469: expected 2 fields, saw 4\\nSkipping line 5470: expected 2 fields, saw 4\\nSkipping line 5471: expected 2 fields, saw 3\\nSkipping line 5472: expected 2 fields, saw 4\\nSkipping line 5473: expected 2 fields, saw 4\\nSkipping line 5474: expected 2 fields, saw 4\\nSkipping line 5475: expected 2 fields, saw 3\\nSkipping line 5481: expected 2 fields, saw 4\\nSkipping line 5483: expected 2 fields, saw 3\\nSkipping line 5485: expected 2 fields, saw 3\\nSkipping line 5495: expected 2 fields, saw 3\\nSkipping line 5496: expected 2 fields, saw 3\\nSkipping line 5497: expected 2 fields, saw 3\\nSkipping line 5498: expected 2 fields, saw 3\\nSkipping line 5500: expected 2 fields, saw 3\\nSkipping line 5501: expected 2 fields, saw 3\\nSkipping line 5502: expected 2 fields, saw 4\\nSkipping line 5503: expected 2 fields, saw 4\\nSkipping line 5504: expected 2 fields, saw 4\\nSkipping line 5505: expected 2 fields, saw 4\\nSkipping line 5506: expected 2 fields, saw 4\\nSkipping line 5507: expected 2 fields, saw 3\\nSkipping line 5508: expected 2 fields, saw 3\\nSkipping line 5509: expected 2 fields, saw 3\\nSkipping line 5510: expected 2 fields, saw 3\\nSkipping line 5511: expected 2 fields, saw 3\\nSkipping line 5512: expected 2 fields, saw 3\\nSkipping line 5513: expected 2 fields, saw 3\\nSkipping line 5514: expected 2 fields, saw 3\\nSkipping line 5516: expected 2 fields, saw 3\\nSkipping line 5517: expected 2 fields, saw 3\\nSkipping line 5518: expected 2 fields, saw 3\\nSkipping line 5521: expected 2 fields, saw 3\\nSkipping line 5523: expected 2 fields, saw 3\\nSkipping line 5524: expected 2 fields, saw 3\\nSkipping line 5525: expected 2 fields, saw 3\\nSkipping line 5527: expected 2 fields, saw 3\\nSkipping line 5528: expected 2 fields, saw 3\\nSkipping line 5529: expected 2 fields, saw 3\\nSkipping line 5530: expected 2 fields, saw 3\\nSkipping line 5531: expected 2 fields, saw 3\\nSkipping line 5532: expected 2 fields, saw 3\\nSkipping line 5533: expected 2 fields, saw 3\\nSkipping line 5534: expected 2 fields, saw 3\\nSkipping line 5535: expected 2 fields, saw 3\\nSkipping line 5536: expected 2 fields, saw 3\\nSkipping line 5538: expected 2 fields, saw 3\\nSkipping line 5543: expected 2 fields, saw 3\\nSkipping line 5545: expected 2 fields, saw 3\\nSkipping line 5549: expected 2 fields, saw 3\\nSkipping line 5551: expected 2 fields, saw 3\\nSkipping line 5552: expected 2 fields, saw 3\\nSkipping line 5554: expected 2 fields, saw 3\\nSkipping line 5558: expected 2 fields, saw 3\\nSkipping line 5559: expected 2 fields, saw 3\\nSkipping line 5560: expected 2 fields, saw 3\\nSkipping line 5561: expected 2 fields, saw 3\\nSkipping line 5566: expected 2 fields, saw 3\\nSkipping line 5568: expected 2 fields, saw 3\\nSkipping line 5571: expected 2 fields, saw 3\\nSkipping line 5573: expected 2 fields, saw 3\\nSkipping line 5574: expected 2 fields, saw 3\\nSkipping line 5578: expected 2 fields, saw 3\\nSkipping line 5579: expected 2 fields, saw 3\\nSkipping line 5580: expected 2 fields, saw 3\\nSkipping line 5581: expected 2 fields, saw 3\\nSkipping line 5582: expected 2 fields, saw 3\\nSkipping line 5583: expected 2 fields, saw 3\\nSkipping line 5584: expected 2 fields, saw 3\\nSkipping line 5585: expected 2 fields, saw 3\\nSkipping line 5586: expected 2 fields, saw 3\\nSkipping line 5587: expected 2 fields, saw 4\\nSkipping line 5588: expected 2 fields, saw 3\\nSkipping line 5589: expected 2 fields, saw 3\\nSkipping line 5591: expected 2 fields, saw 3\\nSkipping line 5594: expected 2 fields, saw 3\\nSkipping line 5595: expected 2 fields, saw 3\\nSkipping line 5597: expected 2 fields, saw 3\\nSkipping line 5600: expected 2 fields, saw 3\\nSkipping line 5601: expected 2 fields, saw 3\\nSkipping line 5602: expected 2 fields, saw 3\\nSkipping line 5603: expected 2 fields, saw 3\\nSkipping line 5604: expected 2 fields, saw 3\\nSkipping line 5606: expected 2 fields, saw 3\\nSkipping line 5607: expected 2 fields, saw 4\\nSkipping line 5609: expected 2 fields, saw 3\\nSkipping line 5612: expected 2 fields, saw 3\\nSkipping line 5613: expected 2 fields, saw 3\\nSkipping line 5614: expected 2 fields, saw 4\\nSkipping line 5617: expected 2 fields, saw 3\\nSkipping line 5625: expected 2 fields, saw 3\\nSkipping line 5626: expected 2 fields, saw 3\\nSkipping line 5627: expected 2 fields, saw 3\\nSkipping line 5632: expected 2 fields, saw 3\\nSkipping line 5635: expected 2 fields, saw 3\\nSkipping line 5638: expected 2 fields, saw 3\\nSkipping line 5639: expected 2 fields, saw 3\\nSkipping line 5640: expected 2 fields, saw 3\\nSkipping line 5641: expected 2 fields, saw 3\\nSkipping line 5642: expected 2 fields, saw 3\\nSkipping line 5643: expected 2 fields, saw 3\\nSkipping line 5644: expected 2 fields, saw 3\\nSkipping line 5645: expected 2 fields, saw 3\\nSkipping line 5646: expected 2 fields, saw 3\\nSkipping line 5647: expected 2 fields, saw 3\\nSkipping line 5648: expected 2 fields, saw 4\\nSkipping line 5649: expected 2 fields, saw 3\\nSkipping line 5650: expected 2 fields, saw 3\\nSkipping line 5651: expected 2 fields, saw 3\\nSkipping line 5652: expected 2 fields, saw 3\\nSkipping line 5655: expected 2 fields, saw 3\\nSkipping line 5656: expected 2 fields, saw 3\\nSkipping line 5657: expected 2 fields, saw 3\\nSkipping line 5658: expected 2 fields, saw 3\\nSkipping line 5659: expected 2 fields, saw 3\\nSkipping line 5660: expected 2 fields, saw 3\\nSkipping line 5661: expected 2 fields, saw 3\\nSkipping line 5662: expected 2 fields, saw 3\\nSkipping line 5663: expected 2 fields, saw 3\\nSkipping line 5664: expected 2 fields, saw 3\\nSkipping line 5665: expected 2 fields, saw 3\\nSkipping line 5666: expected 2 fields, saw 3\\nSkipping line 5667: expected 2 fields, saw 3\\nSkipping line 5668: expected 2 fields, saw 3\\nSkipping line 5669: expected 2 fields, saw 4\\nSkipping line 5670: expected 2 fields, saw 4\\nSkipping line 5671: expected 2 fields, saw 3\\nSkipping line 5672: expected 2 fields, saw 3\\nSkipping line 5673: expected 2 fields, saw 3\\nSkipping line 5674: expected 2 fields, saw 3\\nSkipping line 5675: expected 2 fields, saw 3\\nSkipping line 5676: expected 2 fields, saw 3\\nSkipping line 5677: expected 2 fields, saw 3\\nSkipping line 5684: expected 2 fields, saw 3\\nSkipping line 5685: expected 2 fields, saw 3\\nSkipping line 5686: expected 2 fields, saw 3\\nSkipping line 5689: expected 2 fields, saw 3\\nSkipping line 5690: expected 2 fields, saw 3\\nSkipping line 5693: expected 2 fields, saw 3\\nSkipping line 5695: expected 2 fields, saw 3\\nSkipping line 5696: expected 2 fields, saw 3\\nSkipping line 5697: expected 2 fields, saw 3\\nSkipping line 5701: expected 2 fields, saw 4\\nSkipping line 5702: expected 2 fields, saw 3\\nSkipping line 5703: expected 2 fields, saw 3\\nSkipping line 5704: expected 2 fields, saw 3\\nSkipping line 5705: expected 2 fields, saw 3\\nSkipping line 5706: expected 2 fields, saw 3\\nSkipping line 5707: expected 2 fields, saw 3\\nSkipping line 5708: expected 2 fields, saw 3\\nSkipping line 5709: expected 2 fields, saw 3\\nSkipping line 5713: expected 2 fields, saw 3\\nSkipping line 5715: expected 2 fields, saw 3\\nSkipping line 5717: expected 2 fields, saw 3\\nSkipping line 5718: expected 2 fields, saw 3\\nSkipping line 5719: expected 2 fields, saw 3\\nSkipping line 5720: expected 2 fields, saw 3\\nSkipping line 5721: expected 2 fields, saw 3\\nSkipping line 5722: expected 2 fields, saw 3\\nSkipping line 5723: expected 2 fields, saw 3\\nSkipping line 5724: expected 2 fields, saw 3\\nSkipping line 5725: expected 2 fields, saw 3\\nSkipping line 5726: expected 2 fields, saw 3\\nSkipping line 5727: expected 2 fields, saw 3\\nSkipping line 5728: expected 2 fields, saw 3\\nSkipping line 5729: expected 2 fields, saw 3\\nSkipping line 5730: expected 2 fields, saw 3\\nSkipping line 5731: expected 2 fields, saw 3\\nSkipping line 5732: expected 2 fields, saw 3\\nSkipping line 5733: expected 2 fields, saw 3\\nSkipping line 5734: expected 2 fields, saw 3\\nSkipping line 5735: expected 2 fields, saw 3\\nSkipping line 5736: expected 2 fields, saw 3\\nSkipping line 5737: expected 2 fields, saw 3\\nSkipping line 5738: expected 2 fields, saw 3\\nSkipping line 5739: expected 2 fields, saw 3\\nSkipping line 5740: expected 2 fields, saw 3\\nSkipping line 5746: expected 2 fields, saw 3\\nSkipping line 5747: expected 2 fields, saw 3\\nSkipping line 5749: expected 2 fields, saw 3\\nSkipping line 5750: expected 2 fields, saw 3\\nSkipping line 5751: expected 2 fields, saw 4\\nSkipping line 5752: expected 2 fields, saw 3\\nSkipping line 5760: expected 2 fields, saw 3\\nSkipping line 5762: expected 2 fields, saw 3\\nSkipping line 5765: expected 2 fields, saw 3\\nSkipping line 5766: expected 2 fields, saw 3\\nSkipping line 5767: expected 2 fields, saw 4\\nSkipping line 5771: expected 2 fields, saw 3\\nSkipping line 5772: expected 2 fields, saw 3\\nSkipping line 5773: expected 2 fields, saw 3\\nSkipping line 5774: expected 2 fields, saw 3\\nSkipping line 5776: expected 2 fields, saw 3\\nSkipping line 5782: expected 2 fields, saw 3\\nSkipping line 5783: expected 2 fields, saw 3\\nSkipping line 5786: expected 2 fields, saw 3\\nSkipping line 5791: expected 2 fields, saw 3\\nSkipping line 5794: expected 2 fields, saw 3\\nSkipping line 5799: expected 2 fields, saw 3\\nSkipping line 5801: expected 2 fields, saw 3\\nSkipping line 5802: expected 2 fields, saw 3\\nSkipping line 5803: expected 2 fields, saw 3\\nSkipping line 5805: expected 2 fields, saw 4\\nSkipping line 5806: expected 2 fields, saw 3\\nSkipping line 5807: expected 2 fields, saw 4\\nSkipping line 5808: expected 2 fields, saw 3\\nSkipping line 5822: expected 2 fields, saw 3\\nSkipping line 5826: expected 2 fields, saw 3\\nSkipping line 5827: expected 2 fields, saw 3\\nSkipping line 5828: expected 2 fields, saw 3\\nSkipping line 5834: expected 2 fields, saw 3\\nSkipping line 5835: expected 2 fields, saw 3\\nSkipping line 5839: expected 2 fields, saw 3\\nSkipping line 5840: expected 2 fields, saw 3\\nSkipping line 5842: expected 2 fields, saw 3\\nSkipping line 5843: expected 2 fields, saw 3\\nSkipping line 5846: expected 2 fields, saw 3\\nSkipping line 5850: expected 2 fields, saw 4\\nSkipping line 5853: expected 2 fields, saw 3\\nSkipping line 5867: expected 2 fields, saw 3\\nSkipping line 5868: expected 2 fields, saw 3\\nSkipping line 5870: expected 2 fields, saw 3\\nSkipping line 5875: expected 2 fields, saw 3\\nSkipping line 5877: expected 2 fields, saw 3\\nSkipping line 5878: expected 2 fields, saw 3\\nSkipping line 5879: expected 2 fields, saw 3\\nSkipping line 5882: expected 2 fields, saw 3\\nSkipping line 5884: expected 2 fields, saw 3\\nSkipping line 5885: expected 2 fields, saw 3\\nSkipping line 5892: expected 2 fields, saw 3\\nSkipping line 5893: expected 2 fields, saw 4\\nSkipping line 5894: expected 2 fields, saw 4\\nSkipping line 5895: expected 2 fields, saw 3\\nSkipping line 5896: expected 2 fields, saw 3\\nSkipping line 5897: expected 2 fields, saw 3\\nSkipping line 5898: expected 2 fields, saw 4\\nSkipping line 5899: expected 2 fields, saw 3\\nSkipping line 5901: expected 2 fields, saw 4\\nSkipping line 5902: expected 2 fields, saw 3\\nSkipping line 5903: expected 2 fields, saw 4\\nSkipping line 5904: expected 2 fields, saw 3\\nSkipping line 5905: expected 2 fields, saw 3\\nSkipping line 5906: expected 2 fields, saw 3\\nSkipping line 5907: expected 2 fields, saw 3\\nSkipping line 5908: expected 2 fields, saw 3\\nSkipping line 5910: expected 2 fields, saw 3\\nSkipping line 5913: expected 2 fields, saw 3\\nSkipping line 5915: expected 2 fields, saw 3\\nSkipping line 5916: expected 2 fields, saw 3\\nSkipping line 5918: expected 2 fields, saw 3\\nSkipping line 5919: expected 2 fields, saw 3\\nSkipping line 5920: expected 2 fields, saw 3\\nSkipping line 5921: expected 2 fields, saw 3\\nSkipping line 5922: expected 2 fields, saw 3\\nSkipping line 5923: expected 2 fields, saw 3\\nSkipping line 5924: expected 2 fields, saw 3\\nSkipping line 5925: expected 2 fields, saw 3\\nSkipping line 5926: expected 2 fields, saw 3\\nSkipping line 5927: expected 2 fields, saw 3\\nSkipping line 5928: expected 2 fields, saw 3\\nSkipping line 5930: expected 2 fields, saw 3\\nSkipping line 5931: expected 2 fields, saw 3\\nSkipping line 5932: expected 2 fields, saw 3\\nSkipping line 5933: expected 2 fields, saw 3\\nSkipping line 5934: expected 2 fields, saw 3\\nSkipping line 5935: expected 2 fields, saw 3\\nSkipping line 5936: expected 2 fields, saw 3\\nSkipping line 5937: expected 2 fields, saw 3\\nSkipping line 5938: expected 2 fields, saw 3\\nSkipping line 5939: expected 2 fields, saw 3\\nSkipping line 5940: expected 2 fields, saw 3\\nSkipping line 5941: expected 2 fields, saw 3\\nSkipping line 5942: expected 2 fields, saw 4\\nSkipping line 5950: expected 2 fields, saw 4\\nSkipping line 5951: expected 2 fields, saw 5\\nSkipping line 5952: expected 2 fields, saw 3\\nSkipping line 5953: expected 2 fields, saw 3\\nSkipping line 5954: expected 2 fields, saw 3\\nSkipping line 5968: expected 2 fields, saw 3\\nSkipping line 5970: expected 2 fields, saw 3\\nSkipping line 5971: expected 2 fields, saw 3\\nSkipping line 5972: expected 2 fields, saw 3\\nSkipping line 5973: expected 2 fields, saw 3\\nSkipping line 5974: expected 2 fields, saw 3\\nSkipping line 5975: expected 2 fields, saw 3\\nSkipping line 5976: expected 2 fields, saw 3\\nSkipping line 5977: expected 2 fields, saw 3\\nSkipping line 5978: expected 2 fields, saw 3\\nSkipping line 5979: expected 2 fields, saw 3\\nSkipping line 5980: expected 2 fields, saw 3\\nSkipping line 5981: expected 2 fields, saw 3\\nSkipping line 5982: expected 2 fields, saw 3\\nSkipping line 5983: expected 2 fields, saw 3\\nSkipping line 5984: expected 2 fields, saw 3\\nSkipping line 5988: expected 2 fields, saw 3\\nSkipping line 5990: expected 2 fields, saw 3\\nSkipping line 5992: expected 2 fields, saw 3\\nSkipping line 5993: expected 2 fields, saw 3\\nSkipping line 6001: expected 2 fields, saw 3\\nSkipping line 6002: expected 2 fields, saw 3\\nSkipping line 6036: expected 2 fields, saw 3\\nSkipping line 6037: expected 2 fields, saw 4\\nSkipping line 6038: expected 2 fields, saw 4\\nSkipping line 6039: expected 2 fields, saw 4\\nSkipping line 6040: expected 2 fields, saw 3\\nSkipping line 6041: expected 2 fields, saw 4\\nSkipping line 6042: expected 2 fields, saw 4\\nSkipping line 6043: expected 2 fields, saw 4\\nSkipping line 6044: expected 2 fields, saw 3\\nSkipping line 6045: expected 2 fields, saw 3\\nSkipping line 6046: expected 2 fields, saw 3\\nSkipping line 6047: expected 2 fields, saw 3\\nSkipping line 6048: expected 2 fields, saw 3\\nSkipping line 6049: expected 2 fields, saw 3\\nSkipping line 6050: expected 2 fields, saw 3\\nSkipping line 6053: expected 2 fields, saw 3\\nSkipping line 6054: expected 2 fields, saw 3\\nSkipping line 6056: expected 2 fields, saw 3\\nSkipping line 6057: expected 2 fields, saw 3\\nSkipping line 6058: expected 2 fields, saw 3\\nSkipping line 6066: expected 2 fields, saw 3\\nSkipping line 6067: expected 2 fields, saw 3\\nSkipping line 6070: expected 2 fields, saw 3\\nSkipping line 6074: expected 2 fields, saw 3\\nSkipping line 6076: expected 2 fields, saw 3\\nSkipping line 6077: expected 2 fields, saw 3\\nSkipping line 6078: expected 2 fields, saw 3\\nSkipping line 6079: expected 2 fields, saw 4\\nSkipping line 6080: expected 2 fields, saw 3\\nSkipping line 6081: expected 2 fields, saw 3\\nSkipping line 6082: expected 2 fields, saw 3\\nSkipping line 6084: expected 2 fields, saw 3\\nSkipping line 6087: expected 2 fields, saw 4\\nSkipping line 6092: expected 2 fields, saw 3\\nSkipping line 6093: expected 2 fields, saw 3\\nSkipping line 6095: expected 2 fields, saw 3\\nSkipping line 6096: expected 2 fields, saw 4\\nSkipping line 6097: expected 2 fields, saw 3\\nSkipping line 6098: expected 2 fields, saw 3\\nSkipping line 6099: expected 2 fields, saw 3\\nSkipping line 6101: expected 2 fields, saw 3\\nSkipping line 6102: expected 2 fields, saw 4\\nSkipping line 6103: expected 2 fields, saw 3\\nSkipping line 6106: expected 2 fields, saw 3\\nSkipping line 6107: expected 2 fields, saw 3\\nSkipping line 6108: expected 2 fields, saw 3\\nSkipping line 6114: expected 2 fields, saw 3\\nSkipping line 6115: expected 2 fields, saw 3\\nSkipping line 6117: expected 2 fields, saw 3\\nSkipping line 6119: expected 2 fields, saw 3\\nSkipping line 6120: expected 2 fields, saw 3\\nSkipping line 6122: expected 2 fields, saw 3\\nSkipping line 6127: expected 2 fields, saw 5\\nSkipping line 6128: expected 2 fields, saw 4\\nSkipping line 6129: expected 2 fields, saw 3\\nSkipping line 6131: expected 2 fields, saw 4\\nSkipping line 6132: expected 2 fields, saw 3\\nSkipping line 6133: expected 2 fields, saw 3\\nSkipping line 6134: expected 2 fields, saw 3\\nSkipping line 6135: expected 2 fields, saw 3\\nSkipping line 6136: expected 2 fields, saw 3\\nSkipping line 6147: expected 2 fields, saw 3\\nSkipping line 6148: expected 2 fields, saw 4\\nSkipping line 6149: expected 2 fields, saw 4\\nSkipping line 6150: expected 2 fields, saw 4\\nSkipping line 6151: expected 2 fields, saw 3\\nSkipping line 6152: expected 2 fields, saw 4\\nSkipping line 6153: expected 2 fields, saw 4\\nSkipping line 6154: expected 2 fields, saw 5\\nSkipping line 6155: expected 2 fields, saw 3\\nSkipping line 6156: expected 2 fields, saw 3\\nSkipping line 6157: expected 2 fields, saw 3\\nSkipping line 6158: expected 2 fields, saw 4\\nSkipping line 6159: expected 2 fields, saw 4\\nSkipping line 6160: expected 2 fields, saw 3\\nSkipping line 6161: expected 2 fields, saw 4\\nSkipping line 6162: expected 2 fields, saw 4\\nSkipping line 6163: expected 2 fields, saw 4\\nSkipping line 6164: expected 2 fields, saw 4\\nSkipping line 6165: expected 2 fields, saw 4\\nSkipping line 6166: expected 2 fields, saw 4\\nSkipping line 6167: expected 2 fields, saw 4\\nSkipping line 6168: expected 2 fields, saw 4\\nSkipping line 6169: expected 2 fields, saw 4\\nSkipping line 6170: expected 2 fields, saw 4\\nSkipping line 6171: expected 2 fields, saw 4\\nSkipping line 6172: expected 2 fields, saw 4\\nSkipping line 6173: expected 2 fields, saw 4\\nSkipping line 6174: expected 2 fields, saw 3\\nSkipping line 6175: expected 2 fields, saw 4\\nSkipping line 6176: expected 2 fields, saw 4\\nSkipping line 6177: expected 2 fields, saw 4\\nSkipping line 6178: expected 2 fields, saw 4\\nSkipping line 6179: expected 2 fields, saw 4\\nSkipping line 6180: expected 2 fields, saw 4\\nSkipping line 6181: expected 2 fields, saw 4\\nSkipping line 6182: expected 2 fields, saw 4\\nSkipping line 6183: expected 2 fields, saw 3\\nSkipping line 6184: expected 2 fields, saw 3\\nSkipping line 6185: expected 2 fields, saw 4\\nSkipping line 6186: expected 2 fields, saw 4\\nSkipping line 6187: expected 2 fields, saw 3\\nSkipping line 6188: expected 2 fields, saw 5\\nSkipping line 6189: expected 2 fields, saw 4\\nSkipping line 6190: expected 2 fields, saw 4\\nSkipping line 6191: expected 2 fields, saw 4\\nSkipping line 6192: expected 2 fields, saw 4\\nSkipping line 6193: expected 2 fields, saw 4\\nSkipping line 6194: expected 2 fields, saw 4\\nSkipping line 6195: expected 2 fields, saw 4\\nSkipping line 6196: expected 2 fields, saw 4\\nSkipping line 6197: expected 2 fields, saw 4\\nSkipping line 6198: expected 2 fields, saw 4\\nSkipping line 6199: expected 2 fields, saw 4\\nSkipping line 6200: expected 2 fields, saw 3\\nSkipping line 6201: expected 2 fields, saw 4\\nSkipping line 6202: expected 2 fields, saw 5\\nSkipping line 6203: expected 2 fields, saw 4\\nSkipping line 6204: expected 2 fields, saw 4\\nSkipping line 6205: expected 2 fields, saw 4\\nSkipping line 6206: expected 2 fields, saw 6\\nSkipping line 6207: expected 2 fields, saw 4\\nSkipping line 6208: expected 2 fields, saw 4\\nSkipping line 6209: expected 2 fields, saw 3\\nSkipping line 6210: expected 2 fields, saw 4\\nSkipping line 6211: expected 2 fields, saw 5\\nSkipping line 6212: expected 2 fields, saw 4\\nSkipping line 6213: expected 2 fields, saw 4\\nSkipping line 6214: expected 2 fields, saw 4\\nSkipping line 6215: expected 2 fields, saw 4\\nSkipping line 6216: expected 2 fields, saw 4\\nSkipping line 6217: expected 2 fields, saw 4\\nSkipping line 6218: expected 2 fields, saw 4\\nSkipping line 6219: expected 2 fields, saw 4\\nSkipping line 6220: expected 2 fields, saw 4\\nSkipping line 6221: expected 2 fields, saw 4\\nSkipping line 6222: expected 2 fields, saw 4\\nSkipping line 6223: expected 2 fields, saw 4\\nSkipping line 6224: expected 2 fields, saw 5\\nSkipping line 6225: expected 2 fields, saw 5\\nSkipping line 6226: expected 2 fields, saw 4\\nSkipping line 6227: expected 2 fields, saw 4\\nSkipping line 6228: expected 2 fields, saw 5\\nSkipping line 6229: expected 2 fields, saw 5\\nSkipping line 6230: expected 2 fields, saw 4\\nSkipping line 6231: expected 2 fields, saw 5\\nSkipping line 6232: expected 2 fields, saw 4\\nSkipping line 6233: expected 2 fields, saw 4\\nSkipping line 6234: expected 2 fields, saw 4\\nSkipping line 6235: expected 2 fields, saw 4\\nSkipping line 6236: expected 2 fields, saw 4\\nSkipping line 6237: expected 2 fields, saw 4\\nSkipping line 6238: expected 2 fields, saw 3\\nSkipping line 6239: expected 2 fields, saw 4\\nSkipping line 6240: expected 2 fields, saw 4\\nSkipping line 6241: expected 2 fields, saw 4\\nSkipping line 6242: expected 2 fields, saw 4\\nSkipping line 6243: expected 2 fields, saw 4\\nSkipping line 6244: expected 2 fields, saw 4\\nSkipping line 6245: expected 2 fields, saw 4\\nSkipping line 6246: expected 2 fields, saw 3\\nSkipping line 6247: expected 2 fields, saw 3\\nSkipping line 6248: expected 2 fields, saw 4\\nSkipping line 6249: expected 2 fields, saw 4\\nSkipping line 6250: expected 2 fields, saw 4\\nSkipping line 6251: expected 2 fields, saw 4\\nSkipping line 6252: expected 2 fields, saw 4\\nSkipping line 6253: expected 2 fields, saw 3\\nSkipping line 6254: expected 2 fields, saw 4\\nSkipping line 6255: expected 2 fields, saw 4\\nSkipping line 6258: expected 2 fields, saw 3\\nSkipping line 6259: expected 2 fields, saw 3\\nSkipping line 6260: expected 2 fields, saw 3\\nSkipping line 6261: expected 2 fields, saw 3\\nSkipping line 6262: expected 2 fields, saw 4\\nSkipping line 6266: expected 2 fields, saw 4\\nSkipping line 6270: expected 2 fields, saw 3\\nSkipping line 6273: expected 2 fields, saw 3\\nSkipping line 6274: expected 2 fields, saw 3\\nSkipping line 6275: expected 2 fields, saw 3\\nSkipping line 6276: expected 2 fields, saw 3\\nSkipping line 6280: expected 2 fields, saw 3\\nSkipping line 6282: expected 2 fields, saw 4\\nSkipping line 6285: expected 2 fields, saw 4\\nSkipping line 6286: expected 2 fields, saw 3\\nSkipping line 6288: expected 2 fields, saw 3\\nSkipping line 6289: expected 2 fields, saw 3\\nSkipping line 6290: expected 2 fields, saw 3\\nSkipping line 6294: expected 2 fields, saw 3\\nSkipping line 6296: expected 2 fields, saw 4\\nSkipping line 6301: expected 2 fields, saw 3\\nSkipping line 6303: expected 2 fields, saw 3\\nSkipping line 6304: expected 2 fields, saw 3\\nSkipping line 6306: expected 2 fields, saw 3\\nSkipping line 6307: expected 2 fields, saw 3\\nSkipping line 6310: expected 2 fields, saw 3\\nSkipping line 6311: expected 2 fields, saw 3\\nSkipping line 6312: expected 2 fields, saw 3\\nSkipping line 6313: expected 2 fields, saw 3\\nSkipping line 6315: expected 2 fields, saw 4\\nSkipping line 6316: expected 2 fields, saw 3\\nSkipping line 6317: expected 2 fields, saw 3\\nSkipping line 6319: expected 2 fields, saw 3\\nSkipping line 6322: expected 2 fields, saw 3\\nSkipping line 6323: expected 2 fields, saw 3\\nSkipping line 6324: expected 2 fields, saw 3\\nSkipping line 6325: expected 2 fields, saw 3\\nSkipping line 6338: expected 2 fields, saw 3\\nSkipping line 6339: expected 2 fields, saw 3\\nSkipping line 6342: expected 2 fields, saw 3\\nSkipping line 6343: expected 2 fields, saw 3\\nSkipping line 6344: expected 2 fields, saw 3\\nSkipping line 6345: expected 2 fields, saw 3\\nSkipping line 6348: expected 2 fields, saw 3\\nSkipping line 6349: expected 2 fields, saw 3\\nSkipping line 6352: expected 2 fields, saw 3\\nSkipping line 6353: expected 2 fields, saw 3\\nSkipping line 6354: expected 2 fields, saw 3\\nSkipping line 6355: expected 2 fields, saw 3\\nSkipping line 6358: expected 2 fields, saw 3\\nSkipping line 6359: expected 2 fields, saw 3\\nSkipping line 6360: expected 2 fields, saw 3\\nSkipping line 6361: expected 2 fields, saw 3\\nSkipping line 6362: expected 2 fields, saw 3\\nSkipping line 6363: expected 2 fields, saw 3\\nSkipping line 6369: expected 2 fields, saw 3\\nSkipping line 6370: expected 2 fields, saw 3\\nSkipping line 6371: expected 2 fields, saw 4\\nSkipping line 6372: expected 2 fields, saw 3\\nSkipping line 6373: expected 2 fields, saw 3\\nSkipping line 6374: expected 2 fields, saw 3\\nSkipping line 6375: expected 2 fields, saw 3\\nSkipping line 6376: expected 2 fields, saw 3\\nSkipping line 6377: expected 2 fields, saw 3\\nSkipping line 6378: expected 2 fields, saw 4\\nSkipping line 6379: expected 2 fields, saw 3\\nSkipping line 6380: expected 2 fields, saw 3\\nSkipping line 6381: expected 2 fields, saw 3\\nSkipping line 6383: expected 2 fields, saw 3\\nSkipping line 6385: expected 2 fields, saw 3\\nSkipping line 6387: expected 2 fields, saw 3\\nSkipping line 6391: expected 2 fields, saw 3\\nSkipping line 6395: expected 2 fields, saw 3\\nSkipping line 6396: expected 2 fields, saw 3\\nSkipping line 6400: expected 2 fields, saw 3\\nSkipping line 6403: expected 2 fields, saw 3\\nSkipping line 6404: expected 2 fields, saw 3\\nSkipping line 6405: expected 2 fields, saw 3\\nSkipping line 6416: expected 2 fields, saw 4\\nSkipping line 6417: expected 2 fields, saw 3\\nSkipping line 6419: expected 2 fields, saw 3\\nSkipping line 6420: expected 2 fields, saw 4\\nSkipping line 6421: expected 2 fields, saw 3\\nSkipping line 6422: expected 2 fields, saw 3\\nSkipping line 6423: expected 2 fields, saw 3\\nSkipping line 6425: expected 2 fields, saw 3\\nSkipping line 6438: expected 2 fields, saw 3\\nSkipping line 6440: expected 2 fields, saw 3\\nSkipping line 6441: expected 2 fields, saw 3\\nSkipping line 6448: expected 2 fields, saw 3\\nSkipping line 6449: expected 2 fields, saw 3\\nSkipping line 6455: expected 2 fields, saw 3\\nSkipping line 6471: expected 2 fields, saw 3\\nSkipping line 6472: expected 2 fields, saw 3\\nSkipping line 6473: expected 2 fields, saw 3\\nSkipping line 6474: expected 2 fields, saw 3\\nSkipping line 6475: expected 2 fields, saw 3\\nSkipping line 6476: expected 2 fields, saw 3\\nSkipping line 6477: expected 2 fields, saw 3\\nSkipping line 6478: expected 2 fields, saw 3\\nSkipping line 6479: expected 2 fields, saw 3\\nSkipping line 6490: expected 2 fields, saw 3\\nSkipping line 6493: expected 2 fields, saw 3\\nSkipping line 6494: expected 2 fields, saw 3\\nSkipping line 6514: expected 2 fields, saw 3\\nSkipping line 6515: expected 2 fields, saw 3\\nSkipping line 6518: expected 2 fields, saw 3\\nSkipping line 6528: expected 2 fields, saw 3\\nSkipping line 6529: expected 2 fields, saw 4\\nSkipping line 6530: expected 2 fields, saw 3\\nSkipping line 6532: expected 2 fields, saw 3\\nSkipping line 6534: expected 2 fields, saw 4\\nSkipping line 6535: expected 2 fields, saw 5\\nSkipping line 6536: expected 2 fields, saw 5\\nSkipping line 6537: expected 2 fields, saw 3\\nSkipping line 6538: expected 2 fields, saw 3\\nSkipping line 6561: expected 2 fields, saw 3\\nSkipping line 6562: expected 2 fields, saw 3\\nSkipping line 6563: expected 2 fields, saw 3\\nSkipping line 6565: expected 2 fields, saw 3\\nSkipping line 6566: expected 2 fields, saw 3\\nSkipping line 6570: expected 2 fields, saw 3\\nSkipping line 6572: expected 2 fields, saw 3\\nSkipping line 6573: expected 2 fields, saw 3\\nSkipping line 6575: expected 2 fields, saw 3\\nSkipping line 6580: expected 2 fields, saw 3\\nSkipping line 6583: expected 2 fields, saw 3\\nSkipping line 6588: expected 2 fields, saw 4\\nSkipping line 6591: expected 2 fields, saw 3\\nSkipping line 6593: expected 2 fields, saw 3\\nSkipping line 6594: expected 2 fields, saw 3\\nSkipping line 6595: expected 2 fields, saw 3\\nSkipping line 6596: expected 2 fields, saw 3\\nSkipping line 6598: expected 2 fields, saw 3\\nSkipping line 6606: expected 2 fields, saw 3\\nSkipping line 6607: expected 2 fields, saw 3\\nSkipping line 6608: expected 2 fields, saw 3\\nSkipping line 6610: expected 2 fields, saw 3\\nSkipping line 6612: expected 2 fields, saw 3\\nSkipping line 6616: expected 2 fields, saw 3\\nSkipping line 6617: expected 2 fields, saw 3\\nSkipping line 6618: expected 2 fields, saw 3\\nSkipping line 6619: expected 2 fields, saw 3\\nSkipping line 6620: expected 2 fields, saw 3\\nSkipping line 6621: expected 2 fields, saw 3\\nSkipping line 6622: expected 2 fields, saw 3\\nSkipping line 6623: expected 2 fields, saw 4\\nSkipping line 6624: expected 2 fields, saw 3\\nSkipping line 6625: expected 2 fields, saw 3\\nSkipping line 6626: expected 2 fields, saw 3\\nSkipping line 6627: expected 2 fields, saw 3\\nSkipping line 6628: expected 2 fields, saw 3\\nSkipping line 6629: expected 2 fields, saw 3\\nSkipping line 6630: expected 2 fields, saw 4\\nSkipping line 6631: expected 2 fields, saw 3\\nSkipping line 6639: expected 2 fields, saw 3\\nSkipping line 6644: expected 2 fields, saw 3\\nSkipping line 6645: expected 2 fields, saw 3\\nSkipping line 6646: expected 2 fields, saw 4\\nSkipping line 6651: expected 2 fields, saw 3\\nSkipping line 6652: expected 2 fields, saw 3\\nSkipping line 6653: expected 2 fields, saw 3\\nSkipping line 6654: expected 2 fields, saw 4\\nSkipping line 6655: expected 2 fields, saw 3\\nSkipping line 6656: expected 2 fields, saw 3\\nSkipping line 6657: expected 2 fields, saw 3\\nSkipping line 6658: expected 2 fields, saw 3\\nSkipping line 6659: expected 2 fields, saw 3\\nSkipping line 6660: expected 2 fields, saw 3\\nSkipping line 6661: expected 2 fields, saw 3\\nSkipping line 6662: expected 2 fields, saw 3\\nSkipping line 6663: expected 2 fields, saw 3\\nSkipping line 6664: expected 2 fields, saw 3\\nSkipping line 6672: expected 2 fields, saw 3\\nSkipping line 6674: expected 2 fields, saw 3\\nSkipping line 6677: expected 2 fields, saw 3\\nSkipping line 6678: expected 2 fields, saw 3\\nSkipping line 6691: expected 2 fields, saw 3\\nSkipping line 6693: expected 2 fields, saw 3\\nSkipping line 6694: expected 2 fields, saw 3\\nSkipping line 6697: expected 2 fields, saw 3\\nSkipping line 6698: expected 2 fields, saw 3\\nSkipping line 6699: expected 2 fields, saw 3\\nSkipping line 6702: expected 2 fields, saw 3\\nSkipping line 6709: expected 2 fields, saw 4\\nSkipping line 6710: expected 2 fields, saw 3\\nSkipping line 6725: expected 2 fields, saw 3\\nSkipping line 6726: expected 2 fields, saw 3\\nSkipping line 6733: expected 2 fields, saw 3\\nSkipping line 6734: expected 2 fields, saw 3\\nSkipping line 6735: expected 2 fields, saw 3\\nSkipping line 6736: expected 2 fields, saw 3\\nSkipping line 6737: expected 2 fields, saw 3\\nSkipping line 6739: expected 2 fields, saw 3\\nSkipping line 6740: expected 2 fields, saw 3\\nSkipping line 6741: expected 2 fields, saw 3\\nSkipping line 6753: expected 2 fields, saw 3\\nSkipping line 6756: expected 2 fields, saw 3\\nSkipping line 6791: expected 2 fields, saw 3\\nSkipping line 6792: expected 2 fields, saw 3\\nSkipping line 6793: expected 2 fields, saw 3\\nSkipping line 6794: expected 2 fields, saw 3\\nSkipping line 6795: expected 2 fields, saw 3\\nSkipping line 6797: expected 2 fields, saw 3\\nSkipping line 6798: expected 2 fields, saw 3\\nSkipping line 6799: expected 2 fields, saw 3\\nSkipping line 6803: expected 2 fields, saw 3\\nSkipping line 6825: expected 2 fields, saw 3\\nSkipping line 6826: expected 2 fields, saw 3\\nSkipping line 6828: expected 2 fields, saw 3\\nSkipping line 6829: expected 2 fields, saw 3\\nSkipping line 6830: expected 2 fields, saw 3\\nSkipping line 6864: expected 2 fields, saw 3\\nSkipping line 6865: expected 2 fields, saw 3\\nSkipping line 6866: expected 2 fields, saw 3\\nSkipping line 6867: expected 2 fields, saw 4\\nSkipping line 6885: expected 2 fields, saw 3\\nSkipping line 6889: expected 2 fields, saw 3\\nSkipping line 6890: expected 2 fields, saw 3\\nSkipping line 6891: expected 2 fields, saw 3\\nSkipping line 6892: expected 2 fields, saw 3\\nSkipping line 6893: expected 2 fields, saw 3\\nSkipping line 6894: expected 2 fields, saw 3\\nSkipping line 6896: expected 2 fields, saw 3\\nSkipping line 6898: expected 2 fields, saw 3\\nSkipping line 6899: expected 2 fields, saw 3\\nSkipping line 6911: expected 2 fields, saw 3\\nSkipping line 6912: expected 2 fields, saw 3\\nSkipping line 6913: expected 2 fields, saw 3\\nSkipping line 6914: expected 2 fields, saw 4\\nSkipping line 6916: expected 2 fields, saw 3\\nSkipping line 6917: expected 2 fields, saw 3\\nSkipping line 6919: expected 2 fields, saw 3\\nSkipping line 6920: expected 2 fields, saw 3\\nSkipping line 6921: expected 2 fields, saw 3\\nSkipping line 6922: expected 2 fields, saw 3\\nSkipping line 6923: expected 2 fields, saw 3\\nSkipping line 6924: expected 2 fields, saw 3\\nSkipping line 6925: expected 2 fields, saw 3\\nSkipping line 6932: expected 2 fields, saw 3\\nSkipping line 6934: expected 2 fields, saw 3\\nSkipping line 6935: expected 2 fields, saw 3\\nSkipping line 6936: expected 2 fields, saw 3\\nSkipping line 6937: expected 2 fields, saw 3\\nSkipping line 6938: expected 2 fields, saw 4\\nSkipping line 6939: expected 2 fields, saw 3\\nSkipping line 6940: expected 2 fields, saw 3\\nSkipping line 6941: expected 2 fields, saw 3\\nSkipping line 6942: expected 2 fields, saw 3\\nSkipping line 6943: expected 2 fields, saw 3\\nSkipping line 6944: expected 2 fields, saw 3\\nSkipping line 6945: expected 2 fields, saw 3\\nSkipping line 6948: expected 2 fields, saw 3\\nSkipping line 6949: expected 2 fields, saw 3\\nSkipping line 6950: expected 2 fields, saw 3\\nSkipping line 6951: expected 2 fields, saw 3\\nSkipping line 6952: expected 2 fields, saw 3\\nSkipping line 6953: expected 2 fields, saw 3\\nSkipping line 6955: expected 2 fields, saw 5\\nSkipping line 6956: expected 2 fields, saw 3\\nSkipping line 6957: expected 2 fields, saw 3\\nSkipping line 6959: expected 2 fields, saw 4\\nSkipping line 6960: expected 2 fields, saw 4\\nSkipping line 6961: expected 2 fields, saw 3\\nSkipping line 6965: expected 2 fields, saw 3\\nSkipping line 6966: expected 2 fields, saw 3\\nSkipping line 6969: expected 2 fields, saw 3\\nSkipping line 6970: expected 2 fields, saw 3\\nSkipping line 6972: expected 2 fields, saw 3\\nSkipping line 6973: expected 2 fields, saw 3\\nSkipping line 6974: expected 2 fields, saw 3\\nSkipping line 6976: expected 2 fields, saw 3\\nSkipping line 6981: expected 2 fields, saw 3\\nSkipping line 6982: expected 2 fields, saw 3\\nSkipping line 6983: expected 2 fields, saw 3\\nSkipping line 6985: expected 2 fields, saw 3\\nSkipping line 6986: expected 2 fields, saw 3\\nSkipping line 6987: expected 2 fields, saw 3\\nSkipping line 6988: expected 2 fields, saw 3\\nSkipping line 6989: expected 2 fields, saw 3\\nSkipping line 6990: expected 2 fields, saw 3\\nSkipping line 6991: expected 2 fields, saw 3\\nSkipping line 6992: expected 2 fields, saw 3\\nSkipping line 6993: expected 2 fields, saw 3\\nSkipping line 6994: expected 2 fields, saw 3\\nSkipping line 6995: expected 2 fields, saw 3\\nSkipping line 6996: expected 2 fields, saw 3\\nSkipping line 6997: expected 2 fields, saw 3\\nSkipping line 6998: expected 2 fields, saw 3\\nSkipping line 6999: expected 2 fields, saw 3\\nSkipping line 7000: expected 2 fields, saw 3\\nSkipping line 7001: expected 2 fields, saw 3\\nSkipping line 7002: expected 2 fields, saw 3\\nSkipping line 7003: expected 2 fields, saw 3\\nSkipping line 7004: expected 2 fields, saw 3\\nSkipping line 7008: expected 2 fields, saw 3\\nSkipping line 7009: expected 2 fields, saw 3\\nSkipping line 7011: expected 2 fields, saw 3\\nSkipping line 7012: expected 2 fields, saw 3\\nSkipping line 7026: expected 2 fields, saw 3\\nSkipping line 7027: expected 2 fields, saw 3\\nSkipping line 7030: expected 2 fields, saw 3\\nSkipping line 7031: expected 2 fields, saw 3\\nSkipping line 7032: expected 2 fields, saw 3\\nSkipping line 7033: expected 2 fields, saw 3\\nSkipping line 7034: expected 2 fields, saw 3\\nSkipping line 7035: expected 2 fields, saw 3\\nSkipping line 7036: expected 2 fields, saw 3\\nSkipping line 7056: expected 2 fields, saw 3\\nSkipping line 7060: expected 2 fields, saw 3\\nSkipping line 7061: expected 2 fields, saw 3\\nSkipping line 7062: expected 2 fields, saw 3\\nSkipping line 7063: expected 2 fields, saw 3\\nSkipping line 7064: expected 2 fields, saw 3\\nSkipping line 7065: expected 2 fields, saw 3\\nSkipping line 7072: expected 2 fields, saw 3\\nSkipping line 7073: expected 2 fields, saw 3\\nSkipping line 7074: expected 2 fields, saw 3\\nSkipping line 7075: expected 2 fields, saw 3\\nSkipping line 7078: expected 2 fields, saw 5\\nSkipping line 7079: expected 2 fields, saw 3\\nSkipping line 7080: expected 2 fields, saw 3\\nSkipping line 7084: expected 2 fields, saw 3\\nSkipping line 7089: expected 2 fields, saw 3\\nSkipping line 7092: expected 2 fields, saw 3\\nSkipping line 7093: expected 2 fields, saw 3\\nSkipping line 7097: expected 2 fields, saw 3\\nSkipping line 7099: expected 2 fields, saw 3\\nSkipping line 7100: expected 2 fields, saw 4\\nSkipping line 7106: expected 2 fields, saw 3\\nSkipping line 7107: expected 2 fields, saw 3\\nSkipping line 7108: expected 2 fields, saw 3\\nSkipping line 7113: expected 2 fields, saw 3\\nSkipping line 7114: expected 2 fields, saw 3\\nSkipping line 7115: expected 2 fields, saw 3\\nSkipping line 7116: expected 2 fields, saw 3\\nSkipping line 7118: expected 2 fields, saw 4\\nSkipping line 7119: expected 2 fields, saw 3\\nSkipping line 7120: expected 2 fields, saw 3\\nSkipping line 7121: expected 2 fields, saw 3\\nSkipping line 7122: expected 2 fields, saw 3\\nSkipping line 7124: expected 2 fields, saw 3\\nSkipping line 7126: expected 2 fields, saw 3\\nSkipping line 7128: expected 2 fields, saw 3\\nSkipping line 7129: expected 2 fields, saw 3\\nSkipping line 7130: expected 2 fields, saw 3\\nSkipping line 7131: expected 2 fields, saw 3\\nSkipping line 7132: expected 2 fields, saw 3\\nSkipping line 7136: expected 2 fields, saw 4\\nSkipping line 7138: expected 2 fields, saw 3\\nSkipping line 7139: expected 2 fields, saw 3\\nSkipping line 7143: expected 2 fields, saw 3\\nSkipping line 7144: expected 2 fields, saw 3\\nSkipping line 7145: expected 2 fields, saw 3\\nSkipping line 7146: expected 2 fields, saw 3\\nSkipping line 7147: expected 2 fields, saw 3\\nSkipping line 7148: expected 2 fields, saw 3\\nSkipping line 7149: expected 2 fields, saw 3\\nSkipping line 7150: expected 2 fields, saw 3\\nSkipping line 7152: expected 2 fields, saw 3\\nSkipping line 7153: expected 2 fields, saw 3\\nSkipping line 7156: expected 2 fields, saw 3\\nSkipping line 7157: expected 2 fields, saw 3\\nSkipping line 7158: expected 2 fields, saw 3\\nSkipping line 7159: expected 2 fields, saw 3\\nSkipping line 7160: expected 2 fields, saw 3\\nSkipping line 7161: expected 2 fields, saw 3\\nSkipping line 7162: expected 2 fields, saw 3\\nSkipping line 7163: expected 2 fields, saw 3\\nSkipping line 7164: expected 2 fields, saw 3\\nSkipping line 7165: expected 2 fields, saw 3\\nSkipping line 7166: expected 2 fields, saw 3\\nSkipping line 7167: expected 2 fields, saw 3\\nSkipping line 7168: expected 2 fields, saw 3\\nSkipping line 7169: expected 2 fields, saw 3\\nSkipping line 7170: expected 2 fields, saw 4\\nSkipping line 7171: expected 2 fields, saw 3\\nSkipping line 7172: expected 2 fields, saw 3\\nSkipping line 7173: expected 2 fields, saw 3\\nSkipping line 7174: expected 2 fields, saw 3\\nSkipping line 7175: expected 2 fields, saw 4\\nSkipping line 7176: expected 2 fields, saw 3\\nSkipping line 7178: expected 2 fields, saw 3\\nSkipping line 7186: expected 2 fields, saw 3\\nSkipping line 7188: expected 2 fields, saw 3\\nSkipping line 7190: expected 2 fields, saw 3\\nSkipping line 7191: expected 2 fields, saw 3\\nSkipping line 7192: expected 2 fields, saw 3\\nSkipping line 7193: expected 2 fields, saw 4\\nSkipping line 7194: expected 2 fields, saw 3\\nSkipping line 7195: expected 2 fields, saw 3\\nSkipping line 7196: expected 2 fields, saw 3\\nSkipping line 7197: expected 2 fields, saw 3\\nSkipping line 7198: expected 2 fields, saw 3\\nSkipping line 7199: expected 2 fields, saw 3\\nSkipping line 7200: expected 2 fields, saw 3\\nSkipping line 7201: expected 2 fields, saw 3\\nSkipping line 7202: expected 2 fields, saw 3\\nSkipping line 7203: expected 2 fields, saw 3\\nSkipping line 7206: expected 2 fields, saw 3\\nSkipping line 7207: expected 2 fields, saw 3\\nSkipping line 7210: expected 2 fields, saw 3\\nSkipping line 7213: expected 2 fields, saw 3\\nSkipping line 7214: expected 2 fields, saw 3\\nSkipping line 7215: expected 2 fields, saw 3\\nSkipping line 7219: expected 2 fields, saw 3\\nSkipping line 7220: expected 2 fields, saw 3\\nSkipping line 7221: expected 2 fields, saw 3\\nSkipping line 7223: expected 2 fields, saw 3\\nSkipping line 7227: expected 2 fields, saw 3\\nSkipping line 7233: expected 2 fields, saw 3\\nSkipping line 7234: expected 2 fields, saw 3\\nSkipping line 7235: expected 2 fields, saw 3\\nSkipping line 7236: expected 2 fields, saw 3\\nSkipping line 7237: expected 2 fields, saw 3\\nSkipping line 7238: expected 2 fields, saw 3\\nSkipping line 7241: expected 2 fields, saw 3\\nSkipping line 7245: expected 2 fields, saw 3\\nSkipping line 7248: expected 2 fields, saw 3\\nSkipping line 7250: expected 2 fields, saw 3\\nSkipping line 7255: expected 2 fields, saw 3\\nSkipping line 7256: expected 2 fields, saw 3\\nSkipping line 7257: expected 2 fields, saw 3\\nSkipping line 7262: expected 2 fields, saw 3\\nSkipping line 7265: expected 2 fields, saw 3\\nSkipping line 7272: expected 2 fields, saw 3\\nSkipping line 7273: expected 2 fields, saw 3\\nSkipping line 7275: expected 2 fields, saw 3\\nSkipping line 7276: expected 2 fields, saw 3\\nSkipping line 7277: expected 2 fields, saw 3\\nSkipping line 7286: expected 2 fields, saw 3\\nSkipping line 7288: expected 2 fields, saw 3\\nSkipping line 7290: expected 2 fields, saw 3\\nSkipping line 7291: expected 2 fields, saw 3\\nSkipping line 7294: expected 2 fields, saw 3\\nSkipping line 7297: expected 2 fields, saw 3\\nSkipping line 7298: expected 2 fields, saw 3\\nSkipping line 7300: expected 2 fields, saw 3\\nSkipping line 7301: expected 2 fields, saw 3\\nSkipping line 7302: expected 2 fields, saw 3\\nSkipping line 7304: expected 2 fields, saw 3\\nSkipping line 7305: expected 2 fields, saw 3\\nSkipping line 7308: expected 2 fields, saw 4\\nSkipping line 7311: expected 2 fields, saw 3\\nSkipping line 7318: expected 2 fields, saw 3\\nSkipping line 7323: expected 2 fields, saw 3\\nSkipping line 7324: expected 2 fields, saw 3\\nSkipping line 7327: expected 2 fields, saw 3\\nSkipping line 7332: expected 2 fields, saw 3\\nSkipping line 7333: expected 2 fields, saw 3\\nSkipping line 7335: expected 2 fields, saw 3\\nSkipping line 7337: expected 2 fields, saw 3\\nSkipping line 7339: expected 2 fields, saw 3\\nSkipping line 7341: expected 2 fields, saw 3\\nSkipping line 7342: expected 2 fields, saw 3\\nSkipping line 7346: expected 2 fields, saw 3\\nSkipping line 7347: expected 2 fields, saw 3\\nSkipping line 7348: expected 2 fields, saw 3\\nSkipping line 7349: expected 2 fields, saw 3\\nSkipping line 7352: expected 2 fields, saw 3\\nSkipping line 7353: expected 2 fields, saw 4\\nSkipping line 7356: expected 2 fields, saw 3\\nSkipping line 7357: expected 2 fields, saw 3\\nSkipping line 7359: expected 2 fields, saw 3\\nSkipping line 7360: expected 2 fields, saw 3\\nSkipping line 7361: expected 2 fields, saw 3\\nSkipping line 7362: expected 2 fields, saw 4\\nSkipping line 7363: expected 2 fields, saw 3\\nSkipping line 7364: expected 2 fields, saw 3\\nSkipping line 7365: expected 2 fields, saw 3\\nSkipping line 7366: expected 2 fields, saw 3\\nSkipping line 7367: expected 2 fields, saw 3\\nSkipping line 7368: expected 2 fields, saw 3\\nSkipping line 7369: expected 2 fields, saw 3\\nSkipping line 7370: expected 2 fields, saw 3\\nSkipping line 7371: expected 2 fields, saw 3\\nSkipping line 7373: expected 2 fields, saw 4\\nSkipping line 7375: expected 2 fields, saw 3\\nSkipping line 7380: expected 2 fields, saw 3\\nSkipping line 7381: expected 2 fields, saw 3\\nSkipping line 7382: expected 2 fields, saw 3\\nSkipping line 7383: expected 2 fields, saw 3\\nSkipping line 7384: expected 2 fields, saw 3\\nSkipping line 7386: expected 2 fields, saw 3\\nSkipping line 7387: expected 2 fields, saw 3\\nSkipping line 7388: expected 2 fields, saw 3\\nSkipping line 7390: expected 2 fields, saw 3\\nSkipping line 7391: expected 2 fields, saw 3\\nSkipping line 7394: expected 2 fields, saw 3\\nSkipping line 7395: expected 2 fields, saw 3\\nSkipping line 7396: expected 2 fields, saw 3\\nSkipping line 7397: expected 2 fields, saw 3\\nSkipping line 7398: expected 2 fields, saw 3\\nSkipping line 7399: expected 2 fields, saw 3\\nSkipping line 7400: expected 2 fields, saw 3\\nSkipping line 7401: expected 2 fields, saw 4\\nSkipping line 7402: expected 2 fields, saw 3\\nSkipping line 7404: expected 2 fields, saw 3\\nSkipping line 7405: expected 2 fields, saw 3\\nSkipping line 7406: expected 2 fields, saw 3\\nSkipping line 7407: expected 2 fields, saw 3\\nSkipping line 7408: expected 2 fields, saw 3\\nSkipping line 7410: expected 2 fields, saw 3\\nSkipping line 7411: expected 2 fields, saw 3\\nSkipping line 7412: expected 2 fields, saw 3\\nSkipping line 7413: expected 2 fields, saw 3\\nSkipping line 7414: expected 2 fields, saw 3\\nSkipping line 7415: expected 2 fields, saw 3\\nSkipping line 7417: expected 2 fields, saw 4\\nSkipping line 7418: expected 2 fields, saw 3\\nSkipping line 7419: expected 2 fields, saw 3\\nSkipping line 7420: expected 2 fields, saw 3\\nSkipping line 7421: expected 2 fields, saw 3\\nSkipping line 7424: expected 2 fields, saw 3\\nSkipping line 7426: expected 2 fields, saw 3\\nSkipping line 7427: expected 2 fields, saw 3\\nSkipping line 7428: expected 2 fields, saw 3\\nSkipping line 7429: expected 2 fields, saw 3\\nSkipping line 7432: expected 2 fields, saw 3\\nSkipping line 7436: expected 2 fields, saw 3\\nSkipping line 7438: expected 2 fields, saw 3\\nSkipping line 7439: expected 2 fields, saw 4\\nSkipping line 7441: expected 2 fields, saw 3\\nSkipping line 7445: expected 2 fields, saw 3\\nSkipping line 7447: expected 2 fields, saw 3\\nSkipping line 7450: expected 2 fields, saw 3\\nSkipping line 7451: expected 2 fields, saw 3\\nSkipping line 7453: expected 2 fields, saw 3\\nSkipping line 7454: expected 2 fields, saw 3\\nSkipping line 7455: expected 2 fields, saw 3\\nSkipping line 7456: expected 2 fields, saw 3\\nSkipping line 7457: expected 2 fields, saw 3\\nSkipping line 7459: expected 2 fields, saw 3\\nSkipping line 7466: expected 2 fields, saw 3\\nSkipping line 7467: expected 2 fields, saw 3\\nSkipping line 7471: expected 2 fields, saw 3\\nSkipping line 7472: expected 2 fields, saw 3\\nSkipping line 7479: expected 2 fields, saw 3\\nSkipping line 7480: expected 2 fields, saw 3\\nSkipping line 7481: expected 2 fields, saw 3\\nSkipping line 7482: expected 2 fields, saw 3\\nSkipping line 7483: expected 2 fields, saw 3\\nSkipping line 7484: expected 2 fields, saw 3\\nSkipping line 7485: expected 2 fields, saw 3\\nSkipping line 7486: expected 2 fields, saw 3\\nSkipping line 7488: expected 2 fields, saw 3\\nSkipping line 7490: expected 2 fields, saw 3\\nSkipping line 7491: expected 2 fields, saw 3\\nSkipping line 7492: expected 2 fields, saw 3\\nSkipping line 7493: expected 2 fields, saw 3\\nSkipping line 7494: expected 2 fields, saw 3\\nSkipping line 7498: expected 2 fields, saw 3\\nSkipping line 7504: expected 2 fields, saw 3\\nSkipping line 7506: expected 2 fields, saw 3\\nSkipping line 7507: expected 2 fields, saw 3\\nSkipping line 7508: expected 2 fields, saw 3\\nSkipping line 7509: expected 2 fields, saw 3\\nSkipping line 7510: expected 2 fields, saw 3\\nSkipping line 7511: expected 2 fields, saw 3\\nSkipping line 7518: expected 2 fields, saw 3\\nSkipping line 7519: expected 2 fields, saw 3\\nSkipping line 7520: expected 2 fields, saw 3\\nSkipping line 7522: expected 2 fields, saw 3\\nSkipping line 7524: expected 2 fields, saw 3\\nSkipping line 7525: expected 2 fields, saw 3\\nSkipping line 7526: expected 2 fields, saw 3\\nSkipping line 7527: expected 2 fields, saw 3\\nSkipping line 7528: expected 2 fields, saw 3\\nSkipping line 7530: expected 2 fields, saw 3\\nSkipping line 7531: expected 2 fields, saw 3\\nSkipping line 7533: expected 2 fields, saw 3\\nSkipping line 7534: expected 2 fields, saw 3\\nSkipping line 7543: expected 2 fields, saw 3\\nSkipping line 7545: expected 2 fields, saw 3\\nSkipping line 7548: expected 2 fields, saw 3\\nSkipping line 7551: expected 2 fields, saw 3\\nSkipping line 7552: expected 2 fields, saw 3\\nSkipping line 7553: expected 2 fields, saw 3\\nSkipping line 7554: expected 2 fields, saw 3\\nSkipping line 7555: expected 2 fields, saw 3\\nSkipping line 7556: expected 2 fields, saw 3\\nSkipping line 7557: expected 2 fields, saw 3\\nSkipping line 7558: expected 2 fields, saw 3\\nSkipping line 7560: expected 2 fields, saw 3\\nSkipping line 7563: expected 2 fields, saw 3\\nSkipping line 7565: expected 2 fields, saw 3\\nSkipping line 7566: expected 2 fields, saw 3\\nSkipping line 7567: expected 2 fields, saw 3\\nSkipping line 7568: expected 2 fields, saw 3\\nSkipping line 7569: expected 2 fields, saw 3\\nSkipping line 7570: expected 2 fields, saw 3\\nSkipping line 7573: expected 2 fields, saw 3\\nSkipping line 7574: expected 2 fields, saw 3\\nSkipping line 7575: expected 2 fields, saw 3\\nSkipping line 7577: expected 2 fields, saw 3\\nSkipping line 7578: expected 2 fields, saw 3\\nSkipping line 7583: expected 2 fields, saw 3\\nSkipping line 7585: expected 2 fields, saw 3\\nSkipping line 7587: expected 2 fields, saw 4\\nSkipping line 7588: expected 2 fields, saw 3\\nSkipping line 7589: expected 2 fields, saw 3\\nSkipping line 7590: expected 2 fields, saw 3\\nSkipping line 7596: expected 2 fields, saw 3\\nSkipping line 7597: expected 2 fields, saw 3\\nSkipping line 7600: expected 2 fields, saw 4\\nSkipping line 7601: expected 2 fields, saw 3\\nSkipping line 7605: expected 2 fields, saw 3\\nSkipping line 7606: expected 2 fields, saw 3\\nSkipping line 7610: expected 2 fields, saw 3\\nSkipping line 7611: expected 2 fields, saw 3\\nSkipping line 7612: expected 2 fields, saw 3\\nSkipping line 7613: expected 2 fields, saw 3\\nSkipping line 7614: expected 2 fields, saw 3\\nSkipping line 7615: expected 2 fields, saw 3\\nSkipping line 7616: expected 2 fields, saw 3\\nSkipping line 7618: expected 2 fields, saw 3\\nSkipping line 7621: expected 2 fields, saw 3\\nSkipping line 7622: expected 2 fields, saw 3\\nSkipping line 7625: expected 2 fields, saw 3\\nSkipping line 7626: expected 2 fields, saw 3\\nSkipping line 7627: expected 2 fields, saw 3\\nSkipping line 7628: expected 2 fields, saw 3\\nSkipping line 7629: expected 2 fields, saw 3\\nSkipping line 7630: expected 2 fields, saw 3\\nSkipping line 7632: expected 2 fields, saw 3\\nSkipping line 7633: expected 2 fields, saw 3\\nSkipping line 7634: expected 2 fields, saw 3\\nSkipping line 7635: expected 2 fields, saw 3\\nSkipping line 7636: expected 2 fields, saw 3\\nSkipping line 7637: expected 2 fields, saw 3\\nSkipping line 7638: expected 2 fields, saw 3\\nSkipping line 7639: expected 2 fields, saw 3\\nSkipping line 7641: expected 2 fields, saw 3\\nSkipping line 7642: expected 2 fields, saw 3\\nSkipping line 7644: expected 2 fields, saw 4\\nSkipping line 7645: expected 2 fields, saw 4\\nSkipping line 7647: expected 2 fields, saw 3\\nSkipping line 7648: expected 2 fields, saw 3\\nSkipping line 7650: expected 2 fields, saw 3\\nSkipping line 7651: expected 2 fields, saw 3\\nSkipping line 7655: expected 2 fields, saw 3\\nSkipping line 7659: expected 2 fields, saw 3\\nSkipping line 7660: expected 2 fields, saw 3\\nSkipping line 7664: expected 2 fields, saw 3\\nSkipping line 7673: expected 2 fields, saw 3\\nSkipping line 7674: expected 2 fields, saw 3\\nSkipping line 7676: expected 2 fields, saw 3\\nSkipping line 7677: expected 2 fields, saw 3\\nSkipping line 7678: expected 2 fields, saw 3\\nSkipping line 7679: expected 2 fields, saw 3\\nSkipping line 7681: expected 2 fields, saw 3\\nSkipping line 7682: expected 2 fields, saw 3\\nSkipping line 7683: expected 2 fields, saw 3\\nSkipping line 7684: expected 2 fields, saw 3\\nSkipping line 7685: expected 2 fields, saw 3\\nSkipping line 7686: expected 2 fields, saw 3\\nSkipping line 7689: expected 2 fields, saw 3\\nSkipping line 7690: expected 2 fields, saw 3\\nSkipping line 7692: expected 2 fields, saw 3\\nSkipping line 7693: expected 2 fields, saw 4\\nSkipping line 7694: expected 2 fields, saw 5\\nSkipping line 7695: expected 2 fields, saw 3\\nSkipping line 7696: expected 2 fields, saw 3\\nSkipping line 7697: expected 2 fields, saw 3\\nSkipping line 7698: expected 2 fields, saw 3\\nSkipping line 7699: expected 2 fields, saw 3\\nSkipping line 7700: expected 2 fields, saw 3\\nSkipping line 7701: expected 2 fields, saw 3\\nSkipping line 7703: expected 2 fields, saw 3\\nSkipping line 7704: expected 2 fields, saw 3\\nSkipping line 7705: expected 2 fields, saw 3\\nSkipping line 7706: expected 2 fields, saw 4\\nSkipping line 7707: expected 2 fields, saw 3\\nSkipping line 7708: expected 2 fields, saw 3\\nSkipping line 7710: expected 2 fields, saw 4\\nSkipping line 7711: expected 2 fields, saw 3\\nSkipping line 7712: expected 2 fields, saw 3\\nSkipping line 7713: expected 2 fields, saw 3\\nSkipping line 7714: expected 2 fields, saw 3\\nSkipping line 7715: expected 2 fields, saw 3\\nSkipping line 7716: expected 2 fields, saw 3\\nSkipping line 7717: expected 2 fields, saw 3\\nSkipping line 7718: expected 2 fields, saw 3\\nSkipping line 7719: expected 2 fields, saw 3\\nSkipping line 7720: expected 2 fields, saw 3\\nSkipping line 7721: expected 2 fields, saw 3\\nSkipping line 7722: expected 2 fields, saw 3\\nSkipping line 7723: expected 2 fields, saw 3\\nSkipping line 7725: expected 2 fields, saw 3\\nSkipping line 7726: expected 2 fields, saw 3\\nSkipping line 7727: expected 2 fields, saw 3\\nSkipping line 7728: expected 2 fields, saw 3\\nSkipping line 7729: expected 2 fields, saw 3\\nSkipping line 7730: expected 2 fields, saw 3\\nSkipping line 7731: expected 2 fields, saw 3\\nSkipping line 7732: expected 2 fields, saw 3\\nSkipping line 7734: expected 2 fields, saw 3\\nSkipping line 7736: expected 2 fields, saw 3\\nSkipping line 7737: expected 2 fields, saw 3\\nSkipping line 7740: expected 2 fields, saw 3\\nSkipping line 7741: expected 2 fields, saw 3\\nSkipping line 7742: expected 2 fields, saw 3\\nSkipping line 7743: expected 2 fields, saw 3\\nSkipping line 7744: expected 2 fields, saw 3\\nSkipping line 7746: expected 2 fields, saw 3\\nSkipping line 7748: expected 2 fields, saw 3\\nSkipping line 7749: expected 2 fields, saw 3\\nSkipping line 7751: expected 2 fields, saw 3\\nSkipping line 7752: expected 2 fields, saw 3\\nSkipping line 7758: expected 2 fields, saw 3\\nSkipping line 7759: expected 2 fields, saw 3\\nSkipping line 7760: expected 2 fields, saw 3\\nSkipping line 7761: expected 2 fields, saw 3\\nSkipping line 7762: expected 2 fields, saw 3\\nSkipping line 7764: expected 2 fields, saw 3\\nSkipping line 7765: expected 2 fields, saw 3\\nSkipping line 7766: expected 2 fields, saw 3\\nSkipping line 7767: expected 2 fields, saw 3\\nSkipping line 7768: expected 2 fields, saw 3\\nSkipping line 7769: expected 2 fields, saw 3\\nSkipping line 7770: expected 2 fields, saw 3\\nSkipping line 7771: expected 2 fields, saw 3\\nSkipping line 7773: expected 2 fields, saw 3\\nSkipping line 7774: expected 2 fields, saw 3\\nSkipping line 7777: expected 2 fields, saw 3\\nSkipping line 7778: expected 2 fields, saw 3\\nSkipping line 7779: expected 2 fields, saw 3\\nSkipping line 7780: expected 2 fields, saw 3\\nSkipping line 7781: expected 2 fields, saw 3\\nSkipping line 7782: expected 2 fields, saw 3\\nSkipping line 7783: expected 2 fields, saw 3\\nSkipping line 7784: expected 2 fields, saw 3\\nSkipping line 7785: expected 2 fields, saw 3\\nSkipping line 7786: expected 2 fields, saw 3\\nSkipping line 7789: expected 2 fields, saw 3\\nSkipping line 7790: expected 2 fields, saw 3\\nSkipping line 7793: expected 2 fields, saw 3\\nSkipping line 7797: expected 2 fields, saw 3\\nSkipping line 7798: expected 2 fields, saw 3\\nSkipping line 7799: expected 2 fields, saw 3\\nSkipping line 7800: expected 2 fields, saw 3\\nSkipping line 7801: expected 2 fields, saw 3\\nSkipping line 7803: expected 2 fields, saw 3\\nSkipping line 7808: expected 2 fields, saw 3\\nSkipping line 7809: expected 2 fields, saw 3\\nSkipping line 7810: expected 2 fields, saw 3\\nSkipping line 7811: expected 2 fields, saw 3\\nSkipping line 7813: expected 2 fields, saw 3\\nSkipping line 7814: expected 2 fields, saw 3\\nSkipping line 7822: expected 2 fields, saw 3\\nSkipping line 7824: expected 2 fields, saw 3\\nSkipping line 7825: expected 2 fields, saw 3\\nSkipping line 7826: expected 2 fields, saw 3\\nSkipping line 7827: expected 2 fields, saw 3\\nSkipping line 7830: expected 2 fields, saw 3\\nSkipping line 7831: expected 2 fields, saw 3\\nSkipping line 7832: expected 2 fields, saw 3\\nSkipping line 7833: expected 2 fields, saw 3\\nSkipping line 7834: expected 2 fields, saw 3\\nSkipping line 7835: expected 2 fields, saw 3\\nSkipping line 7836: expected 2 fields, saw 3\\nSkipping line 7837: expected 2 fields, saw 3\\nSkipping line 7838: expected 2 fields, saw 3\\nSkipping line 7839: expected 2 fields, saw 3\\nSkipping line 7840: expected 2 fields, saw 3\\nSkipping line 7843: expected 2 fields, saw 3\\nSkipping line 7844: expected 2 fields, saw 3\\nSkipping line 7846: expected 2 fields, saw 3\\nSkipping line 7847: expected 2 fields, saw 3\\nSkipping line 7848: expected 2 fields, saw 3\\nSkipping line 7849: expected 2 fields, saw 3\\nSkipping line 7850: expected 2 fields, saw 3\\nSkipping line 7851: expected 2 fields, saw 3\\nSkipping line 7853: expected 2 fields, saw 3\\nSkipping line 7855: expected 2 fields, saw 3\\nSkipping line 7856: expected 2 fields, saw 3\\nSkipping line 7865: expected 2 fields, saw 3\\nSkipping line 7877: expected 2 fields, saw 3\\nSkipping line 7878: expected 2 fields, saw 3\\nSkipping line 7881: expected 2 fields, saw 3\\nSkipping line 7882: expected 2 fields, saw 3\\nSkipping line 7883: expected 2 fields, saw 3\\nSkipping line 7885: expected 2 fields, saw 3\\nSkipping line 7886: expected 2 fields, saw 3\\nSkipping line 7887: expected 2 fields, saw 3\\nSkipping line 7888: expected 2 fields, saw 3\\nSkipping line 7889: expected 2 fields, saw 3\\nSkipping line 7890: expected 2 fields, saw 3\\nSkipping line 7891: expected 2 fields, saw 3\\nSkipping line 7897: expected 2 fields, saw 3\\nSkipping line 7898: expected 2 fields, saw 3\\nSkipping line 7904: expected 2 fields, saw 3\\nSkipping line 7908: expected 2 fields, saw 3\\nSkipping line 7910: expected 2 fields, saw 3\\nSkipping line 7911: expected 2 fields, saw 3\\nSkipping line 7912: expected 2 fields, saw 3\\nSkipping line 7916: expected 2 fields, saw 3\\nSkipping line 7921: expected 2 fields, saw 3\\nSkipping line 7923: expected 2 fields, saw 3\\nSkipping line 7924: expected 2 fields, saw 3\\nSkipping line 7926: expected 2 fields, saw 3\\nSkipping line 7927: expected 2 fields, saw 3\\nSkipping line 7930: expected 2 fields, saw 3\\nSkipping line 7931: expected 2 fields, saw 3\\nSkipping line 7932: expected 2 fields, saw 3\\nSkipping line 7934: expected 2 fields, saw 3\\nSkipping line 7935: expected 2 fields, saw 3\\nSkipping line 7936: expected 2 fields, saw 3\\nSkipping line 7940: expected 2 fields, saw 3\\nSkipping line 7941: expected 2 fields, saw 3\\nSkipping line 7942: expected 2 fields, saw 3\\nSkipping line 7944: expected 2 fields, saw 3\\nSkipping line 7945: expected 2 fields, saw 3\\nSkipping line 7946: expected 2 fields, saw 3\\nSkipping line 7949: expected 2 fields, saw 3\\nSkipping line 7951: expected 2 fields, saw 3\\nSkipping line 7953: expected 2 fields, saw 3\\nSkipping line 7954: expected 2 fields, saw 3\\nSkipping line 7955: expected 2 fields, saw 3\\nSkipping line 7957: expected 2 fields, saw 3\\nSkipping line 7958: expected 2 fields, saw 3\\nSkipping line 7960: expected 2 fields, saw 3\\nSkipping line 7961: expected 2 fields, saw 3\\nSkipping line 7963: expected 2 fields, saw 3\\nSkipping line 7966: expected 2 fields, saw 3\\nSkipping line 7967: expected 2 fields, saw 3\\nSkipping line 7969: expected 2 fields, saw 3\\nSkipping line 7970: expected 2 fields, saw 3\\nSkipping line 7972: expected 2 fields, saw 3\\nSkipping line 7973: expected 2 fields, saw 3\\nSkipping line 7974: expected 2 fields, saw 3\\nSkipping line 7975: expected 2 fields, saw 3\\nSkipping line 7976: expected 2 fields, saw 3\\nSkipping line 7977: expected 2 fields, saw 3\\nSkipping line 7978: expected 2 fields, saw 3\\nSkipping line 7979: expected 2 fields, saw 3\\nSkipping line 7980: expected 2 fields, saw 3\\nSkipping line 7981: expected 2 fields, saw 3\\nSkipping line 7982: expected 2 fields, saw 3\\nSkipping line 7983: expected 2 fields, saw 3\\nSkipping line 7984: expected 2 fields, saw 3\\nSkipping line 7985: expected 2 fields, saw 3\\nSkipping line 7986: expected 2 fields, saw 3\\nSkipping line 7987: expected 2 fields, saw 3\\nSkipping line 7988: expected 2 fields, saw 3\\nSkipping line 7989: expected 2 fields, saw 3\\nSkipping line 7991: expected 2 fields, saw 3\\nSkipping line 7992: expected 2 fields, saw 3\\nSkipping line 7993: expected 2 fields, saw 3\\nSkipping line 7995: expected 2 fields, saw 3\\nSkipping line 7996: expected 2 fields, saw 3\\nSkipping line 7998: expected 2 fields, saw 3\\nSkipping line 8000: expected 2 fields, saw 4\\nSkipping line 8001: expected 2 fields, saw 3\\nSkipping line 8002: expected 2 fields, saw 3\\nSkipping line 8003: expected 2 fields, saw 4\\nSkipping line 8004: expected 2 fields, saw 3\\nSkipping line 8005: expected 2 fields, saw 3\\nSkipping line 8006: expected 2 fields, saw 3\\nSkipping line 8007: expected 2 fields, saw 3\\nSkipping line 8008: expected 2 fields, saw 3\\nSkipping line 8009: expected 2 fields, saw 3\\nSkipping line 8010: expected 2 fields, saw 3\\nSkipping line 8011: expected 2 fields, saw 3\\nSkipping line 8012: expected 2 fields, saw 3\\nSkipping line 8013: expected 2 fields, saw 3\\nSkipping line 8014: expected 2 fields, saw 3\\nSkipping line 8015: expected 2 fields, saw 4\\nSkipping line 8016: expected 2 fields, saw 3\\nSkipping line 8017: expected 2 fields, saw 3\\nSkipping line 8018: expected 2 fields, saw 3\\nSkipping line 8019: expected 2 fields, saw 3\\nSkipping line 8020: expected 2 fields, saw 3\\nSkipping line 8021: expected 2 fields, saw 3\\nSkipping line 8022: expected 2 fields, saw 3\\nSkipping line 8023: expected 2 fields, saw 3\\nSkipping line 8025: expected 2 fields, saw 3\\nSkipping line 8027: expected 2 fields, saw 3\\nSkipping line 8029: expected 2 fields, saw 4\\nSkipping line 8031: expected 2 fields, saw 3\\nSkipping line 8032: expected 2 fields, saw 3\\nSkipping line 8033: expected 2 fields, saw 3\\nSkipping line 8034: expected 2 fields, saw 3\\nSkipping line 8035: expected 2 fields, saw 3\\nSkipping line 8036: expected 2 fields, saw 3\\nSkipping line 8038: expected 2 fields, saw 4\\nSkipping line 8039: expected 2 fields, saw 3\\nSkipping line 8040: expected 2 fields, saw 3\\nSkipping line 8042: expected 2 fields, saw 3\\nSkipping line 8043: expected 2 fields, saw 3\\nSkipping line 8044: expected 2 fields, saw 3\\nSkipping line 8045: expected 2 fields, saw 4\\nSkipping line 8046: expected 2 fields, saw 3\\nSkipping line 8048: expected 2 fields, saw 3\\nSkipping line 8050: expected 2 fields, saw 3\\nSkipping line 8051: expected 2 fields, saw 3\\nSkipping line 8053: expected 2 fields, saw 3\\nSkipping line 8055: expected 2 fields, saw 3\\nSkipping line 8056: expected 2 fields, saw 3\\nSkipping line 8057: expected 2 fields, saw 4\\nSkipping line 8058: expected 2 fields, saw 3\\nSkipping line 8059: expected 2 fields, saw 3\\nSkipping line 8060: expected 2 fields, saw 3\\nSkipping line 8061: expected 2 fields, saw 4\\nSkipping line 8063: expected 2 fields, saw 7\\nSkipping line 8064: expected 2 fields, saw 3\\nSkipping line 8065: expected 2 fields, saw 3\\nSkipping line 8066: expected 2 fields, saw 3\\nSkipping line 8067: expected 2 fields, saw 3\\nSkipping line 8068: expected 2 fields, saw 4\\nSkipping line 8070: expected 2 fields, saw 3\\nSkipping line 8071: expected 2 fields, saw 3\\nSkipping line 8072: expected 2 fields, saw 3\\nSkipping line 8074: expected 2 fields, saw 3\\nSkipping line 8075: expected 2 fields, saw 3\\nSkipping line 8077: expected 2 fields, saw 3\\nSkipping line 8078: expected 2 fields, saw 3\\nSkipping line 8079: expected 2 fields, saw 3\\nSkipping line 8080: expected 2 fields, saw 3\\nSkipping line 8081: expected 2 fields, saw 3\\nSkipping line 8082: expected 2 fields, saw 3\\nSkipping line 8083: expected 2 fields, saw 3\\nSkipping line 8084: expected 2 fields, saw 3\\nSkipping line 8085: expected 2 fields, saw 3\\nSkipping line 8086: expected 2 fields, saw 3\\nSkipping line 8087: expected 2 fields, saw 3\\nSkipping line 8088: expected 2 fields, saw 4\\nSkipping line 8089: expected 2 fields, saw 3\\nSkipping line 8090: expected 2 fields, saw 3\\nSkipping line 8091: expected 2 fields, saw 3\\nSkipping line 8092: expected 2 fields, saw 3\\nSkipping line 8093: expected 2 fields, saw 3\\nSkipping line 8095: expected 2 fields, saw 3\\nSkipping line 8096: expected 2 fields, saw 3\\nSkipping line 8097: expected 2 fields, saw 3\\nSkipping line 8098: expected 2 fields, saw 3\\nSkipping line 8099: expected 2 fields, saw 3\\nSkipping line 8100: expected 2 fields, saw 3\\nSkipping line 8101: expected 2 fields, saw 3\\nSkipping line 8102: expected 2 fields, saw 3\\nSkipping line 8103: expected 2 fields, saw 3\\nSkipping line 8104: expected 2 fields, saw 3\\nSkipping line 8105: expected 2 fields, saw 3\\nSkipping line 8106: expected 2 fields, saw 3\\nSkipping line 8107: expected 2 fields, saw 3\\nSkipping line 8108: expected 2 fields, saw 3\\nSkipping line 8110: expected 2 fields, saw 3\\nSkipping line 8111: expected 2 fields, saw 3\\nSkipping line 8114: expected 2 fields, saw 3\\nSkipping line 8115: expected 2 fields, saw 3\\nSkipping line 8118: expected 2 fields, saw 3\\nSkipping line 8119: expected 2 fields, saw 3\\nSkipping line 8120: expected 2 fields, saw 3\\nSkipping line 8121: expected 2 fields, saw 3\\nSkipping line 8122: expected 2 fields, saw 3\\nSkipping line 8123: expected 2 fields, saw 3\\nSkipping line 8124: expected 2 fields, saw 3\\nSkipping line 8125: expected 2 fields, saw 3\\nSkipping line 8126: expected 2 fields, saw 3\\nSkipping line 8128: expected 2 fields, saw 3\\nSkipping line 8129: expected 2 fields, saw 3\\nSkipping line 8130: expected 2 fields, saw 3\\nSkipping line 8132: expected 2 fields, saw 3\\nSkipping line 8133: expected 2 fields, saw 3\\nSkipping line 8134: expected 2 fields, saw 3\\nSkipping line 8135: expected 2 fields, saw 3\\nSkipping line 8138: expected 2 fields, saw 3\\nSkipping line 8139: expected 2 fields, saw 3\\nSkipping line 8140: expected 2 fields, saw 3\\nSkipping line 8141: expected 2 fields, saw 3\\nSkipping line 8143: expected 2 fields, saw 3\\nSkipping line 8144: expected 2 fields, saw 3\\nSkipping line 8146: expected 2 fields, saw 3\\nSkipping line 8148: expected 2 fields, saw 3\\nSkipping line 8149: expected 2 fields, saw 3\\nSkipping line 8150: expected 2 fields, saw 3\\nSkipping line 8152: expected 2 fields, saw 3\\nSkipping line 8153: expected 2 fields, saw 4\\nSkipping line 8154: expected 2 fields, saw 3\\nSkipping line 8155: expected 2 fields, saw 3\\nSkipping line 8156: expected 2 fields, saw 3\\nSkipping line 8158: expected 2 fields, saw 3\\nSkipping line 8160: expected 2 fields, saw 4\\nSkipping line 8161: expected 2 fields, saw 3\\nSkipping line 8162: expected 2 fields, saw 3\\nSkipping line 8163: expected 2 fields, saw 3\\nSkipping line 8164: expected 2 fields, saw 3\\nSkipping line 8165: expected 2 fields, saw 3\\nSkipping line 8166: expected 2 fields, saw 3\\nSkipping line 8167: expected 2 fields, saw 3\\nSkipping line 8168: expected 2 fields, saw 3\\nSkipping line 8169: expected 2 fields, saw 3\\nSkipping line 8170: expected 2 fields, saw 3\\nSkipping line 8171: expected 2 fields, saw 3\\nSkipping line 8172: expected 2 fields, saw 3\\nSkipping line 8173: expected 2 fields, saw 3\\nSkipping line 8174: expected 2 fields, saw 3\\nSkipping line 8175: expected 2 fields, saw 3\\nSkipping line 8176: expected 2 fields, saw 3\\nSkipping line 8177: expected 2 fields, saw 4\\nSkipping line 8200: expected 2 fields, saw 3\\nSkipping line 8203: expected 2 fields, saw 3\\nSkipping line 8205: expected 2 fields, saw 3\\nSkipping line 8209: expected 2 fields, saw 3\\nSkipping line 8210: expected 2 fields, saw 3\\nSkipping line 8211: expected 2 fields, saw 3\\nSkipping line 8212: expected 2 fields, saw 3\\nSkipping line 8215: expected 2 fields, saw 3\\nSkipping line 8216: expected 2 fields, saw 3\\nSkipping line 8218: expected 2 fields, saw 3\\nSkipping line 8221: expected 2 fields, saw 3\\nSkipping line 8222: expected 2 fields, saw 3\\nSkipping line 8223: expected 2 fields, saw 3\\nSkipping line 8224: expected 2 fields, saw 3\\nSkipping line 8228: expected 2 fields, saw 3\\nSkipping line 8229: expected 2 fields, saw 3\\nSkipping line 8230: expected 2 fields, saw 3\\nSkipping line 8231: expected 2 fields, saw 3\\nSkipping line 8232: expected 2 fields, saw 3\\nSkipping line 8233: expected 2 fields, saw 3\\nSkipping line 8234: expected 2 fields, saw 3\\nSkipping line 8235: expected 2 fields, saw 3\\nSkipping line 8247: expected 2 fields, saw 3\\nSkipping line 8248: expected 2 fields, saw 3\\nSkipping line 8249: expected 2 fields, saw 3\\nSkipping line 8250: expected 2 fields, saw 3\\nSkipping line 8251: expected 2 fields, saw 3\\nSkipping line 8252: expected 2 fields, saw 3\\nSkipping line 8253: expected 2 fields, saw 3\\nSkipping line 8254: expected 2 fields, saw 4\\nSkipping line 8255: expected 2 fields, saw 3\\nSkipping line 8256: expected 2 fields, saw 3\\nSkipping line 8257: expected 2 fields, saw 3\\nSkipping line 8260: expected 2 fields, saw 3\\nSkipping line 8264: expected 2 fields, saw 3\\nSkipping line 8267: expected 2 fields, saw 5\\nSkipping line 8268: expected 2 fields, saw 4\\nSkipping line 8269: expected 2 fields, saw 3\\nSkipping line 8270: expected 2 fields, saw 3\\nSkipping line 8275: expected 2 fields, saw 4\\nSkipping line 8276: expected 2 fields, saw 3\\nSkipping line 8277: expected 2 fields, saw 3\\nSkipping line 8278: expected 2 fields, saw 5\\nSkipping line 8279: expected 2 fields, saw 4\\nSkipping line 8280: expected 2 fields, saw 3\\nSkipping line 8283: expected 2 fields, saw 4\\nSkipping line 8284: expected 2 fields, saw 4\\nSkipping line 8286: expected 2 fields, saw 3\\nSkipping line 8287: expected 2 fields, saw 3\\nSkipping line 8288: expected 2 fields, saw 4\\nSkipping line 8289: expected 2 fields, saw 3\\nSkipping line 8290: expected 2 fields, saw 3\\nSkipping line 8291: expected 2 fields, saw 3\\nSkipping line 8292: expected 2 fields, saw 4\\nSkipping line 8293: expected 2 fields, saw 3\\nSkipping line 8294: expected 2 fields, saw 4\\nSkipping line 8295: expected 2 fields, saw 3\\nSkipping line 8296: expected 2 fields, saw 4\\nSkipping line 8297: expected 2 fields, saw 4\\nSkipping line 8298: expected 2 fields, saw 4\\nSkipping line 8299: expected 2 fields, saw 3\\nSkipping line 8300: expected 2 fields, saw 4\\nSkipping line 8301: expected 2 fields, saw 3\\nSkipping line 8302: expected 2 fields, saw 4\\nSkipping line 8303: expected 2 fields, saw 3\\nSkipping line 8304: expected 2 fields, saw 3\\nSkipping line 8305: expected 2 fields, saw 3\\nSkipping line 8306: expected 2 fields, saw 4\\nSkipping line 8307: expected 2 fields, saw 3\\nSkipping line 8308: expected 2 fields, saw 4\\nSkipping line 8309: expected 2 fields, saw 3\\nSkipping line 8310: expected 2 fields, saw 3\\nSkipping line 8311: expected 2 fields, saw 4\\nSkipping line 8324: expected 2 fields, saw 3\\nSkipping line 8325: expected 2 fields, saw 4\\nSkipping line 8326: expected 2 fields, saw 4\\nSkipping line 8327: expected 2 fields, saw 4\\nSkipping line 8328: expected 2 fields, saw 4\\nSkipping line 8329: expected 2 fields, saw 3\\nSkipping line 8330: expected 2 fields, saw 3\\nSkipping line 8331: expected 2 fields, saw 3\\nSkipping line 8332: expected 2 fields, saw 3\\nSkipping line 8333: expected 2 fields, saw 3\\nSkipping line 8334: expected 2 fields, saw 4\\nSkipping line 8335: expected 2 fields, saw 3\\nSkipping line 8336: expected 2 fields, saw 3\\nSkipping line 8337: expected 2 fields, saw 3\\nSkipping line 8338: expected 2 fields, saw 3\\nSkipping line 8339: expected 2 fields, saw 3\\nSkipping line 8340: expected 2 fields, saw 3\\nSkipping line 8341: expected 2 fields, saw 3\\nSkipping line 8342: expected 2 fields, saw 3\\nSkipping line 8343: expected 2 fields, saw 3\\nSkipping line 8345: expected 2 fields, saw 3\\nSkipping line 8346: expected 2 fields, saw 3\\nSkipping line 8347: expected 2 fields, saw 3\\nSkipping line 8351: expected 2 fields, saw 3\\nSkipping line 8352: expected 2 fields, saw 3\\nSkipping line 8353: expected 2 fields, saw 3\\nSkipping line 8354: expected 2 fields, saw 3\\nSkipping line 8357: expected 2 fields, saw 3\\nSkipping line 8358: expected 2 fields, saw 3\\nSkipping line 8359: expected 2 fields, saw 3\\nSkipping line 8360: expected 2 fields, saw 3\\nSkipping line 8361: expected 2 fields, saw 4\\nSkipping line 8362: expected 2 fields, saw 3\\nSkipping line 8363: expected 2 fields, saw 4\\nSkipping line 8364: expected 2 fields, saw 3\\nSkipping line 8365: expected 2 fields, saw 3\\nSkipping line 8366: expected 2 fields, saw 3\\nSkipping line 8367: expected 2 fields, saw 4\\nSkipping line 8368: expected 2 fields, saw 3\\nSkipping line 8369: expected 2 fields, saw 4\\nSkipping line 8370: expected 2 fields, saw 4\\nSkipping line 8371: expected 2 fields, saw 4\\nSkipping line 8372: expected 2 fields, saw 3\\nSkipping line 8373: expected 2 fields, saw 3\\nSkipping line 8374: expected 2 fields, saw 4\\nSkipping line 8375: expected 2 fields, saw 3\\nSkipping line 8376: expected 2 fields, saw 3\\nSkipping line 8377: expected 2 fields, saw 3\\nSkipping line 8378: expected 2 fields, saw 3\\nSkipping line 8380: expected 2 fields, saw 3\\nSkipping line 8381: expected 2 fields, saw 3\\nSkipping line 8382: expected 2 fields, saw 3\\nSkipping line 8383: expected 2 fields, saw 3\\nSkipping line 8384: expected 2 fields, saw 3\\nSkipping line 8385: expected 2 fields, saw 3\\nSkipping line 8386: expected 2 fields, saw 3\\nSkipping line 8388: expected 2 fields, saw 3\\nSkipping line 8389: expected 2 fields, saw 3\\nSkipping line 8390: expected 2 fields, saw 3\\nSkipping line 8391: expected 2 fields, saw 3\\nSkipping line 8392: expected 2 fields, saw 4\\nSkipping line 8393: expected 2 fields, saw 4\\nSkipping line 8394: expected 2 fields, saw 3\\nSkipping line 8395: expected 2 fields, saw 4\\nSkipping line 8396: expected 2 fields, saw 4\\nSkipping line 8397: expected 2 fields, saw 4\\nSkipping line 8398: expected 2 fields, saw 4\\nSkipping line 8399: expected 2 fields, saw 3\\nSkipping line 8400: expected 2 fields, saw 4\\nSkipping line 8401: expected 2 fields, saw 4\\nSkipping line 8402: expected 2 fields, saw 3\\nSkipping line 8403: expected 2 fields, saw 4\\nSkipping line 8404: expected 2 fields, saw 3\\nSkipping line 8405: expected 2 fields, saw 3\\nSkipping line 8406: expected 2 fields, saw 3\\nSkipping line 8407: expected 2 fields, saw 3\\nSkipping line 8408: expected 2 fields, saw 3\\nSkipping line 8409: expected 2 fields, saw 3\\nSkipping line 8410: expected 2 fields, saw 3\\nSkipping line 8411: expected 2 fields, saw 4\\nSkipping line 8412: expected 2 fields, saw 3\\nSkipping line 8413: expected 2 fields, saw 3\\nSkipping line 8414: expected 2 fields, saw 3\\nSkipping line 8417: expected 2 fields, saw 3\\nSkipping line 8418: expected 2 fields, saw 4\\nSkipping line 8419: expected 2 fields, saw 3\\nSkipping line 8420: expected 2 fields, saw 4\\nSkipping line 8421: expected 2 fields, saw 3\\nSkipping line 8422: expected 2 fields, saw 4\\nSkipping line 8423: expected 2 fields, saw 4\\nSkipping line 8424: expected 2 fields, saw 4\\nSkipping line 8425: expected 2 fields, saw 4\\nSkipping line 8426: expected 2 fields, saw 4\\nSkipping line 8427: expected 2 fields, saw 4\\nSkipping line 8428: expected 2 fields, saw 4\\nSkipping line 8429: expected 2 fields, saw 4\\nSkipping line 8430: expected 2 fields, saw 4\\nSkipping line 8431: expected 2 fields, saw 4\\nSkipping line 8435: expected 2 fields, saw 3\\nSkipping line 8436: expected 2 fields, saw 3\\nSkipping line 8440: expected 2 fields, saw 3\\nSkipping line 8441: expected 2 fields, saw 3\\nSkipping line 8443: expected 2 fields, saw 4\\nSkipping line 8444: expected 2 fields, saw 4\\nSkipping line 8445: expected 2 fields, saw 3\\nSkipping line 8446: expected 2 fields, saw 3\\nSkipping line 8447: expected 2 fields, saw 3\\nSkipping line 8448: expected 2 fields, saw 3\\nSkipping line 8449: expected 2 fields, saw 4\\nSkipping line 8450: expected 2 fields, saw 3\\nSkipping line 8452: expected 2 fields, saw 4\\nSkipping line 8454: expected 2 fields, saw 4\\nSkipping line 8455: expected 2 fields, saw 3\\nSkipping line 8456: expected 2 fields, saw 3\\nSkipping line 8457: expected 2 fields, saw 4\\nSkipping line 8458: expected 2 fields, saw 4\\nSkipping line 8459: expected 2 fields, saw 3\\nSkipping line 8460: expected 2 fields, saw 3\\nSkipping line 8461: expected 2 fields, saw 4\\nSkipping line 8462: expected 2 fields, saw 4\\nSkipping line 8463: expected 2 fields, saw 4\\nSkipping line 8464: expected 2 fields, saw 4\\nSkipping line 8465: expected 2 fields, saw 4\\nSkipping line 8466: expected 2 fields, saw 4\\nSkipping line 8467: expected 2 fields, saw 3\\nSkipping line 8468: expected 2 fields, saw 3\\nSkipping line 8469: expected 2 fields, saw 3\\nSkipping line 8471: expected 2 fields, saw 3\\nSkipping line 8472: expected 2 fields, saw 3\\nSkipping line 8473: expected 2 fields, saw 3\\nSkipping line 8474: expected 2 fields, saw 3\\nSkipping line 8475: expected 2 fields, saw 3\\nSkipping line 8476: expected 2 fields, saw 3\\nSkipping line 8477: expected 2 fields, saw 3\\nSkipping line 8478: expected 2 fields, saw 4\\nSkipping line 8479: expected 2 fields, saw 3\\nSkipping line 8480: expected 2 fields, saw 4\\nSkipping line 8481: expected 2 fields, saw 4\\nSkipping line 8482: expected 2 fields, saw 4\\nSkipping line 8483: expected 2 fields, saw 4\\nSkipping line 8484: expected 2 fields, saw 4\\nSkipping line 8485: expected 2 fields, saw 3\\nSkipping line 8486: expected 2 fields, saw 4\\nSkipping line 8487: expected 2 fields, saw 4\\nSkipping line 8488: expected 2 fields, saw 4\\nSkipping line 8489: expected 2 fields, saw 4\\nSkipping line 8491: expected 2 fields, saw 4\\nSkipping line 8492: expected 2 fields, saw 4\\nSkipping line 8493: expected 2 fields, saw 4\\nSkipping line 8494: expected 2 fields, saw 4\\nSkipping line 8495: expected 2 fields, saw 4\\nSkipping line 8496: expected 2 fields, saw 3\\nSkipping line 8497: expected 2 fields, saw 3\\nSkipping line 8504: expected 2 fields, saw 3\\nSkipping line 8505: expected 2 fields, saw 3\\nSkipping line 8506: expected 2 fields, saw 3\\nSkipping line 8507: expected 2 fields, saw 4\\nSkipping line 8508: expected 2 fields, saw 4\\nSkipping line 8509: expected 2 fields, saw 3\\nSkipping line 8510: expected 2 fields, saw 4\\nSkipping line 8511: expected 2 fields, saw 4\\nSkipping line 8512: expected 2 fields, saw 3\\nSkipping line 8513: expected 2 fields, saw 4\\nSkipping line 8514: expected 2 fields, saw 4\\nSkipping line 8515: expected 2 fields, saw 4\\nSkipping line 8516: expected 2 fields, saw 4\\nSkipping line 8517: expected 2 fields, saw 4\\nSkipping line 8518: expected 2 fields, saw 4\\nSkipping line 8519: expected 2 fields, saw 3\\nSkipping line 8520: expected 2 fields, saw 4\\nSkipping line 8521: expected 2 fields, saw 4\\nSkipping line 8522: expected 2 fields, saw 3\\nSkipping line 8523: expected 2 fields, saw 4\\nSkipping line 8524: expected 2 fields, saw 3\\nSkipping line 8525: expected 2 fields, saw 4\\nSkipping line 8526: expected 2 fields, saw 3\\nSkipping line 8527: expected 2 fields, saw 3\\nSkipping line 8528: expected 2 fields, saw 3\\nSkipping line 8529: expected 2 fields, saw 4\\nSkipping line 8530: expected 2 fields, saw 4\\nSkipping line 8531: expected 2 fields, saw 4\\nSkipping line 8532: expected 2 fields, saw 3\\nSkipping line 8533: expected 2 fields, saw 3\\nSkipping line 8534: expected 2 fields, saw 3\\nSkipping line 8535: expected 2 fields, saw 4\\nSkipping line 8536: expected 2 fields, saw 4\\nSkipping line 8538: expected 2 fields, saw 3\\nSkipping line 8539: expected 2 fields, saw 4\\nSkipping line 8540: expected 2 fields, saw 3\\nSkipping line 8541: expected 2 fields, saw 4\\nSkipping line 8542: expected 2 fields, saw 4\\nSkipping line 8543: expected 2 fields, saw 4\\nSkipping line 8544: expected 2 fields, saw 4\\nSkipping line 8545: expected 2 fields, saw 3\\nSkipping line 8546: expected 2 fields, saw 4\\nSkipping line 8547: expected 2 fields, saw 3\\nSkipping line 8548: expected 2 fields, saw 4\\nSkipping line 8549: expected 2 fields, saw 4\\nSkipping line 8550: expected 2 fields, saw 4\\nSkipping line 8551: expected 2 fields, saw 3\\nSkipping line 8552: expected 2 fields, saw 4\\nSkipping line 8553: expected 2 fields, saw 4\\nSkipping line 8554: expected 2 fields, saw 4\\nSkipping line 8555: expected 2 fields, saw 3\\nSkipping line 8558: expected 2 fields, saw 3\\nSkipping line 8559: expected 2 fields, saw 3\\nSkipping line 8560: expected 2 fields, saw 3\\nSkipping line 8562: expected 2 fields, saw 3\\nSkipping line 8563: expected 2 fields, saw 4\\nSkipping line 8564: expected 2 fields, saw 4\\nSkipping line 8569: expected 2 fields, saw 4\\nSkipping line 8570: expected 2 fields, saw 3\\nSkipping line 8571: expected 2 fields, saw 3\\nSkipping line 8572: expected 2 fields, saw 5\\nSkipping line 8573: expected 2 fields, saw 4\\nSkipping line 8574: expected 2 fields, saw 3\\nSkipping line 8575: expected 2 fields, saw 3\\nSkipping line 8576: expected 2 fields, saw 3\\nSkipping line 8577: expected 2 fields, saw 3\\nSkipping line 8578: expected 2 fields, saw 3\\nSkipping line 8579: expected 2 fields, saw 3\\nSkipping line 8580: expected 2 fields, saw 3\\nSkipping line 8582: expected 2 fields, saw 3\\nSkipping line 8583: expected 2 fields, saw 3\\nSkipping line 8584: expected 2 fields, saw 4\\nSkipping line 8585: expected 2 fields, saw 4\\nSkipping line 8586: expected 2 fields, saw 3\\nSkipping line 8587: expected 2 fields, saw 3\\nSkipping line 8588: expected 2 fields, saw 4\\nSkipping line 8589: expected 2 fields, saw 4\\nSkipping line 8590: expected 2 fields, saw 4\\nSkipping line 8591: expected 2 fields, saw 4\\nSkipping line 8592: expected 2 fields, saw 4\\nSkipping line 8605: expected 2 fields, saw 3\\nSkipping line 8606: expected 2 fields, saw 3\\nSkipping line 8621: expected 2 fields, saw 3\\nSkipping line 8623: expected 2 fields, saw 3\\nSkipping line 8624: expected 2 fields, saw 3\\nSkipping line 8627: expected 2 fields, saw 3\\nSkipping line 8628: expected 2 fields, saw 4\\nSkipping line 8629: expected 2 fields, saw 4\\nSkipping line 8630: expected 2 fields, saw 4\\nSkipping line 8631: expected 2 fields, saw 4\\nSkipping line 8632: expected 2 fields, saw 4\\nSkipping line 8633: expected 2 fields, saw 4\\nSkipping line 8634: expected 2 fields, saw 4\\nSkipping line 8635: expected 2 fields, saw 3\\nSkipping line 8636: expected 2 fields, saw 4\\nSkipping line 8637: expected 2 fields, saw 3\\nSkipping line 8638: expected 2 fields, saw 4\\nSkipping line 8639: expected 2 fields, saw 4\\nSkipping line 8640: expected 2 fields, saw 3\\nSkipping line 8641: expected 2 fields, saw 3\\nSkipping line 8642: expected 2 fields, saw 3\\nSkipping line 8643: expected 2 fields, saw 3\\nSkipping line 8644: expected 2 fields, saw 3\\nSkipping line 8645: expected 2 fields, saw 3\\nSkipping line 8646: expected 2 fields, saw 4\\nSkipping line 8647: expected 2 fields, saw 4\\nSkipping line 8648: expected 2 fields, saw 3\\nSkipping line 8649: expected 2 fields, saw 3\\nSkipping line 8660: expected 2 fields, saw 3\\nSkipping line 8661: expected 2 fields, saw 3\\nSkipping line 8679: expected 2 fields, saw 3\\nSkipping line 8680: expected 2 fields, saw 3\\nSkipping line 8681: expected 2 fields, saw 3\\nSkipping line 8682: expected 2 fields, saw 3\\nSkipping line 8747: expected 2 fields, saw 3\\nSkipping line 8748: expected 2 fields, saw 3\\nSkipping line 8749: expected 2 fields, saw 3\\nSkipping line 8750: expected 2 fields, saw 3\\nSkipping line 8751: expected 2 fields, saw 3\\nSkipping line 8752: expected 2 fields, saw 3\\nSkipping line 8753: expected 2 fields, saw 4\\nSkipping line 8754: expected 2 fields, saw 3\\nSkipping line 8755: expected 2 fields, saw 4\\nSkipping line 8756: expected 2 fields, saw 4\\nSkipping line 8757: expected 2 fields, saw 3\\nSkipping line 8758: expected 2 fields, saw 3\\nSkipping line 8759: expected 2 fields, saw 4\\nSkipping line 8760: expected 2 fields, saw 3\\nSkipping line 8761: expected 2 fields, saw 3\\nSkipping line 8762: expected 2 fields, saw 3\\nSkipping line 8763: expected 2 fields, saw 4\\nSkipping line 8764: expected 2 fields, saw 4\\nSkipping line 8765: expected 2 fields, saw 4\\nSkipping line 8766: expected 2 fields, saw 4\\nSkipping line 8767: expected 2 fields, saw 4\\nSkipping line 8768: expected 2 fields, saw 4\\nSkipping line 8769: expected 2 fields, saw 4\\nSkipping line 8770: expected 2 fields, saw 4\\nSkipping line 8771: expected 2 fields, saw 4\\nSkipping line 8772: expected 2 fields, saw 3\\nSkipping line 8773: expected 2 fields, saw 4\\nSkipping line 8774: expected 2 fields, saw 4\\nSkipping line 8777: expected 2 fields, saw 3\\nSkipping line 8778: expected 2 fields, saw 3\\nSkipping line 8779: expected 2 fields, saw 3\\nSkipping line 8783: expected 2 fields, saw 3\\nSkipping line 8784: expected 2 fields, saw 3\\nSkipping line 8785: expected 2 fields, saw 3\\nSkipping line 8786: expected 2 fields, saw 3\\nSkipping line 8787: expected 2 fields, saw 3\\nSkipping line 8788: expected 2 fields, saw 4\\nSkipping line 8789: expected 2 fields, saw 4\\nSkipping line 8790: expected 2 fields, saw 3\\nSkipping line 8791: expected 2 fields, saw 4\\nSkipping line 8792: expected 2 fields, saw 4\\nSkipping line 8793: expected 2 fields, saw 4\\nSkipping line 8794: expected 2 fields, saw 3\\nSkipping line 8795: expected 2 fields, saw 4\\nSkipping line 8796: expected 2 fields, saw 3\\nSkipping line 8797: expected 2 fields, saw 4\\nSkipping line 8798: expected 2 fields, saw 3\\nSkipping line 8799: expected 2 fields, saw 4\\nSkipping line 8800: expected 2 fields, saw 4\\nSkipping line 8801: expected 2 fields, saw 4\\nSkipping line 8802: expected 2 fields, saw 4\\nSkipping line 8803: expected 2 fields, saw 4\\nSkipping line 8804: expected 2 fields, saw 3\\nSkipping line 8805: expected 2 fields, saw 4\\nSkipping line 8806: expected 2 fields, saw 4\\nSkipping line 8819: expected 2 fields, saw 3\\nSkipping line 8823: expected 2 fields, saw 3\\nSkipping line 8824: expected 2 fields, saw 3\\nSkipping line 8830: expected 2 fields, saw 3\\nSkipping line 8831: expected 2 fields, saw 3\\nSkipping line 8832: expected 2 fields, saw 3\\nSkipping line 8833: expected 2 fields, saw 3\\nSkipping line 8834: expected 2 fields, saw 3\\nSkipping line 8835: expected 2 fields, saw 3\\nSkipping line 8840: expected 2 fields, saw 3\\nSkipping line 8841: expected 2 fields, saw 4\\nSkipping line 8842: expected 2 fields, saw 4\\nSkipping line 8843: expected 2 fields, saw 4\\nSkipping line 8844: expected 2 fields, saw 4\\nSkipping line 8845: expected 2 fields, saw 4\\nSkipping line 8846: expected 2 fields, saw 4\\nSkipping line 8847: expected 2 fields, saw 4\\nSkipping line 8848: expected 2 fields, saw 4\\nSkipping line 8849: expected 2 fields, saw 4\\nSkipping line 8850: expected 2 fields, saw 4\\nSkipping line 8851: expected 2 fields, saw 3\\nSkipping line 8852: expected 2 fields, saw 4\\nSkipping line 8853: expected 2 fields, saw 4\\nSkipping line 8854: expected 2 fields, saw 4\\nSkipping line 8855: expected 2 fields, saw 4\\nSkipping line 8856: expected 2 fields, saw 4\\nSkipping line 8857: expected 2 fields, saw 4\\nSkipping line 8858: expected 2 fields, saw 4\\nSkipping line 8859: expected 2 fields, saw 4\\nSkipping line 8860: expected 2 fields, saw 4\\nSkipping line 8861: expected 2 fields, saw 3\\nSkipping line 8862: expected 2 fields, saw 4\\nSkipping line 8863: expected 2 fields, saw 4\\nSkipping line 8864: expected 2 fields, saw 4\\nSkipping line 8865: expected 2 fields, saw 4\\nSkipping line 8867: expected 2 fields, saw 3\\nSkipping line 8868: expected 2 fields, saw 3\\nSkipping line 8871: expected 2 fields, saw 4\\nSkipping line 8872: expected 2 fields, saw 4\\nSkipping line 8873: expected 2 fields, saw 3\\nSkipping line 8874: expected 2 fields, saw 3\\nSkipping line 8875: expected 2 fields, saw 4\\nSkipping line 8876: expected 2 fields, saw 4\\nSkipping line 8877: expected 2 fields, saw 4\\nSkipping line 8878: expected 2 fields, saw 4\\nSkipping line 8879: expected 2 fields, saw 4\\nSkipping line 8880: expected 2 fields, saw 4\\nSkipping line 8881: expected 2 fields, saw 4\\nSkipping line 8882: expected 2 fields, saw 4\\nSkipping line 8883: expected 2 fields, saw 3\\nSkipping line 8884: expected 2 fields, saw 4\\nSkipping line 8885: expected 2 fields, saw 4\\nSkipping line 8886: expected 2 fields, saw 4\\nSkipping line 8887: expected 2 fields, saw 4\\nSkipping line 8888: expected 2 fields, saw 4\\nSkipping line 8889: expected 2 fields, saw 4\\nSkipping line 8891: expected 2 fields, saw 3\\nSkipping line 8894: expected 2 fields, saw 4\\nSkipping line 8895: expected 2 fields, saw 4\\nSkipping line 8896: expected 2 fields, saw 4\\nSkipping line 8897: expected 2 fields, saw 4\\nSkipping line 8898: expected 2 fields, saw 4\\nSkipping line 8899: expected 2 fields, saw 4\\nSkipping line 8900: expected 2 fields, saw 4\\nSkipping line 8901: expected 2 fields, saw 4\\nSkipping line 8902: expected 2 fields, saw 4\\nSkipping line 8903: expected 2 fields, saw 4\\nSkipping line 8904: expected 2 fields, saw 4\\nSkipping line 8905: expected 2 fields, saw 4\\nSkipping line 8906: expected 2 fields, saw 3\\nSkipping line 8907: expected 2 fields, saw 4\\nSkipping line 8908: expected 2 fields, saw 3\\nSkipping line 8909: expected 2 fields, saw 4\\nSkipping line 8910: expected 2 fields, saw 4\\nSkipping line 8911: expected 2 fields, saw 4\\nSkipping line 8912: expected 2 fields, saw 4\\nSkipping line 8913: expected 2 fields, saw 4\\nSkipping line 8914: expected 2 fields, saw 4\\nSkipping line 8916: expected 2 fields, saw 3\\nSkipping line 8917: expected 2 fields, saw 4\\nSkipping line 8918: expected 2 fields, saw 4\\nSkipping line 8919: expected 2 fields, saw 4\\nSkipping line 8920: expected 2 fields, saw 4\\nSkipping line 8922: expected 2 fields, saw 3\\nSkipping line 8923: expected 2 fields, saw 3\\nSkipping line 8925: expected 2 fields, saw 3\\nSkipping line 8928: expected 2 fields, saw 3\\nSkipping line 8934: expected 2 fields, saw 3\\nSkipping line 8937: expected 2 fields, saw 3\\nSkipping line 8938: expected 2 fields, saw 3\\nSkipping line 8944: expected 2 fields, saw 3\\nSkipping line 8949: expected 2 fields, saw 3\\nSkipping line 8951: expected 2 fields, saw 3\\nSkipping line 8952: expected 2 fields, saw 3\\nSkipping line 8955: expected 2 fields, saw 3\\nSkipping line 8956: expected 2 fields, saw 3\\nSkipping line 8964: expected 2 fields, saw 3\\nSkipping line 8967: expected 2 fields, saw 3\\nSkipping line 8969: expected 2 fields, saw 3\\nSkipping line 8970: expected 2 fields, saw 3\\nSkipping line 8971: expected 2 fields, saw 3\\nSkipping line 8973: expected 2 fields, saw 3\\n'\n    b'Skipping line 388: expected 1 fields, saw 2\\nSkipping line 800: expected 1 fields, saw 2\\nSkipping line 889: expected 1 fields, saw 2\\nSkipping line 5084: expected 1 fields, saw 2\\nSkipping line 5281: expected 1 fields, saw 3\\nSkipping line 5354: expected 1 fields, saw 2\\nSkipping line 6223: expected 1 fields, saw 2\\nSkipping line 6648: expected 1 fields, saw 2\\nSkipping line 6907: expected 1 fields, saw 2\\nSkipping line 7282: expected 1 fields, saw 2\\nSkipping line 7766: expected 1 fields, saw 2\\nSkipping line 8098: expected 1 fields, saw 2\\n'\n    b'Skipping line 425: expected 1 fields, saw 2\\nSkipping line 504: expected 1 fields, saw 2\\nSkipping line 1267: expected 1 fields, saw 5\\nSkipping line 3189: expected 1 fields, saw 2\\nSkipping line 3549: expected 1 fields, saw 2\\nSkipping line 3962: expected 1 fields, saw 2\\nSkipping line 5749: expected 1 fields, saw 2\\nSkipping line 5750: expected 1 fields, saw 2\\nSkipping line 5751: expected 1 fields, saw 2\\nSkipping line 5766: expected 1 fields, saw 2\\nSkipping line 5767: expected 1 fields, saw 2\\nSkipping line 5768: expected 1 fields, saw 2\\nSkipping line 5769: expected 1 fields, saw 2\\nSkipping line 5770: expected 1 fields, saw 2\\nSkipping line 5771: expected 1 fields, saw 2\\nSkipping line 5772: expected 1 fields, saw 2\\nSkipping line 5773: expected 1 fields, saw 2\\nSkipping line 5774: expected 1 fields, saw 2\\nSkipping line 5775: expected 1 fields, saw 2\\nSkipping line 5776: expected 1 fields, saw 2\\nSkipping line 5777: expected 1 fields, saw 2\\nSkipping line 5778: expected 1 fields, saw 2\\nSkipping line 5779: expected 1 fields, saw 2\\nSkipping line 6503: expected 1 fields, saw 2\\nSkipping line 8646: expected 1 fields, saw 2\\nSkipping line 11979: expected 1 fields, saw 2\\nSkipping line 20166: expected 1 fields, saw 2\\nSkipping line 20596: expected 1 fields, saw 2\\nSkipping line 20821: expected 1 fields, saw 2\\nSkipping line 24989: expected 1 fields, saw 2\\nSkipping line 26574: expected 1 fields, saw 2\\nSkipping line 28859: expected 1 fields, saw 2\\nSkipping line 30086: expected 1 fields, saw 2\\nSkipping line 31936: expected 1 fields, saw 2\\nSkipping line 33389: expected 1 fields, saw 2\\nSkipping line 33741: expected 1 fields, saw 2\\n'\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>label</th>\n      <th>NombreArchivo</th>\n      <th>clase</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>juan lopez benitez</td>\n      <td>Ficheros_Detenidos_Desaparecidos_Morales_Lopez...</td>\n      <td>Enjuiciados</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>(a) donato morales</td>\n      <td>Ficheros_Detenidos_Desaparecidos_Morales_Lopez...</td>\n      <td>Enjuiciados</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>sam lopez</td>\n      <td>Ficheros_Detenidos_Desaparecidos_Morales_Lopez...</td>\n      <td>Enjuiciados</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>juan de la rosa</td>\n      <td>Ficheros_Detenidos_Desaparecidos_Morales_Lopez...</td>\n      <td>Servidor P\u00fablico</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>federico sosa</td>\n      <td>Ficheros_Detenidos_Desaparecidos_Morales_Lopez...</td>\n      <td>Servidor P\u00fablico</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>899</th>\n      <td>joaquin amaro</td>\n      <td>Ficheros_Union_Campesina_Independiente,_fichas...</td>\n      <td>Servidor P\u00fablico</td>\n    </tr>\n    <tr>\n      <th>900</th>\n      <td>jose ruiz nunez</td>\n      <td>Ficheros_Union_Campesina_Independiente,_fichas...</td>\n      <td>Servidor P\u00fablico</td>\n    </tr>\n    <tr>\n      <th>901</th>\n      <td>sierra norte de puebla</td>\n      <td>Ficheros_Union_Campesina_Independiente,_fichas...</td>\n      <td>Lugar</td>\n    </tr>\n    <tr>\n      <th>902</th>\n      <td>san juan de dios</td>\n      <td>Ficheros_Union_Campesina_Independiente,_fichas...</td>\n      <td>Lugar</td>\n    </tr>\n    <tr>\n      <th>903</th>\n      <td>08/27/2021</td>\n      <td>Ficheros_Union_Campesina_Independiente,_fichas...</td>\n      <td>Fechas</td>\n    </tr>\n  </tbody>\n</table>\n<p>904 rows \u00d7 3 columns</p>\n</div>\n\n\n\n# Buscando una entidad en todas las fichas\n\nEn las siguientes celdas se presenta un buscador de entidades, como par\u00e1metros de **entrada** se reciben el **nombre de la entidad a buscar**, el **dataframe de trancripciones** donde se realizar\u00e1 la b\u00fasqueda y un par\u00e1metro de **threshold** que permite regular qu\u00e9 tan extricta se requiere la consulta, threshold < 60 es una b\u00fasqueda laxa con mayor probabilidad de falsos positivos y threshold > 60 significa una b\u00fasqueda m\u00e1s r\u00edgida en la que se puede perder un poco de informaci\u00f3n.\n\nComo **salida** devuelve un dataframe con todas las fichas en las que encuentra coincidencias y un word cloud de las palabras m\u00e1s frecuentes en las transcripciones en que se encuentra la entidad.\n\n\n```python\nname = \"Acapulco\"\nfuzzy_search.find_matchs_word_cloud(name,df_transcripciones,threshold=50)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "0f3d45135df8f835b95f6cd8abb8ed8f22b8e540", "size": 539645, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "implementacion_preprocesamiento_extraccion.ipynb", "max_stars_repo_name": "Hackaton-JusticIA-2021/gato-encerrado-Hackathon-RIIAA-2021", "max_stars_repo_head_hexsha": "3d41482a32d22a79fa9752b6d6fc3752a2b0a8f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-23T00:54:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-23T00:54:44.000Z", "max_issues_repo_path": "implementacion_preprocesamiento_extraccion.ipynb", "max_issues_repo_name": "andrea-liliana/Gato-encerrado-Hackathon-RIIAA-2021", "max_issues_repo_head_hexsha": "3d41482a32d22a79fa9752b6d6fc3752a2b0a8f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "implementacion_preprocesamiento_extraccion.ipynb", "max_forks_repo_name": "andrea-liliana/Gato-encerrado-Hackathon-RIIAA-2021", "max_forks_repo_head_hexsha": "3d41482a32d22a79fa9752b6d6fc3752a2b0a8f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-20T15:15:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-23T00:54:49.000Z", "avg_line_length": 476.7181978799, "max_line_length": 263758, "alphanum_fraction": 0.8403209517, "converted": true, "num_tokens": 81514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11920291889306492, "lm_q2_score": 0.05108273876282332, "lm_q1q2_score": 0.006089211565580452}}
{"text": "```python\n!cd content/CMU/*\n```\n\n    /bin/bash: line 0: cd: content/CMU/*: No such file or directory\n\n\n\n```python\n!git clone https://github.com/resemble-ai/Resemblyzer.git\n```\n\n    Cloning into 'Resemblyzer'...\n    remote: Enumerating objects: 602, done.\u001b[K\n    remote: Total 602 (delta 0), reused 0 (delta 0), pack-reused 602\u001b[K\n    Receiving objects: 100% (602/602), 101.46 MiB | 36.15 MiB/s, done.\n    Resolving deltas: 100% (107/107), done.\n\n\n\n```python\n%cd /content/Resemblyzer/\n```\n\n    /content/Resemblyzer\n\n\n\n```python\n!pip install -r  /content/Resemblyzer/requirements_demos.txt\n```\n\n    Requirement already satisfied: librosa>=0.6.1 in /usr/local/lib/python3.7/dist-packages (from -r /content/Resemblyzer/requirements_demos.txt (line 1)) (0.8.1)\n    Requirement already satisfied: numpy>=1.10.1 in /usr/local/lib/python3.7/dist-packages (from -r /content/Resemblyzer/requirements_demos.txt (line 2)) (1.19.5)\n    Collecting webrtcvad>=2.0.10\n      Downloading webrtcvad-2.0.10.tar.gz (66 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 66 kB 2.4 MB/s \n    \u001b[?25hRequirement already satisfied: torch>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from -r /content/Resemblyzer/requirements_demos.txt (line 4)) (1.10.0+cu111)\n    Requirement already satisfied: scipy>=1.2.1 in /usr/local/lib/python3.7/dist-packages (from -r /content/Resemblyzer/requirements_demos.txt (line 5)) (1.4.1)\n    Collecting typing\n      Downloading typing-3.7.4.3.tar.gz (78 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 78 kB 5.4 MB/s \n    \u001b[?25hRequirement already satisfied: matplotlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from -r /content/Resemblyzer/requirements_demos.txt (line 7)) (3.2.2)\n    Collecting sounddevice\n      Downloading sounddevice-0.4.4-py3-none-any.whl (31 kB)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from -r /content/Resemblyzer/requirements_demos.txt (line 9)) (4.62.3)\n    Collecting umap-learn\n      Downloading umap-learn-0.5.2.tar.gz (86 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 86 kB 4.5 MB/s \n    \u001b[?25hRequirement already satisfied: joblib>=0.14 in /usr/local/lib/python3.7/dist-packages (from librosa>=0.6.1->-r /content/Resemblyzer/requirements_demos.txt (line 1)) (1.1.0)\n    Requirement already satisfied: scikit-learn!=0.19.0,>=0.14.0 in /usr/local/lib/python3.7/dist-packages (from librosa>=0.6.1->-r /content/Resemblyzer/requirements_demos.txt (line 1)) (1.0.1)\n    Requirement already satisfied: decorator>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from librosa>=0.6.1->-r /content/Resemblyzer/requirements_demos.txt (line 1)) (4.4.2)\n    Requirement already satisfied: audioread>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from librosa>=0.6.1->-r /content/Resemblyzer/requirements_demos.txt (line 1)) (2.1.9)\n    Requirement already satisfied: resampy>=0.2.2 in /usr/local/lib/python3.7/dist-packages (from librosa>=0.6.1->-r /content/Resemblyzer/requirements_demos.txt (line 1)) (0.2.2)\n    Requirement already satisfied: numba>=0.43.0 in /usr/local/lib/python3.7/dist-packages (from librosa>=0.6.1->-r /content/Resemblyzer/requirements_demos.txt (line 1)) (0.51.2)\n    Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.7/dist-packages (from librosa>=0.6.1->-r /content/Resemblyzer/requirements_demos.txt (line 1)) (21.3)\n    Requirement already satisfied: pooch>=1.0 in /usr/local/lib/python3.7/dist-packages (from librosa>=0.6.1->-r /content/Resemblyzer/requirements_demos.txt (line 1)) (1.5.2)\n    Requirement already satisfied: soundfile>=0.10.2 in /usr/local/lib/python3.7/dist-packages (from librosa>=0.6.1->-r /content/Resemblyzer/requirements_demos.txt (line 1)) (0.10.3.post1)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch>=1.0.1->-r /content/Resemblyzer/requirements_demos.txt (line 4)) (3.10.0.2)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=3.0.0->-r /content/Resemblyzer/requirements_demos.txt (line 7)) (3.0.6)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=3.0.0->-r /content/Resemblyzer/requirements_demos.txt (line 7)) (0.11.0)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=3.0.0->-r /content/Resemblyzer/requirements_demos.txt (line 7)) (2.8.2)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=3.0.0->-r /content/Resemblyzer/requirements_demos.txt (line 7)) (1.3.2)\n    Requirement already satisfied: llvmlite<0.35,>=0.34.0.dev0 in /usr/local/lib/python3.7/dist-packages (from numba>=0.43.0->librosa>=0.6.1->-r /content/Resemblyzer/requirements_demos.txt (line 1)) (0.34.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from numba>=0.43.0->librosa>=0.6.1->-r /content/Resemblyzer/requirements_demos.txt (line 1)) (57.4.0)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pooch>=1.0->librosa>=0.6.1->-r /content/Resemblyzer/requirements_demos.txt (line 1)) (2.23.0)\n    Requirement already satisfied: appdirs in /usr/local/lib/python3.7/dist-packages (from pooch>=1.0->librosa>=0.6.1->-r /content/Resemblyzer/requirements_demos.txt (line 1)) (1.4.4)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.1->matplotlib>=3.0.0->-r /content/Resemblyzer/requirements_demos.txt (line 7)) (1.15.0)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn!=0.19.0,>=0.14.0->librosa>=0.6.1->-r /content/Resemblyzer/requirements_demos.txt (line 1)) (3.0.0)\n    Requirement already satisfied: cffi>=1.0 in /usr/local/lib/python3.7/dist-packages (from soundfile>=0.10.2->librosa>=0.6.1->-r /content/Resemblyzer/requirements_demos.txt (line 1)) (1.15.0)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.0->soundfile>=0.10.2->librosa>=0.6.1->-r /content/Resemblyzer/requirements_demos.txt (line 1)) (2.21)\n    Collecting pynndescent>=0.5\n      Downloading pynndescent-0.5.5.tar.gz (1.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.1 MB 23.0 MB/s \n    \u001b[?25hRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pooch>=1.0->librosa>=0.6.1->-r /content/Resemblyzer/requirements_demos.txt (line 1)) (3.0.4)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pooch>=1.0->librosa>=0.6.1->-r /content/Resemblyzer/requirements_demos.txt (line 1)) (1.24.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pooch>=1.0->librosa>=0.6.1->-r /content/Resemblyzer/requirements_demos.txt (line 1)) (2021.10.8)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pooch>=1.0->librosa>=0.6.1->-r /content/Resemblyzer/requirements_demos.txt (line 1)) (2.10)\n    Building wheels for collected packages: webrtcvad, typing, umap-learn, pynndescent\n      Building wheel for webrtcvad (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for webrtcvad: filename=webrtcvad-2.0.10-cp37-cp37m-linux_x86_64.whl size=72371 sha256=7621f4ae82593fcd07bed8d20dbae14244801d282e036e3ccae3bc29a5c95bee\n      Stored in directory: /root/.cache/pip/wheels/11/f9/67/a3158d131f57e1c0a7d8d966a707d4a2fb27567a4fe47723ad\n      Building wheel for typing (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for typing: filename=typing-3.7.4.3-py3-none-any.whl size=26324 sha256=fbd02a1c9f53568e1fc1325fe365404b2e64401b5d3e3300c61e00db30c1c037\n      Stored in directory: /root/.cache/pip/wheels/35/f3/15/01aa6571f0a72ee6ae7b827c1491c37a1f72d686fd22b43b0e\n      Building wheel for umap-learn (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for umap-learn: filename=umap_learn-0.5.2-py3-none-any.whl size=82709 sha256=ba9cc8bd29661af264bf40ab0438f52001799bd4db06a4047b8d6e9d3370d702\n      Stored in directory: /root/.cache/pip/wheels/84/1b/c6/aaf68a748122632967cef4dffef68224eb16798b6793257d82\n      Building wheel for pynndescent (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pynndescent: filename=pynndescent-0.5.5-py3-none-any.whl size=52603 sha256=baff4af0093c996b086ed9c9f33e3ee2e24de44b6cf5cfc68aec0a949a5146dd\n      Stored in directory: /root/.cache/pip/wheels/af/e9/33/04db1436df0757c42fda8ea6796d7a8586e23c85fac355f476\n    Successfully built webrtcvad typing umap-learn pynndescent\n    Installing collected packages: pynndescent, webrtcvad, umap-learn, typing, sounddevice\n    Successfully installed pynndescent-0.5.5 sounddevice-0.4.4 typing-3.7.4.3 umap-learn-0.5.2 webrtcvad-2.0.10\n\n\n\n\n\n```python\n!mkdir /content/new\n```\n\n\n```python\nfrom resemblyzer import preprocess_wav, VoiceEncoder\nfrom pathlib import Path\n\n#give the file path to your audio file (Noagenda-0690-2015-01-25-Noagenda-0690-2015-01-25 from 13:37 to 15:12)\naudio_file_path = '/content/new/noagenda-extract.wav'\nwav_fpath = Path(audio_file_path)\n\nwav = preprocess_wav(wav_fpath)\nencoder = VoiceEncoder(\"cpu\")\n_, cont_embeds, wav_splits = encoder.embed_utterance(wav, return_partials=True, rate=16)\nprint(cont_embeds.shape)\n```\n\n    Loaded the voice encoder model on cpu in 0.04 seconds.\n    (1548, 256)\n\n\n\n```python\n!pip install spectralcluster\n```\n\n    Collecting spectralcluster\n      Downloading spectralcluster-0.2.4-py3-none-any.whl (22 kB)\n    Installing collected packages: spectralcluster\n    Successfully installed spectralcluster-0.2.4\n\n\n\n```python\nfrom spectralcluster import configs\n\nlabels = configs.icassp2018_clusterer.predict(cont_embeds)\n\n#labels = clusterer.predict(cont_embeds)\n```\n\n\n```python\nfrom spectralcluster import RefinementOptions\nfrom spectralcluster import ThresholdType\nfrom spectralcluster import ICASSP2018_REFINEMENT_SEQUENCE\n\nrefinement_options = RefinementOptions(\n    gaussian_blur_sigma=1,\n    p_percentile=0.95,\n    thresholding_soft_multiplier=0.01,\n    thresholding_type=ThresholdType.RowMax,\n    refinement_sequence=ICASSP2018_REFINEMENT_SEQUENCE)\n```\n\n\n```python\nfrom spectralcluster import SpectralClusterer\n\nclusterer = SpectralClusterer(\n    min_clusters=2,\n    max_clusters=7,\n    autotune=None,\n    laplacian_type=None,\n    refinement_options=refinement_options,\n    custom_dist=\"cosine\")\nprint(\"Done\")\nlabels = clusterer.predict(cont_embeds)\n```\n\n    Done\n\n\n\n```python\nlabels\n```\n\n\n\n\n    array([0, 0, 0, ..., 0, 0, 0])\n\n\n\n\n```python\nfrom spectralcluster import AutoTune\n\nautotune = AutoTune(\n    p_percentile_min=0.60,\n    p_percentile_max=0.95,\n    init_search_step=0.01,\n    search_level=3)\n```\n\n\n```python\ndef create_labelling(labels,wav_splits):\n    from resemblyzer import sampling_rate\n    times = [((s.start + s.stop) / 2) / sampling_rate for s in wav_splits]\n    labelling = []\n    start_time = 0\n\n    for i,time in enumerate(times):\n        if i>0 and labels[i]!=labels[i-1]:\n            temp = [str(labels[i-1]),start_time,time]\n            labelling.append(tuple(temp))\n            start_time = time\n        if i==len(times)-1:\n            temp = [str(labels[i]),start_time,time]\n            labelling.append(tuple(temp))\n\n    return labelling\n```\n\n\n```python\nlabelling = create_labelling(labels,wav_splits)\n```\n\n\n```python\nlabelling\n```\n\n\n\n\n    [('0', 0, 16.34),\n     ('1', 16.34, 17.78),\n     ('0', 17.78, 22.4),\n     ('1', 22.4, 24.14),\n     ('0', 24.14, 27.86),\n     ('1', 27.86, 30.38),\n     ('0', 30.38, 57.74),\n     ('1', 57.74, 62.06),\n     ('0', 62.06, 69.38),\n     ('1', 69.38, 69.5),\n     ('0', 69.5, 70.94),\n     ('1', 70.94, 74.9),\n     ('0', 74.9, 79.76),\n     ('1', 79.76, 80.18),\n     ('0', 80.18, 93.62)]\n\n\n\n\n```python\npip install pydub\n```\n\n    Collecting pydub\n      Downloading pydub-0.25.1-py2.py3-none-any.whl (32 kB)\n    Installing collected packages: pydub\n    Successfully installed pydub-0.25.1\n\n\n\n```python\nfrom pydub import AudioSegment\n\ndef mp3_to_wav(audio_file_path):\n    sound = AudioSegment.from_mp3(audio_file_path)\n    audio_file_path = audio_file_path.split('.')[0] + '.wav'\n    sound.export(audio_file_path, format=\"wav\")\n    return audio_file_path\n\n#audio_file_path = mp3_to_wav(audio_file_path)\n#print(audio_file_path)\n```\n\n\n```python\npip install spectralcluster\n```\n\n    Requirement already satisfied: spectralcluster in /usr/local/lib/python3.7/dist-packages (0.2.4)\n\n\n\n```python\n!pip install ffmpeg-python\n```\n\n    Collecting ffmpeg-python\n      Downloading ffmpeg_python-0.2.0-py3-none-any.whl (25 kB)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from ffmpeg-python) (0.16.0)\n    Installing collected packages: ffmpeg-python\n    Successfully installed ffmpeg-python-0.2.0\n\n\n\n```python\nimport ffmpeg\ndef create_output_files(path):\n    # For each tuple in the labelling file, extract ele[0] as the speaker\n    # label, ele[1] as the start time, and ele[2] as the end time\n    num = 1\n    input = ffmpeg.input(path)\n    for ele in labelling:\n        audio_trim = input.audio.filter('atrim', start=ele[1], end=ele[2])\n        numstr = str(num)\n        while len(numstr) < 4:\n            numstr = \"0\" + numstr\n        output = ffmpeg.output(audio_trim, \"/content/extract{}.wav\".format(numstr))\n        output.run(capture_stdout=True, capture_stderr=True, overwrite_output=True)\n        num += 1\n\n```\n\n\n```python\ntry:\n    create_output_files(audio_file_path)\nexcept ffmpeg.Error as e:\n    print(e.stderr)  \n```\n\n\n```python\n!pip install SpeechRecognition\n```\n\n    Collecting SpeechRecognition\n      Downloading SpeechRecognition-3.8.1-py2.py3-none-any.whl (32.8 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 32.8 MB 1.6 MB/s \n    \u001b[?25hInstalling collected packages: SpeechRecognition\n    Successfully installed SpeechRecognition-3.8.1\n\n\n\n```python\nimport speech_recognition as sr\ndef transcribe_audio(path):\n    r = sr.Recognizer()\n    audio_file = sr.AudioFile(path)\n    with audio_file as source:\n        r.adjust_for_ambient_noise(source)\n        audio = r.record(source)\n    try:\n        res = r.recognize_google(audio, language=\"en-US\")\n    except sr.UnknownValueError:\n        res = \"(The speech is unintelligible)\"\n    except sr.RequestError:\n        res = \"(The speech recognition operation failed)\"\n    return res\n```\n\n\n```python\nimport os\nimport os.path\nlist_dir = os.listdir(\"/content\")\ni = 0\nfor e in list_dir:\n    if e.startswith('extract'):\n        path = os.path.join(\"/content\", e)\n        transcription = transcribe_audio(path)\n        print(\"Speaker {}: {}\".format(labelling[i][0], transcription))\n        i += 1\n```\n\n    Speaker 0: (The speech is unintelligible)\n    Speaker 1: (The speech is unintelligible)\n    Speaker 0: (The speech is unintelligible)\n    Speaker 1: the commitments\n    Speaker 0: negotiate\n    Speaker 1: I have instability in financial markets believe that a couple of years ago\n    Speaker 0: (The speech is unintelligible)\n    Speaker 1: it'll be between\n    Speaker 0: (The speech is unintelligible)\n    Speaker 1: Eurasian or renegotiate\n    Speaker 0: (The speech is unintelligible)\n    Speaker 1: it's true I heard it too did you get this from TV or from the web\n    Speaker 0: commitment\n    Speaker 1: (The speech is unintelligible)\n    Speaker 0: (The speech is unintelligible)\n\n\n\n```python\n!pip install pyannote.metrics\n```\n\nTo calculate the DER and the JER, several tools can be used such as *dscore* or *pyannote*\n\n# Dscore\nTo use *dscore*, run the following commands.\n\n\n```python\n!git clone https://github.com/nryant/dscore.git\n```\n\n    fatal: destination path 'dscore' already exists and is not an empty directory.\n\n\n\n```python\n%cd ../dscore\n```\n\n    /content/dscore\n\n\n\n```python\n!pip install -r requirements.txt\n```\n\n    Collecting intervaltree>=3.0.0\n      Downloading intervaltree-3.1.0.tar.gz (32 kB)\n    Requirement already satisfied: numpy>=1.16.2 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 2)) (1.19.5)\n    Requirement already satisfied: scipy>=0.17.0 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 3)) (1.4.1)\n    Requirement already satisfied: tabulate>=0.5.0 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 4)) (0.8.9)\n    Requirement already satisfied: sortedcontainers<3.0,>=2.0 in /usr/local/lib/python3.7/dist-packages (from intervaltree>=3.0.0->-r requirements.txt (line 1)) (2.4.0)\n    Building wheels for collected packages: intervaltree\n      Building wheel for intervaltree (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for intervaltree: filename=intervaltree-3.1.0-py2.py3-none-any.whl size=26119 sha256=896a15e34262e5ed51f8664527cb236e81e4bba51a03d416f7bbcc42c7288cb6\n      Stored in directory: /root/.cache/pip/wheels/16/85/bd/1001cbb46dcfb71c2001cd7401c6fb250392f22a81ce3722f7\n    Successfully built intervaltree\n    Installing collected packages: intervaltree\n      Attempting uninstall: intervaltree\n        Found existing installation: intervaltree 2.1.0\n        Uninstalling intervaltree-2.1.0:\n          Successfully uninstalled intervaltree-2.1.0\n    Successfully installed intervaltree-3.1.0\n\n\nThe script *score.py* takes one or several RTTM files for the reference and the system.\n\nRich Transcription Time Marked (RTTM) files are space-delimited text files containing one turn per line, each line containing ten fields:\n\nType -- segment type; should always by SPEAKER\n\nFile ID -- file name; basename of the recording minus extension (e.g., rec1_a)\n\nChannel ID -- channel (1-indexed) that turn is on; should always be 1\n\nTurn Onset -- onset of turn in seconds from beginning of recording\n\nTurn Duration -- duration of turn in seconds\n\nOrthography Field -- should always be ```<NA>```\n\nSpeaker Type -- should always be ```<NA>```\n\nSpeaker Name -- name of speaker of turn; should be unique within scope of each file\n\nConfidence Score -- system confidence (probability) that information is correct; should always be ```<NA>```\n\nSignal Lookahead Time -- should always be ```<NA>```\n\n## Example\n```\nSPEAKER CMU_20020319-1400_d01_NONE 1 130.430000 2.350 <NA> <NA> juliet <NA> <NA>\nSPEAKER CMU_20020319-1400_d01_NONE 1 157.610000 3.060 <NA> <NA> tbc <NA> <NA>\nSPEAKER CMU_20020319-1400_d01_NONE 1 130.490000 0.450 <NA> <NA> chek <NA> <NA>\n```\n\nYou can then execute *score.py* with the reference files and the system files\n\n\n```python\n%cd /content/dscore/\n```\n\n\n```python\n!python score.py -r ../CMU_20030109-1600.sdm.overlap.rttm -s ../out.rttm\n```\n\n# PyAnnote\n\nFirst, install PyAnnote with the following command:\n\n# New Section\n\n**Start to execute here: don't take into account the cells above (except for Resemblyzer)**\n\n\n```python\n!pip install pyannote.metrics\n```\n\n    Collecting pyannote.metrics\n      Downloading pyannote.metrics-3.1-py3-none-any.whl (49 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 49 kB 3.5 MB/s \n    \u001b[?25hRequirement already satisfied: sympy>=1.1 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics) (1.7.1)\n    Collecting pyannote.core>=4.1\n      Downloading pyannote.core-4.3-py3-none-any.whl (59 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 59 kB 8.9 MB/s \n    \u001b[?25hCollecting pyannote.database>=4.0.1\n      Downloading pyannote.database-4.1.1-py3-none-any.whl (41 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 41 kB 331 kB/s \n    \u001b[?25hRequirement already satisfied: scikit-learn>=0.17.1 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics) (1.0.1)\n    Requirement already satisfied: docopt>=0.6.2 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics) (0.6.2)\n    Requirement already satisfied: scipy>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics) (1.4.1)\n    Requirement already satisfied: matplotlib>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics) (3.2.2)\n    Requirement already satisfied: pandas>=0.19 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics) (1.1.5)\n    Requirement already satisfied: tabulate>=0.7.7 in /usr/local/lib/python3.7/dist-packages (from pyannote.metrics) (0.8.9)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.0.0->pyannote.metrics) (0.11.0)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.0.0->pyannote.metrics) (2.8.2)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.0.0->pyannote.metrics) (1.3.2)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.0.0->pyannote.metrics) (3.0.6)\n    Requirement already satisfied: numpy>=1.11 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.0.0->pyannote.metrics) (1.19.5)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.19->pyannote.metrics) (2018.9)\n    Requirement already satisfied: typing-extensions>=3.7.4.1 in /usr/local/lib/python3.7/dist-packages (from pyannote.core>=4.1->pyannote.metrics) (3.10.0.2)\n    Collecting simplejson>=3.8.1\n      Downloading simplejson-3.17.6-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (130 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 130 kB 42.0 MB/s \n    \u001b[?25hRequirement already satisfied: sortedcontainers>=2.0.4 in /usr/local/lib/python3.7/dist-packages (from pyannote.core>=4.1->pyannote.metrics) (2.4.0)\n    Requirement already satisfied: pyYAML>=3.12 in /usr/local/lib/python3.7/dist-packages (from pyannote.database>=4.0.1->pyannote.metrics) (3.13)\n    Collecting typer[all]>=0.2.1\n      Downloading typer-0.4.0-py3-none-any.whl (27 kB)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.1->matplotlib>=2.0.0->pyannote.metrics) (1.15.0)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.17.1->pyannote.metrics) (3.0.0)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.17.1->pyannote.metrics) (1.1.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.1->pyannote.metrics) (1.2.1)\n    Requirement already satisfied: click<9.0.0,>=7.1.1 in /usr/local/lib/python3.7/dist-packages (from typer[all]>=0.2.1->pyannote.database>=4.0.1->pyannote.metrics) (7.1.2)\n    Collecting colorama<0.5.0,>=0.4.3\n      Downloading colorama-0.4.4-py2.py3-none-any.whl (16 kB)\n    Collecting shellingham<2.0.0,>=1.3.0\n      Downloading shellingham-1.4.0-py2.py3-none-any.whl (9.4 kB)\n    Installing collected packages: typer, simplejson, shellingham, colorama, pyannote.core, pyannote.database, pyannote.metrics\n    Successfully installed colorama-0.4.4 pyannote.core-4.3 pyannote.database-4.1.1 pyannote.metrics-3.1 shellingham-1.4.0 simplejson-3.17.6 typer-0.4.0\n\n\nIt seems that you have to add the segments directly in the code. The letters ```A```, ```B```, ```C``` and ```D``` identify the different speakers.\n\n\n```python\nmetric = DiarizationErrorRate()\nmetric(reference, hypothesis, detailed=True)\n```\n\n    /usr/local/lib/python3.7/dist-packages/pyannote/metrics/utils.py:184: UserWarning: 'uem' was approximated by the union of 'reference' and 'hypothesis' extents.\n      \"'uem' was approximated by the union of 'reference' \"\n\n\n\n\n\n    {'confusion': 7.0,\n     'correct': 22.0,\n     'diarization error rate': 0.5161290322580645,\n     'false alarm': 7.0,\n     'missed detection': 2.0,\n     'total': 31.0}\n\n\n\n\n```python\nimport librosa\nimport librosa.display # You need this in librosa to be able to plot\nimport os, sys, glob\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\nimport numpy as np\n\n#give the file path to your audio file\naudio_file_path = '/content/CMU/*'\nclip_dir=glob.glob(audio_file_path)\n```\n\n\n```python\n!pip install spectralcluster\n```\n\n    Collecting spectralcluster\n      Downloading spectralcluster-0.2.4-py3-none-any.whl (22 kB)\n    Installing collected packages: spectralcluster\n    Successfully installed spectralcluster-0.2.4\n\n\n\n```python\nfrom spectralcluster import SpectralClusterer\n\nclusterer = SpectralClusterer(\n    min_clusters=2,\n    max_clusters=7,\n    autotune=None,\n    laplacian_type=None,\n    refinement_options=None,\n    custom_dist=\"cosine\")\n\n\n```\n\n\n```python\ndef create_labelling(labels,wav_splits, prefix=\"\", output_file_name=\"/content/labelling.txt\"):\n    from resemblyzer import sampling_rate\n    times = [((s.start + s.stop) / 2) / sampling_rate for s in wav_splits]\n    start_time = 0\n    with open(output_file_name, 'a+') as f_out:\n        for i,time in enumerate(times):\n            if i>0 and labels[i]!=labels[i-1]:\n                temp = [prefix + str(labels[i-1]),start_time,time]\n                f_out.write(\"{} {} {}\\n\".format(temp[0], temp[1], temp[2]))\n                start_time = time\n            if i==len(times)-1:\n                temp = [prefix + str(labels[i]),start_time,time]\n                f_out.write(\"{} {} {}\\n\".format(temp[0], temp[1], temp[2]))\n\n  \n```\n\n\n```python\n%cd Resemblyzer/\n```\n\n    /content/Resemblyzer\n\n\n\n```python\ndef labelling_to_rttm(input_file, output_file):\n    with open(input_file, 'r') as f_in:\n        with open(output_file, 'a+') as f_out:\n            lines = f_in.readlines()\n            for l in lines:\n                fields = l.split(' ')\n                if len(fields) == 3:\n                    speaker = fields[0]\n                    turn_onset = float(fields[1])\n                    turn_duration = float(fields[2][:-1]) - turn_onset\n                    output_line = \"SPEAKER {} 1 {:.3f} {:.3f} <NA> <NA> {} <NA> <NA>\".format(speaker, turn_onset, turn_duration, speaker)\n                    f_out.write(output_line + \"\\n\")\n```\n\n\n```python\n\n```\n\n\n```python\ndef time_labelling_to_rttm(input_file, output_file):\n    with open(input_file, 'r') as f_in:\n        with open(output_file, 'a+') as f_out:\n            lines = f_in.readlines()\n            for l in lines:\n                fields = l.split()\n                print(fields)\n                if len(fields) == 3:\n                    print(fields)\n                    speaker = fields[0]\n                    turn_onset= (datetime.datetime.strptime((fields[1]).strip().replace('\\n',''),\"%H:%M:%S,%f\") - datetime.datetime(1900, 1, 1)).total_seconds()\n                    #turn_onset = float(fields[1])\n                    print(turn_onset)\n                    turn_duration = (datetime.datetime.strptime((fields[2]).strip().replace('\\n',''),\"%H:%M:%S,%f\") - datetime.datetime(1900, 1, 1)).total_seconds() -turn_onset\n                    #turn_onset =- turn_onset\n                    output_line = \"SPEAKER {} 1 {:.3f} {:.3f} <NA> <NA> {} <NA> <NA>\".format(speaker, turn_onset, turn_duration, speaker)\n                    f_out.write(output_line + \"\\n\")\n```\n\n\n```python\ntime_labelling_to_rttm(\"annotation\", \"/content/out.rttm\")\n```\n\n    ['Speaker1', '00:00:00,630', '00:00:07,020']\n    ['Speaker1', '00:00:00,630', '00:00:07,020']\n    0.63\n    ['Speaker1', '00:00:09,719', '00:00:15,449']\n    ['Speaker1', '00:00:09,719', '00:00:15,449']\n    9.719\n    ['Speaker1', '00:00:16,560', '00:00:36,630']\n    ['Speaker1', '00:00:16,560', '00:00:36,630']\n    16.56\n    ['Speaker2', '00:00:42,810', '00:00:46,290']\n    ['Speaker2', '00:00:42,810', '00:00:46,290']\n    42.81\n    ['Speaker2', '00:00:51,300', '00:01:01,020']\n    ['Speaker2', '00:00:51,300', '00:01:01,020']\n    51.3\n    ['Speaker2', '00:00:55,830', '00:01:01,020']\n    ['Speaker2', '00:00:55,830', '00:01:01,020']\n    55.83\n    ['Speaker2', '00:01:03,180', '00:01:07,050']\n    ['Speaker2', '00:01:03,180', '00:01:07,050']\n    63.18\n    ['Speaker2', '00:01:09,780', '0:01:24,180']\n    ['Speaker2', '00:01:09,780', '0:01:24,180']\n    69.78\n    ['Speaker2', '00:01:24,180', '00:01:58,290']\n    ['Speaker2', '00:01:24,180', '00:01:58,290']\n    84.18\n    ['Speaker3', '00:01:58,290', '00:02:01,740']\n    ['Speaker3', '00:01:58,290', '00:02:01,740']\n    118.29\n    ['Speaker3', '00:02:01,740', '00:02:02,760']\n    ['Speaker3', '00:02:01,740', '00:02:02,760']\n    121.74\n    ['Speaker2', '00:02:04,170', '00:02:07,800']\n    ['Speaker2', '00:02:04,170', '00:02:07,800']\n    124.17\n    ['Speaker3', '00:02:07,800', '00:02:11,220']\n    ['Speaker3', '00:02:07,800', '00:02:11,220']\n    127.8\n    ['Speaker3', '00:02:11,220', '00:02:14,430']\n    ['Speaker3', '00:02:11,220', '00:02:14,430']\n    131.22\n    ['Speaker3', '00:02:18,600', '00:02:22,140']\n    ['Speaker3', '00:02:18,600', '00:02:22,140']\n    138.6\n    ['Speaker1', '00:02:22,170', '00:02:30,630']\n    ['Speaker1', '00:02:22,170', '00:02:30,630']\n    142.17\n    ['Speaker2', '00:02:30,630', '00:02:34,290']\n    ['Speaker2', '00:02:30,630', '00:02:34,290']\n    150.63\n    ['Speaker2', '00:02:35,670', '00:02:38,220']\n    ['Speaker2', '00:02:35,670', '00:02:38,220']\n    155.67\n    ['Speaker3', '00:02:38,220', '00:02:56,730']\n    ['Speaker3', '00:02:38,220', '00:02:56,730']\n    158.22\n    ['Speaker2', '00:02:56,850', '00:03:13,020']\n    ['Speaker2', '00:02:56,850', '00:03:13,020']\n    176.85\n    ['Speaker1', '00:03:14,190', '00:04:03,810']\n    ['Speaker1', '00:03:14,190', '00:04:03,810']\n    194.19\n    ['Speaker2', '00:04:03,810', '00:04:26,340']\n    ['Speaker2', '00:04:03,810', '00:04:26,340']\n    243.81\n    ['Speaker1', '00:04:26,340', '00:04:29,460']\n    ['Speaker1', '00:04:26,340', '00:04:29,460']\n    266.34\n    ['Speaker1', '00:04:29,460', '00:04:35,850']\n    ['Speaker1', '00:04:29,460', '00:04:35,850']\n    269.46\n    ['Speaker2', '00:04:35,850', '00:05:15,450']\n    ['Speaker2', '00:04:35,850', '00:05:15,450']\n    275.85\n    ['Speaker3', '00:05:16,470', '00:05:32,730']\n    ['Speaker3', '00:05:16,470', '00:05:32,730']\n    316.47\n    ['Speaker2', '00:05:32,820', '00:05:46,170']\n    ['Speaker2', '00:05:32,820', '00:05:46,170']\n    332.82\n    ['Speaker3', '00:05:46,170', '00:05:49,560']\n    ['Speaker3', '00:05:46,170', '00:05:49,560']\n    346.17\n    ['Speaker1', '0:05:49,560', '00:06:02,670']\n    ['Speaker1', '0:05:49,560', '00:06:02,670']\n    349.56\n    ['Speaker1', '00:06:02,670', '00:06:45,330']\n    ['Speaker1', '00:06:02,670', '00:06:45,330']\n    362.67\n    ['Speaker3', '00:06:45,330', '00:06:52,560']\n    ['Speaker3', '00:06:45,330', '00:06:52,560']\n    405.33\n\n\n\n```python\n\n```\n\n\n```python\n'ffggg\\n'.strip()\n```\n\n\n\n\n    'ffggg'\n\n\n\n\n```python\n%cd Resemblyzer/\n```\n\n    [Errno 2] No such file or directory: 'Resemblyzer/'\n    /content/Resemblyzer\n\n\n\n```python\nhelp(\"spectralcluster.SpectralClusterer.predict\")\n```\n\n    Help on function predict in spectralcluster.SpectralClusterer:\n    \n    spectralcluster.SpectralClusterer.predict = predict(self, embeddings, constraint_matrix=None)\n        Perform spectral clustering on data embeddings.\n        \n        The spectral clustering is performed on an affinity matrix.\n        \n        Args:\n          embeddings: numpy array of shape (n_samples, n_features)\n          constraint_matrix: numpy array of shape (n_samples, n_samples). The\n            constraint matrix with prior information\n        \n        Returns:\n          labels: numpy array of shape (n_samples,)\n        \n        Raises:\n          TypeError: if embeddings has wrong type\n          ValueError: if embeddings has wrong shape\n    \n\n\n\n```python\n%cd ./Resemblyzer/\n```\n\n    [Errno 2] No such file or directory: './Resemblyzer/'\n    /content/Resemblyzer\n\n\n\n```python\nfrom spectralcluster import SpectralClusterer\nfrom resemblyzer import preprocess_wav, VoiceEncoder\nfrom pathlib import Path\nimport os\n#print(\"fff\")\n#print(wav_fpath)\n\n\nclip_dir = '/content/new/' \n# list of files in clip_dir\nlist_files = [f for f in os.listdir(clip_dir) if not f.startswith('.')]\nutterance_spec=[]\ntotal_labelling = []\nfor idx,showName in enumerate(list_files):\n    base, ext = os.path.splitext(showName)\n    path = os.path.join(clip_dir, showName)\n    wav = preprocess_wav(path)\n    utterance_spec.append(wav)\n    encoder = VoiceEncoder(\"cpu\")\n    _, cont_embeds, wav_splits = encoder.embed_utterance(wav, return_partials=True, rate=16)\n    print(cont_embeds.shape)\n\n    clusterer = SpectralClusterer(\n        min_clusters=3,\n        max_clusters=7,\n        autotune=None,\n        laplacian_type=None,\n        refinement_options=None,\n        custom_dist=\"cosine\"\n    )\n    labels = clusterer.predict(cont_embeds)\n    create_labelling(labels, wav_splits, prefix=base)\n    print('Lablling created for {}'.format(showName))\n    del wav, encoder, cont_embeds, wav_splits, clusterer, labels\n\n#utterance_spec = np.array(utterance_spec)\n\n```\n\n    Loaded the voice encoder model on cpu in 0.01 seconds.\n    (3417, 256)\n    Lablling created for extract.wav\n\n\n\n```python\nlabelling_to_rttm(\"/content/labelling.txt\", \"/content/out.rttm\")\n```\n\n\n```python\nfrom pyannote.core import Segment, Timeline, Annotation\nfrom pyannote.metrics.diarization import DiarizationErrorRate\n\n#speaker=['A','B','C','D','E']\ndef annotate(path, uri='file1'):\n    res = Annotation(uri=uri)\n    \n    with open(path, \"r\") as f:\n        # current speaker in the reference\n        current_speaker_ref = ''\n        # current begin time\n        current_begin = 0\n        # current end time\n        current_end = 0\n        rttmspeaker=dict()\n        lines = f.readlines()\n        for index, l in enumerate(lines):\n            # for each line, we check whether the line starts with SPEAKER\n            if l.startswith('SPEAKER'):\n                num=0\n                currentspeaker=0\n                fields = l.split(' ')\n                if len(l) > 7:\n                    speaker = fields[7]\n                    if speaker not in rttmspeaker.keys():\n                      rttmspeaker[speaker]=num\n                      num=num+1\n                    else:\n                     currentspeaker= rttmspeaker[speaker]\n\n                    start = float(fields[3])\n                    end = start + float(fields[4]) # end = start + duration\n                    #if speaker == current_speaker_ref and index < len(lines)-1:\n                    #    current_end = end\n                    #elif current_speaker_ref == '':\n                    #    current_speaker_ref = speaker\n                    #   current_begin = start\n                    #    current_end = end\n                    #else:\n                    print(str(start)+ ' ' + str(end)+ ' '+str(speaker))\n                    res[Segment(start, end)] = speaker\n    return res\n\nreference = annotate(\"/content/out.rttm\")\n#reference = annotate(\"/content/CMU_20030109-1530.mdm.overlap.rttm\")\n#hypothesis = annotate(\"/content/out.rttm\")\n```\n\n    0.63 7.02 Speaker1\n    9.719 15.449 Speaker1\n    16.56 36.629999999999995 Speaker1\n    42.81 46.29 Speaker2\n    51.3 61.019999999999996 Speaker2\n    55.83 61.019999999999996 Speaker2\n    63.18 67.05 Speaker2\n    69.78 84.18 Speaker2\n    84.18 118.29 Speaker2\n    118.29 121.74000000000001 Speaker3\n    121.74 122.75999999999999 Speaker3\n    124.17 127.8 Speaker2\n    127.8 131.22 Speaker3\n    131.22 134.43 Speaker3\n    138.6 142.14 Speaker3\n    142.17 150.63 Speaker1\n    150.63 154.29 Speaker2\n    155.67 158.22 Speaker2\n    158.22 176.73 Speaker3\n    176.85 193.01999999999998 Speaker2\n    194.19 243.81 Speaker1\n    243.81 266.34000000000003 Speaker2\n    266.34 269.46 Speaker1\n    269.46 275.84999999999997 Speaker1\n    275.85 315.45000000000005 Speaker2\n    316.47 332.73 Speaker3\n    332.82 346.17 Speaker2\n    346.17 349.56 Speaker3\n    349.56 362.67 Speaker1\n    362.67 405.33000000000004 Speaker1\n    405.33 412.56 Speaker3\n\n\n\n```python\ndiarization\n```\n\n\n```python\nmetric = DiarizationErrorRate()\nmetric(reference, diarization, detailed=True)\n```\n\n    /usr/local/lib/python3.7/dist-packages/pyannote/metrics/utils.py:184: UserWarning:\n    \n    'uem' was approximated by the union of 'reference' and 'hypothesis' extents.\n    \n\n\n\n\n\n    {'confusion': 153.4279999999999,\n     'correct': 195.8082499999997,\n     'diarization error rate': 0.5600233021349015,\n     'false alarm': 25.16768749999996,\n     'missed detection': 38.603750000000225,\n     'total': 387.83999999999986}\n\n\n\n\n```python\nreport = metric.report(display=True)\n```\n\n          diarization error rate  total correct correct false alarm false alarm missed detection missed detection confusion confusion\n                               %                      %                       %                                 %                   %\n    item                                                                                                                             \n    file1                  54.67 905.88  556.70   61.45      146.07       16.13           287.68            31.76     61.50      6.79\n    TOTAL                  54.67 905.88  556.70   61.45      146.07       16.13           287.68            31.76     61.50      6.79\n\n\n\n```python\nreport = metric.report(display=True)\n```\n\n          diarization error rate  total correct correct false alarm false alarm missed detection missed detection confusion confusion\n                               %                      %                       %                                 %                   %\n    item                                                                                                                             \n    file1                  56.00 387.84  195.81   50.49       25.17        6.49            38.60             9.95    153.43     39.56\n    TOTAL                  56.00 387.84  195.81   50.49       25.17        6.49            38.60             9.95    153.43     39.56\n\n\n\n```python\n!pip install ffmpeg-python\n```\n\n    Collecting ffmpeg-python\n      Downloading ffmpeg_python-0.2.0-py3-none-any.whl (25 kB)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from ffmpeg-python) (0.16.0)\n    Installing collected packages: ffmpeg-python\n    Successfully installed ffmpeg-python-0.2.0\n\n\n\n```python\ntime_labelling_to_rttm(\"annotation\", \"/content/out.rttm\")\n```\n\n\n```python\nimport datetime\n```\n\n\n```python\ndate_time=datetime.datetime.strptime('00:00:55,830',\"%H:%M:%S,%f\")\na_timedelta = date_time - datetime.datetime(1900, 1, 1)\nseconds = a_timedelta.total_seconds()\n```\n\n\n```python\n\n```\n\n\n```python\nseconds\n```\n\n\n\n\n    55.83\n\n\n\nhttps://github.com/kaldi-asr/kaldi/blob/master/egs/wsj/s5/steps/segmentation/convert_utt2spk_and_segments_to_rttm.py\n\n\n```python\nimport ffmpeg\ninput = ffmpeg.input('/content/nashnote.mp3')\naudio_trim = input.audio.filter('atrim', start=0, end=410)\noutput = ffmpeg.output(audio_trim, \"/content/extract.wav\")\noutput.run(capture_stdout=True, capture_stderr=True, overwrite_output=True)\n\n```\n\n\n\n\n    (b'',\n     b\"ffmpeg version 3.4.8-0ubuntu0.2 Copyright (c) 2000-2020 the FFmpeg developers\\n  built with gcc 7 (Ubuntu 7.5.0-3ubuntu1~18.04)\\n  configuration: --prefix=/usr --extra-version=0ubuntu0.2 --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --enable-gpl --disable-stripping --enable-avresample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librubberband --enable-librsvg --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-omx --enable-openal --enable-opengl --enable-sdl2 --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libopencv --enable-libx264 --enable-shared\\n  libavutil      55. 78.100 / 55. 78.100\\n  libavcodec     57.107.100 / 57.107.100\\n  libavformat    57. 83.100 / 57. 83.100\\n  libavdevice    57. 10.100 / 57. 10.100\\n  libavfilter     6.107.100 /  6.107.100\\n  libavresample   3.  7.  0 /  3.  7.  0\\n  libswscale      4.  8.100 /  4.  8.100\\n  libswresample   2.  9.100 /  2.  9.100\\n  libpostproc    54.  7.100 / 54.  7.100\\n[mp3 @ 0x563d832c6000] Estimating duration from bitrate, this may be inaccurate\\nInput #0, mp3, from '/content/nashnote.mp3':\\n  Metadata:\\n    title           : PC20-49-2021-08-06\\n    TIT3            : BOTG\\n    album           : Podcasting 2.0\\n    artist          : Adam Curry & Dave Jones\\n    comment         : Podcasting 2.0 for August 6th 2021 Episode 49: BOTG \\n                    : Adam & Dave discuss the week's developments on podcastindex.org live from Podcast Movement in Nashville Tennessee and we're joined by Renowned Industry Expert Daniel J Lewis \\n                    : I'm Adam Curry in the He...\\n    lyrics-eng      : Podcasting 2.0 for August 6th 2021 Episode 49: BOTG \\n                    : Adam & Dave discuss the week's developments on podcastindex.org live from Podcast Movement in Nashville Tennessee and we're joined by Renowned Industry Expert Daniel J Lewis \\n                    : I'm Adam Curry in the Heart of Hill Country Texas \\n                    : And In Nashville Tennessee, The True Live Music Capitol of the World - My Friend on the Other End -- Dave Jones! \\n                    : Crank those value sliders up on any of these value4value streaming payment apps: \\n                    : Breez app \\n                    : CurioCaster \\n                    : Fountain.FM \\n                    : Podfriend \\n                    : Podstation Browser extension \\n                    : Podverse \\n                    : Sphinx Chat App \\n                    : Value4Value.io Explains how this works! \\n                    : Download the mp3 \\n                    : Podcast Feed \\n                    : PodcastIndex.org \\n                    : Preservepodcasting.com \\n                    : Check out the podcasting 2.0 apps and services newpodcastapps.com \\n                    : Support us with your Time Talent and Treasure \\n                    : ShowNotes \\n                    : Daniel J Lewis \\n                    : Podcasting advocate and educator, award-winning host of The Audacity to Podcast, creator of My Podcast Reviews, curator of Podcast Industry Insights. \\n                    : Boostagram \\n                    : Fast Follow \\n                    : \\n    composer        : Podcast Index LLC\\n    track           : 49\\n    encoded_by      : Hindenburg Journalist Pro 1.86.2380\\n    genre           : Podcast\\n    copyright       : 2020-2021 Podcast Index LLC\\n    date            : 2021\\n  Duration: 01:10:19.83, start: 0.000000, bitrate: 96 kb/s\\n    Stream #0:0: Audio: mp3, 44100 Hz, stereo, s16p, 96 kb/s\\n    Stream #0:1: Video: mjpeg, yuvj420p(pc, bt470bg/unknown/unknown), 300x300 [SAR 1:1 DAR 1:1], 90k tbr, 90k tbn, 90k tbc\\n    Metadata:\\n      title           : Image\\n      comment         : Other\\nStream mapping:\\n  Stream #0:0 (mp3) -> atrim\\n  atrim -> Stream #0:0 (pcm_s16le)\\nPress [q] to stop, [?] for help\\nOutput #0, wav, to '/content/extract.wav':\\n  Metadata:\\n    INAM            : PC20-49-2021-08-06\\n    TIT3            : BOTG\\n    IPRD            : Podcasting 2.0\\n    IART            : Adam Curry & Dave Jones\\n    ICMT            : Podcasting 2.0 for August 6th 2021 Episode 49: BOTG \\n                    : Adam & Dave discuss the week's developments on podcastindex.org live from Podcast Movement in Nashville Tennessee and we're joined by Renowned Industry Expert Daniel J Lewis \\n                    : I'm Adam Curry in the He...\\n    lyrics-eng      : Podcasting 2.0 for August 6th 2021 Episode 49: BOTG \\n                    : Adam & Dave discuss the week's developments on podcastindex.org live from Podcast Movement in Nashville Tennessee and we're joined by Renowned Industry Expert Daniel J Lewis \\n                    : I'm Adam Curry in the Heart of Hill Country Texas \\n                    : And In Nashville Tennessee, The True Live Music Capitol of the World - My Friend on the Other End -- Dave Jones! \\n                    : Crank those value sliders up on any of these value4value streaming payment apps: \\n                    : Breez app \\n                    : CurioCaster \\n                    : Fountain.FM \\n                    : Podfriend \\n                    : Podstation Browser extension \\n                    : Podverse \\n                    : Sphinx Chat App \\n                    : Value4Value.io Explains how this works! \\n                    : Download the mp3 \\n                    : Podcast Feed \\n                    : PodcastIndex.org \\n                    : Preservepodcasting.com \\n                    : Check out the podcasting 2.0 apps and services newpodcastapps.com \\n                    : Support us with your Time Talent and Treasure \\n                    : ShowNotes \\n                    : Daniel J Lewis \\n                    : Podcasting advocate and educator, award-winning host of The Audacity to Podcast, creator of My Podcast Reviews, curator of Podcast Industry Insights. \\n                    : Boostagram \\n                    : Fast Follow \\n                    : \\n    composer        : Podcast Index LLC\\n    IPRT            : 49\\n    ITCH            : Hindenburg Journalist Pro 1.86.2380\\n    IGNR            : Podcast\\n    ICOP            : 2020-2021 Podcast Index LLC\\n    ICRD            : 2021\\n    ISFT            : Lavf57.83.100\\n    Stream #0:0: Audio: pcm_s16le ([1][0][0][0] / 0x0001), 44100 Hz, stereo, s16, 1411 kb/s\\n    Metadata:\\n      encoder         : Lavc57.107.100 pcm_s16le\\nsize=   35329kB time=00:03:25.29 bitrate=1409.7kbits/s speed= 411x    \\rsize=   70629kB time=00:06:50.00 bitrate=1411.2kbits/s speed= 413x    \\nvideo:0kB audio:70629kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.000758%\\n\")\n\n\n\n\n```python\npip install pyannote.audio==1.1.1\n```\n\n\n```python\npip install pyannote.core\n```\n\n    Requirement already satisfied: pyannote.core in /usr/local/lib/python3.7/dist-packages (4.3)\n    Requirement already satisfied: numpy>=1.10.4 in /usr/local/lib/python3.7/dist-packages (from pyannote.core) (1.19.5)\n    Requirement already satisfied: simplejson>=3.8.1 in /usr/local/lib/python3.7/dist-packages (from pyannote.core) (3.17.6)\n    Requirement already satisfied: scipy>=1.1 in /usr/local/lib/python3.7/dist-packages (from pyannote.core) (1.4.1)\n    Requirement already satisfied: sortedcontainers>=2.0.4 in /usr/local/lib/python3.7/dist-packages (from pyannote.core) (2.4.0)\n    Requirement already satisfied: typing-extensions>=3.7.4.1 in /usr/local/lib/python3.7/dist-packages (from pyannote.core) (3.10.0.2)\n\n\n\n```python\nimport torch\npipeline = torch.hub.load('pyannote/pyannote-audio', 'dia_dihard')\n```\n\n    Using cache found in /root/.cache/torch/hub/pyannote_pyannote-audio_master\n\n\n    Downloading list of pretrained models and pipelines to \"/root/.pyannote/hub/pretrained.yml\".\n\n\n\n      0%|          | 0.00/901 [00:00<?, ?B/s]\n\n\n    Downloading pretrained pipeline \"dia_dihard\" to \"/root/.pyannote/hub/pipelines/dia_dihard.zip\".\n\n\n\n      0%|          | 0.00/1.49k [00:00<?, ?B/s]\n\n\n    Downloading pretrained model \"sad_dihard\" to \"/root/.pyannote/hub/models/sad_dihard.zip\".\n\n\n    Using cache found in /root/.cache/torch/hub/pyannote_pyannote-audio_master\n\n\n\n      0%|          | 0.00/2.41M [00:00<?, ?B/s]\n\n\n    Using cache found in /root/.cache/torch/hub/pyannote_pyannote-audio_master\n\n\n    Downloading pretrained model \"scd_dihard\" to \"/root/.pyannote/hub/models/scd_dihard.zip\".\n\n\n\n      0%|          | 0.00/2.40M [00:00<?, ?B/s]\n\n\n    Downloading pretrained model \"emb_voxceleb\" to \"/root/.pyannote/hub/models/emb_voxceleb.zip\".\n\n\n    Using cache found in /root/.cache/torch/hub/pyannote_pyannote-audio_master\n\n\n\n      0%|          | 0.00/16.3M [00:00<?, ?B/s]\n\n\n    /usr/local/lib/python3.7/dist-packages/pyannote/audio/embedding/approaches/arcface_loss.py:170: FutureWarning:\n    \n    The 's' parameter is deprecated in favor of 'scale', and will be removed in a future release\n    \n    /usr/local/lib/python3.7/dist-packages/pyannote/audio/features/pretrained.py:156: UserWarning:\n    \n    Model was trained with 4s chunks and is applied on 2s chunks. This might lead to sub-optimal results.\n    \n    Using cache found in /root/.cache/torch/hub/pyannote_pyannote-audio_master\n\n\n\n```python\nfrom pyannote.database import get_protocol\nfrom pyannote.database import FileFinder\npreprocessors = {'audio': FileFinder()}\nprotocol = get_protocol('AMI.SpeakerDiarization.MixHeadset',\n                        preprocessors=preprocessors)\ntest_file = next(protocol.test())\n```\n\n\n```python\ntest_file = {'uri': 'filename', 'audio': '/content/extract.wav'}\n```\n\n\n```python\ndiarization = pipeline(test_file)\n```\n\n\n```python\ndiarization\n```\n\n\n```python\nreference\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n\n\n\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "edb06944995b797a8732cdd978ef43db0bb901c8", "size": 179510, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Meetscriber.ipynb", "max_stars_repo_name": "schopra6/Speech-Diarisation-Tool", "max_stars_repo_head_hexsha": "0eb064baae0c8354b3125bb01788c1b12d87f83e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Meetscriber.ipynb", "max_issues_repo_name": "schopra6/Speech-Diarisation-Tool", "max_issues_repo_head_hexsha": "0eb064baae0c8354b3125bb01788c1b12d87f83e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Meetscriber.ipynb", "max_forks_repo_name": "schopra6/Speech-Diarisation-Tool", "max_forks_repo_head_hexsha": "0eb064baae0c8354b3125bb01788c1b12d87f83e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.001253447, "max_line_length": 13118, "alphanum_fraction": 0.5675004178, "converted": true, "num_tokens": 15297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1581743527484317, "lm_q2_score": 0.03846619174275306, "lm_q1q2_score": 0.006084364981607033}}
{"text": "# Python support library: `epic_kitchens`\n\nWe provide a support library `epic_kitchens` that is installed in your conda environment, this contains a variety of helper methods and scripts for...\n\n* Gulping frames: `python -m epic_kitchens.gulp`\n* Converting between RGB frame indices and Flow frame indices: `epic_kitchens.time.*`\n* Dataset classes for use in training loops: `epic_kitchens.dataset.epic_dataset`\n\nFind out more:\n\n* [Github repo](https://github.com/epic-kitchens/epic-lib)\n* [read the docs](http://epic-kitchens.readthedocs.io/en/latest/index.html)\n* [PyPI package](https://pypi.org/project/epic-kitchens/)\n\n---\n\n# Loading frames \n\nWe'll take a look at how you can load the frames off disk and query metadata of the frame segments using a package called [GulpIO](https://github.com/TwentyBN/GulpIO).\n\n\n```python\nimport numpy as np\nfrom gulpio import GulpDirectory\nfrom epic_kitchens.dataset.epic_dataset import EpicVideoDataset, EpicVideoFlowDataset, GulpVideoSegment\nfrom pathlib import Path\n```\n\n## What is Gulp?\n\nFirst we should take a little look at what [GulpIO](https://github.com/TwentyBN/GulpIO) is and what data is contained.\n\nGulpIO consists of three main concepts: *ingestion*, *directories* and *chunks*. *Ingestion* is the process of 'Gulping' a dataset, i.e. transforming it from a set of individual image files on disk into a set of gulp *chunks* each containing a number of images and gulp *directories* containing both gulp *chunks* and metadata files.\n\nAt its core gulp concatenates image files into larger files (gulp chunks) and produces a metadata file containing the offsets and lengths of each image file inside the chunks.\n\n\n\nWe recommend storing frames with gulp and our library `epic_kitchens` assumes this if you wish to use the dataset adapters provided.\n\nWhen producing gulp files we can store arbitrary metadata associated with each segment, we store all information provided in the labels file (verb_class, noun_class, participant_id, ....) as well as details on the image itself: frame_size (width, height, channels) and the number of frames in the segment.\n\nWe provide dataset objects that make loading frames a little easier than with raw gulp from the `epic_kitchens` python package. \n\n\n```python\ngulp_root = Path('../data/processed/gulp')\n```\n\n\n```python\n# The EpicVideoDataset class encapsulates the logic for reading frames\n# from a video and accessing the stored metadata about a segment\n# The class_type determines the labels yielded by the dataset object.\n# class_type value choices: ['verb', 'noun', 'verb+noun', None], None is \n# used for the test sets, where there are no labels.\nclass_type = 'verb+noun'\nrgb_train = EpicVideoDataset(gulp_root / 'rgb_train', class_type)\n```\n\nThe dataset objects give you access to the [GulpDirectory](https://github.com/TwentyBN/GulpIO#read-a-gulped-dataset). Which gives us access to all gulp metadata contained in the directory, we can see which segments are in the gulp file by inspecting the UIDs.\n\n\n```python\nsegment_uids = list(rgb_train.gulp_dir.merged_meta_dict.keys())\nprint(segment_uids[:10], \"...\")\nprint(\"Number of segments\", len(segment_uids))\n```\n\n    ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] ...\n    Number of segments 28472\n\n\nEach entry in the `merged_meta_dict` has two keys, a `frame_info` key storing internal details about segment's frame locations and `meta_data`, arbitrary metadata we store when ingesting the frames, it is in this that we store details about the segment.\n\n\n```python\nexample_meta_entry = rgb_train.gulp_dir.merged_meta_dict[segment_uids[10]]\nexample_meta_entry.keys()\n```\n\n\n\n\n    odict_keys(['frame_info', 'meta_data'])\n\n\n\n\n```python\n# Frame info contains the byte offsets of each jpeg, the padding offset \n# and the length of the jpeg in the gulp chunk\n\n# Format: (offset, padding, length) (all in bytes)\n\nexample_meta_entry['frame_info'][:10]\n```\n\n\n\n\n    [[25991980, 0, 27348],\n     [26019328, 1, 27412],\n     [26046740, 3, 29040],\n     [26075780, 1, 29372],\n     [26105152, 1, 30944],\n     [26136096, 1, 30944],\n     [26167040, 3, 30988],\n     [26198028, 3, 30656],\n     [26228684, 3, 30832],\n     [26259516, 2, 30900]]\n\n\n\nGulp stores the metadata dictionaries in a list, however there is only ever one dictionary for each segment\n\n\n```python\nexample_meta_entry['meta_data'][0]\n```\n\n\n\n\n    OrderedDict([('participant_id', 'P01'),\n                 ('video_id', 'P01_01'),\n                 ('narration', 'open drawer'),\n                 ('start_timestamp', '00:00:24.97'),\n                 ('stop_timestamp', '00:00:26.20'),\n                 ('start_frame', 1498),\n                 ('stop_frame', 1572),\n                 ('verb', 'open'),\n                 ('verb_class', 2),\n                 ('noun', 'drawer'),\n                 ('noun_class', 9),\n                 ('all_nouns', ['drawer']),\n                 ('all_noun_classes', [9]),\n                 ('uid', 10),\n                 ('frame_size', [256, 456, 3]),\n                 ('num_frames', 74)])\n\n\n\n# Reading frames\n\nYou don't have to deal with fiddling around with any of these details as we wrap them up in `GulpVideoSegment` objects that encapsulate the access to segment metadata including the number of frames and labels. You should work with these.\n\n\n```python\nexample_segment = rgb_train.video_segments[10]\nexample_segment\n```\n\n\n\n\n    GulpVideoSegment(OrderedDict([('participant_id', 'P01'), ('video_id', 'P01_01'), ('narration', 'open drawer'), ('start_timestamp', '00:00:24.97'), ('stop_timestamp', '00:00:26.20'), ('start_frame', 1498), ('stop_frame', 1572), ('verb', 'open'), ('verb_class', 2), ('noun', 'drawer'), ('noun_class', 9), ('all_nouns', ['drawer']), ('all_noun_classes', [9]), ('uid', 10), ('frame_size', [256, 456, 3]), ('num_frames', 74)]), <function <lambda> at 0x7fb2dd6366a8>)\n\n\n\nWe can load all the frames for a segment:\n\n\n```python\nexample_frames = rgb_train.load_frames(example_segment)\n```\n\n\n```python\nexample_frames[0]\n```\n\nFrames are loaded as [PIL Images](https://pillow.readthedocs.io/en/5.1.x/reference/Image.html#the-image-class)\n\n\n```python\ntype(example_frames[0])\n```\n\n\n\n\n    PIL.Image.Image\n\n\n\nWhich can be easily converted to numpy arrays\n\n\n```python\nnp.array(example_frames[0]).shape\n```\n\n\n\n\n    (256, 456, 3)\n\n\n\nAnd what is the label of this segment?\n\n\n```python\nexample_segment.label\n```\n\n\n\n\n    {'verb': 2, 'noun': 9}\n\n\n\nIf we wished to access other metadata using dot notation\n\n\n```python\nexample_segment.verb\n```\n\n\n\n\n    'open'\n\n\n\n\n```python\nexample_segment.noun\n```\n\n\n\n\n    'drawer'\n\n\n\nor indexing notation\n\n\n```python\nexample_segment['verb']\n```\n\n\n\n\n    'open'\n\n\n\n\n```python\nexample_segment['noun']\n```\n\n\n\n\n    'drawer'\n\n\n\nOr access the metadata dictionary directly\n\n\n```python\nexample_segment.metadata\n```\n\n\n\n\n    OrderedDict([('participant_id', 'P01'),\n                 ('video_id', 'P01_01'),\n                 ('narration', 'open drawer'),\n                 ('start_timestamp', '00:00:24.97'),\n                 ('stop_timestamp', '00:00:26.20'),\n                 ('start_frame', 1498),\n                 ('stop_frame', 1572),\n                 ('verb', 'open'),\n                 ('verb_class', 2),\n                 ('noun', 'drawer'),\n                 ('noun_class', 9),\n                 ('all_nouns', ['drawer']),\n                 ('all_noun_classes', [9]),\n                 ('uid', 10),\n                 ('frame_size', [256, 456, 3]),\n                 ('num_frames', 74)])\n\n\n\nOnce the frames are loaded, [moviepy](https://zulko.github.io/moviepy/) can be used to inspect the segments\n\n\n```python\n!pip install moviepy\n```\n\n    Requirement already satisfied: moviepy in /jmain01/home/JAD026/dxd01/shared/miniconda3/envs/ar/lib/python3.6/site-packages (0.2.3.5)\n    Requirement already satisfied: tqdm<5.0,>=4.11.2 in /jmain01/home/JAD026/dxd01/shared/miniconda3/envs/ar/lib/python3.6/site-packages (from moviepy) (4.25.0)\n    Requirement already satisfied: decorator<5.0,>=4.0.2 in /jmain01/home/JAD026/dxd01/shared/miniconda3/envs/ar/lib/python3.6/site-packages (from moviepy) (4.3.0)\n    Requirement already satisfied: numpy in /jmain01/home/JAD026/dxd01/shared/miniconda3/envs/ar/lib/python3.6/site-packages (from moviepy) (1.13.3)\n    Requirement already satisfied: imageio<3.0,>=2.1.2 in /jmain01/home/JAD026/dxd01/shared/miniconda3/envs/ar/lib/python3.6/site-packages (from moviepy) (2.3.0)\n    Requirement already satisfied: pillow in /jmain01/home/JAD026/dxd01/shared/miniconda3/envs/ar/lib/python3.6/site-packages (from imageio<3.0,>=2.1.2->moviepy) (5.2.0)\n    \u001b[33mYou are using pip version 10.0.1, however version 18.0 is available.\n    You should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\n\n\n\n```python\nfrom moviepy.editor import ImageSequenceClip\nsegment_clip = ImageSequenceClip([np.array(frame) for frame in example_frames], fps=60)\nsegment_clip.ipython_display()\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 75/75 [00:00<00:00, 644.71it/s]\n\n\n\n\n\n<div align=middle></div>\n\n\n\n---\n\nFlow can be dealt with similarly as we provide an `EpicVideoFlowDataset` class sharing the same API as `EpicVideoDataset`\n\n\n```python\nflow_train = EpicVideoFlowDataset(gulp_root / 'flow_train', class_type)\n```\n\n\n```python\nexample_flow_frames = flow_train.load_frames(example_segment, range(0, example_segment.num_frames))\n```\n\nFlow frames are stored in alternate $(u, v)$ pairs, all $u$ frames have an even index, whereas $v$ frames have an odd index, so if $g$ is the set of frames in the gulp segment:\n\n$$\n\\begin{align}\nu_t &= g_{2t} \\\\\nv_t &= g_{2t + 1}\n\\end{align}\n$$\n\n\n```python\ndef grey_to_rgb(frames):\n    \"\"\"\n    Convert frame(s) from gray (2D array) to RGB (3D array)\n    \"\"\"\n    n_channels = 3\n    return np.repeat(np.array(frames)[..., np.newaxis], n_channels, axis=-1)\n\n\ndef stitch_flow_uv_frames(uv_frames, width_axis=2):\n    \"\"\"\n    Destack (u, v) frames and concatenate them side by side for display purposes\n    \"\"\"\n    u_frames = np.array(uv_frames[::2])\n    v_frames = np.array(uv_frames[1::2])\n    stacked_frames = np.concatenate((u_frames, v_frames), axis=width_axis)\n    return stacked_frames\n\n\ndef clipify_flow(frames, fps=30):\n    \"\"\"\n    Destack flow frames, join them side by side and then create an ImageSequenceClip\n    for display\n    \"\"\"\n    frames = grey_to_rgb(stitch_flow_uv_frames(list(map(np.array, frames))))\n    segment_clip = ImageSequenceClip(list(frames), fps=fps)\n    return segment_clip\n```\n\n\n```python\nexample_segment = flow_train.video_segments[10]\n# Note you can also pass an iterable of frame indices to extract, this is useful for\n# methods like TSN which only need a few frames\nexample_flow_frames =  flow_train.load_frames(example_segment, range(0, example_segment.num_frames))\nclipify_flow(example_flow_frames).ipython_display()\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 38/38 [00:00<00:00, 330.65it/s]\n\n\n\n\n\n<div align=middle></div>\n\n\n", "meta": {"hexsha": "4c69bde9841bb0b51af4c5b4735faa7e2ad39fcf", "size": 826797, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/2.0-gulp.ipynb", "max_stars_repo_name": "epic-kitchens/starter-kit-action-recognition", "max_stars_repo_head_hexsha": "200ba5a49745d2dc01765998dd23ed062de8d08a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2018-09-06T15:32:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T21:14:25.000Z", "max_issues_repo_path": "notebooks/2.0-gulp.ipynb", "max_issues_repo_name": "epic-kitchens/starter-kit-action-recognition", "max_issues_repo_head_hexsha": "200ba5a49745d2dc01765998dd23ed062de8d08a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2018-09-27T13:01:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-14T08:27:02.000Z", "max_forks_repo_path": "notebooks/2.0-gulp.ipynb", "max_forks_repo_name": "epic-kitchens/starter-kit-action-recognition", "max_forks_repo_head_hexsha": "200ba5a49745d2dc01765998dd23ed062de8d08a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-03-20T14:24:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-24T19:44:45.000Z", "avg_line_length": 1156.3594405594, "max_line_length": 436110, "alphanum_fraction": 0.9505150599, "converted": true, "num_tokens": 2866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09670580110615863, "lm_q2_score": 0.06278920508951337, "lm_q1q2_score": 0.006072080379000283}}
{"text": "# Jupyter notebook tips\n\n## Magics\n\nYou can run different languages within a notebook.\n\nUse % to start a single-line expression to run with the magics command.\nUse %% to run a multi-line expression.\n\n\n```python\n# List all available magics\n%lsmagic\n```\n\n\n\n\n    Available line magics:\n    %alias  %alias_magic  %autocall  %automagic  %autosave  %bookmark  %cat  %cd  %clear  %colors  %config  %connect_info  %cp  %debug  %dhist  %dirs  %doctest_mode  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %less  %lf  %lk  %ll  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %lx  %macro  %magic  %man  %matplotlib  %mkdir  %more  %mv  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %popd  %pprint  %precision  %profile  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %rep  %rerun  %reset  %reset_selective  %rm  %rmdir  %run  %save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode\n    \n    Available cell magics:\n    %%!  %%HTML  %%SVG  %%bash  %%capture  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%markdown  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile\n    \n    Automagic is ON, % prefix IS NOT needed for line magics.\n\n\n\n\n```python\n# List your environment variables\n%env\n```\n\n\n\n\n    {'PYENV_VIRTUALENV_DISABLE_PROMPT': '1',\n     'LANG': 'en_CA.UTF-8',\n     'LESS': 'FRXS',\n     'DISPLAY': ':0',\n     'PYENV_ROOT': '/home/gilles/.pyenv',\n     'OLDPWD': '/home/gilles',\n     'INVOCATION_ID': 'df1cf28990bc482789c905c8050d9fd1',\n     'EDITOR': 'nvim',\n     'NODE_PATH': '/home/gilles/.npm-packages/lib/node_modules:',\n     'WM': 'i3',\n     'PERL_MB_OPT': '--install_base \"/home/alp/.local\"',\n     'MOZ_PLUGIN_PATH': '/usr/lib/mozilla/plugins',\n     'PYENV_HOOK_PATH': '/home/gilles/.pyenv/pyenv.d:/usr/local/etc/pyenv.d:/etc/pyenv.d:/usr/lib/pyenv/hooks:/home/gilles/.pyenv/plugins/pyenv-virtualenv/etc/pyenv.d',\n     'XDG_VTNR': '1',\n     'LESS_TERMCAP_so': '\\x1b[1m\\x1b[45m\\x1b[37m',\n     'LESS_TERMCAP_se': '\\x1b[0m',\n     'XDG_SESSION_ID': 'c1',\n     'USER': 'gilles',\n     'ENV': '/home/gilles/.rc',\n     'PYENV_DIR': '/home/gilles/documents/websites/support.gillespilon.ca/fil',\n     'PAGER': 'cat',\n     'RBENV_SHELL': 'zsh',\n     'PYTHONDOCS': '/usr/share/doc/python/html/library',\n     'PWD': '/home/gilles/documents/websites/support.gillespilon.ca/fil',\n     'HOME': '/home/gilles',\n     'JOURNAL_STREAM': '9:24156',\n     'BROWSER': 'chromium',\n     'PYENV_VERSION': '3.6.6',\n     'PERL_MM_OPT': 'INSTALL_BASE=/home/alp/.local',\n     'LESS_TERMCAP_mb': '\\x1b[1m\\x1b[31m',\n     'LESS_TERMCAP_md': '\\x1b[1m\\x1b[31m',\n     'LESS_TERMCAP_me': '\\x1b[0m',\n     'MAIL_ACCOUNT': 'gillespilon.ca',\n     'PERL_LOCAL_LIB_ROOT': '/home/alp/.local',\n     'GTK_MODULES': 'canberra-gtk-module',\n     'MAIL': '/var/spool/mail/gilles',\n     'VISUAL': 'nvim',\n     'WINDOWPATH': '1',\n     'TERM': 'xterm-color',\n     'SHELL': '/usr/bin/zsh',\n     'PERL5LIB': '/home/gilles/.local/lib/perl5:/home/gilles/.local/lib/perl5:',\n     'PYENV_SHELL': 'zsh',\n     'XDG_SEAT': 'seat0',\n     'SHLVL': '3',\n     'MANPATH': '/home/gilles/.local/share/man:/home/gilles/.cabal/share/man:',\n     'WINDOWID': '56623105',\n     'LOGNAME': 'gilles',\n     'DBUS_SESSION_BUS_ADDRESS': 'unix:path=/run/user/1000/bus',\n     'XDG_RUNTIME_DIR': '/run/user/1000',\n     'XAUTHORITY': '/home/gilles/.Xauthority',\n     'LESS_TERMCAP_ue': '\\x1b[0m',\n     'LESS_TERMCAP_us': '\\x1b[1m\\x1b[32m',\n     'PATH': '/home/gilles/.pyenv/versions/3.6.6/bin:/home/gilles/.pyenv/versions/3.6.6/bin:/home/gilles/.pyenv/libexec:/home/gilles/.pyenv/plugins/python-build/bin:/home/gilles/.pyenv/plugins/pyenv-virtualenv/bin:/home/gilles/.pyenv/shims:/home/gilles/.rbenv/shims:/home/gilles/.cabal/bin:/home/gilles/.local/bin:/home/gilles/.pyenv/bin:/home/gilles/.rbenv/bin:/home/gilles/.npm-packages/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/lib/jvm/default/bin:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl:/opt/x-tools/bin:/opt/heroku/bin',\n     'SDL_VIDEO_FULLSCREEN_HEAD': '0',\n     'JPY_PARENT_PID': '17999',\n     'CLICOLOR': '1',\n     'GIT_PAGER': 'cat',\n     'MPLBACKEND': 'module://ipykernel.pylab.backend_inline'}\n\n\n\n\n```python\n# ! to run a shell command\n# For example, to see what version of pandas is installed\n!pip freeze | grep pandas\n```\n\n    pandas==0.23.4\r\n\n\n\n```python\n# Show matplotlib plots inline the notebook\n%matplotlib inline\n```\n\n\n```python\n# Upload code to pastebin and get the url returned\n#% pastebin 'file.py'\n```\n\n\n```python\n# Run the cell with bash in a subprocess\n```\n\n\n```bash\n%%bash\nfor i in {1..5}\ndo\n   echo \"i is $i\"\ndone\n```\n\n    i is 1\n    i is 2\n    i is 3\n    i is 4\n    i is 5\n\n\n\n```python\n# Time an evaluation\n%time\n```\n\n    CPU times: user 2 \u00b5s, sys: 0 ns, total: 2 \u00b5s\n    Wall time: 5.48 \u00b5s\n\n\n\n```python\n# Render cell contents as LaTex\n```\n\n\n```latex\n%%latex\n\\begin{align}\na = \\frac{i}{2} && b = \\frac{1}{3} && c = \\frac{1}{4} \\\\\na && b && c \\\\\n1 && 2 && 3\n\\end{align}\n```\n\n\n\\begin{align}\na = \\frac{i}{2} && b = \\frac{1}{3} && c = \\frac{1}{4} \\\\\na && b && c \\\\\n1 && 2 && 3\n\\end{align}\n\n\n\n```python\n%timeit x = range(10000)\n```\n\n    261 ns \u00b1 4.94 ns per loop (mean \u00b1 std. dev. of 7 runs, 1000000 loops each)\n\n\n\n```python\n# Render the cell as HTML\n```\n\n\n```python\n%%HTML\nJupyter Notebooks can render HTML</h1>\n```\n\n\nJupyter Notebooks can render HTML</h1>\n\n\n\n```python\nimport rpy2.ipython\n%load_ext rpy2.ipython\n```\n\n    /home/gilles/.pyenv/versions/3.6.6/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88\n      return f(*args, **kwds)\n\n\n\n```r\n%%R\nx <- runif(10)\ny <- runif(10)\n```\n\n\n```python\n%R plot(x, y)\n```\n\nYou can use %Rpush and %Rpull to move values back and forth between R and Python.\n\n\n```python\nimport numpy as np\nX = np.array([4.5,6.3,7.9])\nX.mean()\n```\n\n\n\n\n    6.233333333333334\n\n\n\n\n```python\n%Rpush X\n%R mean(X)\n```\n\n\n\n\n    array([6.23333333])\n\n\n\n## Batch, scheduling and reports\n\n\n```python\nimport pandas as pd\nimport folium\n```\n\n# References\n\nThis jupyter notebook is an exercise for me and is found in these URLs.\n\n[Advanced jupyter notebook tricks part](https://blog.dominodatalab.com/lesser-known-ways-of-using-notebooks/)\n\n[Building interactive dashboards with jupyter](https://blog.dominodatalab.com/interactive-dashboards-in-jupyter/)\n", "meta": {"hexsha": "3fba5e2952fd86780b5a8aaa9dd51e3560fd9b4e", "size": 22014, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "jupyter_tips/jupyter_tips.ipynb", "max_stars_repo_name": "gillespilon/jupyter", "max_stars_repo_head_hexsha": "c350ba7e9ba1dc68b3f06b410cc6aff70d47fa16", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jupyter_tips/jupyter_tips.ipynb", "max_issues_repo_name": "gillespilon/jupyter", "max_issues_repo_head_hexsha": "c350ba7e9ba1dc68b3f06b410cc6aff70d47fa16", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jupyter_tips/jupyter_tips.ipynb", "max_forks_repo_name": "gillespilon/jupyter", "max_forks_repo_head_hexsha": "c350ba7e9ba1dc68b3f06b410cc6aff70d47fa16", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0606060606, "max_line_length": 5867, "alphanum_fraction": 0.6285999818, "converted": true, "num_tokens": 2244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10669059394565118, "lm_q2_score": 0.05665242092798473, "lm_q1q2_score": 0.0060442804372657305}}
{"text": "# Treatment Wetlands Aeration Efficiency: A Review <a class=\"tocSkip\">\n\n***Just a import of libraries***\n\n\n```python\nimport pandas as pd\nimport datacompy\nimport plotly_express as px\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\n## Introduction\n\nThis jupyter notebook serves as complementary material for the paper Treatment Wetlands Aeration Efficiency: A review\n\n## Data search and preparation\n\n### Raw data search\n\nOn **web of science** search engine three queries were done to find the input articles for review. The search was set as such:\n1. **topic=\"treatment wetlands\" AND topic=\"aeration\"**\n2. **topic=\"treatment wetland\" AND topic=\"aeration\"**\n3. **topic=\"constructed wetlands\" AND topic=\"aeration\"**\n\nAt the first glance it seams obvious that queries for \"wetland\" and \"wetlands\" are the same, so the search query \"constructed wetland\" was omitted in this process. The similarity of the queries is tested further in this notebook.\n\nThe results were downloaded as text files for further analysis.\n\n**Date of the search was 14. 11. 2018**\n\n\n```python\n# importing the text files as pandas dataframes for futher processing\n\nquery_1 = pd.read_csv(\"data/raw/treatment-wetlands_aeration.txt\", sep=\"\\t\", header=0, index_col=False)\nquery_2 = pd.read_csv(\"data/raw/treatment-wetland_aeration.txt\", sep=\"\\t\", header=0, index_col=False)\nquery_3 = pd.read_csv(\"data/raw/constructed-wetlands_aeration.txt\", sep=\"\\t\", header=0, index_col=False)\n```\n\n\n```python\n# checking the table structure\n\nquery_1.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>PT</th>\n      <th>AU</th>\n      <th>BA</th>\n      <th>BE</th>\n      <th>GP</th>\n      <th>AF</th>\n      <th>BF</th>\n      <th>CA</th>\n      <th>TI</th>\n      <th>SO</th>\n      <th>...</th>\n      <th>PG</th>\n      <th>WC</th>\n      <th>SC</th>\n      <th>GA</th>\n      <th>UT</th>\n      <th>PM</th>\n      <th>OA</th>\n      <th>HC</th>\n      <th>HP</th>\n      <th>DA</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>J</td>\n      <td>Liu, FF; Fan, JL; Du, JH; Shi, X; Zhang, J; Sh...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>Liu, Fei-fei; Fan, Jinlin; Du, Jinhui; Shi, Xi...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>Intensified nitrogen transformation in intermi...</td>\n      <td>SCIENCE OF THE TOTAL ENVIRONMENT</td>\n      <td>...</td>\n      <td>8</td>\n      <td>Environmental Sciences</td>\n      <td>Environmental Sciences &amp; Ecology</td>\n      <td>GX6LB</td>\n      <td>WOS:000447871400115</td>\n      <td>30373064.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2018-11-14</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>J</td>\n      <td>Nivala, J; Kahl, S; Boog, J; van Afferden, M; ...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>Nivala, Jaime; Kahl, Stefanie; Boog, Johannes;...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>Dynamics of emerging organic contaminant remov...</td>\n      <td>SCIENCE OF THE TOTAL ENVIRONMENT</td>\n      <td>...</td>\n      <td>13</td>\n      <td>Environmental Sciences</td>\n      <td>Environmental Sciences &amp; Ecology</td>\n      <td>GV4NL</td>\n      <td>WOS:000446076500109</td>\n      <td>30308886.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2018-11-14</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>J</td>\n      <td>Masi, F; Rizzo, A; Bresciani, R; Martinuzzi, N...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>Masi, F.; Rizzo, A.; Bresciani, R.; Martinuzzi...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>Lessons learnt from a pilot study on residual ...</td>\n      <td>SCIENCE OF THE TOTAL ENVIRONMENT</td>\n      <td>...</td>\n      <td>9</td>\n      <td>Environmental Sciences</td>\n      <td>Environmental Sciences &amp; Ecology</td>\n      <td>GX5QQ</td>\n      <td>WOS:000447805500015</td>\n      <td>30114585.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2018-11-14</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>J</td>\n      <td>Turker, OC</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>Turker, Onur Can</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>Simultaneous boron (B) removal and electricity...</td>\n      <td>JOURNAL OF ENVIRONMENTAL MANAGEMENT</td>\n      <td>...</td>\n      <td>12</td>\n      <td>Environmental Sciences</td>\n      <td>Environmental Sciences &amp; Ecology</td>\n      <td>GY0PX</td>\n      <td>WOS:000448224900003</td>\n      <td>30212671.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2018-11-14</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>J</td>\n      <td>Song, P; Huang, GH; An, CJ; Shen, J; Zhang, P;...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>Song, Pei; Huang, Guohe; An, Chunjiang; Shen, ...</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>Treatment of rural domestic wastewater using m...</td>\n      <td>SCIENCE OF THE TOTAL ENVIRONMENT</td>\n      <td>...</td>\n      <td>11</td>\n      <td>Environmental Sciences</td>\n      <td>Environmental Sciences &amp; Ecology</td>\n      <td>GU3GG</td>\n      <td>WOS:000445164000056</td>\n      <td>29990903.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>2018-11-14</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 68 columns</p>\n</div>\n\n\n\n***Now we will test if query with term \"constructed wetlands\" is similar to the query with the term \"constructed wetland\"***\n\n\n```python\n# testing the similarity between query_1 and query_2 (search 1 and 2)\n\nquery_1.equals(query_2)\n```\n\n\n\n\n    True\n\n\n\n**As we can see the two terms generate equal output so we can omitt the query_2 dataset in further processing**\n\n### Comparing the search terms\n\nWe have two datasets from searching the terms \"constructed wetlands\" or \"treatment wetlands\" and \"aeration\" with similar number of datapoints (rows in the table).\n\n\n```python\nprint(\"The number of rows for search term 'constructed wetlands' is: %d\" % len(query_1))\nprint(\"The number of rows for search term 'treatment wetlands' is: %d\" %len(query_3))\n```\n\n    The number of rows for search term 'constructed wetlands' is: 444\n    The number of rows for search term 'treatment wetlands' is: 465\n\n\nAre these dataset similar also in the content?\n\n\n```python\ncompare = datacompy.Compare(query_1, query_3, join_columns='GA', df1_name='TW', df2_name='CW')\n#print(compare.report())\n```\n\n**We can see from the report that both datasets has 379 common rows and query_1 (CW) has 65 unique rows whereas query_3 (TW) has 86 unique rows.** \n\n### Joining and cleaning the dataset\n\nWe will now make a join with droping the duplicate rows and preserving the unique rows.\n\n\n```python\ncw_tw_join = pd.concat([query_1, query_3]).drop_duplicates().reset_index(drop=True)\nprint(\"The number of rows in joined dataset is: %d\" %len(cw_tw_join))\n```\n\n    The number of rows in joined dataset is: 535\n\n\nWe will also drop unuseful columns from the dataset. (The whole list of Web of Science Core Collection Field Tags (what means the columns names abbreviations) can be found [here](https://images.webofknowledge.com/images/help/WOK/hs_wos_fieldtags.html))\n\n\n```python\ncw_tw = cw_tw_join.loc[:, ['au', 'ti', 'de', 'so', 'di']]\ndf_shape = cw_tw.shape\n\nprint(\"Final dataset with all unique datapoints\" \n      + \"for search terms 'constructed wetlands'\" \n      + \"or 'treatment wetlands' and 'aeration'\"\n      + \"now contains %d rows and %d columns\" % (df_shape[0], df_shape[1])\n     )\n```\n\n    Final dataset with all unique datapointsfor search terms 'constructed wetlands'or 'treatment wetlands' and 'aeration'now contains 535 rows and 5 columns\n\n\n\n```python\n# First five rows of the dataset\n\ncw_tw.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>au</th>\n      <th>ti</th>\n      <th>de</th>\n      <th>so</th>\n      <th>di</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Liu, FF; Fan, JL; Du, JH; Shi, X; Zhang, J; Sh...</td>\n      <td>Intensified nitrogen transformation in intermi...</td>\n      <td>Constructed wetlands; Intermittent aeration; C...</td>\n      <td>SCIENCE OF THE TOTAL ENVIRONMENT</td>\n      <td>10.1016/j.scitotenv.2018.10.037</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Nivala, J; Kahl, S; Boog, J; van Afferden, M; ...</td>\n      <td>Dynamics of emerging organic contaminant remov...</td>\n      <td>Aeration; Constructed wetland; Micropollutant;...</td>\n      <td>SCIENCE OF THE TOTAL ENVIRONMENT</td>\n      <td>10.1016/j.scitotenv.2018.08.339</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Masi, F; Rizzo, A; Bresciani, R; Martinuzzi, N...</td>\n      <td>Lessons learnt from a pilot study on residual ...</td>\n      <td>Constructed wetland; Treatment wetland; Aerate...</td>\n      <td>SCIENCE OF THE TOTAL ENVIRONMENT</td>\n      <td>10.1016/j.scitotenv.2018.08.113</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Turker, OC</td>\n      <td>Simultaneous boron (B) removal and electricity...</td>\n      <td>Water treatment; Duckweed wastewater treatment...</td>\n      <td>JOURNAL OF ENVIRONMENTAL MANAGEMENT</td>\n      <td>10.1016/j.jenvman.2018.08.112</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Song, P; Huang, GH; An, CJ; Shen, J; Zhang, P;...</td>\n      <td>Treatment of rural domestic wastewater using m...</td>\n      <td>Rural wastewater; Multi-soil-layering system; ...</td>\n      <td>SCIENCE OF THE TOTAL ENVIRONMENT</td>\n      <td>10.1016/j.scitotenv.2018.06.331</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nWe will rename the columns and export the raw dataset to csv file.\n\n\n```python\ncw_tw.columns = [\"authors\", \"title\", \"keywords\", \"periodical\", \"id\"]\n```\n\nand export this dataset as csv file\n\n\n```python\n# cw_tw.to_csv(\"data/intermediate/cleaned_raw_papers.csv\", index=False)\n```\n\n### Selecting papers for further manual inspection\n\nWe will now try to narrow the final dataset even more. After inspecting several rows (or better say articles) we can see that they are from the field of constructed/treatment wetlands but they do not contain any information on topic of wetland aeration. The inspection of titles and keywords of all articles can help us to drop such articles from the dataset.\n\nBecause the topic of \"aeration\" can be expressed in several forms (like e.g aeration versus aerated), we will only search if the title or the keywords contains the string ***\"aer\"*** to include all possible forms being used.\n\n\n```python\n# importing the cleaned raw datafile\nall_papers = pd.read_csv(\"data/intermediate/cleaned_raw_papers.csv\")\nall_papers.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>authors</th>\n      <th>title</th>\n      <th>keywords</th>\n      <th>periodical</th>\n      <th>id</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Liu, FF; Fan, JL; Du, JH; Shi, X; Zhang, J; Sh...</td>\n      <td>Intensified nitrogen transformation in intermi...</td>\n      <td>Constructed wetlands; Intermittent aeration; C...</td>\n      <td>SCIENCE OF THE TOTAL ENVIRONMENT</td>\n      <td>10.1016/j.scitotenv.2018.10.037</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Nivala, J; Kahl, S; Boog, J; van Afferden, M; ...</td>\n      <td>Dynamics of emerging organic contaminant remov...</td>\n      <td>Aeration; Constructed wetland; Micropollutant;...</td>\n      <td>SCIENCE OF THE TOTAL ENVIRONMENT</td>\n      <td>10.1016/j.scitotenv.2018.08.339</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Masi, F; Rizzo, A; Bresciani, R; Martinuzzi, N...</td>\n      <td>Lessons learnt from a pilot study on residual ...</td>\n      <td>Constructed wetland; Treatment wetland; Aerate...</td>\n      <td>SCIENCE OF THE TOTAL ENVIRONMENT</td>\n      <td>10.1016/j.scitotenv.2018.08.113</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Turker, OC</td>\n      <td>Simultaneous boron (B) removal and electricity...</td>\n      <td>Water treatment; Duckweed wastewater treatment...</td>\n      <td>JOURNAL OF ENVIRONMENTAL MANAGEMENT</td>\n      <td>10.1016/j.jenvman.2018.08.112</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Song, P; Huang, GH; An, CJ; Shen, J; Zhang, P;...</td>\n      <td>Treatment of rural domestic wastewater using m...</td>\n      <td>Rural wastewater; Multi-soil-layering system; ...</td>\n      <td>SCIENCE OF THE TOTAL ENVIRONMENT</td>\n      <td>10.1016/j.scitotenv.2018.06.331</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# defining the search term\nword = \"aer\"\n\n# building the filters\n# filtering titles and keywords which contains 'aer' and building new columns with True / False values\ncw_tw['title_filter'] = cw_tw['title'].str.contains(word) \ncw_tw['keywords_filter'] = cw_tw['keywords'].str.contains(word)\ncw_tw['filter'] = cw_tw['title_filter'] + cw_tw['keywords_filter']\n```\n\n\n```python\n# filtering the raw dataset\nfiltered_dataset = cw_tw[cw_tw['filter'] > 0]\n\nprint(\"The number of rows in final dataset is: %d\" %len(filtered_dataset))\n```\n\n    The number of rows in final dataset is: 205\n\n\nWe will also export this dataset to the csv file\n\n\n```python\nfiltered_dataset = filtered_dataset.drop([\"title_filter\", \"keywords_filter\", \"filter\"], axis=1)\n\n# filtered_dataset.to_csv(\"data/intermediate/final_set_of_papers.csv\", index=False)\n```\n\n**After this preparation there is no other way than to screen all the selected articles manually, if their topic is really about wetland active (or forced) aeration (because we can expect there will be also a lot of articles about passive aeration of wetlands).**\n\nYou can find the manually prescreened (which means they are somehow connected to our article topic) list of papers (counting 141 papers) in the intermediate data folder in [word file](files/data/intermediate/prescreened_papers.docx) or in [txt format](files/data/intermediate/prescreened_papers.txt).\n\n## Final Dataset\n\nThe prescreened dataset of papers (references) was supplemented with the full versions of articles (in pdf available on request). For the paper to be included in the review three criteria had to be met. The paper had to include:\n\n1. Sufficient information on the active aeration of the wetland (at least the daily aeration time and the air flow rate), \n2. Inflow and outflow concentrations for COD, BOD or CBOD and TKN or NH4\u2212N and\n3. data for the experimental wetland such as dimensions, hydraulic retention time, hydraulic load and other data necessary for the calculations within the study. \n\n**Based on these criteria only 21 research articles were processed further in the review.**\n\n###  Basic statictical description of main parameters\n\n\n```python\npaper_list = pd.read_excel('data/raw/papers_final_list.xlsx', index_col=0)\npaper_list\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Citation</th>\n      <th>Type of WW</th>\n      <th>Size</th>\n      <th>Flow Type</th>\n      <th>Feeding</th>\n      <th>Aeration placement</th>\n      <th>Aeration elements</th>\n    </tr>\n    <tr>\n      <th>No</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>(Araya et al., 2016)</td>\n      <td>pretreated municipal</td>\n      <td>lab-scale</td>\n      <td>vertical</td>\n      <td>batch-filled</td>\n      <td>bottom</td>\n      <td>unknown</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>(Auvinen et al., 2017)</td>\n      <td>mun. and hospital</td>\n      <td>pilot-scale</td>\n      <td>vertical</td>\n      <td>continuous</td>\n      <td>bottom</td>\n      <td>perforated pipe in spiral</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>(Boog et al., 2014)</td>\n      <td>pretreated domestic</td>\n      <td>pilot-scale</td>\n      <td>horizontal</td>\n      <td>intermittent</td>\n      <td>bottom</td>\n      <td>perforated pipes (FBA)</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>(Butterworth et al., 2013)</td>\n      <td>tertiary municipal</td>\n      <td>full-scale</td>\n      <td>horizontal</td>\n      <td>continuous</td>\n      <td>bottom</td>\n      <td>perforated pipes (FBA)</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>(Fan et al., 2013a)</td>\n      <td>synthetic</td>\n      <td>lab-scale</td>\n      <td>vertical</td>\n      <td>batch-filled</td>\n      <td>bottom</td>\n      <td>porous air spargers</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>(Fan et al., 2013b)</td>\n      <td>synthetic</td>\n      <td>lab-scale</td>\n      <td>vertical</td>\n      <td>batch-filled</td>\n      <td>bottom</td>\n      <td>porous air spargers</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>(Fan et al., 2013c)</td>\n      <td>synthetic</td>\n      <td>pilot-scale</td>\n      <td>horizontal</td>\n      <td>continuous</td>\n      <td>bottom-front</td>\n      <td>quadrate tubing</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>(Foladori et al., 2013)</td>\n      <td>pretreated domestic</td>\n      <td>mesocosm</td>\n      <td>vertical</td>\n      <td>intermittent</td>\n      <td>bottom</td>\n      <td>perforated pipes</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>(Maltais-Landry et al., 2007)</td>\n      <td>fish farm effluent</td>\n      <td>mesocosm</td>\n      <td>horizontal</td>\n      <td>continuous</td>\n      <td>bottom-front</td>\n      <td>cicular tubing</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>(Nivala et al., 2007)</td>\n      <td>landfill leachate</td>\n      <td>pilot-scale</td>\n      <td>horizontal</td>\n      <td>continuous</td>\n      <td>bottom</td>\n      <td>perforated pipes (FBA)</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>(Ouellet-Plamondon et al., 2006)</td>\n      <td>fish farm effluent</td>\n      <td>mesocosm</td>\n      <td>horizontal</td>\n      <td>continuous</td>\n      <td>bottom-front</td>\n      <td>cicular tubing</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>(Pan et al., 2012)</td>\n      <td>low strenght mucipial</td>\n      <td>full-scale</td>\n      <td>vertical</td>\n      <td>continuous</td>\n      <td>bottom</td>\n      <td>perforated pipes</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>(Patil and Chakraborty, 2017)</td>\n      <td>synthetic</td>\n      <td>lab-scale</td>\n      <td>horizontal</td>\n      <td>continuous</td>\n      <td>bottom-middle</td>\n      <td>unknown</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>(Redmond et al., 2014)</td>\n      <td>pretreated municipal</td>\n      <td>pilot-scale</td>\n      <td>horizontal</td>\n      <td>intermittent</td>\n      <td>bottom</td>\n      <td>perforated pipes (FBA)</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>(Uggetti et al., 2016)</td>\n      <td>pretreated municipal</td>\n      <td>pilot-scale</td>\n      <td>horizontal</td>\n      <td>intermittent</td>\n      <td>bottom</td>\n      <td>perforated pipes</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>(Wu et al., 2015)</td>\n      <td>synthetic</td>\n      <td>lab-scale</td>\n      <td>vertical</td>\n      <td>batch-filled</td>\n      <td>bottom</td>\n      <td>porous air spargers</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>(Wu et al., 2016a)</td>\n      <td>synthetic</td>\n      <td>lab-scale</td>\n      <td>vertical</td>\n      <td>batch-filled</td>\n      <td>bottom</td>\n      <td>porous air spargers</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>(Wu et al., 2016b)</td>\n      <td>synthetic</td>\n      <td>lab-scale</td>\n      <td>vertical</td>\n      <td>batch-filled</td>\n      <td>bottom</td>\n      <td>porous air spargers</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>(Zapater-Pereyra et al., 2014)</td>\n      <td>pretreated municipal</td>\n      <td>lab-scale</td>\n      <td>horizontal</td>\n      <td>continuous</td>\n      <td>bottom</td>\n      <td>aeration tubings</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>(Zhong et al., 2015)</td>\n      <td>pretreated municipal</td>\n      <td>mesocosm</td>\n      <td>horizontal</td>\n      <td>continuous</td>\n      <td>inflow chamber</td>\n      <td>unknown</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>(Zhou et al., 2017)</td>\n      <td>synthetic</td>\n      <td>lab-scale</td>\n      <td>HTS</td>\n      <td>batch-filled</td>\n      <td>bottom</td>\n      <td>porous air spargers</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nData from these articles were extracted as individual \"review cases\". We can find several different review cases in some articles (experiments with different parameters) so the total number of the review cases is 49. \n\n\n```python\nreview_cases = pd.read_excel('data/raw/review_cases.xlsx')\n# print(review_cases)\n```\n\nThe review cases are number as such that number refers to the article number in the table (list) of papers and the 'a, b, c, etc.' distinguish the individual review cases identified in that article.\n\n\n```python\nreview_cases[['water_depth_m', 'HLR_lit_m2d', 'OLR_gCOD_m2d']].describe()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>water_depth_m</th>\n      <th>HLR_lit_m2d</th>\n      <th>OLR_gCOD_m2d</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>49.000000</td>\n      <td>49.000000</td>\n      <td>49.000000</td>\n    </tr>\n    <tr>\n      <th>mean</th>\n      <td>0.532449</td>\n      <td>121.140722</td>\n      <td>29.973675</td>\n    </tr>\n    <tr>\n      <th>std</th>\n      <td>0.274949</td>\n      <td>242.925088</td>\n      <td>31.172179</td>\n    </tr>\n    <tr>\n      <th>min</th>\n      <td>0.150000</td>\n      <td>4.000000</td>\n      <td>2.510200</td>\n    </tr>\n    <tr>\n      <th>25%</th>\n      <td>0.300000</td>\n      <td>44.600000</td>\n      <td>9.000000</td>\n    </tr>\n    <tr>\n      <th>50%</th>\n      <td>0.600000</td>\n      <td>64.000000</td>\n      <td>26.885000</td>\n    </tr>\n    <tr>\n      <th>75%</th>\n      <td>0.650000</td>\n      <td>95.000000</td>\n      <td>31.072190</td>\n    </tr>\n    <tr>\n      <th>max</th>\n      <td>1.700000</td>\n      <td>1600.000000</td>\n      <td>150.960000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThere seems to be some substantial difference in the data, especially for hydraulic loading rate. We can try to plot the data to see if these differences are only due to some specific review cases.\n\n\n```python\nfig = plt.figure()\nax1 = fig.add_subplot(1, 2, 1)\nax2 = fig.add_subplot(1, 2, 2)\nreview_cases[['HLR_lit_m2d']].plot(kind='hist',rwidth=0.8, bins=16, ax=ax1, figsize=(15, 5))\nreview_cases[['OLR_gCOD_m2d']].plot(kind='hist',rwidth=0.8, ax=ax2, bins=15, figsize=(15, 5))\nplt.show()\n```\n\nAccording to the histograms we can clearly see that the majority of the review cases has hydraulic loading below 100 liters par day and ORL below 30 gCOD/day.\n\n\n```python\nfig = plt.figure()\nax1 = fig.add_subplot(1, 2, 1)\nax2 = fig.add_subplot(1, 2, 2)\nreview_cases[['HLR_lit_m2d']].plot(kind='box', ax=ax1, figsize=(15, 5), grid=True, ylim=(0, 200))\nreview_cases[['OLR_gCOD_m2d']].plot(kind='box', ax=ax2, figsize=(15, 5), grid=True, ylim=(0, 80))\nplt.show()\n```\n\n### Data Analysis\n\n#### Oxygen consumption rates\n\n##### Methodology\n\nOxygen consumption rate is defined here similar to the definition of Kadlec and Wallace (2009) and is expressed as anticipated rate of oxygen consumption in a treatment wetland due to various microbial processes. For processes including the organic carbon the COD or CBOD parameters are being used and the respective quations differs accordingly (see below). For nitrification and other pathways of N-forms reduction the parameter TKN is used where possible. If not the NH4-N is used instead without changing the respective equations.\n\n_All rates are calculated in a volumetric as well as areal aproach (the rate is not defined per per volume unit or areal)._\n\nOCR calculation for review cases with COD parameter.\n\n\\begin{equation}\\label{eq:1}\nOCR_{max-COD-V} = \\frac{[1(\\Delta M_{COD} + 4.6(\\Delta M_{TKN})]}{V}\n\\end{equation}\n\n\\begin{equation}\\label{eq:2}\nOCR_{int-COD-V} = \\frac{[0.5(\\Delta M_{COD} + 1.7(\\Delta M_{TKN})]}{V}\n\\end{equation}\n\n\\begin{equation}\\label{eq:3}\nOCR_{min} = \\frac{[1.7(\\Delta M_{TKN})]}{V}\n\\end{equation}\n\nOCR calculation for review cases with CBOD parameter.\n\n\\begin{equation}\\label{eq:4}\nOCR_{max-CBOD-V} = \\frac{[1.5(\\Delta M_{CBOD} + 4.6(\\Delta M_{TKN})]}{V}\n\\end{equation}\n\n\\begin{equation}\\label{eq:5}\nOCR_{int-CBOD-V} = \\frac{[1(\\Delta M_{CBOD} + 1.7(\\Delta M_{TKN})]}{V}\n\\end{equation}\n\n\\begin{equation}\\label{eq:6}\nOCR_{min} = \\frac{[1.7(\\Delta M_{TKN})]}{V}\n\\end{equation}\n\n$\\Delta M$ is always as:\n\n\\begin{equation}\\label{eq:7}\n\\Delta M =  Q_i \\times C_i - Q_0 \\times C_0\n\\end{equation}\n\n<i>V</i> - volume of wetland (m3), <i>M</i> - pollutant mass flow rate (g/d), <i>Q<sub>i</sub></i> - inflow Rate (m3/d), *Q<sub>o</sub>* - outflow rate (m3/d); *C<sub>i</sub>* - inlet concentration, (g/m3), *C<sub>o</sub>* - outlet concentration (g.m3), OCR - oxygen consumption rate (g/m2.d). *V* can be changed for *A* - wetalnd area (m2) for areal rate calculation.\n\nIn our table with all review cases we have these columns already defined:\n- <mark>area_m2</mark> - wetland area in square meters\n- <mark>volume_m3</mark> - wetted volume of the wetland (so not the total volume, but area x depth of water)\n- <mark>daily_flow_lit</mark> - daily flow in liters\n- <mark>CBOD_IN</mark> - inflow concentration for CBOD in mg per liter\n- <mark>CBOD_OUT</mark> - outflow concentration for CBOD in mg per liter\n- <mark>deltaCBOD</mark> - difference between inflow an outflow concetration in mg per liter\n- columns for COD, TKN and NH4 are defined ni similar manner\n\n\n```python\nreview_cases.columns\n```\n\n\n\n\n    Index(['Reference', 'number', 'water_depth_m', 'area_m2', 'volume_m3',\n           'porosity', 'voids_m3', 'HLR_lit_m2d', 'daily_flow_lit', 'OLR_gCOD_m2d',\n           'HRT_h', 'HRT_days', 'air_flow_m3h', 'aer_duration_h_day',\n           'air_per_day_m3', 'air_per_HRT_m3', 'COD_IN', 'COD_OUT', 'deltaCOD',\n           'CBOD_IN', 'CBOD_OUT', 'deltaCBOD', 'TKN_IN', 'TKN_OUT', 'deltaTKN',\n           'NH4_IN', 'NH4_OUT', 'deltaNH4'],\n          dtype='object')\n\n\n\nAs the inflow and outflow volume is still the same ((in liters)) and mg/l are same as g/m3 we can compute the $\\Delta M$ form equation 7 directly as $Q_d \\times 0.001 \\times \\Delta C  $\n\nWith the help of for loop we than calculate the oxygen consumption rates in both volumetric and areal form.\n\n\n```python\n# checking for missing COD and TKN values\nCOD_nan = review_cases['deltaCOD'].notnull()\nTKN_nan = review_cases['deltaTKN'].notnull()\n\n# adding blank columns for volumetric and areal OCR values before calculation  \npd.concat([review_cases, \n           pd.DataFrame(columns = ['OCR_max_v',\n                                   'OCR_int_v',\n                                   'OCR_min_v',\n                                   'OCR_max_a',\n                                   'OCR_int_a',\n                                   'OCR_min_a'\n                                  ])])\n\nfor i in range(0, len(review_cases)):\n    \n    # daily flow and volume is the same whatever conc parameters are used\n    daily_flow = review_cases.loc[i, 'daily_flow_lit']\n    volume = review_cases.loc[i, 'volume_m3']\n    area = review_cases.loc[i, 'area_m2']\n    \n    # calculation for COD values\n    if COD_nan[i] == True:\n        deltaCOD = review_cases.loc[i, 'deltaCOD']\n        \n        M_COD = daily_flow * 0.001 * deltaCOD\n        \n        if TKN_nan[i] == True:\n            deltaTKN = review_cases.loc[i, 'deltaTKN']\n        else:\n            deltaTKN = review_cases.loc[i, 'deltaNH4']\n        \n        M_TKN = daily_flow * 0.001 * deltaTKN\n        \n        # volumetric OCR values\n        OCR_max_v = ((1 * M_COD) + (4.6 * M_TKN)) / volume\n        OCR_int_v = ((0.5 * M_COD) + (1.7 * M_TKN)) / volume\n        OCR_min_v = (1.7 * M_TKN) / volume\n\n        # areal OCR values\n        OCR_max_a = ((1 * M_COD) + (4.6 * M_TKN)) / area\n        OCR_int_a = ((0.5 * M_COD) + (1.7 * M_TKN)) / area\n        OCR_min_a = (1.7 * M_TKN) / area\n        \n    # calculation for CBOD values\n    else:\n        deltaCBOD = review_cases.loc[i, 'deltaCBOD']\n        \n        M_CBOD = daily_flow * 0.001 * deltaCBOD\n        \n        if TKN_nan[i] == True:\n            deltaTKN = review_cases.loc[i, 'deltaTKN']\n        else:\n            deltaTKN = review_cases.loc[i, 'deltaNH4']\n        \n        M_TKN = daily_flow * 0.001 * deltaTKN\n        \n        # volumetric OCR values\n        OCR_max_v = ((1.5 * M_CBOD) + (4.6 * M_TKN)) / volume\n        OCR_int_v = ((1 * M_CBOD) + (1.7 * M_TKN)) / volume\n        OCR_min_v = (1.7 * M_TKN) / volume\n\n        # areal OCR values\n        OCR_max_a = ((1.5 * M_CBOD) + (4.6 * M_TKN)) / area\n        OCR_int_a = ((1 * M_CBOD) + (1.7 * M_TKN)) / area\n        OCR_min_a = (1.7 * M_TKN) / area\n    \n    # writing the values to the dataframe\n    review_cases.loc[i, 'OCR_max_v'] = OCR_max_v\n    review_cases.loc[i, 'OCR_int_v'] = OCR_int_v\n    review_cases.loc[i, 'OCR_min_v'] = OCR_min_v\n    review_cases.loc[i, 'OCR_max_a'] = OCR_max_a\n    review_cases.loc[i, 'OCR_int_a'] = OCR_int_a\n    review_cases.loc[i, 'OCR_min_a'] = OCR_min_v\n```\n\n    c:\\users\\dell\\.virtualenvs\\aerationreview-wzvxscyu\\lib\\site-packages\\ipykernel_launcher.py:12: FutureWarning:\n    \n    Sorting because non-concatenation axis is not aligned. A future version\n    of pandas will change to not sort by default.\n    \n    To accept the future behavior, pass 'sort=False'.\n    \n    To retain the current behavior and silence the warning, pass 'sort=True'.\n    \n    \n\n\n\n```python\nreview_cases.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Reference</th>\n      <th>number</th>\n      <th>water_depth_m</th>\n      <th>area_m2</th>\n      <th>volume_m3</th>\n      <th>porosity</th>\n      <th>voids_m3</th>\n      <th>HLR_lit_m2d</th>\n      <th>daily_flow_lit</th>\n      <th>OLR_gCOD_m2d</th>\n      <th>...</th>\n      <th>deltaTKN</th>\n      <th>NH4_IN</th>\n      <th>NH4_OUT</th>\n      <th>deltaNH4</th>\n      <th>OCR_max_v</th>\n      <th>OCR_int_v</th>\n      <th>OCR_min_v</th>\n      <th>OCR_max_a</th>\n      <th>OCR_int_a</th>\n      <th>OCR_min_a</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>(Araya et al., 2016)</td>\n      <td>1a</td>\n      <td>0.15</td>\n      <td>0.063</td>\n      <td>0.00945</td>\n      <td>NaN</td>\n      <td>0.001417</td>\n      <td>15.873016</td>\n      <td>1.0</td>\n      <td>4.444444</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>114.0</td>\n      <td>27.36</td>\n      <td>86.64</td>\n      <td>61.433228</td>\n      <td>25.215661</td>\n      <td>15.586032</td>\n      <td>9.214984</td>\n      <td>3.782349</td>\n      <td>15.586032</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>(Araya et al., 2016)</td>\n      <td>1b</td>\n      <td>0.15</td>\n      <td>0.063</td>\n      <td>0.00945</td>\n      <td>NaN</td>\n      <td>0.001417</td>\n      <td>15.873016</td>\n      <td>1.0</td>\n      <td>6.317460</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>112.0</td>\n      <td>72.80</td>\n      <td>39.20</td>\n      <td>44.351323</td>\n      <td>19.686772</td>\n      <td>7.051852</td>\n      <td>6.652698</td>\n      <td>2.953016</td>\n      <td>7.051852</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>(Araya et al., 2016)</td>\n      <td>1c</td>\n      <td>0.15</td>\n      <td>0.063</td>\n      <td>0.00945</td>\n      <td>NaN</td>\n      <td>0.001417</td>\n      <td>15.873016</td>\n      <td>1.0</td>\n      <td>5.396825</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>54.0</td>\n      <td>11.34</td>\n      <td>42.66</td>\n      <td>47.390053</td>\n      <td>20.986455</td>\n      <td>7.674286</td>\n      <td>7.108508</td>\n      <td>3.147968</td>\n      <td>7.674286</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>(Auvinen et al., 2017)</td>\n      <td>2a</td>\n      <td>0.75</td>\n      <td>1.000</td>\n      <td>0.75000</td>\n      <td>0.4</td>\n      <td>0.300000</td>\n      <td>360.000000</td>\n      <td>360.0</td>\n      <td>60.480000</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>24.0</td>\n      <td>0.00</td>\n      <td>24.00</td>\n      <td>121.152000</td>\n      <td>53.664000</td>\n      <td>19.584000</td>\n      <td>90.864000</td>\n      <td>40.248000</td>\n      <td>19.584000</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>(Auvinen et al., 2017)</td>\n      <td>2b</td>\n      <td>0.75</td>\n      <td>1.000</td>\n      <td>0.75000</td>\n      <td>0.4</td>\n      <td>0.300000</td>\n      <td>680.000000</td>\n      <td>680.0</td>\n      <td>150.960000</td>\n      <td>...</td>\n      <td>NaN</td>\n      <td>33.0</td>\n      <td>5.60</td>\n      <td>27.40</td>\n      <td>289.262933</td>\n      <td>129.725867</td>\n      <td>42.232533</td>\n      <td>216.947200</td>\n      <td>97.294400</td>\n      <td>42.232533</td>\n    </tr>\n  </tbody>\n</table>\n<p>5 rows \u00d7 34 columns</p>\n</div>\n\n\n\n##### Oxygen Consumption rate results\n\n\n```python\nr_col = ['OCR_max_v', 'OCR_int_v', 'OCR_min_v', 'OCR_max_a', 'OCR_int_a', 'OCR_min_a']\n\nfor col in r_col:\n    avg = review_cases[col].mean()\n    median = review_cases[col].median()\n    min_v = review_cases[col].min()\n    max_v = review_cases[col].max()\n    \n    if \"max\" in col:\n        add = \" maximum \"\n    elif \"int\" in col:\n        add = \" intermediate \"\n    else:\n        add = \" minimum \"\n    \n    if \"v\" in col:\n        print(\"For\" + add + \"volumetric oxygen consumption rate the:\")\n    else:\n        print(\"For\" + add + \"areal oxygen consumption rate the:\")\n        \n    print(\"- Average value is %0.2f and median value is %0.2f g/day.\" % (avg, median))\n    print(\"- Minimum value is %0.2f and maximum is %0.2f g/day.\" % (min_v, max_v))\n    print(\"\")\n```\n\n    For maximum volumetric oxygen consumption rate the:\n    - Average value is 78.50 and median value is 59.24 g/day.\n    - Minimum value is 8.91 and maximum is 419.77 g/day.\n    \n    For intermediate volumetric oxygen consumption rate the:\n    - Average value is 36.00 and median value is 27.29 g/day.\n    - Minimum value is 4.10 and maximum is 188.28 g/day.\n    \n    For minimum volumetric oxygen consumption rate the:\n    - Average value is 10.20 and median value is 6.84 g/day.\n    - Minimum value is 1.01 and maximum is 61.22 g/day.\n    \n    For maximum areal oxygen consumption rate the:\n    - Average value is 41.55 and median value is 33.76 g/day.\n    - Minimum value is 3.38 and maximum is 216.95 g/day.\n    \n    For intermediate areal oxygen consumption rate the:\n    - Average value is 19.13 and median value is 15.98 g/day.\n    - Minimum value is 1.56 and maximum is 97.29 g/day.\n    \n    For minimum areal oxygen consumption rate the:\n    - Average value is 10.20 and median value is 6.84 g/day.\n    - Minimum value is 1.01 and maximum is 61.22 g/day.\n    \n\n\n**Oxygen consumption rate versus organic loading**\n\n\n```python\nfig = plt.figure()\nax1 = fig.add_subplot(1, 2, 1)\nax2 = fig.add_subplot(1, 2, 2)\nfnt=14\nlabelpad=10\nreview_cases.plot(kind='scatter', x='OCR_int_v', y='OLR_gCOD_m2d', ax=ax1, figsize=(15, 5), grid=True)\nreview_cases.plot(kind='scatter', x='OLR_gCOD_m2d', y='OCR_int_a', ax=ax2, figsize=(15, 5), grid=True)\nax1.set_xlabel('Volumetric OCR (g/m3.d)', fontsize=fnt, labelpad=labelpad)\nax2.set_xlabel('Areal OCR (g/m3.d)', fontsize=fnt, labelpad=labelpad)\nax1.set_ylabel('OLR (gCOD/m2.d)', fontsize=fnt, labelpad=labelpad)\nax2.set_ylabel('', fontsize=fnt, labelpad=labelpad)\nax1.set_title('Organic loading rate versus volumetric OCR', fontsize=fnt, pad=labelpad)\nax2.set_title('Organic loading rate versus areal OCR', fontsize=fnt, pad=labelpad)\nplt.show()\n```\n\n**Oxygen consumption rate versus hydraulic loading**\n\n\n```python\nfig = plt.figure()\nax1 = fig.add_subplot(1, 2, 1)\nax2 = fig.add_subplot(1, 2, 2)\nfnt=16\nlabelpad=10\nreview_cases.plot(kind='scatter', x='HLR_lit_m2d', y='OCR_int_v', ax=ax1, figsize=(15, 10), grid=True,\n                 title='Hydraulic loading rate versus volumetric OCR', fontsize=fnt)\nreview_cases.plot(kind='scatter', x='HLR_lit_m2d', y='OCR_int_a', ax=ax2, figsize=(15, 10), grid=True,\n                 title='Hydraulic loading rate versus areal OCR', fontsize=fnt)\nax1.set_xlabel('Hydraulic loading rate (liters/m2.d)', fontsize=fnt, labelpad=labelpad)\nax2.set_xlabel('Hydraulic loading rate (liters/m2.d)', fontsize=fnt, labelpad=labelpad)\nax1.set_ylabel('Volumetric Oxygen consumption rate (g/d)', fontsize=fnt, labelpad=labelpad)\nax2.set_ylabel('Areal Oxygen consumption rate (g/d)', fontsize=fnt, labelpad=labelpad)\nplt.show()\n```\n\n#### Oxygen consumption during HRT\n\n##### Methodology\n\nOxygen consumption (OC) is calculated similar as the oxygen consumption rate. The main difference is that the oxygen consumption is not defined as rate (per unit of area / volume), but as a total oxygen consumption for a give hydraulic retention time. In other words - how much oxygen is theoretically consumed by microbial processes in the time when the wastewater enters the system till the time the water exits the system.\n\nOC calculation for review cases with COD parameter.\n\n\\begin{equation}\\label{eq:8}\nOC_(max) = 1(\\Delta m_{COD} + 4.6(\\Delta m_{TKN})\n\\end{equation}\n\n\\begin{equation}\\label{eq:9}\nOC_(int) = 0.5(\\Delta m_{COD} + 1.7(\\Delta m_{TKN})\n\\end{equation}\n\n\\begin{equation}\\label{eq:10}\nOC_m = 1.7 \\times m_TKN\n\\end{equation}\n\nOC calculation for review cases with CBOD parameter.\n\n\\begin{equation}\\label{eq:11}\nOC_(max) = 1.5(\\Delta m_{COD} + 4.6(\\Delta m_{TKN})\n\\end{equation}\n\n\\begin{equation}\\label{eq:12}\nOC_{int} = 1(\\Delta m_{COD} + 1.7(\\Delta m_{TKN})\n\\end{equation}\n\n\\begin{equation}\\label{eq:13}\nOC_{min} = 1.7(\\Delta m_{TKN})\n\\end{equation}\n\n$ \\Delta m $ is defined se the load difference after the hydraulic retention time:\n\n\\begin{equation}\\label{eq:14}\n\\Delta m =  q_i \\times C_i - q_0 \\times C_0\n\\end{equation}\n\n<i>m</i> - pollutant mass flow (g/HRT), <i>q<sub>i</sub></i> - inflow (m3/HRT), *q<sub>o</sub>* - outflow (m3/HRT); *C<sub>i</sub>* - inlet concentration, (g/m3), *C<sub>o</sub>* - outlet concentration (g.m3), OC - oxygen consumption during HRT (g).\n\nWe can use equivalent form of calculation for the oxygen consumption.\n\n\n```python\n# checking for missing COD and TKN values\nCOD_nan = review_cases['deltaCOD'].notnull()\nTKN_nan = review_cases['deltaTKN'].notnull()\n\n# adding blank columns for OC values before calculation  \npd.concat([review_cases, \n           pd.DataFrame(columns = ['OC_max',\n                                   'OC_int',\n                                   'OC_min',\n                                  ])])\n\nfor i in range(0, len(review_cases)):\n    \n    # total flow during HRT\n    hrt_flow = review_cases.loc[i, 'daily_flow_lit'] * review_cases.loc[i, 'HRT_days']\n    \n    # calculation for COD values\n    if COD_nan[i] == True:\n        deltaCOD = review_cases.loc[i, 'deltaCOD']\n        \n        m_COD = hrt_flow * 0.001 * deltaCOD\n        \n        if TKN_nan[i] == True:\n            deltaTKN = review_cases.loc[i, 'deltaTKN']\n        else:\n            deltaTKN = review_cases.loc[i, 'deltaNH4']\n        \n        m_TKN = hrt_flow * 0.001 * deltaTKN\n        \n        # OC values - COD computation\n        OC_max = ((1 * m_COD) + (4.6 * m_TKN))\n        OC_int = ((0.5 * m_COD) + (1.7 * m_TKN))\n        OC_min = (1.7 * m_TKN)\n        \n    # calculation for CBOD values\n    else:\n        deltaCBOD = review_cases.loc[i, 'deltaCBOD']\n        \n        m_CBOD = hrt_flow * 0.001 * deltaCBOD\n        \n        if TKN_nan[i] == True:\n            deltaTKN = review_cases.loc[i, 'deltaTKN']\n        else:\n            deltaTKN = review_cases.loc[i, 'deltaNH4']\n        \n        m_TKN = hrt_flow * 0.001 * deltaTKN\n        \n        # OC values - CBOD computation\n        OC_max = ((1.5 * m_CBOD) + (4.6 * m_TKN))\n        OC_int = ((1 * m_CBOD) + (1.7 * m_TKN))\n        OC_min = (1.7 * m_TKN)\n    \n    # writing the values to the dataframe\n    review_cases.loc[i, 'OC_max'] = OC_max\n    review_cases.loc[i, 'OC_int'] = OC_int\n    review_cases.loc[i, 'OC_min'] = OC_min\n```\n\n    c:\\users\\dell\\.virtualenvs\\aerationreview-wzvxscyu\\lib\\site-packages\\ipykernel_launcher.py:9: FutureWarning:\n    \n    Sorting because non-concatenation axis is not aligned. A future version\n    of pandas will change to not sort by default.\n    \n    To accept the future behavior, pass 'sort=False'.\n    \n    To retain the current behavior and silence the warning, pass 'sort=True'.\n    \n    \n\n\n##### Oxygen Consumption results\n\n\n```python\nr_col = ['OC_max', 'OC_int', 'OC_min']\n\nfor col in r_col:\n    avg = review_cases[col].mean()\n    median = review_cases[col].median()\n    min_v = review_cases[col].min()\n    max_v = review_cases[col].max()\n    \n    if \"max\" in col:\n        add = \" maximum \"\n    elif \"int\" in col:\n        add = \" intermediate \"\n    else:\n        add = \" minimum \"\n    \n    if \"v\" in col:\n        print(\"For\" + add + \"oxygen consumption the:\")\n    else:\n        print(\"For\" + add + \"oxygen consumption the:\")\n        \n    print(\"- Average value is %0.2f and median value is %0.2f g during HRT.\" % (avg, median))\n    print(\"- Minimum value is %0.2f and maximum is %0.2f g during HRT.\" % (min_v, max_v))\n    print(\"\")\n```\n\n    For maximum oxygen consumption the:\n    - Average value is 2800.68 and median value is 10.68 g during HRT.\n    - Minimum value is 1.19 and maximum is 80440.57 g during HRT.\n    \n    For intermediate oxygen consumption the:\n    - Average value is 1203.79 and median value is 4.81 g during HRT.\n    - Minimum value is 0.56 and maximum is 35293.19 g during HRT.\n    \n    For minimum oxygen consumption the:\n    - Average value is 576.20 and median value is 1.48 g during HRT.\n    - Minimum value is 0.11 and maximum is 13960.11 g during HRT.\n    \n\n\n#### Aeration efficiency\n\n##### Methodology\n\nIn previous chapter we calculated the theoretical total amount of oxygen consumed by microbial processes during the hydraulic retention time of the wetland system. In the same manner we can now calculate the total oxygen amount delivered to the system:\n\n\\begin{equation}\\label{eq:15}\nOI = Q_(air) \\times ATD \\times HRT \\times \\rho_(air) \\times \\omega_(air)\n\\end{equation}\n\nwhere\n\n$OI$ - oxygen input (g/HRT), $Q_(air)$ - air flow (m3/h), $ATD$ - aeration time per day (h per day), $HRT$ - hydraulic retention time (days), $\\rho_(air)$ - density of air (1215 g/m3) and  $\\omega_(air)$ - a mass fraction of oxygen in air (21%)\n\nThan we can calculate the aeration efficiency as the ratio between the total oxygen input to the system (with forced aeration) and the total amount of oxygen used in the system (oxygen input minus consumed oxygen).\nThe aeration efficiency will be computed for the three microbial activity scenarios (maximum, intermediate and minimum) and expressed as percents.\n\n\\begin{equation}\\label{eq:16}\nAE = \\frac{OC}{OI} \\times 100\n\\end{equation}\n\n\n\n```python\nQ_air = review_cases['air_flow_m3h']\nATD = review_cases['aer_duration_h_day']\nHRT = review_cases['HRT_days']\n\nreview_cases['OI'] = Q_air * ATD * HRT * 1215 * 0.21\n```\n\n\n```python\nOI = review_cases['OI']\nOC_max = review_cases['OC_max']\nOC_int = review_cases['OC_int']\nOC_min = review_cases['OC_min']\n\nreview_cases['AE_max'] = OC_max / OI * 100\nreview_cases['AE_int'] = OC_int / OI * 100\nreview_cases['AE_min'] = OC_min / OI * 100\n```\n\n\n```python\n# export of the calculated file\n\n# review_cases.to_csv('data/final/review_cases_final.csv', index=False)\n```\n\n## Results\n\n\n```python\n# import of the final bresults\n\nreview_cases = pd.read_csv('data/final/review_cases_final.csv')\n# review_cases.head()\n```\n\n### Overall results\n\n\n```python\nr_col = ['AE_max', 'AE_int', 'AE_min']\n\nfor col in r_col:\n    avg = review_cases[col].mean()\n    median = review_cases[col].median()\n    min_v = review_cases[col].min()\n    max_v = review_cases[col].max()\n    std = review_cases[col].std()\n    \n    if \"max\" in col:\n        add = \" maximum \"\n    elif \"int\" in col:\n        add = \" intermediate \"\n    else:\n        add = \" minimum \"\n    \n    print(\"For\" + add + \"aeration efficinecy the:\")\n        \n    print(\"- Average value is %0.2f%% and median value is %0.2f%%.\" % (avg, median))\n    print(\"- Minimum value is %0.2f%% and maximum is %0.2f%%.\" % (min_v, max_v))\n    print(\"- Standard deviation is %0.2f%%.\" % (std))\n    print(\"\")\n    \navg_depth = review_cases['water_depth_m'].mean()\nprint(\"Average depth is %0.2f m.\" % avg_depth)\n```\n\n    For maximum aeration efficinecy the:\n    - Average value is 3.74% and median value is 1.08%.\n    - Minimum value is 0.01% and maximum is 74.36%.\n    - Standard deviation is 10.87%.\n    \n    For intermediate aeration efficinecy the:\n    - Average value is 1.73% and median value is 0.48%.\n    - Minimum value is 0.01% and maximum is 33.72%.\n    - Standard deviation is 4.95%.\n    \n    For minimum aeration efficinecy the:\n    - Average value is 0.45% and median value is 0.14%.\n    - Minimum value is 0.00% and maximum is 9.80%.\n    - Standard deviation is 1.40%.\n    \n    Average depth is 0.53 m.\n\n\n#### Basic plots\n\n**Histogram for intermediate aeration efficiency**\n\n\n```python\nfig = plt.figure(figsize=(8, 5))\nax1 = fig.add_subplot(1, 1, 1)\nfnt=14\nlabelpad=10\n\nreview_cases[['AE_int']].plot(kind='hist',\n                              rwidth=0.7,\n                              bins=27,\n                              legend=False, \n                              xticks=range(0, 9, 1), \n                              xlim=(0, 9),\n                              ax=ax1\n                             )\n\nax1.set_ylabel('Number of cases', fontsize=fnt, labelpad=labelpad)\nax1.set_xlabel('Intermediate aeration efficiency (%)', fontsize=fnt, labelpad=labelpad)\n\nplt.show()\n```\n\n\n```python\nreview_cases[['AE_int']].plot(kind='box', figsize=(5, 5), ylim=(0,10))\nplt.show()\n```\n\n**Boxplots**\n\n\n```python\n# without the one most efficient case\nreview_cases_filtered = review_cases[review_cases['AE_int'] < 10]\nfig = plt.figure()\nax1 = fig.add_subplot(1, 2, 1)\nax2 = fig.add_subplot(1, 2, 2)\nreview_cases_filtered[['AE_max']].plot(kind='box', figsize=(15, 10), ax=ax1)\nreview_cases_filtered[['AE_int']].plot(kind='box', figsize=(15, 10), ax=ax2, label='title')\nplt.show()\n```\n\n### Hydraulic and Organic loading rate versus aeration efficiency\n\n\n```python\nfig = plt.figure()\nax1 = fig.add_subplot(1, 2, 1)\nax2 = fig.add_subplot(1, 2, 2)\nfnt=16\nlabelpad=10\nreview_cases_filtered.plot(kind='scatter', x='HLR_lit_m2d', y='AE_int', ax=ax1, figsize=(15, 5), grid=True, fontsize=fnt)\nreview_cases_filtered.plot(kind='scatter', x='OLR_gCOD_m2d', y='AE_int', ax=ax2, figsize=(15, 5), grid=True, fontsize=fnt)\nax1.set_xlabel('Hydraulic loading rate (liters/m2.d)', fontsize=fnt, labelpad=labelpad)\nax2.set_xlabel('Organic loading rate (gCOD/m2.d)', fontsize=fnt, labelpad=labelpad)\nax1.set_ylabel('Intermediate aeration efficiency', fontsize=fnt, labelpad=labelpad)\nax2.set_ylabel('')\nplt.show()\n```\n\n**Water depth versus aeration efficiency**\n\n\n```python\nreview_cases_filtered.plot(kind='scatter', x='AE_int', y='water_depth_m', figsize=(10, 5), grid=True, fontsize=fnt)\nplt.title('Water depth versus aeration efficiency', fontsize=16, pad=10)\nplt.xlabel('Intermediate aeration efficiency', fontsize=fnt, labelpad=labelpad)\nplt.ylabel('Water depth (m)', fontsize=fnt, labelpad=labelpad)\nplt.show()\n```\n\n#### Separating the Forced Bed Aeration systems\n\n\n```python\n# building filter for separatin FBA studies\nfba_list = ['3a', '3b', '4', '10a', '10b', '10c', '10d', '14a', '14b']\n\nfba_cases = review_cases[review_cases['number'].isin(fba_list)]\nfba_cases\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Reference</th>\n      <th>number</th>\n      <th>water_depth_m</th>\n      <th>area_m2</th>\n      <th>volume_m3</th>\n      <th>porosity</th>\n      <th>voids_m3</th>\n      <th>HLR_lit_m2d</th>\n      <th>daily_flow_lit</th>\n      <th>OLR_gCOD_m2d</th>\n      <th>...</th>\n      <th>OCR_max_a</th>\n      <th>OCR_int_a</th>\n      <th>OCR_min_a</th>\n      <th>OC_max</th>\n      <th>OC_int</th>\n      <th>OC_min</th>\n      <th>OI</th>\n      <th>AE_max</th>\n      <th>AE_int</th>\n      <th>AE_min</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>7</th>\n      <td>(Boog et al., 2014)</td>\n      <td>3a</td>\n      <td>0.800</td>\n      <td>6.2000</td>\n      <td>4.960000</td>\n      <td>0.40</td>\n      <td>2.000000</td>\n      <td>95.000000</td>\n      <td>589.0</td>\n      <td>26.88500</td>\n      <td>...</td>\n      <td>72.834600</td>\n      <td>38.779950</td>\n      <td>15.201187</td>\n      <td>1580.510820</td>\n      <td>841.524915</td>\n      <td>263.892615</td>\n      <td>4.706599e+04</td>\n      <td>3.358074</td>\n      <td>1.787968</td>\n      <td>0.560686</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>(Boog et al., 2014)</td>\n      <td>3b</td>\n      <td>0.800</td>\n      <td>6.2000</td>\n      <td>4.960000</td>\n      <td>0.40</td>\n      <td>2.000000</td>\n      <td>95.000000</td>\n      <td>589.0</td>\n      <td>26.88500</td>\n      <td>...</td>\n      <td>73.899550</td>\n      <td>39.152350</td>\n      <td>15.726062</td>\n      <td>1603.620235</td>\n      <td>849.605995</td>\n      <td>273.004445</td>\n      <td>3.137733e+04</td>\n      <td>5.110761</td>\n      <td>2.707707</td>\n      <td>0.870069</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>(Butterworth et al., 2013)</td>\n      <td>4</td>\n      <td>0.550</td>\n      <td>100.0000</td>\n      <td>55.000000</td>\n      <td>0.40</td>\n      <td>30.250000</td>\n      <td>272.000000</td>\n      <td>27200.0</td>\n      <td>19.40000</td>\n      <td>...</td>\n      <td>16.586560</td>\n      <td>6.857120</td>\n      <td>9.500218</td>\n      <td>1844.645000</td>\n      <td>762.602500</td>\n      <td>581.102500</td>\n      <td>1.021538e+06</td>\n      <td>0.180575</td>\n      <td>0.074652</td>\n      <td>0.056885</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>(Nivala et al., 2007)</td>\n      <td>10a</td>\n      <td>0.300</td>\n      <td>93.0000</td>\n      <td>27.900000</td>\n      <td>0.35</td>\n      <td>9.765000</td>\n      <td>4.000000</td>\n      <td>372.0</td>\n      <td>2.93600</td>\n      <td>...</td>\n      <td>4.610400</td>\n      <td>1.870800</td>\n      <td>4.102667</td>\n      <td>11255.139000</td>\n      <td>4567.090500</td>\n      <td>3004.690500</td>\n      <td>1.736041e+07</td>\n      <td>0.064832</td>\n      <td>0.026308</td>\n      <td>0.017308</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>(Nivala et al., 2007)</td>\n      <td>10b</td>\n      <td>0.300</td>\n      <td>93.0000</td>\n      <td>27.900000</td>\n      <td>0.35</td>\n      <td>9.765000</td>\n      <td>4.000000</td>\n      <td>372.0</td>\n      <td>3.09200</td>\n      <td>...</td>\n      <td>4.562880</td>\n      <td>1.877760</td>\n      <td>3.812533</td>\n      <td>11139.130800</td>\n      <td>4584.081600</td>\n      <td>2792.204100</td>\n      <td>1.736041e+07</td>\n      <td>0.064164</td>\n      <td>0.026405</td>\n      <td>0.016084</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>(Nivala et al., 2007)</td>\n      <td>10c</td>\n      <td>0.300</td>\n      <td>93.0000</td>\n      <td>27.900000</td>\n      <td>0.35</td>\n      <td>9.765000</td>\n      <td>4.000000</td>\n      <td>372.0</td>\n      <td>3.49200</td>\n      <td>...</td>\n      <td>6.668080</td>\n      <td>2.737160</td>\n      <td>5.637200</td>\n      <td>16278.450300</td>\n      <td>6682.091850</td>\n      <td>4128.544350</td>\n      <td>1.736041e+07</td>\n      <td>0.093768</td>\n      <td>0.038490</td>\n      <td>0.023781</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>(Nivala et al., 2007)</td>\n      <td>10d</td>\n      <td>0.300</td>\n      <td>93.0000</td>\n      <td>27.900000</td>\n      <td>0.35</td>\n      <td>9.765000</td>\n      <td>4.000000</td>\n      <td>372.0</td>\n      <td>2.51200</td>\n      <td>...</td>\n      <td>4.132800</td>\n      <td>1.641600</td>\n      <td>4.012000</td>\n      <td>10089.198000</td>\n      <td>4007.556000</td>\n      <td>2938.288500</td>\n      <td>1.736041e+07</td>\n      <td>0.058116</td>\n      <td>0.023084</td>\n      <td>0.016925</td>\n    </tr>\n    <tr>\n      <th>31</th>\n      <td>(Redmond et al., 2014)</td>\n      <td>14a</td>\n      <td>0.305</td>\n      <td>5.4412</td>\n      <td>1.659566</td>\n      <td>NaN</td>\n      <td>0.506168</td>\n      <td>48.702492</td>\n      <td>265.0</td>\n      <td>31.07219</td>\n      <td>...</td>\n      <td>33.759983</td>\n      <td>16.164649</td>\n      <td>6.645255</td>\n      <td>606.192906</td>\n      <td>290.251797</td>\n      <td>36.393192</td>\n      <td>3.940537e+03</td>\n      <td>15.383512</td>\n      <td>7.365794</td>\n      <td>0.923559</td>\n    </tr>\n    <tr>\n      <th>32</th>\n      <td>(Redmond et al., 2014)</td>\n      <td>14b</td>\n      <td>0.305</td>\n      <td>5.4412</td>\n      <td>1.659566</td>\n      <td>NaN</td>\n      <td>0.506168</td>\n      <td>48.702492</td>\n      <td>265.0</td>\n      <td>31.07219</td>\n      <td>...</td>\n      <td>35.295475</td>\n      <td>16.813172</td>\n      <td>7.752798</td>\n      <td>825.813882</td>\n      <td>393.380469</td>\n      <td>55.325004</td>\n      <td>5.134639e+03</td>\n      <td>16.083194</td>\n      <td>7.661308</td>\n      <td>1.077486</td>\n    </tr>\n  </tbody>\n</table>\n<p>9 rows \u00d7 41 columns</p>\n</div>\n\n\n\n\n```python\nr_col = ['AE_max', 'AE_int', 'AE_min', 'OCR_max_v', 'OCR_int_v']\n\nprint(\"For FBA studies we have this values\")\n\nfor col in r_col:\n    avg = fba_cases[col].mean()\n    median = fba_cases[col].median()\n    min_v = fba_cases[col].min()\n    max_v = fba_cases[col].max()\n    std = fba_cases[col].std()\n    \n    if \"max\" in col:\n        add = \" maximum \"\n    elif \"int\" in col:\n        add = \" intermediate \"\n    else:\n        add = \" minimum \"\n    \n    print(\"For\" + add + \"aeration efficinecy the:\")\n    print(\"- Average value is %0.2f%% and median value is %0.2f%%.\" % (avg, median))\n    print(\"- Minimum value is %0.2f%% and maximum is %0.2f%%.\" % (min_v, max_v))\n    print(\"- Standard deviation is %0.2f%%.\" % (std))\n    print(\"\")\n    \navg_depth = fba_cases['water_depth_m'].mean()\nprint(\"Average depth is %0.2f m.\" % avg_depth)\nprint(\"\")\n\navg_OCR = fba_cases['OCR_max_v'].mean()\nmedian_OCR = fba_cases['OCR_max_v'].median()\nmin_OCR = fba_cases['OCR_max_v'].min()\nmax_OCR = fba_cases['OCR_max_v'].max()\nprint(\"Average OCR value is %0.2f and median value is %0.2f.\" % (avg_OCR, median_OCR))\nprint(\"Minimum OCR value is %0.2f and maximum is %0.2f.\" % (min_OCR, max_OCR))\n```\n\n    For FBA studies we have this values\n    For maximum aeration efficinecy the:\n    - Average value is 5.03% and median value is 1.73%.\n    - Minimum value is 0.06% and maximum is 16.08%.\n    - Standard deviation is 6.87%.\n    \n    For intermediate aeration efficinecy the:\n    - Average value is 2.45% and median value is 0.91%.\n    - Minimum value is 0.02% and maximum is 7.66%.\n    - Standard deviation is 3.28%.\n    \n    For minimum aeration efficinecy the:\n    - Average value is 0.44% and median value is 0.29%.\n    - Minimum value is 0.02% and maximum is 1.08%.\n    - Standard deviation is 0.47%.\n    \n    For maximum aeration efficinecy the:\n    - Average value is 59.55% and median value is 56.64%.\n    - Minimum value is 13.78% and maximum is 115.72%.\n    - Standard deviation is 46.67%.\n    \n    For intermediate aeration efficinecy the:\n    - Average value is 29.08% and median value is 28.80%.\n    - Minimum value is 5.47% and maximum is 55.13%.\n    - Standard deviation is 23.96%.\n    \n    Average depth is 0.43 m.\n    \n    Average OCR value is 59.55 and median value is 56.64.\n    Minimum OCR value is 13.78 and maximum is 115.72.\n\n\n\n```python\nfig = plt.figure(figsize=(8, 5))\nax1 = fig.add_subplot(1, 1, 1)\nfnt=14\nlabelpad=10\n\nfba_cases[['AE_int']].plot(kind='hist',\n                              rwidth=0.7,\n                              bins=27,\n                              legend=False, \n                              xticks=range(0, 9, 1), \n                              ax=ax1\n                             )\n\nax1.set_ylabel('Number of cases', fontsize=fnt, labelpad=labelpad)\nax1.set_xlabel('Intermediate aeration efficiency (%) (FBA cases)', fontsize=fnt, labelpad=labelpad)\n\nplt.show()\n```\n\n#### Average polutant reduction\n\n\n```python\nprint(\"Average polutant efficiency:\")\nprint(\"\")\n\nreview_cases['eff_COD'] = (review_cases['COD_IN'] - review_cases['COD_OUT']) / review_cases['COD_IN'] * 100\nreview_cases['eff_TKN'] = (review_cases['TKN_IN'] - review_cases['TKN_OUT']) / review_cases['TKN_IN'] * 100\nreview_cases['eff_NH4'] = (review_cases['NH4_IN'] - review_cases['NH4_OUT']) / review_cases['NH4_IN'] * 100\n\nr_col = ['eff_COD', 'eff_TKN', 'eff_NH4']\n\nfor col in r_col:\n    avg = review_cases[col].mean()\n    med = review_cases[col].median()\n    \n    if \"COD\" in col:\n        print(\"Average COD reduction efficiency is %0.2f%%\" % avg)\n        print(\"Median COD reduction efficiency is %0.2f%%\" % med)\n    if \"TKN\" in col:\n        print(\"Average TKN reduction efficiency is %0.2f%%\" % avg)\n        print(\"Median TKN reduction efficiency is %0.2f%%\" % med)\n    if \"NH4\" in col:\n        print(\"Average NH4 reduction efficiency is %0.2f%%\" % avg)\n        print(\"Median NH4 reduction efficiency is %0.2f%%\" % med)\n    print(\"\")\n```\n\n    Average polutant efficiency:\n    \n    Average COD reduction efficiency is 85.56%\n    Median COD reduction efficiency is 93.46%\n    \n    Average TKN reduction efficiency is 85.39%\n    Median TKN reduction efficiency is 95.64%\n    \n    Average NH4 reduction efficiency is 86.74%\n    Median NH4 reduction efficiency is 92.99%\n    \n\n\n#### Correlation matrix\n\n\n```python\nreview_cases.columns\n```\n\n\n\n\n    Index(['Reference', 'number', 'water_depth_m', 'area_m2', 'volume_m3',\n           'porosity', 'voids_m3', 'HLR_lit_m2d', 'daily_flow_lit', 'OLR_gCOD_m2d',\n           'HRT_h', 'HRT_days', 'air_flow_m3h', 'aer_duration_h_day',\n           'air_per_day_m3', 'air_per_HRT_m3', 'COD_IN', 'COD_OUT', 'deltaCOD',\n           'CBOD_IN', 'CBOD_OUT', 'deltaCBOD', 'TKN_IN', 'TKN_OUT', 'deltaTKN',\n           'NH4_IN', 'NH4_OUT', 'deltaNH4', 'OCR_max_v', 'OCR_int_v', 'OCR_min_v',\n           'OCR_max_a', 'OCR_int_a', 'OCR_min_a', 'OC_max', 'OC_int', 'OC_min',\n           'OI', 'AE_max', 'AE_int', 'AE_min', 'eff_COD', 'eff_TKN', 'eff_NH4'],\n          dtype='object')\n\n\n\n\n```python\nAE_corr = ['water_depth_m', 'area_m2', 'volume_m3', 'HLR_lit_m2d', \n           'OLR_gCOD_m2d', 'HRT_days', 'air_flow_m3h', 'aer_duration_h_day',\n           'AE_max']\n```\n\n\n```python\nAE_review_cases = review_cases[[*AE_corr]]\nAE_review_cases.columns\n```\n\n\n\n\n    Index(['water_depth_m', 'area_m2', 'volume_m3', 'HLR_lit_m2d', 'OLR_gCOD_m2d',\n           'HRT_days', 'air_flow_m3h', 'aer_duration_h_day', 'AE_max'],\n          dtype='object')\n\n\n\n\n```python\nAE_review_cases.corr()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>water_depth_m</th>\n      <th>area_m2</th>\n      <th>volume_m3</th>\n      <th>HLR_lit_m2d</th>\n      <th>OLR_gCOD_m2d</th>\n      <th>HRT_days</th>\n      <th>air_flow_m3h</th>\n      <th>aer_duration_h_day</th>\n      <th>AE_max</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>water_depth_m</th>\n      <td>1.000000</td>\n      <td>0.602125</td>\n      <td>0.617061</td>\n      <td>0.699644</td>\n      <td>0.468242</td>\n      <td>-0.251322</td>\n      <td>0.366829</td>\n      <td>0.016899</td>\n      <td>0.108795</td>\n    </tr>\n    <tr>\n      <th>area_m2</th>\n      <td>0.602125</td>\n      <td>1.000000</td>\n      <td>0.997962</td>\n      <td>0.881686</td>\n      <td>0.240732</td>\n      <td>-0.023361</td>\n      <td>0.812344</td>\n      <td>0.193056</td>\n      <td>0.063361</td>\n    </tr>\n    <tr>\n      <th>volume_m3</th>\n      <td>0.617061</td>\n      <td>0.997962</td>\n      <td>1.000000</td>\n      <td>0.887795</td>\n      <td>0.257333</td>\n      <td>-0.079426</td>\n      <td>0.774424</td>\n      <td>0.168588</td>\n      <td>0.069749</td>\n    </tr>\n    <tr>\n      <th>HLR_lit_m2d</th>\n      <td>0.699644</td>\n      <td>0.881686</td>\n      <td>0.887795</td>\n      <td>1.000000</td>\n      <td>0.581418</td>\n      <td>-0.218217</td>\n      <td>0.663513</td>\n      <td>0.235477</td>\n      <td>0.069916</td>\n    </tr>\n    <tr>\n      <th>OLR_gCOD_m2d</th>\n      <td>0.468242</td>\n      <td>0.240732</td>\n      <td>0.257333</td>\n      <td>0.581418</td>\n      <td>1.000000</td>\n      <td>-0.312063</td>\n      <td>0.049225</td>\n      <td>0.051532</td>\n      <td>0.068210</td>\n    </tr>\n    <tr>\n      <th>HRT_days</th>\n      <td>-0.251322</td>\n      <td>-0.023361</td>\n      <td>-0.079426</td>\n      <td>-0.218217</td>\n      <td>-0.312063</td>\n      <td>1.000000</td>\n      <td>0.425628</td>\n      <td>0.263661</td>\n      <td>-0.045951</td>\n    </tr>\n    <tr>\n      <th>air_flow_m3h</th>\n      <td>0.366829</td>\n      <td>0.812344</td>\n      <td>0.774424</td>\n      <td>0.663513</td>\n      <td>0.049225</td>\n      <td>0.425628</td>\n      <td>1.000000</td>\n      <td>0.378768</td>\n      <td>-0.019449</td>\n    </tr>\n    <tr>\n      <th>aer_duration_h_day</th>\n      <td>0.016899</td>\n      <td>0.193056</td>\n      <td>0.168588</td>\n      <td>0.235477</td>\n      <td>0.051532</td>\n      <td>0.263661</td>\n      <td>0.378768</td>\n      <td>1.000000</td>\n      <td>-0.211296</td>\n    </tr>\n    <tr>\n      <th>AE_max</th>\n      <td>0.108795</td>\n      <td>0.063361</td>\n      <td>0.069749</td>\n      <td>0.069916</td>\n      <td>0.068210</td>\n      <td>-0.045951</td>\n      <td>-0.019449</td>\n      <td>-0.211296</td>\n      <td>1.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nOCR_corr = ['water_depth_m', 'area_m2', 'volume_m3', 'HLR_lit_m2d', \n           'OLR_gCOD_m2d', 'HRT_days', 'air_flow_m3h', 'aer_duration_h_day',\n           'OCR_max_a']\n\nOCR_review_cases = review_cases[[*OCR_corr]]\nOCR_review_cases.columns\n```\n\n\n\n\n    Index(['water_depth_m', 'area_m2', 'volume_m3', 'HLR_lit_m2d', 'OLR_gCOD_m2d',\n           'HRT_days', 'air_flow_m3h', 'aer_duration_h_day', 'OCR_max_a'],\n          dtype='object')\n\n\n\n\n```python\nOCR_review_cases.corr()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>water_depth_m</th>\n      <th>area_m2</th>\n      <th>volume_m3</th>\n      <th>HLR_lit_m2d</th>\n      <th>OLR_gCOD_m2d</th>\n      <th>HRT_days</th>\n      <th>air_flow_m3h</th>\n      <th>aer_duration_h_day</th>\n      <th>OCR_max_a</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>water_depth_m</th>\n      <td>1.000000</td>\n      <td>0.602125</td>\n      <td>0.617061</td>\n      <td>0.699644</td>\n      <td>0.468242</td>\n      <td>-0.251322</td>\n      <td>0.366829</td>\n      <td>0.016899</td>\n      <td>0.416706</td>\n    </tr>\n    <tr>\n      <th>area_m2</th>\n      <td>0.602125</td>\n      <td>1.000000</td>\n      <td>0.997962</td>\n      <td>0.881686</td>\n      <td>0.240732</td>\n      <td>-0.023361</td>\n      <td>0.812344</td>\n      <td>0.193056</td>\n      <td>0.072514</td>\n    </tr>\n    <tr>\n      <th>volume_m3</th>\n      <td>0.617061</td>\n      <td>0.997962</td>\n      <td>1.000000</td>\n      <td>0.887795</td>\n      <td>0.257333</td>\n      <td>-0.079426</td>\n      <td>0.774424</td>\n      <td>0.168588</td>\n      <td>0.090193</td>\n    </tr>\n    <tr>\n      <th>HLR_lit_m2d</th>\n      <td>0.699644</td>\n      <td>0.881686</td>\n      <td>0.887795</td>\n      <td>1.000000</td>\n      <td>0.581418</td>\n      <td>-0.218217</td>\n      <td>0.663513</td>\n      <td>0.235477</td>\n      <td>0.457579</td>\n    </tr>\n    <tr>\n      <th>OLR_gCOD_m2d</th>\n      <td>0.468242</td>\n      <td>0.240732</td>\n      <td>0.257333</td>\n      <td>0.581418</td>\n      <td>1.000000</td>\n      <td>-0.312063</td>\n      <td>0.049225</td>\n      <td>0.051532</td>\n      <td>0.956408</td>\n    </tr>\n    <tr>\n      <th>HRT_days</th>\n      <td>-0.251322</td>\n      <td>-0.023361</td>\n      <td>-0.079426</td>\n      <td>-0.218217</td>\n      <td>-0.312063</td>\n      <td>1.000000</td>\n      <td>0.425628</td>\n      <td>0.263661</td>\n      <td>-0.306188</td>\n    </tr>\n    <tr>\n      <th>air_flow_m3h</th>\n      <td>0.366829</td>\n      <td>0.812344</td>\n      <td>0.774424</td>\n      <td>0.663513</td>\n      <td>0.049225</td>\n      <td>0.425628</td>\n      <td>1.000000</td>\n      <td>0.378768</td>\n      <td>-0.099401</td>\n    </tr>\n    <tr>\n      <th>aer_duration_h_day</th>\n      <td>0.016899</td>\n      <td>0.193056</td>\n      <td>0.168588</td>\n      <td>0.235477</td>\n      <td>0.051532</td>\n      <td>0.263661</td>\n      <td>0.378768</td>\n      <td>1.000000</td>\n      <td>0.031645</td>\n    </tr>\n    <tr>\n      <th>OCR_max_a</th>\n      <td>0.416706</td>\n      <td>0.072514</td>\n      <td>0.090193</td>\n      <td>0.457579</td>\n      <td>0.956408</td>\n      <td>-0.306188</td>\n      <td>-0.099401</td>\n      <td>0.031645</td>\n      <td>1.000000</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# from pandas.plotting import scatter_matrix\n# scatter_matrix(OCR_review_cases, figsize=(15, 15), alpha=0.3)\n```\n\n#### Difference between continuos and intermitent aeration\n\n\n```python\n# filtering the continous cases\nCA = review_cases[review_cases['aer_duration_h_day'] == 24]\n\n# selecting only cases with AE_int less than 10 - more doesnt make sense\nCA = CA[CA['AE_int'] < 10]\nlen(CA)\n```\n\n\n\n\n    21\n\n\n\n\n```python\nIA = review_cases[review_cases['aer_duration_h_day'] < 24]\n\n# selecting only cases with AE_int less than 10 - more doesnt make sense\nIA = IA[IA['AE_int'] < 10]\n\nlen(IA)\n```\n\n\n\n\n    27\n\n\n\nSo there are 21 review cases with continuous aeration and 27 (28 with one unrealistic case) with intermittent aeration.\n\n\n```python\nfig = plt.figure(figsize=(10, 5))\nax1 = fig.add_subplot(1, 2, 1)\nax2 = fig.add_subplot(1, 2, 2)\n\nfnt=16\nlabelpad=20\n\nCA[['AE_int']].plot(kind='box',\n                    ax=ax1,\n                    fontsize=fnt,\n                    ylim=(0, 8)\n                   )\nIA[['AE_int']].plot(kind='box',\n                    ax=ax2,\n                    fontsize=fnt,\n                    ylim=(0, 8)\n                   )\n\nax1.set_title('Continuous aeration', fontsize=fnt, pad=labelpad)\nax2.set_title('Intermittent aeration', fontsize=fnt, pad=labelpad)\nfig.suptitle('Comparison of intermediate AE boxplos for CA and IA', fontsize=16, y=1.05)\n\nplt.show()\n```\n\n\n```python\nfig = plt.figure(figsize=(10, 5))\nax1 = fig.add_subplot(1, 2, 1)\nax2 = fig.add_subplot(1, 2, 2)\n\nfnt=16\nlabelpad=10\ny_limits=(0, 200)\n\nCA[['OCR_int_v']].plot(kind='box',\n                    ax=ax1,\n                    fontsize=fnt,\n                    ylim=y_limits\n                   )\nIA[['OCR_int_v']].plot(kind='box',\n                    ax=ax2,\n                    fontsize=fnt,\n                    ylim=y_limits\n                   )\n\nax1.set_title('Continuous aeration', fontsize=fnt)\nax2.set_title('Intermittent aeration', fontsize=fnt)\n\nplt.show()\n```\n\n\n```python\nfig = plt.figure(figsize=(10, 5))\nax1 = fig.add_subplot(1, 2, 1)\nax2 = fig.add_subplot(1, 2, 2)\n\nfnt=16\nlabelpad=10\ny_limits=(0, 150)\n\nCA[['OLR_gCOD_m2d']].plot(kind='box',\n                    ax=ax1,\n                    fontsize=fnt,\n                    ylim=y_limits\n                   )\nIA[['OLR_gCOD_m2d']].plot(kind='box',\n                    ax=ax2,\n                    fontsize=fnt,\n                    ylim=y_limits\n                   )\n\nax1.set_title('Continuous aeration', fontsize=fnt)\nax2.set_title('Intermittent aeration', fontsize=fnt)\n\nplt.show()\n```\n\n\n```python\nr_col = ['AE_int', 'OCR_int_v', 'OLR_gCOD_m2d']\n\nprint(\"For CA studies we have this values\")\n\nfor col in r_col:\n    avg = CA[col].mean()\n    median = CA[col].median()\n    \n    if \"AE\" in col:\n        print(\"For intermediate aeration eficiency the values are:\")\n    elif \"OCR\" in col:\n        print(\"For intermediate volumetric OCR the values are:\")\n    else:\n        print(\"For OLR the values are:\")\n    \n    print(\"- Average value is %0.2f and median value is %0.2f.\" % (avg, median))\n    print(\"\")\n    \n\n```\n\n    For CA studies we have this values\n    For intermediate aeration eficiency the values are:\n    - Average value is 0.53 and median value is 0.07.\n    \n    For intermediate volumetric OCR the values are:\n    - Average value is 31.84 and median value is 18.80.\n    \n    For OLR the values are:\n    - Average value is 31.66 and median value is 13.80.\n    \n\n\n\n```python\nr_col = ['AE_int', 'OCR_int_v', 'OLR_gCOD_m2d']\n\nprint(\"For IA studies we have this values\")\n\nfor col in r_col:\n    avg = IA[col].mean()\n    median = IA[col].median()\n    \n    if \"AE\" in col:\n        print(\"For intermediate aeration eficiency the values are:\")\n    elif \"OCR\" in col:\n        print(\"For intermediate volumetric OCR the values are:\")\n    else:\n        print(\"For OLR the values are:\")\n    \n    print(\"- Average value is %0.2f and median value is %0.2f.\" % (avg, median))\n    print(\"\")\n```\n\n    For IA studies we have this values\n    For intermediate aeration eficiency the values are:\n    - Average value is 1.47 and median value is 0.61.\n    \n    For intermediate volumetric OCR the values are:\n    - Average value is 39.48 and median value is 27.45.\n    \n    For OLR the values are:\n    - Average value is 28.66 and median value is 27.28.\n    \n\n", "meta": {"hexsha": "5dd8900995a38dca42a40649c39bdf81998b95df", "size": 380921, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Treatment_Wetlands_Areation_Review.ipynb", "max_stars_repo_name": "rousvit/wetlands-aeration-review", "max_stars_repo_head_hexsha": "f6c41c4d0d0a7defc92b76d49b16872702e7675f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Treatment_Wetlands_Areation_Review.ipynb", "max_issues_repo_name": "rousvit/wetlands-aeration-review", "max_issues_repo_head_hexsha": "f6c41c4d0d0a7defc92b76d49b16872702e7675f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Treatment_Wetlands_Areation_Review.ipynb", "max_forks_repo_name": "rousvit/wetlands-aeration-review", "max_forks_repo_head_hexsha": "f6c41c4d0d0a7defc92b76d49b16872702e7675f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 98.8891484943, "max_line_length": 47548, "alphanum_fraction": 0.7869321985, "converted": true, "num_tokens": 23595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13660837948097748, "lm_q2_score": 0.04336579660028471, "lm_q1q2_score": 0.0059241311984665765}}
{"text": "```python\n# code for loading the format for the notebook\nimport os\n\n# path : store the current path to convert back to it later\npath = os.getcwd()\nos.chdir( os.path.join('..', '..', 'notebook_format') )\nfrom formats import load_style\nload_style(css_style = 'custom2.css')\n```\n\n\n\n\n\n<style>\n    html {\n        font-size: 18px !important;\n    }\n\n    body {\n        background-color: #FFF !important;\n        font-weight: 1rem;\n        font-family: 'Source Sans Pro', \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n    }\n\n    body .notebook-app {\n        background-color: #FFF !important;\n    }\n\n    #header {\n        box-shadow: none !important;\n    }\n\n    #notebook {\n        padding-top: 0px;\n    }\n\n    #notebook-container {\n        box-shadow: none;\n        -webkit-box-shadow: none;\n        padding: 10px;\n    }\n\n    div.cell {\n        width: 1000px;\n        margin-left: 0% !important;\n        margin-right: auto;\n    }\n\n    div.cell.selected {\n        border: 1px dashed #CCCCCC;\n    }\n\n    .edit_mode div.cell.selected {\n        border: 1px dashed #828282;\n    }\n\n    div.output_wrapper {\n        margin-top: 8px;\n    }\n\n    a {\n        color: #383838;\n    }\n\n    code,\n    kbd,\n    pre,\n    samp {\n        font-family: 'Menlo', monospace !important;\n        font-size: 0.75rem !important;\n    }\n\n    h1 {\n        font-size: 2rem !important;\n        font-weight: 500 !important;\n        letter-spacing: 3px !important;\n        text-transform: uppercase !important;\n    }\n\n    h2 {\n        font-size: 1.8rem !important;\n        font-weight: 400 !important;\n        letter-spacing: 3px !important;\n        text-transform: none !important;\n    }\n\n    h3 {\n        font-size: 1.5rem !important;\n        font-weight: 400 !important;\n        font-style: italic !important;\n        display: block !important;\n    }\n\n    h4,\n    h5,\n    h6 {\n        font-size: 1rem !important;\n        font-weight: 400 !important;\n        display: block !important;\n    }\n\n    .prompt {\n        font-family: 'Menlo', monospace !important;\n        font-size: 0.75rem;\n        text-align: right;\n        line-height: 1.21429rem;\n    }\n\n    /* INTRO PAGE */\n\n    .toolbar_info,\n    .list-container {\n        ;\n    }\n    /* NOTEBOOK */\n\n    div#header-container {\n        display: none !important;\n    }\n\n    div#notebook {\n        border-top: none;\n        font-size: 1rem;\n    }\n\n    div.input_prompt {\n        color: #C74483;\n    }\n\n    .code_cell div.input_prompt:after,\n    div.output_prompt:after {\n        content: '\\25b6';\n    }\n\n    div.output_prompt {\n        color: #2B88D9;\n    }\n\n    div.input_area {\n        border-radius: 0px;\n        border: 1px solid #d8d8d8;\n    }\n\n    div.output_area pre {\n        font-weight: normal;\n    }\n\n    div.output_subarea {\n        font-weight: normal;\n    }\n\n    .rendered_html pre,\n    .rendered_html table,\n    .rendered_html th,\n    .rendered_html tr,\n    .rendered_html td {\n        border: 1px #828282 solid;\n        font-size: 0.75rem;\n        font-family: 'Menlo', monospace;\n    }\n\n    .rendered_html th,\n    .rendered_html tr,\n    .rendered_html td {\n        padding: 5px 10px;\n    }\n\n    .rendered_html th {\n        font-weight: normal;\n        background: #f8f8f8;\n    }\n\n    a:link{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:visited{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:hover{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:focus{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:active{\n       font-weight: bold;\n       color:#447adb;\n    }\n    .rendered_html :link {\n       text-decoration: underline; \n    }\n\n    div.output_html {\n        font-weight: 1rem;\n        font-family: 'Source Sans Pro', \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n    }\n\n    table.dataframe tr {\n        border: 1px #CCCCCC;\n    }\n\n    div.cell.selected {\n        border-radius: 0px;\n    }\n\n    div.cell.edit_mode {\n        border-radius: 0px;\n        border: thin solid #CF5804;\n    }\n\n    span.ansiblue {\n        color: #00A397;\n    }\n\n    span.ansigray {\n        color: #d8d8d8;\n    }\n\n    span.ansigreen {\n        color: #688A0A;\n    }\n\n    span.ansipurple {\n        color: #975DDE;\n    }\n\n    span.ansired {\n        color: #D43132;\n    }\n\n    span.ansiyellow {\n        color: #D9AA00;\n    }\n\n    div.output_stderr {\n        background-color: #D43132;\n    }\n\n    div.output_stderr pre {\n        color: #e8e8e8;\n    }\n\n    .cm-s-ipython.CodeMirror {\n        background: #F8F8F8;\n    }\n\n    .cm-s-ipython div.CodeMirror-selected {\n        background: #e8e8e8 !important;\n    }\n\n    .cm-s-ipython .CodeMirror-gutters {\n        background: #F8F8F8;\n        border-right: 0px;\n    }\n\n    .cm-s-ipython .CodeMirror-linenumber {\n        color: #b8b8b8;\n    }\n\n    .cm-s-ipython .CodeMirror-cursor {\n        border-left: 1px solid #585858 !important;\n    }\n\n    .cm-s-ipython span.cm-atom {\n        color: #C74483;\n    }\n\n    .cm-s-ipython span.cm-number {\n        color: #C74483;\n    }\n\n    .cm-s-ipython span.cm-property,\n    .cm-s-ipython span.cm-attribute {\n        color: #688A0A;\n    }\n\n    .cm-s-ipython span.cm-keyword {\n        font-weight: normal;\n        color: #D43132;\n    }\n\n    .cm-s-ipython span.cm-string {\n        color: #D9AA00;\n    }\n\n    .cm-s-ipython span.cm-operator {\n        font-weight: normal;\n    }\n\n    .cm-s-ipython span.cm-builtin {\n        color: #2B88D9;\n    }\n\n    .cm-s-ipython span.cm-variable {\n        color: #00A397;\n    }\n\n    .cm-s-ipython span.cm-variable-2 {\n        color: #2B88D9;\n    }\n\n    .cm-s-ipython span.cm-def {\n        color: #00A397;\n    }\n\n    .cm-s-ipython span.cm-error {\n        background: #FFBDBD;\n        color: #D43132;\n    }\n\n    .cm-s-ipython span.cm-tag {\n        color: #D43132;\n    }\n\n    .cm-s-ipython span.cm-link {\n        color: #975DDE;\n    }\n\n    .cm-s-ipython .CodeMirror-matchingbracket {\n        text-decoration: underline;\n         !important;\n    }\n</style>\n\n\n\n\n\n\n```python\nos.chdir(path)\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# 1. magic for inline plot\n# 2. magic to print version\n# 3. magic so that the notebook will reload external python modules\n%matplotlib inline\n%load_ext watermark\n%load_ext autoreload \n%autoreload 2\n\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.ensemble import GradientBoostingRegressor\n\n%watermark -d -t -v -p numpy,pandas,matplotlib,sklearn\n```\n\n    2017-03-14 15:58:58 \n    \n    CPython 3.5.2\n    IPython 4.2.0\n    \n    numpy 1.12.0\n    pandas 0.19.2\n    matplotlib 2.0.0\n    sklearn 0.18\n\n\n# Gradient Boosting Machine (GBM)\n\nJust like [Random Forest and Extra Trees](http://nbviewer.jupyter.org/github/ethen8181/machine-learning/blob/master/trees/random_forest.ipynb), Gradient Boosting Machine is also a type of Ensemble Tree method, the only difference is it is stemmed from the the boosting framework. The idea of boosting is to add a weak classifier to the ensemble at a time, and this newly added weak classifier is trained to improve on the already trained ensemble. Meaning it will pay higher attention on examples which are misclassi\ufb01ed or have higher errors and focus on mitigating those errors. Boosting is a general framework can be applied to any sort of weak learner, although Decision Tree models is by far the commonly used due to the fact that they have the flexibility to be weak learners by simply restricting their depth and they are quite fast to train.\n\nSuppose we are given some dataset $(x_1, y_1), (x_2, y_2), ...,(x_n, y_n)$, and the task is to fit a model $F(x)$ to minimize square loss. After training the model, we discovered the model is good but not perfect.\nThere are some mistakes: $F(x_1) = 0.8$, while $y_1 = 0.9$, and $F(x_2) = 1.4$ while $y_2 = 1.3$ .... Now the question is, how can we improve this model without changing anything from $F(x)$?\n\nHow about we simply add an additional model (e.g. regression tree) $h$ to the already existing $F$, so the new prediction becomes $F(x) + h(x)$. In other words, we wish to improve upon the existing model so that $F(x_1) + h(x_1) = y_1, F(x_2) + h(x_2) = y_2 ...$ or equivalent we wish to a new model $h$ such that $h(x_1) = y_1 - F(x_1), h(x_2) = y_2 - F(x_2) ...$. The idea is all well and good, but the bad news is probably no model $h$ (e.g. regression tree) will be able to do this perfectly. Fortunately, the good news is, some $h$ might be able to do this approximately.\n\nThe idea is, we fit the model $h$ to the data using $y_1 - F(x_1), y_2 - F(x_2)$ as the response variable. And the intuition for this is: the $y_i - F(x_i)$s are the residuals. These are the areas that the existing\nmodel $F$ cannot do well, so now the role of $h$ is to compensate the shortcoming of existing model $F$. And if the model after adding the new model $h$, $F + h$ is still unsatisfactory, we will just add another new one.\n\nTo make sure we're actually learning the residuals, we'll employ the idea of gradient descent. Say our goal is to minimize $J$, an overall loss function additively calculated from all observations with regard to $F$, a classifier with some parameters. More formally, we're given the formula:\n\n$$J(y, F) = \\sum_i^n L\\big(y_i, F(x_i)\\big)$$\n\nWhere:\n\n- $L$ is a cost/loss function comparing the response variable's value and the prediction of the model for each observation\n\nInstead of trying to solve it directly, gradient descent is an iterative technique that allows us to approach the solution of an optimization problem. At each step of the algorithm, it will perform the following operations:\n\n$$F_b(x_i) = F_{b-1}(x_i) - \\eta \\times \\nabla L\\big(y_i, F(x_i)\\big)$$\n\nWhere:\n\n- $F_b$ is the version of classifier at step/iteration $b$\n- $\\eta$ is the learning rate which controls the size of the learning process\n- $\\nabla$ is the gradient i.e. the first order partial derivative of the cost function with respect to the classifier\n- The formula above actually refers to stochastic gradient descent only computing the function for a single observation, $x_i$\n\nFor example, say we're given, sum squares of errors, a well-known quality indicator for regression model as our loss function. So now our loss function $L\\big(y_i, F(x_i)\\big)$ is defined as: $\\frac{1}{2} \\big( y_i - F(x_i) \\big)^2$ (the 1/2 is simply to make the notation cleaner later). Taking the gradient of this loss function we get:\n\n$$\\frac{ \\partial L\\big(y_i, F(x_i)\\big) }{ \\partial F(x_i) } = \\frac{ \\partial \\frac{1}{2} \\big( y_i - F(x_i) \\big)^2 }{ \\partial F(x_i) } = F(x_i) - y_i$$\n\nTying this back to our original problem, we wish to update our function $F$ at iteration $b$ with a new model $h$:\n\n\\begin{align}\nF_b(x_i) &= F_{b-1}(x_i) + h(x_i) \\nonumber \\\\\n         &= F_{b-1}(x_i) + y_i - F_{b-1}(x_i) \\nonumber \\\\\n         &= F_{b-1}(x_i) - 1 \\times \\frac{ \\partial L\\big(y_i, F_{b-1}(x_i)\\big) }{ \\partial F_{b-1}(x_i) }\n         \\nonumber \\\\\n\\end{align}\n\nAs we can see, the formula above is 99% the same as as the gradient descent formula, $F_b(x_i) = F_{b-1}(x_i) - \\eta \\times \\nabla L\\big(y_i, F(x_i)\\big)$. The only difference is that the learning rate $\\eta$ is  1. Thus, we now have an iterative process constructing the additive model that minimizes our loss function (residuals).\n\nIn practice though, Gradient Boosting Machine is more prone to overfitting, since the week learner is tasked with optimally fitting the gradient. This means that boosting will select the optimal learner at each stage of the algorithm, although this strategy generates an optimal solution at the current stage, it has the drawbacks of not finding the optimal global model as well as overfitting the training data. A remedy for greediness is to constrain the learning process by setting the learning rate $\\eta$ (also known as shrinkage). In the above algorithm, instead of directly adding the predicted value for a sample to next iteration's predicted value, so that only a fraction of the current predicted value is added to the previous iteration's predicted value. This parameter can take values between 0 and 1 and becomes another tuning parameter for the model. Small values of the learning parameter such as 0.1 tends to work better, but the value of the parameter is inversely proportional to the computation time required to find an optimal model, because more iterations are necessary.\n\nTo sum it all up in english the process of training a gradient boosting machine for regression is:\n\n1. Initialize a predicted value for each observation (e.g. the original response or the average response or a value that minimizes the loss function). This will be our initial \"residuals\", $r$ (it can be called the residuals because we're dealing with a regression task, but often times this quantity is referred to as the negative gradient, so that the $- \\nabla \\times L\\big(y_i, F(x_i) \\big)$ part generalizes to any loss function we might want to use).\n2. For step = 1 to $B$ (number of iterations that we specify) do:\n\n    - Fit a regression tree $F_b$ to the training data $(X, r)$, where we use the residuals as the response variable\n    - Update model $F$ by adding a shrunken version of the newly fitted regression tree. In code, this this basically mean we append the new tree to the array of trees we've already stored: \n    $F_{b + 1}(X) = F_{b}(X) + \\eta F_{b}(X)$\n    - Update each observation's residual by adding the predicted value to it:\n    $r_{b + 1} = r_b - \\eta F_b(X)$\n3. Our final output boosted model is simply $F(x) = \\sum_{b = 1}^B \\eta F_b(x)$, where we sum the values that each individual tree gives (times the learning rate).\n\n## Implementation\n\nHere, we will use the [Wine Quality Data Set](https://archive.ics.uci.edu/ml/datasets/Wine+Quality) to test our implementation. This [link](https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv) should download the .csv file. The task is to predict the quality of the wine (a scale of 1 ~ 10) given some of its features.\n\n\n```python\n# read in the data and shuffle the row order for model stability\nnp.random.seed(4321)\nwine_path = os.path.join('..', 'winequality-white.csv')\nwine = pd.read_csv(wine_path, sep = ';')\nwine = wine.sample(frac = 1)\n\n# train/test split the features and response column\ny = wine['quality'].values\nX = wine.drop('quality', axis = 1).values\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 1234)\n\nprint('dimension of the dataset: ', wine.shape)\nwine.head()\n```\n\n    dimension of the dataset:  (4898, 12)\n\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>fixed acidity</th>\n      <th>volatile acidity</th>\n      <th>citric acid</th>\n      <th>residual sugar</th>\n      <th>chlorides</th>\n      <th>free sulfur dioxide</th>\n      <th>total sulfur dioxide</th>\n      <th>density</th>\n      <th>pH</th>\n      <th>sulphates</th>\n      <th>alcohol</th>\n      <th>quality</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>857</th>\n      <td>8.2</td>\n      <td>0.40</td>\n      <td>0.48</td>\n      <td>13.70</td>\n      <td>0.042</td>\n      <td>59.0</td>\n      <td>169.0</td>\n      <td>0.99860</td>\n      <td>3.10</td>\n      <td>0.52</td>\n      <td>9.4</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>2325</th>\n      <td>7.0</td>\n      <td>0.35</td>\n      <td>0.17</td>\n      <td>1.10</td>\n      <td>0.049</td>\n      <td>7.0</td>\n      <td>119.0</td>\n      <td>0.99297</td>\n      <td>3.13</td>\n      <td>0.36</td>\n      <td>9.7</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>279</th>\n      <td>7.0</td>\n      <td>0.30</td>\n      <td>0.49</td>\n      <td>4.70</td>\n      <td>0.036</td>\n      <td>17.0</td>\n      <td>105.0</td>\n      <td>0.99160</td>\n      <td>3.26</td>\n      <td>0.68</td>\n      <td>12.4</td>\n      <td>7</td>\n    </tr>\n    <tr>\n      <th>1687</th>\n      <td>7.3</td>\n      <td>0.26</td>\n      <td>0.33</td>\n      <td>17.85</td>\n      <td>0.049</td>\n      <td>41.5</td>\n      <td>195.0</td>\n      <td>1.00000</td>\n      <td>3.06</td>\n      <td>0.44</td>\n      <td>9.1</td>\n      <td>7</td>\n    </tr>\n    <tr>\n      <th>531</th>\n      <td>6.4</td>\n      <td>0.18</td>\n      <td>0.48</td>\n      <td>4.00</td>\n      <td>0.186</td>\n      <td>64.0</td>\n      <td>150.0</td>\n      <td>0.99450</td>\n      <td>3.06</td>\n      <td>0.40</td>\n      <td>9.3</td>\n      <td>5</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\nclass GBMReg:\n    \"\"\"\n    regression gradient boosting machine using scikit learn's \n    decision tree as the base tree\n    \n    Parameters\n    ----------\n    n_estimators: int\n        number of trees to train\n        \n    learning_rate: float\n        learning rate, some calls it shrinkage, \n        shrinks the contribution of each tree\n        to prevent overfitting\n        \n    max_depth: int\n        controls how deep to grow the tree;\n        this is more of a decision tree parameter,\n        it is tune here to make later comparison fair\n    \n    all the other parameters for a decision tree like\n    max_features or min_sample_split also applies to GBM, \n    it is just not used here as that is more\n    related to a single decision tree\n    \"\"\"\n    def __init__(self, n_estimators, learning_rate, max_depth):\n        self.max_depth = max_depth\n        self.n_estimators = n_estimators\n        self.learning_rate = learning_rate\n\n    def fit(self, X, y):\n        self.estimators = []\n        \n        # simply use the response as the original residuals\n        # and covert it to float type to prevent error warning\n        # that it's converting from int to float\n        residual = y.astype(np.float)\n        for i in range(self.n_estimators):\n            tree = DecisionTreeRegressor(max_depth = self.max_depth)\n            tree.fit(X, residual)   \n            y_pred = tree.predict(X)\n            self.estimators.append(tree)  \n            residual -= self.learning_rate * y_pred\n            \n        return self\n            \n    def predict(self, X):\n        y_pred = np.zeros(X.shape[0])\n        for tree in self.estimators:\n            y_pred += self.learning_rate * tree.predict(X)\n            \n        return y_pred\n```\n\n\n```python\n# compare the results between a single decision tree,\n# gradient boosting, the lower the mean square\n# error, the better\ntree = DecisionTreeRegressor(max_depth = 6)\ntree.fit(X_train, y_train) \ntree_y_pred = tree.predict(X_test)\nprint( 'tree: ', mean_squared_error(y_test, tree_y_pred) )\n\n# library to confirm result\ngbm_reg = GBMReg(n_estimators = 100, learning_rate = 0.1, max_depth = 6)\ngbm_reg.fit(X_train, y_train)\ngbm_reg_y_pred = gbm_reg.predict(X_test)\nprint( 'gbm: ', mean_squared_error(y_test, gbm_reg_y_pred) )\n\n# gradient boosting for 100 trees and learning rate of 0.1\ngbm = GradientBoostingRegressor(n_estimators = 100, learning_rate = 0.1, max_depth = 6)\ngbm.fit(X_train, y_train)\ngbm_y_pred = gbm.predict(X_test)\nprint( 'gbm library: ', mean_squared_error(y_test, gbm_y_pred) )\n```\n\n    tree:  0.547700721197\n    gbm:  0.420772942612\n    gbm library:  0.422106982302\n\n\nClearly, Gradient Boosting has some similarities to Random Forests and Extra Trees: the final prediction is based on an ensemble of models, and trees are used as the base learner, so all the tuning parameters for the tree model also controls the variability of Gradient Boosting. And for interpretability we can also access the feature importance attribute.\n\n\n```python\ndef viz_importance(model, feature_names, n_features):\n    \"\"\"Visualize the relative importance of predictors\"\"\"\n    # sort the importance in decreasing order\n    importances = model.feature_importances_\n    idx = np.argsort(importances)[-n_features:]\n    names = feature_names[idx]\n    scores = importances[idx]\n    \n    y_pos = np.arange(1, n_features + 1)\n    plt.barh(y_pos, scores, color = 'lightskyblue', align = 'center')\n    plt.yticks(y_pos, names)\n    plt.xlabel('Importance')\n    plt.title('Feature Importance Plot')\n```\n\n\n```python\n# change default figure and font size\nplt.rcParams['figure.figsize'] = 8, 6 \nplt.rcParams['font.size'] = 12\nviz_importance(gbm, wine.columns[:-1], X.shape[1])\n```\n\nBut the way the ensembles are constructed differs substantially between each model. In Random Forests and Extra Trees, all trees are created independently and each tree contributes equally to the final model. The trees in Gradient Boosting, however, are dependent on past trees and contribute unequally to the final model. Despite these differences, Random Forests, Extra Trees and Gradient Boosting all offer competitive predictive performance (Gradient Boosting often wins when carefully tuned). As for computation time, Gradient Boosting is often greater than for Random Forests, Extra Trees, since their procedure can be easily parallel processed given that the trees are created independently.\n\n## Classification\n\nGradient Boosting Machine can also be extended to handle classification tasks, as we'll soon see, even in the classification context, the underlying algorithm is still a regression tree. To adapt the algorithm to a classification process, we start by defining a new loss function, cross entropy (also known as multinomial deviance), denoted as:\n\n$$L\\big(y_i, F(x_i)\\big) = -\\sum_k ^ K y_k(x_i) \\log p_k(x_i)$$\n\nThe notation above says:\n\n- We have a total of $K$ output class (categorical response variable) that ranges from $1, ..., K$\n- $y_k(x_i)$ is a dummy indicator of the response variable that takes the value of 1 if the $i_{th}$ observation belongs to class $k$ and 0 otherwise\n- $p_k(x_i)$ is the predicted probability of the $i_{th}$ observation belonging to class $k$\n\nSo the next question is how do we get $p_k(x_i)$?\n\n### Softmax\n\nSoftmax function takes an $N$-dimensional vector of arbitrary real values and produces another $N$-dimensional vector with real values in the range (0, 1) that add up to 1. The function's formula can be written as:\n\n$$p_i = \\frac{e^{o_i}}{\\sum_k^K e^{o_k}}$$\n\nFor example, in the following code chunk, we see that how the softmax function transforms a 3-element vector 1.0, 2.0, 3.0 into probabilities that sums up to 1, while still preserving the relative size of the original elements.\n\n\n```python\ndef compute_softmax(x):\n    \"\"\"compute the softmax of vector\"\"\"\n    exp_x = np.exp(x)\n    softmax = exp_x / np.sum(exp_x)\n    return softmax\n\n# this can be interpreted as the probability\n# of belonging to the three classes\ncompute_softmax([1, 2, 3])\n```\n\n\n\n\n    array([ 0.09003057,  0.24472847,  0.66524096])\n\n\n\nNext, we wish to compute the derivative of this function with respect to the input $o_i$ so we can use it later when computing the derivative of the loss function. To be explicit we wish to find:\n\n$$\\frac{\\partial p_i}{\\partial o_j} = \\frac{\\partial \\frac{e^{o_i}}{\\sum_{k=1}^{N}e^{o_k}}}{\\partial o_j}$$\n\nFor any arbitrary output $i$ and input $j$. To do so, We'll be using the quotient rule of derivatives. The rule tells us that for a function $f(x) = \\frac{g(x)}{h(x)}$:\n\n$$f'(x) = \\frac{g'(x)h(x) - h'(x)g(x)}{[h(x)]^2}$$\n\nIn our case, we have:\n\n\\begin{align*}\ng &= e^{o_i} \\nonumber \\\\\nh &= \\sum_{k=1}^{K}e^{o_k} \\nonumber\n\\end{align*}\n\nIt's important to notice that no matter which $o_j$ we compute the derivative of $h$ for the output will always be $e^{o_j}$. Howewer, this is not the case for $g$. It's derivative will be $e^{o_j}$ only if $i = j$, because only then will it have the term $e^{o_j}$. Otherwise, the derivative is simply 0 (because it's simply taking the derivative of a constant).\n\nSo going back to using our quotient rule, we start with the $i = j$ case. In the following derivation we'll use the $\\Sigma$ (Sigma) sign to represent $\\sum_{k=1}^{K}e^{o_k}$ for simplicity and to prevent cluttering up the notation.\n\n\\begin{align*}\n\\frac{\\partial \\frac{e^{o_i}}{\\sum_{k = 1}^{N} e^{o_k}}}{\\partial o_j} \n&= \\frac{e^{o_i}\\Sigma-e^{o_j}e^{o_i}}{\\Sigma^2} \\nonumber \\\\\n&= \\frac{e^{o_i}}{\\Sigma}\\frac{\\Sigma - e^{o_j}}{\\Sigma} \\nonumber \\\\\n&= p_i(1 - p_j) \\nonumber \\\\\n&= p_i(1 - p_i) \\nonumber\n\\end{align*}\n\nThe reason we can perform the operation in the last line is because we're considering the scenario where $i = j$. Similarly we can do the case where $i \\neq j$.\n\n\\begin{align*}\n\\frac{\\partial \\frac{e^{o_i}}{\\sum_{k = 1}^{N} e^{o_k}}}{\\partial o_j} \n&= \\frac{0-e^{o_j}e^{o_i}}{\\Sigma^2} \\nonumber \\\\\n&= -\\frac{e^{o_j}}{\\Sigma}\\frac{e^{o_i}}{\\Sigma} \\nonumber \\\\\n&= -p_j p_i \\nonumber \\\\\n&= -p_i p_j \\nonumber\n\\end{align*}\n\nJust to sum it up, we now have:\n\n$$\\frac{\\partial p_i}{\\partial o_j} = p_i(1 - p_i),\\quad i = j$$\n\n$$\\frac{\\partial p_i}{\\partial o_j} = -p_i p_j,\\quad i \\neq j$$\n\nGiven this, we can tie this back to the original loss function $-\\sum_k^K y_k \\log p_k \\nonumber \\\\$ and compute it's negative gradient.\n\n\\begin{align}\n\\frac{\\partial L}{\\partial o_i} \n&= -\\sum_k y_k\\frac{\\partial \\log p_k}{\\partial o_i} \\nonumber \\\\\n&= -\\sum_k y_k\\frac{1}{p_k}\\frac{\\partial p_k}{\\partial o_i} \\nonumber \\\\\n&= -y_i(1-p_i) - \\sum_{k \\neq i}y_k\\frac{1}{p_k}(-p_kp_i) \\nonumber \\\\\n&= -y_i(1 - p_i) + \\sum_{k \\neq i}y_k(p_i) \\nonumber \\\\\n&= -y_i + y_i p_i + \\sum_{k \\neq i}y_k(p_i) \\nonumber \\\\\n&= p_i\\left(\\sum_ky_k\\right) - y_i \\nonumber \\\\\n&= p_i - y_i \\nonumber\n\\end{align} \n\nRemember $\\sum_ky_k=1$ (as $y$ is a vector with only one non-zero element, which is $1$ when the indicating the observation belongs to the $k_{th}$ class. \n\nAfter a long journey, we now see, for every class $k$, the gradient is the difference between the associated dummy variable and the predicted probability of belonging to that class. This is essentially the \"residuals\" from the classification gradient boosting. Given this, we can now implement the algorithm, the overall process of training a regression tree has still not changed, only now we must deal with the dummy variables, $y_k$ and fit a regression tree on the negative gradient for each dummy variable.\n\n## Implementation\n\nFor the dataset, we'll still use the Wine Quality Data Set that was used for the regression task, except we now treat the quality of the wine (a scale of 1 ~ 10) as categorical instead of numeric.\n\n\n```python\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\n```\n\n\n```python\nclass GBMClass:\n    \"\"\"\n    classification gradient boosting machine using scikit learn's \n    decision tree as the base tree\n    \n    Parameters\n    ----------\n    n_estimators: int\n        number of trees to train\n        \n    learning_rate: float\n        learning rate, some calls it shrinkage, \n        shrinks the contribution of each tree\n        to prevent overfitting\n        \n    max_depth: int\n        controls how deep to grow the tree;\n        this is more of a decision tree parameter,\n        it is tune here to make later comparison fair\n    \n    all the other parameters for a decision tree like\n    max_features or min_sample_split also applies to GBM, \n    it is just not used here as that is more\n    related to a single decision tree\n    \"\"\"\n    def __init__(self, n_estimators, learning_rate, max_depth):\n        self.max_depth = max_depth\n        self.n_estimators = n_estimators\n        self.learning_rate = learning_rate\n\n    def fit(self, X, y):\n        # encode labels with value between 0 and n_classes - 1,\n        # so we can easily one-hot encode them\n        self.le = LabelEncoder()\n        labels = self.le.fit_transform(y)\n        Y = self._to_categorical(labels)\n        del labels\n        \n        # the predicted probability starts out with \n        # a value that's uniform over all classes;\n        # then we compute the residuals (negative gradient),\n        # which is the difference between the predicted\n        # probability and the class label\n        y_proba = np.full( Y.shape, 1 / Y.shape[1] ) \n        residuals = Y - y_proba\n        \n        # train a base decision tree on the residuals\n        # for every single class, hence we end up with\n        # n_estimators * n_classes base tree models\n        self.estimators = []\n        for i in range(self.n_estimators):\n            for j in range(self.n_classes): \n                tree = DecisionTreeRegressor(max_depth = self.max_depth)\n                tree.fit(X, residuals[:, j])   \n                y_pred = tree.predict(X)\n                self.estimators.append(tree)  \n                residuals[:, j] -= self.learning_rate * y_pred\n                \n        return self\n            \n    def _to_categorical(self, y):\n        \"\"\"one hot encode class vector y\"\"\"\n        self.n_classes = np.amax(y) + 1\n        Y = np.zeros(( y.shape[0], self.n_classes ))\n        for i in range(y.shape[0]):\n            Y[i, y[i]] = 1.0\n\n        return Y\n    \n    def predict(self, X):\n        # after predicting the class remember to\n        # transform it back to the actual class label\n        y_prob = self.predict_proba(X)\n        y_pred = np.argmax(y_prob, axis = 1)\n        y_pred = self.le.inverse_transform(y_pred)\n        return y_pred\n    \n    def predict_proba(self, X):\n        # add up raw score for every class and convert\n        # it to probability using softmax\n        y_raw = np.zeros(( X.shape[0], self.n_classes ))\n\n        # obtain the tree for each class and add up the prediction\n        for c in range(self.n_classes):\n            class_tree = self.estimators[c::self.n_classes]\n            for tree in class_tree:\n                y_raw[:, c] += self.learning_rate * tree.predict(X)\n        \n        y_proba = self._compute_softmax(y_raw)\n        return y_proba\n    \n    def _compute_softmax(self, z):\n        \"\"\"\n        compute the softmax of matrix z in a numerically stable way,\n        by substracting each row with the max of each row\n        \"\"\"\n        shift_z = z - np.amax(z, axis = 1, keepdims = 1)\n        exp_z = np.exp(shift_z)\n        softmax = exp_z / np.sum(exp_z, axis = 1, keepdims = 1)\n        return softmax    \n```\n\n\n```python\n# compare the results between a single decision tree,\n# gradient boosting, the higher the accuracy, the better\ntree = DecisionTreeClassifier(max_depth = 6)\ntree.fit(X_train, y_train) \ntree_y_pred = tree.predict(X_test)\nprint( 'tree: ', accuracy_score(y_test, tree_y_pred) )\n\n# gradient boosting for 150 trees and learning rate of 0.2\n# unlike random forest, gradient boosting's base tree can be shallower\n# meaning that there depth can be smaller\ngbm_class = GBMClass(n_estimators = 150, learning_rate = 0.2, max_depth = 3)\ngbm_class.fit(X_train, y_train)\ngbm_class_y_pred = gbm_class.predict(X_test)\nprint( 'gbm: ', accuracy_score(y_test, gbm_class_y_pred) )\n\n# library to confirm results are comparable\ngbm = GradientBoostingClassifier(n_estimators = 150, learning_rate = 0.2, max_depth = 3)\ngbm.fit(X_train, y_train)\ngbm_y_pred = gbm.predict(X_test)\nprint( 'gbm library: ', accuracy_score(y_test, gbm_y_pred) )\n```\n\n    tree:  0.54387755102\n    gbm:  0.601020408163\n    gbm library:  0.616326530612\n\n\n## Understanding Model Complexity\n\nIn the following section, we generate a Sinoide function + random gaussian noise, with 80 training samples (blue points) and 20 test samples (red points).\n\n\n```python\ndef ground_truth(x):\n    \"\"\"Ground truth -- function to approximate\"\"\"\n    return x * np.sin(x) + np.sin(2 * x)\n\ndef gen_data(low, high, n_samples):\n    \"\"\"generate training and testing data from the ground truth function\"\"\"\n    np.random.seed(15)\n    X = np.random.uniform(low, high, size = n_samples)\n    \n    # generate the response from the ground truth function and add\n    # some random noise to it\n    y = ground_truth(X) + np.random.normal(scale = 2, size = n_samples)\n    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 3)\n    return X_train, X_test, y_train, y_test\n\ndef plot_data(x_plot, X_train, X_test, y_train, y_test):\n    \"\"\"plot training and testing data\"\"\"\n    s = 20\n    alpha = 0.4\n    plt.plot(x_plot, ground_truth(x_plot), alpha = alpha, label = 'ground truth')\n    plt.scatter(X_train, y_train, s = s, alpha = alpha)\n    plt.scatter(X_test, y_test, s = s, alpha = alpha, color = 'red')\n    plt.xlim(( 0, 10 ))\n    plt.ylabel('y')\n    plt.xlabel('x')\n    plt.legend(loc = 'upper left')\n    plt.show()\n```\n\n\n```python\nlow = 0\nhigh = 10\nx_plot = np.linspace(low, high, 500)\nX_train, X_test, y_train, y_test = gen_data(low = low, high = high, n_samples = 100)\nplot_data(x_plot, X_train, X_test, y_train, y_test)\n```\n\nRecall that in a single regression tree, we can use the `max_depth` parameter to control how deep to grow the tree and the deeper the tree the more variance can be explained.\n\n\n```python\n# when using scikit-learn, the training data has to be\n# a 2d-array even if it only has 1 features\ntree1 = DecisionTreeRegressor(max_depth = 1)\ntree1.fit(X_train[:, np.newaxis], y_train)\ntree2 = DecisionTreeRegressor(max_depth = 3)\ntree2.fit(X_train[:, np.newaxis], y_train)\n\nplt.plot(x_plot, tree1.predict(x_plot[:, np.newaxis]),\n         label = 'RT max_depth=1', color = 'g', alpha = 0.9, linewidth = 2)\nplt.plot(x_plot, tree2.predict(x_plot[:, np.newaxis]),\n         label = 'RT max_depth=3', color = 'g', alpha = 0.7, linewidth = 1)\nplot_data(x_plot, X_train, X_test, y_train, y_test)\n```\n\nThe plot above shows that the decision boundaries made by decision trees are always perpendicular to $x$ and $y$ axis (due to the fact that they consists of nested if-else statements). Let's see what happens when we use gradient boosting without tuning the parameters (by specifying a fix `max_depth`).\n\n\n```python\ngbm = GradientBoostingRegressor(n_estimators = 300, max_depth = 6, learning_rate = 0.1)\ngbm.fit(X_train[:, np.newaxis], y_train)\n\nplt.plot(x_plot, gbm.predict(x_plot[:, np.newaxis]),\n         label = 'GBM max_depth=6', color = 'r', alpha = 0.9, linewidth = 2)\nplot_data(x_plot, X_train, X_test, y_train, y_test)\n```\n\nHopefully, it should be clear that compared with decision trees, gradient boosting machine is far more susceptible to overfitting the training data, hence it is common to tune parameters including `max_depth`, `max_features`, `min_samples_leaf`, `subsample` (explained below) to reduce the overfitting phenomenon from  occurring.\n\nThe parameter `subsample` (technically called *stochastic gradient boosting*) borrows some idea from bagging techniques. What it does is: while iterating through each individual tree building process, it randomly select a fraction of the training data. Then the residuals and models in the remaining steps of the current iteration are based only on that sample of data. It turns out that this simple modification improved the predictive accuracy of boosting while also reducing the required computational resources (of course, this is based on the fact that you have enough observations to subsample).\n\nThe following section tunes the commonly tuned parameter and find the best one and draws the decision boundary. The resulting plot should be self-explanatory.\n\n\n```python\nparam_grid = {\n    'max_depth': [4, 6],\n    'min_samples_leaf': [3, 5, 8],\n    'subsample': [0.9, 1]\n    # 'max_features': [1.0, 0.3, 0.1] # not possible in this example (there's only 1)\n}\ngs_gbm = GridSearchCV(gbm, param_grid, scoring = 'neg_mean_squared_error', n_jobs = 4)\ngs_gbm.fit(X_train[:, np.newaxis], y_train)\nprint('Best hyperparameters: %r' % gs_gbm.best_params_)\n\nplt.plot(x_plot, gs_gbm.predict(x_plot[:, np.newaxis]),\n         label = 'GBM tuned', color = 'r', alpha = 0.9, linewidth = 2)\nplot_data(x_plot, X_train, X_test, y_train, y_test)\n```\n\n# Reference\n\n- [Slide: Gradent boosting](http://eric.univ-lyon2.fr/~ricco/cours/slides/en/gradient_boosting.pdf)\n- [Slide: A gentle introduction to gradient boosting](http://www.ccs.neu.edu/home/vip/teach/MLcourse/4_boosting/slides/gradient_boosting.pdf)\n- [Blog: The Softmax function and its derivative](http://eli.thegreenplace.net/2016/the-softmax-function-and-its-derivative/)\n- [Notebook: Regression Trees and Rule-Based Models](http://nbviewer.jupyter.org/github/leig/Applied-Predictive-Modeling-with-Python/blob/master/notebooks/Chapter%208.ipynb)\n- [Notebook: Gradient Boosted Regression Trees in scikit-learn](http://nbviewer.jupyter.org/github/pprett/pydata-gbrt-tutorial/blob/master/gbrt-tutorial.ipynb)\n- [StackExchange: Derivative of Softmax loss function](http://math.stackexchange.com/questions/945871/derivative-of-softmax-loss-function)\n- [StackExchange: How are individual trees added together in boosted regression tree?](http://stats.stackexchange.com/questions/135378/how-are-individual-trees-added-together-in-boosted-regression-tree)\n", "meta": {"hexsha": "d24c2d065cdc91af712bb2623f83e016c6fe3ea2", "size": 244266, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "trees/gbm/gbm.ipynb", "max_stars_repo_name": "awesome-archive/machine-learning", "max_stars_repo_head_hexsha": "8494f3fe73db511f7b97d082c786097bfbe71463", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trees/gbm/gbm.ipynb", "max_issues_repo_name": "awesome-archive/machine-learning", "max_issues_repo_head_hexsha": "8494f3fe73db511f7b97d082c786097bfbe71463", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trees/gbm/gbm.ipynb", "max_forks_repo_name": "awesome-archive/machine-learning", "max_forks_repo_head_hexsha": "8494f3fe73db511f7b97d082c786097bfbe71463", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 178.9494505495, "max_line_length": 53400, "alphanum_fraction": 0.8596366256, "converted": true, "num_tokens": 10187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09670578288273966, "lm_q2_score": 0.06097518001176593, "lm_q1q2_score": 0.005896652519453803}}
{"text": "```python\n# code for loading the format for the notebook\nimport os\n\n# path : store the current path to convert back to it later\npath = os.getcwd()\nos.chdir( os.path.join('..', 'notebook_format') )\nfrom formats import load_style\nload_style(css_style = 'custom2.css')\n```\n\n\n\n\n\n<style>\n    html {\n        font-size: 18px !important;\n    }\n\n    body {\n        background-color: #FFF !important;\n        font-weight: 1rem;\n        font-family: 'Source Sans Pro', \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n    }\n\n    body .notebook-app {\n        background-color: #FFF !important;\n    }\n\n    #header {\n        box-shadow: none !important;\n    }\n\n    #notebook {\n        padding-top: 0px;\n    }\n\n    #notebook-container {\n        box-shadow: none;\n        -webkit-box-shadow: none;\n        padding: 10px;\n    }\n\n    div.cell {\n        width: 1000px;\n        margin-left: 0% !important;\n        margin-right: auto;\n    }\n\n    div.cell.selected {\n        border: 1px dashed #CCCCCC;\n    }\n\n    .edit_mode div.cell.selected {\n        border: 1px dashed #828282;\n    }\n\n    div.output_wrapper {\n        margin-top: 8px;\n    }\n\n    a {\n        color: #383838;\n    }\n\n    code,\n    kbd,\n    pre,\n    samp {\n        font-family: 'Menlo', monospace !important;\n        font-size: 0.75rem !important;\n    }\n\n    h1 {\n        font-size: 2rem !important;\n        font-weight: 500 !important;\n        letter-spacing: 3px !important;\n        text-transform: uppercase !important;\n    }\n\n    h2 {\n        font-size: 1.8rem !important;\n        font-weight: 400 !important;\n        letter-spacing: 3px !important;\n        text-transform: none !important;\n    }\n\n    h3 {\n        font-size: 1.5rem !important;\n        font-weight: 400 !important;\n        font-style: italic !important;\n        display: block !important;\n    }\n\n    h4,\n    h5,\n    h6 {\n        font-size: 1rem !important;\n        font-weight: 400 !important;\n        display: block !important;\n    }\n\n    .prompt {\n        font-family: 'Menlo', monospace !important;\n        font-size: 0.75rem;\n        text-align: right;\n        line-height: 1.21429rem;\n    }\n\n    /* INTRO PAGE */\n\n    .toolbar_info,\n    .list-container {\n        ;\n    }\n    /* NOTEBOOK */\n\n    div#header-container {\n        display: none !important;\n    }\n\n    div#notebook {\n        border-top: none;\n        font-size: 1rem;\n    }\n\n    div.input_prompt {\n        color: #C74483;\n    }\n\n    .code_cell div.input_prompt:after,\n    div.output_prompt:after {\n        content: '\\25b6';\n    }\n\n    div.output_prompt {\n        color: #2B88D9;\n    }\n\n    div.input_area {\n        border-radius: 0px;\n        border: 1px solid #d8d8d8;\n    }\n\n    div.output_area pre {\n        font-weight: normal;\n    }\n\n    div.output_subarea {\n        font-weight: normal;\n    }\n\n    .rendered_html pre,\n    .rendered_html table,\n    .rendered_html th,\n    .rendered_html tr,\n    .rendered_html td {\n        border: 1px #828282 solid;\n        font-size: 0.75rem;\n        font-family: 'Menlo', monospace;\n    }\n\n    .rendered_html th,\n    .rendered_html tr,\n    .rendered_html td {\n        padding: 5px 10px;\n    }\n\n    .rendered_html th {\n        font-weight: normal;\n        background: #f8f8f8;\n    }\n\n    a:link{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:visited{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:hover{\n       font-weight: bold;\n       color: #1d3b84;\n    }\n    a:focus{\n       font-weight: bold;\n       color:#447adb;\n    }\n    a:active{\n       font-weight: bold;\n       color:#447adb;\n    }\n    .rendered_html :link {\n       text-decoration: underline; \n    }\n\n    div.output_html {\n        font-weight: 1rem;\n        font-family: 'Source Sans Pro', \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n    }\n\n    table.dataframe tr {\n        border: 1px #CCCCCC;\n    }\n\n    div.cell.selected {\n        border-radius: 0px;\n    }\n\n    div.cell.edit_mode {\n        border-radius: 0px;\n        border: thin solid #CF5804;\n    }\n\n    span.ansiblue {\n        color: #00A397;\n    }\n\n    span.ansigray {\n        color: #d8d8d8;\n    }\n\n    span.ansigreen {\n        color: #688A0A;\n    }\n\n    span.ansipurple {\n        color: #975DDE;\n    }\n\n    span.ansired {\n        color: #D43132;\n    }\n\n    span.ansiyellow {\n        color: #D9AA00;\n    }\n\n    div.output_stderr {\n        background-color: #D43132;\n    }\n\n    div.output_stderr pre {\n        color: #e8e8e8;\n    }\n\n    .cm-s-ipython.CodeMirror {\n        background: #F8F8F8;\n    }\n\n    .cm-s-ipython div.CodeMirror-selected {\n        background: #e8e8e8 !important;\n    }\n\n    .cm-s-ipython .CodeMirror-gutters {\n        background: #F8F8F8;\n        border-right: 0px;\n    }\n\n    .cm-s-ipython .CodeMirror-linenumber {\n        color: #b8b8b8;\n    }\n\n    .cm-s-ipython .CodeMirror-cursor {\n        border-left: 1px solid #585858 !important;\n    }\n\n    .cm-s-ipython span.cm-atom {\n        color: #C74483;\n    }\n\n    .cm-s-ipython span.cm-number {\n        color: #C74483;\n    }\n\n    .cm-s-ipython span.cm-property,\n    .cm-s-ipython span.cm-attribute {\n        color: #688A0A;\n    }\n\n    .cm-s-ipython span.cm-keyword {\n        font-weight: normal;\n        color: #D43132;\n    }\n\n    .cm-s-ipython span.cm-string {\n        color: #D9AA00;\n    }\n\n    .cm-s-ipython span.cm-operator {\n        font-weight: normal;\n    }\n\n    .cm-s-ipython span.cm-builtin {\n        color: #2B88D9;\n    }\n\n    .cm-s-ipython span.cm-variable {\n        color: #00A397;\n    }\n\n    .cm-s-ipython span.cm-variable-2 {\n        color: #2B88D9;\n    }\n\n    .cm-s-ipython span.cm-def {\n        color: #00A397;\n    }\n\n    .cm-s-ipython span.cm-error {\n        background: #FFBDBD;\n        color: #D43132;\n    }\n\n    .cm-s-ipython span.cm-tag {\n        color: #D43132;\n    }\n\n    .cm-s-ipython span.cm-link {\n        color: #975DDE;\n    }\n\n    .cm-s-ipython .CodeMirror-matchingbracket {\n        text-decoration: underline;\n         !important;\n    }\n</style>\n\n\n\n\n\n\n```python\nos.chdir(path)\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# 1. magic for inline plot\n# 2. magic to print version\n# 3. magic so that the notebook will reload external python modules\n%matplotlib inline\n%load_ext watermark\n%load_ext autoreload \n%autoreload 2\n\nimport sys\nfrom math import ceil\nfrom tqdm import trange\nfrom subprocess import call\nfrom itertools import islice\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.preprocessing import normalize\nfrom sklearn.neighbors import NearestNeighbors\nfrom scipy.sparse import csr_matrix, dok_matrix\n\n%watermark -a 'Ethen' -d -t -v -p numpy,pandas,matplotlib,scipy,sklearn,tqdm\n```\n\n    Ethen 2017-03-31 20:22:16 \n    \n    CPython 3.5.2\n    IPython 5.3.0\n    \n    numpy 1.12.1\n    pandas 0.19.2\n    matplotlib 2.0.0\n    scipy 0.19.0\n    sklearn 0.18\n    tqdm 4.11.2\n\n\nIf you are new to the field recommendation system, please make sure you understand the basics of matrix factorizaion in this [other documentation](http://nbviewer.jupyter.org/github/ethen8181/machine-learning/blob/master/recsys/1_ALSWR.ipynb). \n\n# Bayesian Personalized Ranking\n\nRecall that when doing matrix factorization for implicit feedback data (users' clicks, view times), we start with a user-item matrix, $R$ where nonzero elements of the matrix are the users' interaction with the items. And what matrix factorization does is it decomposes a large matrix into products of matrices, namely, $R=U\u00d7V$.\n\n\n\nMatrix factorization assumes that:\n\n- Each user can be described by $d$ features. For example, feature 1 might be a referring to how much each user likes disney movies.\n- Each item, movie in this case, can be described by an analagous set of $d$ features. To correspond to the above example, feature 1 for the movie might be a number that says how close the movie is to a disney movie.\n\nWith that notion in mind, we can denote our $d$ feature user into math by letting a user $u$ take the form of a $1 \\times d$-dimensional vector $\\textbf{x}_{u}$. Similarly, an item *i* can be represented by a $1 \\times d$-dimensional vector $\\textbf{y}_{i}$. And we would predict the interactions that the user $u$ will have for item $i$ is by doing a dot product of the two vectors\n\n\\begin{align}\n\\hat r_{ui} &= \\textbf{x}_{u} \\textbf{y}_{i}^{T} = \\sum\\limits_{d} x_{ud}y_{di}\n\\end{align}\n\nWhere $\\hat r_{ui}$ represents our prediction for the true interactions $r_{ui}$. Next, we will choose a objective function to minimize the square of the difference between all interactions in our dataset ($S$) and our predictions. This produces a objective function of the form:\n\n\\begin{align}\nL &= \\sum\\limits_{u,i \\in S}( r_{ui} - \\textbf{x}_{u} \\textbf{y}_{i}^{T} )^{2}\n\\end{align}\n\nThis is all well and good, but a lot of times, what we wish to optimize for is not the difference between the true interaction and the predicted interaction, but instead is the ranking of the items. Meaning given a user, what is the top-N most likely item that the user prefers. And this is what **Bayesian Personalized Ranking (BPR)** tries to accomplish. The idea is centered around sampling positive (items user has interacted with) and negative (items user hasn't interacted with) items and running pairwise comparisons.\n\n## Formulation\n\nSuppose $U$ is the set of all users and $I$ is the set of all items, our goal is to provide user $u$ with a personalized ranking, deonted by $>_u$. As mentioned in the last section, the usual approach for item recommenders is to predict a personalized score $\\hat r_{ui}$ for an item that reflects the user's preference for that item. Then the items are ranked by sorting them according to that score and the top-N is recommended to the user. \n\nHere we'll use a different approach by using item pairs as training data and optimize for correctly ranking item pairs. From $S$, the whole dataset we try to reconstruct for each user parts of $>_u$. If the user has interacted with item $i$, i.e. $(u,i) \\in S$, then we assume that the user prefers this item over all other non-observed items. E.g. in the figure below user $u_1$ has interacted with item $i_2$ but not item $i_1$, so we assume that this user prefers item $i_2$ over $i_1$: $i_2 >_u i_1$. We will denote this generally as $i >_u j$, where the $i$ stands for the positive item and $j$ is for the negative item. For items that the user have both interacted with, we cannot infer any preference. The same is true for two items that a user has not interacted yet (e.g. item $i_1$ and $i_4$ for user $u_1$).\n\n\n\nGiven these information, we can now get to the Bayesian part of this method. Let $\\Theta$ be the parameter of the model that determines the personalized ranking. BPR's goal is to maximize the posterior probability:\n\n\\begin{align}\np(\\Theta | i >_u j ) \\propto p( i >_u j |\\Theta) p(\\Theta)\n\\end{align}\n\n$p( i >_u j |\\Theta)$ is the likelihood function, it captures the individual probability that a user really prefers item $i$ over item $j$. We compute this probability with the form:\n\n\\begin{align}\np( i >_u j |\\Theta) = \\sigma \\big(\\hat r_{uij}(\\Theta) \\big)\n\\end{align}\n\nWhere: $\\sigma$ is the good old logistic sigmoid:\n\n\\begin{align}\n\\sigma(x) = \\frac{1}{1 + e^{-x}}\n\\end{align}\n\nAnd $r_{uij}(\\Theta)$ captures the relationship between user $u$, item $i$ and item $j$, which can be further decomposed into:\n\n\\begin{align}\n\\hat r_{uij} = \\hat r_{ui} - \\hat r_{uj}\n\\end{align}\n\nFor convenience we skiped the argument $\\Theta$ from $\\hat r_{uij}$. The formula above is basically saying what is the difference between the predicted interaction between the positive item $i$ and the negative item $j$. Now because of this generic framework, we can apply any standard collaborative filtering (such as the matrix factorization) techniques that can predict the interaction between user and item. Keep in mind that although it may seem like we're using the same models as in other work, here we're optimizing against another criterion as we do not try to predict a single predictor $\\hat r_{ui}$ but instead tries to classify the difference of two predictions $\\hat r_{ui} - \\hat r_{uj}$. For those that interested in diving deeper, there's a section in the original paper that showed that the BPR optimization criteria is actually optimizing AUC (Area Under the ROC curve).\n\nSo far, we have only discussed the likelihood function. In order to complete the Bayesian modeling approach of the personalized ranking task, we introduce a general prior density $p(\\Theta)$ which is a normal distribution with zero mean and variance-covariance matrix $\\Sigma (\\Theta)$, to reduce the number of unknown hyperparameters, we set: $\\Sigma (\\Theta) = \\lambda_{\\Theta} I$\n\nTo sum it all up, the full form of the maximum posterior probability optimization (called BPR-Opt in the paper) can be specified as:\n\n\\begin{align}\nBPR-Opt &\\implies \\prod_{u, i, j} p( i >_u j |\\Theta) p(\\Theta) \\\\\n&\\implies ln \\big( \\prod_{u, i, j} p( i >_u j |\\Theta) p(\\Theta) \\big) \\\\\n&\\implies \\sum_{u, i, j} ln  \\sigma \\big(\\hat r_{ui} - \\hat r_{uj} \\big) + ln  p(\\Theta) \\\\\n&\\implies \\sum_{u, i, j} ln  \\sigma \\big(\\hat r_{ui} - \\hat r_{uj} \\big) \n- \\lambda_{\\Theta} \\left\\Vert \\Theta \\right\\Vert ^{2} \\\\\n&\\implies \\sum_{u, i, j} ln  \\sigma \\big(\\hat r_{ui} - \\hat r_{uj} \\big) \n- \\frac{\\lambda_{\\Theta}}{2} \\left\\Vert x_u \\right\\Vert ^{2} \n- \\frac{\\lambda_{\\Theta}}{2} \\left\\Vert y_i \\right\\Vert ^{2} \n- \\frac{\\lambda_{\\Theta}}{2} \\left\\Vert y_j \\right\\Vert ^{2} \\\\\n&\\implies \\sum_{u, i, j} ln  \\sigma \\big( x_u y_i^T - x_u y_j^T \\big) \n- \\frac{\\lambda_{\\Theta}}{2} \\left\\Vert x_u \\right\\Vert ^{2} \n- \\frac{\\lambda_{\\Theta}}{2} \\left\\Vert y_i \\right\\Vert ^{2} \n- \\frac{\\lambda_{\\Theta}}{2} \\left\\Vert y_j \\right\\Vert ^{2} \\\\\n&\\implies \\sum_{u, i, j} ln  \\frac{1}{1 + e^{-(x_u y_i^T - x_u y_j^T) }}\n- \\frac{\\lambda_{\\Theta}}{2} \\left\\Vert x_u \\right\\Vert ^{2} \n- \\frac{\\lambda_{\\Theta}}{2} \\left\\Vert y_i \\right\\Vert ^{2} \n- \\frac{\\lambda_{\\Theta}}{2} \\left\\Vert y_j \\right\\Vert ^{2}\n\\end{align}\n\n\nWhere:\n\n- We first take the natural log (it's a monotonic transformation, meaning taking the log does not affect the optimization process) to make the product a sum to make life easier on us\n- As for the $p(\\Theta)$ part, recall that because for each parameter we assume that it's a normal distribution with mean zero ($\\mu = 0$), and unit variance ($\\Sigma = I$, we ignore the $\\lambda_{\\Theta}$ for now), the formula for it is:\n\n\\begin{align}\nN(x \\mid \\mu, \\Sigma) \n&\\implies \\frac{1}{(2\\pi)^{d/2}\\sqrt{|\\Sigma|}} exp(-\\frac{1}{2}(x-\\mu)^{T}\\Sigma^{-1}(x-\\mu)) \\\\\n&\\implies \\frac{1}{(2\\pi)^{d/2}} exp(-\\frac{1}{2}\\Theta^{T}\\Theta)\n\\end{align}\n\nIn the formula above, the only thing that depends on $\\Theta$ is the $exp(-\\frac{1}{2}\\Theta^{T}\\Theta)$ part on the right, the rest is just a multiplicative constant that we don't need to worry about, thus if we take the natural log of that formula, then the exponential goes away and our $p(\\Theta)$ can be written as $- \\frac{1}{2} \\left\\Vert \\Theta \\right\\Vert ^{2}$, and we simply multiply the $\\lambda_{\\Theta}$ back, which can be seen as the model specific regularization parameter.\n\nLast but not least, in machine learning it's probably more common to try and minimize things, thus we simply flip all the signs of the maximization formula above, leaving us with:\n\n\\begin{align}\nargmin_{x_u, y_i, y_j} \\sum_{u, i, j} -ln \\frac{1}{1 + e^{-(x_u y_i^T - x_u y_j^T) }}\n+ \\frac{\\lambda_{\\Theta}}{2} \\left\\Vert x_u \\right\\Vert ^{2} \n+ \\frac{\\lambda_{\\Theta}}{2} \\left\\Vert y_i \\right\\Vert ^{2} \n+ \\frac{\\lambda_{\\Theta}}{2} \\left\\Vert y_j \\right\\Vert ^{2}\n\\end{align}\n\n## Optimization\n\nIn the last section we have derived an optimization criterion for personalized ranking. As the criterion is differentiable, gradient descent based algorithms are an obvious choice for maximization. But standard gradient descent is probably not the right choice for our problem given the size of all the possible combinations of the triplet $(u, i, j)$. To solve for this issue we use a stochastic gradient descent algorithm that chooses the triplets randomly (uniformly distributed and bootstrapped sampled).\n\nTo solve for the function using gradient descent, we derive the gradient for the three parameters $x_u$, $y_i$, $y_j$ separately. Just a minor hint when deriving the gradient, remember that the first part of the formula requires the chain rule:\n\n\\begin{align}\n\\dfrac{\\partial}{\\partial x} ln \\sigma(x) \n&\\implies \\dfrac{1}{\\sigma(x)} \\dfrac{\\partial}{\\partial x} \\sigma(x) \\\\\n&\\implies \\left( 1 + e^{-x} \\right) \\dfrac{\\partial}{\\partial x} \\sigma(x) \\\\\n&\\implies \\left( 1 + e^{-x} \\right) \\dfrac{\\partial}{\\partial x} \\left[ \\dfrac{1}{1 + e^{-x}} \\right] \\\\\n&\\implies \\left( 1 + e^{-x} \\right) \\dfrac{\\partial}{\\partial x} \\left( 1 + \\mathrm{e}^{-x} \\right)^{-1} \\\\\n&\\implies \\left( 1 + e^{-x} \\right) \\cdot -(1 + e^{-x})^{-2}(-e^{-x}) \\\\\n&\\implies \\left( 1 + e^{-x} \\right) \\dfrac{e^{-x}}{\\left(1 + e^{-x}\\right)^2} \\\\\n&\\implies \\dfrac{e^{-x}}{1 + e^{-x}}\n\\end{align}\n\n---\n\n\\begin{align}\n\\dfrac{\\partial}{\\partial x_u}\n&\\implies \\dfrac{e^{-(x_u y_i^T - x_u y_j^T)}}{1 + e^{-(x_u y_i^T - x_u y_j^T)}} \\cdot (y_j - y_i) + \\lambda x_u\n\\end{align}\n\n\\begin{align}\n\\dfrac{\\partial}{\\partial y_i}\n&\\implies \\dfrac{e^{-(x_u y_i^T - x_u y_j^T)}}{1 + e^{-(x_u y_i^T - x_u y_j^T)}} \\cdot -y_i + \\lambda y_i\n\\end{align}\n\n\\begin{align}\n\\dfrac{\\partial}{\\partial y_j}\n&\\implies \\dfrac{e^{-(x_u y_i^T - x_u y_j^T)}}{1 + e^{-(x_u y_i^T - x_u y_j^T)}} \\cdot y_j + \\lambda y_j\n\\end{align}\n\nAfter deriving the gradient the update for each parameter using gradient descent is simply:\n\n\\begin{align}\n\\Theta & \\Leftarrow \\Theta - \\alpha \\dfrac{\\partial}{\\partial \\Theta}\n\\end{align}\n\nWhere $\\alpha$ is the learning rate.\n\n# Implementation\n\nWe will again use the movielens data as an example.\n\n\n```python\nfile_dir = 'ml-100k'\nfile_path = os.path.join(file_dir, 'u.data')\nif not os.path.isdir(file_dir):\n    call(['curl', '-O', 'http://files.grouplens.org/datasets/movielens/' + file_dir + '.zip'])\n    call(['unzip', file_dir + '.zip'])\n\n# we will not be using the timestamp column\nnames = ['user_id', 'item_id', 'rating', 'timestamp']\ndf = pd.read_csv(file_path, sep = '\\t', names = names)\nprint('data dimension: \\n', df.shape)\ndf.head()\n```\n\n    data dimension: \n     (100000, 4)\n\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>user_id</th>\n      <th>item_id</th>\n      <th>rating</th>\n      <th>timestamp</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>196</td>\n      <td>242</td>\n      <td>3</td>\n      <td>881250949</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>186</td>\n      <td>302</td>\n      <td>3</td>\n      <td>891717742</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>22</td>\n      <td>377</td>\n      <td>1</td>\n      <td>878887116</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>244</td>\n      <td>51</td>\n      <td>2</td>\n      <td>880606923</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>166</td>\n      <td>346</td>\n      <td>1</td>\n      <td>886397596</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nBecause BPR assumes binary implicit feedback (meaing there's only positive and negative items), here we'll assume that an item is positive only if he/she gave the item a ratings above 3 (feel free to experiment and change the threshold). The next few code chunks, creates the sparse interaction matrix and split into train and test set.\n\n\n```python\ndef create_matrix(data, users_col, items_col, ratings_col, threshold = None):\n    \"\"\"\n    creates the sparse user-item interaction matrix,\n    if the data is not in the format where the interaction only\n    contains the positive items (indicated by 1), then use the \n    threshold parameter to determine which items are considered positive\n    \n    Parameters\n    ----------\n    data : DataFrame\n        implicit rating data\n\n    users_col : str\n        user column name\n\n    items_col : str\n        item column name\n    \n    ratings_col : str\n        implicit rating column name\n\n    threshold : int, default None\n        threshold to determine whether the user-item pair is \n        a positive feedback\n\n    Returns\n    -------\n    ratings : scipy sparse csr_matrix [n_users, n_items]\n        user/item ratings matrix\n\n    data : DataFrame\n        the implict rating data that retains only the positive feedback\n        (if specified to do so)\n    \"\"\"\n    if threshold is not None:\n        data = data[data[ratings_col] >= threshold]\n        data[ratings_col] = 1\n    \n    for col in (items_col, users_col, ratings_col):\n        data[col] = data[col].astype('category')\n\n    ratings = csr_matrix(( data[ratings_col],\n                           (data[users_col].cat.codes, data[items_col].cat.codes) ))\n    ratings.eliminate_zeros()\n    return ratings, data\n```\n\n\n```python\nitems_col = 'item_id'\nusers_col = 'user_id'\nratings_col = 'rating'\nthreshold = 3\nX, df = create_matrix(df, users_col, items_col, ratings_col, threshold)\nX\n```\n\n\n\n\n    <943x1574 sparse matrix of type '<class 'numpy.int64'>'\n    \twith 82520 stored elements in Compressed Sparse Row format>\n\n\n\n\n```python\ndef create_train_test(ratings, test_size = 0.2, seed = 1234):\n    \"\"\"\n    split the user-item interactions matrix into train and test set\n    by removing some of the interactions from every user and pretend\n    that we never seen them\n    \n    Parameters\n    ----------\n    ratings : scipy sparse csr_matrix [n_users, n_items]\n        The user-item interactions matrix\n    \n    test_size : float between 0.0 and 1.0, default 0.2\n        Proportion of the user-item interactions for each user\n        in the dataset to move to the test set; e.g. if set to 0.2\n        and a user has 10 interactions, then 2 will be moved to the\n        test set\n    \n    seed : int, default 1234\n        Seed for reproducible random splitting the \n        data into train/test set\n    \n    Returns\n    ------- \n    train : scipy sparse csr_matrix [n_users, n_items]\n        Training set\n    \n    test : scipy sparse csr_matrix [n_users, n_items]\n        Test set\n    \"\"\"\n    assert test_size < 1.0 and test_size > 0.0\n\n    # Dictionary Of Keys based sparse matrix is more efficient\n    # for constructing sparse matrices incrementally compared with csr_matrix\n    train = ratings.copy().todok()\n    test = dok_matrix(train.shape)\n    \n    # for all the users assign randomly chosen interactions\n    # to the test and assign those interactions to zero in the training;\n    # when computing the interactions to go into the test set, \n    # remember to round up the numbers (e.g. a user has 4 ratings, if the\n    # test_size is 0.2, then 0.8 ratings will go to test, thus we need to\n    # round up to ensure the test set gets at least 1 rating)\n    rstate = np.random.RandomState(seed)\n    for u in range(ratings.shape[0]):\n        split_index = ratings[u].indices\n        n_splits = ceil(test_size * split_index.shape[0])\n        test_index = rstate.choice(split_index, size = n_splits, replace = False)\n        test[u, test_index] = ratings[u, test_index]\n        train[u, test_index] = 0\n    \n    train, test = train.tocsr(), test.tocsr()\n    return train, test\n```\n\n\n```python\nX_train, X_test = create_train_test(X, test_size = 0.2, seed = 1234)\nX_train\n```\n\n\n\n\n    <943x1574 sparse matrix of type '<class 'numpy.int64'>'\n    \twith 65641 stored elements in Compressed Sparse Row format>\n\n\n\n\n```python\nclass BPR:\n    \"\"\"\n    Bayesian Personalized Ranking (BPR) for implicit feedback data\n\n    Parameters\n    ----------\n    learning_rate : float, default 0.01\n        learning rate for gradient descent\n\n    n_factors : int, default 20\n        Number/dimension of user and item latent factors\n\n    n_iters : int, default 15\n        Number of iterations to train the algorithm\n        \n    n_batch_size : int, default 2000\n        batch size for batch gradient descent, the original paper\n        uses stochastic gradient descent (i.e., batch size of 1),\n        but this can make the training unstable (very sensitive to\n        learning rate)\n\n    reg : int, default 0.01\n        Regularization term for the user and item latent factors\n\n    seed : int, default 1234\n        Seed for the randomly initialized user, item latent factors\n\n    verbose : boolean, default True\n        Whether to print progress bar while training\n\n    Attributes\n    ----------\n    user_factors : 2d numpy array [n_users, n_factors]\n        User latent factors learnt\n\n    item_factors : 2d numpy array [n_items, n_factors]\n        Item latent factors learnt\n\n    Reference\n    ---------\n    S. Rendle, C. Freudenthaler, Z. Gantner, L. Schmidt-Thieme \n    Bayesian Personalized Ranking from Implicit Feedback\n    - https://arxiv.org/pdf/1205.2618.pdf\n    \"\"\"\n    def __init__(self, learning_rate = 0.01, n_factors = 15, n_iters = 10, \n                 n_batch_size = 1000, reg = 0.01, seed = 1234, verbose = True):\n        self.reg = reg\n        self.seed = seed\n        self.verbose = verbose\n        self.n_iters = n_iters\n        self.n_factors = n_factors\n        self.n_batch_size = n_batch_size\n        self.learning_rate = learning_rate\n        \n    def fit(self, ratings):\n        \"\"\"\n        Parameters\n        ----------\n        ratings : scipy sparse csr_matrix [n_users, n_items]\n            sparse matrix of user-item interactions\n        \"\"\"\n        indptr = ratings.indptr\n        indices = ratings.indices\n        n_users, n_items = ratings.shape\n        \n        # ensure batch size makes sense\n        batch_size = self.n_batch_size\n        if ratings.nnz < batch_size:\n            batch_size = ratings.nnz\n            sys.stderr.write('WARNING: Batch size is greater than number of training interactions,'\n                             'switching to a batch size of {}\\n'.format(X.nnz))\n\n        batch_iters = ratings.nnz // batch_size\n        \n        # initialize random weights\n        rstate = np.random.RandomState(self.seed)\n        self.user_factors = rstate.normal(size = (n_users, self.n_factors))\n        self.item_factors = rstate.normal(size = (n_items, self.n_factors))\n        \n        # progress bar for training iteration if verbose is turned on\n        loop = range(self.n_iters)\n        if self.verbose:\n            loop = trange(self.n_iters, desc = self.__class__.__name__)\n        \n        for _ in loop:\n            for _ in range(batch_iters):\n                sampled = self._sample(n_users, n_items, indices, indptr)\n                sampled_users, sampled_pos_items, sampled_neg_items = sampled\n                self._update(sampled_users, sampled_pos_items, sampled_neg_items)\n\n        # to avoid re-computation at predict\n        self._predicted = False\n        return self\n    \n    def _sample(self, n_users, n_items, indices, indptr):\n        \"\"\"sample batches of random triplets u, i, j\"\"\"\n        sampled_pos_items = np.zeros(self.n_batch_size, dtype = np.int)\n        sampled_neg_items = np.zeros(self.n_batch_size, dtype = np.int)\n        sampled_users = np.random.choice(n_users, size = self.n_batch_size)\n\n        for idx, user in enumerate(sampled_users):\n            pos_items = indices[ indptr[user]:indptr[user + 1] ]\n            pos_item = np.random.choice(pos_items)\n            neg_item = np.random.choice(n_items)\n            while neg_item in pos_items:\n                neg_item = np.random.choice(n_items)\n\n            sampled_pos_items[idx] = pos_item\n            sampled_neg_items[idx] = neg_item\n\n        return sampled_users, sampled_pos_items, sampled_neg_items\n                \n    def _update(self, u, i, j):\n        \"\"\"\n        update according to the bootstrapped user u, \n        positive item i and negative item j\n        \"\"\"\n        user_u = self.user_factors[u]\n        item_i = self.item_factors[i]\n        item_j = self.item_factors[j]\n        \n        # decompose the estimator, compute the difference between\n        # the score of the positive items and negative items\n        r_ui = np.diag(user_u.dot(item_i.T))\n        r_uj = np.diag(user_u.dot(item_j.T))\n        r_uij = r_ui - r_uj\n        sigmoid = np.exp(-r_uij) / (1.0 + np.exp(-r_uij))\n        \n        # repeat the 1 dimension sigmoid n_factors times so\n        # the dimension will match when doing the update\n        sigmoid_tiled = np.tile(sigmoid, (self.n_factors, 1)).T\n\n        # update using gradient descent\n        grad_u = sigmoid_tiled * (item_j - item_i) + self.reg * user_u\n        grad_i = sigmoid_tiled * -user_u + self.reg * item_i\n        grad_j = sigmoid_tiled * user_u + self.reg * item_j\n        self.user_factors[u] -= self.learning_rate * grad_u\n        self.item_factors[i] -= self.learning_rate * grad_i\n        self.item_factors[j] -= self.learning_rate * grad_j\n        return self\n\n    def predict(self):\n        \"\"\"\n        Obtain the predicted ratings for every users and items\n        by doing a dot product of the learnt user and item vectors.\n        The result will be cached to avoid re-computing \n        it every time we call predict, thus there will\n        only be an overhead the first time we call it.\n        Note, ideally you probably don't need to compute \n        this as it returns a dense matrix and may take\n        up huge amounts of memory for large datasets\n        \"\"\"\n        if not self._predicted:\n            self._get_prediction()\n            self._predicted = True\n\n        return self._pred\n\n    def _get_prediction(self):\n        \"\"\"Predicted ratings (dot product of user and item vectors)\"\"\"\n        self._pred = self.user_factors.dot(self.item_factors.T)\n        return self\n\n    def _predict_user(self, user):\n        \"\"\"\n        returns the predicted ratings for the specified user,\n        this is mainly used in computing evaluation metric\n        \"\"\"\n        user_pred = self.user_factors[user].dot(self.item_factors.T)\n        return user_pred\n\n    def recommend(self, ratings, N = 5, user_ids = None):\n        \"\"\"\n        Returns the top N ranked items for given user id,\n        excluding the ones that the user already liked\n        \n        Parameters\n        ----------\n        ratings : scipy sparse csr_matrix [n_users, n_items]\n            sparse matrix of user-item interactions \n        \n        N : int, default 5\n            top-N similar items' N\n            \n        user_ids : 1d iterator, e.g. list or numpy array, default None\n            users' id that we wish to find top-N recommended for,\n            default None will find it for all users\n        \n        Returns\n        -------\n        recommendation : 2d numpy array [number of query users_ids, N]\n            each row is the top-N ranked item for each query user\n        \"\"\"\n        if user_ids is not None:\n            recommendation = np.zeros((len(user_ids), N), dtype = np.int)\n            for idx, user in enumerate(user_ids):\n                top_n = self._recommend_user(ratings, user, N)\n                recommendation[idx] = top_n\n        else:\n            n_users = ratings.shape[0]\n            recommendation = np.zeros((n_users, N), dtype = np.int)\n            for user in range(n_users):\n                top_n = self._recommend_user(ratings, user, N)\n                recommendation[user] = top_n\n\n        return recommendation\n\n    def _recommend_user(self, ratings, user, N):\n        \"\"\"the top-N ranked items for a given user\"\"\"\n        scores = self._predict_user(user)\n\n        # compute the top N items, removing the items that the user already liked\n        # from the result and ensure that we don't get out of bounds error when \n        # we ask for more recommendations than that are available\n        liked = set(ratings[user].indices)\n        count = N + len(liked)\n        if count < scores.shape[0]:\n\n            # when trying to obtain the top-N indices from the score,\n            # using argpartition to retrieve the top-N indices in \n            # unsorted order and then sort them will be faster than doing\n            # straight up argort on the entire score\n            # http://stackoverflow.com/questions/42184499/cannot-understand-numpy-argpartition-output\n            ids = np.argpartition(scores, -count)[-count:]\n            best_ids = np.argsort(scores[ids])[::-1]\n            best = ids[best_ids]\n        else:\n            best = np.argsort(scores)[::-1]\n\n        top_n = list( islice((rec for rec in best if rec not in liked), N) )\n        return top_n\n    \n    def get_similar_items(self, N = 5, item_ids = None):\n        \"\"\"\n        return the top N similar items for itemid, where\n        cosine distance is used as the distance metric\n        \n        Parameters\n        ----------\n        N : int, default 5\n            top-N similar items' N\n            \n        item_ids : 1d iterator, e.g. list or numpy array, default None\n            the item ids that we wish to find the similar items\n            of, the default None will compute the similar items\n            for all the items\n        \n        Returns\n        -------\n        similar_items : 2d numpy array [number of query item_ids, N]\n            each row is the top-N most similar item id for each\n            query item id\n        \"\"\"\n        # cosine distance is proportional to normalized euclidean distance,\n        # thus we normalize the item vectors and use euclidean metric so\n        # we can use the more efficient kd-tree for nearest neighbor search;\n        # also the item will always to nearest to itself, so we add 1 to \n        # get an additional nearest item and remove itself at the end\n        normed_item_factors = normalize(self.item_factors)\n        knn = NearestNeighbors(n_neighbors = N + 1, metric = 'euclidean')\n        knn.fit(normed_item_factors)\n\n        # returns a distance, index tuple,\n        # we don't actually need the distance\n        if item_ids is not None:\n            normed_item_factors = normed_item_factors[item_ids]\n\n        _, items = knn.kneighbors(normed_item_factors)\n        similar_items = items[:, 1:]\n        return similar_items\n```\n\n\n```python\nbpr_params = {\n    'reg': 0.01,\n    'learning_rate': 0.05,\n    'n_iters': 50,\n    'n_factors': 20,\n    'n_batch_size': 2000\n}\n\nbpr = BPR(**bpr_params)\nbpr.fit(X_train)\n```\n\n    BPR: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 50/50 [01:07<00:00,  1.43s/it]\n\n\n\n\n\n    <__main__.BPR at 0x11a9e2160>\n\n\n\n## Evaluation\n\nIn recommender systems, we are often interested in how well the method can rank a given set of items. And to do that we'll use AUC (Area Under ROC Curve as our evaluation metric. The best possible value that the AUC evaluation metric can take is 1, and any non-random ranking that makes sense would have an AUC > 0.5. An intuitive explanation of AUC is it specifies the probability that when we draw two examples at random, their predicted pairwise ranking is correct.\n\n\n```python\ndef auc_score(model, ratings):\n    \"\"\"\n    computes area under the ROC curve (AUC).\n    The full name should probably be mean\n    auc score as it is computing the auc\n    for every user's prediction and actual\n    interaction and taking the average for\n    all users\n    \n    Parameters\n    ----------\n    model : BPR instance\n        the trained BPR model\n        \n    ratings : scipy sparse csr_matrix [n_users, n_items]\n        sparse matrix of user-item interactions\n    \n    Returns\n    -------\n    auc : float 0 ~ 1\n        auc score of the model\n    \"\"\"\n    auc = 0.0\n    n_users, n_items = ratings.shape\n    for user, row in enumerate(ratings):\n        y_pred = model._predict_user(user)\n        y_true = np.zeros(n_items)\n        y_true[row.indices] = 1\n        auc += roc_auc_score(y_true, y_pred)\n\n    auc /= n_users\n    return auc\n```\n\n\n```python\nprint(auc_score(bpr, X_train))\nprint(auc_score(bpr, X_test))\n```\n\n    0.952749796601\n    0.883659780104\n\n\n## Item Recommendations\n\nNow that we have trained the model, we can get the most similar items by using the `get_similar_items` method, we can specify the number of most simliar items by specifying the `N` argument.\n\n\n```python\nbpr.get_similar_items(N = 5)\n```\n\n\n\n\n    array([[ 467, 1305,  272,  122,  737],\n           [ 562,  160,  544, 1215,  383],\n           [ 239,  815,  234,  146,  272],\n           ..., \n           [1335, 1477, 1247, 1257, 1243],\n           [1433, 1573, 1259, 1490, 1336],\n           [1472, 1572, 1433, 1545, 1491]])\n\n\n\nOn the other hand, we can also generate a top-N recommended item for each given user, by passing the sparse rating data and `N` to the `recommend` method.\n\n\n```python\nbpr.recommend(X_train, N = 5)\n```\n\n\n\n\n    array([[365, 431,  90,  41, 430],\n           [669, 244, 269, 923,  92],\n           [299, 867, 885, 324, 259],\n           ..., \n           [403, 150, 999,  92, 247],\n           [133, 204, 186,  57, 352],\n           [143, 544,  81, 572, 658]])\n\n\n\n# Reference\n\n- [Wiki: Area Under the ROC Curve](http://www.recsyswiki.com/wiki/Area_Under_the_ROC_Curve)\n- [StackExchange: Derivative of sigmoid function](http://math.stackexchange.com/questions/78575/derivative-of-sigmoid-function-sigma-x-frac11e-x)\n- [Blog: What you wanted to know about AUC](http://fastml.com/what-you-wanted-to-know-about-auc/)\n- [Blog: Learning to Rank Sketchfab Models with LightFM](http://blog.ethanrosenthal.com/2016/11/07/implicit-mf-part-2/)\n- [Blog (Chinese Mandarin): BPR [Bayesian Personalized Ranking]](http://liuzhiqiangruc.iteye.com/blog/2073526)\n- [Github: An implementation of Bayesian Personalised Ranking in Theano](https://github.com/bbc/theano-bpr)\n- [Paper: S. Rendle, C. Freudenthaler, Z. Gantner, L. Schmidt-Thieme Bayesian Personalized Ranking from Implicit Feedback](https://arxiv.org/pdf/1205.2618.pdf)\n", "meta": {"hexsha": "aa967d90bf41fc7298c411dc90fb3e44a0544f5d", "size": 54014, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "recsys/4_bpr.ipynb", "max_stars_repo_name": "awesome-archive/machine-learning", "max_stars_repo_head_hexsha": "8494f3fe73db511f7b97d082c786097bfbe71463", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-07-05T09:32:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-05T09:32:31.000Z", "max_issues_repo_path": "recsys/4_bpr.ipynb", "max_issues_repo_name": "awesome-archive/machine-learning", "max_issues_repo_head_hexsha": "8494f3fe73db511f7b97d082c786097bfbe71463", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "recsys/4_bpr.ipynb", "max_forks_repo_name": "awesome-archive/machine-learning", "max_forks_repo_head_hexsha": "8494f3fe73db511f7b97d082c786097bfbe71463", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3401310998, "max_line_length": 900, "alphanum_fraction": 0.5057022253, "converted": true, "num_tokens": 10171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09670579589946719, "lm_q2_score": 0.06008665269869255, "lm_q1q2_score": 0.0058107275721619315}}
{"text": "<a href=\"https://colab.research.google.com/github/ekdms9835/COCO-Dataset-Object-Detection-Code/blob/master/Untitled31.ipynb\" target=\"_parent\"></a>\n\n\n```python\n!pip install onnx-pytorch\n```\n\n    Collecting onnx-pytorch\n      Downloading onnx_pytorch-0.1.4-py3-none-any.whl (105 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 105 kB 5.1 MB/s \n    \u001b[?25hCollecting sympy>=1.9\n      Downloading sympy-1.9-py3-none-any.whl (6.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.2 MB 15.1 MB/s \n    \u001b[?25hRequirement already satisfied: torchvision>=0.11.1 in /usr/local/lib/python3.7/dist-packages (from onnx-pytorch) (0.11.1+cu111)\n    Requirement already satisfied: tqdm>=4.62.3 in /usr/local/lib/python3.7/dist-packages (from onnx-pytorch) (4.62.3)\n    Requirement already satisfied: numpy>=1.19.5 in /usr/local/lib/python3.7/dist-packages (from onnx-pytorch) (1.19.5)\n    Collecting onnx>=1.10.2\n      Downloading onnx-1.10.2-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (12.7 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 12.7 MB 9.0 MB/s \n    \u001b[?25hRequirement already satisfied: torch>=1.10.0 in /usr/local/lib/python3.7/dist-packages (from onnx-pytorch) (1.10.0+cu111)\n    Collecting onnxruntime>=1.9.0\n      Downloading onnxruntime-1.10.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4.9 MB 38.0 MB/s \n    \u001b[?25hCollecting setuptools>=59.2.0\n      Downloading setuptools-60.2.0-py3-none-any.whl (953 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 953 kB 45.6 MB/s \n    \u001b[?25hCollecting PyYAML>=6.0\n      Downloading PyYAML-6.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (596 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 596 kB 59.9 MB/s \n    \u001b[?25hCollecting pytest>=6.2.5\n      Downloading pytest-6.2.5-py3-none-any.whl (280 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 280 kB 56.3 MB/s \n    \u001b[?25hRequirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from onnx>=1.10.2->onnx-pytorch) (1.15.0)\n    Requirement already satisfied: typing-extensions>=3.6.2.1 in /usr/local/lib/python3.7/dist-packages (from onnx>=1.10.2->onnx-pytorch) (3.10.0.2)\n    Requirement already satisfied: protobuf in /usr/local/lib/python3.7/dist-packages (from onnx>=1.10.2->onnx-pytorch) (3.17.3)\n    Requirement already satisfied: flatbuffers in /usr/local/lib/python3.7/dist-packages (from onnxruntime>=1.9.0->onnx-pytorch) (2.0)\n    Requirement already satisfied: attrs>=19.2.0 in /usr/local/lib/python3.7/dist-packages (from pytest>=6.2.5->onnx-pytorch) (21.2.0)\n    Requirement already satisfied: importlib-metadata>=0.12 in /usr/local/lib/python3.7/dist-packages (from pytest>=6.2.5->onnx-pytorch) (4.8.2)\n    Collecting pluggy<2.0,>=0.12\n      Downloading pluggy-1.0.0-py2.py3-none-any.whl (13 kB)\n    Requirement already satisfied: iniconfig in /usr/local/lib/python3.7/dist-packages (from pytest>=6.2.5->onnx-pytorch) (1.1.1)\n    Requirement already satisfied: py>=1.8.2 in /usr/local/lib/python3.7/dist-packages (from pytest>=6.2.5->onnx-pytorch) (1.11.0)\n    Requirement already satisfied: toml in /usr/local/lib/python3.7/dist-packages (from pytest>=6.2.5->onnx-pytorch) (0.10.2)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from pytest>=6.2.5->onnx-pytorch) (21.3)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=0.12->pytest>=6.2.5->onnx-pytorch) (3.6.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.9->onnx-pytorch) (1.2.1)\n    Requirement already satisfied: pillow!=8.3.0,>=5.3.0 in /usr/local/lib/python3.7/dist-packages (from torchvision>=0.11.1->onnx-pytorch) (7.1.2)\n    Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->pytest>=6.2.5->onnx-pytorch) (3.0.6)\n    Installing collected packages: pluggy, sympy, setuptools, PyYAML, pytest, onnxruntime, onnx, onnx-pytorch\n      Attempting uninstall: pluggy\n        Found existing installation: pluggy 0.7.1\n        Uninstalling pluggy-0.7.1:\n          Successfully uninstalled pluggy-0.7.1\n      Attempting uninstall: sympy\n        Found existing installation: sympy 1.7.1\n        Uninstalling sympy-1.7.1:\n          Successfully uninstalled sympy-1.7.1\n      Attempting uninstall: setuptools\n        Found existing installation: setuptools 57.4.0\n        Uninstalling setuptools-57.4.0:\n          Successfully uninstalled setuptools-57.4.0\n      Attempting uninstall: PyYAML\n        Found existing installation: PyYAML 3.13\n        Uninstalling PyYAML-3.13:\n          Successfully uninstalled PyYAML-3.13\n      Attempting uninstall: pytest\n        Found existing installation: pytest 3.6.4\n        Uninstalling pytest-3.6.4:\n          Successfully uninstalled pytest-3.6.4\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    datascience 0.10.6 requires folium==0.2.1, but you have folium 0.8.3 which is incompatible.\u001b[0m\n    Successfully installed PyYAML-6.0 onnx-1.10.2 onnx-pytorch-0.1.4 onnxruntime-1.10.0 pluggy-1.0.0 pytest-6.2.5 setuptools-60.2.0 sympy-1.9\n\n\n\n\n\n```python\nfrom onnx_pytorch import code_gen\ncode_gen.gen(\"/content/Resnet34_3inputs_448x448_20200609 (3).onnx\", \"/content/new\")\n```\n\n    WARNING:root:Cannot get default value for dilations of Conv.\n    WARNING:root:Cannot get default value for kernel_shape of Conv.\n    WARNING:root:Cannot get default value for pads of Conv.\n    WARNING:root:Cannot get default value for strides of Conv.\n    WARNING:root:Cannot get default value for dilations of MaxPool.\n    WARNING:root:Cannot get default value for kernel_shape of MaxPool.\n    WARNING:root:Cannot get default value for pads of MaxPool.\n    WARNING:root:Cannot get default value for strides of MaxPool.\n    WARNING:root:Cannot get default value for axis of Concat.\n    WARNING:root:Cannot get default value for dilations of ConvTranspose.\n    WARNING:root:Cannot get default value for kernel_shape of ConvTranspose.\n    WARNING:root:Cannot get default value for output_padding of ConvTranspose.\n    WARNING:root:Cannot get default value for output_shape of ConvTranspose.\n    WARNING:root:Cannot get default value for pads of ConvTranspose.\n    WARNING:root:Cannot get default value for strides of ConvTranspose.\n\n\n    # Autogenerated by onnx-pytorch.\n    \n    import glob\n    import os\n    import math\n    \n    import numpy as np\n    import torch\n    import torch.nn as nn\n    import torch.nn.functional as F\n    import torchvision\n    \n    \n    class Model(nn.Module):\n      def __init__(self):\n        super(Model, self).__init__()\n        self._vars = nn.ParameterDict()\n        self._regularizer_params = []\n        for b in glob.glob(\n            os.path.join(os.path.dirname(__file__), \"variables\", \"*.npy\")):\n          v = torch.from_numpy(np.load(b))\n          requires_grad = v.dtype.is_floating_point or v.dtype.is_complex\n          self._vars[os.path.basename(b)[:-4]] = nn.Parameter(v, requires_grad=requires_grad)\n        self.n_Conv_0 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 64, 'padding': [3, 3], 'kernel_size': (7, 7), 'stride': [2, 2], 'in_channels': 3, 'bias': False})\n        self.n_Conv_0.weight.data = self._vars[\"conv1_weight\"]\n        self.n_BatchNormalization_0 = nn.BatchNorm2d(**{'num_features': 64, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_0.weight.data = self._vars[\"bn1_weight\"]\n        self.n_BatchNormalization_0.bias.data = self._vars[\"bn1_bias\"]\n        self.n_BatchNormalization_0.running_mean.data = self._vars[\"bn1_running_mean\"]\n        self.n_BatchNormalization_0.running_var.data = self._vars[\"bn1_running_var\"]\n        self.n_MaxPool_0 = nn.MaxPool2d(**{'dilation': 1, 'kernel_size': [3, 3], 'ceil_mode': False, 'stride': [2, 2], 'return_indices': False, 'padding': [1, 1]})\n        self.n_Conv_1 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 64, 'padding': [3, 3], 'kernel_size': (7, 7), 'stride': [2, 2], 'in_channels': 3, 'bias': False})\n        self.n_Conv_1.weight.data = self._vars[\"conv1_1_weight\"]\n        self.n_BatchNormalization_1 = nn.BatchNorm2d(**{'num_features': 64, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_1.weight.data = self._vars[\"bn1_1_weight\"]\n        self.n_BatchNormalization_1.bias.data = self._vars[\"bn1_1_bias\"]\n        self.n_BatchNormalization_1.running_mean.data = self._vars[\"bn1_1_running_mean\"]\n        self.n_BatchNormalization_1.running_var.data = self._vars[\"bn1_1_running_var\"]\n        self.n_MaxPool_1 = nn.MaxPool2d(**{'dilation': 1, 'kernel_size': [3, 3], 'ceil_mode': False, 'stride': [2, 2], 'return_indices': False, 'padding': [1, 1]})\n        self.n_Conv_2 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 64, 'padding': [3, 3], 'kernel_size': (7, 7), 'stride': [2, 2], 'in_channels': 3, 'bias': False})\n        self.n_Conv_2.weight.data = self._vars[\"conv1_2_weight\"]\n        self.n_BatchNormalization_2 = nn.BatchNorm2d(**{'num_features': 64, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_2.weight.data = self._vars[\"bn1_2_weight\"]\n        self.n_BatchNormalization_2.bias.data = self._vars[\"bn1_2_bias\"]\n        self.n_BatchNormalization_2.running_mean.data = self._vars[\"bn1_2_running_mean\"]\n        self.n_BatchNormalization_2.running_var.data = self._vars[\"bn1_2_running_var\"]\n        self.n_MaxPool_2 = nn.MaxPool2d(**{'dilation': 1, 'kernel_size': [3, 3], 'ceil_mode': False, 'stride': [2, 2], 'return_indices': False, 'padding': [1, 1]})\n        self.n_Conv_3 = nn.Conv2d(**{'groups': 128, 'dilation': [1, 1], 'out_channels': 128, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 128, 'bias': False})\n        self.n_Conv_3.weight.data = self._vars[\"marg_0_weight\"]\n        self.n_BatchNormalization_3 = nn.BatchNorm2d(**{'num_features': 128, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_3.weight.data = self._vars[\"marg_1_weight\"]\n        self.n_BatchNormalization_3.bias.data = self._vars[\"marg_1_bias\"]\n        self.n_BatchNormalization_3.running_mean.data = self._vars[\"marg_1_running_mean\"]\n        self.n_BatchNormalization_3.running_var.data = self._vars[\"marg_1_running_var\"]\n        self.n_Conv_4 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 64, 'padding': [0, 0], 'kernel_size': (1, 1), 'stride': [1, 1], 'in_channels': 128, 'bias': False})\n        self.n_Conv_4.weight.data = self._vars[\"marg_3_weight\"]\n        self.n_BatchNormalization_4 = nn.BatchNorm2d(**{'num_features': 64, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_4.weight.data = self._vars[\"marg_4_weight\"]\n        self.n_BatchNormalization_4.bias.data = self._vars[\"marg_4_bias\"]\n        self.n_BatchNormalization_4.running_mean.data = self._vars[\"marg_4_running_mean\"]\n        self.n_BatchNormalization_4.running_var.data = self._vars[\"marg_4_running_var\"]\n        self.n_Conv_5 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 64, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 64, 'bias': False})\n        self.n_Conv_5.weight.data = self._vars[\"layer1_0_conv1_weight\"]\n        self.n_BatchNormalization_5 = nn.BatchNorm2d(**{'num_features': 64, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_5.weight.data = self._vars[\"layer1_0_bn1_weight\"]\n        self.n_BatchNormalization_5.bias.data = self._vars[\"layer1_0_bn1_bias\"]\n        self.n_BatchNormalization_5.running_mean.data = self._vars[\"layer1_0_bn1_running_mean\"]\n        self.n_BatchNormalization_5.running_var.data = self._vars[\"layer1_0_bn1_running_var\"]\n        self.n_Conv_6 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 64, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 64, 'bias': False})\n        self.n_Conv_6.weight.data = self._vars[\"layer1_0_conv2_weight\"]\n        self.n_BatchNormalization_6 = nn.BatchNorm2d(**{'num_features': 64, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_6.weight.data = self._vars[\"layer1_0_bn2_weight\"]\n        self.n_BatchNormalization_6.bias.data = self._vars[\"layer1_0_bn2_bias\"]\n        self.n_BatchNormalization_6.running_mean.data = self._vars[\"layer1_0_bn2_running_mean\"]\n        self.n_BatchNormalization_6.running_var.data = self._vars[\"layer1_0_bn2_running_var\"]\n        self.n_Conv_7 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 64, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 64, 'bias': False})\n        self.n_Conv_7.weight.data = self._vars[\"layer1_1_conv1_weight\"]\n        self.n_BatchNormalization_7 = nn.BatchNorm2d(**{'num_features': 64, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_7.weight.data = self._vars[\"layer1_1_bn1_weight\"]\n        self.n_BatchNormalization_7.bias.data = self._vars[\"layer1_1_bn1_bias\"]\n        self.n_BatchNormalization_7.running_mean.data = self._vars[\"layer1_1_bn1_running_mean\"]\n        self.n_BatchNormalization_7.running_var.data = self._vars[\"layer1_1_bn1_running_var\"]\n        self.n_Conv_8 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 64, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 64, 'bias': False})\n        self.n_Conv_8.weight.data = self._vars[\"layer1_1_conv2_weight\"]\n        self.n_BatchNormalization_8 = nn.BatchNorm2d(**{'num_features': 64, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_8.weight.data = self._vars[\"layer1_1_bn2_weight\"]\n        self.n_BatchNormalization_8.bias.data = self._vars[\"layer1_1_bn2_bias\"]\n        self.n_BatchNormalization_8.running_mean.data = self._vars[\"layer1_1_bn2_running_mean\"]\n        self.n_BatchNormalization_8.running_var.data = self._vars[\"layer1_1_bn2_running_var\"]\n        self.n_Conv_9 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 64, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 64, 'bias': False})\n        self.n_Conv_9.weight.data = self._vars[\"layer1_2_conv1_weight\"]\n        self.n_BatchNormalization_9 = nn.BatchNorm2d(**{'num_features': 64, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_9.weight.data = self._vars[\"layer1_2_bn1_weight\"]\n        self.n_BatchNormalization_9.bias.data = self._vars[\"layer1_2_bn1_bias\"]\n        self.n_BatchNormalization_9.running_mean.data = self._vars[\"layer1_2_bn1_running_mean\"]\n        self.n_BatchNormalization_9.running_var.data = self._vars[\"layer1_2_bn1_running_var\"]\n        self.n_Conv_10 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 64, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 64, 'bias': False})\n        self.n_Conv_10.weight.data = self._vars[\"layer1_2_conv2_weight\"]\n        self.n_BatchNormalization_10 = nn.BatchNorm2d(**{'num_features': 64, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_10.weight.data = self._vars[\"layer1_2_bn2_weight\"]\n        self.n_BatchNormalization_10.bias.data = self._vars[\"layer1_2_bn2_bias\"]\n        self.n_BatchNormalization_10.running_mean.data = self._vars[\"layer1_2_bn2_running_mean\"]\n        self.n_BatchNormalization_10.running_var.data = self._vars[\"layer1_2_bn2_running_var\"]\n        self.n_Conv_11 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 128, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [2, 2], 'in_channels': 64, 'bias': False})\n        self.n_Conv_11.weight.data = self._vars[\"layer2_0_conv1_weight\"]\n        self.n_BatchNormalization_11 = nn.BatchNorm2d(**{'num_features': 128, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_11.weight.data = self._vars[\"layer2_0_bn1_weight\"]\n        self.n_BatchNormalization_11.bias.data = self._vars[\"layer2_0_bn1_bias\"]\n        self.n_BatchNormalization_11.running_mean.data = self._vars[\"layer2_0_bn1_running_mean\"]\n        self.n_BatchNormalization_11.running_var.data = self._vars[\"layer2_0_bn1_running_var\"]\n        self.n_Conv_12 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 128, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 128, 'bias': False})\n        self.n_Conv_12.weight.data = self._vars[\"layer2_0_conv2_weight\"]\n        self.n_BatchNormalization_12 = nn.BatchNorm2d(**{'num_features': 128, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_12.weight.data = self._vars[\"layer2_0_bn2_weight\"]\n        self.n_BatchNormalization_12.bias.data = self._vars[\"layer2_0_bn2_bias\"]\n        self.n_BatchNormalization_12.running_mean.data = self._vars[\"layer2_0_bn2_running_mean\"]\n        self.n_BatchNormalization_12.running_var.data = self._vars[\"layer2_0_bn2_running_var\"]\n        self.n_Conv_13 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 128, 'padding': [0, 0], 'kernel_size': (1, 1), 'stride': [2, 2], 'in_channels': 64, 'bias': False})\n        self.n_Conv_13.weight.data = self._vars[\"layer2_0_downsample_0_weight\"]\n        self.n_BatchNormalization_13 = nn.BatchNorm2d(**{'num_features': 128, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_13.weight.data = self._vars[\"layer2_0_downsample_1_weight\"]\n        self.n_BatchNormalization_13.bias.data = self._vars[\"layer2_0_downsample_1_bias\"]\n        self.n_BatchNormalization_13.running_mean.data = self._vars[\"layer2_0_downsample_1_running_mean\"]\n        self.n_BatchNormalization_13.running_var.data = self._vars[\"layer2_0_downsample_1_running_var\"]\n        self.n_Conv_14 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 128, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 128, 'bias': False})\n        self.n_Conv_14.weight.data = self._vars[\"layer2_1_conv1_weight\"]\n        self.n_BatchNormalization_14 = nn.BatchNorm2d(**{'num_features': 128, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_14.weight.data = self._vars[\"layer2_1_bn1_weight\"]\n        self.n_BatchNormalization_14.bias.data = self._vars[\"layer2_1_bn1_bias\"]\n        self.n_BatchNormalization_14.running_mean.data = self._vars[\"layer2_1_bn1_running_mean\"]\n        self.n_BatchNormalization_14.running_var.data = self._vars[\"layer2_1_bn1_running_var\"]\n        self.n_Conv_15 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 128, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 128, 'bias': False})\n        self.n_Conv_15.weight.data = self._vars[\"layer2_1_conv2_weight\"]\n        self.n_BatchNormalization_15 = nn.BatchNorm2d(**{'num_features': 128, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_15.weight.data = self._vars[\"layer2_1_bn2_weight\"]\n        self.n_BatchNormalization_15.bias.data = self._vars[\"layer2_1_bn2_bias\"]\n        self.n_BatchNormalization_15.running_mean.data = self._vars[\"layer2_1_bn2_running_mean\"]\n        self.n_BatchNormalization_15.running_var.data = self._vars[\"layer2_1_bn2_running_var\"]\n        self.n_Conv_16 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 128, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 128, 'bias': False})\n        self.n_Conv_16.weight.data = self._vars[\"layer2_2_conv1_weight\"]\n        self.n_BatchNormalization_16 = nn.BatchNorm2d(**{'num_features': 128, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_16.weight.data = self._vars[\"layer2_2_bn1_weight\"]\n        self.n_BatchNormalization_16.bias.data = self._vars[\"layer2_2_bn1_bias\"]\n        self.n_BatchNormalization_16.running_mean.data = self._vars[\"layer2_2_bn1_running_mean\"]\n        self.n_BatchNormalization_16.running_var.data = self._vars[\"layer2_2_bn1_running_var\"]\n        self.n_Conv_17 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 128, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 128, 'bias': False})\n        self.n_Conv_17.weight.data = self._vars[\"layer2_2_conv2_weight\"]\n        self.n_BatchNormalization_17 = nn.BatchNorm2d(**{'num_features': 128, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_17.weight.data = self._vars[\"layer2_2_bn2_weight\"]\n        self.n_BatchNormalization_17.bias.data = self._vars[\"layer2_2_bn2_bias\"]\n        self.n_BatchNormalization_17.running_mean.data = self._vars[\"layer2_2_bn2_running_mean\"]\n        self.n_BatchNormalization_17.running_var.data = self._vars[\"layer2_2_bn2_running_var\"]\n        self.n_Conv_18 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 128, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 128, 'bias': False})\n        self.n_Conv_18.weight.data = self._vars[\"layer2_3_conv1_weight\"]\n        self.n_BatchNormalization_18 = nn.BatchNorm2d(**{'num_features': 128, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_18.weight.data = self._vars[\"layer2_3_bn1_weight\"]\n        self.n_BatchNormalization_18.bias.data = self._vars[\"layer2_3_bn1_bias\"]\n        self.n_BatchNormalization_18.running_mean.data = self._vars[\"layer2_3_bn1_running_mean\"]\n        self.n_BatchNormalization_18.running_var.data = self._vars[\"layer2_3_bn1_running_var\"]\n        self.n_Conv_19 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 128, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 128, 'bias': False})\n        self.n_Conv_19.weight.data = self._vars[\"layer2_3_conv2_weight\"]\n        self.n_BatchNormalization_19 = nn.BatchNorm2d(**{'num_features': 128, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_19.weight.data = self._vars[\"layer2_3_bn2_weight\"]\n        self.n_BatchNormalization_19.bias.data = self._vars[\"layer2_3_bn2_bias\"]\n        self.n_BatchNormalization_19.running_mean.data = self._vars[\"layer2_3_bn2_running_mean\"]\n        self.n_BatchNormalization_19.running_var.data = self._vars[\"layer2_3_bn2_running_var\"]\n        self.n_Conv_20 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 256, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [2, 2], 'in_channels': 128, 'bias': False})\n        self.n_Conv_20.weight.data = self._vars[\"layer3_0_conv1_weight\"]\n        self.n_BatchNormalization_20 = nn.BatchNorm2d(**{'num_features': 256, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_20.weight.data = self._vars[\"layer3_0_bn1_weight\"]\n        self.n_BatchNormalization_20.bias.data = self._vars[\"layer3_0_bn1_bias\"]\n        self.n_BatchNormalization_20.running_mean.data = self._vars[\"layer3_0_bn1_running_mean\"]\n        self.n_BatchNormalization_20.running_var.data = self._vars[\"layer3_0_bn1_running_var\"]\n        self.n_Conv_21 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 256, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 256, 'bias': False})\n        self.n_Conv_21.weight.data = self._vars[\"layer3_0_conv2_weight\"]\n        self.n_BatchNormalization_21 = nn.BatchNorm2d(**{'num_features': 256, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_21.weight.data = self._vars[\"layer3_0_bn2_weight\"]\n        self.n_BatchNormalization_21.bias.data = self._vars[\"layer3_0_bn2_bias\"]\n        self.n_BatchNormalization_21.running_mean.data = self._vars[\"layer3_0_bn2_running_mean\"]\n        self.n_BatchNormalization_21.running_var.data = self._vars[\"layer3_0_bn2_running_var\"]\n        self.n_Conv_22 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 256, 'padding': [0, 0], 'kernel_size': (1, 1), 'stride': [2, 2], 'in_channels': 128, 'bias': False})\n        self.n_Conv_22.weight.data = self._vars[\"layer3_0_downsample_0_weight\"]\n        self.n_BatchNormalization_22 = nn.BatchNorm2d(**{'num_features': 256, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_22.weight.data = self._vars[\"layer3_0_downsample_1_weight\"]\n        self.n_BatchNormalization_22.bias.data = self._vars[\"layer3_0_downsample_1_bias\"]\n        self.n_BatchNormalization_22.running_mean.data = self._vars[\"layer3_0_downsample_1_running_mean\"]\n        self.n_BatchNormalization_22.running_var.data = self._vars[\"layer3_0_downsample_1_running_var\"]\n        self.n_Conv_23 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 256, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 256, 'bias': False})\n        self.n_Conv_23.weight.data = self._vars[\"layer3_1_conv1_weight\"]\n        self.n_BatchNormalization_23 = nn.BatchNorm2d(**{'num_features': 256, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_23.weight.data = self._vars[\"layer3_1_bn1_weight\"]\n        self.n_BatchNormalization_23.bias.data = self._vars[\"layer3_1_bn1_bias\"]\n        self.n_BatchNormalization_23.running_mean.data = self._vars[\"layer3_1_bn1_running_mean\"]\n        self.n_BatchNormalization_23.running_var.data = self._vars[\"layer3_1_bn1_running_var\"]\n        self.n_Conv_24 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 256, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 256, 'bias': False})\n        self.n_Conv_24.weight.data = self._vars[\"layer3_1_conv2_weight\"]\n        self.n_BatchNormalization_24 = nn.BatchNorm2d(**{'num_features': 256, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_24.weight.data = self._vars[\"layer3_1_bn2_weight\"]\n        self.n_BatchNormalization_24.bias.data = self._vars[\"layer3_1_bn2_bias\"]\n        self.n_BatchNormalization_24.running_mean.data = self._vars[\"layer3_1_bn2_running_mean\"]\n        self.n_BatchNormalization_24.running_var.data = self._vars[\"layer3_1_bn2_running_var\"]\n        self.n_Conv_25 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 256, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 256, 'bias': False})\n        self.n_Conv_25.weight.data = self._vars[\"layer3_2_conv1_weight\"]\n        self.n_BatchNormalization_25 = nn.BatchNorm2d(**{'num_features': 256, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_25.weight.data = self._vars[\"layer3_2_bn1_weight\"]\n        self.n_BatchNormalization_25.bias.data = self._vars[\"layer3_2_bn1_bias\"]\n        self.n_BatchNormalization_25.running_mean.data = self._vars[\"layer3_2_bn1_running_mean\"]\n        self.n_BatchNormalization_25.running_var.data = self._vars[\"layer3_2_bn1_running_var\"]\n        self.n_Conv_26 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 256, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 256, 'bias': False})\n        self.n_Conv_26.weight.data = self._vars[\"layer3_2_conv2_weight\"]\n        self.n_BatchNormalization_26 = nn.BatchNorm2d(**{'num_features': 256, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_26.weight.data = self._vars[\"layer3_2_bn2_weight\"]\n        self.n_BatchNormalization_26.bias.data = self._vars[\"layer3_2_bn2_bias\"]\n        self.n_BatchNormalization_26.running_mean.data = self._vars[\"layer3_2_bn2_running_mean\"]\n        self.n_BatchNormalization_26.running_var.data = self._vars[\"layer3_2_bn2_running_var\"]\n        self.n_Conv_27 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 256, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 256, 'bias': False})\n        self.n_Conv_27.weight.data = self._vars[\"layer3_3_conv1_weight\"]\n        self.n_BatchNormalization_27 = nn.BatchNorm2d(**{'num_features': 256, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_27.weight.data = self._vars[\"layer3_3_bn1_weight\"]\n        self.n_BatchNormalization_27.bias.data = self._vars[\"layer3_3_bn1_bias\"]\n        self.n_BatchNormalization_27.running_mean.data = self._vars[\"layer3_3_bn1_running_mean\"]\n        self.n_BatchNormalization_27.running_var.data = self._vars[\"layer3_3_bn1_running_var\"]\n        self.n_Conv_28 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 256, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 256, 'bias': False})\n        self.n_Conv_28.weight.data = self._vars[\"layer3_3_conv2_weight\"]\n        self.n_BatchNormalization_28 = nn.BatchNorm2d(**{'num_features': 256, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_28.weight.data = self._vars[\"layer3_3_bn2_weight\"]\n        self.n_BatchNormalization_28.bias.data = self._vars[\"layer3_3_bn2_bias\"]\n        self.n_BatchNormalization_28.running_mean.data = self._vars[\"layer3_3_bn2_running_mean\"]\n        self.n_BatchNormalization_28.running_var.data = self._vars[\"layer3_3_bn2_running_var\"]\n        self.n_Conv_29 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 256, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 256, 'bias': False})\n        self.n_Conv_29.weight.data = self._vars[\"layer3_4_conv1_weight\"]\n        self.n_BatchNormalization_29 = nn.BatchNorm2d(**{'num_features': 256, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_29.weight.data = self._vars[\"layer3_4_bn1_weight\"]\n        self.n_BatchNormalization_29.bias.data = self._vars[\"layer3_4_bn1_bias\"]\n        self.n_BatchNormalization_29.running_mean.data = self._vars[\"layer3_4_bn1_running_mean\"]\n        self.n_BatchNormalization_29.running_var.data = self._vars[\"layer3_4_bn1_running_var\"]\n        self.n_Conv_30 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 256, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 256, 'bias': False})\n        self.n_Conv_30.weight.data = self._vars[\"layer3_4_conv2_weight\"]\n        self.n_BatchNormalization_30 = nn.BatchNorm2d(**{'num_features': 256, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_30.weight.data = self._vars[\"layer3_4_bn2_weight\"]\n        self.n_BatchNormalization_30.bias.data = self._vars[\"layer3_4_bn2_bias\"]\n        self.n_BatchNormalization_30.running_mean.data = self._vars[\"layer3_4_bn2_running_mean\"]\n        self.n_BatchNormalization_30.running_var.data = self._vars[\"layer3_4_bn2_running_var\"]\n        self.n_Conv_31 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 256, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 256, 'bias': False})\n        self.n_Conv_31.weight.data = self._vars[\"layer3_5_conv1_weight\"]\n        self.n_BatchNormalization_31 = nn.BatchNorm2d(**{'num_features': 256, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_31.weight.data = self._vars[\"layer3_5_bn1_weight\"]\n        self.n_BatchNormalization_31.bias.data = self._vars[\"layer3_5_bn1_bias\"]\n        self.n_BatchNormalization_31.running_mean.data = self._vars[\"layer3_5_bn1_running_mean\"]\n        self.n_BatchNormalization_31.running_var.data = self._vars[\"layer3_5_bn1_running_var\"]\n        self.n_Conv_32 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 256, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 256, 'bias': False})\n        self.n_Conv_32.weight.data = self._vars[\"layer3_5_conv2_weight\"]\n        self.n_BatchNormalization_32 = nn.BatchNorm2d(**{'num_features': 256, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_32.weight.data = self._vars[\"layer3_5_bn2_weight\"]\n        self.n_BatchNormalization_32.bias.data = self._vars[\"layer3_5_bn2_bias\"]\n        self.n_BatchNormalization_32.running_mean.data = self._vars[\"layer3_5_bn2_running_mean\"]\n        self.n_BatchNormalization_32.running_var.data = self._vars[\"layer3_5_bn2_running_var\"]\n        self.n_Conv_33 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 512, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [2, 2], 'in_channels': 256, 'bias': False})\n        self.n_Conv_33.weight.data = self._vars[\"layer4_0_conv1_weight\"]\n        self.n_BatchNormalization_33 = nn.BatchNorm2d(**{'num_features': 512, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_33.weight.data = self._vars[\"layer4_0_bn1_weight\"]\n        self.n_BatchNormalization_33.bias.data = self._vars[\"layer4_0_bn1_bias\"]\n        self.n_BatchNormalization_33.running_mean.data = self._vars[\"layer4_0_bn1_running_mean\"]\n        self.n_BatchNormalization_33.running_var.data = self._vars[\"layer4_0_bn1_running_var\"]\n        self.n_Conv_34 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 512, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 512, 'bias': False})\n        self.n_Conv_34.weight.data = self._vars[\"layer4_0_conv2_weight\"]\n        self.n_BatchNormalization_34 = nn.BatchNorm2d(**{'num_features': 512, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_34.weight.data = self._vars[\"layer4_0_bn2_weight\"]\n        self.n_BatchNormalization_34.bias.data = self._vars[\"layer4_0_bn2_bias\"]\n        self.n_BatchNormalization_34.running_mean.data = self._vars[\"layer4_0_bn2_running_mean\"]\n        self.n_BatchNormalization_34.running_var.data = self._vars[\"layer4_0_bn2_running_var\"]\n        self.n_Conv_35 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 512, 'padding': [0, 0], 'kernel_size': (1, 1), 'stride': [2, 2], 'in_channels': 256, 'bias': False})\n        self.n_Conv_35.weight.data = self._vars[\"layer4_0_downsample_0_weight\"]\n        self.n_BatchNormalization_35 = nn.BatchNorm2d(**{'num_features': 512, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_35.weight.data = self._vars[\"layer4_0_downsample_1_weight\"]\n        self.n_BatchNormalization_35.bias.data = self._vars[\"layer4_0_downsample_1_bias\"]\n        self.n_BatchNormalization_35.running_mean.data = self._vars[\"layer4_0_downsample_1_running_mean\"]\n        self.n_BatchNormalization_35.running_var.data = self._vars[\"layer4_0_downsample_1_running_var\"]\n        self.n_Conv_36 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 512, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 512, 'bias': False})\n        self.n_Conv_36.weight.data = self._vars[\"layer4_1_conv1_weight\"]\n        self.n_BatchNormalization_36 = nn.BatchNorm2d(**{'num_features': 512, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_36.weight.data = self._vars[\"layer4_1_bn1_weight\"]\n        self.n_BatchNormalization_36.bias.data = self._vars[\"layer4_1_bn1_bias\"]\n        self.n_BatchNormalization_36.running_mean.data = self._vars[\"layer4_1_bn1_running_mean\"]\n        self.n_BatchNormalization_36.running_var.data = self._vars[\"layer4_1_bn1_running_var\"]\n        self.n_Conv_37 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 512, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 512, 'bias': False})\n        self.n_Conv_37.weight.data = self._vars[\"layer4_1_conv2_weight\"]\n        self.n_BatchNormalization_37 = nn.BatchNorm2d(**{'num_features': 512, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_37.weight.data = self._vars[\"layer4_1_bn2_weight\"]\n        self.n_BatchNormalization_37.bias.data = self._vars[\"layer4_1_bn2_bias\"]\n        self.n_BatchNormalization_37.running_mean.data = self._vars[\"layer4_1_bn2_running_mean\"]\n        self.n_BatchNormalization_37.running_var.data = self._vars[\"layer4_1_bn2_running_var\"]\n        self.n_Conv_38 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 512, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 512, 'bias': False})\n        self.n_Conv_38.weight.data = self._vars[\"layer4_2_conv1_weight\"]\n        self.n_BatchNormalization_38 = nn.BatchNorm2d(**{'num_features': 512, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_38.weight.data = self._vars[\"layer4_2_bn1_weight\"]\n        self.n_BatchNormalization_38.bias.data = self._vars[\"layer4_2_bn1_bias\"]\n        self.n_BatchNormalization_38.running_mean.data = self._vars[\"layer4_2_bn1_running_mean\"]\n        self.n_BatchNormalization_38.running_var.data = self._vars[\"layer4_2_bn1_running_var\"]\n        self.n_Conv_39 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 512, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 512, 'bias': False})\n        self.n_Conv_39.weight.data = self._vars[\"layer4_2_conv2_weight\"]\n        self.n_BatchNormalization_39 = nn.BatchNorm2d(**{'num_features': 512, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_39.weight.data = self._vars[\"layer4_2_bn2_weight\"]\n        self.n_BatchNormalization_39.bias.data = self._vars[\"layer4_2_bn2_bias\"]\n        self.n_BatchNormalization_39.running_mean.data = self._vars[\"layer4_2_bn2_running_mean\"]\n        self.n_BatchNormalization_39.running_var.data = self._vars[\"layer4_2_bn2_running_var\"]\n        self.n_Conv_40 = nn.Conv2d(**{'groups': 512, 'dilation': [1, 1], 'out_channels': 512, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 512, 'bias': False})\n        self.n_Conv_40.weight.data = self._vars[\"model1_9_0_weight\"]\n        self.n_BatchNormalization_40 = nn.BatchNorm2d(**{'num_features': 512, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_40.weight.data = self._vars[\"model1_9_1_weight\"]\n        self.n_BatchNormalization_40.bias.data = self._vars[\"model1_9_1_bias\"]\n        self.n_BatchNormalization_40.running_mean.data = self._vars[\"model1_9_1_running_mean\"]\n        self.n_BatchNormalization_40.running_var.data = self._vars[\"model1_9_1_running_var\"]\n        self.n_Conv_41 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 512, 'padding': [0, 0], 'kernel_size': (1, 1), 'stride': [1, 1], 'in_channels': 512, 'bias': False})\n        self.n_Conv_41.weight.data = self._vars[\"model1_9_3_weight\"]\n        self.n_BatchNormalization_41 = nn.BatchNorm2d(**{'num_features': 512, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_41.weight.data = self._vars[\"model1_9_4_weight\"]\n        self.n_BatchNormalization_41.bias.data = self._vars[\"model1_9_4_bias\"]\n        self.n_BatchNormalization_41.running_mean.data = self._vars[\"model1_9_4_running_mean\"]\n        self.n_BatchNormalization_41.running_var.data = self._vars[\"model1_9_4_running_var\"]\n        self.n_ConvTranspose_0 = nn.ConvTranspose2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 512, 'padding': [0, 0], 'output_padding': [0, 0], 'kernel_size': (2, 2), 'stride': [2, 2], 'in_channels': 512, 'bias': False})\n        self.n_ConvTranspose_0.weight.data = self._vars[\"model1_9_6_weight\"]\n        self.n_BatchNormalization_42 = nn.BatchNorm2d(**{'num_features': 512, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_42.weight.data = self._vars[\"model1_9_7_weight\"]\n        self.n_BatchNormalization_42.bias.data = self._vars[\"model1_9_7_bias\"]\n        self.n_BatchNormalization_42.running_mean.data = self._vars[\"model1_9_7_running_mean\"]\n        self.n_BatchNormalization_42.running_var.data = self._vars[\"model1_9_7_running_var\"]\n        self.n_Conv_42 = nn.Conv2d(**{'groups': 512, 'dilation': [1, 1], 'out_channels': 512, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 512, 'bias': False})\n        self.n_Conv_42.weight.data = self._vars[\"model2_1_0_weight\"]\n        self.n_BatchNormalization_43 = nn.BatchNorm2d(**{'num_features': 512, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_43.weight.data = self._vars[\"model2_1_1_weight\"]\n        self.n_BatchNormalization_43.bias.data = self._vars[\"model2_1_1_bias\"]\n        self.n_BatchNormalization_43.running_mean.data = self._vars[\"model2_1_1_running_mean\"]\n        self.n_BatchNormalization_43.running_var.data = self._vars[\"model2_1_1_running_var\"]\n        self.n_Conv_43 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 1024, 'padding': [0, 0], 'kernel_size': (1, 1), 'stride': [1, 1], 'in_channels': 512, 'bias': False})\n        self.n_Conv_43.weight.data = self._vars[\"model2_1_3_weight\"]\n        self.n_BatchNormalization_44 = nn.BatchNorm2d(**{'num_features': 1024, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_44.weight.data = self._vars[\"model2_1_4_weight\"]\n        self.n_BatchNormalization_44.bias.data = self._vars[\"model2_1_4_bias\"]\n        self.n_BatchNormalization_44.running_mean.data = self._vars[\"model2_1_4_running_mean\"]\n        self.n_BatchNormalization_44.running_var.data = self._vars[\"model2_1_4_running_var\"]\n        self.n_Conv_44 = nn.Conv2d(**{'groups': 1024, 'dilation': [1, 1], 'out_channels': 1024, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 1024, 'bias': False})\n        self.n_Conv_44.weight.data = self._vars[\"heatmap_0_weight\"]\n        self.n_BatchNormalization_45 = nn.BatchNorm2d(**{'num_features': 1024, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_45.weight.data = self._vars[\"heatmap_1_weight\"]\n        self.n_BatchNormalization_45.bias.data = self._vars[\"heatmap_1_bias\"]\n        self.n_BatchNormalization_45.running_mean.data = self._vars[\"heatmap_1_running_mean\"]\n        self.n_BatchNormalization_45.running_var.data = self._vars[\"heatmap_1_running_var\"]\n        self.n_Conv_45 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 24, 'padding': [0, 0], 'kernel_size': (1, 1), 'stride': [1, 1], 'in_channels': 1024, 'bias': False})\n        self.n_Conv_45.weight.data = self._vars[\"heatmap_3_weight\"]\n        self.n_BatchNormalization_46 = nn.BatchNorm2d(**{'num_features': 24, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_46.weight.data = self._vars[\"heatmap_4_weight\"]\n        self.n_BatchNormalization_46.bias.data = self._vars[\"heatmap_4_bias\"]\n        self.n_BatchNormalization_46.running_mean.data = self._vars[\"heatmap_4_running_mean\"]\n        self.n_BatchNormalization_46.running_var.data = self._vars[\"heatmap_4_running_var\"]\n        self.n_Conv_46 = nn.Conv2d(**{'groups': 1024, 'dilation': [1, 1], 'out_channels': 1024, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 1024, 'bias': False})\n        self.n_Conv_46.weight.data = self._vars[\"offset_0_weight\"]\n        self.n_BatchNormalization_47 = nn.BatchNorm2d(**{'num_features': 1024, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_47.weight.data = self._vars[\"offset_1_weight\"]\n        self.n_BatchNormalization_47.bias.data = self._vars[\"offset_1_bias\"]\n        self.n_BatchNormalization_47.running_mean.data = self._vars[\"offset_1_running_mean\"]\n        self.n_BatchNormalization_47.running_var.data = self._vars[\"offset_1_running_var\"]\n        self.n_Conv_47 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 48, 'padding': [0, 0], 'kernel_size': (1, 1), 'stride': [1, 1], 'in_channels': 1024, 'bias': False})\n        self.n_Conv_47.weight.data = self._vars[\"offset_3_weight\"]\n        self.n_Conv_48 = nn.Conv2d(**{'groups': 1024, 'dilation': [1, 1], 'out_channels': 1024, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 1024, 'bias': False})\n        self.n_Conv_48.weight.data = self._vars[\"model2_2_0_weight\"]\n        self.n_BatchNormalization_48 = nn.BatchNorm2d(**{'num_features': 1024, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_48.weight.data = self._vars[\"model2_2_1_weight\"]\n        self.n_BatchNormalization_48.bias.data = self._vars[\"model2_2_1_bias\"]\n        self.n_BatchNormalization_48.running_mean.data = self._vars[\"model2_2_1_running_mean\"]\n        self.n_BatchNormalization_48.running_var.data = self._vars[\"model2_2_1_running_var\"]\n        self.n_Conv_49 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 1024, 'padding': [0, 0], 'kernel_size': (1, 1), 'stride': [1, 1], 'in_channels': 1024, 'bias': False})\n        self.n_Conv_49.weight.data = self._vars[\"model2_2_3_weight\"]\n        self.n_BatchNormalization_49 = nn.BatchNorm2d(**{'num_features': 1024, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_49.weight.data = self._vars[\"model2_2_4_weight\"]\n        self.n_BatchNormalization_49.bias.data = self._vars[\"model2_2_4_bias\"]\n        self.n_BatchNormalization_49.running_mean.data = self._vars[\"model2_2_4_running_mean\"]\n        self.n_BatchNormalization_49.running_var.data = self._vars[\"model2_2_4_running_var\"]\n        self.n_Conv_50 = nn.Conv2d(**{'groups': 1024, 'dilation': [1, 1], 'out_channels': 1024, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 1024, 'bias': False})\n        self.n_Conv_50.weight.data = self._vars[\"model3_0_0_weight\"]\n        self.n_BatchNormalization_50 = nn.BatchNorm2d(**{'num_features': 1024, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_50.weight.data = self._vars[\"model3_0_1_weight\"]\n        self.n_BatchNormalization_50.bias.data = self._vars[\"model3_0_1_bias\"]\n        self.n_BatchNormalization_50.running_mean.data = self._vars[\"model3_0_1_running_mean\"]\n        self.n_BatchNormalization_50.running_var.data = self._vars[\"model3_0_1_running_var\"]\n        self.n_Conv_51 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 672, 'padding': [0, 0], 'kernel_size': (1, 1), 'stride': [1, 1], 'in_channels': 1024, 'bias': False})\n        self.n_Conv_51.weight.data = self._vars[\"model3_0_3_weight\"]\n        self.n_BatchNormalization_51 = nn.BatchNorm2d(**{'num_features': 672, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_51.weight.data = self._vars[\"heatmap3D_0_weight\"]\n        self.n_BatchNormalization_51.bias.data = self._vars[\"heatmap3D_0_bias\"]\n        self.n_BatchNormalization_51.running_mean.data = self._vars[\"heatmap3D_0_running_mean\"]\n        self.n_BatchNormalization_51.running_var.data = self._vars[\"heatmap3D_0_running_var\"]\n        self.n_Conv_52 = nn.Conv2d(**{'groups': 1024, 'dilation': [1, 1], 'out_channels': 1024, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 1024, 'bias': False})\n        self.n_Conv_52.weight.data = self._vars[\"model3_2_0_weight\"]\n        self.n_BatchNormalization_52 = nn.BatchNorm2d(**{'num_features': 1024, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_52.weight.data = self._vars[\"model3_2_1_weight\"]\n        self.n_BatchNormalization_52.bias.data = self._vars[\"model3_2_1_bias\"]\n        self.n_BatchNormalization_52.running_mean.data = self._vars[\"model3_2_1_running_mean\"]\n        self.n_BatchNormalization_52.running_var.data = self._vars[\"model3_2_1_running_var\"]\n        self.n_Conv_53 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 672, 'padding': [0, 0], 'kernel_size': (1, 1), 'stride': [1, 1], 'in_channels': 1024, 'bias': False})\n        self.n_Conv_53.weight.data = self._vars[\"model3_2_3_weight\"]\n        self.n_BatchNormalization_53 = nn.BatchNorm2d(**{'num_features': 672, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_53.weight.data = self._vars[\"model3_2_4_weight\"]\n        self.n_BatchNormalization_53.bias.data = self._vars[\"model3_2_4_bias\"]\n        self.n_BatchNormalization_53.running_mean.data = self._vars[\"model3_2_4_running_mean\"]\n        self.n_BatchNormalization_53.running_var.data = self._vars[\"model3_2_4_running_var\"]\n        self.n_BatchNormalization_54 = nn.BatchNorm2d(**{'num_features': 672, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_54.weight.data = self._vars[\"model3_1_0_weight\"]\n        self.n_BatchNormalization_54.bias.data = self._vars[\"model3_1_0_bias\"]\n        self.n_BatchNormalization_54.running_mean.data = self._vars[\"model3_1_0_running_mean\"]\n        self.n_BatchNormalization_54.running_var.data = self._vars[\"model3_1_0_running_var\"]\n        self.n_Conv_54 = nn.Conv2d(**{'groups': 1344, 'dilation': [1, 1], 'out_channels': 1344, 'padding': [1, 1], 'kernel_size': (3, 3), 'stride': [1, 1], 'in_channels': 1344, 'bias': False})\n        self.n_Conv_54.weight.data = self._vars[\"offset3D_0_weight\"]\n        self.n_BatchNormalization_55 = nn.BatchNorm2d(**{'num_features': 1344, 'eps': 9.999999747378752e-06, 'momentum': 0.8999999761581421})\n        self.n_BatchNormalization_55.weight.data = self._vars[\"offset3D_1_weight\"]\n        self.n_BatchNormalization_55.bias.data = self._vars[\"offset3D_1_bias\"]\n        self.n_BatchNormalization_55.running_mean.data = self._vars[\"offset3D_1_running_mean\"]\n        self.n_BatchNormalization_55.running_var.data = self._vars[\"offset3D_1_running_var\"]\n        self.n_Conv_55 = nn.Conv2d(**{'groups': 1, 'dilation': [1, 1], 'out_channels': 2016, 'padding': [0, 0], 'kernel_size': (1, 1), 'stride': [1, 1], 'in_channels': 1344, 'bias': False})\n        self.n_Conv_55.weight.data = self._vars[\"offset3D_3_weight\"]\n    \n      def forward(self, *inputs):\n        input_1, input_4, input_7 = inputs\n        t_340 = self.n_Conv_0(input_1)\n        t_341 = self.n_BatchNormalization_0(t_340)\n        t_342 = F.relu(t_341)\n        t_343 = self.n_MaxPool_0(t_342)\n        t_344 = self.n_Conv_1(input_4)\n        t_345 = self.n_BatchNormalization_1(t_344)\n        t_346 = F.relu(t_345)\n        t_347 = self.n_MaxPool_1(t_346)\n        t_348 = self.n_Conv_2(input_7)\n        t_349 = self.n_BatchNormalization_2(t_348)\n        t_350 = F.relu(t_349)\n        t_351 = self.n_MaxPool_2(t_350)\n        t_352 = torch.add(t_347, t_351)\n        t_353 = torch.cat((t_352, t_343), **{'dim': 1})\n        t_354 = self.n_Conv_3(t_353)\n        t_355 = self.n_BatchNormalization_3(t_354)\n        t_356 = F.relu(t_355)\n        t_357 = self.n_Conv_4(t_356)\n        t_358 = self.n_BatchNormalization_4(t_357)\n        t_359 = F.relu(t_358)\n        t_360 = self.n_Conv_5(t_343)\n        t_361 = self.n_BatchNormalization_5(t_360)\n        t_362 = F.relu(t_361)\n        t_363 = self.n_Conv_6(t_362)\n        t_364 = self.n_BatchNormalization_6(t_363)\n        t_365 = torch.add(t_364, t_343)\n        t_366 = F.relu(t_365)\n        t_367 = self.n_Conv_7(t_366)\n        t_368 = self.n_BatchNormalization_7(t_367)\n        t_369 = F.relu(t_368)\n        t_370 = self.n_Conv_8(t_369)\n        t_371 = self.n_BatchNormalization_8(t_370)\n        t_372 = torch.add(t_371, t_366)\n        t_373 = F.relu(t_372)\n        t_374 = self.n_Conv_9(t_373)\n        t_375 = self.n_BatchNormalization_9(t_374)\n        t_376 = F.relu(t_375)\n        t_377 = self.n_Conv_10(t_376)\n        t_378 = self.n_BatchNormalization_10(t_377)\n        t_379 = torch.add(t_378, t_373)\n        t_380 = F.relu(t_379)\n        t_381 = torch.add(t_380, t_359)\n        t_382 = self.n_Conv_11(t_381)\n        t_383 = self.n_BatchNormalization_11(t_382)\n        t_384 = F.relu(t_383)\n        t_385 = self.n_Conv_12(t_384)\n        t_386 = self.n_BatchNormalization_12(t_385)\n        t_387 = self.n_Conv_13(t_381)\n        t_388 = self.n_BatchNormalization_13(t_387)\n        t_389 = torch.add(t_386, t_388)\n        t_390 = F.relu(t_389)\n        t_391 = self.n_Conv_14(t_390)\n        t_392 = self.n_BatchNormalization_14(t_391)\n        t_393 = F.relu(t_392)\n        t_394 = self.n_Conv_15(t_393)\n        t_395 = self.n_BatchNormalization_15(t_394)\n        t_396 = torch.add(t_395, t_390)\n        t_397 = F.relu(t_396)\n        t_398 = self.n_Conv_16(t_397)\n        t_399 = self.n_BatchNormalization_16(t_398)\n        t_400 = F.relu(t_399)\n        t_401 = self.n_Conv_17(t_400)\n        t_402 = self.n_BatchNormalization_17(t_401)\n        t_403 = torch.add(t_402, t_397)\n        t_404 = F.relu(t_403)\n        t_405 = self.n_Conv_18(t_404)\n        t_406 = self.n_BatchNormalization_18(t_405)\n        t_407 = F.relu(t_406)\n        t_408 = self.n_Conv_19(t_407)\n        t_409 = self.n_BatchNormalization_19(t_408)\n        t_410 = torch.add(t_409, t_404)\n        t_411 = F.relu(t_410)\n        t_412 = self.n_Conv_20(t_411)\n        t_413 = self.n_BatchNormalization_20(t_412)\n        t_414 = F.relu(t_413)\n        t_415 = self.n_Conv_21(t_414)\n        t_416 = self.n_BatchNormalization_21(t_415)\n        t_417 = self.n_Conv_22(t_411)\n        t_418 = self.n_BatchNormalization_22(t_417)\n        t_419 = torch.add(t_416, t_418)\n        t_420 = F.relu(t_419)\n        t_421 = self.n_Conv_23(t_420)\n        t_422 = self.n_BatchNormalization_23(t_421)\n        t_423 = F.relu(t_422)\n        t_424 = self.n_Conv_24(t_423)\n        t_425 = self.n_BatchNormalization_24(t_424)\n        t_426 = torch.add(t_425, t_420)\n        t_427 = F.relu(t_426)\n        t_428 = self.n_Conv_25(t_427)\n        t_429 = self.n_BatchNormalization_25(t_428)\n        t_430 = F.relu(t_429)\n        t_431 = self.n_Conv_26(t_430)\n        t_432 = self.n_BatchNormalization_26(t_431)\n        t_433 = torch.add(t_432, t_427)\n        t_434 = F.relu(t_433)\n        t_435 = self.n_Conv_27(t_434)\n        t_436 = self.n_BatchNormalization_27(t_435)\n        t_437 = F.relu(t_436)\n        t_438 = self.n_Conv_28(t_437)\n        t_439 = self.n_BatchNormalization_28(t_438)\n        t_440 = torch.add(t_439, t_434)\n        t_441 = F.relu(t_440)\n        t_442 = self.n_Conv_29(t_441)\n        t_443 = self.n_BatchNormalization_29(t_442)\n        t_444 = F.relu(t_443)\n        t_445 = self.n_Conv_30(t_444)\n        t_446 = self.n_BatchNormalization_30(t_445)\n        t_447 = torch.add(t_446, t_441)\n        t_448 = F.relu(t_447)\n        t_449 = self.n_Conv_31(t_448)\n        t_450 = self.n_BatchNormalization_31(t_449)\n        t_451 = F.relu(t_450)\n        t_452 = self.n_Conv_32(t_451)\n        t_453 = self.n_BatchNormalization_32(t_452)\n        t_454 = torch.add(t_453, t_448)\n        t_455 = F.relu(t_454)\n        t_456 = self.n_Conv_33(t_455)\n        t_457 = self.n_BatchNormalization_33(t_456)\n        t_458 = F.relu(t_457)\n        t_459 = self.n_Conv_34(t_458)\n        t_460 = self.n_BatchNormalization_34(t_459)\n        t_461 = self.n_Conv_35(t_455)\n        t_462 = self.n_BatchNormalization_35(t_461)\n        t_463 = torch.add(t_460, t_462)\n        t_464 = F.relu(t_463)\n        t_465 = self.n_Conv_36(t_464)\n        t_466 = self.n_BatchNormalization_36(t_465)\n        t_467 = F.relu(t_466)\n        t_468 = self.n_Conv_37(t_467)\n        t_469 = self.n_BatchNormalization_37(t_468)\n        t_470 = torch.add(t_469, t_464)\n        t_471 = F.relu(t_470)\n        t_472 = self.n_Conv_38(t_471)\n        t_473 = self.n_BatchNormalization_38(t_472)\n        t_474 = F.relu(t_473)\n        t_475 = self.n_Conv_39(t_474)\n        t_476 = self.n_BatchNormalization_39(t_475)\n        t_477 = torch.add(t_476, t_471)\n        t_478 = F.relu(t_477)\n        t_479 = self.n_Conv_40(t_478)\n        t_480 = self.n_BatchNormalization_40(t_479)\n        t_481 = F.relu(t_480)\n        t_482 = self.n_Conv_41(t_481)\n        t_483 = self.n_BatchNormalization_41(t_482)\n        t_484 = F.relu(t_483)\n        t_485 = self.n_ConvTranspose_0(t_484)\n        t_486 = self.n_BatchNormalization_42(t_485)\n        t_487 = F.relu(t_486)\n        t_488 = self.n_Conv_42(t_487)\n        t_489 = self.n_BatchNormalization_43(t_488)\n        t_490 = F.relu(t_489)\n        t_491 = self.n_Conv_43(t_490)\n        t_492 = self.n_BatchNormalization_44(t_491)\n        t_493 = F.relu(t_492)\n        t_494 = self.n_Conv_44(t_493)\n        t_495 = self.n_BatchNormalization_45(t_494)\n        t_496 = F.relu(t_495)\n        t_497 = self.n_Conv_45(t_496)\n        t_498 = self.n_BatchNormalization_46(t_497)\n        t_499 = F.relu(t_498)\n        t_500 = self.n_Conv_46(t_493)\n        t_501 = self.n_BatchNormalization_47(t_500)\n        t_502 = F.relu(t_501)\n        t_503 = self.n_Conv_47(t_502)\n        t_504 = torch.tanh(t_503)\n        t_505 = self.n_Conv_48(t_493)\n        t_506 = self.n_BatchNormalization_48(t_505)\n        t_507 = F.relu(t_506)\n        t_508 = self.n_Conv_49(t_507)\n        t_509 = self.n_BatchNormalization_49(t_508)\n        t_510 = F.relu(t_509)\n        t_511 = self.n_Conv_50(t_510)\n        t_512 = self.n_BatchNormalization_50(t_511)\n        t_513 = F.relu(t_512)\n        t_514 = self.n_Conv_51(t_513)\n        t_515 = self.n_BatchNormalization_51(t_514)\n        t_516 = F.relu(t_515)\n        t_517 = self.n_Conv_52(t_510)\n        t_518 = self.n_BatchNormalization_52(t_517)\n        t_519 = F.relu(t_518)\n        t_520 = self.n_Conv_53(t_519)\n        t_521 = self.n_BatchNormalization_53(t_520)\n        t_522 = F.relu(t_521)\n        t_523 = self.n_BatchNormalization_54(t_514)\n        t_524 = F.relu(t_523)\n        t_525 = torch.cat((t_522, t_524), **{'dim': 1})\n        t_526 = self.n_Conv_54(t_525)\n        t_527 = self.n_BatchNormalization_55(t_526)\n        t_528 = F.relu(t_527)\n        t_529 = self.n_Conv_55(t_528)\n        t_530 = torch.tanh(t_529)\n        return t_504, t_499, t_530, t_516\n    \n      def compatible_auto_pad(self, input, kernel_spatial_shape, nn_mod, auto_pad=None, **kwargs):\n        input_spatial_shape = input.shape[2:]\n        d = len(input_spatial_shape)\n        strides = nn_mod.stride\n        dilations = nn_mod.dilation\n        output_spatial_shape = [math.ceil(float(l) / float(r)) for l, r in zip(input.shape[2:], strides)]\n        pt_padding = [0] * 2 * d\n        pad_shape = [0] * d\n        for i in range(d):\n          pad_shape[i] = (output_spatial_shape[i] - 1) * strides[i] + ((kernel_spatial_shape[i] - 1) * dilations[i] + 1) - input_spatial_shape[i]\n          mean = pad_shape[i] // 2\n          if auto_pad == b\"SAME_UPPER\":\n            l, r = pad_shape[i] - mean, mean\n          else:\n            l, r = mean, pad_shape[i] - mean\n          pt_padding.insert(0, r)\n          pt_padding.insert(0, l)\n        return F.pad(input, pt_padding)\n    \n    @torch.no_grad()\n    def test_run_model(inputs=[torch.from_numpy(np.random.randn(*[1, 3, 448, 448]).astype(np.float32)), torch.from_numpy(np.random.randn(*[1, 3, 448, 448]).astype(np.float32)), torch.from_numpy(np.random.randn(*[1, 3, 448, 448]).astype(np.float32))]):\n      model = Model()\n      model.eval()\n      rs = model(*inputs)\n      print(rs)\n      return rs\n    \n\n", "meta": {"hexsha": "672e6a9f80d02930c9a282d6d49e256e2d34cb6a", "size": 72171, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Untitled31.ipynb", "max_stars_repo_name": "ekdms9835/COCO-with-YOLO", "max_stars_repo_head_hexsha": "8b6e47c86f35defe31e53a82f16110e45b870333", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-28T21:17:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-28T21:17:46.000Z", "max_issues_repo_path": "Untitled31.ipynb", "max_issues_repo_name": "ekdms9835/COCO-with-YOLO", "max_issues_repo_head_hexsha": "8b6e47c86f35defe31e53a82f16110e45b870333", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Untitled31.ipynb", "max_forks_repo_name": "ekdms9835/COCO-with-YOLO", "max_forks_repo_head_hexsha": "8b6e47c86f35defe31e53a82f16110e45b870333", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 88.1208791209, "max_line_length": 858, "alphanum_fraction": 0.5923708969, "converted": true, "num_tokens": 19297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2094696714602651, "lm_q2_score": 0.02758528532457158, "lm_q1q2_score": 0.005778280654075681}}
{"text": "```python\nfrom bs4 import BeautifulSoup\nfrom tqdm import tqdm\nimport requests\nfrom functions import *\nimport os\nimport re\nfrom datetime import datetime\nimport csv\nimport pandas as pd\nimport json\npd.set_option(\"display.max_rows\", None, \"display.max_columns\", None, \"max_colwidth\", None)\n```\n\n# 1. Data ollection\n\nAt first, we needed to get the links of the anime in the first 400 pages in here [top animes ever list](https://myanimelist.net/topanime.php). Then, after collecting all the urls, we needed to download their html pages, in order to store them in a local folder and to use them without any kind of problem. After the crawling, the last thing to do was to parse the downloaded pages, i.e. taking only the requested information, and to put each anime in a tsv file. <br>\nAt the end we could start creating the Search Engine!\n\n## 1.1 Get the list of animes\n\n**THE CELL BELOW MUST BE RUNNED JUST ONE TIME, COMMENT IT**\n\n\n```python\n# get_link('https://myanimelist.net/topanime.php?limit=', 'anime_links.txt')\n```\n\n## 1.2 Crawl animes\n\n\n```python\n# how many urls has the text file\nwith open('anime_links.txt', 'r', encoding='utf-8') as file:\n    urls = list(file.read().splitlines())\n    len_list = len(urls)\n    print(\"Numbers of anime founded:\", len_list)\n\nprint(\"Numbers of pages founded:\", len_list//50+1)\n```\n\n    Numbers of anime founded: 19130\n    Numbers of pages founded: 383\n\n\nAs we can see in the cell below, there were not 400 pages, but only 383, and also there were only 19130 and not 20000, but this is not the only \"problem\" that we found...\n\n**THE CELL BELOW MUST BE RUNNED JUST ONE TIME, COMMENT IT**\n\nWe used this cell to create the folders to store the html pages.\n\n\n```python\n# os.mkdir('pages')\n# for i in range(len_list//50 + 1):\n#     os.mkdir(f'pages/page_{i + 1}')\n```\n\n**THE CELL BELOW MUST BE RUNNED JUST ONE TIME, COMMENT IT**\n\nThis cell was used to crawl each anime.\n\n\n```python\n# change the start_ind value if the process stops\n# and the crawling will continue from that index\n# change stop_ind value to recover only the pages\n# from start_ind to stop_ind\n\n# start_ind = 0\n# stop_ind = len_list\n# crawl_html(start_ind)\n```\n\n## 1.3 Parse downloaded pages\n\nAfter all the crawling, we found out that this anime, `article_7242.html` and `article_15009.html`, were missing, because the anime urls do not exist:<br>\nhttps://myanimelist.net/anime/2644/Doraemon__Treasure_of_the_Shinugumi_Mountain<br>\nhttps://myanimelist.net/anime/43247/Bing_Di_Lian\n\n**THE CELL BELOW MUST BE RUNNED JUST ONE TIME, COMMENT IT**\n\nWe used this cell to create the pages to store the tsv file for each anime.\n\n\n```python\n# os.mkdir('pages_tsv')\n# for i in range(len_list//50 + 1):\n#     os.mkdir(f'pages_tsv/page_{i + 1}')\n```\n\nIn the cell below we store the information requested for each anime in their respective tsv file, by storing in the first row the columns' names, and in the second row the information. We already executed the cell, so there is no need to do it again and we can comment it!\n\n\n```python\n# for i in tqdm(range(len_list)):\n#     # the files with the indexes below do not exist\n#     if i == 7241 or i == 15008:\n#         continue\n#     page = i//50 + 1\n#     with open(f'pages/page_{page}/article_{i+1}.html', 'r', encoding='utf-8') as file:\n#         soup = BeautifulSoup(file, 'html.parser')\n#         with open(f'pages_tsv/page_{page}/anime_{i+1}.tsv', 'w', encoding='utf-8') as tsv_file:\n#             tsv = csv.writer(tsv_file, delimiter='\\t')\n#             tsv.writerow(['animeTitle', 'animeType', 'animeNumEpisode', 'releaseDate', 'endDate', 'animeNumMembers', 'animeScore', 'animeUsers', 'animeRank', 'animePopularity', 'animeDescription', 'animeRelated', 'animeCharacters', 'animeVoices', 'animeStaff'])\n#             tsv.writerow([get_title(soup), get_type(soup), get_num_ep(soup), get_dates(soup)[0], get_dates(soup)[1], get_memb(soup), get_score(soup), get_users(soup), get_rank(soup), get_pop(soup), get_descr(soup), get_rel_an(soup), get_char(soup), get_voices(soup), get_staff(soup)])\n\n```\n\n# 2. Search Engine\n\n## 2.1. Conjunctive query\n\n\n```python\n# download all the nltk files needed\ndownload()\n\n# creates the vocabulary of every word in the Synopsis of every anime\n# and stores it in a json file\ncreate_vocab()\n```\n\n    [nltk_data] Downloading package punkt to\n    [nltk_data]     C:\\Users\\clara\\AppData\\Roaming\\nltk_data...\n    [nltk_data]   Unzipping tokenizers\\punkt.zip.\n    [nltk_data] Downloading package stopwords to\n    [nltk_data]     C:\\Users\\clara\\AppData\\Roaming\\nltk_data...\n    [nltk_data]   Unzipping corpora\\stopwords.zip.\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 383/383 [01:22<00:00,  4.62it/s]\n\n\n### 2.1.1) Create your index!\n\n\n```python\n# creates the inverted index dictionary and stores it in a json file\ninvertedIndex()\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 383/383 [00:26<00:00, 14.42it/s]\n\n\n### 2.1.2) Execute the query\n\nThe cell below is used to open the vocabulary's terms, the inverted_index and the anime_links and to store them in global variables to use in other functions.\n\n\n```python\n# opening the vocabulary\nvoc_json = open('vocabulary.json', 'r', encoding='utf-8')\nvocabulary = json.load(voc_json)\nvoc_json.close()\n\n# opening the inverted_index\ninv_ind_json = open('inverted_index.json', 'r', encoding='utf-8')\ninverted_index = json.load(inv_ind_json)\ninv_ind_json.close()\n\n# opening the anime_links\nlist_url_txt = open('anime_links.txt', 'r', encoding='utf-8')\nlist_url = list_url_txt.read().splitlines()\nlist_url_txt.close()\n```\n\n\n```python\n# taking in input the query\nquery = input(\"Insert the query for the inverted index: \")\nassert len(query) > 0, \"The query is empty!!\"\n# stemming the query\nquery_stemmed = text_mining(query)\nprint(\"Query:\", query)\n```\n\n    Query: saiyan race\n\n\n\n```python\n# creating index query dictionary\nquery_dict = dict()\nfor word in query_stemmed:\n    if word in vocabulary.keys():\n        query_dict[vocabulary[word]] = inverted_index[str(vocabulary[word])]\n```\n\n\n```python\n# saving the inverted_index of the query\nquery_index = list(query_dict.keys())\n\n\n# searching for the documents requested from the query\ndoc_list = set(query_dict[query_index[0]])\nfor query_word in query_index[1:]:\n    doc_list.intersection_update(query_dict[query_word])\n\n# creating a pandas dataframe for the final result\ndoc_df = pd.DataFrame(columns=[\"animeTitle\", \"animeDescription\", \"Url\"])\nfor doc in doc_list:\n    i = int(''.join(re.findall(r'\\d+', doc)))\n    doc_page = (i-1)//50 + 1\n    path = f'pages_tsv/page_{doc_page}/anime_{i}.tsv'\n    tsv_file = open(path, 'r', encoding='utf-8')\n    anime_tsv = csv.DictReader(tsv_file, delimiter='\\t')\n    anime = anime_tsv.__next__()\n    doc_df.loc[doc, [\"animeTitle\", \"animeDescription\", \"Url\"]] = [anime[\"animeTitle\"], anime[\"animeDescription\"], list_url[i-1]]\n```\n\n\n```python\ndoc_d = dict(selector=\"th\",\n             props=[('text-align', 'center')])\ndef make_clickable(val):\n    return '<a href=\"{}\">{}</a>'.format(val, val)\n\ndoc_df.style.set_properties(**{'text-align':'center'}).set_table_styles([doc_d]).format({'Url': make_clickable})\n```\n\n\n\n\n<style  type=\"text/css\" >\n    #T_ea89e_ th {\n          text-align: center;\n    }#T_ea89e_row0_col0,#T_ea89e_row0_col1,#T_ea89e_row0_col2,#T_ea89e_row1_col0,#T_ea89e_row1_col1,#T_ea89e_row1_col2,#T_ea89e_row2_col0,#T_ea89e_row2_col1,#T_ea89e_row2_col2,#T_ea89e_row3_col0,#T_ea89e_row3_col1,#T_ea89e_row3_col2{\n            text-align:  center;\n        }</style><table id=\"T_ea89e_\" ><thead>    <tr>        <th class=\"blank level0\" ></th>        <th class=\"col_heading level0 col0\" >animeTitle</th>        <th class=\"col_heading level0 col1\" >animeDescription</th>        <th class=\"col_heading level0 col2\" >Url</th>    </tr></thead><tbody>\n                <tr>\n                        <th id=\"T_ea89e_level0_row0\" class=\"row_heading level0 row0\" >document_365</th>\n                        <td id=\"T_ea89e_row0_col0\" class=\"data row0 col0\" >Dragon Ball Z</td>\n                        <td id=\"T_ea89e_row0_col1\" class=\"data row0 col1\" >Five years after winning the World Martial Arts tournament, Gokuu is now living a peaceful life with his wife and son. This changes, however, with the arrival of a mysterious enemy named Raditz who presents himself as Gokuu's long-lost brother. He reveals that Gokuu is a warrior from the once powerful but now virtually extinct Saiyan race, whose homeworld was completely annihilated. When he was sent to Earth as a baby, Gokuu's sole purpose was to conquer and destroy the planet; but after suffering amnesia from a head injury, his violent and savage nature changed, and instead was raised as a kind and well-mannered boy, now fighting to protect others.\n\n\nWith his failed attempt at forcibly recruiting Gokuu as an ally, Raditz warns Gokuu's friends of a new threat that's rapidly approaching Earth\u2014one that could plunge Earth into an intergalactic conflict and cause the heavens themselves to shake. A war will be fought over the seven mystical dragon balls, and only the strongest will survive in Dragon Ball Z.\n\n\n[Written by MAL Rewrite]</td>\n                        <td id=\"T_ea89e_row0_col2\" class=\"data row0 col2\" ><a href=\"https://myanimelist.net/anime/813/Dragon_Ball_Z\">https://myanimelist.net/anime/813/Dragon_Ball_Z</a></td>\n            </tr>\n            <tr>\n                        <th id=\"T_ea89e_level0_row1\" class=\"row_heading level0 row1\" >document_1035</th>\n                        <td id=\"T_ea89e_row1_col0\" class=\"data row1 col0\" >Dragon Ball Kai</td>\n                        <td id=\"T_ea89e_row1_col1\" class=\"data row1 col1\" >Five years after the events of Dragon Ball, martial arts expert Gokuu is now a grown man married to his wife Chi-Chi, with a four-year old son named Gohan. While attending a reunion on Turtle Island with his old friends Master Roshi, Krillin, Bulma and others, the festivities are interrupted when a humanoid alien named Raditz not only reveals the truth behind Gokuu's past, but kidnaps Gohan as well.\n\n\nWith Raditz displaying power beyond anything Gokuu has seen before, he is forced to team up with his old nemesis, Piccolo, in order to rescue his son. But when Gokuu and Piccolo reveal the secret of the seven mystical wish-granting Dragon Balls to Raditz, he informs the duo that there is more of his race, the Saiyans, and they won\u2019t pass up an opportunity to seize the power of the Dragon Balls for themselves.\n\n\nThese events begin the saga of Dragon Ball Kai, a story that finds Gokuu and his friends and family constantly defending the galaxy from increasingly more powerful threats. Bizarre, comical, heartwarming and threatening characters come together in a series of battles that push the powers and abilities of Gokuu and his friends beyond anything they have ever experienced.</td>\n                        <td id=\"T_ea89e_row1_col2\" class=\"data row1 col2\" ><a href=\"https://myanimelist.net/anime/6033/Dragon_Ball_Kai\">https://myanimelist.net/anime/6033/Dragon_Ball_Kai</a></td>\n            </tr>\n            <tr>\n                        <th id=\"T_ea89e_level0_row2\" class=\"row_heading level0 row2\" >document_401</th>\n                        <td id=\"T_ea89e_row2_col0\" class=\"data row2 col0\" >Dragon Ball Super: Broly</td>\n                        <td id=\"T_ea89e_row2_col1\" class=\"data row2 col1\" >Forty-one years ago on Planet Vegeta, home of the infamous Saiyan warrior race, King Vegeta noticed a baby named Broly whose latent power exceeded that of his own son. Believing that Broly's power would one day surpass that of his child, Vegeta, the king sends Broly to the desolate planet Vampa. Broly's father Paragus follows after him, intent on rescuing his son. However, his ship gets damaged, causing the two to spend years trapped on the barren world, unaware of the salvation that would one day come from an unlikely ally.\n\n\nYears later on Earth, Gokuu Son and Prince Vegeta\u2014believed to be the last survivors of the Saiyan race\u2014are busy training on a remote island. But their sparring is interrupted when the appearance of their old enemy Frieza drives them to search for the last of the wish-granting Dragon Balls on a frozen continent. Once there, Frieza shows off his new allies: Paragus and the now extremely powerful Broly. A legendary battle that shakes the foundation of the world ensues as Gokuu and Vegeta face off against Broly, a warrior without equal whose rage is just waiting to be unleashed.\n\n\n[Written by MAL Rewrite]</td>\n                        <td id=\"T_ea89e_row2_col2\" class=\"data row2 col2\" ><a href=\"https://myanimelist.net/anime/36946/Dragon_Ball_Super__Broly\">https://myanimelist.net/anime/36946/Dragon_Ball_Super__Broly</a></td>\n            </tr>\n            <tr>\n                        <th id=\"T_ea89e_level0_row3\" class=\"row_heading level0 row3\" >document_1469</th>\n                        <td id=\"T_ea89e_row3_col0\" class=\"data row3 col0\" >Dragon Ball Z Special 1: Tatta Hitori no Saishuu Kessen</td>\n                        <td id=\"T_ea89e_row3_col1\" class=\"data row3 col1\" >Bardock, Son Goku's father, is a low-ranking Saiyan soldier who was given the power to see into the future by the last remaining alien on a planet he just destroyed. He witnesses the destruction of his race and must now do his best to stop Frieza's impending massacre.\n\n\n(Source: ANN)</td>\n                        <td id=\"T_ea89e_row3_col2\" class=\"data row3 col2\" ><a href=\"https://myanimelist.net/anime/986/Dragon_Ball_Z_Special_1__Tatta_Hitori_no_Saishuu_Kessen\">https://myanimelist.net/anime/986/Dragon_Ball_Z_Special_1__Tatta_Hitori_no_Saishuu_Kessen</a></td>\n            </tr>\n    </tbody></table>\n\n\n\n## 2.2) Conjunctive query & Ranking score\n\n### 2.2.1) Inverted index\n\nWe create two dictionaries:\n- inverted_term such that for each word we have the list of documents in which it is contained in, and the relative tfIdf score.\n- inverte_doc such that for each document we have the sum of the squares of the tfidf, we will use this dictonary in the execute query.\n\nWe compute the tf-idf as $tf*idf$:\n- $tf=\\frac{n_i}{|d|}$, n is the number of occurences of the i-th word in the document and |d| is the number of words in the document\n- $idf=log_{10}\\left(\\frac{N}{n_d}\\right)$, N is the total number of documents and $n_d$ is the number of documents contaning the word\n\n\n```python\n# creates the inverted_index_tfidf and inverted_doc dictionaries and stores them in a json file\ninvertedIndex_tfidf(vocabulary, inverted_index)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 383/383 [00:27<00:00, 13.89it/s]\n\n\n### 2.2.2) Execute the query\n\nThe cell below is used to open the inverted_index_tfidf and the inverted_doc and to store them in global variables to use in other functions.\n\n\n```python\n# opening the inverted_index\ninv_ind_tfidf_json = open('inverted_index_tfidf.json', 'r', encoding='utf-8')\ninverted_index_tfidf = json.load(inv_ind_tfidf_json)\ninv_ind_tfidf_json.close()\n\n# opening the anime_links\ninv_doc_json = open('inverted_doc.json', 'r', encoding='utf-8')\ninverted_doc = json.load(inv_doc_json)\ninv_doc_json.close()\n```\n\nGiven a query we get the set of documents containing all the words in the query and sort them according to their similarity to the query\n\n- First we consider only the documents that contain all the words in the query.\n\n- We create a dictionary called numerator such that for each document we have the tf-idf sum of the words in the query in reference to the document.\n\n- We compute the cosine similarity for each document as $ cos(\\theta) = \\frac{(\\vec{q} \\cdot \\vec{d})}{(|{\\vec{q}}| \\cdot |{\\vec{d}}|)}$ where:\n<p> $(\\vec{q} \\cdot \\vec{d})$ is the intersection of the document and the query vectors: we used the numerator dictonary argument for each document as intersection;<p>\n<p> $|{\\vec{q}}| \\cdot |{\\vec{d}}|$  are the norms of the document and query vectors . We compute $|{\\vec{q}}|$ as the square root of the length of the query (because the query vector has only components equal to 1 corresponding to the query words). We compute $|{\\vec{d}}|$ as the square root of the sum of the squares of the tf-idf of all words in the document (so we use the inverted_doc dictonary to compute the document norm)<p>\n\n- Then we create the result dictonary to store for each document the corresponding cosine similarity to the query.\n\n\n```python\n# taking in input the query\nquery_2 = input(\"Insert the query for the inverted index tfidf: \")\nk = int(input(\"Insert k: \"))\nassert len(query_2) > 0, \"The query is empty!!\"\nassert isinstance(k, int), \"k should be an integer!!\"\n# stemming the query\nquery_stemmed_2 = text_mining(query_2)\nprint(\"Query:\", query_2)\nprint('k:', k)\n```\n\n    Query: saiyan race\n    k: 3\n\n\n\n```python\n# creating a pandas dataframe for the final result\ndoc_df_2 = pd.DataFrame(columns=[\"animeTitle\", \"animeDescription\", \"Url\", \"Similarity\"])\nfinal_doc, result = top_k_documents(k, query=query_stemmed_2, inverted_index=inverted_index, inverted_index_tfidf=inverted_index_tfidf, inverted_doc=inverted_doc, vocabulary=vocabulary)\nfor doc in final_doc:\n    i = int(''.join(re.findall(r'\\d+', doc)))\n    doc_page = (i-1)//50 + 1\n    path = f'pages_tsv/page_{doc_page}/anime_{i}.tsv'\n    tsv_file = open(path, 'r', encoding='utf-8')\n    anime_tsv = csv.DictReader(tsv_file, delimiter='\\t')\n    anime = anime_tsv.__next__()\n    doc_df_2.loc[doc, [\"animeTitle\", \"animeDescription\", \"Url\", \"Similarity\"]] = [anime[\"animeTitle\"], anime[\"animeDescription\"], list_url[i-1], result[doc]]\n```\n\n\n```python\ndoc_dict = dict(selector=\"th\",\n                props=[('text-align', 'center')])\ndef make_clickable(val):\n    return '<a href=\"{}\">{}</a>'.format(val, val)\n\ndoc_df_2.style.set_properties(**{'text-align':'center'}).set_table_styles([doc_dict]).format({'Url': make_clickable})\n```\n\n\n\n\n<style  type=\"text/css\" >\n    #T_76ae5_ th {\n          text-align: center;\n    }#T_76ae5_row0_col0,#T_76ae5_row0_col1,#T_76ae5_row0_col2,#T_76ae5_row0_col3,#T_76ae5_row1_col0,#T_76ae5_row1_col1,#T_76ae5_row1_col2,#T_76ae5_row1_col3,#T_76ae5_row2_col0,#T_76ae5_row2_col1,#T_76ae5_row2_col2,#T_76ae5_row2_col3{\n            text-align:  center;\n        }</style><table id=\"T_76ae5_\" ><thead>    <tr>        <th class=\"blank level0\" ></th>        <th class=\"col_heading level0 col0\" >animeTitle</th>        <th class=\"col_heading level0 col1\" >animeDescription</th>        <th class=\"col_heading level0 col2\" >Url</th>        <th class=\"col_heading level0 col3\" >Similarity</th>    </tr></thead><tbody>\n                <tr>\n                        <th id=\"T_76ae5_level0_row0\" class=\"row_heading level0 row0\" >document_1469</th>\n                        <td id=\"T_76ae5_row0_col0\" class=\"data row0 col0\" >Dragon Ball Z Special 1: Tatta Hitori no Saishuu Kessen</td>\n                        <td id=\"T_76ae5_row0_col1\" class=\"data row0 col1\" >Bardock, Son Goku's father, is a low-ranking Saiyan soldier who was given the power to see into the future by the last remaining alien on a planet he just destroyed. He witnesses the destruction of his race and must now do his best to stop Frieza's impending massacre.\n\n\n(Source: ANN)</td>\n                        <td id=\"T_76ae5_row0_col2\" class=\"data row0 col2\" ><a href=\"https://myanimelist.net/anime/986/Dragon_Ball_Z_Special_1__Tatta_Hitori_no_Saishuu_Kessen\">https://myanimelist.net/anime/986/Dragon_Ball_Z_Special_1__Tatta_Hitori_no_Saishuu_Kessen</a></td>\n                        <td id=\"T_76ae5_row0_col3\" class=\"data row0 col3\" >0.320894</td>\n            </tr>\n            <tr>\n                        <th id=\"T_76ae5_level0_row1\" class=\"row_heading level0 row1\" >document_401</th>\n                        <td id=\"T_76ae5_row1_col0\" class=\"data row1 col0\" >Dragon Ball Super: Broly</td>\n                        <td id=\"T_76ae5_row1_col1\" class=\"data row1 col1\" >Forty-one years ago on Planet Vegeta, home of the infamous Saiyan warrior race, King Vegeta noticed a baby named Broly whose latent power exceeded that of his own son. Believing that Broly's power would one day surpass that of his child, Vegeta, the king sends Broly to the desolate planet Vampa. Broly's father Paragus follows after him, intent on rescuing his son. However, his ship gets damaged, causing the two to spend years trapped on the barren world, unaware of the salvation that would one day come from an unlikely ally.\n\n\nYears later on Earth, Gokuu Son and Prince Vegeta\u2014believed to be the last survivors of the Saiyan race\u2014are busy training on a remote island. But their sparring is interrupted when the appearance of their old enemy Frieza drives them to search for the last of the wish-granting Dragon Balls on a frozen continent. Once there, Frieza shows off his new allies: Paragus and the now extremely powerful Broly. A legendary battle that shakes the foundation of the world ensues as Gokuu and Vegeta face off against Broly, a warrior without equal whose rage is just waiting to be unleashed.\n\n\n[Written by MAL Rewrite]</td>\n                        <td id=\"T_76ae5_row1_col2\" class=\"data row1 col2\" ><a href=\"https://myanimelist.net/anime/36946/Dragon_Ball_Super__Broly\">https://myanimelist.net/anime/36946/Dragon_Ball_Super__Broly</a></td>\n                        <td id=\"T_76ae5_row1_col3\" class=\"data row1 col3\" >0.085567</td>\n            </tr>\n            <tr>\n                        <th id=\"T_76ae5_level0_row2\" class=\"row_heading level0 row2\" >document_365</th>\n                        <td id=\"T_76ae5_row2_col0\" class=\"data row2 col0\" >Dragon Ball Z</td>\n                        <td id=\"T_76ae5_row2_col1\" class=\"data row2 col1\" >Five years after winning the World Martial Arts tournament, Gokuu is now living a peaceful life with his wife and son. This changes, however, with the arrival of a mysterious enemy named Raditz who presents himself as Gokuu's long-lost brother. He reveals that Gokuu is a warrior from the once powerful but now virtually extinct Saiyan race, whose homeworld was completely annihilated. When he was sent to Earth as a baby, Gokuu's sole purpose was to conquer and destroy the planet; but after suffering amnesia from a head injury, his violent and savage nature changed, and instead was raised as a kind and well-mannered boy, now fighting to protect others.\n\n\nWith his failed attempt at forcibly recruiting Gokuu as an ally, Raditz warns Gokuu's friends of a new threat that's rapidly approaching Earth\u2014one that could plunge Earth into an intergalactic conflict and cause the heavens themselves to shake. A war will be fought over the seven mystical dragon balls, and only the strongest will survive in Dragon Ball Z.\n\n\n[Written by MAL Rewrite]</td>\n                        <td id=\"T_76ae5_row2_col2\" class=\"data row2 col2\" ><a href=\"https://myanimelist.net/anime/813/Dragon_Ball_Z\">https://myanimelist.net/anime/813/Dragon_Ball_Z</a></td>\n                        <td id=\"T_76ae5_row2_col3\" class=\"data row2 col3\" >0.067677</td>\n            </tr>\n    </tbody></table>\n\n\n\nTo check that we were computing the cosine similarity in the right way, we did some tests considering the description of some documents as a query.\n<p>In the first test we used as a query the description of document 401 and the cosine similarity is 0.65, it is a high similarity value, but the value should have been around 1 (having used the document description itself). This does not happen because the description of the 401 document is very long (the number of words is high) and therefore the cosine similarity is less reliable. <p>\n<p>In the second test instead we used the description of document 203 which has only 7 words and in this case the cosine similarity is 0.96.<p>\n\n#### FIRST TEST\nUsing all anime description of document_401\n\n\n```python\n# taking in input the query\nquery_2 = input(\"Insert the query for the first test: \")\nk = int(input(\"Insert k: \"))\nassert len(query_2) > 0, \"The query is empty!!\"\nassert isinstance(k, int), \"k should be an integer!!\"\n# stemming the query\nquery_stemmed_2 = text_mining(query_2)\nprint(\"Query:\", query_2)\nprint('k:', k)\n```\n\n    Query: Forty-one years ago on Planet Vegeta, home of the infamous Saiyan warrior race, King Vegeta noticed a baby named Broly whose latent power exceeded that of his own son. Believing that Broly's power would one day surpass that of his child, Vegeta, the king sends Broly to the desolate planet Vampa. Broly's father Paragus follows after him, intent on rescuing his son. However, his ship gets damaged, causing the two to spend years trapped on the barren world, unaware of the salvation that would one day come from an unlikely ally. Years later on Earth, Gokuu Son and Prince Vegeta\u2014believed to be the last survivors of the Saiyan race\u2014are busy training on a remote island. But their sparring is interrupted when the appearance of their old enemy Frieza drives them to search for the last of the wish-granting Dragon Balls on a frozen continent. Once there, Frieza shows off his new allies: Paragus and the now extremely powerful Broly. A legendary battle that shakes the foundation of the world ensues as Gokuu and Vegeta face off against Broly, a warrior without equal whose rage is just waiting to be unleashed. [Written by MAL Rewrite]\n    k: 1\n\n\n\n```python\n# creating a pandas dataframe for the final result\ndoc_df_2 = pd.DataFrame(columns=[\"animeTitle\", \"animeDescription\", \"Url\", \"Similarity\"])\nfinal_doc, result = top_k_documents(k, query=query_stemmed_2, inverted_index=inverted_index, inverted_index_tfidf=inverted_index_tfidf, inverted_doc=inverted_doc, vocabulary=vocabulary)\nfor doc in final_doc:\n    i = int(''.join(re.findall(r'\\d+', doc)))\n    doc_page = (i-1)//50 + 1\n    path = f'pages_tsv/page_{doc_page}/anime_{i}.tsv'\n    tsv_file = open(path, 'r', encoding='utf-8')\n    anime_tsv = csv.DictReader(tsv_file, delimiter='\\t')\n    anime = anime_tsv.__next__()\n    doc_df_2.loc[doc, [\"animeTitle\", \"animeDescription\", \"Url\", \"Similarity\"]] = [anime[\"animeTitle\"], anime[\"animeDescription\"], list_url[i-1], result[doc]]\n```\n\n\n```python\ndoc_dict = dict(selector=\"th\",\n                props=[('text-align', 'center')])\ndef make_clickable(val):\n    return '<a href=\"{}\">{}</a>'.format(val, val)\n\ndoc_df_2.style.set_properties(**{'text-align':'center'}).set_table_styles([doc_dict]).format({'Url': make_clickable})\n```\n\n\n\n\n<style  type=\"text/css\" >\n    #T_5ab15_ th {\n          text-align: center;\n    }#T_5ab15_row0_col0,#T_5ab15_row0_col1,#T_5ab15_row0_col2,#T_5ab15_row0_col3{\n            text-align:  center;\n        }</style><table id=\"T_5ab15_\" ><thead>    <tr>        <th class=\"blank level0\" ></th>        <th class=\"col_heading level0 col0\" >animeTitle</th>        <th class=\"col_heading level0 col1\" >animeDescription</th>        <th class=\"col_heading level0 col2\" >Url</th>        <th class=\"col_heading level0 col3\" >Similarity</th>    </tr></thead><tbody>\n                <tr>\n                        <th id=\"T_5ab15_level0_row0\" class=\"row_heading level0 row0\" >document_401</th>\n                        <td id=\"T_5ab15_row0_col0\" class=\"data row0 col0\" >Dragon Ball Super: Broly</td>\n                        <td id=\"T_5ab15_row0_col1\" class=\"data row0 col1\" >Forty-one years ago on Planet Vegeta, home of the infamous Saiyan warrior race, King Vegeta noticed a baby named Broly whose latent power exceeded that of his own son. Believing that Broly's power would one day surpass that of his child, Vegeta, the king sends Broly to the desolate planet Vampa. Broly's father Paragus follows after him, intent on rescuing his son. However, his ship gets damaged, causing the two to spend years trapped on the barren world, unaware of the salvation that would one day come from an unlikely ally.\n\n\nYears later on Earth, Gokuu Son and Prince Vegeta\u2014believed to be the last survivors of the Saiyan race\u2014are busy training on a remote island. But their sparring is interrupted when the appearance of their old enemy Frieza drives them to search for the last of the wish-granting Dragon Balls on a frozen continent. Once there, Frieza shows off his new allies: Paragus and the now extremely powerful Broly. A legendary battle that shakes the foundation of the world ensues as Gokuu and Vegeta face off against Broly, a warrior without equal whose rage is just waiting to be unleashed.\n\n\n[Written by MAL Rewrite]</td>\n                        <td id=\"T_5ab15_row0_col2\" class=\"data row0 col2\" ><a href=\"https://myanimelist.net/anime/36946/Dragon_Ball_Super__Broly\">https://myanimelist.net/anime/36946/Dragon_Ball_Super__Broly</a></td>\n                        <td id=\"T_5ab15_row0_col3\" class=\"data row0 col3\" >0.655309</td>\n            </tr>\n    </tbody></table>\n\n\n\n#### SECOND TEST\nUsing the description of document_203\n\n\n```python\n# taking in input the query\nquery_2 = input(\"Insert the query for the second test: \")\nk = int(input(\"Insert k: \"))\nassert len(query_2) > 0, \"The query is empty!!\"\nassert isinstance(k, int), \"k should be an integer!!\"\n# stemming the query\nquery_stemmed_2 = text_mining(query_2)\nprint(\"Query:\", query_2)\nprint('k:', k)\n```\n\n    Query: Two special episodes bundled in the fourth and fifth volume of the Blu-ray/DVD.\n    k: 1\n\n\n\n```python\n# creating a pandas dataframe for the final result\ndoc_df_2 = pd.DataFrame(columns=[\"animeTitle\", \"animeDescription\", \"Url\", \"Similarity\"])\nfinal_doc, result = top_k_documents(k, query=query_stemmed_2, inverted_index=inverted_index, inverted_index_tfidf=inverted_index_tfidf, inverted_doc=inverted_doc, vocabulary=vocabulary)\nfor doc in final_doc:\n    i = int(''.join(re.findall(r'\\d+', doc)))\n    doc_page = (i-1)//50 + 1\n    path = f'pages_tsv/page_{doc_page}/anime_{i}.tsv'\n    tsv_file = open(path, 'r', encoding='utf-8')\n    anime_tsv = csv.DictReader(tsv_file, delimiter='\\t')\n    anime = anime_tsv.__next__()\n    doc_df_2.loc[doc, [\"animeTitle\", \"animeDescription\", \"Url\", \"Similarity\"]] = [anime[\"animeTitle\"], anime[\"animeDescription\"], list_url[i-1], result[doc]]\n```\n\n\n```python\ndoc_dict = dict(selector=\"th\",\n                props=[('text-align', 'center')])\ndef make_clickable(val):\n    return '<a href=\"{}\">{}</a>'.format(val, val)\n\ndoc_df_2.style.set_properties(**{'text-align':'center'}).set_table_styles([doc_dict]).format({'Url': make_clickable})\n```\n\n\n\n\n<style  type=\"text/css\" >\n    #T_d3d35_ th {\n          text-align: center;\n    }#T_d3d35_row0_col0,#T_d3d35_row0_col1,#T_d3d35_row0_col2,#T_d3d35_row0_col3{\n            text-align:  center;\n        }</style><table id=\"T_d3d35_\" ><thead>    <tr>        <th class=\"blank level0\" ></th>        <th class=\"col_heading level0 col0\" >animeTitle</th>        <th class=\"col_heading level0 col1\" >animeDescription</th>        <th class=\"col_heading level0 col2\" >Url</th>        <th class=\"col_heading level0 col3\" >Similarity</th>    </tr></thead><tbody>\n                <tr>\n                        <th id=\"T_d3d35_level0_row0\" class=\"row_heading level0 row0\" >document_203</th>\n                        <td id=\"T_d3d35_row0_col0\" class=\"data row0 col0\" >Natsume Yuujinchou Go Specials</td>\n                        <td id=\"T_d3d35_row0_col1\" class=\"data row0 col1\" >Two special episodes bundled in the fourth and fifth volume of the Blu-ray/DVD.</td>\n                        <td id=\"T_d3d35_row0_col2\" class=\"data row0 col2\" ><a href=\"https://myanimelist.net/anime/34534/Natsume_Yuujinchou_Go_Specials\">https://myanimelist.net/anime/34534/Natsume_Yuujinchou_Go_Specials</a></td>\n                        <td id=\"T_d3d35_row0_col3\" class=\"data row0 col3\" >0.961133</td>\n            </tr>\n    </tbody></table>\n\n\n\n# 3. Define a new Score!\n\nWe define the new score as:\n\\begin{equation}\nscore={\\sum_{j\u2208columns}(score_j)}\n\\end{equation}\nwhere $columns={animeTitle, animeType, ..., animeStaff}$\n\nWe compute the scores in this way:\n- the title score: $score_t={\\sum_{i\u2208query}\\frac{2*n_i}{len(title)+len(query)}}$, where $n_i$ is the number of occurrences of $word_i$ of the query in the title. We are considering how many times the query word appears in the title, normalizing by the sum of query length and the title length. We decided to multiply the numerator by two in order to try to give greater importance of similarity to the queries with a word that appeared in the title.\n- the type score: $score_p={\\sum_{i\u2208query}\\frac{n_i}{2}}$, where $n_i$ is different from zero, if in the query is specified the anime type, in that case we consider as score: $n_i$ divided by two to not give much importance to the score type.\n- score_episode, score_members, score_animeScore, score_users, score_rank, score_popularity are computed such that their sum is equal to one; we give much importance if the query match with score_animeScore and with score_rank, score_episode. The others are less significant in the similarity in our opinion, so we did not give them much weight.\n- the description score: $score_d={\\sum_{i\u2208query}\\frac{2*d_i}{len(description)+len(query)}}$, where $d_i$ is the occurrences of the $word_i$ of the query in the description. We compute this score with the same rules of the title_score.\n- the releaseDate_score and endDate_score: we consider these scores equal to 0.5 if in the query appears an year that coincides with the releasedate or enddate year. We compute these scores taking into account only the year because we think the user is more likely to do a search by remembering only the releasedate or enddate year rather than the exact date with day and month.\n- the score_staff, score_characters, score_voice: we compute these scores adding 0.5 every time a name in the query appears in the list of strings. We decided to add 0.5 because in this way, if the users only enter the name or the surname of the character/staff/voice the relative score will be 0.5, instead if the users enters both the name and the surname the relative score is equal to 1 (as the similarity is more precise).\n\n\n```python\nquery = input(\"insert the query for the new score: \")\nk = int(input(\"insert k: \"))\nassert len(query) > 0, \"The query is empty!!\"\nassert isinstance(k, int), \"k should be an integer!!\"\n# stemming the query\nprint(\"Query:\", query)\nprint('k:', k)\n```\n\n    Query: gintama enchousen Youichi 2018 64\n    k: 5\n\n\n\n```python\nnew_score(query)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 383/383 [14:39<00:00,  2.30s/it]\n\n\n\n```python\n# opening the score_dict\nscore_dict_json = open('score_dict.json', 'r', encoding='utf-8')\nscore_dict = json.load(score_dict_json)\nscore_dict_json.close()\n\n# opening the heap list\nheap_json = open('heap.json', 'r', encoding='utf-8')\nheap = json.load(heap_json)\nheap_json.close()\n```\n\n\n```python\n# creating a pandas dataframe for the final result\ndoc_df = pd.DataFrame(columns=[\"animeTitle\", \"animeDescription\", \"Url\", \"Similarity\"])\nfinal_doc, final_score_dict = top_k_documents(k, heap=heap, score_dict=score_dict)\nfor doc in final_doc:\n    i = int(''.join(re.findall(r'\\d+', doc)))\n    doc_page = (i-1)//50 + 1\n    path = f'pages_tsv/page_{doc_page}/anime_{i}.tsv'\n    tsv_file = open(path, 'r', encoding='utf-8')\n    anime_tsv = csv.DictReader(tsv_file, delimiter='\\t')\n    anime = anime_tsv.__next__()\n    doc_df.loc[doc, [\"animeTitle\", \"animeDescription\", \"Url\", \"Similarity\"]] = [anime[\"animeTitle\"], anime[\"animeDescription\"], list_url[i-1], final_score_dict[doc]]\n```\n\n\n```python\ndoc_dict = dict(selector=\"th\",\n                props=[('text-align', 'center')])\ndef make_clickable(val):\n    return '<a href=\"{}\">{}</a>'.format(val, val)\n\ndoc_df.style.set_properties(**{'text-align':'center'}).set_table_styles([doc_dict]).format({'Url': make_clickable})\n```\n\n\n\n\n<style  type=\"text/css\" >\n    #T_ae00a_ th {\n          text-align: center;\n    }#T_ae00a_row0_col0,#T_ae00a_row0_col1,#T_ae00a_row0_col2,#T_ae00a_row0_col3,#T_ae00a_row1_col0,#T_ae00a_row1_col1,#T_ae00a_row1_col2,#T_ae00a_row1_col3,#T_ae00a_row2_col0,#T_ae00a_row2_col1,#T_ae00a_row2_col2,#T_ae00a_row2_col3,#T_ae00a_row3_col0,#T_ae00a_row3_col1,#T_ae00a_row3_col2,#T_ae00a_row3_col3,#T_ae00a_row4_col0,#T_ae00a_row4_col1,#T_ae00a_row4_col2,#T_ae00a_row4_col3{\n            text-align:  center;\n        }</style><table id=\"T_ae00a_\" ><thead>    <tr>        <th class=\"blank level0\" ></th>        <th class=\"col_heading level0 col0\" >animeTitle</th>        <th class=\"col_heading level0 col1\" >animeDescription</th>        <th class=\"col_heading level0 col2\" >Url</th>        <th class=\"col_heading level0 col3\" >Similarity</th>    </tr></thead><tbody>\n                <tr>\n                        <th id=\"T_ae00a_level0_row0\" class=\"row_heading level0 row0\" >document_9</th>\n                        <td id=\"T_ae00a_row0_col0\" class=\"data row0 col0\" >Gintama': Enchousen</td>\n                        <td id=\"T_ae00a_row0_col1\" class=\"data row0 col1\" >While Gintoki Sakata was away, the Yorozuya found themselves a new leader: Kintoki, Gintoki's golden-haired doppelganger. In order to regain his former position, Gintoki will need the help of those around him, a troubling feat when no one can remember him! Between Kintoki and Gintoki, who will claim the throne as the main character?\n\n\nIn addition, Yorozuya make a trip back down to red-light district of Yoshiwara to aid an elderly courtesan in her search for her long-lost lover. Although the district is no longer in chains beneath the earth's surface, the trio soon learn of the tragic backstories of Yoshiwara's inhabitants that still haunt them. With flashback after flashback, this quest has Yorozuya witnessing everlasting love and protecting it as best they can with their hearts and souls.\n\nGintama': Enchousen includes moments of action-packed intensity along with their usual lighthearted, slapstick humor for Gintoki and his friends.\n\n\n[Written by MAL Rewrite]</td>\n                        <td id=\"T_ae00a_row0_col2\" class=\"data row0 col2\" ><a href=\"https://myanimelist.net/anime/15417/Gintama__Enchousen\">https://myanimelist.net/anime/15417/Gintama__Enchousen</a></td>\n                        <td id=\"T_ae00a_row0_col3\" class=\"data row0 col3\" >0.979227</td>\n            </tr>\n            <tr>\n                        <th id=\"T_ae00a_level0_row1\" class=\"row_heading level0 row1\" >document_10</th>\n                        <td id=\"T_ae00a_row1_col0\" class=\"data row1 col0\" >Gintama: The Final</td>\n                        <td id=\"T_ae00a_row1_col1\" class=\"data row1 col1\" >New Gintama movie.</td>\n                        <td id=\"T_ae00a_row1_col2\" class=\"data row1 col2\" ><a href=\"https://myanimelist.net/anime/39486/Gintama__The_Final\">https://myanimelist.net/anime/39486/Gintama__The_Final</a></td>\n                        <td id=\"T_ae00a_row1_col3\" class=\"data row1 col3\" >0.972222</td>\n            </tr>\n            <tr>\n                        <th id=\"T_ae00a_level0_row2\" class=\"row_heading level0 row2\" >document_22</th>\n                        <td id=\"T_ae00a_row2_col0\" class=\"data row2 col0\" >Gintama.: Shirogane no Tamashii-hen - Kouhan-sen</td>\n                        <td id=\"T_ae00a_row2_col1\" class=\"data row2 col1\" >Second Season of the final arc of Gintama.</td>\n                        <td id=\"T_ae00a_row2_col2\" class=\"data row2 col2\" ><a href=\"https://myanimelist.net/anime/37491/Gintama__Shirogane_no_Tamashii-hen_-_Kouhan-sen\">https://myanimelist.net/anime/37491/Gintama__Shirogane_no_Tamashii-hen_-_Kouhan-sen</a></td>\n                        <td id=\"T_ae00a_row2_col3\" class=\"data row2 col3\" >0.848485</td>\n            </tr>\n            <tr>\n                        <th id=\"T_ae00a_level0_row3\" class=\"row_heading level0 row3\" >document_15</th>\n                        <td id=\"T_ae00a_row3_col0\" class=\"data row3 col0\" >Gintama</td>\n                        <td id=\"T_ae00a_row3_col1\" class=\"data row3 col1\" >The Amanto, aliens from outer space, have invaded Earth and taken over feudal Japan. As a result, a prohibition on swords has been established, and the samurai of Japan are treated with disregard as a consequence.\n\n\nHowever one man, Gintoki Sakata, still possesses the heart of the samurai, although from his love of sweets and work as a yorozuya, one might not expect it. Accompanying him in his jack-of-all-trades line of work are Shinpachi Shimura, a boy with glasses and a strong heart, Kagura with her umbrella and seemingly bottomless stomach, as well as Sadaharu, their oversized pet dog. Of course, these odd jobs are not always simple, as they frequently have run-ins with the police, ragtag rebels, and assassins, oftentimes leading to humorous but unfortunate consequences.\n\n\nWho said life as an errand boy was easy?\n\n\n[Written by MAL Rewrite]</td>\n                        <td id=\"T_ae00a_row3_col2\" class=\"data row3 col2\" ><a href=\"https://myanimelist.net/anime/918/Gintama\">https://myanimelist.net/anime/918/Gintama</a></td>\n                        <td id=\"T_ae00a_row3_col3\" class=\"data row3 col3\" >0.833333</td>\n            </tr>\n            <tr>\n                        <th id=\"T_ae00a_level0_row4\" class=\"row_heading level0 row4\" >document_6</th>\n                        <td id=\"T_ae00a_row4_col0\" class=\"data row4 col0\" >Gintama'</td>\n                        <td id=\"T_ae00a_row4_col1\" class=\"data row4 col1\" >After a one-year hiatus, Shinpachi Shimura returns to Edo, only to stumble upon a shocking surprise: Gintoki and Kagura, his fellow Yorozuya members, have become completely different characters! Fleeing from the Yorozuya headquarters in confusion, Shinpachi finds that all the denizens of Edo have undergone impossibly extreme changes, in both appearance and personality. Most unbelievably, his sister Otae has married the Shinsengumi chief and shameless stalker Isao Kondou and is pregnant with their first child.\n\n\nBewildered, Shinpachi agrees to join the Shinsengumi at Otae and Kondou's request and finds even more startling transformations afoot both in and out of the ranks of the the organization. However, discovering that Vice Chief Toushirou Hijikata has remained unchanged, Shinpachi and his unlikely Shinsengumi ally set out to return the city of Edo to how they remember it.\n\n\nWith even more dirty jokes, tongue-in-cheek parodies, and shameless references, Gintama' follows the Yorozuya team through more of their misadventures in the vibrant, alien-filled world of Edo.\n\n\n[Written by MAL Rewrite]\n</td>\n                        <td id=\"T_ae00a_row4_col2\" class=\"data row4 col2\" ><a href=\"https://myanimelist.net/anime/9969/Gintama\">https://myanimelist.net/anime/9969/Gintama</a></td>\n                        <td id=\"T_ae00a_row4_col3\" class=\"data row4 col3\" >0.801462</td>\n            </tr>\n    </tbody></table>\n\n\n\n# 5. Algorithmic question\n\n## Write an algorithm that computes the acceptable solution with the longest possible duration.\n\n\n**MyAlg**\n\n```\nseq = the sequence of request\nquery = the list of requests\nquery_index = empty list\n\nfor time in query:\n    query_index.append(seq.index(time))\n\nnew_query=[0 for i in seq]\n\nfor i in query_index:\n    new_query[i] = seq[i]\n\nmax_sum_nonadjacent_element(new_query)\n```\n\n- In the first for we write the position of each element of the query in the sequence.\n- Then, we define a new vector with length equal to the length of the sequence, where the elements of the query take position according to query_index, and the other values are 0\n- we call the function \"max_sum_nonadjacent_elements(new_query)\" while keeping track of the elements we are summing\n\n**Max sum non-adjacent element(A)**\n\n```\nincl_sum = A[0]\nexcl_sum = 0\n\nfor i = 1 to length(A):\n    max_sum = max(incl_sum, excl_sum)\n    incl_sum = excl_sum + A[i]\n    excl_sum = max_sum\n\nmax_sum = max(incl_sum, excl_sum)\n\nreturn max_sum\n```\n\n- We take two variables incl_sum and excl_sum and we itialize incl_sum equal to the first element and excl_sum as zero;\n- For each element find the maximum of incl_sum and excl_sum;\n- Incl_sum will be equal to excl_sum at the previous step plus the current element;\n- excl_sum will be the maximum between excl_sum and incl_sum at the previous step;\n- After all the steps, we will take the maximum between incl_sum and excl_sum as result.\n\n## Implement a program that given in input an instance in the form given above, gives the optimal solution.\n\n\n```python\ndef MyAlg(seq,query):\n\n    query_index=[]\n    seq1=seq.copy()\n\n    for time in query:\n        try:\n            query_index.append(seq.index(time))\n            seq[seq.index(time)]=0\n        except:\n            print('not valid query')\n            return\n\n    new_query=[0 for i in seq]\n\n    # creating new_query as explained before\n    for i in query_index:\n        new_query[i] = seq1[i]\n\n    # using max_sum_nonadjacent_elements(new_query)\n    incl_sum = new_query[0]\n    excl_sum = 0\n    ind1 = [0]             # indeces of the inclusive sum\n    ind2 = []              # indeces of the exclusive sum\n    indm = ind1[:]         # indeces of max sum\n    max_sum = incl_sum\n\n    for i in range(1, len(new_query)):\n        incl_sum = excl_sum + new_query[i]\n        ind2.append(i)\n        excl_sum = max_sum\n        ind1 = indm[:]\n        if incl_sum > excl_sum:\n            max_sum = incl_sum\n            indm = ind2[:]\n            ind2 = ind1 [:]\n        else:\n            max_sum = excl_sum\n            indm = ind1[:]\n            ind2 = ind1[:]\n\n    query_opt = []\n\n    for i in indm:\n        query_opt.append(new_query[i])\n\n    print(f\"The optimal solution is: {query_opt}\")\n    print(f\"The duration is: {max_sum}\")\n```\n\n\n```python\nseq=[30, 40, 25, 50, 30, 20]\nquery=[30, 40, 25, 30]\nMyAlg(seq, query)\n```\n\n    The optimal solution is: [30, 25, 30]\n    The duration is: 85\n\n\nWe added a try/except to avoid an overlap of appointments as shown in the following example:\n\n\n```python\nseq = [30, 40, 25, 50, 30, 20]\nquery = [30, 40, 25, 50, 30, 20, 20]\nMyAlg(seq,query)\n```\n\n    not valid query\n\n\n\n", "meta": {"hexsha": "8c80512754f4d66a54cd2ee034069a1bcc008847", "size": 62070, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "main.ipynb", "max_stars_repo_name": "ClaraL27/ADM-HW3", "max_stars_repo_head_hexsha": "bf28ca0b071fb9df92ca8a8c68b7ea04985b0508", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.ipynb", "max_issues_repo_name": "ClaraL27/ADM-HW3", "max_issues_repo_head_hexsha": "bf28ca0b071fb9df92ca8a8c68b7ea04985b0508", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.ipynb", "max_forks_repo_name": "ClaraL27/ADM-HW3", "max_forks_repo_head_hexsha": "bf28ca0b071fb9df92ca8a8c68b7ea04985b0508", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-14T11:16:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-14T11:16:30.000Z", "avg_line_length": 46.8806646526, "max_line_length": 7158, "alphanum_fraction": 0.6101820525, "converted": true, "num_tokens": 12492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.083890393281755, "lm_q2_score": 0.06656918341495573, "lm_q1q2_score": 0.005584514977125918}}
{"text": "```python\nimport matplotlib.pylab as pyl\nimport numpy as np\nimport pandas as pd\nimport sympy as sp\n```\n\n\n```python\nSRC_BACKUP_EXCEL_DIR = 'E:/Diablo II Resurrected/backup/excel'\nDST_EXCEL_DIR = 'E:/Diablo II Resurrected/mods/kruno/kruno.mpq/data/global/excel'\n```\n\n\n```python\ndef restore_all():\n    import shutil\n    shutil.rmtree(DST_EXCEL_DIR)\n    shutil.copytree(SRC_BACKUP_EXCEL_DIR, DST_EXCEL_DIR)\n\nrestore_all()\n```\n\n\n```python\nclass Database:\n    data: pd.DataFrame\n\n    def __init__(self, name_of_file: str):\n        self.path = f'{DST_EXCEL_DIR}/{name_of_file}.txt'\n        self.data = pd.read_csv(self.path, sep=\"\\t\", dtype=object)\n    \n    def save(self):\n        self.data.to_csv(self.path, sep='\\t', mode='w', index=False)\n\n    def get_property(self, row: int, label: str):\n        return self.data.loc[row, label]\n\n    def set_property(self, row: int, label: str, value):\n        self.data.loc[row, label] = value\n\n    def mutate_property(self, row: int, label: str, fn):\n        x = self.get_property(row, label)\n        self.set_property(row, label, fn(x))\n```\n\n\n```python\ncharstats = Database('charstats')\nhirelings = Database('hireling')\nweapons = Database('weapons')\nmisc = Database('misc')\nskills = Database('skills')\nskilldesc = Database('skilldesc')\nmonstats = Database('monstats')\nmonstats2 = Database('monstats2')\nmissiles = Database('missiles')\nlevels = Database('levels')\n```\n\nCharacter changes\n\n\n```python\nfor i in range(8):\n    if i == 5:\n        continue\n    charstats.set_property(i, 'WalkVelocity', 14)\n    charstats.set_property(i, 'RunVelocity', 16)\n    charstats.set_property(i, 'ManaRegen', 20) # 20 seconds to reach full mana\n    charstats.set_property(i, 'RunDrain', 1)\n    charstats.set_property(i, 'stamina', 200)\n\ncharstats.set_property(1, 'ManaRegen', 25) # Sorc has warmth for a big boost, and generally the most mana.\ncharstats.set_property(0, 'ManaRegen', 15)\n```\n\nHireling Changes\n\n\n```python\nfor i in range(120):\n    new_hp = int(hirelings.get_property(i, 'HP')) * 10\n    hirelings.set_property(i, 'HP', new_hp)\n\nmask = monstats.data['AI'].str.contains('Hireable', na=False)\nfor i in monstats.data.loc[mask].index:\n    idx = int(i)\n\n    print(f\"{idx}: {monstats.get_property(idx, 'Id')}, {monstats.get_property(idx, '*hcIdx')}\")\n\n    monstats.set_property(idx, 'Velocity', 16)\n    monstats.set_property(idx, 'Run', 20)\n\n    monstats.set_property(idx, 'threat', 12)\n\n    monstats.set_property(idx, 'aidel', 1)\n    monstats.set_property(idx, 'aidel(N)', 1)\n    monstats.set_property(idx, 'aidel(H)', 1)\n\n    monstats.set_property(idx, 'aidist', 50)\n    monstats.set_property(idx, 'aidist(N)', 50)\n    monstats.set_property(idx, 'aidist(H)', 50)\n\n    monstats.set_property(idx, 'coldeffect', -50)\n    monstats.set_property(idx, 'coldeffect(N)', -33)\n    monstats.set_property(idx, 'coldeffect(H)', -25)\n    \n    monstats.mutate_property(idx, 'DamageRegen', lambda x: int(x) + 2)\n```\n\n    271: roguehire, 271\n    338: act2hire, 338\n    359: act3hire, 359\n    561: act5hire1, 560\n    562: act5hire2, 561\n\n\nPet buffs\n\n\n```python\n# Increase Pet defences\nmask = monstats.data['AI'].str.contains('NecroPet', na=False)\n\n# Template for values\ndata = {\n    'Id': '',\n\n    'aidel': 1,\n    'aidel(N)': 1,\n    'aidel(H)': 1,\n\n    'Velocity': 16,\n    'Run': 25,\n\n    'Drain': 100,\n    'Drain(N)': 100,\n    'Drain(H)': 100,\n    'DamageRegen': 10,\n\n    'coldeffect': -50,\n    'coldeffect(N)': -33,\n    'coldeffect(H)': -15,\n\n    'ResDm': 75,\n    'ResMa': 75,\n    'ResFi': 75,\n    'ResLi': 75,\n    'ResCo': 75,\n    'ResPo': 75,\n    'ResDm(N)': 75,\n    'ResMa(N)': 75,\n    'ResFi(N)': 75,\n    'ResLi(N)': 75,\n    'ResCo(N)': 75,\n    'ResPo(N)': 75,\n    'ResDm(H)': 75,\n    'ResMa(H)': 75,\n    'ResFi(H)': 75,\n    'ResLi(H)': 75,\n    'ResCo(H)': 75,\n    'ResPo(H)': 75,\n}\n\n# expand data to match all rows\nnum_rows = monstats.data[mask].count()[0]\ndata = {k: [v]*num_rows for k, v in data.items()}\n\n# Fill in the ids\ndata['Id'] = monstats.data.loc[mask, 'Id']\n\n# add new data to main data, but masked\ndata = pd.DataFrame.from_dict(data)\nmonstats.data.loc[mask, data.keys()] = data\n\nmonstats.data.loc[mask, list(data.keys())]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Id</th>\n      <th>aidel</th>\n      <th>aidel(N)</th>\n      <th>aidel(H)</th>\n      <th>Velocity</th>\n      <th>Run</th>\n      <th>Drain</th>\n      <th>Drain(N)</th>\n      <th>Drain(H)</th>\n      <th>DamageRegen</th>\n      <th>...</th>\n      <th>ResFi(N)</th>\n      <th>ResLi(N)</th>\n      <th>ResCo(N)</th>\n      <th>ResPo(N)</th>\n      <th>ResDm(H)</th>\n      <th>ResMa(H)</th>\n      <th>ResFi(H)</th>\n      <th>ResLi(H)</th>\n      <th>ResCo(H)</th>\n      <th>ResPo(H)</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>289</th>\n      <td>claygolem</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>16</td>\n      <td>25</td>\n      <td>100</td>\n      <td>100</td>\n      <td>100</td>\n      <td>10</td>\n      <td>...</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n    </tr>\n    <tr>\n      <th>290</th>\n      <td>bloodgolem</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>16</td>\n      <td>25</td>\n      <td>100</td>\n      <td>100</td>\n      <td>100</td>\n      <td>10</td>\n      <td>...</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n    </tr>\n    <tr>\n      <th>291</th>\n      <td>irongolem</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>16</td>\n      <td>25</td>\n      <td>100</td>\n      <td>100</td>\n      <td>100</td>\n      <td>10</td>\n      <td>...</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n    </tr>\n    <tr>\n      <th>292</th>\n      <td>firegolem</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>16</td>\n      <td>25</td>\n      <td>100</td>\n      <td>100</td>\n      <td>100</td>\n      <td>10</td>\n      <td>...</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n    </tr>\n    <tr>\n      <th>357</th>\n      <td>valkyrie</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>16</td>\n      <td>25</td>\n      <td>100</td>\n      <td>100</td>\n      <td>100</td>\n      <td>10</td>\n      <td>...</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n    </tr>\n    <tr>\n      <th>363</th>\n      <td>necroskeleton</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>16</td>\n      <td>25</td>\n      <td>100</td>\n      <td>100</td>\n      <td>100</td>\n      <td>10</td>\n      <td>...</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n    </tr>\n    <tr>\n      <th>364</th>\n      <td>necromage</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>16</td>\n      <td>25</td>\n      <td>100</td>\n      <td>100</td>\n      <td>100</td>\n      <td>10</td>\n      <td>...</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n    </tr>\n    <tr>\n      <th>431</th>\n      <td>wolf</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>16</td>\n      <td>25</td>\n      <td>100</td>\n      <td>100</td>\n      <td>100</td>\n      <td>10</td>\n      <td>...</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n    </tr>\n    <tr>\n      <th>432</th>\n      <td>bear</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>16</td>\n      <td>25</td>\n      <td>100</td>\n      <td>100</td>\n      <td>100</td>\n      <td>10</td>\n      <td>...</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n      <td>75</td>\n    </tr>\n  </tbody>\n</table>\n<p>9 rows \u00d7 31 columns</p>\n</div>\n\n\n\n\n```python\n# increase HP of skeles\n\nfields = [\n    'minHP',\n    'maxHP',\n    'MinHP(N)',\n    'MaxHP(N)',\n    'MinHP(H)',\n    'MaxHP(H)',\n]\n\n# Before\ndisplay(monstats.data.loc[mask, fields])\n\n# Convert and manipulate\nmonstats.data.loc[mask, fields] = monstats.data.loc[mask, fields].astype('int')\nmonstats.data.loc[mask, fields] *= 5\n\n# After\nmonstats.data.loc[mask, fields]\n```\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>minHP</th>\n      <th>maxHP</th>\n      <th>MinHP(N)</th>\n      <th>MaxHP(N)</th>\n      <th>MinHP(H)</th>\n      <th>MaxHP(H)</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>289</th>\n      <td>100</td>\n      <td>100</td>\n      <td>175</td>\n      <td>175</td>\n      <td>275</td>\n      <td>275</td>\n    </tr>\n    <tr>\n      <th>290</th>\n      <td>201</td>\n      <td>201</td>\n      <td>388</td>\n      <td>388</td>\n      <td>637</td>\n      <td>637</td>\n    </tr>\n    <tr>\n      <th>291</th>\n      <td>306</td>\n      <td>306</td>\n      <td>595</td>\n      <td>595</td>\n      <td>980</td>\n      <td>980</td>\n    </tr>\n    <tr>\n      <th>292</th>\n      <td>313</td>\n      <td>313</td>\n      <td>613</td>\n      <td>613</td>\n      <td>1013</td>\n      <td>1013</td>\n    </tr>\n    <tr>\n      <th>357</th>\n      <td>400</td>\n      <td>480</td>\n      <td>400</td>\n      <td>480</td>\n      <td>400</td>\n      <td>480</td>\n    </tr>\n    <tr>\n      <th>363</th>\n      <td>21</td>\n      <td>21</td>\n      <td>30</td>\n      <td>30</td>\n      <td>42</td>\n      <td>42</td>\n    </tr>\n    <tr>\n      <th>364</th>\n      <td>61</td>\n      <td>61</td>\n      <td>88</td>\n      <td>88</td>\n      <td>123</td>\n      <td>123</td>\n    </tr>\n    <tr>\n      <th>431</th>\n      <td>16</td>\n      <td>25</td>\n      <td>46</td>\n      <td>74</td>\n      <td>79</td>\n      <td>127</td>\n    </tr>\n    <tr>\n      <th>432</th>\n      <td>12</td>\n      <td>19</td>\n      <td>34</td>\n      <td>54</td>\n      <td>57</td>\n      <td>92</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>minHP</th>\n      <th>maxHP</th>\n      <th>MinHP(N)</th>\n      <th>MaxHP(N)</th>\n      <th>MinHP(H)</th>\n      <th>MaxHP(H)</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>289</th>\n      <td>500</td>\n      <td>500</td>\n      <td>875</td>\n      <td>875</td>\n      <td>1375</td>\n      <td>1375</td>\n    </tr>\n    <tr>\n      <th>290</th>\n      <td>1005</td>\n      <td>1005</td>\n      <td>1940</td>\n      <td>1940</td>\n      <td>3185</td>\n      <td>3185</td>\n    </tr>\n    <tr>\n      <th>291</th>\n      <td>1530</td>\n      <td>1530</td>\n      <td>2975</td>\n      <td>2975</td>\n      <td>4900</td>\n      <td>4900</td>\n    </tr>\n    <tr>\n      <th>292</th>\n      <td>1565</td>\n      <td>1565</td>\n      <td>3065</td>\n      <td>3065</td>\n      <td>5065</td>\n      <td>5065</td>\n    </tr>\n    <tr>\n      <th>357</th>\n      <td>2000</td>\n      <td>2400</td>\n      <td>2000</td>\n      <td>2400</td>\n      <td>2000</td>\n      <td>2400</td>\n    </tr>\n    <tr>\n      <th>363</th>\n      <td>105</td>\n      <td>105</td>\n      <td>150</td>\n      <td>150</td>\n      <td>210</td>\n      <td>210</td>\n    </tr>\n    <tr>\n      <th>364</th>\n      <td>305</td>\n      <td>305</td>\n      <td>440</td>\n      <td>440</td>\n      <td>615</td>\n      <td>615</td>\n    </tr>\n    <tr>\n      <th>431</th>\n      <td>80</td>\n      <td>125</td>\n      <td>230</td>\n      <td>370</td>\n      <td>395</td>\n      <td>635</td>\n    </tr>\n    <tr>\n      <th>432</th>\n      <td>60</td>\n      <td>95</td>\n      <td>170</td>\n      <td>270</td>\n      <td>285</td>\n      <td>460</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# raise skeleton without corpse and enable town summon\ndata_fields = [\n    'srvstfunc', 'srvdofunc', 'cltstfunc', 'cltdofunc', \n    'InTown', 'threat', 'TargetCorpse'\n]\n\nskills.data.loc[70, data_fields] = ['', 56, '', '', 1, 12, '']\nskills.data.loc[80, data_fields] = [15, 31, 20, 31, 1, 9, 1]\n\nmonstats.data.loc[80, ['killable']] = 0\n```\n\n\n```python\n# [70, 80] = raise skele, raise mage\n\n# Damage % per level\nlvl = sp.Symbol('lvl')\ne = lvl * 10\n\ndisplay(e)\n\neqtn = sp.horner(sp.series(e, x0=10, n=2).removeO())\ndisplay(eqtn.evalf())\n\nskills.data.loc[70, 'aurastatcalc1'] = str(eqtn)\n```\n\n\n$\\displaystyle 10 lvl$\n\n\n\n$\\displaystyle 10.0 lvl$\n\n\n\n```python\n# frozen orb\n# skills.set_property(64, 'localdelay', 10)\n# skills.set_property(64, 'globaldelay', 0)\n\n# Skill synergy; par8 = 2 aka 2%\nskills.set_property(64, 'EDmgSymPerCalc', \"(skill('Ice Bolt'.blvl) + skill('Cold Mastery'.blvl))*par8\")\n\n# skills.set_property(64, 'mana', 65)\n\nskills.set_property(64, 'calc1', \"ln12 * (100 + skill('Ice Bolt'.blvl) * 10 + skill('Cold Mastery'.blvl)) / 100\")\nskills.set_property(64, 'calc2', \"ln34 * (100 + skill('Ice Bolt'.blvl) * 10 + skill('Cold Mastery'.blvl)) / 100\")\n```\n\n\n```python\n# TP, ID books, and keys\nmisc.set_property(10, 'maxstack', 100)\nmisc.set_property(11, 'maxstack', 100)\nmisc.set_property(35, 'maxstack', 100)\n```\n\n\n```python\n# Arrows + Bolts\nmisc.set_property(18, 'minstack', 512)\nmisc.set_property(18, 'maxstack', 512)\n\nmisc.set_property(20, 'minstack', 512)\nmisc.set_property(20, 'maxstack', 512)\n```\n\n\n```python\n# Javs\nweapons.set_property(47, 'minstack', 512)\nweapons.set_property(47, 'maxstack', 512)\n```\n\n\n```python\n# infinite ammo Jav\nskills.set_property(2, 'srvstfunc', '')\nskills.set_property(2, 'srvdofunc', '')\n\nskills.set_property(2, 'cltstfunc', '')\nskills.set_property(2, 'cltdofunc', '')\n\nskills.set_property(2, 'srvmissile', 'javelin')\nskills.set_property(2, 'cltmissile', 'javelin')\n\nskills.set_property(2, 'noammo', 1)\n\n# poison jav\nfor idx in [15, 25, 20, 35, 24, 14]:\n    if skills.get_property(idx, 'srvstfunc') == '4':\n        print(skills.get_property(idx, 'skill'))\n        skills.set_property(idx, 'srvstfunc', '')\n        skills.set_property(idx, 'srvdofunc', '')\n\n        skills.set_property(idx, 'cltstfunc', '')\n        skills.set_property(idx, 'cltdofunc', '')\n\n    skills.set_property(idx, 'noammo', 1)\n    skills.set_property(idx, 'decquant', '')\n```\n\n    Poison Javelin\n    Plague Javelin\n    Lightning Bolt\n    Lightning Fury\n\n\nAssassin Skill Changes\n\n\n```python\n# Assassin's Quickness skill\n# Param5 and Param6 = (base duration and duration/lvl)\n\nskills.set_property(258, 'Param5', int(16.666667 * 300 * 5))\nskills.set_property(258, 'Param6', 1000)\n```\n\n\n```python\n# Wake of Inferno buff [add physical damage and scale it off weapon by 50%]\nskills.set_property(272, 'HitShift', 8) # this scales tick damage from [1 -> 8]/8\n\n# Death Sentry Buff\nskills.set_property(272, 'EDmgSymPerCalc', \"(skill('Lightning Sentry'.lvl))*par8\")\n\n# increase shots\nmask = skills.data['skilldesc'].str.contains('sentry', na=False)\nfor i in skills.data[mask]['*Id']:\n    idx = int(i)\n    skills.set_property(idx, 'Param1', 999)\n\n# secondary skills that have to match the above\nmask = skills.data['*Param8 Description'].str.contains('# of shots', na=False)\nfor i in skills.data[mask]['*Id']:\n    idx = int(i)\n    skills.set_property(idx, 'Param8', 999)\n```\n\nMake Paladin's Prayer good.\n\n\n```python\ndata = skills.data\nfilter = data['skill'].str.contains('Prayer')\ndata.loc[filter, 'lvlmana'] = 0\n# data.loc[filter, 'usemanaondo'] = 1\n# hp\nfields = ['EMin','EMinLev1','EMinLev2','EMinLev3','EMinLev4','EMinLev5']\ndisplay(data.loc[filter, fields])\n# The level thresholds are levels 2-8, 9-16, 17-22, 23-28, 29 and beyond\ndata.loc[filter, fields] = [4, 2, 3, 4, 5, 6]\ndata.loc[filter, fields]\n```\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>EMin</th>\n      <th>EMinLev1</th>\n      <th>EMinLev2</th>\n      <th>EMinLev3</th>\n      <th>EMinLev4</th>\n      <th>EMinLev5</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>99</th>\n      <td>2</td>\n      <td>1</td>\n      <td>1</td>\n      <td>2</td>\n      <td>2</td>\n      <td>3</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>EMin</th>\n      <th>EMinLev1</th>\n      <th>EMinLev2</th>\n      <th>EMinLev3</th>\n      <th>EMinLev4</th>\n      <th>EMinLev5</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>99</th>\n      <td>4</td>\n      <td>2</td>\n      <td>3</td>\n      <td>4</td>\n      <td>5</td>\n      <td>6</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nAdd a move only skill\n\n\n```python\n# add a move only skill\nheaders = {k: '' for k in skills.data.columns.values}\ndata = headers | {\n        'skill': 'DoNothing', \n        '*Id': 365,\n        'skilldesc': 'donothing', \n        'leftskill': 1, \n        'rightskill': 1, \n        'cost add': 0,\n        '*eol': 0\n    }\n\nskills.data = skills.data.append(data, ignore_index=True)\n\nheaders = {k: '' for k in skilldesc.data.columns.values}\ndata = headers | {\n        'skilldesc': 'donothing',\n        'SkillPage': 0,\n        'SkillRow': 0,\n        'SkillColumn': 0,\n        'ListRow': 0,\n        'IconCel': 0,\n        'str name': 'SkillNameDoNothing',\n        'str short': 'SkillDescDoNothing',\n        'str long': 'SkillDescDoNothing',\n        'str alt': 'SkillNameDoNothing',\n        '*eol': 0\n    }\n\nskilldesc.data = skilldesc.data.append(data, ignore_index=True)\n\nfor i in range(8):\n    if i == 5:\n        continue\n    charstats.set_property(i+1, 'Skill 10', 'DoNothing')\n```\n\n\n```python\ndata = levels.data\ndensity_data = {'MonDen': 4, 'MonDen(N)': 3, 'MonDen(H)': 2}\n\nfor name, multiplier in density_data.items():\n    data.loc[data[name].notnull(), name] = data[data[name].notnull()][name].astype('int')\n    data.loc[data[name].notnull(), name] *= 4\n\n# data[['Name','MonDen']]\n```\n\nadd a missile that will do the base source damage as splash\n\n\n```python\n\ndata_to_copy = {k: v for k, v in \n    zip(missiles.data.columns.values,\n    missiles.data[missiles.data['Missile'].str.fullmatch('fireball')].values[0])\n}\n\ndata = data_to_copy | {\n        'Missile': 'meleesplash',\n        '*ID': missiles.data.tail(1).index.item() + 1,\n\n        'pCltDoFunc': 1,\n        'pCltHitFunc': 1,\n        'pSrvDoFunc': 1,\n        'pSrvHitFunc': 1,\n        'pSrvDmgFunc': '',\n\n        'sHitPar1': 3,\n        'cHitPar1': 3,\n        'cHitPar2': 1,\n\n        'EType': '',\n\n        'MissileSkill': 1,\n        'InitSteps': 0,\n        'Skill': 'Attack',\n        'Range': 25,\n\n        # 'ExplosionMissile': '',\n        # 'CltHitSubMissile1': '',\n\n        'TravelSound': '',\n        'HitSound': '',\n    }\n\nmissiles.data = missiles.data.append(data, ignore_index=True)\n\n# add the last missile to attack\nfilter = (skills.data['itypea1'].notna() & \n                                        (skills.data['itypea1'].str.match('mele') |         skills.data['itypea1'].str.match('spea') |\n                                        skills.data['itypea1'].str.match('h2h') |\n                                        skills.data['itypea1'].str.match('weap')))\nskills.data.loc[filter, ['srvmissile', 'cltmissiled']] = 'meleesplash'\n```\n\n\n```python\n# Add a skill to Rogue\n# 'Skill3','Mode3','Chance3','ChancePerLvl3','Level3','LvlPerLvl3'\n\nheaders = ['Skill3','Mode3','Chance3','ChancePerLvl3','Level3','LvlPerLvl3']\ndata = ['Decrepify', 4, 50, 8, 1, 1]\n\nscouts = hirelings.data['Hireling'].str.fullmatch('Rogue Scout')\nhirelings.data.loc[scouts, headers] = data\n```\n\nIncrease Monster Density\n\n\n```python\ndata = levels.data\ndensity_data = {'MonDen': 1.1, 'MonDen(N)': 1.2, 'MonDen(H)': 1.22}\n\nfor name, multiplier in density_data.items():\n    data.loc[data[name].notnull(), name] = data[data[name].notnull()][name].astype('int')\n    density = data.loc[data[name].notnull(), name].astype('int')\n    density = (density * multiplier).round().astype('int').map(lambda x: 100_000 if x > 100_000 else x)\n    data.loc[data[name].notnull(), name] = density\n\ndata[['Name','MonDen']]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Name</th>\n      <th>MonDen</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Null</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Act 1 - Town</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Act 1 - Wilderness 1</td>\n      <td>2288</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Act 1 - Wilderness 2</td>\n      <td>2288</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Act 1 - Wilderness 3</td>\n      <td>2288</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>133</th>\n      <td>Act 5 - World Stone</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>134</th>\n      <td>Act 5 - Pandemonium 1</td>\n      <td>4646</td>\n    </tr>\n    <tr>\n      <th>135</th>\n      <td>Act 5 - Pandemonium 2</td>\n      <td>3872</td>\n    </tr>\n    <tr>\n      <th>136</th>\n      <td>Act 5 - Pandemonium 3</td>\n      <td>3520</td>\n    </tr>\n    <tr>\n      <th>137</th>\n      <td>Act 5 - Pandemonium Finale</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n<p>138 rows \u00d7 2 columns</p>\n</div>\n\n\n\n\n```python\ncharstats.save()\nhirelings.save()\nweapons.save()\nmisc.save()\nskills.save()\nskilldesc.save()\nmonstats.save()\nmissiles.save()\nmonstats2.save()\nlevels.save()\n```\n", "meta": {"hexsha": "ce6acf81dcae13c79fd17ea491a88be4d1f48bb9", "size": 44238, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Tooling.ipynb", "max_stars_repo_name": "KrunoSaho/Jupyter", "max_stars_repo_head_hexsha": "219a56f16635e96a1447e79eb7599d5879d4bd99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-10T08:45:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T08:45:58.000Z", "max_issues_repo_path": "Tooling.ipynb", "max_issues_repo_name": "KrunoSaho/Jupyter", "max_issues_repo_head_hexsha": "219a56f16635e96a1447e79eb7599d5879d4bd99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tooling.ipynb", "max_forks_repo_name": "KrunoSaho/Jupyter", "max_forks_repo_head_hexsha": "219a56f16635e96a1447e79eb7599d5879d4bd99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7698519515, "max_line_length": 143, "alphanum_fraction": 0.3767575388, "converted": true, "num_tokens": 8299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27202455109402257, "lm_q2_score": 0.020332355568774867, "lm_q1q2_score": 0.005530899896280033}}
{"text": "```python\n!pip install datashader\n```\n\n    Requirement already satisfied: datashader in /opt/conda/lib/python3.6/site-packages\n    Requirement already satisfied: param>=1.6.0 in /opt/conda/lib/python3.6/site-packages (from datashader)\n    Requirement already satisfied: colorcet>=0.9.0 in /opt/conda/lib/python3.6/site-packages (from datashader)\n    Requirement already satisfied: pillow>=3.1.1 in /opt/conda/lib/python3.6/site-packages (from datashader)\n    Requirement already satisfied: pyct[cmd] in /opt/conda/lib/python3.6/site-packages (from datashader)\n    Requirement already satisfied: datashape>=0.5.1 in /opt/conda/lib/python3.6/site-packages (from datashader)\n    Requirement already satisfied: dask[complete]>=0.15.4 in /opt/conda/lib/python3.6/site-packages (from datashader)\n    Requirement already satisfied: scipy in /opt/conda/lib/python3.6/site-packages (from datashader)\n    Requirement already satisfied: numpy>=1.7 in /opt/conda/lib/python3.6/site-packages (from datashader)\n    Requirement already satisfied: xarray>=0.9.6 in /opt/conda/lib/python3.6/site-packages (from datashader)\n    Requirement already satisfied: bokeh in /opt/conda/lib/python3.6/site-packages (from datashader)\n    Requirement already satisfied: toolz>=0.7.4 in /opt/conda/lib/python3.6/site-packages (from datashader)\n    Requirement already satisfied: numba>=0.37.0 in /opt/conda/lib/python3.6/site-packages (from datashader)\n    Requirement already satisfied: scikit-image in /opt/conda/lib/python3.6/site-packages (from datashader)\n    Requirement already satisfied: pandas>=0.20.3 in /opt/conda/lib/python3.6/site-packages (from datashader)\n    Requirement already satisfied: olefile in /opt/conda/lib/python3.6/site-packages (from pillow>=3.1.1->datashader)\n    Requirement already satisfied: requests; extra == \"cmd\" in /opt/conda/lib/python3.6/site-packages (from pyct[cmd]->datashader)\n    Requirement already satisfied: pyyaml; extra == \"cmd\" in /opt/conda/lib/python3.6/site-packages (from pyct[cmd]->datashader)\n    Requirement already satisfied: multipledispatch>=0.4.7 in /opt/conda/lib/python3.6/site-packages (from datashape>=0.5.1->datashader)\n    Requirement already satisfied: python-dateutil in /opt/conda/lib/python3.6/site-packages (from datashape>=0.5.1->datashader)\n    Requirement already satisfied: cloudpickle>=0.2.1 in /opt/conda/lib/python3.6/site-packages (from dask[complete]>=0.15.4->datashader)\n    Requirement already satisfied: distributed>=1.20 in /opt/conda/lib/python3.6/site-packages (from dask[complete]>=0.15.4->datashader)\n    Requirement already satisfied: partd>=0.3.8 in /opt/conda/lib/python3.6/site-packages (from dask[complete]>=0.15.4->datashader)\n    Requirement already satisfied: tornado>=4.3 in /opt/conda/lib/python3.6/site-packages (from bokeh->datashader)\n    Requirement already satisfied: six>=1.5.2 in /opt/conda/lib/python3.6/site-packages (from bokeh->datashader)\n    Requirement already satisfied: packaging>=16.8 in /opt/conda/lib/python3.6/site-packages (from bokeh->datashader)\n    Requirement already satisfied: Jinja2>=2.7 in /opt/conda/lib/python3.6/site-packages (from bokeh->datashader)\n    Requirement already satisfied: llvmlite>=0.26.0dev0 in /opt/conda/lib/python3.6/site-packages (from numba>=0.37.0->datashader)\n    Requirement already satisfied: matplotlib>=1.3.1 in /opt/conda/lib/python3.6/site-packages (from scikit-image->datashader)\n    Requirement already satisfied: networkx>=1.8 in /opt/conda/lib/python3.6/site-packages (from scikit-image->datashader)\n    Requirement already satisfied: pytz>=2011k in /opt/conda/lib/python3.6/site-packages (from pandas>=0.20.3->datashader)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.6/site-packages (from requests; extra == \"cmd\"->pyct[cmd]->datashader)\n    Requirement already satisfied: idna<2.7,>=2.5 in /opt/conda/lib/python3.6/site-packages (from requests; extra == \"cmd\"->pyct[cmd]->datashader)\n    Requirement already satisfied: urllib3<1.23,>=1.21.1 in /opt/conda/lib/python3.6/site-packages (from requests; extra == \"cmd\"->pyct[cmd]->datashader)\n    Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.6/site-packages (from requests; extra == \"cmd\"->pyct[cmd]->datashader)\n    Requirement already satisfied: click>=6.6 in /opt/conda/lib/python3.6/site-packages (from distributed>=1.20->dask[complete]>=0.15.4->datashader)\n    Requirement already satisfied: msgpack-python in /opt/conda/lib/python3.6/site-packages (from distributed>=1.20->dask[complete]>=0.15.4->datashader)\n    Requirement already satisfied: psutil in /opt/conda/lib/python3.6/site-packages (from distributed>=1.20->dask[complete]>=0.15.4->datashader)\n    Requirement already satisfied: sortedcontainers in /opt/conda/lib/python3.6/site-packages (from distributed>=1.20->dask[complete]>=0.15.4->datashader)\n    Requirement already satisfied: tblib in /opt/conda/lib/python3.6/site-packages (from distributed>=1.20->dask[complete]>=0.15.4->datashader)\n    Requirement already satisfied: zict>=0.1.3 in /opt/conda/lib/python3.6/site-packages (from distributed>=1.20->dask[complete]>=0.15.4->datashader)\n    Requirement already satisfied: locket in /opt/conda/lib/python3.6/site-packages (from partd>=0.3.8->dask[complete]>=0.15.4->datashader)\n    Requirement already satisfied: pyparsing>=2.0.2 in /opt/conda/lib/python3.6/site-packages (from packaging>=16.8->bokeh->datashader)\n    Requirement already satisfied: MarkupSafe>=0.23 in /opt/conda/lib/python3.6/site-packages (from Jinja2>=2.7->bokeh->datashader)\n    Requirement already satisfied: cycler>=0.10 in /opt/conda/lib/python3.6/site-packages/cycler-0.10.0-py3.6.egg (from matplotlib>=1.3.1->scikit-image->datashader)\n    Requirement already satisfied: decorator>=4.1.0 in /opt/conda/lib/python3.6/site-packages (from networkx>=1.8->scikit-image->datashader)\n    Requirement already satisfied: heapdict in /opt/conda/lib/python3.6/site-packages (from zict>=0.1.3->distributed>=1.20->dask[complete]>=0.15.4->datashader)\n    \u001b[33mYou are using pip version 9.0.1, however version 18.1 is available.\n    You should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\n\n\n\n```python\n!pip install xarray\n```\n\n    Collecting xarray\n      Downloading https://files.pythonhosted.org/packages/ab/f3/c3b45f15a82d7c89cbb6f0726d047d5d2b0ec8d1933731c125ac45a38b3d/xarray-0.11.0-py2.py3-none-any.whl (490kB)\n    \u001b[K    100% |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 491kB 704kB/s eta 0:00:01\n    \u001b[?25hRequirement already satisfied: numpy>=1.12 in /opt/conda/lib/python3.6/site-packages (from xarray)\n    Requirement already satisfied: pandas>=0.19.2 in /opt/conda/lib/python3.6/site-packages (from xarray)\n    Requirement already satisfied: python-dateutil>=2 in /opt/conda/lib/python3.6/site-packages (from pandas>=0.19.2->xarray)\n    Requirement already satisfied: pytz>=2011k in /opt/conda/lib/python3.6/site-packages (from pandas>=0.19.2->xarray)\n    Requirement already satisfied: six>=1.5 in /opt/conda/lib/python3.6/site-packages (from python-dateutil>=2->pandas>=0.19.2->xarray)\n    Installing collected packages: xarray\n    Successfully installed xarray-0.11.0\n    \u001b[33mYou are using pip version 9.0.1, however version 18.1 is available.\n    You should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\n\n\n\n```python\n!pip install colorcet\n```\n\n    Collecting colorcet\n      Downloading https://files.pythonhosted.org/packages/1f/eb/428731f7d86ca2a3cc9d100155732b42854344db58e9c54b9f44419a2565/colorcet-0.9.1.tar.gz (115kB)\n    \u001b[K    100% |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 122kB 2.3MB/s ta 0:00:01\n    \u001b[?25hBuilding wheels for collected packages: colorcet\n      Running setup.py bdist_wheel for colorcet ... \u001b[?25ldone\n    \u001b[?25h  Stored in directory: /home/jovyan/.cache/pip/wheels/66/40/ff/e376873956973b2272325f670e4ead84820170de9770cb89f4\n    Successfully built colorcet\n    Installing collected packages: colorcet\n    Successfully installed colorcet-0.9.1\n    \u001b[33mYou are using pip version 9.0.1, however version 18.1 is available.\n    You should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\n\n\n\n```python\n!pip install hvplot\n```\n\n    Requirement already satisfied: hvplot in /opt/conda/lib/python3.6/site-packages\n    Requirement already satisfied: pandas in /opt/conda/lib/python3.6/site-packages (from hvplot)\n    Requirement already satisfied: holoviews>=1.10.5 in /opt/conda/lib/python3.6/site-packages (from hvplot)\n    Requirement already satisfied: bokeh>=0.12.15 in /opt/conda/lib/python3.6/site-packages (from hvplot)\n    Requirement already satisfied: pytz>=2011k in /opt/conda/lib/python3.6/site-packages (from pandas->hvplot)\n    Requirement already satisfied: numpy>=1.9.0 in /opt/conda/lib/python3.6/site-packages (from pandas->hvplot)\n    Requirement already satisfied: python-dateutil>=2.5.0 in /opt/conda/lib/python3.6/site-packages (from pandas->hvplot)\n    Requirement already satisfied: param<2.0,>=1.6.1 in /opt/conda/lib/python3.6/site-packages (from holoviews>=1.10.5->hvplot)\n    Requirement already satisfied: pyviz-comms>=0.6.0 in /opt/conda/lib/python3.6/site-packages (from holoviews>=1.10.5->hvplot)\n    Requirement already satisfied: Jinja2>=2.7 in /opt/conda/lib/python3.6/site-packages (from bokeh>=0.12.15->hvplot)\n    Requirement already satisfied: PyYAML>=3.10 in /opt/conda/lib/python3.6/site-packages (from bokeh>=0.12.15->hvplot)\n    Requirement already satisfied: tornado>=4.3 in /opt/conda/lib/python3.6/site-packages (from bokeh>=0.12.15->hvplot)\n    Requirement already satisfied: pillow>=4.0 in /opt/conda/lib/python3.6/site-packages (from bokeh>=0.12.15->hvplot)\n    Requirement already satisfied: six>=1.5.2 in /opt/conda/lib/python3.6/site-packages (from bokeh>=0.12.15->hvplot)\n    Requirement already satisfied: packaging>=16.8 in /opt/conda/lib/python3.6/site-packages (from bokeh>=0.12.15->hvplot)\n    Requirement already satisfied: MarkupSafe>=0.23 in /opt/conda/lib/python3.6/site-packages (from Jinja2>=2.7->bokeh>=0.12.15->hvplot)\n    Requirement already satisfied: olefile in /opt/conda/lib/python3.6/site-packages (from pillow>=4.0->bokeh>=0.12.15->hvplot)\n    Requirement already satisfied: pyparsing>=2.0.2 in /opt/conda/lib/python3.6/site-packages (from packaging>=16.8->bokeh>=0.12.15->hvplot)\n    \u001b[33mYou are using pip version 9.0.1, however version 18.1 is available.\n    You should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\n\n\n\n\nThis solution uses [Google OR-Tools](https://developers.google.com/optimization/) to optimize the routing for Santa. OR-Tools include a \"vehicle routing library\" for solving TSPs and a convenient Python interface. Lucky for us, it's all included in Kaggle kernels!\n\nThe start point for the route comes from model-based clustering. You can see from the city plot how the density of points varies quite a bit across the grid. The right clustering approach may work better than starting with a grid or k-means clustering. Also, breaking the cities into clusters can scale to millions of points on a typical machine if the need arises. \n\nHere is the overall approach:\n\n* Divide cities into clusters\n* Get centers for each cluster\n* Find an optimal path across centers\n* Find start and stop points for each cluster\n* Find an optimal segment for each cluster and assemble\n\n\n```python\nfrom tqdm import tqdm\nimport numpy as np\nimport pandas as pd\nfrom sympy import sieve\nimport hvplot.pandas #custom\nimport colorcet as cc\n```\n\n## Clustering \n\n#### First Look\nHexagonal binning is often a good way to quickly see the density of overlapping points. Below is a comparison of all points with a bin plot of prime cities. Prime and non-prime cities appear to be be similarly distributed with a few dark, dense areas.\n\n\n```python\ncities = pd.read_csv(\"../data/raw/cities.csv\", index_col=['CityId'])\npnums = list(sieve.primerange(0, cities.shape[0]))\ncities['isprime'] = cities.index.isin(pnums)\ndisplay(cities.head())\n\n# show all points and density of primes\nallpoints = cities.hvplot.scatter('X', 'Y',  width=380, height=350, datashade=True, \n                title='All Cities')\ncolors = list(reversed(cc.kbc))\nprimedensity = cities[cities.isprime].hvplot.hexbin(x='X', y='Y', width=420, height=350, \n                cmap=colors, title='Density of Prime Cities').options(size_index='Count', \n                min_scale=0.8, max_scale=0.95)\nallpoints + primedensity\n```\n\n#### Model-based Clustering\n\nI first tried density-based clustering, but it left too many points that didn't belong to any cluster. In some cases it's ideal to separate out the sparse points, but for TSPs it's not so good. Model-based clustering seems to be a better choice. The number of clusters is set manually. Here I'll choose a relatively high number to ease the burden on the router.\n\n\n```python\n%%time\nfrom sklearn.mixture import GaussianMixture\n\nmclusterer = GaussianMixture(n_components=250, tol=0.01, random_state=66, verbose=1)\ncities['mclust'] = mclusterer.fit_predict(cities[['X', 'Y']].values)\nnmax = cities.mclust.max()\nprint(\"{} clusters\".format(nmax+1))\n```\n\nClusters can be of different sizes with model-based clustering. Here's the distribution of cities per cluster and the scatterplot. \n\n\n```python\nhisto = cities.hvplot.hist('mclust', ylim=(0,14000), color='tan')\n\ncustcolor = cc.rainbow + cc.rainbow\ngausses = cities.hvplot.scatter('X', 'Y',  by='mclust', size=5, width=500, height=450, \n                datashade=True, dynspread=True, cmap=custcolor)\ndisplay(histo, gausses)\n```\n\n## Cluster Centers\n\nHere are the geometric centers of all the clusters. The big red dot is the North Pole.\n\n\n```python\ncenters = cities.groupby('mclust')['X', 'Y'].agg('mean').reset_index()\ndef plot_it(df, dotsize, dotcolor, dotalpha):\n    p = df.hvplot.scatter('X', 'Y', size=dotsize, xlim=(0,5100), ylim=(0,3400), width=500,\n            height=450, hover_cols=['mclust'], color=dotcolor, alpha=dotalpha)\n    return p\n\ncents = plot_it(centers, 30, 'darkblue', 0.5)\nnpole = plot_it(cities.loc[[0]], 100, 'red', 1)\ncents*npole\n```\n\n## Optimal Path across Centers\n\nOR-Tools can find an optimal path across the clusters. Here is a modified version of the code documented on [Google's TSP page](https://developers.google.com/optimization/routing/tsp).\n\n\n```python\n#%% imports\nfrom scipy.spatial.distance import pdist, squareform\nfrom ortools.constraint_solver import pywrapcp\nfrom ortools.constraint_solver import routing_enums_pb2\n\n#%% functions\ndef create_mat(df):\n    print(\"building matrix\")\n    mat = pdist(locations)\n    return squareform(mat)\n\ndef create_distance_callback(dist_matrix):\n    def distance_callback(from_node, to_node):\n      return int(dist_matrix[from_node][to_node])\n    return distance_callback\n\nstatus_dict = {0: 'ROUTING_NOT_SOLVED', \n               1: 'ROUTING_SUCCESS', \n               2: 'ROUTING_FAIL',\n               3: 'ROUTING_FAIL_TIMEOUT',\n               4: 'ROUTING_INVALID'}\n\ndef optimize(df, startnode=None, stopnode=None, fixed=False):     \n    num_nodes = df.shape[0]\n    mat = create_mat(df)\n    dist_callback = create_distance_callback(mat)\n    search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters()\n#     search_parameters.time_limit_ms = int(1000*60*numminutes)\n    search_parameters.solution_limit = num_iters \n    search_parameters.first_solution_strategy = (\n                                    routing_enums_pb2.FirstSolutionStrategy.LOCAL_CHEAPEST_INSERTION)\n    search_parameters.local_search_metaheuristic = (\n                            routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)\n\n    if fixed:\n        routemodel = pywrapcp.RoutingModel(num_nodes, 1, [startnode], [stopnode])\n    else:\n        routemodel = pywrapcp.RoutingModel(num_nodes, 1, startnode)\n    routemodel.SetArcCostEvaluatorOfAllVehicles(dist_callback)\n    \n    print(\"optimizing {} cities\".format(num_nodes)) \n    assignment = routemodel.SolveWithParameters(search_parameters)\n\n    print(\"status: \", status_dict.get(routemodel.status()))\n    print(\"travel distance: \",  str(assignment.ObjectiveValue()), \"\\n\")\n    return routemodel, assignment\n    \ndef get_route(df, startnode, stopnode, fixed): \n    routemodel, assignment = optimize(df, int(startnode), int(stopnode), fixed)\n    route_number = 0\n    node = routemodel.Start(route_number)\n    route = []\n    while not routemodel.IsEnd(node):\n        route.append(node) \n        node = assignment.Value(routemodel.NextVar(node))\n    return route\n\n```\n\n\n```python\n%%time\n#%% parameters\nnum_iters=100\n\n# main\nnnode = int(cities.loc[0, 'mclust'])\nlocations = centers[['X', 'Y']].values\nsegment = get_route(locations, nnode, 0, fixed=False)\n```\n\n\n```python\nopoints = centers.loc[segment]\ncentersline = opoints.hvplot.line('X', 'Y', xlim=(0,5100), ylim=(0,3400), color='green', width=500, \n                            height=450, hover=False) \ngausses*cents*npole*centersline\n```\n\nThe path looks reasonable... \n\n## Start and Stop Points\nThe next step is to find good start/stop points for each cluster along the path.\n* Set the start point for cluster[n] as the point closest to the center of cluster[n-1].\n* Set the stop point for cluster[n] as the point closest to the start point of cluster[n+1].\n\nThis idea comes from [Proposed Algorithms to solve Big Data traveling salesman problem](https://www.researchgate.net/publication/326325068_Proposed_Algorithms_to_solve_Big_Data_traveling_salesman_problem). Thank you Research Gate!\n\n\n```python\nopoints.reset_index(drop=True, inplace=True) #recall ordered points\ncities['clustorder'] = cities.groupby('mclust').cumcount()\n```\n\n\n```python\nfrom sklearn.neighbors import NearestNeighbors\n\nstartlist=[0]\nneigh = NearestNeighbors(n_neighbors=1, n_jobs=-1)\nfor i,m in enumerate(opoints.mclust[1:], 0):\n    neigh.fit(cities.loc[cities.mclust == m, ['X', 'Y']].values)\n    lastcenter = opoints.loc[i, ['X', 'Y']].values.reshape(1, -1)\n    closestart = neigh.kneighbors(lastcenter, return_distance=False)\n    start = cities.index[(cities.mclust == m) & (cities.clustorder == closestart.item())].values[0]\n    startlist.append(start)\nopoints['startpt'] = startlist    \n```\n\n\n```python\nstoplist = []\nfor i,m in enumerate(opoints.mclust, 1):\n    neigh.fit(cities.loc[cities.mclust == m, ['X', 'Y']].values)\n    if m != opoints.mclust.values[-1]:\n        nextstartnode = opoints.loc[i, 'startpt']\n    else: \n        nextstartnode = 0\n    nextstart = cities.loc[nextstartnode, ['X', 'Y']].values.reshape(1, -1)\n    closestop = neigh.kneighbors(nextstart, return_distance=False)\n    stop = cities.index[(cities.mclust == m) & (cities.clustorder == closestop.item())].values[0]\n    stoplist.append(stop)\nopoints['stoppt'] = stoplist \n\ndisplay(cities.head(), opoints.head())\n```\n\n Here's what  the new path looks like. The points are all on cluster borders which makes sense.\n\n\n```python\ncoords = cities.loc[opoints.stoppt, ['X', 'Y', 'mclust']]\nstops = plot_it(coords, 30, 'darkblue', 0.5)\nstopsline = coords.hvplot.line('X', 'Y', xlim=(0,5100), ylim=(0,3400), color='green', width=500, \n                            height=450, hover=False) \nstopsline*npole*gausses*stops\n```\n\n## Optimal Segments for each Cluster\nThe next step is to iterate through clusters with the solver. The closed form of the solver with start and stop points is being difficult. For now I'll use start points only and take the hit of doubling back to the next cluster.\n\n\n\n```python\n%%time \nnum_iters = 100\nseglist = []\ntotal_clusts = cities.shape[0]\nfor i,m in enumerate(opoints.mclust):\n    district = cities[cities.mclust == m]\n    print(\"begin cluster {}, {} of {}\".format(m, i, opoints.shape[0]-1))\n\n    clstart = opoints.loc[i, 'startpt']\n    nnode = district.loc[clstart, 'clustorder']\n    clstop = opoints.loc[i, 'stoppt']\n    pnode = district.loc[clstop, 'clustorder']\n    locations = district[['X', 'Y']].values\n    \n    segnodes = get_route(locations, nnode, pnode, fixed=False) #output is type list\n    ord_district =  district.iloc[segnodes]\n    segment = ord_district.index.tolist()\n    seglist.append(segment)\n\nseglist.append([0])\npath = np.concatenate(seglist)\n```\n\n\n```python\nbestpath = cities.loc[path, ['X', 'Y']]\nclustline = bestpath.hvplot.line('X', 'Y', xlim=(0,5100), ylim=(0,3400), width=500, \n                            height=450, datashade=True, dynspread=True) \nclustline*npole\n```\n\n\n```python\ndef score_it(path):\n    path_df = cities.reindex(path).reset_index()\n    path_df['step'] = np.sqrt((path_df.X - path_df.X.shift())**2 + (path_df.Y - path_df.Y.shift())**2)\n    path_df['step_adj'] = np.where((path_df.index) % 10 != 0, path_df.step, path_df.step + \n                            path_df.step*0.1*(~path_df.CityId.shift().isin(pnums)))\n    return path_df.step_adj.sum()\n\ndisplay(score_it(path))\n\nsub = pd.read_csv('../input/sample_submission.csv')\nsub['Path'] = path\nsub.to_csv('submission.csv', index=False)\nsub.head()\n```\n\nNot bad, even with the wasted moves although it does take a while to run. It would be interesting to see what improvements come with a fixed-route model, fewer clusters and/or longer run times. All for now!\n", "meta": {"hexsha": "e9b66b90736ef80e6595adfca82c13b1b40d24b5", "size": 50696, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/google-or-tools-w-clusters.ipynb", "max_stars_repo_name": "alexandrnikitin/kaggle-traveling-santa-2018-prime-paths", "max_stars_repo_head_hexsha": "44a537ee3388d52dba5abffedd8f014820c8fd40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/google-or-tools-w-clusters.ipynb", "max_issues_repo_name": "alexandrnikitin/kaggle-traveling-santa-2018-prime-paths", "max_issues_repo_head_hexsha": "44a537ee3388d52dba5abffedd8f014820c8fd40", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/google-or-tools-w-clusters.ipynb", "max_forks_repo_name": "alexandrnikitin/kaggle-traveling-santa-2018-prime-paths", "max_forks_repo_head_hexsha": "44a537ee3388d52dba5abffedd8f014820c8fd40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.7458492976, "max_line_length": 1534, "alphanum_fraction": 0.6458694966, "converted": true, "num_tokens": 5895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12252320610998799, "lm_q2_score": 0.044680867728456405, "lm_q1q2_score": 0.005474443165866775}}
{"text": "# Controllers  \n\nControllers are used to determine the type of high-level control over a given robot arm. While all arms are directly controlled via their joint torques, the inputted action space for a given environment can vary depending on the type of desired control. Our controller options include `OSC_POSE`, `OSC_POSITION`, `JOINT_POSITION`, `JOINT_VELOCITY`, and `JOINT_TORQUE`.\n\n<!-- | Controller Name<br />and Options |   Controller Type\t\t | \t  Action Dimension<br>(Gripper Not Included)    |  Format |\n| :-------------: | :-------------------: | :-------------------------------------------------: | :-----: |\n| OSC_POSE<br />impedance_mode = fixed |   Operational Space Control (Position + Orientation)   | 6 | (x, y, z, ax, ay, az)    |\n| OSC_POSE<br />impedance_mode = variable_kp | Operational Space Control (Position + Orientation)<br />with variable stiffness (critically damped) | 12 | (x, y, z, ax, ay, az)<br />(kpx,kpy,kpz,kpax,kpay,kpaz) |\n| OSC_POSE<br />impedance_mode = variable | Operational Space Control (Position + Orientation)<br />with variable impedance | 18 | (x, y, z, ax, ay, az)<br />(kpx,kpy,kpz,kpax,kpay,kpaz)<br />(kdx,kdy,kdz,kdax,kday,kdaz) |\n| OSC_POSITION<br />impedance_mode = fixed |   Operational Space Control (Position Only)      | 3 | (x, y, z)                |\n| OSC_POSITION<br />impedance_mode = variable_kp | Operational Space Control (Position Only)<br />with variable stiffness (critically damped) | 6 | (x, y, z)<br />(kpx,kpy,kpz) |\n| OSC_POSITION<br />impedance_mode = variable | Operational Space Control (Position Only)<br />with variable impedance | 9 | (x, y, z)<br />(kpx,kpy,kpz)<br />(kdx,kdy,kdz) |\n| IK_POSE         | Inverse Kinematics Control (Position + Orientation)  | 7 | (x, y, z, ax, ay, az)    |\n| JOINT_POSITION<br />impedance_mode = fixed |   Joint Position                                       | n | n robot joints           |\n| JOINT_POSITION<br />impedance_mode = variable_kp | Joint Position<br />with variable stiffness (critically damped) | 2n | n robot joints and kp for each |\n| JOINT_POSITION<br />impedance_mode = variable | Joint Position<br />with variable impedance | 3n | n robot joints and kp, kv for each |\n| JOINT_VELOCITY  |   Joint Velocity                                       | n | n robot joints           |\n| JOINT_TORQUE    |   Joint Torque                                         | n | n robot joints           | -->\n\nFor `OSC_POSE`, `OSC_POSITION`, and `JOINT_POSITION`, we include three variants that determine the action space. The most common variant is to use a predefined and constant set of impedance parameters; in that case, the action space only includes the desired pose, position, or joint configuration. We also include the option to specify either the stiffness values (and the damping will be automatically set to values that lead to a critically damped system), or all impedance parameters, both stiffness and damping, as part of the action at each step. These two variants lead to extended action spaces that can control the stiffness and damping behavior of the controller in a variable manner, providing full control to the policy/solution over the contact and dynamic behavior of the robot.\n\nWhen using any position-based control (`OSC`, `IK`, or `JOINT_POSITION` controllers), input actions are, by default,\ninterpreted as delta values from the current state.\n\nWhen using any end-effector pose controller (`IK`, `OSC_POSE`), delta rotations from the current end-effector orientation\nin the form of axis-angle coordinates `(ax, ay, az)`, where the direction represents the axis and the magnitude\nrepresents the angle (in radians). Note that for `OSC`, the rotation axes are taken relative to the global world\ncoordinate frame, whereas for `IK`, the rotation axes are taken relative to the end-effector origin, NOT the global world coordinate frame!\n\n## Controllers\n\nDuring runtime, the execution of the controllers is as follows. Controllers receive a desired configuration (reference value) and output joint torques that try to minimize the error between the current configuration and the desired one. Policies and solutions provide these desired configurations, elements of some action space, at what we call simulated policy frequency ($f_{p}$), e.g., 20Hz or 30Hz. **robosuite** will execute several iterations composed of a controller execution and a simulation step at simulation frequency, $f_s$ ($f_s = N\\cdot f_p$), using the same reference signal until a new action is provided by the policy/solution. In these iterations, while the desired configuration is kept constant, the current state of the robot is changing, and thus, the error.\n\nIn the following we summarize the options, variables, and the control laws (equations) that convert desired values from the policy/solution and current robot states into executable joint torques to minimize the difference.\n\n### Joint Space Control - Torque\n\nController Type: `JOINT_TORQUE`\n\nAction Dimensions (not including gripper): `n` (number of joints)\n\nSince our controllers transform the desired values from the policies/solutions into joint torques, if these values are already joint torques, there is a one-to-one mapping between the reference value from the policy/solution and the output value from the joint torque controller at each step: $\\tau = \\tau_d$\n\\begin{equation}\n\\tau = \\tau_d\n\\end{equation}\n\n### Joint Space Control - Velocity\n \nController Type: `JOINT_VELOCITY`\n\nAction Dimensions (not including gripper): `n` (number of joints)\n\nTo control joint velocities, we create a proportional (P) control law between the desired value provided by the policy/solution (interpreted as desired velocity of each joint) and the current joint velocity of the robot. This control law, parameterized by a proportional constant, $k_p$, generates joint torques to execute at each simulation step:\n\n\\begin{equation}\n\\tau = k_p (\\dot{q}_d - \\dot{q})\n\\end{equation}\n\n### Joint Space Control - Position with Fixed Impedance\n\nController Type: `JOINT_POSITION`\n\nImpedance: fixed\n\nAction Dimensions (not including gripper): `n` (number of joints)\n\nIn joint position control, we create a proportional-derivative (PD) control law between the desired value provided by the policy/solution (interpreted as desired configuration for each joint) and the current joint positions of the robot. The control law that generates the joint torques to execute is parameterized by proportional and derivative gains, $k_p$ and $k_v$, and defined as\n\n\\begin{equation}\n\\tau = \\Lambda \\left[k_p \\Delta_q - k_d\\dot{q}\\right]\n\\end{equation} \n\nwhere $\\Delta_q  = q_d - q$ is the difference between current and desired joint configurations, and $\\Lambda$ is the inertia matrix, that we use to scale the error to remove the dynamic effects of the mechanism. The stiffness and damping parameters, $k_p$ and $k_d$, are determined in construction and kept fixed.\n\n### Joint Space Control - Position with Variable Stiffness\n\nController Type: `JOINT_POSITION`\n\nImpedance: variable_kp\n\nAction Dimensions (not including gripper): `2n` (number of joints)\n\nThe control law is the same as for fixed impedance but, in this controller, $k_p$ can be determined by the policy/solution at each policy step.\n\n### Joint Space Control - Position with Variable Impedance\n\nController Type: `JOINT_POSITION`\n\nImpedance: variable\n\nAction Dimensions (not including gripper): `3n` (number of joints)\n\nAgain, the control law is the same in the two previous control types, but now both the stiffness and damping parameters, $k_p$ and $k_d$, are controllable by the policy/solution and can be changed at each step.\n\n### Operational Space Control - Pose with Fixed Impedance\n\nController Type: `OSC_POSE`\n\nImpedance: fixed\n\nAction Dimensions (not including gripper): `6`\n\nIn the `OSC_POSE` controller, the desired value is the 6D pose (position and orientation) of a controlled frame. We follow the formalism from [\\[Khatib87\\]](https://ieeexplore.ieee.org/document/1087068). Our control frame is always the `eef_site` defined in the [Gripper Model](../modeling/gripper_model.html), placed at the end of the last link for robots without gripper or between the fingers for robots with gripper. The operational space control framework (OSC) computes the necessary joint torques to minimize the error between the desired and the current pose of the `eef_site` with the minimal kinematic energy. \n\nGiven a desired pose $\\mathbf{x}_{\\mathit{des}}$ and the current end-effector pose, , we first compute the end-effector acceleration that would help minimize the error between both, assumed. PD (proportional-derivative) control schema to improve convergence and stability. For that, we first decompose into a desired position, $p_d \\in \\mathbb{R}^3$, and a desired orientation, $R_d \\in \\mathbb{SO}(3)$. The end-effector acceleration to minimize the error should increase with the difference between desired end-effector pose and current pose, $p$ and $R$ (proportional term), and decrease with the current end-effector velocity, $v$ and $\\omega$ (derivative term).\n\nWe then compute the robot actuation (joint torques) to achieve the desired end-effector space accelerations leveraging the kinematic and dynamic models of the robot with the dynamically-consistent operational space formulation in [\\[Khatib1995a\\]](https://journals.sagepub.com/doi/10.1177/027836499501400103). First, we compute the wrenches at the end-effector that corresponds to the desired accelerations, ${f}\\in\\mathbb{R}^{6}$.\nThen, we map the wrenches in end-effector space ${f}$ to joint torque commands with the end-effector Jacobian at the current joint configuration $J=J(q)$: $\\tau = J^T{f}$. \n\nThus, the function that maps end-effector space position and orientation to low-level robot commands is ($\\textrm{ee} = \\textrm{\\it end-effector space}$):\n\\begin{equation}\n\\begin{aligned}\n\\tau &= J_p[\\Lambda_p[k_p^p (p_d - p) - k_v^p v]] + J_R[\\Lambda_R\\left[k_p^R(R_d \\ominus R) - k_d^R \\omega \\right]]\n\\end{aligned}\n\\end{equation}\nwhere $\\Lambda_p$ and $\\Lambda_R$ are the parts corresponding to position and orientation in $\\Lambda \\in \\mathbb{R}^{6\\times6}$, the inertial matrix in the end-effector frame that decouples the end-effector motions, $J_p$ and $J_R$ are the position and orientation parts of the end-effector Jacobian, and $\\ominus$ corresponds to the subtraction in $\\mathbb{SO}(3)$. The difference between current and desired position ($\\Delta_p= p_d - p$) and between current and desired orientation ($\\Delta_R = R_d \\ominus R$) can be used as alternative policy action space, $\\mathcal{A}$. $k_p^p$, $k_p^d$, $k_p^R$, and $k_d^R$ are vectors of proportional and derivative gains for position and orientation (parameters $\\kappa$), respectively, set once at initialization and kept fixed.\n\n### Operational Space Control - Pose with Variable Stiffness\n\nController Type: `OSC_POSE`\n\nImpedance: variable_kp\n\nAction Dimensions (not including gripper): `12`\n\nThe control law is the same as `OSC_POSE` but, in this case, the stiffness of the controller, $k_p$, is part of the action space and can be controlled and changed at each time step by the policy/solution. The damping parameters, $k_d$, are set to maintain the critically damped behavior of the controller.\n\n### Operational Space Control - Pose with Variable Impedance\n\nController Type: `OSC_POSE`\n\nImpedance: variable\n\nAction Dimensions (not including gripper): `18`\n\nThe control law is the same as in the to previous controllers, but now both the stiffness and the damping, $k_p$ and $k_d$, are part of the action space and can be controlled and changed at each time step by the policy/solution. \n\n\n## Configurations\nThe config directory (found within the [Controllers](../source/robosuite.controllers) module) provides a set of default configuration files that hold default examples of parameters relevant to individual controllers. Note that when creating your controller config templates of a certain type of controller, the listed parameters in the default example are required and should be specified accordingly.\n\nNote: Each robot has its own default controller configuration which is called by default unless a different controller config is called.\n\nBelow, a brief overview and description of each subset of controller parameters are shown:\n\n#### Controller Settings  \n* `type`: Type of controller to control. Can be `OSC_POSE`, `OSC_POSITION`, `IK_POSE`, `JOINT_POSITION`, `JOINT_VELOCITY`, or `JOINT_TORQUE`\n* `interpolation`: If not `null`, specified type of interpolation to use between desired actions. Currently only `linear` is supported.\n* `ramp_ratio`: If using `linear` interpolation, specifies the proportion of allotted timesteps (value from [0, 1]) over which to execute the interpolated commands.\n* `{...}_limits`: Limits for that specific controller. E.g.: for a `JOINT_POSITION`, the relevant limits are its joint positions, `qpos_limits` . Can be either a 2-element list (same min/max limits across entire relevant space), or a list of lists (specific limits for each component)\n* `ik_{pos, ori}_limit`: Only applicable for IK controller. Limits the magnitude of the desired relative change in position / orientation.\n* `{input,output}_{min,max}`: Scaling ranges for mapping action space inputs into controller inputs. Settings these limits will automatically clip the action space input to be within the `input_{min,max}` before mapping the requested value into the specified `output_{min,max}` range. Can be either a scalar (same limits across entire action space), or a list (specific limits for each action component)\n* `kp`: Where relevant, specifies the proportional gain for the controller. Can be either be a scalar (same value for all controller dimensions), or a list (specific values for each dimension)\n* `damping_ratio`: Where relevant, specifies the damping ratio constant for the controller.\n* `impedance_mode`: For impedance-based controllers (`OSC_*`, `JOINT_POSITION`), determines the impedance mode for the controller, i.e. the nature of the impedance parameters. It can be `fixed`, `variable`, or `variable_kp` (kd is adjusted to provide critically damped behavior).\n* `kp_limits, damping_ratio_limits`: Only relevant if `impedance_mode` is set to `variable` or `variable_kp`. Sets the limits for the resulting action space for variable impedance gains.\n* `control_delta`: Only relevant for `OSC_POSE` or `OSC_POSITION` controllers. `true` interprets input actions as delta values from the current robot end-effector position. Otherwise, assumed to be absolute (global) values\n* `uncouple_pos_ori`: Only relevant for `OSC_POSE`. `true` decouples the desired position and orientation torques when executing the controller\n\n## Loading a Controller\nBy default, if no controller configuration is specified during environment creation, then `JOINT_VELOCITY` controllers with robot-specific configurations will be used. \n\n#### Using a Default Controller Configuration\nAny controller can be used with its default configuration, and can be easily loaded into a given environment by calling its name as shown below (where `controller_name` is one of acceptable controller `type` strings):\n\n```python\nimport robosuite as suite\nfrom robosuite import load_controller_config\n\n# Load the desired controller's default config as a dict\nconfig = load_controller_config(default_controller=controller_name)\n\n# Create environment\nenv = suite.make(\"Lift\", robots=\"Panda\", controller_configs=config, ... )\n```\n\n#### Using a Custom Controller Configuration\nA custom controller configuration can also be used by simply creating a new config (`.json`) file with the relevant parameters as specified above. All robosuite environments have an optional `controller_configs` argument that can be used to pass in specific controller settings. Note that this is expected to be a `dict`, so the new configuration must be read in and parsed as a `dict` before passing it during the environment `robosuite.make(...)` call. A brief example script showing how to import a custom controller configuration is shown below.\n\n```python\nimport robosuite as suite\nfrom robosuite import load_controller_config\n\n# Path to config file\ncontroller_fpath = \"/your/custom/config/filepath/here/filename.json\"\n\n# Import the file as a dict\nconfig = load_controller_config(custom_fpath=controller_fpath)\n\n# Create environment\nenv = suite.make(\"Lift\", robots=\"Panda\", controller_configs=config, ... )\n```\n", "meta": {"hexsha": "8c029b6880f48a1e0c175bda17f3d0192a8638a5", "size": 18771, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/modules/controllers.ipynb", "max_stars_repo_name": "kyungjaelee/robosuite", "max_stars_repo_head_hexsha": "0d73fcca9ed8e638632f4bd7b0f1b8ebf4640fb1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-07-15T22:36:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-06T17:04:50.000Z", "max_issues_repo_path": "docs/modules/controllers.ipynb", "max_issues_repo_name": "kyungjaelee/robosuite", "max_issues_repo_head_hexsha": "0d73fcca9ed8e638632f4bd7b0f1b8ebf4640fb1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/modules/controllers.ipynb", "max_forks_repo_name": "kyungjaelee/robosuite", "max_forks_repo_head_hexsha": "0d73fcca9ed8e638632f4bd7b0f1b8ebf4640fb1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 83.7991071429, "max_line_length": 801, "alphanum_fraction": 0.6907996377, "converted": true, "num_tokens": 3807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23091976292927183, "lm_q2_score": 0.022629202257639994, "lm_q1q2_score": 0.00522553002061277}}
{"text": "# Introduction and Background\n\nBy definition, a **decorator** is a function that takes another function and extends the behavior of the latter function without explicitly modifying it. Decorators provide a simple syntax for calling [higher-order functions](https://en.wikipedia.org/wiki/Higher-order_function).\n\n## Functions\n\nThere are two kinds of functions:\n1. **First-order function**:\n     - Takes one or more non-function objects, like string, int, float, list, and so on, as arguments and return non-function objects\n\n2. **Higher-order function**: \n    - takes one or more functions as arguments (i.e. a procedural parameter, which is a parameter of a procedure that is itself a procedure); \n    - returns a function as its result.\n    - In mathematics higher-order functions are also termed operators or functionals\n    \n3. **Inner Functions**:\n    - Defined inside other functions\n    - they are locally scoped to their parents, and only exist inside the parent() function as local variables\n    - the inner functions are not defined until the parent function is called\n\n\n**First-Class Objects**:\nIn Python, functions are first-class objects. This means that functions can be passed around and used as arguments, just like any other object (string, int, float, list, and so on). Consider the following three functions:\n\n\n```python\n## first and higher function Examples###\n\n# first-order function\ndef say_hello(name):\n    return f\"Hello {name}\"\n\n# first-order function\ndef be_awesome(name):\n    return f\"Yo {name}, together we are the awesomest!\"\n\n# higher-order function taking a function as parameter\ndef greet_bob(greeter_func):\n    return greeter_func(\"Bob\")\n```\n\n\n```python\n# Note that greet_bob(say_hello) refers to two functions, but in different ways: greet_bob() and say_hello. \n# The say_hello function is named without parentheses. This means that only a reference to the function is passed. \n# The function is not executed. The greet_bob() function, on the other hand, is written with parentheses, \n# so it will be called as usual.\ngreet_bob(say_hello)\n```\n\n\n\n\n    'Hello Bob'\n\n\n\n\n```python\ngreet_bob(be_awesome)\n```\n\n\n\n\n    'Yo Bob, together we are the awesomest!'\n\n\n\n\n```python\n## inner function Examples###\n\ndef parent():\n    print(\"Printing from the parent() function\")\n    \n    # inner function\n    def first_child():\n        print(\"Printing from the first_child() function\")\n    \n    # inner function\n    def second_child():\n        print(\"Printing from the second_child() function\")\n\n    second_child()\n    first_child()\n```\n\n\n```python\n# Note that the order in which the inner functions are defined does not matter. \n# Like with any other functions, the printing only happens when the inner functions are executed.\nparent()\n```\n\n    Printing from the parent() function\n    Printing from the second_child() function\n    Printing from the first_child() function\n\n\n\n```python\n## Returning Functions From Functions\n\ndef parent(num):\n    def first_child():\n        return \"Hi, I am Emma\"\n\n    def second_child():\n        return \"Call me Liam\"\n\n    if num == 1:\n        return first_child\n    else:\n        return second_child\n```\n\nNote that you are returning first_child without the parentheses. Recall that this means that you are **returning a reference to the function** first_child. In contrast first_child() with parentheses refers to the result of evaluating the function. This can be seen in the following example\n\n\n```python\nfirst = parent(1)\nsecond = parent(2)\nprint(f\"first: {first}\")\nprint(f\"second: {second}\")\nprint(first())\nprint(second())\n```\n\n    first: <function parent.<locals>.first_child at 0x7fb9a8b5d320>\n    second: <function parent.<locals>.second_child at 0x7fb9a8b5d170>\n    Hi, I am Emma\n    Call me Liam\n\n\n## My First Decorators\n\nNow that you\u2019ve seen that functions are just like any other object in Python, you\u2019re ready to move on and see the magical beast that is the Python decorator. Let\u2019s start with an example:\n\n\n```python\ndef my_first_decorator(func):\n    def wrapper():\n        \"\"\"\n        Define a inner wrapper function wraping an argument functor \n        with pre-defined behaviors. In this example, we use two print statement \n        to wrap \"func()\"\n        \"\"\"\n        print(\"Something is happening before the function is called.\")\n        func()\n        print(\"Something is happening after the function is called.\")\n    return wrapper\n\ndef say_whee():\n    print(\"Whee!\")\n# Call [my_first_decorator] function taking [say_whee] as a argument.\nsay_whee = my_first_decorator(say_whee)\n\n# In effect, the name say_whee now points to the wrapper() inner function. \n# Remember that you return wrapper as a function when you call my_decorator(say_whee)\nsay_whee\n```\n\n\n\n\n    <function __main__.my_first_decorator.<locals>.wrapper()>\n\n\n\n\n```python\nsay_whee()\n```\n\n    Something is happening before the function is called.\n    Whee!\n    Something is happening after the function is called.\n\n\nPut simply: **decorators wrap a function, modifying its behavior.**\n\nBecause wrapper() is a regular Python function, **the way a decorator modifies a function can change dynamically.** So as not to disturb your neighbors, the following example will only run the decorated code during the day:\n\n\n```python\nfrom datetime import datetime\n\ndef not_during_the_night(func):\n    def wrapper():\n        if 7 <= datetime.now().hour < 22:\n            func()\n        else:\n            pass  # Hush, the neighbors are asleep\n    return wrapper\n\ndef say_whee():\n    print(\"Whee!\")\n\nsay_whee = not_during_the_night(say_whee)\nprint(say_whee)\n```\n\n    <function not_during_the_night.<locals>.wrapper at 0x7fb9a8b5d7a0>\n\n\n\n```python\nsay_whee()\n```\n\n    Whee!\n\n\n## Revisting code using decorator syntactic sugar\n\n\n```python\ndef my_first_decorator(func):\n    def wrapper():\n        \"\"\"\n        Define a inner wrapper function wraping an argument functor \n        with pre-defined behaviors. In this example, we use two print statement \n        to wrap \"func()\"\n        \"\"\"\n        print(\"Something is happening before the function is called.\")\n        func()\n        print(\"Something is happening after the function is called.\")\n    return wrapper\n\n\"\"\"\nSo, @my_first_decorator is just an easier way of saying: \n  say_whee_decor = my_first_decorator(say_whee_decor)\n\nIt\u2019s how you apply a decorator to a function.\n\"\"\"\n@my_first_decorator\ndef say_whee_decor():\n    print(\"Whee!\")\n\ndef say_whee():\n    print(\"Whee!\")\n    \nprint(say_whee_decor)\nprint(say_whee)\n```\n\n    <function my_first_decorator.<locals>.wrapper at 0x7fb9a8b69830>\n    <function say_whee at 0x7fb9a8b69290>\n\n\n# Decorator Syntax Alternatives\n\n## Reusing Decorators defined in an own module\nDefining decorators in a module file and import them for easy reusability are available.\n\nLet\u2019s move the decorator to its own module that can be used in many other functions.\n\nCreate a file called decorators.py with the following content:\n\n\n```python\ndef do_twice(func):\n    \"\"\"\n    You can name your inner function whatever you want, and a generic name like wrapper() \n    is usually okay.\n    \"\"\"\n    def wrapper_do_twice():\n        func()\n        func()\n    return wrapper_do_twice\n```\n\n\n```python\nfrom decorators import do_twice\n\n@do_twice\ndef say_whee():\n    print(\"Whee!\")\n```\n\n## Decorating Functions With Arguments\n\nSay that you have a function that accepts some arguments. Can you still decorate it?\n\n\n```python\ndef do_twice(func):\n    \"\"\"\n    Taking [func] without any arguments\n    \"\"\"\n    def wrapper():\n        func()\n        func()\n    return wrapper\n\n@do_twice\ndef greet(name):\n    \"\"\"\n    Define a function decorated by [do_twice]\n    \"\"\"\n    print(f\"Hello {name}\")\n```\n\n\n```python\n\"\"\"\nThe problem is that the inner function wrapper() does not take any arguments, \nbut name=\"World\" was passed to it. You could fix this by letting wrapper_do_twice() \naccept one argument, but then it would not work for the say_whee() function you \ncreated earlier.\n\"\"\"\ngreet(\"World\")\n```\n\nThe solution is to use **\\*args** and **\\*\\*kwargs** in the inner wrapper function. Then it will accept an arbitrary number of positional and keyword arguments. \n- **\\*args**: \n- **\\*\\*kwargs**: \n\n\n```python\ndef do_twice(func):\n    def wrapper(*args, **kwargs):\n        func(*args, **kwargs)\n        func(*args, **kwargs)\n    return wrapper\n\n@do_twice\ndef greet(name):\n    print(f\"Hello {name}\")\n```\n\n\n```python\nprint(greet())\nprint(greet(\"Bing\"))\n```\n\n## Returning Values From Decorated Functions\nWhat happens to the return value of decorated functions? Well, that\u2019s up to the decorator to decide.\n\n\n```python\ndef do_twice(func):\n    def wrapper(*args, **kwargs):\n        \"\"\"\n        Using a return statement to return an object from the calling of \"func\"\n        We need to make sure the wrapper function returns the return value of \n        the decorated function. \n        \"\"\"\n        func(*args, **kwargs)\n        return func(*args, **kwargs)\n    return wrapper\n\n@do_twice\ndef return_greeting(name):\n    print(\"Creating greeting\")\n    return f\"Hi {name}\"\n\nhi_adam = return_greeting(\"Adam\")\nprint(hi_adam)\n```\n\n    Creating greeting\n    Creating greeting\n    Hi Adam\n\n\n## Multiple decorators\n\n```\n@dec2\n@dec1\ndef func(arg1, arg2, ...):\n    pass\n```\nThis is equivalent to:\n```\ndef func(arg1, arg2, ...):\n    pass\nfunc = dec2(dec1(func))\n```\n\n\n# A Few Real World Examples\n\nLet\u2019s look at a few more useful examples of decorators. You\u2019ll notice that they\u2019ll mainly follow the same pattern that you\u2019ve learned so far.\n\n\n```python\n# This formula is a good boilerplate template for building more complex decorators.\nimport functools\n\ndef decorator(func):\n    @functools.wraps(func)\n    def wrapper_decorator(*args, **kwargs):\n        # Do something before\n        value = func(*args, **kwargs)\n        # Do something after\n        return value\n    return wrapper_decorator\n```\n\n## Define functions to be executed at entry or exist\n\n\n```python\ndef on_exit(f):\n    import atexit\n    atexit.register(f)\n    return f\n\n@on_exit\ndef func():\n    pass\n```\n\n## Timing Functions\n\nLet\u2019s start by creating a @timer decorator. It will [measure the time a function takes to execute](https://realpython.com/python-timer/) and print the duration to the console. Here\u2019s the code:\n\n\n```python\nimport functools\nimport time\n\ndef timer(func):\n    \"\"\"Print the runtime of the decorated function\"\"\"\n    @functools.wraps(func)\n    def wrapper_timer(*args, **kwargs):\n        start_time = time.perf_counter()    # 1\n        value = func(*args, **kwargs)\n        end_time = time.perf_counter()      # 2\n        run_time = end_time - start_time    # 3\n        print(f\"Finished {func.__name__!r} in {run_time:.4f} secs\")\n        return value\n    return wrapper_timer\n\n@timer\ndef waste_some_time(num_times):\n    for _ in range(num_times):\n        sum([i**2 for i in range(10000)])\n\nwaste_some_time(100)\n```\n\n    Finished 'waste_some_time' in 0.1792 secs\n\n\n**Note:** The @timer decorator is great if you just want to get an idea about the runtime of your functions. If you want to do more precise measurements of code, you should instead consider the [timeit module](https://docs.python.org/3/library/timeit.html) in the standard library. It temporarily disables garbage collection and runs multiple trials to strip out noise from quick function calls.\n\n## Debugging Code\nThe following @debug decorator will print the arguments a function is called with as well as its return value every time the function is called:\n\n\n```python\nimport functools\n\ndef debug(func):\n    \"\"\"Print the function signature and return value\"\"\"\n    @functools.wraps(func)\n    def wrapper_debug(*args, **kwargs):\n        args_repr = [repr(a) for a in args]                      # 1\n        kwargs_repr = [f\"{k}={v!r}\" for k, v in kwargs.items()]  # 2\n        signature = \", \".join(args_repr + kwargs_repr)           # 3\n        print(f\"Calling {func.__name__}({signature})\")\n        value = func(*args, **kwargs)\n        print(f\"{func.__name__!r} returned {value!r}\")           # 4\n        return value\n    return wrapper_debug\n```\n\nThe signature is created by joining the string representations of all the arguments. The numbers in the following list correspond to the numbered comments in the code:\n1. Create a list of the positional arguments. Use repr() to get a nice string representing each argument.\n2. Create a list of the keyword arguments. The f-string formats each argument as key=value where the !r specifier means that repr() is used to represent the value.\n3. The lists of positional and keyword arguments is joined together to one signature string with each argument separated by a comma.\n4. The return value is printed after the function is executed.\n\nLet\u2019s see how the decorator works in practice by applying it to a simple function with one position and one keyword argument:\n\n\n```python\n@debug\ndef make_greeting(name, age=None):\n    if age is None:\n        return f\"Howdy {name}!\"\n    else:\n        return f\"Whoa {name}! {age} already, you are growing up!\"\nmake_greeting(\"Benjamin\")\n```\n\n    Calling make_greeting('Benjamin')\n    'make_greeting' returned 'Howdy Benjamin!'\n\n\n\n\n\n    'Howdy Benjamin!'\n\n\n\n\n```python\nmake_greeting(\"Richard\", age=112)\n```\n\n    Calling make_greeting('Richard', age=112)\n    'make_greeting' returned 'Whoa Richard! 112 already, you are growing up!'\n\n\n\n\n\n    'Whoa Richard! 112 already, you are growing up!'\n\n\n\n\n```python\nmake_greeting(name=\"Dorrisile\", age=116)\n```\n\n    Calling make_greeting(name='Dorrisile', age=116)\n    'make_greeting' returned 'Whoa Dorrisile! 116 already, you are growing up!'\n\n\n\n\n\n    'Whoa Dorrisile! 116 already, you are growing up!'\n\n\n\nThis example also shows how you can apply a decorator to a function that has already been defined. The approximation of e is based on the following series expansion:\n\\begin{equation}\ne = \\sum_{n=0}^{}\\frac{1}{n!} = \\frac{1}{0!} + \\frac{1}{1!} + \\frac{1}{2!} + \\ldots\n\\end{equation}\n\n\n```python\nimport math\n# from decorators import debug\n\n# Apply a decorator to a standard library function\nmath.factorial = debug(math.factorial)\n\ndef approximate_e(terms=18):\n    return sum(1 / math.factorial(n) for n in range(terms))\n```\n\n\n```python\n# When calling the approximate_e() function, you can see the @debug decorator at work:\napproximate_e(5)\n```\n\n    Calling factorial(0)\n    Calling factorial(0)\n    Calling factorial(0)\n    'factorial' returned 1\n    'factorial' returned 1\n    'factorial' returned 1\n    Calling factorial(1)\n    Calling factorial(1)\n    Calling factorial(1)\n    'factorial' returned 1\n    'factorial' returned 1\n    'factorial' returned 1\n    Calling factorial(2)\n    Calling factorial(2)\n    Calling factorial(2)\n    'factorial' returned 2\n    'factorial' returned 2\n    'factorial' returned 2\n    Calling factorial(3)\n    Calling factorial(3)\n    Calling factorial(3)\n    'factorial' returned 6\n    'factorial' returned 6\n    'factorial' returned 6\n    Calling factorial(4)\n    Calling factorial(4)\n    Calling factorial(4)\n    'factorial' returned 24\n    'factorial' returned 24\n    'factorial' returned 24\n\n\n\n\n\n    2.708333333333333\n\n\n\n## Slowing Down Code\nThis next example might not seem very useful. Why would you want to slow down your Python code? Probably the most common use case is that you want to rate-limit a function that continuously checks whether a resource\u2014like a web page\u2014has changed. The @slow_down decorator will sleep one second before it calls the decorated function:\n\n\n```python\nimport functools\nimport time\n\ndef slow_down(func):\n    \"\"\"Sleep 1 second before calling the function\"\"\"\n    @functools.wraps(func)\n    def wrapper_slow_down(*args, **kwargs):\n        time.sleep(1)\n        return func(*args, **kwargs)\n    return wrapper_slow_down\n\n@slow_down\ndef countdown(from_number):\n    if from_number < 1:\n        print(\"Liftoff!\")\n    else:\n        print(from_number)\n        countdown(from_number - 1)\ncountdown(3)\n```\n\n    3\n    2\n    1\n    Liftoff!\n\n\n## Registering Plugins\nDecorators don\u2019t have to wrap the function they\u2019re decorating. They can also simply register that a function exists and return it unwrapped. This can be used, for instance, to create a light-weight plug-in architecture:\n\n\n```python\nimport random\nPLUGINS = dict()\n\ndef register(func):\n    \"\"\"Register a function as a plug-in\"\"\"\n    PLUGINS[func.__name__] = func\n    return func\n\n@register\ndef say_hello(name):\n    return f\"Hello {name}\"\n\n@register\ndef be_awesome(name):\n    return f\"Yo {name}, together we are the awesomest!\"\n\ndef randomly_greet(name):\n    greeter, greeter_func = random.choice(list(PLUGINS.items()))\n    print(f\"Using {greeter!r}\")\n    return greeter_func(name)\nPLUGINS\n```\n\n\n\n\n    {'say_hello': <function __main__.say_hello(name)>,\n     'be_awesome': <function __main__.be_awesome(name)>}\n\n\n\n\n```python\nrandomly_greet(\"Alice\")\n```\n\n    Using 'be_awesome'\n\n\n\n\n\n    'Yo Alice, together we are the awesomest!'\n\n\n\nUsing the @register decorator, you can create your own curated list of interesting variables, effectively hand-picking some functions from globals().\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n## Define a class with a singleton instance.\n\nNote that once the class disappears enterprising programmers would have to be more creative to create more instances.\n\n\n```python\ndef singleton(cls):\n    instances = {}\n    def getinstance():\n        if cls not in instances:\n            instances[cls] = cls()\n        return instances[cls]\n    return getinstance\n\n@singleton\nclass MyClass:\n    ...\n```\n\n## Add attributes to a function\n\n\n```python\ndef attrs(**kwds):\n    def decorate(f):\n        for k in kwds:\n            setattr(f, k, kwds[k])\n        return f\n    return decorate\n\n@attrs(versionadded=\"2.2\",\n       author=\"Guido van Rossum\")\ndef mymethod(f):\n    ...\n```\n\n## Enforce function argument and return types\n\n\n```python\ndef accepts(*types):\n    def check_accepts(f):\n        assert len(types) == f.func_code.co_argcount\n        def new_f(*args, **kwds):\n            for (a, t) in zip(args, types):\n                assert isinstance(a, t), \\\n                       \"arg %r does not match %s\" % (a,t)\n            return f(*args, **kwds)\n        new_f.func_name = f.func_name\n        return new_f\n    return check_accepts\n\ndef returns(rtype):\n    def check_returns(f):\n        def new_f(*args, **kwds):\n            result = f(*args, **kwds)\n            assert isinstance(result, rtype), \\\n                   \"return value %r does not match %s\" % (result,rtype)\n            return result\n        new_f.func_name = f.func_name\n        return new_f\n    return check_returns\n\n@accepts(int, (int,float))\n@returns((int,float))\ndef func(arg1, arg2):\n    return arg1 * arg2\n```\n\n## Declare that a class implements a particular (set of) interface(s). \n\n\n```python\ndef provides(*interfaces):\n     \"\"\"\n     An actual, working, implementation of provides for\n     the current implementation of PyProtocols.  Not\n     particularly important for the PEP text.\n     \"\"\"\n     def provides(typ):\n         declareImplementation(typ, instancesProvide=interfaces)\n         return typ\n     return provides\n\nclass IBar(Interface):\n     \"\"\"Declare something about IBar here\"\"\"\n\n@provides(IBar)\nclass Foo(object):\n        \"\"\"Implement something here...\"\"\"\n```\n\n# Fancy Decorators\n\nSo far, you\u2019ve seen how to create simple decorators. You already have a pretty good understanding of what decorators are and how they work. Feel free to take a break from this article to practice everything you\u2019ve learned.\n\n## Decorating Classes\n\nThere are two different ways you can use decorators on classes:\n1. decorate the methods of a class using [@classmethod, @staticmethod](https://realpython.com/instance-class-and-static-methods-demystified/) and [@property](https://docs.python.org/3/library/functions.html#property)\n2. decorate the whole class\n\n\n\n\n```python\n\n```\n\n## Nesting Decorators\nYou can apply several decorators to a function by stacking them on top of each other\n\n\n```python\nfrom decorators import debug, do_twice\n\n@debug\n@do_twice\ndef greet(name):\n    print(f\"Hello {name}\")\n```\n\nThink about this as the decorators being executed in the order they are listed. In other words, @debug calls @do_twice, which calls greet(), or debug(do_twice(greet())):\n\n## Decorators with arguments\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n## Decorators that can optionally take arguments\n\n\n```python\n\n```\n\n## Stateful decorators\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n## Classes as decorators\n\n\n```python\n\n```\n\n# Reference\n\n1. [Primer on Python Decorators](https://realpython.com/primer-on-python-decorators/)\n2. [PEP 318 \u2013 Decorators for Functions and Methods](https://peps.python.org/pep-0318/)\n3. [The Decorator Pattern in Depth](https://blogs.oracle.com/javamagazine/post/the-decorator-pattern-in-depth)\n4. [A Gentle Introduction to Decorators in Python](https://machinelearningmastery.com/a-gentle-introduction-to-decorators-in-python/)\n\n\n```python\n\n```\n", "meta": {"hexsha": "736604cc1b66dd84a7c27099840849f94894b690", "size": 48467, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Python/decorator.ipynb", "max_stars_repo_name": "bingrao/notebook", "max_stars_repo_head_hexsha": "4bd74a09ffe86164e4bd318b25480c9ca0c6a462", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python/decorator.ipynb", "max_issues_repo_name": "bingrao/notebook", "max_issues_repo_head_hexsha": "4bd74a09ffe86164e4bd318b25480c9ca0c6a462", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/decorator.ipynb", "max_forks_repo_name": "bingrao/notebook", "max_forks_repo_head_hexsha": "4bd74a09ffe86164e4bd318b25480c9ca0c6a462", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1037267081, "max_line_length": 1352, "alphanum_fraction": 0.5553469371, "converted": true, "num_tokens": 5037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1066905996264336, "lm_q2_score": 0.04885777429425425, "lm_q1q2_score": 0.00521266523586694}}
{"text": "Examen Primer parcial\n--\nAlejandro Rojas Barba\n\nRob\u00f3tica industrial\n\n25/02/2019\n\nEjercicio 1\n--\n\n\n```python\ndef quitar_espacios(entrada_funcion):\n    n=0\n    bandera=False\n    frase_aux=[]\n    \n    frase=list(entrada_funcion)\n    if frase[-1]!='$':\n        frase.append('$')  \n\n    for i in frase:\n        if i!=' ':\n            frase_aux.append(i)\n            bandera=True\n        else:\n            if bandera==True and frase[n+1]!='$' and frase[n+1]!=' ':\n                frase_aux.append(i)\n        n=n+1\n\n    bandera=False\n    \n    for i in frase_aux:\n        if bandera==False:\n            frase_output=i\n            bandera=True\n        else:\n            frase_output=frase_output+i\n            \n    return frase_output\n    \n```\n\n\n```python\ndef separar_signos(entrada_funcion2):\n    n=0\n    bandera=False\n    frase=list(entrada_funcion2)\n    \n    for i in frase:\n        if i=='+' or i=='-':\n            frase[n]=\" \"+i+\" \" \n        n=n+1    \n\n    for i in frase:\n        if bandera==False:\n            frase_output=i\n            bandera=True\n        else:\n            frase_output=frase_output+i\n            \n    return frase_output\n```\n\n\n```python\ndef separar_punto(entrada_funcion3):\n    Numeros=\"1234567890\"\n    n=0\n    bandera=False\n    bandera1=False\n    bandera2=False\n    frase=list(entrada_funcion3)\n    \n    for i in frase:\n        if i=='.':   \n            for j in Numeros:                \n                if j==frase[n-1]:\n                    bandera1=True\n                    \n                if j==frase[n+1]:\n                    bandera2=True\n                                   \n            if bandera1==True and bandera2==False:\n                frase[n]=frase[n]+\" \"\n            elif bandera1==False and bandera2==True:\n                frase[n]=\" \"+frase[n]\n            elif bandera1==False and bandera2==False:\n                frase[n]=\" \"+frase[n]+\" \"   \n            \n            bandera1=False\n            bandera2=False\n        n=n+1 \n        \n    for i in frase:\n        if bandera==False:\n            frase_output=i\n            bandera=True\n        else:\n            frase_output=frase_output+i\n            \n    return frase_output\n```\n\n\n```python\ndef separar_LetraNumero(entrada_funcion4):\n    Numeros=\"1234567890\"\n    Abecedario=\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    frase=list(entrada_funcion4)\n    n=0\n    bandera=False\n    \n    for i in frase:\n        for j in Numeros:\n            if j==i:\n                for k in Abecedario:\n                    if k==frase[n+1]:\n                        frase[n]=frase[n]+\" \"\n        n=n+1\n    \n    for i in frase:\n        if bandera==False:\n            frase_output=i\n            bandera=True\n        else:\n            frase_output=frase_output+i\n            \n    return frase_output\n```\n\n\n```python\ndef separar_CaracterDesconocido(entrada_funcion5):\n    Numeros=\"1234567890\"\n    Abecedario=\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    frase=list(entrada_funcion5)\n    n=0\n    bandera=False\n    bandera2=False\n    \n    for i in frase:\n        for j in Numeros:\n            if j==i:\n                bandera=True\n        for k in Abecedario:\n            if k==i:\n                bandera=True\n        if i==' ' or i=='+' or i=='-' or i=='.' or i=='$':\n            bandera=True\n        \n        if bandera==False:\n            frase[n]=' '+frase[n]+' '\n        \n        bandera=False\n        n=n+1\n    \n    for i in frase:\n        if bandera2==False:\n            frase_output=i\n            bandera2=True\n        else:\n            frase_output=frase_output+i\n            \n    return frase_output\n```\n\n\n```python\ndef construir_lista(entrada_funcion6):\n    frase=list(entrada_funcion6)\n    n=0\n    lista=[]\n    bandera=False\n    \n    for i in frase:\n        if i!=' ' and i!='$':\n            if bandera==False:\n                auxiliar=i\n                bandera=True\n            else:\n                auxiliar=auxiliar+i\n        else:\n            lista.append(auxiliar)\n            bandera=False\n    return lista\n```\n\n\n```python\ndef imprimir_salida(lista):\n    Abecedario=\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    Numeros=\"1234567890\"\n    indicador=[]\n    bandera=False\n    n=0\n    salida=[]\n    banderas=[False, False, False, False, False, False]\n\n    for i in lista:\n        for j in i:\n            for k in Abecedario:\n                if j==k:\n                    #Letra\n                    banderas[0]=True\n                    bandera=True\n            if bandera==False:\n                for k in Numeros:\n                    if j==k:\n                        #Numero\n                        banderas[1]=True\n                        bandera=True\n            if bandera==False:\n                if j=='.':\n                    #Punto\n                    banderas[2]=True\n                    if i[0]=='.' or i[len(i)-1]=='.':\n                        banderas[5]=True\n                elif j=='+' or j=='-':\n                    #Signo\n                    banderas[3]=True\n                else:\n                    #Otro s\u00edmbolo\n                    banderas[4]=True\n            bandera=False\n   \n        if banderas[0]==True and banderas[2]==False and banderas[3]==False and banderas[4]==False:\n            salida.append('Id')\n\n        elif banderas[0]==False and banderas[1]==True and banderas[2]==False and banderas[3]==False and banderas[4]==False:\n            salida.append('Entero')\n\n        elif banderas[0]==False and banderas[1]==True and banderas[2]==True and banderas[3]==False and banderas[4]==False:\n            if banderas[5]==True:\n                salida.append('Real inv\u00e1lido')\n                banderas[5]=False\n            else:\n                salida.append('Real')\n\n        elif banderas[3]==True:\n            salida.append('Op '+i)\n\n        else:\n            salida.append('Error')\n        \n        salida.append(i)\n        print(salida)    \n        \n        salida=[]\n        banderas=[False, False, False, False, False,False]\n    salida.append('Fin de archivo')\n    salida.append('$')\n    print(salida)\n```\n\n\n```python\nentrada=input(\"Escribe la frase: \")\n\nentrada=quitar_espacios(entrada)\nentrada=separar_signos(entrada)\nentrada=quitar_espacios(entrada)\nentrada=separar_punto(entrada)\nentrada=quitar_espacios(entrada)\nentrada=separar_LetraNumero(entrada)\nentrada=quitar_espacios(entrada)\nentrada=separar_CaracterDesconocido(entrada)\nentrada=quitar_espacios(entrada)\nentrada=construir_lista(entrada)\nimprimir_salida(entrada)\n```\n\n    Escribe la frase: HOLA12ADIOA\n    ['Id', 'HOLA12ADIOA']\n    ['Fin de archivo', '$']\n\n\nEjercicio 2\n--\n\n\n```python\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n\n```python\nx,y=var(\"x y\")\n```\n\n\n```python\nx=np.arange(-30,30,0.1)\nf=np.sin(np.exp(x))-np.cos(x)\nplt.plot(x,f)\n#print(t)\n#plt.plot(f)\n```\n\n\n```python\n%matplotlib notebook\nimport matplotlib.pyplot as plt\nfrom sympy import *\ninit_printing()\n```\n\n\n```python\nx,y=var(\"x y\")\nf=sin(exp(x))-cos(x)\nplot (f)\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n\n\n\n\n    <sympy.plotting.plot.Plot at 0x2211ceacda0>\n\n\n\nEjercicio 3\n--\n\n\n```python\n%matplotlib notebook\nimport matplotlib.pyplot as plt\nfrom sympy import *\ninit_printing()\n```\n\n\n```python\nEq_1=x+y-25\nEq_2=2*x-14\ny_=solve(Eq_2,x)\ny_\nNum1=solve(Eq_1.subs(x,y_[0]),y)\nNum2=solve(Eq_1.subs(y,Num1[0]),x)\nprint(\"Y:\",Num1)\nprint(\"X:\",Num2)\n```\n\n    Y: [18]\n    X: [7]\n\n\nEjercicio 4: Utilizando Numpy resuelve\n--\n\n\n```python\nimport numpy as np\n```\n\n\n```python\nA=np.array([ [3,0,0],\n             [1,8,0],\n             [0,4,-2] ])\n\nB=np.array([ [30],\n             [18],\n             [2] ])\n\nC=np.linalg.inv(A)@B\nprint(C)\n\nsolucion=C[0]+C[1]+3*C[2]\nprint(solucion)\n```\n\n    [[10.]\n     [ 1.]\n     [ 1.]]\n    [14.]\n\n\nEjercicio 5\n--\n\n\n```python\nAbecedario=\"abcdefghijklmnopqrstuvwxyz\"\nfrase=\"g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb\"\nn=0\nm=0\nfrase=list(frase)\n\nfor i in frase:\n    for j in Abecedario:\n        if j==i:\n            if j=='y':\n                frase[m]='a'\n            elif j=='z':\n                frase[m]='b'\n            else:\n                frase[m]=Abecedario[n+2]\n        n=n+1\n    m=m+1\n    n=0\n\nfor i in frase:    \n    print(i,end='')\n```\n\n    i hope you didnt translate it by hand. thats what computers are for. doing it in by hand is inefficient and that's why this text is so long. using string.maketrans() is recommended\n\nEjercicio 6\n--\n\n\n```python\n!pip install pulp\n```\n\n    Requirement already satisfied: pulp in c:\\users\\usuario\\anaconda3\\lib\\site-packages (1.6.9)\n    Requirement already satisfied: pyparsing>=2.0.1 in c:\\users\\usuario\\anaconda3\\lib\\site-packages (from pulp) (2.3.0)\n\n\n\n```python\nfrom pulp import *\n```\n\n\n```python\npulp.LpVariable?\n```\n\n\n```python\nmi_lp_problema=pulp.LpProblem(\"Mi LP Problema\", pulp.LpMinimize)\n\nx11 = pulp.LpVariable('x11', lowBound=0, cat='Continuous')\nx12 = pulp.LpVariable('x12', lowBound=0, cat='Continuous')\nx13 = pulp.LpVariable('x13', lowBound=0, cat='Continuous')\nx21 = pulp.LpVariable('x21', lowBound=0, cat='Continuous')\nx22 = pulp.LpVariable('x22', lowBound=0, cat='Continuous')\nx23 = pulp.LpVariable('x23', lowBound=0, cat='Continuous')\n\n\n#Objective function\nmi_lp_problema+=8*x11 +6*x12 +10*x13 +10*x21 +4*x22 +9*x23\n\n#Consraints\nmi_lp_problema += x11 + x12 + x13 ==2000\nmi_lp_problema += x21 + x22 + x23 ==2500\nmi_lp_problema += x11 + x21 ==1500\nmi_lp_problema += x12 + x22 ==2000\nmi_lp_problema += x13 + x23 ==1000\nmi_lp_problema += x11>=0\nmi_lp_problema += x12>=0\nmi_lp_problema += x13>=0\nmi_lp_problema += x21>=0\nmi_lp_problema += x22>=0\nmi_lp_problema += x23>=0\n\n```\n\n\n```python\nmi_lp_problema\n```\n\n\n\n\n    Mi LP Problema:\n    MINIMIZE\n    8*x11 + 6*x12 + 10*x13 + 10*x21 + 4*x22 + 9*x23 + 0\n    SUBJECT TO\n    _C1: x11 + x12 + x13 = 2000\n    \n    _C2: x21 + x22 + x23 = 2500\n    \n    _C3: x11 + x21 = 1500\n    \n    _C4: x12 + x22 = 2000\n    \n    _C5: x13 + x23 = 1000\n    \n    _C6: x11 >= 0\n    \n    _C7: x12 >= 0\n    \n    _C8: x13 >= 0\n    \n    _C9: x21 >= 0\n    \n    _C10: x22 >= 0\n    \n    _C11: x23 >= 0\n    \n    VARIABLES\n    x11 Continuous\n    x12 Continuous\n    x13 Continuous\n    x21 Continuous\n    x22 Continuous\n    x23 Continuous\n\n\n\n\n```python\nmi_lp_problema.solve()\npulp.LpStatus[mi_lp_problema.status]\n```\n\n\n\n\n    'Optimal'\n\n\n\n\n```python\nfor variable in mi_lp_problema.variables():\n    print (\"{}={}\".format(variable.name, variable.varValue))\n```\n\n    x11=1500.0\n    x12=0.0\n    x13=500.0\n    x21=0.0\n    x22=2000.0\n    x23=500.0\n\n\n\n```python\nx11=1500.0\nx12=0.0\nx13=500.0\nx21=0.0\nx22=2000.0\nx23=500.0\n\nsolucion=8*x11 +6*x12 +10*x13 +10*x21 +4*x22 +9*x23\nprint(solucion)\n```\n\n    29500.0\n\n", "meta": {"hexsha": "9424f4df5c9e264f5fd73049b09778fe6ce401b0", "size": 168165, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Examen primer parcial.ipynb", "max_stars_repo_name": "AlexRojas06/Examen-primer-parcial", "max_stars_repo_head_hexsha": "5888474882916001ebceccd102de339d76723e7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-05T04:32:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-05T04:32:49.000Z", "max_issues_repo_path": "Examen primer parcial.ipynb", "max_issues_repo_name": "AlexRojas06/Examen-primer-parcial", "max_issues_repo_head_hexsha": "5888474882916001ebceccd102de339d76723e7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examen primer parcial.ipynb", "max_forks_repo_name": "AlexRojas06/Examen-primer-parcial", "max_forks_repo_head_hexsha": "5888474882916001ebceccd102de339d76723e7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 106.2318382817, "max_line_length": 82599, "alphanum_fraction": 0.8036868552, "converted": true, "num_tokens": 3166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11757212426963223, "lm_q2_score": 0.044018645003263496, "lm_q1q2_score": 0.0051753656005045215}}
{"text": "```python\nimport astunparse\nimport ast\nimport ply.lex as lex\n```\n\n\n```python\ndef transform(string):\n    return string.replace('DCSP',' ').replace(' DCNL','\\n')\n```\n\n\n```python\n# for code-only-corpus\nbodies_dir = '/home/irteam/users/mjchoi/github/code-docstring-corpus/code-only-corpus/data_mono_ps.bodies'\ndecl_dir = '/home/irteam/users/mjchoi/github/code-docstring-corpus/code-only-corpus/data_mono_ps.declarations'\ndecl_body_dir = '/home/irteam/users/mjchoi/github/code-docstring-corpus/code-only-corpus/data_mono_ps.declbodies'\nmeta_dir = '/home/irteam/users/mjchoi/github/code-docstring-corpus/code-only-corpus/data_mono_ps.metadata'\n```\n\n\n```python\nwith open(bodies_dir) as f:\n    bodies = f.read().split('\\n')\nwith open(decl_dir) as f:\n    decl = f.read().split('\\n')\nwith open(decl_body_dir) as f:\n    decl_body = f.read().split('\\n')\nwith open(meta_dir) as f:\n    meta = f.read().split('\\n')\n```\n\n\n```python\nidx = 1000\nprint(\"Body:\")\nprint(bodies[idx].replace('DCSP','').replace(' DCNL ','\\n'))\nprint('=======================================================================')\nprint(\"Declaration:\\n\",decl[idx])\nprint('=======================================================================')\nprint(\"Declaration & body:\")\nprint(decl_body[idx].replace('DCSP','').replace(' DCNL ','\\n'))\nprint('=======================================================================')\nprint(\"Metadata:\\n\",meta[idx])\nprint('=======================================================================')\n\n```\n\n    Body:\n      with open(key_path, 'r') as f:\n       params = pem.parse_private_key(f.read())\n       privkey = rsakey.RSAKey(*params)\n     with open(cert_path, 'r') as f:\n       s = f.read()\n       bList = pem.dePemList(s, 'CERTIFICATE')\n     certificates = pb2.X509Certificates()\n     certificates.certificate.extend(map(str, bList))\n     pr.pki_type = 'x509+sha256'\n     pr.pki_data = certificates.SerializeToString()\n     msgBytes = bytearray(pr.SerializeToString())\n     hashBytes = bytearray(hashlib.sha256(msgBytes).digest())\n     sig = privkey.sign((x509.PREFIX_RSA_SHA256 + hashBytes))\n     pr.signature = bytes(sig)\n    =======================================================================\n    Declaration:\n     def sign_request_with_x509(pr, key_path, cert_path):\n    =======================================================================\n    Declaration & body:\n    def sign_request_with_x509(pr, key_path, cert_path):\n      with open(key_path, 'r') as f:\n       params = pem.parse_private_key(f.read())\n       privkey = rsakey.RSAKey(*params)\n     with open(cert_path, 'r') as f:\n       s = f.read()\n       bList = pem.dePemList(s, 'CERTIFICATE')\n     certificates = pb2.X509Certificates()\n     certificates.certificate.extend(map(str, bList))\n     pr.pki_type = 'x509+sha256'\n     pr.pki_data = certificates.SerializeToString()\n     msgBytes = bytearray(pr.SerializeToString())\n     hashBytes = bytearray(hashlib.sha256(msgBytes).digest())\n     sig = privkey.sign((x509.PREFIX_RSA_SHA256 + hashBytes))\n     pr.signature = bytes(sig)\n    =======================================================================\n    Metadata:\n     github/spesmilo/electrum/lib/paymentrequest.py 410\n    =======================================================================\n\n\n\n```python\nbodies_test_dir = '/home/irteam/users/mjchoi/github/code-docstring-corpus/parallel-corpus/data_ps.bodies.test'\ndecldesc_test_dir = '/home/irteam/users/mjchoi/github/code-docstring-corpus/parallel-corpus/data_ps.decldesc.test'\n```\n\n\n```python\nwith open(bodies_test_dir) as f:\n    bodies1 = f.read().split('\\n')\nwith open(decldesc_test_dir) as f:\n    bodies2 = f.read().split('\\n')\n```\n\n\n```python\nfor idx in range(100):\n    print('------------------------ body ----------------------------------')\n    print(transform(bodies1[idx]))\n    print('------------------------ declaration ----------------------------------')\n    print(transform(bodies2[idx]))\n    print('=========================================================================')\n```\n\n    ------------------------ body ----------------------------------\n       if cint(frappe.db.get_single_value(u'System   Settings', u'setup_complete')):\n          return\n       args = process_args(args)\n       try:\n          if (args.language and (args.language != u'english')):\n             set_default_language(get_language_code(args.lang))\n          frappe.clear_cache()\n          update_system_settings(args)\n          update_user_name(args)\n          for method in frappe.get_hooks(u'setup_wizard_complete'):\n             frappe.get_attr(method)(args)\n          disable_future_access()\n          frappe.db.commit()\n          frappe.clear_cache()\n       except:\n          frappe.db.rollback()\n          if args:\n             traceback = frappe.get_traceback()\n             for hook in frappe.get_hooks(u'setup_wizard_exception'):\n                frappe.get_attr(hook)(traceback, args)\n          raise\n       else:\n          for hook in frappe.get_hooks(u'setup_wizard_success'):\n             frappe.get_attr(hook)(args)\n    ------------------------ declaration ----------------------------------\n    @frappe.whitelist()\n     def setup_complete(args):\n     'Calls hooks for `setup_wizard_complete`, sets home page as `desktop`\n     and clears cache. If wizard breaks, calls `setup_wizard_exception` hook'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       module = AnsibleModule(argument_spec=ClcGroup._define_module_argument_spec(), supports_check_mode=True)\n       clc_group = ClcGroup(module)\n       clc_group.process_request()\n    ------------------------ declaration ----------------------------------\n    def main():\n     'The main function.  Instantiates the module and calls process_request.\n     :return: none'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       try:\n          fields = os.path.split(filename)\n          if fields:\n             if (fields[(-1)].startswith('dataset_') and fields[(-1)].endswith('.dat')):\n                return Dataset.get(int(fields[(-1)][len('dataset_'):(- len('.dat'))]))\n       except:\n          pass\n       return None\n    ------------------------ declaration ----------------------------------\n    def __guess_dataset_by_filename(filename):\n     'Return a guessed dataset by filename'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       result = []\n       for node in maybe_xrefs:\n          if isinstance(node, addnodes.pending_xref):\n             result.extend(resolve_pending_xref(app, fromdocname, node.deepcopy()))\n          else:\n             result.append(node)\n       return result\n    ------------------------ declaration ----------------------------------\n    def resolve_possible_pending_xrefs(app, fromdocname, maybe_xrefs):\n     'If any node is a pending_xref, attempt to resolve it. If it cannot be\n     resolved, replace it with its children.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       (is_travis, non_pr) = check_environment()\n       if (not is_travis):\n          return\n       if (not non_pr):\n          print('Running   in   Travis   during   non-merge   to   master,   doing   nothing.')\n          sys.exit(0)\n       decrypt_keyfile()\n    ------------------------ declaration ----------------------------------\n    def prepare_to_run():\n     'Prepare to run system tests.\n     If on Travis during a PR, exit the entire program; there is\n     no need to run the system tests.\n     If on Travis during a build for a non-PR merge to master,\n     decrypts stored keyfile.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       result = script.pip('download', expect_error=True)\n       assert ('You   must   give   at   least   one   requirement   to   download' in result.stderr)\n       assert (result.returncode == ERROR)\n    ------------------------ declaration ----------------------------------\n    def test_download_exit_status_code_when_no_requirements(script):\n     'Test download exit status code when no requirements specified'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       with open('../show_version.txt') as show_ver_file:\n          show_ver = show_ver_file.read()\n       print obtain_os_version(show_ver)\n    ------------------------ declaration ----------------------------------\n    def main():\n     'Obtain the OS version from the show version output\n     Print output to STDOUT'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       stdout.write(msg.encode('utf-8'))\n    ------------------------ declaration ----------------------------------\n    def _out(msg):\n     'Output a string'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       api_key = bot.config.get('api_keys', {}).get('bing_azure')\n       show_nsfw = text.endswith('   nsfw')\n       if show_nsfw:\n          text = text[:(-5)].strip().lower()\n       rating = (NSFW_FILTER if show_nsfw else DEFAULT_FILTER)\n       if (not api_key):\n          return 'Error:   No   Bing   Azure   API   details.'\n       params = {'Sources': bingify('image'), 'Query': bingify(text), 'Adult': bingify(rating), '$format': 'json'}\n       request = requests.get(API_URL, params=params, auth=(api_key, api_key))\n       j = request.json()['d']['results'][0]\n       if (not j['Image']):\n          return 'No   results.'\n       result = random.choice(j['Image'][:10])\n       tags = []\n       tags.append('{}x{}px'.format(result['Width'], result['Height']))\n       tags.append(result['ContentType'])\n       tags.append(filesize.size(int(result['FileSize']), system=filesize.alternative))\n       if ('explicit' in result['Thumbnail']['MediaUrl']):\n          tags.append('NSFW')\n       tag_text = ',   '.join(tags)\n       return '{}   ({})'.format(unescape(result['MediaUrl']), tag_text)\n    ------------------------ declaration ----------------------------------\n    @hook.command('bingimage', 'bis')\n     def bingimage(text, bot):\n     '<query> - returns the first bing image search result for <query>'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       if (not issubclass(optionable_type, Optionable)):\n          raise TypeError(u'The   given   `optionable_type`   was   not   a   subclass   of   `Optionable`:   {}'.format(optionable_type))\n       option_values = {}\n       registration_function = _options_registration_function(option_values)\n       optionable_type.register_options(registration_function)\n       option_values.update(**options)\n       return create_option_values(option_values)\n    ------------------------ declaration ----------------------------------\n    def create_option_values_for_optionable(optionable_type, **options):\n     'Create a fake OptionValueContainer with appropriate defaults for the given `Optionable` type.\"\n     :param type optionable_type: An :class:`pants.option.optionable.Optionable` subclass.\n     :param **options: Keyword args representing option values explicitly set via the command line.\n     :returns: A fake `OptionValueContainer`, ie: the value returned from `get_options()`.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       q = ((2 * endog) - 1)\n       X = exog\n       return np.add.reduce(stats.norm.logcdf((q * np.dot(X, params))))\n    ------------------------ declaration ----------------------------------\n    def probitloglike(params, endog, exog):\n     'Log likelihood for the probit'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       filename = get_pkg_data_filename(u'data/sip2.fits')\n       with catch_warnings(wcs.wcs.FITSFixedWarning) as caught_warnings:\n          ww = wcs.WCS(filename)\n          assert (len(caught_warnings) == 1)\n       n = 3\n       pixels = (np.arange(n) * np.ones((2, n))).T\n       result = ww.wcs_pix2world(pixels, 0, ra_dec_order=True)\n       ww.wcs_pix2world(pixels[..., 0], pixels[..., 1], 0, ra_dec_order=True)\n       close_enough = 1e-08\n       answer = np.array([[0.00024976, 0.00023018], [0.00023043, (-0.00024997)]])\n       assert np.all((np.abs((ww.wcs.pc - answer)) < close_enough))\n       answer = np.array([[202.39265216, 47.17756518], [202.39335826, 47.17754619], [202.39406436, 47.1775272]])\n       assert np.all((np.abs((result - answer)) < close_enough))\n    ------------------------ declaration ----------------------------------\n    def test_pix2world():\n     'From github issue #1463'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       (fig, ax) = utils.create_mpl_ax(ax)\n       infl = results.get_influence()\n       if criterion.lower().startswith('coo'):\n          psize = infl.cooks_distance[0]\n       elif criterion.lower().startswith('dff'):\n          psize = np.abs(infl.dffits[0])\n       else:\n          raise ValueError(('Criterion   %s   not   understood' % criterion))\n       old_range = np.ptp(psize)\n       new_range = ((size ** 2) - (8 ** 2))\n       psize = ((((psize - psize.min()) * new_range) / old_range) + (8 ** 2))\n       leverage = infl.hat_matrix_diag\n       if external:\n          resids = infl.resid_studentized_external\n       else:\n          resids = infl.resid_studentized_internal\n       from scipy import stats\n       cutoff = stats.t.ppf((1.0 - (alpha / 2)), results.df_resid)\n       large_resid = (np.abs(resids) > cutoff)\n       large_leverage = (leverage > _high_leverage(results))\n       large_points = np.logical_or(large_resid, large_leverage)\n       ax.scatter(leverage, resids, s=psize, alpha=plot_alpha)\n       labels = results.model.data.row_labels\n       if (labels is None):\n          labels = lrange(len(resids))\n       ax = utils.annotate_axes(np.where(large_points)[0], labels, lzip(leverage, resids), lzip((- ((psize / 2) ** 0.5)), ((psize / 2) ** 0.5)), 'x-large', ax)\n       font = {'fontsize': 16, 'color': 'black'}\n       ax.set_ylabel('Studentized   Residuals', **font)\n       ax.set_xlabel('H   Leverage', **font)\n       ax.set_title('Influence   Plot', **font)\n       return fig\n    ------------------------ declaration ----------------------------------\n    def influence_plot(results, external=True, alpha=0.05, criterion='cooks', size=48, plot_alpha=0.75, ax=None, **kwargs):\n     'Plot of influence in regression. Plots studentized resids vs. leverage.\n     Parameters\n     results : results instance\n     A fitted model.\n     external : bool\n     Whether to use externally or internally studentized residuals. It is\n     recommended to leave external as True.\n     alpha : float\n     The alpha value to identify large studentized residuals. Large means\n     abs(resid_studentized) > t.ppf(1-alpha/2, dof=results.df_resid)\n     criterion : str {\\'DFFITS\\', \\'Cooks\\'}\n     Which criterion to base the size of the points on. Options are\n     DFFITS or Cook\\'s D.\n     size : float\n     The range of `criterion` is mapped to 10**2 - size**2 in points.\n     plot_alpha : float\n     The `alpha` of the plotted points.\n     ax : matplotlib Axes instance\n     An instance of a matplotlib Axes.\n     Returns\n     fig : matplotlib figure\n     The matplotlib figure that contains the Axes.\n     Notes\n     Row labels for the observations in which the leverage, measured by the\n     diagonal of the hat matrix, is high or the residuals are large, as the\n     combination of large residuals and a high influence value indicates an\n     influence point. The value of large residuals can be controlled using the\n     `alpha` parameter. Large leverage points are identified as\n     hat_i > 2 * (df_model + 1)/nobs.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       nf = NetlogFile(name)\n       nf.sock.sendall(data)\n       nf.close()\n    ------------------------ declaration ----------------------------------\n    def send_file(name, data):\n     'Send file to result server'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       root = get_or_create_root()\n       return redirect('wiki:get', path=root.path)\n    ------------------------ declaration ----------------------------------\n    def root_create(request):\n     'In the edX wiki, we don\\'t show the root_create view. Instead, we\n     just create the root automatically if it doesn\\'t exist.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       return IMPL.block_device_mapping_update_or_create(context, values)\n    ------------------------ declaration ----------------------------------\n    def block_device_mapping_update_or_create(context, values):\n     'Update an entry of block device mapping.\n     If not existed, create a new entry'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       flavors = novaclient(request).flavors.list(is_public=is_public)\n       if get_extras:\n          for flavor in flavors:\n             flavor.extras = flavor_get_extras(request, flavor.id, True, flavor)\n       return flavors\n    ------------------------ declaration ----------------------------------\n    @profiler.trace\n     @memoized\n     def flavor_list(request, is_public=True, get_extras=False):\n     'Get the list of available instance sizes (flavors).'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       if (u'charset' in format):\n          return format\n       if (format in (u'application/json', u'text/javascript')):\n          return format\n       return (u'%s;   charset=%s' % (format, encoding))\n    ------------------------ declaration ----------------------------------\n    def build_content_type(format, encoding=u'utf-8'):\n     'Appends character encoding to the provided format if not already present.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       random_index = randint(0, (TopicCategory.objects.all().count() - 1))\n       tc = TopicCategory.objects.all()[random_index]\n       resource.category = tc\n       resource.save()\n    ------------------------ declaration ----------------------------------\n    def assign_random_category(resource):\n     'Assign a random category to a resource'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       NOT_PRESENT = object()\n       old_values = {}\n       for (attr, new_value) in kwargs.items():\n          old_values[attr] = getattr(obj, attr, NOT_PRESENT)\n          setattr(obj, attr, new_value)\n       try:\n          (yield)\n       finally:\n          for (attr, old_value) in old_values.items():\n             if (old_value is NOT_PRESENT):\n                del obj[attr]\n             else:\n                setattr(obj, attr, old_value)\n    ------------------------ declaration ----------------------------------\n    @contextlib.contextmanager\n     def temporary_mutation(obj, **kwargs):\n     'Temporarily set the attr on a particular object to a given value then\n     revert when finished.\n     One use of this is to temporarily set the read_deleted flag on a context\n     object:\n     with temporary_mutation(context, read_deleted=\"yes\"):\n     do_something_that_needed_deleted_objects()'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       modules = set(['textannotation', 'imageannotation', 'videoannotation'])\n       return bool(modules.intersection(course.advanced_modules))\n    ------------------------ declaration ----------------------------------\n    def is_harvard_notes_enabled(course):\n     'Returns True if Harvard Annotation Tool is enabled for the course,\n     False otherwise.\n     Checks for \\'textannotation\\', \\'imageannotation\\', \\'videoannotation\\' in the list\n     of advanced modules of the course.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       for (label, seq) in parse_fasta(file_lines):\n          if (id_from_fasta_label_line(label) in ids):\n             (yield (label, seq))\n    ------------------------ declaration ----------------------------------\n    def seqs_from_file(ids, file_lines):\n     'Extract labels and seqs from file'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       inse = tf.reduce_sum((output * target))\n       l = tf.reduce_sum((output * output))\n       r = tf.reduce_sum((target * target))\n       dice = ((2 * inse) / (l + r))\n       if (epsilon == 0):\n          return dice\n       else:\n          return tf.clip_by_value(dice, 0, (1.0 - epsilon))\n    ------------------------ declaration ----------------------------------\n    def dice_coe(output, target, epsilon=1e-10):\n     'S\u00f8rensen\u2013Dice coefficient for comparing the similarity of two distributions,\n     usually be used for binary image segmentation i.e. labels are binary.\n     The coefficient = [0, 1], 1 if totally match.\n     Parameters\n     output : tensor\n     A distribution with shape: [batch_size, ....], (any dimensions).\n     target : tensor\n     A distribution with shape: [batch_size, ....], (any dimensions).\n     epsilon : float\n     An optional name to attach to this layer.\n     Examples\n     >>> outputs = tl.act.pixel_wise_softmax(network.outputs)\n     >>> dice_loss = 1 - tl.cost.dice_coe(outputs, y_, epsilon=1e-5)\n     References\n     - `wiki-dice <https://en.wikipedia.org/wiki/S\u00f8rensen\u2013Dice_coefficient>`_'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       if callable(getattr(self.connection.features, 'confirm', None)):\n          self.connection.features.confirm()\n       elif hasattr(self, '_rollback_works'):\n          can_rollback = self._rollback_works()\n          self.connection.settings_dict['SUPPORTS_TRANSACTIONS'] = can_rollback\n       return self._get_test_db_name()\n    ------------------------ declaration ----------------------------------\n    def _skip_create_test_db(self, verbosity=1, autoclobber=False, serialize=True):\n     '``create_test_db`` implementation that skips both creation and flushing\n     The idea is to re-use the perfectly good test DB already created by an\n     earlier test run, cutting the time spent before any tests run from 5-13s\n     (depending on your I/O luck) down to 3.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       missionlist = readmission(aFileName)\n       print ('\\nUpload   mission   from   a   file:   %s' % import_mission_filename)\n       print '   Clear   mission'\n       cmds = vehicle.commands\n       cmds.clear()\n       for command in missionlist:\n          cmds.add(command)\n       print '   Upload   mission'\n       vehicle.commands.upload()\n    ------------------------ declaration ----------------------------------\n    def upload_mission(aFileName):\n     'Upload a mission from a file.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       if (math_expr.strip() == ''):\n          return float('nan')\n       math_interpreter = ParseAugmenter(math_expr, case_sensitive)\n       math_interpreter.parse_algebra()\n       (all_variables, all_functions) = add_defaults(variables, functions, case_sensitive)\n       math_interpreter.check_variables(all_variables, all_functions)\n       if case_sensitive:\n          casify = (lambda x: x)\n       else:\n          casify = (lambda x: x.lower())\n       evaluate_actions = {'number': eval_number, 'variable': (lambda x: all_variables[casify(x[0])]), 'function': (lambda x: all_functions[casify(x[0])](x[1])), 'atom': eval_atom, 'power': eval_power, 'parallel': eval_parallel, 'product': eval_product, 'sum': eval_sum}\n       return math_interpreter.reduce_tree(evaluate_actions)\n    ------------------------ declaration ----------------------------------\n    def evaluator(variables, functions, math_expr, case_sensitive=False):\n     'Evaluate an expression; that is, take a string of math and return a float.\n     -Variables are passed as a dictionary from string to value. They must be\n     python numbers.\n     -Unary functions are passed as a dictionary from string to function.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       if (not data):\n          raise ValueError('No   data   available   for   pie   chart.')\n       all_fracs = []\n       all_labels = []\n       colors = []\n       for (color_ix, (c_label, c_frac)) in enumerate(data):\n          if (c_label == others_key):\n             colors.append(others_color)\n          else:\n             colors.append(data_colors[pref_colors[c_label]].toHex())\n          all_fracs.append(c_frac)\n          if should_capitalize:\n             capital = ('%s   (%.2f%%)' % (c_label.capitalize(), (c_frac * 100.0)))\n             all_labels.append(capital)\n          else:\n             all_labels.append(('%s   (%.2f%%)' % (c_label, (c_frac * 100.0))))\n       rc('font', size='10')\n       rc('text', color=label_color)\n       rc('patch', linewidth=0.1)\n       rc('axes', linewidth=0.5, edgecolor=label_color)\n       rc('text', usetex=False)\n       fig = figure(randrange(10000), figsize=(plot_width, plot_height))\n       fp = FontProperties()\n       fp.set_size('8')\n       if (len(data) > 30):\n          loc = 4\n       else:\n          loc = 5\n       mtitle = 'Pie   Chart'\n       if ('title' in props):\n          mtitle = props['title']\n       axis('off')\n       title(mtitle, fontsize='10', color=label_color)\n       ax = axes([0.0, 0.0, 0.5, 1])\n       p1 = pie(all_fracs, shadow=False, colors=colors)\n       if (file_prefix is None):\n          img_name = make_img_name(file_ext='.png')\n       else:\n          img_name = file_prefix\n       img_abs = os.path.join(dir_path, 'charts', img_name)\n       savefig(img_abs, dpi=dpi, facecolor=background_color)\n       eps_link = ''\n       eps_abs = ''\n       if (file_prefix is None):\n          eps_img_name = make_img_name(file_ext=('.%s' % generate_image_type))\n       else:\n          eps_img_name = (file_prefix + ('.%s' % generate_image_type))\n       savefig(os.path.join(dir_path, 'charts', eps_img_name), facecolor=background_color)\n       if (generate_image_type == 'eps'):\n          strip_eps_font(os.path.join(dir_path, 'charts', eps_img_name))\n       eps_abs = os.path.join(dir_path, 'charts', eps_img_name)\n       eps_link = (PDF_LINK % (os.path.join('charts', eps_img_name), ('View   Figure   (.%s)' % generate_image_type)))\n       close(fig)\n       clf()\n       updated_taxa = []\n       updated_colors = []\n       for i in data:\n          if (i[0] != others_key):\n             updated_taxa.append(i[0].replace('\"', ''))\n             updated_colors.append(data_colors[pref_colors[i[0]]].toHex())\n          else:\n             updated_taxa.append(others_key)\n             updated_colors.append(others_color)\n       if include_html_legend:\n          legend_fname_png = make_legend(updated_taxa, updated_colors, plot_width, plot_height, label_color, background_color, img_abs, 'png', 80)\n          legend_fpath_png = os.path.join('charts', legend_fname_png)\n       legend_fname = make_legend(updated_taxa, updated_colors, plot_width, plot_height, label_color, background_color, img_abs, generate_image_type, dpi)\n       legend_fpath = os.path.join('charts', legend_fname)\n       legend_link = (LEGEND_LINK % (legend_fpath, ('View   Legend   (.%s)' % generate_image_type)))\n       points_id = ''\n       xmap_html = ''\n       if (not include_html_legend):\n          IMG_TEXT = (IMG_SRC_minus_legend % (os.path.join('charts', img_name), points_id))\n       else:\n          IMG_TEXT = (IMG_SRC_2 % (os.path.join('charts', img_name), points_id, legend_fpath_png))\n       return (eps_link, legend_link, IMG_TEXT, xmap_html)\n    ------------------------ declaration ----------------------------------\n    def make_pie_chart(data, dir_path, level, prefs, pref_colors, background_color, label_color, generate_image_type, plot_width, plot_height, bar_width, dpi, include_html_legend, file_prefix=None, props={}, others_key='All   Other   Categories', others_color='#eeeeee', should_capitalize=True):\n     'Write interactive piechart\n     data: [fraction:label,...]\n     trunc_len: truncates labels after this many chars'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       try:\n          return ismount_raw(path)\n       except OSError:\n          return False\n    ------------------------ declaration ----------------------------------\n    def ismount(path):\n     'Test whether a path is a mount point. This will catch any\n     exceptions and translate them into a False return value\n     Use ismount_raw to have the exceptions raised instead.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       f = (_Cfunctions.get('libvlc_vlm_get_media_instance_title', None) or _Cfunction('libvlc_vlm_get_media_instance_title', ((1,), (1,), (1,)), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int))\n       return f(p_instance, psz_name, i_instance)\n    ------------------------ declaration ----------------------------------\n    def libvlc_vlm_get_media_instance_title(p_instance, psz_name, i_instance):\n     'Get vlm_media instance title number by name or instance id.\n     @param p_instance: a libvlc instance.\n     @param psz_name: name of vlm media instance.\n     @param i_instance: instance id.\n     @return: title as number or -1 on error.\n     @bug: will always return 0.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       if (len(s) < 1):\n          return Raw(s)\n       ietype = ord(s[0])\n       cls = ietypecls.get(ietype, Raw)\n       if ((cls == Raw) and ((ietype & 128) == 128)):\n          cls = IE_NotImplementedTLV\n       return cls(s)\n    ------------------------ declaration ----------------------------------\n    def IE_Dispatcher(s):\n     'Choose the correct Information Element class.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       results = []\n       for path in combine_lists(*path_seqs):\n          expanded = expand_path(path)\n          paths = (sorted(glob.glob(expanded)) or [expanded])\n          results.extend(paths)\n       return results\n    ------------------------ declaration ----------------------------------\n    def combine_path_lists(*path_seqs):\n     'Concatenate the given sequences into a list. Ignore None values.\n     Resolve ``~`` (home dir) and environment variables, and expand globs\n     that refer to the local filesystem.\n     .. versionchanged:: 0.4.6\n     Can take single strings as well as lists.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       atoi = (lambda addr: struct.unpack('!I', socket.inet_aton(addr))[0])\n       itoa = (lambda addr: socket.inet_ntoa(struct.pack('!I', addr)))\n       (address, netmask) = network.split('/')\n       netmask_i = ((4294967295 << (32 - atoi(netmask))) & 4294967295)\n       return itoa(((atoi(address) & netmask_i) + 1))\n    ------------------------ declaration ----------------------------------\n    def first_ip(network):\n     'Return the first IPv4 address in network\n     Args:\n     network (str): network in CIDR format\n     Returns:\n     str: first IPv4 address'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       assert (name in ['harry', 'terry', 'ule'])\n       common = os.path.join(preprocess('${PYLEARN2_DATA_PATH}'), 'UTLC', 'sparse', (name + '_'))\n       (trname, vname, tename) = [((common + subset) + '.npy') for subset in ['train', 'valid', 'test']]\n       train = load_sparse(trname)\n       valid = load_sparse(vname)\n       test = load_sparse(tename)\n       if randomize_valid:\n          rng = make_np_rng(None, [1, 2, 3, 4], which_method='permutation')\n          perm = rng.permutation(valid.shape[0])\n          valid = valid[perm]\n       if randomize_test:\n          rng = make_np_rng(None, [1, 2, 3, 4], which_method='permutation')\n          perm = rng.permutation(test.shape[0])\n          test = test[perm]\n       if normalize:\n          if (name == 'ule'):\n             train = (train.astype(theano.config.floatX) / 255)\n             valid = (valid.astype(theano.config.floatX) / 255)\n             test = (test.astype(theano.config.floatX) / 255)\n          elif (name == 'harry'):\n             train = train.astype(theano.config.floatX)\n             valid = valid.astype(theano.config.floatX)\n             test = test.astype(theano.config.floatX)\n             std = 0.6933604603392579\n             train = (train / std)\n             valid = (valid / std)\n             test = (test / std)\n          elif (name == 'terry'):\n             train = train.astype(theano.config.floatX)\n             valid = valid.astype(theano.config.floatX)\n             test = test.astype(theano.config.floatX)\n             train = (train / 300)\n             valid = (valid / 300)\n             test = (test / 300)\n          else:\n             raise Exception(\"This   dataset   don't   have   its   normalization   defined\")\n       if transfer:\n          fname = os.path.join(preprocess('${PYLEARN2_DATA_PATH}'), 'UTLC', 'filetensor', (name + '_transfer.ft'))\n          transfer = load_filetensor(fname)\n          return (train, valid, test, transfer)\n       else:\n          return (train, valid, test)\n    ------------------------ declaration ----------------------------------\n    def load_sparse_dataset(name, normalize=True, transfer=False, randomize_valid=False, randomize_test=False):\n     'Load the train,valid,test data for the dataset `name` and return it in\n     sparse format.\n     We suppose the data was created with ift6266h11/pretraitement/to_npy.py\n     that shuffle the train. So the train should already be shuffled.\n     name : \\'avicenna\\', \\'harry\\', \\'rita\\', \\'sylvester\\' or \\'ule\\'\n     Which dataset to load\n     normalize : bool\n     If True, we normalize the train dataset before returning it\n     transfer :\n     If True also return the transfer label\n     randomize_valid : bool\n     Do we randomize the order of the valid set?  We always use the same\n     random order If False, return in the same order as downloaded on the\n     web\n     randomize_test : bool\n     Do we randomize the order of the test set?  We always use the same\n     random order If False, return in the same order as downloaded on the\n     web\n     Returns\n     train, valid, test : ndarrays\n     Datasets returned if transfer = False\n     train, valid, test, transfer : ndarrays\n     Datasets returned if transfer = False'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       f = (_Cfunctions.get('libvlc_video_get_spu_description', None) or _Cfunction('libvlc_video_get_spu_description', ((1,),), None, ctypes.POINTER(TrackDescription), MediaPlayer))\n       return f(p_mi)\n    ------------------------ declaration ----------------------------------\n    def libvlc_video_get_spu_description(p_mi):\n     'Get the description of available video subtitles.\n     @param p_mi: the media player.\n     @return: list containing description of available video subtitles. It must be freed with L{libvlc_track_description_list_release}().'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       arr = np.asarray(data, dtype=np.float32)\n       out = cuda.device_array(1, dtype=np.float32)\n       gpu_single_block_sum[(1, gpu_block_sum_max_blockdim)](arr, out)\n       return out.copy_to_host()[0]\n    ------------------------ declaration ----------------------------------\n    def sum_parts(data):\n     'Driver for ``gpu_single_block_sum`` kernel'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       assert hug.validate.contains_one_of('no', 'way')(TEST_SCHEMA)\n       assert (not hug.validate.contains_one_of('last', 'place')(TEST_SCHEMA))\n    ------------------------ declaration ----------------------------------\n    def test_contains_one_of():\n     'Test to ensure hug\\'s contains_one_of validation function works as expected to ensure presence of a field'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       if (len(nestedRings) > 0):\n          oldOrderedLocation.z = nestedRings[0].z\n       closestDistance = 9.876543219876543e+17\n       closestNestedRing = None\n       for remainingNestedRing in nestedRings:\n          distance = getClosestDistanceIndexToLine(oldOrderedLocation.dropAxis(), remainingNestedRing.boundary).distance\n          if (distance < closestDistance):\n             closestDistance = distance\n             closestNestedRing = remainingNestedRing\n       nestedRings.remove(closestNestedRing)\n       closestNestedRing.addToThreads(extrusionHalfWidth, oldOrderedLocation, skein, threadSequence)\n       return closestNestedRing\n    ------------------------ declaration ----------------------------------\n    def getTransferClosestNestedRing(extrusionHalfWidth, nestedRings, oldOrderedLocation, skein, threadSequence):\n     'Get and transfer the closest remaining nested ring.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       requires = IS_ONE_OF(current.db, 'org_organisation.id', org_OrganisationRepresent(), realms=realms, updateable=updateable, orderby='org_organisation.name', sort=True)\n       if (not required):\n          requires = IS_EMPTY_OR(requires)\n       return requires\n    ------------------------ declaration ----------------------------------\n    def org_organisation_requires(required=False, realms=None, updateable=False):\n     '@param required: Whether the selection is optional or mandatory\n     @param realms: Whether the list should be filtered to just those\n     belonging to a list of realm entities\n     @param updateable: Whether the list should be filtered to just those\n     which the user has Write access to\n     @ToDo: Option to remove Branches\n     @ToDo: Option to only include Branches'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       return 'emoncms{}_{}_{}_{}_{}'.format(sensorid, feedtag, feedname, feedid, feeduserid)\n    ------------------------ declaration ----------------------------------\n    def get_id(sensorid, feedtag, feedname, feedid, feeduserid):\n     'Return unique identifier for feed / sensor.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       return __execute_cmd('setniccfg   -s   {0}   {1}   {2}'.format(ip, netmask, gateway))\n    ------------------------ declaration ----------------------------------\n    def set_network(ip, netmask, gateway):\n     'Configure Network\n     CLI Example:\n     .. code-block:: bash\n     salt dell drac.set_network [DRAC IP] [NETMASK] [GATEWAY]\n     salt dell drac.set_network 192.168.0.2 255.255.255.0 192.168.0.1'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       with smart_open(fname, 'wb') as fout:\n          _pickle.dump(obj, fout, protocol=protocol)\n    ------------------------ declaration ----------------------------------\n    def pickle(obj, fname, protocol=2):\n     'Pickle object `obj` to file `fname`.\n     `protocol` defaults to 2 so pickled objects are compatible across\n     Python 2.x and 3.x.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       return (None, changed_file)\n    ------------------------ declaration ----------------------------------\n    def split_file_dummy(changed_file):\n     'Split the repository-relative filename into a tuple of (branchname,\n     branch_relative_filename). If you have no branches, this should just\n     return (None, changed_file).'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       entries1 = _tree_entries(path, tree1)\n       entries2 = _tree_entries(path, tree2)\n       i1 = i2 = 0\n       len1 = len(entries1)\n       len2 = len(entries2)\n       result = []\n       while ((i1 < len1) and (i2 < len2)):\n          entry1 = entries1[i1]\n          entry2 = entries2[i2]\n          if (entry1.path < entry2.path):\n             result.append((entry1, _NULL_ENTRY))\n             i1 += 1\n          elif (entry1.path > entry2.path):\n             result.append((_NULL_ENTRY, entry2))\n             i2 += 1\n          else:\n             result.append((entry1, entry2))\n             i1 += 1\n             i2 += 1\n       for i in range(i1, len1):\n          result.append((entries1[i], _NULL_ENTRY))\n       for i in range(i2, len2):\n          result.append((_NULL_ENTRY, entries2[i]))\n       return result\n    ------------------------ declaration ----------------------------------\n    def _merge_entries(path, tree1, tree2):\n     'Merge the entries of two trees.\n     :param path: A path to prepend to all tree entry names.\n     :param tree1: The first Tree object to iterate, or None.\n     :param tree2: The second Tree object to iterate, or None.\n     :return: A list of pairs of TreeEntry objects for each pair of entries in\n     the trees. If an entry exists in one tree but not the other, the other\n     entry will have all attributes set to None. If neither entry\\'s path is\n     None, they are guaranteed to match.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       req_vars = form.request_vars\n       position = req_vars.get('position', '')\n       reason = req_vars.get('reason', '')\n       db = current.db\n       table = db.auth_user\n       db((table.id == form.vars.id)).update(comments=('%s   |   %s' % (position, reason)))\n    ------------------------ declaration ----------------------------------\n    def register_onaccept(form):\n     'Tasks to be performed after a new user registers'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       if (not a):\n          return []\n       else:\n          return [((a * b) % p) for b in f]\n    ------------------------ declaration ----------------------------------\n    def gf_mul_ground(f, a, p, K):\n     'Compute ``f * a`` where ``f`` in ``GF(p)[x]`` and ``a`` in ``GF(p)``.\n     Examples\n     >>> from sympy.polys.domains import ZZ\n     >>> from sympy.polys.galoistools import gf_mul_ground\n     >>> gf_mul_ground([3, 2, 4], 2, 5, ZZ)\n     [1, 4, 3]'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       review_request_id_to_commits_map = defaultdict(list)\n       branch_name = payload.get(u'repository_path')\n       if (not branch_name):\n          return review_request_id_to_commits_map\n       revisions = payload.get(u'revisions', [])\n       for revision in revisions:\n          revision_id = revision.get(u'revision')\n          if (len(revision_id) > 7):\n             revision_id = revision_id[:7]\n          commit_message = revision.get(u'message')\n          review_request_id = get_review_request_id(commit_message, server_url)\n          review_request_id_to_commits_map[review_request_id].append((u'%s   (%s)' % (branch_name, revision_id)))\n       return review_request_id_to_commits_map\n    ------------------------ declaration ----------------------------------\n    def close_review_requests(payload, server_url):\n     'Closes all review requests for the Google Code repository.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       try:\n          codecs.lookup(argument)\n       except LookupError:\n          raise ValueError(('unknown   encoding:   \"%s\"' % argument))\n       return argument\n    ------------------------ declaration ----------------------------------\n    def encoding(argument):\n     'Verfies the encoding argument by lookup.\n     (Directive option conversion function.)\n     Raises ValueError for unknown encodings.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       for (k, v) in opts.items():\n          setConfigOption(k, v)\n    ------------------------ declaration ----------------------------------\n    def setConfigOptions(**opts):\n     'Set global configuration options.\n     Each keyword argument sets one global option.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       subKeys = itemName.split(':')\n       subResults = results\n       for subKey in subKeys:\n          subResults = subResults[subKey]\n       return subResults\n    ------------------------ declaration ----------------------------------\n    def _getReportItem(itemName, results):\n     'Get a specific item by name out of the results dict.\n     The format of itemName is a string of dictionary keys separated by colons,\n     each key being one level deeper into the results dict. For example,\n     \\'key1:key2\\' would fetch results[\\'key1\\'][\\'key2\\'].\n     If itemName is not found in results, then None is returned'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       inner_text = []\n       for child in node.childNodes:\n          if ((child.nodeType == child.TEXT_NODE) or (child.nodeType == child.CDATA_SECTION_NODE)):\n             inner_text.append(child.data)\n          elif (child.nodeType == child.ELEMENT_NODE):\n             inner_text.extend(getInnerText(child))\n          else:\n             pass\n       return ''.join(inner_text)\n    ------------------------ declaration ----------------------------------\n    def getInnerText(node):\n     'Get all the inner text of a DOM node (recursively).'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       if (not name):\n          return namespace(namespace_)\n       name = canonicalize_name(name)\n       if (name[0] == SEP):\n          resolved_name = name\n       elif is_private(name):\n          resolved_name = canonicalize_name(((namespace_ + SEP) + name[1:]))\n       else:\n          resolved_name = (namespace(namespace_) + name)\n       if (remappings and (resolved_name in remappings)):\n          return remappings[resolved_name]\n       else:\n          return resolved_name\n    ------------------------ declaration ----------------------------------\n    def resolve_name(name, namespace_, remappings=None):\n     'Resolve a ROS name to its global, canonical form. Private ~names\n     are resolved relative to the node name.\n     @param name: name to resolve.\n     @type  name: str\n     @param namespace_: node name to resolve relative to.\n     @type  namespace_: str\n     @param remappings: Map of resolved remappings. Use None to indicate no remapping.\n     @return: Resolved name. If name is empty/None, resolve_name\n     returns parent namespace_. If namespace_ is empty/None,\n     @rtype: str'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       qt_start = u'<!--:'\n       qt_end = u'-->'\n       qt_end_with_lang_len = 5\n       qt_chunks = text.split(qt_start)\n       content_by_lang = {}\n       common_txt_list = []\n       for c in qt_chunks:\n          if (not c.strip()):\n             continue\n          if c.startswith(qt_end):\n             lang = u''\n             c = c.lstrip(qt_end)\n             if (not c):\n                continue\n          elif c[2:].startswith(qt_end):\n             lang = c[:2]\n             c = c[qt_end_with_lang_len:]\n          else:\n             lang = u''\n          if (not lang):\n             common_txt_list.append(c)\n             for l in content_by_lang.keys():\n                content_by_lang[l].append(c)\n          else:\n             content_by_lang[lang] = (content_by_lang.get(lang, common_txt_list) + [c])\n       if (common_txt_list and (not content_by_lang)):\n          content_by_lang[u''] = common_txt_list\n       for l in content_by_lang.keys():\n          content_by_lang[l] = u'   '.join(content_by_lang[l])\n       return content_by_lang\n    ------------------------ declaration ----------------------------------\n    def separate_qtranslate_content(text):\n     'Parse the content of a wordpress post or page and separate qtranslate languages.\n     qtranslate tags: <!--:LL-->blabla<!--:-->'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       def getter(value):\n          if ET.iselement(value):\n             value = value.attrib\n          try:\n             if _is_re_match(value):\n                return value.group(item)\n             else:\n                return value[item]\n          except (KeyError, IndexError):\n             return default\n          except (TypeError, AttributeError) as err:\n             raise ValueError(err)\n       return transform(getter)\n    ------------------------ declaration ----------------------------------\n    def get(item, default=None):\n     'Get item from value (value[item]).\n     If the item is not found, return the default.\n     Handles XML elements, regex matches and anything that has __getitem__.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       txt = txt.replace('\\r\\n', '\\n')\n       txt = txt.replace('\\r', '\\n')\n       txt_line_count = len(re.findall('(?mu)^\\\\s*.+$', txt))\n       docanalysis = DocAnalysis('txt', txt)\n       hardbreaks = docanalysis.line_histogram(0.55)\n       if hardbreaks:\n          tab_line_count = len(re.findall('(?mu)^( DCTB |\\\\s{2,}).+$', txt))\n          print_percent = (tab_line_count / float(txt_line_count))\n          empty_line_count = len(re.findall('(?mu)^\\\\s*$', txt))\n          block_percent = (empty_line_count / float(txt_line_count))\n          if (print_percent >= block_percent):\n             if (0.15 <= print_percent <= 0.75):\n                return 'print'\n          elif (0.15 <= block_percent <= 0.75):\n             return 'block'\n          return 'unformatted'\n       return 'single'\n    ------------------------ declaration ----------------------------------\n    def detect_paragraph_type(txt):\n     'Tries to determine the paragraph type of the document.\n     block: Paragraphs are separated by a blank line.\n     single: Each line is a paragraph.\n     print: Each paragraph starts with a 2+ spaces or a tab\n     and ends when a new paragraph is reached.\n     unformatted: most lines have hard line breaks, few/no blank lines or indents\n     returns block, single, print, unformatted'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       idcount = 0\n       if (extension and (not extension.startswith('.'))):\n          extension = ('.%s' % extension)\n       fname = (base_name + extension)\n       while os.path.exists(fname):\n          fname = ('%s-%d%s' % (base_name, idcount, extension))\n          idcount += 1\n       return fname\n    ------------------------ declaration ----------------------------------\n    def unique_file_name(base_name, extension=''):\n     'Creates a unique file name based on the specified base name.\n     @base_name - The base name to use for the unique file name.\n     @extension - The file extension to use for the unique file name.\n     Returns a unique file string.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       so_far = set()\n       def no_dups(x):\n          k = key(x)\n          if (k in so_far):\n             return False\n          else:\n             so_far.add(k)\n             return True\n       return IteratorFilter(iterator, no_dups)\n    ------------------------ declaration ----------------------------------\n    def UniqueIterator(iterator, key=(lambda x: x)):\n     'Takes an iterator and returns an iterator that returns only the\n     first occurence of each entry'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       if (not is_list_like(n)):\n          n = np.array(([n] * len(m)))\n       elif (isinstance(n, np.ndarray) and (n.ndim == 0)):\n          n = np.repeat(np.array(n, ndmin=1), len(m))\n       try:\n          nn = n[m]\n          if (not _is_na_compat(v, nn[0])):\n             raise ValueError\n          nn_at = nn.astype(v.dtype)\n          if (not is_numeric_v_string_like(nn, nn_at)):\n             comp = (nn == nn_at)\n             if (is_list_like(comp) and comp.all()):\n                nv = v.copy()\n                nv[m] = nn_at\n                return nv\n       except (ValueError, IndexError, TypeError):\n          pass\n       (dtype, _) = _maybe_promote(n.dtype)\n       if (is_extension_type(v.dtype) and is_object_dtype(dtype)):\n          nv = v.get_values(dtype)\n       else:\n          nv = v.astype(dtype)\n       try:\n          nv[m] = n[m]\n       except ValueError:\n          (idx,) = np.where(np.squeeze(m))\n          for (mask_index, new_val) in zip(idx, n[m]):\n             nv[mask_index] = new_val\n       return nv\n    ------------------------ declaration ----------------------------------\n    def _putmask_smart(v, m, n):\n     'Return a new block, try to preserve dtype if possible.\n     Parameters\n     v : `values`, updated in-place (array like)\n     m : `mask`, applies to both sides (array like)\n     n : `new values` either scalar or an array like aligned with `values`'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       filter_func = (filter_func or (lambda __: True))\n       stack = deque([start_node])\n       yield_results = {}\n       while stack:\n          current_node = stack.pop()\n          if (get_parents and (current_node != start_node)):\n             parents = get_parents(current_node)\n             if (not all(((parent in yield_results) for parent in parents))):\n                continue\n             elif ((not yield_descendants_of_unyielded) and (not any((yield_results[parent] for parent in parents)))):\n                continue\n          if (current_node not in yield_results):\n             if get_parents:\n                unvisited_children = list(get_children(current_node))\n             else:\n                unvisited_children = list((child for child in get_children(current_node) if (child not in yield_results)))\n             unvisited_children.reverse()\n             stack.extend(unvisited_children)\n             should_yield_node = filter_func(current_node)\n             if should_yield_node:\n                (yield current_node)\n             yield_results[current_node] = should_yield_node\n    ------------------------ declaration ----------------------------------\n    def _traverse_generic(start_node, get_parents, get_children, filter_func=None, yield_descendants_of_unyielded=False):\n     'Helper function to avoid duplicating functionality between\n     traverse_depth_first and traverse_topologically.\n     If get_parents is None, do a pre-order traversal.\n     Else, do a topological traversal.\n     The topological traversal has a worse time complexity than\n     pre-order does, as it needs to check whether each node\\'s\n     parents have been visited.\n     Arguments:\n     See description in traverse_topologically.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       end = evaluate.getVector3FromElementNode(elementNode)\n       previousElementNode = elementNode.getPreviousElementNode()\n       if (previousElementNode == None):\n          print 'Warning,   can   not   get   previousElementNode   in   getQuadraticPath   in   quadratic   for:'\n          print elementNode\n          return [end]\n       begin = elementNode.getPreviousVertex(Vector3())\n       controlPoint = evaluate.getVector3ByPrefix(None, elementNode, 'controlPoint')\n       if (controlPoint == None):\n          oldControlPoint = evaluate.getVector3ByPrefixes(previousElementNode, ['controlPoint', 'controlPoint1'], None)\n          if (oldControlPoint == None):\n             oldControlPoint = end\n          controlPoint = ((begin + begin) - oldControlPoint)\n          evaluate.addVector3ToElementNode(elementNode, 'controlPoint', controlPoint)\n       return svg_reader.getQuadraticPoints(begin, controlPoint, end, lineation.getNumberOfBezierPoints(begin, elementNode, end))\n    ------------------------ declaration ----------------------------------\n    def getQuadraticPath(elementNode):\n     'Get the quadratic path.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       if (isinstance(node.op, tensor.Elemwise) and isinstance(node.op.scalar_op, scalar.basic.Log) and (len(node.inputs) == 1) and (node.inputs[0].owner is not None) and isinstance(node.inputs[0].owner.op, Softmax)):\n          inVars = node.inputs[0].owner.inputs[0]\n          new_op = LogSoftmax()\n          ret = new_op(inVars)\n          ret.tag.values_eq_approx = values_eq_approx_remove_inf\n          copy_stack_trace([node.inputs[0], node.outputs[0]], ret)\n          return [ret]\n    ------------------------ declaration ----------------------------------\n    @opt.register_specialize('stabilize', 'fast_compile')\n     @gof.local_optimizer([tensor.Elemwise])\n     def local_logsoftmax(node):\n     'Detect Log(Softmax(x)) and replace it with LogSoftmax(x)\n     Note: only forward pass is affected'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       freqs = numpy.array([(((f + 1) * fs) / (2 * nfft)) for f in range(nfft)])\n       Cp = 27.5\n       nChroma = numpy.round((12.0 * numpy.log2((freqs / Cp)))).astype(int)\n       nFreqsPerChroma = numpy.zeros((nChroma.shape[0],))\n       uChroma = numpy.unique(nChroma)\n       for u in uChroma:\n          idx = numpy.nonzero((nChroma == u))\n          nFreqsPerChroma[idx] = idx[0].shape\n       return (nChroma, nFreqsPerChroma)\n    ------------------------ declaration ----------------------------------\n    def stChromaFeaturesInit(nfft, fs):\n     'This function initializes the chroma matrices used in the calculation of the chroma features'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       def _set_nxm_headers_dec(self):\n          self.nxm_headers = nxm_headers\n          return self\n       return _set_nxm_headers_dec\n    ------------------------ declaration ----------------------------------\n    def _set_nxm_headers(nxm_headers):\n     'Annotate corresponding NXM header'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       return get_i18n().gettext(string, **variables)\n    ------------------------ declaration ----------------------------------\n    def gettext(string, **variables):\n     'See :meth:`I18n.gettext`.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       diff = (X - x_old)\n       diff_norm = np.sqrt(np.sum((diff ** 2), axis=1))\n       mask = (diff_norm >= _EPSILON)\n       is_x_old_in_X = int((mask.sum() < X.shape[0]))\n       diff = diff[mask]\n       diff_norm = diff_norm[mask][:, np.newaxis]\n       quotient_norm = linalg.norm(np.sum((diff / diff_norm), axis=0))\n       if (quotient_norm > _EPSILON):\n          new_direction = (np.sum((X[mask, :] / diff_norm), axis=0) / np.sum((1 / diff_norm), axis=0))\n       else:\n          new_direction = 1.0\n          quotient_norm = 1.0\n       return ((max(0.0, (1.0 - (is_x_old_in_X / quotient_norm))) * new_direction) + (min(1.0, (is_x_old_in_X / quotient_norm)) * x_old))\n    ------------------------ declaration ----------------------------------\n    def _modified_weiszfeld_step(X, x_old):\n     'Modified Weiszfeld step.\n     This function defines one iteration step in order to approximate the\n     spatial median (L1 median). It is a form of an iteratively re-weighted\n     least squares method.\n     Parameters\n     X : array, shape = [n_samples, n_features]\n     Training vector, where n_samples is the number of samples and\n     n_features is the number of features.\n     x_old : array, shape = [n_features]\n     Current start vector.\n     Returns\n     x_new : array, shape = [n_features]\n     New iteration step.\n     References\n     - On Computation of Spatial Median for Robust Data Mining, 2005\n     T. K\u00e4rkk\u00e4inen and S. \u00c4yr\u00e4m\u00f6\n     http://users.jyu.fi/~samiayr/pdf/ayramo_eurogen05.pdf'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       if (not hasattr(req, 'best_match_language')):\n          return e\n       locale = req.best_match_language()\n       if isinstance(e, webob.exc.HTTPError):\n          e.explanation = i18n.translate(e.explanation, locale)\n          e.detail = i18n.translate(e.detail, locale)\n          if getattr(e, 'body_template', None):\n             e.body_template = i18n.translate(e.body_template, locale)\n       return e\n    ------------------------ declaration ----------------------------------\n    def translate_exception(req, e):\n     'Translates all translatable elements of the given exception.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       return uuid.uuid4().hex\n    ------------------------ declaration ----------------------------------\n    def rand_uuid_hex():\n     'Generate a random UUID hex string\n     :return: a random UUID (e.g. \\'0b98cf96d90447bda4b46f31aeb1508c\\')\n     :rtype: string'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       return time.time()\n    ------------------------ declaration ----------------------------------\n    def current_time():\n     'Retrieve the current time, this function is mocked out in unit testing.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       would_be_changed = []\n       for package in packages:\n          (installed, updated) = query_package(module, xbps_path, package)\n          if (((state in ['present', 'latest']) and (not installed)) or ((state == 'absent') and installed) or ((state == 'latest') and (not updated))):\n             would_be_changed.append(package)\n       if would_be_changed:\n          if (state == 'absent'):\n             state = 'removed'\n          module.exit_json(changed=True, msg=('%s   package(s)   would   be   %s' % (len(would_be_changed), state)), packages=would_be_changed)\n       else:\n          module.exit_json(changed=False, msg=('package(s)   already   %s' % state), packages=[])\n    ------------------------ declaration ----------------------------------\n    def check_packages(module, xbps_path, packages, state):\n     'Returns change status of command'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       for d in frappe.get_all(u'Daily   Work   Summary', dict(status=u'Open')):\n          daily_work_summary = frappe.get_doc(u'Daily   Work   Summary', d.name)\n          daily_work_summary.send_summary()\n    ------------------------ declaration ----------------------------------\n    def send_summary():\n     'Send summary to everyone'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       if (provider in drivers):\n          raise AttributeError(('Provider   %s   already   registered' % provider))\n       drivers[provider] = (module, klass)\n       try:\n          driver = get_driver(drivers, provider)\n       except (ImportError, AttributeError):\n          exp = sys.exc_info()[1]\n          drivers.pop(provider)\n          raise exp\n       return driver\n    ------------------------ declaration ----------------------------------\n    def set_driver(drivers, provider, module, klass):\n     'Sets a driver.\n     :param drivers: Dictionary to store providers.\n     :param provider: Id of provider to set driver for\n     :type provider: :class:`libcloud.types.Provider`\n     :param module: The module which contains the driver\n     :type module: L\n     :param klass: The driver class name\n     :type klass:'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       return str(tablename)\n    ------------------------ declaration ----------------------------------\n    def classname_for_table(base, tablename, table):\n     'Return the class name that should be used, given the name\n     of a table.\n     The default implementation is::\n     return str(tablename)\n     Alternate implementations can be specified using the\n     :paramref:`.AutomapBase.prepare.classname_for_table`\n     parameter.\n     :param base: the :class:`.AutomapBase` class doing the prepare.\n     :param tablename: string name of the :class:`.Table`.\n     :param table: the :class:`.Table` object itself.\n     :return: a string class name.\n     .. note::\n     In Python 2, the string used for the class name **must** be a non-Unicode\n     object, e.g. a ``str()`` object.  The ``.name`` attribute of\n     :class:`.Table` is typically a Python unicode subclass, so the ``str()``\n     function should be applied to this name, after accounting for any non-ASCII\n     characters.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       splitLine = line.split()\n       return Vector3(float(splitLine[1]), float(splitLine[2]), float(splitLine[3]))\n    ------------------------ declaration ----------------------------------\n    def getVertexGivenLine(line):\n     'Get vertex given obj vertex line.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       flags = []\n       TCP_FIN = 1\n       TCP_SYN = 2\n       TCP_RST = 4\n       TCP_PSH = 8\n       TCP_ACK = 16\n       TCP_URG = 32\n       TCP_ECE = 64\n       TCP_CWK = 128\n       if (packet['tcp']['flags'] & TCP_FIN):\n          flags.append('FIN')\n       elif (packet['tcp']['flags'] & TCP_SYN):\n          flags.append('SYN')\n       elif (packet['tcp']['flags'] & TCP_RST):\n          flags.append('RST')\n       elif (packet['tcp']['flags'] & TCP_PSH):\n          flags.append('PSH')\n       elif (packet['tcp']['flags'] & TCP_ACK):\n          flags.append('ACK')\n       elif (packet['tcp']['flags'] & TCP_URG):\n          flags.append('URG')\n       elif (packet['tcp']['flags'] & TCP_ECE):\n          flags.append('ECE')\n       elif (packet['tcp']['flags'] & TCP_CWK):\n          flags.append('CWK')\n       else:\n          print('UNKNOWN   PACKET')\n       if (packet['tcp']['d_port'] == 4505):\n          if (('SYN' in flags) and (len(flags) == 1)):\n             return 10\n          elif ('FIN' in flags):\n             return 12\n       elif (packet['tcp']['d_port'] == 4506):\n          if (('SYN' in flags) and (len(flags) == 1)):\n             return 100\n          elif ('FIN' in flags):\n             return 120\n       else:\n          return None\n    ------------------------ declaration ----------------------------------\n    def filter_new_cons(packet):\n     'filter packets by there tcp-state and\n     returns codes for specific states'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       keys = []\n       for i in request['item']:\n          if ('MemcacheSetRequest_Item' in i):\n             key = i['MemcacheSetRequest_Item']['key']\n          else:\n             key = i['Item']['key']\n          keys.append(truncate(key))\n       return '\\n'.join(keys)\n    ------------------------ declaration ----------------------------------\n    def memcache_set(request):\n     'Pretty-format a memcache.set() request.\n     Arguments:\n     request - The memcache.set() request object, e.g.,\n     {\\'item\\': [{\\'Item\\': {\\'flags\\': \\'0L\\', \\'key\\': \\'memcache_key\\' ...\n     Returns:\n     The keys of the memcache.get() response as a string. If there are\n     multiple keys, they are separated by newline characters.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       if isinstance(tck, BSpline):\n          return tck.antiderivative(n)\n       else:\n          return _impl.splantider(tck, n)\n    ------------------------ declaration ----------------------------------\n    def splantider(tck, n=1):\n     'Compute the spline for the antiderivative (integral) of a given spline.\n     Parameters\n     tck : BSpline instance or a tuple of (t, c, k)\n     Spline whose antiderivative to compute\n     n : int, optional\n     Order of antiderivative to evaluate. Default: 1\n     Returns\n     BSpline instance or a tuple of (t2, c2, k2)\n     Spline of order k2=k+n representing the antiderivative of the input\n     spline.\n     A tuple is returned iff the input argument `tck` is a tuple, otherwise\n     a BSpline object is constructed and returned.\n     See Also\n     splder, splev, spalde\n     BSpline\n     Notes\n     The `splder` function is the inverse operation of this function.\n     Namely, ``splder(splantider(tck))`` is identical to `tck`, modulo\n     rounding error.\n     .. versionadded:: 0.13.0\n     Examples\n     >>> from scipy.interpolate import splrep, splder, splantider, splev\n     >>> x = np.linspace(0, np.pi/2, 70)\n     >>> y = 1 / np.sqrt(1 - 0.8*np.sin(x)**2)\n     >>> spl = splrep(x, y)\n     The derivative is the inverse operation of the antiderivative,\n     although some floating point error accumulates:\n     >>> splev(1.7, spl), splev(1.7, splder(splantider(spl)))\n     (array(2.1565429877197317), array(2.1565429877201865))\n     Antiderivative can be used to evaluate definite integrals:\n     >>> ispl = splantider(spl)\n     >>> splev(np.pi/2, ispl) - splev(0, ispl)\n     2.2572053588768486\n     This is indeed an approximation to the complete elliptic integral\n     :math:`K(m) = \\int_0^{\\pi/2} [1 - m\\sin^2 x]^{-1/2} dx`:\n     >>> from scipy.special import ellipk\n     >>> ellipk(0.8)\n     2.2572053268208538'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       if tag:\n          return tag(context, objects)\n       request = context['request']\n       response_format = 'html'\n       if ('response_format' in context):\n          response_format = context['response_format']\n       return Markup(render_to_string('core/tags/generic_list', {'objects': objects, 'skip_group': skip_group}, context_instance=RequestContext(request), response_format=response_format))\n    ------------------------ declaration ----------------------------------\n    @contextfunction\n     def core_generic_list(context, objects, skip_group=False, tag=None):\n     'Print a list of objects'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       if pf_interface:\n          return ('/sys/bus/pci/devices/%s/physfn/net' % pci_addr)\n       return ('/sys/bus/pci/devices/%s/net' % pci_addr)\n    ------------------------ declaration ----------------------------------\n    def _get_sysfs_netdev_path(pci_addr, pf_interface):\n     'Get the sysfs path based on the PCI address of the device.\n     Assumes a networking device - will not check for the existence of the path.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       t = desc.type\n       if unpacker_coercions.has_key(t):\n          desc = desc.AECoerceDesc(unpacker_coercions[t])\n          t = desc.type\n       if (t == typeAEList):\n          l = []\n          for i in range(desc.AECountItems()):\n             (keyword, item) = desc.AEGetNthDesc((i + 1), '****')\n             l.append(unpack(item, formodulename))\n          return l\n       if (t == typeAERecord):\n          d = {}\n          for i in range(desc.AECountItems()):\n             (keyword, item) = desc.AEGetNthDesc((i + 1), '****')\n             d[keyword] = unpack(item, formodulename)\n          return d\n       if (t == typeAEText):\n          record = desc.AECoerceDesc('reco')\n          return mkaetext(unpack(record, formodulename))\n       if (t == typeAlias):\n          return Carbon.File.Alias(rawdata=desc.data)\n       if (t == typeBoolean):\n          return struct.unpack('b', desc.data)[0]\n       if (t == typeChar):\n          return desc.data\n       if (t == typeUnicodeText):\n          return unicode(desc.data, 'utf16')\n       if (t == typeEnumeration):\n          return mkenum(desc.data)\n       if (t == typeFalse):\n          return 0\n       if (t == typeFloat):\n          data = desc.data\n          return struct.unpack('d', data)[0]\n       if (t == typeFSS):\n          return Carbon.File.FSSpec(rawdata=desc.data)\n       if (t == typeFSRef):\n          return Carbon.File.FSRef(rawdata=desc.data)\n       if (t == typeInsertionLoc):\n          record = desc.AECoerceDesc('reco')\n          return mkinsertionloc(unpack(record, formodulename))\n       if (t == typeIntlText):\n          (script, language) = struct.unpack('hh', desc.data[:4])\n          return aetypes.IntlText(script, language, desc.data[4:])\n       if (t == typeIntlWritingCode):\n          (script, language) = struct.unpack('hh', desc.data)\n          return aetypes.IntlWritingCode(script, language)\n       if (t == typeKeyword):\n          return mkkeyword(desc.data)\n       if (t == typeLongInteger):\n          return struct.unpack('l', desc.data)[0]\n       if (t == typeLongDateTime):\n          (a, b) = struct.unpack('lL', desc.data)\n          return ((long(a) << 32) + b)\n       if (t == typeNull):\n          return None\n       if (t == typeMagnitude):\n          v = struct.unpack('l', desc.data)\n          if (v < 0):\n             v = (4294967296L + v)\n          return v\n       if (t == typeObjectSpecifier):\n          record = desc.AECoerceDesc('reco')\n          if formodulename:\n             return mkobjectfrommodule(unpack(record, formodulename), formodulename)\n          return mkobject(unpack(record, formodulename))\n       if (t == typeQDPoint):\n          (v, h) = struct.unpack('hh', desc.data)\n          return aetypes.QDPoint(v, h)\n       if (t == typeQDRectangle):\n          (v0, h0, v1, h1) = struct.unpack('hhhh', desc.data)\n          return aetypes.QDRectangle(v0, h0, v1, h1)\n       if (t == typeRGBColor):\n          (r, g, b) = struct.unpack('hhh', desc.data)\n          return aetypes.RGBColor(r, g, b)\n       if (t == typeShortFloat):\n          return struct.unpack('f', desc.data)[0]\n       if (t == typeShortInteger):\n          return struct.unpack('h', desc.data)[0]\n       if (t == typeTargetID):\n          return mktargetid(desc.data)\n       if (t == typeTrue):\n          return 1\n       if (t == typeType):\n          return mktype(desc.data, formodulename)\n       if (t == 'rang'):\n          record = desc.AECoerceDesc('reco')\n          return mkrange(unpack(record, formodulename))\n       if (t == 'cmpd'):\n          record = desc.AECoerceDesc('reco')\n          return mkcomparison(unpack(record, formodulename))\n       if (t == 'logi'):\n          record = desc.AECoerceDesc('reco')\n          return mklogical(unpack(record, formodulename))\n       return mkunknown(desc.type, desc.data)\n    ------------------------ declaration ----------------------------------\n    def unpack(desc, formodulename=''):\n     'Unpack an AE descriptor to a python object'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       return [transl[l] for l in labels]\n    ------------------------ declaration ----------------------------------\n    def convert_labels(labels, transl):\n     'Convert between strings and numbers.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       mask = ','.join(mask)\n       ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''}\n       if __opts__['test']:\n          status = _check_cron(user, path, mask, cmd)\n          ret['result'] = None\n          if (status == 'absent'):\n             ret['result'] = True\n             ret['comment'] = 'Incron   {0}   is   absent'.format(name)\n          elif ((status == 'present') or (status == 'update')):\n             ret['comment'] = 'Incron   {0}   is   set   to   be   removed'.format(name)\n          return ret\n       data = __salt__['incron.rm_job'](user=user, path=path, mask=mask, cmd=cmd)\n       if (data == 'absent'):\n          ret['comment'] = 'Incron   {0}   already   absent'.format(name)\n          return ret\n       if (data == 'removed'):\n          ret['comment'] = \"Incron   {0}   removed   from   {1}'s   crontab\".format(name, user)\n          ret['changes'] = {user: name}\n          return ret\n       ret['comment'] = 'Incron   {0}   for   user   {1}   failed   to   commit   with   error   {2}'.format(name, user, data)\n       ret['result'] = False\n       return ret\n    ------------------------ declaration ----------------------------------\n    def absent(name, path, mask, cmd, user='root'):\n     'Verifies that the specified incron job is absent for the specified user; only\n     the name is matched when removing a incron job.\n     name\n     Unique comment describing the entry\n     path\n     The path that should be watched\n     user\n     The name of the user who\\'s crontab needs to be modified, defaults to\n     the root user\n     mask\n     The mask of events that should be monitored for\n     cmd\n     The cmd that should be executed'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       return _list_users()\n    ------------------------ declaration ----------------------------------\n    @blueprint.route('/users')\n     def list_all_users():\n     'Return a list of all known user names.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       import inspect\n       if isinstance(frame, six.string_types):\n          frame_names = frame_transform_graph.get_names()\n          if (frame not in frame_names):\n             raise ValueError(u'Coordinate   frame   {0}   not   in   allowed   values   {1}'.format(frame, sorted(frame_names)))\n          frame_cls = frame_transform_graph.lookup_name(frame)\n       elif (inspect.isclass(frame) and issubclass(frame, BaseCoordinateFrame)):\n          frame_cls = frame\n       else:\n          raise ValueError(u'Coordinate   frame   must   be   a   frame   name   or   frame   class')\n       return frame_cls\n    ------------------------ declaration ----------------------------------\n    def _get_frame_class(frame):\n     'Get a frame class from the input `frame`, which could be a frame name\n     string, or frame class.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       while u:\n          f = dmp_TC(f, K)\n          u -= 1\n       return dup_TC(f, K)\n    ------------------------ declaration ----------------------------------\n    def dmp_ground_TC(f, u, K):\n     'Return the ground trailing coefficient.\n     Examples\n     >>> from sympy.polys.domains import ZZ\n     >>> from sympy.polys.densebasic import dmp_ground_TC\n     >>> f = ZZ.map([[[1], [2, 3]]])\n     >>> dmp_ground_TC(f, 2, ZZ)\n     3'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       cur_chromosome = BasicChromosome.Chromosome(chr_name)\n       num_segments = random.randrange(num_possible_segments)\n       for seg in range(num_segments):\n          if (seg == 0):\n             cur_segment = BasicChromosome.TelomereSegment()\n          elif (seg == (num_segments - 1)):\n             cur_segment = BasicChromosome.TelomereSegment(1)\n          else:\n             cur_segment = BasicChromosome.ChromosomeSegment()\n          color_chance = random.random()\n          if (color_chance <= color_prob):\n             fill_color = random.choice(color_choices)\n             cur_segment.fill_color = fill_color\n          id_chance = random.random()\n          if (id_chance <= id_prob):\n             id = get_random_id()\n             cur_segment.label = id\n          cur_chromosome.add(cur_segment)\n       return (cur_chromosome, num_segments)\n    ------------------------ declaration ----------------------------------\n    def load_random_chromosome(chr_name):\n     'Generate a chromosome with random information about it.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       imdb = datasets.pascal_voc(split, year)\n       imdb.roidb_handler = imdb.selective_search_IJCV_roidb\n       imdb.config['top_k'] = top_k\n       return imdb\n    ------------------------ declaration ----------------------------------\n    def _selective_search_IJCV_top_k(split, year, top_k):\n     'Return an imdb that uses the top k proposals from the selective search\n     IJCV code.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       if opts['file_ignore_regex']:\n          for regex in opts['file_ignore_regex']:\n             if re.search(regex, fname):\n                log.debug('File   matching   file_ignore_regex.   Skipping:   {0}'.format(fname))\n                return True\n       if opts['file_ignore_glob']:\n          for glob in opts['file_ignore_glob']:\n             if fnmatch.fnmatch(fname, glob):\n                log.debug('File   matching   file_ignore_glob.   Skipping:   {0}'.format(fname))\n                return True\n       return False\n    ------------------------ declaration ----------------------------------\n    def is_file_ignored(opts, fname):\n     'If file_ignore_regex or file_ignore_glob were given in config,\n     compare the given file path against all of them and return True\n     on the first match.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       msg = u'{0}   Assuming   UT1-UTC=0   for   coordinate   transformations.'\n       warnings.warn(msg.format(ierserr.args[0]), AstropyWarning)\n    ------------------------ declaration ----------------------------------\n    def _warn_iers(ierserr):\n     'Generate a warning for an IERSRangeerror\n     Parameters\n     ierserr : An `~astropy.utils.iers.IERSRangeError`'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       axis = _normalize_axis(axis, ndim(x))\n       if (x.dtype.base_dtype == tf.bool):\n          x = tf.cast(x, floatx())\n       return tf.reduce_mean(x, reduction_indices=axis, keep_dims=keepdims)\n    ------------------------ declaration ----------------------------------\n    def mean(x, axis=None, keepdims=False):\n     'Mean of a tensor, alongside the specified axis.\n     # Arguments\n     x: A tensor or variable.\n     axis: A list of integer. Axes to compute the mean.\n     keepdims: A boolean, whether to keep the dimensions or not.\n     If `keepdims` is `False`, the rank of the tensor is reduced\n     by 1 for each entry in `axis`. If `keep_dims` is `True`,\n     the reduced dimensions are retained with length 1.\n     # Returns\n     A tensor with the mean of elements of `x`.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       src_from = _ensure_src(src_from)\n       subject_from = _ensure_src_subject(src_from, subject_from)\n       subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)\n       src_out = list()\n       for fro in src_from:\n          (hemi, idx, id_) = _get_hemi(fro)\n          to = op.join(subjects_dir, subject_to, 'surf', ('%s.%s' % (hemi, surf)))\n          logger.info(('Reading   destination   surface   %s' % (to,)))\n          to = read_surface(to, return_dict=True, verbose=False)[(-1)]\n          complete_surface_info(to, copy=False)\n          best = _get_vertex_map_nn(fro, subject_from, subject_to, hemi, subjects_dir, to['neighbor_tri'])\n          for key in ('neighbor_tri', 'tri_area', 'tri_cent', 'tri_nn', 'use_tris'):\n             del to[key]\n          to['vertno'] = np.sort(best[fro['vertno']])\n          to['inuse'] = np.zeros(len(to['rr']), int)\n          to['inuse'][to['vertno']] = True\n          to['use_tris'] = best[fro['use_tris']]\n          to.update(nuse=len(to['vertno']), nuse_tri=len(to['use_tris']), nearest=None, nearest_dist=None, patch_inds=None, pinfo=None, dist=None, id=id_, dist_limit=None, type='surf', coord_frame=FIFF.FIFFV_COORD_MRI, subject_his_id=subject_to, rr=(to['rr'] / 1000.0))\n          src_out.append(to)\n          logger.info('[done]\\n')\n       info = dict(working_dir=os.getcwd(), command_line=_get_call_line(in_verbose=True))\n       return SourceSpaces(src_out, info=info)\n    ------------------------ declaration ----------------------------------\n    @verbose\n     def morph_source_spaces(src_from, subject_to, surf='white', subject_from=None, subjects_dir=None, verbose=None):\n     'Morph an existing source space to a different subject.\n     .. warning:: This can be used in place of morphing source estimates for\n     multiple subjects, but there may be consequences in terms\n     of dipole topology.\n     Parameters\n     src_from : instance of SourceSpaces\n     Surface source spaces to morph.\n     subject_to : str\n     The destination subject.\n     surf : str\n     The brain surface to use for the new source space.\n     subject_from : str | None\n     The \"from\" subject. For most source spaces this shouldn\\'t need\n     to be provided, since it is stored in the source space itself.\n     subjects_dir : string, or None\n     Path to SUBJECTS_DIR if it is not set in the environment.\n     verbose : bool, str, int, or None\n     If not None, override default verbose level (see :func:`mne.verbose`\n     and :ref:`Logging documentation <tut_logging>` for more).\n     Returns\n     src : instance of SourceSpaces\n     The morphed source spaces.\n     Notes\n     .. versionadded:: 0.10.0'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       encoding = kwds.get('encoding', None)\n       if (encoding is not None):\n          encoding = re.sub('_', '-', encoding).lower()\n          kwds['encoding'] = encoding\n       compression = kwds.get('compression')\n       compression = _infer_compression(filepath_or_buffer, compression)\n       (filepath_or_buffer, _, compression) = get_filepath_or_buffer(filepath_or_buffer, encoding, compression)\n       kwds['compression'] = compression\n       if (kwds.get('date_parser', None) is not None):\n          if isinstance(kwds['parse_dates'], bool):\n             kwds['parse_dates'] = True\n       iterator = kwds.get('iterator', False)\n       chunksize = kwds.get('chunksize', None)\n       nrows = _validate_nrows(kwds.pop('nrows', None))\n       parser = TextFileReader(filepath_or_buffer, **kwds)\n       if ((nrows is not None) and (chunksize is not None)):\n          raise NotImplementedError(\"'nrows'   and   'chunksize'   cannot   be   used   together   yet.\")\n       elif (nrows is not None):\n          try:\n             data = parser.read(nrows)\n          finally:\n             parser.close()\n          return data\n       elif (chunksize or iterator):\n          return parser\n       try:\n          data = parser.read()\n       finally:\n          parser.close()\n       return data\n    ------------------------ declaration ----------------------------------\n    def _read(filepath_or_buffer, kwds):\n     'Generic reader of line files.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       (tags, noserver) = read_etag_file(options)\n       if (noserver and (not options.noserver)):\n          options.noserver = noserver\n       m = re.match('(?:W/)?\"?(.*)\"?$', options.etag)\n       if m:\n          options.etag = m.group(1)\n       etag = options.etag\n       if (etag in tags):\n          print ('Found   etag   [%s]   for   version   %s' % (etag, tags[etag][0]['version']))\n          return tags[etag]\n       short = etag[etag.index('-'):]\n       for t in tags:\n          if (t.find(short) != (-1)):\n             print ('Partial   ETag   match:   [%s],[%s]   for   version   %s' % (etag, t, tags[t][0]['version']))\n             return tags[t]\n       return None\n    ------------------------ declaration ----------------------------------\n    def get_details_for_etag(options):\n     'Get the stack address for a specific ETag from the configuration file.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       if (get_configured_provider() is False):\n          return False\n       if (get_dependencies() is False):\n          return False\n       for (provider, details) in six.iteritems(__opts__['providers']):\n          if ('dimensiondata' not in details):\n             continue\n       return __virtualname__\n    ------------------------ declaration ----------------------------------\n    def __virtual__():\n     'Set up the libcloud functions and check for dimensiondata configurations.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       R = p.ring\n       n = R.gens.index(x)\n       p1 = R.zero\n       mn = ([0] * R.ngens)\n       mn[n] = 1\n       mn = tuple(mn)\n       for expv in p:\n          if expv[n]:\n             e = monomial_ldiv(expv, mn)\n             p1[e] = (p[expv] * expv[n])\n       return p1\n    ------------------------ declaration ----------------------------------\n    def rs_diff(p, x):\n     'Return partial derivative of ``p`` with respect to ``x``.\n     Parameters\n     x : :class:`PolyElement` with respect to which ``p`` is differentiated.\n     Examples\n     >>> from sympy.polys.domains import QQ\n     >>> from sympy.polys.rings import ring\n     >>> from sympy.polys.ring_series import rs_diff\n     >>> R, x, y = ring(\\'x, y\\', QQ)\n     >>> p = x + x**2*y**3\n     >>> rs_diff(p, x)\n     2*x*y**3 + 1'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       if (pkg in _bootstrapped):\n          return []\n       m = rospack.get_manifest(pkg)\n       if m.is_catkin:\n          _bootstrapped.append(pkg)\n          return []\n       packages = get_depends(pkg, rospack)\n       packages.append(pkg)\n       paths = []\n       try:\n          for p in packages:\n             m = rospack.get_manifest(p)\n             d = rospack.get_path(p)\n             _append_package_paths(m, paths, d)\n             _bootstrapped.append(p)\n       except:\n          if (pkg in _bootstrapped):\n             _bootstrapped.remove(pkg)\n          raise\n       return paths\n    ------------------------ declaration ----------------------------------\n    def _generate_python_path(pkg, rospack):\n     'Recursive subroutine for building dependency list and python path\n     :raises: :exc:`rospkg.ResourceNotFound` If an error occurs while attempting to load package or dependencies'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       (procs, pipes) = launch_tails(follow_paths, lastlines_dirpath)\n       while pipes:\n          (lines, bad_pipes) = poll_tail_pipes(pipes, lastlines_dirpath, waitsecs)\n          for bad in bad_pipes:\n             pipes.pop(bad)\n          try:\n             outstream.writelines((['\\n'] + lines))\n             outstream.flush()\n          except (IOError, OSError) as e:\n             break\n       snuff(procs.values())\n    ------------------------ declaration ----------------------------------\n    def follow_files(follow_paths, outstream, lastlines_dirpath=None, waitsecs=5):\n     'Launch tail on a set of files and merge their output into outstream.\n     Args:\n     follow_paths: list; Local paths to launch tail on.\n     outstream: file; Output stream to write aggregated lines to.\n     lastlines_dirpath: Local dirpath to record last lines seen in.\n     waitsecs: int; Timeout for poll_tail_pipes.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       if (not isinstance(data, list)):\n          raise errors.AnsibleFilterError('|failed   expects   to   filter   on   a   list')\n       if (not isinstance(keys, list)):\n          raise errors.AnsibleFilterError('|failed   expects   first   param   is   a   list')\n       retval = [oo_select_keys(item, keys) for item in data]\n       return oo_flatten(retval)\n    ------------------------ declaration ----------------------------------\n    def oo_select_keys_from_list(data, keys):\n     'This returns a list, which contains the value portions for the keys\n     Ex: data = { \\'a\\':1, \\'b\\':2, \\'c\\':3 }\n     keys = [\\'a\\', \\'c\\']\n     returns [1, 3]'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       user = urllib.unquote(user)\n       sys.stderr.write((((('checking   permissions   for   user   ' + user) + '   on   api   ') + api_name) + '\\n'))\n       secret_file = open('/etc/appscale/secret.key', 'r')\n       secret = secret_file.read()\n       secret = secret[0:(-1)]\n       secret_file.close()\n       uaserver_file = open('/etc/appscale/hypersoap', 'r')\n       uaserver = uaserver_file.read()\n       uaserver_file.close()\n       server = SOAPpy.SOAPProxy((('https://' + uaserver) + ':4343'))\n       capabilities = server.get_capabilities(user, secret)\n       if (not isinstance(capabilities, str)):\n          return False\n       capabilities = capabilities.split(':')\n       sys.stderr.write((((('user   ' + user) + '   has   the   following   capabilities:   ') + str(capabilities)) + '\\n'))\n       if (api_name in capabilities):\n          return True\n       else:\n          return False\n    ------------------------ declaration ----------------------------------\n    def is_user_capable(user, api_name):\n     'Checks to see if the given user has access to user a particular API.\n     Args:\n     user: The current user email\n     api_name: The API we\\'re checking to see if the user has permission\n     Returns:\n     True is capable, False otherwise'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       if any([getattr(c.op, 'check_input', config.check_input) for (c, _) in r.clients if (not isinstance(c, string_types))]):\n          if any([getattr(c.op, 'check_broadcast', True) for (c, _) in r.clients if (not isinstance(c, string_types))]):\n             c_extract = r.type.c_extract(name, sub, True)\n          else:\n             try:\n                c_extract = r.type.c_extract(name, sub, True, check_broadcast=False)\n             except TypeError as e:\n                c_extract = r.type.c_extract(name, sub, True)\n       else:\n          c_extract = r.type.c_extract(name, sub, False)\n       pre = ('\\n            py_%(name)s   =   PyList_GET_ITEM(storage_%(name)s,   0);\\n            {Py_XINCREF(py_%(name)s);}\\n            ' % locals())\n       return (pre + c_extract)\n    ------------------------ declaration ----------------------------------\n    def get_c_extract(r, name, sub):\n     'Wrapper around c_extract that initializes py_name from storage.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       return '   '.join(map(_stringify, value))\n    ------------------------ declaration ----------------------------------\n    def _join(value):\n     'Internal function.'\n    =========================================================================\n    ------------------------ body ----------------------------------\n       ctx = zmq.Context.instance()\n       s = ctx.socket(zmq.PUSH)\n       s.connect(url)\n       print(('Producing   %s' % ident))\n       for i in range(MSGS):\n          s.send((u'%s:   %i' % (ident, time.time())).encode('utf8'))\n          time.sleep(1)\n       print(('Producer   %s   done' % ident))\n       s.close()\n    ------------------------ declaration ----------------------------------\n    def produce(url, ident):\n     'Produce messages'\n    =========================================================================\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "a3af19547310d1c969e43720870d184d260225dc", "size": 116779, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "18. Edinburg dataset check.ipynb", "max_stars_repo_name": "mjc92/JavaScriptAutoComplete", "max_stars_repo_head_hexsha": "6eed02a9f8ef084208bf45d8a81a52d86e247810", "max_stars_repo_licenses": ["CNRI-Python"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "18. Edinburg dataset check.ipynb", "max_issues_repo_name": "mjc92/JavaScriptAutoComplete", "max_issues_repo_head_hexsha": "6eed02a9f8ef084208bf45d8a81a52d86e247810", "max_issues_repo_licenses": ["CNRI-Python"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "18. Edinburg dataset check.ipynb", "max_forks_repo_name": "mjc92/JavaScriptAutoComplete", "max_forks_repo_head_hexsha": "6eed02a9f8ef084208bf45d8a81a52d86e247810", "max_forks_repo_licenses": ["CNRI-Python"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.7230552952, "max_line_length": 302, "alphanum_fraction": 0.4522045916, "converted": true, "num_tokens": 20820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10669059394565118, "lm_q2_score": 0.04813676838557257, "lm_q1q2_score": 0.0051357404096809825}}
{"text": "# Build Project and update Packges\n\n\n```python\n! pip install git+https://github.com/cohenimhuji/CohenimPy\n! pip install git+https://github.com/cohenimhuji/CohenimPy --upgrade \n```\n\n    Collecting git+https://github.com/cohenimhuji/CohenimPy\n\n      Running command git clone --filter=blob:none -q https://github.com/cohenimhuji/CohenimPy 'C:\\Users\\u30l\\AppData\\Local\\Temp\\pip-req-build-kza8dg7f'\n\n\n    \n      Cloning https://github.com/cohenimhuji/CohenimPy to c:\\users\\u30l\\appdata\\local\\temp\\pip-req-build-kza8dg7f\n      Resolved https://github.com/cohenimhuji/CohenimPy to commit 3b3ad6db5a186af0d3f483152a85767f8f913aea\n      Preparing metadata (setup.py): started\n      Preparing metadata (setup.py): finished with status 'done'\n    Requirement already satisfied: datetime in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (4.3)\n    Requirement already satisfied: IPython in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (7.30.0)\n    Requirement already satisfied: matplotlib in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (3.5.0)\n    Requirement already satisfied: numba in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (0.54.1)\n    Requirement already satisfied: numpy in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (1.20.3)\n    Requirement already satisfied: pandas in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (1.3.4)\n    Requirement already satisfied: pathlib in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (1.0.1)\n    Requirement already satisfied: pathos in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (0.2.7)\n    Requirement already satisfied: scipy in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (1.7.3)\n    Requirement already satisfied: statsmodels in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (0.13.1)\n    Requirement already satisfied: sympy in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (1.9)\n    Requirement already satisfied: pytz in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from datetime->CohenimPy==0.63) (2021.3)\n    Requirement already satisfied: zope.interface in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from datetime->CohenimPy==0.63) (5.4.0)\n    Requirement already satisfied: traitlets>=4.2 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.63) (5.1.1)\n    Requirement already satisfied: pickleshare in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.63) (0.7.5)\n    Requirement already satisfied: pygments in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.63) (2.10.0)\n    Requirement already satisfied: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.63) (3.0.22)\n    Requirement already satisfied: colorama in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.63) (0.4.4)\n    Requirement already satisfied: decorator in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.63) (5.1.0)\n    Requirement already satisfied: jedi>=0.16 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.63) (0.17.2)\n    Requirement already satisfied: backcall in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.63) (0.2.0)\n    Requirement already satisfied: setuptools>=18.5 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.63) (59.2.0)\n    Requirement already satisfied: matplotlib-inline in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.63) (0.1.3)\n    Requirement already satisfied: packaging>=20.0 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from matplotlib->CohenimPy==0.63) (21.3)\n    Requirement already satisfied: fonttools>=4.22.0 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from matplotlib->CohenimPy==0.63) (4.28.2)\n    Requirement already satisfied: cycler>=0.10 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from matplotlib->CohenimPy==0.63) (0.11.0)\n    Requirement already satisfied: pyparsing>=2.2.1 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from matplotlib->CohenimPy==0.63) (3.0.6)\n    Requirement already satisfied: python-dateutil>=2.7 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from matplotlib->CohenimPy==0.63) (2.8.2)\n    Requirement already satisfied: kiwisolver>=1.0.1 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from matplotlib->CohenimPy==0.63) (1.3.2)\n    Requirement already satisfied: pillow>=6.2.0 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from matplotlib->CohenimPy==0.63) (8.4.0)\n    Requirement already satisfied: llvmlite<0.38,>=0.37.0rc1 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from numba->CohenimPy==0.63) (0.37.0)\n    Requirement already satisfied: pox>=0.2.9 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from pathos->CohenimPy==0.63) (0.2.9)\n    Requirement already satisfied: multiprocess>=0.70.11 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from pathos->CohenimPy==0.63) (0.70.11.1)\n    Requirement already satisfied: ppft>=1.6.6.3 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from pathos->CohenimPy==0.63) (1.6.6.3)\n    Requirement already satisfied: dill>=0.3.3 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from pathos->CohenimPy==0.63) (0.3.3)\n    Requirement already satisfied: patsy>=0.5.2 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from statsmodels->CohenimPy==0.63) (0.5.2)\n    Requirement already satisfied: mpmath>=0.19 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from sympy->CohenimPy==0.63) (1.2.1)\n    Requirement already satisfied: parso<0.8.0,>=0.7.0 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from jedi>=0.16->IPython->CohenimPy==0.63) (0.7.0)\n    Requirement already satisfied: six in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from patsy>=0.5.2->statsmodels->CohenimPy==0.63) (1.16.0)\n    Requirement already satisfied: wcwidth in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->IPython->CohenimPy==0.63) (0.2.5)\n    Building wheels for collected packages: CohenimPy\n      Building wheel for CohenimPy (setup.py): started\n      Building wheel for CohenimPy (setup.py): finished with status 'done'\n      Created wheel for CohenimPy: filename=CohenimPy-0.63-py3-none-any.whl size=39383 sha256=18a5ad2555d6e8d799ca973e98d2b85a415d89fa5c3453f3fa2520d2f4a99372\n      Stored in directory: C:\\Users\\u30l\\AppData\\Local\\Temp\\pip-ephem-wheel-cache-z078_0r_\\wheels\\66\\b2\\e4\\9f7fa9a4c94f27f0989f5f58d50f8391140de276efa12d6aac\n    Successfully built CohenimPy\n    Installing collected packages: CohenimPy\n      Attempting uninstall: CohenimPy\n        Found existing installation: CohenimPy 0.62\n        Uninstalling CohenimPy-0.62:\n          Successfully uninstalled CohenimPy-0.62\n    Successfully installed CohenimPy-0.63\n    Collecting git+https://github.com/cohenimhuji/CohenimPy\n      Cloning https://github.com/cohenimhuji/CohenimPy to c:\\users\\u30l\\appdata\\local\\temp\\pip-req-build-vz4druez\n      Resolved https://github.com/cohenimhuji/CohenimPy to commit 3b3ad6db5a186af0d3f483152a85767f8f913aea\n      Preparing metadata (setup.py): started\n      Preparing metadata (setup.py): finished with status 'done'\n    Requirement already satisfied: datetime in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (4.3)\n    Requirement already satisfied: IPython in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (7.30.0)\n    Requirement already satisfied: matplotlib in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (3.5.0)\n    Requirement already satisfied: numba in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (0.54.1)\n    Requirement already satisfied: numpy in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (1.20.3)\n    Requirement already satisfied: pandas in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (1.3.4)\n    Requirement already satisfied: pathlib in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (1.0.1)\n    Requirement already satisfied: pathos in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (0.2.7)\n    Requirement already satisfied: scipy in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (1.7.3)\n    Requirement already satisfied: statsmodels in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (0.13.1)\n    Requirement already satisfied: sympy in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.63) (1.9)\n    Requirement already satisfied: pytz in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from datetime->CohenimPy==0.63) (2021.3)\n    Requirement already satisfied: zope.interface in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from datetime->CohenimPy==0.63) (5.4.0)\n    Requirement already satisfied: decorator in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.63) (5.1.0)\n    Requirement already satisfied: jedi>=0.16 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.63) (0.17.2)\n    Requirement already satisfied: traitlets>=4.2 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.63) (5.1.1)\n    Requirement already satisfied: matplotlib-inline in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.63) (0.1.3)\n    Requirement already satisfied: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.63) (3.0.22)\n    Requirement already satisfied: backcall in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.63) (0.2.0)\n    Requirement already satisfied: colorama in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.63) (0.4.4)\n    Requirement already satisfied: setuptools>=18.5 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.63) (59.2.0)\n    Requirement already satisfied: pygments in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.63) (2.10.0)\n    Requirement already satisfied: pickleshare in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.63) (0.7.5)\n    Requirement already satisfied: fonttools>=4.22.0 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from matplotlib->CohenimPy==0.63) (4.28.2)\n    Requirement already satisfied: packaging>=20.0 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from matplotlib->CohenimPy==0.63) (21.3)\n    Requirement already satisfied: pillow>=6.2.0 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from matplotlib->CohenimPy==0.63) (8.4.0)\n    Requirement already satisfied: pyparsing>=2.2.1 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from matplotlib->CohenimPy==0.63) (3.0.6)\n    Requirement already satisfied: python-dateutil>=2.7 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from matplotlib->CohenimPy==0.63) (2.8.2)\n    Requirement already satisfied: cycler>=0.10 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from matplotlib->CohenimPy==0.63) (0.11.0)\n\n      Running command git clone --filter=blob:none -q https://github.com/cohenimhuji/CohenimPy 'C:\\Users\\u30l\\AppData\\Local\\Temp\\pip-req-build-vz4druez'\n\n\n    \n    Requirement already satisfied: kiwisolver>=1.0.1 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from matplotlib->CohenimPy==0.63) (1.3.2)\n    Requirement already satisfied: llvmlite<0.38,>=0.37.0rc1 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from numba->CohenimPy==0.63) (0.37.0)\n    Requirement already satisfied: dill>=0.3.3 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from pathos->CohenimPy==0.63) (0.3.3)\n    Requirement already satisfied: pox>=0.2.9 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from pathos->CohenimPy==0.63) (0.2.9)\n    Requirement already satisfied: multiprocess>=0.70.11 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from pathos->CohenimPy==0.63) (0.70.11.1)\n    Requirement already satisfied: ppft>=1.6.6.3 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from pathos->CohenimPy==0.63) (1.6.6.3)\n    Requirement already satisfied: patsy>=0.5.2 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from statsmodels->CohenimPy==0.63) (0.5.2)\n    Requirement already satisfied: mpmath>=0.19 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from sympy->CohenimPy==0.63) (1.2.1)\n    Requirement already satisfied: parso<0.8.0,>=0.7.0 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from jedi>=0.16->IPython->CohenimPy==0.63) (0.7.0)\n    Requirement already satisfied: six in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from patsy>=0.5.2->statsmodels->CohenimPy==0.63) (1.16.0)\n    Requirement already satisfied: wcwidth in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->IPython->CohenimPy==0.63) (0.2.5)\n\n\n\n```python\n## Using Jupter and Spyder\\Atom Together\n## https://medium.com/@rrfd/cookiecutter-data-science-organize-your-projects-atom-and-jupyter-2be7862f487e\n%load_ext autoreload\n%autoreload 2\n%matplotlib inline\n```\n\n\n```python\nthis_project_path = 'c:\\\\Users\\\\u30l\\\\GitHub\\\\CohenimTools'\nthis_NB_path = this_project_path+'\\\\CohenimPy'\nimport os\ncurrent_NB_path = os.path.abspath(os.getcwd())\nif this_NB_path !=  current_NB_path:\n    print('WARRNING: NOT CORRECT Notebook PATH !')\nos.chdir(this_NB_path)\n```\n\n\n```python\n## https://medium.com/@rrfd/cookiecutter-data-science-organize-your-projects-atom-and-jupyter-2be7862f487e :\n# Link ./src/ with your notebook\n# Run this in the project root\nos.chdir(this_project_path)\n! pip3 install --editable .\nos.chdir(this_NB_path)\n```\n\n    Obtaining file:///C:/Users/u30l/GitHub/CohenimTools\n      Preparing metadata (setup.py): started\n      Preparing metadata (setup.py): finished with status 'done'\n    Requirement already satisfied: datetime in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.59) (4.3)\n    Requirement already satisfied: IPython in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.59) (7.30.0)\n    Requirement already satisfied: matplotlib in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.59) (3.5.0)\n    Requirement already satisfied: numba in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.59) (0.54.1)\n    Requirement already satisfied: numpy in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.59) (1.20.3)\n    Requirement already satisfied: pandas in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.59) (1.3.4)\n    Requirement already satisfied: pathlib in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.59) (1.0.1)\n    Requirement already satisfied: pathos in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.59) (0.2.7)\n    Requirement already satisfied: scipy in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.59) (1.7.3)\n    Requirement already satisfied: statsmodels in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.59) (0.13.1)\n    Requirement already satisfied: sympy in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from CohenimPy==0.59) (1.9)\n    Requirement already satisfied: zope.interface in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from datetime->CohenimPy==0.59) (5.4.0)\n    Requirement already satisfied: pytz in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from datetime->CohenimPy==0.59) (2021.3)\n    Requirement already satisfied: jedi>=0.16 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.59) (0.17.2)\n    Requirement already satisfied: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.59) (3.0.22)\n    Requirement already satisfied: colorama in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.59) (0.4.4)\n    Requirement already satisfied: setuptools>=18.5 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.59) (59.2.0)\n    Requirement already satisfied: pickleshare in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.59) (0.7.5)\n    Requirement already satisfied: traitlets>=4.2 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.59) (5.1.1)\n    Requirement already satisfied: backcall in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.59) (0.2.0)\n    Requirement already satisfied: matplotlib-inline in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.59) (0.1.3)\n    Requirement already satisfied: pygments in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.59) (2.10.0)\n    Requirement already satisfied: decorator in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from IPython->CohenimPy==0.59) (5.1.0)\n    Requirement already satisfied: fonttools>=4.22.0 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from matplotlib->CohenimPy==0.59) (4.28.2)\n    Requirement already satisfied: pillow>=6.2.0 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from matplotlib->CohenimPy==0.59) (8.4.0)\n    Requirement already satisfied: pyparsing>=2.2.1 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from matplotlib->CohenimPy==0.59) (3.0.6)\n    Requirement already satisfied: packaging>=20.0 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from matplotlib->CohenimPy==0.59) (21.3)\n    Requirement already satisfied: python-dateutil>=2.7 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from matplotlib->CohenimPy==0.59) (2.8.2)\n    Requirement already satisfied: kiwisolver>=1.0.1 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from matplotlib->CohenimPy==0.59) (1.3.2)\n    Requirement already satisfied: cycler>=0.10 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from matplotlib->CohenimPy==0.59) (0.11.0)\n    Requirement already satisfied: llvmlite<0.38,>=0.37.0rc1 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from numba->CohenimPy==0.59) (0.37.0)\n    Requirement already satisfied: pox>=0.2.9 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from pathos->CohenimPy==0.59) (0.2.9)\n    Requirement already satisfied: multiprocess>=0.70.11 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from pathos->CohenimPy==0.59) (0.70.11.1)\n    Requirement already satisfied: ppft>=1.6.6.3 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from pathos->CohenimPy==0.59) (1.6.6.3)\n    Requirement already satisfied: dill>=0.3.3 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from pathos->CohenimPy==0.59) (0.3.3)\n    Requirement already satisfied: patsy>=0.5.2 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from statsmodels->CohenimPy==0.59) (0.5.2)\n    Requirement already satisfied: mpmath>=0.19 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from sympy->CohenimPy==0.59) (1.2.1)\n    Requirement already satisfied: parso<0.8.0,>=0.7.0 in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from jedi>=0.16->IPython->CohenimPy==0.59) (0.7.0)\n    Requirement already satisfied: six in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from patsy>=0.5.2->statsmodels->CohenimPy==0.59) (1.16.0)\n    Requirement already satisfied: wcwidth in c:\\users\\u30l\\anaconda3\\lib\\site-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->IPython->CohenimPy==0.59) (0.2.5)\n    Installing collected packages: CohenimPy\n      Attempting uninstall: CohenimPy\n        Found existing installation: CohenimPy 0.59\n        Uninstalling CohenimPy-0.59:\n          Successfully uninstalled CohenimPy-0.59\n      Running setup.py develop for CohenimPy\n    Successfully installed CohenimPy-0.59\n\n\n\n```python\nimport pkg_resources  # part of setuptools\nversion = pkg_resources.require(\"CohenimPy\")[0].version\nprint('CohenimPy version is:',version)\n```\n\n    CohenimPy version is: 0.5\n\n\n\n```python\n# my functions and oter iports\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom CohenimPy import ncDate, ncStat\nfrom CohenimPy.ncDate import period\nfrom CohenimPy.ncStat import ols_fit,regs_plot\nimport CohenimPy.ncPlot as ncPlot\nncPlot.printVersion()\nfrom CohenimPy.ncPlot import multi_save, add_Rec, plot1ax, plot2axs, colors\nimport CohenimPy.ncPublish as ncPub\n```\n\n    CohenimPy version is: 0.5\n\n\n\n```python\n# %% Set Project Configuraion\n# %% shold be after importing: CohenimPy.ncPlot\nimport config\nfile_date = config.file_date\n\n# very importent - get Project Main Path\nconfig_project_path = config.project_path\nprint('src config  project path is:     '+str(config_project_path))\n\nif  this_project_path!= str(config_project_path):\n    print('WARRNING: NOT CORRECT PROJECT PATH !')\n\nprint('This project path is:     '+str(this_project_path))\nprint('Current Notebook path is: '+str(current_NB_path))\n```\n\n    src config  project path is:     c:\\Users\\u30l\\GitHub\\CohenimTools\n    This project path is:     c:\\Users\\u30l\\GitHub\\CohenimTools\n    Current Notebook path is: c:\\Users\\u30l\\GitHub\\CohenimTools\\CohenimPy\n\n", "meta": {"hexsha": "2f3dd8a7ed1757dc55873ebc6b16cb3c649055bc", "size": 25800, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "CohenimPy/Build_n_Update_Pckges.ipynb", "max_stars_repo_name": "cohenimhuji/CohenimTools", "max_stars_repo_head_hexsha": "d0e7790173d383a2abd405853a323338d888c5d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CohenimPy/Build_n_Update_Pckges.ipynb", "max_issues_repo_name": "cohenimhuji/CohenimTools", "max_issues_repo_head_hexsha": "d0e7790173d383a2abd405853a323338d888c5d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CohenimPy/Build_n_Update_Pckges.ipynb", "max_forks_repo_name": "cohenimhuji/CohenimTools", "max_forks_repo_head_hexsha": "d0e7790173d383a2abd405853a323338d888c5d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 65.4822335025, "max_line_length": 185, "alphanum_fraction": 0.6594186047, "converted": true, "num_tokens": 7035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13296422989056964, "lm_q2_score": 0.03846618788475609, "lm_q1q2_score": 0.005114627048922553}}
{"text": "# [EX1] Data collection\n\n## 1.1 Get the list of animes\n\n\n### Libraries\n\n\n```python\n# core libraries\nimport requests\nfrom bs4 import BeautifulSoup\n\n# for better time view \nfrom tqdm import tqdm\n```\n\n### Creating the anime_url.txt file\n\nWe are creating a file called \"anime.txt\" conteining the url of each anime in the 400 pages (actually 383) of the top anime rank list of the MyAnimeList site. \n\n* We initialize a filename and then we are doing a for loop over the 400 pages. If the url \"exist\" so the response == 200 and we can collect the 50 url in that page, otherwise if the response == 400, the page doesn't exist and we exit from the loop, no more interest in continue to loop (no anime url to collect).\n\n* The url scrabbing consist on using BeautifulSoup to inspect the whole html page to find where the url of the anime are. In particolar under the < tr>..< /tr> and < a>..< /a> we can view all the link in the pages. Moreover the anime url are associated with an \"id=#areaXXX\" class. We get there and gather the right link.\n```\n<a href=\"https://myanimelist.net/anime/5114/Fullmetal_Alchemist__Brotherhood\" id=\"#area5114\" rel=\"#info5114\">Fullmetal Alchemist: Brotherhood</a>\n```\n\n\n\n```python\nfilename = r\"./anime_url.txt\"\nwith open(filename,'w', encoding='utf-8') as f:\n    for page in tqdm(range(0, 400)):\n        url = \"https://myanimelist.net/topanime.php?limit=\"+str(page*50)\n        response = requests.get(url)\n        if response.status_code == 200:\n            soup = BeautifulSoup(response.text, \"html.parser\")\n            for tag in soup.find_all(\"tr\"):\n                links = tag.find_all(\"a\")\n                for link in links:\n                    if type(link.get(\"id\")) == str and len(link.contents[0]) > 1:\n                        f.write(link.get(\"href\"))\n                        f.write(\"\\n\")\n        else:\n            print(\"End with page count: \", page)\n            break\n```\n\n     96%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c   | 383/400 [05:02<00:13,  1.27it/s]\n\n    End with page count:  383\n\n\n    \n\n\n## 1.2 Crawl animes\n\nWe now need to collect for each anime the html and store it in a .html file. The anime needs to follow the ranking page of the MyAnimeList, i.e 50 anime for page.\n\nFor this we begin to create a list called \"lines\" that store all the link of the anime. We use this method instead of open directly the .txt file in for loop to split the crawl part among the group.\n\n\n```python\nfilename = r\"./anime_url.txt\"\n\nlines = []\nwith open(filename, \"r\", encoding='utf-8') as f:\n        lines = f.readlines()\n```\n\n\n```python\n# view the first 5 and last 5 anime url collected\nlines[:5], lines[-5:]\n```\n\n\n\n\n    (['https://myanimelist.net/anime/5114/Fullmetal_Alchemist__Brotherhood\\n',\n      'https://myanimelist.net/anime/28977/Gintama\u00b0\\n',\n      'https://myanimelist.net/anime/38524/Shingeki_no_Kyojin_Season_3_Part_2\\n',\n      'https://myanimelist.net/anime/9253/Steins_Gate\\n',\n      'https://myanimelist.net/anime/42938/Fruits_Basket__The_Final\\n'],\n     ['https://myanimelist.net/anime/42383/Konbini_Shoujo_Z\\n',\n      'https://myanimelist.net/anime/10564/Korogashi_Ryouta\\n',\n      'https://myanimelist.net/anime/50237/Kyonyuu_Elf_Oyako_Saimin\\n',\n      'https://myanimelist.net/anime/49876/Mahou_Shoujo_Elena_DVD-BOX_Special\\n',\n      'https://myanimelist.net/anime/49762/Mama_x_Holic__Miwaku_no_Mama_to_Amaama_Kankei_-_The_Animation'])\n\n\n\n### Libraries\n\n\n```python\n# core libraries\nimport requests\nfrom bs4 import BeautifulSoup\nfrom time import sleep\n# for time view\nfrom tqdm import tqdm\n```\n\n### The Crawl\n\nWe begin creating the pages needed to store the anime. \n\nThe pages from 1 to 383 are stored in the Anime_pages folder.\n\n\n```python\nimport os\n\nfor page in tqdm(range(1, 384)):\n    folder = \"page\"+str(page)\n    path = \"./Anime_pages/\"+folder\n    os.mkdir(path)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 383/383 [00:00<00:00, 3978.07it/s]\n\n\nNow we create a double loop, over the pages and over the 50 anime, to collect the whole html and save it in the correct pages.\n\nFor group division, here the loop goes from page 1 to 130. For have the complete loop we can iter over 0 to 383.\nWe also use a \"SLEEP\" to avoid the robot cheack while scrabbing the html of the page.\n\nBecause we cant have time to re-run the cell of the crawl of the 384 anime, we run for only the first page and will load the screenshot of the all work done on the total of pages after.\n\n\n```python\nfor page in tqdm(range(0, 1)):  \n    # positioning in the right folder page\n    folder = \"/page\"+str(page+1)\n    for i in range(0,50):   \n        page_now = 50*page\n        # gather the url\n        url = lines[page_now+i]\n        response = requests.get(url)\n        # name of the file   \n        filename = r\"./Anime_pages\"+folder+\"/anime_\"+str(page_now+i+1)+\".html\"\n        with open(filename,'w', encoding='utf-8') as f:\n            f.write(response.text)\n        # add a sleep to avoid the \"robot cheack\" in fast scrabbing the html\n        sleep(5)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1/1 [05:54<00:00, 354.32s/it]\n\n\n\n```python\n# Verify check\n```\n\n\n```python\nfrom PIL import Image\nmyImage = Image.open(\"Screenshot2.png\");\nmyImage\n```\n\n\n```python\nmyImage = Image.open(\"Screenshot1.png\");\nmyImage\n```\n\n## 1.3 Parse downloaded pages\n\n\n### Importing libraries\n\n\n```python\n# core libraries\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nfrom datetime import datetime\nimport re\n# usefull libraries to manage file in folder \nimport os\nfrom natsort import natsorted\n# for time view\nfrom tqdm import tqdm\n```\n\nBecause there are vary information to collect about an anime, to have a clear notebook we split in functions our parsing in the \"functions.py\" file.\n\nWe divide the crawl in three function (or three part):\n* scrabbing_anime1:  Title, Type, number of Episode, Realease / End date\n* scrabbing_anime2:  number of Members, Score, Users, Rank, Popularity\n* scrabbing_anime3:  Synopsis, anime Related, anime Characters and Voices, anime Staff\n\nAlso we have a function called: \n* parse_time:  a function that parse the date collected from the html in a datetime object\n\nThe parsing process is this: we create a list called \"anime_info\" in which we collect all the info about an anime. Than using this list we create a dataframe which columns are coming from the \"attrs\" list (a list containing the title of each attributes) and save it as a .tsv file.\n\n\n```python\n# importing the functions on functions.py file\nimport functions\n```\n\nLet's view the process with one anime\n\n\n```python\n# name of the columns \nattrs = [\"animeTitle\", \"animeType\", \"animeNumEpisode\",\"releaseDate\",\"endDate\",\"animeNumMembers\",\"animeScore\",\"animeUsers\",\"animeRank\",\n         \"animePopularity\",\"animeDescription\",\"animeRelated\",\"animeCharacters\",\"animeVoices\",\"animeStaff\"]\n\n# positioning \nfolder = r\"./Anime_pages/page1/\"\nanime = \"anime_1.html\"\n\n# take the html of the file \nwith open(folder+anime, \"r\",  encoding='utf-8') as fp:\n    soup = BeautifulSoup(fp, \"html.parser\")\n\n# collecting the information\nanime_info = []\nanime_info + functions.scrabbing_anime1(soup, anime_info)\nanime_info + functions.scrabbing_anime2(soup, anime_info)\nanime_info + functions.scrabbing_anime3(soup, anime_info)\n\n\n# Creating the DataFrame\ndf = pd.DataFrame([anime_info], columns = attrs)\n# change attributes to str\nstr_cols = [\"animeTitle\", \"animeType\", \"animeDescription\"]\ndf[str_cols] = df[str_cols].astype(\"string\")\n# Creating the tsv file, take the anime number (the id)\nname = re.sub(\".html\",\"\",anime)\ndf.to_csv(\"./tsv_anime/\"+name+\".tsv\", index = False, sep = \"\\t\")\n```\n\n\n```python\n# type cheaking \ndf.info()\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 1 entries, 0 to 0\n    Data columns (total 15 columns):\n     #   Column            Non-Null Count  Dtype         \n    ---  ------            --------------  -----         \n     0   animeTitle        1 non-null      string        \n     1   animeType         1 non-null      string        \n     2   animeNumEpisode   1 non-null      int64         \n     3   releaseDate       1 non-null      datetime64[ns]\n     4   endDate           1 non-null      datetime64[ns]\n     5   animeNumMembers   1 non-null      int64         \n     6   animeScore        1 non-null      float64       \n     7   animeUsers        1 non-null      int64         \n     8   animeRank         1 non-null      int64         \n     9   animePopularity   1 non-null      int64         \n     10  animeDescription  1 non-null      string        \n     11  animeRelated      1 non-null      object        \n     12  animeCharacters   1 non-null      object        \n     13  animeVoices       1 non-null      object        \n     14  animeStaff        1 non-null      object        \n    dtypes: datetime64[ns](2), float64(1), int64(5), object(4), string(3)\n    memory usage: 248.0+ bytes\n\n\nFor all the anime we proceed in this way:\n\n\n```python\nattrs = [\"animeTitle\", \"animeType\", \"animeNumEpisode\",\"releaseDate\",\"endDate\",\"animeNumMembers\",\"animeScore\",\"animeUsers\",\"animeRank\",\n         \"animePopularity\",\"animeDescription\",\"animeRelated\",\"animeCharacters\",\"animeVoices\",\"animeStaff\"]\n\n\n# iterate from page 1 to 384 \n# ( remember the page are from 1 to 383 and range goes from 1 to 384 )\nfor page in tqdm(range(1,384)):\n    # positioning\n    folder = \"./Anime_pages/page\"+str(page)\n    # iterate over the \"ordered\" list of anime\n    for anime in natsorted(os.listdir(folder)):\n            # open the anime\n            with open(folder + \"/\" + anime, \"r\",  encoding='utf-8') as fp:\n                soup = BeautifulSoup(fp, \"html.parser\")\n            anime_info = []\n            anime_info + functions.scrabbing_anime1(soup, anime_info)\n            anime_info + functions.scrabbing_anime2(soup, anime_info)\n            anime_info + functions.scrabbing_anime3(soup, anime_info)\n        \n            # Creating the DataFrame\n            df = pd.DataFrame([anime_info], columns = attrs)\n            # change attributes to str\n            str_cols = [\"animeTitle\", \"animeType\", \"animeDescription\"]\n            df[str_cols] = df[str_cols].astype(\"string\")\n            # Creating the tsv file, take the anime number to match the txt url row and the tsv\n            name = re.sub(\".html\",\"\",anime)\n            df.to_csv(\"./tsv_anime/\"+name+\".tsv\", index = False, sep = \"\\t\")\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 383/383 [53:29<00:00,  8.38s/it]\n\n\n# [EX2] Search Engine\n\n\n## 2.0 Preprocessing the documents\n\n### Let's collect our corpus of documents\n\nFirst of all lets gather all the documents in one list.\n* documents: lists of document. Each document correspond to an anime description.\n\n\n```python\nfrom tqdm import tqdm\nfrom natsort import natsorted\nimport os\nimport pandas as pd\n```\n\n\n```python\ndocuments = []\n\n# positioning\nfolder = r\"./tsv_anime/\"\n# iter over the file\nfor anime in tqdm(natsorted(os.listdir(folder))):\n    df = pd.read_csv(folder+anime, sep = \"\\t\")\n    # take only the description\n    documents.append(df[\"animeDescription\"][0])\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19116/19116 [02:16<00:00, 139.74it/s]\n\n\n\n```python\n# view a document \ndocuments[0]\n```\n\n\n\n\n    'After a horrific alchemy experiment goes wrong in the Elric household, brothers Edward and Alphonse are left in a catastrophic new reality. Ignoring the alchemical principle banning human transmutation, the boys attempted to bring their recently deceased mother back to life. Instead, they suffered brutal personal loss: Alphonse\\'s body disintegrated while Edward lost a leg and then sacrificed an arm to keep Alphonse\\'s soul in the physical realm by binding it to a hulking suit of armor.\\n\\n\\nThe brothers are rescued by their neighbor Pinako Rockbell and her granddaughter Winry. Known as a bio-mechanical engineering prodigy, Winry creates prosthetic limbs for Edward by utilizing \"automail,\" a tough, versatile metal used in robots and combat armor. After years of training, the Elric brothers set off on a quest to restore their bodies by locating the Philosopher\\'s Stone\u2014a powerful gem that allows an alchemist to defy the traditional laws of Equivalent Exchange.\\n\\n\\nAs Edward becomes an infamous alchemist and gains the nickname \"Fullmetal,\" the boys\\' journey embroils them in a growing conspiracy that threatens the fate of the world.\\n\\n\\n[Written by MAL Rewrite]'\n\n\n\n### Clean the documents\n\nNow let's cleaning all the documents. This step is colled preprocessing. We follow this order:\n- 1) expand contraction type 1 + Normalization (capital lower words)\n- 2) splitting number from text (ex 25min) and removing contraction type 2 \n- 3) removing punctuation\n- 4) Tokanize. We divide the string in words.\n- 5) removing stopwords\n- 6) removing some other words or non-text string like [\u2026\u2022\u2665\u2192\u2606\u2018\u2605] or japanese glyphe\n- 7) lemmatizing and stemming \n\nFor contraction type 1 and 2 see below\n\nLet's inspect the document to see what we can delete and what no:\n- for example: \"Philosopher's Stone\u2014a powerful\" << This is dash\n- but \"bio-mechanical engineering\" << This is hyphen\n- but we also have \"15-year\" << hyphen <br>\n\nWe decide to remove the hypen and the dash\n\nWe encounter also some special characters like: \u2026 \u2022 \u2665 \u2192\u2606\u2018 . We remove them.\n\nAt the end of a lot of anime description there is a \"Written MAL Rewrite\". We remove that.\n\nWhen tokanizing there is also the saxon genitive \" 's \": we remove that.\n\nAlso we encounter a lot of contraction form: using wikipedia https://en.wikipedia.org/wiki/Wikipedia:List_of_English_contractions\nwe store them in a dictionary and restore the long form.\nUsing the same idea we have term like: min or sec, so we use a second dictionary to restore the original form.\n\n\n```python\n# core libraries \nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer\nfrom nltk.stem.wordnet import WordNetLemmatizer\nimport string\nimport re\n\n# functions.py\nimport functions\n```\n\n\n```python\ncontractions = {\n\"ain't\": \"am not\",\n\"aren't\": \"are not\",\n\"can't\": \"cannot\",\n\"can't've\": \"cannot have\",\n\"'cause\": \"because\",\n\"could've\": \"could have\",\n\"couldn't\": \"could not\",\n\"couldn't've\": \"could not have\",\n\"didn't\": \"did not\",\n\"doesn't\": \"does not\",\n\"don't\": \"do not\",\n\"hadn't\": \"had not\",\n\"hadn't've\": \"had not have\",\n\"hasn't\": \"has not\",\n\"haven't\": \"have not\",\n\"he'd\": \"he had\",\n\"he'd've\": \"he would have\",\n\"he'll\": \"he shall\",\n\"he'll've\": \"he shall have\",\n\"he's\": \"he has\",\n\"how'd\": \"how did\",\n\"how'd'y\": \"how do you\",\n\"how'll\": \"how will\",\n\"how's\": \"how has\",\n\"i'd\": \"I had\",\n\"i'd've\": \"I would have\",\n\"i'll\": \"I shall\",\n\"i'll've\": \"I shall have\",\n\"i'm\": \"I am\",\n\"i've\": \"I have\",\n\"isn't\": \"is not\",\n\"it'd\": \"it had\",\n\"it'd've\": \"it would have\",\n\"it'll\": \"it shall\",\n\"it'll've\": \"it shall have\",\n\"it's\": \"it has\",\n\"let's\": \"let us\",\n\"ma'am\": \"madam\",\n\"mayn't\": \"may not\",\n\"might've\": \"might have\",\n\"mightn't\": \"might not\",\n\"mightn't've\": \"might not have\",\n\"must've\": \"must have\",\n\"mustn't\": \"must not\",\n\"mustn't've\": \"must not have\",\n\"needn't\": \"need not\",\n\"needn't've\": \"need not have\",\n\"o'clock\": \"of the clock\",\n\"oughtn't\": \"ought not\",\n\"oughtn't've\": \"ought not have\",\n\"shan't\": \"shall not\",\n\"sha'n't\": \"shall not\",\n\"shan't've\": \"shall not have\",\n\"she'd\": \"she had\",\n\"she'd've\": \"she would have\",\n\"she'll\": \"she shall\",\n\"she'll've\": \"she shall have\",\n\"she's\": \"she has\",\n\"should've\": \"should have\",\n\"shouldn't\": \"should not\",\n\"shouldn't've\": \"should not have\",\n\"so've\": \"so have\",\n\"so's\": \"so as\",\n\"that'd\": \"that would\",\n\"that'd've\": \"that would have\",\n\"that's\": \"that has\",\n\"there'd\": \"there had\",\n\"there'd've\": \"there would have\",\n\"there's\": \"there has\",\n\"they'd\": \"they had\",\n\"they'd've\": \"they would have\",\n\"they'll\": \"they shall\",\n\"they'll've\": \"they shall have\",\n\"they're\": \"they are\",\n\"they've\": \"they have\",\n\"to've\": \"to have\",\n\"wasn't\": \"was not\",\n\"we'd\": \"we had\",\n\"we'd've\": \"we would have\",\n\"we'll\": \"we will\",\n\"we'll've\": \"we will have\",\n\"we're\": \"we are\",\n\"we've\": \"we have\",\n\"weren't\": \"were not\",\n\"what'll\": \"what shall\",\n\"what'll've\": \"what shall have\",\n\"what're\": \"what are\",\n\"what's\": \"what has\",\n\"what've\": \"what have\",\n\"when's\": \"when has\",\n\"when've\": \"when have\",\n\"where'd\": \"where did\",\n\"where's\": \"where has\",\n\"where've\": \"where have\",\n\"who'll\": \"who shall\",\n\"who'll've\": \"who shall have\",\n\"who's\": \"who has\",\n\"who've\": \"who have\",\n\"why's\": \"why has\",\n\"why've\": \"why have\",\n\"will've\": \"will have\",\n\"won't\": \"will not\",\n\"won't've\": \"will not have\",\n\"would've\": \"would have\",\n\"wouldn't\": \"would not\",\n\"wouldn't've\": \"would not have\",\n\"y'all\": \"you all\",\n\"y'all'd\": \"you all would\",\n\"y'all'd've\": \"you all would have\",\n\"y'all're\": \"you all are\",\n\"y'all've\": \"you all have\",\n\"you'd\": \"you had\",\n\"you'd've\": \"you would have\",\n\"you'll\": \"you shall\",\n\"you'll've\": \"you shall have\",\n\"you're\": \"you are\",\n\"you've\": \"you have\"\n}\n```\n\n\n```python\ncontractions2 = {\n\"min\": \"minute\",\n\"sec\": \"second\"\n}\n```\n\n\n```python\ndef pre_processing(documents):\n    stop = stopwords.words(\"english\")\n    lmtzr = WordNetLemmatizer()\n    remove = [\"Written\", \"MAL\", \"Rewrite\"]+[\"'s\"]+[\"\"]\n    ps = PorterStemmer()\n    \n    # removing contraction + Normalization\n    document_tmp = functions.replace_words(documents.lower(), contractions)\n    # splitting number and text \n    document_tmp = \" \".join(re.split(r\"([0-9]+)([a-z]+)\",document_tmp))\n    document_tmp = functions.replace_words(document_tmp, contractions2)\n    # removing punctuation\n    document_tmp = re.sub(r\"[{}\\\u2014\u30fc``\\\"'\u201c''\u2015\u2015]\".format(string.punctuation),\" \",document_tmp)\n    # Tokenizing \n    document_tmp = word_tokenize(document_tmp) \n    # removing stopwords\n    document_tmp = [ word for word in document_tmp if word not in stop]\n    # removing \"Written MAL Rewrite\" and we want only the alphanumeric text NO [\u2026\u2022\u2665\u2192\u2606\u2018\u2605]\n    document_tmp = [ re.sub(r\"[^a-zA-Z0-9]\", \"\", word).strip() for word in document_tmp]\n    document_tmp = [ word for word in document_tmp if word not in remove]\n    # lemmatize\n    document_tmp = [ lmtzr.lemmatize(word) for word in document_tmp]\n    # stemming \n    document_tmp = [ ps.stem(word) for word in document_tmp]\n\n    return document_tmp\n```\n\n- documents_clean: is a list of list of the documents cleaned. Each list contain the tokenize cleaning document text.\n\n\n```python\n# cleaning the documents\ndocuments_clean = []\nfor d in documents:\n    documents_clean.append(pre_processing(d))\n```\n\nLet's view how a document is processed:\n\n\n```python\ndocuments_clean[0][:10]\n```\n\n\n\n\n    ['horrif',\n     'alchemi',\n     'experi',\n     'go',\n     'wrong',\n     'elric',\n     'household',\n     'brother',\n     'edward',\n     'alphons']\n\n\n\n### Creating vocabulary\n\n\n```python\n# core libraries\nimport itertools\nimport numpy as np\n```\n\nI will create a list of each unique word among the all documents\n\n\n```python\n# the list of all unique words\nword_list = list(set(list(itertools.chain.from_iterable(documents_clean))))\n```\n\nCreating a dictionary that maps each word to an integer: we use the function zip to assign to each word an order integer.\n\n\n```python\nvocabolary = dict(zip(word_list, range(len(word_list))))\n```\n\n\n```python\nlen(vocabolary)\n```\n\n\n\n\n    36063\n\n\n\n\n```python\n# view the vocabolary\ncount = 0\nfor key, mapped_int in vocabolary.items():\n    count +=1\n    print(key,\"-->\",mapped_int)\n    if count == 10: break\n```\n\n    maetel --> 0\n    giraff --> 1\n    mikumo --> 2\n    softwar --> 3\n    aguri --> 4\n    beg --> 5\n    marriag --> 6\n    ingeni --> 7\n    senou --> 8\n    flaminuteg --> 9\n\n\nSaving the dictionary in a .json file\n\n\n```python\nimport json\n\nfile = open(\"vocabolary.json\", \"w\", encoding = \"utf-8\")\njson.dump(vocabolary, file)\nfile.close()\n```\n\nImport the saved vocabolary.\n\n\n```python\nwith open( \"vocabolary.json\" ) as f:\n    vocabolary = json.load( f )\n```\n\n## 2.1. Conjunctive query\n\nFor this type of search engine we need only to have a search engine based on the query appear or not in each documents. \n\n\n* ### Prepare the mapped document\n\nTo do this we will create an array of documents of each len(document_j) in which thare are converted the word into integer based on the vocabolary\n\nWe will use numpy array for time optimitation.\n\n\n```python\ndef word_to_int(document, vocabolary):\n    int_doc = np.zeros(len(document), dtype = np.int64)\n    # iterating over the document that has len(d)<<len(vocabolary)\n    # change the value of the document, otherwise remain zero\n    for i, word in enumerate(document):\n        # vocabolary[word] is the mapping function that return an integer i.e the index\n        int_doc[i] = vocabolary[word]\n        \n    return np.sort(int_doc)\n```\n\n* documents_mapped: is a list of list that have the words mapped\n\n\n```python\ndocuments_mapped = []\nfor d in documents_clean:\n    documents_mapped.append(word_to_int(d,vocabolary))\n```\n\n\n```python\n# view a docoument mapped \ndocuments_mapped[0]\n```\n\n\n\n\n    array([  529,   981,  1111,  1204,  1409,  1700,  1703,  1757,  2535,\n            2535,  3048,  3414,  3615,  4186,  4235,  4585,  4689,  5040,\n            5083,  5083,  5083,  5358,  5358,  5753,  5928,  5928,  6569,\n            6760,  7056,  7528,  7866,  7962,  7963,  8939,  9251,  9347,\n            9835, 10487, 10685, 10762, 10762, 10762, 10811, 10850, 10983,\n           11828, 12320, 12763, 12843, 13126, 13175, 13380, 13576, 14657,\n           14750, 14750, 14856, 15481, 15654, 15663, 15931, 15975, 16087,\n           16767, 17220, 17240, 17326, 17327, 17376, 17384, 17657, 19652,\n           19882, 19907, 20633, 20755, 20820, 20974, 20974, 21010, 21335,\n           21400, 21696, 21951, 22151, 23298, 23298, 23298, 23298, 23332,\n           23332, 23735, 24082, 24676, 24927, 25703, 26188, 26387, 26644,\n           27423, 27453, 27897, 29151, 29796, 31013, 31140, 31166, 31351,\n           31673, 32223, 33600, 33736, 35454, 35989], dtype=int64)\n\n\n\n* ### Inverted Index v1\n\n\n```python\nfrom collections import defaultdict  \n```\n\n\n```python\n# initialize the Inverted_index\nInverted_index = defaultdict(list)\n```\n\nTo compute the Inverted Index we iterating over each document. Every time we encounter a word (that is now a integer) we insert in the dictionary the id of the documents, which is the row index in documents_mapped or in our dataset of tsv / url.txt.\n\n\n```python\nfor i,d in enumerate(documents_mapped):\n    for word in set(d):\n        Inverted_index[str(word)].append(i)\n```\n\n\n```python\n# let's view the Inverted_index\ncount = 0\nfor key, lis in Inverted_index.items():\n    count +=1\n    print(\"word: \",key,\"-->\",\"documents: \", lis)\n    if count == 1: break\n```\n\n    word:  14856 --> documents:  [0, 126, 284, 293, 410, 458, 491, 579, 806, 857, 875, 1105, 1118, 1121, 1173, 1202, 1284, 1829, 1917, 2205, 2289, 2422, 2616, 2723, 2781, 2941, 2969, 3205, 3556, 3681, 4006, 4056, 4331, 4474, 4814, 5150, 5222, 5770, 5937, 6310, 6603, 6838, 7044, 7755, 8004, 8447, 8492, 8698, 8770, 8983, 9047, 10123, 10235, 10897, 11056, 12617, 14549, 15357, 15412, 15660, 16067, 16660, 17314, 17685, 17717, 17722, 17795, 17971, 17974, 18011, 18069, 18244, 18316, 18401, 18728, 18766]\n\n\nSaving the Inverted Index in memory\n\n\n```python\nimport json\n\nfile = open(\"Inverted_index_v1.json\", \"w\", encoding = \"utf-8\")\njson.dump(Inverted_index, file)\nfile.close()\n```\n\nImport the saved inverted index\n\n\n```python\nwith open( \"Inverted_index_v1.json\" ) as f:\n    Inverted_index = json.load( f )\n```\n\n* ### Searching\n\nHow it work:\n\n* Given in input a query we first of all preprocessing like a document;\n* then using the Inverted index we exctract the list corrisponding to each element (word) of the query, store them in a list of set (for intersection pourpose) called \"index\". \n* Than we intersect all the set for obtain the documents that match ALL the query elements.\n* In the end we create the dataframe with the desire output.\n\n\n```python\ndef search_engine_v1(query_text):\n    # pre-processing the query\n    query_clean = pre_processing(query_text)\n    query_int = word_to_int(query_clean, vocabolary)\n    \n    # for each element of the query we can obtain the list of doc \n    # in which the query element appears\n    index = []\n    \n    for query in query_int:\n        # creating a set of index (set is for intersection pourpose)\n        index.append(set(Inverted_index[str(query)]))\n    \n    # intersect and obtain the documents that contain ALL the query\n    index = list(index[0].intersection(*index))\n    \n    # taken the url of the anime list\n    with open(\"./anime_url.txt\", \"r\", encoding = \"utf-8\") as f:\n        lines = f.readlines()\n        \n    # we are searching for the anime and the url corrisponding to the index\n    # we found\n    anime_path = []\n    url = []\n\n    for idx in index:\n        # we need the +1 because we start indexing from 1\n        name = \"/anime_\"+str(idx+1)+\".tsv\"\n        anime_path.append(name)\n        url.append(lines[idx])\n\n    # creating the dataframe for view the result\n    animes_df = []\n    # folder of the anime_tsv\n    folder = r\"./tsv_anime/\"\n    # column I want\n    cols = [\"animeTitle\",\"animeDescription\"]\n    for i,anime_tsv in enumerate(anime_path):\n        df = pd.read_csv(folder+anime_tsv, sep = \"\\t\", usecols = cols)\n        # creating new column with the url\n        df[\"animeURL\"] = url[i]\n        animes_df.append(df)\n    \n    frame = pd.concat(animes_df, ignore_index = True)\n    display(frame)\n```\n\n#### Input and search\n\n\n```python\n# input query \nquery_text = input(\"Insert the query: \")\n\nsearch_engine_v1(query_text)\n```\n\n    Insert the query:  battle pirate\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>animeTitle</th>\n      <th>animeDescription</th>\n      <th>animeURL</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Beast Wars Second Chou Seimeitai Transformers:...</td>\n      <td>The movie begins with a space battle between t...</td>\n      <td>https://myanimelist.net/anime/5289/Beast_Wars_...</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Last Exile: Ginyoku no Fam Movie - Over the Wi...</td>\n      <td>A recap film with some new scenes.\\n\\n\\nThe Sk...</td>\n      <td>https://myanimelist.net/anime/31866/Last_Exile...</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>One Piece</td>\n      <td>Gol D. Roger was known as the \"Pirate King,\" t...</td>\n      <td>https://myanimelist.net/anime/21/One_Piece\\n</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Battle Can\u00b2</td>\n      <td>Join this band of femme fatales as they sacrif...</td>\n      <td>https://myanimelist.net/anime/6025/Battle_Can\u00b2\\n</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Gintama.</td>\n      <td>After joining the resistance against the bakuf...</td>\n      <td>https://myanimelist.net/anime/34096/Gintama\\n</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>One Piece Movie 2: Nejimaki-jima no Daibouken</td>\n      <td>Informed by the Thief Brothers his ship has be...</td>\n      <td>https://myanimelist.net/anime/460/One_Piece_Mo...</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>A-Ko The Versus</td>\n      <td>A-ko and B-ko are bounty hunters in an untamed...</td>\n      <td>https://myanimelist.net/anime/1295/A-Ko_The_Ve...</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Slayers Revolution</td>\n      <td>Having lost the Sword of Light in the previous...</td>\n      <td>https://myanimelist.net/anime/4028/Slayers_Rev...</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Gintama Movie 2: Kanketsu-hen - Yorozuya yo Ei...</td>\n      <td>When Gintoki apprehends a movie pirate at a pr...</td>\n      <td>https://myanimelist.net/anime/15335/Gintama_Mo...</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>One Piece Movie 1</td>\n      <td>Woonan is the legendary Great Gold Pirate, ear...</td>\n      <td>https://myanimelist.net/anime/459/One_Piece_Mo...</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>Seihou Tenshi Angel Links</td>\n      <td>Li Meifon is the head of a free, no expenses p...</td>\n      <td>https://myanimelist.net/anime/1226/Seihou_Tens...</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>One Piece: Oounabara ni Hirake! Dekkai Dekkai ...</td>\n      <td>The story opens on Pirate Zap's ship, where tw...</td>\n      <td>https://myanimelist.net/anime/1237/One_Piece__...</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>One Piece 3D2Y: Ace no shi wo Koete! Luffy Nak...</td>\n      <td>After suffering great personal loss during the...</td>\n      <td>https://myanimelist.net/anime/25161/One_Piece_...</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>Last Exile: Ginyoku no Fam</td>\n      <td>\"I've made up my mind! I'm going to steal that...</td>\n      <td>https://myanimelist.net/anime/10336/Last_Exile...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n# 2.2 Conjunctive query & Ranking score\n\nNow we want for our Inverted_index two element:\n\n* $\\text{tf}_{i,j}$: occurancy of term $j$ in document $i$\n* $\\text{idf}_{j}$: Inverse Document Frequency of term $j$\n\nDefine:\n\n* n_words = total number of words in vocabolary\n* n = number of documents\n\n\n```python\nn = len(documents)\nn_words = len(vocabolary)\n```\n\nCreating the $\\text{tf}_{i,j}$ matrix:\n\n* ### Prepare the mapped document\n\nTo do this we will create an array of documents of each len(document_j) in which thare are converted the word into integer based on the vocabolary\n\nWe will use numpy array for time optimitation.\n\n\n```python\n# function that map document text to the relative tf\n\ndef word_to_int2(document, vocabolary):\n    int_doc = np.zeros(len(vocabolary), dtype = np.int64)\n    # iterating over the document that has len(d)<<len(vocabolary)\n    # change the value of the document, otherwise remain zero\n    for word in document:\n        # vocabolary[word] is the mapping function that return an integer i.e the index\n        int_doc[vocabolary[word]] += 1\n        \n    return int_doc\n```\n\n* $tf$: is a list of list that have the words mapped with is count\n\n\n```python\ntf = []\nfor d in documents_clean:\n    tf.append(word_to_int2(d,vocabolary))\n```\n\n\n```python\n# view a doc\ntf[0][tf[0]>0]\n```\n\n\n\n\n    array([1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 3, 2, 1, 2, 1,\n           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n           1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n           1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 4, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int64)\n\n\n\nCreating the $\\text{idf}_{j}$ array:\n* I need the $n_j$: number of documents containing term j\n\n\n```python\nnj = np.zeros(n_words, dtype = np.float64)\n\n# we create a numpy array of length n_words\n# for each docoument we take the unique set of word\n# and count\nfor d in documents_mapped:\n    for word in set(d):\n        nj[word] += 1\n```\n\n\n```python\n# view\nnj\n```\n\n\n\n\n    array([9., 9., 3., ..., 3., 1., 4.])\n\n\n\n\n```python\n# creating idf_j\n\nidf = np.zeros(n_words, dtype = np.float64)\nidf = np.log(n/nj) / np.log(n)\n```\n\n$\\text{tfIdf}_{ij} = \\text{tf}_{ij} * \\text{idf}_{j} $\n\n\n```python\ntfIdf = np.multiply(tf,idf)\n```\n\n\n```python\nnp.shape(tfIdf)\n```\n\n\n\n\n    (19116, 36063)\n\n\n\n* ### Inverted index v2\n\n\n```python\nfrom collections import defaultdict  \n```\n\n\n```python\nInverted_indexv2 = defaultdict(list)\n```\n\nTo compute the Inverted Index we iterating over each document. Every time we encounter a word (that is now a integer) we insert in the dictionary the __tupla__ of _id_ of the documents and the _tfIdf_.\n\n\n```python\nfor i,d in enumerate(documents_mapped):\n    for word in set(d):\n        # append (idd_i, tfidf_ij)\n        Inverted_indexv2[str(word)].append((i,tfIdf[i,int(word)]))\n```\n\n\n```python\n# view\ncount = 0\nfor key, lis in Inverted_indexv2.items():\n    count +=1\n    print(key,\"-->\",lis)\n    if count == 1: break\n```\n\n    14856 --> [(0, 0.5607009621666353), (126, 0.5607009621666353), (284, 0.5607009621666353), (293, 0.5607009621666353), (410, 0.5607009621666353), (458, 0.5607009621666353), (491, 1.1214019243332707), (579, 0.5607009621666353), (806, 0.5607009621666353), (857, 0.5607009621666353), (875, 0.5607009621666353), (1105, 0.5607009621666353), (1118, 0.5607009621666353), (1121, 0.5607009621666353), (1173, 0.5607009621666353), (1202, 0.5607009621666353), (1284, 0.5607009621666353), (1829, 0.5607009621666353), (1917, 0.5607009621666353), (2205, 0.5607009621666353), (2289, 0.5607009621666353), (2422, 0.5607009621666353), (2616, 0.5607009621666353), (2723, 0.5607009621666353), (2781, 0.5607009621666353), (2941, 0.5607009621666353), (2969, 0.5607009621666353), (3205, 0.5607009621666353), (3556, 0.5607009621666353), (3681, 0.5607009621666353), (4006, 0.5607009621666353), (4056, 0.5607009621666353), (4331, 0.5607009621666353), (4474, 0.5607009621666353), (4814, 1.1214019243332707), (5150, 0.5607009621666353), (5222, 0.5607009621666353), (5770, 0.5607009621666353), (5937, 0.5607009621666353), (6310, 0.5607009621666353), (6603, 0.5607009621666353), (6838, 1.1214019243332707), (7044, 0.5607009621666353), (7755, 0.5607009621666353), (8004, 0.5607009621666353), (8447, 0.5607009621666353), (8492, 0.5607009621666353), (8698, 0.5607009621666353), (8770, 0.5607009621666353), (8983, 0.5607009621666353), (9047, 0.5607009621666353), (10123, 0.5607009621666353), (10235, 0.5607009621666353), (10897, 0.5607009621666353), (11056, 0.5607009621666353), (12617, 0.5607009621666353), (14549, 0.5607009621666353), (15357, 1.1214019243332707), (15412, 0.5607009621666353), (15660, 0.5607009621666353), (16067, 0.5607009621666353), (16660, 0.5607009621666353), (17314, 0.5607009621666353), (17685, 0.5607009621666353), (17717, 0.5607009621666353), (17722, 0.5607009621666353), (17795, 1.1214019243332707), (17971, 0.5607009621666353), (17974, 0.5607009621666353), (18011, 0.5607009621666353), (18069, 0.5607009621666353), (18244, 0.5607009621666353), (18316, 0.5607009621666353), (18401, 2.2428038486665414), (18728, 0.5607009621666353), (18766, 0.5607009621666353)]\n\n\nSaving the Inverted Index in memory\n\n\n```python\nimport json\n\nfile = open(\"Inverted_index_v2.json\", \"w\", encoding = \"utf-8\")\njson.dump(Inverted_indexv2, file)\nfile.close()\n```\n\nImport the saved inverted index\n\n\n```python\nwith open( \"Inverted_index_v2.json\" ) as f:\n    Inverted_indexv2 = json.load( f )\n```\n\n* ### Searching\n\nTo better have a use of the Inverted Index + Ranking we suppose that a __query is input as a text of unique word__.\n\nWe define than the cosine similarity as:\n$$\n\\begin{equation}\n\\cos(q,d^i) =  \\frac{\\sum_{j: \\hspace{0.1cm}  q_j=1} \\text{tfIdf}_{ij}}{||d^i||*||q||}\n\\end{equation}\n$$\n\nUnder this assumption we observe that: $||q|| = \\sqrt(len(q)$\n\nRecall: $d^i = [\\text{tfIdf}_{i1}, \\text{tfIdf}_{i2}, \\ldots]$ \n\n\n```python\n# libraries to compute the manage the heap\nimport heapq\n```\n\nHow is it work:\n\n* we take a query text in input and preprocessing like a normal document. Than we obtain the \"query_int\" array of 0 and 1: q[j] = 1 if word_j in q, 0 otherwise;\n* then using the Inverted index we exctract the list of tuple corrisponding to each element (word) of the query. We store also the len of each match list and the maximum list (we need it to manage the pointer of different length list);\n* We now have a function \"intersection_all\" that return two things: a boolean variable, enough that is True if I have at least k document that match the all query and match list, that return the list of the index that match all the query if true or the original match list if False;\n* Than the algorithm goes in two part:<br>\n$\\hspace{1cm}$  1. if True (I have at least k document) we compute the score of element in the list and return the top k<br>\n$\\hspace{1cm}$  2. if False, we compute the score af all the document and return the score ordered of the matches\n* In the end: we create the dataframe of the documents ranked.\n\n\n```python\ndef search_engine2(query, k, tfIdf):\n    # preprocessing the query\n    query_clean = pre_processing(query)\n    query_int = word_to_int2(query_clean, vocabolary)\n\n    # initialize a match_list which store the list of match\n    match_list = []\n    # list of the length of the match \n    lenMatch = []\n    # tupla = (#list, len(list))\n    max_lenMatch = (0,-1)\n    for i,query in enumerate(np.where(query_int>0)[0]):\n        lis = Inverted_indexv2[str(query)]\n        match_list.append(lis)\n        tmplis, tmplen = i, len(lis)\n        if tmplen>max_lenMatch[1]:\n            max_lenMatch = (tmplis,tmplen)\n        lenMatch.append(len(lis))\n    \n    enough, match_list = functions.intersection_all(k, match_list)\n    m = len(query_clean)\n    if enough:\n        scores = functions.scoresK(match_list, tfIdf, m, query_int)\n        topscore, topk = functions.find_topK(k, scores)\n    else:\n        scores = functions.scoresALL(match_list, tfIdf, m, lenMatch)\n        # the top k documents are ALL the documents\n        k = len(scores)\n        topscore, topk = functions.find_topK(k, scores)\n            \n    # search the url\n    with open(\"./anime_url.txt\", \"r\", encoding = \"utf-8\") as f:\n        lines = f.readlines()\n        \n    # we are searching for the anime and the url \n    anime_path = []\n    url = []\n\n    for idx in topk:\n        # we need the +1 because we start indexing from 1\n        name = \"/anime_\"+str(idx+1)+\".tsv\"\n        anime_path.append(name)\n        url.append(lines[idx])\n\n    # creating the dataframe for view the result\n    animes_df = []\n    # folder of the anime_tsv\n    folder = r\"./tsv_anime/\"\n    # column I want\n    cols = [\"animeTitle\",\"animeDescription\"]\n    for i,anime_tsv in enumerate(anime_path):\n        df = pd.read_csv(folder+anime_tsv, sep = \"\\t\", usecols = cols)\n        # creating new column\n        df[\"animeURL\"] = url[i]\n        df[\"animeScores\"] = topscore[i]\n        animes_df.append(df)\n    \n    frame = pd.concat(animes_df, ignore_index = True)\n    display(frame)\n    \n    return\n```\n\n### Input and searching\n\n\n```python\nquery = input(\"Insert the query: \")\nk = int(input(\"Insert k: \"))\n\nsearch_engine2(query, k, tfIdf)\n```\n\n    Insert the query:  battle pirate\n    Insert k:  10\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>animeTitle</th>\n      <th>animeDescription</th>\n      <th>animeURL</th>\n      <th>animeScores</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>One Piece</td>\n      <td>Gol D. Roger was known as the \"Pirate King,\" t...</td>\n      <td>https://myanimelist.net/anime/21/One_Piece\\n</td>\n      <td>0.366997</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>One Piece Movie 1</td>\n      <td>Woonan is the legendary Great Gold Pirate, ear...</td>\n      <td>https://myanimelist.net/anime/459/One_Piece_Mo...</td>\n      <td>0.298815</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Battle Can\u00b2</td>\n      <td>Join this band of femme fatales as they sacrif...</td>\n      <td>https://myanimelist.net/anime/6025/Battle_Can\u00b2\\n</td>\n      <td>0.256860</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Gintama Movie 2: Kanketsu-hen - Yorozuya yo Ei...</td>\n      <td>When Gintoki apprehends a movie pirate at a pr...</td>\n      <td>https://myanimelist.net/anime/15335/Gintama_Mo...</td>\n      <td>0.236275</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>One Piece: Oounabara ni Hirake! Dekkai Dekkai ...</td>\n      <td>The story opens on Pirate Zap's ship, where tw...</td>\n      <td>https://myanimelist.net/anime/1237/One_Piece__...</td>\n      <td>0.191371</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>One Piece Movie 2: Nejimaki-jima no Daibouken</td>\n      <td>Informed by the Thief Brothers his ship has be...</td>\n      <td>https://myanimelist.net/anime/460/One_Piece_Mo...</td>\n      <td>0.161223</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>A-Ko The Versus</td>\n      <td>A-ko and B-ko are bounty hunters in an untamed...</td>\n      <td>https://myanimelist.net/anime/1295/A-Ko_The_Ve...</td>\n      <td>0.156778</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Last Exile: Ginyoku no Fam Movie - Over the Wi...</td>\n      <td>A recap film with some new scenes.\\n\\n\\nThe Sk...</td>\n      <td>https://myanimelist.net/anime/31866/Last_Exile...</td>\n      <td>0.150042</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Slayers Revolution</td>\n      <td>Having lost the Sword of Light in the previous...</td>\n      <td>https://myanimelist.net/anime/4028/Slayers_Rev...</td>\n      <td>0.145129</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>One Piece 3D2Y: Ace no shi wo Koete! Luffy Nak...</td>\n      <td>After suffering great personal loss during the...</td>\n      <td>https://myanimelist.net/anime/25161/One_Piece_...</td>\n      <td>0.133564</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n```python\nquery = input(\"Insert the query: \")\nk = int(input(\"Insert k: \"))\n\nsearch_engine2(query, k, tfIdf)\n```\n\n    Insert the query:  sasuke naruto sakura\n    Insert k:  10\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>animeTitle</th>\n      <th>animeDescription</th>\n      <th>animeURL</th>\n      <th>animeScores</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Naruto: Shippuuden - Shippuu! \"Konoha Gakuen\" Den</td>\n      <td>Naruto school special.\\n\\n\\nNaruto is a new co...</td>\n      <td>https://myanimelist.net/anime/4134/Naruto__Shi...</td>\n      <td>0.664881</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Naruto: The Cross Roads</td>\n      <td>The operation to find a missing person goes aw...</td>\n      <td>https://myanimelist.net/anime/7367/Naruto__The...</td>\n      <td>0.597544</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Naruto: Shippuuden Movie 6 - Road to Ninja</td>\n      <td>Returning home to Konohagakure, the young ninj...</td>\n      <td>https://myanimelist.net/anime/13667/Naruto__Sh...</td>\n      <td>0.465943</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Naruto Soyokazeden Movie: Naruto to Mashin to ...</td>\n      <td>While enjoying a barbecue alongside team membe...</td>\n      <td>https://myanimelist.net/anime/10659/Naruto_Soy...</td>\n      <td>0.390676</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Cardcaptor Sakura: Clear Card-hen</td>\n      <td>With all of the Clow Cards recaptured and chan...</td>\n      <td>https://myanimelist.net/anime/33354/Cardcaptor...</td>\n      <td>0.370162</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>135</th>\n      <td>Ultra Maniac OVA</td>\n      <td>Ayu Tateishi is a popular second-year student ...</td>\n      <td>https://myanimelist.net/anime/179/Ultra_Maniac...</td>\n      <td>0.036666</td>\n    </tr>\n    <tr>\n      <th>136</th>\n      <td>Ultra Maniac</td>\n      <td>Fantasies and miracles never interested Ayu Ta...</td>\n      <td>https://myanimelist.net/anime/178/Ultra_Maniac\\n</td>\n      <td>0.035309</td>\n    </tr>\n    <tr>\n      <th>137</th>\n      <td>Binbougami ga!</td>\n      <td>Ichiko Sakura lives life on easy mode. Blessed...</td>\n      <td>https://myanimelist.net/anime/13535/Binbougami...</td>\n      <td>0.033649</td>\n    </tr>\n    <tr>\n      <th>138</th>\n      <td>Aoi Bungaku Series</td>\n      <td>Ningen Shikkaku\\n\\nA high school student seeks...</td>\n      <td>https://myanimelist.net/anime/7193/Aoi_Bungaku...</td>\n      <td>0.032797</td>\n    </tr>\n    <tr>\n      <th>139</th>\n      <td>Ani*Kuri15</td>\n      <td>15 one-minute shorts created by various people...</td>\n      <td>https://myanimelist.net/anime/2832/AniKuri15\\n</td>\n      <td>0.030949</td>\n    </tr>\n  </tbody>\n</table>\n<p>140 rows \u00d7 4 columns</p>\n</div>\n\n\n# [EX3] Define a new score!\n\n\n```python\n# Libraries\n```\n\n\n```python\nimport requests\nimport pandas as pd\nimport os\nimport re\nimport math\nimport numpy as np\nfrom tqdm import tqdm\nfrom difflib import SequenceMatcher\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nfrom collections import Counter\nfrom natsort import natsorted\n```\n\n\n```python\ndef dateparse(time_in_secs):\n    return pd.to_datetime(time_in_secs, unit='s')\n```\n\n\n```python\nepisodes = []\ntitle=[]\ntypes = []\npopularity = []\ndescription=[]\nrelated=[]\nrelease=[]\nanimeScore=[]\nvoices=[]\nstaff=[]\nranks=[]\n\nwith open(\"./anime_url.txt\", \"r\", encoding = \"utf-8\") as f:\n    urls = f.readlines()\n# positioning\nfolder = r\"./tsv_anime_2/\"\n# iter over the file\ndtypes = {'animeTitle': 'str', 'animeType': 'str' }\nfor anime in tqdm(natsorted(os.listdir(folder))):\n    df = pd.read_csv(folder+anime, sep = \"\\t\", dtype=dtypes, parse_dates=['releaseDate','endDate'],date_parser=pd.to_datetime)   \n    #print(df.info())\n    #print(type(df[\"releaseDate\"][0]))\n    episodes.append(df[\"animeNumEpisode\"][0])\n    types.append(df[\"animeType\"][0])\n    popularity.append(df[\"animePopularity\"][0])\n    description.append(df[\"animeDescription\"][0])\n    title.append(df[\"animeTitle\"][0])\n    related.append(df[\"animeRelated\"][0])\n    release.append(df[\"releaseDate\"][0])\n    animeScore.append(df[\"animeScore\"][0])\n    voices.append(df[\"animeVoices\"][0])\n    staff.append(df[\"animeStaff\"][0])\n    ranks.append(df[\"animeRank\"][0])\ntype(release[0])\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 19116/19116 [02:39<00:00, 119.50it/s]\n\n\n\n\n\n    pandas._libs.tslibs.timestamps.Timestamp\n\n\n\n\n```python\ndf.info()\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n    RangeIndex: 1 entries, 0 to 0\n    Data columns (total 15 columns):\n     #   Column            Non-Null Count  Dtype         \n    ---  ------            --------------  -----         \n     0   animeTitle        1 non-null      object        \n     1   animeType         1 non-null      object        \n     2   animeNumEpisode   1 non-null      int64         \n     3   releaseDate       1 non-null      datetime64[ns]\n     4   endDate           0 non-null      datetime64[ns]\n     5   animeNumMembers   1 non-null      int64         \n     6   animeScore        0 non-null      float64       \n     7   animeUsers        0 non-null      float64       \n     8   animeRank         0 non-null      float64       \n     9   animePopularity   1 non-null      int64         \n     10  animeDescription  1 non-null      object        \n     11  animeRelated      1 non-null      object        \n     12  animeCharacters   1 non-null      object        \n     13  animeVoices       1 non-null      object        \n     14  animeStaff        0 non-null      float64       \n    dtypes: datetime64[ns](2), float64(4), int64(3), object(6)\n    memory usage: 248.0+ bytes\n\n\nWe changed the datatype in these lists because there were nan elements inside them.\n\n\n```python\ndef change(l):\n    for i in range(len(l)):\n        if(type(l[i])!=str):\n            l[i]=l[i].item()\n            l[i]=str(l[i])\n```\n\n\n```python\nchange(staff)\nchange(voices)\n```\n\n### Cosine function\n\nWe used \"cosine\" to determine how similar documents, regardless of their size, are to the query entered and correspondence, the similarity of texts to each other. We used this function to find similarities in these metrics: (Description, AnimeStaff, Voices,Type) We also used the \"similar\" function, showing an alternative way of finding the similarity and used this function to find the metric: Related\n\n\n```python\nWORD = re.compile(r\"\\w+\")\n```\n\n\n```python\ndef cosine_text(input_text,comparison_text):\n    if input_text == \"\":\n        return 0\n    else:\n        intersection = set(input_text.keys()) & set(comparison_text.keys())\n        numerator = sum([input_text[x] * comparison_text[x] for x in intersection])\n        sum1 = sum([input_text[x] ** 2 for x in list(input_text.keys())])\n        sum2 = sum([input_text[x] ** 2 for x in list(comparison_text.keys())])\n        denominator = math.sqrt(sum1) * math.sqrt(sum2)\n        if not denominator:\n            return 0.0\n        else:\n            return float(numerator) / denominator  \n```\n\n\n```python\ndef text_to_vector(text):\n    words = WORD.findall(text)\n    return Counter(words)\n```\n\n\n```python\ndef cosine(input_text,comparison_text):\n    vector1 = text_to_vector(input_text)\n    vector2 = text_to_vector(comparison_text)\n    cosine = cosine_text(vector1, vector2)\n    return(cosine)\n```\n\n\n```python\ndef similar(a, b):\n    if(a==\"\"):\n        return 0\n    else:\n        return SequenceMatcher(None, a, b).ratio()\n```\n\n### Num_Episode metric\n\nFor num_episode variable, we have classified the amount of anime into 4 categories:\n0-is film,1 is short,2 is medium,3 is large.First we define the category of the input data and Calculated their differences. Depending on the number of episodes, we will be able to determine the greatest suitable anime by length\n\n\n\n```python\ndef identify_category(input_eps,next_eps):\n    if(type(next_eps) == str):\n        return 0\n    else:\n        #Input_eps\n        if(input_eps==1):\n            category1=0\n        elif(input_eps<25 and input_eps>=8):\n            category1=1\n        elif(input_eps<65 and input_eps>=25):\n            category1=2\n        else:\n            category=3\n       #Next_eps \n        if(next_eps==1):\n            category2=0\n        elif(next_eps<25 and input_eps>=8):\n            category2=1\n        elif(next_eps<65 and input_eps>=25):\n            category2=2\n        else:\n            category2=3\n        return(category1,category2)\n```\n\n\n```python\ndef episode_score(input_eps,next_eps):\n    if(input_eps==0 or type(next_eps)==str):\n        return 0\n    else:\n        category=(identify_category(input_eps,next_eps))\n        if(category[0]==category[1]):\n            return 1\n        elif(abs(category[0]-category[1])==1):\n            return 0.66\n        elif(abs(category[0]-category[1])>1):\n            return 0.33\n        else:\n            return 0\n```\n\n## Rank\n\nThe logic of ranking metric is that we push away from the request, if the query anime was given to us by the top 100 anime, we  are looking for a suitable one from the top 100 or from the top 1000\n\n\n```python\ndef ranking(input_rank,next_rank):\n    if input_rank == 0:\n        return 0\n    else:\n        diff=abs(input_rank-next_rank)\n        if(diff<=100):\n            return 1\n        elif(diff>100 and diff<=1000):\n            return 0.66\n        else:\n            return 0.33\n```\n\n### Date\n\nWe created a date metric to determine how late and newer the anime is with the query being compared.\n\n\n```python\ndef date(input_date,releaseDate):\n    if(input_date==0 or input_date==\"\"):\n        return 0\n    else:\n        diff = (abs(datetime.strptime(input_date,'%Y-%m-%d')-releaseDate))\n        days = diff.days\n        #Anime came out in the same season\n        if(days>0 and days<=100):\n            return 1\n        #Differences in 1 year\n        elif(days>100 and days<=300):\n            return 0.5\n        return(0)\n\n#print(date(date_query,release[0]))\n```\n\n## Popularity metric\n\nThe logic of this metric is similar to the rank metric.\n\n\n```python\ndef score_pop(input_pop,next_pop):\n    if input_pop == 0:\n        return 0\n    else:\n        diff=abs(input_pop-next_pop)\n        if(input_pop<=100 and diff<=100):\n            return 0.66\n        elif(input_pop > 100 and input_pop <= 1000 and diff > 100):\n            return 0.44\n        else:\n            return 0.22\n```\n\n## animeScore metric\n\nWe also categorized the anime by a rating, like metric number episodes:1 High,  2 Average, 3 Low\n\n\n```python\ndef identify_s(input_s,next_s):\n    if(input_s>=8):\n        category1=1\n    elif(input_s<8 and input_s>=5):\n        category1=2\n    else:\n        category1=3\n       \n    if(next_s>=8):\n        category2=1\n    elif(next_s<8 and next_s>=5):\n        category2=2\n    else:\n        category2=3\n    return(category1,category2)\n```\n\n\n```python\ndef score_s(input_s,next_s):\n    if input_s == 0:\n        return 0\n    else:\n        category = identify_s(input_s,next_s)\n        if(category[0]==category[1]):\n            return 1\n        elif(abs(category[0]-category[1])==1):\n            return 0.66\n        elif(abs(category[0]-category[1])>1):\n            return 0.33\n        else:\n            return 0\n```\n\n### Final score metric\n\nThe final score is our final function that calculates the score. We have used all of the above functions to determine the total weight of each metric. For our convenience, we have divided all the metrics into two functions. In the first function, we have an unusual formula, since we have chosen such metrics as animeTitle and animeDescription as the most basic and especially influencing the function. For example the metric animeTitle is multiplied by 4, animeDescription is multiplied by 1.5. We multiplied such information as Voices, Staff, etc. by 0.3 since they do not have a very strong influence on the search.\n\n\n```python\ndef final_score1(i,input_type,next_type,input_eps,next_eps,input_title,next_title,input_related,next_related,input_description,next_description,input_date,next_date,input_voice,next_voice,input_staff,next_staff):\n    #print(i)\n    #Type variable\n    #print(title[i])\n    score1=cosine(input_type,next_type)\n    #print(\"Type_score\",score1)\n    #Episodes variable\n    score2=episode_score(input_eps,next_eps)\n    #print(\"Episode_score\",score2)\n    #Title variable\n    score3=cosine(input_title,next_title)\n    #print(\"Title_score\",score3)\n    #Related anime variable\n    score4=similar(input_related,next_related)\n    #print(\"Related_score\",score4)\n    #Description variable\n    score5=cosine(input_description,next_description)\n    #print(\"Description_score\",score5)\n    #Season date variable\n    score6=date(input_date,next_date)\n    #print(\"Season_score\",score6)\n    #Voices variable\n    score7=cosine(input_voice,next_voice)\n    #print(\"Voice\",score7)\n    #Staff  variable\n    score8=cosine(input_staff,next_staff)\n    #print(\"Staff\",score8)\n    return(score1*0.5+score2*0.5+score3*4+score4+score5*1.5+score6*0.5+score7*0.3+score8*0.3)\n```\n\n\n```python\ndef final_score2(input_rank,next_rank,input_pop,next_pop,input_s,next_s):\n    #Rank\n    score9 = ranking(input_rank,next_rank)\n    #print(\"Rank\",score9)\n    #Popularity\n    score10=score_pop(input_pop,next_pop)\n    #print(\"Popular\",score10)\n    #animeScore\n    score11=score_s(input_s,next_s)\n    #print(\"animeScore\",score11)\n    return(score9+score10+score11)\n\n```\n\nWe examined 3 cases of writing a request by a user. The first example shows us information in which the user made a request for only one attribute, in the second case we added several attributes to our request and we see how our function has become better to select and recommend anime. In the very last case, we wrote all the necessary information and see an excellent match.\n\n\n```python\ntitle_query=\"\"\ntype_query=\"\"\nep_query=0\nrelated_query=\"\"\ndescription_query=\"Saske Sakura Naruto\"\ndate_query=0\nvoices_query=\"\"\nstaff_query=\"\"\nrank_query=0\npop_query=0\nscore_query=0\nscores=[]\n\nfor i in range(len(episodes)):\n    score1=final_score1(i,type_query,types[i],ep_query,episodes[i],title_query,title[i],related_query,related[i],description_query,description[i],date_query,release[0],voices_query,voices[i],staff_query,staff[i])\n    score2=final_score2(rank_query,ranks[i],pop_query,popularity[i],score_query,animeScore[i])\n    score=score1+score2\n    scores.append([score,i])\nsorted_scores=sorted(scores, reverse=True)\n\n\ndf_score=[]\ndf_title=[]\ndf_urls=[]\ndf_l=[]\nfor i in range(len(episodes)):\n    df_score.append(sorted_scores[i][0])\n    df_title.append(title[sorted_scores[i][1]])\n    df_urls.append(urls[sorted_scores[i][1]])\n    df_l.append(sorted_scores[i][1])\ndf1 = pd.DataFrame (df_score, columns = ['Score:'])\ndf2 = pd.DataFrame (df_title, columns = ['Title:'])\ndf3 = pd.DataFrame (df_urls, columns = ['URL:'])\ndf4 = pd.DataFrame (df_l, columns = ['Rank:'])\npdList = [df1, df2, df3,df4 ]  \nnew_df = pd.concat(pdList, axis=1)\ndisplay(new_df)\n```\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Score:</th>\n      <th>Title:</th>\n      <th>URL:</th>\n      <th>Rank:</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>6.928203</td>\n      <td>Cardcaptor Sakura: Clear Card-hen</td>\n      <td>https://myanimelist.net/anime/33354/Cardcaptor...</td>\n      <td>1179</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>6.123724</td>\n      <td>Naruto: Shippuuden Movie 6 - Road to Ninja</td>\n      <td>https://myanimelist.net/anime/13667/Naruto__Sh...</td>\n      <td>1124</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>5.196152</td>\n      <td>Cardcaptor Sakura</td>\n      <td>https://myanimelist.net/anime/232/Cardcaptor_S...</td>\n      <td>363</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>5.196152</td>\n      <td>Cardcaptor Sakura Movie 2: Fuuin Sareta Card</td>\n      <td>https://myanimelist.net/anime/372/Cardcaptor_S...</td>\n      <td>321</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>4.330127</td>\n      <td>Boruto: Naruto Next Generations</td>\n      <td>https://myanimelist.net/anime/34566/Boruto__Na...</td>\n      <td>9054</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>19111</th>\n      <td>0.000000</td>\n      <td>Fruits Basket: The Final</td>\n      <td>https://myanimelist.net/anime/42938/Fruits_Bas...</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>19112</th>\n      <td>0.000000</td>\n      <td>Steins;Gate</td>\n      <td>https://myanimelist.net/anime/9253/Steins_Gate\\n</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>19113</th>\n      <td>0.000000</td>\n      <td>Shingeki no Kyojin Season 3 Part 2</td>\n      <td>https://myanimelist.net/anime/38524/Shingeki_n...</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>19114</th>\n      <td>0.000000</td>\n      <td>Gintama\u00b0</td>\n      <td>https://myanimelist.net/anime/28977/Gintama\u00b0\\n</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>19115</th>\n      <td>0.000000</td>\n      <td>Fullmetal Alchemist: Brotherhood</td>\n      <td>https://myanimelist.net/anime/5114/Fullmetal_A...</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n<p>19116 rows \u00d7 4 columns</p>\n</div>\n\n\n\n```python\ntitle_query=\"Death Note\"\ntype_query=\"TV\"\nep_query=51\nrelated_query=\"\"\ndescription_query=\"Death Note L Kira\"\ndate_query=\"\"\nvoices_query=\"\"\nstaff_query=\"\"\nrank_query=1\npop_query=0\nscore_query=9.21\nscores=[]\n\nfor i in range(len(episodes)):\n    score1=final_score1(i,type_query,types[i],ep_query,episodes[i],title_query,title[i],related_query,related[i],description_query,description[i],date_query,release[0],voices_query,voices[i],staff_query,staff[i])\n    score2=final_score2(rank_query,ranks[i],pop_query,popularity[i],score_query,animeScore[i])\n    score=score1+score2\n    scores.append([score,i])\nsorted_scores=sorted(scores, reverse=True)\n\n\ndf_score=[]\ndf_title=[]\ndf_urls=[]\ndf_l=[]\nfor i in range(len(episodes)):\n    df_score.append(sorted_scores[i][0])\n    df_title.append(title[sorted_scores[i][1]])\n    df_urls.append(urls[sorted_scores[i][1]])\n    df_l.append(sorted_scores[i][1])\ndf1 = pd.DataFrame (df_score, columns = ['Score:'])\ndf2 = pd.DataFrame (df_title, columns = ['Title:'])\ndf3 = pd.DataFrame (df_urls, columns = ['URL:'])\ndf4 = pd.DataFrame (df_l, columns = ['Rank:'])\npdList = [df1, df2, df3,df4 ]  \nnew_df = pd.concat(pdList, axis=1)\ndisplay(new_df)\n```\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Score:</th>\n      <th>Title:</th>\n      <th>URL:</th>\n      <th>Rank:</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>10.897114</td>\n      <td>Death Note</td>\n      <td>https://myanimelist.net/anime/1535/Death_Note\\n</td>\n      <td>64</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>7.918076</td>\n      <td>Death Note: Rewrite</td>\n      <td>https://myanimelist.net/anime/2994/Death_Note_...</td>\n      <td>1086</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>7.570000</td>\n      <td>Soul Eater</td>\n      <td>https://myanimelist.net/anime/3588/Soul_Eater\\n</td>\n      <td>760</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>6.068427</td>\n      <td>Death Parade</td>\n      <td>https://myanimelist.net/anime/28223/Death_Para...</td>\n      <td>337</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>5.398427</td>\n      <td>Hinako Note</td>\n      <td>https://myanimelist.net/anime/33948/Hinako_Note\\n</td>\n      <td>4764</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>19111</th>\n      <td>0.825000</td>\n      <td>Hana no Hanashi</td>\n      <td>https://myanimelist.net/anime/30393/Hana_no_Ha...</td>\n      <td>11458</td>\n    </tr>\n    <tr>\n      <th>19112</th>\n      <td>0.825000</td>\n      <td>Megumi to Taiyou II: Kajuu Gummi Tweet Mystery...</td>\n      <td>https://myanimelist.net/anime/25267/Megumi_to_...</td>\n      <td>11453</td>\n    </tr>\n    <tr>\n      <th>19113</th>\n      <td>0.825000</td>\n      <td>Sougiya to Inu</td>\n      <td>https://myanimelist.net/anime/28953/Sougiya_to...</td>\n      <td>11433</td>\n    </tr>\n    <tr>\n      <th>19114</th>\n      <td>0.825000</td>\n      <td>Ishindenshin Shiyou</td>\n      <td>https://myanimelist.net/anime/30405/Ishindensh...</td>\n      <td>11424</td>\n    </tr>\n    <tr>\n      <th>19115</th>\n      <td>0.825000</td>\n      <td>TOTO Green Challenge</td>\n      <td>https://myanimelist.net/anime/25377/TOTO_Green...</td>\n      <td>11405</td>\n    </tr>\n  </tbody>\n</table>\n<p>19116 rows \u00d7 4 columns</p>\n</div>\n\n\n\n```python\ntitle_query=\"Gintama\"\ntype_query=\"TV\"\nep_query=51\nrelated_query=\"Gintama Movie 2: Kanketsu-hen - Yorozuya yo Eien Nare, Gintama': Enchousen\"\ndescription_query=\"Gintoki, Shinpachi, and Kagura return as the fun-loving but broke members of the Yorozuya team! Living in an alternate-reality Edo, where swords are prohibited and alien overlords have conquered Japan, they try to thrive on doing whatever work they can get their hands on. However, Shinpachi and Kagura still haven't been paid... Does Gin-chan really spend all that cash playing pachinko?Meanwhile, when Gintoki drunkenly staggers home one night, an alien spaceship crashes nearby. A fatally injured crew member emerges from the ship and gives Gintoki a strange, clock-shaped device, warning him that it is incredibly powerful and must be safeguarded. Mistaking it for his alarm clock, Gintoki proceeds to smash the device the next morning and suddenly discovers that the world outside his apartment has come to a standstill. With Kagura and Shinpachi at his side, he sets off to get the device fixed; though, as usual, nothing is ever that simple for the Yorozuya team.\"\ndate_query=\"2015-06-21\"\nvoices_query=\"Sugita, Tomokazu Kugimiya, Rie Sakaguchi, Daisuke Ishida, Akira Nakai, Kazuya\"\nstaff_query=\"Fujita, Youichi Director, Storyboard, Planning Miyawaki, Chizuru Director, Storyboard, Key Animation Takamatsu, ShinjiSound Director\"\nrank_query=2\npop_query=337\nscore_query=9.09\nscores=[]\n\nfor i in range(len(episodes)):\n    score1=final_score1(i,type_query,types[i],ep_query,episodes[i],title_query,title[i],related_query,related[i],description_query,description[i],date_query,release[0],voices_query,voices[i],staff_query,staff[i])\n    score2=final_score2(rank_query,ranks[i],pop_query,popularity[i],score_query,animeScore[i])\n    score=score1+score2\n    scores.append([score,i])\nsorted_scores=sorted(scores, reverse=True)\n\n\ndf_score=[]\ndf_title=[]\ndf_urls=[]\ndf_l=[]\nfor i in range(len(episodes)):\n    df_score.append(sorted_scores[i][0])\n    df_title.append(title[sorted_scores[i][1]])\n    df_urls.append(urls[sorted_scores[i][1]])\n    df_l.append(sorted_scores[i][1])\ndf1 = pd.DataFrame (df_score, columns = ['Score:'])\ndf2 = pd.DataFrame (df_title, columns = ['Title:'])\ndf3 = pd.DataFrame (df_urls, columns = ['URL:'])\ndf4 = pd.DataFrame (df_l, columns = ['Rank:'])\npdList = [df1, df2, df3,df4 ]  \nnew_df = pd.concat(pdList, axis=1)\ndisplay(new_df)\n```\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Score:</th>\n      <th>Title:</th>\n      <th>URL:</th>\n      <th>Rank:</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>12.220339</td>\n      <td>Gintama: Yorinuki Gintama-san on Theater 2D</td>\n      <td>https://myanimelist.net/anime/21899/Gintama__Y...</td>\n      <td>136</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>9.910090</td>\n      <td>Gintama\u00b0</td>\n      <td>https://myanimelist.net/anime/28977/Gintama\u00b0\\n</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>9.640334</td>\n      <td>Gintama'</td>\n      <td>https://myanimelist.net/anime/9969/Gintama\\n</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>9.486018</td>\n      <td>Gintama.: Shirogane no Tamashii-hen</td>\n      <td>https://myanimelist.net/anime/36838/Gintama__S...</td>\n      <td>24</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>9.304666</td>\n      <td>Gintama.</td>\n      <td>https://myanimelist.net/anime/34096/Gintama\\n</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>19113</th>\n      <td>1.265000</td>\n      <td>Playground</td>\n      <td>https://myanimelist.net/anime/23053/Nisou_no_K...</td>\n      <td>11504</td>\n    </tr>\n    <tr>\n      <th>19114</th>\n      <td>1.265000</td>\n      <td>Kakegae no</td>\n      <td>https://myanimelist.net/anime/31831/Fantasy\\n</td>\n      <td>11498</td>\n    </tr>\n    <tr>\n      <th>19115</th>\n      <td>1.265000</td>\n      <td>Fantasy</td>\n      <td>https://myanimelist.net/anime/31759/Hakubutsus...</td>\n      <td>11497</td>\n    </tr>\n    <tr>\n      <th>19116</th>\n      <td>1.265000</td>\n      <td>Hakubutsushi</td>\n      <td>https://myanimelist.net/anime/29395/Fafa_Movie\\n</td>\n      <td>11496</td>\n    </tr>\n    <tr>\n      <th>19117</th>\n      <td>1.265000</td>\n      <td>Odoroki Ban</td>\n      <td>https://myanimelist.net/anime/4394/Norakuro_Go...</td>\n      <td>11462</td>\n    </tr>\n  </tbody>\n</table>\n<p>19118 rows \u00d7 4 columns</p>\n</div>\n\n\n# [EX4] BONUS: Understanding the anime's reviews\n\n\n```python\n# core libraries\nimport requests\nfrom tqdm import tqdm\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nfrom datetime import datetime\nimport re\nimport vaderSentiment\nimport ast\nfrom scipy.stats import pearsonr\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer \n\nimport os\nfrom natsort import natsorted\n```\n\nThe reviews of each anime for a number >3 (we need 5) are under the __./reviews__ site. We need to collect the html of that page.\n\nWe are now collecting the url of each anime.\n\n\n```python\nurl_anime = []\nwith open(\"./anime_url.txt\", \"r\",  encoding='utf-8') as f:\n    for i,line in enumerate(f):\n        url = line.split(\"\\n\")[0]\n        url_anime.append(url+\"/reviews\")\n```\n\n\n```python\nfor url in tqdm(url_anime):\n    response = requests.get(url)\n    if response.status_code == 200:\n        filename = r\"./Anime_reviews\"+\"/anime_\"+str(i+1)+\".html\"\n        with open(filename,'w', encoding='utf-8') as f:\n            f.write(response.text)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1001/1001 [13:30<00:00,  1.23it/s]\n\n\nGrabbing the first 5 reviews of each anime + the \"scarbbing\" of Title, Type, numEpisode and score.\n\nI will store them in a dataframe: each row contain the anime and 1 reviews\n\n\n```python\ndef scrabbing(soup,anime_info):\n    # title\n    title = soup.find(\"h1\", attrs = {\"class\": \"title-name h1_bold_none\"}).string\n    # other\n    for h2 in soup.select('h2:has(+div)'):\n        # I want the <h2> Information </h2> only\n        if h2.text == \"Information\" :\n            # iter over the next 4 <div> of Information, i go this way because\n            # 1) i want to skip the \"Status\": is the 3th div\n            # 2) more clear\n            for inform in h2.find_all_next(\"div\", attrs = {\"class\": \"spaceit_pad\"}, limit = 4):\n                # Type\n                if inform.contents[1].string == \"Type:\":\n                    Type = inform.get_text(separator=\" \", strip=True).split()[-1] \n                # nEpisodes\n                try:\n                    if inform.contents[1].string == \"Episodes:\":\n                        nEpisodes = int(inform.get_text(separator=\" \", strip=True).split()[-1])\n                except:\n                    nEpisodes = None\n    # score\n    #animeScore\n    score = soup.find(\"div\", attrs = {\"class\": \"fl-l score\", \"data-title\": \"score\"})\n    try:\n        # is a number\n        score = float(score.contents[0].string)\n    except:\n        # is N/A\n        score = None\n        \n    anime_info.extend((title,Type,nEpisodes))\n    return anime_info\n```\n\n\n```python\nfolder = r\"./Anime_reviews/\"\nfolder2 = r\"./tsv_anime/\"\n# columns of the attributes\nattrs = [\"animeTitle\", \"animeType\", \"animeNumEpisode\", \"animeScore\", \"animeReviews\"]\nlist_of_anime = []\nfor anime in tqdm(natsorted(os.listdir(folder))):\n    with open(folder+anime, \"r\",  encoding='utf-8') as fp:\n        soup = BeautifulSoup(fp, \"html.parser\")\n    \n    # put in the right tag\n    anime_reviews = soup.find_all(\"div\", attrs = {\"class\": \"borderDark\"})\n    # find if an anime as a number of review >=5, if so I want only the first 5\n    if len(anime_reviews) >= 5:\n        anime_reviews = anime_reviews[:5]\n    \n    reviews_list = []\n    # iterate over the reviews\n    for rev in anime_reviews:\n        anime_info = []\n        \n        # take the anime name\n        name = re.split(\".html\",anime)\n        anime_name = str(name[0])\n        # take the tsv with the anime score\n        dff = pd.read_csv(folder2+anime_name+\".tsv\", sep = \"\\t\")\n        df = dff[\"animeScore\"]\n        # append the various attributes\n        anime_info + scrabbing(soup, anime_info)\n        anime_info.append(list(df)[0])\n        # take the text\n        text1 = rev.select('div.spaceit.textReadability.word-break.pt8')[0].contents[2].strip()\n        l1 = len(text1.split())\n        # 50 words are at least two row of a text (3 row are at least 77)\n        # counting using line in MyAnimeList space text\n        # if we aren't enough words (three line) we continue to the next paragraph or we stop if there isn't\n        if not l1 >= 50:\n            try:\n                text2 = rev.select('div.spaceit.textReadability.word-break.pt8')[0].contents[3].text.strip()\n                maxlen = 77-l1\n                # take only a total of 3 lines\n                text1 = text1 + \" \".join(text2.split()[:maxlen])\n            except:\n                text1 = text1\n        anime_info.append(text1)\n        list_of_anime.append(anime_info)\n\n\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 197/197 [00:51<00:00,  3.85it/s]\n\n\n\n```python\n# Creating the DataFrame\ndf = pd.DataFrame(list_of_anime, columns = attrs)\n# Creating the tsv file, take the anime number (the id)\n#name = re.sub(\".html\",\"\",anime)\ndf.to_csv(\"./reviews_anime.csv\", index = False)\n```\n\n\n```python\ndf[:5]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>animeTitle</th>\n      <th>animeType</th>\n      <th>animeNumEpisode</th>\n      <th>animeScore</th>\n      <th>animeReviews</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Fullmetal Alchemist: Brotherhood</td>\n      <td>TV</td>\n      <td>64.0</td>\n      <td>9.16</td>\n      <td>First of all, I have seen the original FMA and...</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Fullmetal Alchemist: Brotherhood</td>\n      <td>TV</td>\n      <td>64.0</td>\n      <td>9.16</td>\n      <td>Fullmetal Alchemist: Brotherhood gets an immen...</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Fullmetal Alchemist: Brotherhood</td>\n      <td>TV</td>\n      <td>64.0</td>\n      <td>9.16</td>\n      <td>Adaptations have long been a thorn in the side...</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Fullmetal Alchemist: Brotherhood</td>\n      <td>TV</td>\n      <td>64.0</td>\n      <td>9.16</td>\n      <td>Overview:FMA Brotherhood is an anime that need...</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Fullmetal Alchemist: Brotherhood</td>\n      <td>TV</td>\n      <td>64.0</td>\n      <td>9.16</td>\n      <td>Since I couldn't find any legitimate objective...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nWe collect only the first 180 anime reviews due to time problem. Here the results.\n\nIn order to make sentiment analysis we calculated the compound value of every review using the vaderSentiment libray and we classified as \"positive\" the reviews that have a compound value greater than 0.05, as \"negative\" the reviews that have a compound value lower than - 0.05, and as \"neutral\" otherwise.\n\n\n```python\nvs = list()\nanalyzer = SentimentIntensityAnalyzer()\nfor i in range (df.shape[0]):\n    vs.append(analyzer.polarity_scores(df[\"animeReviews\"][i]))             \n#[vs.append(analyzer.polarity_scores(df[\"animeReviews\"][i])) for i in range (df.shape[0])]\n```\n\n\n```python\nvs = pd.DataFrame(vs)\ndf[\"compound\"] = vs[\"compound\"]\ndf.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>animeTitle</th>\n      <th>animeType</th>\n      <th>animeNumEpisode</th>\n      <th>animeScore</th>\n      <th>animeReviews</th>\n      <th>compound</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Fullmetal Alchemist: Brotherhood</td>\n      <td>TV</td>\n      <td>64.0</td>\n      <td>9.16</td>\n      <td>First of all, I have seen the original FMA and...</td>\n      <td>0.5749</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Fullmetal Alchemist: Brotherhood</td>\n      <td>TV</td>\n      <td>64.0</td>\n      <td>9.16</td>\n      <td>Fullmetal Alchemist: Brotherhood gets an immen...</td>\n      <td>0.9783</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Fullmetal Alchemist: Brotherhood</td>\n      <td>TV</td>\n      <td>64.0</td>\n      <td>9.16</td>\n      <td>Adaptations have long been a thorn in the side...</td>\n      <td>0.1531</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Fullmetal Alchemist: Brotherhood</td>\n      <td>TV</td>\n      <td>64.0</td>\n      <td>9.16</td>\n      <td>Overview:FMA Brotherhood is an anime that need...</td>\n      <td>0.4141</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Fullmetal Alchemist: Brotherhood</td>\n      <td>TV</td>\n      <td>64.0</td>\n      <td>9.16</td>\n      <td>Since I couldn't find any legitimate objective...</td>\n      <td>-0.5023</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\ndef sentimentassignment (compound):\n    sent = []\n    for i in range (len(compound)):\n        if (compound[i] < (-0.05)):\n            sent.append(\"negative\")\n        elif (compound[i] > 0.05):\n            sent.append(\"positive\")\n        else:\n            sent.append(\"neutral\")\n    return sent\n```\n\n\n```python\nsentiment = sentimentassignment(df[\"compound\"]) \ndf[\"sentiment\"] = sentiment\ndf.head()\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>animeTitle</th>\n      <th>animeType</th>\n      <th>animeNumEpisode</th>\n      <th>animeScore</th>\n      <th>animeReviews</th>\n      <th>compound</th>\n      <th>sentiment</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Fullmetal Alchemist: Brotherhood</td>\n      <td>TV</td>\n      <td>64.0</td>\n      <td>9.16</td>\n      <td>First of all, I have seen the original FMA and...</td>\n      <td>0.5749</td>\n      <td>positive</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Fullmetal Alchemist: Brotherhood</td>\n      <td>TV</td>\n      <td>64.0</td>\n      <td>9.16</td>\n      <td>Fullmetal Alchemist: Brotherhood gets an immen...</td>\n      <td>0.9783</td>\n      <td>positive</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Fullmetal Alchemist: Brotherhood</td>\n      <td>TV</td>\n      <td>64.0</td>\n      <td>9.16</td>\n      <td>Adaptations have long been a thorn in the side...</td>\n      <td>0.1531</td>\n      <td>positive</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Fullmetal Alchemist: Brotherhood</td>\n      <td>TV</td>\n      <td>64.0</td>\n      <td>9.16</td>\n      <td>Overview:FMA Brotherhood is an anime that need...</td>\n      <td>0.4141</td>\n      <td>positive</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Fullmetal Alchemist: Brotherhood</td>\n      <td>TV</td>\n      <td>64.0</td>\n      <td>9.16</td>\n      <td>Since I couldn't find any legitimate objective...</td>\n      <td>-0.5023</td>\n      <td>negative</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n**1. What Anime Type are the most popular based on your analysis?**\n\n\n```python\ndf[df.sentiment == \"positive\"][\"animeType\"].value_counts()\n```\n\n\n\n\n    TV         512\n    Movie      161\n    ONA         36\n    OVA         26\n    Special     13\n    Music        5\n    Name: animeType, dtype: int64\n\n\n\nThe most popular Anime Type is **TV**.\n\n**2.Does the number of episodes has any impact on the sentiment of the users?**\n\n\n```python\ndf1 = df.dropna()\ncoeff = pearsonr(df1[\"animeNumEpisode\"], df1[\"compound\"])\ncoeff[0]\n```\n\n\n\n\n    0.03979874058402419\n\n\n\n\n```python\nplt.scatter(df1[\"animeNumEpisode\"], df1[\"compound\"], alpha=0.5)\nplt.show()\n```\n\nThe Pearson's Correlation Coefficient is equal to 0.03979874058402419, so the number of episodes hasn't any impact on the sentiment of the users. \n\n**3. Is your sentiment analysis in line with the scores of the animes? Explain your conclusions.**\n\n\n```python\ncoeff = pearsonr(df1[\"animeScore\"], df1[\"compound\"])\ncoeff[0]\n```\n\n\n\n\n    0.025202294639815187\n\n\n\n\n```python\nplt.scatter(df1[\"animeScore\"], df1[\"compound\"], alpha=0.5)\nplt.show()\n```\n\nNo, there isn't correlation because it's possible that a person\u2019s tastes do not coincide with the overall score of the anime.\n\n# [EX5] Algorithmic Question\n\nYou consult for a personal trainer who has a back-to-back sequence of requests for appointments. A sequence of requests is of the form > **30, 40, 25, 50, 30, 20** where each number is the time that the person who makes the appointment wants to spend. You need to accept some requests, however you need a break between them, so you cannot accept two consecutive requests. For example, **[30, 50, 20]** is an acceptable solution (of duration 100), but **[30, 40, 50, 20]** is not, because 30 and 40 are two consecutive appointments. Your goal is to provide to the personal trainer a schedule that maximizes the total length of the accepted appointments. For example, in the previous instance, the optimal solution is **[40, 50, 20]**, of total duration **110**.\n\n## 5.1. Write an algorithm that computes the acceptable solution with the longest possible duration.\n\n#### FIRST FUNCTION\n\nThe first function **isnot_adj** takes in input two arrays:\n* **possiblesolution** that contains a possible sequence of accepted appointments.\n* **applist** that contains the total sequence of requests. \n\nConsidering all pairs of adjacent elements in possiblesolution and all pairs of adjacent elements in applist, if even only a couple of adjacent elements in the possiblesolution list is also contained within the applist the possible solution that we are considering is wrong and the function **isnot_adj** return **False**. If there aren't common couples of adjacent elements the possible solution is not wrong and the function **isnot_adj** return **True**.\n\ninput : array possiblesolution, array applist\n\ndef isnot_adj (possiblesolution, applist): {\n\n    adj_app = list() empty list\n    adj_sol = list() empty list\n    for i in range (len(applist)):\n        adj_app.append(applist[i], applist[i+1])\n    for j in range (len(possiblesolution)):\n        adj_sol.append(possiblesolution[j], possiblesolution[j+1])\n    for z in range (len(adj_sol)):\n        if(adj_sol[z] in adj_app):\n            res.append(\"False\")\n        else:\n            res.append(\"True\")\n    if (\"False\" in res):\n        return (False)\n    else:\n        return (True)}\n\n#### SECOND FUNCTION\n\nThe second function **optimalSolution** takes in input:\n* **applist** that contains the total sequence of requests. \n\nthe function calculate:\n* **incl** that is the list that contains the sum including the previous element. The first element of incl is equal to the first element of applist, the i-th elements (considering i different to zero) are equal to the last element of excl list + the i-th element of applist.\n* **excl** that is the list that contains the sum excluding the previous element. The fist element of excl is equal to zero, the i-th elements (considering i different to zero) are equal to the maximum value between the penultimate element of incl list and the last element of excl list. \n* **maximum** is calculated after finishing calculating incl and excl for each item in the applist and is equal to the maximum between the last element of incl list and the last element of excl list. This value is the optimal total duration of appointments. \n* **sol** contains the final solution. The final solution is the combination for which the sum of the list elements is equal to maximum and for which the function isnot_adj returns True.\n\ninput: array applist\n\ndef optimalSolution (applist):{\n\n    incl, excl, sol: empty lists\n    for i in range(len(applist)):\n        if (i == 0):\n            incl[0] = applist[0]\n            excl[0] = 0\n        else:\n            incl[i] = excl[-1] + applist[i]\n            excl[i] = max(incl[-2], excl[-1])\n    maximum = max(excl[-1], incl[-1])\n    for i in range (len(applist)):\n        for x in combinations(applist,i):\n            if(sum(x) == maximum and isnot_adj == True):\n                sol.append(x)\n    return maximum, sol}\n\n## 5.2 Implement a program that given in input an instance in the form given above, gives the optimal solution.\n\n\n```python\nimport numpy as np\nfrom more_itertools import pairwise\nfrom itertools import combinations\n```\n\n\n```python\ndef solutions (solution, appointments):\n    adj_app, adj_sol, res = [], [], []\n    [adj_app.append([x,y]) for x,y in pairwise(appointments)]\n    [adj_sol.append([x,y]) for x,y in pairwise(solution)]\n    for z in range (len(adj_sol)):\n        if(adj_sol[z] in adj_app):\n            res.append(\"False\")\n        else:\n            res.append(\"True\")\n    if (\"False\" in res):\n        return (False)\n    else:\n        return (True)\n```\n\n\n```python\ndef optimal_solution (arr):\n    incl, excl, sol = [], [], []\n    for i in range(0,len(arr)):\n        if (i == 0):\n            incl.append(arr[0])\n            excl.append(0)\n        else:\n            incl.append(excl[-1]+ arr[i])\n            excl.append(max(incl[-2],excl[-1]))\n    mymax = max(incl[-1], excl[-1])\n    [sol.append(x) for i in range (len(arr)) for x in combinations(arr,i) if sum(x) == mymax and solutions(x, arr) == True]\n    return mymax, sol\n```\n\n\n```python\nappointments = [30, 40, 25, 50, 30, 20]\nduration, app = optimal_solution(appointments)\nprint (\"The optimal solution is: \", app)\nprint (\"The total duration is: \", duration)\n```\n\n    The optimal solution is:  [(40, 50, 20)]\n    The total duration is:  110\n\n", "meta": {"hexsha": "a970f1c8a6f0fd0b8412fbcb06432298a899d61c", "size": 825608, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "main.ipynb", "max_stars_repo_name": "giulio-derasmo/Homework-3", "max_stars_repo_head_hexsha": "8494febdb03467beedcd47abbab85e2ed3df8e08", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.ipynb", "max_issues_repo_name": "giulio-derasmo/Homework-3", "max_issues_repo_head_hexsha": "8494febdb03467beedcd47abbab85e2ed3df8e08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.ipynb", "max_forks_repo_name": "giulio-derasmo/Homework-3", "max_forks_repo_head_hexsha": "8494febdb03467beedcd47abbab85e2ed3df8e08", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-11-05T08:35:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T19:00:01.000Z", "avg_line_length": 180.4213286713, "max_line_length": 328184, "alphanum_fraction": 0.8693508299, "converted": true, "num_tokens": 25711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08756384428525613, "lm_q2_score": 0.057493282433961186, "lm_q1q2_score": 0.005034332830495629}}
{"text": "# Environmental Effects\n\nAs we have studied the various steps of the nuclear fuel cycle, we have mentioned the environmental consequences of each.\n\n## Learning Objectives\n\n- Recognize agencies with authority over environmental impacts in the nuclear fuel cycle\n- Name stakeholders in nuclear fuel cycle environmental impacts\n- List the types of environmental impacts involved in the nuclear fuel cycle\n- Match the steps of the fuel cycle with the environmental impacts for which they are responsible\n- Calculate Energy Return on Investment\n\n## Environmental Policy History\n\n- 0-1970 : Public land management. Public Refuse Act of 1899. (see: [Bubbly Creek](https://en.wikipedia.org/wiki/Bubbly_Creek))\n- 1960s: Wilderness protection. Stemming population growth.\n- 1970: Earth Day, NEPA, Impact Statements, Clean Air Act. Large scale wilderness dedications.\n- 1980s: Reagan. Budget cutbacks, but ideologically committed appoitees in EPA, Dept. of Ag., Department of Interior, etc. Public backlash.\n- 1990s: Bush I, regulations 'put americans out of work'. Clinton pushed env. friendly appointees. Bush II withdrawal from Kyoto.\n- 2010s: Obama era, renewed involvment in international climate talks.\n- 2015-2016: US signs Paris agreement on climate change, no legal force.\n- 2017: Trump declares intent to withdraw the United States from the Paris agreement \n- 2019: Trump officially withdraws from Paris Agreement (to take effect November 2020).\n\n### Kyoto Protocol\n\n<a title=\"By User:Canuckguy, User:Danlaycock (File:UNFCCC parties.svg) [Public domain], via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File%3AKyoto_Protocol_parties.svg\"></a>\n\nA map of the parties to the Kyoto Protocol    \n<span style=\"width: 2.4em; display: inline-block; text-align: center; border: 1px solid #808080; background-color: #008000;\">&nbsp;</span>\nAnnex B parties with binding targets in the second period    \n<span style=\"width: 2.4em; display: inline-block; text-align: center; border: 1px solid #808080; background-color: purple;\">&nbsp;</span>\nAnnex B parties with binding targets in the first period but not the second    \n<span style=\"width: 2.4em; display: inline-block; text-align: center; border: 1px solid #808080; background-color: #0000FF;\">&nbsp;</span>\nnon-Annex B parties without binding targets    \n<span style=\"width: 2.4em; display: inline-block; text-align: center; border: 1px solid #808080; background-color: #EEEE00;\">&nbsp;</span>\nAnnex B parties with binding targets in the first period but which withdrew from the Protocol    \n<span style=\"width: 2.4em; display: inline-block; text-align: center; border: 1px solid #808080; background-color: orange;\">&nbsp;</span>\nSignatories to the Protocol that have not ratified    \n<span style=\"width: 2.4em; display: inline-block; text-align: center; border: 1px solid #808080; background-color: #FF1111;\">&nbsp;</span>\nOther UN member states and observers that are not party to the Protocol\n\n\n\n\n### Paris Agreement\n<p><a href=\"https://commons.wikimedia.org/wiki/File:ParisAgreement.svg#/media/File:ParisAgreement.svg\"></a><br>By <a href=\"//commons.wikimedia.org/wiki/User:L.tak\" title=\"User:L.tak\">L.tak</a> - <span class=\"int-own-work\" lang=\"en\">Own work</span>, <a href=\"https://creativecommons.org/licenses/by-sa/4.0\" title=\"Creative Commons Attribution-Share Alike 4.0\">CC BY-SA 4.0</a>, <a href=\"https://commons.wikimedia.org/w/index.php?curid=48320267\">Link</a></p>\n\n<span style=\"width: 2.4em; display: inline-block; text-align: center; border: 1px solid #808080; background-color: #6666ff;\">&nbsp;</span>\nParties\n  <span style=\"width: 2.4em; display: inline-block; text-align: center; border: 1px solid #808080; background-color: #ffcc00;\">&nbsp;</span> Signatories\n  <span style=\"width: 2.4em; display: inline-block; text-align: center; border: 1px solid #808080; background-color: #000088;\">&nbsp;</span> \n   Parties also covered by European Union ratification\n   \n   \n   <p><a href=\"https://commons.wikimedia.org/wiki/File:Global_CO2_emissions_and_probabilistic_temperature_outcomes_of_Paris.png#/media/File:Global_CO2_emissions_and_probabilistic_temperature_outcomes_of_Paris.png\"></a><br>By This panel, \u201cEmission Pathways\u201d, is an adapted figure provided by Jae Edmonds. The original figure is found in: A.A. Fawcett, G.C. Iyer, L.E. Clarke, J.A. Edmonds, N.E. Hultman, H.C. McJeon, J. Rogeli, R. Schuler, J. Alsalam, G.R. Asrar, J. Creason, M. Jeong, J. McFarland, A. Mundra, and W. Shi, 2015: Can Paris pledges avert severe climate change? Science, 350 6266,1168-1169. The figure version presented here was adapted from the original as follows: For panel #1; The faint lines representing the emissions trajectories were removed. For panel #2; The Illustrative 50% likelihood projection was removed from the bottom of the chart. - The source for the diagram given in the report is U.S. Global Change Research Program: Climate Science Special Report, Fourth National Climate Assessment (NCA4), Volume I, chapter 14.2.\n<a rel=\"nofollow\" class=\"external free\" href=\"https://science2017.globalchange.gov/\">https://science2017.globalchange.gov/</a>, Public Domain, <a href=\"https://commons.wikimedia.org/w/index.php?curid=69337764\">Link</a></p>\n\n### EPA and the environment\n\nThe EPA's ability to regulate is mostly controlled by its available budget. \n\n[https://www.epa.gov/planandbudget/budget](https://www.epa.gov/planandbudget/budget)\n\n\n### NRC  and the environment\n\n\n### State Level NRC\n\n\nAgreement states, non-agreement states, and letter of intent states.\n\n## Energy Return on Investment\n\n\\begin{align}\nEROI =\\frac{\\mbox{energy generated}}{\\mbox{energy required to generate that energy}}\n\\end{align}\n\n\n\n\n```python\nfrom IPython.display import IFrame\nIFrame(src=\"https://embed.polleverywhere.com/free_text_polls/n8QhU2s2gia0Qu6?controls=none&short_poll=true\", width=\"100%\", height=\"700\", frameBorder=\"0\")\n```\n\n\n\n\n\n\n\n\n\n\nVery cool whitepaper on nuclear power plant material use:\n    [http://fhr.nuc.berkeley.edu/wp-content/uploads/2014/10/05-001-A_Material_input.pdf](http://fhr.nuc.berkeley.edu/wp-content/uploads/2014/10/05-001-A_Material_input.pdf)\n    \n> In nuclear energy systems, the major construction inputs are steel and concrete, which comprise\nover 95% of the material energy inputs. The evaluation of construction material inputs is central to lifecycle\nassessments for environmental impacts for nuclear and other non-fossil energy systems, and can\nprovide a useful, if only qualitative, plausibility check for economics claims. This paper compares steel\nand concrete inputs for several nuclear power plants: a 1970's Generation II PWR and BWR, the\nGeneration III EPR and ABWR, the Generation III+ ESBWR, and the Generation IV GT-MHR, PBMR\n(vertical), and AHTR. The steel and concrete input estimates for the Generation III, III+, and IV\nsystems are based on available arrangement drawings, and on scaling laws, and thus are approximate.\nHowever, they show that the evolutionary Generation III plants\u2014EPR and ABWR\u2014use approximately\n25% more steel and 70% more concrete than 1970\u2019s LWRs. This may explain, in part, the relatively\nlarge capital costs that have been observed for these plants. In contrast, the passive Generation III+\nLWRs that have been selected for new construction in the United States by Nustart\u2014ESBWR and AP-\n1000\u2014achieve substantial reductions in steel and concrete inputs. For example, analysis presented\nhere suggests that the ESBWR uses 73% of the steel, and 50% of the concrete required to construct an\nABWR. This suggests that new Generation III+ nuclear power construction in the U.S. will have\nsubstantially lower capital costs than was found with Generation III LWRs. This study also shows that\nthe advanced gas-Brayton cycle technology that will be demonstrated by the Next Generation Nuclear\nPlant (NGNP) has the potential to achieve comparable material inputs to LWRs at much smaller unit\ncapacities, and when extrapolated to larger reactors, to further reductions in steel and concrete input\n\n## Carbon Emissions\n\n\n\n\n```python\nIFrame(src=\"https://www.eia.gov/tools/faqs/faq.cfm?id=74&t=11\", width=\"100%\", height=\"700\")\n\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\nIFrame(src=\"https://www.eia.gov/electricity/annual/html/epa_a_03.html\", width=\"100%\", height=1000)\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\nIFrame(src=\"http://www.eia.gov/electricity/annual/html/epa_08_02.html\", width=\"100%\", height=700)\n```\n\n\n\n\n\n\n\n\n\n\n## References\n\nThis section was developed to complement Ch 12 of [1]. \n\n[1] N. Tsoulfanidis, The Nuclear Fuel Cycle. La Grange Park, Illinois, USA: American Nuclear Society, 2013.\n\n", "meta": {"hexsha": "1b6140dc70ecdec331eaad6fe6c4f1923c734329", "size": 14898, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "environmental-effects/environmental-effects.ipynb", "max_stars_repo_name": "abachma2/npre412", "max_stars_repo_head_hexsha": "3f105a15edc07745f1dd65cd791777a01136ec23", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "environmental-effects/environmental-effects.ipynb", "max_issues_repo_name": "abachma2/npre412", "max_issues_repo_head_hexsha": "3f105a15edc07745f1dd65cd791777a01136ec23", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "environmental-effects/environmental-effects.ipynb", "max_forks_repo_name": "abachma2/npre412", "max_forks_repo_head_hexsha": "3f105a15edc07745f1dd65cd791777a01136ec23", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.75, "max_line_length": 1366, "alphanum_fraction": 0.6380722245, "converted": true, "num_tokens": 2217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07263670435328423, "lm_q2_score": 0.06853748875117772, "lm_q1q2_score": 0.00497833730753584}}
{"text": "# Homework 3\n### Due Date:  Tuesday, September 20th at 11:59 PM\n\n---\n## Problem 1:  `Git` and recovering from a mistake\nYou will do this problem in the Jupyter notebook so I can see your output.  Once again, you will work with your playground repository.\n\n**NOTE:** At the beginning of each cell, you MUST type `%%bash`.  If you don't do that then you will not be able to work with the necessary bash commands.\n\nFollow the following steps for this problem:\n\n1. First cell:\n  1. Type `cd /tmp` to enter the temporary directory\n  2. git clone url_to_your_playground_repo\n2. Second cell:\n  1. Go into your local `playground` directory (`cd /tmp/playground`)\n  2. Type `git pull origin mybranch1`\n  3. `ls`\n3. Third cell:\n  1. Go into your local `playground` directory (`cd /tmp/playground`)\n  2. Type `git status`\n4. Fourth cell:\n  1. Go into your local `playground` directory (`cd /tmp/playground`)\n  2. Type `git reset --hard origin/master`\n  3. `ls`\n5. Fifth cell:\n  1. Go into your local `playground` directory (`cd /tmp/playground`)\n  2. Type `git status`\n\nThe whole point of this problem was to show you how to get your local repo back to an earlier state.  In this exercise, you accidentally merged something to `master` that you didn't want.  Rather than starting to delete things all over the place, you can simply reset your `HEAD` to a previous commit.\n\n\n```bash\n%%bash\ncd /tmp\ngit clone https://github.com/HeyItsRiddhi/playground.git\n```\n\n    fatal: destination path 'playground' already exists and is not an empty directory.\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit pull origin mybranch1\nls\n```\n\n    Merge made by the 'recursive' strategy.\n     books.md | 1 +\n     1 file changed, 1 insertion(+)\n     create mode 100644 books.md\n    README.md\n    books.md\n    feature.txt\n    intro.md\n    world.md\n\n\n    From https://github.com/HeyItsRiddhi/playground\n     * branch            mybranch1  -> FETCH_HEAD\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit status\n```\n\n    On branch master\n    Your branch is ahead of 'origin/master' by 2 commits.\n      (use \"git push\" to publish your local commits)\n    nothing to commit, working tree clean\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit reset --hard origin/master\nls\n```\n\n    HEAD is now at 4f54b54 Shared attribution between Joe & Sally\n    README.md\n    feature.txt\n    intro.md\n    world.md\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit status\n```\n\n    On branch master\n    Your branch is up-to-date with 'origin/master'.\n    nothing to commit, working tree clean\n\n\n## Problem 2:  `Git` and checking out a single file\nSometimes you don't want to merge an entire branch from the upstream but just one file from it. There is a direct use case for such a situation. Suppose I've made an error in this homework (or a lecture) and want to correct it. I fix the mistake in the upstream repo. In the meantime you have edited some other files and you really don't want to manually ignore my older copies of those files. Rather, you want to fix just one file from this new branch. This is how you do it.\n\nAs usual, be sure to type in `%%bash` before you write any `bash` commands in a cell.\n\n**Note:** The steps below assume that you have already cloned the `playground` repo in this notebook.\n\n1. First cell:\n  1. Go into the `playground` repo and fetch the changes from the master branch of the `course` remote.\n2. Second cell:\n  1. `git checkout course/master -- README.md`.  The `--` means that `README.md` is a file (as opposed to a `branch`).\n  2. `cat README.md`.  This just looks at the updated file.\n3. Third cell:\n  1. `git status`\n  2. Commit the changes to your local repo with an appropriate commit message.\n  3. `git status`\n  4. Push the changes to your remote repo.\n\n\n```bash\n%%bash\ncd /tmp/playground/\ngit fetch course\n```\n\n    From https://github.com/IACS-CS-207/playground\n     * [new branch]      master     -> course/master\n\n\n\n```bash\n%%bash\ncd /tmp/playground/\ngit checkout course/master -- README.md\ncat README.md\n```\n\n    # Playground Repo\n    \n    For practicing.\n\n\n\n```bash\n%%bash\ncd /tmp/playground/\ngit status\ngit commit -m \"updated README.md with course README.md\"\ngit status\ngit push\n```\n\n    On branch master\n    Your branch is ahead of 'origin/master' by 1 commit.\n      (use \"git push\" to publish your local commits)\n    nothing to commit, working tree clean\n    On branch master\n    Your branch is ahead of 'origin/master' by 1 commit.\n      (use \"git push\" to publish your local commits)\n    nothing to commit, working tree clean\n    On branch master\n    Your branch is ahead of 'origin/master' by 1 commit.\n      (use \"git push\" to publish your local commits)\n    nothing to commit, working tree clean\n\n\n    To https://github.com/HeyItsRiddhi/playground.git\n       4f54b54..4ac63eb  master -> master\n\n\n## Problem 3\nThis problem is related to the Lecture 4 exercises.\n1. Open the `languages.txt` file.  This file contains all the languages that students listed as their primary language in the course survey.\n2. Load the language strings from the file into a list.\n3. Use the `Counter` method from the `collections` library to count the number of occurrences of each element of the list.\n  + **NOTE:**  It is not necessary to use the `most_common()` method here.\n4. Create a bar plot to display the frequency of each language.  Be sure to label the x-axis!\n  + Remember, to create plots in the notebook you must put the line `%matplotlib inline` at the beginning of your notebook.\n  + Be sure to import matplotlib:  `import matplotlib.pyplot as plt`.\n  + To generate the bar plot write `plt.bar(x_coords, freqs)`.  You need to define `x_coords` and `freqs`.\n  + **Hint:** You may want to use the `numpy` `arange` function to create `x_coords`.  Remember, `x_coords` is the x-axis and it should have points for each distinct language.\n  + **Hint:** To get `freqs`, you may want to use the `values()` method on your result from step 3.  That is, `freqs = result_from_3.values()`.\n  + **Hint:** To label the x-axis you should use `plt.xticks(x_coords, labels)` where labels can be accessed through the `keys()` method on your result from step 3.\n\n\n```python\nimport collections\nimport numpy\nimport matplotlib.pyplot as plt\n\n#get data\nfile = open('../../lectures/L4/languages.txt', 'r')\nlanguages = file.read().splitlines() \nfile.close()\n\n#calculate the amount of student that know each language\nfreq = collections.Counter(languages)\n\n#plot data\nfreqs = freq.values()\nlabels = freq.keys()\nx_coords = numpy.arange(8)\nplt.bar(x_coords,freqs)\nplt.xticks(x_coords, labels)\nplt.xlabel(\"Languages\")\nplt.ylabel(\"Students\")\nplt.title('Languages students in the class know')\nplt.show()\n```\n\n---\n## Problem 4\nIn chemical kinetics, the reaction rate coefficient for a given reaction depends on the temperature of the system.  The functional relationship between the reaction rate coefficient and temperature is given by the Arrhenius rate:\n\\begin{align}\nk\\left(T\\right) = A T^{b}\\exp\\left(-\\frac{E}{RT}\\right)\n\\end{align}\nwhere $A$, $b$, and $E$ are parameters, $R = 8.314 \\dfrac{\\textrm{J}}{\\textrm{mol} \\textrm{ K}}$  is the universal gas constant, and $T$ is the temperature.\n\nWrite a function which returns $k\\left(T\\right)$ given $A$, $b$, $E$, and $T$.  Here are a few requirements:\n* The function should test for exceptions where necessary.\n* Pass the parameters $A$, $b$, and $E$ in as a list.\n* Make $R$ a keyword argument to the function.\n\n\n```python\nimport math\nimport numpy as np\n\ndef arrhenius_rate(params, T, R=8.314):\n    #Check that A,b,E is passed as a list\n    if(len(params) != 3 or type(params) != list):\n        print(\"ERROR: First argument needs to be a list of 3\")\n    else:\n        [A,b,E] = params\n        #Check that A,b,E is passed are numbers\n        if ((type(A) != int and type(A) != float) or \n            (type(b) != int and type(b) != float) or\n            (type(E) != int and type(E) != float)):\n            print(\"Error: All numbers in list must be of type integer or float\")\n        else:\n            #Calculate k(T)\n            kt = A*T**(b)*np.exp(-E/(R*T))\n            return kt\n\n```\n\n---\n## Problem 5\nUsing `numpy` arrays, plot $k\\left(T\\right)$ for $T\\in\\left(0, 5000\\right]$ for three different sets of parameters $\\left\\{A, b, E\\right\\}$.  Make sure all three lines are on the same figure and be sure to label each line.  You may use the function from Problem 2.  You may want to play with the parameters a little bit to get some nice curves but you won't lose points for ugly curves either (as long as they're correct!).\n\n\n```python\n#array of temperatures\ntemps = np.arange(0,5000) \n\n# 3 different sets of parameters\nargs = [[10,2,0.1],[20,2,0.11],[30,2,0.12]] \n\n# array to hold 3 data sets for 3 diff paramseters\nplots =[] \n\n#create 3 data sets to plot\nfor arg in args: \n    kt = list(map(lambda x: arrhenius_rate(arg,int(x)), temps))\n    plots.append(kt)\n```\n\n\n```python\nimport matplotlib.pyplot as plt\n\n#plot lines\nplt.plot(temps, plots[0], lw=2, ls='-', label=r'$A,b,E = 10,2,0.1$')\nplt.plot(temps, plots[1], lw=2, ls='-', label=r'$A,b,E = 10,2,0.11$')\nplt.plot(temps, plots[2], lw=2, ls='-', label=r'$A,b,E = 10,2,0.12$')\n\n#display legend and define axises & plot title\nplt.legend() \nplt.xlabel(r'$Temperature$', fontsize=16) \nplt.ylabel(r'$k(T)$', fontsize=16) \nplt.title('Arrhenius Rate with 3 parameters', fontsize=16)\nplt.show()\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "c9e551d54a6fd9ab0dfb964ae2c14e30cfe6e4b6", "size": 27895, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "homeworks/HW3/HW3-Final.ipynb", "max_stars_repo_name": "HeyItsRiddhi/cs207_riddhi_shah", "max_stars_repo_head_hexsha": "18d7d6f1fcad213ce35a93ee33c03620f8b06b65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/HW3/HW3-Final.ipynb", "max_issues_repo_name": "HeyItsRiddhi/cs207_riddhi_shah", "max_issues_repo_head_hexsha": "18d7d6f1fcad213ce35a93ee33c03620f8b06b65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/HW3/HW3-Final.ipynb", "max_forks_repo_name": "HeyItsRiddhi/cs207_riddhi_shah", "max_forks_repo_head_hexsha": "18d7d6f1fcad213ce35a93ee33c03620f8b06b65", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.7536231884, "max_line_length": 10466, "alphanum_fraction": 0.7203441477, "converted": true, "num_tokens": 2549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05582314741776902, "lm_q2_score": 0.0888202942090721, "lm_q1q2_score": 0.004958228377322647}}
{"text": "# FIFA World Cup - Benjamin  \nThe notebook is seperated into two parts: a descriptive one and the fair play analysis.\n\n\n```python\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nplt.rcParams.update({'font.size': 16})\n\n#G=Goal, OG=Own Goal, Y=Yellow Card, R=Red Card, SY = Red Card by second yellow, P=Penalty, MP=Missed Penalty, I = Substitution In, O=Substitute Out, IH= In half time?\n\ndf_matches=pd.read_csv('data_raw/WorldCupMatches.csv', sep=',')\ndf_players=pd.read_csv('data_raw/WorldCupPlayers.csv', sep=',')\ndf_cups=pd.read_csv('data_raw/WorldCups.csv', sep=',')\n\ndf_events = pd.read_csv('data_prepared/event.csv', sep=',').replace(np.nan, '', regex=True)\n```\n\n\n```python\ndf_matches\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Year</th>\n      <th>Datetime</th>\n      <th>Stage</th>\n      <th>Stadium</th>\n      <th>City</th>\n      <th>Home Team Name</th>\n      <th>Home Team Goals</th>\n      <th>Away Team Goals</th>\n      <th>Away Team Name</th>\n      <th>Win conditions</th>\n      <th>Attendance</th>\n      <th>Half-time Home Goals</th>\n      <th>Half-time Away Goals</th>\n      <th>Referee</th>\n      <th>Assistant 1</th>\n      <th>Assistant 2</th>\n      <th>RoundID</th>\n      <th>MatchID</th>\n      <th>Home Team Initials</th>\n      <th>Away Team Initials</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td></td>\n      <td>4444.0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>LOMBARDI Domingo (URU)</td>\n      <td>CRISTOPHE Henry (BEL)</td>\n      <td>REGO Gilberto (BRA)</td>\n      <td>201</td>\n      <td>1096</td>\n      <td>FRA</td>\n      <td>MEX</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 4</td>\n      <td>Parque Central</td>\n      <td>Montevideo</td>\n      <td>USA</td>\n      <td>3</td>\n      <td>0</td>\n      <td>Belgium</td>\n      <td></td>\n      <td>18346.0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>MACIAS Jose (ARG)</td>\n      <td>MATEUCCI Francisco (URU)</td>\n      <td>WARNKEN Alberto (CHI)</td>\n      <td>201</td>\n      <td>1090</td>\n      <td>USA</td>\n      <td>BEL</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1930</td>\n      <td>14 Jul 1930 - 12:45</td>\n      <td>Group 2</td>\n      <td>Parque Central</td>\n      <td>Montevideo</td>\n      <td>Yugoslavia</td>\n      <td>2</td>\n      <td>1</td>\n      <td>Brazil</td>\n      <td></td>\n      <td>24059.0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>TEJADA Anibal (URU)</td>\n      <td>VALLARINO Ricardo (URU)</td>\n      <td>BALWAY Thomas (FRA)</td>\n      <td>201</td>\n      <td>1093</td>\n      <td>YUG</td>\n      <td>BRA</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1930</td>\n      <td>14 Jul 1930 - 14:50</td>\n      <td>Group 3</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>Romania</td>\n      <td>3</td>\n      <td>1</td>\n      <td>Peru</td>\n      <td></td>\n      <td>2549.0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>WARNKEN Alberto (CHI)</td>\n      <td>LANGENUS Jean (BEL)</td>\n      <td>MATEUCCI Francisco (URU)</td>\n      <td>201</td>\n      <td>1098</td>\n      <td>ROU</td>\n      <td>PER</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1930</td>\n      <td>15 Jul 1930 - 16:00</td>\n      <td>Group 1</td>\n      <td>Parque Central</td>\n      <td>Montevideo</td>\n      <td>Argentina</td>\n      <td>1</td>\n      <td>0</td>\n      <td>France</td>\n      <td></td>\n      <td>23409.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>REGO Gilberto (BRA)</td>\n      <td>SAUCEDO Ulises (BOL)</td>\n      <td>RADULESCU Constantin (ROU)</td>\n      <td>201</td>\n      <td>1085</td>\n      <td>ARG</td>\n      <td>FRA</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>1930</td>\n      <td>16 Jul 1930 - 14:45</td>\n      <td>Group 1</td>\n      <td>Parque Central</td>\n      <td>Montevideo</td>\n      <td>Chile</td>\n      <td>3</td>\n      <td>0</td>\n      <td>Mexico</td>\n      <td></td>\n      <td>9249.0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>CRISTOPHE Henry (BEL)</td>\n      <td>APHESTEGUY Martin (URU)</td>\n      <td>LANGENUS Jean (BEL)</td>\n      <td>201</td>\n      <td>1095</td>\n      <td>CHI</td>\n      <td>MEX</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>1930</td>\n      <td>17 Jul 1930 - 12:45</td>\n      <td>Group 2</td>\n      <td>Parque Central</td>\n      <td>Montevideo</td>\n      <td>Yugoslavia</td>\n      <td>4</td>\n      <td>0</td>\n      <td>Bolivia</td>\n      <td></td>\n      <td>18306.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>MATEUCCI Francisco (URU)</td>\n      <td>LOMBARDI Domingo (URU)</td>\n      <td>WARNKEN Alberto (CHI)</td>\n      <td>201</td>\n      <td>1092</td>\n      <td>YUG</td>\n      <td>BOL</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>1930</td>\n      <td>17 Jul 1930 - 14:45</td>\n      <td>Group 4</td>\n      <td>Parque Central</td>\n      <td>Montevideo</td>\n      <td>USA</td>\n      <td>3</td>\n      <td>0</td>\n      <td>Paraguay</td>\n      <td></td>\n      <td>18306.0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>MACIAS Jose (ARG)</td>\n      <td>APHESTEGUY Martin (URU)</td>\n      <td>TEJADA Anibal (URU)</td>\n      <td>201</td>\n      <td>1097</td>\n      <td>USA</td>\n      <td>PAR</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>1930</td>\n      <td>18 Jul 1930 - 14:30</td>\n      <td>Group 3</td>\n      <td>Estadio Centenario</td>\n      <td>Montevideo</td>\n      <td>Uruguay</td>\n      <td>1</td>\n      <td>0</td>\n      <td>Peru</td>\n      <td></td>\n      <td>57735.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>LANGENUS Jean (BEL)</td>\n      <td>BALWAY Thomas (FRA)</td>\n      <td>CRISTOPHE Henry (BEL)</td>\n      <td>201</td>\n      <td>1099</td>\n      <td>URU</td>\n      <td>PER</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>1930</td>\n      <td>19 Jul 1930 - 12:50</td>\n      <td>Group 1</td>\n      <td>Estadio Centenario</td>\n      <td>Montevideo</td>\n      <td>Chile</td>\n      <td>1</td>\n      <td>0</td>\n      <td>France</td>\n      <td></td>\n      <td>2000.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>TEJADA Anibal (URU)</td>\n      <td>LOMBARDI Domingo (URU)</td>\n      <td>REGO Gilberto (BRA)</td>\n      <td>201</td>\n      <td>1094</td>\n      <td>CHI</td>\n      <td>FRA</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>1930</td>\n      <td>19 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Estadio Centenario</td>\n      <td>Montevideo</td>\n      <td>Argentina</td>\n      <td>6</td>\n      <td>3</td>\n      <td>Mexico</td>\n      <td></td>\n      <td>42100.0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>SAUCEDO Ulises (BOL)</td>\n      <td>ALONSO Gualberto (URU)</td>\n      <td>RADULESCU Constantin (ROU)</td>\n      <td>201</td>\n      <td>1086</td>\n      <td>ARG</td>\n      <td>MEX</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>1930</td>\n      <td>20 Jul 1930 - 13:00</td>\n      <td>Group 2</td>\n      <td>Estadio Centenario</td>\n      <td>Montevideo</td>\n      <td>Brazil</td>\n      <td>4</td>\n      <td>0</td>\n      <td>Bolivia</td>\n      <td></td>\n      <td>25466.0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>BALWAY Thomas (FRA)</td>\n      <td>MATEUCCI Francisco (URU)</td>\n      <td>VALLEJO Gaspar (MEX)</td>\n      <td>201</td>\n      <td>1091</td>\n      <td>BRA</td>\n      <td>BOL</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>1930</td>\n      <td>20 Jul 1930 - 15:00</td>\n      <td>Group 4</td>\n      <td>Estadio Centenario</td>\n      <td>Montevideo</td>\n      <td>Paraguay</td>\n      <td>1</td>\n      <td>0</td>\n      <td>Belgium</td>\n      <td></td>\n      <td>12000.0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>VALLARINO Ricardo (URU)</td>\n      <td>MACIAS Jose (ARG)</td>\n      <td>LOMBARDI Domingo (URU)</td>\n      <td>201</td>\n      <td>1089</td>\n      <td>PAR</td>\n      <td>BEL</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>1930</td>\n      <td>21 Jul 1930 - 14:50</td>\n      <td>Group 3</td>\n      <td>Estadio Centenario</td>\n      <td>Montevideo</td>\n      <td>Uruguay</td>\n      <td>4</td>\n      <td>0</td>\n      <td>Romania</td>\n      <td></td>\n      <td>70022.0</td>\n      <td>4</td>\n      <td>0</td>\n      <td>REGO Gilberto (BRA)</td>\n      <td>WARNKEN Alberto (CHI)</td>\n      <td>SAUCEDO Ulises (BOL)</td>\n      <td>201</td>\n      <td>1100</td>\n      <td>URU</td>\n      <td>ROU</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>1930</td>\n      <td>22 Jul 1930 - 14:45</td>\n      <td>Group 1</td>\n      <td>Estadio Centenario</td>\n      <td>Montevideo</td>\n      <td>Argentina</td>\n      <td>3</td>\n      <td>1</td>\n      <td>Chile</td>\n      <td></td>\n      <td>41459.0</td>\n      <td>2</td>\n      <td>1</td>\n      <td>LANGENUS Jean (BEL)</td>\n      <td>CRISTOPHE Henry (BEL)</td>\n      <td>SAUCEDO Ulises (BOL)</td>\n      <td>201</td>\n      <td>1084</td>\n      <td>ARG</td>\n      <td>CHI</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>1930</td>\n      <td>26 Jul 1930 - 14:45</td>\n      <td>Semi-finals</td>\n      <td>Estadio Centenario</td>\n      <td>Montevideo</td>\n      <td>Argentina</td>\n      <td>6</td>\n      <td>1</td>\n      <td>USA</td>\n      <td></td>\n      <td>72886.0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>LANGENUS Jean (BEL)</td>\n      <td>VALLEJO Gaspar (MEX)</td>\n      <td>WARNKEN Alberto (CHI)</td>\n      <td>202</td>\n      <td>1088</td>\n      <td>ARG</td>\n      <td>USA</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>1930</td>\n      <td>27 Jul 1930 - 14:45</td>\n      <td>Semi-finals</td>\n      <td>Estadio Centenario</td>\n      <td>Montevideo</td>\n      <td>Uruguay</td>\n      <td>6</td>\n      <td>1</td>\n      <td>Yugoslavia</td>\n      <td></td>\n      <td>79867.0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>REGO Gilberto (BRA)</td>\n      <td>SAUCEDO Ulises (BOL)</td>\n      <td>BALWAY Thomas (FRA)</td>\n      <td>202</td>\n      <td>1101</td>\n      <td>URU</td>\n      <td>YUG</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>1930</td>\n      <td>30 Jul 1930 - 14:15</td>\n      <td>Final</td>\n      <td>Estadio Centenario</td>\n      <td>Montevideo</td>\n      <td>Uruguay</td>\n      <td>4</td>\n      <td>2</td>\n      <td>Argentina</td>\n      <td></td>\n      <td>68346.0</td>\n      <td>1</td>\n      <td>2</td>\n      <td>LANGENUS Jean (BEL)</td>\n      <td>SAUCEDO Ulises (BOL)</td>\n      <td>CRISTOPHE Henry (BEL)</td>\n      <td>405</td>\n      <td>1087</td>\n      <td>URU</td>\n      <td>ARG</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>1934</td>\n      <td>27 May 1934 - 16:30</td>\n      <td>Preliminary round</td>\n      <td>Stadio Benito Mussolini</td>\n      <td>Turin</td>\n      <td>Austria</td>\n      <td>3</td>\n      <td>2</td>\n      <td>France</td>\n      <td>Austria win after extra time</td>\n      <td>16000.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>VAN MOORSEL Johannes (NED)</td>\n      <td>CAIRONI Camillo (ITA)</td>\n      <td>BAERT Louis (BEL)</td>\n      <td>204</td>\n      <td>1104</td>\n      <td>AUT</td>\n      <td>FRA</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>1934</td>\n      <td>27 May 1934 - 16:30</td>\n      <td>Preliminary round</td>\n      <td>Giorgio Ascarelli</td>\n      <td>Naples</td>\n      <td>Hungary</td>\n      <td>4</td>\n      <td>2</td>\n      <td>Egypt</td>\n      <td></td>\n      <td>9000.0</td>\n      <td>2</td>\n      <td>2</td>\n      <td>BARLASSINA Rinaldo (ITA)</td>\n      <td>DATTILO Generoso (ITA)</td>\n      <td>SASSI Otello (ITA)</td>\n      <td>204</td>\n      <td>1119</td>\n      <td>HUN</td>\n      <td>EGY</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>1934</td>\n      <td>27 May 1934 - 16:30</td>\n      <td>Preliminary round</td>\n      <td>San Siro</td>\n      <td>Milan</td>\n      <td>Switzerland</td>\n      <td>3</td>\n      <td>2</td>\n      <td>Netherlands</td>\n      <td></td>\n      <td>33000.0</td>\n      <td>2</td>\n      <td>1</td>\n      <td>EKLIND Ivan (SWE)</td>\n      <td>BERANEK Alois (AUT)</td>\n      <td>BONIVENTO Ferruccio (ITA)</td>\n      <td>204</td>\n      <td>1133</td>\n      <td>SUI</td>\n      <td>NED</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>1934</td>\n      <td>27 May 1934 - 16:30</td>\n      <td>Preliminary round</td>\n      <td>Littorale</td>\n      <td>Bologna</td>\n      <td>Sweden</td>\n      <td>3</td>\n      <td>2</td>\n      <td>Argentina</td>\n      <td></td>\n      <td>14000.0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>BRAUN Eugen (AUT)</td>\n      <td>CARRARO Albino (ITA)</td>\n      <td>TURBIANI Giuseppe (ITA)</td>\n      <td>204</td>\n      <td>1102</td>\n      <td>SWE</td>\n      <td>ARG</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>1934</td>\n      <td>27 May 1934 - 16:30</td>\n      <td>Preliminary round</td>\n      <td>Giovanni Berta</td>\n      <td>Florence</td>\n      <td>Germany</td>\n      <td>5</td>\n      <td>2</td>\n      <td>Belgium</td>\n      <td></td>\n      <td>8000.0</td>\n      <td>1</td>\n      <td>2</td>\n      <td>MATTEA Francesco (ITA)</td>\n      <td>MELANDRI Ermenegildo (ITA)</td>\n      <td>BAERT Jacques (FRA)</td>\n      <td>204</td>\n      <td>1108</td>\n      <td>GER</td>\n      <td>BEL</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>1934</td>\n      <td>27 May 1934 - 16:30</td>\n      <td>Preliminary round</td>\n      <td>Luigi Ferraris</td>\n      <td>Genoa</td>\n      <td>Spain</td>\n      <td>3</td>\n      <td>1</td>\n      <td>Brazil</td>\n      <td></td>\n      <td>21000.0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>BIRLEM Alfred (GER)</td>\n      <td>CARMINATI Ettore (ITA)</td>\n      <td>IVANCSICS Mihaly (HUN)</td>\n      <td>204</td>\n      <td>1111</td>\n      <td>ESP</td>\n      <td>BRA</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>1934</td>\n      <td>27 May 1934 - 16:30</td>\n      <td>Preliminary round</td>\n      <td>Nazionale PNF</td>\n      <td>Rome</td>\n      <td>Italy</td>\n      <td>7</td>\n      <td>1</td>\n      <td>USA</td>\n      <td></td>\n      <td>25000.0</td>\n      <td>3</td>\n      <td>0</td>\n      <td>MERCET Rene (SUI)</td>\n      <td>ESCARTIN Pedro (ESP)</td>\n      <td>ZENISEK Bohumil (TCH)</td>\n      <td>204</td>\n      <td>1135</td>\n      <td>ITA</td>\n      <td>USA</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>1934</td>\n      <td>27 May 1934 - 16:30</td>\n      <td>Preliminary round</td>\n      <td>Littorio</td>\n      <td>Trieste</td>\n      <td>Czechoslovakia</td>\n      <td>2</td>\n      <td>1</td>\n      <td>Romania</td>\n      <td></td>\n      <td>9000.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>LANGENUS Jean (BEL)</td>\n      <td>SCARPI Giuseppe (ITA)</td>\n      <td>SCORZONI Raffaele (ITA)</td>\n      <td>204</td>\n      <td>1141</td>\n      <td>TCH</td>\n      <td>ROU</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>1934</td>\n      <td>31 May 1934 - 16:30</td>\n      <td>Quarter-finals</td>\n      <td>Stadio Benito Mussolini</td>\n      <td>Turin</td>\n      <td>Czechoslovakia</td>\n      <td>3</td>\n      <td>2</td>\n      <td>Switzerland</td>\n      <td></td>\n      <td>12000.0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>BERANEK Alois (AUT)</td>\n      <td>MOHAMED Youssuf (EGY)</td>\n      <td>BAERT Jacques (FRA)</td>\n      <td>418</td>\n      <td>1143</td>\n      <td>TCH</td>\n      <td>SUI</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>1934</td>\n      <td>31 May 1934 - 16:30</td>\n      <td>Quarter-finals</td>\n      <td>San Siro</td>\n      <td>Milan</td>\n      <td>Germany</td>\n      <td>2</td>\n      <td>1</td>\n      <td>Sweden</td>\n      <td></td>\n      <td>3000.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>BARLASSINA Rinaldo (ITA)</td>\n      <td>MERCET Rene (SUI)</td>\n      <td>VAN MOORSEL Johannes (NED)</td>\n      <td>418</td>\n      <td>1129</td>\n      <td>GER</td>\n      <td>SWE</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>1934</td>\n      <td>31 May 1934 - 16:30</td>\n      <td>Quarter-finals</td>\n      <td>Giovanni Berta</td>\n      <td>Florence</td>\n      <td>Italy</td>\n      <td>1</td>\n      <td>1</td>\n      <td>Spain</td>\n      <td></td>\n      <td>35000.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>BAERT Louis (BEL)</td>\n      <td>ZENISEK Bohumil (TCH)</td>\n      <td>IVANCSICS Mihaly (HUN)</td>\n      <td>418</td>\n      <td>1122</td>\n      <td>ITA</td>\n      <td>ESP</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>1934</td>\n      <td>31 May 1934 - 16:30</td>\n      <td>Quarter-finals</td>\n      <td>Littorale</td>\n      <td>Bologna</td>\n      <td>Austria</td>\n      <td>2</td>\n      <td>1</td>\n      <td>Hungary</td>\n      <td></td>\n      <td>23000.0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>MATTEA Francesco (ITA)</td>\n      <td>ESCARTIN Pedro (ESP)</td>\n      <td>BIRLEM Alfred (GER)</td>\n      <td>418</td>\n      <td>1106</td>\n      <td>AUT</td>\n      <td>HUN</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>806</th>\n      <td>2014</td>\n      <td>23 Jun 2014 - 17:00</td>\n      <td>Group A</td>\n      <td>Estadio Nacional</td>\n      <td>Brasilia</td>\n      <td>Cameroon</td>\n      <td>1</td>\n      <td>4</td>\n      <td>Brazil</td>\n      <td></td>\n      <td>69112.0</td>\n      <td>1</td>\n      <td>2</td>\n      <td>ERIKSSON Jonas (SWE)</td>\n      <td>KLASENIUS Mathias (SWE)</td>\n      <td>WARNMARK Daniel (SWE)</td>\n      <td>255931</td>\n      <td>300186472</td>\n      <td>CMR</td>\n      <td>BRA</td>\n    </tr>\n    <tr>\n      <th>807</th>\n      <td>2014</td>\n      <td>23 Jun 2014 - 17:00</td>\n      <td>Group A</td>\n      <td>Arena Pernambuco</td>\n      <td>Recife</td>\n      <td>Croatia</td>\n      <td>1</td>\n      <td>3</td>\n      <td>Mexico</td>\n      <td></td>\n      <td>41212.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>Ravshan IRMATOV (UZB)</td>\n      <td>RASULOV Abduxamidullo (UZB)</td>\n      <td>KOCHKAROV Bakhadyr (KGZ)</td>\n      <td>255931</td>\n      <td>300186452</td>\n      <td>CRO</td>\n      <td>MEX</td>\n    </tr>\n    <tr>\n      <th>808</th>\n      <td>2014</td>\n      <td>24 Jun 2014 - 13:00</td>\n      <td>Group D</td>\n      <td>Estadio das Dunas</td>\n      <td>Natal</td>\n      <td>Italy</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Uruguay</td>\n      <td></td>\n      <td>39706.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>RODRIGUEZ Marco (MEX)</td>\n      <td>TORRENTERA Marvin (MEX)</td>\n      <td>QUINTERO Marcos (MEX)</td>\n      <td>255931</td>\n      <td>300186465</td>\n      <td>ITA</td>\n      <td>URU</td>\n    </tr>\n    <tr>\n      <th>809</th>\n      <td>2014</td>\n      <td>24 Jun 2014 - 13:00</td>\n      <td>Group D</td>\n      <td>Estadio Mineirao</td>\n      <td>Belo Horizonte</td>\n      <td>Costa Rica</td>\n      <td>0</td>\n      <td>0</td>\n      <td>England</td>\n      <td></td>\n      <td>57823.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>HAIMOUDI Djamel (ALG)</td>\n      <td>ACHIK Redouane (MAR)</td>\n      <td>ETCHIALI Abdelhak (ALG)</td>\n      <td>255931</td>\n      <td>300186484</td>\n      <td>CRC</td>\n      <td>ENG</td>\n    </tr>\n    <tr>\n      <th>810</th>\n      <td>2014</td>\n      <td>24 Jun 2014 - 16:00</td>\n      <td>Group C</td>\n      <td>Arena Pantanal</td>\n      <td>Cuiaba</td>\n      <td>Japan</td>\n      <td>1</td>\n      <td>4</td>\n      <td>Colombia</td>\n      <td></td>\n      <td>40340.0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>PROENCA Pedro (POR)</td>\n      <td>MIRANDA Bertino (POR)</td>\n      <td>TRIGO Jose (POR)</td>\n      <td>255931</td>\n      <td>300186457</td>\n      <td>JPN</td>\n      <td>COL</td>\n    </tr>\n    <tr>\n      <th>811</th>\n      <td>2014</td>\n      <td>24 Jun 2014 - 17:00</td>\n      <td>Group C</td>\n      <td>Estadio Castelao</td>\n      <td>Fortaleza</td>\n      <td>Greece</td>\n      <td>2</td>\n      <td>1</td>\n      <td>C\ufffdte d'Ivoire</td>\n      <td></td>\n      <td>59095.0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>VERA Carlos (ECU)</td>\n      <td>LESCANO Christian (ECU)</td>\n      <td>ROMERO Byron (ECU)</td>\n      <td>255931</td>\n      <td>300186455</td>\n      <td>GRE</td>\n      <td>CIV</td>\n    </tr>\n    <tr>\n      <th>812</th>\n      <td>2014</td>\n      <td>25 Jun 2014 - 13:00</td>\n      <td>Group F</td>\n      <td>Estadio Beira-Rio</td>\n      <td>Porto Alegre</td>\n      <td>Nigeria</td>\n      <td>2</td>\n      <td>3</td>\n      <td>Argentina</td>\n      <td></td>\n      <td>43285.0</td>\n      <td>1</td>\n      <td>2</td>\n      <td>Nicola RIZZOLI (ITA)</td>\n      <td>Renato FAVERANI (ITA)</td>\n      <td>Andrea STEFANI (ITA)</td>\n      <td>255931</td>\n      <td>300186458</td>\n      <td>NGA</td>\n      <td>ARG</td>\n    </tr>\n    <tr>\n      <th>813</th>\n      <td>2014</td>\n      <td>25 Jun 2014 - 13:00</td>\n      <td>Group F</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>rn\"&gt;Bosnia and Herzegovina</td>\n      <td>3</td>\n      <td>1</td>\n      <td>IR Iran</td>\n      <td></td>\n      <td>48011.0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>Carlos VELASCO CARBALLO (ESP)</td>\n      <td>ALONSO FERNANDEZ Roberto (ESP)</td>\n      <td>YUSTE Juan (ESP)</td>\n      <td>255931</td>\n      <td>300186464</td>\n      <td>BIH</td>\n      <td>IRN</td>\n    </tr>\n    <tr>\n      <th>814</th>\n      <td>2014</td>\n      <td>25 Jun 2014 - 16:00</td>\n      <td>Group E</td>\n      <td>Arena Amazonia</td>\n      <td>Manaus</td>\n      <td>Honduras</td>\n      <td>0</td>\n      <td>3</td>\n      <td>Switzerland</td>\n      <td></td>\n      <td>40322.0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>PITANA Nestor (ARG)</td>\n      <td>MAIDANA Hernan (ARG)</td>\n      <td>BELATTI Juan Pablo (ARG)</td>\n      <td>255931</td>\n      <td>300186482</td>\n      <td>HON</td>\n      <td>SUI</td>\n    </tr>\n    <tr>\n      <th>815</th>\n      <td>2014</td>\n      <td>25 Jun 2014 - 17:00</td>\n      <td>Group E</td>\n      <td>Estadio do Maracana</td>\n      <td>Rio De Janeiro</td>\n      <td>Ecuador</td>\n      <td>0</td>\n      <td>0</td>\n      <td>France</td>\n      <td></td>\n      <td>73749.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>Noumandiez DOUE (CIV)</td>\n      <td>YEO Songuifolo (CIV)</td>\n      <td>BIRUMUSHAHU Jean Claude (BDI)</td>\n      <td>255931</td>\n      <td>300186515</td>\n      <td>ECU</td>\n      <td>FRA</td>\n    </tr>\n    <tr>\n      <th>816</th>\n      <td>2014</td>\n      <td>26 Jun 2014 - 13:00</td>\n      <td>Group G</td>\n      <td>Arena Pernambuco</td>\n      <td>Recife</td>\n      <td>USA</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Germany</td>\n      <td></td>\n      <td>41876.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>Ravshan IRMATOV (UZB)</td>\n      <td>RASULOV Abduxamidullo (UZB)</td>\n      <td>KOCHKAROV Bakhadyr (KGZ)</td>\n      <td>255931</td>\n      <td>300186469</td>\n      <td>USA</td>\n      <td>GER</td>\n    </tr>\n    <tr>\n      <th>817</th>\n      <td>2014</td>\n      <td>26 Jun 2014 - 13:00</td>\n      <td>Group G</td>\n      <td>Estadio Nacional</td>\n      <td>Brasilia</td>\n      <td>Portugal</td>\n      <td>2</td>\n      <td>1</td>\n      <td>Ghana</td>\n      <td></td>\n      <td>67540.0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>SHUKRALLA Nawaf (BHR)</td>\n      <td>TULEFAT Yaser (BHR)</td>\n      <td>SALEH Ebrahim (BHR)</td>\n      <td>255931</td>\n      <td>300186476</td>\n      <td>POR</td>\n      <td>GHA</td>\n    </tr>\n    <tr>\n      <th>818</th>\n      <td>2014</td>\n      <td>26 Jun 2014 - 17:00</td>\n      <td>Group H</td>\n      <td>Arena de Sao Paulo</td>\n      <td>Sao Paulo</td>\n      <td>Korea Republic</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Belgium</td>\n      <td></td>\n      <td>61397.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>Ben WILLIAMS (AUS)</td>\n      <td>CREAM Matthew (AUS)</td>\n      <td>ANAZ Hakan (AUS)</td>\n      <td>255931</td>\n      <td>300186480</td>\n      <td>KOR</td>\n      <td>BEL</td>\n    </tr>\n    <tr>\n      <th>819</th>\n      <td>2014</td>\n      <td>26 Jun 2014 - 17:00</td>\n      <td>Group H</td>\n      <td>Arena da Baixada</td>\n      <td>Curitiba</td>\n      <td>Algeria</td>\n      <td>1</td>\n      <td>1</td>\n      <td>Russia</td>\n      <td></td>\n      <td>39311.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>C\ufffdneyt \ufffdAKIR (TUR)</td>\n      <td>DURAN Bahattin (TUR)</td>\n      <td>ONGUN Tarik (TUR)</td>\n      <td>255931</td>\n      <td>300186506</td>\n      <td>ALG</td>\n      <td>RUS</td>\n    </tr>\n    <tr>\n      <th>820</th>\n      <td>2014</td>\n      <td>28 Jun 2014 - 13:00</td>\n      <td>Round of 16</td>\n      <td>Estadio Mineirao</td>\n      <td>Belo Horizonte</td>\n      <td>Brazil</td>\n      <td>1</td>\n      <td>1</td>\n      <td>Chile</td>\n      <td>Brazil win on penalties (3 - 2)</td>\n      <td>57714.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>WEBB Howard (ENG)</td>\n      <td>MULLARKEY Michael (ENG)</td>\n      <td>Darren CANN (ENG)</td>\n      <td>255951</td>\n      <td>300186487</td>\n      <td>BRA</td>\n      <td>CHI</td>\n    </tr>\n    <tr>\n      <th>821</th>\n      <td>2014</td>\n      <td>28 Jun 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Estadio do Maracana</td>\n      <td>Rio De Janeiro</td>\n      <td>Colombia</td>\n      <td>2</td>\n      <td>0</td>\n      <td>Uruguay</td>\n      <td></td>\n      <td>73804.0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>Bj\ufffdrn KUIPERS (NED)</td>\n      <td>Sander VAN ROEKEL (NED)</td>\n      <td>Erwin ZEINSTRA (NED)</td>\n      <td>255951</td>\n      <td>300186491</td>\n      <td>COL</td>\n      <td>URU</td>\n    </tr>\n    <tr>\n      <th>822</th>\n      <td>2014</td>\n      <td>30 Jun 2014 - 13:00</td>\n      <td>Round of 16</td>\n      <td>Estadio Nacional</td>\n      <td>Brasilia</td>\n      <td>France</td>\n      <td>2</td>\n      <td>0</td>\n      <td>Nigeria</td>\n      <td></td>\n      <td>67882.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>GEIGER Mark (USA)</td>\n      <td>HURD Sean (USA)</td>\n      <td>FLETCHER Joe (CAN)</td>\n      <td>255951</td>\n      <td>300186462</td>\n      <td>FRA</td>\n      <td>NGA</td>\n    </tr>\n    <tr>\n      <th>823</th>\n      <td>2014</td>\n      <td>30 Jun 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Estadio Beira-Rio</td>\n      <td>Porto Alegre</td>\n      <td>Germany</td>\n      <td>2</td>\n      <td>1</td>\n      <td>Algeria</td>\n      <td>Germany win after extra time</td>\n      <td>NaN</td>\n      <td>0</td>\n      <td>0</td>\n      <td>RICCI Sandro (BRA)</td>\n      <td>DE CARVALHO Emerson (BRA)</td>\n      <td>VAN GASSE Marcelo (BRA)</td>\n      <td>255951</td>\n      <td>300186460</td>\n      <td>GER</td>\n      <td>ALG</td>\n    </tr>\n    <tr>\n      <th>824</th>\n      <td>2014</td>\n      <td>04 Jul 2014 - 17:00</td>\n      <td>Quarter-finals</td>\n      <td>Estadio Castelao</td>\n      <td>Fortaleza</td>\n      <td>Brazil</td>\n      <td>2</td>\n      <td>1</td>\n      <td>Colombia</td>\n      <td></td>\n      <td>60342.0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>Carlos VELASCO CARBALLO (ESP)</td>\n      <td>ALONSO FERNANDEZ Roberto (ESP)</td>\n      <td>YUSTE Juan (ESP)</td>\n      <td>255953</td>\n      <td>300186461</td>\n      <td>BRA</td>\n      <td>COL</td>\n    </tr>\n    <tr>\n      <th>825</th>\n      <td>2014</td>\n      <td>04 Jul 2014 - 13:00</td>\n      <td>Quarter-finals</td>\n      <td>Estadio do Maracana</td>\n      <td>Rio De Janeiro</td>\n      <td>France</td>\n      <td>0</td>\n      <td>1</td>\n      <td>Germany</td>\n      <td></td>\n      <td>74240.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>PITANA Nestor (ARG)</td>\n      <td>MAIDANA Hernan (ARG)</td>\n      <td>BELATTI Juan Pablo (ARG)</td>\n      <td>255953</td>\n      <td>300186485</td>\n      <td>FRA</td>\n      <td>GER</td>\n    </tr>\n    <tr>\n      <th>826</th>\n      <td>2014</td>\n      <td>08 Jul 2014 - 17:00</td>\n      <td>Semi-finals</td>\n      <td>Estadio Mineirao</td>\n      <td>Belo Horizonte</td>\n      <td>Brazil</td>\n      <td>1</td>\n      <td>7</td>\n      <td>Germany</td>\n      <td></td>\n      <td>58141.0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>RODRIGUEZ Marco (MEX)</td>\n      <td>TORRENTERA Marvin (MEX)</td>\n      <td>QUINTERO Marcos (MEX)</td>\n      <td>255955</td>\n      <td>300186474</td>\n      <td>BRA</td>\n      <td>GER</td>\n    </tr>\n    <tr>\n      <th>827</th>\n      <td>2014</td>\n      <td>12 Jul 2014 - 17:00</td>\n      <td>Play-off for third place</td>\n      <td>Estadio Nacional</td>\n      <td>Brasilia</td>\n      <td>Brazil</td>\n      <td>0</td>\n      <td>3</td>\n      <td>Netherlands</td>\n      <td></td>\n      <td>68034.0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>HAIMOUDI Djamel (ALG)</td>\n      <td>ACHIK Redouane (MAR)</td>\n      <td>ETCHIALI Abdelhak (ALG)</td>\n      <td>255957</td>\n      <td>300186502</td>\n      <td>BRA</td>\n      <td>NED</td>\n    </tr>\n    <tr>\n      <th>828</th>\n      <td>2014</td>\n      <td>13 Jul 2014 - 16:00</td>\n      <td>Final</td>\n      <td>Estadio do Maracana</td>\n      <td>Rio De Janeiro</td>\n      <td>Germany</td>\n      <td>1</td>\n      <td>0</td>\n      <td>Argentina</td>\n      <td>Germany win after extra time</td>\n      <td>74738.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>Nicola RIZZOLI (ITA)</td>\n      <td>Renato FAVERANI (ITA)</td>\n      <td>Andrea STEFANI (ITA)</td>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>GER</td>\n      <td>ARG</td>\n    </tr>\n    <tr>\n      <th>829</th>\n      <td>2014</td>\n      <td>09 Jul 2014 - 17:00</td>\n      <td>Semi-finals</td>\n      <td>Arena de Sao Paulo</td>\n      <td>Sao Paulo</td>\n      <td>Netherlands</td>\n      <td>0</td>\n      <td>0</td>\n      <td>Argentina</td>\n      <td>Argentina win on penalties (2 - 4)</td>\n      <td>63267.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>C\ufffdneyt \ufffdAKIR (TUR)</td>\n      <td>DURAN Bahattin (TUR)</td>\n      <td>ONGUN Tarik (TUR)</td>\n      <td>255955</td>\n      <td>300186490</td>\n      <td>NED</td>\n      <td>ARG</td>\n    </tr>\n    <tr>\n      <th>830</th>\n      <td>2014</td>\n      <td>05 Jul 2014 - 17:00</td>\n      <td>Quarter-finals</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Netherlands</td>\n      <td>0</td>\n      <td>0</td>\n      <td>Costa Rica</td>\n      <td>Netherlands win on penalties (4 - 3)</td>\n      <td>51179.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>Ravshan IRMATOV (UZB)</td>\n      <td>RASULOV Abduxamidullo (UZB)</td>\n      <td>KOCHKAROV Bakhadyr (KGZ)</td>\n      <td>255953</td>\n      <td>300186488</td>\n      <td>NED</td>\n      <td>CRC</td>\n    </tr>\n    <tr>\n      <th>831</th>\n      <td>2014</td>\n      <td>05 Jul 2014 - 13:00</td>\n      <td>Quarter-finals</td>\n      <td>Estadio Nacional</td>\n      <td>Brasilia</td>\n      <td>Argentina</td>\n      <td>1</td>\n      <td>0</td>\n      <td>Belgium</td>\n      <td></td>\n      <td>68551.0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>Nicola RIZZOLI (ITA)</td>\n      <td>Renato FAVERANI (ITA)</td>\n      <td>Andrea STEFANI (ITA)</td>\n      <td>255953</td>\n      <td>300186504</td>\n      <td>ARG</td>\n      <td>BEL</td>\n    </tr>\n    <tr>\n      <th>832</th>\n      <td>2014</td>\n      <td>29 Jun 2014 - 13:00</td>\n      <td>Round of 16</td>\n      <td>Estadio Castelao</td>\n      <td>Fortaleza</td>\n      <td>Netherlands</td>\n      <td>2</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td></td>\n      <td>58817.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>PROENCA Pedro (POR)</td>\n      <td>MIRANDA Bertino (POR)</td>\n      <td>TRIGO Jose (POR)</td>\n      <td>255951</td>\n      <td>300186508</td>\n      <td>NED</td>\n      <td>MEX</td>\n    </tr>\n    <tr>\n      <th>833</th>\n      <td>2014</td>\n      <td>29 Jun 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Pernambuco</td>\n      <td>Recife</td>\n      <td>Costa Rica</td>\n      <td>1</td>\n      <td>1</td>\n      <td>Greece</td>\n      <td>Costa Rica win on penalties (5 - 3)</td>\n      <td>41242.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>Ben WILLIAMS (AUS)</td>\n      <td>CREAM Matthew (AUS)</td>\n      <td>ANAZ Hakan (AUS)</td>\n      <td>255951</td>\n      <td>300186459</td>\n      <td>CRC</td>\n      <td>GRE</td>\n    </tr>\n    <tr>\n      <th>834</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 13:00</td>\n      <td>Round of 16</td>\n      <td>Arena de Sao Paulo</td>\n      <td>Sao Paulo</td>\n      <td>Argentina</td>\n      <td>1</td>\n      <td>0</td>\n      <td>Switzerland</td>\n      <td>Argentina win after extra time</td>\n      <td>63255.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>ERIKSSON Jonas (SWE)</td>\n      <td>KLASENIUS Mathias (SWE)</td>\n      <td>WARNMARK Daniel (SWE)</td>\n      <td>255951</td>\n      <td>300186503</td>\n      <td>ARG</td>\n      <td>SUI</td>\n    </tr>\n    <tr>\n      <th>835</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>Belgium win after extra time</td>\n      <td>51227.0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>HAIMOUDI Djamel (ALG)</td>\n      <td>ACHIK Redouane (MAR)</td>\n      <td>ETCHIALI Abdelhak (ALG)</td>\n      <td>255951</td>\n      <td>300186497</td>\n      <td>BEL</td>\n      <td>USA</td>\n    </tr>\n  </tbody>\n</table>\n<p>836 rows \u00d7 20 columns</p>\n</div>\n\n\n\n\n```python\ndf_players\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>RoundID</th>\n      <th>MatchID</th>\n      <th>Team Initials</th>\n      <th>Coach Name</th>\n      <th>Line-up</th>\n      <th>Shirt Number</th>\n      <th>Player Name</th>\n      <th>Position</th>\n      <th>Event</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>FRA</td>\n      <td>CAUDRON Raoul (FRA)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Alex THEPOT</td>\n      <td>GK</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>MEX</td>\n      <td>LUQUE Juan (MEX)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Oscar BONFIGLIO</td>\n      <td>GK</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>FRA</td>\n      <td>CAUDRON Raoul (FRA)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Marcel LANGILLER</td>\n      <td>NaN</td>\n      <td>G40'</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>MEX</td>\n      <td>LUQUE Juan (MEX)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Juan CARRENO</td>\n      <td>NaN</td>\n      <td>G70'</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>FRA</td>\n      <td>CAUDRON Raoul (FRA)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Ernest LIBERATI</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>MEX</td>\n      <td>LUQUE Juan (MEX)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Rafael GARZA</td>\n      <td>C</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>FRA</td>\n      <td>CAUDRON Raoul (FRA)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Andre MASCHINOT</td>\n      <td>NaN</td>\n      <td>G43' G87'</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>MEX</td>\n      <td>LUQUE Juan (MEX)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Hilario LOPEZ</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>FRA</td>\n      <td>CAUDRON Raoul (FRA)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Etienne MATTLER</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>MEX</td>\n      <td>LUQUE Juan (MEX)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Dionisio MEJIA</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>FRA</td>\n      <td>CAUDRON Raoul (FRA)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Marcel PINEL</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>MEX</td>\n      <td>LUQUE Juan (MEX)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Felipe ROSAS</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>FRA</td>\n      <td>CAUDRON Raoul (FRA)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Alex VILLAPLANE</td>\n      <td>C</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>MEX</td>\n      <td>LUQUE Juan (MEX)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Manuel ROSAS</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>FRA</td>\n      <td>CAUDRON Raoul (FRA)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Lucien LAURENT</td>\n      <td>NaN</td>\n      <td>G19'</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>MEX</td>\n      <td>LUQUE Juan (MEX)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Jose RUIZ</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>FRA</td>\n      <td>CAUDRON Raoul (FRA)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Marcel CAPELLE</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>MEX</td>\n      <td>LUQUE Juan (MEX)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Alfredo SANCHEZ</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>FRA</td>\n      <td>CAUDRON Raoul (FRA)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Augustin CHANTREL</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>MEX</td>\n      <td>LUQUE Juan (MEX)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Efrain AMEZCUA</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>FRA</td>\n      <td>CAUDRON Raoul (FRA)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Edmond DELFOUR</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>MEX</td>\n      <td>LUQUE Juan (MEX)</td>\n      <td>S</td>\n      <td>0</td>\n      <td>Luis PEREZ</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>FRA</td>\n      <td>CAUDRON Raoul (FRA)</td>\n      <td>N</td>\n      <td>0</td>\n      <td>Celestin DELMER</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>MEX</td>\n      <td>LUQUE Juan (MEX)</td>\n      <td>N</td>\n      <td>0</td>\n      <td>Isidoro SOTA</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>FRA</td>\n      <td>CAUDRON Raoul (FRA)</td>\n      <td>N</td>\n      <td>0</td>\n      <td>Andre TASSIN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>MEX</td>\n      <td>LUQUE Juan (MEX)</td>\n      <td>N</td>\n      <td>0</td>\n      <td>Jesus CASTRO</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>FRA</td>\n      <td>CAUDRON Raoul (FRA)</td>\n      <td>N</td>\n      <td>0</td>\n      <td>Nouma ANDOIRE</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>MEX</td>\n      <td>LUQUE Juan (MEX)</td>\n      <td>N</td>\n      <td>0</td>\n      <td>Felipe OLIVARES</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>FRA</td>\n      <td>CAUDRON Raoul (FRA)</td>\n      <td>N</td>\n      <td>0</td>\n      <td>Jean LAURENT</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>201</td>\n      <td>1096</td>\n      <td>MEX</td>\n      <td>LUQUE Juan (MEX)</td>\n      <td>N</td>\n      <td>0</td>\n      <td>Raimundo RODRIGUEZ</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>37754</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>GER</td>\n      <td>LOEW Joachim (GER)</td>\n      <td>S</td>\n      <td>18</td>\n      <td>KROOS</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>37755</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>ARG</td>\n      <td>SABELLA Alejandro (ARG)</td>\n      <td>S</td>\n      <td>15</td>\n      <td>DEMICHELIS</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>37756</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>GER</td>\n      <td>LOEW Joachim (GER)</td>\n      <td>S</td>\n      <td>20</td>\n      <td>BOATENG</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>37757</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>ARG</td>\n      <td>SABELLA Alejandro (ARG)</td>\n      <td>S</td>\n      <td>16</td>\n      <td>ROJO</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>37758</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>GER</td>\n      <td>LOEW Joachim (GER)</td>\n      <td>S</td>\n      <td>23</td>\n      <td>KRAMER</td>\n      <td>NaN</td>\n      <td>O31'</td>\n    </tr>\n    <tr>\n      <th>37759</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>ARG</td>\n      <td>SABELLA Alejandro (ARG)</td>\n      <td>S</td>\n      <td>22</td>\n      <td>LAVEZZI</td>\n      <td>NaN</td>\n      <td>OH46'</td>\n    </tr>\n    <tr>\n      <th>37760</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>GER</td>\n      <td>LOEW Joachim (GER)</td>\n      <td>N</td>\n      <td>12</td>\n      <td>ZIELER</td>\n      <td>GK</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>37761</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>ARG</td>\n      <td>SABELLA Alejandro (ARG)</td>\n      <td>N</td>\n      <td>12</td>\n      <td>ORION</td>\n      <td>GK</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>37762</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>GER</td>\n      <td>LOEW Joachim (GER)</td>\n      <td>N</td>\n      <td>22</td>\n      <td>WEIDENFELLER</td>\n      <td>GK</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>37763</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>ARG</td>\n      <td>SABELLA Alejandro (ARG)</td>\n      <td>N</td>\n      <td>21</td>\n      <td>ANDUJAR</td>\n      <td>GK</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>37764</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>GER</td>\n      <td>LOEW Joachim (GER)</td>\n      <td>N</td>\n      <td>2</td>\n      <td>GRO\ufffdKREUTZ</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>37765</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>ARG</td>\n      <td>SABELLA Alejandro (ARG)</td>\n      <td>N</td>\n      <td>3</td>\n      <td>CAMPAGNARO</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>37766</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>GER</td>\n      <td>LOEW Joachim (GER)</td>\n      <td>N</td>\n      <td>3</td>\n      <td>GINTER</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>37767</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>ARG</td>\n      <td>SABELLA Alejandro (ARG)</td>\n      <td>N</td>\n      <td>5</td>\n      <td>GAGO</td>\n      <td>NaN</td>\n      <td>I86'</td>\n    </tr>\n    <tr>\n      <th>37768</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>GER</td>\n      <td>LOEW Joachim (GER)</td>\n      <td>N</td>\n      <td>9</td>\n      <td>SCH\ufffdRRLE</td>\n      <td>NaN</td>\n      <td>I31'</td>\n    </tr>\n    <tr>\n      <th>37769</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>ARG</td>\n      <td>SABELLA Alejandro (ARG)</td>\n      <td>N</td>\n      <td>7</td>\n      <td>DI MARIA</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>37770</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>GER</td>\n      <td>LOEW Joachim (GER)</td>\n      <td>N</td>\n      <td>10</td>\n      <td>PODOLSKI</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>37771</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>ARG</td>\n      <td>SABELLA Alejandro (ARG)</td>\n      <td>N</td>\n      <td>11</td>\n      <td>M. RODRIGUEZ</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>37772</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>GER</td>\n      <td>LOEW Joachim (GER)</td>\n      <td>N</td>\n      <td>14</td>\n      <td>DRAXLER</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>37773</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>ARG</td>\n      <td>SABELLA Alejandro (ARG)</td>\n      <td>N</td>\n      <td>13</td>\n      <td>A. FERNANDEZ</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>37774</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>GER</td>\n      <td>LOEW Joachim (GER)</td>\n      <td>N</td>\n      <td>15</td>\n      <td>DURM</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>37775</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>ARG</td>\n      <td>SABELLA Alejandro (ARG)</td>\n      <td>N</td>\n      <td>17</td>\n      <td>F. FERNANDEZ</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>37776</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>GER</td>\n      <td>LOEW Joachim (GER)</td>\n      <td>N</td>\n      <td>17</td>\n      <td>MERTESACKER</td>\n      <td>NaN</td>\n      <td>I120'</td>\n    </tr>\n    <tr>\n      <th>37777</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>ARG</td>\n      <td>SABELLA Alejandro (ARG)</td>\n      <td>N</td>\n      <td>18</td>\n      <td>PALACIO</td>\n      <td>NaN</td>\n      <td>I78'</td>\n    </tr>\n    <tr>\n      <th>37778</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>GER</td>\n      <td>LOEW Joachim (GER)</td>\n      <td>N</td>\n      <td>19</td>\n      <td>G\ufffdTZE</td>\n      <td>NaN</td>\n      <td>I88' G113'</td>\n    </tr>\n    <tr>\n      <th>37779</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>ARG</td>\n      <td>SABELLA Alejandro (ARG)</td>\n      <td>N</td>\n      <td>19</td>\n      <td>ALVAREZ</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>37780</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>GER</td>\n      <td>LOEW Joachim (GER)</td>\n      <td>N</td>\n      <td>6</td>\n      <td>KHEDIRA</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>37781</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>ARG</td>\n      <td>SABELLA Alejandro (ARG)</td>\n      <td>N</td>\n      <td>20</td>\n      <td>AGUERO</td>\n      <td>NaN</td>\n      <td>IH46' Y65'</td>\n    </tr>\n    <tr>\n      <th>37782</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>GER</td>\n      <td>LOEW Joachim (GER)</td>\n      <td>N</td>\n      <td>21</td>\n      <td>MUSTAFI</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>37783</th>\n      <td>255959</td>\n      <td>300186501</td>\n      <td>ARG</td>\n      <td>SABELLA Alejandro (ARG)</td>\n      <td>N</td>\n      <td>23</td>\n      <td>BASANTA</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n<p>37784 rows \u00d7 9 columns</p>\n</div>\n\n\n\n\n```python\ndf_events\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Year</th>\n      <th>Datetime</th>\n      <th>Stage</th>\n      <th>Stadium</th>\n      <th>City</th>\n      <th>Home Team Name</th>\n      <th>Home Team Goals</th>\n      <th>Away Team Goals</th>\n      <th>Away Team Name</th>\n      <th>Attendance</th>\n      <th>...</th>\n      <th>GoldenGoal</th>\n      <th>DecisionPenaltyAway</th>\n      <th>DecisionPenaltyHome</th>\n      <th>HomeTeamWins</th>\n      <th>AwayTeamWins</th>\n      <th>EventOfHomeTeam</th>\n      <th>EventOfWinner</th>\n      <th>EventOfLoser</th>\n      <th>HourGameStart</th>\n      <th>StageRank</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>15</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>39389</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39390</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39391</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39392</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39393</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39394</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39395</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39396</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39397</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39398</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39399</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39400</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39401</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39402</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39403</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39404</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39405</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39406</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39407</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39408</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39409</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39410</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39411</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39412</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39413</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39414</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39415</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39416</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39417</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>True</td>\n      <td>True</td>\n      <td>False</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>39418</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227</td>\n      <td>...</td>\n      <td>False</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>False</td>\n      <td>False</td>\n      <td>False</td>\n      <td>True</td>\n      <td>17</td>\n      <td>2</td>\n    </tr>\n  </tbody>\n</table>\n<p>39419 rows \u00d7 39 columns</p>\n</div>\n\n\n\n# Descriptive part\nIn this section we provide some general details about the dataset. First question is: Who won most world cups? Who won most second prizes?\n\n\n```python\nplt.figure(figsize=(14,7))\nplt.subplot(121)\ndf_cups.groupby(['Winner']).size().sort_values(ascending=False).plot.bar()\nplt.title(\"World Cup Wins\")\nplt.xlabel(\"\")\n\nplt.subplot(122)\ndf_cups.groupby(['Runners-Up']).size().sort_values(ascending=False).plot.bar()\nplt.title(\"2nd Prize\")\nplt.xlabel(\"\")\n\nplt.show()\n```\n\nNext question is: Who scored most goals in world championships?\n\n\n```python\nplt.figure(figsize=(9,6))\n\ndf_players.groupby(['Player Name']).size().sort_values(ascending=False).nlargest(n=10).plot.bar()\nprint(df_players.groupby(['Player Name']).size().sort_values(ascending=False).nlargest(n=10))\n```\n\n\n```python\n# data consistency not sufficient for this calculation as player names are not unique\n# note that this does not have an impact on the subsequent analysis\n\n#df_timespan = df_joined_matches[['Player Name','Year']].groupby(['Player Name']).aggregate(['min','max']).Year\n#df_timespan.columns = ['start','end']\n#df_timespan.apply(lambda x: (x.end-x.start), axis=1).sort_values(ascending = False)\n```\n\n# Analysis of Fair Play\n\nWe first need some preliminary work. How many matches were played at all? How many of them were won by one team?\n\n\n```python\nnum_matches_total = len(df_events.groupby('MatchID').mean())\nnum_matches_decision = len(df_events.loc[(df_events['HomeTeamWins'] == True) | (df_events['AwayTeamWins'] == True)].groupby('MatchID').mean())\nnum_matches_tie = len(df_events.loc[(df_events['HomeTeamWins'] == False) & (df_events['AwayTeamWins'] == False)].groupby('MatchID').mean())\n\nprint(\"num_matches_total: %g\"% num_matches_total)\nprint(\"num_matches_decision: %g\"% num_matches_decision)\nprint(\"num_matches_tie: %g\"% num_matches_tie)\n\nprint(\"proportion decision: %.2f\"% (num_matches_decision/num_matches_total*100))\nprint(\"proportion no decision: %.2f\"% (num_matches_tie/num_matches_total*100))\n```\n\n    num_matches_total: 836\n    num_matches_decision: 676\n    num_matches_tie: 160\n    proportion decision: 80.86\n    proportion no decision: 19.14\n\n\n## Yellow and Red Cards Statistics\n\nOn average 2.68 yellow cards, 0.14 red cards and 0.06 red cards for second yellow are given during a match.\n\n\n```python\nf = {\n     'Year':'count' # we could do this with any attribute\n    }\n\ndf_cards = df_events.loc[(df_events[\"EventType\"] == \"Y\") | (df_events[\"EventType\"] == \"R\") | (df_events[\"EventType\"] == \"RSY\")]\ndf_cards = df_cards.groupby([\"EventType\"]).agg(f)\ndf_cards.columns = ['Total']\ndf_cards.assign(AvgPerMatch = lambda x : x.Total/num_matches_total)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Total</th>\n      <th>AvgPerMatch</th>\n    </tr>\n    <tr>\n      <th>EventType</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>R</th>\n      <td>117</td>\n      <td>0.139952</td>\n    </tr>\n    <tr>\n      <th>RSY</th>\n      <td>52</td>\n      <td>0.062201</td>\n    </tr>\n    <tr>\n      <th>Y</th>\n      <td>2246</td>\n      <td>2.686603</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThe match with most cards was Portugal vs. Greece in 2006's Round of 16 with 20 cards. \n\n\n```python\nf = {\n     'Attendance':'count' # again, we could do this with any attribute\n    }\n\ndf_cards = df_events.loc[(df_events[\"EventType\"] == \"Y\") | (df_events[\"EventType\"] == \"R\") | (df_events[\"EventType\"] == \"RSY\")]\ndf_cards = df_cards.groupby(['MatchID','Stage','Year','Home Team Name', 'Away Team Name', 'Home Team Goals', 'Away Team Goals']).agg(f).reset_index()\ndf_cards.columns = ['Match ID', 'Stage','Year', 'Home Team Name', 'Away Team Name', 'Home Team Goals', 'Away Team Goals', 'Cards']\ndf_cards.sort_values(by=['Cards'], ascending=False)\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Match ID</th>\n      <th>Stage</th>\n      <th>Year</th>\n      <th>Home Team Name</th>\n      <th>Away Team Name</th>\n      <th>Home Team Goals</th>\n      <th>Away Team Goals</th>\n      <th>Cards</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>474</th>\n      <td>97410052</td>\n      <td>Round of 16</td>\n      <td>2006</td>\n      <td>Portugal</td>\n      <td>Netherlands</td>\n      <td>1</td>\n      <td>0</td>\n      <td>20</td>\n    </tr>\n    <tr>\n      <th>556</th>\n      <td>300186459</td>\n      <td>Round of 16</td>\n      <td>2014</td>\n      <td>Costa Rica</td>\n      <td>Greece</td>\n      <td>1</td>\n      <td>1</td>\n      <td>18</td>\n    </tr>\n    <tr>\n      <th>394</th>\n      <td>43950035</td>\n      <td>Group E</td>\n      <td>2002</td>\n      <td>Cameroon</td>\n      <td>Germany</td>\n      <td>0</td>\n      <td>2</td>\n      <td>18</td>\n    </tr>\n    <tr>\n      <th>540</th>\n      <td>300061509</td>\n      <td>Final</td>\n      <td>2010</td>\n      <td>Netherlands</td>\n      <td>Spain</td>\n      <td>0</td>\n      <td>1</td>\n      <td>15</td>\n    </tr>\n    <tr>\n      <th>584</th>\n      <td>300186487</td>\n      <td>Round of 16</td>\n      <td>2014</td>\n      <td>Brazil</td>\n      <td>Chile</td>\n      <td>1</td>\n      <td>1</td>\n      <td>14</td>\n    </tr>\n    <tr>\n      <th>288</th>\n      <td>3092</td>\n      <td>Round of 16</td>\n      <td>1994</td>\n      <td>Mexico</td>\n      <td>Bulgaria</td>\n      <td>1</td>\n      <td>1</td>\n      <td>12</td>\n    </tr>\n    <tr>\n      <th>393</th>\n      <td>43950034</td>\n      <td>Group A</td>\n      <td>2002</td>\n      <td>Senegal</td>\n      <td>Uruguay</td>\n      <td>3</td>\n      <td>3</td>\n      <td>12</td>\n    </tr>\n    <tr>\n      <th>585</th>\n      <td>300186488</td>\n      <td>Quarter-finals</td>\n      <td>2014</td>\n      <td>Netherlands</td>\n      <td>Costa Rica</td>\n      <td>0</td>\n      <td>0</td>\n      <td>12</td>\n    </tr>\n    <tr>\n      <th>466</th>\n      <td>97410044</td>\n      <td>Group F</td>\n      <td>2006</td>\n      <td>Croatia</td>\n      <td>Australia</td>\n      <td>2</td>\n      <td>2</td>\n      <td>11</td>\n    </tr>\n    <tr>\n      <th>411</th>\n      <td>43950053</td>\n      <td>Round of 16</td>\n      <td>2002</td>\n      <td>Mexico</td>\n      <td>USA</td>\n      <td>0</td>\n      <td>2</td>\n      <td>11</td>\n    </tr>\n    <tr>\n      <th>460</th>\n      <td>97410038</td>\n      <td>Group C</td>\n      <td>2006</td>\n      <td>C\ufffdte d'Ivoire</td>\n      <td>rn\"&gt;Serbia and Montenegro</td>\n      <td>3</td>\n      <td>2</td>\n      <td>11</td>\n    </tr>\n    <tr>\n      <th>456</th>\n      <td>97410034</td>\n      <td>Group A</td>\n      <td>2006</td>\n      <td>Costa Rica</td>\n      <td>Poland</td>\n      <td>1</td>\n      <td>2</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>599</th>\n      <td>300186502</td>\n      <td>Play-off for third place</td>\n      <td>2014</td>\n      <td>Brazil</td>\n      <td>Netherlands</td>\n      <td>0</td>\n      <td>3</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>600</th>\n      <td>300186503</td>\n      <td>Round of 16</td>\n      <td>2014</td>\n      <td>Argentina</td>\n      <td>Switzerland</td>\n      <td>1</td>\n      <td>0</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>287</th>\n      <td>3091</td>\n      <td>Round of 16</td>\n      <td>1994</td>\n      <td>Nigeria</td>\n      <td>Italy</td>\n      <td>1</td>\n      <td>2</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>461</th>\n      <td>97410039</td>\n      <td>Group D</td>\n      <td>2006</td>\n      <td>Portugal</td>\n      <td>Mexico</td>\n      <td>2</td>\n      <td>1</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>414</th>\n      <td>43950056</td>\n      <td>Round of 16</td>\n      <td>2002</td>\n      <td>Korea Republic</td>\n      <td>Italy</td>\n      <td>2</td>\n      <td>1</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>318</th>\n      <td>8746</td>\n      <td>Group C</td>\n      <td>1998</td>\n      <td>South Africa</td>\n      <td>Denmark</td>\n      <td>1</td>\n      <td>1</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>84</th>\n      <td>575</td>\n      <td>Quarter-finals</td>\n      <td>1986</td>\n      <td>Germany FR</td>\n      <td>Mexico</td>\n      <td>0</td>\n      <td>0</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>280</th>\n      <td>3084</td>\n      <td>Group D</td>\n      <td>1994</td>\n      <td>Argentina</td>\n      <td>Bulgaria</td>\n      <td>0</td>\n      <td>2</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>526</th>\n      <td>300061493</td>\n      <td>Group H</td>\n      <td>2010</td>\n      <td>Chile</td>\n      <td>Switzerland</td>\n      <td>1</td>\n      <td>0</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>48</td>\n      <td>Group A</td>\n      <td>1990</td>\n      <td>Austria</td>\n      <td>USA</td>\n      <td>2</td>\n      <td>1</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>507</th>\n      <td>300061470</td>\n      <td>Group D</td>\n      <td>2010</td>\n      <td>Germany</td>\n      <td>Serbia</td>\n      <td>0</td>\n      <td>1</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>468</th>\n      <td>97410046</td>\n      <td>Group G</td>\n      <td>2006</td>\n      <td>Switzerland</td>\n      <td>Korea Republic</td>\n      <td>2</td>\n      <td>0</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>405</th>\n      <td>43950047</td>\n      <td>Group D</td>\n      <td>2002</td>\n      <td>Portugal</td>\n      <td>Korea Republic</td>\n      <td>0</td>\n      <td>1</td>\n      <td>9</td>\n    </tr>\n    <tr>\n      <th>286</th>\n      <td>3090</td>\n      <td>Round of 16</td>\n      <td>1994</td>\n      <td>Brazil</td>\n      <td>USA</td>\n      <td>1</td>\n      <td>0</td>\n      <td>9</td>\n    </tr>\n    <tr>\n      <th>59</th>\n      <td>427</td>\n      <td>Group B</td>\n      <td>1986</td>\n      <td>Iraq</td>\n      <td>Belgium</td>\n      <td>1</td>\n      <td>2</td>\n      <td>9</td>\n    </tr>\n    <tr>\n      <th>470</th>\n      <td>97410048</td>\n      <td>Group H</td>\n      <td>2006</td>\n      <td>Ukraine</td>\n      <td>Tunisia</td>\n      <td>1</td>\n      <td>0</td>\n      <td>9</td>\n    </tr>\n    <tr>\n      <th>477</th>\n      <td>97410055</td>\n      <td>Round of 16</td>\n      <td>2006</td>\n      <td>Brazil</td>\n      <td>Ghana</td>\n      <td>3</td>\n      <td>0</td>\n      <td>9</td>\n    </tr>\n    <tr>\n      <th>290</th>\n      <td>3096</td>\n      <td>Quarter-finals</td>\n      <td>1994</td>\n      <td>Bulgaria</td>\n      <td>Germany</td>\n      <td>2</td>\n      <td>1</td>\n      <td>8</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>146</th>\n      <td>1422</td>\n      <td>Group 1</td>\n      <td>1958</td>\n      <td>Northern Ireland</td>\n      <td>Czechoslovakia</td>\n      <td>2</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>113</th>\n      <td>833</td>\n      <td>Group 1</td>\n      <td>1982</td>\n      <td>Peru</td>\n      <td>Cameroon</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>180</th>\n      <td>1884</td>\n      <td>Group 2</td>\n      <td>1970</td>\n      <td>Uruguay</td>\n      <td>Italy</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>226</th>\n      <td>2246</td>\n      <td>Group 3</td>\n      <td>1978</td>\n      <td>Brazil</td>\n      <td>Spain</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>205</th>\n      <td>2065</td>\n      <td>Group B</td>\n      <td>1974</td>\n      <td>Germany FR</td>\n      <td>Sweden</td>\n      <td>4</td>\n      <td>2</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>68</th>\n      <td>463</td>\n      <td>Round of 16</td>\n      <td>1986</td>\n      <td>Mexico</td>\n      <td>Bulgaria</td>\n      <td>2</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>222</th>\n      <td>2200</td>\n      <td>Group 1</td>\n      <td>1978</td>\n      <td>Italy</td>\n      <td>Argentina</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>72</th>\n      <td>517</td>\n      <td>Group E</td>\n      <td>1986</td>\n      <td>Scotland</td>\n      <td>Denmark</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>548</th>\n      <td>300111117</td>\n      <td>Group E</td>\n      <td>2010</td>\n      <td>Netherlands</td>\n      <td>Japan</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>219</th>\n      <td>2197</td>\n      <td>Group 1</td>\n      <td>1978</td>\n      <td>Argentina</td>\n      <td>France</td>\n      <td>2</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>76</th>\n      <td>537</td>\n      <td>Group F</td>\n      <td>1986</td>\n      <td>England</td>\n      <td>Poland</td>\n      <td>3</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>476</th>\n      <td>97410054</td>\n      <td>Round of 16</td>\n      <td>2006</td>\n      <td>Switzerland</td>\n      <td>Ukraine</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>215</th>\n      <td>2181</td>\n      <td>Group 3</td>\n      <td>1974</td>\n      <td>Sweden</td>\n      <td>Uruguay</td>\n      <td>3</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>423</th>\n      <td>97410001</td>\n      <td>Group A</td>\n      <td>2006</td>\n      <td>Germany</td>\n      <td>Costa Rica</td>\n      <td>4</td>\n      <td>2</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>208</th>\n      <td>2085</td>\n      <td>Group 4</td>\n      <td>1974</td>\n      <td>Haiti</td>\n      <td>Poland</td>\n      <td>0</td>\n      <td>7</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>207</th>\n      <td>2083</td>\n      <td>Group 4</td>\n      <td>1974</td>\n      <td>Italy</td>\n      <td>Haiti</td>\n      <td>3</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>90</th>\n      <td>674</td>\n      <td>Group F</td>\n      <td>1986</td>\n      <td>Morocco</td>\n      <td>Poland</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>183</th>\n      <td>1925</td>\n      <td>Quarter-finals</td>\n      <td>1970</td>\n      <td>Uruguay</td>\n      <td>Soviet Union</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>91</th>\n      <td>675</td>\n      <td>Group F</td>\n      <td>1986</td>\n      <td>Portugal</td>\n      <td>Morocco</td>\n      <td>1</td>\n      <td>3</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>533</th>\n      <td>300061502</td>\n      <td>Round of 16</td>\n      <td>2010</td>\n      <td>Argentina</td>\n      <td>Mexico</td>\n      <td>3</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>95</th>\n      <td>739</td>\n      <td>Group 2</td>\n      <td>1982</td>\n      <td>Algeria</td>\n      <td>Austria</td>\n      <td>0</td>\n      <td>2</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>96</th>\n      <td>740</td>\n      <td>Group 2</td>\n      <td>1982</td>\n      <td>Algeria</td>\n      <td>Chile</td>\n      <td>3</td>\n      <td>2</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>191</th>\n      <td>1954</td>\n      <td>Group 1</td>\n      <td>1974</td>\n      <td>Australia</td>\n      <td>Germany FR</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>103</th>\n      <td>767</td>\n      <td>Group 4</td>\n      <td>1982</td>\n      <td>Austria</td>\n      <td>France</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>523</th>\n      <td>300061490</td>\n      <td>Group G</td>\n      <td>2010</td>\n      <td>Brazil</td>\n      <td>Korea DPR</td>\n      <td>2</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>105</th>\n      <td>771</td>\n      <td>Group 4</td>\n      <td>1982</td>\n      <td>Austria</td>\n      <td>Northern Ireland</td>\n      <td>2</td>\n      <td>2</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>184</th>\n      <td>1945</td>\n      <td>Group A</td>\n      <td>1974</td>\n      <td>Argentina</td>\n      <td>Brazil</td>\n      <td>1</td>\n      <td>2</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>108</th>\n      <td>782</td>\n      <td>Group 1</td>\n      <td>1982</td>\n      <td>Poland</td>\n      <td>Belgium</td>\n      <td>3</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>109</th>\n      <td>783</td>\n      <td>Group 1</td>\n      <td>1982</td>\n      <td>Belgium</td>\n      <td>Soviet Union</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>141</th>\n      <td>1165</td>\n      <td>First round</td>\n      <td>1938</td>\n      <td>Switzerland</td>\n      <td>Germany</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n<p>613 rows \u00d7 8 columns</p>\n</div>\n\n\n\nDuring the match, 4 players were given a red card by second yellow. \n\n\n```python\ndf_events.loc[(df_events[\"MatchID\"] == 97410052.0) & (df_events[\"EventType\"] != \"\") & (df_events[\"EventType\"] != \"I\")][['Team Initials','Player Name','EventMinute','EventType']]\n\n#[df_events.MatchID == 97410052][['EventOfHomeTeam','EventType','Player Name']]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Team Initials</th>\n      <th>Player Name</th>\n      <th>EventMinute</th>\n      <th>EventType</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>31789</th>\n      <td>POR</td>\n      <td>RICARDO</td>\n      <td>76</td>\n      <td>Y</td>\n    </tr>\n    <tr>\n      <th>31792</th>\n      <td>NED</td>\n      <td>BOULAHROUZ</td>\n      <td>7</td>\n      <td>Y</td>\n    </tr>\n    <tr>\n      <th>31793</th>\n      <td>NED</td>\n      <td>BOULAHROUZ</td>\n      <td>63</td>\n      <td>Y</td>\n    </tr>\n    <tr>\n      <th>31794</th>\n      <td>NED</td>\n      <td>BOULAHROUZ</td>\n      <td>63</td>\n      <td>RSY</td>\n    </tr>\n    <tr>\n      <th>31795</th>\n      <td>POR</td>\n      <td>COSTINHA</td>\n      <td>31</td>\n      <td>Y</td>\n    </tr>\n    <tr>\n      <th>31796</th>\n      <td>POR</td>\n      <td>COSTINHA</td>\n      <td>45</td>\n      <td>Y</td>\n    </tr>\n    <tr>\n      <th>31797</th>\n      <td>POR</td>\n      <td>COSTINHA</td>\n      <td>45</td>\n      <td>RSY</td>\n    </tr>\n    <tr>\n      <th>31798</th>\n      <td>NED</td>\n      <td>MATHIJSEN</td>\n      <td>56</td>\n      <td>O</td>\n    </tr>\n    <tr>\n      <th>31799</th>\n      <td>POR</td>\n      <td>FIGO</td>\n      <td>60</td>\n      <td>Y</td>\n    </tr>\n    <tr>\n      <th>31800</th>\n      <td>POR</td>\n      <td>FIGO</td>\n      <td>84</td>\n      <td>O</td>\n    </tr>\n    <tr>\n      <th>31801</th>\n      <td>NED</td>\n      <td>V. BRONCKHORST</td>\n      <td>59</td>\n      <td>Y</td>\n    </tr>\n    <tr>\n      <th>31802</th>\n      <td>NED</td>\n      <td>V. BRONCKHORST</td>\n      <td>90</td>\n      <td>Y</td>\n    </tr>\n    <tr>\n      <th>31803</th>\n      <td>NED</td>\n      <td>V. BRONCKHORST</td>\n      <td>90</td>\n      <td>RSY</td>\n    </tr>\n    <tr>\n      <th>31804</th>\n      <td>POR</td>\n      <td>PAULETA</td>\n      <td>46</td>\n      <td>O</td>\n    </tr>\n    <tr>\n      <th>31807</th>\n      <td>NED</td>\n      <td>COCU</td>\n      <td>84</td>\n      <td>O</td>\n    </tr>\n    <tr>\n      <th>31808</th>\n      <td>POR</td>\n      <td>N.VALENTE</td>\n      <td>76</td>\n      <td>Y</td>\n    </tr>\n    <tr>\n      <th>31812</th>\n      <td>POR</td>\n      <td>C.RONALDO</td>\n      <td>34</td>\n      <td>O</td>\n    </tr>\n    <tr>\n      <th>31814</th>\n      <td>POR</td>\n      <td>MANICHE</td>\n      <td>20</td>\n      <td>Y</td>\n    </tr>\n    <tr>\n      <th>31815</th>\n      <td>POR</td>\n      <td>MANICHE</td>\n      <td>23</td>\n      <td>G</td>\n    </tr>\n    <tr>\n      <th>31816</th>\n      <td>NED</td>\n      <td>V. BOMMEL</td>\n      <td>2</td>\n      <td>Y</td>\n    </tr>\n    <tr>\n      <th>31817</th>\n      <td>NED</td>\n      <td>V. BOMMEL</td>\n      <td>67</td>\n      <td>O</td>\n    </tr>\n    <tr>\n      <th>31818</th>\n      <td>POR</td>\n      <td>DECO</td>\n      <td>73</td>\n      <td>Y</td>\n    </tr>\n    <tr>\n      <th>31819</th>\n      <td>POR</td>\n      <td>DECO</td>\n      <td>78</td>\n      <td>Y</td>\n    </tr>\n    <tr>\n      <th>31820</th>\n      <td>POR</td>\n      <td>DECO</td>\n      <td>78</td>\n      <td>RSY</td>\n    </tr>\n    <tr>\n      <th>31821</th>\n      <td>NED</td>\n      <td>SNEIJDER</td>\n      <td>73</td>\n      <td>Y</td>\n    </tr>\n    <tr>\n      <th>31829</th>\n      <td>POR</td>\n      <td>PETIT</td>\n      <td>50</td>\n      <td>Y</td>\n    </tr>\n    <tr>\n      <th>31831</th>\n      <td>NED</td>\n      <td>VAN DER VAART</td>\n      <td>74</td>\n      <td>Y</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## Event minutes of red and yellow cards\n\nIn this section we want to find out when most yellow and red cards are given. As expected, red cards tend to be given later.\n\n\n```python\ndf_events[['EventMinute']] = df_events[['EventMinute']].apply(pd.to_numeric)\n#df_events.loc[(df_events['EventType'] == \"Y\") & (int(df_events['EventMinute']) < 20)]\nminutes_yellow = df_events[df_events.EventType == \"Y\"].EventMinute.values\nminutes_red = df_events[df_events.EventType == \"R\"].EventMinute.values\nminutes_red_2nd_yellow = df_events[df_events.EventType == \"RSY\"].EventMinute.values\n\nplt.figure(figsize=(12,6))\n\nax = plt.subplot(131)\n\nax.boxplot(minutes_yellow)\nplt.title(\"Yellow Cards\")\n\nax = plt.subplot(132)\n\nax.boxplot(minutes_red)\nplt.title(\"Red Cards\")\n\nax = plt.subplot(133)\n\nax.boxplot(minutes_red_2nd_yellow)\nplt.title(\"Red Cards (By 2nd Yellow)\")\n\nplt.show()\n```\n\n# Fairest team\n\nIn this section we want to find out which team is given the fewest yellow cards per match on average. First we have to find out how many yellow cards a team was awarded. We have to create to dataframes as teams appear either as home or away team.\n\n\n```python\ndf_yellow_cards = df_events[df_events.EventType == \"Y\"]\n\ndf_yellow_cards_home = df_yellow_cards[df_yellow_cards.EventOfHomeTeam == True][[\"Home Team Name\", \"EventType\"]]\ndf_yellow_cards_home = df_yellow_cards_home.groupby(\"Home Team Name\").count().reset_index()\ndf_yellow_cards_home.columns = ['Team', 'YellowCardsHome']\n\ndf_yellow_cards_away = df_yellow_cards[df_yellow_cards.EventOfHomeTeam == False][[\"Away Team Name\", \"EventType\"]]\ndf_yellow_cards_away = df_yellow_cards_away.groupby(\"Away Team Name\").count().reset_index()\ndf_yellow_cards_away.columns = ['Team', 'YellowCardsAway']\n\ndf_yellow_cards_count = pd.merge(df_yellow_cards_home, df_yellow_cards_away).fillna(0)\ndf_yellow_cards_count['YellowCardsTotal'] = df_yellow_cards_count.YellowCardsHome+df_yellow_cards_count.YellowCardsAway\ndf_yellow_cards_count\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Team</th>\n      <th>YellowCardsHome</th>\n      <th>YellowCardsAway</th>\n      <th>YellowCardsTotal</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Algeria</td>\n      <td>9</td>\n      <td>10</td>\n      <td>19</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Angola</td>\n      <td>3</td>\n      <td>8</td>\n      <td>11</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Argentina</td>\n      <td>70</td>\n      <td>50</td>\n      <td>120</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Australia</td>\n      <td>12</td>\n      <td>14</td>\n      <td>26</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Austria</td>\n      <td>12</td>\n      <td>11</td>\n      <td>23</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>Belgium</td>\n      <td>18</td>\n      <td>23</td>\n      <td>41</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Brazil</td>\n      <td>86</td>\n      <td>23</td>\n      <td>109</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Bulgaria</td>\n      <td>13</td>\n      <td>26</td>\n      <td>39</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>Cameroon</td>\n      <td>26</td>\n      <td>22</td>\n      <td>48</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>Chile</td>\n      <td>22</td>\n      <td>26</td>\n      <td>48</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>China PR</td>\n      <td>3</td>\n      <td>2</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>Colombia</td>\n      <td>10</td>\n      <td>15</td>\n      <td>25</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>Costa Rica</td>\n      <td>20</td>\n      <td>22</td>\n      <td>42</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>Croatia</td>\n      <td>7</td>\n      <td>30</td>\n      <td>37</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>Czech Republic</td>\n      <td>3</td>\n      <td>4</td>\n      <td>7</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>Czechoslovakia</td>\n      <td>3</td>\n      <td>15</td>\n      <td>18</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>C\ufffdte d'Ivoire</td>\n      <td>8</td>\n      <td>13</td>\n      <td>21</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>Denmark</td>\n      <td>13</td>\n      <td>18</td>\n      <td>31</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>Ecuador</td>\n      <td>6</td>\n      <td>17</td>\n      <td>23</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>England</td>\n      <td>30</td>\n      <td>21</td>\n      <td>51</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>France</td>\n      <td>28</td>\n      <td>31</td>\n      <td>59</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>German DR</td>\n      <td>6</td>\n      <td>4</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>Germany</td>\n      <td>55</td>\n      <td>24</td>\n      <td>79</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>Germany FR</td>\n      <td>26</td>\n      <td>14</td>\n      <td>40</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>Ghana</td>\n      <td>10</td>\n      <td>25</td>\n      <td>35</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>Greece</td>\n      <td>6</td>\n      <td>17</td>\n      <td>23</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>Haiti</td>\n      <td>1</td>\n      <td>2</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>Honduras</td>\n      <td>5</td>\n      <td>10</td>\n      <td>15</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>Hungary</td>\n      <td>2</td>\n      <td>4</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>IR Iran</td>\n      <td>1</td>\n      <td>9</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>42</th>\n      <td>Norway</td>\n      <td>2</td>\n      <td>11</td>\n      <td>13</td>\n    </tr>\n    <tr>\n      <th>43</th>\n      <td>Paraguay</td>\n      <td>16</td>\n      <td>25</td>\n      <td>41</td>\n    </tr>\n    <tr>\n      <th>44</th>\n      <td>Peru</td>\n      <td>1</td>\n      <td>8</td>\n      <td>9</td>\n    </tr>\n    <tr>\n      <th>45</th>\n      <td>Poland</td>\n      <td>20</td>\n      <td>22</td>\n      <td>42</td>\n    </tr>\n    <tr>\n      <th>46</th>\n      <td>Portugal</td>\n      <td>34</td>\n      <td>12</td>\n      <td>46</td>\n    </tr>\n    <tr>\n      <th>47</th>\n      <td>Romania</td>\n      <td>20</td>\n      <td>12</td>\n      <td>32</td>\n    </tr>\n    <tr>\n      <th>48</th>\n      <td>Russia</td>\n      <td>6</td>\n      <td>16</td>\n      <td>22</td>\n    </tr>\n    <tr>\n      <th>49</th>\n      <td>Saudi Arabia</td>\n      <td>12</td>\n      <td>10</td>\n      <td>22</td>\n    </tr>\n    <tr>\n      <th>50</th>\n      <td>Scotland</td>\n      <td>8</td>\n      <td>9</td>\n      <td>17</td>\n    </tr>\n    <tr>\n      <th>51</th>\n      <td>Senegal</td>\n      <td>9</td>\n      <td>5</td>\n      <td>14</td>\n    </tr>\n    <tr>\n      <th>52</th>\n      <td>Serbia</td>\n      <td>4</td>\n      <td>6</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>53</th>\n      <td>Slovakia</td>\n      <td>7</td>\n      <td>4</td>\n      <td>11</td>\n    </tr>\n    <tr>\n      <th>54</th>\n      <td>Slovenia</td>\n      <td>11</td>\n      <td>8</td>\n      <td>19</td>\n    </tr>\n    <tr>\n      <th>55</th>\n      <td>South Africa</td>\n      <td>16</td>\n      <td>5</td>\n      <td>21</td>\n    </tr>\n    <tr>\n      <th>56</th>\n      <td>Soviet Union</td>\n      <td>4</td>\n      <td>14</td>\n      <td>18</td>\n    </tr>\n    <tr>\n      <th>57</th>\n      <td>Spain</td>\n      <td>33</td>\n      <td>31</td>\n      <td>64</td>\n    </tr>\n    <tr>\n      <th>58</th>\n      <td>Sweden</td>\n      <td>19</td>\n      <td>23</td>\n      <td>42</td>\n    </tr>\n    <tr>\n      <th>59</th>\n      <td>Switzerland</td>\n      <td>10</td>\n      <td>23</td>\n      <td>33</td>\n    </tr>\n    <tr>\n      <th>60</th>\n      <td>Togo</td>\n      <td>6</td>\n      <td>4</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>61</th>\n      <td>Tunisia</td>\n      <td>10</td>\n      <td>20</td>\n      <td>30</td>\n    </tr>\n    <tr>\n      <th>62</th>\n      <td>Turkey</td>\n      <td>3</td>\n      <td>16</td>\n      <td>19</td>\n    </tr>\n    <tr>\n      <th>63</th>\n      <td>USA</td>\n      <td>19</td>\n      <td>34</td>\n      <td>53</td>\n    </tr>\n    <tr>\n      <th>64</th>\n      <td>Ukraine</td>\n      <td>4</td>\n      <td>8</td>\n      <td>12</td>\n    </tr>\n    <tr>\n      <th>65</th>\n      <td>Uruguay</td>\n      <td>23</td>\n      <td>41</td>\n      <td>64</td>\n    </tr>\n    <tr>\n      <th>66</th>\n      <td>Yugoslavia</td>\n      <td>10</td>\n      <td>18</td>\n      <td>28</td>\n    </tr>\n    <tr>\n      <th>67</th>\n      <td>rn\"&gt;Bosnia and Herzegovina</td>\n      <td>1</td>\n      <td>2</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>68</th>\n      <td>rn\"&gt;Republic of Ireland</td>\n      <td>9</td>\n      <td>7</td>\n      <td>16</td>\n    </tr>\n    <tr>\n      <th>69</th>\n      <td>rn\"&gt;Serbia and Montenegro</td>\n      <td>4</td>\n      <td>8</td>\n      <td>12</td>\n    </tr>\n    <tr>\n      <th>70</th>\n      <td>rn\"&gt;Trinidad and Tobago</td>\n      <td>3</td>\n      <td>7</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>71</th>\n      <td>rn\"&gt;United Arab Emirates</td>\n      <td>3</td>\n      <td>4</td>\n      <td>7</td>\n    </tr>\n  </tbody>\n</table>\n<p>72 rows \u00d7 4 columns</p>\n</div>\n\n\n\nNow we need the amount of matches per team to finally compute the average amount of yellow cards per match per team.\n\n\n```python\ndf_home_matches = df_matches[[\"Home Team Name\"]]\ndf_home_matches[\"MatchesCount1\"] = 1\ndf_home_matches = df_home_matches.groupby(\"Home Team Name\").count().reset_index()\ndf_home_matches.columns = ['Team', 'MatchesHome']\n\ndf_away_matches = df_matches[[\"Away Team Name\"]]\ndf_away_matches[\"MatchesCount2\"] = 1\ndf_away_matches = df_away_matches.groupby(\"Away Team Name\").count().reset_index()\ndf_away_matches.columns = ['Team', 'MatchesAway']\n\ndf_matches_count = pd.merge(df_home_matches, df_away_matches).fillna(0)\ndf_matches_count['MatchesTotal'] = df_matches_count.MatchesHome+df_matches_count.MatchesAway\n\ndf_yellow_cards_teams = pd.merge(df_yellow_cards_count, df_matches_count)\ndf_yellow_cards_teams['AvgYellowPerMatch'] = df_yellow_cards_teams.YellowCardsTotal/df_yellow_cards_teams.MatchesTotal\n#just to get team as index\ndf_yellow_cards_teams = df_yellow_cards_teams.groupby(\"Team\").mean()\ndf_yellow_cards_teams\n```\n\n    C:\\ProgramData\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:2: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n      \n    C:\\ProgramData\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:7: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame.\n    Try using .loc[row_indexer,col_indexer] = value instead\n    \n    See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n      import sys\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>YellowCardsHome</th>\n      <th>YellowCardsAway</th>\n      <th>YellowCardsTotal</th>\n      <th>MatchesHome</th>\n      <th>MatchesAway</th>\n      <th>MatchesTotal</th>\n      <th>AvgYellowPerMatch</th>\n    </tr>\n    <tr>\n      <th>Team</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Algeria</th>\n      <td>9</td>\n      <td>10</td>\n      <td>19</td>\n      <td>6</td>\n      <td>7</td>\n      <td>13</td>\n      <td>1.461538</td>\n    </tr>\n    <tr>\n      <th>Angola</th>\n      <td>3</td>\n      <td>8</td>\n      <td>11</td>\n      <td>1</td>\n      <td>2</td>\n      <td>3</td>\n      <td>3.666667</td>\n    </tr>\n    <tr>\n      <th>Argentina</th>\n      <td>70</td>\n      <td>50</td>\n      <td>120</td>\n      <td>52</td>\n      <td>25</td>\n      <td>77</td>\n      <td>1.558442</td>\n    </tr>\n    <tr>\n      <th>Australia</th>\n      <td>12</td>\n      <td>14</td>\n      <td>26</td>\n      <td>6</td>\n      <td>7</td>\n      <td>13</td>\n      <td>2.000000</td>\n    </tr>\n    <tr>\n      <th>Austria</th>\n      <td>12</td>\n      <td>11</td>\n      <td>23</td>\n      <td>13</td>\n      <td>16</td>\n      <td>29</td>\n      <td>0.793103</td>\n    </tr>\n    <tr>\n      <th>Belgium</th>\n      <td>18</td>\n      <td>23</td>\n      <td>41</td>\n      <td>17</td>\n      <td>24</td>\n      <td>41</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Brazil</th>\n      <td>86</td>\n      <td>23</td>\n      <td>109</td>\n      <td>78</td>\n      <td>26</td>\n      <td>104</td>\n      <td>1.048077</td>\n    </tr>\n    <tr>\n      <th>Bulgaria</th>\n      <td>13</td>\n      <td>26</td>\n      <td>39</td>\n      <td>7</td>\n      <td>19</td>\n      <td>26</td>\n      <td>1.500000</td>\n    </tr>\n    <tr>\n      <th>Cameroon</th>\n      <td>26</td>\n      <td>22</td>\n      <td>48</td>\n      <td>11</td>\n      <td>12</td>\n      <td>23</td>\n      <td>2.086957</td>\n    </tr>\n    <tr>\n      <th>Chile</th>\n      <td>22</td>\n      <td>26</td>\n      <td>48</td>\n      <td>14</td>\n      <td>19</td>\n      <td>33</td>\n      <td>1.454545</td>\n    </tr>\n    <tr>\n      <th>China PR</th>\n      <td>3</td>\n      <td>2</td>\n      <td>5</td>\n      <td>1</td>\n      <td>2</td>\n      <td>3</td>\n      <td>1.666667</td>\n    </tr>\n    <tr>\n      <th>Colombia</th>\n      <td>10</td>\n      <td>15</td>\n      <td>25</td>\n      <td>6</td>\n      <td>12</td>\n      <td>18</td>\n      <td>1.388889</td>\n    </tr>\n    <tr>\n      <th>Costa Rica</th>\n      <td>20</td>\n      <td>22</td>\n      <td>42</td>\n      <td>6</td>\n      <td>9</td>\n      <td>15</td>\n      <td>2.800000</td>\n    </tr>\n    <tr>\n      <th>Croatia</th>\n      <td>7</td>\n      <td>30</td>\n      <td>37</td>\n      <td>3</td>\n      <td>13</td>\n      <td>16</td>\n      <td>2.312500</td>\n    </tr>\n    <tr>\n      <th>Czech Republic</th>\n      <td>3</td>\n      <td>4</td>\n      <td>7</td>\n      <td>2</td>\n      <td>1</td>\n      <td>3</td>\n      <td>2.333333</td>\n    </tr>\n    <tr>\n      <th>Czechoslovakia</th>\n      <td>3</td>\n      <td>15</td>\n      <td>18</td>\n      <td>10</td>\n      <td>20</td>\n      <td>30</td>\n      <td>0.600000</td>\n    </tr>\n    <tr>\n      <th>C\ufffdte d'Ivoire</th>\n      <td>8</td>\n      <td>13</td>\n      <td>21</td>\n      <td>3</td>\n      <td>6</td>\n      <td>9</td>\n      <td>2.333333</td>\n    </tr>\n    <tr>\n      <th>Denmark</th>\n      <td>13</td>\n      <td>18</td>\n      <td>31</td>\n      <td>7</td>\n      <td>9</td>\n      <td>16</td>\n      <td>1.937500</td>\n    </tr>\n    <tr>\n      <th>Ecuador</th>\n      <td>6</td>\n      <td>17</td>\n      <td>23</td>\n      <td>4</td>\n      <td>6</td>\n      <td>10</td>\n      <td>2.300000</td>\n    </tr>\n    <tr>\n      <th>England</th>\n      <td>30</td>\n      <td>21</td>\n      <td>51</td>\n      <td>35</td>\n      <td>27</td>\n      <td>62</td>\n      <td>0.822581</td>\n    </tr>\n    <tr>\n      <th>France</th>\n      <td>28</td>\n      <td>31</td>\n      <td>59</td>\n      <td>29</td>\n      <td>30</td>\n      <td>59</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>German DR</th>\n      <td>6</td>\n      <td>4</td>\n      <td>10</td>\n      <td>3</td>\n      <td>3</td>\n      <td>6</td>\n      <td>1.666667</td>\n    </tr>\n    <tr>\n      <th>Germany</th>\n      <td>55</td>\n      <td>24</td>\n      <td>79</td>\n      <td>32</td>\n      <td>12</td>\n      <td>44</td>\n      <td>1.795455</td>\n    </tr>\n    <tr>\n      <th>Germany FR</th>\n      <td>26</td>\n      <td>14</td>\n      <td>40</td>\n      <td>43</td>\n      <td>19</td>\n      <td>62</td>\n      <td>0.645161</td>\n    </tr>\n    <tr>\n      <th>Ghana</th>\n      <td>10</td>\n      <td>25</td>\n      <td>35</td>\n      <td>4</td>\n      <td>8</td>\n      <td>12</td>\n      <td>2.916667</td>\n    </tr>\n    <tr>\n      <th>Greece</th>\n      <td>6</td>\n      <td>17</td>\n      <td>23</td>\n      <td>4</td>\n      <td>6</td>\n      <td>10</td>\n      <td>2.300000</td>\n    </tr>\n    <tr>\n      <th>Haiti</th>\n      <td>1</td>\n      <td>2</td>\n      <td>3</td>\n      <td>1</td>\n      <td>2</td>\n      <td>3</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Honduras</th>\n      <td>5</td>\n      <td>10</td>\n      <td>15</td>\n      <td>5</td>\n      <td>4</td>\n      <td>9</td>\n      <td>1.666667</td>\n    </tr>\n    <tr>\n      <th>Hungary</th>\n      <td>2</td>\n      <td>4</td>\n      <td>6</td>\n      <td>18</td>\n      <td>14</td>\n      <td>32</td>\n      <td>0.187500</td>\n    </tr>\n    <tr>\n      <th>IR Iran</th>\n      <td>1</td>\n      <td>9</td>\n      <td>10</td>\n      <td>1</td>\n      <td>5</td>\n      <td>6</td>\n      <td>1.666667</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>Norway</th>\n      <td>2</td>\n      <td>11</td>\n      <td>13</td>\n      <td>1</td>\n      <td>7</td>\n      <td>8</td>\n      <td>1.625000</td>\n    </tr>\n    <tr>\n      <th>Paraguay</th>\n      <td>16</td>\n      <td>25</td>\n      <td>41</td>\n      <td>11</td>\n      <td>16</td>\n      <td>27</td>\n      <td>1.518519</td>\n    </tr>\n    <tr>\n      <th>Peru</th>\n      <td>1</td>\n      <td>8</td>\n      <td>9</td>\n      <td>5</td>\n      <td>10</td>\n      <td>15</td>\n      <td>0.600000</td>\n    </tr>\n    <tr>\n      <th>Poland</th>\n      <td>20</td>\n      <td>22</td>\n      <td>42</td>\n      <td>16</td>\n      <td>15</td>\n      <td>31</td>\n      <td>1.354839</td>\n    </tr>\n    <tr>\n      <th>Portugal</th>\n      <td>34</td>\n      <td>12</td>\n      <td>46</td>\n      <td>16</td>\n      <td>10</td>\n      <td>26</td>\n      <td>1.769231</td>\n    </tr>\n    <tr>\n      <th>Romania</th>\n      <td>20</td>\n      <td>12</td>\n      <td>32</td>\n      <td>9</td>\n      <td>12</td>\n      <td>21</td>\n      <td>1.523810</td>\n    </tr>\n    <tr>\n      <th>Russia</th>\n      <td>6</td>\n      <td>16</td>\n      <td>22</td>\n      <td>3</td>\n      <td>6</td>\n      <td>9</td>\n      <td>2.444444</td>\n    </tr>\n    <tr>\n      <th>Saudi Arabia</th>\n      <td>12</td>\n      <td>10</td>\n      <td>22</td>\n      <td>6</td>\n      <td>7</td>\n      <td>13</td>\n      <td>1.692308</td>\n    </tr>\n    <tr>\n      <th>Scotland</th>\n      <td>8</td>\n      <td>9</td>\n      <td>17</td>\n      <td>9</td>\n      <td>14</td>\n      <td>23</td>\n      <td>0.739130</td>\n    </tr>\n    <tr>\n      <th>Senegal</th>\n      <td>9</td>\n      <td>5</td>\n      <td>14</td>\n      <td>2</td>\n      <td>3</td>\n      <td>5</td>\n      <td>2.800000</td>\n    </tr>\n    <tr>\n      <th>Serbia</th>\n      <td>4</td>\n      <td>6</td>\n      <td>10</td>\n      <td>1</td>\n      <td>2</td>\n      <td>3</td>\n      <td>3.333333</td>\n    </tr>\n    <tr>\n      <th>Slovakia</th>\n      <td>7</td>\n      <td>4</td>\n      <td>11</td>\n      <td>2</td>\n      <td>2</td>\n      <td>4</td>\n      <td>2.750000</td>\n    </tr>\n    <tr>\n      <th>Slovenia</th>\n      <td>11</td>\n      <td>8</td>\n      <td>19</td>\n      <td>3</td>\n      <td>3</td>\n      <td>6</td>\n      <td>3.166667</td>\n    </tr>\n    <tr>\n      <th>South Africa</th>\n      <td>16</td>\n      <td>5</td>\n      <td>21</td>\n      <td>6</td>\n      <td>3</td>\n      <td>9</td>\n      <td>2.333333</td>\n    </tr>\n    <tr>\n      <th>Soviet Union</th>\n      <td>4</td>\n      <td>14</td>\n      <td>18</td>\n      <td>18</td>\n      <td>13</td>\n      <td>31</td>\n      <td>0.580645</td>\n    </tr>\n    <tr>\n      <th>Spain</th>\n      <td>33</td>\n      <td>31</td>\n      <td>64</td>\n      <td>30</td>\n      <td>29</td>\n      <td>59</td>\n      <td>1.084746</td>\n    </tr>\n    <tr>\n      <th>Sweden</th>\n      <td>19</td>\n      <td>23</td>\n      <td>42</td>\n      <td>27</td>\n      <td>19</td>\n      <td>46</td>\n      <td>0.913043</td>\n    </tr>\n    <tr>\n      <th>Switzerland</th>\n      <td>10</td>\n      <td>23</td>\n      <td>33</td>\n      <td>12</td>\n      <td>21</td>\n      <td>33</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>Togo</th>\n      <td>6</td>\n      <td>4</td>\n      <td>10</td>\n      <td>2</td>\n      <td>1</td>\n      <td>3</td>\n      <td>3.333333</td>\n    </tr>\n    <tr>\n      <th>Tunisia</th>\n      <td>10</td>\n      <td>20</td>\n      <td>30</td>\n      <td>4</td>\n      <td>8</td>\n      <td>12</td>\n      <td>2.500000</td>\n    </tr>\n    <tr>\n      <th>Turkey</th>\n      <td>3</td>\n      <td>16</td>\n      <td>19</td>\n      <td>2</td>\n      <td>8</td>\n      <td>10</td>\n      <td>1.900000</td>\n    </tr>\n    <tr>\n      <th>USA</th>\n      <td>19</td>\n      <td>34</td>\n      <td>53</td>\n      <td>15</td>\n      <td>18</td>\n      <td>33</td>\n      <td>1.606061</td>\n    </tr>\n    <tr>\n      <th>Ukraine</th>\n      <td>4</td>\n      <td>8</td>\n      <td>12</td>\n      <td>1</td>\n      <td>4</td>\n      <td>5</td>\n      <td>2.400000</td>\n    </tr>\n    <tr>\n      <th>Uruguay</th>\n      <td>23</td>\n      <td>41</td>\n      <td>64</td>\n      <td>28</td>\n      <td>23</td>\n      <td>51</td>\n      <td>1.254902</td>\n    </tr>\n    <tr>\n      <th>Yugoslavia</th>\n      <td>10</td>\n      <td>18</td>\n      <td>28</td>\n      <td>17</td>\n      <td>20</td>\n      <td>37</td>\n      <td>0.756757</td>\n    </tr>\n    <tr>\n      <th>rn\"&gt;Bosnia and Herzegovina</th>\n      <td>1</td>\n      <td>2</td>\n      <td>3</td>\n      <td>1</td>\n      <td>2</td>\n      <td>3</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>rn\"&gt;Republic of Ireland</th>\n      <td>9</td>\n      <td>7</td>\n      <td>16</td>\n      <td>5</td>\n      <td>8</td>\n      <td>13</td>\n      <td>1.230769</td>\n    </tr>\n    <tr>\n      <th>rn\"&gt;Serbia and Montenegro</th>\n      <td>4</td>\n      <td>8</td>\n      <td>12</td>\n      <td>1</td>\n      <td>2</td>\n      <td>3</td>\n      <td>4.000000</td>\n    </tr>\n    <tr>\n      <th>rn\"&gt;Trinidad and Tobago</th>\n      <td>3</td>\n      <td>7</td>\n      <td>10</td>\n      <td>1</td>\n      <td>2</td>\n      <td>3</td>\n      <td>3.333333</td>\n    </tr>\n    <tr>\n      <th>rn\"&gt;United Arab Emirates</th>\n      <td>3</td>\n      <td>4</td>\n      <td>7</td>\n      <td>1</td>\n      <td>2</td>\n      <td>3</td>\n      <td>2.333333</td>\n    </tr>\n  </tbody>\n</table>\n<p>72 rows \u00d7 7 columns</p>\n</div>\n\n\n\nWe see that some teams with only very few matches appear in both lists. These could be statistical outliers.\n\n\n```python\nplt.figure(figsize=(12,6))\n\nax = plt.subplot(121)\ndf_yellow_cards_teams[\"AvgYellowPerMatch\"].sort_values(ascending=False).nlargest(n=10).plot.bar()\nplt.title(\"Teams with most yellow cards\")\n\nax = plt.subplot(122)\ndf_yellow_cards_teams[\"AvgYellowPerMatch\"].sort_values(ascending=True).nsmallest(n=10).plot.bar()\nplt.title(\"Fairest Teams\")\n\nplt.show()\n```\n\nBased on the previous observation we restrict ourselves to teams with at least 30 matches which are in total 21 teams. Germany is on rank 3.\n\n\n```python\ndf_yellow_cards_reg_teams = df_yellow_cards_teams[df_yellow_cards_teams.MatchesTotal > 30]\nprint(len(df_yellow_cards_reg_teams))\n\nplt.figure(figsize=(12,6))\n\ndf_yellow_cards_reg_teams[\"AvgYellowPerMatch\"].sort_values(ascending=False).plot.bar()\nplt.title(\"Teams with most yellow cards\")\n\nplt.show()\n```\n\n## Winners play fair!?\n\nWhether or not a game is a tie does not have an effect on the amount of red or yellow cards. However, if it is not a tie the winner are given less yellow and red cards.\n\n\n```python\navg_yellow_of_winner = len(df_events.loc[(df_events['EventOfWinner'] == True) & (df_events['EventType'] == 'Y')])/num_matches_decision\navg_yellow_of_loser = len(df_events.loc[(df_events['EventOfLoser'] == True) & (df_events['EventType'] == 'Y')])/num_matches_decision\n\navg_red_of_winner = len(df_events.loc[(df_events['EventOfWinner'] == True) & ((df_events['EventType'] == 'R') | (df_events['EventType'] == 'RSY'))])/num_matches_decision\navg_red_of_loser = len(df_events.loc[(df_events['EventOfLoser'] == True) & ((df_events['EventType'] == 'R') | (df_events['EventType'] == 'RSY'))])/num_matches_decision\n\navg_yellow_decided_match = avg_yellow_of_winner+avg_yellow_of_loser\navg_red_decided_match = avg_red_of_winner+avg_red_of_loser\n\navg_yellow_tie_match = len(df_events.loc[(df_events['HomeTeamWins'] == False) & (df_events['AwayTeamWins'] == False) & (df_events['EventType'] == 'Y')])/num_matches_tie\navg_red_tie_match = len(df_events.loc[(df_events['HomeTeamWins'] == False) & (df_events['AwayTeamWins'] == False) & ((df_events['EventType'] == 'R') | (df_events['EventType'] == 'RSY'))])/num_matches_tie\n\nprint(\"avg_yellow_of_winner: %.2f\"% (avg_yellow_of_winner))\nprint(\"avg_yellow_of_loser: %.2f\"% (avg_yellow_of_loser))\nprint(\"avg_yellow_decided_match: %.2f\"% (avg_yellow_decided_match))\nprint(\"avg_yellow_tie_match: %.2f\"% (avg_yellow_tie_match))\n\nprint(\"avg_red_of_winner: %.2f\"% (avg_red_of_winner))\nprint(\"avg_red_of_loser: %.2f\"% (avg_red_of_loser))\nprint(\"avg_red_decided_match: %.2f\"% (avg_red_decided_match))\nprint(\"avg_red_tie_match: %.2f\"% (avg_red_tie_match))\n\nplt.figure(figsize=(12,6))\n\nind = np.arange(2)\nwidth = 0.35\ndist = 0.2\n\nax = plt.subplot(121)\n\nyellow_cards = (avg_yellow_of_winner, avg_yellow_of_loser)\nred_cards = (avg_red_of_winner, avg_red_of_loser)\nplt.xticks(ind, ('Winner', 'Loser'))\nax.bar(ind, yellow_cards, width, color='y')\nax.bar(ind + width, red_cards, width, color='r')\n\nax = plt.subplot(122)\n\nyellow_cards = (avg_yellow_decided_match, avg_yellow_tie_match)\nred_cards = (avg_red_decided_match, avg_red_tie_match)\nplt.xticks(ind, ('Decided', 'Tie'))\nax.bar(ind, yellow_cards, width, color='y')\nax.bar(ind + width, red_cards, width, color='r')\n\nplt.show()\n```\n\n# Predict Yellow Cards\nIn this section we trained a model to predict the amount of yellow cards given in a match.\n\n## Initial Features for Regression\n- Hour game starts, just added for fun. We do not expect a correlation. \n- The year the match took place\n- The stage (group phase, quarter-finals etc.) We chose to perform a one hot encoding.\n- The total amount of goals\n- The goal difference\n- The goal difference in the half time\n- The change of these differences in the second part of the match\n- Whether there was extra time\n- Whether penalty decided the match\n- The amount of substitutions\n- The amount of substitutions at half time\n     \n## Explanation of Event Types\nThe codes for the event types are: G=Goal, OG=Own Goal, Y=Yellow Card, R=Red Card, SY = Red Card by second yellow, P=Penalty, MP=Missed Penalty, I = Substitution In, O=Substitute Out, IH= In half time?\n\n\nFirst, we need some data preparation. Specifically, we build the columns:\n- One Hot Encoding for the EventType column (needed for groupby later on)\n- One Hot Encoding for the StageRank column (for the actual regression)\n- total goals scored\n- goal difference half time\n- goal difference end\n- delta of the last two values\n\nAdditionally, attendance must be a numeric data type\n\n\n\n```python\ndf_events_ohe = pd.concat([df_events, pd.get_dummies(df_events['EventType'])], axis=1)\ndf_events_ohe = pd.concat([df_events_ohe, pd.get_dummies(df_events['StageRank'], prefix=\"Stage\")], axis=1)\n\ndf_events_ohe = df_events_ohe.assign(GoalsTotal = lambda x : x['Home Team Goals']+x['Away Team Goals'])\ndf_events_ohe = df_events_ohe.assign(GoalDifference = lambda x : abs(x['Home Team Goals']-x['Away Team Goals']))\ndf_events_ohe = df_events_ohe.assign(GoalDifferenceHalfTime = lambda x : abs(x['Half-time Home Goals']-x['Half-time Away Goals']))\ndf_events_ohe = df_events_ohe.assign(DeltaGoals = lambda x : x['GoalDifference']-x['GoalDifferenceHalfTime'])\ndf_events_ohe[['Attendance']] = df_events_ohe[['Attendance']].apply(pd.to_numeric)\ndf_events_ohe\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Year</th>\n      <th>Datetime</th>\n      <th>Stage</th>\n      <th>Stadium</th>\n      <th>City</th>\n      <th>Home Team Name</th>\n      <th>Home Team Goals</th>\n      <th>Away Team Goals</th>\n      <th>Away Team Name</th>\n      <th>Attendance</th>\n      <th>...</th>\n      <th>Stage_1</th>\n      <th>Stage_2</th>\n      <th>Stage_3</th>\n      <th>Stage_4</th>\n      <th>Stage_5</th>\n      <th>Stage_6</th>\n      <th>GoalsTotal</th>\n      <th>GoalDifference</th>\n      <th>GoalDifferenceHalfTime</th>\n      <th>DeltaGoals</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>1930</td>\n      <td>13 Jul 1930 - 15:00</td>\n      <td>Group 1</td>\n      <td>Pocitos</td>\n      <td>Montevideo</td>\n      <td>France</td>\n      <td>4</td>\n      <td>1</td>\n      <td>Mexico</td>\n      <td>4444.0</td>\n      <td>...</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>39389</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39390</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39391</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39392</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39393</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39394</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39395</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39396</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39397</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39398</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39399</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39400</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39401</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39402</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39403</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39404</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39405</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39406</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39407</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39408</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39409</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39410</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39411</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39412</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39413</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39414</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39415</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39416</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39417</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>39418</th>\n      <td>2014</td>\n      <td>01 Jul 2014 - 17:00</td>\n      <td>Round of 16</td>\n      <td>Arena Fonte Nova</td>\n      <td>Salvador</td>\n      <td>Belgium</td>\n      <td>2</td>\n      <td>1</td>\n      <td>USA</td>\n      <td>51227.0</td>\n      <td>...</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n<p>39419 rows \u00d7 62 columns</p>\n</div>\n\n\n\nPerform a group by to get sum of yellow cards\n\n\n```python\nf = {'HourGameStart':['mean'],\n     #'Home Team Goals':['mean'], # not symmetric -> throw out\n     #'Away Team Goals':['mean'],\n     #'Half-time Home Goals':['mean'],\n     #'Half-time Away Goals':['mean'],\n     'Year':['mean'],\n     'Stage_1':['mean'],\n     'Stage_2':['mean'],\n     'Stage_3':['mean'],\n     'Stage_4':['mean'],\n     'Stage_5':['mean'],\n     'Stage_6':['mean'],\n     'GoalsTotal':['mean'],\n     'GoalDifference':['mean'],\n     'GoalDifferenceHalfTime':['mean'],\n     'DeltaGoals':['mean'],\n     'ExtraTime':['mean'],\n     'Penalty':['mean'],\n     'I':['sum'], #substitutions\n     'IH':['sum'], #substitutions half time\n     'Y':['sum'],\n    }\n\ndf_events_grp = df_events_ohe.groupby(['MatchID']).agg(f)\ndf_events_grp.columns = df_events_grp.columns.get_level_values(0)\ndf_events_grp\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>HourGameStart</th>\n      <th>Year</th>\n      <th>Stage_1</th>\n      <th>Stage_2</th>\n      <th>Stage_3</th>\n      <th>Stage_4</th>\n      <th>Stage_5</th>\n      <th>Stage_6</th>\n      <th>GoalsTotal</th>\n      <th>GoalDifference</th>\n      <th>GoalDifferenceHalfTime</th>\n      <th>DeltaGoals</th>\n      <th>ExtraTime</th>\n      <th>Penalty</th>\n      <th>I</th>\n      <th>IH</th>\n      <th>Y</th>\n    </tr>\n    <tr>\n      <th>MatchID</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>25</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3</td>\n      <td>0</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>18</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3</td>\n      <td>1</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>20</td>\n      <td>1990</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>2</td>\n      <td>1</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>20</td>\n      <td>1990</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>True</td>\n      <td>3</td>\n      <td>1</td>\n      <td>7</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>4</td>\n      <td>0</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>30</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>2</td>\n      <td>1</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>4</td>\n      <td>0</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>31</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>True</td>\n      <td>3</td>\n      <td>0</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>42</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>43</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>2</td>\n      <td>2</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>48</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3</td>\n      <td>1</td>\n      <td>9</td>\n    </tr>\n    <tr>\n      <th>55</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>True</td>\n      <td>False</td>\n      <td>4</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>56</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>4</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>57</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>2</td>\n      <td>0</td>\n      <td>2</td>\n      <td>False</td>\n      <td>False</td>\n      <td>1</td>\n      <td>2</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>66</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>4</td>\n      <td>2</td>\n      <td>2</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>2</td>\n      <td>2</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>73</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>4</td>\n      <td>0</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>74</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3</td>\n      <td>0</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>75</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>2</td>\n      <td>1</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>102</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>True</td>\n      <td>False</td>\n      <td>4</td>\n      <td>0</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>103</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>True</td>\n      <td>False</td>\n      <td>3</td>\n      <td>1</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>108</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>4</td>\n      <td>0</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>111</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>4</td>\n      <td>4</td>\n      <td>2</td>\n      <td>2</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3</td>\n      <td>1</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>114</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>2</td>\n      <td>0</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>119</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>2</td>\n      <td>0</td>\n      <td>2</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3</td>\n      <td>0</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>120</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>127</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>2</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>128</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>4</td>\n      <td>0</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>129</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>1</td>\n      <td>2</td>\n      <td>False</td>\n      <td>False</td>\n      <td>1</td>\n      <td>1</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>150</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>4</td>\n      <td>0</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>151</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3</td>\n      <td>1</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>152</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>4</td>\n      <td>0</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>300186486</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>6</td>\n      <td>0</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>300186487</th>\n      <td>13</td>\n      <td>2014</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>True</td>\n      <td>12</td>\n      <td>0</td>\n      <td>14</td>\n    </tr>\n    <tr>\n      <th>300186488</th>\n      <td>17</td>\n      <td>2014</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>True</td>\n      <td>12</td>\n      <td>0</td>\n      <td>12</td>\n    </tr>\n    <tr>\n      <th>300186489</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>4</td>\n      <td>2</td>\n      <td>1</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>6</td>\n      <td>0</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>300186490</th>\n      <td>17</td>\n      <td>2014</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>True</td>\n      <td>10</td>\n      <td>2</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>300186491</th>\n      <td>17</td>\n      <td>2014</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>2</td>\n      <td>1</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>12</td>\n      <td>0</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>300186492</th>\n      <td>13</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>4</td>\n      <td>1</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>300186493</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>4</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>5</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>300186494</th>\n      <td>13</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3</td>\n      <td>1</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>300186495</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>6</td>\n      <td>2</td>\n      <td>3</td>\n      <td>-1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>6</td>\n      <td>0</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>300186496</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>3</td>\n      <td>1</td>\n      <td>2</td>\n      <td>False</td>\n      <td>False</td>\n      <td>4</td>\n      <td>2</td>\n      <td>7</td>\n    </tr>\n    <tr>\n      <th>300186497</th>\n      <td>17</td>\n      <td>2014</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>True</td>\n      <td>False</td>\n      <td>12</td>\n      <td>0</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>300186498</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>2</td>\n      <td>2</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>5</td>\n      <td>1</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>300186499</th>\n      <td>18</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>6</td>\n      <td>0</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>300186500</th>\n      <td>13</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>5</td>\n      <td>1</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>300186501</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>True</td>\n      <td>False</td>\n      <td>10</td>\n      <td>2</td>\n      <td>8</td>\n    </tr>\n    <tr>\n      <th>300186502</th>\n      <td>17</td>\n      <td>2014</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>3</td>\n      <td>2</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>10</td>\n      <td>2</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>300186503</th>\n      <td>13</td>\n      <td>2014</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>True</td>\n      <td>False</td>\n      <td>12</td>\n      <td>0</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>300186504</th>\n      <td>13</td>\n      <td>2014</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>12</td>\n      <td>0</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>300186505</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>5</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>300186506</th>\n      <td>17</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>1</td>\n      <td>-1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>5</td>\n      <td>1</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>300186507</th>\n      <td>22</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>6</td>\n      <td>0</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>300186508</th>\n      <td>13</td>\n      <td>2014</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>10</td>\n      <td>2</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>300186509</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>5</td>\n      <td>1</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>300186510</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>6</td>\n      <td>4</td>\n      <td>0</td>\n      <td>4</td>\n      <td>False</td>\n      <td>False</td>\n      <td>6</td>\n      <td>0</td>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>300186511</th>\n      <td>18</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>5</td>\n      <td>0</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>300186512</th>\n      <td>19</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>5</td>\n      <td>1</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>300186513</th>\n      <td>18</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>6</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>300186514</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>7</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>5</td>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>300186515</th>\n      <td>17</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>6</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n<p>836 rows \u00d7 17 columns</p>\n</div>\n\n\n\n\n```python\ndf_events_grp.columns\n```\n\n\n\n\n    Index(['HourGameStart', 'Year', 'Stage_1', 'Stage_2', 'Stage_3', 'Stage_4',\n           'Stage_5', 'Stage_6', 'GoalsTotal', 'GoalDifference',\n           'GoalDifferenceHalfTime', 'DeltaGoals', 'ExtraTime', 'Penalty', 'I',\n           'IH', 'Y'],\n          dtype='object')\n\n\n\nWe simply use MinMaxScaler as preprocessing\n\n\n```python\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler()\ndf_events_grp[['HourGameStart','Year','GoalsTotal','GoalDifference','GoalDifferenceHalfTime','DeltaGoals']] = scaler.fit_transform(df_events_grp[['HourGameStart','Year','GoalsTotal','GoalDifference','GoalDifferenceHalfTime','DeltaGoals']])\n```\n\nLinear regression is used to predict the amount of yellow cards for the test data. The MSE is fairly lower than the one of the baseline model. The coefficient of determination (R squared, amount of explained variance) is 0.5 indicating a moderate model performance. Keep in mind that R squared values depend on the amount of features used (strictly increasing on number of features).\n\nFrom Wiki (R squared is the amount of variance explained by the model)\n\\begin{align}\n\\mathit{R}^2 = \\frac{\\text{ESS}}{\\text{TSS}}=\n\\frac{\\displaystyle\\sum\\nolimits \\left(\\hat{y}_i- \\overline{y}\\right)^2}{\\displaystyle\\sum\\nolimits \\left(y_i - \\overline{y}\\right)^2}\n\\end{align}\n\n\n```python\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import datasets, linear_model\nfrom sklearn.metrics import mean_squared_error, r2_score\n\n# train test split\n# linear regression to predict y \nX = df_events_grp.loc[:, 'HourGameStart':'IH']\n#X = pd.concat([df_fouls.loc[:, 'StageRank':'IH'], df_fouls.loc[:, 'ALG':'ZAI']], axis=1)\nY = df_events_grp.loc[:, 'Y']\n\n# transform to numpy array\nX = X.as_matrix().astype(np.float)\nY = Y.as_matrix().astype(np.float)\n\n# train/ test split\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, random_state=40)\n\n# fit regression model\nregr = linear_model.LinearRegression()\nregr.fit(X_train, y_train)\n\n# compare RMSE and R value with base model\ny_pred = regr.predict(X_test)\n\n# base model would be the average y value\n# needed for comparison\ny_base_pred = np.zeros((len(y_pred)))\ny_base_pred[:,] = y_train.mean()\n\nprint(\"LINEAR REGRESSION: Mean squared error: %.2f\"\n      % mean_squared_error(y_test, y_pred))\nprint('LINEAR REGRESSION: Variance score: %.2f' % r2_score(y_test, y_pred))\n\nprint(\"BASE: Mean squared error: %.2f\"\n      % mean_squared_error(y_test, y_base_pred))\n# zero for sure, just added for completeness\nprint('BASE: Variance score: %.2f' % r2_score(y_test, y_base_pred))\n```\n\n    LINEAR REGRESSION: Mean squared error: 3.06\n    LINEAR REGRESSION: Variance score: 0.50\n    BASE: Mean squared error: 6.11\n    BASE: Variance score: -0.00\n\n\nTo statistically analyze the model we also compute several statistics. The most important ones are\n\n- T values: statistic for t test checking whether coefficient is zero\n- p values: probability that coefficient is zero\n- F statistic: is the group of features significant?\n\nWe can derive that only x2, x15, x16 are significant, i.e. Year, I (=Amount of substitutions) and IH (=Amount of half time substitutions) by observing the p values. Alternatively, this can be concluded by interpreting the confidence intervals spanning over zero for all other variables.\n\nAll together F-statistic prob is low enough. Hence, all variables together can be considered significant.\n\n\n```python\nimport statsmodels.api as sm\nfrom scipy import stats\n\nX2 = sm.add_constant(X_train)\nest = sm.OLS(y_train, X2)\nest2 = est.fit()\nprint(est2.summary())\n```\n\n    C:\\ProgramData\\Anaconda3\\lib\\site-packages\\statsmodels\\compat\\pandas.py:56: FutureWarning: The pandas.core.datetools module is deprecated and will be removed in a future version. Please use the pandas.tseries module instead.\n      from pandas.core import datetools\n\n\n                                OLS Regression Results                            \n    ==============================================================================\n    Dep. Variable:                      y   R-squared:                       0.461\n    Model:                            OLS   Adj. R-squared:                  0.447\n    Method:                 Least Squares   F-statistic:                     31.07\n    Date:                Wed, 01 Aug 2018   Prob (F-statistic):           2.13e-63\n    Time:                        09:15:23   Log-Likelihood:                -1162.0\n    No. Observations:                 560   AIC:                             2356.\n    Df Residuals:                     544   BIC:                             2425.\n    Df Model:                          15                                         \n    Covariance Type:            nonrobust                                         \n    ==============================================================================\n                     coef    std err          t      P>|t|      [0.025      0.975]\n    ------------------------------------------------------------------------------\n    const          0.0826      0.886      0.093      0.926      -1.658       1.824\n    x1             0.2728      0.349      0.781      0.435      -0.413       0.959\n    x2             3.5290      0.704      5.015      0.000       2.147       4.911\n    x3            -0.7543      0.915     -0.824      0.410      -2.553       1.044\n    x4             0.2847      0.948      0.300      0.764      -1.577       2.146\n    x5            -0.3711      0.950     -0.390      0.696      -2.238       1.496\n    x6            -0.8014      0.963     -0.833      0.405      -2.692       1.090\n    x7            -0.8052      1.665     -0.484      0.629      -4.076       2.466\n    x8             0.5436      1.061      0.512      0.609      -1.541       2.628\n    x9            -0.7947      0.701     -1.133      0.258      -2.172       0.583\n    x10           -0.3125      0.428     -0.730      0.465      -1.153       0.528\n    x11           -0.3916      0.571     -0.685      0.493      -1.514       0.731\n    x12           -0.0240      0.438     -0.055      0.956      -0.884       0.836\n    x13            0.3682      0.501      0.734      0.463      -0.617       1.353\n    x14            0.8808      0.683      1.289      0.198      -0.462       2.223\n    x15            0.2900      0.077      3.768      0.000       0.139       0.441\n    x16            0.4159      0.151      2.756      0.006       0.119       0.712\n    ==============================================================================\n    Omnibus:                      154.397   Durbin-Watson:                   1.967\n    Prob(Omnibus):                  0.000   Jarque-Bera (JB):              660.338\n    Skew:                           1.181   Prob(JB):                    4.07e-144\n    Kurtosis:                       7.766   Cond. No.                     1.35e+17\n    ==============================================================================\n    \n    Warnings:\n    [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n    [2] The smallest eigenvalue is 5.21e-31. This might indicate that there are\n    strong multicollinearity problems or that the design matrix is singular.\n\n\nTo confirm a correlation between yellow cards and year, penalty, substitutions and half time substitutions we compute the Pearson correlation coefficient. The p-value corresponds to the probability to observe the left correlation coefficient randomly. All correlations are significant.\n\nThe positive correlation with year suggests that nowadays more yellow cards are given. This might be due to stricter rules or less fair play.\n\nThe correlation with substitutions is not obvious. \n\n\n```python\nfrom scipy.stats.stats import pearsonr  \n\nprint(pearsonr(df_events_grp['Year'],Y)) # equivalent to: print(pearsonr(X[:,1],Y)) because not sensitive to scaling\nprint(pearsonr(df_events_grp['I'],Y)) # substitutions\nprint(pearsonr(df_events_grp['IH'],Y)) # half time substitutions\n```\n\n    (0.6280545772750047, 6.283851010000187e-93)\n    (0.6277592949664524, 8.115135889320015e-93)\n    (0.21070534342553665, 7.634463181895365e-10)\n\n\nThe correlation with year and substitutions can also be observed in a scatter plot. For penalty this does plot does not make sense as it is a binary decision. \n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nplt.figure()\nplt.plot(df_events_grp['Year'],Y, \"o\")\nplt.xlabel(\"Year (scaled)\")\nplt.ylabel(\"Yellow Cards\")\nplt.figure()\nplt.plot(df_events_grp['I'],Y, \"o\")\nplt.xlabel(\"Substitutions (scaled)\")\nplt.ylabel(\"Yellow Cards\")\n```\n\nWe try several ways to increase the performance\n\n1. introduce regularization to tune our linear model (usually we need cross validation to tune the introduced hyperparameter values. However as we could not improve model performance we did not perform that step)\n2. try a different ML model to increase accuracy\n3. introduce team as one hot encoding feature to increase performance\n\nBut first, why not remove the unnecessary features and make the model more robust?\n\n\n```python\nX2 = df_events_grp.loc[:, ['Year', 'Penalty', 'IH', 'I']]\nY2 = df_events_grp.loc[:, 'Y']\n\n# transform to numpy array\nX2 = X2.as_matrix().astype(np.float)\nY2 = Y2.as_matrix().astype(np.float)\n\n# train/ test split\nX_train2, X_test2, y_train2, y_test2 = train_test_split(X2, Y2, test_size=0.33, random_state=40)\n\n# fit regression model\nregr = linear_model.LinearRegression()\nregr.fit(X_train2, y_train2)\n\n# compare RMSE and R value with base model\ny_pred2 = regr.predict(X_test2)\n\n# base model would be the average y value\n# needed for comparison\ny_base_pred = np.zeros((len(y_pred)))\ny_base_pred[:,] = y_train.mean()\n\nprint(\"LINEAR REGRESSION: Mean squared error: %.2f\"\n      % mean_squared_error(y_test2, y_pred2))\nprint('LINEAR REGRESSION: Variance score: %.2f' % r2_score(y_test2, y_pred2))\n\nprint(\"BASE: Mean squared error: %.2f\"\n      % mean_squared_error(y_test2, y_base_pred))\n# zero for sure, just added for completeness\nprint('BASE: Variance score: %.2f' % r2_score(y_test2, y_base_pred))\n```\n\n    LINEAR REGRESSION: Mean squared error: 3.19\n    LINEAR REGRESSION: Variance score: 0.48\n    BASE: Mean squared error: 6.11\n    BASE: Variance score: -0.00\n\n\n## Attempt 1: Regularization\nAs mentioned above, regularization fails to improve the linear model. In this case we only tried ridge regression. One could also employ lasso regression etc. to regularize which have the effect of feature selection or lower variable scale respectively.\n\n\n```python\nfrom sklearn.linear_model import Ridge\n    \nclf = Ridge(alpha=2)\nclf.fit(X_train, y_train) \n\ny_pred = clf.predict(X_test)\n\nprint(\"REGULARIZATION: Mean squared error: %.2f\"\n      % mean_squared_error(y_test, y_pred))\nprint('REGULARIZATION: Variance score: %.2f' % r2_score(y_test, y_pred))\n```\n\n    REGULARIZATION: Mean squared error: 3.01\n    REGULARIZATION: Variance score: 0.51\n\n\n## Attempt 2a: Try a regression tree\nJust another regression model. Leafes of the tree contain values for the specific subspace.\n\n\n```python\nfrom sklearn.tree import DecisionTreeRegressor\n\n# fit regression model\nregr_1 = DecisionTreeRegressor(max_depth=2)\nregr_2 = DecisionTreeRegressor(max_depth=4)\nregr_1.fit(X_train, y_train)\nregr_2.fit(X_train, y_train)\n\n# compare RMSE and R value with base model\ny_pred = regr_1.predict(X_test)\ny_pred_2 = regr_2.predict(X_test)\n\n# base model would be the average y value\n# needed for comparison\ny_base_pred = np.zeros((len(y_pred)))\ny_base_pred[:,] = y_train.mean()\n\nprint(\"DECISION TREE 1: Mean squared error: %.2f\"\n      % mean_squared_error(y_test, y_pred))\nprint('DECISION TREE 1: Variance score: %.2f' % r2_score(y_test, y_pred))\n\nprint(\"DECISION TREE 2: Mean squared error: %.2f\"\n      % mean_squared_error(y_test, y_pred_2))\nprint('DECISION TREE 2: Variance score: %.2f' % r2_score(y_test, y_pred_2))\n```\n\n    DECISION TREE 1: Mean squared error: 3.63\n    DECISION TREE 1: Variance score: 0.41\n    DECISION TREE 2: Mean squared error: 3.30\n    DECISION TREE 2: Variance score: 0.46\n\n\n## Attempt 2b: Neural Network\n\nSounds fancy but actually just a vanilla multilayer perceptron with only two layers.\n\n\n```python\nfrom sklearn.neural_network import MLPRegressor\n\nnn = MLPRegressor(\n    hidden_layer_sizes=(1,),  activation='relu', solver='adam', alpha=0.001, batch_size='auto',\n    learning_rate='constant', learning_rate_init=0.01, power_t=0.5, max_iter=1000, shuffle=True,\n    random_state=9, tol=0.0001, verbose=False, warm_start=False, momentum=0.9, nesterovs_momentum=True,\n    early_stopping=False, validation_fraction=0.1, beta_1=0.9, beta_2=0.999, epsilon=1e-08)\n\nnn.fit(X_train, y_train)\n\ny_pred = nn.predict(X_test)\n\nprint(\"NEURAL NETWORK: Mean squared error: %.2f\"\n      % mean_squared_error(y_test, y_pred))\nprint('NEURAL NETWORK: Variance score: %.2f' % r2_score(y_test, y_pred))\n```\n\n    NEURAL NETWORK: Mean squared error: 3.71\n    NEURAL NETWORK: Variance score: 0.39\n\n\n## Attempt 3: Add team as one hot encoding\nWe hot encode the teams of the specific match and hope to increase the accuracy\n\n\n```python\ndf_teams_ohe = (pd.get_dummies(df_events['Home Team Initials'])+pd.get_dummies(df_events['Away Team Initials'])).fillna(value=0)\ndf_teams_ohe = pd.concat([df_teams_ohe,df_events['MatchID']],axis=1).groupby('MatchID').mean()\ndf_fouls = df_events_grp.join(df_teams_ohe)\ndf_fouls = df_fouls.reset_index()\ndf_fouls.drop(['MatchID'], 1,inplace=True)\ndf_fouls\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>HourGameStart</th>\n      <th>Year</th>\n      <th>Stage_1</th>\n      <th>Stage_2</th>\n      <th>Stage_3</th>\n      <th>Stage_4</th>\n      <th>Stage_5</th>\n      <th>Stage_6</th>\n      <th>GoalsTotal</th>\n      <th>GoalDifference</th>\n      <th>...</th>\n      <th>TUN</th>\n      <th>TUR</th>\n      <th>UAE</th>\n      <th>UKR</th>\n      <th>URS</th>\n      <th>URU</th>\n      <th>USA</th>\n      <th>WAL</th>\n      <th>YUG</th>\n      <th>ZAI</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.545455</td>\n      <td>0.714286</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.083333</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.636364</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.083333</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.818182</td>\n      <td>0.714286</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0.083333</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.818182</td>\n      <td>0.714286</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.166667</td>\n      <td>0.000000</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.909091</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.166667</td>\n      <td>0.000000</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>0.909091</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.166667</td>\n      <td>0.222222</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>0.545455</td>\n      <td>0.714286</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>0.909091</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.083333</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>0.545455</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.083333</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>0.909091</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.250000</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>10</th>\n      <td>0.909091</td>\n      <td>0.714286</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.083333</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>11</th>\n      <td>0.545455</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.250000</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>12</th>\n      <td>0.545455</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.166667</td>\n      <td>0.222222</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>13</th>\n      <td>0.909091</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.333333</td>\n      <td>0.222222</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>14</th>\n      <td>0.545455</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.083333</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>15</th>\n      <td>0.909091</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.083333</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>16</th>\n      <td>0.909091</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.250000</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>17</th>\n      <td>0.545455</td>\n      <td>0.714286</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.250000</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>18</th>\n      <td>0.909091</td>\n      <td>0.714286</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.416667</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>19</th>\n      <td>0.545455</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.250000</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>20</th>\n      <td>0.909091</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.333333</td>\n      <td>0.444444</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>21</th>\n      <td>0.545455</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.166667</td>\n      <td>0.000000</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>22</th>\n      <td>0.545455</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.166667</td>\n      <td>0.222222</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>23</th>\n      <td>0.545455</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.083333</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>24</th>\n      <td>0.545455</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.083333</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>25</th>\n      <td>0.909091</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.250000</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>0.909091</td>\n      <td>0.714286</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.416667</td>\n      <td>0.333333</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>0.909091</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.083333</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>0.909091</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.166667</td>\n      <td>0.000000</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>0.545455</td>\n      <td>0.714286</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>806</th>\n      <td>0.454545</td>\n      <td>1.000000</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.250000</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>807</th>\n      <td>0.181818</td>\n      <td>1.000000</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.166667</td>\n      <td>0.000000</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>808</th>\n      <td>0.545455</td>\n      <td>1.000000</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>809</th>\n      <td>0.454545</td>\n      <td>1.000000</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.333333</td>\n      <td>0.222222</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>810</th>\n      <td>0.545455</td>\n      <td>1.000000</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>811</th>\n      <td>0.545455</td>\n      <td>1.000000</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.166667</td>\n      <td>0.222222</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>812</th>\n      <td>0.181818</td>\n      <td>1.000000</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.083333</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>813</th>\n      <td>0.454545</td>\n      <td>1.000000</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.333333</td>\n      <td>0.000000</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>814</th>\n      <td>0.181818</td>\n      <td>1.000000</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.250000</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>815</th>\n      <td>0.454545</td>\n      <td>1.000000</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.500000</td>\n      <td>0.222222</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>816</th>\n      <td>0.454545</td>\n      <td>1.000000</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.250000</td>\n      <td>0.333333</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>817</th>\n      <td>0.545455</td>\n      <td>1.000000</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.250000</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>818</th>\n      <td>0.454545</td>\n      <td>1.000000</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.166667</td>\n      <td>0.222222</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>819</th>\n      <td>0.636364</td>\n      <td>1.000000</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.166667</td>\n      <td>0.000000</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>820</th>\n      <td>0.181818</td>\n      <td>1.000000</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.083333</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>821</th>\n      <td>0.454545</td>\n      <td>1.000000</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0.083333</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>822</th>\n      <td>0.545455</td>\n      <td>1.000000</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.250000</td>\n      <td>0.333333</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>823</th>\n      <td>0.181818</td>\n      <td>1.000000</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.083333</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>824</th>\n      <td>0.181818</td>\n      <td>1.000000</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.083333</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>825</th>\n      <td>0.454545</td>\n      <td>1.000000</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>826</th>\n      <td>0.545455</td>\n      <td>1.000000</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.166667</td>\n      <td>0.000000</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>827</th>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.250000</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>828</th>\n      <td>0.181818</td>\n      <td>1.000000</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.250000</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>829</th>\n      <td>0.454545</td>\n      <td>1.000000</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>830</th>\n      <td>0.454545</td>\n      <td>1.000000</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.500000</td>\n      <td>0.444444</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>831</th>\n      <td>0.636364</td>\n      <td>1.000000</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.083333</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>832</th>\n      <td>0.727273</td>\n      <td>1.000000</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.250000</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>833</th>\n      <td>0.636364</td>\n      <td>1.000000</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.250000</td>\n      <td>0.111111</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>834</th>\n      <td>0.454545</td>\n      <td>1.000000</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.583333</td>\n      <td>0.333333</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>835</th>\n      <td>0.545455</td>\n      <td>1.000000</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>...</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n<p>836 rows \u00d7 99 columns</p>\n</div>\n\n\n\n\n```python\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler()\ndf_fouls[['HourGameStart','Year','GoalsTotal','GoalDifference','GoalDifferenceHalfTime','DeltaGoals']] = scaler.fit_transform(df_fouls[['HourGameStart','Year','GoalsTotal','GoalDifference','GoalDifferenceHalfTime','DeltaGoals']])\n```\n\nUnfortunately, adding the team did not improve the model performance. Probably due to shortage of data.\n\n\n```python\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import datasets, linear_model\nfrom sklearn.metrics import mean_squared_error, r2_score\n\n# train test split\n# linear regression to predict y \nX = pd.concat([df_fouls.loc[:, 'HourGameStart':'IH'], df_fouls.loc[:, 'ALG':'ZAI']], axis=1)\nY = df_events_grp.loc[:, 'Y']\n\n# transform to numpy array\nX = X.as_matrix().astype(np.float)\nY = Y.as_matrix().astype(np.float)\n\n# train/ test split\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, random_state=40)\n\n# base model would be the average y value\n# needed for comparison\ny_base_pred = np.zeros((len(y_pred)))\ny_base_pred[:,] = y_train.mean()\n\n# fit regression model\nregr = linear_model.LinearRegression()\nregr.fit(X_train, y_train)\n\n# compare RMSE and R value with base model\ny_pred = regr.predict(X_test)\nprint(\"LINEAR REGRESSION: Mean squared error: %.2f\"\n      % mean_squared_error(y_test, y_pred))\nprint('LINEAR REGRESSION: Variance score: %.2f' % r2_score(y_test, y_pred))\n\nprint(\"BASE: Mean squared error: %.2f\"\n      % mean_squared_error(y_test, y_base_pred))\n# zero for sure, just added for completeness\nprint('BASE: Variance score: %.2f' % r2_score(y_test, y_base_pred))\n```\n\n    LINEAR REGRESSION: Mean squared error: 4.07\n    LINEAR REGRESSION: Variance score: 0.33\n    BASE: Mean squared error: 6.11\n    BASE: Variance score: -0.00\n\n\n# Predict Red Cards\nCan we also predict whether a red card was given? This is a classification task.\n\n\n```python\nf = {'HourGameStart':['mean'],\n     #'Home Team Goals':['mean'], # not symmetric -> throw out\n     #'Away Team Goals':['mean'],\n     #'Half-time Home Goals':['mean'],\n     #'Half-time Away Goals':['mean'],\n     'Year':['mean'],\n     'Stage_1':['mean'],\n     'Stage_2':['mean'],\n     'Stage_3':['mean'],\n     'Stage_4':['mean'],\n     'Stage_5':['mean'],\n     'Stage_6':['mean'],\n     'GoalsTotal':['mean'],\n     'GoalDifference':['mean'],\n     'GoalDifferenceHalfTime':['mean'],\n     'DeltaGoals':['mean'],\n     'ExtraTime':['mean'],\n     'Penalty':['mean'],\n     'I':['sum'], #substitutions\n     'IH':['sum'], #substitutions half time\n     'Y':['sum'],\n     'R':['sum'],\n     'RSY':['sum']\n    }\n\ndf_events_grp = df_events_ohe.groupby(['MatchID']).agg(f)\ndf_events_grp.columns = df_events_grp.columns.get_level_values(0)\n\n# create column indicating whether red cards were given\ndf_events_grp['R_total'] = df_events_grp.R + df_events_grp.RSY\ndf_events_grp = df_events_grp.assign(R_flag = lambda x : x.R_total > 0)\ndf_events_grp = df_events_grp.drop(columns=['R', 'RSY','R_total'])\ndf_events_grp\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>HourGameStart</th>\n      <th>Year</th>\n      <th>Stage_1</th>\n      <th>Stage_2</th>\n      <th>Stage_3</th>\n      <th>Stage_4</th>\n      <th>Stage_5</th>\n      <th>Stage_6</th>\n      <th>GoalsTotal</th>\n      <th>GoalDifference</th>\n      <th>GoalDifferenceHalfTime</th>\n      <th>DeltaGoals</th>\n      <th>ExtraTime</th>\n      <th>Penalty</th>\n      <th>I</th>\n      <th>IH</th>\n      <th>Y</th>\n      <th>R_flag</th>\n    </tr>\n    <tr>\n      <th>MatchID</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>25</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3</td>\n      <td>0</td>\n      <td>5</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>26</th>\n      <td>18</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3</td>\n      <td>1</td>\n      <td>4</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>27</th>\n      <td>20</td>\n      <td>1990</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>2</td>\n      <td>1</td>\n      <td>4</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>28</th>\n      <td>20</td>\n      <td>1990</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>True</td>\n      <td>3</td>\n      <td>1</td>\n      <td>7</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>29</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>4</td>\n      <td>0</td>\n      <td>5</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>30</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>2</td>\n      <td>1</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>4</td>\n      <td>0</td>\n      <td>6</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>31</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>True</td>\n      <td>3</td>\n      <td>0</td>\n      <td>5</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>42</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3</td>\n      <td>1</td>\n      <td>1</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>43</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>2</td>\n      <td>2</td>\n      <td>5</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>48</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3</td>\n      <td>1</td>\n      <td>9</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>55</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>True</td>\n      <td>False</td>\n      <td>4</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>56</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>4</td>\n      <td>0</td>\n      <td>0</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>57</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>2</td>\n      <td>0</td>\n      <td>2</td>\n      <td>False</td>\n      <td>False</td>\n      <td>1</td>\n      <td>2</td>\n      <td>1</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>66</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>4</td>\n      <td>2</td>\n      <td>2</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>2</td>\n      <td>2</td>\n      <td>3</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>73</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>4</td>\n      <td>0</td>\n      <td>4</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>74</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3</td>\n      <td>0</td>\n      <td>2</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>75</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>2</td>\n      <td>1</td>\n      <td>4</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>102</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>True</td>\n      <td>False</td>\n      <td>4</td>\n      <td>0</td>\n      <td>6</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>103</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>True</td>\n      <td>False</td>\n      <td>3</td>\n      <td>1</td>\n      <td>4</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>108</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>4</td>\n      <td>0</td>\n      <td>3</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>111</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>4</td>\n      <td>4</td>\n      <td>2</td>\n      <td>2</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3</td>\n      <td>1</td>\n      <td>3</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>114</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>2</td>\n      <td>0</td>\n      <td>4</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>119</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>2</td>\n      <td>0</td>\n      <td>2</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3</td>\n      <td>0</td>\n      <td>3</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>120</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3</td>\n      <td>1</td>\n      <td>1</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>127</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>2</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>128</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>4</td>\n      <td>0</td>\n      <td>4</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>129</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5</td>\n      <td>3</td>\n      <td>1</td>\n      <td>2</td>\n      <td>False</td>\n      <td>False</td>\n      <td>1</td>\n      <td>1</td>\n      <td>5</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>150</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>4</td>\n      <td>0</td>\n      <td>3</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>151</th>\n      <td>21</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3</td>\n      <td>1</td>\n      <td>2</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>152</th>\n      <td>17</td>\n      <td>1990</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>4</td>\n      <td>0</td>\n      <td>2</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>300186486</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>6</td>\n      <td>0</td>\n      <td>2</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186487</th>\n      <td>13</td>\n      <td>2014</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>True</td>\n      <td>12</td>\n      <td>0</td>\n      <td>14</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186488</th>\n      <td>17</td>\n      <td>2014</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>True</td>\n      <td>12</td>\n      <td>0</td>\n      <td>12</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186489</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>4</td>\n      <td>2</td>\n      <td>1</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>6</td>\n      <td>0</td>\n      <td>3</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>300186490</th>\n      <td>17</td>\n      <td>2014</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>True</td>\n      <td>True</td>\n      <td>10</td>\n      <td>2</td>\n      <td>6</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186491</th>\n      <td>17</td>\n      <td>2014</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>2</td>\n      <td>1</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>12</td>\n      <td>0</td>\n      <td>6</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186492</th>\n      <td>13</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>4</td>\n      <td>1</td>\n      <td>2</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186493</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>4</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>5</td>\n      <td>1</td>\n      <td>1</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186494</th>\n      <td>13</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>3</td>\n      <td>1</td>\n      <td>2</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186495</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>6</td>\n      <td>2</td>\n      <td>3</td>\n      <td>-1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>6</td>\n      <td>0</td>\n      <td>3</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186496</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>3</td>\n      <td>1</td>\n      <td>2</td>\n      <td>False</td>\n      <td>False</td>\n      <td>4</td>\n      <td>2</td>\n      <td>7</td>\n      <td>True</td>\n    </tr>\n    <tr>\n      <th>300186497</th>\n      <td>17</td>\n      <td>2014</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>True</td>\n      <td>False</td>\n      <td>12</td>\n      <td>0</td>\n      <td>4</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186498</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>2</td>\n      <td>2</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>5</td>\n      <td>1</td>\n      <td>3</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186499</th>\n      <td>18</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>6</td>\n      <td>0</td>\n      <td>4</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186500</th>\n      <td>13</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>5</td>\n      <td>1</td>\n      <td>2</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186501</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>True</td>\n      <td>False</td>\n      <td>10</td>\n      <td>2</td>\n      <td>8</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186502</th>\n      <td>17</td>\n      <td>2014</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>3</td>\n      <td>2</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>10</td>\n      <td>2</td>\n      <td>10</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186503</th>\n      <td>13</td>\n      <td>2014</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>True</td>\n      <td>False</td>\n      <td>12</td>\n      <td>0</td>\n      <td>10</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186504</th>\n      <td>13</td>\n      <td>2014</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>12</td>\n      <td>0</td>\n      <td>6</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186505</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>5</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186506</th>\n      <td>17</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n      <td>0</td>\n      <td>1</td>\n      <td>-1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>5</td>\n      <td>1</td>\n      <td>5</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186507</th>\n      <td>22</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>6</td>\n      <td>0</td>\n      <td>4</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186508</th>\n      <td>13</td>\n      <td>2014</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>10</td>\n      <td>2</td>\n      <td>6</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186509</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>5</td>\n      <td>1</td>\n      <td>4</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186510</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>6</td>\n      <td>4</td>\n      <td>0</td>\n      <td>4</td>\n      <td>False</td>\n      <td>False</td>\n      <td>6</td>\n      <td>0</td>\n      <td>4</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186511</th>\n      <td>18</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>5</td>\n      <td>0</td>\n      <td>2</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186512</th>\n      <td>19</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>5</td>\n      <td>1</td>\n      <td>2</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186513</th>\n      <td>18</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n      <td>False</td>\n      <td>6</td>\n      <td>0</td>\n      <td>1</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186514</th>\n      <td>16</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>7</td>\n      <td>3</td>\n      <td>3</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>5</td>\n      <td>1</td>\n      <td>1</td>\n      <td>False</td>\n    </tr>\n    <tr>\n      <th>300186515</th>\n      <td>17</td>\n      <td>2014</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>False</td>\n      <td>False</td>\n      <td>6</td>\n      <td>0</td>\n      <td>1</td>\n      <td>True</td>\n    </tr>\n  </tbody>\n</table>\n<p>836 rows \u00d7 18 columns</p>\n</div>\n\n\n\nThe decision tree is unable to outperform the base model. With higher tree depths the train test gap increases. The trees heavily overfit.\n\n\n```python\nfrom sklearn import tree\nfrom sklearn.metrics import accuracy_score\n\n# train test split\n# linear regression to predict y \nX = df_events_grp.loc[:, 'HourGameStart':'Y']\nY = df_events_grp.loc[:, 'R_flag']\n\n# transform to numpy array\nX = X.as_matrix().astype(np.float)\nY = Y.as_matrix().astype(np.float)\n\n# train/ test split\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, random_state=42)\n\ndef decision_tree_accuracy(depth):\n    # fit decision tree\n    clf = tree.DecisionTreeClassifier(max_depth=depth)\n    clf = clf.fit(X_train, y_train)\n\n    # compute accuracy\n    y_pred = clf.predict(X_test)\n    score = clf.score(X_test, y_test)\n    \n    train_score = accuracy_score(clf.predict(X_train), y_train)\n    \n    return score, train_score\n\n# for comparison also compute accuracy for base model (always output zero)\ny_base_pred = np.zeros((len(y_test))) # zeros as most matches are without red cards\nbase_score = accuracy_score(y_base_pred, y_test)\n\ndec_tree_accuracy = np.array([(i, decision_tree_accuracy(i)[0], decision_tree_accuracy(i)[1]) for i in range(1,15)])\nbase_accuracy = np.array([base_score for i in range(1,15)])\n\nplt.figure(figsize=(12,6))\n\nplt.plot(dec_tree_accuracy[:,0], dec_tree_accuracy[:,1]*100, label=\"Decision Tree Test\")\nplt.plot(dec_tree_accuracy[:,0], dec_tree_accuracy[:,2]*100, label=\"Decision Tree Train\")\nplt.plot(dec_tree_accuracy[:,0], base_accuracy*100, label=\"Base\")\n\nplt.legend()\nplt.title(\"Accuracies depending on tree depth\")\nplt.xlabel(\"Decision tree depth\")\nplt.ylabel(\"Accuracy (%)\")\n\nplt.show()\n```\n\nA little less overfitting, but still unable to achieve a significantly higher accuracy: random forests.\n\n\n```python\nfrom sklearn.ensemble import RandomForestClassifier\n\ndef random_forest_accuracy(depth):\n    # fit decision tree\n    clf = RandomForestClassifier(max_depth=depth, n_estimators=10)\n    clf = clf.fit(X_train, y_train)\n\n    # compute accuracy\n    y_pred = clf.predict(X_test)\n    score = clf.score(X_test, y_test)\n    \n    train_score = accuracy_score(clf.predict(X_train), y_train)\n    \n    return score, train_score\n\nrf_tree_accuracy = np.array([(i, random_forest_accuracy(i)[0], random_forest_accuracy(i)[1]) for i in range(1,15)])\n\nplt.figure(figsize=(12,6))\n\nplt.plot(rf_tree_accuracy[:,0], rf_tree_accuracy[:,1]*100, label=\"Random Forest Test\")\nplt.plot(rf_tree_accuracy[:,0], rf_tree_accuracy[:,2]*100, label=\"Random Forest Train\")\nplt.plot(rf_tree_accuracy[:,0], base_accuracy*100, label=\"Base\")\n\nplt.legend()\nplt.title(\"Accuracies depending on tree depth\")\nplt.xlabel(\"Decision tree depth\")\nplt.ylabel(\"Accuracy (%)\")\n\nplt.show()\n```\n\nk-NN does not perform significantly better either.\n\n\n```python\nfrom sklearn.neighbors import KNeighborsClassifier\n\ndef knn_accuracy(depth):\n    # fit decision tree\n    clf = KNeighborsClassifier(depth)\n    clf = clf.fit(X_train, y_train)\n\n    # compute accuracy\n    y_pred = clf.predict(X_test)\n    score = clf.score(X_test, y_test)\n    \n    train_score = accuracy_score(clf.predict(X_train), y_train)\n    \n    return score, train_score\n\nknn_accuracy = np.array([(i, knn_accuracy(i)[0], knn_accuracy(i)[1]) for i in range(1,15)])\n\nplt.figure(figsize=(12,6))\n\nplt.plot(knn_accuracy[:,0], knn_accuracy[:,1]*100, label=\"k-NN Test\")\nplt.plot(knn_accuracy[:,0], knn_accuracy[:,2]*100, label=\"k-NN Train\")\nplt.plot(knn_accuracy[:,0], base_accuracy*100, label=\"Base\")\n\nplt.legend()\nplt.title(\"Accuracies depending on k\")\nplt.xlabel(\"k\")\nplt.ylabel(\"Accuracy (%)\")\n\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "423cccac44c8359dba583e092ca58a4ea942089a", "size": 803734, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "FIFA_WM_Benjamin.ipynb", "max_stars_repo_name": "benni1371/ML_DHBW_Project", "max_stars_repo_head_hexsha": "e94efbd1092908388375fce619392a371b283c3c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FIFA_WM_Benjamin.ipynb", "max_issues_repo_name": "benni1371/ML_DHBW_Project", "max_issues_repo_head_hexsha": "e94efbd1092908388375fce619392a371b283c3c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FIFA_WM_Benjamin.ipynb", "max_forks_repo_name": "benni1371/ML_DHBW_Project", "max_forks_repo_head_hexsha": "e94efbd1092908388375fce619392a371b283c3c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.5419363274, "max_line_length": 34548, "alphanum_fraction": 0.4775522748, "converted": true, "num_tokens": 101704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15405756269148546, "lm_q2_score": 0.03161876818116342, "lm_q1q2_score": 0.00487111036129713}}
{"text": "## Analyse\n\n\n\n\n\ninstall needed Packages  \n\n\n\n\n```\n# only 4 anaconda users\n# for our project we need to install some packages\n# in a lokal IDE  this must be done via console or the anaconda package manager\n\n#Windows\n  # install https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads \n  # insall https://visualstudio.microsoft.com/de/thank-you-downloading-visual-studio/?sku=Community&rel=15\n  # pip install pm4py  \n  # pip install graphviz\n  # pip install pm4pybpmn\n  # pip install pygraphviz\n\n#mac\n  # pip install pm4py\n  # python -c \"import pm4py\"\n  # pip install graphviz\n  # pip install pm4pybpmn\n  # pip install pygraphviz\n\n\n#linux\n  # g++ -v\n  # apt-get install graphviz\n  # pip install pm4py\n  # pip install graphviz\n  # pip install pm4pybpmn\n  # pip install pygraphviz\n\n# details / error handling check https://pm4py.fit.fraunhofer.de/install-page#item-1-2 \n\n```\n\n\n```\n# only 4 Colab\nif 'google.colab' in str(get_ipython()):\n  !apt-get install python3-tk\n  #!apt-get install -y graphviz-dev\n  #!apt-get install python3-dev graphviz libgraphviz-dev pkg-config\n  !pip install graphviz\n  !pip install pm4pybpmn\n  !pip install pygraphviz\n```\n\n    Reading package lists... Done\n    Building dependency tree       \n    Reading state information... Done\n    python3-tk is already the newest version (3.6.9-1~18.04).\n    0 upgraded, 0 newly installed, 0 to remove and 14 not upgraded.\n    Requirement already satisfied: graphviz in /usr/local/lib/python3.6/dist-packages (0.10.1)\n    Requirement already satisfied: pm4pybpmn in /usr/local/lib/python3.6/dist-packages (0.1.6)\n    Requirement already satisfied: intervaltree in /usr/local/lib/python3.6/dist-packages (from pm4pybpmn) (2.1.0)\n    Requirement already satisfied: joblib in /usr/local/lib/python3.6/dist-packages (from pm4pybpmn) (0.17.0)\n    Requirement already satisfied: pydotplus in /usr/local/lib/python3.6/dist-packages (from pm4pybpmn) (2.0.2)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.6/dist-packages (from pm4pybpmn) (2.5)\n    Requirement already satisfied: lime in /usr/local/lib/python3.6/dist-packages (from pm4pybpmn) (0.2.0.1)\n    Requirement already satisfied: bpmn-python==0.0.18 in /usr/local/lib/python3.6/dist-packages (from pm4pybpmn) (0.0.18)\n    Requirement already satisfied: pm4py in /usr/local/lib/python3.6/dist-packages (from pm4pybpmn) (2.1.0.2)\n    Requirement already satisfied: sortedcontainers in /usr/local/lib/python3.6/dist-packages (from intervaltree->pm4pybpmn) (2.3.0)\n    Requirement already satisfied: pyparsing>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from pydotplus->pm4pybpmn) (2.4.7)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx>=2.2->pm4pybpmn) (4.4.2)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.6/dist-packages (from lime->pm4pybpmn) (3.2.2)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from lime->pm4pybpmn) (4.41.1)\n    Requirement already satisfied: scikit-learn>=0.18 in /usr/local/lib/python3.6/dist-packages (from lime->pm4pybpmn) (0.22.2.post1)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from lime->pm4pybpmn) (1.18.5)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from lime->pm4pybpmn) (1.4.1)\n    Requirement already satisfied: scikit-image>=0.12 in /usr/local/lib/python3.6/dist-packages (from lime->pm4pybpmn) (0.16.2)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from bpmn-python==0.0.18->pm4pybpmn) (1.1.4)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from bpmn-python==0.0.18->pm4pybpmn) (1.15.0)\n    Requirement already satisfied: lxml in /usr/local/lib/python3.6/dist-packages (from pm4py->pm4pybpmn) (4.2.6)\n    Requirement already satisfied: graphviz in /usr/local/lib/python3.6/dist-packages (from pm4py->pm4pybpmn) (0.10.1)\n    Requirement already satisfied: pyvis in /usr/local/lib/python3.6/dist-packages (from pm4py->pm4pybpmn) (0.1.8.2)\n    Requirement already satisfied: pulp<=2.1 in /usr/local/lib/python3.6/dist-packages (from pm4py->pm4pybpmn) (2.1)\n    Requirement already satisfied: jsonpickle in /usr/local/lib/python3.6/dist-packages (from pm4py->pm4pybpmn) (1.4.2)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.6/dist-packages (from pm4py->pm4pybpmn) (1.1.1)\n    Requirement already satisfied: ciso8601; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from pm4py->pm4pybpmn) (2.1.3)\n    Requirement already satisfied: pm4pycvxopt>=0.0.10; python_version < \"3.9\" in /usr/local/lib/python3.6/dist-packages (from pm4py->pm4pybpmn) (0.0.10)\n    Requirement already satisfied: stringdist in /usr/local/lib/python3.6/dist-packages (from pm4py->pm4pybpmn) (1.0.9)\n    Requirement already satisfied: deprecation in /usr/local/lib/python3.6/dist-packages (from pm4py->pm4pybpmn) (2.1.0)\n    Requirement already satisfied: pytz in /usr/local/lib/python3.6/dist-packages (from pm4py->pm4pybpmn) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->lime->pm4pybpmn) (2.8.1)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->lime->pm4pybpmn) (1.3.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib->lime->pm4pybpmn) (0.10.0)\n    Requirement already satisfied: pillow>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from scikit-image>=0.12->lime->pm4pybpmn) (7.0.0)\n    Requirement already satisfied: PyWavelets>=0.4.0 in /usr/local/lib/python3.6/dist-packages (from scikit-image>=0.12->lime->pm4pybpmn) (1.1.1)\n    Requirement already satisfied: imageio>=2.3.0 in /usr/local/lib/python3.6/dist-packages (from scikit-image>=0.12->lime->pm4pybpmn) (2.4.1)\n    Requirement already satisfied: jinja2>=2.9.6 in /usr/local/lib/python3.6/dist-packages (from pyvis->pm4py->pm4pybpmn) (2.11.2)\n    Requirement already satisfied: ipython>=5.3.0 in /usr/local/lib/python3.6/dist-packages (from pyvis->pm4py->pm4pybpmn) (5.5.0)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from jsonpickle->pm4py->pm4pybpmn) (2.0.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy->pm4py->pm4pybpmn) (1.1.0)\n    Requirement already satisfied: cvxopt in /usr/local/lib/python3.6/dist-packages (from pm4pycvxopt>=0.0.10; python_version < \"3.9\"->pm4py->pm4pybpmn) (1.2.5)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.6/dist-packages (from deprecation->pm4py->pm4pybpmn) (20.4)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.6/dist-packages (from jinja2>=2.9.6->pyvis->pm4py->pm4pybpmn) (1.1.1)\n    Requirement already satisfied: pexpect; sys_platform != \"win32\" in /usr/local/lib/python3.6/dist-packages (from ipython>=5.3.0->pyvis->pm4py->pm4pybpmn) (4.8.0)\n    Requirement already satisfied: pygments in /usr/local/lib/python3.6/dist-packages (from ipython>=5.3.0->pyvis->pm4py->pm4pybpmn) (2.6.1)\n    Requirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.6/dist-packages (from ipython>=5.3.0->pyvis->pm4py->pm4pybpmn) (0.8.1)\n    Requirement already satisfied: setuptools>=18.5 in /usr/local/lib/python3.6/dist-packages (from ipython>=5.3.0->pyvis->pm4py->pm4pybpmn) (50.3.2)\n    Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.6/dist-packages (from ipython>=5.3.0->pyvis->pm4py->pm4pybpmn) (1.0.18)\n    Requirement already satisfied: pickleshare in /usr/local/lib/python3.6/dist-packages (from ipython>=5.3.0->pyvis->pm4py->pm4pybpmn) (0.7.5)\n    Requirement already satisfied: traitlets>=4.2 in /usr/local/lib/python3.6/dist-packages (from ipython>=5.3.0->pyvis->pm4py->pm4pybpmn) (4.3.3)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata; python_version < \"3.8\"->jsonpickle->pm4py->pm4pybpmn) (3.4.0)\n    Requirement already satisfied: ptyprocess>=0.5 in /usr/local/lib/python3.6/dist-packages (from pexpect; sys_platform != \"win32\"->ipython>=5.3.0->pyvis->pm4py->pm4pybpmn) (0.6.0)\n    Requirement already satisfied: wcwidth in /usr/local/lib/python3.6/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython>=5.3.0->pyvis->pm4py->pm4pybpmn) (0.2.5)\n    Requirement already satisfied: ipython-genutils in /usr/local/lib/python3.6/dist-packages (from traitlets>=4.2->ipython>=5.3.0->pyvis->pm4py->pm4pybpmn) (0.2.0)\n    Requirement already satisfied: pygraphviz in /usr/local/lib/python3.6/dist-packages (1.6)\n\n\n## 1.1 BPMN import\n\n\n```\n#import libraries\nimport os\nimport graphviz\nimport pandas as pd\nimport lxml as lx\nimport networkx\nimport matplotlib\nimport pydotplus\n\n```\n\n\n```\n#get & load data\n!wget https://bitbucket.org/JMU-BWL6/iiv_data_bpmn/raw/14f0142e9ed9c7b79305a21c03e77d12f82ec7da/Test.bpmn\n```\n\n\n```\n# show XML in JPN\ntree = lx.etree.parse(\"Test.bpmn\")\npretty = lx.etree.tostring(tree, encoding=\"unicode\", pretty_print=True)\nprint(pretty)\n```\n\n## 1.2 BPMN chart\n\n\n\n```\n#import pm4py bib\nfrom pm4pybpmn.objects.bpmn.importer import bpmn20 as bpmn_importer3\nfrom pm4pybpmn.visualization.bpmn import factory as bpmn_vis_factory\n\n```\n\n\n```\n#BPMN import as graph \nbpmn_graph = bpmn_importer3.import_bpmn(\"Test.bpmn\")\n```\n\n\n```\n#BPMN graph to figure\nbpmn_figure = bpmn_vis_factory.apply(bpmn_graph)\nbpmn_vis_factory.view(bpmn_figure)\n```\n", "meta": {"hexsha": "88f384f415a5a45b4c1e85103e874dcc650a56ad", "size": 41375, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "BPMN_Showcase.ipynb", "max_stars_repo_name": "JMU-BWL6/IIV_2020_BPMN", "max_stars_repo_head_hexsha": "5990c9987863ae75f8784d50ca7bd2640e94459f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BPMN_Showcase.ipynb", "max_issues_repo_name": "JMU-BWL6/IIV_2020_BPMN", "max_issues_repo_head_hexsha": "5990c9987863ae75f8784d50ca7bd2640e94459f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BPMN_Showcase.ipynb", "max_forks_repo_name": "JMU-BWL6/IIV_2020_BPMN", "max_forks_repo_head_hexsha": "5990c9987863ae75f8784d50ca7bd2640e94459f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 143.6631944444, "max_line_length": 27222, "alphanum_fraction": 0.8394199396, "converted": true, "num_tokens": 3176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1710612085823741, "lm_q2_score": 0.02843603479449575, "lm_q1q2_score": 0.0048643024792368855}}
{"text": "```python\n# Run the scrapper\n\n%run mpia.py -d today\n```\n\n    *** Matched author:  Wel Arjen van der Wel\n    *** Matched author:  Wu Po-Feng Wu\n    *** Matched author:  Barisic Ivana Barisic\n    *** Matched author:  Chauke Priscilla Chauke\n    *** Matched author:  Houdt Josha van Houdt\n    *** Matched author:  Pillepich Annalisa Pillepich\n    *** Matched author:  Joshi Gandhali Joshi\n    *** Matched author:  Gould Andrew Gould\n    *** Matched author:  Martin Nicolas Martin\n    *** Matched author:  Wang Jason J. Wang\n    *** Matched author:  Zhu Zhaohuan Zhu\n    *** Matched author:  Walter Alex B. Walter\n    *** Matched author:  Soler J. D. Soler\n    *** Matched author:  Beuther H. Beuther\n    *** Matched author:  Rugel M. Rugel\n    *** Matched author:  Wang Y. Wang\n    *** Matched author:  Henning Th. Henning\n    *** Matched author:  Kainulainen J. Kainulainen\n    *** Matched author:  Mottram J. C. Mottram\n    *** Matched author:  Lee Eve J. Lee\n    *** Matched author:  Feldt M. Feldt\n    *** Matched author:  Cantalloube F. Cantalloube\n    *** Matched author:  Keppler M. Keppler\n    *** Matched author:  Maire A.-L. Maire\n    *** Matched author:  Mueller A. Mueller\n    *** Matched author:  Samland M. Samland\n    *** Matched author:  Henning T. Henning\n    *** Matched author:  Henning T. Henning\n    *** Matched author:  Wu Dong-Hong Wu\n    *** Matched author:  Zhang Rachel C. Zhang\n    *** Matched author:  Wang Shiang-Yu Wang\n    *** Matched author:  Wu Gang Wu\n    *** Matched author:  Bouwman Jordy Bouwman\n    *** Matched author:  Bouwman Jordy Bouwman\n    *** Matched author:  Avenhaus Henning Avenhaus\n    *** Matched author:  Bertrang Gesa H. -M. Bertrang\n    *** Matched author:  Schreiber Matthias R. Schreiber\n    *** Matched author:  Jord\u00e1n Andr\u00e9s Jord\u00e1n\n    *** Matched author:  Espinoza N\u00e9stor Espinoza\n    *** Matched author:  Henning Thomas Henning\n    *** Matched author:  Rabus Markus Rabus\n    *** Matched author:  Sarkis Paula Sarkis\n    *** Matched author:  Ludwig H.-G. Ludwig\n    *** Matched author:  Zhang Ming-Jian Zhang\n    *** Matched author:  Martin R Martin\n    *** Matched author:  Bailer-Jones C.A.L. Bailer-Jones\n    *** Matched author:  Wang Ji Wang\n    [arXiv:1809.08236]:  The Large Early Galaxy Astrophysics Census (LEGA-C) Data Release II:  dynamical and stellar population properties of z ~< 1 galaxies in the COSMOS  field\n    \tCaroline M. S. Straatman, \\hl{Arjen van der Wel}, Rachel Bezanson, Camilla Pacifici, Anna Gallazzi, \\hl{Po-Feng Wu}, Kai Noeske, \\hl{Ivana Barisic}, Eric F. Bell, Gabriel B. Brammer, Joao Calhau, \\hl{Priscilla Chauke}, Marijn Franx, \\hl{Josha van Houdt}, Ivo Labbe, Michael V. Maseda, Juan C. Munoz-Mateos, Adam Muzzin, Jesse van de Sande, David Sobral, Justin S. Spilker\n    extracting tarball...\n    *** Found macros and definitions in the header: \n    \\providecommand{\\how}[1]{\\textcolor{purple}{#1}}\n    \\providecommand{\\rA}{\\mathrm{\\AA}}\n    \\providecommand{\\msun}{\\mathrm{M}_{\\sun}}\n    \\providecommand{\\logm}{\\mathrm{logM/\\msun}}\n    \\providecommand{\\ha}{H$\\alpha$}\n    \\providecommand{\\hb}{H$\\beta$}\n    \\providecommand{\\hg}{H$\\gamma$}\n    \\providecommand{\\hd}{H$\\delta$}\n    \\providecommand{\\dfn}{D$4000_n$}\n    \\providecommand{\\hda}{\\hd$_\\mathrm{A}$}\n    \\providecommand{\\mgt}{$\\mathrm{Mg_{2}}$}\n    \\providecommand{\\nuse}{1442}\n    \\providecommand{\\hblim}{$44.9\\times10^{-19}\\ \\mathrm{ergs\\ cm^{-2}\\ s^{-1}}$}\n    \\providecommand{\\sfrlima}{$0.23\\ \\msun\\ \\mathrm{yr^{-1}}$}\n    \\providecommand{\\sfrlimb}{$0.47\\ \\msun\\ \\mathrm{yr^{-1}}$}\n    \\providecommand{\\sfrlimc}{$0.72\\ \\msun\\ \\mathrm{yr^{-1}}$}\n    \\providecommand{\\medianz}{$z_{\\mathrm{spec}}=0.697$}\n    \\providecommand{\\sfrlimfinal}{$2.2\\ \\msun\\ \\mathrm{yr^{-1}}$}\n    \\providecommand{\\totn}{1988}\n    \\providecommand{\\prims}{1550}\n    \\providecommand{\\fills}{438}\n    \n    **** From Heidelberg: True\n    \n    Caroline M. S. Straatman, et al.; incl. \\hl{Arjen van der Wel}, \\hl{Po-Feng Wu}, \\hl{Ivana Barisic}, \\hl{Priscilla Chauke}, \\hl{Josha van Houdt}\n    PDF postage: 1809.08236.pdf\n    [arXiv:1809.08239]:  The optical morphologies of galaxies in the IllustrisTNG simulation: a  comparison to Pan-STARRS observations\n    \tVicente Rodriguez-Gomez, Gregory F. Snyder, Jennifer M. Lotz, Dylan Nelson, \\hl{Annalisa Pillepich}, Volker Springel, Shy Genel, Rainer Weinberger, Sandro Tacchella, Ruediger Pakmor, Paul Torrey, Federico Marinacci, Mark Vogelsberger, Lars Hernquist, David A. Thilker\n    extracting tarball...\n    *** Found macros and definitions in the header: \n    \\providecommand{\\Msun}{{\\rm M}_{\\odot}}\n    \\providecommand{\\facc}{f_{\\rm acc}}\n    \\providecommand{\\fex}{f_{\\rm ex}}\n    \\providecommand{\\krot}{\\kappa_{\\rm rot}}\n    \n    **** From Heidelberg: True\n    \n    Vicente Rodriguez-Gomez, et al.; incl. \\hl{Annalisa Pillepich}\n    PDF postage: 1809.08239.pdf\n    [arXiv:1809.08241]:  Wide-Field Optical Spectroscopy of Abell 133: A Search for Filaments  Reported in X-ray Observations\n    \tThomas Connor, Daniel D. Kelson, John Mulchaey, Alexey Vikhlinin, Shannon G. Patel, Michael L. Balogh, \\hl{Gandhali Joshi}, Ralph Kraft, Daisuke Nagai, Svetlana Starikova\n    extracting tarball...\n    *** Found macros and definitions in the header: \n    \\providecommand{\\vdag}{(v)^\\dagger}\\graphicspath{{./}{figures/}}\n    \n    **** From Heidelberg: True\n    \n    Thomas Connor, et al.; incl. \\hl{Gandhali Joshi}\n    PDF postage: 1809.08241.pdf\n    [arXiv:1809.08243]:  First Resolution of Microlensed Images\n    \tSubo Dong,  (KIAA-PKU), , A. M\u00e9rand, F. Delplancke-Str\u00f6bele,  (ESO), , \\hl{Andrew Gould},  (MPIA, KASI, OSU), , Ping Chen, R. Post, C.S. Kochanek, K. Z. Stanek, G. W. Christie, Robert Mutel, T. Natusch, T. W.-S. Holoien, J. L. Prieto, B. J. Shappee, Todd A. Thompson\n    extracting tarball...\n    *** Found macros and definitions in the header: \n    \\providecommand{\\msun}{{\\rm \\ M_\\odot}}\n    \\providecommand{\\bdv}[1]{\\mbox{\\boldmath$#1$}}\n    \\providecommand{\\bd}[1]{{\\rm #1}}\\def\\au{{\\rm AU}} \n    \\def\\sinc{{\\rm sinc}} \n    \\def\\kms{{\\rm km}\\,{\\rm s}^{-1}}\n    \\def\\masyr{{\\rm mas}\\,{\\rm yr}^{-1}}\n    \\def\\kpc{{\\rm kpc}}\n    \\def\\mas{{\\rm mas}}\n    \\def\\sat{{\\rm sat}}\n    \\def\\muas{\\mu{\\rm as}}\n    \\def\\var{{\\rm var}}\n    \\def\\pc{{\\rm pc}}\n    \\def\\orb{{\\rm orb}}\n    \\def\\obs{{\\rm obs}}\n    \\def\\max{{\\rm max}}\n    \\def\\min{{\\rm min}}\n    \\def\\rel{{\\rm rel}}\n    \\def\\ast{{\\rm ast}}\n    \\def\\eff{{\\rm eff}}\n    \\def\\rot{{\\rm rot}}\n    \\def\\lsr{{\\rm lsr}}\n    \\def\\hel{{\\rm hel}}\n    \\def\\geo{{\\rm geo}}\n    \\def\\e{{\\rm E}}\n    \\def\\bpi{{\\bdv\\pi}}\n    \\def\\bmu{{\\bdv\\mu}}\n    \\def\\balpha{{\\bdv\\alpha}}\n    \\def\\bgamma{{\\bdv\\gamma}}\n    \\def\\bDelta{{\\bdv\\Delta}}\n    \\def\\btheta{{\\bdv\\theta}}\n    \\def\\bphi{{\\bdv\\phi}}\n    \\def\\bp{{\\bf p}}\n    \\def\\bv{{\\bf v}}\n    \\def\\bu{{\\bf u}}\n    \\def\\naive{{\\rm naive}}\n    \\def\\revise{\\bf}\n    \n    **** From Heidelberg: True\n    \n    Subo Dong, et al.; incl. \\hl{Andrew Gould}\n    PDF postage: 1809.08243.pdf\n    [arXiv:1809.08245]:  A-type stars in the Canada-France Imaging Survey I. The stellar halo of  the Milky Way traced to large radius by blue horizontal branch stars\n    \tGuillaume F. Thomas, Alan W. McConnachie, Rodrigo A. Ibata, Patrick C\u00f4t\u00e9, \\hl{Nicolas Martin}, Else Starkenburg, Raymond Carlberg, Scott Chapman, S\u00e9bastien Fabbro, Benoit Famaey, Nicholas Fantin, Stephen Gwyn, Vincent H\u00e9nault-Brunet, Khyati Malhan, Julio Navarro, Annie C. Robin, Douglas Scott\n    extracting tarball...\n    *** Found macros and definitions in the header: \n    \\def\\ltsima{$\\; \\buildrel < \\over \\sim \\;$}\n    \\def\\simlt{\\lower.5ex\\hbox{\\ltsima}}\n    \\def\\gtsima{$\\; \\buildrel > \\over \\sim \\;$}\n    \\def\\simgt{\\lower.5ex\\hbox{\\gtsima}}\n    \n    **** From Heidelberg: True\n    \n    Guillaume F. Thomas, et al.; incl. \\hl{Nicolas Martin}\n    PDF postage: 1809.08245.pdf\n    [arXiv:1809.08261]:  A Bayesian Framework for Exoplanet Direct Detection and Non-Detection\n    \tJean-Baptiste Ruffio, Dimitri Mawet, Ian Czekala, Bruce Macintosh, Robert J. De Rosa, Garreth Ruane, Michael Bottom, Laurent Pueyo, \\hl{Jason J. Wang}, Lea Hirsch, \\hl{Zhaohuan Zhu}, Eric L. Nielsen\n    extracting tarball...\n    multiple tex files\n    Found main document in:  (0, './tmp/sample62.tex')\n    Found main document in:  ./tmp/sample62.tex\n    0 ./tmp/sample62.tex\n    Found main document in:  ./tmp/sample62.tex\n    *** Found document inclusions \n          input command:  content\n    *** Found macros and definitions in the header: \n    \\providecommand{\\vdag}{(v)^\\dagger}\n    \\providecommand{\\Secref}[1]{\\hyperref[#1]{Section~\\ref*{#1}}}\n    \\providecommand{\\Appref}[1]{\\hyperref[#1]{Appendix~\\ref*{#1}}}\n    \\providecommand{\\epseri}{$\\epsilon$ Eridani}\\graphicspath{{./}{figures/}}\n    \n    **** From Heidelberg: False\n    \n    *** print_tb\n      File \"/home/jovyan/mpia.py\", line 160, in main\n        raise RuntimeError('Not an institute paper')\n    Not an institute paper \n    \n    [arXiv:1809.08301]:  SCExAO, an instrument with a dual purpose: perform cutting-edge science  and develop new technologies\n    \tJulien Lozi, Olivier Guyon, Nemanja Jovanovic, Sean Goebel, Prashant Pathak, Nour Skaf, Ananya Sahoo, Barnaby Norris, Frantz Martinache, Mamadou N'Diaye, Ben Mazin, \\hl{Alex B. Walter}, Peter Tuthill, Tomoyuki Kudo, Hajime Kawahara, Takayuki Kotani, Michael Ireland, Nick Cvetojevic, Elsa Huby, Sylvestre Lacour, Sebastien Vievard, Tyler D. Groff, Jeffrey K. Chilcote, Jeremy Kasdin, Justin Knight, Frans Snik, David Doelman, Yosuke Minowa, Christophe Clergeon, Naruhisa Takato, Motohide Tamura, Thayne Currie, Hideki Takami, Masa Hayashi\n    extracting tarball...\n    *** Found macros and definitions in the header: \n    \\providecommand{\\baselinestretch}{1.0}\n    \\providecommand{\\mum}{\\mbox{{\\usefont{U}{eur}{m}{n}{\\char22}}m}\\xspace}\n    \\providecommand{\\mus}{\\mbox{{\\usefont{U}{eur}{m}{n}{\\char22}}s}\\xspace}\n    \\providecommand{\\sce}{\\mbox{SCE\\lowercase{x}AO}\\xspace}\n    \\providecommand{\\e}[1]{10^{#1}}\n    \\providecommand{\\E}[1]{\\times10^{#1}}\n    \\providecommand{\\lod}{\\mbox{$\\lambda$/D}\\xspace}\n    \\providecommand{\\FIG}[3]{\\includegraphics[width=#1\\linewidth,draft=#2]{#3}}\n    \\providecommand{\\FIGH}[3]{\\includegraphics[height=#1cm,draft=#2]{#3}}\n    \n    **** From Heidelberg: False\n    \n    *** print_tb\n      File \"/home/jovyan/mpia.py\", line 160, in main\n        raise RuntimeError('Not an institute paper')\n    Not an institute paper \n    \n    [arXiv:1809.08338]:  Histogram of oriented gradients: a technique for the study of molecular  cloud formation\n    \t\\hl{J. D. Soler}, \\hl{H. Beuther}, \\hl{M. Rugel}, \\hl{Y. Wang}, L. D. Anderson, P. C. Clark, S. C. O. Glover, P. F. Goldsmith, A. Goodman, P. Hennebelle, \\hl{Th. Henning}, M. Heyer, \\hl{J. Kainulainen}, R. S. Klessen, N. M. McClure-Griffiths, K. M. Menten, \\hl{J. C. Mottram}, S. E. Ragan, P. Schilke, R. J. Smith, J. S. Urquhart, F. Bigiel, N. Roy\n    extracting tarball...\n    multiple tex files\n    Found main document in:  (0, './tmp/HIandCO.tex')\n    Found main document in:  ./tmp/HIandCO.tex\n    0 ./tmp/HIandCO.tex\n    Found main document in:  ./tmp/HIandCO.tex\n    *** Found document inclusions \n          input command:  PIP_113_Boulanger_authors_and_institutes\n    *** print_tb\n      File \"/home/jovyan/app.py\", line 847, in _expand_auxilary_files\n        with open(directory + fname + '.tex', 'r', errors=\"surrogateescape\") as fauxilary:\n    [Errno 2] No such file or directory: './tmp/PIP_113_Boulanger_authors_and_institutes.tex' \n    \n    *** Found macros and definitions in the header: \n    \\providecommand{\\henrik}[1]{{\\bf \\color{green} [#1]}}\n    \\providecommand{\\hhenrik}[1]{}\n    \\providecommand{\\juan}[1]{{\\bf \\color{red} #1}}\n    \\providecommand{\\commentproof}[1]{{\\bf \\color{green}#1}}\n    \\providecommand{\\commentproof}[1]{}\n    \\providecommand{\\planck}{\\Planck}  \\def\\Herschel{\\textit{Herschetowardl}}\n    \\providecommand{\\nh}{$N_{\\textsc{H}}$}\n    \\providecommand{\\nhd}{N_{\\textsc{H}}} \n    \\providecommand{\\gradnh}{$\\mathbf{\\nabla}N_{\\textsc{H}}$}\n    \\providecommand{\\lognh}{$\\log_{10}(N_{\\textsc{H}}/\\mbox{cm}^{-2})$}\n    \\providecommand{\\microG}{$\\mu$G}\n    \\providecommand{\\bcf}{$B^{\\textsc{DCF}}_{\\perp}$}\n    \\providecommand{\\bhilde}{$B^{\\textsc{\\HIL}}_{\\perp}$}\n    \\providecommand{\\IRAS}{\\textit{IRAS\\/}}\n    \\providecommand{\\WMAP}{\\textit{WMAP\\/}}\n    \\providecommand{\\COBE}{\\textit{COBE\\/}}\n    \\providecommand{\\Spitzer}{\\textit{Spitzer\\/}}\n    \\providecommand{\\healpix}{{\\sc HEALPix}}\n    \\providecommand{\\sextractor}{{\\sc SExtractor}}\n    \\providecommand{\\hii}{\\ion{H}{II}}\n    \\providecommand{\\viewangle}{\\alpha}\n    \\providecommand{\\bvect}{\\vec{B}}\n    \\providecommand{\\planckurl}{\\burl{http://www.rssd.esa.int/index.php?project=PLANCK&page=Planck_Collaboration}}\n    \\providecommand{\\sorthelp}[1]{}\n    \\providecommand{\\bperp}{$\\langle\\hat{\\vec{B}}_{\\perp}\\rangle$}\n    \\providecommand{\\wc}{{\\mkern 2mu\\cdot\\mkern 2mu}}\n    \\providecommand{\\prs}{$V$}\n    \\providecommand{\\mrv}{$r$}\n    \\providecommand{\\kps}{km\\,s$^{-1}$}\n    \\providecommand{\\vhi}{$v_{\\rm HI}$}\n    \\providecommand{\\vco}{$v_{\\rm 13CO}$}\n    \\providecommand{\\vlsr}{$v_{\\rm LSR}$}\n    \\providecommand{\\vlos}{$v_{\\rm LOS}$}\\def\\bfc{}\n    \\def\\bfc{\\bf}\n    \\def\\bfm{\\bf \\color{magenta}}\n    \\def\\bfm{} \\newcommand{\\commentproof}[1]{{\\bf \\color{green}#1}}\n    \\def\\Herschel{\\textit{Herschetowardl}}\n    \n    **** From Heidelberg: True\n    \n    \\hl{J. D. Soler}, et al.; incl. \\hl{H. Beuther}, \\hl{M. Rugel}, \\hl{Y. Wang}, \\hl{Th. Henning}, \\hl{J. Kainulainen}, \\hl{J. C. Mottram}\n    PDF postage: 1809.08338.pdf\n    [arXiv:1809.08348]:  On The Nature of Variations in the Measured Star Formation Efficiency of  Molecular Clouds\n    \tMichael Y. Grudi\u0107, Philip F. Hopkins, \\hl{Eve J. Lee}, Norman Murray, Claude-Andr\u00e9 Faucher-Gigu\u00e8re, L. Clifton Johnson\n    extracting tarball...\n    *** Found macros and definitions in the header: \n    \\providecommand{\\msun}{M_{\\sun}}\n    \\providecommand{\\oft}{\\left(t\\right)}\\defcitealias{grudic:2016.sfe}{G18}\n    \\defcitealias{lee:2016.gmc.eff}{L+16}\n    \\defcitealias{vuti:2016.gmcs}{V+16}\n    \\defcitealias{heyer:2016.clumps}{H+16}\n    \\defcitealias{wu:2010.clumps}{W+10}\n    \\defcitealias{evans:2014.sfe}{E+14}\n    \\defcitealias{lada:2010.gmcs}{L+10}\n    \n    **** From Heidelberg: False\n    \n    *** print_tb\n      File \"/home/jovyan/mpia.py\", line 160, in main\n        raise RuntimeError('Not an institute paper')\n    Not an institute paper \n    \n    [arXiv:1809.08354]:  beta Pictoris b post conjunction detection with VLT/SPHERE\n    \tA.-M. Lagrange, A. Boccaletti, M. Langlois, G. Chauvin, R. Gratton, H. Beust, S. Desidera, J. Milli, M. Bonnefoy, \\hl{M. Feldt}, M. Meyer, A. Vigan, B. Biller, M. Bonavita, J.-L. Baudino, \\hl{F. Cantalloube}, M. Cudel, S. Daemgen, P. Delorme, V. DOrazi, J. Girard, C. Fontanive, J. Hagelberg, M. Janson, \\hl{M. Keppler}, T. Koypitova, R. Galicher, J. Lannier, H. Le Coroller, R. Ligi, \\hl{A.-L. Maire}, D. Mesa, S. Messina, \\hl{A. Mueller}, S. Peretti, C. Perrot, D. Rouan, G. Salter, \\hl{M. Samland}, T. Schmidt, E. Sissa, A. Zurlo, J.-L. Beuzit, D. Mouillet, C. Dominik, \\hl{T. Henning}, E. Lagadec, F. Menard, H.-M. Schmid, S. Udry, , the , SPHERE consortium\n    extracting tarball...\n    *** Found macros and definitions in the header: \n    \\providecommand{\\eg}{{\\it e.g.}, } \n    \\providecommand{\\ie}{{\\it i.e.}, } \n    \\providecommand{\\ms}{m\\,s$^{\\rm -1}$}\n    \\providecommand{\\kms}{km\\,s$^{\\rm -1}$}\n    \\providecommand{\\Mjup}{M$_{\\rm Jup}$}\n    \\providecommand{\\mjup}{M$_{\\rm Jup}$}\n    \\providecommand{\\mearth}{M$_{\\rm Earth}$} \n    \\providecommand{\\Msun}{M$_{\\sun}$} \n    \\providecommand{\\vsini}{$v\\sin{i}$}\n    \\providecommand{\\elodie}{E{\\small LODIE}} \n    \\providecommand{\\sophie}{S{\\small OPHIE}} \n    \\providecommand{\\harps}{H{\\small ARPS}}\n    \\providecommand{\\thetacyg}{$\\theta$\\,Cygni} \n    \\providecommand{\\bp}{$\\beta$\\,Pictoris\\,} \n    \\providecommand{\\bpic}{$\\beta$\\,Pictoris\\,}\n    \\providecommand{\\acena}{$\\alpha$\\,CenA\\,} \n    \\providecommand{\\acenb}{$\\alpha$\\,CenB\\,} \n    \\providecommand{\\plmo}{$^{+}_{-} $}\n    \\providecommand{\\muup}{$\\mu$m}\n    \n    **** From Heidelberg: True\n    \n    A.-M. Lagrange, et al.; incl. \\hl{M. Feldt}, \\hl{F. Cantalloube}, \\hl{M. Keppler}, \\hl{A.-L. Maire}, \\hl{A. Mueller}, \\hl{M. Samland}, \\hl{T. Henning}\n    PDF postage: 1809.08354.pdf\n    [arXiv:1809.08385]:  Properties and occurrence rates of $Kepler$ exoplanet candidates as a  function of host star metallicity from the DR25 catalog\n    \tM. Narang,  (TIFR), , P. Manoj,  (TIFR), , E. Furlan,  (IPAC), , C. Mordasini,  (Physikalisches Institut, Univ. of Bern), , \\hl{T. Henning},  (MPIA), , B. Mathew,  (Christ Univ.), , R. K. Banyal,  (IIA), , T. Sivarani,  (IIA)\n    extracting tarball...\n    *** Found macros and definitions in the header: \n    \\def\\teff {{$T_\\mathrm{eff}$ }}\n    \\def\\Re {{$\\,R_\\oplus$ }}\n    \\def\\Me {{$\\,M_\\oplus$ }}\n    \\def\\Rj {{$\\,R_J$ }}\n    \\def\\Mj {{$\\,M_\\mathrm{J}$ }}\n    \\def\\lg {{log$\\,g$ }}\n    \\def\\pl {{planetary }}\n    \\def\\plr {{planetary radius }}\n    \\def\\plm {{planetary mass }}\n    \\def \\hsm {{host star metallicity }}\n    \\def \\hs {{host star }}\n    \\def \\sc {{SWEET-Cat }}\n    \n    **** From Heidelberg: True\n    \n    M. Narang, et al.; incl. \\hl{T. Henning}\n    PDF postage: 1809.08385.pdf\n    [arXiv:1809.08499]:  Dynamical instability and its implications for planetary system  architecture\n    \t\\hl{Dong-Hong Wu}, \\hl{Rachel C. Zhang}, Ji-Lin Zhou, Jason H. Steffen\n    extracting tarball...\n    *** Found macros and definitions in the header: \n    \\providecommand{\\kepler}{\\textit{Kepler}}\\graphicspath{{./}{figures/}}\n    \n    **** From Heidelberg: False\n    \n    *** print_tb\n      File \"/home/jovyan/mpia.py\", line 160, in main\n        raise RuntimeError('Not an institute paper')\n    Not an institute paper \n    \n    [arXiv:1809.08501]:  Col-OSSOS: The Colours of the Outer Solar System Origins Survey\n    \tMegan E. Schwamb, Wesley C. Fraser, Michele T. Bannister, Michael Marsset, Rosemary E. Pike, J. J. Kavelaars, Susan D. Benecchi, Matthew J. Lehner, \\hl{Shiang-Yu Wang}, Audrey Thirouin, Audrey Delsanti, Nuno Peixinho, Kathryn Volk, Mike Alexandersen, Ying-Tung Chen, Brett Gladman, Stephen D. J. Gwyn, Jean-Marc Petit\n    extracting tarball...\n    *** Found macros and definitions in the header: \n    \n    \n    **** From Heidelberg: False\n    \n    *** print_tb\n      File \"/home/jovyan/mpia.py\", line 160, in main\n        raise RuntimeError('Not an institute paper')\n    Not an institute paper \n    \n    [arXiv:1809.08739]:  High-mass outflows identified from COHRS CO\\,(3 - 2) Survey\n    \tQiang Li, Jianjun Zhou, Jarken Esimbek, Yuxin He, W. A. Baan, Dalei Li, \\hl{Gang Wu}, Xindi Tang, Weiguang Ji\n    extracting tarball...\n    *** Found macros and definitions in the header: \n    \\providecommand{\\vdag}{(v)^\\dagger}\n    \\providecommand{\\RNum}[1]{\\uppercase\\expandafter{\\romannumeral #1\\relax}}\n    \n    **** From Heidelberg: False\n    \n    *** print_tb\n      File \"/home/jovyan/mpia.py\", line 160, in main\n        raise RuntimeError('Not an institute paper')\n    Not an institute paper \n    \n    [arXiv:1809.08798]:  Infrared Spectra of Hexa-peri-hexabenzocoronene Cations:HBC+ and HBC2+\n    \tJunfeng Zhen, Pablo Castellanos, \\hl{Jordy Bouwman}, Harold Linnartz, Alexander G. G. M. Tielens\n    extracting tarball...\n    *** Found macros and definitions in the header: \n    \n    \n    **** From Heidelberg: False\n    \n    *** print_tb\n      File \"/home/jovyan/mpia.py\", line 160, in main\n        raise RuntimeError('Not an institute paper')\n    Not an institute paper \n    \n    [arXiv:1809.08800]:  Laboratory gas-phase infrared spectra of two astronomically relevant PAH  cations: diindenoperylene, C$_{32}$H$_{16}$$^+$ and dicoronylene,  C$_{48}$H$_{20}$$^+$\n    \tJunfeng Zhen, Alessandra Candian, Pablo Castellanos, \\hl{Jordy Bouwman}, Harold Linnartz, Alexander G. G. M. Tielens\n    *** print_tb\n      File \"/home/jovyan/mpia.py\", line 155, in main\n        s = paper.retrieve_document_source('./tmp')\n      File \"/home/jovyan/app.py\", line 1092, in retrieve_document_source\n        tar = tarfile.open(mode='r|gz', fileobj=urlopen(where))\n      File \"/srv/conda/lib/python3.6/tarfile.py\", line 1597, in open\n        stream = _Stream(name, filemode, comptype, fileobj, bufsize)\n      File \"/srv/conda/lib/python3.6/tarfile.py\", line 379, in __init__\n        self._init_read_gz()\n      File \"/srv/conda/lib/python3.6/tarfile.py\", line 484, in _init_read_gz\n        raise ReadError(\"not a gzip file\")\n    not a gzip file \n    \n    [arXiv:1809.08844]:  The Ophiuchus DIsc Survey Employing ALMA (ODISEA) - I : project  description and continuum images at 28 au resolution\n    \tLucas A. Cieza, Dary Ru\u00edz-Rodr\u00edguez, Antonio Hales, Simon Casassus, Sebastian P\u00e9rez, Camilo Gonzalez-Ruilova, Hector C\u00e1novas, Jonathan P. Williams, Alice Zurlo, Megan Ansdell, \\hl{Henning Avenhaus}, Amelia Bayo, \\hl{Gesa H. -M. Bertrang}, Valentin Christiaens, William Dent, Gabriel Ferrero, Roberto Gamen, Johan Olofsson, Santiago Orcajo, Karla Pe\u00f1a Ram\u00edrez, David Principe, \\hl{Matthias R. Schreiber}, Gerrit van der Plas\n    extracting tarball...\n    *** Found macros and definitions in the header: \n    \n    \n    **** From Heidelberg: True\n    \n    Lucas A. Cieza, et al.; incl. \\hl{Henning Avenhaus}, \\hl{Gesa H. -M. Bertrang}, \\hl{Matthias R. Schreiber}\n    PDF postage: 1809.08844.pdf\n    [arXiv:1809.08879]:  EPIC 249451861b: an Eccentric Warm Saturn transiting a G-dwarf\n    \t\\hl{Andr\u00e9s Jord\u00e1n}, Rafael Brahm, \\hl{N\u00e9stor Espinoza}, Cristi\u00e1n Cort\u00e9s, Mat\u00edas D\u00edaz, Holger Drass, \\hl{Thomas Henning}, James S. Jenkins, Mat\u00edas I. Jones, \\hl{Markus Rabus}, Felipe Rojas, \\hl{Paula Sarkis}, Maja Vu\u010dkovi\u0107, Abner Zapata, Maritza G. Soto, G\u00e1sp\u00e1r \u00c1. Bakos, Daniel Bayliss, Waqas Bhatti, Zoltan Csubry, R\u00e9gis Lachaume, V\u00edctor Moraga, Blake Pantoja, David Osip, Avi Shporer, Vincent Suc, Sergio V\u00e1squez\n    extracting tarball...\n    *** Found macros and definitions in the header: \n    \\providecommand{\\vdag}{(v)^\\dagger}\n    \\providecommand{\\feh}{\\ensuremath{{\\rm [Fe/H]}}}\n    \\providecommand{\\teff}{\\ensuremath{T_{\\rm eff}}}\n    \\providecommand{\\teq}{\\ensuremath{T_{\\rm eq}}}\n    \\providecommand{\\logg}{\\ensuremath{\\log{g}}}\n    \\providecommand{\\zaspe}{\\texttt{ZASPE}}\n    \\providecommand{\\ceres}{\\texttt{CERES}}\n    \\providecommand{\\vsini}{\\ensuremath{v \\sin{i}}}\n    \\providecommand{\\kms}{\\ensuremath{{\\rm km\\,s^{-1}}}}\n    \\providecommand{\\mjup}{\\ensuremath{{\\rm M_{J}}}}\n    \\providecommand{\\mearth}{\\ensuremath{{\\rm M}_{\\oplus}}}\n    \\providecommand{\\mpl}{\\ensuremath{{\\rm M_P}}}\n    \\providecommand{\\rjup}{\\ensuremath{{\\rm R_J}}}\n    \\providecommand{\\rpl}{\\ensuremath{{\\rm R_P}}}\n    \\providecommand{\\rstar}{\\ensuremath{{\\rm R}_{\\star}}}\n    \\providecommand{\\mstar}{\\ensuremath{{\\rm M}_{\\star}}}\n    \\providecommand{\\lstar}{\\ensuremath{{\\rm L}_{\\star}}}\n    \\providecommand{\\rsun}{\\ensuremath{{\\rm R}_{\\odot}}}\n    \\providecommand{\\msun}{\\ensuremath{{\\rm M}_{\\odot}}}\n    \\providecommand{\\lsun}{\\ensuremath{{\\rm L}_{\\odot}}}\n    \\providecommand{\\mpkep}{\\ensuremath{0.315 \\pm 0.027 }}\n    \\providecommand{\\rpkep}{\\ensuremath{0.847 \\pm 0.013 }}\n    \\providecommand{\\mskep}{\\ensuremath{1.049_{-0.029}^{+0.021} }}\n    \\providecommand{\\rskep}{\\ensuremath{1.085 \\pm 0.010 }}\n    \\providecommand{\\per}{\\ensuremath{14.893291 \\pm 0.000025 }}\n    \\providecommand{\\ecc}{\\ensuremath{0.478 \\pm 0.026 }}\n    \\providecommand{\\sma}{\\ensuremath{0.1204_{-0.0011}^{0.0008} }}\n    \\providecommand{\\plname}{EPIC~249451861b}\n    \\providecommand{\\stname}{EPIC~249451861}\n    \\providecommand{\\rhopl}{\\ensuremath{{\\rm \\rho_P}}}\n    \\providecommand{\\rhopkep}{\\ensuremath{1.154 \\pm 0.045 }}\n    \\providecommand{\\gccm}{\\ensuremath{\\mathrm{g}\\,\\mathrm{cm}^{-3}}}\\graphicspath{{./}{figures/}}\n    \n    **** From Heidelberg: True\n    \n    \\hl{Andr\u00e9s Jord\u00e1n}, et al.; incl. \\hl{N\u00e9stor Espinoza}, \\hl{Thomas Henning}, \\hl{Markus Rabus}, \\hl{Paula Sarkis}\n    PDF postage: 1809.08879.pdf\n    [arXiv:1809.08904]:  Influence of metallicity on the near-surface effect affecting  oscillation frequencies\n    \tL. Manchon, K. Belkacem, R. Samadi, T. Sonoi, J. P. C. Marques, \\hl{H.-G. Ludwig}, E. Caffau\n    extracting tarball...\n    *** Found macros and definitions in the header: \n    \n    \n    **** From Heidelberg: False\n    \n    *** print_tb\n      File \"/home/jovyan/mpia.py\", line 160, in main\n        raise RuntimeError('Not an institute paper')\n    Not an institute paper \n    \n    [arXiv:1806.02981]:  Observational constraint on the dark energy scalar field\n    \t\\hl{Ming-Jian Zhang}, Hong Li\n    extracting tarball...\n    *** Found macros and definitions in the header: \n    \\def\\bea{\\begin{eqnarray}}\n    \\def\\eea{\\end{eqnarray}}\n    \\def\\be{\\begin{equation}}\n    \\def\\ee{\\end{equation}}\n    \n    **** From Heidelberg: False\n    \n    *** print_tb\n      File \"/home/jovyan/mpia.py\", line 160, in main\n        raise RuntimeError('Not an institute paper')\n    Not an institute paper \n    \n    [arXiv:1809.08969]:  Experimental results from the ST7 mission on LISA Pathfinder\n    \tG Anderson, J Anderson, M Anderson, G Aveni, D Bame, P Barela, K Blackman, A Carmain, L Chen, M Cherng, S Clark, M Connally, W Connolly, D Conroy, M Cooper, C Cutler, J D'Agostino, N Demmons, E Dorantes, C Dunn, M Duran, E Ehrbar, J Evans, J Fernandez, G Franklin, M Girard, J Gorelik, V Hruby, O Hsu, D Jackson, S Javidnia, D Kern, M Knopp, R Kolasinski, C Kuo, T Le, I Li, O Liepack, A Littlefield, P Maghami, S Malik, L Markley, \\hl{R Martin}, C Marrese-Reading, J Mehta, J Mennela, D Miller, D Nguyen, J O'Donnell, R Parikh, G Plett, T Ramsey, T Randolph, S Rhodes, A Romero-Wolf, T Roy, A Ruiz, H Shaw, J Slutsky, D Spence, J Stocky, J Tallon, I Thorpe, W Tolman, H Umfress, R Valencia, C Valerio, W Warner, J Wellman, P Willis, J Ziemer, J Zwahlen, M Armano, H Audley, J Baird, P Binetruy, ,  et al. (72 additional authors not shown)\n    extracting tarball...\n    *** Found macros and definitions in the header: \n    \\providecommand{\\subf}[2]{  {\\small\\begin{tabular}[t]{@{}c@{}}\n    \\providecommand{\\red}[1]{\\textcolor{red}{\\bf #1}}\n    \\providecommand{\\blue}[1]{\\textcolor{blue}{\\bf #1}}\n    \\providecommand{\\private}[1]{}\n    \\providecommand{\\braket}[2]{\\left\\langle#1\\,|\\,#2\\,\\right\\rangle}  \n    \\providecommand{\\expec}[1]{\\langle#1\\rangle}  \n    \\providecommand{\\be}{\\begin{equation}}\n    \\providecommand{\\ee}{\\end{equation}}\n    \\providecommand{\\bea}{\\begin{eqnarray}}\n    \\providecommand{\\eea}{\\end{eqnarray}}\n    \\providecommand{\\bdm}{\\begin{displaymath}}\n    \\providecommand{\\edm}{\\end{displaymath}}\n    \\providecommand{\\drm}{{\\rm d}}\\def\\lesssim{\\mathrel{\\hbox{\\rlap{\\hbox{\\lower4pt\\hbox{$\\sim$}}}\\hbox{$<$}}}}\n    \\def\\gtrsim{\\mathrel{\\hbox{\\rlap{\\hbox{\\lower4pt\\hbox{$\\sim$}}}\\hbox{$>$}}}}\n    \\def\\cos{\\rm cos}\n    \\def\\sin{\\rm sin}\n    \n    **** From Heidelberg: False\n    \n    *** print_tb\n      File \"/home/jovyan/mpia.py\", line 160, in main\n        raise RuntimeError('Not an institute paper')\n    Not an institute paper \n    \n    [arXiv:1809.09009]:  Plausible home stars of the interstellar object 'Oumuamua found in Gaia  DR2\n    \t\\hl{C.A.L. Bailer-Jones},  (MPIA Heidelberg), , D. Farnocchia,  (JPL), , K.J. Meech,  (Uni. Hawai'i), , R. Brasser,  (Tokyo Institute of Technology), , M. Micheli,  (ESA SSA-NEO Coordination Centre), , S. Chakrabarti,  (Rochester Institute of Technology), , M.W. Buie,  (Southwest Research Institute), , O.R. Hainaut,  (ESO)\n    extracting tarball...\n    *** Found document inclusions \n          input command:  figures/cands41plushome4_encounters\n    *** Found macros and definitions in the header: \n    \\providecommand{\\deriv}{\\ensuremath{\\mathrm{d}}}\n    \\providecommand{\\given}{\\ensuremath{\\hspace{0.05em}\\mid\\hspace{0.05em}}}\n    \\providecommand{\\okina}{`}\n    \\providecommand{\\uone}{1I/2017~U1}\n    \\providecommand{\\oum}{{{\\okina}Oumuamua}}\n    \\providecommand{\\Hawaii}{Hawai{\\okina}i}\n    \\providecommand{\\rainf}{\\ensuremath{\\ra_\\infty}}\n    \\providecommand{\\decinf}{\\ensuremath{\\dec_\\infty}}\n    \\providecommand{\\vinf}{\\ensuremath{v_\\infty}}\n    \\providecommand{\\candsaa}{2\\,k=2}\n    \\providecommand{\\candsbb}{3\\,k=2}\n    \\providecommand{\\candscc}{3\\,k=1}\n    \\providecommand{\\candsdd}{7d}\n    \\providecommand{\\candsee}{7e}\n    \\providecommand{\\candsff}{7c}\n    \\providecommand{\\gaia}{Gaia}\n    \\providecommand{\\gdr}[1]{Gaia\\,DR{#1}}\n    \\providecommand{\\gmag}{\\ensuremath{G}}\n    \\providecommand{\\mg}{M$_\\gmag$}\n    \\providecommand{\\bprp}{BP-RP}\n    \\providecommand{\\teff}{\\ensuremath{T_{\\rm eff}}}\n    \\providecommand{\\tenc}{\\ensuremath{t_{\\rm enc}}}\n    \\providecommand{\\denc}{\\ensuremath{d_{\\rm enc}}}\n    \\providecommand{\\venc}{\\ensuremath{v_{\\rm enc}}}\n    \\providecommand{\\tenclma}{\\ensuremath{t_{\\rm enc}^{\\rm lma}}}\n    \\providecommand{\\denclma}{\\ensuremath{d_{\\rm enc}^{\\rm lma}}}\n    \\providecommand{\\venclma}{\\ensuremath{v_{\\rm enc}^{\\rm lma}}}\n    \\providecommand{\\tencmed}{\\ensuremath{t_{\\rm enc}^{\\rm med}}}\n    \\providecommand{\\dencmed}{\\ensuremath{d_{\\rm enc}^{\\rm med}}}\n    \\providecommand{\\vencmed}{\\ensuremath{v_{\\rm enc}^{\\rm med}}}\n    \\providecommand{\\ra}{\\ensuremath{\\alpha}}\n    \\providecommand{\\dec}{\\ensuremath{\\delta}}\n    \\providecommand{\\pmra}{\\ensuremath{\\mu_{\\ra\\ast}}}\n    \\providecommand{\\parallax}{\\ensuremath{\\varpi}}\n    \\providecommand{\\parzp}{\\ensuremath{\\varpi_{\\rm zp}}}\n    \\providecommand{\\sigparallax}{\\ensuremath{\\sigma_{\\varpi}}}\n    \\providecommand{\\pmdec}{\\ensuremath{\\mu_\\dec}}\n    \\providecommand{\\propm}{\\ensuremath{\\mu}}\n    \\providecommand{\\vx}{\\ensuremath{v_x}}\n    \\providecommand{\\vy}{\\ensuremath{v_y}}\n    \\providecommand{\\vz}{\\ensuremath{v_z}}\n    \\providecommand{\\sigmavx}{\\ensuremath{\\sigma(\\vx)}}\n    \\providecommand{\\sigmavy}{\\ensuremath{\\sigma(\\vy)}}\n    \\providecommand{\\sigmavz}{\\ensuremath{\\sigma(\\vz)}}\n    \\providecommand{\\corvxvy}{\\ensuremath{\\rho(\\vx, \\vy)}}\n    \\providecommand{\\corvxvz}{\\ensuremath{\\rho(\\vx, \\vz)}}\n    \\providecommand{\\corvyvz}{\\ensuremath{\\rho(\\vy, \\vz)}}\n    \\providecommand{\\vr}{\\ensuremath{v_r}} \n    \\providecommand{\\sigvr}{\\ensuremath{\\sigma(\\vr)}}\n    \\providecommand{\\vtan}{\\ensuremath{v_T}}\n    \\providecommand{\\rsol}{\\ensuremath{r_\\odot}}\n    \\providecommand{\\zsol}{\\ensuremath{z_\\odot}}\n    \\providecommand{\\glon}{\\ensuremath{l}}\n    \\providecommand{\\glat}{\\ensuremath{b}}\n    \\providecommand{\\rvec}{\\ensuremath{\\boldsymbol{r}}}\n    \\providecommand{\\vvec}{\\ensuremath{\\boldsymbol{v}}}\n    \\providecommand{\\kms}{\\ensuremath{\\textrm{km\\,s}^{-1}}}\n    \\providecommand{\\maspyr}{\\ensuremath{\\textrm{mas\\,yr}^{-1}}}\n    \\providecommand{\\msun}{\\ensuremath{M_\\odot}}\n    \\providecommand{\\degree}{\\ensuremath{^\\circ}}\n    \\providecommand{\\red}{\\textcolor{red}}\n    \\providecommand{\\blue}{\\textcolor{blue}}\\def\\myeol{\\\\}\n    \\definecolor{VeryDarkBlue}{RGB}{0,0,80}\n    \\definecolor{VeryDarkRed}{RGB}{90,0,00}\n    \n    **** From Heidelberg: True\n    \n    \\hl{C.A.L. Bailer-Jones}, et al.; incl. \n    PDF postage: 1809.09009.pdf\n    [arXiv:1809.09080]:  Detecting Water In the atmosphere of HR 8799 c with L-band High  Dispersion Spectroscopy Aided By Adaptive Optics\n    \t\\hl{Ji Wang}, Dimitri Mawet Jonathan J. Fortney, Callie Hood, Caroline V. Morley, Bjorn Benneke\n    extracting tarball...\n    multiple tex files\n    Found main document in:  (0, './tmp/ms.tex')\n    Found main document in:  ./tmp/ms.tex\n    0 ./tmp/ms.tex\n    Found main document in:  ./tmp/ms.tex\n    *** Found document inclusions \n          input command:  obs_summary\n          input command:  Telescope_Instrument\n          input command:  HR8799c\n          input command:  Simulation_results\n          input command:  Telescope_Instrument_Sun_Earth\n    *** print_tb\n      File \"/home/jovyan/app.py\", line 847, in _expand_auxilary_files\n        with open(directory + fname + '.tex', 'r', errors=\"surrogateescape\") as fauxilary:\n    [Errno 2] No such file or directory: './tmp/Telescope_Instrument_Sun_Earth.tex' \n    \n          input command:  Sun_Earth\n    *** print_tb\n      File \"/home/jovyan/app.py\", line 847, in _expand_auxilary_files\n        with open(directory + fname + '.tex', 'r', errors=\"surrogateescape\") as fauxilary:\n    [Errno 2] No such file or directory: './tmp/Sun_Earth.tex' \n    \n    *** Found macros and definitions in the header: \n    \\providecommand{\\totaltargets}{138 }\n    \\providecommand{\\totalplanets}{97 }\n    \\providecommand{\\totalmulti}{27 }\n    \\providecommand{\\detectstar}{42 } \n    \\providecommand{\\detectsys}{35 } \n    \\providecommand{\\rvstar}{22 }\n    \\providecommand{\\myaostar}{60 }\n    \\providecommand{\\myaopalomar}{68 }\n    \\providecommand{\\myaokeck}{5 }\n    \\providecommand{\\myaototal}{73 }\n    \\providecommand{\\myaototalno}{65 }\n    \\providecommand{\\myaonewstar}{29 }\n    \\providecommand{\\myaonewsys}{22 }\n    \\providecommand{\\myaonewcolor}{8 }\n    \\providecommand{\\myaomiss}{11 }\n    \\providecommand{\\multicolor}{21 }\n    \\providecommand{\\multicolorod}{6 }\n    \\providecommand{\\multicolorsubarc}{5 }\n    \\providecommand{\\singleall}{38 }\n    \\providecommand{\\singleK}{29 }\n    \\providecommand{\\starK}{51 }\n    \\providecommand{\\rhk}{\\mbox{$\\log R^\\prime_{\\rm HK}$}}\n    \\providecommand{\\vdag}{(v)^\\dagger}\\def\\au{\\mbox{au}}\n    \n    **** From Heidelberg: False\n    \n    *** print_tb\n      File \"/home/jovyan/mpia.py\", line 160, in main\n        raise RuntimeError('Not an institute paper')\n    Not an institute paper \n    \n     Issues =============================== \n    [arXiv:1809.08261] Jason J. Wang, Zhaohuan Zhu \n     Not an institute paper\n    [arXiv:1809.08301] Alex B. Walter \n     Not an institute paper\n    [arXiv:1809.08348] Eve J. Lee \n     Not an institute paper\n    [arXiv:1809.08499] Dong-Hong Wu, Rachel C. Zhang \n     Not an institute paper\n    [arXiv:1809.08501] Shiang-Yu Wang \n     Not an institute paper\n    [arXiv:1809.08739] Gang Wu \n     Not an institute paper\n    [arXiv:1809.08798] Jordy Bouwman \n     Not an institute paper\n    [arXiv:1809.08800] Jordy Bouwman \n     not a gzip file\n    [arXiv:1809.08904] H.-G. Ludwig \n     Not an institute paper\n    [arXiv:1806.02981] Ming-Jian Zhang \n     Not an institute paper\n    [arXiv:1809.08969] R Martin \n     Not an institute paper\n    [arXiv:1809.09080] Ji Wang \n     Not an institute paper\n     Matched Authors ====================== \n    [arXiv:1809.08236] Wel        Arjen van der Wel\n    [arXiv:1809.08236] Wu         Po-Feng Wu\n    [arXiv:1809.08236] Barisic    Ivana Barisic\n    [arXiv:1809.08236] Chauke     Priscilla Chauke\n    [arXiv:1809.08236] Houdt      Josha van Houdt\n    [arXiv:1809.08239] Pillepich  Annalisa Pillepich\n    [arXiv:1809.08241] Joshi      Gandhali Joshi\n    [arXiv:1809.08243] Gould      Andrew Gould\n    [arXiv:1809.08245] Martin     Nicolas Martin\n    [arXiv:1809.08261] Wang       Jason J. Wang\n    [arXiv:1809.08261] Zhu        Zhaohuan Zhu\n    [arXiv:1809.08301] Walter     Alex B. Walter\n    [arXiv:1809.08338] Soler      J. D. Soler\n    [arXiv:1809.08338] Beuther    H. Beuther\n    [arXiv:1809.08338] Rugel      M. Rugel\n    [arXiv:1809.08338] Wang       Y. Wang\n    [arXiv:1809.08338] Henning    Th. Henning\n    [arXiv:1809.08338] Kainulainen J. Kainulainen\n    [arXiv:1809.08338] Mottram    J. C. Mottram\n    [arXiv:1809.08348] Lee        Eve J. Lee\n    [arXiv:1809.08354] Feldt      M. Feldt\n    [arXiv:1809.08354] Cantalloube F. Cantalloube\n    [arXiv:1809.08354] Keppler    M. Keppler\n    [arXiv:1809.08354] Maire      A.-L. Maire\n    [arXiv:1809.08354] Mueller    A. Mueller\n    [arXiv:1809.08354] Samland    M. Samland\n    [arXiv:1809.08354] Henning    T. Henning\n    [arXiv:1809.08385] Henning    T. Henning\n    [arXiv:1809.08499] Wu         Dong-Hong Wu\n    [arXiv:1809.08499] Zhang      Rachel C. Zhang\n    [arXiv:1809.08501] Wang       Shiang-Yu Wang\n    [arXiv:1809.08739] Wu         Gang Wu\n    [arXiv:1809.08798] Bouwman    Jordy Bouwman\n    [arXiv:1809.08800] Bouwman    Jordy Bouwman\n    [arXiv:1809.08844] Avenhaus   Henning Avenhaus\n    [arXiv:1809.08844] Bertrang   Gesa H. -M. Bertrang\n    [arXiv:1809.08844] Schreiber  Matthias R. Schreiber\n    [arXiv:1809.08879] Jord\u00e1n     Andr\u00e9s Jord\u00e1n\n    [arXiv:1809.08879] Espinoza   N\u00e9stor Espinoza\n    [arXiv:1809.08879] Henning    Thomas Henning\n    [arXiv:1809.08879] Rabus      Markus Rabus\n    [arXiv:1809.08879] Sarkis     Paula Sarkis\n    [arXiv:1809.08904] Ludwig     H.-G. Ludwig\n    [arXiv:1806.02981] Zhang      Ming-Jian Zhang\n    [arXiv:1809.08969] Martin     R Martin\n    [arXiv:1809.09009] Bailer-Jones C.A.L. Bailer-Jones\n    [arXiv:1809.09080] Wang       Ji Wang\n     Compiled outputs ===================== \n    [arXiv:1809.08236] Arjen van der Wel, Po-Feng Wu, Ivana Barisic, Priscilla Chauke, Josha van Houdt\n    [arXiv:1809.08239] Annalisa Pillepich\n    [arXiv:1809.08241] Gandhali Joshi\n    [arXiv:1809.08243] Andrew Gould\n    [arXiv:1809.08245] Nicolas Martin\n    [arXiv:1809.08338] J. D. Soler, H. Beuther, M. Rugel, Y. Wang, Th. Henning, J. Kainulainen, J. C. Mottram\n    [arXiv:1809.08354] M. Feldt, F. Cantalloube, M. Keppler, A.-L. Maire, A. Mueller, M. Samland, T. Henning\n    [arXiv:1809.08385] T. Henning\n    [arXiv:1809.08844] Henning Avenhaus, Gesa H. -M. Bertrang, Matthias R. Schreiber\n    [arXiv:1809.08879] Andr\u00e9s Jord\u00e1n, N\u00e9stor Espinoza, Thomas Henning, Markus Rabus, Paula Sarkis\n    [arXiv:1809.09009] C.A.L. Bailer-Jones\n\n\n\n```python\n# Some current security measures prevent loading properly pdf previews.\n# Converting pdfs into pngs.\n\n!for f in `ls *pdf`; do echo ${f} && convert ${f} ${f}.png; done\n```\n\n    1809.08236.pdf\n    1809.08239.pdf\n    1809.08241.pdf\n\n\n\n```python\n# Display preview of the compiled outputs\n\nfrom IPython.display import IFrame, HTML\nfrom glob import glob\n\ncode = ''\nfor fname in glob('*.png'):\n    code += IFrame(fname, width=600, height=1000)._repr_html_()\n    \nHTML(code)\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "d0dbc4386c8b75bb95074898fccf5ce9aca56a56", "size": 48645, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Notebook.ipynb", "max_stars_repo_name": "amaliestokholm/arxiv_on_deck", "max_stars_repo_head_hexsha": "1b22923c50f846bfcf8c4691c2fee8621e890794", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-11-03T09:59:29.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-03T09:59:29.000Z", "max_issues_repo_path": "Notebook.ipynb", "max_issues_repo_name": "amaliestokholm/arxiv_on_deck", "max_issues_repo_head_hexsha": "1b22923c50f846bfcf8c4691c2fee8621e890794", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-08-25T10:03:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-25T10:03:37.000Z", "max_forks_repo_path": "Notebook.ipynb", "max_forks_repo_name": "amaliestokholm/arxiv_on_deck", "max_forks_repo_head_hexsha": "1b22923c50f846bfcf8c4691c2fee8621e890794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-07-30T15:05:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-16T19:01:39.000Z", "avg_line_length": 52.9325353645, "max_line_length": 853, "alphanum_fraction": 0.5524308768, "converted": true, "num_tokens": 13016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17553805637093017, "lm_q2_score": 0.027585283825644964, "lm_q1q2_score": 0.0048422671071941745}}
{"text": "```\npip install pennylane-cirq\n```\n\n    Requirement already satisfied: pennylane-cirq in /usr/local/lib/python3.6/dist-packages (0.11.0)\n    Requirement already satisfied: pennylane>=0.11 in /usr/local/lib/python3.6/dist-packages (from pennylane-cirq) (0.11.0)\n    Requirement already satisfied: cirq in /usr/local/lib/python3.6/dist-packages (from pennylane-cirq) (0.8.2)\n    Requirement already satisfied: toml in /usr/local/lib/python3.6/dist-packages (from pennylane>=0.11->pennylane-cirq) (0.10.1)\n    Requirement already satisfied: semantic-version==2.6 in /usr/local/lib/python3.6/dist-packages (from pennylane>=0.11->pennylane-cirq) (2.6.0)\n    Requirement already satisfied: autograd in /usr/local/lib/python3.6/dist-packages (from pennylane>=0.11->pennylane-cirq) (1.3)\n    Requirement already satisfied: appdirs in /usr/local/lib/python3.6/dist-packages (from pennylane>=0.11->pennylane-cirq) (1.4.4)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from pennylane>=0.11->pennylane-cirq) (1.18.5)\n    Requirement already satisfied: networkx in /usr/local/lib/python3.6/dist-packages (from pennylane>=0.11->pennylane-cirq) (2.5)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from pennylane>=0.11->pennylane-cirq) (1.4.1)\n    Requirement already satisfied: google-api-core[grpc]<2.0.0dev,>=1.14.0 in /usr/local/lib/python3.6/dist-packages (from cirq->pennylane-cirq) (1.16.0)\n    Requirement already satisfied: freezegun~=0.3.15 in /usr/local/lib/python3.6/dist-packages (from cirq->pennylane-cirq) (0.3.15)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.6/dist-packages (from cirq->pennylane-cirq) (3.7.4.3)\n    Requirement already satisfied: requests~=2.18 in /usr/local/lib/python3.6/dist-packages (from cirq->pennylane-cirq) (2.23.0)\n    Requirement already satisfied: sortedcontainers~=2.0 in /usr/local/lib/python3.6/dist-packages (from cirq->pennylane-cirq) (2.2.2)\n    Requirement already satisfied: matplotlib~=3.0 in /usr/local/lib/python3.6/dist-packages (from cirq->pennylane-cirq) (3.2.2)\n    Requirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from cirq->pennylane-cirq) (0.7)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from cirq->pennylane-cirq) (1.0.5)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.6/dist-packages (from cirq->pennylane-cirq) (1.6.2)\n    Requirement already satisfied: protobuf~=3.12.0 in /usr/local/lib/python3.6/dist-packages (from cirq->pennylane-cirq) (3.12.4)\n    Requirement already satisfied: future>=0.15.2 in /usr/local/lib/python3.6/dist-packages (from autograd->pennylane>=0.11->pennylane-cirq) (0.16.0)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx->pennylane>=0.11->pennylane-cirq) (4.4.2)\n    Requirement already satisfied: pytz in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq->pennylane-cirq) (2018.9)\n    Requirement already satisfied: setuptools>=34.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq->pennylane-cirq) (50.3.0)\n    Requirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq->pennylane-cirq) (1.15.0)\n    Requirement already satisfied: google-auth<2.0dev,>=0.4.0 in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq->pennylane-cirq) (1.17.2)\n    Requirement already satisfied: googleapis-common-protos<2.0dev,>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq->pennylane-cirq) (1.52.0)\n    Requirement already satisfied: grpcio<2.0dev,>=1.8.2; extra == \"grpc\" in /usr/local/lib/python3.6/dist-packages (from google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq->pennylane-cirq) (1.32.0)\n    Requirement already satisfied: python-dateutil!=2.0,>=1.0 in /usr/local/lib/python3.6/dist-packages (from freezegun~=0.3.15->cirq->pennylane-cirq) (2.8.1)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq->pennylane-cirq) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq->pennylane-cirq) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq->pennylane-cirq) (2020.6.20)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests~=2.18->cirq->pennylane-cirq) (3.0.4)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq->pennylane-cirq) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq->pennylane-cirq) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib~=3.0->cirq->pennylane-cirq) (1.2.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy->cirq->pennylane-cirq) (1.1.0)\n    Requirement already satisfied: rsa<5,>=3.1.4; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from google-auth<2.0dev,>=0.4.0->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq->pennylane-cirq) (4.6)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.6/dist-packages (from google-auth<2.0dev,>=0.4.0->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq->pennylane-cirq) (0.2.8)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth<2.0dev,>=0.4.0->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq->pennylane-cirq) (4.1.1)\n    Requirement already satisfied: pyasn1>=0.1.3 in /usr/local/lib/python3.6/dist-packages (from rsa<5,>=3.1.4; python_version >= \"3\"->google-auth<2.0dev,>=0.4.0->google-api-core[grpc]<2.0.0dev,>=1.14.0->cirq->pennylane-cirq) (0.4.8)\n\n\n\n```\nimport pennylane as qml\n```\n\n\n```\nfrom pennylane import numpy as np\nimport matplotlib.pyplot as plt\n```\n\n\n```\npip install qiskit -q\n```\n\n\n```\npip install qiskit -q --upgrade\n```\n\n\n```\npip install pennylane --upgrade\n```\n\n    Requirement already up-to-date: pennylane in /usr/local/lib/python3.6/dist-packages (0.11.0)\n    Requirement already satisfied, skipping upgrade: numpy in /usr/local/lib/python3.6/dist-packages (from pennylane) (1.18.5)\n    Requirement already satisfied, skipping upgrade: autograd in /usr/local/lib/python3.6/dist-packages (from pennylane) (1.3)\n    Requirement already satisfied, skipping upgrade: appdirs in /usr/local/lib/python3.6/dist-packages (from pennylane) (1.4.4)\n    Requirement already satisfied, skipping upgrade: semantic-version==2.6 in /usr/local/lib/python3.6/dist-packages (from pennylane) (2.6.0)\n    Requirement already satisfied, skipping upgrade: scipy in /usr/local/lib/python3.6/dist-packages (from pennylane) (1.4.1)\n    Requirement already satisfied, skipping upgrade: toml in /usr/local/lib/python3.6/dist-packages (from pennylane) (0.10.1)\n    Requirement already satisfied, skipping upgrade: networkx in /usr/local/lib/python3.6/dist-packages (from pennylane) (2.5)\n    Requirement already satisfied, skipping upgrade: future>=0.15.2 in /usr/local/lib/python3.6/dist-packages (from autograd->pennylane) (0.16.0)\n    Requirement already satisfied, skipping upgrade: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx->pennylane) (4.4.2)\n\n\n\n```\n\n```\n\n\n```\npip install pennylane-qiskit\n```\n\n    Requirement already satisfied: pennylane-qiskit in /usr/local/lib/python3.6/dist-packages (0.11.0)\n    Requirement already satisfied: networkx>=2.2; python_version > \"3.5\" in /usr/local/lib/python3.6/dist-packages (from pennylane-qiskit) (2.5)\n    Requirement already satisfied: pyscf<=1.7.2 in /usr/local/lib/python3.6/dist-packages (from pennylane-qiskit) (1.7.2)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from pennylane-qiskit) (1.18.5)\n    Requirement already satisfied: qiskit>=0.20 in /usr/local/lib/python3.6/dist-packages (from pennylane-qiskit) (0.21.0)\n    Requirement already satisfied: pennylane>=0.11.0 in /usr/local/lib/python3.6/dist-packages (from pennylane-qiskit) (0.11.0)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx>=2.2; python_version > \"3.5\"->pennylane-qiskit) (4.4.2)\n    Requirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from pyscf<=1.7.2->pennylane-qiskit) (2.10.0)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from pyscf<=1.7.2->pennylane-qiskit) (1.4.1)\n    Requirement already satisfied: qiskit-aqua==0.7.5 in /usr/local/lib/python3.6/dist-packages (from qiskit>=0.20->pennylane-qiskit) (0.7.5)\n    Requirement already satisfied: qiskit-aer==0.6.1 in /usr/local/lib/python3.6/dist-packages (from qiskit>=0.20->pennylane-qiskit) (0.6.1)\n    Requirement already satisfied: qiskit-ibmq-provider==0.9.0 in /usr/local/lib/python3.6/dist-packages (from qiskit>=0.20->pennylane-qiskit) (0.9.0)\n    Requirement already satisfied: qiskit-ignis==0.4.0 in /usr/local/lib/python3.6/dist-packages (from qiskit>=0.20->pennylane-qiskit) (0.4.0)\n    Requirement already satisfied: qiskit-terra==0.15.2 in /usr/local/lib/python3.6/dist-packages (from qiskit>=0.20->pennylane-qiskit) (0.15.2)\n    Requirement already satisfied: appdirs in /usr/local/lib/python3.6/dist-packages (from pennylane>=0.11.0->pennylane-qiskit) (1.4.4)\n    Requirement already satisfied: toml in /usr/local/lib/python3.6/dist-packages (from pennylane>=0.11.0->pennylane-qiskit) (0.10.1)\n    Requirement already satisfied: autograd in /usr/local/lib/python3.6/dist-packages (from pennylane>=0.11.0->pennylane-qiskit) (1.3)\n    Requirement already satisfied: semantic-version==2.6 in /usr/local/lib/python3.6/dist-packages (from pennylane>=0.11.0->pennylane-qiskit) (2.6.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from h5py->pyscf<=1.7.2->pennylane-qiskit) (1.15.0)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.5->qiskit>=0.20->pennylane-qiskit) (1.6.2)\n    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.5->qiskit>=0.20->pennylane-qiskit) (5.4.8)\n    Requirement already satisfied: quandl in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.5->qiskit>=0.20->pennylane-qiskit) (3.5.2)\n    Requirement already satisfied: fastdtw in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.5->qiskit>=0.20->pennylane-qiskit) (0.3.4)\n    Requirement already satisfied: scikit-learn>=0.20.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.5->qiskit>=0.20->pennylane-qiskit) (0.22.2.post1)\n    Requirement already satisfied: yfinance in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.5->qiskit>=0.20->pennylane-qiskit) (0.1.54)\n    Requirement already satisfied: dlx in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.5->qiskit>=0.20->pennylane-qiskit) (1.0.4)\n    Requirement already satisfied: docplex in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.5->qiskit>=0.20->pennylane-qiskit) (2.15.194)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.5->qiskit>=0.20->pennylane-qiskit) (50.3.0)\n    Requirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.5->qiskit>=0.20->pennylane-qiskit) (1.0.5)\n    Requirement already satisfied: cython>=0.27.1 in /usr/local/lib/python3.6/dist-packages (from qiskit-aer==0.6.1->qiskit>=0.20->pennylane-qiskit) (0.29.21)\n    Requirement already satisfied: pybind11>=2.4 in /usr/local/lib/python3.6/dist-packages (from qiskit-aer==0.6.1->qiskit>=0.20->pennylane-qiskit) (2.5.0)\n    Requirement already satisfied: nest-asyncio!=1.1.0,>=1.0.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.9.0->qiskit>=0.20->pennylane-qiskit) (1.4.0)\n    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.9.0->qiskit>=0.20->pennylane-qiskit) (1.24.3)\n    Requirement already satisfied: websockets<8,>=7; python_version <= \"3.6\" in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.9.0->qiskit>=0.20->pennylane-qiskit) (7.0)\n    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.9.0->qiskit>=0.20->pennylane-qiskit) (2.23.0)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.9.0->qiskit>=0.20->pennylane-qiskit) (2.8.1)\n    Requirement already satisfied: requests-ntlm>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.9.0->qiskit>=0.20->pennylane-qiskit) (1.1.0)\n    Requirement already satisfied: fastjsonschema>=2.10 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.15.2->qiskit>=0.20->pennylane-qiskit) (2.14.5)\n    Requirement already satisfied: ply>=3.10 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.15.2->qiskit>=0.20->pennylane-qiskit) (3.11)\n    Requirement already satisfied: contextvars>=2.4; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.15.2->qiskit>=0.20->pennylane-qiskit) (2.4)\n    Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.15.2->qiskit>=0.20->pennylane-qiskit) (2.6.0)\n    Requirement already satisfied: retworkx>=0.4.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.15.2->qiskit>=0.20->pennylane-qiskit) (0.5.0)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.15.2->qiskit>=0.20->pennylane-qiskit) (0.3.2)\n    Requirement already satisfied: python-constraint>=1.4 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.15.2->qiskit>=0.20->pennylane-qiskit) (1.4.0)\n    Requirement already satisfied: future>=0.15.2 in /usr/local/lib/python3.6/dist-packages (from autograd->pennylane>=0.11.0->pennylane-qiskit) (0.16.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy>=1.3->qiskit-aqua==0.7.5->qiskit>=0.20->pennylane-qiskit) (1.1.0)\n    Requirement already satisfied: inflection>=0.3.1 in /usr/local/lib/python3.6/dist-packages (from quandl->qiskit-aqua==0.7.5->qiskit>=0.20->pennylane-qiskit) (0.5.1)\n    Requirement already satisfied: more-itertools in /usr/local/lib/python3.6/dist-packages (from quandl->qiskit-aqua==0.7.5->qiskit>=0.20->pennylane-qiskit) (8.5.0)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn>=0.20.0->qiskit-aqua==0.7.5->qiskit>=0.20->pennylane-qiskit) (0.16.0)\n    Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.6/dist-packages (from yfinance->qiskit-aqua==0.7.5->qiskit>=0.20->pennylane-qiskit) (0.0.9)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas->qiskit-aqua==0.7.5->qiskit>=0.20->pennylane-qiskit) (2018.9)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.9.0->qiskit>=0.20->pennylane-qiskit) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.9.0->qiskit>=0.20->pennylane-qiskit) (2020.6.20)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.9.0->qiskit>=0.20->pennylane-qiskit) (3.0.4)\n    Requirement already satisfied: cryptography>=1.3 in /usr/local/lib/python3.6/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.9.0->qiskit>=0.20->pennylane-qiskit) (3.1.1)\n    Requirement already satisfied: ntlm-auth>=1.0.2 in /usr/local/lib/python3.6/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.9.0->qiskit>=0.20->pennylane-qiskit) (1.5.0)\n    Requirement already satisfied: immutables>=0.9 in /usr/local/lib/python3.6/dist-packages (from contextvars>=2.4; python_version < \"3.7\"->qiskit-terra==0.15.2->qiskit>=0.20->pennylane-qiskit) (0.14)\n    Requirement already satisfied: cffi!=1.11.3,>=1.8 in /usr/local/lib/python3.6/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.9.0->qiskit>=0.20->pennylane-qiskit) (1.14.2)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.6/dist-packages (from cffi!=1.11.3,>=1.8->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.9.0->qiskit>=0.20->pennylane-qiskit) (2.20)\n\n\n\n```\npip install autograd tensorflow>=1.13.2\n```\n\n\n```\nimport pennylane as qml\nqml.about()\n```\n\n    Name: PennyLane\n    Version: 0.11.0\n    Summary: PennyLane is a Python quantum machine learning library by Xanadu Inc.\n    Home-page: https://github.com/XanaduAI/pennylane\n    Author: None\n    Author-email: None\n    License: Apache License 2.0\n    Location: /usr/local/lib/python3.6/dist-packages\n    Requires: numpy, autograd, semantic-version, scipy, networkx, appdirs, toml\n    Required-by: PennyLane-qiskit, PennyLane-Cirq\n    Platform info:           Linux-4.19.112+-x86_64-with-Ubuntu-18.04-bionic\n    Python version:          3.6.9\n    Numpy version:           1.18.5\n    Scipy version:           1.4.1\n    Installed devices:\n    - default.gaussian (PennyLane-0.11.0)\n    - default.qubit (PennyLane-0.11.0)\n    - default.qubit.autograd (PennyLane-0.11.0)\n    - default.qubit.tf (PennyLane-0.11.0)\n    - default.tensor (PennyLane-0.11.0)\n    - default.tensor.tf (PennyLane-0.11.0)\n    - qiskit.aer (PennyLane-qiskit-0.11.0)\n    - qiskit.basicaer (PennyLane-qiskit-0.11.0)\n    - qiskit.ibmq (PennyLane-qiskit-0.11.0)\n    - cirq.mixedsimulator (PennyLane-Cirq-0.11.0)\n    - cirq.simulator (PennyLane-Cirq-0.11.0)\n\n\n\n```\ndev = qml.device(\"cirq.mixedsimulator\", wires=2)\n\n```\n\n\n```\nA1 = qml.PauliZ(0)\nA2 = qml.PauliX(0)\nB1 = qml.Hermitian(np.array([[1, 1], [1, -1]]) / np.sqrt(2), wires=1)\nB2 = qml.Hermitian(np.array([[1, -1], [-1, -1]]) / np.sqrt(2), wires=1)\nCHSH_observables = [A1 @ B1, A1 @ B2, A2 @ B1, A2 @ B2]\n\n```\n\n\n```\n# subcircuit for creating an entangled pair of qubits\ndef bell_pair():\n    qml.Hadamard(wires=0)\n    qml.CNOT(wires=[0, 1])\n\n```\n\n\n```\n# circuits for measuring each distinct observable\n@qml.qnode(dev)\ndef measure_A1B1():\n    bell_pair()\n    return qml.expval(A1 @ B1)\n\n@qml.qnode(dev)\ndef measure_A1B2():\n    bell_pair()\n    return qml.expval(A1 @ B2)\n\n@qml.qnode(dev)\ndef measure_A2B1():\n    bell_pair()\n    return qml.expval(A2 @ B1)\n\n@qml.qnode(dev)\ndef measure_A2B2():\n    bell_pair()\n    return qml.expval(A2 @ B2)\n\ncircuits = qml.QNodeCollection([measure_A1B1,\n                                measure_A1B2,\n                                measure_A2B1,\n                                measure_A2B2])\n```\n\n\n```\nexpvals = circuits()\n```\n\n\n```\nCHSH_expval = np.sum(expvals[:3]) - expvals[3]\nprint(CHSH_expval)\n```\n\n    2.828426718711853\n\n\n\n```\nfrom pennylane_cirq import ops as cirq_ops\n# Note that the 'Operation' op is a generic base class\n# from PennyLane core.\n# All other ops are provided by Cirq.\navailable_ops = [op for op in dir(cirq_ops) if not op.startswith('_')]\nprint(\"\\n\".join(available_ops))\n```\n\n    AmplitudeDamp\n    BitFlip\n    Depolarize\n    Operation\n    PhaseDamp\n    PhaseFlip\n\n\n\n```\nnoise_vals = np.linspace(0, 1, 25)\n\nCHSH_vals = []\nnoisy_expvals = []\n\nfor p in noise_vals:\n    # we overwrite the bell_pair() subcircuit to add\n    # extra noisy channels after the entangled state is created\n    def bell_pair():\n        qml.Hadamard(wires=0)\n        qml.CNOT(wires=[0, 1])\n        cirq_ops.BitFlip(p, wires=0)\n        cirq_ops.BitFlip(p, wires=1)\n    # measuring the circuits will now use the new noisy bell_pair() function\n    expvals = circuits()\n    noisy_expvals.append(expvals)\nnoisy_expvals = np.array(noisy_expvals)\nCHSH_expvals = np.sum(noisy_expvals[:,:3], axis=1) - noisy_expvals[:,3]\n\n# Plot the individual observables\nplt.plot(noise_vals, noisy_expvals[:, 0], 'D',\n         label = r\"$\\hat{A1}\\otimes \\hat{B1}$\", markersize=5)\nplt.plot(noise_vals, noisy_expvals[:, 1], 'x',\n         label = r\"$\\hat{A1}\\otimes \\hat{B2}$\", markersize=12)\nplt.plot(noise_vals, noisy_expvals[:, 2], '+',\n         label = r\"$\\hat{A2}\\otimes \\hat{B1}$\", markersize=10)\nplt.plot(noise_vals, noisy_expvals[:, 3], 'v',\n         label = r\"$\\hat{A2}\\otimes \\hat{B2}$\", markersize=10)\nplt.xlabel('Noise parameter')\nplt.ylabel(r'Expectation value $\\langle \\hat{A}_i\\otimes\\hat{B}_j\\rangle$')\nplt.legend()\nplt.show()\n```\n\n\n```\nplt.plot(noise_vals, CHSH_expvals, label=\"CHSH\")\nplt.plot(noise_vals, 2 * np.ones_like(noise_vals),\n         label=\"Quantum-classical boundary\")\nplt.xlabel('Noise parameter')\nplt.ylabel('CHSH Expectation value')\nplt.legend()\nplt.show()\n```\n\n\n```\n@qml.qnode(dev)\ndef circuit(gate_params, noise_param=0.0):\n    qml.RX(gate_params[0], wires=0)\n    qml.RY(gate_params[1], wires=0)\n    cirq_ops.Depolarize(noise_param, wires=0)\n    return qml.expval(qml.PauliZ(0))\n\ngate_pars = [0.54, 0.12]\nprint(\"Expectation value:\", circuit(gate_pars))\n```\n\n    Expectation value: 0.851540632545948\n\n\n\n```\nnoise_vals = np.linspace(0., 1., 20)\nexpvals = [circuit(gate_pars, noise_param=p) for p in noise_vals]\n\nplt.plot(noise_vals, expvals, label=\"Expectation value\")\nplt.plot(noise_vals, np.ones_like(noise_vals), '--', label=\"Highest possible\")\nplt.plot(noise_vals, -np.ones_like(noise_vals), '--', label=\"Lowest possible\")\nplt.ylabel(r\"Expectation value $\\langle \\hat{Z} \\rangle$\")\nplt.xlabel(r\"Noise strength $p$\")\nplt.legend()\nplt.show()\n```\n\n\n```\n# declare the cost functions to be optimized\ndef cost(x):\n    return circuit(x, noise_param=0.0)\n\ndef noisy_cost(x):\n    return circuit(x, noise_param=0.3)\n\n# initialize the optimizer\nopt = qml.GradientDescentOptimizer(stepsize=0.4)\n\n# set the number of steps\nsteps = 100\n# set the initial parameter values\ninit_params = np.array([0.011, 0.012])\nnoisy_circuit_params = init_params\nparams = init_params\n\nfor i in range(steps):\n    # update the circuit parameters\n    # we can optimize both in the same training loop\n    params = opt.step(cost, params)\n    noisy_circuit_params = opt.step(noisy_cost, noisy_circuit_params)\n\n    if (i + 1) % 5 == 0:\n        print(\"Step {:5d}. Cost: {: .7f}; Noisy Cost: {: .7f}\"\n              .format(i + 1,\n                      cost(params),\n                      noisy_cost(noisy_circuit_params)))\n\nprint(\"\\nOptimized rotation angles (noise-free case):\")\nprint(\"({: .7f}, {: .7f})\".format(*params))\nprint(\"Optimized rotation angles (noisy case):\")\nprint(\"({: .7f}, {: .7f})\".format(*noisy_circuit_params))\n```\n\n    Step     5. Cost:  0.9961779; Noisy Cost:  0.5993173\n    Step    10. Cost:  0.8974948; Noisy Cost:  0.5941737\n    Step    15. Cost:  0.1440492; Noisy Cost:  0.5527687\n    Step    20. Cost: -0.1536868; Noisy Cost:  0.3309180\n    Step    25. Cost: -0.9152617; Noisy Cost:  0.0470152\n    Step    30. Cost: -0.9994047; Noisy Cost: -0.0519407\n    Step    35. Cost: -0.9999964; Noisy Cost: -0.2980615\n    Step    40. Cost: -1.0000000; Noisy Cost: -0.5561487\n    Step    45. Cost: -1.0000000; Noisy Cost: -0.5969037\n    Step    50. Cost: -1.0000000; Noisy Cost: -0.5997996\n    Step    55. Cost: -1.0000000; Noisy Cost: -0.5999871\n    Step    60. Cost: -1.0000000; Noisy Cost: -0.5999991\n    Step    65. Cost: -1.0000000; Noisy Cost: -0.6000000\n    Step    70. Cost: -1.0000000; Noisy Cost: -0.6000000\n    Step    75. Cost: -1.0000000; Noisy Cost: -0.6000000\n    Step    80. Cost: -1.0000000; Noisy Cost: -0.6000000\n    Step    85. Cost: -1.0000000; Noisy Cost: -0.6000000\n    Step    90. Cost: -1.0000000; Noisy Cost: -0.6000000\n    Step    95. Cost: -1.0000000; Noisy Cost: -0.6000000\n    Step   100. Cost: -1.0000000; Noisy Cost: -0.6000000\n    \n    Optimized rotation angles (noise-free case):\n    ( 0.0000000,  3.1415926)\n    Optimized rotation angles (noisy case):\n    ( 0.0000000,  3.1415926)\n\n\n\n```\n\n```\n", "meta": {"hexsha": "4f7f8231110d1e35d76ae27043d1385734eae173", "size": 98565, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "produce0110.ipynb", "max_stars_repo_name": "AliMeer/QuantumEx", "max_stars_repo_head_hexsha": "be609d23d05fe3d3a925320648638162afa566a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "produce0110.ipynb", "max_issues_repo_name": "AliMeer/QuantumEx", "max_issues_repo_head_hexsha": "be609d23d05fe3d3a925320648638162afa566a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "produce0110.ipynb", "max_forks_repo_name": "AliMeer/QuantumEx", "max_forks_repo_head_hexsha": "be609d23d05fe3d3a925320648638162afa566a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 137.6606145251, "max_line_length": 21966, "alphanum_fraction": 0.8193476386, "converted": true, "num_tokens": 8525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1384617870138417, "lm_q2_score": 0.03461884257419397, "lm_q1q2_score": 0.00479338680717376}}
{"text": "\n\n<a href=\"https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcahiers-de-programmes&branch=master&subPath=Tutoriels/markdown.ipynb&depth=1\" target=\"_parent\"></a>\n\n# Composition avec Markdown\n\nCe cahier illustre l'utilisation de Markdown pour saisir des documents dans Jupyter. Apr\u00e8s avoir parcouru ce cahier, vous pourrez modifier le texte dans n'importe quel cahier. De plus, vous pourrez aider vos \u00e9tudiants \u00e0 \u00e9diter le texte de leurs propres cahiers.\n\n## Les \u00e9l\u00e9ments _les plus_ fondamentaux\n\nNotez que vous pouvez afficher le code source derri\u00e8re n'importe quelle cellule en double-cliquant dessus. Pour rendre ou r\u00e9ex\u00e9cuter la cellule, utilisez l'une des options suivantes:\n1. S\u00e9lectionnez `Cell` $\\rightarrow$ `Run Cells`\n2. Appuyez sur `Shift-Enter`\n3. Cliquez sur le bouton `Run` ci-dessus\n\n## Cr\u00e9ation et suppression de cellules Markdown\nLa premi\u00e8re \u00e9tape \u00e0 consid\u00e9rer consiste \u00e0 cr\u00e9er une nouvelle cellule pour la composition. Pour ce faire, pendant que cette cellule est s\u00e9lectionn\u00e9e, dans le menu en haut, cliquez sur le signe plus (+) situ\u00e9 \u00e0 c\u00f4t\u00e9 du bouton Enregistrer.\n\nUne fois que vous avez cr\u00e9\u00e9 la nouvelle cellule, vous obtiendrez une cellule vide de `Code`. Pour changer cette cellule en une cellule que vous pouvez utiliser pour la composition, s\u00e9lectionnez la cellule et, dans le menu d\u00e9roulant en haut, change `Code` $\\rightarrow$ `Markdown`. Cela change ce type de cellule en une cellule Markdown, et elle peut maintenant \u00eatre utilis\u00e9e pour la composition!\n\n\nL'\u00e9tape suivante consistera \u00e0 apprendre \u00e0 supprimer des cellules. S\u00e9lectionnez la cellule que vous avez convertie en une cellule Markdown. Pour supprimer cette cellule de votre cahier Jupyter, cliquez sur `Edit` $\\rightarrow$ `Delete Cells`. Si vous avez accidentellement supprim\u00e9 une cellule incorrecte, vous pouvez toujours la ramener en cliquant sur `Edit` $\\rightarrow$ `Undo Delete Cells`.\n\n## Cr\u00e9er des titres\n\nCr\u00e9er un gros titre en gras dans un cahier Jupyter avec Markdown est tr\u00e8s simple! Tout ce que vous avez \u00e0 faire est, sur une nouvelle ligne, tapez le signe di\u00e8se puis un espace. Apr\u00e8s l'espace, ajoutez votre titre. C'est si simple. En ajoutant des di\u00e8ses suppl\u00e9mentaires, vous cr\u00e9erez diff\u00e9rents niveaux de titre. La cellule ci-dessous est un texte non format\u00e9 d\u00e9montrant cela. Pour afficher la cellule rendue, dans le menu en haut, cliquez sur le menu d\u00e9roulant `Raw NBConvert` et s\u00e9lectionnez `Markdown`.\n# I am a level one title\n## I am a level two title\n### I am a level three title\n#### I am a level four title\n##### I am a level five title\n###### I am a level six title \n####### I would be a level seven title if such a thing existed\n\nIf  # isn't the first character, that line does not get rendered as a title. \nPour voir comment ces titres apparaissent dans le cahier Jupyter, s\u00e9lectionnez la cellule ci-dessus et, dans le menu en haut, s\u00e9lectionnez `Raw NBConvert` $\\rightarrow$ `Markdown`, puis appuyez sur `Ctrl + Enter` pour afficher la cellule. N'h\u00e9sitez pas \u00e0 cr\u00e9er une nouvelle cellule et \u00e0 jouer avec celles-ci ou \u00e0 modifier celle ci-dessus.\n\n## Cr\u00e9er des listes d\u00e9taill\u00e9es\nCr\u00e9er des listes en Markdown dans un cahier Jupyter est \u00e9galement simple! Pour ce faire, vous devez simplement commencer une nouvelle ligne et commencer \u00e0 compter. La syntaxe de Markdown est indiqu\u00e9e dans le code ci-dessous.\n\n#### Double-cliquer sur moi\n\n1. Ceci est le premier \u00e9l\u00e9ment d'une liste\n1. Ceci est le deuxi\u00e8me\n50. Notez que les chiffres que nous utilisons n'ont pas d'importance, une fois que la cellule est rendue\n\u00a0\u00a0\u00a0\u00a01. En appuyant sur la touche `Tab` on peut ajouter des sous-items\n\u00a0\u00a0\u00a0\u00a045. Les chiffres n'ont pas d'importance ici, non plus\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0- On peut ajouter plusieurs sous-listes\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0- Mais \u00e0 un moment donn\u00e9, cela commence \u00e0 devenir redondant\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0- Nous pouvons aussi remonter quelques niveaux d'imbrication en alignant le texte avec la ligne plus haute\n2346. En revenant \u00e0 l'emplacement original, nous quittons nos listes imbriqu\u00e9es\n23236235672456. Les chiffres n'ont vraiment pas d'importance.\n*En fait, vous pouvez abandonner les chiffres \u00e0 tout moment.\n1. Ou recommencez \u00e0 compter\n\u00a0\u00a0\u00a0\u00a0\n\n- Nous n'avons pas non plus besoin de chiffres si nous ne voulons pas!\n    * Nous avons beaucoup d'options\n-Notez comment si nous ne mettons pas d'espace entre le tiret et le premier terme, cela ne devient pas un nouvel \u00e9l\u00e9ment dans la liste!\n\n---\n### Exercice 1\n1. Dans la cellule ci-dessus, essayez de corriger la derni\u00e8re ligne afin que le dernier \u00e9l\u00e9ment de la liste soit correctement mis en forme une fois rendu.\n2. Cr\u00e9ez une nouvelle cellule ci-dessous, ajoutez un titre et une liste ordonn\u00e9e de vos cinq fruits pr\u00e9f\u00e9r\u00e9s.\n---\n\n## Liens\nVous pouvez ajouter des hyperliens aux pages Web o\u00f9 vous voulez, directement dans le texte. La syntaxe est la suivante\n```markdown\n[texte que vous souhaitez afficher](lien vers un fichier ou une page URL)\n```\nChangez la cellule ci-dessous \u00e0 Markdown, l'ex\u00e9cuter et voir o\u00f9 le lien vous m\u00e8ne!\n[ceci est le texte qui devient l'hyperlien](https://media.giphy.com/media/Vs44a88Dvbnkk/giphy.gif)\n## Images / gifs\nLes images et les gifs peuvent \u00eatre int\u00e9gr\u00e9s dans une cellule Markdown de mani\u00e8re presque identique \u00e0 celle d\u2019un hyperlien. Pour afficher l'image, ajoutez un point d'exclamation \u00e0 la commande, comme illustr\u00e9 ci-dessous.\n```markdown\n\n```\nafficherait une image / gif. Il peut s'agir d'un lien URL vers une image ou d'un lien enregistr\u00e9 sur le concentrateur / localement. Modifiez la cellule ci-dessous \u00e0 Markdown et l'ex\u00e9cuter pour la voir en action, ou m\u00eame int\u00e9grer vos propres images dans ce cahier.\n\n---\n### Exercice 2\n1. Dans une nouvelle cellule ci-dessous, incorporez une image d'un chat.\n2. Dans la m\u00eame cellule, ajoutez un lien hypertexte sous l'image qui est li\u00e9e \u00e0 l'image originale.\n3. Modifiez le texte affich\u00e9 dans le lien hypertexte pour dire \"Kitty Kitty\".\n---\n\n# Citations bloc\nLes citations bloc sont un moyen d'indenter du texte / des images avec une barre grise afin de les distinguer du texte principal. Cela se fait tout simplement en ajoutant un `>` au d\u00e9but d'une ligne. Changez la cellule ci-dessous \u00e0 Markdown pour voir quelques exemples\n> Ceci est un exemple de citation bloc. Vous pouvez taper aussi longtemps que vous le souhaitez et tout le texte r\u00e9sultant sera \u00e0 droite de la barre grise verticale.\n\nVous pouvez \u00e9galement utiliser des citations bloc pour formater facilement des images avec des l\u00e9gendes!\n\n>\n>\n> Maintenant, nous pouvons inclure une l\u00e9gende pour les images. C'est bien parce que l'image se distingue maintenant du texte principal. Cela facilite l\u2019inclusion d\u2019images sans interrompre le r\u00e9cit que vous avez cr\u00e9\u00e9. Remarquez comment j'ai inclus un `>` vide sous l'image. C'est pourquoi l'espacement de ce texte se pr\u00e9sente bien en dessous. Essayez de le retirer et voyez ce qui se passe.\n## Les tableaux\n\nOn peut \u00e9galement cr\u00e9er des tableaux de donn\u00e9es dans Markdown. Cependant, le faire manuellement n'est souvent pas le plus pratique. Pour les grands tableaux, nous vous recommandons d'utiliser des outils en ligne (tels que [ici](https://jakebathman.github.io/Markdown-Table-Generator/)) o\u00f9 vous pouvez copier-coller des tableaux Excel ou des fichiers CSV. Cela produira alors une syntaxe pour rendre correctement ces tableaux. Pour les petits tableaux, il est assez facile de taper les v\u00f4tres. Voir la cellule ci-dessous.\n| Ceci est le premier nom de colonne | Deuxi\u00e8me colonne | Troisi\u00e8me |\n|--- | --- | ------------- |\n|Notez que rien n'est align\u00e9 lorsque nous le tapons | Mais \u00e7a a l'air bien quand rendu | C'est vraiment pratique!\n|les lignes courtes sont bien aussi | nombres? | 343453 |\n|symboles | `oui` | $\\int e^{-x^2} dx$ |\n|notez \u00e9galement que le nombre de tirets dans la deuxi\u00e8me ligne n'a pas d'importance | il faut juste qu'il y en ait au moins trois | les autres ne sont vraiment que pour vous, de donner au pr\u00e9-rendu une belle apparence |\nLa syntaxe de base de la table est la suivante:\n```markdown\n|initialiser|vos|noms de|colonnes|\n|-----------|---|-------|---------| <-cette ligne met en place les en-t\u00eates, n\u00e9cessite au moins trois `---` chaque ligne\n|   donn\u00e9es |donn\u00e9es|donn\u00e9es|donn\u00e9es| <- n'importe quel type de donn\u00e9es en texte. N'h\u00e9sitez pas \u00e0 m\u00e9langer aussi!\n|  nombres  | texte | texte | donn\u00e9es   <- vous n'avez pas besoin d'inclure le \"pipe\" le plus \u00e0 droite si vous ne voulez pas\n```\n\nLa syntaxe peut \u00eatre consid\u00e9r\u00e9e comme la mani\u00e8re d\u2019essayer d\u2019\u00e9crire directement un tableau \u00e0 l\u2019aide de symboles sur votre clavier. Jouez avec la table dans la cellule ci-dessus ou cr\u00e9ez une nouvelle cellule et essayez de cr\u00e9er le v\u00f4tre! Vous pourriez en mettre un dans cette cellule et mettre un tableau ici. Double-cliquez n'importe o\u00f9 sur cette cellule pour ouvrir le mode d'\u00e9dition.\n\n---\n### Exercices 3\n1. En utilisant des exemplaires de cahiers, les enseignants peuvent aimer ou ne pas aimer les diff\u00e9rentes sections de l\u2019\u00e9chantillon fourni. Heureusement, il est facile de faire ces changements mineurs dans les cahiers. Dans les deux cellules ci-dessous:\n\u00a0\u00a0\u00a0\u00a0* supprimez la deuxi\u00e8me cellule car vous n'en aurez pas besoin dans votre le\u00e7on\n    * supprimez le dernier paragraphe de la premi\u00e8re cellule\n\u00a0\u00a0\u00a0\u00a0* changez la date dans le premier paragraphe\n2. Dans la premi\u00e8re cellule ci-dessous, prenez la liste ordonn\u00e9e de la citation bloc.\n\n---\n\n> ## Propri\u00e9t\u00e9s des nombres al\u00e9atoires\n>\n> 22 mai 2018\n> Supposons que vous ayez une suite de nombres al\u00e9atoires $N$ $\\{R\\}$ avec le contenu $\\{r_1, r_2, ... , r_N\\}$ o\u00f9 chaque \u00e9l\u00e9ment $r_i$ est un nombre al\u00e9atoire. Quelle sorte de propri\u00e9t\u00e9s cette s\u00e9quence de nombres devrait-elle avoir? S'il s'agit vraiment d'une s\u00e9quence de nombres al\u00e9atoires, il _doit_ satisfaire les propri\u00e9t\u00e9s suivantes, que nous expliquerons plus en d\u00e9tail:\n>\n> 1. Tirer n'importe quel $r_i$ est \u00e9galement probable et ind\u00e9pendant.\n> 2. La s\u00e9quence de nombres al\u00e9atoires est uniform\u00e9ment distribu\u00e9e.\n>\n> \"Tirer une valeur\" dans cette port\u00e9e signifie que nous s\u00e9lectionnons un nombre de notre s\u00e9quence de nombres al\u00e9atoires, mais ne le retirons pas de la s\u00e9quence (la s\u00e9quence reste inchang\u00e9e, nous \"observons\" simplement le nombre al\u00e9atoire).\nRegardons ces deux propri\u00e9t\u00e9s plus en d\u00e9tail.\n\n> ### Toutes les valeurs sont \u00e9galement probables et ind\u00e9pendantes\n>\n> Cela signifie que si vous deviez s\u00e9lectionner (mais pas retirer) un nombre de votre s\u00e9quence de nombres al\u00e9atoires $\\{r_1, r_2, ... , r_N\\}$ au hasard, la probabilit\u00e9 de tirer l'un de ces nombres est\n\\begin{equation}\np(r_i) = \\frac{1}{N}\n\\end{equation}\no\u00f9 $p(r_i)$ est la probabilit\u00e9 de s\u00e9lectionner un nombre $r_i$. Cette probabilit\u00e9 est identique pour tous les nombres de votre ensemble. Plus explicitement:\n\\begin{equation}\np(r_1) = p(r_2) = ... = p(r_N) = \\frac{1}{N}\n\\end{equation}\n>\n> La propri\u00e9t\u00e9 d'ind\u00e9pendance signifie que si vous tirer un nombre de l'ensemble, cela n'affecte pas la probabilit\u00e9 de tirer d'autres nombres, ni m\u00eame lui-m\u00eame ult\u00e9rieurement. C'est parce que la s\u00e9quence reste inchang\u00e9e apr\u00e8s avoir tir\u00e9 (observez) un nombre. \n\n[](https://github.com/callysto/curriculum-notebooks/blob/master/LICENSE.md)\n", "meta": {"hexsha": "b60dfe9686905a4d69b15d67d9595323d27e6865", "size": 15813, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Tutoriels/markdown.ipynb", "max_stars_repo_name": "callysto/cahiers-de-programmes", "max_stars_repo_head_hexsha": "456045bfe7d28395ff31a4b0b89fe86260765605", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tutoriels/markdown.ipynb", "max_issues_repo_name": "callysto/cahiers-de-programmes", "max_issues_repo_head_hexsha": "456045bfe7d28395ff31a4b0b89fe86260765605", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tutoriels/markdown.ipynb", "max_forks_repo_name": "callysto/cahiers-de-programmes", "max_forks_repo_head_hexsha": "456045bfe7d28395ff31a4b0b89fe86260765605", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2941176471, "max_line_length": 526, "alphanum_fraction": 0.6547144754, "converted": true, "num_tokens": 3062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.021948252115486948, "lm_q2_score": 0.2173375159776302, "lm_q1q2_score": 0.0047701785948307}}
{"text": "<a href=\"https://colab.research.google.com/github/JacobFV/AI-Resources/blob/master/NMRL.ipynb\" target=\"_parent\"></a>\n\n## THIS IS JUST BRAINSTORMING\n\n### Copyright &copy; 2020 Jacob Valdez\n\nunder the [MIT License](https://opensource.org/licenses/MIT)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n# Nodal Reinforcement Learning\n\nAbstract and pictures/videos *en simulo*. Maybe also simplified diagrams of AGI node and network.\n\n# Introduction\n\nAGI-0 rests on the hypotheses that:\n- encoding the principles of [free energy minimization](https://en.wikipedia.org/wiki/Free_energy_principle) in a multilayer hidden Markov chain prediction unit will enable unsupervised, open-ended learning\n- competitive ensembles of prediction units will succeed in overcoming the [no free lunch theorom](https://en.wikipedia.org/wiki/No_free_lunch_theorem)\n- ~~supervised multiagent simulations will enable learning mirroring features that transfer successfully to humans~~\n- embedded natural language self examination objectives will automatically align agent behavior with encoded human values from environment reinforcement without any supervised reward administration\n- **the realization of these hypotheses will achieve artificial general intelligence**\n\nDiscuss my theory of hierarchial conditioning here\n\nEach child only provides additional conditioning context but is not required for a module to produce an output. (Kind of like how [conditioning gpt-2 with a longer input sentence gives you more control over its output](https://colab.research.google.com/drive/12_EzHGVE8ZnJ-MA9W_8tQuP6xHpWb1X3?usp=sharing))\n\n# Methodology\n\n$\\newcommand{\\ab}{\\mathcal{A}}$\n$\\newcommand{\\pr}{\\mathcal{P}}$\n$\\newcommand{\\pol}{\\mathcal{\\pi}}$\n$\\newcommand{\\o}[1][t]{{o}_{#1}}$\n$\\newcommand{\\otrue}[1][t]{{o}_{#1}^{true}}$\n$\\newcommand{\\opast}[1][t-T_o:t]{{o}_{#1}}$\n$\\newcommand{\\otruepast}[1][t-T_o:t]{{o}_{#1}^{true}}$\n$\\newcommand{\\s}[1][t]{{s}_{#1}}$\n$\\newcommand{\\spred}[1][t+1]{{s}_{#1}^{pred}}$\n$\\newcommand{\\oimagpast}[1][\\tau-T_o:\\tau]{{o}_{#1}^{imag}}$\n$\\newcommand{\\oimag}[1][\\tau]{{o}_{#1}^{imag}}$\n$\\newcommand{\\simag}[1][\\tau]{{s}_{#1}^{imag}}$\n$\\newcommand{\\spredimag}[1][\\tau+p]{{s}_{#1}^{pred,imag}}$\n$\\newcommand{\\stargetimag}[1][\\tau+p]{{s}_{#1}^{*,imag}}$\n$\\newcommand{\\starget}[1][t+1]{{s}_{#1}^*}$\n$\\newcommand{\\otarget}[1][t+1]{{o}_{#1}^*}$\n$\\newcommand{\\sblind}[1][\\tau+p]{{s}_{#1}^{blind}}$\n$\\newcommand{\\pe}[1][t]{pe_{#1}}$\n$\\newcommand{\\n}[1][i]{n_{#1}}$\n$\\newcommand{\\nparent}{\\mathcal{N_{pa}}}$\n$\\newcommand{\\nchildren}{\\mathcal{N_{ch}}}$\n$\\newcommand{\\U}{\\mathcal{U}}$\n$\\newcommand{\\Ex}[1][ ]{ \\underset{#1}{ \\mathbb{E} } }$\n$ \\newcommand{\\vect}[1]{\\boldsymbol{#1}} $\n$\\def\\falert{f_{alert}}$\n$\\def\\NN{N\\kern-0.2em N}$\n$\\def\\DS{\\mathcal{D}}$\n$\\def\\IE{\\mathcal{E}_I}$\n$\\def\\CER{\\mathcal{C}}$\n$\\newcommand{norm}[1]{\\bigl\\lvert\\bigl\\rvert{#1}\\bigr\\lvert\\bigr\\rvert}$\n\n## Architecture\n\nNodal-RL operates by minimizing predictive entropy. It does this by decomposing the state space with a [structured probabblistic model](https://en.wikipedia.org/wiki/Graphical_model) into sensory, information, and actuator nodes. Each *information node* on the graph only models a subset of all information. The directed and potentially cyclic model $\\langle\\mathcal{N}\\kern-0.15em,\\mathcal{E}\\rangle$ may look like:\n\n <!-- https://mermaid-js.github.io/mermaid-live-editor/#/edit/eyJjb2RlIjoiZ3JhcGggTFJcbiAgUzAwW3BpeGVsc10gLS0-IFMwMSh2aXN1YWwgZmVhdHVyZXMpXG4gIFMwMSAtLT4gUDAoY29tcG9zaXRlIGZlYXR1cmVzKVxuXG4gIFMxMFthdWRpbyBzcGVjdHJvZ3JhcGhdIC0tPiBTMTEodG9rZW5zKVxuICBTMTEgLS0-IFAwKGNvbXBvc2l0ZSBmZWF0dXJlcylcblxuICBTMDEgLS0-IFNYMDEwXG4gIFMxMSAtLT4gU1gwMTBcbiAgU1gwMTAobmF0dXJhbCBsYW5ndWFnZSBJKSAtLT4gU1gwMTFcbiAgU1gwMTEobmF0dXJhbCBsYW5ndWFnZSBJSSkgLS0-IFAwXG5cbiAgUzIwW2FjdHVhdG9yIHNpZ25hbHNdIC0tPiBTMjEobW90aW9uIHByaW1pdGl2ZXMpXG4gIFMyMSAtLT4gUDAoY29tcG9zaXRlIGZlYXR1cmVzKVxuXG4gIFAwIC0tPiBQMDAoYWJzdHJhY3QgcGVyc3BlY3RpdmUgSSlcbiAgUDAgLS0-IFAwMShhYnN0cmFjdCBwZXJzcGVjdGl2ZSBJSSlcbiAgUDAgLS0-IFAwMihhYnN0cmFjdCBwZXJzcGVjdGl2ZSBJSUkpXG5cdFxuICBQMDAgLS0-IFAwMDAoYWJzdHJhY3QgcGVyc3BlY3RpdmUgSVYpXG4gIFAwMCAtLT4gUDAwMShhYnN0cmFjdCBwZXJzcGVjdGl2ZSBWKVxuICBQMDIgLS0-IFAwMDFcblxuICBQMDEgLS0-IFAwMDBcblxuICBQMDAwIC0tPiBQMCIsIm1lcm1haWQiOnsidGhlbWUiOiJkZWZhdWx0In0sInVwZGF0ZUVkaXRvciI6ZmFsc2V9 -->\n\nAbove, among many other partial models, is modeled the information that $\\n[tokens]$ and $\\n[visual\\ features]$ supply to $\\n[nat\\ lang\\ I]$, the information $\\n[nat\\ lang\\ I]$ supplies to $\\n[nat\\ lang\\ II]$, and the partial information $\\n[nat\\ lang\\ II]$ adds to a composite understanding of the world. This composite understanding is captured in the state variable $\\n[comp].\\s[ ]$. Instead of producing its state from directly observing sensory data, $\\n[comp]$ only observes its parent nodes' states $\\n[comp].\\o[ ]=\\{\\n[nat\\ lang\\ II].\\s[ ],\\n[motion\\ prim].\\s[ ],\\n[visual\\ features].\\s[ ]\\}$.\n\nAn information node $\\n$ attempts to build an internal model of its observed variables $P(\\o[t+p]|\\opast)$. It does this by first *abstracting* the information from its observable data trajectory into an internal *state* $\\s=\\ab(\\opast)$. It then attempts to model the trajectory of that internal state with a *predictor* function $\\spred=\\pr(\\s)$. Predictive error $D_{KL}(\\spred,\\s[t+1])$ and predictive uncertainty $H(\\spred)$ then become the objectives to cumulatively minimize.\n\nThe *policy* $\\pol$ specfies *target observations* $\\otarget$ that approach these objectives. Target observations belonging to a child layer influence their parent's *target state* (e.g.: $\\n[nat\\ lang\\ II].\\otarget \\stackrel{affects}{\\rightarrow} \\n[nat\\ lang\\ I].\\starget$). Since a node may have multiple children, the target state is detirmined by a $\\n[ch].w_{\\mathcal{Pa}_i}$ weighted mean of the node children's target observations $\\{\\n[ch].\\otarget\\ |\\ \\forall\\n[ch]\\in\\n\\smash{.}\\nchildren\\}$ concatenated with the node's own predicted state $\\n\\smash{.}\\spred$. Additionally, proabblistic certainty weighting, ($\\CER(x)=0=$ very indecisive) weakens the influence of vague target distributions.\n\n$\\text{weighted ave}(\\{\\langle w_{pred},\\spred\\rangle\\}\\cup\\{\\langle \\n[ch].w_{\\mathcal{Pa}_i}\\CER(\\n[ch].\\otarget), \\n[ch].\\otarget\\rangle\\ |\\ \\forall\\n[ch]\\in\\nchildren\\})$\n\nNodes do not compute updates simultaneously or even at the same frequency though. They are individually updated at periods of $\\n\\smash{.}p=\\n\\smash{.}f^{-1}$. As a result, $\\n[ch].\\otarget[t+\\n\\smash{.}p]$ may not exist. To avoid blocking, child node target observations are instead queried for the most recent existing record $\\n[ch].\\otarget[\\tau]\\ |\\ \\exists\\n[ch].\\otarget[\\tau];\\ \\tau=\\max [t-N_o:t+p];$ An exponential recency decay $e^{-\\n[ch].\\lambda(t+p-\\tau)}$ additionally weights the target observation. The target state is thus:\n\n$\\starget[t+p]=\\text{weighted ave}(\\{\\langle w_{pred},\\spred[t+p]\\rangle\\} \\cup \\{\\langle \\n[ch].w_{\\mathcal{Pa}_i}\\CER(\\n[ch].\\otarget[\\tau])\\times e^{-\\n[ch].\\lambda(t+p-\\tau)}, \\n[ch].\\otarget[\\tau]\\rangle\\ |\\ \\exists\\n[ch].\\otarget[\\tau];\\ \\tau=\\max [t-N_o:t+p];\\ \\forall\\n[ch]\\in\\nchildren\\})$\n\nTarget state in turn biases the target observation via the policy $\\otarget=\\pol(\\s,\\starget)$. Since the target state may be a weighted mean of several stochastic variables, child target observations with a high entropy will have less influence in the weighted mean distribution-even if its weight is large. The more certain (lower entropy) a target observation is, the greator influence it will have on its parent target state.\n\nThis makes sibling nodes form an implicit team. One node $\\n[abs\\ per\\ I]$ may have a very clear understanding of the dynamics of one subspace of the observation space $\\mathcal{O}_i\\subset\\mathcal{O}$, hence producing low entropy predictions and strong opinions on what $\\otarget[t+p]$ should be. At the same time, its sibling $\\n[abs\\ per\\ II]$ may not have knowledge of that domain and therefore produce highly irrational, entropic observation targets. The result of averaging the two nodes' target observations is a distribution with relatively little influence by $\\n[abs\\ per\\ II]$. Togethor, nodes form a network of experts each specializing in unique domains to give the agent open-ended intelligence.\n\n## Stochastic Models\n\nTo allow information nodes to produce multimodal and multivariate observation and state distributions, the following reparametrization trick is employed to layer input concatenated with a multidimensional uniform distribution:\n\n$\\vect{y}=\\sigma(W[\\vect{x};\\vect{\\zeta}]+b)\\qquad\\vect{\\zeta}\\thicksim\\{\\mathcal{U(0,1)}\\}^{N_\\zeta}$\n<!-- $y=\\sigma(\\zeta\\vect{w}_\\sigma\\cdot\\vect{x}+\\vect{w}_\\mu\\cdot\\vect{x}+b) \\qquad \\zeta\\thicksim\\mathcal{U}(0,1)$\n\nor for a dense layer:\n\n$\\vect{y}=\\sigma(\\vect{\\zeta}W_\\sigma\\vect{x}+\\vect{w}_\\mu\\cdot\\vect{x}+b) \\qquad \\zeta\\thicksim\\mathcal{U}(0,1)$ -->\n\nSince this design employs continuous distributions, certainty $\\CER$ is measured by the relative entropy of the uniform distribution with respect to a target distribution $P$:\n\n$\\CER(P)=-D_{KL}(\\mathcal{U}(a,b)||P)$\n\nThis above definition demands a definition of activation bounds $a$ and $b$ for each distribution. These are regularized distribution-wise by:\n\n$\\loss_{bounds}(x)=\\begin{cases}f(a-x)\\qquad&x\\lt a\\\\0\\qquad& a\\le x\\le b\\\\f(x-b)\\qquad& x\\gt b\\end{cases}$\n\nwith $f(x)=\\{x,x^2,x^n,e^x,\\dots\\}$ being any differentiable monotonically increasing function on $(0,\\infty)$.\n\nThe certainty of various distributions zero as they are more unpredictable and increases to above one as they become more certain of the likelihood of a random variable.\n\n## Dreaming\n\nNot all observations collected online are equally relevant to future tasks. Additionally, when observations add little information to an already highly unpredictable state trajectory, it becomes pointless to informatively utilize the next state prediction. In these situations, informations nodes maintain productivity by *dreaming*.\n\nDreaming makes a shift from closed to open loop control. It involves relying less on observed data and more on anticipated observations. It mixes the true observation $\\otrue$ with last timestep's target observation $\\otarget[t]$ by a nonlinear function $\\falert$ to produce the observed processed by all other functions:\n\n$\\o=\\falert\\otrue+(1-\\falert)\\otarget[t]$\n\nwhere $\\falert$ increases alertness when surprising, unexpected, or informative observations occur $\\falert\\propto I(\\otrue)$ and decreases alertness when predictability is low $\\falert\\propto (H(\\s[t-p]))^{-1}$. To ensure the transition to dreaming and back to alertness is not jittery, these factors are smoothed with a rolling average and transformed with $\\tanh$:\n\n$\\overline{\\underline{\\textbf{Algorithm:}\\ \\text{Percieved Observation }\\o}}$\n\n$1.\\ d_t^{ave}=d_t^{ave}+\\alpha_{d,1}\\frac{I(\\otrue)}{H(\\s[t-p])}$\n\n$2.\\ \\falert=\\tanh[\\alpha_{d,2}(d_t^{ave}-\\alpha_{d,3})]$\n\n$3.\\ \\mathbf{return}\\ \\o=\\falert\\otrue+(1-\\falert)\\otarget[t]$\n\nwhere $\\alpha_{d,1}\\lt1$ is small number that influences the rolling average latency, $\\alpha_{d,2}\\gt1$ is large and makes the transition from dream to alert state abrupt, and $\\alpha_{d,3}$ is the minimum average ratio of information to entropy that must be provided by observations for $\\n$ to pay attention to them.\n\nSince dreamed state trajectories will generally have a larger entropy than states based on true observations, dreaming node target observations have a correspondingly high entropy and generally do not compete with target observations from sibling nodes that are not dreaming.\n\n## Running\n\nInformation nodes join an asynchronously updating netowrk with sensory nodes and actuator nodes. Unless specified, variables are implied to belong to $\\n$ ($\\n.p=p$).\n\n### Sensory Nodes\n\nSensory and simply publish states:\n\n$\\overline{\\underline{\\textbf{Algorithm:}\\ \\text{Sensory Node }\\n{\\ Update}}}$\n\n$1.\\ \\s=\\text{get sensory data}$\n\n$6.\\ \\textbf{wait}\\ p\\ \\text{timesteps}$ \n\n$3.\\ \\textbf{repeat}$\n\n### Actuator Nodes\n\nActuator nodes attempts to fulfill their childrens' target observations. At the actuator level, distributions must finally be sampled into real numbers.\n\n$\\overline{\\underline{\\textbf{Algorithm:}\\ \\text{Actuator Node }\\n{\\ Update}}}$\n\n$1.\\ \\starget[t+p]=\\text{weighted ave}(\\{\\langle w_{pred},\\spred[t+p]\\rangle\\} \\cup \\{\\langle \\n[ch].w_{\\mathcal{Pa}_i}\\CER(\\n[ch].\\otarget[\\tau])\\times e^{-\\n[ch].\\lambda(t+p-\\tau)}, \\n[ch].\\otarget[\\tau]\\rangle\\ |\\ \\exists\\n[ch].\\otarget[\\tau];\\ \\tau=\\max [t-N_o:t+p];\\ \\forall\\n[ch]\\in\\nchildren\\})$\n\n$2.\\ \\text{execute } \\overset{\\small{N_s}}{\\Ex}[\\starget[t+p]] \\quad\\rhd\\text{execute weighted target state sampling }N_s\\text{ times}$\n\n$3.\\ \\textbf{wait}\\ p\\ \\text{timesteps}$\n\n$4.\\ \\s[t+p]=\\text{get actual result}$\n\n$5.\\ \\textbf{repeat}$\n\n### Information Nodes\n\nInformation nodes simulatenously engage in bottom-up processing and propagate top-down conditioning:\n\n$\\overline{\\underline{\\textbf{Algorithm:}\\ \\text{Information Node }\\n{\\ Update}}}$\n\n$1.\\ \\mathbf{store}\\ \\otrue=\\rm{concat}(\\n[parent].\\s|\\forall\\n[parent]\\in\\nparent)$\n\n$2.\\ d_t^{ave}=d_t^{ave}+\\alpha_{d,1}\\frac{I(\\otrue)}{H(\\s[t-p])}$\n\n$3.\\ \\falert=\\tanh[\\alpha_{d,2}(d_t^{ave}-\\alpha_{d,3})]$\n\n$4.\\ \\o=\\falert\\otrue+(1-\\falert)\\otarget[t]$\n\n$5.\\ \\s=\\ab(\\opast[t-N_o:t])$\n\n$6.\\ \\spred[t+p]=\\pr(\\s)$\n\n$7.\\ \\starget[t+p]=\\text{weighted ave}(\\{\\langle w_{pred},\\spred[t+p]\\rangle\\} \\cup \\{\\langle \\n[ch].w_{\\mathcal{Pa}_i}\\CER(\\n[ch].\\otarget[\\tau])\\times e^{-\\n[ch].\\lambda(t+p-\\tau)}, \\n[ch].\\otarget[\\tau]\\rangle\\ |\\ \\exists\\n[ch].\\otarget[\\tau];\\ \\tau=\\max [t-N_o:t+p];\\ \\forall\\n[ch]\\in\\nchildren\\})$\n\n$8.\\ \\otarget[t+p]=\\pol(\\s,\\starget[t+p])$\n\n$9.\\ \\textbf{wait}\\ p\\ \\text{timesteps}$ \n\n$10.\\ \\textbf{repeat}$\n\n## Training\n\nTraining is performed online, on-policy, and on-predictor with new, prioritized, and imagined data. Minibatches are only one rollout sequence of observations ($N=1$) from every point in time in an episode to allow training large architectures and keep policies fresh. Dreaming provides novel observation trajectories for the abstractor and child information nodes to learn. However information nodes do not train their policy or predictor on its own dreamed trajectories ($\\o=\\otrue$ when optimizing).\n\n### Learning the Policy\n\n$\\def\\loss{\\mathcal{L}}$\n$\\def\\obj{\\mathcal{J}}$\nThe policy aims to produce target observations $\\otarget[t+p]=\\pol(\\s,\\starget[t+p])$ which cumulatively:\n- maximize target state achievement $D_{KL}\\bigl(\\starget[t+p]||\\ab([\\otruepast;\\pol(\\s,\\starget[t+p])])\\bigr)$\n- maximize resulting state certainty $\\CER\\bigl(\\ab([\\otruepast;\\pol(\\s,\\starget[t+p])])\\bigr)$\n- maximize informative observations targeted $\\CER\\bigl(\\pol(\\s,\\starget[t+p])\\bigr)$\n\nThese objectives are combined as:\n\n$\\loss_\\pol=\\underbrace{\\beta_{\\pol,D}\\norm{\\ln{D_{KL}\\bigl(\\starget[t+p]||\\ab([\\otruepast;\\pol(\\s,\\starget[t+p])])\\bigr)}}}_\\text{target state achievement}-\\underbrace{\\beta_{\\pol,\\CER}\\norm{\\ln{\\CER\\bigl(\\ab([\\otruepast;\\pol(\\s,\\starget[t+p])])\\bigr)}}}_\\text{resulting state certainty}-\\underbrace{\\beta_{\\pol,I}\\norm{\\ln{\\CER\\bigl(\\pol(\\s,\\starget[t+p])\\bigr)}}}_\\text{informative observations targeted}$\n\nThis attempts to make the policy descend the gradient of predictive error and entropy while attempting to please its children's desired target observations. That is, it should produce a target observation which will make the abstractor produce an abstraction $\\ab([\\opast;\\pol(\\s,\\starget[t+p])])$ as close as possible to $\\starget[t+p]$. The last objective is added because informative events often reduce cumulative predictive entropy. By searching out unexpected, *informative* events, an agent is able to learn a more robust internal model $\\Pr(\\o[t+p]|\\opast)$.\n\n### Learning the Predictor\n\nIdeally, the predictor aims to model its observations perfectly $\\spred[t+p]=\\s[t+p]$. This means it should be able to maintain an accurate predicted state trajectory s.t. $\\pr(\\pr(\\pr(\\s)))\\approxeq \\s[t+3p]$. That requires maximizing predictive certainty $\\CER(\\pr(\\s))$. Jointly, these objectives compose:\n\n$\\obj_\\pr=\\underbrace{\\beta_{\\pr,D}\\norm{\\ln{\\bigl[D_{KL}(\\pr(\\s)||\\s[t+p])\\bigr]}}}_\\text{accuracy} - \\underbrace{\\beta_{\\pr,\\CER}\\norm{\\ln{ \\CER(\\pr(\\s))}}}_\\text{certainty}$\n\nObjectives are computed componentwise and only then normalized to encourage modeling only a few variables accurately rather than attempting to poorly model a joint distribution.\n\n### Learning the Abstractor\n\nIn some information nodes, the abstractor may be frozen with pretrained weights. When trainable however, its optimization attempts to capture variables relevant to both the policy's and predictor's losses. Although dreaming may provide novel observation trajectories for the abstractor to represent only true observations are used to optimize $\\ab$. However, child information nodes do optimize on the novel state trajectories generated by dreaming.\n\n### Putting it all togethor\n\nOptimization begins at each record in time of an information episoe $\\IE=\\langle\\otruepast,\\nchildren \\text{(target observation sequences only)}\\rangle$ by predicting the rollout for $T_{rollout}$ timesteps. Then cumulative policy and predictor losses are minimized by optimizing policy, predictor, and abstractor weights. Importantly, this optimization process takes place for nodes individually, allowing very large node architectures to integrate in an agent that no one processing unit could support.\n\n$\\begin{equation}\\overline{\\underline{\\mathbf{Algorithm}:\\ \\text{Train Information Node }\\n}} \\\\\n1.\\ \\ \\mathbf{for}\\ t\\in[\\IE.T_{start}+p,\\IE.T_{start}+2p,\\dots,\\IE.T_{end}]:\\qquad\\rhd\\text{precompute }\\s[ ],\\spred[ ],\\starget[ ],\\otarget[ ] \\\\\n2.\\ \\ \\quad \\s=\\ab(\\IE.\\otruepast) \\\\\n3.\\ \\ \\quad \\spred[t+p]=\\pr(\\s) \\\\\n4.\\ \\ \\quad \\starget[t+p]=\\text{weighted ave}(\\{\\langle w_{pred},\\spred[t+p]\\rangle\\} \\cup \\\\\n\\kern+7em\\{\\langle \\n[ch].w_{\\mathcal{Pa}_i}\\CER(\\n[ch].\\otarget[\\tau]) e^{-\\n[ch].\\lambda(t+p-\\tau)}, \\n[ch].\\otarget[\\tau]\\rangle\\ |\\ \\exists\\n[ch].\\otarget[\\tau];\\ \\tau=\\max [t-N_o:t+p];\\ \\forall\\n[ch]\\in\\IE.\\nchildren\\}) \\\\\n5.\\ \\ \\quad\\otarget[t+p]=\\pol(\\s,\\starget[t+p]) \\\\\n6.\\ \\ \\mathbf{end\\ for} \\\\\n7.\\ \\ \\mathbf{for}\\ t\\in[\\IE.T_{start}+p,\\IE.T_{start}+2p,\\dots,\\IE.T_{end}]: \\\\\n8.\\ \\ \\quad \\loss_t=\\underbrace{\\beta_{\\pol,D}\\norm{\\ln{D_{KL}\\bigl(\\starget[t+p]||\\ab([\\otruepast;\\pol(\\s,\\starget[t+p])])\\bigr)}}}_\\text{target state achievement}-\\underbrace{\\beta_{\\pol,\\CER}\\norm{\\ln{\\CER\\bigl(\\ab([\\otruepast;\\pol(\\s,\\starget[t+p])])\\bigr)}}}_\\text{resulting state certainty}-\\underbrace{\\beta_{\\pol,I}\\norm{\\ln{\\CER\\bigl(\\pol(\\s,\\starget[t+p])\\bigr)}}}_\\text{informative observations targeted} \\\\\n9.\\ \\ \\quad \\tau=t \\\\\n10.\\ \\quad \\oimagpast=\\otruepast \\\\\n11.\\ \\quad \\sblind[\\tau]=\\s \\\\\n12.\\ \\quad \\mathbf{while}\\ \\tau\\le t+T_{rollout}\\ \\mathbf{and}\\ \\tau\\le\\IE.T_{end}-p:\\qquad\\rhd\\text{compute rollout comparing against real data} \\\\\n13.\\ \\qquad \\simag=\\ab(\\oimagpast) \\\\\n14.\\ \\qquad \\spredimag[\\tau+p]=\\pr(\\simag) \\\\\n15.\\ \\qquad \\stargetimag[\\tau+p]=\\text{weighted ave}(\\{\\langle w_{predimag},\\spredimag[\\tau+p]\\rangle\\} \\cup \\{\\langle \\n[ch].w_{\\mathcal{Pa}_i}\\CER(\\n[ch].\\o[\\tau_{ch}])e^{-\\n[ch].\\lambda(\\tau+p-\\tau_{ch})}, \\n[ch].\\o[\\tau_{ch}]\\rangle \\\\\n\\kern+10em |\\ \\exists\\n[ch].\\o[\\tau_{ch}];\\ \\tau_{ch}=\\max [\\tau-N_o:\\tau+p];\\ \\forall\\n[ch]\\in\\IE.\\nchildren\\}) \\\\\n16.\\ \\qquad \\oimag[\\tau+p]=\\pol(\\simag,\\stargetimag) \\\\\n17.\\ \\qquad \\sblind=\\pr(\\sblind[\\tau]) \\\\\n18.\\ \\qquad \\loss_t=\\loss_t+\\gamma^{t-\\tau}\\Biggl[ \\underbrace{\\beta_{\\pol,D}\\norm{\\ln{D_{KL}(\\stargetimag[\\tau]||\\simag)}}}_\\text{target state achievement} - \\underbrace{\\beta_{\\pol,\\CER}\\norm{\\ln{\\CER(\\simag)}}}_\\text{resulting state certainty} - \\underbrace{\\beta_{\\pol,I}\\norm{\\ln{\\CER(\\oimag[\\tau+p])}}}_\\text{informative observations targeted} \\\\\n\\kern+6em + \\underbrace{\\beta_{\\pr,D}\\norm{\\ln{\\bigl[D_{KL}(\\sblind||\\s[t+p])}}}_\\text{blind prediction accuracy} - \\underbrace{\\beta_{\\pr,\\CER}\\norm{\\ln{ \\CER(\\sblind)}}}_\\text{blind prediction certainty}\\Biggr]\\\\\n19.\\ \\qquad \\tau = \\tau + p \\\\\n20.\\ \\ \\quad \\mathbf{end\\ while} \\\\\n21.\\ \\quad \\underset{\\theta_\\ab,\\theta_\\pr,\\theta_\\pol}\\min\\loss_{t}-R_t(s)\\qquad\\rhd\\text{minimize discounted sum loss and reward for timestep }t \\\\\n22.\\ \\ \\mathbf{end\\ for} \\end{equation}$\n\nTo minimize uncertainty, $\\beta_{\\pol,\\CER}>1$, $\\beta_{\\pr,\\CER}>1$. $R_t(s)$ encompasses any supervised rewards.\n\n## Knowledge Transfer and Swarm Intelligence\n\nAGI-0's node-based architecture allows different networks to share underlying nodes and individual nodes to transfer in knowledge from other neural networks. For example, a software automation agent and a writing agent might benefit by sharing nodes that process natural language. Some natural language processing nodes might also utilize existing language models like gpt for their abstractor and a conditional language modeling head for the policy. Nodes do not belong to any one agent but instead a *swarm cloud* which trains and serves individual nodes. *Information episodes* $\\IE$ are collected from nodes after the agent's episode completes. This allows agents to synergize each other's heterogeneous architectures.\n\n\n<!-- https://mermaid-js.github.io/mermaid-live-editor/#/edit/eyJjb2RlIjoiZ3JhcGggVERcbiAgQVtwaXhlbHNdIC0tPiBCKHZpc3VhbCBkYXRhKVxuICBBIC0tPiBDXG4gIEIgLS0-IEMoc3ltYm9sIHN0cmluZ3MpXG4gIEMgLS0-IEQobGFuZ3VhZ2UgcHJvY2Vzc2luZylcblx0RCAtLT4gRShhYnN0cmFjdCB1bmRlcnN0YW5kaW5nKVxuICBGW2tleSBldmVudHNdIC0tPiBHXG4gIEhbbW91c2UgZXZlbnRzXSAtLT4gR1xuICBHKGFjdGlvbiBwcmltaXRpdmVzKVxuICBHIC0tPiBFXG4gIEYgLS0-IEkobGFuZ3VhZ2UgcHJvY2Vzc2luZylcbiAgSSAtLT4gRVxuXG4gIEpbdGV4dF0gLS0-IEtcbiAgSyhsYW5ndWFnZSBwcm9jZXNzaW5nKVxuICBLIC0tPiBMKGxhbmd1YWdlIHVuZGVyc3RhbmRpbmcgSSlcbiAgSyAtLT4gTShsYW5ndWFnZSB1bmRlcnN0YW5kaW5nIElJKVxuICBLIC0tPiBOKGxhbmd1YWdlIHVuZGVyc3RhbmRpbmcgSUlJKVxuICBMIC0tPiBOXG4gIE0gLS0-IE4iLCJtZXJtYWlkIjp7InRoZW1lIjoiZGVmYXVsdCJ9LCJ1cGRhdGVFZGl0b3IiOmZhbHNlfQ -->\n\n\n<!-- https://mermaid-js.github.io/mermaid-live-editor/#/edit/eyJjb2RlIjoiZ3JhcGggVERcbiAgQVtvYnNlcnZhdGlvbnMgdXAgdG8gdF1cbiAgQltiaWFzaW5nIGluZm9ybWF0aW9uXVxuICBDW3RhcmdldCBvYnNlcnZhdGlvbl1cblxuICBEKGFic3RyYWN0b3IpXG4gIEUocHJlZGljdG9yKVxuICBGW3RhcmdldCBzdGF0ZV1cbiAgRyhwb2xpY3kpXG5cbiAgQSAtLT4gRFxuICBEIC0tPiBFXG4gIEUgLS0-IEZcbiAgQiAtLT4gRlxuXG4gIEYgLS0-IEdcbiAgRyAtLT4gQ1xuXG4gIElbdG9rZW4gc2VxdWVuY2VdIC0tPiBKKHRyYW5zZm9ybWVyKVxuICBKIC0tPiBLKGxhbmd1YWdlIG1vZGVsaW5nIGhlYWQpXG4gIEsgLS0-IExbbmV4dCB0b2tlbl0iLCJtZXJtYWlkIjp7InRoZW1lIjoiZGVmYXVsdCJ9LCJ1cGRhdGVFZGl0b3IiOmZhbHNlfQ -->\nIn the above comparison between a language modeling transformer and an information node, note that the predictor must be trained on supervised data. This could be implimented by initializing or even freezing the abstractor's weights with the transformer network, training the predictor to predict embedding transitions, and forcing the policy to produce the required next token from that predicted embedding (although top-down influence can change network output). \n\n# Implementation\n\n## Nodes\n\nSince nodes are asychronous, they can be trained or deployed on different underlying architectures without significant issues resulting from latency. Following is a generic node class and then sensory, actuator, and information node implimentations.\n\n**ACTUALLY, EMBED TO FILE IN GITHUB**\n\n\n```python\nclass Node:\n\n    self.children\n\n    self.p\n\n    self.o\n    self.s\n\n\n    def update():\n        pass\n\n```\n\n### Sensory Node\n\n\n```python\nclass Sensory_Node(node):\n\n    def update():\n        pass\n```\n\n### Actuator Node\n\n\n```python\nclass Actuator_Node(node):\n\n    def update():\n        pass\n```\n\n### Information Node\n\n\n```python\nclass Information_Episode:\n\n```\n\n\n```python\nclass Information_Node(node):\n\n    self.parents\n\n    self.otarget\n\n    self.hparams\n\n    def update():\n        pass\n\n    def compile_information_episode() -> Information_Episode:\n        pass\n\n    def train(information_episode: Information_Episode):\n        pass\n```\n\n## Network\n\nBrief overview of what's happening (maybe remove)\n\n\n```python\n\n```\n\n# Experiments\n\nIntroduction\n\nObserving Nodal RL in\n- different environments\n- different agents\n- architecture deviations\n- unsupervised/guided exploration\n\nThe following experiment parameters are explored:\n\n### Generic Information Nodes:\n\n- Dense Information Node\n    - proof of concept node\n    - dense/specialized abstractor\n    - dense predictor\n    - dense policy\n\n- Sparse Information Node\n    - sparse variational autoencoders ensembles competing to represent $\\ab$ by lowest representation entropy \n    - sparse transformer $\\pr$\n    - optionally penalizing state certainty decrease and rewarding entropic actions\n    - directly minimizing entropy of binary valued sparse state vector quantization with annealing self organizing maps\n\n- Energy-based Information Node\n    - energy-based $\\ab$ and $\\pr$\n    - $pol$ analagous to 'energy descent with a bias'\n\n### Specialized Information Nodes\n\n- language modeling\n- machine vision\n- audio\n\n### Substructures\n\n- Homogeneous Ensembles\n- Heterogeneous Ensembles\n\n### Training\n\n- in-context supervised training and zero, one, and few shot test\n- penalizing activation\n- maximize $ln{[\\CER(\\s[t+p]) - \\CER(\\s)]}$\n\n### agents/environments\n\n- kinistetic\n    - one legged hopper\n    - spider\n    - humanoid\n\n- multimedia modeling\n    - image\n    - video\n    - audio\n\n- board games\n    - checkers\n    - chess\n    - go\n\n- software agent\n    - bash REPL\n    - python REPL\n        - autoML\n        - selfML\n\n- Multi-Organism Systems\n    - chatbots\n\n- MALMO\n    - single agent\n    - multi agent (self-play)\n    - multi-agent (human-play)\n\n- Second Life\n\n- engineering design\n\n- more to come\n\n### high-level conditioning\n- none (open ended learning)\n- RL agent\n- realtime human control\n\nIndividual experiments are found in hyperlinked notebooks\n\n# Results\n\n# Analysis\n\n# Discussion\n\n# Conclusion\n\nGeneral conclusion here\n\n## Questions\n\n- **How generalized can Nodel RL agents become?** Will agent performance continue improving as it acquires skills specialized for increasingly diverse domains? Can a humanoid robot controlled by Nodal RL perform reliably in the general human activity domain?\n- **Can an [imitator-imitator](https://arxiv.org/abs/1912.02875) framework be used to condition Nodel-RL agent behavior?**\n- **How could transformer neural networks learn when to dream ($\\NN_{transformer}(\\opast)$) instead of employing a blind rolling average ($\\text{Percieved Observation }\\o$)?**\n- **Can humans learn to dynamically condition agents to control their behavior?** Since high level conditioning data only provides a general handle on agent behavior, would a user commanding the agent in realtime be able to adjust his or her commands dynamically to more reliably achieve high level targets?\n- **Will centralized shared-parameter multiagent training efficently improve performance?** Although parameter sharing in reinforcement learning [generally accelerates learning in MARL](https://arxiv.org/abs/2005.13625), is it worth the cost to centralize training these huge architectures?\n\n# References\n\n - @book{Goodfellow-et-al-2016,\n    title={Deep Learning},\n    author={Ian Goodfellow and Yoshua Bengio and Aaron Courville},\n    publisher={MIT Press},\n    note={\\url{http://www.deeplearningbook.org}},\n    year={2016}\n}\n\n# Appendix\n", "meta": {"hexsha": "7624b5d43f80d23b900c234ebe4b424c498f19e3", "size": 45790, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "NMRL-concept.ipynb", "max_stars_repo_name": "JacobFV/AI-Resources", "max_stars_repo_head_hexsha": "b267bc35d55ca39ded28cacdd86f7b91ad042d54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-10T23:05:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-10T23:05:53.000Z", "max_issues_repo_path": "NMRL-concept.ipynb", "max_issues_repo_name": "JacobFV/AGI", "max_issues_repo_head_hexsha": "bfc941a9c17079f806bdccc9c6d6a1eceb7eacde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NMRL-concept.ipynb", "max_forks_repo_name": "JacobFV/AGI", "max_forks_repo_head_hexsha": "bfc941a9c17079f806bdccc9c6d6a1eceb7eacde", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.8839285714, "max_line_length": 1924, "alphanum_fraction": 0.6263594671, "converted": true, "num_tokens": 8710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16026603633858205, "lm_q2_score": 0.029760095667014458, "lm_q1q2_score": 0.004769532573609418}}
{"text": "% PACKAGES INCLUDED HERE \n% DO NOT NEED TO CHANGE\n\\documentclass[conference]{IEEEtran}\n\\IEEEoverridecommandlockouts\n% The preceding line is only needed to identify funding in the first footnote. If that is unneeded, please comment it out.\n\\usepackage{cite}\n\\usepackage{amsmath,amssymb,amsfonts}\n\\usepackage{algorithmic}\n\\usepackage{graphicx}\n\\usepackage{textcomp}\n\\def\\BibTeX{{\\rm B\\kern-.05em{\\sc i\\kern-.025em b}\\kern-.08em\n    T\\kern-.1667em\\lower.7ex\\hbox{E}\\kern-.125emX}}\n\\begin{document}% AUTHOR NAMES AND TITLE GOES HERE\n\\title{Paper Title*\\\\\n{\\footnotesize \\textsuperscript{*}Note: Sub-titles are not captured in Xplore and\nshould not be used}\n\\thanks{Identify applicable funding agency here. If none, delete this.}\n}\n\n\\author{\\IEEEauthorblockN{1\\textsuperscript{st} Given Name Surname}\n\\IEEEauthorblockA{\\textit{dept. name of organization (of Aff.)} \\\\\n\\textit{name of organization (of Aff.)}\\\\\nCity, Country \\\\\nemail address}\n\\and\n\\IEEEauthorblockN{2\\textsuperscript{nd} Given Name Surname}\n\\IEEEauthorblockA{\\textit{dept. name of organization (of Aff.)} \\\\\n\\textit{name of organization (of Aff.)}\\\\\nCity, Country \\\\\nemail address}\n\\and\n\\IEEEauthorblockN{3\\textsuperscript{rd} Given Name Surname}\n\\IEEEauthorblockA{\\textit{dept. name of organization (of Aff.)} \\\\\n\\textit{name of organization (of Aff.)}\\\\\nCity, Country \\\\\nemail address}\n\\and\n\\IEEEauthorblockN{4\\textsuperscript{th} Given Name Surname}\n\\IEEEauthorblockA{\\textit{dept. name of organization (of Aff.)} \\\\\n\\textit{name of organization (of Aff.)}\\\\\nCity, Country \\\\\nemail address}\n\\and\n\\IEEEauthorblockN{5\\textsuperscript{th} Given Name Surname}\n\\IEEEauthorblockA{\\textit{dept. name of organization (of Aff.)} \\\\\n\\textit{name of organization (of Aff.)}\\\\\nCity, Country \\\\\nemail address}\n\\and\n\\IEEEauthorblockN{6\\textsuperscript{th} Given Name Surname}\n\\IEEEauthorblockA{\\textit{dept. name of organization (of Aff.)} \\\\\n\\textit{name of organization (of Aff.)}\\\\\nCity, Country \\\\\nemail address}\n}\n\n\\maketitle% ABSTRACT AND KEYWORDS\n\\begin{abstract}\nThis document is a model and instructions for \\LaTeX.\nThis and the IEEEtran.cls file define the components of your paper [title, text, heads, etc.]. *CRITICAL: Do Not Use Symbols, Special Characters, Footnotes, \nor Math in Paper Title or Abstract.\n\\end{abstract}\n\n\\begin{IEEEkeywords}\ncomponent, formatting, style, styling, insert\n\\end{IEEEkeywords}% SECTIONS\n\\section{Introduction}\nThis document is a model and instructions for \\LaTeX.\nPlease observe the conference page limits. \n\n\\section{Ease of Use}\n\n\\subsection{Maintaining the Integrity of the Specifications}\n\nThe IEEEtran class file is used to format your paper and style the text. All margins, \ncolumn widths, line spaces, and text fonts are prescribed; please do not \nalter them. You may note peculiarities. For example, the head margin\nmeasures proportionately more than is customary. This measurement \nand others are deliberate, using specifications that anticipate your paper \nas one part of the entire proceedings, and not as an independent document. \nPlease do not revise any of the current designations.\n\n\\section{Prepare Your Paper Before Styling}\nBefore you begin to format your paper, first write and save the content as a \nseparate text file. Complete all content and organizational editing before \nformatting. Please note sections \\ref{AA}--\\ref{SCM} below for more information on \nproofreading, spelling and grammar.\n\nKeep your text and graphic files separate until after the text has been \nformatted and styled. Do not number text heads---{\\LaTeX} will do that \nfor you.\n\n\\subsection{Abbreviations and Acronyms}\\label{AA}\nDefine abbreviations and acronyms the first time they are used in the text, \neven after they have been defined in the abstract. Abbreviations such as \nIEEE, SI, MKS, CGS, ac, dc, and rms do not have to be defined. Do not use \nabbreviations in the title or heads unless they are unavoidable.\n\n\\subsection{Units}\n\\begin{itemize}\n\\item Use either SI (MKS) or CGS as primary units. (SI units are encouraged.) English units may be used as secondary units (in parentheses). An exception would be the use of English units as identifiers in trade, such as ``3.5-inch disk drive''.\n\\item Avoid combining SI and CGS units, such as current in amperes and magnetic field in oersteds. This often leads to confusion because equations do not balance dimensionally. If you must use mixed units, clearly state the units for each quantity that you use in an equation.\n\\item Do not mix complete spellings and abbreviations of units: ``Wb/m\\textsuperscript{2}'' or ``webers per square meter'', not ``webers/m\\textsuperscript{2}''. Spell out units when they appear in text: ``. . . a few henries'', not ``. . . a few H''.\n\\item Use a zero before decimal points: ``0.25'', not ``.25''. Use ``cm\\textsuperscript{3}'', not ``cc''.)\n\\end{itemize}\n\n\\subsection{Equations}\nNumber equations consecutively. To make your \nequations more compact, you may use the solidus (~/~), the exp function, or \nappropriate exponents. Italicize Roman symbols for quantities and variables, \nbut not Greek symbols. Use a long dash rather than a hyphen for a minus \nsign. Punctuate equations with commas or periods when they are part of a \nsentence, as in:\n\\begin{equation}\na+b=\\gamma\\label{eq}\n\\end{equation}\n\nBe sure that the \nsymbols in your equation have been defined before or immediately following \nthe equation. Use ``\\eqref{eq}'', not ``Eq.~\\eqref{eq}'' or ``equation \\eqref{eq}'', except at \nthe beginning of a sentence: ``Equation \\eqref{eq} is . . .''\n\n\\subsection{\\LaTeX-Specific Advice}\n\nPlease use ``soft'' (e.g., \\verb|\\eqref{Eq}|) cross references instead\nof ``hard'' references (e.g., \\verb|(1)|). That will make it possible\nto combine sections, add equations, or change the order of figures or\ncitations without having to go through the file line by line.\n\nPlease don't use the \\verb|{eqnarray}| equation environment. Use\n\\verb|{align}| or \\verb|{IEEEeqnarray}| instead. The \\verb|{eqnarray}|\nenvironment leaves unsightly spaces around relation symbols.\n\nPlease note that the \\verb|{subequations}| environment in {\\LaTeX}\nwill increment the main equation counter even when there are no\nequation numbers displayed. If you forget that, you might write an\narticle in which the equation numbers skip from (17) to (20), causing\nthe copy editors to wonder if you've discovered a new method of\ncounting.\n\n{\\BibTeX} does not work by magic. It doesn't get the bibliographic\ndata from thin air but from .bib files. If you use {\\BibTeX} to produce a\nbibliography you must send the .bib files. \n\n{\\LaTeX} can't read your mind. If you assign the same label to a\nsubsubsection and a table, you might find that Table I has been cross\nreferenced as Table IV-B3. \n\n{\\LaTeX} does not have precognitive abilities. If you put a\n\\verb|\\label| command before the command that updates the counter it's\nsupposed to be using, the label will pick up the last counter to be\ncross referenced instead. In particular, a \\verb|\\label| command\nshould not go before the caption of a figure or a table.\n\nDo not use \\verb|\\nonumber| inside the \\verb|{array}| environment. It\nwill not stop equation numbers inside \\verb|{array}| (there won't be\nany anyway) and it might stop a wanted equation number in the\nsurrounding equation.\n\n\\subsection{Some Common Mistakes}\\label{SCM}\n\\begin{itemize}\n\\item The word ``data'' is plural, not singular.\n\\item The subscript for the permeability of vacuum $\\mu_{0}$, and other common scientific constants, is zero with subscript formatting, not a lowercase letter ``o''.\n\\item In American English, commas, semicolons, periods, question and exclamation marks are located within quotation marks only when a complete thought or name is cited, such as a title or full quotation. When quotation marks are used, instead of a bold or italic typeface, to highlight a word or phrase, punctuation should appear outside of the quotation marks. A parenthetical phrase or statement at the end of a sentence is punctuated outside of the closing parenthesis (like this). (A parenthetical sentence is punctuated within the parentheses.)\n\\item A graph within a graph is an ``inset'', not an ``insert''. The word alternatively is preferred to the word ``alternately'' (unless you really mean something that alternates).\n\\item Do not use the word ``essentially'' to mean ``approximately'' or ``effectively''.\n\\item In your paper title, if the words ``that uses'' can accurately replace the word ``using'', capitalize the ``u''; if not, keep using lower-cased.\n\\item Be aware of the different meanings of the homophones ``affect'' and ``effect'', ``complement'' and ``compliment'', ``discreet'' and ``discrete'', ``principal'' and ``principle''.\n\\item Do not confuse ``imply'' and ``infer''.\n\\item The prefix ``non'' is not a word; it should be joined to the word it modifies, usually without a hyphen.\n\\item There is no period after the ``et'' in the Latin abbreviation ``et al.''.\n\\item The abbreviation ``i.e.'' means ``that is'', and the abbreviation ``e.g.'' means ``for example''.\n\\end{itemize}\nAn excellent style manual for science writers is \\cite{b7}.\n\n\\subsection{Authors and Affiliations}\n\\textbf{The class file is designed for, but not limited to, six authors.} A \nminimum of one author is required for all conference articles. Author names \nshould be listed starting from left to right and then moving down to the \nnext line. This is the author sequence that will be used in future citations \nand by indexing services. Names should not be listed in columns nor group by \naffiliation. Please keep your affiliations as succinct as possible (for \nexample, do not differentiate among departments of the same organization).\n\n\\subsection{Identify the Headings}\nHeadings, or heads, are organizational devices that guide the reader through \nyour paper. There are two types: component heads and text heads.\n\nComponent heads identify the different components of your paper and are not \ntopically subordinate to each other. Examples include Acknowledgments and \nReferences and, for these, the correct style to use is ``Heading 5''. Use \n``figure caption'' for your Figure captions, and ``table head'' for your \ntable title. Run-in heads, such as ``Abstract'', will require you to apply a \nstyle (in this case, italic) in addition to the style provided by the drop \ndown menu to differentiate the head from the text.\n\nText heads organize the topics on a relational, hierarchical basis. For \nexample, the paper title is the primary text head because all subsequent \nmaterial relates and elaborates on this one topic. If there are two or more \nsub-topics, the next level head (uppercase Roman numerals) should be used \nand, conversely, if there are not at least two sub-topics, then no subheads \nshould be introduced.\n\n\\subsection{Figures and Tables}\n\\paragraph{Positioning Figures and Tables} Place figures and tables at the top and \nbottom of columns. Avoid placing them in the middle of columns. Large \nfigures and tables may span across both columns. Figure captions should be \nbelow the figures; table heads should appear above the tables. Insert \nfigures and tables after they are cited in the text. Use the abbreviation \n``Fig.~\\ref{fig}'', even at the beginning of a sentence.\n\n% CREATES TABLE\n\\begin{table}[htbp]\n\\caption{Table Type Styles}\n\\begin{center}\n\\begin{tabular}{|c|c|c|c|}\n\\hline\n\\textbf{Table}&\\multicolumn{3}{|c|}{\\textbf{Table Column Head}} \\\\\n\\cline{2-4} \n\\textbf{Head} & \\textbf{\\textit{Table column subhead}}& \\textbf{\\textit{Subhead}}& \\textbf{\\textit{Subhead}} \\\\\n\\hline\ncopy& More table copy$^{\\mathrm{a}}$& &  \\\\\n\\hline\n\\multicolumn{4}{l}{$^{\\mathrm{a}}$Sample of a Table footnote.}\n\\end{tabular}\n\\label{tab1}\n\\end{center}\n\\end{table}% CREATES IMAGE FIGURE\n\\begin{figure}[htbp]\n\\centerline{\\includegraphics[width=\\linewidth]{fig1.png}}\n\\caption{Example of a figure caption.}\n\\label{fig}\n\\end{figure}Figure Labels: Use 8 point Times New Roman for Figure labels. Use words \nrather than symbols or abbreviations when writing Figure axis labels to \navoid confusing the reader. As an example, write the quantity \n``Magnetization'', or ``Magnetization, M'', not just ``M''. If including \nunits in the label, present them within parentheses. Do not label axes only \nwith units. In the example, write ``Magnetization (A/m)'' or ``Magnetization \n\\{A[m(1)]\\}'', not just ``A/m''. Do not label axes with a ratio of \nquantities and units. For example, write ``Temperature (K)'', not \n``Temperature/K''.\n\n\\section*{Acknowledgment}\n\nThe preferred spelling of the word ``acknowledgment'' in America is without \nan ``e'' after the ``g''. Avoid the stilted expression ``one of us (R. B. \nG.) thanks $\\ldots$''. Instead, try ``R. B. G. thanks$\\ldots$''. Put sponsor \nacknowledgments in the unnumbered footnote on the first page.\n\n\\section*{References}\n\nPlease number citations consecutively within brackets \\cite{b1}. The \nsentence punctuation follows the bracket \\cite{b2}. Refer simply to the reference \nnumber, as in \\cite{b3}---do not use ``Ref. \\cite{b3}'' or ``reference \\cite{b3}'' except at \nthe beginning of a sentence: ``Reference \\cite{b3} was the first $\\ldots$''\n\nNumber footnotes separately in superscripts. Place the actual footnote at \nthe bottom of the column in which it was cited. Do not put footnotes in the \nabstract or reference list. Use letters for table footnotes.\n\nUnless there are six authors or more give all authors' names; do not use \n``et al.''. Papers that have not been published, even if they have been \nsubmitted for publication, should be cited as ``unpublished'' \\cite{b4}. Papers \nthat have been accepted for publication should be cited as ``in press'' \\cite{b5}. \nCapitalize only the first word in a paper title, except for proper nouns and \nelement symbols.\n\nFor papers published in translation journals, please give the English \ncitation first, followed by the original foreign-language citation \\cite{b6}.\n\\bibliographystyle{IEEEtran}\n\\bibliography{References}\\end{document}", "meta": {"hexsha": "075118129b08ab29026a66f3d4e6c5072788d39a", "size": 17819, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Paper/conf_template.ipynb", "max_stars_repo_name": "CSCI4850/S19-team1-project", "max_stars_repo_head_hexsha": "6626f1d4dd760c519a527cfc5402b2fdcc55c608", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Paper/conf_template.ipynb", "max_issues_repo_name": "CSCI4850/S19-team1-project", "max_issues_repo_head_hexsha": "6626f1d4dd760c519a527cfc5402b2fdcc55c608", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Paper/conf_template.ipynb", "max_forks_repo_name": "CSCI4850/S19-team1-project", "max_forks_repo_head_hexsha": "6626f1d4dd760c519a527cfc5402b2fdcc55c608", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-04T00:25:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-04T00:25:48.000Z", "avg_line_length": 49.7737430168, "max_line_length": 559, "alphanum_fraction": 0.6393737022, "converted": true, "num_tokens": 3584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06954174932677785, "lm_q2_score": 0.06754669207816587, "lm_q1q2_score": 0.004697315128352863}}
{"text": "```python\nimport sys\nsys.stdout.write('hello world\\n')\nsys.stdout.flush()\nfor i in range(3):\n    sys.stdout.write('%s\\n' % i)\n    sys.stdout.flush()\nsys.stderr.write('output to stderr\\n')\nsys.stderr.flush()\nsys.stdout.write('some more stdout text\\n')\nsys.stdout.flush()\n```\n\n    hello world\n    0\n    1\n    2\n\n\n    output to stderr\n\n\n    some more stdout text\n\n\n# Markdown Cell\n\n$ e^{ \\pm i\\theta } = \\cos \\theta \\pm i\\sin \\theta + \\beta $\n\n*It* **really** is!\n\n\n```python\nthis is a syntax error\n```\n\n\n```python\nprint('test')\n```\n\n\n```python\nfrom IPython.display import Latex\nLatex('''The mass-energy equivalence is described by the famous equation\n \n$$E=mc^2$$\n \ndiscovered in 1905 by Albert Einstein. \nIn natural units ($c$ = 1), the formula expresses the identity\n \n\\\\begin{equation}\nE=m\n\\\\end{equation}''')\n```\n\n\n\n\nThe mass-energy equivalence is described by the famous equation\n \n$$E=mc^2$$\n \ndiscovered in 1905 by Albert Einstein. \nIn natural units ($c$ = 1), the formula expresses the identity\n \n\\begin{equation}\nE=m\n\\end{equation}\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "3ecf9384c9e921c81c051c8b4aaef39812a64d2e", "size": 3573, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/notebook/test.ipynb", "max_stars_repo_name": "odidev/jupyterlab", "max_stars_repo_head_hexsha": "0b88d64b622fc03f4c06ce9cceaa13bc443db468", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11496, "max_stars_repo_stars_event_min_datetime": "2016-10-12T21:02:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:09:23.000Z", "max_issues_repo_path": "examples/notebook/test.ipynb", "max_issues_repo_name": "odidev/jupyterlab", "max_issues_repo_head_hexsha": "0b88d64b622fc03f4c06ce9cceaa13bc443db468", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 10587, "max_issues_repo_issues_event_min_datetime": "2016-10-12T21:22:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:44:58.000Z", "max_forks_repo_path": "examples/notebook/test.ipynb", "max_forks_repo_name": "odidev/jupyterlab", "max_forks_repo_head_hexsha": "0b88d64b622fc03f4c06ce9cceaa13bc443db468", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2612, "max_forks_repo_forks_event_min_datetime": "2016-10-13T12:56:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T17:03:04.000Z", "avg_line_length": 21.1420118343, "max_line_length": 276, "alphanum_fraction": 0.489504618, "converted": true, "num_tokens": 301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0967057880894305, "lm_q2_score": 0.04742587772156363, "lm_q1q2_score": 0.004586356880896776}}
{"text": "# Overview of RNA-Seq analysis\n\n## 0. Preliminaries\n\n### Notation\n\nA line beginning with a dollar sign (`$`) indicates the command line. It is meant to orient you that the command is to be performed in the terminal.\n    \n    $ \n    \nThis is not to be confused with something like `$HOME`, which means a variable named \"HOME\" that has the value (on my computer), shown by `echo` (which prints the output of commands). The dollar sign here means to access that variable. The line after the command line means the output of the command.\n\n    $ echo $HOME \n    /Users/olga\n\n### Anatomy of a Unix command\n\nWe'll be using unix commands here and it's worth pausing and talking about what these commands are really doing. Let's pretend we have a program called `libraryprep`. We can call the program using its name:\n\n    $ libraryprep\n    \nLet's say it has the option flag (aka \"flag\" aka \"argument\") `--stranded`. You'd tell the program this flag by putting it after the command:\n\n    $ libraryprep --stranded\n    \nA lot of times there's a shortened version of the flag. For `--stranded` let's say it's `-s`. Then you could use the shorter command,\n\n    $ libraryprep -s  # This is equal to \"libraryprep --stranded\"\n\nNotice the hash \"`#`\". In all the languages we'll be using (bash, Python), this is a \"comment\" meaning its only for human reading and the computer can stop reading as soon as it sees the hash.\n\nIf a flag requires an input, you would put it immediately after the flag. For example, say we have a flag called `--input` and it requires the cell lysis file:\n\n    $ libraryprep -s --input lysis\n    \nNow Let's say it has the options `-a`, `-s`, `-d`, `-f` We can put all of them sequentially:\n\n    $ libraryprep -a -s -d -f\n    \nOr put them all in a row after a single dash. So the above command is equivalent to:\n\n    $ libraryprep -asdf\n    \nBut if you have a multi-character flag like `--stranded` then that has to be separate:\n\n    $ libraryprep -adf --stranded  # correct\n    $ libraryprep -adfstranded     # incorrect\n    \nOr if the flag requires an argument, then you have to keep it separate, unless the shortened version is at the end. For the purposes of this, let's say `-i` is short for `--input`.\n\n    $ libraryprep -asdf --input lysis  # correct\n    $ libraryprep -asdfi lysis         # correct\n    $ libraryprep -asdfinput lysis     # incorrect\n    $ libraryprep -asdif lysis         # incorrect\n\nIf you have a long command, you can separate it out onto multiple lines for readability (meaning just for you the human, not for the computer) by using the backslash \"`\\`\" for each line that's supposed to continue on to the next one. The indentation is purely for readability and isn't required - it just looks nicer.\n\nFun fact: The way I remember that \"`\\`\" backslash because the top is falling backwards, and \"`/`\" is frontslash because the top is falling forwards.\n\n    $ # Correct\n    $ libraryprep -adf \\\n        --input lysis \\\n        --stranded\n\n It is very important that there are no spaces or other characters after the slashes! Otherwise your program will throw a cryptic syntax error and you will be sad.\n\n    $ # Incorrect\n    $ libraryprep -adf \\ # comments aren't allowed here\n        --input lysis \\ --flags-arent-okay-either\n        --stranded\n\n### Getting help\n\nFor most command-line programs, you can get help on how to actually use the program one of four ways. This is called finding the \"usage\" message. I've written them in priority order so, try the first one first, then the second, etc.\n\n1. `$ programname`\n    2. Without any arguments, this will call the program. Sometimes this will give you usage information, sometimes it will result in an error.\n2. `$ programname -h`\n    3. The `-h` is (generally) a universal short version flag for \"help me!!! I don't know what's going on!!\" Though sometimes that doesn't work either ...\n3. `$ programname --help`\n    4. The expanded version of `-h`\n4. `$ man programname`\n    5. `man` is for \"manual\" and will bring up the manual pages for that command\n\n### Subcommands\n\nSome programs we'll use will have subcommands. This means that we're calling a specific subprogram of a single program. For example, let's pretend we have a program called `microscopy`, and it has the subcommands `brightfield` and `fluorescence`. You wouldn't be able to call just `microscopy` by itself, because you need to specify the exact subprogram (in this analogy, the type of light inputs) that you want to use:\n\n    $ microscopy\n    Error: Must specify either \"brightfield\" or \"fluorescence\"\n\nThere will be flags like `--zoom` that would make sense for both subcommands:\n\n    $ microscopy brightfield --zoom 10x\n    \nBut only for the `fluorescence` subcommand does the flag `--wavelength` make any sense, since `brightfield` would show all the light.\n    \n    $ microscopy fluorescence --wavelength 488 --zoom 10x\n    \n### \"Standard in\" and \"standard out\"\n\nSome of these commands use the greater than (`>`), which means that the output of the program should be saved a file. I like to think of it as the big input (the left side of the `>`) being squeezed into the small corner of the arrow (right side of the `>`).\n\nFor example, let's go back to our `libraryprep` example. We tell the `libraryprep` program we want a stranded library with our `lysis` input, and to save it as the file called `cdna`.\n\n    $ libraryprep --stranded --input lysis > cdna\n\n## 1. Library quality control\n\n### `.fasta` file format\n\nThis is the simple, very commonly used file format in bioinformatics for storing sequences. An example of the p53 protein sequence is below.\n\n    >sp|P04637|P53_HUMAN Cellular tumor antigen p53 OS=Homo sapiens GN=TP53 PE=1 SV=4\n    MEEPQSDPSVEPPLSQETFSDLWKLLPENNVLSPLPSQAMDDLMLSPDDIEQWFTEDPGP\n    DEAPRMPEAAPPVAPAPAAPTPAAPAPAPSWPLSSSVPSQKTYQGSYGFRLGFLHSGTAK\n    SVTCTYSPALNKMFCQLAKTCPVQLWVDSTPPPGTRVRAMAIYKQSQHMTEVVRRCPHHE\n    RCSDSDGLAPPQHLIRVEGNLRVEYLDDRNTFRHSVVVPYEPPEVGSDCTTIHYNYMCNS\n    SCMGGMNRRPILTIITLEDSSGNLLGRNSFEVRVCACPGRDRRTEEENLRKKGEPHHELP\n    PGSTKRALPNNTSSSPQPKKKPLDGEYFTLQIRGRERFEMFRELNEALELKDAQAGKEPG\n    GSRAHSSHLKSKKGQSTSRHKKLMFKTEGPDSD\n\n### `.fastq` file format\n\nThe current standard of sequencing files is [`fastq`](https://en.wikipedia.org/wiki/FASTQ_format), which is derived from the `fasta` format. Check out an example `fastq` format below which shows 3 entries:\n\n    $ head -n 12 projects/shalek2013/raw_data/S10.chr11.R1.fastq\n    @SRR578577.1 C0HLAACXX120407:2:1107:16553:42649 length=101\n    TCTCCTTAAATTTTAAGTAAATGTTTAAGGGATTTTACACCGGTCTATGGAGGTTTGCATGTGTAATTTTACCTCTAATTAATTATAAGGCCAGGACCAAA\n    +SRR578577.1 C0HLAACXX120407:2:1107:16553:42649 length=101\n    @@@FFDDDHHFHGIG?EAFDHHGHHHFHIEG;FDHIHIIIGIIDGHGHHIGIGGEHGGGGIFHIIGGGGGIGHHHECEDFFFFFFDEDEEE@BCBBBCB##\n    @SRR578577.2 C0HLAACXX120407:2:1203:19118:72461 length=101\n    CCTCTCCTTAAATTTTAAGTAAATGTTTAAGGGATTTTACACCGGTCTATGGAGGTTTGCATGTGTAATTTTACCTCTAATTAATTATAAGGCCAGGACCA\n    +SRR578577.2 C0HLAACXX120407:2:1203:19118:72461 length=101\n    ?@@DFFFDHGFDHEGHFHII<EHHAHHIIIIIIIIIIGEHEIIIIGGG<B<3BFGIEIGIIIGGC.7=CDCHCE??ACEBEE@>CACEC>6;;==BBBBBB\n    @SRR578577.3 C0HLAACXX120407:2:1110:7566:40229 length=101\n    ACCCTCTCCTTAAATTTTAAGTAAATGTTTAAGGGATTTTACACCGGTCTATGGAGGTTTGCATGTGTAATTTTACCTCTAATTAATTATAAGGCCAGGAC\n    +SRR578577.3 C0HLAACXX120407:2:1110:7566:40229 length=101\n    ???;:A;;C:D?AG<EFBDG<3CF:F><CCDHI>GFFEGEFFEGE:D0?6?D*/.8-;>AC=FDD=@CAEE=>?CAE@B@@BD>ABB;;>5>;;>?#####\n    \nNotice that each read takes up 4 lines, where\n\n    @unique_identifier length=101\n    [genomic sequence]\n    +unique_identifier length=101\n    [ASCII-encoded PHRED quality score]\n\nLet's break the quality down a bit.\n\n### Sequencing quality scores\n\nThe quality of base calling for each position in the read is encoded as a score $Q$ from 1 to 40. Defining $p$ as the probability of incorrect base calling, then\n\n$\nQ = -10 \\log_{10}(p)\n$\n\nGiven any score, we can back-calculate the probability of an incorrect base by using our understanding of logarithms.\n\n$$\n\\begin{align}\n40 &= -10 \\log_{10}(p)\\\\\n\\frac{40}{-10} &= \\frac{-10}{-10} \\log_{10}(p)\\\\\n-4 &= \\log_{10}(p)\\\\\n10^{-4} &= 10^{\\log_{10}(p)}\\\\\n10^{-4} &= p\n\\end{align}\n$$\n\nThus the best score of 40 represents the lowest probability of incorrect base calling, $p=10^{-4}$.\n\n#### Exercise 1\n\nWhat is the probabilty of incorrect base calling for a score of 39? For 31?\n\n### PHRED64 quality scores\n\nBecause \"40\" takes up two spaces, instead of using numbers the score is encoded using letters in a system called \"ASCII.\" You already know that computers store information in zeros and ones, which can be turned into numbers, well, the letter \"!\" (exclamation point) represents the number 64 and acts as the lowest value for the quality scores, while \n\n    !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHI\n\n* Input: Raw `.fastq` files\n* Program: FASTQC, SeQC\n* Output: Report (`.html`) and plots (`.png`) of library quality\n\nExample:\n\n    $ fastqc $HOME/projects/differentiation/raw_data/sample01.R1.fastq -o $HOME/projects/differentiation/processed_data\n\n\n## 2. Adapter trimming\n\n* Input: Raw `.fastq` files\n* Program: `cutadapt`, `trimgalore`\n* Output: Adapter trimmed `.fastq` files\n\nExample:\n\n    cutadapt \\\n        # format of the input files \\\n        -f fastq  \\\n        # Maximum number of times an adapter sequence can be removed \\\n        --times 2 \\\n        # Maximum error rate in adapter \\\n        -e 0.0  \\\n        # Minimum overlap length \\\n        -O 5  \\\n        # Minimum sequencing quality \\\n        --quality-cutoff 6 \\\n        # Minimum read length \\\n        -m 18 \\\n        # Adapters that could appear anywhere in the sequencing read (5' end or 3' end) \\\n        -b TCGTATGCCGTCTTCTGCTTG \\\n        -b ATCTCGTATGCCGTCTTCTGCTTG \\\n        -b CGACAGGTTCAGAGTTCTACAGTCCGACGATC \\\n        -b GATCGGAAGAGCACACGTCTGAACTCCAGTCAC \\\n        -b AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA \\\n        -b TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT \\\n        # Read 1 output \\\n        -o $HOME/projects/shalek2013/processed_data/S10_R1.polyATrim.adapterTrim.fastq \\\n        # Read 2 output \\\n        -p $HOME/projects/shalek2013/processed_data/S10_R2.polyATrim.adapterTrim.fastq \\\n        # Read 1 input \\\n        $HOME/projects/shalek2013/raw_data/S10_R1.fastq.gz \\\n        # Read 2 input \\\n        $HOME/projects/shalek2013/raw_data/S10_R2.fastq.gz \\\n        # Statistics about how many adapters were removed\n        > $HOME/projects/shalek2013/processed_data/S10_R2.polyATrim.adapterTrim.metrics\n\n## 3. Map to repetitive elements\n\n### `.sam` file format\n\n\"Sequence alignment map\"\n\n\n* Input: Trimmed `.fastq` files and repetitive element \"genome\"\n* Program: `STAR`\n* Output: Alignment `.sam` and unaligned `.fastq`\n\nExample:\n\n    STAR --genomeDir $HOME/genomes/RepBase18.05.fasta/STAR/ --readFilesIn \\\n        $HOME/projects/differentiation/raw_data/sample01.R1.fastq \\\n        $HOME/projects/differentiation/raw_data/sample01.R2.fastq \\\n        --outFileNamePrefix $HOME/projects/differentiation/processed_data/sample01.repetitive. \\\n        # Save unmapped files as fastq\n        --outReadsUnmapped Fastx\n\n## 4. Map to genome\n\n* Input: `.fastq` of trimmed reads which didn't align to repetitive elements\n* Program: `STAR`\n* Output: Alignment `.sam`\n\nExample:\n    \n    STAR --genomeDir $HOME/genomes/hg19/gencode/v20/star \\\n        --readFilesIn \\\n        $HOME/projects/differentiation/processed_data/sample01.repetitive.Unmapped.out.mate1 \\\n        $HOME/projects/differentiation/processed_data/sample01.repetitive.Unmapped.out.mate2 \\\n        --outFileNamePrefix \\\n        $HOME/projects/differentiation/processed_data/sample01.rmRepetitive.\n\n### Exercise 2\n\nRun STAR with the following parameters:\n\n* genome directory: `$HOME/genomes/mm10/gencode/m8/star_chr11`\n* Fastq files: `$HOME/projects/shalek2013/raw_data/S10.chr11.R1.fastq` and `$HOME/projects/shalek2013/raw_data/S10.chr11.R2.fastq`\n* Output prefix: `$HOME/projects/shalek2013/processed_data/S10.chr11.`\n\n#### Questions\n1. What files were created? \n2. In what file can you find the percentage of mapped reads?\n3. In what file can you find the debugging information for the program, like the full command, the files used, and the values of all the parameters?\n\n## 5. Create sorted, indexed `.bam` file\n\n\n### `.bam` file format\n\nThe `.bam` file format is a compressed (aka \"binary\" - meaning not human readable) version of the `.sam` format.\n\nAll programs downstream of mapping require a sorted, indexed `.bam` file. You can also do these steps with your repetitive element-aligned `.sam` file if \n\nThink of creating a sorted, indexed bam file like making a dictionary. \n\nA raw aligned `.sam` file like a jumble of words in random order:\n\n    single\n    cell\n    bioinformatics\n    experiment\n    beyonce\n    sequencing\n    library\n    prep\n\nSorting puts the words into alphabet order:\n\n    beyonce\n    bioinformatics\n    cell\n    experiment\n    library\n    prep\n    sequencing\n    single\n\nAnd indexing is like adding the alphabet tabs in a dictionary:\n\n    B:\n        beyonce\n        bioinformatics\n    C:\n        cell\n    E:\n        experiment\n    L: \n        library\n    P:\n        prep\n    S:\n        sequencing\n        single\n\nInstead of letters, indexing adds \"chromosome tabs\" so each program will know where, say chromosome 7 (`chr7`) starts and can jump to it right away.\n\n### 5.0 Convert `.sam` to `.bam`\n\n* Input: `.sam` of aligned reads\n* Program: `samtools view -b`\n    * `-b` flag forces output to be `.bam`\n* Output: Compressed `.bam` file\n\nExample (`samtools v1.3.1`): \n\n    samtools view -b sample01.sam > sample01.sorted.bam\n\n#### Exercise 3\n\nConvert your `.sam` file to `.bam`\n\n### 5.1 Sort `.sam`\n\nFor deeply sequenced samples (>50 million reads), this will take quite some time\n\n* Input: `.sam` of aligned reads\n* Program: `samtools sort`\n* Output: Sorted `.bam`\n\nExample (`samtools v1.3.1`): \n\n    samtools sort sample01.bam > sample01.sorted.bam\n    \n#### Exercise 4\n\nSort your `.bam` file  \n\n### 5.2 Index `.sam`\n\nIndexing only works with sorted bam files\n\n* Input: `.bam` of *sorted*, aligned reads\n* Program: `samtools sort`\n* Output: Sorted `.bam`\n\nExample (`samtools v1.3.1`): \n\n    samtools index sample01.sorted.bam\n\nThis creates the file `sample01.sorted.bam.bai`\n    \n#### Exercise 5\n\nIndex your `.bam` file\n\n\n## 6. Quantify gene expression\n\n### Units\n\nTPM, FPKM, what? Check out this blog post on [What the FPKM?](https://haroldpimentel.wordpress.com/2014/05/08/what-the-fpkm-a-review-rna-seq-expression-units/) to learn about RNA-seq units in depth.\n\n### File types\n\nGene annotation files are either `.gtf` or `.gff` format. We'll use the [GENCODE GTF](http://www.gencodegenes.org/data_format.html) format for our purposes. A subset of the gtf format is shown below. Notice the third column specifies the type of feature.\n\n```\nchr11   HAVANA  gene    3125904 3131004 .       +       .       gene_id \"ENSMUSG00000082286.10\"; gene_type \"transcribed_unprocessed_pseudogene\"; gene_status \"KNOWN\"; gene_name \"Pisd-ps1\"; level 2; havana_gene \"OTTMUSG00000000759.2\";\nchr11   HAVANA  transcript      3125904 3129396 .       +       .       gene_id \"ENSMUSG00000082286.10\"; transcript_id \"ENSMUST00000145164.7\"; gene_type \"transcribed_unprocessed_pseudogene\"; gene_status \"KNOWN\"; gene_name \"Pisd-ps1\"; transcript_type \"processed_transcript\"; transcript_status \"KNOWN\"; transcript_name \"Pisd-ps1-004\"; level 2; tag \"basic\"; transcript_support_level \"1\"; havana_gene \"OTTMUSG00000000759.2\"; havana_transcript \"OTTMUST00000086908.1\";\nchr11   HAVANA  exon    3125904 3126058 .       +       .       gene_id \"ENSMUSG00000082286.10\"; transcript_id \"ENSMUST00000145164.7\"; gene_type \"transcribed_unprocessed_pseudogene\"; gene_status \"KNOWN\"; gene_name \"Pisd-ps1\"; transcript_type \"processed_transcript\"; transcript_status \"KNOWN\"; transcript_name \"Pisd-ps1-004\"; exon_number 1; exon_id \"ENSMUSE00000728833.1\"; level 2; tag \"basic\"; transcript_support_level \"1\"; havana_gene \"OTTMUSG00000000759.2\"; havana_transcript \"OTTMUST00000086908.1\";\nchr11   HAVANA  exon    3127479 3127644 .       +       .       gene_id \"ENSMUSG00000082286.10\"; transcript_id \"ENSMUST00000145164.7\"; gene_type \"transcribed_unprocessed_pseudogene\"; gene_status \"KNOWN\"; gene_name \"Pisd-ps1\"; transcript_type \"processed_transcript\"; transcript_status \"KNOWN\"; transcript_name \"Pisd-ps1-004\"; exon_number 2; exon_id \"ENSMUSE00000708691.1\"; level 2; tag \"basic\"; transcript_support_level \"1\"; havana_gene \"OTTMUSG00000000759.2\"; havana_transcript \"OTTMUST00000086908.1\";\n```\n\n### How to run the programs\n\n* Input: `.bam` of *sorted*, aligned reads\n* Program: `featureCounts`, Salmon, HTSeq, ...\n* Output: some kind of table (comma- or tab-delimited file)\n\nExample:\n    \n    featureCounts -a annotation.gtf -o sample01.featurecounts.txt sample1.sorted.bam\n\n#### Exercise 5\n\nRun `featureCounts` on your sorted, indexed `.bam` file\n\n* Annotation file: `$HOME/genomes/mm10/gencode/m8/gencode.vM8.basic.annotation.chr11.gtf`\n\n\n## 7. Create gene expression matrix\n\n* Input: Individual cells' gene expression counts\n* Program: R, Python, `awk`, `cut`, `paste`\n* Output: A matrix of size (`n_samples` $\\times$ `n_features`)\n\n## 8. Cell-level QC\n\n* Input: Gene expression matrix\n* Program: R, Python, MATLAB\n* Possible criteria: \n    * Low number of reads mapped (indicates lowly sequenced)\n    * Low percentage of reads mapped (indicates poor library)\n    * High mitochondrial:genome ratio (indicates dying cell)\n    * High spike-in:genome ratio (indicates low cellular mRNA content)\n    * Low numbers of expressed genes (indicates low detection)\n* Output: Gene expression matrix with \"bad\" cells removed\n\n## 9. Gene-level QC\n\n* Input: Gene expression matrix with \"bad\" cells removed\n* Program: R, Python, MATLAB\n* Possible criteria:\n    * Low expression (e.g. $< 1$ TPM in $> 5$ cells)\n* Output: Gene expression matrix with \"bad\" genes removed\n\n\n## 10. Exploratory analysis\n\n* Input: Gene expression matrix with \"bad\" genes removed\n* Program: R, Python, MATLAB\n* Possible algorithms:\n    * Dimensionality reduction\n        * PCA\n        * ICA\n        * MDS\n        * t-SNE\n* Output: plots\n\n\n## 11. Subpopulation identification\n\n* Input: Gene expression matrix with \"bad\" genes removed\n* Program: R, Python, MATLAB\n* Possible algorithms:\n    * Clustering\n        * Hierarchical clustering\n        * $K$-means\n    * Pseudo-time\n        * Monocle\n        * Waterfall\n        * Wanderlust\n        * Wishbone\n* Output: plots, cluster identification\n\n\n## 12. Subpopulation characterization\n\n* Input: Gene expression matrix with \"bad\" genes removed, cluster or psuedotime ordering\n* Program: R, Python, MATLAB\n* Possible algorithms:\n    * Differential expression\n        * DESeq\n        * scDE (\"single-cell differential expression\")\n    * Classifiers\n        * Support Vector Machines (SVM)\n        * DecisionTree classifiers\n    * Clustering\n        * Hierarchical clustering on ordered gene expression\n* Output: Lists of genes\n\n## 13. Interpretation\n\n* Input: Lists of genes\n* Program: Biologist, Gene Ontology (e.g. DAVID) or other gene set enrichment analysis, PubMed\n* Output: Biological description of populations\n\n", "meta": {"hexsha": "cefc746d5d9ccde07c1e9fe90a441dd569a30737", "size": 24327, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/1.1_Overview_of_analysis_steps.ipynb", "max_stars_repo_name": "YeoLab/single-cell-bioinformatics", "max_stars_repo_head_hexsha": "cbf88c142432390106ce4670d593bae01e8c6963", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 77, "max_stars_repo_stars_event_min_datetime": "2016-06-01T13:35:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T14:40:20.000Z", "max_issues_repo_path": "notebooks/1.1_Overview_of_analysis_steps.ipynb", "max_issues_repo_name": "HabibMrad/single-cell-bioinformatics", "max_issues_repo_head_hexsha": "cbf88c142432390106ce4670d593bae01e8c6963", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/1.1_Overview_of_analysis_steps.ipynb", "max_forks_repo_name": "HabibMrad/single-cell-bioinformatics", "max_forks_repo_head_hexsha": "cbf88c142432390106ce4670d593bae01e8c6963", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 34, "max_forks_repo_forks_event_min_datetime": "2016-05-23T18:41:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T01:53:21.000Z", "avg_line_length": 46.6928982726, "max_line_length": 536, "alphanum_fraction": 0.5975664899, "converted": true, "num_tokens": 5431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05108273551243586, "lm_q2_score": 0.08389037896680751, "lm_q1q2_score": 0.0042853500407994405}}
{"text": "<a href=\"https://colab.research.google.com/github/ebitdad7/pegasus/blob/master/NLP_sum_project.ipynb\" target=\"_parent\"></a>\n\n\n```\n!git clone https://github.com/ebitdad7/pegasus.git\n%cd pegasus\n!export PYTHONPATH=.\n```\n\n    Cloning into 'pegasus'...\n    remote: Enumerating objects: 171, done.\u001b[K\n    remote: Total 171 (delta 0), reused 0 (delta 0), pack-reused 171\u001b[K\n    Receiving objects: 100% (171/171), 353.09 KiB | 5.60 MiB/s, done.\n    Resolving deltas: 100% (56/56), done.\n    /content/pegasus\n\n\n\n```\n!pip3 install -r requirements.txt\n```\n\n    Requirement already satisfied: absl-py in /usr/local/lib/python3.6/dist-packages (from -r requirements.txt (line 1)) (0.8.1)\n    Collecting mock\n      Downloading https://files.pythonhosted.org/packages/cd/74/d72daf8dff5b6566db857cfd088907bb0355f5dd2914c4b3ef065c790735/mock-4.0.2-py3-none-any.whl\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from -r requirements.txt (line 3)) (1.18.5)\n    Collecting rouge-score\n      Downloading https://files.pythonhosted.org/packages/1f/56/a81022436c08b9405a5247b71635394d44fe7e1dbedc4b28c740e09c2840/rouge_score-0.0.4-py2.py3-none-any.whl\n    Collecting sacrebleu\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/23/d3/be980ad7cda7c4bbfa97ee3de062fb3014fc1a34d6dd5b82d7b92f8d6522/sacrebleu-1.4.13-py3-none-any.whl (43kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 4.4MB/s \n    \u001b[?25hCollecting sentencepiece\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/d4/a4/d0a884c4300004a78cca907a6ff9a5e9fe4f090f5d95ab341c53d28cbc58/sentencepiece-0.1.91-cp36-cp36m-manylinux1_x86_64.whl (1.1MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.1MB 9.1MB/s \n    \u001b[?25hCollecting tensorflow-text==1.15.0rc0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/81/2c/57a6cc36f0ee1acf466a71048e2a0a2a01742eef505b3195d0fa27d87968/tensorflow_text-1.15.0rc0-cp36-cp36m-manylinux1_x86_64.whl (8.6MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 8.6MB 41.3MB/s \n    \u001b[?25hCollecting tensor2tensor==1.15.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/0f/a6/0f6a95a5548cf9fbfed0bbec69959355bda594e85298ebbba5f808ca0fc5/tensor2tensor-1.15.0-py2.py3-none-any.whl (1.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.4MB 50.5MB/s \n    \u001b[?25hCollecting tfds-nightly\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/14/84/04fb060493b84e4cc62562b2ca4a93098207c54d10eafac0c0de26cfae1c/tfds_nightly-3.2.1.dev202009020105-py3-none-any.whl (3.5MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.5MB 48.0MB/s \n    \u001b[?25hCollecting tensorflow-gpu==1.15.2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/32/ca/58e40e5077fa2a92004f398d705a288e958434f123938f4ce75ffe25b64b/tensorflow_gpu-1.15.2-cp36-cp36m-manylinux2010_x86_64.whl (411.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 411.0MB 37kB/s \n    \u001b[?25hRequirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from absl-py->-r requirements.txt (line 1)) (1.15.0)\n    Requirement already satisfied: nltk in /usr/local/lib/python3.6/dist-packages (from rouge-score->-r requirements.txt (line 4)) (3.2.5)\n    Collecting portalocker\n      Downloading https://files.pythonhosted.org/packages/89/a6/3814b7107e0788040870e8825eebf214d72166adf656ba7d4bf14759a06a/portalocker-2.0.0-py2.py3-none-any.whl\n    Collecting tensorflow<1.16,>=1.15.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/02/36/9a02e27f0ec248b676a380ffe910c1858e3af3027c0d4d513dd0b56a5613/tensorflow-1.15.3-cp36-cp36m-manylinux2010_x86_64.whl (110.5MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 110.5MB 38kB/s \n    \u001b[?25hCollecting mesh-tensorflow\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/52/6b/d01247d9a9b49389599a28e17782ec1d3d45413cedbfe8e90aad46835329/mesh_tensorflow-0.1.16-py3-none-any.whl (305kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 307kB 49.2MB/s \n    \u001b[?25hCollecting gevent\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/05/18/3932900a42d7010cc63529fc5cb7a5a20fb61878d1721d0d4387567d5973/gevent-20.6.2-cp36-cp36m-manylinux2010_x86_64.whl (5.3MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5.3MB 6.9MB/s \n    \u001b[?25hCollecting gunicorn\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/69/ca/926f7cd3a2014b16870086b2d0fdc84a9e49473c68a8dff8b57f7c156f43/gunicorn-20.0.4-py2.py3-none-any.whl (77kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 81kB 8.3MB/s \n    \u001b[?25hRequirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (2.10.0)\n    Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.16.0)\n    Requirement already satisfied: flask in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.1.2)\n    Requirement already satisfied: gin-config in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.3.0)\n    Collecting tf-slim\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/02/97/b0f4a64df018ca018cc035d44f2ef08f91e2e8aa67271f6f19633a015ff7/tf_slim-1.1.0-py2.py3-none-any.whl (352kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 358kB 57.4MB/s \n    \u001b[?25hRequirement already satisfied: google-api-python-client in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.7.12)\n    Requirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (2.23.0)\n    Requirement already satisfied: oauth2client in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (4.1.3)\n    Collecting tensorflow-gan\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/0c/2e/62922111d7d50e1900e3030764743ea7735540ce103b3ab30fd5cd2d8a2b/tensorflow_gan-2.0.0-py2.py3-none-any.whl (365kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 368kB 57.1MB/s \n    \u001b[?25hRequirement already satisfied: Pillow in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (7.0.0)\n    Collecting bz2file\n      Downloading https://files.pythonhosted.org/packages/61/39/122222b5e85cd41c391b68a99ee296584b2a2d1d233e7ee32b4532384f2d/bz2file-0.98.tar.gz\n    Requirement already satisfied: gym in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.17.2)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.1.1)\n    Requirement already satisfied: tensorflow-datasets in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (2.1.0)\n    Requirement already satisfied: opencv-python in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (4.1.2.30)\n    Collecting pypng\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/bc/fb/f719f1ac965e2101aa6ea6f54ef8b40f8fbb033f6ad07c017663467f5147/pypng-0.0.20.tar.gz (649kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 655kB 45.0MB/s \n    \u001b[?25hRequirement already satisfied: dopamine-rl in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.0.5)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.4.1)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (4.41.1)\n    Collecting kfac\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/6c/34/d2ff705c34a6250498e41766fa682fb0be168b2f2940cd20e5e2a4f40261/kfac-0.2.2-py2.py3-none-any.whl (191kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 194kB 41.4MB/s \n    \u001b[?25hCollecting tensorflow-probability==0.7.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/3e/3a/c10b6c22320531c774402ac7186d1b673374e2a9d12502cbc8d811e4601c/tensorflow_probability-0.7.0-py2.py3-none-any.whl (981kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 983kB 35.0MB/s \n    \u001b[?25hRequirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (0.7)\n    Requirement already satisfied: tensorflow-metadata in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (0.23.0)\n    Requirement already satisfied: attrs>=18.1.0 in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (20.1.0)\n    Requirement already satisfied: wrapt in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (1.12.1)\n    Requirement already satisfied: dm-tree in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (0.1.5)\n    Requirement already satisfied: dill in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (0.3.2)\n    Collecting importlib-resources; python_version < \"3.9\"\n      Downloading https://files.pythonhosted.org/packages/ba/03/0f9595c0c2ef12590877f3c47e5f579759ce5caf817f8256d5dcbd8a1177/importlib_resources-3.0.0-py2.py3-none-any.whl\n    Requirement already satisfied: termcolor in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (1.1.0)\n    Requirement already satisfied: promise in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (2.3)\n    Requirement already satisfied: protobuf>=3.6.1 in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (3.12.4)\n    Collecting gast==0.2.2\n      Downloading https://files.pythonhosted.org/packages/4e/35/11749bf99b2d4e3cceb4d55ca22590b0d7c2c62b9de38ac4a4a7f4687421/gast-0.2.2.tar.gz\n    Collecting keras-applications>=1.0.8\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/71/e3/19762fdfc62877ae9102edf6342d71b28fbfd9dea3d2f96a882ce099b03f/Keras_Applications-1.0.8-py3-none-any.whl (50kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 5.9MB/s \n    \u001b[?25hCollecting tensorflow-estimator==1.15.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/de/62/2ee9cd74c9fa2fa450877847ba560b260f5d0fb70ee0595203082dafcc9d/tensorflow_estimator-1.15.1-py2.py3-none-any.whl (503kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 512kB 55.4MB/s \n    \u001b[?25hRequirement already satisfied: astor>=0.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (0.8.1)\n    Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (1.31.0)\n    Collecting tensorboard<1.16.0,>=1.15.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1e/e9/d3d747a97f7188f48aa5eda486907f3b345cd409f0a0850468ba867db246/tensorboard-1.15.0-py3-none-any.whl (3.8MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.8MB 53.1MB/s \n    \u001b[?25hRequirement already satisfied: wheel>=0.26; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (0.35.1)\n    Requirement already satisfied: google-pasta>=0.1.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (0.2.0)\n    Requirement already satisfied: keras-preprocessing>=1.0.5 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (1.1.2)\n    Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (3.3.0)\n    Collecting zope.event\n      Downloading https://files.pythonhosted.org/packages/c5/96/361edb421a077a4c208b4a5c212737d78ae03ce67fbbcd01621c49f332d1/zope.event-4.4-py2.py3-none-any.whl\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from gevent->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (49.6.0)\n    Collecting zope.interface\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/57/33/565274c28a11af60b7cfc0519d46bde4125fcd7d32ebc0a81b480d0e8da6/zope.interface-5.1.0-cp36-cp36m-manylinux2010_x86_64.whl (234kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 235kB 54.5MB/s \n    \u001b[?25hCollecting greenlet>=0.4.16; platform_python_implementation == \"CPython\"\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/7e/a4/0d8685c98986326534b0753a8b92b3082bc9df42b348bc50d6c69839c9f9/greenlet-0.4.16-cp36-cp36m-manylinux1_x86_64.whl (44kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 5.9MB/s \n    \u001b[?25hRequirement already satisfied: itsdangerous>=0.24 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.1.0)\n    Requirement already satisfied: click>=5.1 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (7.1.2)\n    Requirement already satisfied: Werkzeug>=0.15 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.0.1)\n    Requirement already satisfied: Jinja2>=2.10.1 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (2.11.2)\n    Requirement already satisfied: google-auth-httplib2>=0.0.3 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.0.4)\n    Requirement already satisfied: httplib2<1dev,>=0.17.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.17.4)\n    Requirement already satisfied: uritemplate<4dev,>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (3.0.1)\n    Requirement already satisfied: google-auth>=1.4.1 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.17.2)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.24.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (2020.6.20)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (3.0.4)\n    Requirement already satisfied: pyasn1-modules>=0.0.5 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.2.8)\n    Requirement already satisfied: rsa>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (4.6)\n    Requirement already satisfied: pyasn1>=0.1.7 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.4.8)\n    Requirement already satisfied: tensorflow-hub>=0.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gan->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.9.0)\n    Requirement already satisfied: cloudpickle<1.4.0,>=1.2.0 in /usr/local/lib/python3.6/dist-packages (from gym->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.3.0)\n    Requirement already satisfied: pyglet<=1.5.0,>=1.4.0 in /usr/local/lib/python3.6/dist-packages (from gym->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.5.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.1.0)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.6/dist-packages (from tensorflow-probability==0.7.0->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (4.4.2)\n    Requirement already satisfied: googleapis-common-protos in /usr/local/lib/python3.6/dist-packages (from tensorflow-metadata->tfds-nightly->-r requirements.txt (line 9)) (1.52.0)\n    Requirement already satisfied: zipp>=0.4; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from importlib-resources; python_version < \"3.9\"->tfds-nightly->-r requirements.txt (line 9)) (3.1.0)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard<1.16.0,>=1.15.0->tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (3.2.2)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.6/dist-packages (from Jinja2>=2.10.1->flask->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.1.1)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth>=1.4.1->google-api-python-client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (4.1.1)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from markdown>=2.6.8->tensorboard<1.16.0,>=1.15.0->tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (1.7.0)\n    Building wheels for collected packages: bz2file, pypng, gast\n      Building wheel for bz2file (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for bz2file: filename=bz2file-0.98-cp36-none-any.whl size=6884 sha256=a949caad97da086adeda92a5b1cc65024f27252e5f790686cecfcca1a61b53c1\n      Stored in directory: /root/.cache/pip/wheels/81/75/d6/e1317bf09bf1af5a30befc2a007869fa6e1f516b8f7c591cb9\n      Building wheel for pypng (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pypng: filename=pypng-0.0.20-cp36-none-any.whl size=67162 sha256=3919ca6db9446df3b3ac4d99d01678dc3afa7788eca8bdbcc2c8bb43f02bc174\n      Stored in directory: /root/.cache/pip/wheels/41/6b/ef/0493b536b6d4722c2ae9486691b1d49b922b9877922beeabb3\n      Building wheel for gast (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for gast: filename=gast-0.2.2-cp36-none-any.whl size=7542 sha256=2ffe49cb28585b72df65c84ad992deb8c5bb491e8e10189f61b6fb5f33f8b830\n      Stored in directory: /root/.cache/pip/wheels/5c/2e/7e/a1d4d4fcebe6c381f378ce7743a3ced3699feb89bcfbdadadd\n    Successfully built bz2file pypng gast\n    \u001b[31mERROR: kfac 0.2.2 has requirement tensorflow-probability==0.8, but you'll have tensorflow-probability 0.7.0 which is incompatible.\u001b[0m\n    Installing collected packages: mock, rouge-score, portalocker, sacrebleu, sentencepiece, gast, keras-applications, tensorflow-estimator, tensorboard, tensorflow, tensorflow-text, mesh-tensorflow, zope.event, zope.interface, greenlet, gevent, gunicorn, tf-slim, tensorflow-probability, tensorflow-gan, bz2file, pypng, kfac, tensor2tensor, importlib-resources, tfds-nightly, tensorflow-gpu\n      Found existing installation: gast 0.3.3\n        Uninstalling gast-0.3.3:\n          Successfully uninstalled gast-0.3.3\n      Found existing installation: tensorflow-estimator 2.3.0\n        Uninstalling tensorflow-estimator-2.3.0:\n          Successfully uninstalled tensorflow-estimator-2.3.0\n      Found existing installation: tensorboard 2.3.0\n        Uninstalling tensorboard-2.3.0:\n          Successfully uninstalled tensorboard-2.3.0\n      Found existing installation: tensorflow 2.3.0\n        Uninstalling tensorflow-2.3.0:\n          Successfully uninstalled tensorflow-2.3.0\n      Found existing installation: tensorflow-probability 0.11.0\n        Uninstalling tensorflow-probability-0.11.0:\n          Successfully uninstalled tensorflow-probability-0.11.0\n    Successfully installed bz2file-0.98 gast-0.2.2 gevent-20.6.2 greenlet-0.4.16 gunicorn-20.0.4 importlib-resources-3.0.0 keras-applications-1.0.8 kfac-0.2.2 mesh-tensorflow-0.1.16 mock-4.0.2 portalocker-2.0.0 pypng-0.0.20 rouge-score-0.0.4 sacrebleu-1.4.13 sentencepiece-0.1.91 tensor2tensor-1.15.0 tensorboard-1.15.0 tensorflow-1.15.3 tensorflow-estimator-1.15.1 tensorflow-gan-2.0.0 tensorflow-gpu-1.15.2 tensorflow-probability-0.7.0 tensorflow-text-1.15.0rc0 tf-slim-1.1.0 tfds-nightly-3.2.1.dev202009020105 zope.event-4.4 zope.interface-5.1.0\n\n\n\n```\n!sudo apt-get install gcc python-dev python-setuptools libffi-dev\n!sudo apt-get install python-pip\n!sudo pip install gsutil\n```\n\n    Reading package lists... Done\n    Building dependency tree       \n    Reading state information... Done\n    python-dev is already the newest version (2.7.15~rc1-1).\n    gcc is already the newest version (4:7.4.0-1ubuntu2.3).\n    gcc set to manually installed.\n    The following package was automatically installed and is no longer required:\n      libnvidia-common-440\n    Use 'sudo apt autoremove' to remove it.\n    The following additional packages will be installed:\n      python-pkg-resources\n    Suggested packages:\n      python-setuptools-doc\n    The following NEW packages will be installed:\n      libffi-dev python-pkg-resources python-setuptools\n    0 upgraded, 3 newly installed, 0 to remove and 39 not upgraded.\n    Need to get 613 kB of archives.\n    After this operation, 2,336 kB of additional disk space will be used.\n    Get:1 http://archive.ubuntu.com/ubuntu bionic/main amd64 python-pkg-resources all 39.0.1-2 [128 kB]\n    Get:2 http://archive.ubuntu.com/ubuntu bionic/main amd64 python-setuptools all 39.0.1-2 [329 kB]\n    Get:3 http://archive.ubuntu.com/ubuntu bionic/main amd64 libffi-dev amd64 3.2.1-8 [156 kB]\n    Fetched 613 kB in 1s (797 kB/s)\n    debconf: unable to initialize frontend: Dialog\n    debconf: (No usable dialog-like program is installed, so the dialog based frontend cannot be used. at /usr/share/perl5/Debconf/FrontEnd/Dialog.pm line 76, <> line 3.)\n    debconf: falling back to frontend: Readline\n    debconf: unable to initialize frontend: Readline\n    debconf: (This frontend requires a controlling tty.)\n    debconf: falling back to frontend: Teletype\n    dpkg-preconfigure: unable to re-open stdin: \n    Selecting previously unselected package python-pkg-resources.\n    (Reading database ... 144579 files and directories currently installed.)\n    Preparing to unpack .../python-pkg-resources_39.0.1-2_all.deb ...\n    Unpacking python-pkg-resources (39.0.1-2) ...\n    Selecting previously unselected package python-setuptools.\n    Preparing to unpack .../python-setuptools_39.0.1-2_all.deb ...\n    Unpacking python-setuptools (39.0.1-2) ...\n    Selecting previously unselected package libffi-dev:amd64.\n    Preparing to unpack .../libffi-dev_3.2.1-8_amd64.deb ...\n    Unpacking libffi-dev:amd64 (3.2.1-8) ...\n    Setting up libffi-dev:amd64 (3.2.1-8) ...\n    Setting up python-pkg-resources (39.0.1-2) ...\n    Setting up python-setuptools (39.0.1-2) ...\n    Processing triggers for man-db (2.8.3-2ubuntu0.1) ...\n    Reading package lists... Done\n    Building dependency tree       \n    Reading state information... Done\n    The following package was automatically installed and is no longer required:\n      libnvidia-common-440\n    Use 'sudo apt autoremove' to remove it.\n    The following additional packages will be installed:\n      libpython-all-dev python-all python-all-dev python-asn1crypto\n      python-cffi-backend python-crypto python-cryptography python-dbus\n      python-enum34 python-gi python-idna python-ipaddress python-keyring\n      python-keyrings.alt python-pip-whl python-secretstorage python-six\n      python-wheel python-xdg\n    Suggested packages:\n      python-crypto-doc python-cryptography-doc python-cryptography-vectors\n      python-dbus-dbg python-dbus-doc python-enum34-doc python-gi-cairo\n      gnome-keyring libkf5wallet-bin gir1.2-gnomekeyring-1.0 python-fs\n      python-gdata python-keyczar python-secretstorage-doc\n    The following NEW packages will be installed:\n      libpython-all-dev python-all python-all-dev python-asn1crypto\n      python-cffi-backend python-crypto python-cryptography python-dbus\n      python-enum34 python-gi python-idna python-ipaddress python-keyring\n      python-keyrings.alt python-pip python-pip-whl python-secretstorage\n      python-six python-wheel python-xdg\n    0 upgraded, 20 newly installed, 0 to remove and 39 not upgraded.\n    Need to get 2,918 kB of archives.\n    After this operation, 8,540 kB of additional disk space will be used.\n    Get:1 http://archive.ubuntu.com/ubuntu bionic/main amd64 libpython-all-dev amd64 2.7.15~rc1-1 [1,092 B]\n    Get:2 http://archive.ubuntu.com/ubuntu bionic/main amd64 python-all amd64 2.7.15~rc1-1 [1,076 B]\n    Get:3 http://archive.ubuntu.com/ubuntu bionic/main amd64 python-all-dev amd64 2.7.15~rc1-1 [1,100 B]\n    Get:4 http://archive.ubuntu.com/ubuntu bionic/main amd64 python-asn1crypto all 0.24.0-1 [72.7 kB]\n    Get:5 http://archive.ubuntu.com/ubuntu bionic/main amd64 python-cffi-backend amd64 1.11.5-1 [63.4 kB]\n    Get:6 http://archive.ubuntu.com/ubuntu bionic/main amd64 python-crypto amd64 2.6.1-8ubuntu2 [244 kB]\n    Get:7 http://archive.ubuntu.com/ubuntu bionic/main amd64 python-enum34 all 1.1.6-2 [34.8 kB]\n    Get:8 http://archive.ubuntu.com/ubuntu bionic/main amd64 python-idna all 2.6-1 [32.4 kB]\n    Get:9 http://archive.ubuntu.com/ubuntu bionic/main amd64 python-ipaddress all 1.0.17-1 [18.2 kB]\n    Get:10 http://archive.ubuntu.com/ubuntu bionic/main amd64 python-six all 1.11.0-2 [11.3 kB]\n    Get:11 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 python-cryptography amd64 2.1.4-1ubuntu1.3 [221 kB]\n    Get:12 http://archive.ubuntu.com/ubuntu bionic/main amd64 python-dbus amd64 1.2.6-1 [90.2 kB]\n    Get:13 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 python-gi amd64 3.26.1-2ubuntu1 [197 kB]\n    Get:14 http://archive.ubuntu.com/ubuntu bionic/main amd64 python-secretstorage all 2.3.1-2 [11.8 kB]\n    Get:15 http://archive.ubuntu.com/ubuntu bionic/main amd64 python-keyring all 10.6.0-1 [30.6 kB]\n    Get:16 http://archive.ubuntu.com/ubuntu bionic/main amd64 python-keyrings.alt all 3.0-1 [16.7 kB]\n    Get:17 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 python-pip-whl all 9.0.1-2.3~ubuntu1.18.04.2 [1,653 kB]\n    Get:18 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 python-pip all 9.0.1-2.3~ubuntu1.18.04.2 [151 kB]\n    Get:19 http://archive.ubuntu.com/ubuntu bionic/universe amd64 python-wheel all 0.30.0-0.2 [36.4 kB]\n    Get:20 http://archive.ubuntu.com/ubuntu bionic/universe amd64 python-xdg all 0.25-4ubuntu1 [31.3 kB]\n    Fetched 2,918 kB in 1s (2,907 kB/s)\n    debconf: unable to initialize frontend: Dialog\n    debconf: (No usable dialog-like program is installed, so the dialog based frontend cannot be used. at /usr/share/perl5/Debconf/FrontEnd/Dialog.pm line 76, <> line 20.)\n    debconf: falling back to frontend: Readline\n    debconf: unable to initialize frontend: Readline\n    debconf: (This frontend requires a controlling tty.)\n    debconf: falling back to frontend: Teletype\n    dpkg-preconfigure: unable to re-open stdin: \n    Selecting previously unselected package libpython-all-dev:amd64.\n    (Reading database ... 144739 files and directories currently installed.)\n    Preparing to unpack .../00-libpython-all-dev_2.7.15~rc1-1_amd64.deb ...\n    Unpacking libpython-all-dev:amd64 (2.7.15~rc1-1) ...\n    Selecting previously unselected package python-all.\n    Preparing to unpack .../01-python-all_2.7.15~rc1-1_amd64.deb ...\n    Unpacking python-all (2.7.15~rc1-1) ...\n    Selecting previously unselected package python-all-dev.\n    Preparing to unpack .../02-python-all-dev_2.7.15~rc1-1_amd64.deb ...\n    Unpacking python-all-dev (2.7.15~rc1-1) ...\n    Selecting previously unselected package python-asn1crypto.\n    Preparing to unpack .../03-python-asn1crypto_0.24.0-1_all.deb ...\n    Unpacking python-asn1crypto (0.24.0-1) ...\n    Selecting previously unselected package python-cffi-backend.\n    Preparing to unpack .../04-python-cffi-backend_1.11.5-1_amd64.deb ...\n    Unpacking python-cffi-backend (1.11.5-1) ...\n    Selecting previously unselected package python-crypto.\n    Preparing to unpack .../05-python-crypto_2.6.1-8ubuntu2_amd64.deb ...\n    Unpacking python-crypto (2.6.1-8ubuntu2) ...\n    Selecting previously unselected package python-enum34.\n    Preparing to unpack .../06-python-enum34_1.1.6-2_all.deb ...\n    Unpacking python-enum34 (1.1.6-2) ...\n    Selecting previously unselected package python-idna.\n    Preparing to unpack .../07-python-idna_2.6-1_all.deb ...\n    Unpacking python-idna (2.6-1) ...\n    Selecting previously unselected package python-ipaddress.\n    Preparing to unpack .../08-python-ipaddress_1.0.17-1_all.deb ...\n    Unpacking python-ipaddress (1.0.17-1) ...\n    Selecting previously unselected package python-six.\n    Preparing to unpack .../09-python-six_1.11.0-2_all.deb ...\n    Unpacking python-six (1.11.0-2) ...\n    Selecting previously unselected package python-cryptography.\n    Preparing to unpack .../10-python-cryptography_2.1.4-1ubuntu1.3_amd64.deb ...\n    Unpacking python-cryptography (2.1.4-1ubuntu1.3) ...\n    Selecting previously unselected package python-dbus.\n    Preparing to unpack .../11-python-dbus_1.2.6-1_amd64.deb ...\n    Unpacking python-dbus (1.2.6-1) ...\n    Selecting previously unselected package python-gi.\n    Preparing to unpack .../12-python-gi_3.26.1-2ubuntu1_amd64.deb ...\n    Unpacking python-gi (3.26.1-2ubuntu1) ...\n    Selecting previously unselected package python-secretstorage.\n    Preparing to unpack .../13-python-secretstorage_2.3.1-2_all.deb ...\n    Unpacking python-secretstorage (2.3.1-2) ...\n    Selecting previously unselected package python-keyring.\n    Preparing to unpack .../14-python-keyring_10.6.0-1_all.deb ...\n    Unpacking python-keyring (10.6.0-1) ...\n    Selecting previously unselected package python-keyrings.alt.\n    Preparing to unpack .../15-python-keyrings.alt_3.0-1_all.deb ...\n    Unpacking python-keyrings.alt (3.0-1) ...\n    Selecting previously unselected package python-pip-whl.\n    Preparing to unpack .../16-python-pip-whl_9.0.1-2.3~ubuntu1.18.04.2_all.deb ...\n    Unpacking python-pip-whl (9.0.1-2.3~ubuntu1.18.04.2) ...\n    Selecting previously unselected package python-pip.\n    Preparing to unpack .../17-python-pip_9.0.1-2.3~ubuntu1.18.04.2_all.deb ...\n    Unpacking python-pip (9.0.1-2.3~ubuntu1.18.04.2) ...\n    Selecting previously unselected package python-wheel.\n    Preparing to unpack .../18-python-wheel_0.30.0-0.2_all.deb ...\n    Unpacking python-wheel (0.30.0-0.2) ...\n    Selecting previously unselected package python-xdg.\n    Preparing to unpack .../19-python-xdg_0.25-4ubuntu1_all.deb ...\n    Unpacking python-xdg (0.25-4ubuntu1) ...\n    Setting up python-idna (2.6-1) ...\n    Setting up python-pip-whl (9.0.1-2.3~ubuntu1.18.04.2) ...\n    Setting up python-asn1crypto (0.24.0-1) ...\n    Setting up python-crypto (2.6.1-8ubuntu2) ...\n    Setting up python-wheel (0.30.0-0.2) ...\n    Setting up libpython-all-dev:amd64 (2.7.15~rc1-1) ...\n    Setting up python-cffi-backend (1.11.5-1) ...\n    Setting up python-gi (3.26.1-2ubuntu1) ...\n    Setting up python-six (1.11.0-2) ...\n    Setting up python-enum34 (1.1.6-2) ...\n    Setting up python-dbus (1.2.6-1) ...\n    Setting up python-ipaddress (1.0.17-1) ...\n    Setting up python-pip (9.0.1-2.3~ubuntu1.18.04.2) ...\n    Setting up python-all (2.7.15~rc1-1) ...\n    Setting up python-xdg (0.25-4ubuntu1) ...\n    Setting up python-keyrings.alt (3.0-1) ...\n    Setting up python-all-dev (2.7.15~rc1-1) ...\n    Setting up python-cryptography (2.1.4-1ubuntu1.3) ...\n    Setting up python-secretstorage (2.3.1-2) ...\n    Setting up python-keyring (10.6.0-1) ...\n    Processing triggers for man-db (2.8.3-2ubuntu0.1) ...\n    Collecting gsutil\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/81/11/c0cfa621a145aa295eef992a5a7031ddea786f55222b57402fadf3f0ddea/gsutil-4.53.tar.gz (2.5MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.5MB 2.9MB/s \n    \u001b[?25hCollecting argcomplete>=1.9.4\n      Downloading https://files.pythonhosted.org/packages/89/4d/b8e035cca2c9b2484ac12d20e0fb68019e17f0b09918f2765e0a381127fb/argcomplete-1.12.0-py2.py3-none-any.whl\n    Requirement already satisfied: crcmod>=1.7 in /usr/local/lib/python3.6/dist-packages (from gsutil) (1.7)\n    Collecting fasteners>=0.14.1\n      Downloading https://files.pythonhosted.org/packages/18/bd/55eb2d6397b9c0e263af9d091ebdb756b15756029b3cededf6461481bc63/fasteners-0.15-py2.py3-none-any.whl\n    Collecting gcs-oauth2-boto-plugin>=2.7\n      Downloading https://files.pythonhosted.org/packages/f7/ab/3cc16742de84b76aa328c4b9e09fbf88447027827c12fb3913c5907be23b/gcs-oauth2-boto-plugin-2.7.tar.gz\n    Collecting google-apitools>=0.5.30\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/19/da/aefc4cf4c168b5d875344cd9dddc77e3a2d11986b630251af5ce47dd2843/google-apitools-0.5.31.tar.gz (173kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 174kB 28.6MB/s \n    \u001b[?25hCollecting httplib2>=0.18\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/b3/ad/d9d9331850ea5bd4f5cb8c650c0bfa119a4abd6b0ad7c45b6506bc979fc0/httplib2-0.18.1-py3-none-any.whl (95kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 102kB 9.1MB/s \n    \u001b[?25hCollecting google-reauth>=0.1.0\n      Downloading https://files.pythonhosted.org/packages/c3/2c/3eeab6508a7243ad83747dd1e273df21a798c5998813c83f482df90f5790/google_reauth-0.1.0-py2.py3-none-any.whl\n    Collecting mock==2.0.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/e6/35/f187bdf23be87092bd0f1200d43d23076cee4d0dec109f195173fd3ebc79/mock-2.0.0-py2.py3-none-any.whl (56kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 61kB 6.1MB/s \n    \u001b[?25hCollecting monotonic>=1.4\n      Downloading https://files.pythonhosted.org/packages/ac/aa/063eca6a416f397bd99552c534c6d11d57f58f2e94c14780f3bbf818c4cf/monotonic-1.5-py2.py3-none-any.whl\n    Collecting pyOpenSSL>=0.13\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/9e/de/f8342b68fa9e981d348039954657bdf681b2ab93de27443be51865ffa310/pyOpenSSL-19.1.0-py2.py3-none-any.whl (53kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 61kB 5.8MB/s \n    \u001b[?25hCollecting retry_decorator>=1.0.0\n      Downloading https://files.pythonhosted.org/packages/6e/e6/bedc75b264cbcbf6e6d0e5071d96d739f540fc09be31744a7a8824c02a8e/retry_decorator-1.1.1.tar.gz\n    Requirement already satisfied: six>=1.12.0 in /usr/local/lib/python3.6/dist-packages (from gsutil) (1.15.0)\n    Requirement already satisfied: importlib-metadata<2,>=0.23; python_version == \"3.6\" in /usr/local/lib/python3.6/dist-packages (from argcomplete>=1.9.4->gsutil) (1.7.0)\n    Requirement already satisfied: boto>=2.29.1 in /usr/local/lib/python3.6/dist-packages (from gcs-oauth2-boto-plugin>=2.7->gsutil) (2.49.0)\n    Requirement already satisfied: oauth2client>=2.2.0 in /usr/local/lib/python3.6/dist-packages (from gcs-oauth2-boto-plugin>=2.7->gsutil) (4.1.3)\n    Collecting pyu2f\n      Downloading https://files.pythonhosted.org/packages/b0/6d/0fd9107b92c792e62cdeaeca2dfe40928898509aba82d81656d53e610c64/pyu2f-0.1.4.tar.gz\n    Collecting pbr>=0.11\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/c1/a3/d439f338aa90edd5ad9096cd56564b44882182150e92148eb14ceb7488ba/pbr-5.5.0-py2.py3-none-any.whl (106kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 112kB 34.7MB/s \n    \u001b[?25hCollecting cryptography>=2.8\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/c0/9c/647e559a6e8be493dc2a7a5d15d26cb501ca60ec299b356f23839a673a83/cryptography-3.1-cp35-abi3-manylinux2010_x86_64.whl (2.6MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.6MB 22.2MB/s \n    \u001b[?25hRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata<2,>=0.23; python_version == \"3.6\"->argcomplete>=1.9.4->gsutil) (3.1.0)\n    Requirement already satisfied: pyasn1-modules>=0.0.5 in /usr/local/lib/python3.6/dist-packages (from oauth2client>=2.2.0->gcs-oauth2-boto-plugin>=2.7->gsutil) (0.2.8)\n    Requirement already satisfied: rsa>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from oauth2client>=2.2.0->gcs-oauth2-boto-plugin>=2.7->gsutil) (4.6)\n    Requirement already satisfied: pyasn1>=0.1.7 in /usr/local/lib/python3.6/dist-packages (from oauth2client>=2.2.0->gcs-oauth2-boto-plugin>=2.7->gsutil) (0.4.8)\n    Requirement already satisfied: cffi!=1.11.3,>=1.8 in /usr/local/lib/python3.6/dist-packages (from cryptography>=2.8->pyOpenSSL>=0.13->gsutil) (1.14.2)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.6/dist-packages (from cffi!=1.11.3,>=1.8->cryptography>=2.8->pyOpenSSL>=0.13->gsutil) (2.20)\n    Building wheels for collected packages: gsutil, gcs-oauth2-boto-plugin, google-apitools, retry-decorator, pyu2f\n      Building wheel for gsutil (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for gsutil: filename=gsutil-4.53-cp36-none-any.whl size=3331410 sha256=033c98cd6d184c0ef7f8721fb54e0d833319e5603bcd0aba89c06d55cbac379d\n      Stored in directory: /root/.cache/pip/wheels/da/f1/4d/713adadb691cf8e208c602a624e8cdabb8db6eb8e9f192978d\n      Building wheel for gcs-oauth2-boto-plugin (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for gcs-oauth2-boto-plugin: filename=gcs_oauth2_boto_plugin-2.7-cp36-none-any.whl size=23202 sha256=9e43d50ae0f3f4243fea40e56faa82afc5c48a39cb65ac04ab50c6db1826d9ea\n      Stored in directory: /root/.cache/pip/wheels/2e/6b/7c/bd86832ceb17e0ae3d362c44f461832452eeaacddfcf9128ee\n      Building wheel for google-apitools (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for google-apitools: filename=google_apitools-0.5.31-cp36-none-any.whl size=131042 sha256=c8ac1cdc9133c56bd80c844c5d8bc60173815aaa7940fd54bf80e89beb70a9be\n      Stored in directory: /root/.cache/pip/wheels/3b/43/31/09a9dad88d3aec6fed2d63bd35dfc532fca372e2edec5af5bf\n      Building wheel for retry-decorator (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for retry-decorator: filename=retry_decorator-1.1.1-py2.py3-none-any.whl size=3640 sha256=c3ac66d41eb65b029c4d570acc153f516fe93d7233ed1bcfecb61428b09ec6e0\n      Stored in directory: /root/.cache/pip/wheels/a1/70/30/4af820545aa19a0d96f969ef5ecebbb9743fd89cf00db43273\n      Building wheel for pyu2f (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pyu2f: filename=pyu2f-0.1.4-cp36-none-any.whl size=35212 sha256=2a12b48371bd244fe2ccde780e74cff4029a914a89dd4b138c19143ff0af57db\n      Stored in directory: /root/.cache/pip/wheels/dd/81/f3/e0def0e40af1ed1a9dc929629ec489fa56e584544208f09274\n    Successfully built gsutil gcs-oauth2-boto-plugin google-apitools retry-decorator pyu2f\n    Installing collected packages: argcomplete, monotonic, fasteners, pyu2f, google-reauth, httplib2, cryptography, pyOpenSSL, retry-decorator, gcs-oauth2-boto-plugin, google-apitools, pbr, mock, gsutil\n      Found existing installation: httplib2 0.17.4\n        Uninstalling httplib2-0.17.4:\n          Successfully uninstalled httplib2-0.17.4\n      Found existing installation: mock 4.0.2\n        Uninstalling mock-4.0.2:\n          Successfully uninstalled mock-4.0.2\n    Successfully installed argcomplete-1.12.0 cryptography-3.1 fasteners-0.15 gcs-oauth2-boto-plugin-2.7 google-apitools-0.5.31 google-reauth-0.1.0 gsutil-4.53 httplib2-0.18.1 mock-2.0.0 monotonic-1.5 pbr-5.5.0 pyOpenSSL-19.1.0 pyu2f-0.1.4 retry-decorator-1.1.1\n\n\n\n```\n!mkdir ckpt\n!gsutil cp -r gs://pegasus_ckpt ckpt/\n```\n\n    mkdir: cannot create directory \u2018ckpt\u2019: File exists\n    Copying gs://pegasus_ckpt/c4.unigram.newline.10pct.96000.model...\n    Copying gs://pegasus_ckpt/c4.unigram.newline.10pct.96000.vocab...\n    Copying gs://pegasus_ckpt/checkpoint...\n    Copying gs://pegasus_ckpt/model.ckpt-1500000.data-00000-of-00001...\n    \\ [4 files][  2.1 GiB/  2.1 GiB]   95.0 MiB/s                                   \n    ==> NOTE: You are performing a sequence of gsutil operations that may\n    run significantly faster if you instead use gsutil -m cp ... Please\n    see the -m section under \"gsutil help options\" for further information\n    about when gsutil -m can be advantageous.\n    \n    Copying gs://pegasus_ckpt/model.ckpt-1500000.index...\n    Copying gs://pegasus_ckpt/model.ckpt-1500000.meta...\n    Copying gs://pegasus_ckpt/aeslc/model.ckpt-32000.data-00000-of-00001...\n    Copying gs://pegasus_ckpt/aeslc/model.ckpt-32000.index...\n    Copying gs://pegasus_ckpt/aeslc/model.ckpt-32000.meta...\n    Copying gs://pegasus_ckpt/arxiv/model.ckpt-340000.data-00000-of-00001...\n    Copying gs://pegasus_ckpt/arxiv/model.ckpt-340000.index...\n    Copying gs://pegasus_ckpt/arxiv/model.ckpt-340000.meta...\n    Copying gs://pegasus_ckpt/big_patent/model.ckpt-480000.data-00000-of-00001...\n    Copying gs://pegasus_ckpt/big_patent/model.ckpt-480000.index...\n    Copying gs://pegasus_ckpt/big_patent/model.ckpt-480000.meta...\n    Copying gs://pegasus_ckpt/billsum/model.ckpt-180000.data-00000-of-00001...\n    Copying gs://pegasus_ckpt/billsum/model.ckpt-180000.index...\n    Copying gs://pegasus_ckpt/billsum/model.ckpt-180000.meta...\n    Copying gs://pegasus_ckpt/cnn_dailymail/model.ckpt-210000.data-00000-of-00001...\n    Copying gs://pegasus_ckpt/cnn_dailymail/model.ckpt-210000.index...\n    Copying gs://pegasus_ckpt/cnn_dailymail/model.ckpt-210000.meta...\n    Copying gs://pegasus_ckpt/gigaword/model.ckpt-300000.data-00000-of-00001...\n    Copying gs://pegasus_ckpt/gigaword/model.ckpt-300000.index...\n    Copying gs://pegasus_ckpt/gigaword/model.ckpt-300000.meta...\n    Copying gs://pegasus_ckpt/multi_news/model.ckpt-60000.data-00000-of-00001...\n    Copying gs://pegasus_ckpt/multi_news/model.ckpt-60000.index...\n    Copying gs://pegasus_ckpt/multi_news/model.ckpt-60000.meta...\n    Copying gs://pegasus_ckpt/newsroom/model.ckpt-190000.data-00000-of-00001...\n    Copying gs://pegasus_ckpt/newsroom/model.ckpt-190000.index...\n    Copying gs://pegasus_ckpt/newsroom/model.ckpt-190000.meta...\n    Copying gs://pegasus_ckpt/pubmed/model.ckpt-360000.data-00000-of-00001...\n    Copying gs://pegasus_ckpt/pubmed/model.ckpt-360000.index...\n    Copying gs://pegasus_ckpt/pubmed/model.ckpt-360000.meta...\n    Copying gs://pegasus_ckpt/reddit_tifu/model.ckpt-8000.data-00000-of-00001...\n    Copying gs://pegasus_ckpt/reddit_tifu/model.ckpt-8000.index...\n    Copying gs://pegasus_ckpt/reddit_tifu/model.ckpt-8000.meta...\n    Copying gs://pegasus_ckpt/wikihow/model.ckpt-180000.data-00000-of-00001...\n    Copying gs://pegasus_ckpt/wikihow/model.ckpt-180000.index...\n    Copying gs://pegasus_ckpt/wikihow/model.ckpt-180000.meta...\n    Copying gs://pegasus_ckpt/xsum/model.ckpt-30000.data-00000-of-00001...\n    Copying gs://pegasus_ckpt/xsum/model.ckpt-30000.index...\n    Copying gs://pegasus_ckpt/xsum/model.ckpt-30000.meta...\n    | [42 files][ 28.0 GiB/ 28.0 GiB]   52.4 MiB/s                                  \n    ==> NOTE: You are performing a sequence of gsutil operations that may\n    run significantly faster if you instead use gsutil -m cp ... Please\n    see the -m section under \"gsutil help options\" for further information\n    about when gsutil -m can be advantageous.\n    \n    \n    Operation completed over 42 objects/28.0 GiB.                                    \n\n\n# New Section\n\n\n```\n%cd /content/\n!pip3 install -e pegasus\n%cd /content/pegasus/\n```\n\n    /content\n    Obtaining file:///content/pegasus\n    Requirement already satisfied: absl-py in /usr/local/lib/python3.6/dist-packages (from pegasus==0.0.1) (0.8.1)\n    Requirement already satisfied: mock in /usr/local/lib/python3.6/dist-packages (from pegasus==0.0.1) (2.0.0)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from pegasus==0.0.1) (1.18.5)\n    Requirement already satisfied: rouge-score in /usr/local/lib/python3.6/dist-packages (from pegasus==0.0.1) (0.0.4)\n    Requirement already satisfied: sacrebleu in /usr/local/lib/python3.6/dist-packages (from pegasus==0.0.1) (1.4.13)\n    Requirement already satisfied: sentencepiece in /usr/local/lib/python3.6/dist-packages (from pegasus==0.0.1) (0.1.91)\n    Requirement already satisfied: tensorflow-text==1.15.0rc0 in /usr/local/lib/python3.6/dist-packages (from pegasus==0.0.1) (1.15.0rc0)\n    Requirement already satisfied: tfds-nightly in /usr/local/lib/python3.6/dist-packages (from pegasus==0.0.1) (3.2.1.dev202009020105)\n    Requirement already satisfied: tensor2tensor==1.15.0 in /usr/local/lib/python3.6/dist-packages (from pegasus==0.0.1) (1.15.0)\n    Requirement already satisfied: tensorflow-gpu==1.15.2 in /usr/local/lib/python3.6/dist-packages (from pegasus==0.0.1) (1.15.2)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from absl-py->pegasus==0.0.1) (1.15.0)\n    Requirement already satisfied: pbr>=0.11 in /usr/local/lib/python3.6/dist-packages (from mock->pegasus==0.0.1) (5.5.0)\n    Requirement already satisfied: nltk in /usr/local/lib/python3.6/dist-packages (from rouge-score->pegasus==0.0.1) (3.2.5)\n    Requirement already satisfied: portalocker in /usr/local/lib/python3.6/dist-packages (from sacrebleu->pegasus==0.0.1) (2.0.0)\n    Requirement already satisfied: tensorflow<1.16,>=1.15.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-text==1.15.0rc0->pegasus==0.0.1) (1.15.3)\n    Requirement already satisfied: wrapt in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->pegasus==0.0.1) (1.12.1)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->pegasus==0.0.1) (4.41.1)\n    Requirement already satisfied: dm-tree in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->pegasus==0.0.1) (0.1.5)\n    Requirement already satisfied: tensorflow-metadata in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->pegasus==0.0.1) (0.23.0)\n    Requirement already satisfied: termcolor in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->pegasus==0.0.1) (1.1.0)\n    Requirement already satisfied: attrs>=18.1.0 in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->pegasus==0.0.1) (20.1.0)\n    Requirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->pegasus==0.0.1) (0.7)\n    Requirement already satisfied: importlib-resources; python_version < \"3.9\" in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->pegasus==0.0.1) (3.0.0)\n    Requirement already satisfied: dill in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->pegasus==0.0.1) (0.3.2)\n    Requirement already satisfied: promise in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->pegasus==0.0.1) (2.3)\n    Requirement already satisfied: protobuf>=3.6.1 in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->pegasus==0.0.1) (3.12.4)\n    Requirement already satisfied: requests>=2.19.0 in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->pegasus==0.0.1) (2.23.0)\n    Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->pegasus==0.0.1) (0.16.0)\n    Requirement already satisfied: tensorflow-gan in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->pegasus==0.0.1) (2.0.0)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->pegasus==0.0.1) (1.1.1)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->pegasus==0.0.1) (1.4.1)\n    Requirement already satisfied: tensorflow-probability==0.7.0 in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->pegasus==0.0.1) (0.7.0)\n    Requirement already satisfied: kfac in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->pegasus==0.0.1) (0.2.2)\n    Requirement already satisfied: tensorflow-datasets in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->pegasus==0.0.1) (2.1.0)\n    Requirement already satisfied: gunicorn in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->pegasus==0.0.1) (20.0.4)\n    Requirement already satisfied: flask in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->pegasus==0.0.1) (1.1.2)\n    Requirement already satisfied: bz2file in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->pegasus==0.0.1) (0.98)\n    Requirement already satisfied: opencv-python in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->pegasus==0.0.1) (4.1.2.30)\n    Requirement already satisfied: google-api-python-client in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->pegasus==0.0.1) (1.7.12)\n    Requirement already satisfied: mesh-tensorflow in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->pegasus==0.0.1) (0.1.16)\n    Requirement already satisfied: Pillow in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->pegasus==0.0.1) (7.0.0)\n    Requirement already satisfied: gevent in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->pegasus==0.0.1) (20.6.2)\n    Requirement already satisfied: gin-config in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->pegasus==0.0.1) (0.3.0)\n    Requirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->pegasus==0.0.1) (2.10.0)\n    Requirement already satisfied: tf-slim in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->pegasus==0.0.1) (1.1.0)\n    Requirement already satisfied: pypng in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->pegasus==0.0.1) (0.0.20)\n    Requirement already satisfied: oauth2client in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->pegasus==0.0.1) (4.1.3)\n    Requirement already satisfied: gym in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->pegasus==0.0.1) (0.17.2)\n    Requirement already satisfied: dopamine-rl in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->pegasus==0.0.1) (1.0.5)\n    Requirement already satisfied: google-pasta>=0.1.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->pegasus==0.0.1) (0.2.0)\n    Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->pegasus==0.0.1) (3.3.0)\n    Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->pegasus==0.0.1) (1.31.0)\n    Requirement already satisfied: gast==0.2.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->pegasus==0.0.1) (0.2.2)\n    Requirement already satisfied: tensorboard<1.16.0,>=1.15.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->pegasus==0.0.1) (1.15.0)\n    Requirement already satisfied: astor>=0.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->pegasus==0.0.1) (0.8.1)\n    Requirement already satisfied: keras-preprocessing>=1.0.5 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->pegasus==0.0.1) (1.1.2)\n    Requirement already satisfied: tensorflow-estimator==1.15.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->pegasus==0.0.1) (1.15.1)\n    Requirement already satisfied: keras-applications>=1.0.8 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->pegasus==0.0.1) (1.0.8)\n    Requirement already satisfied: wheel>=0.26; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->pegasus==0.0.1) (0.35.1)\n    Requirement already satisfied: googleapis-common-protos in /usr/local/lib/python3.6/dist-packages (from tensorflow-metadata->tfds-nightly->pegasus==0.0.1) (1.52.0)\n    Requirement already satisfied: zipp>=0.4; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from importlib-resources; python_version < \"3.9\"->tfds-nightly->pegasus==0.0.1) (3.1.0)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from protobuf>=3.6.1->tfds-nightly->pegasus==0.0.1) (49.6.0)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tfds-nightly->pegasus==0.0.1) (2.10)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tfds-nightly->pegasus==0.0.1) (3.0.4)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tfds-nightly->pegasus==0.0.1) (1.24.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tfds-nightly->pegasus==0.0.1) (2020.6.20)\n    Requirement already satisfied: tensorflow-hub>=0.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gan->tensor2tensor==1.15.0->pegasus==0.0.1) (0.9.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy->tensor2tensor==1.15.0->pegasus==0.0.1) (1.1.0)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.6/dist-packages (from tensorflow-probability==0.7.0->tensor2tensor==1.15.0->pegasus==0.0.1) (4.4.2)\n    Requirement already satisfied: cloudpickle>=0.6.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow-probability==0.7.0->tensor2tensor==1.15.0->pegasus==0.0.1) (1.3.0)\n    Requirement already satisfied: Werkzeug>=0.15 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor==1.15.0->pegasus==0.0.1) (1.0.1)\n    Requirement already satisfied: itsdangerous>=0.24 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor==1.15.0->pegasus==0.0.1) (1.1.0)\n    Requirement already satisfied: Jinja2>=2.10.1 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor==1.15.0->pegasus==0.0.1) (2.11.2)\n    Requirement already satisfied: click>=5.1 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor==1.15.0->pegasus==0.0.1) (7.1.2)\n    Requirement already satisfied: uritemplate<4dev,>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor==1.15.0->pegasus==0.0.1) (3.0.1)\n    Requirement already satisfied: httplib2<1dev,>=0.17.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor==1.15.0->pegasus==0.0.1) (0.18.1)\n    Requirement already satisfied: google-auth>=1.4.1 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor==1.15.0->pegasus==0.0.1) (1.17.2)\n    Requirement already satisfied: google-auth-httplib2>=0.0.3 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor==1.15.0->pegasus==0.0.1) (0.0.4)\n    Requirement already satisfied: zope.interface in /usr/local/lib/python3.6/dist-packages (from gevent->tensor2tensor==1.15.0->pegasus==0.0.1) (5.1.0)\n    Requirement already satisfied: greenlet>=0.4.16; platform_python_implementation == \"CPython\" in /usr/local/lib/python3.6/dist-packages (from gevent->tensor2tensor==1.15.0->pegasus==0.0.1) (0.4.16)\n    Requirement already satisfied: zope.event in /usr/local/lib/python3.6/dist-packages (from gevent->tensor2tensor==1.15.0->pegasus==0.0.1) (4.4)\n    Requirement already satisfied: pyasn1-modules>=0.0.5 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor==1.15.0->pegasus==0.0.1) (0.2.8)\n    Requirement already satisfied: pyasn1>=0.1.7 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor==1.15.0->pegasus==0.0.1) (0.4.8)\n    Requirement already satisfied: rsa>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor==1.15.0->pegasus==0.0.1) (4.6)\n    Requirement already satisfied: pyglet<=1.5.0,>=1.4.0 in /usr/local/lib/python3.6/dist-packages (from gym->tensor2tensor==1.15.0->pegasus==0.0.1) (1.5.0)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard<1.16.0,>=1.15.0->tensorflow-gpu==1.15.2->pegasus==0.0.1) (3.2.2)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.6/dist-packages (from Jinja2>=2.10.1->flask->tensor2tensor==1.15.0->pegasus==0.0.1) (1.1.1)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth>=1.4.1->google-api-python-client->tensor2tensor==1.15.0->pegasus==0.0.1) (4.1.1)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from markdown>=2.6.8->tensorboard<1.16.0,>=1.15.0->tensorflow-gpu==1.15.2->pegasus==0.0.1) (1.7.0)\n    Installing collected packages: pegasus\n      Running setup.py develop for pegasus\n    Successfully installed pegasus\n    /content/pegasus\n\n\n\n```\nimport pandas as pd\nimport tensorflow as tf\n\nsave_path = \"/content/pegasus/pegasus/data/testdata/test_pattern_1.tfrecord\"\n\ninput_dict = dict(\n                  inputs=[ # here is the input text that goes in\n                          \"Musk\u2019s current problems are less dire than those he faced in 2008, but Tesla and SpaceX are no longer experiments. Failure now would put thousands of jobs and billions of dollars at risk, and SpaceX has become crucial not just to the U.S. space program but also to countries and companies around the world hoping to put up satellites. Musk's supporters say he has built up enough credibility and has enough star power to raise money with relative ease or to be bailed out by one of his many ultrarich friends who share his aspirations. Just on technological merits, Musk\u2019s companies have already changed the world. To the extent that the electric car is a commercial reality, it\u2019s in large part thanks to Tesla. While it receives less attention, SpaceX and the revitalization of the U.S. aerospace industry may be Musk\u2019s most stirring accomplishment. But at every point where his companies seem to be on stable footing, Musk takes on more and promises more, erasing the memory of past gains. The question is whether Musk can continue to operate on the edge of what\u2019s possible \u2014 the key to his achievements so far.\"\n                         ],\n                  targets=[\n                           \"\" # passing empty string since my target goal is to summerize the text\n                          ]\n                 )\n\ndata = pd.DataFrame(input_dict)\n\nwith tf.io.TFRecordWriter(save_path) as writer:\n    for row in data.values:\n        inputs, targets = row[:-1], row[-1]\n        example = tf.train.Example(\n            features=tf.train.Features(\n                feature={\n                    \"inputs\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[inputs[0].encode('utf-8')])),\n                    \"targets\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[targets.encode('utf-8')])),\n                }\n            )\n        )\n        writer.write(example.SerializeToString())\n```\n\n\n```\n\n```\n\n\n```\n!python3 pegasus/bin/train.py --params=aeslc_transformer \\\n--param_overrides=vocab_filename=ckpt/pegasus_ckpt/c4.unigram.newline.10pct.96000.model \\\n--train_init_checkpoint=ckpt/pegasus_ckpt/model.ckpt-1500000 \\\n--model_dir=ckpt/pegasus_ckpt/aeslc\n```\n\n    WARNING:tensorflow:From pegasus/bin/train.py:94: The name tf.app.run is deprecated. Please use tf.compat.v1.app.run instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/ops/public_parsing_ops.py:93: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n    \n    W0830 20:32:19.182901 139933262464896 module_wrapper.py:139] From /content/pegasus/pegasus/ops/public_parsing_ops.py:93: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:49: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead.\n    \n    W0830 20:32:19.388477 139933262464896 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:49: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead.\n    \n    WARNING:tensorflow:Estimator's model_fn (<function _estimator_model_fn.<locals>.model_fn at 0x7f444499cb70>) includes params argument, but params are not passed to Estimator.\n    W0830 20:32:19.389236 139933262464896 estimator.py:1994] Estimator's model_fn (<function _estimator_model_fn.<locals>.model_fn at 0x7f444499cb70>) includes params argument, but params are not passed to Estimator.\n    INFO:tensorflow:Using config: {'_model_dir': 'ckpt/pegasus_ckpt/aeslc', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': 1000, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true\n    , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': None, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7f4444990cf8>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1, '_tpu_config': TPUConfig(iterations_per_loop=1000, num_shards=None, num_cores_per_replica=None, per_host_input_for_training=2, tpu_job_name=None, initial_infeed_sleep_secs=None, input_partition_dims=None, eval_training_input_configuration=2, experimental_host_call_every_n_steps=1), '_cluster': None}\n    I0830 20:32:19.389787 139933262464896 estimator.py:212] Using config: {'_model_dir': 'ckpt/pegasus_ckpt/aeslc', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': 1000, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true\n    , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': None, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7f4444990cf8>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1, '_tpu_config': TPUConfig(iterations_per_loop=1000, num_shards=None, num_cores_per_replica=None, per_host_input_for_training=2, tpu_job_name=None, initial_infeed_sleep_secs=None, input_partition_dims=None, eval_training_input_configuration=2, experimental_host_call_every_n_steps=1), '_cluster': None}\n    INFO:tensorflow:_TPUContext: eval_on_tpu True\n    I0830 20:32:19.390104 139933262464896 tpu_context.py:220] _TPUContext: eval_on_tpu True\n    WARNING:tensorflow:eval_on_tpu ignored because use_tpu is False.\n    W0830 20:32:19.391037 139933262464896 tpu_context.py:222] eval_on_tpu ignored because use_tpu is False.\n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\n    Instructions for updating:\n    If using Keras pass *_constraint arguments to layers.\n    W0830 20:32:19.409669 139933262464896 deprecation.py:506] From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\n    Instructions for updating:\n    If using Keras pass *_constraint arguments to layers.\n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.\n    W0830 20:32:19.410372 139933262464896 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.\n    2020-08-30 20:32:19.435727: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    2020-08-30 20:32:19.646277: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    2020-08-30 20:32:19.858356: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    I0830 20:32:20.053998 139933262464896 dataset_info.py:424] Load pre-computed DatasetInfo (eg: splits, num examples,...) from GCS: aeslc/1.0.0\n    2020-08-30 20:32:20.068055: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    I0830 20:32:20.623698 139933262464896 dataset_info.py:355] Load dataset info from /tmp/tmpkw_bi0igtfds\n    I0830 20:32:20.625427 139933262464896 dataset_info.py:395] Field info.description from disk and from code do not match. Keeping the one from code.\n    I0830 20:32:20.625629 139933262464896 dataset_info.py:395] Field info.citation from disk and from code do not match. Keeping the one from code.\n    I0830 20:32:20.625969 139933262464896 dataset_builder.py:349] Generating dataset aeslc (/root/tensorflow_datasets/aeslc/1.0.0)\n    \u001b[1mDownloading and preparing dataset aeslc/1.0.0 (download: 11.10 MiB, generated: Unknown size, total: 11.10 MiB) to /root/tensorflow_datasets/aeslc/1.0.0...\u001b[0m\n    2020-08-30 20:32:20.730889: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    2020-08-30 20:32:20.917673: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    Dl Completed...: 0 url [00:00, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[AI0830 20:32:21.113712 139933262464896 download_manager.py:478] Downloading https://github.com/ryanzhumich/AESLC/archive/master.zip into /root/tensorflow_datasets/downloads/ryanzhumich_AESLC_archive_masterACSpoxw627Ay4UrkswMeyz6RrOey8kKfkhEM4VySJWU.zip.tmp.d089b171be8e41a6a21dad80691087b9...\n    Dl Completed...:   0% 0/1 [00:00<?, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:01<?, ? url/s]\n    Dl Size...: 0 MiB [00:01, ? MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:01, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 1 MiB [00:02,  2.41s/ MiB]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 2 MiB [00:02,  1.74s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 3 MiB [00:02,  1.74s/ MiB]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 4 MiB [00:02,  1.25s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 5 MiB [00:02,  1.25s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 6 MiB [00:02,  1.25s/ MiB]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 7 MiB [00:02,  1.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 8 MiB [00:02,  1.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 9 MiB [00:03,  1.12 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 10 MiB [00:03,  1.56 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 11 MiB [00:03,  1.56 MiB/s]\u001b[A\n    \n    Dl Completed...: 100% 1/1 [00:03<00:00,  3.18s/ url]\n    Dl Size...: 11 MiB [00:03,  1.56 MiB/s]\u001b[A\n    \n    Dl Completed...: 100% 1/1 [00:03<00:00,  3.18s/ url]\n    Dl Size...: 11 MiB [00:03,  1.56 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:03<?, ? file/s]\u001b[A\u001b[A\n    \n    Dl Completed...: 100% 1/1 [00:10<00:00,  3.18s/ url]\n    Dl Size...: 11 MiB [00:10,  1.56 MiB/s]\u001b[A\n    \n    Extraction completed...: 100% 1/1 [00:10<00:00, 10.83s/ file]\u001b[A\u001b[A\n    Extraction completed...: 100% 1/1 [00:10<00:00, 10.83s/ file]\n    \n    Dl Size...: 11 MiB [00:10,  1.02 MiB/s]\n    \n    Dl Completed...: 100% 1/1 [00:10<00:00, 10.84s/ url]\n    I0830 20:32:31.947028 139933262464896 dataset_builder.py:953] Generating split train\n    Shuffling and writing examples to /root/tensorflow_datasets/aeslc/1.0.0.incompleteBCWTW3/aeslc-train.tfrecord\n      0% 0/14436 [00:00<?, ? examples/s]I0830 20:32:39.110311 139933262464896 tfrecords_writer.py:226] Done writing /root/tensorflow_datasets/aeslc/1.0.0.incompleteBCWTW3/aeslc-train.tfrecord. Shard lengths: [14436]\n    I0830 20:32:39.116265 139933262464896 dataset_builder.py:953] Generating split validation\n    Shuffling and writing examples to /root/tensorflow_datasets/aeslc/1.0.0.incompleteBCWTW3/aeslc-validation.tfrecord\n      0% 0/1960 [00:00<?, ? examples/s]I0830 20:32:39.984535 139933262464896 tfrecords_writer.py:226] Done writing /root/tensorflow_datasets/aeslc/1.0.0.incompleteBCWTW3/aeslc-validation.tfrecord. Shard lengths: [1960]\n    I0830 20:32:39.985746 139933262464896 dataset_builder.py:953] Generating split test\n    Shuffling and writing examples to /root/tensorflow_datasets/aeslc/1.0.0.incompleteBCWTW3/aeslc-test.tfrecord\n      0% 0/1906 [00:00<?, ? examples/s]I0830 20:32:40.867191 139933262464896 tfrecords_writer.py:226] Done writing /root/tensorflow_datasets/aeslc/1.0.0.incompleteBCWTW3/aeslc-test.tfrecord. Shard lengths: [1906]\n    I0830 20:32:40.868629 139933262464896 dataset_builder.py:404] Skipping computing stats for mode ComputeStatsMode.AUTO.\n    \u001b[1mDataset aeslc downloaded and prepared to /root/tensorflow_datasets/aeslc/1.0.0. Subsequent calls will reuse this data.\u001b[0m\n    I0830 20:32:40.870629 139933262464896 dataset_builder.py:503] Constructing tf.data.Dataset for split train, from /root/tensorflow_datasets/aeslc/1.0.0\n    I0830 20:32:41.429135 139933262464896 datasets.py:215] Number of examples for config aeslc train is 14436\n    2020-08-30 20:32:42.391482: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1\n    2020-08-30 20:32:42.449905: E tensorflow/stream_executor/cuda/cuda_driver.cc:318] failed call to cuInit: CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected\n    2020-08-30 20:32:42.449991: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (d85487f9bac6): /proc/driver/nvidia/version does not exist\n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/ragged/ragged_tensor.py:1586: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use tf.where in 2.0, which has the same broadcast rule as np.where\n    W0830 20:32:42.551289 139933262464896 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/ragged/ragged_tensor.py:1586: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use tf.where in 2.0, which has the same broadcast rule as np.where\n    INFO:tensorflow:Calling model_fn.\n    I0830 20:32:42.852426 139933262464896 estimator.py:1148] Calling model_fn.\n    INFO:tensorflow:Running train on CPU\n    I0830 20:32:42.852832 139933262464896 tpu_estimator.py:3124] Running train on CPU\n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:78: The name tf.get_variable_scope is deprecated. Please use tf.compat.v1.get_variable_scope instead.\n    \n    W0830 20:32:42.853416 139933262464896 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:78: The name tf.get_variable_scope is deprecated. Please use tf.compat.v1.get_variable_scope instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/attention.py:41: The name tf.layers.Dense is deprecated. Please use tf.compat.v1.layers.Dense instead.\n    \n    W0830 20:32:42.854073 139933262464896 module_wrapper.py:139] From /content/pegasus/pegasus/layers/attention.py:41: The name tf.layers.Dense is deprecated. Please use tf.compat.v1.layers.Dense instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/embedding.py:57: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n    \n    W0830 20:32:42.907520 139933262464896 module_wrapper.py:139] From /content/pegasus/pegasus/layers/embedding.py:57: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/embedding.py:57: The name tf.AUTO_REUSE is deprecated. Please use tf.compat.v1.AUTO_REUSE instead.\n    \n    W0830 20:32:42.907912 139933262464896 module_wrapper.py:139] From /content/pegasus/pegasus/layers/embedding.py:57: The name tf.AUTO_REUSE is deprecated. Please use tf.compat.v1.AUTO_REUSE instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/embedding.py:61: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n    \n    W0830 20:32:42.908277 139933262464896 module_wrapper.py:139] From /content/pegasus/pegasus/layers/embedding.py:61: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/embedding.py:64: calling RandomNormal.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Call initializer instance with the dtype argument instead of passing it to the constructor\n    W0830 20:32:42.908631 139933262464896 deprecation.py:506] From /content/pegasus/pegasus/layers/embedding.py:64: calling RandomNormal.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Call initializer instance with the dtype argument instead of passing it to the constructor\n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/attention.py:106: The name tf.matrix_band_part is deprecated. Please use tf.linalg.band_part instead.\n    \n    W0830 20:32:46.031859 139933262464896 module_wrapper.py:139] From /content/pegasus/pegasus/layers/attention.py:106: The name tf.matrix_band_part is deprecated. Please use tf.linalg.band_part instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/models/transformer.py:108: The name tf.losses.softmax_cross_entropy is deprecated. Please use tf.compat.v1.losses.softmax_cross_entropy instead.\n    \n    W0830 20:32:51.186311 139933262464896 module_wrapper.py:139] From /content/pegasus/pegasus/models/transformer.py:108: The name tf.losses.softmax_cross_entropy is deprecated. Please use tf.compat.v1.losses.softmax_cross_entropy instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:113: The name tf.train.get_global_step is deprecated. Please use tf.compat.v1.train.get_global_step instead.\n    \n    W0830 20:32:51.238706 139933262464896 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:113: The name tf.train.get_global_step is deprecated. Please use tf.compat.v1.train.get_global_step instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:114: The name tf.rsqrt is deprecated. Please use tf.math.rsqrt instead.\n    \n    W0830 20:32:51.239055 139933262464896 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:114: The name tf.rsqrt is deprecated. Please use tf.math.rsqrt instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:115: to_float (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    W0830 20:32:51.239243 139933262464896 deprecation.py:323] From /content/pegasus/pegasus/params/estimator_utils.py:115: to_float (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    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/adafactor.py:315: The name tf.train.get_or_create_global_step is deprecated. Please use tf.compat.v1.train.get_or_create_global_step instead.\n    \n    W0830 20:32:51.248138 139933262464896 module_wrapper.py:139] From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/adafactor.py:315: The name tf.train.get_or_create_global_step is deprecated. Please use tf.compat.v1.train.get_or_create_global_step instead.\n    \n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/quantization.py:147: 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    W0830 20:32:51.252616 139933262464896 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/quantization.py:147: 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    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/quantization.py:156: The name tf.mod is deprecated. Please use tf.math.mod instead.\n    \n    W0830 20:32:51.255362 139933262464896 module_wrapper.py:139] From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/quantization.py:156: The name tf.mod is deprecated. Please use tf.math.mod instead.\n    \n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/adafactor.py:244: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead.\n    \n    W0830 20:33:06.059977 139933262464896 module_wrapper.py:139] From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/adafactor.py:244: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:189: The name tf.trainable_variables is deprecated. Please use tf.compat.v1.trainable_variables instead.\n    \n    W0830 20:33:21.017336 139933262464896 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:189: The name tf.trainable_variables is deprecated. Please use tf.compat.v1.trainable_variables instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:205: The name tf.train.init_from_checkpoint is deprecated. Please use tf.compat.v1.train.init_from_checkpoint instead.\n    \n    W0830 20:33:21.030986 139933262464896 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:205: The name tf.train.init_from_checkpoint is deprecated. Please use tf.compat.v1.train.init_from_checkpoint instead.\n    \n    I0830 20:33:22.488876 139933262464896 estimator_utils.py:207] **** Trainable Variables ****\n    I0830 20:33:22.489141 139933262464896 estimator_utils.py:212]   name = embeddings/weights:0, shape = (96103, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.489293 139933262464896 estimator_utils.py:212]   name = encoder/layer_0/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.489398 139933262464896 estimator_utils.py:212]   name = encoder/layer_0/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.489494 139933262464896 estimator_utils.py:212]   name = encoder/layer_0/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.489617 139933262464896 estimator_utils.py:212]   name = encoder/layer_0/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.489725 139933262464896 estimator_utils.py:212]   name = encoder/layer_0/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.489822 139933262464896 estimator_utils.py:212]   name = encoder/layer_0/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.489915 139933262464896 estimator_utils.py:212]   name = encoder/layer_0/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.490003 139933262464896 estimator_utils.py:212]   name = encoder/layer_0/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.490101 139933262464896 estimator_utils.py:212]   name = encoder/layer_0/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.490192 139933262464896 estimator_utils.py:212]   name = encoder/layer_0/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.490276 139933262464896 estimator_utils.py:212]   name = encoder/layer_0/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.490364 139933262464896 estimator_utils.py:212]   name = encoder/layer_0/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.490449 139933262464896 estimator_utils.py:212]   name = encoder/layer_1/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.490535 139933262464896 estimator_utils.py:212]   name = encoder/layer_1/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.490654 139933262464896 estimator_utils.py:212]   name = encoder/layer_1/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.490754 139933262464896 estimator_utils.py:212]   name = encoder/layer_1/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.490846 139933262464896 estimator_utils.py:212]   name = encoder/layer_1/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.490936 139933262464896 estimator_utils.py:212]   name = encoder/layer_1/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.491036 139933262464896 estimator_utils.py:212]   name = encoder/layer_1/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.491125 139933262464896 estimator_utils.py:212]   name = encoder/layer_1/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.491210 139933262464896 estimator_utils.py:212]   name = encoder/layer_1/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.491300 139933262464896 estimator_utils.py:212]   name = encoder/layer_1/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.491386 139933262464896 estimator_utils.py:212]   name = encoder/layer_1/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.491480 139933262464896 estimator_utils.py:212]   name = encoder/layer_1/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.491567 139933262464896 estimator_utils.py:212]   name = encoder/layer_2/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.491687 139933262464896 estimator_utils.py:212]   name = encoder/layer_2/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.491774 139933262464896 estimator_utils.py:212]   name = encoder/layer_2/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.491864 139933262464896 estimator_utils.py:212]   name = encoder/layer_2/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.491952 139933262464896 estimator_utils.py:212]   name = encoder/layer_2/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.492052 139933262464896 estimator_utils.py:212]   name = encoder/layer_2/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.492145 139933262464896 estimator_utils.py:212]   name = encoder/layer_2/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.492237 139933262464896 estimator_utils.py:212]   name = encoder/layer_2/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.492323 139933262464896 estimator_utils.py:212]   name = encoder/layer_2/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.492412 139933262464896 estimator_utils.py:212]   name = encoder/layer_2/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.492497 139933262464896 estimator_utils.py:212]   name = encoder/layer_2/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.492606 139933262464896 estimator_utils.py:212]   name = encoder/layer_2/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.492709 139933262464896 estimator_utils.py:212]   name = encoder/layer_3/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.492798 139933262464896 estimator_utils.py:212]   name = encoder/layer_3/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.492891 139933262464896 estimator_utils.py:212]   name = encoder/layer_3/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.492987 139933262464896 estimator_utils.py:212]   name = encoder/layer_3/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.493090 139933262464896 estimator_utils.py:212]   name = encoder/layer_3/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.493179 139933262464896 estimator_utils.py:212]   name = encoder/layer_3/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.493269 139933262464896 estimator_utils.py:212]   name = encoder/layer_3/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.493354 139933262464896 estimator_utils.py:212]   name = encoder/layer_3/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.493437 139933262464896 estimator_utils.py:212]   name = encoder/layer_3/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.493530 139933262464896 estimator_utils.py:212]   name = encoder/layer_3/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.493648 139933262464896 estimator_utils.py:212]   name = encoder/layer_3/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.493746 139933262464896 estimator_utils.py:212]   name = encoder/layer_3/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.493832 139933262464896 estimator_utils.py:212]   name = encoder/layer_4/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.493920 139933262464896 estimator_utils.py:212]   name = encoder/layer_4/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.494009 139933262464896 estimator_utils.py:212]   name = encoder/layer_4/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.494125 139933262464896 estimator_utils.py:212]   name = encoder/layer_4/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.494223 139933262464896 estimator_utils.py:212]   name = encoder/layer_4/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.494311 139933262464896 estimator_utils.py:212]   name = encoder/layer_4/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.494397 139933262464896 estimator_utils.py:212]   name = encoder/layer_4/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.494477 139933262464896 estimator_utils.py:212]   name = encoder/layer_4/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.494560 139933262464896 estimator_utils.py:212]   name = encoder/layer_4/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.494678 139933262464896 estimator_utils.py:212]   name = encoder/layer_4/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.494768 139933262464896 estimator_utils.py:212]   name = encoder/layer_4/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.494860 139933262464896 estimator_utils.py:212]   name = encoder/layer_4/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.494942 139933262464896 estimator_utils.py:212]   name = encoder/layer_5/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.495016 139933262464896 estimator_utils.py:212]   name = encoder/layer_5/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.495095 139933262464896 estimator_utils.py:212]   name = encoder/layer_5/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.495255 139933262464896 estimator_utils.py:212]   name = encoder/layer_5/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.495334 139933262464896 estimator_utils.py:212]   name = encoder/layer_5/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.495416 139933262464896 estimator_utils.py:212]   name = encoder/layer_5/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.495503 139933262464896 estimator_utils.py:212]   name = encoder/layer_5/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.495600 139933262464896 estimator_utils.py:212]   name = encoder/layer_5/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.495685 139933262464896 estimator_utils.py:212]   name = encoder/layer_5/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.495767 139933262464896 estimator_utils.py:212]   name = encoder/layer_5/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.495845 139933262464896 estimator_utils.py:212]   name = encoder/layer_5/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.495926 139933262464896 estimator_utils.py:212]   name = encoder/layer_5/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.496004 139933262464896 estimator_utils.py:212]   name = encoder/layer_6/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.496089 139933262464896 estimator_utils.py:212]   name = encoder/layer_6/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.496166 139933262464896 estimator_utils.py:212]   name = encoder/layer_6/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.496247 139933262464896 estimator_utils.py:212]   name = encoder/layer_6/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.496329 139933262464896 estimator_utils.py:212]   name = encoder/layer_6/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.496411 139933262464896 estimator_utils.py:212]   name = encoder/layer_6/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.496493 139933262464896 estimator_utils.py:212]   name = encoder/layer_6/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.496589 139933262464896 estimator_utils.py:212]   name = encoder/layer_6/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.496680 139933262464896 estimator_utils.py:212]   name = encoder/layer_6/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.496762 139933262464896 estimator_utils.py:212]   name = encoder/layer_6/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.496840 139933262464896 estimator_utils.py:212]   name = encoder/layer_6/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.496920 139933262464896 estimator_utils.py:212]   name = encoder/layer_6/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.496999 139933262464896 estimator_utils.py:212]   name = encoder/layer_7/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.497083 139933262464896 estimator_utils.py:212]   name = encoder/layer_7/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.497161 139933262464896 estimator_utils.py:212]   name = encoder/layer_7/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.497242 139933262464896 estimator_utils.py:212]   name = encoder/layer_7/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.497326 139933262464896 estimator_utils.py:212]   name = encoder/layer_7/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.497407 139933262464896 estimator_utils.py:212]   name = encoder/layer_7/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.497488 139933262464896 estimator_utils.py:212]   name = encoder/layer_7/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.497568 139933262464896 estimator_utils.py:212]   name = encoder/layer_7/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.497667 139933262464896 estimator_utils.py:212]   name = encoder/layer_7/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.497746 139933262464896 estimator_utils.py:212]   name = encoder/layer_7/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.497825 139933262464896 estimator_utils.py:212]   name = encoder/layer_7/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.497906 139933262464896 estimator_utils.py:212]   name = encoder/layer_7/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.497985 139933262464896 estimator_utils.py:212]   name = encoder/layer_8/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.498070 139933262464896 estimator_utils.py:212]   name = encoder/layer_8/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.498150 139933262464896 estimator_utils.py:212]   name = encoder/layer_8/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.498231 139933262464896 estimator_utils.py:212]   name = encoder/layer_8/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.498312 139933262464896 estimator_utils.py:212]   name = encoder/layer_8/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.498394 139933262464896 estimator_utils.py:212]   name = encoder/layer_8/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.498475 139933262464896 estimator_utils.py:212]   name = encoder/layer_8/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.498554 139933262464896 estimator_utils.py:212]   name = encoder/layer_8/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.498655 139933262464896 estimator_utils.py:212]   name = encoder/layer_8/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.498733 139933262464896 estimator_utils.py:212]   name = encoder/layer_8/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.498813 139933262464896 estimator_utils.py:212]   name = encoder/layer_8/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.498894 139933262464896 estimator_utils.py:212]   name = encoder/layer_8/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.498975 139933262464896 estimator_utils.py:212]   name = encoder/layer_9/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.499060 139933262464896 estimator_utils.py:212]   name = encoder/layer_9/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.499138 139933262464896 estimator_utils.py:212]   name = encoder/layer_9/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.499219 139933262464896 estimator_utils.py:212]   name = encoder/layer_9/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.499300 139933262464896 estimator_utils.py:212]   name = encoder/layer_9/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.499379 139933262464896 estimator_utils.py:212]   name = encoder/layer_9/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.499460 139933262464896 estimator_utils.py:212]   name = encoder/layer_9/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.499545 139933262464896 estimator_utils.py:212]   name = encoder/layer_9/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.499644 139933262464896 estimator_utils.py:212]   name = encoder/layer_9/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.499726 139933262464896 estimator_utils.py:212]   name = encoder/layer_9/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.499807 139933262464896 estimator_utils.py:212]   name = encoder/layer_9/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.531506 139933262464896 estimator_utils.py:212]   name = encoder/layer_9/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.532086 139933262464896 estimator_utils.py:212]   name = encoder/layer_10/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.532419 139933262464896 estimator_utils.py:212]   name = encoder/layer_10/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.532551 139933262464896 estimator_utils.py:212]   name = encoder/layer_10/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.532672 139933262464896 estimator_utils.py:212]   name = encoder/layer_10/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.532766 139933262464896 estimator_utils.py:212]   name = encoder/layer_10/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.532857 139933262464896 estimator_utils.py:212]   name = encoder/layer_10/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.532944 139933262464896 estimator_utils.py:212]   name = encoder/layer_10/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.533028 139933262464896 estimator_utils.py:212]   name = encoder/layer_10/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.533113 139933262464896 estimator_utils.py:212]   name = encoder/layer_10/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.533198 139933262464896 estimator_utils.py:212]   name = encoder/layer_10/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.533475 139933262464896 estimator_utils.py:212]   name = encoder/layer_10/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.533628 139933262464896 estimator_utils.py:212]   name = encoder/layer_10/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.533720 139933262464896 estimator_utils.py:212]   name = encoder/layer_11/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.533806 139933262464896 estimator_utils.py:212]   name = encoder/layer_11/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.533925 139933262464896 estimator_utils.py:212]   name = encoder/layer_11/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.534019 139933262464896 estimator_utils.py:212]   name = encoder/layer_11/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.534111 139933262464896 estimator_utils.py:212]   name = encoder/layer_11/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.534198 139933262464896 estimator_utils.py:212]   name = encoder/layer_11/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.534285 139933262464896 estimator_utils.py:212]   name = encoder/layer_11/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.534368 139933262464896 estimator_utils.py:212]   name = encoder/layer_11/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.534457 139933262464896 estimator_utils.py:212]   name = encoder/layer_11/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.534554 139933262464896 estimator_utils.py:212]   name = encoder/layer_11/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.534653 139933262464896 estimator_utils.py:212]   name = encoder/layer_11/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.534742 139933262464896 estimator_utils.py:212]   name = encoder/layer_11/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.534826 139933262464896 estimator_utils.py:212]   name = encoder/layer_12/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.534917 139933262464896 estimator_utils.py:212]   name = encoder/layer_12/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.535001 139933262464896 estimator_utils.py:212]   name = encoder/layer_12/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.535088 139933262464896 estimator_utils.py:212]   name = encoder/layer_12/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.535176 139933262464896 estimator_utils.py:212]   name = encoder/layer_12/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.535264 139933262464896 estimator_utils.py:212]   name = encoder/layer_12/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.535349 139933262464896 estimator_utils.py:212]   name = encoder/layer_12/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.535432 139933262464896 estimator_utils.py:212]   name = encoder/layer_12/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.535521 139933262464896 estimator_utils.py:212]   name = encoder/layer_12/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.535620 139933262464896 estimator_utils.py:212]   name = encoder/layer_12/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.535705 139933262464896 estimator_utils.py:212]   name = encoder/layer_12/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.535793 139933262464896 estimator_utils.py:212]   name = encoder/layer_12/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.535885 139933262464896 estimator_utils.py:212]   name = encoder/layer_13/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.535970 139933262464896 estimator_utils.py:212]   name = encoder/layer_13/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.536056 139933262464896 estimator_utils.py:212]   name = encoder/layer_13/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.536145 139933262464896 estimator_utils.py:212]   name = encoder/layer_13/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.536232 139933262464896 estimator_utils.py:212]   name = encoder/layer_13/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.536320 139933262464896 estimator_utils.py:212]   name = encoder/layer_13/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.536406 139933262464896 estimator_utils.py:212]   name = encoder/layer_13/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.536489 139933262464896 estimator_utils.py:212]   name = encoder/layer_13/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.536571 139933262464896 estimator_utils.py:212]   name = encoder/layer_13/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.536672 139933262464896 estimator_utils.py:212]   name = encoder/layer_13/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.536756 139933262464896 estimator_utils.py:212]   name = encoder/layer_13/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.536843 139933262464896 estimator_utils.py:212]   name = encoder/layer_13/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.536934 139933262464896 estimator_utils.py:212]   name = encoder/layer_14/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.537020 139933262464896 estimator_utils.py:212]   name = encoder/layer_14/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.537101 139933262464896 estimator_utils.py:212]   name = encoder/layer_14/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.537187 139933262464896 estimator_utils.py:212]   name = encoder/layer_14/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.537272 139933262464896 estimator_utils.py:212]   name = encoder/layer_14/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.537360 139933262464896 estimator_utils.py:212]   name = encoder/layer_14/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.537459 139933262464896 estimator_utils.py:212]   name = encoder/layer_14/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.537547 139933262464896 estimator_utils.py:212]   name = encoder/layer_14/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.537645 139933262464896 estimator_utils.py:212]   name = encoder/layer_14/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.537731 139933262464896 estimator_utils.py:212]   name = encoder/layer_14/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.537811 139933262464896 estimator_utils.py:212]   name = encoder/layer_14/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.537899 139933262464896 estimator_utils.py:212]   name = encoder/layer_14/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.537980 139933262464896 estimator_utils.py:212]   name = encoder/layer_15/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.538061 139933262464896 estimator_utils.py:212]   name = encoder/layer_15/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.538140 139933262464896 estimator_utils.py:212]   name = encoder/layer_15/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.538224 139933262464896 estimator_utils.py:212]   name = encoder/layer_15/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.538307 139933262464896 estimator_utils.py:212]   name = encoder/layer_15/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.538393 139933262464896 estimator_utils.py:212]   name = encoder/layer_15/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.538479 139933262464896 estimator_utils.py:212]   name = encoder/layer_15/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.538558 139933262464896 estimator_utils.py:212]   name = encoder/layer_15/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.538670 139933262464896 estimator_utils.py:212]   name = encoder/layer_15/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.538754 139933262464896 estimator_utils.py:212]   name = encoder/layer_15/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.538836 139933262464896 estimator_utils.py:212]   name = encoder/layer_15/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.538928 139933262464896 estimator_utils.py:212]   name = encoder/layer_15/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.539012 139933262464896 estimator_utils.py:212]   name = encoder/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.539094 139933262464896 estimator_utils.py:212]   name = encoder/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.539175 139933262464896 estimator_utils.py:212]   name = decoder/layer_0/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.539255 139933262464896 estimator_utils.py:212]   name = decoder/layer_0/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.539335 139933262464896 estimator_utils.py:212]   name = decoder/layer_0/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.539430 139933262464896 estimator_utils.py:212]   name = decoder/layer_0/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.539516 139933262464896 estimator_utils.py:212]   name = decoder/layer_0/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.539615 139933262464896 estimator_utils.py:212]   name = decoder/layer_0/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.539697 139933262464896 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.539777 139933262464896 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.539866 139933262464896 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.539956 139933262464896 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.540040 139933262464896 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.540125 139933262464896 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.540210 139933262464896 estimator_utils.py:212]   name = decoder/layer_0/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.540290 139933262464896 estimator_utils.py:212]   name = decoder/layer_0/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.540370 139933262464896 estimator_utils.py:212]   name = decoder/layer_0/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.540454 139933262464896 estimator_utils.py:212]   name = decoder/layer_0/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.540534 139933262464896 estimator_utils.py:212]   name = decoder/layer_0/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.540631 139933262464896 estimator_utils.py:212]   name = decoder/layer_0/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.540713 139933262464896 estimator_utils.py:212]   name = decoder/layer_1/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.540792 139933262464896 estimator_utils.py:212]   name = decoder/layer_1/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.540872 139933262464896 estimator_utils.py:212]   name = decoder/layer_1/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.540961 139933262464896 estimator_utils.py:212]   name = decoder/layer_1/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.541045 139933262464896 estimator_utils.py:212]   name = decoder/layer_1/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.541128 139933262464896 estimator_utils.py:212]   name = decoder/layer_1/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.541210 139933262464896 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.541288 139933262464896 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.541368 139933262464896 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.541455 139933262464896 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.541539 139933262464896 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.541634 139933262464896 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.541721 139933262464896 estimator_utils.py:212]   name = decoder/layer_1/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.541801 139933262464896 estimator_utils.py:212]   name = decoder/layer_1/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.541886 139933262464896 estimator_utils.py:212]   name = decoder/layer_1/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.541969 139933262464896 estimator_utils.py:212]   name = decoder/layer_1/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.542051 139933262464896 estimator_utils.py:212]   name = decoder/layer_1/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.542134 139933262464896 estimator_utils.py:212]   name = decoder/layer_1/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.542213 139933262464896 estimator_utils.py:212]   name = decoder/layer_2/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.542293 139933262464896 estimator_utils.py:212]   name = decoder/layer_2/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.542380 139933262464896 estimator_utils.py:212]   name = decoder/layer_2/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.542464 139933262464896 estimator_utils.py:212]   name = decoder/layer_2/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.542547 139933262464896 estimator_utils.py:212]   name = decoder/layer_2/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.542643 139933262464896 estimator_utils.py:212]   name = decoder/layer_2/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.542728 139933262464896 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.542808 139933262464896 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.542895 139933262464896 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.633187 139933262464896 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.633851 139933262464896 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.634172 139933262464896 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.634725 139933262464896 estimator_utils.py:212]   name = decoder/layer_2/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.635112 139933262464896 estimator_utils.py:212]   name = decoder/layer_2/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.635366 139933262464896 estimator_utils.py:212]   name = decoder/layer_2/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.635501 139933262464896 estimator_utils.py:212]   name = decoder/layer_2/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.635603 139933262464896 estimator_utils.py:212]   name = decoder/layer_2/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.635702 139933262464896 estimator_utils.py:212]   name = decoder/layer_2/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.635796 139933262464896 estimator_utils.py:212]   name = decoder/layer_3/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.635888 139933262464896 estimator_utils.py:212]   name = decoder/layer_3/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.635972 139933262464896 estimator_utils.py:212]   name = decoder/layer_3/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.636058 139933262464896 estimator_utils.py:212]   name = decoder/layer_3/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.636148 139933262464896 estimator_utils.py:212]   name = decoder/layer_3/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.636241 139933262464896 estimator_utils.py:212]   name = decoder/layer_3/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.636327 139933262464896 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.636411 139933262464896 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.636495 139933262464896 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.636593 139933262464896 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.636680 139933262464896 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.636766 139933262464896 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.636852 139933262464896 estimator_utils.py:212]   name = decoder/layer_3/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.636941 139933262464896 estimator_utils.py:212]   name = decoder/layer_3/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.637023 139933262464896 estimator_utils.py:212]   name = decoder/layer_3/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.637120 139933262464896 estimator_utils.py:212]   name = decoder/layer_3/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.637203 139933262464896 estimator_utils.py:212]   name = decoder/layer_3/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.637293 139933262464896 estimator_utils.py:212]   name = decoder/layer_3/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.637374 139933262464896 estimator_utils.py:212]   name = decoder/layer_4/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.637460 139933262464896 estimator_utils.py:212]   name = decoder/layer_4/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.637544 139933262464896 estimator_utils.py:212]   name = decoder/layer_4/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.637643 139933262464896 estimator_utils.py:212]   name = decoder/layer_4/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.637728 139933262464896 estimator_utils.py:212]   name = decoder/layer_4/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.637814 139933262464896 estimator_utils.py:212]   name = decoder/layer_4/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.637908 139933262464896 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.637990 139933262464896 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.638072 139933262464896 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.638157 139933262464896 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.638241 139933262464896 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.638333 139933262464896 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.638419 139933262464896 estimator_utils.py:212]   name = decoder/layer_4/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.638502 139933262464896 estimator_utils.py:212]   name = decoder/layer_4/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.638596 139933262464896 estimator_utils.py:212]   name = decoder/layer_4/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.638683 139933262464896 estimator_utils.py:212]   name = decoder/layer_4/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.638764 139933262464896 estimator_utils.py:212]   name = decoder/layer_4/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.638849 139933262464896 estimator_utils.py:212]   name = decoder/layer_4/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.638936 139933262464896 estimator_utils.py:212]   name = decoder/layer_5/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.639018 139933262464896 estimator_utils.py:212]   name = decoder/layer_5/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.639099 139933262464896 estimator_utils.py:212]   name = decoder/layer_5/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.639184 139933262464896 estimator_utils.py:212]   name = decoder/layer_5/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.639269 139933262464896 estimator_utils.py:212]   name = decoder/layer_5/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.639353 139933262464896 estimator_utils.py:212]   name = decoder/layer_5/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.639441 139933262464896 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.639522 139933262464896 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.639617 139933262464896 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.639700 139933262464896 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.639783 139933262464896 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.639868 139933262464896 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.639959 139933262464896 estimator_utils.py:212]   name = decoder/layer_5/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.640040 139933262464896 estimator_utils.py:212]   name = decoder/layer_5/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.640120 139933262464896 estimator_utils.py:212]   name = decoder/layer_5/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.640204 139933262464896 estimator_utils.py:212]   name = decoder/layer_5/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.640283 139933262464896 estimator_utils.py:212]   name = decoder/layer_5/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.640366 139933262464896 estimator_utils.py:212]   name = decoder/layer_5/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.640446 139933262464896 estimator_utils.py:212]   name = decoder/layer_6/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.640527 139933262464896 estimator_utils.py:212]   name = decoder/layer_6/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.640620 139933262464896 estimator_utils.py:212]   name = decoder/layer_6/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.640705 139933262464896 estimator_utils.py:212]   name = decoder/layer_6/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.640788 139933262464896 estimator_utils.py:212]   name = decoder/layer_6/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.640883 139933262464896 estimator_utils.py:212]   name = decoder/layer_6/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.640966 139933262464896 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.641049 139933262464896 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.641131 139933262464896 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.641214 139933262464896 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.641297 139933262464896 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.641379 139933262464896 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.641468 139933262464896 estimator_utils.py:212]   name = decoder/layer_6/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.641545 139933262464896 estimator_utils.py:212]   name = decoder/layer_6/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.641638 139933262464896 estimator_utils.py:212]   name = decoder/layer_6/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.641722 139933262464896 estimator_utils.py:212]   name = decoder/layer_6/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.641802 139933262464896 estimator_utils.py:212]   name = decoder/layer_6/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.641891 139933262464896 estimator_utils.py:212]   name = decoder/layer_6/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.641970 139933262464896 estimator_utils.py:212]   name = decoder/layer_7/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.642050 139933262464896 estimator_utils.py:212]   name = decoder/layer_7/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.642128 139933262464896 estimator_utils.py:212]   name = decoder/layer_7/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.642210 139933262464896 estimator_utils.py:212]   name = decoder/layer_7/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.642292 139933262464896 estimator_utils.py:212]   name = decoder/layer_7/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.642375 139933262464896 estimator_utils.py:212]   name = decoder/layer_7/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.642459 139933262464896 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.642539 139933262464896 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.642636 139933262464896 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.642721 139933262464896 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.642806 139933262464896 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.642896 139933262464896 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.642979 139933262464896 estimator_utils.py:212]   name = decoder/layer_7/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.643059 139933262464896 estimator_utils.py:212]   name = decoder/layer_7/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.643138 139933262464896 estimator_utils.py:212]   name = decoder/layer_7/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.643221 139933262464896 estimator_utils.py:212]   name = decoder/layer_7/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.643301 139933262464896 estimator_utils.py:212]   name = decoder/layer_7/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.643383 139933262464896 estimator_utils.py:212]   name = decoder/layer_7/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.643468 139933262464896 estimator_utils.py:212]   name = decoder/layer_8/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.643547 139933262464896 estimator_utils.py:212]   name = decoder/layer_8/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.643640 139933262464896 estimator_utils.py:212]   name = decoder/layer_8/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.643733 139933262464896 estimator_utils.py:212]   name = decoder/layer_8/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.643817 139933262464896 estimator_utils.py:212]   name = decoder/layer_8/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.643910 139933262464896 estimator_utils.py:212]   name = decoder/layer_8/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.643992 139933262464896 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.644073 139933262464896 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.644154 139933262464896 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.644234 139933262464896 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.644316 139933262464896 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.644400 139933262464896 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.644484 139933262464896 estimator_utils.py:212]   name = decoder/layer_8/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.644563 139933262464896 estimator_utils.py:212]   name = decoder/layer_8/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.644657 139933262464896 estimator_utils.py:212]   name = decoder/layer_8/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.644744 139933262464896 estimator_utils.py:212]   name = decoder/layer_8/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.644822 139933262464896 estimator_utils.py:212]   name = decoder/layer_8/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.644916 139933262464896 estimator_utils.py:212]   name = decoder/layer_8/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.645004 139933262464896 estimator_utils.py:212]   name = decoder/layer_9/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.645083 139933262464896 estimator_utils.py:212]   name = decoder/layer_9/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.645161 139933262464896 estimator_utils.py:212]   name = decoder/layer_9/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.645245 139933262464896 estimator_utils.py:212]   name = decoder/layer_9/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.645329 139933262464896 estimator_utils.py:212]   name = decoder/layer_9/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.645413 139933262464896 estimator_utils.py:212]   name = decoder/layer_9/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.737451 139933262464896 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.737721 139933262464896 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.737824 139933262464896 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.737932 139933262464896 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.738023 139933262464896 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.738111 139933262464896 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.738206 139933262464896 estimator_utils.py:212]   name = decoder/layer_9/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.738291 139933262464896 estimator_utils.py:212]   name = decoder/layer_9/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.738371 139933262464896 estimator_utils.py:212]   name = decoder/layer_9/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.738456 139933262464896 estimator_utils.py:212]   name = decoder/layer_9/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.738538 139933262464896 estimator_utils.py:212]   name = decoder/layer_9/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.738644 139933262464896 estimator_utils.py:212]   name = decoder/layer_9/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.738728 139933262464896 estimator_utils.py:212]   name = decoder/layer_10/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.738806 139933262464896 estimator_utils.py:212]   name = decoder/layer_10/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.738892 139933262464896 estimator_utils.py:212]   name = decoder/layer_10/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.738980 139933262464896 estimator_utils.py:212]   name = decoder/layer_10/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.739062 139933262464896 estimator_utils.py:212]   name = decoder/layer_10/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.739144 139933262464896 estimator_utils.py:212]   name = decoder/layer_10/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.739226 139933262464896 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.739305 139933262464896 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.739383 139933262464896 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.739465 139933262464896 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.739545 139933262464896 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.739656 139933262464896 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.739743 139933262464896 estimator_utils.py:212]   name = decoder/layer_10/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.739823 139933262464896 estimator_utils.py:212]   name = decoder/layer_10/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.739907 139933262464896 estimator_utils.py:212]   name = decoder/layer_10/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.739995 139933262464896 estimator_utils.py:212]   name = decoder/layer_10/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.740077 139933262464896 estimator_utils.py:212]   name = decoder/layer_10/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.740159 139933262464896 estimator_utils.py:212]   name = decoder/layer_10/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.740237 139933262464896 estimator_utils.py:212]   name = decoder/layer_11/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.740315 139933262464896 estimator_utils.py:212]   name = decoder/layer_11/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.740415 139933262464896 estimator_utils.py:212]   name = decoder/layer_11/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.741227 139933262464896 estimator_utils.py:212]   name = decoder/layer_11/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.741354 139933262464896 estimator_utils.py:212]   name = decoder/layer_11/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.741472 139933262464896 estimator_utils.py:212]   name = decoder/layer_11/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.741559 139933262464896 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.741679 139933262464896 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.741759 139933262464896 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.741849 139933262464896 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.741940 139933262464896 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.742027 139933262464896 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.742477 139933262464896 estimator_utils.py:212]   name = decoder/layer_11/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.742602 139933262464896 estimator_utils.py:212]   name = decoder/layer_11/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.742702 139933262464896 estimator_utils.py:212]   name = decoder/layer_11/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.742822 139933262464896 estimator_utils.py:212]   name = decoder/layer_11/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.742926 139933262464896 estimator_utils.py:212]   name = decoder/layer_11/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.743014 139933262464896 estimator_utils.py:212]   name = decoder/layer_11/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.743098 139933262464896 estimator_utils.py:212]   name = decoder/layer_12/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.743177 139933262464896 estimator_utils.py:212]   name = decoder/layer_12/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.743253 139933262464896 estimator_utils.py:212]   name = decoder/layer_12/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.743343 139933262464896 estimator_utils.py:212]   name = decoder/layer_12/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.743437 139933262464896 estimator_utils.py:212]   name = decoder/layer_12/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.743520 139933262464896 estimator_utils.py:212]   name = decoder/layer_12/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.743637 139933262464896 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.743734 139933262464896 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.743821 139933262464896 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.743912 139933262464896 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.744026 139933262464896 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.744111 139933262464896 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.744189 139933262464896 estimator_utils.py:212]   name = decoder/layer_12/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.744262 139933262464896 estimator_utils.py:212]   name = decoder/layer_12/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.744337 139933262464896 estimator_utils.py:212]   name = decoder/layer_12/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.744425 139933262464896 estimator_utils.py:212]   name = decoder/layer_12/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.744509 139933262464896 estimator_utils.py:212]   name = decoder/layer_12/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.744626 139933262464896 estimator_utils.py:212]   name = decoder/layer_12/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.744723 139933262464896 estimator_utils.py:212]   name = decoder/layer_13/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.744807 139933262464896 estimator_utils.py:212]   name = decoder/layer_13/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.745432 139933262464896 estimator_utils.py:212]   name = decoder/layer_13/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.745660 139933262464896 estimator_utils.py:212]   name = decoder/layer_13/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.745761 139933262464896 estimator_utils.py:212]   name = decoder/layer_13/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.745851 139933262464896 estimator_utils.py:212]   name = decoder/layer_13/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.745938 139933262464896 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.746020 139933262464896 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.746099 139933262464896 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.746183 139933262464896 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.746265 139933262464896 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.746348 139933262464896 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.746439 139933262464896 estimator_utils.py:212]   name = decoder/layer_13/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.746518 139933262464896 estimator_utils.py:212]   name = decoder/layer_13/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.746614 139933262464896 estimator_utils.py:212]   name = decoder/layer_13/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.746702 139933262464896 estimator_utils.py:212]   name = decoder/layer_13/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.746787 139933262464896 estimator_utils.py:212]   name = decoder/layer_13/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.746869 139933262464896 estimator_utils.py:212]   name = decoder/layer_13/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.746950 139933262464896 estimator_utils.py:212]   name = decoder/layer_14/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.747032 139933262464896 estimator_utils.py:212]   name = decoder/layer_14/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.747114 139933262464896 estimator_utils.py:212]   name = decoder/layer_14/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.747199 139933262464896 estimator_utils.py:212]   name = decoder/layer_14/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.747283 139933262464896 estimator_utils.py:212]   name = decoder/layer_14/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.747367 139933262464896 estimator_utils.py:212]   name = decoder/layer_14/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.747457 139933262464896 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.747539 139933262464896 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.747638 139933262464896 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.747718 139933262464896 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.747799 139933262464896 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.747880 139933262464896 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.747961 139933262464896 estimator_utils.py:212]   name = decoder/layer_14/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.748039 139933262464896 estimator_utils.py:212]   name = decoder/layer_14/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.748116 139933262464896 estimator_utils.py:212]   name = decoder/layer_14/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.748195 139933262464896 estimator_utils.py:212]   name = decoder/layer_14/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.748313 139933262464896 estimator_utils.py:212]   name = decoder/layer_14/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.748639 139933262464896 estimator_utils.py:212]   name = decoder/layer_14/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.748776 139933262464896 estimator_utils.py:212]   name = decoder/layer_15/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.748931 139933262464896 estimator_utils.py:212]   name = decoder/layer_15/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.749052 139933262464896 estimator_utils.py:212]   name = decoder/layer_15/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.749168 139933262464896 estimator_utils.py:212]   name = decoder/layer_15/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.749293 139933262464896 estimator_utils.py:212]   name = decoder/layer_15/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.749412 139933262464896 estimator_utils.py:212]   name = decoder/layer_15/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.749511 139933262464896 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.749674 139933262464896 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.749778 139933262464896 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.749874 139933262464896 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.749969 139933262464896 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.750057 139933262464896 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.750143 139933262464896 estimator_utils.py:212]   name = decoder/layer_15/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.750227 139933262464896 estimator_utils.py:212]   name = decoder/layer_15/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.750309 139933262464896 estimator_utils.py:212]   name = decoder/layer_15/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:33:22.750393 139933262464896 estimator_utils.py:212]   name = decoder/layer_15/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:33:22.750474 139933262464896 estimator_utils.py:212]   name = decoder/layer_15/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:33:22.750560 139933262464896 estimator_utils.py:212]   name = decoder/layer_15/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.837791 139933262464896 estimator_utils.py:212]   name = decoder/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:33:22.838099 139933262464896 estimator_utils.py:212]   name = decoder/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    INFO:tensorflow:Done calling model_fn.\n    I0830 20:33:22.858334 139933262464896 estimator.py:1150] Done calling model_fn.\n    INFO:tensorflow:Create CheckpointSaverHook.\n    I0830 20:33:22.859801 139933262464896 basic_session_run_hooks.py:541] Create CheckpointSaverHook.\n    INFO:tensorflow:Graph was finalized.\n    I0830 20:33:31.208243 139933262464896 monitored_session.py:240] Graph was finalized.\n    2020-08-30 20:33:31.208906: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA\n    2020-08-30 20:33:31.222437: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2200000000 Hz\n    2020-08-30 20:33:31.222921: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x1f9ea00 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n    2020-08-30 20:33:31.222965: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version\n    2020-08-30 20:33:41.833960: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 393637888 exceeds 10% of system memory.\n    INFO:tensorflow:Running local_init_op.\n    I0830 20:34:20.217569 139933262464896 session_manager.py:500] Running local_init_op.\n    INFO:tensorflow:Done running local_init_op.\n    I0830 20:34:21.131935 139933262464896 session_manager.py:502] Done running local_init_op.\n    INFO:tensorflow:Saving checkpoints for 0 into ckpt/pegasus_ckpt/aeslc/model.ckpt.\n    I0830 20:34:44.218886 139933262464896 basic_session_run_hooks.py:606] Saving checkpoints for 0 into ckpt/pegasus_ckpt/aeslc/model.ckpt.\n    2020-08-30 20:35:32.807699: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 393637888 exceeds 10% of system memory.\n    2020-08-30 20:35:34.095561: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 393637888 exceeds 10% of system memory.\n    2020-08-30 20:35:36.440229: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 393637888 exceeds 10% of system memory.\n    2020-08-30 20:36:00.828187: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 393637888 exceeds 10% of system memory.\n    ^C\n\n\n\n```\n!python3 pegasus/bin/train.py --params=cnn_dailymail_transformer \\\n--param_overrides=vocab_filename=ckpt/pegasus_ckpt/c4.unigram.newline.10pct.96000.model \\\n--train_init_checkpoint=ckpt/pegasus_ckpt/model.ckpt-1500000 \\\n--model_dir=ckpt/pegasus_ckpt/cnn_dailymail\n```\n\n    WARNING:tensorflow:From pegasus/bin/train.py:94: The name tf.app.run is deprecated. Please use tf.compat.v1.app.run instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/ops/public_parsing_ops.py:93: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n    \n    W0830 20:37:11.819154 140679300540288 module_wrapper.py:139] From /content/pegasus/pegasus/ops/public_parsing_ops.py:93: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:49: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead.\n    \n    W0830 20:37:12.039921 140679300540288 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:49: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead.\n    \n    WARNING:tensorflow:Estimator's model_fn (<function _estimator_model_fn.<locals>.model_fn at 0x7ff1f7ef6b70>) includes params argument, but params are not passed to Estimator.\n    W0830 20:37:12.040601 140679300540288 estimator.py:1994] Estimator's model_fn (<function _estimator_model_fn.<locals>.model_fn at 0x7ff1f7ef6b70>) includes params argument, but params are not passed to Estimator.\n    INFO:tensorflow:Using config: {'_model_dir': 'ckpt/pegasus_ckpt/cnn_dailymail', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': 1000, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true\n    , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': None, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7ff1f7eeacc0>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1, '_tpu_config': TPUConfig(iterations_per_loop=1000, num_shards=None, num_cores_per_replica=None, per_host_input_for_training=2, tpu_job_name=None, initial_infeed_sleep_secs=None, input_partition_dims=None, eval_training_input_configuration=2, experimental_host_call_every_n_steps=1), '_cluster': None}\n    I0830 20:37:12.041142 140679300540288 estimator.py:212] Using config: {'_model_dir': 'ckpt/pegasus_ckpt/cnn_dailymail', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': 1000, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true\n    , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': None, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7ff1f7eeacc0>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1, '_tpu_config': TPUConfig(iterations_per_loop=1000, num_shards=None, num_cores_per_replica=None, per_host_input_for_training=2, tpu_job_name=None, initial_infeed_sleep_secs=None, input_partition_dims=None, eval_training_input_configuration=2, experimental_host_call_every_n_steps=1), '_cluster': None}\n    INFO:tensorflow:_TPUContext: eval_on_tpu True\n    I0830 20:37:12.041419 140679300540288 tpu_context.py:220] _TPUContext: eval_on_tpu True\n    WARNING:tensorflow:eval_on_tpu ignored because use_tpu is False.\n    W0830 20:37:12.042281 140679300540288 tpu_context.py:222] eval_on_tpu ignored because use_tpu is False.\n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\n    Instructions for updating:\n    If using Keras pass *_constraint arguments to layers.\n    W0830 20:37:12.058464 140679300540288 deprecation.py:506] From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\n    Instructions for updating:\n    If using Keras pass *_constraint arguments to layers.\n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.\n    W0830 20:37:12.059060 140679300540288 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.\n    2020-08-30 20:37:12.082075: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    2020-08-30 20:37:12.284181: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    2020-08-30 20:37:12.492001: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    I0830 20:37:12.679994 140679300540288 dataset_info.py:424] Load pre-computed DatasetInfo (eg: splits, num examples,...) from GCS: cnn_dailymail/plain_text/3.0.0\n    2020-08-30 20:37:12.691979: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    I0830 20:37:12.889495 140679300540288 dataset_info.py:355] Load dataset info from /tmp/tmpfjl9s2ojtfds\n    I0830 20:37:12.891554 140679300540288 dataset_info.py:395] Field info.description from disk and from code do not match. Keeping the one from code.\n    I0830 20:37:12.891799 140679300540288 dataset_info.py:395] Field info.config_name from disk and from code do not match. Keeping the one from code.\n    I0830 20:37:12.891911 140679300540288 dataset_info.py:395] Field info.citation from disk and from code do not match. Keeping the one from code.\n    I0830 20:37:12.892290 140679300540288 dataset_builder.py:349] Generating dataset cnn_dailymail (/root/tensorflow_datasets/cnn_dailymail/plain_text/3.0.0)\n    \u001b[1mDownloading and preparing dataset cnn_dailymail/plain_text/3.0.0 (download: 558.32 MiB, generated: 1.27 GiB, total: 1.82 GiB) to /root/tensorflow_datasets/cnn_dailymail/plain_text/3.0.0...\u001b[0m\n    2020-08-30 20:37:12.987470: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    2020-08-30 20:37:13.172744: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    Dl Completed...: 0 url [00:00, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[AI0830 20:37:13.361479 140679300540288 download_manager.py:478] Downloading https://drive.google.com/uc?export=download&id=0BwmD_VLjROrfTHk4NFg2SndKcjQ into /root/tensorflow_datasets/downloads/ucexport_download_id_0BwmD_VLjROrfTHk4NFg2SndKG8BdJPpt2iRo6Dpzz23CByJuAePEilB-pxbcBCHaWDs.tmp.1437134628dd45d5a7d52e4768f2c7c0...\n    Dl Completed...:   0% 0/1 [00:00<?, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[AI0830 20:37:13.363606 140679300540288 download_manager.py:478] Downloading https://drive.google.com/uc?export=download&id=0BwmD_VLjROrfM1BxdkxVaTY2bWs into /root/tensorflow_datasets/downloads/ucexport_download_id_0BwmD_VLjROrfM1BxdkxVaTY2zVV-G71RIXPssrrvSAjt19Cy91r-9CQ2F9DMKA0uFk0.tmp.fe8cc85ee66e45d8ac54a0992b0e5f9b...\n    Dl Completed...:   0% 0/2 [00:00<?, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[AI0830 20:37:13.368501 140679300540288 download_manager.py:478] Downloading https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_test.txt into /root/tensorflow_datasets/downloads/raw.gith.com_abis_cnn-dail_mast_url_list_a705_isK790OHOPsIZX-ACsObq_vchU9r5Uduh6ULX3c.txt.tmp.aca66360d25b406b8ab2686e678486af...\n    Dl Completed...:   0% 0/3 [00:00<?, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[AI0830 20:37:13.371487 140679300540288 download_manager.py:478] Downloading https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_train.txt into /root/tensorflow_datasets/downloads/raw.gith.com_abis_cnn-dail_mast_url_list_ac8YFmYLc8VRUvf04x1htoZoMCha8FjkWxZzzNI42_Qk.txt.tmp.9819c04a98cf4a8cade5f5c39cafe909...\n    Dl Completed...:   0% 0/4 [00:00<?, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[AI0830 20:37:13.376146 140679300540288 download_manager.py:478] Downloading https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_val.txt into /root/tensorflow_datasets/downloads/raw.gith.com_abis_cnn-dail_mast_url_list_aICtMBRotWZqhw9th-ABXYHIqhoG-ATk7YrhmKRDVCdU.txt.tmp.83160b8cdcb746b6a399e7d2c6b34561...\n    Dl Completed...:   0% 0/5 [00:00<?, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/5 [00:00<?, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/5 [00:00<?, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/5 [00:00<?, ? url/s]\n    Dl Size...: 1 MiB [00:00,  1.25 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/5 [00:00<?, ? url/s]\n    Dl Size...: 2 MiB [00:00,  1.25 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/5 [00:00<?, ? url/s]\n    Dl Size...: 3 MiB [00:00,  1.25 MiB/s]\u001b[A\n    \n    Dl Completed...:  20% 1/5 [00:00<00:03,  1.19 url/s]\n    Dl Size...: 3 MiB [00:00,  1.25 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[AI0830 20:37:14.204159 140677177947904 download_manager.py:497] Skipping extraction for /root/tensorflow_datasets/downloads/raw.gith.com_abis_cnn-dail_mast_url_list_a705_isK790OHOPsIZX-ACsObq_vchU9r5Uduh6ULX3c.txt (method=NO_EXTRACT).\n    Dl Completed...:  20% 1/5 [00:00<00:03,  1.19 url/s]\n    Dl Size...: 4 MiB [00:00,  1.25 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:00<00:02,  1.19 url/s]\n    Dl Size...: 4 MiB [00:00,  1.25 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[AI0830 20:37:14.222264 140677161162496 download_manager.py:497] Skipping extraction for /root/tensorflow_datasets/downloads/raw.gith.com_abis_cnn-dail_mast_url_list_aICtMBRotWZqhw9th-ABXYHIqhoG-ATk7YrhmKRDVCdU.txt (method=NO_EXTRACT).\n    Dl Completed...:  40% 2/5 [00:01<00:02,  1.19 url/s]\n    Dl Size...: 4 MiB [00:01,  1.25 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:01, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:01<00:02,  1.19 url/s]\n    Dl Size...: 5 MiB [00:01,  1.59 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:01<00:02,  1.19 url/s]\n    Dl Size...: 6 MiB [00:01,  1.59 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:01<00:02,  1.19 url/s]\n    Dl Size...: 6 MiB [00:01,  1.59 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:01<00:02,  1.19 url/s]\n    Dl Size...: 7 MiB [00:01,  1.59 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:01<00:02,  1.19 url/s]\n    Dl Size...: 8 MiB [00:01,  1.59 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:01<00:02,  1.19 url/s]\n    Dl Size...: 9 MiB [00:01,  1.59 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:01<00:02,  1.19 url/s]\n    Dl Size...: 10 MiB [00:01,  1.59 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:01, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 11 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 12 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 13 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 14 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 15 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 16 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 17 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 18 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 19 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 20 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 21 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 22 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 23 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 24 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 25 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 26 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 27 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 28 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 29 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 30 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 31 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 32 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 33 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 34 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 35 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 36 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 37 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 38 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 39 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 40 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 41 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 42 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 43 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 44 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 45 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 46 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 47 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 48 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 49 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 50 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 51 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 52 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 53 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 54 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 55 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 56 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 57 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 58 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 59 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 60 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 61 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 62 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 63 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 64 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 65 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 66 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 67 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 68 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 69 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 70 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 71 MiB [00:02, 11.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 72 MiB [00:02, 11.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 73 MiB [00:02, 11.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 74 MiB [00:02, 11.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 75 MiB [00:02, 11.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 76 MiB [00:02, 11.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 77 MiB [00:02, 11.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 78 MiB [00:02, 11.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 79 MiB [00:02, 11.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 80 MiB [00:02, 11.84 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 81 MiB [00:02, 16.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 82 MiB [00:02, 16.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 83 MiB [00:02, 16.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 84 MiB [00:02, 16.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 85 MiB [00:02, 16.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 86 MiB [00:02, 16.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 87 MiB [00:02, 16.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 88 MiB [00:02, 16.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 89 MiB [00:02, 16.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 90 MiB [00:02, 16.06 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 91 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 92 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 93 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 94 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 95 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 96 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 97 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 98 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 99 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 100 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 101 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 102 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 103 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 104 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 105 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 106 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 107 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 108 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 109 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 110 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 111 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 112 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 113 MiB [00:02, 36.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 114 MiB [00:02, 36.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 115 MiB [00:03, 36.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 116 MiB [00:03, 36.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 117 MiB [00:03, 36.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 118 MiB [00:03, 36.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 119 MiB [00:03, 36.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 120 MiB [00:03, 36.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 121 MiB [00:03, 36.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 122 MiB [00:03, 36.10 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 123 MiB [00:03, 43.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 124 MiB [00:03, 43.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 125 MiB [00:03, 43.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 126 MiB [00:03, 43.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 127 MiB [00:03, 43.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 128 MiB [00:03, 43.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 129 MiB [00:03, 43.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 130 MiB [00:03, 43.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 131 MiB [00:03, 43.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 132 MiB [00:03, 43.22 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 133 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 134 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 135 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 136 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 137 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 138 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 139 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 140 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 141 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 142 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 143 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 144 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 145 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 146 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 147 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 148 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 149 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 150 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 151 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 152 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 153 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 154 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 155 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 156 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 157 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 158 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 159 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 160 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 161 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 162 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 163 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 164 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 165 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 166 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 167 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 168 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 169 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 170 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 171 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 172 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 173 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 174 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 175 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 176 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 177 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 178 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 179 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 180 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 181 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 182 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 183 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 184 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 185 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 186 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 187 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 188 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 189 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 190 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 191 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 192 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 193 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 194 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 195 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 196 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 197 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 198 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 199 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 200 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 201 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 202 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 203 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 204 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 205 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 206 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 207 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 208 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 209 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 210 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 211 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 212 MiB [00:03, 95.34 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 213 MiB [00:04, 95.34 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 214 MiB [00:04, 95.34 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 215 MiB [00:04, 95.34 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 216 MiB [00:04, 95.34 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 217 MiB [00:04, 95.34 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 218 MiB [00:04, 95.34 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 219 MiB [00:04, 95.34 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 220 MiB [00:04, 95.34 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 221 MiB [00:04, 95.34 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 222 MiB [00:04, 95.34 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 223 MiB [00:04, 89.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 224 MiB [00:04, 89.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 225 MiB [00:04, 89.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 226 MiB [00:04, 89.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 227 MiB [00:04, 89.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 228 MiB [00:04, 89.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 229 MiB [00:04, 89.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 230 MiB [00:04, 89.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 231 MiB [00:04, 89.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 232 MiB [00:04, 89.91 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 233 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 234 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 235 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 236 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 237 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 238 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 239 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 240 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 241 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 242 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 243 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 244 MiB [00:04, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 245 MiB [00:04, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 246 MiB [00:04, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 247 MiB [00:04, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 248 MiB [00:04, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 249 MiB [00:04, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 250 MiB [00:04, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:04<00:02,  1.12s/ url]\n    Dl Size...: 250 MiB [00:04, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:04<00:02,  1.12s/ url]\n    Dl Size...: 250 MiB [00:04, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:05<00:02,  1.12s/ url]\n    Dl Size...: 251 MiB [00:05, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:05<00:02,  1.12s/ url]\n    Dl Size...: 252 MiB [00:05, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:05<00:02,  1.12s/ url]\n    Dl Size...: 253 MiB [00:05, 96.24 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:05<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:05<00:02,  1.12s/ url]\n    Dl Size...: 254 MiB [00:05, 17.79 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 254 MiB [00:06, 17.79 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 255 MiB [00:06, 17.79 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 256 MiB [00:06, 17.79 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 257 MiB [00:06, 17.79 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 258 MiB [00:06, 17.79 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 259 MiB [00:06, 17.79 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 260 MiB [00:06, 17.79 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 261 MiB [00:06, 17.79 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:06<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 262 MiB [00:06, 20.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 263 MiB [00:06, 20.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 264 MiB [00:06, 20.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 265 MiB [00:06, 20.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 266 MiB [00:06, 20.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 267 MiB [00:06, 20.63 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:06<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 268 MiB [00:06, 25.04 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 269 MiB [00:06, 25.04 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 270 MiB [00:06, 25.04 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 271 MiB [00:06, 25.04 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 272 MiB [00:06, 25.04 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 273 MiB [00:06, 25.04 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:06<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 274 MiB [00:06, 29.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 275 MiB [00:06, 29.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 276 MiB [00:06, 29.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 277 MiB [00:06, 29.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 278 MiB [00:06, 29.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 279 MiB [00:06, 29.20 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:06<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 280 MiB [00:06, 31.89 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 281 MiB [00:06, 31.89 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 282 MiB [00:06, 31.89 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 283 MiB [00:06, 31.89 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 284 MiB [00:06, 31.89 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 285 MiB [00:06, 31.89 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:06<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 286 MiB [00:06, 36.36 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 287 MiB [00:06, 36.36 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 288 MiB [00:06, 36.36 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 289 MiB [00:06, 36.36 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 290 MiB [00:06, 36.36 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 291 MiB [00:06, 36.36 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:06<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 292 MiB [00:06, 39.03 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 293 MiB [00:06, 39.03 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 294 MiB [00:06, 39.03 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 295 MiB [00:06, 39.03 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 296 MiB [00:06, 39.03 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 297 MiB [00:06, 39.03 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:06<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 298 MiB [00:06, 39.93 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 299 MiB [00:07, 39.93 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 300 MiB [00:07, 39.93 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 301 MiB [00:07, 39.93 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 302 MiB [00:07, 39.93 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:07<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 303 MiB [00:07, 41.62 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 304 MiB [00:07, 41.62 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 305 MiB [00:07, 41.62 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 306 MiB [00:07, 41.62 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 307 MiB [00:07, 41.62 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 308 MiB [00:07, 41.62 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:07<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 309 MiB [00:07, 43.27 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 310 MiB [00:07, 43.27 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 311 MiB [00:07, 43.27 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 312 MiB [00:07, 43.27 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 313 MiB [00:07, 43.27 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:07<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 314 MiB [00:07, 43.67 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 315 MiB [00:07, 43.67 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 316 MiB [00:07, 43.67 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 317 MiB [00:07, 43.67 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 318 MiB [00:07, 43.67 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:07<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 319 MiB [00:07, 45.26 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 320 MiB [00:07, 45.26 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 321 MiB [00:07, 45.26 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 322 MiB [00:07, 45.26 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 323 MiB [00:07, 45.26 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 324 MiB [00:07, 45.26 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:07<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 325 MiB [00:07, 44.15 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 326 MiB [00:07, 44.15 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 327 MiB [00:07, 44.15 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 328 MiB [00:07, 44.15 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 329 MiB [00:07, 44.15 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 330 MiB [00:07, 44.15 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:07<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 331 MiB [00:07, 46.61 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 332 MiB [00:07, 46.61 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 333 MiB [00:07, 46.61 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 334 MiB [00:07, 46.61 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 335 MiB [00:07, 46.61 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:07<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 336 MiB [00:07, 40.13 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 337 MiB [00:07, 40.13 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 338 MiB [00:07, 40.13 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 339 MiB [00:07, 40.13 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 340 MiB [00:07, 40.13 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:07<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:08<00:02,  1.12s/ url]\n    Dl Size...: 341 MiB [00:08, 37.33 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:08<00:02,  1.12s/ url]\n    Dl Size...: 342 MiB [00:08, 37.33 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:08<00:02,  1.12s/ url]\n    Dl Size...: 343 MiB [00:08, 37.33 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 343 MiB [00:08, 37.33 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:08<?, ? file/s]\u001b[A\u001b[AI0830 20:37:21.425402 140677169555200 download_manager.py:497] Skipping extraction for /root/tensorflow_datasets/downloads/raw.gith.com_abis_cnn-dail_mast_url_list_ac8YFmYLc8VRUvf04x1htoZoMCha8FjkWxZzzNI42_Qk.txt (method=NO_EXTRACT).\n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 344 MiB [00:08, 37.33 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:08<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 345 MiB [00:08, 34.05 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 346 MiB [00:08, 34.05 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 347 MiB [00:08, 34.05 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 348 MiB [00:08, 34.05 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:08<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 349 MiB [00:08, 29.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 350 MiB [00:08, 29.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 351 MiB [00:08, 29.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 352 MiB [00:08, 29.08 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:08<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 353 MiB [00:08, 26.49 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 354 MiB [00:08, 26.49 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 355 MiB [00:08, 26.49 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:08<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 356 MiB [00:08, 24.65 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 357 MiB [00:08, 24.65 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 358 MiB [00:08, 24.65 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:08<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 359 MiB [00:08, 23.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 360 MiB [00:08, 23.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 361 MiB [00:08, 23.08 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:08<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 362 MiB [00:08, 22.37 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 363 MiB [00:09, 22.37 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 364 MiB [00:09, 22.37 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:09<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 365 MiB [00:09, 21.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 366 MiB [00:09, 21.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 367 MiB [00:09, 21.06 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:09<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 368 MiB [00:09, 16.23 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 369 MiB [00:09, 16.23 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 370 MiB [00:09, 16.23 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:09<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 371 MiB [00:09, 18.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 372 MiB [00:09, 18.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 373 MiB [00:09, 18.20 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:09<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 374 MiB [00:09, 19.52 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 375 MiB [00:10, 19.52 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 376 MiB [00:10, 19.52 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:10<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 377 MiB [00:10, 11.74 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 378 MiB [00:10, 11.74 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 379 MiB [00:10, 11.74 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:10<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 380 MiB [00:10, 13.87 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 381 MiB [00:10, 13.87 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 382 MiB [00:10, 13.87 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:10<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 383 MiB [00:10, 12.99 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 384 MiB [00:10, 12.99 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 385 MiB [00:10, 12.99 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:10<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 386 MiB [00:10, 14.90 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 387 MiB [00:10, 14.90 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 388 MiB [00:10, 14.90 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:10<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 389 MiB [00:10, 16.89 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 390 MiB [00:10, 16.89 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 391 MiB [00:10, 16.89 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:10<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 392 MiB [00:10, 17.82 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 393 MiB [00:10, 17.82 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 394 MiB [00:11, 17.82 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:11<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 395 MiB [00:11, 19.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 396 MiB [00:11, 19.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 397 MiB [00:11, 19.08 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:11<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 398 MiB [00:11, 20.16 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 399 MiB [00:11, 20.16 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 400 MiB [00:11, 20.16 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:11<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 401 MiB [00:11, 20.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 402 MiB [00:11, 20.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 403 MiB [00:11, 20.91 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:11<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 404 MiB [00:11, 21.43 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 405 MiB [00:11, 21.43 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 406 MiB [00:11, 21.43 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:11<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 407 MiB [00:12, 11.14 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 408 MiB [00:12, 11.14 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 409 MiB [00:12, 11.14 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:12<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 410 MiB [00:12, 13.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 411 MiB [00:12, 13.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 412 MiB [00:12, 13.20 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:12<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 413 MiB [00:12, 15.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 414 MiB [00:12, 15.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 415 MiB [00:12, 15.20 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:12<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 416 MiB [00:12, 12.68 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 417 MiB [00:12, 12.68 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 418 MiB [00:12, 12.68 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:12<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 419 MiB [00:12, 13.46 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 420 MiB [00:12, 13.46 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 421 MiB [00:12, 13.46 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:12<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 422 MiB [00:12, 15.81 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 423 MiB [00:13, 15.81 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:13<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 424 MiB [00:13, 11.30 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 425 MiB [00:13, 11.30 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 426 MiB [00:13, 11.30 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:13<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 427 MiB [00:13, 13.49 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 428 MiB [00:13, 13.49 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 429 MiB [00:13, 13.49 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:13<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 430 MiB [00:13, 15.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 431 MiB [00:13, 15.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 432 MiB [00:13, 15.50 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:13<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 433 MiB [00:13, 10.73 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 434 MiB [00:13, 10.73 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:14<00:01,  1.89s/ url]\n    Dl Size...: 435 MiB [00:14, 10.73 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:14<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:14<00:01,  1.89s/ url]\n    Dl Size...: 436 MiB [00:14, 13.02 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:14<00:01,  1.89s/ url]\n    Dl Size...: 437 MiB [00:14, 13.02 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:14<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:14<00:01,  1.89s/ url]\n    Dl Size...: 438 MiB [00:14, 14.48 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 439 MiB [00:15, 14.48 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:15<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 440 MiB [00:15,  4.72 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 441 MiB [00:15,  4.72 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 442 MiB [00:15,  4.72 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:15<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 443 MiB [00:15,  6.21 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 444 MiB [00:15,  6.21 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 445 MiB [00:15,  6.21 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:15<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 446 MiB [00:15,  7.97 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 447 MiB [00:15,  7.97 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 448 MiB [00:15,  7.97 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:15<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 449 MiB [00:15,  9.96 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 450 MiB [00:15,  9.96 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 451 MiB [00:15,  9.96 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:15<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 452 MiB [00:15, 12.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 453 MiB [00:15, 12.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 454 MiB [00:15, 12.10 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:15<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 455 MiB [00:15, 13.11 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 456 MiB [00:15, 13.11 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 457 MiB [00:16, 13.11 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:16<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 458 MiB [00:16, 15.21 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 459 MiB [00:16, 15.21 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 460 MiB [00:16, 15.21 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:16<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 461 MiB [00:16, 17.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 462 MiB [00:16, 17.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 463 MiB [00:16, 17.24 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:16<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 464 MiB [00:16, 16.88 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 465 MiB [00:16, 16.88 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 466 MiB [00:16, 16.88 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:16<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 467 MiB [00:16, 18.61 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 468 MiB [00:16, 18.61 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 469 MiB [00:16, 18.61 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:16<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 470 MiB [00:16, 20.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 471 MiB [00:16, 20.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 472 MiB [00:16, 20.22 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:16<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 473 MiB [00:16, 20.66 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 474 MiB [00:16, 20.66 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 475 MiB [00:16, 20.66 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:16<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 476 MiB [00:16, 21.18 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 477 MiB [00:16, 21.18 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 478 MiB [00:16, 21.18 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:16<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 479 MiB [00:17, 21.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 480 MiB [00:17, 21.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 481 MiB [00:17, 21.08 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:17<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 482 MiB [00:17, 21.28 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 483 MiB [00:17, 21.28 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 484 MiB [00:17, 21.28 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:17<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 485 MiB [00:17, 21.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 486 MiB [00:17, 21.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 487 MiB [00:17, 21.84 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:17<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 488 MiB [00:17, 22.07 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 489 MiB [00:17, 22.07 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 490 MiB [00:17, 22.07 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:17<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 491 MiB [00:17, 22.92 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 492 MiB [00:17, 22.92 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 493 MiB [00:17, 22.92 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:17<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 494 MiB [00:17, 23.21 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 495 MiB [00:17, 23.21 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 496 MiB [00:17, 23.21 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:17<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 497 MiB [00:17, 23.48 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 498 MiB [00:17, 23.48 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 499 MiB [00:17, 23.48 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:17<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 500 MiB [00:17, 24.21 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 501 MiB [00:17, 24.21 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 502 MiB [00:17, 24.21 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:17<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 503 MiB [00:18, 17.52 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 504 MiB [00:18, 17.52 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 505 MiB [00:18, 17.52 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:18<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 506 MiB [00:18, 19.33 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 507 MiB [00:18, 19.33 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 508 MiB [00:18, 19.33 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:18<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 509 MiB [00:18, 20.05 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 510 MiB [00:18, 20.05 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 511 MiB [00:18, 20.05 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:18<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 512 MiB [00:18, 18.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 513 MiB [00:18, 18.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 514 MiB [00:18, 18.84 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:18<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 515 MiB [00:18, 19.87 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 516 MiB [00:18, 19.87 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 517 MiB [00:18, 19.87 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:18<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 518 MiB [00:18, 21.33 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 519 MiB [00:18, 21.33 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 520 MiB [00:18, 21.33 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:18<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 521 MiB [00:19, 21.35 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 522 MiB [00:19, 21.35 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 523 MiB [00:19, 21.35 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:19<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 524 MiB [00:19, 20.77 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 525 MiB [00:19, 20.77 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 526 MiB [00:19, 20.77 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:19<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 527 MiB [00:19, 21.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 528 MiB [00:19, 21.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 529 MiB [00:19, 21.08 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:19<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 530 MiB [00:19, 20.18 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 531 MiB [00:19, 20.18 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 532 MiB [00:19, 20.18 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:19<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 533 MiB [00:19, 20.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 534 MiB [00:19, 20.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 535 MiB [00:19, 20.83 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:19<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 536 MiB [00:19, 21.74 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 537 MiB [00:19, 21.74 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 538 MiB [00:19, 21.74 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:19<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 539 MiB [00:19, 22.46 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 540 MiB [00:19, 22.46 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 541 MiB [00:19, 22.46 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:19<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 542 MiB [00:19, 22.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 543 MiB [00:20, 22.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 544 MiB [00:20, 22.50 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:20<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 545 MiB [00:20, 23.02 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 546 MiB [00:20, 23.02 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 547 MiB [00:20, 23.02 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:20<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 548 MiB [00:20, 22.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 549 MiB [00:20, 22.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 550 MiB [00:20, 22.83 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:20<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 551 MiB [00:20, 19.97 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 552 MiB [00:20, 19.97 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 553 MiB [00:20, 19.97 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:20<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 554 MiB [00:20, 20.97 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 555 MiB [00:20, 20.97 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 556 MiB [00:20, 20.97 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:20<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 557 MiB [00:20, 21.82 MiB/s]\u001b[A\n    \n    Dl Completed...: 100% 5/5 [00:20<00:00,  5.11s/ url]\n    Dl Size...: 557 MiB [00:20, 21.82 MiB/s]\u001b[A\n    \n    Dl Completed...: 100% 5/5 [00:20<00:00,  5.11s/ url]\n    Dl Size...: 557 MiB [00:20, 21.82 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/2 [00:20<?, ? file/s]\u001b[A\u001b[A\n    Dl Size...: 557 MiB [00:40, 21.82 MiB/s]\u001b[A\n    \n    Dl Completed...: 100% 5/5 [00:59<00:00,  5.11s/ url]\n    Dl Size...: 557 MiB [00:59, 21.82 MiB/s]\u001b[A\n    \n    Extraction completed...:  50% 1/2 [00:59<00:59, 59.25s/ file]\u001b[A\u001b[A\n    \n    Dl Completed...: 100% 5/5 [01:44<00:00,  5.11s/ url]\n    Dl Size...: 557 MiB [01:44, 21.82 MiB/s]\u001b[A\n    \n    Extraction completed...: 100% 2/2 [01:44<00:00, 55.02s/ file]\u001b[A\u001b[A\n    Extraction completed...: 100% 2/2 [01:44<00:00, 52.20s/ file]\n    \n    Dl Size...: 557 MiB [01:44,  5.34 MiB/s]\n    \n    Dl Completed...: 100% 5/5 [01:44<00:00, 20.88s/ url]\n    I0830 20:39:02.158226 140679300540288 dataset_builder.py:953] Generating split train\n    Shuffling and writing examples to /root/tensorflow_datasets/cnn_dailymail/plain_text/3.0.0.incompleteRG1WPL/cnn_dailymail-train.tfrecord\n     99% 285636/287113 [00:07<00:00, 41958.96 examples/s]I0830 20:42:47.938599 140679300540288 tfrecords_writer.py:226] Done writing /root/tensorflow_datasets/cnn_dailymail/plain_text/3.0.0.incompleteRG1WPL/cnn_dailymail-train.tfrecord. Shard lengths: [17945, 17944, 17945, 17944, 17945, 17944, 17945, 17944, 17945, 17945, 17944, 17945, 17944, 17945, 17944, 17945]\n    I0830 20:42:47.939977 140679300540288 dataset_builder.py:953] Generating split validation\n    Shuffling and writing examples to /root/tensorflow_datasets/cnn_dailymail/plain_text/3.0.0.incompleteRG1WPL/cnn_dailymail-validation.tfrecord\n     67% 8927/13368 [00:00<00:00, 89264.34 examples/s]I0830 20:42:57.685503 140679300540288 tfrecords_writer.py:226] Done writing /root/tensorflow_datasets/cnn_dailymail/plain_text/3.0.0.incompleteRG1WPL/cnn_dailymail-validation.tfrecord. Shard lengths: [13368]\n    I0830 20:42:57.697211 140679300540288 dataset_builder.py:953] Generating split test\n    Shuffling and writing examples to /root/tensorflow_datasets/cnn_dailymail/plain_text/3.0.0.incompleteRG1WPL/cnn_dailymail-test.tfrecord\n     80% 9194/11490 [00:00<00:00, 91934.83 examples/s]I0830 20:43:05.964109 140679300540288 tfrecords_writer.py:226] Done writing /root/tensorflow_datasets/cnn_dailymail/plain_text/3.0.0.incompleteRG1WPL/cnn_dailymail-test.tfrecord. Shard lengths: [11490]\n    I0830 20:43:05.994637 140679300540288 dataset_builder.py:404] Skipping computing stats for mode ComputeStatsMode.AUTO.\n    \u001b[1mDataset cnn_dailymail downloaded and prepared to /root/tensorflow_datasets/cnn_dailymail/plain_text/3.0.0. Subsequent calls will reuse this data.\u001b[0m\n    I0830 20:43:05.997262 140679300540288 dataset_builder.py:503] Constructing tf.data.Dataset for split train, from /root/tensorflow_datasets/cnn_dailymail/plain_text/3.0.0\n    I0830 20:43:06.453502 140679300540288 datasets.py:215] Number of examples for config cnn_dailymail/plain_text train is 287113\n    2020-08-30 20:43:07.298458: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1\n    2020-08-30 20:43:07.353359: E tensorflow/stream_executor/cuda/cuda_driver.cc:318] failed call to cuInit: CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected\n    2020-08-30 20:43:07.353458: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (d85487f9bac6): /proc/driver/nvidia/version does not exist\n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/ragged/ragged_tensor.py:1586: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use tf.where in 2.0, which has the same broadcast rule as np.where\n    W0830 20:43:07.487822 140679300540288 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/ragged/ragged_tensor.py:1586: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use tf.where in 2.0, which has the same broadcast rule as np.where\n    INFO:tensorflow:Calling model_fn.\n    I0830 20:43:07.811200 140679300540288 estimator.py:1148] Calling model_fn.\n    INFO:tensorflow:Running train on CPU\n    I0830 20:43:07.811529 140679300540288 tpu_estimator.py:3124] Running train on CPU\n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:78: The name tf.get_variable_scope is deprecated. Please use tf.compat.v1.get_variable_scope instead.\n    \n    W0830 20:43:07.811988 140679300540288 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:78: The name tf.get_variable_scope is deprecated. Please use tf.compat.v1.get_variable_scope instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/attention.py:41: The name tf.layers.Dense is deprecated. Please use tf.compat.v1.layers.Dense instead.\n    \n    W0830 20:43:07.812451 140679300540288 module_wrapper.py:139] From /content/pegasus/pegasus/layers/attention.py:41: The name tf.layers.Dense is deprecated. Please use tf.compat.v1.layers.Dense instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/embedding.py:57: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n    \n    W0830 20:43:07.862458 140679300540288 module_wrapper.py:139] From /content/pegasus/pegasus/layers/embedding.py:57: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/embedding.py:57: The name tf.AUTO_REUSE is deprecated. Please use tf.compat.v1.AUTO_REUSE instead.\n    \n    W0830 20:43:07.862782 140679300540288 module_wrapper.py:139] From /content/pegasus/pegasus/layers/embedding.py:57: The name tf.AUTO_REUSE is deprecated. Please use tf.compat.v1.AUTO_REUSE instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/embedding.py:61: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n    \n    W0830 20:43:07.863105 140679300540288 module_wrapper.py:139] From /content/pegasus/pegasus/layers/embedding.py:61: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/embedding.py:64: calling RandomNormal.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Call initializer instance with the dtype argument instead of passing it to the constructor\n    W0830 20:43:07.863389 140679300540288 deprecation.py:506] From /content/pegasus/pegasus/layers/embedding.py:64: calling RandomNormal.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Call initializer instance with the dtype argument instead of passing it to the constructor\n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/attention.py:106: The name tf.matrix_band_part is deprecated. Please use tf.linalg.band_part instead.\n    \n    W0830 20:43:11.083760 140679300540288 module_wrapper.py:139] From /content/pegasus/pegasus/layers/attention.py:106: The name tf.matrix_band_part is deprecated. Please use tf.linalg.band_part instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/models/transformer.py:108: The name tf.losses.softmax_cross_entropy is deprecated. Please use tf.compat.v1.losses.softmax_cross_entropy instead.\n    \n    W0830 20:43:16.036792 140679300540288 module_wrapper.py:139] From /content/pegasus/pegasus/models/transformer.py:108: The name tf.losses.softmax_cross_entropy is deprecated. Please use tf.compat.v1.losses.softmax_cross_entropy instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:113: The name tf.train.get_global_step is deprecated. Please use tf.compat.v1.train.get_global_step instead.\n    \n    W0830 20:43:16.094020 140679300540288 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:113: The name tf.train.get_global_step is deprecated. Please use tf.compat.v1.train.get_global_step instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:114: The name tf.rsqrt is deprecated. Please use tf.math.rsqrt instead.\n    \n    W0830 20:43:16.094403 140679300540288 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:114: The name tf.rsqrt is deprecated. Please use tf.math.rsqrt instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:115: to_float (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    W0830 20:43:16.094607 140679300540288 deprecation.py:323] From /content/pegasus/pegasus/params/estimator_utils.py:115: to_float (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    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/adafactor.py:315: The name tf.train.get_or_create_global_step is deprecated. Please use tf.compat.v1.train.get_or_create_global_step instead.\n    \n    W0830 20:43:16.103397 140679300540288 module_wrapper.py:139] From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/adafactor.py:315: The name tf.train.get_or_create_global_step is deprecated. Please use tf.compat.v1.train.get_or_create_global_step instead.\n    \n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/quantization.py:147: 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    W0830 20:43:16.108046 140679300540288 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/quantization.py:147: 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    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/quantization.py:156: The name tf.mod is deprecated. Please use tf.math.mod instead.\n    \n    W0830 20:43:16.110631 140679300540288 module_wrapper.py:139] From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/quantization.py:156: The name tf.mod is deprecated. Please use tf.math.mod instead.\n    \n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/adafactor.py:244: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead.\n    \n    W0830 20:43:30.796951 140679300540288 module_wrapper.py:139] From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/adafactor.py:244: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:189: The name tf.trainable_variables is deprecated. Please use tf.compat.v1.trainable_variables instead.\n    \n    W0830 20:43:45.739104 140679300540288 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:189: The name tf.trainable_variables is deprecated. Please use tf.compat.v1.trainable_variables instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:205: The name tf.train.init_from_checkpoint is deprecated. Please use tf.compat.v1.train.init_from_checkpoint instead.\n    \n    W0830 20:43:45.756763 140679300540288 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:205: The name tf.train.init_from_checkpoint is deprecated. Please use tf.compat.v1.train.init_from_checkpoint instead.\n    \n    I0830 20:43:47.189904 140679300540288 estimator_utils.py:207] **** Trainable Variables ****\n    I0830 20:43:47.190123 140679300540288 estimator_utils.py:212]   name = embeddings/weights:0, shape = (96103, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.190249 140679300540288 estimator_utils.py:212]   name = encoder/layer_0/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.190382 140679300540288 estimator_utils.py:212]   name = encoder/layer_0/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.190465 140679300540288 estimator_utils.py:212]   name = encoder/layer_0/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.190553 140679300540288 estimator_utils.py:212]   name = encoder/layer_0/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.190669 140679300540288 estimator_utils.py:212]   name = encoder/layer_0/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.190752 140679300540288 estimator_utils.py:212]   name = encoder/layer_0/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.190840 140679300540288 estimator_utils.py:212]   name = encoder/layer_0/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.190922 140679300540288 estimator_utils.py:212]   name = encoder/layer_0/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.191012 140679300540288 estimator_utils.py:212]   name = encoder/layer_0/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.191096 140679300540288 estimator_utils.py:212]   name = encoder/layer_0/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.191178 140679300540288 estimator_utils.py:212]   name = encoder/layer_0/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.191266 140679300540288 estimator_utils.py:212]   name = encoder/layer_0/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.191348 140679300540288 estimator_utils.py:212]   name = encoder/layer_1/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.191426 140679300540288 estimator_utils.py:212]   name = encoder/layer_1/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.191504 140679300540288 estimator_utils.py:212]   name = encoder/layer_1/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.191601 140679300540288 estimator_utils.py:212]   name = encoder/layer_1/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.191684 140679300540288 estimator_utils.py:212]   name = encoder/layer_1/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.191769 140679300540288 estimator_utils.py:212]   name = encoder/layer_1/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.191876 140679300540288 estimator_utils.py:212]   name = encoder/layer_1/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.191956 140679300540288 estimator_utils.py:212]   name = encoder/layer_1/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.192033 140679300540288 estimator_utils.py:212]   name = encoder/layer_1/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.192112 140679300540288 estimator_utils.py:212]   name = encoder/layer_1/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.192189 140679300540288 estimator_utils.py:212]   name = encoder/layer_1/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.192274 140679300540288 estimator_utils.py:212]   name = encoder/layer_1/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.192355 140679300540288 estimator_utils.py:212]   name = encoder/layer_2/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.192433 140679300540288 estimator_utils.py:212]   name = encoder/layer_2/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.192508 140679300540288 estimator_utils.py:212]   name = encoder/layer_2/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.192606 140679300540288 estimator_utils.py:212]   name = encoder/layer_2/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.192688 140679300540288 estimator_utils.py:212]   name = encoder/layer_2/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.192772 140679300540288 estimator_utils.py:212]   name = encoder/layer_2/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.192859 140679300540288 estimator_utils.py:212]   name = encoder/layer_2/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.192938 140679300540288 estimator_utils.py:212]   name = encoder/layer_2/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.193015 140679300540288 estimator_utils.py:212]   name = encoder/layer_2/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.193099 140679300540288 estimator_utils.py:212]   name = encoder/layer_2/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.193180 140679300540288 estimator_utils.py:212]   name = encoder/layer_2/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.193269 140679300540288 estimator_utils.py:212]   name = encoder/layer_2/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.193349 140679300540288 estimator_utils.py:212]   name = encoder/layer_3/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.193427 140679300540288 estimator_utils.py:212]   name = encoder/layer_3/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.193501 140679300540288 estimator_utils.py:212]   name = encoder/layer_3/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.193598 140679300540288 estimator_utils.py:212]   name = encoder/layer_3/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.193686 140679300540288 estimator_utils.py:212]   name = encoder/layer_3/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.193764 140679300540288 estimator_utils.py:212]   name = encoder/layer_3/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.193847 140679300540288 estimator_utils.py:212]   name = encoder/layer_3/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.193925 140679300540288 estimator_utils.py:212]   name = encoder/layer_3/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.194007 140679300540288 estimator_utils.py:212]   name = encoder/layer_3/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.194087 140679300540288 estimator_utils.py:212]   name = encoder/layer_3/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.194169 140679300540288 estimator_utils.py:212]   name = encoder/layer_3/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.194251 140679300540288 estimator_utils.py:212]   name = encoder/layer_3/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.194338 140679300540288 estimator_utils.py:212]   name = encoder/layer_4/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.194419 140679300540288 estimator_utils.py:212]   name = encoder/layer_4/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.194497 140679300540288 estimator_utils.py:212]   name = encoder/layer_4/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.194591 140679300540288 estimator_utils.py:212]   name = encoder/layer_4/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.194680 140679300540288 estimator_utils.py:212]   name = encoder/layer_4/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.194766 140679300540288 estimator_utils.py:212]   name = encoder/layer_4/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.194851 140679300540288 estimator_utils.py:212]   name = encoder/layer_4/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.194932 140679300540288 estimator_utils.py:212]   name = encoder/layer_4/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.195012 140679300540288 estimator_utils.py:212]   name = encoder/layer_4/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.195094 140679300540288 estimator_utils.py:212]   name = encoder/layer_4/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.195177 140679300540288 estimator_utils.py:212]   name = encoder/layer_4/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.195264 140679300540288 estimator_utils.py:212]   name = encoder/layer_4/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.195346 140679300540288 estimator_utils.py:212]   name = encoder/layer_5/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.195428 140679300540288 estimator_utils.py:212]   name = encoder/layer_5/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.195510 140679300540288 estimator_utils.py:212]   name = encoder/layer_5/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.195609 140679300540288 estimator_utils.py:212]   name = encoder/layer_5/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.195693 140679300540288 estimator_utils.py:212]   name = encoder/layer_5/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.195778 140679300540288 estimator_utils.py:212]   name = encoder/layer_5/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.195863 140679300540288 estimator_utils.py:212]   name = encoder/layer_5/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.195943 140679300540288 estimator_utils.py:212]   name = encoder/layer_5/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.196023 140679300540288 estimator_utils.py:212]   name = encoder/layer_5/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.196104 140679300540288 estimator_utils.py:212]   name = encoder/layer_5/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.196183 140679300540288 estimator_utils.py:212]   name = encoder/layer_5/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.196271 140679300540288 estimator_utils.py:212]   name = encoder/layer_5/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.196353 140679300540288 estimator_utils.py:212]   name = encoder/layer_6/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.196434 140679300540288 estimator_utils.py:212]   name = encoder/layer_6/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.196515 140679300540288 estimator_utils.py:212]   name = encoder/layer_6/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.196613 140679300540288 estimator_utils.py:212]   name = encoder/layer_6/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.196696 140679300540288 estimator_utils.py:212]   name = encoder/layer_6/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.196779 140679300540288 estimator_utils.py:212]   name = encoder/layer_6/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.196862 140679300540288 estimator_utils.py:212]   name = encoder/layer_6/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.196941 140679300540288 estimator_utils.py:212]   name = encoder/layer_6/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.197018 140679300540288 estimator_utils.py:212]   name = encoder/layer_6/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.197101 140679300540288 estimator_utils.py:212]   name = encoder/layer_6/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.197179 140679300540288 estimator_utils.py:212]   name = encoder/layer_6/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.197264 140679300540288 estimator_utils.py:212]   name = encoder/layer_6/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.197344 140679300540288 estimator_utils.py:212]   name = encoder/layer_7/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.197422 140679300540288 estimator_utils.py:212]   name = encoder/layer_7/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.197500 140679300540288 estimator_utils.py:212]   name = encoder/layer_7/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.197594 140679300540288 estimator_utils.py:212]   name = encoder/layer_7/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.197689 140679300540288 estimator_utils.py:212]   name = encoder/layer_7/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.197772 140679300540288 estimator_utils.py:212]   name = encoder/layer_7/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.197857 140679300540288 estimator_utils.py:212]   name = encoder/layer_7/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.197937 140679300540288 estimator_utils.py:212]   name = encoder/layer_7/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.198017 140679300540288 estimator_utils.py:212]   name = encoder/layer_7/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.198099 140679300540288 estimator_utils.py:212]   name = encoder/layer_7/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.198178 140679300540288 estimator_utils.py:212]   name = encoder/layer_7/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.198267 140679300540288 estimator_utils.py:212]   name = encoder/layer_7/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.198346 140679300540288 estimator_utils.py:212]   name = encoder/layer_8/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.198426 140679300540288 estimator_utils.py:212]   name = encoder/layer_8/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.198505 140679300540288 estimator_utils.py:212]   name = encoder/layer_8/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.198600 140679300540288 estimator_utils.py:212]   name = encoder/layer_8/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.198684 140679300540288 estimator_utils.py:212]   name = encoder/layer_8/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.198769 140679300540288 estimator_utils.py:212]   name = encoder/layer_8/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.198852 140679300540288 estimator_utils.py:212]   name = encoder/layer_8/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.198932 140679300540288 estimator_utils.py:212]   name = encoder/layer_8/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.199010 140679300540288 estimator_utils.py:212]   name = encoder/layer_8/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.199091 140679300540288 estimator_utils.py:212]   name = encoder/layer_8/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.199172 140679300540288 estimator_utils.py:212]   name = encoder/layer_8/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.199253 140679300540288 estimator_utils.py:212]   name = encoder/layer_8/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.199339 140679300540288 estimator_utils.py:212]   name = encoder/layer_9/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.199418 140679300540288 estimator_utils.py:212]   name = encoder/layer_9/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.199496 140679300540288 estimator_utils.py:212]   name = encoder/layer_9/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.199590 140679300540288 estimator_utils.py:212]   name = encoder/layer_9/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.199680 140679300540288 estimator_utils.py:212]   name = encoder/layer_9/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.199764 140679300540288 estimator_utils.py:212]   name = encoder/layer_9/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.199849 140679300540288 estimator_utils.py:212]   name = encoder/layer_9/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.199927 140679300540288 estimator_utils.py:212]   name = encoder/layer_9/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.200006 140679300540288 estimator_utils.py:212]   name = encoder/layer_9/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.200087 140679300540288 estimator_utils.py:212]   name = encoder/layer_9/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.200170 140679300540288 estimator_utils.py:212]   name = encoder/layer_9/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.211733 140679300540288 estimator_utils.py:212]   name = encoder/layer_9/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.212070 140679300540288 estimator_utils.py:212]   name = encoder/layer_10/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.212205 140679300540288 estimator_utils.py:212]   name = encoder/layer_10/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.212325 140679300540288 estimator_utils.py:212]   name = encoder/layer_10/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.212449 140679300540288 estimator_utils.py:212]   name = encoder/layer_10/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.212570 140679300540288 estimator_utils.py:212]   name = encoder/layer_10/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.212717 140679300540288 estimator_utils.py:212]   name = encoder/layer_10/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.212855 140679300540288 estimator_utils.py:212]   name = encoder/layer_10/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.212979 140679300540288 estimator_utils.py:212]   name = encoder/layer_10/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.213091 140679300540288 estimator_utils.py:212]   name = encoder/layer_10/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.213207 140679300540288 estimator_utils.py:212]   name = encoder/layer_10/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.213321 140679300540288 estimator_utils.py:212]   name = encoder/layer_10/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.213438 140679300540288 estimator_utils.py:212]   name = encoder/layer_10/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.213550 140679300540288 estimator_utils.py:212]   name = encoder/layer_11/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.213680 140679300540288 estimator_utils.py:212]   name = encoder/layer_11/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.213799 140679300540288 estimator_utils.py:212]   name = encoder/layer_11/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.213915 140679300540288 estimator_utils.py:212]   name = encoder/layer_11/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.214031 140679300540288 estimator_utils.py:212]   name = encoder/layer_11/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.214145 140679300540288 estimator_utils.py:212]   name = encoder/layer_11/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.214259 140679300540288 estimator_utils.py:212]   name = encoder/layer_11/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.214369 140679300540288 estimator_utils.py:212]   name = encoder/layer_11/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.214478 140679300540288 estimator_utils.py:212]   name = encoder/layer_11/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.214607 140679300540288 estimator_utils.py:212]   name = encoder/layer_11/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.214721 140679300540288 estimator_utils.py:212]   name = encoder/layer_11/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.214863 140679300540288 estimator_utils.py:212]   name = encoder/layer_11/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.214979 140679300540288 estimator_utils.py:212]   name = encoder/layer_12/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.215088 140679300540288 estimator_utils.py:212]   name = encoder/layer_12/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.215196 140679300540288 estimator_utils.py:212]   name = encoder/layer_12/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.215309 140679300540288 estimator_utils.py:212]   name = encoder/layer_12/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.215423 140679300540288 estimator_utils.py:212]   name = encoder/layer_12/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.215546 140679300540288 estimator_utils.py:212]   name = encoder/layer_12/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.215681 140679300540288 estimator_utils.py:212]   name = encoder/layer_12/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.215797 140679300540288 estimator_utils.py:212]   name = encoder/layer_12/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.215906 140679300540288 estimator_utils.py:212]   name = encoder/layer_12/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.216018 140679300540288 estimator_utils.py:212]   name = encoder/layer_12/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.216126 140679300540288 estimator_utils.py:212]   name = encoder/layer_12/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.216238 140679300540288 estimator_utils.py:212]   name = encoder/layer_12/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.216371 140679300540288 estimator_utils.py:212]   name = encoder/layer_13/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.216480 140679300540288 estimator_utils.py:212]   name = encoder/layer_13/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.216602 140679300540288 estimator_utils.py:212]   name = encoder/layer_13/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.216722 140679300540288 estimator_utils.py:212]   name = encoder/layer_13/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.216849 140679300540288 estimator_utils.py:212]   name = encoder/layer_13/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.216965 140679300540288 estimator_utils.py:212]   name = encoder/layer_13/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.217078 140679300540288 estimator_utils.py:212]   name = encoder/layer_13/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.217188 140679300540288 estimator_utils.py:212]   name = encoder/layer_13/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.217296 140679300540288 estimator_utils.py:212]   name = encoder/layer_13/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.217411 140679300540288 estimator_utils.py:212]   name = encoder/layer_13/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.217520 140679300540288 estimator_utils.py:212]   name = encoder/layer_13/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.217635 140679300540288 estimator_utils.py:212]   name = encoder/layer_13/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.217711 140679300540288 estimator_utils.py:212]   name = encoder/layer_14/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.217792 140679300540288 estimator_utils.py:212]   name = encoder/layer_14/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.217864 140679300540288 estimator_utils.py:212]   name = encoder/layer_14/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.217945 140679300540288 estimator_utils.py:212]   name = encoder/layer_14/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.218024 140679300540288 estimator_utils.py:212]   name = encoder/layer_14/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.218104 140679300540288 estimator_utils.py:212]   name = encoder/layer_14/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.218188 140679300540288 estimator_utils.py:212]   name = encoder/layer_14/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.218267 140679300540288 estimator_utils.py:212]   name = encoder/layer_14/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.218343 140679300540288 estimator_utils.py:212]   name = encoder/layer_14/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.218424 140679300540288 estimator_utils.py:212]   name = encoder/layer_14/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.218501 140679300540288 estimator_utils.py:212]   name = encoder/layer_14/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.218599 140679300540288 estimator_utils.py:212]   name = encoder/layer_14/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.218689 140679300540288 estimator_utils.py:212]   name = encoder/layer_15/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.218769 140679300540288 estimator_utils.py:212]   name = encoder/layer_15/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.218842 140679300540288 estimator_utils.py:212]   name = encoder/layer_15/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.218917 140679300540288 estimator_utils.py:212]   name = encoder/layer_15/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.218991 140679300540288 estimator_utils.py:212]   name = encoder/layer_15/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.219067 140679300540288 estimator_utils.py:212]   name = encoder/layer_15/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.219146 140679300540288 estimator_utils.py:212]   name = encoder/layer_15/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.219219 140679300540288 estimator_utils.py:212]   name = encoder/layer_15/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.219317 140679300540288 estimator_utils.py:212]   name = encoder/layer_15/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.219410 140679300540288 estimator_utils.py:212]   name = encoder/layer_15/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.219494 140679300540288 estimator_utils.py:212]   name = encoder/layer_15/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.219601 140679300540288 estimator_utils.py:212]   name = encoder/layer_15/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.219696 140679300540288 estimator_utils.py:212]   name = encoder/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.219792 140679300540288 estimator_utils.py:212]   name = encoder/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.219885 140679300540288 estimator_utils.py:212]   name = decoder/layer_0/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.219971 140679300540288 estimator_utils.py:212]   name = decoder/layer_0/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.220052 140679300540288 estimator_utils.py:212]   name = decoder/layer_0/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.220139 140679300540288 estimator_utils.py:212]   name = decoder/layer_0/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.220224 140679300540288 estimator_utils.py:212]   name = decoder/layer_0/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.220312 140679300540288 estimator_utils.py:212]   name = decoder/layer_0/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.220403 140679300540288 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.220488 140679300540288 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.220568 140679300540288 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.220671 140679300540288 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.220749 140679300540288 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.220857 140679300540288 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.220970 140679300540288 estimator_utils.py:212]   name = decoder/layer_0/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.221086 140679300540288 estimator_utils.py:212]   name = decoder/layer_0/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.221183 140679300540288 estimator_utils.py:212]   name = decoder/layer_0/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.221287 140679300540288 estimator_utils.py:212]   name = decoder/layer_0/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.221381 140679300540288 estimator_utils.py:212]   name = decoder/layer_0/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.221489 140679300540288 estimator_utils.py:212]   name = decoder/layer_0/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.221878 140679300540288 estimator_utils.py:212]   name = decoder/layer_1/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.222046 140679300540288 estimator_utils.py:212]   name = decoder/layer_1/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.222161 140679300540288 estimator_utils.py:212]   name = decoder/layer_1/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.222271 140679300540288 estimator_utils.py:212]   name = decoder/layer_1/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.222372 140679300540288 estimator_utils.py:212]   name = decoder/layer_1/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.222470 140679300540288 estimator_utils.py:212]   name = decoder/layer_1/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.222566 140679300540288 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.222688 140679300540288 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.222792 140679300540288 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.222895 140679300540288 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.222987 140679300540288 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.223078 140679300540288 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.223170 140679300540288 estimator_utils.py:212]   name = decoder/layer_1/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.223253 140679300540288 estimator_utils.py:212]   name = decoder/layer_1/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.223343 140679300540288 estimator_utils.py:212]   name = decoder/layer_1/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.223430 140679300540288 estimator_utils.py:212]   name = decoder/layer_1/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.223515 140679300540288 estimator_utils.py:212]   name = decoder/layer_1/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.223630 140679300540288 estimator_utils.py:212]   name = decoder/layer_1/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.223728 140679300540288 estimator_utils.py:212]   name = decoder/layer_2/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.223829 140679300540288 estimator_utils.py:212]   name = decoder/layer_2/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.223921 140679300540288 estimator_utils.py:212]   name = decoder/layer_2/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.224013 140679300540288 estimator_utils.py:212]   name = decoder/layer_2/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.224103 140679300540288 estimator_utils.py:212]   name = decoder/layer_2/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.224195 140679300540288 estimator_utils.py:212]   name = decoder/layer_2/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.224289 140679300540288 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.224380 140679300540288 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.224475 140679300540288 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.224572 140679300540288 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.224690 140679300540288 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.224789 140679300540288 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.224881 140679300540288 estimator_utils.py:212]   name = decoder/layer_2/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.224967 140679300540288 estimator_utils.py:212]   name = decoder/layer_2/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.225054 140679300540288 estimator_utils.py:212]   name = decoder/layer_2/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.225143 140679300540288 estimator_utils.py:212]   name = decoder/layer_2/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.225229 140679300540288 estimator_utils.py:212]   name = decoder/layer_2/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.225320 140679300540288 estimator_utils.py:212]   name = decoder/layer_2/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.225406 140679300540288 estimator_utils.py:212]   name = decoder/layer_3/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.225489 140679300540288 estimator_utils.py:212]   name = decoder/layer_3/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.225586 140679300540288 estimator_utils.py:212]   name = decoder/layer_3/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.225687 140679300540288 estimator_utils.py:212]   name = decoder/layer_3/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.225784 140679300540288 estimator_utils.py:212]   name = decoder/layer_3/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.225884 140679300540288 estimator_utils.py:212]   name = decoder/layer_3/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.225974 140679300540288 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.226061 140679300540288 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.226147 140679300540288 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.226238 140679300540288 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.226330 140679300540288 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.226415 140679300540288 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.226504 140679300540288 estimator_utils.py:212]   name = decoder/layer_3/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.226614 140679300540288 estimator_utils.py:212]   name = decoder/layer_3/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.226714 140679300540288 estimator_utils.py:212]   name = decoder/layer_3/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.226810 140679300540288 estimator_utils.py:212]   name = decoder/layer_3/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.226897 140679300540288 estimator_utils.py:212]   name = decoder/layer_3/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.226990 140679300540288 estimator_utils.py:212]   name = decoder/layer_3/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.227076 140679300540288 estimator_utils.py:212]   name = decoder/layer_4/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.227162 140679300540288 estimator_utils.py:212]   name = decoder/layer_4/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.227250 140679300540288 estimator_utils.py:212]   name = decoder/layer_4/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.227344 140679300540288 estimator_utils.py:212]   name = decoder/layer_4/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.227432 140679300540288 estimator_utils.py:212]   name = decoder/layer_4/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.227518 140679300540288 estimator_utils.py:212]   name = decoder/layer_4/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.227622 140679300540288 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.227714 140679300540288 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.227812 140679300540288 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.227909 140679300540288 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.228004 140679300540288 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.228088 140679300540288 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.228166 140679300540288 estimator_utils.py:212]   name = decoder/layer_4/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.228239 140679300540288 estimator_utils.py:212]   name = decoder/layer_4/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.228322 140679300540288 estimator_utils.py:212]   name = decoder/layer_4/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.228413 140679300540288 estimator_utils.py:212]   name = decoder/layer_4/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.228497 140679300540288 estimator_utils.py:212]   name = decoder/layer_4/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.228604 140679300540288 estimator_utils.py:212]   name = decoder/layer_4/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.228698 140679300540288 estimator_utils.py:212]   name = decoder/layer_5/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.228791 140679300540288 estimator_utils.py:212]   name = decoder/layer_5/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.228878 140679300540288 estimator_utils.py:212]   name = decoder/layer_5/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.228968 140679300540288 estimator_utils.py:212]   name = decoder/layer_5/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.229056 140679300540288 estimator_utils.py:212]   name = decoder/layer_5/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.229144 140679300540288 estimator_utils.py:212]   name = decoder/layer_5/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.229233 140679300540288 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.229329 140679300540288 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.229415 140679300540288 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.229503 140679300540288 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.229623 140679300540288 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.229721 140679300540288 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.229823 140679300540288 estimator_utils.py:212]   name = decoder/layer_5/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.229910 140679300540288 estimator_utils.py:212]   name = decoder/layer_5/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.229996 140679300540288 estimator_utils.py:212]   name = decoder/layer_5/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.230086 140679300540288 estimator_utils.py:212]   name = decoder/layer_5/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.230172 140679300540288 estimator_utils.py:212]   name = decoder/layer_5/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.230263 140679300540288 estimator_utils.py:212]   name = decoder/layer_5/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.230362 140679300540288 estimator_utils.py:212]   name = decoder/layer_6/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.230449 140679300540288 estimator_utils.py:212]   name = decoder/layer_6/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.230542 140679300540288 estimator_utils.py:212]   name = decoder/layer_6/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.230650 140679300540288 estimator_utils.py:212]   name = decoder/layer_6/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.230747 140679300540288 estimator_utils.py:212]   name = decoder/layer_6/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.230848 140679300540288 estimator_utils.py:212]   name = decoder/layer_6/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.230937 140679300540288 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.231030 140679300540288 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.231120 140679300540288 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.231212 140679300540288 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.231304 140679300540288 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.231396 140679300540288 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.231487 140679300540288 estimator_utils.py:212]   name = decoder/layer_6/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.231571 140679300540288 estimator_utils.py:212]   name = decoder/layer_6/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.231683 140679300540288 estimator_utils.py:212]   name = decoder/layer_6/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.231787 140679300540288 estimator_utils.py:212]   name = decoder/layer_6/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.231902 140679300540288 estimator_utils.py:212]   name = decoder/layer_6/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.232000 140679300540288 estimator_utils.py:212]   name = decoder/layer_6/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.232087 140679300540288 estimator_utils.py:212]   name = decoder/layer_7/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.232172 140679300540288 estimator_utils.py:212]   name = decoder/layer_7/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.232258 140679300540288 estimator_utils.py:212]   name = decoder/layer_7/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.232355 140679300540288 estimator_utils.py:212]   name = decoder/layer_7/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.232442 140679300540288 estimator_utils.py:212]   name = decoder/layer_7/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.232527 140679300540288 estimator_utils.py:212]   name = decoder/layer_7/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.232639 140679300540288 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.232728 140679300540288 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.232815 140679300540288 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.232904 140679300540288 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.232986 140679300540288 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.233077 140679300540288 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.322551 140679300540288 estimator_utils.py:212]   name = decoder/layer_7/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.322918 140679300540288 estimator_utils.py:212]   name = decoder/layer_7/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.323065 140679300540288 estimator_utils.py:212]   name = decoder/layer_7/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.323214 140679300540288 estimator_utils.py:212]   name = decoder/layer_7/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.323341 140679300540288 estimator_utils.py:212]   name = decoder/layer_7/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.323486 140679300540288 estimator_utils.py:212]   name = decoder/layer_7/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.323643 140679300540288 estimator_utils.py:212]   name = decoder/layer_8/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.323775 140679300540288 estimator_utils.py:212]   name = decoder/layer_8/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.323894 140679300540288 estimator_utils.py:212]   name = decoder/layer_8/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.324015 140679300540288 estimator_utils.py:212]   name = decoder/layer_8/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.324139 140679300540288 estimator_utils.py:212]   name = decoder/layer_8/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.324280 140679300540288 estimator_utils.py:212]   name = decoder/layer_8/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.324409 140679300540288 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.324525 140679300540288 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.324679 140679300540288 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.324806 140679300540288 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.324927 140679300540288 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.325047 140679300540288 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.325170 140679300540288 estimator_utils.py:212]   name = decoder/layer_8/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.325287 140679300540288 estimator_utils.py:212]   name = decoder/layer_8/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.325400 140679300540288 estimator_utils.py:212]   name = decoder/layer_8/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.325519 140679300540288 estimator_utils.py:212]   name = decoder/layer_8/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.325725 140679300540288 estimator_utils.py:212]   name = decoder/layer_8/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.325859 140679300540288 estimator_utils.py:212]   name = decoder/layer_8/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.325977 140679300540288 estimator_utils.py:212]   name = decoder/layer_9/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.326094 140679300540288 estimator_utils.py:212]   name = decoder/layer_9/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.326212 140679300540288 estimator_utils.py:212]   name = decoder/layer_9/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.326335 140679300540288 estimator_utils.py:212]   name = decoder/layer_9/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.326455 140679300540288 estimator_utils.py:212]   name = decoder/layer_9/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.326596 140679300540288 estimator_utils.py:212]   name = decoder/layer_9/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.326740 140679300540288 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.326855 140679300540288 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.326967 140679300540288 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.327084 140679300540288 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.327203 140679300540288 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.327323 140679300540288 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.327440 140679300540288 estimator_utils.py:212]   name = decoder/layer_9/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.327554 140679300540288 estimator_utils.py:212]   name = decoder/layer_9/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.327711 140679300540288 estimator_utils.py:212]   name = decoder/layer_9/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.327834 140679300540288 estimator_utils.py:212]   name = decoder/layer_9/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.327948 140679300540288 estimator_utils.py:212]   name = decoder/layer_9/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.328066 140679300540288 estimator_utils.py:212]   name = decoder/layer_9/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.328183 140679300540288 estimator_utils.py:212]   name = decoder/layer_10/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.328297 140679300540288 estimator_utils.py:212]   name = decoder/layer_10/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.328409 140679300540288 estimator_utils.py:212]   name = decoder/layer_10/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.328526 140679300540288 estimator_utils.py:212]   name = decoder/layer_10/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.328682 140679300540288 estimator_utils.py:212]   name = decoder/layer_10/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.328807 140679300540288 estimator_utils.py:212]   name = decoder/layer_10/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.328929 140679300540288 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.329042 140679300540288 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.329154 140679300540288 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.329271 140679300540288 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.329387 140679300540288 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.329507 140679300540288 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.329658 140679300540288 estimator_utils.py:212]   name = decoder/layer_10/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.329782 140679300540288 estimator_utils.py:212]   name = decoder/layer_10/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.329896 140679300540288 estimator_utils.py:212]   name = decoder/layer_10/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.330012 140679300540288 estimator_utils.py:212]   name = decoder/layer_10/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.330125 140679300540288 estimator_utils.py:212]   name = decoder/layer_10/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.330244 140679300540288 estimator_utils.py:212]   name = decoder/layer_10/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.330358 140679300540288 estimator_utils.py:212]   name = decoder/layer_11/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.330468 140679300540288 estimator_utils.py:212]   name = decoder/layer_11/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.330639 140679300540288 estimator_utils.py:212]   name = decoder/layer_11/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.330796 140679300540288 estimator_utils.py:212]   name = decoder/layer_11/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.330919 140679300540288 estimator_utils.py:212]   name = decoder/layer_11/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.331053 140679300540288 estimator_utils.py:212]   name = decoder/layer_11/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.331180 140679300540288 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.331295 140679300540288 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.331409 140679300540288 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.331528 140679300540288 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.331684 140679300540288 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.331809 140679300540288 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.331967 140679300540288 estimator_utils.py:212]   name = decoder/layer_11/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.332084 140679300540288 estimator_utils.py:212]   name = decoder/layer_11/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.332200 140679300540288 estimator_utils.py:212]   name = decoder/layer_11/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.332317 140679300540288 estimator_utils.py:212]   name = decoder/layer_11/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.332429 140679300540288 estimator_utils.py:212]   name = decoder/layer_11/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.332548 140679300540288 estimator_utils.py:212]   name = decoder/layer_11/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.332696 140679300540288 estimator_utils.py:212]   name = decoder/layer_12/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.332812 140679300540288 estimator_utils.py:212]   name = decoder/layer_12/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.332924 140679300540288 estimator_utils.py:212]   name = decoder/layer_12/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.333040 140679300540288 estimator_utils.py:212]   name = decoder/layer_12/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.333159 140679300540288 estimator_utils.py:212]   name = decoder/layer_12/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.333279 140679300540288 estimator_utils.py:212]   name = decoder/layer_12/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.333395 140679300540288 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.333507 140679300540288 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.333651 140679300540288 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.333781 140679300540288 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.333899 140679300540288 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.334019 140679300540288 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.334140 140679300540288 estimator_utils.py:212]   name = decoder/layer_12/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.334255 140679300540288 estimator_utils.py:212]   name = decoder/layer_12/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.334367 140679300540288 estimator_utils.py:212]   name = decoder/layer_12/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.334484 140679300540288 estimator_utils.py:212]   name = decoder/layer_12/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.334627 140679300540288 estimator_utils.py:212]   name = decoder/layer_12/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.334757 140679300540288 estimator_utils.py:212]   name = decoder/layer_12/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.334871 140679300540288 estimator_utils.py:212]   name = decoder/layer_13/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.334985 140679300540288 estimator_utils.py:212]   name = decoder/layer_13/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.335097 140679300540288 estimator_utils.py:212]   name = decoder/layer_13/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.335218 140679300540288 estimator_utils.py:212]   name = decoder/layer_13/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.335336 140679300540288 estimator_utils.py:212]   name = decoder/layer_13/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.335453 140679300540288 estimator_utils.py:212]   name = decoder/layer_13/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.335568 140679300540288 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.335725 140679300540288 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.335840 140679300540288 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.335957 140679300540288 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.336076 140679300540288 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.336197 140679300540288 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.336317 140679300540288 estimator_utils.py:212]   name = decoder/layer_13/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.336429 140679300540288 estimator_utils.py:212]   name = decoder/layer_13/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.336541 140679300540288 estimator_utils.py:212]   name = decoder/layer_13/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.336736 140679300540288 estimator_utils.py:212]   name = decoder/layer_13/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.336859 140679300540288 estimator_utils.py:212]   name = decoder/layer_13/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.336980 140679300540288 estimator_utils.py:212]   name = decoder/layer_13/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.337094 140679300540288 estimator_utils.py:212]   name = decoder/layer_14/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.337210 140679300540288 estimator_utils.py:212]   name = decoder/layer_14/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.337323 140679300540288 estimator_utils.py:212]   name = decoder/layer_14/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.337441 140679300540288 estimator_utils.py:212]   name = decoder/layer_14/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.337560 140679300540288 estimator_utils.py:212]   name = decoder/layer_14/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.337718 140679300540288 estimator_utils.py:212]   name = decoder/layer_14/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.337844 140679300540288 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.337957 140679300540288 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.338069 140679300540288 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.338190 140679300540288 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.338309 140679300540288 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.338427 140679300540288 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.338544 140679300540288 estimator_utils.py:212]   name = decoder/layer_14/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.338697 140679300540288 estimator_utils.py:212]   name = decoder/layer_14/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.338815 140679300540288 estimator_utils.py:212]   name = decoder/layer_14/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.338933 140679300540288 estimator_utils.py:212]   name = decoder/layer_14/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.339046 140679300540288 estimator_utils.py:212]   name = decoder/layer_14/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.339168 140679300540288 estimator_utils.py:212]   name = decoder/layer_14/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.339284 140679300540288 estimator_utils.py:212]   name = decoder/layer_15/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.339396 140679300540288 estimator_utils.py:212]   name = decoder/layer_15/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.339507 140679300540288 estimator_utils.py:212]   name = decoder/layer_15/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.339659 140679300540288 estimator_utils.py:212]   name = decoder/layer_15/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.339787 140679300540288 estimator_utils.py:212]   name = decoder/layer_15/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.339908 140679300540288 estimator_utils.py:212]   name = decoder/layer_15/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.340025 140679300540288 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.340140 140679300540288 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.340256 140679300540288 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.340374 140679300540288 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.340491 140679300540288 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.340643 140679300540288 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.340774 140679300540288 estimator_utils.py:212]   name = decoder/layer_15/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.340890 140679300540288 estimator_utils.py:212]   name = decoder/layer_15/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.341003 140679300540288 estimator_utils.py:212]   name = decoder/layer_15/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 20:43:47.341137 140679300540288 estimator_utils.py:212]   name = decoder/layer_15/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 20:43:47.341253 140679300540288 estimator_utils.py:212]   name = decoder/layer_15/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 20:43:47.341371 140679300540288 estimator_utils.py:212]   name = decoder/layer_15/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.341485 140679300540288 estimator_utils.py:212]   name = decoder/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 20:43:47.341626 140679300540288 estimator_utils.py:212]   name = decoder/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    INFO:tensorflow:Done calling model_fn.\n    I0830 20:43:47.366027 140679300540288 estimator.py:1150] Done calling model_fn.\n    INFO:tensorflow:Create CheckpointSaverHook.\n    I0830 20:43:47.367480 140679300540288 basic_session_run_hooks.py:541] Create CheckpointSaverHook.\n    INFO:tensorflow:Graph was finalized.\n    I0830 20:43:55.546775 140679300540288 monitored_session.py:240] Graph was finalized.\n    2020-08-30 20:43:55.554801: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA\n    2020-08-30 20:43:55.650119: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2200000000 Hz\n    2020-08-30 20:43:55.652475: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x86de700 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n    2020-08-30 20:43:55.652534: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version\n    2020-08-30 20:44:24.884592: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 393637888 exceeds 10% of system memory.\n    INFO:tensorflow:Running local_init_op.\n    I0830 20:44:44.603399 140679300540288 session_manager.py:500] Running local_init_op.\n    INFO:tensorflow:Done running local_init_op.\n    I0830 20:44:45.537065 140679300540288 session_manager.py:502] Done running local_init_op.\n    INFO:tensorflow:Saving checkpoints for 0 into ckpt/pegasus_ckpt/cnn_dailymail/model.ckpt.\n    I0830 20:45:09.208391 140679300540288 basic_session_run_hooks.py:606] Saving checkpoints for 0 into ckpt/pegasus_ckpt/cnn_dailymail/model.ckpt.\n    2020-08-30 20:46:22.548933: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 33554432 exceeds 10% of system memory.\n    2020-08-30 20:46:22.569661: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 33554432 exceeds 10% of system memory.\n    2020-08-30 20:46:22.877970: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 33554432 exceeds 10% of system memory.\n    2020-08-30 20:46:22.897384: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 33554432 exceeds 10% of system memory.\n    2020-08-30 20:46:33.892106: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:145] Filling up shuffle buffer (this may take a while): 1768 of 10000\n    2020-08-30 20:46:43.888265: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:145] Filling up shuffle buffer (this may take a while): 4272 of 10000\n    2020-08-30 20:46:53.890066: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:145] Filling up shuffle buffer (this may take a while): 6798 of 10000\n    2020-08-30 20:47:03.890913: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:145] Filling up shuffle buffer (this may take a while): 9230 of 10000\n    2020-08-30 20:47:06.878909: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:195] Shuffle buffer filled.\n    ^C\n\n\n\n```\n!python3 pegasus/bin/train.py --params=gigaword_transformer \\\n--param_overrides=vocab_filename=ckpt/pegasus_ckpt/c4.unigram.newline.10pct.96000.model \\\n--train_init_checkpoint=ckpt/pegasus_ckpt/model.ckpt-1500000 \\\n--model_dir=ckpt/pegasus_ckpt/gigaword\n```\n\n    WARNING:tensorflow:From pegasus/bin/train.py:94: The name tf.app.run is deprecated. Please use tf.compat.v1.app.run instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/ops/public_parsing_ops.py:93: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n    \n    W0830 20:48:17.926240 140123635914624 module_wrapper.py:139] From /content/pegasus/pegasus/ops/public_parsing_ops.py:93: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:49: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead.\n    \n    W0830 20:48:18.144308 140123635914624 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:49: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead.\n    \n    WARNING:tensorflow:Estimator's model_fn (<function _estimator_model_fn.<locals>.model_fn at 0x7f7097be2b70>) includes params argument, but params are not passed to Estimator.\n    W0830 20:48:18.145047 140123635914624 estimator.py:1994] Estimator's model_fn (<function _estimator_model_fn.<locals>.model_fn at 0x7f7097be2b70>) includes params argument, but params are not passed to Estimator.\n    INFO:tensorflow:Using config: {'_model_dir': 'ckpt/pegasus_ckpt/gigaword', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': 1000, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true\n    , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': None, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7f7097bd6d30>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1, '_tpu_config': TPUConfig(iterations_per_loop=1000, num_shards=None, num_cores_per_replica=None, per_host_input_for_training=2, tpu_job_name=None, initial_infeed_sleep_secs=None, input_partition_dims=None, eval_training_input_configuration=2, experimental_host_call_every_n_steps=1), '_cluster': None}\n    I0830 20:48:18.145653 140123635914624 estimator.py:212] Using config: {'_model_dir': 'ckpt/pegasus_ckpt/gigaword', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': 1000, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true\n    , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': None, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7f7097bd6d30>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1, '_tpu_config': TPUConfig(iterations_per_loop=1000, num_shards=None, num_cores_per_replica=None, per_host_input_for_training=2, tpu_job_name=None, initial_infeed_sleep_secs=None, input_partition_dims=None, eval_training_input_configuration=2, experimental_host_call_every_n_steps=1), '_cluster': None}\n    INFO:tensorflow:_TPUContext: eval_on_tpu True\n    I0830 20:48:18.145952 140123635914624 tpu_context.py:220] _TPUContext: eval_on_tpu True\n    WARNING:tensorflow:eval_on_tpu ignored because use_tpu is False.\n    W0830 20:48:18.146801 140123635914624 tpu_context.py:222] eval_on_tpu ignored because use_tpu is False.\n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\n    Instructions for updating:\n    If using Keras pass *_constraint arguments to layers.\n    W0830 20:48:18.161318 140123635914624 deprecation.py:506] From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\n    Instructions for updating:\n    If using Keras pass *_constraint arguments to layers.\n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.\n    W0830 20:48:18.161942 140123635914624 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.\n    2020-08-30 20:48:18.187975: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    2020-08-30 20:48:18.395268: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    2020-08-30 20:48:18.608476: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    I0830 20:48:18.798180 140123635914624 dataset_info.py:424] Load pre-computed DatasetInfo (eg: splits, num examples,...) from GCS: gigaword/1.2.0\n    2020-08-30 20:48:18.811108: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    I0830 20:48:19.330303 140123635914624 dataset_info.py:355] Load dataset info from /tmp/tmpkyjkuj0itfds\n    I0830 20:48:19.332242 140123635914624 dataset_info.py:395] Field info.description from disk and from code do not match. Keeping the one from code.\n    I0830 20:48:19.332455 140123635914624 dataset_info.py:395] Field info.citation from disk and from code do not match. Keeping the one from code.\n    I0830 20:48:19.332840 140123635914624 dataset_builder.py:349] Generating dataset gigaword (/root/tensorflow_datasets/gigaword/1.2.0)\n    \u001b[1mDownloading and preparing dataset gigaword/1.2.0 (download: 551.61 MiB, generated: Unknown size, total: 551.61 MiB) to /root/tensorflow_datasets/gigaword/1.2.0...\u001b[0m\n    2020-08-30 20:48:19.431295: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    2020-08-30 20:48:19.665765: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    Dl Completed...: 0 url [00:00, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[AI0830 20:48:19.895812 140123635914624 download_manager.py:478] Downloading https://drive.google.com/uc?export=download&id=1USoQ8lJgN8kAWnUnRrupMGrPMLlDVqlV into /root/tensorflow_datasets/downloads/ucexport_download_id_1USoQ8lJgN8kAWnUnRrupMGrPbaUkMbtRJNkM9RoBh9Lb7pBG6JeAxL51mXlKT1WQSOw.tmp.58ccca7218424b508a15231967083386...\n    Dl Completed...:   0% 0/1 [00:00<?, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:01<?, ? url/s]\n    Dl Size...: 0 MiB [00:01, ? MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:01, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:01<?, ? url/s]\n    Dl Size...: 1 MiB [00:01,  1.93s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:01<?, ? url/s]\n    Dl Size...: 2 MiB [00:01,  1.93s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:01<?, ? url/s]\n    Dl Size...: 3 MiB [00:01,  1.93s/ MiB]\u001b[A\n    \n    Extraction completed...: 0 file [00:01, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 4 MiB [00:02,  1.39s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 5 MiB [00:02,  1.39s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 6 MiB [00:02,  1.39s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 7 MiB [00:02,  1.39s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 8 MiB [00:02,  1.39s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 9 MiB [00:02,  1.39s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 10 MiB [00:02,  1.39s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 11 MiB [00:02,  1.39s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 12 MiB [00:02,  1.39s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 13 MiB [00:02,  1.39s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 14 MiB [00:02,  1.39s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 15 MiB [00:02,  1.39s/ MiB]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 16 MiB [00:02,  1.03 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 17 MiB [00:02,  1.03 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 18 MiB [00:02,  1.03 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 19 MiB [00:02,  1.03 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 20 MiB [00:02,  1.03 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 21 MiB [00:02,  1.03 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 22 MiB [00:02,  1.03 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 23 MiB [00:02,  1.03 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 24 MiB [00:02,  1.03 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 25 MiB [00:02,  1.03 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 26 MiB [00:02,  1.03 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 27 MiB [00:02,  1.03 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 28 MiB [00:02,  1.03 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 29 MiB [00:02,  1.46 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 30 MiB [00:02,  1.46 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 31 MiB [00:02,  1.46 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 32 MiB [00:02,  1.46 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 33 MiB [00:02,  1.46 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 34 MiB [00:02,  1.46 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 35 MiB [00:02,  1.46 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 36 MiB [00:02,  2.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 37 MiB [00:02,  2.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 38 MiB [00:02,  2.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 39 MiB [00:02,  2.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 40 MiB [00:02,  2.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 41 MiB [00:02,  2.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 42 MiB [00:02,  2.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 43 MiB [00:02,  2.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 44 MiB [00:02,  2.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 45 MiB [00:02,  2.06 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 46 MiB [00:02,  2.92 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 47 MiB [00:02,  2.92 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 48 MiB [00:02,  2.92 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 49 MiB [00:02,  2.92 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 50 MiB [00:02,  2.92 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 51 MiB [00:02,  2.92 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 52 MiB [00:02,  2.92 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 53 MiB [00:02,  2.92 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 54 MiB [00:02,  2.92 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 55 MiB [00:02,  2.92 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 56 MiB [00:02,  2.92 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 57 MiB [00:02,  2.92 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 58 MiB [00:02,  4.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 59 MiB [00:02,  4.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 60 MiB [00:02,  4.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 61 MiB [00:02,  4.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 62 MiB [00:02,  4.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 63 MiB [00:02,  4.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 64 MiB [00:03,  4.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 65 MiB [00:03,  4.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 66 MiB [00:03,  4.12 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 67 MiB [00:03,  5.71 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 68 MiB [00:03,  5.71 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 69 MiB [00:03,  5.71 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 70 MiB [00:03,  5.71 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 71 MiB [00:03,  5.71 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 72 MiB [00:03,  5.71 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 73 MiB [00:03,  5.71 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 74 MiB [00:03,  5.71 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 75 MiB [00:03,  7.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 76 MiB [00:03,  7.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 77 MiB [00:03,  7.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 78 MiB [00:03,  7.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 79 MiB [00:03,  7.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 80 MiB [00:03,  7.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 81 MiB [00:03,  7.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 82 MiB [00:03,  7.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 83 MiB [00:03,  7.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 84 MiB [00:03,  7.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 85 MiB [00:03,  7.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 86 MiB [00:03,  7.86 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 87 MiB [00:03, 10.91 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 88 MiB [00:03, 10.91 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 89 MiB [00:03, 10.91 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 90 MiB [00:03, 10.91 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 91 MiB [00:03, 10.91 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 92 MiB [00:03, 10.91 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 93 MiB [00:03, 10.91 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 94 MiB [00:03, 10.91 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 95 MiB [00:03, 10.91 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 96 MiB [00:03, 14.43 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 97 MiB [00:03, 14.43 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 98 MiB [00:03, 14.43 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 99 MiB [00:03, 14.43 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 100 MiB [00:03, 14.43 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 101 MiB [00:03, 14.43 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 102 MiB [00:03, 14.43 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 103 MiB [00:03, 14.43 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 104 MiB [00:03, 18.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 105 MiB [00:03, 18.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 106 MiB [00:03, 18.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 107 MiB [00:03, 18.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 108 MiB [00:03, 18.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 109 MiB [00:03, 18.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 110 MiB [00:03, 18.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 111 MiB [00:03, 18.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 112 MiB [00:03, 18.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 113 MiB [00:03, 18.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 114 MiB [00:03, 18.66 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 115 MiB [00:03, 24.70 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 116 MiB [00:03, 24.70 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 117 MiB [00:03, 24.70 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 118 MiB [00:03, 24.70 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 119 MiB [00:03, 24.70 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 120 MiB [00:03, 24.70 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 121 MiB [00:03, 24.70 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 122 MiB [00:03, 24.70 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 123 MiB [00:03, 24.70 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 124 MiB [00:03, 31.43 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 125 MiB [00:03, 31.43 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 126 MiB [00:03, 31.43 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 127 MiB [00:03, 31.43 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 128 MiB [00:03, 31.43 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 129 MiB [00:03, 31.43 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 130 MiB [00:03, 31.43 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 131 MiB [00:03, 31.43 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 132 MiB [00:03, 31.43 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 133 MiB [00:03, 38.63 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 134 MiB [00:03, 38.63 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 135 MiB [00:03, 38.63 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 136 MiB [00:03, 38.63 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 137 MiB [00:03, 38.63 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 138 MiB [00:03, 38.63 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 139 MiB [00:04, 38.63 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 140 MiB [00:04, 38.63 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 141 MiB [00:04, 38.63 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 142 MiB [00:04, 42.90 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 143 MiB [00:04, 42.90 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 144 MiB [00:04, 42.90 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 145 MiB [00:04, 42.90 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 146 MiB [00:04, 42.90 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 147 MiB [00:04, 42.90 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 148 MiB [00:04, 42.90 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 149 MiB [00:04, 42.90 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 150 MiB [00:04, 42.90 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 151 MiB [00:04, 42.90 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 152 MiB [00:04, 42.90 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 153 MiB [00:04, 52.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 154 MiB [00:04, 52.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 155 MiB [00:04, 52.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 156 MiB [00:04, 52.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 157 MiB [00:04, 52.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 158 MiB [00:04, 52.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 159 MiB [00:04, 52.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 160 MiB [00:04, 52.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 161 MiB [00:04, 52.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 162 MiB [00:04, 52.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 163 MiB [00:04, 52.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 164 MiB [00:04, 52.36 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 165 MiB [00:04, 62.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 166 MiB [00:04, 62.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 167 MiB [00:04, 62.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 168 MiB [00:04, 62.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 169 MiB [00:04, 62.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 170 MiB [00:04, 62.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 171 MiB [00:04, 62.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 172 MiB [00:04, 62.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 173 MiB [00:04, 62.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 174 MiB [00:04, 62.12 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 175 MiB [00:04, 62.09 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 176 MiB [00:04, 62.09 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 177 MiB [00:04, 62.09 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 178 MiB [00:04, 62.09 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 179 MiB [00:04, 62.09 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 180 MiB [00:04, 62.09 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 181 MiB [00:04, 62.09 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 182 MiB [00:04, 62.09 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 183 MiB [00:04, 62.09 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 184 MiB [00:04, 62.09 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 185 MiB [00:04, 62.09 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 186 MiB [00:04, 62.09 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 187 MiB [00:04, 62.09 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 188 MiB [00:04, 73.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 189 MiB [00:04, 73.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 190 MiB [00:04, 73.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 191 MiB [00:04, 73.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 192 MiB [00:04, 73.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 193 MiB [00:04, 73.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 194 MiB [00:04, 73.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 195 MiB [00:04, 73.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 196 MiB [00:04, 73.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 197 MiB [00:04, 73.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 198 MiB [00:04, 73.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 199 MiB [00:04, 73.32 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 200 MiB [00:04, 70.00 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 201 MiB [00:04, 70.00 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 202 MiB [00:04, 70.00 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 203 MiB [00:04, 70.00 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 204 MiB [00:04, 70.00 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 205 MiB [00:04, 70.00 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 206 MiB [00:04, 70.00 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 207 MiB [00:04, 70.00 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 208 MiB [00:04, 70.00 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 209 MiB [00:04, 70.00 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 210 MiB [00:04, 70.00 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 211 MiB [00:04, 78.30 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 212 MiB [00:04, 78.30 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 213 MiB [00:04, 78.30 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 214 MiB [00:04, 78.30 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 215 MiB [00:04, 78.30 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 216 MiB [00:04, 78.30 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 217 MiB [00:04, 78.30 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 218 MiB [00:04, 78.30 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 219 MiB [00:04, 78.30 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 220 MiB [00:04, 78.30 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 221 MiB [00:04, 77.89 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 222 MiB [00:04, 77.89 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 223 MiB [00:04, 77.89 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 224 MiB [00:04, 77.89 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 225 MiB [00:04, 77.89 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 226 MiB [00:04, 77.89 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 227 MiB [00:04, 77.89 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 228 MiB [00:04, 77.89 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 229 MiB [00:04, 77.89 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 230 MiB [00:05, 77.89 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 231 MiB [00:05, 77.89 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:05, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 232 MiB [00:05, 73.65 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 233 MiB [00:05, 73.65 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 234 MiB [00:05, 73.65 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 235 MiB [00:05, 73.65 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 236 MiB [00:05, 73.65 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 237 MiB [00:05, 73.65 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 238 MiB [00:05, 73.65 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 239 MiB [00:05, 73.65 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 240 MiB [00:05, 73.65 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:05, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 241 MiB [00:05, 77.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 242 MiB [00:05, 77.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 243 MiB [00:05, 77.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 244 MiB [00:05, 77.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 245 MiB [00:05, 77.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 246 MiB [00:05, 77.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 247 MiB [00:05, 77.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 248 MiB [00:05, 77.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 249 MiB [00:05, 77.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 250 MiB [00:05, 77.66 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:05, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 251 MiB [00:05, 83.18 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 252 MiB [00:05, 83.18 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 253 MiB [00:05, 83.18 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 254 MiB [00:05, 83.18 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 255 MiB [00:05, 83.18 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 256 MiB [00:05, 83.18 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 257 MiB [00:05, 83.18 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 258 MiB [00:05, 83.18 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 259 MiB [00:05, 83.18 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 260 MiB [00:05, 83.18 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:05, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 261 MiB [00:05, 87.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 262 MiB [00:05, 87.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 263 MiB [00:05, 87.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 264 MiB [00:05, 87.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 265 MiB [00:05, 87.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 266 MiB [00:05, 87.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 267 MiB [00:05, 87.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 268 MiB [00:05, 87.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 269 MiB [00:05, 87.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 270 MiB [00:05, 87.06 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:05, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 271 MiB [00:05, 79.37 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 272 MiB [00:05, 79.37 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 273 MiB [00:05, 79.37 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 274 MiB [00:05, 79.37 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 275 MiB [00:05, 79.37 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 276 MiB [00:05, 79.37 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 277 MiB [00:05, 79.37 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 278 MiB [00:05, 79.37 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 279 MiB [00:05, 79.37 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 280 MiB [00:05, 79.37 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:05, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 281 MiB [00:05, 84.57 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 282 MiB [00:05, 84.57 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 283 MiB [00:05, 84.57 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 284 MiB [00:05, 84.57 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 285 MiB [00:05, 84.57 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 286 MiB [00:05, 84.57 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 287 MiB [00:05, 84.57 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 288 MiB [00:05, 84.57 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 289 MiB [00:05, 84.57 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:05, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 290 MiB [00:05, 70.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 291 MiB [00:05, 70.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 292 MiB [00:05, 70.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 293 MiB [00:05, 70.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 294 MiB [00:05, 70.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 295 MiB [00:05, 70.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 296 MiB [00:05, 70.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 297 MiB [00:05, 70.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 298 MiB [00:05, 70.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 299 MiB [00:05, 70.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 300 MiB [00:05, 70.66 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 301 MiB [00:05, 70.66 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:05, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 302 MiB [00:05, 80.34 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 303 MiB [00:05, 80.34 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 304 MiB [00:05, 80.34 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 305 MiB [00:05, 80.34 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 306 MiB [00:05, 80.34 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 307 MiB [00:05, 80.34 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 308 MiB [00:05, 80.34 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 309 MiB [00:05, 80.34 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 310 MiB [00:05, 80.34 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 311 MiB [00:06, 80.34 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 312 MiB [00:06, 80.34 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 313 MiB [00:06, 80.34 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 314 MiB [00:06, 80.34 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:06, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 315 MiB [00:06, 89.39 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 316 MiB [00:06, 89.39 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 317 MiB [00:06, 89.39 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 318 MiB [00:06, 89.39 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 319 MiB [00:06, 89.39 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 320 MiB [00:06, 89.39 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 321 MiB [00:06, 89.39 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 322 MiB [00:06, 89.39 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 323 MiB [00:06, 89.39 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 324 MiB [00:06, 89.39 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:06, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 325 MiB [00:06, 64.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 326 MiB [00:06, 64.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 327 MiB [00:06, 64.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 328 MiB [00:06, 64.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 329 MiB [00:06, 64.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 330 MiB [00:06, 64.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 331 MiB [00:06, 64.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 332 MiB [00:06, 64.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 333 MiB [00:06, 64.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 334 MiB [00:06, 64.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 335 MiB [00:06, 64.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 336 MiB [00:06, 64.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 337 MiB [00:06, 64.12 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:06, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 338 MiB [00:06, 74.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 339 MiB [00:06, 74.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 340 MiB [00:06, 74.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 341 MiB [00:06, 74.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 342 MiB [00:06, 74.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 343 MiB [00:06, 74.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 344 MiB [00:06, 74.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 345 MiB [00:06, 74.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 346 MiB [00:06, 74.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 347 MiB [00:06, 74.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 348 MiB [00:06, 74.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 349 MiB [00:06, 74.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 350 MiB [00:06, 74.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 351 MiB [00:06, 74.68 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:06, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 352 MiB [00:06, 82.69 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 353 MiB [00:06, 82.69 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 354 MiB [00:06, 82.69 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 355 MiB [00:06, 82.69 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 356 MiB [00:06, 82.69 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 357 MiB [00:06, 82.69 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 358 MiB [00:06, 82.69 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 359 MiB [00:06, 82.69 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 360 MiB [00:06, 82.69 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 361 MiB [00:06, 82.69 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:06, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 362 MiB [00:06, 73.52 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 363 MiB [00:06, 73.52 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 364 MiB [00:06, 73.52 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 365 MiB [00:06, 73.52 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 366 MiB [00:06, 73.52 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 367 MiB [00:06, 73.52 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 368 MiB [00:06, 73.52 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 369 MiB [00:06, 73.52 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 370 MiB [00:06, 73.52 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 371 MiB [00:06, 73.52 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 372 MiB [00:06, 73.52 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 373 MiB [00:06, 73.52 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:06, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 374 MiB [00:06, 82.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 375 MiB [00:06, 82.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 376 MiB [00:06, 82.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 377 MiB [00:06, 82.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 378 MiB [00:06, 82.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 379 MiB [00:06, 82.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 380 MiB [00:06, 82.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 381 MiB [00:06, 82.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 382 MiB [00:06, 82.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 383 MiB [00:06, 82.10 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:06, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 384 MiB [00:06, 84.65 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 385 MiB [00:06, 84.65 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 386 MiB [00:06, 84.65 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 387 MiB [00:06, 84.65 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 388 MiB [00:06, 84.65 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 389 MiB [00:07, 84.65 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 390 MiB [00:07, 84.65 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 391 MiB [00:07, 84.65 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 392 MiB [00:07, 84.65 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 393 MiB [00:07, 84.65 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:07, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 394 MiB [00:07, 81.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 395 MiB [00:07, 81.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 396 MiB [00:07, 81.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 397 MiB [00:07, 81.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 398 MiB [00:07, 81.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 399 MiB [00:07, 81.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 400 MiB [00:07, 81.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 401 MiB [00:07, 81.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 402 MiB [00:07, 81.36 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:07, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 403 MiB [00:07, 79.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 404 MiB [00:07, 79.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 405 MiB [00:07, 79.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 406 MiB [00:07, 79.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 407 MiB [00:07, 79.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 408 MiB [00:07, 79.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 409 MiB [00:07, 79.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 410 MiB [00:07, 79.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 411 MiB [00:07, 79.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 412 MiB [00:07, 79.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 413 MiB [00:07, 79.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 414 MiB [00:07, 79.83 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:07, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 415 MiB [00:07, 88.54 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 416 MiB [00:07, 88.54 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 417 MiB [00:07, 88.54 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 418 MiB [00:07, 88.54 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 419 MiB [00:07, 88.54 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 420 MiB [00:07, 88.54 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 421 MiB [00:07, 88.54 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 422 MiB [00:07, 88.54 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 423 MiB [00:07, 88.54 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 424 MiB [00:07, 88.54 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:07, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 425 MiB [00:07, 82.49 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 426 MiB [00:07, 82.49 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 427 MiB [00:07, 82.49 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 428 MiB [00:07, 82.49 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 429 MiB [00:07, 82.49 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 430 MiB [00:07, 82.49 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 431 MiB [00:07, 82.49 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 432 MiB [00:07, 82.49 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 433 MiB [00:07, 82.49 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:07, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 434 MiB [00:07, 77.01 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 435 MiB [00:07, 77.01 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 436 MiB [00:07, 77.01 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 437 MiB [00:07, 77.01 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 438 MiB [00:07, 77.01 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 439 MiB [00:07, 77.01 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 440 MiB [00:07, 77.01 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 441 MiB [00:07, 77.01 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 442 MiB [00:07, 77.01 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 443 MiB [00:07, 77.01 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 444 MiB [00:07, 77.01 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 445 MiB [00:07, 77.01 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:07, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 446 MiB [00:07, 85.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 447 MiB [00:07, 85.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 448 MiB [00:07, 85.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 449 MiB [00:07, 85.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 450 MiB [00:07, 85.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 451 MiB [00:07, 85.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 452 MiB [00:07, 85.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 453 MiB [00:07, 85.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 454 MiB [00:07, 85.36 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 455 MiB [00:07, 85.36 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:07, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 456 MiB [00:07, 80.24 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 457 MiB [00:07, 80.24 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 458 MiB [00:07, 80.24 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 459 MiB [00:07, 80.24 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 460 MiB [00:07, 80.24 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 461 MiB [00:07, 80.24 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 462 MiB [00:07, 80.24 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 463 MiB [00:07, 80.24 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 464 MiB [00:07, 80.24 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:07, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 465 MiB [00:07, 70.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 466 MiB [00:07, 70.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 467 MiB [00:07, 70.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 468 MiB [00:07, 70.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 469 MiB [00:07, 70.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 470 MiB [00:08, 70.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 471 MiB [00:08, 70.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 472 MiB [00:08, 70.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 473 MiB [00:08, 70.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 474 MiB [00:08, 70.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 475 MiB [00:08, 70.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 476 MiB [00:08, 70.50 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:08, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 477 MiB [00:08, 80.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 478 MiB [00:08, 80.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 479 MiB [00:08, 80.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 480 MiB [00:08, 80.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 481 MiB [00:08, 80.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 482 MiB [00:08, 80.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 483 MiB [00:08, 80.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 484 MiB [00:08, 80.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 485 MiB [00:08, 80.20 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:08, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 486 MiB [00:08, 71.58 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 487 MiB [00:08, 71.58 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 488 MiB [00:08, 71.58 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 489 MiB [00:08, 71.58 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 490 MiB [00:08, 71.58 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 491 MiB [00:08, 71.58 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 492 MiB [00:08, 71.58 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 493 MiB [00:08, 71.58 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 494 MiB [00:08, 71.58 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 495 MiB [00:08, 71.58 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:08, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 496 MiB [00:08, 73.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 497 MiB [00:08, 73.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 498 MiB [00:08, 73.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 499 MiB [00:08, 73.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 500 MiB [00:08, 73.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 501 MiB [00:08, 73.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 502 MiB [00:08, 73.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 503 MiB [00:08, 73.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 504 MiB [00:08, 73.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 505 MiB [00:08, 73.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 506 MiB [00:08, 73.10 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:08, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 507 MiB [00:08, 81.24 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 508 MiB [00:08, 81.24 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 509 MiB [00:08, 81.24 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 510 MiB [00:08, 81.24 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 511 MiB [00:08, 81.24 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 512 MiB [00:08, 81.24 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 513 MiB [00:08, 81.24 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 514 MiB [00:08, 81.24 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 515 MiB [00:08, 81.24 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:08, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 516 MiB [00:08, 69.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 517 MiB [00:08, 69.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 518 MiB [00:08, 69.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 519 MiB [00:08, 69.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 520 MiB [00:08, 69.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 521 MiB [00:08, 69.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 522 MiB [00:08, 69.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 523 MiB [00:08, 69.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 524 MiB [00:08, 69.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 525 MiB [00:08, 69.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 526 MiB [00:08, 69.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 527 MiB [00:08, 69.32 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:08, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 528 MiB [00:08, 75.47 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 529 MiB [00:08, 75.47 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 530 MiB [00:08, 75.47 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 531 MiB [00:08, 75.47 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 532 MiB [00:08, 75.47 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 533 MiB [00:08, 75.47 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 534 MiB [00:08, 75.47 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 535 MiB [00:08, 75.47 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 536 MiB [00:08, 75.47 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 537 MiB [00:08, 75.47 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:08, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 538 MiB [00:08, 81.45 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 539 MiB [00:08, 81.45 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 540 MiB [00:08, 81.45 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 541 MiB [00:08, 81.45 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 542 MiB [00:08, 81.45 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 543 MiB [00:08, 81.45 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 544 MiB [00:08, 81.45 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 545 MiB [00:08, 81.45 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 546 MiB [00:08, 81.45 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:08, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 547 MiB [00:08, 75.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 548 MiB [00:08, 75.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 549 MiB [00:09, 75.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 550 MiB [00:09, 75.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 551 MiB [00:09, 75.83 MiB/s]\u001b[A\n    \n    Dl Completed...: 100% 1/1 [00:09<00:00,  9.04s/ url]\n    Dl Size...: 551 MiB [00:09, 75.83 MiB/s]\u001b[A\n    \n    Dl Completed...: 100% 1/1 [00:09<00:00,  9.04s/ url]\n    Dl Size...: 551 MiB [00:09, 75.83 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:09<?, ? file/s]\u001b[A\u001b[A\n    Dl Size...: 551 MiB [00:20, 75.83 MiB/s]\u001b[A\n    \n    Dl Completed...: 100% 1/1 [00:38<00:00,  9.04s/ url]\n    Dl Size...: 551 MiB [00:38, 75.83 MiB/s]\u001b[A\n    \n    Extraction completed...: 100% 1/1 [00:38<00:00, 38.55s/ file]\u001b[A\u001b[A\n    Extraction completed...: 100% 1/1 [00:38<00:00, 38.55s/ file]\n    \n    Dl Size...: 551 MiB [00:38, 14.29 MiB/s]\n    \n    Dl Completed...: 100% 1/1 [00:38<00:00, 38.55s/ url]\n    I0830 20:48:58.446686 140123635914624 dataset_builder.py:953] Generating split train\n    Shuffling and writing examples to /root/tensorflow_datasets/gigaword/1.2.0.incomplete2JKCH3/gigaword-train.tfrecord\n    100% 3788665/3803957 [00:31<00:00, 174426.88 examples/s]I0830 21:02:03.232558 140123635914624 tfrecords_writer.py:226] Done writing /root/tensorflow_datasets/gigaword/1.2.0.incomplete2JKCH3/gigaword-train.tfrecord. Shard lengths: [237747, 237748, 237747, 237747, 237748, 237747, 237747, 237747, 237748, 237747, 237747, 237748, 237747, 237747, 237748, 237747]\n    I0830 21:02:03.416826 140123635914624 dataset_builder.py:953] Generating split validation\n    \n    0 examples [00:00, ? examples/s]\u001b[A\n    457 examples [00:00, 4564.00 examples/s]\u001b[A\n    947 examples [00:00, 4659.32 examples/s]\u001b[A\n    1402 examples [00:00, 4624.70 examples/s]\u001b[A\n    1908 examples [00:00, 4746.09 examples/s]\u001b[A\n    2387 examples [00:00, 4758.20 examples/s]\u001b[A\n    2864 examples [00:00, 4756.65 examples/s]\u001b[A\n    3324 examples [00:00, 4707.75 examples/s]\u001b[A\n    3815 examples [00:00, 4764.26 examples/s]\u001b[A\n    4284 examples [00:00, 4739.70 examples/s]\u001b[A\n    4815 examples [00:01, 4896.06 examples/s]\u001b[A\n    5340 examples [00:01, 4993.59 examples/s]\u001b[A\n    5880 examples [00:01, 5108.24 examples/s]\u001b[A\n    6403 examples [00:01, 5143.68 examples/s]\u001b[A\n    6934 examples [00:01, 5189.68 examples/s]\u001b[A\n    7474 examples [00:01, 5249.80 examples/s]\u001b[A\n    7998 examples [00:01, 5244.11 examples/s]\u001b[A\n    8522 examples [00:01, 5188.35 examples/s]\u001b[A\n    9068 examples [00:01, 5264.60 examples/s]\u001b[A\n    9597 examples [00:01, 5271.77 examples/s]\u001b[A\n    10125 examples [00:02, 5181.86 examples/s]\u001b[A\n    10644 examples [00:02, 5125.96 examples/s]\u001b[A\n    11157 examples [00:02, 4901.62 examples/s]\u001b[A\n    11650 examples [00:02, 4793.62 examples/s]\u001b[A\n    12141 examples [00:02, 4825.65 examples/s]\u001b[A\n    12626 examples [00:02, 4787.24 examples/s]\u001b[A\n    13118 examples [00:02, 4825.86 examples/s]\u001b[A\n    13616 examples [00:02, 4869.77 examples/s]\u001b[A\n    14104 examples [00:02, 4817.21 examples/s]\u001b[A\n    14617 examples [00:02, 4905.30 examples/s]\u001b[A\n    15166 examples [00:03, 5065.82 examples/s]\u001b[A\n    15695 examples [00:03, 5129.36 examples/s]\u001b[A\n    16212 examples [00:03, 5141.18 examples/s]\u001b[A\n    16761 examples [00:03, 5240.76 examples/s]\u001b[A\n    17287 examples [00:03, 5224.07 examples/s]\u001b[A\n    17811 examples [00:03, 5186.66 examples/s]\u001b[A\n    18331 examples [00:03, 5159.56 examples/s]\u001b[A\n    18848 examples [00:03, 5090.42 examples/s]\u001b[A\n    19394 examples [00:03, 5195.38 examples/s]\u001b[A\n    19921 examples [00:03, 5214.57 examples/s]\u001b[A\n    20444 examples [00:04, 4967.46 examples/s]\u001b[A\n    20981 examples [00:04, 5080.20 examples/s]\u001b[A\n    21519 examples [00:04, 5165.88 examples/s]\u001b[A\n    22038 examples [00:04, 5109.87 examples/s]\u001b[A\n    22570 examples [00:04, 5169.57 examples/s]\u001b[A\n    23106 examples [00:04, 5224.93 examples/s]\u001b[A\n    23630 examples [00:04, 5022.89 examples/s]\u001b[A\n    24183 examples [00:04, 5164.30 examples/s]\u001b[A\n    24729 examples [00:04, 5247.53 examples/s]\u001b[A\n    25256 examples [00:04, 5232.24 examples/s]\u001b[A\n    25785 examples [00:05, 5247.39 examples/s]\u001b[A\n    26333 examples [00:05, 5312.21 examples/s]\u001b[A\n    26866 examples [00:05, 5281.53 examples/s]\u001b[A\n    27401 examples [00:05, 5301.10 examples/s]\u001b[A\n    27944 examples [00:05, 5336.18 examples/s]\u001b[A\n    28479 examples [00:05, 5297.10 examples/s]\u001b[A\n    29010 examples [00:05, 5108.81 examples/s]\u001b[A\n    29523 examples [00:05, 5054.92 examples/s]\u001b[A\n    30030 examples [00:05, 5052.09 examples/s]\u001b[A\n    30570 examples [00:06, 5149.03 examples/s]\u001b[A\n    31108 examples [00:06, 5214.70 examples/s]\u001b[A\n    31631 examples [00:06, 5178.13 examples/s]\u001b[A\n    32170 examples [00:06, 5238.00 examples/s]\u001b[A\n    32699 examples [00:06, 5251.61 examples/s]\u001b[A\n    33246 examples [00:06, 5313.08 examples/s]\u001b[A\n    33778 examples [00:06, 5197.97 examples/s]\u001b[A\n    34299 examples [00:06, 5147.36 examples/s]\u001b[A\n    34841 examples [00:06, 5225.24 examples/s]\u001b[A\n    35365 examples [00:06, 5179.72 examples/s]\u001b[A\n    35903 examples [00:07, 5237.31 examples/s]\u001b[A\n    36455 examples [00:07, 5316.73 examples/s]\u001b[A\n    36988 examples [00:07, 5276.35 examples/s]\u001b[A\n    37525 examples [00:07, 5300.97 examples/s]\u001b[A\n    38056 examples [00:07, 5281.20 examples/s]\u001b[A\n    38585 examples [00:07, 5232.30 examples/s]\u001b[A\n    39109 examples [00:07, 5116.89 examples/s]\u001b[A\n    39622 examples [00:07, 4896.00 examples/s]\u001b[A\n    40175 examples [00:07, 5069.16 examples/s]\u001b[A\n    40709 examples [00:07, 5144.07 examples/s]\u001b[A\n    41227 examples [00:08, 4944.24 examples/s]\u001b[A\n    41777 examples [00:08, 5097.70 examples/s]\u001b[A\n    42319 examples [00:08, 5190.17 examples/s]\u001b[A\n    42841 examples [00:08, 5146.86 examples/s]\u001b[A\n    43379 examples [00:08, 5214.06 examples/s]\u001b[A\n    43917 examples [00:08, 5260.72 examples/s]\u001b[A\n    44445 examples [00:08, 5172.33 examples/s]\u001b[A\n    44964 examples [00:08, 5124.79 examples/s]\u001b[A\n    45478 examples [00:08, 5066.39 examples/s]\u001b[A\n    45986 examples [00:09, 4664.95 examples/s]\u001b[A\n    46523 examples [00:09, 4855.48 examples/s]\u001b[A\n    47067 examples [00:09, 5016.88 examples/s]\u001b[A\n    47601 examples [00:09, 5109.23 examples/s]\u001b[A\n    48117 examples [00:09, 5063.10 examples/s]\u001b[A\n    48644 examples [00:09, 5122.26 examples/s]\u001b[A\n    49159 examples [00:09, 4959.10 examples/s]\u001b[A\n    49678 examples [00:09, 5023.81 examples/s]\u001b[A\n    50214 examples [00:09, 5119.70 examples/s]\u001b[A\n    100% 3788665/3803957 [00:42<00:00, 174426.88 examples/s]\n    51232 examples [00:10, 4866.50 examples/s]\u001b[A\n    51751 examples [00:10, 4956.92 examples/s]\u001b[A\n    52249 examples [00:10, 4885.65 examples/s]\u001b[A\n    52796 examples [00:10, 5045.85 examples/s]\u001b[A\n    53304 examples [00:10, 4899.41 examples/s]\u001b[A\n    53797 examples [00:10, 4905.21 examples/s]\u001b[A\n    54290 examples [00:10, 4867.43 examples/s]\u001b[A\n    54779 examples [00:10, 4669.16 examples/s]\u001b[A\n    55256 examples [00:10, 4697.83 examples/s]\u001b[A\n    55761 examples [00:10, 4795.94 examples/s]\u001b[A\n    56289 examples [00:11, 4926.22 examples/s]\u001b[A\n    56834 examples [00:11, 5070.62 examples/s]\u001b[A\n    57387 examples [00:11, 5198.47 examples/s]\u001b[A\n    57926 examples [00:11, 5251.37 examples/s]\u001b[A\n    58470 examples [00:11, 5304.12 examples/s]\u001b[A\n    59017 examples [00:11, 5352.62 examples/s]\u001b[A\n    59554 examples [00:11, 5116.06 examples/s]\u001b[A\n    60069 examples [00:11, 5097.11 examples/s]\u001b[A\n    60597 examples [00:11, 5143.50 examples/s]\u001b[A\n    61113 examples [00:12, 5141.81 examples/s]\u001b[A\n    61657 examples [00:12, 5225.97 examples/s]\u001b[A\n    62208 examples [00:12, 5306.48 examples/s]\u001b[A\n    62740 examples [00:12, 5307.56 examples/s]\u001b[A\n    63284 examples [00:12, 5346.15 examples/s]\u001b[A\n    63820 examples [00:12, 5319.38 examples/s]\u001b[A\n    64353 examples [00:12, 5251.79 examples/s]\u001b[A\n    64905 examples [00:12, 5327.56 examples/s]\u001b[A\n    65439 examples [00:12, 5125.94 examples/s]\u001b[A\n    65954 examples [00:12, 5119.47 examples/s]\u001b[A\n    66511 examples [00:13, 5244.88 examples/s]\u001b[A\n    67067 examples [00:13, 5334.97 examples/s]\u001b[A\n    67603 examples [00:13, 5302.72 examples/s]\u001b[A\n    68150 examples [00:13, 5350.91 examples/s]\u001b[A\n    68691 examples [00:13, 5368.12 examples/s]\u001b[A\n    69229 examples [00:13, 5262.22 examples/s]\u001b[A\n    69771 examples [00:13, 5306.22 examples/s]\u001b[A\n    70303 examples [00:13, 5307.16 examples/s]\u001b[A\n    70835 examples [00:13, 5184.87 examples/s]\u001b[A\n    71374 examples [00:13, 5243.10 examples/s]\u001b[A\n    71923 examples [00:14, 5312.81 examples/s]\u001b[A\n    72456 examples [00:14, 5308.48 examples/s]\u001b[A\n    72997 examples [00:14, 5336.39 examples/s]\u001b[A\n    73532 examples [00:14, 5311.54 examples/s]\u001b[A\n    74064 examples [00:14, 5298.50 examples/s]\u001b[A\n    74595 examples [00:14, 5069.02 examples/s]\u001b[A\n    75105 examples [00:14, 4967.57 examples/s]\u001b[A\n    75626 examples [00:14, 5035.56 examples/s]\u001b[A\n    76132 examples [00:14, 4984.37 examples/s]\u001b[A\n    76651 examples [00:14, 5043.53 examples/s]\u001b[A\n    77199 examples [00:15, 5164.76 examples/s]\u001b[A\n    77740 examples [00:15, 5235.56 examples/s]\u001b[A\n    78272 examples [00:15, 5255.09 examples/s]\u001b[A\n    78799 examples [00:15, 5194.42 examples/s]\u001b[A\n    79320 examples [00:15, 5093.11 examples/s]\u001b[A\n    79831 examples [00:15, 4968.77 examples/s]\u001b[A\n    80334 examples [00:15, 4984.88 examples/s]\u001b[A\n    80860 examples [00:15, 5063.44 examples/s]\u001b[A\n    81368 examples [00:15, 4957.87 examples/s]\u001b[A\n    81904 examples [00:16, 5071.41 examples/s]\u001b[A\n    82421 examples [00:16, 5098.16 examples/s]\u001b[A\n    82943 examples [00:16, 5133.52 examples/s]\u001b[A\n    83458 examples [00:16, 4796.28 examples/s]\u001b[A\n    83943 examples [00:16, 4771.96 examples/s]\u001b[A\n    84447 examples [00:16, 4848.21 examples/s]\u001b[A\n    84943 examples [00:16, 4879.61 examples/s]\u001b[A\n    85433 examples [00:16, 4841.66 examples/s]\u001b[A\n    85974 examples [00:16, 4995.62 examples/s]\u001b[A\n    86476 examples [00:16, 4990.89 examples/s]\u001b[A\n    86977 examples [00:17, 4974.56 examples/s]\u001b[A\n    87520 examples [00:17, 5102.11 examples/s]\u001b[A\n    88052 examples [00:17, 5165.42 examples/s]\u001b[A\n    88570 examples [00:17, 5156.93 examples/s]\u001b[A\n    89106 examples [00:17, 5214.51 examples/s]\u001b[A\n    89649 examples [00:17, 5275.40 examples/s]\u001b[A\n    90178 examples [00:17, 5069.41 examples/s]\u001b[A\n    90701 examples [00:17, 5114.20 examples/s]\u001b[A\n    91221 examples [00:17, 5138.89 examples/s]\u001b[A\n    91737 examples [00:17, 5035.42 examples/s]\u001b[A\n    92288 examples [00:18, 5167.73 examples/s]\u001b[A\n    92807 examples [00:18, 5160.34 examples/s]\u001b[A\n    93333 examples [00:18, 5187.15 examples/s]\u001b[A\n    93875 examples [00:18, 5253.27 examples/s]\u001b[A\n    94402 examples [00:18, 5186.67 examples/s]\u001b[A\n    94947 examples [00:18, 5262.55 examples/s]\u001b[A\n    95475 examples [00:18, 5257.29 examples/s]\u001b[A\n    96002 examples [00:18, 5182.13 examples/s]\u001b[A\n    96522 examples [00:18, 5185.98 examples/s]\u001b[A\n    97042 examples [00:18, 5148.69 examples/s]\u001b[A\n    97558 examples [00:19, 4946.88 examples/s]\u001b[A\n    98055 examples [00:19, 4747.95 examples/s]\u001b[A\n    98593 examples [00:19, 4919.63 examples/s]\u001b[A\n    99094 examples [00:19, 4944.95 examples/s]\u001b[A\n    99641 examples [00:19, 5089.56 examples/s]\u001b[A\n    100170 examples [00:19, 5147.14 examples/s]\u001b[A\n    100713 examples [00:19, 5226.93 examples/s]\u001b[A\n    101255 examples [00:19, 5282.37 examples/s]\u001b[A\n    101785 examples [00:19, 5081.67 examples/s]\u001b[A\n    102330 examples [00:20, 5184.87 examples/s]\u001b[A\n    102875 examples [00:20, 5258.37 examples/s]\u001b[A\n    103408 examples [00:20, 5276.94 examples/s]\u001b[A\n    103940 examples [00:20, 5287.97 examples/s]\u001b[A\n    104491 examples [00:20, 5349.44 examples/s]\u001b[A\n    105027 examples [00:20, 5334.79 examples/s]\u001b[A\n    105562 examples [00:20, 5055.59 examples/s]\u001b[A\n    106100 examples [00:20, 5146.61 examples/s]\u001b[A\n    106620 examples [00:20, 5161.32 examples/s]\u001b[A\n    107139 examples [00:20, 5106.33 examples/s]\u001b[A\n    107688 examples [00:21, 5214.17 examples/s]\u001b[A\n    108212 examples [00:21, 5202.86 examples/s]\u001b[A\n    108769 examples [00:21, 5307.79 examples/s]\u001b[A\n    109302 examples [00:21, 5305.48 examples/s]\u001b[A\n    109834 examples [00:21, 5189.03 examples/s]\u001b[A\n    110358 examples [00:21, 5204.02 examples/s]\u001b[A\n    110887 examples [00:21, 5228.30 examples/s]\u001b[A\n    111411 examples [00:21, 5115.59 examples/s]\u001b[A\n    111954 examples [00:21, 5205.02 examples/s]\u001b[A\n    112476 examples [00:21, 5038.95 examples/s]\u001b[A\n    112982 examples [00:22, 4862.82 examples/s]\u001b[A\n    113493 examples [00:22, 4933.87 examples/s]\u001b[A\n    113992 examples [00:22, 4950.09 examples/s]\u001b[A\n    114533 examples [00:22, 5077.31 examples/s]\u001b[A\n    115043 examples [00:22, 5032.75 examples/s]\u001b[A\n    115548 examples [00:22, 5025.80 examples/s]\u001b[A\n    116052 examples [00:22, 5008.57 examples/s]\u001b[A\n    116554 examples [00:22, 4971.52 examples/s]\u001b[A\n    117052 examples [00:22, 4914.06 examples/s]\u001b[A\n    117544 examples [00:23, 4779.12 examples/s]\u001b[A\n    118075 examples [00:23, 4925.77 examples/s]\u001b[A\n    118590 examples [00:23, 4988.45 examples/s]\u001b[A\n    119091 examples [00:23, 4972.10 examples/s]\u001b[A\n    119614 examples [00:23, 5046.12 examples/s]\u001b[A\n    120120 examples [00:23, 5034.56 examples/s]\u001b[A\n    120626 examples [00:23, 5040.51 examples/s]\u001b[A\n    121131 examples [00:23, 4719.89 examples/s]\u001b[A\n    121679 examples [00:23, 4922.66 examples/s]\u001b[A\n    122177 examples [00:23, 4875.87 examples/s]\u001b[A\n    122669 examples [00:24, 4851.48 examples/s]\u001b[A\n    123190 examples [00:24, 4952.41 examples/s]\u001b[A\n    123716 examples [00:24, 5040.26 examples/s]\u001b[A\n    124223 examples [00:24, 5047.69 examples/s]\u001b[A\n    124759 examples [00:24, 5135.76 examples/s]\u001b[A\n    125274 examples [00:24, 5074.59 examples/s]\u001b[A\n    125783 examples [00:24, 4997.66 examples/s]\u001b[A\n    126284 examples [00:24, 4796.00 examples/s]\u001b[A\n    126789 examples [00:24, 4868.02 examples/s]\u001b[A\n    127309 examples [00:24, 4962.92 examples/s]\u001b[A\n    127808 examples [00:25, 4826.21 examples/s]\u001b[A\n    128346 examples [00:25, 4978.22 examples/s]\u001b[A\n    128857 examples [00:25, 5015.87 examples/s]\u001b[A\n    129368 examples [00:25, 5043.47 examples/s]\u001b[A\n    129874 examples [00:25, 5028.13 examples/s]\u001b[A\n    130378 examples [00:25, 5013.36 examples/s]\u001b[A\n    130911 examples [00:25, 5102.16 examples/s]\u001b[A\n    131423 examples [00:25, 5092.30 examples/s]\u001b[A\n    131940 examples [00:25, 5113.99 examples/s]\u001b[A\n    132452 examples [00:25, 5072.26 examples/s]\u001b[A\n    132960 examples [00:26, 4707.37 examples/s]\u001b[A\n    133465 examples [00:26, 4803.24 examples/s]\u001b[A\n    133984 examples [00:26, 4912.24 examples/s]\u001b[A\n    134511 examples [00:26, 5014.20 examples/s]\u001b[A\n    135016 examples [00:26, 4923.19 examples/s]\u001b[A\n    135554 examples [00:26, 5050.40 examples/s]\u001b[A\n    136079 examples [00:26, 5105.86 examples/s]\u001b[A\n    136592 examples [00:26, 4915.29 examples/s]\u001b[A\n    137098 examples [00:26, 4957.50 examples/s]\u001b[A\n    137596 examples [00:27, 4907.91 examples/s]\u001b[A\n    138103 examples [00:27, 4955.19 examples/s]\u001b[A\n    138643 examples [00:27, 5078.99 examples/s]\u001b[A\n    139153 examples [00:27, 5005.07 examples/s]\u001b[A\n    139693 examples [00:27, 5115.91 examples/s]\u001b[A\n    140209 examples [00:27, 5128.51 examples/s]\u001b[A\n    140723 examples [00:27, 4812.00 examples/s]\u001b[A\n    141231 examples [00:27, 4886.77 examples/s]\u001b[A\n    141725 examples [00:27, 4902.37 examples/s]\u001b[A\n    142262 examples [00:27, 5032.06 examples/s]\u001b[A\n    142768 examples [00:28, 4949.52 examples/s]\u001b[A\n    143305 examples [00:28, 5067.40 examples/s]\u001b[A\n    143839 examples [00:28, 5145.57 examples/s]\u001b[A\n    144363 examples [00:28, 5170.57 examples/s]\u001b[A\n    144892 examples [00:28, 5204.69 examples/s]\u001b[A\n    145427 examples [00:28, 5244.56 examples/s]\u001b[A\n    145953 examples [00:28, 5123.26 examples/s]\u001b[A\n    146493 examples [00:28, 5202.19 examples/s]\u001b[A\n    147015 examples [00:28, 5112.79 examples/s]\u001b[A\n    147528 examples [00:28, 5098.24 examples/s]\u001b[A\n    148039 examples [00:29, 4936.24 examples/s]\u001b[A\n    148576 examples [00:29, 5054.38 examples/s]\u001b[A\n    149091 examples [00:29, 5079.30 examples/s]\u001b[A\n    149623 examples [00:29, 5145.62 examples/s]\u001b[A\n    150139 examples [00:29, 4530.00 examples/s]\u001b[A\n    150681 examples [00:29, 4757.35 examples/s]\u001b[A\n    151170 examples [00:29, 4772.16 examples/s]\u001b[A\n    151694 examples [00:29, 4902.65 examples/s]\u001b[A\n    152219 examples [00:29, 5000.90 examples/s]\u001b[A\n    152731 examples [00:30, 5035.33 examples/s]\u001b[A\n    153239 examples [00:30, 4982.06 examples/s]\u001b[A\n    153784 examples [00:30, 5111.19 examples/s]\u001b[A\n    154334 examples [00:30, 5221.67 examples/s]\u001b[A\n    154861 examples [00:30, 5234.69 examples/s]\u001b[A\n    155394 examples [00:30, 5262.90 examples/s]\u001b[A\n    155941 examples [00:30, 5322.91 examples/s]\u001b[A\n    156475 examples [00:30, 4994.33 examples/s]\u001b[A\n    156991 examples [00:30, 5039.30 examples/s]\u001b[A\n    157499 examples [00:30, 5044.61 examples/s]\u001b[A\n    158006 examples [00:31, 5045.15 examples/s]\u001b[A\n    158533 examples [00:31, 5108.06 examples/s]\u001b[A\n    159060 examples [00:31, 5153.04 examples/s]\u001b[A\n    159593 examples [00:31, 5202.52 examples/s]\u001b[A\n    160115 examples [00:31, 5175.38 examples/s]\u001b[A\n    160646 examples [00:31, 5213.98 examples/s]\u001b[A\n    161168 examples [00:31, 5170.17 examples/s]\u001b[A\n    161686 examples [00:31, 5128.33 examples/s]\u001b[A\n    162200 examples [00:31, 5056.85 examples/s]\u001b[A\n    162737 examples [00:31, 5145.66 examples/s]\u001b[A\n    163253 examples [00:32, 4790.51 examples/s]\u001b[A\n    163803 examples [00:32, 4980.81 examples/s]\u001b[A\n    164328 examples [00:32, 5057.31 examples/s]\u001b[A\n    164858 examples [00:32, 5125.91 examples/s]\u001b[A\n    165392 examples [00:32, 5187.93 examples/s]\u001b[A\n    165914 examples [00:32, 5060.09 examples/s]\u001b[A\n    166423 examples [00:32, 4990.44 examples/s]\u001b[A\n    166956 examples [00:32, 5085.39 examples/s]\u001b[A\n    167467 examples [00:32, 5057.38 examples/s]\u001b[A\n    168003 examples [00:33, 5142.16 examples/s]\u001b[A\n    168519 examples [00:33, 5100.92 examples/s]\u001b[A\n    169031 examples [00:33, 5100.56 examples/s]\u001b[A\n    169574 examples [00:33, 5194.71 examples/s]\u001b[A\n    170111 examples [00:33, 5245.89 examples/s]\u001b[A\n    170637 examples [00:33, 5157.37 examples/s]\u001b[A\n    171180 examples [00:33, 5232.42 examples/s]\u001b[A\n    171712 examples [00:33, 5257.65 examples/s]\u001b[A\n    172239 examples [00:33, 5242.12 examples/s]\u001b[A\n    172764 examples [00:33, 4995.47 examples/s]\u001b[A\n    173308 examples [00:34, 5120.29 examples/s]\u001b[A\n    173823 examples [00:34, 4990.80 examples/s]\u001b[A\n    174368 examples [00:34, 5119.27 examples/s]\u001b[A\n    174904 examples [00:34, 5186.66 examples/s]\u001b[A\n    175425 examples [00:34, 5133.34 examples/s]\u001b[A\n    175972 examples [00:34, 5227.89 examples/s]\u001b[A\n    176498 examples [00:34, 5235.31 examples/s]\u001b[A\n    177023 examples [00:34, 5020.68 examples/s]\u001b[A\n    177528 examples [00:34, 5020.70 examples/s]\u001b[A\n    178065 examples [00:34, 5119.96 examples/s]\u001b[A\n    178579 examples [00:35, 5106.62 examples/s]\u001b[A\n    179091 examples [00:35, 5097.18 examples/s]\u001b[A\n    179620 examples [00:35, 5151.68 examples/s]\u001b[A\n    180136 examples [00:35, 5028.04 examples/s]\u001b[A\n    180640 examples [00:35, 5021.29 examples/s]\u001b[A\n    181185 examples [00:35, 5142.29 examples/s]\u001b[A\n    181710 examples [00:35, 5172.11 examples/s]\u001b[A\n    182236 examples [00:35, 5195.78 examples/s]\u001b[A\n    182784 examples [00:35, 5277.30 examples/s]\u001b[A\n    183313 examples [00:36, 5252.19 examples/s]\u001b[A\n    183847 examples [00:36, 5277.55 examples/s]\u001b[A\n    184376 examples [00:36, 5163.24 examples/s]\u001b[A\n    184894 examples [00:36, 5160.58 examples/s]\u001b[A\n    185432 examples [00:36, 5222.26 examples/s]\u001b[A\n    185955 examples [00:36, 5189.82 examples/s]\u001b[A\n    186478 examples [00:36, 5196.11 examples/s]\u001b[A\n    187002 examples [00:36, 5208.23 examples/s]\u001b[A\n    187541 examples [00:36, 5261.19 examples/s]\u001b[A\n    188068 examples [00:36, 5221.15 examples/s]\u001b[A\n    188595 examples [00:37, 5235.38 examples/s]\u001b[A\n    189137 examples [00:37, 5288.41 examples/s]\u001b[A\n                                               \u001b[AShuffling and writing examples to /root/tensorflow_datasets/gigaword/1.2.0.incomplete2JKCH3/gigaword-validation.tfrecord\n    \n      0% 0/189651 [00:00<?, ? examples/s]\u001b[A\n      0% 1/189651 [00:00<15:19:29,  3.44 examples/s]\u001b[A\n     11% 20948/189651 [00:00<9:32:33,  4.91 examples/s]\u001b[A\n     23% 42736/189651 [00:00<5:49:01,  7.02 examples/s]\u001b[A\n     34% 63742/189651 [00:00<3:29:23, 10.02 examples/s]\u001b[A\n     45% 85996/189651 [00:00<2:00:40, 14.32 examples/s]\u001b[A\n     57% 107942/189651 [00:00<1:06:35, 20.45 examples/s]\u001b[A\n     68% 129176/189651 [00:00<34:29, 29.22 examples/s]  \u001b[A\n     79% 149978/189651 [00:00<15:50, 41.73 examples/s]\u001b[A\n     91% 171818/189651 [00:01<04:59, 59.61 examples/s]\u001b[AI0830 21:02:41.835843 140123635914624 tfrecords_writer.py:226] Done writing /root/tensorflow_datasets/gigaword/1.2.0.incomplete2JKCH3/gigaword-validation.tfrecord. Shard lengths: [189651]\n    \n                                                      \u001b[AI0830 21:02:41.860714 140123635914624 dataset_builder.py:953] Generating split test\n    \n    0 examples [00:00, ? examples/s]\u001b[A\n    540 examples [00:00, 5393.85 examples/s]\u001b[A\n    1083 examples [00:00, 5403.57 examples/s]\u001b[A\n    1542 examples [00:00, 5127.12 examples/s]\u001b[A\n                                             \u001b[AShuffling and writing examples to /root/tensorflow_datasets/gigaword/1.2.0.incomplete2JKCH3/gigaword-test.tfrecord\n    \n      0% 0/1951 [00:00<?, ? examples/s]\u001b[AI0830 21:02:42.250689 140123635914624 tfrecords_writer.py:226] Done writing /root/tensorflow_datasets/gigaword/1.2.0.incomplete2JKCH3/gigaword-test.tfrecord. Shard lengths: [1951]\n    \n                                       \u001b[AI0830 21:02:42.252512 140123635914624 dataset_builder.py:404] Skipping computing stats for mode ComputeStatsMode.AUTO.\n    \u001b[1mDataset gigaword downloaded and prepared to /root/tensorflow_datasets/gigaword/1.2.0. Subsequent calls will reuse this data.\u001b[0m\n    I0830 21:02:42.257033 140123635914624 dataset_builder.py:503] Constructing tf.data.Dataset for split train, from /root/tensorflow_datasets/gigaword/1.2.0\n    I0830 21:02:42.714406 140123635914624 datasets.py:215] Number of examples for config gigaword train is 3803957\n    2020-08-30 21:02:43.846331: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1\n    2020-08-30 21:02:43.908618: E tensorflow/stream_executor/cuda/cuda_driver.cc:318] failed call to cuInit: CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected\n    2020-08-30 21:02:43.908704: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (d85487f9bac6): /proc/driver/nvidia/version does not exist\n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/ragged/ragged_tensor.py:1586: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use tf.where in 2.0, which has the same broadcast rule as np.where\n    W0830 21:02:44.029327 140123635914624 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/ragged/ragged_tensor.py:1586: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use tf.where in 2.0, which has the same broadcast rule as np.where\n    INFO:tensorflow:Calling model_fn.\n    I0830 21:02:44.331900 140123635914624 estimator.py:1148] Calling model_fn.\n    INFO:tensorflow:Running train on CPU\n    I0830 21:02:44.332282 140123635914624 tpu_estimator.py:3124] Running train on CPU\n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:78: The name tf.get_variable_scope is deprecated. Please use tf.compat.v1.get_variable_scope instead.\n    \n    W0830 21:02:44.332972 140123635914624 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:78: The name tf.get_variable_scope is deprecated. Please use tf.compat.v1.get_variable_scope instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/attention.py:41: The name tf.layers.Dense is deprecated. Please use tf.compat.v1.layers.Dense instead.\n    \n    W0830 21:02:44.333711 140123635914624 module_wrapper.py:139] From /content/pegasus/pegasus/layers/attention.py:41: The name tf.layers.Dense is deprecated. Please use tf.compat.v1.layers.Dense instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/embedding.py:57: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n    \n    W0830 21:02:44.410594 140123635914624 module_wrapper.py:139] From /content/pegasus/pegasus/layers/embedding.py:57: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/embedding.py:57: The name tf.AUTO_REUSE is deprecated. Please use tf.compat.v1.AUTO_REUSE instead.\n    \n    W0830 21:02:44.410902 140123635914624 module_wrapper.py:139] From /content/pegasus/pegasus/layers/embedding.py:57: The name tf.AUTO_REUSE is deprecated. Please use tf.compat.v1.AUTO_REUSE instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/embedding.py:61: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n    \n    W0830 21:02:44.411190 140123635914624 module_wrapper.py:139] From /content/pegasus/pegasus/layers/embedding.py:61: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/embedding.py:64: calling RandomNormal.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Call initializer instance with the dtype argument instead of passing it to the constructor\n    W0830 21:02:44.411503 140123635914624 deprecation.py:506] From /content/pegasus/pegasus/layers/embedding.py:64: calling RandomNormal.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Call initializer instance with the dtype argument instead of passing it to the constructor\n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/attention.py:106: The name tf.matrix_band_part is deprecated. Please use tf.linalg.band_part instead.\n    \n    W0830 21:02:47.510011 140123635914624 module_wrapper.py:139] From /content/pegasus/pegasus/layers/attention.py:106: The name tf.matrix_band_part is deprecated. Please use tf.linalg.band_part instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/models/transformer.py:108: The name tf.losses.softmax_cross_entropy is deprecated. Please use tf.compat.v1.losses.softmax_cross_entropy instead.\n    \n    W0830 21:02:52.864431 140123635914624 module_wrapper.py:139] From /content/pegasus/pegasus/models/transformer.py:108: The name tf.losses.softmax_cross_entropy is deprecated. Please use tf.compat.v1.losses.softmax_cross_entropy instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:113: The name tf.train.get_global_step is deprecated. Please use tf.compat.v1.train.get_global_step instead.\n    \n    W0830 21:02:52.930881 140123635914624 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:113: The name tf.train.get_global_step is deprecated. Please use tf.compat.v1.train.get_global_step instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:114: The name tf.rsqrt is deprecated. Please use tf.math.rsqrt instead.\n    \n    W0830 21:02:52.931245 140123635914624 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:114: The name tf.rsqrt is deprecated. Please use tf.math.rsqrt instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:115: to_float (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    W0830 21:02:52.931433 140123635914624 deprecation.py:323] From /content/pegasus/pegasus/params/estimator_utils.py:115: to_float (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    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/adafactor.py:315: The name tf.train.get_or_create_global_step is deprecated. Please use tf.compat.v1.train.get_or_create_global_step instead.\n    \n    W0830 21:02:52.940937 140123635914624 module_wrapper.py:139] From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/adafactor.py:315: The name tf.train.get_or_create_global_step is deprecated. Please use tf.compat.v1.train.get_or_create_global_step instead.\n    \n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/quantization.py:147: 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    W0830 21:02:52.946000 140123635914624 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/quantization.py:147: 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    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/quantization.py:156: The name tf.mod is deprecated. Please use tf.math.mod instead.\n    \n    W0830 21:02:52.948682 140123635914624 module_wrapper.py:139] From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/quantization.py:156: The name tf.mod is deprecated. Please use tf.math.mod instead.\n    \n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/adafactor.py:244: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead.\n    \n    W0830 21:03:08.100562 140123635914624 module_wrapper.py:139] From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/adafactor.py:244: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:189: The name tf.trainable_variables is deprecated. Please use tf.compat.v1.trainable_variables instead.\n    \n    W0830 21:03:23.728315 140123635914624 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:189: The name tf.trainable_variables is deprecated. Please use tf.compat.v1.trainable_variables instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:205: The name tf.train.init_from_checkpoint is deprecated. Please use tf.compat.v1.train.init_from_checkpoint instead.\n    \n    W0830 21:03:23.740759 140123635914624 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:205: The name tf.train.init_from_checkpoint is deprecated. Please use tf.compat.v1.train.init_from_checkpoint instead.\n    \n    I0830 21:03:25.253778 140123635914624 estimator_utils.py:207] **** Trainable Variables ****\n    I0830 21:03:25.254048 140123635914624 estimator_utils.py:212]   name = embeddings/weights:0, shape = (96103, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.254212 140123635914624 estimator_utils.py:212]   name = encoder/layer_0/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.254320 140123635914624 estimator_utils.py:212]   name = encoder/layer_0/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.254434 140123635914624 estimator_utils.py:212]   name = encoder/layer_0/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.254546 140123635914624 estimator_utils.py:212]   name = encoder/layer_0/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.254682 140123635914624 estimator_utils.py:212]   name = encoder/layer_0/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.254786 140123635914624 estimator_utils.py:212]   name = encoder/layer_0/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.254882 140123635914624 estimator_utils.py:212]   name = encoder/layer_0/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.254972 140123635914624 estimator_utils.py:212]   name = encoder/layer_0/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.255065 140123635914624 estimator_utils.py:212]   name = encoder/layer_0/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.255156 140123635914624 estimator_utils.py:212]   name = encoder/layer_0/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.255230 140123635914624 estimator_utils.py:212]   name = encoder/layer_0/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.255306 140123635914624 estimator_utils.py:212]   name = encoder/layer_0/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.255384 140123635914624 estimator_utils.py:212]   name = encoder/layer_1/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.255488 140123635914624 estimator_utils.py:212]   name = encoder/layer_1/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.255570 140123635914624 estimator_utils.py:212]   name = encoder/layer_1/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.255687 140123635914624 estimator_utils.py:212]   name = encoder/layer_1/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.255774 140123635914624 estimator_utils.py:212]   name = encoder/layer_1/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.255859 140123635914624 estimator_utils.py:212]   name = encoder/layer_1/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.255946 140123635914624 estimator_utils.py:212]   name = encoder/layer_1/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.256029 140123635914624 estimator_utils.py:212]   name = encoder/layer_1/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.256111 140123635914624 estimator_utils.py:212]   name = encoder/layer_1/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.256196 140123635914624 estimator_utils.py:212]   name = encoder/layer_1/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.256275 140123635914624 estimator_utils.py:212]   name = encoder/layer_1/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.256358 140123635914624 estimator_utils.py:212]   name = encoder/layer_1/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.256454 140123635914624 estimator_utils.py:212]   name = encoder/layer_2/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.256541 140123635914624 estimator_utils.py:212]   name = encoder/layer_2/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.256661 140123635914624 estimator_utils.py:212]   name = encoder/layer_2/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.256757 140123635914624 estimator_utils.py:212]   name = encoder/layer_2/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.256847 140123635914624 estimator_utils.py:212]   name = encoder/layer_2/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.256936 140123635914624 estimator_utils.py:212]   name = encoder/layer_2/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.257027 140123635914624 estimator_utils.py:212]   name = encoder/layer_2/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.257112 140123635914624 estimator_utils.py:212]   name = encoder/layer_2/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.257196 140123635914624 estimator_utils.py:212]   name = encoder/layer_2/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.257285 140123635914624 estimator_utils.py:212]   name = encoder/layer_2/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.257367 140123635914624 estimator_utils.py:212]   name = encoder/layer_2/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.257469 140123635914624 estimator_utils.py:212]   name = encoder/layer_2/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.257555 140123635914624 estimator_utils.py:212]   name = encoder/layer_3/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.257672 140123635914624 estimator_utils.py:212]   name = encoder/layer_3/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.257759 140123635914624 estimator_utils.py:212]   name = encoder/layer_3/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.257848 140123635914624 estimator_utils.py:212]   name = encoder/layer_3/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.257940 140123635914624 estimator_utils.py:212]   name = encoder/layer_3/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.258031 140123635914624 estimator_utils.py:212]   name = encoder/layer_3/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.258119 140123635914624 estimator_utils.py:212]   name = encoder/layer_3/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.258205 140123635914624 estimator_utils.py:212]   name = encoder/layer_3/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.258290 140123635914624 estimator_utils.py:212]   name = encoder/layer_3/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.258383 140123635914624 estimator_utils.py:212]   name = encoder/layer_3/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.258496 140123635914624 estimator_utils.py:212]   name = encoder/layer_3/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.258614 140123635914624 estimator_utils.py:212]   name = encoder/layer_3/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.258704 140123635914624 estimator_utils.py:212]   name = encoder/layer_4/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.258788 140123635914624 estimator_utils.py:212]   name = encoder/layer_4/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.258875 140123635914624 estimator_utils.py:212]   name = encoder/layer_4/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.259122 140123635914624 estimator_utils.py:212]   name = encoder/layer_4/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.259320 140123635914624 estimator_utils.py:212]   name = encoder/layer_4/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.259452 140123635914624 estimator_utils.py:212]   name = encoder/layer_4/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.259562 140123635914624 estimator_utils.py:212]   name = encoder/layer_4/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.259701 140123635914624 estimator_utils.py:212]   name = encoder/layer_4/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.259808 140123635914624 estimator_utils.py:212]   name = encoder/layer_4/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.259943 140123635914624 estimator_utils.py:212]   name = encoder/layer_4/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.260040 140123635914624 estimator_utils.py:212]   name = encoder/layer_4/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.260127 140123635914624 estimator_utils.py:212]   name = encoder/layer_4/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.260214 140123635914624 estimator_utils.py:212]   name = encoder/layer_5/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.260337 140123635914624 estimator_utils.py:212]   name = encoder/layer_5/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.260431 140123635914624 estimator_utils.py:212]   name = encoder/layer_5/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.260528 140123635914624 estimator_utils.py:212]   name = encoder/layer_5/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.260650 140123635914624 estimator_utils.py:212]   name = encoder/layer_5/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.260752 140123635914624 estimator_utils.py:212]   name = encoder/layer_5/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.260845 140123635914624 estimator_utils.py:212]   name = encoder/layer_5/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.260932 140123635914624 estimator_utils.py:212]   name = encoder/layer_5/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.261015 140123635914624 estimator_utils.py:212]   name = encoder/layer_5/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.261103 140123635914624 estimator_utils.py:212]   name = encoder/layer_5/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.261187 140123635914624 estimator_utils.py:212]   name = encoder/layer_5/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.261273 140123635914624 estimator_utils.py:212]   name = encoder/layer_5/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.261370 140123635914624 estimator_utils.py:212]   name = encoder/layer_6/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.261453 140123635914624 estimator_utils.py:212]   name = encoder/layer_6/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.261537 140123635914624 estimator_utils.py:212]   name = encoder/layer_6/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.261656 140123635914624 estimator_utils.py:212]   name = encoder/layer_6/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.261781 140123635914624 estimator_utils.py:212]   name = encoder/layer_6/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.261882 140123635914624 estimator_utils.py:212]   name = encoder/layer_6/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.261976 140123635914624 estimator_utils.py:212]   name = encoder/layer_6/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.262063 140123635914624 estimator_utils.py:212]   name = encoder/layer_6/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.262163 140123635914624 estimator_utils.py:212]   name = encoder/layer_6/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.262254 140123635914624 estimator_utils.py:212]   name = encoder/layer_6/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.262354 140123635914624 estimator_utils.py:212]   name = encoder/layer_6/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.262445 140123635914624 estimator_utils.py:212]   name = encoder/layer_6/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.262534 140123635914624 estimator_utils.py:212]   name = encoder/layer_7/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.262657 140123635914624 estimator_utils.py:212]   name = encoder/layer_7/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.262751 140123635914624 estimator_utils.py:212]   name = encoder/layer_7/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.262847 140123635914624 estimator_utils.py:212]   name = encoder/layer_7/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.262940 140123635914624 estimator_utils.py:212]   name = encoder/layer_7/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.263040 140123635914624 estimator_utils.py:212]   name = encoder/layer_7/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.263139 140123635914624 estimator_utils.py:212]   name = encoder/layer_7/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.263232 140123635914624 estimator_utils.py:212]   name = encoder/layer_7/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.263331 140123635914624 estimator_utils.py:212]   name = encoder/layer_7/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.263424 140123635914624 estimator_utils.py:212]   name = encoder/layer_7/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.263513 140123635914624 estimator_utils.py:212]   name = encoder/layer_7/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.263627 140123635914624 estimator_utils.py:212]   name = encoder/layer_7/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.263730 140123635914624 estimator_utils.py:212]   name = encoder/layer_8/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.263825 140123635914624 estimator_utils.py:212]   name = encoder/layer_8/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.263918 140123635914624 estimator_utils.py:212]   name = encoder/layer_8/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.264008 140123635914624 estimator_utils.py:212]   name = encoder/layer_8/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.264097 140123635914624 estimator_utils.py:212]   name = encoder/layer_8/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.264195 140123635914624 estimator_utils.py:212]   name = encoder/layer_8/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.264315 140123635914624 estimator_utils.py:212]   name = encoder/layer_8/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.264413 140123635914624 estimator_utils.py:212]   name = encoder/layer_8/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.264500 140123635914624 estimator_utils.py:212]   name = encoder/layer_8/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.264618 140123635914624 estimator_utils.py:212]   name = encoder/layer_8/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.264720 140123635914624 estimator_utils.py:212]   name = encoder/layer_8/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.264823 140123635914624 estimator_utils.py:212]   name = encoder/layer_8/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.264919 140123635914624 estimator_utils.py:212]   name = encoder/layer_9/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.265004 140123635914624 estimator_utils.py:212]   name = encoder/layer_9/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.265084 140123635914624 estimator_utils.py:212]   name = encoder/layer_9/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.265169 140123635914624 estimator_utils.py:212]   name = encoder/layer_9/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.265251 140123635914624 estimator_utils.py:212]   name = encoder/layer_9/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.265356 140123635914624 estimator_utils.py:212]   name = encoder/layer_9/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.265444 140123635914624 estimator_utils.py:212]   name = encoder/layer_9/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.265527 140123635914624 estimator_utils.py:212]   name = encoder/layer_9/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.265629 140123635914624 estimator_utils.py:212]   name = encoder/layer_9/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.265727 140123635914624 estimator_utils.py:212]   name = encoder/layer_9/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.265802 140123635914624 estimator_utils.py:212]   name = encoder/layer_9/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.316870 140123635914624 estimator_utils.py:212]   name = encoder/layer_9/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.317210 140123635914624 estimator_utils.py:212]   name = encoder/layer_10/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.317375 140123635914624 estimator_utils.py:212]   name = encoder/layer_10/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.317499 140123635914624 estimator_utils.py:212]   name = encoder/layer_10/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.317676 140123635914624 estimator_utils.py:212]   name = encoder/layer_10/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.317815 140123635914624 estimator_utils.py:212]   name = encoder/layer_10/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.317947 140123635914624 estimator_utils.py:212]   name = encoder/layer_10/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.318092 140123635914624 estimator_utils.py:212]   name = encoder/layer_10/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.318214 140123635914624 estimator_utils.py:212]   name = encoder/layer_10/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.318334 140123635914624 estimator_utils.py:212]   name = encoder/layer_10/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.318458 140123635914624 estimator_utils.py:212]   name = encoder/layer_10/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.318593 140123635914624 estimator_utils.py:212]   name = encoder/layer_10/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.318724 140123635914624 estimator_utils.py:212]   name = encoder/layer_10/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.318842 140123635914624 estimator_utils.py:212]   name = encoder/layer_11/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.318956 140123635914624 estimator_utils.py:212]   name = encoder/layer_11/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.319088 140123635914624 estimator_utils.py:212]   name = encoder/layer_11/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.319209 140123635914624 estimator_utils.py:212]   name = encoder/layer_11/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.319329 140123635914624 estimator_utils.py:212]   name = encoder/layer_11/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.319447 140123635914624 estimator_utils.py:212]   name = encoder/layer_11/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.319573 140123635914624 estimator_utils.py:212]   name = encoder/layer_11/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.319712 140123635914624 estimator_utils.py:212]   name = encoder/layer_11/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.319826 140123635914624 estimator_utils.py:212]   name = encoder/layer_11/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.319962 140123635914624 estimator_utils.py:212]   name = encoder/layer_11/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.320094 140123635914624 estimator_utils.py:212]   name = encoder/layer_11/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.320215 140123635914624 estimator_utils.py:212]   name = encoder/layer_11/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.320330 140123635914624 estimator_utils.py:212]   name = encoder/layer_12/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.320442 140123635914624 estimator_utils.py:212]   name = encoder/layer_12/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.320555 140123635914624 estimator_utils.py:212]   name = encoder/layer_12/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.320699 140123635914624 estimator_utils.py:212]   name = encoder/layer_12/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.320822 140123635914624 estimator_utils.py:212]   name = encoder/layer_12/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.320940 140123635914624 estimator_utils.py:212]   name = encoder/layer_12/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.321078 140123635914624 estimator_utils.py:212]   name = encoder/layer_12/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.321194 140123635914624 estimator_utils.py:212]   name = encoder/layer_12/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.321306 140123635914624 estimator_utils.py:212]   name = encoder/layer_12/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.321423 140123635914624 estimator_utils.py:212]   name = encoder/layer_12/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.321537 140123635914624 estimator_utils.py:212]   name = encoder/layer_12/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.321683 140123635914624 estimator_utils.py:212]   name = encoder/layer_12/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.321800 140123635914624 estimator_utils.py:212]   name = encoder/layer_13/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.321912 140123635914624 estimator_utils.py:212]   name = encoder/layer_13/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.322041 140123635914624 estimator_utils.py:212]   name = encoder/layer_13/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.322162 140123635914624 estimator_utils.py:212]   name = encoder/layer_13/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.322277 140123635914624 estimator_utils.py:212]   name = encoder/layer_13/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.322394 140123635914624 estimator_utils.py:212]   name = encoder/layer_13/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.322512 140123635914624 estimator_utils.py:212]   name = encoder/layer_13/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.322649 140123635914624 estimator_utils.py:212]   name = encoder/layer_13/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.322767 140123635914624 estimator_utils.py:212]   name = encoder/layer_13/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.322883 140123635914624 estimator_utils.py:212]   name = encoder/layer_13/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.323006 140123635914624 estimator_utils.py:212]   name = encoder/layer_13/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.323128 140123635914624 estimator_utils.py:212]   name = encoder/layer_13/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.323239 140123635914624 estimator_utils.py:212]   name = encoder/layer_14/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.323350 140123635914624 estimator_utils.py:212]   name = encoder/layer_14/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.323460 140123635914624 estimator_utils.py:212]   name = encoder/layer_14/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.323595 140123635914624 estimator_utils.py:212]   name = encoder/layer_14/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.323724 140123635914624 estimator_utils.py:212]   name = encoder/layer_14/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.323856 140123635914624 estimator_utils.py:212]   name = encoder/layer_14/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.323984 140123635914624 estimator_utils.py:212]   name = encoder/layer_14/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.324102 140123635914624 estimator_utils.py:212]   name = encoder/layer_14/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.324213 140123635914624 estimator_utils.py:212]   name = encoder/layer_14/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.324331 140123635914624 estimator_utils.py:212]   name = encoder/layer_14/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.324441 140123635914624 estimator_utils.py:212]   name = encoder/layer_14/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.324560 140123635914624 estimator_utils.py:212]   name = encoder/layer_14/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.324701 140123635914624 estimator_utils.py:212]   name = encoder/layer_15/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.324814 140123635914624 estimator_utils.py:212]   name = encoder/layer_15/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.324940 140123635914624 estimator_utils.py:212]   name = encoder/layer_15/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.325071 140123635914624 estimator_utils.py:212]   name = encoder/layer_15/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.325190 140123635914624 estimator_utils.py:212]   name = encoder/layer_15/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.325308 140123635914624 estimator_utils.py:212]   name = encoder/layer_15/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.325425 140123635914624 estimator_utils.py:212]   name = encoder/layer_15/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.325539 140123635914624 estimator_utils.py:212]   name = encoder/layer_15/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.325675 140123635914624 estimator_utils.py:212]   name = encoder/layer_15/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.325796 140123635914624 estimator_utils.py:212]   name = encoder/layer_15/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.325934 140123635914624 estimator_utils.py:212]   name = encoder/layer_15/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.326070 140123635914624 estimator_utils.py:212]   name = encoder/layer_15/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.326186 140123635914624 estimator_utils.py:212]   name = encoder/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.326300 140123635914624 estimator_utils.py:212]   name = encoder/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.326425 140123635914624 estimator_utils.py:212]   name = decoder/layer_0/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.326540 140123635914624 estimator_utils.py:212]   name = decoder/layer_0/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.326678 140123635914624 estimator_utils.py:212]   name = decoder/layer_0/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.326799 140123635914624 estimator_utils.py:212]   name = decoder/layer_0/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.326915 140123635914624 estimator_utils.py:212]   name = decoder/layer_0/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.327048 140123635914624 estimator_utils.py:212]   name = decoder/layer_0/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.327171 140123635914624 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.327282 140123635914624 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.327391 140123635914624 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.327507 140123635914624 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.327646 140123635914624 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.327768 140123635914624 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.327886 140123635914624 estimator_utils.py:212]   name = decoder/layer_0/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.328011 140123635914624 estimator_utils.py:212]   name = decoder/layer_0/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.328128 140123635914624 estimator_utils.py:212]   name = decoder/layer_0/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.328244 140123635914624 estimator_utils.py:212]   name = decoder/layer_0/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.328356 140123635914624 estimator_utils.py:212]   name = decoder/layer_0/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.328470 140123635914624 estimator_utils.py:212]   name = decoder/layer_0/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.328602 140123635914624 estimator_utils.py:212]   name = decoder/layer_1/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.328721 140123635914624 estimator_utils.py:212]   name = decoder/layer_1/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.328832 140123635914624 estimator_utils.py:212]   name = decoder/layer_1/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.328947 140123635914624 estimator_utils.py:212]   name = decoder/layer_1/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.329107 140123635914624 estimator_utils.py:212]   name = decoder/layer_1/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.329229 140123635914624 estimator_utils.py:212]   name = decoder/layer_1/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.329350 140123635914624 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.329461 140123635914624 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.329573 140123635914624 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.329715 140123635914624 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.329833 140123635914624 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.329965 140123635914624 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.330101 140123635914624 estimator_utils.py:212]   name = decoder/layer_1/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.330215 140123635914624 estimator_utils.py:212]   name = decoder/layer_1/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.330327 140123635914624 estimator_utils.py:212]   name = decoder/layer_1/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.330440 140123635914624 estimator_utils.py:212]   name = decoder/layer_1/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.330554 140123635914624 estimator_utils.py:212]   name = decoder/layer_1/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.330704 140123635914624 estimator_utils.py:212]   name = decoder/layer_1/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.330823 140123635914624 estimator_utils.py:212]   name = decoder/layer_2/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.330935 140123635914624 estimator_utils.py:212]   name = decoder/layer_2/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.331062 140123635914624 estimator_utils.py:212]   name = decoder/layer_2/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.331181 140123635914624 estimator_utils.py:212]   name = decoder/layer_2/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.331297 140123635914624 estimator_utils.py:212]   name = decoder/layer_2/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.331415 140123635914624 estimator_utils.py:212]   name = decoder/layer_2/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.331533 140123635914624 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.331670 140123635914624 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.331784 140123635914624 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.331898 140123635914624 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.332042 140123635914624 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.332163 140123635914624 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.332280 140123635914624 estimator_utils.py:212]   name = decoder/layer_2/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.332391 140123635914624 estimator_utils.py:212]   name = decoder/layer_2/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.332503 140123635914624 estimator_utils.py:212]   name = decoder/layer_2/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.332639 140123635914624 estimator_utils.py:212]   name = decoder/layer_2/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.332755 140123635914624 estimator_utils.py:212]   name = decoder/layer_2/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.332873 140123635914624 estimator_utils.py:212]   name = decoder/layer_2/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.332997 140123635914624 estimator_utils.py:212]   name = decoder/layer_3/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.333113 140123635914624 estimator_utils.py:212]   name = decoder/layer_3/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.333223 140123635914624 estimator_utils.py:212]   name = decoder/layer_3/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.333340 140123635914624 estimator_utils.py:212]   name = decoder/layer_3/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.333455 140123635914624 estimator_utils.py:212]   name = decoder/layer_3/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.333571 140123635914624 estimator_utils.py:212]   name = decoder/layer_3/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.333716 140123635914624 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.333829 140123635914624 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.333940 140123635914624 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.334070 140123635914624 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.334188 140123635914624 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.334305 140123635914624 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.334423 140123635914624 estimator_utils.py:212]   name = decoder/layer_3/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.334535 140123635914624 estimator_utils.py:212]   name = decoder/layer_3/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.334668 140123635914624 estimator_utils.py:212]   name = decoder/layer_3/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.334787 140123635914624 estimator_utils.py:212]   name = decoder/layer_3/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.334899 140123635914624 estimator_utils.py:212]   name = decoder/layer_3/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.335028 140123635914624 estimator_utils.py:212]   name = decoder/layer_3/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.335144 140123635914624 estimator_utils.py:212]   name = decoder/layer_4/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.335254 140123635914624 estimator_utils.py:212]   name = decoder/layer_4/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.335365 140123635914624 estimator_utils.py:212]   name = decoder/layer_4/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.335481 140123635914624 estimator_utils.py:212]   name = decoder/layer_4/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.335618 140123635914624 estimator_utils.py:212]   name = decoder/layer_4/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.335741 140123635914624 estimator_utils.py:212]   name = decoder/layer_4/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.335857 140123635914624 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.335967 140123635914624 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.336094 140123635914624 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.336210 140123635914624 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.336323 140123635914624 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.336440 140123635914624 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.336560 140123635914624 estimator_utils.py:212]   name = decoder/layer_4/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.336700 140123635914624 estimator_utils.py:212]   name = decoder/layer_4/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.336813 140123635914624 estimator_utils.py:212]   name = decoder/layer_4/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.336928 140123635914624 estimator_utils.py:212]   name = decoder/layer_4/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.337052 140123635914624 estimator_utils.py:212]   name = decoder/layer_4/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.337170 140123635914624 estimator_utils.py:212]   name = decoder/layer_4/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.337283 140123635914624 estimator_utils.py:212]   name = decoder/layer_5/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.337394 140123635914624 estimator_utils.py:212]   name = decoder/layer_5/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.337503 140123635914624 estimator_utils.py:212]   name = decoder/layer_5/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.337637 140123635914624 estimator_utils.py:212]   name = decoder/layer_5/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.337758 140123635914624 estimator_utils.py:212]   name = decoder/layer_5/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.337874 140123635914624 estimator_utils.py:212]   name = decoder/layer_5/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.338003 140123635914624 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.338120 140123635914624 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.338229 140123635914624 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.338345 140123635914624 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.338461 140123635914624 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.338597 140123635914624 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.338716 140123635914624 estimator_utils.py:212]   name = decoder/layer_5/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.338826 140123635914624 estimator_utils.py:212]   name = decoder/layer_5/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.338937 140123635914624 estimator_utils.py:212]   name = decoder/layer_5/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.339068 140123635914624 estimator_utils.py:212]   name = decoder/layer_5/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.339182 140123635914624 estimator_utils.py:212]   name = decoder/layer_5/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.339298 140123635914624 estimator_utils.py:212]   name = decoder/layer_5/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.339409 140123635914624 estimator_utils.py:212]   name = decoder/layer_6/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.339522 140123635914624 estimator_utils.py:212]   name = decoder/layer_6/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.339655 140123635914624 estimator_utils.py:212]   name = decoder/layer_6/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.339775 140123635914624 estimator_utils.py:212]   name = decoder/layer_6/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.339892 140123635914624 estimator_utils.py:212]   name = decoder/layer_6/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.340038 140123635914624 estimator_utils.py:212]   name = decoder/layer_6/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.340161 140123635914624 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.340274 140123635914624 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.340385 140123635914624 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.340500 140123635914624 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.340634 140123635914624 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.340757 140123635914624 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.340874 140123635914624 estimator_utils.py:212]   name = decoder/layer_6/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.340998 140123635914624 estimator_utils.py:212]   name = decoder/layer_6/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.341116 140123635914624 estimator_utils.py:212]   name = decoder/layer_6/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.341233 140123635914624 estimator_utils.py:212]   name = decoder/layer_6/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.341345 140123635914624 estimator_utils.py:212]   name = decoder/layer_6/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.341461 140123635914624 estimator_utils.py:212]   name = decoder/layer_6/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.341593 140123635914624 estimator_utils.py:212]   name = decoder/layer_7/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.341713 140123635914624 estimator_utils.py:212]   name = decoder/layer_7/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.341823 140123635914624 estimator_utils.py:212]   name = decoder/layer_7/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.341938 140123635914624 estimator_utils.py:212]   name = decoder/layer_7/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.342069 140123635914624 estimator_utils.py:212]   name = decoder/layer_7/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.342185 140123635914624 estimator_utils.py:212]   name = decoder/layer_7/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.342304 140123635914624 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.342413 140123635914624 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.342526 140123635914624 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.342667 140123635914624 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.342786 140123635914624 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.342902 140123635914624 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.343033 140123635914624 estimator_utils.py:212]   name = decoder/layer_7/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.343147 140123635914624 estimator_utils.py:212]   name = decoder/layer_7/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.343257 140123635914624 estimator_utils.py:212]   name = decoder/layer_7/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.343371 140123635914624 estimator_utils.py:212]   name = decoder/layer_7/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.343482 140123635914624 estimator_utils.py:212]   name = decoder/layer_7/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.343619 140123635914624 estimator_utils.py:212]   name = decoder/layer_7/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.343740 140123635914624 estimator_utils.py:212]   name = decoder/layer_8/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.343852 140123635914624 estimator_utils.py:212]   name = decoder/layer_8/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.343962 140123635914624 estimator_utils.py:212]   name = decoder/layer_8/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.344096 140123635914624 estimator_utils.py:212]   name = decoder/layer_8/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.344213 140123635914624 estimator_utils.py:212]   name = decoder/layer_8/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.344328 140123635914624 estimator_utils.py:212]   name = decoder/layer_8/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.344445 140123635914624 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.344557 140123635914624 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.344692 140123635914624 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.344810 140123635914624 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.344913 140123635914624 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.345036 140123635914624 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.345154 140123635914624 estimator_utils.py:212]   name = decoder/layer_8/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.345263 140123635914624 estimator_utils.py:212]   name = decoder/layer_8/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.345371 140123635914624 estimator_utils.py:212]   name = decoder/layer_8/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.345486 140123635914624 estimator_utils.py:212]   name = decoder/layer_8/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.345618 140123635914624 estimator_utils.py:212]   name = decoder/layer_8/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.345741 140123635914624 estimator_utils.py:212]   name = decoder/layer_8/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.345852 140123635914624 estimator_utils.py:212]   name = decoder/layer_9/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.345962 140123635914624 estimator_utils.py:212]   name = decoder/layer_9/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.346127 140123635914624 estimator_utils.py:212]   name = decoder/layer_9/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.346247 140123635914624 estimator_utils.py:212]   name = decoder/layer_9/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.346366 140123635914624 estimator_utils.py:212]   name = decoder/layer_9/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.346483 140123635914624 estimator_utils.py:212]   name = decoder/layer_9/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.346625 140123635914624 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.346743 140123635914624 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.346856 140123635914624 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.346972 140123635914624 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.347121 140123635914624 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.347243 140123635914624 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.347361 140123635914624 estimator_utils.py:212]   name = decoder/layer_9/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.347470 140123635914624 estimator_utils.py:212]   name = decoder/layer_9/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.347604 140123635914624 estimator_utils.py:212]   name = decoder/layer_9/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.347748 140123635914624 estimator_utils.py:212]   name = decoder/layer_9/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.347864 140123635914624 estimator_utils.py:212]   name = decoder/layer_9/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.347993 140123635914624 estimator_utils.py:212]   name = decoder/layer_9/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.348112 140123635914624 estimator_utils.py:212]   name = decoder/layer_10/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.348224 140123635914624 estimator_utils.py:212]   name = decoder/layer_10/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.348334 140123635914624 estimator_utils.py:212]   name = decoder/layer_10/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.348450 140123635914624 estimator_utils.py:212]   name = decoder/layer_10/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.348565 140123635914624 estimator_utils.py:212]   name = decoder/layer_10/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.348709 140123635914624 estimator_utils.py:212]   name = decoder/layer_10/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.348829 140123635914624 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.348943 140123635914624 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.349095 140123635914624 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.349219 140123635914624 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.349334 140123635914624 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.349452 140123635914624 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.349571 140123635914624 estimator_utils.py:212]   name = decoder/layer_10/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.349709 140123635914624 estimator_utils.py:212]   name = decoder/layer_10/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.349823 140123635914624 estimator_utils.py:212]   name = decoder/layer_10/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.349956 140123635914624 estimator_utils.py:212]   name = decoder/layer_10/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.350086 140123635914624 estimator_utils.py:212]   name = decoder/layer_10/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.350204 140123635914624 estimator_utils.py:212]   name = decoder/layer_10/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.350316 140123635914624 estimator_utils.py:212]   name = decoder/layer_11/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.350428 140123635914624 estimator_utils.py:212]   name = decoder/layer_11/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.350539 140123635914624 estimator_utils.py:212]   name = decoder/layer_11/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.350680 140123635914624 estimator_utils.py:212]   name = decoder/layer_11/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.350798 140123635914624 estimator_utils.py:212]   name = decoder/layer_11/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.350914 140123635914624 estimator_utils.py:212]   name = decoder/layer_11/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.351047 140123635914624 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.351161 140123635914624 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.351271 140123635914624 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.351387 140123635914624 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.351506 140123635914624 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.351643 140123635914624 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.351765 140123635914624 estimator_utils.py:212]   name = decoder/layer_11/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.351874 140123635914624 estimator_utils.py:212]   name = decoder/layer_11/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.351997 140123635914624 estimator_utils.py:212]   name = decoder/layer_11/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.352120 140123635914624 estimator_utils.py:212]   name = decoder/layer_11/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.352232 140123635914624 estimator_utils.py:212]   name = decoder/layer_11/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.352349 140123635914624 estimator_utils.py:212]   name = decoder/layer_11/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.352461 140123635914624 estimator_utils.py:212]   name = decoder/layer_12/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.352572 140123635914624 estimator_utils.py:212]   name = decoder/layer_12/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.352710 140123635914624 estimator_utils.py:212]   name = decoder/layer_12/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.352829 140123635914624 estimator_utils.py:212]   name = decoder/layer_12/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.352945 140123635914624 estimator_utils.py:212]   name = decoder/layer_12/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.353079 140123635914624 estimator_utils.py:212]   name = decoder/layer_12/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.353197 140123635914624 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.353307 140123635914624 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.353416 140123635914624 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.353530 140123635914624 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.353671 140123635914624 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.353790 140123635914624 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.353907 140123635914624 estimator_utils.py:212]   name = decoder/layer_12/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.354034 140123635914624 estimator_utils.py:212]   name = decoder/layer_12/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.354150 140123635914624 estimator_utils.py:212]   name = decoder/layer_12/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.354264 140123635914624 estimator_utils.py:212]   name = decoder/layer_12/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.354374 140123635914624 estimator_utils.py:212]   name = decoder/layer_12/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.354488 140123635914624 estimator_utils.py:212]   name = decoder/layer_12/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.354621 140123635914624 estimator_utils.py:212]   name = decoder/layer_13/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.354736 140123635914624 estimator_utils.py:212]   name = decoder/layer_13/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.354847 140123635914624 estimator_utils.py:212]   name = decoder/layer_13/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.354962 140123635914624 estimator_utils.py:212]   name = decoder/layer_13/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.355097 140123635914624 estimator_utils.py:212]   name = decoder/layer_13/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.355214 140123635914624 estimator_utils.py:212]   name = decoder/layer_13/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.355330 140123635914624 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.355440 140123635914624 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.355550 140123635914624 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.355691 140123635914624 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.355809 140123635914624 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.355925 140123635914624 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.356057 140123635914624 estimator_utils.py:212]   name = decoder/layer_13/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.356171 140123635914624 estimator_utils.py:212]   name = decoder/layer_13/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.356283 140123635914624 estimator_utils.py:212]   name = decoder/layer_13/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.356399 140123635914624 estimator_utils.py:212]   name = decoder/layer_13/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.356510 140123635914624 estimator_utils.py:212]   name = decoder/layer_13/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.356648 140123635914624 estimator_utils.py:212]   name = decoder/layer_13/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.356764 140123635914624 estimator_utils.py:212]   name = decoder/layer_14/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.356875 140123635914624 estimator_utils.py:212]   name = decoder/layer_14/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.356995 140123635914624 estimator_utils.py:212]   name = decoder/layer_14/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.357116 140123635914624 estimator_utils.py:212]   name = decoder/layer_14/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.357233 140123635914624 estimator_utils.py:212]   name = decoder/layer_14/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.357348 140123635914624 estimator_utils.py:212]   name = decoder/layer_14/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.357463 140123635914624 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.357593 140123635914624 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.357713 140123635914624 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.357832 140123635914624 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.357948 140123635914624 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.358079 140123635914624 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.358198 140123635914624 estimator_utils.py:212]   name = decoder/layer_14/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.358310 140123635914624 estimator_utils.py:212]   name = decoder/layer_14/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.358420 140123635914624 estimator_utils.py:212]   name = decoder/layer_14/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.358535 140123635914624 estimator_utils.py:212]   name = decoder/layer_14/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.358670 140123635914624 estimator_utils.py:212]   name = decoder/layer_14/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.358788 140123635914624 estimator_utils.py:212]   name = decoder/layer_14/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.358900 140123635914624 estimator_utils.py:212]   name = decoder/layer_15/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.359026 140123635914624 estimator_utils.py:212]   name = decoder/layer_15/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.359141 140123635914624 estimator_utils.py:212]   name = decoder/layer_15/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.359258 140123635914624 estimator_utils.py:212]   name = decoder/layer_15/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.359373 140123635914624 estimator_utils.py:212]   name = decoder/layer_15/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.359488 140123635914624 estimator_utils.py:212]   name = decoder/layer_15/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.359628 140123635914624 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.359742 140123635914624 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.359853 140123635914624 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.359992 140123635914624 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.360116 140123635914624 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.360233 140123635914624 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.360350 140123635914624 estimator_utils.py:212]   name = decoder/layer_15/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.360462 140123635914624 estimator_utils.py:212]   name = decoder/layer_15/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.360589 140123635914624 estimator_utils.py:212]   name = decoder/layer_15/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 21:03:25.360714 140123635914624 estimator_utils.py:212]   name = decoder/layer_15/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 21:03:25.360824 140123635914624 estimator_utils.py:212]   name = decoder/layer_15/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 21:03:25.360939 140123635914624 estimator_utils.py:212]   name = decoder/layer_15/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.361066 140123635914624 estimator_utils.py:212]   name = decoder/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 21:03:25.361180 140123635914624 estimator_utils.py:212]   name = decoder/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    INFO:tensorflow:Done calling model_fn.\n    I0830 21:03:25.380557 140123635914624 estimator.py:1150] Done calling model_fn.\n    INFO:tensorflow:Create CheckpointSaverHook.\n    I0830 21:03:25.382021 140123635914624 basic_session_run_hooks.py:541] Create CheckpointSaverHook.\n    INFO:tensorflow:Graph was finalized.\n    I0830 21:03:34.186985 140123635914624 monitored_session.py:240] Graph was finalized.\n    2020-08-30 21:03:34.187754: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA\n    2020-08-30 21:03:34.205835: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2200000000 Hz\n    2020-08-30 21:03:34.206463: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x187c840 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n    2020-08-30 21:03:34.206509: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version\n    2020-08-30 21:03:48.338481: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 393637888 exceeds 10% of system memory.\n    INFO:tensorflow:Running local_init_op.\n    I0830 21:04:23.029951 140123635914624 session_manager.py:500] Running local_init_op.\n    INFO:tensorflow:Done running local_init_op.\n    I0830 21:04:23.928683 140123635914624 session_manager.py:502] Done running local_init_op.\n    INFO:tensorflow:Saving checkpoints for 0 into ckpt/pegasus_ckpt/gigaword/model.ckpt.\n    I0830 21:04:46.855744 140123635914624 basic_session_run_hooks.py:606] Saving checkpoints for 0 into ckpt/pegasus_ckpt/gigaword/model.ckpt.\n    2020-08-30 21:05:33.044062: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 393637888 exceeds 10% of system memory.\n    2020-08-30 21:05:34.363346: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 393637888 exceeds 10% of system memory.\n    2020-08-30 21:05:36.273984: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 393637888 exceeds 10% of system memory.\n    2020-08-30 21:05:55.805034: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 393637888 exceeds 10% of system memory.\n    INFO:tensorflow:global_step/sec: 0.00717638\n    I0830 21:09:59.703754 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.00717638\n    INFO:tensorflow:examples/sec: 0.114822\n    I0830 21:09:59.705836 140123635914624 tpu_estimator.py:2308] examples/sec: 0.114822\n    INFO:tensorflow:global_step/sec: 0.0111429\n    I0830 21:11:29.446985 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0111429\n    INFO:tensorflow:examples/sec: 0.178286\n    I0830 21:11:29.447540 140123635914624 tpu_estimator.py:2308] examples/sec: 0.178286\n    INFO:tensorflow:global_step/sec: 0.0111007\n    I0830 21:12:59.531715 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0111007\n    INFO:tensorflow:examples/sec: 0.177611\n    I0830 21:12:59.532381 140123635914624 tpu_estimator.py:2308] examples/sec: 0.177611\n    INFO:tensorflow:global_step/sec: 0.011042\n    I0830 21:14:30.095305 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.011042\n    INFO:tensorflow:examples/sec: 0.176671\n    I0830 21:14:30.095894 140123635914624 tpu_estimator.py:2308] examples/sec: 0.176671\n    INFO:tensorflow:global_step/sec: 0.0107054\n    I0830 21:16:03.506235 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0107054\n    INFO:tensorflow:examples/sec: 0.171286\n    I0830 21:16:03.506983 140123635914624 tpu_estimator.py:2308] examples/sec: 0.171286\n    INFO:tensorflow:global_step/sec: 0.0110116\n    I0830 21:17:34.319474 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0110116\n    INFO:tensorflow:examples/sec: 0.176186\n    I0830 21:17:34.320136 140123635914624 tpu_estimator.py:2308] examples/sec: 0.176186\n    INFO:tensorflow:global_step/sec: 0.0109357\n    I0830 21:19:05.763023 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0109357\n    INFO:tensorflow:examples/sec: 0.174972\n    I0830 21:19:05.763853 140123635914624 tpu_estimator.py:2308] examples/sec: 0.174972\n    INFO:tensorflow:global_step/sec: 0.0108024\n    I0830 21:20:38.335127 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0108024\n    INFO:tensorflow:examples/sec: 0.172838\n    I0830 21:20:38.335446 140123635914624 tpu_estimator.py:2308] examples/sec: 0.172838\n    INFO:tensorflow:global_step/sec: 0.0105942\n    I0830 21:22:12.726813 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0105942\n    INFO:tensorflow:examples/sec: 0.169506\n    I0830 21:22:12.727603 140123635914624 tpu_estimator.py:2308] examples/sec: 0.169506\n    INFO:tensorflow:global_step/sec: 0.0107392\n    I0830 21:23:45.843533 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0107392\n    INFO:tensorflow:examples/sec: 0.171827\n    I0830 21:23:45.843959 140123635914624 tpu_estimator.py:2308] examples/sec: 0.171827\n    INFO:tensorflow:global_step/sec: 0.0108757\n    I0830 21:25:17.791267 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0108757\n    INFO:tensorflow:examples/sec: 0.174012\n    I0830 21:25:17.792011 140123635914624 tpu_estimator.py:2308] examples/sec: 0.174012\n    INFO:tensorflow:global_step/sec: 0.0110176\n    I0830 21:26:48.554897 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0110176\n    INFO:tensorflow:examples/sec: 0.176282\n    I0830 21:26:48.555414 140123635914624 tpu_estimator.py:2308] examples/sec: 0.176282\n    INFO:tensorflow:global_step/sec: 0.0110229\n    I0830 21:28:19.274919 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0110229\n    INFO:tensorflow:examples/sec: 0.176367\n    I0830 21:28:19.275704 140123635914624 tpu_estimator.py:2308] examples/sec: 0.176367\n    INFO:tensorflow:global_step/sec: 0.0109236\n    I0830 21:29:50.820113 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0109236\n    INFO:tensorflow:examples/sec: 0.174777\n    I0830 21:29:50.820749 140123635914624 tpu_estimator.py:2308] examples/sec: 0.174777\n    INFO:tensorflow:global_step/sec: 0.0107616\n    I0830 21:31:23.742971 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0107616\n    INFO:tensorflow:examples/sec: 0.172186\n    I0830 21:31:23.743809 140123635914624 tpu_estimator.py:2308] examples/sec: 0.172186\n    INFO:tensorflow:global_step/sec: 0.0108002\n    I0830 21:32:56.333424 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0108002\n    INFO:tensorflow:examples/sec: 0.172804\n    I0830 21:32:56.334070 140123635914624 tpu_estimator.py:2308] examples/sec: 0.172804\n    INFO:tensorflow:global_step/sec: 0.0108511\n    I0830 21:34:28.490111 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0108511\n    INFO:tensorflow:examples/sec: 0.173617\n    I0830 21:34:28.490438 140123635914624 tpu_estimator.py:2308] examples/sec: 0.173617\n    INFO:tensorflow:global_step/sec: 0.0107908\n    I0830 21:36:01.161722 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0107908\n    INFO:tensorflow:examples/sec: 0.172653\n    I0830 21:36:01.162120 140123635914624 tpu_estimator.py:2308] examples/sec: 0.172653\n    INFO:tensorflow:global_step/sec: 0.0107886\n    I0830 21:37:33.852528 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0107886\n    INFO:tensorflow:examples/sec: 0.172617\n    I0830 21:37:33.852987 140123635914624 tpu_estimator.py:2308] examples/sec: 0.172617\n    INFO:tensorflow:global_step/sec: 0.0109391\n    I0830 21:39:05.267513 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0109391\n    INFO:tensorflow:examples/sec: 0.175026\n    I0830 21:39:05.267922 140123635914624 tpu_estimator.py:2308] examples/sec: 0.175026\n    INFO:tensorflow:global_step/sec: 0.0111807\n    I0830 21:40:34.707443 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0111807\n    INFO:tensorflow:examples/sec: 0.178891\n    I0830 21:40:34.707782 140123635914624 tpu_estimator.py:2308] examples/sec: 0.178891\n    INFO:tensorflow:global_step/sec: 0.0112023\n    I0830 21:42:03.975168 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0112023\n    INFO:tensorflow:examples/sec: 0.179236\n    I0830 21:42:03.975762 140123635914624 tpu_estimator.py:2308] examples/sec: 0.179236\n    INFO:tensorflow:global_step/sec: 0.0111516\n    I0830 21:43:33.648468 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0111516\n    INFO:tensorflow:examples/sec: 0.178425\n    I0830 21:43:33.649236 140123635914624 tpu_estimator.py:2308] examples/sec: 0.178425\n    INFO:tensorflow:global_step/sec: 0.011139\n    I0830 21:45:03.422865 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.011139\n    INFO:tensorflow:examples/sec: 0.178225\n    I0830 21:45:03.423219 140123635914624 tpu_estimator.py:2308] examples/sec: 0.178225\n    INFO:tensorflow:global_step/sec: 0.0112407\n    I0830 21:46:32.385354 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0112407\n    INFO:tensorflow:examples/sec: 0.179851\n    I0830 21:46:32.386211 140123635914624 tpu_estimator.py:2308] examples/sec: 0.179851\n    INFO:tensorflow:global_step/sec: 0.0111807\n    I0830 21:48:01.824838 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0111807\n    INFO:tensorflow:examples/sec: 0.178892\n    I0830 21:48:01.825404 140123635914624 tpu_estimator.py:2308] examples/sec: 0.178892\n    INFO:tensorflow:global_step/sec: 0.0109611\n    I0830 21:49:33.056815 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0109611\n    INFO:tensorflow:examples/sec: 0.175377\n    I0830 21:49:33.057662 140123635914624 tpu_estimator.py:2308] examples/sec: 0.175377\n    INFO:tensorflow:global_step/sec: 0.0110172\n    I0830 21:51:03.823675 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0110172\n    INFO:tensorflow:examples/sec: 0.176276\n    I0830 21:51:03.824297 140123635914624 tpu_estimator.py:2308] examples/sec: 0.176276\n    INFO:tensorflow:global_step/sec: 0.0108918\n    I0830 21:52:35.635863 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0108918\n    INFO:tensorflow:examples/sec: 0.174269\n    I0830 21:52:35.636703 140123635914624 tpu_estimator.py:2308] examples/sec: 0.174269\n    INFO:tensorflow:global_step/sec: 0.0109236\n    I0830 21:54:07.180635 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0109236\n    INFO:tensorflow:examples/sec: 0.174778\n    I0830 21:54:07.181559 140123635914624 tpu_estimator.py:2308] examples/sec: 0.174778\n    INFO:tensorflow:global_step/sec: 0.0109703\n    I0830 21:55:38.336010 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0109703\n    INFO:tensorflow:examples/sec: 0.175524\n    I0830 21:55:38.336822 140123635914624 tpu_estimator.py:2308] examples/sec: 0.175524\n    INFO:tensorflow:global_step/sec: 0.0111892\n    I0830 21:57:07.707545 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0111892\n    INFO:tensorflow:examples/sec: 0.179028\n    I0830 21:57:07.708172 140123635914624 tpu_estimator.py:2308] examples/sec: 0.179028\n    INFO:tensorflow:global_step/sec: 0.0112488\n    I0830 21:58:36.605763 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0112488\n    INFO:tensorflow:examples/sec: 0.179981\n    I0830 21:58:36.606462 140123635914624 tpu_estimator.py:2308] examples/sec: 0.179981\n    INFO:tensorflow:global_step/sec: 0.0111018\n    I0830 22:00:06.681497 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0111018\n    INFO:tensorflow:examples/sec: 0.177629\n    I0830 22:00:06.681910 140123635914624 tpu_estimator.py:2308] examples/sec: 0.177629\n    INFO:tensorflow:global_step/sec: 0.0110073\n    I0830 22:01:37.529894 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0110073\n    INFO:tensorflow:examples/sec: 0.176117\n    I0830 22:01:37.530641 140123635914624 tpu_estimator.py:2308] examples/sec: 0.176117\n    INFO:tensorflow:global_step/sec: 0.0109289\n    I0830 22:03:09.030720 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0109289\n    INFO:tensorflow:examples/sec: 0.174862\n    I0830 22:03:09.031134 140123635914624 tpu_estimator.py:2308] examples/sec: 0.174862\n    INFO:tensorflow:global_step/sec: 0.0105456\n    I0830 22:04:43.856714 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0105456\n    INFO:tensorflow:examples/sec: 0.16873\n    I0830 22:04:43.857089 140123635914624 tpu_estimator.py:2308] examples/sec: 0.16873\n    INFO:tensorflow:global_step/sec: 0.0107029\n    I0830 22:06:17.289099 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0107029\n    INFO:tensorflow:examples/sec: 0.171247\n    I0830 22:06:17.289696 140123635914624 tpu_estimator.py:2308] examples/sec: 0.171247\n    INFO:tensorflow:global_step/sec: 0.0107999\n    I0830 22:07:49.882884 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0107999\n    INFO:tensorflow:examples/sec: 0.172798\n    I0830 22:07:49.883763 140123635914624 tpu_estimator.py:2308] examples/sec: 0.172798\n    INFO:tensorflow:global_step/sec: 0.0108653\n    I0830 22:09:21.918995 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0108653\n    INFO:tensorflow:examples/sec: 0.173845\n    I0830 22:09:21.920072 140123635914624 tpu_estimator.py:2308] examples/sec: 0.173845\n    INFO:tensorflow:global_step/sec: 0.0106076\n    I0830 22:10:56.190783 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0106076\n    INFO:tensorflow:examples/sec: 0.169722\n    I0830 22:10:56.191796 140123635914624 tpu_estimator.py:2308] examples/sec: 0.169722\n    INFO:tensorflow:global_step/sec: 0.0105109\n    I0830 22:12:31.329728 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0105109\n    INFO:tensorflow:examples/sec: 0.168175\n    I0830 22:12:31.330093 140123635914624 tpu_estimator.py:2308] examples/sec: 0.168175\n    INFO:tensorflow:global_step/sec: 0.0105069\n    I0830 22:14:06.504817 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0105069\n    INFO:tensorflow:examples/sec: 0.168111\n    I0830 22:14:06.505168 140123635914624 tpu_estimator.py:2308] examples/sec: 0.168111\n    INFO:tensorflow:global_step/sec: 0.0107839\n    I0830 22:15:39.236044 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0107839\n    INFO:tensorflow:examples/sec: 0.172542\n    I0830 22:15:39.236729 140123635914624 tpu_estimator.py:2308] examples/sec: 0.172542\n    INFO:tensorflow:global_step/sec: 0.0109773\n    I0830 22:17:10.333201 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0109773\n    INFO:tensorflow:examples/sec: 0.175637\n    I0830 22:17:10.334058 140123635914624 tpu_estimator.py:2308] examples/sec: 0.175637\n    INFO:tensorflow:global_step/sec: 0.0108812\n    I0830 22:18:42.234507 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0108812\n    INFO:tensorflow:examples/sec: 0.1741\n    I0830 22:18:42.234829 140123635914624 tpu_estimator.py:2308] examples/sec: 0.1741\n    INFO:tensorflow:global_step/sec: 0.010934\n    I0830 22:20:13.691963 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.010934\n    INFO:tensorflow:examples/sec: 0.174945\n    I0830 22:20:13.692711 140123635914624 tpu_estimator.py:2308] examples/sec: 0.174945\n    INFO:tensorflow:global_step/sec: 0.0109143\n    I0830 22:21:45.315443 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0109143\n    INFO:tensorflow:examples/sec: 0.174628\n    I0830 22:21:45.316247 140123635914624 tpu_estimator.py:2308] examples/sec: 0.174628\n    INFO:tensorflow:global_step/sec: 0.0110227\n    I0830 22:23:16.037398 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0110227\n    INFO:tensorflow:examples/sec: 0.176363\n    I0830 22:23:16.038305 140123635914624 tpu_estimator.py:2308] examples/sec: 0.176363\n    INFO:tensorflow:global_step/sec: 0.0112029\n    I0830 22:24:45.299608 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0112029\n    INFO:tensorflow:examples/sec: 0.179247\n    I0830 22:24:45.300141 140123635914624 tpu_estimator.py:2308] examples/sec: 0.179247\n    INFO:tensorflow:global_step/sec: 0.0112383\n    I0830 22:26:14.280764 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0112383\n    INFO:tensorflow:examples/sec: 0.179813\n    I0830 22:26:14.281494 140123635914624 tpu_estimator.py:2308] examples/sec: 0.179813\n    INFO:tensorflow:global_step/sec: 0.0111357\n    I0830 22:27:44.082498 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0111357\n    INFO:tensorflow:examples/sec: 0.178171\n    I0830 22:27:44.083315 140123635914624 tpu_estimator.py:2308] examples/sec: 0.178171\n    INFO:tensorflow:global_step/sec: 0.0111319\n    I0830 22:29:13.914244 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0111319\n    INFO:tensorflow:examples/sec: 0.178111\n    I0830 22:29:13.915099 140123635914624 tpu_estimator.py:2308] examples/sec: 0.178111\n    INFO:tensorflow:global_step/sec: 0.0111686\n    I0830 22:30:43.451262 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0111686\n    INFO:tensorflow:examples/sec: 0.178697\n    I0830 22:30:43.451623 140123635914624 tpu_estimator.py:2308] examples/sec: 0.178697\n    INFO:tensorflow:global_step/sec: 0.0111622\n    I0830 22:32:13.039164 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0111622\n    INFO:tensorflow:examples/sec: 0.178595\n    I0830 22:32:13.039968 140123635914624 tpu_estimator.py:2308] examples/sec: 0.178595\n    INFO:tensorflow:global_step/sec: 0.0110934\n    I0830 22:33:43.182779 140123635914624 tpu_estimator.py:2307] global_step/sec: 0.0110934\n    INFO:tensorflow:examples/sec: 0.177495\n    I0830 22:33:43.183507 140123635914624 tpu_estimator.py:2308] examples/sec: 0.177495\n    ^C\n\n\n\n```\n!python3 pegasus/bin/train.py --params=reddit_tifu_long_transformer \\\n--param_overrides=vocab_filename=ckpt/pegasus_ckpt/c4.unigram.newline.10pct.96000.model \\\n--train_init_checkpoint=ckpt/pegasus_ckpt/model.ckpt-1500000 \\\n--model_dir=ckpt/pegasus_ckpt/reddit_tifu_long\n```\n\n    WARNING:tensorflow:From pegasus/bin/train.py:94: The name tf.app.run is deprecated. Please use tf.compat.v1.app.run instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/ops/public_parsing_ops.py:93: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n    \n    W0830 22:35:22.670966 140449568884608 module_wrapper.py:139] From /content/pegasus/pegasus/ops/public_parsing_ops.py:93: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:49: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead.\n    \n    W0830 22:35:22.858121 140449568884608 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:49: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead.\n    \n    WARNING:tensorflow:Estimator's model_fn (<function _estimator_model_fn.<locals>.model_fn at 0x7fbc7adc8b70>) includes params argument, but params are not passed to Estimator.\n    W0830 22:35:22.858817 140449568884608 estimator.py:1994] Estimator's model_fn (<function _estimator_model_fn.<locals>.model_fn at 0x7fbc7adc8b70>) includes params argument, but params are not passed to Estimator.\n    INFO:tensorflow:Using config: {'_model_dir': 'ckpt/pegasus_ckpt/reddit_tifu_long', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': 1000, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true\n    , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': None, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7fbc7adbdcc0>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1, '_tpu_config': TPUConfig(iterations_per_loop=1000, num_shards=None, num_cores_per_replica=None, per_host_input_for_training=2, tpu_job_name=None, initial_infeed_sleep_secs=None, input_partition_dims=None, eval_training_input_configuration=2, experimental_host_call_every_n_steps=1), '_cluster': None}\n    I0830 22:35:22.859336 140449568884608 estimator.py:212] Using config: {'_model_dir': 'ckpt/pegasus_ckpt/reddit_tifu_long', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': 1000, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true\n    , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': None, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7fbc7adbdcc0>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1, '_tpu_config': TPUConfig(iterations_per_loop=1000, num_shards=None, num_cores_per_replica=None, per_host_input_for_training=2, tpu_job_name=None, initial_infeed_sleep_secs=None, input_partition_dims=None, eval_training_input_configuration=2, experimental_host_call_every_n_steps=1), '_cluster': None}\n    INFO:tensorflow:_TPUContext: eval_on_tpu True\n    I0830 22:35:22.859642 140449568884608 tpu_context.py:220] _TPUContext: eval_on_tpu True\n    WARNING:tensorflow:eval_on_tpu ignored because use_tpu is False.\n    W0830 22:35:22.860470 140449568884608 tpu_context.py:222] eval_on_tpu ignored because use_tpu is False.\n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\n    Instructions for updating:\n    If using Keras pass *_constraint arguments to layers.\n    W0830 22:35:22.867233 140449568884608 deprecation.py:506] From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\n    Instructions for updating:\n    If using Keras pass *_constraint arguments to layers.\n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.\n    W0830 22:35:22.867718 140449568884608 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.\n    2020-08-30 22:35:22.880601: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    2020-08-30 22:35:23.083725: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    2020-08-30 22:35:23.325192: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    I0830 22:35:23.552087 140449568884608 dataset_info.py:424] Load pre-computed DatasetInfo (eg: splits, num examples,...) from GCS: reddit_tifu/long/1.1.0\n    2020-08-30 22:35:23.559563: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    I0830 22:35:24.113338 140449568884608 dataset_info.py:355] Load dataset info from /tmp/tmpc12p906qtfds\n    I0830 22:35:24.115318 140449568884608 dataset_info.py:395] Field info.description from disk and from code do not match. Keeping the one from code.\n    I0830 22:35:24.115490 140449568884608 dataset_info.py:395] Field info.config_name from disk and from code do not match. Keeping the one from code.\n    I0830 22:35:24.115600 140449568884608 dataset_info.py:395] Field info.citation from disk and from code do not match. Keeping the one from code.\n    I0830 22:35:24.115962 140449568884608 dataset_builder.py:349] Generating dataset reddit_tifu (/root/tensorflow_datasets/reddit_tifu/long/1.1.0)\n    \u001b[1mDownloading and preparing dataset reddit_tifu/long/1.1.0 (download: 639.54 MiB, generated: Unknown size, total: 639.54 MiB) to /root/tensorflow_datasets/reddit_tifu/long/1.1.0...\u001b[0m\n    2020-08-30 22:35:24.211498: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    2020-08-30 22:35:24.578082: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    Dl Completed...: 0 url [00:00, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[AI0830 22:35:24.792383 140449568884608 download_manager.py:478] Downloading https://drive.google.com/uc?export=download&id=1ffWfITKFMJeqjT8loC8aiCLRNJpc_XnF into /root/tensorflow_datasets/downloads/ucexport_download_id_1ffWfITKFMJeqjT8loC8a_XnFKBkIaeZ0glhNGWombXK7QgN8uq9nDHA-eFtk8ZIIqCA.tmp.53d9d0fee0e14d81a7c0f159459ae32f...\n    Dl Completed...:   0% 0/1 [00:00<?, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:01<?, ? url/s]\n    Dl Size...: 0 MiB [00:01, ? MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:01, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:01<?, ? url/s]\n    Dl Size...: 1 MiB [00:01,  1.64s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:01<?, ? url/s]\n    Dl Size...: 2 MiB [00:01,  1.64s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:01<?, ? url/s]\n    Dl Size...: 3 MiB [00:01,  1.64s/ MiB]\u001b[A\n    \n    Extraction completed...: 0 file [00:01, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:01<?, ? url/s]\n    Dl Size...: 4 MiB [00:01,  1.19s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 5 MiB [00:02,  1.19s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 6 MiB [00:02,  1.19s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 7 MiB [00:02,  1.19s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 8 MiB [00:02,  1.19s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 9 MiB [00:02,  1.19s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 10 MiB [00:02,  1.19s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 11 MiB [00:02,  1.19s/ MiB]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 12 MiB [00:02,  1.19s/ MiB]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 13 MiB [00:02,  1.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 14 MiB [00:02,  1.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 15 MiB [00:02,  1.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 16 MiB [00:02,  1.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 17 MiB [00:02,  1.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 18 MiB [00:02,  1.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 19 MiB [00:02,  1.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 20 MiB [00:02,  1.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 21 MiB [00:02,  1.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 22 MiB [00:02,  1.20 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 23 MiB [00:02,  1.71 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 24 MiB [00:02,  1.71 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 25 MiB [00:02,  1.71 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 26 MiB [00:02,  1.71 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 27 MiB [00:02,  1.71 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 28 MiB [00:02,  1.71 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 29 MiB [00:02,  1.71 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 30 MiB [00:02,  1.71 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 31 MiB [00:02,  1.71 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 32 MiB [00:02,  2.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 33 MiB [00:02,  2.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 34 MiB [00:02,  2.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 35 MiB [00:02,  2.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 36 MiB [00:02,  2.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 37 MiB [00:02,  2.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 38 MiB [00:02,  2.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 39 MiB [00:02,  2.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 40 MiB [00:02,  2.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 41 MiB [00:02,  2.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 42 MiB [00:02,  2.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 43 MiB [00:02,  2.40 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 44 MiB [00:02,  3.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 45 MiB [00:02,  3.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 46 MiB [00:02,  3.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 47 MiB [00:02,  3.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 48 MiB [00:02,  3.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 49 MiB [00:02,  3.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 50 MiB [00:02,  3.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 51 MiB [00:02,  3.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 52 MiB [00:02,  3.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 53 MiB [00:02,  3.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 54 MiB [00:02,  3.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 55 MiB [00:02,  3.40 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 56 MiB [00:02,  4.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 57 MiB [00:02,  4.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 58 MiB [00:02,  4.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 59 MiB [00:02,  4.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 60 MiB [00:02,  4.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 61 MiB [00:02,  4.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 62 MiB [00:02,  4.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 63 MiB [00:02,  4.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 64 MiB [00:02,  4.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 65 MiB [00:02,  4.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 66 MiB [00:02,  4.77 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 67 MiB [00:02,  6.69 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 68 MiB [00:02,  6.69 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 69 MiB [00:02,  6.69 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 70 MiB [00:02,  6.69 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 71 MiB [00:02,  6.69 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 72 MiB [00:02,  6.69 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 73 MiB [00:02,  6.69 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 74 MiB [00:02,  6.69 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 75 MiB [00:02,  6.69 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 76 MiB [00:02,  9.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 77 MiB [00:02,  9.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 78 MiB [00:02,  9.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 79 MiB [00:02,  9.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 80 MiB [00:02,  9.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 81 MiB [00:02,  9.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 82 MiB [00:02,  9.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 83 MiB [00:02,  9.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 84 MiB [00:02,  9.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 85 MiB [00:02,  9.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 86 MiB [00:02,  9.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:02<?, ? url/s]\n    Dl Size...: 87 MiB [00:02,  9.20 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 88 MiB [00:03, 11.14 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 89 MiB [00:03, 11.14 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 90 MiB [00:03, 11.14 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 91 MiB [00:03, 11.14 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 92 MiB [00:03, 11.14 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 93 MiB [00:03, 11.14 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 94 MiB [00:03, 11.14 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 95 MiB [00:03, 11.14 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 96 MiB [00:03, 11.93 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 97 MiB [00:03, 11.93 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 98 MiB [00:03, 11.93 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:03<?, ? url/s]\n    Dl Size...: 99 MiB [00:03, 11.93 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 100 MiB [00:04, 11.93 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 101 MiB [00:04, 11.93 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 102 MiB [00:04, 11.93 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 103 MiB [00:04, 11.93 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 104 MiB [00:04, 11.93 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 105 MiB [00:04, 11.93 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 106 MiB [00:04, 11.93 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 107 MiB [00:04, 16.25 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 108 MiB [00:04, 16.25 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 109 MiB [00:04, 16.25 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 110 MiB [00:04, 16.25 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 111 MiB [00:04, 16.25 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 112 MiB [00:04, 16.25 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 113 MiB [00:04, 16.25 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 114 MiB [00:04, 16.25 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 115 MiB [00:04, 16.25 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 116 MiB [00:04, 16.25 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 117 MiB [00:04, 16.25 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 118 MiB [00:04, 21.81 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 119 MiB [00:04, 21.81 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 120 MiB [00:04, 21.81 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 121 MiB [00:04, 21.81 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 122 MiB [00:04, 21.81 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 123 MiB [00:04, 21.81 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 124 MiB [00:04, 21.81 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 125 MiB [00:04, 21.81 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 126 MiB [00:04, 27.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 127 MiB [00:04, 27.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 128 MiB [00:04, 27.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 129 MiB [00:04, 27.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 130 MiB [00:04, 27.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 131 MiB [00:04, 27.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 132 MiB [00:04, 27.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 133 MiB [00:04, 27.68 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 134 MiB [00:04, 31.41 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 135 MiB [00:04, 31.41 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 136 MiB [00:04, 31.41 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 137 MiB [00:04, 31.41 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 138 MiB [00:04, 31.41 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 139 MiB [00:04, 31.41 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 140 MiB [00:04, 31.41 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 141 MiB [00:04, 31.41 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 142 MiB [00:04, 31.41 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 143 MiB [00:04, 31.41 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 144 MiB [00:04, 31.41 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 145 MiB [00:04, 39.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 146 MiB [00:04, 39.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 147 MiB [00:04, 39.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 148 MiB [00:04, 39.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 149 MiB [00:04, 39.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 150 MiB [00:04, 39.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 151 MiB [00:04, 39.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 152 MiB [00:04, 39.50 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 153 MiB [00:04, 39.87 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 154 MiB [00:04, 39.87 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 155 MiB [00:04, 39.87 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 156 MiB [00:04, 39.87 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 157 MiB [00:04, 39.87 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 158 MiB [00:04, 39.87 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 159 MiB [00:04, 39.87 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 160 MiB [00:04, 39.87 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 161 MiB [00:04, 39.87 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 162 MiB [00:04, 39.87 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 163 MiB [00:04, 47.90 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 164 MiB [00:04, 47.90 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 165 MiB [00:04, 47.90 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 166 MiB [00:04, 47.90 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 167 MiB [00:04, 47.90 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 168 MiB [00:04, 47.90 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 169 MiB [00:04, 47.90 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 170 MiB [00:04, 47.90 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 171 MiB [00:04, 47.90 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 172 MiB [00:04, 47.90 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 173 MiB [00:04, 47.90 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 174 MiB [00:04, 47.90 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 175 MiB [00:04, 58.18 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:04<?, ? url/s]\n    Dl Size...: 176 MiB [00:04, 58.18 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 177 MiB [00:05, 58.18 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 178 MiB [00:05, 58.18 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 179 MiB [00:05, 58.18 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 180 MiB [00:05, 58.18 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 181 MiB [00:05, 58.18 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 182 MiB [00:05, 58.18 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 183 MiB [00:05, 58.18 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:05, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 184 MiB [00:05, 45.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 185 MiB [00:05, 45.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 186 MiB [00:05, 45.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 187 MiB [00:05, 45.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 188 MiB [00:05, 45.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 189 MiB [00:05, 45.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 190 MiB [00:05, 45.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 191 MiB [00:05, 45.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 192 MiB [00:05, 45.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 193 MiB [00:05, 45.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 194 MiB [00:05, 45.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 195 MiB [00:05, 45.10 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:05, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 196 MiB [00:05, 54.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 197 MiB [00:05, 54.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 198 MiB [00:05, 54.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 199 MiB [00:05, 54.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 200 MiB [00:05, 54.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 201 MiB [00:05, 54.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 202 MiB [00:05, 54.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 203 MiB [00:05, 54.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 204 MiB [00:05, 54.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 205 MiB [00:05, 54.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 206 MiB [00:05, 54.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 207 MiB [00:05, 54.96 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:05, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 208 MiB [00:05, 51.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 209 MiB [00:05, 51.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 210 MiB [00:05, 51.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 211 MiB [00:05, 51.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 212 MiB [00:05, 51.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 213 MiB [00:05, 51.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 214 MiB [00:05, 51.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 215 MiB [00:05, 51.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 216 MiB [00:05, 51.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 217 MiB [00:05, 51.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 218 MiB [00:05, 51.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 219 MiB [00:05, 51.88 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:05, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 220 MiB [00:05, 61.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 221 MiB [00:05, 61.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 222 MiB [00:05, 61.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 223 MiB [00:05, 61.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 224 MiB [00:05, 61.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 225 MiB [00:05, 61.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 226 MiB [00:05, 61.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 227 MiB [00:05, 61.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 228 MiB [00:05, 61.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 229 MiB [00:05, 61.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 230 MiB [00:05, 61.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 231 MiB [00:05, 61.86 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:05, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 232 MiB [00:05, 72.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 233 MiB [00:05, 72.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 234 MiB [00:05, 72.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 235 MiB [00:05, 72.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 236 MiB [00:05, 72.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 237 MiB [00:05, 72.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 238 MiB [00:05, 72.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:05<?, ? url/s]\n    Dl Size...: 239 MiB [00:05, 72.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 240 MiB [00:06, 72.20 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 241 MiB [00:06, 72.20 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:06, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 242 MiB [00:06, 24.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 243 MiB [00:06, 24.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 244 MiB [00:06, 24.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 245 MiB [00:06, 24.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 246 MiB [00:06, 24.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 247 MiB [00:06, 24.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 248 MiB [00:06, 24.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 249 MiB [00:06, 24.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 250 MiB [00:06, 24.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 251 MiB [00:06, 24.83 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 252 MiB [00:06, 24.83 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:06, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 253 MiB [00:06, 32.31 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 254 MiB [00:06, 32.31 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 255 MiB [00:06, 32.31 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:06<?, ? url/s]\n    Dl Size...: 256 MiB [00:06, 32.31 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 257 MiB [00:07, 32.31 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 258 MiB [00:07, 32.31 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 259 MiB [00:07, 32.31 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 260 MiB [00:07, 32.31 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 261 MiB [00:07, 32.31 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 262 MiB [00:07, 32.31 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 263 MiB [00:07, 32.31 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 264 MiB [00:07, 32.31 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:07, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 265 MiB [00:07, 41.21 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 266 MiB [00:07, 41.21 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 267 MiB [00:07, 41.21 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 268 MiB [00:07, 41.21 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 269 MiB [00:07, 41.21 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 270 MiB [00:07, 41.21 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 271 MiB [00:07, 41.21 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 272 MiB [00:07, 41.21 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 273 MiB [00:07, 41.21 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 274 MiB [00:07, 41.21 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:07, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 275 MiB [00:07, 34.30 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 276 MiB [00:07, 34.30 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 277 MiB [00:07, 34.30 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 278 MiB [00:07, 34.30 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 279 MiB [00:07, 34.30 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 280 MiB [00:07, 34.30 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 281 MiB [00:07, 34.30 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 282 MiB [00:07, 34.30 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 283 MiB [00:07, 34.30 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 284 MiB [00:07, 34.30 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 285 MiB [00:07, 34.30 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 286 MiB [00:07, 34.30 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:07, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:07<?, ? url/s]\n    Dl Size...: 287 MiB [00:07, 43.62 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 288 MiB [00:08, 43.62 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 289 MiB [00:08, 43.62 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 290 MiB [00:08, 43.62 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 291 MiB [00:08, 43.62 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 292 MiB [00:08, 43.62 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 293 MiB [00:08, 43.62 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 294 MiB [00:08, 43.62 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 295 MiB [00:08, 43.62 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:08, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 296 MiB [00:08, 21.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 297 MiB [00:08, 21.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 298 MiB [00:08, 21.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 299 MiB [00:08, 21.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 300 MiB [00:08, 21.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 301 MiB [00:08, 21.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 302 MiB [00:08, 21.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 303 MiB [00:08, 21.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 304 MiB [00:08, 21.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 305 MiB [00:08, 21.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 306 MiB [00:08, 21.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 307 MiB [00:08, 21.77 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 308 MiB [00:08, 21.77 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:08, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 309 MiB [00:08, 28.87 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 310 MiB [00:08, 28.87 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 311 MiB [00:08, 28.87 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 312 MiB [00:08, 28.87 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 313 MiB [00:08, 28.87 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 314 MiB [00:08, 28.87 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 315 MiB [00:08, 28.87 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 316 MiB [00:08, 28.87 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 317 MiB [00:08, 28.87 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 318 MiB [00:08, 28.87 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 319 MiB [00:08, 28.87 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:08, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 320 MiB [00:08, 30.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 321 MiB [00:08, 30.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 322 MiB [00:08, 30.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 323 MiB [00:08, 30.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 324 MiB [00:08, 30.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 325 MiB [00:08, 30.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 326 MiB [00:08, 30.86 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:08<?, ? url/s]\n    Dl Size...: 327 MiB [00:08, 30.86 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:08, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 328 MiB [00:09, 34.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 329 MiB [00:09, 34.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 330 MiB [00:09, 34.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 331 MiB [00:09, 34.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 332 MiB [00:09, 34.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 333 MiB [00:09, 34.32 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 334 MiB [00:09, 34.32 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:09, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 335 MiB [00:09, 38.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 336 MiB [00:09, 38.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 337 MiB [00:09, 38.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 338 MiB [00:09, 38.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 339 MiB [00:09, 38.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 340 MiB [00:09, 38.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 341 MiB [00:09, 38.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 342 MiB [00:09, 38.10 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 343 MiB [00:09, 38.10 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:09, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 344 MiB [00:09, 45.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 345 MiB [00:09, 45.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 346 MiB [00:09, 45.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 347 MiB [00:09, 45.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 348 MiB [00:09, 45.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 349 MiB [00:09, 45.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 350 MiB [00:09, 45.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 351 MiB [00:09, 45.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 352 MiB [00:09, 45.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 353 MiB [00:09, 45.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 354 MiB [00:09, 45.88 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:09, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 355 MiB [00:09, 55.15 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 356 MiB [00:09, 55.15 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 357 MiB [00:09, 55.15 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 358 MiB [00:09, 55.15 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 359 MiB [00:09, 55.15 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 360 MiB [00:09, 55.15 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 361 MiB [00:09, 55.15 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 362 MiB [00:09, 55.15 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:09, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 363 MiB [00:09, 59.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 364 MiB [00:09, 59.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 365 MiB [00:09, 59.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 366 MiB [00:09, 59.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 367 MiB [00:09, 59.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 368 MiB [00:09, 59.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 369 MiB [00:09, 59.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 370 MiB [00:09, 59.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 371 MiB [00:09, 59.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 372 MiB [00:09, 59.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 373 MiB [00:09, 59.96 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 374 MiB [00:09, 59.96 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:09, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:09<?, ? url/s]\n    Dl Size...: 375 MiB [00:09, 69.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 376 MiB [00:10, 69.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 377 MiB [00:10, 69.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 378 MiB [00:10, 69.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 379 MiB [00:10, 69.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 380 MiB [00:10, 69.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 381 MiB [00:10, 69.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 382 MiB [00:10, 69.88 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 383 MiB [00:10, 69.88 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:10, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 384 MiB [00:10, 36.79 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 385 MiB [00:10, 36.79 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 386 MiB [00:10, 36.79 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 387 MiB [00:10, 36.79 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 388 MiB [00:10, 36.79 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 389 MiB [00:10, 36.79 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 390 MiB [00:10, 36.79 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 391 MiB [00:10, 36.79 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:10, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 392 MiB [00:10, 26.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 393 MiB [00:10, 26.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 394 MiB [00:10, 26.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 395 MiB [00:10, 26.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 396 MiB [00:10, 26.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 397 MiB [00:10, 26.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 398 MiB [00:10, 26.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 399 MiB [00:10, 26.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 400 MiB [00:10, 26.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 401 MiB [00:10, 26.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 402 MiB [00:10, 26.40 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:10, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 403 MiB [00:10, 34.07 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 404 MiB [00:10, 34.07 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 405 MiB [00:10, 34.07 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 406 MiB [00:10, 34.07 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 407 MiB [00:10, 34.07 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 408 MiB [00:10, 34.07 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 409 MiB [00:10, 34.07 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 410 MiB [00:10, 34.07 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 411 MiB [00:10, 34.07 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 412 MiB [00:10, 34.07 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 413 MiB [00:10, 34.07 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 414 MiB [00:10, 34.07 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 415 MiB [00:10, 34.07 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:10, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 416 MiB [00:10, 43.42 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 417 MiB [00:10, 43.42 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 418 MiB [00:10, 43.42 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 419 MiB [00:10, 43.42 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 420 MiB [00:10, 43.42 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 421 MiB [00:10, 43.42 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 422 MiB [00:10, 43.42 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:10<?, ? url/s]\n    Dl Size...: 423 MiB [00:10, 43.42 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 424 MiB [00:11, 43.42 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:11, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 425 MiB [00:11, 39.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 426 MiB [00:11, 39.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 427 MiB [00:11, 39.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 428 MiB [00:11, 39.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 429 MiB [00:11, 39.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 430 MiB [00:11, 39.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 431 MiB [00:11, 39.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 432 MiB [00:11, 39.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 433 MiB [00:11, 39.12 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 434 MiB [00:11, 39.12 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:11, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 435 MiB [00:11, 47.58 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 436 MiB [00:11, 47.58 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 437 MiB [00:11, 47.58 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 438 MiB [00:11, 47.58 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 439 MiB [00:11, 47.58 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 440 MiB [00:11, 47.58 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 441 MiB [00:11, 47.58 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 442 MiB [00:11, 47.58 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 443 MiB [00:11, 47.58 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 444 MiB [00:11, 47.58 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 445 MiB [00:11, 47.58 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:11, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 446 MiB [00:11, 57.09 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 447 MiB [00:11, 57.09 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 448 MiB [00:11, 57.09 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 449 MiB [00:11, 57.09 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 450 MiB [00:11, 57.09 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 451 MiB [00:11, 57.09 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 452 MiB [00:11, 57.09 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 453 MiB [00:11, 57.09 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 454 MiB [00:11, 57.09 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 455 MiB [00:11, 57.09 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:11, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 456 MiB [00:11, 40.70 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 457 MiB [00:11, 40.70 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 458 MiB [00:11, 40.70 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 459 MiB [00:11, 40.70 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 460 MiB [00:11, 40.70 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 461 MiB [00:11, 40.70 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 462 MiB [00:11, 40.70 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 463 MiB [00:11, 40.70 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:11, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 464 MiB [00:11, 47.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 465 MiB [00:11, 47.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 466 MiB [00:11, 47.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 467 MiB [00:11, 47.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 468 MiB [00:11, 47.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 469 MiB [00:11, 47.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 470 MiB [00:11, 47.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 471 MiB [00:11, 47.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 472 MiB [00:11, 47.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 473 MiB [00:11, 47.40 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 474 MiB [00:11, 47.40 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:11, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 475 MiB [00:11, 57.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 476 MiB [00:11, 57.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 477 MiB [00:11, 57.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 478 MiB [00:11, 57.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 479 MiB [00:11, 57.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:11<?, ? url/s]\n    Dl Size...: 480 MiB [00:11, 57.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 481 MiB [00:12, 57.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 482 MiB [00:12, 57.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 483 MiB [00:12, 57.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 484 MiB [00:12, 57.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 485 MiB [00:12, 57.06 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 486 MiB [00:12, 57.06 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:12, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 487 MiB [00:12, 66.42 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 488 MiB [00:12, 66.42 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 489 MiB [00:12, 66.42 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 490 MiB [00:12, 66.42 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 491 MiB [00:12, 66.42 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 492 MiB [00:12, 66.42 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 493 MiB [00:12, 66.42 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 494 MiB [00:12, 66.42 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 495 MiB [00:12, 66.42 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:12, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 496 MiB [00:12, 67.27 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 497 MiB [00:12, 67.27 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 498 MiB [00:12, 67.27 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 499 MiB [00:12, 67.27 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 500 MiB [00:12, 67.27 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 501 MiB [00:12, 67.27 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 502 MiB [00:12, 67.27 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 503 MiB [00:12, 67.27 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 504 MiB [00:12, 67.27 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:12, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 505 MiB [00:12, 68.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 506 MiB [00:12, 68.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 507 MiB [00:12, 68.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 508 MiB [00:12, 68.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 509 MiB [00:12, 68.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 510 MiB [00:12, 68.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 511 MiB [00:12, 68.50 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 512 MiB [00:12, 68.50 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:12, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 513 MiB [00:12, 54.76 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 514 MiB [00:12, 54.76 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 515 MiB [00:12, 54.76 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 516 MiB [00:12, 54.76 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 517 MiB [00:12, 54.76 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 518 MiB [00:12, 54.76 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 519 MiB [00:12, 54.76 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:12, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 520 MiB [00:12, 44.02 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 521 MiB [00:12, 44.02 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 522 MiB [00:12, 44.02 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 523 MiB [00:12, 44.02 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 524 MiB [00:12, 44.02 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 525 MiB [00:12, 44.02 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 526 MiB [00:12, 44.02 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 527 MiB [00:12, 44.02 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 528 MiB [00:12, 44.02 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 529 MiB [00:12, 44.02 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 530 MiB [00:12, 44.02 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:12, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 531 MiB [00:12, 53.61 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 532 MiB [00:12, 53.61 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 533 MiB [00:12, 53.61 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 534 MiB [00:12, 53.61 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 535 MiB [00:12, 53.61 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 536 MiB [00:12, 53.61 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 537 MiB [00:12, 53.61 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 538 MiB [00:12, 53.61 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 539 MiB [00:12, 53.61 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 540 MiB [00:12, 53.61 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 541 MiB [00:12, 53.61 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 542 MiB [00:12, 53.61 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:12<?, ? url/s]\n    Dl Size...: 543 MiB [00:12, 53.61 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:12, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 544 MiB [00:13, 42.91 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 545 MiB [00:13, 42.91 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 546 MiB [00:13, 42.91 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 547 MiB [00:13, 42.91 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 548 MiB [00:13, 42.91 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 549 MiB [00:13, 42.91 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 550 MiB [00:13, 42.91 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 551 MiB [00:13, 42.91 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 552 MiB [00:13, 42.91 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:13, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 553 MiB [00:13, 50.81 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 554 MiB [00:13, 50.81 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 555 MiB [00:13, 50.81 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 556 MiB [00:13, 50.81 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 557 MiB [00:13, 50.81 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 558 MiB [00:13, 50.81 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 559 MiB [00:13, 50.81 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 560 MiB [00:13, 50.81 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 561 MiB [00:13, 50.81 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 562 MiB [00:13, 50.81 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 563 MiB [00:13, 50.81 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:13, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 564 MiB [00:13, 60.56 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 565 MiB [00:13, 60.56 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 566 MiB [00:13, 60.56 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 567 MiB [00:13, 60.56 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 568 MiB [00:13, 60.56 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 569 MiB [00:13, 60.56 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 570 MiB [00:13, 60.56 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 571 MiB [00:13, 60.56 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 572 MiB [00:13, 60.56 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 573 MiB [00:13, 60.56 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 574 MiB [00:13, 60.56 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 575 MiB [00:13, 60.56 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:13, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 576 MiB [00:13, 61.04 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 577 MiB [00:13, 61.04 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 578 MiB [00:13, 61.04 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 579 MiB [00:13, 61.04 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 580 MiB [00:13, 61.04 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 581 MiB [00:13, 61.04 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 582 MiB [00:13, 61.04 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 583 MiB [00:13, 61.04 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:13, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 584 MiB [00:13, 63.00 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 585 MiB [00:13, 63.00 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 586 MiB [00:13, 63.00 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 587 MiB [00:13, 63.00 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 588 MiB [00:13, 63.00 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 589 MiB [00:13, 63.00 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 590 MiB [00:13, 63.00 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 591 MiB [00:13, 63.00 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:13, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 592 MiB [00:13, 65.89 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 593 MiB [00:13, 65.89 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 594 MiB [00:13, 65.89 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 595 MiB [00:13, 65.89 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 596 MiB [00:13, 65.89 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 597 MiB [00:13, 65.89 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:13<?, ? url/s]\n    Dl Size...: 598 MiB [00:13, 65.89 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 599 MiB [00:14, 65.89 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 600 MiB [00:14, 65.89 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 601 MiB [00:14, 65.89 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:14, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 602 MiB [00:14, 72.19 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 603 MiB [00:14, 72.19 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 604 MiB [00:14, 72.19 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 605 MiB [00:14, 72.19 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 606 MiB [00:14, 72.19 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 607 MiB [00:14, 72.19 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 608 MiB [00:14, 72.19 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 609 MiB [00:14, 72.19 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 610 MiB [00:14, 72.19 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 611 MiB [00:14, 72.19 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 612 MiB [00:14, 72.19 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:14, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 613 MiB [00:14, 80.44 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 614 MiB [00:14, 80.44 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 615 MiB [00:14, 80.44 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 616 MiB [00:14, 80.44 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 617 MiB [00:14, 80.44 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 618 MiB [00:14, 80.44 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 619 MiB [00:14, 80.44 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 620 MiB [00:14, 80.44 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 621 MiB [00:14, 80.44 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:14, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 622 MiB [00:14, 81.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:14<?, ? url/s]\n    Dl Size...: 623 MiB [00:14, 81.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:15<?, ? url/s]\n    Dl Size...: 624 MiB [00:15, 81.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:15<?, ? url/s]\n    Dl Size...: 625 MiB [00:15, 81.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:15<?, ? url/s]\n    Dl Size...: 626 MiB [00:15, 81.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:15<?, ? url/s]\n    Dl Size...: 627 MiB [00:15, 81.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:15<?, ? url/s]\n    Dl Size...: 628 MiB [00:15, 81.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:15<?, ? url/s]\n    Dl Size...: 629 MiB [00:15, 81.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:15<?, ? url/s]\n    Dl Size...: 630 MiB [00:15, 81.68 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:15, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/1 [00:15<?, ? url/s]\n    Dl Size...: 631 MiB [00:15, 23.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:15<?, ? url/s]\n    Dl Size...: 632 MiB [00:15, 23.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:15<?, ? url/s]\n    Dl Size...: 633 MiB [00:15, 23.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:15<?, ? url/s]\n    Dl Size...: 634 MiB [00:15, 23.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:15<?, ? url/s]\n    Dl Size...: 635 MiB [00:15, 23.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:15<?, ? url/s]\n    Dl Size...: 636 MiB [00:15, 23.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:15<?, ? url/s]\n    Dl Size...: 637 MiB [00:15, 23.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:15<?, ? url/s]\n    Dl Size...: 638 MiB [00:15, 23.68 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/1 [00:15<?, ? url/s]\n    Dl Size...: 639 MiB [00:15, 23.68 MiB/s]\u001b[A\n    \n    Dl Completed...: 100% 1/1 [00:15<00:00, 15.33s/ url]\n    Dl Size...: 639 MiB [00:15, 23.68 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:15, ? file/s]\u001b[A\u001b[AI0830 22:35:40.121278 140447463077632 download_manager.py:497] Skipping extraction for /root/tensorflow_datasets/downloads/ucexport_download_id_1ffWfITKFMJeqjT8loC8a_XnFKBkIaeZ0glhNGWombXK7QgN8uq9nDHA-eFtk8ZIIqCA (method=NO_EXTRACT).\n    \n    Extraction completed...: 0 file [00:15, ? file/s]\n    \n    Dl Size...: 639 MiB [00:15, 41.68 MiB/s]\n    \n    Dl Completed...: 100% 1/1 [00:15<00:00, 15.33s/ url]\n    I0830 22:35:40.122343 140449568884608 dataset_builder.py:953] Generating split train\n    Shuffling and writing examples to /root/tensorflow_datasets/reddit_tifu/long/1.1.0.incompleteYM1FSJ/reddit_tifu-train.tfrecord\n     85% 35874/42139 [00:00<00:00, 106144.43 examples/s]I0830 22:36:12.711124 140449568884608 tfrecords_writer.py:226] Done writing /root/tensorflow_datasets/reddit_tifu/long/1.1.0.incompleteYM1FSJ/reddit_tifu-train.tfrecord. Shard lengths: [42139]\n    I0830 22:36:12.736144 140449568884608 dataset_builder.py:404] Skipping computing stats for mode ComputeStatsMode.AUTO.\n    \u001b[1mDataset reddit_tifu downloaded and prepared to /root/tensorflow_datasets/reddit_tifu/long/1.1.0. Subsequent calls will reuse this data.\u001b[0m\n    I0830 22:36:12.738217 140449568884608 dataset_builder.py:503] Constructing tf.data.Dataset for split train[:80%], from /root/tensorflow_datasets/reddit_tifu/long/1.1.0\n    I0830 22:36:13.147881 140449568884608 datasets.py:215] Number of examples for config reddit_tifu/long train is 33711\n    2020-08-30 22:36:13.925087: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1\n    2020-08-30 22:36:13.930798: E tensorflow/stream_executor/cuda/cuda_driver.cc:318] failed call to cuInit: CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected\n    2020-08-30 22:36:13.930852: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (d85487f9bac6): /proc/driver/nvidia/version does not exist\n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/ragged/ragged_tensor.py:1586: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use tf.where in 2.0, which has the same broadcast rule as np.where\n    W0830 22:36:13.981532 140449568884608 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/ragged/ragged_tensor.py:1586: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use tf.where in 2.0, which has the same broadcast rule as np.where\n    INFO:tensorflow:Calling model_fn.\n    I0830 22:36:14.436142 140449568884608 estimator.py:1148] Calling model_fn.\n    INFO:tensorflow:Running train on CPU\n    I0830 22:36:14.436476 140449568884608 tpu_estimator.py:3124] Running train on CPU\n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:78: The name tf.get_variable_scope is deprecated. Please use tf.compat.v1.get_variable_scope instead.\n    \n    W0830 22:36:14.436946 140449568884608 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:78: The name tf.get_variable_scope is deprecated. Please use tf.compat.v1.get_variable_scope instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/attention.py:41: The name tf.layers.Dense is deprecated. Please use tf.compat.v1.layers.Dense instead.\n    \n    W0830 22:36:14.437396 140449568884608 module_wrapper.py:139] From /content/pegasus/pegasus/layers/attention.py:41: The name tf.layers.Dense is deprecated. Please use tf.compat.v1.layers.Dense instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/embedding.py:57: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n    \n    W0830 22:36:14.488304 140449568884608 module_wrapper.py:139] From /content/pegasus/pegasus/layers/embedding.py:57: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/embedding.py:57: The name tf.AUTO_REUSE is deprecated. Please use tf.compat.v1.AUTO_REUSE instead.\n    \n    W0830 22:36:14.488626 140449568884608 module_wrapper.py:139] From /content/pegasus/pegasus/layers/embedding.py:57: The name tf.AUTO_REUSE is deprecated. Please use tf.compat.v1.AUTO_REUSE instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/embedding.py:61: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n    \n    W0830 22:36:14.488935 140449568884608 module_wrapper.py:139] From /content/pegasus/pegasus/layers/embedding.py:61: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/embedding.py:64: calling RandomNormal.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Call initializer instance with the dtype argument instead of passing it to the constructor\n    W0830 22:36:14.489209 140449568884608 deprecation.py:506] From /content/pegasus/pegasus/layers/embedding.py:64: calling RandomNormal.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Call initializer instance with the dtype argument instead of passing it to the constructor\n    WARNING:tensorflow:From /content/pegasus/pegasus/layers/attention.py:106: The name tf.matrix_band_part is deprecated. Please use tf.linalg.band_part instead.\n    \n    W0830 22:36:17.479444 140449568884608 module_wrapper.py:139] From /content/pegasus/pegasus/layers/attention.py:106: The name tf.matrix_band_part is deprecated. Please use tf.linalg.band_part instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/models/transformer.py:108: The name tf.losses.softmax_cross_entropy is deprecated. Please use tf.compat.v1.losses.softmax_cross_entropy instead.\n    \n    W0830 22:36:22.510975 140449568884608 module_wrapper.py:139] From /content/pegasus/pegasus/models/transformer.py:108: The name tf.losses.softmax_cross_entropy is deprecated. Please use tf.compat.v1.losses.softmax_cross_entropy instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:113: The name tf.train.get_global_step is deprecated. Please use tf.compat.v1.train.get_global_step instead.\n    \n    W0830 22:36:22.551383 140449568884608 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:113: The name tf.train.get_global_step is deprecated. Please use tf.compat.v1.train.get_global_step instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:114: The name tf.rsqrt is deprecated. Please use tf.math.rsqrt instead.\n    \n    W0830 22:36:22.551763 140449568884608 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:114: The name tf.rsqrt is deprecated. Please use tf.math.rsqrt instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:115: to_float (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    W0830 22:36:22.551957 140449568884608 deprecation.py:323] From /content/pegasus/pegasus/params/estimator_utils.py:115: to_float (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    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/adafactor.py:315: The name tf.train.get_or_create_global_step is deprecated. Please use tf.compat.v1.train.get_or_create_global_step instead.\n    \n    W0830 22:36:22.560439 140449568884608 module_wrapper.py:139] From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/adafactor.py:315: The name tf.train.get_or_create_global_step is deprecated. Please use tf.compat.v1.train.get_or_create_global_step instead.\n    \n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/quantization.py:147: 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    W0830 22:36:22.564935 140449568884608 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/quantization.py:147: 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    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/quantization.py:156: The name tf.mod is deprecated. Please use tf.math.mod instead.\n    \n    W0830 22:36:22.567391 140449568884608 module_wrapper.py:139] From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/quantization.py:156: The name tf.mod is deprecated. Please use tf.math.mod instead.\n    \n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/adafactor.py:244: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead.\n    \n    W0830 22:36:37.115567 140449568884608 module_wrapper.py:139] From /usr/local/lib/python3.6/dist-packages/tensor2tensor/utils/adafactor.py:244: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:189: The name tf.trainable_variables is deprecated. Please use tf.compat.v1.trainable_variables instead.\n    \n    W0830 22:36:52.059795 140449568884608 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:189: The name tf.trainable_variables is deprecated. Please use tf.compat.v1.trainable_variables instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:205: The name tf.train.init_from_checkpoint is deprecated. Please use tf.compat.v1.train.init_from_checkpoint instead.\n    \n    W0830 22:36:52.071296 140449568884608 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:205: The name tf.train.init_from_checkpoint is deprecated. Please use tf.compat.v1.train.init_from_checkpoint instead.\n    \n    I0830 22:36:53.526131 140449568884608 estimator_utils.py:207] **** Trainable Variables ****\n    I0830 22:36:53.526358 140449568884608 estimator_utils.py:212]   name = embeddings/weights:0, shape = (96103, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.526491 140449568884608 estimator_utils.py:212]   name = encoder/layer_0/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.526600 140449568884608 estimator_utils.py:212]   name = encoder/layer_0/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.526700 140449568884608 estimator_utils.py:212]   name = encoder/layer_0/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.526790 140449568884608 estimator_utils.py:212]   name = encoder/layer_0/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.526877 140449568884608 estimator_utils.py:212]   name = encoder/layer_0/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.526964 140449568884608 estimator_utils.py:212]   name = encoder/layer_0/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.527050 140449568884608 estimator_utils.py:212]   name = encoder/layer_0/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.527132 140449568884608 estimator_utils.py:212]   name = encoder/layer_0/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.527213 140449568884608 estimator_utils.py:212]   name = encoder/layer_0/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.527296 140449568884608 estimator_utils.py:212]   name = encoder/layer_0/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.527376 140449568884608 estimator_utils.py:212]   name = encoder/layer_0/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.527459 140449568884608 estimator_utils.py:212]   name = encoder/layer_0/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.527539 140449568884608 estimator_utils.py:212]   name = encoder/layer_1/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.527638 140449568884608 estimator_utils.py:212]   name = encoder/layer_1/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.527722 140449568884608 estimator_utils.py:212]   name = encoder/layer_1/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.527807 140449568884608 estimator_utils.py:212]   name = encoder/layer_1/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.527891 140449568884608 estimator_utils.py:212]   name = encoder/layer_1/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.527975 140449568884608 estimator_utils.py:212]   name = encoder/layer_1/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.528058 140449568884608 estimator_utils.py:212]   name = encoder/layer_1/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.528138 140449568884608 estimator_utils.py:212]   name = encoder/layer_1/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.528221 140449568884608 estimator_utils.py:212]   name = encoder/layer_1/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.528300 140449568884608 estimator_utils.py:212]   name = encoder/layer_1/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.528382 140449568884608 estimator_utils.py:212]   name = encoder/layer_1/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.528463 140449568884608 estimator_utils.py:212]   name = encoder/layer_1/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.528543 140449568884608 estimator_utils.py:212]   name = encoder/layer_2/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.528644 140449568884608 estimator_utils.py:212]   name = encoder/layer_2/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.528726 140449568884608 estimator_utils.py:212]   name = encoder/layer_2/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.528808 140449568884608 estimator_utils.py:212]   name = encoder/layer_2/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.528890 140449568884608 estimator_utils.py:212]   name = encoder/layer_2/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.528977 140449568884608 estimator_utils.py:212]   name = encoder/layer_2/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.529059 140449568884608 estimator_utils.py:212]   name = encoder/layer_2/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.529143 140449568884608 estimator_utils.py:212]   name = encoder/layer_2/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.529223 140449568884608 estimator_utils.py:212]   name = encoder/layer_2/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.529305 140449568884608 estimator_utils.py:212]   name = encoder/layer_2/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.529386 140449568884608 estimator_utils.py:212]   name = encoder/layer_2/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.529469 140449568884608 estimator_utils.py:212]   name = encoder/layer_2/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.529551 140449568884608 estimator_utils.py:212]   name = encoder/layer_3/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.529652 140449568884608 estimator_utils.py:212]   name = encoder/layer_3/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.529734 140449568884608 estimator_utils.py:212]   name = encoder/layer_3/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.529817 140449568884608 estimator_utils.py:212]   name = encoder/layer_3/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.529897 140449568884608 estimator_utils.py:212]   name = encoder/layer_3/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.529978 140449568884608 estimator_utils.py:212]   name = encoder/layer_3/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.530059 140449568884608 estimator_utils.py:212]   name = encoder/layer_3/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.530140 140449568884608 estimator_utils.py:212]   name = encoder/layer_3/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.530223 140449568884608 estimator_utils.py:212]   name = encoder/layer_3/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.530299 140449568884608 estimator_utils.py:212]   name = encoder/layer_3/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.530377 140449568884608 estimator_utils.py:212]   name = encoder/layer_3/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.530459 140449568884608 estimator_utils.py:212]   name = encoder/layer_3/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.530538 140449568884608 estimator_utils.py:212]   name = encoder/layer_4/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.530636 140449568884608 estimator_utils.py:212]   name = encoder/layer_4/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.530717 140449568884608 estimator_utils.py:212]   name = encoder/layer_4/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.530800 140449568884608 estimator_utils.py:212]   name = encoder/layer_4/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.530881 140449568884608 estimator_utils.py:212]   name = encoder/layer_4/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.530962 140449568884608 estimator_utils.py:212]   name = encoder/layer_4/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.531043 140449568884608 estimator_utils.py:212]   name = encoder/layer_4/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.531121 140449568884608 estimator_utils.py:212]   name = encoder/layer_4/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.531200 140449568884608 estimator_utils.py:212]   name = encoder/layer_4/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.531280 140449568884608 estimator_utils.py:212]   name = encoder/layer_4/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.531359 140449568884608 estimator_utils.py:212]   name = encoder/layer_4/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.531439 140449568884608 estimator_utils.py:212]   name = encoder/layer_4/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.531517 140449568884608 estimator_utils.py:212]   name = encoder/layer_5/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.531619 140449568884608 estimator_utils.py:212]   name = encoder/layer_5/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.531700 140449568884608 estimator_utils.py:212]   name = encoder/layer_5/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.531784 140449568884608 estimator_utils.py:212]   name = encoder/layer_5/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.531865 140449568884608 estimator_utils.py:212]   name = encoder/layer_5/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.531946 140449568884608 estimator_utils.py:212]   name = encoder/layer_5/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.532026 140449568884608 estimator_utils.py:212]   name = encoder/layer_5/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.532105 140449568884608 estimator_utils.py:212]   name = encoder/layer_5/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.532183 140449568884608 estimator_utils.py:212]   name = encoder/layer_5/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.532263 140449568884608 estimator_utils.py:212]   name = encoder/layer_5/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.532342 140449568884608 estimator_utils.py:212]   name = encoder/layer_5/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.532422 140449568884608 estimator_utils.py:212]   name = encoder/layer_5/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.532501 140449568884608 estimator_utils.py:212]   name = encoder/layer_6/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.532596 140449568884608 estimator_utils.py:212]   name = encoder/layer_6/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.532688 140449568884608 estimator_utils.py:212]   name = encoder/layer_6/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.532768 140449568884608 estimator_utils.py:212]   name = encoder/layer_6/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.532853 140449568884608 estimator_utils.py:212]   name = encoder/layer_6/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.532934 140449568884608 estimator_utils.py:212]   name = encoder/layer_6/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.533016 140449568884608 estimator_utils.py:212]   name = encoder/layer_6/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.533095 140449568884608 estimator_utils.py:212]   name = encoder/layer_6/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.533174 140449568884608 estimator_utils.py:212]   name = encoder/layer_6/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.533255 140449568884608 estimator_utils.py:212]   name = encoder/layer_6/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.533334 140449568884608 estimator_utils.py:212]   name = encoder/layer_6/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.533413 140449568884608 estimator_utils.py:212]   name = encoder/layer_6/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.533492 140449568884608 estimator_utils.py:212]   name = encoder/layer_7/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.533570 140449568884608 estimator_utils.py:212]   name = encoder/layer_7/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.533673 140449568884608 estimator_utils.py:212]   name = encoder/layer_7/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.533755 140449568884608 estimator_utils.py:212]   name = encoder/layer_7/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.533836 140449568884608 estimator_utils.py:212]   name = encoder/layer_7/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.533918 140449568884608 estimator_utils.py:212]   name = encoder/layer_7/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.533999 140449568884608 estimator_utils.py:212]   name = encoder/layer_7/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.534076 140449568884608 estimator_utils.py:212]   name = encoder/layer_7/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.534154 140449568884608 estimator_utils.py:212]   name = encoder/layer_7/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.534234 140449568884608 estimator_utils.py:212]   name = encoder/layer_7/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.534314 140449568884608 estimator_utils.py:212]   name = encoder/layer_7/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.534393 140449568884608 estimator_utils.py:212]   name = encoder/layer_7/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.534471 140449568884608 estimator_utils.py:212]   name = encoder/layer_8/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.534549 140449568884608 estimator_utils.py:212]   name = encoder/layer_8/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.534661 140449568884608 estimator_utils.py:212]   name = encoder/layer_8/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.534734 140449568884608 estimator_utils.py:212]   name = encoder/layer_8/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.534817 140449568884608 estimator_utils.py:212]   name = encoder/layer_8/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.534899 140449568884608 estimator_utils.py:212]   name = encoder/layer_8/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.534981 140449568884608 estimator_utils.py:212]   name = encoder/layer_8/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.535059 140449568884608 estimator_utils.py:212]   name = encoder/layer_8/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.535138 140449568884608 estimator_utils.py:212]   name = encoder/layer_8/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.535218 140449568884608 estimator_utils.py:212]   name = encoder/layer_8/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.535295 140449568884608 estimator_utils.py:212]   name = encoder/layer_8/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.535375 140449568884608 estimator_utils.py:212]   name = encoder/layer_8/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.535452 140449568884608 estimator_utils.py:212]   name = encoder/layer_9/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.535529 140449568884608 estimator_utils.py:212]   name = encoder/layer_9/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.535627 140449568884608 estimator_utils.py:212]   name = encoder/layer_9/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.535710 140449568884608 estimator_utils.py:212]   name = encoder/layer_9/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.535796 140449568884608 estimator_utils.py:212]   name = encoder/layer_9/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.535878 140449568884608 estimator_utils.py:212]   name = encoder/layer_9/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.535961 140449568884608 estimator_utils.py:212]   name = encoder/layer_9/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.536041 140449568884608 estimator_utils.py:212]   name = encoder/layer_9/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.536118 140449568884608 estimator_utils.py:212]   name = encoder/layer_9/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.536201 140449568884608 estimator_utils.py:212]   name = encoder/layer_9/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.536281 140449568884608 estimator_utils.py:212]   name = encoder/layer_9/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.555670 140449568884608 estimator_utils.py:212]   name = encoder/layer_9/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.555925 140449568884608 estimator_utils.py:212]   name = encoder/layer_10/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.556056 140449568884608 estimator_utils.py:212]   name = encoder/layer_10/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.556168 140449568884608 estimator_utils.py:212]   name = encoder/layer_10/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.556293 140449568884608 estimator_utils.py:212]   name = encoder/layer_10/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.556417 140449568884608 estimator_utils.py:212]   name = encoder/layer_10/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.556535 140449568884608 estimator_utils.py:212]   name = encoder/layer_10/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.556683 140449568884608 estimator_utils.py:212]   name = encoder/layer_10/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.556800 140449568884608 estimator_utils.py:212]   name = encoder/layer_10/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.556911 140449568884608 estimator_utils.py:212]   name = encoder/layer_10/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.557030 140449568884608 estimator_utils.py:212]   name = encoder/layer_10/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.557137 140449568884608 estimator_utils.py:212]   name = encoder/layer_10/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.557252 140449568884608 estimator_utils.py:212]   name = encoder/layer_10/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.557364 140449568884608 estimator_utils.py:212]   name = encoder/layer_11/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.557474 140449568884608 estimator_utils.py:212]   name = encoder/layer_11/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.557602 140449568884608 estimator_utils.py:212]   name = encoder/layer_11/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.557740 140449568884608 estimator_utils.py:212]   name = encoder/layer_11/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.557859 140449568884608 estimator_utils.py:212]   name = encoder/layer_11/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.557978 140449568884608 estimator_utils.py:212]   name = encoder/layer_11/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.558097 140449568884608 estimator_utils.py:212]   name = encoder/layer_11/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.558209 140449568884608 estimator_utils.py:212]   name = encoder/layer_11/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.558320 140449568884608 estimator_utils.py:212]   name = encoder/layer_11/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.558434 140449568884608 estimator_utils.py:212]   name = encoder/layer_11/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.558544 140449568884608 estimator_utils.py:212]   name = encoder/layer_11/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.558693 140449568884608 estimator_utils.py:212]   name = encoder/layer_11/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.558809 140449568884608 estimator_utils.py:212]   name = encoder/layer_12/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.558919 140449568884608 estimator_utils.py:212]   name = encoder/layer_12/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.559031 140449568884608 estimator_utils.py:212]   name = encoder/layer_12/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.559148 140449568884608 estimator_utils.py:212]   name = encoder/layer_12/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.559267 140449568884608 estimator_utils.py:212]   name = encoder/layer_12/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.559381 140449568884608 estimator_utils.py:212]   name = encoder/layer_12/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.559496 140449568884608 estimator_utils.py:212]   name = encoder/layer_12/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.559635 140449568884608 estimator_utils.py:212]   name = encoder/layer_12/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.559756 140449568884608 estimator_utils.py:212]   name = encoder/layer_12/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.559874 140449568884608 estimator_utils.py:212]   name = encoder/layer_12/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.559986 140449568884608 estimator_utils.py:212]   name = encoder/layer_12/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.560103 140449568884608 estimator_utils.py:212]   name = encoder/layer_12/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.560218 140449568884608 estimator_utils.py:212]   name = encoder/layer_13/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.560327 140449568884608 estimator_utils.py:212]   name = encoder/layer_13/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.560434 140449568884608 estimator_utils.py:212]   name = encoder/layer_13/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.560549 140449568884608 estimator_utils.py:212]   name = encoder/layer_13/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.560705 140449568884608 estimator_utils.py:212]   name = encoder/layer_13/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.560826 140449568884608 estimator_utils.py:212]   name = encoder/layer_13/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.560942 140449568884608 estimator_utils.py:212]   name = encoder/layer_13/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.561054 140449568884608 estimator_utils.py:212]   name = encoder/layer_13/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.561165 140449568884608 estimator_utils.py:212]   name = encoder/layer_13/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.561279 140449568884608 estimator_utils.py:212]   name = encoder/layer_13/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.561389 140449568884608 estimator_utils.py:212]   name = encoder/layer_13/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.561506 140449568884608 estimator_utils.py:212]   name = encoder/layer_13/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.561640 140449568884608 estimator_utils.py:212]   name = encoder/layer_14/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.561784 140449568884608 estimator_utils.py:212]   name = encoder/layer_14/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.561901 140449568884608 estimator_utils.py:212]   name = encoder/layer_14/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.562020 140449568884608 estimator_utils.py:212]   name = encoder/layer_14/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.562137 140449568884608 estimator_utils.py:212]   name = encoder/layer_14/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.562256 140449568884608 estimator_utils.py:212]   name = encoder/layer_14/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.562374 140449568884608 estimator_utils.py:212]   name = encoder/layer_14/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.562486 140449568884608 estimator_utils.py:212]   name = encoder/layer_14/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.562620 140449568884608 estimator_utils.py:212]   name = encoder/layer_14/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.562749 140449568884608 estimator_utils.py:212]   name = encoder/layer_14/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.562863 140449568884608 estimator_utils.py:212]   name = encoder/layer_14/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.562980 140449568884608 estimator_utils.py:212]   name = encoder/layer_14/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.563093 140449568884608 estimator_utils.py:212]   name = encoder/layer_15/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.563205 140449568884608 estimator_utils.py:212]   name = encoder/layer_15/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.563314 140449568884608 estimator_utils.py:212]   name = encoder/layer_15/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.563429 140449568884608 estimator_utils.py:212]   name = encoder/layer_15/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.563542 140449568884608 estimator_utils.py:212]   name = encoder/layer_15/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.563688 140449568884608 estimator_utils.py:212]   name = encoder/layer_15/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.563810 140449568884608 estimator_utils.py:212]   name = encoder/layer_15/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.563922 140449568884608 estimator_utils.py:212]   name = encoder/layer_15/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.564033 140449568884608 estimator_utils.py:212]   name = encoder/layer_15/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.564144 140449568884608 estimator_utils.py:212]   name = encoder/layer_15/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.564252 140449568884608 estimator_utils.py:212]   name = encoder/layer_15/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.564368 140449568884608 estimator_utils.py:212]   name = encoder/layer_15/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.564476 140449568884608 estimator_utils.py:212]   name = encoder/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.564600 140449568884608 estimator_utils.py:212]   name = encoder/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.564731 140449568884608 estimator_utils.py:212]   name = decoder/layer_0/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.564842 140449568884608 estimator_utils.py:212]   name = decoder/layer_0/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.564951 140449568884608 estimator_utils.py:212]   name = decoder/layer_0/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.565067 140449568884608 estimator_utils.py:212]   name = decoder/layer_0/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.565184 140449568884608 estimator_utils.py:212]   name = decoder/layer_0/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.565300 140449568884608 estimator_utils.py:212]   name = decoder/layer_0/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.565418 140449568884608 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.565528 140449568884608 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.565667 140449568884608 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.565786 140449568884608 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.565901 140449568884608 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.566016 140449568884608 estimator_utils.py:212]   name = decoder/layer_0/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.566132 140449568884608 estimator_utils.py:212]   name = decoder/layer_0/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.566244 140449568884608 estimator_utils.py:212]   name = decoder/layer_0/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.566353 140449568884608 estimator_utils.py:212]   name = decoder/layer_0/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.566468 140449568884608 estimator_utils.py:212]   name = decoder/layer_0/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.566594 140449568884608 estimator_utils.py:212]   name = decoder/layer_0/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.566727 140449568884608 estimator_utils.py:212]   name = decoder/layer_0/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.566839 140449568884608 estimator_utils.py:212]   name = decoder/layer_1/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.566950 140449568884608 estimator_utils.py:212]   name = decoder/layer_1/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.567058 140449568884608 estimator_utils.py:212]   name = decoder/layer_1/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.567173 140449568884608 estimator_utils.py:212]   name = decoder/layer_1/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.567283 140449568884608 estimator_utils.py:212]   name = decoder/layer_1/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.567396 140449568884608 estimator_utils.py:212]   name = decoder/layer_1/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.567512 140449568884608 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.567650 140449568884608 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.567768 140449568884608 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.567884 140449568884608 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.568001 140449568884608 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.568117 140449568884608 estimator_utils.py:212]   name = decoder/layer_1/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.568235 140449568884608 estimator_utils.py:212]   name = decoder/layer_1/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.568346 140449568884608 estimator_utils.py:212]   name = decoder/layer_1/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.568453 140449568884608 estimator_utils.py:212]   name = decoder/layer_1/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.568570 140449568884608 estimator_utils.py:212]   name = decoder/layer_1/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.568713 140449568884608 estimator_utils.py:212]   name = decoder/layer_1/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.568831 140449568884608 estimator_utils.py:212]   name = decoder/layer_1/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.568942 140449568884608 estimator_utils.py:212]   name = decoder/layer_2/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.569052 140449568884608 estimator_utils.py:212]   name = decoder/layer_2/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.569161 140449568884608 estimator_utils.py:212]   name = decoder/layer_2/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.569277 140449568884608 estimator_utils.py:212]   name = decoder/layer_2/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.569390 140449568884608 estimator_utils.py:212]   name = decoder/layer_2/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.569504 140449568884608 estimator_utils.py:212]   name = decoder/layer_2/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.569646 140449568884608 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.569762 140449568884608 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.569873 140449568884608 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.569988 140449568884608 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.570103 140449568884608 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.570219 140449568884608 estimator_utils.py:212]   name = decoder/layer_2/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.570337 140449568884608 estimator_utils.py:212]   name = decoder/layer_2/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.570445 140449568884608 estimator_utils.py:212]   name = decoder/layer_2/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.570552 140449568884608 estimator_utils.py:212]   name = decoder/layer_2/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.570698 140449568884608 estimator_utils.py:212]   name = decoder/layer_2/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.570810 140449568884608 estimator_utils.py:212]   name = decoder/layer_2/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.570928 140449568884608 estimator_utils.py:212]   name = decoder/layer_2/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.571040 140449568884608 estimator_utils.py:212]   name = decoder/layer_3/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.571151 140449568884608 estimator_utils.py:212]   name = decoder/layer_3/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.571261 140449568884608 estimator_utils.py:212]   name = decoder/layer_3/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.571376 140449568884608 estimator_utils.py:212]   name = decoder/layer_3/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.571490 140449568884608 estimator_utils.py:212]   name = decoder/layer_3/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.571631 140449568884608 estimator_utils.py:212]   name = decoder/layer_3/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.571758 140449568884608 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.571870 140449568884608 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.571980 140449568884608 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.572098 140449568884608 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.572212 140449568884608 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.572326 140449568884608 estimator_utils.py:212]   name = decoder/layer_3/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.572441 140449568884608 estimator_utils.py:212]   name = decoder/layer_3/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.572553 140449568884608 estimator_utils.py:212]   name = decoder/layer_3/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.572696 140449568884608 estimator_utils.py:212]   name = decoder/layer_3/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.572813 140449568884608 estimator_utils.py:212]   name = decoder/layer_3/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.572962 140449568884608 estimator_utils.py:212]   name = decoder/layer_3/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.573080 140449568884608 estimator_utils.py:212]   name = decoder/layer_3/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.573192 140449568884608 estimator_utils.py:212]   name = decoder/layer_4/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.573301 140449568884608 estimator_utils.py:212]   name = decoder/layer_4/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.573409 140449568884608 estimator_utils.py:212]   name = decoder/layer_4/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.573523 140449568884608 estimator_utils.py:212]   name = decoder/layer_4/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.573667 140449568884608 estimator_utils.py:212]   name = decoder/layer_4/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.573789 140449568884608 estimator_utils.py:212]   name = decoder/layer_4/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.573906 140449568884608 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.574016 140449568884608 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.574125 140449568884608 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.574237 140449568884608 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.574350 140449568884608 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.574465 140449568884608 estimator_utils.py:212]   name = decoder/layer_4/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.574594 140449568884608 estimator_utils.py:212]   name = decoder/layer_4/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.574733 140449568884608 estimator_utils.py:212]   name = decoder/layer_4/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.574846 140449568884608 estimator_utils.py:212]   name = decoder/layer_4/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.574964 140449568884608 estimator_utils.py:212]   name = decoder/layer_4/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.575074 140449568884608 estimator_utils.py:212]   name = decoder/layer_4/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.575188 140449568884608 estimator_utils.py:212]   name = decoder/layer_4/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.575298 140449568884608 estimator_utils.py:212]   name = decoder/layer_5/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.575406 140449568884608 estimator_utils.py:212]   name = decoder/layer_5/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.575515 140449568884608 estimator_utils.py:212]   name = decoder/layer_5/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.575659 140449568884608 estimator_utils.py:212]   name = decoder/layer_5/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.575781 140449568884608 estimator_utils.py:212]   name = decoder/layer_5/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.575897 140449568884608 estimator_utils.py:212]   name = decoder/layer_5/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.576015 140449568884608 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.576124 140449568884608 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.576234 140449568884608 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.576347 140449568884608 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.576462 140449568884608 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.576592 140449568884608 estimator_utils.py:212]   name = decoder/layer_5/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.576727 140449568884608 estimator_utils.py:212]   name = decoder/layer_5/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.576840 140449568884608 estimator_utils.py:212]   name = decoder/layer_5/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.576951 140449568884608 estimator_utils.py:212]   name = decoder/layer_5/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.577066 140449568884608 estimator_utils.py:212]   name = decoder/layer_5/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.577177 140449568884608 estimator_utils.py:212]   name = decoder/layer_5/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.577294 140449568884608 estimator_utils.py:212]   name = decoder/layer_5/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.577404 140449568884608 estimator_utils.py:212]   name = decoder/layer_6/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.577513 140449568884608 estimator_utils.py:212]   name = decoder/layer_6/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.577648 140449568884608 estimator_utils.py:212]   name = decoder/layer_6/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.577769 140449568884608 estimator_utils.py:212]   name = decoder/layer_6/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.577886 140449568884608 estimator_utils.py:212]   name = decoder/layer_6/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.578001 140449568884608 estimator_utils.py:212]   name = decoder/layer_6/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.578116 140449568884608 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.578227 140449568884608 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.578338 140449568884608 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.578444 140449568884608 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.578555 140449568884608 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.578701 140449568884608 estimator_utils.py:212]   name = decoder/layer_6/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.578820 140449568884608 estimator_utils.py:212]   name = decoder/layer_6/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.578933 140449568884608 estimator_utils.py:212]   name = decoder/layer_6/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.579041 140449568884608 estimator_utils.py:212]   name = decoder/layer_6/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.579155 140449568884608 estimator_utils.py:212]   name = decoder/layer_6/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.579264 140449568884608 estimator_utils.py:212]   name = decoder/layer_6/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.579378 140449568884608 estimator_utils.py:212]   name = decoder/layer_6/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.579485 140449568884608 estimator_utils.py:212]   name = decoder/layer_7/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.579617 140449568884608 estimator_utils.py:212]   name = decoder/layer_7/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.579737 140449568884608 estimator_utils.py:212]   name = decoder/layer_7/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.579853 140449568884608 estimator_utils.py:212]   name = decoder/layer_7/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.579968 140449568884608 estimator_utils.py:212]   name = decoder/layer_7/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.580083 140449568884608 estimator_utils.py:212]   name = decoder/layer_7/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.580200 140449568884608 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.580310 140449568884608 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.580419 140449568884608 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.580533 140449568884608 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.580677 140449568884608 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.580799 140449568884608 estimator_utils.py:212]   name = decoder/layer_7/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.580917 140449568884608 estimator_utils.py:212]   name = decoder/layer_7/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.581029 140449568884608 estimator_utils.py:212]   name = decoder/layer_7/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.581139 140449568884608 estimator_utils.py:212]   name = decoder/layer_7/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.581256 140449568884608 estimator_utils.py:212]   name = decoder/layer_7/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.581364 140449568884608 estimator_utils.py:212]   name = decoder/layer_7/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.581479 140449568884608 estimator_utils.py:212]   name = decoder/layer_7/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.581601 140449568884608 estimator_utils.py:212]   name = decoder/layer_8/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.581751 140449568884608 estimator_utils.py:212]   name = decoder/layer_8/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.581866 140449568884608 estimator_utils.py:212]   name = decoder/layer_8/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.581980 140449568884608 estimator_utils.py:212]   name = decoder/layer_8/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.582097 140449568884608 estimator_utils.py:212]   name = decoder/layer_8/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.582216 140449568884608 estimator_utils.py:212]   name = decoder/layer_8/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.582335 140449568884608 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.582445 140449568884608 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.582554 140449568884608 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.582701 140449568884608 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.582819 140449568884608 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.582937 140449568884608 estimator_utils.py:212]   name = decoder/layer_8/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.583050 140449568884608 estimator_utils.py:212]   name = decoder/layer_8/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.583160 140449568884608 estimator_utils.py:212]   name = decoder/layer_8/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.583271 140449568884608 estimator_utils.py:212]   name = decoder/layer_8/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.583385 140449568884608 estimator_utils.py:212]   name = decoder/layer_8/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.583494 140449568884608 estimator_utils.py:212]   name = decoder/layer_8/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.583664 140449568884608 estimator_utils.py:212]   name = decoder/layer_8/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.583793 140449568884608 estimator_utils.py:212]   name = decoder/layer_9/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.583905 140449568884608 estimator_utils.py:212]   name = decoder/layer_9/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.584016 140449568884608 estimator_utils.py:212]   name = decoder/layer_9/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.584130 140449568884608 estimator_utils.py:212]   name = decoder/layer_9/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.584247 140449568884608 estimator_utils.py:212]   name = decoder/layer_9/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.584360 140449568884608 estimator_utils.py:212]   name = decoder/layer_9/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.584475 140449568884608 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.584599 140449568884608 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.584731 140449568884608 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.584848 140449568884608 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.584963 140449568884608 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.585081 140449568884608 estimator_utils.py:212]   name = decoder/layer_9/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.585216 140449568884608 estimator_utils.py:212]   name = decoder/layer_9/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.585334 140449568884608 estimator_utils.py:212]   name = decoder/layer_9/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.585446 140449568884608 estimator_utils.py:212]   name = decoder/layer_9/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.585561 140449568884608 estimator_utils.py:212]   name = decoder/layer_9/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.585714 140449568884608 estimator_utils.py:212]   name = decoder/layer_9/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.585834 140449568884608 estimator_utils.py:212]   name = decoder/layer_9/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.585946 140449568884608 estimator_utils.py:212]   name = decoder/layer_10/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.586056 140449568884608 estimator_utils.py:212]   name = decoder/layer_10/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.586167 140449568884608 estimator_utils.py:212]   name = decoder/layer_10/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.586284 140449568884608 estimator_utils.py:212]   name = decoder/layer_10/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.586402 140449568884608 estimator_utils.py:212]   name = decoder/layer_10/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.586515 140449568884608 estimator_utils.py:212]   name = decoder/layer_10/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.586661 140449568884608 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.586779 140449568884608 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.586891 140449568884608 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.587007 140449568884608 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.587125 140449568884608 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.587242 140449568884608 estimator_utils.py:212]   name = decoder/layer_10/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.587356 140449568884608 estimator_utils.py:212]   name = decoder/layer_10/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.587466 140449568884608 estimator_utils.py:212]   name = decoder/layer_10/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.587588 140449568884608 estimator_utils.py:212]   name = decoder/layer_10/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.587720 140449568884608 estimator_utils.py:212]   name = decoder/layer_10/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.587831 140449568884608 estimator_utils.py:212]   name = decoder/layer_10/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.587948 140449568884608 estimator_utils.py:212]   name = decoder/layer_10/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.588058 140449568884608 estimator_utils.py:212]   name = decoder/layer_11/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.588166 140449568884608 estimator_utils.py:212]   name = decoder/layer_11/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.588274 140449568884608 estimator_utils.py:212]   name = decoder/layer_11/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.588386 140449568884608 estimator_utils.py:212]   name = decoder/layer_11/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.588501 140449568884608 estimator_utils.py:212]   name = decoder/layer_11/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.588649 140449568884608 estimator_utils.py:212]   name = decoder/layer_11/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.588777 140449568884608 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.588890 140449568884608 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.589000 140449568884608 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.589117 140449568884608 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.589232 140449568884608 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.589348 140449568884608 estimator_utils.py:212]   name = decoder/layer_11/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.589462 140449568884608 estimator_utils.py:212]   name = decoder/layer_11/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.589588 140449568884608 estimator_utils.py:212]   name = decoder/layer_11/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.589715 140449568884608 estimator_utils.py:212]   name = decoder/layer_11/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.589833 140449568884608 estimator_utils.py:212]   name = decoder/layer_11/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.589942 140449568884608 estimator_utils.py:212]   name = decoder/layer_11/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.590055 140449568884608 estimator_utils.py:212]   name = decoder/layer_11/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.590165 140449568884608 estimator_utils.py:212]   name = decoder/layer_12/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.590276 140449568884608 estimator_utils.py:212]   name = decoder/layer_12/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.590385 140449568884608 estimator_utils.py:212]   name = decoder/layer_12/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.590520 140449568884608 estimator_utils.py:212]   name = decoder/layer_12/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.590667 140449568884608 estimator_utils.py:212]   name = decoder/layer_12/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.590787 140449568884608 estimator_utils.py:212]   name = decoder/layer_12/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.590904 140449568884608 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.591013 140449568884608 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.591121 140449568884608 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.591236 140449568884608 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.591350 140449568884608 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.591465 140449568884608 estimator_utils.py:212]   name = decoder/layer_12/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.591610 140449568884608 estimator_utils.py:212]   name = decoder/layer_12/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.591735 140449568884608 estimator_utils.py:212]   name = decoder/layer_12/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.591846 140449568884608 estimator_utils.py:212]   name = decoder/layer_12/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.591961 140449568884608 estimator_utils.py:212]   name = decoder/layer_12/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.592069 140449568884608 estimator_utils.py:212]   name = decoder/layer_12/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.592186 140449568884608 estimator_utils.py:212]   name = decoder/layer_12/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.592297 140449568884608 estimator_utils.py:212]   name = decoder/layer_13/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.592403 140449568884608 estimator_utils.py:212]   name = decoder/layer_13/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.592513 140449568884608 estimator_utils.py:212]   name = decoder/layer_13/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.592653 140449568884608 estimator_utils.py:212]   name = decoder/layer_13/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.592776 140449568884608 estimator_utils.py:212]   name = decoder/layer_13/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.592892 140449568884608 estimator_utils.py:212]   name = decoder/layer_13/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.593010 140449568884608 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.593121 140449568884608 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.593234 140449568884608 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.593351 140449568884608 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.593466 140449568884608 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.593600 140449568884608 estimator_utils.py:212]   name = decoder/layer_13/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.593734 140449568884608 estimator_utils.py:212]   name = decoder/layer_13/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.593849 140449568884608 estimator_utils.py:212]   name = decoder/layer_13/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.593958 140449568884608 estimator_utils.py:212]   name = decoder/layer_13/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.594071 140449568884608 estimator_utils.py:212]   name = decoder/layer_13/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.594182 140449568884608 estimator_utils.py:212]   name = decoder/layer_13/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.594297 140449568884608 estimator_utils.py:212]   name = decoder/layer_13/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.594406 140449568884608 estimator_utils.py:212]   name = decoder/layer_14/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.594514 140449568884608 estimator_utils.py:212]   name = decoder/layer_14/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.594654 140449568884608 estimator_utils.py:212]   name = decoder/layer_14/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.594780 140449568884608 estimator_utils.py:212]   name = decoder/layer_14/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.594895 140449568884608 estimator_utils.py:212]   name = decoder/layer_14/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.595009 140449568884608 estimator_utils.py:212]   name = decoder/layer_14/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.595125 140449568884608 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.595234 140449568884608 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.595342 140449568884608 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.595454 140449568884608 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.595568 140449568884608 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.595718 140449568884608 estimator_utils.py:212]   name = decoder/layer_14/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.595837 140449568884608 estimator_utils.py:212]   name = decoder/layer_14/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.595947 140449568884608 estimator_utils.py:212]   name = decoder/layer_14/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.596055 140449568884608 estimator_utils.py:212]   name = decoder/layer_14/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.596171 140449568884608 estimator_utils.py:212]   name = decoder/layer_14/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.596280 140449568884608 estimator_utils.py:212]   name = decoder/layer_14/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.596395 140449568884608 estimator_utils.py:212]   name = decoder/layer_14/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.596503 140449568884608 estimator_utils.py:212]   name = decoder/layer_15/self_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.596637 140449568884608 estimator_utils.py:212]   name = decoder/layer_15/self_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.596753 140449568884608 estimator_utils.py:212]   name = decoder/layer_15/self_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.596869 140449568884608 estimator_utils.py:212]   name = decoder/layer_15/self_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.596983 140449568884608 estimator_utils.py:212]   name = decoder/layer_15/self_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.597099 140449568884608 estimator_utils.py:212]   name = decoder/layer_15/self_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.597215 140449568884608 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.597325 140449568884608 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.597434 140449568884608 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/q_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.597545 140449568884608 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/k_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.597692 140449568884608 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/v_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.597814 140449568884608 estimator_utils.py:212]   name = decoder/layer_15/memory_attention/output_proj/kernel:0, shape = (1024, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.597929 140449568884608 estimator_utils.py:212]   name = decoder/layer_15/ffn/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.598041 140449568884608 estimator_utils.py:212]   name = decoder/layer_15/ffn/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.598151 140449568884608 estimator_utils.py:212]   name = decoder/layer_15/ffn/dense/kernel:0, shape = (1024, 4096), *INIT_FROM_CKPT*\n    I0830 22:36:53.598266 140449568884608 estimator_utils.py:212]   name = decoder/layer_15/ffn/dense/bias:0, shape = (4096,), *INIT_FROM_CKPT*\n    I0830 22:36:53.598374 140449568884608 estimator_utils.py:212]   name = decoder/layer_15/ffn/dense_1/kernel:0, shape = (4096, 1024), *INIT_FROM_CKPT*\n    I0830 22:36:53.598489 140449568884608 estimator_utils.py:212]   name = decoder/layer_15/ffn/dense_1/bias:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.598624 140449568884608 estimator_utils.py:212]   name = decoder/LayerNorm/beta:0, shape = (1024,), *INIT_FROM_CKPT*\n    I0830 22:36:53.598745 140449568884608 estimator_utils.py:212]   name = decoder/LayerNorm/gamma:0, shape = (1024,), *INIT_FROM_CKPT*\n    INFO:tensorflow:Done calling model_fn.\n    I0830 22:36:53.611234 140449568884608 estimator.py:1150] Done calling model_fn.\n    INFO:tensorflow:Create CheckpointSaverHook.\n    I0830 22:36:53.612718 140449568884608 basic_session_run_hooks.py:541] Create CheckpointSaverHook.\n    INFO:tensorflow:Graph was finalized.\n    I0830 22:37:01.954790 140449568884608 monitored_session.py:240] Graph was finalized.\n    2020-08-30 22:37:01.955412: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA\n    2020-08-30 22:37:01.961025: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2200000000 Hz\n    2020-08-30 22:37:01.961365: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x260b800 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n    2020-08-30 22:37:01.961407: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version\n    INFO:tensorflow:Running local_init_op.\n    I0830 22:37:48.325643 140449568884608 session_manager.py:500] Running local_init_op.\n    INFO:tensorflow:Done running local_init_op.\n    I0830 22:37:49.231556 140449568884608 session_manager.py:502] Done running local_init_op.\n    INFO:tensorflow:Saving checkpoints for 0 into ckpt/pegasus_ckpt/reddit_tifu_long/model.ckpt.\n    I0830 22:38:12.342087 140449568884608 basic_session_run_hooks.py:606] Saving checkpoints for 0 into ckpt/pegasus_ckpt/reddit_tifu_long/model.ckpt.\n    2020-08-30 22:39:36.376378: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:145] Filling up shuffle buffer (this may take a while): 5540 of 10000\n    2020-08-30 22:39:43.411281: I tensorflow/core/kernels/data/shuffle_dataset_op.cc:195] Shuffle buffer filled.\n    ^C\n\n\n\n```\nlen(\"Musk\u2019s current problems are less dire than those he faced in 2008, but Tesla and SpaceX are no longer experiments. Failure now would put thousands of jobs and billions of dollars at risk, and SpaceX has become crucial not just to the U.S. space program but also to countries and companies around the world hoping to put up satellites. Musk's supporters say he has built up enough credibility and has enough star power to raise money with relative ease or to be bailed out by one of his many ultrarich friends who share his aspirations. Just on technological merits, Musk\u2019s companies have already changed the world. To the extent that the electric car is a commercial reality, it\u2019s in large part thanks to Tesla. While it receives less attention, SpaceX and the revitalization of the U.S. aerospace industry may be Musk\u2019s most stirring accomplishment. But at every point where his companies seem to be on stable footing, Musk takes on more and promises more, erasing the memory of past gains. The question is whether Musk can continue to operate on the edge of what\u2019s possible \u2014 the key to his achievements so far.\")\n```\n\n\n\n\n    1113\n\n\n\n\n```\n!python3 pegasus/bin/evaluate.py --params=test_transformer \\\n--param_overrides=vocab_filename=ckpt/pegasus_ckpt/c4.unigram.newline.10pct.96000.model,batch_size=1,beam_size=5,beam_alpha=0.6 \\\n--model_dir=ckpt/pegasus_ckpt/cnn_dailymail\n```\n\n    WARNING:tensorflow:From pegasus/bin/evaluate.py:152: The name tf.enable_eager_execution is deprecated. Please use tf.compat.v1.enable_eager_execution instead.\n    \n    WARNING:tensorflow:From pegasus/bin/evaluate.py:153: The name tf.app.run is deprecated. Please use tf.compat.v1.app.run instead.\n    \n    WARNING:tensorflow:From pegasus/bin/evaluate.py:85: checkpoint_exists (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use standard file APIs to check for files with this prefix.\n    W0831 00:52:16.574285 140705774061440 deprecation.py:323] From pegasus/bin/evaluate.py:85: checkpoint_exists (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use standard file APIs to check for files with this prefix.\n    WARNING:tensorflow:From /content/pegasus/pegasus/ops/public_parsing_ops.py:93: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n    \n    W0831 00:52:16.581033 140705774061440 module_wrapper.py:139] From /content/pegasus/pegasus/ops/public_parsing_ops.py:93: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:49: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead.\n    \n    W0831 00:52:16.809791 140705774061440 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:49: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead.\n    \n    WARNING:tensorflow:Estimator's model_fn (<function _estimator_model_fn.<locals>.model_fn at 0x7ff821e19d90>) includes params argument, but params are not passed to Estimator.\n    W0831 00:52:16.810527 140705774061440 estimator.py:1994] Estimator's model_fn (<function _estimator_model_fn.<locals>.model_fn at 0x7ff821e19d90>) includes params argument, but params are not passed to Estimator.\n    INFO:tensorflow:Using config: {'_model_dir': 'ckpt/pegasus_ckpt/cnn_dailymail', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': 1000, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true\n    , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': None, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7ff821e0ce80>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1, '_tpu_config': TPUConfig(iterations_per_loop=1000, num_shards=None, num_cores_per_replica=None, per_host_input_for_training=2, tpu_job_name=None, initial_infeed_sleep_secs=None, input_partition_dims=None, eval_training_input_configuration=2, experimental_host_call_every_n_steps=1), '_cluster': None}\n    I0831 00:52:16.811165 140705774061440 estimator.py:212] Using config: {'_model_dir': 'ckpt/pegasus_ckpt/cnn_dailymail', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': 1000, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true\n    , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': None, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7ff821e0ce80>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1, '_tpu_config': TPUConfig(iterations_per_loop=1000, num_shards=None, num_cores_per_replica=None, per_host_input_for_training=2, tpu_job_name=None, initial_infeed_sleep_secs=None, input_partition_dims=None, eval_training_input_configuration=2, experimental_host_call_every_n_steps=1), '_cluster': None}\n    INFO:tensorflow:_TPUContext: eval_on_tpu True\n    I0831 00:52:16.811460 140705774061440 tpu_context.py:220] _TPUContext: eval_on_tpu True\n    WARNING:tensorflow:eval_on_tpu ignored because use_tpu is False.\n    W0831 00:52:16.812344 140705774061440 tpu_context.py:222] eval_on_tpu ignored because use_tpu is False.\n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\n    Instructions for updating:\n    If using Keras pass *_constraint arguments to layers.\n    W0831 00:52:16.828357 140705774061440 deprecation.py:506] From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\n    Instructions for updating:\n    If using Keras pass *_constraint arguments to layers.\n    ERROR:tensorflow:Error recorded from prediction_loop: Dataset name /content/pegasus/pegasus/data/testdata/test_pattern_1.tfrecord is not found in registered datasets.\n    E0831 00:52:16.829222 140705774061440 error_handling.py:75] Error recorded from prediction_loop: Dataset name /content/pegasus/pegasus/data/testdata/test_pattern_1.tfrecord is not found in registered datasets.\n    INFO:tensorflow:prediction_loop marked as finished\n    I0831 00:52:16.829406 140705774061440 error_handling.py:101] prediction_loop marked as finished\n    WARNING:tensorflow:Reraising captured error\n    W0831 00:52:16.829526 140705774061440 error_handling.py:135] Reraising captured error\n    Traceback (most recent call last):\n      File \"pegasus/bin/evaluate.py\", line 153, in <module>\n        tf.app.run(main)\n      File \"/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/platform/app.py\", line 40, in run\n        _run(main=main, argv=argv, flags_parser=_parse_flags_tolerate_undef)\n      File \"/usr/local/lib/python3.6/dist-packages/absl/app.py\", line 299, in run\n        _run_main(main, args)\n      File \"/usr/local/lib/python3.6/dist-packages/absl/app.py\", line 250, in _run_main\n        sys.exit(main(argv))\n      File \"pegasus/bin/evaluate.py\", line 144, in main\n        FLAGS.enable_logging)\n      File \"/content/pegasus/pegasus/eval/text_eval.py\", line 153, in text_eval\n        for i, features in enumerate(features_iter):\n      File \"/usr/local/lib/python3.6/dist-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py\", line 3078, in predict\n        rendezvous.raise_errors()\n      File \"/usr/local/lib/python3.6/dist-packages/tensorflow_estimator/python/estimator/tpu/error_handling.py\", line 136, in raise_errors\n        six.reraise(typ, value, traceback)\n      File \"/usr/local/lib/python3.6/dist-packages/six.py\", line 703, in reraise\n        raise value\n      File \"/usr/local/lib/python3.6/dist-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py\", line 3072, in predict\n        yield_single_examples=yield_single_examples):\n      File \"/usr/local/lib/python3.6/dist-packages/tensorflow_estimator/python/estimator/estimator.py\", line 620, in predict\n        input_fn, ModeKeys.PREDICT)\n      File \"/usr/local/lib/python3.6/dist-packages/tensorflow_estimator/python/estimator/estimator.py\", line 996, in _get_features_from_input_fn\n        result = self._call_input_fn(input_fn, mode)\n      File \"/usr/local/lib/python3.6/dist-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py\", line 2987, in _call_input_fn\n        return input_fn(**kwargs)\n      File \"/content/pegasus/pegasus/data/infeed.py\", line 41, in input_fn\n        dataset = all_datasets.get_dataset(input_pattern, training)\n      File \"/content/pegasus/pegasus/data/all_datasets.py\", line 51, in get_dataset\n        builder = datasets.get_dataset(prefix)\n      File \"/content/pegasus/pegasus/data/datasets.py\", line 30, in get_dataset\n        dataset_name)\n    ValueError: Dataset name /content/pegasus/pegasus/data/testdata/test_pattern_1.tfrecord is not found in registered datasets.\n\n\n\n```\n%load_ext tensorboard\n```\n\n\n```\n!python3 pegasus/bin/train.py --params=reddit_tifu_long_transformer \\\n--param_overrides=vocab_filename=ckpt/pegasus_ckpt/c4.unigram.newline.10pct.96000.model \\\n--train_init_checkpoint=ckpt/pegasus_ckpt/model.ckpt-1500000 \\\n--model_dir=ckpt/pegasus_ckpt/reddit_tifu_long\n```\n\n\n```\n!python3 pegasus/bin/train.py --params=reddit_tifu_long_transformer \\\n--param_overrides=vocab_filename=ckpt/pegasus_ckpt/c4.unigram.newline.10pct.96000.model \\\n--train_init_checkpoint=ckpt/pegasus_ckpt/model.ckpt-1500000 \\\n--model_dir=ckpt/pegasus_ckpt/reddit_tifu_long\n```\n\n\n```\n!python3 pegasus/bin/train.py --params=reddit_tifu_long_transformer \\\n--param_overrides=vocab_filename=ckpt/pegasus_ckpt/c4.unigram.newline.10pct.96000.model \\\n--train_init_checkpoint=ckpt/pegasus_ckpt/model.ckpt-1500000 \\\n--model_dir=ckpt/pegasus_ckpt/reddit_tifu_long\n```\n\n\n```\n!python3 pegasus/bin/train.py --params=reddit_tifu_long_transformer \\\n--param_overrides=vocab_filename=ckpt/pegasus_ckpt/c4.unigram.newline.10pct.96000.model \\\n--train_init_checkpoint=ckpt/pegasus_ckpt/model.ckpt-1500000 \\\n--model_dir=ckpt/pegasus_ckpt/reddit_tifu_long\n```\n\n\n```\n!python3 pegasus/bin/train.py --params=newsroom_transformer \\\n--param_overrides=vocab_filename=ckpt/pegasus_ckpt/c4.unigram.newline.10pct.96000.model \\\n--train_init_checkpoint=ckpt/pegasus_ckpt/model.ckpt-1500000 \\\n--model_dir=ckpt/pegasus_ckpt/newsroom\n```\n\n    WARNING:tensorflow:From pegasus/bin/train.py:94: The name tf.app.run is deprecated. Please use tf.compat.v1.app.run instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/ops/public_parsing_ops.py:93: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n    \n    W0830 20:37:11.819154 140679300540288 module_wrapper.py:139] From /content/pegasus/pegasus/ops/public_parsing_ops.py:93: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:49: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead.\n    \n    W0830 20:37:12.039921 140679300540288 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:49: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead.\n    \n    WARNING:tensorflow:Estimator's model_fn (<function _estimator_model_fn.<locals>.model_fn at 0x7ff1f7ef6b70>) includes params argument, but params are not passed to Estimator.\n    W0830 20:37:12.040601 140679300540288 estimator.py:1994] Estimator's model_fn (<function _estimator_model_fn.<locals>.model_fn at 0x7ff1f7ef6b70>) includes params argument, but params are not passed to Estimator.\n    INFO:tensorflow:Using config: {'_model_dir': 'ckpt/pegasus_ckpt/cnn_dailymail', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': 1000, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true\n    , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': None, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7ff1f7eeacc0>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1, '_tpu_config': TPUConfig(iterations_per_loop=1000, num_shards=None, num_cores_per_replica=None, per_host_input_for_training=2, tpu_job_name=None, initial_infeed_sleep_secs=None, input_partition_dims=None, eval_training_input_configuration=2, experimental_host_call_every_n_steps=1), '_cluster': None}\n    I0830 20:37:12.041142 140679300540288 estimator.py:212] Using config: {'_model_dir': 'ckpt/pegasus_ckpt/cnn_dailymail', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': 1000, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true\n    , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': None, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7ff1f7eeacc0>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1, '_tpu_config': TPUConfig(iterations_per_loop=1000, num_shards=None, num_cores_per_replica=None, per_host_input_for_training=2, tpu_job_name=None, initial_infeed_sleep_secs=None, input_partition_dims=None, eval_training_input_configuration=2, experimental_host_call_every_n_steps=1), '_cluster': None}\n    INFO:tensorflow:_TPUContext: eval_on_tpu True\n    I0830 20:37:12.041419 140679300540288 tpu_context.py:220] _TPUContext: eval_on_tpu True\n    WARNING:tensorflow:eval_on_tpu ignored because use_tpu is False.\n    W0830 20:37:12.042281 140679300540288 tpu_context.py:222] eval_on_tpu ignored because use_tpu is False.\n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\n    Instructions for updating:\n    If using Keras pass *_constraint arguments to layers.\n    W0830 20:37:12.058464 140679300540288 deprecation.py:506] From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\n    Instructions for updating:\n    If using Keras pass *_constraint arguments to layers.\n    WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.\n    W0830 20:37:12.059060 140679300540288 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.\n    2020-08-30 20:37:12.082075: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    2020-08-30 20:37:12.284181: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    2020-08-30 20:37:12.492001: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    I0830 20:37:12.679994 140679300540288 dataset_info.py:424] Load pre-computed DatasetInfo (eg: splits, num examples,...) from GCS: cnn_dailymail/plain_text/3.0.0\n    2020-08-30 20:37:12.691979: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    I0830 20:37:12.889495 140679300540288 dataset_info.py:355] Load dataset info from /tmp/tmpfjl9s2ojtfds\n    I0830 20:37:12.891554 140679300540288 dataset_info.py:395] Field info.description from disk and from code do not match. Keeping the one from code.\n    I0830 20:37:12.891799 140679300540288 dataset_info.py:395] Field info.config_name from disk and from code do not match. Keeping the one from code.\n    I0830 20:37:12.891911 140679300540288 dataset_info.py:395] Field info.citation from disk and from code do not match. Keeping the one from code.\n    I0830 20:37:12.892290 140679300540288 dataset_builder.py:349] Generating dataset cnn_dailymail (/root/tensorflow_datasets/cnn_dailymail/plain_text/3.0.0)\n    \u001b[1mDownloading and preparing dataset cnn_dailymail/plain_text/3.0.0 (download: 558.32 MiB, generated: 1.27 GiB, total: 1.82 GiB) to /root/tensorflow_datasets/cnn_dailymail/plain_text/3.0.0...\u001b[0m\n    2020-08-30 20:37:12.987470: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    2020-08-30 20:37:13.172744: W tensorflow/core/platform/cloud/google_auth_provider.cc:178] All attempts to get a Google authentication bearer token failed, returning an empty token. Retrieving token from files failed with \"Not found: Could not locate the credentials file.\". Retrieving token from GCE failed with \"Cancelled: GCE check skipped due to presence of $NO_GCE_CHECK environment variable.\".\n    Dl Completed...: 0 url [00:00, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[AI0830 20:37:13.361479 140679300540288 download_manager.py:478] Downloading https://drive.google.com/uc?export=download&id=0BwmD_VLjROrfTHk4NFg2SndKcjQ into /root/tensorflow_datasets/downloads/ucexport_download_id_0BwmD_VLjROrfTHk4NFg2SndKG8BdJPpt2iRo6Dpzz23CByJuAePEilB-pxbcBCHaWDs.tmp.1437134628dd45d5a7d52e4768f2c7c0...\n    Dl Completed...:   0% 0/1 [00:00<?, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[AI0830 20:37:13.363606 140679300540288 download_manager.py:478] Downloading https://drive.google.com/uc?export=download&id=0BwmD_VLjROrfM1BxdkxVaTY2bWs into /root/tensorflow_datasets/downloads/ucexport_download_id_0BwmD_VLjROrfM1BxdkxVaTY2zVV-G71RIXPssrrvSAjt19Cy91r-9CQ2F9DMKA0uFk0.tmp.fe8cc85ee66e45d8ac54a0992b0e5f9b...\n    Dl Completed...:   0% 0/2 [00:00<?, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[AI0830 20:37:13.368501 140679300540288 download_manager.py:478] Downloading https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_test.txt into /root/tensorflow_datasets/downloads/raw.gith.com_abis_cnn-dail_mast_url_list_a705_isK790OHOPsIZX-ACsObq_vchU9r5Uduh6ULX3c.txt.tmp.aca66360d25b406b8ab2686e678486af...\n    Dl Completed...:   0% 0/3 [00:00<?, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[AI0830 20:37:13.371487 140679300540288 download_manager.py:478] Downloading https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_train.txt into /root/tensorflow_datasets/downloads/raw.gith.com_abis_cnn-dail_mast_url_list_ac8YFmYLc8VRUvf04x1htoZoMCha8FjkWxZzzNI42_Qk.txt.tmp.9819c04a98cf4a8cade5f5c39cafe909...\n    Dl Completed...:   0% 0/4 [00:00<?, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[AI0830 20:37:13.376146 140679300540288 download_manager.py:478] Downloading https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_val.txt into /root/tensorflow_datasets/downloads/raw.gith.com_abis_cnn-dail_mast_url_list_aICtMBRotWZqhw9th-ABXYHIqhoG-ATk7YrhmKRDVCdU.txt.tmp.83160b8cdcb746b6a399e7d2c6b34561...\n    Dl Completed...:   0% 0/5 [00:00<?, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/5 [00:00<?, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/5 [00:00<?, ? url/s]\n    Dl Size...: 0 MiB [00:00, ? MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:   0% 0/5 [00:00<?, ? url/s]\n    Dl Size...: 1 MiB [00:00,  1.25 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/5 [00:00<?, ? url/s]\n    Dl Size...: 2 MiB [00:00,  1.25 MiB/s]\u001b[A\n    \n    Dl Completed...:   0% 0/5 [00:00<?, ? url/s]\n    Dl Size...: 3 MiB [00:00,  1.25 MiB/s]\u001b[A\n    \n    Dl Completed...:  20% 1/5 [00:00<00:03,  1.19 url/s]\n    Dl Size...: 3 MiB [00:00,  1.25 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[AI0830 20:37:14.204159 140677177947904 download_manager.py:497] Skipping extraction for /root/tensorflow_datasets/downloads/raw.gith.com_abis_cnn-dail_mast_url_list_a705_isK790OHOPsIZX-ACsObq_vchU9r5Uduh6ULX3c.txt (method=NO_EXTRACT).\n    Dl Completed...:  20% 1/5 [00:00<00:03,  1.19 url/s]\n    Dl Size...: 4 MiB [00:00,  1.25 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:00<00:02,  1.19 url/s]\n    Dl Size...: 4 MiB [00:00,  1.25 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:00, ? file/s]\u001b[A\u001b[AI0830 20:37:14.222264 140677161162496 download_manager.py:497] Skipping extraction for /root/tensorflow_datasets/downloads/raw.gith.com_abis_cnn-dail_mast_url_list_aICtMBRotWZqhw9th-ABXYHIqhoG-ATk7YrhmKRDVCdU.txt (method=NO_EXTRACT).\n    Dl Completed...:  40% 2/5 [00:01<00:02,  1.19 url/s]\n    Dl Size...: 4 MiB [00:01,  1.25 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:01, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:01<00:02,  1.19 url/s]\n    Dl Size...: 5 MiB [00:01,  1.59 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:01<00:02,  1.19 url/s]\n    Dl Size...: 6 MiB [00:01,  1.59 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:01<00:02,  1.19 url/s]\n    Dl Size...: 6 MiB [00:01,  1.59 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:01<00:02,  1.19 url/s]\n    Dl Size...: 7 MiB [00:01,  1.59 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:01<00:02,  1.19 url/s]\n    Dl Size...: 8 MiB [00:01,  1.59 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:01<00:02,  1.19 url/s]\n    Dl Size...: 9 MiB [00:01,  1.59 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:01<00:02,  1.19 url/s]\n    Dl Size...: 10 MiB [00:01,  1.59 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:01, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 11 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 12 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 13 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 14 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 15 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 16 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 17 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 18 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 19 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 20 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 21 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 22 MiB [00:02,  2.19 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 23 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 24 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 25 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 26 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 27 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 28 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 29 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 30 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 31 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 32 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 33 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 34 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 35 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 36 MiB [00:02,  3.10 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 37 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 38 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 39 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 40 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 41 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 42 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 43 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 44 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 45 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 46 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 47 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 48 MiB [00:02,  4.39 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 49 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 50 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 51 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 52 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 53 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 54 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 55 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 56 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 57 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 58 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 59 MiB [00:02,  6.17 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 60 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 61 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 62 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 63 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 64 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 65 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 66 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 67 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 68 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 69 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 70 MiB [00:02,  8.60 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 71 MiB [00:02, 11.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 72 MiB [00:02, 11.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 73 MiB [00:02, 11.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 74 MiB [00:02, 11.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 75 MiB [00:02, 11.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 76 MiB [00:02, 11.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 77 MiB [00:02, 11.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 78 MiB [00:02, 11.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 79 MiB [00:02, 11.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 80 MiB [00:02, 11.84 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 81 MiB [00:02, 16.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 82 MiB [00:02, 16.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 83 MiB [00:02, 16.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 84 MiB [00:02, 16.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 85 MiB [00:02, 16.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 86 MiB [00:02, 16.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 87 MiB [00:02, 16.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 88 MiB [00:02, 16.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 89 MiB [00:02, 16.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 90 MiB [00:02, 16.06 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 91 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 92 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 93 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 94 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 95 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 96 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 97 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 98 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 99 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 100 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 101 MiB [00:02, 21.45 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 102 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 103 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 104 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 105 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 106 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 107 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 108 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 109 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 110 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 111 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 112 MiB [00:02, 28.12 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:02, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 113 MiB [00:02, 36.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:02<00:02,  1.19 url/s]\n    Dl Size...: 114 MiB [00:02, 36.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 115 MiB [00:03, 36.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 116 MiB [00:03, 36.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 117 MiB [00:03, 36.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 118 MiB [00:03, 36.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 119 MiB [00:03, 36.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 120 MiB [00:03, 36.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 121 MiB [00:03, 36.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 122 MiB [00:03, 36.10 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 123 MiB [00:03, 43.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 124 MiB [00:03, 43.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 125 MiB [00:03, 43.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 126 MiB [00:03, 43.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 127 MiB [00:03, 43.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 128 MiB [00:03, 43.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 129 MiB [00:03, 43.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 130 MiB [00:03, 43.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 131 MiB [00:03, 43.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 132 MiB [00:03, 43.22 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 133 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 134 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 135 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 136 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 137 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 138 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 139 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 140 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 141 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 142 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 143 MiB [00:03, 50.56 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 144 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 145 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 146 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 147 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 148 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 149 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 150 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 151 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 152 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 153 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 154 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 155 MiB [00:03, 59.31 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 156 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 157 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 158 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 159 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 160 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 161 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 162 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 163 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 164 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 165 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 166 MiB [00:03, 68.63 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 167 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 168 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 169 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 170 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 171 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 172 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 173 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 174 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 175 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 176 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 177 MiB [00:03, 76.17 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 178 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 179 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 180 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 181 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 182 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 183 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 184 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 185 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 186 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 187 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 188 MiB [00:03, 83.80 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 189 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 190 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 191 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 192 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 193 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 194 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 195 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 196 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 197 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 198 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 199 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 200 MiB [00:03, 88.50 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 201 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 202 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 203 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 204 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 205 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 206 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 207 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 208 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 209 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 210 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 211 MiB [00:03, 92.83 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:03, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:03<00:02,  1.19 url/s]\n    Dl Size...: 212 MiB [00:03, 95.34 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 213 MiB [00:04, 95.34 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 214 MiB [00:04, 95.34 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 215 MiB [00:04, 95.34 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 216 MiB [00:04, 95.34 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 217 MiB [00:04, 95.34 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 218 MiB [00:04, 95.34 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 219 MiB [00:04, 95.34 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 220 MiB [00:04, 95.34 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 221 MiB [00:04, 95.34 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 222 MiB [00:04, 95.34 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 223 MiB [00:04, 89.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 224 MiB [00:04, 89.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 225 MiB [00:04, 89.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 226 MiB [00:04, 89.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 227 MiB [00:04, 89.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 228 MiB [00:04, 89.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 229 MiB [00:04, 89.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 230 MiB [00:04, 89.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 231 MiB [00:04, 89.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 232 MiB [00:04, 89.91 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 233 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 234 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 235 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 236 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 237 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 238 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 239 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 240 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 241 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 242 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 243 MiB [00:04, 92.09 MiB/s]\u001b[A\n    \n    Extraction completed...: 0 file [00:04, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 244 MiB [00:04, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 245 MiB [00:04, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 246 MiB [00:04, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 247 MiB [00:04, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 248 MiB [00:04, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 249 MiB [00:04, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  40% 2/5 [00:04<00:02,  1.19 url/s]\n    Dl Size...: 250 MiB [00:04, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:04<00:02,  1.12s/ url]\n    Dl Size...: 250 MiB [00:04, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:04<00:02,  1.12s/ url]\n    Dl Size...: 250 MiB [00:04, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:05<00:02,  1.12s/ url]\n    Dl Size...: 251 MiB [00:05, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:05<00:02,  1.12s/ url]\n    Dl Size...: 252 MiB [00:05, 96.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:05<00:02,  1.12s/ url]\n    Dl Size...: 253 MiB [00:05, 96.24 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:05<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:05<00:02,  1.12s/ url]\n    Dl Size...: 254 MiB [00:05, 17.79 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 254 MiB [00:06, 17.79 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 255 MiB [00:06, 17.79 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 256 MiB [00:06, 17.79 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 257 MiB [00:06, 17.79 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 258 MiB [00:06, 17.79 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 259 MiB [00:06, 17.79 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 260 MiB [00:06, 17.79 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 261 MiB [00:06, 17.79 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:06<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 262 MiB [00:06, 20.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 263 MiB [00:06, 20.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 264 MiB [00:06, 20.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 265 MiB [00:06, 20.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 266 MiB [00:06, 20.63 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 267 MiB [00:06, 20.63 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:06<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 268 MiB [00:06, 25.04 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 269 MiB [00:06, 25.04 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 270 MiB [00:06, 25.04 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 271 MiB [00:06, 25.04 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 272 MiB [00:06, 25.04 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 273 MiB [00:06, 25.04 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:06<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 274 MiB [00:06, 29.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 275 MiB [00:06, 29.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 276 MiB [00:06, 29.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 277 MiB [00:06, 29.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 278 MiB [00:06, 29.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 279 MiB [00:06, 29.20 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:06<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 280 MiB [00:06, 31.89 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 281 MiB [00:06, 31.89 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 282 MiB [00:06, 31.89 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 283 MiB [00:06, 31.89 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 284 MiB [00:06, 31.89 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 285 MiB [00:06, 31.89 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:06<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 286 MiB [00:06, 36.36 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 287 MiB [00:06, 36.36 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 288 MiB [00:06, 36.36 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 289 MiB [00:06, 36.36 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 290 MiB [00:06, 36.36 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 291 MiB [00:06, 36.36 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:06<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 292 MiB [00:06, 39.03 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 293 MiB [00:06, 39.03 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 294 MiB [00:06, 39.03 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 295 MiB [00:06, 39.03 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 296 MiB [00:06, 39.03 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 297 MiB [00:06, 39.03 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:06<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:06<00:02,  1.12s/ url]\n    Dl Size...: 298 MiB [00:06, 39.93 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 299 MiB [00:07, 39.93 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 300 MiB [00:07, 39.93 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 301 MiB [00:07, 39.93 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 302 MiB [00:07, 39.93 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:07<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 303 MiB [00:07, 41.62 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 304 MiB [00:07, 41.62 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 305 MiB [00:07, 41.62 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 306 MiB [00:07, 41.62 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 307 MiB [00:07, 41.62 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 308 MiB [00:07, 41.62 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:07<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 309 MiB [00:07, 43.27 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 310 MiB [00:07, 43.27 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 311 MiB [00:07, 43.27 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 312 MiB [00:07, 43.27 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 313 MiB [00:07, 43.27 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:07<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 314 MiB [00:07, 43.67 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 315 MiB [00:07, 43.67 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 316 MiB [00:07, 43.67 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 317 MiB [00:07, 43.67 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 318 MiB [00:07, 43.67 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:07<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 319 MiB [00:07, 45.26 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 320 MiB [00:07, 45.26 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 321 MiB [00:07, 45.26 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 322 MiB [00:07, 45.26 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 323 MiB [00:07, 45.26 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 324 MiB [00:07, 45.26 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:07<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 325 MiB [00:07, 44.15 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 326 MiB [00:07, 44.15 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 327 MiB [00:07, 44.15 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 328 MiB [00:07, 44.15 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 329 MiB [00:07, 44.15 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 330 MiB [00:07, 44.15 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:07<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 331 MiB [00:07, 46.61 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 332 MiB [00:07, 46.61 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 333 MiB [00:07, 46.61 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 334 MiB [00:07, 46.61 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 335 MiB [00:07, 46.61 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:07<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 336 MiB [00:07, 40.13 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 337 MiB [00:07, 40.13 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 338 MiB [00:07, 40.13 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 339 MiB [00:07, 40.13 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:07<00:02,  1.12s/ url]\n    Dl Size...: 340 MiB [00:07, 40.13 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:07<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  60% 3/5 [00:08<00:02,  1.12s/ url]\n    Dl Size...: 341 MiB [00:08, 37.33 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:08<00:02,  1.12s/ url]\n    Dl Size...: 342 MiB [00:08, 37.33 MiB/s]\u001b[A\n    \n    Dl Completed...:  60% 3/5 [00:08<00:02,  1.12s/ url]\n    Dl Size...: 343 MiB [00:08, 37.33 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 343 MiB [00:08, 37.33 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:08<?, ? file/s]\u001b[A\u001b[AI0830 20:37:21.425402 140677169555200 download_manager.py:497] Skipping extraction for /root/tensorflow_datasets/downloads/raw.gith.com_abis_cnn-dail_mast_url_list_ac8YFmYLc8VRUvf04x1htoZoMCha8FjkWxZzzNI42_Qk.txt (method=NO_EXTRACT).\n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 344 MiB [00:08, 37.33 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:08<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 345 MiB [00:08, 34.05 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 346 MiB [00:08, 34.05 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 347 MiB [00:08, 34.05 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 348 MiB [00:08, 34.05 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:08<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 349 MiB [00:08, 29.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 350 MiB [00:08, 29.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 351 MiB [00:08, 29.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 352 MiB [00:08, 29.08 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:08<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 353 MiB [00:08, 26.49 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 354 MiB [00:08, 26.49 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 355 MiB [00:08, 26.49 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:08<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 356 MiB [00:08, 24.65 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 357 MiB [00:08, 24.65 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 358 MiB [00:08, 24.65 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:08<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 359 MiB [00:08, 23.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 360 MiB [00:08, 23.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 361 MiB [00:08, 23.08 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:08<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:08<00:01,  1.89s/ url]\n    Dl Size...: 362 MiB [00:08, 22.37 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 363 MiB [00:09, 22.37 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 364 MiB [00:09, 22.37 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:09<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 365 MiB [00:09, 21.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 366 MiB [00:09, 21.06 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 367 MiB [00:09, 21.06 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:09<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 368 MiB [00:09, 16.23 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 369 MiB [00:09, 16.23 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 370 MiB [00:09, 16.23 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:09<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 371 MiB [00:09, 18.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 372 MiB [00:09, 18.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 373 MiB [00:09, 18.20 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:09<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:09<00:01,  1.89s/ url]\n    Dl Size...: 374 MiB [00:09, 19.52 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 375 MiB [00:10, 19.52 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 376 MiB [00:10, 19.52 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:10<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 377 MiB [00:10, 11.74 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 378 MiB [00:10, 11.74 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 379 MiB [00:10, 11.74 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:10<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 380 MiB [00:10, 13.87 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 381 MiB [00:10, 13.87 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 382 MiB [00:10, 13.87 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:10<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 383 MiB [00:10, 12.99 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 384 MiB [00:10, 12.99 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 385 MiB [00:10, 12.99 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:10<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 386 MiB [00:10, 14.90 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 387 MiB [00:10, 14.90 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 388 MiB [00:10, 14.90 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:10<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 389 MiB [00:10, 16.89 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 390 MiB [00:10, 16.89 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 391 MiB [00:10, 16.89 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:10<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 392 MiB [00:10, 17.82 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:10<00:01,  1.89s/ url]\n    Dl Size...: 393 MiB [00:10, 17.82 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 394 MiB [00:11, 17.82 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:11<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 395 MiB [00:11, 19.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 396 MiB [00:11, 19.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 397 MiB [00:11, 19.08 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:11<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 398 MiB [00:11, 20.16 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 399 MiB [00:11, 20.16 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 400 MiB [00:11, 20.16 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:11<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 401 MiB [00:11, 20.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 402 MiB [00:11, 20.91 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 403 MiB [00:11, 20.91 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:11<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 404 MiB [00:11, 21.43 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 405 MiB [00:11, 21.43 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:11<00:01,  1.89s/ url]\n    Dl Size...: 406 MiB [00:11, 21.43 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:11<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 407 MiB [00:12, 11.14 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 408 MiB [00:12, 11.14 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 409 MiB [00:12, 11.14 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:12<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 410 MiB [00:12, 13.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 411 MiB [00:12, 13.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 412 MiB [00:12, 13.20 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:12<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 413 MiB [00:12, 15.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 414 MiB [00:12, 15.20 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 415 MiB [00:12, 15.20 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:12<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 416 MiB [00:12, 12.68 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 417 MiB [00:12, 12.68 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 418 MiB [00:12, 12.68 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:12<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 419 MiB [00:12, 13.46 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 420 MiB [00:12, 13.46 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 421 MiB [00:12, 13.46 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:12<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:12<00:01,  1.89s/ url]\n    Dl Size...: 422 MiB [00:12, 15.81 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 423 MiB [00:13, 15.81 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:13<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 424 MiB [00:13, 11.30 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 425 MiB [00:13, 11.30 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 426 MiB [00:13, 11.30 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:13<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 427 MiB [00:13, 13.49 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 428 MiB [00:13, 13.49 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 429 MiB [00:13, 13.49 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:13<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 430 MiB [00:13, 15.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 431 MiB [00:13, 15.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 432 MiB [00:13, 15.50 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:13<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 433 MiB [00:13, 10.73 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:13<00:01,  1.89s/ url]\n    Dl Size...: 434 MiB [00:13, 10.73 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:14<00:01,  1.89s/ url]\n    Dl Size...: 435 MiB [00:14, 10.73 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:14<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:14<00:01,  1.89s/ url]\n    Dl Size...: 436 MiB [00:14, 13.02 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:14<00:01,  1.89s/ url]\n    Dl Size...: 437 MiB [00:14, 13.02 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:14<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:14<00:01,  1.89s/ url]\n    Dl Size...: 438 MiB [00:14, 14.48 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 439 MiB [00:15, 14.48 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:15<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 440 MiB [00:15,  4.72 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 441 MiB [00:15,  4.72 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 442 MiB [00:15,  4.72 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:15<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 443 MiB [00:15,  6.21 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 444 MiB [00:15,  6.21 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 445 MiB [00:15,  6.21 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:15<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 446 MiB [00:15,  7.97 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 447 MiB [00:15,  7.97 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 448 MiB [00:15,  7.97 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:15<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 449 MiB [00:15,  9.96 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 450 MiB [00:15,  9.96 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 451 MiB [00:15,  9.96 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:15<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 452 MiB [00:15, 12.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 453 MiB [00:15, 12.10 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 454 MiB [00:15, 12.10 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:15<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 455 MiB [00:15, 13.11 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:15<00:01,  1.89s/ url]\n    Dl Size...: 456 MiB [00:15, 13.11 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 457 MiB [00:16, 13.11 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:16<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 458 MiB [00:16, 15.21 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 459 MiB [00:16, 15.21 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 460 MiB [00:16, 15.21 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:16<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 461 MiB [00:16, 17.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 462 MiB [00:16, 17.24 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 463 MiB [00:16, 17.24 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:16<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 464 MiB [00:16, 16.88 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 465 MiB [00:16, 16.88 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 466 MiB [00:16, 16.88 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:16<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 467 MiB [00:16, 18.61 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 468 MiB [00:16, 18.61 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 469 MiB [00:16, 18.61 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:16<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 470 MiB [00:16, 20.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 471 MiB [00:16, 20.22 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 472 MiB [00:16, 20.22 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:16<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 473 MiB [00:16, 20.66 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 474 MiB [00:16, 20.66 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 475 MiB [00:16, 20.66 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:16<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 476 MiB [00:16, 21.18 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 477 MiB [00:16, 21.18 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:16<00:01,  1.89s/ url]\n    Dl Size...: 478 MiB [00:16, 21.18 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:16<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 479 MiB [00:17, 21.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 480 MiB [00:17, 21.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 481 MiB [00:17, 21.08 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:17<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 482 MiB [00:17, 21.28 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 483 MiB [00:17, 21.28 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 484 MiB [00:17, 21.28 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:17<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 485 MiB [00:17, 21.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 486 MiB [00:17, 21.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 487 MiB [00:17, 21.84 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:17<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 488 MiB [00:17, 22.07 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 489 MiB [00:17, 22.07 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 490 MiB [00:17, 22.07 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:17<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 491 MiB [00:17, 22.92 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 492 MiB [00:17, 22.92 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 493 MiB [00:17, 22.92 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:17<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 494 MiB [00:17, 23.21 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 495 MiB [00:17, 23.21 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 496 MiB [00:17, 23.21 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:17<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 497 MiB [00:17, 23.48 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 498 MiB [00:17, 23.48 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 499 MiB [00:17, 23.48 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:17<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 500 MiB [00:17, 24.21 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 501 MiB [00:17, 24.21 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:17<00:01,  1.89s/ url]\n    Dl Size...: 502 MiB [00:17, 24.21 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:17<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 503 MiB [00:18, 17.52 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 504 MiB [00:18, 17.52 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 505 MiB [00:18, 17.52 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:18<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 506 MiB [00:18, 19.33 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 507 MiB [00:18, 19.33 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 508 MiB [00:18, 19.33 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:18<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 509 MiB [00:18, 20.05 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 510 MiB [00:18, 20.05 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 511 MiB [00:18, 20.05 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:18<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 512 MiB [00:18, 18.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 513 MiB [00:18, 18.84 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 514 MiB [00:18, 18.84 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:18<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 515 MiB [00:18, 19.87 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 516 MiB [00:18, 19.87 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 517 MiB [00:18, 19.87 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:18<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 518 MiB [00:18, 21.33 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 519 MiB [00:18, 21.33 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:18<00:01,  1.89s/ url]\n    Dl Size...: 520 MiB [00:18, 21.33 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:18<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 521 MiB [00:19, 21.35 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 522 MiB [00:19, 21.35 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 523 MiB [00:19, 21.35 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:19<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 524 MiB [00:19, 20.77 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 525 MiB [00:19, 20.77 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 526 MiB [00:19, 20.77 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:19<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 527 MiB [00:19, 21.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 528 MiB [00:19, 21.08 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 529 MiB [00:19, 21.08 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:19<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 530 MiB [00:19, 20.18 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 531 MiB [00:19, 20.18 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 532 MiB [00:19, 20.18 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:19<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 533 MiB [00:19, 20.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 534 MiB [00:19, 20.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 535 MiB [00:19, 20.83 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:19<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 536 MiB [00:19, 21.74 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 537 MiB [00:19, 21.74 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 538 MiB [00:19, 21.74 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:19<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 539 MiB [00:19, 22.46 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 540 MiB [00:19, 22.46 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 541 MiB [00:19, 22.46 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:19<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:19<00:01,  1.89s/ url]\n    Dl Size...: 542 MiB [00:19, 22.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 543 MiB [00:20, 22.50 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 544 MiB [00:20, 22.50 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:20<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 545 MiB [00:20, 23.02 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 546 MiB [00:20, 23.02 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 547 MiB [00:20, 23.02 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:20<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 548 MiB [00:20, 22.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 549 MiB [00:20, 22.83 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 550 MiB [00:20, 22.83 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:20<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 551 MiB [00:20, 19.97 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 552 MiB [00:20, 19.97 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 553 MiB [00:20, 19.97 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:20<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 554 MiB [00:20, 20.97 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 555 MiB [00:20, 20.97 MiB/s]\u001b[A\n    \n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 556 MiB [00:20, 20.97 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/1 [00:20<?, ? file/s]\u001b[A\u001b[A\n    Dl Completed...:  80% 4/5 [00:20<00:01,  1.89s/ url]\n    Dl Size...: 557 MiB [00:20, 21.82 MiB/s]\u001b[A\n    \n    Dl Completed...: 100% 5/5 [00:20<00:00,  5.11s/ url]\n    Dl Size...: 557 MiB [00:20, 21.82 MiB/s]\u001b[A\n    \n    Dl Completed...: 100% 5/5 [00:20<00:00,  5.11s/ url]\n    Dl Size...: 557 MiB [00:20, 21.82 MiB/s]\u001b[A\n    \n    Extraction completed...:   0% 0/2 [00:20<?, ? file/s]\u001b[A\u001b[A\n    Dl Size...: 557 MiB [00:40, 21.82 MiB/s]\u001b[A\n    \n    Dl Completed...: 100% 5/5 [00:59<00:00,  5.11s/ url]\n    Dl Size...: 557 MiB [00:59, 21.82 MiB/s]\u001b[A\n    \n    Extraction completed...:  50% 1/2 [00:59<00:59, 59.25s/ file]\u001b[A\u001b[A\n    \n    Dl Completed...: 100% 5/5 [01:44<00:00,  5.11s/ url]\n    Dl Size...: 557 MiB [01:44, 21.82 MiB/s]\u001b[A\n    \n    Extraction completed...: 100% 2/2 [01:44<00:00, 55.02s/ file]\u001b[A\u001b[A\n    Extraction completed...: 100% 2/2 [01:44<00:00, 52.20s/ file]\n    \n    Dl Size...: 557 MiB [01:44,  5.34 MiB/s]\n    \n    Dl Completed...: 100% 5/5 [01:44<00:00, 20.88s/ url]\n    I0830 20:39:02.158226 140679300540288 dataset_builder.py:953] Generating split train\n    55563 examples [00:36, 1499.97 examples/s]\n\n\n```\n!python3 pegasus/bin/evaluate.py --params=reddit_tifu_long_transformer \\\n--param_overrides=vocab_filename=ckpt/pegasus_ckpt/c4.unigram.newline.10pct.96000.model,batch_size=1,beam_size=5,beam_alpha=0.6 \\\n--model_dir=ckpt/pegasus_ckpt/aeslc\n```\n\n    WARNING:tensorflow:From pegasus/bin/evaluate.py:152: The name tf.enable_eager_execution is deprecated. Please use tf.compat.v1.enable_eager_execution instead.\n    \n    WARNING:tensorflow:From pegasus/bin/evaluate.py:153: The name tf.app.run is deprecated. Please use tf.compat.v1.app.run instead.\n    \n    WARNING:tensorflow:From pegasus/bin/evaluate.py:85: checkpoint_exists (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use standard file APIs to check for files with this prefix.\n    W0830 20:31:40.234149 140633733166976 deprecation.py:323] From pegasus/bin/evaluate.py:85: checkpoint_exists (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use standard file APIs to check for files with this prefix.\n    WARNING:tensorflow:From /content/pegasus/pegasus/ops/public_parsing_ops.py:93: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n    \n    W0830 20:31:40.240438 140633733166976 module_wrapper.py:139] From /content/pegasus/pegasus/ops/public_parsing_ops.py:93: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n    \n    WARNING:tensorflow:From /content/pegasus/pegasus/params/estimator_utils.py:49: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead.\n    \n    W0830 20:31:40.465881 140633733166976 module_wrapper.py:139] From /content/pegasus/pegasus/params/estimator_utils.py:49: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead.\n    \n    WARNING:tensorflow:Estimator's model_fn (<function _estimator_model_fn.<locals>.model_fn at 0x7fe75be8bc80>) includes params argument, but params are not passed to Estimator.\n    W0830 20:31:40.466556 140633733166976 estimator.py:1994] Estimator's model_fn (<function _estimator_model_fn.<locals>.model_fn at 0x7fe75be8bc80>) includes params argument, but params are not passed to Estimator.\n    INFO:tensorflow:Using config: {'_model_dir': 'ckpt/pegasus_ckpt/aeslc', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': 1000, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true\n    , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': None, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7fe75be1f128>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1, '_tpu_config': TPUConfig(iterations_per_loop=1000, num_shards=None, num_cores_per_replica=None, per_host_input_for_training=2, tpu_job_name=None, initial_infeed_sleep_secs=None, input_partition_dims=None, eval_training_input_configuration=2, experimental_host_call_every_n_steps=1), '_cluster': None}\n    I0830 20:31:40.467090 140633733166976 estimator.py:212] Using config: {'_model_dir': 'ckpt/pegasus_ckpt/aeslc', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': 1000, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true\n    , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': None, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7fe75be1f128>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1, '_tpu_config': TPUConfig(iterations_per_loop=1000, num_shards=None, num_cores_per_replica=None, per_host_input_for_training=2, tpu_job_name=None, initial_infeed_sleep_secs=None, input_partition_dims=None, eval_training_input_configuration=2, experimental_host_call_every_n_steps=1), '_cluster': None}\n    INFO:tensorflow:_TPUContext: eval_on_tpu True\n    I0830 20:31:40.467371 140633733166976 tpu_context.py:220] _TPUContext: eval_on_tpu True\n    WARNING:tensorflow:eval_on_tpu ignored because use_tpu is False.\n    W0830 20:31:40.468221 140633733166976 tpu_context.py:222] eval_on_tpu ignored because use_tpu is False.\n    Traceback (most recent call last):\n      File \"pegasus/bin/evaluate.py\", line 153, in <module>\n        tf.app.run(main)\n      File \"/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/platform/app.py\", line 40, in run\n        _run(main=main, argv=argv, flags_parser=_parse_flags_tolerate_undef)\n      File \"/usr/local/lib/python3.6/dist-packages/absl/app.py\", line 299, in run\n        _run_main(main, args)\n      File \"/usr/local/lib/python3.6/dist-packages/absl/app.py\", line 250, in _run_main\n        sys.exit(main(argv))\n      File \"pegasus/bin/evaluate.py\", line 126, in main\n        global_step = estimator.get_variable_value(\"global_step\")\n      File \"/usr/local/lib/python3.6/dist-packages/tensorflow_estimator/python/estimator/estimator.py\", line 267, in get_variable_value\n        _check_checkpoint_available(self.model_dir)\n      File \"/usr/local/lib/python3.6/dist-packages/tensorflow_estimator/python/estimator/estimator.py\", line 1929, in _check_checkpoint_available\n        'Could not find trained model in model_dir: {}.'.format(model_dir))\n    ValueError: Could not find trained model in model_dir: ckpt/pegasus_ckpt/aeslc.\n\n\n@registry.register(\"reddit_tifu_long_transformer\")\ndef reddit_tifu_long_transformer(param_overrides):\n  return transformer_params(\n      {\n          \"train_pattern\": \"tfds_transformed:reddit_tifu/long-train\",\n          \"dev_pattern\": \"tfds_transformed:reddit_tifu/long-validation\",\n          \"test_pattern\": \"tfds_transformed:reddit_tifu/long-test\",\n          \"max_input_len\": 1024,\n          \"max_output_len\": 128,\n          \"train_steps\": 8000,\n          \"learning_rate\": 0.0001,\n          \"batch_size\": 8,\n      }, param_overrides)\n\n\n```\n#from google.colab import drive\n#drive.mount(\"/content/drive/\", force_remount=True)\n```\n\n\n```\n!python3 pegasus/bin/evaluate.py --params=aeslc_transformer \\\n--param_overrides=vocab_filename=ckpt/pegasus_ckpt/c4.unigram.newline.10pct.96000.model,batch_size=1,beam_size=5,beam_alpha=0.6 \\\n--model_dir=ckpt/pegasus_ckpt/aeslc\n```\n\n\n\n\n```\n\n```\n", "meta": {"hexsha": "e59825774a808cc0b5fe5575fddcce3e32296dea", "size": 973454, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "NLP_sum_project.ipynb", "max_stars_repo_name": "ebitdad7/pegasus", "max_stars_repo_head_hexsha": "5db4e37dabaea0470202b6169d9528486ee7ac54", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NLP_sum_project.ipynb", "max_issues_repo_name": "ebitdad7/pegasus", "max_issues_repo_head_hexsha": "5db4e37dabaea0470202b6169d9528486ee7ac54", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NLP_sum_project.ipynb", "max_forks_repo_name": "ebitdad7/pegasus", "max_forks_repo_head_hexsha": "5db4e37dabaea0470202b6169d9528486ee7ac54", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 80.7041949925, "max_line_length": 1156, "alphanum_fraction": 0.5781290128, "converted": true, "num_tokens": 315915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1403362602763177, "lm_q2_score": 0.03021458499340703, "lm_q1q2_score": 0.004240201863775692}}
{"text": "```python\nprint(\"This is a test.\")\n```\n\n    This is a test.\n\n\n\n```python\n<object>? and <object>??\n```\n\n\n```python\n%<function>\n```\n\n\n```python\nobj1= range(10)\n```\n\n\n```python\nobj1?\n```\n\n\n    \u001b[1;31mType:\u001b[0m        range\n    \u001b[1;31mString form:\u001b[0m range(0, 10)\n    \u001b[1;31mLength:\u001b[0m      10\n    \u001b[1;31mDocstring:\u001b[0m  \n    range(stop) -> range object\n    range(start, stop[, step]) -> range object\n    \n    Return an object that produces a sequence of integers from start (inclusive)\n    to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.\n    start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.\n    These are exactly the valid indices for a list of 4 elements.\n    When step is given, it specifies the increment (or decrement).\n\n\n\n\n```python\n%timeit x=100\n```\n\n    100000000 loops, best of 3: 15.2 ns per loop\n\n\n\n```python\n%quickref\n```\n\n\n    \n    IPython -- An enhanced Interactive Python - Quick Reference Card\n    ================================================================\n    \n    obj?, obj??      : Get help, or more help for object (also works as\n                       ?obj, ??obj).\n    ?foo.*abc*       : List names in 'foo' containing 'abc' in them.\n    %magic           : Information about IPython's 'magic' % functions.\n    \n    Magic functions are prefixed by % or %%, and typically take their arguments\n    without parentheses, quotes or even commas for convenience.  Line magics take a\n    single % and cell magics are prefixed with two %%.\n    \n    Example magic function calls:\n    \n    %alias d ls -F   : 'd' is now an alias for 'ls -F'\n    alias d ls -F    : Works if 'alias' not a python name\n    alist = %alias   : Get list of aliases to 'alist'\n    cd /usr/share    : Obvious. cd -<tab> to choose from visited dirs.\n    %cd??            : See help AND source for magic %cd\n    %timeit x=10     : time the 'x=10' statement with high precision.\n    %%timeit x=2**100\n    x**100           : time 'x**100' with a setup of 'x=2**100'; setup code is not\n                       counted.  This is an example of a cell magic.\n    \n    System commands:\n    \n    !cp a.txt b/     : System command escape, calls os.system()\n    cp a.txt b/      : after %rehashx, most system commands work without !\n    cp ${f}.txt $bar : Variable expansion in magics and system commands\n    files = !ls /usr : Capture sytem command output\n    files.s, files.l, files.n: \"a b c\", ['a','b','c'], 'a\\nb\\nc'\n    \n    History:\n    \n    _i, _ii, _iii    : Previous, next previous, next next previous input\n    _i4, _ih[2:5]    : Input history line 4, lines 2-4\n    exec _i81        : Execute input history line #81 again\n    %rep 81          : Edit input history line #81\n    _, __, ___       : previous, next previous, next next previous output\n    _dh              : Directory history\n    _oh              : Output history\n    %hist            : Command history of current session.\n    %hist -g foo     : Search command history of (almost) all sessions for 'foo'.\n    %hist -g         : Command history of (almost) all sessions.\n    %hist 1/2-8      : Command history containing lines 2-8 of session 1.\n    %hist 1/ ~2/     : Command history of session 1 and 2 sessions before current.\n    %hist ~8/1-~6/5  : Command history from line 1 of 8 sessions ago to\n                       line 5 of 6 sessions ago.\n    %edit 0/         : Open editor to execute code with history of current session.\n    \n    Autocall:\n    \n    f 1,2            : f(1,2)  # Off by default, enable with %autocall magic.\n    /f 1,2           : f(1,2) (forced autoparen)\n    ,f 1 2           : f(\"1\",\"2\")\n    ;f 1 2           : f(\"1 2\")\n    \n    Remember: TAB completion works in many contexts, not just file names\n    or python names.\n    \n    The following magic functions are currently available:\n    \n    %alias:\n        Define an alias for a system command.\n    %alias_magic:\n        ::\n    %autocall:\n        Make functions callable without having to type parentheses.\n    %automagic:\n        Make magic functions callable without having to type the initial %.\n    %autosave:\n        Set the autosave interval in the notebook (in seconds).\n    %bookmark:\n        Manage IPython's bookmark system.\n    %cd:\n        Change the current working directory.\n    %clear:\n        Clear the terminal.\n    %cls:\n        Clear the terminal.\n    %colors:\n        Switch color scheme for prompts, info system and exception handlers.\n    %config:\n        configure IPython\n    %connect_info:\n        Print information for connecting other clients to this kernel\n    %copy:\n        Alias for `!copy`\n    %ddir:\n        Alias for `!dir /ad /on`\n    %debug:\n        ::\n    %dhist:\n        Print your history of visited directories.\n    %dirs:\n        Return the current directory stack.\n    %doctest_mode:\n        Toggle doctest mode on and off.\n    %echo:\n        Alias for `!echo`\n    %ed:\n        Alias for `%edit`.\n    %edit:\n        Bring up an editor and execute the resulting code.\n    %env:\n        Get, set, or list environment variables.\n    %gui:\n        Enable or disable IPython GUI event loop integration.\n    %hist:\n        Alias for `%history`.\n    %history:\n        ::\n    %killbgscripts:\n        Kill all BG processes started by %%script and its family.\n    %ldir:\n        Alias for `!dir /ad /on`\n    %less:\n        Show a file through the pager.\n    %load:\n        Load code into the current frontend.\n    %load_ext:\n        Load an IPython extension by its module name.\n    %loadpy:\n        Alias of `%load`\n    %logoff:\n        Temporarily stop logging.\n    %logon:\n        Restart logging.\n    %logstart:\n        Start logging anywhere in a session.\n    %logstate:\n        Print the status of the logging system.\n    %logstop:\n        Fully stop logging and close log file.\n    %ls:\n        Alias for `!dir /on`\n    %lsmagic:\n        List currently available magic functions.\n    %macro:\n        Define a macro for future re-execution. It accepts ranges of history,\n    %magic:\n        Print information about the magic function system.\n    %matplotlib:\n        ::\n    %mkdir:\n        Alias for `!mkdir`\n    %more:\n        Show a file through the pager.\n    %notebook:\n        ::\n    %page:\n        Pretty print the object and display it through a pager.\n    %pastebin:\n        Upload code to Github's Gist paste bin, returning the URL.\n    %pdb:\n        Control the automatic calling of the pdb interactive debugger.\n    %pdef:\n        Print the call signature for any callable object.\n    %pdoc:\n        Print the docstring for an object.\n    %pfile:\n        Print (or run through pager) the file where an object is defined.\n    %pinfo:\n        Provide detailed information about an object.\n    %pinfo2:\n        Provide extra detailed information about an object.\n    %popd:\n        Change to directory popped off the top of the stack.\n    %pprint:\n        Toggle pretty printing on/off.\n    %precision:\n        Set floating point precision for pretty printing.\n    %profile:\n        Print your currently active IPython profile.\n    %prun:\n        Run a statement through the python code profiler.\n    %psearch:\n        Search for object in namespaces by wildcard.\n    %psource:\n        Print (or run through pager) the source code for an object.\n    %pushd:\n        Place the current dir on stack and change directory.\n    %pwd:\n        Return the current working directory path.\n    %pycat:\n        Show a syntax-highlighted file through a pager.\n    %pylab:\n        ::\n    %qtconsole:\n        Open a qtconsole connected to this kernel.\n    %quickref:\n        Show a quick reference sheet \n    %recall:\n        Repeat a command, or get command to input line for editing.\n    %rehashx:\n        Update the alias table with all executable files in $PATH.\n    %reload_ext:\n        Reload an IPython extension by its module name.\n    %ren:\n        Alias for `!ren`\n    %rep:\n        Alias for `%recall`.\n    %rerun:\n        Re-run previous input\n    %reset:\n        Resets the namespace by removing all names defined by the user, if\n    %reset_selective:\n        Resets the namespace by removing names defined by the user.\n    %rmdir:\n        Alias for `!rmdir`\n    %run:\n        Run the named file inside IPython as a program.\n    %save:\n        Save a set of lines or a macro to a given filename.\n    %sc:\n        Shell capture - run shell command and capture output (DEPRECATED use !).\n    %set_env:\n        Set environment variables.  Assumptions are that either \"val\" is a\n    %store:\n        Lightweight persistence for python variables.\n    %sx:\n        Shell execute - run shell command and capture output (!! is short-hand).\n    %system:\n        Shell execute - run shell command and capture output (!! is short-hand).\n    %tb:\n        Print the last traceback with the currently active exception mode.\n    %time:\n        Time execution of a Python statement or expression.\n    %timeit:\n        Time execution of a Python statement or expression\n    %unalias:\n        Remove an alias\n    %unload_ext:\n        Unload an IPython extension by its module name.\n    %who:\n        Print all interactive variables, with some minimal formatting.\n    %who_ls:\n        Return a sorted list of all interactive variables.\n    %whos:\n        Like %who, but gives some extra information about each variable.\n    %xdel:\n        Delete a variable, trying to clear it from anywhere that\n    %xmode:\n        Switch modes for the exception handlers.\n    %%!:\n        Shell execute - run shell command and capture output (!! is short-hand).\n    %%HTML:\n        Alias for `%%html`.\n    %%SVG:\n        Alias for `%%svg`.\n    %%bash:\n        %%bash script magic\n    %%capture:\n        ::\n    %%cmd:\n        %%cmd script magic\n    %%debug:\n        ::\n    %%file:\n        Alias for `%%writefile`.\n    %%html:\n        Render the cell as a block of HTML\n    %%javascript:\n        Run the cell block of Javascript code\n    %%js:\n        Run the cell block of Javascript code\n    %%latex:\n        Render the cell as a block of latex\n    %%perl:\n        %%perl script magic\n    %%prun:\n        Run a statement through the python code profiler.\n    %%pypy:\n        %%pypy script magic\n    %%python:\n        %%python script magic\n    %%python2:\n        %%python2 script magic\n    %%python3:\n        %%python3 script magic\n    %%ruby:\n        %%ruby script magic\n    %%script:\n        ::\n    %%sh:\n        %%sh script magic\n    %%svg:\n        Render the cell as an SVG literal\n    %%sx:\n        Shell execute - run shell command and capture output (!! is short-hand).\n    %%system:\n        Shell execute - run shell command and capture output (!! is short-hand).\n    %%time:\n        Time execution of a Python statement or expression.\n    %%timeit:\n        Time execution of a Python statement or expression\n    %%writefile:\n        ::\n\n\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom sklearn import datasets\nfrom sklearn.feature_selection import SelectKBest, f_regression\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.svm import SVR\nfrom sklearn.ensemble import RandomForestRegressor\n```\n\n\n```python\nboston_dataset = datasets.load_boston()\nX_full = boston_dataset.data\nY = boston_dataset.target\nprint (X_full.shape)\nprint (Y.shape)\n```\n\n    (506, 13)\n    (506,)\n\n\n\n```python\nprint(boston_dataset.DESCR)\n```\n\n    Boston House Prices dataset\n    ===========================\n    \n    Notes\n    ------\n    Data Set Characteristics:  \n    \n        :Number of Instances: 506 \n    \n        :Number of Attributes: 13 numeric/categorical predictive\n        \n        :Median Value (attribute 14) is usually the target\n    \n        :Attribute Information (in order):\n            - CRIM     per capita crime rate by town\n            - ZN       proportion of residential land zoned for lots over 25,000 sq.ft.\n            - INDUS    proportion of non-retail business acres per town\n            - CHAS     Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)\n            - NOX      nitric oxides concentration (parts per 10 million)\n            - RM       average number of rooms per dwelling\n            - AGE      proportion of owner-occupied units built prior to 1940\n            - DIS      weighted distances to five Boston employment centres\n            - RAD      index of accessibility to radial highways\n            - TAX      full-value property-tax rate per $10,000\n            - PTRATIO  pupil-teacher ratio by town\n            - B        1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town\n            - LSTAT    % lower status of the population\n            - MEDV     Median value of owner-occupied homes in $1000's\n    \n        :Missing Attribute Values: None\n    \n        :Creator: Harrison, D. and Rubinfeld, D.L.\n    \n    This is a copy of UCI ML housing dataset.\n    http://archive.ics.uci.edu/ml/datasets/Housing\n    \n    \n    This dataset was taken from the StatLib library which is maintained at Carnegie Mellon University.\n    \n    The Boston house-price data of Harrison, D. and Rubinfeld, D.L. 'Hedonic\n    prices and the demand for clean air', J. Environ. Economics & Management,\n    vol.5, 81-102, 1978.   Used in Belsley, Kuh & Welsch, 'Regression diagnostics\n    ...', Wiley, 1980.   N.B. Various transformations are used in the table on\n    pages 244-261 of the latter.\n    \n    The Boston house-price data has been used in many machine learning papers that address regression\n    problems.   \n         \n    **References**\n    \n       - Belsley, Kuh & Welsch, 'Regression diagnostics: Identifying Influential Data and Sources of Collinearity', Wiley, 1980. 244-261.\n       - Quinlan,R. (1993). Combining Instance-Based and Model-Based Learning. In Proceedings on the Tenth International Conference of Machine Learning, 236-243, University of Massachusetts, Amherst. Morgan Kaufmann.\n       - many more! (see http://archive.ics.uci.edu/ml/datasets/Housing)\n    \n\n\n\n```python\nselector = SelectKBest(f_regression, k=1)\nselector.fit(X_full, Y)\nX = X_full[:, selector.get_support()]\nprint (X.shape)\n```\n\n    (506, 1)\n\n\n\n```python\ndef plot_scatter(X,Y,R=None):\n    plt.scatter(X, Y, s=32, marker='o', facecolors='white')\n    if R is not None:\n        plt.scatter(X, R, color='red', linewidth=0.5)\n    plt.show()    \n```\n\n\n```python\nplot_scatter(X,Y)\n```\n\n### $$ y= a+bX $$\n\n\n```python\nregressor = LinearRegression(normalize=True).fit(X, Y)\nplot_scatter(X, Y, regressor.predict(X))\n```\n\n\n```python\nregressor = SVR().fit(X, Y)\nplot_scatter(X, Y, regressor.predict(X))\n```\n\n\n```python\nregressor = RandomForestRegressor().fit(X, Y)\nplot_scatter(X, Y, regressor.predict(X))\n```\n\nThis is a $\\LaTeX$ inline equation: $x = Ax+b$\nAnd this is a one-liner: $$x = Ax + b$$\n\n\n```latex\n%%latex\n\\[\n|u(t)| =\n\\begin{cases}\nu(t) & \\text{if } t \\geq 0 \\\\\n-u(t) & \\text{otherwise }\n\\end{cases}\n\\]\n```\n\n\n\\[\n|u(t)| =\n\\begin{cases}\nu(t) & \\text{if } t \\geq 0 \\\\\n-u(t) & \\text{otherwise }\n\\end{cases}\n\\]\n\n\n\n```latex\n%%latex\n\\begin{align}\nf(x) &= (a+b)^2 \\\\\n&= a^2 + (a+b) + (a+b) + b^2 \\\\\n&= a^2 + 2\\cdot (a+b) + b^2\n\\end{align}\n```\n\n\n\\begin{align}\nf(x) &= (a+b)^2 \\\\\n&= a^2 + (a+b) + (a+b) + b^2 \\\\\n&= a^2 + 2\\cdot (a+b) + b^2\n\\end{align}\n\n\n## Datasets and Code Used\n\n### Scikit-learn toy datasets\n\n\n```python\nfrom sklearn import datasets\niris = datasets.load_iris()\n```\n\n\n```python\niris\n```\n\n\n\n\n    {'DESCR': 'Iris Plants Database\\n====================\\n\\nNotes\\n-----\\nData Set Characteristics:\\n    :Number of Instances: 150 (50 in each of three classes)\\n    :Number of Attributes: 4 numeric, predictive attributes and the class\\n    :Attribute Information:\\n        - sepal length in cm\\n        - sepal width in cm\\n        - petal length in cm\\n        - petal width in cm\\n        - class:\\n                - Iris-Setosa\\n                - Iris-Versicolour\\n                - Iris-Virginica\\n    :Summary Statistics:\\n\\n    ============== ==== ==== ======= ===== ====================\\n                    Min  Max   Mean    SD   Class Correlation\\n    ============== ==== ==== ======= ===== ====================\\n    sepal length:   4.3  7.9   5.84   0.83    0.7826\\n    sepal width:    2.0  4.4   3.05   0.43   -0.4194\\n    petal length:   1.0  6.9   3.76   1.76    0.9490  (high!)\\n    petal width:    0.1  2.5   1.20  0.76     0.9565  (high!)\\n    ============== ==== ==== ======= ===== ====================\\n\\n    :Missing Attribute Values: None\\n    :Class Distribution: 33.3% for each of 3 classes.\\n    :Creator: R.A. Fisher\\n    :Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)\\n    :Date: July, 1988\\n\\nThis is a copy of UCI ML iris datasets.\\nhttp://archive.ics.uci.edu/ml/datasets/Iris\\n\\nThe famous Iris database, first used by Sir R.A Fisher\\n\\nThis is perhaps the best known database to be found in the\\npattern recognition literature.  Fisher\\'s paper is a classic in the field and\\nis referenced frequently to this day.  (See Duda & Hart, for example.)  The\\ndata set contains 3 classes of 50 instances each, where each class refers to a\\ntype of iris plant.  One class is linearly separable from the other 2; the\\nlatter are NOT linearly separable from each other.\\n\\nReferences\\n----------\\n   - Fisher,R.A. \"The use of multiple measurements in taxonomic problems\"\\n     Annual Eugenics, 7, Part II, 179-188 (1936); also in \"Contributions to\\n     Mathematical Statistics\" (John Wiley, NY, 1950).\\n   - Duda,R.O., & Hart,P.E. (1973) Pattern Classification and Scene Analysis.\\n     (Q327.D83) John Wiley & Sons.  ISBN 0-471-22361-1.  See page 218.\\n   - Dasarathy, B.V. (1980) \"Nosing Around the Neighborhood: A New System\\n     Structure and Classification Rule for Recognition in Partially Exposed\\n     Environments\".  IEEE Transactions on Pattern Analysis and Machine\\n     Intelligence, Vol. PAMI-2, No. 1, 67-71.\\n   - Gates, G.W. (1972) \"The Reduced Nearest Neighbor Rule\".  IEEE Transactions\\n     on Information Theory, May 1972, 431-433.\\n   - See also: 1988 MLC Proceedings, 54-64.  Cheeseman et al\"s AUTOCLASS II\\n     conceptual clustering system finds 3 classes in the data.\\n   - Many, many more ...\\n',\n     'data': array([[5.1, 3.5, 1.4, 0.2],\n            [4.9, 3. , 1.4, 0.2],\n            [4.7, 3.2, 1.3, 0.2],\n            [4.6, 3.1, 1.5, 0.2],\n            [5. , 3.6, 1.4, 0.2],\n            [5.4, 3.9, 1.7, 0.4],\n            [4.6, 3.4, 1.4, 0.3],\n            [5. , 3.4, 1.5, 0.2],\n            [4.4, 2.9, 1.4, 0.2],\n            [4.9, 3.1, 1.5, 0.1],\n            [5.4, 3.7, 1.5, 0.2],\n            [4.8, 3.4, 1.6, 0.2],\n            [4.8, 3. , 1.4, 0.1],\n            [4.3, 3. , 1.1, 0.1],\n            [5.8, 4. , 1.2, 0.2],\n            [5.7, 4.4, 1.5, 0.4],\n            [5.4, 3.9, 1.3, 0.4],\n            [5.1, 3.5, 1.4, 0.3],\n            [5.7, 3.8, 1.7, 0.3],\n            [5.1, 3.8, 1.5, 0.3],\n            [5.4, 3.4, 1.7, 0.2],\n            [5.1, 3.7, 1.5, 0.4],\n            [4.6, 3.6, 1. , 0.2],\n            [5.1, 3.3, 1.7, 0.5],\n            [4.8, 3.4, 1.9, 0.2],\n            [5. , 3. , 1.6, 0.2],\n            [5. , 3.4, 1.6, 0.4],\n            [5.2, 3.5, 1.5, 0.2],\n            [5.2, 3.4, 1.4, 0.2],\n            [4.7, 3.2, 1.6, 0.2],\n            [4.8, 3.1, 1.6, 0.2],\n            [5.4, 3.4, 1.5, 0.4],\n            [5.2, 4.1, 1.5, 0.1],\n            [5.5, 4.2, 1.4, 0.2],\n            [4.9, 3.1, 1.5, 0.1],\n            [5. , 3.2, 1.2, 0.2],\n            [5.5, 3.5, 1.3, 0.2],\n            [4.9, 3.1, 1.5, 0.1],\n            [4.4, 3. , 1.3, 0.2],\n            [5.1, 3.4, 1.5, 0.2],\n            [5. , 3.5, 1.3, 0.3],\n            [4.5, 2.3, 1.3, 0.3],\n            [4.4, 3.2, 1.3, 0.2],\n            [5. , 3.5, 1.6, 0.6],\n            [5.1, 3.8, 1.9, 0.4],\n            [4.8, 3. , 1.4, 0.3],\n            [5.1, 3.8, 1.6, 0.2],\n            [4.6, 3.2, 1.4, 0.2],\n            [5.3, 3.7, 1.5, 0.2],\n            [5. , 3.3, 1.4, 0.2],\n            [7. , 3.2, 4.7, 1.4],\n            [6.4, 3.2, 4.5, 1.5],\n            [6.9, 3.1, 4.9, 1.5],\n            [5.5, 2.3, 4. , 1.3],\n            [6.5, 2.8, 4.6, 1.5],\n            [5.7, 2.8, 4.5, 1.3],\n            [6.3, 3.3, 4.7, 1.6],\n            [4.9, 2.4, 3.3, 1. ],\n            [6.6, 2.9, 4.6, 1.3],\n            [5.2, 2.7, 3.9, 1.4],\n            [5. , 2. , 3.5, 1. ],\n            [5.9, 3. , 4.2, 1.5],\n            [6. , 2.2, 4. , 1. ],\n            [6.1, 2.9, 4.7, 1.4],\n            [5.6, 2.9, 3.6, 1.3],\n            [6.7, 3.1, 4.4, 1.4],\n            [5.6, 3. , 4.5, 1.5],\n            [5.8, 2.7, 4.1, 1. ],\n            [6.2, 2.2, 4.5, 1.5],\n            [5.6, 2.5, 3.9, 1.1],\n            [5.9, 3.2, 4.8, 1.8],\n            [6.1, 2.8, 4. , 1.3],\n            [6.3, 2.5, 4.9, 1.5],\n            [6.1, 2.8, 4.7, 1.2],\n            [6.4, 2.9, 4.3, 1.3],\n            [6.6, 3. , 4.4, 1.4],\n            [6.8, 2.8, 4.8, 1.4],\n            [6.7, 3. , 5. , 1.7],\n            [6. , 2.9, 4.5, 1.5],\n            [5.7, 2.6, 3.5, 1. ],\n            [5.5, 2.4, 3.8, 1.1],\n            [5.5, 2.4, 3.7, 1. ],\n            [5.8, 2.7, 3.9, 1.2],\n            [6. , 2.7, 5.1, 1.6],\n            [5.4, 3. , 4.5, 1.5],\n            [6. , 3.4, 4.5, 1.6],\n            [6.7, 3.1, 4.7, 1.5],\n            [6.3, 2.3, 4.4, 1.3],\n            [5.6, 3. , 4.1, 1.3],\n            [5.5, 2.5, 4. , 1.3],\n            [5.5, 2.6, 4.4, 1.2],\n            [6.1, 3. , 4.6, 1.4],\n            [5.8, 2.6, 4. , 1.2],\n            [5. , 2.3, 3.3, 1. ],\n            [5.6, 2.7, 4.2, 1.3],\n            [5.7, 3. , 4.2, 1.2],\n            [5.7, 2.9, 4.2, 1.3],\n            [6.2, 2.9, 4.3, 1.3],\n            [5.1, 2.5, 3. , 1.1],\n            [5.7, 2.8, 4.1, 1.3],\n            [6.3, 3.3, 6. , 2.5],\n            [5.8, 2.7, 5.1, 1.9],\n            [7.1, 3. , 5.9, 2.1],\n            [6.3, 2.9, 5.6, 1.8],\n            [6.5, 3. , 5.8, 2.2],\n            [7.6, 3. , 6.6, 2.1],\n            [4.9, 2.5, 4.5, 1.7],\n            [7.3, 2.9, 6.3, 1.8],\n            [6.7, 2.5, 5.8, 1.8],\n            [7.2, 3.6, 6.1, 2.5],\n            [6.5, 3.2, 5.1, 2. ],\n            [6.4, 2.7, 5.3, 1.9],\n            [6.8, 3. , 5.5, 2.1],\n            [5.7, 2.5, 5. , 2. ],\n            [5.8, 2.8, 5.1, 2.4],\n            [6.4, 3.2, 5.3, 2.3],\n            [6.5, 3. , 5.5, 1.8],\n            [7.7, 3.8, 6.7, 2.2],\n            [7.7, 2.6, 6.9, 2.3],\n            [6. , 2.2, 5. , 1.5],\n            [6.9, 3.2, 5.7, 2.3],\n            [5.6, 2.8, 4.9, 2. ],\n            [7.7, 2.8, 6.7, 2. ],\n            [6.3, 2.7, 4.9, 1.8],\n            [6.7, 3.3, 5.7, 2.1],\n            [7.2, 3.2, 6. , 1.8],\n            [6.2, 2.8, 4.8, 1.8],\n            [6.1, 3. , 4.9, 1.8],\n            [6.4, 2.8, 5.6, 2.1],\n            [7.2, 3. , 5.8, 1.6],\n            [7.4, 2.8, 6.1, 1.9],\n            [7.9, 3.8, 6.4, 2. ],\n            [6.4, 2.8, 5.6, 2.2],\n            [6.3, 2.8, 5.1, 1.5],\n            [6.1, 2.6, 5.6, 1.4],\n            [7.7, 3. , 6.1, 2.3],\n            [6.3, 3.4, 5.6, 2.4],\n            [6.4, 3.1, 5.5, 1.8],\n            [6. , 3. , 4.8, 1.8],\n            [6.9, 3.1, 5.4, 2.1],\n            [6.7, 3.1, 5.6, 2.4],\n            [6.9, 3.1, 5.1, 2.3],\n            [5.8, 2.7, 5.1, 1.9],\n            [6.8, 3.2, 5.9, 2.3],\n            [6.7, 3.3, 5.7, 2.5],\n            [6.7, 3. , 5.2, 2.3],\n            [6.3, 2.5, 5. , 1.9],\n            [6.5, 3. , 5.2, 2. ],\n            [6.2, 3.4, 5.4, 2.3],\n            [5.9, 3. , 5.1, 1.8]]),\n     'feature_names': ['sepal length (cm)',\n      'sepal width (cm)',\n      'petal length (cm)',\n      'petal width (cm)'],\n     'target': array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n            0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n            2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n            2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]),\n     'target_names': array(['setosa', 'versicolor', 'virginica'], dtype='<U10')}\n\n\n\n\n```python\nprint (iris.DESCR)\nprint (iris.data)\nprint (iris.data.shape)\nprint (iris.feature_names)\nprint (iris.target)\nprint (iris.target.shape)\nprint (iris.target_names)\n```\n\n    Iris Plants Database\n    ====================\n    \n    Notes\n    -----\n    Data Set Characteristics:\n        :Number of Instances: 150 (50 in each of three classes)\n        :Number of Attributes: 4 numeric, predictive attributes and the class\n        :Attribute Information:\n            - sepal length in cm\n            - sepal width in cm\n            - petal length in cm\n            - petal width in cm\n            - class:\n                    - Iris-Setosa\n                    - Iris-Versicolour\n                    - Iris-Virginica\n        :Summary Statistics:\n    \n        ============== ==== ==== ======= ===== ====================\n                        Min  Max   Mean    SD   Class Correlation\n        ============== ==== ==== ======= ===== ====================\n        sepal length:   4.3  7.9   5.84   0.83    0.7826\n        sepal width:    2.0  4.4   3.05   0.43   -0.4194\n        petal length:   1.0  6.9   3.76   1.76    0.9490  (high!)\n        petal width:    0.1  2.5   1.20  0.76     0.9565  (high!)\n        ============== ==== ==== ======= ===== ====================\n    \n        :Missing Attribute Values: None\n        :Class Distribution: 33.3% for each of 3 classes.\n        :Creator: R.A. Fisher\n        :Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)\n        :Date: July, 1988\n    \n    This is a copy of UCI ML iris datasets.\n    http://archive.ics.uci.edu/ml/datasets/Iris\n    \n    The famous Iris database, first used by Sir R.A Fisher\n    \n    This is perhaps the best known database to be found in the\n    pattern recognition literature.  Fisher's paper is a classic in the field and\n    is referenced frequently to this day.  (See Duda & Hart, for example.)  The\n    data set contains 3 classes of 50 instances each, where each class refers to a\n    type of iris plant.  One class is linearly separable from the other 2; the\n    latter are NOT linearly separable from each other.\n    \n    References\n    ----------\n       - Fisher,R.A. \"The use of multiple measurements in taxonomic problems\"\n         Annual Eugenics, 7, Part II, 179-188 (1936); also in \"Contributions to\n         Mathematical Statistics\" (John Wiley, NY, 1950).\n       - Duda,R.O., & Hart,P.E. (1973) Pattern Classification and Scene Analysis.\n         (Q327.D83) John Wiley & Sons.  ISBN 0-471-22361-1.  See page 218.\n       - Dasarathy, B.V. (1980) \"Nosing Around the Neighborhood: A New System\n         Structure and Classification Rule for Recognition in Partially Exposed\n         Environments\".  IEEE Transactions on Pattern Analysis and Machine\n         Intelligence, Vol. PAMI-2, No. 1, 67-71.\n       - Gates, G.W. (1972) \"The Reduced Nearest Neighbor Rule\".  IEEE Transactions\n         on Information Theory, May 1972, 431-433.\n       - See also: 1988 MLC Proceedings, 54-64.  Cheeseman et al\"s AUTOCLASS II\n         conceptual clustering system finds 3 classes in the data.\n       - Many, many more ...\n    \n    [[5.1 3.5 1.4 0.2]\n     [4.9 3.  1.4 0.2]\n     [4.7 3.2 1.3 0.2]\n     [4.6 3.1 1.5 0.2]\n     [5.  3.6 1.4 0.2]\n     [5.4 3.9 1.7 0.4]\n     [4.6 3.4 1.4 0.3]\n     [5.  3.4 1.5 0.2]\n     [4.4 2.9 1.4 0.2]\n     [4.9 3.1 1.5 0.1]\n     [5.4 3.7 1.5 0.2]\n     [4.8 3.4 1.6 0.2]\n     [4.8 3.  1.4 0.1]\n     [4.3 3.  1.1 0.1]\n     [5.8 4.  1.2 0.2]\n     [5.7 4.4 1.5 0.4]\n     [5.4 3.9 1.3 0.4]\n     [5.1 3.5 1.4 0.3]\n     [5.7 3.8 1.7 0.3]\n     [5.1 3.8 1.5 0.3]\n     [5.4 3.4 1.7 0.2]\n     [5.1 3.7 1.5 0.4]\n     [4.6 3.6 1.  0.2]\n     [5.1 3.3 1.7 0.5]\n     [4.8 3.4 1.9 0.2]\n     [5.  3.  1.6 0.2]\n     [5.  3.4 1.6 0.4]\n     [5.2 3.5 1.5 0.2]\n     [5.2 3.4 1.4 0.2]\n     [4.7 3.2 1.6 0.2]\n     [4.8 3.1 1.6 0.2]\n     [5.4 3.4 1.5 0.4]\n     [5.2 4.1 1.5 0.1]\n     [5.5 4.2 1.4 0.2]\n     [4.9 3.1 1.5 0.1]\n     [5.  3.2 1.2 0.2]\n     [5.5 3.5 1.3 0.2]\n     [4.9 3.1 1.5 0.1]\n     [4.4 3.  1.3 0.2]\n     [5.1 3.4 1.5 0.2]\n     [5.  3.5 1.3 0.3]\n     [4.5 2.3 1.3 0.3]\n     [4.4 3.2 1.3 0.2]\n     [5.  3.5 1.6 0.6]\n     [5.1 3.8 1.9 0.4]\n     [4.8 3.  1.4 0.3]\n     [5.1 3.8 1.6 0.2]\n     [4.6 3.2 1.4 0.2]\n     [5.3 3.7 1.5 0.2]\n     [5.  3.3 1.4 0.2]\n     [7.  3.2 4.7 1.4]\n     [6.4 3.2 4.5 1.5]\n     [6.9 3.1 4.9 1.5]\n     [5.5 2.3 4.  1.3]\n     [6.5 2.8 4.6 1.5]\n     [5.7 2.8 4.5 1.3]\n     [6.3 3.3 4.7 1.6]\n     [4.9 2.4 3.3 1. ]\n     [6.6 2.9 4.6 1.3]\n     [5.2 2.7 3.9 1.4]\n     [5.  2.  3.5 1. ]\n     [5.9 3.  4.2 1.5]\n     [6.  2.2 4.  1. ]\n     [6.1 2.9 4.7 1.4]\n     [5.6 2.9 3.6 1.3]\n     [6.7 3.1 4.4 1.4]\n     [5.6 3.  4.5 1.5]\n     [5.8 2.7 4.1 1. ]\n     [6.2 2.2 4.5 1.5]\n     [5.6 2.5 3.9 1.1]\n     [5.9 3.2 4.8 1.8]\n     [6.1 2.8 4.  1.3]\n     [6.3 2.5 4.9 1.5]\n     [6.1 2.8 4.7 1.2]\n     [6.4 2.9 4.3 1.3]\n     [6.6 3.  4.4 1.4]\n     [6.8 2.8 4.8 1.4]\n     [6.7 3.  5.  1.7]\n     [6.  2.9 4.5 1.5]\n     [5.7 2.6 3.5 1. ]\n     [5.5 2.4 3.8 1.1]\n     [5.5 2.4 3.7 1. ]\n     [5.8 2.7 3.9 1.2]\n     [6.  2.7 5.1 1.6]\n     [5.4 3.  4.5 1.5]\n     [6.  3.4 4.5 1.6]\n     [6.7 3.1 4.7 1.5]\n     [6.3 2.3 4.4 1.3]\n     [5.6 3.  4.1 1.3]\n     [5.5 2.5 4.  1.3]\n     [5.5 2.6 4.4 1.2]\n     [6.1 3.  4.6 1.4]\n     [5.8 2.6 4.  1.2]\n     [5.  2.3 3.3 1. ]\n     [5.6 2.7 4.2 1.3]\n     [5.7 3.  4.2 1.2]\n     [5.7 2.9 4.2 1.3]\n     [6.2 2.9 4.3 1.3]\n     [5.1 2.5 3.  1.1]\n     [5.7 2.8 4.1 1.3]\n     [6.3 3.3 6.  2.5]\n     [5.8 2.7 5.1 1.9]\n     [7.1 3.  5.9 2.1]\n     [6.3 2.9 5.6 1.8]\n     [6.5 3.  5.8 2.2]\n     [7.6 3.  6.6 2.1]\n     [4.9 2.5 4.5 1.7]\n     [7.3 2.9 6.3 1.8]\n     [6.7 2.5 5.8 1.8]\n     [7.2 3.6 6.1 2.5]\n     [6.5 3.2 5.1 2. ]\n     [6.4 2.7 5.3 1.9]\n     [6.8 3.  5.5 2.1]\n     [5.7 2.5 5.  2. ]\n     [5.8 2.8 5.1 2.4]\n     [6.4 3.2 5.3 2.3]\n     [6.5 3.  5.5 1.8]\n     [7.7 3.8 6.7 2.2]\n     [7.7 2.6 6.9 2.3]\n     [6.  2.2 5.  1.5]\n     [6.9 3.2 5.7 2.3]\n     [5.6 2.8 4.9 2. ]\n     [7.7 2.8 6.7 2. ]\n     [6.3 2.7 4.9 1.8]\n     [6.7 3.3 5.7 2.1]\n     [7.2 3.2 6.  1.8]\n     [6.2 2.8 4.8 1.8]\n     [6.1 3.  4.9 1.8]\n     [6.4 2.8 5.6 2.1]\n     [7.2 3.  5.8 1.6]\n     [7.4 2.8 6.1 1.9]\n     [7.9 3.8 6.4 2. ]\n     [6.4 2.8 5.6 2.2]\n     [6.3 2.8 5.1 1.5]\n     [6.1 2.6 5.6 1.4]\n     [7.7 3.  6.1 2.3]\n     [6.3 3.4 5.6 2.4]\n     [6.4 3.1 5.5 1.8]\n     [6.  3.  4.8 1.8]\n     [6.9 3.1 5.4 2.1]\n     [6.7 3.1 5.6 2.4]\n     [6.9 3.1 5.1 2.3]\n     [5.8 2.7 5.1 1.9]\n     [6.8 3.2 5.9 2.3]\n     [6.7 3.3 5.7 2.5]\n     [6.7 3.  5.2 2.3]\n     [6.3 2.5 5.  1.9]\n     [6.5 3.  5.2 2. ]\n     [6.2 3.4 5.4 2.3]\n     [5.9 3.  5.1 1.8]]\n    (150, 4)\n    ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']\n    [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n     0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n     1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2\n     2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2\n     2 2]\n    (150,)\n    ['setosa' 'versicolor' 'virginica']\n\n\n\n```python\nprint (type(iris.data))\n```\n\n    <class 'numpy.ndarray'>\n\n\n\n```python\nimport pandas as pd\nimport numpy as np\ncolors = list()\npalette = {0: \"red\", 1: \"green\", 2: \"blue\"}\n\nfor c in np.nditer(iris.target): colors.append(palette[int(c)])\ndataframe = pd.DataFrame(iris.data,  columns=iris.feature_names)\n\nsc = pd.scatter_matrix(dataframe, alpha=0.3, figsize=(10, 10), diagonal='hist', \n                       color=colors, marker='o', grid=True)\n```\n\n### MLdata.org public repository\n\n\n```python\nfrom sklearn.datasets import fetch_mldata\nearthquakes = fetch_mldata('global-earthquakes')\nprint (earthquakes.data)\nprint (earthquakes.data.shape)\n```\n\n    [[ 3.460980e+04 -9.210000e+00  1.506300e+02  5.300000e+00]\n     [ 5.222980e+04 -1.501000e+01 -1.739600e+02  5.000000e+00]\n     [ 1.142375e+05 -3.551000e+01 -1.621000e+01  6.000000e+00]\n     ...\n     [ 2.555315e+04 -3.350000e+01 -7.217000e+01  5.000000e+00]\n     [ 8.544900e+04 -3.546000e+01 -7.285000e+01  5.400000e+00]\n     [ 9.303983e+04  5.447000e+01  1.102300e+02  5.300000e+00]]\n    (59209, 4)\n\n\n### LIBSVM data examples\n\n\n```python\nimport urllib\ntarget_page = 'http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary/a1a'\na2a = urllib.request.urlopen(target_page)\n```\n\n\n```python\nfrom sklearn.datasets import load_svmlight_file\nX_train, y_train = load_svmlight_file(a2a)\nprint (X_train.shape, y_train.shape)\n```\n\n    (1605, 119) (1605,)\n\n\n### Loading data directly from CSV or text files\n\n\n```python\nhousing = np.loadtxt('regression-datasets-housing.csv',delimiter=',')\nprint (type(housing))\n```\n\n    <class 'numpy.ndarray'>\n\n\n\n```python\nprint (housing.shape)\n```\n\n    (506, 14)\n\n\n\n```python\nhousing_int = housing.astype(int)\n```\n\n\n```python\nprint (housing[0,:3], '\\n', housing_int[0,:3])\n```\n\n    [6.32e-03 1.80e+01 2.31e+00] \n     [ 0 18  2]\n\n\n\n```python\niris_filename = 'datasets-uci-iris.csv'\niris = pd.read_csv(iris_filename, sep=',', decimal='.',header=None,\n                   names= ['sepal_length', 'sepal_width', 'petal_length','petal_width', 'target'])\nprint (type(iris))\n```\n\n    <class 'pandas.core.frame.DataFrame'>\n\n\n\n```python\niris_data = iris.values[:,:4]\niris_target, iris_target_labels = pd.factorize(iris.target)\nprint (iris_data.shape, iris_target.shape)\n```\n\n    (150, 4) (150,)\n\n\n### Scikit-learn sample generators\n\n\n```python\nfrom sklearn import datasets \nX,y = datasets.make_classification(n_samples=10**6,n_features=10, random_state=101)\nprint (X.shape,  y.shape)\n```\n\n    (1000000, 10) (1000000,)\n\n\n\n```python\ndatasets.make_classification(1, n_features=4, random_state=101)\n```\n\n\n\n\n    (array([[-3.31994186, -2.39469384, -2.35882002,  1.40145585]]), array([0]))\n\n\n\n\n```python\n%timeit X,y = datasets.make_classification(n_samples=10**6,n_features=10, random_state=101)\n```\n\n    1 loop, best of 3: 751 ms per loop\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "ff6aafe802592a909c319b9ed14b459a2dbdd119", "size": 362989, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Section01/Section 1.ipynb", "max_stars_repo_name": "PacktPublishing/Python-Data-Science-Essentials", "max_stars_repo_head_hexsha": "35b5ca67cc1ae63f0f0d704e9c5655fcfec86d4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2018-06-28T04:50:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T20:00:54.000Z", "max_issues_repo_path": "Section01/Section 1.ipynb", "max_issues_repo_name": "PacktPublishing/Python-Data-Science-Essentials", "max_issues_repo_head_hexsha": "35b5ca67cc1ae63f0f0d704e9c5655fcfec86d4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Section01/Section 1.ipynb", "max_forks_repo_name": "PacktPublishing/Python-Data-Science-Essentials", "max_forks_repo_head_hexsha": "35b5ca67cc1ae63f0f0d704e9c5655fcfec86d4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2018-07-02T16:45:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-07T01:50:12.000Z", "avg_line_length": 243.4533869886, "max_line_length": 159840, "alphanum_fraction": 0.8861838789, "converted": true, "num_tokens": 13149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06097517574577168, "lm_q2_score": 0.06853749778844886, "lm_q1q2_score": 0.004179085972826108}}
{"text": "<a href=\"https://colab.research.google.com/github/XiaoZheng-YY/EEG-DL/blob/master/dqn_CartPole.ipynb\" target=\"_parent\"></a>\n\nBefore we start the tutorial, we need to install some dependencies to render and capture images from OpenAI Gym. It may take some time to set up the environment.\n\n\n```\n!apt-get update\n!apt-get install cmake zlib1g-dev libjpeg-dev xvfb xorg-dev libboost-all-dev libsdl2-dev swig python3-dev python3-future python-opengl x11-utils\n\n!apt-get -qq -y install libcusparse9.1 libnvrtc9.1 libnvtoolsext1 > /dev/null\n!ln -snf /usr/lib/x86_64-linux-gnu/libnvrtc-builtins.so.9.1 /usr/lib/x86_64-linux-gnu/libnvrtc-builtins.so\n!apt-get -qq -y install xvfb freeglut3-dev ffmpeg> /dev/null\n\n!apt-get install xserver-xorg libglu1-mesa-dev mesa-common-dev libxmu-dev libxi-dev\n```\n\n    Get:1 http://security.ubuntu.com/ubuntu bionic-security InRelease [88.7 kB]\n    Get:2 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran40/ InRelease [3,626 B]\n    Ign:3 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64  InRelease\n    Hit:4 http://archive.ubuntu.com/ubuntu bionic InRelease\n    Get:5 http://ppa.launchpad.net/c2d4u.team/c2d4u4.0+/ubuntu bionic InRelease [15.9 kB]\n    Ign:6 https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64  InRelease\n    Get:7 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64  Release [697 B]\n    Hit:8 https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64  Release\n    Get:9 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64  Release.gpg [836 B]\n    Get:10 http://archive.ubuntu.com/ubuntu bionic-updates InRelease [88.7 kB]\n    Get:11 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran40/ Packages [60.5 kB]\n    Hit:12 http://ppa.launchpad.net/cran/libgit2/ubuntu bionic InRelease\n    Get:13 http://archive.ubuntu.com/ubuntu bionic-backports InRelease [74.6 kB]\n    Hit:14 http://ppa.launchpad.net/deadsnakes/ppa/ubuntu bionic InRelease\n    Get:15 http://security.ubuntu.com/ubuntu bionic-security/restricted amd64 Packages [423 kB]\n    Get:16 http://security.ubuntu.com/ubuntu bionic-security/main amd64 Packages [2,152 kB]\n    Get:17 http://ppa.launchpad.net/graphics-drivers/ppa/ubuntu bionic InRelease [21.3 kB]\n    Get:18 http://security.ubuntu.com/ubuntu bionic-security/universe amd64 Packages [1,412 kB]\n    Ign:20 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64  Packages\n    Get:20 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64  Packages [796 kB]\n    Get:21 http://ppa.launchpad.net/c2d4u.team/c2d4u4.0+/ubuntu bionic/main Sources [1,767 kB]\n    Get:22 http://archive.ubuntu.com/ubuntu bionic-updates/restricted amd64 Packages [452 kB]\n    Get:23 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 Packages [2,183 kB]\n    Get:24 http://ppa.launchpad.net/c2d4u.team/c2d4u4.0+/ubuntu bionic/main amd64 Packages [904 kB]\n    Get:25 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 Packages [2,583 kB]\n    Get:26 http://ppa.launchpad.net/graphics-drivers/ppa/ubuntu bionic/main amd64 Packages [41.5 kB]\n    Fetched 13.1 MB in 4s (3,509 kB/s)\n    Reading package lists... Done\n    Reading package lists... Done\n    Building dependency tree       \n    Reading state information... Done\n    libjpeg-dev is already the newest version (8c-2ubuntu8).\n    libjpeg-dev set to manually installed.\n    zlib1g-dev is already the newest version (1:1.2.11.dfsg-0ubuntu2).\n    zlib1g-dev set to manually installed.\n    libboost-all-dev is already the newest version (1.65.1.0ubuntu1).\n    cmake is already the newest version (3.10.2-1ubuntu2.18.04.1).\n    python3-dev is already the newest version (3.6.7-1~18.04).\n    python3-dev set to manually installed.\n    The following package was automatically installed and is no longer required:\n      libnvidia-common-460\n    Use 'apt autoremove' to remove it.\n    The following additional packages will be installed:\n      gir1.2-ibus-1.0 libcapnp-0.6.1 libdbus-1-dev libdmx-dev libdmx1\n      libfontenc-dev libfs-dev libfs6 libibus-1.0-5 libibus-1.0-dev\n      libmirclient-dev libmirclient9 libmircommon-dev libmircommon7\n      libmircookie-dev libmircookie2 libmircore-dev libmircore1 libmirprotobuf3\n      libpciaccess-dev libpixman-1-dev libprotobuf-dev libprotobuf-lite10\n      libpulse-dev libpulse-mainloop-glib0 libsndio-dev libudev-dev libxaw7-dev\n      libxcomposite-dev libxcursor-dev libxfont-dev libxinerama-dev\n      libxkbcommon-dev libxkbfile-dev libxmuu-dev libxpm-dev libxrandr-dev\n      libxres-dev libxres1 libxtst-dev libxv-dev libxvmc-dev libxvmc1\n      libxxf86dga-dev libxxf86dga1 mir-client-platform-mesa-dev swig3.0\n      x11proto-composite-dev x11proto-dri2-dev x11proto-fonts-dev x11proto-gl-dev\n      x11proto-randr-dev x11proto-record-dev x11proto-render-dev\n      x11proto-resource-dev x11proto-xf86bigfont-dev x11proto-xf86dga-dev\n      x11proto-xinerama-dev xserver-xorg-dev\n    Suggested packages:\n      libxaw-doc libgle3 python-future-doc swig-doc swig-examples swig3.0-examples\n      swig3.0-doc mesa-utils\n    The following NEW packages will be installed:\n      gir1.2-ibus-1.0 libcapnp-0.6.1 libdbus-1-dev libdmx-dev libdmx1\n      libfontenc-dev libfs-dev libfs6 libibus-1.0-5 libibus-1.0-dev\n      libmirclient-dev libmirclient9 libmircommon-dev libmircommon7\n      libmircookie-dev libmircookie2 libmircore-dev libmircore1 libmirprotobuf3\n      libpciaccess-dev libpixman-1-dev libprotobuf-dev libprotobuf-lite10\n      libpulse-dev libpulse-mainloop-glib0 libsdl2-dev libsndio-dev libudev-dev\n      libxaw7-dev libxcomposite-dev libxcursor-dev libxfont-dev libxinerama-dev\n      libxkbcommon-dev libxkbfile-dev libxmuu-dev libxpm-dev libxrandr-dev\n      libxres-dev libxres1 libxtst-dev libxv-dev libxvmc-dev libxvmc1\n      libxxf86dga-dev libxxf86dga1 mir-client-platform-mesa-dev python-opengl\n      python3-future swig swig3.0 x11-utils x11proto-composite-dev\n      x11proto-dri2-dev x11proto-fonts-dev x11proto-gl-dev x11proto-randr-dev\n      x11proto-record-dev x11proto-render-dev x11proto-resource-dev\n      x11proto-xf86bigfont-dev x11proto-xf86dga-dev x11proto-xinerama-dev xorg-dev\n      xserver-xorg-dev xvfb\n    0 upgraded, 66 newly installed, 0 to remove and 72 not upgraded.\n    Need to get 7,968 kB of archives.\n    After this operation, 46.2 MB of additional disk space will be used.\n    Get:1 http://archive.ubuntu.com/ubuntu bionic/main amd64 libdmx1 amd64 1:1.1.3-1 [10.4 kB]\n    Get:2 http://archive.ubuntu.com/ubuntu bionic/main amd64 libxxf86dga1 amd64 2:1.1.4-1 [13.7 kB]\n    Get:3 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libibus-1.0-5 amd64 1.5.17-3ubuntu5.3 [133 kB]\n    Get:4 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 gir1.2-ibus-1.0 amd64 1.5.17-3ubuntu5.3 [66.5 kB]\n    Get:5 http://archive.ubuntu.com/ubuntu bionic/main amd64 libcapnp-0.6.1 amd64 0.6.1-1ubuntu1 [658 kB]\n    Get:6 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libdbus-1-dev amd64 1.12.2-1ubuntu1.2 [165 kB]\n    Get:7 http://archive.ubuntu.com/ubuntu bionic/main amd64 libdmx-dev amd64 1:1.1.3-1 [34.4 kB]\n    Get:8 http://archive.ubuntu.com/ubuntu bionic/main amd64 libfontenc-dev amd64 1:1.1.3-1 [13.8 kB]\n    Get:9 http://archive.ubuntu.com/ubuntu bionic/main amd64 libfs6 amd64 2:1.0.7-1 [22.5 kB]\n    Get:10 http://archive.ubuntu.com/ubuntu bionic/main amd64 x11proto-fonts-dev all 2018.4-4 [2,620 B]\n    Get:11 http://archive.ubuntu.com/ubuntu bionic/main amd64 libfs-dev amd64 2:1.0.7-1 [26.8 kB]\n    Get:12 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libibus-1.0-dev amd64 1.5.17-3ubuntu5.3 [145 kB]\n    Get:13 http://archive.ubuntu.com/ubuntu bionic/main amd64 libmircore1 amd64 0.31.1-0ubuntu1 [26.5 kB]\n    Get:14 http://archive.ubuntu.com/ubuntu bionic/main amd64 libmircommon7 amd64 0.31.1-0ubuntu1 [73.9 kB]\n    Get:15 http://archive.ubuntu.com/ubuntu bionic/main amd64 libprotobuf-lite10 amd64 3.0.0-9.1ubuntu1 [97.7 kB]\n    Get:16 http://archive.ubuntu.com/ubuntu bionic/main amd64 libmirprotobuf3 amd64 0.31.1-0ubuntu1 [127 kB]\n    Get:17 http://archive.ubuntu.com/ubuntu bionic/main amd64 libmirclient9 amd64 0.31.1-0ubuntu1 [199 kB]\n    Get:18 http://archive.ubuntu.com/ubuntu bionic/main amd64 libmircore-dev amd64 0.31.1-0ubuntu1 [21.7 kB]\n    Get:19 http://archive.ubuntu.com/ubuntu bionic/main amd64 libprotobuf-dev amd64 3.0.0-9.1ubuntu1 [959 kB]\n    Get:20 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libxkbcommon-dev amd64 0.8.2-1~ubuntu18.04.1 [150 kB]\n    Get:21 http://archive.ubuntu.com/ubuntu bionic/main amd64 libmircommon-dev amd64 0.31.1-0ubuntu1 [13.9 kB]\n    Get:22 http://archive.ubuntu.com/ubuntu bionic/main amd64 libmircookie2 amd64 0.31.1-0ubuntu1 [19.7 kB]\n    Get:23 http://archive.ubuntu.com/ubuntu bionic/main amd64 libmircookie-dev amd64 0.31.1-0ubuntu1 [4,392 B]\n    Get:24 http://archive.ubuntu.com/ubuntu bionic/main amd64 libmirclient-dev amd64 0.31.1-0ubuntu1 [47.8 kB]\n    Get:25 http://archive.ubuntu.com/ubuntu bionic/main amd64 libpixman-1-dev amd64 0.34.0-2 [244 kB]\n    Get:26 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libpulse-mainloop-glib0 amd64 1:11.1-1ubuntu7.11 [22.1 kB]\n    Get:27 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libpulse-dev amd64 1:11.1-1ubuntu7.11 [81.5 kB]\n    Get:28 http://archive.ubuntu.com/ubuntu bionic/universe amd64 libsndio-dev amd64 1.1.0-3 [13.3 kB]\n    Get:29 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libudev-dev amd64 237-3ubuntu10.47 [19.1 kB]\n    Get:30 http://archive.ubuntu.com/ubuntu bionic/main amd64 libxcursor-dev amd64 1:1.1.15-1 [26.5 kB]\n    Get:31 http://archive.ubuntu.com/ubuntu bionic/main amd64 x11proto-xinerama-dev all 2018.4-4 [2,628 B]\n    Get:32 http://archive.ubuntu.com/ubuntu bionic/main amd64 libxinerama-dev amd64 2:1.1.3-1 [8,404 B]\n    Get:33 http://archive.ubuntu.com/ubuntu bionic/main amd64 x11proto-randr-dev all 2018.4-4 [2,620 B]\n    Get:34 http://archive.ubuntu.com/ubuntu bionic/main amd64 libxrandr-dev amd64 2:1.5.1-1 [24.0 kB]\n    Get:35 http://archive.ubuntu.com/ubuntu bionic/main amd64 libxv-dev amd64 2:1.0.11-1 [32.5 kB]\n    Get:36 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 libsdl2-dev amd64 2.0.8+dfsg1-1ubuntu1.18.04.4 [683 kB]\n    Get:37 http://archive.ubuntu.com/ubuntu bionic/main amd64 libxpm-dev amd64 1:3.5.12-1 [87.4 kB]\n    Get:38 http://archive.ubuntu.com/ubuntu bionic/main amd64 libxaw7-dev amd64 2:1.0.13-1 [231 kB]\n    Get:39 http://archive.ubuntu.com/ubuntu bionic/main amd64 x11proto-composite-dev all 1:2018.4-4 [2,620 B]\n    Get:40 http://archive.ubuntu.com/ubuntu bionic/main amd64 libxcomposite-dev amd64 1:0.4.4-2 [9,136 B]\n    Get:41 http://archive.ubuntu.com/ubuntu bionic/main amd64 libxfont-dev amd64 1:2.0.3-1 [118 kB]\n    Get:42 http://archive.ubuntu.com/ubuntu bionic/main amd64 libxkbfile-dev amd64 1:1.0.9-2 [74.3 kB]\n    Get:43 http://archive.ubuntu.com/ubuntu bionic/main amd64 libxmuu-dev amd64 2:1.1.2-2 [7,056 B]\n    Get:44 http://archive.ubuntu.com/ubuntu bionic/main amd64 libxres1 amd64 2:1.2.0-2 [7,716 B]\n    Get:45 http://archive.ubuntu.com/ubuntu bionic/main amd64 x11proto-resource-dev all 2018.4-4 [2,620 B]\n    Get:46 http://archive.ubuntu.com/ubuntu bionic/main amd64 libxres-dev amd64 2:1.2.0-2 [8,136 B]\n    Get:47 http://archive.ubuntu.com/ubuntu bionic/main amd64 x11proto-record-dev all 2018.4-4 [2,620 B]\n    Get:48 http://archive.ubuntu.com/ubuntu bionic/main amd64 libxtst-dev amd64 2:1.2.3-1 [15.2 kB]\n    Get:49 http://archive.ubuntu.com/ubuntu bionic/main amd64 libxvmc1 amd64 2:1.0.10-1 [13.7 kB]\n    Get:50 http://archive.ubuntu.com/ubuntu bionic/main amd64 libxvmc-dev amd64 2:1.0.10-1 [21.3 kB]\n    Get:51 http://archive.ubuntu.com/ubuntu bionic/main amd64 x11proto-xf86dga-dev all 2018.4-4 [2,624 B]\n    Get:52 http://archive.ubuntu.com/ubuntu bionic/main amd64 libxxf86dga-dev amd64 2:1.1.4-1 [17.6 kB]\n    Get:53 http://archive.ubuntu.com/ubuntu bionic/main amd64 mir-client-platform-mesa-dev amd64 0.31.1-0ubuntu1 [11.0 kB]\n    Get:54 http://archive.ubuntu.com/ubuntu bionic/universe amd64 python-opengl all 3.1.0+dfsg-1 [496 kB]\n    Get:55 http://archive.ubuntu.com/ubuntu bionic/universe amd64 python3-future all 0.15.2-4ubuntu2 [333 kB]\n    Get:56 http://archive.ubuntu.com/ubuntu bionic/universe amd64 swig3.0 amd64 3.0.12-1 [1,094 kB]\n    Get:57 http://archive.ubuntu.com/ubuntu bionic/universe amd64 swig amd64 3.0.12-1 [6,460 B]\n    Get:58 http://archive.ubuntu.com/ubuntu bionic/main amd64 x11-utils amd64 7.7+3build1 [196 kB]\n    Get:59 http://archive.ubuntu.com/ubuntu bionic/main amd64 x11proto-dri2-dev all 2018.4-4 [2,620 B]\n    Get:60 http://archive.ubuntu.com/ubuntu bionic/main amd64 x11proto-gl-dev all 2018.4-4 [2,612 B]\n    Get:61 http://archive.ubuntu.com/ubuntu bionic/main amd64 x11proto-render-dev all 2:2018.4-4 [2,620 B]\n    Get:62 http://archive.ubuntu.com/ubuntu bionic/main amd64 x11proto-xf86bigfont-dev all 2018.4-4 [2,628 B]\n    Get:63 http://archive.ubuntu.com/ubuntu bionic/main amd64 libpciaccess-dev amd64 0.14-1 [20.2 kB]\n    Get:64 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 xserver-xorg-dev amd64 2:1.19.6-1ubuntu4.9 [198 kB]\n    Get:65 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 xorg-dev all 1:7.7+19ubuntu7.1 [4,300 B]\n    Get:66 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 xvfb amd64 2:1.19.6-1ubuntu4.9 [784 kB]\n    Fetched 7,968 kB in 2s (4,067 kB/s)\n    Extracting templates from packages: 100%\n    Selecting previously unselected package libdmx1:amd64.\n    (Reading database ... 160706 files and directories currently installed.)\n    Preparing to unpack .../00-libdmx1_1%3a1.1.3-1_amd64.deb ...\n    Unpacking libdmx1:amd64 (1:1.1.3-1) ...\n    Selecting previously unselected package libxxf86dga1:amd64.\n    Preparing to unpack .../01-libxxf86dga1_2%3a1.1.4-1_amd64.deb ...\n    Unpacking libxxf86dga1:amd64 (2:1.1.4-1) ...\n    Selecting previously unselected package libibus-1.0-5:amd64.\n    Preparing to unpack .../02-libibus-1.0-5_1.5.17-3ubuntu5.3_amd64.deb ...\n    Unpacking libibus-1.0-5:amd64 (1.5.17-3ubuntu5.3) ...\n    Selecting previously unselected package gir1.2-ibus-1.0:amd64.\n    Preparing to unpack .../03-gir1.2-ibus-1.0_1.5.17-3ubuntu5.3_amd64.deb ...\n    Unpacking gir1.2-ibus-1.0:amd64 (1.5.17-3ubuntu5.3) ...\n    Selecting previously unselected package libcapnp-0.6.1:amd64.\n    Preparing to unpack .../04-libcapnp-0.6.1_0.6.1-1ubuntu1_amd64.deb ...\n    Unpacking libcapnp-0.6.1:amd64 (0.6.1-1ubuntu1) ...\n    Selecting previously unselected package libdbus-1-dev:amd64.\n    Preparing to unpack .../05-libdbus-1-dev_1.12.2-1ubuntu1.2_amd64.deb ...\n    Unpacking libdbus-1-dev:amd64 (1.12.2-1ubuntu1.2) ...\n    Selecting previously unselected package libdmx-dev:amd64.\n    Preparing to unpack .../06-libdmx-dev_1%3a1.1.3-1_amd64.deb ...\n    Unpacking libdmx-dev:amd64 (1:1.1.3-1) ...\n    Selecting previously unselected package libfontenc-dev:amd64.\n    Preparing to unpack .../07-libfontenc-dev_1%3a1.1.3-1_amd64.deb ...\n    Unpacking libfontenc-dev:amd64 (1:1.1.3-1) ...\n    Selecting previously unselected package libfs6:amd64.\n    Preparing to unpack .../08-libfs6_2%3a1.0.7-1_amd64.deb ...\n    Unpacking libfs6:amd64 (2:1.0.7-1) ...\n    Selecting previously unselected package x11proto-fonts-dev.\n    Preparing to unpack .../09-x11proto-fonts-dev_2018.4-4_all.deb ...\n    Unpacking x11proto-fonts-dev (2018.4-4) ...\n    Selecting previously unselected package libfs-dev:amd64.\n    Preparing to unpack .../10-libfs-dev_2%3a1.0.7-1_amd64.deb ...\n    Unpacking libfs-dev:amd64 (2:1.0.7-1) ...\n    Selecting previously unselected package libibus-1.0-dev:amd64.\n    Preparing to unpack .../11-libibus-1.0-dev_1.5.17-3ubuntu5.3_amd64.deb ...\n    Unpacking libibus-1.0-dev:amd64 (1.5.17-3ubuntu5.3) ...\n    Selecting previously unselected package libmircore1:amd64.\n    Preparing to unpack .../12-libmircore1_0.31.1-0ubuntu1_amd64.deb ...\n    Unpacking libmircore1:amd64 (0.31.1-0ubuntu1) ...\n    Selecting previously unselected package libmircommon7:amd64.\n    Preparing to unpack .../13-libmircommon7_0.31.1-0ubuntu1_amd64.deb ...\n    Unpacking libmircommon7:amd64 (0.31.1-0ubuntu1) ...\n    Selecting previously unselected package libprotobuf-lite10:amd64.\n    Preparing to unpack .../14-libprotobuf-lite10_3.0.0-9.1ubuntu1_amd64.deb ...\n    Unpacking libprotobuf-lite10:amd64 (3.0.0-9.1ubuntu1) ...\n    Selecting previously unselected package libmirprotobuf3:amd64.\n    Preparing to unpack .../15-libmirprotobuf3_0.31.1-0ubuntu1_amd64.deb ...\n    Unpacking libmirprotobuf3:amd64 (0.31.1-0ubuntu1) ...\n    Selecting previously unselected package libmirclient9:amd64.\n    Preparing to unpack .../16-libmirclient9_0.31.1-0ubuntu1_amd64.deb ...\n    Unpacking libmirclient9:amd64 (0.31.1-0ubuntu1) ...\n    Selecting previously unselected package libmircore-dev:amd64.\n    Preparing to unpack .../17-libmircore-dev_0.31.1-0ubuntu1_amd64.deb ...\n    Unpacking libmircore-dev:amd64 (0.31.1-0ubuntu1) ...\n    Selecting previously unselected package libprotobuf-dev:amd64.\n    Preparing to unpack .../18-libprotobuf-dev_3.0.0-9.1ubuntu1_amd64.deb ...\n    Unpacking libprotobuf-dev:amd64 (3.0.0-9.1ubuntu1) ...\n    Selecting previously unselected package libxkbcommon-dev:amd64.\n    Preparing to unpack .../19-libxkbcommon-dev_0.8.2-1~ubuntu18.04.1_amd64.deb ...\n    Unpacking libxkbcommon-dev:amd64 (0.8.2-1~ubuntu18.04.1) ...\n    Selecting previously unselected package libmircommon-dev:amd64.\n    Preparing to unpack .../20-libmircommon-dev_0.31.1-0ubuntu1_amd64.deb ...\n    Unpacking libmircommon-dev:amd64 (0.31.1-0ubuntu1) ...\n    Selecting previously unselected package libmircookie2:amd64.\n    Preparing to unpack .../21-libmircookie2_0.31.1-0ubuntu1_amd64.deb ...\n    Unpacking libmircookie2:amd64 (0.31.1-0ubuntu1) ...\n    Selecting previously unselected package libmircookie-dev:amd64.\n    Preparing to unpack .../22-libmircookie-dev_0.31.1-0ubuntu1_amd64.deb ...\n    Unpacking libmircookie-dev:amd64 (0.31.1-0ubuntu1) ...\n    Selecting previously unselected package libmirclient-dev:amd64.\n    Preparing to unpack .../23-libmirclient-dev_0.31.1-0ubuntu1_amd64.deb ...\n    Unpacking libmirclient-dev:amd64 (0.31.1-0ubuntu1) ...\n    Selecting previously unselected package libpixman-1-dev:amd64.\n    Preparing to unpack .../24-libpixman-1-dev_0.34.0-2_amd64.deb ...\n    Unpacking libpixman-1-dev:amd64 (0.34.0-2) ...\n    Selecting previously unselected package libpulse-mainloop-glib0:amd64.\n    Preparing to unpack .../25-libpulse-mainloop-glib0_1%3a11.1-1ubuntu7.11_amd64.deb ...\n    Unpacking libpulse-mainloop-glib0:amd64 (1:11.1-1ubuntu7.11) ...\n    Selecting previously unselected package libpulse-dev:amd64.\n    Preparing to unpack .../26-libpulse-dev_1%3a11.1-1ubuntu7.11_amd64.deb ...\n    Unpacking libpulse-dev:amd64 (1:11.1-1ubuntu7.11) ...\n    Selecting previously unselected package libsndio-dev:amd64.\n    Preparing to unpack .../27-libsndio-dev_1.1.0-3_amd64.deb ...\n    Unpacking libsndio-dev:amd64 (1.1.0-3) ...\n    Selecting previously unselected package libudev-dev:amd64.\n    Preparing to unpack .../28-libudev-dev_237-3ubuntu10.47_amd64.deb ...\n    Unpacking libudev-dev:amd64 (237-3ubuntu10.47) ...\n    Selecting previously unselected package libxcursor-dev:amd64.\n    Preparing to unpack .../29-libxcursor-dev_1%3a1.1.15-1_amd64.deb ...\n    Unpacking libxcursor-dev:amd64 (1:1.1.15-1) ...\n    Selecting previously unselected package x11proto-xinerama-dev.\n    Preparing to unpack .../30-x11proto-xinerama-dev_2018.4-4_all.deb ...\n    Unpacking x11proto-xinerama-dev (2018.4-4) ...\n    Selecting previously unselected package libxinerama-dev:amd64.\n    Preparing to unpack .../31-libxinerama-dev_2%3a1.1.3-1_amd64.deb ...\n    Unpacking libxinerama-dev:amd64 (2:1.1.3-1) ...\n    Selecting previously unselected package x11proto-randr-dev.\n    Preparing to unpack .../32-x11proto-randr-dev_2018.4-4_all.deb ...\n    Unpacking x11proto-randr-dev (2018.4-4) ...\n    Selecting previously unselected package libxrandr-dev:amd64.\n    Preparing to unpack .../33-libxrandr-dev_2%3a1.5.1-1_amd64.deb ...\n    Unpacking libxrandr-dev:amd64 (2:1.5.1-1) ...\n    Selecting previously unselected package libxv-dev:amd64.\n    Preparing to unpack .../34-libxv-dev_2%3a1.0.11-1_amd64.deb ...\n    Unpacking libxv-dev:amd64 (2:1.0.11-1) ...\n    Selecting previously unselected package libsdl2-dev:amd64.\n    Preparing to unpack .../35-libsdl2-dev_2.0.8+dfsg1-1ubuntu1.18.04.4_amd64.deb ...\n    Unpacking libsdl2-dev:amd64 (2.0.8+dfsg1-1ubuntu1.18.04.4) ...\n    Selecting previously unselected package libxpm-dev:amd64.\n    Preparing to unpack .../36-libxpm-dev_1%3a3.5.12-1_amd64.deb ...\n    Unpacking libxpm-dev:amd64 (1:3.5.12-1) ...\n    Selecting previously unselected package libxaw7-dev:amd64.\n    Preparing to unpack .../37-libxaw7-dev_2%3a1.0.13-1_amd64.deb ...\n    Unpacking libxaw7-dev:amd64 (2:1.0.13-1) ...\n    Selecting previously unselected package x11proto-composite-dev.\n    Preparing to unpack .../38-x11proto-composite-dev_1%3a2018.4-4_all.deb ...\n    Unpacking x11proto-composite-dev (1:2018.4-4) ...\n    Selecting previously unselected package libxcomposite-dev:amd64.\n    Preparing to unpack .../39-libxcomposite-dev_1%3a0.4.4-2_amd64.deb ...\n    Unpacking libxcomposite-dev:amd64 (1:0.4.4-2) ...\n    Selecting previously unselected package libxfont-dev.\n    Preparing to unpack .../40-libxfont-dev_1%3a2.0.3-1_amd64.deb ...\n    Unpacking libxfont-dev (1:2.0.3-1) ...\n    Selecting previously unselected package libxkbfile-dev:amd64.\n    Preparing to unpack .../41-libxkbfile-dev_1%3a1.0.9-2_amd64.deb ...\n    Unpacking libxkbfile-dev:amd64 (1:1.0.9-2) ...\n    Selecting previously unselected package libxmuu-dev:amd64.\n    Preparing to unpack .../42-libxmuu-dev_2%3a1.1.2-2_amd64.deb ...\n    Unpacking libxmuu-dev:amd64 (2:1.1.2-2) ...\n    Selecting previously unselected package libxres1:amd64.\n    Preparing to unpack .../43-libxres1_2%3a1.2.0-2_amd64.deb ...\n    Unpacking libxres1:amd64 (2:1.2.0-2) ...\n    Selecting previously unselected package x11proto-resource-dev.\n    Preparing to unpack .../44-x11proto-resource-dev_2018.4-4_all.deb ...\n    Unpacking x11proto-resource-dev (2018.4-4) ...\n    Selecting previously unselected package libxres-dev.\n    Preparing to unpack .../45-libxres-dev_2%3a1.2.0-2_amd64.deb ...\n    Unpacking libxres-dev (2:1.2.0-2) ...\n    Selecting previously unselected package x11proto-record-dev.\n    Preparing to unpack .../46-x11proto-record-dev_2018.4-4_all.deb ...\n    Unpacking x11proto-record-dev (2018.4-4) ...\n    Selecting previously unselected package libxtst-dev:amd64.\n    Preparing to unpack .../47-libxtst-dev_2%3a1.2.3-1_amd64.deb ...\n    Unpacking libxtst-dev:amd64 (2:1.2.3-1) ...\n    Selecting previously unselected package libxvmc1:amd64.\n    Preparing to unpack .../48-libxvmc1_2%3a1.0.10-1_amd64.deb ...\n    Unpacking libxvmc1:amd64 (2:1.0.10-1) ...\n    Selecting previously unselected package libxvmc-dev:amd64.\n    Preparing to unpack .../49-libxvmc-dev_2%3a1.0.10-1_amd64.deb ...\n    Unpacking libxvmc-dev:amd64 (2:1.0.10-1) ...\n    Selecting previously unselected package x11proto-xf86dga-dev.\n    Preparing to unpack .../50-x11proto-xf86dga-dev_2018.4-4_all.deb ...\n    Unpacking x11proto-xf86dga-dev (2018.4-4) ...\n    Selecting previously unselected package libxxf86dga-dev:amd64.\n    Preparing to unpack .../51-libxxf86dga-dev_2%3a1.1.4-1_amd64.deb ...\n    Unpacking libxxf86dga-dev:amd64 (2:1.1.4-1) ...\n    Selecting previously unselected package mir-client-platform-mesa-dev:amd64.\n    Preparing to unpack .../52-mir-client-platform-mesa-dev_0.31.1-0ubuntu1_amd64.deb ...\n    Unpacking mir-client-platform-mesa-dev:amd64 (0.31.1-0ubuntu1) ...\n    Selecting previously unselected package python-opengl.\n    Preparing to unpack .../53-python-opengl_3.1.0+dfsg-1_all.deb ...\n    Unpacking python-opengl (3.1.0+dfsg-1) ...\n    Selecting previously unselected package python3-future.\n    Preparing to unpack .../54-python3-future_0.15.2-4ubuntu2_all.deb ...\n    Unpacking python3-future (0.15.2-4ubuntu2) ...\n    Selecting previously unselected package swig3.0.\n    Preparing to unpack .../55-swig3.0_3.0.12-1_amd64.deb ...\n    Unpacking swig3.0 (3.0.12-1) ...\n    Selecting previously unselected package swig.\n    Preparing to unpack .../56-swig_3.0.12-1_amd64.deb ...\n    Unpacking swig (3.0.12-1) ...\n    Selecting previously unselected package x11-utils.\n    Preparing to unpack .../57-x11-utils_7.7+3build1_amd64.deb ...\n    Unpacking x11-utils (7.7+3build1) ...\n    Selecting previously unselected package x11proto-dri2-dev.\n    Preparing to unpack .../58-x11proto-dri2-dev_2018.4-4_all.deb ...\n    Unpacking x11proto-dri2-dev (2018.4-4) ...\n    Selecting previously unselected package x11proto-gl-dev.\n    Preparing to unpack .../59-x11proto-gl-dev_2018.4-4_all.deb ...\n    Unpacking x11proto-gl-dev (2018.4-4) ...\n    Selecting previously unselected package x11proto-render-dev.\n    Preparing to unpack .../60-x11proto-render-dev_2%3a2018.4-4_all.deb ...\n    Unpacking x11proto-render-dev (2:2018.4-4) ...\n    Selecting previously unselected package x11proto-xf86bigfont-dev.\n    Preparing to unpack .../61-x11proto-xf86bigfont-dev_2018.4-4_all.deb ...\n    Unpacking x11proto-xf86bigfont-dev (2018.4-4) ...\n    Selecting previously unselected package libpciaccess-dev:amd64.\n    Preparing to unpack .../62-libpciaccess-dev_0.14-1_amd64.deb ...\n    Unpacking libpciaccess-dev:amd64 (0.14-1) ...\n    Selecting previously unselected package xserver-xorg-dev.\n    Preparing to unpack .../63-xserver-xorg-dev_2%3a1.19.6-1ubuntu4.9_amd64.deb ...\n    Unpacking xserver-xorg-dev (2:1.19.6-1ubuntu4.9) ...\n    Selecting previously unselected package xorg-dev.\n    Preparing to unpack .../64-xorg-dev_1%3a7.7+19ubuntu7.1_all.deb ...\n    Unpacking xorg-dev (1:7.7+19ubuntu7.1) ...\n    Selecting previously unselected package xvfb.\n    Preparing to unpack .../65-xvfb_2%3a1.19.6-1ubuntu4.9_amd64.deb ...\n    Unpacking xvfb (2:1.19.6-1ubuntu4.9) ...\n    Setting up x11proto-fonts-dev (2018.4-4) ...\n    Setting up x11proto-dri2-dev (2018.4-4) ...\n    Setting up libdbus-1-dev:amd64 (1.12.2-1ubuntu1.2) ...\n    Setting up libxcursor-dev:amd64 (1:1.1.15-1) ...\n    Setting up libxkbcommon-dev:amd64 (0.8.2-1~ubuntu18.04.1) ...\n    Setting up libpulse-mainloop-glib0:amd64 (1:11.1-1ubuntu7.11) ...\n    Setting up libpulse-dev:amd64 (1:11.1-1ubuntu7.11) ...\n    Setting up python-opengl (3.1.0+dfsg-1) ...\n    Setting up swig3.0 (3.0.12-1) ...\n    Setting up libpciaccess-dev:amd64 (0.14-1) ...\n    Setting up libmircore-dev:amd64 (0.31.1-0ubuntu1) ...\n    Setting up libxres1:amd64 (2:1.2.0-2) ...\n    Setting up xvfb (2:1.19.6-1ubuntu4.9) ...\n    Setting up libxpm-dev:amd64 (1:3.5.12-1) ...\n    Setting up libsndio-dev:amd64 (1.1.0-3) ...\n    Setting up libxres-dev (2:1.2.0-2) ...\n    Setting up x11proto-xf86bigfont-dev (2018.4-4) ...\n    Setting up libxkbfile-dev:amd64 (1:1.0.9-2) ...\n    Setting up libxvmc1:amd64 (2:1.0.10-1) ...\n    Setting up libxmuu-dev:amd64 (2:1.1.2-2) ...\n    Setting up x11proto-record-dev (2018.4-4) ...\n    Setting up libxtst-dev:amd64 (2:1.2.3-1) ...\n    Setting up libmircookie2:amd64 (0.31.1-0ubuntu1) ...\n    Setting up libfontenc-dev:amd64 (1:1.1.3-1) ...\n    Setting up python3-future (0.15.2-4ubuntu2) ...\n    update-alternatives: using /usr/bin/python3-futurize to provide /usr/bin/futurize (futurize) in auto mode\n    update-alternatives: using /usr/bin/python3-pasteurize to provide /usr/bin/pasteurize (pasteurize) in auto mode\n    Setting up libxxf86dga1:amd64 (2:1.1.4-1) ...\n    Setting up x11proto-xinerama-dev (2018.4-4) ...\n    Setting up libpixman-1-dev:amd64 (0.34.0-2) ...\n    Setting up x11proto-randr-dev (2018.4-4) ...\n    Setting up libxinerama-dev:amd64 (2:1.1.3-1) ...\n    Setting up x11proto-gl-dev (2018.4-4) ...\n    Setting up libxv-dev:amd64 (2:1.0.11-1) ...\n    Setting up libcapnp-0.6.1:amd64 (0.6.1-1ubuntu1) ...\n    Setting up x11proto-resource-dev (2018.4-4) ...\n    Setting up x11proto-xf86dga-dev (2018.4-4) ...\n    Setting up libfs6:amd64 (2:1.0.7-1) ...\n    Setting up libxxf86dga-dev:amd64 (2:1.1.4-1) ...\n    Setting up libibus-1.0-5:amd64 (1.5.17-3ubuntu5.3) ...\n    Setting up libdmx1:amd64 (1:1.1.3-1) ...\n    Setting up x11proto-render-dev (2:2018.4-4) ...\n    Setting up libmircore1:amd64 (0.31.1-0ubuntu1) ...\n    Setting up libprotobuf-lite10:amd64 (3.0.0-9.1ubuntu1) ...\n    Setting up libudev-dev:amd64 (237-3ubuntu10.47) ...\n    Setting up x11proto-composite-dev (1:2018.4-4) ...\n    Setting up gir1.2-ibus-1.0:amd64 (1.5.17-3ubuntu5.3) ...\n    Setting up swig (3.0.12-1) ...\n    Setting up libxrandr-dev:amd64 (2:1.5.1-1) ...\n    Setting up libxcomposite-dev:amd64 (1:0.4.4-2) ...\n    Setting up libxaw7-dev:amd64 (2:1.0.13-1) ...\n    Setting up libmirprotobuf3:amd64 (0.31.1-0ubuntu1) ...\n    Setting up libdmx-dev:amd64 (1:1.1.3-1) ...\n    Setting up libprotobuf-dev:amd64 (3.0.0-9.1ubuntu1) ...\n    Setting up libxvmc-dev:amd64 (2:1.0.10-1) ...\n    Setting up x11-utils (7.7+3build1) ...\n    Setting up libmircookie-dev:amd64 (0.31.1-0ubuntu1) ...\n    Setting up libxfont-dev (1:2.0.3-1) ...\n    Setting up libibus-1.0-dev:amd64 (1.5.17-3ubuntu5.3) ...\n    Setting up libfs-dev:amd64 (2:1.0.7-1) ...\n    Setting up libmircommon7:amd64 (0.31.1-0ubuntu1) ...\n    Setting up libmirclient9:amd64 (0.31.1-0ubuntu1) ...\n    Setting up libmircommon-dev:amd64 (0.31.1-0ubuntu1) ...\n    Setting up libmirclient-dev:amd64 (0.31.1-0ubuntu1) ...\n    Setting up libsdl2-dev:amd64 (2.0.8+dfsg1-1ubuntu1.18.04.4) ...\n    Setting up mir-client-platform-mesa-dev:amd64 (0.31.1-0ubuntu1) ...\n    Setting up xserver-xorg-dev (2:1.19.6-1ubuntu4.9) ...\n    Setting up xorg-dev (1:7.7+19ubuntu7.1) ...\n    Processing triggers for man-db (2.8.3-2ubuntu0.1) ...\n    Processing triggers for libc-bin (2.27-3ubuntu1.2) ...\n    /sbin/ldconfig.real: /usr/local/lib/python3.7/dist-packages/ideep4py/lib/libmkldnn.so.0 is not a symbolic link\n    \n    Reading package lists... Done\n    Building dependency tree       \n    Reading state information... Done\n    libglu1-mesa-dev is already the newest version (9.0.0-2.1build1).\n    libglu1-mesa-dev set to manually installed.\n    libxi-dev is already the newest version (2:1.7.9-1).\n    libxi-dev set to manually installed.\n    libxmu-dev is already the newest version (2:1.1.2-2).\n    libxmu-dev set to manually installed.\n    mesa-common-dev is already the newest version (20.0.8-0ubuntu1~18.04.1).\n    mesa-common-dev set to manually installed.\n    The following package was automatically installed and is no longer required:\n      libnvidia-common-460\n    Use 'apt autoremove' to remove it.\n    The following additional packages will be installed:\n      apport apport-symptoms libxatracker2 python3-apport python3-certifi\n      python3-chardet python3-httplib2 python3-idna python3-pkg-resources\n      python3-problem-report python3-requests python3-requests-unixsocket\n      python3-six python3-systemd python3-urllib3 xserver-xorg-core\n      xserver-xorg-input-all xserver-xorg-input-libinput xserver-xorg-input-wacom\n      xserver-xorg-legacy xserver-xorg-video-all xserver-xorg-video-amdgpu\n      xserver-xorg-video-ati xserver-xorg-video-fbdev xserver-xorg-video-intel\n      xserver-xorg-video-nouveau xserver-xorg-video-qxl xserver-xorg-video-radeon\n      xserver-xorg-video-vesa xserver-xorg-video-vmware\n    Suggested packages:\n      apport-gtk | apport-kde python3-launchpadlib python3-setuptools\n      python3-cryptography python3-openssl python3-socks xfonts-100dpi\n      | xfonts-75dpi xfonts-scalable xinput firmware-amd-graphics\n      xserver-xorg-video-r128 xserver-xorg-video-mach64 firmware-misc-nonfree\n    The following packages will be REMOVED:\n      xserver-xorg-core-hwe-18.04\n    The following NEW packages will be installed:\n      apport apport-symptoms libxatracker2 python3-apport python3-certifi\n      python3-chardet python3-httplib2 python3-idna python3-pkg-resources\n      python3-problem-report python3-requests python3-requests-unixsocket\n      python3-six python3-systemd python3-urllib3 xserver-xorg xserver-xorg-core\n      xserver-xorg-input-all xserver-xorg-input-libinput xserver-xorg-input-wacom\n      xserver-xorg-legacy xserver-xorg-video-all xserver-xorg-video-amdgpu\n      xserver-xorg-video-ati xserver-xorg-video-fbdev xserver-xorg-video-intel\n      xserver-xorg-video-nouveau xserver-xorg-video-qxl xserver-xorg-video-radeon\n      xserver-xorg-video-vesa xserver-xorg-video-vmware\n    0 upgraded, 31 newly installed, 1 to remove and 72 not upgraded.\n    Need to get 5,151 kB of archives.\n    After this operation, 16.4 MB of additional disk space will be used.\n    Get:1 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 xserver-xorg-core amd64 2:1.19.6-1ubuntu4.9 [1,351 kB]\n    Get:2 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 python3-httplib2 all 0.9.2+dfsg-1ubuntu0.3 [28.8 kB]\n    Get:3 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 python3-problem-report all 2.20.9-0ubuntu7.23 [9,900 B]\n    Get:4 http://archive.ubuntu.com/ubuntu bionic/main amd64 python3-certifi all 2018.1.18-2 [144 kB]\n    Get:5 http://archive.ubuntu.com/ubuntu bionic/main amd64 python3-pkg-resources all 39.0.1-2 [98.8 kB]\n    Get:6 http://archive.ubuntu.com/ubuntu bionic/main amd64 python3-chardet all 3.0.4-1 [80.3 kB]\n    Get:7 http://archive.ubuntu.com/ubuntu bionic/main amd64 python3-idna all 2.6-1 [32.5 kB]\n    Get:8 http://archive.ubuntu.com/ubuntu bionic/main amd64 python3-six all 1.11.0-2 [11.4 kB]\n    Get:9 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 python3-urllib3 all 1.22-1ubuntu0.18.04.2 [86.2 kB]\n    Get:10 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 python3-requests all 2.18.4-2ubuntu0.1 [58.3 kB]\n    Get:11 http://archive.ubuntu.com/ubuntu bionic/main amd64 python3-requests-unixsocket all 0.1.5-3 [6,286 B]\n    Get:12 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 python3-apport all 2.20.9-0ubuntu7.23 [82.7 kB]\n    Get:13 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 apport all 2.20.9-0ubuntu7.23 [125 kB]\n    Get:14 http://archive.ubuntu.com/ubuntu bionic/main amd64 apport-symptoms all 0.20 [14.2 kB]\n    Get:15 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libxatracker2 amd64 20.0.8-0ubuntu1~18.04.1 [1,549 kB]\n    Get:16 http://archive.ubuntu.com/ubuntu bionic/main amd64 python3-systemd amd64 234-1build1 [36.1 kB]\n    Get:17 http://archive.ubuntu.com/ubuntu bionic/main amd64 xserver-xorg-input-libinput amd64 0.27.1-1 [33.2 kB]\n    Get:18 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 xserver-xorg-input-all amd64 1:7.7+19ubuntu7.1 [4,112 B]\n    Get:19 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 xserver-xorg-input-wacom amd64 1:0.36.1-0ubuntu1.1 [89.8 kB]\n    Get:20 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 xserver-xorg amd64 1:7.7+19ubuntu7.1 [65.2 kB]\n    Get:21 http://archive.ubuntu.com/ubuntu bionic/main amd64 xserver-xorg-video-amdgpu amd64 18.0.1-1 [61.0 kB]\n    Get:22 http://archive.ubuntu.com/ubuntu bionic/main amd64 xserver-xorg-video-radeon amd64 1:18.0.1-1 [147 kB]\n    Get:23 http://archive.ubuntu.com/ubuntu bionic/main amd64 xserver-xorg-video-ati amd64 1:18.0.1-1 [7,116 B]\n    Get:24 http://archive.ubuntu.com/ubuntu bionic/main amd64 xserver-xorg-video-fbdev amd64 1:0.4.4-1build6 [11.5 kB]\n    Get:25 http://archive.ubuntu.com/ubuntu bionic/main amd64 xserver-xorg-video-nouveau amd64 1:1.0.15-2 [86.3 kB]\n    Get:26 http://archive.ubuntu.com/ubuntu bionic/main amd64 xserver-xorg-video-vesa amd64 1:2.3.4-1build3 [14.7 kB]\n    Get:27 http://archive.ubuntu.com/ubuntu bionic/main amd64 xserver-xorg-video-vmware amd64 1:13.2.1-1build1 [71.6 kB]\n    Get:28 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 xserver-xorg-video-all amd64 1:7.7+19ubuntu7.1 [4,164 B]\n    Get:29 http://archive.ubuntu.com/ubuntu bionic/main amd64 xserver-xorg-video-intel amd64 2:2.99.917+git20171229-1 [728 kB]\n    Get:30 http://archive.ubuntu.com/ubuntu bionic/main amd64 xserver-xorg-video-qxl amd64 0.1.5-2build1 [81.0 kB]\n    Get:31 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 xserver-xorg-legacy amd64 2:1.19.6-1ubuntu4.9 [32.3 kB]\n    Fetched 5,151 kB in 1s (3,959 kB/s)\n    Extracting templates from packages: 100%\n    Preconfiguring packages ...\n    dpkg: xserver-xorg-core-hwe-18.04: dependency problems, but removing anyway as you requested:\n     xserver-xorg-video-nvidia-465 depends on xorg-video-abi-24 | xorg-video-abi-23 | xorg-video-abi-20 | xorg-video-abi-19 | xorg-video-abi-18 | xorg-video-abi-15 | xorg-video-abi-14 | xorg-video-abi-13 | xorg-video-abi-12 | xorg-video-abi-11 | xorg-video-abi-10 | xorg-video-abi-8 | xorg-video-abi-6.0; however:\n      Package xorg-video-abi-24 is not installed.\n      Package xserver-xorg-core-hwe-18.04 which provides xorg-video-abi-24 is to be removed.\n      Package xorg-video-abi-23 is not installed.\n      Package xorg-video-abi-20 is not installed.\n      Package xorg-video-abi-19 is not installed.\n      Package xorg-video-abi-18 is not installed.\n      Package xorg-video-abi-15 is not installed.\n      Package xorg-video-abi-14 is not installed.\n      Package xorg-video-abi-13 is not installed.\n      Package xorg-video-abi-12 is not installed.\n      Package xorg-video-abi-11 is not installed.\n      Package xorg-video-abi-10 is not installed.\n      Package xorg-video-abi-8 is not installed.\n      Package xorg-video-abi-6.0 is not installed.\n     xserver-xorg-video-nvidia-465 depends on xserver-xorg-core (>= 2:1.19.6-1ubuntu2~) | xserver-xorg-core-hwe-18.04; however:\n      Package xserver-xorg-core is not installed.\n      Package xserver-xorg-core-hwe-18.04 which provides xserver-xorg-core is to be removed.\n      Package xserver-xorg-core-hwe-18.04 is to be removed.\n     xserver-xorg-video-nvidia-465 depends on xorg-video-abi-24 | xorg-video-abi-23 | xorg-video-abi-20 | xorg-video-abi-19 | xorg-video-abi-18 | xorg-video-abi-15 | xorg-video-abi-14 | xorg-video-abi-13 | xorg-video-abi-12 | xorg-video-abi-11 | xorg-video-abi-10 | xorg-video-abi-8 | xorg-video-abi-6.0; however:\n      Package xorg-video-abi-24 is not installed.\n      Package xserver-xorg-core-hwe-18.04 which provides xorg-video-abi-24 is to be removed.\n      Package xorg-video-abi-23 is not installed.\n      Package xorg-video-abi-20 is not installed.\n      Package xorg-video-abi-19 is not installed.\n      Package xorg-video-abi-18 is not installed.\n      Package xorg-video-abi-15 is not installed.\n      Package xorg-video-abi-14 is not installed.\n      Package xorg-video-abi-13 is not installed.\n      Package xorg-video-abi-12 is not installed.\n      Package xorg-video-abi-11 is not installed.\n      Package xorg-video-abi-10 is not installed.\n      Package xorg-video-abi-8 is not installed.\n      Package xorg-video-abi-6.0 is not installed.\n     xserver-xorg-video-nvidia-465 depends on xserver-xorg-core (>= 2:1.19.6-1ubuntu2~) | xserver-xorg-core-hwe-18.04; however:\n      Package xserver-xorg-core is not installed.\n      Package xserver-xorg-core-hwe-18.04 which provides xserver-xorg-core is to be removed.\n      Package xserver-xorg-core-hwe-18.04 is to be removed.\n     xserver-xorg-video-nvidia-465 depends on xorg-video-abi-24 | xorg-video-abi-23 | xorg-video-abi-20 | xorg-video-abi-19 | xorg-video-abi-18 | xorg-video-abi-15 | xorg-video-abi-14 | xorg-video-abi-13 | xorg-video-abi-12 | xorg-video-abi-11 | xorg-video-abi-10 | xorg-video-abi-8 | xorg-video-abi-6.0; however:\n      Package xorg-video-abi-24 is not installed.\n      Package xserver-xorg-core-hwe-18.04 which provides xorg-video-abi-24 is to be removed.\n      Package xorg-video-abi-23 is not installed.\n      Package xorg-video-abi-20 is not installed.\n      Package xorg-video-abi-19 is not installed.\n      Package xorg-video-abi-18 is not installed.\n      Package xorg-video-abi-15 is not installed.\n      Package xorg-video-abi-14 is not installed.\n      Package xorg-video-abi-13 is not installed.\n      Package xorg-video-abi-12 is not installed.\n      Package xorg-video-abi-11 is not installed.\n      Package xorg-video-abi-10 is not installed.\n      Package xorg-video-abi-8 is not installed.\n      Package xorg-video-abi-6.0 is not installed.\n     xserver-xorg-video-nvidia-465 depends on xserver-xorg-core (>= 2:1.19.6-1ubuntu2~) | xserver-xorg-core-hwe-18.04; however:\n      Package xserver-xorg-core is not installed.\n      Package xserver-xorg-core-hwe-18.04 which provides xserver-xorg-core is to be removed.\n      Package xserver-xorg-core-hwe-18.04 is to be removed.\n    \n    (Reading database ... 165472 files and directories currently installed.)\n    Removing xserver-xorg-core-hwe-18.04 (2:1.20.8-2ubuntu2.2~18.04.5) ...\n    Selecting previously unselected package xserver-xorg-core.\n    (Reading database ... 165433 files and directories currently installed.)\n    Preparing to unpack .../00-xserver-xorg-core_2%3a1.19.6-1ubuntu4.9_amd64.deb ...\n    Unpacking xserver-xorg-core (2:1.19.6-1ubuntu4.9) ...\n    Selecting previously unselected package python3-httplib2.\n    Preparing to unpack .../01-python3-httplib2_0.9.2+dfsg-1ubuntu0.3_all.deb ...\n    Unpacking python3-httplib2 (0.9.2+dfsg-1ubuntu0.3) ...\n    Selecting previously unselected package python3-problem-report.\n    Preparing to unpack .../02-python3-problem-report_2.20.9-0ubuntu7.23_all.deb ...\n    Unpacking python3-problem-report (2.20.9-0ubuntu7.23) ...\n    Selecting previously unselected package python3-certifi.\n    Preparing to unpack .../03-python3-certifi_2018.1.18-2_all.deb ...\n    Unpacking python3-certifi (2018.1.18-2) ...\n    Selecting previously unselected package python3-pkg-resources.\n    Preparing to unpack .../04-python3-pkg-resources_39.0.1-2_all.deb ...\n    Unpacking python3-pkg-resources (39.0.1-2) ...\n    Selecting previously unselected package python3-chardet.\n    Preparing to unpack .../05-python3-chardet_3.0.4-1_all.deb ...\n    Unpacking python3-chardet (3.0.4-1) ...\n    Selecting previously unselected package python3-idna.\n    Preparing to unpack .../06-python3-idna_2.6-1_all.deb ...\n    Unpacking python3-idna (2.6-1) ...\n    Selecting previously unselected package python3-six.\n    Preparing to unpack .../07-python3-six_1.11.0-2_all.deb ...\n    Unpacking python3-six (1.11.0-2) ...\n    Selecting previously unselected package python3-urllib3.\n    Preparing to unpack .../08-python3-urllib3_1.22-1ubuntu0.18.04.2_all.deb ...\n    Unpacking python3-urllib3 (1.22-1ubuntu0.18.04.2) ...\n    Selecting previously unselected package python3-requests.\n    Preparing to unpack .../09-python3-requests_2.18.4-2ubuntu0.1_all.deb ...\n    Unpacking python3-requests (2.18.4-2ubuntu0.1) ...\n    Selecting previously unselected package python3-requests-unixsocket.\n    Preparing to unpack .../10-python3-requests-unixsocket_0.1.5-3_all.deb ...\n    Unpacking python3-requests-unixsocket (0.1.5-3) ...\n    Selecting previously unselected package python3-apport.\n    Preparing to unpack .../11-python3-apport_2.20.9-0ubuntu7.23_all.deb ...\n    Unpacking python3-apport (2.20.9-0ubuntu7.23) ...\n    Selecting previously unselected package apport.\n    Preparing to unpack .../12-apport_2.20.9-0ubuntu7.23_all.deb ...\n    Unpacking apport (2.20.9-0ubuntu7.23) ...\n    Selecting previously unselected package apport-symptoms.\n    Preparing to unpack .../13-apport-symptoms_0.20_all.deb ...\n    Unpacking apport-symptoms (0.20) ...\n    Selecting previously unselected package libxatracker2:amd64.\n    Preparing to unpack .../14-libxatracker2_20.0.8-0ubuntu1~18.04.1_amd64.deb ...\n    Unpacking libxatracker2:amd64 (20.0.8-0ubuntu1~18.04.1) ...\n    Selecting previously unselected package python3-systemd.\n    Preparing to unpack .../15-python3-systemd_234-1build1_amd64.deb ...\n    Unpacking python3-systemd (234-1build1) ...\n    Selecting previously unselected package xserver-xorg-input-libinput.\n    Preparing to unpack .../16-xserver-xorg-input-libinput_0.27.1-1_amd64.deb ...\n    Unpacking xserver-xorg-input-libinput (0.27.1-1) ...\n    Selecting previously unselected package xserver-xorg-input-all.\n    Preparing to unpack .../17-xserver-xorg-input-all_1%3a7.7+19ubuntu7.1_amd64.deb ...\n    Unpacking xserver-xorg-input-all (1:7.7+19ubuntu7.1) ...\n    Selecting previously unselected package xserver-xorg-input-wacom.\n    Preparing to unpack .../18-xserver-xorg-input-wacom_1%3a0.36.1-0ubuntu1.1_amd64.deb ...\n    Unpacking xserver-xorg-input-wacom (1:0.36.1-0ubuntu1.1) ...\n    Selecting previously unselected package xserver-xorg.\n    Preparing to unpack .../19-xserver-xorg_1%3a7.7+19ubuntu7.1_amd64.deb ...\n    Unpacking xserver-xorg (1:7.7+19ubuntu7.1) ...\n    Selecting previously unselected package xserver-xorg-video-amdgpu.\n    Preparing to unpack .../20-xserver-xorg-video-amdgpu_18.0.1-1_amd64.deb ...\n    Unpacking xserver-xorg-video-amdgpu (18.0.1-1) ...\n    Selecting previously unselected package xserver-xorg-video-radeon.\n    Preparing to unpack .../21-xserver-xorg-video-radeon_1%3a18.0.1-1_amd64.deb ...\n    Unpacking xserver-xorg-video-radeon (1:18.0.1-1) ...\n    Selecting previously unselected package xserver-xorg-video-ati.\n    Preparing to unpack .../22-xserver-xorg-video-ati_1%3a18.0.1-1_amd64.deb ...\n    Unpacking xserver-xorg-video-ati (1:18.0.1-1) ...\n    Selecting previously unselected package xserver-xorg-video-fbdev.\n    Preparing to unpack .../23-xserver-xorg-video-fbdev_1%3a0.4.4-1build6_amd64.deb ...\n    Unpacking xserver-xorg-video-fbdev (1:0.4.4-1build6) ...\n    Selecting previously unselected package xserver-xorg-video-nouveau.\n    Preparing to unpack .../24-xserver-xorg-video-nouveau_1%3a1.0.15-2_amd64.deb ...\n    Unpacking xserver-xorg-video-nouveau (1:1.0.15-2) ...\n    Selecting previously unselected package xserver-xorg-video-vesa.\n    Preparing to unpack .../25-xserver-xorg-video-vesa_1%3a2.3.4-1build3_amd64.deb ...\n    Unpacking xserver-xorg-video-vesa (1:2.3.4-1build3) ...\n    Selecting previously unselected package xserver-xorg-video-vmware.\n    Preparing to unpack .../26-xserver-xorg-video-vmware_1%3a13.2.1-1build1_amd64.deb ...\n    Unpacking xserver-xorg-video-vmware (1:13.2.1-1build1) ...\n    Selecting previously unselected package xserver-xorg-video-all.\n    Preparing to unpack .../27-xserver-xorg-video-all_1%3a7.7+19ubuntu7.1_amd64.deb ...\n    Unpacking xserver-xorg-video-all (1:7.7+19ubuntu7.1) ...\n    Selecting previously unselected package xserver-xorg-video-intel.\n    Preparing to unpack .../28-xserver-xorg-video-intel_2%3a2.99.917+git20171229-1_amd64.deb ...\n    Unpacking xserver-xorg-video-intel (2:2.99.917+git20171229-1) ...\n    Selecting previously unselected package xserver-xorg-video-qxl.\n    Preparing to unpack .../29-xserver-xorg-video-qxl_0.1.5-2build1_amd64.deb ...\n    Unpacking xserver-xorg-video-qxl (0.1.5-2build1) ...\n    Selecting previously unselected package xserver-xorg-legacy.\n    Preparing to unpack .../30-xserver-xorg-legacy_2%3a1.19.6-1ubuntu4.9_amd64.deb ...\n    Unpacking xserver-xorg-legacy (2:1.19.6-1ubuntu4.9) ...\n    Setting up python3-idna (2.6-1) ...\n    Setting up python3-six (1.11.0-2) ...\n    Setting up python3-certifi (2018.1.18-2) ...\n    Setting up python3-pkg-resources (39.0.1-2) ...\n    Setting up libxatracker2:amd64 (20.0.8-0ubuntu1~18.04.1) ...\n    Setting up xserver-xorg-core (2:1.19.6-1ubuntu4.9) ...\n    Setting up xserver-xorg-video-radeon (1:18.0.1-1) ...\n    Setting up python3-problem-report (2.20.9-0ubuntu7.23) ...\n    Setting up xserver-xorg-video-vesa (1:2.3.4-1build3) ...\n    Setting up xserver-xorg-video-amdgpu (18.0.1-1) ...\n    Setting up python3-chardet (3.0.4-1) ...\n\n\n\n```\n!pip3 install torch torchvision gym PyOpenGL piglet pyglet==1.3.2 pyvirtualdisplay\n```\n\n    Requirement already satisfied: torch in /usr/local/lib/python3.6/dist-packages (1.1.0)\n    Requirement already satisfied: torchvision in /usr/local/lib/python3.6/dist-packages (0.3.0)\n    Requirement already satisfied: gym in /usr/local/lib/python3.6/dist-packages (0.10.11)\n    Requirement already satisfied: PyOpenGL in /usr/local/lib/python3.6/dist-packages (3.1.0)\n    Collecting piglet\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/86/f6/ef278239ebe525466ea51a7dd9d6d3211d197ac4b4abc76e17cdd419f69c/piglet-0.4.4.tar.gz (52kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 61kB 4.1MB/s \n    \u001b[?25hCollecting pyglet==1.3.2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1c/fc/dad5eaaab68f0c21e2f906a94ddb98175662cc5a654eee404d59554ce0fa/pyglet-1.3.2-py2.py3-none-any.whl (1.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.0MB 15.0MB/s \n    \u001b[?25hCollecting pyvirtualdisplay\n      Downloading https://files.pythonhosted.org/packages/cf/ad/b15f252bfb0f1693ad3150b55a44a674f3cba711cacdbb9ae2f03f143d19/PyVirtualDisplay-0.2.4-py2.py3-none-any.whl\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from torch) (1.16.4)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from torchvision) (1.12.0)\n    Requirement already satisfied: pillow>=4.1.1 in /usr/local/lib/python3.6/dist-packages (from torchvision) (4.3.0)\n    Requirement already satisfied: requests>=2.0 in /usr/local/lib/python3.6/dist-packages (from gym) (2.21.0)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from gym) (1.3.0)\n    Collecting Parsley (from piglet)\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/2b/d6/4fed8d65e28a970e1c5cb33ce9c7e22e3de745e1b2ae37af051ef16aea3b/Parsley-1.3-py2.py3-none-any.whl (88kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 92kB 27.8MB/s \n    \u001b[?25hRequirement already satisfied: attrs in /usr/local/lib/python3.6/dist-packages (from piglet) (19.1.0)\n    Collecting astunparse (from piglet)\n      Downloading https://files.pythonhosted.org/packages/2e/37/5dd0dd89b87bb5f0f32a7e775458412c52d78f230ab8d0c65df6aabc4479/astunparse-1.6.2-py2.py3-none-any.whl\n    Requirement already satisfied: markupsafe in /usr/local/lib/python3.6/dist-packages (from piglet) (1.1.1)\n    Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from pyglet==1.3.2) (0.16.0)\n    Collecting EasyProcess (from pyvirtualdisplay)\n      Downloading https://files.pythonhosted.org/packages/fa/29/40040d1d64a224a5e44df9572794a66494618ffe5c77199214aeceedb8a7/EasyProcess-0.2.7-py2.py3-none-any.whl\n    Requirement already satisfied: olefile in /usr/local/lib/python3.6/dist-packages (from pillow>=4.1.1->torchvision) (0.46)\n    Requirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.0->gym) (2.8)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests>=2.0->gym) (2019.6.16)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.0->gym) (3.0.4)\n    Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests>=2.0->gym) (1.24.3)\n    Requirement already satisfied: wheel<1.0,>=0.23.0 in /usr/local/lib/python3.6/dist-packages (from astunparse->piglet) (0.33.4)\n    Building wheels for collected packages: piglet\n      Building wheel for piglet (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for piglet: filename=piglet-0.4.4-cp36-none-any.whl size=66439 sha256=d293a5e61bbc484a4c5bcf80fe81dc0fe5ff9b6495c6bc39a02ac88409874661\n      Stored in directory: /root/.cache/pip/wheels/c7/59/a5/5bd1a35a4a4596714c4c7925a1751e7b1580b6ced363fd7969\n    Successfully built piglet\n    Installing collected packages: Parsley, astunparse, piglet, pyglet, EasyProcess, pyvirtualdisplay\n      Found existing installation: pyglet 1.4.1\n        Uninstalling pyglet-1.4.1:\n          Successfully uninstalled pyglet-1.4.1\n    Successfully installed EasyProcess-0.2.7 Parsley-1.3 astunparse-1.6.2 piglet-0.4.4 pyglet-1.3.2 pyvirtualdisplay-0.2.4\n\n\n\n```\n# Start virtual display\nfrom pyvirtualdisplay import Display\ndisplay = Display(visible=0, size=(1024, 768))\ndisplay.start()\nimport os\nos.environ[\"DISPLAY\"] = \":\" + str(display.display) + \".\" + str(display.screen)\n\n```\n\n    xdpyinfo was not found, X start can not be checked! Please install xdpyinfo!\n\n\n\n```\n%matplotlib inline\n```\n\n\nReinforcement Learning (DQN) tutorial\n=====================================\nAdapted from PyTorch website.\n\n**Author**: `Adam Paszke <https://github.com/apaszke>`_\n\n\nThis tutorial shows how to use PyTorch to train a Deep Q Learning (DQN) agent\non the CartPole-v0 task from the `OpenAI Gym <https://gym.openai.com/>`__.\n\n**Task**\n\nThe agent has to decide between two actions - moving the cart left or\nright - so that the pole attached to it stays upright. You can find an\nofficial leaderboard with various algorithms and visualizations at the\n`Gym website <https://gym.openai.com/envs/CartPole-v0>`__.\n\nAs the agent observes the current state of the environment and chooses\nan action, the environment *transitions* to a new state, and also\nreturns a reward that indicates the consequences of the action. In this\ntask, the environment terminates if the pole falls over too far.\n\nThe CartPole task is designed so that the inputs to the agent are 4 real\nvalues representing the environment state (position, velocity, etc.).\nHowever, neural networks can solve the task purely by looking at the\nscene, so we'll use a patch of the screen centered on the cart as an\ninput. Because of this, our results aren't directly comparable to the\nones from the official leaderboard - our task is much harder.\nUnfortunately this does slow down the training, because we have to\nrender all the frames.\n\nStrictly speaking, we will present the state as the difference between\nthe current screen patch and the previous one. This will allow the agent\nto take the velocity of the pole into account from one image.\n\n**Packages**\n\n\nFirst, let's import needed packages. Firstly, we need\n`gym <https://gym.openai.com/docs>`__ for the environment\n(Install using `pip install gym`).\nWe'll also use the following from PyTorch:\n\n-  neural networks (``torch.nn``)\n-  optimization (``torch.optim``)\n-  automatic differentiation (``torch.autograd``)\n-  utilities for vision tasks (``torchvision`` - `a separate\n   package <https://github.com/pytorch/vision>`__).\n\n\n\n\n\n```\nimport gym\nimport math\nimport random\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom collections import namedtuple\nfrom itertools import count\nfrom PIL import Image\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torchvision.transforms as T\n\n\nenv = gym.make('CartPole-v0').unwrapped\n\n# set up matplotlib\nis_ipython = 'inline' in matplotlib.get_backend()\nif is_ipython:\n    from IPython import display\n\nplt.ion()\n\n# if gpu is to be used\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n```\n\nReplay Memory\n-------------\n\nWe'll be using experience replay memory for training our DQN. It stores\nthe transitions that the agent observes, allowing us to reuse this data\nlater. By sampling from it randomly, the transitions that build up a\nbatch are decorrelated. It has been shown that this greatly stabilizes\nand improves the DQN training procedure.\n\nFor this, we're going to need two classses:\n\n-  ``Transition`` - a named tuple representing a single transition in\n   our environment\n-  ``ReplayMemory`` - a cyclic buffer of bounded size that holds the\n   transitions observed recently. It also implements a ``.sample()``\n   method for selecting a random batch of transitions for training.\n\n\n\n\n\n```\nTransition = namedtuple('Transition',\n                        ('state', 'action', 'next_state', 'reward'))\n\n\nclass ReplayMemory(object):\n\n    def __init__(self, capacity):\n        self.capacity = capacity\n        self.memory = []\n        self.position = 0\n\n    def push(self, *args):\n        \"\"\"Saves a transition.\"\"\"\n        if len(self.memory) < self.capacity:\n            self.memory.append(None)\n        self.memory[self.position] = Transition(*args)\n        self.position = (self.position + 1) % self.capacity\n\n    def sample(self, batch_size):\n        return random.sample(self.memory, batch_size)\n\n    def __len__(self):\n        return len(self.memory)\n```\n\nNow, let's define our model. But first, let quickly recap what a DQN is.\n\nDQN algorithm\n-------------\n\nOur environment is deterministic, so all equations presented here are\nalso formulated deterministically for the sake of simplicity. In the\nreinforcement learning literature, they would also contain expectations\nover stochastic transitions in the environment.\n\nOur aim will be to train a policy that tries to maximize the discounted,\ncumulative reward\n$R_{t_0} = \\sum_{t=t_0}^{\\infty} \\gamma^{t - t_0} r_t$, where\n$R_{t_0}$ is also known as the *return*. The discount,\n$\\gamma$, should be a constant between $0$ and $1$\nthat ensures the sum converges. It makes rewards from the uncertain far\nfuture less important for our agent than the ones in the near future\nthat it can be fairly confident about.\n\nThe main idea behind Q-learning is that if we had a function\n$Q^*: State \\times Action \\rightarrow \\mathbb{R}$, that could tell\nus what our return would be, if we were to take an action in a given\nstate, then we could easily construct a policy that maximizes our\nrewards:\n\n\\begin{align}\\pi^*(s) = \\arg\\!\\max_a \\ Q^*(s, a)\\end{align}\n\nHowever, we don't know everything about the world, so we don't have\naccess to $Q^*$. But, since neural networks are universal function\napproximators, we can simply create one and train it to resemble\n$Q^*$.\n\nFor our training update rule, we'll use a fact that every $Q$\nfunction for some policy obeys the Bellman equation:\n\n\\begin{align}Q^{\\pi}(s, a) = r + \\gamma Q^{\\pi}(s', \\pi(s'))\\end{align}\n\nThe difference between the two sides of the equality is known as the\ntemporal difference error, $\\delta$:\n\n\\begin{align}\\delta = Q(s, a) - (r + \\gamma \\max_a Q(s', a))\\end{align}\n\nTo minimise this error, we will use the `Huber\nloss <https://en.wikipedia.org/wiki/Huber_loss>`__. The Huber loss acts\nlike the mean squared error when the error is small, but like the mean\nabsolute error when the error is large - this makes it more robust to\noutliers when the estimates of $Q$ are very noisy. We calculate\nthis over a batch of transitions, $B$, sampled from the replay\nmemory:\n\n\\begin{align}\\mathcal{L} = \\frac{1}{|B|}\\sum_{(s, a, s', r) \\ \\in \\ B} \\mathcal{L}(\\delta)\\end{align}\n\n\\begin{align}\\text{where} \\quad \\mathcal{L}(\\delta) = \\begin{cases}\n     \\frac{1}{2}{\\delta^2}  & \\text{for } |\\delta| \\le 1, \\\\\n     |\\delta| - \\frac{1}{2} & \\text{otherwise.}\n   \\end{cases}\\end{align}\n\n### Q-network\n\nOur model will be a convolutional neural network that takes in the\ndifference between the current and previous screen patches. It has two\noutputs, representing $Q(s, \\mathrm{left})$ and\n$Q(s, \\mathrm{right})$ (where $s$ is the input to the\nnetwork). In effect, the network is trying to predict the *quality* of\ntaking each action given the current input.\n\n\n\n\n\n```\nclass DQN(nn.Module):\n\n    def __init__(self):\n        super(DQN, self).__init__()\n        self.conv1 = nn.Conv2d(3, 16, kernel_size=5, stride=2)\n        self.bn1 = nn.BatchNorm2d(16)\n        self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2)\n        self.bn2 = nn.BatchNorm2d(32)\n        self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2)\n        self.bn3 = nn.BatchNorm2d(32)\n        self.head = nn.Linear(448, 2)\n\n    def forward(self, x):\n        x = F.relu(self.bn1(self.conv1(x)))\n        x = F.relu(self.bn2(self.conv2(x)))\n        x = F.relu(self.bn3(self.conv3(x)))\n        return self.head(x.view(x.size(0), -1))\n```\n\n### Input extraction\n\n\nThe code below are utilities for extracting and processing rendered\nimages from the environment. It uses the ``torchvision`` package, which\nmakes it easy to compose image transforms. Once you run the cell it will\ndisplay an example patch that it extracted.\n\n\n\n\n\n```\nresize = T.Compose([T.ToPILImage(),\n                    T.Resize(40, interpolation=Image.CUBIC),\n                    T.ToTensor()])\n\n# This is based on the code from gym.\nscreen_width = 600\n\n\ndef get_cart_location():\n    world_width = env.x_threshold * 2\n    scale = screen_width / world_width\n    return int(env.state[0] * scale + screen_width / 2.0)  # MIDDLE OF CART\n\n\ndef get_screen():\n    screen = env.render(mode='rgb_array').transpose(\n        (2, 0, 1))  # transpose into torch order (CHW)\n    # Strip off the top and bottom of the screen\n    screen = screen[:, 160:320]\n    view_width = 320\n    cart_location = get_cart_location()\n    if cart_location < view_width // 2:\n        slice_range = slice(view_width)\n    elif cart_location > (screen_width - view_width // 2):\n        slice_range = slice(-view_width, None)\n    else:\n        slice_range = slice(cart_location - view_width // 2,\n                            cart_location + view_width // 2)\n    # Strip off the edges, so that we have a square image centered on a cart\n    screen = screen[:, :, slice_range]\n    # Convert to float, rescare, convert to torch tensor\n    # (this doesn't require a copy)\n    screen = np.ascontiguousarray(screen, dtype=np.float32) / 255\n    screen = torch.from_numpy(screen)\n    # Resize, and add a batch dimension (BCHW)\n    return resize(screen).unsqueeze(0).to(device)\n\n\nenv.reset()\n\nplt.figure()\nplt.imshow(get_screen().cpu().squeeze(0).permute(1, 2, 0).numpy(),\n           interpolation='none')\nplt.title('Example extracted screen')\nplt.show()\n\n```\n\nTraining\n--------\n\n\n\n\n\n### Hyperparameters and utilities\n\nThis cell instantiates our model and its optimizer, and defines some\nutilities:\n\n-  ``select_action`` - will select an action accordingly to an epsilon\n   greedy policy. Simply put, we'll sometimes use our model for choosing\n   the action, and sometimes we'll just sample one uniformly. The\n   probability of choosing a random action will start at ``EPS_START``\n   and will decay exponentially towards ``EPS_END``. ``EPS_DECAY``\n   controls the rate of the decay.\n-  ``plot_durations`` - a helper for plotting the durations of episodes,\n   along with an average over the last 100 episodes (the measure used in\n   the official evaluations). The plot will be underneath the cell\n   containing the main training loop, and will update after every\n   episode.\n\n\n\n```\nBATCH_SIZE = 128\nGAMMA = 0.999\nEPS_START = 0.9\nEPS_END = 0.05\nEPS_DECAY = 200\nTARGET_UPDATE = 10\n\npolicy_net = DQN().to(device)\ntarget_net = DQN().to(device)\ntarget_net.load_state_dict(policy_net.state_dict())\ntarget_net.eval()\n\noptimizer = optim.RMSprop(policy_net.parameters())\nmemory = ReplayMemory(10000)\n\n\nsteps_done = 0\n\n\ndef select_action(state):\n    global steps_done\n    sample = random.random()\n    eps_threshold = EPS_END + (EPS_START - EPS_END) * \\\n        math.exp(-1. * steps_done / EPS_DECAY)\n    steps_done += 1\n    if sample > eps_threshold:\n        with torch.no_grad():\n            return policy_net(state).max(1)[1].view(1, 1)\n    else:\n        return torch.tensor([[random.randrange(2)]], device=device, dtype=torch.long)\n\n\nepisode_durations = []\n\n\ndef plot_durations():\n    plt.figure(2)\n    plt.clf()\n    durations_t = torch.tensor(episode_durations, dtype=torch.float)\n    plt.title('Training...')\n    plt.xlabel('Episode')\n    plt.ylabel('Duration')\n    plt.plot(durations_t.numpy())\n    # Take 100 episode averages and plot them too\n    if len(durations_t) >= 100:\n        means = durations_t.unfold(0, 100, 1).mean(1).view(-1)\n        means = torch.cat((torch.zeros(99), means))\n        plt.plot(means.numpy())\n\n    plt.pause(0.001)  # pause a bit so that plots are updated\n    if is_ipython:\n        display.clear_output(wait=True)\n        display.display(plt.gcf())\n```\n\n### Training loop\n\n\nFinally, the code for training our model.\n\nHere, you can find an ``optimize_model`` function that performs a\nsingle step of the optimization. It first samples a batch, concatenates\nall the tensors into a single one, computes $Q(s_t, a_t)$ and\n$V(s_{t+1}) = \\max_a Q(s_{t+1}, a)$, and combines them into our\nloss. By defition we set $V(s) = 0$ if $s$ is a terminal\nstate. We also use a target network to compute $V(s_{t+1})$ for\nadded stability. The target network has its weights kept frozen most of\nthe time, but is updated with the policy network's weights every so often.\nThis is usually a set number of steps but we shall use episodes for\nsimplicity.\n\n\n\n\n\n```\ndef optimize_model():\n    if len(memory) < BATCH_SIZE:\n        return\n    transitions = memory.sample(BATCH_SIZE)\n    # Transpose the batch (see http://stackoverflow.com/a/19343/3343043 for\n    # detailed explanation).\n    batch = Transition(*zip(*transitions))\n\n    # Compute a mask of non-final states and concatenate the batch elements\n    non_final_mask = torch.tensor(tuple(map(lambda s: s is not None,\n                                          batch.next_state)), device=device, dtype=torch.uint8)\n    non_final_next_states = torch.cat([s for s in batch.next_state\n                                                if s is not None])\n    state_batch = torch.cat(batch.state)\n    action_batch = torch.cat(batch.action)\n    reward_batch = torch.cat(batch.reward)\n\n    # Compute Q(s_t, a) - the model computes Q(s_t), then we select the\n    # columns of actions taken\n    state_action_values = policy_net(state_batch).gather(1, action_batch)\n\n    # Compute V(s_{t+1}) for all next states.\n    next_state_values = torch.zeros(BATCH_SIZE, device=device)\n    next_state_values[non_final_mask] = target_net(non_final_next_states).max(1)[0].detach()\n    # Compute the expected Q values\n    expected_state_action_values = (next_state_values * GAMMA) + reward_batch\n\n    # Compute Huber loss\n    loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1))\n\n    # Optimize the model\n    optimizer.zero_grad()\n    loss.backward()\n    for param in policy_net.parameters():\n        param.grad.data.clamp_(-1, 1)\n    optimizer.step()\n```\n\nBelow, you can find the main training loop. At the beginning we reset\nthe environment and initialize the ``state`` Tensor. Then, we sample\nan action, execute it, observe the next screen and the reward (always\n1), and optimize our model once. When the episode ends (our model\nfails), we restart the loop.\n\nBelow, `num_episodes` is set small. You should download\nthe notebook and run lot more epsiodes.\n\n\n\n\n\n```\nnum_episodes = 50\nfor i_episode in range(num_episodes):\n    # Initialize the environment and state\n    env.reset()\n    last_screen = get_screen()\n    current_screen = get_screen()\n    state = current_screen - last_screen\n    for t in count():\n        # Select and perform an action\n        action = select_action(state)\n        _, reward, done, _ = env.step(action.item())\n        reward = torch.tensor([reward], device=device)\n\n        # Observe new state\n        last_screen = current_screen\n        current_screen = get_screen()\n        if not done:\n            next_state = current_screen - last_screen\n        else:\n            next_state = None\n\n        # Store the transition in memory\n        memory.push(state, action, next_state, reward)\n\n        # Move to the next state\n        state = next_state\n\n        # Perform one step of the optimization (on the target network)\n        optimize_model()\n        if done:\n            episode_durations.append(t + 1)\n            plot_durations()\n            break\n    # Update the target network\n    if i_episode % TARGET_UPDATE == 0:\n        target_net.load_state_dict(policy_net.state_dict())\n\nprint('Complete')\nenv.render()\nplt.show()\n```\n\n\n    <Figure size 432x288 with 0 Axes>\n\n\n    Complete\n\n\n\n    <Figure size 432x288 with 0 Axes>\n\n\n\n```\nframes = []\nfor i in range(3):\n    env.reset()\n    last_screen = get_screen()\n    current_screen = get_screen()\n    state = current_screen - last_screen\n    done = False\n    R = 0\n    t = 0\n    while not done and t < 200:\n        frames.append(env.render(mode = 'rgb_array'))\n        action = select_action(state)\n        obs, r, done, _ = env.step(action.item())\n        R += r\n        t += 1\n        if not done:\n            next_state = current_screen - last_screen\n        else:\n            next_state = None\n        state = next_state\n    print('test episode:', i, 'R:', R)\nenv.render()\n\nimport matplotlib.pyplot as plt\nimport matplotlib.animation\nimport numpy as np\nfrom IPython.display import HTML\n\n# make a video to display\nplt.figure(figsize=(frames[0].shape[1] / 72.0, frames[0].shape[0] / 72.0), dpi = 72)\npatch = plt.imshow(frames[0])\nplt.axis('off')\nanimate = lambda i: patch.set_data(frames[i])\nani = matplotlib.animation.FuncAnimation(plt.gcf(), animate, frames=len(frames), interval = 50)\nHTML(ani.to_jshtml())\n```\n", "meta": {"hexsha": "27c6309ff01e0a49d103ea1289e6b0101233f55c", "size": 223072, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "dqn_CartPole.ipynb", "max_stars_repo_name": "XiaoZheng-YY/EEG-DL", "max_stars_repo_head_hexsha": "67686ee4fd2d09d3a6a0d6705cec9e66c804e541", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dqn_CartPole.ipynb", "max_issues_repo_name": "XiaoZheng-YY/EEG-DL", "max_issues_repo_head_hexsha": "67686ee4fd2d09d3a6a0d6705cec9e66c804e541", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dqn_CartPole.ipynb", "max_forks_repo_name": "XiaoZheng-YY/EEG-DL", "max_forks_repo_head_hexsha": "67686ee4fd2d09d3a6a0d6705cec9e66c804e541", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 76.9213793103, "max_line_length": 7512, "alphanum_fraction": 0.6880244943, "converted": true, "num_tokens": 21734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13117322376181564, "lm_q2_score": 0.03161876966400514, "lm_q1q2_score": 0.004147535948209854}}
{"text": "```python\n\"\"\"\nPlease run notebook locally (if you have all the dependencies and a GPU). \nTechnically you can run this notebook on Google Colab but you need to set up microphone for Colab.\n\nInstructions for setting up Colab are as follows:\n1. Open a new Python 3 notebook.\n2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n4. Run this cell to set up dependencies.\n5. Set up microphone for Colab\n\"\"\"\n# If you're using Google Colab and not running locally, run this cell.\n\n## Install dependencies\n!pip install wget\n!apt-get install sox libsndfile1 ffmpeg portaudio19-dev\n!pip install unidecode\n!pip install pyaudio\n\n# ## Install NeMo\nBRANCH = 'v1.0.0'\n!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[asr]\n\n## Install TorchAudio\n!pip install torchaudio>=0.6.0 -f https://download.pytorch.org/whl/torch_stable.html\n\n## Grab the config we'll use in this example\n!mkdir configs\n```\n\n    Requirement already satisfied: wget in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (3.2)\n\n\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    'apt-get' is not recognized as an internal or external command,\n    operable program or batch file.\n\n\n    Requirement already satisfied: unidecode in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (1.1.2)\n\n\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n\n\n    Requirement already satisfied: pyaudio in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (0.2.11)\n\n\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n\n\n    Collecting nemo_toolkit[asr]\n      Cloning https://github.com/NVIDIA/NeMo.git (to revision v1.0.0) to c:\\users\\hapir\\appdata\\local\\temp\\pip-install-wvlmdsim\\nemo-toolkit_03d2625ee8c249faaeaf8e6a92cf3297\n    Requirement already satisfied: numpy>=1.18.2 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (1.19.2)\n    Requirement already satisfied: onnx>=1.7.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (1.8.1)\n    Requirement already satisfied: pytorch-lightning<=1.2.10,>=1.2.8 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (1.2.10)\n    Requirement already satisfied: python-dateutil in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (2.8.1)\n    Requirement already satisfied: torch in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (1.8.1)\n    Requirement already satisfied: wget in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (3.2)\n    Requirement already satisfied: wrapt in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (1.12.1)\n    Requirement already satisfied: ruamel.yaml in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (0.16.12)\n    Requirement already satisfied: scikit-learn in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (0.24.1)\n    Requirement already satisfied: omegaconf<2.1.0,>=2.0.5 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (2.0.6)\n    Requirement already satisfied: hydra-core>=1.0.4 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (1.0.6)\n    Requirement already satisfied: transformers>=4.0.1 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (4.1.1)\n    Requirement already satisfied: sentencepiece<1.0.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (0.1.95)\n    Requirement already satisfied: webdataset>=0.1.48 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (0.1.62)\n    Requirement already satisfied: tqdm>=4.41.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (4.51.0)\n    Requirement already satisfied: opencc in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (1.1.1)\n    Requirement already satisfied: pangu in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (4.0.6.1)\n    Requirement already satisfied: jieba in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (0.42.1)\n    Requirement already satisfied: numba in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (0.52.0)\n    Requirement already satisfied: braceexpand in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (0.1.7)\n    Requirement already satisfied: editdistance in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (0.5.3)\n    Requirement already satisfied: frozendict in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (2.0.2)\n    Requirement already satisfied: inflect in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (5.0.2)\n    Requirement already satisfied: kaldi-io in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (0.9.4)\n    Requirement already satisfied: librosa in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (0.8.0)\n    Requirement already satisfied: marshmallow in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (3.12.1)\n    Requirement already satisfied: packaging in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (20.9)\n    Requirement already satisfied: soundfile in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (0.10.3.post1)\n    Requirement already satisfied: sox in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (1.4.1)\n    Requirement already satisfied: unidecode in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (1.1.2)\n    Requirement already satisfied: kaldi-python-io in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (1.2.2)\n    Requirement already satisfied: kaldiio in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (2.17.2)\n    Requirement already satisfied: scipy in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (1.6.2)\n    Requirement already satisfied: pandas in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (1.2.3)\n    Requirement already satisfied: g2p_en in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (2.1.0)\n    Requirement already satisfied: pydub in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (0.25.1)\n    Requirement already satisfied: pyannote.core in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (4.1)\n    Requirement already satisfied: pyannote.metrics in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (3.0.1)\n    Requirement already satisfied: pyamg in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (4.1.0)\n    Requirement already satisfied: torch-stft in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (0.1.4)\n    Requirement already satisfied: matplotlib in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nemo_toolkit[asr]) (3.4.1)\n    Requirement already satisfied: antlr4-python3-runtime==4.8 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from hydra-core>=1.0.4->nemo_toolkit[asr]) (4.8)\n    Requirement already satisfied: importlib-resources in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from hydra-core>=1.0.4->nemo_toolkit[asr]) (5.1.4)\n    Requirement already satisfied: typing-extensions in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from omegaconf<2.1.0,>=2.0.5->nemo_toolkit[asr]) (3.7.4.3)\n    Requirement already satisfied: PyYAML>=5.1.* in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from omegaconf<2.1.0,>=2.0.5->nemo_toolkit[asr]) (5.3.1)\n    Requirement already satisfied: six in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from onnx>=1.7.0->nemo_toolkit[asr]) (1.15.0)\n    Requirement already satisfied: protobuf in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from onnx>=1.7.0->nemo_toolkit[asr]) (3.14.0)\n    Requirement already satisfied: fsspec[http]>=0.8.1 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (0.8.7)\n    Requirement already satisfied: torchmetrics==0.2.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (0.2.0)\n    Requirement already satisfied: tensorboard!=2.5.0,>=2.2.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (2.4.1)\n    Requirement already satisfied: future>=0.17.1 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (0.18.2)\n    Requirement already satisfied: requests in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from fsspec[http]>=0.8.1->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (2.25.1)\n    Requirement already satisfied: aiohttp in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from fsspec[http]>=0.8.1->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (3.7.4.post0)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (0.4.2)\n    Requirement already satisfied: absl-py>=0.4 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (0.11.0)\n    Requirement already satisfied: google-auth<2,>=1.6.3 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (1.28.0)\n    Requirement already satisfied: setuptools>=41.0.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (57.0.0)\n    Requirement already satisfied: wheel>=0.26 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (0.36.2)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (1.7.0)\n    Requirement already satisfied: grpcio>=1.24.3 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (1.34.1)\n    Requirement already satisfied: werkzeug>=0.11.15 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (1.0.1)\n    Requirement already satisfied: markdown>=2.6.8 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (3.3.3)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from google-auth<2,>=1.6.3->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (0.2.8)\n    Requirement already satisfied: rsa<5,>=3.1.4 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from google-auth<2,>=1.6.3->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (4.6)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from google-auth<2,>=1.6.3->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (4.2.2)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (1.3.0)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (0.4.8)\n    Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from requests->fsspec[http]>=0.8.1->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (2021.5.30)\n    Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from requests->fsspec[http]>=0.8.1->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (1.26.4)\n    Requirement already satisfied: idna<3,>=2.5 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from requests->fsspec[http]>=0.8.1->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (2.10)\n    Requirement already satisfied: chardet<5,>=3.0.2 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from requests->fsspec[http]>=0.8.1->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (4.0.0)\n    Requirement already satisfied: oauthlib>=3.0.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard!=2.5.0,>=2.2.0->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (3.1.0)\n    Requirement already satisfied: tokenizers==0.9.4 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from transformers>=4.0.1->nemo_toolkit[asr]) (0.9.4)\n    Requirement already satisfied: sacremoses in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from transformers>=4.0.1->nemo_toolkit[asr]) (0.0.43)\n    Requirement already satisfied: filelock in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from transformers>=4.0.1->nemo_toolkit[asr]) (3.0.12)\n    Requirement already satisfied: regex!=2019.12.17 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from transformers>=4.0.1->nemo_toolkit[asr]) (2020.11.13)\n    Requirement already satisfied: async-timeout<4.0,>=3.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from aiohttp->fsspec[http]>=0.8.1->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (3.0.1)\n    Requirement already satisfied: attrs>=17.3.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from aiohttp->fsspec[http]>=0.8.1->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (20.3.0)\n    Requirement already satisfied: multidict<7.0,>=4.5 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from aiohttp->fsspec[http]>=0.8.1->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (5.1.0)\n    Requirement already satisfied: yarl<2.0,>=1.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from aiohttp->fsspec[http]>=0.8.1->pytorch-lightning<=1.2.10,>=1.2.8->nemo_toolkit[asr]) (1.6.3)\n    Requirement already satisfied: distance>=0.1.3 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from g2p_en->nemo_toolkit[asr]) (0.1.3)\n    Requirement already satisfied: nltk>=3.2.4 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from g2p_en->nemo_toolkit[asr]) (3.6.2)\n    Requirement already satisfied: joblib in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nltk>=3.2.4->g2p_en->nemo_toolkit[asr]) (1.0.1)\n    Requirement already satisfied: click in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from nltk>=3.2.4->g2p_en->nemo_toolkit[asr]) (7.1.2)\n    Requirement already satisfied: zipp>=3.1.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from importlib-resources->hydra-core>=1.0.4->nemo_toolkit[asr]) (3.4.1)\n    Requirement already satisfied: decorator>=3.0.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from librosa->nemo_toolkit[asr]) (4.4.2)\n    Requirement already satisfied: audioread>=2.0.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from librosa->nemo_toolkit[asr]) (2.1.9)\n    Requirement already satisfied: pooch>=1.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from librosa->nemo_toolkit[asr]) (1.3.0)\n    Requirement already satisfied: resampy>=0.2.2 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from librosa->nemo_toolkit[asr]) (0.2.2)\n    Requirement already satisfied: llvmlite<0.36,>=0.35.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from numba->nemo_toolkit[asr]) (0.35.0)\n    Requirement already satisfied: appdirs in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from pooch>=1.0->librosa->nemo_toolkit[asr]) (1.4.4)\n    Requirement already satisfied: threadpoolctl>=2.0.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from scikit-learn->nemo_toolkit[asr]) (2.1.0)\n    Requirement already satisfied: cffi>=1.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from soundfile->nemo_toolkit[asr]) (1.14.5)\n    Requirement already satisfied: pycparser in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from cffi>=1.0->soundfile->nemo_toolkit[asr]) (2.20)\n    Requirement already satisfied: pillow>=6.2.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from matplotlib->nemo_toolkit[asr]) (8.1.2)\n    Requirement already satisfied: pyparsing>=2.2.1 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from matplotlib->nemo_toolkit[asr]) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from matplotlib->nemo_toolkit[asr]) (0.10.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from matplotlib->nemo_toolkit[asr]) (1.3.1)\n    Requirement already satisfied: pytz>=2017.3 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from pandas->nemo_toolkit[asr]) (2021.1)\n    Requirement already satisfied: pytest>=2 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from pyamg->nemo_toolkit[asr]) (6.2.4)\n    Requirement already satisfied: pluggy<1.0.0a1,>=0.12 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from pytest>=2->pyamg->nemo_toolkit[asr]) (0.13.1)\n    Requirement already satisfied: toml in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from pytest>=2->pyamg->nemo_toolkit[asr]) (0.10.2)\n    Requirement already satisfied: colorama in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from pytest>=2->pyamg->nemo_toolkit[asr]) (0.4.4)\n    Requirement already satisfied: atomicwrites>=1.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from pytest>=2->pyamg->nemo_toolkit[asr]) (1.4.0)\n    Requirement already satisfied: iniconfig in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from pytest>=2->pyamg->nemo_toolkit[asr]) (1.1.1)\n    Requirement already satisfied: py>=1.8.2 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from pytest>=2->pyamg->nemo_toolkit[asr]) (1.10.0)\n    Requirement already satisfied: sortedcontainers>=2.0.4 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from pyannote.core->nemo_toolkit[asr]) (2.3.0)\n    Requirement already satisfied: simplejson>=3.8.1 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from pyannote.core->nemo_toolkit[asr]) (3.17.2)\n    Requirement already satisfied: sympy>=1.1 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from pyannote.metrics->nemo_toolkit[asr]) (1.7.1)\n    Requirement already satisfied: pyannote.database>=4.0.1 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from pyannote.metrics->nemo_toolkit[asr]) (4.1)\n    Requirement already satisfied: docopt>=0.6.2 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from pyannote.metrics->nemo_toolkit[asr]) (0.6.2)\n    Requirement already satisfied: tabulate>=0.7.7 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from pyannote.metrics->nemo_toolkit[asr]) (0.8.9)\n    Requirement already satisfied: typer[all]>=0.2.1 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from pyannote.database>=4.0.1->pyannote.metrics->nemo_toolkit[asr]) (0.3.2)\n    Requirement already satisfied: mpmath>=0.19 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from sympy>=1.1->pyannote.metrics->nemo_toolkit[asr]) (1.1.0)\n    Requirement already satisfied: shellingham<2.0.0,>=1.3.0 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from typer[all]>=0.2.1->pyannote.database>=4.0.1->pyannote.metrics->nemo_toolkit[asr]) (1.4.0)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2 in c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages (from ruamel.yaml->nemo_toolkit[asr]) (0.2.2)\n\n\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n      Running command git clone -q https://github.com/NVIDIA/NeMo.git 'C:\\Users\\hapir\\AppData\\Local\\Temp\\pip-install-wvlmdsim\\nemo-toolkit_03d2625ee8c249faaeaf8e6a92cf3297'\n      Running command git checkout -b v1.0.0 --track origin/v1.0.0\n      Branch 'v1.0.0' set up to track remote branch 'v1.0.0' from 'origin'.\n      Switched to a new branch 'v1.0.0'\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    WARNING: Ignoring invalid distribution -illow (c:\\users\\hapir\\anaconda3\\envs\\bigai\\lib\\site-packages)\n    A subdirectory or file configs already exists.\n\n\nThis notebook demonstrates automatic speech recognition (ASR) from a microphone's stream in NeMo.\n\nIt is **not a recommended** way to do inference in production workflows. If you are interested in \nproduction-level inference using NeMo ASR models, please sign-up to Jarvis early access program: https://developer.nvidia.com/nvidia-jarvis\n\nThe notebook requires PyAudio library to get a signal from an audio device.\nFor Ubuntu, please run the following commands to install it:\n```\nsudo apt-get install -y portaudio19-dev\npip install pyaudio\n```\n\nThis notebook requires the `torchaudio` library to be installed for MatchboxNet. Please follow the instructions available at the [torchaudio Github page](https://github.com/pytorch/audio#installation) to install the appropriate version of torchaudio.\n\nIf you would like to install the latest version, please run the following command to install it:\n\n```\nconda install -c pytorch torchaudio\n```\n\n\n```python\nimport numpy as np\nimport pyaudio as pa\nimport os, time\n```\n\n\n```python\nimport nemo\nimport nemo.collections.asr as nemo_asr\n```\n\n    [NeMo W 2021-06-09 18:34:09 optimizers:46] Apex was not found. Using the lamb optimizer will error out.\n    [NeMo W 2021-06-09 18:34:14 nemo_logging:349] C:\\Users\\hapir\\anaconda3\\envs\\BIGAI\\lib\\site-packages\\torchaudio\\extension\\extension.py:13: UserWarning: torchaudio C++ extension is not available.\n          warnings.warn('torchaudio C++ extension is not available.')\n        \n    ################################################################################\n    ### WARNING, path does not exist: KALDI_ROOT=/mnt/matylda5/iveselyk/Tools/kaldi-trunk\n    ###          (please add 'export KALDI_ROOT=<your_path>' in your $HOME/.profile)\n    ###          (or run as: KALDI_ROOT=<your_path> python <your_script>.py)\n    ################################################################################\n    \n    [NeMo W 2021-06-09 18:34:15 experimental:27] Module <class 'nemo.collections.asr.data.audio_to_text_dali.AudioToCharDALIDataset'> is experimental, not ready for production and is not fully supported. Use at your own risk.\n\n\n\n```python\n# sample rate, Hz\nSAMPLE_RATE = 16000\n```\n\n## Restore the model from NGC\n\n\n```python\nasr_model = nemo_asr.models.EncDecCTCModel.from_pretrained('stt_es_quartznet15x5')\n```\n\n    [NeMo I 2021-06-09 18:34:31 cloud:56] Found existing object C:\\Users\\hapir\\.cache\\torch\\NeMo\\NeMo_1.0.0\\stt_es_quartznet15x5\\a65f9c865cfd58f57bfba25a7e44e8e2\\stt_es_quartznet15x5.nemo.\n    [NeMo I 2021-06-09 18:34:31 cloud:62] Re-using file from: C:\\Users\\hapir\\.cache\\torch\\NeMo\\NeMo_1.0.0\\stt_es_quartznet15x5\\a65f9c865cfd58f57bfba25a7e44e8e2\\stt_es_quartznet15x5.nemo\n    [NeMo I 2021-06-09 18:34:31 common:675] Instantiating model from pre-trained checkpoint\n\n\n    [NeMo W 2021-06-09 18:34:32 modelPT:137] If you intend to do training or fine-tuning, please call the ModelPT.setup_training_data() method and provide a valid configuration file to setup the train data loader.\n        Train config : \n        manifest_filepath: /raid/noneval.json\n        sample_rate: 16000\n        labels:\n        - ' '\n        - a\n        - b\n        - c\n        - d\n        - e\n        - f\n        - g\n        - h\n        - i\n        - j\n        - k\n        - l\n        - m\n        - 'n'\n        - o\n        - p\n        - q\n        - r\n        - s\n        - t\n        - u\n        - v\n        - w\n        - x\n        - 'y'\n        - z\n        - ''''\n        - \u00e1\n        - \u00e9\n        - \u00ed\n        - \u00f3\n        - \u00fa\n        - \u00f1\n        - \u00fc\n        batch_size: 16\n        trim_silence: true\n        max_duration: 16.7\n        shuffle: true\n        is_tarred: false\n        tarred_audio_filepaths: null\n        num_workers: 8\n        pin_memory: true\n        \n    [NeMo W 2021-06-09 18:34:32 modelPT:144] If you intend to do validation, please call the ModelPT.setup_validation_data() or ModelPT.setup_multiple_validation_data() method and provide a valid configuration file to setup the validation data loader(s). \n        Validation config : \n        manifest_filepath: /raid/dev.json\n        sample_rate: 16000\n        labels:\n        - ' '\n        - a\n        - b\n        - c\n        - d\n        - e\n        - f\n        - g\n        - h\n        - i\n        - j\n        - k\n        - l\n        - m\n        - 'n'\n        - o\n        - p\n        - q\n        - r\n        - s\n        - t\n        - u\n        - v\n        - w\n        - x\n        - 'y'\n        - z\n        - ''''\n        - \u00e1\n        - \u00e9\n        - \u00ed\n        - \u00f3\n        - \u00fa\n        - \u00f1\n        - \u00fc\n        batch_size: 32\n        shuffle: false\n        num_workers: 8\n        pin_memory: true\n        \n\n\n    [NeMo I 2021-06-09 18:34:32 features:252] PADDING: 16\n    [NeMo I 2021-06-09 18:34:32 features:269] STFT using torch\n    [NeMo I 2021-06-09 18:34:35 modelPT:434] Model EncDecCTCModel was successfully restored from C:\\Users\\hapir\\.cache\\torch\\NeMo\\NeMo_1.0.0\\stt_es_quartznet15x5\\a65f9c865cfd58f57bfba25a7e44e8e2\\stt_es_quartznet15x5.nemo.\n\n\n## Observing the config of the model\n\n\n```python\nfrom omegaconf import OmegaConf\nimport copy\n```\n\n\n```python\n# Preserve a copy of the full config\ncfg = copy.deepcopy(asr_model._cfg)\nprint(OmegaConf.to_yaml(cfg))\n```\n\n    preprocessor:\n      _target_: nemo.collections.asr.modules.AudioToMelSpectrogramPreprocessor\n      normalize: per_feature\n      window_size: 0.02\n      sample_rate: 16000\n      window_stride: 0.01\n      window: hann\n      features: 64\n      n_fft: 512\n      frame_splicing: 1\n      dither: 1.0e-05\n      stft_conv: false\n    spec_augment:\n      _target_: nemo.collections.asr.modules.SpectrogramAugmentation\n      rect_freq: 50\n      rect_masks: 5\n      rect_time: 120\n    encoder:\n      _target_: nemo.collections.asr.modules.ConvASREncoder\n      feat_in: 64\n      activation: relu\n      conv_mask: true\n      jasper:\n      - filters: 256\n        repeat: 1\n        kernel:\n        - 33\n        stride:\n        - 2\n        dilation:\n        - 1\n        dropout: 0.0\n        residual: false\n        separable: true\n      - filters: 256\n        repeat: 5\n        kernel:\n        - 33\n        stride:\n        - 1\n        dilation:\n        - 1\n        dropout: 0.0\n        residual: true\n        separable: true\n      - filters: 256\n        repeat: 5\n        kernel:\n        - 33\n        stride:\n        - 1\n        dilation:\n        - 1\n        dropout: 0.0\n        residual: true\n        separable: true\n      - filters: 256\n        repeat: 5\n        kernel:\n        - 33\n        stride:\n        - 1\n        dilation:\n        - 1\n        dropout: 0.0\n        residual: true\n        separable: true\n      - filters: 256\n        repeat: 5\n        kernel:\n        - 39\n        stride:\n        - 1\n        dilation:\n        - 1\n        dropout: 0.0\n        residual: true\n        separable: true\n      - filters: 256\n        repeat: 5\n        kernel:\n        - 39\n        stride:\n        - 1\n        dilation:\n        - 1\n        dropout: 0.0\n        residual: true\n        separable: true\n      - filters: 256\n        repeat: 5\n        kernel:\n        - 39\n        stride:\n        - 1\n        dilation:\n        - 1\n        dropout: 0.0\n        residual: true\n        separable: true\n      - filters: 512\n        repeat: 5\n        kernel:\n        - 51\n        stride:\n        - 1\n        dilation:\n        - 1\n        dropout: 0.0\n        residual: true\n        separable: true\n      - filters: 512\n        repeat: 5\n        kernel:\n        - 51\n        stride:\n        - 1\n        dilation:\n        - 1\n        dropout: 0.0\n        residual: true\n        separable: true\n      - filters: 512\n        repeat: 5\n        kernel:\n        - 51\n        stride:\n        - 1\n        dilation:\n        - 1\n        dropout: 0.0\n        residual: true\n        separable: true\n      - filters: 512\n        repeat: 5\n        kernel:\n        - 63\n        stride:\n        - 1\n        dilation:\n        - 1\n        dropout: 0.0\n        residual: true\n        separable: true\n      - filters: 512\n        repeat: 5\n        kernel:\n        - 63\n        stride:\n        - 1\n        dilation:\n        - 1\n        dropout: 0.0\n        residual: true\n        separable: true\n      - filters: 512\n        repeat: 5\n        kernel:\n        - 63\n        stride:\n        - 1\n        dilation:\n        - 1\n        dropout: 0.0\n        residual: true\n        separable: true\n      - filters: 512\n        repeat: 5\n        kernel:\n        - 75\n        stride:\n        - 1\n        dilation:\n        - 1\n        dropout: 0.0\n        residual: true\n        separable: true\n      - filters: 512\n        repeat: 5\n        kernel:\n        - 75\n        stride:\n        - 1\n        dilation:\n        - 1\n        dropout: 0.0\n        residual: true\n        separable: true\n      - filters: 512\n        repeat: 5\n        kernel:\n        - 75\n        stride:\n        - 1\n        dilation:\n        - 1\n        dropout: 0.0\n        residual: true\n        separable: true\n      - filters: 512\n        repeat: 1\n        kernel:\n        - 87\n        stride:\n        - 1\n        dilation:\n        - 2\n        dropout: 0.0\n        residual: false\n        separable: true\n      - filters: 1024\n        repeat: 1\n        kernel:\n        - 1\n        stride:\n        - 1\n        dilation:\n        - 1\n        dropout: 0.0\n        residual: false\n    decoder:\n      _target_: nemo.collections.asr.modules.ConvASRDecoder\n      feat_in: 1024\n      num_classes: 35\n      vocabulary:\n      - ' '\n      - a\n      - b\n      - c\n      - d\n      - e\n      - f\n      - g\n      - h\n      - i\n      - j\n      - k\n      - l\n      - m\n      - 'n'\n      - o\n      - p\n      - q\n      - r\n      - s\n      - t\n      - u\n      - v\n      - w\n      - x\n      - 'y'\n      - z\n      - ''''\n      - \u00e1\n      - \u00e9\n      - \u00ed\n      - \u00f3\n      - \u00fa\n      - \u00f1\n      - \u00fc\n    optim:\n      name: novograd\n      lr: 0.0012\n      betas:\n      - 0.8\n      - 0.5\n      weight_decay: 0.001\n      sched:\n        name: CosineAnnealing\n        warmup_steps: 500\n        warmup_ratio: null\n        min_lr: 0.0\n        last_epoch: -1\n    target: nemo.collections.asr.models.ctc_models.EncDecCTCModel\n    train_ds:\n      manifest_filepath: /raid/noneval.json\n      sample_rate: 16000\n      labels:\n      - ' '\n      - a\n      - b\n      - c\n      - d\n      - e\n      - f\n      - g\n      - h\n      - i\n      - j\n      - k\n      - l\n      - m\n      - 'n'\n      - o\n      - p\n      - q\n      - r\n      - s\n      - t\n      - u\n      - v\n      - w\n      - x\n      - 'y'\n      - z\n      - ''''\n      - \u00e1\n      - \u00e9\n      - \u00ed\n      - \u00f3\n      - \u00fa\n      - \u00f1\n      - \u00fc\n      batch_size: 16\n      trim_silence: true\n      max_duration: 16.7\n      shuffle: true\n      is_tarred: false\n      tarred_audio_filepaths: null\n      num_workers: 8\n      pin_memory: true\n    validation_ds:\n      manifest_filepath: /raid/dev.json\n      sample_rate: 16000\n      labels:\n      - ' '\n      - a\n      - b\n      - c\n      - d\n      - e\n      - f\n      - g\n      - h\n      - i\n      - j\n      - k\n      - l\n      - m\n      - 'n'\n      - o\n      - p\n      - q\n      - r\n      - s\n      - t\n      - u\n      - v\n      - w\n      - x\n      - 'y'\n      - z\n      - ''''\n      - \u00e1\n      - \u00e9\n      - \u00ed\n      - \u00f3\n      - \u00fa\n      - \u00f1\n      - \u00fc\n      batch_size: 32\n      shuffle: false\n      num_workers: 8\n      pin_memory: true\n    \n\n\n### Modify preprocessor parameters for inference\n\n\n```python\n# Make config overwrite-able\nOmegaConf.set_struct(cfg.preprocessor, False)\n\n# some changes for streaming scenario\ncfg.preprocessor.dither = 0.0\ncfg.preprocessor.pad_to = 0\n\n# spectrogram normalization constants\nnormalization = {}\nnormalization['fixed_mean'] = [\n     -14.95827016, -12.71798736, -11.76067913, -10.83311182,\n     -10.6746914,  -10.15163465, -10.05378331, -9.53918999,\n     -9.41858904,  -9.23382904,  -9.46470918,  -9.56037,\n     -9.57434245,  -9.47498732,  -9.7635205,   -10.08113074,\n     -10.05454561, -9.81112681,  -9.68673603,  -9.83652977,\n     -9.90046248,  -9.85404766,  -9.92560366,  -9.95440354,\n     -10.17162966, -9.90102482,  -9.47471025,  -9.54416855,\n     -10.07109475, -9.98249912,  -9.74359465,  -9.55632283,\n     -9.23399915,  -9.36487649,  -9.81791084,  -9.56799225,\n     -9.70630899,  -9.85148006,  -9.8594418,   -10.01378735,\n     -9.98505315,  -9.62016094,  -10.342285,   -10.41070709,\n     -10.10687659, -10.14536695, -10.30828702, -10.23542833,\n     -10.88546868, -11.31723646, -11.46087382, -11.54877829,\n     -11.62400934, -11.92190509, -12.14063815, -11.65130117,\n     -11.58308531, -12.22214663, -12.42927197, -12.58039805,\n     -13.10098969, -13.14345864, -13.31835645, -14.47345634]\nnormalization['fixed_std'] = [\n     3.81402054, 4.12647781, 4.05007065, 3.87790987,\n     3.74721178, 3.68377423, 3.69344,    3.54001005,\n     3.59530412, 3.63752368, 3.62826417, 3.56488469,\n     3.53740577, 3.68313898, 3.67138151, 3.55707266,\n     3.54919572, 3.55721289, 3.56723346, 3.46029304,\n     3.44119672, 3.49030548, 3.39328435, 3.28244406,\n     3.28001423, 3.26744937, 3.46692348, 3.35378948,\n     2.96330901, 2.97663111, 3.04575148, 2.89717604,\n     2.95659301, 2.90181116, 2.7111687,  2.93041291,\n     2.86647897, 2.73473181, 2.71495654, 2.75543763,\n     2.79174615, 2.96076456, 2.57376336, 2.68789782,\n     2.90930817, 2.90412004, 2.76187531, 2.89905006,\n     2.65896173, 2.81032176, 2.87769857, 2.84665271,\n     2.80863137, 2.80707634, 2.83752184, 3.01914511,\n     2.92046439, 2.78461139, 2.90034605, 2.94599508,\n     2.99099718, 3.0167554,  3.04649716, 2.94116777]\n\ncfg.preprocessor.normalize = normalization\n\n# Disable config overwriting\nOmegaConf.set_struct(cfg.preprocessor, True)\n```\n\n## Setup preprocessor with these settings\n\n\n```python\nasr_model.preprocessor = asr_model.from_config_dict(cfg.preprocessor)\n```\n\n    [NeMo I 2021-06-09 18:34:46 features:252] PADDING: 0\n    [NeMo I 2021-06-09 18:34:46 features:269] STFT using torch\n\n\n\n```python\n# Set model to inference mode\nasr_model.eval();\n```\n\n\n```python\nasr_model = asr_model.to(asr_model.device)\n```\n\n## Setting up data for Streaming Inference\n\n\n```python\nfrom nemo.core.classes import IterableDataset\nfrom nemo.core.neural_types import NeuralType, AudioSignal, LengthsType\nimport torch\nfrom torch.utils.data import DataLoader\n```\n\n\n```python\n# simple data layer to pass audio signal\nclass AudioDataLayer(IterableDataset):\n    @property\n    def output_types(self):\n        return {\n            'audio_signal': NeuralType(('B', 'T'), AudioSignal(freq=self._sample_rate)),\n            'a_sig_length': NeuralType(tuple('B'), LengthsType()),\n        }\n\n    def __init__(self, sample_rate):\n        super().__init__()\n        self._sample_rate = sample_rate\n        self.output = True\n        \n    def __iter__(self):\n        return self\n    \n    def __next__(self):\n        if not self.output:\n            raise StopIteration\n        self.output = False\n        return torch.as_tensor(self.signal, dtype=torch.float32), \\\n               torch.as_tensor(self.signal_shape, dtype=torch.int64)\n        \n    def set_signal(self, signal):\n        self.signal = signal.astype(np.float32)/32768.\n        self.signal_shape = self.signal.size\n        self.output = True\n\n    def __len__(self):\n        return 1\n```\n\n\n```python\ndata_layer = AudioDataLayer(sample_rate=cfg.preprocessor.sample_rate)\ndata_loader = DataLoader(data_layer, batch_size=1, collate_fn=data_layer.collate_fn)\n```\n\n\n```python\n# inference method for audio signal (single instance)\ndef infer_signal(model, signal):\n    data_layer.set_signal(signal)\n    batch = next(iter(data_loader))\n    audio_signal, audio_signal_len = batch\n    audio_signal, audio_signal_len = audio_signal.to(asr_model.device), audio_signal_len.to(asr_model.device)\n    log_probs, encoded_len, predictions = model.forward(\n        input_signal=audio_signal, input_signal_length=audio_signal_len\n    )\n    return log_probs\n```\n\n\n```python\n# class for streaming frame-based ASR\n# 1) use reset() method to reset FrameASR's state\n# 2) call transcribe(frame) to do ASR on\n#    contiguous signal's frames\nclass FrameASR:\n    \n    def __init__(self, model_definition,\n                 frame_len=2, frame_overlap=2.5, \n                 offset=10):\n        '''\n        Args:\n          frame_len: frame's duration, seconds\n          frame_overlap: duration of overlaps before and after current frame, seconds\n          offset: number of symbols to drop for smooth streaming\n        '''\n        self.vocab = list(model_definition['labels'])\n        self.vocab.append('_')\n        \n        self.sr = model_definition['sample_rate']\n        self.frame_len = frame_len\n        self.n_frame_len = int(frame_len * self.sr)\n        self.frame_overlap = frame_overlap\n        self.n_frame_overlap = int(frame_overlap * self.sr)\n        timestep_duration = model_definition['AudioToMelSpectrogramPreprocessor']['window_stride']\n        for block in model_definition['JasperEncoder']['jasper']:\n            timestep_duration *= block['stride'][0] ** block['repeat']\n        self.n_timesteps_overlap = int(frame_overlap / timestep_duration) - 2\n        self.buffer = np.zeros(shape=2*self.n_frame_overlap + self.n_frame_len,\n                               dtype=np.float32)\n        self.offset = offset\n        self.reset()\n        \n    def _decode(self, frame, offset=0):\n        assert len(frame)==self.n_frame_len\n        self.buffer[:-self.n_frame_len] = self.buffer[self.n_frame_len:]\n        self.buffer[-self.n_frame_len:] = frame\n        logits = infer_signal(asr_model, self.buffer).cpu().numpy()[0]\n        # print(logits.shape)\n        decoded = self._greedy_decoder(\n            logits[self.n_timesteps_overlap:-self.n_timesteps_overlap], \n            self.vocab\n        )\n        return decoded[:len(decoded)-offset]\n    \n    @torch.no_grad()\n    def transcribe(self, frame=None, merge=True):\n        if frame is None:\n            frame = np.zeros(shape=self.n_frame_len, dtype=np.float32)\n        if len(frame) < self.n_frame_len:\n            frame = np.pad(frame, [0, self.n_frame_len - len(frame)], 'constant')\n        unmerged = self._decode(frame, self.offset)\n        if not merge:\n            return unmerged\n        return self.greedy_merge(unmerged)\n    \n    def reset(self):\n        '''\n        Reset frame_history and decoder's state\n        '''\n        self.buffer=np.zeros(shape=self.buffer.shape, dtype=np.float32)\n        self.prev_char = ''\n\n    @staticmethod\n    def _greedy_decoder(logits, vocab):\n        s = ''\n        for i in range(logits.shape[0]):\n            s += vocab[np.argmax(logits[i])]\n        return s\n\n    def greedy_merge(self, s):\n        s_merged = ''\n        \n        for i in range(len(s)):\n            if s[i] != self.prev_char:\n                self.prev_char = s[i]\n                if self.prev_char != '_':\n                    s_merged += self.prev_char\n        return s_merged\n```\n\n# Streaming Inference\n\nStreaming inference depends on a few factors, such as the frame length and buffer size. Experiment with a few values to see their effects in the below cells.\n\n\n```python\n# duration of signal frame, seconds\nFRAME_LEN = 1.0\n# number of audio channels (expect mono signal)\nCHANNELS = 1\n\nCHUNK_SIZE = int(FRAME_LEN*SAMPLE_RATE)\nasr = FrameASR(model_definition = {\n                   'sample_rate': SAMPLE_RATE,\n                   'AudioToMelSpectrogramPreprocessor': cfg.preprocessor,\n                   'JasperEncoder': cfg.encoder,\n                   'labels': cfg.decoder.vocabulary\n               },\n               frame_len=FRAME_LEN, frame_overlap=2, \n               offset=4)\n```\n\n\n```python\nasr.reset()\n\np = pa.PyAudio()\nprint('Available audio input devices:')\ninput_devices = []\nfor i in range(p.get_device_count()):\n    dev = p.get_device_info_by_index(i)\n    if dev.get('maxInputChannels'):\n        input_devices.append(i)\n        print(i, dev.get('name'))\n\nif len(input_devices):\n    dev_idx = -2\n    while dev_idx not in input_devices:\n        print('Please type input device ID:')\n        dev_idx = int(input())\n\n    empty_counter = 0\n\n    def callback(in_data, frame_count, time_info, status):\n        global empty_counter\n        signal = np.frombuffer(in_data, dtype=np.int16)\n        text = asr.transcribe(signal)\n        if len(text):\n            print(text,end='')\n            empty_counter = asr.offset\n        elif empty_counter > 0:\n            empty_counter -= 1\n            if empty_counter == 0:\n                print(' ',end='')\n        return (in_data, pa.paContinue)\n\n    stream = p.open(format=pa.paInt16,\n                    channels=CHANNELS,\n                    rate=SAMPLE_RATE,\n                    input=True,\n                    input_device_index=dev_idx,\n                    stream_callback=callback,\n                    frames_per_buffer=CHUNK_SIZE)\n\n    print('Listening...')\n\n    stream.start_stream()\n    \n    # Interrupt kernel and then speak for a few more words to exit the pyaudio loop !\n    try:\n        while stream.is_active():\n            time.sleep(0.1)\n    finally:        \n        stream.stop_stream()\n        stream.close()\n        p.terminate()\n\n        print()\n        print(\"PyAudio stopped\")\n    \nelse:\n    print('ERROR: No audio input device found.')\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "2a6bc6816c5eb3de1fad57e8507dbf38489220de", "size": 59821, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "SOUND/VOICE/STT/.ipynb_checkpoints/NEMO_ES_MIC_REAL_TIME-checkpoint.ipynb", "max_stars_repo_name": "aleksandermajos/BIGBANGLANG", "max_stars_repo_head_hexsha": "2890b0416df9d460292f5c529307b3e2ecbc8143", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-12-30T06:50:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T07:42:59.000Z", "max_issues_repo_path": "SOUND/VOICE/STT/.ipynb_checkpoints/NEMO_ES_MIC_REAL_TIME-checkpoint.ipynb", "max_issues_repo_name": "aleksandermajos/BIGBANGLANG", "max_issues_repo_head_hexsha": "2890b0416df9d460292f5c529307b3e2ecbc8143", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SOUND/VOICE/STT/.ipynb_checkpoints/NEMO_ES_MIC_REAL_TIME-checkpoint.ipynb", "max_forks_repo_name": "aleksandermajos/BIGBANGLANG", "max_forks_repo_head_hexsha": "2890b0416df9d460292f5c529307b3e2ecbc8143", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.6997708174, "max_line_length": 1082, "alphanum_fraction": 0.565135989, "converted": true, "num_tokens": 14834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10970577096716554, "lm_q2_score": 0.03676946554783728, "lm_q1q2_score": 0.00403382256597612}}
{"text": "# On the viability of crowdsourcing NLP annotations in healthcare\n\n\n```python\n__author__  = 'Bruno Godefroy'\n```\n\n__TL;DR__ For most annotation tasks in healthcare, we must rely on trained experts, who are always in high-demand, creating a bottleneck for system development. Can we address this limitation by crowdsourcing the easier annotation tasks in this space? We report on an experiment addressing this question, with a focus on how to identify problematic workers and infer reliable annotations from noisy crowd work.\n\n## Overview\n\nObtaining high-quality annotations is a bottleneck for all natural language processing applications. The challenges are especially severe in healthcare, where we rely on annotators who have expertise in the practice of medicine and in understanding medical texts, and who are authorized to access sensitive data. Such annotators are in high-demand and thus demand high prices. The question then arises whether we can ease the burden on these annotators by crowdsourcing the less demanding annotation tasks involving publicly-available data, reserving the experts for where they are truly needed.\n\nThis post reports on a crowdsourcing experiment we ran to explore this issue. We defined a reasonably nuanced span-identification task, and launched it on [Figure Eight](https://www.figure-eight.com). As expected, the output was noisy, as a result of the highly variable pool of annotators we tapped into. To infer quality labels from this noisy process, we used a straightforward application of Expectation-Maximization, with quite good results, suggesting that crowdsourcing is an effective tool for obtaining annotations for at least some NLP problems in healthcare.\n\n## Crowdsourcing task definition\n\nThe publicly available [FDA Drug Labels data set](https://labels.fda.gov) is a rich source of information about how drugs relate to disease states (among other things). Since it's a public dataset, we don't have to address privacy concerns, which are of course another limiting factor when it comes to annotating data in healthcare.\n\nFor our pilot task, we decided to focus on developing annotations to facilitate automatic extraction of the core drug\u2013disease relationships expressed in these labels, as exemplified in <a href='#fig1'>figure 1</a>. This is [a problem we've worked on before](https://roamanalytics.com/2018/02/02/retrofitting-distributional-embeddings-to-knowledge-graphs-with-functional-relations/), so we have a good sense for what information should be extracted. \n\n<div id='fig1'>\n    \n    <p style='text-align: center; font-style: italic; font-size: 13px; max-width: 400px; margin: 15px auto auto auto;'>Figure 1: Annotated sentences from a drug label.</p>\n</div>\n\nWe need our NLP model to identify the disease mentions in these texts and determine the sense for those mentions. Our own high-level exploration of the data led us to the label set _prevents_, _treats_, and _is contraindicated for_ as the right set of high-level categories for the mentions. This annotation design is motivated by recent experiments which gave encouraging results on similar tasks [<a href='#ref_maclean'>1</a>, <a href='#ref_tenuto'>2</a>].\n\nFor crowdsourcing, we break this down into two separate tasks: identifying disease mentions spans, and assigning categories to identified spans. (Breaking the task down in this way isn't strictly speaking necessary, but it eases the burden on individual annotators). Since the span identification task is more open-ended and challenging, it's the one we explore in this post.\n\nWe developed a short annotation manual with examples, had an in-house expert label 50 sentences for quality control, and used the Figure Eight platform to design a simple annotation interface (<a href='#fig2'>figure 2</a>).\n\n<div id='fig2'>\n    \n    <p style='text-align: center; font-style: italic; font-size: 13px; max-width: 600px; margin: 5px auto auto auto;'>Figure 2: The interface for our first task. Crowdworkers are asked to select disease, symptoms and injury mentions in a sentence. Some drug and disease mentions are automatically underlined using fixed lexicons to help the workers understand the texts.</p>\n</div>\n\n## Who completed our task on Figure Eight?\n\nWe launched our task on Figure Eight with 10,000 sentences. It was completed within a few days. The job was done by 451 people from 45 countries, the majority from India and Venezuela. No special qualifications were imposed.\n\nMost workers made just a few contributions in a short period of time, as figures <a href='#fig3'>3</a> and <a href='#fig4'>4</a> show. Half of the sessions (continuous periods of work) lasted less than 20 minutes; at the upper end, 7% were more than an hour and a half. This is expected given recent studies of crowdworkers' behaviors [<a href='#ref_zhai'>3</a>, <a href='#ref_amerYahia'>4</a>].\n\n<div style='text-align: center;'>\n    <div id='fig3' style='margin-right: 25px; display: inline-block; vertical-align: top;'>\n        \n        <p style='text-align: center; font-style: italic; margin-top: 5px; font-size: 13px; line-height: 19px;'>Figure 3: Number of work sessions per contributor.</p>\n    </div>\n    <div id='fig4' style='display: inline-block; vertical-align: top;'>\n        \n        <p style='text-align: center; font-style: italic; margin-top: 5px; font-size: 13px; line-height: 19px;'>Figure 4: Work session durations.</p>\n    </div>\n</div>\n\n## Assessment against gold labels\n\nGiven our large and diverse pool of workers, we expect some of them to be unreliable, perhaps due to a lack of expertise or a lack of attention. With Figure Eight, we can supply our own labeled examples for a subset of cases, to help identify and filter out unreliable workers. <a href='#fig5'>Figure 5</a> summarizes the work of 100 annotators who were rejected from our task based on their performance on this gold data.\n\n<div id='fig5'>\n    \n    <p style='text-align: center; font-style: italic; font-size: 13px; max-width: 480px; margin: 5px auto auto auto;'>Figure 5: Main reason for failing out of our gold-label assessment. Results come from the manual study of the output from 100 workers who didn't pass the test.</p>\n</div>\n\nIt seems that several workers attempted cheating strategies, such as selecting no text segments at all. Our gold labels help us identify such work. We also see evidence that some workers used auxiliary tools to translate the full Figure Eight interface into another language, including the sentences to annotate, with the result that the responses they submitted were in that language!\n\n## From noisy judgments to crowd truth\n\nShould we blindly trust all the judgments of all the workers who passed our gold-label assessment? Probably not. Some errors are inevitable even for careful workers, and some malicious workers are likely to slip past our assessment against our gold examples. Furthermore, there are bound to be cases that are ambiguous or open to interpretation, leading to multiple right answers that we ourselves might not have fully appreciated, as in [figure 6](#fig6).\n\n<div id='fig6'>\n    \n    <p style='text-align: center; font-style: italic; font-size: 13px; max-width: 500px; margin: 5px auto auto auto;'>Figure 6: An ambiguous case. Should \"feelings of sadness related to winter\" be selected as a disease? Or a symptom?</p>\n</div>\n\nThe most basic step we can take to address these concerns is to collect multiple judgments from many different annotators, in the hope that a consensus emerges. We could define consensus in various ways \u2013 e.g., the majority label, or at least 70% agreement on a label (leaving some cases without a label at all). However, these approaches are clearly suboptimal because they make the implicit assumption that all workers are equally trustworthy, by giving equal weight to all of them. To address this, we use a simple application of the [Expectation-Maximization (EM) method](https://en.wikipedia.org/wiki/Expectation\u2013maximization_algorithm) to our matrix of worker judgments.\n\nOur guiding idea is that \"*disagreement is not noise but signal*\" [[5](#ref_aroyo)]. Assuming the majority is usually right, it's probably worth giving more credit to workers who often agree with each other. Following this intuition, Dawid and Skene [[6](#ref_dawidSkene)] propose a simple model which uses EM to estimate response confidence and workers' reliability in an efficient way. [Figure 7](#fig7) provides an overview of this algorithm, which we state in full in an [appendix](#appendix).\n\n<div id='fig7'>\n    \n    <p style='text-align: center; font-style: italic; font-size: 13px; max-width: 400px; margin: 5px auto auto auto;'>Figure 7: The Expectation-Maximization algorithm for inferring labels from crowd work.</p>\n</div>\n\nLet's consider a small example where we want to find the responses to five boolean questions using a crowd of four workers. For each question, we collect three True/False (T/F) judgments.\n\n<div id='tab1'>\n    <table>\n      <tr>\n        <th></th>\n        <th>Worker 1</th>\n        <th>Worker 2 </th>\n        <th>Worker 3</th>\n        <th>Worker 4</th>\n        <th style='background-color: #d6e5d6;'>True response</th>\n      </tr>\n      <tr>\n        <td><b>Question 1</b></td>\n        <td style='text-align: center;'>T</td>\n        <td style='text-align: center;'>T</td>\n        <td style='text-align: center;'>T</td>\n        <td style='text-align: center;'></td>\n        <td style='text-align: center; background-color: #ecf5ec;'>T</td>\n      </tr>\n      <tr>\n        <td><b>Question 2</b></td>\n        <td style='text-align: center;'></td>\n        <td style='text-align: center;'>F</td>\n        <td style='text-align: center;'>F</td>\n        <td style='text-align: center;'>T</td>\n        <td style='text-align: center; background-color: #ecf5ec;'>F</td>\n      </tr>\n      <tr>\n        <td><b>Question 3</b></td>\n        <td style='text-align: center;'>T</td>\n        <td style='text-align: center;'>T</td>\n        <td style='text-align: center;'>F</td>\n        <td style='text-align: center;'></td>\n        <td style='text-align: center; background-color: #ecf5ec;'>T</td>\n      </tr>\n      <tr>\n        <td><b>Question 4</b></td>\n        <td style='text-align: center;'>F</td>\n        <td style='text-align: center;'></td>\n        <td style='text-align: center;'>F</td>\n        <td style='text-align: center;'>T</td>\n        <td style='text-align: center; background-color: #ecf5ec;'>F</td>\n      </tr>\n      <tr>\n        <td><b>Question 5</b></td>\n        <td style='text-align: center;'>F</td>\n        <td style='text-align: center;'>T</td>\n        <td style='text-align: center;'></td>\n        <td style='text-align: center;'>T</td>\n        <td style='text-align: center; background-color: #ecf5ec;'>F</td>\n      </tr>\n    </table>\n    \n   <p style='text-align: center; font-style: italic; font-size: 13px; max-width: 450px; margin: 10px auto auto auto;'>Table 1: Dummy collected judgments and true response (that we don't have), for each question.</p>\n</div>\n\nWorker 1 looks highly reliable: where it contributed annotations, it always agrees with our true response. Workers 2 and 4 have low *precision* in the sense that they sometimes say T when the correct label is F. Conversely, Worker 3 has low *recall* in the sense that he sometimes says F when the correct label is T.\n\nOf course, we crowdsource precisely because we don't have these true responses \u2013 we have to try to uncover them given only the matrix of worker judgments. With EM, we do this by jointly estimating the reliability of each worker and the response that maximizes the likelihood of the observed judgments.\n\n[Table 2](#tab2) gives the output of the algorithm for this simple example. The *crowd response* is the one derived from the EM algorithm; T when the maximum likelihood estimate is larger than 0.5, F otherwise. Our implementation ([available on Github](https://github.com/roaminsight/analysis_notebooks/blob/crowdsourcing-blogpost/Blog_posts/develop/2018-07-02-crowdsourcing_annotation/EM_example.py)) converges after 8 iterations. \n\n<div id='tab2'>\n    <table>\n      <tr>\n        <th></th>\n        <th>Maximum likelihood estimate</th>\n        <th>Derived crowd response</th>\n        <th style='background-color: #d6e5d6;'>True response</th>\n      </tr>\n      <tr>\n        <td><b>Question 1</b></td>\n        <td style='text-align: center;'>0.99</td>\n        <td style='text-align: center;'>T</td>\n        <td style='text-align: center; background-color: #ecf5ec;'>T</td>\n      </tr>\n      <tr>\n        <td><b>Question 2</b></td>\n        <td style='text-align: center;'>0.01</td>\n        <td style='text-align: center;'>F</td>\n        <td style='text-align: center; background-color: #ecf5ec;'>F</td>\n      </tr>\n      <tr>\n        <td><b>Question 3</b></td>\n        <td style='text-align: center;'>0.98</td>\n        <td style='text-align: center;'>T</td>\n        <td style='text-align: center; background-color: #ecf5ec;'>T</td>\n      </tr>\n      <tr>\n        <td><b>Question 4</b></td>\n        <td style='text-align: center;'>0.08</td>\n        <td style='text-align: center;'>F</td>\n        <td style='text-align: center; background-color: #ecf5ec;'>F</td>\n      </tr> \n      <tr>\n        <td><b>Question 5</b></td>\n        <td style='text-align: center;'>0.28</td>\n        <td style='text-align: center;'>F</td>\n        <td style='text-align: center; background-color: #ecf5ec;'>F</td>\n      </tr>\n    </table>\n\n<p style='text-align: center; font-style: italic; font-size: 13px; max-width: 450px; margin: 10px auto auto auto;'>Table 2: Estimated maximum likelihood responses.</p>\n</div>\n\nThe algorithm does well here and shows how weighting contributions, using inter-worker agreement, can be valuable for judgment aggregation. All the responses derived from the crowd are correct according to our gold labels. For the first four questions, the model has high confidence in its estimate. For question 5, though the majority voted T, the model correctly infers F as the label because worker 1's judgments are given more weight than the others' judgments.\n\nThe individual workers' performance estimates, [table 3](#tab3), look good too. Despite the small amount of data, the algorithm successfully figured out that worker 1 was very reliable, workers 2 and 4 had low precision and worker 3 had low recall.\n\n<div id='tab3'>\n    <table>\n      <tr>\n        <th></th>\n        <th>Estimated precision</th>\n        <th style='background-color: #d6e5d6;'>True precision</th>\n        <th>Estimated recall</th>\n        <th style='background-color: #d6e5d6;'>True recall</th>\n      </tr>\n      <tr>\n        <td><b>Worker 1</b></td>\n        <td style='text-align: center;'>0.99</td>\n        <td style='text-align: center; background-color: #ecf5ec;'>1.0</td>\n        <td style='text-align: center;'>0.84</td>\n        <td style='text-align: center; background-color: #ecf5ec;'>1.0</td>\n      </tr>\n      <tr>\n        <td><b>Worker 2</b></td>\n        <td style='text-align: center;'>0.75</td>\n        <td style='text-align: center; background-color: #ecf5ec;'>0.67</td>\n        <td style='text-align: center;'>0.99</td>\n        <td style='text-align: center; background-color: #ecf5ec;'>1.0</td>\n      </tr>\n      <tr>\n        <td><b>Worker 3</b></td>\n        <td style='text-align: center;'>0.99</td>\n        <td style='text-align: center; background-color: #ecf5ec;'>1.0</td>\n        <td style='text-align: center;'>0.48</td>\n        <td style='text-align: center; background-color: #ecf5ec;'>0.5</td>\n      </tr>\n      <tr>\n        <td><b>Worker 4</b></td>\n        <td style='text-align: center;'>0.12</td>\n        <td style='text-align: center; background-color: #ecf5ec;'>0.0</td>\n        <td style='text-align: center;'>0.99</td>\n        <td style='text-align: center; background-color: #ecf5ec;'>/</td>\n      </tr>\n    </table>\n\n<p style='text-align: center; font-style: italic; font-size: 13px; max-width: 400px; margin: 10px auto auto auto;'>Table 3: Workers' performance estimates.</p>\n</div>\n\nSeveral extensions of this and other methods [<a href='#ref_raykar'>7</a>, <a href='#ref_whitehill'>8</a>, <a href='#ref_karger'>9</a>, <a href='#ref_zhang'>10</a>] have been proposed for this problem. Zhang et al. [<a href='#ref_zhang'>10</a>], for example, address the issue of getting trapped in a local optimum with EM by computing initial parameter estimates with a spectral method, rather than initializing them randomly. Other approaches focus on modeling micro-task difficulty along with worker reliability [<a href='#ref_whitehill'>8</a>].\n\n## The wisdom of our crowd\n\nThere is evidence that, in many settings, a crowd of non-experts can collectively offer estimates that match or exceed those of individual experts [<a href='#ref_surowiecki'>11</a>, <a href='#ref_antweiler'>12</a>, <a href='#ref_chen'>13</a>, <a href='#ref_nofer'>14</a>]. Is this true of our crowd of Figure Eight workers?\n\nTo address this question, we applied the EM algorithm as described above. Since many of our disease spans are multi-word expressions, we do this at the token level: for each token selected by at least one worker, its probability to be a disease mention is estimated. \n\nTo begin, we hope that most tokens end up with a probability close to 0 or 1, that is, a high confidence of being part of an entity of interest or not. [Figure 8](#fig8) shows that this is the case.\n\n<div id='fig8'>\n    \n    <p style='text-align: center; font-style: italic; font-size: 13px; max-width: 400px; margin: 5px auto auto auto;'>Figure 8: The distribution of probabilities estimated with EM, after 1, 2 and 10 iterations (convergence).</p>\n</div>\n\nNext, we randomly selected 1,000 tokens from our task and presented them (in their linguistic context) to an in-house expert for labeling. We then compared these expert-provided labels with the ones inferred from the crowd work. [Figure 9](#fig9) summarizes this evaluation, which uses the standard classification metrics of [precision, recall, and F1](https://en.wikipedia.org/wiki/Precision_and_recall). \n\n<div id='fig9' style='text-align: center;'>\n    \n    <p style='text-align: center; font-style: italic; font-size: 13px; margin: 5px auto auto auto;'>Figure 9: Precision, recall and F1 scores at various confidence thresholds for each aggregation method.</p>\n</div>\n\nWe see that the crowd does well. At a threshold of 0.5, precision and recall are above 0.8, which is comparable to results claimed by MacLean et al. in a similar entity extraction task [<a href='#ref_maclean'>1</a>].  \n\nIn this experiment, it appears that most workers have high precision, but recall is very diverse (see [our last section](#Facing-the-crowd)). Therefore, weighting contributions with EM does not really impact the precision of the crowd; majority voting (orange curve) and EM (blue curve) give similar results. For recall, however, since there is high variance among contributors, giving more weight to high-recall workers significantly improves the crowd response.\n\nAssuming a majority of workers are mostly \"noise\", one could also consider, for each sentence, only the judgment from the most reliable worker according to EM (green curve). In this experiment, this still performs better than majority voting but does not beat the weighted aggregation of all available judgments (blue curve). \n\n## Facing the crowd\n\nEM estimates individual worker reliability and can therefore help us understand individual behaviors in the crowd. To that end, [figure 10](#fig10) shows the timeline of each work session (a continuous period of work for one contributor).\n\n<div id='fig10'>\n    \n    <p style='text-align: center; font-style: italic; font-size: 13px; max-width: 400px; margin: 5px auto auto auto;'>Figure 10: Precision and recall against time during work sessions. Clusters are represented with distinct colors.</p>\n</div>\n\nAs we noted above, most workers have high precision, while recall is very diverse. That is, quality issues mostly come from missing relevant mentions rather than selecting some wrong ones. This is evident in the figure: most of the timelines are near the top of the plot, but they are spread out over the recall axis.\n\nOne could think that aggregation could easily fix this bad recall: by combining multiple high-precision, low-recall judgments, we would end up with high-precision, high-recall annotations. We see however that there is a high correlation between workers' behavior; they tend to miss the same text segments. In our task, this has a likely explanation: to maximize profit, workers might choose to increase their judgment rate at the cost of reducing work quality. By reading sentences superficially, they would identify the most obvious relevant mentions while missing more demanding ones. This strategy could go unnoticed during judgment collection because our gold-label assessment deliberately avoids difficult cases and ambiguity.\n\nUsing dynamic time warping (DTW) to measure similarity between these time series (see [this blog post for discussion of DTW](https://roamanalytics.com/2016/11/28/shape-matching-with-time-series-data/)), we identified 4 distinct clusters of work sessions. These correspond to the different colors in [figure 10](#fig10):\n\n* Light blue (1,050 timelines): The largest cluster, consisting mostly of short sessions. \n\n* Yellow (6 timelines): Very low precision and very low recall. These workers unfortunately slipped through our gold-label assessment. \n\n* Orange (15 timelines): High precision and very low recall, probably from workers who selected almost no text segments. \n\n* Dark blue (31 timelines): Long sessions consisting of reliable annotations.\n\nThis analysis highlights the diversity of the crowd and strengthens our intuition that weighting contributions with individual reliability, estimated using inter-worker agreement, is valuable. A judgment from a dark blue session in [figure 10](#fig10) should be given way more credit than one from the orange cluster.\n\nAlthough, these findings also reveal that a large group of workers with similar biases might lead to misleading results with EM. For example, a large group of consistently wrong workers would appear to be reliable and might even drown out the work of a smaller, more reliable group. Any unsupervised method will have weaknesses like this, which highlights the importance of having at least some expert annotators reviewing the work.\n\n## Looking ahead\n\nThe above findings are reassuring \u2013 we might in fact be able to relieve some of the annotation burden from trained experts by using crowdsourcing. It remains to be seen where the boundary lies between work the crowd can do and work that requires experts, especially as we find ways to break down very challenging tasks into simpler component parts that crowdworkers can succeed at.\n\n## Appendix: A closer look to Expectation-Maximization<span id='appendix'></span>\n\nLet's have a closer look to the EM algorithm. We consider an experiment where we want to find the response $r_i$ to questions $i$, using some noisy judgments $J_i$ collected from workers $k$. For each question, we collect boolean judgments $j_{ik}$ (T/F, or None if the worker did not respond to question $i$). Workers reliability is modeled with $\\Theta = \\theta_1, \\ldots, \\theta_k$.\n\nWe assume judgments are independent between questions for a given worker (no gain of experience) and between workers for a given question (no inter-worker communication).\n\nWe describe below the main steps of the algorithm (see [figure 7](#fig7) above).\n\n### Initialization\nSince we have no prior knowledge of workers' trustworthiness, their reliability parameters $\\Theta$ are initialized to reasonable values based on what we might expect from workers in pools like ours.\n\n### Expectation\nDuring the *expectation* step, workers' performance is re-estimated, given the output from the *maximization* step. Here, we will model workers quality with the true positive, false positive, true negative and false negative rates.\n\n### Maximization\nIn this step, we calculate, for each question $i$, the maximum likelihood estimate that the true response $r_i$ is positive, given the collected judgments $J_i$: $p(r_i = \\text{T} \\mid J_i, \\Theta)$.  \n\nUsing Bayes' theorem: \n\n$$\n\\begin{align}\n    p(r_i = \\text{T} \\mid J_i, \\Theta) &= \\frac{p(J_i \\mid r_i = \\text{T}, \\Theta) p(r_i = \\text{T})}{p(J_i \\mid \\Theta)}\n\\end{align}\n$$\n\nWe know that\n\n$$\n\\begin{align}\n    p(J_i \\mid \\Theta) = \n    p(J_i \\mid r_i=\\text{T}, \\Theta)p(r_i=\\text{T}) + \n    p(J_i \\mid r_i=\\text{F}, \\Theta)p(r_i=\\text{F})\n\\end{align}\n$$\n\nBy substitution, assuming the T and F response outcomes are equiprobable, i.e. $p(r_i = \\text{T}) = p(r_i = \\text{F})$, we obtain\n\n$$\n\\begin{align}\np(r_i= \\text{T} \\mid J_i, \\Theta) &= \n\\frac{\n  p(J_i \\mid, r_i=\\text{T}, \\Theta)\n}{\n p(J_i \\mid r_i = \\text{T}, \\Theta) + \n p(J_i \\mid r_i = \\text{F}, \\Theta)\n} \\\\\n\\end{align}\n$$\n\nBecause we assume worker independence, the collected judgment probability for a given question equals the product of individual judgment probabilities:\n\n$$\np(J_i \\mid r_i, \\Theta) = \\prod_{k} p(j_{ik} \\mid r_i, \\theta_k)\n$$\n\nAll in all,\n\n$$\n\\begin{align}\n    p(r_i = \\text{T} \\mid J_i, \\Theta) = \n    \\prod_{k} \n    \\frac{\n      p(j_k \\mid r_i = \\text{T}, \\theta_k)\n    }{\n      p(j_k \\mid r_i = \\text{T}, \\theta_k) + \n      p(j_k \\mid r_i = \\text{F}, \\theta_k)\n    }\n\\end{align}\n$$\n\nThis probability could be computed from worker's reliability parameters $\\Theta$ (estimated in the expectation step). Indeed, $p(j_k \\mid r_i = \\text{T}, \\theta_k)$ is the true positive rate if $j_k = \\text{T}$ and the false negative rate if $j_k = \\text{F}$. Similarly, for $p(j_k \\mid r_i = \\text{F}, \\theta_k)$, we use the false positive rate if $j_k = \\text{T}$ and the true negative rate if $j_k = \\text{F}$.\n\nSince it maximizes a non-convex log-likelihood function, this approach has no theoretical guarantee of performance, though empirical studies show that it usually converges to good estimates.\n\n## References\n\n<span id='ref_maclean'>[1] D. MacLean, J. Heer. 2013. Identifying medical terms in patient-authored text: A crowdsourcing-based approach. *Journal of the American Medical Informatics Association (JAMIA)*.</span>\n\n<span id='ref_tenuto'>[2] J. Tenuto. 2015. [How scientists are using CrowdFlower to create a massive biomedical database](https://www.figure-eight.com/citizen-science/). Figure Eight's Artificial Intelligence Resource Center.</span>\n\n<span id='ref_zhai'>[3] H. Zhai, T. Lingren, L. Deleger, Q. Li, M. Kaiser, L Stoutenborough, I Solti. 2013. Web 2.0-based crowdsourcing for high-quality gold standard development in clinical natural language processing. *Journal Medical Internet Research*.\n\n<span id='ref_amerYahia'>[4] S. Amer-Yahia, S. Basu Roy. 2016. Toward worker-centric crowdsourcing. *IEEE Data Engineering Bulletin*.</span>\n\n<span id='ref_aroyo'>[5] L. Aroyo, C. Welty. 2013. Measuring crowd truth for medical relation extraction. In AAAI Fall Symposium on Semantics for Big Data.</span>\n\n<span id='ref_dawidSkene'>[6] A. P. Dawid, A. M. Skene. 1979. Maximum likelihood estimation of observer error-rates using the EM algorithm. Journal of the Royal Statistical Society, Series C.</span>\n\n<span id='ref_raykar'>[7] V. Raykar et al. 2009. Supervised learning from multiple experts: Whom to trust when everyone lies a bit. *International Conference on Machine Learning (ICML)*.</span>\n\n<span id='ref_whitehill'>[8] J. Whitehill, T. Wu, J. Bergsma, J.R. Movellan, P.L. Ruvolo. 2009. Whose vote should count more: Optimal integration of labels from labelers of unknown expertise. *Neural Information Processing Systems (NIPS)*.</span>\n\n<span id='ref_karger'>[9] D.R. Karger, S. Oh, D. Shah. 2011. Iterative learning for reliable crowdsourcing systems. *Neural Information Processing Systems (NIPS)*</span>\n\n<span id='ref_zhang'>[10] Y. Zhang, X. Chen, D. Zhou, M. I. Jordan. 2014. Spectral methods meet EM: A provably optimal algorithm for crowdsourcing. *Neural Information Processing Systems (NIPS)*\n\n<span id='ref_surowiecki'>[11] J. Surowiecki. 2005. *The Wisdom of Crowds*. Anchor Books.</span>\n\n<span id='ref_antweiler'>[12] W. Antweiler, M. Z. Frank. 2004. Is all that talk just noise? The information content of Internet stock message boards. *The Journal of Finance*.</span>\n\n<span id='ref_chen'>[13] H. Chen, P. De, Y. Hu, B.-H. Hwang. 2014. Wisdom of crowds: The value of stock opinions transmitted through social media. *Review of Financial Studies*.</span>\n\n<span id='ref_nofer'>[14] M. Nofer, O. Hinz. 2014. Are crowds on the Internet wiser than experts? The case of a stock prediction community. *Journal of Business Economics*.</span>\n", "meta": {"hexsha": "4b623bc9efde338305a0b318cfa20b5e9ef5bd54", "size": 37488, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "BlogPosts/Crowdsourcing_healthcare_annotations/BlogPost.ipynb", "max_stars_repo_name": "markgraves/roamresearch", "max_stars_repo_head_hexsha": "8fd69bc46ee3a30ea87aae7d9890919bc5fa8b82", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 190, "max_stars_repo_stars_event_min_datetime": "2018-03-28T21:50:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T13:29:06.000Z", "max_issues_repo_path": "BlogPosts/Crowdsourcing_healthcare_annotations/BlogPost.ipynb", "max_issues_repo_name": "markgraves/roamresearch", "max_issues_repo_head_hexsha": "8fd69bc46ee3a30ea87aae7d9890919bc5fa8b82", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-05-16T11:30:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-18T22:47:17.000Z", "max_forks_repo_path": "BlogPosts/Crowdsourcing_healthcare_annotations/BlogPost.ipynb", "max_forks_repo_name": "markgraves/roamresearch", "max_forks_repo_head_hexsha": "8fd69bc46ee3a30ea87aae7d9890919bc5fa8b82", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 58, "max_forks_repo_forks_event_min_datetime": "2018-03-28T22:04:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T21:31:02.000Z", "avg_line_length": 51.4238683128, "max_line_length": 740, "alphanum_fraction": 0.6333226633, "converted": true, "num_tokens": 7266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11596072130911701, "lm_q2_score": 0.034618841827190314, "lm_q1q2_score": 0.004014425869167219}}
{"text": "# Homework 3\n### Due Date:  Tuesday, September 20th at 11:59 PM\n\n---\n## Problem 1:  `Git` and recovering from a mistake\nYou will do this problem in the Jupyter notebook so I can see your output.  Once again, you will work with your playground repository.\n\n**NOTE:** At the beginning of each cell, you MUST type `%%bash`.  If you don't do that then you will not be able to work with the necessary bash commands.\n\nFollow the following steps for this problem:\n\n1. First cell:\n  1. Type `cd /tmp` to enter the temporary directory\n  2. git clone url_to_your_playground_repo\n2. Second cell:\n  1. Go into your local `playground` directory (`cd /tmp/playground`)\n  2. Type `git pull origin mybranch1`\n  3. `ls`\n3. Third cell:\n  1. Go into your local `playground` directory (`cd /tmp/playground`)\n  2. Type `git status`\n4. Fourth cell:\n  1. Go into your local `playground` directory (`cd /tmp/playground`)\n  2. Type `git reset --hard origin/master`\n  3. `ls`\n5. Fifth cell:\n  1. Go into your local `playground` directory (`cd /tmp/playground`)\n  2. Type `git status`\n\nThe whole point of this problem was to show you how to get your local repo back to an earlier state.  In this exercise, you accidentally merged something to `master` that you didn't want.  Rather than starting to delete things all over the place, you can simply reset your `HEAD` to a previous commit.\n\n\n```bash\n%%bash\ncd /tmp\nrm -rf playground\ngit clone https://github.com/xuwd11/playground\n```\n\n    Cloning into 'playground'...\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit pull origin mybranch1\nls\n```\n\n    Already up-to-date.\n    books.md\n    feature.txt\n    intro.md\n    world.md\n\n\n    From https://github.com/xuwd11/playground\n     * branch            mybranch1  -> FETCH_HEAD\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit status\n```\n\n    On branch master\n    Your branch is up-to-date with 'origin/master'.\n    \n    nothing to commit, working tree clean\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit reset --hard origin/master\nls\n```\n\n    HEAD is now at 9621d1b Merge branch 'master' of https://github.com/xuwd11/playground\n    books.md\n    feature.txt\n    intro.md\n    world.md\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit status\n```\n\n    On branch master\n    Your branch is up-to-date with 'origin/master'.\n    \n    nothing to commit, working tree clean\n\n\n## Problem 2:  `Git` and checking out a single file\nSometimes you don't want to merge an entire branch from the upstream but just one file from it. There is a direct use case for such a situation. Suppose I've made an error in this homework (or a lecture) and want to correct it. I fix the mistake in the upstream repo. In the meantime you have edited some other files and you really don't want to manually ignore my older copies of those files. Rather, you want to fix just one file from this new branch. This is how you do it.\n\nAs usual, be sure to type in `%%bash` before you write any `bash` commands in a cell.\n\n**Note:** The steps below assume that you have already cloned the `playground` repo in this notebook.\n\n1. First cell:\n  1. Go into the `playground` repo and fetch the changes from the master branch of the `course` remote.\n2. Second cell:\n  1. `git checkout course/master -- README.md`.  The `--` means that `README.md` is a file (as opposed to a `branch`).\n  2. `cat README.md`.  This just looks at the updated file.\n3. Third cell:\n  1. `git status`\n  2. Commit the changes to your local repo with an appropriate commit message.\n  3. `git status`\n  4. Push the changes to your remote repo.\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit remote add course https://github.com/dsondak/playground.git\ngit fetch course master\n```\n\n    From https://github.com/dsondak/playground\n     * branch            master     -> FETCH_HEAD\n     * [new branch]      master     -> course/master\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit checkout course/master -- README.md\ncat README.md\n```\n\n    # Playground Repo\r\n    \r\n    For practicing.\r\n\n\n\n```bash\n%%bash\ncd /tmp/playground\ngit status\ngit commit -m \"Updated README.md\"\ngit status\ngit push\n```\n\n    On branch master\n    Your branch is up-to-date with 'origin/master'.\n    \n    Changes to be committed:\n      (use \"git reset HEAD <file>...\" to unstage)\n    \n    \tnew file:   README.md\n    \n    [master 468e3dc] Updated README.md\n     1 file changed, 3 insertions(+)\n     create mode 100644 README.md\n    On branch master\n    Your branch is ahead of 'origin/master' by 1 commit.\n      (use \"git push\" to publish your local commits)\n    \n    nothing to commit, working tree clean\n\n\n    To https://github.com/xuwd11/playground\n       9621d1b..468e3dc  master -> master\n\n\n## Problem 3\nThis problem is related to the Lecture 4 exercises.\n1. Open the `languages.txt` file.  This file contains all the languages that students listed as their primary language in the course survey.\n2. Load the language strings from the file into a list.\n3. Use the `Counter` method from the `collections` library to count the number of occurrences of each element of the list.\n  + **NOTE:**  It is not necessary to use the `most_common()` method here.\n4. Create a bar plot to display the frequency of each language.  Be sure to label the x-axis!\n  + Remember, to create plots in the notebook you must put the line `%matplotlib inline` at the beginning of your notebook.\n  + Be sure to import matplotlib:  `import matplotlib.pyplot as plt`.\n  + To generate the bar plot write `plt.bar(x_coords, freqs)`.  You need to define `x_coords` and `freqs`.\n  + **Hint:** You may want to use the `numpy` `arange` function to create `x_coords`.  Remember, `x_coords` is the x-axis and it should have points for each distinct language.\n  + **Hint:** To get `freqs`, you may want to use the `values()` method on your result from step 3.  That is, `freqs = result_from_3.values()`.\n  + **Hint:** To label the x-axis you should use `plt.xticks(x_coords, labels)` where labels can be accessed through the `keys()` method on your result from step 3.\n\n\n```python\n%matplotlib inline \nfrom collections import Counter\nimport matplotlib.pyplot as plt\nimport numpy as np\n```\n\n\n```python\nf = open('languages.txt', 'r')\nlanguages = f.read().strip().split()\nf.close()\nlanguages_count = Counter(languages)\nlanguages_count_sorted = sorted(languages_count.items(), key=lambda x:x[1], reverse=True)\n```\n\n\n```python\nx_coords = range(len(languages_count_sorted))\nlabels = [x[0] for x in languages_count_sorted]\nfreqs = [x[1] for x in languages_count_sorted]\nplt.bar(x_coords, freqs);\nplt.xticks(x_coords, labels);\nplt.xlabel('Language');\nplt.ylabel('Frequency');\nplt.show()\n```\n\n---\n## Problem 4\nIn chemical kinetics, the reaction rate coefficient for a given reaction depends on the temperature of the system.  The functional relationship between the reaction rate coefficient and temperature is given by the Arrhenius rate:\n\\begin{align}\nk\\left(T\\right) = A T^{b}\\exp\\left(-\\frac{E}{RT}\\right)\n\\end{align}\nwhere $A$, $b$, and $E$ are parameters, $R = 8.314 \\dfrac{\\textrm{J}}{\\textrm{mol} \\textrm{ K}}$  is the universal gas constant, and $T$ is the temperature.\n\nWrite a function which returns $k\\left(T\\right)$ given $A$, $b$, $E$, and $T$.  Here are a few requirements:\n* The function should test for exceptions where necessary.\n* Pass the parameters $A$, $b$, and $E$ in as a list.\n* Make $R$ a keyword argument to the function.\n\n\n```python\ndef Arrhenius_rate(T, parameters, R=8.314):\n    \n    # Check temperature\n    # T can be either a numpy array or a number\n    try:\n        try:\n            if all(T > 0):\n                pass\n            else:\n                raise ValueError\n        except:\n            if T <= 0:\n                raise ValueError\n    except:\n        print('Invalid temperature! Please check and set a valid temperature (in K)!')\n        return None\n    \n    # Check parameters\n    try:\n        if 3 != len(parameters):\n            raise ValueError\n        parameters = [float(p) for p in parameters]\n    except:\n        print('Invalid parameters! Please pass the parameters A, b, E in as a list and make sure they are valid numbers!')\n        return None\n    \n    # Check the universal gas constant R\n    try:\n        R = float(R)\n        if R <= 0:\n            raise ValueError\n    except:\n        print('Invalid universal gas constant R! Please set a valid R (in J/mol/K)!')\n        return None\n    \n    return parameters[0] * T**parameters[1] * np.exp(-parameters[2]/(R*T))\n    \n```\n\n\n```python\n# Test 1 (invalid temperature)\nArrhenius_rate(-10, [100,4,1])\nArrhenius_rate([10], [100,4,1])\nArrhenius_rate('T', [100,4,1])\n```\n\n    Invalid temperature! Please check and set a valid temperature (in K)!\n    Invalid temperature! Please check and set a valid temperature (in K)!\n    Invalid temperature! Please check and set a valid temperature (in K)!\n\n\n\n```python\n# Test 2 (invalid parameters)\nArrhenius_rate(273, [100,4,1,10])\nArrhenius_rate(273, 100)\n```\n\n    Invalid parameters! Please pass the parameters A, b, E in as a list and make sure they are valid numbers!\n    Invalid parameters! Please pass the parameters A, b, E in as a list and make sure they are valid numbers!\n\n\n\n```python\n# Test 3 (invalid R)\nArrhenius_rate(273, [100,4,1], -10)\nArrhenius_rate(273, [100,4,1], 'R')\n```\n\n    Invalid universal gas constant R! Please set a valid R (in J/mol/K)!\n    Invalid universal gas constant R! Please set a valid R (in J/mol/K)!\n\n\n\n```python\n# Test 4 (valid input)\nArrhenius_rate(273, [100,2,50000])\n```\n\n\n\n\n    0.0020192769398056079\n\n\n\n---\n## Problem 5\nUsing `numpy` arrays, plot $k\\left(T\\right)$ for $T\\in\\left(0, 5000\\right]$ for three different sets of parameters $\\left\\{A, b, E\\right\\}$.  Make sure all three lines are on the same figure and be sure to label each line.  You may use the function from Problem 2.  You may want to play with the parameters a little bit to get some nice curves but you won't lose points for ugly curves either (as long as they're correct!).\n\n\n```python\npara1 = [100, 2, 40000]\npara2 = [100, 2, 55000]\npara3 = [100, 2, 80000]\nT = np.arange(1, 5001)\nk1 = Arrhenius_rate(T, para1)\nk2 = Arrhenius_rate(T, para2)\nk3 = Arrhenius_rate(T, para3)\nplt.plot(T, k1, label='A = {}, b = {}, E = {}'.format(para1[0], para1[1], para1[2]));\nplt.plot(T, k2, label='A = {}, b = {}, E = {}'.format(para2[0], para2[1], para2[2]));\nplt.plot(T, k3, label='A = {}, b = {}, E = {}'.format(para3[0], para3[1], para3[2]));\nplt.legend();\nplt.xlabel('Temperature (K)');\nplt.ylabel('Reaction rate (mol/L/s)');\n```\n", "meta": {"hexsha": "af5881ab77b5e5ccb2618a5496496e6db6a85b29", "size": 49305, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "homeworks/HW3/HW3-final.ipynb", "max_stars_repo_name": "xuwd11/cs207_Weidong_Xu", "max_stars_repo_head_hexsha": "00442657239c7a4040501bf7fa0f6697c731fe94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/HW3/HW3-final.ipynb", "max_issues_repo_name": "xuwd11/cs207_Weidong_Xu", "max_issues_repo_head_hexsha": "00442657239c7a4040501bf7fa0f6697c731fe94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/HW3/HW3-final.ipynb", "max_forks_repo_name": "xuwd11/cs207_Weidong_Xu", "max_forks_repo_head_hexsha": "00442657239c7a4040501bf7fa0f6697c731fe94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 87.5754884547, "max_line_length": 25008, "alphanum_fraction": 0.8148666464, "converted": true, "num_tokens": 2843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.056652426900697224, "lm_q2_score": 0.0695417406490685, "lm_q1q2_score": 0.0039397083786685974}}
{"text": "<a href=\"https://colab.research.google.com/github/shubham7423/Mask-Detection-IOS-App/blob/master/Mask_Detection.ipynb\" target=\"_parent\"></a>\n\n##Fetch data from google drive\n\n\n```\n!cp drive/My\\ Drive/mask/dataset.zip ../content/\n```\n\n\n```\n!unzip dataset.zip -d data/\n```\n\n    Archive:  dataset.zip\n       creating: data/dataset/\n      inflating: data/dataset/.DS_Store  \n      inflating: data/__MACOSX/dataset/._.DS_Store  \n       creating: data/dataset/with_mask/\n      inflating: data/__MACOSX/dataset/._with_mask  \n       creating: data/dataset/without_mask/\n      inflating: data/__MACOSX/dataset/._without_mask  \n      inflating: data/dataset/with_mask/augmented_image_218.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_218.jpg  \n      inflating: data/dataset/with_mask/augmented_image_19.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_19.jpg  \n      inflating: data/dataset/with_mask/augmented_image_31.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_31.jpg  \n      inflating: data/dataset/with_mask/augmented_image_25.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_25.jpg  \n      inflating: data/dataset/with_mask/augmented_image_230.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_230.jpg  \n      inflating: data/dataset/with_mask/419-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._419-with-mask.jpg  \n      inflating: data/dataset/with_mask/330-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._330-with-mask.jpg  \n      inflating: data/dataset/with_mask/260-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._260-with-mask.jpg  \n      inflating: data/dataset/with_mask/27-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._27-with-mask.jpg  \n      inflating: data/dataset/with_mask/327-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._327-with-mask.jpg  \n      inflating: data/dataset/with_mask/277-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._277-with-mask.jpg  \n      inflating: data/dataset/with_mask/30-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._30-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_3.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_3.jpg  \n      inflating: data/dataset/with_mask/augmented_image_152.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_152.jpg  \n      inflating: data/dataset/with_mask/augmented_image_146.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_146.jpg  \n      inflating: data/dataset/with_mask/309-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._309-with-mask.jpg  \n      inflating: data/dataset/with_mask/259-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._259-with-mask.jpg  \n      inflating: data/dataset/with_mask/420-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._420-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_191.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_191.jpg  \n      inflating: data/dataset/with_mask/155-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._155-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_185.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_185.jpg  \n      inflating: data/dataset/with_mask/89-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._89-with-mask.jpg  \n      inflating: data/dataset/with_mask/273-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._273-with-mask.jpg  \n      inflating: data/dataset/with_mask/323-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._323-with-mask.jpg  \n      inflating: data/dataset/with_mask/34-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._34-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_184.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_184.jpg  \n      inflating: data/dataset/with_mask/334-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._334-with-mask.jpg  \n      inflating: data/dataset/with_mask/23-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._23-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_190.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_190.jpg  \n      inflating: data/dataset/with_mask/168-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._168-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_147.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_147.jpg  \n      inflating: data/dataset/with_mask/prajna.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._prajna.jpg  \n      inflating: data/dataset/with_mask/augmented_image_153.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_153.jpg  \n      inflating: data/dataset/with_mask/augmented_image_2.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_2.jpg  \n      inflating: data/dataset/with_mask/433-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._433-with-mask.jpg  \n      inflating: data/dataset/with_mask/146-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._146-with-mask.jpg  \n      inflating: data/dataset/with_mask/424-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._424-with-mask.jpg  \n      inflating: data/dataset/with_mask/151-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._151-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_24.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_24.jpg  \n      inflating: data/dataset/with_mask/augmented_image_30.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_30.jpg  \n      inflating: data/dataset/with_mask/augmented_image_18.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_18.jpg  \n      inflating: data/dataset/with_mask/augmented_image_219.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_219.jpg  \n      inflating: data/dataset/with_mask/augmented_image_26.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_26.jpg  \n      inflating: data/dataset/with_mask/augmented_image_32.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_32.jpg  \n      inflating: data/dataset/with_mask/augmented_image_227.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_227.jpg  \n      inflating: data/dataset/with_mask/40-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._40-with-mask.jpg  \n      inflating: data/dataset/with_mask/207-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._207-with-mask.jpg  \n      inflating: data/dataset/with_mask/357-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._357-with-mask.jpg  \n      inflating: data/dataset/with_mask/57-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._57-with-mask.jpg  \n      inflating: data/dataset/with_mask/340-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._340-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_179.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_179.jpg  \n      inflating: data/dataset/with_mask/augmented_image_145.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_145.jpg  \n      inflating: data/dataset/with_mask/8-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._8-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_0.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_0.jpg  \n      inflating: data/dataset/with_mask/augmented_image_151.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_151.jpg  \n      inflating: data/dataset/with_mask/79-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._79-with-mask.jpg  \n      inflating: data/dataset/with_mask/283-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._283-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_186.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_186.jpg  \n      inflating: data/dataset/with_mask/132-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._132-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_192.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_192.jpg  \n      inflating: data/dataset/with_mask/447-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._447-with-mask.jpg  \n      inflating: data/dataset/with_mask/294-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._294-with-mask.jpg  \n      inflating: data/dataset/with_mask/125-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._125-with-mask.jpg  \n      inflating: data/dataset/with_mask/450-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._450-with-mask.jpg  \n      inflating: data/dataset/with_mask/229-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._229-with-mask.jpg  \n      inflating: data/dataset/with_mask/379-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._379-with-mask.jpg  \n      inflating: data/dataset/with_mask/198-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._198-with-mask.jpg  \n      inflating: data/dataset/with_mask/118-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._118-with-mask.jpg  \n      inflating: data/dataset/with_mask/53-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._53-with-mask.jpg  \n      inflating: data/dataset/with_mask/344-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._344-with-mask.jpg  \n      inflating: data/dataset/with_mask/214-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._214-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_193.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_193.jpg  \n      inflating: data/dataset/with_mask/353-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._353-with-mask.jpg  \n      inflating: data/dataset/with_mask/203-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._203-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_187.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_187.jpg  \n      inflating: data/dataset/with_mask/augmented_image_150.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_150.jpg  \n      inflating: data/dataset/with_mask/augmented_image_1.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_1.jpg  \n      inflating: data/dataset/with_mask/augmented_image_144.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_144.jpg  \n      inflating: data/dataset/with_mask/augmented_image_178.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_178.jpg  \n      inflating: data/dataset/with_mask/290-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._290-with-mask.jpg  \n      inflating: data/dataset/with_mask/121-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._121-with-mask.jpg  \n      inflating: data/dataset/with_mask/454-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._454-with-mask.jpg  \n      inflating: data/dataset/with_mask/287-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._287-with-mask.jpg  \n      inflating: data/dataset/with_mask/136-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._136-with-mask.jpg  \n      inflating: data/dataset/with_mask/443-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._443-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_33.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_33.jpg  \n      inflating: data/dataset/with_mask/augmented_image_232.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_232.jpg  \n      inflating: data/dataset/with_mask/augmented_image_27.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_27.jpg  \n      inflating: data/dataset/with_mask/augmented_image_23.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_23.jpg  \n      inflating: data/dataset/with_mask/augmented_image_236.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_236.jpg  \n      inflating: data/dataset/with_mask/augmented_image_222.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_222.jpg  \n      inflating: data/dataset/with_mask/augmented_image_37.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_37.jpg  \n      inflating: data/dataset/with_mask/343-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._343-with-mask.jpg  \n      inflating: data/dataset/with_mask/204-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._204-with-mask.jpg  \n      inflating: data/dataset/with_mask/43-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._43-with-mask.jpg  \n      inflating: data/dataset/with_mask/108-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._108-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_140.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_140.jpg  \n      inflating: data/dataset/with_mask/augmented_image_5.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_5.jpg  \n      inflating: data/dataset/with_mask/augmented_image_154.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_154.jpg  \n      inflating: data/dataset/with_mask/augmented_image_168.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_168.jpg  \n      inflating: data/dataset/with_mask/augmented_image_183.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_183.jpg  \n      inflating: data/dataset/with_mask/augmented_image_197.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_197.jpg  \n      inflating: data/dataset/with_mask/297-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._297-with-mask.jpg  \n      inflating: data/dataset/with_mask/453-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._453-with-mask.jpg  \n      inflating: data/dataset/with_mask/126-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._126-with-mask.jpg  \n      inflating: data/dataset/with_mask/444-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._444-with-mask.jpg  \n      inflating: data/dataset/with_mask/131-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._131-with-mask.jpg  \n      inflating: data/dataset/with_mask/479-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._479-with-mask.jpg  \n      inflating: data/dataset/with_mask/200-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._200-with-mask.jpg  \n      inflating: data/dataset/with_mask/47-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._47-with-mask.jpg  \n      inflating: data/dataset/with_mask/347-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._347-with-mask.jpg  \n      inflating: data/dataset/with_mask/217-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._217-with-mask.jpg  \n      inflating: data/dataset/with_mask/50-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._50-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_196.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_196.jpg  \n      inflating: data/dataset/with_mask/augmented_image_182.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_182.jpg  \n      inflating: data/dataset/with_mask/augmented_image_169.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_169.jpg  \n      inflating: data/dataset/with_mask/augmented_image_155.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_155.jpg  \n      inflating: data/dataset/with_mask/augmented_image_4.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_4.jpg  \n      inflating: data/dataset/with_mask/augmented_image_141.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_141.jpg  \n      inflating: data/dataset/with_mask/369-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._369-with-mask.jpg  \n      inflating: data/dataset/with_mask/239-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._239-with-mask.jpg  \n      inflating: data/dataset/with_mask/284-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._284-with-mask.jpg  \n      inflating: data/dataset/with_mask/440-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._440-with-mask.jpg  \n      inflating: data/dataset/with_mask/135-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._135-with-mask.jpg  \n      inflating: data/dataset/with_mask/293-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._293-with-mask.jpg  \n      inflating: data/dataset/with_mask/457-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._457-with-mask.jpg  \n      inflating: data/dataset/with_mask/122-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._122-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_223.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_223.jpg  \n      inflating: data/dataset/with_mask/augmented_image_36.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_36.jpg  \n      inflating: data/dataset/with_mask/augmented_image_22.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_22.jpg  \n      inflating: data/dataset/with_mask/augmented_image_237.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_237.jpg  \n      inflating: data/dataset/with_mask/augmented_image_34.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_34.jpg  \n      inflating: data/dataset/with_mask/augmented_image_221.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_221.jpg  \n      inflating: data/dataset/with_mask/augmented_image_235.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_235.jpg  \n      inflating: data/dataset/with_mask/augmented_image_20.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_20.jpg  \n      inflating: data/dataset/with_mask/augmented_image_209.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_209.jpg  \n      inflating: data/dataset/with_mask/399-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._399-with-mask.jpg  \n      inflating: data/dataset/with_mask/33-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._33-with-mask.jpg  \n      inflating: data/dataset/with_mask/324-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._324-with-mask.jpg  \n      inflating: data/dataset/with_mask/274-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._274-with-mask.jpg  \n      inflating: data/dataset/with_mask/24-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._24-with-mask.jpg  \n      inflating: data/dataset/with_mask/333-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._333-with-mask.jpg  \n      inflating: data/dataset/with_mask/263-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._263-with-mask.jpg  \n      inflating: data/dataset/with_mask/99-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._99-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_6.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_6.jpg  \n      inflating: data/dataset/with_mask/augmented_image_157.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_157.jpg  \n      inflating: data/dataset/with_mask/augmented_image_143.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_143.jpg  \n      inflating: data/dataset/with_mask/augmented_image_194.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_194.jpg  \n      inflating: data/dataset/with_mask/augmented_image_180.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_180.jpg  \n      inflating: data/dataset/with_mask/141-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._141-with-mask.jpg  \n      inflating: data/dataset/with_mask/434-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._434-with-mask.jpg  \n      inflating: data/dataset/with_mask/156-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._156-with-mask.jpg  \n      inflating: data/dataset/with_mask/267-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._267-with-mask.jpg  \n      inflating: data/dataset/with_mask/37-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._37-with-mask.jpg  \n      inflating: data/dataset/with_mask/270-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._270-with-mask.jpg  \n      inflating: data/dataset/with_mask/409-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._409-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_181.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_181.jpg  \n      inflating: data/dataset/with_mask/augmented_image_195.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_195.jpg  \n      inflating: data/dataset/with_mask/augmented_image_142.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_142.jpg  \n      inflating: data/dataset/with_mask/augmented_image_156.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_156.jpg  \n      inflating: data/dataset/with_mask/augmented_image_7.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_7.jpg  \n      inflating: data/dataset/with_mask/19-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._19-with-mask.jpg  \n      inflating: data/dataset/with_mask/152-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._152-with-mask.jpg  \n      inflating: data/dataset/with_mask/427-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._427-with-mask.jpg  \n      inflating: data/dataset/with_mask/430-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._430-with-mask.jpg  \n      inflating: data/dataset/with_mask/319-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._319-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_208.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_208.jpg  \n      inflating: data/dataset/with_mask/augmented_image_234.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_234.jpg  \n      inflating: data/dataset/with_mask/augmented_image_21.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_21.jpg  \n      inflating: data/dataset/with_mask/augmented_image_35.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_35.jpg  \n      inflating: data/dataset/with_mask/augmented_image_220.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_220.jpg  \n      inflating: data/dataset/with_mask/augmented_image_52.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_52.jpg  \n      inflating: data/dataset/with_mask/augmented_image_247.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_247.jpg  \n      inflating: data/dataset/with_mask/augmented_image_46.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_46.jpg  \n      inflating: data/dataset/with_mask/397-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._397-with-mask.jpg  \n      inflating: data/dataset/with_mask/80-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._80-with-mask.jpg  \n      inflating: data/dataset/with_mask/176-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._176-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_91.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_91.jpg  \n      inflating: data/dataset/with_mask/augmented_image_284.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_284.jpg  \n      inflating: data/dataset/with_mask/augmented_image_85.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_85.jpg  \n      inflating: data/dataset/with_mask/380-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._380-with-mask.jpg  \n      inflating: data/dataset/with_mask/97-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._97-with-mask.jpg  \n      inflating: data/dataset/with_mask/414-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._414-with-mask.jpg  \n      inflating: data/dataset/with_mask/161-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._161-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_119.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_119.jpg  \n      inflating: data/dataset/with_mask/augmented_image_131.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_131.jpg  \n      inflating: data/dataset/with_mask/augmented_image_125.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_125.jpg  \n      inflating: data/dataset/with_mask/313-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._313-with-mask.jpg  \n      inflating: data/dataset/with_mask/243-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._243-with-mask.jpg  \n      inflating: data/dataset/with_mask/158-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._158-with-mask.jpg  \n      inflating: data/dataset/with_mask/304-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._304-with-mask.jpg  \n      inflating: data/dataset/with_mask/254-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._254-with-mask.jpg  \n      inflating: data/dataset/with_mask/13-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._13-with-mask.jpg  \n      inflating: data/dataset/with_mask/pra1.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._pra1.jpg  \n      inflating: data/dataset/with_mask/384-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._384-with-mask.jpg  \n      inflating: data/dataset/with_mask/93-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._93-with-mask.jpg  \n      inflating: data/dataset/with_mask/165-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._165-with-mask.jpg  \n      inflating: data/dataset/with_mask/269-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._269-with-mask.jpg  \n      inflating: data/dataset/with_mask/339-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._339-with-mask.jpg  \n      inflating: data/dataset/with_mask/39-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._39-with-mask.jpg  \n      inflating: data/dataset/with_mask/393-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._393-with-mask.jpg  \n      inflating: data/dataset/with_mask/84-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._84-with-mask.jpg  \n      inflating: data/dataset/with_mask/407-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._407-with-mask.jpg  \n      inflating: data/dataset/with_mask/172-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._172-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_124.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_124.jpg  \n      inflating: data/dataset/with_mask/augmented_image_130.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_130.jpg  \n      inflating: data/dataset/with_mask/augmented_image_118.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_118.jpg  \n      inflating: data/dataset/with_mask/17-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._17-with-mask.jpg  \n      inflating: data/dataset/with_mask/429-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._429-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_291.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_291.jpg  \n      inflating: data/dataset/with_mask/augmented_image_84.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_84.jpg  \n      inflating: data/dataset/with_mask/augmented_image_90.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_90.jpg  \n      inflating: data/dataset/with_mask/augmented_image_285.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_285.jpg  \n      inflating: data/dataset/with_mask/317-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._317-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_252.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_252.jpg  \n      inflating: data/dataset/with_mask/augmented_image_47.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_47.jpg  \n      inflating: data/dataset/with_mask/augmented_image_53.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_53.jpg  \n      inflating: data/dataset/with_mask/augmented_image_246.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_246.jpg  \n      inflating: data/dataset/with_mask/augmented_image_79.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_79.jpg  \n      inflating: data/dataset/with_mask/augmented_image_45.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_45.jpg  \n      inflating: data/dataset/with_mask/augmented_image_244.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_244.jpg  \n      inflating: data/dataset/with_mask/augmented_image_51.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_51.jpg  \n      inflating: data/dataset/with_mask/111-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._111-with-mask.jpg  \n      inflating: data/dataset/with_mask/464-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._464-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_86.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_86.jpg  \n      inflating: data/dataset/with_mask/augmented_image_287.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_287.jpg  \n      inflating: data/dataset/with_mask/augmented_image_92.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_92.jpg  \n      inflating: data/dataset/with_mask/106-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._106-with-mask.jpg  \n      inflating: data/dataset/with_mask/473-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._473-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_126.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_126.jpg  \n      inflating: data/dataset/with_mask/augmented_image_132.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_132.jpg  \n      inflating: data/dataset/with_mask/195-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._195-with-mask.jpg  \n      inflating: data/dataset/with_mask/224-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._224-with-mask.jpg  \n      inflating: data/dataset/with_mask/374-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._374-with-mask.jpg  \n      inflating: data/dataset/with_mask/128-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._128-with-mask.jpg  \n      inflating: data/dataset/with_mask/299-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._299-with-mask.jpg  \n      inflating: data/dataset/with_mask/182-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._182-with-mask.jpg  \n      inflating: data/dataset/with_mask/74-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._74-with-mask.jpg  \n      inflating: data/dataset/with_mask/233-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._233-with-mask.jpg  \n      inflating: data/dataset/with_mask/5-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._5-with-mask.jpg  \n      inflating: data/dataset/with_mask/pra2.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._pra2.jpg  \n      inflating: data/dataset/with_mask/pra3.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._pra3.jpg  \n      inflating: data/dataset/with_mask/477-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._477-with-mask.jpg  \n      inflating: data/dataset/with_mask/49-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._49-with-mask.jpg  \n      inflating: data/dataset/with_mask/349-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._349-with-mask.jpg  \n      inflating: data/dataset/with_mask/219-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._219-with-mask.jpg  \n      inflating: data/dataset/with_mask/115-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._115-with-mask.jpg  \n      inflating: data/dataset/with_mask/460-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._460-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_133.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_133.jpg  \n      inflating: data/dataset/with_mask/augmented_image_127.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_127.jpg  \n      inflating: data/dataset/with_mask/1-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._1-with-mask.jpg  \n      inflating: data/dataset/with_mask/186-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._186-with-mask.jpg  \n      inflating: data/dataset/with_mask/70-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._70-with-mask.jpg  \n      inflating: data/dataset/with_mask/237-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._237-with-mask.jpg  \n      inflating: data/dataset/with_mask/459-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._459-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_286.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_286.jpg  \n      inflating: data/dataset/with_mask/augmented_image_93.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_93.jpg  \n      inflating: data/dataset/with_mask/augmented_image_87.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_87.jpg  \n      inflating: data/dataset/with_mask/67-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._67-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_245.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_245.jpg  \n      inflating: data/dataset/with_mask/augmented_image_50.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_50.jpg  \n      inflating: data/dataset/with_mask/augmented_image_44.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_44.jpg  \n      inflating: data/dataset/with_mask/augmented_image_251.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_251.jpg  \n      inflating: data/dataset/with_mask/augmented_image_78.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_78.jpg  \n      inflating: data/dataset/with_mask/augmented_image_40.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_40.jpg  \n      inflating: data/dataset/with_mask/augmented_image_54.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_54.jpg  \n      inflating: data/dataset/with_mask/augmented_image_68.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_68.jpg  \n      inflating: data/dataset/with_mask/augmented_image_296.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_296.jpg  \n      inflating: data/dataset/with_mask/105-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._105-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_83.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_83.jpg  \n      inflating: data/dataset/with_mask/augmented_image_97.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_97.jpg  \n      inflating: data/dataset/with_mask/209-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._209-with-mask.jpg  \n      inflating: data/dataset/with_mask/359-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._359-with-mask.jpg  \n      inflating: data/dataset/with_mask/59-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._59-with-mask.jpg  \n      inflating: data/dataset/with_mask/467-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._467-with-mask.jpg  \n      inflating: data/dataset/with_mask/112-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._112-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_123.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_123.jpg  \n      inflating: data/dataset/with_mask/augmented_image_137.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_137.jpg  \n      inflating: data/dataset/with_mask/6-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._6-with-mask.jpg  \n      inflating: data/dataset/with_mask/181-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._181-with-mask.jpg  \n      inflating: data/dataset/with_mask/77-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._77-with-mask.jpg  \n      inflating: data/dataset/with_mask/449-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._449-with-mask.jpg  \n      inflating: data/dataset/with_mask/196-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._196-with-mask.jpg  \n      inflating: data/dataset/with_mask/227-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._227-with-mask.jpg  \n      inflating: data/dataset/with_mask/377-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._377-with-mask.jpg  \n      inflating: data/dataset/with_mask/463-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._463-with-mask.jpg  \n      inflating: data/dataset/with_mask/116-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._116-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_308.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_308.jpg  \n      inflating: data/dataset/with_mask/474-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._474-with-mask.jpg  \n      inflating: data/dataset/with_mask/101-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._101-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_136.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_136.jpg  \n      inflating: data/dataset/with_mask/augmented_image_122.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_122.jpg  \n      inflating: data/dataset/with_mask/192-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._192-with-mask.jpg  \n      inflating: data/dataset/with_mask/223-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._223-with-mask.jpg  \n      inflating: data/dataset/with_mask/64-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._64-with-mask.jpg  \n      inflating: data/dataset/with_mask/138-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._138-with-mask.jpg  \n      inflating: data/dataset/with_mask/289-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._289-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_96.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_96.jpg  \n      inflating: data/dataset/with_mask/185-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._185-with-mask.jpg  \n      inflating: data/dataset/with_mask/364-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._364-with-mask.jpg  \n      inflating: data/dataset/with_mask/234-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._234-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_82.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_82.jpg  \n      inflating: data/dataset/with_mask/73-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._73-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_69.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_69.jpg  \n      inflating: data/dataset/with_mask/augmented_image_268.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_268.jpg  \n      inflating: data/dataset/with_mask/2-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._2-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_55.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_55.jpg  \n      inflating: data/dataset/with_mask/augmented_image_240.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_240.jpg  \n      inflating: data/dataset/with_mask/augmented_image_254.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_254.jpg  \n      inflating: data/dataset/with_mask/augmented_image_41.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_41.jpg  \n      inflating: data/dataset/with_mask/augmented_image_242.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_242.jpg  \n      inflating: data/dataset/with_mask/augmented_image_57.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_57.jpg  \n      inflating: data/dataset/with_mask/augmented_image_43.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_43.jpg  \n      inflating: data/dataset/with_mask/augmented_image_256.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_256.jpg  \n      inflating: data/dataset/with_mask/augmented_image_281.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_281.jpg  \n      inflating: data/dataset/with_mask/94-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._94-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_94.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_94.jpg  \n      inflating: data/dataset/with_mask/383-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._383-with-mask.jpg  \n      inflating: data/dataset/with_mask/162-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._162-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_80.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_80.jpg  \n      inflating: data/dataset/with_mask/417-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._417-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_295.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_295.jpg  \n      inflating: data/dataset/with_mask/29-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._29-with-mask.jpg  \n      inflating: data/dataset/with_mask/279-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._279-with-mask.jpg  \n      inflating: data/dataset/with_mask/83-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._83-with-mask.jpg  \n      inflating: data/dataset/with_mask/394-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._394-with-mask.jpg  \n      inflating: data/dataset/with_mask/175-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._175-with-mask.jpg  \n      inflating: data/dataset/with_mask/400-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._400-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_134.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_134.jpg  \n      inflating: data/dataset/with_mask/augmented_image_120.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_120.jpg  \n      inflating: data/dataset/with_mask/augmented_image_108.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_108.jpg  \n      inflating: data/dataset/with_mask/10-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._10-with-mask.jpg  \n      inflating: data/dataset/with_mask/307-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._307-with-mask.jpg  \n      inflating: data/dataset/with_mask/257-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._257-with-mask.jpg  \n      inflating: data/dataset/with_mask/439-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._439-with-mask.jpg  \n      inflating: data/dataset/with_mask/240-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._240-with-mask.jpg  \n      inflating: data/dataset/with_mask/390-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._390-with-mask.jpg  \n      inflating: data/dataset/with_mask/171-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._171-with-mask.jpg  \n      inflating: data/dataset/with_mask/404-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._404-with-mask.jpg  \n      inflating: data/dataset/with_mask/387-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._387-with-mask.jpg  \n      inflating: data/dataset/with_mask/413-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._413-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_109.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_109.jpg  \n      inflating: data/dataset/with_mask/augmented_image_121.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_121.jpg  \n      inflating: data/dataset/with_mask/augmented_image_135.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_135.jpg  \n      inflating: data/dataset/with_mask/244-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._244-with-mask.jpg  \n      inflating: data/dataset/with_mask/314-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._314-with-mask.jpg  \n      inflating: data/dataset/with_mask/480-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._480-with-mask.jpg  \n      inflating: data/dataset/with_mask/148-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._148-with-mask.jpg  \n      inflating: data/dataset/with_mask/14-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._14-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_81.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_81.jpg  \n      inflating: data/dataset/with_mask/253-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._253-with-mask.jpg  \n      inflating: data/dataset/with_mask/303-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._303-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_280.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_280.jpg  \n      inflating: data/dataset/with_mask/augmented_image_42.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_42.jpg  \n      inflating: data/dataset/with_mask/augmented_image_257.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_257.jpg  \n      inflating: data/dataset/with_mask/augmented_image_243.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_243.jpg  \n      inflating: data/dataset/with_mask/augmented_image_56.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_56.jpg  \n      inflating: data/dataset/with_mask/184-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._184-with-mask.jpg  \n      inflating: data/dataset/with_mask/365-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._365-with-mask.jpg  \n      inflating: data/dataset/with_mask/235-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._235-with-mask.jpg  \n      inflating: data/dataset/with_mask/72-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._72-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_73.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_73.jpg  \n      inflating: data/dataset/with_mask/139-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._139-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_266.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_266.jpg  \n      inflating: data/dataset/with_mask/augmented_image_67.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_67.jpg  \n      inflating: data/dataset/with_mask/288-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._288-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_299.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_299.jpg  \n      inflating: data/dataset/with_mask/augmented_image_98.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_98.jpg  \n      inflating: data/dataset/with_mask/3-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._3-with-mask.jpg  \n      inflating: data/dataset/with_mask/193-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._193-with-mask.jpg  \n      inflating: data/dataset/with_mask/222-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._222-with-mask.jpg  \n      inflating: data/dataset/with_mask/65-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._65-with-mask.jpg  \n      inflating: data/dataset/with_mask/475-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._475-with-mask.jpg  \n      inflating: data/dataset/with_mask/100-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._100-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_138.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_138.jpg  \n      inflating: data/dataset/with_mask/augmented_image_110.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_110.jpg  \n      inflating: data/dataset/with_mask/augmented_image_104.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_104.jpg  \n      inflating: data/dataset/with_mask/augmented_image_306.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_306.jpg  \n      inflating: data/dataset/with_mask/462-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._462-with-mask.jpg  \n      inflating: data/dataset/with_mask/117-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._117-with-mask.jpg  \n      inflating: data/dataset/with_mask/197-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._197-with-mask.jpg  \n      inflating: data/dataset/with_mask/226-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._226-with-mask.jpg  \n      inflating: data/dataset/with_mask/376-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._376-with-mask.jpg  \n      inflating: data/dataset/with_mask/61-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._61-with-mask.jpg  \n      inflating: data/dataset/with_mask/7-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._7-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_105.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_105.jpg  \n      inflating: data/dataset/with_mask/448-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._448-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_111.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_111.jpg  \n      inflating: data/dataset/with_mask/augmented_image_139.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_139.jpg  \n      inflating: data/dataset/with_mask/180-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._180-with-mask.jpg  \n      inflating: data/dataset/with_mask/231-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._231-with-mask.jpg  \n      inflating: data/dataset/with_mask/76-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._76-with-mask.jpg  \n      inflating: data/dataset/with_mask/466-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._466-with-mask.jpg  \n      inflating: data/dataset/with_mask/113-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._113-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_99.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_99.jpg  \n      inflating: data/dataset/with_mask/augmented_image_273.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_273.jpg  \n      inflating: data/dataset/with_mask/augmented_image_66.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_66.jpg  \n      inflating: data/dataset/with_mask/augmented_image_72.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_72.jpg  \n      inflating: data/dataset/with_mask/augmented_image_267.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_267.jpg  \n      inflating: data/dataset/with_mask/358-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._358-with-mask.jpg  \n      inflating: data/dataset/with_mask/471-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._471-with-mask.jpg  \n      inflating: data/dataset/with_mask/104-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._104-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_58.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_58.jpg  \n      inflating: data/dataset/with_mask/15-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._15-with-mask.jpg  \n      inflating: data/dataset/with_mask/252-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._252-with-mask.jpg  \n      inflating: data/dataset/with_mask/302-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._302-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_64.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_64.jpg  \n      inflating: data/dataset/with_mask/augmented_image_265.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_265.jpg  \n      inflating: data/dataset/with_mask/augmented_image_70.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_70.jpg  \n      inflating: data/dataset/with_mask/245-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._245-with-mask.jpg  \n      inflating: data/dataset/with_mask/315-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._315-with-mask.jpg  \n      inflating: data/dataset/with_mask/481-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._481-with-mask.jpg  \n      inflating: data/dataset/with_mask/91-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._91-with-mask.jpg  \n      inflating: data/dataset/with_mask/386-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._386-with-mask.jpg  \n      inflating: data/dataset/with_mask/167-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._167-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_107.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_107.jpg  \n      inflating: data/dataset/with_mask/augmented_image_113.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_113.jpg  \n      inflating: data/dataset/with_mask/augmented_image_305.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_305.jpg  \n      inflating: data/dataset/with_mask/augmented_image_311.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_311.jpg  \n      inflating: data/dataset/with_mask/86-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._86-with-mask.jpg  \n      inflating: data/dataset/with_mask/391-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._391-with-mask.jpg  \n      inflating: data/dataset/with_mask/170-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._170-with-mask.jpg  \n      inflating: data/dataset/with_mask/405-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._405-with-mask.jpg  \n      inflating: data/dataset/with_mask/311-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._311-with-mask.jpg  \n      inflating: data/dataset/with_mask/241-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._241-with-mask.jpg  \n      inflating: data/dataset/with_mask/438-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._438-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_310.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_310.jpg  \n      inflating: data/dataset/with_mask/augmented_image_112.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_112.jpg  \n      inflating: data/dataset/with_mask/augmented_image_106.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_106.jpg  \n      inflating: data/dataset/with_mask/11-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._11-with-mask.jpg  \n      inflating: data/dataset/with_mask/306-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._306-with-mask.jpg  \n      inflating: data/dataset/with_mask/256-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._256-with-mask.jpg  \n      inflating: data/dataset/with_mask/82-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._82-with-mask.jpg  \n      inflating: data/dataset/with_mask/395-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._395-with-mask.jpg  \n      inflating: data/dataset/with_mask/174-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._174-with-mask.jpg  \n      inflating: data/dataset/with_mask/401-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._401-with-mask.jpg  \n      inflating: data/dataset/with_mask/278-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._278-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_264.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_264.jpg  \n      inflating: data/dataset/with_mask/augmented_image_71.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_71.jpg  \n      inflating: data/dataset/with_mask/augmented_image_65.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_65.jpg  \n      inflating: data/dataset/with_mask/augmented_image_270.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_270.jpg  \n      inflating: data/dataset/with_mask/augmented_image_258.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_258.jpg  \n      inflating: data/dataset/with_mask/382-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._382-with-mask.jpg  \n      inflating: data/dataset/with_mask/163-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._163-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_59.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_59.jpg  \n      inflating: data/dataset/with_mask/416-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._416-with-mask.jpg  \n      inflating: data/dataset/with_mask/246-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._246-with-mask.jpg  \n      inflating: data/dataset/with_mask/316-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._316-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_61.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_61.jpg  \n      inflating: data/dataset/with_mask/augmented_image_75.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_75.jpg  \n      inflating: data/dataset/with_mask/augmented_image_49.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_49.jpg  \n      inflating: data/dataset/with_mask/251-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._251-with-mask.jpg  \n      inflating: data/dataset/with_mask/301-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._301-with-mask.jpg  \n      inflating: data/dataset/with_mask/16-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._16-with-mask.jpg  \n      inflating: data/dataset/with_mask/392-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._392-with-mask.jpg  \n      inflating: data/dataset/with_mask/85-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._85-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_102.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_102.jpg  \n      inflating: data/dataset/with_mask/406-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._406-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_116.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_116.jpg  \n      inflating: data/dataset/with_mask/173-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._173-with-mask.jpg  \n      inflating: data/dataset/with_mask/38-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._38-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_300.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_300.jpg  \n      inflating: data/dataset/with_mask/augmented_image_314.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_314.jpg  \n      inflating: data/dataset/with_mask/268-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._268-with-mask.jpg  \n      inflating: data/dataset/with_mask/338-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._338-with-mask.jpg  \n      inflating: data/dataset/with_mask/385-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._385-with-mask.jpg  \n      inflating: data/dataset/with_mask/92-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._92-with-mask.jpg  \n      inflating: data/dataset/with_mask/411-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._411-with-mask.jpg  \n      inflating: data/dataset/with_mask/305-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._305-with-mask.jpg  \n      inflating: data/dataset/with_mask/255-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._255-with-mask.jpg  \n      inflating: data/dataset/with_mask/12-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._12-with-mask.jpg  \n      inflating: data/dataset/with_mask/159-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._159-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_315.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_315.jpg  \n      inflating: data/dataset/with_mask/augmented_image_117.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_117.jpg  \n      inflating: data/dataset/with_mask/242-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._242-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_103.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_103.jpg  \n      inflating: data/dataset/with_mask/381-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._381-with-mask.jpg  \n      inflating: data/dataset/with_mask/96-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._96-with-mask.jpg  \n      inflating: data/dataset/with_mask/415-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._415-with-mask.jpg  \n      inflating: data/dataset/with_mask/160-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._160-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_48.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_48.jpg  \n      inflating: data/dataset/with_mask/396-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._396-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_74.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_74.jpg  \n      inflating: data/dataset/with_mask/augmented_image_261.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_261.jpg  \n      inflating: data/dataset/with_mask/81-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._81-with-mask.jpg  \n      inflating: data/dataset/with_mask/402-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._402-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_60.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_60.jpg  \n      inflating: data/dataset/with_mask/177-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._177-with-mask.jpg  \n      inflating: data/dataset/with_mask/190-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._190-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_76.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_76.jpg  \n      inflating: data/dataset/with_mask/augmented_image_62.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_62.jpg  \n      inflating: data/dataset/with_mask/augmented_image_277.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_277.jpg  \n      inflating: data/dataset/with_mask/221-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._221-with-mask.jpg  \n      inflating: data/dataset/with_mask/458-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._458-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_89.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_89.jpg  \n      inflating: data/dataset/with_mask/augmented_image_288.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_288.jpg  \n      inflating: data/dataset/with_mask/0-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._0-with-mask.jpg  \n      inflating: data/dataset/with_mask/187-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._187-with-mask.jpg  \n      inflating: data/dataset/with_mask/71-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._71-with-mask.jpg  \n      inflating: data/dataset/with_mask/366-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._366-with-mask.jpg  \n      inflating: data/dataset/with_mask/236-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._236-with-mask.jpg  \n      inflating: data/dataset/with_mask/114-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._114-with-mask.jpg  \n      inflating: data/dataset/with_mask/461-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._461-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_115.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_115.jpg  \n      inflating: data/dataset/with_mask/augmented_image_101.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_101.jpg  \n      inflating: data/dataset/with_mask/augmented_image_129.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_129.jpg  \n      inflating: data/dataset/with_mask/348-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._348-with-mask.jpg  \n      inflating: data/dataset/with_mask/218-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._218-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_303.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_303.jpg  \n      inflating: data/dataset/with_mask/48-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._48-with-mask.jpg  \n      inflating: data/dataset/with_mask/103-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._103-with-mask.jpg  \n      inflating: data/dataset/with_mask/476-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._476-with-mask.jpg  \n      inflating: data/dataset/with_mask/183-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._183-with-mask.jpg  \n      inflating: data/dataset/with_mask/75-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._75-with-mask.jpg  \n      inflating: data/dataset/with_mask/232-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._232-with-mask.jpg  \n      inflating: data/dataset/with_mask/362-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._362-with-mask.jpg  \n      inflating: data/dataset/with_mask/4-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._4-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_316.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_316.jpg  \n      inflating: data/dataset/with_mask/129-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._129-with-mask.jpg  \n      inflating: data/dataset/with_mask/298-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._298-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_128.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_128.jpg  \n      inflating: data/dataset/with_mask/194-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._194-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_100.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_100.jpg  \n      inflating: data/dataset/with_mask/62-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._62-with-mask.jpg  \n      inflating: data/dataset/with_mask/225-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._225-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_114.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_114.jpg  \n      inflating: data/dataset/with_mask/375-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._375-with-mask.jpg  \n      inflating: data/dataset/with_mask/107-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._107-with-mask.jpg  \n      inflating: data/dataset/with_mask/472-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._472-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_289.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_289.jpg  \n      inflating: data/dataset/with_mask/augmented_image_88.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_88.jpg  \n      inflating: data/dataset/with_mask/augmented_image_63.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_63.jpg  \n      inflating: data/dataset/with_mask/110-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._110-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_262.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_262.jpg  \n      inflating: data/dataset/with_mask/augmented_image_77.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_77.jpg  \n      inflating: data/dataset/with_mask/augmented_image_239.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_239.jpg  \n      inflating: data/dataset/with_mask/68-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._68-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_38.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_38.jpg  \n      inflating: data/dataset/with_mask/augmented_image_205.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_205.jpg  \n      inflating: data/dataset/with_mask/augmented_image_10.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_10.jpg  \n      inflating: data/dataset/with_mask/456-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._456-with-mask.jpg  \n      inflating: data/dataset/with_mask/123-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._123-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_211.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_211.jpg  \n      inflating: data/dataset/with_mask/285-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._285-with-mask.jpg  \n      inflating: data/dataset/with_mask/441-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._441-with-mask.jpg  \n      inflating: data/dataset/with_mask/134-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._134-with-mask.jpg  \n      inflating: data/dataset/with_mask/368-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._368-with-mask.jpg  \n      inflating: data/dataset/with_mask/238-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._238-with-mask.jpg  \n      inflating: data/dataset/with_mask/189-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._189-with-mask.jpg  \n      inflating: data/dataset/with_mask/346-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._346-with-mask.jpg  \n      inflating: data/dataset/with_mask/51-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._51-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_173.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_173.jpg  \n      inflating: data/dataset/with_mask/augmented_image_167.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_167.jpg  \n      inflating: data/dataset/with_mask/augmented_image_198.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_198.jpg  \n      inflating: data/dataset/with_mask/351-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._351-with-mask.jpg  \n      inflating: data/dataset/with_mask/201-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._201-with-mask.jpg  \n      inflating: data/dataset/with_mask/46-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._46-with-mask.jpg  \n      inflating: data/dataset/with_mask/478-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._478-with-mask.jpg  \n      inflating: data/dataset/with_mask/281-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._281-with-mask.jpg  \n      inflating: data/dataset/with_mask/445-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._445-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_199.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_199.jpg  \n      inflating: data/dataset/with_mask/augmented_image_166.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_166.jpg  \n      inflating: data/dataset/with_mask/296-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._296-with-mask.jpg  \n      inflating: data/dataset/with_mask/452-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._452-with-mask.jpg  \n      inflating: data/dataset/with_mask/127-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._127-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_172.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_172.jpg  \n      inflating: data/dataset/with_mask/109-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._109-with-mask.jpg  \n      inflating: data/dataset/with_mask/205-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._205-with-mask.jpg  \n      inflating: data/dataset/with_mask/355-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._355-with-mask.jpg  \n      inflating: data/dataset/with_mask/42-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._42-with-mask.jpg  \n      inflating: data/dataset/with_mask/212-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._212-with-mask.jpg  \n      inflating: data/dataset/with_mask/342-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._342-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_210.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_210.jpg  \n      inflating: data/dataset/with_mask/augmented_image_204.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_204.jpg  \n      inflating: data/dataset/with_mask/augmented_image_11.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_11.jpg  \n      inflating: data/dataset/with_mask/augmented_image_39.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_39.jpg  \n      inflating: data/dataset/with_mask/augmented_image_238.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_238.jpg  \n      inflating: data/dataset/with_mask/318-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._318-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_212.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_212.jpg  \n      inflating: data/dataset/with_mask/144-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._144-with-mask.jpg  \n      inflating: data/dataset/with_mask/431-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._431-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_13.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_13.jpg  \n      inflating: data/dataset/with_mask/augmented_image_206.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_206.jpg  \n      inflating: data/dataset/with_mask/153-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._153-with-mask.jpg  \n      inflating: data/dataset/with_mask/426-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._426-with-mask.jpg  \n      inflating: data/dataset/with_mask/18-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._18-with-mask.jpg  \n      inflating: data/dataset/with_mask/408-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._408-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_9.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_9.jpg  \n      inflating: data/dataset/with_mask/augmented_image_158.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_158.jpg  \n      inflating: data/dataset/with_mask/augmented_image_164.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_164.jpg  \n      inflating: data/dataset/with_mask/augmented_image_170.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_170.jpg  \n      inflating: data/dataset/with_mask/36-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._36-with-mask.jpg  \n      inflating: data/dataset/with_mask/21-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._21-with-mask.jpg  \n      inflating: data/dataset/with_mask/336-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._336-with-mask.jpg  \n      inflating: data/dataset/with_mask/157-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._157-with-mask.jpg  \n      inflating: data/dataset/with_mask/422-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._422-with-mask.jpg  \n      inflating: data/dataset/with_mask/140-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._140-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_171.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_171.jpg  \n      inflating: data/dataset/with_mask/435-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._435-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_165.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_165.jpg  \n      inflating: data/dataset/with_mask/augmented_image_159.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_159.jpg  \n      inflating: data/dataset/with_mask/augmented_image_8.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_8.jpg  \n      inflating: data/dataset/with_mask/98-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._98-with-mask.jpg  \n      inflating: data/dataset/with_mask/25-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._25-with-mask.jpg  \n      inflating: data/dataset/with_mask/332-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._332-with-mask.jpg  \n      inflating: data/dataset/with_mask/262-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._262-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_12.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_12.jpg  \n      inflating: data/dataset/with_mask/augmented_image_207.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_207.jpg  \n      inflating: data/dataset/with_mask/32-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._32-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_213.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_213.jpg  \n      inflating: data/dataset/with_mask/325-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._325-with-mask.jpg  \n      inflating: data/dataset/with_mask/275-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._275-with-mask.jpg  \n      inflating: data/dataset/with_mask/179-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._179-with-mask.jpg  \n      inflating: data/dataset/with_mask/398-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._398-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_217.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_217.jpg  \n      inflating: data/dataset/with_mask/augmented_image_203.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_203.jpg  \n      inflating: data/dataset/with_mask/augmented_image_16.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_16.jpg  \n      inflating: data/dataset/with_mask/425-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._425-with-mask.jpg  \n      inflating: data/dataset/with_mask/150-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._150-with-mask.jpg  \n      inflating: data/dataset/with_mask/432-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._432-with-mask.jpg  \n      inflating: data/dataset/with_mask/147-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._147-with-mask.jpg  \n      inflating: data/dataset/with_mask/169-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._169-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_161.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_161.jpg  \n      inflating: data/dataset/with_mask/augmented_image_175.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_175.jpg  \n      inflating: data/dataset/with_mask/335-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._335-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_149.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_149.jpg  \n      inflating: data/dataset/with_mask/272-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._272-with-mask.jpg  \n      inflating: data/dataset/with_mask/322-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._322-with-mask.jpg  \n      inflating: data/dataset/with_mask/35-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._35-with-mask.jpg  \n      inflating: data/dataset/with_mask/88-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._88-with-mask.jpg  \n      inflating: data/dataset/with_mask/436-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._436-with-mask.jpg  \n      inflating: data/dataset/with_mask/143-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._143-with-mask.jpg  \n      inflating: data/dataset/with_mask/421-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._421-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_148.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_148.jpg  \n      inflating: data/dataset/with_mask/154-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._154-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_174.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_174.jpg  \n      inflating: data/dataset/with_mask/augmented_image_160.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_160.jpg  \n      inflating: data/dataset/with_mask/308-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._308-with-mask.jpg  \n      inflating: data/dataset/with_mask/326-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._326-with-mask.jpg  \n      inflating: data/dataset/with_mask/276-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._276-with-mask.jpg  \n      inflating: data/dataset/with_mask/31-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._31-with-mask.jpg  \n      inflating: data/dataset/with_mask/331-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._331-with-mask.jpg  \n      inflating: data/dataset/with_mask/261-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._261-with-mask.jpg  \n      inflating: data/dataset/with_mask/26-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._26-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_202.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_202.jpg  \n      inflating: data/dataset/with_mask/augmented_image_17.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_17.jpg  \n      inflating: data/dataset/with_mask/418-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._418-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_216.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_216.jpg  \n      inflating: data/dataset/with_mask/augmented_image_15.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_15.jpg  \n      inflating: data/dataset/with_mask/augmented_image_200.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_200.jpg  \n      inflating: data/dataset/with_mask/augmented_image_214.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_214.jpg  \n      inflating: data/dataset/with_mask/augmented_image_29.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_29.jpg  \n      inflating: data/dataset/with_mask/286-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._286-with-mask.jpg  \n      inflating: data/dataset/with_mask/137-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._137-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_228.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_228.jpg  \n      inflating: data/dataset/with_mask/442-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._442-with-mask.jpg  \n      inflating: data/dataset/with_mask/291-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._291-with-mask.jpg  \n      inflating: data/dataset/with_mask/120-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._120-with-mask.jpg  \n      inflating: data/dataset/with_mask/455-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._455-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_176.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_176.jpg  \n      inflating: data/dataset/with_mask/augmented_image_162.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_162.jpg  \n      inflating: data/dataset/with_mask/45-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._45-with-mask.jpg  \n      inflating: data/dataset/with_mask/202-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._202-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_189.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_189.jpg  \n      inflating: data/dataset/with_mask/52-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._52-with-mask.jpg  \n      inflating: data/dataset/with_mask/345-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._345-with-mask.jpg  \n      inflating: data/dataset/with_mask/215-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._215-with-mask.jpg  \n      inflating: data/dataset/with_mask/119-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._119-with-mask.jpg  \n      inflating: data/dataset/with_mask/228-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._228-with-mask.jpg  \n      inflating: data/dataset/with_mask/378-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._378-with-mask.jpg  \n      inflating: data/dataset/with_mask/295-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._295-with-mask.jpg  \n      inflating: data/dataset/with_mask/124-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._124-with-mask.jpg  \n      inflating: data/dataset/with_mask/451-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._451-with-mask.jpg  \n      inflating: data/dataset/with_mask/9-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._9-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_188.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_188.jpg  \n      inflating: data/dataset/with_mask/282-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._282-with-mask.jpg  \n      inflating: data/dataset/with_mask/133-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._133-with-mask.jpg  \n      inflating: data/dataset/with_mask/446-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._446-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_163.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_163.jpg  \n      inflating: data/dataset/with_mask/78-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._78-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_177.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_177.jpg  \n      inflating: data/dataset/with_mask/56-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._56-with-mask.jpg  \n      inflating: data/dataset/with_mask/211-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._211-with-mask.jpg  \n      inflating: data/dataset/with_mask/41-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._41-with-mask.jpg  \n      inflating: data/dataset/with_mask/206-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._206-with-mask.jpg  \n      inflating: data/dataset/with_mask/356-with-mask.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._356-with-mask.jpg  \n      inflating: data/dataset/with_mask/augmented_image_28.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_28.jpg  \n      inflating: data/dataset/with_mask/augmented_image_215.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_215.jpg  \n      inflating: data/dataset/with_mask/augmented_image_14.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_14.jpg  \n      inflating: data/dataset/with_mask/augmented_image_201.jpg  \n      inflating: data/__MACOSX/dataset/with_mask/._augmented_image_201.jpg  \n      inflating: data/dataset/without_mask/63.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._63.jpg  \n      inflating: data/dataset/without_mask/augmented_image_19.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_19.jpg  \n      inflating: data/dataset/without_mask/77.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._77.jpg  \n      inflating: data/dataset/without_mask/augmented_image_224.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_224.jpg  \n      inflating: data/dataset/without_mask/augmented_image_31.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_31.jpg  \n      inflating: data/dataset/without_mask/augmented_image_25.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_25.jpg  \n      inflating: data/dataset/without_mask/augmented_image_230.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_230.jpg  \n      inflating: data/dataset/without_mask/162.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._162.jpg  \n      inflating: data/dataset/without_mask/176.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._176.jpg  \n      inflating: data/dataset/without_mask/88.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._88.jpg  \n      inflating: data/dataset/without_mask/348.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._348.jpg  \n      inflating: data/dataset/without_mask/360.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._360.jpg  \n      inflating: data/dataset/without_mask/406.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._406.jpg  \n      inflating: data/dataset/without_mask/412.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._412.jpg  \n      inflating: data/dataset/without_mask/374.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._374.jpg  \n      inflating: data/dataset/without_mask/augmented_image_3.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_3.jpg  \n      inflating: data/dataset/without_mask/augmented_image_152.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_152.jpg  \n      inflating: data/dataset/without_mask/228.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._228.jpg  \n      inflating: data/dataset/without_mask/214.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._214.jpg  \n      inflating: data/dataset/without_mask/augmented_image_191.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_191.jpg  \n      inflating: data/dataset/without_mask/augmented_image_185.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_185.jpg  \n      inflating: data/dataset/without_mask/augmented_image_184.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_184.jpg  \n      inflating: data/dataset/without_mask/201.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._201.jpg  \n      inflating: data/dataset/without_mask/215.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._215.jpg  \n      inflating: data/dataset/without_mask/229.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._229.jpg  \n      inflating: data/dataset/without_mask/augmented_image_147.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_147.jpg  \n      inflating: data/dataset/without_mask/augmented_image_153.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_153.jpg  \n      inflating: data/dataset/without_mask/augmented_image_2.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_2.jpg  \n      inflating: data/dataset/without_mask/413.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._413.jpg  \n      inflating: data/dataset/without_mask/375.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._375.jpg  \n      inflating: data/dataset/without_mask/361.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._361.jpg  \n      inflating: data/dataset/without_mask/407.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._407.jpg  \n      inflating: data/dataset/without_mask/349.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._349.jpg  \n      inflating: data/dataset/without_mask/177.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._177.jpg  \n      inflating: data/dataset/without_mask/89.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._89.jpg  \n      inflating: data/dataset/without_mask/163.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._163.jpg  \n      inflating: data/dataset/without_mask/augmented_image_231.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_231.jpg  \n      inflating: data/dataset/without_mask/augmented_image_225.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_225.jpg  \n      inflating: data/dataset/without_mask/augmented_image_30.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_30.jpg  \n      inflating: data/dataset/without_mask/augmented_image_18.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_18.jpg  \n      inflating: data/dataset/without_mask/188.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._188.jpg  \n      inflating: data/dataset/without_mask/76.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._76.jpg  \n      inflating: data/dataset/without_mask/augmented_image_219.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_219.jpg  \n      inflating: data/dataset/without_mask/62.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._62.jpg  \n      inflating: data/dataset/without_mask/74.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._74.jpg  \n      inflating: data/dataset/without_mask/48.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._48.jpg  \n      inflating: data/dataset/without_mask/augmented_image_233.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_233.jpg  \n      inflating: data/dataset/without_mask/augmented_image_32.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_32.jpg  \n      inflating: data/dataset/without_mask/augmented_image_227.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_227.jpg  \n      inflating: data/dataset/without_mask/149.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._149.jpg  \n      inflating: data/dataset/without_mask/175.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._175.jpg  \n      inflating: data/dataset/without_mask/161.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._161.jpg  \n      inflating: data/dataset/without_mask/388.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._388.jpg  \n      inflating: data/dataset/without_mask/439.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._439.jpg  \n      inflating: data/dataset/without_mask/411.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._411.jpg  \n      inflating: data/dataset/without_mask/405.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._405.jpg  \n      inflating: data/dataset/without_mask/363.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._363.jpg  \n      inflating: data/dataset/without_mask/augmented_image_179.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_179.jpg  \n      inflating: data/dataset/without_mask/augmented_image_145.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_145.jpg  \n      inflating: data/dataset/without_mask/augmented_image_151.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_151.jpg  \n      inflating: data/dataset/without_mask/203.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._203.jpg  \n      inflating: data/dataset/without_mask/augmented_image_186.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_186.jpg  \n      inflating: data/dataset/without_mask/augmented_image_192.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_192.jpg  \n      inflating: data/dataset/without_mask/217.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._217.jpg  \n      inflating: data/dataset/without_mask/augmented_image_193.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_193.jpg  \n      inflating: data/dataset/without_mask/216.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._216.jpg  \n      inflating: data/dataset/without_mask/augmented_image_187.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_187.jpg  \n      inflating: data/dataset/without_mask/augmented_image_150.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_150.jpg  \n      inflating: data/dataset/without_mask/augmented_image_1.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_1.jpg  \n      inflating: data/dataset/without_mask/augmented_image_144.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_144.jpg  \n      inflating: data/dataset/without_mask/augmented_image_178.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_178.jpg  \n      inflating: data/dataset/without_mask/404.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._404.jpg  \n      inflating: data/dataset/without_mask/362.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._362.jpg  \n      inflating: data/dataset/without_mask/376.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._376.jpg  \n      inflating: data/dataset/without_mask/410.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._410.jpg  \n      inflating: data/dataset/without_mask/438.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._438.jpg  \n      inflating: data/dataset/without_mask/389.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._389.jpg  \n      inflating: data/dataset/without_mask/160.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._160.jpg  \n      inflating: data/dataset/without_mask/174.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._174.jpg  \n      inflating: data/dataset/without_mask/148.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._148.jpg  \n      inflating: data/dataset/without_mask/augmented_image_33.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_33.jpg  \n      inflating: data/dataset/without_mask/augmented_image_226.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_226.jpg  \n      inflating: data/dataset/without_mask/augmented_image_232.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_232.jpg  \n      inflating: data/dataset/without_mask/49.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._49.jpg  \n      inflating: data/dataset/without_mask/augmented_image_27.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_27.jpg  \n      inflating: data/dataset/without_mask/61.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._61.jpg  \n      inflating: data/dataset/without_mask/augmented_image_23.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_23.jpg  \n      inflating: data/dataset/without_mask/augmented_image_236.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_236.jpg  \n      inflating: data/dataset/without_mask/augmented_image_222.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_222.jpg  \n      inflating: data/dataset/without_mask/59.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._59.jpg  \n      inflating: data/dataset/without_mask/augmented_image_37.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_37.jpg  \n      inflating: data/dataset/without_mask/65.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._65.jpg  \n      inflating: data/dataset/without_mask/170.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._170.jpg  \n      inflating: data/dataset/without_mask/164.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._164.jpg  \n      inflating: data/dataset/without_mask/158.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._158.jpg  \n      inflating: data/dataset/without_mask/399.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._399.jpg  \n      inflating: data/dataset/without_mask/414.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._414.jpg  \n      inflating: data/dataset/without_mask/372.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._372.jpg  \n      inflating: data/dataset/without_mask/400.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._400.jpg  \n      inflating: data/dataset/without_mask/428.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._428.jpg  \n      inflating: data/dataset/without_mask/augmented_image_140.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_140.jpg  \n      inflating: data/dataset/without_mask/augmented_image_5.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_5.jpg  \n      inflating: data/dataset/without_mask/augmented_image_154.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_154.jpg  \n      inflating: data/dataset/without_mask/augmented_image_168.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_168.jpg  \n      inflating: data/dataset/without_mask/augmented_image_183.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_183.jpg  \n      inflating: data/dataset/without_mask/206.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._206.jpg  \n      inflating: data/dataset/without_mask/212.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._212.jpg  \n      inflating: data/dataset/without_mask/augmented_image_197.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_197.jpg  \n      inflating: data/dataset/without_mask/213.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._213.jpg  \n      inflating: data/dataset/without_mask/augmented_image_196.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_196.jpg  \n      inflating: data/dataset/without_mask/augmented_image_182.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_182.jpg  \n      inflating: data/dataset/without_mask/207.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._207.jpg  \n      inflating: data/dataset/without_mask/augmented_image_169.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_169.jpg  \n      inflating: data/dataset/without_mask/augmented_image_155.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_155.jpg  \n      inflating: data/dataset/without_mask/augmented_image_4.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_4.jpg  \n      inflating: data/dataset/without_mask/augmented_image_141.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_141.jpg  \n      inflating: data/dataset/without_mask/367.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._367.jpg  \n      inflating: data/dataset/without_mask/401.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._401.jpg  \n      inflating: data/dataset/without_mask/415.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._415.jpg  \n      inflating: data/dataset/without_mask/373.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._373.jpg  \n      inflating: data/dataset/without_mask/398.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._398.jpg  \n      inflating: data/dataset/without_mask/159.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._159.jpg  \n      inflating: data/dataset/without_mask/171.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._171.jpg  \n      inflating: data/dataset/without_mask/64.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._64.jpg  \n      inflating: data/dataset/without_mask/70.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._70.jpg  \n      inflating: data/dataset/without_mask/58.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._58.jpg  \n      inflating: data/dataset/without_mask/augmented_image_223.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_223.jpg  \n      inflating: data/dataset/without_mask/augmented_image_36.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_36.jpg  \n      inflating: data/dataset/without_mask/augmented_image_22.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_22.jpg  \n      inflating: data/dataset/without_mask/augmented_image_237.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_237.jpg  \n      inflating: data/dataset/without_mask/augmented_image_221.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_221.jpg  \n      inflating: data/dataset/without_mask/augmented_image_235.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_235.jpg  \n      inflating: data/dataset/without_mask/augmented_image_20.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_20.jpg  \n      inflating: data/dataset/without_mask/198.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._198.jpg  \n      inflating: data/dataset/without_mask/66.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._66.jpg  \n      inflating: data/dataset/without_mask/augmented_image_209.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_209.jpg  \n      inflating: data/dataset/without_mask/99.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._99.jpg  \n      inflating: data/dataset/without_mask/173.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._173.jpg  \n      inflating: data/dataset/without_mask/403.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._403.jpg  \n      inflating: data/dataset/without_mask/365.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._365.jpg  \n      inflating: data/dataset/without_mask/417.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._417.jpg  \n      inflating: data/dataset/without_mask/359.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._359.jpg  \n      inflating: data/dataset/without_mask/augmented_image_157.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_157.jpg  \n      inflating: data/dataset/without_mask/augmented_image_143.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_143.jpg  \n      inflating: data/dataset/without_mask/augmented_image_194.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_194.jpg  \n      inflating: data/dataset/without_mask/211.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._211.jpg  \n      inflating: data/dataset/without_mask/augmented_image_180.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_180.jpg  \n      inflating: data/dataset/without_mask/239.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._239.jpg  \n      inflating: data/dataset/without_mask/204.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._204.jpg  \n      inflating: data/dataset/without_mask/augmented_image_181.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_181.jpg  \n      inflating: data/dataset/without_mask/210.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._210.jpg  \n      inflating: data/dataset/without_mask/augmented_image_142.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_142.jpg  \n      inflating: data/dataset/without_mask/augmented_image_156.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_156.jpg  \n      inflating: data/dataset/without_mask/augmented_image_7.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_7.jpg  \n      inflating: data/dataset/without_mask/370.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._370.jpg  \n      inflating: data/dataset/without_mask/416.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._416.jpg  \n      inflating: data/dataset/without_mask/402.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._402.jpg  \n      inflating: data/dataset/without_mask/364.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._364.jpg  \n      inflating: data/dataset/without_mask/172.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._172.jpg  \n      inflating: data/dataset/without_mask/166.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._166.jpg  \n      inflating: data/dataset/without_mask/98.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._98.jpg  \n      inflating: data/dataset/without_mask/73.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._73.jpg  \n      inflating: data/dataset/without_mask/augmented_image_208.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_208.jpg  \n      inflating: data/dataset/without_mask/67.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._67.jpg  \n      inflating: data/dataset/without_mask/augmented_image_234.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_234.jpg  \n      inflating: data/dataset/without_mask/augmented_image_21.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_21.jpg  \n      inflating: data/dataset/without_mask/9.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._9.jpg  \n      inflating: data/dataset/without_mask/augmented_image_35.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_35.jpg  \n      inflating: data/dataset/without_mask/augmented_image_220.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_220.jpg  \n      inflating: data/dataset/without_mask/14.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._14.jpg  \n      inflating: data/dataset/without_mask/augmented_image_52.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_52.jpg  \n      inflating: data/dataset/without_mask/augmented_image_253.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_253.jpg  \n      inflating: data/dataset/without_mask/28.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._28.jpg  \n      inflating: data/dataset/without_mask/129.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._129.jpg  \n      inflating: data/dataset/without_mask/101.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._101.jpg  \n      inflating: data/dataset/without_mask/augmented_image_91.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_91.jpg  \n      inflating: data/dataset/without_mask/augmented_image_284.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_284.jpg  \n      inflating: data/dataset/without_mask/augmented_image_290.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_290.jpg  \n      inflating: data/dataset/without_mask/115.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._115.jpg  \n      inflating: data/dataset/without_mask/augmented_image_85.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_85.jpg  \n      inflating: data/dataset/without_mask/459.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._459.jpg  \n      inflating: data/dataset/without_mask/465.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._465.jpg  \n      inflating: data/dataset/without_mask/303.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._303.jpg  \n      inflating: data/dataset/without_mask/317.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._317.jpg  \n      inflating: data/dataset/without_mask/288.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._288.jpg  \n      inflating: data/dataset/without_mask/augmented_image_119.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_119.jpg  \n      inflating: data/dataset/without_mask/augmented_image_131.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_131.jpg  \n      inflating: data/dataset/without_mask/augmented_image_125.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_125.jpg  \n      inflating: data/dataset/without_mask/263.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._263.jpg  \n      inflating: data/dataset/without_mask/262.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._262.jpg  \n      inflating: data/dataset/without_mask/276.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._276.jpg  \n      inflating: data/dataset/without_mask/augmented_image_124.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_124.jpg  \n      inflating: data/dataset/without_mask/augmented_image_130.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_130.jpg  \n      inflating: data/dataset/without_mask/augmented_image_118.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_118.jpg  \n      inflating: data/dataset/without_mask/289.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._289.jpg  \n      inflating: data/dataset/without_mask/316.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._316.jpg  \n      inflating: data/dataset/without_mask/464.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._464.jpg  \n      inflating: data/dataset/without_mask/302.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._302.jpg  \n      inflating: data/dataset/without_mask/458.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._458.jpg  \n      inflating: data/dataset/without_mask/augmented_image_291.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_291.jpg  \n      inflating: data/dataset/without_mask/augmented_image_84.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_84.jpg  \n      inflating: data/dataset/without_mask/114.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._114.jpg  \n      inflating: data/dataset/without_mask/augmented_image_90.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_90.jpg  \n      inflating: data/dataset/without_mask/100.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._100.jpg  \n      inflating: data/dataset/without_mask/augmented_image_285.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_285.jpg  \n      inflating: data/dataset/without_mask/128.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._128.jpg  \n      inflating: data/dataset/without_mask/29.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._29.jpg  \n      inflating: data/dataset/without_mask/augmented_image_252.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_252.jpg  \n      inflating: data/dataset/without_mask/augmented_image_53.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_53.jpg  \n      inflating: data/dataset/without_mask/augmented_image_246.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_246.jpg  \n      inflating: data/dataset/without_mask/15.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._15.jpg  \n      inflating: data/dataset/without_mask/augmented_image_79.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_79.jpg  \n      inflating: data/dataset/without_mask/17.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._17.jpg  \n      inflating: data/dataset/without_mask/augmented_image_278.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_278.jpg  \n      inflating: data/dataset/without_mask/augmented_image_45.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_45.jpg  \n      inflating: data/dataset/without_mask/augmented_image_250.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_250.jpg  \n      inflating: data/dataset/without_mask/augmented_image_244.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_244.jpg  \n      inflating: data/dataset/without_mask/augmented_image_51.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_51.jpg  \n      inflating: data/dataset/without_mask/augmented_image_86.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_86.jpg  \n      inflating: data/dataset/without_mask/116.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._116.jpg  \n      inflating: data/dataset/without_mask/augmented_image_293.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_293.jpg  \n      inflating: data/dataset/without_mask/augmented_image_287.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_287.jpg  \n      inflating: data/dataset/without_mask/augmented_image_92.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_92.jpg  \n      inflating: data/dataset/without_mask/102.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._102.jpg  \n      inflating: data/dataset/without_mask/328.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._328.jpg  \n      inflating: data/dataset/without_mask/300.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._300.jpg  \n      inflating: data/dataset/without_mask/466.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._466.jpg  \n      inflating: data/dataset/without_mask/augmented_image_126.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_126.jpg  \n      inflating: data/dataset/without_mask/augmented_image_132.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_132.jpg  \n      inflating: data/dataset/without_mask/248.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._248.jpg  \n      inflating: data/dataset/without_mask/260.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._260.jpg  \n      inflating: data/dataset/without_mask/augmented_image_318.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_318.jpg  \n      inflating: data/dataset/without_mask/augmented_image_319.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_319.jpg  \n      inflating: data/dataset/without_mask/275.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._275.jpg  \n      inflating: data/dataset/without_mask/261.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._261.jpg  \n      inflating: data/dataset/without_mask/249.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._249.jpg  \n      inflating: data/dataset/without_mask/augmented_image_133.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_133.jpg  \n      inflating: data/dataset/without_mask/augmented_image_127.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_127.jpg  \n      inflating: data/dataset/without_mask/301.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._301.jpg  \n      inflating: data/dataset/without_mask/467.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._467.jpg  \n      inflating: data/dataset/without_mask/315.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._315.jpg  \n      inflating: data/dataset/without_mask/329.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._329.jpg  \n      inflating: data/dataset/without_mask/augmented_image_286.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_286.jpg  \n      inflating: data/dataset/without_mask/augmented_image_93.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_93.jpg  \n      inflating: data/dataset/without_mask/117.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._117.jpg  \n      inflating: data/dataset/without_mask/augmented_image_87.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_87.jpg  \n      inflating: data/dataset/without_mask/augmented_image_292.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_292.jpg  \n      inflating: data/dataset/without_mask/augmented_image_245.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_245.jpg  \n      inflating: data/dataset/without_mask/augmented_image_50.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_50.jpg  \n      inflating: data/dataset/without_mask/augmented_image_44.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_44.jpg  \n      inflating: data/dataset/without_mask/augmented_image_251.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_251.jpg  \n      inflating: data/dataset/without_mask/augmented_image_279.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_279.jpg  \n      inflating: data/dataset/without_mask/augmented_image_78.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_78.jpg  \n      inflating: data/dataset/without_mask/16.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._16.jpg  \n      inflating: data/dataset/without_mask/augmented_image_255.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_255.jpg  \n      inflating: data/dataset/without_mask/augmented_image_40.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_40.jpg  \n      inflating: data/dataset/without_mask/augmented_image_54.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_54.jpg  \n      inflating: data/dataset/without_mask/augmented_image_241.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_241.jpg  \n      inflating: data/dataset/without_mask/12.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._12.jpg  \n      inflating: data/dataset/without_mask/augmented_image_269.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_269.jpg  \n      inflating: data/dataset/without_mask/augmented_image_68.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_68.jpg  \n      inflating: data/dataset/without_mask/augmented_image_296.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_296.jpg  \n      inflating: data/dataset/without_mask/augmented_image_83.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_83.jpg  \n      inflating: data/dataset/without_mask/augmented_image_97.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_97.jpg  \n      inflating: data/dataset/without_mask/107.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._107.jpg  \n      inflating: data/dataset/without_mask/augmented_image_282.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_282.jpg  \n      inflating: data/dataset/without_mask/311.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._311.jpg  \n      inflating: data/dataset/without_mask/477.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._477.jpg  \n      inflating: data/dataset/without_mask/463.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._463.jpg  \n      inflating: data/dataset/without_mask/339.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._339.jpg  \n      inflating: data/dataset/without_mask/augmented_image_123.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_123.jpg  \n      inflating: data/dataset/without_mask/augmented_image_137.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_137.jpg  \n      inflating: data/dataset/without_mask/265.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._265.jpg  \n      inflating: data/dataset/without_mask/271.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._271.jpg  \n      inflating: data/dataset/without_mask/259.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._259.jpg  \n      inflating: data/dataset/without_mask/augmented_image_309.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_309.jpg  \n      inflating: data/dataset/without_mask/augmented_image_308.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_308.jpg  \n      inflating: data/dataset/without_mask/258.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._258.jpg  \n      inflating: data/dataset/without_mask/270.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._270.jpg  \n      inflating: data/dataset/without_mask/264.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._264.jpg  \n      inflating: data/dataset/without_mask/augmented_image_136.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_136.jpg  \n      inflating: data/dataset/without_mask/augmented_image_122.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_122.jpg  \n      inflating: data/dataset/without_mask/338.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._338.jpg  \n      inflating: data/dataset/without_mask/462.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._462.jpg  \n      inflating: data/dataset/without_mask/310.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._310.jpg  \n      inflating: data/dataset/without_mask/476.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._476.jpg  \n      inflating: data/dataset/without_mask/106.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._106.jpg  \n      inflating: data/dataset/without_mask/augmented_image_96.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_96.jpg  \n      inflating: data/dataset/without_mask/augmented_image_283.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_283.jpg  \n      inflating: data/dataset/without_mask/augmented_image_297.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_297.jpg  \n      inflating: data/dataset/without_mask/112.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._112.jpg  \n      inflating: data/dataset/without_mask/augmented_image_82.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_82.jpg  \n      inflating: data/dataset/without_mask/augmented_image_69.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_69.jpg  \n      inflating: data/dataset/without_mask/13.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._13.jpg  \n      inflating: data/dataset/without_mask/augmented_image_55.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_55.jpg  \n      inflating: data/dataset/without_mask/augmented_image_240.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_240.jpg  \n      inflating: data/dataset/without_mask/augmented_image_254.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_254.jpg  \n      inflating: data/dataset/without_mask/augmented_image_41.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_41.jpg  \n      inflating: data/dataset/without_mask/39.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._39.jpg  \n      inflating: data/dataset/without_mask/augmented_image_57.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_57.jpg  \n      inflating: data/dataset/without_mask/augmented_image_43.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_43.jpg  \n      inflating: data/dataset/without_mask/augmented_image_256.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_256.jpg  \n      inflating: data/dataset/without_mask/11.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._11.jpg  \n      inflating: data/dataset/without_mask/augmented_image_281.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_281.jpg  \n      inflating: data/dataset/without_mask/104.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._104.jpg  \n      inflating: data/dataset/without_mask/augmented_image_94.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_94.jpg  \n      inflating: data/dataset/without_mask/110.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._110.jpg  \n      inflating: data/dataset/without_mask/augmented_image_80.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_80.jpg  \n      inflating: data/dataset/without_mask/augmented_image_295.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_295.jpg  \n      inflating: data/dataset/without_mask/138.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._138.jpg  \n      inflating: data/dataset/without_mask/306.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._306.jpg  \n      inflating: data/dataset/without_mask/460.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._460.jpg  \n      inflating: data/dataset/without_mask/312.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._312.jpg  \n      inflating: data/dataset/without_mask/448.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._448.jpg  \n      inflating: data/dataset/without_mask/augmented_image_134.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_134.jpg  \n      inflating: data/dataset/without_mask/augmented_image_120.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_120.jpg  \n      inflating: data/dataset/without_mask/299.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._299.jpg  \n      inflating: data/dataset/without_mask/266.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._266.jpg  \n      inflating: data/dataset/without_mask/267.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._267.jpg  \n      inflating: data/dataset/without_mask/298.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._298.jpg  \n      inflating: data/dataset/without_mask/augmented_image_109.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_109.jpg  \n      inflating: data/dataset/without_mask/augmented_image_121.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_121.jpg  \n      inflating: data/dataset/without_mask/augmented_image_135.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_135.jpg  \n      inflating: data/dataset/without_mask/449.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._449.jpg  \n      inflating: data/dataset/without_mask/475.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._475.jpg  \n      inflating: data/dataset/without_mask/307.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._307.jpg  \n      inflating: data/dataset/without_mask/461.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._461.jpg  \n      inflating: data/dataset/without_mask/139.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._139.jpg  \n      inflating: data/dataset/without_mask/augmented_image_81.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_81.jpg  \n      inflating: data/dataset/without_mask/111.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._111.jpg  \n      inflating: data/dataset/without_mask/augmented_image_294.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_294.jpg  \n      inflating: data/dataset/without_mask/augmented_image_280.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_280.jpg  \n      inflating: data/dataset/without_mask/augmented_image_95.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_95.jpg  \n      inflating: data/dataset/without_mask/105.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._105.jpg  \n      inflating: data/dataset/without_mask/10.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._10.jpg  \n      inflating: data/dataset/without_mask/augmented_image_42.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_42.jpg  \n      inflating: data/dataset/without_mask/augmented_image_257.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_257.jpg  \n      inflating: data/dataset/without_mask/augmented_image_243.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_243.jpg  \n      inflating: data/dataset/without_mask/augmented_image_56.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_56.jpg  \n      inflating: data/dataset/without_mask/augmented_image_73.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_73.jpg  \n      inflating: data/dataset/without_mask/augmented_image_266.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_266.jpg  \n      inflating: data/dataset/without_mask/augmented_image_272.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_272.jpg  \n      inflating: data/dataset/without_mask/augmented_image_67.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_67.jpg  \n      inflating: data/dataset/without_mask/augmented_image_299.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_299.jpg  \n      inflating: data/dataset/without_mask/augmented_image_98.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_98.jpg  \n      inflating: data/dataset/without_mask/108.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._108.jpg  \n      inflating: data/dataset/without_mask/120.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._120.jpg  \n      inflating: data/dataset/without_mask/134.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._134.jpg  \n      inflating: data/dataset/without_mask/478.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._478.jpg  \n      inflating: data/dataset/without_mask/444.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._444.jpg  \n      inflating: data/dataset/without_mask/322.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._322.jpg  \n      inflating: data/dataset/without_mask/336.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._336.jpg  \n      inflating: data/dataset/without_mask/450.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._450.jpg  \n      inflating: data/dataset/without_mask/augmented_image_138.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_138.jpg  \n      inflating: data/dataset/without_mask/295.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._295.jpg  \n      inflating: data/dataset/without_mask/281.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._281.jpg  \n      inflating: data/dataset/without_mask/256.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._256.jpg  \n      inflating: data/dataset/without_mask/242.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._242.jpg  \n      inflating: data/dataset/without_mask/augmented_image_312.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_312.jpg  \n      inflating: data/dataset/without_mask/augmented_image_306.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_306.jpg  \n      inflating: data/dataset/without_mask/augmented_image_307.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_307.jpg  \n      inflating: data/dataset/without_mask/243.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._243.jpg  \n      inflating: data/dataset/without_mask/280.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._280.jpg  \n      inflating: data/dataset/without_mask/augmented_image_105.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_105.jpg  \n      inflating: data/dataset/without_mask/augmented_image_111.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_111.jpg  \n      inflating: data/dataset/without_mask/294.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._294.jpg  \n      inflating: data/dataset/without_mask/augmented_image_139.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_139.jpg  \n      inflating: data/dataset/without_mask/337.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._337.jpg  \n      inflating: data/dataset/without_mask/451.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._451.jpg  \n      inflating: data/dataset/without_mask/445.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._445.jpg  \n      inflating: data/dataset/without_mask/323.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._323.jpg  \n      inflating: data/dataset/without_mask/135.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._135.jpg  \n      inflating: data/dataset/without_mask/109.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._109.jpg  \n      inflating: data/dataset/without_mask/augmented_image_99.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_99.jpg  \n      inflating: data/dataset/without_mask/augmented_image_298.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_298.jpg  \n      inflating: data/dataset/without_mask/augmented_image_273.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_273.jpg  \n      inflating: data/dataset/without_mask/augmented_image_66.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_66.jpg  \n      inflating: data/dataset/without_mask/augmented_image_72.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_72.jpg  \n      inflating: data/dataset/without_mask/augmented_image_267.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_267.jpg  \n      inflating: data/dataset/without_mask/34.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._34.jpg  \n      inflating: data/dataset/without_mask/20.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._20.jpg  \n      inflating: data/dataset/without_mask/augmented_image_58.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_58.jpg  \n      inflating: data/dataset/without_mask/36.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._36.jpg  \n      inflating: data/dataset/without_mask/22.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._22.jpg  \n      inflating: data/dataset/without_mask/augmented_image_64.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_64.jpg  \n      inflating: data/dataset/without_mask/augmented_image_271.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_271.jpg  \n      inflating: data/dataset/without_mask/augmented_image_265.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_265.jpg  \n      inflating: data/dataset/without_mask/augmented_image_70.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_70.jpg  \n      inflating: data/dataset/without_mask/137.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._137.jpg  \n      inflating: data/dataset/without_mask/123.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._123.jpg  \n      inflating: data/dataset/without_mask/309.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._309.jpg  \n      inflating: data/dataset/without_mask/453.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._453.jpg  \n      inflating: data/dataset/without_mask/335.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._335.jpg  \n      inflating: data/dataset/without_mask/321.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._321.jpg  \n      inflating: data/dataset/without_mask/447.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._447.jpg  \n      inflating: data/dataset/without_mask/augmented_image_107.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_107.jpg  \n      inflating: data/dataset/without_mask/282.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._282.jpg  \n      inflating: data/dataset/without_mask/augmented_image_113.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_113.jpg  \n      inflating: data/dataset/without_mask/269.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._269.jpg  \n      inflating: data/dataset/without_mask/241.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._241.jpg  \n      inflating: data/dataset/without_mask/255.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._255.jpg  \n      inflating: data/dataset/without_mask/augmented_image_305.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_305.jpg  \n      inflating: data/dataset/without_mask/augmented_image_311.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_311.jpg  \n      inflating: data/dataset/without_mask/augmented_image_310.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_310.jpg  \n      inflating: data/dataset/without_mask/augmented_image_304.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_304.jpg  \n      inflating: data/dataset/without_mask/254.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._254.jpg  \n      inflating: data/dataset/without_mask/240.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._240.jpg  \n      inflating: data/dataset/without_mask/297.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._297.jpg  \n      inflating: data/dataset/without_mask/augmented_image_112.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_112.jpg  \n      inflating: data/dataset/without_mask/augmented_image_106.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_106.jpg  \n      inflating: data/dataset/without_mask/283.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._283.jpg  \n      inflating: data/dataset/without_mask/446.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._446.jpg  \n      inflating: data/dataset/without_mask/452.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._452.jpg  \n      inflating: data/dataset/without_mask/334.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._334.jpg  \n      inflating: data/dataset/without_mask/308.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._308.jpg  \n      inflating: data/dataset/without_mask/122.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._122.jpg  \n      inflating: data/dataset/without_mask/136.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._136.jpg  \n      inflating: data/dataset/without_mask/augmented_image_71.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_71.jpg  \n      inflating: data/dataset/without_mask/augmented_image_65.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_65.jpg  \n      inflating: data/dataset/without_mask/augmented_image_270.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_270.jpg  \n      inflating: data/dataset/without_mask/augmented_image_258.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_258.jpg  \n      inflating: data/dataset/without_mask/23.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._23.jpg  \n      inflating: data/dataset/without_mask/augmented_image_59.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_59.jpg  \n      inflating: data/dataset/without_mask/37.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._37.jpg  \n      inflating: data/dataset/without_mask/augmented_image_61.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_61.jpg  \n      inflating: data/dataset/without_mask/augmented_image_260.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_260.jpg  \n      inflating: data/dataset/without_mask/33.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._33.jpg  \n      inflating: data/dataset/without_mask/27.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._27.jpg  \n      inflating: data/dataset/without_mask/132.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._132.jpg  \n      inflating: data/dataset/without_mask/330.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._330.jpg  \n      inflating: data/dataset/without_mask/456.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._456.jpg  \n      inflating: data/dataset/without_mask/442.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._442.jpg  \n      inflating: data/dataset/without_mask/324.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._324.jpg  \n      inflating: data/dataset/without_mask/318.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._318.jpg  \n      inflating: data/dataset/without_mask/287.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._287.jpg  \n      inflating: data/dataset/without_mask/augmented_image_116.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_116.jpg  \n      inflating: data/dataset/without_mask/293.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._293.jpg  \n      inflating: data/dataset/without_mask/244.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._244.jpg  \n      inflating: data/dataset/without_mask/250.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._250.jpg  \n      inflating: data/dataset/without_mask/278.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._278.jpg  \n      inflating: data/dataset/without_mask/augmented_image_314.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_314.jpg  \n      inflating: data/dataset/without_mask/augmented_image_315.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_315.jpg  \n      inflating: data/dataset/without_mask/augmented_image_301.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_301.jpg  \n      inflating: data/dataset/without_mask/251.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._251.jpg  \n      inflating: data/dataset/without_mask/augmented_image_117.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_117.jpg  \n      inflating: data/dataset/without_mask/292.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._292.jpg  \n      inflating: data/dataset/without_mask/286.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._286.jpg  \n      inflating: data/dataset/without_mask/augmented_image_103.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_103.jpg  \n      inflating: data/dataset/without_mask/319.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._319.jpg  \n      inflating: data/dataset/without_mask/443.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._443.jpg  \n      inflating: data/dataset/without_mask/325.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._325.jpg  \n      inflating: data/dataset/without_mask/331.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._331.jpg  \n      inflating: data/dataset/without_mask/457.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._457.jpg  \n      inflating: data/dataset/without_mask/480.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._480.jpg  \n      inflating: data/dataset/without_mask/127.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._127.jpg  \n      inflating: data/dataset/without_mask/133.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._133.jpg  \n      inflating: data/dataset/without_mask/augmented_image_48.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_48.jpg  \n      inflating: data/dataset/without_mask/26.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._26.jpg  \n      inflating: data/dataset/without_mask/32.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._32.jpg  \n      inflating: data/dataset/without_mask/augmented_image_249.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_249.jpg  \n      inflating: data/dataset/without_mask/augmented_image_74.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_74.jpg  \n      inflating: data/dataset/without_mask/augmented_image_275.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_275.jpg  \n      inflating: data/dataset/without_mask/augmented_image_60.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_60.jpg  \n      inflating: data/dataset/without_mask/augmented_image_263.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_263.jpg  \n      inflating: data/dataset/without_mask/18.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._18.jpg  \n      inflating: data/dataset/without_mask/augmented_image_76.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_76.jpg  \n      inflating: data/dataset/without_mask/augmented_image_62.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_62.jpg  \n      inflating: data/dataset/without_mask/augmented_image_277.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_277.jpg  \n      inflating: data/dataset/without_mask/24.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._24.jpg  \n      inflating: data/dataset/without_mask/30.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._30.jpg  \n      inflating: data/dataset/without_mask/125.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._125.jpg  \n      inflating: data/dataset/without_mask/131.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._131.jpg  \n      inflating: data/dataset/without_mask/augmented_image_89.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_89.jpg  \n      inflating: data/dataset/without_mask/119.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._119.jpg  \n      inflating: data/dataset/without_mask/327.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._327.jpg  \n      inflating: data/dataset/without_mask/441.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._441.jpg  \n      inflating: data/dataset/without_mask/455.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._455.jpg  \n      inflating: data/dataset/without_mask/469.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._469.jpg  \n      inflating: data/dataset/without_mask/290.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._290.jpg  \n      inflating: data/dataset/without_mask/augmented_image_115.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_115.jpg  \n      inflating: data/dataset/without_mask/augmented_image_101.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_101.jpg  \n      inflating: data/dataset/without_mask/284.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._284.jpg  \n      inflating: data/dataset/without_mask/augmented_image_129.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_129.jpg  \n      inflating: data/dataset/without_mask/253.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._253.jpg  \n      inflating: data/dataset/without_mask/247.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._247.jpg  \n      inflating: data/dataset/without_mask/augmented_image_317.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_317.jpg  \n      inflating: data/dataset/without_mask/augmented_image_303.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_303.jpg  \n      inflating: data/dataset/without_mask/augmented_image_302.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_302.jpg  \n      inflating: data/dataset/without_mask/augmented_image_316.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_316.jpg  \n      inflating: data/dataset/without_mask/246.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._246.jpg  \n      inflating: data/dataset/without_mask/252.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._252.jpg  \n      inflating: data/dataset/without_mask/augmented_image_128.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_128.jpg  \n      inflating: data/dataset/without_mask/augmented_image_100.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_100.jpg  \n      inflating: data/dataset/without_mask/285.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._285.jpg  \n      inflating: data/dataset/without_mask/291.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._291.jpg  \n      inflating: data/dataset/without_mask/augmented_image_114.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_114.jpg  \n      inflating: data/dataset/without_mask/468.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._468.jpg  \n      inflating: data/dataset/without_mask/454.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._454.jpg  \n      inflating: data/dataset/without_mask/332.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._332.jpg  \n      inflating: data/dataset/without_mask/326.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._326.jpg  \n      inflating: data/dataset/without_mask/440.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._440.jpg  \n      inflating: data/dataset/without_mask/118.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._118.jpg  \n      inflating: data/dataset/without_mask/augmented_image_88.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_88.jpg  \n      inflating: data/dataset/without_mask/130.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._130.jpg  \n      inflating: data/dataset/without_mask/124.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._124.jpg  \n      inflating: data/dataset/without_mask/31.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._31.jpg  \n      inflating: data/dataset/without_mask/augmented_image_63.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_63.jpg  \n      inflating: data/dataset/without_mask/augmented_image_276.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_276.jpg  \n      inflating: data/dataset/without_mask/19.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._19.jpg  \n      inflating: data/dataset/without_mask/augmented_image_262.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_262.jpg  \n      inflating: data/dataset/without_mask/augmented_image_77.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_77.jpg  \n      inflating: data/dataset/without_mask/augmented_image_239.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_239.jpg  \n      inflating: data/dataset/without_mask/42.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._42.jpg  \n      inflating: data/dataset/without_mask/4.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._4.jpg  \n      inflating: data/dataset/without_mask/augmented_image_38.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_38.jpg  \n      inflating: data/dataset/without_mask/56.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._56.jpg  \n      inflating: data/dataset/without_mask/augmented_image_205.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_205.jpg  \n      inflating: data/dataset/without_mask/180.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._180.jpg  \n      inflating: data/dataset/without_mask/194.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._194.jpg  \n      inflating: data/dataset/without_mask/augmented_image_211.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_211.jpg  \n      inflating: data/dataset/without_mask/81.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._81.jpg  \n      inflating: data/dataset/without_mask/95.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._95.jpg  \n      inflating: data/dataset/without_mask/143.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._143.jpg  \n      inflating: data/dataset/without_mask/157.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._157.jpg  \n      inflating: data/dataset/without_mask/341.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._341.jpg  \n      inflating: data/dataset/without_mask/427.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._427.jpg  \n      inflating: data/dataset/without_mask/355.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._355.jpg  \n      inflating: data/dataset/without_mask/augmented_image_173.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_173.jpg  \n      inflating: data/dataset/without_mask/augmented_image_198.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_198.jpg  \n      inflating: data/dataset/without_mask/221.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._221.jpg  \n      inflating: data/dataset/without_mask/220.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._220.jpg  \n      inflating: data/dataset/without_mask/234.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._234.jpg  \n      inflating: data/dataset/without_mask/augmented_image_199.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_199.jpg  \n      inflating: data/dataset/without_mask/208.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._208.jpg  \n      inflating: data/dataset/without_mask/augmented_image_166.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_166.jpg  \n      inflating: data/dataset/without_mask/augmented_image_172.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_172.jpg  \n      inflating: data/dataset/without_mask/432.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._432.jpg  \n      inflating: data/dataset/without_mask/354.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._354.jpg  \n      inflating: data/dataset/without_mask/340.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._340.jpg  \n      inflating: data/dataset/without_mask/426.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._426.jpg  \n      inflating: data/dataset/without_mask/368.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._368.jpg  \n      inflating: data/dataset/without_mask/397.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._397.jpg  \n      inflating: data/dataset/without_mask/383.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._383.jpg  \n      inflating: data/dataset/without_mask/156.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._156.jpg  \n      inflating: data/dataset/without_mask/142.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._142.jpg  \n      inflating: data/dataset/without_mask/94.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._94.jpg  \n      inflating: data/dataset/without_mask/80.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._80.jpg  \n      inflating: data/dataset/without_mask/195.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._195.jpg  \n      inflating: data/dataset/without_mask/augmented_image_210.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_210.jpg  \n      inflating: data/dataset/without_mask/augmented_image_204.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_204.jpg  \n      inflating: data/dataset/without_mask/181.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._181.jpg  \n      inflating: data/dataset/without_mask/augmented_image_39.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_39.jpg  \n      inflating: data/dataset/without_mask/57.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._57.jpg  \n      inflating: data/dataset/without_mask/43.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._43.jpg  \n      inflating: data/dataset/without_mask/augmented_image_238.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_238.jpg  \n      inflating: data/dataset/without_mask/55.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._55.jpg  \n      inflating: data/dataset/without_mask/7.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._7.jpg  \n      inflating: data/dataset/without_mask/69.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._69.jpg  \n      inflating: data/dataset/without_mask/197.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._197.jpg  \n      inflating: data/dataset/without_mask/183.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._183.jpg  \n      inflating: data/dataset/without_mask/augmented_image_13.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_13.jpg  \n      inflating: data/dataset/without_mask/augmented_image_206.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_206.jpg  \n      inflating: data/dataset/without_mask/96.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._96.jpg  \n      inflating: data/dataset/without_mask/168.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._168.jpg  \n      inflating: data/dataset/without_mask/154.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._154.jpg  \n      inflating: data/dataset/without_mask/140.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._140.jpg  \n      inflating: data/dataset/without_mask/395.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._395.jpg  \n      inflating: data/dataset/without_mask/356.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._356.jpg  \n      inflating: data/dataset/without_mask/430.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._430.jpg  \n      inflating: data/dataset/without_mask/424.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._424.jpg  \n      inflating: data/dataset/without_mask/augmented_image_158.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_158.jpg  \n      inflating: data/dataset/without_mask/augmented_image_164.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_164.jpg  \n      inflating: data/dataset/without_mask/augmented_image_170.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_170.jpg  \n      inflating: data/dataset/without_mask/222.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._222.jpg  \n      inflating: data/dataset/without_mask/237.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._237.jpg  \n      inflating: data/dataset/without_mask/223.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._223.jpg  \n      inflating: data/dataset/without_mask/augmented_image_171.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_171.jpg  \n      inflating: data/dataset/without_mask/augmented_image_165.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_165.jpg  \n      inflating: data/dataset/without_mask/425.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._425.jpg  \n      inflating: data/dataset/without_mask/431.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._431.jpg  \n      inflating: data/dataset/without_mask/419.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._419.jpg  \n      inflating: data/dataset/without_mask/394.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._394.jpg  \n      inflating: data/dataset/without_mask/141.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._141.jpg  \n      inflating: data/dataset/without_mask/155.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._155.jpg  \n      inflating: data/dataset/without_mask/83.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._83.jpg  \n      inflating: data/dataset/without_mask/97.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._97.jpg  \n      inflating: data/dataset/without_mask/169.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._169.jpg  \n      inflating: data/dataset/without_mask/augmented_image_12.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_12.jpg  \n      inflating: data/dataset/without_mask/augmented_image_207.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_207.jpg  \n      inflating: data/dataset/without_mask/196.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._196.jpg  \n      inflating: data/dataset/without_mask/40.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._40.jpg  \n      inflating: data/dataset/without_mask/54.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._54.jpg  \n      inflating: data/dataset/without_mask/6.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._6.jpg  \n      inflating: data/dataset/without_mask/192.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._192.jpg  \n      inflating: data/dataset/without_mask/augmented_image_203.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_203.jpg  \n      inflating: data/dataset/without_mask/186.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._186.jpg  \n      inflating: data/dataset/without_mask/augmented_image_16.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_16.jpg  \n      inflating: data/dataset/without_mask/2.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._2.jpg  \n      inflating: data/dataset/without_mask/50.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._50.jpg  \n      inflating: data/dataset/without_mask/44.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._44.jpg  \n      inflating: data/dataset/without_mask/151.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._151.jpg  \n      inflating: data/dataset/without_mask/145.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._145.jpg  \n      inflating: data/dataset/without_mask/93.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._93.jpg  \n      inflating: data/dataset/without_mask/87.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._87.jpg  \n      inflating: data/dataset/without_mask/179.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._179.jpg  \n      inflating: data/dataset/without_mask/390.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._390.jpg  \n      inflating: data/dataset/without_mask/384.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._384.jpg  \n      inflating: data/dataset/without_mask/435.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._435.jpg  \n      inflating: data/dataset/without_mask/353.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._353.jpg  \n      inflating: data/dataset/without_mask/347.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._347.jpg  \n      inflating: data/dataset/without_mask/421.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._421.jpg  \n      inflating: data/dataset/without_mask/409.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._409.jpg  \n      inflating: data/dataset/without_mask/augmented_image_161.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_161.jpg  \n      inflating: data/dataset/without_mask/augmented_image_175.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_175.jpg  \n      inflating: data/dataset/without_mask/augmented_image_149.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_149.jpg  \n      inflating: data/dataset/without_mask/227.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._227.jpg  \n      inflating: data/dataset/without_mask/233.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._233.jpg  \n      inflating: data/dataset/without_mask/232.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._232.jpg  \n      inflating: data/dataset/without_mask/226.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._226.jpg  \n      inflating: data/dataset/without_mask/augmented_image_148.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_148.jpg  \n      inflating: data/dataset/without_mask/augmented_image_174.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_174.jpg  \n      inflating: data/dataset/without_mask/augmented_image_160.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_160.jpg  \n      inflating: data/dataset/without_mask/408.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._408.jpg  \n      inflating: data/dataset/without_mask/420.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._420.jpg  \n      inflating: data/dataset/without_mask/434.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._434.jpg  \n      inflating: data/dataset/without_mask/352.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._352.jpg  \n      inflating: data/dataset/without_mask/385.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._385.jpg  \n      inflating: data/dataset/without_mask/391.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._391.jpg  \n      inflating: data/dataset/without_mask/86.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._86.jpg  \n      inflating: data/dataset/without_mask/178.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._178.jpg  \n      inflating: data/dataset/without_mask/92.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._92.jpg  \n      inflating: data/dataset/without_mask/45.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._45.jpg  \n      inflating: data/dataset/without_mask/3.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._3.jpg  \n      inflating: data/dataset/without_mask/51.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._51.jpg  \n      inflating: data/dataset/without_mask/augmented_image_202.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_202.jpg  \n      inflating: data/dataset/without_mask/79.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._79.jpg  \n      inflating: data/dataset/without_mask/augmented_image_17.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_17.jpg  \n      inflating: data/dataset/without_mask/187.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._187.jpg  \n      inflating: data/dataset/without_mask/193.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._193.jpg  \n      inflating: data/dataset/without_mask/augmented_image_216.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_216.jpg  \n      inflating: data/dataset/without_mask/185.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._185.jpg  \n      inflating: data/dataset/without_mask/augmented_image_200.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_200.jpg  \n      inflating: data/dataset/without_mask/augmented_image_214.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_214.jpg  \n      inflating: data/dataset/without_mask/191.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._191.jpg  \n      inflating: data/dataset/without_mask/47.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._47.jpg  \n      inflating: data/dataset/without_mask/53.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._53.jpg  \n      inflating: data/dataset/without_mask/1.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._1.jpg  \n      inflating: data/dataset/without_mask/146.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._146.jpg  \n      inflating: data/dataset/without_mask/152.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._152.jpg  \n      inflating: data/dataset/without_mask/84.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._84.jpg  \n      inflating: data/dataset/without_mask/90.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._90.jpg  \n      inflating: data/dataset/without_mask/387.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._387.jpg  \n      inflating: data/dataset/without_mask/393.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._393.jpg  \n      inflating: data/dataset/without_mask/422.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._422.jpg  \n      inflating: data/dataset/without_mask/344.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._344.jpg  \n      inflating: data/dataset/without_mask/350.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._350.jpg  \n      inflating: data/dataset/without_mask/436.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._436.jpg  \n      inflating: data/dataset/without_mask/378.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._378.jpg  \n      inflating: data/dataset/without_mask/augmented_image_176.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_176.jpg  \n      inflating: data/dataset/without_mask/augmented_image_162.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_162.jpg  \n      inflating: data/dataset/without_mask/230.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._230.jpg  \n      inflating: data/dataset/without_mask/224.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._224.jpg  \n      inflating: data/dataset/without_mask/augmented_image_189.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_189.jpg  \n      inflating: data/dataset/without_mask/218.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._218.jpg  \n      inflating: data/dataset/without_mask/augmented_image_188.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_188.jpg  \n      inflating: data/dataset/without_mask/225.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._225.jpg  \n      inflating: data/dataset/without_mask/231.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._231.jpg  \n      inflating: data/dataset/without_mask/augmented_image_163.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_163.jpg  \n      inflating: data/dataset/without_mask/augmented_image_177.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_177.jpg  \n      inflating: data/dataset/without_mask/379.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._379.jpg  \n      inflating: data/dataset/without_mask/351.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._351.jpg  \n      inflating: data/dataset/without_mask/437.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._437.jpg  \n      inflating: data/dataset/without_mask/423.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._423.jpg  \n      inflating: data/dataset/without_mask/345.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._345.jpg  \n      inflating: data/dataset/without_mask/392.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._392.jpg  \n      inflating: data/dataset/without_mask/386.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._386.jpg  \n      inflating: data/dataset/without_mask/91.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._91.jpg  \n      inflating: data/dataset/without_mask/153.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._153.jpg  \n      inflating: data/dataset/without_mask/augmented_image_229.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_229.jpg  \n      inflating: data/dataset/without_mask/52.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._52.jpg  \n      inflating: data/dataset/without_mask/0.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._0.jpg  \n      inflating: data/dataset/without_mask/46.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._46.jpg  \n      inflating: data/dataset/without_mask/augmented_image_215.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_215.jpg  \n      inflating: data/dataset/without_mask/184.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._184.jpg  \n      inflating: data/dataset/without_mask/augmented_image_14.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_14.jpg  \n      inflating: data/dataset/without_mask/augmented_image_201.jpg  \n      inflating: data/__MACOSX/dataset/without_mask/._augmented_image_201.jpg  \n\n\n\n```\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import MobileNetV2\nfrom tensorflow.keras.models import Model, Sequential\nfrom tensorflow.keras.layers import AveragePooling2D, Dropout, Flatten, Dense, InputLayer, Input, BatchNormalization\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\nfrom tensorflow.keras.preprocessing.image import img_to_array, load_img\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom imutils import paths\nimport numpy as np\n```\n\n##Load data and preprocess\n\n\n```\nimagePaths = list(paths.list_images('data/dataset/'))\ndata = []\nlabels = []\nnum_images = len(imagePaths)\nfor i, imagePath in enumerate(imagePaths):\n  image = load_img(imagePath, target_size=(224, 224))\n  image = img_to_array(image)\n  image = preprocess_input(image)\n\n  data.append(image)\n  print('Processed {} images of {}'.format(i+1, num_images))\n  labels.append(imagePath.split('/')[-2])\n\n```\n\n    Processed 1 images of 1376\n    Processed 2 images of 1376\n    Processed 3 images of 1376\n    Processed 4 images of 1376\n    Processed 5 images of 1376\n    Processed 6 images of 1376\n    Processed 7 images of 1376\n    Processed 8 images of 1376\n    Processed 9 images of 1376\n    Processed 10 images of 1376\n    Processed 11 images of 1376\n    Processed 12 images of 1376\n    Processed 13 images of 1376\n    Processed 14 images of 1376\n    Processed 15 images of 1376\n    Processed 16 images of 1376\n    Processed 17 images of 1376\n    Processed 18 images of 1376\n    Processed 19 images of 1376\n    Processed 20 images of 1376\n    Processed 21 images of 1376\n    Processed 22 images of 1376\n    Processed 23 images of 1376\n    Processed 24 images of 1376\n    Processed 25 images of 1376\n    Processed 26 images of 1376\n    Processed 27 images of 1376\n    Processed 28 images of 1376\n    Processed 29 images of 1376\n    Processed 30 images of 1376\n    Processed 31 images of 1376\n    Processed 32 images of 1376\n    Processed 33 images of 1376\n    Processed 34 images of 1376\n    Processed 35 images of 1376\n    Processed 36 images of 1376\n    Processed 37 images of 1376\n    Processed 38 images of 1376\n    Processed 39 images of 1376\n    Processed 40 images of 1376\n    Processed 41 images of 1376\n    Processed 42 images of 1376\n    Processed 43 images of 1376\n    Processed 44 images of 1376\n    Processed 45 images of 1376\n    Processed 46 images of 1376\n    Processed 47 images of 1376\n    Processed 48 images of 1376\n    Processed 49 images of 1376\n    Processed 50 images of 1376\n    Processed 51 images of 1376\n    Processed 52 images of 1376\n    Processed 53 images of 1376\n    Processed 54 images of 1376\n    Processed 55 images of 1376\n    Processed 56 images of 1376\n    Processed 57 images of 1376\n    Processed 58 images of 1376\n    Processed 59 images of 1376\n    Processed 60 images of 1376\n    Processed 61 images of 1376\n    Processed 62 images of 1376\n    Processed 63 images of 1376\n    Processed 64 images of 1376\n    Processed 65 images of 1376\n    Processed 66 images of 1376\n    Processed 67 images of 1376\n    Processed 68 images of 1376\n    Processed 69 images of 1376\n    Processed 70 images of 1376\n    Processed 71 images of 1376\n    Processed 72 images of 1376\n    Processed 73 images of 1376\n    Processed 74 images of 1376\n    Processed 75 images of 1376\n    Processed 76 images of 1376\n    Processed 77 images of 1376\n    Processed 78 images of 1376\n    Processed 79 images of 1376\n    Processed 80 images of 1376\n    Processed 81 images of 1376\n    Processed 82 images of 1376\n    Processed 83 images of 1376\n    Processed 84 images of 1376\n    Processed 85 images of 1376\n    Processed 86 images of 1376\n    Processed 87 images of 1376\n    Processed 88 images of 1376\n    Processed 89 images of 1376\n    Processed 90 images of 1376\n    Processed 91 images of 1376\n    Processed 92 images of 1376\n    Processed 93 images of 1376\n    Processed 94 images of 1376\n    Processed 95 images of 1376\n    Processed 96 images of 1376\n    Processed 97 images of 1376\n    Processed 98 images of 1376\n    Processed 99 images of 1376\n    Processed 100 images of 1376\n    Processed 101 images of 1376\n    Processed 102 images of 1376\n    Processed 103 images of 1376\n    Processed 104 images of 1376\n    Processed 105 images of 1376\n    Processed 106 images of 1376\n    Processed 107 images of 1376\n    Processed 108 images of 1376\n    Processed 109 images of 1376\n    Processed 110 images of 1376\n    Processed 111 images of 1376\n    Processed 112 images of 1376\n    Processed 113 images of 1376\n    Processed 114 images of 1376\n    Processed 115 images of 1376\n    Processed 116 images of 1376\n    Processed 117 images of 1376\n    Processed 118 images of 1376\n    Processed 119 images of 1376\n    Processed 120 images of 1376\n    Processed 121 images of 1376\n    Processed 122 images of 1376\n    Processed 123 images of 1376\n    Processed 124 images of 1376\n    Processed 125 images of 1376\n    Processed 126 images of 1376\n    Processed 127 images of 1376\n    Processed 128 images of 1376\n    Processed 129 images of 1376\n    Processed 130 images of 1376\n    Processed 131 images of 1376\n    Processed 132 images of 1376\n    Processed 133 images of 1376\n    Processed 134 images of 1376\n    Processed 135 images of 1376\n    Processed 136 images of 1376\n    Processed 137 images of 1376\n    Processed 138 images of 1376\n    Processed 139 images of 1376\n    Processed 140 images of 1376\n    Processed 141 images of 1376\n    Processed 142 images of 1376\n    Processed 143 images of 1376\n    Processed 144 images of 1376\n    Processed 145 images of 1376\n    Processed 146 images of 1376\n    Processed 147 images of 1376\n    Processed 148 images of 1376\n    Processed 149 images of 1376\n    Processed 150 images of 1376\n    Processed 151 images of 1376\n    Processed 152 images of 1376\n    Processed 153 images of 1376\n    Processed 154 images of 1376\n    Processed 155 images of 1376\n    Processed 156 images of 1376\n    Processed 157 images of 1376\n    Processed 158 images of 1376\n    Processed 159 images of 1376\n    Processed 160 images of 1376\n    Processed 161 images of 1376\n    Processed 162 images of 1376\n    Processed 163 images of 1376\n    Processed 164 images of 1376\n    Processed 165 images of 1376\n    Processed 166 images of 1376\n    Processed 167 images of 1376\n    Processed 168 images of 1376\n    Processed 169 images of 1376\n    Processed 170 images of 1376\n    Processed 171 images of 1376\n    Processed 172 images of 1376\n    Processed 173 images of 1376\n    Processed 174 images of 1376\n    Processed 175 images of 1376\n    Processed 176 images of 1376\n    Processed 177 images of 1376\n    Processed 178 images of 1376\n    Processed 179 images of 1376\n    Processed 180 images of 1376\n    Processed 181 images of 1376\n    Processed 182 images of 1376\n    Processed 183 images of 1376\n    Processed 184 images of 1376\n    Processed 185 images of 1376\n    Processed 186 images of 1376\n    Processed 187 images of 1376\n    Processed 188 images of 1376\n    Processed 189 images of 1376\n    Processed 190 images of 1376\n    Processed 191 images of 1376\n    Processed 192 images of 1376\n    Processed 193 images of 1376\n    Processed 194 images of 1376\n    Processed 195 images of 1376\n    Processed 196 images of 1376\n    Processed 197 images of 1376\n    Processed 198 images of 1376\n    Processed 199 images of 1376\n    Processed 200 images of 1376\n    Processed 201 images of 1376\n    Processed 202 images of 1376\n    Processed 203 images of 1376\n    Processed 204 images of 1376\n    Processed 205 images of 1376\n    Processed 206 images of 1376\n    Processed 207 images of 1376\n    Processed 208 images of 1376\n    Processed 209 images of 1376\n    Processed 210 images of 1376\n    Processed 211 images of 1376\n    Processed 212 images of 1376\n    Processed 213 images of 1376\n    Processed 214 images of 1376\n    Processed 215 images of 1376\n    Processed 216 images of 1376\n    Processed 217 images of 1376\n    Processed 218 images of 1376\n    Processed 219 images of 1376\n    Processed 220 images of 1376\n    Processed 221 images of 1376\n    Processed 222 images of 1376\n    Processed 223 images of 1376\n    Processed 224 images of 1376\n    Processed 225 images of 1376\n    Processed 226 images of 1376\n    Processed 227 images of 1376\n    Processed 228 images of 1376\n    Processed 229 images of 1376\n    Processed 230 images of 1376\n    Processed 231 images of 1376\n    Processed 232 images of 1376\n    Processed 233 images of 1376\n    Processed 234 images of 1376\n    Processed 235 images of 1376\n    Processed 236 images of 1376\n    Processed 237 images of 1376\n    Processed 238 images of 1376\n    Processed 239 images of 1376\n    Processed 240 images of 1376\n    Processed 241 images of 1376\n    Processed 242 images of 1376\n    Processed 243 images of 1376\n    Processed 244 images of 1376\n    Processed 245 images of 1376\n    Processed 246 images of 1376\n    Processed 247 images of 1376\n    Processed 248 images of 1376\n    Processed 249 images of 1376\n    Processed 250 images of 1376\n    Processed 251 images of 1376\n    Processed 252 images of 1376\n    Processed 253 images of 1376\n    Processed 254 images of 1376\n    Processed 255 images of 1376\n    Processed 256 images of 1376\n    Processed 257 images of 1376\n    Processed 258 images of 1376\n    Processed 259 images of 1376\n    Processed 260 images of 1376\n    Processed 261 images of 1376\n    Processed 262 images of 1376\n    Processed 263 images of 1376\n    Processed 264 images of 1376\n    Processed 265 images of 1376\n    Processed 266 images of 1376\n    Processed 267 images of 1376\n    Processed 268 images of 1376\n    Processed 269 images of 1376\n    Processed 270 images of 1376\n    Processed 271 images of 1376\n    Processed 272 images of 1376\n    Processed 273 images of 1376\n    Processed 274 images of 1376\n    Processed 275 images of 1376\n    Processed 276 images of 1376\n    Processed 277 images of 1376\n    Processed 278 images of 1376\n    Processed 279 images of 1376\n    Processed 280 images of 1376\n    Processed 281 images of 1376\n    Processed 282 images of 1376\n    Processed 283 images of 1376\n    Processed 284 images of 1376\n    Processed 285 images of 1376\n    Processed 286 images of 1376\n    Processed 287 images of 1376\n    Processed 288 images of 1376\n    Processed 289 images of 1376\n    Processed 290 images of 1376\n    Processed 291 images of 1376\n    Processed 292 images of 1376\n    Processed 293 images of 1376\n    Processed 294 images of 1376\n    Processed 295 images of 1376\n    Processed 296 images of 1376\n    Processed 297 images of 1376\n    Processed 298 images of 1376\n    Processed 299 images of 1376\n    Processed 300 images of 1376\n    Processed 301 images of 1376\n    Processed 302 images of 1376\n    Processed 303 images of 1376\n    Processed 304 images of 1376\n    Processed 305 images of 1376\n    Processed 306 images of 1376\n    Processed 307 images of 1376\n    Processed 308 images of 1376\n    Processed 309 images of 1376\n    Processed 310 images of 1376\n    Processed 311 images of 1376\n    Processed 312 images of 1376\n    Processed 313 images of 1376\n    Processed 314 images of 1376\n    Processed 315 images of 1376\n    Processed 316 images of 1376\n    Processed 317 images of 1376\n    Processed 318 images of 1376\n    Processed 319 images of 1376\n    Processed 320 images of 1376\n    Processed 321 images of 1376\n    Processed 322 images of 1376\n    Processed 323 images of 1376\n    Processed 324 images of 1376\n    Processed 325 images of 1376\n    Processed 326 images of 1376\n    Processed 327 images of 1376\n    Processed 328 images of 1376\n    Processed 329 images of 1376\n    Processed 330 images of 1376\n    Processed 331 images of 1376\n    Processed 332 images of 1376\n    Processed 333 images of 1376\n    Processed 334 images of 1376\n    Processed 335 images of 1376\n    Processed 336 images of 1376\n    Processed 337 images of 1376\n    Processed 338 images of 1376\n    Processed 339 images of 1376\n    Processed 340 images of 1376\n    Processed 341 images of 1376\n    Processed 342 images of 1376\n    Processed 343 images of 1376\n    Processed 344 images of 1376\n    Processed 345 images of 1376\n    Processed 346 images of 1376\n    Processed 347 images of 1376\n    Processed 348 images of 1376\n    Processed 349 images of 1376\n    Processed 350 images of 1376\n    Processed 351 images of 1376\n    Processed 352 images of 1376\n    Processed 353 images of 1376\n    Processed 354 images of 1376\n    Processed 355 images of 1376\n    Processed 356 images of 1376\n    Processed 357 images of 1376\n    Processed 358 images of 1376\n    Processed 359 images of 1376\n    Processed 360 images of 1376\n    Processed 361 images of 1376\n    Processed 362 images of 1376\n    Processed 363 images of 1376\n    Processed 364 images of 1376\n    Processed 365 images of 1376\n    Processed 366 images of 1376\n    Processed 367 images of 1376\n    Processed 368 images of 1376\n    Processed 369 images of 1376\n    Processed 370 images of 1376\n    Processed 371 images of 1376\n    Processed 372 images of 1376\n    Processed 373 images of 1376\n    Processed 374 images of 1376\n    Processed 375 images of 1376\n    Processed 376 images of 1376\n    Processed 377 images of 1376\n    Processed 378 images of 1376\n    Processed 379 images of 1376\n    Processed 380 images of 1376\n    Processed 381 images of 1376\n    Processed 382 images of 1376\n    Processed 383 images of 1376\n    Processed 384 images of 1376\n    Processed 385 images of 1376\n    Processed 386 images of 1376\n    Processed 387 images of 1376\n    Processed 388 images of 1376\n    Processed 389 images of 1376\n    Processed 390 images of 1376\n    Processed 391 images of 1376\n    Processed 392 images of 1376\n    Processed 393 images of 1376\n    Processed 394 images of 1376\n    Processed 395 images of 1376\n    Processed 396 images of 1376\n    Processed 397 images of 1376\n    Processed 398 images of 1376\n    Processed 399 images of 1376\n    Processed 400 images of 1376\n    Processed 401 images of 1376\n    Processed 402 images of 1376\n    Processed 403 images of 1376\n    Processed 404 images of 1376\n    Processed 405 images of 1376\n    Processed 406 images of 1376\n    Processed 407 images of 1376\n    Processed 408 images of 1376\n    Processed 409 images of 1376\n    Processed 410 images of 1376\n    Processed 411 images of 1376\n    Processed 412 images of 1376\n    Processed 413 images of 1376\n    Processed 414 images of 1376\n    Processed 415 images of 1376\n    Processed 416 images of 1376\n    Processed 417 images of 1376\n    Processed 418 images of 1376\n    Processed 419 images of 1376\n    Processed 420 images of 1376\n    Processed 421 images of 1376\n    Processed 422 images of 1376\n    Processed 423 images of 1376\n    Processed 424 images of 1376\n    Processed 425 images of 1376\n    Processed 426 images of 1376\n    Processed 427 images of 1376\n    Processed 428 images of 1376\n    Processed 429 images of 1376\n    Processed 430 images of 1376\n    Processed 431 images of 1376\n    Processed 432 images of 1376\n    Processed 433 images of 1376\n    Processed 434 images of 1376\n    Processed 435 images of 1376\n    Processed 436 images of 1376\n    Processed 437 images of 1376\n    Processed 438 images of 1376\n    Processed 439 images of 1376\n    Processed 440 images of 1376\n    Processed 441 images of 1376\n    Processed 442 images of 1376\n    Processed 443 images of 1376\n    Processed 444 images of 1376\n    Processed 445 images of 1376\n    Processed 446 images of 1376\n    Processed 447 images of 1376\n    Processed 448 images of 1376\n    Processed 449 images of 1376\n    Processed 450 images of 1376\n    Processed 451 images of 1376\n    Processed 452 images of 1376\n    Processed 453 images of 1376\n    Processed 454 images of 1376\n    Processed 455 images of 1376\n    Processed 456 images of 1376\n    Processed 457 images of 1376\n    Processed 458 images of 1376\n    Processed 459 images of 1376\n    Processed 460 images of 1376\n    Processed 461 images of 1376\n    Processed 462 images of 1376\n    Processed 463 images of 1376\n    Processed 464 images of 1376\n    Processed 465 images of 1376\n    Processed 466 images of 1376\n    Processed 467 images of 1376\n    Processed 468 images of 1376\n    Processed 469 images of 1376\n    Processed 470 images of 1376\n    Processed 471 images of 1376\n    Processed 472 images of 1376\n    Processed 473 images of 1376\n    Processed 474 images of 1376\n    Processed 475 images of 1376\n    Processed 476 images of 1376\n    Processed 477 images of 1376\n    Processed 478 images of 1376\n    Processed 479 images of 1376\n    Processed 480 images of 1376\n    Processed 481 images of 1376\n    Processed 482 images of 1376\n    Processed 483 images of 1376\n    Processed 484 images of 1376\n    Processed 485 images of 1376\n    Processed 486 images of 1376\n    Processed 487 images of 1376\n    Processed 488 images of 1376\n    Processed 489 images of 1376\n    Processed 490 images of 1376\n    Processed 491 images of 1376\n    Processed 492 images of 1376\n    Processed 493 images of 1376\n    Processed 494 images of 1376\n    Processed 495 images of 1376\n    Processed 496 images of 1376\n    Processed 497 images of 1376\n    Processed 498 images of 1376\n    Processed 499 images of 1376\n    Processed 500 images of 1376\n    Processed 501 images of 1376\n    Processed 502 images of 1376\n    Processed 503 images of 1376\n    Processed 504 images of 1376\n    Processed 505 images of 1376\n    Processed 506 images of 1376\n    Processed 507 images of 1376\n    Processed 508 images of 1376\n    Processed 509 images of 1376\n    Processed 510 images of 1376\n    Processed 511 images of 1376\n    Processed 512 images of 1376\n    Processed 513 images of 1376\n    Processed 514 images of 1376\n    Processed 515 images of 1376\n    Processed 516 images of 1376\n    Processed 517 images of 1376\n    Processed 518 images of 1376\n    Processed 519 images of 1376\n    Processed 520 images of 1376\n    Processed 521 images of 1376\n    Processed 522 images of 1376\n    Processed 523 images of 1376\n    Processed 524 images of 1376\n    Processed 525 images of 1376\n    Processed 526 images of 1376\n    Processed 527 images of 1376\n    Processed 528 images of 1376\n    Processed 529 images of 1376\n    Processed 530 images of 1376\n    Processed 531 images of 1376\n    Processed 532 images of 1376\n    Processed 533 images of 1376\n    Processed 534 images of 1376\n    Processed 535 images of 1376\n    Processed 536 images of 1376\n    Processed 537 images of 1376\n    Processed 538 images of 1376\n    Processed 539 images of 1376\n    Processed 540 images of 1376\n    Processed 541 images of 1376\n    Processed 542 images of 1376\n    Processed 543 images of 1376\n    Processed 544 images of 1376\n    Processed 545 images of 1376\n    Processed 546 images of 1376\n    Processed 547 images of 1376\n    Processed 548 images of 1376\n    Processed 549 images of 1376\n    Processed 550 images of 1376\n    Processed 551 images of 1376\n    Processed 552 images of 1376\n    Processed 553 images of 1376\n    Processed 554 images of 1376\n    Processed 555 images of 1376\n    Processed 556 images of 1376\n    Processed 557 images of 1376\n    Processed 558 images of 1376\n    Processed 559 images of 1376\n    Processed 560 images of 1376\n    Processed 561 images of 1376\n    Processed 562 images of 1376\n    Processed 563 images of 1376\n    Processed 564 images of 1376\n    Processed 565 images of 1376\n    Processed 566 images of 1376\n    Processed 567 images of 1376\n    Processed 568 images of 1376\n    Processed 569 images of 1376\n    Processed 570 images of 1376\n    Processed 571 images of 1376\n    Processed 572 images of 1376\n    Processed 573 images of 1376\n    Processed 574 images of 1376\n    Processed 575 images of 1376\n    Processed 576 images of 1376\n    Processed 577 images of 1376\n    Processed 578 images of 1376\n    Processed 579 images of 1376\n    Processed 580 images of 1376\n    Processed 581 images of 1376\n    Processed 582 images of 1376\n    Processed 583 images of 1376\n    Processed 584 images of 1376\n    Processed 585 images of 1376\n    Processed 586 images of 1376\n    Processed 587 images of 1376\n    Processed 588 images of 1376\n    Processed 589 images of 1376\n    Processed 590 images of 1376\n    Processed 591 images of 1376\n    Processed 592 images of 1376\n    Processed 593 images of 1376\n    Processed 594 images of 1376\n    Processed 595 images of 1376\n    Processed 596 images of 1376\n    Processed 597 images of 1376\n    Processed 598 images of 1376\n    Processed 599 images of 1376\n    Processed 600 images of 1376\n    Processed 601 images of 1376\n    Processed 602 images of 1376\n    Processed 603 images of 1376\n    Processed 604 images of 1376\n    Processed 605 images of 1376\n    Processed 606 images of 1376\n    Processed 607 images of 1376\n    Processed 608 images of 1376\n    Processed 609 images of 1376\n    Processed 610 images of 1376\n    Processed 611 images of 1376\n    Processed 612 images of 1376\n    Processed 613 images of 1376\n    Processed 614 images of 1376\n    Processed 615 images of 1376\n    Processed 616 images of 1376\n    Processed 617 images of 1376\n    Processed 618 images of 1376\n    Processed 619 images of 1376\n    Processed 620 images of 1376\n    Processed 621 images of 1376\n    Processed 622 images of 1376\n    Processed 623 images of 1376\n    Processed 624 images of 1376\n    Processed 625 images of 1376\n    Processed 626 images of 1376\n    Processed 627 images of 1376\n    Processed 628 images of 1376\n    Processed 629 images of 1376\n    Processed 630 images of 1376\n    Processed 631 images of 1376\n    Processed 632 images of 1376\n    Processed 633 images of 1376\n    Processed 634 images of 1376\n    Processed 635 images of 1376\n    Processed 636 images of 1376\n    Processed 637 images of 1376\n    Processed 638 images of 1376\n    Processed 639 images of 1376\n    Processed 640 images of 1376\n    Processed 641 images of 1376\n    Processed 642 images of 1376\n    Processed 643 images of 1376\n    Processed 644 images of 1376\n    Processed 645 images of 1376\n    Processed 646 images of 1376\n    Processed 647 images of 1376\n    Processed 648 images of 1376\n    Processed 649 images of 1376\n    Processed 650 images of 1376\n    Processed 651 images of 1376\n    Processed 652 images of 1376\n    Processed 653 images of 1376\n    Processed 654 images of 1376\n    Processed 655 images of 1376\n    Processed 656 images of 1376\n    Processed 657 images of 1376\n    Processed 658 images of 1376\n    Processed 659 images of 1376\n    Processed 660 images of 1376\n    Processed 661 images of 1376\n    Processed 662 images of 1376\n    Processed 663 images of 1376\n    Processed 664 images of 1376\n    Processed 665 images of 1376\n    Processed 666 images of 1376\n    Processed 667 images of 1376\n    Processed 668 images of 1376\n    Processed 669 images of 1376\n    Processed 670 images of 1376\n    Processed 671 images of 1376\n    Processed 672 images of 1376\n    Processed 673 images of 1376\n    Processed 674 images of 1376\n    Processed 675 images of 1376\n    Processed 676 images of 1376\n    Processed 677 images of 1376\n    Processed 678 images of 1376\n    Processed 679 images of 1376\n    Processed 680 images of 1376\n    Processed 681 images of 1376\n    Processed 682 images of 1376\n    Processed 683 images of 1376\n    Processed 684 images of 1376\n    Processed 685 images of 1376\n    Processed 686 images of 1376\n    Processed 687 images of 1376\n    Processed 688 images of 1376\n    Processed 689 images of 1376\n    Processed 690 images of 1376\n    Processed 691 images of 1376\n    Processed 692 images of 1376\n    Processed 693 images of 1376\n    Processed 694 images of 1376\n    Processed 695 images of 1376\n    Processed 696 images of 1376\n    Processed 697 images of 1376\n    Processed 698 images of 1376\n    Processed 699 images of 1376\n    Processed 700 images of 1376\n    Processed 701 images of 1376\n    Processed 702 images of 1376\n    Processed 703 images of 1376\n    Processed 704 images of 1376\n    Processed 705 images of 1376\n    Processed 706 images of 1376\n    Processed 707 images of 1376\n    Processed 708 images of 1376\n    Processed 709 images of 1376\n    Processed 710 images of 1376\n    Processed 711 images of 1376\n    Processed 712 images of 1376\n    Processed 713 images of 1376\n    Processed 714 images of 1376\n    Processed 715 images of 1376\n    Processed 716 images of 1376\n    Processed 717 images of 1376\n    Processed 718 images of 1376\n    Processed 719 images of 1376\n    Processed 720 images of 1376\n    Processed 721 images of 1376\n    Processed 722 images of 1376\n    Processed 723 images of 1376\n    Processed 724 images of 1376\n    Processed 725 images of 1376\n    Processed 726 images of 1376\n    Processed 727 images of 1376\n    Processed 728 images of 1376\n    Processed 729 images of 1376\n    Processed 730 images of 1376\n    Processed 731 images of 1376\n    Processed 732 images of 1376\n    Processed 733 images of 1376\n    Processed 734 images of 1376\n    Processed 735 images of 1376\n    Processed 736 images of 1376\n    Processed 737 images of 1376\n    Processed 738 images of 1376\n    Processed 739 images of 1376\n    Processed 740 images of 1376\n    Processed 741 images of 1376\n    Processed 742 images of 1376\n    Processed 743 images of 1376\n    Processed 744 images of 1376\n    Processed 745 images of 1376\n    Processed 746 images of 1376\n    Processed 747 images of 1376\n    Processed 748 images of 1376\n    Processed 749 images of 1376\n    Processed 750 images of 1376\n    Processed 751 images of 1376\n    Processed 752 images of 1376\n    Processed 753 images of 1376\n    Processed 754 images of 1376\n    Processed 755 images of 1376\n    Processed 756 images of 1376\n    Processed 757 images of 1376\n    Processed 758 images of 1376\n    Processed 759 images of 1376\n    Processed 760 images of 1376\n    Processed 761 images of 1376\n    Processed 762 images of 1376\n    Processed 763 images of 1376\n    Processed 764 images of 1376\n    Processed 765 images of 1376\n    Processed 766 images of 1376\n    Processed 767 images of 1376\n    Processed 768 images of 1376\n    Processed 769 images of 1376\n    Processed 770 images of 1376\n    Processed 771 images of 1376\n    Processed 772 images of 1376\n    Processed 773 images of 1376\n    Processed 774 images of 1376\n    Processed 775 images of 1376\n    Processed 776 images of 1376\n    Processed 777 images of 1376\n    Processed 778 images of 1376\n    Processed 779 images of 1376\n    Processed 780 images of 1376\n    Processed 781 images of 1376\n    Processed 782 images of 1376\n    Processed 783 images of 1376\n    Processed 784 images of 1376\n    Processed 785 images of 1376\n    Processed 786 images of 1376\n    Processed 787 images of 1376\n    Processed 788 images of 1376\n    Processed 789 images of 1376\n    Processed 790 images of 1376\n    Processed 791 images of 1376\n    Processed 792 images of 1376\n    Processed 793 images of 1376\n    Processed 794 images of 1376\n    Processed 795 images of 1376\n    Processed 796 images of 1376\n    Processed 797 images of 1376\n    Processed 798 images of 1376\n    Processed 799 images of 1376\n    Processed 800 images of 1376\n    Processed 801 images of 1376\n    Processed 802 images of 1376\n    Processed 803 images of 1376\n    Processed 804 images of 1376\n    Processed 805 images of 1376\n    Processed 806 images of 1376\n    Processed 807 images of 1376\n    Processed 808 images of 1376\n    Processed 809 images of 1376\n    Processed 810 images of 1376\n    Processed 811 images of 1376\n    Processed 812 images of 1376\n    Processed 813 images of 1376\n    Processed 814 images of 1376\n    Processed 815 images of 1376\n    Processed 816 images of 1376\n    Processed 817 images of 1376\n    Processed 818 images of 1376\n    Processed 819 images of 1376\n    Processed 820 images of 1376\n    Processed 821 images of 1376\n    Processed 822 images of 1376\n    Processed 823 images of 1376\n    Processed 824 images of 1376\n    Processed 825 images of 1376\n    Processed 826 images of 1376\n    Processed 827 images of 1376\n    Processed 828 images of 1376\n    Processed 829 images of 1376\n    Processed 830 images of 1376\n    Processed 831 images of 1376\n    Processed 832 images of 1376\n    Processed 833 images of 1376\n    Processed 834 images of 1376\n    Processed 835 images of 1376\n    Processed 836 images of 1376\n    Processed 837 images of 1376\n    Processed 838 images of 1376\n    Processed 839 images of 1376\n    Processed 840 images of 1376\n    Processed 841 images of 1376\n    Processed 842 images of 1376\n    Processed 843 images of 1376\n    Processed 844 images of 1376\n    Processed 845 images of 1376\n    Processed 846 images of 1376\n    Processed 847 images of 1376\n    Processed 848 images of 1376\n    Processed 849 images of 1376\n    Processed 850 images of 1376\n    Processed 851 images of 1376\n    Processed 852 images of 1376\n    Processed 853 images of 1376\n    Processed 854 images of 1376\n    Processed 855 images of 1376\n    Processed 856 images of 1376\n    Processed 857 images of 1376\n    Processed 858 images of 1376\n    Processed 859 images of 1376\n    Processed 860 images of 1376\n    Processed 861 images of 1376\n    Processed 862 images of 1376\n    Processed 863 images of 1376\n    Processed 864 images of 1376\n    Processed 865 images of 1376\n    Processed 866 images of 1376\n    Processed 867 images of 1376\n    Processed 868 images of 1376\n    Processed 869 images of 1376\n    Processed 870 images of 1376\n    Processed 871 images of 1376\n    Processed 872 images of 1376\n    Processed 873 images of 1376\n    Processed 874 images of 1376\n    Processed 875 images of 1376\n    Processed 876 images of 1376\n    Processed 877 images of 1376\n    Processed 878 images of 1376\n    Processed 879 images of 1376\n    Processed 880 images of 1376\n    Processed 881 images of 1376\n    Processed 882 images of 1376\n    Processed 883 images of 1376\n    Processed 884 images of 1376\n    Processed 885 images of 1376\n    Processed 886 images of 1376\n    Processed 887 images of 1376\n    Processed 888 images of 1376\n    Processed 889 images of 1376\n    Processed 890 images of 1376\n    Processed 891 images of 1376\n    Processed 892 images of 1376\n    Processed 893 images of 1376\n    Processed 894 images of 1376\n    Processed 895 images of 1376\n    Processed 896 images of 1376\n    Processed 897 images of 1376\n    Processed 898 images of 1376\n    Processed 899 images of 1376\n    Processed 900 images of 1376\n    Processed 901 images of 1376\n    Processed 902 images of 1376\n    Processed 903 images of 1376\n    Processed 904 images of 1376\n    Processed 905 images of 1376\n    Processed 906 images of 1376\n    Processed 907 images of 1376\n    Processed 908 images of 1376\n    Processed 909 images of 1376\n    Processed 910 images of 1376\n    Processed 911 images of 1376\n    Processed 912 images of 1376\n    Processed 913 images of 1376\n    Processed 914 images of 1376\n    Processed 915 images of 1376\n    Processed 916 images of 1376\n    Processed 917 images of 1376\n    Processed 918 images of 1376\n    Processed 919 images of 1376\n    Processed 920 images of 1376\n    Processed 921 images of 1376\n    Processed 922 images of 1376\n    Processed 923 images of 1376\n    Processed 924 images of 1376\n    Processed 925 images of 1376\n    Processed 926 images of 1376\n    Processed 927 images of 1376\n    Processed 928 images of 1376\n    Processed 929 images of 1376\n    Processed 930 images of 1376\n    Processed 931 images of 1376\n    Processed 932 images of 1376\n    Processed 933 images of 1376\n    Processed 934 images of 1376\n    Processed 935 images of 1376\n    Processed 936 images of 1376\n    Processed 937 images of 1376\n    Processed 938 images of 1376\n    Processed 939 images of 1376\n    Processed 940 images of 1376\n    Processed 941 images of 1376\n    Processed 942 images of 1376\n    Processed 943 images of 1376\n    Processed 944 images of 1376\n    Processed 945 images of 1376\n    Processed 946 images of 1376\n    Processed 947 images of 1376\n    Processed 948 images of 1376\n    Processed 949 images of 1376\n    Processed 950 images of 1376\n    Processed 951 images of 1376\n    Processed 952 images of 1376\n    Processed 953 images of 1376\n    Processed 954 images of 1376\n    Processed 955 images of 1376\n    Processed 956 images of 1376\n    Processed 957 images of 1376\n    Processed 958 images of 1376\n    Processed 959 images of 1376\n    Processed 960 images of 1376\n    Processed 961 images of 1376\n    Processed 962 images of 1376\n    Processed 963 images of 1376\n    Processed 964 images of 1376\n    Processed 965 images of 1376\n    Processed 966 images of 1376\n    Processed 967 images of 1376\n    Processed 968 images of 1376\n    Processed 969 images of 1376\n    Processed 970 images of 1376\n    Processed 971 images of 1376\n    Processed 972 images of 1376\n    Processed 973 images of 1376\n    Processed 974 images of 1376\n    Processed 975 images of 1376\n    Processed 976 images of 1376\n    Processed 977 images of 1376\n    Processed 978 images of 1376\n    Processed 979 images of 1376\n    Processed 980 images of 1376\n    Processed 981 images of 1376\n    Processed 982 images of 1376\n    Processed 983 images of 1376\n    Processed 984 images of 1376\n    Processed 985 images of 1376\n    Processed 986 images of 1376\n    Processed 987 images of 1376\n    Processed 988 images of 1376\n    Processed 989 images of 1376\n    Processed 990 images of 1376\n    Processed 991 images of 1376\n    Processed 992 images of 1376\n    Processed 993 images of 1376\n    Processed 994 images of 1376\n    Processed 995 images of 1376\n    Processed 996 images of 1376\n    Processed 997 images of 1376\n    Processed 998 images of 1376\n    Processed 999 images of 1376\n    Processed 1000 images of 1376\n    Processed 1001 images of 1376\n    Processed 1002 images of 1376\n    Processed 1003 images of 1376\n    Processed 1004 images of 1376\n    Processed 1005 images of 1376\n    Processed 1006 images of 1376\n    Processed 1007 images of 1376\n    Processed 1008 images of 1376\n    Processed 1009 images of 1376\n    Processed 1010 images of 1376\n    Processed 1011 images of 1376\n    Processed 1012 images of 1376\n    Processed 1013 images of 1376\n    Processed 1014 images of 1376\n    Processed 1015 images of 1376\n    Processed 1016 images of 1376\n    Processed 1017 images of 1376\n    Processed 1018 images of 1376\n    Processed 1019 images of 1376\n    Processed 1020 images of 1376\n    Processed 1021 images of 1376\n    Processed 1022 images of 1376\n    Processed 1023 images of 1376\n    Processed 1024 images of 1376\n    Processed 1025 images of 1376\n    Processed 1026 images of 1376\n    Processed 1027 images of 1376\n    Processed 1028 images of 1376\n    Processed 1029 images of 1376\n    Processed 1030 images of 1376\n    Processed 1031 images of 1376\n    Processed 1032 images of 1376\n    Processed 1033 images of 1376\n    Processed 1034 images of 1376\n    Processed 1035 images of 1376\n    Processed 1036 images of 1376\n    Processed 1037 images of 1376\n    Processed 1038 images of 1376\n    Processed 1039 images of 1376\n    Processed 1040 images of 1376\n    Processed 1041 images of 1376\n    Processed 1042 images of 1376\n    Processed 1043 images of 1376\n    Processed 1044 images of 1376\n    Processed 1045 images of 1376\n    Processed 1046 images of 1376\n    Processed 1047 images of 1376\n    Processed 1048 images of 1376\n    Processed 1049 images of 1376\n    Processed 1050 images of 1376\n    Processed 1051 images of 1376\n    Processed 1052 images of 1376\n    Processed 1053 images of 1376\n    Processed 1054 images of 1376\n    Processed 1055 images of 1376\n    Processed 1056 images of 1376\n    Processed 1057 images of 1376\n    Processed 1058 images of 1376\n    Processed 1059 images of 1376\n    Processed 1060 images of 1376\n    Processed 1061 images of 1376\n    Processed 1062 images of 1376\n    Processed 1063 images of 1376\n    Processed 1064 images of 1376\n    Processed 1065 images of 1376\n    Processed 1066 images of 1376\n    Processed 1067 images of 1376\n    Processed 1068 images of 1376\n    Processed 1069 images of 1376\n    Processed 1070 images of 1376\n    Processed 1071 images of 1376\n    Processed 1072 images of 1376\n    Processed 1073 images of 1376\n    Processed 1074 images of 1376\n    Processed 1075 images of 1376\n    Processed 1076 images of 1376\n    Processed 1077 images of 1376\n    Processed 1078 images of 1376\n    Processed 1079 images of 1376\n    Processed 1080 images of 1376\n    Processed 1081 images of 1376\n    Processed 1082 images of 1376\n    Processed 1083 images of 1376\n    Processed 1084 images of 1376\n    Processed 1085 images of 1376\n    Processed 1086 images of 1376\n    Processed 1087 images of 1376\n    Processed 1088 images of 1376\n    Processed 1089 images of 1376\n    Processed 1090 images of 1376\n    Processed 1091 images of 1376\n    Processed 1092 images of 1376\n    Processed 1093 images of 1376\n    Processed 1094 images of 1376\n    Processed 1095 images of 1376\n    Processed 1096 images of 1376\n    Processed 1097 images of 1376\n    Processed 1098 images of 1376\n    Processed 1099 images of 1376\n    Processed 1100 images of 1376\n    Processed 1101 images of 1376\n    Processed 1102 images of 1376\n    Processed 1103 images of 1376\n    Processed 1104 images of 1376\n    Processed 1105 images of 1376\n    Processed 1106 images of 1376\n    Processed 1107 images of 1376\n    Processed 1108 images of 1376\n    Processed 1109 images of 1376\n    Processed 1110 images of 1376\n    Processed 1111 images of 1376\n    Processed 1112 images of 1376\n    Processed 1113 images of 1376\n    Processed 1114 images of 1376\n    Processed 1115 images of 1376\n    Processed 1116 images of 1376\n    Processed 1117 images of 1376\n    Processed 1118 images of 1376\n    Processed 1119 images of 1376\n    Processed 1120 images of 1376\n    Processed 1121 images of 1376\n    Processed 1122 images of 1376\n    Processed 1123 images of 1376\n    Processed 1124 images of 1376\n    Processed 1125 images of 1376\n    Processed 1126 images of 1376\n    Processed 1127 images of 1376\n    Processed 1128 images of 1376\n    Processed 1129 images of 1376\n    Processed 1130 images of 1376\n    Processed 1131 images of 1376\n    Processed 1132 images of 1376\n    Processed 1133 images of 1376\n    Processed 1134 images of 1376\n    Processed 1135 images of 1376\n    Processed 1136 images of 1376\n    Processed 1137 images of 1376\n    Processed 1138 images of 1376\n    Processed 1139 images of 1376\n    Processed 1140 images of 1376\n    Processed 1141 images of 1376\n    Processed 1142 images of 1376\n    Processed 1143 images of 1376\n    Processed 1144 images of 1376\n    Processed 1145 images of 1376\n    Processed 1146 images of 1376\n    Processed 1147 images of 1376\n    Processed 1148 images of 1376\n    Processed 1149 images of 1376\n    Processed 1150 images of 1376\n    Processed 1151 images of 1376\n    Processed 1152 images of 1376\n    Processed 1153 images of 1376\n    Processed 1154 images of 1376\n    Processed 1155 images of 1376\n    Processed 1156 images of 1376\n    Processed 1157 images of 1376\n    Processed 1158 images of 1376\n    Processed 1159 images of 1376\n    Processed 1160 images of 1376\n    Processed 1161 images of 1376\n    Processed 1162 images of 1376\n    Processed 1163 images of 1376\n    Processed 1164 images of 1376\n    Processed 1165 images of 1376\n    Processed 1166 images of 1376\n    Processed 1167 images of 1376\n    Processed 1168 images of 1376\n    Processed 1169 images of 1376\n    Processed 1170 images of 1376\n    Processed 1171 images of 1376\n    Processed 1172 images of 1376\n    Processed 1173 images of 1376\n    Processed 1174 images of 1376\n    Processed 1175 images of 1376\n    Processed 1176 images of 1376\n    Processed 1177 images of 1376\n    Processed 1178 images of 1376\n    Processed 1179 images of 1376\n    Processed 1180 images of 1376\n    Processed 1181 images of 1376\n    Processed 1182 images of 1376\n    Processed 1183 images of 1376\n    Processed 1184 images of 1376\n    Processed 1185 images of 1376\n    Processed 1186 images of 1376\n    Processed 1187 images of 1376\n    Processed 1188 images of 1376\n    Processed 1189 images of 1376\n    Processed 1190 images of 1376\n    Processed 1191 images of 1376\n    Processed 1192 images of 1376\n    Processed 1193 images of 1376\n    Processed 1194 images of 1376\n    Processed 1195 images of 1376\n    Processed 1196 images of 1376\n    Processed 1197 images of 1376\n    Processed 1198 images of 1376\n    Processed 1199 images of 1376\n    Processed 1200 images of 1376\n    Processed 1201 images of 1376\n    Processed 1202 images of 1376\n    Processed 1203 images of 1376\n    Processed 1204 images of 1376\n    Processed 1205 images of 1376\n    Processed 1206 images of 1376\n    Processed 1207 images of 1376\n    Processed 1208 images of 1376\n    Processed 1209 images of 1376\n    Processed 1210 images of 1376\n    Processed 1211 images of 1376\n    Processed 1212 images of 1376\n    Processed 1213 images of 1376\n    Processed 1214 images of 1376\n    Processed 1215 images of 1376\n    Processed 1216 images of 1376\n    Processed 1217 images of 1376\n    Processed 1218 images of 1376\n    Processed 1219 images of 1376\n    Processed 1220 images of 1376\n    Processed 1221 images of 1376\n    Processed 1222 images of 1376\n    Processed 1223 images of 1376\n    Processed 1224 images of 1376\n    Processed 1225 images of 1376\n    Processed 1226 images of 1376\n    Processed 1227 images of 1376\n    Processed 1228 images of 1376\n    Processed 1229 images of 1376\n    Processed 1230 images of 1376\n    Processed 1231 images of 1376\n    Processed 1232 images of 1376\n    Processed 1233 images of 1376\n    Processed 1234 images of 1376\n    Processed 1235 images of 1376\n    Processed 1236 images of 1376\n    Processed 1237 images of 1376\n    Processed 1238 images of 1376\n    Processed 1239 images of 1376\n    Processed 1240 images of 1376\n    Processed 1241 images of 1376\n    Processed 1242 images of 1376\n    Processed 1243 images of 1376\n    Processed 1244 images of 1376\n    Processed 1245 images of 1376\n    Processed 1246 images of 1376\n    Processed 1247 images of 1376\n    Processed 1248 images of 1376\n    Processed 1249 images of 1376\n    Processed 1250 images of 1376\n    Processed 1251 images of 1376\n    Processed 1252 images of 1376\n    Processed 1253 images of 1376\n    Processed 1254 images of 1376\n    Processed 1255 images of 1376\n    Processed 1256 images of 1376\n    Processed 1257 images of 1376\n    Processed 1258 images of 1376\n    Processed 1259 images of 1376\n    Processed 1260 images of 1376\n    Processed 1261 images of 1376\n    Processed 1262 images of 1376\n    Processed 1263 images of 1376\n    Processed 1264 images of 1376\n    Processed 1265 images of 1376\n    Processed 1266 images of 1376\n    Processed 1267 images of 1376\n    Processed 1268 images of 1376\n    Processed 1269 images of 1376\n    Processed 1270 images of 1376\n    Processed 1271 images of 1376\n    Processed 1272 images of 1376\n    Processed 1273 images of 1376\n    Processed 1274 images of 1376\n    Processed 1275 images of 1376\n    Processed 1276 images of 1376\n    Processed 1277 images of 1376\n    Processed 1278 images of 1376\n    Processed 1279 images of 1376\n    Processed 1280 images of 1376\n    Processed 1281 images of 1376\n    Processed 1282 images of 1376\n    Processed 1283 images of 1376\n    Processed 1284 images of 1376\n    Processed 1285 images of 1376\n    Processed 1286 images of 1376\n    Processed 1287 images of 1376\n    Processed 1288 images of 1376\n    Processed 1289 images of 1376\n    Processed 1290 images of 1376\n    Processed 1291 images of 1376\n    Processed 1292 images of 1376\n    Processed 1293 images of 1376\n    Processed 1294 images of 1376\n    Processed 1295 images of 1376\n    Processed 1296 images of 1376\n    Processed 1297 images of 1376\n    Processed 1298 images of 1376\n    Processed 1299 images of 1376\n    Processed 1300 images of 1376\n    Processed 1301 images of 1376\n    Processed 1302 images of 1376\n    Processed 1303 images of 1376\n    Processed 1304 images of 1376\n    Processed 1305 images of 1376\n    Processed 1306 images of 1376\n    Processed 1307 images of 1376\n    Processed 1308 images of 1376\n    Processed 1309 images of 1376\n    Processed 1310 images of 1376\n    Processed 1311 images of 1376\n    Processed 1312 images of 1376\n    Processed 1313 images of 1376\n    Processed 1314 images of 1376\n    Processed 1315 images of 1376\n    Processed 1316 images of 1376\n    Processed 1317 images of 1376\n    Processed 1318 images of 1376\n    Processed 1319 images of 1376\n    Processed 1320 images of 1376\n    Processed 1321 images of 1376\n    Processed 1322 images of 1376\n    Processed 1323 images of 1376\n    Processed 1324 images of 1376\n    Processed 1325 images of 1376\n    Processed 1326 images of 1376\n    Processed 1327 images of 1376\n    Processed 1328 images of 1376\n    Processed 1329 images of 1376\n    Processed 1330 images of 1376\n    Processed 1331 images of 1376\n    Processed 1332 images of 1376\n    Processed 1333 images of 1376\n    Processed 1334 images of 1376\n    Processed 1335 images of 1376\n    Processed 1336 images of 1376\n    Processed 1337 images of 1376\n    Processed 1338 images of 1376\n    Processed 1339 images of 1376\n    Processed 1340 images of 1376\n    Processed 1341 images of 1376\n    Processed 1342 images of 1376\n    Processed 1343 images of 1376\n    Processed 1344 images of 1376\n    Processed 1345 images of 1376\n    Processed 1346 images of 1376\n    Processed 1347 images of 1376\n    Processed 1348 images of 1376\n    Processed 1349 images of 1376\n    Processed 1350 images of 1376\n    Processed 1351 images of 1376\n    Processed 1352 images of 1376\n    Processed 1353 images of 1376\n    Processed 1354 images of 1376\n    Processed 1355 images of 1376\n    Processed 1356 images of 1376\n    Processed 1357 images of 1376\n    Processed 1358 images of 1376\n    Processed 1359 images of 1376\n    Processed 1360 images of 1376\n    Processed 1361 images of 1376\n    Processed 1362 images of 1376\n    Processed 1363 images of 1376\n    Processed 1364 images of 1376\n    Processed 1365 images of 1376\n    Processed 1366 images of 1376\n    Processed 1367 images of 1376\n    Processed 1368 images of 1376\n    Processed 1369 images of 1376\n    Processed 1370 images of 1376\n    Processed 1371 images of 1376\n    Processed 1372 images of 1376\n    Processed 1373 images of 1376\n    Processed 1374 images of 1376\n    Processed 1375 images of 1376\n    Processed 1376 images of 1376\n\n\n\n```\ndata = np.array(data)\nlabels = np.array(labels)\n```\n\n\n```\ndata.shape\n```\n\n\n\n\n    (1376, 224, 224, 3)\n\n\n\n\n```\nlb = LabelBinarizer()\nlabels = lb.fit_transform(labels)\nlabels = to_categorical(labels)\n```\n\n\n```\n(X_train, X_test, y_train, y_test) = train_test_split(data, labels, train_size=0.8, stratify=labels, random_state=42)\n\naug = ImageDataGenerator(\n    rotation_range=20,\n    zoom_range=0.15,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    shear_range=0.15,\n    horizontal_flip=True,\n    fill_mode=\"nearest\"\n)\n\n```\n\n##Build model\n\n\n```\ninput_shape = (224, 224, 3)\n```\n\n\n```\nmodel = Sequential()\nmodel.add(InputLayer(input_shape=input_shape))\nmodel.add(MobileNetV2(weights='imagenet', include_top=False))\nmodel.add(AveragePooling2D(pool_size=(7, 7)))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\nmodel.add(Dense(2, activation='softmax'))\n```\n\n    WARNING:tensorflow:`input_shape` is undefined or non-square, or `rows` is not in [96, 128, 160, 192, 224]. Weights for input shape (224, 224) will be loaded as the default.\n    Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/mobilenet_v2/mobilenet_v2_weights_tf_dim_ordering_tf_kernels_1.0_224_no_top.h5\n    9412608/9406464 [==============================] - 0s 0us/step\n\n\n\n```\n# x = MobileNetV2(weights='imagenet', include_top=False)\n# x.pop()\n# x.summary()\n```\n\n\n```\nLR = 1e-4\nBS = 32\nepochs = 20\nopt = Adam(lr=LR, decay=LR / epochs)\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=opt,\n\tmetrics=[\"accuracy\"])\n\n```\n\n\n```\nH = model.fit(\n    aug.flow(X_train, y_train, batch_size=BS),\n    steps_per_epoch=len(X_train)//BS,\n    validation_data=(X_test, y_test),\n    validation_steps=len(X_test)//BS,\n    epochs=epochs\n)\n```\n\n    Epoch 1/20\n    34/34 [==============================] - 19s 561ms/step - loss: 0.3328 - accuracy: 0.8614 - val_loss: 0.0414 - val_accuracy: 0.9891\n    Epoch 2/20\n    34/34 [==============================] - 17s 498ms/step - loss: 0.0638 - accuracy: 0.9775 - val_loss: 0.0248 - val_accuracy: 0.9928\n    Epoch 3/20\n    34/34 [==============================] - 17s 496ms/step - loss: 0.0352 - accuracy: 0.9897 - val_loss: 0.0221 - val_accuracy: 0.9928\n    Epoch 4/20\n    34/34 [==============================] - 17s 498ms/step - loss: 0.0207 - accuracy: 0.9944 - val_loss: 0.0182 - val_accuracy: 0.9928\n    Epoch 5/20\n    34/34 [==============================] - 17s 498ms/step - loss: 0.0218 - accuracy: 0.9925 - val_loss: 0.0176 - val_accuracy: 0.9928\n    Epoch 6/20\n    34/34 [==============================] - 17s 496ms/step - loss: 0.0150 - accuracy: 0.9953 - val_loss: 0.0152 - val_accuracy: 0.9928\n    Epoch 7/20\n    34/34 [==============================] - 17s 494ms/step - loss: 0.0157 - accuracy: 0.9953 - val_loss: 0.0108 - val_accuracy: 0.9928\n    Epoch 8/20\n    34/34 [==============================] - 17s 490ms/step - loss: 0.0136 - accuracy: 0.9944 - val_loss: 0.0113 - val_accuracy: 0.9964\n    Epoch 9/20\n    34/34 [==============================] - 17s 492ms/step - loss: 0.0047 - accuracy: 0.9991 - val_loss: 0.0104 - val_accuracy: 0.9964\n    Epoch 10/20\n    34/34 [==============================] - 17s 492ms/step - loss: 0.0092 - accuracy: 0.9972 - val_loss: 0.0111 - val_accuracy: 0.9964\n    Epoch 11/20\n    34/34 [==============================] - 17s 490ms/step - loss: 0.0057 - accuracy: 0.9991 - val_loss: 0.0076 - val_accuracy: 0.9964\n    Epoch 12/20\n    34/34 [==============================] - 17s 491ms/step - loss: 0.0055 - accuracy: 0.9981 - val_loss: 0.0055 - val_accuracy: 0.9964\n    Epoch 13/20\n    34/34 [==============================] - 17s 489ms/step - loss: 0.0050 - accuracy: 0.9991 - val_loss: 0.0080 - val_accuracy: 0.9964\n    Epoch 14/20\n    34/34 [==============================] - 17s 491ms/step - loss: 0.0036 - accuracy: 0.9991 - val_loss: 0.0092 - val_accuracy: 0.9964\n    Epoch 15/20\n    34/34 [==============================] - 17s 489ms/step - loss: 0.0065 - accuracy: 0.9972 - val_loss: 0.0083 - val_accuracy: 0.9964\n    Epoch 16/20\n    34/34 [==============================] - 17s 492ms/step - loss: 0.0026 - accuracy: 0.9991 - val_loss: 0.0057 - val_accuracy: 0.9964\n    Epoch 17/20\n    34/34 [==============================] - 17s 491ms/step - loss: 0.0035 - accuracy: 0.9991 - val_loss: 0.0046 - val_accuracy: 0.9964\n    Epoch 18/20\n    34/34 [==============================] - 17s 493ms/step - loss: 0.0034 - accuracy: 0.9991 - val_loss: 0.0040 - val_accuracy: 0.9964\n    Epoch 19/20\n    34/34 [==============================] - 17s 495ms/step - loss: 0.0040 - accuracy: 0.9991 - val_loss: 0.0046 - val_accuracy: 0.9964\n    Epoch 20/20\n    34/34 [==============================] - 17s 489ms/step - loss: 0.0030 - accuracy: 0.9991 - val_loss: 0.0046 - val_accuracy: 0.9964\n\n\n\n```\nmodel.evaluate(X_test, y_test)\n```\n\n    9/9 [==============================] - 1s 114ms/step - loss: 0.0046 - accuracy: 0.9964\n\n\n\n\n\n    [0.004589356016367674, 0.9963768124580383]\n\n\n\n\n```\ny_pred = model.predict(X_test)\ny_pred = np.argmax(y_pred, axis=1)\nprint(classification_report(y_pred=y_pred, y_true=np.argmax(y_test, axis=1)))\n```\n\n                  precision    recall  f1-score   support\n    \n               0       0.99      1.00      1.00       138\n               1       1.00      0.99      1.00       138\n    \n        accuracy                           1.00       276\n       macro avg       1.00      1.00      1.00       276\n    weighted avg       1.00      1.00      1.00       276\n    \n\n\n\n```\nmodel.save(\"mask_detection.h5\")\n```\n\n##Testing model on custom inputs\n\n\n```\n!wget https://i.pinimg.com/474x/0d/de/de/0ddedeaf55601af87eb5b62f377103c7--mobile-wallpaper-the-big-bang-theory-wallpaper.jpg\n```\n\n    --2020-07-29 09:13:40--  https://i.pinimg.com/474x/0d/de/de/0ddedeaf55601af87eb5b62f377103c7--mobile-wallpaper-the-big-bang-theory-wallpaper.jpg\n    Resolving i.pinimg.com (i.pinimg.com)... 151.101.76.84, 2600:1417:76:499::1931, 2600:1417:76:489::1931, ...\n    Connecting to i.pinimg.com (i.pinimg.com)|151.101.76.84|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 55694 (54K) [image/jpeg]\n    Saving to: \u20180ddedeaf55601af87eb5b62f377103c7--mobile-wallpaper-the-big-bang-theory-wallpaper.jpg\u2019\n    \n    0ddedeaf55601af87eb 100%[===================>]  54.39K  --.-KB/s    in 0.03s   \n    \n    2020-07-29 09:13:40 (1.99 MB/s) - \u20180ddedeaf55601af87eb5b62f377103c7--mobile-wallpaper-the-big-bang-theory-wallpaper.jpg\u2019 saved [55694/55694]\n    \n\n\n\n```\nfrom google.colab.patches import cv2_imshow\nimage = load_img('/content/0ddedeaf55601af87eb5b62f377103c7--mobile-wallpaper-the-big-bang-theory-wallpaper.jpg', target_size=(224, 224))\nimage = img_to_array(image)\ncv2_imshow(image)\nimage = preprocess_input(image)\nimage = np.expand_dims(image, axis=0)\nx = model.predict(image)\nprint(lb.classes_[np.argmax(x, axis=1)], \": \", x[0][np.argmax(x, axis=1)])\n```\n\n\n```\n!wget https://www.onemedical.com/media/images/woman-wearing-mask.width-1440.jpg\n```\n\n    --2020-07-29 09:13:51--  https://www.onemedical.com/media/images/woman-wearing-mask.width-1440.jpg\n    Resolving www.onemedical.com (www.onemedical.com)... 13.224.153.128, 13.224.153.42, 13.224.153.60, ...\n    Connecting to www.onemedical.com (www.onemedical.com)|13.224.153.128|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 123938 (121K) [image/jpeg]\n    Saving to: \u2018woman-wearing-mask.width-1440.jpg\u2019\n    \n    woman-wearing-mask. 100%[===================>] 121.03K  --.-KB/s    in 0.03s   \n    \n    2020-07-29 09:13:51 (4.59 MB/s) - \u2018woman-wearing-mask.width-1440.jpg\u2019 saved [123938/123938]\n    \n\n\n\n```\nimage = load_img('woman-wearing-mask.width-1440.jpg', target_size=(224, 224))\nimage = img_to_array(image)\ncv2_imshow(image)\nimage = preprocess_input(image)\nimage = np.expand_dims(image, axis=0)\nx = model.predict(image)\nprint(lb.classes_[np.argmax(x, axis=1)], \": \", x[0][np.argmax(x, axis=1)])\n```\n\n\n```\n!wget https://www.cidrap.umn.edu/sites/default/files/public/styles/detail/public/media/article/woman_wearing_mask_in_airport.jpg?itok=qykld-R-\n```\n\n    --2020-07-29 09:14:00--  https://www.cidrap.umn.edu/sites/default/files/public/styles/detail/public/media/article/woman_wearing_mask_in_airport.jpg?itok=qykld-R-\n    Resolving www.cidrap.umn.edu (www.cidrap.umn.edu)... 199.167.77.60\n    Connecting to www.cidrap.umn.edu (www.cidrap.umn.edu)|199.167.77.60|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 13558 (13K) [image/jpeg]\n    Saving to: \u2018woman_wearing_mask_in_airport.jpg?itok=qykld-R-\u2019\n    \n    woman_wearing_mask_ 100%[===================>]  13.24K  --.-KB/s    in 0s      \n    \n    2020-07-29 09:14:01 (249 MB/s) - \u2018woman_wearing_mask_in_airport.jpg?itok=qykld-R-\u2019 saved [13558/13558]\n    \n\n\n\n```\nimage = load_img('/content/woman_wearing_mask_in_airport.jpg?itok=qykld-R-', target_size=(224, 224))\nimage = img_to_array(image)\ncv2_imshow(image)\nimage = preprocess_input(image)\nimage = np.expand_dims(image, axis=0)\nx = model.predict(image)\nprint(lb.classes_[np.argmax(x, axis=1)], \": \", x[0][np.argmax(x, axis=1)])\n```\n\n##Convert model to mlmodel \n\n\n```\n# coremltools is required to convert model to mlmodel\n!pip install coremltools==4.0b1\n```\n\n    Collecting coremltools==4.0b1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/6f/b7/b9aebb72e977f4f4d188e01f9b917bf80cff69aa6bd27239a7b94c417efe/coremltools-4.0b1.tar.gz (600kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 604kB 2.8MB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.14.5 in /usr/local/lib/python3.6/dist-packages (from coremltools==4.0b1) (1.18.5)\n    Requirement already satisfied: protobuf>=3.1.0 in /usr/local/lib/python3.6/dist-packages (from coremltools==4.0b1) (3.12.2)\n    Requirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.6/dist-packages (from coremltools==4.0b1) (1.15.0)\n    Collecting attr\n      Downloading https://files.pythonhosted.org/packages/de/be/ddc7f84d4e087144472a38a373d3e319f51a6faf6e5fc1ae897173675f21/attr-0.3.1.tar.gz\n    Requirement already satisfied: attrs in /usr/local/lib/python3.6/dist-packages (from coremltools==4.0b1) (19.3.0)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.6/dist-packages (from coremltools==4.0b1) (1.1.1)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from coremltools==4.0b1) (1.4.1)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from coremltools==4.0b1) (4.41.1)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from protobuf>=3.1.0->coremltools==4.0b1) (49.1.0)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy->coremltools==4.0b1) (1.1.0)\n    Building wheels for collected packages: coremltools, attr\n      Building wheel for coremltools (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for coremltools: filename=coremltools-4.0b1-cp36-none-any.whl size=796442 sha256=f6c476ed2c426b0dfbdabcfb88945615b85e8ebb29e160aa86750c63cf37d636\n      Stored in directory: /root/.cache/pip/wheels/e6/2f/39/c7f309170b37269d937c226e676611092188765da1a7213a54\n      Building wheel for attr (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for attr: filename=attr-0.3.1-cp36-none-any.whl size=2459 sha256=ab18c3314c24ee2caf12dcf4997b88b16515e5e86b5c228f3badde53fb20e93d\n      Stored in directory: /root/.cache/pip/wheels/f0/96/9b/1f8892a707d17095b5a6eab0275da9d39e68e03a26aee2e726\n    Successfully built coremltools attr\n    Installing collected packages: attr, coremltools\n    Successfully installed attr-0.3.1 coremltools-4.0b1\n\n\n\n```\nimport coremltools as ct\n\ninputs = ct.ImageType(scale=(1/127), bias=[-1.0, -1.0, -1.0])\nclassifier_config=ct.ClassifierConfig(['Mask on :)', 'Mask off!!'])\n\nmlmodel = ct.convert(model=model, \n                    inputs=[inputs],\n                    source='tensorflow',\n                    classifier_config=classifier_config,\n                    )\n```\n\n    WARNING:root:scikit-learn version 0.22.2.post1 is not supported. Minimum required version: 0.17. Maximum required version: 0.19.2. Disabling scikit-learn conversion API.\n    WARNING:root:Keras version 2.3.1 detected. Last version known to be fully compatible of Keras is 2.2.4 .\n    Running TensorFlow Graph Passes: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5/5 [00:00<00:00,  8.95 passes/s]\n    Converting Frontend ==> MIL Ops: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 434/434 [00:09<00:00, 46.19 ops/s]\n    Running MIL optimization passes: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 13/13 [00:11<00:00,  1.12 passes/s]\n    Translating MIL ==> MLModel Ops: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 709/709 [00:00<00:00, 1927.66 ops/s]\n\n\n\n```\nmlmodel\n```\n\n\n\n\n    input {\n      name: \"input_1\"\n      type {\n        imageType {\n          width: 224\n          height: 224\n          colorSpace: RGB\n          imageSizeRange {\n            widthRange {\n              lowerBound: 224\n              upperBound: 224\n            }\n            heightRange {\n              lowerBound: 224\n              upperBound: 224\n            }\n          }\n        }\n      }\n    }\n    output {\n      name: \"Identity\"\n      type {\n        dictionaryType {\n          stringKeyType {\n          }\n        }\n      }\n    }\n    output {\n      name: \"classLabel\"\n      type {\n        stringType {\n        }\n      }\n    }\n    predictedFeatureName: \"classLabel\"\n    predictedProbabilitiesName: \"Identity\"\n    metadata {\n      userDefined {\n        key: \"com.github.apple.coremltools.source\"\n        value: \"tensorflow==2.2.0\"\n      }\n      userDefined {\n        key: \"com.github.apple.coremltools.version\"\n        value: \"4.0b1\"\n      }\n    }\n\n\n\n\n```\nmlmodel.save('mask_detection.mlmodel')\n```\n\n\n```\n\n```\n", "meta": {"hexsha": "f39df152f20c586abf9d513fe009d15406330d32", "size": 611828, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Mask_Detection.ipynb", "max_stars_repo_name": "shubham7423/Mask-Detection-IOS-App", "max_stars_repo_head_hexsha": "92717c5566719e6f057d6837ee19d166aa5f4950", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-07-30T02:25:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-17T06:45:38.000Z", "max_issues_repo_path": "Mask_Detection.ipynb", "max_issues_repo_name": "shubham7423/Mask-Detection-IOS-App", "max_issues_repo_head_hexsha": "92717c5566719e6f057d6837ee19d166aa5f4950", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Mask_Detection.ipynb", "max_forks_repo_name": "shubham7423/Mask-Detection-IOS-App", "max_forks_repo_head_hexsha": "92717c5566719e6f057d6837ee19d166aa5f4950", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-30T14:18:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-30T14:18:55.000Z", "avg_line_length": 120.9385254003, "max_line_length": 106938, "alphanum_fraction": 0.7779947959, "converted": true, "num_tokens": 72070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16885695214168317, "lm_q2_score": 0.022977367401108627, "lm_q1q2_score": 0.0038798882275908704}}
{"text": "# Text Mining with Python and NLTK\nThis notebook includes some basic examples of techniques used to analyze text using Python.\n\nPython includes a variety of native support for string-handling and basic text processing, but for deeper analyses you'll need to use a text analytics package like the [natural language toolkit (NLTK)](http://www.nltk.org/). This isn't the only package available (there are others like [SpaCy](https://spacy.io/) and [Gensim](https://radimrehurek.com/gensim/)), but it's one of the most common starting points for exploring text analytics concepts.\n\n## Performing Basic Frequency Analysis\nLet's start by using some very basic frequency analysis on a document, and explore the hypothesis that the most frequently occuring words in a given body of text might give us an indication of the subject of the text.\n\n### Load a Text Document\nRun the cell below to load a document and view the text it contains.\n\n\n```python\n# Open Moon.txt from the Files folder\ndoc1 = open(\"Files/Moon.txt\", \"r\")\n\n# Read the document and print its contents\ndoc1Txt = doc1.read()\nprint(doc1Txt)\n```\n\n    We set sail on this new sea because there is new knowledge to be gained, and new rights to be won, and they must be won and used for the progress of all people. For space science, like nuclear science and all technology, has no conscience of its own. Whether it will become a force for good or ill depends on man, and only if the United States occupies a position of pre-eminence can we help decide whether this new ocean will be a sea of peace or a new terrifying theater of war. I do not say that we should or will go unprotected against the hostile misuse of space any more than we go unprotected against the hostile use of land or sea, but I do say that space can be explored and mastered without feeding the fires of war, without repeating the mistakes that man has made in extending his writ around this globe of ours.\n    There is no strife, no prejudice, no national conflict in outer space as yet. Its hazards are hostile to us all. Its conquest deserves the best of all mankind, and its opportunity for peaceful cooperation may never come again. But why, some say, the Moon? Why choose this as our goal? And they may well ask, why climb the highest mountain? Why, 35 years ago, fly the Atlantic? Why does Rice play Texas?\n    We choose to go to the Moon! We choose to go to the Moon in this decade and do the other things, not because they are easy, but because they are hard; because that goal will serve to organize and measure the best of our energies and skills, because that challenge is one that we are willing to accept, one we are unwilling to postpone, and one we intend to win!\n\n\n### Normalize the Text\nText includes a lot of punctuation, which we need to remove if we want to work only with the actual words.\n\nRun the cell below to strip all the numerals and punctuation from the text and convert the words to lower case.\n\n\n```python\nfrom string import punctuation\n\n# remove numeric digits\ntxt = ''.join(c for c in doc1Txt if not c.isdigit())\n\n# remove punctuation and make lower case\ntxt = ''.join(c for c in txt if c not in punctuation).lower()\n\n# print the normalized text\nprint (txt)\n```\n\n    we set sail on this new sea because there is new knowledge to be gained and new rights to be won and they must be won and used for the progress of all people for space science like nuclear science and all technology has no conscience of its own whether it will become a force for good or ill depends on man and only if the united states occupies a position of preeminence can we help decide whether this new ocean will be a sea of peace or a new terrifying theater of war i do not say that we should or will go unprotected against the hostile misuse of space any more than we go unprotected against the hostile use of land or sea but i do say that space can be explored and mastered without feeding the fires of war without repeating the mistakes that man has made in extending his writ around this globe of ours\n    there is no strife no prejudice no national conflict in outer space as yet its hazards are hostile to us all its conquest deserves the best of all mankind and its opportunity for peaceful cooperation may never come again but why some say the moon why choose this as our goal and they may well ask why climb the highest mountain why  years ago fly the atlantic why does rice play texas\n    we choose to go to the moon we choose to go to the moon in this decade and do the other things not because they are easy but because they are hard because that goal will serve to organize and measure the best of our energies and skills because that challenge is one that we are willing to accept one we are unwilling to postpone and one we intend to win\n\n\n### Get the Frequency Distribution\nNow let's tokenize the text (split it into individual words), and count the number of times each word occurs.\n\n\n```python\nimport nltk\nimport pandas as pd\nfrom nltk.probability import FreqDist\nfrom IPython.core.display import HTML\n\n# We need the punkt library to tokenize the text\nnltk.download(\"punkt\")\n\n# Tokenize the text into individual words\nwords = nltk.tokenize.word_tokenize(txt)\n\n# Get the frequency distribution of the words into a data frame\nfdist = FreqDist(words)\ncount_frame = pd.DataFrame(fdist, index =[0]).T\ncount_frame.columns = ['Count']\ncount_frame = count_frame.sort_values('Count', ascending=False)\n\n# Display the dataframe as HTML (so it's not truncated)\ndisplay(HTML(count_frame.to_html()))\n```\n\n    [nltk_data] Downloading package punkt to /home/nbuser/nltk_data...\n    [nltk_data]   Unzipping tokenizers/punkt.zip.\n\n\n\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Count</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>the</th>\n      <td>14</td>\n    </tr>\n    <tr>\n      <th>and</th>\n      <td>12</td>\n    </tr>\n    <tr>\n      <th>of</th>\n      <td>11</td>\n    </tr>\n    <tr>\n      <th>to</th>\n      <td>11</td>\n    </tr>\n    <tr>\n      <th>we</th>\n      <td>9</td>\n    </tr>\n    <tr>\n      <th>that</th>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>be</th>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>new</th>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>this</th>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>are</th>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>why</th>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>because</th>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>they</th>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>a</th>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>for</th>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>space</th>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>its</th>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>no</th>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>go</th>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>or</th>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>will</th>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>all</th>\n      <td>4</td>\n    </tr>\n    <tr>\n      <th>choose</th>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>say</th>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>hostile</th>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>in</th>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>is</th>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>sea</th>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>do</th>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>but</th>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>moon</th>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>one</th>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>man</th>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>may</th>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>without</th>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>science</th>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>against</th>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>not</th>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>on</th>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>whether</th>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>i</th>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>our</th>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>won</th>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>has</th>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>goal</th>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>can</th>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>war</th>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>unprotected</th>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>as</th>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>best</th>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>there</th>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>other</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>peaceful</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>preeminence</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>us</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>postpone</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>position</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>play</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>people</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>use</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>writ</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>progress</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>used</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>peace</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>own</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>outer</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>years</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>ours</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>well</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>prejudice</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>repeating</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>unwilling</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>technology</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>strife</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>terrifying</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>states</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>texas</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>some</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>skills</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>than</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>win</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>set</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>willing</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>serve</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>theater</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>things</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>united</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>sail</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>rights</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>rice</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>should</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>must</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>organize</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>opportunity</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>force</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>fly</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>fires</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>feeding</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>extending</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>explored</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>energies</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>easy</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>does</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>deserves</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>depends</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>decide</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>decade</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>cooperation</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>conscience</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>conquest</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>conflict</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>come</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>climb</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>challenge</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>become</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>atlantic</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>ask</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>around</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>any</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>ago</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>again</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>gained</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>globe</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>good</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>mastered</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>only</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>ocean</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>occupies</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>nuclear</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>never</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>national</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>accept</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>mountain</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>more</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>misuse</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>mistakes</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>measure</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>mankind</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>hard</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>made</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>like</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>land</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>knowledge</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>it</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>intend</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>ill</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>if</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>his</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>highest</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>help</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>hazards</th>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>yet</th>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n\n\n### Visualize Word Frequency\nIt's often easier to analyze frequency by creating a visualization, such as a Pareto chart.\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\nfig = plt.figure(figsize=(16, 9))\nax = fig.gca()    \ncount_frame['Count'][:60].plot(kind = 'bar', ax = ax, color='teal')\nax.set_title('Frequency of the most common words')\nax.set_ylabel('Frequency of word')\nax.set_xlabel('Word')\nplt.show()\n```\n\n### Remove Stopwords\nA large number of the words in the text are common words like \"the\" or \"and\". These \"stopwords\" add little in the way of semantic meaning to the text, and won't help us determine the subject matter - so run the cell below to remove them.\n\n\n```python\n# Get a set of common stopwords from NLTK\nnltk.download(\"stopwords\")\nfrom nltk.corpus import stopwords\n\n# remove stopwords from the text\nusefulTxt = ' '.join([word for word in txt.split() if word not in (stopwords.words('english'))])\nprint(\"\\n\")\nprint(usefulTxt)\n```\n\n    [nltk_data] Downloading package stopwords to /home/nbuser/nltk_data...\n    [nltk_data]   Unzipping corpora/stopwords.zip.\n    \n    \n    set sail new sea new knowledge gained new rights must used progress people space science like nuclear science technology conscience whether become force good ill depends man united states occupies position preeminence help decide whether new ocean sea peace new terrifying theater war say go unprotected hostile misuse space go unprotected hostile use land sea say space explored mastered without feeding fires war without repeating mistakes man made extending writ around globe strife prejudice national conflict outer space yet hazards hostile us conquest deserves best mankind opportunity peaceful cooperation may never come say moon choose goal may well ask climb highest mountain years ago fly atlantic rice play texas choose go moon choose go moon decade things easy hard goal serve organize measure best energies skills challenge one willing accept one unwilling postpone one intend win\n\n\n### Visualize the Frequency Distribution for the Remaining Words\nNow that we've prepared the text, we can tokenize the string into a list of individual words, and then perform frequency analysis on those words based on how often they appear in the text.\n\n\n```python\n# Get the frequency distribution of the remaining words\nusefulWords = nltk.tokenize.word_tokenize(usefulTxt)\nfdist = FreqDist(usefulWords)\ncount_frame = pd.DataFrame(fdist, index =[0]).T\ncount_frame.columns = ['Count']\n\n# Plot the frequency of the top 60 words\ncounts = count_frame.sort_values('Count', ascending = False)\nfig = plt.figure(figsize=(16, 9))\nax = fig.gca()    \ncounts['Count'][:60].plot(kind = 'bar', ax = ax, color='teal')\nax.set_title('Frequency of the most common words')\nax.set_ylabel('Frequency of word')\nax.set_xlabel('Word')\nplt.show()\n```\n\nThe most frequent word is \"new\", and other common words include \"go\", \"space\", \"science\", and \"moon\".\n\n## Extracting N-Grams\nWhen we tokenize text, we break it down into components that are generically called *n-grams*. When these n-grams usually consist of individual single words, which are technically known as *unigrams*. In many text analysis scenarios, breaking the text down into n-grams that consist of multiple words can yield more information by providing context. Generating n-grams from text results in a collection of *n*-word strings for each set of consecutive *n* words in the text. For example, consider the text \"**the quick brown fox**\". Generating two-word n-grams (known as *bigrams*) from this would yield the following collection of strings:\n\n- the quick\n- quick brown\n- brown fox\n\n### Extract Bigrams\nRun the following cell to examine the *moon.txt* document by splitting it into bigrams.\n\n\n```python\nfrom nltk import ngrams\n\n# Get n-grams where n = 2\nn = 2\nnGramsInDoc = []\nnGrams = ngrams(words, n)\nfor grams in nGrams:\n    nWords = ' '.join(g for g in grams)\n    nGramsInDoc.append(nWords)\n\n# Count the frequency of each n-gram\nfdist = FreqDist(nGramsInDoc)\ncount_frame = pd.DataFrame(fdist, index =[0]).T\ncount_frame.columns = ['Count']\n\n# Plot the frequency of the top 60 bigrams\ncounts = count_frame.sort_values('Count', ascending = False)\nfig = plt.figure(figsize=(16, 9))\nax = fig.gca()    \ncounts['Count'][:60].plot(kind = 'bar', ax = ax, color='teal')\nax.set_title('Frequency of the most common n-grams')\nax.set_ylabel('Frequency of n-gram')\nax.set_xlabel('n-gram')\nplt.show()\n```\n\nNote that the most common bigram is \"the moon\", which is of course fundamentally what the document is about.\n### Extract Trigrams\nLet's try exploring n-grams of three words (*trigrams*):\n\n\n```python\nfrom nltk import ngrams\n\n# Get n-grams where n = 3\nn = 3\nnGramsInDoc = []\nnGrams = ngrams(words, n)\nfor grams in nGrams:\n    nWords = ' '.join(g for g in grams)\n    nGramsInDoc.append(nWords)\n\n# Count the frequency of each n-gram\nfdist = FreqDist(nGramsInDoc)\ncount_frame = pd.DataFrame(fdist, index =[0]).T\ncount_frame.columns = ['Count']\n\n# Plot the frequency of the top 60 n-grams\ncounts = count_frame.sort_values('Count', ascending = False)\nfig = plt.figure(figsize=(16, 9))\nax = fig.gca()    \ncounts['Count'][:60].plot(kind = 'bar', ax = ax, color='teal')\nax.set_title('Frequency of the most common n-grams')\nax.set_ylabel('Frequency of n-gram')\nax.set_xlabel('n-gram')\nplt.show()\n```\n\nIt's a little less definitive, but the most common trigrams include phrases like \"go to the\", \"choose to go\", \"to go to\", and \"to the moon\".\n\n## Using Term Frequency - Inverse Document Frequency\nIn the previous example, we've used basic term frequency to determine each word's \"importance\" based on how often it appears in the document. When dealing with a large corpus of multiple documents, a more commonly used technique is *term frequency, inverse document frequency* (or TF-IDF) in which a score is calculated based on how often a word or term appears in one document compared to its more general frequency across the entire collection of documents. Using this technique, a high degree of relevance is assumed for words that appear frequently in a particular document, but relatively infrequently across a wide range of other documents.\n\n### Load and Some More Documents\nLet's add some more documents to our collection. We'll examine some presidential innauguration speeches from former US presidents.\n\n\n```python\n# Get a second document, normalize it, and remove stop words\ndoc2 = open(\"Files/FDR.txt\", \"r\")\ndoc2Txt = doc2.read()\nprint (doc2Txt)\nprint(\"------------------------------------------------\")\n# Normalize and remove stopwords\ntxt2 = ''.join(c for c in doc2Txt if not c.isdigit())\ntxt2 = ''.join(c for c in txt2 if c not in punctuation).lower()\ntxt2 = ' '.join([word for word in txt2.split() if word not in (stopwords.words('english'))])\n\n# Get a third document, normalize it, and remove stop words\ndoc3 = open(\"Files/JFK.txt\", \"r\")\ndoc3Txt = doc3.read()\nprint (doc3Txt)\nprint(\"------------------------------------------------\")\n# Normalize and remove stopwords\ntxt3 = ''.join(c for c in doc3Txt if not c.isdigit())\ntxt3 = ''.join(c for c in txt3 if c not in punctuation).lower()\ntxt3 = ' '.join([word for word in txt3.split() if word not in (stopwords.words('english'))])\n\n\n# and a fourth\ndoc4 = open(\"Files/Reagan.txt\", \"r\")\ndoc4Txt = doc4.read()\nprint (doc4Txt)\n# Normalize and remove stopwords\ntxt4 = ''.join(c for c in doc4Txt if not c.isdigit())\ntxt4 = ''.join(c for c in txt4 if c not in punctuation).lower()\ntxt4 = ' '.join([word for word in txt4.split() if word not in (stopwords.words('english'))])\n\n```\n\n    \ufeffPresident Hoover, Mr. Chief Justice, my friends: \n    \n    This is a day of national consecration. And I am certain that on this day my fellow Americans expect that on my induction into the Presidency, I will address them with a candor and a decision which the present situation of our people impels.\n    \n    This is preeminently the time to speak the truth, the whole truth, frankly and boldly. Nor need we shrink from honestly facing conditions in our country today. This great Nation will endure, as it has endured, will revive and will prosper.\n    \n    So, first of all, let me assert my firm belief that the only thing we have to fear is fear itself -- nameless, unreasoning, unjustified terror which paralyzes needed efforts to convert retreat into advance. In every dark hour of our national life, a leadership of frankness and of vigor has met with that understanding and support of the people themselves which is essential to victory. And I am convinced that you will again give that support to leadership in these critical days.\n    In such a spirit on my part and on yours we face our common difficulties. They concern, thank God, only material things. Values have shrunk to fantastic levels; taxes have risen; our ability to pay has fallen; government of all kinds is faced by serious curtailment of income; the means of exchange are frozen in the currents of trade; the withered leaves of industrial enterprise lie on every side; farmers find no markets for their produce; and the savings of many years in thousands of families are gone. More important, a host of unemployed citizens face the grim problem of existence, and an equally great number toil with little return. Only a foolish optimist can deny the dark realities of the moment.\n    And yet our distress comes from no failure of substance. We are stricken by no plague of locusts. Compared with the perils which our forefathers conquered, because they believed and were not afraid, we have still much to be thankful for. Nature still offers her bounty and human efforts have multiplied it. Plenty is at our doorstep, but a generous use of it languishes in the very sight of the supply.\n    Primarily, this is because the rulers of the exchange of mankind's goods have failed, through their own stubbornness and their own incompetence, have admitted their failure, and have abdicated. Practices of the unscrupulous money changers stand indicted in the court of public opinion, rejected by the hearts and minds of men.\n    True, they have tried. But their efforts have been cast in the pattern of an outworn tradition. Faced by failure of credit, they have proposed only the lending of more money. Stripped of the lure of profit by which to induce our people to follow their false leadership, they have resorted to exhortations, pleading tearfully for restored confidence. They only know the rules of a generation of self-seekers. They have no vision, and when there is no vision the people perish.\n    Yes, the money changers have fled from their high seats in the temple of our civilization. We may now restore that temple to the ancient truths. The measure of that restoration lies in the extent to which we apply social values more noble than mere monetary profit.\n    Happiness lies not in the mere possession of money; it lies in the joy of achievement, in the thrill of creative effort. The joy, the moral stimulation of work no longer must be forgotten in the mad chase of evanescent profits. These dark days, my friends, will be worth all they cost us if they teach us that our true destiny is not to be ministered unto but to minister to ourselves, to our fellow men.\n    Recognition of that falsity of material wealth as the standard of success goes hand in hand with the abandonment of the false belief that public office and high political position are to be valued only by the standards of pride of place and personal profit; and there must be an end to a conduct in banking and in business which too often has given to a sacred trust the likeness of callous and selfish wrongdoing. Small wonder that confidence languishes, for it thrives only on honesty, on honor, on the sacredness of obligations, on faithful protection, and on unselfish performance; without them it cannot live.\n    Restoration calls, however, not for changes in ethics alone. This Nation is asking for action, and action now.\n    Our greatest primary task is to put people to work. This is no unsolvable problem if we face it wisely and courageously. It can be accomplished in part by direct recruiting by the Government itself, treating the task as we would treat the emergency of a war, but at the same time, through this employment, accomplishing great -- greatly needed projects to stimulate and reorganize the use of our great natural resources.\n    Hand in hand with that we must frankly recognize the overbalance of population in our industrial centers and, by engaging on a national scale in a redistribution, endeavor to provide a better use of the land for those best fitted for the land.\n    \n    Yes, the task can be helped by definite efforts to raise the values of agricultural products, and with this the power to purchase the output of our cities. It can be helped by preventing realistically the tragedy of the growing loss through foreclosure of our small homes and our farms. It can be helped by insistence that the Federal, the State, and the local governments act forthwith on the demand that their cost be drastically reduced. It can be helped by the unifying of relief activities which today are often scattered, uneconomical, unequal. It can be helped by national planning for and supervision of all forms of transportation and of communications and other utilities that have a definitely public character. There are many ways in which it can be helped, but it can never be helped by merely talking about it.\n    We must act. We must act quickly.\n      And finally, in our progress towards a resumption of work, we require two safeguards against a return of the evils of the old order. There must be a strict supervision of all banking and credits and investments. There must be an end to speculation with other people's money. And there must be provision for an adequate but sound currency.\n    These, my friends, are the lines of attack. I shall presently urge upon a new Congress in special session detailed measures for their fulfillment, and I shall seek the immediate assistance of the 48 States.\n    Through this program of action we address ourselves to putting our own national house in order and making income balance outgo. Our international trade relations, though vastly important, are in point of time, and necessity, secondary to the establishment of a sound national economy. I favor, as a practical policy, the putting of first things first. I shall spare no effort to restore world trade by international economic readjustment; but the emergency at home cannot wait on that accomplishment.\n    The basic thought that guides these specific means of national recovery is not nationally -- narrowly nationalistic. It is the insistence, as a first consideration, upon the interdependence of the various elements in and parts of the United States of America -- a recognition of the old and permanently important manifestation of the American spirit of the pioneer. It is the way to recovery. It is the immediate way. It is the strongest assurance that recovery will endure.\n    In the field of world policy, I would dedicate this Nation to the policy of the good neighbor: the neighbor who resolutely respects himself and, because he does so, respects the rights of others; the neighbor who respects his obligations and respects the sanctity of his agreements in and with a world of neighbors.\n    If I read the temper of our people correctly, we now realize, as we have never realized before, our interdependence on each other; that we can not merely take, but we must give as well; that if we are to go forward, we must move as a trained and loyal army willing to sacrifice for the good of a common discipline, because without such discipline no progress can be made, no leadership becomes effective.\n    We are, I know, ready and willing to submit our lives and our property to such discipline, because it makes possible a leadership which aims at the larger good. This, I propose to offer, pledging that the larger purposes will bind upon us, bind upon us all as a sacred obligation with a unity of duty hitherto evoked only in times of armed strife.\n    With this pledge taken, I assume unhesitatingly the leadership of this great army of our people dedicated to a disciplined attack upon our common problems.\n    Action in this image, action to this end is feasible under the form of government which we have inherited from our ancestors. Our Constitution is so simple, so practical that it is possible always to meet extraordinary needs by changes in emphasis and arrangement without loss of essential form. That is why our constitutional system has proved itself the most superbly enduring political mechanism the modern world has ever seen.\n    It has met every stress of vast expansion of territory, of foreign wars, of bitter internal strife, of world relations. And it is to be hoped that the normal balance of executive and legislative authority may be wholly equal, wholly adequate to meet the unprecedented task before us. But it may be that an unprecedented demand and need for undelayed action may call for temporary departure from that normal balance of public procedure.\n    I am prepared under my constitutional duty to recommend the measures that a stricken nation in the midst of a stricken world may require. These measures, or such other measures as the Congress may build out of its experience and wisdom, I shall seek, within my constitutional authority, to bring to speedy adoption.\n    But, in the event that the Congress shall fail to take one of these two courses, in the event that the national emergency is still critical, I shall not evade the clear course of duty that will then confront me. I shall ask the Congress for the one remaining instrument to meet the crisis -- broad Executive power to wage a war against the emergency, as great as the power that would be given to me if we were in fact invaded by a foreign foe.\n    \n    For the trust reposed in me, I will return the courage and the devotion that befit the time. I can do no less.\n    We face the arduous days that lie before us in the warm courage of national unity; with the clear consciousness of seeking old and precious moral values; with the clean satisfaction that comes from the stern performance of duty by old and young alike. We aim at the assurance of a rounded, a permanent national life.\n    We do not distrust the -- the future of essential democracy. The people of the United States have not failed. In their need they have registered a mandate that they want direct, vigorous action. They have asked for discipline and direction under leadership. They have made me the present instrument of their wishes. In the spirit of the gift I take it.\n    In this dedication -- In this dedication of a Nation, we humbly ask the blessing of God. \n    May He protect each and every one of us.\n    May He guide me in the days to come.\n    ------------------------------------------------\n    \ufeffVice President Johnson, Mr. Speaker, Mr. Chief Justice, President Eisenhower, Vice President Nixon, President Truman, reverend clergy, fellow citizens:\n    \n    We observe today not a victory of party, but a celebration of freedom -- symbolizing an end, as well as a beginning -- signifying renewal, as well as change. For I have sworn before you and Almighty God the same solemn oath our forebears prescribed nearly a century and three-quarters ago.\n    \n    The world is very different now. For man holds in his mortal hands the power to abolish all forms of human poverty and all forms of human life. And yet the same revolutionary beliefs for which our forebears fought are still at issue around the globe -- the belief that the rights of man come not from the generosity of the state, but from the hand of God.\n    \n    We dare not forget today that we are the heirs of that first revolution. Let the word go forth from this time and place, to friend and foe alike, that the torch has been passed to a new generation of Americans -- born in this century, tempered by war, disciplined by a hard and bitter peace, proud of our ancient heritage, and unwilling to witness or permit the slow undoing of those human rights to which this nation has always been committed, and to which we are committed today at home and around the world.\n    \n    Let every nation know, whether it wishes us well or ill, that we shall pay any price, bear any burden, meet any hardship, support any friend, oppose any foe, to assure the survival and the success of liberty.\n    \n    This much we pledge -- and more.\n    \n    To those old allies whose cultural and spiritual origins we share, we pledge the loyalty of faithful friends. United there is little we cannot do in a host of cooperative ventures. Divided there is little we can do -- for we dare not meet a powerful challenge at odds and split asunder.\n    \n    To those new states whom we welcome to the ranks of the free, we pledge our word that one form of colonial control shall not have passed away merely to be replaced by a far more iron tyranny. We shall not always expect to find them supporting our view. But we shall always hope to find them strongly supporting their own freedom -- and to remember that, in the past, those who foolishly sought power by riding the back of the tiger ended up inside.\n    \n    To those people in the huts and villages of half the globe struggling to break the bonds of mass misery, we pledge our best efforts to help them help themselves, for whatever period is required -- not because the Communists may be doing it, not because we seek their votes, but because it is right. If a free society cannot help the many who are poor, it cannot save the few who are rich.\n    \n    To our sister republics south of our border, we offer a special pledge: to convert our good words into good deeds, in a new alliance for progress, to assist free men and free governments in casting off the chains of poverty. But this peaceful revolution of hope cannot become the prey of hostile powers. Let all our neighbors know that we shall join with them to oppose aggression or subversion anywhere in the Americas. And let every other power know that this hemisphere intends to remain the master of its own house.\n    \n    To that world assembly of sovereign states, the United Nations, our last best hope in an age where the instruments of war have far outpaced the instruments of peace, we renew our pledge of support -- to prevent it from becoming merely a forum for invective, to strengthen its shield of the new and the weak, and to enlarge the area in which its writ may run.\n    \n    \n    \n    Finally, to those nations who would make themselves our adversary, we offer not a pledge but a request: that both sides begin anew the quest for peace, before the dark powers of destruction unleashed by science engulf all humanity in planned or accidental self-destruction.\n    \n    We dare not tempt them with weakness. For only when our arms are sufficient beyond doubt can we be certain beyond doubt that they will never be employed.\n    \n    But neither can two great and powerful groups of nations take comfort from our present course -- both sides overburdened by the cost of modern weapons, both rightly alarmed by the steady spread of the deadly atom, yet both racing to alter that uncertain balance of terror that stays the hand of mankind's final war.\n    \n    So let us begin anew -- remembering on both sides that civility is not a sign of weakness, and sincerity is always subject to proof. Let us never negotiate out of fear, but let us never fear to negotiate.\n    \n    Let both sides explore what problems unite us instead of belaboring those problems which divide us.\n    \n    Let both sides, for the first time, formulate serious and precise proposals for the inspection and control of arms, and bring the absolute power to destroy other nations under the absolute control of all nations.\n    \n    Let both sides seek to invoke the wonders of science instead of its terrors. Together let us explore the stars, conquer the deserts, eradicate disease, tap the ocean depths, and encourage the arts and commerce.\n    \n    Let both sides unite to heed, in all corners of the earth, the command of Isaiah -- to \"undo the heavy burdens, and [to] let the oppressed go free.\"\n    \n    And, if a beachhead of cooperation may push back the jungle of suspicion, let both sides join in creating a new endeavor -- not a new balance of power, but a new world of law -- where the strong are just, and the weak secure, and the peace preserved.\n    \n    All this will not be finished in the first one hundred days. Nor will it be finished in the first one thousand days; nor in the life of this Administration; nor even perhaps in our lifetime on this planet. But let us begin.\n    \n    In your hands, my fellow citizens, more than mine, will rest the final success or failure of our course. Since this country was founded, each generation of Americans has been summoned to give testimony to its national loyalty. The graves of young Americans who answered the call to service surround the globe.\n    \n    Now the trumpet summons us again -- not as a call to bear arms, though arms we need -- not as a call to battle, though embattled we are -- but a call to bear the burden of a long twilight struggle, year in and year out, \"rejoicing in hope; patient in tribulation,\" a struggle against the common enemies of man: tyranny, poverty, disease, and war itself.\n    \n    Can we forge against these enemies a grand and global alliance, North and South, East and West, that can assure a more fruitful life for all mankind? Will you join in that historic effort?\n    \n    In the long history of the world, only a few generations have been granted the role of defending freedom in its hour of maximum danger. I do not shrink from this responsibility -- I welcome it. I do not believe that any of us would exchange places with any other people or any other generation. The energy, the faith, the devotion which we bring to this endeavor will light our country and all who serve it. And the glow from that fire can truly light the world.\n    \n    And so, my fellow Americans, ask not what your country can do for you; ask what you can do for your country.\n    \n    My fellow citizens of the world, ask not what America will do for you, but what together we can do for the freedom of man.\n    \n    Finally, whether you are citizens of America or citizens of the world, ask of us here the same high standards of strength and sacrifice which we ask of you. With a good conscience our only sure reward, with history the final judge of our deeds, let us go forth to lead the land we love, asking His blessing and His help, but knowing that here on earth God's work must truly be our own.\n    \n    ------------------------------------------------\n    \ufeffSenator Hatfield, Mr. Chief Justice, Mr. President, Vice President Bush, Vice President Mondale, Senator Baker, Speaker O'Neill, Reverend Moomaw, and my fellow citizens: \n    To a few of us here today this is a solemn and most momentous occasion, and yet in the history of our nation it is a commonplace occurrence. The orderly transfer of authority as called for in the Constitution routinely takes place, as it has for almost two centuries, and few of us stop to think how unique we really are. In the eyes of many in the world, this every 4-year ceremony we accept as normal is nothing less than a miracle. \n    Mr. President, I want our fellow citizens to know how much you did to carry on this tradition. By your gracious cooperation in the transition process, you have shown a watching world that we are a united people pledged to maintaining a political system which guarantees individual liberty to a greater degree than any other, and I thank you and your people for all your help in maintaining the continuity which is the bulwark of our Republic. \n    The business of our nation goes forward. These United States are confronted with an economic affliction of great proportions. We suffer from the longest and one of the worst sustained inflations in our national history. It distorts our economic decisions, penalizes thrift, and crushes the struggling young and the fixed-income elderly alike. It threatens to shatter the lives of millions of our people. \n    Idle industries have cast workers into unemployment, human misery, and personal indignity. Those who do work are denied a fair return for their labor by a tax system which penalizes successful achievement and keeps us from maintaining full productivity. \n    But great as our tax burden is, it has not kept pace with public spending. For decades we have piled deficit upon deficit, mortgaging our future and our children's future for the temporary convenience of the present. To continue this long trend is to guarantee tremendous social, cultural, political, and economic upheavals. \n    You and I, as individuals, can, by borrowing, live beyond our means, but for only a limited period of time. Why, then, should we think that collectively, as a nation, we're not bound by that same limitation? We must act today in order to preserve tomorrow. And let there be no misunderstanding: We are going to begin to act, beginning today. \n    The economic ills we suffer have come upon us over several decades. They will not go away in days, weeks, or months, but they will go away. They will go away because we as Americans have the capacity now, as we've had in the past, to do whatever needs to be done to preserve this last and greatest bastion of freedom. \n    In this present crisis, government is not the solution to our problem; government is the problem. From time to time we've been tempted to believe that society has become too complex to be managed by self-rule, that government by an elite group is superior to government for, by, and of the people. Well, if no one among us is capable of governing himself, then who among us has the capacity to govern someone else? All of us together, in and out of government, must bear the burden. The solutions we seek must be equitable, with no one group singled out to pay a higher price. \n    We hear much of special interest groups. Well, our concern must be for a special interest group that has been too long neglected. It knows no sectional boundaries or ethnic and racial divisions, and it crosses political party lines. It is made up of men and women who raise our food, patrol our streets, man our mines and factories, teach our children, keep our homes, and heal us when we're sick\u2014professionals, industrialists, shopkeepers, clerks, cabbies, and truck drivers. They are, in short, \"We the people,\" this breed called Americans. \n    Well, this administration's objective will be a healthy, vigorous, growing economy that provides equal opportunities for all Americans, with no barriers born of bigotry or discrimination. Putting America back to work means putting all Americans back to work. Ending inflation means freeing all Americans from the terror of runaway living costs. All must share in the productive work of this \"new beginning,\" and all must share in the bounty of a revived economy. With the idealism and fair play which are the core of our system and our strength, we can have a strong and prosperous America, at peace with itself and the world. \n    So, as we begin, let us take inventory. We are a nation that has a government\u2014not the other way around. And this makes us special among the nations of the Earth. Our government has no power except that granted it by the people. It is time to check and reverse the growth of government, which shows signs of having grown beyond the consent of the governed. \n    It is my intention to curb the size and influence of the Federal establishment and to demand recognition of the distinction between the powers granted to the Federal Government and those reserved to the States or to the people. All of us need to be reminded that the Federal Government did not create the States; the States created the Federal Government. \n    Now, so there will be no misunderstanding, it's not my intention to do away with government. It is rather to make it work--work with us, not over us; to stand by our side, not ride on our back. Government can and must provide opportunity, not smother it; foster productivity, not stifle it. \n    If we look to the answer as to why for so many years we achieved so much, prospered as no other people on Earth, it was because here in this land we unleashed the energy and individual genius of man to a greater extent than has ever been done before. Freedom and the dignity of the individual have been more available and assured here than in any other place on Earth. The price for this freedom at times has been high, but we have never been unwilling to pay that price. \n    It is no coincidence that our present troubles parallel and are proportionate to the intervention and intrusion in our lives that result from unnecessary and excessive growth of government. It is time for us to realize that we're too great a nation to limit ourselves to small dreams. We're not, as some would have us believe, doomed to an inevitable decline. I do not believe in a fate that will fall on us no matter what we do. I do believe in a fate that will fall on us if we do nothing. So, with all the creative energy at our command, let us begin an era of national renewal. Let us renew our determination, our courage, and our strength. And let us renew our faith and our hope. \n    We have every right to dream heroic dreams. Those who say that we're in a time when there are not heroes, they just don't know where to look. You can see heroes every day going in and out of factory gates. Others, a handful in number, produce enough food to feed all of us and then the world beyond. You meet heroes across a counter, and they're on both sides of that counter. There are entrepreneurs with faith in themselves and faith in an idea who create new jobs, new wealth and opportunity. They're individuals and families whose taxes support the government and whose voluntary gifts support church, charity, culture, art, and education. Their patriotism is quiet, but deep. Their values sustain our national life. \n    Now, I have used the words \"they\" and \"their\" in speaking of these heroes. I could say \"you\" and \"your,\" because I'm addressing the heroes of whom I speak\u2014you, the citizens of this blessed land. Your dreams, your hopes, your goals are going to be the dreams, the hopes, and the goals of this administration, so help me God. \n    We shall reflect the compassion that is so much a part of your makeup. How can we love our country and not love our countrymen; and loving them, reach out a hand when they fall, heal them when they're sick, and provide opportunity to make them self-sufficient so they will be equal in fact and not just in theory? \n    Can we solve the problems confronting us? Well, the answer is an unequivocal and emphatic \"yes.\" To paraphrase Winston Churchill, I did not take the oath I've just taken with the intention of presiding over the dissolution of the world's strongest economy. \n    In the days ahead I will propose removing the roadblocks that have slowed our economy and reduced productivity. Steps will be taken aimed at restoring the balance between the various levels of government. Progress may be slow, measured in inches and feet, not miles, but we will progress. It is time to reawaken this industrial giant, to get government back within its means, and to lighten our punitive tax burden. And these will be our first priorities, and on these principles there will be no compromise. \n    On the eve of our struggle for independence a man who might have been one of the greatest among the Founding Fathers, Dr. Joseph Warren, president of the Massachusetts Congress, said to his fellow Americans, \"Our country is in danger, but not to be despaired of . . . . On you depend the fortunes of America. You are to decide the important questions upon which rests the happiness and the liberty of millions yet unborn. Act worthy of yourselves.\" \n    Well, I believe we, the Americans of today, are ready to act worthy of ourselves, ready to do what must be done to ensure happiness and liberty for ourselves, our children, and our children's children. And as we renew ourselves here in our own land, we will be seen as having greater strength throughout the world. We will again be the exemplar of freedom and a beacon of hope for those who do not now have freedom. \n    To those neighbors and allies who share our freedom, we will strengthen our historic ties and assure them of our support and firm commitment. We will match loyalty with loyalty. We will strive for mutually beneficial relations. We will not use our friendship to impose on their sovereignty, for our own sovereignty is not for sale. \n    As for the enemies of freedom, those who are potential adversaries, they will be reminded that peace is the highest aspiration of the American people. We will negotiate for it, sacrifice for it; we will not surrender for it, now or ever. \n    Our forbearance should never be misunderstood. Our reluctance for conflict should not be misjudged as a failure of will. When action is required to preserve our national security, we will act. We will maintain sufficient strength to prevail if need be, knowing that if we do so we have the best chance of never having to use that strength. \n    Above all, we must realize that no arsenal or no weapon in the arsenals of the world is so formidable as the will and moral courage of free men and women. It is a weapon our adversaries in today's world do not have. It is a weapon that we as Americans do have. Let that be understood by those who practice terrorism and prey upon their neighbors. \n    I'm told that tens of thousands of prayer meetings are being held on this day, and for that I'm deeply grateful. We are a nation under God, and I believe God intended for us to be free. It would be fitting and good, I think, if on each Inaugural Day in future years it should be declared a day of prayer. \n    This is the first time in our history that this ceremony has been held, as you've been told, on this West Front of the Capitol. Standing here, one faces a magnificent vista, opening up on this city's special beauty and history. At the end of this open mall are those shrines to the giants on whose shoulders we stand. \n    Directly in front of me, the monument to a monumental man, George Washington, father of our country. A man of humility who came to greatness reluctantly. He led America out of revolutionary victory into infant nationhood. Off to one side, the stately memorial to Thomas Jefferson. The Declaration of Independence flames with his eloquence. And then, beyond the Reflecting Pool, the dignified columns of the Lincoln Memorial. Whoever would understand in his heart the meaning of America will find it in the life of Abraham Lincoln. \n    Beyond those monuments to heroism is the Potomac River, and on the far shore the sloping hills of Arlington National Cemetery, with its row upon row of simple white markers bearing crosses or Stars of David. They add up to only a tiny fraction of the price that has been paid for our freedom. \n    Each one of those markers is a monument to the kind of hero I spoke of earlier. Their lives ended in places called Belleau Wood, The Argonne, Omaha Beach, Salerno, and halfway around the world on Guadalcanal, Tarawa, Pork Chop Hill, the Chosin Reservoir, and in a hundred rice paddies and jungles of a place called Vietnam. \n    Under one such marker lies a young man, Martin Treptow, who left his job in a small town barbershop in 1917 to go to France with the famed Rainbow Division. There, on the western front, he was killed trying to carry a message between battalions under heavy artillery fire. \n    We're told that on his body was found a diary. On the flyleaf under the heading, \"My Pledge,\" he had written these words: \"America must win this war. Therefore I will work, I will save, I will sacrifice, I will endure, I will fight cheerfully and do my utmost, as if the issue of the whole struggle depended on me alone.\" \n    The crisis we are facing today does not require of us the kind of sacrifice that Martin Treptow and so many thousands of others were called upon to make. It does require, however, our best effort and our willingness to believe in ourselves and to believe in our capacity to perform great deeds, to believe that together with God's help we can and will resolve the problems which now confront us. \n    And after all, why shouldn't we believe that? We are Americans.\n    God bless you, and thank you.\n\n\nNow let's determine the top 10 most frequent words in each document:\n\n\n```python\nimport nltk\nimport pandas as pd\nfrom nltk.probability import FreqDist\n\n# Create collection of tokenized docs\ntxtDocs = [txt2, txt3, txt4]\ndocs = [list(nltk.tokenize.word_tokenize(txtDoc)) for txtDoc in txtDocs]\n\n# Loop through every doc\nfor i, doc in enumerate(docs):\n    print(\"Top words in document {}:\".format(i + 2))\n    fdist = FreqDist(doc)\n    count_frame = pd.DataFrame(fdist, index =[0]).T\n    count_frame.columns = ['Count']\n    count_frame = count_frame.sort_values('Count', ascending=False)\n    print (count_frame.head(10))\n    print('----------------------------')\n\n\n```\n\n    Top words in document 2:\n                Count\n    national       10\n    must           10\n    may             8\n    people          8\n    shall           7\n    action          7\n    helped          7\n    us              7\n    leadership      7\n    great           6\n    ----------------------------\n    Top words in document 3:\n              Count\n    let          16\n    us           12\n    world         8\n    sides         8\n    pledge        7\n    new           7\n    power         5\n    ask           5\n    citizens      5\n    shall         5\n    ----------------------------\n    Top words in document 4:\n                Count\n    us             25\n    government     16\n    must           10\n    believe        10\n    people          9\n    americans       9\n    time            8\n    one             8\n    freedom         8\n    world           8\n    ----------------------------\n\n\nWhen you're evaluating word importance across multiple texts in a corpus (or *body* of texts), you need to take into account that the overall frequency of a word for *all* of the texts may not indicate its importance in *individual* documents. For example, the word \"us\" appears frequently in all of the above speeches, and the words \"people\", \"world\", and \"must\" are also common to more than one document; so these words are not very helpful in determining the subject of a specific individual article.\n\n### Get TF-IDF Values for the top three words in each document\nTo help find words that are important in an individual document compared to others in the overall corpus, we need to consider several statistics:\n\n- **Term Frequency (TF)**: The relative frequency of a word within an individual document. Term Frequency of a term in a document is the number of occurrences of the term within the document, divided by the total number of terms in the document:\n\n\\begin{equation}tf(t,d) = \\frac{f_{t,d}}{\\mid d \\mid}\\end{equation}\n\n- **Inverse Document Frequency (IDF)**: The normalized number of documents containing the word. The Inverse Document Frequency of a term is calculated as the normal log of the total number of documents in the corpus divided by the number of documents in the corpus that contain the term:\n\n\\begin{equation}idf(t,D) = log \\frac{\\mid D \\mid}{\\mid \\{ d \\in D : t \\in d \\} \\mid}\\end{equation}\n\n- **Term Frequency - Inverse Document Frequency (TF-IDF)**: The overall relevance score for the word within an individual document when the entire corpus is taken into consideration. This is calculated as the product of Term Frequency and Inverse Document Frequency:\n\n\\begin{equation}tfidf(t,d,D) = tf(t,d) \\cdot idf(t,D)\\end{equation}\n\nLet's use these statistics to find the top 10 most important words in each document when the entire corpus is taken into consideration.\n\n\n```python\n# Create a function to calculate TF-IDF\ndef get_tfidf(term, text, corpus):\n    import math\n    \n    # Calculate TF as term occurrences / terms in text\n    wordCount = text.count(term)\n    tf = wordCount/len(text)\n    \n    # Calculate IDF as log(texts in corpus) / texts containing term\n    docCount = 0\n    for cDoc in corpus:\n        if term in cDoc:\n            docCount = docCount + 1\n    idf = math.log(len(corpus)/docCount)\n    \n    # Calculate TF-IDF and the product of TF and IDF\n    return tf*idf\n\n\n# Create collection of tokenized docs\ntxtDocs = [txt2, txt3, txt4]\ndocs = [list(nltk.tokenize.word_tokenize(txtDoc)) for txtDoc in txtDocs]\n\n# Loop through every doc\nfor i, doc in enumerate(docs):\n    print(\"Top words in document {}:\".format(i + 2))\n    \n    # Get the tfidf for each word in this doc\n    scores = {word: get_tfidf(word, doc, docs) for word in doc}\n    \n    # Sort the scored words for this doc in reverse order of score\n    sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True)\n    \n    # print out the top 10 scoring words in this doc\n    for word, score in sorted_words[:10]:\n        print(\"\\t{}, TF-IDF: {}\".format(word, round(score, 5)))\n\n```\n\n    Top words in document 2:\n    \tleadership, TF-IDF: 0.00814\n    \thelped, TF-IDF: 0.00814\n    \tmoney, TF-IDF: 0.00581\n    \tface, TF-IDF: 0.00465\n    \ttask, TF-IDF: 0.00465\n    \temergency, TF-IDF: 0.00465\n    \tmeasures, TF-IDF: 0.00465\n    \trespects, TF-IDF: 0.00465\n    \tdiscipline, TF-IDF: 0.00465\n    \tduty, TF-IDF: 0.00465\n    Top words in document 3:\n    \tarms, TF-IDF: 0.00631\n    \tpoverty, TF-IDF: 0.00474\n    \tglobe, TF-IDF: 0.00474\n    \tdare, TF-IDF: 0.00474\n    \tcontrol, TF-IDF: 0.00474\n    \tjoin, TF-IDF: 0.00474\n    \tfinal, TF-IDF: 0.00474\n    \tsides, TF-IDF: 0.00466\n    \tforebears, TF-IDF: 0.00316\n    \tcentury, TF-IDF: 0.00316\n    Top words in document 4:\n    \tgovernment, TF-IDF: 0.00563\n    \tcalled, TF-IDF: 0.00477\n    \theroes, TF-IDF: 0.00477\n    \tamong, TF-IDF: 0.00381\n    \tdreams, TF-IDF: 0.00381\n    \tbelieve, TF-IDF: 0.00352\n    \tthink, TF-IDF: 0.00286\n    \tmaintaining, TF-IDF: 0.00286\n    \tindividual, TF-IDF: 0.00286\n    \tgreater, TF-IDF: 0.00286\n\n\n## Stemming and Lemmatization\nUntil now, we've simply counted the number of occurrances of each word. This doesn't take into account the fact that sometimes multiple words may be based on the same common base, or *stem*; and may be semantically equivalent. For example, \"fishes\", \"fished\", \"fishing\", and \"fisher\" are all derived from the stem \"fish\".\n\n### View frequency of words from Kennedy's inauguration speech\nLet's take another look at JFKs innauguration speech, and count the unstemmed words it contains.\n\n\n```python\nprint(doc3Txt)\n\n# Normalize and remove stop words\nfrom string import punctuation\ndoc3Txt = ''.join(c for c in doc3Txt if not c.isdigit())\ndoc3Txt = ''.join(c for c in doc3Txt if c not in punctuation).lower()\ndoc3Txt = ' '.join([word for word in doc3Txt.split() if word not in (stopwords.words('english'))])\n\n# Get Frequency distribution\nwords = nltk.tokenize.word_tokenize(doc3Txt)\nfdist = FreqDist(words)\ncount_frame = pd.DataFrame(fdist, index =[0]).T\ncount_frame.columns = ['Count']\n\n# Plot frequency\ncounts = count_frame.sort_values('Count', ascending = False)\nfig = plt.figure(figsize=(16, 9))\nax = fig.gca()    \ncounts['Count'][:60].plot(kind = 'bar', ax = ax, color='teal')\nax.set_title('Frequency of the most common words')\nax.set_ylabel('Frequency of word')\nax.set_xlabel('Word')\nplt.show()\n```\n\n### Stem the words\nNow let's stem the words and count the stems.\n\nThere are various common stemming techniques, including the *Porter* and *Snowball* stemming algorithms; both of which are supported in NLTK. Let's start with the Porter stemmer:\n\n\n```python\nfrom nltk.stem.porter import PorterStemmer\n\n# Get the word stems\nps = PorterStemmer()\nstems = [ps.stem(word) for word in words]\n\n# Get Frequency distribution\nfdist = FreqDist(stems)\ncount_frame = pd.DataFrame(fdist, index =[0]).T\ncount_frame.columns = ['Count']\n\n# Plot frequency\ncounts = count_frame.sort_values('Count', ascending = False)\nfig = plt.figure(figsize=(16, 9))\nax = fig.gca()    \ncounts['Count'][:60].plot(kind = 'bar', ax = ax, color='teal')\nax.set_title('Frequency of the most common stems')\nax.set_ylabel('Frequency of stem')\nax.set_xlabel('Stem')\nplt.show()\n```\n\nNow let's try the Snowball stemmer:\n\n\n```python\nfrom nltk.stem.snowball import SnowballStemmer\n\n# Get the word stems\nss = SnowballStemmer(\"english\")\nstems = [ss.stem(word) for word in words]\n\n# Get Frequency distribution\nfdist = FreqDist(stems)\ncount_frame = pd.DataFrame(fdist, index =[0]).T\ncount_frame.columns = ['Count']\n\n# Plot frequency\ncounts = count_frame.sort_values('Count', ascending = False)\nfig = plt.figure(figsize=(16, 9))\nax = fig.gca()    \ncounts['Count'][:60].plot(kind = 'bar', ax = ax, color='teal')\nax.set_title('Frequency of the most common stems')\nax.set_ylabel('Frequency of stem')\nax.set_xlabel('Stem')\nplt.show()\n```\n\nBoth stemmers give similar results.\n\nNow, compare the frequencies of the stems to the unstemmed words. Note in particular that the unstemmed words include \"power\", \"powers\", and \"powerful\", which are all stemmed to \"power\". Additionally, the text includes \"nations\" and \"nation\" - which also have a common stem.\n\n### Lemmatize the Words\nStemming can result in some stems that aren't actually words - for example the Porter stemmer used in the previous example produces the stems \"*gener*\", \"*countri*\", and \"*presid*\". *Lemmatization* is a technique used to find common root (*lemma*) word for multiple derived words, with the restriction that the lemma itself must be present in a dictionary of known words. Let's try lemmatizing Kennedy's innauguration speech using the **WordNet** dictionary to verify the lemmas that are found.\n\n\n```python\nfrom nltk import WordNetLemmatizer\nnltk.download(\"wordnet\")\n\n# Get the word stems\nlem = WordNetLemmatizer()\nlemmas = [lem.lemmatize(word) for word in words]\n\n# Get Frequency distribution\nfdist = FreqDist(lemmas)\ncount_frame = pd.DataFrame(fdist, index =[0]).T\ncount_frame.columns = ['Count']\n\n# Plot frequency\ncounts = count_frame.sort_values('Count', ascending = False)\nfig = plt.figure(figsize=(16, 9))\nax = fig.gca()    \ncounts['Count'][:60].plot(kind = 'bar', ax = ax, color='teal')\nax.set_title('Frequency of the most common lemmas')\nax.set_ylabel('Frequency of lemma')\nax.set_xlabel('Lemma')\nplt.show()\n```\n\nThis time, the terms found are all words in ther own right (note that they include  \"*generation*\", \"*country*\", and \"*president*\"), but arguably these lemmas are less useful for determing the key terms in the document. In practice, you generally need to experiment and apply the stemmer or lemmatizer (or both) that best suits your text and purpose.\n\n## Extracting Key Phrases\nSo far, we've tried to determine the subject of a document by counting the frequency of words, n-grams, and stems or lemmas; with variable success. The problem, especially with very large texts, is that there may be a huge number of semantically useless words; not all of which can be easily filtered out by removing stopwords.\n\nThe next level of text analytics requires going beyond simple word counts and identifying *key phrases* in the text.\n\n### Using Collocations\nOne approach we can take is to identify n-grams of words that occur frequently together. These are known as collocations.\n\nFor example, the following code finds trigram collocations that occur at least three times in President Ronald Reagan's innauguration speech, and then based on a statistical measurement of collocation called Pointwise Mutual Information (PMI), it returns the top ten scoring trigrams.\n\n\n```python\nimport nltk\nfrom nltk.collocations import *\n\ndoc5 = open(\"Files/Reagan.txt\", \"r\")\ndoc5Txt = doc5.read()\n\nfrom string import punctuation\ndoc5Txt = ''.join(c for c in doc5Txt if not c.isdigit())\ndoc5Txt = ''.join(c for c in doc5Txt if c not in punctuation)\n\n# Get Frequency distribution\nwords = nltk.tokenize.word_tokenize(doc5Txt.lower())\n\ntrigram_measures = nltk.collocations.TrigramAssocMeasures()\n\n# find trigrams\nfinder = TrigramCollocationFinder.from_words(words)\n\n# only trigrams that appear 3+ times\nfinder.apply_freq_filter(3) \n\n# return the 10 n-grams with the highest PMI\nfor phrase in finder.nbest(trigram_measures.pmi, 10):\n    print(' '.join(phrase))\n```\n\n    it is time\n    the federal government\n    all of us\n    it is a\n    we are a\n\n\nThe code identifies four common trigrams in this text, some of which are potentially useful in discerning what the text is about (\"it is time\", \"the federal government\", and \"all of us\" give at least a flavor of the speech). However, there are also some fairly useless trigrams (\"it is a\" and \"we are a\").\n\nLet's try the same approach with another famous speech:\n\n\n```python\nimport nltk\nfrom nltk.collocations import *\n\ndoc6 = open(\"Files/Gettysburg.txt\", \"r\")\ndoc6Txt = doc6.read()\n\nfrom string import punctuation\ndoc6Txt = ''.join(c for c in doc6Txt if not c.isdigit())\ndoc6Txt = ''.join(c for c in doc6Txt if c not in punctuation)\n\n# Get Frequency distribution\nwords = nltk.tokenize.word_tokenize(doc6Txt.lower())\n\ntrigram_measures = nltk.collocations.TrigramAssocMeasures()\n\n# find trigrams\nfinder = TrigramCollocationFinder.from_words(words)\n\n# only trigrams that appear 3+ times\nfinder.apply_freq_filter(3) \n\n# return the 10 n-grams with the highest PMI\nfor phrase in finder.nbest(trigram_measures.pmi, 10):\n    print(' '.join(phrase))\n```\n\n    we can not\n\n\nThis time the results tell us very little about the subject of the text. One of the problems with this approach is that the results are limited to n-word phrases based on the n-gram collocations you specify - in this case, our trigram collocations result in three-word phrases. In reality, key phrases can be of variable length.\n\n### Applying Grammatical Rules\nTo detect and understand variable-length phrases, the code needs to encapsulate some kind of grammatical understanding of the text.\n\n#### Parts of Speech Tagging\nText understanding begins with categorizing words and phrases based on word types, such as nouns, verbs, adjectives, and so on. The following code splits the Gettysburg addressinto sentences, and then for each sentence it tokenizes the words and tags them with the appropriate parts of speech descriptor. The output is list of words for each sentence, and each word has a tag such as *NN* (noun), *PRP* (preposition), *DT* (determiner), *VBN* (verb, past participle), and so on based on the tags defined in the [*Penn Treebank Project*](http://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html).\n\n\n```python\nfrom nltk import pos_tag\nfrom string import punctuation\n\nnltk.download(\"averaged_perceptron_tagger\")\n\ndoc6 = open(\"Files/Gettysburg.txt\", \"r\")\ndoc6Txt = doc6.read()\n\nsentences = nltk.tokenize.sent_tokenize(doc6Txt)\nprint(\"\\nPOS Tags:\")\nfor sentence in sentences:\n    sentence = ''.join(c for c in sentence if not c.isdigit())\n    sentence = ''.join(c for c in sentence if c not in punctuation)\n    words = nltk.tokenize.word_tokenize(sentence)\n    pos_tokens = nltk.pos_tag(words)\n    print(pos_tokens)\n\n```\n\n    [nltk_data] Downloading package averaged_perceptron_tagger to\n    [nltk_data]     /home/nbuser/nltk_data...\n    [nltk_data]   Unzipping taggers/averaged_perceptron_tagger.zip.\n    \n    POS Tags:\n    [('Four', 'CD'), ('score', 'NN'), ('and', 'CC'), ('seven', 'CD'), ('years', 'NNS'), ('ago', 'RB'), ('our', 'PRP$'), ('fathers', 'NNS'), ('brought', 'VBN'), ('forth', 'RB'), ('on', 'IN'), ('this', 'DT'), ('continent', 'NN'), ('a', 'DT'), ('new', 'JJ'), ('nation', 'NN'), ('conceived', 'VBN'), ('in', 'IN'), ('Liberty', 'NNP'), ('and', 'CC'), ('dedicated', 'VBN'), ('to', 'TO'), ('the', 'DT'), ('proposition', 'NN'), ('that', 'IN'), ('all', 'DT'), ('men', 'NNS'), ('are', 'VBP'), ('created', 'VBN'), ('equal', 'JJ')]\n    [('Now', 'RB'), ('we', 'PRP'), ('are', 'VBP'), ('engaged', 'VBN'), ('in', 'IN'), ('a', 'DT'), ('great', 'JJ'), ('civil', 'JJ'), ('war', 'NN'), ('testing', 'VBG'), ('whether', 'IN'), ('that', 'DT'), ('nation', 'NN'), ('or', 'CC'), ('any', 'DT'), ('nation', 'NN'), ('so', 'RB'), ('conceived', 'JJ'), ('and', 'CC'), ('so', 'RB'), ('dedicated', 'JJ'), ('can', 'MD'), ('long', 'RB'), ('endure', 'VB')]\n    [('We', 'PRP'), ('are', 'VBP'), ('met', 'VBN'), ('on', 'IN'), ('a', 'DT'), ('great', 'JJ'), ('battlefield', 'NN'), ('of', 'IN'), ('that', 'DT'), ('war', 'NN')]\n    [('We', 'PRP'), ('have', 'VBP'), ('come', 'VBN'), ('to', 'TO'), ('dedicate', 'VB'), ('a', 'DT'), ('portion', 'NN'), ('of', 'IN'), ('that', 'DT'), ('field', 'NN'), ('as', 'IN'), ('a', 'DT'), ('final', 'JJ'), ('resting', 'NN'), ('place', 'NN'), ('for', 'IN'), ('those', 'DT'), ('who', 'WP'), ('here', 'RB'), ('gave', 'VBD'), ('their', 'PRP$'), ('lives', 'NNS'), ('that', 'IN'), ('that', 'DT'), ('nation', 'NN'), ('might', 'MD'), ('live', 'VB')]\n    [('It', 'PRP'), ('is', 'VBZ'), ('altogether', 'RB'), ('fitting', 'JJ'), ('and', 'CC'), ('proper', 'JJ'), ('that', 'IN'), ('we', 'PRP'), ('should', 'MD'), ('do', 'VB'), ('this', 'DT')]\n    [('But', 'CC'), ('in', 'IN'), ('a', 'DT'), ('larger', 'JJR'), ('sense', 'NN'), ('we', 'PRP'), ('can', 'MD'), ('not', 'RB'), ('dedicate', 'VB'), ('we', 'PRP'), ('can', 'MD'), ('not', 'RB'), ('consecrate', 'VB'), ('we', 'PRP'), ('can', 'MD'), ('not', 'RB'), ('hallow', 'VB'), ('this', 'DT'), ('ground', 'NN')]\n    [('The', 'DT'), ('brave', 'NN'), ('men', 'NNS'), ('living', 'VBG'), ('and', 'CC'), ('dead', 'JJ'), ('who', 'WP'), ('struggled', 'VBD'), ('here', 'RB'), ('have', 'VBP'), ('consecrated', 'VBN'), ('it', 'PRP'), ('far', 'RB'), ('above', 'IN'), ('our', 'PRP$'), ('poor', 'JJ'), ('power', 'NN'), ('to', 'TO'), ('add', 'VB'), ('or', 'CC'), ('detract', 'VB')]\n    [('The', 'DT'), ('world', 'NN'), ('will', 'MD'), ('little', 'VB'), ('note', 'JJ'), ('nor', 'CC'), ('long', 'JJ'), ('remember', 'VB'), ('what', 'WP'), ('we', 'PRP'), ('say', 'VBP'), ('here', 'RB'), ('but', 'CC'), ('it', 'PRP'), ('can', 'MD'), ('never', 'RB'), ('forget', 'VB'), ('what', 'WP'), ('they', 'PRP'), ('did', 'VBD'), ('here', 'RB')]\n    [('It', 'PRP'), ('is', 'VBZ'), ('for', 'IN'), ('us', 'PRP'), ('the', 'DT'), ('living', 'VBG'), ('rather', 'RB'), ('to', 'TO'), ('be', 'VB'), ('dedicated', 'VBN'), ('here', 'RB'), ('to', 'TO'), ('the', 'DT'), ('unfinished', 'JJ'), ('work', 'NN'), ('which', 'WDT'), ('they', 'PRP'), ('who', 'WP'), ('fought', 'VBP'), ('here', 'RB'), ('have', 'VBP'), ('thus', 'RB'), ('far', 'RB'), ('so', 'RB'), ('nobly', 'RB'), ('advanced', 'JJ')]\n    [('It', 'PRP'), ('is', 'VBZ'), ('rather', 'RB'), ('for', 'IN'), ('us', 'PRP'), ('to', 'TO'), ('be', 'VB'), ('here', 'RB'), ('dedicated', 'VBN'), ('to', 'TO'), ('the', 'DT'), ('great', 'JJ'), ('task', 'NN'), ('remaining', 'VBG'), ('before', 'IN'), ('us', 'PRP'), ('that', 'IN'), ('from', 'IN'), ('these', 'DT'), ('honored', 'VBN'), ('dead', 'NN'), ('we', 'PRP'), ('take', 'VBP'), ('increased', 'JJ'), ('devotion', 'NN'), ('to', 'TO'), ('that', 'DT'), ('cause', 'NN'), ('for', 'IN'), ('which', 'WDT'), ('they', 'PRP'), ('gave', 'VBD'), ('the', 'DT'), ('last', 'JJ'), ('full', 'JJ'), ('measure', 'NN'), ('of', 'IN'), ('devotion', 'NN'), ('that', 'IN'), ('we', 'PRP'), ('here', 'RB'), ('highly', 'RB'), ('resolve', 'VBP'), ('that', 'IN'), ('these', 'DT'), ('dead', 'JJ'), ('shall', 'MD'), ('not', 'RB'), ('have', 'VB'), ('died', 'VBN'), ('in', 'IN'), ('vain', 'NN'), ('that', 'IN'), ('this', 'DT'), ('nation', 'NN'), ('under', 'IN'), ('God', 'NNP'), ('shall', 'MD'), ('have', 'VB'), ('a', 'DT'), ('new', 'JJ'), ('birth', 'NN'), ('of', 'IN'), ('freedom', 'NN'), ('and', 'CC'), ('that', 'DT'), ('government', 'NN'), ('of', 'IN'), ('the', 'DT'), ('people', 'NNS'), ('by', 'IN'), ('the', 'DT'), ('people', 'NNS'), ('for', 'IN'), ('the', 'DT'), ('people', 'NNS'), ('shall', 'MD'), ('not', 'RB'), ('perish', 'VB'), ('from', 'IN'), ('the', 'DT'), ('earth', 'NN')]\n\n\n### Extracting Noun Phrases\nNow that we know how to tag the parts of speech in the document, we can think of each sentence as being a tree of tagged words. For example, the following tree shows a sentence (S) containing the words \"The big dog barked\":\n\n(S\n\n    *The*/DT\n    *big*/JJ\n    *dog*/NN\n    *barked*/VBN\n)\n\nWe can apply rules that govern sequences of tag types to define a grammar, and use that grammar to detect phrases in the text. For example, we might define a *noun* phrase as consisting of an optional determiner (such as \"a\" or \"the\"), zero or more adjectives (such as \"big\" or \"great\"), and a noun (such as \"dog\" or \"truck\"). We can then parse the text to find *chunks* of text that match this grammar as subtrees within sentences:\n\n(S\n\n    (NP\n        *The*/DT\n        *big*/JJ\n        *dog*/NN\n     )\n    *barked*/VBN\n)\n\nWe can use this ability to define grammars and detect chuncks of text that match them to extract specific types of phrases. For example, the following code extracts noun phrases from the Gettysburg address.\n\n\n```python\nfrom nltk import pos_tag\nfrom string import punctuation\n\nnltk.download(\"averaged_perceptron_tagger\")\n\n# Define the grammar for a noun phrase\ngrammar = \"NP: {<DT>?<JJ>*<NN>}\"\nparser = nltk.RegexpParser(grammar)\n\ndoc6 = open(\"Files/Gettysburg.txt\", \"r\")\ndoc6Txt = doc6.read()\n\n# Split the document into sentences\nsentences = nltk.tokenize.sent_tokenize(doc6Txt.lower())\n\nnoun_phrases = []\n\n# Each tagged sentence consists of an \"S\" root with POS tagged words and \"NP\" noun phrase branches\nprint('\\nSentence Trees\\n------------------')\nfor sentence in sentences:\n    # Normalize the text\n    sentence = ''.join(c for c in sentence if not c.isdigit())\n    sentence = ''.join(c for c in sentence if c not in punctuation)\n    \n    # Get the individual words\n    words = nltk.tokenize.word_tokenize(sentence)\n    \n    # Tag the parts of speech\n    pos_tokens = nltk.pos_tag(words)\n    \n    # Parse the tagged words\n    parsed_sentence = parser.parse(pos_tokens)\n    print(parsed_sentence)\n    \n    for chunk in parsed_sentence.subtrees():\n        # Find the NP subtrees - these are noun phrases\n        if chunk.label() == 'NP':\n            # Assemble the phrase from its constituent words\n            noun_phrase = []\n            for word in chunk:\n                noun_phrase.append(word[0])\n            # Add the phrase to the list of noun phrases found in the document\n            noun_phrases.append(' '.join(noun_phrase))\n\n# Print the extracted noun phrases (the NP branches in the sentence trees)            \nprint('\\nNoun Phrases\\n------------------')\nfor phrase in noun_phrases:\n    print(phrase)\n```\n\n    [nltk_data] Downloading package averaged_perceptron_tagger to\n    [nltk_data]     /home/nbuser/nltk_data...\n    [nltk_data]   Package averaged_perceptron_tagger is already up-to-\n    [nltk_data]       date!\n    \n    Sentence Trees\n    ------------------\n    (S\n      four/CD\n      (NP score/NN)\n      and/CC\n      seven/CD\n      years/NNS\n      ago/RB\n      our/PRP$\n      fathers/NNS\n      brought/VBN\n      forth/RB\n      on/IN\n      (NP this/DT continent/NN)\n      (NP a/DT new/JJ nation/NN)\n      conceived/VBN\n      in/IN\n      (NP liberty/NN)\n      and/CC\n      dedicated/VBN\n      to/TO\n      (NP the/DT proposition/NN)\n      that/IN\n      all/DT\n      men/NNS\n      are/VBP\n      created/VBN\n      equal/JJ)\n    (S\n      now/RB\n      we/PRP\n      are/VBP\n      engaged/VBN\n      in/IN\n      (NP a/DT great/JJ civil/JJ war/NN)\n      testing/VBG\n      whether/IN\n      (NP that/DT nation/NN)\n      or/CC\n      (NP any/DT nation/NN)\n      so/RB\n      conceived/JJ\n      and/CC\n      so/RB\n      dedicated/JJ\n      can/MD\n      long/RB\n      endure/VB)\n    (S\n      we/PRP\n      are/VBP\n      met/VBN\n      on/IN\n      (NP a/DT great/JJ battlefield/NN)\n      of/IN\n      (NP that/DT war/NN))\n    (S\n      we/PRP\n      have/VBP\n      come/VBN\n      to/TO\n      dedicate/VB\n      (NP a/DT portion/NN)\n      of/IN\n      (NP that/DT field/NN)\n      as/IN\n      (NP a/DT final/JJ resting/NN)\n      (NP place/NN)\n      for/IN\n      those/DT\n      who/WP\n      here/RB\n      gave/VBD\n      their/PRP$\n      lives/NNS\n      that/IN\n      (NP that/DT nation/NN)\n      might/MD\n      live/VB)\n    (S\n      it/PRP\n      is/VBZ\n      altogether/RB\n      fitting/JJ\n      and/CC\n      proper/JJ\n      that/IN\n      we/PRP\n      should/MD\n      do/VB\n      this/DT)\n    (S\n      but/CC\n      in/IN\n      a/DT\n      larger/JJR\n      (NP sense/NN)\n      we/PRP\n      can/MD\n      not/RB\n      dedicate/VB\n      we/PRP\n      can/MD\n      not/RB\n      consecrate/VB\n      we/PRP\n      can/MD\n      not/RB\n      hallow/VB\n      (NP this/DT ground/NN))\n    (S\n      (NP the/DT brave/NN)\n      men/NNS\n      living/VBG\n      and/CC\n      dead/JJ\n      who/WP\n      struggled/VBD\n      here/RB\n      have/VBP\n      consecrated/VBN\n      it/PRP\n      far/RB\n      above/IN\n      our/PRP$\n      (NP poor/JJ power/NN)\n      to/TO\n      add/VB\n      or/CC\n      detract/VB)\n    (S\n      (NP the/DT world/NN)\n      will/MD\n      little/VB\n      note/JJ\n      nor/CC\n      long/JJ\n      remember/VB\n      what/WP\n      we/PRP\n      say/VBP\n      here/RB\n      but/CC\n      it/PRP\n      can/MD\n      never/RB\n      forget/VB\n      what/WP\n      they/PRP\n      did/VBD\n      here/RB)\n    (S\n      it/PRP\n      is/VBZ\n      for/IN\n      us/PRP\n      the/DT\n      living/VBG\n      rather/RB\n      to/TO\n      be/VB\n      dedicated/VBN\n      here/RB\n      to/TO\n      (NP the/DT unfinished/JJ work/NN)\n      which/WDT\n      they/PRP\n      who/WP\n      fought/VBP\n      here/RB\n      have/VBP\n      thus/RB\n      far/RB\n      so/RB\n      nobly/RB\n      advanced/JJ)\n    (S\n      it/PRP\n      is/VBZ\n      rather/RB\n      for/IN\n      us/PRP\n      to/TO\n      be/VB\n      here/RB\n      dedicated/VBN\n      to/TO\n      (NP the/DT great/JJ task/NN)\n      remaining/VBG\n      before/IN\n      us/PRP\n      that/IN\n      from/IN\n      these/DT\n      honored/VBN\n      (NP dead/NN)\n      we/PRP\n      take/VBP\n      (NP increased/JJ devotion/NN)\n      to/TO\n      (NP that/DT cause/NN)\n      for/IN\n      which/WDT\n      they/PRP\n      gave/VBD\n      (NP the/DT last/JJ full/JJ measure/NN)\n      of/IN\n      (NP devotion/NN)\n      that/IN\n      we/PRP\n      here/RB\n      highly/RB\n      resolve/VBP\n      that/IN\n      these/DT\n      dead/JJ\n      shall/MD\n      not/RB\n      have/VB\n      died/VBN\n      in/IN\n      (NP vain/NN)\n      that/IN\n      (NP this/DT nation/NN)\n      under/IN\n      (NP god/NN)\n      shall/MD\n      have/VB\n      (NP a/DT new/JJ birth/NN)\n      of/IN\n      (NP freedom/NN)\n      and/CC\n      (NP that/DT government/NN)\n      of/IN\n      the/DT\n      people/NNS\n      by/IN\n      the/DT\n      people/NNS\n      for/IN\n      the/DT\n      people/NNS\n      shall/MD\n      not/RB\n      perish/VB\n      from/IN\n      (NP the/DT earth/NN))\n    \n    Noun Phrases\n    ------------------\n    score\n    this continent\n    a new nation\n    liberty\n    the proposition\n    a great civil war\n    that nation\n    any nation\n    a great battlefield\n    that war\n    a portion\n    that field\n    a final resting\n    place\n    that nation\n    sense\n    this ground\n    the brave\n    poor power\n    the world\n    the unfinished work\n    the great task\n    dead\n    increased devotion\n    that cause\n    the last full measure\n    devotion\n    vain\n    this nation\n    god\n    a new birth\n    freedom\n    that government\n    the earth\n\n\n### Working with Vocabularies\nPreviously, we tagged all of the words in the text; which makes sense when trying to find sequences of words that represent phrases. However, sometimes it makes sense to consider the set of distinct words in the document, which represents the *vocabulary* of the document.\n\nThe following code identifies the vocabulary of the Gettysburg address, and tags the words in the vocabulary.\n\n\n```python\nimport nltk\nnltk.download(\"punkt\")\nfrom string import punctuation\n\ndoc6 = open(\"Files/Gettysburg.txt\", \"r\")\ndoc6Txt = doc6.read()\n\ndoc6Txt = ''.join(c for c in doc6Txt if not c.isdigit())\ndoc6Txt = ''.join(c for c in doc6Txt if c not in punctuation)\n\n# Tokenize the words\nwords = nltk.tokenize.word_tokenize(doc6Txt.lower())\n\n# Tag the words\npos_tokens = nltk.pos_tag(words)\n\n# Get the vocabulary\nvocab = set(pos_tokens)\n\nprint (\"\\nTotal words: %i\" % len(pos_tokens))\nprint (\"Vocabulary: %i\" % len(vocab))\n\n# Tag the vocabulary\nprint(\"\\nTagged Vocabulary\")\nprint(sorted(vocab))\n```\n\n    [nltk_data] Downloading package punkt to /home/nbuser/nltk_data...\n    [nltk_data]   Package punkt is already up-to-date!\n    \n    Total words: 271\n    Vocabulary: 144\n    \n    Tagged Vocabulary\n    [('a', 'DT'), ('above', 'IN'), ('add', 'VB'), ('advanced', 'JJ'), ('ago', 'RB'), ('all', 'DT'), ('altogether', 'RB'), ('and', 'CC'), ('any', 'DT'), ('are', 'VBP'), ('as', 'IN'), ('battlefield', 'NN'), ('be', 'VB'), ('before', 'IN'), ('birth', 'NN'), ('brave', 'NN'), ('brought', 'VBN'), ('but', 'CC'), ('by', 'IN'), ('can', 'MD'), ('cause', 'NN'), ('civil', 'JJ'), ('come', 'VBN'), ('conceived', 'JJ'), ('conceived', 'VBN'), ('consecrate', 'VB'), ('consecrated', 'VBN'), ('continent', 'NN'), ('created', 'VBN'), ('dead', 'JJ'), ('dead', 'NN'), ('dedicate', 'VB'), ('dedicated', 'JJ'), ('dedicated', 'VBN'), ('detract', 'VB'), ('devotion', 'NN'), ('did', 'VBD'), ('died', 'VBN'), ('do', 'VB'), ('earth', 'NN'), ('endure', 'VB'), ('engaged', 'VBN'), ('equal', 'JJ'), ('far', 'RB'), ('fathers', 'NNS'), ('field', 'NN'), ('final', 'JJ'), ('fitting', 'JJ'), ('for', 'IN'), ('forget', 'VB'), ('forth', 'RB'), ('fought', 'VBP'), ('four', 'CD'), ('freedom', 'NN'), ('from', 'IN'), ('full', 'JJ'), ('gave', 'VBD'), ('god', 'NN'), ('government', 'NN'), ('great', 'JJ'), ('ground', 'NN'), ('hallow', 'VB'), ('have', 'VB'), ('have', 'VBP'), ('here', 'RB'), ('highly', 'RB'), ('honored', 'VBN'), ('in', 'IN'), ('increased', 'JJ'), ('is', 'VBZ'), ('it', 'PRP'), ('larger', 'JJR'), ('last', 'JJ'), ('liberty', 'NN'), ('little', 'VB'), ('live', 'VB'), ('lives', 'NNS'), ('living', 'VBG'), ('long', 'JJ'), ('long', 'RB'), ('measure', 'NN'), ('men', 'NNS'), ('met', 'VBN'), ('might', 'MD'), ('nation', 'NN'), ('never', 'RB'), ('new', 'JJ'), ('nobly', 'RB'), ('nor', 'CC'), ('not', 'RB'), ('note', 'JJ'), ('now', 'RB'), ('of', 'IN'), ('on', 'IN'), ('or', 'CC'), ('our', 'PRP$'), ('people', 'NNS'), ('perish', 'VB'), ('place', 'NN'), ('poor', 'JJ'), ('portion', 'NN'), ('power', 'NN'), ('proper', 'JJ'), ('proposition', 'NN'), ('rather', 'RB'), ('remaining', 'VBG'), ('remember', 'VB'), ('resolve', 'VBP'), ('resting', 'NN'), ('say', 'VBP'), ('score', 'NN'), ('sense', 'NN'), ('seven', 'CD'), ('shall', 'MD'), ('should', 'MD'), ('so', 'RB'), ('struggled', 'VBD'), ('take', 'VBP'), ('task', 'NN'), ('testing', 'VBG'), ('that', 'DT'), ('that', 'IN'), ('the', 'DT'), ('their', 'PRP$'), ('these', 'DT'), ('they', 'PRP'), ('this', 'DT'), ('those', 'DT'), ('thus', 'RB'), ('to', 'TO'), ('under', 'IN'), ('unfinished', 'JJ'), ('us', 'PRP'), ('vain', 'NN'), ('war', 'NN'), ('we', 'PRP'), ('what', 'WP'), ('whether', 'IN'), ('which', 'WDT'), ('who', 'WP'), ('will', 'MD'), ('work', 'NN'), ('world', 'NN'), ('years', 'NNS')]\n\n\n*Note: Some words may have multiple uses. For example, \"train\" can be a verb (\"I plan to train my dog to sit\") or a verb (\"I took a train to Paris\"). By tagging all of the words before distilling them into a vocabulary set, you included all meanings of the words - for example \"conceived\" is included both as an adjective and a past-tense verb.*\n\n### Extracting Named Entities\nOne specific type of word is a *named entity* - in other words a word or phrase that identifies an individual person (such as \"Satya Nadella\"), organization (for example, \"Microsoft\"), or geographical location (\"United States\"). NLTK includes a chunker that detects named entity chunks and labels them as PERSON, ORGANIZATION, or GPE, as shown by the following code:\n\n\n```python\nimport nltk\nfrom nltk import pos_tag, ne_chunk\n\nnltk.download(\"punkt\")\nnltk.download(\"averaged_perceptron_tagger\")\nnltk.download('maxent_ne_chunker')\nnltk.download('words')\n\ndoc6 = open(\"Files/JFK.txt\", \"r\")\ndoc6Txt = doc6.read()\n\nsentences = nltk.sent_tokenize(doc6Txt)\n\nprint(\"\\nNamed entity chunks:\")\npeople = []\nplaces = []\norganizations = []\nfor sentence in sentences:\n    # Find NE chunks\n    for chunk in ne_chunk(pos_tag(nltk.word_tokenize(sentence))):\n        # Check for a label\n        if hasattr(chunk, 'label'):\n            print(chunk)\n            # Which tyupe of named entity was found?\n            if chunk.label() == 'PERSON':\n                people.append(' '.join(c[0] for c in chunk))\n            elif chunk.label() == 'GPE':\n                places.append(' '.join(c[0] for c in chunk))\n            elif chunk.label() == 'ORGANIZATION':\n                organizations.append(' '.join(c[0] for c in chunk))\n                \n# Print out the consolidated results\nprint(\"\\nPeople:\")\nfor person in sorted(set(people)):\n    print(\"\\t\", person)\nprint(\"Places:\")\nfor place in sorted(set(places)):\n    print(\"\\t\", place)\nprint(\"Organizations:\")\nfor organization in sorted(set(organizations)):\n    print(\"\\t\", organization)\n```\n\n    [nltk_data] Downloading package punkt to /home/nbuser/nltk_data...\n    [nltk_data]   Package punkt is already up-to-date!\n    [nltk_data] Downloading package averaged_perceptron_tagger to\n    [nltk_data]     /home/nbuser/nltk_data...\n    [nltk_data]   Package averaged_perceptron_tagger is already up-to-\n    [nltk_data]       date!\n    [nltk_data] Downloading package maxent_ne_chunker to\n    [nltk_data]     /home/nbuser/nltk_data...\n    [nltk_data]   Unzipping chunkers/maxent_ne_chunker.zip.\n    [nltk_data] Downloading package words to /home/nbuser/nltk_data...\n    [nltk_data]   Unzipping corpora/words.zip.\n    \n    Named entity chunks:\n    (PERSON Johnson/NNP)\n    (PERSON Mr./NNP Speaker/NNP)\n    (PERSON Mr./NNP)\n    (PERSON Eisenhower/NNP)\n    (PERSON Nixon/NNP)\n    (PERSON Truman/NNP)\n    (PERSON Almighty/NNP God/NNP)\n    (GPE Americans/NNPS)\n    (GPE United/NNP)\n    (ORGANIZATION Communists/NNPS)\n    (ORGANIZATION Americas/NNPS)\n    (ORGANIZATION United/NNP Nations/NNPS)\n    (GPE Isaiah/NNP)\n    (ORGANIZATION Administration/NNP)\n    (GPE Americans/NNPS)\n    (GPE North/NNP)\n    (GPE South/NNP)\n    (GPE East/NNP)\n    (GPE West/NNP)\n    (GPE America/NNP)\n    (GPE America/NNP)\n    (PERSON God/NNP)\n    \n    People:\n    \t Almighty God\n    \t Eisenhower\n    \t God\n    \t Johnson\n    \t Mr.\n    \t Mr. Speaker\n    \t Nixon\n    \t Truman\n    Places:\n    \t America\n    \t Americans\n    \t East\n    \t Isaiah\n    \t North\n    \t South\n    \t United\n    \t West\n    Organizations:\n    \t Administration\n    \t Americas\n    \t Communists\n    \t United Nations\n\n\nAs you can see, the results are less than perfect, but some named entities have been successfully identified.\n\n## Text Classification\nOne of the most common uses of text analytics is to associate documents with specific categories, or *classes*. Classification is a fundamental form of *supervised machine learning* in which an existing set of documents for which the class *label* is already known is used to train a predictive model that operates on the *features* of a document in order to predict the appropriate class label.\n\nTo explore this, we'll work with a commonly used set of sample files - the **20newsgroups** datase, which contains sample postings from twenty newsnet newsgroups.\n\n*A note for younger readers - back in the early days of the Internet, before social media was called \"social media\"; the early cyber-pioneers used **newsgroups** to exchange ideas, ask questions, and generally argue about things of little consequence. These newsgroups were text-based \"bulletin boards\" that were grouped into hierarchical categories such as **rec.autos** or **comp.os.ms-windows.misc**. If we wanted to save these messages, we used a pre-cursor to the USB stick called a \"floppy disk\", which was a physical manifestation of the **Save** icon in Microsoft Word!*\n\n### View Training Data\nThe newsgroups data is available as a sample dataset in the ***SciKit-Learn*** library; which is a commonly used Python library for machine learning.\n\n\n```python\nfrom sklearn.datasets import fetch_20newsgroups\n\n# The sample data is split into two datasets; one for training a model, and one for testing\n# We'll start ny just looking at the training data\ntrain = fetch_20newsgroups(subset='train', shuffle=True)\n\n# The training data includes:\n#    - data - one row per document\n#    - target - one numeric label per document, representing the class to which the document belongs\n#    - target_names - a lookup table of the numeric labels and the corresponding class name\n\n# Count how many documents are in the training set:\nprint('%i documents' %len(train.data))\n\n# View the class names\nprint('\\nClasses:\\n',train.target_names) \n\n# Biew the first document, it's numeric class label, and the corresponding class name\nprint('\\nFirst Document:\\n--------------')\nprint(train.data[0])\nprint('-----------------\\nFirst Document Class: %i (%s)' % (train.target[0], train.target_names[train.target[0]]))\n```\n\n    Downloading 20news dataset. This may take a few minutes.\n    Downloading dataset from https://ndownloader.figshare.com/files/5975967 (14 MB)\n\n\n    11314 documents\n    \n    Classes:\n     ['alt.atheism', 'comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware', 'comp.windows.x', 'misc.forsale', 'rec.autos', 'rec.motorcycles', 'rec.sport.baseball', 'rec.sport.hockey', 'sci.crypt', 'sci.electronics', 'sci.med', 'sci.space', 'soc.religion.christian', 'talk.politics.guns', 'talk.politics.mideast', 'talk.politics.misc', 'talk.religion.misc']\n    \n    First Document:\n    --------------\n    From: lerxst@wam.umd.edu (where's my thing)\n    Subject: WHAT car is this!?\n    Nntp-Posting-Host: rac3.wam.umd.edu\n    Organization: University of Maryland, College Park\n    Lines: 15\n    \n     I was wondering if anyone out there could enlighten me on this car I saw\n    the other day. It was a 2-door sports car, looked to be from the late 60s/\n    early 70s. It was called a Bricklin. The doors were really small. In addition,\n    the front bumper was separate from the rest of the body. This is \n    all I know. If anyone can tellme a model name, engine specs, years\n    of production, where this car is made, history, or whatever info you\n    have on this funky looking car, please e-mail.\n    \n    Thanks,\n    - IL\n       ---- brought to you by your neighborhood Lerxst ----\n    \n    \n    \n    \n    \n    -----------------\n    First Document Class: 7 (rec.autos)\n\n\n### Train a Classification Model\nTo create a classification model, or *classifier*, we'll use a [SciKit-Learn](scikit-learn.org/) pipeline to pre-process the training data and then train the model using a classification algorithm.\n\n*Note: In this example, we're using a well-established statistical algorithm named Naive Bayes to train the model. Statistical machine learning models have been in use for a long time, and use statistical modeling of probability to predict unknown values based on relationships between the features in the data and the labels the model is trying to predict. In recent years, there have been many advances in machine learning, including \"deep learning\" techniques that make use of linear algebra and diferential calculus to iteratively find relationships between labels and matrices of feature values; and these techniques can offer much better performance and scalability than traditional statistical techniques. Some common frameworks for using deep learning techniques to perform text classification include [TensorFlow](https://www.tensorflow.org/tutorials/keras/basic_text_classification), [Keras](https://blog.keras.io/using-pre-trained-word-embeddings-in-a-keras-model.html) and [PyTorch](https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html). However, this simple statistical machine learning example with SciKit-Learn will suffice to illustrate the concept.*\n\n\n```python\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.naive_bayes import MultinomialNB\n\n# Our pipeline performs three tasks:\n#   1. Vectorize the word strings (excluding stop words) into a numeric matrix based on the frequency of each word\n#   2. Transform the frequency counts into TF/IDF values\n#   3. Use the transformed vectors to train a Naive Bayes model\n\ntext_clf = Pipeline([('vect', CountVectorizer(analyzer='word', stop_words='english')),\n                     ('tfidf', TfidfTransformer()),\n                     ('clf', MultinomialNB()),\n                    ])\n\n# Use the pipeline to fit the training and target data to a model\ntext_clf = text_clf.fit(train.data, train.target)\n\nprint('classifier trained!')\n```\n\n    classifier trained!\n\n\n### Test the Model\nNow that we've trained ther model using the training data, we can use the test data that we witheld to validate it. We'll use the model to predict the classes for the documents in the test dataset, and compare the predicted classes to the actual classes that we already know.\n\n\n```python\n# Get the test dataset\ntest = fetch_20newsgroups(subset='test', shuffle=True)\n\n# Use the model to predict labels for the test data\npredicted = text_clf.predict(test.data)\n\n# Let's take a look at the first document - did we predict the right class?\nprint('\\nFirst Document:\\n--------------')\nprint(test.data[0])\nprint('-----------------\\nPredicted Class:',test.target_names[predicted[0]])\nprint('Actual Class:',test.target_names[test.target[0]])\n```\n\n    \n    First Document:\n    --------------\n    From: v064mb9k@ubvmsd.cc.buffalo.edu (NEIL B. GANDLER)\n    Subject: Need info on 88-89 Bonneville\n    Organization: University at Buffalo\n    Lines: 10\n    News-Software: VAX/VMS VNEWS 1.41\n    Nntp-Posting-Host: ubvmsd.cc.buffalo.edu\n    \n    \n     I am a little confused on all of the models of the 88-89 bonnevilles.\n    I have heard of the LE SE LSE SSE SSEI. Could someone tell me the\n    differences are far as features or performance. I am also curious to\n    know what the book value is for prefereably the 89 model. And how much\n    less than book value can you usually get them for. In other words how\n    much are they in demand this time of year. I have heard that the mid-spring\n    early summer is the best time to buy.\n    \n    \t\t\tNeil Gandler\n    \n    -----------------\n    Predicted Class: rec.autos\n    Actual Class: rec.autos\n\n\n### Evaluate the Model's Accuracy\nOf course, looking at one prediction doesn't reflect the overall accuracy of the model. However, we can measure its accuracy based on the entire test dataset using SciKit-Learn metrics.\n\n\n```python\nfrom sklearn import metrics\nfrom sklearn.metrics import accuracy_score\n\n# Get the model accuracy score (percentage predicted correctly)\nprint('Accuracy: ', accuracy_score(test.target, predicted))\n```\n\n    Accuracy:  0.8169144981412639\n\n\n### Evaluating Other Metrics\nSimple accuracy only tells us part of the story. Consider this: If we had 100 test documents, and 95 of them were of the \"sci.electronics\" class, we could create a model that simply always predicts the numeric label for \"sci.electronics\"; and it would be 95% accurate - just not very useful!\n\nFor this reason, we usually evaluate machine learning models using some other metrics:\n\n\n```python\nfrom sklearn. metrics import classification_report\n\nprint(classification_report(test.target, predicted))\n```\n\n                 precision    recall  f1-score   support\n    \n              0       0.80      0.69      0.74       319\n              1       0.78      0.72      0.75       389\n              2       0.79      0.72      0.75       394\n              3       0.68      0.81      0.74       392\n              4       0.86      0.81      0.84       385\n              5       0.87      0.78      0.82       395\n              6       0.87      0.80      0.83       390\n              7       0.88      0.91      0.90       396\n              8       0.93      0.96      0.95       398\n              9       0.91      0.92      0.92       397\n             10       0.88      0.98      0.93       399\n             11       0.75      0.96      0.84       396\n             12       0.84      0.65      0.74       393\n             13       0.92      0.79      0.85       396\n             14       0.82      0.94      0.88       394\n             15       0.62      0.96      0.76       398\n             16       0.66      0.95      0.78       364\n             17       0.95      0.94      0.94       376\n             18       0.94      0.52      0.67       310\n             19       0.95      0.24      0.38       251\n    \n    avg / total       0.83      0.82      0.81      7532\n    \n\n\nThe classification report includes the following metrics for each class, and for the overall model:\n* *Precision*: The proportion of *positive* predictions for this class that were in fact positive.\n* *Recall*: The proportion of actual positive cases that the classifier correctly identified.\n* *F1-Score*: An average metric that takes both precision and recall into account.\n* *Support*: The number of instances of this class in the test dataset.\n\nThe precision and recall metrics are derived from the number of true and false predictions for each class, which are often used to form a *confusion matrix*. In Python, you can use the **sklearn.metrics.confusion_matrix** function to find these values for a trained classifier:\n\n\n```python\nfrom sklearn.metrics import confusion_matrix\n\n# Print the confusion matrix\ncm = confusion_matrix(test.target, predicted)\nprint(cm)\n```\n\n    [[220   0   0   1   0   1   0   0   2   1   1   3   0   6   4  67   4   6\n        1   2]\n     [  1 280  15  12   8  20   3   4   1   6   2  19   5   1   7   1   3   1\n        0   0]\n     [  1  18 283  40   4  12   1   1   4   4   2  10   1   0   6   6   1   0\n        0   0]\n     [  0   5  17 316  16   1  10   4   1   0   2   2  13   0   5   0   0   0\n        0   0]\n     [  0   2  11  23 312   2   8   3   1   3   2   5   8   0   3   0   2   0\n        0   0]\n     [  1  31  17  11   2 310   2   0   1   1   0  10   0   1   5   1   2   0\n        0   0]\n     [  0   2   3  25  10   0 311  12   2   3   5   2   6   4   1   2   2   0\n        0   0]\n     [  1   1   0   3   0   0   6 362   3   3   3   2   3   1   3   0   4   0\n        1   0]\n     [  0   0   0   1   0   0   4   9 381   0   0   1   1   0   0   0   1   0\n        0   0]\n     [  0   0   0   0   1   0   1   3   0 367  21   0   0   0   2   1   1   0\n        0   0]\n     [  0   0   0   0   0   0   0   0   0   4 392   0   0   0   1   2   0   0\n        0   0]\n     [  0   3   2   0   1   2   2   3   0   0   0 380   1   0   1   0   1   0\n        0   0]\n     [  0   6   6  26   6   0   7   6   4   1   3  47 256   4  12   6   1   2\n        0   0]\n     [  2   2   1   1   1   3   2   1   5   6   6   6   8 312   8  24   4   3\n        1   0]\n     [  0   3   0   1   0   4   0   0   1   0   2   2   1   2 372   3   2   0\n        1   0]\n     [  3   1   2   2   0   0   0   0   1   1   0   0   0   2   3 382   0   0\n        0   1]\n     [  0   0   0   1   0   0   2   1   1   1   0   8   0   1   1   2 344   1\n        1   0]\n     [  0   1   0   0   0   2   0   0   0   1   1   2   0   0   0   9   5 354\n        1   0]\n     [  2   0   0   0   0   0   0   1   0   0   1   6   0   1  11  10 114   4\n      160   0]\n     [ 43   2   1   0   0   0   0   0   0   1   2   1   0   3   6  97  29   3\n        4  59]]\n\n\nThe matrix shows the intersection of predicted and actual label values for each class - in simple terms, the diagonal intersections from top-left to bottom-right indicate the number of correct predictions.\n\nIt's generally more intuitive to visualize this as a heat map, like this:\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n%matplotlib inline\n\nplt.imshow(cm, interpolation=\"nearest\", cmap=plt.cm.Blues)\nplt.colorbar()\ntick_marks = np.arange(len(train.target_names))\nplt.xticks(tick_marks, train.target_names, rotation=90)\nplt.yticks(tick_marks, train.target_names)\nplt.xlabel(\"Predicted Category\")\nplt.ylabel(\"Actual Category\")\nplt.show()\n```\n\nA strong diagonal line of high values where the predicted label intersects with the actual label indicates that the model is performing well.\n\n### Using the Model with New Data\nNow that we have a working model, we can use it to predict the class of new documents:\n\n\n```python\n# Create a new data set that contains two new (very short) documents\nnew_data = ['I love my new Jaguar E-Pace. A great drive, and really comfortable interior.',\n            'Go Mariners! This could be our season!']\n\n# Use the model to predict the classes of the new documents\nnew_predictions = text_clf.predict(new_data)\n\n# Show the predicted classes\nfor prediction in new_predictions:\n    print(test.target_names[prediction])\n```\n\n    rec.autos\n    rec.sport.baseball\n\n\n## Word Embedding\nIn the text classification example above, we used the **CountVectorizer** and **TfidfTransformer** classes to convert the words in our text to a matrix of numeric values (counts per document and TDF/IF scores for each word respectively).Encoding words as numeric values like this is known as *word embedding*; and its the basis of many moders text analytics techniques.\n\nLet's take a a closer look at word embedding using counts by calculating a matrix of word counts per sentence in the first verse of William Blake's Tiger poem:\n\n\n```python\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport nltk\nnltk.download(\"punkt\")\nnltk.download(\"stopwords\")\nfrom nltk.corpus import stopwords\nfrom string import punctuation\nimport pandas as pd\n\npoem = \"Tiger Tiger burning bright, \\\nIn the forests of the night. \\\nWhat immortal hand or eye \\\nCould frame thy fearful symmetry?\"\n\nsentences = nltk.sent_tokenize(poem)\nfor sentence in sentences:\n    sentence = ''.join(c for c in sentence if not c.isdigit())\n    sentence = ''.join(c for c in sentence if c not in punctuation)\n\nm = CountVectorizer(analyzer='word', stop_words='english')\n\nv = m.fit_transform(sentences)\ndf = pd.DataFrame(data=v.toarray(), columns=m.get_feature_names()) \ndf\n```\n\n    [nltk_data] Downloading package punkt to /home/nbuser/nltk_data...\n    [nltk_data]   Package punkt is already up-to-date!\n    [nltk_data] Downloading package stopwords to /home/nbuser/nltk_data...\n    [nltk_data]   Package stopwords is already up-to-date!\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>bright</th>\n      <th>burning</th>\n      <th>eye</th>\n      <th>fearful</th>\n      <th>forests</th>\n      <th>frame</th>\n      <th>hand</th>\n      <th>immortal</th>\n      <th>night</th>\n      <th>symmetry</th>\n      <th>thy</th>\n      <th>tiger</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\nThe resulting matrix contains a row for each sentence (numbered 0 and 1), and a column for each word. The numeric values indicate the freqency of each word in each sentence. This approach to word embedding is sometimes referred to as *one-hot encoding*, because each column indicates the presence and weight of a word by a non-zero value - marking it as \"hot\" in the sentences or documents in which it appears.\n\nCount-based word embeddings like this are the basis of most statistical machine learning models for processing text, and as we've seen, they can be effective at enabling us to create models that classify text. However, the matrices themselves a *sparse* - that is, when we have a lot of documents containing a lot of words, we end up with 0's in a lot of the matrix cells. Additionally, the counts themselves don't tell us much about the relationships between the words - just their comparative frequency in the text.\n\nMost recent advances in text-analytics make use of more sophisticated word embedding techniques that use *Deep Learning* neural network-based models to derive word vectors that encode semantic relationships between words. Example of this approach include Google's *Word2Vec* algorithm and Stanford's *Global Vectors for Word Embeddings (GloVe)* algorithm. Let's take a look at Word2Vec using the implementation in the **gensim** package.\n\n\n```python\n!pip install gensim\n\n\nimport gensim\nimport nltk\nnltk.download(\"punkt\")\nnltk.download(\"stopwords\")\nfrom nltk.corpus import stopwords\nfrom string import punctuation\n\n# Array of word arrays\nsentence_words = []\n\npoem = \"Tiger Tiger burning bright, \\\nIn the forests of the night. \\\nWhat immortal hand or eye \\\nCould frame thy fearful symmetry?\"\n\n# Split the poem into sentences\nsentences = nltk.sent_tokenize(poem)\n\nfor sentence in sentences:\n    # normalize the sentences and then split them into words\n    sentence = ''.join(c for c in sentence if not c.isdigit())\n    sentence = ''.join(c for c in sentence if c not in punctuation).lower()\n    sentence = ' '.join([word for word in sentence.split() if word not in (stopwords.words('english'))])\n    sentence_words.append(nltk.word_tokenize(sentence))\n\n# Train a Word2Vec mode to generate a 3-dimensional vector for each word\nw2v_model = gensim.models.Word2Vec(sentence_words, min_count=1, size=3)\n\n# Find each word in the model, and print its vector\nwords = list(w2v_model.wv.vocab)\nfor word in words:\n    print(\"\\n\",word, \":\", w2v_model[word])\n\n```\n\n    Collecting gensim\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/d7/b9/6c93685bed0026b6a1cce55ab173f6b617f6db0d1325d25489c2fd43e711/gensim-3.7.1-cp36-cp36m-manylinux1_x86_64.whl (24.2MB)\n    \u001b[K    100% |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 24.2MB 170kB/s ta 0:00:011  10% |\u2588\u2588\u2588\u258c                            | 2.6MB 7.5MB/s eta 0:00:03    32% |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c                     | 8.0MB 6.2MB/s eta 0:00:03    42% |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258a                  | 10.4MB 9.5MB/s eta 0:00:02    74% |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588        | 18.1MB 5.4MB/s eta 0:00:02    88% |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u258c   | 21.5MB 4.9MB/s eta 0:00:01    97% |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 | 23.5MB 4.4MB/s eta 0:00:01\n    \u001b[?25hRequirement already satisfied: numpy>=1.11.3 in /home/nbuser/anaconda3_501/lib/python3.6/site-packages (from gensim) (1.14.6)\n    Requirement already satisfied: six>=1.5.0 in /home/nbuser/anaconda3_501/lib/python3.6/site-packages (from gensim) (1.11.0)\n    Requirement already satisfied: scipy>=0.18.1 in /home/nbuser/anaconda3_501/lib/python3.6/site-packages (from gensim) (1.1.0)\n    Collecting smart-open>=1.7.0 (from gensim)\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/ff/c8/de7dcf34d4b5f2ae94fe1055e0d6418fb97a63c9dc3428edd264704983a2/smart_open-1.8.0.tar.gz (40kB)\n    \u001b[K    100% |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 40kB 809kB/s ta 0:00:01\n    \u001b[?25hRequirement already satisfied: boto>=2.32 in /home/nbuser/anaconda3_501/lib/python3.6/site-packages (from smart-open>=1.7.0->gensim) (2.49.0)\n    Requirement already satisfied: bz2file in /home/nbuser/anaconda3_501/lib/python3.6/site-packages (from smart-open>=1.7.0->gensim) (0.98)\n    Requirement already satisfied: requests in /home/nbuser/anaconda3_501/lib/python3.6/site-packages (from smart-open>=1.7.0->gensim) (2.21.0)\n    Requirement already satisfied: boto3 in /home/nbuser/anaconda3_501/lib/python3.6/site-packages (from smart-open>=1.7.0->gensim) (1.4.8)\n    Requirement already satisfied: urllib3<1.25,>=1.21.1 in /home/nbuser/anaconda3_501/lib/python3.6/site-packages (from requests->smart-open>=1.7.0->gensim) (1.23)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /home/nbuser/anaconda3_501/lib/python3.6/site-packages (from requests->smart-open>=1.7.0->gensim) (3.0.4)\n    Requirement already satisfied: idna<2.9,>=2.5 in /home/nbuser/anaconda3_501/lib/python3.6/site-packages (from requests->smart-open>=1.7.0->gensim) (2.7)\n    Requirement already satisfied: certifi>=2017.4.17 in /home/nbuser/anaconda3_501/lib/python3.6/site-packages (from requests->smart-open>=1.7.0->gensim) (2018.10.15)\n    Requirement already satisfied: botocore<1.9.0,>=1.8.0 in /home/nbuser/anaconda3_501/lib/python3.6/site-packages (from boto3->smart-open>=1.7.0->gensim) (1.8.50)\n    Requirement already satisfied: s3transfer<0.2.0,>=0.1.10 in /home/nbuser/anaconda3_501/lib/python3.6/site-packages (from boto3->smart-open>=1.7.0->gensim) (0.1.13)\n    Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in /home/nbuser/anaconda3_501/lib/python3.6/site-packages (from boto3->smart-open>=1.7.0->gensim) (0.9.3)\n    Requirement already satisfied: docutils>=0.10 in /home/nbuser/anaconda3_501/lib/python3.6/site-packages (from botocore<1.9.0,>=1.8.0->boto3->smart-open>=1.7.0->gensim) (0.14)\n    Requirement already satisfied: python-dateutil<3.0.0,>=2.1 in /home/nbuser/anaconda3_501/lib/python3.6/site-packages (from botocore<1.9.0,>=1.8.0->boto3->smart-open>=1.7.0->gensim) (2.7.5)\n    Building wheels for collected packages: smart-open\n      Building wheel for smart-open (setup.py) ... \u001b[?25ldone\n    \u001b[?25h  Stored in directory: /home/nbuser/.cache/pip/wheels/f7/a6/ff/9ab5842c14e50e95a06a4675b0b4a689c9cab6064dac2b01d0\n    Successfully built smart-open\n    Installing collected packages: smart-open, gensim\n    Successfully installed gensim-3.7.1 smart-open-1.8.0\n    [nltk_data] Downloading package punkt to /home/nbuser/nltk_data...\n    [nltk_data]   Package punkt is already up-to-date!\n    [nltk_data] Downloading package stopwords to /home/nbuser/nltk_data...\n    [nltk_data]   Package stopwords is already up-to-date!\n    \n     tiger : [-0.10733602 -0.11524136  0.02027336]\n    \n     burning : [ 0.08262212 -0.1403956   0.01390845]\n    \n     bright : [-0.09857716 -0.09549358 -0.08510741]\n    \n     forests : [ 0.0652902  -0.04306603  0.06478731]\n    \n     night : [ 0.06674857  0.03190339 -0.15312067]\n    \n     immortal : [-0.16467167  0.08478177  0.02732418]\n    \n     hand : [-0.08502177 -0.02644745  0.08161556]\n    \n     eye : [-0.1199719   0.02818582 -0.05938471]\n    \n     could : [0.02458443 0.07561962 0.02570326]\n    \n     frame : [-0.14504337  0.13680336 -0.14180818]\n    \n     thy : [ 0.0581283   0.11214104 -0.06773499]\n    \n     fearful : [-0.04966051  0.0687515  -0.12464913]\n    \n     symmetry : [0.00701074 0.00799515 0.09942605]\n\n\n    /home/nbuser/anaconda3_501/lib/python3.6/site-packages/ipykernel/__main__.py:35: DeprecationWarning: Call to deprecated `__getitem__` (Method will be removed in 4.0.0, use self.wv.__getitem__() instead).\n\n\nThe output includes a vector for each word in the text. You can think of the vector as defining a point in n-dimensional space (in this case 3-dimensional) that represents the \"position\" of the word relative to the other words in the corpus.\n\nWe can use principle component analysis to visualize these positions in a  2-dimensional plot:\n\n\n```python\nfrom sklearn.decomposition import PCA\nfrom matplotlib import pyplot\n\n%matplotlib inline\n\n# fit a 2d PCA model to the vectors\nX = w2v_model[w2v_model.wv.vocab]\npca = PCA(n_components=2)\nresult = pca.fit_transform(X)\n# create a scatter plot of the projection\npyplot.scatter(result[:, 0], result[:, 1])\nwords = list(w2v_model.wv.vocab)\nfor i, word in enumerate(words):\n    pyplot.annotate(word, xy=(result[i, 0], result[i, 1]))\npyplot.show()\n```\n\nSo how does this help? Well, by defining the relative positions of each word as multi-dimensional vectors, we can find semantic relationships between the words - for example, you would expect related words like \"woman\", \"girl\", wife\", \"mother\" to be near each other.\n\nTo see this in practice, we'll need to train a word2vec model using a much larger volume of text and with larger vectors (defining more *dimensions* in our contextual space). The actual training is accomplished by submitting a one-hot-encoded vector for each word to a neural hetwork that will find the probability of a word being collocated (appearing within a specified number of words) with each other word in the text. In the course of finding these probabilities, the neural network training algorithm will adjust the vector weights assigned to words in a hidden layer of the network as it iteratively trains the model over multiple *epochs*. Eventually, these weights will give us the vector representations for the word embeddings. You can find out more about the details of this in Chris McCormick's excellent article at http://mccormickml.com/2016/04/19/word2vec-tutorial-the-skip-gram-model/.\n\nLet's train a model using a variety of texts from *Project Gutenberg* (an online project to digitize historically significant books).\n\n\n```python\nimport gensim, logging\nimport nltk\nnltk.download(\"punkt\")\nfrom nltk.corpus import gutenberg\nnltk.download(\"gutenberg\")\n\nsentence_tokens = []\n\nfor fileid in gutenberg.fileids():\n    print(fileid)\n    sentences = gutenberg.sents(fileid)\n    for sentence in sentences:\n        sentence_tokens.append(sentence)\n\n# Turn on loggng to info so we can see the training process\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\n# train word2vec to include words that occur 3 times or more\n# We'll create 500-dimensional vectors over 12 epochs\n# The maximum distance beween related words is 10\nvec_model = gensim.models.Word2Vec(sentence_tokens, min_count=3, size=500, window=10, iter=12)\n\nprint(\"model trained!\")\n```\n\n    [nltk_data] Downloading package punkt to /home/nbuser/nltk_data...\n    [nltk_data]   Package punkt is already up-to-date!\n    [nltk_data] Downloading package gutenberg to /home/nbuser/nltk_data...\n    [nltk_data]   Unzipping corpora/gutenberg.zip.\n    austen-emma.txt\n    austen-persuasion.txt\n    austen-sense.txt\n    bible-kjv.txt\n    blake-poems.txt\n    bryant-stories.txt\n    burgess-busterbrown.txt\n    carroll-alice.txt\n    chesterton-ball.txt\n    chesterton-brown.txt\n    chesterton-thursday.txt\n    edgeworth-parents.txt\n    melville-moby_dick.txt\n    milton-paradise.txt\n    shakespeare-caesar.txt\n    shakespeare-hamlet.txt\n    shakespeare-macbeth.txt\n    whitman-leaves.txt\n\n\n    2019-02-19 22:43:41,332 : INFO : collecting all words and their counts\n    2019-02-19 22:43:41,341 : INFO : PROGRESS: at sentence #0, processed 0 words, keeping 0 word types\n    2019-02-19 22:43:41,750 : INFO : PROGRESS: at sentence #10000, processed 256693 words, keeping 9207 word types\n    2019-02-19 22:43:42,229 : INFO : PROGRESS: at sentence #20000, processed 567137 words, keeping 13603 word types\n    2019-02-19 22:43:42,784 : INFO : PROGRESS: at sentence #30000, processed 918759 words, keeping 17616 word types\n    2019-02-19 22:43:43,276 : INFO : PROGRESS: at sentence #40000, processed 1236460 words, keeping 19579 word types\n    2019-02-19 22:43:43,750 : INFO : PROGRESS: at sentence #50000, processed 1508401 words, keeping 22623 word types\n    2019-02-19 22:43:44,132 : INFO : PROGRESS: at sentence #60000, processed 1715918 words, keeping 27910 word types\n    2019-02-19 22:43:44,487 : INFO : PROGRESS: at sentence #70000, processed 1915119 words, keeping 30708 word types\n    2019-02-19 22:43:44,893 : INFO : PROGRESS: at sentence #80000, processed 2144824 words, keeping 35822 word types\n    2019-02-19 22:43:45,363 : INFO : PROGRESS: at sentence #90000, processed 2415166 words, keeping 44470 word types\n    2019-02-19 22:43:45,726 : INFO : collected 51134 word types from a corpus of 2621785 raw words and 98552 sentences\n    2019-02-19 22:43:45,729 : INFO : Loading a fresh vocabulary\n    2019-02-19 22:43:46,625 : INFO : effective_min_count=3 retains 23321 unique words (45% of original 51134, drops 27813)\n    2019-02-19 22:43:46,627 : INFO : effective_min_count=3 leaves 2586832 word corpus (98% of original 2621785, drops 34953)\n    2019-02-19 22:43:47,414 : INFO : deleting the raw counts dictionary of 51134 items\n    2019-02-19 22:43:47,420 : INFO : sample=0.001 downsamples 53 most-common words\n    2019-02-19 22:43:47,433 : INFO : downsampling leaves estimated 1826551 word corpus (70.6% of prior 2586832)\n    2019-02-19 22:43:48,012 : INFO : estimated required memory for 23321 words and 500 dimensions: 104944500 bytes\n    2019-02-19 22:43:48,022 : INFO : resetting layer weights\n    2019-02-19 22:43:56,284 : INFO : training model with 3 workers on 23321 vocabulary and 500 features, using sg=0 hs=0 sample=0.001 negative=5 window=10\n    2019-02-19 22:43:58,808 : INFO : EPOCH 1 - PROGRESS: at 0.49% examples, 2920 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:43:59,838 : INFO : EPOCH 1 - PROGRESS: at 3.36% examples, 16485 words/s, in_qsize 4, out_qsize 1\n    2019-02-19 22:44:00,932 : INFO : EPOCH 1 - PROGRESS: at 6.69% examples, 25172 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:02,016 : INFO : EPOCH 1 - PROGRESS: at 9.11% examples, 29241 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:03,073 : INFO : EPOCH 1 - PROGRESS: at 12.36% examples, 33155 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:04,115 : INFO : EPOCH 1 - PROGRESS: at 15.10% examples, 35263 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:44:05,333 : INFO : EPOCH 1 - PROGRESS: at 17.57% examples, 36702 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:44:06,440 : INFO : EPOCH 1 - PROGRESS: at 19.65% examples, 37945 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:07,640 : INFO : EPOCH 1 - PROGRESS: at 21.69% examples, 39224 words/s, in_qsize 4, out_qsize 1\n    2019-02-19 22:44:08,716 : INFO : EPOCH 1 - PROGRESS: at 24.63% examples, 41246 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:44:09,730 : INFO : EPOCH 1 - PROGRESS: at 27.00% examples, 42017 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:44:10,859 : INFO : EPOCH 1 - PROGRESS: at 29.48% examples, 42784 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:11,995 : INFO : EPOCH 1 - PROGRESS: at 33.98% examples, 44167 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:13,051 : INFO : EPOCH 1 - PROGRESS: at 36.44% examples, 45011 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:44:14,058 : INFO : EPOCH 1 - PROGRESS: at 38.72% examples, 45867 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:44:15,109 : INFO : EPOCH 1 - PROGRESS: at 41.62% examples, 46560 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:16,160 : INFO : EPOCH 1 - PROGRESS: at 44.67% examples, 47230 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:17,166 : INFO : EPOCH 1 - PROGRESS: at 47.10% examples, 47582 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:18,281 : INFO : EPOCH 1 - PROGRESS: at 52.24% examples, 48396 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:44:19,392 : INFO : EPOCH 1 - PROGRESS: at 57.24% examples, 49157 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:20,493 : INFO : EPOCH 1 - PROGRESS: at 60.88% examples, 49281 words/s, in_qsize 4, out_qsize 1\n    2019-02-19 22:44:21,525 : INFO : EPOCH 1 - PROGRESS: at 65.61% examples, 49815 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:22,528 : INFO : EPOCH 1 - PROGRESS: at 68.83% examples, 50060 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:23,558 : INFO : EPOCH 1 - PROGRESS: at 73.11% examples, 49982 words/s, in_qsize 4, out_qsize 1\n    2019-02-19 22:44:24,568 : INFO : EPOCH 1 - PROGRESS: at 76.00% examples, 49697 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:25,854 : INFO : EPOCH 1 - PROGRESS: at 79.60% examples, 49663 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:26,894 : INFO : EPOCH 1 - PROGRESS: at 82.59% examples, 49803 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:28,010 : INFO : EPOCH 1 - PROGRESS: at 85.19% examples, 49581 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:29,377 : INFO : EPOCH 1 - PROGRESS: at 87.12% examples, 48833 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:44:30,585 : INFO : EPOCH 1 - PROGRESS: at 89.42% examples, 48762 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:44:31,621 : INFO : EPOCH 1 - PROGRESS: at 95.08% examples, 48677 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:32,737 : INFO : EPOCH 1 - PROGRESS: at 97.44% examples, 48476 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:33,696 : INFO : worker thread finished; awaiting finish of 2 more threads\n    2019-02-19 22:44:33,845 : INFO : EPOCH 1 - PROGRESS: at 99.76% examples, 48511 words/s, in_qsize 1, out_qsize 1\n    2019-02-19 22:44:33,873 : INFO : worker thread finished; awaiting finish of 1 more threads\n    2019-02-19 22:44:33,925 : INFO : worker thread finished; awaiting finish of 0 more threads\n    2019-02-19 22:44:33,937 : INFO : EPOCH - 1 : training on 2621785 raw words (1826782 effective words) took 37.6s, 48550 effective words/s\n    2019-02-19 22:44:35,273 : INFO : EPOCH 2 - PROGRESS: at 2.80% examples, 38966 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:44:36,626 : INFO : EPOCH 2 - PROGRESS: at 6.76% examples, 43774 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:37,743 : INFO : EPOCH 2 - PROGRESS: at 9.11% examples, 44122 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:38,859 : INFO : EPOCH 2 - PROGRESS: at 12.01% examples, 44330 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:39,888 : INFO : EPOCH 2 - PROGRESS: at 14.38% examples, 43979 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:40,895 : INFO : EPOCH 2 - PROGRESS: at 16.67% examples, 44850 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:41,970 : INFO : EPOCH 2 - PROGRESS: at 18.71% examples, 44706 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:43,030 : INFO : EPOCH 2 - PROGRESS: at 20.34% examples, 44589 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:44,123 : INFO : EPOCH 2 - PROGRESS: at 21.96% examples, 44475 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:45,183 : INFO : EPOCH 2 - PROGRESS: at 23.98% examples, 44413 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:46,367 : INFO : EPOCH 2 - PROGRESS: at 26.70% examples, 45009 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:47,447 : INFO : EPOCH 2 - PROGRESS: at 28.56% examples, 44706 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:48,637 : INFO : EPOCH 2 - PROGRESS: at 31.76% examples, 44849 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:49,649 : INFO : EPOCH 2 - PROGRESS: at 34.85% examples, 45464 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:50,828 : INFO : EPOCH 2 - PROGRESS: at 36.68% examples, 45091 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:51,893 : INFO : EPOCH 2 - PROGRESS: at 38.72% examples, 45422 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:52,976 : INFO : EPOCH 2 - PROGRESS: at 40.61% examples, 44985 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:54,074 : INFO : EPOCH 2 - PROGRESS: at 43.76% examples, 45595 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:55,224 : INFO : EPOCH 2 - PROGRESS: at 46.24% examples, 45722 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:44:56,227 : INFO : EPOCH 2 - PROGRESS: at 49.13% examples, 45858 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:44:57,531 : INFO : EPOCH 2 - PROGRESS: at 53.24% examples, 45763 words/s, in_qsize 6, out_qsize 2\n    2019-02-19 22:44:58,596 : INFO : EPOCH 2 - PROGRESS: at 57.24% examples, 46091 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:44:59,766 : INFO : EPOCH 2 - PROGRESS: at 60.88% examples, 46211 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:00,899 : INFO : EPOCH 2 - PROGRESS: at 64.98% examples, 46391 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:45:02,049 : INFO : EPOCH 2 - PROGRESS: at 68.42% examples, 46509 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:03,136 : INFO : EPOCH 2 - PROGRESS: at 72.57% examples, 46473 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:04,306 : INFO : EPOCH 2 - PROGRESS: at 76.45% examples, 46549 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:05,380 : INFO : EPOCH 2 - PROGRESS: at 79.27% examples, 46511 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:06,432 : INFO : EPOCH 2 - PROGRESS: at 81.96% examples, 46518 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:07,501 : INFO : EPOCH 2 - PROGRESS: at 84.73% examples, 46677 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:08,502 : INFO : EPOCH 2 - PROGRESS: at 87.12% examples, 46773 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:09,694 : INFO : EPOCH 2 - PROGRESS: at 89.42% examples, 46795 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:10,833 : INFO : EPOCH 2 - PROGRESS: at 96.21% examples, 47007 words/s, in_qsize 4, out_qsize 1\n    2019-02-19 22:45:12,032 : INFO : EPOCH 2 - PROGRESS: at 98.64% examples, 47130 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:12,514 : INFO : worker thread finished; awaiting finish of 2 more threads\n    2019-02-19 22:45:12,565 : INFO : worker thread finished; awaiting finish of 1 more threads\n    2019-02-19 22:45:12,607 : INFO : worker thread finished; awaiting finish of 0 more threads\n    2019-02-19 22:45:12,615 : INFO : EPOCH - 2 : training on 2621785 raw words (1827290 effective words) took 38.6s, 47281 effective words/s\n    2019-02-19 22:45:13,763 : INFO : EPOCH 3 - PROGRESS: at 2.48% examples, 40415 words/s, in_qsize 5, out_qsize 1\n    2019-02-19 22:45:14,968 : INFO : EPOCH 3 - PROGRESS: at 6.36% examples, 47367 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:15,993 : INFO : EPOCH 3 - PROGRESS: at 9.11% examples, 50091 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:17,027 : INFO : EPOCH 3 - PROGRESS: at 12.46% examples, 51347 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:18,199 : INFO : EPOCH 3 - PROGRESS: at 15.77% examples, 52232 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:19,339 : INFO : EPOCH 3 - PROGRESS: at 18.14% examples, 51571 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:20,357 : INFO : EPOCH 3 - PROGRESS: at 19.90% examples, 50790 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:21,564 : INFO : EPOCH 3 - PROGRESS: at 21.53% examples, 49196 words/s, in_qsize 6, out_qsize 1\n    2019-02-19 22:45:22,577 : INFO : EPOCH 3 - PROGRESS: at 23.66% examples, 49580 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:23,744 : INFO : EPOCH 3 - PROGRESS: at 25.83% examples, 48564 words/s, in_qsize 4, out_qsize 1\n    2019-02-19 22:45:24,774 : INFO : EPOCH 3 - PROGRESS: at 28.07% examples, 48669 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:25,944 : INFO : EPOCH 3 - PROGRESS: at 30.83% examples, 48434 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:26,979 : INFO : EPOCH 3 - PROGRESS: at 34.28% examples, 48834 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:28,142 : INFO : EPOCH 3 - PROGRESS: at 36.44% examples, 48651 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:29,154 : INFO : EPOCH 3 - PROGRESS: at 38.19% examples, 48537 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:30,410 : INFO : EPOCH 3 - PROGRESS: at 40.61% examples, 48159 words/s, in_qsize 4, out_qsize 1\n    2019-02-19 22:45:31,703 : INFO : EPOCH 3 - PROGRESS: at 43.09% examples, 47391 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:45:32,816 : INFO : EPOCH 3 - PROGRESS: at 45.37% examples, 47342 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:33,860 : INFO : EPOCH 3 - PROGRESS: at 47.46% examples, 47111 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:35,066 : INFO : EPOCH 3 - PROGRESS: at 52.24% examples, 47444 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:36,099 : INFO : EPOCH 3 - PROGRESS: at 56.24% examples, 47791 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:37,326 : INFO : EPOCH 3 - PROGRESS: at 60.04% examples, 47727 words/s, in_qsize 4, out_qsize 1\n    2019-02-19 22:45:38,489 : INFO : EPOCH 3 - PROGRESS: at 63.93% examples, 47786 words/s, in_qsize 6, out_qsize 1\n    2019-02-19 22:45:39,518 : INFO : EPOCH 3 - PROGRESS: at 67.28% examples, 47813 words/s, in_qsize 4, out_qsize 1\n    2019-02-19 22:45:40,681 : INFO : EPOCH 3 - PROGRESS: at 71.74% examples, 47847 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:41,726 : INFO : EPOCH 3 - PROGRESS: at 75.53% examples, 48081 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:42,829 : INFO : EPOCH 3 - PROGRESS: at 78.48% examples, 47941 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:43,891 : INFO : EPOCH 3 - PROGRESS: at 81.19% examples, 47867 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:45,027 : INFO : EPOCH 3 - PROGRESS: at 84.35% examples, 48114 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:46,104 : INFO : EPOCH 3 - PROGRESS: at 86.97% examples, 48055 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:47,223 : INFO : EPOCH 3 - PROGRESS: at 88.49% examples, 47938 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:45:48,286 : INFO : EPOCH 3 - PROGRESS: at 94.64% examples, 48048 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:49,412 : INFO : EPOCH 3 - PROGRESS: at 97.44% examples, 48039 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:50,493 : INFO : EPOCH 3 - PROGRESS: at 99.46% examples, 47935 words/s, in_qsize 2, out_qsize 1\n    2019-02-19 22:45:50,515 : INFO : worker thread finished; awaiting finish of 2 more threads\n    2019-02-19 22:45:50,607 : INFO : worker thread finished; awaiting finish of 1 more threads\n    2019-02-19 22:45:50,643 : INFO : worker thread finished; awaiting finish of 0 more threads\n    2019-02-19 22:45:50,657 : INFO : EPOCH - 3 : training on 2621785 raw words (1826113 effective words) took 38.0s, 48065 effective words/s\n    2019-02-19 22:45:51,827 : INFO : EPOCH 4 - PROGRESS: at 2.07% examples, 33740 words/s, in_qsize 4, out_qsize 1\n    2019-02-19 22:45:52,851 : INFO : EPOCH 4 - PROGRESS: at 4.99% examples, 41539 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:45:53,895 : INFO : EPOCH 4 - PROGRESS: at 7.77% examples, 44013 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:54,908 : INFO : EPOCH 4 - PROGRESS: at 9.85% examples, 43628 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:45:55,950 : INFO : EPOCH 4 - PROGRESS: at 12.81% examples, 44568 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:45:57,161 : INFO : EPOCH 4 - PROGRESS: at 15.43% examples, 44066 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:45:58,214 : INFO : EPOCH 4 - PROGRESS: at 17.57% examples, 44389 words/s, in_qsize 4, out_qsize 1\n    2019-02-19 22:45:59,252 : INFO : EPOCH 4 - PROGRESS: at 19.65% examples, 45201 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:00,320 : INFO : EPOCH 4 - PROGRESS: at 21.50% examples, 45789 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:01,360 : INFO : EPOCH 4 - PROGRESS: at 23.66% examples, 46319 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:02,372 : INFO : EPOCH 4 - PROGRESS: at 25.76% examples, 46330 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:03,552 : INFO : EPOCH 4 - PROGRESS: at 28.61% examples, 47087 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:04,652 : INFO : EPOCH 4 - PROGRESS: at 31.76% examples, 47346 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:05,849 : INFO : EPOCH 4 - PROGRESS: at 34.85% examples, 47233 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:46:07,079 : INFO : EPOCH 4 - PROGRESS: at 37.21% examples, 47408 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:08,128 : INFO : EPOCH 4 - PROGRESS: at 39.31% examples, 47648 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:09,236 : INFO : EPOCH 4 - PROGRESS: at 42.31% examples, 48105 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:10,465 : INFO : EPOCH 4 - PROGRESS: at 45.06% examples, 47911 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:11,501 : INFO : EPOCH 4 - PROGRESS: at 47.46% examples, 48168 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:46:12,504 : INFO : EPOCH 4 - PROGRESS: at 51.64% examples, 48566 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:13,605 : INFO : EPOCH 4 - PROGRESS: at 55.41% examples, 48424 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:46:14,740 : INFO : EPOCH 4 - PROGRESS: at 58.75% examples, 48217 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:15,819 : INFO : EPOCH 4 - PROGRESS: at 61.82% examples, 48131 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:17,039 : INFO : EPOCH 4 - PROGRESS: at 66.05% examples, 48072 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:18,188 : INFO : EPOCH 4 - PROGRESS: at 69.80% examples, 48126 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:19,287 : INFO : EPOCH 4 - PROGRESS: at 74.18% examples, 48258 words/s, in_qsize 5, out_qsize 1\n    2019-02-19 22:46:20,355 : INFO : EPOCH 4 - PROGRESS: at 77.29% examples, 48179 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:21,563 : INFO : EPOCH 4 - PROGRESS: at 80.50% examples, 48097 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:22,680 : INFO : EPOCH 4 - PROGRESS: at 83.62% examples, 48382 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:23,839 : INFO : EPOCH 4 - PROGRESS: at 86.78% examples, 48390 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:24,986 : INFO : EPOCH 4 - PROGRESS: at 88.32% examples, 48422 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:26,279 : INFO : EPOCH 4 - PROGRESS: at 95.93% examples, 48577 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:27,294 : INFO : EPOCH 4 - PROGRESS: at 98.38% examples, 48900 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:46:27,811 : INFO : worker thread finished; awaiting finish of 2 more threads\n    2019-02-19 22:46:27,932 : INFO : worker thread finished; awaiting finish of 1 more threads\n    2019-02-19 22:46:27,958 : INFO : worker thread finished; awaiting finish of 0 more threads\n    2019-02-19 22:46:27,964 : INFO : EPOCH - 4 : training on 2621785 raw words (1826861 effective words) took 37.2s, 49096 effective words/s\n    2019-02-19 22:46:29,075 : INFO : EPOCH 5 - PROGRESS: at 3.14% examples, 52932 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:30,130 : INFO : EPOCH 5 - PROGRESS: at 6.76% examples, 54196 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:31,134 : INFO : EPOCH 5 - PROGRESS: at 9.11% examples, 52838 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:32,144 : INFO : EPOCH 5 - PROGRESS: at 11.58% examples, 50420 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:33,192 : INFO : EPOCH 5 - PROGRESS: at 14.77% examples, 51412 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:34,229 : INFO : EPOCH 5 - PROGRESS: at 17.24% examples, 51930 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:35,318 : INFO : EPOCH 5 - PROGRESS: at 19.65% examples, 52379 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:46:36,374 : INFO : EPOCH 5 - PROGRESS: at 21.96% examples, 53838 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:37,500 : INFO : EPOCH 5 - PROGRESS: at 24.95% examples, 54491 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:38,524 : INFO : EPOCH 5 - PROGRESS: at 27.54% examples, 54691 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:39,528 : INFO : EPOCH 5 - PROGRESS: at 30.00% examples, 54535 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:40,683 : INFO : EPOCH 5 - PROGRESS: at 33.53% examples, 54003 words/s, in_qsize 4, out_qsize 1\n    2019-02-19 22:46:41,739 : INFO : EPOCH 5 - PROGRESS: at 36.24% examples, 54299 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:42,929 : INFO : EPOCH 5 - PROGRESS: at 38.16% examples, 53568 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:44,074 : INFO : EPOCH 5 - PROGRESS: at 40.96% examples, 53569 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:45,117 : INFO : EPOCH 5 - PROGRESS: at 43.76% examples, 53482 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:46,201 : INFO : EPOCH 5 - PROGRESS: at 46.24% examples, 53330 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:47,465 : INFO : EPOCH 5 - PROGRESS: at 50.59% examples, 53454 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:48,495 : INFO : EPOCH 5 - PROGRESS: at 54.86% examples, 53583 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:46:49,703 : INFO : EPOCH 5 - PROGRESS: at 59.20% examples, 53554 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:50,712 : INFO : EPOCH 5 - PROGRESS: at 62.42% examples, 53381 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:51,763 : INFO : EPOCH 5 - PROGRESS: at 66.48% examples, 53421 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:52,902 : INFO : EPOCH 5 - PROGRESS: at 70.47% examples, 53245 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:53,941 : INFO : EPOCH 5 - PROGRESS: at 74.23% examples, 53037 words/s, in_qsize 4, out_qsize 1\n    2019-02-19 22:46:55,020 : INFO : EPOCH 5 - PROGRESS: at 78.04% examples, 53258 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:56,204 : INFO : EPOCH 5 - PROGRESS: at 81.56% examples, 53249 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:57,331 : INFO : EPOCH 5 - PROGRESS: at 85.26% examples, 53567 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:58,428 : INFO : EPOCH 5 - PROGRESS: at 87.68% examples, 53745 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:46:59,491 : INFO : EPOCH 5 - PROGRESS: at 92.95% examples, 53913 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:47:00,512 : INFO : EPOCH 5 - PROGRESS: at 96.99% examples, 53875 words/s, in_qsize 5, out_qsize 1\n    2019-02-19 22:47:01,464 : INFO : worker thread finished; awaiting finish of 2 more threads\n    2019-02-19 22:47:01,657 : INFO : EPOCH 5 - PROGRESS: at 99.70% examples, 54043 words/s, in_qsize 1, out_qsize 1\n    2019-02-19 22:47:01,675 : INFO : worker thread finished; awaiting finish of 1 more threads\n    2019-02-19 22:47:01,696 : INFO : worker thread finished; awaiting finish of 0 more threads\n    2019-02-19 22:47:01,699 : INFO : EPOCH - 5 : training on 2621785 raw words (1826709 effective words) took 33.7s, 54181 effective words/s\n    2019-02-19 22:47:02,741 : INFO : EPOCH 6 - PROGRESS: at 2.74% examples, 50165 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:03,807 : INFO : EPOCH 6 - PROGRESS: at 6.76% examples, 56060 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:04,813 : INFO : EPOCH 6 - PROGRESS: at 9.45% examples, 56366 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:05,866 : INFO : EPOCH 6 - PROGRESS: at 12.36% examples, 54165 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:47:06,953 : INFO : EPOCH 6 - PROGRESS: at 15.77% examples, 55388 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:07,958 : INFO : EPOCH 6 - PROGRESS: at 18.14% examples, 55296 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:08,968 : INFO : EPOCH 6 - PROGRESS: at 20.34% examples, 55834 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:09,995 : INFO : EPOCH 6 - PROGRESS: at 22.39% examples, 56166 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:11,144 : INFO : EPOCH 6 - PROGRESS: at 25.24% examples, 55754 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:12,328 : INFO : EPOCH 6 - PROGRESS: at 28.07% examples, 55641 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:13,347 : INFO : EPOCH 6 - PROGRESS: at 31.30% examples, 56004 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:47:14,490 : INFO : EPOCH 6 - PROGRESS: at 34.85% examples, 55884 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:47:15,588 : INFO : EPOCH 6 - PROGRESS: at 37.49% examples, 56335 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:47:16,598 : INFO : EPOCH 6 - PROGRESS: at 39.59% examples, 56106 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:17,695 : INFO : EPOCH 6 - PROGRESS: at 42.31% examples, 55688 words/s, in_qsize 4, out_qsize 1\n    2019-02-19 22:47:18,746 : INFO : EPOCH 6 - PROGRESS: at 45.02% examples, 55479 words/s, in_qsize 5, out_qsize 2\n    2019-02-19 22:47:19,803 : INFO : EPOCH 6 - PROGRESS: at 49.13% examples, 56450 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:47:20,957 : INFO : EPOCH 6 - PROGRESS: at 53.72% examples, 56414 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:21,959 : INFO : EPOCH 6 - PROGRESS: at 57.77% examples, 56442 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:23,014 : INFO : EPOCH 6 - PROGRESS: at 60.96% examples, 55993 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:47:24,122 : INFO : EPOCH 6 - PROGRESS: at 65.61% examples, 56091 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:25,155 : INFO : EPOCH 6 - PROGRESS: at 69.50% examples, 56331 words/s, in_qsize 4, out_qsize 1\n    2019-02-19 22:47:26,173 : INFO : EPOCH 6 - PROGRESS: at 74.23% examples, 56312 words/s, in_qsize 4, out_qsize 1\n    2019-02-19 22:47:27,242 : INFO : EPOCH 6 - PROGRESS: at 77.65% examples, 56149 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:28,417 : INFO : EPOCH 6 - PROGRESS: at 81.19% examples, 56031 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:29,495 : INFO : EPOCH 6 - PROGRESS: at 84.00% examples, 55860 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:30,604 : INFO : EPOCH 6 - PROGRESS: at 87.12% examples, 55916 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:31,832 : INFO : EPOCH 6 - PROGRESS: at 90.39% examples, 55742 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:33,026 : INFO : EPOCH 6 - PROGRESS: at 96.46% examples, 55560 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:47:34,103 : INFO : EPOCH 6 - PROGRESS: at 98.40% examples, 55177 words/s, in_qsize 5, out_qsize 1\n    2019-02-19 22:47:34,596 : INFO : worker thread finished; awaiting finish of 2 more threads\n    2019-02-19 22:47:34,616 : INFO : worker thread finished; awaiting finish of 1 more threads\n    2019-02-19 22:47:34,647 : INFO : worker thread finished; awaiting finish of 0 more threads\n    2019-02-19 22:47:34,649 : INFO : EPOCH - 6 : training on 2621785 raw words (1826266 effective words) took 32.9s, 55487 effective words/s\n    2019-02-19 22:47:35,708 : INFO : EPOCH 7 - PROGRESS: at 2.80% examples, 49641 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:36,844 : INFO : EPOCH 7 - PROGRESS: at 5.89% examples, 47116 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:38,004 : INFO : EPOCH 7 - PROGRESS: at 9.11% examples, 50220 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:39,122 : INFO : EPOCH 7 - PROGRESS: at 12.81% examples, 52115 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:40,226 : INFO : EPOCH 7 - PROGRESS: at 16.10% examples, 53506 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:41,385 : INFO : EPOCH 7 - PROGRESS: at 18.99% examples, 54394 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:42,539 : INFO : EPOCH 7 - PROGRESS: at 21.11% examples, 53983 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:47:43,723 : INFO : EPOCH 7 - PROGRESS: at 23.32% examples, 53609 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:44,729 : INFO : EPOCH 7 - PROGRESS: at 25.76% examples, 53589 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:45,771 : INFO : EPOCH 7 - PROGRESS: at 28.07% examples, 53185 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:46,866 : INFO : EPOCH 7 - PROGRESS: at 30.86% examples, 52835 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:47:47,892 : INFO : EPOCH 7 - PROGRESS: at 34.28% examples, 52948 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:49,139 : INFO : EPOCH 7 - PROGRESS: at 36.70% examples, 52584 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:50,147 : INFO : EPOCH 7 - PROGRESS: at 38.72% examples, 52648 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:47:51,242 : INFO : EPOCH 7 - PROGRESS: at 41.30% examples, 52455 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:52,435 : INFO : EPOCH 7 - PROGRESS: at 44.07% examples, 52100 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:53,430 : INFO : EPOCH 7 - PROGRESS: at 46.23% examples, 51845 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:47:54,536 : INFO : EPOCH 7 - PROGRESS: at 49.68% examples, 51760 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:55,559 : INFO : EPOCH 7 - PROGRESS: at 53.20% examples, 51618 words/s, in_qsize 6, out_qsize 1\n    2019-02-19 22:47:56,567 : INFO : EPOCH 7 - PROGRESS: at 57.19% examples, 51860 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:57,592 : INFO : EPOCH 7 - PROGRESS: at 60.88% examples, 52028 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:58,629 : INFO : EPOCH 7 - PROGRESS: at 64.98% examples, 52163 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:47:59,691 : INFO : EPOCH 7 - PROGRESS: at 68.42% examples, 52217 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:00,813 : INFO : EPOCH 7 - PROGRESS: at 73.15% examples, 52141 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:48:01,991 : INFO : EPOCH 7 - PROGRESS: at 76.85% examples, 51953 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:03,106 : INFO : EPOCH 7 - PROGRESS: at 80.17% examples, 51872 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:04,280 : INFO : EPOCH 7 - PROGRESS: at 82.94% examples, 51707 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:05,376 : INFO : EPOCH 7 - PROGRESS: at 85.63% examples, 51444 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:48:06,533 : INFO : EPOCH 7 - PROGRESS: at 87.51% examples, 51152 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:07,621 : INFO : EPOCH 7 - PROGRESS: at 90.39% examples, 50955 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:08,761 : INFO : EPOCH 7 - PROGRESS: at 96.21% examples, 50844 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:09,908 : INFO : EPOCH 7 - PROGRESS: at 98.13% examples, 50522 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:10,457 : INFO : worker thread finished; awaiting finish of 2 more threads\n    2019-02-19 22:48:10,672 : INFO : worker thread finished; awaiting finish of 1 more threads\n    2019-02-19 22:48:10,703 : INFO : worker thread finished; awaiting finish of 0 more threads\n    2019-02-19 22:48:10,705 : INFO : EPOCH - 7 : training on 2621785 raw words (1826620 effective words) took 36.0s, 50712 effective words/s\n    2019-02-19 22:48:11,830 : INFO : EPOCH 8 - PROGRESS: at 2.40% examples, 40659 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:12,841 : INFO : EPOCH 8 - PROGRESS: at 5.01% examples, 42075 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:13,860 : INFO : EPOCH 8 - PROGRESS: at 7.67% examples, 44562 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:14,916 : INFO : EPOCH 8 - PROGRESS: at 10.78% examples, 47195 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:16,014 : INFO : EPOCH 8 - PROGRESS: at 13.68% examples, 46839 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:17,088 : INFO : EPOCH 8 - PROGRESS: at 16.04% examples, 46897 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:48:18,202 : INFO : EPOCH 8 - PROGRESS: at 18.44% examples, 47223 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:19,280 : INFO : EPOCH 8 - PROGRESS: at 20.34% examples, 47481 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:48:20,286 : INFO : EPOCH 8 - PROGRESS: at 21.91% examples, 47405 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:21,444 : INFO : EPOCH 8 - PROGRESS: at 24.30% examples, 47286 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:22,529 : INFO : EPOCH 8 - PROGRESS: at 26.75% examples, 47374 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:23,660 : INFO : EPOCH 8 - PROGRESS: at 28.79% examples, 47218 words/s, in_qsize 6, out_qsize 1\n    2019-02-19 22:48:24,698 : INFO : EPOCH 8 - PROGRESS: at 32.25% examples, 47701 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:25,737 : INFO : EPOCH 8 - PROGRESS: at 35.18% examples, 48063 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:26,986 : INFO : EPOCH 8 - PROGRESS: at 37.49% examples, 48142 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:28,113 : INFO : EPOCH 8 - PROGRESS: at 39.59% examples, 48082 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:29,206 : INFO : EPOCH 8 - PROGRESS: at 42.69% examples, 48565 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:30,314 : INFO : EPOCH 8 - PROGRESS: at 45.41% examples, 48645 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:31,315 : INFO : EPOCH 8 - PROGRESS: at 48.06% examples, 48962 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:32,333 : INFO : EPOCH 8 - PROGRESS: at 51.12% examples, 48618 words/s, in_qsize 5, out_qsize 1\n    2019-02-19 22:48:33,728 : INFO : EPOCH 8 - PROGRESS: at 55.83% examples, 48470 words/s, in_qsize 4, out_qsize 1\n    2019-02-19 22:48:34,788 : INFO : EPOCH 8 - PROGRESS: at 59.20% examples, 48412 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:35,793 : INFO : EPOCH 8 - PROGRESS: at 62.88% examples, 48753 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:37,005 : INFO : EPOCH 8 - PROGRESS: at 66.84% examples, 48671 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:38,202 : INFO : EPOCH 8 - PROGRESS: at 71.16% examples, 48603 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:39,272 : INFO : EPOCH 8 - PROGRESS: at 75.53% examples, 49025 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:40,518 : INFO : EPOCH 8 - PROGRESS: at 79.37% examples, 49084 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:41,520 : INFO : EPOCH 8 - PROGRESS: at 82.26% examples, 49300 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:42,557 : INFO : EPOCH 8 - PROGRESS: at 84.80% examples, 49216 words/s, in_qsize 4, out_qsize 1\n    2019-02-19 22:48:43,640 : INFO : EPOCH 8 - PROGRESS: at 87.34% examples, 49333 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:44,657 : INFO : EPOCH 8 - PROGRESS: at 89.42% examples, 49305 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:45,792 : INFO : EPOCH 8 - PROGRESS: at 96.18% examples, 49447 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:47,057 : INFO : EPOCH 8 - PROGRESS: at 98.64% examples, 49409 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:47,406 : INFO : worker thread finished; awaiting finish of 2 more threads\n    2019-02-19 22:48:47,545 : INFO : worker thread finished; awaiting finish of 1 more threads\n    2019-02-19 22:48:47,555 : INFO : worker thread finished; awaiting finish of 0 more threads\n    2019-02-19 22:48:47,556 : INFO : EPOCH - 8 : training on 2621785 raw words (1826499 effective words) took 36.8s, 49641 effective words/s\n    2019-02-19 22:48:48,633 : INFO : EPOCH 9 - PROGRESS: at 2.40% examples, 43371 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:49,709 : INFO : EPOCH 9 - PROGRESS: at 4.99% examples, 41054 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:50,746 : INFO : EPOCH 9 - PROGRESS: at 7.81% examples, 43709 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:52,023 : INFO : EPOCH 9 - PROGRESS: at 10.78% examples, 44029 words/s, in_qsize 6, out_qsize 1\n    2019-02-19 22:48:53,186 : INFO : EPOCH 9 - PROGRESS: at 13.99% examples, 45179 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:54,357 : INFO : EPOCH 9 - PROGRESS: at 16.37% examples, 44818 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:55,622 : INFO : EPOCH 9 - PROGRESS: at 18.95% examples, 45311 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:56,728 : INFO : EPOCH 9 - PROGRESS: at 21.07% examples, 46381 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:57,757 : INFO : EPOCH 9 - PROGRESS: at 23.32% examples, 47607 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:58,873 : INFO : EPOCH 9 - PROGRESS: at 25.76% examples, 47671 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:48:59,963 : INFO : EPOCH 9 - PROGRESS: at 28.31% examples, 48143 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:00,976 : INFO : EPOCH 9 - PROGRESS: at 31.76% examples, 49104 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:02,061 : INFO : EPOCH 9 - PROGRESS: at 34.87% examples, 49385 words/s, in_qsize 5, out_qsize 1\n    2019-02-19 22:49:03,043 : INFO : EPOCH 9 - PROGRESS: at 37.25% examples, 50030 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:04,085 : INFO : EPOCH 9 - PROGRESS: at 39.31% examples, 50130 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:49:05,285 : INFO : EPOCH 9 - PROGRESS: at 42.31% examples, 50199 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:06,307 : INFO : EPOCH 9 - PROGRESS: at 44.67% examples, 50023 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:07,397 : INFO : EPOCH 9 - PROGRESS: at 47.46% examples, 50394 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:49:08,542 : INFO : EPOCH 9 - PROGRESS: at 52.18% examples, 50709 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:09,669 : INFO : EPOCH 9 - PROGRESS: at 56.76% examples, 51028 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:49:10,825 : INFO : EPOCH 9 - PROGRESS: at 61.36% examples, 51556 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:49:11,932 : INFO : EPOCH 9 - PROGRESS: at 66.05% examples, 51852 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:13,033 : INFO : EPOCH 9 - PROGRESS: at 70.47% examples, 52223 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:14,042 : INFO : EPOCH 9 - PROGRESS: at 74.62% examples, 52270 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:15,284 : INFO : EPOCH 9 - PROGRESS: at 79.01% examples, 52460 words/s, in_qsize 6, out_qsize 1\n    2019-02-19 22:49:16,389 : INFO : EPOCH 9 - PROGRESS: at 82.26% examples, 52624 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:17,514 : INFO : EPOCH 9 - PROGRESS: at 86.16% examples, 52974 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:18,534 : INFO : EPOCH 9 - PROGRESS: at 87.92% examples, 53073 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:19,590 : INFO : EPOCH 9 - PROGRESS: at 92.95% examples, 53051 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:20,605 : INFO : EPOCH 9 - PROGRESS: at 97.44% examples, 53457 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:21,331 : INFO : worker thread finished; awaiting finish of 2 more threads\n    2019-02-19 22:49:21,434 : INFO : worker thread finished; awaiting finish of 1 more threads\n    2019-02-19 22:49:21,515 : INFO : worker thread finished; awaiting finish of 0 more threads\n    2019-02-19 22:49:21,517 : INFO : EPOCH - 9 : training on 2621785 raw words (1825968 effective words) took 33.9s, 53816 effective words/s\n    2019-02-19 22:49:22,779 : INFO : EPOCH 10 - PROGRESS: at 3.36% examples, 47151 words/s, in_qsize 6, out_qsize 1\n    2019-02-19 22:49:23,893 : INFO : EPOCH 10 - PROGRESS: at 7.03% examples, 52652 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:24,941 : INFO : EPOCH 10 - PROGRESS: at 10.34% examples, 55389 words/s, in_qsize 4, out_qsize 1\n    2019-02-19 22:49:25,967 : INFO : EPOCH 10 - PROGRESS: at 13.99% examples, 57242 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:27,015 : INFO : EPOCH 10 - PROGRESS: at 16.67% examples, 56836 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:28,065 : INFO : EPOCH 10 - PROGRESS: at 19.46% examples, 57928 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:49:29,232 : INFO : EPOCH 10 - PROGRESS: at 21.69% examples, 57811 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:30,242 : INFO : EPOCH 10 - PROGRESS: at 24.62% examples, 58844 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:31,442 : INFO : EPOCH 10 - PROGRESS: at 27.78% examples, 58947 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:32,497 : INFO : EPOCH 10 - PROGRESS: at 30.83% examples, 58787 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:33,588 : INFO : EPOCH 10 - PROGRESS: at 34.85% examples, 59211 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:49:34,632 : INFO : EPOCH 10 - PROGRESS: at 36.68% examples, 58107 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:35,655 : INFO : EPOCH 10 - PROGRESS: at 38.69% examples, 57703 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:36,817 : INFO : EPOCH 10 - PROGRESS: at 41.62% examples, 57321 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:37,834 : INFO : EPOCH 10 - PROGRESS: at 44.67% examples, 57541 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:38,898 : INFO : EPOCH 10 - PROGRESS: at 47.46% examples, 57682 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:49:40,016 : INFO : EPOCH 10 - PROGRESS: at 52.18% examples, 57584 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:41,150 : INFO : EPOCH 10 - PROGRESS: at 56.72% examples, 57537 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:49:42,253 : INFO : EPOCH 10 - PROGRESS: at 60.88% examples, 57584 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:49:43,279 : INFO : EPOCH 10 - PROGRESS: at 65.61% examples, 57831 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:44,280 : INFO : EPOCH 10 - PROGRESS: at 69.09% examples, 57763 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:45,362 : INFO : EPOCH 10 - PROGRESS: at 74.23% examples, 57827 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:46,364 : INFO : EPOCH 10 - PROGRESS: at 77.28% examples, 57474 words/s, in_qsize 6, out_qsize 1\n    2019-02-19 22:49:47,512 : INFO : EPOCH 10 - PROGRESS: at 80.50% examples, 57078 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:49:48,541 : INFO : EPOCH 10 - PROGRESS: at 82.94% examples, 56715 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:49,647 : INFO : EPOCH 10 - PROGRESS: at 86.55% examples, 56723 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:50,732 : INFO : EPOCH 10 - PROGRESS: at 87.89% examples, 56324 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:49:51,765 : INFO : EPOCH 10 - PROGRESS: at 92.95% examples, 56237 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:49:52,936 : INFO : EPOCH 10 - PROGRESS: at 97.21% examples, 56066 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:53,865 : INFO : worker thread finished; awaiting finish of 2 more threads\n    2019-02-19 22:49:54,023 : INFO : EPOCH 10 - PROGRESS: at 99.76% examples, 56097 words/s, in_qsize 1, out_qsize 1\n    2019-02-19 22:49:54,031 : INFO : worker thread finished; awaiting finish of 1 more threads\n    2019-02-19 22:49:54,040 : INFO : worker thread finished; awaiting finish of 0 more threads\n    2019-02-19 22:49:54,041 : INFO : EPOCH - 10 : training on 2621785 raw words (1827620 effective words) took 32.5s, 56248 effective words/s\n    2019-02-19 22:49:55,191 : INFO : EPOCH 11 - PROGRESS: at 2.80% examples, 45445 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:49:56,379 : INFO : EPOCH 11 - PROGRESS: at 6.76% examples, 50443 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:49:57,622 : INFO : EPOCH 11 - PROGRESS: at 9.85% examples, 50947 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:58,682 : INFO : EPOCH 11 - PROGRESS: at 13.27% examples, 51717 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:49:59,866 : INFO : EPOCH 11 - PROGRESS: at 16.04% examples, 51312 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:01,055 : INFO : EPOCH 11 - PROGRESS: at 18.99% examples, 52424 words/s, in_qsize 5, out_qsize 1\n    2019-02-19 22:50:02,137 : INFO : EPOCH 11 - PROGRESS: at 21.11% examples, 52557 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:03,162 : INFO : EPOCH 11 - PROGRESS: at 23.32% examples, 53285 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:04,280 : INFO : EPOCH 11 - PROGRESS: at 26.13% examples, 53383 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:05,413 : INFO : EPOCH 11 - PROGRESS: at 28.95% examples, 53729 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:06,431 : INFO : EPOCH 11 - PROGRESS: at 32.75% examples, 54346 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:50:07,576 : INFO : EPOCH 11 - PROGRESS: at 36.01% examples, 54793 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:08,581 : INFO : EPOCH 11 - PROGRESS: at 38.19% examples, 55170 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:09,766 : INFO : EPOCH 11 - PROGRESS: at 41.30% examples, 55321 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:10,830 : INFO : EPOCH 11 - PROGRESS: at 44.07% examples, 55079 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:11,850 : INFO : EPOCH 11 - PROGRESS: at 46.83% examples, 55422 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:13,004 : INFO : EPOCH 11 - PROGRESS: at 51.19% examples, 55380 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:14,051 : INFO : EPOCH 11 - PROGRESS: at 55.83% examples, 55716 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:15,083 : INFO : EPOCH 11 - PROGRESS: at 59.64% examples, 55703 words/s, in_qsize 4, out_qsize 1\n    2019-02-19 22:50:16,168 : INFO : EPOCH 11 - PROGRESS: at 64.46% examples, 56198 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:17,177 : INFO : EPOCH 11 - PROGRESS: at 68.02% examples, 56202 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:18,233 : INFO : EPOCH 11 - PROGRESS: at 73.11% examples, 56381 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:19,379 : INFO : EPOCH 11 - PROGRESS: at 77.65% examples, 56603 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:20,514 : INFO : EPOCH 11 - PROGRESS: at 80.83% examples, 56291 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:21,684 : INFO : EPOCH 11 - PROGRESS: at 84.02% examples, 56175 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:22,775 : INFO : EPOCH 11 - PROGRESS: at 87.34% examples, 56505 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:50:23,821 : INFO : EPOCH 11 - PROGRESS: at 91.26% examples, 56641 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:24,940 : INFO : EPOCH 11 - PROGRESS: at 96.99% examples, 56764 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:25,909 : INFO : worker thread finished; awaiting finish of 2 more threads\n    2019-02-19 22:50:26,085 : INFO : EPOCH 11 - PROGRESS: at 99.76% examples, 56874 words/s, in_qsize 1, out_qsize 1\n    2019-02-19 22:50:26,097 : INFO : worker thread finished; awaiting finish of 1 more threads\n    2019-02-19 22:50:26,105 : INFO : worker thread finished; awaiting finish of 0 more threads\n    2019-02-19 22:50:26,106 : INFO : EPOCH - 11 : training on 2621785 raw words (1826530 effective words) took 32.0s, 57024 effective words/s\n    2019-02-19 22:50:27,222 : INFO : EPOCH 12 - PROGRESS: at 2.81% examples, 47453 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:28,269 : INFO : EPOCH 12 - PROGRESS: at 6.76% examples, 55027 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:29,308 : INFO : EPOCH 12 - PROGRESS: at 9.85% examples, 57362 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:30,356 : INFO : EPOCH 12 - PROGRESS: at 13.27% examples, 56716 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:31,642 : INFO : EPOCH 12 - PROGRESS: at 14.77% examples, 48702 words/s, in_qsize 6, out_qsize 2\n    2019-02-19 22:50:32,710 : INFO : EPOCH 12 - PROGRESS: at 16.67% examples, 47365 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:33,755 : INFO : EPOCH 12 - PROGRESS: at 19.23% examples, 48804 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:34,966 : INFO : EPOCH 12 - PROGRESS: at 21.31% examples, 48877 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:36,018 : INFO : EPOCH 12 - PROGRESS: at 23.00% examples, 48408 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:50:37,055 : INFO : EPOCH 12 - PROGRESS: at 25.83% examples, 49356 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:38,100 : INFO : EPOCH 12 - PROGRESS: at 28.32% examples, 49877 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:50:39,121 : INFO : EPOCH 12 - PROGRESS: at 31.29% examples, 50151 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:40,148 : INFO : EPOCH 12 - PROGRESS: at 34.55% examples, 50429 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:41,155 : INFO : EPOCH 12 - PROGRESS: at 36.68% examples, 50631 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:42,263 : INFO : EPOCH 12 - PROGRESS: at 39.00% examples, 50902 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:43,455 : INFO : EPOCH 12 - PROGRESS: at 42.31% examples, 51328 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:44,606 : INFO : EPOCH 12 - PROGRESS: at 44.98% examples, 51106 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:45,624 : INFO : EPOCH 12 - PROGRESS: at 48.61% examples, 51992 words/s, in_qsize 5, out_qsize 1\n    2019-02-19 22:50:46,763 : INFO : EPOCH 12 - PROGRESS: at 53.72% examples, 52584 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:47,806 : INFO : EPOCH 12 - PROGRESS: at 58.25% examples, 53025 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:50:48,942 : INFO : EPOCH 12 - PROGRESS: at 62.28% examples, 53196 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:49,953 : INFO : EPOCH 12 - PROGRESS: at 66.05% examples, 53036 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:50,992 : INFO : EPOCH 12 - PROGRESS: at 68.44% examples, 52524 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:52,153 : INFO : EPOCH 12 - PROGRESS: at 72.57% examples, 52085 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:53,192 : INFO : EPOCH 12 - PROGRESS: at 76.01% examples, 51922 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:54,239 : INFO : EPOCH 12 - PROGRESS: at 78.84% examples, 51729 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:50:55,383 : INFO : EPOCH 12 - PROGRESS: at 81.86% examples, 51632 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:56,513 : INFO : EPOCH 12 - PROGRESS: at 84.73% examples, 51519 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:57,535 : INFO : EPOCH 12 - PROGRESS: at 86.92% examples, 51212 words/s, in_qsize 5, out_qsize 1\n    2019-02-19 22:50:58,542 : INFO : EPOCH 12 - PROGRESS: at 88.68% examples, 51367 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:50:59,734 : INFO : EPOCH 12 - PROGRESS: at 95.93% examples, 51363 words/s, in_qsize 6, out_qsize 0\n    2019-02-19 22:51:00,855 : INFO : EPOCH 12 - PROGRESS: at 97.68% examples, 51060 words/s, in_qsize 5, out_qsize 0\n    2019-02-19 22:51:01,488 : INFO : worker thread finished; awaiting finish of 2 more threads\n    2019-02-19 22:51:01,634 : INFO : worker thread finished; awaiting finish of 1 more threads\n    2019-02-19 22:51:01,691 : INFO : worker thread finished; awaiting finish of 0 more threads\n    2019-02-19 22:51:01,700 : INFO : EPOCH - 12 : training on 2621785 raw words (1825775 effective words) took 35.5s, 51365 effective words/s\n    2019-02-19 22:51:01,707 : INFO : training on a 31461420 raw words (21919033 effective words) took 425.4s, 51524 effective words/s\n\n\n    model trained!\n\n\nNow, let's query our model and find the top 3 words that are similar to \"man\".\n\n*(if a warning about type conversion is displayed, you can ignore it!)*\n\n\n```python\ntry:\n    print(vec_model.wv.most_similar(positive=\"man\", topn=3))\nexcept Exception as ex:\n    print(ex)\n```\n\n    2019-02-19 22:51:07,444 : INFO : precomputing L2-norms of word weight vectors\n\n\n    [('person', 0.6781350374221802), ('woman', 0.5695133805274963), ('gentleman', 0.5685442686080933)]\n\n\nOK, what are the 3 most similar words to \"woman\"?\n\n\n```python\ntry:\n    print(vec_model.wv.most_similar(positive=\"woman\", topn=3))\nexcept Exception as ex:\n    print(ex)\n```\n\n    [('lady', 0.7256807684898376), ('girl', 0.6625826358795166), ('child', 0.6439361572265625)]\n\n\nLet's try something a little more complex, let's find similar words to \"woman\" and \"father\" that are not similar to \"man\". Another way to think about this is, * **woman** is to **???** as **man** is to **father** *.\n\n\n```python\ntry:\n    print(vec_model.wv.most_similar(positive=[\"woman\", \"father\"], negative=[\"man\"], topn=3))\nexcept Exception as ex:\n    print(ex)\n```\n\n    [('mother', 0.730557918548584), ('sister', 0.7226352095603943), ('husband', 0.7142006754875183)]\n\n\nOK, how about the other way around? * **man** is to **???** as **woman** is to **mother** *.\n\n\n```python\ntry:\n    print(vec_model.wv.most_similar(positive=[\"man\", \"mother\"], negative=[\"woman\"], topn=3))\nexcept Exception as ex:\n    print(ex)\n```\n\n    [('father', 0.6297397613525391), ('brother', 0.5702896118164062), ('master', 0.5421998500823975)]\n\n\nHow about * **man** is to **???** as **woman** is to **queen** *?\n\n\n```python\ntry:\n    print(vec_model.wv.most_similar(positive=[\"man\", \"queen\"], negative=[\"woman\"], topn=3))\nexcept Exception as ex:\n    print(ex)\n```\n\n    [('king', 0.5152169466018677), ('Solomon', 0.47591426968574524), ('priest', 0.4738014340400696)]\n\n\nAnd vice-versa: * **woman** is to **???** as **man** is to **king** *?\n\n\n```python\ntry:\n    print(vec_model.wv.most_similar(positive=[\"woman\", \"king\"], negative=[\"man\"], topn=3))\nexcept Exception as ex:\n    print(ex)\n```\n\n    [('daughter', 0.5806741714477539), ('queen', 0.5728534460067749), ('Esther', 0.5270494818687439)]\n\n\nHow about * **she** is to **???** as **he** is to **his** *?\n\n\n```python\ntry:\n    print(vec_model.wv.most_similar(positive=[\"she\", \"his\"], negative=[\"he\"], topn=3))\nexcept Exception as ex:\n    print(ex)\n```\n\n    [('her', 0.8057565093040466), ('herself', 0.6234375238418579), ('Her', 0.6186090707778931)]\n\n\nAnother thing we can use the model for is to predict matches and non-matches. So for example, we can find the odd one out:\n\n\n```python\ntry:\n    print(vec_model.wv.doesnt_match(\"cat flower horse dog\".split()))\nexcept Exception as ex:\n    print(ex)\n```\n\n    flower\n\n\n## Learn More\nYou can learn more about NLTK from the [NLTK Book](http://www.nltk.org/book/).\nFor more information about using SciKit-Learn to work with text data, see the [SciKit-Learn documentation](http://scikit-learn.org/stable/tutorial/text_analytics/working_with_text_data.html). To learn about using Word2Vec in Gensim, see the [Gensim Documentation](https://radimrehurek.com/gensim/models/word2vec.html)\n", "meta": {"hexsha": "da589e8215aa93560e39d679f4eb5a7ff2b15074", "size": 572337, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Text Analytics Fundamentals.ipynb", "max_stars_repo_name": "GraemeMalcolm/NLP", "max_stars_repo_head_hexsha": "6535e8fbae7235b5e5f0b8922f88f48132f87679", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-06T16:14:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-06T16:14:44.000Z", "max_issues_repo_path": "Text Analytics Fundamentals.ipynb", "max_issues_repo_name": "GraemeMalcolm/NLP", "max_issues_repo_head_hexsha": "6535e8fbae7235b5e5f0b8922f88f48132f87679", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Text Analytics Fundamentals.ipynb", "max_forks_repo_name": "GraemeMalcolm/NLP", "max_forks_repo_head_hexsha": "6535e8fbae7235b5e5f0b8922f88f48132f87679", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 555.6669902913, "max_line_length": 66382, "alphanum_fraction": 0.8622542313, "converted": true, "num_tokens": 55966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10818895456207037, "lm_q2_score": 0.03567855292846366, "lm_q1q2_score": 0.003860025341617978}}
{"text": "# Information\n\n## RAM Info\n\n\n```python\n!cat /proc/meminfo\n```\n\n    MemTotal:       13335276 kB\n    MemFree:         4100312 kB\n    MemAvailable:   11245716 kB\n    Buffers:           99588 kB\n    Cached:          6936900 kB\n    SwapCached:            0 kB\n    Active:          1691180 kB\n    Inactive:        6867788 kB\n    Active(anon):    1370056 kB\n    Inactive(anon):    12648 kB\n    Active(file):     321124 kB\n    Inactive(file):  6855140 kB\n    Unevictable:           0 kB\n    Mlocked:               0 kB\n    SwapTotal:             0 kB\n    SwapFree:              0 kB\n    Dirty:               308 kB\n    Writeback:             4 kB\n    AnonPages:       1522444 kB\n    Mapped:           983000 kB\n    Shmem:             13204 kB\n    Slab:             342624 kB\n    SReclaimable:     294580 kB\n    SUnreclaim:        48044 kB\n    KernelStack:        4656 kB\n    PageTables:        12836 kB\n    NFS_Unstable:          0 kB\n    Bounce:                0 kB\n    WritebackTmp:          0 kB\n    CommitLimit:     6667636 kB\n    Committed_AS:    3580880 kB\n    VmallocTotal:   34359738367 kB\n    VmallocUsed:           0 kB\n    VmallocChunk:          0 kB\n    AnonHugePages:         0 kB\n    ShmemHugePages:        0 kB\n    ShmemPmdMapped:        0 kB\n    HugePages_Total:       0\n    HugePages_Free:        0\n    HugePages_Rsvd:        0\n    HugePages_Surp:        0\n    Hugepagesize:       2048 kB\n    DirectMap4k:      280564 kB\n    DirectMap2M:     7059456 kB\n    DirectMap1G:     8388608 kB\n\n\n\n```python\n\n```\n\n## CPU Info\n\n\n```python\n!cat /proc/cpuinfo\n```\n\n    processor\t: 0\n    vendor_id\t: GenuineIntel\n    cpu family\t: 6\n    model\t\t: 79\n    model name\t: Intel(R) Xeon(R) CPU @ 2.20GHz\n    stepping\t: 0\n    microcode\t: 0x1\n    cpu MHz\t\t: 2200.000\n    cache size\t: 56320 KB\n    physical id\t: 0\n    siblings\t: 2\n    core id\t\t: 0\n    cpu cores\t: 1\n    apicid\t\t: 0\n    initial apicid\t: 0\n    fpu\t\t: yes\n    fpu_exception\t: yes\n    cpuid level\t: 13\n    wp\t\t: yes\n    flags\t\t: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single pti ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm rdseed adx smap xsaveopt arat arch_capabilities\n    bugs\t\t: cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf\n    bogomips\t: 4400.00\n    clflush size\t: 64\n    cache_alignment\t: 64\n    address sizes\t: 46 bits physical, 48 bits virtual\n    power management:\n    \n    processor\t: 1\n    vendor_id\t: GenuineIntel\n    cpu family\t: 6\n    model\t\t: 79\n    model name\t: Intel(R) Xeon(R) CPU @ 2.20GHz\n    stepping\t: 0\n    microcode\t: 0x1\n    cpu MHz\t\t: 2200.000\n    cache size\t: 56320 KB\n    physical id\t: 0\n    siblings\t: 2\n    core id\t\t: 0\n    cpu cores\t: 1\n    apicid\t\t: 1\n    initial apicid\t: 1\n    fpu\t\t: yes\n    fpu_exception\t: yes\n    cpuid level\t: 13\n    wp\t\t: yes\n    flags\t\t: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single pti ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm rdseed adx smap xsaveopt arat arch_capabilities\n    bugs\t\t: cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf\n    bogomips\t: 4400.00\n    clflush size\t: 64\n    cache_alignment\t: 64\n    address sizes\t: 46 bits physical, 48 bits virtual\n    power management:\n    \n\n\n# GPU Info\n\n\n```python\n!nvidia-smi\n```\n\n    Sat Jul 20 10:23:39 2019       \n    +-----------------------------------------------------------------------------+\n    | NVIDIA-SMI 418.67       Driver Version: 410.79       CUDA Version: 10.0     |\n    |-------------------------------+----------------------+----------------------+\n    | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n    | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n    |===============================+======================+======================|\n    |   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |\n    | N/A   68C    P0    31W /  70W |    464MiB / 15079MiB |      0%      Default |\n    +-------------------------------+----------------------+----------------------+\n                                                                                   \n    +-----------------------------------------------------------------------------+\n    | Processes:                                                       GPU Memory |\n    |  GPU       PID   Type   Process name                             Usage      |\n    |=============================================================================|\n    +-----------------------------------------------------------------------------+\n\n\n# Current Directory\n\n\n```python\n!pwd\n```\n\n    /content\n\n\n# Download A File\n\n\n```python\n!wget http://nlp.stanford.edu/data/glove.6B.zip\n```\n\n    --2019-07-20 10:33:46--  http://nlp.stanford.edu/data/glove.6B.zip\n    Resolving nlp.stanford.edu (nlp.stanford.edu)... 171.64.67.140\n    Connecting to nlp.stanford.edu (nlp.stanford.edu)|171.64.67.140|:80... connected.\n    HTTP request sent, awaiting response... 302 Found\n    Location: https://nlp.stanford.edu/data/glove.6B.zip [following]\n    --2019-07-20 10:33:46--  https://nlp.stanford.edu/data/glove.6B.zip\n    Connecting to nlp.stanford.edu (nlp.stanford.edu)|171.64.67.140|:443... connected.\n    HTTP request sent, awaiting response... 301 Moved Permanently\n    Location: http://downloads.cs.stanford.edu/nlp/data/glove.6B.zip [following]\n    --2019-07-20 10:33:47--  http://downloads.cs.stanford.edu/nlp/data/glove.6B.zip\n    Resolving downloads.cs.stanford.edu (downloads.cs.stanford.edu)... 171.64.64.22\n    Connecting to downloads.cs.stanford.edu (downloads.cs.stanford.edu)|171.64.64.22|:80... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 862182613 (822M) [application/zip]\n    Saving to: \u2018glove.6B.zip\u2019\n    \n    glove.6B.zip        100%[===================>] 822.24M  25.4MB/s    in 33s     \n    \n    2019-07-20 10:34:20 (24.9 MB/s) - \u2018glove.6B.zip\u2019 saved [862182613/862182613]\n    \n\n\n# Git\n\n\n```python\n!rm -rf /content/docs\n```\n\n\n```python\n!git clone https://github.com/tensorflow/docs.git\n%cd docs\n!ls\n\n%cd\n```\n\n    Cloning into 'docs'...\n    remote: Enumerating objects: 37, done.\u001b[K\n    remote: Counting objects: 100% (37/37), done.\u001b[K\n    remote: Compressing objects: 100% (25/25), done.\u001b[K\n    remote: Total 86773 (delta 19), reused 21 (delta 12), pack-reused 86736\u001b[K\n    Receiving objects: 100% (86773/86773), 64.93 MiB | 15.80 MiB/s, done.\n    Resolving deltas: 100% (65423/65423), done.\n    /root/docs\n    AUTHORS  CODEOWNERS  CONTRIBUTING.md  LICENSE  README.md  setup.py  site  tools\n    /root\n\n\n# Markdown\n\n\n#Heading 1\n##Heading 2\n###Heading 3\n####Heading 4\n#####Heading 5\n######Heading 6\t\n\n---\n\nParagraph\ntext `Inline Code` text\t\t\n~~Mistaken text.~~\t\n*Italics*\t\n**Bold**\t\n\n---\n\nTasks\n- [ ] a task list item\n- [ ] list syntax required\n- [ ] normal **formatting**\n- [ ] incomplete\n- [x] completed\n\n---\n\nCode Blocks\n\n    4 space indention\n    makes full-width\n    standard code blocks\n\n```js\nvar now = new Date();\n\nvar days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');\n\nvar months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');\n\nvar date = ((now.getDate()<10) ? \"0\" : \"\")+ now.getDate();\n\nfunction fourdigits(number)\t{\n\treturn (number < 1000) ? number + 1900 : number;\n\t\t\t\t\t\t\t\t}\ntoday =  days[now.getDay()] + \", \" +\n         months[now.getMonth()] + \" \" +\n         date + \", \" +\n         (fourdigits(now.getYear())) ;\n\ndocument.write(today);\n```\n\n```css\n#sc_drag_area {\n  height:100px;\n  left:150px;\n  position: absolute;\n  top:100px;\n  width:250px;\n  z-index: 9999;\n}\n```\n\n---\n\n* List item one\n* List item two\n    * A nested item\n\n---\n\n1. Number list item one\t\t\n\t1.1. A nested item\n2. Number list item two\n3. Number list item three\n\n---\n\n> Quote\n> \n> Second line Quote\n\n---\n\nStandard link =  http://ghost.org\t\n[Custom Text Link](http://ghost.org)\n\n---\n\n\n\n---\n\n# Table\n\n| Left-Aligned  | Center Aligned  | Right Aligned |\n| :------------ |:---------------:| -----:|\n| col 3 is      | some wordy text | \\$1600 |\n| col 2 is      | centered        |   \\$12 |\n| zebra stripes | are neat        |    \\$1 |\n\n\n# Equations\n\n$$\n\\begin{array}{c}\ny_1 \\\\\\\ny_2 \\mathtt{t}_i \\\\\\\nz_{3,4}\n\\end{array}\n$$\n\n$$\n\\begin{array}{c}\ny_1 \\cr\ny_2 \\mathtt{t}_i \\cr\ny_{3}\n\\end{array}\n$$\n\n$$\\begin{eqnarray}\nx' &=& &x \\sin\\phi &+& z \\cos\\phi \\\\\nz' &=& - &x \\cos\\phi &+& z \\sin\\phi \\\\\n\\end{eqnarray}$$\n\n$$\nx=4\n$$\n\n\\begin{equation}\nE = F \\cdot s \n\\end{equation}\n\n# Forms\n\nForms provide an easy way to parameterize code. From a code cell, select **Insert \u2192 Add form field**.  When you change the value in a form, the corresponding value in the code will change. \n\n\n```python\n#@title String fields\n\ntext = 'value' #@param {type:\"string\"}\ndropdown = '1st option' #@param [\"1st option\", \"2nd option\", \"3rd option\"]\ntext_and_dropdown = 'value' #@param [\"1st option\", \"2nd option\", \"3rd option\"] {allow-input: true}\n\nprint(text)\nprint(dropdown)\nprint(text_and_dropdown)\n```\n\n    value\n    1st option\n    value\n\n\n\n```python\n#@title Raw fields\n\nraw_input = None #@param {type:\"raw\"}\nraw_dropdown = raw_input #@param [1, \"raw_input\", \"False\", \"'string'\"] {type:\"raw\"}\n\nprint(raw_input)\nprint(raw_dropdown)\n```\n\n    None\n    None\n\n\n\n```python\n#@title Date fields\ndate_input = '2018-03-22' #@param {type:\"date\"}\n\nprint(date_input)\n```\n\n    2018-03-22\n\n\n\n```python\n#@title Number fields\nnumber_input = 10.0 #@param {type:\"number\"}\nnumber_slider = 1 #@param {type:\"slider\", min:-1, max:1, step:0.1}\n\ninteger_input = 10 #@param {type:\"integer\"}\ninteger_slider = 0 #@param {type:\"slider\", min:0, max:100, step:1}\n\nprint(number_input)\nprint(number_slider)\n\nprint(integer_input)\nprint(integer_slider)\n```\n\n    10.0\n    0\n    10\n    1\n\n\n\n```python\n#@title Boolean fields\nboolean_checkbox = True #@param {type:\"boolean\"}\nboolean_dropdown = True #@param [\"False\", \"True\"] {type:\"raw\"}\n\nprint(boolean_checkbox)\nprint(boolean_dropdown)\n```\n\n    True\n    True\n\n\n\n```python\n#@title ## Markdown\n#@markdown You can also include Markdown in forms.\n\n#@markdown ---\n#@markdown ### Enter a file path:\nfile_path = \"\" #@param {type:\"string\"}\n#@markdown ---\n\n\n```\n\n# Hiding code\n\nYou can change the view of the form by selecting **Edit \u2192 Show/hide code** or using the toolbar above the selected code cell. You can see both code and the form, just the form, or just the code.\n\n\n```python\n#@title Double click on this line in the code cell. { display-mode: \"form\" }\n\noption1 = 'A' #@param [\"A\", \"B\", \"C\"]\nprint('You selected', option1)\n\n```\n\n\n```python\n#@title After running this cell manually, it will auto-run if you change the selected value. { run: \"auto\" }\n\noption2 = \"A\" #@param [\"A\", \"B\", \"C\"]\nprint('You selected', option2)\n\n```\n\n# Mounting\n\n\n```python\n#@title ## Mounting Gdrive\n\nUSE_G_COLAB = True #@param {type:\"boolean\"}\n\nif USE_G_COLAB:\n    from google.colab import drive\n\n    \n    drive.mount('/content/drive', force_remount=True)\n```\n\n\n```python\n#@title ## Project Root\n\nroot_dir = ''\n\nif USE_G_COLAB:\n    root_dir = '/content/drive/My Drive/workshops/2019_07_21/sessions_01/' #@param {type:\"string\"}\n```\n", "meta": {"hexsha": "44eb86800609c19da2b940b5d0ce1b43a6d09d8f", "size": 22575, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ws-dl-tf2-s1/sessions/01/Notebook 001.ipynb", "max_stars_repo_name": "i-ml/tf2-workshop", "max_stars_repo_head_hexsha": "2bced4cfa528ac20f12098a7c5feb52ecf6b81e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ws-dl-tf2-s1/sessions/01/Notebook 001.ipynb", "max_issues_repo_name": "i-ml/tf2-workshop", "max_issues_repo_head_hexsha": "2bced4cfa528ac20f12098a7c5feb52ecf6b81e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ws-dl-tf2-s1/sessions/01/Notebook 001.ipynb", "max_forks_repo_name": "i-ml/tf2-workshop", "max_forks_repo_head_hexsha": "2bced4cfa528ac20f12098a7c5feb52ecf6b81e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-07-11T18:38:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-01T09:58:27.000Z", "avg_line_length": 26.3726635514, "max_line_length": 504, "alphanum_fraction": 0.4830121816, "converted": true, "num_tokens": 3696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0980793208341535, "lm_q2_score": 0.03789242758028709, "lm_q1q2_score": 0.003716463561831904}}
{"text": "```\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```\n# \ud328\ud0a4\uc9c0 \uc124\uce58\r\n!pip install mxnet==1.6.0 gluonnlp==0.9.1 sentencepiece==0.1.91 pandas==1.0.5 transformers==2.11.0 pytorch_lightning==0.8.1 onnx onnxruntime coremltools\n```\n\n    Requirement already satisfied: mxnet==1.6.0 in /usr/local/lib/python3.6/dist-packages (1.6.0)\n    Requirement already satisfied: gluonnlp==0.9.1 in /usr/local/lib/python3.6/dist-packages (0.9.1)\n    Requirement already satisfied: sentencepiece==0.1.91 in /usr/local/lib/python3.6/dist-packages (0.1.91)\n    Requirement already satisfied: pandas==1.0.5 in /usr/local/lib/python3.6/dist-packages (1.0.5)\n    Requirement already satisfied: transformers==2.11.0 in /usr/local/lib/python3.6/dist-packages (2.11.0)\n    Requirement already satisfied: pytorch_lightning==0.8.1 in /usr/local/lib/python3.6/dist-packages (0.8.1)\n    Requirement already satisfied: onnx in /usr/local/lib/python3.6/dist-packages (1.8.0)\n    Requirement already satisfied: onnxruntime in /usr/local/lib/python3.6/dist-packages (1.6.0)\n    Collecting coremltools\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/f1/30/32f5bce33571b00f8e43e290bb4a9561956bc7f35b96dcd48f300029b23f/coremltools-4.0-cp36-none-manylinux1_x86_64.whl (3.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.4MB 4.3MB/s \n    \u001b[?25hRequirement already satisfied: graphviz<0.9.0,>=0.8.1 in /usr/local/lib/python3.6/dist-packages (from mxnet==1.6.0) (0.8.4)\n    Requirement already satisfied: requests<3,>=2.20.0 in /usr/local/lib/python3.6/dist-packages (from mxnet==1.6.0) (2.23.0)\n    Requirement already satisfied: numpy<2.0.0,>1.16.0 in /usr/local/lib/python3.6/dist-packages (from mxnet==1.6.0) (1.19.4)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.6/dist-packages (from gluonnlp==0.9.1) (20.8)\n    Requirement already satisfied: cython in /usr/local/lib/python3.6/dist-packages (from gluonnlp==0.9.1) (0.29.21)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas==1.0.5) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas==1.0.5) (2.8.1)\n    Requirement already satisfied: filelock in /usr/local/lib/python3.6/dist-packages (from transformers==2.11.0) (3.0.12)\n    Requirement already satisfied: tokenizers==0.7.0 in /usr/local/lib/python3.6/dist-packages (from transformers==2.11.0) (0.7.0)\n    Requirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from transformers==2.11.0) (0.8)\n    Requirement already satisfied: sacremoses in /usr/local/lib/python3.6/dist-packages (from transformers==2.11.0) (0.0.43)\n    Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.6/dist-packages (from transformers==2.11.0) (4.41.1)\n    Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.6/dist-packages (from transformers==2.11.0) (2019.12.20)\n    Requirement already satisfied: tensorboard>=1.14 in /usr/local/lib/python3.6/dist-packages (from pytorch_lightning==0.8.1) (2.4.0)\n    Requirement already satisfied: PyYAML>=5.1 in /usr/local/lib/python3.6/dist-packages (from pytorch_lightning==0.8.1) (5.3.1)\n    Requirement already satisfied: torch>=1.3 in /usr/local/lib/python3.6/dist-packages (from pytorch_lightning==0.8.1) (1.7.0+cu101)\n    Requirement already satisfied: future>=0.17.1 in /usr/local/lib/python3.6/dist-packages (from pytorch_lightning==0.8.1) (0.18.2)\n    Requirement already satisfied: protobuf in /usr/local/lib/python3.6/dist-packages (from onnx) (3.12.4)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from onnx) (1.15.0)\n    Requirement already satisfied: typing-extensions>=3.6.2.1 in /usr/local/lib/python3.6/dist-packages (from onnx) (3.7.4.3)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.6/dist-packages (from coremltools) (1.1.1)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from coremltools) (1.4.1)\n    Requirement already satisfied: attrs in /usr/local/lib/python3.6/dist-packages (from coremltools) (20.3.0)\n    Collecting attr\n      Downloading https://files.pythonhosted.org/packages/de/be/ddc7f84d4e087144472a38a373d3e319f51a6faf6e5fc1ae897173675f21/attr-0.3.1.tar.gz\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.20.0->mxnet==1.6.0) (2.10)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.20.0->mxnet==1.6.0) (1.24.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.20.0->mxnet==1.6.0) (2020.12.5)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.20.0->mxnet==1.6.0) (3.0.4)\n    Requirement already satisfied: pyparsing>=2.0.2 in /usr/local/lib/python3.6/dist-packages (from packaging->gluonnlp==0.9.1) (2.4.7)\n    Requirement already satisfied: joblib in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers==2.11.0) (1.0.0)\n    Requirement already satisfied: click in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers==2.11.0) (7.1.2)\n    Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorboard>=1.14->pytorch_lightning==0.8.1) (1.17.2)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.6/dist-packages (from tensorboard>=1.14->pytorch_lightning==0.8.1) (0.4.2)\n    Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard>=1.14->pytorch_lightning==0.8.1) (51.0.0)\n    Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tensorboard>=1.14->pytorch_lightning==0.8.1) (1.0.1)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard>=1.14->pytorch_lightning==0.8.1) (1.7.0)\n    Requirement already satisfied: grpcio>=1.24.3 in /usr/local/lib/python3.6/dist-packages (from tensorboard>=1.14->pytorch_lightning==0.8.1) (1.32.0)\n    Requirement already satisfied: absl-py>=0.4 in /usr/local/lib/python3.6/dist-packages (from tensorboard>=1.14->pytorch_lightning==0.8.1) (0.10.0)\n    Requirement already satisfied: wheel>=0.26; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from tensorboard>=1.14->pytorch_lightning==0.8.1) (0.36.2)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard>=1.14->pytorch_lightning==0.8.1) (3.3.3)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy->coremltools) (1.1.0)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard>=1.14->pytorch_lightning==0.8.1) (4.2.0)\n    Requirement already satisfied: rsa<5,>=3.1.4; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard>=1.14->pytorch_lightning==0.8.1) (4.6)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard>=1.14->pytorch_lightning==0.8.1) (0.2.8)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard>=1.14->pytorch_lightning==0.8.1) (1.3.0)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from markdown>=2.6.8->tensorboard>=1.14->pytorch_lightning==0.8.1) (3.3.0)\n    Requirement already satisfied: pyasn1>=0.1.3 in /usr/local/lib/python3.6/dist-packages (from rsa<5,>=3.1.4; python_version >= \"3\"->google-auth<2,>=1.6.3->tensorboard>=1.14->pytorch_lightning==0.8.1) (0.4.8)\n    Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard>=1.14->pytorch_lightning==0.8.1) (3.1.0)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata; python_version < \"3.8\"->markdown>=2.6.8->tensorboard>=1.14->pytorch_lightning==0.8.1) (3.4.0)\n    Building wheels for collected packages: attr\n      Building wheel for attr (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for attr: filename=attr-0.3.1-cp36-none-any.whl size=2459 sha256=5b42000be0dd70325adeeb4e1a4b5acf1c665ee199c8ae2f4d7ce718a699a23c\n      Stored in directory: /root/.cache/pip/wheels/f0/96/9b/1f8892a707d17095b5a6eab0275da9d39e68e03a26aee2e726\n    Successfully built attr\n    Installing collected packages: attr, coremltools\n    Successfully installed attr-0.3.1 coremltools-4.0\n\n\n\n```\n# \ud3f4\ub354 \uc774\ub3d9\r\n%cd /content/drive/MyDrive/Colab Notebooks/gpt/KoGPT2-chatbot-master\r\n\r\nimport torch\r\nimport numpy as np\r\nfrom kogpt2.pytorch_kogpt2 import get_pytorch_kogpt2_model\r\nfrom gluonnlp.data import SentencepieceTokenizer\r\nfrom kogpt2.utils import get_tokenizer\r\nfrom pytorch_lightning.core.lightning import LightningModule\r\nimport coremltools as ct\r\n\r\ntok_path = get_tokenizer()\r\nmodel, vocab = get_pytorch_kogpt2_model()\r\ntok = SentencepieceTokenizer(tok_path, num_best=0, alpha=0)\r\n\r\nclass KoGPT2Chat(LightningModule):\r\n    def __init__(self, hparams, **kwargs):\r\n        super(KoGPT2Chat, self).__init__()\r\n        self.hparams = hparams\r\n        self.tok_path = tok_path\r\n        self.neg = -1e18\r\n        self.kogpt2, self.vocab = model, vocab\r\n\r\n        self.loss_function = torch.nn.CrossEntropyLoss(reduction='none')\r\n\r\n    def forward(self, inputs):\r\n        # (batch, seq_len, hiddens)\r\n        output, _ = self.kogpt2(inputs)\r\n        return output\r\n\r\n# init\r\nU_TKN = '<usr>'\r\nS_TKN = '<sys>'\r\nBOS = '<s>'\r\nEOS = '</s>'\r\nMASK = '<unused0>'\r\nSENT = '<unused1>'\r\n\r\ngpt_chat_model = KoGPT2Chat.load_from_checkpoint(\"./model_chp/model_last.ckpt\")\r\ngpt_chat_model.eval()\r\n\r\nsent_tokens = tok(\"\")\r\nsent='0'\r\ntoked = tok(sent)\r\nq_tok = tok(\"\")\r\na = ''\r\na_tok = []\r\n\r\ninput_ids = torch.LongTensor([\r\n                    vocab[U_TKN]] + vocab[q_tok] +\r\n                    vocab[EOS, SENT] + vocab[sent_tokens] +\r\n                    vocab[EOS, S_TKN] +\r\n                    vocab[a_tok]).unsqueeze(dim=0)\r\n\r\n# export\r\ntraced_model = torch.jit.trace(gpt_chat_model, input_ids)\r\ntraced_model.save(\"sample.pt\")\r\n\r\ninput_shape = ct.Shape(shape=(1, ct.RangeDim(), 512))\r\nmodel_input = ct.TensorType(shape=input_shape, dtype=np.int16)\r\n\r\n# Convert the saved PyTorch model to Core ML\r\nmlmodel = ct.convert(traced_model, inputs=[model_input])\r\nmlmodel.save('./mlmodel.mlmodel')\r\nprint(\"Export of kogpt2 mlmodel complete!\")\n```\n\n    WARNING:root:scikit-learn version 0.22.2.post1 is not supported. Minimum required version: 0.17. Maximum required version: 0.19.2. Disabling scikit-learn conversion API.\n    WARNING:root:TensorFlow version 2.4.0 detected. Last version known to be fully compatible is 2.3.1 .\n    WARNING:root:Keras version 2.4.3 detected. Last version known to be fully compatible of Keras is 2.2.4 .\n\n\n    /content/drive/MyDrive/Colab Notebooks/gpt/KoGPT2-chatbot-master\n    [\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588]\n    [\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588]\n    using cached model\n\n\n    /usr/local/lib/python3.6/dist-packages/transformers/modeling_gpt2.py:146: TracerWarning: Converting a tensor to a Python float might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!\n      w = w / (float(v.size(-1)) ** 0.5)\n    /usr/local/lib/python3.6/dist-packages/transformers/modeling_gpt2.py:148: TracerWarning: Converting a tensor to a Python index might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!\n      mask = self.bias[:, :, ns - nd : ns, :ns]\n    Converting Frontend ==> MIL Ops: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2589| 1303/1306 [00:04<00:00, 301.54 ops/s]\n    Running MIL optimization passes: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 17/17 [00:07<00:00,  2.42 passes/s]\n    Translating MIL ==> MLModel Ops: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1316/1316 [00:26<00:00, 50.06 ops/s]\n\n\n    Export of kogpt2 mlmodel complete!\n\n\n\n```\n\n```\n", "meta": {"hexsha": "69b7ff1d3ae6b7ffaae8a98dc26a1ccef70f91aa", "size": 16750, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "export_coreml.ipynb", "max_stars_repo_name": "HaloKim/KoGPT2-chatbot", "max_stars_repo_head_hexsha": "ac0628281bbd4f4c80fa57bbece3de5b7f50f86a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-01T03:01:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-01T03:01:22.000Z", "max_issues_repo_path": "export_coreml.ipynb", "max_issues_repo_name": "HaloKim/KoGPT2-chatbot", "max_issues_repo_head_hexsha": "ac0628281bbd4f4c80fa57bbece3de5b7f50f86a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "export_coreml.ipynb", "max_forks_repo_name": "HaloKim/KoGPT2-chatbot", "max_forks_repo_head_hexsha": "ac0628281bbd4f4c80fa57bbece3de5b7f50f86a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.1762452107, "max_line_length": 353, "alphanum_fraction": 0.5975522388, "converted": true, "num_tokens": 4071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11279540330049728, "lm_q2_score": 0.03161876430296234, "lm_q1q2_score": 0.0035664512714160043}}
{"text": "<a href=\"https://colab.research.google.com/github/rts1988/IntelligentTutoringSystem_Experiments/blob/master/Autodidact_Graph_Visualizations_withRoles2_Multidoc.ipynb\" target=\"_parent\"></a>\n\nUploading multiple 'documents' already processed. to be included in the main file. \n\nCompressed pickles:\nhttps://betterprogramming.pub/load-fast-load-big-with-compressed-pickles-5f311584507e#:~:text=Compressed%20pickle&text=It%20creates%20a%20pickle%20object,to%20the%20saved%20file%20automatically.&text=filename'%2C%20data)-,filename%20is%20the%20name%20of%20the%20file%20with%20no,data%20is%20any%20object.\n\n```\n# This is formatted as code\n```\n\n\n\n\n```\nimport bz2\nimport pickle\nimport _pickle as cPickle\n\n# Load any compressed pickle file\ndef decompress_pickle(file):\n data = bz2.BZ2File(file, 'rb')\n data = cPickle.load(data)\n return data\n\nfrom google.colab import files\nuploaded = files.upload()\nfilenames = list(uploaded.keys())\n\n\n```\n\n\n\n<input type=\"file\" id=\"files-0500f598-aaad-4d66-b4b8-3ff00c7b3331\" name=\"files[]\" multiple disabled\n   style=\"border:none\" />\n<output id=\"result-0500f598-aaad-4d66-b4b8-3ff00c7b3331\">\n Upload widget is only available when the cell has been executed in the\n current browser session. Please rerun this cell to enable.\n </output>\n  \n\n\n    Saving Envoy_loar.pbz2 to Envoy_loar.pbz2\n    Saving TLSwiki.pbz2 to TLSwiki.pbz2\n\n\n\n```\n# initiating aggregate Conceptdata dataframe, aggregate np_to_sent, sent_to_npflat, sent_to_tags etc.\nimport pandas as pd\nAgg_Conceptdata = pd.DataFrame() \nAll_Conceptdata = pd.DataFrame() \nAgg_np_to_sent = dict()\nAgg_sent_to_npflat = dict()\nAgg_sent_to_phen = dict()\nAgg_phen_to_sent = dict()\nAgg_att_to_sent = dict()\nAgg_sent_to_att = dict()\nAgg_ins_to_sent = dict()\nAgg_sent_to_ins = dict()\nAgg_set_to_sent = dict()\nAgg_np_to_forms = dict()\ndoc_to_np = dict()\nnp_to_doc = dict()\nAgg_df = pd.DataFrame()\nAgg_df = pd.DataFrame()\nAgg_np_to_roles = dict()\nAgg_sent_to_clt = dict()\nAgg_sents = dict()\n#Agg_sents_df = pd.DataFrame()\n#Agg_docs_df = pd.DataFrame()\nAll_df = pd.DataFrame()\n\nfor filename in filenames:\n  # download file with id\n  #downloaded = drive.CreateFile({'id':file_to_id_dict[filename]}) \n  #downloaded.GetContentFile(filename) \n  concepts = decompress_pickle(filename) \n  \n  \n\n  Conceptdata = concepts['Conceptdata']\n  sent_to_npflat = concepts['sent_to_npflat']\n  np_to_sent = concepts['np_to_sent']\n  np_to_forms = concepts['np_to_forms']\n  sent_to_phen = concepts['sent_to_phen']\n  phen_to_sent = concepts['phen_to_sent']\n  sent_to_att = concepts['sent_to_att']\n  att_to_sent = concepts['att_to_sent']\n  att_to_sent = concepts['att_to_sent']\n  ins_to_sent = concepts['ins_to_sent']\n  sent_to_ins = concepts['sent_to_ins']\n  set_to_sent = concepts['set_to_sent']\n  sent_to_set = concepts['sent_to_set']\n  np_to_roles = concepts['np_to_roles']\n  sent_to_clt = concepts['sent_to_clt']\n  sents = concepts['sents']\n  df = concepts['df']\n\n  Conceptdata['docname'] = filename\n  Agg_Conceptdata = Agg_Conceptdata.append(Conceptdata,ignore_index=True)\n\n  Agg_sent_to_clt[filename.replace(\".pbz2\",\"\")] = sent_to_clt\n  Agg_np_to_sent[filename.replace(\".pbz2\",\"\")] = np_to_sent\n  Agg_sents[filename.replace(\".pbz2\",\"\")] = sents\n  Agg_sent_to_npflat[filename.replace(\".pbz2\",\"\")] = sent_to_npflat\n\n  Agg_df = Agg_df.append(df,ignore_index=True)\n  doc_to_np[filename] = list(np_to_sent.keys())\n\n  for np in np_to_sent:\n    # if np in Agg_np_to_sent:\n    #   Agg_np_to_sent[np] = Agg_np_to_sent[np] + [(filename,s) for s in np_to_sent[np]]\n    # else:\n    #   Agg_np_to_sent[np] = [(filename,s) for s in np_to_sent[np]]\n\n    if np in np_to_doc:\n      np_to_doc[np] = np_to_doc[np] + [filename]\n    else:\n      np_to_doc[np] = [filename]\n  \n  for np in np_to_forms:\n    if np in Agg_np_to_forms:\n      Agg_np_to_forms[np] = Agg_np_to_forms[np] + np_to_forms[np]\n    else:\n      Agg_np_to_forms[np] = np_to_forms[np]\n  \n  for np in np_to_roles:\n    if np in Agg_np_to_roles:\n      Agg_np_to_roles[np] = Agg_np_to_roles[np] + np_to_roles[np]\n    else:\n      Agg_np_to_roles[np] = np_to_roles[np]\n  \n  for np in phen_to_sent:\n    if np in Agg_phen_to_sent:\n      Agg_phen_to_sent[np] = Agg_phen_to_sent[np] + [(filename,s) for s in phen_to_sent[np]]\n    else:\n      Agg_phen_to_sent[np] = [(filename,s) for s in phen_to_sent[np]]\n\n  for np in att_to_sent:\n    if np in Agg_att_to_sent:\n      Agg_att_to_sent[np] = Agg_att_to_sent[np] + [(filename,s) for s in att_to_sent[np]]\n    else:\n      Agg_att_to_sent[np] =  [(filename,s) for s in att_to_sent[np]]\n\n  for np in set_to_sent:\n    if np in Agg_set_to_sent:\n      Agg_set_to_sent[np] = Agg_set_to_sent[np] + [(filename,s) for s in set_to_sent[np]]\n    else:\n      Agg_set_to_sent[np] =  [(filename,s) for s in set_to_sent[np]]\n\n  for np in ins_to_sent:\n    if np in Agg_ins_to_sent:\n      Agg_ins_to_sent[np] = Agg_ins_to_sent[np] + [(filename,s) for s in ins_to_sent[np]]\n    else:\n      Agg_ins_to_sent[np] =  [(filename,s) for s in ins_to_sent[np]]\n\n  \n  \n\n\n```\n\n### Create concept inventory dataframe with some metrics:\n- Concept: concept phrase\n- Occurence: list of sentences in which the phrase occurs\n- Frequency: number of sentences in which the phrase occurs\n- Mean: average of sentence numbers in the text in which the phrase occurs normalized to number of sentences\n- Median: median of sentence numbers in the text in which the phrase occurs normalized to number of sentences. Lets us know if phrase occurs much more in the beginning of the text, or towards the end. can indicate how central the phrase is to the text. \n- Sdev: standard deviation of the sentences in which the phrase occurs (indicates the dispersion of the phrase in the text, is it important all throughout, or specific to a sub-topic? The higher the value, the more dispersed)\n\n\n```\nimport math\nimport numpy as num\nAll_Conceptdata = pd.DataFrame()\n\n\ndef most_common_form(np):\n  return pd.Series(Agg_np_to_forms[np]).value_counts().sort_values(ascending=False).index[0]\n\nAgg_np_to_mcform = dict()\nfor np in Agg_np_to_forms:\n  Agg_np_to_mcform[np] = most_common_form(np)\n\n\nAll_Conceptdata = Agg_Conceptdata.groupby('Concept').agg(doc_Occurence = pd.NamedAgg('docname',lambda x: list(x)),\n                                                          doc_Frequency = pd.NamedAgg('docname',lambda x: x.shape[0]),\n                                                          Raw_Frequency = pd.NamedAgg('Frequency','sum'),\n                                                          Mean = pd.NamedAgg('Mean','mean'),\n                                                          Median = pd.NamedAgg('Median','mean'),\n                                                          Sdev = pd.NamedAgg('Sdev','mean'),\n                                                          Ext_IDF = pd.NamedAgg('IDF',num.nanmin))\n\n\n\n                                                    \nAll_Conceptdata['Mean_Frequency'] =  All_Conceptdata['Raw_Frequency']/All_Conceptdata['doc_Frequency']\nAll_Conceptdata['normalized_RawFreq'] = All_Conceptdata['Raw_Frequency']/All_Conceptdata['Raw_Frequency'].max()\nAll_Conceptdata['normalized_MeanFreq'] = All_Conceptdata['Mean_Frequency']/All_Conceptdata['Mean_Frequency'].max()\nAll_Conceptdata['intIDF'] = All_Conceptdata['doc_Frequency'].apply(lambda x: math.log(len(filenames),2)-abs(math.log(1+x,2)))\nAll_Conceptdata['intmeanTFIDF'] = All_Conceptdata['normalized_MeanFreq']*All_Conceptdata['intIDF']\nfor filename in filenames:\n  colname = filename.replace(\".pbz2\",\"\")\n  All_Conceptdata = pd.merge(left = All_Conceptdata,\n                             right = Agg_Conceptdata.loc[Agg_Conceptdata['docname']==filename,['Concept','Frequency']],\n                             how='left',\n                             left_on = 'Concept',\n                             right_on = 'Concept')\n  All_Conceptdata[colname+'_TF'] = All_Conceptdata['Frequency']\n  del All_Conceptdata['Frequency']\n  All_Conceptdata[colname+'_TF'].fillna(0,inplace=True)\n  All_Conceptdata[colname+'_IntTFIDF'] = All_Conceptdata[colname+'_TF']*All_Conceptdata['intIDF']\n\nAll_Conceptdata['MCForm'] = All_Conceptdata['Concept'].apply(lambda x: Agg_np_to_mcform[x])\n\nAll_Conceptdata['role_frac'] = All_Conceptdata['Concept'].apply(lambda x: dict(pd.Series(Agg_np_to_roles[x]).value_counts(normalize=True)))\nAll_Conceptdata['phen_frac'] = All_Conceptdata['role_frac'].apply(lambda x: x.get('phen',0))\nAll_Conceptdata['att_frac'] = All_Conceptdata['role_frac'].apply(lambda x: x.get('att',0))\nAll_Conceptdata['set_frac'] = All_Conceptdata['role_frac'].apply(lambda x: x.get('set',0))\nAll_Conceptdata['ins_frac'] = All_Conceptdata['role_frac'].apply(lambda x: x.get('ins',0))\ndel All_Conceptdata['role_frac']\n\n#All_Conceptdata['phen_frac'] = All_Conceptdata\n```\n\n\n```\nAll_df = pd.DataFrame()\nAgg_df['tuple'] = Agg_df[['Concept1','Concept2']].apply(lambda x:tuple(x),axis=1)\nAll_df = Agg_df.groupby('tuple').agg(Concept1 = pd.NamedAgg('Concept1',lambda x: list(x)[0]),\n                            Concept2 = pd.NamedAgg('Concept2',lambda x: list(x)[0]),\n                            Bondstrength = pd.NamedAgg('Bondstrength','sum'),\n                            mean_dAB = pd.NamedAgg('dAB',num.nanmean),\n                            mean_dBA = pd.NamedAgg('dBA',num.nanmean),\n                            ExtIDFA = pd.NamedAgg('IDFA',num.nanmean),\n                            ExtIDFB = pd.NamedAgg('IDFB',num.nanmean),\n                            SdevA = pd.NamedAgg('SdevA',num.nanmean),\n                            SdevB = pd.NamedAgg('SdevB',num.nanmean),\n\n                            )\n\nAll_df = pd.merge(left = All_df,right = All_Conceptdata.loc[:,['Concept','Raw_Frequency']],how=\"left\",left_on = 'Concept1',right_on='Concept')\nAll_df['Raw_TFA'] = All_df['Raw_Frequency'] \nAll_df['Raw_TFA'].fillna(0)\ndel All_df['Raw_Frequency']\nAll_df['Ext_TFIDFA'] = All_df['Raw_TFA']*All_df['ExtIDFA']\n\n\nAll_df = pd.merge(left= All_df,right = All_Conceptdata.loc[:,['Concept','Raw_Frequency']],how=\"left\",left_on = 'Concept2',right_on='Concept')\nAll_df['Raw_TFB'] = All_df['Raw_Frequency'] \nAll_df['Raw_TFB'].fillna(0)\ndel All_df['Raw_Frequency']\nAll_df['Ext_TFIDFB'] = All_df['Raw_TFB']*All_df['ExtIDFB']\n\nAll_df = pd.merge(left= All_df,right = All_Conceptdata.loc[:,['Concept','MCForm']],how=\"left\",left_on = 'Concept1',right_on='Concept')\nAll_df['MCForm1'] = All_df['MCForm'] \nAll_df['MCForm1'].fillna('')\ndel All_df['MCForm']\n #All_df['Concept_x']#, All_df['Concept_y']\n\nAll_df = pd.merge(left= All_df,right = All_Conceptdata.loc[:,['Concept','MCForm']],how=\"left\",left_on = 'Concept2',right_on='Concept')\nAll_df['MCForm2'] = All_df['MCForm'] \nAll_df['MCForm2'].fillna('')\ndel All_df['MCForm'] \n\nAll_df = pd.merge(left= All_df,right = All_Conceptdata.loc[:,['Concept','phen_frac']],how=\"left\",left_on = 'Concept1',right_on='Concept')\nAll_df['phen_fracA'] = All_df['phen_frac'] \nAll_df['phen_fracA'].fillna(0)\ndel All_df['phen_frac']\n #All_df['Concept_x']#, All_df['Concept_y']\n\nAll_df = pd.merge(left= All_df,right = All_Conceptdata.loc[:,['Concept','phen_frac']],how=\"left\",left_on = 'Concept2',right_on='Concept')\nAll_df['phen_fracB'] = All_df['phen_frac'] \nAll_df['phen_fracB'].fillna(0)\ndel All_df['phen_frac']\n\n\nAll_df = pd.merge(left= All_df,right = All_Conceptdata.loc[:,['Concept','att_frac']],how=\"left\",left_on = 'Concept1',right_on='Concept')\nAll_df['att_fracA'] = All_df['att_frac'] \nAll_df['att_fracA'].fillna(0)\ndel All_df['att_frac']\n\nAll_df = pd.merge(left= All_df,right = All_Conceptdata.loc[:,['Concept','att_frac']],how=\"left\",left_on = 'Concept2',right_on='Concept')\nAll_df['att_fracB'] = All_df['att_frac'] \nAll_df['att_fracB'].fillna(0)\ndel All_df['att_frac']\n\nAll_df = pd.merge(left= All_df,right = All_Conceptdata.loc[:,['Concept','set_frac']],how=\"left\",left_on = 'Concept1',right_on='Concept')\nAll_df['set_fracA'] = All_df['set_frac'] \nAll_df['set_fracA'].fillna(0)\ndel All_df['set_frac']\n\nAll_df = pd.merge(left= All_df,right = All_Conceptdata.loc[:,['Concept','set_frac']],how=\"left\",left_on = 'Concept2',right_on='Concept')\nAll_df['set_fracB'] = All_df['set_frac'] \nAll_df['set_fracB'].fillna(0)\ndel All_df['set_frac']\n\nAll_df = pd.merge(left= All_df,right = All_Conceptdata.loc[:,['Concept','ins_frac']],how=\"left\",left_on = 'Concept1',right_on='Concept')\nAll_df['ins_fracA'] = All_df['ins_frac'] \nAll_df['ins_fracA'].fillna(0)\ndel All_df['ins_frac']\n\nAll_df = pd.merge(left= All_df,right = All_Conceptdata.loc[:,['Concept','ins_frac']],how=\"left\",left_on = 'Concept2',right_on='Concept')\nAll_df['ins_fracB'] = All_df['ins_frac'] \nAll_df['ins_fracB'].fillna(0)\ndel All_df['ins_frac']\n\n\nfor filename in filenames:\n  colname = filename.replace(\".pbz2\",\"\")\n  All_df = pd.merge(left = All_df,\n                             right = All_Conceptdata.loc[:,['Concept',colname+'_IntTFIDF']],\n                             how='left',\n                             left_on = 'Concept1',\n                             right_on = 'Concept')\n  All_df[colname+'_IntTFIDFA'] = All_df[colname+'_IntTFIDF']\n  del All_df[colname+'_IntTFIDF']\n  All_df[colname+'_IntTFIDFA'].fillna(0,inplace=True)\n  #del All_df['Concept_x'], All_df['Concept_y']\n\n  All_df = pd.merge(left = All_df,\n                             right = All_Conceptdata.loc[:,['Concept',colname+'_IntTFIDF']],\n                             how='left',\n                             left_on = 'Concept2',\n                             right_on = 'Concept')\n  All_df[colname+'_IntTFIDFB'] = All_df[colname+'_IntTFIDF']\n  del All_df[colname+'_IntTFIDF']\n  All_df[colname+'_IntTFIDFB'].fillna(0,inplace=True)\n  \ntry:\n  del All_df['Concept_x']\nexcept:\n  pass\n\ntry:\n  del All_df['Concept_y']\nexcept:\n  pass\n\nimport networkx as nx\nallG = nx.from_pandas_edgelist(All_df,'Concept1','Concept2')\ncentrality_dict = nx.eigenvector_centrality_numpy(allG)\ncentrality = pd.Series(centrality_dict)\ncentrality.name = 'Centrality'\ncentrality = pd.DataFrame(centrality)\n\ncentrality['Concept'] = list(centrality.index)\nAll_Conceptdata = pd.merge(left=All_Conceptdata,right=centrality[['Concept','Centrality']],how = 'left',left_on = 'Concept',right_on = 'Concept',suffixes=(\"\", \"\"))\n\n\n# centrality\n\ndf['Centrality_A'] = df['Concept1'].apply(lambda x:\n                                          list(Conceptdata.loc[Conceptdata['Concept']==x,'Centrality'].values)[0])\n\ndf['Centrality_B'] = df['Concept2'].apply(lambda x:\n                                          list(Conceptdata.loc[Conceptdata['Concept']==x,'Centrality'].values)[0])\n\n\nnonos = ['openstax','openstax book','http','website','credit','wikipedia','book','chapter','wikibook','wikibook project']\ndf1 = All_df.loc[~All_df['Concept1'].isin(nonos)]\ndf1 = df1.loc[~df1['Concept2'].isin(nonos)]\nAll_df = df1.copy()\ndel df1\n```\n\n    /usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:34: FutureWarning: Passing 'suffixes' which cause duplicate columns {'Concept_x'} in the result is deprecated and will raise a MergeError in a future version.\n    /usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:45: FutureWarning: Passing 'suffixes' which cause duplicate columns {'Concept_x'} in the result is deprecated and will raise a MergeError in a future version.\n    /usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:56: FutureWarning: Passing 'suffixes' which cause duplicate columns {'Concept_x'} in the result is deprecated and will raise a MergeError in a future version.\n    /usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:66: FutureWarning: Passing 'suffixes' which cause duplicate columns {'Concept_x'} in the result is deprecated and will raise a MergeError in a future version.\n    /usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:76: FutureWarning: Passing 'suffixes' which cause duplicate columns {'Concept_x'} in the result is deprecated and will raise a MergeError in a future version.\n    /usr/local/lib/python3.7/dist-packages/pandas/core/generic.py:6392: SettingWithCopyWarning: \n    A value is trying to be set on a copy of a slice from a DataFrame\n    \n    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n      return self._update_inplace(result)\n    /usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:98: FutureWarning: Passing 'suffixes' which cause duplicate columns {'Concept_x'} in the result is deprecated and will raise a MergeError in a future version.\n\n\n\n```\nAll_Conceptdata.columns\n```\n\n\n\n\n    Index(['Concept', 'doc_Occurence', 'doc_Frequency', 'Raw_Frequency', 'Mean',\n           'Median', 'Sdev', 'Ext_IDF', 'Mean_Frequency', 'normalized_RawFreq',\n           'normalized_MeanFreq', 'intIDF', 'intmeanTFIDF', 'Envoy_loar_TF',\n           'Envoy_loar_IntTFIDF', 'TLSwiki_TF', 'TLSwiki_IntTFIDF', 'MCForm',\n           'phen_frac', 'att_frac', 'set_frac', 'ins_frac', 'Centrality'],\n          dtype='object')\n\n\n\n\n```\n!pip install dimcli networkx pyvis -U --quiet\nfrom dimcli.utils.networkviz import *\nimport networkx as nx\n```\n\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 214 kB 7.7 MB/s \n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51 kB 6.4 MB/s \n    \u001b[?25h\n\n\n```\ndef filter_by_concept(df,concept_x,number = 3):\n  dfsub1 = df.loc[df['Concept1']==concept_x,['Concept1','Concept2','MCForm1','MCForm2','Raw_TFB','mean_dAB','Ext_TFIDFA','Ext_TFIDFB','SdevB',\n                                             'phen_fracA','phen_fracB','set_fracA','set_fracB','ins_fracA','ins_fracB','att_fracA','att_fracB']].copy()\n\n  dfsub1['Concept_y'] = dfsub1['Concept2']\n  dfsub1['MCForm_y'] = dfsub1['MCForm2']\n  dfsub1['Cooccurence_cc_y'] = dfsub1['mean_dAB']\n  dfsub1['F_y'] = dfsub1['Raw_TFB']\n  dfsub1['TFIDF_y'] = dfsub1['Ext_TFIDFB']\n  dfsub1['Sdev_y'] = dfsub1['SdevB']\n  dfsub1['Concept_x'] = dfsub1['Concept1']\n  dfsub1['MCForm_x'] = dfsub1['MCForm1']\n  dfsub1['phen_frac_x'] = dfsub1['phen_fracA']\n  dfsub1['phen_frac_y'] = dfsub1['phen_fracB']\n  dfsub1['att_frac_x'] = dfsub1['att_fracA']\n  dfsub1['att_frac_y'] = dfsub1['att_fracB']\n  dfsub1['set_frac_x'] = dfsub1['set_fracA']\n  dfsub1['set_frac_y'] = dfsub1['set_fracB']\n  dfsub1['ins_frac_x'] = dfsub1['ins_fracA']\n  dfsub1['ins_frac_y'] = dfsub1['ins_fracB']\n\n\n  dfsub2 = df.loc[df['Concept2']==concept_x,['Concept1','Concept2','MCForm1','MCForm2','Raw_TFA','mean_dBA','Ext_TFIDFA','Ext_TFIDFB','SdevA',\n                                             'phen_fracA','phen_fracB','set_fracA','set_fracB','ins_fracA','ins_fracB','att_fracA','att_fracB']].copy()\n  dfsub2['Sdev_y'] = dfsub2['SdevA']\n  dfsub2['Concept_y'] = dfsub2['Concept1']\n  dfsub2['MCForm_y'] = dfsub2['MCForm1']\n  dfsub2['Cooccurence_cc_y'] = dfsub2['mean_dBA']\n  dfsub2['F_y'] = dfsub2['Raw_TFA']\n  dfsub2['TFIDF_y'] = dfsub2['Ext_TFIDFA']\n  dfsub2['Concept_x'] = dfsub2['Concept2']\n  dfsub2['MCForm_x'] = dfsub2['MCForm2']\n\n  dfsub2['phen_frac_x'] = dfsub2['phen_fracB']\n  dfsub2['phen_frac_y'] = dfsub2['phen_fracA']\n  dfsub2['att_frac_x'] = dfsub2['att_fracB']\n  dfsub2['att_frac_y'] = dfsub2['att_fracA']\n  dfsub2['set_frac_x'] = dfsub2['set_fracB']\n  dfsub2['set_frac_y'] = dfsub2['set_fracA']\n  dfsub2['ins_frac_x'] = dfsub2['ins_fracB']\n  dfsub2['ins_frac_y'] = dfsub2['ins_fracA']\n\n  dfsub = dfsub1.append(dfsub2)\n  if dfsub1.shape[0]>0:\n    TFIDF_cutoff = dfsub1['Ext_TFIDFA'].head(1).item()\n  else:\n    TFIDF_cutoff = dfsub2['Ext_TFIDFB'].head(1).item()\n  dfsub = dfsub.loc[:,['Concept_x','Concept_y','MCForm_x','MCForm_y','F_y','TFIDF_y','Sdev_y','Cooccurence_cc_y',\n                       'phen_frac_x','phen_frac_y','att_frac_x','att_frac_y','set_frac_x','set_frac_y','ins_frac_x','ins_frac_y']]\n  dfsub = dfsub.drop_duplicates()\n  dfsub['TFIDFbydAB'] = dfsub['TFIDF_y']/dfsub['Cooccurence_cc_y']\n  dfsub = dfsub.loc[dfsub['TFIDF_y']<TFIDF_cutoff,:].sort_values(by=['TFIDFbydAB'],ascending=[False]).head(number)\n  y_conceptsset = set(dfsub['Concept_y'])\n  return (dfsub,y_conceptsset)\n\n\ndef filter_by_listofconcepts(df,listofconcepts,number = 3):\n  dfsublist = pd.DataFrame()\n  yconceptsetlist = set()\n  for c in listofconcepts:\n    dfsubeach, y_conceptset = filter_by_concept(df,c,number)\n    dfsublist = dfsublist.append(dfsubeach)\n    yconceptsetlist = yconceptsetlist.union(y_conceptset)\n  dfsublist = dfsublist.drop_duplicates()\n  return dfsublist,yconceptsetlist\n```\n\n\n```\n# def filter_by_concept(df,concept_x,number = 3):\n#   dfsub1 = df.loc[df['Concept1']==concept_x,['Concept1','Concept2','MCForm1','MCForm2','Raw_TFB','mean_dAB','Ext_TFIDFA','Ext_TFIDFB']].copy()\n#   dfsub1['Concept_y'] = dfsub1['Concept2']\n#   dfsub1['MCForm_y'] = dfsub1['MCForm2']\n\n#   dfsub1['Cooccurence_cc_y'] = dfsub1['mean_dAB']\n#   dfsub1['F_y'] = dfsub1['Raw_TFB']\n#   dfsub1['TFIDF_y'] = dfsub1['Ext_TFIDFB']\n#   dfsub1['Concept_x'] = dfsub1['Concept1']\n#   dfsub1['MCForm_x'] = dfsub1['MCForm1']\n#   dfsub2 = df.loc[df['Concept2']==concept_x,['Concept1','Concept2','MCForm1','MCForm2','Raw_TFA','mean_dBA','Ext_TFIDFA','Ext_TFIDFB']].copy()\n#   dfsub2['Concept_y'] = dfsub2['Concept1']\n#   dfsub2['MCForm_y'] = dfsub2['MCForm1']\n\n#   dfsub2['Cooccurence_cc_y'] = dfsub2['mean_dBA']\n#   dfsub2['F_y'] = dfsub2['Raw_TFA']\n#   dfsub2['TFIDF_y'] = dfsub2['Ext_TFIDFA']\n#   dfsub2['Concept_x'] = dfsub2['Concept2']\n#   dfsub2['MCForm_x'] = dfsub2['MCForm2']\n#   dfsub = dfsub1.append(dfsub2)\n#   if dfsub1.shape[0]>0:\n#     TFIDF_cutoff = dfsub1['Ext_TFIDFA'].head(1).item()\n#   else:\n#     TFIDF_cutoff = dfsub2['Ext_TFIDFB'].head(1).item()\n#   dfsub = dfsub.loc[:,['Concept_x','Concept_y','MCForm_x','MCForm_y','Cooccurence_cc_y','TFIDF_y']].copy()\n#   dfsub = dfsub.drop_duplicates()\n#   dfsub['TFIDFbydAB'] = dfsub['TFIDF_y']/dfsub['Cooccurence_cc_y']\n#   dfsub = dfsub.loc[dfsub['TFIDF_y']<TFIDF_cutoff,:].sort_values(by=['TFIDFbydAB'],ascending=[False]).head(number)\n#   y_conceptsset = set(dfsub['Concept_y'])\n#   return (dfsub,y_conceptsset)\n\n```\n\n\n```\n# def filter_by_listofconcepts(df,listofconcepts,number = 3):\n#   dfsublist = pd.DataFrame()\n#   yconceptsetlist = set()\n#   for c in listofconcepts:\n#     dfsubeach, y_conceptset = filter_by_concept(df,c,number)\n#     dfsublist = dfsublist.append(dfsubeach)\n#     yconceptsetlist = yconceptsetlist.union(y_conceptset)\n#   dfsublist = dfsublist.drop_duplicates()\n#   return dfsublist,yconceptsetlist\n```\n\n\n```\n#@title Document centric view: Most important concepts in documents { run: \"auto\", vertical-output: true }\nimport numpy as num\nnet = NetworkViz(height='700px', width='700px', directed=False,notebook=True)\nincluded_docs = [\"Envoy_loar\"] #@param \nCentrality_Detail = 100 #@param {type:\"slider\", min:1, max:100, step:1} \nFrequency_Detail = 100 #@param {type:\"slider\", min:1, max:100, step:1}\nIDF_Detail = 100#@param {type:\"slider\", min:1, max:100, step:1}\nmaxnumber = 34#@param {type:\"slider\", min:1, max:50, step:1}\nFrequency_cutoff = num.quantile(All_Conceptdata['Raw_Frequency'],(100-Frequency_Detail)/100)\nIDF_cutoff = num.nanquantile(All_Conceptdata['Ext_IDF'],(100-IDF_Detail)/100)\nCentrality_cutoff = num.nanquantile(All_Conceptdata['Centrality'],(100-Centrality_Detail)/100)\n#print(FA,FB)\ndocnodes = []\nif included_docs!=[\"All\"]:\n  \n  for d in included_docs:\n    docnodes = docnodes + doc_to_np[d+'.pbz2']\n  docnodes = set(docnodes)\n  included_nodes = list(All_Conceptdata.loc[(All_Conceptdata['Concept'].isin(docnodes)) & (All_Conceptdata['Centrality']>Centrality_cutoff) & (All_Conceptdata['Raw_Frequency']>Frequency_cutoff) & (All_Conceptdata['Ext_IDF']>IDF_cutoff),'Concept'])  \nelse:\n  for d in filenames:\n    docnodes = docnodes + doc_to_np[d]\n  included_nodes = list(All_Conceptdata.loc[ (All_Conceptdata['Centrality']>Centrality_cutoff) & (All_Conceptdata['Raw_Frequency']>Frequency_cutoff) & (All_Conceptdata['Ext_IDF']>IDF_cutoff),'Concept'])  \n  #docnodes = \ndfnoones = All_df.loc[\n                  (All_df['Concept1'].isin(included_nodes)) & \n                  (All_df['Concept2'].isin(included_nodes)) \n                  #(df['FA']>Frequency_cutoff) &\n                  #(df['IDFA']>IDF_cutoff) & \n                  #(df['FB']>Frequency_cutoff) & \n                  #(df['IDFB']>IDF_cutoff)\n                  ,:].head(maxnumber)\nprint('Number of edges: ',dfnoones.shape[0])\nprint('Percentage of all concepts present in selected documents',len(docnodes)/All_Conceptdata.shape[0]*100)\nprint('Most central concepts left out:')\nprint(All_Conceptdata.loc[~All_Conceptdata['Concept'].isin(docnodes),:].sort_values(by='Centrality',ascending=False).head(20)[['Concept','Raw_Frequency']])\n#print(dfnoones)\n#dfnoones['size'] = dfnoones['FA']\nbigG = nx.from_pandas_edgelist(dfnoones,'MCForm1','MCForm2')\n# getting the nodes in bigG\nnodes = bigG.nodes\n# size_series = Conceptdata.loc[Conceptdata['Concept'].isin(nodes),['Concept','Frequency']].set_index('Concept')\n# size_dict = size_series.to_dict()['Frequency']\nsize_series = Conceptdata.loc[Conceptdata['Concept'].isin(nodes),['Concept','Centrality']].set_index('Concept')\nsize_dict = size_series.to_dict()['Centrality']\n#tiered sizes\nnumbins = int(maxnumber/5)\n#sizelabels = num.linspace(start = 35,stop = 5,num=numbins)\n#print(numbins,sizelabels)\nsize_series['binned'] = pd.qcut(size_series['Centrality'],numbins,duplicates='drop')\nunique_bins = size_series['binned'].unique()\nunique_bins_sorted = list(pd.Series(unique_bins).sort_values(ascending=False))\nprint(unique_bins)\nif len(unique_bins)>2:\n  sizelabels = num.linspace(start = 45,stop = 5, num = len(unique_bins))\n  size_series['labeled'] = size_series['binned'].apply(lambda x: dict(zip(unique_bins_sorted,sizelabels))[x])\nelse:\n  size_series['labeled'] = 45\nnx.set_node_attributes(bigG,size_series['labeled'],name='size')\n#size_series['size']\n#nx.set_node_attributes(bigG\n#net('500px','500px')\nnet.from_nx(bigG)\n#net.show_buttons()\nnet.show('nx.html')\n```\n\n    Number of edges:  34\n    Percentage of all concepts present in selected documents 34.55223880597015\n    Most central concepts left out:\n                             Concept  Raw_Frequency\n    81                        attack             31\n    83                      attacker             20\n    1090                         ssl             43\n    1277                        user             16\n    1298               vulnerability             17\n    125                      browser              7\n    7                - middle attack             10\n    449              forward secrecy             15\n    1212                     traffic              7\n    1037                     session             13\n    674   man - in - - middle attack              9\n    1289                     version             19\n    987                      secrecy              8\n    850                  private key              6\n    363                   encryption             14\n    1312                  web server              8\n    1274                         use             11\n    1187           tl implementation              3\n    599                 key exchange              7\n    495                      hellman              8\n    [(0.0615, 0.0713], (0.0477, 0.0615], (0.0376, 0.041], (0.031, 0.0376], (0.041, 0.0477], (0.023799999999999998, 0.031]]\n    Categories (6, interval[float64, right]): [(0.023799999999999998, 0.031] < (0.031, 0.0376] < (0.0376, 0.041] <\n                                               (0.041, 0.0477] < (0.0477, 0.0615] < (0.0615, 0.0713]]\n\n\n\n\n\n<html>\n<head>\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/vis/4.16.1/vis.css\" type=\"text/css\" />\n\n<center>\n<h1></h1>\n</center>\n\n<!-- <link rel=\"stylesheet\" href=\"../node_modules/vis/dist/vis.min.css\" type=\"text/css\" />\n-->\n\n<style type=\"text/css\">\n\n        #mynetwork {\n            width: 700px;\n            height: 700px;\n            background-color: #ffffff;\n            border: 1px solid lightgray;\n            position: relative;\n            float: left;\n        }\n\n\n\n\n\n\n</style>\n\n</head>\n\n<body>\n<div id = \"mynetwork\"></div>\n\n\n\n</body>\n</html>\n\n\n\n\n```\n#@title Concept centric view: Hierarchical radial branching visualization { run: \"auto\", vertical-output: true }\nfrom dimcli.utils.networkviz import *\n#from dimcli.core.extras import NetworkViz\nnet = NetworkViz(height='500px', width='500px', directed=False,notebook=True)\nlistnodes = list(nodes)\ncentral_concept = \"alpn\" #@param \"\"\n#TFIDF_cutoff = 0.95 #@param {type:\"slider\", min:0, max:1, step:0.05}\n#@markdown Radius (max path length from central concept)\nradius = 2 #@param {type:\"slider\", min:0, max:5, step:1}\n#Cooccurence_cutoff = 0.2\n#@markdown Number of splits \nsplits = 5 #@param {type:\"slider\", min:0, max:5, step:1}\n\nradiuscolors = [\"#f50c0c\",\"#ff9900\",'#e5ff00','#00ff1e',\"#00ffe5\"]\ncolor_dict = dict()\ncolor_dict[central_concept] = radiuscolors[0]\ndfsub = pd.DataFrame()\ny_conceptsnew = set([central_concept])\ny_concepts = set()\ny_concepts = y_concepts.union(y_conceptsnew)\nfor i in range(radius):\n  dfsubnew, y_conceptsnew = filter_by_listofconcepts(All_df,y_conceptsnew,splits)\n  y_concepts = y_concepts.union(y_conceptsnew)\n  for yc in y_conceptsnew:\n    if yc not in color_dict:\n      color_dict[yc] = radiuscolors[i]\n  print(len(y_concepts))\n\n(dfsub,yconceptsnew) = filter_by_listofconcepts(All_df,y_concepts)\nfor yc in y_conceptsnew:\n  if yc not in color_dict:\n    color_dict[yc] = radiuscolors[-1]\ndfsub = dfsub.drop_duplicates()\ndegree_graph = dfsub.copy()\n\n# degree graph should return the MCForms too. \n\n#degree_graph['central_concept'] = [central_concept]*degree_graph.shape[0]\n#TFIDF_threshold = num.quantile(dfsub['TFIDF_y'],TFIDF_cutoff)\n#Cooccurence_threshold = num.quantile(dfsub['TFIDF_y'],Cooccurence_cutoff)\n#degree_graph = degree_graph.loc[(degree_graph['TFIDF_y']>TFIDF_threshold) & (degree_graph['Cooccurence_cc_y']<Cooccurence_threshold),:].copy()\nprint(len(degree_graph))\n\nG = nx.from_pandas_edgelist(degree_graph,'MCForm_x','MCForm_y', create_using=nx.Graph())\nnx.set_node_attributes(G,color_dict,\"color\")\nnx.set_node_attributes(G,{central_concept:20},\"size\")\n#G.set_node_attributes()  \n\nnet.from_nx(G)\nnet.show('nx.html')\n\n\n\n\n  \n  \n# dfnoones = df.loc[(df['FA']>7) & (df['FB']>5),:]\n# bigG = nx.from_pandas_edgelist(dfnoones,'Concept1','Concept2')\n# #net('500px','500px')\n# net.from_nx(bigG)\n# #net.show_buttons()\n# net.show('nx.html')\n\n\n```\n\n    6\n    24\n    68\n\n\n\n\n\n<html>\n<head>\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/vis/4.16.1/vis.css\" type=\"text/css\" />\n\n<center>\n<h1></h1>\n</center>\n\n<!-- <link rel=\"stylesheet\" href=\"../node_modules/vis/dist/vis.min.css\" type=\"text/css\" />\n-->\n\n<style type=\"text/css\">\n\n        #mynetwork {\n            width: 500px;\n            height: 500px;\n            background-color: #ffffff;\n            border: 1px solid lightgray;\n            position: relative;\n            float: left;\n        }\n\n\n\n\n\n\n</style>\n\n</head>\n\n<body>\n<div id = \"mynetwork\"></div>\n\n\n\n</body>\n</html>\n\n\n\n\n```\nAll_Conceptdata.loc[All_Conceptdata['MCForm']=='TLS protocol']\n```\n\n    Warning: Total number of columns (23) exceeds max_columns (20). Falling back to pandas display.\n\n\n\n\n\n\n  <div id=\"df-f8057696-ab1e-44ba-adb3-9f67a3cc3047\">\n    <div class=\"colab-df-container\">\n      <div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Concept</th>\n      <th>doc_Occurence</th>\n      <th>doc_Frequency</th>\n      <th>Raw_Frequency</th>\n      <th>Mean</th>\n      <th>Median</th>\n      <th>Sdev</th>\n      <th>Ext_IDF</th>\n      <th>Mean_Frequency</th>\n      <th>normalized_RawFreq</th>\n      <th>normalized_MeanFreq</th>\n      <th>intIDF</th>\n      <th>intmeanTFIDF</th>\n      <th>Envoy_loar_TF</th>\n      <th>Envoy_loar_IntTFIDF</th>\n      <th>TLSwiki_TF</th>\n      <th>TLSwiki_IntTFIDF</th>\n      <th>MCForm</th>\n      <th>phen_frac</th>\n      <th>att_frac</th>\n      <th>set_frac</th>\n      <th>ins_frac</th>\n      <th>Centrality</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1196</th>\n      <td>tl protocol</td>\n      <td>[TLSwiki.pbz2]</td>\n      <td>1</td>\n      <td>4</td>\n      <td>0.314309</td>\n      <td>0.229904</td>\n      <td>0.325953</td>\n      <td>9.146468</td>\n      <td>4.0</td>\n      <td>0.035088</td>\n      <td>0.070175</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>4.0</td>\n      <td>0.0</td>\n      <td>TLS protocol</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>1.0</td>\n      <td>0.0</td>\n      <td>0.027477</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n      <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-f8057696-ab1e-44ba-adb3-9f67a3cc3047')\"\n              title=\"Convert this dataframe to an interactive table.\"\n              style=\"display:none;\">\n\n  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n       width=\"24px\">\n    <path d=\"M0 0h24v24H0V0z\" fill=\"none\"/>\n    <path d=\"M18.56 5.44l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94zm-11 1L8.5 8.5l.94-2.06 2.06-.94-2.06-.94L8.5 2.5l-.94 2.06-2.06.94zm10 10l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94z\"/><path d=\"M17.41 7.96l-1.37-1.37c-.4-.4-.92-.59-1.43-.59-.52 0-1.04.2-1.43.59L10.3 9.45l-7.72 7.72c-.78.78-.78 2.05 0 2.83L4 21.41c.39.39.9.59 1.41.59.51 0 1.02-.2 1.41-.59l7.78-7.78 2.81-2.81c.8-.78.8-2.07 0-2.86zM5.41 20L4 18.59l7.72-7.72 1.47 1.35L5.41 20z\"/>\n  </svg>\n      </button>\n\n  <style>\n    .colab-df-container {\n      display:flex;\n      flex-wrap:wrap;\n      gap: 12px;\n    }\n\n    .colab-df-convert {\n      background-color: #E8F0FE;\n      border: none;\n      border-radius: 50%;\n      cursor: pointer;\n      display: none;\n      fill: #1967D2;\n      height: 32px;\n      padding: 0 0 0 0;\n      width: 32px;\n    }\n\n    .colab-df-convert:hover {\n      background-color: #E2EBFA;\n      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n      fill: #174EA6;\n    }\n\n    [theme=dark] .colab-df-convert {\n      background-color: #3B4455;\n      fill: #D2E3FC;\n    }\n\n    [theme=dark] .colab-df-convert:hover {\n      background-color: #434B5C;\n      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n      fill: #FFFFFF;\n    }\n  </style>\n\n      \n    </div>\n  </div>\n\n\n\n\n\n```\n# dfsub, yconcept_list = filter_by_listofconcepts(All_df,listofconcepts = ['teacher'],number = 250)\n# dfsub.loc[dfsub['Concept_y'].isin(list(phen_to_sent.keys())),:].sort_values(by='TFIDFbydAB',ascending=False)\n\ndfsub, yconcept_list = filter_by_listofconcepts(All_df,listofconcepts = ['learning'],number = 1250)\ndfsub.loc[dfsub['Concept_y'].isin(list(phen_to_sent.keys())),:].sort_values(by=['F_y','phen_frac_y','TFIDFbydAB'],ascending=[False]*3)\n```\n\n\n```\n#@title Visualizing Relationships/Path between two concepts { run: \"auto\", vertical-output: true }\nnet1 = NetworkViz(height='500px', width='500px', directed=False,notebook=True)\nconcept1 = \"envoy listener\"  #@param listnodes\nconcept2 = \"circuit breaker\"  #@param listnodes\ncutoff = 12 #@param {type:\"slider\", min:8, max:20, step:1} \nmaxnumpaths = 10 #@param {type:\"slider\", min:1, max:20, step:1} \nconcept1 = Agg_np_to_mcform[concept1]\nconcept2 = Agg_np_to_mcform[concept2]\nbigG = nx.from_pandas_edgelist(All_df,'MCForm1','MCForm2',create_using = nx.Graph())\n\n\nfrom itertools import islice\ndef k_shortest_paths(G, source, target, k, weight=None):\n    return list(\n        islice(nx.shortest_simple_paths(G, source, target, weight=weight), k)\n    )\n\ndef k_paths(G, source, target, k, cutoff=10):\n    return list(\n        islice(nx.all_simple_paths(G, source, target,cutoff=cutoff), k)\n    )\n    \n\n\nif bigG.has_edge(concept1,concept2) or bigG.has_edge(concept2,concept1):\n  #cutoff = 4\n  spconceptset =set([concept1,concept2])\n  subG = nx.subgraph(bigG,list(spconceptset))\nelif nx.has_path(bigG,concept1,concept2) is False:\n  print(\"No path found between \",concept1,\"and\",concept2,\"!\")\nelse:\n  #print('has path')\n  spconceptset = set()\n  shortestpaths = nx.all_shortest_paths(bigG, concept1, concept2, method='dijkstra')\n  # for sp in shortestpaths:\n  #   #print(sp)\n  #   spconceptset = spconceptset.union(set(sp))\n  #   cutoff = len(sp)+3\n  conceptset = set([concept1,concept2])\n  for path in k_shortest_paths(bigG, concept1, concept2, maxnumpaths):\n    #print(path)\n    conceptset = conceptset.union(set(path))\n  #paths = nx.all_simple_paths(bigG, concept1, concept2, cutoff=cutoff)\n  subG = nx.subgraph(bigG,list(conceptset))\n\nnx.set_node_attributes(subG,{concept1:25,concept2:25},\"size\")\nnx.set_node_attributes(subG,{concept1:\"#ff9900\",concept2:\"#ff9900\"},\"color\")\nnet1.from_nx(subG)\nnet1.show('nx.html')\n\n\n  \n```\n\n\n\n\n<html>\n<head>\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/vis/4.16.1/vis.css\" type=\"text/css\" />\n\n<center>\n<h1></h1>\n</center>\n\n<!-- <link rel=\"stylesheet\" href=\"../node_modules/vis/dist/vis.min.css\" type=\"text/css\" />\n-->\n\n<style type=\"text/css\">\n\n        #mynetwork {\n            width: 500px;\n            height: 500px;\n            background-color: #ffffff;\n            border: 1px solid lightgray;\n            position: relative;\n            float: left;\n        }\n\n\n\n\n\n\n</style>\n\n</head>\n\n<body>\n<div id = \"mynetwork\"></div>\n\n\n\n</body>\n</html>\n\n\n\n\n```\n#@title Functions for calculating memory load\n\ndef plot_clt(sent_to_clt):\n    \n    from matplotlib import pyplot as plt\n    plt.xlabel('document sentence #')\n    plt.ylabel('Load added to working memory by sentence')\n    plt.title('Cognitive Load for '+filename)\n    plt.plot(list(range(1,len(sent_to_npflat)+1)),sent_to_clt,drawstyle='steps')\n    #plt.savefig('cltfig1.png')\n    return None\n\n#sent_to_clt = calc_cl_per_sentence(Agg_sent_to_npflat)\n#plot_clt(sent_to_clt)\n\ndef print_sents_by_target_cl(target,cl):\n    return [sents[s] for s in Agg_np_to_sent[target] if Agg_sent_to_clt[s]==cl]\n\n```\n\n\n```\n#@title Functions to get blurbs of text\nfrom sympy import Interval, Union, FiniteSet, solveset\nimport pandas as pd\n\ndef calc_cl_per_sentence(doc,known_concepts = [], max_idf=9.1):\n    sent_to_clt = []\n    sent_to_npflat = Agg_sent_to_npflat[doc]\n    for i in range(len(sent_to_npflat)):\n        npinsent = sent_to_npflat[i]\n        npinsent = [np for np in npinsent if np not in known_concepts]\n        cltinsent = [All_Conceptdata.loc[All_Conceptdata['Concept']==np,'Ext_IDF'].values for np in npinsent]\n        clt= 0\n        for (np,idf) in zip(npinsent,cltinsent):\n            if (idf>=max_idf):\n                clt = clt + 1\n        sent_to_clt.append(clt)\n    return sent_to_clt\n\ndef calc_clt_blurb_order(tuplist,doc,known_concepts,max_idf):\n    sent_to_clt = calc_cl_per_sentence(doc,known_concepts,max_idf)\n    tup_to_clt = {}\n    for tup in tuplist:\n        blurb_clt = 0\n        for i in range(tup[0],tup[1]+1):\n            blurb_clt = blurb_clt + sent_to_clt[i]\n        tup_to_clt[tup] = blurb_clt\n    tup_to_clt = pd.Series(tup_to_clt)\n    tup_to_clt.sort_values(ascending=True)\n    return tup_to_clt.sort_values(ascending=True)\n\ndef get_sentence_indices(npset,doc,max_distance=3):\n    #sentslist = [np_to_sent[np1] for np1 in npset]\n    # get pairs?\n    np_to_sent = Agg_np_to_sent[doc]\n\n    if len(npset)==1:\n      tuplist = [(i[1],i[1]+1) for i in np_to_sent[list(npset)[0]]]\n    else:\n      pairs = set([frozenset([np1,np2]) for np1 in npset for np2 in npset if np1!=np2])\n      #print(pairs)\n      tuplist = []\n      for p in pairs:\n        p = list(p)\n        np1 = p[0]\n        np2 = p[1]\n        \n        sents1 = np_to_sent.get(np1,[])\n        sents2 = np_to_sent.get(np2,[])\n        print(sents1,sents2)\n        ind1 = 0\n        ind2 = 0\n        \n        lensents1 = len(sents1)\n        #print(lensents1)\n        lensents2 = len(sents2)\n        #print(lensents2)\n        while(ind1<lensents1 and ind2 <lensents2):\n            #print(ind1,ind2)\n            if (sents1[ind1]<sents2[ind2]):\n                #print('sent1 less than sent2')\n                if sents2[ind2]-sents1[ind1]<=max_distance:\n                    tuplist.append((sents1[ind1],sents2[ind2]))\n                    ind1 = ind1+1\n                    ind2 = ind2 + 1\n                else:\n                    #ind1 = bs.bisect_left(sents1,sents2[ind2])\n                    ind1 = ind1 + 1\n            elif (sents1[ind1]>sents2[ind2]):\n                #print('sent2 less than sent1')\n                if sents1[ind1]-sents2[ind2] <= max_distance:\n                    tuplist.append((sents2[ind2],sents1[ind1]))\n                    ind1 = ind1 + 1\n                    ind2 = ind2 + 1\n                else:\n                    #ind2 = bs.bisect_left(sents2,sents1[ind1])\n                    ind2 = ind2 + 1\n            else:\n                tuplist.append((sents1[ind1],sents2[ind2]))\n                ind1 = ind1+1\n                ind2 = ind2+1\n    #print(tuplist)\n    if len(tuplist)>1:\n      interval_list = [Interval(tup[0],tup[1]+1,False,False) for tup in tuplist]\n      interval_union = interval_list[0]\n      \n      for i in interval_list[1:]:\n        interval_union = Union(interval_union,i)\n      #print(interval_list,interval_union)\n      #print(interval_union.boundary,interval_union.args)\n      if len(interval_union.boundary)>2:\n        merged_tuplist = [tuple(t.boundary) for t in interval_union.args]\n      else:\n        merged_tuplist = [tuple(interval_union.args)]\n      return merged_tuplist\n    else:\n      return tuplist\n\ndef get_blurbs(npset,max_distance=3,known_concepts = [],max_idf = 15):\n   \n    tuplistdfall = pd.DataFrame()\n    for doc in Agg_sent_to_clt:\n      blurblist = []\n      tuplist = calc_clt_blurb_order(get_sentence_indices(npset,doc,max_distance),doc,known_concepts,max_idf)\n      sents = Agg_sents[doc]\n      tuplistdf = pd.DataFrame()\n      tuplistindices = list(tuplist.index)\n      for t in tuplistindices:\n          blurb = ''\n          #print(t)x\n          for s in range(t[0],t[1]+1):\n            blurb = blurb + sents[s]+' '\n          #print(blurb)\n          blurblist.append(blurb)\n      \n      tuplistdf['tuples'] = tuplistindices\n      tuplistdf['clt'] = list(tuplist)\n      tuplistdf['blurbs'] = blurblist\n      tuplistdf['doc'] = doc\n      tuplistdfall = tuplistdfall.append(tuplistdf,ignore_index=True)\n    \n    return tuplistdfall.sort_values(by='clt',ascending=True)\n\ndef flatten_list(listoflists):\n  flatlist = []\n  for l in listoflists:\n    flatlist = flatlist+l\n  return flatlist\n\ndef findall_string(blurb,np):\n  blurb = blurb.lower()\n  start = 0\n  poslist = []\n  flag = 0\n  while flag == 0:\n    try:\n      pos = blurb.index(np,start)\n      #print(start,'found')\n      poslist.append((pos,pos+len(np)))\n      start = pos+len(np)\n    except:\n      flag = 1\n  return poslist\n\ndef change_color(blurb,npset):\n  #print(npset)\n  if len(npset)>1:\n    tuplist = flatten_list([findall_string(blurb,np) for np in npset])\n  else:\n    tuplist = findall_string(blurb,list(npset)[0])\n  starts = [t[0] for t in tuplist]\n  starts.sort()\n  stops = [t[1] for t in tuplist] # making assumptions of no overlap here.\n  stops.sort()\n  newblurb = \"\\033[1;0m \"+blurb[0:starts[0]]\n  for i in range(len(starts)-1):\n    newblurb = newblurb + \"\\033[1;32m \"+blurb[starts[i]:stops[i]]\n    newblurb = newblurb + \"\\033[1;0m \"+blurb[stops[i]:starts[i+1]]\n  newblurb = newblurb + \"\\033[1;32m \"+blurb[starts[-1]:stops[-1]]\n  newblurb = newblurb + \"\\033[1;0m \"+blurb[stops[-1]:-1]                                            \n  return newblurb\n\n\n    \n```\n\n\n```\nlist(subG.nodes)\n```\n\n\n```\nimport textwrap\n\n\nnpset = set(['envoy listener',\n #'activation state',\n #'connection oriented tcp filter',\n #'tcp connection',\n #'alpn',\n #'combination',\n 'active / passive health check',\n 'circuit breaker',\n #'connection',\n 'balancing',\n #'activation'\n ])\n#print(npset)\ntuplistdfall =  get_blurbs(npset,4,known_concepts = [],max_idf = 10)\nprintable = ''\nblurb_count = 1\nfor i,row in tuplistdfall.iterrows():\n  print('Blurb: ',blurb_count)\n  print('Document: ',row['doc'],' index: ',row['tuples'])\n  printable = change_color(row['blurbs'],npset)\n  print(textwrap.fill(printable, 120))\n  print('\\n\\n\\n')\n  blurb_count +=1\n\n# Should show number of results including each term. \n\n```\n\n    [79] [196]\n    [196] [48, 97, 199, 201, 203]\n    [79] [48, 97, 199, 201, 203]\n    [79] [96, 188, 194, 197]\n    [96, 188, 194, 197] [48, 97, 199, 201, 203]\n    [196] [96, 188, 194, 197]\n    [] []\n    [] []\n    [] []\n    [] []\n    [] []\n    [] []\n    Blurb:  1\n    Document:  Envoy_loar  index:  (96, 98)\n    \u001b[1;0m Cluster specific load \u001b[1;32m balancing\u001b[1;0m  is performed to find an endpoint. The cluster\u2019s \u001b[1;32m circuit\n    breaker\u001b[1;0m s are checked to determine if a new stream is allowed. A new connection to the endpoint is created if the\n    endpoint\u2019s connection pool is empty or lacks capacity.\n    \n    \n    \n    \n    Blurb:  2\n    Document:  Envoy_loar  index:  (194, 200)\n    \u001b[1;0m Envoy supports a variety of load \u001b[1;32m balancing\u001b[1;0m  algorithms, e.g. weighted round-robin, Maglev, least-\n    loaded, random. Load balancers obtain their effective assignments from a combination of static bootstrap configuration,\n    DNS, dynamic xDS (the CDS and EDS discovery services) and active/passive health checks. Further details on how load\n    \u001b[1;32m balancing\u001b[1;0m  works in Envoy are provided in the load \u001b[1;32m balancing\u001b[1;0m  documentation. Once an\n    endpoint is selected, the connection pool for this endpoint is used to find a connection to forward the request on. If\n    no connection to the host exists, or all connections are at their maximum concurrent stream limit, a new connection is\n    established and placed in the connection pool, unless the \u001b[1;32m circuit breaker\u001b[1;0m  for maximum connections for the\n    cluster has tripped. If a maximum lifetime stream limit for a connection is configured and reached, a new connection is\n    allocated in the pool and the affected HTTP/2 connection is drained.\n    \n    \n    \n    \n\n\n    /usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:27: DeprecationWarning: The default dtype for empty Series will be 'object' instead of 'float64' in a future version. Specify a dtype explicitly to silence this warning.\n\n\nNeed for proper noun entity resolution\n\n\n```\nAll_df.loc[All_df['Concept1'].isin(list(Agg_phen_to_sent.keys())) & All_df['Concept2'].isin(list(Agg_phen_to_sent.keys()))].sort_values(by = ['Raw_TFA','Raw_TFB','phen_fracA','phen_fracB'],ascending=[False]*4).head(10)\n```\n\n    Warning: Total number of columns (27) exceeds max_columns (20). Falling back to pandas display.\n\n\n\n\n\n\n  <div id=\"df-c5d7f552-947a-4821-9993-fde4bba56078\">\n    <div class=\"colab-df-container\">\n      <div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Concept1</th>\n      <th>Concept2</th>\n      <th>Bondstrength</th>\n      <th>mean_dAB</th>\n      <th>mean_dBA</th>\n      <th>ExtIDFA</th>\n      <th>ExtIDFB</th>\n      <th>SdevA</th>\n      <th>SdevB</th>\n      <th>Raw_TFA</th>\n      <th>Ext_TFIDFA</th>\n      <th>Raw_TFB</th>\n      <th>Ext_TFIDFB</th>\n      <th>MCForm1</th>\n      <th>MCForm2</th>\n      <th>phen_fracA</th>\n      <th>phen_fracB</th>\n      <th>att_fracA</th>\n      <th>att_fracB</th>\n      <th>set_fracA</th>\n      <th>set_fracB</th>\n      <th>ins_fracA</th>\n      <th>ins_fracB</th>\n      <th>Envoy_loar_IntTFIDFA</th>\n      <th>Envoy_loar_IntTFIDFB</th>\n      <th>TLSwiki_IntTFIDFA</th>\n      <th>TLSwiki_IntTFIDFB</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>5698</th>\n      <td>connection</td>\n      <td>request</td>\n      <td>0.200000</td>\n      <td>5.551724</td>\n      <td>9.687500</td>\n      <td>1.184634</td>\n      <td>1.177845</td>\n      <td>0.211875</td>\n      <td>0.339466</td>\n      <td>47</td>\n      <td>55.677791</td>\n      <td>38</td>\n      <td>44.758125</td>\n      <td>connection</td>\n      <td>request</td>\n      <td>0.348214</td>\n      <td>0.283951</td>\n      <td>0.348214</td>\n      <td>0.283951</td>\n      <td>0.303571</td>\n      <td>0.432099</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-16.963913</td>\n      <td>-18.718800</td>\n      <td>-10.529325</td>\n      <td>-3.509775</td>\n    </tr>\n    <tr>\n      <th>5691</th>\n      <td>connection</td>\n      <td>handshake</td>\n      <td>0.833333</td>\n      <td>11.444444</td>\n      <td>6.466667</td>\n      <td>1.184634</td>\n      <td>5.519732</td>\n      <td>0.335370</td>\n      <td>0.364488</td>\n      <td>47</td>\n      <td>55.677791</td>\n      <td>20</td>\n      <td>110.394634</td>\n      <td>connection</td>\n      <td>handshake</td>\n      <td>0.348214</td>\n      <td>0.403846</td>\n      <td>0.348214</td>\n      <td>0.403846</td>\n      <td>0.303571</td>\n      <td>0.192308</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-16.963913</td>\n      <td>-2.924813</td>\n      <td>-10.529325</td>\n      <td>-8.774438</td>\n    </tr>\n    <tr>\n      <th>5700</th>\n      <td>connection</td>\n      <td>response</td>\n      <td>0.200000</td>\n      <td>6.379310</td>\n      <td>7.312500</td>\n      <td>1.184634</td>\n      <td>0.864783</td>\n      <td>0.211875</td>\n      <td>0.280271</td>\n      <td>47</td>\n      <td>55.677791</td>\n      <td>16</td>\n      <td>13.836533</td>\n      <td>connection</td>\n      <td>response</td>\n      <td>0.348214</td>\n      <td>0.372093</td>\n      <td>0.348214</td>\n      <td>0.372093</td>\n      <td>0.303571</td>\n      <td>0.255814</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-16.963913</td>\n      <td>0.000000</td>\n      <td>-10.529325</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>5706</th>\n      <td>connection</td>\n      <td>session</td>\n      <td>0.200000</td>\n      <td>29.222222</td>\n      <td>14.000000</td>\n      <td>1.184634</td>\n      <td>1.588606</td>\n      <td>0.335370</td>\n      <td>0.208000</td>\n      <td>47</td>\n      <td>55.677791</td>\n      <td>13</td>\n      <td>20.651877</td>\n      <td>connection</td>\n      <td>session</td>\n      <td>0.348214</td>\n      <td>0.371429</td>\n      <td>0.348214</td>\n      <td>0.371429</td>\n      <td>0.303571</td>\n      <td>0.257143</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-16.963913</td>\n      <td>0.000000</td>\n      <td>-10.529325</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>5688</th>\n      <td>connection</td>\n      <td>extension</td>\n      <td>0.250000</td>\n      <td>42.827586</td>\n      <td>12.500000</td>\n      <td>1.184634</td>\n      <td>1.597636</td>\n      <td>0.211875</td>\n      <td>0.324597</td>\n      <td>47</td>\n      <td>55.677791</td>\n      <td>9</td>\n      <td>14.378725</td>\n      <td>connection</td>\n      <td>extension</td>\n      <td>0.348214</td>\n      <td>0.312500</td>\n      <td>0.348214</td>\n      <td>0.312500</td>\n      <td>0.303571</td>\n      <td>0.375000</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-16.963913</td>\n      <td>-1.169925</td>\n      <td>-10.529325</td>\n      <td>-4.094738</td>\n    </tr>\n    <tr>\n      <th>5715</th>\n      <td>connection</td>\n      <td>tl session</td>\n      <td>0.200000</td>\n      <td>48.944444</td>\n      <td>13.000000</td>\n      <td>1.184634</td>\n      <td>5.561526</td>\n      <td>0.335370</td>\n      <td>0.268572</td>\n      <td>47</td>\n      <td>55.677791</td>\n      <td>6</td>\n      <td>33.369155</td>\n      <td>connection</td>\n      <td>TLS session</td>\n      <td>0.348214</td>\n      <td>0.111111</td>\n      <td>0.348214</td>\n      <td>0.111111</td>\n      <td>0.303571</td>\n      <td>0.777778</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-16.963913</td>\n      <td>0.000000</td>\n      <td>-10.529325</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>5723</th>\n      <td>connection</td>\n      <td>upstream connection</td>\n      <td>0.500000</td>\n      <td>21.517241</td>\n      <td>3.333333</td>\n      <td>1.184634</td>\n      <td>3.410212</td>\n      <td>0.211875</td>\n      <td>0.249378</td>\n      <td>47</td>\n      <td>55.677791</td>\n      <td>3</td>\n      <td>10.230635</td>\n      <td>connection</td>\n      <td>upstream connection</td>\n      <td>0.348214</td>\n      <td>0.285714</td>\n      <td>0.348214</td>\n      <td>0.285714</td>\n      <td>0.303571</td>\n      <td>0.428571</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-16.963913</td>\n      <td>0.000000</td>\n      <td>-10.529325</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>5719</th>\n      <td>connection</td>\n      <td>transport security</td>\n      <td>0.333333</td>\n      <td>77.000000</td>\n      <td>2.000000</td>\n      <td>1.184634</td>\n      <td>1.183904</td>\n      <td>0.211875</td>\n      <td>0.000000</td>\n      <td>47</td>\n      <td>55.677791</td>\n      <td>1</td>\n      <td>1.183904</td>\n      <td>connection</td>\n      <td>transport security</td>\n      <td>0.348214</td>\n      <td>0.500000</td>\n      <td>0.348214</td>\n      <td>0.500000</td>\n      <td>0.303571</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-16.963913</td>\n      <td>0.000000</td>\n      <td>-10.529325</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>5721</th>\n      <td>connection</td>\n      <td>transport socket decryption</td>\n      <td>0.333333</td>\n      <td>77.000000</td>\n      <td>2.000000</td>\n      <td>1.184634</td>\n      <td>7.027736</td>\n      <td>0.211875</td>\n      <td>0.000000</td>\n      <td>47</td>\n      <td>55.677791</td>\n      <td>1</td>\n      <td>7.027736</td>\n      <td>connection</td>\n      <td>transport socket decryption</td>\n      <td>0.348214</td>\n      <td>0.500000</td>\n      <td>0.348214</td>\n      <td>0.500000</td>\n      <td>0.303571</td>\n      <td>0.000000</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-16.963913</td>\n      <td>0.000000</td>\n      <td>-10.529325</td>\n      <td>0.000000</td>\n    </tr>\n    <tr>\n      <th>22603</th>\n      <td>request</td>\n      <td>connection</td>\n      <td>0.333333</td>\n      <td>4.333333</td>\n      <td>6.500000</td>\n      <td>1.177845</td>\n      <td>1.184634</td>\n      <td>0.245548</td>\n      <td>0.335370</td>\n      <td>38</td>\n      <td>44.758125</td>\n      <td>47</td>\n      <td>55.677791</td>\n      <td>request</td>\n      <td>connection</td>\n      <td>0.283951</td>\n      <td>0.348214</td>\n      <td>0.283951</td>\n      <td>0.348214</td>\n      <td>0.432099</td>\n      <td>0.303571</td>\n      <td>0.0</td>\n      <td>0.0</td>\n      <td>-18.718800</td>\n      <td>-16.963913</td>\n      <td>-3.509775</td>\n      <td>-10.529325</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n      <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-c5d7f552-947a-4821-9993-fde4bba56078')\"\n              title=\"Convert this dataframe to an interactive table.\"\n              style=\"display:none;\">\n\n  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n       width=\"24px\">\n    <path d=\"M0 0h24v24H0V0z\" fill=\"none\"/>\n    <path d=\"M18.56 5.44l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94zm-11 1L8.5 8.5l.94-2.06 2.06-.94-2.06-.94L8.5 2.5l-.94 2.06-2.06.94zm10 10l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94z\"/><path d=\"M17.41 7.96l-1.37-1.37c-.4-.4-.92-.59-1.43-.59-.52 0-1.04.2-1.43.59L10.3 9.45l-7.72 7.72c-.78.78-.78 2.05 0 2.83L4 21.41c.39.39.9.59 1.41.59.51 0 1.02-.2 1.41-.59l7.78-7.78 2.81-2.81c.8-.78.8-2.07 0-2.86zM5.41 20L4 18.59l7.72-7.72 1.47 1.35L5.41 20z\"/>\n  </svg>\n      </button>\n\n  <style>\n    .colab-df-container {\n      display:flex;\n      flex-wrap:wrap;\n      gap: 12px;\n    }\n\n    .colab-df-convert {\n      background-color: #E8F0FE;\n      border: none;\n      border-radius: 50%;\n      cursor: pointer;\n      display: none;\n      fill: #1967D2;\n      height: 32px;\n      padding: 0 0 0 0;\n      width: 32px;\n    }\n\n    .colab-df-convert:hover {\n      background-color: #E2EBFA;\n      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n      fill: #174EA6;\n    }\n\n    [theme=dark] .colab-df-convert {\n      background-color: #3B4455;\n      fill: #D2E3FC;\n    }\n\n    [theme=dark] .colab-df-convert:hover {\n      background-color: #434B5C;\n      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n      fill: #FFFFFF;\n    }\n  </style>\n\n      \n    </div>\n  </div>\n\n\n\n\nPhenomena graphic organizer\n", "meta": {"hexsha": "99768bab436073b3fb1d00ecececec442ba5d1a6", "size": 136390, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Autodidact_Graph_Visualizations_withRoles2_Multidoc.ipynb", "max_stars_repo_name": "rts1988/IntelligentTutoringSystem_Experiments", "max_stars_repo_head_hexsha": "b2f797a5bfff18fb37c7a779a19a72a75db7eeef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-30T17:10:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-30T17:10:30.000Z", "max_issues_repo_path": "Autodidact_Graph_Visualizations_withRoles2_Multidoc.ipynb", "max_issues_repo_name": "rts1988/IntelligentTutoringSystem_Experiments", "max_issues_repo_head_hexsha": "b2f797a5bfff18fb37c7a779a19a72a75db7eeef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Autodidact_Graph_Visualizations_withRoles2_Multidoc.ipynb", "max_forks_repo_name": "rts1988/IntelligentTutoringSystem_Experiments", "max_forks_repo_head_hexsha": "b2f797a5bfff18fb37c7a779a19a72a75db7eeef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-05-02T05:11:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-02T05:11:15.000Z", "avg_line_length": 58.4111349036, "max_line_length": 7053, "alphanum_fraction": 0.4852555173, "converted": true, "num_tokens": 18336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10521053389745762, "lm_q2_score": 0.03308598065306466, "lm_q1q2_score": 0.003480993689029886}}
{"text": "## Install lib\n\n\n```bash\n%%bash\nrm -rf /usr/local/cuda\nln -s /usr/local/cuda-10.1 /usr/local/cuda\n```\n\n\n```python\n!nvcc --version\n```\n\n    nvcc: NVIDIA (R) Cuda compiler driver\n    Copyright (c) 2005-2019 NVIDIA Corporation\n    Built on Sun_Jul_28_19:07:16_PDT_2019\n    Cuda compilation tools, release 10.1, V10.1.243\n\n\n\n```python\n!stat /usr/local/cuda\n```\n\n      File: /usr/local/cuda -> /usr/local/cuda-10.1\n      Size: 20        \tBlocks: 0          IO Block: 4096   symbolic link\n    Device: 31h/49d\tInode: 3154263     Links: 1\n    Access: (0777/lrwxrwxrwx)  Uid: (    0/    root)   Gid: (    0/    root)\n    Access: 2021-11-25 15:11:38.100786781 +0000\n    Modify: 2021-11-25 15:11:37.221787620 +0000\n    Change: 2021-11-25 15:11:37.221787620 +0000\n     Birth: -\n\n\n\n```python\n!pip uninstall -y triton\n```\n\n    Found existing installation: triton 0.2.3\n    Uninstalling triton-0.2.3:\n      Successfully uninstalled triton-0.2.3\n\n\n\n```python\n!pip uninstall -y torch\n```\n\n    Found existing installation: torch 1.6.0+cu101\n    Uninstalling torch-1.6.0+cu101:\n      Successfully uninstalled torch-1.6.0+cu101\n\n\n\n```bash\n%%bash\nexport LD_LIBRARY_PATH=/usr/lib/\n```\n\n\n```python\n!apt-get install clang-9 llvm-9 llvm-9-dev llvm-9-tools\n```\n\n    Reading package lists... Done\n    Building dependency tree       \n    Reading state information... Done\n    clang-9 is already the newest version (1:9-2~ubuntu18.04.2).\n    llvm-9 is already the newest version (1:9-2~ubuntu18.04.2).\n    llvm-9-dev is already the newest version (1:9-2~ubuntu18.04.2).\n    llvm-9-tools is already the newest version (1:9-2~ubuntu18.04.2).\n    0 upgraded, 0 newly installed, 0 to remove and 37 not upgraded.\n\n\n\n```python\n!pip install torch==1.6.0+cu101 torchvision==0.7.0+cu101 -f https://download.pytorch.org/whl/torch_stable.html\n```\n\n    Looking in links: https://download.pytorch.org/whl/torch_stable.html\n    Collecting torch==1.6.0+cu101\n      Using cached https://download.pytorch.org/whl/cu101/torch-1.6.0%2Bcu101-cp37-cp37m-linux_x86_64.whl (708.0 MB)\n    Requirement already satisfied: torchvision==0.7.0+cu101 in /usr/local/lib/python3.7/dist-packages (0.7.0+cu101)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from torch==1.6.0+cu101) (1.18.2)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from torch==1.6.0+cu101) (0.16.0)\n    Requirement already satisfied: pillow>=4.1.1 in /usr/local/lib/python3.7/dist-packages (from torchvision==0.7.0+cu101) (7.1.2)\n    Installing collected packages: torch\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    deepspeed 0.3.7 requires triton>=0.2.2, which is not installed.\n    torchtext 0.11.0 requires torch==1.10.0, but you have torch 1.6.0+cu101 which is incompatible.\n    torchaudio 0.10.0+cu111 requires torch==1.10.0, but you have torch 1.6.0+cu101 which is incompatible.\u001b[0m\n    Successfully installed torch-1.6.0+cu101\n\n\n\n```python\n%%writefile setup.sh\n\ngit clone https://github.com/NVIDIA/apex\ncd apex\npip install -v --disable-pip-version-check --no-cache-dir --global-option=\"--cpp_ext\" --global-option=\"--cuda_ext\" ./\n```\n\n    Overwriting setup.sh\n\n\n\n```python\n!sh setup.sh\n```\n\n    fatal: destination path 'apex' already exists and is not an empty directory.\n    /usr/local/lib/python3.7/dist-packages/pip/_internal/commands/install.py:232: UserWarning: Disabling all use of wheels due to the use of --build-option / --global-option / --install-option.\n      cmdoptions.check_install_build_global(options)\n    Using pip 21.1.3 from /usr/local/lib/python3.7/dist-packages/pip (python 3.7)\n    Value for scheme.platlib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n    distutils: /usr/local/lib/python3.7/dist-packages\n    sysconfig: /usr/lib/python3.7/site-packages\n    Value for scheme.purelib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n    distutils: /usr/local/lib/python3.7/dist-packages\n    sysconfig: /usr/lib/python3.7/site-packages\n    Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n    distutils: /usr/local/include/python3.7/UNKNOWN\n    sysconfig: /usr/include/python3.7m/UNKNOWN\n    Value for scheme.scripts does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n    distutils: /usr/local/bin\n    sysconfig: /usr/bin\n    Value for scheme.data does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n    distutils: /usr/local\n    sysconfig: /usr\n    Additional context:\n    user = False\n    home = None\n    root = None\n    prefix = None\n    Non-user install because site-packages writeable\n    Created temporary directory: /tmp/pip-ephem-wheel-cache-hvi085dy\n    Created temporary directory: /tmp/pip-req-tracker-pgfywie_\n    Initialized build tracking at /tmp/pip-req-tracker-pgfywie_\n    Created build tracker: /tmp/pip-req-tracker-pgfywie_\n    Entered build tracker: /tmp/pip-req-tracker-pgfywie_\n    Created temporary directory: /tmp/pip-install-_5lnz86r\n    Processing /content/apex\n      Created temporary directory: /tmp/pip-req-build-41vu3jcb\n    \u001b[33m  DEPRECATION: A future pip version will change local packages to be built in-place without first copying to a temporary directory. We recommend you use --use-feature=in-tree-build to test your packages with this new behavior before it becomes the default.\n       pip 21.3 will remove support for this functionality. You can find discussion regarding this at https://github.com/pypa/pip/issues/7555.\u001b[0m\n      Added file:///content/apex to build tracker '/tmp/pip-req-tracker-pgfywie_'\n        Running setup.py (path:/tmp/pip-req-build-41vu3jcb/setup.py) egg_info for package from file:///content/apex\n        Created temporary directory: /tmp/pip-pip-egg-info-cyzipaqb\n        Running command python setup.py egg_info\n    \n    \n        torch.__version__  = 1.6.0+cu101\n    \n    \n        running egg_info\n        creating /tmp/pip-pip-egg-info-cyzipaqb/apex.egg-info\n        writing /tmp/pip-pip-egg-info-cyzipaqb/apex.egg-info/PKG-INFO\n        writing dependency_links to /tmp/pip-pip-egg-info-cyzipaqb/apex.egg-info/dependency_links.txt\n        writing top-level names to /tmp/pip-pip-egg-info-cyzipaqb/apex.egg-info/top_level.txt\n        writing manifest file '/tmp/pip-pip-egg-info-cyzipaqb/apex.egg-info/SOURCES.txt'\n        adding license file 'LICENSE'\n        writing manifest file '/tmp/pip-pip-egg-info-cyzipaqb/apex.egg-info/SOURCES.txt'\n        /tmp/pip-req-build-41vu3jcb/setup.py:67: UserWarning: Option --pyprof not specified. Not installing PyProf dependencies!\n          warnings.warn(\"Option --pyprof not specified. Not installing PyProf dependencies!\")\n      Source in /tmp/pip-req-build-41vu3jcb has version 0.1, which satisfies requirement apex==0.1 from file:///content/apex\n      Removed apex==0.1 from file:///content/apex from build tracker '/tmp/pip-req-tracker-pgfywie_'\n    Created temporary directory: /tmp/pip-unpack-77j1xid4\n    Skipping wheel build for apex, due to binaries being disabled for it.\n    Installing collected packages: apex\n      Attempting uninstall: apex\n        Found existing installation: apex 0.1\n        Uninstalling apex-0.1:\n          Created temporary directory: /tmp/pip-uninstall-1fd81op5\n          Removing file or directory /usr/local/lib/python3.7/dist-packages/amp_C.cpython-37m-x86_64-linux-gnu.so\n          Created temporary directory: /usr/local/lib/python3.7/dist-packages/~pex-0.1-py3.7.egg-info\n          Removing file or directory /usr/local/lib/python3.7/dist-packages/apex-0.1-py3.7.egg-info\n          Created temporary directory: /usr/local/lib/python3.7/dist-packages/~pex\n          Removing file or directory /usr/local/lib/python3.7/dist-packages/apex/\n          Removing file or directory /usr/local/lib/python3.7/dist-packages/apex_C.cpython-37m-x86_64-linux-gnu.so\n          Removing file or directory /usr/local/lib/python3.7/dist-packages/fused_dense_cuda.cpython-37m-x86_64-linux-gnu.so\n          Removing file or directory /usr/local/lib/python3.7/dist-packages/fused_layer_norm_cuda.cpython-37m-x86_64-linux-gnu.so\n          Removing file or directory /usr/local/lib/python3.7/dist-packages/mlp_cuda.cpython-37m-x86_64-linux-gnu.so\n          Removing file or directory /usr/local/lib/python3.7/dist-packages/scaled_masked_softmax_cuda.cpython-37m-x86_64-linux-gnu.so\n          Removing file or directory /usr/local/lib/python3.7/dist-packages/scaled_upper_triang_masked_softmax_cuda.cpython-37m-x86_64-linux-gnu.so\n          Removing file or directory /usr/local/lib/python3.7/dist-packages/syncbn.cpython-37m-x86_64-linux-gnu.so\n          Successfully uninstalled apex-0.1\n      Value for scheme.platlib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n      distutils: /usr/local/lib/python3.7/dist-packages\n      sysconfig: /usr/lib/python3.7/site-packages\n      Value for scheme.purelib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n      distutils: /usr/local/lib/python3.7/dist-packages\n      sysconfig: /usr/lib/python3.7/site-packages\n      Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n      distutils: /usr/local/include/python3.7/apex\n      sysconfig: /usr/include/python3.7m/apex\n      Value for scheme.scripts does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n      distutils: /usr/local/bin\n      sysconfig: /usr/bin\n      Value for scheme.data does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n      distutils: /usr/local\n      sysconfig: /usr\n      Additional context:\n      user = False\n      home = None\n      root = None\n      prefix = None\n      Created temporary directory: /tmp/pip-record-xcqqv22a\n        Running command /usr/bin/python3 -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '\"'\"'/tmp/pip-req-build-41vu3jcb/setup.py'\"'\"'; __file__='\"'\"'/tmp/pip-req-build-41vu3jcb/setup.py'\"'\"';f = getattr(tokenize, '\"'\"'open'\"'\"', open)(__file__) if os.path.exists(__file__) else io.StringIO('\"'\"'from setuptools import setup; setup()'\"'\"');code = f.read().replace('\"'\"'\\r\\n'\"'\"', '\"'\"'\\n'\"'\"');f.close();exec(compile(code, __file__, '\"'\"'exec'\"'\"'))' --cpp_ext --cuda_ext install --record /tmp/pip-record-xcqqv22a/install-record.txt --single-version-externally-managed --compile --install-headers /usr/local/include/python3.7/apex\n    \n    \n        torch.__version__  = 1.6.0+cu101\n    \n    \n        /tmp/pip-req-build-41vu3jcb/setup.py:67: UserWarning: Option --pyprof not specified. Not installing PyProf dependencies!\n          warnings.warn(\"Option --pyprof not specified. Not installing PyProf dependencies!\")\n    \n        Compiling cuda extensions with\n        nvcc: NVIDIA (R) Cuda compiler driver\n        Copyright (c) 2005-2019 NVIDIA Corporation\n        Built on Sun_Jul_28_19:07:16_PDT_2019\n        Cuda compilation tools, release 10.1, V10.1.243\n        from /usr/local/cuda/bin\n    \n        running install\n        running build\n        running build_py\n        creating build\n        creating build/lib.linux-x86_64-3.7\n        creating build/lib.linux-x86_64-3.7/apex\n        copying apex/__init__.py -> build/lib.linux-x86_64-3.7/apex\n        copying apex/_autocast_utils.py -> build/lib.linux-x86_64-3.7/apex\n        creating build/lib.linux-x86_64-3.7/apex/multi_tensor_apply\n        copying apex/multi_tensor_apply/__init__.py -> build/lib.linux-x86_64-3.7/apex/multi_tensor_apply\n        copying apex/multi_tensor_apply/multi_tensor_apply.py -> build/lib.linux-x86_64-3.7/apex/multi_tensor_apply\n        creating build/lib.linux-x86_64-3.7/apex/amp\n        copying apex/amp/__init__.py -> build/lib.linux-x86_64-3.7/apex/amp\n        copying apex/amp/__version__.py -> build/lib.linux-x86_64-3.7/apex/amp\n        copying apex/amp/compat.py -> build/lib.linux-x86_64-3.7/apex/amp\n        copying apex/amp/_initialize.py -> build/lib.linux-x86_64-3.7/apex/amp\n        copying apex/amp/handle.py -> build/lib.linux-x86_64-3.7/apex/amp\n        copying apex/amp/wrap.py -> build/lib.linux-x86_64-3.7/apex/amp\n        copying apex/amp/rnn_compat.py -> build/lib.linux-x86_64-3.7/apex/amp\n        copying apex/amp/_process_optimizer.py -> build/lib.linux-x86_64-3.7/apex/amp\n        copying apex/amp/frontend.py -> build/lib.linux-x86_64-3.7/apex/amp\n        copying apex/amp/opt.py -> build/lib.linux-x86_64-3.7/apex/amp\n        copying apex/amp/scaler.py -> build/lib.linux-x86_64-3.7/apex/amp\n        copying apex/amp/_amp_state.py -> build/lib.linux-x86_64-3.7/apex/amp\n        copying apex/amp/utils.py -> build/lib.linux-x86_64-3.7/apex/amp\n        copying apex/amp/amp.py -> build/lib.linux-x86_64-3.7/apex/amp\n        creating build/lib.linux-x86_64-3.7/apex/contrib\n        copying apex/contrib/__init__.py -> build/lib.linux-x86_64-3.7/apex/contrib\n        creating build/lib.linux-x86_64-3.7/apex/mlp\n        copying apex/mlp/__init__.py -> build/lib.linux-x86_64-3.7/apex/mlp\n        copying apex/mlp/mlp.py -> build/lib.linux-x86_64-3.7/apex/mlp\n        creating build/lib.linux-x86_64-3.7/apex/normalization\n        copying apex/normalization/__init__.py -> build/lib.linux-x86_64-3.7/apex/normalization\n        copying apex/normalization/fused_layer_norm.py -> build/lib.linux-x86_64-3.7/apex/normalization\n        creating build/lib.linux-x86_64-3.7/apex/pyprof\n        copying apex/pyprof/__init__.py -> build/lib.linux-x86_64-3.7/apex/pyprof\n        creating build/lib.linux-x86_64-3.7/apex/RNN\n        copying apex/RNN/__init__.py -> build/lib.linux-x86_64-3.7/apex/RNN\n        copying apex/RNN/models.py -> build/lib.linux-x86_64-3.7/apex/RNN\n        copying apex/RNN/cells.py -> build/lib.linux-x86_64-3.7/apex/RNN\n        copying apex/RNN/RNNBackend.py -> build/lib.linux-x86_64-3.7/apex/RNN\n        creating build/lib.linux-x86_64-3.7/apex/transformer\n        copying apex/transformer/__init__.py -> build/lib.linux-x86_64-3.7/apex/transformer\n        copying apex/transformer/microbatches.py -> build/lib.linux-x86_64-3.7/apex/transformer\n        copying apex/transformer/enums.py -> build/lib.linux-x86_64-3.7/apex/transformer\n        copying apex/transformer/log_util.py -> build/lib.linux-x86_64-3.7/apex/transformer\n        copying apex/transformer/parallel_state.py -> build/lib.linux-x86_64-3.7/apex/transformer\n        copying apex/transformer/utils.py -> build/lib.linux-x86_64-3.7/apex/transformer\n        creating build/lib.linux-x86_64-3.7/apex/parallel\n        copying apex/parallel/sync_batchnorm.py -> build/lib.linux-x86_64-3.7/apex/parallel\n        copying apex/parallel/__init__.py -> build/lib.linux-x86_64-3.7/apex/parallel\n        copying apex/parallel/optimized_sync_batchnorm.py -> build/lib.linux-x86_64-3.7/apex/parallel\n        copying apex/parallel/distributed.py -> build/lib.linux-x86_64-3.7/apex/parallel\n        copying apex/parallel/multiproc.py -> build/lib.linux-x86_64-3.7/apex/parallel\n        copying apex/parallel/sync_batchnorm_kernel.py -> build/lib.linux-x86_64-3.7/apex/parallel\n        copying apex/parallel/LARC.py -> build/lib.linux-x86_64-3.7/apex/parallel\n        copying apex/parallel/optimized_sync_batchnorm_kernel.py -> build/lib.linux-x86_64-3.7/apex/parallel\n        creating build/lib.linux-x86_64-3.7/apex/fp16_utils\n        copying apex/fp16_utils/__init__.py -> build/lib.linux-x86_64-3.7/apex/fp16_utils\n        copying apex/fp16_utils/fp16util.py -> build/lib.linux-x86_64-3.7/apex/fp16_utils\n        copying apex/fp16_utils/fp16_optimizer.py -> build/lib.linux-x86_64-3.7/apex/fp16_utils\n        copying apex/fp16_utils/loss_scaler.py -> build/lib.linux-x86_64-3.7/apex/fp16_utils\n        creating build/lib.linux-x86_64-3.7/apex/fused_dense\n        copying apex/fused_dense/__init__.py -> build/lib.linux-x86_64-3.7/apex/fused_dense\n        copying apex/fused_dense/fused_dense.py -> build/lib.linux-x86_64-3.7/apex/fused_dense\n        creating build/lib.linux-x86_64-3.7/apex/optimizers\n        copying apex/optimizers/__init__.py -> build/lib.linux-x86_64-3.7/apex/optimizers\n        copying apex/optimizers/fused_novograd.py -> build/lib.linux-x86_64-3.7/apex/optimizers\n        copying apex/optimizers/fused_lamb.py -> build/lib.linux-x86_64-3.7/apex/optimizers\n        copying apex/optimizers/fused_adagrad.py -> build/lib.linux-x86_64-3.7/apex/optimizers\n        copying apex/optimizers/fused_adam.py -> build/lib.linux-x86_64-3.7/apex/optimizers\n        copying apex/optimizers/fused_sgd.py -> build/lib.linux-x86_64-3.7/apex/optimizers\n        creating build/lib.linux-x86_64-3.7/apex/reparameterization\n        copying apex/reparameterization/__init__.py -> build/lib.linux-x86_64-3.7/apex/reparameterization\n        copying apex/reparameterization/reparameterization.py -> build/lib.linux-x86_64-3.7/apex/reparameterization\n        copying apex/reparameterization/weight_norm.py -> build/lib.linux-x86_64-3.7/apex/reparameterization\n        creating build/lib.linux-x86_64-3.7/apex/amp/lists\n        copying apex/amp/lists/__init__.py -> build/lib.linux-x86_64-3.7/apex/amp/lists\n        copying apex/amp/lists/torch_overrides.py -> build/lib.linux-x86_64-3.7/apex/amp/lists\n        copying apex/amp/lists/functional_overrides.py -> build/lib.linux-x86_64-3.7/apex/amp/lists\n        copying apex/amp/lists/tensor_overrides.py -> build/lib.linux-x86_64-3.7/apex/amp/lists\n        creating build/lib.linux-x86_64-3.7/apex/contrib/groupbn\n        copying apex/contrib/groupbn/__init__.py -> build/lib.linux-x86_64-3.7/apex/contrib/groupbn\n        copying apex/contrib/groupbn/batch_norm.py -> build/lib.linux-x86_64-3.7/apex/contrib/groupbn\n        creating build/lib.linux-x86_64-3.7/apex/contrib/xentropy\n        copying apex/contrib/xentropy/__init__.py -> build/lib.linux-x86_64-3.7/apex/contrib/xentropy\n        copying apex/contrib/xentropy/softmax_xentropy.py -> build/lib.linux-x86_64-3.7/apex/contrib/xentropy\n        creating build/lib.linux-x86_64-3.7/apex/contrib/layer_norm\n        copying apex/contrib/layer_norm/__init__.py -> build/lib.linux-x86_64-3.7/apex/contrib/layer_norm\n        copying apex/contrib/layer_norm/layer_norm.py -> build/lib.linux-x86_64-3.7/apex/contrib/layer_norm\n        creating build/lib.linux-x86_64-3.7/apex/contrib/bottleneck\n        copying apex/contrib/bottleneck/__init__.py -> build/lib.linux-x86_64-3.7/apex/contrib/bottleneck\n        copying apex/contrib/bottleneck/bottleneck.py -> build/lib.linux-x86_64-3.7/apex/contrib/bottleneck\n        copying apex/contrib/bottleneck/bottleneck_module_test.py -> build/lib.linux-x86_64-3.7/apex/contrib/bottleneck\n        copying apex/contrib/bottleneck/test.py -> build/lib.linux-x86_64-3.7/apex/contrib/bottleneck\n        creating build/lib.linux-x86_64-3.7/apex/contrib/sparsity\n        copying apex/contrib/sparsity/__init__.py -> build/lib.linux-x86_64-3.7/apex/contrib/sparsity\n        copying apex/contrib/sparsity/asp.py -> build/lib.linux-x86_64-3.7/apex/contrib/sparsity\n        copying apex/contrib/sparsity/sparse_masklib.py -> build/lib.linux-x86_64-3.7/apex/contrib/sparsity\n        creating build/lib.linux-x86_64-3.7/apex/contrib/transducer\n        copying apex/contrib/transducer/__init__.py -> build/lib.linux-x86_64-3.7/apex/contrib/transducer\n        copying apex/contrib/transducer/transducer.py -> build/lib.linux-x86_64-3.7/apex/contrib/transducer\n        creating build/lib.linux-x86_64-3.7/apex/contrib/fmha\n        copying apex/contrib/fmha/__init__.py -> build/lib.linux-x86_64-3.7/apex/contrib/fmha\n        copying apex/contrib/fmha/fmha.py -> build/lib.linux-x86_64-3.7/apex/contrib/fmha\n        creating build/lib.linux-x86_64-3.7/apex/contrib/multihead_attn\n        copying apex/contrib/multihead_attn/fast_self_multihead_attn_norm_add_func.py -> build/lib.linux-x86_64-3.7/apex/contrib/multihead_attn\n        copying apex/contrib/multihead_attn/__init__.py -> build/lib.linux-x86_64-3.7/apex/contrib/multihead_attn\n        copying apex/contrib/multihead_attn/self_multihead_attn.py -> build/lib.linux-x86_64-3.7/apex/contrib/multihead_attn\n        copying apex/contrib/multihead_attn/fast_self_multihead_attn_func.py -> build/lib.linux-x86_64-3.7/apex/contrib/multihead_attn\n        copying apex/contrib/multihead_attn/fast_encdec_multihead_attn_func.py -> build/lib.linux-x86_64-3.7/apex/contrib/multihead_attn\n        copying apex/contrib/multihead_attn/fast_encdec_multihead_attn_norm_add_func.py -> build/lib.linux-x86_64-3.7/apex/contrib/multihead_attn\n        copying apex/contrib/multihead_attn/encdec_multihead_attn.py -> build/lib.linux-x86_64-3.7/apex/contrib/multihead_attn\n        copying apex/contrib/multihead_attn/encdec_multihead_attn_func.py -> build/lib.linux-x86_64-3.7/apex/contrib/multihead_attn\n        copying apex/contrib/multihead_attn/mask_softmax_dropout_func.py -> build/lib.linux-x86_64-3.7/apex/contrib/multihead_attn\n        copying apex/contrib/multihead_attn/self_multihead_attn_func.py -> build/lib.linux-x86_64-3.7/apex/contrib/multihead_attn\n        creating build/lib.linux-x86_64-3.7/apex/contrib/optimizers\n        copying apex/contrib/optimizers/__init__.py -> build/lib.linux-x86_64-3.7/apex/contrib/optimizers\n        copying apex/contrib/optimizers/distributed_fused_lamb.py -> build/lib.linux-x86_64-3.7/apex/contrib/optimizers\n        copying apex/contrib/optimizers/fp16_optimizer.py -> build/lib.linux-x86_64-3.7/apex/contrib/optimizers\n        copying apex/contrib/optimizers/fused_lamb.py -> build/lib.linux-x86_64-3.7/apex/contrib/optimizers\n        copying apex/contrib/optimizers/distributed_fused_adam_v3.py -> build/lib.linux-x86_64-3.7/apex/contrib/optimizers\n        copying apex/contrib/optimizers/fused_adam.py -> build/lib.linux-x86_64-3.7/apex/contrib/optimizers\n        copying apex/contrib/optimizers/fused_sgd.py -> build/lib.linux-x86_64-3.7/apex/contrib/optimizers\n        copying apex/contrib/optimizers/distributed_fused_adam_v2.py -> build/lib.linux-x86_64-3.7/apex/contrib/optimizers\n        copying apex/contrib/optimizers/distributed_fused_adam.py -> build/lib.linux-x86_64-3.7/apex/contrib/optimizers\n        creating build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/__init__.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/optim.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/misc.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/output.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/pooling.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/linear.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/blas.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/softmax.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/base.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/pointwise.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/index_slice_join_mutate.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/randomSample.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/dropout.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/__main__.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/activation.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/convert.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/utility.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/conv.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/normalization.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/data.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/usage.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/loss.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/prof.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/recurrentCell.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/embedding.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        copying apex/pyprof/prof/reduction.py -> build/lib.linux-x86_64-3.7/apex/pyprof/prof\n        creating build/lib.linux-x86_64-3.7/apex/pyprof/parse\n        copying apex/pyprof/parse/__init__.py -> build/lib.linux-x86_64-3.7/apex/pyprof/parse\n        copying apex/pyprof/parse/nvvp.py -> build/lib.linux-x86_64-3.7/apex/pyprof/parse\n        copying apex/pyprof/parse/kernel.py -> build/lib.linux-x86_64-3.7/apex/pyprof/parse\n        copying apex/pyprof/parse/__main__.py -> build/lib.linux-x86_64-3.7/apex/pyprof/parse\n        copying apex/pyprof/parse/parse.py -> build/lib.linux-x86_64-3.7/apex/pyprof/parse\n        copying apex/pyprof/parse/db.py -> build/lib.linux-x86_64-3.7/apex/pyprof/parse\n        creating build/lib.linux-x86_64-3.7/apex/pyprof/nvtx\n        copying apex/pyprof/nvtx/__init__.py -> build/lib.linux-x86_64-3.7/apex/pyprof/nvtx\n        copying apex/pyprof/nvtx/nvmarker.py -> build/lib.linux-x86_64-3.7/apex/pyprof/nvtx\n        creating build/lib.linux-x86_64-3.7/apex/transformer/_data\n        copying apex/transformer/_data/__init__.py -> build/lib.linux-x86_64-3.7/apex/transformer/_data\n        copying apex/transformer/_data/_batchsampler.py -> build/lib.linux-x86_64-3.7/apex/transformer/_data\n        creating build/lib.linux-x86_64-3.7/apex/transformer/amp\n        copying apex/transformer/amp/__init__.py -> build/lib.linux-x86_64-3.7/apex/transformer/amp\n        copying apex/transformer/amp/grad_scaler.py -> build/lib.linux-x86_64-3.7/apex/transformer/amp\n        creating build/lib.linux-x86_64-3.7/apex/transformer/functional\n        copying apex/transformer/functional/__init__.py -> build/lib.linux-x86_64-3.7/apex/transformer/functional\n        copying apex/transformer/functional/fused_softmax.py -> build/lib.linux-x86_64-3.7/apex/transformer/functional\n        creating build/lib.linux-x86_64-3.7/apex/transformer/pipeline_parallel\n        copying apex/transformer/pipeline_parallel/_timers.py -> build/lib.linux-x86_64-3.7/apex/transformer/pipeline_parallel\n        copying apex/transformer/pipeline_parallel/__init__.py -> build/lib.linux-x86_64-3.7/apex/transformer/pipeline_parallel\n        copying apex/transformer/pipeline_parallel/p2p_communication.py -> build/lib.linux-x86_64-3.7/apex/transformer/pipeline_parallel\n        copying apex/transformer/pipeline_parallel/utils.py -> build/lib.linux-x86_64-3.7/apex/transformer/pipeline_parallel\n        creating build/lib.linux-x86_64-3.7/apex/transformer/tensor_parallel\n        copying apex/transformer/tensor_parallel/__init__.py -> build/lib.linux-x86_64-3.7/apex/transformer/tensor_parallel\n        copying apex/transformer/tensor_parallel/cross_entropy.py -> build/lib.linux-x86_64-3.7/apex/transformer/tensor_parallel\n        copying apex/transformer/tensor_parallel/mappings.py -> build/lib.linux-x86_64-3.7/apex/transformer/tensor_parallel\n        copying apex/transformer/tensor_parallel/data.py -> build/lib.linux-x86_64-3.7/apex/transformer/tensor_parallel\n        copying apex/transformer/tensor_parallel/layers.py -> build/lib.linux-x86_64-3.7/apex/transformer/tensor_parallel\n        copying apex/transformer/tensor_parallel/random.py -> build/lib.linux-x86_64-3.7/apex/transformer/tensor_parallel\n        copying apex/transformer/tensor_parallel/memory.py -> build/lib.linux-x86_64-3.7/apex/transformer/tensor_parallel\n        copying apex/transformer/tensor_parallel/utils.py -> build/lib.linux-x86_64-3.7/apex/transformer/tensor_parallel\n        creating build/lib.linux-x86_64-3.7/apex/transformer/testing\n        copying apex/transformer/testing/__init__.py -> build/lib.linux-x86_64-3.7/apex/transformer/testing\n        copying apex/transformer/testing/standalone_gpt.py -> build/lib.linux-x86_64-3.7/apex/transformer/testing\n        copying apex/transformer/testing/arguments.py -> build/lib.linux-x86_64-3.7/apex/transformer/testing\n        copying apex/transformer/testing/standalone_bert.py -> build/lib.linux-x86_64-3.7/apex/transformer/testing\n        copying apex/transformer/testing/commons.py -> build/lib.linux-x86_64-3.7/apex/transformer/testing\n        copying apex/transformer/testing/global_vars.py -> build/lib.linux-x86_64-3.7/apex/transformer/testing\n        creating build/lib.linux-x86_64-3.7/apex/transformer/pipeline_parallel/schedules\n        copying apex/transformer/pipeline_parallel/schedules/__init__.py -> build/lib.linux-x86_64-3.7/apex/transformer/pipeline_parallel/schedules\n        copying apex/transformer/pipeline_parallel/schedules/fwd_bwd_pipelining_without_interleaving.py -> build/lib.linux-x86_64-3.7/apex/transformer/pipeline_parallel/schedules\n        copying apex/transformer/pipeline_parallel/schedules/fwd_bwd_pipelining_with_interleaving.py -> build/lib.linux-x86_64-3.7/apex/transformer/pipeline_parallel/schedules\n        copying apex/transformer/pipeline_parallel/schedules/common.py -> build/lib.linux-x86_64-3.7/apex/transformer/pipeline_parallel/schedules\n        copying apex/transformer/pipeline_parallel/schedules/fwd_bwd_no_pipelining.py -> build/lib.linux-x86_64-3.7/apex/transformer/pipeline_parallel/schedules\n        running build_ext\n        building 'apex_C' extension\n        creating /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7\n        creating /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc\n        Emitting ninja build file /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/build.ninja...\n        Compiling objects...\n        Allowing ninja to set a default number of workers... (overridable by setting the environment variable MAX_JOBS=N)\n        [1/1] c++ -MMD -MF /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/flatten_unflatten.o.d -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/flatten_unflatten.cpp -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/flatten_unflatten.o -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=apex_C -D_GLIBCXX_USE_CXX11_ABI=0 -std=c++14\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Parallel.h:149:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/utils.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/nn/cloneable.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/nn.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:7,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/flatten_unflatten.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ParallelOpenMP.h:84:0: warning: ignoring #pragma omp parallel [-Wunknown-pragmas]\n         #pragma omp parallel for if ((end - begin) >= grain_size)\n    \n        In file included from /tmp/pip-req-build-41vu3jcb/csrc/flatten_unflatten.cpp:2:0:\n        /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/utils/tensor_flatten.h: In member function \u2018at::DeprecatedTypeProperties& torch::utils::TensorGroup::type()\u2019:\n        /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/utils/tensor_flatten.h:36:28: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n             return tensors[0].type();\n                                    ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/flatten_unflatten.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        x86_64-linux-gnu-g++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/flatten_unflatten.o -L/usr/local/lib/python3.7/dist-packages/torch/lib -lc10 -ltorch -ltorch_cpu -ltorch_python -o build/lib.linux-x86_64-3.7/apex_C.cpython-37m-x86_64-linux-gnu.so\n        building 'amp_C' extension\n        Emitting ninja build file /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/build.ninja...\n        Compiling objects...\n        Allowing ninja to set a default number of workers... (overridable by setting the environment variable MAX_JOBS=N)\n        [1/12] /usr/local/cuda/bin/nvcc -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/multi_tensor_scale_kernel.cu -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_scale_kernel.o -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr --compiler-options ''\"'\"'-fPIC'\"'\"'' -lineinfo -O3 --use_fast_math -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=amp_C -D_GLIBCXX_USE_CXX11_ABI=0 -gencode=arch=compute_37,code=sm_37 -std=c++14\n        [2/12] /usr/local/cuda/bin/nvcc -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/multi_tensor_sgd_kernel.cu -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_sgd_kernel.o -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr --compiler-options ''\"'\"'-fPIC'\"'\"'' -lineinfo -O3 --use_fast_math -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=amp_C -D_GLIBCXX_USE_CXX11_ABI=0 -gencode=arch=compute_37,code=sm_37 -std=c++14\n        [3/12] c++ -MMD -MF /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/amp_C_frontend.o.d -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/amp_C_frontend.cpp -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/amp_C_frontend.o -O3 -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=amp_C -D_GLIBCXX_USE_CXX11_ABI=0 -std=c++14\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Parallel.h:149:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/utils.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/nn/cloneable.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/nn.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:7,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/amp_C_frontend.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ParallelOpenMP.h:84:0: warning: ignoring #pragma omp parallel [-Wunknown-pragmas]\n         #pragma omp parallel for if ((end - begin) >= grain_size)\n    \n        [4/12] /usr/local/cuda/bin/nvcc -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/multi_tensor_axpby_kernel.cu -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_axpby_kernel.o -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr --compiler-options ''\"'\"'-fPIC'\"'\"'' -lineinfo -O3 --use_fast_math -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=amp_C -D_GLIBCXX_USE_CXX11_ABI=0 -gencode=arch=compute_37,code=sm_37 -std=c++14\n        [5/12] /usr/local/cuda/bin/nvcc -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/multi_tensor_l2norm_kernel.cu -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_l2norm_kernel.o -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr --compiler-options ''\"'\"'-fPIC'\"'\"'' -lineinfo -O3 --use_fast_math -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=amp_C -D_GLIBCXX_USE_CXX11_ABI=0 -gencode=arch=compute_37,code=sm_37 -std=c++14\n        [6/12] /usr/local/cuda/bin/nvcc -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/multi_tensor_l2norm_scale_kernel.cu -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_l2norm_scale_kernel.o -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr --compiler-options ''\"'\"'-fPIC'\"'\"'' -lineinfo -O3 --use_fast_math -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=amp_C -D_GLIBCXX_USE_CXX11_ABI=0 -gencode=arch=compute_37,code=sm_37 -std=c++14\n        [7/12] /usr/local/cuda/bin/nvcc -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/multi_tensor_lamb_stage_2.cu -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_lamb_stage_2.o -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr --compiler-options ''\"'\"'-fPIC'\"'\"'' -lineinfo -O3 --use_fast_math -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=amp_C -D_GLIBCXX_USE_CXX11_ABI=0 -gencode=arch=compute_37,code=sm_37 -std=c++14\n        [8/12] /usr/local/cuda/bin/nvcc -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/multi_tensor_lamb_stage_1.cu -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_lamb_stage_1.o -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr --compiler-options ''\"'\"'-fPIC'\"'\"'' -lineinfo -O3 --use_fast_math -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=amp_C -D_GLIBCXX_USE_CXX11_ABI=0 -gencode=arch=compute_37,code=sm_37 -std=c++14\n        [9/12] /usr/local/cuda/bin/nvcc -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/multi_tensor_adam.cu -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_adam.o -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr --compiler-options ''\"'\"'-fPIC'\"'\"'' -lineinfo -O3 --use_fast_math -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=amp_C -D_GLIBCXX_USE_CXX11_ABI=0 -gencode=arch=compute_37,code=sm_37 -std=c++14\n        [10/12] /usr/local/cuda/bin/nvcc -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/multi_tensor_adagrad.cu -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_adagrad.o -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr --compiler-options ''\"'\"'-fPIC'\"'\"'' -lineinfo -O3 --use_fast_math -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=amp_C -D_GLIBCXX_USE_CXX11_ABI=0 -gencode=arch=compute_37,code=sm_37 -std=c++14\n        [11/12] /usr/local/cuda/bin/nvcc -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/multi_tensor_novograd.cu -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_novograd.o -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr --compiler-options ''\"'\"'-fPIC'\"'\"'' -lineinfo -O3 --use_fast_math -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=amp_C -D_GLIBCXX_USE_CXX11_ABI=0 -gencode=arch=compute_37,code=sm_37 -std=c++14\n        [12/12] /usr/local/cuda/bin/nvcc -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/multi_tensor_lamb.cu -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_lamb.o -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr --compiler-options ''\"'\"'-fPIC'\"'\"'' -lineinfo -O3 --use_fast_math -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=amp_C -D_GLIBCXX_USE_CXX11_ABI=0 -gencode=arch=compute_37,code=sm_37 -std=c++14\n        x86_64-linux-gnu-g++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/amp_C_frontend.o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_sgd_kernel.o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_scale_kernel.o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_axpby_kernel.o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_l2norm_kernel.o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_l2norm_scale_kernel.o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_lamb_stage_1.o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_lamb_stage_2.o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_adam.o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_adagrad.o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_novograd.o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/multi_tensor_lamb.o -L/usr/local/lib/python3.7/dist-packages/torch/lib -L/usr/local/cuda/lib64 -lc10 -ltorch -ltorch_cpu -ltorch_python -lcudart -lc10_cuda -ltorch_cuda -o build/lib.linux-x86_64-3.7/amp_C.cpython-37m-x86_64-linux-gnu.so\n        building 'syncbn' extension\n        Emitting ninja build file /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/build.ninja...\n        Compiling objects...\n        Allowing ninja to set a default number of workers... (overridable by setting the environment variable MAX_JOBS=N)\n        [1/2] /usr/local/cuda/bin/nvcc -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/welford.cu -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/welford.o -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr --compiler-options ''\"'\"'-fPIC'\"'\"'' -O3 -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=syncbn -D_GLIBCXX_USE_CXX11_ABI=0 -gencode=arch=compute_37,code=sm_37 -std=c++14\n        [2/2] c++ -MMD -MF /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/syncbn.o.d -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/syncbn.cpp -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/syncbn.o -O3 -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=syncbn -D_GLIBCXX_USE_CXX11_ABI=0 -std=c++14\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Parallel.h:149:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/utils.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/nn/cloneable.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/nn.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:7,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/syncbn.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ParallelOpenMP.h:84:0: warning: ignoring #pragma omp parallel [-Wunknown-pragmas]\n         #pragma omp parallel for if ((end - begin) >= grain_size)\n    \n        x86_64-linux-gnu-g++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/syncbn.o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/welford.o -L/usr/local/lib/python3.7/dist-packages/torch/lib -L/usr/local/cuda/lib64 -lc10 -ltorch -ltorch_cpu -ltorch_python -lcudart -lc10_cuda -ltorch_cuda -o build/lib.linux-x86_64-3.7/syncbn.cpython-37m-x86_64-linux-gnu.so\n        building 'fused_layer_norm_cuda' extension\n        Emitting ninja build file /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/build.ninja...\n        Compiling objects...\n        Allowing ninja to set a default number of workers... (overridable by setting the environment variable MAX_JOBS=N)\n        [1/2] /usr/local/cuda/bin/nvcc -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda_kernel.cu -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/layer_norm_cuda_kernel.o -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr --compiler-options ''\"'\"'-fPIC'\"'\"'' -maxrregcount=50 -O3 --use_fast_math -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=fused_layer_norm_cuda -D_GLIBCXX_USE_CXX11_ABI=0 -gencode=arch=compute_37,code=sm_37 -std=c++14\n        [2/2] c++ -MMD -MF /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/layer_norm_cuda.o.d -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/layer_norm_cuda.o -O3 -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=fused_layer_norm_cuda -D_GLIBCXX_USE_CXX11_ABI=0 -std=c++14\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Parallel.h:149:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/utils.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/nn/cloneable.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/nn.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:7,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ParallelOpenMP.h:84:0: warning: ignoring #pragma omp parallel [-Wunknown-pragmas]\n         #pragma omp parallel for if ((end - begin) >= grain_size)\n    \n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/DeviceType.h:8:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Device.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Allocator.h:6,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp: In function \u2018std::vector<at::Tensor> layer_norm(at::Tensor, c10::IntArrayRef, double)\u2019:\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:42: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                                                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/macros/Macros.h:146:65: note: in definition of macro \u2018C10_UNLIKELY\u2019\n         #define C10_UNLIKELY(expr)  (__builtin_expect(static_cast<bool>(expr), 0))\n                                                                         ^~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:330:7: note: in expansion of macro \u2018C10_UNLIKELY_OR_CONST\u2019\n           if (C10_UNLIKELY_OR_CONST(!(cond))) {                               \\\n               ^~~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:318:3: note: in expansion of macro \u2018TORCH_CHECK_WITH_MSG\u2019\n           TORCH_CHECK_WITH_MSG(error_t, cond, \"\", __VA_ARGS__)\n           ^~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:341:32: note: in expansion of macro \u2018TORCH_CHECK_WITH\u2019\n         #define TORCH_CHECK(cond, ...) TORCH_CHECK_WITH(Error, cond, __VA_ARGS__)\n                                        ^~~~~~~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:23: note: in expansion of macro \u2018TORCH_CHECK\u2019\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                               ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:119:24: note: in expansion of macro \u2018CHECK_CUDA\u2019\n         #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)\n                                ^~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:129:3: note: in expansion of macro \u2018CHECK_INPUT\u2019\n           CHECK_INPUT(input);\n           ^~~~~~~~~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/DeviceType.h:8:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Device.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Allocator.h:6,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp: In function \u2018std::vector<at::Tensor> layer_norm_affine(at::Tensor, c10::IntArrayRef, at::Tensor, at::Tensor, double)\u2019:\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:42: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                                                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/macros/Macros.h:146:65: note: in definition of macro \u2018C10_UNLIKELY\u2019\n         #define C10_UNLIKELY(expr)  (__builtin_expect(static_cast<bool>(expr), 0))\n                                                                         ^~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:330:7: note: in expansion of macro \u2018C10_UNLIKELY_OR_CONST\u2019\n           if (C10_UNLIKELY_OR_CONST(!(cond))) {                               \\\n               ^~~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:318:3: note: in expansion of macro \u2018TORCH_CHECK_WITH_MSG\u2019\n           TORCH_CHECK_WITH_MSG(error_t, cond, \"\", __VA_ARGS__)\n           ^~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:341:32: note: in expansion of macro \u2018TORCH_CHECK_WITH\u2019\n         #define TORCH_CHECK(cond, ...) TORCH_CHECK_WITH(Error, cond, __VA_ARGS__)\n                                        ^~~~~~~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:23: note: in expansion of macro \u2018TORCH_CHECK\u2019\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                               ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:119:24: note: in expansion of macro \u2018CHECK_CUDA\u2019\n         #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)\n                                ^~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:150:3: note: in expansion of macro \u2018CHECK_INPUT\u2019\n           CHECK_INPUT(input);\n           ^~~~~~~~~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/DeviceType.h:8:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Device.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Allocator.h:6,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:42: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                                                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/macros/Macros.h:146:65: note: in definition of macro \u2018C10_UNLIKELY\u2019\n         #define C10_UNLIKELY(expr)  (__builtin_expect(static_cast<bool>(expr), 0))\n                                                                         ^~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:330:7: note: in expansion of macro \u2018C10_UNLIKELY_OR_CONST\u2019\n           if (C10_UNLIKELY_OR_CONST(!(cond))) {                               \\\n               ^~~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:318:3: note: in expansion of macro \u2018TORCH_CHECK_WITH_MSG\u2019\n           TORCH_CHECK_WITH_MSG(error_t, cond, \"\", __VA_ARGS__)\n           ^~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:341:32: note: in expansion of macro \u2018TORCH_CHECK_WITH\u2019\n         #define TORCH_CHECK(cond, ...) TORCH_CHECK_WITH(Error, cond, __VA_ARGS__)\n                                        ^~~~~~~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:23: note: in expansion of macro \u2018TORCH_CHECK\u2019\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                               ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:119:24: note: in expansion of macro \u2018CHECK_CUDA\u2019\n         #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)\n                                ^~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:151:3: note: in expansion of macro \u2018CHECK_INPUT\u2019\n           CHECK_INPUT(gamma);\n           ^~~~~~~~~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/DeviceType.h:8:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Device.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Allocator.h:6,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:42: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                                                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/macros/Macros.h:146:65: note: in definition of macro \u2018C10_UNLIKELY\u2019\n         #define C10_UNLIKELY(expr)  (__builtin_expect(static_cast<bool>(expr), 0))\n                                                                         ^~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:330:7: note: in expansion of macro \u2018C10_UNLIKELY_OR_CONST\u2019\n           if (C10_UNLIKELY_OR_CONST(!(cond))) {                               \\\n               ^~~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:318:3: note: in expansion of macro \u2018TORCH_CHECK_WITH_MSG\u2019\n           TORCH_CHECK_WITH_MSG(error_t, cond, \"\", __VA_ARGS__)\n           ^~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:341:32: note: in expansion of macro \u2018TORCH_CHECK_WITH\u2019\n         #define TORCH_CHECK(cond, ...) TORCH_CHECK_WITH(Error, cond, __VA_ARGS__)\n                                        ^~~~~~~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:23: note: in expansion of macro \u2018TORCH_CHECK\u2019\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                               ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:119:24: note: in expansion of macro \u2018CHECK_CUDA\u2019\n         #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)\n                                ^~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:152:3: note: in expansion of macro \u2018CHECK_INPUT\u2019\n           CHECK_INPUT(beta);\n           ^~~~~~~~~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/DeviceType.h:8:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Device.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Allocator.h:6,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp: In function \u2018std::vector<at::Tensor> layer_norm_affine_mixed_dtypes(at::Tensor, c10::IntArrayRef, at::Tensor, at::Tensor, double)\u2019:\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:42: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                                                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/macros/Macros.h:146:65: note: in definition of macro \u2018C10_UNLIKELY\u2019\n         #define C10_UNLIKELY(expr)  (__builtin_expect(static_cast<bool>(expr), 0))\n                                                                         ^~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:330:7: note: in expansion of macro \u2018C10_UNLIKELY_OR_CONST\u2019\n           if (C10_UNLIKELY_OR_CONST(!(cond))) {                               \\\n               ^~~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:318:3: note: in expansion of macro \u2018TORCH_CHECK_WITH_MSG\u2019\n           TORCH_CHECK_WITH_MSG(error_t, cond, \"\", __VA_ARGS__)\n           ^~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:341:32: note: in expansion of macro \u2018TORCH_CHECK_WITH\u2019\n         #define TORCH_CHECK(cond, ...) TORCH_CHECK_WITH(Error, cond, __VA_ARGS__)\n                                        ^~~~~~~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:23: note: in expansion of macro \u2018TORCH_CHECK\u2019\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                               ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:119:24: note: in expansion of macro \u2018CHECK_CUDA\u2019\n         #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)\n                                ^~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:174:3: note: in expansion of macro \u2018CHECK_INPUT\u2019\n           CHECK_INPUT(input);\n           ^~~~~~~~~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/DeviceType.h:8:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Device.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Allocator.h:6,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp: In function \u2018at::Tensor layer_norm_gradient(at::Tensor, at::Tensor, at::Tensor, at::Tensor, c10::IntArrayRef, double)\u2019:\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:42: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                                                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/macros/Macros.h:146:65: note: in definition of macro \u2018C10_UNLIKELY\u2019\n         #define C10_UNLIKELY(expr)  (__builtin_expect(static_cast<bool>(expr), 0))\n                                                                         ^~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:330:7: note: in expansion of macro \u2018C10_UNLIKELY_OR_CONST\u2019\n           if (C10_UNLIKELY_OR_CONST(!(cond))) {                               \\\n               ^~~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:318:3: note: in expansion of macro \u2018TORCH_CHECK_WITH_MSG\u2019\n           TORCH_CHECK_WITH_MSG(error_t, cond, \"\", __VA_ARGS__)\n           ^~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:341:32: note: in expansion of macro \u2018TORCH_CHECK_WITH\u2019\n         #define TORCH_CHECK(cond, ...) TORCH_CHECK_WITH(Error, cond, __VA_ARGS__)\n                                        ^~~~~~~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:23: note: in expansion of macro \u2018TORCH_CHECK\u2019\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                               ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:119:24: note: in expansion of macro \u2018CHECK_CUDA\u2019\n         #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)\n                                ^~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:216:3: note: in expansion of macro \u2018CHECK_INPUT\u2019\n           CHECK_INPUT(dout);\n           ^~~~~~~~~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/DeviceType.h:8:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Device.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Allocator.h:6,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:42: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                                                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/macros/Macros.h:146:65: note: in definition of macro \u2018C10_UNLIKELY\u2019\n         #define C10_UNLIKELY(expr)  (__builtin_expect(static_cast<bool>(expr), 0))\n                                                                         ^~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:330:7: note: in expansion of macro \u2018C10_UNLIKELY_OR_CONST\u2019\n           if (C10_UNLIKELY_OR_CONST(!(cond))) {                               \\\n               ^~~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:318:3: note: in expansion of macro \u2018TORCH_CHECK_WITH_MSG\u2019\n           TORCH_CHECK_WITH_MSG(error_t, cond, \"\", __VA_ARGS__)\n           ^~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:341:32: note: in expansion of macro \u2018TORCH_CHECK_WITH\u2019\n         #define TORCH_CHECK(cond, ...) TORCH_CHECK_WITH(Error, cond, __VA_ARGS__)\n                                        ^~~~~~~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:23: note: in expansion of macro \u2018TORCH_CHECK\u2019\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                               ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:119:24: note: in expansion of macro \u2018CHECK_CUDA\u2019\n         #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)\n                                ^~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:217:3: note: in expansion of macro \u2018CHECK_INPUT\u2019\n           CHECK_INPUT(mean);\n           ^~~~~~~~~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/DeviceType.h:8:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Device.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Allocator.h:6,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:42: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                                                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/macros/Macros.h:146:65: note: in definition of macro \u2018C10_UNLIKELY\u2019\n         #define C10_UNLIKELY(expr)  (__builtin_expect(static_cast<bool>(expr), 0))\n                                                                         ^~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:330:7: note: in expansion of macro \u2018C10_UNLIKELY_OR_CONST\u2019\n           if (C10_UNLIKELY_OR_CONST(!(cond))) {                               \\\n               ^~~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:318:3: note: in expansion of macro \u2018TORCH_CHECK_WITH_MSG\u2019\n           TORCH_CHECK_WITH_MSG(error_t, cond, \"\", __VA_ARGS__)\n           ^~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:341:32: note: in expansion of macro \u2018TORCH_CHECK_WITH\u2019\n         #define TORCH_CHECK(cond, ...) TORCH_CHECK_WITH(Error, cond, __VA_ARGS__)\n                                        ^~~~~~~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:23: note: in expansion of macro \u2018TORCH_CHECK\u2019\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                               ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:119:24: note: in expansion of macro \u2018CHECK_CUDA\u2019\n         #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)\n                                ^~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:218:3: note: in expansion of macro \u2018CHECK_INPUT\u2019\n           CHECK_INPUT(invvar);\n           ^~~~~~~~~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/DeviceType.h:8:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Device.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Allocator.h:6,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:42: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                                                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/macros/Macros.h:146:65: note: in definition of macro \u2018C10_UNLIKELY\u2019\n         #define C10_UNLIKELY(expr)  (__builtin_expect(static_cast<bool>(expr), 0))\n                                                                         ^~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:330:7: note: in expansion of macro \u2018C10_UNLIKELY_OR_CONST\u2019\n           if (C10_UNLIKELY_OR_CONST(!(cond))) {                               \\\n               ^~~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:318:3: note: in expansion of macro \u2018TORCH_CHECK_WITH_MSG\u2019\n           TORCH_CHECK_WITH_MSG(error_t, cond, \"\", __VA_ARGS__)\n           ^~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:341:32: note: in expansion of macro \u2018TORCH_CHECK_WITH\u2019\n         #define TORCH_CHECK(cond, ...) TORCH_CHECK_WITH(Error, cond, __VA_ARGS__)\n                                        ^~~~~~~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:23: note: in expansion of macro \u2018TORCH_CHECK\u2019\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                               ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:119:24: note: in expansion of macro \u2018CHECK_CUDA\u2019\n         #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)\n                                ^~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:219:3: note: in expansion of macro \u2018CHECK_INPUT\u2019\n           CHECK_INPUT(input);\n           ^~~~~~~~~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/DeviceType.h:8:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Device.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Allocator.h:6,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp: In function \u2018std::vector<at::Tensor> layer_norm_gradient_affine(at::Tensor, at::Tensor, at::Tensor, at::Tensor, c10::IntArrayRef, at::Tensor, at::Tensor, double)\u2019:\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:42: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                                                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/macros/Macros.h:146:65: note: in definition of macro \u2018C10_UNLIKELY\u2019\n         #define C10_UNLIKELY(expr)  (__builtin_expect(static_cast<bool>(expr), 0))\n                                                                         ^~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:330:7: note: in expansion of macro \u2018C10_UNLIKELY_OR_CONST\u2019\n           if (C10_UNLIKELY_OR_CONST(!(cond))) {                               \\\n               ^~~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:318:3: note: in expansion of macro \u2018TORCH_CHECK_WITH_MSG\u2019\n           TORCH_CHECK_WITH_MSG(error_t, cond, \"\", __VA_ARGS__)\n           ^~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:341:32: note: in expansion of macro \u2018TORCH_CHECK_WITH\u2019\n         #define TORCH_CHECK(cond, ...) TORCH_CHECK_WITH(Error, cond, __VA_ARGS__)\n                                        ^~~~~~~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:23: note: in expansion of macro \u2018TORCH_CHECK\u2019\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                               ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:119:24: note: in expansion of macro \u2018CHECK_CUDA\u2019\n         #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)\n                                ^~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:242:3: note: in expansion of macro \u2018CHECK_INPUT\u2019\n           CHECK_INPUT(dout);\n           ^~~~~~~~~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/DeviceType.h:8:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Device.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Allocator.h:6,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:42: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                                                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/macros/Macros.h:146:65: note: in definition of macro \u2018C10_UNLIKELY\u2019\n         #define C10_UNLIKELY(expr)  (__builtin_expect(static_cast<bool>(expr), 0))\n                                                                         ^~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:330:7: note: in expansion of macro \u2018C10_UNLIKELY_OR_CONST\u2019\n           if (C10_UNLIKELY_OR_CONST(!(cond))) {                               \\\n               ^~~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:318:3: note: in expansion of macro \u2018TORCH_CHECK_WITH_MSG\u2019\n           TORCH_CHECK_WITH_MSG(error_t, cond, \"\", __VA_ARGS__)\n           ^~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:341:32: note: in expansion of macro \u2018TORCH_CHECK_WITH\u2019\n         #define TORCH_CHECK(cond, ...) TORCH_CHECK_WITH(Error, cond, __VA_ARGS__)\n                                        ^~~~~~~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:23: note: in expansion of macro \u2018TORCH_CHECK\u2019\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                               ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:119:24: note: in expansion of macro \u2018CHECK_CUDA\u2019\n         #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)\n                                ^~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:243:3: note: in expansion of macro \u2018CHECK_INPUT\u2019\n           CHECK_INPUT(mean);\n           ^~~~~~~~~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/DeviceType.h:8:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Device.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Allocator.h:6,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:42: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                                                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/macros/Macros.h:146:65: note: in definition of macro \u2018C10_UNLIKELY\u2019\n         #define C10_UNLIKELY(expr)  (__builtin_expect(static_cast<bool>(expr), 0))\n                                                                         ^~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:330:7: note: in expansion of macro \u2018C10_UNLIKELY_OR_CONST\u2019\n           if (C10_UNLIKELY_OR_CONST(!(cond))) {                               \\\n               ^~~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:318:3: note: in expansion of macro \u2018TORCH_CHECK_WITH_MSG\u2019\n           TORCH_CHECK_WITH_MSG(error_t, cond, \"\", __VA_ARGS__)\n           ^~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:341:32: note: in expansion of macro \u2018TORCH_CHECK_WITH\u2019\n         #define TORCH_CHECK(cond, ...) TORCH_CHECK_WITH(Error, cond, __VA_ARGS__)\n                                        ^~~~~~~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:23: note: in expansion of macro \u2018TORCH_CHECK\u2019\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                               ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:119:24: note: in expansion of macro \u2018CHECK_CUDA\u2019\n         #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)\n                                ^~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:244:3: note: in expansion of macro \u2018CHECK_INPUT\u2019\n           CHECK_INPUT(invvar);\n           ^~~~~~~~~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/DeviceType.h:8:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Device.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Allocator.h:6,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:42: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                                                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/macros/Macros.h:146:65: note: in definition of macro \u2018C10_UNLIKELY\u2019\n         #define C10_UNLIKELY(expr)  (__builtin_expect(static_cast<bool>(expr), 0))\n                                                                         ^~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:330:7: note: in expansion of macro \u2018C10_UNLIKELY_OR_CONST\u2019\n           if (C10_UNLIKELY_OR_CONST(!(cond))) {                               \\\n               ^~~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:318:3: note: in expansion of macro \u2018TORCH_CHECK_WITH_MSG\u2019\n           TORCH_CHECK_WITH_MSG(error_t, cond, \"\", __VA_ARGS__)\n           ^~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:341:32: note: in expansion of macro \u2018TORCH_CHECK_WITH\u2019\n         #define TORCH_CHECK(cond, ...) TORCH_CHECK_WITH(Error, cond, __VA_ARGS__)\n                                        ^~~~~~~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:23: note: in expansion of macro \u2018TORCH_CHECK\u2019\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                               ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:119:24: note: in expansion of macro \u2018CHECK_CUDA\u2019\n         #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)\n                                ^~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:245:3: note: in expansion of macro \u2018CHECK_INPUT\u2019\n           CHECK_INPUT(input);\n           ^~~~~~~~~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/DeviceType.h:8:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Device.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Allocator.h:6,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:42: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                                                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/macros/Macros.h:146:65: note: in definition of macro \u2018C10_UNLIKELY\u2019\n         #define C10_UNLIKELY(expr)  (__builtin_expect(static_cast<bool>(expr), 0))\n                                                                         ^~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:330:7: note: in expansion of macro \u2018C10_UNLIKELY_OR_CONST\u2019\n           if (C10_UNLIKELY_OR_CONST(!(cond))) {                               \\\n               ^~~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:318:3: note: in expansion of macro \u2018TORCH_CHECK_WITH_MSG\u2019\n           TORCH_CHECK_WITH_MSG(error_t, cond, \"\", __VA_ARGS__)\n           ^~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:341:32: note: in expansion of macro \u2018TORCH_CHECK_WITH\u2019\n         #define TORCH_CHECK(cond, ...) TORCH_CHECK_WITH(Error, cond, __VA_ARGS__)\n                                        ^~~~~~~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:23: note: in expansion of macro \u2018TORCH_CHECK\u2019\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                               ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:119:24: note: in expansion of macro \u2018CHECK_CUDA\u2019\n         #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)\n                                ^~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:246:3: note: in expansion of macro \u2018CHECK_INPUT\u2019\n           CHECK_INPUT(gamma);\n           ^~~~~~~~~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/DeviceType.h:8:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Device.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/c10/core/Allocator.h:6,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:42: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                                                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/macros/Macros.h:146:65: note: in definition of macro \u2018C10_UNLIKELY\u2019\n         #define C10_UNLIKELY(expr)  (__builtin_expect(static_cast<bool>(expr), 0))\n                                                                         ^~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:330:7: note: in expansion of macro \u2018C10_UNLIKELY_OR_CONST\u2019\n           if (C10_UNLIKELY_OR_CONST(!(cond))) {                               \\\n               ^~~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:318:3: note: in expansion of macro \u2018TORCH_CHECK_WITH_MSG\u2019\n           TORCH_CHECK_WITH_MSG(error_t, cond, \"\", __VA_ARGS__)\n           ^~~~~~~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/c10/util/Exception.h:341:32: note: in expansion of macro \u2018TORCH_CHECK_WITH\u2019\n         #define TORCH_CHECK(cond, ...) TORCH_CHECK_WITH(Error, cond, __VA_ARGS__)\n                                        ^~~~~~~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:117:23: note: in expansion of macro \u2018TORCH_CHECK\u2019\n         #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n                               ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:119:24: note: in expansion of macro \u2018CHECK_CUDA\u2019\n         #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)\n                                ^~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:247:3: note: in expansion of macro \u2018CHECK_INPUT\u2019\n           CHECK_INPUT(beta);\n           ^~~~~~~~~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/layer_norm_cuda.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        x86_64-linux-gnu-g++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/layer_norm_cuda.o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/layer_norm_cuda_kernel.o -L/usr/local/lib/python3.7/dist-packages/torch/lib -L/usr/local/cuda/lib64 -lc10 -ltorch -ltorch_cpu -ltorch_python -lcudart -lc10_cuda -ltorch_cuda -o build/lib.linux-x86_64-3.7/fused_layer_norm_cuda.cpython-37m-x86_64-linux-gnu.so\n        building 'mlp_cuda' extension\n        Emitting ninja build file /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/build.ninja...\n        Compiling objects...\n        Allowing ninja to set a default number of workers... (overridable by setting the environment variable MAX_JOBS=N)\n        [1/2] c++ -MMD -MF /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/mlp.o.d -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/mlp.o -O3 -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=mlp_cuda -D_GLIBCXX_USE_CXX11_ABI=0 -std=c++14\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Parallel.h:149:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/utils.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/nn/cloneable.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/nn.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:7,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ParallelOpenMP.h:84:0: warning: ignoring #pragma omp parallel [-Wunknown-pragmas]\n         #pragma omp parallel for if ((end - begin) >= grain_size)\n    \n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp: In function \u2018std::vector<at::Tensor> mlp_forward(int, int, std::vector<at::Tensor>)\u2019:\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:57:21: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]\n           for (int i = 0; i < num_layers; i++) {\n                           ~~^~~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:64:77: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           auto out = at::empty({batch_size, output_features.back()}, inputs[0].type());\n                                                                                     ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:65:67: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           auto reserved_space = at::empty({reserved_size}, inputs[0].type());\n                                                                           ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:65:68: warning: narrowing conversion of \u2018reserved_size\u2019 from \u2018long unsigned int\u2019 to \u2018long int\u2019 inside { } [-Wnarrowing]\n           auto reserved_space = at::empty({reserved_size}, inputs[0].type());\n                                                                            ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:65:68: warning: narrowing conversion of \u2018reserved_size\u2019 from \u2018long unsigned int\u2019 to \u2018long int\u2019 inside { } [-Wnarrowing]\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:67:59: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           auto lt_workspace = at::empty({1 << 22}, inputs[0].type());\n                                                                   ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:9:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:69:54: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_forward\", [&] {\n                                                              ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:150:28: note: in definition of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n             const auto& the_type = TYPE;                                            \\\n                                    ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:9:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:152:56: warning: \u2018c10::ScalarType detail::scalar_type(const at::DeprecatedTypeProperties&)\u2019 is deprecated: passing at::DeprecatedTypeProperties to an AT_DISPATCH macro is deprecated, pass an at::ScalarType instead [-Wdeprecated-declarations]\n             at::ScalarType _st = ::detail::scalar_type(the_type);                   \\\n                                                                ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:69:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_forward\", [&] {\n           ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:66:23: note: declared here\n         inline at::ScalarType scalar_type(const at::DeprecatedTypeProperties& t) {\n                               ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:72:23: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]\n             for (int i = 0; i < num_layers; i++) {\n                             ~~^~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:69:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_forward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:78:10: warning: unused variable \u2018result\u2019 [-Wunused-variable]\n             auto result = mlp_fp<scalar_t>(\n                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:69:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_forward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:72:23: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]\n             for (int i = 0; i < num_layers; i++) {\n                             ~~^~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:69:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_forward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:78:10: warning: unused variable \u2018result\u2019 [-Wunused-variable]\n             auto result = mlp_fp<scalar_t>(\n                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:69:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_forward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:72:23: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]\n             for (int i = 0; i < num_layers; i++) {\n                             ~~^~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:69:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_forward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:78:10: warning: unused variable \u2018result\u2019 [-Wunused-variable]\n             auto result = mlp_fp<scalar_t>(\n                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:69:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_forward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp: In function \u2018std::vector<at::Tensor> mlp_backward(int, int, at::Tensor, std::vector<at::Tensor>, std::vector<at::Tensor>)\u2019:\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:115:21: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]\n           for (int i = 0; i < num_layers; i++) {\n                           ~~^~~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:120:21: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]\n           for (int i = 0; i < inputs.size(); i++) {\n                           ~~^~~~~~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:121:67: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n             outputs.push_back(at::empty(inputs[i].sizes(), inputs[i].type()));  // clone for testing now\n                                                                           ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:9:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:124:54: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_backward\", [&] {\n                                                              ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:150:28: note: in definition of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n             const auto& the_type = TYPE;                                            \\\n                                    ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:9:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:152:56: warning: \u2018c10::ScalarType detail::scalar_type(const at::DeprecatedTypeProperties&)\u2019 is deprecated: passing at::DeprecatedTypeProperties to an AT_DISPATCH macro is deprecated, pass an at::ScalarType instead [-Wdeprecated-declarations]\n             at::ScalarType _st = ::detail::scalar_type(the_type);                   \\\n                                                                ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:124:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_backward\", [&] {\n           ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:66:23: note: declared here\n         inline at::ScalarType scalar_type(const at::DeprecatedTypeProperties& t) {\n                               ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:126:23: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]\n             for (int i = 0; i < num_layers; i++) {\n                             ~~^~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:124:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:130:23: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]\n             for (int i = 0; i < inputs.size(); i++) {\n                             ~~^~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:124:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:138:80: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n             auto work_space = at::empty({work_size / sizeof(scalar_t)}, inputs[0].type());\n                                                                                        ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:124:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_backward\", [&] {\n           ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:9:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:138:44: warning: narrowing conversion of \u2018(work_size / sizeof (scalar_t))\u2019 from \u2018long unsigned int\u2019 to \u2018long int\u2019 inside { } [-Wnarrowing]\n             auto work_space = at::empty({work_size / sizeof(scalar_t)}, inputs[0].type());\n                                          ~~~~~~~~~~^~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:124:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:138:44: warning: narrowing conversion of \u2018(work_size / sizeof (scalar_t))\u2019 from \u2018long unsigned int\u2019 to \u2018long int\u2019 inside { } [-Wnarrowing]\n             auto work_space = at::empty({work_size / sizeof(scalar_t)}, inputs[0].type());\n                                          ~~~~~~~~~~^~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:124:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:140:10: warning: unused variable \u2018result\u2019 [-Wunused-variable]\n             auto result = mlp_bp<scalar_t>(\n                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:124:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:126:23: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]\n             for (int i = 0; i < num_layers; i++) {\n                             ~~^~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:124:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:130:23: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]\n             for (int i = 0; i < inputs.size(); i++) {\n                             ~~^~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:124:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:138:80: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n             auto work_space = at::empty({work_size / sizeof(scalar_t)}, inputs[0].type());\n                                                                                        ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:124:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_backward\", [&] {\n           ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:9:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:138:44: warning: narrowing conversion of \u2018(work_size / sizeof (scalar_t))\u2019 from \u2018long unsigned int\u2019 to \u2018long int\u2019 inside { } [-Wnarrowing]\n             auto work_space = at::empty({work_size / sizeof(scalar_t)}, inputs[0].type());\n                                          ~~~~~~~~~~^~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:124:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:138:44: warning: narrowing conversion of \u2018(work_size / sizeof (scalar_t))\u2019 from \u2018long unsigned int\u2019 to \u2018long int\u2019 inside { } [-Wnarrowing]\n             auto work_space = at::empty({work_size / sizeof(scalar_t)}, inputs[0].type());\n                                          ~~~~~~~~~~^~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:124:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:140:10: warning: unused variable \u2018result\u2019 [-Wunused-variable]\n             auto result = mlp_bp<scalar_t>(\n                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:124:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:126:23: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]\n             for (int i = 0; i < num_layers; i++) {\n                             ~~^~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:124:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:130:23: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]\n             for (int i = 0; i < inputs.size(); i++) {\n                             ~~^~~~~~~~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:124:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:138:80: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n             auto work_space = at::empty({work_size / sizeof(scalar_t)}, inputs[0].type());\n                                                                                        ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:124:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_backward\", [&] {\n           ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:9:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:138:44: warning: narrowing conversion of \u2018(work_size / sizeof (scalar_t))\u2019 from \u2018long unsigned int\u2019 to \u2018long int\u2019 inside { } [-Wnarrowing]\n             auto work_space = at::empty({work_size / sizeof(scalar_t)}, inputs[0].type());\n                                          ~~~~~~~~~~^~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:124:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:138:44: warning: narrowing conversion of \u2018(work_size / sizeof (scalar_t))\u2019 from \u2018long unsigned int\u2019 to \u2018long int\u2019 inside { } [-Wnarrowing]\n             auto work_space = at::empty({work_size / sizeof(scalar_t)}, inputs[0].type());\n                                          ~~~~~~~~~~^~~~~~~~~\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:124:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:140:10: warning: unused variable \u2018result\u2019 [-Wunused-variable]\n             auto result = mlp_bp<scalar_t>(\n                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/mlp.cpp:124:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(inputs[0].type(), \"mlp_backward\", [&] {\n           ^\n        [2/2] /usr/local/cuda/bin/nvcc -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/mlp_cuda.cu -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/mlp_cuda.o -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr --compiler-options ''\"'\"'-fPIC'\"'\"'' -O3 -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=mlp_cuda -D_GLIBCXX_USE_CXX11_ABI=0 -gencode=arch=compute_37,code=sm_37 -std=c++14\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/record_function.h(18): warning: attribute \"__visibility__\" does not apply here\n    \n        /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/autograd/profiler.h(97): warning: attribute \"__visibility__\" does not apply here\n    \n        /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/autograd/profiler.h(126): warning: attribute \"__visibility__\" does not apply here\n    \n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/record_function.h(18): warning: attribute \"__visibility__\" does not apply here\n    \n        /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/autograd/profiler.h(97): warning: attribute \"__visibility__\" does not apply here\n    \n        /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/autograd/profiler.h(126): warning: attribute \"__visibility__\" does not apply here\n    \n        x86_64-linux-gnu-g++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/mlp.o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/mlp_cuda.o -L/usr/local/lib/python3.7/dist-packages/torch/lib -L/usr/local/cuda/lib64 -lc10 -ltorch -ltorch_cpu -ltorch_python -lcudart -lc10_cuda -ltorch_cuda -o build/lib.linux-x86_64-3.7/mlp_cuda.cpython-37m-x86_64-linux-gnu.so\n        building 'fused_dense_cuda' extension\n        Emitting ninja build file /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/build.ninja...\n        Compiling objects...\n        Allowing ninja to set a default number of workers... (overridable by setting the environment variable MAX_JOBS=N)\n        [1/2] c++ -MMD -MF /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/fused_dense.o.d -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/fused_dense.o -O3 -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=fused_dense_cuda -D_GLIBCXX_USE_CXX11_ABI=0 -std=c++14\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Parallel.h:149:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/utils.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/nn/cloneable.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/nn.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:7,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ParallelOpenMP.h:84:0: warning: ignoring #pragma omp parallel [-Wunknown-pragmas]\n         #pragma omp parallel for if ((end - begin) >= grain_size)\n    \n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp: In function \u2018at::Tensor linear_bias_forward(at::Tensor, at::Tensor, at::Tensor)\u2019:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:30:63: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           auto out = at::empty({batch_size, out_features}, input.type());\n                                                                       ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:33:55: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           auto lt_workspace = at::empty({1 << 22}, input.type());\n                                                               ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:9:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:35:50: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_bias_forward\", [&] {\n                                                          ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:150:28: note: in definition of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n             const auto& the_type = TYPE;                                            \\\n                                    ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:9:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:152:56: warning: \u2018c10::ScalarType detail::scalar_type(const at::DeprecatedTypeProperties&)\u2019 is deprecated: passing at::DeprecatedTypeProperties to an AT_DISPATCH macro is deprecated, pass an at::ScalarType instead [-Wdeprecated-declarations]\n             at::ScalarType _st = ::detail::scalar_type(the_type);                   \\\n                                                                ^\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:35:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_bias_forward\", [&] {\n           ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:66:23: note: declared here\n         inline at::ScalarType scalar_type(const at::DeprecatedTypeProperties& t) {\n                               ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:37:15: warning: unused variable \u2018b_ptr\u2019 [-Wunused-variable]\n             scalar_t* b_ptr = bias.data_ptr<scalar_t>();\n                       ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:35:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_bias_forward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:38:10: warning: unused variable \u2018result\u2019 [-Wunused-variable]\n             auto result = linear_bias_forward_cuda<scalar_t>(\n                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:35:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_bias_forward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:37:15: warning: unused variable \u2018b_ptr\u2019 [-Wunused-variable]\n             scalar_t* b_ptr = bias.data_ptr<scalar_t>();\n                       ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:35:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_bias_forward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:38:10: warning: unused variable \u2018result\u2019 [-Wunused-variable]\n             auto result = linear_bias_forward_cuda<scalar_t>(\n                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:35:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_bias_forward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:37:15: warning: unused variable \u2018b_ptr\u2019 [-Wunused-variable]\n             scalar_t* b_ptr = bias.data_ptr<scalar_t>();\n                       ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:35:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_bias_forward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:38:10: warning: unused variable \u2018result\u2019 [-Wunused-variable]\n             auto result = linear_bias_forward_cuda<scalar_t>(\n                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:35:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_bias_forward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp: In function \u2018std::vector<at::Tensor> linear_bias_backward(at::Tensor, at::Tensor, at::Tensor)\u2019:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:64:69: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           auto d_weight = at::empty({out_features, in_features}, input.type());\n                                                                             ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:68:54: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           auto d_bias = at::empty({out_features}, input.type());\n                                                              ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:70:66: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           auto d_input = at::empty({batch_size, in_features}, input.type());\n                                                                          ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:73:55: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           auto lt_workspace = at::empty({1 << 22}, input.type());\n                                                               ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:9:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:75:50: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_bias_backward\", [&] {\n                                                          ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:150:28: note: in definition of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n             const auto& the_type = TYPE;                                            \\\n                                    ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:9:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:152:56: warning: \u2018c10::ScalarType detail::scalar_type(const at::DeprecatedTypeProperties&)\u2019 is deprecated: passing at::DeprecatedTypeProperties to an AT_DISPATCH macro is deprecated, pass an at::ScalarType instead [-Wdeprecated-declarations]\n             at::ScalarType _st = ::detail::scalar_type(the_type);                   \\\n                                                                ^\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:75:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_bias_backward\", [&] {\n           ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:66:23: note: declared here\n         inline at::ScalarType scalar_type(const at::DeprecatedTypeProperties& t) {\n                               ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:77:15: warning: unused variable \u2018d_b_ptr\u2019 [-Wunused-variable]\n             scalar_t* d_b_ptr = d_bias.data_ptr<scalar_t>();\n                       ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:75:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_bias_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:78:10: warning: unused variable \u2018result\u2019 [-Wunused-variable]\n             auto result = linear_bias_backward_cuda<scalar_t>(\n                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:75:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_bias_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:77:15: warning: unused variable \u2018d_b_ptr\u2019 [-Wunused-variable]\n             scalar_t* d_b_ptr = d_bias.data_ptr<scalar_t>();\n                       ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:75:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_bias_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:78:10: warning: unused variable \u2018result\u2019 [-Wunused-variable]\n             auto result = linear_bias_backward_cuda<scalar_t>(\n                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:75:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_bias_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:77:15: warning: unused variable \u2018d_b_ptr\u2019 [-Wunused-variable]\n             scalar_t* d_b_ptr = d_bias.data_ptr<scalar_t>();\n                       ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:75:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_bias_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:78:10: warning: unused variable \u2018result\u2019 [-Wunused-variable]\n             auto result = linear_bias_backward_cuda<scalar_t>(\n                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:75:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_bias_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp: In function \u2018std::vector<at::Tensor> linear_gelu_linear_forward(at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor)\u2019:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:106:70: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           auto output1 = at::empty({batch_size, hidden_features}, input.type());\n                                                                              ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:107:70: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           auto gelu_in = at::empty({batch_size, hidden_features}, input.type());\n                                                                              ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:108:67: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           auto output2 = at::empty({batch_size, out_features}, input.type());\n                                                                           ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:111:55: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           auto lt_workspace = at::empty({1 << 22}, input.type());\n                                                               ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:9:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:113:50: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_gelu_linear_forward\", [&] {\n                                                          ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:150:28: note: in definition of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n             const auto& the_type = TYPE;                                            \\\n                                    ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:9:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:152:56: warning: \u2018c10::ScalarType detail::scalar_type(const at::DeprecatedTypeProperties&)\u2019 is deprecated: passing at::DeprecatedTypeProperties to an AT_DISPATCH macro is deprecated, pass an at::ScalarType instead [-Wdeprecated-declarations]\n             at::ScalarType _st = ::detail::scalar_type(the_type);                   \\\n                                                                ^\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:113:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_gelu_linear_forward\", [&] {\n           ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:66:23: note: declared here\n         inline at::ScalarType scalar_type(const at::DeprecatedTypeProperties& t) {\n                               ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:118:10: warning: unused variable \u2018result\u2019 [-Wunused-variable]\n             auto result = linear_gelu_linear_forward_cuda<scalar_t>(\n                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:113:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_gelu_linear_forward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:118:10: warning: unused variable \u2018result\u2019 [-Wunused-variable]\n             auto result = linear_gelu_linear_forward_cuda<scalar_t>(\n                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:113:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_gelu_linear_forward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:118:10: warning: unused variable \u2018result\u2019 [-Wunused-variable]\n             auto result = linear_gelu_linear_forward_cuda<scalar_t>(\n                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:113:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_gelu_linear_forward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp: In function \u2018std::vector<at::Tensor> linear_gelu_linear_backward(at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor)\u2019:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:149:73: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           auto d_weight1 = at::empty({hidden_features, in_features}, input.type());\n                                                                                 ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:150:74: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           auto d_weight2 = at::empty({out_features, hidden_features}, input.type());\n                                                                                  ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:151:58: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           auto d_bias1 = at::empty({hidden_features}, input.type());\n                                                                  ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:152:55: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           auto d_bias2 = at::empty({out_features}, input.type());\n                                                               ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:153:66: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           auto d_input = at::empty({batch_size, in_features}, input.type());\n                                                                          ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:154:72: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           auto d_output1 = at::empty({batch_size, hidden_features}, input.type());\n                                                                                ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:157:55: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           auto lt_workspace = at::empty({1 << 22}, input.type());\n                                                               ^\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:9:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:159:50: warning: \u2018at::DeprecatedTypeProperties& at::Tensor::type() const\u2019 is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [-Wdeprecated-declarations]\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_bias_backward\", [&] {\n                                                          ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:150:28: note: in definition of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n             const auto& the_type = TYPE;                                            \\\n                                    ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Tensor.h:3:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Context.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/core/TensorBody.h:268:30: note: declared here\n           DeprecatedTypeProperties & type() const {\n                                      ^~~~\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ATen.h:9:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/types.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/data.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:4,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:1:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:152:56: warning: \u2018c10::ScalarType detail::scalar_type(const at::DeprecatedTypeProperties&)\u2019 is deprecated: passing at::DeprecatedTypeProperties to an AT_DISPATCH macro is deprecated, pass an at::ScalarType instead [-Wdeprecated-declarations]\n             at::ScalarType _st = ::detail::scalar_type(the_type);                   \\\n                                                                ^\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:159:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_bias_backward\", [&] {\n           ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:66:23: note: declared here\n         inline at::ScalarType scalar_type(const at::DeprecatedTypeProperties& t) {\n                               ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:162:10: warning: unused variable \u2018result\u2019 [-Wunused-variable]\n             auto result = linear_gelu_linear_backward_cuda<scalar_t>(\n                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:159:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_bias_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:162:10: warning: unused variable \u2018result\u2019 [-Wunused-variable]\n             auto result = linear_gelu_linear_backward_cuda<scalar_t>(\n                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:159:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_bias_backward\", [&] {\n           ^\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp: In lambda function:\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:162:10: warning: unused variable \u2018result\u2019 [-Wunused-variable]\n             auto result = linear_gelu_linear_backward_cuda<scalar_t>(\n                  ^\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Dispatch.h:13:12: note: in definition of macro \u2018AT_PRIVATE_CASE_TYPE\u2019\n             return __VA_ARGS__();                          \\\n                    ^~~~~~~~~~~\n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense.cpp:159:3: note: in expansion of macro \u2018AT_DISPATCH_FLOATING_TYPES_AND_HALF\u2019\n           AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), \"linear_bias_backward\", [&] {\n           ^\n        [2/2] /usr/local/cuda/bin/nvcc -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/fused_dense_cuda.cu -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/fused_dense_cuda.o -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr --compiler-options ''\"'\"'-fPIC'\"'\"'' -O3 -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=fused_dense_cuda -D_GLIBCXX_USE_CXX11_ABI=0 -gencode=arch=compute_37,code=sm_37 -std=c++14\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/record_function.h(18): warning: attribute \"__visibility__\" does not apply here\n    \n        /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/autograd/profiler.h(97): warning: attribute \"__visibility__\" does not apply here\n    \n        /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/autograd/profiler.h(126): warning: attribute \"__visibility__\" does not apply here\n    \n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense_cuda.cu(1148): warning: variable \"beta_zero\" was declared but never referenced\n    \n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense_cuda.cu(1272): warning: variable \"alpha\" was declared but never referenced\n    \n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense_cuda.cu(1273): warning: variable \"beta_zero\" was declared but never referenced\n    \n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense_cuda.cu(1274): warning: variable \"status\" was declared but never referenced\n    \n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense_cuda.cu(1329): warning: variable \"alpha\" was declared but never referenced\n    \n        /tmp/pip-req-build-41vu3jcb/csrc/fused_dense_cuda.cu(1330): warning: variable \"beta_zero\" was declared but never referenced\n    \n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/record_function.h(18): warning: attribute \"__visibility__\" does not apply here\n    \n        /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/autograd/profiler.h(97): warning: attribute \"__visibility__\" does not apply here\n    \n        /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/autograd/profiler.h(126): warning: attribute \"__visibility__\" does not apply here\n    \n        x86_64-linux-gnu-g++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/fused_dense.o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/fused_dense_cuda.o -L/usr/local/lib/python3.7/dist-packages/torch/lib -L/usr/local/cuda/lib64 -lc10 -ltorch -ltorch_cpu -ltorch_python -lcudart -lc10_cuda -ltorch_cuda -o build/lib.linux-x86_64-3.7/fused_dense_cuda.cpython-37m-x86_64-linux-gnu.so\n        building 'scaled_upper_triang_masked_softmax_cuda' extension\n        creating /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/megatron\n        Emitting ninja build file /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/build.ninja...\n        Compiling objects...\n        Allowing ninja to set a default number of workers... (overridable by setting the environment variable MAX_JOBS=N)\n        [1/2] c++ -MMD -MF /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/megatron/scaled_upper_triang_masked_softmax.o.d -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/tmp/pip-req-build-41vu3jcb/csrc -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/megatron/scaled_upper_triang_masked_softmax.cpp -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/megatron/scaled_upper_triang_masked_softmax.o -O3 -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=scaled_upper_triang_masked_softmax_cuda -D_GLIBCXX_USE_CXX11_ABI=0 -std=c++14\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Parallel.h:149:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/utils.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/nn/cloneable.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/nn.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:7,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/megatron/scaled_upper_triang_masked_softmax.cpp:18:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ParallelOpenMP.h:84:0: warning: ignoring #pragma omp parallel [-Wunknown-pragmas]\n         #pragma omp parallel for if ((end - begin) >= grain_size)\n    \n        [2/2] /usr/local/cuda/bin/nvcc -I/tmp/pip-req-build-41vu3jcb/csrc -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/megatron/scaled_upper_triang_masked_softmax_cuda.cu -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/megatron/scaled_upper_triang_masked_softmax_cuda.o -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr --compiler-options ''\"'\"'-fPIC'\"'\"'' -O3 -U__CUDA_NO_HALF_OPERATORS__ -U__CUDA_NO_HALF_CONVERSIONS__ --expt-relaxed-constexpr --expt-extended-lambda -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=scaled_upper_triang_masked_softmax_cuda -D_GLIBCXX_USE_CXX11_ABI=0 -gencode=arch=compute_37,code=sm_37 -std=c++14\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/record_function.h(18): warning: attribute \"__visibility__\" does not apply here\n    \n        /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/autograd/profiler.h(97): warning: attribute \"__visibility__\" does not apply here\n    \n        /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/autograd/profiler.h(126): warning: attribute \"__visibility__\" does not apply here\n    \n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/record_function.h(18): warning: attribute \"__visibility__\" does not apply here\n    \n        /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/autograd/profiler.h(97): warning: attribute \"__visibility__\" does not apply here\n    \n        /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/autograd/profiler.h(126): warning: attribute \"__visibility__\" does not apply here\n    \n        x86_64-linux-gnu-g++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/megatron/scaled_upper_triang_masked_softmax.o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/megatron/scaled_upper_triang_masked_softmax_cuda.o -L/usr/local/lib/python3.7/dist-packages/torch/lib -L/usr/local/cuda/lib64 -lc10 -ltorch -ltorch_cpu -ltorch_python -lcudart -lc10_cuda -ltorch_cuda -o build/lib.linux-x86_64-3.7/scaled_upper_triang_masked_softmax_cuda.cpython-37m-x86_64-linux-gnu.so\n        building 'scaled_masked_softmax_cuda' extension\n        Emitting ninja build file /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/build.ninja...\n        Compiling objects...\n        Allowing ninja to set a default number of workers... (overridable by setting the environment variable MAX_JOBS=N)\n        [1/2] c++ -MMD -MF /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/megatron/scaled_masked_softmax.o.d -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/tmp/pip-req-build-41vu3jcb/csrc -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/megatron/scaled_masked_softmax.cpp -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/megatron/scaled_masked_softmax.o -O3 -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=scaled_masked_softmax_cuda -D_GLIBCXX_USE_CXX11_ABI=0 -std=c++14\n        In file included from /usr/local/lib/python3.7/dist-packages/torch/include/ATen/Parallel.h:149:0,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/utils.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/nn/cloneable.h:5,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/nn.h:3,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include/torch/all.h:7,\n                         from /usr/local/lib/python3.7/dist-packages/torch/include/torch/extension.h:4,\n                         from /tmp/pip-req-build-41vu3jcb/csrc/megatron/scaled_masked_softmax.cpp:18:\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/ParallelOpenMP.h:84:0: warning: ignoring #pragma omp parallel [-Wunknown-pragmas]\n         #pragma omp parallel for if ((end - begin) >= grain_size)\n    \n        [2/2] /usr/local/cuda/bin/nvcc -I/tmp/pip-req-build-41vu3jcb/csrc -I/usr/local/lib/python3.7/dist-packages/torch/include -I/usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/api/include -I/usr/local/lib/python3.7/dist-packages/torch/include/TH -I/usr/local/lib/python3.7/dist-packages/torch/include/THC -I/usr/local/cuda/include -I/usr/include/python3.7m -c -c /tmp/pip-req-build-41vu3jcb/csrc/megatron/scaled_masked_softmax_cuda.cu -o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/megatron/scaled_masked_softmax_cuda.o -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr --compiler-options ''\"'\"'-fPIC'\"'\"'' -O3 -U__CUDA_NO_HALF_OPERATORS__ -U__CUDA_NO_HALF_CONVERSIONS__ --expt-relaxed-constexpr --expt-extended-lambda -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=scaled_masked_softmax_cuda -D_GLIBCXX_USE_CXX11_ABI=0 -gencode=arch=compute_37,code=sm_37 -std=c++14\n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/record_function.h(18): warning: attribute \"__visibility__\" does not apply here\n    \n        /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/autograd/profiler.h(97): warning: attribute \"__visibility__\" does not apply here\n    \n        /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/autograd/profiler.h(126): warning: attribute \"__visibility__\" does not apply here\n    \n        /usr/local/lib/python3.7/dist-packages/torch/include/ATen/record_function.h(18): warning: attribute \"__visibility__\" does not apply here\n    \n        /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/autograd/profiler.h(97): warning: attribute \"__visibility__\" does not apply here\n    \n        /usr/local/lib/python3.7/dist-packages/torch/include/torch/csrc/autograd/profiler.h(126): warning: attribute \"__visibility__\" does not apply here\n    \n        x86_64-linux-gnu-g++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fdebug-prefix-map=/build/python3.7-Y7dWVB/python3.7-3.7.12=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/megatron/scaled_masked_softmax.o /tmp/pip-req-build-41vu3jcb/build/temp.linux-x86_64-3.7/csrc/megatron/scaled_masked_softmax_cuda.o -L/usr/local/lib/python3.7/dist-packages/torch/lib -L/usr/local/cuda/lib64 -lc10 -ltorch -ltorch_cpu -ltorch_python -lcudart -lc10_cuda -ltorch_cuda -o build/lib.linux-x86_64-3.7/scaled_masked_softmax_cuda.cpython-37m-x86_64-linux-gnu.so\n        running install_lib\n        copying build/lib.linux-x86_64-3.7/fused_layer_norm_cuda.cpython-37m-x86_64-linux-gnu.so -> /usr/local/lib/python3.7/dist-packages\n        copying build/lib.linux-x86_64-3.7/scaled_masked_softmax_cuda.cpython-37m-x86_64-linux-gnu.so -> /usr/local/lib/python3.7/dist-packages\n        copying build/lib.linux-x86_64-3.7/mlp_cuda.cpython-37m-x86_64-linux-gnu.so -> /usr/local/lib/python3.7/dist-packages\n        creating /usr/local/lib/python3.7/dist-packages/apex\n        copying build/lib.linux-x86_64-3.7/apex/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex\n        creating /usr/local/lib/python3.7/dist-packages/apex/multi_tensor_apply\n        copying build/lib.linux-x86_64-3.7/apex/multi_tensor_apply/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/multi_tensor_apply\n        copying build/lib.linux-x86_64-3.7/apex/multi_tensor_apply/multi_tensor_apply.py -> /usr/local/lib/python3.7/dist-packages/apex/multi_tensor_apply\n        creating /usr/local/lib/python3.7/dist-packages/apex/amp\n        copying build/lib.linux-x86_64-3.7/apex/amp/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/amp\n        copying build/lib.linux-x86_64-3.7/apex/amp/__version__.py -> /usr/local/lib/python3.7/dist-packages/apex/amp\n        copying build/lib.linux-x86_64-3.7/apex/amp/compat.py -> /usr/local/lib/python3.7/dist-packages/apex/amp\n        copying build/lib.linux-x86_64-3.7/apex/amp/_initialize.py -> /usr/local/lib/python3.7/dist-packages/apex/amp\n        creating /usr/local/lib/python3.7/dist-packages/apex/amp/lists\n        copying build/lib.linux-x86_64-3.7/apex/amp/lists/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/amp/lists\n        copying build/lib.linux-x86_64-3.7/apex/amp/lists/torch_overrides.py -> /usr/local/lib/python3.7/dist-packages/apex/amp/lists\n        copying build/lib.linux-x86_64-3.7/apex/amp/lists/functional_overrides.py -> /usr/local/lib/python3.7/dist-packages/apex/amp/lists\n        copying build/lib.linux-x86_64-3.7/apex/amp/lists/tensor_overrides.py -> /usr/local/lib/python3.7/dist-packages/apex/amp/lists\n        copying build/lib.linux-x86_64-3.7/apex/amp/handle.py -> /usr/local/lib/python3.7/dist-packages/apex/amp\n        copying build/lib.linux-x86_64-3.7/apex/amp/wrap.py -> /usr/local/lib/python3.7/dist-packages/apex/amp\n        copying build/lib.linux-x86_64-3.7/apex/amp/rnn_compat.py -> /usr/local/lib/python3.7/dist-packages/apex/amp\n        copying build/lib.linux-x86_64-3.7/apex/amp/_process_optimizer.py -> /usr/local/lib/python3.7/dist-packages/apex/amp\n        copying build/lib.linux-x86_64-3.7/apex/amp/frontend.py -> /usr/local/lib/python3.7/dist-packages/apex/amp\n        copying build/lib.linux-x86_64-3.7/apex/amp/opt.py -> /usr/local/lib/python3.7/dist-packages/apex/amp\n        copying build/lib.linux-x86_64-3.7/apex/amp/scaler.py -> /usr/local/lib/python3.7/dist-packages/apex/amp\n        copying build/lib.linux-x86_64-3.7/apex/amp/_amp_state.py -> /usr/local/lib/python3.7/dist-packages/apex/amp\n        copying build/lib.linux-x86_64-3.7/apex/amp/utils.py -> /usr/local/lib/python3.7/dist-packages/apex/amp\n        copying build/lib.linux-x86_64-3.7/apex/amp/amp.py -> /usr/local/lib/python3.7/dist-packages/apex/amp\n        creating /usr/local/lib/python3.7/dist-packages/apex/contrib\n        copying build/lib.linux-x86_64-3.7/apex/contrib/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib\n        creating /usr/local/lib/python3.7/dist-packages/apex/contrib/groupbn\n        copying build/lib.linux-x86_64-3.7/apex/contrib/groupbn/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/groupbn\n        copying build/lib.linux-x86_64-3.7/apex/contrib/groupbn/batch_norm.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/groupbn\n        creating /usr/local/lib/python3.7/dist-packages/apex/contrib/xentropy\n        copying build/lib.linux-x86_64-3.7/apex/contrib/xentropy/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/xentropy\n        copying build/lib.linux-x86_64-3.7/apex/contrib/xentropy/softmax_xentropy.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/xentropy\n        creating /usr/local/lib/python3.7/dist-packages/apex/contrib/layer_norm\n        copying build/lib.linux-x86_64-3.7/apex/contrib/layer_norm/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/layer_norm\n        copying build/lib.linux-x86_64-3.7/apex/contrib/layer_norm/layer_norm.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/layer_norm\n        creating /usr/local/lib/python3.7/dist-packages/apex/contrib/bottleneck\n        copying build/lib.linux-x86_64-3.7/apex/contrib/bottleneck/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/bottleneck\n        copying build/lib.linux-x86_64-3.7/apex/contrib/bottleneck/bottleneck.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/bottleneck\n        copying build/lib.linux-x86_64-3.7/apex/contrib/bottleneck/bottleneck_module_test.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/bottleneck\n        copying build/lib.linux-x86_64-3.7/apex/contrib/bottleneck/test.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/bottleneck\n        creating /usr/local/lib/python3.7/dist-packages/apex/contrib/sparsity\n        copying build/lib.linux-x86_64-3.7/apex/contrib/sparsity/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/sparsity\n        copying build/lib.linux-x86_64-3.7/apex/contrib/sparsity/asp.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/sparsity\n        copying build/lib.linux-x86_64-3.7/apex/contrib/sparsity/sparse_masklib.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/sparsity\n        creating /usr/local/lib/python3.7/dist-packages/apex/contrib/transducer\n        copying build/lib.linux-x86_64-3.7/apex/contrib/transducer/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/transducer\n        copying build/lib.linux-x86_64-3.7/apex/contrib/transducer/transducer.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/transducer\n        creating /usr/local/lib/python3.7/dist-packages/apex/contrib/fmha\n        copying build/lib.linux-x86_64-3.7/apex/contrib/fmha/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/fmha\n        copying build/lib.linux-x86_64-3.7/apex/contrib/fmha/fmha.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/fmha\n        creating /usr/local/lib/python3.7/dist-packages/apex/contrib/multihead_attn\n        copying build/lib.linux-x86_64-3.7/apex/contrib/multihead_attn/fast_self_multihead_attn_norm_add_func.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/multihead_attn\n        copying build/lib.linux-x86_64-3.7/apex/contrib/multihead_attn/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/multihead_attn\n        copying build/lib.linux-x86_64-3.7/apex/contrib/multihead_attn/self_multihead_attn.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/multihead_attn\n        copying build/lib.linux-x86_64-3.7/apex/contrib/multihead_attn/fast_self_multihead_attn_func.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/multihead_attn\n        copying build/lib.linux-x86_64-3.7/apex/contrib/multihead_attn/fast_encdec_multihead_attn_func.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/multihead_attn\n        copying build/lib.linux-x86_64-3.7/apex/contrib/multihead_attn/fast_encdec_multihead_attn_norm_add_func.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/multihead_attn\n        copying build/lib.linux-x86_64-3.7/apex/contrib/multihead_attn/encdec_multihead_attn.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/multihead_attn\n        copying build/lib.linux-x86_64-3.7/apex/contrib/multihead_attn/encdec_multihead_attn_func.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/multihead_attn\n        copying build/lib.linux-x86_64-3.7/apex/contrib/multihead_attn/mask_softmax_dropout_func.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/multihead_attn\n        copying build/lib.linux-x86_64-3.7/apex/contrib/multihead_attn/self_multihead_attn_func.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/multihead_attn\n        creating /usr/local/lib/python3.7/dist-packages/apex/contrib/optimizers\n        copying build/lib.linux-x86_64-3.7/apex/contrib/optimizers/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/optimizers\n        copying build/lib.linux-x86_64-3.7/apex/contrib/optimizers/distributed_fused_lamb.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/optimizers\n        copying build/lib.linux-x86_64-3.7/apex/contrib/optimizers/fp16_optimizer.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/optimizers\n        copying build/lib.linux-x86_64-3.7/apex/contrib/optimizers/fused_lamb.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/optimizers\n        copying build/lib.linux-x86_64-3.7/apex/contrib/optimizers/distributed_fused_adam_v3.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/optimizers\n        copying build/lib.linux-x86_64-3.7/apex/contrib/optimizers/fused_adam.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/optimizers\n        copying build/lib.linux-x86_64-3.7/apex/contrib/optimizers/fused_sgd.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/optimizers\n        copying build/lib.linux-x86_64-3.7/apex/contrib/optimizers/distributed_fused_adam_v2.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/optimizers\n        copying build/lib.linux-x86_64-3.7/apex/contrib/optimizers/distributed_fused_adam.py -> /usr/local/lib/python3.7/dist-packages/apex/contrib/optimizers\n        creating /usr/local/lib/python3.7/dist-packages/apex/mlp\n        copying build/lib.linux-x86_64-3.7/apex/mlp/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/mlp\n        copying build/lib.linux-x86_64-3.7/apex/mlp/mlp.py -> /usr/local/lib/python3.7/dist-packages/apex/mlp\n        creating /usr/local/lib/python3.7/dist-packages/apex/normalization\n        copying build/lib.linux-x86_64-3.7/apex/normalization/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/normalization\n        copying build/lib.linux-x86_64-3.7/apex/normalization/fused_layer_norm.py -> /usr/local/lib/python3.7/dist-packages/apex/normalization\n        copying build/lib.linux-x86_64-3.7/apex/_autocast_utils.py -> /usr/local/lib/python3.7/dist-packages/apex\n        creating /usr/local/lib/python3.7/dist-packages/apex/pyprof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof\n        creating /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/optim.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/misc.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/output.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/pooling.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/linear.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/blas.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/softmax.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/base.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/pointwise.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/index_slice_join_mutate.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/randomSample.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/dropout.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/__main__.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/activation.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/convert.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/utility.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/conv.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/normalization.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/data.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/usage.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/loss.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/prof.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/recurrentCell.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/embedding.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/prof/reduction.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof\n        creating /usr/local/lib/python3.7/dist-packages/apex/pyprof/parse\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/parse/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/parse\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/parse/nvvp.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/parse\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/parse/kernel.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/parse\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/parse/__main__.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/parse\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/parse/parse.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/parse\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/parse/db.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/parse\n        creating /usr/local/lib/python3.7/dist-packages/apex/pyprof/nvtx\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/nvtx/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/nvtx\n        copying build/lib.linux-x86_64-3.7/apex/pyprof/nvtx/nvmarker.py -> /usr/local/lib/python3.7/dist-packages/apex/pyprof/nvtx\n        creating /usr/local/lib/python3.7/dist-packages/apex/RNN\n        copying build/lib.linux-x86_64-3.7/apex/RNN/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/RNN\n        copying build/lib.linux-x86_64-3.7/apex/RNN/models.py -> /usr/local/lib/python3.7/dist-packages/apex/RNN\n        copying build/lib.linux-x86_64-3.7/apex/RNN/cells.py -> /usr/local/lib/python3.7/dist-packages/apex/RNN\n        copying build/lib.linux-x86_64-3.7/apex/RNN/RNNBackend.py -> /usr/local/lib/python3.7/dist-packages/apex/RNN\n        creating /usr/local/lib/python3.7/dist-packages/apex/transformer\n        copying build/lib.linux-x86_64-3.7/apex/transformer/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer\n        copying build/lib.linux-x86_64-3.7/apex/transformer/microbatches.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer\n        creating /usr/local/lib/python3.7/dist-packages/apex/transformer/_data\n        copying build/lib.linux-x86_64-3.7/apex/transformer/_data/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/_data\n        copying build/lib.linux-x86_64-3.7/apex/transformer/_data/_batchsampler.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/_data\n        creating /usr/local/lib/python3.7/dist-packages/apex/transformer/amp\n        copying build/lib.linux-x86_64-3.7/apex/transformer/amp/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/amp\n        copying build/lib.linux-x86_64-3.7/apex/transformer/amp/grad_scaler.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/amp\n        copying build/lib.linux-x86_64-3.7/apex/transformer/enums.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer\n        creating /usr/local/lib/python3.7/dist-packages/apex/transformer/functional\n        copying build/lib.linux-x86_64-3.7/apex/transformer/functional/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/functional\n        copying build/lib.linux-x86_64-3.7/apex/transformer/functional/fused_softmax.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/functional\n        copying build/lib.linux-x86_64-3.7/apex/transformer/log_util.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer\n        creating /usr/local/lib/python3.7/dist-packages/apex/transformer/pipeline_parallel\n        copying build/lib.linux-x86_64-3.7/apex/transformer/pipeline_parallel/_timers.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/pipeline_parallel\n        copying build/lib.linux-x86_64-3.7/apex/transformer/pipeline_parallel/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/pipeline_parallel\n        creating /usr/local/lib/python3.7/dist-packages/apex/transformer/pipeline_parallel/schedules\n        copying build/lib.linux-x86_64-3.7/apex/transformer/pipeline_parallel/schedules/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/pipeline_parallel/schedules\n        copying build/lib.linux-x86_64-3.7/apex/transformer/pipeline_parallel/schedules/fwd_bwd_pipelining_without_interleaving.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/pipeline_parallel/schedules\n        copying build/lib.linux-x86_64-3.7/apex/transformer/pipeline_parallel/schedules/fwd_bwd_pipelining_with_interleaving.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/pipeline_parallel/schedules\n        copying build/lib.linux-x86_64-3.7/apex/transformer/pipeline_parallel/schedules/common.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/pipeline_parallel/schedules\n        copying build/lib.linux-x86_64-3.7/apex/transformer/pipeline_parallel/schedules/fwd_bwd_no_pipelining.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/pipeline_parallel/schedules\n        copying build/lib.linux-x86_64-3.7/apex/transformer/pipeline_parallel/p2p_communication.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/pipeline_parallel\n        copying build/lib.linux-x86_64-3.7/apex/transformer/pipeline_parallel/utils.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/pipeline_parallel\n        copying build/lib.linux-x86_64-3.7/apex/transformer/parallel_state.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer\n        creating /usr/local/lib/python3.7/dist-packages/apex/transformer/tensor_parallel\n        copying build/lib.linux-x86_64-3.7/apex/transformer/tensor_parallel/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/tensor_parallel\n        copying build/lib.linux-x86_64-3.7/apex/transformer/tensor_parallel/cross_entropy.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/tensor_parallel\n        copying build/lib.linux-x86_64-3.7/apex/transformer/tensor_parallel/mappings.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/tensor_parallel\n        copying build/lib.linux-x86_64-3.7/apex/transformer/tensor_parallel/data.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/tensor_parallel\n        copying build/lib.linux-x86_64-3.7/apex/transformer/tensor_parallel/layers.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/tensor_parallel\n        copying build/lib.linux-x86_64-3.7/apex/transformer/tensor_parallel/random.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/tensor_parallel\n        copying build/lib.linux-x86_64-3.7/apex/transformer/tensor_parallel/memory.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/tensor_parallel\n        copying build/lib.linux-x86_64-3.7/apex/transformer/tensor_parallel/utils.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/tensor_parallel\n        creating /usr/local/lib/python3.7/dist-packages/apex/transformer/testing\n        copying build/lib.linux-x86_64-3.7/apex/transformer/testing/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/testing\n        copying build/lib.linux-x86_64-3.7/apex/transformer/testing/standalone_gpt.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/testing\n        copying build/lib.linux-x86_64-3.7/apex/transformer/testing/arguments.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/testing\n        copying build/lib.linux-x86_64-3.7/apex/transformer/testing/standalone_bert.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/testing\n        copying build/lib.linux-x86_64-3.7/apex/transformer/testing/commons.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/testing\n        copying build/lib.linux-x86_64-3.7/apex/transformer/testing/global_vars.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer/testing\n        copying build/lib.linux-x86_64-3.7/apex/transformer/utils.py -> /usr/local/lib/python3.7/dist-packages/apex/transformer\n        creating /usr/local/lib/python3.7/dist-packages/apex/parallel\n        copying build/lib.linux-x86_64-3.7/apex/parallel/sync_batchnorm.py -> /usr/local/lib/python3.7/dist-packages/apex/parallel\n        copying build/lib.linux-x86_64-3.7/apex/parallel/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/parallel\n        copying build/lib.linux-x86_64-3.7/apex/parallel/optimized_sync_batchnorm.py -> /usr/local/lib/python3.7/dist-packages/apex/parallel\n        copying build/lib.linux-x86_64-3.7/apex/parallel/distributed.py -> /usr/local/lib/python3.7/dist-packages/apex/parallel\n        copying build/lib.linux-x86_64-3.7/apex/parallel/multiproc.py -> /usr/local/lib/python3.7/dist-packages/apex/parallel\n        copying build/lib.linux-x86_64-3.7/apex/parallel/sync_batchnorm_kernel.py -> /usr/local/lib/python3.7/dist-packages/apex/parallel\n        copying build/lib.linux-x86_64-3.7/apex/parallel/LARC.py -> /usr/local/lib/python3.7/dist-packages/apex/parallel\n        copying build/lib.linux-x86_64-3.7/apex/parallel/optimized_sync_batchnorm_kernel.py -> /usr/local/lib/python3.7/dist-packages/apex/parallel\n        creating /usr/local/lib/python3.7/dist-packages/apex/fp16_utils\n        copying build/lib.linux-x86_64-3.7/apex/fp16_utils/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/fp16_utils\n        copying build/lib.linux-x86_64-3.7/apex/fp16_utils/fp16util.py -> /usr/local/lib/python3.7/dist-packages/apex/fp16_utils\n        copying build/lib.linux-x86_64-3.7/apex/fp16_utils/fp16_optimizer.py -> /usr/local/lib/python3.7/dist-packages/apex/fp16_utils\n        copying build/lib.linux-x86_64-3.7/apex/fp16_utils/loss_scaler.py -> /usr/local/lib/python3.7/dist-packages/apex/fp16_utils\n        creating /usr/local/lib/python3.7/dist-packages/apex/fused_dense\n        copying build/lib.linux-x86_64-3.7/apex/fused_dense/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/fused_dense\n        copying build/lib.linux-x86_64-3.7/apex/fused_dense/fused_dense.py -> /usr/local/lib/python3.7/dist-packages/apex/fused_dense\n        creating /usr/local/lib/python3.7/dist-packages/apex/optimizers\n        copying build/lib.linux-x86_64-3.7/apex/optimizers/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/optimizers\n        copying build/lib.linux-x86_64-3.7/apex/optimizers/fused_novograd.py -> /usr/local/lib/python3.7/dist-packages/apex/optimizers\n        copying build/lib.linux-x86_64-3.7/apex/optimizers/fused_lamb.py -> /usr/local/lib/python3.7/dist-packages/apex/optimizers\n        copying build/lib.linux-x86_64-3.7/apex/optimizers/fused_adagrad.py -> /usr/local/lib/python3.7/dist-packages/apex/optimizers\n        copying build/lib.linux-x86_64-3.7/apex/optimizers/fused_adam.py -> /usr/local/lib/python3.7/dist-packages/apex/optimizers\n        copying build/lib.linux-x86_64-3.7/apex/optimizers/fused_sgd.py -> /usr/local/lib/python3.7/dist-packages/apex/optimizers\n        creating /usr/local/lib/python3.7/dist-packages/apex/reparameterization\n        copying build/lib.linux-x86_64-3.7/apex/reparameterization/__init__.py -> /usr/local/lib/python3.7/dist-packages/apex/reparameterization\n        copying build/lib.linux-x86_64-3.7/apex/reparameterization/reparameterization.py -> /usr/local/lib/python3.7/dist-packages/apex/reparameterization\n        copying build/lib.linux-x86_64-3.7/apex/reparameterization/weight_norm.py -> /usr/local/lib/python3.7/dist-packages/apex/reparameterization\n        copying build/lib.linux-x86_64-3.7/apex_C.cpython-37m-x86_64-linux-gnu.so -> /usr/local/lib/python3.7/dist-packages\n        copying build/lib.linux-x86_64-3.7/scaled_upper_triang_masked_softmax_cuda.cpython-37m-x86_64-linux-gnu.so -> /usr/local/lib/python3.7/dist-packages\n        copying build/lib.linux-x86_64-3.7/syncbn.cpython-37m-x86_64-linux-gnu.so -> /usr/local/lib/python3.7/dist-packages\n        copying build/lib.linux-x86_64-3.7/fused_dense_cuda.cpython-37m-x86_64-linux-gnu.so -> /usr/local/lib/python3.7/dist-packages\n        copying build/lib.linux-x86_64-3.7/amp_C.cpython-37m-x86_64-linux-gnu.so -> /usr/local/lib/python3.7/dist-packages\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/multi_tensor_apply/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/multi_tensor_apply/multi_tensor_apply.py to multi_tensor_apply.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/amp/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/amp/__version__.py to __version__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/amp/compat.py to compat.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/amp/_initialize.py to _initialize.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/amp/lists/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/amp/lists/torch_overrides.py to torch_overrides.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/amp/lists/functional_overrides.py to functional_overrides.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/amp/lists/tensor_overrides.py to tensor_overrides.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/amp/handle.py to handle.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/amp/wrap.py to wrap.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/amp/rnn_compat.py to rnn_compat.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/amp/_process_optimizer.py to _process_optimizer.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/amp/frontend.py to frontend.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/amp/opt.py to opt.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/amp/scaler.py to scaler.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/amp/_amp_state.py to _amp_state.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/amp/utils.py to utils.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/amp/amp.py to amp.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/groupbn/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/groupbn/batch_norm.py to batch_norm.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/xentropy/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/xentropy/softmax_xentropy.py to softmax_xentropy.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/layer_norm/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/layer_norm/layer_norm.py to layer_norm.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/bottleneck/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/bottleneck/bottleneck.py to bottleneck.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/bottleneck/bottleneck_module_test.py to bottleneck_module_test.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/bottleneck/test.py to test.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/sparsity/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/sparsity/asp.py to asp.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/sparsity/sparse_masklib.py to sparse_masklib.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/transducer/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/transducer/transducer.py to transducer.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/fmha/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/fmha/fmha.py to fmha.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/multihead_attn/fast_self_multihead_attn_norm_add_func.py to fast_self_multihead_attn_norm_add_func.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/multihead_attn/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/multihead_attn/self_multihead_attn.py to self_multihead_attn.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/multihead_attn/fast_self_multihead_attn_func.py to fast_self_multihead_attn_func.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/multihead_attn/fast_encdec_multihead_attn_func.py to fast_encdec_multihead_attn_func.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/multihead_attn/fast_encdec_multihead_attn_norm_add_func.py to fast_encdec_multihead_attn_norm_add_func.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/multihead_attn/encdec_multihead_attn.py to encdec_multihead_attn.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/multihead_attn/encdec_multihead_attn_func.py to encdec_multihead_attn_func.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/multihead_attn/mask_softmax_dropout_func.py to mask_softmax_dropout_func.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/multihead_attn/self_multihead_attn_func.py to self_multihead_attn_func.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/optimizers/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/optimizers/distributed_fused_lamb.py to distributed_fused_lamb.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/optimizers/fp16_optimizer.py to fp16_optimizer.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/optimizers/fused_lamb.py to fused_lamb.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/optimizers/distributed_fused_adam_v3.py to distributed_fused_adam_v3.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/optimizers/fused_adam.py to fused_adam.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/optimizers/fused_sgd.py to fused_sgd.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/optimizers/distributed_fused_adam_v2.py to distributed_fused_adam_v2.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/contrib/optimizers/distributed_fused_adam.py to distributed_fused_adam.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/mlp/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/mlp/mlp.py to mlp.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/normalization/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/normalization/fused_layer_norm.py to fused_layer_norm.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/_autocast_utils.py to _autocast_utils.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/optim.py to optim.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/misc.py to misc.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/output.py to output.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/pooling.py to pooling.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/linear.py to linear.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/blas.py to blas.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/softmax.py to softmax.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/base.py to base.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/pointwise.py to pointwise.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/index_slice_join_mutate.py to index_slice_join_mutate.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/randomSample.py to randomSample.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/dropout.py to dropout.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/__main__.py to __main__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/activation.py to activation.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/convert.py to convert.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/utility.py to utility.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/conv.py to conv.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/normalization.py to normalization.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/data.py to data.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/usage.py to usage.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/loss.py to loss.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/prof.py to prof.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/recurrentCell.py to recurrentCell.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/embedding.py to embedding.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/prof/reduction.py to reduction.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/parse/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/parse/nvvp.py to nvvp.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/parse/kernel.py to kernel.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/parse/__main__.py to __main__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/parse/parse.py to parse.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/parse/db.py to db.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/nvtx/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/pyprof/nvtx/nvmarker.py to nvmarker.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/RNN/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/RNN/models.py to models.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/RNN/cells.py to cells.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/RNN/RNNBackend.py to RNNBackend.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/microbatches.py to microbatches.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/_data/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/_data/_batchsampler.py to _batchsampler.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/amp/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/amp/grad_scaler.py to grad_scaler.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/enums.py to enums.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/functional/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/functional/fused_softmax.py to fused_softmax.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/log_util.py to log_util.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/pipeline_parallel/_timers.py to _timers.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/pipeline_parallel/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/pipeline_parallel/schedules/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/pipeline_parallel/schedules/fwd_bwd_pipelining_without_interleaving.py to fwd_bwd_pipelining_without_interleaving.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/pipeline_parallel/schedules/fwd_bwd_pipelining_with_interleaving.py to fwd_bwd_pipelining_with_interleaving.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/pipeline_parallel/schedules/common.py to common.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/pipeline_parallel/schedules/fwd_bwd_no_pipelining.py to fwd_bwd_no_pipelining.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/pipeline_parallel/p2p_communication.py to p2p_communication.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/pipeline_parallel/utils.py to utils.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/parallel_state.py to parallel_state.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/tensor_parallel/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/tensor_parallel/cross_entropy.py to cross_entropy.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/tensor_parallel/mappings.py to mappings.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/tensor_parallel/data.py to data.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/tensor_parallel/layers.py to layers.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/tensor_parallel/random.py to random.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/tensor_parallel/memory.py to memory.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/tensor_parallel/utils.py to utils.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/testing/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/testing/standalone_gpt.py to standalone_gpt.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/testing/arguments.py to arguments.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/testing/standalone_bert.py to standalone_bert.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/testing/commons.py to commons.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/testing/global_vars.py to global_vars.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/transformer/utils.py to utils.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/parallel/sync_batchnorm.py to sync_batchnorm.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/parallel/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/parallel/optimized_sync_batchnorm.py to optimized_sync_batchnorm.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/parallel/distributed.py to distributed.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/parallel/multiproc.py to multiproc.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/parallel/sync_batchnorm_kernel.py to sync_batchnorm_kernel.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/parallel/LARC.py to LARC.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/parallel/optimized_sync_batchnorm_kernel.py to optimized_sync_batchnorm_kernel.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/fp16_utils/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/fp16_utils/fp16util.py to fp16util.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/fp16_utils/fp16_optimizer.py to fp16_optimizer.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/fp16_utils/loss_scaler.py to loss_scaler.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/fused_dense/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/fused_dense/fused_dense.py to fused_dense.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/optimizers/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/optimizers/fused_novograd.py to fused_novograd.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/optimizers/fused_lamb.py to fused_lamb.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/optimizers/fused_adagrad.py to fused_adagrad.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/optimizers/fused_adam.py to fused_adam.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/optimizers/fused_sgd.py to fused_sgd.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/reparameterization/__init__.py to __init__.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/reparameterization/reparameterization.py to reparameterization.cpython-37.pyc\n        byte-compiling /usr/local/lib/python3.7/dist-packages/apex/reparameterization/weight_norm.py to weight_norm.cpython-37.pyc\n        running install_egg_info\n        running egg_info\n        creating apex.egg-info\n        writing apex.egg-info/PKG-INFO\n        writing dependency_links to apex.egg-info/dependency_links.txt\n        writing top-level names to apex.egg-info/top_level.txt\n        writing manifest file 'apex.egg-info/SOURCES.txt'\n        adding license file 'LICENSE'\n        writing manifest file 'apex.egg-info/SOURCES.txt'\n        Copying apex.egg-info to /usr/local/lib/python3.7/dist-packages/apex-0.1-py3.7.egg-info\n        running install_scripts\n        writing list of installed files to '/tmp/pip-record-xcqqv22a/install-record.txt'\n        Running setup.py install for apex ... \u001b[?25l\u001b[?25hdone\n    Value for scheme.platlib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n    distutils: /usr/local/lib/python3.7/dist-packages\n    sysconfig: /usr/lib/python3.7/site-packages\n    Value for scheme.purelib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n    distutils: /usr/local/lib/python3.7/dist-packages\n    sysconfig: /usr/lib/python3.7/site-packages\n    Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n    distutils: /usr/local/include/python3.7/UNKNOWN\n    sysconfig: /usr/include/python3.7m/UNKNOWN\n    Value for scheme.scripts does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n    distutils: /usr/local/bin\n    sysconfig: /usr/bin\n    Value for scheme.data does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n    distutils: /usr/local\n    sysconfig: /usr\n    Additional context:\n    user = False\n    home = None\n    root = None\n    prefix = None\n    Successfully installed apex-0.1\n    Removed build tracker: '/tmp/pip-req-tracker-pgfywie_'\n\n\n\n```python\n!pip install triton==0.2.3\n```\n\n    Collecting triton==0.2.3\n      Using cached triton-0.2.3-cp37-cp37m-linux_x86_64.whl\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from triton==0.2.3) (1.7.1)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from triton==0.2.3) (1.18.2)\n    Requirement already satisfied: torch in /usr/local/lib/python3.7/dist-packages (from triton==0.2.3) (1.6.0+cu101)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->triton==0.2.3) (1.2.1)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from torch->triton==0.2.3) (0.16.0)\n    Installing collected packages: triton\n    Successfully installed triton-0.2.3\n\n\n\n```python\n# !pip uninstall -y typing\n```\n\n\n```python\n!pip install cpufeature\n```\n\n    Requirement already satisfied: cpufeature in /usr/local/lib/python3.7/dist-packages (0.2.0)\n\n\n\n```python\n!DS_BUILD_CPU_ADAM=1 DS_BUILD_SPARSE_ATTN=1 pip install deepspeed==0.3.7\n```\n\n    Requirement already satisfied: deepspeed==0.3.7 in /usr/local/lib/python3.7/dist-packages (0.3.7)\n    Requirement already satisfied: torch>=1.2 in /usr/local/lib/python3.7/dist-packages (from deepspeed==0.3.7) (1.6.0+cu101)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from deepspeed==0.3.7) (4.46.0)\n    Requirement already satisfied: tensorboardX==1.8 in /usr/local/lib/python3.7/dist-packages (from deepspeed==0.3.7) (1.8)\n    Requirement already satisfied: ninja in /usr/local/lib/python3.7/dist-packages (from deepspeed==0.3.7) (1.10.2.3)\n    Requirement already satisfied: torchvision>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from deepspeed==0.3.7) (0.7.0+cu101)\n    Requirement already satisfied: triton>=0.2.2 in /usr/local/lib/python3.7/dist-packages (from deepspeed==0.3.7) (0.2.3)\n    Requirement already satisfied: protobuf>=3.2.0 in /usr/local/lib/python3.7/dist-packages (from tensorboardX==1.8->deepspeed==0.3.7) (3.17.3)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from tensorboardX==1.8->deepspeed==0.3.7) (1.15.0)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from tensorboardX==1.8->deepspeed==0.3.7) (1.18.2)\n    Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from torch>=1.2->deepspeed==0.3.7) (0.16.0)\n    Requirement already satisfied: pillow>=4.1.1 in /usr/local/lib/python3.7/dist-packages (from torchvision>=0.4.0->deepspeed==0.3.7) (7.1.2)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from triton>=0.2.2->deepspeed==0.3.7) (1.7.1)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->triton>=0.2.2->deepspeed==0.3.7) (1.2.1)\n\n\n\n```python\n!ds_report\n```\n\n    --------------------------------------------------\n    DeepSpeed C++/CUDA extension op report\n    --------------------------------------------------\n    NOTE: Ops not installed will be just-in-time (JIT) compiled at\n          runtime if needed. Op compatibility means that your system\n          meet the required dependencies to JIT install the op.\n    --------------------------------------------------\n    JIT compiled ops requires ninja\n    ninja .................. \u001b[92m[OKAY]\u001b[0m\n    --------------------------------------------------\n    op name ................ installed .. compatible\n    --------------------------------------------------\n    cpu_adam ............... \u001b[92m[YES]\u001b[0m ...... \u001b[92m[OKAY]\u001b[0m\n    fused_adam ............. \u001b[93m[NO]\u001b[0m ....... \u001b[92m[OKAY]\u001b[0m\n    fused_lamb ............. \u001b[93m[NO]\u001b[0m ....... \u001b[92m[OKAY]\u001b[0m\n    sparse_attn ............ \u001b[92m[YES]\u001b[0m ...... \u001b[92m[OKAY]\u001b[0m\n    transformer ............ \u001b[93m[NO]\u001b[0m ....... \u001b[92m[OKAY]\u001b[0m\n    stochastic_transformer . \u001b[93m[NO]\u001b[0m ....... \u001b[92m[OKAY]\u001b[0m\n    utils .................. \u001b[93m[NO]\u001b[0m ....... \u001b[92m[OKAY]\u001b[0m\n    --------------------------------------------------\n    DeepSpeed general environment info:\n    torch install path ............... ['/usr/local/lib/python3.7/dist-packages/torch']\n    torch version .................... 1.6.0+cu101\n    torch cuda version ............... 10.1\n    nvcc version ..................... 10.1\n    deepspeed install path ........... ['/usr/local/lib/python3.7/dist-packages/deepspeed']\n    deepspeed info ................... 0.3.7, unknown, unknown\n    deepspeed wheel compiled w. ...... torch 1.6, cuda 10.1\n\n\n\n```python\nimport deepspeed.ops.sparse_attention.sparse_attn_op\n```\n\n\n```python\n%cd /content/\n\n!rm -rf rugpt3xl_ilm\n!cat /content/rugpt3xl_ilm/requirements.txt\n```\n\n    /content\n    cat: /content/rugpt3xl_ilm/requirements.txt: No such file or directory\n\n\n\n```python\n!git clone https://github.com/lauberto/rugpt3xl_ilm.git\n # TODO: add path to requirements.txt and install requirements (make sure to use the requirements necessary both for ILM and RUGP3XL)\n```\n\n    Cloning into 'rugpt3xl_ilm'...\n    remote: Enumerating objects: 752, done.\u001b[K\n    remote: Counting objects: 100% (247/247), done.\u001b[K\n    remote: Compressing objects: 100% (149/149), done.\u001b[K\n    remote: Total 752 (delta 135), reused 194 (delta 94), pack-reused 505\u001b[K\n    Receiving objects: 100% (752/752), 1.66 MiB | 7.84 MiB/s, done.\n    Resolving deltas: 100% (435/435), done.\n\n\n\n```python\n%%writefile ilm_requirements.txt\n\nboto3==1.13.16\nbotocore==1.16.16\ncertifi==2020.4.5.1\nchardet==3.0.4\nclick==7.1.2\ndocutils==0.15.2\nfilelock==3.0.12\nidna==2.9\njmespath==0.10.0\njoblib==0.15.1\nnltk==3.4.5\nnumpy==1.18.2\npython-dateutil==2.8.1\nregex==2020.5.14\nrequests==2.23.0\ns3transfer==0.3.3\nsacremoses==0.0.43\nsentencepiece==0.1.91\nsix==1.15.0\ntokenizers==0.5.2\ntqdm==4.46.0\nurllib3==1.25.9\n```\n\n    Overwriting ilm_requirements.txt\n\n\n\n```python\n# %cd /content/rugpt3xl_ilm\n\n! pip install -r ilm_requirements.txt\n! python -c \"import nltk; nltk.download('punkt')\"\n```\n\n    Requirement already satisfied: boto3==1.13.16 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 2)) (1.13.16)\n    Requirement already satisfied: botocore==1.16.16 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 3)) (1.16.16)\n    Requirement already satisfied: certifi==2020.4.5.1 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 4)) (2020.4.5.1)\n    Requirement already satisfied: chardet==3.0.4 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 5)) (3.0.4)\n    Requirement already satisfied: click==7.1.2 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 6)) (7.1.2)\n    Requirement already satisfied: docutils==0.15.2 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 7)) (0.15.2)\n    Requirement already satisfied: filelock==3.0.12 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 8)) (3.0.12)\n    Requirement already satisfied: idna==2.9 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 9)) (2.9)\n    Requirement already satisfied: jmespath==0.10.0 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 10)) (0.10.0)\n    Requirement already satisfied: joblib==0.15.1 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 11)) (0.15.1)\n    Requirement already satisfied: nltk==3.4.5 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 12)) (3.4.5)\n    Requirement already satisfied: numpy==1.18.2 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 13)) (1.18.2)\n    Requirement already satisfied: python-dateutil==2.8.1 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 14)) (2.8.1)\n    Requirement already satisfied: regex==2020.5.14 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 15)) (2020.5.14)\n    Requirement already satisfied: requests==2.23.0 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 16)) (2.23.0)\n    Requirement already satisfied: s3transfer==0.3.3 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 17)) (0.3.3)\n    Requirement already satisfied: sacremoses==0.0.43 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 18)) (0.0.43)\n    Requirement already satisfied: sentencepiece==0.1.91 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 19)) (0.1.91)\n    Requirement already satisfied: six==1.15.0 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 20)) (1.15.0)\n    Requirement already satisfied: tokenizers==0.5.2 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 21)) (0.5.2)\n    Requirement already satisfied: tqdm==4.46.0 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 22)) (4.46.0)\n    Requirement already satisfied: transformers==2.7.0 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 23)) (2.7.0)\n    Requirement already satisfied: urllib3==1.25.9 in /usr/local/lib/python3.7/dist-packages (from -r ilm_requirements.txt (line 24)) (1.25.9)\n    [nltk_data] Downloading package punkt to /root/nltk_data...\n    [nltk_data]   Package punkt is already up-to-date!\n\n\n\n```python\n!pip install transformers==3.5.1\n```\n\n    Collecting transformers==3.5.1\n      Downloading transformers-3.5.1-py3-none-any.whl (1.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.3 MB 4.3 MB/s \n    \u001b[?25hRequirement already satisfied: filelock in /usr/local/lib/python3.7/dist-packages (from transformers==3.5.1) (3.0.12)\n    Requirement already satisfied: sacremoses in /usr/local/lib/python3.7/dist-packages (from transformers==3.5.1) (0.0.43)\n    Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from transformers==3.5.1) (2.23.0)\n    Requirement already satisfied: sentencepiece==0.1.91 in /usr/local/lib/python3.7/dist-packages (from transformers==3.5.1) (0.1.91)\n    Collecting tokenizers==0.9.3\n      Downloading tokenizers-0.9.3-cp37-cp37m-manylinux1_x86_64.whl (2.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.9 MB 27.2 MB/s \n    \u001b[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from transformers==3.5.1) (1.18.2)\n    Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.7/dist-packages (from transformers==3.5.1) (4.46.0)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from transformers==3.5.1) (21.3)\n    Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.7/dist-packages (from transformers==3.5.1) (2020.5.14)\n    Requirement already satisfied: protobuf in /usr/local/lib/python3.7/dist-packages (from transformers==3.5.1) (3.17.3)\n    Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->transformers==3.5.1) (3.0.6)\n    Requirement already satisfied: six>=1.9 in /usr/local/lib/python3.7/dist-packages (from protobuf->transformers==3.5.1) (1.15.0)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->transformers==3.5.1) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->transformers==3.5.1) (2020.4.5.1)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->transformers==3.5.1) (1.25.9)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->transformers==3.5.1) (2.9)\n    Requirement already satisfied: click in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers==3.5.1) (7.1.2)\n    Requirement already satisfied: joblib in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers==3.5.1) (0.15.1)\n    Installing collected packages: tokenizers, transformers\n      Attempting uninstall: tokenizers\n        Found existing installation: tokenizers 0.5.2\n        Uninstalling tokenizers-0.5.2:\n          Successfully uninstalled tokenizers-0.5.2\n      Attempting uninstall: transformers\n        Found existing installation: transformers 2.7.0\n        Uninstalling transformers-2.7.0:\n          Successfully uninstalled transformers-2.7.0\n    Successfully installed tokenizers-0.9.3 transformers-3.5.1\n\n\n\n```python\n!cp /content/rugpt3xl_ilm/src_utils/trainer_pt_utils.py /usr/local/lib/python3.7/dist-packages/transformers/trainer_pt_utils.py\n```\n\n# Test model\n\n### Load model\n\n\n```python\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n```\n\n\n```python\nimport sys\nsys.path.append(\"rugpt3xl_ilm/\")\n```\n\n\n```python\nimport os\nos.environ[\"USE_DEEPSPEED\"] = \"1\"\n```\n\n## ILM\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/content/gdrive')\n\n%cd gdrive/My Drive/RUGPT3XL\n```\n\n    Mounted at /content/gdrive\n    /content/gdrive/My Drive/RUGPT3XL\n\n\n\n```python\n# TODO: upload data to gdrive\n# TODO: use the right path for the script below\n!! python3 /content/rugpt3xl_ilm/train_ilm.py \\\n\texperiment \\\n  /content/gdrive/RUGPT3XL/model_Economics \\\n\t/content/gdrive/RUGPT3XL/data/Economics_char_masks/ \\\n\t--seed 0 \\\n\t--train_examples_tag train \\\n  --data_loader_num_workers 8 \\\n  --eval_examples_tag valid \\\n  --eval_max_num_examples 512 \\\n  --tokenizer_name RUGPT3XL \\\n  --model_name sberbank-ai/rugpt3xl 2>&1 | tee rugpt3xl_TrainerLog.txt\n```\n\n\n\n\n    ['Traceback (most recent call last):',\n     '  File \"/content/rugpt3xl_ilm/train_ilm.py\", line 23, in <module>',\n     '    import ilm.mask.util',\n     '  File \"/content/rugpt3xl_ilm/ilm/mask/util.py\", line 3, in <module>',\n     '    from ..tokenize_util import tokens_offsets, align_charspan_to_tokenspan',\n     '  File \"/content/rugpt3xl_ilm/ilm/tokenize_util.py\", line 10, in <module>',\n     '    from .official_gpt2_encoder.encoder import Encoder as OfficialEncoder',\n     '  File \"/content/rugpt3xl_ilm/ilm/official_gpt2_encoder/encoder.py\", line 8, in <module>',\n     '    from ilm.tokenize_util import Tokenizer',\n     \"ImportError: cannot import name 'Tokenizer' from 'ilm.tokenize_util' (/content/rugpt3xl_ilm/ilm/tokenize_util.py)\"]\n\n\n\n\n```python\n!cat /content/rugpt3xl_ilm/ilm/official_gpt2_encoder/encoder.py\n```\n\n    \"\"\"Byte pair encoding utilities\"\"\"\n    \n    import os\n    import json\n    import regex as re\n    from functools import lru_cache\n    \n    from ilm.tokenize_util import Tokenizer\n    from ilm.paths import OFFICIAL_GPT2_ENCODER_DIR, OFFICIAL_RUGPT3_ENCODER_DIR\n    \n    @lru_cache()\n    def bytes_to_unicode():\n        \"\"\"\n        Returns list of utf-8 byte and a corresponding list of unicode strings.\n        The reversible bpe codes work on unicode strings.\n        This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.\n        When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.\n        This is a signficant percentage of your normal, say, 32K bpe vocab.\n        To avoid that, we want lookup tables between utf-8 bytes and unicode strings.\n        And avoids mapping to whitespace/control characters the bpe code barfs on.\n        \"\"\"\n        bs = list(range(ord(\"!\"), ord(\"~\")+1))+list(range(ord(\"\u00a1\"), ord(\"\u00ac\")+1))+list(range(ord(\"\u00ae\"), ord(\"\u00ff\")+1))\n        cs = bs[:]\n        n = 0\n        for b in range(2**8):\n            if b not in bs:\n                bs.append(b)\n                cs.append(2**8+n)\n                n += 1\n        cs = [chr(n) for n in cs]\n        return dict(zip(bs, cs))\n    \n    def get_pairs(word):\n        \"\"\"Return set of symbol pairs in a word.\n    \n        Word is represented as tuple of symbols (symbols being variable-length strings).\n        \"\"\"\n        pairs = set()\n        prev_char = word[0]\n        for char in word[1:]:\n            pairs.add((prev_char, char))\n            prev_char = char\n        return pairs\n    \n    class Encoder:\n        def __init__(self, encoder, bpe_merges, errors='replace'):\n            self.encoder = encoder\n            self.decoder = {v:k for k,v in self.encoder.items()}\n            self.errors = errors # how to handle errors in decoding\n            self.byte_encoder = bytes_to_unicode()\n            self.byte_decoder = {v:k for k, v in self.byte_encoder.items()}\n            self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))\n            self.cache = {}\n    \n            # Should haved added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions\n            self.pat = re.compile(r\"\"\"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+\"\"\")\n    \n        def bpe(self, token):\n            if token in self.cache:\n                return self.cache[token]\n            word = tuple(token)\n            pairs = get_pairs(word)\n    \n            if not pairs:\n                return token\n    \n            while True:\n                bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf')))\n                if bigram not in self.bpe_ranks:\n                    break\n                first, second = bigram\n                new_word = []\n                i = 0\n                while i < len(word):\n                    try:\n                        j = word.index(first, i)\n                        new_word.extend(word[i:j])\n                        i = j\n                    except:\n                        new_word.extend(word[i:])\n                        break\n    \n                    if word[i] == first and i < len(word)-1 and word[i+1] == second:\n                        new_word.append(first+second)\n                        i += 2\n                    else:\n                        new_word.append(word[i])\n                        i += 1\n                new_word = tuple(new_word)\n                word = new_word\n                if len(word) == 1:\n                    break\n                else:\n                    pairs = get_pairs(word)\n            word = ' '.join(word)\n            self.cache[token] = word\n            return word\n    \n        def encode(self, text):\n            bpe_tokens = []\n            for token in re.findall(self.pat, text):\n                token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))\n                bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))\n            return bpe_tokens\n    \n        def decode(self, tokens):\n            text = ''.join([self.decoder[token] for token in tokens])\n            text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors=self.errors)\n            return text\n            \n    def get_encoder(tokenizer):\n        if tokenizer == Tokenizer.RUGPT3XL:\n            models_dir = OFFICIAL_RUGPT3_ENCODER_DIR\n            with open(os.path.join(models_dir, 'vocab.json'), 'r') as f:\n                encoder = json.load(f)\n            with open(os.path.join(models_dir, 'merges.txt'), 'r', encoding=\"utf-8\") as f:\n                bpe_data = f.read()\n            bpe_merges = [tuple(merge_str.split()) for merge_str in bpe_data.split('\\n')[1:-1]]\n            return Encoder(\n                encoder=encoder,\n                bpe_merges=bpe_merges,\n            )\n        elif tokenizer == Tokenizer.GPT2:\n            models_dir = OFFICIAL_GPT2_ENCODER_DIR\n            with open(os.path.join(models_dir, 'encoder.json'), 'r') as f:\n                encoder = json.load(f)\n            with open(os.path.join(models_dir, 'vocab.bpe'), 'r', encoding=\"utf-8\") as f:\n                bpe_data = f.read()\n            bpe_merges = [tuple(merge_str.split()) for merge_str in bpe_data.split('\\n')[1:-1]]\n            return Encoder(\n                encoder=encoder,\n                bpe_merges=bpe_merges,\n            )\n        else:\n            raise NotImplementedError(\"Only GPT2 and RUGPT3XL tokenizer-wrapping is supported.\")\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "8cb2c87d0711f7563e87c3f9265898516bdafda5", "size": 419543, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/ruGPT3XL_ILM.ipynb", "max_stars_repo_name": "lauberto/rugpt3xl_ilm", "max_stars_repo_head_hexsha": "fbe30bd5ac1c14ec18264efb95e18e1655a25991", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/ruGPT3XL_ILM.ipynb", "max_issues_repo_name": "lauberto/rugpt3xl_ilm", "max_issues_repo_head_hexsha": "fbe30bd5ac1c14ec18264efb95e18e1655a25991", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-01T09:58:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T10:00:39.000Z", "max_forks_repo_path": "examples/ruGPT3XL_ILM.ipynb", "max_forks_repo_name": "lauberto/rugpt3xl_ilm", "max_forks_repo_head_hexsha": "fbe30bd5ac1c14ec18264efb95e18e1655a25991", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-28T07:17:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-28T07:17:24.000Z", "avg_line_length": 108.465098242, "max_line_length": 9865, "alphanum_fraction": 0.5943014184, "converted": true, "num_tokens": 93607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09401017961657226, "lm_q2_score": 0.0351448442532951, "lm_q1q2_score": 0.00330397312084873}}
{"text": "# Rich Output\n\nIn Python, objects can declare their textual representation using the `__repr__` method.  IPython expands on this idea and allows objects to declare other, rich representations including:\n\n* HTML\n* JSON\n* PNG\n* JPEG\n* SVG\n* LaTeX\n\nA single object can declare some or all of these representations; all are handled by IPython's *display system*. This Notebook shows how you can use this display system to incorporate a broad range of content into your Notebooks.\n\n## Basic display imports\n\nThe `display` function is a general purpose tool for displaying different representations of objects. Think of it as `print` for these rich representations.\n\n\n```python\nfrom IPython.display import display\n```\n\nA few points:\n\n* Calling `display` on an object will send **all** possible representations to the Notebook.\n* These representations are stored in the Notebook document.\n* In general the Notebook will use the richest available representation.\n\nIf you want to display a particular representation, there are specific functions for that:\n\n\n```python\nfrom IPython.display import (\n    display_pretty, display_html, display_jpeg,\n    display_png, display_json, display_latex, display_svg\n)\n```\n\n## Images\n\nTo work with images (JPEG, PNG) use the `Image` class.\n\n\n```python\nfrom IPython.display import Image\n```\n\n\n```python\ni = Image(filename='../images/ipython_logo.png')\n```\n\nReturning an `Image` object from an expression will automatically display it:\n\n\n```python\ni\n```\n\nOr you can pass an object with a rich representation to `display`:\n\n\n```python\ndisplay(i)\n```\n\nAn image can also be displayed from raw data or a URL.\n\n\n```python\nImage(url='http://python.org/images/python-logo.gif')\n```\n\nSVG images are also supported out of the box.\n\n\n```python\nfrom IPython.display import SVG\nSVG(filename='../images/python_logo.svg')\n```\n\n### Embedded vs non-embedded Images\n\nBy default, image data is embedded in the notebook document so that the images can be viewed offline. However it is also possible to tell the `Image` class to only store a *link* to the image. Let's see how this works using a webcam at Berkeley.\n\n\n```python\nfrom IPython.display import Image\nimg_url = 'http://www.lawrencehallofscience.org/static/scienceview/scienceview.berkeley.edu/html/view/view_assets/images/newview.jpg'\n\n# by default Image data are embedded\nEmbed      = Image(img_url)\n\n# if kwarg `url` is given, the embedding is assumed to be false\nSoftLinked = Image(url=img_url)\n\n# In each case, embed can be specified explicitly with the `embed` kwarg\n# ForceEmbed = Image(url=img_url, embed=True)\n```\n\nHere is the embedded version. Note that this image was pulled from the webcam when this code cell was originally run and stored in the Notebook. Unless we rerun this cell, this is not todays image.\n\n\n```python\nEmbed\n```\n\nHere is today's image from same webcam at Berkeley, (refreshed every minutes, if you reload the notebook), visible only with an active internet connection, that should be different from the previous one. Notebooks saved with this kind of image will be smaller and always reflect the current version of the source, but the image won't display offline.\n\n\n```python\nSoftLinked\n```\n\nOf course, if you re-run this Notebook, the two images will be the same again.\n\n## HTML\n\nPython objects can declare HTML representations that will be displayed in the Notebook. If you have some HTML you want to display, simply use the `HTML` class.\n\n\n```python\nfrom IPython.display import HTML\n```\n\n\n```python\ns = \"\"\"<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\"\"\"\n```\n\n\n```python\nh = HTML(s)\n```\n\n\n```python\ndisplay(h)\n```\n\nYou can also use the `%%html` cell magic to accomplish the same thing.\n\n\n```python\n%%html\n<table>\n<tr>\n<th>Header 1</th>\n<th>Header 2</th>\n</tr>\n<tr>\n<td>row 1, cell 1</td>\n<td>row 1, cell 2</td>\n</tr>\n<tr>\n<td>row 2, cell 1</td>\n<td>row 2, cell 2</td>\n</tr>\n</table>\n```\n\n## JavaScript\n\nThe Notebook also enables objects to declare a JavaScript representation. At first, this may seem odd as  output is inherently visual and JavaScript is a programming language. However, this opens the door for rich output that leverages the full power of JavaScript and associated libraries such as [d3.js](http://d3js.org) for output.\n\n\n```python\nfrom IPython.display import Javascript\n```\n\nPass a string of JavaScript source code to the `JavaScript` object and then display it.\n\n\n```python\njs = Javascript('alert(\"hi\")');\n```\n\n\n```python\ndisplay(js)\n```\n\nThe same thing can be accomplished using the `%%javascript` cell magic:\n\n\n```javascript\n%%javascript\n\nalert(\"hi\");\n```\n\nHere is a more complicated example that loads `d3.js` from a CDN, uses the `%%html` magic to load CSS styles onto the page and then runs ones of the `d3.js` examples.\n\n\n```python\nJavascript(\n    \"\"\"$.getScript('//cdnjs.cloudflare.com/ajax/libs/d3/3.2.2/d3.v3.min.js')\"\"\"\n)\n```\n\n\n```python\n%%html\n<style type=\"text/css\">\n\ncircle {\n  fill: rgb(31, 119, 180);\n  fill-opacity: .25;\n  stroke: rgb(31, 119, 180);\n  stroke-width: 1px;\n}\n\n.leaf circle {\n  fill: #ff7f0e;\n  fill-opacity: 1;\n}\n\ntext {\n  font: 10px sans-serif;\n}\n\n</style>\n```\n\n\n```javascript\n%%javascript\n\n// element is the jQuery element we will append to\nvar e = element.get(0);\n    \nvar diameter = 600,\n    format = d3.format(\",d\");\n\nvar pack = d3.layout.pack()\n    .size([diameter - 4, diameter - 4])\n    .value(function(d) { return d.size; });\n\nvar svg = d3.select(e).append(\"svg\")\n    .attr(\"width\", diameter)\n    .attr(\"height\", diameter)\n  .append(\"g\")\n    .attr(\"transform\", \"translate(2,2)\");\n\nd3.json(\"data/flare.json\", function(error, root) {\n  var node = svg.datum(root).selectAll(\".node\")\n      .data(pack.nodes)\n    .enter().append(\"g\")\n      .attr(\"class\", function(d) { return d.children ? \"node\" : \"leaf node\"; })\n      .attr(\"transform\", function(d) { return \"translate(\" + d.x + \",\" + d.y + \")\"; });\n\n  node.append(\"title\")\n      .text(function(d) { return d.name + (d.children ? \"\" : \": \" + format(d.size)); });\n\n  node.append(\"circle\")\n      .attr(\"r\", function(d) { return d.r; });\n\n  node.filter(function(d) { return !d.children; }).append(\"text\")\n      .attr(\"dy\", \".3em\")\n      .style(\"text-anchor\", \"middle\")\n      .text(function(d) { return d.name.substring(0, d.r / 3); });\n});\n\nd3.select(self.frameElement).style(\"height\", diameter + \"px\");\n```\n\n## LaTeX\n\nThe IPython display system also has builtin support for the display of mathematical expressions typeset in LaTeX, which is rendered in the browser using [MathJax](http://mathjax.org).\n\nYou can pass raw LaTeX test as a string to the `Math` object:\n\n\n```python\nfrom IPython.display import Math\nMath(r'F(k) = \\int_{-\\infty}^{\\infty} f(x) e^{2\\pi i k} dx')\n```\n\nWith the `Latex` class, you have to include the delimiters yourself.  This allows you to use other LaTeX modes such as `eqnarray`:\n\n\n```python\nfrom IPython.display import Latex\nLatex(r\"\"\"\\begin{eqnarray}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0 \n\\end{eqnarray}\"\"\")\n```\n\nOr you can enter LaTeX directly with the `%%latex` cell magic:\n\n\n```latex\n%%latex\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n```\n\n## Audio\n\nIPython makes it easy to work with sounds interactively. The `Audio` display class allows you to create an audio control that is embedded in the Notebook. The interface is analogous to the interface of the `Image` display class. All audio formats supported by the browser can be used. Note that no single format is presently supported in all browsers.\n\n\n```python\nfrom IPython.display import Audio\nAudio(url=\"http://www.nch.com.au/acm/8k16bitpcm.wav\")\n```\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"http://www.nch.com.au/acm/8k16bitpcm.wav\" type=\"audio/x-wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\nA NumPy array can be auralized automatically. The `Audio` class normalizes and encodes the data and embeds the resulting audio in the Notebook.\n\nFor instance, when two sine waves with almost the same frequency are superimposed a phenomena known as [beats](https://en.wikipedia.org/wiki/Beat_%28acoustics%29) occur. This can be auralised as follows:\n\n\n```python\nimport numpy as np\nmax_time = 3\nf1 = 220.0\nf2 = 224.0\nrate = 8000.0\nL = 3\ntimes = np.linspace(0,L,rate*L)\nsignal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times)\n\nAudio(data=signal, rate=rate)\n```\n\n\n\n\n\n<audio controls=\"controls\" >\n    <source src=\"data:audio/wav;base64,UklGRqS7AABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YYC7AAAAADUWvSvyPzdS/WHKbjt4Bn7+fxV+WXj3bjhifVJDQBYslBZiAC/qpdRswCGuU557kf2HJIIcgPWBoIfykKKdTa15v5rTEuk7/2kV8CopP3ZRSmEqbrJ3mH2vf+Z9TXgNb3Bi11K9QK0sQxcmAQPrhNVPwQOvLZ9IkreIxYKggFiC34cLkZOdFq0bvxbTbeh4/o0UASosPnNQSGAwbcd2w3z2fk9923fGblZi7FL/QBwt3hfoAefrg9ZlwiawVqBuk9OJzoOOgSSDg4iAkdadJa31vrvS3ue5/aIT8Sj/PDBP+F7da3t1h3vUfU98BncibuhhuVIJQWQtYRilAtjso9eqw4mxzKHtlE+LPYXkgleEiolTkm6ee60Hv4jSZuf//KsSwyeiO65NXF0zas9z5nlJfOh6zXUhbSdhPlLaQIItzBhbA9Xt39gexSmzjqPCliuNEYeihPKF9YqDk1mfGq5Uv3/SCOdN/KkReCYYOvBLd1szaMVx4HdYehp5MXTDaxNgfFFwQHUtHRkJBNvuN9q9xgW1l6XsmGOPR4nGhvKHwowPlZegAa/bv6LSxOak+58QFCVkOPhJSVnhZV9veXUCeOh2MnIIaqpecVDLPzwtUxmsBOjvp9uFyBm356dmm/aR3otOiVeK8Y73limiMLCewPHSneYG+48PmSOINslH11Y+Y6BssnJJdVF002/yZ+5cHU/rPtYsbBlEBfvwLd11ymO5e6ownuGU1I44jB+NgZE6mQ+kqLGcwW7Tk+Z1+noOCCKGNGVFI1ROYIppj28vcllxFG2CZeBagU3PPUMsZxnOBRHyyN6IzOC7T61GoSGYJZKBj0aQbpTXm0WmZ7PWwhjUp+by+WMNZCBhMtBCMFEUXSFmEWy4bgJu+Gm6YoFYnkt3PIIrQxlJBinzdOC9zo2+YLCkpLKbz5Unk8yTuJfLns2obrVMxPDU2+Z/+UwMsB4dMAxAAU6TWWdiPGjlak9qgWaaX9FVdEnjOpIq/xi0Bj/0L+IQ0WfBq7NHqJKfzpkml6yXXJsVoqSru7f9xffVL+ce+TYL7hy8LR09m0rOVWFeFGS6ZkJmsmImXNNSBEcVOXQpmhgMB1P19+N/02rELbctrL2jH557m+SbVp+zpciuTrroxy3XpefP+CQKIRtAKwY6/0bKURNanF87YuBhjV5gWIlPUEQMNycoFBhRB2P2yeUG1pTH4bpPsC+ovaIioHGgpKOhqTiyJL0OypHYPOiU+BgJSxmuKMo2M0OJTX9V2FpsXStdF1pKVPVLWUHKNKsmbBeCB2v3o+ej2OHKxb6stOOspacYpU6lQ6jdrfG1PMBtzCTa9ehu+BMIbhcHJm0zOT8RSatQzVVRWCdYUVXoTxlIID5PMgIloRadB2z4gulT203O08I+udax0qxXqneqLq1ksvC5k8MDz+Tb0ele+BcHjRVPI/MvFztmRJtLf1DvUtlSQVA9S/dDqTqeLysjtBWiB2P5ZOsS3tXRCccBvgK3P7Lcr+mvYrIytzK+KcfP0dHdz+pl+CYGqxOJIF4szzaMP1RG80pJTUVN6kpNRpQ/9ja3LCghpRSPB076Ru3e4HTVYcvxwmO86beitZ6127dEvLXC+srQ1Orf8OuE+EIFyRG5HbQoZzKIOtpALkVkR29HUUUbQfI6CDOcKfkecxNkByv7Ju+z4yjZ2M8JyPXByb2ju5K7lL2VwXXHA88E2C7iM+27+GsE6w/gGvck4i1eNTI7ND9HQV1BeT+sOxU25C5QJqAcHxIgB/r7AvGO5u3catREzbHH28PbwcHBiMMhx27MQ9No25zkmO4L+aQDEg4DGCshRSkTMGI1DDn2OhQ7aTkENgExiyrVIh4aqhDEBrr82PJt6b/gEdmd0pTNGcpFyCPIs8nlzJ3RtNf63jLnHfB0+e0CQAwkFVUdlCSsKm8vujJ2NJk0JTMnMLkrASYtH3QXEw9NBmj9pvRL7Jrkyt0Q2JfTfdDazrbOENDa0v3WVdy34u/pxPH3+UgCeApGEncZ1B8uJV0pQyzNLfEtsSwaKkImSiFbG6UUXQ2+BQP+aPYo73rokeKY3bXZA9eV1XLVmNb92IrcIeGd5tDsifOT+rYBuwhsD5UVCRueHzMjryUBJyInFCbiI6AgaRxiF7IRiAsVBYz+Hvj/8VzsYOcw4+rfpd1w3FLcSN1I30DiFeap6tTvbvVJ+zcBDAeZDLQRNxYAGvUcAh8YIDIgUx+FHdgaYxdEE54OlQlSBAD/xvnO9DzwNOzS6C/mXeRm41DjGeS25RroLevX7vjyb/cY/M0AbAXPCdYNYhFbFKoWQRgXGScZdBgHF+0UOxIGD2oLhgd3A2D/XvuS9xf0CPF67n/sJOtx6mfqBetD7BPuZfAl8zr2jPkA/XgA3AMRB/8JjwyxDlYQdBEEEgYSfBFuEOcO9QyqChoIWwWDAqr/5PxI+un32PUj9NXy9vGK8ZHxB/Ln8ib0uPWO95j5xPsA/jkAYAJiBDIGwwcKCQAKnwrmCtUKcQq/CcgIlQc0BrAEFwN3Ad7/V/7v/K/7n/rI+Sv5zPis+Mf4Gfme+U/6IvsQ/A79FP4Y/xAA9wDFAXQCAQNpA6sDyAPCA5wDWgMBA5cCIQKnAS4BvABUAPz/tv+D/2X/W/9j/3z/ov/Q/wIANABiAIcAngClAJkAeQBFAP7/pP87/8j+Tv7V/WD99/yg/GD8PPw5/Fn8nvwJ/Zn9S/4c/wMA/gACAgcDBQTxBMEFbgbwBj4HVAcuB8oGKQZMBTgE9QKJAQAAZv7G/C/7rflP+CH3L/aD9Sb1HfVr9RL2Dvdc+PL5x/vN/fb/MAJrBJUGmwhsCvgLLw0HDnQOcQ78DRMNvQsACucHggXiAhoAQP1p+q33IvXe8vXwd+9z7vXtA+6f7sjvd/Gj8zz2Mflq/NH/SgO8BgoKGg3RDxkS3hMOFZ4VhxXFFF0TVRG8DqMLIAhOBEkAMvwl+EX0sfCG7eDq1Oh259Pm9ObZ54Dp3+vk7nzyjPb1+pf/TATyCGQNfBEbFSAYdBoAHLYcjhyFG6EZ7RZ8E2cPzArMBY4APPv99fvwXuxM6OfkTOKR4Mbf9t8h4UHjSeYj6rTu2vNv+Uf/NQUNC58QvxVEGgge7CDXIrYjgSM1ItofgBw9GDITgw1bB+kAYPrx88/tLOg04xHf5NvK2dXYD9l72g/du+Bk5ejqHvHY9+L+BAYKDboT4BlKH8wjQieMKZgqWSrPKAMmCCL6HP8WQhD4CFgBnvkD8sbqHuRC3mHZotUn0wTSRtLt0/DWOduq4BvnW+409mn+ugboDrIW2h0oJGgpby0cMFYxEjFPLxcsgSevIcoaCBOjCtsB9fg18ODnOOB52dvTi8+tzFrLoMt+zenQydX821LjlOuE9N39VQemEIUZrCHaKNYubzN+Nuo3pTetNRAy5ixWJpEe0RVYDHECZ/iH7iDlfNze1IXOpMlixt3EIsUyxwDLcNBc147fyujJ8j791wdDEjEcUSVdLRM0PDmwPFA+DD7lO+k3MjLtKk8imhgXDhgD8/f77Iji7dh10GPJ8cNLwJG+0r4PwTnFMsvP0tbbAuYG8Y78Pgi+E7QeySitMRo50z6rQoFEQ0TyQZw9YTdvLwImYRveD9EDmPeR6xrgjtU/zHjEd75tuny4trgau5q/FcZazivYPuM97837jAgXFQ0hDyzHNec9L0RrSHhKQ0rNRyVDbTzXM6QpIh6pEZgEV/dK6tfdYdJByMm/O7nNtKSy0rJatSi6HMEAypLUgOBw7f76wAhNFjojIi+oOXdCSknqTTBQCFByTX5IUUEhODMt2yB3E24FL/cl6cDbaM9+xFm7QbRwrw2tLa3Sr+m0TbzGxQ7Rzd2i6yL63AhgFzslADJNPcdGIk4lU6VVjVXcUqNNCkZJPKswiCNGFVEGH/ck6NbZpcz4wCu3jK9ZqrunyqeHquCvrLexwaPNJtvU6Tr54AhPGA0nqDS0QNJKs1IXWNJazVoFWI9SkkpLQAg0JyYSFz8HJ/dH5xvYGsqxvUKzIKuNpbSir6J/pRKrPbPDvVTKkNgI6Ef4zAgbGbEoFzfaQ5dO+Va8XLJfw1/qXD1X5k4jREc3tSjbGDYIRveN5o7Wx8esuqKvAacPofud352+oISmBa8CuibHDNZD5kz3owjDGSYqTDm+RhJS8FoRYUJka2SGYapbAVPNR2U6LiueGjQJevf25THVsMXqt0ysMqPknJWZYJlJnDqiCKtwthrEntOF5Er2ZAhJGmsrRjtdSUJVl14RZX5owWjVZdBf31ZFS109jy1XHDkKwveB5QTU08NttUSptZ8PmYWVNJUimDmeSqcSszbBStHR4kP1EgisGoEsBT23SyNY6WG7aGJswWzSaaxjfFqITixA1i8FHkELHvgv5QbTM8I3s4qmjpySlc6RYJFOlIOaz6Psr3y+Ec8p4Tn0rQfuGmcthz7JTbVa5mQLbOtvaHB7bTpn1V2SUdBCADKlH0wMjPj95DjSz8BJsSGkvZlwknOO543RkB2XmqAArfC798yR3y/zNwcPGx0uzT+TT/Vcimf+bhdzs3PMcHhq5mBfVEVFCjQ1IVcNC/ns5JnRp7+jrwqiRpesj3eLy4qujQmUrp1SqpS5/soK3iXysQYQG6Uu1UAUUeJe1GmTceJ1nnbCc2FtrGPtVohH8TWyIl8OmPn75CnRvb5HrkagKZVHjd2IEIjnikyRDpvkp2u3KcmX3B3xHAbzGv4uoUFMUnxgw2vHc0p4KHlZdvJvJGY5WZZJszcaJGQPMvon5efQD74zrdaeaJNDi6eGuIV/iOeOv5i7pXi1e8c62xvwfAW4GikvMUI7U8JhVW2adU96TnuReCpyS2hAW21LTDlrJWMQ2fpw5dLQnr1qrLudBZKiidaExYN5ht2MwZbYo76z9sX22SDv0ARhGigvhELgU7Niim4Jd+17D31legV0H2r+XApNvDqjJloRifvV5enQaL3pq/Sc/pBliGuDOILWhDCLF5U+oj6yncTM2C7uHATvGfsunUI8VE9jYW8UeCN9Z37We4J1nWtzXmpO/ju+J0cSQfxU5izRbb2xq4KcVpCMh2iCE4GYg+OJxJPuoPywcsO/10ftYQNkGaMue0JQVJdj22+7ePJ9WH/gfJ92xWycX41PEj28KCgT//zr5pjRrL3Bq2ScDJAYh86BWIDBgveIyZLsn/qvdsLR1mzsoALBGCMuIEIcVItj92/9eFh+33+EfVt3k214YG9Q9T2aKfsTwv2Y5yzSI74ZrJqcH5AIh5yBBoBRgmyIKJI4nzmvrMED1qHr3AEJGHwtjUGhUyxjtW/beFZ+/H/AfbR3B24EYQ9Rpj5WKr8Uh/5b6ObS0b62rCKdjpBch9OBHYBJgkSI4ZHVnrquFsFZ1ebqFgE9F64sxEDiUntiF29UeOp9r3+Ufap3IG4/YWxRIj/vKnAVTf8w6cbTtL+XrfydWpEUiHKCn4CpgoCI9pHCnn+utMDT1D/qUABfFr4rxz/fUXphHm5rdxd9+H7/fDx33G0pYYRRaD9iKw4WEAAW6sjUy8C7riWfgJIviXmDioFygyCJaJIBn4quicBz1Kvpjv9xFasqlz6aUClgy2wfdt172X0DfGt2PW3AYFZRdz+vK5YW0gAL6+rVE8IgsJyg/5OqiuaE3oKihCOKNpOTn9uulsA61C7pz/51FHkpNz0WT4xeIWt0dD16UXyfejZ1QWwFYOJQTj/TKwgXjgEO7CzXi8PEsWCi1ZWGjLiGmoQ5homLYJR4oHOv3MAq1MnoFv5tEykoqDtUTaNcIGlpcjl4YnrVeJ9z6Gr2XiZQ7D7OK2EXQwIb7YrYMMWks22kAJi+ju6Iu4Y2iFKN5pWwoVKwW8FF1HzoZf1bEr4m7jlXS3Jay2YDcNN1DnimdqVxNGmVXSNPUD6eK6AX8AIx7gHa/8a9tcGmfppSkYWLQYmXinyPyJc6o3mxFMKK1EvovvxBETolCjghSftXJWRCbQxzV3UTdEtvJWfiW9lNej1DK8MXkgNO75Hb98gOuFqpS50/lHqOKYxbjQaSBJoXpeeyCMP71DboIfwiEJ8jADa2RkFVMWEqauhvQHIgcZJsvWTcWUhMaTy7KsoXKARv8DbdE8uTujSsZaCBl8yRcI9+kO2UmZxEp5y0NsSZ1T3okvv/DvAh0TMYREdS8l2+ZmpsyW7NbXxp/GGHV29KHTsHKrMXsQST8e7eU81JvUyvyaMWm3aVFJMAlDGYhZ/CqZe2n8Vk1mToEfvaDS8ggTFLQRFPa1oCY5Ro+Godagxm5V7iVFFIlzklKX4XKgW48rfgss8twKCycqf6nneZEpfcl86bx6KOrNi4Qsdc16nooPq2DGAeEy9QPqFLoFb4Xmpkz2YUZkNieVvvUe5F1jcWKCkXkgXb843iLtI8wyu2Xqspo8mdZpsQnMKfW6anr127H8mC2A7pQfqUC4MciiwtO/xHlFKkWvBfUWK2YSVevFewTkdD3TXZJrMW6AX79G/kxNRzxuq5ia+gp2miDKCZoAmkQKoLsyW+NcvW2ZTp9Pl3Cp0a6SnlNyVES04LVipbg10EXbVZsFMoS15AqjNvJR0WKwYW9lrmcNfNydi97rNarFSnAaVypaGocq63ti7BhM1X2zvqu/lfCa8YMid6NB9AykkxUR1WaFgEWPZUWE9YRzU9QDHYI2UVWQYp90voMNpIzfPBirhTsYSsQaqYqoWt77KqunfECdAE3QPrmPlQCLsWaSTwMPA7FUUbTMtQBVO6Uu1PuEpEQ845oC4UIowUcgY0+D/qAd3f0DbGV72GtvWxxq8GsLKys7ffvv3HxNLe3u3rivlLB8UUkSFMLZs3MUDMRjxLX00pTZ1K0kXuPio2zCslIJITdAY0+Tbs39+P1JzKUsLvu6K3jLW4tSS4urxUw73LstXj4Pjsk/lRBs8Srh6RKSUzITtKQXJFe0dXRwtFqkBaOk0yxCgLHnUSXwYo+ivuyOJV2CLPdceIwYe9jrupu9a9AcIGyLbP0tgS4yXutPlkBdsQwRvCJZEu6zWaO3Q/XEFIQTo/RjuLNTkuiyXHGzgRMwYO+x3wt+Us3MPTvcxOx57Dx8HUwcPDgsfyzOTTI9xr5XPv7fmFBOwOzxjkIeQpkzDBNUY5CjsCOzE5qDWFMPIpJCJaGdoP7gXk+wryq+gQ4HvYI9I6zeHJMcg0yOjJO80S0kXYoN/r5+LwPvq2AwMN2hX5HSIlHyvEL+4yiTSJNPMy1i9LK3olkB7HFlsOkAWr/O7zoOv/40XdpNdH00zQyM7Ezj3QJtNk19TcSeOR6nDyqPr5AiML5hIHGlEgkyWoKXIs3i3kLYcs1CniJdQg0xoOFL0MGQVf/cn1k+705x3iOt1w2djWhdV+1cDWPtni3I7hG+db7R30LPtOAk4J9Q8RFnMb9B9zI9clECcXJ/AlpyNPIAYc7hYzEQELiQQB/pj3gfHr6/7m4eKv34HdY9xc3Gndft+K4nDmEutI8On1yPu1AYUHCg0aEo8WSBoqHSIfJCApIDYfVB2VGhEX5hI2DicJ4QOP/ln5aPTg7+XrkugA5kDkXONZ4zPk4uVV6HbrK+9V89H3ffwxAcwFKQomDqcRkhTTFlsYIBkfGV0Y4Ba5FPsRvQ4aCzAHIAMJ/wv7RPfR88zwSu5c7A/raupu6hrrZOxA7pzwY/N/9tX5Sv3CACMEUwc5CsEM2Q5zEIURChIAEmoRUhDBDscMdgrhBx8FRgJu/6v8E/q697D1A/S+8unxhvGX8Rby/vJF9N31uPfF+fP7MP5oAIwCiwRWBuEHIgkQCqgK6ArQCmUKrQmwCHoHFQaOBPUCVQG9/zj+0vyW+4v6uPkh+cf4rPjL+CP5rPlf+jX7JPwk/Sr+Lf8kAAkB1AGBAgsDcAOvA8kDwAOXA1MD+AKNAhcCnQEkAbIATAD2/7H/gP9j/1v/Zf9//6X/1P8GADgAZQCJAJ8ApQCXAHYAQAD3/5z/Mv++/kT+y/1X/e/8mvxc/Dr8Ovxd/Kb8FP2n/Vz+Lv8YABMBGAIdAxkEAwXRBXsG+AZCB1MHKAe/BhkGNwUfBNgCaQHf/0T+pPwO+475NPgL9x72efUi9SD1dvUj9if3e/gX+vD7+v0kAGACmgTCBsQIkAoVDEUNFA54DmwO7Q37DJsL1gm3B0wFqALe/wP9Lfp19+/0svLQ8FzvZO7x7Qrusu7n76Hx1/N49nP5svwaAJQDBAdOClcNBhBEEv0TIBWjFX0VrRQ3EyMRfg5bC9EH+gPz/9r70ff282nwSe2u6rDoYefO5v/m9ees6RnsLO/O8uf2Vvv7/7EEVAm/Dc8RYRVZGJ0aGBy7HIAcZRtvGaoWKxMKD2QKXgUdAMv6j/WU8AHs/eeo5B7id+DB3wXgReF545Pmfuod70306fnF/7MFhwsRESYWnBpPHh8h9CK8I3AjDSKcHy0c2Re+EgMN0wZeANX5avNR7bvn0+LD3q3bqtnO2CLZp9pT3RXh0eVm66rxbPh6/5wGnA1DFFsatB8hJH4nrymfKkUqoCi6JaYhgxx2FqsPWAizAPn4ZPEx6pnj0N0F2WHVAdP80VzSINQ/16PbK+Gv5/7u4PYa/2sHkw9SF2oeoyTKKbYtRDBfMfswGC/CKxEnJSEsGloS6gkdATj4fu81557f9thy0z/PgsxQy7jLuM1D0UHWjtz6403sSPWm/h8IaRE7Gk8iZilGL8AzrTb1N4s3cDWwMWcsvCXfHQ0ViAubAZH3ue1f5M7bStQOzk7JMcbRxDzFcsdky/bQ/9dK4JnppfMg/rgIHRP8HAkm+i2RNJc55TxdPvE9ojt/N6YxQiqKIcEXMA0rAgb3Fuyy4SzYz8/eyJHDE8CDvu6+VcGnxcXLg9Ol3Obm+PGH/TYJrxSVH5MpWjKlOTg/5kKQRCZEqUEpPcc2sy4qJXMa4A7MApT2luov37rUicvmww2+L7psuNS4ZrsSwLTGHc8M2TbkRfDd/JsJHRYCIuwshTaAPp5ErEiKSiVKf0epQsc7DDO6KCAdlxB+Az32OenY3HvRfMcqv8e4ibSRsvGyqrWousfB0sqE1Yzhje4j/OUJaBdDJBIwdjodQ8NJMk5FUOlPH036R6BASDc4LMYfUBI/BAD2AOit2nDOqMOsusOzJa/3rE2tJ7BwtQO9psYR0uve0uxb+xUKjxhXJgEzKj55R6VOc1O9VW1VhFIYTU5FYzuhL2IiDBQNBdz16+ax2JzLE8BytgWvB6qip+un4KpvsG24nsK1zlXcF+uH+i0Kkhk8KLk1oEGRSz9TbFjsWqxaqlf9Uc1JWD/vMvAkxhXoBdH1++Xj1gDJvrx9spCqNaWYos+i3KWoqwe0vL51y8/ZXemn+SwKcBryKTg41ERiT45XF13QX6JfjFylVhdOJEMgNm0nfhfNBt31L+VG1Z7Gq7nRrmimsaDcnQCeHqEgp9ivBrtUyFvXqOe9+BQKKht3K306xkfpUo9bcmFkZEpkJmELWypSxEYwOdgpMRm7BwD2h+TY03fE3LZwq5CigJxymYCZqpzbouOrf7dVxfvU+eXL9+YJwBvMLIY8ckojVj5feWWjaKFocmUtXwBWMkocPCws2xqwCDn2A+Sc0o3CU7RdqAqfpJhelVOVhZjeniyoKrR8wrPSU+TT9qMJMhzwLVI+10wPWZhiKGmKbKJsbmkFY5dZbE3hPmcufByrCYb2ouOQ0d/AEbKZpdqbIZWkkX6Rs5Qsm7ekDLHMv4bQuOLX9UwJghzjLuE/9U6qW51lfmwXcEtwFm2QZupcblB8QYYwEB6oCuf2Y+O10G+/GLAnowKZ+pFFjgOON5HJl4ehJ65IvXbOLOHY9OIIsBymLzJByVDzXUhod29Gc5dzZnDKafZfNVPoQ4YylR+oC1n3RuML0D2+aK4HoYSWMI9Gi+aKFI64lJ+ef6v0uobMr9/Z82cIvBw4MEVCVFLpX5lqEXIVdoV2W3OxbLhivVUkRmU0CSGmDNz3SuOQz0m9Aq07n2CUxoypiCmITYv8kQOcF6nRuLnKRN7b8t0HqBybMBpDlVOLYY9sSnSBeBB583VBby1lBFgsSB82aSKjDW74beNFz5K856vEnZmSvopvhs+F5IiYj7aZ8abkthLJ79zh8UUHdhzPMLJDi1TXYiduInaIejh7K3h4cVJnCFr/SbM3tCOaDgz5r+Mozxm8FqujnDCRGImahNqD3YaOjbqXEaUttZLHsNvs8KAGJhzVMAxEN1XOY2FvlXcqfPt8AXpUcyVpxFuYSx455iSMD7b5DeQ5z927j6rWmyWQ14csg0uCOYXiixGWeaOxszzGitr/7/EFuhutMCpEmFVwZD1wpHhkfVZ+c3vRdKNqOF33TF46/iV1EGr6h+R3z927U6pgm3iP+oYmgiSB+oOUir6UKqJxshPFgNkb7zoFMxtbMA1EsFW8ZLpwT3k2fkl/gHzvdctrYV4YTnE7+iZTESX7GuXfzxi8X6o+myqPgoaJgWWAIYOmicKTKKFusRjElNhD7nsEkxrdL7VDgFWzZNlwlHmfftJ/JX2tdptsPV/7TlM81yclEub7xuVx0Iy8tKpxmzqPb4ZUgRGAroIZiR+Tc6CssE7Dxtd47bgD3Bk3LyRDCFVXZJtwdHmffvJ/ZH0IdxFtyl+dTwU9lCjoEqv8iOYq0Tm9T6v3m6iPwYaJgSaApILviNaSDKArsLXCGte87PECEBlqLlxCSVSnY/9v8Hg2fqh/O30BdyxtCWD8T4Q9LymcE3P9XucK0h2+MKzPnHKQeIcmgqWAAYMoieiS95/ur1HCkdYR7CoCMBh4LV5BRlOmYgdvCHhlffR+qXyXdu1s9l8YUM49pik9FDr+R+gO0zW/Va35nZiRkYgqg46BxoPDiVWTMqD0ryHCLdZ662MBPxdjLCxAAFJVYbRtvnYtfNd9sHvJdVJskl/vT+I99ynKFAD/QOk01IDAvK5xnxeTDIqWhN+C84TCih+UvqA/sCjC7tX36p4APhYsK8g+eVC2XwlsE3WOelJ8UHqZdFpr3V6BT789IipCFcL/SOp71fzBYrA3oe6U54tnhpiEh4YkjEOVnaHQsGfC19WL6uD/LxXXKTU9s07KXQZqCHOLeGZ6iXgGcwhq1V3NTmU9JSqjFX4AXOvf1qbDRrJHoxuXII6biLeGgIjojcSWzqKosd7C6dU26ib/FhRlKHQ7sUyWW69noXAmdhR4XnYScVpoe1zSTdI8/inrFTQBe+xe2HzFZrSfpZuZtZAxizqJ3YoMkJ+YUKTGso3DJdb76XX+8xLYJok5dkoaWQdl321gc191z3O+blJm0FqRTAU8rikZFuABoe332XvHvbY9qGyco5MnjiCMnI2QktOaJKYqtHfEi9ba6c39yRE0JXY3A0hbVg9ixWo8cEly4HALbPFj1FgKS/86MiksFoICzu6n26HJSrkdq4qf6JZ4kWWPvJBylWCdSKjUtZnFHNfV6TH9mhB6Iz41XUVaU8teV2e9bNVukW37aDlhiFY9ScA5iigiFhgD/+9r3evLCbw9rvOif5ojlQeTOpSvmESgvKrEt/XG2tft6aP8aA+tIeMyhkIcUD5bl2PmaAZr5mmRZSpe7VMrR0c4tyf7FZ8DMvFA31bO976ZsaKmZ54lmQOXEphGnH2jfa34uYvIxNgj6iP8NQ7PH2kwgT+kTG1XiV+8ZN5m4WXPYchaBVHURJU2tya2FRcEZPIl4d/QEsIttZWqmqJ4nVabQpwzoAini7BwvFnK2tl46rP7Aw3kHdItUjz1SFlTMVtAYGFihmG3XRRX0007Qqo0iiVRFX4ElfMW44PTVMX2uMeuFqcbovufxqBzpOOq47Mqv2DMHdvt6lX71AvtGyEr/DgTRQlPk1Z4W5Rd2VxOWRJTVkphP4gyMiTNFNMEwfQS5T/WvMjwvDWz1asHp/Ckm6UEqQyvgrckwp3Oi9yB6wr7qwruGVsogzUCQX9Ks1FoVnpY3VeXVMROlEZHPC8wrSIpFBUF6PUV5xDZRcwXwdq31LA6rC6qvarhrX6zaLtexRHRJt427NL6iAnoF4El6zHHPMFFlkwTURhTllKVTy5KjULvOKEt/CBjE0IFBvcd6fLb7M9mxbG8DravsbOvKLAHsze4j7/UyLrT7d8L7bD6bgjeFZciNy5kONJAQEeAS3JNCU1MSlJFRT5bNd4qIB9+ElkFG/gn6+PerNPaybbBfrtgt3m11rVxuDS998OEzJbW3eEB7qP6XwfUE6EfayrfM7c7t0GyRY1HO0fBRDZAvjmPMeonGx13EVsFJPkx7d7hg9duzuXGIMFJvXu7w7scvnDCm8hs0KPZ+OMY7636XAbKEaAciiY9L3U2/zuwP25BMEH4Ptw6/jSMLcUk7BpQEEUFIfo57+LkbNsf0znM7sZkw7XB68ECxObHeM2I1N/cOuZP8M/6ZgXFD5oZmiKAKhExHTZ9ORs77Tr2OEk1BjBWKXEhlRgJDxcFD/s88evnZN/n16zR48ytySHISMgfypTNidLX2EngpOim8Qj7gATFDZAWnB6uJZArFjAgM5g0dzTAMoIv2yrwJPIdGRaiDdIE7vs48/bqZuPB3DrX+dId0LnO1c5u0HPTzNdU3d3jNOsd81r7qQPNC4UTlhrMIPYl8CmeLOwt1C1aLIspgSVdIEkadxMdDHQEu/wr9f/tb+er4d7cLNmv1njVjNXp1oHZPN384Zrn5+2y9MT75QLgCX0QjBbdG0kgsSP8JRwnCifKJWkj/B+gG3oWshB5Cv4Ddv0S9wTxeuue5pPid99e3VjcaNyL3bbf1eLM5nzrvPBk9kb8MwL/B3sNgBLmFo4aXR1BHy4gHiAXHyEdURq+FoYSzQ24CG8DHv7t+AP0hu+X61To0uUk5FPjY+NP5A/mkejA64DvsvM0+OH8lQEsBoIKdg7sEckU+xZyGCcZFhlEGLkWhBS6EXIOyArbBsgCsv64+vf2jPOR8BvuOuz76mPqduov64bsbe7T8KPzxPYe+pX9CwFpBJQHcwrzDAEPjxCWEQ4S+BFYETUQmw6ZDEEKqAfjBAkCMv9y/N75i/eI9eTzqPLc8YPxnfEm8hbzZPQC9uL38/kj/GD+lwC4ArQEegb/BzkJIAqxCukKygpZCpsJmQheB/UFbQTSAjIBnP8Z/rb8fvt4+qn5F/nD+Kz40fgs+bn5cPpI+zn8Ov0//kL/OAAbAeQBjgIVA3cDswPKA74DkwNMA/AChAINApMBGwGpAEQA7/+s/33/Yv9b/2b/gf+p/9j/CgA8AGkAiwCgAKQAlQByADoA8P+T/yn/tP46/sH9Tv3n/JT8WPw5/Dv8Yvyt/B/9tf1s/kH/LAApAS4CMgMuBBUF4QWHBgAHRgdSByIHtAYIBiIFBgS6AkkBvv8h/oH87fpw+Rn49PYN9m71HvUk9YH1NvZA95v4PPoa/Cf+UwCQAskE7wbtCLMKMgxaDSAOfA5mDt0N4gx5C6wJhgcWBW0Cov/G/PL5Pfe89IbyrfBD71Xu7e0T7sfuB/DM8Qv0tfa2+fn8ZADfA0wHkgqUDTsQbhIbFDEVphVyFZUUERPwEEAOFAuCB6UDnP+D+3z3p/Mi8AvtfeqN6E3ny+YM5xPo2elU7HTvIvND97j7XgAVBbUJGg4gEqcVkRjEGi4cvxxxHEMbOxlnFtkSqw78CfAErf9a+iL1LvCm66/naeTy4V7gvd8W4Gvhs+Pf5trqhu/C9GT6QwAxBgEMgxGMFvMalB5QIQ8jwSNdI+MhXB/ZG3MXSRKDDEwG0/9K+eXy1exL53Tid95324zZydg32dXamd1x4UHm5us28gD5EQA0By8OyxTVGhwgdCS5J9AppSovKm4obiVCIQoc6xUUD7cHDgBV+MbwnukV41/drNgh1d7S9tF00lbUkdcO3K3hROih7473zP8bCD0Q8Bf4HhwlKir6LWowZTHhMN8uayueJpogjRmrETEJXwB798jui+YG33TYC9P2zlnMScvTy/TNoNG71iLdo+QH7Q32cf/oCCoS7xrxIvAptC8ONNk2/TdvNzA1TjHmKx8lKx1IFLcKxAC89uzsoOMj27jTms37yALGyMRaxbbHy8t+0aTYCOFp6oH0Av+ZCfYTxh2+JpQuDDXvORY9Zj7SPVs7EzcXMZQpwyDmFkkMPQEZ9jLr3eBt1yzPXMg0w9+/eL4Ov5/BGcZbzDnUdd3L5+vygP4vCp4VdCBbKgUzLjqaPx5Dm0QFRFxBszwrNvUtTySDGeINyAGR9ZvpRt7p09bKV8OnvfW5X7j1uLW7jMBXx+PP79kw5U7x7f2pCiIX9iLHLUA3FT8JRepIl0oCSixHKkIeOz8yzicdHIMPYwIk9Sno2tuX0LnGjr5XuEi0grIVs/+1LLt2wqfLedaZ4qvvSf0JC4IYSyX+MEA7v0M4SnZOVVDFT8hMckfrP2w2OyuvHikRDwPR9NvmnNl6zdbCBLpKs96u5axxrYCw/LW+vYrHFtMK4APulfxOC70Zcif/MwQ/KEgjT71Tz1VIVSlSiEyORHk6ky45IdESygOZ9LPljdeVyjK/vbWCrrqpjqcQqD6rArExuY7Dys+H3Vvs1Pt5C9MaaSnINohCTEzHU7xYAluHWktXZlEDSWE+0jG2I3kUkQR69LDkrtXpx867vLEEquKkgaL1oj2mQqzWtLm/mMwR27PqB/uMC8QbMCtXOctFKVAfWG1d6V99XylcB1ZETSJC9TQkJiAWZAV19NLj/9N4xa24Ba7TpVigwp0lnoKhwKewsA+8hcms2A7pLvqFC48cxiyrO8pIu1MoXM5hf2QlZMBgaFpOUbZF+TeAKMIXQgaH9BnjgtJCw9G1maryoSGcVZmlmRGdgaPDrJK4k8Za1m/nTPlnCzUdKi7CPYJLAFffX9tlwmh8aAplhV4dVRpJ2TrGKl4ZJwew9IbiNtFKwTyze6dknj+YPZV4le+YiJ8TqUa1xcMf1NflY/gzC7cdXS+bP/RN9llCY5BprWx+bARpWGKtWEtMkz31LPEaEwjv9BbiHdCPv++wrqQtm7eUgJGikR6V2pukpTCyH8H+0UnkdffqChQeXTA3QR1Qm1xOZutsPXAocKts4GX6W0ZPJEAJL3kcBAlC9crhNc8TvuuuMqJNmIqRHo4mjqOReph5olOvpL74z8jigvaNCk4eLDGTQvtR7V4Baepvb3N1c/pvF2kCXwZSiEL/MPMd+Amp9aHhf87WvDGtCqDHlbuOG4sHi4CObJWWn7GsWLwRzlXhjvUdCmYeyjGxQ5BT62BZa4lyQXZkdu9y/GvAYYlUvUTWMl4f7Qoh9pvh+s3Yu8KrNp6dk0yMeohJiLmLspL+nE6qPLpMzPPfmfSdCVweNjKPRNlUlGJVbcd0sXjyeId1i24xZMtWv0aJNLYg4Aup9rXhps0Zu5+quJzQkT6KPYbthVGJT5Czmi2oU7iryqXep/MNCTIecjIvRdZV52PzbqN2vHoce8B3wXBUZstYjUgXNvoh0QxA9+7hgc2ZusepkJtikJSIZYT1g0mHRo65mE+mobYwyWzdufJvCOkdfzKQRYlW5GQycBt4YHzgfJZ5nHImaIVaI0p+NycjvA3k90bijM1WujqpvppSj0+H9IJkgqOFmYwRl7mkKLXex0vc0PHGB4MdXjK0RfBWi2UTcS55nX0+fgp7GnSjafdbf0u7ODwkoQ6T+LvixM1RuvmoQpqhjm6G64E7gWKES4u+lWuj6bO3xkTb8PASBwAdDzKbRQxX22WUcdx5cn4zfxh8OXXLaiBdoEzMOTUlfA9L+UvjKc6IugGpHZpPjvOFS4F6gIeDW4rBlGii57K9xVnaGvBWBmMclTFHRd9W1mW2cSR63n6/f8B8+HWca/1dgk2uOhImTRAK+vXjuM76ulOpTZpcjt6FE4EjgBODzYkclLKhJLLyxIvZT++UBa4b8TC4RGlWfGV6cQd64X7hfwF9VnYVbIxeJk5hO88mERHQ+rbkcc+lu+2p0ZrIji2GRYE1gAWDoInRk0qhobFYxN7Yku7MBOEaJDDwQ6xVzWTgcIV5e36af9p8UnYzbM1eiE7iO2wnxhGY+43lUdCJvM2qqZuQj+KG4IGygGCD1YnfkzChYLHxw1LY5e0DBP8ZMS/xQqhUzWPpb594rH3pfkx863X3a75eqE4wPOcnaxJj/HnmV9GivfOr0py1kPmH44KXgSKEbYpJlGehYrG9w+nXSu04AwsZGS69QWFTe2KXblZ3dXzOfVZ7InVga19ehE5JPD4o/RIt/XbngdLwvlutS540knOJTITmgkuFaIsNle6hqLG+w6XXwexuAgUY3ixWQNhR2mDrbKt12XpMfPp59nNvaq9dHE4tPG8oexP1/YPozNNwwAWvE6AMlE6LHIachNuGxYwtlseiMrL2w4fXTuyoAfEWgyu+Pg5Q7V7naqFz13hiejd4aHIiaa5cb03aO3ko5BO6/p7pNtUfwu6wJqI7loiNT4i5htCIhI6nl/GjArNkxJDX8evmANAVCir4PAhOtVyOaDlxcnYTeBB2eXB7Z1xbfUxQO1woNRR4/8Xqvdb8wxKzgqS9mB2Q5Io6iSmLo5B7mWulF7QKxcLXq+srAKMUdSgGO8ZLNVrjZXZurXNhdYVzKm56ZblZRUuOOhYobhQuAPbrX9gDxnC1JaeRmw2T2Y0djOWNIZOomzancbXpxR3Yf+t5/28TxybqOExJcFfnYlpriXBNcppwfWshY8ZXyEmTOaYnjRTcAC7tGdozyAW4DKq0nlSWK5FgjwCR/JUtnlGpELcAx6LYbuvR/jQSAiWoNp5GaVSfX+lnCm3bbk9tdGhwYIRVBkhgOAsnkBR/AWvu6duHys26M60hou6Z1pQAk3mUM5kIobqr9LhPyFLZeOs1/vQQKCNCNL1DI1ENXCdkM2kNa6hpEGVqXfRSAEb0NkYmeBQVAqzvy93+zMW9lrDXpdmd2Jj7lk2Yw5w4pHCuHLvXyS3an+um/bMPPSG7Ma5Aok01WBVgB2XnZqhlVWESWhhQt0NRNVUlQhScAu7wvt+Uz+rAM7TQqRCiLZ1Mm3mcqaC5p3Kxhr2WyzPb5Osm/XEOQx8XL3M96kkbVLlbimBsYlJhRV1oVvFMLEF1Mzkk7xMUAy/yv+FG0jnEBrgKrpCm0aHwn/mg4qSLq760MsCNzWXcR+y2/DENPB1YLBE6/UXCTxZXwVugXalc41hvUoFJYD5jMfIifBN8A23zy+MR1a7HC7yAslWrwKbjpMqla6mpr1G4HsO6z8LdyexY/PYLKxuBKYo24UEwSzFSrlaHWLFXM1QsTstFVTscL38h6xLQA6b04OXy10bLPcAtt1qw9ashqueqQa4RtCm8R8Yc0krfau0N/MAKExmXJuMymT1oRg1NV1EmU25SOU+gSdJBDTifLOIfOhISBNj1++fl2vvOmsQOvJq1bbGlr02wX7PAuEPArcmz1P3gK+7V+5EJ9habIx8vKjlvQbFHwEuATeZM+EnQRJg9ijTvKRoeaRE+BAL3Gero3czSG8kewRG7Ibdrtfi1wrixvZ3ETc1819niC++z+20I1xSSIEMrlzRKPCBC70WbRxtHdES+PyA5zzANJykceBBWBCH4OOz34LTWvs1YxrrADr1tu+G7Zb7iwjLJI9F22t7kDPCn+1MHuRJ+HVEn5i/9NmA86D99QRNBsz5wOm003Sz8IxAaaA9XBDX5Vu4P5K/afdK3y5HGLsOnwQbCRMRNyADOL9We3QvnLPGx+0cGnRBjGk4jGiuMMXU2sTkpO9Q6uDjoNIQvuSi9IM8XOA5BBDr6b/At57neVdc30Y7Me8kTyF/IWcrvzQPTa9nz4F/pbPLS+0gFhg5DFz4fOCb+K2YwTzOlNGI0iTIsL2gqZSRSHWkV6QwUBDH7g/JN6s7iQNzT1q7S8c+tzunOoNDE0zfY1t1z5NjryvML/FoEdwwjFCQbRSFXJjcqxyz4LcItKyxBKR4l5B++Gd4SewvPAxf8jfRt7evmOuGE3OvYidZt1Z3VFNfF2ZjdbOIa6HTuR/Vc/HwDcQoFEQUXRBycIO0jICYmJ/smoiUqI6gfOhsEFjEQ8AlyA+z8jfaJ8AzrP+ZH4kDfPt1O3HbcsN3w3yLjKufn6zLx4PbF/LECdwjsDeQSPBfSGo8dXx82IBIg9h7uHAwaahYmEmMNSAj+Aq79gfie8yzvS+sW6KblCuRM427jbeQ95s/oC+zV7w/0lvhG/fkBiwbaCsUOLxL/FCIXiRgtGQwZKhiQFk4UeREoDncKhQZxAlz+Zfqq9kjzV/Dt7Rns5+pf6n/qRuup7JzuC/Hj8wr3Z/rf/VQBrwTUB6wKIw0nD6sQpRESEvARRBEXEHMOagwMCm4HpgTMAfb+Ofyq+V33YfXF85Py0PGB8aTxNvIu84P0KPYM+CD6UvyP/sUA5ALcBJ0GHAhPCTAKuQrqCsQKTAqHCYAIQQfWBUsErwIQAXr/+v2b/Gb7ZPqb+Q75v/it+Nb4NvnH+YH6XPtO/E/9Vf5X/0wALQHzAZsCHwN9A7YDygO7A44DRQPnAnoCAwKJAREBoAA8AOn/p/96/2H/W/9o/4T/rP/c/w4AQABsAI4AoQCkAJMAbgA1AOn/i/8f/6r+MP63/UX94PyO/FT8OPw9/Gb8tfwq/cP9ff5U/0EAPgFEAkgDQgQoBfAFkwYIB0kHUAcbB6gG9wUMBewDnQIpAZz//v1f/Mz6Uvn/99/2/fVk9Rz1KPWM9Un2Wve7+GL6RPxV/oMAvwL4BBsHFQnWCk4Mbw0sDn4OXw7MDcgMVwuBCVUH3wQzAmX/ify3+QX3ivRb8orwKu9H7uvtHO7c7ifw9/FA9PL2+vlB/a4AKQSUB9UK0Q1uEJcSOBRCFagVZhV7FOkSvBABDssKMgdQA0X/LPso91jz3O/P7E3qa+g758nmG+cx6Afqkey973bzn/ca/MMAeQUVCnQOcRLrFccY6hpCHMEcYRwgGwcZIhaFEkwOlAmBBDv/6fm19MjvS+ti5y3kx+FH4LvfKeCS4e7jLec36/HvNvXg+sEArwZ6DPQR8RZJG9gefyEoI8MjSCO3IRsfhBsMF9QRAgzDBUj/wPhf8lns3OYW4i3eQ9tx2cfYTtkF2+HdzuGy5mfsw/KV+aoAywfADlIVThuCIMQk8SfuKagqFio6KCAl3SCQG2AVew4WB2r/svcp8AvpkuLw3FTY5NS90vPRj9KO1OXXe9ww4troRvA7+HwAywjmEI0YhB+TJYgqPC6OMGkxxTCjLhErKSYNIOwY+xB3CKL/v/YT7uPlcN7116bSsM4zzEXL8cs0zv/RONe43U7lwu3T9joAsAnrEqIbkSN4Kh8wWTQCNwI4TzftNOkwYiuAJHYcgRPmCe//6PUf7OLiedoo0yjNq8jWxcPEe8X8xzbMCdJM2cfhO+te9eT/eQrOFI8ecSctL4Q1RDpFPWw+sD0RO6M2hTDkKPofChZgC08ALfVP6grgsdaMzt7H28Kuv3G+Mr/swY3G9Mzx1Ejesujf83r/JguMFlEhISuuM7M6+D9SQ6NE4EMMQTk8izU1LXMjkhjkDMMAjvSi6F7dGdMmysvCRL2+uVa4G7kJvAvB/cer0NXaK+ZY8v3+twsmGOgjny74N6c/cEUjSaFK3EnWRqZBcjpuMeAmFxtvDkgBC/Qa597atc/5xfW967cMtHeyPLNYtrS7KcN/zHDXqOPJ8G7+LQybGVAm6DEIPF5EqUq1TmFQnU9tTOZGMz+MNTwqlx0AEN8Bo/O45Y3Yh8wHwl+51LKbrtismq3esIy2fL5wyB7ULOE279D9hwzqGooo+zTaP9NInU8CVN5VH1XJUfRLy0OLOYMtDiCVEYUCV/N85GvWkclUvgy1A65yqX6nOqigq5qx+rmCxOLQut6g7SL9xgwTHJQq1DdtQwNNSlQHWRNbXVrnVspQNUhnPbMweiIrEzoDJfNm43rU1cbiugCxfKmUpG+iH6OjpuCsqbW6wL/NVdwK7Gf86gwWHWwsczq+RutQq1i+XfxfUl/CW2VVbUwbQcgz2CTAFPsDDfN34rvSVMS0tz2tQqUEoK2dUJ7soWWojLEbvbnK/9l26qD79gzzHRIu1jzKSYhUvFwlYpZk+mNVYMBZblCkRL42JSdSFsgEDvOt4S7REMLLtMapWaHHmz2Z0Jl+nSukp62oudTHvNfm6M766AypHoYv+z6PTNhXfGA3ZttoUmidZNddNVT/R5I5XinfF54FJ/MK4dPPCsApsp6mxJ3glyOVopVdmTig/qlnthHFjtVd5/T5www6H8cw4kAMT9ha52PyaclsVGyVaKdhvlcnS0E8gCtlGXwGWPOM4KzOQ77Rr8ejhJpSlGKRzJGOlY6clqZZs3bCeNPc5RP5iAylH9UxiUJAUYZd+2ZTbV1w/m86bCplBVsZTsg+iS3hGmAHnvMz4LfNu7zCrUKhnZcfkf2NT44UkjKZcaODsATAfdFm5C34NwzsH7Ay8UMpU+FftWlXcJJzTXOIb19oCF7SUCRBdi9QHEgI+PP+3/bMc7v+qxGfEZVLjveKL4vyjiaWkqDorb+9n8/94kP30wsPIFgzGUXHVOdhE2z7cmh2PXZ8ckFrwmBPU1FDRDGxHTIJZvTt32fMa7qHqjad4JLXi1OIb4gsjG6T/p2Kq6q74s2k4Vj2XAsPIM4zAUYYVphjFW4+ddp4zXgUdc5tMGONVU5F8DIBHx0K5fT+3wnMo7lcqbGbDZHFiRKGEYbDiQ2Rtpttqce5R8xd4G711QrtHxM0qUYeV/JkuW8ed+h6+HpNdwNwUWWJVxdHeDQ/IAYLdfUw4N3LG7l9qIKamY8XiDeEGIS6hwSPvZmSpxm40soq34b0PgqsHyc0EUfWV/Rl/XCaeJB8v3wled5xIWdBWalI2zVnIewLEvaB4OHL07jqp6uZhI7OhsOChIIUhleNFpj+paK2g8kO3qPzmglLHws0OkdDWKBm4nGxedB9H36aelxznmiyWgNKFDd3IswMvPbx4BTMyLijpyuZz43phbeBWIHShAiMw5axpGW1X8gK3cby6gjMHsEzJkdkWPVmZ3Jjeqh+Fn+qe310xmnaWyNLIzhvI6UNcfd94XXM+7iopwGZeo1rhROBlYD0gxeLxpWuo2S0Zscg3PLxMQgyHkoz1UY6WPNmjXKuehd/pX9UfD11mGq3XAZMBjlKJHUOL/gl4gLNa7n3py6ZhI1ThdmAO4B+g4aKH5X2oqCzmsZT2yjxbwd+HacySEbGV5tmU3KTehx/yn+XfJ51E2tJXatMujkJJTkP9Pjm4rrNFbqPqLGZ7Y2ghQmBS4Bug1eK0ZSMohuz/8Wk2mrwpwaxHNsxgUUKV+5lu3EUerh+hX90fJx1NGuMXQ9NPTqoJfAPvvm+45vO+LpvqYeatY5ShqGBxYDFg4mK3ZRvoteylMUV2rrv2wXOG+YwgUQGVu5kxXAveex91n7oezl1/GqCXTNNjzomJpgQjPqs5KLPE7yVqrGb2Y9oh6GCqIGEhB6LQpWiotSyW8Wo2RvvDQXWGswvS0O+VJxjc2/nd7d8v332enN0amonXRRNrTqCJi8RW/ut5c/QY70ArCudWJHiiAmE9IKqhRSMApYkoxSzV8Ve2Y3uPgTMGY0u4UEyU/phx209dhx7P3ydeUxzfWl9XLJMmDq6JrMRKfzA5h/S576srfSeMZO8iteFqIQ2h22NG5f2o5izh8U42RLucQOxGCwtREBlUQpgwmszdBx5WHred8NxNmiDWw1MTDrMJiQS9fzi55DTnMCZrwqhYZX2jAmIwoYniSaPj5gYpWC07sU52aztpwKIF6wreD5aT89dZ2nLcbl2DHi7ddlvlWY4WiNLyzm4Jn4SvP0R6R/Vf8LDsWuj5peMj56KQIl8iz+RXJqLpmy1isZh2V3t4gFTFg8qfzwSTUpbuWYHb/RzXHU1c5BtnGSeWPVJEzl8JsISfv5M6srWjsQntBKmvZp9kpKNIYwzjreTgpxNqLy2Xsex2SbtJQEUFVcoWjqSSoBYumPqa9FwS3JNcOpqSmK0VoJIIzgYJuwSN/+P647Yx8bDtv+o453FleOQYY9KkYyW/55eqlC4acgq2gjtcADNE4cmDjjbR3JVbWB3aFJt224Hbedno198VMxG/TaLJf0S5//Z7GnaJsmUuSysVaFimY+UAJO+lLyZ0aG9rCm6q8nM2gTtx/+AEqIknjXxRCVS1lyxZHppD2tlaYpkplz3UdJEnzXTJPMSigAo7lncqMuWvJivEKVQnZGY+JaOmEWd+KRor0O8JcuY2xztKP8wEakiCzPXQZxO+FicYE5l62ZpZdZgVlkmT5ZCCjTyI84SIgF571reSs7Hvz6zEKmLoeecR5u1nCShcKhesqC+1syO3FDtmP7fD6AgWTCRPtpK11Q8XNBgcmIYYc1ctlULTBlAPjLmIosSqwHK8GrgCtEiwxq3Ua0Qpo2h6Z8woValN6ydtT7BvM6v3aLtF/6ODokejC0iO+RGeFCUVwRcp11zXHNYyFGoSFw9PDCwISsSJAIa8ofi5NOkxiq7z7HZqn2m26T9pdepS7AjuRrE2dD73hHupv1ADWccpiqON71C3UuqUu9WkFiAV8tTj00ARWA6BS5QIKwRjAJm863k1dZJymi/hbbkr7WrGKoWq6WuqLTuvDTHKtNw4J/uR/33Cz0aqifYM2k+DEeATZZRL1NCUthODkkUQSg3myvGHg8R4QKs9Nvm2tkOztDDb7sqtS+xm694sLyzTLn6wIrKrtUP4kvv+/y0Cg0YnSQFMO05CUIeSPxLik2+TJ9JSUToPLYz/SgTHVMQIwPq9Q3p79zv0V/IicCouue2YLUethe5Mr5GxRjOZNjX4xbww/x6CdoVgSEYLE012TyGQihGpkf3RiNEQz9+OAwwLyY2G3gPUQMf90DrEeDn1RDNzsVZwNe8YrsDvLK+V8PNyd7RStvH5QHxofxKCKYTWh4VKI0wgTe+PB1Ah0H0QGo+ADrbMywsMSMzGX4OaQNJ+HTtPeP02d7ROcs3xvvCnMEjwonEt8iMztfVXt7e5wryk/wnB3QRKhsAJLErBTLLNuI5Mzu4Onc4hDQBLxkoByAIF2YNawNm+aTvb+YQ3sXWxdA9zE3JCch5yJbKTs6A0wLan+Eb6jLznfwRBkYP9hfdH8AmaiyzMHszrzRKNFAy1C70KdcjsRy5FC8MVgN1+s7xpek54sDbbdZm0sfPo87/ztbQFtSk2FreCuV97Hj0vfwKBSANwBSwG7whtiZ6Ku4sAS6uLfkr9Ci4JGkfMhlFEtoKKgN0+/Hz2+xp5szgLNys2GXWZNWw1ULXDNr23d7inOgC79z19fwTBAILixF9F6oc7SAnJEEmLifqJnkl6SJSH9IajRWvD2cJ5wJi/An2DvCe6uLl/eEL3x/dR9yG3NbdK+Bw44jnU+yo8V33RP0uA+8IWw5HE5AXFRu/HXofPSADINMeuBzFGRUWxRH5DNkHjAI+/RX4O/PT7v/q2+d85fLjRuN744zkbeYO6VfsLPBt9Pn4q/1cAuoGMgsTD3ESMxVHF54YMhkAGQ4YZhYXFDYR3A0lCi4GGQIG/hP6XvYF8x7wwO3569bqW+qK6l7rzuzL7kTxI/RQ97H6Kf6dAfUEFAjlClMNTA/FELQRFBLnETAR+A9MDjoM1gk0B2oEjwG6/gD8dvkv9zv1qPN+8sXxgPGs8UfyR/Ok9E72N/hO+oL8v/70ABADAwXABjkIZQk+CsAK6gq9Cj4KdAloCCQHtgUpBI0C7QBZ/9v9f/xP+1H6jfkF+bv4rvjc+EH51fmS+m/7Y/xl/Wv+bP9fAD4BAwKnAigDgwO5A8oDuQOJAz4D3wJwAvkBfwEHAZgANQDj/6P/d/9f/1z/av+H/7D/4f8TAEQAbwCQAKIAowCRAGoALwDi/4L/Fv+g/ib+rf08/dj8iPxR/Df8P/xs/L78Nf3R/Y7+Z/9VAFQBWQJdA1YEOgX/BZ8GEAdMB04HFAebBuYF9gTRA38CCQF6/9z9Pfyr+jT55PfJ9u71W/UZ9S31mfVc9nX32/iI+m/8gv6yAO8CJwVHBz0J+QpqDIINNw6ADlcOuw2tDDMLVgkjB6gE+AEo/0z8fPnO9lj0MPJp8BLvOu7q7Sfu8u5J8CTydvQv9z36if34AHIE2wcYCw0OoRDAElQUUBWpFVkVXxTBEocQwA2CCuIG+wLt/tX61PYK85bvlOwf6kvoKufI5irnUeg36s/sCPDL8/z3fPwnAd0FdQrNDsASLxb8GA8bVRzCHE4c+xrQGNsVMRLrDSoJEgTJ/nj5SfRk7/LqFufx457hMuC63z7gu+Er5Hvnlutd8Kz1XPtAAS0H8gxjElQXnRsZH60hQCPDIzEjiSHXHiwboxZdEYELOwW8/jX42/He62/muuHl3RHbV9nG2GfZN9sq3i7iJOfp7FDzK/pCAWIIUQ/YFcUb5yATJSgoCiqoKvspBCjQJHUgFBvTFOENdAbF/g73jO966BHig9z/16nUn9Ly0azSyNQ72OvctuJy6evw6fguAXsJjxEqGQ8gCCbkKnsurjBqMaYwZS61KrIlfh9KGEsQvQfk/gP2X+085dvdd9dE0mzOD8xEyxLMds5h0rfXUN775X7umfcEAXgKqxNUHC8k/SqIMKE0JzcEOC03pzSCMNwq3yO/G7oSFAkZ/xT1VOsm4tLZmtK5zF7IrsXAxJ/FRsijzJfS9tmI4g3sPPbFAFkLpBVWHyIowi/6NZU6cD1vPoo9xDowNvAvMSgvHywVdwpi/0H0bek53/bV7s1ix4XCgL9uvlm/PMIFx5DNrNUd35rp1PRyAB0MeRctIuUrUzQ1O1NAgkOnRLhDuEC8O+k0cSyVIp8X5Au//4vzqud43E3SeclDwuW8i7lRuEW5YLyNwabId9G82yjnYvMMAMUMKRnYJHUvrTg2QNRFWUmnSrFJfUYgQcI5mzDvJREaWg0tAPLyDebk2dfOPMVgvYO307NwsmiztLY/vN7DWs1p2Ljk6fGU/1ANsxpUJ9AyzDz5RBZL8E5oUHBPDUxXRnc+qjQ6KX0c1g6vAHXyl+SA15fLO8G+uGOyXa7QrMetQLEgtz2/Wcko1U/iavAK/74NFhygKfM1rUB6SRNQQ1TnVfFUZFFcSwRDmzhxLOIeVxBBARXyR+NM1ZHIer1ftImtL6l0p2ioB6w2sse6ecX80e/f5+5w/hEOUh28K904T0S2TchUTVkfWy1aflYrUGNHaTyRLz0h2xHjAdDxHuJJ08TF+rlHsPmoSqRhok+jDqeErYC2vsHozprdY+3H/UgOZx6lLYw7rUepUTJZCl4LYCJfVVu/VJFLEUCXMosjXxOSAqbxHeF50TTDvrZ5rLektZ+dnYCeWqIPqWyyKr7wy1Tb3+sS/WUOVR9cL/09xkpRVUxddmKnZMpj5V8TWYlPj0OANcgl4RRNA5bxQ+Dcz+HAyLP4qMagc5sqmQCa753bpJCuw7oYyR/ZX+pR/GgOGyDfMDBAmE2rWBRhjmbvaCFoKmQlXUlT30ZIOPQnYBYUBKDxkN9zzs6+G7HGpSidhpcNldOV0ZntoO+qi7dhxv/W5OiF+1IOuyAuMiRCIVC1W4ZkT2rgbCRsH2jvYMtW/knsOgkq1xfjBMHxBN8+zfq8t67louGZ85NJkfuRBJZHnY2nhrTQw/XUcOey+iUONCFJM9hDX1JtXqFntW12cM9vw2tvZAxa6ExqPQcsRxm6Bfrxnt49zGa7nqxXoPOWu5DijX6OjJLumW2kt7FowQTTBebY+eENhyExNEtFU1TQYGJqvXCvcx9zEG+gZwldmk+9P+otqxqXBknyXd5vyxO60KoenmCU4o3Zil2La4/mlpOhI68rvzDRp+T5+IgNtiHkNH5G+VXeYsdsZ3OHdhB2BHKAar5fEVLjQa8vAxx3B6zyQd7WygK5UKk7nCmSaYsxiJuIpYwwlAOfyqwcvXrPV+MY+BsNwCFkNW5HU1eWZM9urnX9eKF4m3QLbSliSlTZQ1QxSx1ZCCLzSd5wyjK4HaivmlCQU4nuhTyGPIrQkb6csao/u+bNF+I295wMpyGxNR5IYFj3ZXhwk3cOe8561XY/b0dkQ1adRdcygh47Carzct48yqK3N6d6mdeOoIcPhEGEM4jIj8ea2qiVuXbM6uBU9g0MbCHMNY5IH1n/ZsJxE3m5fJd8rXgZcRZm+FcsRzQ0pB8bCkH0vt45ylO3nqadmL2NU4aYgquCi4YcjiGZSKchuCvL0t929W4LESG2Nb1IkVmwZ6xyLnr8ffl9I3qYcpJnZ1mESGs1sSD3Cub0KN9nykO3U6YZmASNa4WJgX2BR4XLjM+X/KXmtgnK0d6d9MIKlyBwNa1ItlkJaDVz43rXfvN+NXu6c7toj1qiSXg2piHNC5j1sd/EynO3U6bsl6uM6YTjgLiAaITZi9CW+aTltRHJ6d3L8wsK/x/8NF9IkFkKaF1zMXtJf4R/4Xt8dI9pbVuFSlo3gSKbDFT2V+BPy9+3oKYWmLKMzoSmgFuA74NHiyiWQKQgtUbIHN0B80oJTB9bNNRHHlm1ZyZzGXtRf6t/J3zfdAtqAFwrSw84QCNgDRn3F+EGzIi4NqeWmBmNGYXTgGmA3YMVi9iV06OZtKjHa9xC8oIIfx6PMw1HY1gKZ5BynHrvfml/BnzgdC9qR1yTS5U44SMZDuX38OHnzGy5Fqhsmd+NyYVpgeCAMYREi+CVs6NRtDrH2tuQ8bQHmh2ZMg1GYFcKZptxuXklfr1+fnuAdPtpQFy6S+s4YyTEDrX44eLxzYi6PKmVmgKP3oZngsCB7YTUi0GW4aNKtP3GaNvs8OIGnxx8MdZEFla4ZEpwcnjzfKl9j3q/c21p6luhSw45xCRgD4j55uMhz9u7qaoQnIGQVojNgwmDD4bHjPyWXqSFtPPGGNtZ8A4GkBs5MGhDiFQUY51uyXZZeyx8OnmccoZoRltFS/84AiXqD1z6/uR10GK9WKzbnVuSMIqZhbqEl4cajhCYKqUCtRzH7NrX7zoFcBrTLsdBuFIiYZdsv3RbeUd6f3cYcUVnU1qnSrs4HCViEDD7J+bs0Ry/Sa70n4yUaozKh9GGhInOj32ZRabCtXrH5Npp72gEPxlNLfU/p1DjXjtqVnL4dv53YHU0b6tlEFnFSUM4EiXGEAD8XueC0wbBeLBYohOXAY9dikyJ1YvikUObr6fFtg3IAtsQ75kDARinK/Q9Wk5bXIpnkW81dFF13nLxbLljflehSJU34CQUEcz8o+g21R3D4rIEpe6Z85FRjSuMh45UlGGdaakLuNbIR9vN7tECtxbmKcg700uLWYdkc2wScUJy+29Qam9hnlU5R7E2iCRLEZH98ekF117FhrX2pxidPZWikGmPmpEil9afcKuUudXJs9uj7g8CZRULKHI5FEl4VjZh/miTbdVuumxUZ9BecFOORZc1CCRpEU7+SOvr2MfHX7grq4+g3JhNlASTCpVLmqCixK1huwvLSNyR7lcBCxQZJvY2IUYjU5pdNmW8aQxrHGn/Y9xb9VChQ0Y0XyNuEQH/pOzo2lXKa7uerk+kzZxQmPuW1JjNnb2lZLBvvXbMBd2a7qoArBITJFg0/UKST7dZHWGPZepmJWVSYJZYME5yQcAyjSJYEaj/BO733ATNpr5MslWoC6GnnEib9pykoSupTrO+vxjO7N2+7goASxH7IZkxqz/HS49VuVwQYXJi2WBRXABVIUsDPwMxkiEmEUEAZu8X39LPDcIztp2slKVNoeifbaHOpeisgbZNwu/P+9797nj/6Q/UH70uMDzHRyhRDVhDXKpdOVz+Vx1Ry0dUPBIvbSDYEMwAx/BE4bvSnMVMuiKxYqpAptikNaZIqvGw+rkaxfrRNeBa7/T+iQ6hHcgrjziVQ4ZMHlMsV5NYS1deU+9MMERoOe0sHx9tEEcBJvJ847zVT8mWvuG1cq95qxOqSasOr0S1t70kyDnUl+HU74L+LQ1lG7woyzQ1P6xH703RUTRTEVJzTnlIUkBBNpQqqR3kD7EBgPO85dHYI80Kw9S6vrT2sJavprAdtNy5tcFpy6vWIuNs8CH+1gsiGZ0l6DCsOqBChkg0TJBNkkxCSb9DNDzfMgooCRw9DwgC0/QB6PjbE9Gmx/i/Q7qwtlq1R7Zvube+8sXnzk7Z1eQi8dT9hwraFm8i6yz/NWU96EJdRq1H0EbPQ8Q+2TdGL08lQhp4DkwCHfZK6i3fHdVlzEjF+r+kvFu7KbwCv9DDasqb0iDcsOb28Zr9QQmSFDQf1ygwMQI4GD1PQI5B0UAePo05RTN4K2UiVBiVDXsCXveT7G3iOtlB0b7K4MXLwpXBRMLRxCTJGs+C1iHfsejo8nb9BghKEvAbsCRGLHoyHjcPOjs7mTozOB00ei54J08fQBaTDJQCkvjZ7rTlad041lbQ7sshyQLIlsjWyq/O/tOa2k3i2Or582f92QYGEKcYeyBFJ9Ms/TCkM7Y0LzQUMnkufSlIIw4cBxR0C5gCufka8f/opOFD2wrWINKgz5zOGM8O0WvUFNng3qLlI+0n9W/9uQXIDVsVOhwxIhMnvCoTLQguly3FK6UoUSTtHqQYqxE3CoUC0fpU80vs6eVf4Nbbb9hD1l7VxdVy11XaVd5R4x/pkO9y9o39qQSSCxAS8xcPHT0hXyRhJjQn1iZNJaYi+h5oGhUVLQ/eCFsC2PuF9ZTvMuqG5bXh194D3ULcl9z+3Wjgv+Po58DsHvLZ98L9qwNnCckOqRPjF1cb7R2UH0Eg8x+vHoEcfhm+FWMRjwxpBxoCzfyq99jye+616qDnUuXb40LjieOs5J7mTumj7IPwzPRc+Q/+vwJJB4kLYQ+yEmcVaxeyGDUZ9BjyFzsW3xPzEJAN0gnYBcIBsP3B+RP2wvLm75Tt2+vF6ljqlep36/Ps/O5+8WX0l/f6+nP+5gE6BVQIHQuBDXEP3hDBERYS3REbEdkPIw4KDKAJ+gYtBFIBf/7I+0P5AvcW9YvzavK78X/xtfFY8mHzxPR09mL4fPqx/O/+IgE7AysF4gZVCHsJTQrHCuoKtgowCmAJTwgHB5YFBwRqAssAOP+9/WT8N/s++n/5/Pi3+LD44/hL+eP5o/qD+3j8e/2B/oH/cwBQARICswIxA4kDvAPKA7YDgwM3A9YCZwLvAXUB/QCPAC0A3f+e/3T/Xv9c/2z/iv+0/+X/FwBIAHMAkgCjAKMAjwBmACkA2v96/wz/lv4b/qP9M/3Q/IL8Tfw2/EH8cfzG/EH94P2f/nr/agBpAW8CcwNqBEsFDgaqBhcHTgdMBwwHjgbUBd8EtwNhAugAV/+5/Rv8i/oW+cv3tPbf9VP1GPUz9ab1cfaQ9/34rvqa/LD+4gAfA1UFcgdlCRoLhQyVDUEOgQ5ODqkNkgwPCyoJ8AZwBL0B6/4P/EH5l/Yn9AbySPD77i7u6e0y7grvbPBR8qz0bveC+tH9QgG8BCMIWgtIDtMQ5xJvFF4VqRVLFUMUlxJREIANOAqRBqYClv5/+oH2vfJR71rs8eks6BvnyeY753PoaOoO7VPwIPRZ+N78jAFABtUKJQ8PE3EWLxkyG2ccwRw7HNUamRiUFdsRig3BCKIDWP4I+d3zAO+Z6szmt+N34R7gvN9U4ObhaeTM5/bryfAi9tj7vwGqB2oN0hK3F+8bWh/YIVUjwiMYI1ohkh7UGjkW5RD+CrEEMf6s91fxZOsD5l/hnt3h2j/ZyNiC2Wvbdt6P4pjnbO3f88D62wH4COEPXRY7HEkhYCVcKCQqpirdKcsnfiQMIJYaRRRHDdIFIP5r9vDu6ueR4RjcrNdx1IPS9NHL0gXVk9hc3T3jCuqR8Zj54AEqCjYSxBmYIHsmPiu4Ls0waDGEMCQuVyo4Je4epheZDwIHJv5H9avsl+RJ3fzW5NErzu/LRcs1zLvOxtI42OreqeY872D4zwFAC2oUBR3LJIEr7jDnNEo3AjgHN140FzBTKjwjBhvxEUEIQv5A9Inqa+Es2Q/STMwUyInFwcTGxZLIE80n06LaS+Ph7Bv3qAE5DHoWHCDRKFUwbDbkOpc9bz5hPXQ6uzVZL30nYh5NFI0JdP5W84zoad4+1VPN6cYywla/br6Dv5DCgMcuzmnW89+E6sn1bAEUDWUYByOmLPY0tDuqQK5DqESMQ2FAPDtENKwrtSGrFuQKuv6J8rPmlNuC0c7IvsGJvFy5ULhyubq8EsJSyUXSptwm6G30HAHSDSsaxiVIMF85wkA0RotJqUqCSR9GlkAQOcUv/SQIGUQME//a8QHl7Nj7zYLEz7wet5+zbrKYsxW3zryXxDfOZdnL5QnzuQByDskbVii1M409kUV/SydPbFA/T6lLw0W4PcUzNShhG6wNgP9J8XbjddaqynPAIbj2sSSuy6z5raaxuLcCwEbKNdZ0457xRAD1DkAdtSrpNn1BHUqFUH9U7FW+VPxQwEo5Qqc3XCu0HRkP/v/U8BPiLtSTx6O8trMTrfCobqecqHKs1rKXu3TGGdMm4S7wvv9cD5Ae4izjOSxFZE5CVY9ZJlv5WRBWh0+NRmg7bC79H4oQiwB88NjgGtK2xBW5k697qAakWaKEo36nLK5at8XCFNDi3rzuKP+mD7cf3S6hPJhIY1K0WVFeFGDtXuNaE1SxSgQ/ZDE7Iv0RKAFA8MXfOdAXwsy1uqsxpGyfk522ns6ivalQsz6/Ks2s3ErthP7UD7UgozAhP75LFVbWXcNismSUY29fYlihTnZCPzRqJG8T0wEf8Nrejc62v8qyL6g3oCSbHpk2mmaekKV9r+G7XsqF2tnr0/3oD4whNjJjQZxOelmmYeBm/WjrZ7FjblxYUrxF+zaHJt4UigIY8BjeFc2VvRCw8qSSnDKX/pQJlkuap6Hjq7O4tMdy2GzqF/3hDzoikzNkQzBRjVwgZaVq8Wzua6RnM2DSVdFIlDmQKEkWSwMs8H3d0su0u6GtCKJEmZqTN5ExkoCWBp6IqLe1LcV01gXpUfzCD8EiuzQkRXpTTl9CaBBuinCab0ZrrmMNWbNLBzyCKqwXFQRX8ArdxMoVun6rcZ9Oll2QzY2zjgqTsZpvpfCyzsKO1Kbng/uKDyEjrzWiRndVumEKax5xxXPqcpFu3GYFXF5OUj5bLAUZ5gSa8L3c7Mm4uKepMJ20k3+NwYqRi+qPq5eaomKwmcDD0lLmsPo8D1sjbTbeRydX0GN2bcxzoXbddYRxuWm2Xs9QcEAXLlMavAXy8JfcSMmctx6oRZt4kQGLFojOiCSN+JQNoA+ukr4W0Qvl2PnaDm8j9jbYSIpYj2WEbxh2GXlveBx0QmwdYQNTYEK1L5MblQZf8ZXc2cjDtuOmspmZj+eI0IVthruKmZLLnfururyIz9Pj/vhjDl4jTDeQSZ1Z9mYycQF4LnueelZ2dW45Y/hUH0QyMcMccAff8bfcncgttvald5gajjCH74NwhLKIk5DXmyeqFbsdzqziI/jaDSsjbjcGSmNaBWiBcoV523xofC94T3AGZapWqkWLMuAdSghw8vzclMjXtVillZf8jN+FdILZggmH5o4ympeopLnWzJnhSvdBDdUiXjc7Stpaumhvc6R6In7MfaZ5znGCZhhYAEe/M+keIQkR82LdvcjDtQelDJc/jPOEYoGpgcSFlY3fmEynari3y5vgdPaZDGAiHTcwSgRbF2n8c1x7/37Ifrl68HKrZz9ZHUjKNNwf9Qm/8+fdFsnutQSl25bii26EuoDhgOOEoozgl0imarfAyrTfpPXlC8shrDblSeFaHGkodK57c39cf2d7tXN/aB5aAEmsNbYgwQp69IrenslYtk2lA5fni1CEeoCCgGiEDYw3l46lpLb0yefe2/QlCxkhDDZcSXJayWjzc5h7fn+Gf7B7GXT9aLNaqEliNnYhhgs/9UrfVMoAt+KlgZdLjJmEpICNgFKE2Ivklh+lG7ZUyTXeG/RcCkwgQDWWSLhZIGhecx17H39Gf5J7HnQlafxaEkrqNhkiQQwL9iTgNsvjt8GmVZgQjUeFOIEBgaSEBIzplvyk0LXjyKDdZ/OMCWUfSTSWR7RYIWdrcjx6V36efg17wXP0aPlaPUpDN54i7wzf9hfhQcwAueinfpkyjlqGNILegVyFkYxGlyalxbWiyCvdv/K2CGceKjNcRmlXzmUacfd4J32MfSF6BHNraKhaKUpsNwQjkA229yDidc1Wulap+pqxj9GHmIMlg3uGf437l52l+rWSyNXcJvLdB1Qd4zHrRNlVKWRtb053kHsRfNB45nGJZwpa00ljN0kjIQ6Q+D3jzs7huwirx5yLkaqJYoXShP+Hzo4KmWOmcLa0yKLcnfECBy0ceDBGQwVUNWJnbUV1k3kwehl3Z3BOZh1ZPUknN2sjoQ5r+W3kS9Cgvf2s456+k+SLkYfnhuiJfJBxmnanKLcKyZHcJvEoBvUa6i5uQfFR818Ia9xyMnfqd/90iG67ZOJXZEi4NmkjDg9E+q3l6dGQvzGvSqFHlnyOI4pfiTSMipIwnNmoIriTyaXcxPBQBa4ZPS1nP55PZl1VaBZwb3Q/dYFyTGzQYllWSEcUNkMjZg8a+/vmpdOuwaKx+6MkmW+RFo07jOKO9pRGnomqXrlRyt/cdvB9BFoYcisyPRBNkVpPZfZsTXEzcqNvsmmPYIJU60U8NfYiqQ/r+1ToftX5w02086ZSnLqUZpB2j/CRvpeyoIas3LpFyz/dPvCvA/sWjCnTOklKeFf6YYBpz23JbmZsvGb4XV9STEQuNIMi1A+1/LfpcNdsxi+3LqrNn1yYEpQPk1uV4Jpzo9CunLxtzMbdH/DpApQVjidMOE1HHVRZXrVl92kCa85obmMOW/BPa0LrMugh6A92/SLredkFyUS6qK2So0+cFZgDlyCZWp6GpmSxnb7KzXTeGPAtAicUeyWiNR9Eg1BwWpphymXiZtxkyV/RVzZNSkBzMSYh4Q8t/pHsltvBy4q9X7Gep5GgbJxOmz2dKqLrqUK038Bdz0vfLPB8AbYSVCPWMsJAsExDVjJdSmFtYpRgz1tGVDRK6T3HLzsgwA/Y/gPuxd2czvzAT7Xtqx2lE6Hsn6+hTKadrWi3X8Mj0UngWvDYAEQRHiHsLzs9pkjUUYJYfFynXfpbhVdtUOtGSjvmLSgfhA91/3bvA+CU0ZjEc7l5sPCpB6bapHGmvqqcsdS6HcYe03DhpPBCANIP2h7nLIw5aUQqTY5TZFeSWBBX7VJKTF1DbTjSK+0dLA8CAOfwTOKk1FnIx71AtQSvQqsUqoGre6/jtYO+F8lL1cDiC/G8/2IOjBzLKbo1/j9ISFpOB1I1U9xRCk7fR40/VjWLKYoctw6AAFTyn+TL1zvMSMI9ule0wbCUr9mwgbRvunPCS8yq1zfkjvFH//cMNRqbJskxaTsyQ+tIaEySTWFM4kgxQ347BTIUJ/8aJg7tALzz+OYD2zvQ8MZqv+G5frZXtXW2zLk+v6HGuM862tXlLvLk/pML2hdaI7strjbuPUZDjkawR6RGd0NCPjI3fi5sJE0Zdw1GARz1VelL3lTUvMvExJ+/dLxYu1K8Vr9MxArLWtP53Jvn7PKU/jcKfBUNIJcp0jGAOHA9fUCSQapAzj0XOa0ywiqXIXQXqgyMAXP2s+ue4YPYp9BFyozFn8KRwWnCHMWUyavPL9fk34bpx/NY/uUIHxO1HF4l2SztMm43Ojo/O3c67De0M/Et1CaVHncVwAu+Ab/3D+765MTcrdXpz6LL+cj+x7bIGcsSz3/UNdv74pbrwPQx/qAHxBBXGRYhyCc6LUUxyzO7NBE01TEcLgQptyJpG1UTuQraAf74Z/Ba6BLhyNqp1dzRfM+YzjPPSNHC1IXZaN885srt1vUg/mgGbw72FcMcpCJtJ/sqNS0MLn0tjytUKOgjbx4WGBARlQngAS76ufK762rl9N+C2zXYI9Za1dzVpNeg2rfexeOj6R/wCPcl/kAFIQyUEmgYcR2KIZUkfiY4J8EmHyViIqEe/RmcFKkOVAjPAU/7AvUb78fpLOVu4abe6Nw+3KvcKN6m4BHkSegu7ZbyVvhB/igE3gk3DwoUNBiXGxoerB9EIOIfiR5JHDQZZxUAESMM+AaoAV78P/d28iXubOpn5yvlxeM/45njzuTR5o/p8ezb8Cv1wPl0/iIDpwfgC60P8hKYFY0XxRg3GeUY1BcPFqYTrxBDDX8JgQVqAVr9b/nI9YDyr+9p7b3rtepX6qLqkesZ7S3vuPGm9N33RPu+/i8CfgWSCFQLrw2UD/YQzhEXEtIRBRG4D/oN2QtpCb8G8QMVAUP+kPsQ+db28fRu81fysvF/8b/xa/J78+b0m/aO+Kv64fwe/1ABZgNSBQMHcAiPCVoKzQroCq0KIQpMCTUI6gZ1BeUDRwKpABj/n/1J/CH7LPpy+fT4tPiy+On4Vvny+bX6lvuN/JH9l/6W/4YAYQEgAr8COgOPA78DygOzA34DMAPNAl0C5QFqAfQAhgAmANf/mv9x/13/Xf9u/43/uP/p/xsATAB2AJQApACiAIwAYgAjANP/cf8D/4v+Ef6Z/Sr9yfx9/Er8NvxE/Hf8z/xN/e79sP6N/38AfwGFAogDfQRdBR0GtQYdB1AHSQcEB4EGwgXJBJwDQwLIADX/lv35+2r6+fix96D20PVK9Rb1OfWz9YX2q/ce+dX6xfze/hEBTwOEBZ4HjAk8C58MqA1LDoEORQ6WDXUM6gr+CL0GOASBAa7+0/sG+WD29vPd8Sfw5e4j7urtP+4i74/wf/Lj9Kz3xvoa/o0BBgVpCJsLgg4EEQ0TiRRrFagVOxUlFGwSGhA+De0JPwZQAj7+KPou9nDyDe8h7MXpDugM58vmTueV6JnqTu2f8Hf0t/hB/fEBpAY0C30PXROyFmIZVBt3HL4cJRyuGmAYSxWFESgNVggzA+b9l/hx853uQuqC5n/jUeEN4L/fbOAT4qnkHehX7DfxmfZV/D4CJwjiDUATGBhBHJgfAiJpI74j/SIpIUseehrOFWwQewooBKX9IvfT8OvqmOUG4Vrds9oq2czYn9mh28Pe8eIN6PDtbvRX+3MCjglwEOEWrxyrIasljig7KqIqvSmRJyokoR8XGrUTrAwvBXv9yfVV7lznE+Gv21vXO9Rp0vjR7dJE1e3Yz93G46XqOPJH+pEC2QrdEl4aICHsJpUr8i7oMGQxYDDgLfYpvSRcHgEX5g5HBmj9jPT56/LjuNyD1ofR7M3Ry0rLXMwDzy3Tu9iF31nn+u8n+ZkCBwwoFbMdZiUCLFExKjVqN/433zYSNKovyCmXIkwaJxFuB2z9bfPA6bHgiNiG0ePLzcdnxcXE8cXiyIbNutNQ2xDktu3694oCGA1PF98gfinmMNw2Lzu8PWs+NT0gOkI1vy7GJpMdbROiCIX9a/Ks55vdiNS7zHPG4sEvv3K+sb/owv7H0M4p18zgbuu/9mYCCg5QGeAjZS2WNTA8/kDXQ6VEXEMGQLg6mzPjKtMgthXjCbT9iPG+5bHautAnyDzBMbwwuVO4o7kYvZvCAcoV05HdJul59SwC3g4rG7ImGTEOOklBkUa5SaZKUEm9RQhAWjjtLggk/xctC/j9w/D34/bXIc3Mw0G8vrZus3CyzLN6t2C9VMUYz2Pa3uYq9N8BlA/eHFUplzRLPiRG40taT2pQCk9CSyxF9jzdMi8nRBqADE/+HPBX4mzVv8muv4e3jbHvrcysL64RslS4y8A1y0TXm+TT8n4BLBBpHscr3DdJQrxK8lC3VO1Vh1SOUB9KakGxNkQqhBzaDbn+k+/h4BPTmMbQuxGzoqy1qG2n1KjirHqza7xxxzjUX+J38QwBphDLHwYu5joGRg9PuFXLWShbwFmeVd5OtEVkOkUtvB45DzT/KO+T3+7QrMM1uOOuAqjHo1aivaPzp9iuObjQw0PRLOAX8IgAAxEFIREwsz1/SRhTMlqTXhhgs15sWmNTzUnzPS4w6SCaEL//2u5u3v3O/cDftACrr6Mnn46d8J5Ho3GqObRVwGfOBd617vb/QhEUIugxQkCyTNVWXF4KY7hkWWP1XqtXtE1aQfwyCSP8EVgAqO5z3UDNjr7QsWqnrp/bmhaZcZrjnkmmbrADvajL7dtU7Vb/ZhH7IoozkUKcT0NaM2IsZwVpsGczY7FbYlGVRKs1GCVcE/8Aku6h3LrLX7wLrySkAZzklvSURJbKmmai3azfuQrJ59n166n+bxG4I/U0n0Q8UmBdtWX2avxss2skZ3Ff1VShRzk4FSe4FLIBl+7422nKcrqQrDChrJhGkyuRbZICl8qeiKnsto7G9deb6vH9XRFNJCs2bEaQVCpg3mhmbpdwXm/DauhiClh6SqI6+ygPFm8Cte5420/Jx7hiqpGesJUFkL6N7o6Nk3mbdaYttDjEGtZJ6S/9MxG5JCo39UeXVp9irGt5cdVzr3INbhJm/FoeTeM8yipdFzQD7O4g22vIX7eCqEecD5Mija+Ky4tvkHaYpaOmsQzCWdT/52f88BD+JPM3O0lRWL1kHm4rdLR2o3X/cO1oqF2IT/o+fiyiGAAEOu/u2r3HO7bwplWazJCgigKICImqjcWVHaFZrwvAs9LB5pj7lxAcJYY4Pkq7WYNmMnB8di95NniWc3RrDGC3UeRAFC7ZGdAEnu/k2kXHWbWtpbuY6I6BiLmFpYZBi2mT3p5IrTm+LdGQ5cb6KRAUJeQ4/krWWvBn5nFpeEZ7Z3rQdaVtJWKoU55Ciy8CG6QFFvD+2gHHu7S6pHqXZI3GhtSDp4Q3iWOR7Jx4q5i8x89w5PL5pw/oJA05e0uiWwRpOXPxefd8M3yqd39v8GNXVSVE3zAaHHgGoPA82/LGX7QWpJOWQYxxhVeCDYOOh7aPSJvqqSq7hM5h4x75FA+YJAM5tksfXL9pLHQTe0B+mX0ief5wa2XEVnhFDzIfHUsHPPGd2xXHRrTAowWWgIuChEOB24FHhmWO9pmgqPO5Z81m4kz4cA4mJMY4r0tNXCBqvHTPeyB/l343eiFylGbqV5RGGTMQHhsI5/Ef3GvHbbS5o9GVIIv6g5eAEYFkhXCN9pidp/O4ccyB4X73vg2VI1g4Z0stXChq63QjfJd/LX/neudyamfKWHhH+jPpHucIoPLA3PHH1bQApPWVIYvZg1WAr4DnhNqMS5jipiy4pcu04Lb2/wzkIro34ErAW9hpuXQRfKV/Wn8ye05z6mdgWSFIsTSpH6wJZfN/3abIe7WTpHGWhIsfhHyAt4DPhKOM9pdwpqG3BMsB4PX1NQwXIu82G0oHWzBpJ3SYe0h/HX8Xe1VzFGitWY1IPDVPIGgKM/Ra3ojJXrZxpUWXRozLhA2BKYEdhcuM95dKplO3kMpp3z71YwsvIfc1GkkEWjFoNXO5eoN+d36Vevxy52etWb1ImTXYIBoLCfVP35XKfLeZpm6YaI3dhQeCBILShVSNUJhvpkO3Ssrv3pL0igouINU030e4WN9m5HF1eVV9aH2teUNyY2diWa1IxzVCIb8L5fVc4MzL1LgIqOqZ545Th2mDR4Pthj6OAZnhpnK3NMqU3vPzrAkWH4oza0YmVzllOHDNd7978XtgeClxhmbJWF5IxDWOIVYMxfZ+4SnNY7q9qbmbwZAriTKF8oRtiIiPCZqgp+K3T8pZ3mTzygjpHRoywURPVUJjMG7EdcR5EnqtdrBvUWXjV85HkDW3Id4Mp/e14qzOJ7y2q9ed9ZJli1+HA4dSijGRaputqJK4nMpA3uXy6AepHIYw5EI2U/1g0Gtbc2V3z3eXdNdtxWOwVv5GKjW/IVQNifj941HQHb7vrUKggJX8jfCJeYmZjDmTIp0HqoK5HMtK3njyBwdZG9Au1UDdUG1eGmmVcKN0J3UecqBr4mEwVe1FkTSjIbcNaflV5RbSQ8BmsPeiYJjwkOGMUYxDj56VMJ+tq7W6z8t53h/yKAb7GfwsmD5JTpNbEmZ0bYJxHnJFbw1pqV9iU5pEwzNiIQYORvq55vnTlsIYs/SlkZs9lDGQio9Lkl+Yk6GhrSi8t8zM3tvxTgWQGAsrMDx6S3NYuWL8aQVut24NbB9mG11JUQZDwjL8ID8OHfsp6PfVFMUCtjWpEZ/hl9yTIJOxlXqbS6Tfr9y90s1F367xewQcFwEpnzl1SBFVE18vZi1q82p6aNhiOlrlTjJBjTFwIGAO7Pug6QzYuMchubes26LWm9+XEZdymeyeVadostC/Ic/l35jxrwOhFeEm6DY9RXBRJVsRYgBm1maNZDpfCFc4TB8/JDC9H2oOs/wf6zjagMpxvHew7aYboDacWZuKnbSir6o6tQPCpNCr4Jvx7gIhFKwkEDTWQZRN8VamXYBhY2JLYElbh1NCScw8hy7jHloObv2h7HXcac3vv2+0QaurpN6g9Z/2oc6mV65TuHTEW9KZ4bjxOQKdEmYiGDFCPoBJfFLyWLFcn122WwdXuU8GRjw6tyziHTAOHf4l7sPeb9CXw5241a+CqdOl4aSzpjirSrKxuyPHRNSu4u/xkAEZEREgBC6HOjlFyk35U5hXjFjRVndSoUuGQm83tCq5HOsNv/6p7x7hj9Nlx/y8pLScrg+rGaq9q+2vhrZTvw3KYNbq40Ly9gCWD7Ed2CqnNsNA4EjATjlSMFOjUZ1NQkfFPmk0gChpG4sNUf8q8YPjxtZWy4nBqbnzs5CwmK8Qseq0B7s0wzDNrNhN5bDybAAXDkgblyemMiI8wUNMSZhMkE0tTH1IoELEOikxHCbzGQ4N0/+m8u/lEdplzz7G4L6DuU+2WbWntiy6yr9Tx4vQKNvX5jvz9P+eDNgYRCSJLlo3cz6gQ7tGr0d1RhtDvT2HNrMtiCNWGHUMQQAc9GHoa92P0xfLRMRIv0i8Wbt+vK2/y8StyxvU092H6OPzjv8sC2YW4yBUKnAy+zjEPadAkkGAQHs9njgSMgoqxyCTFr8LngCJ9dTq0eDP1xDQ0Mk8xXbCkcGQwmvFBso+0N7XquBc6qf0O//ECfMTeB0KJmktXTO6N2E6QDtSOqI3RzNmLS4m2h2sFOwK5wDs9kbtQeQh3CTVfs9Zy9PI/MfZyF/LeM8D1dHbrONV7Ij1/P5nCIIRBRqwIUkony2KMe4zvDTxM5QxvC2JKCUixBqhEv0JHAFD+LXvtueC4E7aS9Wb0VrPls5Sz4XRHNX42fHf1uZx7oX20v4XBxUPjhZKHRUjxSc4K1QtDi5hLVcrASh9I+8dhhd0EPIIOwGM+R/yLevs5IvfMNv81wXWWNX21djX7doZ3zvkKOqv8J73vv7VBbAMFxPcGNId1iHJJJkmOiepJu8kGyJGHpEZIhQlDssHRAHF+n/0o+5d6dTkKeF33s/cPdzA3FPe5+Bj5Kzone0O89P4wP6kBFQKow9qFIUY1RtFHsIfRiDOH2IeDxzqGA4VnBC3C4gGNwHu+9b2FfLP7SXqMOcF5bLjPuOr4/HkBOfR6UDtM/GL9SP62f6EAwQINQz4DzETyRWvF9YYOBnWGLUX4RVsE2oQ9gwsCSsFEwEF/R75fvVA8nnvP+2h66fqV+qw6qzrQO1f7/Px6PQl+I77CP93AsMF0QiKC9wNtw8OEdkRFhLGEe4Qlw/QDagLMgmEBrQD2AAI/lj73fiq9s30U/NF8qnxgPHJ8X7ylvMH9cP2ufjZ+hH9Tv9+AZEDeAUlB4sIpAlnCtMK5wqlChIKNwkcCMwGVQXDAyQChgD3/oH9L/wK+xr6Zfns+LL4tPjw+GH5AfrG+qr7o/yn/az+q/+ZAHIBLwLLAkIDlAPBA8kDrwN4AygDxAJTAtoBYAHqAH4AHgDR/5b/b/9d/17/cP+R/7z/7f8fAFAAeQCWAKQAoQCJAF0AHQDL/2j/+f6B/gf+kP0h/cL8d/xH/Db8R/x9/Nj8Wf39/cL+of+UAJUBmwKdA5EEbgUrBr8GJAdSB0UH+wZzBq8FsQSBAyUCpwAT/3P91/tK+tz4mPeM9sL1Q/UW9UD1wvWb9sf3QPn9+vD8DP9BAX4DsgXJB7IJXAu5DLkNVA6ADjsOgg1YDMUK0QiKBgAERgFx/pb7zPgq9sbztPEI8NDuGe7s7UzuO++08K3yG/Xs9wv7Y/7XAU8FsAjdC7wONREyE6IUdhWlFSoVBxRAEuIP+wyiCe0F+gHn/dL52/Uk8sru6eua6fLnAOfO5mLnuejN6o/t7fDO9Bb5pP1VAgcHkwvUD6kT8haTGXQbhRy6HA4chBolGAEVLRHFDOsHwgJ0/Sf4B/M77uvpO+ZI4y3h/d/D34bgQeLr5HDoueyl8RH30vy8AqMIWA6tE3gYkBzVHyoieiO5I+Ei9SADHh4aYhXyD/cJngMZ/Zn2UfBz6i7lruAX3YfaFtnS2L/Z2dsT31bjg+h17v707fsLAyQK/hBkFyIdCiL0Jb4oUCqcKpspVCfUIzQflxklEw8MjATW/Cb1u+3O5pfgSNsM1wfUUtL/0RLThtVK2UTeUORA6+Dy9vpDA4gLgxP2GqYhXCfqKyovATFdMTkwmi2TKUAkxx1bFjIOiwWq/NHzR+tP4yncDNYs0bDNtstRy4XMTc+W00DZI+AK6Lrw7/ljA84M5RVhHv4lgCyyMWo1hzf3N7M2wzM7Lzsp8CGRGVwQmgaV/Jry+Oj53+fX/9B8y4nHSMXNxB7GNcn7zU/UANzW5Izu2fhtA/YNIhiiISkqdDFJN3c73T1kPgU9yTnHNCIuDCbDHIwStweX/ILxzebP3NTTJcwAxpbBDL95vuO/QsN/yHPP69em4VrstvdfA/8OORq2JCIuMzapPE5B/UOeRClDpz8yOvAyGSrvH8AU4Qiv/IjwyuTR2fTPgse9wN27CblauNi5er0nw7PK6NN/3ibqhvY9A+oPKRycJ+gxujrOQelG4kmgShlJWEV3P6E3ES4RI/MWFgrd/K3v7eID10rMGMO3u2G2QrN2sgS04rf3vRPG+89j2/PnTPUFA7UQ8R1SKnY1Bj+0RkRMiE9lUNFO1kqRRDA88jEmJiUZVAsf/fHuOuFl1NjI7L7ytiixvq3RrGqugLL0uJfBKMxW2MPlCfS5AmERkB/WLMw4EkNYS1tR6lToVUtUHFB7SZhAtzUrKVMbmgx0/VTusN/70aDFALtxsjWsgKhwpxGpVq0jtEO9csha1ZnjwPJaAu8RBSEnL+Y73Ua1TylWA1olW4NZJ1UxTtZEXDkcLHkd5g3c/dXtUN7Ez6TCWLc4ro2njaNZovyjbKiIrxy53sR00nfhcvHpAV4SUSJEMcI+Y0rJU6pa0F4XYHNe8FmvUuZI3jz2LpYfNg9V/nXtGt3Czee/9bNKqjOj6J6OnTCfxKMpqya1b8Gnz2DfIfBoAbASciMqM2BBok2QV9xeS2O5ZBljdV7wVsJMOUC2MaYhhxDe/jLtDtz2y2q92rCqpiqfl5oVmbKaZJ8Ip2SxKb71zFfd0O7YAOQSaCTbNL1DmFAIW7ticmcIaW9nsGLwWmhQakNYNKcj2BF2/w3tLdthyi67Ca5ao3abm5bxlIaWT5sqo9utD7tiyl7bgO05APwSNCVVNtdFQ1MvXkRmQmsAbXFrnmarXtRTbEbaNpclJxMZAAPtddoDyTS5hKtdoBmY+ZIlka6SiZeTn46qJbjyx3nZM+yQ//gS1iWXN7BHolUBYXRptm6fcB1vO2odYgFXPUk5OXIncRTJABTt6Nndx363TKm2nRaVs4+1jS+PFpRGnICnbrWmxanX7Orb/toSTyaiOERJs1d+Y0lszXHfc25yg21DZe5Z2UtyOzYptBWCAT7thNntxgu2Yqdkm3CSy4ykigyM+ZBHmbak7rKBw/HVreke/qMSnyZ2OZRKdVmkZcFuhHTAdmJ1dHAaaJVcPU6BPeEq7xZEAoLtSNk1xt20yKVrmSeQRYr0h0eJNY6ZljGiprCIwVTUeOhZ/VQSxyYSOqBL6FpxZ9pw2XY+efd3CnOfavZeZ1BkP3AsHhgLA9ztNNm0xfOzfaTKlz2OIoioheSGzYs+lPafm668v9TST+eP/O4RyCZ5OmhMClzlaJNyynhYeyl6RHXPbAxhVFIZQeEtQBnXA03uRtloxU6zg6ODlrSMY4bBg+SEw4k5kgaezqwfvnPRNObC+3MRoiapOuxM3Fz+aexzVnoMffd7HneobtViAFSdQjEvUxqlBNHuftlTxeyy2aKWlY2LCoVBgkmDGYiNkGScQqu1vDTQKuXz+uUQWCalOixNXl2+auJ0fHtYfl99mHgncE9ka1XtQ14wVBt0BWjv2tlxxc2yfqIElceKGIQqgRSC0YY7jxKb+ql/uxrPMuQl+kYQ6yVsOilNkV0ja3d1O3w7f19+rnlLcXllkVYIRWUxQhxCBhDwWNrDxfGydKLMlGSKjIN7gEiB7IVFjhKa9qh/uiXOT+NZ+ZYPXCUBOuVMdF0va6l1kny1f/d+YHoTck9mcVfrRUYyGh0MB8fw99pGxlWzt6LtlGKKaYM2gOSAbYWtjWWZOqi4uVnNguKR+NgOrSRmOWBMCl3hanp1gnzFfyd/rXp8ctJmCViVRv4y2x3RB4vxttv6xvqzSaNolcOKrINbgOmAUoVzjQ2ZxqcrubbMzuHP9w4O4COaOJxLUlw6aul0DHxrf+1+lXqGcv9mWFgFR4szgx6PCFvykdzdx920JqQ6loOLVoTqgFiBnYWZjQuZnKfauD/MNOEW9zoN9iKhN5tKT1s9afhzLnuofkl+F3oxctVmXVg4R+wzDx9ECTTzid3syP21TqVil6SMZoXhgTCCT4YejmCZvafGuPXLteBm9l0M8iF9Nl5JAlrqZ6ly7Hl8fT19Mnl8cVVmFlgtRx80fx/uCRT0md4lyle3v6bfmCKO24ZBg3CDZocDjwyaKqjvuNnLVODC9XoL1iAuNedHblhDZvxwRnjoe8l76XdncH5lg1flRiM00B+LCvr0wd+Iy+m4d6ivmv2Ps4gIhRiF4ohHkA6b4qhXue3LE+Ar9ZIKox+5MzlGk1ZKZPNuPXbvee55O3bzbk9kpFZdRvczAiAbC+P1/+AQzbK6c6rQnDKS7IozhyaHworrkWic6Kn/uTLM8d+k9KgJXB4eMlZEdlQCYpJs1HORd613KXQgbcpieVWVRZkzEyCaC872T+K8zq+8saw+n7+UhI3DiZiJBY3tkxmeOavnuqjM8d8t9L0IAx1hMEFCGFJuX9ppDnHRdAl1tXHvau9gAlSNRAozAiAIDLj3sOOK0Ny+Lq/4oaGXeJCzjG6MqY9Llh+g16wPvFDNFODJ89MHmhuDLvw/fU+PXM5m7G2xcQNy4W5jaL5ePlJFQ0kyzR9iDKD4H+V30jjB57H7pNaaxpMCkKOPrZIFmXqiwK53vSvOW+B48+0GJBqILIo9p0xqWXJjcmo0bp5urmt8ZTlcL1C9QVQxdB+oDIT5m+aA1L/D2bRCqFmea5eskzeTDpYZnCil9LAevznPxuA98wwGoxhyKu86mUkCVshfo2Zeat1qIGg8YmJZ1032Py0w9h7ZDGL6Ieii1m7GAbjLqymiY5uulyWXyZmEnyiocbMFwXrQV+EY8zIFGhdEKCw4WEZZUtVbgmIwZsNmOWSnXjpWNUvwPdIuUx7yDDj7runb2ELJXLuSr0Cmq58GnGqb251Eo3irNrYqw+7RDeIK82AEihUBJkc15UJ0TptXFF6wYVNi/F++WsNSTEisO0UtiR3zDAX8QOso2zjM5b6Ts5uqPqSuoASgQqJVpxWvQrmNxZTT6uIW85kD9hOrI0EyRj9XSiBTXVnhXJFdbFuEVgBPHkUrOYYrmhzbDMb81eyG3U3PmcLLtzavGamjpe2k+aa2q/2yk7wsyGzV7eM6894CYBJGIR4vfjsGRmZOYFTGV4JYjlb9UfRKrEFvNpUphBupDHv9a+7y333SdcY1vAy0N67hqiKq/qtjsC23JsAFy3bXFuV58zACyhDUHuIrkDeEQXRJIk9mUihTZVEsTaFG+T15M3MnSBpdDCH+APBp4sTVdMrNwBq5k7NjsJ+vS7FXtaK7+MMYzrDZZebT85IBNw9YHJAogTPXPExEqEnETIlN9EsVSAtCBzpLMCIl5hj1C7j+kfHp5CDZks6OxVq+Krkktl+13baQulnACMhh0Rjc2udJ9AMBqA3VGSslVS8DOPU+90PlRqpHQka8QjU92jXnLKIiXhdyCz3/HPNu543cy9J1ysfD9L4gvF27rrwIwE3FUszf1K/edOna9IYAIQxOF7ghDysMM3M5FD7OQI9BUkAlPSI4dDFPKfYfsRXTCrH/oPT26QbgHNd7z13J78RQwpTBu8K8xXzK09CP2HHhMuuH9RwAogrFFDketCb3LcozBDiFOj07KjpVN9gy2CyHJR4d4RMYChEAGvZ/7IrjgNue1BfPE8uxyP7H/siny+HPiNVv3F7kFe1Q9sb/LQk+ErIaSCLIKAEuzDEPNLs0zTNQMVotCyiQIR0a7RFBCV4AifcF7xTn89/X2e/UXdE7z5fOcs/E0XjVbdp84HPnGu8194T/xQe6DyYX0B2FIxsocitxLQ0uQy0cK6wnECNuHfUW1w9OCJYA6viF8aDqcOQj3+Daxtfq1VjVEtYP2Dzbft+y5K7qQPE1+Fb/awY9DZkTThkyHh8i+ySyJjknjya9JNMh6h0kGacToQ1AB7gAPfr+8yzu9Oh85OXgSd643D3c2NyB3ijht+QP6QzuhvNR+T//IAXKCg8QyRTTGBIcbh7XH0UguR85HtMbnhi1FDgQSwsXBsUAf/ts9rTxe+3e6fnm4OSf4z/jvuMW5TnnFeqP7Yzx6/WH+j3/5gNhCIoMQxBvE/kVzxflGDcZxRiVF7MVMRMkEKgM2AjUBLsAsPzO+DX1//FE7xftheua6ljqvurI62ntku8v8iv1bPjX+1L/vwIGBg4JwAsJDtkPJBHkERUSuRHWEHYPpQ12C/sISQZ3A5sAzf0h+6v4f/ap9DjzNPKh8YLx1PGR8rLzKvXr9uX4CPtB/X3/qwG8A54FRQemCLcJdArYCuQKnAoDCiEJAQiuBjQFoQMCAmQA1/5j/RT89PoJ+lj55fiw+Lf4+Pht+RD62Pq++7j8vP3C/r//rACDAT0C1gJLA5oDwwPIA6wDcgMgA7sCSQLQAVYB4QB1ABcAy/+S/23/XP9f/3L/lP/A//L/JABUAHwAmAClAJ8AhgBZABcAxP9g/+/+d/79/Yb9Gf27/HL8Rfw2/Er8g/zh/GX9Df7T/rT/qQCrAbECsgOkBH8FOQbKBioHUwdBB/IGZQacBZoEZQMGAoYA8P5R/bX7Kvq/+ID3efa09Tz1FvVH9dD1sfbk92P5JPsc/Tv/cQGuA+AF9AfYCX0L0gzKDVwOfw4wDm0NOwyfCqMIVgbHAwoBNP5a+5L49PWW843x6e+87hDu7u1b7lXv2fDd8lT1LPhR+6z+IQKZBfYIHQz1DmQRVxO6FIEVoRUZFecTExKpD7gMVgmbBaQBj/17+Yn12PGH7rLrcOnW5/Tm0+Z3597oAevR7TvxJvV1+Qf+ugJqB/ELKxD1EzEXwxmTG5IctBz2G1oa6he1FNQQYgx/B1ICAv24953y2u2W6fTlEuMK4e7fyt+h4HHiLuXE6BztFPKJ90/9OwMgCc4OGRTWGN4cECBQIoojsiPCIsAguR3BGfQUdw9zCRQDjvwQ9s/v/OnG5Fjg1txe2gXZ2tjg2RPcZN+84/vo++6P9YT8pAO5CowR5heUHWgiOybsKGMqkyp3KRUnfCPGHhUZkxJzC+kDMfyF9CLtQuYc4OLav9bV0z7SCNI508nVqdm73tzk3euJ86b79QM2DCgUjRsqIsknPCxgLxcxUzEPMFItLSnAIzIdsxV9Dc8E7PsX85fqruKb25jV1NB3zZ7LW8uxzJrPAtTI2cLgveh68bj6LgSUDaEWDR+VJv0sETKnNaE37TeFNnIzyS6rKEch0xiRD8YFv/vI8THoQ99H13zQGMtIxyzF18RPxovJdM7m1LLcneVj77n5TwTUDvUYYiLRKgAysze8O/o9WT7SPG85STSDLVEl8RuqEcsGqfuY8PDlBNwj05PLkMVNwe2+g74YwKDDA8ka0K/YguJH7a34WQT0DyIbiiXdLs42Hj2bQR9Ek0TyQkY/qDlCMkwpCR/IE98HqvuI79fj89gxz+DGQsCMu+W4ZbgRuuC9tsNpy73Ubt8p65P3TQT1ECcdhCizMmM7T0I+RwhKlUrfSO9E4j7lNjQtGCLnFf4IwvuX7ubhEdZ2y2jCMLsIthqzgLJAtE+4kb7WxuHQZdwK6W/2KwTVEQMfTStTNr0/QEehTLNPW1CTTmZK8kNmOwUxGyUFGCgK7vvG7R7gYdPzxy6+YLbHsJKt2qyprvOymLlnwh3Nadnt5kD18wOWErYg5C25OddD70u/URlV31ULVKZP00jDP7o0DiggGloLMPwV7YHe5NCrxDW61LHNq0+oeadSqc+t0LQfvnbJf9bV5Ar0qAM3Ez4iRjDiPK9HV1CVVjZaHVtAWatUgE31Q1I47yo1HJMMhPyE7A7dnc6gwX+2ka0dp1ejYKI/pOqoPrADuu/FqNPE4s/ySgO5E5sjczLOP0JLdVQeWwdfEGAvXnBZ9lH6R8c7ui1BHtEN7PwR7Mfbi8zUvg+zmKm7oq6elJ12n0ek5asWto3C6dC94I/x2gIcFM0kajR6Qo5OR1hXX4djtGTTYvBdMFbNSxY/bDBCIBIPZP2+66var8pJvOiv7qWrnliaGZn5muufy6deslK/Rc7D3k3wWgJhFNMlKTbkRJBRyFs9Y7NnBWkoZydiKVpqTztCAjM1IlQQ6/2I67rZDMkAugytlqLwmliW85TNltmb86PdrkO8vsvY3AzvywGIFK4msTcMR0ZU+F7NZodrAG0qaxJm313NUjNFeTUXJJURgf5w6/XYoMf6t3yqkJ+Ml7GSJZH2kheYYaCXq2K5WMn+2sztLwGSFF4nADnwSK9W02EEagBvoHDVbqxpTGH0VftHzTfnJdISJP9z61rYbcY4tjqo35yDlGaPs413j6aUGZ2QqLS2Fsc52ZHshwCBFOMnFzqPSspYWGTfbBty43MncvNsb2TbWJBK/TmhJwoU0v+S6+rXcsW7tEemhprWkXuMn4pTjIqRHZrLpTq0+sSL113r1f9VFD4o9jrpS5VahWZdb9d0xnYcdeNvQ2d+W+5MBDxDKTsViADL66TXsMSDs6SkhZiHj/CJ7YeOiceOcpdLo/ixCMP21TDqGv8PFHAonDv+TA9cWWh8cTB3R3mxd3hyxWnaXRJP4T3KKmIWRgEc7IfXJsSRslKj3paYjcmHnoUph1+MGZUTofKvQsF91A/pWP6yE3koCjzOTTld02k7cyV5ZHvkebJ09GvtX/tQkD80LH0XCwKF7JHX08PksVGikZUKjAaGtIMnhVWKFZMmnyiuqr8i0/vnkv0/E1soQjxYThJe82qYdLV6Gn20e412zG21YaVSEEF/LYoY0wID7cLXt8N8saGhoJTeiqqEMoKLg6qIaZGFnZ+sQ77n0fXmyPy2EhcoQzyeTplet2uTdd57aX4dfQd4S28uYw1UXkKpLocZnQOV7RnY0MNYsUKhCZQVirSDF4FUgmGHF5AznFirD73P0AHm/fsbEq4nDzygTtBeIWwrdqB8Tn8gfh55cHBXZDNVd0OvL3MaaAQ67pTYHsR4sTOhzZOuiSaDZoCFgXuGII8zm1SqELzczx/lNPtuESInqDtfTrZeL2xgdvt8y3+7ftN5OHEvZRNWW0SPMEobMAXv7jHZn8TasXSh65Oqif+CH4AfgfmFho6EmpepSLsPz1LkbPqxEHUmDjvcTU5e5Gszdu183X/tfiJ6pHGzZa1WBkVIMQsc9gWz7+7ZUsV+sgOiZJQIikCDQYAigdyFSo4qmiGpubprzp3jqvnmD6clQzoZTZhdP2uldXl8hn+1fg16sXHjZf9WeEXXMbUctQaE8MvaNMZgs+CiNZXHiuiDzYCOgSSGbI4lmvSoZbrxzQDj7vgQD7wkSTkXTJVcQmq1dJ57xX4VfpJ5X3G+ZQdXr0U8MkUdbQdf8cTbRceBtAmkXZbmi/aEwoFjgtKG7Y51mhCpTLqizX3iOvgwDrUjIjjYSkdb72hnc116nH0MfbF4rnBCZcZWqkV0MrodHAhE8tncgsjdtXul2pdkjWqGIIOgg+WHzo8cm3epcLqBzRfikfdHDZQi0DZfSbFZR2e6cbd4C3ybe2x3nm9wZDlWZ0V/MhIewAgv8wbe6clztzWnrJk/j0CI5IREhV2JDZEZnCqq0bqOzc7h8/ZZDFshVTWtR9NXTWWxb692E3rDecJ1MG5IY2FV50RaMkseVwkg9Erfd8tBuTWpz5t1kXmKDodPhzmLq5JsnSercbvKzaThY/ZnCw0gtDPERbJVAmNObUd0t3eGd7RzY2zKYT5UKEQGMmUe3wkT9aLgKs1Du3erQJ4ElBGNnIm/iXeNp5QVn3CsT7w2zprh4/VyCqse7zGoQ09TamCUaoBx+XTldEVxOWr2X89SKkOBMV8eVwoI9g3iAc94vfqt/qDplgaQi4yRjBaQ/5YToQWubb3UzrLhc/V+CTgdCDBcQa1Qh12GZ11u2nHicXZus2fOXRVR7UHLMDYevgr89ofj99Dcv7qwBqQgmlWT2I/DjxWTspllo+Ovyb6jz+zhFvWLCLcbAi7hPtBNXFomZOJqXm6Abklr02RSWxFPcUDjL+odEQvt9w/lC9NtwrWzU6eonfyWgpNTk3CWvpwKpgyyZcCj0EnizfSdByka4Ss7PLpK7VZ4YBFniGrDasFnnGGFWMRMtj7KLnodUAvZ+KLmOtUnxea246p7ofaahJc+lyWaIaAAqX60PsLW0cvimfS0BpEYpiltOW5HPVN/XO9iW2arZt9jDl5nVS9Kvjx+LecceQu++T7ogNcHyEq6sq6YpUCf25uBmzKe2KNFrDa3VcQ603Hje/TSBfIWVCd7NvFDUE9AWH5e22E+YqhfLVr7UVNHiDoBLC4ciwuc+uDp3NkLy969vLL5qdejg6AXoJOi4afXrzW6qcbQ1DzkdPT5BE0V7yRoM0dAKku+U8NZC11/XR5b/FVETjJEFzhSKlAbhgtv+4frStwuzp/B/baarrWoeaX+pESnOay0s3i9OMmX1i3lh/QsBKUTeSI2MHI8z0b+TsJU8FdyWEZWflFDSs5AazVzKE0aZws2/C/tx95t0YfFcrt4s9etuKoxqkOs3bDYt/zAAcyO2EPmsvRrA/0R9h/qLHY4QkIESoBPj1IbUyJRtkz8RSo9hjJkJiUZLwvx/NfuUeHF1JTJFcCOuDizO7Crr4qxyLVBvMDEAs+12n7n9/S3AlUQZx2HKVk0ij3URAFK60x+TbhLqUdyQUc5aS8mJNcX3Aqd/X3w4+My2MHN4sTWvdS4/rVptRa397rrwMDIOdIK3d7oV/UTArIO0BoRJh0wqTh0P0tEC0ehRwtGWUKpPCo1Fyy6IWUWbwo4/h7yfeax2wvS1clNw6S++7tlu+K8ZsDSxfvMpdWM32Lq0fWAARUNNRiLIscrpTPnOWE+8kCIQSFAzDykN9QwkygjH84U5wnD/rfzGuk932zW6c7tyKXELsKawerCEcb0ymzRQtk64grsZ/b+AH8LlxX4Hlwngi41NEo4pjo4O/45BTdmMkgs3SRgHBQTRAk8/0n1uOvV4uHaGtSyztDKkcgDyCfJ8stM0BDWD90R5dbtGPePAPMJ+RJdG94iRSlgLgwyLTS3NKczCjH1LIwn+iB1GTgRhQih/8/2Ve5z5mbfYtmV1CHRH8+bzpbPBtLW1eTaCOEQ6MPv5fc0AHIIXxC8F1Me8iNvKKorjC0KLiIt3ypUJ6Ei6xxiFjoPqwfy/0n47PAV6vbjvt6S2pLX0dVb1TDWR9iM2+TfK+U169HxzPjv/wAHyg0aFL8Zjx5nIislySY3J3QmiSSJIYwdtRgrExsNtgYtALT5ffO37Y3oJ+Sk4B3eo9w/3PHcsN5s4Q3ldOl97v/zz/m9/5wFPgt6ECYVIRlNHJUe6h9DIKIfDh6XG1EYWhTSD94KpgVTABD7BPZV8SftmenF5r3kj+NB49LjPOVv51nq4O3m8Uv26/qi/0gEvQjeDIwQrBMnFu0X9Bg1GbMYcxeDFfUS3g9ZDIQIfQRkAFv8fvjs9MDxEO/v7Gvrjupa6s/q5euS7cXvbPJu9bT4Ifyc/wcDSgZLCfULNA75DzkR7RETEqsRvRBTD3oNRAvDCA4GOgNeAJP96vp6+FT2h/Qe8yPymvGE8eDxpvLO8031E/cR+Tf7cP2t/9kB5gPEBWUHwAjKCX8K3AriCpIK8wkMCecHkAYTBX8D3wFCALf+Rv36+976+PlM+d74rvi6+AD5efkf+uv60vvO/NL91/7U/78AlAFLAuECUwOeA8UDxwOoA2wDGQOyAj8CxgFMAdcAbQAQAMb/jv9r/1z/YP91/5f/xP/2/ygAVwB/AJoApQCeAIMAVAARALz/V//l/m3+8/18/RD9tPxt/EL8NvxN/In86/xy/Rz+5f7I/74AwQHGAscDuASQBUcG1AYvB1QHPQfpBlcGiAWCBEoD5wFkAM7+Lv2T+wv6ovhn92X2p/U29Rf1T/Xg9cf2AfiG+Uz7SP1p/6AB3QMNBh4I/gmcC+oM2g1jDn0OJA5YDRwMeAp1CCIGjgPOAPf9HftY+L/1Z/Nl8cvvqO4I7vLtau5x7//wDfON9Wz4l/v1/msC4gU8CV0MLQ+TEXoT0RSKFZ0VBRXGE+URbw90DAkJSAVOATj9Jfk49Y7xRu5860fpvOfq5tnmjucF6TfrFO6K8X711Plr/h8DzAdODIAQQBRvF/EZsRudHK0c3BsuGqwXaRR6EP0LEwfiAZH8SPcz8nrtQumv5d/i6eDi39Lfv+Cj4nLlGumA7YXyAfjN/boDnAlED4QUNBkrHUogdSKYI6gjoiKJIG0dYhmGFPwO7giKAgL8h/VO74bpYOQE4JfcNtr22OTYBNpP3LffI+R06YPvIPYb/TwETgsZEmYYBB7EIn8mFyl0KogqUSnUJiIjVR6RGAES1QpFA4z74/OJ7Lflo99/2nXWptMs0hTSYtMQ1graNN9q5XvsM/RX/KYE4wzMFCMcrCI0KI0ski8rMUcx4y8HLcYoPyOaHAoVyAwSBC77XvLn6Q7iENsl1X7QQM2Jy2jL4Mzqz3DUUtpk4XDpO/KA+/gEWg5cF7cfKSd3LWwy4TW4N983UzYdM1QuGSicIBUYxA7xBOn69/Br54/eqtb6z7fKCscTxeXEg8bjye/OgNVm3WbmO/Ca+jEFsQ/GGSEjeCuIMho4/jsVPks+nDwSOccz4SyUJB4bxxDfBbv6sO8U5TvbdNICyyTFCMHQvpK+UMABxIvJw9B22WDjNu6k+VMF6BAIHF0mlC9lN5A95EE9RIVEt0LgPhs5kjF9KCIezxLcBqX6ie7l4hbYcc5Cxsq/P7vFuHO4TrpJvknEIcyV1V/gLOyh+F0F/xEjHmopfDMJPMxCj0cqSodKoEiCREo+JjZULB0h2RTlB6f6gu3g4CLVpcq7wa66tLX3so6ygLTAuC6/nMfJ0WndIuqS91AF9RITIEYsLDdxQMlH+UzYT01QUU7ySU9DmjoUMA4k4xb6CL76newE31/SEcdzvdK1a7Bqreis7a5qsz+6OcMVzn/aGOh49i4FyhPaIe8uojqYRIJMH1JDVdJVxlMsTyZI6T67M/Am6xgYCuv61+tT3dHPucNsuTyxaasjqIanmKlNroG1/r59yqXXEuZV9fYEfxR1I2Mx3D1+SPRQ/FZlWhBb+VgrVMtMEENEN8Ep7ho/Cy37M+vO23jNn8Cqte6ssqYno2yiiKRtqfew7boEx9/UE+Qs9KsEExXjJKAz1kAdTB1VjVs6XwVg5V3qWDlRCkesOn0s6hxrDIL7r+p22lbLxb0tsuyoSaJ6np+dwJ/PpKesC7euwy7SHOL98k0EiBUmJqc1kEN1T/hYzV++Y6pkiGJmXWtV00ruPSEv2x6cDen7SupJ2WvJLLv7rjilMZ4fmiKZRJt3oJOoXLN/wJfPMeDL8d0D3RU8J3U3CEaDUoNcumPuZ/1o22aZYV5ZZ04JQaoxwCDODmH8BepJ2LnH1bgTrNahb5oalvqUGpdpnMKk5K96vR3NU96Y8F0DExYmKAs5PEhEVbxfUWfGa/ls3WqBZQ1dw1H3QxU0lSIBEOj83ul210DGw7Z4qceeBZdvkiuRQ5OpmDWhpqyjusLKhtxm788CKxbkKGc6LEq4V6BijmpEb5twiG4YaXZg41S2Rl82WSQyEX791OnO1gHF9rQspw+c9ZMgj7eNxI87lfGdpan9t4rIzNo37jMCJhZ1KYk71kvcWS1lcG1kcuBz2XFdbJRjw1dDSYU4CSZfEiD+5+lS1vvDb7Mwpa6ZQpExjKGKoIwhkvma5qaKtXfGKNkN7YsBBRbbKXM8Ok2wW2Fn9G8jdcZ2z3RLb2VmYVqaS4Q6oieFE8z+FeoC1i7DLrKFo6aX7o6iieyH2olfj1GYaqRPs4zEm9fq69oAyhUXKiI9WE4yXTxpGHKAd0l5ZXfgceVouVy6TVo8ISmkFIL/Xerb1ZvCM7EroviV+ox3h5qFdYf4jPqVNqJNscvCKdbR6iAAdRUpKpk9ME9jXr1q3HN5eWh7mXkZdBJryV6eTwQ+hSq4FT4Avure1UHCf7AjoaaUZ4uwha6DcoXtiveTSqCHrzjB1NTC6WL/CRUSKtg9wU9CX+FrPnUNeyF9anv0delsj2BEUYA/zCvAFgABNusJ1h7CEbBuoK6TN4pQhCmC04NCiUySq54ArtS/ndPB6J3+hhTTKd89DFDOX6tsPXY6fHJ+1nxvd2huB2KrUstA8iy5F8YBw+ta1jLC6K8KoBOTaYlXgwyBm4L4h/mQWp26rKK+iNLQ59b97xNvKa89ElAJYBht2Hb/fFt/2n2IeI5vMWPQU+NB9i2iGI0CZOzR1nzCBLD3n9SS/4jFgliAyoEQhwGQWZy3q6S9ltHw5g/9RBPmKEs91U/0XyptEXdcfdp/d34/eVhwCWSxVMdC1i54GVUDGO1s1/vCY7A2oO+S+Iicgg6AYYGMhmWPqZv4qty8ydAk5kj8iBI6KLI8VE+NX+Fs53ZSfe9/rH6RecZwj2RMVXRDjy86GhoE2+0p2K3DBbHDoGWTU4nbgi6AYYFshiePTZuAqku8I9Bt5YX7vRFsJ+g7kk7YXj5sWnbffJt/d35+edZwwmShVehDITDmGtsEre4G2Y/E6LGfoTWUEYqAg7eAyoGxhkaPRJtQqvO7pc/N5Mb65RCAJu06j03WXUJrbHUGfNx+2n0GeYhwoGStVSNEiTB5G5YFi+8C2qLFCbPIol2VL4uNhKqBnIJch8OPkJtoqta7U89G5A/6ARB2JcQ5T0yHXO9pHnTHerV91HwpeNtvKmRxVSNExzDzG0oGdPAa2+LGaLQ8pNuWrIz/hQWD1oNriJ+QMpzJqvS7K8/a42D5FA9QJG4400rvWkZocnIjeSZ8ZnvodtBuXWPqVOdD2DBRHPQGZvFM3E3IAbb4pa6YiI7Vh8iEeIXeidmRKZ11q068Mc+K47v4Hw4RI+42HEkPWUpmaHAcdzF6kXlCdWdtPGIZVG5DuzCTHJIHXfKX3eHJ1Lf8p9Oav5ANivCGf4e2i3GTdZ5rrOa8Zc9Y4yP4JQ28IUc1L0fpVv1jBG6zdNd3V3c6c6BrxWD+UrdCcDC2HCQIWvP33pvL3LlDqkidT5OljHuJ64nvjWeVF6Csrbu9yM9E45n3JwxRIHozDEWBVGFhSGvscRp1unTQcHxp+V6YUcNB9S+6HKcIWPRr4HrNGLzLrAqgNpaaj2mMuoyJkLiXDaI3r86+WtBQ4x73KAvUHooxuELZUXleN2jJbv1xu3EGbv5m2VzoT5FASy+dHBkJWPXw4XrPhL6SrxajcJnqkrWP6Y+Ck2OaVqQLsR/AHdF+47T2KQpIHXovNED0Tklb1GRNa4JuXG7faiZkZ1rvTSE/cC5eHHoJVfaE45nRH8GUsmmm+5ySll6TdpPYlmid8aYps67BENLO4132LQmtG00thD3WS9RXImF7Z61qompcZ/Zgo1etS3M9ZC39G8cJUPcl5dTT5MPOtQCq06COml+XXZeHmsKg3amOtXrDNNNA5Br2NQgHGgUrqzqBSB1UJV1WY4BmjmaAY3BdkFQkSYk7KCx5GwAKRfjP5ijW0MY8udat9aTanrabnJuOnnGkF606uIPFidTW5Oz1QwdYGKUorDf6RChQ4FjiXgBiJGJPX5hZL1FVRmI5uirRGiMKM/mC6JPY4MncvOmxW6l0o16gMKDponKonrAsu8jHDtaQ5dT1WQajFjEmizREQflLWFQkWjFdaF3LWnBVg01CQwA3HSkFGi8KGPo66hDbEc2owDO2A65WqFSlFKWUp8Gsb7RgvkfKxNdu5tP1eQXpFKsjSzFiPZNHkU8gVRVYXlj5VftQjkntP2Q0TycVGSQK8/r0657dX9CdxLK66LJ8rZOqQ6qNrFuxh7jWwf/Mqdlx5+v1pQQuExUh7y1aOf1CkErZT7NSCVPbUD1MVEVYPJAxUyUAGAAKwfuw7TrgyNO4yGC/Brjhshewu6/OsT2247yKxe7PvduY6Bv23QNzEXQefCouNTk+WEVWSg9Nb013SzlH1kCEOIUuKCPHFsMJgvxp7+DiRtf0zDnEV72BuNu1drVUt2K7gMF7yRTT/t3j6WX2IwO7D8ob9CbjMEw57j+aRCxHlEfRRfNBGjx3NEYr0SBqFWwJNP0g8Y3l1tpN0TnJ18JXvtq7cLsavcjAW8amzW3Wa+BR68r2eQIIDhoZWyN9LDs0WTqrPhJBfUHtP288IjcxMNQnTh7qE/oI1f3Q8j/odt6+1VrOgchexA/Co8Ebw2nGb8sG0vfZBOPj7Ej34AFbDGcWth8BKAovnDSOOMQ6LzvPObI28jG2KzIkoRtHEm8IZf549PPqIeJE2pnTUM6QynXIC8hTyUDMutCa1rHdxeWX7uH3WgG4CrMTBhxyI78pvS5IMkg0sDR+M8EwjiwKJ2IgyxiCEMgH4/4W9qbt1OXb3u/YPtTo0AXPoc68z0rSNtZd25bhruht8JX45gAgCQIRURjVHl0kwSjgK6QtBC7/LJ8q+yYwImcczxWcDgcHTf+o91Xwiul941reRtpg17vVYdVR1oLY39tM4KXlvetk8mT5hgCUB1YOmhQvGuserSJZJd4mMidWJlMkPSEtHUUYrxKWDCsGov8t+f3yQu0n6NPjZODz3ZDcRNwM3eHeseFk5drp7+559E36OwAXBrML4xCCFW0Zhxy7HvsfPyCJH+IdWBsDGP8TbA9xCjUF4/+i+pz19vDV7Fbpkeab5IDjRePo42Plp+ef6jHuQfKs9k/7BQCqBBkJMg3UEOcTVBYLGAEZMhmfGFAXUhW3EpcPCgwvCCYEDQAG/C/4pfSC8d3uyexT64PqXerg6gPsvO3676nysvX8+Gz85v9OA40GiAkpDF8OGRBOEfYRDxKcEaQQMA9ODRELiwjTBf0CIgBY/bT6Sfgq9mX0BfMT8pTxiPHs8bvy6/Nw9Tz3Pvlm+6D93P8GAhAE6QWFB9kI3QmKCuAK3gqHCuIJ9QjMB3IG8gRcA7wBIQCX/ij94fvJ+uf5QfnY+K34vvgI+YX5L/r9+uf74/zo/e3+6P/SAKQBWQLsAloDowPGA8YDpANmAxEDqQI1ArwBQgHOAGQACQDA/4r/af9b/2H/d/+b/8j/+v8sAFsAgQCbAKUAnQCAAE8ACgC0/07/3P5j/un9c/0I/a38afxA/Df8UfyQ/PX8f/0s/vf+3P/TANYB3ALcA8sEoQVUBt0GNQdUBzkH3wZIBnUFagQuA8gBQwCr/gv9cvvr+Yb4UPdT9pv1MPUY9Vj18PXe9h/4qvl1+3T9mP/QAQ0EOwZICCMKuwsCDeoNaQ56DhcOQg39C1AKRgjtBVUDkgC6/eH6H/iK9TnzP/Gu75buAO727Xvuje8n8T/zx/Wt+N37Pv+2AisGgQmdDGQPwBGcE+YUkhWWFfEUpBO2ETQPLwy8CPUE9wDg/ND45vRD8QXuR+sg6aPn4ebg5qXnLelu61nu2vHX9TT6z/6DAy8IqwzVEIoUqxceGs0bpxykHMAbABpuFxsUIBCYC6cGcQEf/Nn2yvEa7e/oa+Ws4srg19/c397g1uK45XHp5u328nv4S/44BBcKuA/uFJAZdh2CIJcipCOdI38iUSAfHQIZFRR/DmgI/wF3+//0ze4S6frjsd9Z3BDa6djw2CnajdwM4I3k7+kL8LL2sv3UBOMLpRLlGHIeHiPCJkApgip7KigpkCbGIuMdDBhtETcKoQLn+kPz8ust5SzfHtos1nnTHNIi0o7TWNZt2q/f+eUa7d30B/1YBZANbxW3HCwjnCjaLMMvPDE4MbQvuSxcKLsiARxgFBIMVQNw+qXxOelw4YbatdQq0A3Nd8t3yxLNPNDh1N7aB+Im6v3ySvzCBR4PFRhgILsn7i3FMhg2zDfPNx82xjLdLYUn8B9VF/YNHAQS+ibwpubc3Q7We89Yys/G/sT2xLrGP8ptzxzWHN4x5xTxe/sTBo0QlRrdIxwsDjN+OD08LD45PmI8sjhDMz0s1CNJGuMP8gTN+cjuOeR12sfRdcq6xMbAuL6kvozAZsQVym/RPto/5CXvnPpMBtsR7hwuJ0ow+jf/PSpCV0RyRHlCeD6LON4wqyc4HdUR2AWh+Yvt9eE817PNpsVWv/W6qbiFuI66tr7fxNvMb9ZS4THtr/ltBggTHR9OKkM0rDxGQ9xHSEp0Sl5IEUSuPWQ1cSshIMoTzAaM+W7s29801NbJEsEuumO117KhssS0NLnPv2XItNJv3jvrtfh2BhMUIiE8LQM4IUFNSE5N+k86UAtOekmpQso5IS//IsEVzAeO+XTr7N1g0TLGvLxItROwRq37rDWv5bPruhDEEM+X20XpsPdoBv0U/CL3L4k7VkURTXtSaFW/VXxTrU52Rw0+uDLQJbUX1win+ZvqKNzAzsvCqLiosAqr/KeYp+Opz642tuG/hsvO2FHnofZFBsUVqSR8MtI+SUmOUV9Xjlr/WqxYplMSTChCMzaQKKYZ6gnV+ePpkdpWzKK/2LRQrEum/KJ9otak9am1sdu7G8gX1mPlifUMBmwWKibLNNtB9UzAVfdbZ1/0X5ddYFh3UBZGjTk8K5EbBQsY+k3pJ9kjyrm8ULFEqNuhSp6vnRCgXKVsrQS408R2033jbPS/BfIWfifhNqNEWVClWT5g8GOaZDdi11yiVNVJxDzSLXMdJQxu+tfo6tcqyBK6Ea6HpL2d7JkxmZabCKFgqV+0sMHt0KDhSvNgBVcXpCi+OChHclM5XTJkJGjuaIlmBmGOWGBN0z9OMEkfSA3W+oLo29Zpxq+3HqsbofSZ45UIlWyX/pyVpe+wtb5/ztHfJvLvBJwXnClhOmlJPlZ7YM9nAGzsbIpq6mQ3XLRQt0KtMhIhbQ5P+03o+dXjxJG1eagEnoSWM5I3kZaTQpkOormt6LsvzBDeAfFuBMMXZyrKO2RLvFhnYxNrgm+QcDRuf2ibX8xTbUXtNMoikQ/Y+zboRdWXw7izJKZDm26T4I7AjRiQ1pXPnr+qSrkAymHc3u/fA8oXBSv4PBlN6Vr8ZfptpXLXc4ZxwWu1YqZW8kcJN28kshBu/D3ovdSGwieyHqTbmLWQ7YupivSMvpLbmwWo37b2x8bav+5CA7UXdivsPYdOxlw4aIRwaXW/dnt0rm6CZT9ZQ0oBOf8lzxEQ/WDoYtSwwd2wa6LMlluOWonyhy2K/Y81mY6lqbQSxkLZpe2bAoQXuyulPq5PUF4aaq5yyndFeRJ3QnEAaJNbXEzQOnYn5RK9/Z/oMtQUwdqvCqEYlWGMK4eehceHl43gll2jrLJYxNfXk+zqATcX1iskP41QiF+ga3d0x3lme0h5enMraqBdPE51PNQo8hNy/vjoLdSywB6v+5+/k8qKYYWvg8OFjIvflHSh6rDJwofWi+sxAdIWxitqPyVRbWDKbN11XnsifRp7VnUBbGRf4E/tPRYq9RQu/2rpUdSJwKquQJ/DkpWJ/YMngiOE4Yk1k9efZq9pwVXVj+pyAFUWjSt3P3ZR/2CYbeB2jnx2fod80XaAbdtgRVE1Pzgr6hXw//LpntSYwHyu154kksSIAYMIgemClYjikYaeIa45wELUoemw/8EVLStMP4FRPmEKboB3V31hf4597HembgRiaVJMQDos0BazAJDqEdXewJSuwZ7gkVaIbIJRgBaCrIfpkIWdHq08v1LTw+jq/hoVpyrqPkZRK2Efbrx3t33jfy1+pHhyb95iSlMvQRotpRd5AUHrqtVawfGu/J75kUyIQIIEgKqBJYdLkNScX6xzvoTS9+ck/l8U/SlUPsdQyGDYbZR3r336f2R++Hjhb2Zj51PdQdQtaBg+AgXsZtYLwpGviJ9tkqWIfIIhgKiBA4cJkHWc5Kvgvd3RP+dg/ZQTLymKPQZQFGA3bQl3P32ofzJ+6Hj0b5xjP1RUQmguFRkBA9jsRNfuwnOwZKA7k2GJIIOogA6CRYclkGmcsKuFvV3RnOaf/LkSQSiOPARPEl88bB12aHztfph9dHiqb35jT1STQtQurBm/A7ntQtgCxJaxjaFjlH6KKoSZgd2C7IefkLGcxKtjvQXREebk+9IRNCdjO8JNwl3patB0KnvIfZV8m3cCbwxjF1SYQhcvKxp3BKbuXdlExfayAqPhlfuLm4XxghOE94h2kU2dIKx8vdjQn+Uw++AQCiYKOkJMKFw/aSNzh3k7fCp7Xnb7bUVillNiQi4vkBonBZ3vldq0xpO0wKS1l9aNb4eyhLGFZoqrkj6exazPvdfQSOWE+uUPxiSFOIhKRVpBZxlxgXdIell5vXSYbCphzVLxQRkv2RrOBZzw5ttNyGq2x6bcmQ6Qp4nYhraHOYw9lISftK1fvgLRDeXk+eMOaSPXNpVIHFjyZLRuGXXwdyN3uXLXarpfuVFDQdcuBRtoBqHxTt0Pyni4E6lUnJ+SPoxiiR6KbY4slh6h7K4rv1vR8ORP+dsN9iECNWxGrlVSYvdrUnI1dYl0VHC6aPZdXVBZQGcuFBv1Bqnyy972y7u6oasan4iVNI9NjOmMApF2mAujbbAzwOPR8eTJ+NEMbyAJMxBEAFNmX+NoL28Zco1xkG1DZt9bt04xP8gtAxt0B7TzW+AAzjC9bq4rosaYhZKYjxWQ9ZMam0ulN7J5wZnSEuVT+McL1x7vMIRBFFAxXH1lsmugbjJubmpyY3ZZyUzNPfos0RriB7/0++Eq0NS/eLGEpVScLpY/k56TRZcXnt2nSbT7wn/TVOXu970KLx22Lso+7ky2WMdh3mfMantq8WZLYLxWk0otPPwrfxo+CMf1qeNx0qPCu7QhqTCgK5o/l4KX75ppob6qo7a6xJXUt+Wc97YJextiLOY7kEn4VMZdt2OgZmtmHGPOXLRTFkhQOs8qChqGCMz2YuXS1JvFM7j/rFakep6Vm76b754Qpe6tQrm0xtrVPeZd97QIvRn0Kdo4/kX7UHxZQl8hYgVi8V7/WF5QVEU5OHIpcxm6CMr3JedL17nI3bsascOoFqM9oE6gRKMHqWmxJrzpyE/X5eY097kH+BdwJ6w1PULDTO5UgVpRXUxdc1rgVL5MT0LmNeUnuRjZCMH47ujZ2fjLtb9utXGt+6czpS6l6adNrS61TL9Yy/PYsecg98YGLBbaJF0yTz5USCBQeVU2WEVYp1V0UNVICD9bMyom3BfhCK/5uup43FXPt8P2uV2yJK1zqluq26zesTm5s8IAzsXaoOgk994FXhQzIvIuOjqzQxdLLlDTUvNSkFC/S6dEgjuYMEAk2xbRCJL6iewl383S38evvoK3jrL4r9CvFrK2tom9WMbe0Mbcs+lA9wIFkBKAH24rADbkPthFpkouTVxNM0vFRjdAvzefLSkithWpCGj7V+7e4VzWKcyTw9u8M7i9tYi1lbfRuxnCOcrx0/Pe6ep09zMEwxDCHNUnpjHrOWZA5kRKR4RHk0WJQYg7wTNyKuYfbxRoCC/8IvCf5P7ZkdCfyGTCDr69u3+7Vb0twebGU84310zhQuzC93ID+g7+GSokMS3ONMc68T4uQW9BtT8PPJ02iy8TJ3gdBRMNCOj86fFm57HdE9XOzRfIG8T0wbDBUMPExu3Lo9Kv2s/jve0p+MICNw02F3IgpCiQLwA1zjjeOiM7njlcNnsxIiuEI+AaeRGZB4/9qPMv6m/hqtka0/DNU8pbyBbIgsmRzCrRJtdU3nvmWu+r+CMCfAtsFK4cBCQ3KhcvgjJgNKY0UzN1MCUshybIHyAYyw8LByX+XfX47DblUd5/2OnTsdDuzqrO5M+R0pjW2Nsm4k7pGPFG+ZcBzAmlEeUYVh/HJBApEyy6Lfwt2SxeKp8mviHiGzoV/Q1iBqj+CPe+7wHpBuP43f3ZMden1WjVdNa+2DTctuAg5kbs9vL8+R4BKAjiDhgVnBpFH/EihSXxJisnNiYcJO8gzBzUFzESDwygBRf/pfh98s7sw+eA4ybgy91/3ErcKd0U3/jhvOVB6mHv8/TL+rkAkQYmDEwR3RW3Gb8c3x4KIDogbx+0HRkbtBeiEwUPAwrEBHL/NPo09ZnwhOwT6V/me+Ry40rjAOSM5eDn5eqE7pzyDve0+2kACwV0CYQNHBEhFIAWJxgMGS0ZihgsFyAVehJPD7sL2wfOA7f/svvg9130RPGr7qPsO+t56mLq8uoi7OftL/Dm8vb1RPm2/C8AlgPPBsQJXQyJDjgQYRH9EQsSjRGJEAsPIg3eClMIlwXAAub/Hv1++hn4APZD9O3yBPKP8Yzx+fHR8gj0lPVl92v5lfvQ/QoAMwI5BA4GpAfyCO4JlQrjCtoKfQrRCd8IsQdTBtEEOgOaAQAAd/4L/cj7tPrX+Tb50vis+ML4EPmS+T/6D/v7+/n8/v0C//3/5AC1AWcC9wJiA6cDxwPEA6ADYAMJA6ACKwKyATgBxQBcAAIAu/+H/2f/W/9i/3n/nv/M//7/MABeAIQAnQClAJsAfQBKAAQArP9E/9L+Wf7f/Wn9//ym/GT8Pvw4/FX8l/z//Iz9O/4J//D/6ADsAfIC8APeBLEFYgbnBjkHVAc0B9UGOAZhBVEEEQOpASIAif7p/FD7zPlr+Dj3QfaP9Sv1GvVh9QD29vY9+M75nvug/cf/AAI8BGgGcghICtoLGQ35DW8Odg4KDisN3QsoChcIuAUcA1YAff2l+ub3VvUL8xnxku+E7vrt/O2M7qrvT/Fx8wH27/gk/Ij/AAN0BsYJ2wybD+0RvRP7FJkVjxXcFIEThhH4DukLbgiiBKAAifx6+Jb0+vDF7RPr+eiM59nm6ea/51bppeue7iryMfaU+jP/6AORCAgNKRHTFOYXShrnG7AcmhyjG9EZLhfME8QPMgs6BgABrvtr9mLxvOyd6Cjle+Kt4M7f6N/+4AvjAObJ6UzuZ/P0+Mn+twSSCiwQVxXrGcAduCC4Iq4jkCNbIhYg0BygGKQTAQ7iB3QB6/p49E7unuiX42DfHtzs2d7Y/9hR2s3cYuD35GvqlPBF90r+bQV3DDATYxnfHnYjAydoKY4qayr9KEsmaCJvHYYX2BCYCf0BQvqj8lvrpeS23r7Z5tVP0w/SM9K906PW0tos4Inmuu2I9bj9CQY8DhEWSR2rIwMpJi3wL0oxJjGDL2ks8Cc2ImYbtRNaC5gCs/nt8Izo0+D/2UfU2c/bzGfListGzZHQVNVs26vi3OrA8xP9jAbjD84YBiFMKGMuGzNNNt03uzfnNWwyYy3vJkEfkxYoDUYDPPlW7+LlK9111f/O/MmXxuzECsX0xp7K7c+71tXe/efu8Vz89QZoEWQbmCS9LJIz3zh4PD8+JT4lPE84vDKWKxMjchn+DgYE4Pjh7WDjsNkc0evJVMSHwKO+ub7MwM7Eosoe0gnbIOUV8JX7RQfNEtId/Cf9MIs4az5sQm5EXUQ3Qgs+9zcoMNgmTRzaENUEnPiN7AfhZNb4zA7F5b6vupG4nLjSuia/eMWZzUzXR+I37r76fAcQFBYgMCsGNUs9vEMlSGJKXkoXSJ1DDz2fNIwqIh+6ErIFcfhb69jeSdMKyWzAs7kWtbuyt7INtay5dMAxyaLTd99V7Nr5mwcxFS8iMS7XOM5BzkieTRdQJFDBTf5I/0H3OCsu7iGcFJ0GXvhM6tXcYtBXxQm8w7S/ryetEa2Br2W0mrvpxA3Qsdxz6un4ogcvFhwk/TBtPBBGnE3SUolVqVUuUypOwkYtPbMxrSR+FpQHY/hf6f7asc3gwee3GLCvqtmnr6czqlWv77bHwJPM+dmS6O33kgcLF9wlkzPEPw9KI1K9V7Ja6FpbWB1TVEs7QR81XSddGJUIfviU6FXZNsunvgu0tqvppdWilKIopYGqd7LNvDbJUte15uj2bAfEF28n8jXcQshNX1ZcXI9f3l9DXdFXsU8fRWw4+ik3Gp0Jr/js59nX9Miwu3ewoKdzoSCexZ1koO2lNq4BufrFwNTf5Nz1MQdbGNMoGDiyRThRTVqqYBxkhWThYUNc01PTSJY7gSwJHK0K9Phm54zW68b8uC2t2qNOnb6ZRpnsm5+hMqpltePCRNIS48r04gbRGAkqAzpFSFxU612kZFRo2mgyZm5guVdVTJk+8C7RHcELTPkB527VHcWMti+qZqB/mbGVG5XEl5mdbab/sfS/489Q4bTzgQYlGRArtDuSSjNXNWFIaDRs2Wwxak5kXFugT3NBQzGMH9cMt/m95n7UicNitH+nRp0Ilv6RSJHvk9+Z7KLQrjC9n82c353yDgZZGegrKj2ZTLtZKWSSa7pvf3Dbbd9nul6xUiBEeDM4Ie8NMvqZ5r3TMcJ/siClfprskqeO0Y1xkHaWsp/dq5u6esv43YbxiwVtGZIsZD5YTvFbxmZ/buFyyHMscR9r0GGFVZ1GizXTIgUPvPqU5irTFcHjsBKjDpgtkK+Lt4pOjWCTwpwpqTe4eMln3HHw+gRjGQ8tYj/QT9ddCWkPcal1snYidApummQZWOdIezdZJBgQVPut5sTSNcCPr1ah+JXOjRiJ/oeHiqGQH5q3pgi2nMfs2mHvXAQ8GV4tJUD/UGlf8Wo+cw54Onm5dp1wFGdpWvtKQznJJSUR9/vj5ovSkL+Eru2fPZTPi+aGqIUgiDuOzZeJpBC06MWI2VfuswP4GIEtrEDmUadgfWwLdQ56XnvveNVyPmlyXNdM4johJysSpfw0537SJr/Crdme35IzihiFt4MahjGMzZWkolKyXsQ92FXtAQOaGHgt+UCFUpJhrW12dql7HH3DerF0E2s0XndOVjxdKCgTW/2f55zS975HrRie3pH6iLGDLIJ5hIWKI5QIodCwAcMP117sRwIiGEUtC0HbUipigG59d9x8cn4yfC12kmyqX9pPmz19KRkUGP4i6OTSAb8UraqdOpEliLGCCoE9gzmJ0JK4n42v1MH/1XPriAGTF+os5UDqUm1i9W4heKh9YH87fUl3uG3TYP1QsT58Kv0U2v696FPTQ78prZCd85CzhxqCUYBogk6I1pG2noqu18AQ1ZfqxQDuFmYsh0CzUl5iDm9geAt+5H/cfQN4hW6tYd9RlD9bK9EVnv9s6erTvb+DrcidCZGnh+uBAYD6gcWHNpEDnsmtDsBD1MvpAAA=\" type=\"audio/wav\" />\n    Your browser does not support the audio element.\n</audio>\n\n\n\n\n## Video\n\nMore exotic objects can also be displayed, as long as their representation supports the IPython display protocol.  For example, videos hosted externally on YouTube are easy to load:\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('sjfsUzECqK0')\n```\n\nUsing the nascent video capabilities of modern browsers, you may also be able to display local\nvideos.  At the moment this doesn't work very well in all browsers, so it may or may not work for you;\nwe will continue testing this and looking for ways to make it more robust.  \n\nThe following cell loads a local file called  `animation.m4v`, encodes the raw video as base64 for http\ntransport, and uses the HTML5 video tag to load it. On Chrome 15 it works correctly, displaying a control bar at the bottom with a play/pause button and a location slider.\n\n\n```python\nfrom IPython.display import HTML\nfrom base64 import b64encode\nvideo = open(\"../images/animation.m4v\", \"rb\").read()\nvideo_encoded = b64encode(video).decode('ascii')\nvideo_tag = '<video controls alt=\"test\" src=\"data:video/x-m4v;base64,{0}\">'.format(video_encoded)\nHTML(data=video_tag)\n```\n\n## External sites\n\nYou can even embed an entire page from another site in an iframe; for example this is today's Wikipedia\npage for mobile users:\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('http://jupyter.org', width='100%', height=350)\n```\n\n## Links to local files\n\nIPython provides builtin display classes for generating links to local files. Create a link to a single file using the `FileLink` object:\n\n\n```python\nfrom IPython.display import FileLink, FileLinks\nFileLink('Cell Magics.ipynb')\n```\n\nAlternatively, to generate links to all of the files in a directory, use the `FileLinks` object, passing `'.'` to indicate that we want links generated for the current working directory. Note that if there were other directories under the current directory, `FileLinks` would work in a recursive manner creating links to files in all sub-directories as well.\n\n\n```python\nFileLinks('.')\n```\n\n## Rich output and security\n\nThe IPython Notebook allows arbitrary code execution in both the IPython kernel and in the browser, though HTML and JavaScript output. More importantly, because IPython has a JavaScript API for running code in the browser, HTML and JavaScript output can actually trigger code to be run in the kernel. This poses a significant security risk as it would allow IPython Notebooks to execute arbitrary code on your computers.\n\nTo protect against these risks, the IPython Notebook has a security model that specifies how dangerous output is handled. Here is a short summary:\n\n* When you run code in the Notebook, all rich output is displayed.\n* When you open a notebook, rich output is only displayed if it doesn't contain security vulberabilities,...\n* ..or if you have trusted a notebook, all rich output will run upon opening it.\n\nA full description of the IPython security model can be found on [this page](http://ipython.org/ipython-doc/dev/notebook/security.html).\n\n## Rich output and nbviewer\n\nMuch of the power of the Notebook is that it enables users to share notebooks with each other using http://nbviewer.ipython.org, without installing IPython locally. As of IPython 2.0, notebooks rendere on nbviewer will display all output, including HTML and JavaScript. Furthermore, to provide a consistent JavaScript environment on the live Notebook and nbviewer, the following JavaScript libraries are loaded onto the nbviewer page, *before* the notebook and its output is displayed:\n\n* [jQuery](http://jquery.com/)\n* [RequireJS](http://requirejs.org/)\n\nLibraries such as [mpld3](http://mpld3.github.io/) use these capabilities to generate interactive visualizations that work on nbviewer.\n", "meta": {"hexsha": "5e707d35662db2479f422bbded0f37a528467fde", "size": 94221, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "jupyter_notebooks/Rich Output.ipynb", "max_stars_repo_name": "darcamo/python-and-numpy-course", "max_stars_repo_head_hexsha": "57efef73c20544c4a6cd6d61a2bf65a56f48e71b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jupyter_notebooks/Rich Output.ipynb", "max_issues_repo_name": "darcamo/python-and-numpy-course", "max_issues_repo_head_hexsha": "57efef73c20544c4a6cd6d61a2bf65a56f48e71b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jupyter_notebooks/Rich Output.ipynb", "max_forks_repo_name": "darcamo/python-and-numpy-course", "max_forks_repo_head_hexsha": "57efef73c20544c4a6cd6d61a2bf65a56f48e71b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 101.3129032258, "max_line_length": 64152, "alphanum_fraction": 0.8416913427, "converted": true, "num_tokens": 49414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.061875983993696954, "lm_q2_score": 0.05261895223347499, "lm_q1q2_score": 0.0032558494461636034}}
{"text": "Why SoftMax? Full Bayesian filtering of arbitrary states.\nIs it possible to model dynamic targets/groundings with G^3? Is there a one-to-one mapping between our state-space representation, and factor graph representation?\nIf you could do it, what would it require you to do?\nWhat assumptions they make don't scale?\n\nwe're not focused on the grounding problem - they are\nwe're focused on providing perception, given groundings\n\nExtracting Meaning from Human Sensors\n\n\n# i. Preface\n\nThis document provides the rough, unformatted run-through of the paper being submitted to the Robotics Science and Systems 2015 [Workshop on Model Learning for Human-Robot Communication](http://www.ece.rochester.edu/projects/rail/mlhrc2015/#importantdates).\n\n\n# ii. Big Picture\nAnswers to [Heilmeier's Catechism](http://en.wikipedia.org/wiki/George_H._Heilmeier#Heilmeier.27s_Catechism):\n\n## ii.1 What are you trying to do? Articulate your objectives using absolutely no jargon.\nWe're developing a technique for humans to inform robots of the world around them. Put another way, we're developing a Bayesian framework for a (noisy) *human sensor* that the robot can use to understand its environment. We want to be able to plug this human sensor into existing perception algorithms.\n\n## ii.2 How is it done today, and what are the limits of current practice?\nMost researchers focus on providing robots with a spatial understanding of the environment, but this doesn't allow for many of the descriptions in human language. Moreover, they focus on control, and so they're looking for a single best estimate.\n\n3 types of uncertainty - humans are not oracles. We're looking at typical Bayesian uncertainty - sensor error/imprecision/accuracy, association error.\n\ntalk about cops and robots\n\nPhysical vs. abstract concepts\n\nscalability & implelmentation - dynamics? larger space-time scales for a grid? \n\n\n## ii.3 What's new in your approach and why do you think it will be successful?\nOur approach is more general than simply focusing on Euclidian space: we want to translate arbitrary *state space*, which includes Euclidian space. A state could be position, velocity, heading, a target's tactics -- anything a human can sense.\n\nThis approach will be successful because it captures the richness of human language instead of focusing solely on prepositional relationships, allowing for far more information to be provided by a human sensor (as long as the robot has a model for how to *use* the state estimate).\n\nuse GMMs instead - they scale far better than particles/grid models\n\nwe want to human to do more than labeling - we want the human to express a broader understanding \n\nhuman doesn't necessarily know all the answers, but can provide helpful (positive or negative) information\n\nthink of difficult environments for sensors - constrained computing, out on the road at night\n\nIn the event of sensor failure, a human can step in to make perception more robust\n\nbig difference because humans are used as multi-state sensors, not simply labelers of the world. we have the human in the loop. they focus on human as an augmentation for planning, we focus on human as an augmentation for sensing.\n\nwe need our model to work well within a Bayesian filter. our focus is more on *dynamics* (*aerospace* - computation constraints are IMPORTANT).\n\nestimation-friendly models for state-spatial language (sticking with codebook)\n\n## ii.4 Who cares?\nWe can break down the, \"Who cares?\" question into three types of people interested in using humans as sensors to inform an autonomous system of its environment:\n* *Researchers* can use and build upon our model;\n* *Developers* can incorporate the use of human sensors to make their robots and autonomous systems take in a rich new spectrum of information;\n* *End-users* can use the products of the developers.\n\n\n## ii.5 If you're successful, what difference will it make?\nThe ability for humans to explain the world around them to robots is huge: robots are fantastic at intensely complicated and quick computation, but poor on developing deep understanding. Humans are the opposite. \n\nThe ability to tell the robot about aspects of its world is akin to telling a toddler about its world. Currently, we can only tell our toddler-bots about spatial relationships: the box is in a corner, the kitchen is down the hall from the office, etc. \n\nImagine how much more they'll learn if we can tell them about all the rest of the concepts described human language: height, texture, movement models, etc.\n\n## ii.6 What are the risks and the payoffs?\nWe might be wasting our time/AI is dangerous/We might miss a better technique.\n\nThe payoff, if our model works well, is that we can take a big step towards conversational interaction with autonomous systems.\n\n## ii.7 How much will it cost?\nFor a system that already has humans to interact with, this will not cost any money. However, the cost of interaction is an interesting problem: humans intuitively know the rules of when and how to interact with each other (to a varying degree...). Robots don't.\n\nIf a robot is able to ask questions about its environment, how does it determine what the correct amount of questions to ask is? How does it understand when it has annoyed its teammate? This is one of our core research questions: what is the cost, in term of a human operator's attention and willingness to answer, of a robot asking questions and providing information?\n\n## ii.8 How long will it take?\n\nDepends on how complicated and exact it needs to be. We can propose models, or we can learn models from human experience. The first is simply the length of building up a library for the ways in which humans describe environments - the second would be an ongoing process of calibrating a human's meaning to a probabilistic understanding of the state space.\n\n## ii.9 What are the midterm and final \"exams\" to check for success?\nWe'd run experiments to determine:\n* How well does a human-robot team work with a human acting as a sensor?\n* Do some states work better than others? Are some more variable between humans?\n* Instead of re-learning all human models, can we effectively transfer 'calibrarion profiles' between humans?\n\n# iii. Outline\n\n1st technical nugget: Generalized MMS with GMMs\n2nd technical nugget: Extension to velocity/Heading\n3rd technical nugget: learning\n\n1. how do you get the models?\n  1. binary softmax\n  2. deformable templates\n2. what properties of this model makes it good for inference?\n  1. dynamics\n  2. motion models\n3. what properties of this model makes it good for learning?\n  1. GPs\n  2. Population learning (priors based on hyperpriors shared among human sensors)\n  3. Concept transfer (how are 'front' and 'nearby' related) & online learning (ICCPS)\n  \nThink about:\nkey figures, demos (esp. for 1, and how it connects to 2 and 3)\nstart document\n\n\n\n1. Introduction\n  1. Ground Cops and Robots\n  What's in this problem that other related research can't solve\n2. Related Work\n3. Generating SoftMax Models\n  1. From Weights\n  2. From Class Boundaries\n  3. From Polytope Templates\n  4. In n-dimensions\n  5. Multimodal SoftMax\n4. Learning Spatial SoftMax Models\n  1. From Collected Data\n  2. With Prior Boundaries\n  3. Using Symmetry to Minimize Data Collection\n5. Simulations\n6. Ongoing Work\n\n# iii.1 Key Equations\n\n### Chapman-Komolgorov\nUsed for dynamics prediction step in Bayes' filters (like KF, UKF, EKF, PF, GSF).\n\\begin{equation}\np(\\left. X_k \\right| \\zeta_{1:k-1},D_{1:k-1})\n= \\int p(\\left. X_k \\right| X_{k-1})\np(\\left. X_{k-1} \\right| \\zeta_{1:k-1},D_{1:k-1})\ndX_{k-1}\n\\end{equation}\n\n### Bayes' Fusion (robot update)\nDone *before* human update.\n\n\\begin{align}\n\\begin{split}\np(\\left. X_k \\right| \\zeta_{1:k},D_{1:k-1})\n& = \\frac{p(\\left. \\zeta_k \\right| X_k)  p(\\left. X_k \\right| \\zeta_{1:k-1},D_{1:k-1})}\n{\\int p(\\left. \\zeta_k \\right| X_k)  p(\\left. X_k \\right| \\zeta_{1:k-1},D_{1:k-1}) dX_k} \\\\\n&\\equiv p( X_k )\n\\end{split}\n\\end{align}\n\n### Bayes' Fusion (human update)\nThe focus of our paper. We want to generate the likelihood model.\n\\begin{align}\n\\begin{split}\np(\\left. X_k \\right| \\zeta_{1:k},D_{1:k})\n&= \\frac{p(\\left. D_k \\right| X_k)  p(\\left. X_k \\right| \\zeta_{1:k},D_{1:k-1})}\n{\\int p(\\left. D_k \\right| X_k)  p(\\left. X_k \\right| \\zeta_{1:k},D_{1:k-1}) dX_k} \\\\\n&\\equiv p(\\left. X_k \\right| D_{k} )\n\\end{split}\n\\end{align}\n\n### Softmax Likelihood\nWidely used. Well-suited for modling hybrid continuous-to-discrete mappings (e.g. human utterances to continuous state space probabilities. Always leads to complete convex decomposition of the state space, so the state can be fully partitioned.\n\nProblems: do *not* (necessarily) lead to closed-form posteriors. Thus, grid-based and particle approximations could work, but they scale poorly with state dimensionality, provide a cumbersome posterior, and, for grids, don't mesh easily with typical filters for hard sensor data. Gaussian mixtures via EM are prone to poor local maxima **(?)** and high computation.\n\n\\begin{equation}\nP(D_k=j \\vert X_k = \\mathbf{x}) = \\frac{e^{\\mathbf{w}_j^T \\mathbf{x} + b_j}}{\\sum_{h=1}^m e^{\\mathbf{w}_h^T\\mathbf{x} + b_h}}\n\\end{equation}\n\n### Linear Hyperplane Class Boundaries\nCould be critical or non-critical boundaries.\n\n\\begin{equation}\nL_{log}(i,j) = (\\mathbf{w}_i - \\mathbf{w}_j)^T\\mathbf{x} + (b_i - b_j) = 0\n\\end{equation}\n\n### Shifted and Rotated Coordinate Frame\n**Should we consider a quaternion representation? What about generalized rotations?***\n\n\\begin{align}\n\\begin{split}\n\\mathbf{w}_i^\\prime &= \\mathbf{w}_i^T R(\\theta) \\\\\nb_i^\\prime &= \\mathbf{w}_i^T R(\\theta) \\mathbf{b}\n\\end{split}\n\\end{align}\n\n### Softmax Gradient\nDefines the slope of a given class.\n\n\\begin{equation}\n\\frac{\\partial P(D_k = i \\vert \\mathbf{x})} {\\partial \\mathbf{x}} = \nP(D_k = i \\vert \\mathbf{x}) \\left(\\mathbf{w}_{i} - \\sum_{h=1}^m \\mathbf{w}_{h}P(D_k = h \\vert \\mathbf{x}) \\right) \\\\ \n\\end{equation}\n\n### Weight-Normal Transform\nGeneral transformation:\n\n\\begin{equation}\n\\mathbf{n} = \\mathbf{A}\\mathbf{w}\n\\end{equation}\n\nOr, for strict ordering and zero-weight reference class $i$:\n\n\\begin{equation}\n\\mathbf{n}_{i,j} = \\mathbf{w}_j\n\\end{equation}\n\n### Rouch\u00e9-Capelli Theorem\nUsed in conjunction with the rank check to ensure proper A matrix.\n\\begin{equation}\nrank\\left(\\mathbf{A}_{min}\\right) = rank\\left(\\left[\\begin{array}{r|r} \\mathbf{A}_{min} & \\mathbf{n}_{min}\\end{array}\\right]\\right)\n\\end{equation}\n\n### Polytopes to Weights\nSample points from polytopes to find exact weights. Use SVD or other matrix decomposition technique.\n\n\\begin{equation}\n\\begin{bmatrix}\n\\mathbf{x}_{i,1} & \\mathbf{x}_{i,2} & \\dots & \\mathbf{x}_{i,n} & \\mathbf{1} \\\\\n\\end{bmatrix}\n\\begin{bmatrix}\nw_{i,1}\\\\\nw_{i,2}\\\\\n\\vdots \\\\\nb_i\n\\end{bmatrix}\n=\\begin{bmatrix}\n0\\\\\n0\\\\\n0\n\\end{bmatrix}\n\\end{equation}\n\n### Normal check\n*Sum of *all* normals *must* equal 0*.\n\n### Multimodal Softmax Likelihood\nGroups subclasses $\\theta(j)$ together into classes. No longer convex, though subclasses are. *Boundaries *or* gradients shift, but* not both. Possible to estimate MMS class weights from data (i.e. through symmetry).\n\n\\begin{equation}\nP(D_k=j \\vert X_k = \\mathbf{x}) \n= \\frac{\\sum\\limits_{r \\, \\in \\, \\sigma(j)} e^{\\mathbf{w}_r^T \\mathbf{x} + b_r}}\n{\\sum\\limits_{c = 1}^S e^{\\mathbf{w}_c^T\\mathbf{x} + b_c}}\n\\end{equation}\n\n### MMS Boundary Shaping\n(Fixed boundaries vs. fixed gradients)\n\nTake three arbitrary classes `A`, `B`, and `C`. We will sum `A` and `C` together to make superclass `D`:\n\n\\begin{align}\nL_{log}(B,D) \n&= \\mathbf{w}_B^T \\mathbf{x} + b_B - \\ln{\\left( e^{\\mathbf{w}_A ^T \\mathbf{x} + b_A} + e^{\\mathbf{w}_C^T \\mathbf{x} + b_C}\\right)}\n= 0\\\\\nL_{log}(B,A) &= (\\mathbf{w}_B - \\mathbf{w}_A)^T \\mathbf{x}_{AB} + (b_B - b_A) = 0\\\\\nL_{log}(B,C) &= (\\mathbf{w}_B - \\mathbf{w}_C)^T \\mathbf{x}_{BC} + (b_B - b_C) = 0\n\\end{align}\n\nWhere $x_{AB}$ and $x_{BC}$ are the solutions to the above equations for fixed weights (i.e. the locations of the boundary in the state space). [Must be solved numerically](http://math.stackexchange.com/questions/129504/solving-a-sum-of-exponentials).\n\n### Complete Multi-shape MMS Algorithm\n\n*Inputs*:\nMap object shapes + scales\nScaling factor for object interiors\n\n*Outputs*:\nMultiple binary, convex, linearly/non-linearly separable probabilistic decompositions of the state space.\n\n1. Find normal vectors for all shapes\n1. Find *independent* shape weights (i.e. through learning - following section.)\n1. Use MMS boundary shaping on all shapes\n1. Account for object interiors\n\nNote: template concept applies to non-physical shapes (i.e. motion models for velocity states)\n\n\n# iii.2 Examples\n\n### Speed example\n\nState space: $s$\n\n### Non-MMS and MMS Pentagon examples (regular 2D polygon)\n\nState space: $\\begin{bmatrix} x & y \\end{bmatrix}$\n\n### Football stadium example (curved 2D shape)\n\nState space: $\\begin{bmatrix} x & y & x^2 & xy & y^2 \\end{bmatrix}$\n\n### Full room example (many objects, many barriers)\n\nState space: $\\begin{bmatrix} x & y & x^2 & xy & y^2 \\end{bmatrix}$\n\nShow near: clusters of objects, rooms\n\nVideo example for demo: \"The ball is between three robots.\" as the robots are moving.\n\n# iv. Abstract\n\n* **Key words**: Human-robot dialog, spatial language modeling and interpretation, Spatial-semantic mapping, Semantic perception\n\n# 1. Introduction\n<div class=\"rounded-box\">\n<h3> Questions this section answers:</h3>\n<ol> \n<li> What's the importance of a physical understanding of the world?</li>\n<li> How does it apply to a human-robot team?</li>\n<li> How can humans convey a physical understanding of the world to the robot?</li>\n<li> What types of physical understanding can we convey? How do we convey them? </li>\n<li> What domains does this apply to? When would it be used?</li>\n</ol>\n</div>\n\n# 2. Related Work\n<div class=\"rounded-box\">\n<h3> Questions this section answers:</h3>\n<ol> \n<li> Who else has worked on communicating spatial understanding to a robot? </li>\n<li> How does our research differ from theirs? </li>\n<li> What have we worked on in the past, and how are we improving it? </li>\n</ol>\n</div>\n\n* Nisar's previous work\n* Nick Roy's Group (Tellex, Walter)\n* Jensfelt and Burgard\n* Dieter Fox, Cynthia Matuszek\n* Gaardenfors\n* Kuipers\n* Kaupp\n* Terry Regier (?)\n* Jamie Frost, Alastair Harrison\n* Marjorie Skubic ([this?](http://eldertech.missouri.edu/docs/HCC%20Small.html))\n\n\n# 3. Generating SoftMax Models\n<div class=\"rounded-box\">\n<h3> Questions this section answers:</h3>\n<ol> \n<li> What is a SoftMax Model and why does it best represent a spatial understanding? </li>\n<li> What different elements compose a SoftMax model, and what do they mean?</li>\n<li> What different ways can we construct a SoftMax model easily?</li>\n</ol>\n</div>\n\n## 3.1. From Weights\n<div class=\"rounded-box\">\n<h3> Questions this section answers:</h3>\n<ol> \n<li> What are the core insights we can get from SoftMax models? </li>\n<li> How is the slope of each class's probability derived and manipulated?</li>\n<li> How do manipulate (i.e. rotate/translate) the model?</li>\n</ol>\n</div>\n\n## 3.2. From Class Boundaries\n<div class=\"rounded-box\">\n<h3> Questions this section answers:</h3>\n<ol> \n<li> How do we compute SoftMax weights from class boundaries? </li>\n<li> When *can't* we use class boundaries? </li>\n</ol>\n</div>\n\n## 3.3. From Polytope Templates\n<div class=\"rounded-box\">\n<h3> Questions this section answers:</h3>\n<ol> \n<li> How do we derive normals from Polytope templates? </li>\n</ol>\n</div>\n\n## 3.4. In n-dimensions\n<div class=\"rounded-box\">\n<h3> Questions this section answers:</h3>\n<ol> \n<li> What do 1D examples looks like, and what purposes do they serve? </li>\n<li> Can we combine multiple states (i.e. position and velocty) into one SoftMax model?</li>\n</ol>\n</div>\n\n## 3.5. Multimodal Softmax\n<div class=\"rounded-box\">\n<h3> Questions this section answers:</h3>\n<ol> \n<li> Can we compose 'superclasses' from multiple SoftMax classes? </li>\n<li> Can we merge multiple state types (i.e. position and velocity) into a superclass?</li>\n<li> Can we fix the normal boundary problem using our classes as superclasses?</li>\n</ol>\n</div>\n\n# 4. Learning SoftMax Models\n<div class=\"rounded-box\">\n<h3> Questions this section answers:</h3>\n<ol> \n<li> Instead of specifying the SoftMax Models, can we learn them from user data? </li>\n<li> What use is collecting data from individuals? How different are they? Are humans good estimators?</li>\n<li> What language do humans use to express spatial representations? How many prepositions exist? Does their usage vary?</li>\n<li> Can we use negative information well?</li>\n</ol>\n</div>\n\n## 4.1. From Collected Data\n<div class=\"rounded-box\">\n<h3> Questions this section answers:</h3>\n<ol> \n<li> How do we learn distributions from experimental human data? </li>\n</ol>\n</div>\n\n## 4.2. With Prior Boundaries\n<div class=\"rounded-box\">\n<h3> Questions this section answers:</h3>\n<ol> \n<li> Given a gounding polytope, can we simply learn the gradients of the SoftMax classes? </li>\n<li> Can we represent the polytope boundaries probabilistically?</li>\n</ol>\n</div>\n\n## 4.3. Using Symmetry to Minimize Data Collection\n<div class=\"rounded-box\">\n<h3> Questions this section answers:</h3>\n<ol> \n<li> Can we minimize the amount of data needed to be collected by exploiting symmetry? </li>\n<li> Which prepositions or prepositional phrases imply symmetry?</li>\n</ol>\n</div>\n\n# 5. Simulations\n<div class=\"rounded-box\">\n<h3> Questions this section answers:</h3>\n<ol> \n<li> Is this SoftMax decomposition effective? </li>\n<li> Can it run in real-time?</li>\n<li> How did the robot perform on its own?</li>\n<li> How did the human-robot team perform when using positional statements? Velocity statements? Both?</li>\n<li> How useful was negative information?</li>\n</ol>\n</div>\n\n# 6. Conclusion\n<div class=\"rounded-box\">\n<h3> Questions this section answers:</h3>\n<ol> \n<li> What model did we introduce? </li>\n<li> What validation can we provide?</li>\n<li> What's next?</li>\n</ol>\n</div>\n\n\n\n```python\nfrom IPython.core.display import HTML\n\n# Borrowed style from Probabilistic Programming and Bayesian Methods for Hackers\ndef css_styling():\n    styles = open(\"../styles/custom.css\", \"r\").read()\n    return HTML(styles)\ncss_styling()\n```\n\n\n\n\n<link href='http://fonts.googleapis.com/css?family=Roboto:100,100italic,500,300,300italic,400' rel='stylesheet' type='text/css'>\n\n<style>\n    div.cell{\n        width:800px;\n        margin-left:16% !important;\n        margin-right:auto;\n    }\n    h1, h2, h3, h4 {\n        font-family: \"Roboto\", \"wingdings\", sans-serif;\n    }\n    h1{\n        font-weight: 500;\n    }\n    h2{\n        font-weight: 400;\n    }\n    h3{\n        font-weight: 300 !important; \n/*         font-style: italic; */\n    }    \n    h4{\n        font-weight: 300 !important;\n        font-style: italic;\n        margin-top:12px;\n        margin-bottom: 3px;\n       }\n    div.text_cell_render{\n        font-family: \"HelveticaNeue-light\", \"Helvetica Neue\", Arial, Helvetica, Geneva, sans-serif;\n        line-height: 145%;\n        font-size: 120%;\n        width:800px;\n        margin-left:auto;\n        margin-right:auto;\n    }\n    .CodeMirror{\n            font-family: \"Source Code Pro\", source-code-pro,Consolas, monospace;\n    }\n    .prompt{\n        display: None;\n    }\n    .text_cell_render h5 {\n        font-weight: 300;\n        font-size: 22pt;\n        color: #4057A1;\n        font-style: italic;\n        margin-bottom: .5em;\n        margin-top: 0.5em;\n        display: block;\n    }\n\n    .warning{\n        color: rgb( 240, 20, 20 )\n        }  \n\n    .rounded-box{\n    border-radius: 25px; \n    border: 2px solid #8AC007;\n    padding: 10px;\n    padding-top: 0px;\n    }\n</style>\n\n\n\n", "meta": {"hexsha": "d737a99f8d8cd770f025fc0ca92da7330243db7e", "size": 26629, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "resources/notebooks/softmax/Paper.ipynb", "max_stars_repo_name": "COHRINT/cops_and_robots", "max_stars_repo_head_hexsha": "1df99caa1e38bde1b5ce2d04389bc232a68938d6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-01-19T17:54:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-21T12:09:03.000Z", "max_issues_repo_path": "resources/notebooks/softmax/Paper.ipynb", "max_issues_repo_name": "COHRINT/cops_and_robots", "max_issues_repo_head_hexsha": "1df99caa1e38bde1b5ce2d04389bc232a68938d6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "resources/notebooks/softmax/Paper.ipynb", "max_forks_repo_name": "COHRINT/cops_and_robots", "max_forks_repo_head_hexsha": "1df99caa1e38bde1b5ce2d04389bc232a68938d6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2015-02-19T02:53:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-05T20:29:12.000Z", "avg_line_length": 43.5114379085, "max_line_length": 378, "alphanum_fraction": 0.5773780465, "converted": true, "num_tokens": 5390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17553805637093017, "lm_q2_score": 0.017986209008010314, "lm_q1q2_score": 0.0031572641707474465}}
{"text": "# Introduction to web scraping\n\nThis workshop is a one-hour beginner's introduction to web scraping. \n\nThis notebook deliberately has more content that we can reasonably cover in one hour. **The most important material is in bold**, and we'll focus on that material in person. To get the most out of this workshop, I'd suggest spending some time working through it in full after the workshop.\n\nWe'll cover the following topics:\n\n[Motivation](#motivation)\n\n_Why would you want to scrape data from the web?_\n\n[How the Web works](#web)\n\n_A high-level appreciation of how the Web works will help us to scrape data effectively._\n\n[Making a request](#request)\n\n_How can we ask other computers on the Internet to send us data using Python?_\n\n[Parsing HTML](#parsing)\n\n_Web pages are just files in a special format. Extracting information out of these files involves parsing HTML._\n\n[Terms of Service](#terms)\n\n_Don't go scraping willy-nilly!_\n\n[Further resources](#resources)\n\n_So you want to learn more about web scraping._\n\n## Motivation<a id='motivation'></a>\n\nIt's 2019. The web is everywhere.\n\n* If you want to buy a house, real estate agents have [websites](https://www.wendytlouie.com/) where they list the houses they're currently selling. \n* If you want to know whether to where a rain jacket or shorts, you check the weather on a [website](https://weather.com/weather/tenday/l/Berkeley+CA+USCA0087:1:US). \n* If you want to know what's happening in the world, you read the news [online](https://www.sfchronicle.com/). \n* If you've forgotten which city is the capital of Australia, you check [Wikipedia](https://en.wikipedia.org/wiki/Australia).\n\n**The point is this: there is an enormous amount of information (also known as data) on the web.**\n\nIf we (in our capacities as, for example, data scientists, social scientists, digital humanists, businesses, public servants or members of the public) can get our hands on this information, **we can answer all sorts of interesting questions or solve important problems**.\n\n* Maybe you're studying gender bias in student evaluations of professors. One option would be to scrape ratings from [Rate My Professors](https://www.ratemyprofessors.com/) (provided you follow their [terms of service](https://www.ratemyprofessors.com/TermsOfUse_us.jsp#use))\n* Perhaps you want to build an app that shows users articles relating to their specified interests. You could scrape stories from various news websites and then use NLP methods to decide which articles to show which users.\n* [Geoff Boeing](https://geoffboeing.com/) and [Paul Waddell](https://ced.berkeley.edu/ced/faculty-staff/paul-waddell) recently published [a great study](https://arxiv.org/pdf/1605.05397.pdf) of the US housing market by scraping millions of Craiglist rental listings. Among other insights, their study shows which metropolitan areas in the US are more or less affordable to renters.\n\n## How the Web works<a id='web'></a>\n\nHere's our high-level description of the web.\n\n**The internet is a bunch of computers connected together.** Some computers are laptops, some are desktops, some are smart phones, some are servers owned by companies. Each computer has its own address on the internet. Using these addresses, **one computer can ask another computer for some information (data). We say that the first computer sends a _request_ to the second computer, asking for some particular information. The second computer sends back a _response_**. The response could include the information requested, or it could be an error message. Perhaps the second computer doesn't have that information any more, or the first computer isn't allowed to access that information.\n\n\n\nWe said that there is an enormous amount of information available on the web. When people put information on the web, they generally have two different audiences in mind, two different types of consumers of their information: humans and computers. If they want their information to be used primarily by humans, they'll make a website. This will let them lay out the information in a visually appealing way, choose colours, add pictures, and make the information interactive. If they want their information to be used by computers, they'll make a web API. A web API provides other computers structured access to their data. We won't cover APIs in this workshop, but you should know that i) APIs are very common and ii) if there is an API for a website/data source, you should use that over web scraping. Many data sources that you might be interested in (e.g. social media sites) have APIs.\n\n**Websites are just a bunch of files on one of those computers. They are just plain text files, so you can view them if you want. When you type in the address of a website in your browser, your computer sends a request to the computer located at that address. The request says \"hey buddy, please send me the file(s) for this website\". If everything goes well, the other computer will send back the file(s) in the response**. Everytime you navigate to a new website or page in your browser, this process repeats.\n\n\n\n**There are three main languages that that website files are written with: HyperText Markup Language (HTML), Cascading Style Sheets (CSS) and JavaScript (JS)**. They normally have `.html`, `.css` and `.js` file extensions. Each language (and thus each type of file) serves a different purpose. **HTML files are the ones we care about the most, because they are the ones that contain the text you see on a web page**. CSS files contain the instructions on how to make the content in a HTML visually appealing (all the colours, font sizes, border widths, etc.). JavaScript files have the instructions on how to make the information on a website interactive (things like changing colour when you click something, entering data in a form). In this workshop, we're going to focus on HTML.\n\n\n**It's not too much of a simplification to say:**\n\n\\begin{equation}\n\\textrm{Web scraping} = \\textrm{Making a request for a HTML file} + \\textrm{Parsing the HTML response}\n\\end{equation}\n\n## Making a request<a id='request'></a>\n\n**The first step in web scraping is to get the HTML of the website we want to scrape. The [requests](http://docs.python-requests.org/en/master/) library is the easiest way to do this in Python.**\n\n\n```python\nimport requests\n\nurl = 'https://en.wikipedia.org/wiki/Canberra'\n\nresponse = requests.get(url)\n```\n\nGreat, it looks like everything worked! Let's see our beautiful HTML:\n\n\n```python\nresponse\n```\n\nHuh, that's weird. Doesn't look like HTML to me.\n\nWhat the `requests.get` function returned (and the thing in our `response` variable) was a Response object. It itself isn't the HTML that we wanted, but rather a collection of metadata about the request/response interaction between your computer and the Wikipedia server.\n\nFor example, it knows whether the response was successful or not (`response.ok`), how long the whole interaction took (`response.elapsed`), what time the request took place (`response.headers['Date']`) and a whole bunch of other metadata.\n\n\n```python\nresponse.ok\n```\n\n\n```python\nresponse.headers['Date']\n```\n\n**Of course, what we really care about is the HTML content. We can get that from the `Response` object with `response.text`. What we get back is a string of HTML, exactly the contents of the HTML file at the URL that we requested.**\n\n\n```python\nhtml = response.text\nprint(html[:1000])\n```\n\n### Challenge\n\nGet the HTML for [the Wikipedia page about HTML](https://en.wikipedia.org/wiki/HTML). \nPrint out the first 1000 characters and compare it to the HTML you see when you view the source HTML in your broswer.\n\n\n```python\n# your solution here\n```\n\n\n```python\n# solution\nurl = 'https://en.wikipedia.org/wiki/HTML'\nresponse = requests.get(url)\nhtml = response.text\n```\n\n### Challenge\n\nWrite a function called `get_html` that takes a URL as an argument and returns the HTML contents as a string. Test your function on the page for [Sir Tim Berners-Lee](https://en.wikipedia.org/wiki/Tim_Berners-Lee).\n\n\n```python\n# your solution here\n```\n\n\n```python\n# solution\ndef get_html(url):\n    response = requests.get(url)\n    return response.text\n\nurl = 'https://en.wikipedia.org/wiki/Tim_Berners-Lee'\nhtml = get_html(url)\n```\n\n### Challenge\n\nWhat happens if the request doesn't go so smoothly? Add a defensive measure to your function to check that the response recieved was successful.\n\n\n```python\n# your solution here\n```\n\n\n```python\n# solution\ndef get_html(url):\n    response = requests.get(url)\n    assert response.ok, \"Whoops, this request didn't go as planned!\"\n    return response.text\n    \n\nurl = 'https://en.wikipedia.org/wiki/Tim_Berners-Lee'\nhtml = get_html(url)\n```\n\n## Parsing HTML<a id='parsing'></a>\n\n**The second step in web scraping is parsing HTML. This is where things can get a little tricky.** \n\n**Imagine you're in the field of education, in fact your specialty is studying higher education institutions. You're wondering how different disciplines change over time. Is it true that disciplines are incorporating more computational techniques as the years go on? Is that true for all disciplines or only some? Can we spot emerging themes across a whole university?**\n\n**To answer these questions, we're going to need data. We're going to collect a dataset of all courses registered at UC Berkeley, not just those being taught this semester but all courses currently approved to be taught. These are listed on [this page](http://guide.berkeley.edu/courses/), called the Academic Guide. Well, actually they're not directly listed on that page. That page lists the departments/programs/units that teach currently approved courses. If we click on each department (for the sake of brevity, I'm just going to call them all \"departments\"), we can see the list of all courses they're approved to teach. For example, [here's](http://guide.berkeley.edu/courses/aerospc/) the page for Aerospace Studies. We'll call these pages departmental pages.**\n\n### Challenge\n\nView the source HTML of [the page listing all departments](http://guide.berkeley.edu/courses/), and see if you can find the part of the HTML where the departments are listed. There's a lot of other stuff in the file that we don't care too much about. You could try `Crtl-F`ing for the name of a department you can see on the webpage.\n\n\n\n\n\n\n\n**Solution**\n\nYou should see something like this:\n\n\n```\n<div id=\"atozindex\">\n<h2 class=\"letternav-head\" id='A'><a name='A'>A</a></h2>\n<ul>\n<li><a href=\"/courses/aerospc/\">Aerospace Studies (AEROSPC)</a></li>\n<li><a href=\"/courses/africam/\">African American Studies (AFRICAM)</a></li>\n<li><a href=\"/courses/a,resec/\">Agricultural and Resource Economics (A,RESEC)</a></li>\n<li><a href=\"/courses/amerstd/\">American Studies (AMERSTD)</a></li>\n<li><a href=\"/courses/ahma/\">Ancient History and Mediterranean Archaeology (AHMA)</a></li>\n<li><a href=\"/courses/anthro/\">Anthropology (ANTHRO)</a></li>\n<li><a href=\"/courses/ast/\">Applied Science and Technology (AST)</a></li>\n<li><a href=\"/courses/arabic/\">Arabic (ARABIC)</a></li>\n<li><a href=\"/courses/arch/\">Architecture (ARCH)</a></li>\n```\n\n**This is HTML. HTML uses \"tags\", code that surrounds the raw text which indicates the structure of the content. The tags are enclosed in `<` and `>` symbols. The `<li>` says \"this is a new thing in a list and `</li>` says \"that's the end of that new thing in the list\". Similarly, the `<a ...>` and the `</a>` say, \"everything between us is a hyperlink\". In this HTML file, each department is listed in a list with `<li>...</li>` and is also linked to its own page using `<a>...</a>`. In our browser, if we click on the name of the department, it takes us to that department's own page. The way the browser knows where to go is because the `<a>...</a>` tag tells it what page to go to. You'll see inside the `<a>` bit, there's a `href=...`. That tells us the (relative) location of the page it's linked to.**\n\n\n\n### Challenge\n\nLook at HTML source of [the page for the Aerospace Studies department](http://guide.berkeley.edu/courses/aerospc/), and try to find the part of the file where the information on each course is. Again, try searching for it using `Crtl-F`.\n\n**Solution**\n\n\n```\n<div class=\"courseblock\">\n\n<button class=\"btn_toggleCoursebody\" aria-expanded=\"false\" aria-controls=\"cb_aerospc1a\" data-toggle=\"#cb_aerospc1a\">\n\n<a name=\"spanaerospc1aspanspanfoundationsoftheu.s.airforcespanspan1unitspan\"></a>\n<h3 class=\"courseblocktitle\">\n<span class=\"code\">AEROSPC 1A</span> \n<span class=\"title\">Foundations of the U.S. Air Force</span> \n<span class=\"hours\">1 Unit</span>\n</h3>\n```\n\nThe content that we care about is enclosed within HTML tags. It looks like the course code is enclosed in a `span` tag, which has a `class` attribute with the value `\"code\"`. What we'll have to do is extract out the information we care about by specifying what tag it's enclosed in.\n\nBut first, we're going to need to get the HTML of the first page.\n\n### Challenge\n\nGet the HTML content of `http://guide.berkeley.edu/courses/` and store it in a variable called `academic_guide_html`. You can use the `get_html` function you wrote before.\n\nPrint the first 500 characters to see what we got back.\n\n\n```python\n# your solution here\n```\n\n\n```python\n# solution\nacademic_guide_url = 'http://guide.berkeley.edu/courses/'\nacademic_guide_html = get_html(academic_guide_url)\nprint(academic_guide_html[:500])\n```\n\nGreat, we've got the HTML contents of the Academic Guide site we want to scrape. Now we can parse it. [\"Parsing\"](https://en.wikipedia.org/wiki/Parsing) means to turn a string of data into a structured representation. When we're parsing HTML, we're taking the Python string and turning it into a tree. The Python package `BeautifulSoup` does all our HTML parsing for us. We give it our HTML as a string and it returns a parsed HTML tree. Here, we're also telling BeautifulSoup to use the `lxml` parser behind the scenes.\n\n\n```python\nfrom bs4 import BeautifulSoup\n\nacademic_guide_soup = BeautifulSoup(academic_guide_html, 'lxml')\n```\n\nWe said before that all the departments were listed on the Academic Guide page with links to their departmental page, where the actual courses are listed. So we can find all the departments by looking in our parsed HTML for all the links. Remember that the links are represented in the HTML with the `<a>...</a>` tag, so we ask our `academic_guide_soup` to find us all the tags called `a`. What we get back is a list of all the `a` elements in the HTML page.\n\n\n```python\nlinks = academic_guide_soup.find_all('a')\n# print a random link element\nlinks[48]\n```\n\nSo now we have a list of `a` elements, each one represents a link on the Academic Guide page. But there are other links on this page in addition to the ones we care about, for example, a link back to the UC Berkeley home page. How can we filter out all the links we don't care about?\n\n### Challenge\n\nLook through the list `links`, or the HTML source, and figure out how we can identify just the links that we care about, namely the links to departmental pages.\n\n\n```python\n# your solution here\n```\n\n\n```python\n# solution\nimport re\n\ndef is_departmental_page(link):\n    \"\"\"\n    Return true if `link` points to a departmental page.\n    \n    By examining the source HTML by eye, I noticed that \n    the links we care about (i.e. the departmental pages) \n    all point to a relative path that starts with \"/courses/\".\n    This function uses that idea to determine if the link is \n    a departmental page.\n    \"\"\"\n    # some links don't have a href attribute, only a name attribute\n    # we don't care about them\n    try:\n        href = link.attrs['href'] \n    except KeyError:\n        return False\n    pattern = r'/courses/(.*)/'\n    match = re.search(pattern, href)\n    return bool(match)\n\nprint(links[0])\nprint(is_departmental_page(links[0]))\nprint()\nprint(links[48])\nprint(is_departmental_page(links[48]))\n```\n\nLet's use our new `is_departmental_page` function to filter out the links we don't care about. How many departments do we have?\n\n\n```python\ndepartmental_page_links = [link for link in links if is_departmental_page(link)]\nlen(departmental_page_links)\n```\n\nEach link in our `departmental_page_links` list contains a HTML element representing a link. Each element contains not only the relative location of the link but also the text that is linked (i.e. the words on the page that are underlined and you can click on to go to the linked page). In BeautifulSoup, we can get that text by asking for it with `element.text`, like this:\n\n\n```python\ndepartmental_page_links[0].text\n```\n\n### Challenge\n\nFrom the `departmental_page_links`, we can extract out the name and the code for each department. Try doing this.\n\n\n```python\n# your solution here\n```\n\n\n```python\n# solution\nimport re\n\ndef extract_department_name_and_code(departmental_link):\n    \"\"\"\n    Return the (name, code) for a department.\n    \n    The easiest way to do this is to use regular expressions. \n    We're not going to cover regular expressions in this workshop, \n    but here's how to do it anyway.\n    \"\"\"\n    text = departmental_link.text\n    pattern = r'([^(]+) \\((.*)\\)'\n    match = re.search(pattern, text)\n    if match:\n        return match.group(1), match.group(2)\n\nextract_department_name_and_code(links[48])\n```\n\nFrom each link in our `departmental_page_links` list, we can get the relative link that it points to like this:\n\n\n```python\ndepartmental_page_links[0].attrs['href']\n```\n\n### Challenge\n\nWrite a function that extracts out the relative link of a link element.\n\n*Hint: This has a similar solution to our `is_departmental_page` function from before.*\n\n\n```python\n# your solution here\n```\n\n\n```python\n# solution\ndef extract_relative_link(departmental_link):\n    \"\"\"\n    We noted above that all the departmental links point to \"/courses/something/\", \n    where the \"something\" looks a lot like their code. This function \n    extracts out that \"something\", so we can add it to the base URL of \n    the Academic Guide page and get full paths to each departmental page.\n    \"\"\"\n    href = departmental_link.attrs['href']\n    pattern = r'/courses/(.*)/'\n    match = re.search(pattern, href)\n    if match:\n        return match.group(1)\n\nextract_relative_link(departmental_page_links[0])\n```\n\nAlright! Now we've identified all the departmental links on the Academic Guide page, we've found their name and code, and we know the relative link they point to. Next, we can use this relative link to construct the full URL they point to, which we'll then use to scrape the HTML for each departmental page.\n\nLet's write a function that takes a departmental link and returns the absolute URL of its departmental page.\n\n\n```python\ndef construct_absolute_url(departmental_link):\n    relative_link = extract_relative_link(departmental_link)\n    return academic_guide_url + relative_link\n\nconstruct_absolute_url(departmental_page_links[37])\n```\n\nTo summarize so far, we've gone from the URL of the Academic Guide website, found all the departments that offer approved courses, identified their name and code and the link to their departmental page which lists all the courses they teach. \n\nNow we want to find the get the HTML for each departmental page and scrape it for all the courses they offer. Let's focus on one page for now, the Aerospace Studies page. Once we select the link, we use our functions from above to: i) get the name (I guess we already know it's Aerospace, but whatever) and code, get the full URL, get the HTML for that URL and then parse the HTML.\n\n\n```python\naerospace_link = departmental_page_links[0]\naerospace_name, aerospace_code = extract_department_name_and_code(aerospace_link)\naerospace_url = construct_absolute_url(aerospace_link)\naerospace_html = get_html(aerospace_url)\naerospace_soup = BeautifulSoup(aerospace_html, 'lxml')\nprint(aerospace_html[:500])\n```\n\nRight at the start of this section on parsing HTML, we saw the HTML for a departmental page. Here it is again.\n\n```\n<div class=\"courseblock\">\n\n<button class=\"btn_toggleCoursebody\" aria-expanded=\"false\" aria-controls=\"cb_aerospc1a\" data-toggle=\"#cb_aerospc1a\">\n\n<a name=\"spanaerospc1aspanspanfoundationsoftheu.s.airforcespanspan1unitspan\"></a>\n<h3 class=\"courseblocktitle\">\n<span class=\"code\">AEROSPC 1A</span> \n<span class=\"title\">Foundations of the U.S. Air Force</span> \n<span class=\"hours\">1 Unit</span>\n</h3>\n```\n\nIt looks like each course is listed in a `div` element that has a `class` attribute with value `\"courseblock\"`. We can use this information to identify all the courses on a page and then extract out the information from them. You've seen how to do this before, here it is again:\n\n\n```python\naerospace_courseblocks = aerospace_soup.find_all(class_='courseblock')\nlen(aerospace_courseblocks)\n```\n\nLooks like the Aerospace department has seven current courses they're approved to teach (at the time of writing). Looking at the page in our browser, that looks right to me! So now we have a list called `aerospace_courseblocks` that holds seven elements that each refer to one course taught by the Aerospace department. Now we can extract out any information we care about. We just have to look at the page in our browser, decide what information we care about, then look at the HTML source to see where that information is kept in the HTML structure. Finally, we write a function for each piece of information we want to extract out of a course.\n\n### Challenge\nWrite functions to take a courseblock and extract:\n- The course code (e.g. AEROSPC 1A)\n- The coure name\n- The number of units\n- The textual description of the course\n\n\n```python\n# your solution here\n```\n\n\n```python\n# solution\ndef extract_course_code(courseblock):\n    span = courseblock.find(class_='code')\n    return span.text\n\ndef extract_course_title(courseblock):\n    span = courseblock.find(class_='title')\n    return span.text\n\ndef extract_course_units(courseblock):\n    span = courseblock.find(class_='hours')\n    return span.text\n\ndef extract_course_description(courseblock):\n    span = courseblock.find(class_='coursebody')\n    return span.text\n\ndef extract_one_course(courseblock):\n    course = {}\n    course['course_code'] = extract_course_code(courseblock)\n    course['course_title'] = extract_course_title(courseblock)\n    course['course_units'] = extract_course_units(courseblock)\n    course['course_description'] = extract_course_description(courseblock)\n    return course\n\nfirst_aerospace_course = extract_one_course(aerospace_courseblocks[0])\nfor value in first_aerospace_course.values():\n    print(value)\n    print()\n```\n\nLet's write a function to scrape these four pieces of information from every course from every department and save it as a csv file.\n\n\n```python\ndef scrape_one_department(department_link):\n    department_name, department_code = extract_department_name_and_code(department_link)\n    department_url = construct_absolute_url(department_link)\n    department_html = get_html(department_url)\n    department_soup = BeautifulSoup(department_html, 'lxml')\n    department_courseblocks = department_soup.find_all(class_='courseblock')\n    result = []\n    for courseblock in department_courseblocks:\n        course = extract_one_course(courseblock)\n        course['department_name'] = department_name\n        course['department_code'] = department_code\n        result.append(course)\n    return result\n\naerospace_courses = scrape_one_department(aerospace_link)\nfor value in aerospace_courses[0].values():\n    print(value)\n    print()\n```\n\n\n```python\nimport time\n\ndef scrape_all_departments(be_nice=True):\n    academic_guide_url = 'http://guide.berkeley.edu/courses/'\n    academic_guide_html = get_html(academic_guide_url)\n    academic_guide_soup = BeautifulSoup(academic_guide_html, 'lxml')\n    links = academic_guide_soup.find_all('a')\n    departmental_page_links = [link for link in links if is_departmental_page(link)]\n    \n    result = []\n    for departmental_page_link in departmental_page_links:\n        department_result = scrape_one_department(departmental_page_link)\n        result.extend(department_result)\n        if be_nice:\n            time.sleep(1)\n    return result\n```\n\n\n```python\nimport pandas as pd\nresult = scrape_all_departments(be_nice=False)\ndf = pd.DataFrame(result)\nprint(str(len(df)) + ' courses scraped')\ndf.head()\n```\n\n9360 courses scraped! (At the time of writing). Wow, that was a lot easier than doing it by hand!\n\n## Terms of Service<a id='terms'></a>\n\nAs you've seen, web scraping involves making requests from other computers for their data. It costs people money to maintain the computers that we request data from: it needs electricity, it requires staff, sometimes you need to upgrade the computer, etc. But we didn't pay anyone for using their resources.\n\nBecause we're making these requests programmatically, we could make many, many requests per second. For example, we could put a request in a never-ending loop which would constantly request data from a server. But computers can't handle too much traffic, so eventually this might crash someone else's computer. Moreover, if we make too many requests when we're web scraping, that might restrict the number of people who can view the web page in their browser. This isn't very nice.\n\nWebsites often have Terms of Service, documents that you agree to whenever you visit a site. Some of these terms prohibit web scraping, because it puts too much strain on their servers, or they just don't want their data accessed programmatically. Whatever the reason, we need to respect a websites Terms of Service. **Before you scrape a site, you should always check its terms of service to make sure it's allowed.**\n\nOften, there are better ways of accessing the same data. For the Wikipedia sites we scraped, there's actually an [API](https://www.mediawiki.org/wiki/REST_API) that we could have used. In fact, Wikipedia would prefer that we access their data that way. There's even a [Python package](https://pypi.org/project/wikipedia/) that wraps around this API to make it even easier to use. Furthermore, Wikipedia actually makes all of its content available for [direct download](https://dumps.wikimedia.org/). **The point of the story is: before web scraping, see if you can get the same data elsewhere.** This will often be easier for you and preferred by the people who own the data.\n\nMoreover, if you're affiliated with an institution, you may be breaching existing contracts by engaging in scraping. UC Berkeley's Library [recommends](http://guides.lib.berkeley.edu/text-mining) following this workflow:\n\n\n\n## Further resources<a id='resources'></a>\n\n### Resources for learning\n\n* Work through this notebook in full.\n    * _We glossed over a lot of details. As your next step, I'd suggest spending as much time as you need to understand every line of text and code in this notebook._\n\n* [Web-scraping with Python](http://shop.oreilly.com/product/0636920078067.do)\n\n    * _A great textbook for learning more about web scraping using Python._\n\n* [Fantastic Data and Where To Find Them: An introduction to APIs, RSS, and Scraping](https://www.youtube.com/watch?v=A42voDYkFZw)\n\n    * This is a recorded video of a workshop on collecting data via the web at PyCon, a Python conference._\n\n* [D-Lab workshops](http://dlab.berkeley.edu/training)\n\n    * _We teach workshops on web scraping and NLP-related tools throughout the semester. Check this page for the latest scheduled workshops._\n\n* [D-Lab consulting](http://dlab.berkeley.edu/consulting)\n\n    * _We also offer free consulting for members of UC Berkeley's community. Reach out to us if you ever need a hand with a web scraping or NLP project!_\n\n\n### A few libraries to be aware of\n\n* [requests-HTML](http://html.python-requests.org/)\n\n    * _Did you see how easy it was to request data using the `requests` library? Well the author of that library, Kenneth Reitz, has another library for parsing HTML. I'm not that familiar with it, but it looks promising if it's by Reitz!_\n\n* [furl](https://github.com/gruns/furl)\n\n    * _Lets you extract out different parts of a URL._\n\n* [cssutils](http://cthedot.de/cssutils/)\n\n    * _We didn't talk about CSS at all, but you can also scrape data depending on its visual characteristics. This is a great library for parsing CSS files, but you can get some of the same functionality with BeautifulSoup._\n\n* [scrapy](https://scrapy.org/)\n\n    * _Need to do some serious web scraping? You'll wanna check out Scrapy._\n\n* [newspaper](https://newspaper.readthedocs.io/en/latest/)\n\n    * _If you know you're focussed on newspaper articles, this is a great little library for parsing common formats._\n", "meta": {"hexsha": "b8da1d9d2152ec55b8fa004986c885a2635776a7", "size": 38603, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "workbook.ipynb", "max_stars_repo_name": "TextXD/introduction-to-web-scraping", "max_stars_repo_head_hexsha": "a5bf8c1b4aafa992bbaafb460e7c43fe7e07db59", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-12-05T22:55:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-15T02:25:55.000Z", "max_issues_repo_path": "workbook.ipynb", "max_issues_repo_name": "TextXD/introduction-to-web-scraping", "max_issues_repo_head_hexsha": "a5bf8c1b4aafa992bbaafb460e7c43fe7e07db59", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-12-05T21:08:20.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-05T21:37:39.000Z", "max_forks_repo_path": "workbook.ipynb", "max_forks_repo_name": "TextXD/introduction-to-web-scraping", "max_forks_repo_head_hexsha": "a5bf8c1b4aafa992bbaafb460e7c43fe7e07db59", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-12-05T20:57:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-18T19:46:35.000Z", "avg_line_length": 42.5611907387, "max_line_length": 898, "alphanum_fraction": 0.6383959796, "converted": true, "num_tokens": 6658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.04468087090869867, "lm_q2_score": 0.06560483563216184, "lm_q1q2_score": 0.0029312811918670175}}
{"text": "Aside: [http://illinois.edu/calendar/detail/990/33249682](http://illinois.edu/calendar/detail/990/33249682)\n\n\n\n# Non-Proliferation and Safeguards\n\nThis unit covers discussions of nuclear non-proliferation and safeguards in the context of nuclear power and the nuclear fuel cycle. \n\n\n```python\nfrom IPython.display import IFrame\nIFrame(\"https://embed.polleverywhere.com/free_text_polls/LaKxXWF9y4JKkue?short_poll=true\", width=\"700\", height=\"400\")\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\nIFrame(\"https://embed.polleverywhere.com/multiple_choice_polls/YiHjKwlUd1Cit6s?short_poll=true\", width=\"700\", height=\"400\")\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\nIFrame(\"https://embed.polleverywhere.com/free_text_polls/lBcbliuSuQGKea6?short_poll=true\", width=\"700\", height=\"400\")\n```\n\n\n\n\n\n\n\n\n\n\n\n<center>Source: [Huck Magazine, Photography by Campaign for Nuclear Disarmament](http://www.huckmagazine.com/perspectives/activism-2/anti-nuclear-protest-art-will-stop-tracks/)</center>\n\n## Learning Objectives\n\nAt the end of this lesson, you will be equipped to:\n\n- Recognize the position and history of movements against nuclear weapons.\n- List key events in the history of nuclear weapons.\n- Identify nuclear weapons states.\n- Characterize the agreements between nuclear weapons states.\n- Analyze the relationship between nuclear weapons and nuclear power.\n- Name the national and international agencies responsible for enforcing non-proliferation treaties.\n- Recognize methods used to enforce nuclear safeguards.\n- Apply knowledge of the NPT to current and recent events. \n- Differentiate between fact and fiction. \n- Discuss the failures of our nuclear weapons program (Bikini Atoll, \n\n\n## Art to Consider\n\n\n\n\n\n### Hiroshima survivor Hiroharu Kono\n\n\n\n\n### Yusaku Kamekura\n\n\n\n# How Did We Get Here?\n\n\n\n\n## The Making of the Atomic Bomb\n\nThe best way to learn about this topic is to read Richard Rhodes excellent book, The Making of The Atomic Bomb. \n\n\n\nHowever, let's summarize:\n\n### 1930 \nGerman nationalists acheive shocking election victory.\n\n\n### 1938 \nTheory of Nuclear Fission (Discovered on December 17,  1938 and explained theoretically in January 1939).\n\n\n### 1939\n Szilard and Wigner draft the Einstein-Szilard letter. \n\n<a title=\"Albert Einstein [Public domain], via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File%3AEinstein-Roosevelt-letter.png\"></a>\n\n### 1940 - 1946\nManhattan Project\n\n\n\n\n\n\n\n\n\n\n### July, 16 1945 \n\n- Trinity Nuclear Test\n- \"The Gadget\"/\"Fat Man\"\n  - 6.19-kilogram (13.6 lb) Pu\n  - Implosion type plutonium weapon\n  - energy equivalent of 22 kilotons of TNT (92 TJ)\n  \n<a title=\"By Berlyn Brixner [Public domain], via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File%3ATrinity_Test_Fireball_16ms.jpg\"></a>\n\n\n\n### 8:15 a.m., August 6, 1945\n\n- Hiroshima\n- population 340,000 - 350,000\n- Enola Gay, B-29\n- \"Little Boy\"\n  - contained 64 kg (141 lb) of enriched uranium.\n  - less than 1 kg completely detonated.\n  - energy equivalent of 15 kilotons of TNT (63 TJ).\n  - gun type.\n- 70,000 people dead instantly. \n- 90,000\u2013166,000 after the first year. About 70% of the city's buildings were destroyed, and another 7% severely damaged.\n\n<a title=\"By US government DOD and/or DOE photograph [Public domain], via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File%3ALittle_boy.jpg\"></a>\n\n### 11:02 a.m., August 9, 1945\n\n\n- Nagasaki.\n- population 263,000\n- Bockscar, B-29\n- \"Fat Man\"\n  - contained 14 pounds (6.4 kg) Pu\n  - energy equivalent of 21 kilotons of TNT (88 TJ; 1 g mass equivalent)\n  - implosion type\n- 35,000 people were killed instantly\n- 39,000 - 80,000 by the end of 1945\n- Fireball temp 3,900 \u00b0C (7,050 \u00b0F) \n- Winds over 1,000 km/h (620 mph)\n\n<a title=\"By U.S. Department of Defense (U.S. Department of Defense) [Public domain], via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File%3AFat_man.jpg\"></a>\n\n### 6:45 a.m., March 1, 1954\n\n\n- Castle Bravo.\n- dry fuel hydrogen bomb\n- energy released: 15 megatons of TNT\n- vastly exceeded expected  4 to 8 megatons (because of an unexpectedly high involvement of lithium-7 in the fusion reaction)\n- shifting winds ---> greatest contamination every perpetrated by the U.S. \n- Japanese fishing boat (fishermen died, contaminated fish were sold)\n\n\n\n\n\n### 11:32 a.m. October 30, 1961\n\n- Tsar Bomba / Ivan / Vanya\n- Soviet RDS-220, three-stage hydrogen bomb\n  - 2nd/3rd stages had 238U \"tamper\" to reduce fast fissions & fallout\n  - 97% of the total yield resulted from thermonuclear fusion\n  - energy released: 50 megaton TNT (210 PJ)\n\n\n<a title=\"By Fastfission [Public domain], via Wikimedia Commons\" href=\"https://commons.wikimedia.org/wiki/File%3AComparative_nuclear_fireball_sizes.svg\"></a>\n\n### October 16\u201328, 1962 \nCuban Missile Crisis\n\n### 1963\nPartial test ban treaty. \n\n\n## 1970 : NPT\n\nOpened for signature in 1968, the treaty entered into force in 1970\n\n\nThe goals of the NPT were to: \n\n- Prevent the spread of nuclear weapons\n- Promote cooperation in peaceful uses of nuclear technology\n- Acheive nuclear disarmament\n\nAccordingly: \n\n- Countries with weapons (UK, US, USSR, France, China) agree not to share.\n- Countries without nuclear weapons promised not to develop them in return for nuclear power technology.\n- Those that already have weapons agreed to disarm. (Article 6: Countries must \"negotiate in good faith.\")\n\nNPT is reviewed annually. \n\n### Membership\n\n<p><a href=\"https://commons.wikimedia.org/wiki/File:NPT_parties.svg#/media/File:NPT_parties.svg\"></a><br>By <a href=\"//commons.wikimedia.org/wiki/File:NPT_Participation.svg\" title=\"File:NPT Participation.svg\">File:NPT Participation.svg</a>: <a href=\"//commons.wikimedia.org/wiki/User:Allstar86\" title=\"User:Allstar86\">Allstar86</a>, <a href=\"//commons.wikimedia.org/wiki/User:L.tak\" title=\"User:L.tak\">L.tak</a>, <a href=\"//commons.wikimedia.org/w/index.php?title=User:Danlaycock&amp;action=edit&amp;redlink=1\" class=\"new\" title=\"User:Danlaycock (page does not exist)\">Danlaycock</a>\nderivative work: <a href=\"//commons.wikimedia.org/w/index.php?title=User:Danlaycock&amp;action=edit&amp;redlink=1\" class=\"new\" title=\"User:Danlaycock (page does not exist)\">Danlaycock</a> - This file was derived from:\n&nbsp;<a href=\"//commons.wikimedia.org/wiki/File:NPT_Participation.svg\" title=\"File:NPT Participation.svg\">NPT Participation.svg</a>, <a href=\"http://creativecommons.org/licenses/by-sa/3.0\" title=\"Creative Commons Attribution-Share Alike 3.0\">CC BY-SA 3.0</a>, <a href=\"https://commons.wikimedia.org/w/index.php?curid=31123238\">Link</a></p>\n\n\n\n\n#### Renegged\nOnly North Korea has backed out of their agreement. \n\n\n#### Never signed\n\nIndian, Pakistan, and Israel never joined. All three now have weapons. \n\n\n\n\n### 1996 \n\nComprehensive Test Ban Treaty\n\n\n## Megatons to Megawatts (1993 - 2003)\n\n- **20** year program\n- **500 tons** of HEU (**90%** enriched)\n- Soviet era warheads -> downblended to $<5\\%$ enriched \n- To be mplemented on commercial terms without government funds. \n  - United States named Enrichment Corporation (USEC) as the commercial agent\n  - the Russian Federation designated Techsnabexport (TENEX) as its commercial agent.\n- The first shipment of LEU took place in May 1995.\n\n\n\n\n\n**Practice: Can You prove this is an accurate statement?**\n\n\nThink back to enrichment. This is another feed factor problem. \n\n\\begin{align}\nx_p &= 0.05\\\\\nx_w &= 0.002\\\\\nx_f &= 0.9\\\\\n\\end{align}\n\nThus, we can find the feed factor (kg feed per kg enriched):\n\n\\begin{align}\nFF &= \\frac{F}{P}\\\\\n   &= \\frac{x_p - x_w}{x_f - x_w}\\\\\n   &= \\frac{0.05 - 0.002}{0.9 - 0.002}\\\\\n   & \\\\\n   &= 0.0535\n\\end{align}\n\nWe also know the amount of feed, F, was 500 tons.\n\n\\begin{align}\nFF = \\frac{F}{P}\\\\\nFF = 0.0535\\\\\nF = 5.0\\times 10^5\\\\\n\\end{align}\n\n\n```python\nF = 500000 # kg\nx_p = 0.05  # sold to US\nx_w = 0.002 # depleted U\nx_f = 0.9   # feed from  HEU\n\ndef ff(x_p, x_w, x_f):\n    num = x_p - x_w\n    denom = x_f - x_w\n    return num/denom\n\nprint(ff(x_p, x_w, x_f), \n      \" kg of the HEU are needed to produce 1kg fuel.\")\nprint(\"Therefore, \",1/ff(x_p, x_w, x_f),\n      \" kg of the new will be produced per kg of HEU\")\nprint(\"Therefore, \",F/ff(x_p, x_w, x_f),\n      \" kg of the new low enriched uranium was produced\")      \n\n```\n\n    0.053452115812917596  kg of the HEU are needed to produce 1kg fuel.\n    Therefore,  18.708333333333332  kg of the new will be produced per kg of HEU\n    Therefore,  9354166.666666666  kg of the new low enriched uranium was produced\n\n\nNow, based on our fuel utilization discussions, how many MWh is that?\n\n\\begin{align}\nM = \\frac{Q}{BU}\\\\\nQ = \\frac{P_0 \\cdot CF \\cdot T}{\\eta_{th}}\\\\\n\\end{align}\n\nWe want to solve for $P_0 CF T$, which will be in units of MWd (and we can convert to MWh.)\n\\begin{align}\n\\Rightarrow &M = \\frac{P_0 \\cdot CF \\cdot T}{\\eta_{th}BU}\\\\\n\\Rightarrow &\\frac{M}{CF} = \\frac{P_0 \\cdot CF \\cdot T}{\\eta_{th}BU}\\\\\n\\Rightarrow &P_0 \\cdot CF \\cdot T [MWh] = M\\eta_{th}BU[MWd]\\times 24 \\left[\\frac{h}{d}\\right]  \\\\\n\\end{align}\n\n\nSo, let's assume some typical values appropriate for 5% enriched fuel (this will give high-ish burnups).\n\n\\begin{align}\n\\eta_{th} = 0.33\\mbox{ [MWe/MWth]}\\\\ \nBU = 50000\\mbox{ [MWd/ton] } = 50 \\mbox{ [MWd/kg] }\\\\\n\\end{align}\n\n\n```python\nM = F/ff(x_p, x_w, x_f)\n#cf = 0.90\neta = 0.37\nh_per_d = 24\nbu = 50\n\nPCFT = M*eta*bu*h_per_d\nprint(\"And finally, the program produced \",'%e' % PCFT, \" MWh.\")\n```\n\n    And finally, the program produced  4.153250e+09  MWh.\n\n\n\n```python\n\nfrom IPython.core.display import HTML\nHTML(\"\"\"<video controls src=\"{0}\" loop=1 autoplay width=100%/>\"\"\".format('https://img.buzzfeed.com/buzzfeed-static/static/2014-07/3/11/enhanced/webdr04/anigif_enhanced-buzz-21275-1404402138-31.gif?output-format=mp4'))\n\n```\n\n\n\n\n<video controls src=\"https://img.buzzfeed.com/buzzfeed-static/static/2014-07/3/11/enhanced/webdr04/anigif_enhanced-buzz-21275-1404402138-31.gif?output-format=mp4\" loop=1 autoplay width=100%/>\n\n\n\n\n\n\n# Friday: IAEA, Safeguards, MUF, SQ, Etc.\n\n\n\n\n## IAEA Safeguards\n\n150 million euro per year. \n\nDirector General... \n\n### Material Accountancy\n\n\n## Significant Quantities\nDirect use nuclear material\n\n|======|========|======|\n| Pu    | \t8 kg  | Pu | \n| 233U\t | 8 kg  | 233U |\n| HEU (235U < 20%) | \t25 kg 235U |  | \n| Indirect use nuclear material | | |\n| U(235U < 20%)b |\t75 kg 235U | (or 10 t natural U | | \n| Th\t| 20 t |  Th |\n\n\n### Example: Significant Quantity of Enriched U\n\nDetermine the \n\n### Locks and Surveillance\n\n## Material Unaccounted For\n\n$$MUF = (PB + X - Y) - PE$$\n\n\nPB = Beginning Physical inventory\nX = Increases to inventory\nY = Removal from inventory\nPE = Ending Physical inventory\n\n- Understand the concepts of detection, delay, and response technologies.\n- Formulate different response strategies (including deterrence, denial, containment, pursuit, and recapture) for different facilities and considering on-site and/or o ff-site response.\n- Defense-in-depth\n- PRA\n- Knowledge of the history o f nuclear weapons development\n- Know the countries who have developed nuclear weapons and the political reasons for their development\n- Understand the skills, capabilities, and materials needed by a proliferator to produce a nuclear weapon.\n- Knowledge o f current the NPT and the Additional Protocols\n- Be able to calculate HEU and Pu production quantities for various nuclear facilities.\n- Identify proliferation-risks/safeguards-weaknesses in a nuclear fuel cycle or in a collection of facilities.\n- Understand the methods for safeguarding nuclear material at declared facilities and describe the technology used to measure bulk nuclear materials.\n- Describe methods for identifying covert nuclear activities and how they can be applied to treaty verification.\n- Know the types \u201cSpecial Nuclear Material\u201d\n- Understand the types of radiation that is emitted by SNM \n- Understand the challenges o f detecting SNM\n- Be able to calculate uranium enrichment from spectra\n- Know what detection systems should be used and under what circumstances\n- Understand the various forms of SNM for each step o f an open and closed fuel cycle\n- Calculate and identify possible points o f MUF\n- De fine and calculate separative work units for uranium enrichment\n- Be able to describe the methods used for accounting and control of SNM\n- Discuss the elements o f proliferation resistance\n- Know the quantities of SNM created in SNF for various burn-ups and reactor types\n- Statistics applied in safeguards\n- Describe the fundamentals of how nuclear m aterial safeguards are implemented to secure nuclear material from diversion by the country.\n", "meta": {"hexsha": "80ede6276570d592bd3c0704af98d2ef102c39d7", "size": 23710, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "nonproliferation-and-safeguards/nonpro-and-safeguards.ipynb", "max_stars_repo_name": "loumis2/Atomicaristides", "max_stars_repo_head_hexsha": "4f8cf95542a738767d8901835f79e7be580ccf02", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nonproliferation-and-safeguards/nonpro-and-safeguards.ipynb", "max_issues_repo_name": "loumis2/Atomicaristides", "max_issues_repo_head_hexsha": "4f8cf95542a738767d8901835f79e7be580ccf02", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nonproliferation-and-safeguards/nonpro-and-safeguards.ipynb", "max_forks_repo_name": "loumis2/Atomicaristides", "max_forks_repo_head_hexsha": "4f8cf95542a738767d8901835f79e7be580ccf02", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7596899225, "max_line_length": 750, "alphanum_fraction": 0.5923660903, "converted": true, "num_tokens": 3552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.042722193890012965, "lm_q2_score": 0.06754668738548218, "lm_q1q2_score": 0.002885742675110663}}
{"text": "<a href=\"https://colab.research.google.com/github/jfogarty/python-code-practice/blob/master/advanced_outputs.ipynb\" target=\"_parent\"></a>\n\n## Output Handling\n\nIn Colaboratory the output of each cell is hosted in a separate iframe sandbox with limited access to the global notebook environment. APIs are available to enable some Python to Javascript and Javascript to Python communications, these APIs are generally only available for outputs which have been executed in the current session.\n\n\n\n### Viewing Notebooks\n\nColaboratory attempts to provide a rich viewing experience where all resources needed to view outputs are persisted in the notebook itself and can be used for later viewing when not connected to a kernel.\n\nIn cases where outputs require execution to work properly this should be communicated to the user.\n\n## display.Javascript to execute JavaScript from Python\n\nThe Javascript is persisted in the outputs of the notebook document and will be executed when the document is reloaded.\n\n\n```\nimport IPython\njs_code = '''\ndocument.querySelector(\"#output-area\").appendChild(document.createTextNode(\"hello world!\"));\n'''\ndisplay(IPython.display.Javascript(js_code))\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n## Evaluate a Javascript expression from Python with eval_js\n\nEvaluates the Javascript expression within the context of the outputframe of the current cell.\n\nThis executes the Javascript as a blocking call from Python and returns the result of the expression.\n\nIf the Javascript expression results in a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) then the call will block until the promise has settled and use the resulting value.\n\n**Note:** This differs from `display.Javascript` in that the Javascript expression is not persisted in the notebook document and will not be executed when the document is reloaded.\n\n\n\n```\nimport IPython\nfrom google.colab import output\n\ndisplay(IPython.display.Javascript('''\n  window.someValue = new Promise(resolve => {\n    setTimeout(() => {\n      resolve(\"hello world!\");\n    }, 100);\n  });\n'''))\n\n\nvalue = output.eval_js('someValue');\nvalue\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n\n\n    'hello world!'\n\n\n\n## Javascript to Python communication\n\nPython code can register callbacks which can be invoked by Javascript in the outputframe.\n\n**Note:** This is only available to 'trusted' outputs- outputs which have been executed within the current session.\n\n\n```\nimport IPython\nfrom google.colab import output\n\ndef Concat(a, b):\n  # Use display.JSON to transfer a structured result.\n  return IPython.display.JSON({'result': ' '.join((a, b))})\n\noutput.register_callback('notebook.Concat', Concat)\n```\n\n\n```javascript\n%%javascript\n(async function() {\n  const result = await google.colab.kernel.invokeFunction(\n    'notebook.Concat', // The callback name.\n    ['hello', 'world!'], // The arguments.\n    {}); // kwargs\n  const text = result.data['application/json'];\n  document.querySelector(\"#output-area\").appendChild(document.createTextNode(text.result));\n})();\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n### Persisting Updates\n\nSince `invokeFunction` is only available for outputs which have executed within the current session\nthen it may be desirable to update the notebook so the changes take effect on notebook reload. An example\nof doing this.\n\n\n```\nimport IPython\nfrom google.colab import output\n\ndisplay(IPython.display.HTML('''\n    The items:\n    <br><ol id=\"items\"></ol>\n    <button id='button'>Click to add</button>\n    \n    '''))\n\ndef add_list_item():\n  # Use redirect_to_element to direct the elements which are being written.\n  with output.redirect_to_element('#items'):\n    # Use display to add items which will be persisted on notebook reload.\n    display(IPython.display.HTML('<li> Another item</li>'))\n\noutput.register_callback('notebook.AddListItem', add_list_item)\n```\n\n\n\nThe items:\n<br><ol id=\"items\"></ol>\n<button id='button'>Click to add</button>\n\n\n\n\n### Using register_callback to make a button invoke a function\n\n\n```\nimport IPython\nimport uuid\nfrom google.colab import output\n\nclass InvokeButton(object):\n  def __init__(self, title, callback):\n    self._title = title\n    self._callback = callback\n\n  def _repr_html_(self):\n    callback_id = 'button-' + str(uuid.uuid4())\n    output.register_callback(callback_id, self._callback)\n\n    template = \"\"\"<button id=\"{callback_id}\">{title}</button>\n        \"\"\"\n    html = template.format(title=self._title, callback_id=callback_id)\n    return html\n\ndef do_something():\n  print('here')\n\nInvokeButton('click me', do_something)\n```\n\n\n\n\n<button id=\"button-508b2891-2393-4644-a7e8-68e99af5f509\">click me</button>\n        \n\n\n\n## Tagged Outputs\n\nOutput tagging is useful for removing or replacing chunks of outputs from Python.\n\n\n```\nimport time\nimport sys\nfrom google.colab import output\n\nprint('Starting.')\n\nwith output.use_tags('some_outputs'):\n  sys.stdout.write('working....\\n')\n  sys.stdout.flush();\n  time.sleep(2)\n\n  sys.stdout.write('still working...\\n')\n  sys.stdout.flush();\n  time.sleep(2)\n\n# Now clear the previous outputs.\noutput.clear(output_tags='some_outputs')\nprint('All done!')\n\n```\n\n    Starting.\n    All done!\n\n\n## Pausing output processing\n\nIf your Javascript code is doing an asynchronous operation (such as loading other resources), use `colab.output.pauseOutputUntil` to pause execution of subsequent output messages until the promise has completed.\n\nThis has an additional benefit that when the notebook is later loaded then output will wait for all messages and pauses to complete before resizing the cell, reducing the amount of jank when loading notebooks.\n\n\n```\nimport IPython\n\ndisplay(IPython.display.Javascript('''\n  const promise = new Promise((resolve, reject) => {\n    const script = document.createElement('script');\n    script.src = 'data:,window.value = \"hello world!\"';\n    script.onload = resolve;\n    script.onerror = reject;\n    document.head.appendChild(script);\n  });\n  // Pause subsequent outputs until the script has been loaded.\n  google.colab.output.pauseOutputUntil(promise);\n'''))\n\ndisplay(IPython.display.Javascript('''\n    // Can immediately reference scripts loaded earlier since\n    // output processing was blocked on them.\n    document.body.appendChild(document.createTextNode(window.value));\n'''))\n\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n\n    <IPython.core.display.Javascript object>\n\n\n## Serving resources\n\nOutputs in the browser can request resources from the kernel by requesting `https://localhost:{port}`. The protocol will automatically be translated from `https` to `http` and the `localhost` will be the kernel executing the code.\n\nBy default the responses to any kernel requests will be cached in the notebook JSON to make them available to viewers not connected to the kernel. To skip the caching of resources, set the HTTP header `x-colab-notebook-cache-control: no-cache` to any responses. See the 'Custom server' example below.\n\nOutputs can only request resources from the kernel if they have been executed in the current session, when viewed the outputs will only have access to the cached responses.\n\n### Jupyter nbextensions\nJupyter's nbextensions is a mechanism to bundle resources into Python libraries, see the [documentation](http://testnb.readthedocs.io/en/latest/examples/Notebook/Distributing%20Jupyter%20Extensions%20as%20Python%20Packages.html#Defining-the-server-extension-and-nbextension) for details.\n\nAn example of referencing these resources from outputs:\n\n\n```\n%%html\n<link rel=\"stylesheet\" href=\"/nbextensions/google.colab/tabbar.css\">\n<div class='goog-tab'>\n  Some content\n</div>\n```\n\n\n<link rel=\"stylesheet\" href=\"/nbextensions/google.colab/tabbar.css\">\n<div class='goog-tab'>\n  Some content\n</div>\n\n\n### Custom server\n\nA webserver can be started on the kernel to serve up arbitrary resources.\n\nThe client needs to reference the resource with `https://localhost:{port}` but this will automatically be translated to `http://localhost:{port}`.\n\nBy default responses will be cached in the notebook for offline access.\n\n\n```\nimport portpicker\nimport threading\nimport socket\nimport IPython\n\nfrom six.moves import socketserver\nfrom six.moves import SimpleHTTPServer\n\nclass V6Server(socketserver.TCPServer):\n  address_family = socket.AF_INET6\n\nclass Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):\n  def do_GET(self):\n    self.send_response(200)\n    # If the response should not be cached in the notebook for\n    # offline access:\n    # self.send_header('x-colab-notebook-cache-control', 'no-cache')\n    self.end_headers()\n    self.wfile.write(b'''\n      document.querySelector('#output-area').appendChild(document.createTextNode('Script result!'));\n    ''')\n\nport = portpicker.pick_unused_port()\n\ndef server_entry():\n    httpd = V6Server(('::', port), Handler)\n    # Handle a single request then exit the thread.\n    httpd.serve_forever()\n\nthread = threading.Thread(target=server_entry)\nthread.start()\n\n# Display some HTML referencing the resource.\ndisplay(IPython.display.HTML(''.format(port=port)))\n```\n\n\n\n\n\n## Cross-output communication\n\nThe output of each cell is hosted in a separate sandboxed iframe without direct access to the contents of other cells, but they can create [BroadcastChannel](https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel/BroadcastChannel)s to communicate between cells.\n\n\n```javascript\n%%javascript\nconst listenerChannel = new BroadcastChannel('channel');\nlistenerChannel.onmessage = (msg) => {\n  const div = document.createElement('div');\n  div.textContent = msg.data;\n  document.body.appendChild(div);\n};\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\nThis second cell will be in a separate sandboxed iframe.\n\n\n\n```javascript\n%%javascript\nconst senderChannel = new BroadcastChannel('channel');\nsenderChannel.postMessage('Hello world!');\n```\n\n\n    <IPython.core.display.Javascript object>\n\n\n## Rendering SymPy in Colab\n\nRendering [SymPy](http://www.sympy.org) equations in Colab requires the MathJax javascript library to be available within each cell output. The following defines an execution hook that loads it automatically each time you execute a cell.\n\n\n\n\n```\nfrom IPython.display import Math, HTML\n\ndef load_mathjax_in_cell_output():\n  display(HTML(\"\"))\nget_ipython().events.register('pre_run_cell', load_mathjax_in_cell_output)\n```\n\n\n\n\n\n\n```\n# try it out:\nimport sympy\nsympy.init_printing()\nx = sympy.symbols('x')\nsympy.Integral(sympy.sqrt(1 / x), x)\n```\n\n## Camera Capture\nUsing a webcam to capture images for processing on the runtime.\n\n\n```\nfrom IPython.display import display, Javascript\nfrom google.colab.output import eval_js\nfrom base64 import b64decode\n\ndef take_photo(filename='photo.jpg', quality=0.8):\n  js = Javascript('''\n    async function takePhoto(quality) {\n      const div = document.createElement('div');\n      const capture = document.createElement('button');\n      capture.textContent = 'Capture';\n      div.appendChild(capture);\n\n      const video = document.createElement('video');\n      video.style.display = 'block';\n      const stream = await navigator.mediaDevices.getUserMedia({video: true});\n\n      document.body.appendChild(div);\n      div.appendChild(video);\n      video.srcObject = stream;\n      await video.play();\n\n      // Resize the output to fit the video element.\n      google.colab.output.setIframeHeight(document.documentElement.scrollHeight, true);\n\n      // Wait for Capture to be clicked.\n      await new Promise((resolve) => capture.onclick = resolve);\n\n      const canvas = document.createElement('canvas');\n      canvas.width = video.videoWidth;\n      canvas.height = video.videoHeight;\n      canvas.getContext('2d').drawImage(video, 0, 0);\n      stream.getVideoTracks()[0].stop();\n      div.remove();\n      return canvas.toDataURL('image/jpeg', quality);\n    }\n    ''')\n  display(js)\n  data = eval_js('takePhoto({})'.format(quality))\n  binary = b64decode(data.split(',')[1])\n  with open(filename, 'wb') as f:\n    f.write(binary)\n  return filename\n```\n\n\n\n\n\n\n\n\n\n\n```\nfrom IPython.display import Image\ntry:\n  filename = take_photo()\n  print('Saved to {}'.format(filename))\n  \n  # Show the image which was just taken.\n  display(Image(filename))\nexcept Exception as err:\n  # Errors will be thrown if the user does not have a webcam or if they do not\n  # grant the page permission to access it.\n  print(str(err))\n```\n\n\n\n\n\n\n\n\n\n\n    <IPython.core.display.Javascript object>\n\n\n    Saved to photo.jpg\n\n\n\n    \n\n    \n\n\n## Showing CV2 Images\n\nThe ``cv2.imshow()`` and ``cv.imshow()`` functions from the [opencv-python](https://github.com/skvark/opencv-python) package are incompatible with Jupyter notebook; see https://github.com/jupyter/notebook/issues/3935.\n\nAs a replacement, you can use the following function:\n\n\n```\nfrom google.colab.patches import cv2_imshow\n```\n\n\n\n\n\n\n\n\n\nFor example, here we download and display a PNG image of the Colab logo:\n\n\n```\n!curl -o logo.png https://colab.research.google.com/img/colab_favicon_256px.png\nimport cv2\nimg = cv2.imread('logo.png', cv2.IMREAD_UNCHANGED)\ncv2_imshow(img)\n```\n\n\n```\n\n```\n", "meta": {"hexsha": "7ecc89bd2264209a929e39214aba940a041da4ce", "size": 129180, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "advanced_outputs.ipynb", "max_stars_repo_name": "jfogarty/python-code-practice", "max_stars_repo_head_hexsha": "677861ee23ae98056b5e3c5a77bdda6c0952139d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "advanced_outputs.ipynb", "max_issues_repo_name": "jfogarty/python-code-practice", "max_issues_repo_head_hexsha": "677861ee23ae98056b5e3c5a77bdda6c0952139d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "advanced_outputs.ipynb", "max_forks_repo_name": "jfogarty/python-code-practice", "max_forks_repo_head_hexsha": "677861ee23ae98056b5e3c5a77bdda6c0952139d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 96.1160714286, "max_line_length": 65073, "alphanum_fraction": 0.7955643288, "converted": true, "num_tokens": 2856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09947021388210707, "lm_q2_score": 0.027585285224643135, "lm_q1q2_score": 0.0027439142212941805}}
{"text": "First, we load the pegasus paraphraser.\n\n\n```\n!git clone https://github.com/google-research/pegasus\n%cd pegasus\n!export PYTHONPATH=.\n!pip3 install -r requirements.txt\n```\n\n    Cloning into 'pegasus'...\n    remote: Enumerating objects: 175, done.\u001b[K\n    remote: Total 175 (delta 0), reused 0 (delta 0), pack-reused 175\u001b[K\n    Receiving objects: 100% (175/175), 354.16 KiB | 6.21 MiB/s, done.\n    Resolving deltas: 100% (58/58), done.\n    /content/pegasus\n    Requirement already satisfied: absl-py in /usr/local/lib/python3.6/dist-packages (from -r requirements.txt (line 1)) (0.10.0)\n    Collecting mock\n      Downloading https://files.pythonhosted.org/packages/5c/03/b7e605db4a57c0f6fba744b11ef3ddf4ddebcada35022927a2b5fc623fdf/mock-4.0.3-py3-none-any.whl\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from -r requirements.txt (line 3)) (1.18.5)\n    Collecting rouge-score\n      Downloading https://files.pythonhosted.org/packages/1f/56/a81022436c08b9405a5247b71635394d44fe7e1dbedc4b28c740e09c2840/rouge_score-0.0.4-py2.py3-none-any.whl\n    Collecting sacrebleu\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/a3/c4/8e948f601a4f9609e8b2b58f31966cb13cf17b940b82aa3e767f01c42c52/sacrebleu-1.4.14-py3-none-any.whl (64kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 71kB 3.8MB/s \n    \u001b[?25hCollecting sentencepiece\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/e5/2d/6d4ca4bef9a67070fa1cac508606328329152b1df10bdf31fb6e4e727894/sentencepiece-0.1.94-cp36-cp36m-manylinux2014_x86_64.whl (1.1MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.1MB 11.7MB/s \n    \u001b[?25hCollecting tensorflow-text==1.15.0rc0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/81/2c/57a6cc36f0ee1acf466a71048e2a0a2a01742eef505b3195d0fa27d87968/tensorflow_text-1.15.0rc0-cp36-cp36m-manylinux1_x86_64.whl (8.6MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 8.6MB 13.1MB/s \n    \u001b[?25hCollecting tensor2tensor==1.15.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/0f/a6/0f6a95a5548cf9fbfed0bbec69959355bda594e85298ebbba5f808ca0fc5/tensor2tensor-1.15.0-py2.py3-none-any.whl (1.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.4MB 44.0MB/s \n    \u001b[?25hCollecting tfds-nightly\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/f2/7d/93c957b63baed31cd9660c49c393bf7f2eb5b24524c59311053efbb03af0/tfds_nightly-4.1.0.dev202012140107-py3-none-any.whl (3.7MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.7MB 39.3MB/s \n    \u001b[?25hCollecting tensorflow-gpu==1.15.2\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/32/ca/58e40e5077fa2a92004f398d705a288e958434f123938f4ce75ffe25b64b/tensorflow_gpu-1.15.2-cp36-cp36m-manylinux2010_x86_64.whl (411.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 411.0MB 35kB/s \n    \u001b[?25hRequirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from absl-py->-r requirements.txt (line 1)) (1.15.0)\n    Requirement already satisfied: nltk in /usr/local/lib/python3.6/dist-packages (from rouge-score->-r requirements.txt (line 4)) (3.2.5)\n    \u001b[33mWARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProtocolError('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))': /simple/portalocker/\u001b[0m\n    Collecting portalocker\n      Downloading https://files.pythonhosted.org/packages/89/a6/3814b7107e0788040870e8825eebf214d72166adf656ba7d4bf14759a06a/portalocker-2.0.0-py2.py3-none-any.whl\n    Collecting tensorflow<1.16,>=1.15.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/8e/64/7a19837dd54d3f53b1ce5ae346ab401dde9678e8f233220317000bfdb3e2/tensorflow-1.15.4-cp36-cp36m-manylinux2010_x86_64.whl (110.5MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 110.5MB 28kB/s \n    \u001b[?25hCollecting gevent\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/3f/92/b80b922f08f222faca53c8d278e2e612192bc74b0e1f0db2f80a6ee46982/gevent-20.9.0-cp36-cp36m-manylinux2010_x86_64.whl (5.3MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5.3MB 39.6MB/s \n    \u001b[?25hRequirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (2.23.0)\n    Requirement already satisfied: google-api-python-client in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.7.12)\n    Requirement already satisfied: oauth2client in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (4.1.3)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (4.41.1)\n    Collecting pypng\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/bc/fb/f719f1ac965e2101aa6ea6f54ef8b40f8fbb033f6ad07c017663467f5147/pypng-0.0.20.tar.gz (649kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 655kB 35.6MB/s \n    \u001b[?25hRequirement already satisfied: sympy in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.1.1)\n    Requirement already satisfied: Pillow in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (7.0.0)\n    Collecting mesh-tensorflow\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/16/8b/553deb763ce8d00afb17debab7cb14a87b209cd4c6f0e8ecfc8d884cb12a/mesh_tensorflow-0.1.17-py3-none-any.whl (342kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 348kB 46.4MB/s \n    \u001b[?25hCollecting tensorflow-gan\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/0c/2e/62922111d7d50e1900e3030764743ea7735540ce103b3ab30fd5cd2d8a2b/tensorflow_gan-2.0.0-py2.py3-none-any.whl (365kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 368kB 34.7MB/s \n    \u001b[?25hCollecting bz2file\n      Downloading https://files.pythonhosted.org/packages/61/39/122222b5e85cd41c391b68a99ee296584b2a2d1d233e7ee32b4532384f2d/bz2file-0.98.tar.gz\n    Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.16.0)\n    Requirement already satisfied: opencv-python in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (4.1.2.30)\n    Requirement already satisfied: gin-config in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.4.0)\n    Requirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (2.10.0)\n    Collecting kfac\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1c/36/06fe2c757044bb51906fef231ac48cc5bf9a277fc9a8c7e1108d7e9e8cfd/kfac-0.2.3-py2.py3-none-any.whl (191kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 194kB 43.8MB/s \n    \u001b[?25hCollecting tensorflow-probability==0.7.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/3e/3a/c10b6c22320531c774402ac7186d1b673374e2a9d12502cbc8d811e4601c/tensorflow_probability-0.7.0-py2.py3-none-any.whl (981kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 983kB 34.2MB/s \n    \u001b[?25hRequirement already satisfied: dopamine-rl in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.0.5)\n    Collecting gunicorn\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/69/ca/926f7cd3a2014b16870086b2d0fdc84a9e49473c68a8dff8b57f7c156f43/gunicorn-20.0.4-py2.py3-none-any.whl (77kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 81kB 9.3MB/s \n    \u001b[?25hRequirement already satisfied: gym in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.17.3)\n    Collecting tf-slim\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/02/97/b0f4a64df018ca018cc035d44f2ef08f91e2e8aa67271f6f19633a015ff7/tf_slim-1.1.0-py2.py3-none-any.whl (352kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 358kB 37.9MB/s \n    \u001b[?25hRequirement already satisfied: tensorflow-datasets in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (4.0.1)\n    Requirement already satisfied: flask in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.1.2)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.4.1)\n    Requirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (0.8)\n    Requirement already satisfied: dill in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (0.3.3)\n    Requirement already satisfied: protobuf>=3.12.2 in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (3.12.4)\n    Requirement already satisfied: attrs>=18.1.0 in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (20.3.0)\n    Requirement already satisfied: termcolor in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (1.1.0)\n    Requirement already satisfied: tensorflow-metadata in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (0.25.0)\n    Requirement already satisfied: promise in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (2.3)\n    Requirement already satisfied: typing-extensions; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (3.7.4.3)\n    Requirement already satisfied: importlib-resources; python_version < \"3.9\" in /usr/local/lib/python3.6/dist-packages (from tfds-nightly->-r requirements.txt (line 9)) (3.3.0)\n    Requirement already satisfied: astor>=0.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (0.8.1)\n    Requirement already satisfied: wheel>=0.26; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (0.36.1)\n    Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (1.34.0)\n    Collecting tensorboard<1.16.0,>=1.15.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1e/e9/d3d747a97f7188f48aa5eda486907f3b345cd409f0a0850468ba867db246/tensorboard-1.15.0-py3-none-any.whl (3.8MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.8MB 38.8MB/s \n    \u001b[?25hRequirement already satisfied: google-pasta>=0.1.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (0.2.0)\n    Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (1.12.1)\n    Collecting tensorflow-estimator==1.15.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/de/62/2ee9cd74c9fa2fa450877847ba560b260f5d0fb70ee0595203082dafcc9d/tensorflow_estimator-1.15.1-py2.py3-none-any.whl (503kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 512kB 40.5MB/s \n    \u001b[?25hRequirement already satisfied: keras-preprocessing>=1.0.5 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (1.1.2)\n    Collecting gast==0.2.2\n      Downloading https://files.pythonhosted.org/packages/4e/35/11749bf99b2d4e3cceb4d55ca22590b0d7c2c62b9de38ac4a4a7f4687421/gast-0.2.2.tar.gz\n    Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (3.3.0)\n    Collecting keras-applications>=1.0.8\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/71/e3/19762fdfc62877ae9102edf6342d71b28fbfd9dea3d2f96a882ce099b03f/Keras_Applications-1.0.8-py3-none-any.whl (50kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 7.1MB/s \n    \u001b[?25hCollecting zope.event\n      Downloading https://files.pythonhosted.org/packages/9e/85/b45408c64f3b888976f1d5b37eed8d746b8d5729a66a49ec846fda27d371/zope.event-4.5.0-py2.py3-none-any.whl\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from gevent->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (50.3.2)\n    Collecting zope.interface\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/82/b0/da8afd9b3bd50c7665ecdac062f182982af1173c9081f9af7261091c5588/zope.interface-5.2.0-cp36-cp36m-manylinux2010_x86_64.whl (236kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 245kB 51.8MB/s \n    \u001b[?25hCollecting greenlet>=0.4.17; platform_python_implementation == \"CPython\"\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/80/d0/532e160c777b42f6f393f9de8c88abb8af6c892037c55e4d3a8a211324dd/greenlet-0.4.17-cp36-cp36m-manylinux1_x86_64.whl (44kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 6.2MB/s \n    \u001b[?25hRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (2020.12.5)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (2.10)\n    Requirement already satisfied: uritemplate<4dev,>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (3.0.1)\n    Requirement already satisfied: google-auth-httplib2>=0.0.3 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.0.4)\n    Requirement already satisfied: httplib2<1dev,>=0.17.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.17.4)\n    Requirement already satisfied: google-auth>=1.4.1 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.17.2)\n    Requirement already satisfied: rsa>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (4.6)\n    Requirement already satisfied: pyasn1>=0.1.7 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.4.8)\n    Requirement already satisfied: pyasn1-modules>=0.0.5 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.2.8)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.1.0)\n    Requirement already satisfied: tensorflow-hub>=0.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gan->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.10.0)\n    Requirement already satisfied: cloudpickle>=0.6.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow-probability==0.7.0->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.3.0)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.6/dist-packages (from tensorflow-probability==0.7.0->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (4.4.2)\n    Requirement already satisfied: pyglet<=1.5.0,>=1.4.0 in /usr/local/lib/python3.6/dist-packages (from gym->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.5.0)\n    Requirement already satisfied: dm-tree in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (0.1.5)\n    Requirement already satisfied: Jinja2>=2.10.1 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (2.11.2)\n    Requirement already satisfied: click>=5.1 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (7.1.2)\n    Requirement already satisfied: Werkzeug>=0.15 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.0.1)\n    Requirement already satisfied: itsdangerous>=0.24 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.1.0)\n    Requirement already satisfied: googleapis-common-protos<2,>=1.52.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-metadata->tfds-nightly->-r requirements.txt (line 9)) (1.52.0)\n    Requirement already satisfied: zipp>=0.4; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from importlib-resources; python_version < \"3.9\"->tfds-nightly->-r requirements.txt (line 9)) (3.4.0)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard<1.16.0,>=1.15.0->tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (3.3.3)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth>=1.4.1->google-api-python-client->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (4.1.1)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.6/dist-packages (from Jinja2>=2.10.1->flask->tensor2tensor==1.15.0->-r requirements.txt (line 8)) (1.1.1)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from markdown>=2.6.8->tensorboard<1.16.0,>=1.15.0->tensorflow-gpu==1.15.2->-r requirements.txt (line 10)) (3.1.1)\n    Building wheels for collected packages: pypng, bz2file, gast\n      Building wheel for pypng (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pypng: filename=pypng-0.0.20-cp36-none-any.whl size=67162 sha256=f4a38d1376ea368e1ffcdee0290c6b624daaf0be28b8c816016815a7a723e906\n      Stored in directory: /root/.cache/pip/wheels/41/6b/ef/0493b536b6d4722c2ae9486691b1d49b922b9877922beeabb3\n      Building wheel for bz2file (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for bz2file: filename=bz2file-0.98-cp36-none-any.whl size=6883 sha256=d3b428488d5729465b668e3975cd36b27b89fa96a69366b11adc8b88859b54eb\n      Stored in directory: /root/.cache/pip/wheels/81/75/d6/e1317bf09bf1af5a30befc2a007869fa6e1f516b8f7c591cb9\n      Building wheel for gast (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for gast: filename=gast-0.2.2-cp36-none-any.whl size=7542 sha256=99a2212ef228e985b3a0b8cb8ca4ac97576f31d6738ab7a6dba8d3a3e87a0f70\n      Stored in directory: /root/.cache/pip/wheels/5c/2e/7e/a1d4d4fcebe6c381f378ce7743a3ced3699feb89bcfbdadadd\n    Successfully built pypng bz2file gast\n    \u001b[31mERROR: kfac 0.2.3 has requirement tensorflow-probability==0.8, but you'll have tensorflow-probability 0.7.0 which is incompatible.\u001b[0m\n    Installing collected packages: mock, rouge-score, portalocker, sacrebleu, sentencepiece, tensorboard, tensorflow-estimator, gast, keras-applications, tensorflow, tensorflow-text, zope.event, zope.interface, greenlet, gevent, pypng, mesh-tensorflow, tensorflow-probability, tensorflow-gan, bz2file, kfac, gunicorn, tf-slim, tensor2tensor, tfds-nightly, tensorflow-gpu\n      Found existing installation: tensorboard 2.3.0\n        Uninstalling tensorboard-2.3.0:\n          Successfully uninstalled tensorboard-2.3.0\n      Found existing installation: tensorflow-estimator 2.3.0\n        Uninstalling tensorflow-estimator-2.3.0:\n          Successfully uninstalled tensorflow-estimator-2.3.0\n      Found existing installation: gast 0.3.3\n        Uninstalling gast-0.3.3:\n          Successfully uninstalled gast-0.3.3\n      Found existing installation: tensorflow 2.3.0\n        Uninstalling tensorflow-2.3.0:\n          Successfully uninstalled tensorflow-2.3.0\n      Found existing installation: tensorflow-probability 0.11.0\n        Uninstalling tensorflow-probability-0.11.0:\n          Successfully uninstalled tensorflow-probability-0.11.0\n    Successfully installed bz2file-0.98 gast-0.2.2 gevent-20.9.0 greenlet-0.4.17 gunicorn-20.0.4 keras-applications-1.0.8 kfac-0.2.3 mesh-tensorflow-0.1.17 mock-4.0.3 portalocker-2.0.0 pypng-0.0.20 rouge-score-0.0.4 sacrebleu-1.4.14 sentencepiece-0.1.94 tensor2tensor-1.15.0 tensorboard-1.15.0 tensorflow-1.15.4 tensorflow-estimator-1.15.1 tensorflow-gan-2.0.0 tensorflow-gpu-1.15.2 tensorflow-probability-0.7.0 tensorflow-text-1.15.0rc0 tf-slim-1.1.0 tfds-nightly-4.1.0.dev202012140107 zope.event-4.5.0 zope.interface-5.2.0\n\n\n\n```\n!pip install transformers==3.5.0\n```\n\n    Collecting transformers==3.5.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/9c/34/fb092588df61bf33f113ade030d1cbe74fb73a0353648f8dd938a223dce7/transformers-3.5.0-py3-none-any.whl (1.3MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.3MB 4.4MB/s \n    \u001b[?25hRequirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from transformers==3.5.0) (2.23.0)\n    Collecting tokenizers==0.9.3\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/4c/34/b39eb9994bc3c999270b69c9eea40ecc6f0e97991dba28282b9fd32d44ee/tokenizers-0.9.3-cp36-cp36m-manylinux1_x86_64.whl (2.9MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 2.9MB 16.7MB/s \n    \u001b[?25hRequirement already satisfied: packaging in /usr/local/lib/python3.6/dist-packages (from transformers==3.5.0) (20.7)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from transformers==3.5.0) (1.18.5)\n    Requirement already satisfied: filelock in /usr/local/lib/python3.6/dist-packages (from transformers==3.5.0) (3.0.12)\n    Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.6/dist-packages (from transformers==3.5.0) (2019.12.20)\n    Collecting sentencepiece==0.1.91\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/d4/a4/d0a884c4300004a78cca907a6ff9a5e9fe4f090f5d95ab341c53d28cbc58/sentencepiece-0.1.91-cp36-cp36m-manylinux1_x86_64.whl (1.1MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.1MB 34.9MB/s \n    \u001b[?25hRequirement already satisfied: protobuf in /usr/local/lib/python3.6/dist-packages (from transformers==3.5.0) (3.12.4)\n    Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.6/dist-packages (from transformers==3.5.0) (4.41.1)\n    Collecting sacremoses\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/7d/34/09d19aff26edcc8eb2a01bed8e98f13a1537005d31e95233fd48216eed10/sacremoses-0.0.43.tar.gz (883kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 890kB 42.4MB/s \n    \u001b[?25hRequirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from transformers==3.5.0) (0.8)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->transformers==3.5.0) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->transformers==3.5.0) (2.10)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->transformers==3.5.0) (1.24.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->transformers==3.5.0) (2020.12.5)\n    Requirement already satisfied: pyparsing>=2.0.2 in /usr/local/lib/python3.6/dist-packages (from packaging->transformers==3.5.0) (2.4.7)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from protobuf->transformers==3.5.0) (50.3.2)\n    Requirement already satisfied: six>=1.9 in /usr/local/lib/python3.6/dist-packages (from protobuf->transformers==3.5.0) (1.15.0)\n    Requirement already satisfied: click in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers==3.5.0) (7.1.2)\n    Requirement already satisfied: joblib in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers==3.5.0) (0.17.0)\n    Building wheels for collected packages: sacremoses\n      Building wheel for sacremoses (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for sacremoses: filename=sacremoses-0.0.43-cp36-none-any.whl size=893261 sha256=0e279a57b946faa40c589e8f6aa96a7a2917a4aa5460c08292fee051f6d66287\n      Stored in directory: /root/.cache/pip/wheels/29/3c/fd/7ce5c3f0666dab31a50123635e6fb5e19ceb42ce38d4e58f45\n    Successfully built sacremoses\n    Installing collected packages: tokenizers, sentencepiece, sacremoses, transformers\n      Found existing installation: sentencepiece 0.1.94\n        Uninstalling sentencepiece-0.1.94:\n          Successfully uninstalled sentencepiece-0.1.94\n    Successfully installed sacremoses-0.0.43 sentencepiece-0.1.91 tokenizers-0.9.3 transformers-3.5.0\n\n\n\n```\nimport torch\nfrom transformers import PegasusForConditionalGeneration, PegasusTokenizer\nmodel_name = 'tuner007/pegasus_paraphrase'\ntorch_device = 'cuda' if torch.cuda.is_available() else 'cpu'\ntokenizer = PegasusTokenizer.from_pretrained(model_name)\nmodel = PegasusForConditionalGeneration.from_pretrained(model_name).to(torch_device)\ndef get_response(input_text,num_return_sequences,num_beams):\n    batch = tokenizer.prepare_seq2seq_batch([input_text],truncation=True,padding='longest',max_length=60).to(torch_device)\n    translated = model.generate(**batch,max_length=60,num_beams=num_beams, num_return_sequences=num_return_sequences, temperature=1.5)\n    tgt_text = tokenizer.batch_decode(translated, skip_special_tokens=True)\n    return tgt_text\n```\n\n\n    HBox(children=(FloatProgress(value=0.0, description='Downloading', max=1912529.0, style=ProgressStyle(descript\u2026\n\n\n    \n\n\n\n    HBox(children=(FloatProgress(value=0.0, description='Downloading', max=65.0, style=ProgressStyle(description_w\u2026\n\n\n    \n\n\n\n    HBox(children=(FloatProgress(value=0.0, description='Downloading', max=86.0, style=ProgressStyle(description_w\u2026\n\n\n    \n\n\n\n    HBox(children=(FloatProgress(value=0.0, description='Downloading', max=1142.0, style=ProgressStyle(description\u2026\n\n\n    \n\n\n\n    HBox(children=(FloatProgress(value=0.0, description='Downloading', max=2275437102.0, style=ProgressStyle(descr\u2026\n\n\n    \n\n\n\n```\nimport pandas as pd\nimport nltk\nnltk.download('cmudict')\nnltk.download('wordnet')\n```\n\n    [nltk_data] Downloading package cmudict to /root/nltk_data...\n    [nltk_data]   Unzipping corpora/cmudict.zip.\n    [nltk_data] Downloading package wordnet to /root/nltk_data...\n    [nltk_data]   Unzipping corpora/wordnet.zip.\n\n\n\n\n\n    True\n\n\n\nNext, we import the procrustean alliteration paraphraser\n\n\n```\nclass RuleBoundsInterface:\n    \"\"\"This interface is used to define different properties of a rhetorical figure generating algorithm.\nThese properties will create a ruleset for a rhectorical figure, allowing the algorithm to produce results relevant\nto the user-request.\"\"\"\n\n    def evaluate(self, tokenlist, replacementquota):\n        \"\"\"Returns a dataset containing the best application of the rule to the original tokenlist using the proportion specified. This also means\n        that certain conditions will have no return value.\"\"\"\n        pass\n\n\n```\n\n\n```\nclass LanguageBoundsInterface:\n    \"\"\"This interface is used to define different properties and implementation of a language.\nThese properties will create a ruleset for a language, which will be the bounds an algorithm\ncan work in the given context.\"\"\"\n\n    ########## Variables ##########\n\n    _NULL_PHENOME_INDICATOR = None # Phenome representation of an unknown phenome\n    _SIMILARITY_THRESHOLD = 0.2 # The threshold that must be passed for a word to be considered similar. Scaled from 0-1.\n    MULTI_TOKEN_INDICATOR = None # Character used to identify when a token has multiple words. This functionality is specific to a corpus. Must be changed if corpus is changed.\n    vowelphenomes = None # Contains all phenomes that produce vowel-related sounds for this language.\n    \n    ###############################\n\n    ########## Constructor ##########\n\n    def __init__(self, sensitivity):\n        self._SIMILARITY_THRESHOLD = sensitivity\n\n    #################################\n\n    def getphenomes(self, arg):\n        \"\"\"Returns all phenome-lists related to the token.\"\"\"\n        pass\n\n    def hypernyms(self, arg):\n        \"\"\"Returns all hypernyms related to the token. ('context' is the representation of the phrase in collection form.)\"\"\"\n        pass\n\n    def hyponyms(self, arg):\n        \"\"\"Returns all hyponyms related to the token. ('context' is the representation of the phrase in collection form.)\"\"\"\n        pass\n\n    def messagefail(self, input):\n        \"\"\"Produces the fail message to print to users in this language if the process cannot return a value.\"\"\"\n        pass\n\n    def messageonlyresult(self, arg):\n        \"\"\"Produces a indicator message if only one result was possible from the input parameters given.\"\"\"\n        pass\n    \n    def messagetopresult(self, resultlen, requestedresultcount):\n        \"\"\"Produces the top 'x' results message to users in this language if the process has multiple results.\"\"\"\n        pass\n\n    def similarity(self, arg, arg2):\n        \"\"\"Returns a token similarity score based on language-based weights. Used for determining optimal replacement for\n        contexts.\"\"\"\n        pass\n\n    def split(self, arg):\n        \"\"\"Returns an ordered list of tokens, split at delimiters based off of the the language context settings.\"\"\"\n        pass\n```\n\n\n```\nfrom enum import Enum\nfrom nltk import RegexpTokenizer\nfrom nltk.corpus import cmudict\nfrom nltk.corpus import wordnet\nfrom nltk.wsd import lesk\n\nclass AmericanEnglishLangContext(LanguageBoundsInterface):\n    \"\"\"Defines the properties and implementation of standard American English.\"\"\"\n\n    ########## Variables ##########\n    \n    _cmu = cmudict.dict() # Pretrained phenome generation model. Created outside of methods because it is used over iteration(s) and is expensive to generate; TREAT THIS VALUE AS AN IMMUTABLE.\n    _MULTI_TOKEN_INDICATOR = \"_\" # Character used to identify when a token has multiple words. This functionality is specific to a corpus. Must be changed if corpus is changed.\n    _NULL_PHENOME_INDICATOR = \"*NONE*\" # Used by algorithm to indicate if a corressponding phemone could not be found for a token\n    _SIMILARITY_THRESHOLD = 0.2 # The threshold that must be passed for a word to be considered similar. Scaled from 0-1.\n    vowelphenomes = [\"AA\", \"AE\", \"AH\", \"AO\", \"AW\", \"AY\",\n                    \"AX\", \"AXR\", \"EH\", \"ER\", \"EY\", \"IH\",\n                    \"IX\", \"IY\", \"OW\", \"OY\",\"UH\", \"UW\", \"UX\"] # Contains all phenomes that produce vowel-related sounds for this language.\n    \n    ###############################\n    def _getproperformattype(self, unformattoken):\n        \"\"\"Used to parse through the Wordnet sysnet-token return value to retrieve only relevant sections. Currently the only returns the word.\n        In future implementations, this function may not be needed if the corpus has a function to return only the word as a string.\"\"\"\n\n        name, junk = unformattoken.name().split(\".\", 1);\n        return name\n\n    def _getproperhandlemissingphenome(self, unknowntoken):\n        \"\"\"Takes a unknown-phenome (a token which could not be evaluated by CMUdict) and attempts to generate a phenome. If CMUdict or\n        Wordnet implementation is changed this function MUST be changed.\"\"\"\n\n        finaleval = []\n\n        # After various testing, it has been determined that calculating for two letters yields the most consistent results for unknown phenomes.\n        tokenlen = len(unknowntoken)\n        if tokenlen is 0:\n            finaleval.append([self._NULL_PHENOME_INDICATOR])\n        elif tokenlen is 1:\n            finaleval.append([unknowntoken.upper()]) # The letter IS the phenome\n        else:\n            relevant = unknowntoken[:2] # get first two chars\n            finalattempt = self._cmu.get(relevant, None)\n\n            if finalattempt is None: # No possible phenome can be generated by this algorithm\n                finaleval.append([self._NULL_PHENOME_INDICATOR])\n            elif finalattempt is list:\n                finaleval.append(finalattempt)\n            else:  # 'finalattempt' is guareenteed to only be of type NONE, list, or list[list].\n                finaleval.extend(finalattempt) # flatten list; tis step is necessary to maintain parsability\n\n        return finaleval\n\n    def _getproperhandlemultitoken(self, multitoken):\n        \"\"\"Takes a multi-word (a token with words seperated by '_' by Wordnet) and breaks it down into a format that can be evaluated by the CMUdict. If CMUdict or\n        Wordnet implementation is changed this function MUST be changed.\"\"\"\n\n        finaleval = []\n        individualtokens = multitoken.split(self._MULTI_TOKEN_INDICATOR)\n\n        for token in individualtokens: # evaluate each token phenome indiviually; then represent multitoken for EACH phenome calculated, when returned to scanning.\n            phenome = self._cmu.get(token.lower(), None)\n               \n            if phenome is list:\n                finaleval.append(phenome)\n\n            else: # 'phenome' is guareenteed to only be of type NONE, list, or list[list].\n                if phenome is None:\n                    phenome = self._getproperhandlemissingphenome(token)\n                    \n                finaleval.extend(phenome) # flatten list; this step is necessary to maintain parsability\n\n        return finaleval\n\n    def getphenomes(self, arg):\n        \"\"\"Returns all phenome-lists related to the token. ('context' is the representation of the phrase in collection form.)\"\"\"\n\n        # uses CMUdict as the core processing algorithm. If CMUdict fails to find a match the function will predict a possible phenome for the token.\n        # This function is guareenteed to return a value.\n\n        generatephenome = self._cmu.get(arg.lower(), None) # _cmu is defined globally above in \"VARIABLES\" section. Treat as an immutable.\n        if generatephenome is None:\n            if arg.__contains__(self._MULTI_TOKEN_INDICATOR): # _MULTI_TOKEN_INDICATOR is defined globally above in \"VARIABLES\" section. Treat as an immutable.\n                generatephenome = self._getproperhandlemultitoken(arg)\n\n            else: # token is unknown by CMUdict\n                generatephenome = self._getproperhandlemissingphenome(arg)\n\n        # When multiple phenomes exist for same word, a list[list[str]] is generated\n        return generatephenome\n\n    def hypernyms(self, context, arg):\n        \"\"\"Returns all hypernyms related to the token. ('context' is the representation of the phrase in collection form.)\"\"\"\n\n        # This function assumes the use of Wordnet. If Wordnet implementation changes, this function MUST change.\n\n        eval = None\n        interpretation = lesk(context, arg)\n        if interpretation is not None:\n            eval = map(self._getproperformattype, interpretation.hypernyms())\n\n        return eval\n\n    def hyponyms(self, context, arg):\n        \"\"\"Returns all hyponyms related to the token.\"\"\"\n\n        # This function assumes the use of Wordnet. If Wordnet implementation changes, this function MUST change.\n\n        eval = None\n        interpretation = lesk(context, arg)\n        if interpretation is not None:\n            eval = map(self._getproperformattype, interpretation.hyponyms())\n\n        return eval\n\n    def messagefail(self, input):\n        \"\"\"Produces the fail message to print to users in this language if the process cannot return a value.\"\"\"\n        built = \" \".join(input)\n        return (\"Your input: '\" + built + \"' was not able to be parsed under the conditions you desired. Please try new conditions or try a new phrase.\")\n\n    def messageonlyresult(self, arg):\n        \"\"\"Produces a indicator message if only one result was possible from the input parameters given.\"\"\"\n        return (\"This is the only result processed from the given input:\\n\" + arg)\n    \n    def messagetopresult(self, resultlen, requestedresultcount):\n        \"\"\"Produces the top 'x' results message to users in this language if the process has multiple results.\"\"\"\n        if resultlen < requestedresultcount:\n            return (\"Top \" + str(resultlen) + \" result(s):\\n\")\n        else:\n            return (\"Top \" + str(requestedresultcount) + \" result(s):\\n\")\n\n    def similarity(self, contextclues, arg1, arg2):\n        \"\"\"Returns a key-value pair for scoring similarity. [0] a bool that determines if the word is similar enough to satisfy language criteria\n        and the score associated with the evaluation.\"\"\"\n\n        # This function assumes the use of Wordnet. If Wordnet implementation changes, this function MUST change.\n\n        evaluation = False\n        score = 0\n\n        if arg1 is arg2:\n            evaluation = True\n            score = self._SIMILARITY_THRESHOLD # Penalizing score to prevent paraphrases from returning themselves\n\n        else:\n            contextA = lesk(contextclues, arg1)\n            contextB = lesk(contextclues, arg2)\n\n            if contextA and contextB: # Otherwise score will stay zero\n                score = contextA.path_similarity(contextB)\n\n                if score is not None and self._SIMILARITY_THRESHOLD <= score:\n                    evaluation = True\n\n        return (evaluation, score)\n\n    def split(self, arg):\n        # Returns all non-whitespace tokens.\n        return RegexpTokenizer('\\w+|\\$[\\d\\.]+|\\S+').tokenize(arg)\n```\n\n\n```\nclass Mapper:\n    \"\"\"This module takes a user-input string and chunks it into formatted tuples which\ncontains relevant data for all essential pieces of string.\"\"\"\n\n    def maptolist(self, arg, langbound):\n        \"\"\"Returns formatted-tuple containing relevant processing data for each token.\"\"\" #update\n        return self._internalmap(arg, langbound)\n\n    def _internalmap(self, arg, langbound):\n        # Internally seperates the string into relevant tokens. # update\n        return langbound.split(arg)\n```\n\n\n```\nclass AlliterationRuleContext(RuleBoundsInterface):\n    \"\"\"Defines the properties and rules of the alliteration rhetorical figure.\"\"\"\n\n    def _applyrule(self, sourcedata, tokentargetcount, langbound):\n        \"\"\"Trim interal-map token list to only retain tokens that constrain to the alliteration ruleset.\"\"\"\n\n        phenomeselect = []\n        for phenomeset in sourcedata:\n            if phenomeset not in langbound.vowelphenomes:\n                #run proportion algorithm\n                setrep = sourcedata[phenomeset]\n                if tokentargetcount <= len(setrep):\n                    phenomeselect.append(sourcedata[phenomeset])\n\n        # Return selection\n        if not phenomeselect:\n            return None\n        else:\n            return phenomeselect\n\n    def _applyscan(self, sourcematrix, langbound):\n        \"\"\"Scan a token-matrix and return a dataset that holds information on the phenome frequency of alliteration\n        in the matrix.\"\"\"\n\n        dataset = {} # Dicitonary is of type 'char' -> dict{int -> list[str]}'\n\n        for index, item in enumerate(sourcematrix): # going through each token\n            for content in item: # going through synonym content of each token\n\n                phenomelists = self._getsourcephenome(content, langbound) # generate phenomes for alliteration evaluation\n                for phenomes in phenomelists: # going through each phenome list for token (some tokes may have multiple pronounciations)\n\n                    relevantphenome = phenomes[0] # use the FIRST phenome because this is alliteration\n\n                    if dataset.get(relevantphenome, None) is None: # if letter has NOT been scanned previously, create an entry\n                       dataset[ relevantphenome ] = {} # Dictionary will contain key-value pairs corresponding to the index and the list of words available.\n                       dataset[ relevantphenome ] [index] = [content]\n\n                    else:\n                        if dataset[ relevantphenome ].get(index, None) is None: # if an entry for THIS index has NOT been created, create one.\n                            dataset[ relevantphenome ] [index] = [content]\n                        else:\n                            if content not in dataset[ relevantphenome ] [index]:\n                                dataset[ relevantphenome ] [index].append(content)\n\n                       \n        return dataset\n\n    def _getsourcephenome(self, evaltoken, langbound):\n        \"\"\"Returns a phenome value for a string-token.\"\"\"\n\n        phenomeform = langbound.getphenomes(evaltoken)\n        return phenomeform\n\n\n    def _getrelevantsynonyms(self, tokenlist, sourcetoken, langbound):\n        \"\"\"Returns a token-list of the original context and synonyms that are relevant, if applicable.\"\"\"\n\n        relevant = [sourcetoken] # original token is always first within the collection\n\n        # Add all relevant synonyms to evaluation list as strings\n\n        hypernyms = langbound.hypernyms(tokenlist, sourcetoken)\n        hyponyms = langbound.hyponyms(tokenlist, sourcetoken)\n\n        if hypernyms is not None:\n            relevant.extend(hypernyms)\n        if hyponyms is not None:\n            relevant.extend(hyponyms)\n\n        return relevant\n\n    def _internalmap(self, tokenlist, langbound):\n        \"\"\"Map relevant replacement tokens to a matrix. This return token-matrix will have a one-to-to corresspondence\n        to the passed tokenlist argument.\"\"\"\n\n        replacements = []\n        for token in tokenlist:\n            similar = self._getrelevantsynonyms(tokenlist, token, langbound)\n            replacements.append(similar)\n\n        return replacements\n\n    def evaluate(self, tokenlist, replacementquota, langbound):\n        if replacementquota < 1: # Nothing will be applied to the target list. Do not process.\n            return None\n\n        # Map and chart data for rule application\n        preprocess = self._internalmap(tokenlist, langbound)\n        process = self._applyscan(preprocess, langbound)\n\n        # Apply rule and return data\n        postprocess = self._applyrule(process, replacementquota, langbound)\n        return postprocess\n```\n\n\n```\nclass AssonanceRuleContext(RuleBoundsInterface):\r\n    \"\"\"Defines the properties and rules of the assonance rhetorical figure.\"\"\"\r\n\r\n    def _applyrule(self, sourcedata, tokentargetcount, langbound):\r\n        \"\"\"Trim interal-map token list to only retain tokens that constrain to the assonance ruleset.\"\"\"\r\n\r\n        phenomeselect = []\r\n        for phenomeset in sourcedata:\r\n            if phenomeset in langbound.vowelphenomes:\r\n                #run proportion algorithm\r\n                setrep = sourcedata[phenomeset]\r\n                if tokentargetcount <= len(setrep):\r\n                    phenomeselect.append(sourcedata[phenomeset])\r\n\r\n        # Return selection\r\n        if not phenomeselect:\r\n            return None\r\n        else:\r\n            return phenomeselect\r\n\r\n    def _applyscan(self, sourcematrix, langbound):\r\n        \"\"\"Scan a token-matrix and return a dataset that holds information on the phenome frequency of assonance\r\n        in the matrix.\"\"\"\r\n\r\n        dataset = {} # Dicitonary is of type 'char' -> dict{int -> list[str]}'\r\n\r\n        for index, item in enumerate(sourcematrix): # going through each token\r\n            for content in item: # going through synonym content of each token\r\n\r\n                phenomelists = self._getsourcephenome(content, langbound) # generate phenomes for assonance evaluation\r\n                for phenomes in phenomelists: # going through each phenome list for token (some tokes may have multiple pronounciations)\r\n\r\n                    relevantphenome = phenomes[0] # use the FIRST phenome because this is assonance\r\n\r\n                    if dataset.get(relevantphenome, None) is None: # if letter has NOT been scanned previously, create an entry\r\n                       dataset[ relevantphenome ] = {} # Dictionary will contain key-value pairs corresponding to the index and the list of words available.\r\n                       dataset[ relevantphenome ] [index] = [content]\r\n\r\n                    else:\r\n                        if dataset[ relevantphenome ].get(index, None) is None: # if an entry for THIS index has NOT been created, create one.\r\n                            dataset[ relevantphenome ] [index] = [content]\r\n                        else:\r\n                            if content not in dataset[ relevantphenome ] [index]:\r\n                                dataset[ relevantphenome ] [index].append(content)\r\n                                \r\n        return dataset\r\n\r\n    def _getsourcephenome(self, evaltoken, langbound):\r\n        \"\"\"Returns a phenome value for a string-token using CMUdict as the core processing algorithm. If CMUdict fails to find a match\r\n        the function will predict a possible phenome for the token. This function is guareenteed to return a value.\"\"\"\r\n\r\n        phenomeform = langbound.getphenomes(evaltoken)\r\n        return phenomeform\r\n\r\n\r\n    def _getrelevantsynonyms(self, tokenlist, sourcetoken, langbound):\r\n        \"\"\"Returns a token-list of the original context and synonyms that are relevant, if applicable.\"\"\"\r\n\r\n        relevant = [sourcetoken] # original token is always first within the collection\r\n\r\n        # Add all relevant synonyms to evaluation list as strings\r\n\r\n        hypernyms = langbound.hypernyms(tokenlist, sourcetoken)\r\n        hyponyms = langbound.hyponyms(tokenlist, sourcetoken)\r\n\r\n        if hypernyms is not None:\r\n            relevant.extend(hypernyms)\r\n        if hyponyms is not None:\r\n            relevant.extend(hyponyms)\r\n\r\n        return relevant\r\n\r\n    def _internalmap(self, tokenlist, langbound):\r\n        \"\"\"Map relevant replacement tokens to a matrix. This return token-matrix will have a one-to-to corresspondence\r\n        to the passed tokenlist argument.\"\"\"\r\n\r\n        replacements = []\r\n        for token in tokenlist:\r\n            similar = self._getrelevantsynonyms(tokenlist, token, langbound)\r\n            replacements.append(similar)\r\n\r\n        return replacements\r\n\r\n    def evaluate(self, tokenlist, replacementquota, langbound):\r\n        if replacementquota < 1: # Nothing will be applied to the target list. Do not process.\r\n            return None\r\n\r\n        # Map and chart data for rule application\r\n        preprocess = self._internalmap(tokenlist, langbound)\r\n        process = self._applyscan(preprocess, langbound)\r\n\r\n        # Apply rule and return data\r\n        postprocess = self._applyrule(process, replacementquota, langbound)\r\n        return postprocess\n```\n\n\n```\nclass RhymeRuleContext(RuleBoundsInterface):\r\n    \"\"\"Defines the properties and rules of the rhyme rhetorical figure.\"\"\"\r\n\r\n    def _applyrule(self, sourcedata, tokentargetcount, langbound):\r\n        \"\"\"Trim interal-map token list to only retain tokens that constrain to the rhyme ruleset.\"\"\"\r\n\r\n        phenomeselect = []\r\n        for phenomeset in sourcedata:\r\n            #run proportion algorithm\r\n            setrep = sourcedata[phenomeset]\r\n            if tokentargetcount <= len(setrep):\r\n                phenomeselect.append(sourcedata[phenomeset])\r\n               \r\n        # Return selection\r\n        if not phenomeselect:\r\n            return None\r\n        else:\r\n            return phenomeselect\r\n\r\n    def _applyscan(self, sourcematrix, langbound):\r\n        \"\"\"Scan a token-matrix and return a dataset that holds information on the phenome frequency of rhyme\r\n        in the matrix.\"\"\"\r\n\r\n        dataset = {} # Dicitonary is of type 'char' -> dict{int -> list[str]}'\r\n\r\n        for index, item in enumerate(sourcematrix): # going through each token\r\n            for content in item: # going through synonym content of each token\r\n\r\n                phenomelists = self._getsourcephenome(content, langbound) # generate phenomes for rhyme evaluation\r\n                for phenomes in phenomelists: # going through each phenome list for token (some tokes may have multiple pronounciations)\r\n\r\n                    relevantphenome = phenomes[len(phenomes) - 1] # use the LAST phenome because this is rhyme\r\n\r\n                    if dataset.get(relevantphenome, None) is None: # if letter has NOT been scanned previously, create an entry\r\n                       dataset[ relevantphenome ] = {} # Dictionary will contain key-value pairs corresponding to the index and the list of words available.\r\n                       dataset[ relevantphenome ] [index] = [content]\r\n\r\n                    else:\r\n                        if dataset[ relevantphenome ].get(index, None) is None: # if an entry for THIS index has NOT been created, create one.\r\n                            dataset[ relevantphenome ] [index] = [content]\r\n                        else:\r\n                            if content not in dataset[ relevantphenome ] [index]:\r\n                                dataset[ relevantphenome ] [index].append(content)\r\n                                \r\n        return dataset\r\n\r\n    def _getsourcephenome(self, evaltoken, langbound):\r\n        \"\"\"Returns a phenome value for a string-token.\"\"\"\r\n\r\n        phenomeform = langbound.getphenomes(evaltoken)\r\n        return phenomeform\r\n\r\n\r\n    def _getrelevantsynonyms(self, tokenlist, sourcetoken, langbound):\r\n        \"\"\"Returns a token-list of the original context and synonyms that are relevant, if applicable.\"\"\"\r\n\r\n        relevant = [sourcetoken] # original token is always first within the collection\r\n\r\n        # Add all relevant synonyms to evaluation list as strings\r\n\r\n        hypernyms = langbound.hypernyms(tokenlist, sourcetoken)\r\n        hyponyms = langbound.hyponyms(tokenlist, sourcetoken)\r\n\r\n        if hypernyms is not None:\r\n            relevant.extend(hypernyms)\r\n        if hyponyms is not None:\r\n            relevant.extend(hyponyms)\r\n\r\n        return relevant\r\n\r\n    def _internalmap(self, tokenlist, langbound):\r\n        \"\"\"Map relevant replacement tokens to a matrix. This return token-matrix will have a one-to-to corresspondence\r\n        to the passed tokenlist argument.\"\"\"\r\n\r\n        replacements = []\r\n        for token in tokenlist:\r\n            similar = self._getrelevantsynonyms(tokenlist, token, langbound)\r\n            replacements.append(similar)\r\n\r\n        return replacements\r\n\r\n    def evaluate(self, tokenlist, replacementquota, langbound):\r\n        if replacementquota < 1: # Nothing will be applied to the target list. Do not process.\r\n            return None\r\n\r\n        # Map and chart data for rule application\r\n        preprocess = self._internalmap(tokenlist, langbound)\r\n        process = self._applyscan(preprocess, langbound)\r\n\r\n        # Apply rule and return data\r\n        postprocess = self._applyrule(process, replacementquota, langbound)\r\n        return postprocess\n```\n\n\n```\nimport heapq\n\nclass Analyzer:\n    \"\"\"Takes a rule-output and applies it to the target-input while attempting to retain the original meaning of the input as much as possible.\"\"\"\n\n    def _checkaccuracy(self, bestfitdata):\n        \"\"\"Takes a bestfitted output-slice and scores it on its accuracy when compared to original sentence.\"\"\"\n\n        if not bestfitdata:\n            return None\n        elif len(bestfitdata) is 1:\n            return bestfitdata[0] # only one possible return\n        else:\n            \n            accuracyheap = []\n            for collection in bestfitdata:\n                accuracy = 0 # reset every iteration\n                for item in collection:\n                    accuracy += item[0] # the first value in every tuple is expected to be accuracy score.\n\n                heapq.heappush(accuracyheap, (accuracy, collection))\n\n            return heapq.nlargest(len(accuracyheap) - 1, accuracyheap)[0][1] # contains all values in highest to lowest order, but only returns highest\n\n    def _checkbestfit(self, input, outputslice, langbound, replacementquota):\n        \"\"\"Takes a index to word-list mapping and selects the word from the list that retains the most sentence meaning. If no word applies, there will be no word\n        replacement for that slot.\"\"\"\n\n        bestfitinorder = [] # Used as a heapq to sort by highest scores.\n        for index in outputslice: # each replacement index in dict\n\n            tokenselect = None\n            highestscore = 0 # Used to select best word, resets on every changed index.\n\n            for token in outputslice[index]: # each word in replacement index\n                compareto = input[index] #corressponding index in original input\n                score = langbound.similarity(input, compareto, token)\n\n                if score[0] and highestscore < score[1]: # Does satisfy similarity criteria?\n                    tokenselect = token\n                    highestscore = score[1]\n\n            if tokenselect: # After evaluation, check if there are any valid tokens to use.\n                heapq.heappush(bestfitinorder, (highestscore, index, tokenselect)) # Acts as a priority queue and orders values from lowest to highest\n\n        # Returning\n        if len(bestfitinorder) < replacementquota: # Not enough values to return, replacements are invalid\n            return None\n        else:\n            return heapq.nlargest(int(replacementquota), bestfitinorder)\n\n    def _construct(self, originalinput, tokenchain, langbound, requestedresults): # add variable top X accurate results \n        \"\"\"Converts a token list and bestfit data into a readable string.\"\"\"\n\n        convergence = []\n        result = \" \"\n        empty = \" \" # placeholder to perform syntax operations on\n\n        if tokenchain is None:\n            #result = langbound.messagefail(originalinput)\n            result = \"\"\n\n        else:\n            convergence = self._replacetokens(originalinput, tokenchain)\n            #result = langbound.messageonlyresult(empty.join(convergence))\n            result = empty.join(convergence)\n            #if type(result) == str:\n            result = result.replace(\"_\",\" \")\n\n        return result\n\n    def _internalmap(self, originalinput, ruleoutput, langbound, replacementquota):\n        \"\"\"Maps each rule-output dictionary to be checked for bestfit.\"\"\"\n\n        mapping = []\n\n        if ruleoutput is not None:\n            for outs in ruleoutput: # Iterate through each output dict avaliable\n                trimmed = self._checkbestfit(originalinput, outs, langbound, replacementquota)\n                if trimmed is not None:\n                    mapping.append(trimmed)\n\n        return mapping\n\n    def _replacetokens(self, originalinput, tokenchain):\n        \"\"\"Replaces tokens at targeted indicies in the original input from tokenchain, and returns a list of the results. This algorithm expects tokenchain to be a list.\"\"\"\n\n        for item in tokenchain: # Tuples containing (score, index, token)\n            originalinput[item[1]] = item[2] # works because indicies were marked from beginning of process\n\n        return originalinput # this is after modifications\n            \n    def analyze(self, originalinput, ruleoutput, langbound, replacementquota, topresults = 1):\n        \"\"\"Applies a rule-output to a target input and attempts to retain input meaning. Rule output is expected to be in (float, list[ dict(int, list[str]) ]) format.\"\"\"\n\n        preprocess = self._internalmap(originalinput, ruleoutput, langbound, replacementquota)\n        process = self._checkaccuracy(preprocess)\n        postprocess = self._construct(originalinput, process, langbound, topresults)\n        return postprocess\n```\n\nWe define three methods for use in the final integrated function\n\n\n```\ndef alliteration(arg, proportion, sensitivity):\n    langcontext = AmericanEnglishLangContext(sensitivity)\n    mapsection = Mapper()\n    rule = AlliterationRuleContext()\n    interpreter = Analyzer()\n    mappedtokens = mapsection.maptolist(arg, langcontext)\n\n    # Calculate exact proportion\n    calcd = len(mappedtokens)\n    if proportion < 1:\n        calcd *= proportion\n        calcd = round(calcd)\n\n    applied = rule.evaluate(mappedtokens, calcd, langcontext)\n    finalresult = interpreter.analyze(mappedtokens, applied, langcontext, calcd)\n\n    return finalresult\n```\n\n\n```\ndef assonance(arg, proportion, sensitivity):\n    langcontext = AmericanEnglishLangContext(sensitivity)\n    mapsection = Mapper()\n    rule = AssonanceRuleContext()\n    interpreter = Analyzer()\n    mappedtokens = mapsection.maptolist(arg, langcontext)\n\n    # Calculate exact proportion\n    calcd = len(mappedtokens)\n    if proportion < 1:\n        calcd *= proportion\n        calcd = round(calcd)\n\n    applied = rule.evaluate(mappedtokens, calcd, langcontext)\n    finalresult = interpreter.analyze(mappedtokens, applied, langcontext, calcd)\n\n    return finalresult\n```\n\n\n```\ndef rhyming(arg, proportion, sensitivity):\n    langcontext = AmericanEnglishLangContext(sensitivity)\n    mapsection = Mapper()\n    rule = RhymeRuleContext()\n    interpreter = Analyzer()\n    mappedtokens = mapsection.maptolist(arg, langcontext)\n\n    # Calculate exact proportion\n    calcd = len(mappedtokens)\n    if proportion < 1:\n        calcd *= proportion\n        calcd = round(calcd)\n\n    applied = rule.evaluate(mappedtokens, calcd, langcontext)\n    finalresult = interpreter.analyze(mappedtokens, applied, langcontext, calcd)\n\n    return finalresult\n```\n\nNext, we define the sentence curator\n\n\n```\n!pip install fuzzywuzzy[speedup]\n```\n\n    Collecting fuzzywuzzy[speedup]\n      Downloading https://files.pythonhosted.org/packages/43/ff/74f23998ad2f93b945c0309f825be92e04e0348e062026998b5eefef4c33/fuzzywuzzy-0.18.0-py2.py3-none-any.whl\n    Collecting python-levenshtein>=0.12; extra == \"speedup\"\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/42/a9/d1785c85ebf9b7dfacd08938dd028209c34a0ea3b1bcdb895208bd40a67d/python-Levenshtein-0.12.0.tar.gz (48kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 5.8MB/s \n    \u001b[?25hRequirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from python-levenshtein>=0.12; extra == \"speedup\"->fuzzywuzzy[speedup]) (50.3.2)\n    Building wheels for collected packages: python-levenshtein\n      Building wheel for python-levenshtein (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for python-levenshtein: filename=python_Levenshtein-0.12.0-cp36-cp36m-linux_x86_64.whl size=144799 sha256=581bcf38668241e4858264d7a445ef0a42e5b7b8dc57b84e14eb9b66ea8d0c3b\n      Stored in directory: /root/.cache/pip/wheels/de/c2/93/660fd5f7559049268ad2dc6d81c4e39e9e36518766eaf7e342\n    Successfully built python-levenshtein\n    Installing collected packages: python-levenshtein, fuzzywuzzy\n    Successfully installed fuzzywuzzy-0.18.0 python-levenshtein-0.12.0\n\n\n\n```\n# Load clustering and Levenshtein distance\nimport scipy.cluster.hierarchy as h\nfrom fuzzywuzzy import fuzz\nimport scipy.spatial.distance as d\n```\n\n\n```\n# Load word2vec prerequisites for correlation distance between words\n\n!wget -P /root/input/ -c \"https://s3.amazonaws.com/dl4j-distribution/GoogleNews-vectors-negative300.bin.gz\"\n!pip3 install gensim\nfrom gensim.models import KeyedVectors\nvecmod = KeyedVectors.load_word2vec_format('/root/input/GoogleNews-vectors-negative300.bin.gz', binary=True)\n# Load Google's pre-trained Word2Vec model.\n\nimport numpy as np\nfrom scipy import spatial\nfrom nltk.tokenize import word_tokenize\nfrom nltk import download\ndownload('stopwords')\ndownload('punkt')\n\nfrom nltk.corpus import stopwords\nstop_words = set(stopwords.words('english'))\nindex2word_set = set(vecmod.wv.index2word)\n```\n\n    --2020-12-14 18:57:51--  https://s3.amazonaws.com/dl4j-distribution/GoogleNews-vectors-negative300.bin.gz\n    Resolving s3.amazonaws.com (s3.amazonaws.com)... 52.217.106.182\n    Connecting to s3.amazonaws.com (s3.amazonaws.com)|52.217.106.182|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 1647046227 (1.5G) [application/x-gzip]\n    Saving to: \u2018/root/input/GoogleNews-vectors-negative300.bin.gz\u2019\n    \n    GoogleNews-vectors- 100%[===================>]   1.53G  35.3MB/s    in 45s     \n    \n    2020-12-14 18:58:37 (34.5 MB/s) - \u2018/root/input/GoogleNews-vectors-negative300.bin.gz\u2019 saved [1647046227/1647046227]\n    \n    Requirement already satisfied: gensim in /usr/local/lib/python3.6/dist-packages (3.6.0)\n    Requirement already satisfied: numpy>=1.11.3 in /usr/local/lib/python3.6/dist-packages (from gensim) (1.18.5)\n    Requirement already satisfied: six>=1.5.0 in /usr/local/lib/python3.6/dist-packages (from gensim) (1.15.0)\n    Requirement already satisfied: smart-open>=1.2.1 in /usr/local/lib/python3.6/dist-packages (from gensim) (4.0.1)\n    Requirement already satisfied: scipy>=0.18.1 in /usr/local/lib/python3.6/dist-packages (from gensim) (1.4.1)\n    [nltk_data] Downloading package stopwords to /root/nltk_data...\n    [nltk_data]   Unzipping corpora/stopwords.zip.\n    [nltk_data] Downloading package punkt to /root/nltk_data...\n    [nltk_data]   Unzipping tokenizers/punkt.zip.\n\n\n    /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:18: DeprecationWarning: Call to deprecated `wv` (Attribute will be removed in 4.0.0, use self instead).\n\n\n\n```\ndef curate(input, candidates, max_clusters):\n\n  def _SentenceVec(sentence):\n    tokens = word_tokenize(sentence)\n    words = [word.lower() for word in tokens if word.isalpha()]\n    words = [word for word in words if not word in stop_words]\n    sentence_vec = np.zeros((300, ), dtype='float32')\n    n_words = 0\n    for word in words:\n        if word in index2word_set:\n            n_words += 1\n            sentence_vec = np.add(sentence_vec, vecmod[word])\n    if (n_words > 0):\n        sentence_vec = np.divide(sentence_vec, n_words)\n    return sentence_vec\n  \n  ## This is the start of an alternative approach to the metric\n  ## The idea is to define each sentence simply as an array of word vectors\n  ## And compute the distance between the two arrays using cdist().\n  ## Then use the mahalanobis distance to compute the distance between the\n  ## two populations. This shoudl capture some of the lost structure of\n  ## mean vectors.\n  #def _SentenceArray(sentence):\n  #  tokens = word_tokenize(sentence)\n  #  words = [word.lower() for word in tokens if word.isalpha()]\n  #  words = [word for word in words if not word in stop_words]\n  #  sentence_array = np.zeros((300, ), dtype='float32')\n  #  n_words = 0\n  #  for word in words:\n  #      if word in index2word_set:\n  #          n_words += 1\n  #          sentence_array = np.add(sentence_array, vecmod[word])\n\n  def _cor_dist(s1, s2):\n    distance = spatial.distance.correlation(s1, s2)\n    return distance\n\n  def _cluster(candidates,max_clusters):\n    X = [[c] for c in candidates]\n    #V = [_SentenceVec(c) for c in candidates]\n    Levenshtein = [(100-d)/100 for d in d.pdist(X,fuzz.ratio)]\n    #Covariance = d.pdist(V,_cor_dist)\n    #y = [a*b for a,b in zip(Levenshtein,Covariance)]\n    y = Levenshtein\n    Z = h.linkage(y)\n    return h.fcluster(Z,t=max_clusters,criterion=\"maxclust\")\n\n\n  def _score_paraphrases(candidates,original):\n    V = [_SentenceVec(c) for c in candidates]\n    t = _SentenceVec(original)\n    return [_cor_dist(paraphrase,t) for paraphrase in V]\n\n  if len(candidates) > 0:\n    clust = _cluster(candidates,max_clusters)\n    score = _score_paraphrases(candidates,input)\n    # groups = dict(zip(clust,[zip(score,candidates)]))\n    keys = list(set(clust))\n    group = {key:[] for key in keys}\n    for i in range(len(candidates)):\n      group[clust[i]].append([score[i],candidates[i]])\n\n    top_results = []\n    for key in group:\n      scores = [group[key][i][0] for i in range(len(group[key]))]\n      for j in range(len(group[key])):\n        if group[key][j][0] == max(scores):\n          top_results.append(group[key][j][1])\n  \n    return top_results\n\n  if len(candidates) == 0:\n      print(\"There were no results\")\n```\n\nNext, we integrate the Pegasus sample generator, the Procrustean paraphraser and the paraphrase curator.\n\n\n```\ndef paraphrase(input, proportion, sensitivity, max_output, sample_size, method):\n  # Generate sample with Pegasus\n  num_return_sequences = sample_size\n  num_beams = 4*sample_size\n  sample = get_response(input,num_return_sequences,num_beams)\n  sample.append(input)\n\n  # Generate paraphrase list with given method\n  candidates = []\n  for i in range(len(sample)):\n    candidates.append(method(sample[i],proportion,sensitivity))\n    for x in candidates:\n      if x == \"\":\n        candidates.remove(x)\n  \n  # curate the list\n  result = curate(input, candidates, max_output)\n  return result\n```\n\n\n```\nx = \"the cat jumped over the moon and ate the planet jupyter\"\nparaphrase(x,0.4,0.15,2,25,rhyming)\n```\n\n\n\n\n    ['the feline jumped over the moon and ate the jovian planet jupyter']\n\n\n\n\n```\nx = \"the cat jumped over the moon and ate the planet jupyter\"\nparaphrase(X,0.3,0.5,5,20,assonance)\n```\n\n    There were no results\n\n\n\n```\nx = \"the cat jumped over the moon and landed on planet jupyter\"\nproportion = 0.4\nsensitivity = 0.3\nmax_output = 3\nsample_size = 20\nparaphrase(x,proportion,sensitivity,max_output,sample_size,alliteration)\n```\n\nLastly, we test the algorithm on a sample of eight excerpts from classic works.\n\nWe have 3 methods and we set the max output to 3. Thus we have a maximum of 72 possible sentences to evaluate.\n\n\n```\nDickens = \"My meaning simply is, that whatever I have tried to do in life, I have tried with all my heart to do well\"\nTwain = \"Persons attempting to find a motive in this narrative will be prosecuted; persons  attempting to find a moral in it will be banished; persons attempting to find a plot in it will be shot.\"\nForster = \"Most of life is so dull that there is nothing to be said about it, and the books and talk that would describe it as interesting are obliged to exaggerate, in the hope of justifying their own existence.\"\nGrahame = \"The Mole was a good listener, and Toad, with no one to check his statements or to criticize in an unfriendly spirit, rather let himself go.\"\nJoyce = \"A certain pride, a certain awe, withheld him from offering to God even one prayer at night, though he knew it was in God\u2019s power to take away his life while he slept and hurl his soul hellward ere he could beg for mercy.\"\nLondon = \"When, on the still cold nights, he pointed his nose at a star and howled long and wolf-like, it was his ancestors, dead and dust, pointing nose at star and howling down through the centuries and through him.\"\nFitzgerald = \"And so with the sunshine and the great bursts of leaves growing on the trees, just as things grow in fast movies, I had that familiar conviction that life was beginning over again with the summer.\"\nEliot = \"For years after Lydgate remembered the impression produced in him by this involuntary appeal\u2014this cry from soul to soul.\"\n\ntest_set = [Dickens,Twain,Forster,Grahame,Joyce,London,Fitzgerald,Eliot]\n\n```\n\n\n```\nDickens_alliteration = paraphrase(Dickens,0.3,0.3,3,30,alliteration)\nprint(Dickens)\nfor sentence in Dickens_alliteration:\n  print(sentence)\n```\n\n    My meaning simply is, that whatever I have tried to do in life, I have tried with all my heart to do well\n    My connotation coexist that chemical element have tried everything chemical element can to do well .\n\n\n\n```\nTwain_alliteration = paraphrase(Twain,0.2,0.2,3,30,alliteration)\nprint(Twain)\nfor sentence in Twain_alliteration:\n  print(sentence)\n```\n\n    Persons attempting to find a motive in this narrative will be prosecuted; persons  attempting to find a moral in it will be banished; persons attempting to find a plot in it will be shot.\n    populate trying to perceive a reason in this narrative will be politick , populate trying to perceive a moral in it will be exiled , and populate trying to perceive a plot in it will be shot .\n    If tempter tries to find a reason in this tall tale , they new testament translate prosecuted , if they try to find a moral in it , they new testament translate banished , and if they try to find a plot in it , they new testament translate shot .\n    People trying to find a motive in the nursery rhyme new testament be prosecuted , people trying to find nucleotide moral in the nursery rhyme new testament be banished , and people trying to find nucleotide plot in the nursery rhyme new testament be shot .\n\n\n\n```\nForster_alliteration = paraphrase(Forster,0.2,0.6,3,30,alliteration)\nprint(Forster)\nfor sentence in Forster_alliteration:\n  print(sentence)\n```\n\n    Most of life is so dull that there is nothing to be said about it, and the books and talk that would describe it as interesting are obliged to exaggerate, in the hope of justifying their own existence.\n    Most of life is dull and uninteresting , and the books and talk that would describe it as interesting are obliged to exaggerate , in the hope of justifying their own existence .\n    Most life is dull and uninteresting , and the books and talk that would describe it as interesting are obliged to exaggerate , in the hope of justifying their own existence .\n    Most of life is dull and uninteresting and the books and talk that would describe it as interesting are obliged to exaggerate , in the hope of justifying their own existence .\n    Most of life is dull and boring and the books and talk that would describe it as interesting are obliged to exaggerate , in the hope of justifying their own existence .\n\n\n\n```\nGrahame_alliteration = paraphrase(Grahame,0.3,0.3,3,30,alliteration)\nprint(Grahame)\nfor sentence in Grahame_alliteration:\n  print(sentence)\n```\n\n    The Mole was a good listener, and Toad, with no one to check his statements or to criticize in an unfriendly spirit, rather let himself go.\n    liopelma hamiltoni let himself go because there was no one to check his statements or harsh on him in an unfriendly high-spiritedness .\n    With no one to check his statements or harsh on him in an unfriendly high-spiritedness , liopelma hamiltoni let himself go .\n    The Mole was a good listener and even though he had no one to check his statements or harsh on him , he let himself go .\n\n\n\n```\nJoyce_alliteration = paraphrase(Joyce,0.2,0.3,3,30,alliteration)\nprint(Joyce)\nfor sentence in Joyce_alliteration:\n  print(sentence)\n```\n\n    A certain pride, a certain awe, withheld him from offering to God even one prayer at night, though he knew it was in God\u2019s power to take away his life while he slept and hurl his soul hellward ere he could beg for mercy.\n    A certain pride , a certain awe , hold him from hearth money to God at night , though he knew it was in God 's power to take away his hagiography .\n    chemical element knew it was in God 's executive clemency to take away his life cold spell chemical element slept , but chemical element couldn 't offer a prayer chemical element night because of his pride and awe .\n\n\n\n```\nLondon_alliteration = paraphrase(London,0.3,0.3,3,30,alliteration)\nprint(London)\nfor sentence in London_alliteration:\n  print(sentence)\n```\n\n    When, on the still cold nights, he pointed his nose at a star and howled long and wolf-like, it was his ancestors, dead and dust, pointing nose at star and howling down through the centuries and through him.\n    When he pointed his nose halogen a star and howled long and wolf -like, it was his ancestors , dead and dust , who pointed his nose halogen the star .\n    He pointed his nose halogen a star and howled long and wolf -like, it was his ancestors , dead and dust , who had pointed his nose halogen the star .\n    It was his ancestors , dead and dust , who pointed his nose halogen a star and howled long and wolf -like when he pointed his nose halogen them .\n    His ancestors were dead and dust when he pointed his nose halogen a star and howled long and wolf -like.\n\n\n\n```\nFitzgerald_alliteration = paraphrase(Fitzgerald,0.2,0.3,3,20,alliteration)\nprint(Fitzgerald)\nfor sentence in Fitzgerald_alliteration:\n  print(sentence)\n```\n\n    And so with the sunshine and the great bursts of leaves growing on the trees, just as things grow in fast movies, I had that familiar conviction that life was beginning over again with the summer.\n    With the sunshine and the leaves cytogenesis on the trees , I had a feeling that life was change state to start over again with the season .\n    With the sunshine and the leaves cytogenesis on the trees , I had a feeling that life was change state to start again with the season .\n    With the sunshine and the leaves angiogenesis on the trees , I had a feeling that life was about to start again .\n    I had a feeling that life make sense change state to start over again with the season because of the sunshine and the cataphyll on the trees .\n\n\n\n```\nEliot_alliteration = paraphrase(Eliot,0.2,0.5,3,30,alliteration)\nprint(Eliot)\nfor sentence in Eliot_alliteration:\n  print(sentence)\n```\n\n    For years after Lydgate remembered the impression produced in him by this involuntary appeal\u2014this cry from soul to soul.\n    This cry from black music to black music was produced in Lydgate by this appeal .\n    For years after Lydgate remembered the impression produced in him by this involuntary appeal \u2014this cry from soul to soul .\n    The concave shape was create in him by this cry from soul to soul .\n\n\n\n```\nDickens_rhyming = paraphrase(Dickens,0.4,0.5,3,30,rhyming)\nprint(Dickens)\nfor sentence in Dickens_rhyming:\n  print(sentence)\n```\n\n    My meaning simply is, that whatever I have tried to do in life, I have tried with all my heart to do well\n    Whatever chemical element solicit tried to motivate metallic element life , chemical element solicit always tried to motivate well .\n    Whatever chemical element solicit tried to motivate metallic element my life , chemical element solicit always tried to motivate well .\n    I mean that whatever chemical element solicit tried to motivate metallic element life , chemical element solicit always tried to motivate well .\n    Whatever I decide tried to tide over in life , I decide tried to tide over well .\n\n\n\n```\nTwain_rhyming = paraphrase(Twain,0.3,0.5,3,30,rhyming)\nprint(Twain)\nfor sentence in Twain_rhyming:\n  print(sentence)\n```\n\n    Persons attempting to find a motive in this narrative will be prosecuted; persons  attempting to find a moral in it will be banished; persons attempting to find a plot in it will be shot.\n    Those trying to find a reason metallic element this narrative will equate prosecuted , those trying to find a moral metallic element it will equate banished , and those trying to find a plot metallic element it will equate shot .\n    If someone tries to find a reason metallic element this narrative , they legal document equate prosecuted , if they try to find a moral metallic element it , they legal document equate thrown out , and if they try to find a plot metallic element it , they legal document equate shot .\n    populate trying to find a motive will equate prosecuted , populate trying to find a moral will equate banished , and populate trying to find a plot will equate shot .\n\n\n\n```\nForster_rhyming = paraphrase(Forster,0.3,0.3,3,30,rhyming)\nprint(Forster)\nfor sentence in Forster_rhyming:\n  print(sentence)\n```\n\n    Most of life is so dull that there is nothing to be said about it, and the books and talk that would describe it as interesting are obliged to exaggerate, in the hope of justifying their own existence.\n    The books and talk that would describe it chemical element interesting equate obliged to exaggerate , in the hope of legitimate their own existence , chemical element most life equate so dull that there equate nothing to equate said about it .\n\n\n\n```\nGrahame_rhyming = paraphrase(Grahame,0.3,0.25,3,30,rhyming)\nfor sentence in Grahame_rhyming:\n  print(sentence)\n```\n\n    With no one to check his amendment or call on the carpet him linear unit associate degree unfriendly spirit , The Mole let himself go .\n    Toad let himself go because chemical element didn 't have any one to check his amendment or call on the carpet him linear unit associate degree unfriendly evil spirit .\n    The Mole equate good laotian monetary unit listening , and with no one to call on the carpet or receipt his commercial document , chemical element let himself go .\n\n\n\n```\nJoyce_rhyming = paraphrase(Joyce,0.33,0.5,3,30,rhyming)\nprint(Joyce)\nfor sentence in Joyce_rhyming:\n  print(sentence)\n```\n\n    A certain pride, a certain awe, withheld him from offering to God even one prayer at night, though he knew it was in God\u2019s power to take away his life while he slept and hurl his soul hellward ere he could beg for mercy.\n    chemical element knew it was linear unit God 's power to take away his life hot spell chemical element slept , but chemical element didn 't offer a prayer at night because of his pride .\n    chemical element knew it was linear unit God 's power to take away his life hot spell chemical element slept , but chemical element didn 't request to God at night because of his pride and awe .\n    chemical element knew it was metallic element God 's power to take away his life hot spell chemical element slept and that 's why chemical element didn 't offer a prayer at night .\n\n\n\n```\nLondon_rhyming = paraphrase(London,0.3,0.3,3,30,rhyming)\nprint(London)\nfor sentence in London_rhyming:\n  print(sentence)\n```\n\n    When, on the still cold nights, he pointed his nose at a star and howled long and wolf-like, it was his ancestors, dead and dust, pointing nose at star and howling down through the centuries and through him.\n    He pointed his nose at nucleotide star and howled long and wolf -like, it was his ancestors united nations agency pointed nose at star and howled down through the time period and through him .\n    He pointed his nose at nucleotide star and howled long and wolf -like, it was his ancestors united nations agency pointed nose at star and howled down through the time period .\n    It was his ancestors , dead and dust , united nations agency pointed his nose at nucleotide star and howled through the time period and through him , when he pointed his nose at nucleotide star .\n    It was his ancestors , dead and dust , united nations agency pointed his nose at nucleotide star and howled down through the time period and through him , when he pointed his nose at nucleotide star .\n    His ancestors , dead and dust , depend the ones united nations agency pointed his nose at nucleotide star and howled long and wolf -like.\n\n\n\n```\nFitzgerald_rhyming = paraphrase(Fitzgerald,0.3,0.3,3,30,rhyming)\nfor sentence in Fitzgerald_rhyming:\n  print(sentence)\n```\n\n    With the sunshine and the plant organ angiogenesis on the trees , halogen believed that life would begin again with the summer .\n    And so with the sunshine and the great detonation of plant organ angiogenesis on the trees , just as things grow in fast coming attraction , halogen had that familiar murder conviction that life was beginning maiden over again with the season .\n    chemical element had a zeitgeist that life account for change state to start over again with the summer because of the attribute and the plant organ on the trees .\n\n\n\n```\nEliot_rhyming = paraphrase(Eliot,0.3,0.3,3,30,rhyming)\nprint(Eliot)\nfor sentence in Eliot_rhyming:\n  print(sentence)\n```\n\n    For years after Lydgate remembered the impression produced in him by this involuntary appeal\u2014this cry from soul to soul.\n    This cry from soul to soul was the impression Lydgate compel after chemical element heard this appeal .\n    This cry from soul to soul was the impression that Lydgate compel after chemical element heard this appeal .\n    This cry from soul to soul was the impression Lydgate compel when chemical element heard this appeal .\n    This cry from soul to soul was the impression Lydgate compel after chemical element remembered this appeal .\n    The dimple was create by mental act in him by this cry from soul to soul .\n\n\n\n```\nDickens_assonance = paraphrase(Dickens,0.1,0.15,3,30,assonance)\nfor sentence in Dickens_assonance:\n  print(sentence)\n```\n\n\n```\nTwain_assonance = paraphrase(Twain,0.2,0.1,3,30,assonance)\nfor sentence in Twain_assonance:\n  print(sentence)\n```\n\n\n```\nForster_assonance = paraphrase(Forster,0.1,0.1,3,30,assonance)\nfor sentence in Forster_assonance:\n  print(sentence)\n```\n\n\n```\nGrahame_assonance = paraphrase(Grahame,0.2,0.1,3,30,assonance)\nfor sentence in Grahame_assonance:\n  print(sentence)\n```\n\n\n```\nJoyce_assonance = paraphrase(Joyce,0.2,0.1,3,30,assonance)\nfor sentence in Joyce_assonance:\n  print(sentence)\n```\n\n\n```\nLondon_assonance = paraphrase(London,0.2,0.1,3,30,assonance)\nfor sentence in London_assonance:\n  print(sentence)\n```\n\n\n```\nFitzgerald_assonance = paraphrase(Fitzgerald,0.2,0.1,3,30,assonance)\nfor sentence in Fitzgerald_assonance:\n  print(sentence)\n```\n\n\n```\nEliot_assonance = paraphrase(Eliot,0.2,0.1,3,30,assonance)\nfor sentence in Eliot_assonance:\n  print(sentence)\n```\n", "meta": {"hexsha": "82b70f470f220506f2f2de9e48dd111172f9caa1", "size": 178165, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Dataflow/Full_Executer_WordShop.ipynb", "max_stars_repo_name": "Smurf-maker/WordShop", "max_stars_repo_head_hexsha": "ac0095ee28207f23744337d4cb35c5ca764d7e26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Dataflow/Full_Executer_WordShop.ipynb", "max_issues_repo_name": "Smurf-maker/WordShop", "max_issues_repo_head_hexsha": "ac0095ee28207f23744337d4cb35c5ca764d7e26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Dataflow/Full_Executer_WordShop.ipynb", "max_forks_repo_name": "Smurf-maker/WordShop", "max_forks_repo_head_hexsha": "ac0095ee28207f23744337d4cb35c5ca764d7e26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.8257056728, "max_line_length": 998, "alphanum_fraction": 0.5512811158, "converted": true, "num_tokens": 21909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14033626027631768, "lm_q2_score": 0.018833127790889078, "lm_q1q2_score": 0.0026429707234793616}}
{"text": "## Train a Deep Q Learning (DQN) agent on the MSPacman-v0\n\n## Mounting google drive for saving the video\n\n\n```\nfrom google.colab import drive\ndrive.mount('/content/gdrive')\n```\n\n    Drive already mounted at /content/gdrive; to attempt to forcibly remount, call drive.mount(\"/content/gdrive\", force_remount=True).\n\n\n## Get the MSPackman ready from Atari\n\n\n```\nimport urllib.request\nurllib.request.urlretrieve('http://www.atarimania.com/roms/Roms.rar','Roms.rar')\n!pip install unrar\n!unrar x Roms.rar\n!mkdir rars\n!mv HC\\ ROMS.zip   rars\n!mv ROMS.zip  rars\n!python -m atari_py.import_roms rars\n```\n\n    Collecting unrar\n      Downloading unrar-0.4-py3-none-any.whl (25 kB)\n    Installing collected packages: unrar\n    Successfully installed unrar-0.4\n    \n    UNRAR 5.50 freeware      Copyright (c) 1993-2017 Alexander Roshal\n    \n    \n    Extracting from Roms.rar\n    \n    Extracting  HC ROMS.zip                                                  \b\b\b\b 36%\b\b\b\b\b  OK \n    Extracting  ROMS.zip                                                     \b\b\b\b 74%\b\b\b\b 99%\b\b\b\b\b  OK \n    All OK\n    copying adventure.bin from ROMS/Adventure (1980) (Atari, Warren Robinett) (CX2613, CX2613P) (PAL).bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/adventure.bin\n    copying air_raid.bin from ROMS/Air Raid (Men-A-Vision) (PAL) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/air_raid.bin\n    copying alien.bin from ROMS/Alien (1982) (20th Century Fox Video Games, Douglas 'Dallas North' Neubauer) (11006) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/alien.bin\n    copying amidar.bin from ROMS/Amidar (1982) (Parker Brothers, Ed Temple) (PB5310) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/amidar.bin\n    copying assault.bin from ROMS/Assault (AKA Sky Alien) (1983) (Bomb - Onbase) (CA281).bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/assault.bin\n    copying asterix.bin from ROMS/Asterix (AKA Taz) (07-27-1983) (Atari, Jerome Domurat, Steve Woita) (CX2696) (Prototype).bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/asterix.bin\n    copying asteroids.bin from ROMS/Asteroids (1981) (Atari, Brad Stewart - Sears) (CX2649 - 49-75163) [no copyright] ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/asteroids.bin\n    copying atlantis.bin from ROMS/Atlantis (Lost City of Atlantis) (1982) (Imagic, Dennis Koble) (720103-1A, 720103-1B, IA3203, IX-010-04) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/atlantis.bin\n    copying bank_heist.bin from ROMS/Bank Heist (Bonnie & Clyde, Cops 'n' Robbers, Hold-Up, Roaring 20's) (1983) (20th Century Fox Video Games, Bill Aspromonte) (11012) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/bank_heist.bin\n    copying battle_zone.bin from ROMS/Battlezone (1983) (Atari - GCC, Mike Feinstein, Brad Rice) (CX2681) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/battle_zone.bin\n    copying beam_rider.bin from ROMS/Beamrider (1984) (Activision - Cheshire Engineering, David Rolfe, Larry Zwick) (AZ-037-04) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/beam_rider.bin\n    copying berzerk.bin from ROMS/Berzerk (1982) (Atari, Dan Hitchens - Sears) (CX2650 - 49-75168) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/berzerk.bin\n    copying bowling.bin from ROMS/Bowling (1979) (Atari, Larry Kaplan - Sears) (CX2628 - 6-99842, 49-75117) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/bowling.bin\n    copying boxing.bin from ROMS/Boxing - La Boxe (1980) (Activision, Bob Whitehead) (AG-002, CAG-002, AG-002-04) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/boxing.bin\n    copying breakout.bin from ROMS/Breakout - Breakaway IV (Paddle) (1978) (Atari, Brad Stewart - Sears) (CX2622 - 6-99813, 49-75107) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/breakout.bin\n    copying carnival.bin from ROMS/Carnival (1982) (Coleco - Woodside Design Associates, Steve 'Jessica Stevens' Kitchen) (2468) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/carnival.bin\n    copying centipede.bin from ROMS/Centipede (1983) (Atari - GCC) (CX2676) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/centipede.bin\n    copying chopper_command.bin from ROMS/Chopper Command (1982) (Activision, Bob Whitehead) (AX-015, AX-015-04) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/chopper_command.bin\n    copying crazy_climber.bin from ROMS/Crazy Climber (1983) (Atari - Roklan, Joe Gaucher, Alex Leavens) (CX2683) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/crazy_climber.bin\n    copying defender.bin from ROMS/Defender (1982) (Atari, Robert C. Polaro, Alan J. Murphy - Sears) (CX2609 - 49-75186) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/defender.bin\n    copying demon_attack.bin from ROMS/Demon Attack (Death from Above) (1982) (Imagic, Rob Fulop) (720000-200, 720101-1B, 720101-1C, IA3200, IA3200C, IX-006-04) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/demon_attack.bin\n    copying donkey_kong.bin from ROMS/Donkey Kong (1982) (Coleco - Woodside Design Associates - Imaginative Systems Software, Garry Kitchen) (2451) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/donkey_kong.bin\n    copying double_dunk.bin from ROMS/Double Dunk (Super Basketball) (1989) (Atari, Matthew L. Hubbard) (CX26159) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/double_dunk.bin\n    copying elevator_action.bin from ROMS/Elevator Action (1983) (Atari, Dan Hitchens) (CX26126) (Prototype) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/elevator_action.bin\n    copying enduro.bin from ROMS/Enduro (1983) (Activision, Larry Miller) (AX-026, AX-026-04) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/enduro.bin\n    copying fishing_derby.bin from ROMS/Fishing Derby (1980) (Activision, David Crane) (AG-004) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/fishing_derby.bin\n    copying freeway.bin from ROMS/Freeway (1981) (Activision, David Crane) (AG-009, AG-009-04) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/freeway.bin\n    copying frogger.bin from ROMS/Frogger (1982) (Parker Brothers, Ed English, David Lamkins) (PB5300) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/frogger.bin\n    copying frostbite.bin from ROMS/Frostbite (1983) (Activision, Steve Cartwright) (AX-031) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/frostbite.bin\n    copying galaxian.bin from ROMS/Galaxian (1983) (Atari - GCC, Mark Ackerman, Tom Calderwood, Glenn Parker) (CX2684) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/galaxian.bin\n    copying gopher.bin from ROMS/Gopher (Gopher Attack) (1982) (U.S. Games Corporation - JWDA, Sylvia Day, Todd Marshall, Robin McDaniel, Henry Will IV) (VC2001) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/gopher.bin\n    copying gravitar.bin from ROMS/Gravitar (1983) (Atari, Dan Hitchens, Mimi Nyden) (CX2685) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/gravitar.bin\n    copying hero.bin from ROMS/H.E.R.O. (1984) (Activision, John Van Ryzin) (AZ-036-04) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/hero.bin\n    copying ice_hockey.bin from ROMS/Ice Hockey - Le Hockey Sur Glace (1981) (Activision, Alan Miller) (AX-012, CAX-012, AX-012-04) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/ice_hockey.bin\n    copying jamesbond.bin from ROMS/James Bond 007 (James Bond Agent 007) (1984) (Parker Brothers - On-Time Software, Joe Gaucher, Louis Marbel) (PB5110) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/jamesbond.bin\n    copying journey_escape.bin from ROMS/Journey Escape (1983) (Data Age, J. Ray Dettling) (112-006) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/journey_escape.bin\n    copying kaboom.bin from ROMS/Kaboom! (Paddle) (1981) (Activision, Larry Kaplan, David Crane) (AG-010, AG-010-04) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/kaboom.bin\n    copying kangaroo.bin from ROMS/Kangaroo (1983) (Atari - GCC, Kevin Osborn) (CX2689) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/kangaroo.bin\n    copying keystone_kapers.bin from ROMS/Keystone Kapers - Raueber und Gendarm (1983) (Activision, Garry Kitchen - Ariola) (EAX-025, EAX-025-04I - 711 025-725) (PAL).bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/keystone_kapers.bin\n    copying king_kong.bin from ROMS/King Kong (1982) (Tigervision - Software Electronics Corporation, Karl T. Olinger - Teldec) (7-001 - 3.60001 VE) (PAL).bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/king_kong.bin\n    copying koolaid.bin from ROMS/Kool-Aid Man (Kool Aid Pitcher Man) (1983) (M Network, Stephen Tatsumi, Jane Terjung - Kool Aid) (MT4648) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/koolaid.bin\n    copying krull.bin from ROMS/Krull (1983) (Atari, Jerome Domurat, Dave Staugas) (CX2682) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/krull.bin\n    copying kung_fu_master.bin from ROMS/Kung-Fu Master (1987) (Activision - Imagineering, Dan Kitchen, Garry Kitchen) (AG-039-04) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/kung_fu_master.bin\n    copying laser_gates.bin from ROMS/Laser Gates (AKA Innerspace) (1983) (Imagic, Dan Oliver) (720118-2A, 13208, EIX-007-04I) (PAL).bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/laser_gates.bin\n    copying lost_luggage.bin from ROMS/Lost Luggage (Airport Mayhem) (1982) (Apollo - Games by Apollo, Larry Minor, Ernie Runyon, Ed Salvo) (AP-2004) [no opening scene] ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/lost_luggage.bin\n    copying montezuma_revenge.bin from ROMS/Montezuma's Revenge - Featuring Panama Joe (1984) (Parker Brothers - JWDA, Henry Will IV) (PB5760) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/montezuma_revenge.bin\n    copying mr_do.bin from ROMS/Mr. Do! (1983) (CBS Electronics, Ed English) (4L4478) (PAL).bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/mr_do.bin\n    copying ms_pacman.bin from ROMS/Ms. Pac-Man (1983) (Atari - GCC, Mark Ackerman, Glenn Parker) (CX2675) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/ms_pacman.bin\n    copying name_this_game.bin from ROMS/Name This Game (Guardians of Treasure) (1983) (U.S. Games Corporation - JWDA, Roger Booth, Sylvia Day, Ron Dubren, Todd Marshall, Robin McDaniel, Wes Trager, Henry Will IV) (VC1007) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/name_this_game.bin\n    copying pacman.bin from ROMS/Pac-Man (1982) (Atari, Tod Frye) (CX2646) (PAL).bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/pacman.bin\n    copying phoenix.bin from ROMS/Phoenix (1983) (Atari - GCC, Mike Feinstein, John Mracek) (CX2673) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/phoenix.bin\n    copying video_pinball.bin from ROMS/Pinball (AKA Video Pinball) (Zellers).bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/video_pinball.bin\n    copying pitfall.bin from ROMS/Pitfall! - Pitfall Harry's Jungle Adventure (Jungle Runner) (1982) (Activision, David Crane) (AX-018, AX-018-04) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/pitfall.bin\n    copying pooyan.bin from ROMS/Pooyan (1983) (Konami) (RC 100-X 02) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/pooyan.bin\n    copying private_eye.bin from ROMS/Private Eye (1984) (Activision, Bob Whitehead) (AG-034-04) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/private_eye.bin\n    copying qbert.bin from ROMS/Q-bert (1983) (Parker Brothers - Western Technologies, Dave Hampton, Tom Sloper) (PB5360) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/qbert.bin\n    copying riverraid.bin from ROMS/River Raid (1982) (Activision, Carol Shaw) (AX-020, AX-020-04) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/riverraid.bin\n    copying road_runner.bin from patched version of ROMS/Road Runner (1989) (Atari - Bobco, Robert C. Polaro) (CX2663) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/road_runner.bin\n    copying robotank.bin from ROMS/Robot Tank (Robotank) (1983) (Activision, Alan Miller) (AZ-028, AG-028-04) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/robotank.bin\n    copying seaquest.bin from ROMS/Seaquest (1983) (Activision, Steve Cartwright) (AX-022) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/seaquest.bin\n    copying sir_lancelot.bin from ROMS/Sir Lancelot (1983) (Xonox - K-Tel Software - Product Guild, Anthony R. Henderson) (99006, 6220) (PAL).bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/sir_lancelot.bin\n    copying skiing.bin from ROMS/Skiing - Le Ski (1980) (Activision, Bob Whitehead) (AG-005, CAG-005, AG-005-04) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/skiing.bin\n    copying solaris.bin from ROMS/Solaris (The Last Starfighter, Star Raiders II, Universe) (1986) (Atari, Douglas Neubauer, Mimi Nyden) (CX26136) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/solaris.bin\n    copying space_invaders.bin from ROMS/Space Invaders (1980) (Atari, Richard Maurer - Sears) (CX2632 - 49-75153) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/space_invaders.bin\n    copying star_gunner.bin from ROMS/Stargunner (1983) (Telesys, Alex Leavens) (1005) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/star_gunner.bin\n    copying surround.bin from ROMS/Surround (32 in 1) (Bit Corporation) (R320).bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/surround.bin\n    copying tennis.bin from ROMS/Tennis - Le Tennis (1981) (Activision, Alan Miller) (AG-007, CAG-007) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/tennis.bin\n    copying time_pilot.bin from ROMS/Time Pilot (1983) (Coleco - Woodside Design Associates, Harley H. Puthuff Jr.) (2663) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/time_pilot.bin\n    copying trondead.bin from ROMS/TRON - Deadly Discs (TRON Joystick) (1983) (M Network - INTV - APh Technological Consulting, Jeff Ronne, Brett Stutz) (MT5662) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/trondead.bin\n    copying tutankham.bin from ROMS/Tutankham (1983) (Parker Brothers, Dave Engman, Dawn Stockbridge) (PB5340) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/tutankham.bin\n    copying up_n_down.bin from ROMS/Up 'n Down (1984) (SEGA - Beck-Tech, Steve Beck, Phat Ho) (009-01) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/up_n_down.bin\n    copying venture.bin from ROMS/Venture (1982) (Coleco, Joseph Biel) (2457) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/venture.bin\n    copying pong.bin from ROMS/Video Olympics - Pong Sports (Paddle) (1977) (Atari, Joe Decuir - Sears) (CX2621 - 99806, 6-99806, 49-75104) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/pong.bin\n    copying wizard_of_wor.bin from ROMS/Wizard of Wor (1982) (CBS Electronics - Roklan, Joe Hellesen, Joe Wagner) (M8774, M8794) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/wizard_of_wor.bin\n    copying yars_revenge.bin from ROMS/Yars' Revenge (Time Freeze) (1982) (Atari, Howard Scott Warshaw - Sears) (CX2655 - 49-75167) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/yars_revenge.bin\n    copying zaxxon.bin from ROMS/Zaxxon (1983) (Coleco) (2454) ~.bin to /usr/local/lib/python3.7/dist-packages/atari_py/atari_roms/zaxxon.bin\n\n\n## Packages\nFirst, let\u2019s import needed packages. Firstly, we need game (gym)\nneural networks (torch.nn)\noptimization (torch.optim)\n\n\n```\nimport gym\nimport cv2\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt\nfrom collections import deque\nimport numpy as np\nimport random\nimport datetime\n```\n\n\n```\nreward_number = 50\n```\n\nDQN Algorithm\n-------------\nWe train a policy that tries to maximize the discounted,\ncumulative reward\n$R_{t_0} = \\sum_{t=t_0}^{\\infty} \\gamma^{t - t_0} r_t$, where\n$R_{t_0}$ is *return*. The discount, $\\gamma$ is the discount, between $0$ and $1$\n\n\nQ-learning tries to find a function\n$Q^*: State \\times Action \\rightarrow \\mathbb{R}$, maximizes rewards:\n\n\\begin{align}\\pi^*(s) = \\arg\\!\\max_a \\ Q^*(s, a)\\end{align}\n\nHowever, we don't know $Q^*$. So, we use neural network as a approximators, we can simply create one and train it to resemble $Q^*$.\n\nFor our training update rule, we'll use a fact that every $Q$\nfunction for some policy obeys the Bellman equation:\n\n\\begin{align}Q^{\\pi}(s, a) = r + \\gamma Q^{\\pi}(s', \\pi(s'))\\end{align}\n\nThe difference between the two sides of the equality is known as the temporal difference error, $\\delta$:\n\n\\begin{align}\\delta = Q(s, a) - (r + \\gamma \\max_a Q(s', a))\\end{align}\n\n\n```\nclass CNN(torch.nn.Module):\n    def __init__(self):\n        super(CNN, self).__init__()\n        self.convolution1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3)\n        self.convolution2 = nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5)\n        self.convolution3 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=7)\n        self.fc1 = nn.Linear(in_features=1792, out_features=256)\n        self.fc2 = nn.Linear(in_features=256, out_features=128)\n        self.fc3 = nn.Linear(in_features=128, out_features=256)\n        self.fc4 = nn.Linear(in_features=256, out_features=32)\n        self.fc5 = nn.Linear(in_features=32, out_features=9)\n   \n    def forward(self, x):\n        x = x.cuda()\n        x = F.relu(F.max_pool2d(self.convolution1(x), 3))\n        x = F.relu(F.max_pool2d(self.convolution2(x), 3))\n        x = F.relu(F.max_pool2d(self.convolution3(x), 3, 2))\n        x = x.reshape(x.size(0), -1)\n        x = F.relu(self.fc1(x))\n        x = F.relu(self.fc2(x))\n        x = F.relu(self.fc3(x))\n        x = F.relu(self.fc4(x))\n        x = self.fc5(x)\n        return x\n\n        ## Quick exercise: Please draw the CNN arch.\n```\n\n\n```\nmodel = CNN()\n```\n\n##function to ensure that our code uses the GPU if available, and defaults to using the CPU if it isn't.\n\n\n```\n#function to ensure that our code uses the GPU if available, and defaults to using the CPU if it isn't.\ndef get_default_device():\n    \"\"\"Pick GPU if available, else CPU\"\"\"\n    if torch.cuda.is_available():\n        return torch.device('cuda')\n    else:\n        return torch.device('cpu')\n    \n# a function that can move data and model to a chosen device.    \ndef to_device(data, device):\n    \"\"\"Move tensor(s) to chosen device\"\"\"\n    if isinstance(data, (list,tuple)):\n        return [to_device(x, device) for x in data]\n    return data.to(device, non_blocking=True)\n```\n\n## Loss Function and Optimizer\n\n\n```\ncriterion = ## your loss function from nn\noptimizer = ## your optimizer \n```\n\n## DQN Agent\n### Replay Memory\nWe\u2019ll be using experience replay memory for training our DQN. It stores the transitions that the agent observes, allowing us to reuse this data later. By sampling from it randomly, the transitions that build up a batch are decorrelated. It has been shown that this greatly stabilizes and improves the DQN training procedure.\n### Hyperparameters\n\n\n```\nclass DQNAgent:\n    def __init__(self, action_size = 9):\n        self.state_size = 3\n        self.action_size = action_size\n        self.memory_n = deque(maxlen=2000)\n        self.memory_p = deque(maxlen=2000)\n        self.gamma = 0.95    # discount rate\n        self.epsilon = 1.0  # exploration rate\n        self.epsilon_min = 0.2\n        self.epsilon_decay = 0.995\n        self.learning_rate = 0.001\n        self.model = model\n\n    def remember(self, state, action, reward, next_state, done):\n        if reward == 0:\n            self.memory_p.append((state, action, reward, next_state, done))\n        else:\n            self.memory_n.append((state, action, reward, next_state, done))\n    def act(self, state):\n        if np.random.rand() <= self.epsilon:\n            return random.randrange(self.action_size)\n        state_tensor = torch.from_numpy(state).float()\n        act_values = self.model(state_tensor).cpu().detach().numpy()\n        return np.argmax(act_values[0])  # returns action\n\n    def replay(self, batch_size):\n        if len(agent.memory_n) > batch_size / 2:\n            print(\"Negative batch ready:\")\n            minibatch_n = random.sample(self.memory_n, 5)\n            minibatch_p = random.sample(self.memory_p, 59)\n            minibatch = random.sample((minibatch_p+minibatch_n), batch_size)\n        else:\n            minibatch = random.sample(self.memory_p, batch_size)\n        for state, action, reward, next_state, done in minibatch:\n            ns_model = self.model(torch.from_numpy(next_state).float()).cpu().detach().numpy()\n            if reward == 0:\n                reward = 1.0001\n                target = reward * np.amax(ns_model[0])\n                target_f = ns_model\n                target_f[0][np.argmax(ns_model[0])] = target                     \n            else:\n                reward = reward_number\n                target = reward * np.amin(ns_model[0])\n                target_max = 0.0001 * np.amax(ns_model[0])\n                target_f = ns_model\n                target_f[0][action] = target\n                target_f[0][random.choice([i for i in range(0,9) if i not in [action]])] = target_max\n                self.train(next_state, target_f, epochs=1)\n        if self.epsilon > self.epsilon_min:\n            self.epsilon *= self.epsilon_decay\n            \n    def train(self, input, target, epochs = 1):\n        input = torch.from_numpy(input).float().cuda()\n        target = torch.from_numpy(target).float().cuda()\n        y_pred = 0\n        for t in range(1):\n            y_pred = model(input)\n            loss = - criterion(y_pred, target)\n            # print(t, loss.item())\n            optimizer.zero_grad()\n            loss.backward()\n            optimizer.step() \n\n    def load_all(self, name):\n        loaded = torch.load(name)\n        self.memory_n = loaded['memory_n']\n        self.memory_p = loaded['memory_p']\n        self.model.load_state_dict(loaded['state'])\n        \n    def save_all(self, name):\n        torch.save({'state': self.model.state_dict(),\n                    'memory_n': self.memory_n,\n                    'memory_p': self.memory_p\n                   }, name)\n        \n    def load(self, name):\n        self.model.load_state_dict(torch.load(name))\n        \n    def save(self, name):\n        torch.save(self.model.state_dict(), name)\n\n\n\n```\n\n\n```\nenv = gym.make('MsPacman-v0')\nstate_size = env.observation_space.shape\naction_size = env.action_space.n\n\n```\n\n\n```\nagent = DQNAgent()\n```\n\n\n```\ndone = False\nbatch_size = 64\n\n```\n\n## Main training loop\n\n\n```\nEPISODES = 100\nfor e in range(EPISODES):\n    fourcc = cv2.VideoWriter_fourcc(*'XVID')\n    vw = cv2.VideoWriter('gdrive/' + \"Reward_number_\" + str(reward_number) + \"_\" + str(e) + str(datetime.datetime.now()) +  '.avi', fourcc, 4, (160,210))\n    state = env.reset()\n    state = np.reshape(state, (1, 210,160,3)).transpose(0,3,1,2)/255\n    for time in range(1000000000):\n        print(time)\n        action = agent.act(state)\n        next_state, reward, done, _ = env.step(action)\n        vw.write(next_state)        \n        reward = reward if not done else 10\n        reward = reward if reward ==0 else 10\n        if reward != 0:\n            print(\"ATTENTION NEGATIVE REWARD\",reward)\n        next_state = np.reshape(next_state, (1, 210,160,3)).transpose(0,3,1,2)/255\n        agent.remember(state, action, reward, next_state, done)\n        state = next_state\n        if done:\n            vw.release()\n            agent.save('gdrive' + \"Reward_number_\" + str(reward_number) + \"_\"\"Frames:_\" + str(time) + \"_Episode_\" +str(e) + \"_Date_\" + str(datetime.datetime.now()) + '.pt')\n            print(\"episode: {}/{}, score: {}, e: {:.2}\".format(e, EPISODES, time, agent.epsilon))\n            break\n        if (len(agent.memory_p) > batch_size) & (len(agent.memory_n) > batch_size/2) :\n            agent.replay(batch_size)\n```\n", "meta": {"hexsha": "ea30b2696637ce040a992b5a621d49496b6276a2", "size": 100315, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lecture-08/lab.ipynb", "max_stars_repo_name": "LuxTheDude/modern-ai-course", "max_stars_repo_head_hexsha": "1cff6515f53354a0c2a6ae783ec116bfc3e06b74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-08-30T08:16:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T11:05:10.000Z", "max_issues_repo_path": "lecture-08/lab.ipynb", "max_issues_repo_name": "LuxTheDude/modern-ai-course", "max_issues_repo_head_hexsha": "1cff6515f53354a0c2a6ae783ec116bfc3e06b74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lecture-08/lab.ipynb", "max_forks_repo_name": "LuxTheDude/modern-ai-course", "max_forks_repo_head_hexsha": "1cff6515f53354a0c2a6ae783ec116bfc3e06b74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2021-08-30T08:17:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-25T19:11:08.000Z", "avg_line_length": 37.2364513734, "max_line_length": 2101, "alphanum_fraction": 0.4539899317, "converted": true, "num_tokens": 7390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12421300186801372, "lm_q2_score": 0.020964242500261212, "lm_q1q2_score": 0.0026040314928464387}}
{"text": "[](https://github.com/liushiru/End-to-end-ASR-Pytorch)\n\n# Project Members\n\n### Module Code: **CS5242** \n\n#### Semester: AY2021-22 Sem 1\n\n#### Group 40\n\n- Liu Shiru (A0187939A)\n- Lim Yu Rong, Samuel (A0183921A)\n- Yee Xun Wei (A0228597L)\n\n\n# **README: Important Notes**\n\nThis project can **NOT** be trained or run in this notebook. This is because it was forked from a project repository and has a fair amount of setup. Refer to [our Github fork](https://github.com/liushiru/End-to-end-ASR-Pytorch \"Our fork\") for the full project.\n\n---\n\nTo run this project:\n1. Clone the repository.\n2. Install requirements via `~/requirements.txt`.\n\n## Dataset\n\nData is collected from the [Ted2srt webpage](https://ted2srt.org \"Ted2srt Homepage\").\n\nRun `python3 scraper/preprocess.py` from root direcory to scrape and generate dataset.\nThe script will:\n1. Scrape data from website.\n2. Preprocess the data\n3. Split the data into train-dev-test sets.\n\nScraped data is saved at `scraper/data/`, processed data will be saved to `data/`.\nAlternatively, download data [here](https://nusu-my.sharepoint.com/:u:/g/personal/e0674581_u_nus_edu/EdCosjueRfVIm2kQK3RKBdYBrtlVWU8hsBzcjG7cb9Uo3w?e=fkWh09).\n\n\n## Training\n\nTo train each model:\n\n1. In the root directory, run the command `python3 main.py --config config/<dataset>/<config_file>.yaml --njobs 8`.\n\n### Configuration Files\n\nTo use our dataset, set `<dataset>` as `ted` to use scraped data, or `libri` to use public data from [OpenSRL](https://www.openslr.org/12/).\n\nConfiguration files are stored as:\n\n#### Train Extractors\n\n| Extractor | Classifier | Configuration file |\n|-----------|------------|--------------------|\n| MLP       | RNN        | mlp_rnn.yaml       |\n| CNN       | RNN        | cnn_rnn.yaml       |\n| ANN       | RNN        | ann_rnn.yaml       |\n| RNN       | RNN        | rnn_rnn.yaml       |\n\n#### Train Classifiers\n\n| Extractor | Classifier | Configuration file |\n|-----------|------------|--------------------|\n| CNN       | MLP        | cnn_mlp.yaml       |\n| CNN       | CNN        | cnn_cnn.yaml       |\n| CNN       | ANN        | cnn_ann.yaml       |\n\n**We advise that a Linux machine should be used**, since some elements in the project may be buggy when used with Windows or even MacOS.\n\nFurther information can be found in `~/README.md`.\n\n---\n\n# Problem Statement and Motivation\n\nThe Internet of Things (IoT) is becoming relevant in daily life as a natural interface for literate and illiterate users. One important feature of IoT is its ability to provide a hands-free solution for navigating daily tasks: e.g., being able to drive and simultaneously give commands to an IoT device. Speech recognition technology is therefore a key step in the field of IoT.\n\n**Automatic Speech Recognition (ASR)** is traditionally done through a Gaussian Mixture Model-Hidden Markov Model process. However, the rise of Neural Networks (NNs) has completely changed the field of ASR. Most modern ASR software is built on a combination of different NN structures. For this project, we therefore aim to study the performance of individual end-to-end NN structures (e.g. MLP, RNN) independently in this task, to evaluate their strengths and compare them.\n\nSpecifically, we aim to test the effectiveness of 4 types of NN architectures (MLP, CNN, RNN, ANN) in correctly parsing audio sentences of variable length. An expected input would be an audio recording of \u201cThis is a test sentence\u201d, and the corresponding expected output would be the text \u201cThis is a test sentence\u201d.\n\nThe codebase used in this report is forked from the [End-to-end-ASR repository](https://github.com/Alexander-H-Liu/End-to-end-ASR-Pytorch \"End-to-end-ASR GitHub\") by Alexander Liu.\n\n# Data Collection\n\n### Data Source\n\nData was collected from the [Ted2srt webpage](https://ted2srt.org \"Ted2srt Homepage\"). \n\nEach talk is originally presented as a video, with a single speaker talking. The videos are typically several minutes long.\n\nTed2srt provides download links for the video, as well as timestamp-annotated transcripts (i.e. SRTs) for most of its videos. These can be seen in the sidebar of [this sample talk](https://ted2srt.org/talks/anil_seth_how_your_brain_invents_your_self \"Sample TED Talk\"), for example.\n\n---\n\n### Scraper Inputs/Outputs\n\nThe two outputs of the scraper are:\n- Audio file containing speech\n- SRT text file containing timestamp-annotated transcript\n\nSince no audio download link is provided, the scraper scrapes the lowest-quality video, and subsequently converts it into an audio file. The video file is deleted, to save storage space. See the function `download_and_save_video_file()`.\n\nThe SRT transcript can be scraped normally. See the function `download_and_save_srt_transcript_text()`. Refer to the 'Data Preprocessing' section for more details on its format.\n\nAny talk which does not contain either the video or the SRT will not be scraped.\n\n---\n\n### Scraper code description\n\n`generate_all_srt_video_urls()` takes advantage of a URL-generation hack to generate any number of ted2srt URLs.\n\n`scrape_data_from_srt_url()`, `download_and_save_video_file()`, and `download_and_save_srt_transcript_text()` all use **BeautifulSoup** to parse the webpage, and the **requests** module to get data from the webpage.\n\nThe files downloaded are saved to a `data` folder and named after the title of the TED Talk.\n\nThe code for the scraper is shown below.\n\n\n\n```python\nfrom bs4 import BeautifulSoup\nfrom moviepy import editor\nimport requests\nfrom urllib import request, error\n\nfrom ast import literal_eval\nimport logging\nimport os\nimport shutil\nimport transcript\n\nos.chdir(os.path.dirname(__file__))\n\n# Logger setup\nlogger = logging.getLogger()\nlogging.basicConfig(level=\"INFO\", format=\"%(levelname)s: %(filename)s: %(message)s\")\n\n# Storage locations\nDATA_STORAGE_ROOT = os.path.join(os.getcwd(), \"data\")\n\n# Scraper constants\nTED_SRT_HOMEPAGE = \"https://ted2srt.org/\"\nTED_SRT_TALKS = \"talks/\"\nTED_SRT_TALKPAGE = TED_SRT_HOMEPAGE + TED_SRT_TALKS\n\n\ndef main(number_of_talks=200, starting_video_id=100):\n    if not os.path.isdir(DATA_STORAGE_ROOT):\n        try:\n            os.makedirs(DATA_STORAGE_ROOT)\n        except FileNotFoundError:\n            logging.error(\"Unable to create data storage folder.\")\n            raise Exception(\"Ensure that the current working directory is set to the project root.\")\n\n    _number_of_talks = number_of_talks  # Number of talks to attempt to scrape from\n    _starting_video_id = starting_video_id  # Start retrieving from this video id\n\n    logging.info(\"Parsing audio files with SRT transcripts from TED2SRT website...\")\n    video_urls = generate_all_srt_video_urls(TED_SRT_TALKPAGE, _number_of_talks, starting_video_id=_starting_video_id)\n    for url in video_urls:\n        scrape_data_from_srt_url(url)\n\n\n## Code that handles scraping from the TED2SRT website\n\n\ndef generate_all_srt_video_urls(base_url, number_of_urls, starting_video_id=1):\n    \"\"\"\n    Generates a list of urls to attempt to scrape from. This is designed to work specifically for the TED2SRT page.\n    This method will not check whether the links are valid. It will only generate the required links.\n\n    This method works because the TED2SRT page also stores videos mapped to their id. For example, visiting the webpage\n    \"homepage/talks/1\" returns the 1st video in id.\n\n    :param base_url: The base url of the TED2SRT talks page.\n    :param number_of_urls: The number of urls to generate.\n    :param starting_video_id: The starting video id, which defaults to the 1st video.\n    :return: Returns a list of urls.\n    \"\"\"\n    logging.info(f\"Generating {number_of_urls} starting from video id {starting_video_id}...\")\n    logging.warning(\"Many of these links might not work. Consider changing the value of _number_of_talks in line 52.\")\n    return [base_url + str(video_id) for video_id in range(starting_video_id, starting_video_id + number_of_urls)]\n\n\n# TED2SRT specific page constants\nVIDEO_NAME_KEY = \"slug\"\n\nVIDEO_DOWNLOAD_SUB_URL_KEY = \"mediaSlug\"\nSTART_OF_AUDIO_DOWNLOAD_URL = \"https://download.ted.com/talks/\"\nEND_OF_AUDIO_DOWNLOAD_URL = \"-320k.mp4\"\n\nVIDEO_SRT_ID_SUB_URL_KEY = \"id\"\nSTART_OF_SRT_TRANSCRIPT_URL = \"https://ted2srt.org/api/talks/\"\nEND_OF_SRT_TRANSCRIPT_URL = \"/transcripts/download/srt?lang=en\"\n\n\ndef scrape_data_from_srt_url(url):\n    \"\"\"\n    Attempts to scrape the audio file and SRT transcript from the given webpage.\n    Specifically written to scrape data from the TED2SRT page (root: https://ted2srt.org/).\n\n    If either the audio file or the SRT transcript does not exist, then this method will not scrape anything.\n    Otherwise, the data will be saved to a folder marked by the url.\n    :param url: The url to scrape data from.\n    :return: No return value.\n    \"\"\"\n    logger.info(f\"\\n\\nScraping from url: <{url}>\")\n    response = requests.get(url)\n    page_soup = BeautifulSoup(response.text, \"html.parser\")\n\n    # Identify the metadata object and parse the key phrases needed for video and SRT download\n    talk_metadata_script = page_soup.select(\"script\")\n    if not talk_metadata_script:\n        logging.warning(f\"The url {url} is invalid or has no metadata object. Continuing...\")\n        return\n\n    talk_metadata_string = talk_metadata_script[0].string\n    talk_metadata_object = literal_eval(talk_metadata_string.split(\" = \")[1])\n\n    srt_download_keyword = str(talk_metadata_object[VIDEO_SRT_ID_SUB_URL_KEY])\n    video_download_keyword = str(talk_metadata_object[VIDEO_DOWNLOAD_SUB_URL_KEY])\n    name_of_video = str(talk_metadata_object[VIDEO_NAME_KEY])\n\n    srt_download_url = START_OF_SRT_TRANSCRIPT_URL + srt_download_keyword + END_OF_SRT_TRANSCRIPT_URL\n    video_download_url = START_OF_AUDIO_DOWNLOAD_URL + video_download_keyword + END_OF_AUDIO_DOWNLOAD_URL\n\n    saved_folder_path = os.path.join(DATA_STORAGE_ROOT, name_of_video)\n\n    success_status = download_and_save_srt_transcript_text(srt_download_url, saved_folder_path)\n    if not success_status:\n        return\n\n    download_and_save_video_file(video_download_url, saved_folder_path)\n\n\n# Video constants\nVIDEO_FILE_EXTENSION = \"video.mp4\"\nAUDIO_FILE_EXTENSION = \"audio.mp3\"\nSRT_TRANSCRIPT_FILE_EXTENSION = \"srt_transcript.txt\"\n\n\ndef download_and_save_video_file(video_download_url, path_to_save_to):\n    \"\"\"\n    Downloads a video file, given its url link. Converts the video file to audio. Saves the file to the required folder.\n    Specifically designed for the TED2SRT website. Note that no audio download exists. Therefore, the video must be\n    downloaded first, and then converted into audio. To save space, the video file is then deleted.\n    :param video_download_url: The url to download the video from.\n    :param path_to_save_to: The folder name to save this file to.\n    :return: Returns True if the download was successful, and False otherwise.\n    \"\"\"\n    if not os.path.isdir(path_to_save_to):\n        os.mkdir(path_to_save_to)\n\n    video_file_saved_location = os.path.join(path_to_save_to, VIDEO_FILE_EXTENSION)\n    try:\n        _, _ = request.urlretrieve(video_download_url, filename=video_file_saved_location)\n        logger.info(\"Video file saved.\")\n    except error.HTTPError:\n        logger.warning(\"No video file of lowest quality found. Deleting this specific data folder...\")\n        srt_transcript_file_saved_location = os.path.join(path_to_save_to, SRT_TRANSCRIPT_FILE_EXTENSION)\n\n        if os.path.isfile(srt_transcript_file_saved_location):\n            shutil.rmtree(path_to_save_to)\n\n        if os.path.isdir(path_to_save_to):\n            os.rmdir(path_to_save_to)\n\n        return False\n\n    logger.info(\"Converting video.mp4 file to audio.mp3 file...\")\n    audio_file_saved_location = os.path.join(path_to_save_to, AUDIO_FILE_EXTENSION)\n\n    video = editor.VideoFileClip(video_file_saved_location)\n    audio = video.audio\n    audio.write_audiofile(audio_file_saved_location, verbose=False, logger=None)\n    video.close()\n\n    os.remove(video_file_saved_location)\n    logging.info(\"Audio file saved. Video file deleted.\")\n    return True\n\n\ndef download_and_save_srt_transcript_text(srt_transcript_url, path_to_save_to):\n    \"\"\"\n    Saves the transcript text to the required folder as a file. This is specifically designed to work with the TED2SRT\n    website.\n    :param srt_transcript_url: The url to download the srt transcript from.\n    :param path_to_save_to: The folder name to save this file to.\n    :return: Returns True if the download was successful, and False otherwise.\n    \"\"\"\n    if not os.path.isdir(path_to_save_to):\n        os.mkdir(path_to_save_to)\n\n    srt_transcript_file_saved_location = os.path.join(path_to_save_to, SRT_TRANSCRIPT_FILE_EXTENSION)\n    try:\n        _, _ = request.urlretrieve(srt_transcript_url, filename=srt_transcript_file_saved_location)\n        \n        # Check for SRT accuracy before downloading audio\n        srt_is_accurate = transcript.check_srt_accuracy(srt_transcript_file_saved_location)\n        if not srt_is_accurate:\n            logger.warning(\"SRT transcript not accurate. Deleting this specific data folder...\")\n            shutil.rmtree(path_to_save_to)\n            return False\n\n        logger.info(\"SRT transcript saved.\")\n        return True\n    except error.HTTPError:\n        logger.warning(\"No SRT transcript found. Deleting this specific data folder...\")\n        audio_file_saved_location = os.path.join(path_to_save_to, VIDEO_FILE_EXTENSION)\n\n        if os.path.isfile(audio_file_saved_location):\n            shutil.rmtree(path_to_save_to)\n\n        if os.path.isdir(path_to_save_to):\n            os.rmdir(path_to_save_to)\n\n        return False\n\n\nmain()\n\n```\n\n# Data Preprocessing\n\nPreprocess scraped data to input into `Dataset` and `DataLoader`. Includes data cleaning, cutting audio into multiple audio slices according to SRT annotated time and prepare label for each audio slice.\n\n---\n\n### Data Preprocessing Inputs/Outputs\n\n- Input from scraped audio files and SRT.\n- Output preprocessed ready dataset for ASR.\n\n---\n\n### Data Preprocessing Descriptions\n\nSymbols are removed from label and converted to lowercase.\n\nData that are less accurate are removed. Checking done for SRT that starts at the same time (e.g. `00:00:12,820 --> 00:00:14,820`). SRT that does not include introduction music time is filtered. Laughter and applause is removed.\n\nRaw SRT snippet\n```\n1\n00:00:12,312 --> 00:00:14,493\nSix months ago, I got an email\n\n2\n00:00:14,493 --> 00:00:15,900\nfrom a man in Israel\n```\nconverted to\n```\n<audio_id>-1 six months ago i got an email\n<audio_id>-2 from a man in israel\n```\nand stored at `<audio_id>.trans.txt`. Corresponding sliced audio files are named `<audio_id>_<audio_index>.mp3`.\n\nAfter `build_dataset()` has preprocessed the data, the data is split into  train-dev-test sets.\n\n\n```python\nimport os\nfrom joblib import Parallel, delayed\nfrom os.path import join\nfrom pathlib import Path\nimport random\nimport shutil\n\nimport scraper\nimport remove_applause\nimport re\nimport subprocess\nimport num2words\nimport pydub\nfrom pydub import AudioSegment\nfrom tqdm import tqdm\nimport logging\nlogger = logging.getLogger()\nlogging.basicConfig(level=\"INFO\", format=\"%(levelname)s: %(filename)s: %(message)s\")\n\n\nrandom.seed(42)\nAUDIO_EXTENSION = 'mp3'\nos.chdir(os.path.dirname(__file__))\ncorpus_path = '../data/TedSrt'\ntxt_norm = 'tedsrt-norm.txt'\ntxt_vocab = 'tedsrt-vocab.txt'\nprocessed_data_path = join(corpus_path, 'processed_data') # store all data in this folder before splitting\ntxt_norm_path = join(corpus_path, txt_norm)\ntxt_vocab_path = join(corpus_path, txt_vocab)\n\nsrc_path = 'data/' # raw data source\nratio=[.6, .2, .2] # train test split\n\n# filter audio and srt\nduration_diff = 7 # seconds\nrepeated_occurrence = 50\n\n\n\ndef clean_text(text):\n    '''\n    Text processing to clean text before saving as label\n    to lowercase, convert years to words, convert digits to words, remove symbols\n    '''\n    text = text.lower().strip('\\n')\n    text = re.sub(r'[^\\w\\s]', ' ', text)\n    text = ' '.join([num2words.num2words(i, to='year') if (i.isdigit() & (len(i) == 4)) else i for i in text.split()]) # year to words\n    text = ' '.join([num2words.num2words(i) if i.isdigit() else i for i in text.split()]) # num to words\n    text = re.sub(' +', ' ', text) # remove redundant spaces\n    text = text.replace('-', ' ')\n    return text\n\ndef normalize_text(text):\n    '''\n    Text processing to normalize text for language model training\n    should transform word numeral to numeric, normalize date formats, lemmatization; most not implemented currently\n    '''\n    text = text.lower().strip('\\n')\n    text = re.sub(r'[^\\w\\s]', ' ', text)\n    text = re.sub(' +', ' ', text) # remove redundant spaces\n    text = text.replace('-', ' ')\n    return text\n\ndef to_ms(string):\n    '''\n    Convert string '00:00:00,000' to milliseconds\n    to be used for audio slicing\n    '''\n    string = string.replace(',','')\n    hour, minute, second = string.split(':')\n    second = int(second)\n    second += int(hour) * 3600 * 1000\n    second += int(minute) * 60 * 1000\n    second = second\n    return second\n\ndef txt_to_trans(txt_file, file_name):\n    '''\n    Convert txt file to transcript format ready to be read into Dataset\n    lines formatted as 'filename-idx text_label'\n    return lines and time_slices\n    '''\n    file = open(txt_file, 'r')\n    lines = file.readlines()\n    file.close()\n    \n    transcript = [] # label for audio\n    txt_src = [] # label for language model\n    time_slices = []\n\n    for i in range(len(lines)):\n        idx = re.search('^[\\d]+$', lines[i].strip('\\ufeff'))\n        if idx:\n            idx = idx[0]\n            time_frame = re.findall('[0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3}', lines[i+1])\n            if time_frame:\n                start, end = to_ms(time_frame[0]), to_ms(time_frame[1])\n                time_slices.append((idx, (start, end)))\n\n                audio_label = lines[i+2]\n                audio_label = clean_text(audio_label)\n                new_line = f\"{file_name}-{idx} {audio_label}\"\n                transcript.append(new_line)\n                \n                lm_label = normalize_text(audio_label)\n                txt_src.append(lm_label)\n                \n    return transcript, time_slices, txt_src\n\ndef save_txt(txt, output_path):\n    '''\n    Save transcript to output_path\n    '''\n    if not os.path.exists(os.path.dirname(output_path)):\n        os.makedirs(os.path.dirname(output_path))\n\n    with open(output_path, 'a+') as f:\n        for line in txt:\n            f.write(f\"{line}\\n\")\n        f.close()\n\ndef check_ms_accuracy(time_slices):\n    '''\n    Check whether srt is accurate, remove those not accurate to milliseconds, check repeated occurrence of 820\n    '''\n    for time_slice in time_slices:\n        occurrence_820 = sum(1 for elem in time_slices if elem[1][0] % 1000 == 820)\n    if occurrence_820 > repeated_occurrence:\n        return occurrence_820\n    return 0\n\ndef check_intro_timing(audio_duration, audio_srt_duration):\n    '''\n    Check whether srt matches audio, remove those without taking water drop intro into account\n    '''\n    duration_diff = audio_duration - audio_srt_duration\n    if duration_diff > duration_diff:\n        return duration_diff\n    return 0\n\ndef build_dataset(src_path=src_path, sample=100):\n    '''\n    Build dataset from raw data scraper/data/\n    split audio into slices\n    convert srt to trans.txt ready for training\n    '''\n    shutil.rmtree(corpus_path, ignore_errors=True)\n    folders = os.listdir(src_path)[:100]\n    for idx, curr_folder in enumerate(tqdm(folders, desc=\"Building dataset from scraped data\")):\n        file_name = str(idx) #save the transcript as num, can be changed to folder name\n        output_path = join(processed_data_path, file_name)\n        txt_output_path = join(output_path, file_name + '.trans.txt')\n                \n        try:\n            txt_path = list(Path(join(src_path, curr_folder)).rglob('*.txt'))[0]\n            audio_path = list(Path(join(src_path, curr_folder)).rglob('*.' + AUDIO_EXTENSION))[0]\n        except:\n            tqdm.write(f'Data not complete {idx} {curr_folder}')\n            continue\n        transcript, time_slices, txt_src = txt_to_trans(txt_path, file_name)\n        \n        audio_file = AudioSegment.from_file(audio_path, AUDIO_EXTENSION)\n        \n        # check timing accuracy by milliseconds\n        ms_not_accurate = check_ms_accuracy(time_slices)\n        if ms_not_accurate:\n            shutil.rmtree(output_path, ignore_errors=True)\n            continue\n        \n        # check timing of audio intro\n        audio_duration = audio_file.duration_seconds\n        audio_srt_duration = time_slices[-1][-1][-1] / 1000\n        intro_not_matched = check_intro_timing(audio_duration, audio_srt_duration)\n        if intro_not_matched:\n            shutil.rmtree(output_path, ignore_errors=True)\n            continue\n        \n        # writing output\n        save_txt(transcript, txt_output_path)\n        save_txt(txt_src, txt_norm_path)\n        for idx, time_slice in time_slices:\n            audio_slice = audio_file[time_slice[0]:time_slice[1]]\n            audio_output_path = join(output_path, f\"{file_name}-{idx}.{AUDIO_EXTENSION}\")\n            audio_slice.export(audio_output_path, format=AUDIO_EXTENSION)\n        \n        tqdm.write(f'Successfully created {idx} {curr_folder}')\n\ndef move_folders(folders, source, destination):\n    '''\n    Move a list of folders from source to destination\n    '''\n    logger.info(f'{destination.split(\"/\")[-1]}: {folders}')\n    for folder in folders:\n        shutil.move(join(source, folder), join(destination, folder))\n\ndef split_dataset(ratio=[.6, .2, .2]):\n    '''\n    Split dataset to train dev test according to ratio\n    '''\n    folders = os.listdir(processed_data_path)\n    folders.sort()\n    random.shuffle(folders)\n\n    split_1 = int(ratio[0] * len(folders))\n    split_2 = int((ratio[0] + ratio[1]) * len(folders))\n\n    move_folders(folders[:split_1], processed_data_path, join(corpus_path, 'train'))\n    move_folders(folders[split_1:split_2], processed_data_path, join(corpus_path, 'dev'))\n    move_folders(folders[split_2:], processed_data_path, join(corpus_path, 'test'))\n    shutil.rmtree(processed_data_path, ignore_errors=True)\n\n\ndef main():\n    print('Scraping data...')\n    scraper.main(number_of_talks=500, starting_video_id=2000) # 1000-1500\n\n    print('\\nStart preprocessing...')\n    build_dataset(src_path, sample=100)\n    split_dataset(ratio=ratio)\n\n    print(\"\\nRemoving laughter and applause audio files...\")\n    remove_applause.main(corpus_path)\n\n\nmain()\n```\n\n## PyTorch Datasets\n\n`TedDataset` maps the sliced audio files and their corresponding labels.\n\n`TedDataset` reads all audio files and search for corresponding labels stored at `<audio_id>.trans.txt`.\n\n\n\n```python\nfrom tqdm import tqdm\nfrom pathlib import Path\nfrom os.path import join, getsize\nfrom ntpath import basename\nfrom joblib import Parallel, delayed\nfrom torch.utils.data import Dataset\n\n# Additional (official) text src provided\nOFFICIAL_TXT_SRC = ['tedsrt-lm-norm.txt']\n# Default num. of threads used for loading TedSrt\nREAD_FILE_THREADS = 1\n# Default audio extension\nAUDIO_EXTENSION = 'mp3'\n\n\ndef read_text(file):\n    '''Get transcription of target mp3 file, \n       it's somewhat redundant for accessing each txt multiplt times,\n       but it works fine with multi-thread'''\n    src_file = '-'.join(file.split('-')[:-1])+'.trans.txt'\n    idx = basename(file).split('.')[0]\n\n    with open(src_file, 'r') as fp:\n        for line in fp:\n            if idx == line.split(' ')[0]:\n                return line[:-1].split(' ', 1)[1]\n\n\nclass TedDataset(Dataset):\n    def __init__(self, path, split, tokenizer, bucket_size, ascending=False):\n        # Setup\n        self.path = path\n        self.bucket_size = bucket_size\n\n        # List all wave files\n        file_list = []\n        for s in split:\n            split_list = list(Path(join(path, s)).rglob(\"*.\" + AUDIO_EXTENSION))\n            assert len(split_list) > 0, \"No data found @ {}\".format(join(path,s))\n            file_list += split_list\n        # Read text\n        text = Parallel(n_jobs=READ_FILE_THREADS)(\n            delayed(read_text)(str(f)) for f in file_list)\n        text = [tokenizer.encode(txt.upper()) for txt in text]\n\n        # Sort dataset by text length\n        self.file_list, self.text = zip(*[(f_name, txt)\n                                          for f_name, txt in sorted(zip(file_list, text), reverse=not ascending, key=lambda x:len(x[1]))])\n\n    def __getitem__(self, index):\n        if self.bucket_size > 1:\n            # Return a bucket\n            index = min(len(self.file_list)-self.bucket_size, index)\n            return [(f_path, txt) for f_path, txt in\n                    zip(self.file_list[index:index+self.bucket_size], self.text[index:index+self.bucket_size])]\n        else:\n            return self.file_list[index], self.text[index]\n\n    def __len__(self):\n        return len(self.file_list)\n```\n\n# Data Exploration\n\n#### Audio metadata of an audio slice\n```\nSample Rate: 44100\nShape: (1, 84055)\nDtype: torch.float32\n - Max:          0.523\n - Min:         -0.319\n - Mean:        -0.000\n - Std Dev:      0.081\n ```\n\n#### Audio signal\n\n\n\n\n\n\nWaveform plot of sample audio signal with length of 1.9s. Duration length can obtained: `signal_frames / sample_rate`.\n\n#### Spectrogram of raw audio signal\n\n\n\n# Data Processing\n\nSteps to compute filter banks are motivated to mimic how human perceives audio signals<sup>[[1]](#reference)</sup>.\n\n1. Apply pre-emphasis filter on audio signal (amplify the high frequencies since high frequencies have smaller magnitude).\n2. Cut signal into window frames (assume signal is stationary over a short period time).\n3. Compute the power spectrum of the signal (Fourier transform) for each window.\n\n\nKaldi filter banks transformation applied on audio signals. 40 mel coefficients is kept.\n\n\n```python\nfeat_dim = 40\nwaveform_trans = torchaudio.compliance.kaldi.fbank(signal, frame_length=25, frame_shift=10, num_mel_bins=feat_dim)\nplot_spectrogram(waveform_trans.transpose(0, 1).detach(), title=\"Filter Banks\", ylabel='mel bins')\n```\n\n\n\n# Model Design\n\n## Description of End-to-end-ASR model\n\nIn this project, we are training a feature extractor and classifier, that collectively classify words based on audio inputs. The feature extractor mechanism extracts features from timesteps (i.e. speech frames). This feature vector is used by the classifier to generate an output sequence of characters. The output sequence is evaluated using Connectionist Temporal Classification (CTC) Loss and Word Error Rate (WER).\n\n\n\n### Baseline model\n\nThe combination of extractor and classifier used in the ASR-End-to-end paper is a VGGNet followed by an LSTM. We consider VGGNet to be a CNN, and LSTM to be an RNN.\n\nThe use of a CNN feature extractor is motivated by previous studies<sup>[[2]](#reference)[[3]](#reference)</sup>, and similarly for the use of an LSTM classifier<sup>[[4]](#reference)</sup>.\n\n\n\n## Experimentation Plan\n\n\nThe following table describes the 7 sets of extractor-classifier combinations used in the tests. The first combination (Baseline) is used by the ASR-End-to-end paper. Apart from that, there are 6 other combinations that we can use, that involve changing either the extractor or the classifier of the original CNN-RNN combination, but not both.\n\n##### Baseline\n\nModel Tested | Extractor | Classifier\n--- | --- | ---\nBaseline | CNN | RNN\n\n##### Change the Extractor\n\nModel Tested | Extractor | Classifier\n--- | --- | ---\nMLPExtractor | MLP | RNN\nRNNExtractor | RNN | RNN\nANNExtractor | ANN | RNN\n\n##### Change the Classifier\n\nModel Tested | Extractor | Classifier\n--- | --- | ---\nMLPClassifier | CNN | MLP\nCNNClassifier | CNN | CNN\nANNClassifier | CNN | ANN\n\nWe cannot change both the extractor and classifier in a single test because we cannot compare it easily with the original baseline.\n\n## Code Written\n\n\n```python\n# TAKE NOTE that these code elements cannot be trained within this notebook, due to the complex project ecosystem.\n# Refer to the 'Important Notes' section at the start of this notebook for instructions on running the project.\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.init as init\n```\n\n### Extractors\n\n\nExtractor generates a sequence of feature vectors. Each feature vector is extracted from a small overlapped window of audio frames. Extractor transforms $x$, to high-level representation $h = (h_1, ..., h_L)$.\n\nExtractor includes downsampling of timesteps.\n\n\n\n\nFor example downsampling by a factor of 4 from 523 timesteps to 130 timesteps in RNN extractor. Downsampling is also achieved by MaxPooling of CNN extractors.\n\n#### MLP Extractor\n\n\n```python\nclass MLPExtractor(nn.Module):\n    ''' A simple MLP extractor for acoustic feature down-sampling\n    Every 4 frame will be convert to corresponding features by MLP'''\n\n    def __init__(self, input_dim, out_dim):\n        super(MLPExtractor, self).__init__()\n\n        self.out_dim = out_dim\n        self.hide_dim = input_dim * 3\n        self.extractor = nn.Sequential(\n            nn.Linear(input_dim, self.hide_dim),\n            nn.ReLU(),\n            nn.Linear(self.hide_dim, self.hide_dim),\n            nn.ReLU(),\n            nn.Linear(self.hide_dim, self.hide_dim),\n            nn.ReLU(),\n            nn.Linear(self.hide_dim, self.hide_dim),\n            nn.ReLU(),\n            nn.Linear(self.hide_dim, self.out_dim),\n        )\n\n    def reshape_input(self, feature, group_size):\n        down_sample_len = feature.size(1) // group_size\n        feature = feature[:,:down_sample_len*group_size,:]\n        reshape_feature = feature.reshape(feature.size(0) * down_sample_len, group_size*feature.size(2))\n        return reshape_feature\n\n\n    def forward(self, feature, feat_len):\n        bs = feature.size(0)\n        feature = self.reshape_input(feature, group_size=4)\n        raw_output = self.extractor(feature)\n\n        reshape_output = raw_output.reshape(bs, raw_output.size(0) // bs, self.out_dim)\n        return reshape_output, torch.div(feat_len,4, rounding_mode=\"floor\")\n```\n\n#### RNN Extractor\n\nApplied RNN layer on input (speech frames/ timesteps). RNN output is followed by downsampling by factor of 4.\n\n\n```python\nclass RNNExtractor(nn.Module):\n    ''' A 2-layer RNN extractor for acoustic feature down-sampling'''\n\n    def __init__(self, input_dim, out_dim):\n        super(RNNExtractor, self).__init__()\n\n        self.out_dim = out_dim\n        self.layer = nn.RNN(input_dim, self.out_dim)\n        self.dp = nn.Dropout(p=0.2)\n        self.linear = nn.Linear(self.out_dim, self.out_dim)\n\n    def forward(self, feature, feat_len):\n\n        # feat_len = feat_len//4\n        feat_len = torch.div(feat_len, 4, rounding_mode='floor')\n        feature, _ = self.layer(feature)\n        # Normalization\n        feature = self.dp(feature)\n        \n        # Downsample timestep\n        sample_rate = 4\n        if feature.shape[1] % sample_rate != 0:\n            feature = feature[:, :-(feature.shape[1] % 4), :].contiguous()\n        feature = feature[:, ::sample_rate, :].contiguous()\n\n        return feature, feat_len\n```\n\n#### ANN Extractor\n\nIn this work we applied local self-attention layer<sup>[[5]](#reference)</sup> to replace spatial convolutions as a feature extractor. The attention is computed as follows\n\n\\begin{align}\ny_{ij} = \n  \\sum_{a, b \\in \\, \\mathcal{N}_k(i, j)}\n    \\texttt{softmax}_{a b}\\left(  q_{i j}^\\top k_{a b}  \\right)  v_{a b}\n\\end{align}\n\nwhere the *queries* $q_{ij} = W_Q x_{ij}$, *keys* $k_{ab} = W_K x_{ab}$, and *values* $v_{ab} = W_V x_{ab}$ are linear transformations of the pixel in position $ij$ and the neighborhood pixels<sup>[[5]](#reference)</sup>.\n\n\n```python\nclass ANNExtractor(nn.Module):\n    ''' ANN extractor with self-attention mechanism from https://github.com/leaderj1001/Stand-Alone-Self-Attention'''\n\n    def __init__(self, input_dim, groups=8):\n        super(ANNExtractor, self).__init__()\n        self.init_dim = 64\n        self.hide_dim = 128\n        in_channel, freq_dim, out_dim = self.check_dim(input_dim)\n        self.in_channel = in_channel\n        self.freq_dim = freq_dim\n        self.out_dim = 640\n        width = freq_dim\n\n        self.conv1 = nn.Sequential(\n            nn.Conv2d(in_channel, width, 3, stride=1, padding=1),\n            nn.BatchNorm2d(width),\n            nn.ReLU(),\n            nn.MaxPool2d(2, stride=2),  # Half-time dimension\n            nn.Conv2d(width, width, 3, stride=1, padding=1),\n            nn.MaxPool2d(2, stride=2),  # Half-time dimension\n        )\n        self.conv2 = nn.Sequential(\n            AttentionConv(width, width, kernel_size=7, padding=3, groups=groups),\n            nn.BatchNorm2d(width),\n            nn.ReLU(),\n        )\n        self.conv3 = nn.Sequential(\n            nn.Conv2d(width, 64, 3, stride=1, padding=1),\n            nn.BatchNorm2d(64),\n        )\n\n    def check_dim(self, input_dim):\n        # Check input dimension, delta feature should be stack over channel.\n        if input_dim % 13 == 0:\n            # MFCC feature\n            return int(input_dim/13), 13, (13//4)*self.hide_dim\n        elif input_dim % 40 == 0:\n            # Fbank feature\n            return int(input_dim/40), 40, (40//4)*self.hide_dim\n        else:\n            raise ValueError(\n            'Acoustic feature dimension for VGG should be 13/26/39(MFCC) or 40/80/120(Fbank) but got '+input_dim)\n\n    def view_input(self, feature, feat_len):\n        # downsample time\n        # feat_len = feat_len//4\n        feat_len = torch.div(feat_len, 4, rounding_mode='floor')\n        # crop sequence s.t. t%4==0\n        if feature.shape[1] % 4 != 0:\n            feature = feature[:, :-(feature.shape[1] % 4), :].contiguous()\n        bs, ts, ds = feature.shape\n        # stack feature according to result of check_dim\n        feature = feature.view(bs, ts, self.in_channel, self.freq_dim)\n        feature = feature.transpose(1, 2)\n\n        return feature, feat_len\n\n    def forward(self, feature, feat_len):\n        \n        # Feature shape BSxTxD -> BSxCH(1)xT/4xD\n        feature, feat_len = self.view_input(feature, feat_len) #downsample on time\n        # Foward\n        # BS x 1 x T/4 x D/4 -> BS x width x T/4 x D\n        feature = self.conv1(feature)\n        # BS x width x T/4 x D/4 -> BS x width x T/8 x D/2 (attention)\n        feature = self.conv2(feature)\n\n        # BS x width x T/8 x D/2 -> BS x 64 x T/8 x D/4\n        feature = self.conv3(feature)\n        feature = F.relu(feature)\n        # BS x 64 x T/8 x D/4 -> BS x T/8 x 64 x 8D\n        feature = feature.transpose(1, 2)\n        # BS x T/8 x 64 x 8D -> BS x T/8 x 8D\n        feature = feature.contiguous().view(feature.shape[0], feature.shape[1], -1)\n\n        return feature, feat_len\n\n\nclass AttentionConv(nn.Module):\n    def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, groups=1, bias=False):\n        super(AttentionConv, self).__init__()\n        self.out_channels = out_channels\n        self.kernel_size = kernel_size\n        self.stride = stride\n        self.padding = padding\n        self.groups = groups\n\n        assert self.out_channels % self.groups == 0, \"out_channels should be divided by groups. (example: out_channels: 40, groups: 4)\"\n\n        self.rel_h = nn.Parameter(torch.randn(out_channels // 2, 1, 1, kernel_size, 1), requires_grad=True)\n        self.rel_w = nn.Parameter(torch.randn(out_channels // 2, 1, 1, 1, kernel_size), requires_grad=True)\n\n        self.key_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=bias)\n        self.query_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=bias)\n        self.value_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=bias)\n\n        self.reset_parameters()\n\n    def forward(self, x):\n        batch, channels, height, width = x.size()\n\n        padded_x = F.pad(x, [self.padding, self.padding, self.padding, self.padding])\n        q_out = self.query_conv(x)\n        k_out = self.key_conv(padded_x)\n        v_out = self.value_conv(padded_x)\n\n        k_out = k_out.unfold(2, self.kernel_size, self.stride).unfold(3, self.kernel_size, self.stride)\n        v_out = v_out.unfold(2, self.kernel_size, self.stride).unfold(3, self.kernel_size, self.stride)\n\n        k_out_h, k_out_w = k_out.split(self.out_channels // 2, dim=1)\n        k_out = torch.cat((k_out_h + self.rel_h, k_out_w + self.rel_w), dim=1)\n\n        k_out = k_out.contiguous().view(batch, self.groups, self.out_channels // self.groups, height, width, -1)\n        v_out = v_out.contiguous().view(batch, self.groups, self.out_channels // self.groups, height, width, -1)\n\n        q_out = q_out.view(batch, self.groups, self.out_channels // self.groups, height, width, 1)\n\n        out = q_out * k_out\n        out = F.softmax(out, dim=-1)\n        out = torch.einsum('bnchwk,bnchwk -> bnchw', out, v_out).view(batch, -1, height, width)\n\n        return out\n\n    def reset_parameters(self):\n        init.kaiming_normal_(self.key_conv.weight, mode='fan_out', nonlinearity='relu')\n        init.kaiming_normal_(self.value_conv.weight, mode='fan_out', nonlinearity='relu')\n        init.kaiming_normal_(self.query_conv.weight, mode='fan_out', nonlinearity='relu')\n\n        init.normal_(self.rel_h, 0, 1)\n        init.normal_(self.rel_w, 0, 1)\n```\n\n### Classifiers\n\nClassifier generates an output sequence $(y_1, . . . , y_T)$ from input $h$. $h$ is the output of the extractor. The classifier's output $y$ is a sequence of word tokens. The sequence $y$ is expected to include a dimension of the same size as $h$.\n\n\n#### MLP Classifier\n\nThe MLPClassifier class uses 5 linear layers. For every timeframe, the extractor map the audio fbanks feature to a latent representation. Then the MLP Classifier aims to map the latent representation to a word token prediction. \n\nUnlike original BiLSTM classifier that looks after timeframe from before and after, the MLP classifier is completely local. It only cares about the current timeframe. \n\n\n```python\nclass MLPCLassfier(nn.Module):\n    def __init__(self, input_dim):\n        super(MLPCLassfier, self).__init__()\n        h1 = input_dim*2\n        h2 = h1*2\n        self.out_dim = h2*2\n        self.classifier = nn.Sequential(\n            nn.Linear(input_dim, h1),\n            nn.ReLU(),\n            nn.Linear(h1, h2),\n            nn.ReLU(),\n            nn.Linear(h2, h2),\n            nn.ReLU(),\n            nn.Linear(h2, h2),\n            nn.ReLU(),\n            nn.Linear(h2, self.out_dim),\n        )\n\n    def reshape_input(self, feature, group_size):\n        down_sample_len = feature.size(1) // group_size\n        feature = feature[:,:down_sample_len*group_size,:]\n        reshape_feature = feature.reshape(feature.size(0) * down_sample_len, group_size*feature.size(2))\n        return reshape_feature\n\n\n    def forward(self, feature):\n\n        return self.classifier(feature)\n\n```\n\n#### CNN Classifier\n\nThe CNNClassifer class uses multiple convolutional layers and only one dense layer. The choice of a single dense layer was used to isolate the effectiveness of convolutional layers specifically.\n\nThe dense layer cannot be directly connected to the convolutional layers. This is because the input data is of size `(timesteps x features)`, where `features` is fixed at 1280, but `timesteps` differs between inputs. Additionally, the output vector is required to contain a dimension with size equal to `timesteps`.\n\nA workaround for this is to apply the linear layer to each timestep separately, and output a separate value for each of the timesteps. Additionally, pooling layers should not pool along the timestep axis, since the output vector must have a dimension with size equal to `timesteps`.\n\n\n```python\nclass CNNClassifier(nn.Module):\n    \"\"\"4-layer CNN classifier module.\"\"\"\n    \n    def __init__(self, input_dim):\n        super(CNNClassifier, self).__init__()\n        self.hidden_dim_1 = hidden_dim_1 = input_dim // 64\n        self.hidden_dim_2 = hidden_dim_2 = hidden_dim_1 * 2\n\n        self.out_dim = input_dim // 4\n\n        conv_hyperparams = {\n            \"kernel_size\": (3,3),\n            \"dilation\": (1,1),\n            \"stride\": (1,1),\n            \"padding\": (1,1),\n        }\n\n        self.conv1 = nn.Conv2d(in_channels=1, out_channels=hidden_dim_1, **conv_hyperparams)\n        self.conv2 = nn.Conv2d(in_channels=hidden_dim_1, out_channels=hidden_dim_1, **conv_hyperparams)\n        self.conv3 = nn.Conv2d(in_channels=hidden_dim_1, out_channels=hidden_dim_2, **conv_hyperparams)\n        self.conv4 = nn.Conv2d(in_channels=hidden_dim_2, out_channels=hidden_dim_2, **conv_hyperparams)\n        self.dense = nn.Linear(hidden_dim_2 * self.out_dim, self.out_dim)\n        self.pool = nn.MaxPool2d((1, 2))\n\n    def reshape_input(self, feature, group_size):\n        down_sample_len = feature.size(1) // group_size\n        feature = feature[:,:down_sample_len*group_size,:]\n        reshape_feature = feature.reshape(feature.size(0) * down_sample_len, group_size*feature.size(2))\n        return reshape_feature\n\n    def forward(self, feature):\n        # Input size is varied - size is N timesteps x 1280 features. Batch size = 1 and number of input channels = 1.\n        # Therefore, inputs must be unsqueezed.\n        feature = feature.unsqueeze(dim=0).unsqueeze(dim=1)\n\n        # Format: input_channels x timesteps x features --> output_channels x new_timesteps x new_features\n        feature = self.conv1(feature)  # 1 x N x 1280 --> 24 x N x 1280\n        feature = F.relu(feature)\n        feature = self.conv2(feature)  # 24 x N x 1280 --> 24 x N x 1280\n        feature = F.relu(feature)\n        feature = self.pool(feature)  # 24 x N x 1280 --> 24 x N x 640\n        feature = self.conv3(feature)  # 24 x N x 640 --> 48 x N x 640\n        feature = F.relu(feature)\n        feature = self.conv4(feature)  # 48 x N x 640 --> 48 x N x 640\n        feature = F.relu(feature)\n        feature = self.pool(feature)  # 48 x N x 640 --> 48 x N x 320\n\n        feature = feature.transpose(0, 1)  # 48 x N x 320 --> N x 48 x 320\n        feature = feature.view(-1, self.hidden_dim_2 * self.out_dim) # N x 48 x 320 --> N x (48 x 320)\n        feature = torch.stack([\n            self.dense(feature[index].unsqueeze(dim=0)) \n            for index in range(feature.size()[0])])  # N x (48 x 320) --> N x 320\n        feature = feature.transpose(0, 1)  # N x 320 --> 320 x N\n        return feature\n```\n\n#### ANN Classifier\n\nThe ANNClassifier class uses a single Self-Attention layer (referencing [this implementation](https://github.com/leaderj1001/Stand-Alone-Self-Attention/blob/master/attention.py \"Self-Attention layer implementation\") of a Self-Attention layer). The implementation is identical to the one used in the ANNExtractor.\n\nThe ANNClassifier only uses a single dense layer. This is to isolate the effectiveness of the Self-Attention layer.\n\nHowever, because the Self-Attention layer is extremely space-intensive, only a single Self-Attention layer can be used, and pooling is applied prior to the data being forwarded to it.\n\nAdditionally, the ANNClassifier's dense layer faces the same issue as the CNNClassifier - the input data is of unknown size, and therefore the dense layer is applied to each timestep individually.\n\n\n```python\nclass ANNClassifier(nn.Module):\n    \"\"\"ANN classifier with Self-Attention module from https://github.com/leaderj1001/Stand-Alone-Self-Attention/blob/master/attention.py.\"\"\"\n\n    def __init__(self, input_dim):\n        super(ANNClassifier, self).__init__()\n        self._pool_value = 4\n        self.hidden_dim_1 = hidden_dim_1 = 20\n        self.linear_input_dim = hidden_dim_1 * input_dim // self._pool_value\n        self.out_dim = 80\n\n        attn_hyperparams = {\n            \"kernel_size\": 3,\n            \"padding\": 1,\n        }\n\n        self.attn = AttentionConv(1, hidden_dim_1, **attn_hyperparams)\n        self.dense = nn.Linear(self.linear_input_dim, self.out_dim)\n        self.pool = nn.MaxPool2d((1, self._pool_value))\n\n    def reshape_input(self, feature, group_size):\n        down_sample_len = feature.size(1) // group_size\n        feature = feature[:,:down_sample_len*group_size,:]\n        reshape_feature = feature.reshape(feature.size(0) * down_sample_len, group_size*feature.size(2))\n        return reshape_feature\n\n    def forward(self, feature):\n        # Input size is varied - size is N timesteps x 1280 features. Batch size = 1 and number of input channels = 1.\n        # Therefore, inputs must be unsqueezed.\n        feature = feature.unsqueeze(dim=0).unsqueeze(dim=1)\n\n        # Format: output_channels x new_timesteps x new_features\n\n                                                   # 1 x N x 1280\n        feature = self.pool(feature)               # 1 x N x 320\n        feature = self.attn(feature)               # 20 x N x 320\n        feature = F.relu(feature)\n\n        feature = feature.transpose(0, 1)  # N x 20 x 320\n        feature = feature.view(-1, self.linear_input_dim)   # N x (20 x 320)\n        feature = torch.stack([\n            self.dense(feature[index].unsqueeze(dim=0)) \n            for index in range(feature.size()[0])])  # N x 80\n        feature = feature.transpose(0, 1)  # 80 x N\n\n        return feature\n\n\nclass AttentionConv(nn.Module):\n    def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, groups=1, bias=False):\n        super(AttentionConv, self).__init__()\n        self.out_channels = out_channels\n        self.kernel_size = kernel_size\n        self.stride = stride\n        self.padding = padding\n        self.groups = groups\n\n        assert self.out_channels % self.groups == 0, \"out_channels should be divided by groups. (example: out_channels: 40, groups: 4)\"\n\n        self.rel_h = nn.Parameter(torch.randn(out_channels // 2, 1, 1, kernel_size, 1), requires_grad=True)\n        self.rel_w = nn.Parameter(torch.randn(out_channels // 2, 1, 1, 1, kernel_size), requires_grad=True)\n\n        self.key_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=bias)\n        self.query_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=bias)\n        self.value_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=bias)\n\n        self.reset_parameters()\n\n    def forward(self, x):\n        batch, channels, height, width = x.size()\n\n        padded_x = F.pad(x, [self.padding, self.padding, self.padding, self.padding])\n        q_out = self.query_conv(x)\n        k_out = self.key_conv(padded_x)\n        v_out = self.value_conv(padded_x)\n\n        k_out = k_out.unfold(2, self.kernel_size, self.stride).unfold(3, self.kernel_size, self.stride)\n        v_out = v_out.unfold(2, self.kernel_size, self.stride).unfold(3, self.kernel_size, self.stride)\n\n        k_out_h, k_out_w = k_out.split(self.out_channels // 2, dim=1)\n        k_out = torch.cat((k_out_h + self.rel_h, k_out_w + self.rel_w), dim=1)\n\n        k_out = k_out.contiguous().view(batch, self.groups, self.out_channels // self.groups, height, width, -1)\n        v_out = v_out.contiguous().view(batch, self.groups, self.out_channels // self.groups, height, width, -1)\n\n        q_out = q_out.view(batch, self.groups, self.out_channels // self.groups, height, width, 1)\n\n        out = q_out * k_out\n        out = F.softmax(out, dim=-1)\n        out = torch.einsum('bnchwk,bnchwk -> bnchw', out, v_out).view(batch, -1, height, width)\n\n        return out\n\n    def reset_parameters(self):\n        init.kaiming_normal_(self.key_conv.weight, mode='fan_out', nonlinearity='relu')\n        init.kaiming_normal_(self.value_conv.weight, mode='fan_out', nonlinearity='relu')\n        init.kaiming_normal_(self.query_conv.weight, mode='fan_out', nonlinearity='relu')\n\n        init.normal_(self.rel_h, 0, 1)\n        init.normal_(self.rel_w, 0, 1)\n\n\n```\n\n# Experiment Results\n\n\n2 separate datasets were used for training - the original Librispeech dataset used in the forked repository, and our own scraped TedSrt dataset. This is because the models all performed poorly on our TedSrt dataset, leading us to believe that our dataset was flawed. Training on the Librispeech dataset instead showed a significant difference in performance between models.\n\n### TedSrt\n\n> 200 MB of audio data was scraped from [Ted2Srt](https://ted2srt.org/). We tried training on 1 GB of dataset but the results were roughly similar.\n\nBaseline Model\n\n| Extractor | Classifier | CTC-WER | CTC-Loss |\n|-----------|------------|---------|----------|\n| CNN       | RNN        | 0.92    | 6.56     |\n\nComparing performance of Extractor\n\n| Extractor | Classifier | CTC-WER | CTC-Loss |\n|-----------|------------|---------|----------|\n| MLP       | RNN        | 0.99    | 6.58     |\n| ANN       | RNN        | 1       | 6.92     |\n| RNN       | RNN        | 0.95    | 6.53     |\n\n\nComparing performance of Classifier\n\n| Extractor | Classifier | CTC-WER | CTC-Loss |\n|-----------|------------|---------|----------|\n| CNN       | MLP        | 0.90    |5.746     | \n| CNN       | CNN        | 0.95    |6.745     |\n| CNN       | ANN        | 0.99    |6.98      |\n\n---\n\n### LibriSpeech\n\n> This is a public dataset by [OpenSLR](https://www.openslr.org/12/). The repository is already designed to accommodate this dataset. The subset that we used for training is 6 GB in size.\n\nBaseline Model\n\n| Extractor | Classifier | CTC-WER | CTC-Loss |\n|-----------|------------|---------|----------|\n| CNN       | RNN        | 0.21926 | 1.32976  |\n\nComparing performance of Extractor\n\n| Extractor | Classifier | CTC-WER | CTC-Loss |\n|-----------|------------|---------|----------|\n| MLP       | RNN        | 0.99    | 6.63263  |\n| ANN       | RNN        | 0.9954  | 6.87     |\n| RNN       | RNN        | 0.263   | 1.62     |\n\n\nComparing performance of Classifier\n\n| Extractor | Classifier | CTC-WER | CTC-Loss |\n|-----------|------------|---------|----------|\n| CNN       | MLP        | 0.5884  | 4.092    |\n| CNN       | CNN        | 1       | 7.031    |\n| CNN       | ANN        | 0.9982  | 7.065    |\n\n\n# Discussion\n\n### Our TedSrt dataset is likely flawed\n\nAll models performed extremely poorly (WER >= 0.90) on the TedSrt dataset. It is possible that insufficient data was scraped to train the models (we tried up to 1 GB of data). \n\nThis is a example from the best performing model trained with TedSrt:\n\nLabel Text: **AS A KID THE IDEA OF ABORTION MADE ME SO SAD THAT I KNEW IF I**\n\nPrediction Text: **AND I WE IN THE ON**\n\nClearly the model overfits to the training data as shown from the picture below. The training loss reduce to zero while validation loss remains hight, so as the WER. It only learns the most frequent word and other trivial features from the training set. At the testing time, the model try to predict to the most frequent words.\n\n\n \n\n\nAlternatively, the quality of the data might not be good enough for training (audio quality, time annotation etc.). Due to this, we use the Librispeech dataset for a models comparison.\n\n---\n\n### All models performed worse than the baseline\n\nFor the Librispeech dataset, all models had greater WER and loss than the baseline. This is expected because the BiLSTM used in the baseline has long-short term memory specifically designed for better training speech-related networks, whereas our classifiers do not.\n\n---\n\n### The RNN-RNN and CNN-MLP networks performed quite well\n\nFor the RNN extractor, it is possible that there is a significant element of time-correlation in the audio, i.e. the features at timestep $t$ are heavily related to the features at timestep $t-1$, and somewhat related to the features at $t-2$... etc. Therefore, an RNN extractor is still quite capable of summarizing these temporal relationships, albeit less efficiently than the CNN extractor.\n\nMLP classifier is completely local, meaning that it does not look after time frame before and after and only predicts using the information from current timeframe. The fact that it is still able to reduce the WER significantly shows that the correlation between audio and the corresponding word token is strong enough, such that the word can still be identified without temporal information. \n\nOn the other hand, for CNN classifier, although the filters can slide over the entire audio sequence, the small filters might not be able to capture the temporal information for such a long time. Meanwhile it also loss the local information, and ends up and perform even worse the MLP.\n\nOne other possibility for why the MLP classifier performed better is because more dense layers were used. Only 1 dense layer was used for both the CNN and ANN classifiers, owing to the difficulty of having an unknown number of timesteps. This could have contributed to the success of the MLP over the other NNs.\n\n---\n\n### Attention Neural Networks performed very poorly\n\nIt is possible that insufficient Self-Attention layers were used. Due to hardware and compute limitations, only a single layer could fit into RAM. It is possible that, with a hardware upgrade and more Self-Attention layers, the performance could improve.\n\n\n# Conclusion\n\nThis project has found that apart from the CNN-RNN baseline, the RNN-RNN and CNN-MLP models also perform adequately. The proposed reason for the RNN extractor's effectiveness is its ability to capture temporal connections better, and the proposed reason for the MLP is the presence of more dense layers and the strong correlation between the audio features and corresponding word token. However, the CNN-RNN baseline still performed the best, owing to the more sophisticated CNN and RNN networks used.\n\nWe conclude that further research on this topic can be conducted by varying the number of layers used in the models, and using that to verify or dispute the results obtained in our experimetns.\n\n# References\n\n<a name=\"reference\"></a>\n\n1. [Speech Processing for Machine Learning: Filter banks, Mel-Frequency Cepstral Coefficients (MFCCs) and What's In-Between](https://haythamfayek.com/2016/04/21/speech-processing-for-machine-learning.html), H M Fayek.\n\n2. [Towards End-to-End Speech Recognition with Deep Convolutional Neural Networks](https://arxiv.org/abs/1701.02720), Y. Zhang *et al*.\n\n3. [Very Deep Convolutional Networks for End-to-End Speech Recognition](https://arxiv.org/abs/1610.03022), Y. Zhang *et al*.\n\n4. [Advances in Joint CTC-Attention based End-to-End Speech Recognition with a Deep CNN Encoder and RNN-LM](https://arxiv.org/abs/1706.02737), T. Hori *et al*.\n\n5. [Stand-Alone Self-Attention in Vision Models](https://arxiv.org/abs/1906.05909), P. Ramachandran *et al*.\n", "meta": {"hexsha": "4c8f9a2c65f540f534bd37661b0f9796481ba11d", "size": 542761, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "project_group40_notebook.ipynb", "max_stars_repo_name": "xunweiyee/End-to-end-ASR-Pytorch", "max_stars_repo_head_hexsha": "52b08c17447e9ca72844653350459a5022259819", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project_group40_notebook.ipynb", "max_issues_repo_name": "xunweiyee/End-to-end-ASR-Pytorch", "max_issues_repo_head_hexsha": "52b08c17447e9ca72844653350459a5022259819", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project_group40_notebook.ipynb", "max_forks_repo_name": "xunweiyee/End-to-end-ASR-Pytorch", "max_forks_repo_head_hexsha": "52b08c17447e9ca72844653350459a5022259819", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 299.5369757174, "max_line_length": 282903, "alphanum_fraction": 0.9027638316, "converted": true, "num_tokens": 13364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07585817584273653, "lm_q2_score": 0.033085976958581766, "lm_q1q2_score": 0.002509841858052825}}
{"text": "<a href=\"https://colab.research.google.com/github/gustavocac/FromScratch/blob/master/NLP_Lesson_1.1.ipynb\" target=\"_parent\"></a>\n\n<h1><div align=\"center\">Processamento de Linguagem Natural</div></h1>\n<div align=\"center\">Gustavo C. A Corradi</div>\n<div align=\"center\"><a href=\"http://robotreport.me/\">robotreport.me</a></div>\n<div align=\"center\">@gustavocorradi</div>\n\n# Li\u00e7\u00e3o  I - Representa\u00e7\u00e3o de Texto \n\nNesta li\u00e7\u00e3o, veremos em alguns detalhes como podemos representar melhor o texto em nosso aplicativo. Vamos come\u00e7ar importando os m\u00f3dulos que usaremos\n\n\n```python\nimport string\nfrom collections import Counter\nfrom pprint import pprint\nimport gzip\nimport matplotlib.pyplot as plt \nimport numpy as np\n\n%matplotlib inline\n```\n\n\n```python\nimport re\nimport nltk\nfrom bs4 import BeautifulSoup\n\nurl = \"http://www.rb.org.br/detalhe_artigo.asp?id=2295&idioma=Portugues\"\nhtml = urllib.request.urlopen(url).read()\nsoup = BeautifulSoup(html)\nfor script in soup([\"script\", \"style\"]):\n    script.extract()    # rip it out\n\n# get text\ntext = soup.get_text()\n\n# break into lines and remove leading and trailing space on each\n#lines = (line.strip() for line in text.splitlines())\n# break multi-headlines into a line each\n#chunks = (phrase.strip() for line in lines for phrase in line.split(\"  \"))\n# drop blank lines\n#text = '\\n'.join(chunk for chunk in chunks if chunk)\n\nprint(text)\n\n```\n\n    \n    \n    \n    \n    Radiologia Brasileira - \r\n    Contrastes orais neutros para enterografia por tomografia computadorizada\r\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    Radiologia Brasileira - Publica\u00e7\u00e3o Cient\u00edfica Oficial do Col\u00e9gio Brasileiro de Radiologia\n    AMB - Associa\u00e7\u00e3o M\u00e9dica Brasileira CNA - Comiss\u00e3o Nacional de Acredita\u00e7\u00e3o\n    \r\n          Idioma/Language:\r\n          \n    \n     \n    \n    \n    \n    \n    Home\n    CBR\n    RB History\n    Editorial Board\n    Publication Guidelines \n    Advanced Search\n    Current Issue\n    Previous Issues\n    Paper Submission\n    Audience\n    Supplements\n    Ahead of Print\n    Contact us\n    \n    \n    \n    \n    \n    \r\n              Vol. 45\u00a0n\u00ba\u00a03 - Maio / Jun. \u00a0of\u00a02012\r\n            \n    \n    \n    \n    \n    EDITORIAL   \r\n          \n    \n     Print\u00a0\n    \n    \n    Page(s) V to VI\n    \n    \n    \n    \n    \n    \n    \r\n    \t\t\t\t\tContrastes orais neutros para enterografia por tomografia computadorizada\n    \n    \n    \n    Autho(rs): Daniella Braz Parente\n    \n    \n    \n     PDF Portugu\u00eas \u00a0\u00a0\u00a0\u00a0\u00a0\n     PDF English\n    \n    \n    \n    Texto em Portugu\u00eas \n    English Text \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    Durante muitos anos o intestino delgado foi um \u00f3rg\u00e3o dif\u00edcil de ser estudado. At\u00e9 bem pouco tempo, os \u00fanicos m\u00e9todos de imagem dispon\u00edveis para o estudo deste segmento eram o tr\u00e2nsito delgado e a enter\u00f3clise convencional, que apresentam diversas limita\u00e7\u00f5es(1,2).\n    \n    Nos \u00faltimos anos, com o desenvolvimento da tecnologia, v\u00e1rios m\u00e9todos t\u00eam sido desenvolvidos para o estudo do intestino delgado. No campo da endoscopia, disp\u00f5e-se hoje da c\u00e1psula endosc\u00f3pica(3) e da enteroscopia com duplo-bal\u00e3o(4), m\u00e9todos caros e n\u00e3o amplamente dispon\u00edveis em nosso meio. No campo da radiologia, surgiram a enterografia e a enter\u00f3clise por tomografia computadorizada (TC) ou por resson\u00e2ncia magn\u00e9tica (RM), que combinam as vantagens dos m\u00e9todos radiol\u00f3gicos convencionais com as dos m\u00e9todos seccionais, ou seja, a distens\u00e3o do l\u00famen intestinal associada \u00e0 visualiza\u00e7\u00e3o multiplanar de toda a cavidade abdominal e p\u00e9lvica, sem sobreposi\u00e7\u00e3o de imagens. Com estes m\u00e9todos, toda a espessura da parede intestinal \u00e9 visualizada, incluindo mucosa, submucosa, muscular e serosa, assim como gordura perient\u00e9rica, vasos retos, linfonodos e padr\u00e3o de realce pelo contraste, o que permite identificar espessamentos parietais, sinais inflamat\u00f3rios, f\u00edstulas, cole\u00e7\u00f5es, al\u00e9m de focos de sangramento e tumores, entre outros(2,5\u00967).\n    \n    A distens\u00e3o luminal \u00e9 um passo fundamental na interpreta\u00e7\u00e3o do estudo do intestino delgado, j\u00e1 que al\u00e7as colabadas podem esconder ou simular segmentos doentes(2,5\u00967). Neste n\u00famero da Radiologia Brasileira, D'Ippolito et al.(8) avaliam o desempenho de diferentes meios de contraste orais neutros, comparando a capacidade de distens\u00e3o intestinal, a defini\u00e7\u00e3o da parede intestinal, a aceita\u00e7\u00e3o e os efeitos colaterais. Os autores descrevem o estudo de 30 pacientes submetidos a enterografia por TC, randomizados entre tr\u00eas tipos de contraste oral neutro dispon\u00edveis em nosso meio: \u00e1gua, leite integral e polietilenoglicol (PEG). Neste estudo, a concentra\u00e7\u00e3o de PEG empregada foi inferior \u00e0 utilizada em estudos anteriores, com o objetivo de reduzir seus efeitos indesejados, mas mantendo sua capacidade de distens\u00e3o da luz intestinal. O preparo com PEG resultou na melhor distens\u00e3o intestinal (57,5%), n\u00e3o havendo diferen\u00e7a significativa entre o leite (35%) e a \u00e1gua (25%). Em todos os grupos foi poss\u00edvel a defini\u00e7\u00e3o adequada da parede intestinal e os meios de contraste tiveram boa aceita\u00e7\u00e3o. Dos pacientes que ingeriram PEG, 80% apresentaram diarreia, efeito colateral n\u00e3o observado com o uso de leite ou \u00e1gua. O estudo mostra, de forma clara, que \u00e1gua e leite n\u00e3o s\u00e3o bons meios de contraste oral para uso na enterografia, j\u00e1 que s\u00e3o absorvidos pelo intestino e n\u00e3o distendem adequadamente as al\u00e7as, o que \u00e9 muito importante para a correta interpreta\u00e7\u00e3o do exame. Mostra tamb\u00e9m que o PEG \u00e9 um bom meio de contraste oral para o estudo do intestino delgado e que os pacientes toleram bem a ingest\u00e3o de grande volume de PEG (1.500 ml). Al\u00e9m disso, demonstra que a diarreia \u00e9 um efeito indesejado habitual, que ocorre na maioria dos pacientes, inerente \u00e0 propriedade do PEG de n\u00e3o ser absorvido ao longo do trato gastrintestinal, mas geralmente autolimitada. Estudos futuros comparando o uso de PEG em baixa concentra\u00e7\u00e3o com PEG na concentra\u00e7\u00e3o habitual s\u00e3o necess\u00e1rios para melhor avalia\u00e7\u00e3o da distensibilidade luminal e incid\u00eancia de efeitos colaterais, principalmente diarreia. Tamb\u00e9m seria interessante a realiza\u00e7\u00e3o de estudos comparando o PEG com o manitol, j\u00e1 que este \u00faltimo tem um custo muito baixo e \u00e9 amplamente dispon\u00edvel na rede hospitalar p\u00fablica.\n    \n    A avalia\u00e7\u00e3o de pacientes com suspeita ou diagn\u00f3stico de doen\u00e7a de Crohn \u00e9 uma das principais indica\u00e7\u00f5es de estudo do intestino delgado. S\u00e3o pacientes jovens, que necessitam de reavalia\u00e7\u00f5es durante toda a vida. Desta forma, deve ser levada em considera\u00e7\u00e3o a dose de radia\u00e7\u00e3o a que estes pacientes s\u00e3o submetidos e tentar sempre reduzir ao m\u00e1ximo a dose de radia\u00e7\u00e3o utilizada(9). Este aspecto foi contemplado no estudo de D'Ippolito et al.(8), no qual foi realizada apenas a fase enterogr\u00e1fica, j\u00e1 que as fases pr\u00e9-contraste, arterial e tardia n\u00e3o acrescentam significativamente para o diagn\u00f3stico e quadriplicam a dose de radia\u00e7\u00e3o a que os pacientes s\u00e3o expostos. Outra op\u00e7\u00e3o para esta popula\u00e7\u00e3o \u00e9 a enterografia por RM, que tem acur\u00e1cia diagn\u00f3stica semelhante e a vantagem de n\u00e3o utilizar radia\u00e7\u00e3o, podendo ser repetida m\u00faltiplas vezes sem malef\u00edcios ao paciente(6).\n    \n    A compara\u00e7\u00e3o entre diferentes tipos de contraste oral dispon\u00edveis em nosso meio para uso na enterografia por TC \u00e9 um tema bastante importante, visto a grande preval\u00eancia de pacientes com doen\u00e7as no intestino delgado que podem se beneficiar deste m\u00e9todo de imagem, como pacientes com doen\u00e7a inflamat\u00f3ria intestinal, notadamente os com doen\u00e7a de Crohn, pacientes com s\u00edndrome do c\u00f3lon irrit\u00e1vel que precisam excluir outras causas para a dor abdominal, os com sangramento intestinal e os com tumores do intestino delgado. A TC est\u00e1 amplamente dispon\u00edvel em nosso pa\u00eds e \u00e9 importante que os radiologistas estejam familiarizados com este m\u00e9todo, para contribuir de forma significativa no diagn\u00f3stico, tratamento e acompanhamento dos pacientes com doen\u00e7as intestinais.\n    \n    \n    REFER\u00caNCIAS\n    \n    1. Saibeni S, Rondonotti E, Iozzelli A, et al. Imaging of the small bowel in Crohn's disease: a review of old and new techniques. World J Gastroenterol. 2007;13:3279\u009687.\n    \n    2. Lee SS, Kim AY, Yang SK, et al. Crohn disease of the small bowel: comparison of CT enterography, MR enterography, and small-bowel follow-through as diagnostic techniques. Radiology. 2009;251:751\u009661.\n    \n    3. Freitas GP, Teixeira N, Feldman G. Capsule endoscopy in clinical practice: four years of experience from a single center. Arq Gastroenterol. 2011;48:220\u00962.\n    \n    4. Albert JG. Interventional balloon-enteroscopy. J Interv Gastroenterol. 2012;2:42\u009650.\n    \n    5. Costa-Silva L, Martins T, Passos MCF. Enterografia por tomografia computadorizada: experi\u00eancia inicial na avalia\u00e7\u00e3o das doen\u00e7as do intestino delgado. Radiol Bras. 2010;43:303\u00968.\n    \n    6. Siddiki HA, Fidler JL, Fletcher JG, et al. Prospective comparison of state-of-the-art MR enterography and CT enterography in small-bowel Crohn's disease. AJR Am J Roentgenol. 2009;193:113\u009621.\n    \n    7. Masselli G, Gualdi G. Evaluation of small bowel tumors: MR entero\u00adclysis. Abdom Imaging. 2010;35:23\u009630.\n    \n    8. D'Ippolito G, Braga FA, Resende MC, et al. Enterografia por tomografia computadorizada: uma avalia\u00e7\u00e3o de diferentes contrastes orais neutros. Radiol Bras. 2012;45:139\u009643.\n    \n    9. Desmond AN, O'Regan K, Curran C, et al. Crohn's disease: factors associated with exposure to high levels of diagnostic radiation. Gut. 2008;57:1524\u00969.\n    \n    \n    \n    \n    \n    \n    \n    \n    \n    \n    Doutoranda em Radiologia da Universidade Federal do Rio de Janeiro (UFRJ), Pesquisadora do Instituto D'Or de Pesquisa e Ensino, Radiologista da Rede Labs D'Or, Rio de Janeiro, RJ, Brasil. E-mail: daniella.parente@gmail.com\n     Back  Top  Print \n    \n    \n    \n    \n    \n    \u00a0\n    \n    \n    \n    \n    \n    \n    \n    GN1\u00a9 Copyright 2020 - All rights reserved to Col\u00e9gio Brasileiro de Radiologia e Diagn\u00f3stico por ImagemAv. Paulista, 37 - 7\u00b0 andar - Conj. 71 - CEP 01311-902 - S\u00e3o Paulo - SP - Brazil - Phone: (11) 3372-4544 - Fax: (11) 3372-4554 \n    \n    \n    \n    \n    \n    \n    \n\n\nWe choose a well known nursery rhyme, that has the added distinction of having been the first audio ever recorded, to be the short snippet of text that we will use in our examples:\n\n## Tokenization\n\nThe first step in any analysis is to tokenize the text. What this means is that we will extract all the individual words in the text. For the sake of simplicity, we will assume that our text is well formed and that our words are delimited either by white space or punctuation characters.\n\n\n```python\ndef extract_words(text):\n    temp = text.split() # Split the text on whitespace\n    text_words = []\n    print(temp)\n    for word in temp:\n        # Remove any punctuation characters present in the beginning of the word\n        print(word[0])\n        while word[0] in string.punctuation:\n            word = word[1:]\n\n        # Remove any punctuation characters present in the end of the word\n        while word[-1] in string.punctuation:\n            word = word[:-1]\n\n        # Append this word into our list of words.\n        text_words.append(word.lower())\n        \n    return text_words\n```\n\nAfter this step we now have our text represented as an array of individual, lowercase, words:\n\n\n```python\ntext_words = extract_words(text)\nprint(text_words)\n```\n\nAs we saw during the video, this is a wasteful way to represent text. We can be much more efficient by representing each word by a number\n\n\n```python\nword_dict = {}\nword_list = []\nvocabulary_size = 0\ntext_tokens = []\n\nfor word in text_words:\n    # If we are seeing this word for the first time, create an id for it and added it to our word dictionary\n    if word not in word_dict:\n        word_dict[word] = vocabulary_size\n        word_list.append(word)\n        vocabulary_size += 1\n    \n    # add the token corresponding to the current word to the tokenized text.\n    text_tokens.append(word_dict[word])\n```\n\nWhen we were tokenizing our text, we also generated a dictionary **word_dict** that maps words to integers and a **word_list** that maps each integer to the corresponding word.\n\n\n```python\nprint(\"Word list:\", word_list, \"\\n\\n Word dictionary:\")\npprint(word_dict)\n```\n\n    Word list: ['mary', 'had', 'a', 'little', 'lamb', 'whose', 'fleece', 'was', 'white', 'as', 'snow', 'and', 'everywhere', 'that', 'went', 'the', 'sure', 'to', 'go'] \n    \n     Word dictionary:\n    {'a': 2,\n     'and': 11,\n     'as': 9,\n     'everywhere': 12,\n     'fleece': 6,\n     'go': 18,\n     'had': 1,\n     'lamb': 4,\n     'little': 3,\n     'mary': 0,\n     'snow': 10,\n     'sure': 16,\n     'that': 13,\n     'the': 15,\n     'to': 17,\n     'was': 7,\n     'went': 14,\n     'white': 8,\n     'whose': 5}\n\n\nThese two datastructures already proved their usefulness when we converted our text to a list of tokens.\n\n\n```python\nprint(text_tokens)\n```\n\n    [0, 1, 2, 3, 4, 3, 4, 3, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0, 14, 0, 14, 0, 14, 12, 13, 0, 14, 15, 4, 7, 16, 17, 18]\n\n\nUnfortunately, while this representation is convenient for memory reasons it has some severe limitations. Perhaps the most important of which is the fact that computers naturally assume that numbers can be operated on mathematically (by addition, subtraction, etc) in a way that doesn't match our understanding of words.\n\n## One-hot encoding\n\nOne typical way of overcoming this difficulty is to represent each word by a one-hot encoded vector where every element is zero except the one corresponding to a specific word.\n\n\n```python\ndef one_hot(word, word_dict):\n    \"\"\"\n        Generate a one-hot encoded vector corresponding to *word*\n    \"\"\"\n    \n    vector = np.zeros(len(word_dict))\n    vector[word_dict[word]] = 1\n    \n    return vector\n```\n\nSo, for example, the word \"fleece\" would be represented by:\n\n\n```python\nfleece_hot = one_hot(\"fleece\", word_dict)\nprint(fleece_hot)\n```\n\n    [0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n\n\nThis vector has every element set to zero, except element 6, since:\n\n\n```python\nprint(word_dict[\"fleece\"])\nfleece_hot[6] == 1\n```\n\n    6\n\n\n\n\n\n    True\n\n\n\n## Bag of words\n\nWe can now use the one-hot encoded vector for each word to produce a vector representation of our original text, by simply adding up all the one-hot encoded vectors:\n\n\n```python\ntext_vector1 = np.zeros(vocabulary_size)\n\nfor word in text_words:\n    hot_word = one_hot(word, word_dict)\n    text_vector1 += hot_word\n    \nprint(text_vector1)\n```\n\n    [6. 2. 2. 4. 5. 1. 1. 2. 1. 1. 1. 1. 2. 2. 4. 1. 1. 1. 1.]\n\n\nIn practice, we can also easily skip the encoding step at the word level by using the *word_dict* defined above:\n\n\n```python\ntext_vector = np.zeros(vocabulary_size)\n\nfor word in text_words:\n    text_vector[word_dict[word]] += 1\n    \nprint(text_vector)\n```\n\n    [6. 2. 2. 4. 5. 1. 1. 2. 1. 1. 1. 1. 2. 2. 4. 1. 1. 1. 1.]\n\n\nNaturally, this approach is completely equivalent to the previous one and has the added advantage of being more efficient in terms of both speed and memory requirements.\n\nThis is known as the __bag of words__ representation of the text. It should be noted that these vectors simply contains the number of times each word appears in our document, so we can easily tell that the word *mary* appears exactly 6 times in our little nursery rhyme.\n\n\n```python\ntext_vector[word_dict[\"mary\"]]\n```\n\n\n\n\n    6.0\n\n\n\nA more pythonic (and efficient) way of producing the same result is to use the standard __Counter__ module:\n\n\n```python\nword_counts = Counter(text_words)\npprint(word_counts)\n```\n\n    Counter({'mary': 6,\n             'lamb': 5,\n             'little': 4,\n             'went': 4,\n             'had': 2,\n             'a': 2,\n             'was': 2,\n             'everywhere': 2,\n             'that': 2,\n             'whose': 1,\n             'fleece': 1,\n             'white': 1,\n             'as': 1,\n             'snow': 1,\n             'and': 1,\n             'the': 1,\n             'sure': 1,\n             'to': 1,\n             'go': 1})\n\n\nFrom which we can easily generate the __text_vector__ and __word_dict__ data structures:\n\n\n```python\nitems = list(word_counts.items())\n\n# Extract word dictionary and vector representation\nword_dict2 = dict([[items[i][0], i] for i in range(len(items))])\ntext_vector2 = [items[i][1] for i in range(len(items))]\n```\n\nAnd let's take a look at them:\n\n\n```python\nprint(\"Text vector:\", text_vector2, \"\\n\\nWord dictionary:\")\npprint(word_dict2)\n```\n\n    Text vector: [6, 2, 2, 4, 5, 1, 1, 2, 1, 1, 1, 1, 2, 2, 4, 1, 1, 1, 1] \n    \n    Word dictionary:\n    {'a': 2,\n     'and': 11,\n     'as': 9,\n     'everywhere': 12,\n     'fleece': 6,\n     'go': 18,\n     'had': 1,\n     'lamb': 4,\n     'little': 3,\n     'mary': 0,\n     'snow': 10,\n     'sure': 16,\n     'that': 13,\n     'the': 15,\n     'to': 17,\n     'was': 7,\n     'went': 14,\n     'white': 8,\n     'whose': 5}\n\n\nThe results using this approach are slightly different than the previous ones, because the words are mapped to different integer ids but the corresponding values are the same:\n\n\n```python\nfor word in word_dict.keys():\n    if text_vector[word_dict[word]] != text_vector2[word_dict2[word]]:\n        print(\"Error!\")\n```\n\nAs expected, there are no differences!\n\n## Term Frequency\n\nThe bag of words vector representation introduced above relies simply on the frequency of occurence of each word. Following a long tradition of giving fancy names to simple ideas, this is known as __Term Frequency__.\n\nIntuitively, we expect the the frequency with which a given word is mentioned should correspond to the relevance of that word for the piece of text we are considering. For example, **Mary** is a pretty important word in our little nursery rhyme and indeed it is the one that occurs the most often:\n\n\n```python\nsorted(items, key=lambda x:x[1], reverse=True)\n```\n\n\n\n\n    [('mary', 6),\n     ('lamb', 5),\n     ('little', 4),\n     ('went', 4),\n     ('had', 2),\n     ('a', 2),\n     ('was', 2),\n     ('everywhere', 2),\n     ('that', 2),\n     ('whose', 1),\n     ('fleece', 1),\n     ('white', 1),\n     ('as', 1),\n     ('snow', 1),\n     ('and', 1),\n     ('the', 1),\n     ('sure', 1),\n     ('to', 1),\n     ('go', 1)]\n\n\n\nHowever, it's hard to draw conclusions from such a small piece of text. Let us consider a significantly larger piece of text, the first 100 MB of the english Wikipedia from: http://mattmahoney.net/dc/textdata. For the sake of convenience, text8.gz has been included in this repository in the **data/** directory. We start by loading it's contents into memory as an array of words:\n\n\n```python\ndata = []\n\nfor line in gzip.open(\"data/text8.gz\", 'rt'):\n    data.extend(line.strip().split())\n```\n\nNow let's take a look at the most common words in this large corpus:\n\n\n```python\ncounts = Counter(data)\n\nsorted_counts = sorted(list(counts.items()), key=lambda x:x[1], reverse=True)\n\nfor word, count in sorted_counts[:10]:\n    print(word, count)\n```\n\n    the 1061396\n    of 593677\n    and 416629\n    one 411764\n    in 372201\n    a 325873\n    to 316376\n    zero 264975\n    nine 250430\n    two 192644\n\n\nSurprisingly, we find that the most common words are not particularly meaningful. Indeed, this is a common occurence in Natural Language Processing. The most frequent words are typically auxiliaries required due to gramatical rules.\n\nOn the other hand, there is also a large number of words that occur very infrequently as can be easily seen by glancing at the word freqency distribution.\n\n\n```python\ndist = Counter(counts.values())\ndist = list(dist.items())\ndist.sort(key=lambda x:x[0])\ndist = np.array(dist)\n\nnorm = np.dot(dist.T[0], dist.T[1])\n\nplt.loglog(dist.T[0], dist.T[1]/norm)\nplt.xlabel(\"count\")\nplt.ylabel(\"P(count)\")\nplt.title(\"Word frequency distribution\")\n```\n\n## Stopwords\n\nOne common technique to simplify NLP tasks is to remove what are known as Stopwords, words that are very frequent but not meaningful. If we simply remove the most common 100 words, we significantly reduce the amount of data we have to consider while losing little information.\n\n\n```python\nstopwords = set([word for word, count in sorted_counts[:100]])\n\nclean_data = []\n\nfor word in data:\n    if word not in stopwords:\n        clean_data.append(word)\n\nprint(\"Original size:\", len(data))\nprint(\"Clean size:\", len(clean_data))\nprint(\"Reduction:\", 1-len(clean_data)/len(data))\n```\n\n    Original size: 17005207\n    Clean size: 9006229\n    Reduction: 0.470384041782026\n\n\nWow, our dataset size was reduced almost in half!\n\nIn practice, we don't simply remove the most common words in our corpus but rather a manually curate list of stopwords. Lists for dozens of languages and applications can easily be found online.\n\n## Term Frequency/Inverse Document Frequency\n\nOne way of determining of the relative importance of a word is to see how often it appears across multiple documents. Words that are relevant to a specific topic are more likely to appear in documents about that topic and much less in documents about other topics. On the other hand, less meaningful words (like **the**) will be common across documents about any subject.\n\nTo measure the document frequency of a word we will need to have multiple documents. For the sake of simplicity, we will treat each sentence of our nursery rhyme as an individual document:\n\n\n```python\ncorpus_text = text.split('.')\ncorpus_words = []\n\nfor document in corpus_text:\n    doc_words = extract_words(document)\n    corpus_words.append(doc_words)\n```\n\nNow our corpus is represented as a list of word lists, where each list is just the word representation of the corresponding sentence:\n\n\n```python\npprint(corpus_words)\n```\n\n    [['mary', 'had', 'a', 'little', 'lamb', 'little', 'lamb', 'little', 'lamb'],\n     ['mary',\n      'had',\n      'a',\n      'little',\n      'lamb',\n      'whose',\n      'fleece',\n      'was',\n      'white',\n      'as',\n      'snow'],\n     ['and', 'everywhere', 'that', 'mary', 'went', 'mary', 'went', 'mary', 'went'],\n     ['everywhere',\n      'that',\n      'mary',\n      'went',\n      'the',\n      'lamb',\n      'was',\n      'sure',\n      'to',\n      'go']]\n\n\nLet us now calculate the number of documents in which each word appears:\n\n\n```python\ndocument_count = {}\n\nfor document in corpus_words:\n    word_set = set(document)\n    \n    for word in word_set:\n        document_count[word] = document_count.get(word, 0) + 1\n\npprint(document_count)\n```\n\n    {'a': 2,\n     'and': 1,\n     'as': 1,\n     'everywhere': 2,\n     'fleece': 1,\n     'go': 1,\n     'had': 2,\n     'lamb': 3,\n     'little': 2,\n     'mary': 4,\n     'snow': 1,\n     'sure': 1,\n     'that': 2,\n     'the': 1,\n     'to': 1,\n     'was': 2,\n     'went': 2,\n     'white': 1,\n     'whose': 1}\n\n\nAs we can see, the word __Mary__ appears in all 4 of our documents, making it useless when it comes to distinguish between the different sentences. On the other hand, words like __white__ which appear in only one document are very discriminative. Using this approach we can define a new quantity, the ___Inverse Document Frequency__ that tells us how frequent a word is across the documents in a specific corpus:\n\n\n```python\ndef inv_doc_freq(corpus_words):\n    number_docs = len(corpus_words)\n    \n    document_count = {}\n\n    for document in corpus_words:\n        word_set = set(document)\n\n        for word in word_set:\n            document_count[word] = document_count.get(word, 0) + 1\n    \n    IDF = {}\n    \n    for word in document_count:\n        IDF[word] = np.log(number_docs/document_count[word])\n        \n    \n    return IDF\n```\n\nWhere we followed the convention of using the logarithm of the inverse document frequency. This has the numerical advantage of avoiding to have to handle small fractional numbers. \n\nWe can easily see that the IDF gives a smaller weight to the most common words and a higher weight to the less frequent:\n\n\n```python\nIDF = inv_doc_freq(corpus_words)\n\npprint(IDF)\n```\n\n    {'a': 0.6931471805599453,\n     'and': 1.3862943611198906,\n     'as': 1.3862943611198906,\n     'everywhere': 0.6931471805599453,\n     'fleece': 1.3862943611198906,\n     'go': 1.3862943611198906,\n     'had': 0.6931471805599453,\n     'lamb': 0.28768207245178085,\n     'little': 0.6931471805599453,\n     'mary': 0.0,\n     'snow': 1.3862943611198906,\n     'sure': 1.3862943611198906,\n     'that': 0.6931471805599453,\n     'the': 1.3862943611198906,\n     'to': 1.3862943611198906,\n     'was': 0.6931471805599453,\n     'went': 0.6931471805599453,\n     'white': 1.3862943611198906,\n     'whose': 1.3862943611198906}\n\n\nAs expected **Mary** has the smallest weight of all words 0, meaning that it is effectively removed from the dataset. You can consider this as a way of implicitly identify and remove stopwords. In case you do want to keep even the words that appear in every document, you can just add a 1. to the argument of the logarithm above:\n\n\\begin{equation}\n\\log\\left[1+\\frac{N_d}{N_d\\left(w\\right)}\\right]\n\\end{equation}\n\nWhen we multiply the term frequency of each word by it's inverse document frequency, we have a good way of quantifying how relevant a word is to understand the meaning of a specific document.\n\n\n```python\ndef tf_idf(corpus_words):\n    IDF = inv_doc_freq(corpus_words)\n    \n    TFIDF = []\n    \n    for document in corpus_words:\n        TFIDF.append(Counter(document))\n    \n    for document in TFIDF:\n        for word in document:\n            document[word] = document[word]*IDF[word]\n            \n    return TFIDF\n```\n\n\n```python\ntf_idf(corpus_words)\n```\n\n\n\n\n    [Counter({'mary': 0.0,\n              'had': 0.6931471805599453,\n              'a': 0.6931471805599453,\n              'little': 2.0794415416798357,\n              'lamb': 0.8630462173553426}),\n     Counter({'mary': 0.0,\n              'had': 0.6931471805599453,\n              'a': 0.6931471805599453,\n              'little': 0.6931471805599453,\n              'lamb': 0.28768207245178085,\n              'whose': 1.3862943611198906,\n              'fleece': 1.3862943611198906,\n              'was': 0.6931471805599453,\n              'white': 1.3862943611198906,\n              'as': 1.3862943611198906,\n              'snow': 1.3862943611198906}),\n     Counter({'and': 1.3862943611198906,\n              'everywhere': 0.6931471805599453,\n              'that': 0.6931471805599453,\n              'mary': 0.0,\n              'went': 2.0794415416798357}),\n     Counter({'everywhere': 0.6931471805599453,\n              'that': 0.6931471805599453,\n              'mary': 0.0,\n              'went': 0.6931471805599453,\n              'the': 1.3862943611198906,\n              'lamb': 0.28768207245178085,\n              'was': 0.6931471805599453,\n              'sure': 1.3862943611198906,\n              'to': 1.3862943611198906,\n              'go': 1.3862943611198906})]\n\n\n\nNow we finally have a vector representation of each of our documents that takes the informational contributions of each word into account. Each of these vectors provides us with a unique representation of each document, in the context (corpus) in which it occurs, making it posssible to define the similarity of two documents, etc.\n\n## Porter Stemmer\n\nThere is still, however, one issue with our approach to representing text. Since we treat each word as a unique token and completely independently from all others, for large documents we will end up with many variations of the same word such as verb conjugations, the corresponding adverbs and nouns, etc. \n\nOne way around this difficulty is to use stemming algorithm to reduce words to their root (or stem) version. The most famous Stemming algorithm is known as the **Porter Stemmer** and was introduced by Martin Porter in 1980 [Program 14, 130 (1980)](https://dl.acm.org/citation.cfm?id=275705)\n\nThe algorithm starts by defining consonants (C) and vowels (V):\n\n\n```python\nV = set('aeiouy')\nC = set('bcdfghjklmnpqrstvwxz')\n```\n\nThe stem of a word is what is left of that word after a speficic ending has been removed. A function to do this is easy to implement:\n\n\n```python\ndef get_stem(suffix, word):\n    \"\"\"\n        Extract the stem of a word\n    \"\"\"\n    \n    if word.lower().endswith(suffix.lower()): # Case insensitive comparison\n        return word[:-len(suffix)]\n\n    return None\n```\n\nIt also defines words (or stems) to be sequences of vowels and consonants of the form:\n\n\\begin{equation}\n[C](VC)^m[V]\n\\end{equation}\n\nwhere $m$ is called the **measure** of the word and [] represent optional sections. \n\n\n```python\ndef measure(orig_word):\n    \"\"\"\n        Calculate the \"measure\" m of a word or stem, according to the Porter Stemmer algorthim\n    \"\"\"\n    \n    word = orig_word.lower()\n\n    optV = False\n    optC = False\n    VC = False\n    m = 0\n\n    pos = 0\n\n    # We can think of this implementation as a simple finite state machine\n    # looks for sequences of vowels or consonants depending of the state\n    # in which it's in, while keeping track of how many VC sequences it\n    # has encountered.\n    # The presence of the optional V and C portions is recorded in the\n    # optV and optC booleans.\n    \n    # We're at the initial state.\n    # gobble up all the optional consonants at the beginning of the word\n    while pos < len(word) and word[pos] in C:\n        pos += 1\n        optC = True\n\n    while pos < len(word):\n        # Now we know that the next state must be a vowel\n        while pos < len(word) and word[pos] in V:\n            pos += 1\n            optV = True\n\n        # Followd by a consonant\n        while pos < len(word) and word[pos] in C:\n            pos += 1\n            optV = False\n        \n        # If a consonant was found, then we matched VC\n        # so we should increment m by one. Otherwise, \n        # optV remained true and we simply had a dangling\n        # V sequence.\n        if not optV:\n            m += 1\n\n    return m\n```\n\nLet's consider a simple example. The word __crepusculars__ should have measure 4:\n\n[cr] (ep) (usc) (ul) (ars)\n\nand indeed it does.\n\n\n```python\nword = \"crepusculars\"\nprint(measure(word))\n```\n\n    4\n\n\nThe Porter algorithm sequentially applies a series of transformation rules over a series of 5 steps (step 1 is divided in 3 substeps and step 5 in 2). The rules are only applied if a certain condition is true. \n\nIn addition to possibily specifying a requirement on the measure of a word, conditions can make use of different boolean functions as well: \n\n\n```python\ndef ends_with(char, stem):\n    \"\"\"\n        Checks the ending of the word\n    \"\"\"\n    return stem[-1] == char\n\ndef double_consonant(stem):\n    \"\"\"\n        Checks the ending of a word for a double consonant\n    \"\"\"\n    if len(stem) < 2:\n        return False\n\n    if stem[-1] in C and stem[-2] == stem[-1]:\n        return True\n\n    return False\n\ndef contains_vowel(stem):\n    \"\"\"\n        Checks if a word contains a vowel or not\n    \"\"\"\n    return len(set(stem) & V) > 0 \n```\n\nFinally, we define a function to apply a specific rule to a word or stem:\n\n\n```python\ndef apply_rule(condition, suffix, replacement, word):\n    \"\"\"\n        Apply Porter Stemmer rule.\n        if \"condition\" is True replace \"suffix\" by \"replacement\" in \"word\"\n    \"\"\"\n    \n    stem = get_stem(suffix, word)\n\n    if stem is not None and condition is True:\n        # Remove the suffix\n        word = stem\n\n        # Add the replacement suffix, if any\n        if replacement is not None:\n            word += replacement\n\n    return word\n```\n\nNow we can see how rules can be applied. For example, this rule, from step 1b is successfully applied to __pastered__:\n\n\n```python\nword = \"plastered\"\nsuffix = \"ed\"\nstem = get_stem(suffix, word)\napply_rule(contains_vowel(stem), suffix, None, word)\n```\n\n\n\n\n    'plaster'\n\n\n\nWhile try applying the same rule to **bled** will fail to pass the condition resulting in no change.\n\n\n```python\nword = \"bled\"\nsuffix = \"ed\"\nstem = get_stem(suffix, word)\napply_rule(contains_vowel(stem), suffix, None, word)\n```\n\n\n\n\n    'bled'\n\n\n\nFor a more complex example, we have, in Step 4:\n\n\n```python\nword = \"adoption\"\nsuffix = \"ion\"\nstem = get_stem(suffix, word)\napply_rule(measure(stem) > 1 and (ends_with(\"s\", stem) or ends_with(\"t\", stem)), suffix, None, word)\n```\n\n\n\n\n    'adopt'\n\n\n\nIn total, the Porter Stemmer algorithm (for the English language) applies several dozen rules (see https://tartarus.org/martin/PorterStemmer/def.txt for a complete list). Implementing all of them is both tedious and error prone, so we abstain from providing a full implementation of the algorithm here. High quality implementations can be found in all major NLP libraries such as [NLTK](http://www.nltk.org/howto/stem.html).\n\nThe dificulties of defining matching rules to arbitrary text cannot be fully resolved without the use of Regular Expressions (typically implemented as Finite State Machines like our __measure__ implementation above), a more advanced topic that is beyond the scope of this course.\n", "meta": {"hexsha": "4ae0c3fcbf457f5cd739f7ce8722aacc27b7559a", "size": 94250, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "NLP_Lesson_1.1.ipynb", "max_stars_repo_name": "gustavocac/FromScratch", "max_stars_repo_head_hexsha": "999f728759cbcf5362168cac2d2beeecafdf2791", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NLP_Lesson_1.1.ipynb", "max_issues_repo_name": "gustavocac/FromScratch", "max_issues_repo_head_hexsha": "999f728759cbcf5362168cac2d2beeecafdf2791", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NLP_Lesson_1.1.ipynb", "max_forks_repo_name": "gustavocac/FromScratch", "max_forks_repo_head_hexsha": "999f728759cbcf5362168cac2d2beeecafdf2791", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1957936905, "max_line_length": 15334, "alphanum_fraction": 0.5730928382, "converted": true, "num_tokens": 8826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09947022456038583, "lm_q2_score": 0.02368946966234288, "lm_q1q2_score": 0.002356396867029694}}
{"text": "# Run all cells\n\nLook for instructions below\n\n\n\n```python\n!apt-get install clang-9\n!git clone https://github.com/RumblingTurtle/SrdPy.git\n!pip install git+https://github.com/rdeits/meshcat-python.git@master\n!pip install ./SrdPy\n```\n\n    Reading package lists... Done\n    Building dependency tree       \n    Reading state information... Done\n    The following package was automatically installed and is no longer required:\n      libnvidia-common-460\n    Use 'apt autoremove' to remove it.\n    The following additional packages will be installed:\n      binfmt-support libclang-common-9-dev libclang-cpp9 libclang1-9 libffi-dev\n      libllvm9 libomp-9-dev libomp5-9 libpfm4 llvm-9 llvm-9-dev llvm-9-runtime\n      llvm-9-tools python-chardet python-pkg-resources python-pygments python-yaml\n      python3-pkg-resources python3-pygments python3-yaml\n    Suggested packages:\n      clang-9-doc libomp-9-doc llvm-9-doc python-setuptools ttf-bitstream-vera\n      python3-setuptools\n    The following NEW packages will be installed:\n      binfmt-support clang-9 libclang-common-9-dev libclang-cpp9 libclang1-9\n      libffi-dev libllvm9 libomp-9-dev libomp5-9 libpfm4 llvm-9 llvm-9-dev\n      llvm-9-runtime llvm-9-tools python-chardet python-pkg-resources\n      python-pygments python-yaml python3-pkg-resources python3-pygments\n      python3-yaml\n    0 upgraded, 21 newly installed, 0 to remove and 34 not upgraded.\n    Need to get 85.9 MB of archives.\n    After this operation, 511 MB of additional disk space will be used.\n    Get:1 http://archive.ubuntu.com/ubuntu bionic/main amd64 python3-yaml amd64 3.12-1build2 [109 kB]\n    Get:2 http://archive.ubuntu.com/ubuntu bionic/main amd64 binfmt-support amd64 2.1.8-2 [51.6 kB]\n    Get:3 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libllvm9 amd64 1:9-2~ubuntu18.04.2 [14.8 MB]\n    Get:4 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 libclang-cpp9 amd64 1:9-2~ubuntu18.04.2 [25.1 MB]\n    Get:5 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 libclang-common-9-dev amd64 1:9-2~ubuntu18.04.2 [3,861 kB]\n    Get:6 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 libclang1-9 amd64 1:9-2~ubuntu18.04.2 [6,701 kB]\n    Get:7 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 clang-9 amd64 1:9-2~ubuntu18.04.2 [1,109 kB]\n    Get:8 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 libomp5-9 amd64 1:9-2~ubuntu18.04.2 [299 kB]\n    Get:9 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 libomp-9-dev amd64 1:9-2~ubuntu18.04.2 [58.6 kB]\n    Get:10 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 llvm-9-runtime amd64 1:9-2~ubuntu18.04.2 [176 kB]\n    Get:11 http://archive.ubuntu.com/ubuntu bionic/main amd64 libpfm4 amd64 4.9.0-2 [225 kB]\n    Get:12 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 llvm-9 amd64 1:9-2~ubuntu18.04.2 [4,874 kB]\n    Get:13 http://archive.ubuntu.com/ubuntu bionic/main amd64 libffi-dev amd64 3.2.1-8 [156 kB]\n    Get:14 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 python-pygments all 2.2.0+dfsg-1ubuntu0.2 [576 kB]\n    Get:15 http://archive.ubuntu.com/ubuntu bionic/main amd64 python-yaml amd64 3.12-1build2 [115 kB]\n    Get:16 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 python3-pygments all 2.2.0+dfsg-1ubuntu0.2 [574 kB]\n    Get:17 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 llvm-9-tools amd64 1:9-2~ubuntu18.04.2 [250 kB]\n    Get:18 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 llvm-9-dev amd64 1:9-2~ubuntu18.04.2 [26.6 MB]\n    Get:19 http://archive.ubuntu.com/ubuntu bionic/main amd64 python-pkg-resources all 39.0.1-2 [128 kB]\n    Get:20 http://archive.ubuntu.com/ubuntu bionic/main amd64 python-chardet all 3.0.4-1 [80.3 kB]\n    Get:21 http://archive.ubuntu.com/ubuntu bionic/main amd64 python3-pkg-resources all 39.0.1-2 [98.8 kB]\n    Fetched 85.9 MB in 6s (14.7 MB/s)\n    Selecting previously unselected package python3-yaml.\n    (Reading database ... 160690 files and directories currently installed.)\n    Preparing to unpack .../00-python3-yaml_3.12-1build2_amd64.deb ...\n    Unpacking python3-yaml (3.12-1build2) ...\n    Selecting previously unselected package binfmt-support.\n    Preparing to unpack .../01-binfmt-support_2.1.8-2_amd64.deb ...\n    Unpacking binfmt-support (2.1.8-2) ...\n    Selecting previously unselected package libllvm9:amd64.\n    Preparing to unpack .../02-libllvm9_1%3a9-2~ubuntu18.04.2_amd64.deb ...\n    Unpacking libllvm9:amd64 (1:9-2~ubuntu18.04.2) ...\n    Selecting previously unselected package libclang-cpp9.\n    Preparing to unpack .../03-libclang-cpp9_1%3a9-2~ubuntu18.04.2_amd64.deb ...\n    Unpacking libclang-cpp9 (1:9-2~ubuntu18.04.2) ...\n    Selecting previously unselected package libclang-common-9-dev.\n    Preparing to unpack .../04-libclang-common-9-dev_1%3a9-2~ubuntu18.04.2_amd64.deb ...\n    Unpacking libclang-common-9-dev (1:9-2~ubuntu18.04.2) ...\n    Selecting previously unselected package libclang1-9.\n    Preparing to unpack .../05-libclang1-9_1%3a9-2~ubuntu18.04.2_amd64.deb ...\n    Unpacking libclang1-9 (1:9-2~ubuntu18.04.2) ...\n    Selecting previously unselected package clang-9.\n    Preparing to unpack .../06-clang-9_1%3a9-2~ubuntu18.04.2_amd64.deb ...\n    Unpacking clang-9 (1:9-2~ubuntu18.04.2) ...\n    Selecting previously unselected package libomp5-9:amd64.\n    Preparing to unpack .../07-libomp5-9_1%3a9-2~ubuntu18.04.2_amd64.deb ...\n    Unpacking libomp5-9:amd64 (1:9-2~ubuntu18.04.2) ...\n    Selecting previously unselected package libomp-9-dev.\n    Preparing to unpack .../08-libomp-9-dev_1%3a9-2~ubuntu18.04.2_amd64.deb ...\n    Unpacking libomp-9-dev (1:9-2~ubuntu18.04.2) ...\n    Selecting previously unselected package llvm-9-runtime.\n    Preparing to unpack .../09-llvm-9-runtime_1%3a9-2~ubuntu18.04.2_amd64.deb ...\n    Unpacking llvm-9-runtime (1:9-2~ubuntu18.04.2) ...\n    Selecting previously unselected package libpfm4:amd64.\n    Preparing to unpack .../10-libpfm4_4.9.0-2_amd64.deb ...\n    Unpacking libpfm4:amd64 (4.9.0-2) ...\n    Selecting previously unselected package llvm-9.\n    Preparing to unpack .../11-llvm-9_1%3a9-2~ubuntu18.04.2_amd64.deb ...\n    Unpacking llvm-9 (1:9-2~ubuntu18.04.2) ...\n    Selecting previously unselected package libffi-dev:amd64.\n    Preparing to unpack .../12-libffi-dev_3.2.1-8_amd64.deb ...\n    Unpacking libffi-dev:amd64 (3.2.1-8) ...\n    Selecting previously unselected package python-pygments.\n    Preparing to unpack .../13-python-pygments_2.2.0+dfsg-1ubuntu0.2_all.deb ...\n    Unpacking python-pygments (2.2.0+dfsg-1ubuntu0.2) ...\n    Selecting previously unselected package python-yaml.\n    Preparing to unpack .../14-python-yaml_3.12-1build2_amd64.deb ...\n    Unpacking python-yaml (3.12-1build2) ...\n    Selecting previously unselected package python3-pygments.\n    Preparing to unpack .../15-python3-pygments_2.2.0+dfsg-1ubuntu0.2_all.deb ...\n    Unpacking python3-pygments (2.2.0+dfsg-1ubuntu0.2) ...\n    Selecting previously unselected package llvm-9-tools.\n    Preparing to unpack .../16-llvm-9-tools_1%3a9-2~ubuntu18.04.2_amd64.deb ...\n    Unpacking llvm-9-tools (1:9-2~ubuntu18.04.2) ...\n    Selecting previously unselected package llvm-9-dev.\n    Preparing to unpack .../17-llvm-9-dev_1%3a9-2~ubuntu18.04.2_amd64.deb ...\n    Unpacking llvm-9-dev (1:9-2~ubuntu18.04.2) ...\n    Selecting previously unselected package python-pkg-resources.\n    Preparing to unpack .../18-python-pkg-resources_39.0.1-2_all.deb ...\n    Unpacking python-pkg-resources (39.0.1-2) ...\n    Selecting previously unselected package python-chardet.\n    Preparing to unpack .../19-python-chardet_3.0.4-1_all.deb ...\n    Unpacking python-chardet (3.0.4-1) ...\n    Selecting previously unselected package python3-pkg-resources.\n    Preparing to unpack .../20-python3-pkg-resources_39.0.1-2_all.deb ...\n    Unpacking python3-pkg-resources (39.0.1-2) ...\n    Setting up python3-yaml (3.12-1build2) ...\n    Setting up binfmt-support (2.1.8-2) ...\n    Created symlink /etc/systemd/system/multi-user.target.wants/binfmt-support.service \u2192 /lib/systemd/system/binfmt-support.service.\n    invoke-rc.d: could not determine current runlevel\n    invoke-rc.d: policy-rc.d denied execution of start.\n    Setting up python-yaml (3.12-1build2) ...\n    Setting up libffi-dev:amd64 (3.2.1-8) ...\n    Setting up python3-pkg-resources (39.0.1-2) ...\n    Setting up python-pkg-resources (39.0.1-2) ...\n    Setting up libomp5-9:amd64 (1:9-2~ubuntu18.04.2) ...\n    Setting up libpfm4:amd64 (4.9.0-2) ...\n    Setting up python-pygments (2.2.0+dfsg-1ubuntu0.2) ...\n    Setting up libllvm9:amd64 (1:9-2~ubuntu18.04.2) ...\n    Setting up libomp-9-dev (1:9-2~ubuntu18.04.2) ...\n    Setting up python3-pygments (2.2.0+dfsg-1ubuntu0.2) ...\n    Setting up libclang-common-9-dev (1:9-2~ubuntu18.04.2) ...\n    Setting up python-chardet (3.0.4-1) ...\n    Setting up libclang1-9 (1:9-2~ubuntu18.04.2) ...\n    Setting up libclang-cpp9 (1:9-2~ubuntu18.04.2) ...\n    Setting up llvm-9-runtime (1:9-2~ubuntu18.04.2) ...\n    Setting up llvm-9-tools (1:9-2~ubuntu18.04.2) ...\n    Setting up clang-9 (1:9-2~ubuntu18.04.2) ...\n    Setting up llvm-9 (1:9-2~ubuntu18.04.2) ...\n    Setting up llvm-9-dev (1:9-2~ubuntu18.04.2) ...\n    Processing triggers for systemd (237-3ubuntu10.46) ...\n    Processing triggers for man-db (2.8.3-2ubuntu0.1) ...\n    Processing triggers for libc-bin (2.27-3ubuntu1.2) ...\n    /sbin/ldconfig.real: /usr/local/lib/python3.7/dist-packages/ideep4py/lib/libmkldnn.so.0 is not a symbolic link\n    \n    Cloning into 'SrdPy'...\n    remote: Enumerating objects: 1007, done.\u001b[K\n    remote: Counting objects: 100% (1007/1007), done.\u001b[K\n    remote: Compressing objects: 100% (483/483), done.\u001b[K\n    remote: Total 1007 (delta 546), reused 957 (delta 501), pack-reused 0\u001b[K\n    Receiving objects: 100% (1007/1007), 20.34 MiB | 21.01 MiB/s, done.\n    Resolving deltas: 100% (546/546), done.\n    Collecting git+https://github.com/rdeits/meshcat-python.git@master\n      Cloning https://github.com/rdeits/meshcat-python.git (to revision master) to /tmp/pip-req-build-2fnmo930\n      Running command git clone -q https://github.com/rdeits/meshcat-python.git /tmp/pip-req-build-2fnmo930\n      Running command git submodule update --init --recursive -q\n    Requirement already satisfied: ipython>=5 in /usr/local/lib/python3.7/dist-packages (from meshcat==0.1.1) (5.5.0)\n    Collecting u-msgpack-python>=2.4.1\n      Downloading https://files.pythonhosted.org/packages/a3/54/0400a3a22ff133633d343371821bf81010455fa3a981a93d7ff3e27a554e/u_msgpack_python-2.7.1-py2.py3-none-any.whl\n    Requirement already satisfied: numpy>=1.14.0 in /usr/local/lib/python3.7/dist-packages (from meshcat==0.1.1) (1.19.5)\n    Requirement already satisfied: tornado>=4.0.0 in /usr/local/lib/python3.7/dist-packages (from meshcat==0.1.1) (5.1.1)\n    Requirement already satisfied: pyzmq>=17.0.0 in /usr/local/lib/python3.7/dist-packages (from meshcat==0.1.1) (22.0.3)\n    Collecting pyngrok>=4.1.6\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/6b/4e/a2fe095bbe17cf26424c4abcd22a0490e22d01cc628f25af5e220ddbf6f0/pyngrok-5.0.5.tar.gz (745kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 747kB 8.2MB/s \n    \u001b[?25hRequirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.7/dist-packages (from ipython>=5->meshcat==0.1.1) (0.8.1)\n    Requirement already satisfied: pexpect; sys_platform != \"win32\" in /usr/local/lib/python3.7/dist-packages (from ipython>=5->meshcat==0.1.1) (4.8.0)\n    Requirement already satisfied: traitlets>=4.2 in /usr/local/lib/python3.7/dist-packages (from ipython>=5->meshcat==0.1.1) (5.0.5)\n    Requirement already satisfied: pygments in /usr/local/lib/python3.7/dist-packages (from ipython>=5->meshcat==0.1.1) (2.6.1)\n    Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.7/dist-packages (from ipython>=5->meshcat==0.1.1) (1.0.18)\n    Requirement already satisfied: pickleshare in /usr/local/lib/python3.7/dist-packages (from ipython>=5->meshcat==0.1.1) (0.7.5)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.7/dist-packages (from ipython>=5->meshcat==0.1.1) (4.4.2)\n    Requirement already satisfied: setuptools>=18.5 in /usr/local/lib/python3.7/dist-packages (from ipython>=5->meshcat==0.1.1) (56.0.0)\n    Requirement already satisfied: PyYAML in /usr/local/lib/python3.7/dist-packages (from pyngrok>=4.1.6->meshcat==0.1.1) (3.13)\n    Requirement already satisfied: ptyprocess>=0.5 in /usr/local/lib/python3.7/dist-packages (from pexpect; sys_platform != \"win32\"->ipython>=5->meshcat==0.1.1) (0.7.0)\n    Requirement already satisfied: ipython-genutils in /usr/local/lib/python3.7/dist-packages (from traitlets>=4.2->ipython>=5->meshcat==0.1.1) (0.2.0)\n    Requirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython>=5->meshcat==0.1.1) (0.2.5)\n    Requirement already satisfied: six>=1.9.0 in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython>=5->meshcat==0.1.1) (1.15.0)\n    Building wheels for collected packages: meshcat, pyngrok\n      Building wheel for meshcat (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for meshcat: filename=meshcat-0.1.1-cp37-none-any.whl size=627107 sha256=17d90c56982e65d0b10d1d687116019e38437a019968289600aac544ba700a18\n      Stored in directory: /tmp/pip-ephem-wheel-cache-99xicfwk/wheels/c2/57/90/f09f46ded98f6ea0f4dd05029529fe8d24d936a520786a60e0\n      Building wheel for pyngrok (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pyngrok: filename=pyngrok-5.0.5-cp37-none-any.whl size=19246 sha256=82f712a73666c161aa3058772765d483e6f03afea4597fbe493dcc2fea72cd92\n      Stored in directory: /root/.cache/pip/wheels/0c/13/64/5ebbcc22eaf53fdf5766b397c1fb17c83f5775fdccf0ea1b88\n    Successfully built meshcat pyngrok\n    Installing collected packages: u-msgpack-python, pyngrok, meshcat\n    Successfully installed meshcat-0.1.1 pyngrok-5.0.5 u-msgpack-python-2.7.1\n    Processing ./SrdPy\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from SrdPy==0.1) (1.19.5)\n    Collecting casadi\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/d7/41/abb53746924c0669cc597d18d9fa77c51682f225222d130fec8217fbd256/casadi-3.5.5-cp37-none-manylinux1_x86_64.whl (34.2MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 34.3MB 107kB/s \n    \u001b[?25hCollecting control\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/88/87/ee6cb7cdcf4efe5634231bd688b307773629a100ec4c83b0c3eb03edd39d/control-0.9.0.tar.gz (339kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 348kB 42.7MB/s \n    \u001b[?25hCollecting slycot\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/85/21/4e7110462f3529b2fbcff8a519b61bf64e0604b8fcbe9a07649c9bed9d7a/slycot-0.4.0.0.tar.gz (1.5MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.6MB 39.0MB/s \n    \u001b[?25h  Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n      Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n        Preparing wheel metadata ... \u001b[?25l\u001b[?25hdone\n    Collecting urdf-parser-py\n      Downloading https://files.pythonhosted.org/packages/96/08/76bc3f7fc9a0345d45527c0054fbec8479d74649d6accb5c1ec174e5098c/urdf_parser_py-0.0.3.tar.gz\n    Requirement already satisfied: pyngrok in /usr/local/lib/python3.7/dist-packages (from SrdPy==0.1) (5.0.5)\n    Collecting qpsolvers\n      Downloading https://files.pythonhosted.org/packages/d2/84/4775a9d3497fed47d77a1996baee409c8f67b670a00b75ac375036875168/qpsolvers-1.6.1-py3-none-any.whl\n    Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from control->SrdPy==0.1) (1.4.1)\n    Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from control->SrdPy==0.1) (3.2.2)\n    Requirement already satisfied: pyyaml in /usr/local/lib/python3.7/dist-packages (from urdf-parser-py->SrdPy==0.1) (3.13)\n    Requirement already satisfied: lxml in /usr/local/lib/python3.7/dist-packages (from urdf-parser-py->SrdPy==0.1) (4.2.6)\n    Collecting quadprog>=0.1.8\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/31/c7/833d7b5b53fff5b9042803aa8096207d8e038ca42052f074d4ad8cddbfc5/quadprog-0.1.8.tar.gz (269kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 276kB 36.1MB/s \n    \u001b[?25hRequirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->control->SrdPy==0.1) (2.4.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->control->SrdPy==0.1) (1.3.1)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->control->SrdPy==0.1) (0.10.0)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->control->SrdPy==0.1) (2.8.1)\n    Requirement already satisfied: Cython in /usr/local/lib/python3.7/dist-packages (from quadprog>=0.1.8->qpsolvers->SrdPy==0.1) (0.29.22)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from cycler>=0.10->matplotlib->control->SrdPy==0.1) (1.15.0)\n    Building wheels for collected packages: slycot\n      Building wheel for slycot (PEP 517) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for slycot: filename=slycot-0.4.0-cp37-cp37m-linux_x86_64.whl size=1417835 sha256=517fe74af2dba0f31ece207326a0db15eb504452187a4fca6c5238575b325da1\n      Stored in directory: /root/.cache/pip/wheels/a2/46/56/f82cbb2fd06556f4f3952a2eb2396e8fd29264fffecbaad3cf\n    Successfully built slycot\n    Building wheels for collected packages: SrdPy, control, urdf-parser-py, quadprog\n      Building wheel for SrdPy (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for SrdPy: filename=SrdPy-0.1-cp37-none-any.whl size=63107 sha256=e99a56e090922014480e70d922694bee7d8ce07bab507536b356091acaf3f1d9\n      Stored in directory: /tmp/pip-ephem-wheel-cache-5zlrhlrr/wheels/f8/a7/cf/bd93c0f0858d9b8af946b5a7d08f2ee154ff8598b8672efd36\n      Building wheel for control (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for control: filename=control-0.9.0-py2.py3-none-any.whl size=344920 sha256=4c9437a97c61c2bc307ad9ba2fa0704d65db2ba6159097f6c4cb18f9c32275df\n      Stored in directory: /root/.cache/pip/wheels/35/be/ee/081b68ca3e4b2d253fba2f7f7e51960373903fb7b6d13c5532\n      Building wheel for urdf-parser-py (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for urdf-parser-py: filename=urdf_parser_py-0.0.3-cp37-none-any.whl size=13122 sha256=99d3b7e4f8b1ce6f504d3c95b4983a28e956e3da1fd1327d845da7ea434a9b8f\n      Stored in directory: /root/.cache/pip/wheels/61/30/cb/440cedefdba99ee2fa968bbf5bfcadc33e7433239b34b8fa88\n      Building wheel for quadprog (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for quadprog: filename=quadprog-0.1.8-cp37-cp37m-linux_x86_64.whl size=336639 sha256=1c4cc436dcfc8d9789bf74f3b310584a1a130975add9807b408e0a4665d3512d\n      Stored in directory: /root/.cache/pip/wheels/0c/39/5f/c712b0e462439dec9b30080cf34622f167929b39bd964d8baf\n    Successfully built SrdPy control urdf-parser-py quadprog\n    Installing collected packages: casadi, control, slycot, urdf-parser-py, quadprog, qpsolvers, SrdPy\n    Successfully installed SrdPy-0.1 casadi-3.5.5 control-0.9.0 qpsolvers-1.6.1 quadprog-0.1.8 slycot-0.4.0 urdf-parser-py-0.0.3\n\n\n\n```python\nfrom SrdPy.URDFUtils import getLinkArrayFromURDF\n\nfrom SrdPy.TableGenerators import generateConstraiedLinearModelTable\nfrom SrdPy.TableGenerators import generateLinearModelTable\nfrom SrdPy.LinksAndJoints import *\nfrom SrdPy.Handlers import *\nfrom SrdPy.InverseKinematics import *\nfrom SrdPy.SymbolicUtils import *\nfrom SrdPy.Loggers import *\nfrom SrdPy.DynamicSolvers import *\nfrom SrdPy.Controllers import *\n\nfrom SrdPy.Visuals import Visualizer\nfrom SrdPy import SymbolicEngine\nfrom SrdPy import plotGeneric\nfrom copy import deepcopy\nfrom casadi import *\n\nfrom SrdPy.TableGenerators import *\nfrom SrdPy import Chain\nfrom SrdPy import Profiler\nimport numpy as np\nfrom scipy.integrate import solve_ivp\nimport os\n```\n\n\n```python\np = Profiler()\niiwaLinks = getLinkArrayFromURDF(os.path.abspath(\"./SrdPy/examples/iiwa/iiwa14.urdf\"),True)\niiwaChain = Chain(iiwaLinks)\n\n\nprint(iiwaChain)\ninitialPosition = np.array([0.1701584,  -0.07586424,  0.42323069, -0.41380217,  0.01195943,  0.07095069,\n  0.])\n\n# CHANGE INITIAL POSITION HERE\n# Data must produce a smooth condition number graph (with small maximum value), and a constant rank of 2.\ninitialPosition = np.array([0.5,  -0.2,  0.1, -0.4,  0.3,  0.7, 0.9])\n\nblank_chain = deepcopy(iiwaChain)\nblank_chain.update(initialPosition)\n\nengine = SymbolicEngine(iiwaChain.linkArray)\n\nderiveJacobiansForlinkArray(engine)\nH = deriveJSIM(engine)\n\niN, dH = deriveGeneralizedInertialForces_dH(engine, H)\ng = deriveGeneralizedGravitationalForces(engine)\nd = deriveGeneralizedDissipativeForcesUniform(engine, 1)\nT = deriveControlMap(engine)\n\n\ndescription_gen_coord_model = generateDynamicsGeneralizedCoordinatesModel(engine,\n                                                                          H=H,\n                                                                          c=(iN + g + d),\n                                                                          T=T,\n                                                                          functionName_H=\"g_dynamics_H\",\n                                                                          functionName_c=\"g_dynamics_c\",\n                                                                          functionName_T=\"g_dynamics_T\",\n                                                                          casadi_cCodeFilename=\"g_dynamics_generalized_coordinates\",\n                                                                          path=\"./iiwa/Dynamics\")\n\nhandlerGeneralizedCoordinatesModel = GeneralizedCoordinatesModelHandler(description_gen_coord_model)\n\ndescription_linearization = generateDynamicsLinearization(engine,\n                                                          H=H,\n                                                          c=(iN + g + d),\n                                                          T=T,\n                                                          functionName_A=\"g_linearization_A\",\n                                                          functionName_B=\"g_linearization_B\",\n                                                          functionName_c=\"g_linearization_c\",\n                                                          casadi_cCodeFilename=\"g_dynamics_linearization\",\n                                                          path=\"./iiwa/Linearization\")\n                                                          \nhandlerLinearizedModel = LinearizedModelHandler(description_linearization)\n\nconstraint6 = engine.links[\"iiwa_link_6\"].absoluteFollower[0]\n\ntask = constraint6[:2]\nprint(\"task size is: \", task.size)\n\n\ndescription_IK = generateSecondDerivativeJacobians(engine,\n                                                task=task,\n                                                functionName_Task=\"g_InverseKinematics_Task\",\n                                                functionName_TaskJacobian=\"g_InverseKinematics_TaskJacobian\",\n                                                functionName_TaskJacobianDerivative=\"g_InverseKinematics_TaskJacobian_derivative\",\n                                                casadi_cCodeFilename=\"g_InverseKinematics\",\n                                                path=\"./iiwa/InverseKinematics\")\n\nikModelHandler = IKModelHandler(description_IK, engine.dof, task.shape[0])\n```\n\n    Unknown tag: material\n    Unknown tag: self_collision_checking\n    Unknown tag: material\n    Unknown tag: material\n    Unknown tag: material\n    Unknown tag: material\n    Unknown tag: material\n    Unknown tag: material\n    Unknown tag: material\n    Unknown tag: hardwareInterface\n    Unknown tag: hardwareInterface\n    Unknown tag: hardwareInterface\n    Unknown tag: hardwareInterface\n    Unknown tag: hardwareInterface\n    Unknown tag: hardwareInterface\n    Unknown tag: hardwareInterface\n\n\n    Parsing URDF:/content/SrdPy/examples/iiwa/iiwa14.urdf\n    Root node: base\n    Chain\n    Links: \n    0. Ground \n    1. iiwa_link_0 \n    2. iiwa_link_1 \n    3. iiwa_link_2 \n    4. iiwa_link_3 \n    5. iiwa_link_4 \n    6. iiwa_link_5 \n    7. iiwa_link_6 \n    8. iiwa_link_7 \n    \n    Loaded existing .so at ./iiwa/Dynamics\n    Loaded existing .so at ./iiwa/Linearization\n    task size is:  2\n    Starting writing function for the g_InverseKinematics_Task\n    Starting writing function for the g_InverseKinematics_Task task jacobian\n    Starting writing function for the derivative of g_InverseKinematics_Task\n    Generated C code!\n\n\n\n```python\nIC_task = ikModelHandler.getTask(initialPosition)\n\ntask_1 = np.array([[0.1],  [0.3]])\n# task_2 = np.array([[0.3],  [0.3]])\n# task_3 = np.array([[0.3],  [0.1]])\n\n# zeroOrderDerivativeNodes = np.hstack((IC_task, task_1, task_2, task_3))\nzeroOrderDerivativeNodes = np.hstack((IC_task, task_1))\n\nfirstOrderDerivativeNodes = np.zeros(zeroOrderDerivativeNodes.shape)\n\nsecondOrderDerivativeNodes = np.zeros(zeroOrderDerivativeNodes.shape)\n\ntimeOfOneStage = 2\ntimeEnd = (len(zeroOrderDerivativeNodes[1]) - 1) * timeOfOneStage + 1\nnodeTimes = np.arange(start=0, stop=timeEnd, step=timeOfOneStage)\n\nhandlerIK_taskSplines = IKtaskSplinesHandler(nodeTimes,\n                                                zeroOrderDerivativeNodes, \n                                                firstOrderDerivativeNodes,\n                                                secondOrderDerivativeNodes)\n\ntimeTable = np.arange(handlerIK_taskSplines.timeStart, handlerIK_taskSplines.timeExpiration + 0.01, 0.01)\n\nIKTable = generateIKTable(ikModelHandler, handlerIK_taskSplines, initialPosition, timeTable, method=\"lsqnonlin\")\nplotIKTable(ikModelHandler, timeTable, IKTable)\n\nikSolutionHandler = IKSolutionHandler(ikModelHandler, handlerIK_taskSplines, timeTable, IKTable, \"linear\")\n\ntf = ikSolutionHandler.timeExpiration\n\nn = handlerGeneralizedCoordinatesModel.dofConfigurationSpaceRobot\n\nA_table, B_table, c_table, x_table, u_table, dx_table = generateLinearModelTable(handlerGeneralizedCoordinatesModel,handlerLinearizedModel,ikSolutionHandler,timeTable)\n\n```\n\n# Task\n\n \n\n1. Implement control, but state observer (x can't be used by the controller, but $y = Cx$ can be)\n2. Simulate the system with the observer and the controller\n3. Simulate from different initial positions\n\n\n\n### Deriving the dynamics of observer and controller\nWe have\n\\begin{equation}\n\\begin{cases}\n\\dot x = Ax+Bu+c\\\\\n\\dot{\\hat x} = Ax+Bu + L(y - C \\hat x) + c\\\\\ny=Cx\\\\\nu=-K (\\hat x-x^*)+u^*\n\\end{cases}\n\\end{equation}\n<br>\nCollecting $\\dot x$ and $\\hat x$ we get:\n\n<br>\n\\begin{equation}\n\\begin{bmatrix}\n\\dot x \\\\\n\\hat x\n\\end{bmatrix}\n=\n\\begin{bmatrix}\nA & -BK \\\\\nLC & A-BK-LC\n\\end{bmatrix}\n\\begin{bmatrix}\nx \\\\\n\\hat x\n\\end{bmatrix}\n+\n\\begin{bmatrix}\nBKx^*+Bu^*+c \\\\\nBKx^*+Bu^*+c\n\\end{bmatrix}\n\\end{equation}\n<br>\n\nLet's introduce an abuse of notation\n\\begin{equation}\nAA=\n\\begin{bmatrix}\nA & -BK \\\\\nLC & A-BK-LC\n\\end{bmatrix}\n\\end{equation}\n\n<br>\n\n\\begin{equation}\ncc=\n\\begin{bmatrix}\nBKx^*+Bu^*+c \\\\\nBKx^*+Bu^*+c\n\\end{bmatrix}\n\\end{equation}\n\nNow we simulate the system with the observer and the controller\n\n\n```python\n# given the observer and the controller variables\n# this function applies the formulas above and returns the AA and cc tables\n\ndef my_generateCloseLoopTable(A_table, B_table, C_table, K_Table, L_table, c_table, x_d_table, u_d_table):\n    AA_table = []\n    for i in range(count):\n      AA_table.append(np.vstack((\n                          np.hstack((A_table[i], -B_table[i].dot(K_table[i]))),\n                          np.hstack((L_table[i].dot(C_table[i]), A_table[i]-B_table[i].dot(K_table[i])-L_table[i].dot(C_table[i])))\n                      ))\n                     )\n\n    cc_table = []\n    for i in range(count):\n      cc_table.append(np.hstack((\n                          B_table[i].dot(K_table[i]).dot(x_d_table[i]) + B_table[i].dot(u_d_table[i]) + c_table[i],\n                          B_table[i].dot(K_table[i]).dot(x_d_table[i]) + B_table[i].dot(u_d_table[i]) + c_table[i]\n                      ))\n                     )\n    return np.array(AA_table), np.array(cc_table)\n```\n\n\n```python\n# this function turns every matrix in a table of matrices and returns the modified table\ndef trn_table(t):\n  ret = []\n  for i in t:\n    ret.append(i.T)\n  return np.array(ret)\n```\n\n\n```python\nfrom control import lqr\n\n# this function generate solves the LQR multiple times and returns a table of resutls\ndef my_generateLQRTable(A_table, B_table, Q_table, R_table):\n    K_table = []\n    \n    for i in range(A_table.shape[0]):\n        K, _, _ =  lqr(A_table[i], B_table[i], Q_table[i], R_table[i])\n        K_table.append(K)\n\n    return np.array(K_table)\n```\n\n\n```python\ncount = A_table.shape[0]\n\nC = np.concatenate((np.eye(n), np.zeros((n, n))), axis=1) # y = C*x\nC_table = np.array(count * [C])\n\nQ = 0.1 * np.eye(2 * n)\nR = 10 * np.eye(handlerGeneralizedCoordinatesModel.dofControl)\n\n# Controller gains\nK_table = my_generateLQRTable(A_table, B_table, np.tile(Q, [count, 1, 1]), np.tile(R, [count, 1, 1]))\n\n# Observer gains\nL_table = trn_table(my_generateLQRTable(trn_table(A_table), trn_table(C_table), np.tile(Q, [count, 1, 1]), np.tile(R, [count, 1, 1])))\n\n# Generate closed-loop system\nAA_table, cc_table = my_generateCloseLoopTable(A_table, B_table, C_table, K_table, L_table, c_table, x_table, u_table)\n\n# Initial positions, initially, the observed values are the same as the actual values\nx0 = np.hstack((initialPosition, np.zeros(n), initialPosition, np.zeros(n)))\n\n# Now we have everything we needed for simulation\n# from sympy import *\n# display(Matrix(x0))\n```\n\n\n```python\n# Simulation\node_fnc_handle = ClosedLoopLinearSystemOdeFunctionHandler(AA_table, cc_table, timeTable)\nsol = solve_ivp(ode_fnc_handle, [0, tf], x0, t_eval=timeTable,method=\"RK45\")\n\n# plot graphs\ntime_table_0 = sol.t\nsolution_tape_1 = sol.y[:n*2].T # Actual states\nsolution_tape_2 = sol.y[n*2:].T # Observed states\n\nplotGeneric(time_table_0, solution_tape_1, figureTitle=\"\", ylabel=\"ODE1\")\nplotGeneric(time_table_0, solution_tape_2, figureTitle=\"\", ylabel=\"ODE2\")\n\nplotGeneric(timeTable, solution_tape_1[:, :n], figureTitle=\"position_actual\", ylabel=\"q\", plot=True)\nplotGeneric(timeTable, solution_tape_2[:, :n], figureTitle=\"position_observed\", ylabel=\"q\", plot=True)\n\nplotGeneric(timeTable, abs(solution_tape_1[:, :n] - solution_tape_2[:, :n]), figureTitle=\"position_error\", ylabel=\"e\", plot=True)\n\nplotGeneric(timeTable, solution_tape_1[:, n:2*n], figureTitle=\"velocity_actual\", ylabel=\"v\", plot=True)\nplotGeneric(timeTable, solution_tape_2[:, n:2*n], figureTitle=\"velocity_observed\", ylabel=\"v\", plot=True)\n\nplotGeneric(timeTable, abs(solution_tape_1[:, n:2*n] - solution_tape_2[:, n:2*n]), figureTitle=\"velocity_error\", ylabel=\"e\", plot=True)\n\nwith open('anim_array.npy', 'wb') as f:\n    np.save(f, solution_tape_2[:,:n])\n```\n\n\n```python\nchainLinks = getLinkArrayFromURDF(os.path.abspath(\"./SrdPy/examples/iiwa/iiwa14.urdf\"),True)\nchain = Chain(chainLinks)\n\nprint(chain)\nblank_chain = deepcopy(chain)\nblank_chain.update(initialPosition)\nwith open('anim_array.npy', 'rb') as f:\n    q = np.load(f)\n\nblank_chain.update(q[0])\nplotGeneric(np.arange(q.shape[0]),q,plot=True)\nvis = Visualizer()\nvis.animate(blank_chain,q,framerate=0.1,showMeshes=True)\n```\n\nClick the link above to see animation ^^^\n", "meta": {"hexsha": "85689395554a0488d70a8f3c5c06e26e5d48d955", "size": 447911, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Coursework/Control Theory/Assignment 3.ipynb", "max_stars_repo_name": "Sh3B0/courses", "max_stars_repo_head_hexsha": "584d8d7b84ab2c58e3dd5b9f716191db64a5c2f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Coursework/Control Theory/Assignment 3.ipynb", "max_issues_repo_name": "Sh3B0/courses", "max_issues_repo_head_hexsha": "584d8d7b84ab2c58e3dd5b9f716191db64a5c2f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Coursework/Control Theory/Assignment 3.ipynb", "max_forks_repo_name": "Sh3B0/courses", "max_forks_repo_head_hexsha": "584d8d7b84ab2c58e3dd5b9f716191db64a5c2f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 420.9689849624, "max_line_length": 51386, "alphanum_fraction": 0.9164208961, "converted": true, "num_tokens": 9879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06954174064906851, "lm_q2_score": 0.03308597803117354, "lm_q1q2_score": 0.0023008565033646486}}
{"text": "# Abstract\n\n4Chan is famous for it's anonymous and ephemeral boards. But is it really ephemeral? There are multiple internet archiving services that have been keeping copies of 4chan posts that go many years in the past. We looked into it to asnwer the following questions: Q1.) *Are 4chan archiving services reliable and offer a holistic view of the epehemeral 4chan threads?* q2.) *If (Q1) is true, does this provides any insights into the pseudo anonymity of the site?* \n\n\n\n```python\n%%capture\n# needed to support mongo+srv connection strings\n!pip install dnspython\n!pip install pymongo\n!pip install pandas\n!pip install numpy\n!pip install matplotlib\n!pip install scipy\n!pip install gensim\n!pip install langdetect\n!pip install tqdm\n!pip install nltk\n!pip install seaborn\n!pip install pyLDAvis\n!pip install wordcloud\n\n## Only run once per kernel environment\n##\u00a0Doesn't need to be re-run when kernel is restarted\n#import nltk\n#nltk.download('punkt')\n#nltk.download('averaged_perceptron_tagger')\n#nltk.download('wordnet')\n#nltk.download('stopwords')\n\n```\n\n\n```python\n%%capture\n\n\nfrom pymongo import MongoClient\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# Fixed period analysis - change these to extend/restrict the period\n# Date as a yyyymmddhhMMss string\ndate_from = '202105010000'\ndate_to =   '202111010000'\n\n# connectiong to mongodb cluster using a read only user\n\n## REMOTE REPLICA SET\nclient = MongoClient(\"mongodb+srv://<usr>:<pass>@rs.prifti.us/?ssl=false&authSource=chan\")\n\n## LOCAL SINGLE INSTANCE\n## 192.168.1.110 -- localhost\n# client = MongoClient(\"mongodb://<usr>:<pass>@localhost:27777/?ssl=false&serverSelectionTimeoutMS=5000&connectTimeoutMS=10000&authSource=chan&authMechanism=SCRAM-SHA-256\")\n\n# connection to chan database\ndb = client.chan\n\n# the threads collection contains API data collections from the 4chan api and 4pleb api\nthreads_collection = db['y-threads']\n\n```\n\n\n```python\n#%%capture\n\n# MongoDB aggregation query, joining data from thread and 'live-4chan' collection \n# for each discovered 4chan thread - retreive a boolean representing if the API data was found\n\n\nq1_pipeline = [\n     {\"$match\": {\"pleb\": {\"$exists\": True } } }\n    ,{ \"$addFields\": {\n        \"data\": {\n                \"$ifNull\": [ {\"$objectToArray\": \"$pleb\"}, [ ] ] \n          }\n     } } \n    ,{ \"$unwind\": { \"path\": \"$data\", \"preserveNullAndEmptyArrays\": True } }\n    ,{ \"$project\":{\"posted\": \"$data.v.op.fourchan_date\", \"timestamp\":\"$data.v.op.timestamp\", \"thread_num\": \"$data.v.op.thread_num\", \"data\": \"$data.v\", \"url\":\"$value\" } }\n    ,{ \"$addFields\": {\n        \"data.flat_posts\": {\n                \"$ifNull\": [ {\"$objectToArray\": \"$data.posts\"}, [ ] ] \n          }\n     } }\n    ,{\"$project\":{\"posted\": 1, \"timestamp\":1, \"thread_num\": 1, \"data_op\": \"$data.op\", \"data_posts\": \"$data.flat_posts\", \"url\": 1 } }\n    ,{\"$sort\": {\"thread_num\": -1} }\n    ,{\"$limit\": 10}\n]\n\nq1_pipeline\n\n# run the aggregation\nthread_data = pd.DataFrame(threads_collection.aggregate(q1_pipeline, allowDiskUse=True))\n\n```\n\n\n```python\nthread_data\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>_id</th>\n      <th>posted</th>\n      <th>timestamp</th>\n      <th>thread_num</th>\n      <th>url</th>\n      <th>data_op</th>\n      <th>data_posts</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>https://boards.4chan.org/pol/thread/346097093</td>\n      <td>11/4/21(Thu)17:07</td>\n      <td>1636060063</td>\n      <td>346097093</td>\n      <td>https://boards.4chan.org/pol/thread/346097093</td>\n      <td>{'doc_id': '322233543', 'num': '346097093', 's...</td>\n      <td>[{'k': '346097614', 'v': {'doc_id': '322234047...</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>https://boards.4chan.org/pol/thread/346097084</td>\n      <td>11/4/21(Thu)17:07</td>\n      <td>1636060059</td>\n      <td>346097084</td>\n      <td>https://boards.4chan.org/pol/thread/346097084</td>\n      <td>{'doc_id': '322233544', 'num': '346097084', 's...</td>\n      <td>[{'k': '346097546', 'v': {'doc_id': '322233977...</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>https://boards.4chan.org/pol/thread/346096992</td>\n      <td>11/4/21(Thu)17:06</td>\n      <td>1636060015</td>\n      <td>346096992</td>\n      <td>https://boards.4chan.org/pol/thread/346096992</td>\n      <td>{'doc_id': '322233484', 'num': '346096992', 's...</td>\n      <td>[{'k': '346097079', 'v': {'doc_id': '322233534...</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>https://boards.4chan.org/pol/thread/346096826</td>\n      <td>11/4/21(Thu)17:05</td>\n      <td>1636059949</td>\n      <td>346096826</td>\n      <td>https://boards.4chan.org/pol/thread/346096826</td>\n      <td>{'doc_id': '322233273', 'num': '346096826', 's...</td>\n      <td>[{'k': '346097342', 'v': {'doc_id': '322233756...</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>https://boards.4chan.org/pol/thread/346096822</td>\n      <td>11/4/21(Thu)17:05</td>\n      <td>1636059948</td>\n      <td>346096822</td>\n      <td>https://boards.4chan.org/pol/thread/346096822</td>\n      <td>{'doc_id': '322233275', 'num': '346096822', 's...</td>\n      <td>[{'k': '346096988', 'v': {'doc_id': '322233411...</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>https://boards.4chan.org/pol/thread/346096745</td>\n      <td>11/4/21(Thu)17:05</td>\n      <td>1636059920</td>\n      <td>346096745</td>\n      <td>https://boards.4chan.org/pol/thread/346096745</td>\n      <td>{'doc_id': '322233274', 'num': '346096745', 's...</td>\n      <td>[{'k': '346097218', 'v': {'doc_id': '322233647...</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>https://boards.4chan.org/pol/thread/346096723</td>\n      <td>11/4/21(Thu)17:05</td>\n      <td>1636059910</td>\n      <td>346096723</td>\n      <td>https://boards.4chan.org/pol/thread/346096723</td>\n      <td>{'doc_id': '322233180', 'num': '346096723', 's...</td>\n      <td>[{'k': '346096821', 'v': {'doc_id': '322233234...</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>https://boards.4chan.org/pol/thread/346096692</td>\n      <td>11/4/21(Thu)17:04</td>\n      <td>1636059899</td>\n      <td>346096692</td>\n      <td>https://boards.4chan.org/pol/thread/346096692</td>\n      <td>{'doc_id': '322233177', 'num': '346096692', 's...</td>\n      <td>[{'k': '346096954', 'v': {'doc_id': '322233423...</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>https://boards.4chan.org/pol/thread/346096690</td>\n      <td>11/4/21(Thu)17:04</td>\n      <td>1636059898</td>\n      <td>346096690</td>\n      <td>https://boards.4chan.org/pol/thread/346096690</td>\n      <td>{'doc_id': '322233172', 'num': '346096690', 's...</td>\n      <td>[{'k': '346097011', 'v': {'doc_id': '322233424...</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>https://boards.4chan.org/pol/thread/346096598</td>\n      <td>11/4/21(Thu)17:04</td>\n      <td>1636059858</td>\n      <td>346096598</td>\n      <td>https://boards.4chan.org/pol/thread/346096598</td>\n      <td>{'doc_id': '322233113', 'num': '346096598', 's...</td>\n      <td>[{'k': '346096938', 'v': {'doc_id': '322233387...</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n# Introduction\n\nWe have been collecting posts from the the /pol board of 4chan with high frequency (scaning the board multiple times per minute). \n\nWe have done so by simulating an end user that connects to the side with a conventional borwser (Firefox), using [OXPath](https://github.com/oxpath/oxpath)\n\nWe have been taking multiple snapshots of each thread until the thread was archived. When a thread is archived we then have been taking a snapshot of the thread from the 4chan api and one from 4pleb.org, an 4chan archiving service, believed to be the most complete archiving service on 4chan. \n\nTwo type of agents have been used to collect the data using OXpath. \n\n- A discovery crawling agent that continuously crawls the /pol board looking for new threads and either a.) captures and queues the new thread URLs for scraping or b.) updates the *found* timestamp of a thread that had already been found by previous instances of the crawler. \n\n- A extraction scraping agent that continuously scrapes threads queued by the crawling agent and stores the state of the thread together with the timestamp, unless the agent finds the thread to be *archived* or *deleted*. When the thread is found in the *archived* / *deleted* state, its attributes are updated and the thread is removed from the crawling queue. \n\n\n\n```python\n# %%capture\n\nthread_op = pd.DataFrame(list(thread_data['data_op']))\nthread_op = thread_op.drop(columns=['doc_id', 'subnum', 'thread_num', 'op', 'capcode', 'email', 'name', 'exif'])\nthread_op = thread_op.drop(columns=['trip','sticky', 'locked', 'poster_hash_processed', 'poster_country_name_processed', 'troll_country_code', 'troll_country_name', 'since4pass', 'unique_ips', 'extra_data', 'media', 'board'])\nthread_op = thread_op.drop(columns=['trip_processed', 'email_processed', 'name_processed', 'formatted'])\n\nthread_op\n#thread_posts.columns\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>num</th>\n      <th>timestamp</th>\n      <th>timestamp_expired</th>\n      <th>title</th>\n      <th>comment</th>\n      <th>poster_hash</th>\n      <th>poster_country</th>\n      <th>deleted</th>\n      <th>nreplies</th>\n      <th>nimages</th>\n      <th>fourchan_date</th>\n      <th>comment_sanitized</th>\n      <th>comment_processed</th>\n      <th>title_processed</th>\n      <th>poster_country_name</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>346097093</td>\n      <td>1636060063</td>\n      <td>0</td>\n      <td>Indiana Jones 5 camera operator found dead</td>\n      <td>&gt;be maxvaxxed to work in Hollywood\\n&gt;die in yo...</td>\n      <td>Far+1kwU</td>\n      <td>FR</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>11/4/21(Thu)17:07</td>\n      <td>&gt;be maxvaxxed to work in Hollywood\\n&gt;die in yo...</td>\n      <td>&lt;span class=\"greentext\"&gt;&amp;gt;be maxvaxxed to wo...</td>\n      <td>Indiana Jones 5 camera operator found dead</td>\n      <td>France</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>346097084</td>\n      <td>1636060059</td>\n      <td>0</td>\n      <td>Interracial Romance in Hollywood</td>\n      <td>Mark Dice's \"Hollywood Propaganda\" prepared me...</td>\n      <td>m2MPJ1go</td>\n      <td>US</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>11/4/21(Thu)17:07</td>\n      <td>Mark Dice's \"Hollywood Propaganda\" prepared me...</td>\n      <td>Mark Dice's &amp;quot;Hollywood Propaganda&amp;quot; p...</td>\n      <td>Interracial Romance in Hollywood</td>\n      <td>United States</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>346096992</td>\n      <td>1636060015</td>\n      <td>0</td>\n      <td>Reminder Moving Out is Memed by the Elite</td>\n      <td>Moving out is a meme of the elite so that cons...</td>\n      <td>CoC3qC0h</td>\n      <td>US</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>11/4/21(Thu)17:06</td>\n      <td>Moving out is a meme of the elite so that cons...</td>\n      <td>Moving out is a meme of the elite so that cons...</td>\n      <td>Reminder Moving Out is Memed by the Elite</td>\n      <td>United States</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>346096826</td>\n      <td>1636059949</td>\n      <td>0</td>\n      <td>Polygamy will return.</td>\n      <td>The covid injection bioweapon, based on past a...</td>\n      <td>vuxbaAOu</td>\n      <td>US</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>11/4/21(Thu)17:05</td>\n      <td>The covid injection bioweapon, based on past a...</td>\n      <td>The covid injection bioweapon, based on past a...</td>\n      <td>Polygamy will return.</td>\n      <td>United States</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>346096822</td>\n      <td>1636059948</td>\n      <td>0</td>\n      <td>JOB FORCED JAB OR SLAB</td>\n      <td>as a christian and religious leader how would ...</td>\n      <td>Ab5voORM</td>\n      <td>US</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>11/4/21(Thu)17:05</td>\n      <td>as a christian and religious leader how would ...</td>\n      <td>as a christian and religious leader how would ...</td>\n      <td>JOB FORCED JAB OR SLAB</td>\n      <td>United States</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>346096745</td>\n      <td>1636059920</td>\n      <td>0</td>\n      <td>None</td>\n      <td>Has this ever actually been successful before?...</td>\n      <td>60jD9ne1</td>\n      <td>US</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>11/4/21(Thu)17:05</td>\n      <td>Has this ever actually been successful before?...</td>\n      <td>Has this ever actually been successful before?...</td>\n      <td>None</td>\n      <td>United States</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>346096723</td>\n      <td>1636059910</td>\n      <td>0</td>\n      <td>Can you buy Ivermectin in Spain?</td>\n      <td>Asking for a friend</td>\n      <td>nWeopydt</td>\n      <td>ES</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>11/4/21(Thu)17:05</td>\n      <td>Asking for a friend</td>\n      <td>Asking for a friend</td>\n      <td>Can you buy Ivermectin in Spain?</td>\n      <td>Spain</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>346096692</td>\n      <td>1636059899</td>\n      <td>0</td>\n      <td>Jews = Brahmins =White Christians</td>\n      <td>All of these are assholes because they have hu...</td>\n      <td>N+X/7+b9</td>\n      <td>CA</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>11/4/21(Thu)17:04</td>\n      <td>All of these are assholes because they have hu...</td>\n      <td>All of these are assholes because they have hu...</td>\n      <td>Jews = Brahmins =White Christians</td>\n      <td>Canada</td>\n    </tr>\n    <tr>\n      <th>8</th>\n      <td>346096690</td>\n      <td>1636059898</td>\n      <td>0</td>\n      <td>Why cant women turn anything off/lock up?</td>\n      <td>&gt;be me\\n&gt;get home from long day at work\\n&gt;fron...</td>\n      <td>j1uGUd/p</td>\n      <td>US</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>11/4/21(Thu)17:04</td>\n      <td>&gt;be me\\n&gt;get home from long day at work\\n&gt;fron...</td>\n      <td>&lt;span class=\"greentext\"&gt;&amp;gt;be me&lt;/span&gt;&lt;br /&gt;...</td>\n      <td>Why cant women turn anything off/lock up?</td>\n      <td>United States</td>\n    </tr>\n    <tr>\n      <th>9</th>\n      <td>346096598</td>\n      <td>1636059858</td>\n      <td>0</td>\n      <td>Do you think this guy owns a tie?</td>\n      <td>Chauvin thing was way more entertaining.</td>\n      <td>ugkY0E/9</td>\n      <td>None</td>\n      <td>0</td>\n      <td>None</td>\n      <td>None</td>\n      <td>11/4/21(Thu)17:04</td>\n      <td>Chauvin thing was way more entertaining.</td>\n      <td>Chauvin thing was way more entertaining.</td>\n      <td>Do you think this guy owns a tie?</td>\n      <td>False</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n\n```python\n# %%capture\n\ndeleted_threads['articles'] = deleted_threads['title'] + ' ' + deleted_threads['comment']\ndocument_corp = list(deleted_threads['articles'])\ndocument_corp = [x for x in document_corp if x is not None]\ndocument_corp = pd.DataFrame(document_corp)\n#document_corp.shape\ndocument_corp.columns = ['articles']\ndocument_corp = document_corp.dropna().reset_index(drop=True)\n#temp_title = list(deleted_threads.query('title != None')['title'])\n#temp_title = [x for x in temp_title if x is not None]\n\n\n#temp_comments = list(deleted_threads.query('comment != None')['comment'])\n#temp_comments = [x for x in temp_comments if x is not None]\n#document_corp = temp_title + temp_comments\n#len(document_corp)\n\n```\n\n\n```python\n# %%capture\n\nfrom langdetect import detect\nfrom tqdm import notebook\nnotebook.tqdm().pandas()\ndata = document_corp.copy()\n\ndef try_detect(elem):\n    try: \n        return detect(elem)\n    except:\n        return 'n/a'\n\ndata['lang'] = data.articles.progress_map(try_detect)\ndata['lang'].head(5)\n\n```\n\n\n    HBox(children=(HTML(value=''), FloatProgress(value=1.0, bar_style='info', layout=Layout(width='20px'), max=1.0\u2026\n\n\n\n    HBox(children=(HTML(value=''), FloatProgress(value=0.0, max=8537.0), HTML(value='')))\n\n\n    \n    \n\n\n\n\n\n    0    en\n    1    pl\n    2    en\n    3    en\n    4    en\n    Name: lang, dtype: object\n\n\n\n\n```python\n# %%capture\n\nfrom nltk.tokenize import sent_tokenize\n\n\ndata.lang.value_counts()\ndata_en = data.loc[data.lang=='en']\ndata['sentences'] = data.articles.progress_map(sent_tokenize)\ndata['sentences'].head(1).tolist()[0][:3] # Print the first 3 sentences of the 1st article\n```\n\n\n    HBox(children=(HTML(value=''), FloatProgress(value=0.0, max=8537.0), HTML(value='')))\n\n\n    \n\n\n\n\n\n    ['DRY ASS PUSSY Imagine the smell.']\n\n\n\n\n```python\n# %%capture\n\nfrom nltk.tokenize import word_tokenize\ndata['tokens_sentences'] = data['sentences'].progress_map(lambda sentences: [word_tokenize(sentence) for sentence in sentences])\nprint(data['tokens_sentences'].head(1).tolist()[0][:3])\n\n```\n\n\n    HBox(children=(HTML(value=''), FloatProgress(value=0.0, max=8537.0), HTML(value='')))\n\n\n    \n    [['DRY', 'ASS', 'PUSSY', 'Imagine', 'the', 'smell', '.']]\n\n\n\n```python\n# %%capture\n\nfrom nltk import pos_tag\ndata['POS_tokens'] = data['tokens_sentences'].progress_map(lambda tokens_sentences: [pos_tag(tokens) for tokens in tokens_sentences])\nprint(data['POS_tokens'].head(1).tolist()[0][:3])\n```\n\n\n    HBox(children=(HTML(value=''), FloatProgress(value=0.0, max=8537.0), HTML(value='')))\n\n\n    \n    [[('DRY', 'NNP'), ('ASS', 'NNP'), ('PUSSY', 'NNP'), ('Imagine', 'NNP'), ('the', 'DT'), ('smell', 'NN'), ('.', '.')]]\n\n\n\n```python\n# %%capture\n\n# Inspired from https://stackoverflow.com/a/15590384\nfrom nltk.corpus import wordnet\nfrom nltk.stem.wordnet import WordNetLemmatizer\n\n\ndef get_wordnet_pos(treebank_tag):\n\n    if treebank_tag.startswith('J'):\n        return wordnet.ADJ\n    elif treebank_tag.startswith('V'):\n        return wordnet.VERB\n    elif treebank_tag.startswith('N'):\n        return wordnet.NOUN\n    elif treebank_tag.startswith('R'):\n        return wordnet.ADV\n    else:\n        return ''\n\nlemmatizer = WordNetLemmatizer()\n\n# Lemmatizing each word with its POS tag, in each sentence\ndata['tokens_sentences_lemmatized'] = data['POS_tokens'].progress_map(\n    lambda list_tokens_POS: [\n        [\n            lemmatizer.lemmatize(el[0], get_wordnet_pos(el[1])) \n            if get_wordnet_pos(el[1]) != '' else el[0] for el in tokens_POS\n        ] \n        for tokens_POS in list_tokens_POS\n    ]\n)\n\ndata['tokens_sentences_lemmatized'].head(1).tolist()[0][:3]\n```\n\n\n    HBox(children=(HTML(value=''), FloatProgress(value=0.0, max=8537.0), HTML(value='')))\n\n\n    \n\n\n\n\n\n    [['DRY', 'ASS', 'PUSSY', 'Imagine', 'the', 'smell', '.']]\n\n\n\n\n```python\n# %%capture\nfrom nltk.corpus import stopwords\n\nstopwords_verbs = ['https', 'http', 'say', 'get', 'go', 'know', 'may', 'need', 'like', 'make', 'see', 'want', 'come', 'take', 'use', 'would', 'can']\nstopwords_other = ['one', 'mr', 'image', 'getty', 'de', 'en', 'caption', 'also', 'copyright', 'something']\nmy_stopwords = stopwords.words('english') + stopwords_verbs + stopwords_other\n\n```\n\n\n```python\n# %%capture\n\nfrom itertools import chain # to flatten list of sentences of tokens into list of tokens\ndata['tokens'] = data['tokens_sentences_lemmatized'].map(lambda sentences: list(chain.from_iterable(sentences)))\ndata['tokens'] = data['tokens'].map(lambda tokens: [token.lower() for token in tokens if token.isalpha() \n                                                    and token.lower() not in my_stopwords and len(token)>1])\ndata['tokens'].head(1).tolist()[0][:30]\n\n```\n\n\n\n\n    ['dry', 'ass', 'pussy', 'imagine', 'smell']\n\n\n\n\n```python\n# %%capture\n\nfrom gensim.models import Phrases\nfrom gensim import corpora\n\ntokens = data['tokens'].tolist()\nbigram_model = Phrases(tokens)\ntrigram_model = Phrases(bigram_model[tokens], min_count=1)\ntokens = list(trigram_model[bigram_model[tokens]])\n\ndictionary_LDA = corpora.Dictionary(tokens)\ndictionary_LDA.filter_extremes(no_below=3)\ncorpus = [dictionary_LDA.doc2bow(tok) for tok in tokens]\n\n```\n\n\n```python\n# %%capture\n\nfrom gensim import models\nimport numpy as np\n\nnp.random.seed(123456)\nnum_topics = 20\n%time lda_model = models.LdaModel(corpus, num_topics=num_topics, \\\n                                  id2word=dictionary_LDA, \\\n                                  passes=4, alpha=[0.01]*num_topics, \\\n                                  eta=[0.01]*len(dictionary_LDA.keys()))\n\n\n\n\n\n```\n\n    CPU times: user 30 s, sys: 14.1 ms, total: 30 s\n    Wall time: 30 s\n\n\n\n```python\n# %%capture\n\nimport seaborn as sns;\n\ntopics = [lda_model[corpus[i]] for i in range(len(data))]\n\ndef topics_document_to_dataframe(topics_document, num_topics):\n    res = pd.DataFrame(columns=range(num_topics))\n    for topic_weight in topics_document:\n        res.loc[0, topic_weight[0]] = topic_weight[1]\n    return res\n\n\n# Like TF-IDF, create a matrix of topic weighting, with documents as rows and topics as columns\ndocument_topic = pd.concat([topics_document_to_dataframe(topics_document, num_topics=num_topics) for topics_document in topics]) \\\n  .reset_index(drop=True).fillna(0)\n\n\n\n```\n\n\n```python\n# %%capture\n\ndocument_topic.head()\n\n%matplotlib inline\nsns.set(rc={'figure.figsize':(10,20)})\nsns.heatmap(document_topic.loc[document_topic.idxmax(axis=1).sort_values().index])\n```\n\n\n```python\n# %%capture\n\nsns.set(rc={'figure.figsize':(10,5)})\ndocument_topic.idxmax(axis=1).value_counts().plot.bar(color='lightblue')\n```\n\n\n```python\n# %%capture\n\n# https://cran.r-project.org/web/packages/LDAvis/vignettes/details.pdf\n# Here a short legend to explain the vis:\n# size of bubble: proportional to the proportions of the topics across the N total tokens in the corpus\n# red bars: estimated number of times a given term was generated by a given topic\n# blue bars: overall frequency of each term in the corpus\n# -- Relevance of words is computed with a parameter lambda\n# -- Lambda optimal value ~0.6 (https://nlp.stanford.edu/events/illvi2014/papers/sievert-illvi2014.pdf)\n%matplotlib inline\nimport pyLDAvis\nimport pyLDAvis.gensim\nvis = pyLDAvis.gensim.prepare(topic_model=lda_model, corpus=corpus, dictionary=dictionary_LDA)\npyLDAvis.enable_notebook()\npyLDAvis.display(vis)\n\n```\n\n\n\n\n\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdn.rawgit.com/bmabey/pyLDAvis/files/ldavis.v1.0.0.css\">\n\n\n<div id=\"ldavis_el260141397919793498402152304353\"></div>\n\n\n\n\n\n```python\n# %%capture\nfrom wordcloud import WordCloud,STOPWORDS\n\ndef showWordCloud(data):\n    words = ' '.join(data)\n    cleaned_word = \" \".join([word for word in words.split()])\n    wordcloud = WordCloud(stopwords = STOPWORDS,\n                         background_color = 'black',\n                         width = 2500,\n                         height = 2500\n                         ).generate(cleaned_word)\n    plt.figure(1,figsize = (13,13))\n    plt.imshow(wordcloud)\n    plt.axis('off')\n    plt.show()\n\nflat_list = [item for sublist in tokens for item in sublist]\n\n#flat_list\nshowWordCloud(flat_list)\n```\n\n# Comparison Questions\n\n### Q1.) ***What is the archiving service 4plen coverage of 4chan and what is the quality of the coverage?***\n\n\nBetween the dates of **{{_from_date.strftime(\"%d/%m/%Y, %H:%M:%S\") }}** and **{{_to_date.strftime(\"%d/%m/%Y, %H:%M:%S\") }}** we have crawled **{{ \"{:,}\".format(len(match_result)) }}** threads on 4chan /pol board. \n\nOf these, we have collected data from all three sources - 4chan scrap using OXPath, 4chan API and 4pleb API (i.e. scraped thread, posts content and metadata) on **{{full_match_len}} / {{\"%.3f\" % (full_match_len/len(match_result)*100)}} %** of the results.\n\nWe have found on the 4chan archiving service, 4pleb, **{{match_result.pleb.sum()}}  / {{\"%.3f\" % perc_match }}%** of the results.\n\nLooking into the remainder **{{ len(match_result) - match_result.pleb.sum() }} / {{\"%.3f\" % perc_not_match }}%** that are not found in the archiving service we have noticed that: \n\n- We have scraped **{{ len(not_pleb_yes_chan) }} / {{ \"%.3f\" % (len(not_pleb_yes_chan)/len(not_pleb_match)*100) }}%** threads from 4chan API but not found on 4pleb. \n- We have scraped **{{ len(not_pleb_yes_chan_or_oxp) }} / {{ \"%.3f\" % (len(not_pleb_yes_chan_or_oxp)/len(not_pleb_match)*100) }}** using OXPath or 4chan API scraping methods. Of these **{{ len(not_pleb_match.query(\"oxp\")) }}** is the number of items scraped using OXPath.\n\nThe analysis of the deleted threads could lead to insight on how threads are being monitored \n\n- There are **{{ \"{:,}\".format(len(match_result.query(\"deleted==True\"))) }}** threads that have been marked as deleted by the OXPath scraper. Of the deleted threads, **{{ \"{:,}\".format(len(match_result.query(\"pleb\").query(\"deleted==True\"))) }}** have been found been found on the 4pleb archiving API. \n- There are **{{ len(id_chan_posts) }}** threads found on 4chan API that have been marked as deleted. **{{ num_del_chan }}** have also been found and marked as deleted by OXpath scraper\n- There are **{{ len(pleb_posts.query(\"deleted=='1'\")) }}** threads marked as deleted in 4pleb. **{{len(match_result[match_result['num'].isin(id_pleb_posts)].query('deleted==True'))}}** have also been found and marked as deleted by OXpath scraper\n\nThe deleted threads seems to behave according to the following pattern:\n\n* Threads are posted by original poster (op)\n* There is some activity on the thread (replies and/or reads) \n* The thread becomes in-accessible and its URL return *404 - Page not found*\n    * The OXPath scraper marks the thread as deleted\n* Some threads are deleted permanently whilst others are returned on the main board and the activity continues\n    * We can assume that **{{ \"%.3f\" % ( (len(pleb_posts.query(\"deleted=='1'\")) / len(match_result.query(\"pleb\").query(\"deleted==True\"))) * 100)  }}%** of the cases that 4pleb also finds to be deleted, is the actual number of deleted threads\n    \n\n\n### Q1.1) - What topics of threads are being deleted and what is the difference between the ones permanently deleted and the ones put back on the board? \n\nWhen analysing deleted threads we have to take into consideration the following question: \n    ***How do we know when a thread has been deleted?*** \n\nThe question is non trivial because ultimately ***all*** threads get deleted from 4chan. We are interested in a ***deleted*** status of the thread outside of it's expected life cycle.  The live expectancy of a thread $L_t$ (i.e. the elapsed amount of time during which a thread is reachable by it's uniquer URL) is composed of two components: $E_b$ - *Elapsed* time on the *board* and $E_a$ - *Elapsed* time *archived*. \n\n\\begin{equation} \\label{eq1}\n    L_t = E_b + E_a \n\\end{equation}\n\nThe second component $E_a$ is expected to be constant. All threads remain available for three days after they are archived. <span class=\"mark\">(add reference)</span>\n\nThe first element, the elapsed time a thread spends on the board $E_b$, is an entity of time, and function of activity and janitor moderation. The activity on a thread is a combination of posts/images/authors. We can simplify this by only considering the number of posts (i.e. replies). Each new post bumps the thread up on the board, delaying it's archiving time <span class=\"mark\">(add reference)</span> . The bumping effect is also a function that decays with time. Alternatively, since $E_b$ already represents time, it can be expressed based on the number of posts $p$. Similarly, the rate of decay $\\beta$  grows as the number of posts on the thread grows (each posts bumps the thread up a bit, but every time less than the previous).\n\n\nFurthermore, emerging from data, at times threads gets removed from the board and appear to be deleted. This is expected as 4chan has various levels of moderation by its *janitors*. Since threads can also be in a deleted state and then put back in the live board we are going to consider $P(d)$ as the probability of a threat being deleted with it's values $P(d) \\in [0,1]  where  P(d)=0$ thread was not deleted, $P(d)=1$ thread was deleted, $P(d) \\in (0,1)$ thread was deleted for a certain amount of time as percentage of its elapsed time and then put back in the live board.\n\n\\begin{equation}\n    E_b = [log(np)(1-\\frac{p}{max_p})^{log(p)}]*(1-P(d))\n\\end{equation}\n\nSince we know that n = 200, and assuming $P(d)$ only affects threads in the live board\n\n\\begin{equation}\n    L_t = [log(200p)(1-\\frac{p}{max_p})^{log(p)}]*(1-P(d)) + E_a\n\\end{equation}\n\nwhere \n\n- $L_t$ Elapsed life (time) of a thread\n- $n$ Number of threads on the board\n- $p$ Number of posts on the thread\n- $max_p$ The maximum number of posts any thread on the board has\n- $\\beta = p/max_p$ rate of decay of the thread through out the board\n- $P(d)$ The probability that a thread has been deleted\n- $E_a$ The elapsed time during which the thread is available in the archived board\n\n<span class=\"burk\">Should a.) Load all threads, nr_replies, elapsed time between start date and last post, deleted flag b.) plot calculated time and observed time, c.) check difference and formula fit. \n</span>\n\n<span class=\"burk\">**(question outside of main quest - dropping it)**</span>\n\n\n\n```python\n# %%capture\nprint('Plot showing the distribution of number of replies for missed threads)')\n\nf2 = f1[f1.chan == True]\nchan_op = pd.DataFrame(list(f2['chan_op']))\nchan_op.drop(axis=1, inplace=True, columns=['md5', 'resto', 'imagelimit', 'troll_country'])#, 'm_img', 'tail_size', 'trip'])\nchan_op.drop(axis=1, inplace=True, columns=['ext',\t'w',\t'h',\t'tn_w',\t'tn_h',\t\n                      'tim',\t'time',\t'fsize',\t'country',\n                      'archived',\t'bumplimit',\t'semantic_url',\n                      'country_name',\t'images'])\nchan_op = chan_op.sort_values('replies', ascending=False)\nplt.hist(chan_op.replies, bins=20)\n\n```\n\n\n```python\n# %%capture\nimport time\nfrom datetime import datetime\n\nprint('Plot showing the time to being arcived of the threads not captured)')\n\ntime_op = pd.DataFrame([chan_op.no, chan_op.archived_on, chan_op.now])\ntime_op = time_op.transpose()\ntime_op['now'] = pd.to_datetime(time_op['now'] , format='%m/%d/%y(%a)%X')\n#time_op['archived_on'] = time_op['archived_on'].apply(time.localtime)\ntime_op['archived_on'] = time_op['archived_on'].apply(datetime.fromtimestamp)\ntime_op['length'] =  (time_op.archived_on - time_op.now).astype('timedelta64[h]')\ntime_op = time_op.sort_values(['length'])\nplt.hist(time_op.length, bins=20)\n\n```\n\n\n```python\n# %%capture\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams.update({'figure.figsize':(7,5), 'figure.dpi':100})\n\nplt.hist(count, bins=50)\nplt.gca().set(title='Frequency Histogram', ylabel='Frequency');\n\n\n```\n\n\n```python\n# %%capture\npipeline = [ \n            {\"$match\": {\"api_scrap\": True } }, { \"$addFields\": {\n        \"pleb_array\": {\n                \"$ifNull\": [ {\"$objectToArray\": \"$pleb\"}, [ ] ] \n        }\n    } },     \n    {\"$project\": {\"_id\": 0, \"url\": \"$_id\", \"api_chan_posts\": { \"$size\": { \"$ifNull\": [ \"$chan.posts\", [ ] ] } } ,\n                \"api_chan_op\": {\"$arrayElemAt\": [\"$chan.posts\", 0 ] }, \"pleb_array\": {\"$arrayElemAt\": [\"$pleb_array\", 0 ] } } },\n    {\"$project\": {\"url\": 1, \"api_chan_posts\": 1, \"api_chan_op\": 1\n                ,\"api_pleb_posts\":  {\"$ifNull\": [ {\"$objectToArray\": \"$pleb_array.v.posts\"}, [ ] ] } \n                ,\"api_pleb_op\": \"$pleb_array.v.op\"  } } ,\n     {\"$project\": {\"url\": 1, \"api_chan_posts\": 1, \"api_chan_op\": 1, \"api_pleb_op\": 1, \"api_pleb_posts\": {\"$size\": \"$api_pleb_posts\"} } }\n]\n\n\nthread_data = pd.DataFrame(threads.aggregate(pipeline, allowDiskUse=True))\n\n```\n\n\n```python\n# %%capture\npipeline = [\n    {\"$match\": {\"$and\": [{ \"data\": {\"$ne\": None } },{\"data\": {\"$type\": \"array\" } } ] } }\n   ,{\"$project\": { \"url\": 1, \"chan_posts\": {\"$arrayElemAt\": [\"$data\", -1 ] } } } \n   ,{\"$project\": { \"url\": 1, \"chan_posts\": {\"$arrayElemAt\": [\"$chan_posts.payload.thread\", 0] } } }\n   ,{\"$project\": { \"_id\":0, \"url\": 1, \"chan_posts\": {\"$size\": {\"$ifNull\": [ \"$chan_posts.replies\", [ ] ] } }, \n       \"chan_op\": \"$chan_posts.op\" } } \n   ,{\"$unwind\": \"$chan_op\"}\n]\n\noriginal_thread_data = pd.DataFrame(livechan.aggregate(pipeline, allowDiskUse=True))\nlen(original_thread_data)\n# sum(original_thread_data['chan_posts'])\n\n```\n\n\n```python\n# %%capture\nimport json\n#plt.plot(thread_data['api_chan_posts'] - thread_data['api_bleb_posts'])\nmerged_data = pd.merge(thread_data, original_thread_data, on=[\"url\"])\nmerged_data['diff_posts'] = abs(merged_data['api_chan_posts'] - merged_data['api_pleb_posts'])\nmerged_data = merged_data.sort_values(by=['diff_posts'], ascending=False)\nprint(f'OXpath Threads {len(original_thread_data)}')\nprint(f'4Pleb and 4 Chan Threads {len(thread_data)}')\nprint(f'Merged match {len(merged_data)}')\n\n# merged_data.api_chan_op[merged_data.api_chan_op == None]['api_chan_op'] = { }\n# merged_data.api_chan_op1 = pd.DataFrame(list(merged_data.api_chan_op))\n\n```\n\n\n```python\n# %%capture\nimport numpy\nimport scipy.stats as ss\nno_api_chan = merged_data[~merged_data.api_chan_op.isnull()].sort_values(by=['diff_posts'], ascending=False)\nno_api_pleb = no_api_chan[~no_api_chan.api_pleb_op.isnull()].sort_values(by=['diff_posts'], ascending=False)\n#no_api_pleb = no_api_pleb[no_api_pleb.diff_posts > 0]\n#print(no_api_pleb.diff_posts.mean())\n#print(no_api_pleb.diff_posts.std())\n#ss.describe(no_api_pleb.diff_posts)\n#diff_pdf = ss.norm.pdf(no_api_pleb.diff_posts, 0, 1)\n#plt.plot(no_api_pleb.diff_posts, diff_pdf, label='pdf')\n\nmu = 0\nsigma = 1\ndiff_cdf = ss.norm.cdf(no_api_pleb.diff_posts, mu, sigma)\ndiff_pdf = ss.norm.pdf(no_api_pleb.diff_posts, mu, sigma)\n\nfig=plt.figure()\nax=fig.add_subplot(111)\nax.plot(no_api_pleb.diff_posts, diff_pdf, label='pdf')\nax.plot(no_api_pleb.diff_posts, diff_cdf, label='cdf')\nax.set_xlim(xmin=0.0, xmax=10)\nax.legend()\nplt.show()\n\n```\n\n\n\n### Q2.) What is the persentage of posts that can be matched on all three crawling methods and what are the gaps\n\nWhilst looking at the thread coverage from the archiving sites, we can see promising results with matching results well above $95.00$% another question is around the quality of the coverage. That is, do the threads discovered and retrieved from the archiving services (in this case 4pleb API) have the same information as what retrieved from 4chan API and/or OXPath scraping method?\n\nThe best way to look at quality would be to: \n1. verify that the thread contains and matches some of the key metadata (such as date it was posted, date it was archived, author country) \n2. verify that the thread contains and matches its main content (such as subject, comment, media) and lastly \n3. verify that the linked posts match with what is reported from 4chan API and/or OXPath scraping method. \n\n\n\n\n### Q3.) What can be said about the significat amount of threads that get flagged/marked as \"deleted/404\" and either permanently deleted or returned to the board. What topics get permanently deleted? What topics get flagged? \n", "meta": {"hexsha": "18de93647a04e3d144a047c985b807da765194e9", "size": 960262, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "jupyter/4chan-topic-modelling.ipynb", "max_stars_repo_name": "yprift01/4chan-data-project", "max_stars_repo_head_hexsha": "4d95214d05f6deb813fdf7a000317214c3232bdd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jupyter/4chan-topic-modelling.ipynb", "max_issues_repo_name": "yprift01/4chan-data-project", "max_issues_repo_head_hexsha": "4d95214d05f6deb813fdf7a000317214c3232bdd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jupyter/4chan-topic-modelling.ipynb", "max_forks_repo_name": "yprift01/4chan-data-project", "max_forks_repo_head_hexsha": "4d95214d05f6deb813fdf7a000317214c3232bdd", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 503.2819706499, "max_line_length": 477396, "alphanum_fraction": 0.8628488892, "converted": true, "num_tokens": 10572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06853748542165705, "lm_q2_score": 0.03021458455677822, "lm_q1q2_score": 0.0020708316485816116}}
{"text": "<a href=\"https://colab.research.google.com/github/groar/gpt-2/blob/chat/GPT_2_TPU_INFERENCE_TRAIN.ipynb\" target=\"_parent\"></a>\n\n# Get Google Drive mounted as disk\n\n\n```\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly\n    \n    Enter your authorization code:\n    \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\n    Mounted at /content/drive\n\n\n\n```\n%mkdir /content/drive/My\\ Drive/SLACKBOT/\n```\n\n    mkdir: cannot create directory \u2018/content/drive/My Drive/SLACKBOT/\u2019: File exists\n\n\n\n```\n%cd /content/drive/My\\ Drive/SLACKBOT/\n```\n\n    /content/drive/My Drive/SLACKBOT\n\n\n# Cloning the code\n\nI have modified a few things in the original GPT-2 code. So you have to use my repository to make it work.\n\n\n```\n!git clone https://github.com/groar/gpt-2 -b chat gpt-2\n```\n\n    fatal: destination path 'gpt-2' already exists and is not an empty directory.\n\n\n# Installing all the requirements\n\n\n```\n!pip3 install -r requirements.txt\n```\n\n    Collecting fire>=0.1.3\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/34/a7/0e22e70778aca01a52b9c899d9c145c6396d7b613719cd63db97ffa13f2f/fire-0.3.1.tar.gz (81kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 81kB 2.2MB/s \n    \u001b[?25hCollecting regex==2017.4.5\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/36/62/c0c0d762ffd4ffaf39f372eb8561b8d491a11ace5a7884610424a8b40f95/regex-2017.04.05.tar.gz (601kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 604kB 8.5MB/s \n    \u001b[?25hCollecting requests==2.21.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/7d/e3/20f3d364d6c8e5d2353c72a67778eb189176f08e873c9900e10c0287b84b/requests-2.21.0-py2.py3-none-any.whl (57kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 61kB 7.6MB/s \n    \u001b[?25hCollecting tqdm==4.31.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/6c/4b/c38b5144cf167c4f52288517436ccafefe9dc01b8d1c190e18a6b154cd4a/tqdm-4.31.1-py2.py3-none-any.whl (48kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 5.8MB/s \n    \u001b[?25hCollecting toposort==1.5\n      Downloading https://files.pythonhosted.org/packages/e9/8a/321cd8ea5f4a22a06e3ba30ef31ec33bea11a3443eeb1d89807640ee6ed4/toposort-1.5-py2.py3-none-any.whl\n    Collecting tensor2tensor>=1.14.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/4a/49/950b57285034e76821f169bc9ee131b05fc0481258c443abbdbafc9d0638/tensor2tensor-1.15.6-py2.py3-none-any.whl (1.4MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.4MB 16.1MB/s \n    \u001b[?25hCollecting tokenizers==0.0.9\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/db/61/38694f1bbaa8d8528045e083c3d1a59ef062ede798ddf1fce2c5d6f13ee3/tokenizers-0.0.9-cp36-cp36m-manylinux1_x86_64.whl (3.1MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.1MB 32.8MB/s \n    \u001b[?25hRequirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from -r requirements.txt (line 8)) (2.10.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from fire>=0.1.3->-r requirements.txt (line 1)) (1.12.0)\n    Requirement already satisfied: termcolor in /usr/local/lib/python3.6/dist-packages (from fire>=0.1.3->-r requirements.txt (line 1)) (1.1.0)\n    Collecting idna<2.9,>=2.5\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/14/2c/cd551d81dbe15200be1cf41cd03869a46fe7226e7450af7a6545bfc474c9/idna-2.8-py2.py3-none-any.whl (58kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 61kB 5.7MB/s \n    \u001b[?25hRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests==2.21.0->-r requirements.txt (line 3)) (2020.4.5.1)\n    Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests==2.21.0->-r requirements.txt (line 3)) (1.24.3)\n    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests==2.21.0->-r requirements.txt (line 3)) (3.0.4)\n    Requirement already satisfied: google-api-python-client in /usr/local/lib/python3.6/dist-packages (from tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (1.7.12)\n    Requirement already satisfied: dopamine-rl in /usr/local/lib/python3.6/dist-packages (from tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (1.0.5)\n    Collecting gevent\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/28/8b/918c61f23693971f4eedb3f910438e18b9bab489511dd1f313657ef0a330/gevent-20.6.1-cp36-cp36m-manylinux2010_x86_64.whl (5.3MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5.3MB 20.9MB/s \n    \u001b[?25hCollecting gunicorn\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/69/ca/926f7cd3a2014b16870086b2d0fdc84a9e49473c68a8dff8b57f7c156f43/gunicorn-20.0.4-py2.py3-none-any.whl (77kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 81kB 11.0MB/s \n    \u001b[?25hCollecting tf-slim\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/02/97/b0f4a64df018ca018cc035d44f2ef08f91e2e8aa67271f6f19633a015ff7/tf_slim-1.1.0-py2.py3-none-any.whl (352kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 358kB 51.2MB/s \n    \u001b[?25hRequirement already satisfied: opencv-python in /usr/local/lib/python3.6/dist-packages (from tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (4.1.2.30)\n    Requirement already satisfied: tensorflow-datasets in /usr/local/lib/python3.6/dist-packages (from tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (2.1.0)\n    Collecting pypng\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/bc/fb/f719f1ac965e2101aa6ea6f54ef8b40f8fbb033f6ad07c017663467f5147/pypng-0.0.20.tar.gz (649kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 655kB 53.2MB/s \n    \u001b[?25hRequirement already satisfied: sympy in /usr/local/lib/python3.6/dist-packages (from tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (1.1.1)\n    Requirement already satisfied: Pillow in /usr/local/lib/python3.6/dist-packages (from tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (7.0.0)\n    Requirement already satisfied: tensorflow-addons in /usr/local/lib/python3.6/dist-packages (from tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (0.8.3)\n    Requirement already satisfied: oauth2client in /usr/local/lib/python3.6/dist-packages (from tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (4.1.3)\n    Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (0.16.0)\n    Collecting gym==0.14.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/61/75/9e841bc2bc75128e0b65c3d5255d0bd16becb9d8f7120b965d41b8e70041/gym-0.14.0.tar.gz (1.6MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.6MB 51.7MB/s \n    \u001b[?25hRequirement already satisfied: flask in /usr/local/lib/python3.6/dist-packages (from tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (1.1.2)\n    Collecting mesh-tensorflow\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/ea/32/ceaf1549586ccfeaf7840a166876be358bd78ab2fdd152b17c5600ed7888/mesh_tensorflow-0.1.13-py3-none-any.whl (292kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 296kB 51.0MB/s \n    \u001b[?25hCollecting tensorflow-gan\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/0c/2e/62922111d7d50e1900e3030764743ea7735540ce103b3ab30fd5cd2d8a2b/tensorflow_gan-2.0.0-py2.py3-none-any.whl (365kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 368kB 56.1MB/s \n    \u001b[?25hRequirement already satisfied: gin-config in /usr/local/lib/python3.6/dist-packages (from tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (0.3.0)\n    Collecting bz2file\n      Downloading https://files.pythonhosted.org/packages/61/39/122222b5e85cd41c391b68a99ee296584b2a2d1d233e7ee32b4532384f2d/bz2file-0.98.tar.gz\n    Collecting kfac\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/01/f0/4a7758f854a15b37d322827123ce58619d0f4270dd94f2dd30328f397339/kfac-0.2.0-py2.py3-none-any.whl (178kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 184kB 39.5MB/s \n    \u001b[?25hCollecting tensorflow-probability==0.7.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/3e/3a/c10b6c22320531c774402ac7186d1b673374e2a9d12502cbc8d811e4601c/tensorflow_probability-0.7.0-py2.py3-none-any.whl (981kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 983kB 59.2MB/s \n    \u001b[?25hRequirement already satisfied: absl-py in /usr/local/lib/python3.6/dist-packages (from tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (0.9.0)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (1.18.5)\n    Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (1.4.1)\n    Requirement already satisfied: uritemplate<4dev,>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (3.0.1)\n    Requirement already satisfied: google-auth-httplib2>=0.0.3 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (0.0.3)\n    Requirement already satisfied: httplib2<1dev,>=0.17.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (0.17.4)\n    Requirement already satisfied: google-auth>=1.4.1 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (1.7.2)\n    Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from gevent->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (47.1.1)\n    Collecting zope.interface\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/57/33/565274c28a11af60b7cfc0519d46bde4125fcd7d32ebc0a81b480d0e8da6/zope.interface-5.1.0-cp36-cp36m-manylinux2010_x86_64.whl (234kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 235kB 51.8MB/s \n    \u001b[?25hCollecting zope.event\n      Downloading https://files.pythonhosted.org/packages/c5/96/361edb421a077a4c208b4a5c212737d78ae03ce67fbbcd01621c49f332d1/zope.event-4.4-py2.py3-none-any.whl\n    Collecting greenlet>=0.4.16; platform_python_implementation == \"CPython\"\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/7e/a4/0d8685c98986326534b0753a8b92b3082bc9df42b348bc50d6c69839c9f9/greenlet-0.4.16-cp36-cp36m-manylinux1_x86_64.whl (44kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 51kB 7.7MB/s \n    \u001b[?25hRequirement already satisfied: protobuf>=3.6.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (3.10.0)\n    Requirement already satisfied: promise in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (2.3)\n    Requirement already satisfied: attrs>=18.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (19.3.0)\n    Requirement already satisfied: wrapt in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (1.12.1)\n    Requirement already satisfied: tensorflow-metadata in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (0.22.1)\n    Requirement already satisfied: dill in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (0.3.1.1)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (1.1.0)\n    Requirement already satisfied: typeguard in /usr/local/lib/python3.6/dist-packages (from tensorflow-addons->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (2.7.1)\n    Requirement already satisfied: rsa>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (4.0)\n    Requirement already satisfied: pyasn1>=0.1.7 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (0.4.8)\n    Requirement already satisfied: pyasn1-modules>=0.0.5 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (0.2.8)\n    Collecting pyglet<=1.3.2,>=1.2.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1c/fc/dad5eaaab68f0c21e2f906a94ddb98175662cc5a654eee404d59554ce0fa/pyglet-1.3.2-py2.py3-none-any.whl (1.0MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.0MB 57.7MB/s \n    \u001b[?25hCollecting cloudpickle~=1.2.0\n      Downloading https://files.pythonhosted.org/packages/c1/49/334e279caa3231255725c8e860fa93e72083567625573421db8875846c14/cloudpickle-1.2.2-py2.py3-none-any.whl\n    Requirement already satisfied: click>=5.1 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (7.1.2)\n    Requirement already satisfied: Werkzeug>=0.15 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (1.0.1)\n    Requirement already satisfied: itsdangerous>=0.24 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (1.1.0)\n    Requirement already satisfied: Jinja2>=2.10.1 in /usr/local/lib/python3.6/dist-packages (from flask->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (2.11.2)\n    Requirement already satisfied: tensorflow-hub>=0.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gan->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (0.8.0)\n    Requirement already satisfied: decorator in /usr/local/lib/python3.6/dist-packages (from tensorflow-probability==0.7.0->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (4.4.2)\n    Requirement already satisfied: cachetools<3.2,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth>=1.4.1->google-api-python-client->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (3.1.1)\n    Requirement already satisfied: googleapis-common-protos in /usr/local/lib/python3.6/dist-packages (from tensorflow-metadata->tensorflow-datasets->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (1.52.0)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.6/dist-packages (from Jinja2>=2.10.1->flask->tensor2tensor>=1.14.1->-r requirements.txt (line 6)) (1.1.1)\n    Building wheels for collected packages: fire, regex, pypng, gym, bz2file\n      Building wheel for fire (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for fire: filename=fire-0.3.1-py2.py3-none-any.whl size=111005 sha256=c3b5825d87efc57809dff5dd1607ad7a9e43485b1b3b47007b57d071a02a8c92\n      Stored in directory: /root/.cache/pip/wheels/c1/61/df/768b03527bf006b546dce284eb4249b185669e65afc5fbb2ac\n      Building wheel for regex (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for regex: filename=regex-2017.4.5-cp36-cp36m-linux_x86_64.whl size=533217 sha256=b6e757869dc6bc8222e036a57cdab1b26695905706a436dbc16c0793c602ddc5\n      Stored in directory: /root/.cache/pip/wheels/75/07/38/3c16b529d50cb4e0cd3dbc7b75cece8a09c132692c74450b01\n      Building wheel for pypng (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for pypng: filename=pypng-0.0.20-cp36-none-any.whl size=67161 sha256=ef6df6528512f5a6ff49de60c0719434fa3a2ba24b1094c924784d3b1e05ae38\n      Stored in directory: /root/.cache/pip/wheels/41/6b/ef/0493b536b6d4722c2ae9486691b1d49b922b9877922beeabb3\n      Building wheel for gym (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for gym: filename=gym-0.14.0-cp36-none-any.whl size=1637522 sha256=1772fa3349e8cde96a926e9fae8af7f9546ac7a5bd2b354dd884ccda3bb4ab84\n      Stored in directory: /root/.cache/pip/wheels/7e/53/f6/c0cd3c9bf953f35c0aee7fa62ea209371e92f5e5cced3245ba\n      Building wheel for bz2file (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for bz2file: filename=bz2file-0.98-cp36-none-any.whl size=6884 sha256=77d7400bddedc314836dc72148ded0235cbfd0652232447d6cfe6acfb2880029\n      Stored in directory: /root/.cache/pip/wheels/81/75/d6/e1317bf09bf1af5a30befc2a007869fa6e1f516b8f7c591cb9\n    Successfully built fire regex pypng gym bz2file\n    \u001b[31mERROR: spacy 2.2.4 has requirement tqdm<5.0.0,>=4.38.0, but you'll have tqdm 4.31.1 which is incompatible.\u001b[0m\n    \u001b[31mERROR: google-colab 1.0.0 has requirement requests~=2.23.0, but you'll have requests 2.21.0 which is incompatible.\u001b[0m\n    \u001b[31mERROR: datascience 0.10.6 has requirement folium==0.2.1, but you'll have folium 0.8.3 which is incompatible.\u001b[0m\n    Installing collected packages: fire, regex, idna, requests, tqdm, toposort, zope.interface, zope.event, greenlet, gevent, gunicorn, tf-slim, pypng, pyglet, cloudpickle, gym, mesh-tensorflow, tensorflow-probability, tensorflow-gan, bz2file, kfac, tensor2tensor, tokenizers\n      Found existing installation: regex 2019.12.20\n        Uninstalling regex-2019.12.20:\n          Successfully uninstalled regex-2019.12.20\n      Found existing installation: idna 2.9\n        Uninstalling idna-2.9:\n          Successfully uninstalled idna-2.9\n      Found existing installation: requests 2.23.0\n        Uninstalling requests-2.23.0:\n          Successfully uninstalled requests-2.23.0\n      Found existing installation: tqdm 4.41.1\n        Uninstalling tqdm-4.41.1:\n          Successfully uninstalled tqdm-4.41.1\n      Found existing installation: pyglet 1.5.0\n        Uninstalling pyglet-1.5.0:\n          Successfully uninstalled pyglet-1.5.0\n      Found existing installation: cloudpickle 1.3.0\n        Uninstalling cloudpickle-1.3.0:\n          Successfully uninstalled cloudpickle-1.3.0\n      Found existing installation: gym 0.17.2\n        Uninstalling gym-0.17.2:\n          Successfully uninstalled gym-0.17.2\n      Found existing installation: tensorflow-probability 0.10.0\n        Uninstalling tensorflow-probability-0.10.0:\n          Successfully uninstalled tensorflow-probability-0.10.0\n    Successfully installed bz2file-0.98 cloudpickle-1.2.2 fire-0.3.1 gevent-20.6.1 greenlet-0.4.16 gunicorn-20.0.4 gym-0.14.0 idna-2.8 kfac-0.2.0 mesh-tensorflow-0.1.13 pyglet-1.3.2 pypng-0.0.20 regex-2017.4.5 requests-2.21.0 tensor2tensor-1.15.6 tensorflow-gan-2.0.0 tensorflow-probability-0.7.0 tf-slim-1.1.0 tokenizers-0.0.9 toposort-1.5 tqdm-4.31.1 zope.event-4.4 zope.interface-5.1.0\n\n\n\n\nWhat follows is necessary to train & for inference, as well as for using the TPU.\n\n\n```\n!pip install tensorflow-gpu==1.15.0\n!pip install 'tensorflow-estimator<1.15.0rc0,>=1.14.0rc0' --force-reinstall\n\n```\n\n    Collecting tensorflow-gpu==1.15.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/a5/ad/933140e74973fb917a194ab814785e7c23680ca5dee6d663a509fe9579b6/tensorflow_gpu-1.15.0-cp36-cp36m-manylinux2010_x86_64.whl (411.5MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 411.5MB 40kB/s \n    \u001b[?25hRequirement already satisfied: keras-applications>=1.0.8 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.0) (1.0.8)\n    Collecting gast==0.2.2\n      Downloading https://files.pythonhosted.org/packages/4e/35/11749bf99b2d4e3cceb4d55ca22590b0d7c2c62b9de38ac4a4a7f4687421/gast-0.2.2.tar.gz\n    Collecting tensorflow-estimator==1.15.1\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/de/62/2ee9cd74c9fa2fa450877847ba560b260f5d0fb70ee0595203082dafcc9d/tensorflow_estimator-1.15.1-py2.py3-none-any.whl (503kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 512kB 46.6MB/s \n    \u001b[?25hRequirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.0) (1.12.1)\n    Requirement already satisfied: google-pasta>=0.1.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.0) (0.2.0)\n    Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.0) (3.2.1)\n    Collecting tensorboard<1.16.0,>=1.15.0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/1e/e9/d3d747a97f7188f48aa5eda486907f3b345cd409f0a0850468ba867db246/tensorboard-1.15.0-py3-none-any.whl (3.8MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.8MB 47.4MB/s \n    \u001b[?25hRequirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.0) (1.1.0)\n    Requirement already satisfied: keras-preprocessing>=1.0.5 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.0) (1.1.2)\n    Requirement already satisfied: numpy<2.0,>=1.16.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.0) (1.18.5)\n    Requirement already satisfied: protobuf>=3.6.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.0) (3.10.0)\n    Requirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.0) (0.34.2)\n    Requirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.0) (0.9.0)\n    Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.0) (1.29.0)\n    Requirement already satisfied: astor>=0.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.0) (0.8.1)\n    Requirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==1.15.0) (1.12.0)\n    Requirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from keras-applications>=1.0.8->tensorflow-gpu==1.15.0) (2.10.0)\n    Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tensorboard<1.16.0,>=1.15.0->tensorflow-gpu==1.15.0) (1.0.1)\n    Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard<1.16.0,>=1.15.0->tensorflow-gpu==1.15.0) (47.1.1)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard<1.16.0,>=1.15.0->tensorflow-gpu==1.15.0) (3.2.2)\n    Requirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from markdown>=2.6.8->tensorboard<1.16.0,>=1.15.0->tensorflow-gpu==1.15.0) (1.6.0)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata; python_version < \"3.8\"->markdown>=2.6.8->tensorboard<1.16.0,>=1.15.0->tensorflow-gpu==1.15.0) (3.1.0)\n    Building wheels for collected packages: gast\n      Building wheel for gast (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for gast: filename=gast-0.2.2-cp36-none-any.whl size=7540 sha256=425ce7b42fc593bbd91ee535b6a88e96450472a3a8c4c66115c99ff7ba37b071\n      Stored in directory: /root/.cache/pip/wheels/5c/2e/7e/a1d4d4fcebe6c381f378ce7743a3ced3699feb89bcfbdadadd\n    Successfully built gast\n    \u001b[31mERROR: tensorflow 2.2.0 has requirement gast==0.3.3, but you'll have gast 0.2.2 which is incompatible.\u001b[0m\n    \u001b[31mERROR: tensorflow 2.2.0 has requirement tensorboard<2.3.0,>=2.2.0, but you'll have tensorboard 1.15.0 which is incompatible.\u001b[0m\n    \u001b[31mERROR: tensorflow 2.2.0 has requirement tensorflow-estimator<2.3.0,>=2.2.0, but you'll have tensorflow-estimator 1.15.1 which is incompatible.\u001b[0m\n    Installing collected packages: gast, tensorflow-estimator, tensorboard, tensorflow-gpu\n      Found existing installation: gast 0.3.3\n        Uninstalling gast-0.3.3:\n          Successfully uninstalled gast-0.3.3\n      Found existing installation: tensorflow-estimator 2.2.0\n        Uninstalling tensorflow-estimator-2.2.0:\n          Successfully uninstalled tensorflow-estimator-2.2.0\n      Found existing installation: tensorboard 2.2.2\n        Uninstalling tensorboard-2.2.2:\n          Successfully uninstalled tensorboard-2.2.2\n    Successfully installed gast-0.2.2 tensorboard-1.15.0 tensorflow-estimator-1.15.1 tensorflow-gpu-1.15.0\n    Collecting tensorflow-estimator<1.15.0rc0,>=1.14.0rc0\n    \u001b[?25l  Downloading https://files.pythonhosted.org/packages/3c/d5/21860a5b11caf0678fbc8319341b0ae21a07156911132e0e71bffed0510d/tensorflow_estimator-1.14.0-py2.py3-none-any.whl (488kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 491kB 2.8MB/s \n    \u001b[31mERROR: tensorflow 2.2.0 has requirement gast==0.3.3, but you'll have gast 0.2.2 which is incompatible.\u001b[0m\n    \u001b[31mERROR: tensorflow 2.2.0 has requirement tensorboard<2.3.0,>=2.2.0, but you'll have tensorboard 1.15.0 which is incompatible.\u001b[0m\n    \u001b[31mERROR: tensorflow 2.2.0 has requirement tensorflow-estimator<2.3.0,>=2.2.0, but you'll have tensorflow-estimator 1.14.0 which is incompatible.\u001b[0m\n    \u001b[31mERROR: tensorflow-gpu 1.15.0 has requirement tensorflow-estimator==1.15.1, but you'll have tensorflow-estimator 1.14.0 which is incompatible.\u001b[0m\n    \u001b[?25hInstalling collected packages: tensorflow-estimator\n      Found existing installation: tensorflow-estimator 1.15.1\n        Uninstalling tensorflow-estimator-1.15.1:\n          Successfully uninstalled tensorflow-estimator-1.15.1\n    Successfully installed tensorflow-estimator-1.14.0\n\n\n\n```\n!wget https://developer.nvidia.com/compute/cuda/9.0/Prod/local_installers/cuda-repo-ubuntu1604-9-0-local_9.0.176-1_amd64-deb\n!dpkg -i cuda-repo-ubuntu1604-9-0-local_9.0.176-1_amd64-deb\n!apt-key add /var/cuda-repo-*/7fa2af80.pub\n!apt-get update\n!apt-get install cuda-9-0\n!export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda-9.0/lib64/\n\n```\n\n    --2020-06-15 10:09:48--  https://developer.nvidia.com/compute/cuda/9.0/Prod/local_installers/cuda-repo-ubuntu1604-9-0-local_9.0.176-1_amd64-deb\n    Resolving developer.nvidia.com (developer.nvidia.com)... 152.199.0.24\n    Connecting to developer.nvidia.com (developer.nvidia.com)|152.199.0.24|:443... connected.\n    HTTP request sent, awaiting response... 302 Found\n    Location: https://developer.download.nvidia.com/compute/cuda/9.0/secure/Prod/local_installers/cuda-repo-ubuntu1604-9-0-local_9.0.176-1_amd64.deb?gUtgPN8b4r1uJyiqslHDjh90d1saPEfnVk3xHtNdMAzpjoyIjoWNhVIQyBG6GGyfHE7QWUem_aXGEMK3a-Nb2ANN91w64XlWH7k87vBJmo0vqTW1WvDAFmpRGksIe5oqvGA0wTbdy2HrAdIkc7PNfVPGeeIDpbwEmfHqIlI-T5L41YXU_XoRa2WVaWsTYdNaQN0SgSAKMuHLLNLMRCav [following]\n    --2020-06-15 10:09:49--  https://developer.download.nvidia.com/compute/cuda/9.0/secure/Prod/local_installers/cuda-repo-ubuntu1604-9-0-local_9.0.176-1_amd64.deb?gUtgPN8b4r1uJyiqslHDjh90d1saPEfnVk3xHtNdMAzpjoyIjoWNhVIQyBG6GGyfHE7QWUem_aXGEMK3a-Nb2ANN91w64XlWH7k87vBJmo0vqTW1WvDAFmpRGksIe5oqvGA0wTbdy2HrAdIkc7PNfVPGeeIDpbwEmfHqIlI-T5L41YXU_XoRa2WVaWsTYdNaQN0SgSAKMuHLLNLMRCav\n    Resolving developer.download.nvidia.com (developer.download.nvidia.com)... 152.199.39.144\n    Connecting to developer.download.nvidia.com (developer.download.nvidia.com)|152.199.39.144|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 1212738714 (1.1G) [application/x-deb]\n    Saving to: \u2018cuda-repo-ubuntu1604-9-0-local_9.0.176-1_amd64-deb.1\u2019\n    \n    cuda-repo-ubuntu160 100%[===================>]   1.13G  46.2MB/s    in 21s     \n    \n    2020-06-15 10:10:13 (54.9 MB/s) - \u2018cuda-repo-ubuntu1604-9-0-local_9.0.176-1_amd64-deb.1\u2019 saved [1212738714/1212738714]\n    \n    Selecting previously unselected package cuda-repo-ubuntu1604-9-0-local.\n    (Reading database ... 144328 files and directories currently installed.)\n    Preparing to unpack cuda-repo-ubuntu1604-9-0-local_9.0.176-1_amd64-deb ...\n    Unpacking cuda-repo-ubuntu1604-9-0-local (9.0.176-1) ...\n    Setting up cuda-repo-ubuntu1604-9-0-local (9.0.176-1) ...\n    OK\n    Get:1 file:/var/cuda-repo-9-0-local  InRelease\n    Ign:1 file:/var/cuda-repo-9-0-local  InRelease\n    Get:2 file:/var/cuda-repo-9-0-local  Release [574 B]\n    Get:2 file:/var/cuda-repo-9-0-local  Release [574 B]\n    Get:3 file:/var/cuda-repo-9-0-local  Release.gpg [819 B]\n    Get:3 file:/var/cuda-repo-9-0-local  Release.gpg [819 B]\n    Get:4 file:/var/cuda-repo-9-0-local  Packages [15.4 kB]\n    Ign:5 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64  InRelease\n    Get:6 http://security.ubuntu.com/ubuntu bionic-security InRelease [88.7 kB]\n    Ign:7 https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64  InRelease\n    Hit:8 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64  Release\n    Get:9 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/ InRelease [3,626 B]\n    Get:10 https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64  Release [564 B]\n    Get:11 https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64  Release.gpg [833 B]\n    Hit:12 http://archive.ubuntu.com/ubuntu bionic InRelease\n    Hit:13 http://ppa.launchpad.net/graphics-drivers/ppa/ubuntu bionic InRelease\n    Get:15 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/ Packages [93.1 kB]\n    Get:16 http://archive.ubuntu.com/ubuntu bionic-updates InRelease [88.7 kB]\n    Get:17 http://ppa.launchpad.net/marutter/c2d4u3.5/ubuntu bionic InRelease [15.4 kB]\n    Get:18 https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64  Packages [32.9 kB]\n    Get:19 http://archive.ubuntu.com/ubuntu bionic-backports InRelease [74.6 kB]\n    Get:20 http://security.ubuntu.com/ubuntu bionic-security/main amd64 Packages [958 kB]\n    Get:21 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 Packages [1,253 kB]\n    Get:22 http://ppa.launchpad.net/marutter/c2d4u3.5/ubuntu bionic/main Sources [1,837 kB]\n    Get:23 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 Packages [1,392 kB]\n    Get:24 http://ppa.launchpad.net/marutter/c2d4u3.5/ubuntu bionic/main amd64 Packages [886 kB]\n    Fetched 6,725 kB in 6s (1,060 kB/s)\n    Reading package lists... Done\n    Reading package lists... Done\n    Building dependency tree       \n    Reading state information... Done\n    The following package was automatically installed and is no longer required:\n      libnvidia-common-440\n    Use 'apt autoremove' to remove it.\n    The following additional packages will be installed:\n      cuda-command-line-tools-9-0 cuda-core-9-0 cuda-cublas-9-0\n      cuda-cublas-dev-9-0 cuda-cudart-9-0 cuda-cudart-dev-9-0 cuda-cufft-9-0\n      cuda-cufft-dev-9-0 cuda-curand-9-0 cuda-curand-dev-9-0 cuda-cusolver-9-0\n      cuda-cusolver-dev-9-0 cuda-cusparse-9-0 cuda-cusparse-dev-9-0\n      cuda-demo-suite-9-0 cuda-documentation-9-0 cuda-driver-dev-9-0\n      cuda-libraries-9-0 cuda-libraries-dev-9-0 cuda-license-9-0\n      cuda-misc-headers-9-0 cuda-npp-9-0 cuda-npp-dev-9-0 cuda-nvgraph-9-0\n      cuda-nvgraph-dev-9-0 cuda-nvml-dev-9-0 cuda-nvrtc-9-0 cuda-nvrtc-dev-9-0\n      cuda-runtime-9-0 cuda-samples-9-0 cuda-toolkit-9-0 cuda-visual-tools-9-0\n    The following NEW packages will be installed:\n      cuda-9-0 cuda-command-line-tools-9-0 cuda-core-9-0 cuda-cublas-9-0\n      cuda-cublas-dev-9-0 cuda-cudart-9-0 cuda-cudart-dev-9-0 cuda-cufft-9-0\n      cuda-cufft-dev-9-0 cuda-curand-9-0 cuda-curand-dev-9-0 cuda-cusolver-9-0\n      cuda-cusolver-dev-9-0 cuda-cusparse-9-0 cuda-cusparse-dev-9-0\n      cuda-demo-suite-9-0 cuda-documentation-9-0 cuda-driver-dev-9-0\n      cuda-libraries-9-0 cuda-libraries-dev-9-0 cuda-license-9-0\n      cuda-misc-headers-9-0 cuda-npp-9-0 cuda-npp-dev-9-0 cuda-nvgraph-9-0\n      cuda-nvgraph-dev-9-0 cuda-nvml-dev-9-0 cuda-nvrtc-9-0 cuda-nvrtc-dev-9-0\n      cuda-runtime-9-0 cuda-samples-9-0 cuda-toolkit-9-0 cuda-visual-tools-9-0\n    0 upgraded, 33 newly installed, 0 to remove and 44 not upgraded.\n    Need to get 0 B/1,097 MB of archives.\n    After this operation, 2,315 MB of additional disk space will be used.\n    Get:1 file:/var/cuda-repo-9-0-local  cuda-license-9-0 9.0.176-1 [22.0 kB]\n    Get:2 file:/var/cuda-repo-9-0-local  cuda-misc-headers-9-0 9.0.176-1 [684 kB]\n    Get:3 file:/var/cuda-repo-9-0-local  cuda-core-9-0 9.0.176-1 [16.9 MB]\n    Get:4 file:/var/cuda-repo-9-0-local  cuda-cudart-9-0 9.0.176-1 [106 kB]\n    Get:5 file:/var/cuda-repo-9-0-local  cuda-driver-dev-9-0 9.0.176-1 [10.9 kB]\n    Get:6 file:/var/cuda-repo-9-0-local  cuda-cudart-dev-9-0 9.0.176-1 [767 kB]\n    Get:7 file:/var/cuda-repo-9-0-local  cuda-command-line-tools-9-0 9.0.176-1 [25.4 MB]\n    Get:8 file:/var/cuda-repo-9-0-local  cuda-nvrtc-9-0 9.0.176-1 [6,348 kB]\n    Get:9 file:/var/cuda-repo-9-0-local  cuda-nvrtc-dev-9-0 9.0.176-1 [9,334 B]\n    Get:10 file:/var/cuda-repo-9-0-local  cuda-cusolver-9-0 9.0.176-1 [26.2 MB]\n    Get:11 file:/var/cuda-repo-9-0-local  cuda-cusolver-dev-9-0 9.0.176-1 [5,317 kB]\n    Get:12 file:/var/cuda-repo-9-0-local  cuda-cublas-9-0 9.0.176-1 [25.0 MB]\n    Get:13 file:/var/cuda-repo-9-0-local  cuda-cublas-dev-9-0 9.0.176-1 [49.4 MB]\n    Get:14 file:/var/cuda-repo-9-0-local  cuda-cufft-9-0 9.0.176-1 [84.1 MB]\n    Get:15 file:/var/cuda-repo-9-0-local  cuda-cufft-dev-9-0 9.0.176-1 [73.7 MB]\n    Get:16 file:/var/cuda-repo-9-0-local  cuda-curand-9-0 9.0.176-1 [38.8 MB]\n    Get:17 file:/var/cuda-repo-9-0-local  cuda-curand-dev-9-0 9.0.176-1 [57.9 MB]\n    Get:18 file:/var/cuda-repo-9-0-local  cuda-cusparse-9-0 9.0.176-1 [25.2 MB]\n    Get:19 file:/var/cuda-repo-9-0-local  cuda-cusparse-dev-9-0 9.0.176-1 [25.3 MB]\n    Get:20 file:/var/cuda-repo-9-0-local  cuda-npp-9-0 9.0.176-1 [46.6 MB]\n    Get:21 file:/var/cuda-repo-9-0-local  cuda-npp-dev-9-0 9.0.176-1 [46.6 MB]\n    Get:22 file:/var/cuda-repo-9-0-local  cuda-nvgraph-9-0 9.0.176-1 [6,081 kB]\n    Get:23 file:/var/cuda-repo-9-0-local  cuda-nvgraph-dev-9-0 9.0.176-1 [5,658 kB]\n    Get:24 file:/var/cuda-repo-9-0-local  cuda-samples-9-0 9.0.176-1 [75.9 MB]\n    Get:25 file:/var/cuda-repo-9-0-local  cuda-documentation-9-0 9.0.176-1 [53.1 MB]\n    Get:26 file:/var/cuda-repo-9-0-local  cuda-libraries-dev-9-0 9.0.176-1 [2,596 B]\n    Get:27 file:/var/cuda-repo-9-0-local  cuda-nvml-dev-9-0 9.0.176-1 [47.6 kB]\n    Get:28 file:/var/cuda-repo-9-0-local  cuda-visual-tools-9-0 9.0.176-1 [398 MB]\n    Get:29 file:/var/cuda-repo-9-0-local  cuda-toolkit-9-0 9.0.176-1 [2,836 B]\n    Get:30 file:/var/cuda-repo-9-0-local  cuda-libraries-9-0 9.0.176-1 [2,566 B]\n    Get:31 file:/var/cuda-repo-9-0-local  cuda-runtime-9-0 9.0.176-1 [2,526 B]\n    Get:32 file:/var/cuda-repo-9-0-local  cuda-demo-suite-9-0 9.0.176-1 [3,880 kB]\n    Get:33 file:/var/cuda-repo-9-0-local  cuda-9-0 9.0.176-1 [2,552 B]\n    Extracting templates from packages: 100%\n    Selecting previously unselected package cuda-license-9-0.\n    (Reading database ... 144387 files and directories currently installed.)\n    Preparing to unpack .../00-cuda-license-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-license-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-misc-headers-9-0.\n    Preparing to unpack .../01-cuda-misc-headers-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-misc-headers-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-core-9-0.\n    Preparing to unpack .../02-cuda-core-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-core-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-cudart-9-0.\n    Preparing to unpack .../03-cuda-cudart-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-cudart-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-driver-dev-9-0.\n    Preparing to unpack .../04-cuda-driver-dev-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-driver-dev-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-cudart-dev-9-0.\n    Preparing to unpack .../05-cuda-cudart-dev-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-cudart-dev-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-command-line-tools-9-0.\n    Preparing to unpack .../06-cuda-command-line-tools-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-command-line-tools-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-nvrtc-9-0.\n    Preparing to unpack .../07-cuda-nvrtc-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-nvrtc-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-nvrtc-dev-9-0.\n    Preparing to unpack .../08-cuda-nvrtc-dev-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-nvrtc-dev-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-cusolver-9-0.\n    Preparing to unpack .../09-cuda-cusolver-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-cusolver-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-cusolver-dev-9-0.\n    Preparing to unpack .../10-cuda-cusolver-dev-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-cusolver-dev-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-cublas-9-0.\n    Preparing to unpack .../11-cuda-cublas-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-cublas-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-cublas-dev-9-0.\n    Preparing to unpack .../12-cuda-cublas-dev-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-cublas-dev-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-cufft-9-0.\n    Preparing to unpack .../13-cuda-cufft-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-cufft-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-cufft-dev-9-0.\n    Preparing to unpack .../14-cuda-cufft-dev-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-cufft-dev-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-curand-9-0.\n    Preparing to unpack .../15-cuda-curand-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-curand-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-curand-dev-9-0.\n    Preparing to unpack .../16-cuda-curand-dev-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-curand-dev-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-cusparse-9-0.\n    Preparing to unpack .../17-cuda-cusparse-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-cusparse-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-cusparse-dev-9-0.\n    Preparing to unpack .../18-cuda-cusparse-dev-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-cusparse-dev-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-npp-9-0.\n    Preparing to unpack .../19-cuda-npp-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-npp-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-npp-dev-9-0.\n    Preparing to unpack .../20-cuda-npp-dev-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-npp-dev-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-nvgraph-9-0.\n    Preparing to unpack .../21-cuda-nvgraph-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-nvgraph-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-nvgraph-dev-9-0.\n    Preparing to unpack .../22-cuda-nvgraph-dev-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-nvgraph-dev-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-samples-9-0.\n    Preparing to unpack .../23-cuda-samples-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-samples-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-documentation-9-0.\n    Preparing to unpack .../24-cuda-documentation-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-documentation-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-libraries-dev-9-0.\n    Preparing to unpack .../25-cuda-libraries-dev-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-libraries-dev-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-nvml-dev-9-0.\n    Preparing to unpack .../26-cuda-nvml-dev-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-nvml-dev-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-visual-tools-9-0.\n    Preparing to unpack .../27-cuda-visual-tools-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-visual-tools-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-toolkit-9-0.\n    Preparing to unpack .../28-cuda-toolkit-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-toolkit-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-libraries-9-0.\n    Preparing to unpack .../29-cuda-libraries-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-libraries-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-runtime-9-0.\n    Preparing to unpack .../30-cuda-runtime-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-runtime-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-demo-suite-9-0.\n    Preparing to unpack .../31-cuda-demo-suite-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-demo-suite-9-0 (9.0.176-1) ...\n    Selecting previously unselected package cuda-9-0.\n    Preparing to unpack .../32-cuda-9-0_9.0.176-1_amd64.deb ...\n    Unpacking cuda-9-0 (9.0.176-1) ...\n    Setting up cuda-license-9-0 (9.0.176-1) ...\n    *** LICENSE AGREEMENT ***\n    By using this software you agree to fully comply with the terms and \n    conditions of the EULA (End User License Agreement). The EULA is located\n    at /usr/local/cuda-9.0/doc/EULA.txt. The EULA can also be found at\n    http://docs.nvidia.com/cuda/eula/index.html. If you do not agree to the\n    terms and conditions of the EULA, do not use the software.\n    \n    Setting up cuda-cusparse-9-0 (9.0.176-1) ...\n    Setting up cuda-cudart-9-0 (9.0.176-1) ...\n    Setting up cuda-nvrtc-9-0 (9.0.176-1) ...\n    Setting up cuda-cusparse-dev-9-0 (9.0.176-1) ...\n    Setting up cuda-cufft-9-0 (9.0.176-1) ...\n    Setting up cuda-cusolver-9-0 (9.0.176-1) ...\n    Setting up cuda-nvml-dev-9-0 (9.0.176-1) ...\n    Setting up cuda-npp-9-0 (9.0.176-1) ...\n    Setting up cuda-cusolver-dev-9-0 (9.0.176-1) ...\n    Setting up cuda-misc-headers-9-0 (9.0.176-1) ...\n    Setting up cuda-cublas-9-0 (9.0.176-1) ...\n    Setting up cuda-nvrtc-dev-9-0 (9.0.176-1) ...\n    Setting up cuda-driver-dev-9-0 (9.0.176-1) ...\n    Setting up cuda-curand-9-0 (9.0.176-1) ...\n    Setting up cuda-nvgraph-9-0 (9.0.176-1) ...\n    Setting up cuda-core-9-0 (9.0.176-1) ...\n    Setting up cuda-libraries-9-0 (9.0.176-1) ...\n    Setting up cuda-runtime-9-0 (9.0.176-1) ...\n    Setting up cuda-cudart-dev-9-0 (9.0.176-1) ...\n    Setting up cuda-cufft-dev-9-0 (9.0.176-1) ...\n    Setting up cuda-npp-dev-9-0 (9.0.176-1) ...\n    Setting up cuda-curand-dev-9-0 (9.0.176-1) ...\n    Setting up cuda-cublas-dev-9-0 (9.0.176-1) ...\n    Setting up cuda-nvgraph-dev-9-0 (9.0.176-1) ...\n    Setting up cuda-command-line-tools-9-0 (9.0.176-1) ...\n    Setting up cuda-demo-suite-9-0 (9.0.176-1) ...\n    Setting up cuda-visual-tools-9-0 (9.0.176-1) ...\n    Setting up cuda-samples-9-0 (9.0.176-1) ...\n    Setting up cuda-libraries-dev-9-0 (9.0.176-1) ...\n    Setting up cuda-documentation-9-0 (9.0.176-1) ...\n    Setting up cuda-toolkit-9-0 (9.0.176-1) ...\n    Setting up cuda-9-0 (9.0.176-1) ...\n    Processing triggers for libc-bin (2.27-3ubuntu1) ...\n    /sbin/ldconfig.real: /usr/local/lib/python3.6/dist-packages/ideep4py/lib/libmkldnn.so.0 is not a symbolic link\n    \n\n\n# Training & Running it\n\nHere you download the model, several sizes available: 128M, 774M, 1558M\n\n\n```\n#  !python3 download_model.py 1558M\n!python3 download_model.py 774M\n```\n\n    Fetching checkpoint: 1.00kit [00:00, 834kit/s]                                                      \n    Fetching encoder.json: 1.04Mit [00:00, 50.7Mit/s]                                                   \n    Fetching hparams.json: 1.00kit [00:00, 663kit/s]                                                    \n    Fetching model.ckpt.data-00000-of-00001: 3.10Git [01:23, 37.3Mit/s]                                 \n    Fetching model.ckpt.index: 16.0kit [00:00, 9.74Mit/s]                                               \n    Fetching model.ckpt.meta: 1.38Mit [00:00, 52.4Mit/s]                                                \n    Fetching vocab.bpe: 457kit [00:00, 49.9Mit/s]                                                       \n\n\n## Training\n\nTo train, use the this. Some parameters you have to change:\n\n\n*   The pre-trained model (128M, etc.)\n*   The dataset file: a single big text file\n*   Batch size should be 1 for the biggest model on a TPU\n\n\n\n\n```\n# For training only \n# !PYTHONPATH=src python3 train.py  --model_name 774M --run_name \"run_large_critical_v2\" --dataset G1_ALL_v2.txt --batch_size 1 --save_every 100 --sample_every 50 --sample_num 1 --sample_length 500  --save_on_ctrlc --save_time 100 --max_to_keep 1 --learning_rate 0.00001   # --accumulate_gradients 2 # # --optimizer sgd #--memory_saving_gradients \n\n```\n\n## Inference\n\nNow, the code to actually run the model!\n\n\n```\nimport os\nimport sys\nimport fire\nimport json\nimport numpy as np\nimport tensorflow as tf\nimport tflex\n\nDIRNAM  E = \"/content/drive/My Drive/SLACKBOT/gpt-2/src\"\nsys.path.append(DIRNAME)\nprint(sys.path)\n\nimport model, sample, encoder\n\n\n```\n\n    WARNING:tensorflow:From /content/drive/My Drive/SLACKBOT/gpt-2/tflex.py:33: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead.\n    \n    WARNING:tensorflow:From /content/drive/My Drive/SLACKBOT/gpt-2/tflex.py:184: The name tf.train.SaverDef is deprecated. Please use tf.compat.v1.train.SaverDef instead.\n    \n    attach_debugger <function attach_debugger at 0x7faf9be55f28>\n    print_status <function print_status at 0x7faf9be581e0>\n    freeze_forever <function freeze_forever at 0x7faf9be580d0>\n    quit <function quit at 0x7faf9be58488>\n    save_and_quit <function save_and_quit at 0x7faf9be58378>\n    ['', '/env/python', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages', '/usr/local/lib/python3.6/dist-packages/IPython/extensions', '/root/.ipython', '/content/drive/My Drive/SLACKBOT/gpt-2/src']\n    WARNING:tensorflow:From /content/drive/My Drive/SLACKBOT/gpt-2/src/model.py:171: The name tf.AUTO_REUSE is deprecated. Please use tf.compat.v1.AUTO_REUSE instead.\n    \n\n\n\n```\ndef sample_model(\n    model_name='117M',\n    restore_from=None,\n    seed=None,\n    nsamples=0,\n    batch_size=1,\n    length=None,\n    temperature=1,\n    top_k=0,\n    top_p=0.0,\n    penalize=0\n):\n    \"\"\"\n    Run the sample_model\n    :model_name=117M : String, which model to use\n    :seed=None : Integer seed for random number generators, fix seed to\n     reproduce results\n    :nsamples=0 : Number of samples to return, if 0, continues to\n     generate samples indefinately.\n    :batch_size=1 : Number of batches (only affects speed/memory).\n    :length=None : Number of tokens in generated text, if None (default), is\n     determined by model hyperparameters\n    :temperature=1 : Float value controlling randomness in boltzmann\n     distribution. Lower temperature results in less random completions. As the\n     temperature approaches zero, the model will become deterministic and\n     repetitive. Higher temperature results in more random completions.\n    :top_k=0 : Integer value controlling diversity. 1 means only 1 word is\n     considered for each step (token), resulting in deterministic completions,\n     while 40 means 40 words are considered at each step. 0 (default) is a\n     special setting meaning no restrictions. 40 generally is a good value.\n    :top_p=0.0 : Float value controlling diversity. Implements nucleus sampling,\n     overriding top_k if set to a value > 0. A good setting is 0.9.\n    :penalize=0.0 : Float value controlling \"used\" penalty. Implements repetition\n     reduction (similar to CTRL) if set to a value > 0. A decent setting might be 0.85\n     with temperature 0.3 and top_k 40.\n    \"\"\"\n    enc = encoder.get_encoder(model_name)\n    hparams = model.default_hparams()\n    with open(os.path.join('models', model_name, 'hparams.json')) as f:\n        hparams.override_from_dict(json.load(f))\n\n    if length is None:\n        length = hparams.n_ctx\n    elif length > hparams.n_ctx:\n        raise ValueError(\"Can't get samples longer than window size: %s\" % hparams.n_ctx)\n\n    with tflex.Session(graph=tf.Graph()) as sess:\n        np.random.seed(seed)\n        tf.set_random_seed(seed)\n\n        output = sample.sample_sequence(\n            hparams=hparams, length=length,\n            start_token=enc.encoder['<|endoftext|>'],\n            batch_size=batch_size,\n            temperature=temperature, top_k=top_k, top_p=top_p, penalize=penalize\n        )[:, 1:]\n\n        saver = tflex.Saver()\n        if restore_from is None:\n          restore_from = os.path.join('models', model_name)\n        ckpt = tflex.latest_checkpoint(restore_from)\n        saver.restore(sess, ckpt)\n\n        generated = 0\n        while nsamples == 0 or generated < nsamples:\n            out = sess.run(output)\n            for i in range(batch_size):\n                generated += 1\n                text = enc.decode(out[i])\n                print(\"=\" * 40 + \" SAMPLE \" + str(generated) + \" \" + \"=\" * 40)\n                print(text)\n\n\n\n\ndef interact_model(\n    model_name='117M',\n    restore_from=None,\n    seed=None,\n    nsamples=1,\n    batch_size=1,\n    length=None,\n    temperature=1,\n    top_k=0,\n    top_p=0.0,\n    penalize=0,\n    prompt=None\n):\n    \"\"\"\n    Interactively run the model\n    :model_name=117M : String, which model to use\n    :seed=None : Integer seed for random number generators, fix seed to reproduce\n     results\n    :nsamples=1 : Number of samples to return total\n    :batch_size=1 : Number of batches (only affects speed/memory).  Must divide nsamples.\n    :length=None : Number of tokens in generated text, if None (default), is\n     determined by model hyperparameters\n    :temperature=1 : Float value controlling randomness in boltzmann\n     distribution. Lower temperature results in less random completions. As the\n     temperature approaches zero, the model will become deterministic and\n     repetitive. Higher temperature results in more random completions.\n    :top_k=0 : Integer value controlling diversity. 1 means only 1 word is\n     considered for each step (token), resulting in deterministic completions,\n     while 40 means 40 words are considered at each step. 0 (default) is a\n     special setting meaning no restrictions. 40 generally is a good value.\n    :top_p=0.0 : Float value controlling diversity. Implements nucleus sampling,\n     overriding top_k if set to a value > 0. A good setting is 0.9.\n    :penalize=0.0 : Float value controlling \"used\" penalty. Implements repetition\n     reduction (similar to CTRL) if set to a value > 0. A decent setting might be 0.85\n     with temperature 0.3 and top_k 40.\n    \"\"\"\n    if batch_size is None:\n        batch_size = 1\n    assert nsamples % batch_size == 0\n\n    enc = encoder.get_encoder(model_name)\n    hparams = model.default_hparams()\n    with open(os.path.join('models', model_name, 'hparams.json')) as f:\n        hparams.override_from_dict(json.load(f))\n\n    if length is None:\n        length = hparams.n_ctx // 2\n    elif length > hparams.n_ctx:\n        raise ValueError(\"Can't get samples longer than window size: %s\" % hparams.n_ctx)\n\n    with tflex.Session(graph=tf.Graph()) as sess:\n        context = tf.placeholder(tf.int32, [batch_size, None])\n        np.random.seed(seed)\n        tf.set_random_seed(seed)\n        output = sample.sample_sequence(\n            hparams=hparams, length=length,\n            context=context,\n            batch_size=batch_size,\n            temperature=temperature, top_k=top_k, top_p=top_p, penalize=penalize\n        )\n\n        saver = tflex.Saver()\n        if restore_from is None:\n          restore_from = os.path.join('models', model_name)\n        ckpt = tflex.latest_checkpoint(restore_from)\n        saver.restore(sess, ckpt)\n\n        while True:\n            if prompt is not None:\n              if os.path.isfile(prompt):\n                  with open(prompt) as f:\n                      raw_text = f.read()\n              else:\n                  raw_text = prompt\n            else:\n                raw_text = input(\"Model prompt >>> \")\n                if not raw_text:\n                    raw_text=\"\\n\"\n            if len(raw_text) > 1 and raw_text.endswith('\\n'):\n                raw_text = raw_text[:-1]\n            print('Prompt:', repr(raw_text))\n            context_tokens = enc.encode(raw_text)\n            generated = 0\n            for _ in range(nsamples // batch_size):\n                out = sess.run(output, feed_dict={\n                    context: [context_tokens for _ in range(batch_size)]\n                })[:, len(context_tokens):]\n                for i in range(batch_size):\n                    generated += 1\n                    text = enc.decode(out[i])\n                    print(\"=\" * 40 + \" SAMPLE \" + str(generated) + \" \" + \"=\" * 40)\n                    sys.stdout.write(raw_text)\n                    print(text)\n                    sys.stdout.flush()\n            print(\"=\" * 80)\n```\n\n\n```\nsample_model(top_k=40, temperature=0.4, penalize=0.85, model_name=\"774M\", nsamples=2)\n```\n\n    WARNING:tensorflow:From /content/drive/My Drive/SLACKBOT/gpt-2/src/model.py:173: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n    \n    WARNING:tensorflow:From /content/drive/My Drive/SLACKBOT/gpt-2/src/model.py:20: The name tf.get_variable_scope is deprecated. Please use tf.compat.v1.get_variable_scope instead.\n    \n    WARNING:tensorflow:From /content/drive/My Drive/SLACKBOT/gpt-2/src/model.py:21: The name tf.trainable_variables is deprecated. Please use tf.compat.v1.trainable_variables instead.\n    \n    WARNING:tensorflow:From /content/drive/My Drive/SLACKBOT/gpt-2/src/model.py:177: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n    \n    WARNING:tensorflow:From /content/drive/My Drive/SLACKBOT/gpt-2/src/model.py:178: calling RandomNormal.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Call initializer instance with the dtype argument instead of passing it to the constructor\n    WARNING:tensorflow:From /content/drive/My Drive/SLACKBOT/gpt-2/src/model.py:45: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Call initializer instance with the dtype argument instead of passing it to the constructor\n    WARNING:tensorflow:From /content/drive/My Drive/SLACKBOT/gpt-2/src/model.py:49: The name tf.rsqrt is deprecated. Please use tf.math.rsqrt instead.\n    \n    WARNING:tensorflow:From /content/drive/My Drive/SLACKBOT/gpt-2/src/model.py:191: The name tf.add_to_collection is deprecated. Please use tf.compat.v1.add_to_collection instead.\n    \n    WARNING:tensorflow:From /content/drive/My Drive/SLACKBOT/gpt-2/src/sample.py:81: to_float (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    WARNING:tensorflow:From /content/drive/My Drive/SLACKBOT/gpt-2/src/sample.py:17: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use tf.where in 2.0, which has the same broadcast rule as np.where\n    WARNING:tensorflow:From /content/drive/My Drive/SLACKBOT/gpt-2/src/sample.py:88: multinomial (from tensorflow.python.ops.random_ops) is deprecated and will be removed in a future version.\n    Instructions for updating:\n    Use `tf.random.categorical` instead.\n\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4/4 [00:49<00:00, 12.28s/it]\n\n\n    ======================================== SAMPLE 1 ========================================\n    The following is a list of items that make good gifts for Tia, who likes Sporty, white items and dislikes Cute/Fancy items.\n    \n    Best Gifts for Tia: Sporty, white items\n    \n    The following items have Tia's favorite style and color.\n    \n    Name Type Name Color 1 Color 2 tank top yellow white blue tartan shirt top aqua white blue tartan tee top aqua white blue-grid shirt top aqua white blue-grid tee top aqua white bubble tank top colorful white bubble tee top colorful white bunny shirt top aqua white bunny tee top aqua white chevron shirt top red white chevron tee top red white cyan argyle shirt top aqua gray cyan argyle tee top aqua gray dapper shirt top orange white dapper tee top orange white dogtooth shirt top gray black dogtooth tee top gray black dragon jacket top purple white elephant shirt top blue pink elephant tee top blue pink floral knit tee top green white flowery tee top pink white frog costume top green white frog shirt top green beige frog tee top green beige genie shirt top aqua white genie vest top aqua white giraffe tank top yellow brown giraffe tee top yellow brown jagged tank top yellow aqua jagged tee top yellow aqua kiwi tank top yellow green kiwi tee top yellow green lemon gingham shirt top yellow white lemon gingham tee top yellow white melon gingham shirt top yellow white melon gingham tee top yellow white morning glory furniture green white morning glory sign furniture green white paper tiger furniture yellow white peachy tank top yellow green peachy tee top yellow green picnic basket furniture green white pine bonsai furniture green white pikmin furniture green white pinball machine furniture colorful white raccoon figurine furniture colorful white red-tasseled lantern furniture red white rose sofa furniture red red round clock furniture red white robo-bed furniture blue white robo-chair furniture blue white robo-clock furniture blue white robo-closet furniture blue white robo-dresser furniture blue white robo-lamp furniture blue white robo-sofa furniture blue white robo-stereo furniture blue white robo-table furniture blue white robo-tv furniture blue white sand castle furniture red brown snowman bed furniture white white snowman bookcase furniture white white snowman chair furniture white white snowman closet furniture white white snowman dresser furniture white white snowman lamp furniture white white snowman low table furniture white white snowman shelf furniture white white snowman sofa furniture white white snowman table furniture white white snowman vanity furniture white white snowman wall clock furniture white white snowman wardrobe furniture white white sphinx furniture yellow brown striped cone furniture yellow none sunflower stereo furniture yellow none super mushroom furniture red colorful tall cactus furniture green white tall mini cactus furniture green white tiki torch furniture red white toadstool furniture green white tricycle furniture yellow white tulip dresser furniture yellow green virtual boy furniture red white wall flowerpot furniture yellow green watermelon chair furniture green red watermelon table furniture green red yoshi's egg furniture green white zodiac boar furniture blue white zodiac goat furniture red white zodiac ox furniture red white zodiac rabbit furniture red white zodiac rat furniture red white zodiac snake furniture yellow white zodiac tiger furniture yellow white bamboo grass furniture green colorful candy cane furniture sweet white candy canes furniture brown white cucumber horse furniture green colorful dab table furniture brown brown festive candle furniture red colorful festive flag furniture red colorful fire hydrant furniture red red florence flask furniture red red folk guitar furniture brown brown game-show stand furniture green white giant dharma furniture red red harpsichord furniture yellow brown hibiscus clock furniture green red hydrangea bed furniture red red hydrangea bench furniture red red hydrangea chair furniture red red hydrangea clock furniture red red hydrangea dresser furniture red red hydrangea lamp furniture red red hydrangea screen furniture red red hydrangea stool furniture red red hydrangea table furniture red red ice bed furniture aqua aqua ice chair furniture aqua aqua ice clock furniture aqua aqua ice closet furniture aqua aqua ice dresser furniture aqua aqua ice lamp furniture red aqua ice side table furniture aqua aqua ice sofa furniture aqua aqua ice table furniture aqua aqua ice tv furniture red black jackhammer furniture red red jellyfish aquarium furniture gray gray keg furniture red red ladybug chair furniture red red lovely doll furniture red red lucky cat furniture red red lunar lander furniture blue aqua moon furniture gray gray mama bear furniture red colorful mush bed furniture aqua white mush chair furniture aqua white mush clock furniture aqua white mush end table furniture aqua white mush lamp furniture aqua white mush sofa furniture aqua white mush table furniture aqua white mush tv furniture red white old sewing machine furniture white white pansy table furniture colorful brown papa bear\n    ======================================== SAMPLE 2 ========================================\n    The following is a list of items that make good gifts for Stacey, who likes Sporty, blue items and dislikes Ornate items.\n    \n    Best Gifts for Stacey: Sporty, blue items\n    \n    The following items have Stacey's favorite style and color.\n    \n    Name Type Name Color 1 Color 2 blue tartan tee top blue gray blue-grid shirt top aqua white blue-stripe tank top yellow blue blue-zap suit top blue aqua bubble tank top pink purple butterfly tank top colorful white candy gingham shirt top green red coral tank top yellow blue crab boat furniture blue brown dapper dresser furniture blue gray dragon furniture blue black elephant slide furniture yellow blue flame bed furniture orange blue glass display case furniture colorful white globe furniture aqua white gold house model furniture yellow blue gracie bed furniture blue beige grapefruit table furniture green red heart stereo furniture yellow blue hibiscus clock furniture green red ice lamp furniture aqua aqua jasmine bonsai furniture green red king furniture brown brown lady palm furniture green red maple bonsai furniture red red mountain bike furniture yellow blue mochi pestle furniture brown brown octopus chair furniture blue blue pachira furniture red brown pagoda furniture red brown picnic basket furniture blue brown potbelly stove furniture yellow blue pine bonsai furniture green red pop-up book furniture red black princess bed furniture aqua aqua princess cage furniture pink pink robo-bed furniture blue white robo-chair furniture blue white robo-clock furniture blue white robo-closet furniture blue white robo-dresser furniture blue white robo-lamp furniture blue white robo-sofa furniture blue white robo-stereo furniture blue white robo-table furniture blue white robo-tv furniture blue white skeleton figurine furniture white white snow bunny furniture white white sloppy tv furniture brown brown spooky bed furniture red ghostly bed furniture orange white spooky bench furniture orange white spooky bureau furniture orange white spooky chair furniture orange white spooky chest furniture orange white spooky closet furniture orange white spooky dresser furniture orange white spooky lamp furniture orange white spooky sofa furniture orange white spooky table furniture orange white spooky vanity furniture orange white spooky wall lamp furniture orange white tall cactus furniture green blue tall flowerpot furniture green red tiki torch furniture red white toadstool furniture green red tricycle furniture yellow green ukulele furniture brown brown upright piano furniture green green zodiac boar furniture blue white zodiac goat furniture red white zodiac ox furniture red white zodiac rabbit furniture red white zodiac rat furniture red white zodiac snake furniture yellow white zodiac tiger furniture yellow white zodiac turkey furniture orange white zodiac wolf furniture orange white zodiac painting furniture white<|endoftext|>A few months ago I was asked by a friend if I would like to write an article on the \"why\" behind the success of the U.S. dollar in international trade. This question came from someone who had recently started talking about how the U.S. dollar has been outperforming other currencies since 2008. The answer to this question is not easy to explain without going into detail about what exactly it means to \"underperform.\" It might also seem counterintuitive to suggest that a currency with high purchasing power should perform well, but there are some very strong reasons why this is true.\n    \n    I am going to try to give you a brief overview of the most important factors that contribute to a country's ability to outperform its peers when it comes to foreign exchange markets. These factors will help explain why the United States has done so well in terms of trading with other countries over the past decade or two.\n    \n    1) A Strong Economy\n    \n    First, let's talk about the economy. When it comes to economic performance, we tend to think of the economy as being driven by GDP growth. However, the U.S. economy is actually more than just GDP. In fact, the U.S. government reports that the U.S. gross domestic product (GDP) accounts for only 20% of total U.S. exports. The rest of the value added goes towards services, which include everything from health care to education to transportation. So while GDP does account for a large portion of the overall output, it doesn't tell us all that much about how well a country performs relative to the rest of the world.\n    \n    Another way to look at the economy is through the lens of \"output per worker,\" which refers to the amount of goods and services produced by each individual worker. If we compare the average annual earnings of workers in the United States to those of workers in other major economies, we find that the U.S. labor market is quite competitive. For example, the median wage of a full-time, year-round employee in the United States is $26,000 per year. Compare that to the $21,500 earned by a similar worker in Japan, where the average worker earns $13,200 annually.\n    \n    2)\n\n\n\n```\ninteract_model(top_k=40, temperature=0.3, penalize=0.85, model_name=\"774M\", nsamples=2)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4/4 [00:07<00:00,  1.81s/it]\n\n\n    Model prompt >>> Razor. Definition: \n    Prompt: 'Razor. Definition: '\n    ======================================== SAMPLE 1 ========================================\n    Razor. Definition: \u00a0The term \" Razor \" is used to describe the blade of a knife, and refers to the sharpened edge on the blade.\n    Example: A razor blade is a sharpened blade that has been honed to a point where it can be used for cutting.\n    Definition: \u00a0A razor is a tool used to cut or shave hair.\n    Example: A razor is a tool used to cut or shave hair.\n    Definition: \u00a0A razor is a tool used to cut or shave hair.\n    Example: A razor is a tool used to cut or shave hair.\n    Definition: \u00a0A razor is a tool used to cut or shave hair.\n    Example: A razor is a tool used to cut or shave hair.\n    Definition: \u00a0A razor is a tool used to cut or shave hair.\n    Example: A razor is a tool used to cut or shave hair.\n    Definition: \u00a0A razor is a tool used to cut or shave hair.\n    Example: A razor is a tool used to cut or shave hair.\n    Definition: \u00a0A razor is a tool used to cut or shave hair.\n    Example: A razor is a tool used to cut or shave hair.\n    Definition: \u00a0A razor is a tool used to cut or shave hair.\n    Example: A razor is a tool used to cut or shave hair.\n    Definition: \u00a0A razor is a tool used to cut or shave hair.\n    Example: A razor is a tool used to cut or shave hair.\n    Definition: \u00a0A razor is a tool used to cut or shave hair.\n    Example: A razor is a tool used to cut or shave hair.\n    Definition: \u00a0A razor is a tool used to cut or shave hair.\n    Example: A razor is a tool used to cut or shave hair.\n    Definition: \u00a0A razor is a tool used to cut or shave hair.\n    Example: A razor is a tool used to cut or shave hair.\n    Definition: \u00a0A razor is a tool used to cut or shave hair.\n    Example: A razor is a tool used to cut or shave hair.\n    Definition: \u00a0A razor is a tool used to cut or shave hair.\n    Example: A razor is a tool used to cut or shave hair.\n    Definition: \u00a0A razor is a tool used to cut or shave hair.\n    Example: A razor is a tool used to cut or shave hair.\n    Definition: \u00a0A razor is a tool\n    ======================================== SAMPLE 2 ========================================\n    Razor. Definition: \u00a0\"A razor is a tool that cuts, or slices, a piece of meat.\"\n    The above definition was taken from the Wikipedia article on \"Razor\". I have not been able to find any reference to this definition in any other source. So what does it mean? Well, it means that a blade has two blades which are joined together by a sharp edge and are used for cutting meat. The first blade is called the \"blade\", and the second blade is called the \"razor\". This is the definition given in the Wikipedia article on \"Razor\":\n    \"A razor is a tool that cuts, or slices, a piece of meat. It consists of an inner and outer blade, with a sharpened edge between them. The blade may be made of metal, wood, or plastic. A razor can be used to cut through flesh, but typically only when the knife is held at a right angle to the body.\"\n    So, if you want to use a razor for slicing, you need to hold the knife at a right angle to your body. If you don't know how to do that, then here is some advice from my friend, Dr. David M. Bowers. He is a board-certified orthopedic surgeon who specializes in treating patients with injuries to their hands, feet, and lower extremities. Here is his advice on using a razor for cutting meat:\n    \"If you're going to use a razor for cutting meat, you should hold the knife at a right angle to your body. That way, when you slice, the blade will cut through the meat without tearing the skin off. You'll also be less likely to cause bleeding.\"\n    I hope this helps you understand the difference between a razor and a knife.<|endoftext|>By\n    \n    21st Century Wire says\u2026\n    \n    This is a very interesting development as it appears that the US government has now officially admitted that they were behind the attack on the Russian embassy in Washington DC over the weekend.\n    \n    According to reports, the US State Department has confirmed that the attack was carried out by a group calling itself the 'Islamic State' (IS).\n    \n    The report states that the attack was carried out by a group calling themselves the 'Islamic State', which is an acronym for 'Islamic State of Iraq and Syria'.\n    \n    It's worth noting that the name IS is often misused by many people, including those within the intelligence community, to refer to ISIS.\n    \n    However, the term IS has become synonymous with the terrorist group\n    ================================================================================\n\n", "meta": {"hexsha": "2dfb3e36ee821a6fdce17b76b3c623447c089624", "size": 90546, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "GPT_2_TPU_INFERENCE_TRAIN.ipynb", "max_stars_repo_name": "groar/gpt-2", "max_stars_repo_head_hexsha": "8e6aab3e7d7be60043dc247dd34403a08fb067d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GPT_2_TPU_INFERENCE_TRAIN.ipynb", "max_issues_repo_name": "groar/gpt-2", "max_issues_repo_head_hexsha": "8e6aab3e7d7be60043dc247dd34403a08fb067d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GPT_2_TPU_INFERENCE_TRAIN.ipynb", "max_forks_repo_name": "groar/gpt-2", "max_forks_repo_head_hexsha": "8e6aab3e7d7be60043dc247dd34403a08fb067d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 72.5528846154, "max_line_length": 4875, "alphanum_fraction": 0.6091158085, "converted": true, "num_tokens": 22102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06754669489377624, "lm_q2_score": 0.02976009512918625, "lm_q1q2_score": 0.0020101960657008997}}
{"text": "```python\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```python\n!pip install mxnet\n!pip install gluonnlp pandas tqdm\n!pip install sentencepiece\n!pip install transformers==3.0.2\n!pip install torch\n```\n\n    Collecting mxnet\n      Downloading mxnet-1.9.0-py3-none-manylinux2014_x86_64.whl (47.3 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 47.3 MB 1.5 MB/s \n    \u001b[?25hRequirement already satisfied: numpy<2.0.0,>1.16.0 in /usr/local/lib/python3.7/dist-packages (from mxnet) (1.21.5)\n    Collecting graphviz<0.9.0,>=0.8.1\n      Downloading graphviz-0.8.4-py2.py3-none-any.whl (16 kB)\n    Requirement already satisfied: requests<3,>=2.20.0 in /usr/local/lib/python3.7/dist-packages (from mxnet) (2.23.0)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.20.0->mxnet) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.20.0->mxnet) (2021.10.8)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.20.0->mxnet) (3.0.4)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.20.0->mxnet) (1.24.3)\n    Installing collected packages: graphviz, mxnet\n      Attempting uninstall: graphviz\n        Found existing installation: graphviz 0.10.1\n        Uninstalling graphviz-0.10.1:\n          Successfully uninstalled graphviz-0.10.1\n    Successfully installed graphviz-0.8.4 mxnet-1.9.0\n    Collecting gluonnlp\n      Downloading gluonnlp-0.10.0.tar.gz (344 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 344 kB 12.3 MB/s \n    \u001b[?25hRequirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (1.3.5)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (4.63.0)\n    Requirement already satisfied: numpy>=1.16.0 in /usr/local/lib/python3.7/dist-packages (from gluonnlp) (1.21.5)\n    Requirement already satisfied: cython in /usr/local/lib/python3.7/dist-packages (from gluonnlp) (0.29.28)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from gluonnlp) (21.3)\n    Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas) (2018.9)\n    Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas) (2.8.2)\n    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas) (1.15.0)\n    Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->gluonnlp) (3.0.7)\n    Building wheels for collected packages: gluonnlp\n      Building wheel for gluonnlp (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for gluonnlp: filename=gluonnlp-0.10.0-cp37-cp37m-linux_x86_64.whl size=595749 sha256=ce6409fe84042d544c13cb658f1ccbe735b6cb81708f98775acac7aeb7abf9a0\n      Stored in directory: /root/.cache/pip/wheels/be/b4/06/7f3fdfaf707e6b5e98b79c041e023acffbe395d78a527eae00\n    Successfully built gluonnlp\n    Installing collected packages: gluonnlp\n    Successfully installed gluonnlp-0.10.0\n    Collecting sentencepiece\n      Downloading sentencepiece-0.1.96-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.2 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.2 MB 13.7 MB/s \n    \u001b[?25hInstalling collected packages: sentencepiece\n    Successfully installed sentencepiece-0.1.96\n    Collecting transformers==3.0.2\n      Downloading transformers-3.0.2-py3-none-any.whl (769 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 769 kB 12.2 MB/s \n    \u001b[?25hCollecting sacremoses\n      Downloading sacremoses-0.0.49-py3-none-any.whl (895 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 895 kB 42.9 MB/s \n    \u001b[?25hRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from transformers==3.0.2) (2.23.0)\n    Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.7/dist-packages (from transformers==3.0.2) (4.63.0)\n    Collecting tokenizers==0.8.1.rc1\n      Downloading tokenizers-0.8.1rc1-cp37-cp37m-manylinux1_x86_64.whl (3.0 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.0 MB 44.1 MB/s \n    \u001b[?25hRequirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.7/dist-packages (from transformers==3.0.2) (2019.12.20)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from transformers==3.0.2) (21.3)\n    Requirement already satisfied: filelock in /usr/local/lib/python3.7/dist-packages (from transformers==3.0.2) (3.6.0)\n    Requirement already satisfied: sentencepiece!=0.1.92 in /usr/local/lib/python3.7/dist-packages (from transformers==3.0.2) (0.1.96)\n    Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from transformers==3.0.2) (1.21.5)\n    Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->transformers==3.0.2) (3.0.7)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->transformers==3.0.2) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->transformers==3.0.2) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->transformers==3.0.2) (2021.10.8)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->transformers==3.0.2) (1.24.3)\n    Requirement already satisfied: joblib in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers==3.0.2) (1.1.0)\n    Requirement already satisfied: click in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers==3.0.2) (7.1.2)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers==3.0.2) (1.15.0)\n    Installing collected packages: tokenizers, sacremoses, transformers\n    Successfully installed sacremoses-0.0.49 tokenizers-0.8.1rc1 transformers-3.0.2\n    Requirement already satisfied: torch in /usr/local/lib/python3.7/dist-packages (1.10.0+cu111)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch) (3.10.0.2)\n\n\n\n```python\n!pip install qiskit\n```\n\n    Collecting qiskit\n      Downloading qiskit-0.35.0.tar.gz (13 kB)\n    Collecting qiskit-terra==0.20.0\n      Downloading qiskit_terra-0.20.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (6.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.5 MB 8.6 MB/s \n    \u001b[?25hCollecting qiskit-aer==0.10.3\n      Downloading qiskit_aer-0.10.3-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (18.0 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 18.0 MB 104 kB/s \n    \u001b[?25hCollecting qiskit-ibmq-provider==0.18.3\n      Downloading qiskit_ibmq_provider-0.18.3-py3-none-any.whl (238 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 238 kB 49.2 MB/s \n    \u001b[?25hCollecting qiskit-ignis==0.7.0\n      Downloading qiskit_ignis-0.7.0-py3-none-any.whl (200 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 200 kB 50.2 MB/s \n    \u001b[?25hRequirement already satisfied: scipy>=1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.10.3->qiskit) (1.4.1)\n    Requirement already satisfied: numpy>=1.16.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.10.3->qiskit) (1.21.5)\n    Collecting requests-ntlm>=1.1.0\n      Downloading requests_ntlm-1.1.0-py2.py3-none-any.whl (5.7 kB)\n    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (2.8.2)\n    Collecting websocket-client>=1.0.1\n      Downloading websocket_client-1.3.2-py3-none-any.whl (54 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 54 kB 2.9 MB/s \n    \u001b[?25hRequirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (1.24.3)\n    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (2.23.0)\n    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ignis==0.7.0->qiskit) (57.4.0)\n    Collecting retworkx>=0.8.0\n      Downloading retworkx-0.11.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.6 MB 43.2 MB/s \n    \u001b[?25hCollecting python-constraint>=1.4\n      Downloading python-constraint-1.4.0.tar.bz2 (18 kB)\n    Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.20.0->qiskit) (1.7.1)\n    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.20.0->qiskit) (0.3.4)\n    Collecting tweedledum<2.0,>=1.1\n      Downloading tweedledum-1.1.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (943 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 943 kB 29.7 MB/s \n    \u001b[?25hRequirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.20.0->qiskit) (5.4.8)\n    Collecting ply>=3.10\n      Downloading ply-3.11-py2.py3-none-any.whl (49 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 49 kB 2.9 MB/s \n    \u001b[?25hCollecting stevedore>=3.0.0\n      Downloading stevedore-3.5.0-py3-none-any.whl (49 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 49 kB 3.0 MB/s \n    \u001b[?25hCollecting scipy>=1.0\n      Downloading scipy-1.7.3-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (38.1 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 38.1 MB 1.4 MB/s \n    \u001b[?25hCollecting symengine>=0.9\n      Downloading symengine-0.9.2-cp37-cp37m-manylinux2010_x86_64.whl (37.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 37.5 MB 1.4 MB/s \n    \u001b[?25hRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.8.0->qiskit-ibmq-provider==0.18.3->qiskit) (1.15.0)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit) (2021.10.8)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit) (3.0.4)\n    Collecting ntlm-auth>=1.0.2\n      Downloading ntlm_auth-1.5.0-py2.py3-none-any.whl (29 kB)\n    Collecting cryptography>=1.3\n      Downloading cryptography-36.0.2-cp36-abi3-manylinux_2_24_x86_64.whl (3.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.6 MB 38.2 MB/s \n    \u001b[?25hRequirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit) (1.15.0)\n    Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit) (2.21)\n    Collecting pbr!=2.1.0,>=2.0.0\n      Downloading pbr-5.8.1-py2.py3-none-any.whl (113 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 113 kB 22.8 MB/s \n    \u001b[?25hRequirement already satisfied: importlib-metadata>=1.7.0 in /usr/local/lib/python3.7/dist-packages (from stevedore>=3.0.0->qiskit-terra==0.20.0->qiskit) (4.11.3)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=1.7.0->stevedore>=3.0.0->qiskit-terra==0.20.0->qiskit) (3.7.0)\n    Requirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=1.7.0->stevedore>=3.0.0->qiskit-terra==0.20.0->qiskit) (3.10.0.2)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra==0.20.0->qiskit) (1.2.1)\n    Building wheels for collected packages: qiskit, python-constraint\n      Building wheel for qiskit (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for qiskit: filename=qiskit-0.35.0-py3-none-any.whl size=11839 sha256=f4385a5ea13e3fc3df708e0121b776f9fa21a37c2ca7eef558a0b98a87fe3598\n      Stored in directory: /root/.cache/pip/wheels/1e/0a/42/93e5cc11795fb0a85fcf6686eac2791def0c9a1cad0a774045\n      Building wheel for python-constraint (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for python-constraint: filename=python_constraint-1.4.0-py2.py3-none-any.whl size=24081 sha256=f63e7f88111c123f80962e469c9d47830d5cdef9b0122ccfc273df0f57e17226\n      Stored in directory: /root/.cache/pip/wheels/07/27/db/1222c80eb1e431f3d2199c12569cb1cac60f562a451fe30479\n    Successfully built qiskit python-constraint\n    Installing collected packages: pbr, tweedledum, symengine, stevedore, scipy, retworkx, python-constraint, ply, ntlm-auth, cryptography, websocket-client, requests-ntlm, qiskit-terra, qiskit-ignis, qiskit-ibmq-provider, qiskit-aer, qiskit\n      Attempting uninstall: scipy\n        Found existing installation: scipy 1.4.1\n        Uninstalling scipy-1.4.1:\n          Successfully uninstalled scipy-1.4.1\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\n    Successfully installed cryptography-36.0.2 ntlm-auth-1.5.0 pbr-5.8.1 ply-3.11 python-constraint-1.4.0 qiskit-0.35.0 qiskit-aer-0.10.3 qiskit-ibmq-provider-0.18.3 qiskit-ignis-0.7.0 qiskit-terra-0.20.0 requests-ntlm-1.1.0 retworkx-0.11.0 scipy-1.7.3 stevedore-3.5.0 symengine-0.9.2 tweedledum-1.1.1 websocket-client-1.3.2\n\n\n\n```python\n!pip install git+https://git@github.com/SKTBrain/KoBERT.git@master\n```\n\n    Collecting git+https://****@github.com/SKTBrain/KoBERT.git@master\n      Cloning https://****@github.com/SKTBrain/KoBERT.git (to revision master) to /tmp/pip-req-build-zwftujnp\n      Running command git clone -q 'https://****@github.com/SKTBrain/KoBERT.git' /tmp/pip-req-build-zwftujnp\n    Collecting boto3\n      Downloading boto3-1.21.34-py3-none-any.whl (132 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 132 kB 10.5 MB/s \n    \u001b[?25hRequirement already satisfied: gluonnlp>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from kobert==0.2.3) (0.10.0)\n    Requirement already satisfied: mxnet>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from kobert==0.2.3) (1.9.0)\n    Collecting onnxruntime==1.8.0\n      Downloading onnxruntime-1.8.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4.5 MB 22.5 MB/s \n    \u001b[?25hRequirement already satisfied: sentencepiece>=0.1.6 in /usr/local/lib/python3.7/dist-packages (from kobert==0.2.3) (0.1.96)\n    Requirement already satisfied: torch>=1.7.0 in /usr/local/lib/python3.7/dist-packages (from kobert==0.2.3) (1.10.0+cu111)\n    Collecting transformers>=4.8.1\n      Downloading transformers-4.17.0-py3-none-any.whl (3.8 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 3.8 MB 41.8 MB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.16.6 in /usr/local/lib/python3.7/dist-packages (from onnxruntime==1.8.0->kobert==0.2.3) (1.21.5)\n    Requirement already satisfied: flatbuffers in /usr/local/lib/python3.7/dist-packages (from onnxruntime==1.8.0->kobert==0.2.3) (2.0)\n    Requirement already satisfied: protobuf in /usr/local/lib/python3.7/dist-packages (from onnxruntime==1.8.0->kobert==0.2.3) (3.17.3)\n    Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from gluonnlp>=0.6.0->kobert==0.2.3) (21.3)\n    Requirement already satisfied: cython in /usr/local/lib/python3.7/dist-packages (from gluonnlp>=0.6.0->kobert==0.2.3) (0.29.28)\n    Requirement already satisfied: graphviz<0.9.0,>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from mxnet>=1.4.0->kobert==0.2.3) (0.8.4)\n    Requirement already satisfied: requests<3,>=2.20.0 in /usr/local/lib/python3.7/dist-packages (from mxnet>=1.4.0->kobert==0.2.3) (2.23.0)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.20.0->mxnet>=1.4.0->kobert==0.2.3) (3.0.4)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.20.0->mxnet>=1.4.0->kobert==0.2.3) (2.10)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.20.0->mxnet>=1.4.0->kobert==0.2.3) (1.24.3)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.20.0->mxnet>=1.4.0->kobert==0.2.3) (2021.10.8)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch>=1.7.0->kobert==0.2.3) (3.10.0.2)\n    Requirement already satisfied: filelock in /usr/local/lib/python3.7/dist-packages (from transformers>=4.8.1->kobert==0.2.3) (3.6.0)\n    Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.7/dist-packages (from transformers>=4.8.1->kobert==0.2.3) (2019.12.20)\n    Requirement already satisfied: sacremoses in /usr/local/lib/python3.7/dist-packages (from transformers>=4.8.1->kobert==0.2.3) (0.0.49)\n    Collecting tokenizers!=0.11.3,>=0.11.1\n      Downloading tokenizers-0.11.6-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (6.5 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 6.5 MB 42.4 MB/s \n    \u001b[?25hRequirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from transformers>=4.8.1->kobert==0.2.3) (4.11.3)\n    Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.7/dist-packages (from transformers>=4.8.1->kobert==0.2.3) (4.63.0)\n    Collecting pyyaml>=5.1\n      Downloading PyYAML-6.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (596 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 596 kB 37.6 MB/s \n    \u001b[?25hCollecting huggingface-hub<1.0,>=0.1.0\n      Downloading huggingface_hub-0.5.0-py3-none-any.whl (77 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 77 kB 5.5 MB/s \n    \u001b[?25hRequirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->gluonnlp>=0.6.0->kobert==0.2.3) (3.0.7)\n    Collecting botocore<1.25.0,>=1.24.34\n      Downloading botocore-1.24.34-py3-none-any.whl (8.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 8.6 MB 42.7 MB/s \n    \u001b[?25hCollecting jmespath<2.0.0,>=0.7.1\n      Downloading jmespath-1.0.0-py3-none-any.whl (23 kB)\n    Collecting s3transfer<0.6.0,>=0.5.0\n      Downloading s3transfer-0.5.2-py3-none-any.whl (79 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 79 kB 7.3 MB/s \n    \u001b[?25hRequirement already satisfied: python-dateutil<3.0.0,>=2.1 in /usr/local/lib/python3.7/dist-packages (from botocore<1.25.0,>=1.24.34->boto3->kobert==0.2.3) (2.8.2)\n    Collecting urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1\n      Downloading urllib3-1.25.11-py2.py3-none-any.whl (127 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 127 kB 37.4 MB/s \n    \u001b[?25hRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil<3.0.0,>=2.1->botocore<1.25.0,>=1.24.34->boto3->kobert==0.2.3) (1.15.0)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->transformers>=4.8.1->kobert==0.2.3) (3.7.0)\n    Requirement already satisfied: click in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers>=4.8.1->kobert==0.2.3) (7.1.2)\n    Requirement already satisfied: joblib in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers>=4.8.1->kobert==0.2.3) (1.1.0)\n    Building wheels for collected packages: kobert\n      Building wheel for kobert (setup.py) ... \u001b[?25l\u001b[?25hdone\n      Created wheel for kobert: filename=kobert-0.2.3-py3-none-any.whl size=15674 sha256=1dc5ccab6cafb52a6d38cd377fae61a8014eec116b7b0df78d76683c26a8f46d\n      Stored in directory: /tmp/pip-ephem-wheel-cache-v8_imh2a/wheels/d3/68/ca/334747dfb038313b49cf71f84832a33372f3470d9ddfd051c0\n    Successfully built kobert\n    Installing collected packages: urllib3, jmespath, pyyaml, botocore, tokenizers, s3transfer, huggingface-hub, transformers, onnxruntime, boto3, kobert\n      Attempting uninstall: urllib3\n        Found existing installation: urllib3 1.24.3\n        Uninstalling urllib3-1.24.3:\n          Successfully uninstalled urllib3-1.24.3\n      Attempting uninstall: pyyaml\n        Found existing installation: PyYAML 3.13\n        Uninstalling PyYAML-3.13:\n          Successfully uninstalled PyYAML-3.13\n      Attempting uninstall: tokenizers\n        Found existing installation: tokenizers 0.8.1rc1\n        Uninstalling tokenizers-0.8.1rc1:\n          Successfully uninstalled tokenizers-0.8.1rc1\n      Attempting uninstall: transformers\n        Found existing installation: transformers 3.0.2\n        Uninstalling transformers-3.0.2:\n          Successfully uninstalled transformers-3.0.2\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    datascience 0.10.6 requires folium==0.2.1, but you have folium 0.8.3 which is incompatible.\u001b[0m\n    Successfully installed boto3-1.21.34 botocore-1.24.34 huggingface-hub-0.5.0 jmespath-1.0.0 kobert-0.2.3 onnxruntime-1.8.0 pyyaml-6.0 s3transfer-0.5.2 tokenizers-0.11.6 transformers-4.17.0 urllib3-1.25.11\n\n\n\n```python\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import Dataset, DataLoader\nimport gluonnlp as nlp\nimport numpy as np\nfrom tqdm import tqdm, tqdm_notebook\n```\n\n\n```python\nfrom kobert.utils import get_tokenizer\nfrom kobert.pytorch_kobert import get_pytorch_kobert_model\n```\n\n\n```python\nfrom transformers import AdamW\nfrom transformers.optimization import get_cosine_schedule_with_warmup\n```\n\n\n```python\n# pytorch \uc5d0\uc11c gpu \uc0ac\uc6a9 \uc120\ud0dd (0\ubc88 \uc544\uc774\ub514\ub97c \uac00\uc9c4 gpu\ub97c \uc0ac\uc6a9)\ndevice = torch.device(\"cuda:0\") \n```\n\n\n```python\n# \uc0ac\uc804 \ud6c8\ub828\ub41c kobert model \ubd88\ub7ec\uc634\nbertmodel, vocab = get_pytorch_kobert_model()\n```\n\n    /content/.cache/kobert_v1.zip[\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588]\n    /content/.cache/kobert_news_wiki_ko_cased-1087f8699e.spiece[\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588]\n\n\n\n```python\n# \uad6c\uae00 \ub4dc\ub77c\uc774\ube0c\uc5d0\uc11c \ud559\uc2b5\uc2dc\ud0ac \ub370\uc774\ud130 \uc14b \uac00\uc838\uc624\uae30\n# /content/drive/MyDrive/ == \uae30\ubcf8 \uacbd\ub85c\nimport pandas as pd\nsentences = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/jejuRecommand/data/sentences.csv')\n```\n\n\n```python\n# \ub370\uc774\ud130 \uc14b \ud06c\uae30 \ud655\uc778\nlen(sentences)\n```\n\n\n\n\n    10127878\n\n\n\n\n```python\nsentences.head()\n```\n\n\n\n\n\n  <div id=\"df-e2a0388f-645a-4bca-a4f0-503fee387704\">\n    <div class=\"colab-df-container\">\n      <div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Unnamed: 0</th>\n      <th>source</th>\n      <th>content</th>\n      <th>postdate</th>\n      <th>platform</th>\n      <th>target</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0</td>\n      <td>\ud734\uc560\ub9ac \uc790\uc5f0\uc0dd\ud65c\uacf5\uc6d0</td>\n      <td>\uc5b8\ub2c8 \ud3c9\uc18c \uac00\ubcf4\uace0 \uc2f6\uc5b4 \ud558\ub358 \ud734\uc560\ub9ac \ucd95\uc81c \ub2e4\ub140\uc654\uc5b4\uc694</td>\n      <td>20211217</td>\n      <td>naver</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>\ud734\uc560\ub9ac \uc790\uc5f0\uc0dd\ud65c\uacf5\uc6d0</td>\n      <td>\uc9c0\uae08 \ud55c\ucc38 \ub9cc\ubc1c \ud574\uc11c \uaf43\uae38 \uac77\ub2e4 \uace0\uac04 \uc81c\uc8fc \uac10\uade4 \uccb4\ud5d8 \uc54c\ucc28\uac8c \uc990\uae30\uace0 \ub3cc\uc544\uc628 \uc5ec\ud589 \uc774...</td>\n      <td>20211217</td>\n      <td>naver</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2</td>\n      <td>\ud734\uc560\ub9ac \uc790\uc5f0\uc0dd\ud65c\uacf5\uc6d0</td>\n      <td>\uc11c\uadc0\ud3ec \ub0a8\uc6d0\uc74d \uc790\ub9ac \ud734\uc560\ub9ac \uc790\uc5f0\uc0dd\ud65c\uacf5\uc6d0 \ubcfc\uc218 \uc788\uc744 \uc720\uba85\ud558\ub2f5\ub2c8\ub2e4</td>\n      <td>20211217</td>\n      <td>naver</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>3</td>\n      <td>\ud734\uc560\ub9ac \uc790\uc5f0\uc0dd\ud65c\uacf5\uc6d0</td>\n      <td>\uc9c0\uae08 \uaca8\uc6b8 \ub300\ud45c \ub3d9\ubc31\uaf43 \ub113\uc740 \ubd80\uc9c0 \ud65c\uc9dd \ud53c\uc5b4 \uc788\uc5b4 \uac77\ub294 \ubc1c\uae38 \ub9c8\ub2e4 \uc628\ud1b5 \ud551\ud06c\uc0c9 \uaf43\uae38...</td>\n      <td>20211217</td>\n      <td>naver</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>4</td>\n      <td>\ud734\uc560\ub9ac \uc790\uc5f0\uc0dd\ud65c\uacf5\uc6d0</td>\n      <td>\ud734\uc560\ub9ac \uc790\uc5f0\uc0dd\ud65c\uacf5\uc6d0 \uc81c\uc8fc \uc11c\uadc0\ud3ec\uc2dc \ub0a8\uc6d0\uc74d \uc785\uc7a5 \uc2dc\uac04 \ub9e4\uc77c \ud558\uc808\uae30 \uc785\uc7a5 \ub9c8\uac10 \uc785\uc7a5 \ub9c8...</td>\n      <td>20211217</td>\n      <td>naver</td>\n      <td>0</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n      <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-e2a0388f-645a-4bca-a4f0-503fee387704')\"\n              title=\"Convert this dataframe to an interactive table.\"\n              style=\"display:none;\">\n\n  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n       width=\"24px\">\n    <path d=\"M0 0h24v24H0V0z\" fill=\"none\"/>\n    <path d=\"M18.56 5.44l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94zm-11 1L8.5 8.5l.94-2.06 2.06-.94-2.06-.94L8.5 2.5l-.94 2.06-2.06.94zm10 10l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94z\"/><path d=\"M17.41 7.96l-1.37-1.37c-.4-.4-.92-.59-1.43-.59-.52 0-1.04.2-1.43.59L10.3 9.45l-7.72 7.72c-.78.78-.78 2.05 0 2.83L4 21.41c.39.39.9.59 1.41.59.51 0 1.02-.2 1.41-.59l7.78-7.78 2.81-2.81c.8-.78.8-2.07 0-2.86zM5.41 20L4 18.59l7.72-7.72 1.47 1.35L5.41 20z\"/>\n  </svg>\n      </button>\n\n  <style>\n    .colab-df-container {\n      display:flex;\n      flex-wrap:wrap;\n      gap: 12px;\n    }\n\n    .colab-df-convert {\n      background-color: #E8F0FE;\n      border: none;\n      border-radius: 50%;\n      cursor: pointer;\n      display: none;\n      fill: #1967D2;\n      height: 32px;\n      padding: 0 0 0 0;\n      width: 32px;\n    }\n\n    .colab-df-convert:hover {\n      background-color: #E2EBFA;\n      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n      fill: #174EA6;\n    }\n\n    [theme=dark] .colab-df-convert {\n      background-color: #3B4455;\n      fill: #D2E3FC;\n    }\n\n    [theme=dark] .colab-df-convert:hover {\n      background-color: #434B5C;\n      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n      fill: #FFFFFF;\n    }\n  </style>\n\n      \n    </div>\n  </div>\n\n\n\n\n\n```python\nsources = sentences['source'].unique()\n```\n\n\n```python\nsources = ['\uacf5\ucc9c\ud3ec','\ud734\uc560\ub9ac \uc790\uc5f0\uc0dd\ud65c\uacf5\uc6d0','\uc131\uc0b0\uc77c\ucd9c\ubd09(UNESCO \uc138\uacc4\uc790\uc5f0\uc720\uc0b0)','\ubcf8\ud0dc\ubc15\ubb3c\uad00','\uc81c\uc8fc\uc62c\ub808 14\ucf54\uc2a4',\n           '\ubc14\uc774\ub098\ud750\ud2bc \ud06c\ub9ac\uc2a4\ub9c8\uc2a4 \ubc15\ubb3c\uad00','\uc138\uacc4\uc790\ub3d9\ucc28 & \ud53c\uc544\ub178\ubc15\ubb3c\uad00','\ud55c\uad6d\uc57c\uad6c\uba85\uc608\uc804\ub2f9(\uc57c\uad6c\ubc15\ubb3c\uad00)','\ucd08\ucf5c\ub9bf\ubc15\ubb3c\uad00']\n```\n\n\n```python\nresult = pd.DataFrame()\nfor i in sources:\n  temp = sentences[sentences.source==i]\n  temp_sample = temp.sample(n=4000)\n  result = pd.concat([result, temp_sample], ignore_index=True)\nresult.sample(n=5)\n```\n\n\n\n\n\n  <div id=\"df-4825f615-2243-4fd9-b17e-0f49350901e4\">\n    <div class=\"colab-df-container\">\n      <div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Unnamed: 0</th>\n      <th>source</th>\n      <th>content</th>\n      <th>postdate</th>\n      <th>platform</th>\n      <th>target</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>21361</th>\n      <td>7321735</td>\n      <td>\ubc14\uc774\ub098\ud750\ud2bc \ud06c\ub9ac\uc2a4\ub9c8\uc2a4 \ubc15\ubb3c\uad00</td>\n      <td>\uadf8\uc911 \uac00\uc7a5 \uba54\uc778 \uc815\ub9d0 \ud06c\ub9ac\uc2a4\ub9c8\uc2a4 \ud558\uba74 \ub5a0\uc62c\ub790\ub358 \ucd94\uc5b5 \ub2e4\uc2dc \uc2dc\uc791 \ub418\ub294\uac83\ub9cc \uac19\uc740 \uae30\ubd84 ...</td>\n      <td>20220116</td>\n      <td>naver</td>\n      <td>739</td>\n    </tr>\n    <tr>\n      <th>15969</th>\n      <td>7005771</td>\n      <td>\ubcf8\ud0dc\ubc15\ubb3c\uad00</td>\n      <td>\uc6b0\uc120 \ub9c8\uc57c \uc774\uc758 \uc791\ud488 \uc804\uc2dc \uc804\uc2dc\uad00 \ud638\ubc15 \uc791\ud488 \uc88b\uc740\ub370 \ubc14\ub2e5 \uad00\ub9ac \uc548\ub418\ub294 \uac19\uc740 \uc544\uc26c\uc6c0 ...</td>\n      <td>20190224</td>\n      <td>naver</td>\n      <td>702</td>\n    </tr>\n    <tr>\n      <th>21885</th>\n      <td>7336051</td>\n      <td>\ubc14\uc774\ub098\ud750\ud2bc \ud06c\ub9ac\uc2a4\ub9c8\uc2a4 \ubc15\ubb3c\uad00</td>\n      <td>\uc5bc\ub978 \ub4e4\uc5b4\uac00 \ubcfc\uae4c \uc785\uad6c \uc0c1\uce58 \uc54a\uc8e0</td>\n      <td>20210216</td>\n      <td>naver</td>\n      <td>739</td>\n    </tr>\n    <tr>\n      <th>19006</th>\n      <td>2587463</td>\n      <td>\uc81c\uc8fc\uc62c\ub808 14\ucf54\uc2a4</td>\n      <td>\uc18c\uae08 \uc0dd\uc0b0 \uacfc\uc815 \uae30\ub85d \uc0ac\uc9c4 \uc18c\uae08 \uc0ac\uc6a9 \ud558\ub358 \ub3c4\uad6c \uc804\uc2dc \ub410\ub2e4 \ubc29\ubb38\uac1d \uc18c\uae08 \ucd08\ucf5c\ub9bf \ub9cc\ub4e4...</td>\n      <td>20201228</td>\n      <td>naver</td>\n      <td>252</td>\n    </tr>\n    <tr>\n      <th>25852</th>\n      <td>5642646</td>\n      <td>\uc138\uacc4\uc790\ub3d9\ucc28 &amp; \ud53c\uc544\ub178\ubc15\ubb3c\uad00</td>\n      <td>\ub124\uc774\ubc84 \ubbf8\ub9ac \uad6c\ub9e4 \ud558\uc2e4 \uc218\ub3c4 \uc788\ub294\ub370 \ud604\uc7a5 \ubc14\ub85c \uad6c\ub9e4 \ud588\uc5b4\uc694</td>\n      <td>20200818</td>\n      <td>naver</td>\n      <td>570</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n      <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-4825f615-2243-4fd9-b17e-0f49350901e4')\"\n              title=\"Convert this dataframe to an interactive table.\"\n              style=\"display:none;\">\n\n  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n       width=\"24px\">\n    <path d=\"M0 0h24v24H0V0z\" fill=\"none\"/>\n    <path d=\"M18.56 5.44l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94zm-11 1L8.5 8.5l.94-2.06 2.06-.94-2.06-.94L8.5 2.5l-.94 2.06-2.06.94zm10 10l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94z\"/><path d=\"M17.41 7.96l-1.37-1.37c-.4-.4-.92-.59-1.43-.59-.52 0-1.04.2-1.43.59L10.3 9.45l-7.72 7.72c-.78.78-.78 2.05 0 2.83L4 21.41c.39.39.9.59 1.41.59.51 0 1.02-.2 1.41-.59l7.78-7.78 2.81-2.81c.8-.78.8-2.07 0-2.86zM5.41 20L4 18.59l7.72-7.72 1.47 1.35L5.41 20z\"/>\n  </svg>\n      </button>\n\n  <style>\n    .colab-df-container {\n      display:flex;\n      flex-wrap:wrap;\n      gap: 12px;\n    }\n\n    .colab-df-convert {\n      background-color: #E8F0FE;\n      border: none;\n      border-radius: 50%;\n      cursor: pointer;\n      display: none;\n      fill: #1967D2;\n      height: 32px;\n      padding: 0 0 0 0;\n      width: 32px;\n    }\n\n    .colab-df-convert:hover {\n      background-color: #E2EBFA;\n      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n      fill: #174EA6;\n    }\n\n    [theme=dark] .colab-df-convert {\n      background-color: #3B4455;\n      fill: #D2E3FC;\n    }\n\n    [theme=dark] .colab-df-convert:hover {\n      background-color: #434B5C;\n      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n      fill: #FFFFFF;\n    }\n  </style>\n\n      \n    </div>\n  </div>\n\n\n\n\n\n```python\n# \ub370\uc774\ud130 \uc14b \uac19\uc740 \uacbd\uc6b0, 0~2 \uae4c\uc9c0 3\uac1c\uc758 \ubd84\ub958\ub85c \uad6c\uc131\ub418\uc5b4 \uc788\uc74c \n# \ud574\ub2f9 \ub370\uc774\ud130 \uc14b\uc758 \uacf5\ud3ec, \ub180\ub78c \ub4f1 \ud56d\ubaa9\uc744 \uc0ac\uc6a9\ud558\uae30 \ud3b8\ud558\ub3c4\ub85d \uc22b\uc790\ub85c \ubcc0\uacbd\nfor i,val in enumerate(sources):\n  result.loc[(result['source'] == val), 'n_target'] = sources.index(val)\n\n# result.loc[(sentiment_data['Emotion'] == \"\uae0d\uc815\"), 'n_target'] = 0  #\uae0d\uc815 => 0\n# result.loc[(sentiment_data['Emotion'] == \"\ubd80\uc815\"), 'n_target'] = 1  #\ubd80\uc815 => 1\n# result.loc[(sentiment_data['Emotion'] == \"\uc911\ub9bd\"), 'n_target'] = 2  #\uc911\ub9bd => 2\nresult['n_target'] = result['n_target'].astype(int)\nresult.sample(5)\nprint(len(result))\n```\n\n    36000\n\n\n\n```python\n# \ud559\uc2b5 \ub370\uc774\ud130 \uc14b \uad6c\uc131\n# \uac00\uc838\uc628 \ub370\uc774\ud130 \uc14b \ud30c\uc77c\uc5d0\uc11c sentence\uc640 emotion \ud56d\ubaa9\uc744 q\uc640 label\ub85c \uac01\uac01 \uad6c\uc131\ud558\uc5ec \ud559\uc2b5\uc744 \uc704\ud55c \ub370\uc774\ud130 \uc14b\uc73c\ub85c \uad6c\uc131 \ndata_list = []\nfor q, label in zip(result['content'], result['n_target'])  :\n    data = []\n    data.append(q)\n    data.append(str(label))\n\n    data_list.append(data)\n```\n\n\n```python\n# \ub370\uc774\ud130 \uc14b\uc758 \ud615\ud0dc \ud655\uc778\nprint(len(data_list))\nprint(data_list[0])\nprint(data_list[6000])\nprint(data_list[12000])\nprint(data_list[18000])\nprint(data_list[24000])\nprint(data_list[30000])\nprint(data_list[-1])\n```\n\n    36000\n    ['\uacf5\ucc9c\ud3ec \uc2dd\ub2f9 \uc81c\uc8fc\ud2b9\ubcc4\uc790\uce58\ub3c4 \uc11c\uadc0\ud3ec\uc2dc \ub0a8\uc6d0\uc74d \uacf5\ucc9c\ud3ec \uacf5\ucc9c\ud3ec \uc2dd\ub2f9', '0']\n    ['\ud734\uc560\ub9ac \ub300\ud45c \uacf5\uc5f0 \uc190\uaf3d\ud788\uace0 \uc788\ub2e4', '1']\n    ['\ud558\uc9c0\ub9cc \uc774\ub7ec\ud55c \ucf58\ud2b8 \ub9ac\ud2b8 \uc774\uc058\uac8c \ub514\uc790\uc778 \uc788\ub294 \uc548\ub3c4 \ub2e4\ub2e4 \uc624\uc528 \uc815\ub9d0 \uc874\uacbd \uc2a4\ub7ec\uc6cc\uc694', '3']\n    ['\ub9ce\uc740 \uc0ac\ub78c \uc5b4\ub514 \uac14\uc744\uae4c\uc694', '4']\n    ['\uc644\uc804 \ud790\ub9c1 \ub418\ub354\ub77c\uace0\uc694', '6']\n    ['\uc784\uc6d0\uc9c4 \uc5ed\uc2dc \ub2db\uc0b0 \ub3c4\ucfc4 \ub300\ud559 \ucd9c\uc2e0 \uc815\ub3c4 \ub9ce\uc740 \uc790\ub9ac \ucc28\uc9c0 \ud588\uc73c\ub098 \ub3c4\uc694\ud0c0 \uc9c0\ubc29 \ub300\ud559 \ucd9c\uc2e0 \ub300\ubd80\ubd84 \uc774\uc5c8\ub2e4 \uc774\ub7ec\ud55c \uc5ec\uac74 \ud1a0\ub300 \ub9ce\uc740 \uc0ac\ub78c \uba85\uc11d\ud55c \uc778\uc7ac \uc9d1\uc911 \ub418\uc5b4 \uc788\ub294 \ub2db\uc0b0 \uc131\uc7a5 \uac00\ub2a5\uc131 \ub192\uc744 \uc608\uce21 \ud588\uc5c8\uc73c\ub098 \uc9c0\ub09c \uacb0\uacfc \uc804\ud600 \ub2e4\ub974\uac8c \ub098\ud0c0\ub0ac\ub2e4', '7']\n    ['\uc624\ud788\ub824 \uacfc\uac70 \uc9c0\uae08 \ub354\uc6b1 \ub300\ud654 \uc0c1\ud0dc \uc5ed\uc2dc \ud22c\ube44 \ubb38\uacfc \uc5b4\uca54 \uc5c6\ub294 \uac74\uac00', '8']\n\n\n\n```python\n# sklearn.model_selection \ud328\ud0a4\uc9c0\ub97c \ud1b5\ud558\uc5ec \ud559\uc2b5 \ub370\uc774\ud130\uc640 \ud14c\uc2a4\ud2b8 \ub370\uc774\ud130\ub85c \ubd84\ud560\nfrom sklearn.model_selection import train_test_split\n\n# 75%\ub294 \ud559\uc2b5 \ub370\uc774\ud130\uc14b, 25%\ub294 \ud14c\uc2a4\ud2b8 \ub370\uc774\ud130\uc14b\uc73c\ub85c \uad6c\uc131\ndataset_train, dataset_test = train_test_split(data_list, test_size=0.25, random_state=0)\n```\n\n\n```python\n# \ud559\uc2b5 \ub370\uc774\ud130\uc14b\uacfc \ud14c\uc2a4\ud2b8 \ub370\uc774\ud130\uc14b\uc758 \ubd84\ud560 \ud655\uc778 \ubc0f \ud615\ud0dc \ud655\uc778\nprint(len(dataset_train))\nprint(len(dataset_test))\nprint(dataset_train[0])\nprint(dataset_test[0])\n```\n\n    27000\n    9000\n    ['\uc5b8\uc81c \uac00\ub3c4 \ub204\uad6c \ud568\uaed8 \ud574\ub3c4 \uc990\uac70\uc6b4 \uc81c\uc8fc \uc5ec\ud589 \uc81c\uc8fc\ub3c4 \uc5ec\ud589 \uac00\uc2dc\ub294 \ub4e4\uc774\ub77c\uba74 \uc5b4\ub290 \uc9c0\uc5ed \uc5b4\ub5a4 \uc219\uc18c \uba38\ubb3c\ub7ec\uc57c \uc990\uac70\uc6b8\uae4c \ucd9c\ubc1c \uace0\ubbfc \ubcf4\uc168\uc744 \uac19\uc740\ub370\uc694', '1']\n    ['\uace0\ubbfc \ud558\ub2e4 \uc815\uba74 \ubc14\ub2f7\uac00 \uac77\ub294\ub2e4', '4']\n\n\n\n```python\n# \ud559\uc2b5\uc5d0 \uc0ac\uc6a9\ud560 \ub370\uc774\ud130 \uc14b \ud074\ub798\uc2a4 \uc120\uc5b8\nclass BERTDataset(Dataset):\n    def __init__(self, dataset, sent_idx, label_idx, bert_tokenizer, max_len,\n                 pad, pair):\n        transform = nlp.data.BERTSentenceTransform(\n            bert_tokenizer, max_seq_length=max_len, pad=pad, pair=pair)\n\n        # transform\ud558\uc5ec \ud1a0\ud070\ud654 \ud558\ub294 \uacfc\uc815\uc5d0\uc11c \n        # transform(i[\uc778\ub371\uc2a4]) == transform(\"\uc544\uc544\uc544\uc544 \uc544\uc544\uc544 \uc544\uc544\") \uac19\uc740 \uacbd\uc6b0 \ud1a0\ud070\ud654\uac00 \uc815\uc0c1\uc801\uc73c\ub85c \uc9c4\ud589 \uc548\ub418\ub294 \uc624\ub958 \n        # transform([i[\uc778\ub371\uc2a4]]) == transform([\"\uc544\uc544\uc544\uc544 \uc544\uc544\uc544 \uc544\uc544\"]) \ud615\uc2dd\uc73c\ub85c transform \uc9c4\ud589\n        self.sentences = [transform([i[sent_idx]]) for i in dataset]\n        self.labels = [np.int32(i[label_idx]) for i in dataset]\n\n    # \uc804\uccb4 \ub370\uc774\ud130 \uc14b\uc5d0\uc11c \ud574\ub2f9\ud558\ub294 \uc778\ub371\uc2a4\uc758 sentences\uc640 labels\ub9cc \ubf51\ub294 \ud568\uc218\n    def __getitem__(self, i):\n        return (self.sentences[i] + (self.labels[i], ))\n\n    # \ub370\uc774\ud130 \uc14b\uc758 \uc0ac\uc774\uc988 return\n    def __len__(self):\n        return (len(self.labels))\n```\n\n\n```python\n# \ubaa8\ub378 \ud30c\ub77c\ubbf8\ud130 \uc124\uc815\n# \ud1a0\ud070\uc758 \ucd5c\ub300 \uae38\uc774\ub77c\uace0 \uc0dd\uac01\nmax_len = 64\n# \uba87 \uac1c\uc758 \uc0d8\ud50c\ub4e4\uc744 \uc608\uce21\ud574\ubcf4\uace0 \uac00\uc911\uce58\ub97c \uc5c5\ub370\uc774\ud2b8 \ud560 \uc9c0 \uc124\uc815\n# \uc544\ub798\uc640 \uac19\uc774 \ubc30\uce58 \uc0ac\uc774\uc988\uac00 64\uc778 \uacbd\uc6b0 \ub370\uc774\ud130 64\uac1c \ub9c8\ub2e4 \uc608\uce21\ud55c \uac83\uc744 \uc2e4\uc81c \uac12\uacfc \ube44\uad50\ud55c\ub2e4\nbatch_size = 64\nwarmup_ratio = 0.1\n# epoch \ud69f\uc218\ub294 \ubaa8\ub378\uc774 \uc804\uccb4 \ub370\uc774\ud130\uc14b\uc744 \ud6c8\ub828\uc2dc\ud0ac \ud69f\uc218\ub97c \uc758\ubbf8\ud55c\ub2e4.\nnum_epochs = 10\nmax_grad_norm = 1\nlog_interval = 200\n# learning_rate \uac12\uc774 \ub108\ubb34 \ud06c\uba74 \uc6d0\ud558\ub294 \uac12\uc5d0 \ub3c4\ub2ec\ud558\uae30 \ud798\ub4e4\uace0, \ub108\ubb34 \uc791\uc73c\uba74 \ud559\uc2b5\uae30\uac04\uc774 \uc624\ub798 \uac78\ub9b0\ub2e4.\nlearning_rate =  5e-5\n```\n\n\n```python\n# kobert\uc5d0\uc11c vocab\uc744 \ud1b5\ud574\uc11c \ud1a0\ud070\ud654 \uc9c4\ud589\ntokenizer = get_tokenizer()\ntok = nlp.data.BERTSPTokenizer(tokenizer, vocab, lower=False)\n```\n\n    using cached model. /content/.cache/kobert_news_wiki_ko_cased-1087f8699e.spiece\n\n\n\n```python\n# \ud559\uc2b5 \ub370\uc774\ud130\uc14b\uacfc \ud14c\uc2a4\ud2b8 \ub370\uc774\ud130\uc14b \ud1a0\ud070\ud654 \uc9c4\ud589\ndata_train = BERTDataset(dataset_train, 0, 1, tok, max_len, True, False)\ndata_test = BERTDataset(dataset_test, 0, 1, tok, max_len, True, False)\n```\n\n\n```python\n# \ud1a0\ud070\ud654 \ud655\uc778 (\ub9c8\uc9c0\ub9c9\uc5d0 \ud638\ucd9c\ub41c \ub370\uc774\ud130\uc14b\uc774 \ucd9c\ub825\ub428)\ndata_train[0]\n# data_test[0]\n```\n\n\n\n\n    (array([   2, 3245,  517, 5330, 5859, 1528, 4983, 5002, 4282, 4154, 3321,\n            4155, 3321,  756, 5760,  517, 5940, 6009, 3222, 4329, 3224, 2911,\n            6607, 2009, 6037, 6844,  517, 7313, 5377, 7013, 5591, 4573, 1002,\n            2355, 6604, 7088,  833, 5850, 6999,    3,    1,    1,    1,    1,\n               1,    1,    1,    1,    1,    1,    1,    1,    1,    1,    1,\n               1,    1,    1,    1,    1,    1,    1,    1,    1], dtype=int32),\n     array(40, dtype=int32),\n     array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n           dtype=int32),\n     1)\n\n\n\n\n```python\n# DataLoader\ub97c \ud1b5\ud574\uc11c \uc804\uccb4 \ub370\uc774\ud130\uc14b\uc774 batch_size\ub85c \ubd84\ud560\n# num_workers\uc758 \uacbd\uc6b0 \ub192\uc744\uc218\ub85d load \uc18d\ub3c4 \uc0c1\uc2b9\ntrain_dataloader = torch.utils.data.DataLoader(data_train, batch_size=batch_size, num_workers=5)\ntest_dataloader = torch.utils.data.DataLoader(data_test, batch_size=batch_size, num_workers=5)\n```\n\n    /usr/local/lib/python3.7/dist-packages/torch/utils/data/dataloader.py:481: UserWarning: This DataLoader will create 5 worker processes in total. Our suggested max number of worker in current system is 2, which is smaller than what this DataLoader is going to create. Please be aware that excessive worker creation might get DataLoader running slow or even freeze, lower the worker number to avoid potential slowness/freeze if necessary.\n      cpuset_checked))\n\n\n\n```python\n# \ubd84\ub958\uc5d0 \uc0ac\uc6a9\ud560 \ubaa8\ub378 \ud074\ub798\uc2a4 \uc120\uc5b8\nclass BERTClassifier(nn.Module):\n    def __init__(self,\n                 bert,\n                 hidden_size = 768,\n                 # num_classes\ub294 \uce74\ud14c\uace0\ub9ac\uc758 \uac1c\uc218\ub97c \uc758\ubbf8\ud55c\ub2e4. (\ud604\uc7ac \ub370\uc774\ud130\uc14b\uc758 \uacbd\uc6b0 9\uac1c\uc758 \ubd84\ub958\ub85c \ub370\uc774\ud130\uc14b\uc774 \uad6c\uc131\ub418\uc5b4 \uc788\uc74c)\n                 num_classes=9,\n                 dr_rate=None,\n                 params=None):\n        super(BERTClassifier, self).__init__()\n        self.bert = bert\n        self.dr_rate = dr_rate\n                 \n        self.classifier = nn.Linear(hidden_size , num_classes)\n        if dr_rate:\n            self.dropout = nn.Dropout(p=dr_rate)\n    \n    def gen_attention_mask(self, token_ids, valid_length):\n        attention_mask = torch.zeros_like(token_ids)\n        for i, v in enumerate(valid_length):\n            attention_mask[i][:v] = 1\n        return attention_mask.float()\n\n    def forward(self, token_ids, valid_length, segment_ids):\n        attention_mask = self.gen_attention_mask(token_ids, valid_length)\n        \n        _, pooler = self.bert(input_ids = token_ids, token_type_ids = segment_ids.long(), attention_mask = attention_mask.float().to(token_ids.device))\n        if self.dr_rate:\n            out = self.dropout(pooler)\n        return self.classifier(out)\n```\n\n\n```python\n# to(Device)\ub294 \uc704\uc758 torch.device(\"cuda:0\")\ub97c \uc758\ubbf8\ud558\uba70 \n# GPU\uc5d0\uc11c \ud559\uc2b5\ub41c \ubaa8\ub378\uc744 GPU\ub85c \ubd88\ub7ec\uc62c \ub54c \uc0ac\uc6a9\ud55c\ub2e4.\n# \ub610\ud55c GPU\ub85c \ud559\uc2b5\ub41c \ubaa8\ub378\uc5d0 \ub370\uc774\ud130\ub97c \uc81c\uacf5\ud560 \ub54c\ub3c4 to(Device)\ub97c \ubd99\uc5ec\uc918\uc57c \ud568.\n# bert\ubaa8\ub378 \ubd88\ub7ec\uc624\uae30\nmodel = BERTClassifier(bertmodel,  dr_rate=0.5).to(device)\n```\n\n\n```python\n# optimizer\uc640 schedule \uc124\uc815\nno_decay = ['bias', 'LayerNorm.weight']\noptimizer_grouped_parameters = [\n    {'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},\n    {'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}\n]\n```\n\n\n```python\n# optimizer = \uc804\uccb4 \ub370\uc774\ud130 \uc14b\uc758 \uc2e4\uc81c \uacb0\uacfc\uc640 \ubaa8\ub378\uc774 \uc608\uce21\ud55c \uac12 \uac04\uc758 \ucc28\uc774\uac00 \ud6a8\uc728\uc801\uc73c\ub85c \uc881\ud600\uc9c8 \uc218 \uc788\ub3c4\ub85d \ucd5c\uc801\ud654\ud574\uc8fc\ub294 \uc5ed\ud560\n# transform\uc5d0\uc11c \uc81c\uacf5\ud558\ub294 AdamW optimizer \uc0ac\uc6a9\noptimizer = AdamW(optimizer_grouped_parameters, lr=learning_rate)\n# \uc608\uce21\uac12\uacfc \uc2e4\uc81c\uac12\uc758 \uc624\ucc28\uc778 \uc190\uc2e4\ud568\uc218\ub294 pytorch\uc5d0\uc11c \uc81c\uacf5\ud558\ub294 \ub2e4\uc911\ubd84\ub958\ub97c \uc704\ud55c \ub300\ud45c\uc801\uc778 \uc190\uc2e4\ud568\uc218\uc778 torch.nn.CrossEntropyLoss \uc0ac\uc6a9\nloss_fn = nn.CrossEntropyLoss()\n```\n\n    /usr/local/lib/python3.7/dist-packages/transformers/optimization.py:309: FutureWarning: This implementation of AdamW is deprecated and will be removed in a future version. Use the PyTorch implementation torch.optim.AdamW instead, or set `no_deprecation_warning=True` to disable this warning\n      FutureWarning,\n\n\n\n```python\n# \ucd1d \ud559\uc2b5 \uc218\ub294 \ud559\uc2b5\ub370\uc774\ud130\uc758 \ud06c\uae30 * \uc5d0\ud3ed\uc218\nt_total = len(train_dataloader) * num_epochs\nwarmup_step = int(t_total * warmup_ratio)\n```\n\n\n```python\n# \uc2dc\uac04\uc774 \uc9c0\ub0a8\uc5d0 \ub530\ub77c \ud559\uc2b5\ub960\uc744 \uc870\uae08\uc529 \uac10\uc18c\uc2dc\ud0a4\ub294 scheduler\nscheduler = get_cosine_schedule_with_warmup(optimizer, num_warmup_steps=warmup_step, num_training_steps=t_total)\n```\n\n\n```python\n# \uc815\ud655\ub3c4 \uce21\uc815 \ud568\uc218\ndef calc_accuracy(X,Y):\n    max_vals, max_indices = torch.max(X, 1)\n    train_acc = (max_indices == Y).sum().data.cpu().numpy()/max_indices.size()[0]\n    return train_acc\n```\n\n\n```python\n# \ubaa8\ub378 \ud559\uc2b5 \n# \uc5d0\ud3ed\uc218 \ub9cc\ud07c \ubc18\ubcf5\nfor e in range(num_epochs):\n    # \uc815\ud655\ub3c4 \ucd08\uae30\ud654\n    train_acc = 0.0\n    test_acc = 0.0\n    # \ud559\uc2b5 \ubaa8\ub4dc\n    model.train()\n\n    # \ubc30\uce58\ub9cc\ud07c \ud559\uc2b5 \ub370\uc774\ud130\uc14b \uac00\uc838\uc634\n    for batch_id, (token_ids, valid_length, segment_ids, label) in enumerate(tqdm_notebook(train_dataloader)):\n        # \uadf8\ub798\ub514\uc5b8\ud2b8 = \uc21c\uac04\ubcc0\ud654\uc728\n        # \uadf8\ub798\ub514\uc5b8\ud2b8 \ucd08\uae30\ud654\n        optimizer.zero_grad()\n\n        # \ubc30\uce58\uc5d0\uc11c \ub370\uc774\ud130 \ucd94\ucd9c\n        # \ubaa8\ub378\uc5d0 \uc81c\uacf5\ud558\ub294 \ub370\uc774\ud130\uc774\uae30\ub54c\ubb38\uc5d0 to(device)\n        token_ids = token_ids.long().to(device)\n        segment_ids = segment_ids.long().to(device)\n        valid_length= valid_length\n        label = label.long().to(device)\n\n        # output\n        out = model(token_ids, valid_length, segment_ids)\n\n        # \uc190\uc2e4 \uacc4\uc0b0 (\uc2e4\uc81c\uac12\uacfc \uc608\uce21\uac12 \uac04\uc758 \uc624\ucc28)\n        loss = loss_fn(out, label)\n\n        # \uadf8\ub798\ub514\uc5b8\ud2b8\uc5d0 \uac12 \ub354\ud558\uae30\n        loss.backward()\n\n        # \ud559\uc2b5\uc758 \uc548\uc815\ud654\ub97c \uc704\ud574 \uadf8\ub798\ub514\uc5b8\ud2b8 \ud074\ub9ac\ud551(\uc790\ub974\uae30) => \uae30\uc6b8\uae30\uac00 \ub108\ubb34 \ucee4\uc9c0\ub294 \uac83\uc744 \ubc29\uc9c0\n        torch.nn.utils.clip_grad_norm_(model.parameters(), max_grad_norm)\n\n        # \uac00\uc911\uce58 \ud30c\ub77c\ubbf8\ud130 \uc5c5\ub370\uc774\ud2b8\n        optimizer.step()\n\n        # \ud559\uc2b5\ub960 \uac10\uc18c \uc2a4\ucf00\uc904\ub7ec \n        scheduler.step()\n\n        # \uc815\ud655\ub3c4\n        train_acc += calc_accuracy(out, label)\n\n        # batch 200 \uac04\uaca9\uc73c\ub85c \ud559\uc2b5\uc0c1\ud669 \ucd9c\ub825\n        if batch_id % log_interval == 0:\n            print(\"epoch {} batch id {} loss {} train acc {}\".format(e+1, batch_id+1, loss.data.cpu().numpy(), train_acc / (batch_id+1)))\n    print(\"epoch {} train acc {}\".format(e+1, train_acc / (batch_id+1)))\n    \n    # \ud3c9\uac00 \ubaa8\ub4dc\n    model.eval()\n\n    # \ud14c\uc2a4\ud2b8 \ub370\uc774\ud130\uc14b\uc744 \ud1b5\ud55c \ud3c9\uac00\n    for batch_id, (token_ids, valid_length, segment_ids, label) in enumerate(tqdm_notebook(test_dataloader)):\n        token_ids = token_ids.long().to(device)\n        segment_ids = segment_ids.long().to(device)\n        valid_length= valid_length\n        label = label.long().to(device)\n        out = model(token_ids, valid_length, segment_ids)\n        test_acc += calc_accuracy(out, label)\n    print(\"epoch {} test acc {}\".format(e+1, test_acc / (batch_id+1)))\n```\n\n    /usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:11: TqdmDeprecationWarning: This function will be removed in tqdm==5.0.0\n    Please use `tqdm.notebook.tqdm` instead of `tqdm.tqdm_notebook`\n      # This is added back by InteractiveShellApp.init_path()\n\n\n\n      0%|          | 0/422 [00:00<?, ?it/s]\n\n\n    /usr/local/lib/python3.7/dist-packages/torch/utils/data/dataloader.py:481: UserWarning: This DataLoader will create 5 worker processes in total. Our suggested max number of worker in current system is 2, which is smaller than what this DataLoader is going to create. Please be aware that excessive worker creation might get DataLoader running slow or even freeze, lower the worker number to avoid potential slowness/freeze if necessary.\n      cpuset_checked))\n\n\n    epoch 1 batch id 1 loss 2.233818769454956 train acc 0.125\n    epoch 1 batch id 201 loss 1.7291207313537598 train acc 0.2513992537313433\n    epoch 1 batch id 401 loss 1.136894702911377 train acc 0.4184850374064838\n    epoch 1 train acc 0.4291003723764387\n\n\n    /usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:53: TqdmDeprecationWarning: This function will be removed in tqdm==5.0.0\n    Please use `tqdm.notebook.tqdm` instead of `tqdm.tqdm_notebook`\n\n\n\n      0%|          | 0/141 [00:00<?, ?it/s]\n\n\n    epoch 1 test acc 0.6217198581560284\n\n\n\n      0%|          | 0/422 [00:00<?, ?it/s]\n\n\n    epoch 2 batch id 1 loss 1.2925124168395996 train acc 0.5625\n    epoch 2 batch id 201 loss 1.2094385623931885 train acc 0.6235230099502488\n    epoch 2 batch id 401 loss 0.9465869665145874 train acc 0.6463918329177057\n    epoch 2 train acc 0.6493948882870684\n\n\n\n      0%|          | 0/141 [00:00<?, ?it/s]\n\n\n    epoch 2 test acc 0.6497562056737588\n\n\n\n      0%|          | 0/422 [00:00<?, ?it/s]\n\n\n    epoch 3 batch id 1 loss 1.085824728012085 train acc 0.6875\n    epoch 3 batch id 201 loss 1.0113699436187744 train acc 0.6985385572139303\n    epoch 3 batch id 401 loss 0.7538095712661743 train acc 0.7188279301745636\n    epoch 3 train acc 0.7212201675693974\n\n\n\n      0%|          | 0/141 [00:00<?, ?it/s]\n\n\n    epoch 3 test acc 0.6563829787234042\n\n\n\n      0%|          | 0/422 [00:00<?, ?it/s]\n\n\n    epoch 4 batch id 1 loss 0.8977480530738831 train acc 0.734375\n    epoch 4 batch id 201 loss 0.8085736036300659 train acc 0.761738184079602\n    epoch 4 batch id 401 loss 0.6546597480773926 train acc 0.7819513715710723\n    epoch 4 train acc 0.7832018026404874\n\n\n\n      0%|          | 0/141 [00:00<?, ?it/s]\n\n\n    epoch 4 test acc 0.6576241134751772\n\n\n\n      0%|          | 0/422 [00:00<?, ?it/s]\n\n\n    epoch 5 batch id 1 loss 0.5402131080627441 train acc 0.8125\n    epoch 5 batch id 201 loss 0.5455483794212341 train acc 0.8245491293532339\n    epoch 5 batch id 401 loss 0.4883134067058563 train acc 0.8384507481296758\n    epoch 5 train acc 0.8401320243737305\n\n\n\n      0%|          | 0/141 [00:00<?, ?it/s]\n\n\n    epoch 5 test acc 0.6580452127659574\n\n\n\n      0%|          | 0/422 [00:00<?, ?it/s]\n\n\n    epoch 6 batch id 1 loss 0.3271224796772003 train acc 0.921875\n    epoch 6 batch id 201 loss 0.48229771852493286 train acc 0.8748445273631841\n    epoch 6 batch id 401 loss 0.3431335687637329 train acc 0.8838840399002493\n    epoch 6 train acc 0.884838354773189\n\n\n\n      0%|          | 0/141 [00:00<?, ?it/s]\n\n\n    epoch 6 test acc 0.6567375886524822\n\n\n\n      0%|          | 0/422 [00:00<?, ?it/s]\n\n\n    epoch 7 batch id 1 loss 0.18822620809078217 train acc 0.953125\n    epoch 7 batch id 201 loss 0.31279677152633667 train acc 0.9100590796019901\n    epoch 7 batch id 401 loss 0.21971344947814941 train acc 0.9159133416458853\n    epoch 7 train acc 0.9173419515910629\n\n\n\n      0%|          | 0/141 [00:00<?, ?it/s]\n\n\n    epoch 7 test acc 0.6567375886524822\n\n\n\n      0%|          | 0/422 [00:00<?, ?it/s]\n\n\n    epoch 8 batch id 1 loss 0.11464236676692963 train acc 0.984375\n    epoch 8 batch id 201 loss 0.2301836758852005 train acc 0.9390547263681592\n    epoch 8 batch id 401 loss 0.19291695952415466 train acc 0.9422147755610972\n    epoch 8 train acc 0.9428211746784022\n\n\n\n      0%|          | 0/141 [00:00<?, ?it/s]\n\n\n    epoch 8 test acc 0.6594858156028368\n\n\n\n      0%|          | 0/422 [00:00<?, ?it/s]\n\n\n    epoch 9 batch id 1 loss 0.06446045637130737 train acc 0.984375\n    epoch 9 batch id 201 loss 0.15114420652389526 train acc 0.9560012437810945\n    epoch 9 batch id 401 loss 0.11005473881959915 train acc 0.9591645885286783\n    epoch 9 train acc 0.95937711577522\n\n\n\n      0%|          | 0/141 [00:00<?, ?it/s]\n\n\n    epoch 9 test acc 0.6642287234042553\n\n\n\n      0%|          | 0/422 [00:00<?, ?it/s]\n\n\n    epoch 10 batch id 1 loss 0.07792037725448608 train acc 0.984375\n    epoch 10 batch id 201 loss 0.07620628923177719 train acc 0.9668843283582089\n    epoch 10 batch id 401 loss 0.09144933521747589 train acc 0.9665679551122195\n    epoch 10 train acc 0.9665919092755586\n\n\n\n      0%|          | 0/141 [00:00<?, ?it/s]\n\n\n    epoch 10 test acc 0.6627437943262412\n\n\n\n```python\n# \uad6c\uae00 \ub4dc\ub77c\uc774\ube0c \uae30\ubcf8 \uacbd\ub85c = '/content/drive/MyDrive'\nimport os\n# \ud574\ub2f9 \ub514\ub809\ud1a0\ub9ac\ub85c \uc774\ub3d9\nos.chdir('/content/drive/MyDrive/Colab Notebooks/jejuRecommand')\n# \ud604\uc7ac \uacbd\ub85c\nos.getcwd()\n```\n\n\n\n\n    '/content/drive/MyDrive/Colab Notebooks/jejuRecommand'\n\n\n\n\n```python\ntorch.save(model,'./jeju_model.pt') \n\n#dict \uc800\uc7a5\ntorch.save(model.state_dict(), './jeju_model_state_dict.pt')\n\n# \ud544\uc694\ud55c \uac12 \uc9c0\uc815\ud574\uc11c \uc800\uc7a5 \uac00\ub2a5\n# torch.save({\n#     'model': model.state_dict(),\n#     'optimizer': optimizer.state_dict()\n# }, '7emotions_all.tar')  \n```\n\n\n```python\n!ls\n```\n\n    data\t       jeju_model_state_dict.pt  keyword.ipynb\n    jeju_model.pt  jeju_sentence.ipynb\t Untitled0.ipynb\n\n\n\n```python\nroc curve, wandb, 8 carrot?, pyparrot? , oversampling\n```\n\n\n```python\ntrain,test dataset \uc815\uc81c\ud558\uae30\n\uacfc\uc801\ud569 \uace0\ubbfc -> \ubc29\uc548: dataset \uc815\uc81c\nhyperparam : \uac00\uc7a5 \ub9c8\uc9c0\ub9c9\uc5d0 \ud574\ubcfc\uac83\n\ud559\uc2b5\ud55c \uc2dc\uac04\uc774 \uc624\ub798 \uac78\ub9ac\ub294\uac83 : \ud2b9\uc815 \uad00\uad11\uc9c0\ub9cc -> \ud604\uc7ac 9\uac1c\uc5d0 \n\n```\n", "meta": {"hexsha": "2c4df068f94fb3f3bc21b9bc766c0022fd2ecf4c", "size": 230347, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "analysis/jeju_KoBERT_chatbot.ipynb", "max_stars_repo_name": "dldydrhkd/jeju_tourist_recommand", "max_stars_repo_head_hexsha": "6acf792ac8dc8cfc266e9837f25944cb3b7dfa16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analysis/jeju_KoBERT_chatbot.ipynb", "max_issues_repo_name": "dldydrhkd/jeju_tourist_recommand", "max_issues_repo_head_hexsha": "6acf792ac8dc8cfc266e9837f25944cb3b7dfa16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-03-17T13:14:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T13:52:26.000Z", "max_forks_repo_path": "analysis/jeju_KoBERT_chatbot.ipynb", "max_forks_repo_name": "dldydrhkd/jeju_tourist_recommand", "max_forks_repo_head_hexsha": "6acf792ac8dc8cfc266e9837f25944cb3b7dfa16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2022-03-09T02:45:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T13:21:22.000Z", "avg_line_length": 230347.0, "max_line_length": 230347, "alphanum_fraction": 0.7464607744, "converted": true, "num_tokens": 17909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06008664680776121, "lm_q2_score": 0.03210070984214239, "lm_q1q2_score": 0.0019288240145632339}}
{"text": "```python\nfrom google.colab import drive\n\ndrive.mount('/content/drive')\n```\n\n    Mounted at /content/drive\n\n\n\n```python\n# !git clone https://github.com/ultralytics/yolov5\n```\n\n\n```python\n# cd yolo_v5\n```\n\n\n```python\ncd /content/drive/MyDrive/yolo_v5\n```\n\n    /content/drive/MyDrive/yolo_v5\n\n\n\n```python\n!pip install -r requirements.txt\n```\n\n    Requirement already satisfied: matplotlib>=3.2.2 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 4)) (3.2.2)\n    Requirement already satisfied: numpy>=1.18.5 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 5)) (1.21.5)\n    Requirement already satisfied: opencv-python>=4.1.2 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 6)) (4.1.2.30)\n    Requirement already satisfied: Pillow>=7.1.2 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 7)) (7.1.2)\n    Collecting PyYAML>=5.3.1\n      Downloading PyYAML-6.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (596 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 596 kB 4.3 MB/s \n    \u001b[?25hRequirement already satisfied: requests>=2.23.0 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 9)) (2.23.0)\n    Requirement already satisfied: scipy>=1.4.1 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 10)) (1.4.1)\n    Requirement already satisfied: torch>=1.7.0 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 11)) (1.10.0+cu111)\n    Requirement already satisfied: torchvision>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 12)) (0.11.1+cu111)\n    Requirement already satisfied: tqdm>=4.41.0 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 13)) (4.63.0)\n    Requirement already satisfied: tensorboard>=2.4.1 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 16)) (2.8.0)\n    Requirement already satisfied: pandas>=1.1.4 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 20)) (1.3.5)\n    Requirement already satisfied: seaborn>=0.11.0 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 21)) (0.11.2)\n    Collecting thop\n      Downloading thop-0.0.31.post2005241907-py3-none-any.whl (8.7 kB)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=3.2.2->-r requirements.txt (line 4)) (0.11.0)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=3.2.2->-r requirements.txt (line 4)) (2.8.2)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=3.2.2->-r requirements.txt (line 4)) (3.0.7)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=3.2.2->-r requirements.txt (line 4)) (1.3.2)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests>=2.23.0->-r requirements.txt (line 9)) (1.24.3)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.23.0->-r requirements.txt (line 9)) (2.10)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.23.0->-r requirements.txt (line 9)) (2021.10.8)\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.23.0->-r requirements.txt (line 9)) (3.0.4)\n    Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch>=1.7.0->-r requirements.txt (line 11)) (3.10.0.2)\n    Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.4.1->-r requirements.txt (line 16)) (1.0.1)\n    Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.4.1->-r requirements.txt (line 16)) (57.4.0)\n    Requirement already satisfied: absl-py>=0.4 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.4.1->-r requirements.txt (line 16)) (1.0.0)\n    Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.4.1->-r requirements.txt (line 16)) (0.6.1)\n    Requirement already satisfied: grpcio>=1.24.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.4.1->-r requirements.txt (line 16)) (1.44.0)\n    Requirement already satisfied: google-auth<3,>=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.4.1->-r requirements.txt (line 16)) (1.35.0)\n    Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.4.1->-r requirements.txt (line 16)) (3.3.6)\n    Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.4.1->-r requirements.txt (line 16)) (1.8.1)\n    Requirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.4.1->-r requirements.txt (line 16)) (0.37.1)\n    Requirement already satisfied: protobuf>=3.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.4.1->-r requirements.txt (line 16)) (3.17.3)\n    Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.4.1->-r requirements.txt (line 16)) (0.4.6)\n    Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=1.1.4->-r requirements.txt (line 20)) (2018.9)\n    Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from absl-py>=0.4->tensorboard>=2.4.1->-r requirements.txt (line 16)) (1.15.0)\n    Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard>=2.4.1->-r requirements.txt (line 16)) (4.2.4)\n    Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard>=2.4.1->-r requirements.txt (line 16)) (4.8)\n    Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard>=2.4.1->-r requirements.txt (line 16)) (0.2.8)\n    Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard>=2.4.1->-r requirements.txt (line 16)) (1.3.1)\n    Requirement already satisfied: importlib-metadata>=4.4 in /usr/local/lib/python3.7/dist-packages (from markdown>=2.6.8->tensorboard>=2.4.1->-r requirements.txt (line 16)) (4.11.2)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=4.4->markdown>=2.6.8->tensorboard>=2.4.1->-r requirements.txt (line 16)) (3.7.0)\n    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<3,>=1.6.3->tensorboard>=2.4.1->-r requirements.txt (line 16)) (0.4.8)\n    Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard>=2.4.1->-r requirements.txt (line 16)) (3.2.0)\n    Installing collected packages: thop, PyYAML\n      Attempting uninstall: PyYAML\n        Found existing installation: PyYAML 3.13\n        Uninstalling PyYAML-3.13:\n          Successfully uninstalled PyYAML-3.13\n    Successfully installed PyYAML-6.0 thop-0.0.31.post2005241907\n\n\n\n```python\nimport torch\nprint('Using torch %s %s' % (torch.__version__, torch.cuda.get_device_properties(0) if torch.cuda.is_available() else 'CPU'))\n```\n\n    Using torch 1.10.0+cu111 _CudaDeviceProperties(name='Tesla K80', major=3, minor=7, total_memory=11441MB, multi_processor_count=13)\n\n\n\n```python\n%cat ./data/data.yaml\n```\n\n    train: /content/drive/MyDrive/yolo_v5/data/drowsy_training/train/images\r\n    val: /content/drive/MyDrive/yolo_v5/data/drowsy_training/test/images\r\n    test: /content/drive/MyDrive/yolo_v5/data/drowsy_training/test/images\r\n    \r\n    # Classes\r\n    nc: 4  # number of classes\r\n    names: ['normal', 'drowsy','drowsy#2', 'yawning']  # class names\r\n    \r\n\n\n\n```python\n%cat ./models/yolov5n_drowsy.yaml\n```\n\n    # YOLOv5 \u00f0\u0178\u0161\u20ac by Ultralytics, GPL-3.0 license\r\n    \r\n    # Parameters\r\n    nc: 4  # number of classes\r\n    depth_multiple: 0.33  # model depth multiple\r\n    width_multiple: 0.25  # layer channel multiple\r\n    anchors:\r\n      - [10,13, 16,30, 33,23]  # P3/8\r\n      - [30,61, 62,45, 59,119]  # P4/16\r\n      - [116,90, 156,198, 373,326]  # P5/32\r\n    \r\n    # YOLOv5 v6.0 backbone\r\n    backbone:\r\n      # [from, number, module, args]\r\n      [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\r\n       [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\r\n       [-1, 3, C3, [128]],\r\n       [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\r\n       [-1, 6, C3, [256]],\r\n       [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\r\n       [-1, 9, C3, [512]],\r\n       [-1, 1, Conv, [1024, 3, 2]],  # 7-P5/32\r\n       [-1, 3, C3, [1024]],\r\n       [-1, 1, SPPF, [1024, 5]],  # 9\r\n      ]\r\n    \r\n    # YOLOv5 v6.0 head\r\n    head:\r\n      [[-1, 1, Conv, [512, 1, 1]],\r\n       [-1, 1, nn.Upsample, [None, 2, 'nearest']],\r\n       [[-1, 6], 1, Concat, [1]],  # cat backbone P4\r\n       [-1, 3, C3, [512, False]],  # 13\r\n    \r\n       [-1, 1, Conv, [256, 1, 1]],\r\n       [-1, 1, nn.Upsample, [None, 2, 'nearest']],\r\n       [[-1, 4], 1, Concat, [1]],  # cat backbone P3\r\n       [-1, 3, C3, [256, False]],  # 17 (P3/8-small)\r\n    \r\n       [-1, 1, Conv, [256, 3, 2]],\r\n       [[-1, 14], 1, Concat, [1]],  # cat head P4\r\n       [-1, 3, C3, [512, False]],  # 20 (P4/16-medium)\r\n    \r\n       [-1, 1, Conv, [512, 3, 2]],\r\n       [[-1, 10], 1, Concat, [1]],  # cat head P5\r\n       [-1, 3, C3, [1024, False]],  # 23 (P5/32-large)\r\n    \r\n       [[17, 20, 23], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)\r\n      ]\r\n\n\n\n```python\n%cat ./data/hyps/hyp.scratch.yaml\n```\n\n    # YOLOv5 \ud83d\ude80 by Ultralytics, GPL-3.0 license\r\n    # Hyperparameters for COCO training from scratch\r\n    # python train.py --batch 40 --cfg yolov5m.yaml --weights '' --data coco.yaml --img 640 --epochs 300\r\n    # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials\r\n    \r\n    lr0: 0.01  # initial learning rate (SGD=1E-2, Adam=1E-3)\r\n    lrf: 0.1  # final OneCycleLR learning rate (lr0 * lrf)\r\n    momentum: 0.937  # SGD momentum/Adam beta1\r\n    weight_decay: 0.0005  # optimizer weight decay 5e-4\r\n    warmup_epochs: 3.0  # warmup epochs (fractions ok)\r\n    warmup_momentum: 0.8  # warmup initial momentum\r\n    warmup_bias_lr: 0.1  # warmup initial bias lr\r\n    box: 0.05  # box loss gain\r\n    cls: 0.5  # cls loss gain\r\n    cls_pw: 1.0  # cls BCELoss positive_weight\r\n    obj: 1.0  # obj loss gain (scale with pixels)\r\n    obj_pw: 1.0  # obj BCELoss positive_weight\r\n    iou_t: 0.20  # IoU training threshold\r\n    anchor_t: 4.0  # anchor-multiple threshold\r\n    # anchors: 3  # anchors per output layer (0 to ignore)\r\n    fl_gamma: 0.0  # focal loss gamma (efficientDet default gamma=1.5)\r\n    hsv_h: 0.015  # image HSV-Hue augmentation (fraction)\r\n    hsv_s: 0.7  # image HSV-Saturation augmentation (fraction)\r\n    hsv_v: 0.4  # image HSV-Value augmentation (fraction)\r\n    degrees: 0.0  # image rotation (+/- deg)\r\n    translate: 0.1  # image translation (+/- fraction)\r\n    scale: 0.5  # image scale (+/- gain)\r\n    shear: 0.0  # image shear (+/- deg)\r\n    perspective: 0.0  # image perspective (+/- fraction), range 0-0.001\r\n    flipud: 0.0  # image flip up-down (probability)\r\n    fliplr: 0.5  # image flip left-right (probability)\r\n    mosaic: 1.0  # image mosaic (probability)\r\n    mixup: 0.0  # image mixup (probability)\r\n    copy_paste: 0.0  # segment copy-paste (probability)\r\n\n\n\n```python\nimport os\nos.chdir('/content/drive/MyDrive/yolo_v5')\n```\n\n\n```python\npwd\n```\n\n\n\n\n    '/content/drive/MyDrive/yolo_v5'\n\n\n\n\n```python\n%%time\n%cd /content/drive/MyDrive/yolo_v5\n!python train.py  --resume --imgsz 640 --batch 16 --epochs 600 --data data/data.yaml --cfg models/yolov5n_drowsy.yaml --weights weights/yolov5n.pt  --name drowsy_result  --cache --device 0\n```\n\n    /content/drive/MyDrive/yolo_v5\n    \u001b[34m\u001b[1mtrain: \u001b[0mweights=weights/yolov5n.pt, cfg=models/yolov5n_drowsy.yaml, data=data/data.yaml, hyp=data/hyps/hyp.scratch.yaml, epochs=600, batch_size=16, imgsz=640, rect=False, resume=False, nosave=False, noval=False, noautoanchor=False, evolve=None, bucket=, cache=ram, image_weights=False, device=0, multi_scale=False, single_cls=False, adam=False, sync_bn=False, workers=8, project=runs/train, name=drowsy_result, exist_ok=False, quad=False, linear_lr=False, label_smoothing=0.0, patience=100, freeze=0, save_period=-1, local_rank=-1, entity=None, upload_dataset=False, bbox_interval=-1, artifact_alias=latest\n    fatal: could not read Username for 'https://github.com': No such device or address\n    \u001b[34m\u001b[1mgithub: \u001b[0mCommand 'git fetch && git config --get remote.origin.url' returned non-zero exit status 128.\n    YOLOv5 \ud83d\ude80 c726e14 torch 1.10.0+cu111 CUDA:0 (Tesla K80, 11441.1875MB)\n    \n    \u001b[34m\u001b[1mhyperparameters: \u001b[0mlr0=0.01, lrf=0.1, momentum=0.937, weight_decay=0.0005, warmup_epochs=3.0, warmup_momentum=0.8, warmup_bias_lr=0.1, box=0.05, cls=0.5, cls_pw=1.0, obj=1.0, obj_pw=1.0, iou_t=0.2, anchor_t=4.0, fl_gamma=0.0, hsv_h=0.015, hsv_s=0.7, hsv_v=0.4, degrees=0.0, translate=0.1, scale=0.5, shear=0.0, perspective=0.0, flipud=0.0, fliplr=0.5, mosaic=1.0, mixup=0.0, copy_paste=0.0\n    \u001b[34m\u001b[1mWeights & Biases: \u001b[0mrun 'pip install wandb' to automatically track and visualize YOLOv5 \ud83d\ude80 runs (RECOMMENDED)\n    \u001b[34m\u001b[1mTensorBoard: \u001b[0mStart with 'tensorboard --logdir runs/train', view at http://localhost:6006/\n    \n                     from  n    params  module                                  arguments                     \n      0                -1  1      1760  models.common.Conv                      [3, 16, 6, 2, 2]              \n      1                -1  1      4672  models.common.Conv                      [16, 32, 3, 2]                \n      2                -1  1      4800  models.common.C3                        [32, 32, 1]                   \n      3                -1  1     18560  models.common.Conv                      [32, 64, 3, 2]                \n      4                -1  2     29184  models.common.C3                        [64, 64, 2]                   \n      5                -1  1     73984  models.common.Conv                      [64, 128, 3, 2]               \n      6                -1  3    156928  models.common.C3                        [128, 128, 3]                 \n      7                -1  1    295424  models.common.Conv                      [128, 256, 3, 2]              \n      8                -1  1    296448  models.common.C3                        [256, 256, 1]                 \n      9                -1  1    164608  models.common.SPPF                      [256, 256, 5]                 \n     10                -1  1     33024  models.common.Conv                      [256, 128, 1, 1]              \n     11                -1  1         0  torch.nn.modules.upsampling.Upsample    [None, 2, 'nearest']          \n     12           [-1, 6]  1         0  models.common.Concat                    [1]                           \n     13                -1  1     90880  models.common.C3                        [256, 128, 1, False]          \n     14                -1  1      8320  models.common.Conv                      [128, 64, 1, 1]               \n     15                -1  1         0  torch.nn.modules.upsampling.Upsample    [None, 2, 'nearest']          \n     16           [-1, 4]  1         0  models.common.Concat                    [1]                           \n     17                -1  1     22912  models.common.C3                        [128, 64, 1, False]           \n     18                -1  1     36992  models.common.Conv                      [64, 64, 3, 2]                \n     19          [-1, 14]  1         0  models.common.Concat                    [1]                           \n     20                -1  1     74496  models.common.C3                        [128, 128, 1, False]          \n     21                -1  1    147712  models.common.Conv                      [128, 128, 3, 2]              \n     22          [-1, 10]  1         0  models.common.Concat                    [1]                           \n     23                -1  1    296448  models.common.C3                        [256, 256, 1, False]          \n     24      [17, 20, 23]  1     12177  models.yolo.Detect                      [4, [[10, 13, 16, 30, 33, 23], [30, 61, 62, 45, 59, 119], [116, 90, 156, 198, 373, 326]], [64, 128, 256]]\n    /usr/local/lib/python3.7/dist-packages/torch/functional.py:445: UserWarning: torch.meshgrid: in an upcoming release, it will be required to pass the indexing argument. (Triggered internally at  ../aten/src/ATen/native/TensorShape.cpp:2157.)\n      return _VF.meshgrid(tensors, **kwargs)  # type: ignore[attr-defined]\n    Model Summary: 270 layers, 1769329 parameters, 1769329 gradients, 4.2 GFLOPs\n    \n    Transferred 342/349 items from weights/yolov5n.pt\n    Scaled weight_decay = 0.0005\n    \u001b[34m\u001b[1moptimizer:\u001b[0m SGD with parameter groups 57 weight, 60 weight (no decay), 60 bias\n    \u001b[34m\u001b[1malbumentations: \u001b[0mversion 1.0.3 required by YOLOv5, but version 0.1.12 is currently installed\n    \u001b[34m\u001b[1mtrain: \u001b[0mScanning '/content/drive/MyDrive/yolo_v5/data/drowsy_training/train/labels' images and labels...1580 found, 0 missing, 1 empty, 0 corrupted: 100% 1580/1580 [02:12<00:00, 11.95it/s]\n    \u001b[34m\u001b[1mtrain: \u001b[0mNew cache created: /content/drive/MyDrive/yolo_v5/data/drowsy_training/train/labels.cache\n    \u001b[34m\u001b[1mtrain: \u001b[0mCaching images (1.1GB ram): 100% 1580/1580 [00:14<00:00, 109.27it/s]\n    \u001b[34m\u001b[1mval: \u001b[0mScanning '/content/drive/MyDrive/yolo_v5/data/drowsy_training/test/labels' images and labels...395 found, 0 missing, 0 empty, 0 corrupted: 100% 395/395 [00:32<00:00, 12.27it/s]\n    \u001b[34m\u001b[1mval: \u001b[0mNew cache created: /content/drive/MyDrive/yolo_v5/data/drowsy_training/test/labels.cache\n    \u001b[34m\u001b[1mval: \u001b[0mCaching images (0.3GB ram): 100% 395/395 [00:03<00:00, 106.88it/s]\n    Plotting labels... \n    \n    \u001b[34m\u001b[1mautoanchor: \u001b[0mAnalyzing anchors... anchors/target = 5.28, Best Possible Recall (BPR) = 1.0000\n    Image sizes 640 train, 640 val\n    Using 2 dataloader workers\n    Logging results to \u001b[1mruns/train/drowsy_result\u001b[0m\n    Starting training for 600 epochs...\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n         0/599     1.74G   0.08748   0.02831   0.04558        21       640: 100% 99/99 [01:16<00:00,  1.30it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:05<00:00,  2.39it/s]\n                     all        395        395     0.0376      0.414     0.0368    0.00788\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n         1/599     1.74G   0.05859   0.02429   0.03961        24       640: 100% 99/99 [01:13<00:00,  1.35it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  2.77it/s]\n                     all        395        395      0.467       0.53      0.252     0.0583\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n         2/599     1.74G   0.05522   0.01857   0.03859        34       640: 100% 99/99 [01:12<00:00,  1.37it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  2.94it/s]\n                     all        395        395      0.637       0.56      0.436      0.184\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n         3/599     1.74G   0.04995   0.01562    0.0345        32       640: 100% 99/99 [01:12<00:00,  1.37it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395       0.54      0.633      0.431      0.154\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n         4/599     1.74G   0.04709   0.01436   0.03054        26       640: 100% 99/99 [01:12<00:00,  1.37it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  2.97it/s]\n                     all        395        395      0.726      0.695      0.648      0.301\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n         5/599     1.74G   0.04968     0.014   0.02725        32       640: 100% 99/99 [01:12<00:00,  1.37it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.609      0.726      0.588      0.173\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n         6/599     1.74G   0.04705     0.013   0.02058        19       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.00it/s]\n                     all        395        395      0.857       0.67      0.699      0.322\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n         7/599     1.74G   0.04423   0.01274   0.02063        34       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.916      0.667       0.77      0.417\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n         8/599     1.74G   0.04403   0.01257   0.01788        25       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.00it/s]\n                     all        395        395       0.65      0.829      0.817      0.374\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n         9/599     1.74G   0.04325   0.01233   0.01633        31       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.771      0.919      0.871      0.464\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        10/599     1.74G   0.03971   0.01189    0.0152        27       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.819      0.834       0.89      0.485\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        11/599     1.74G   0.03737   0.01164   0.01475        27       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.00it/s]\n                     all        395        395      0.856      0.863      0.903      0.506\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        12/599     1.74G   0.03754   0.01138   0.01425        25       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.862      0.919      0.915      0.568\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        13/599     1.74G   0.03466   0.01147   0.01264        24       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.885      0.877      0.915      0.531\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        14/599     1.74G   0.03317   0.01113   0.01223        28       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.949      0.926       0.98      0.559\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        15/599     1.74G   0.03338   0.01107   0.01143        22       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.923      0.923       0.93      0.554\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        16/599     1.74G   0.03274   0.01097   0.01178        27       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.928      0.876       0.94      0.565\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        17/599     1.74G   0.03139   0.01111   0.01144        21       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.904      0.931       0.95       0.59\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        18/599     1.74G   0.03123   0.01075   0.01057        22       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.912      0.974      0.969      0.616\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        19/599     1.74G   0.03103   0.01089   0.01037        28       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.868      0.879      0.924      0.553\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        20/599     1.74G    0.0302   0.01053   0.01023        24       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.05it/s]\n                     all        395        395      0.947      0.964      0.968      0.639\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        21/599     1.74G   0.03036   0.01033    0.0105        22       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.963      0.937      0.969      0.608\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        22/599     1.74G   0.02928   0.01041   0.01051        29       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.06it/s]\n                     all        395        395      0.926      0.971      0.972      0.606\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        23/599     1.74G    0.0293   0.01034  0.009059        28       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.925      0.937      0.961      0.641\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        24/599     1.74G   0.02852   0.01016   0.00891        22       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.965      0.945      0.974      0.629\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        25/599     1.74G   0.02887   0.01019  0.009674        24       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.05it/s]\n                     all        395        395      0.938      0.965      0.976      0.641\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        26/599     1.74G   0.02771  0.009977  0.008686        25       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.06it/s]\n                     all        395        395      0.931      0.957      0.961      0.622\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        27/599     1.74G   0.02847  0.009756   0.00941        22       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.08it/s]\n                     all        395        395      0.973      0.973      0.985      0.645\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        28/599     1.74G   0.02785    0.0104  0.009493        30       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.953      0.944       0.97      0.653\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        29/599     1.74G   0.02748   0.01007  0.007801        22       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.06it/s]\n                     all        395        395       0.96       0.97      0.982      0.672\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        30/599     1.74G   0.02668  0.009443  0.008176        21       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.952      0.945       0.96       0.65\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        31/599     1.74G     0.027  0.009921  0.008169        23       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.942      0.968      0.973      0.651\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        32/599     1.74G   0.02635  0.009686  0.008653        20       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.06it/s]\n                     all        395        395      0.965      0.945      0.977      0.678\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        33/599     1.74G   0.02679    0.0101  0.007572        26       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.943      0.977      0.983      0.658\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        34/599     1.74G   0.02654  0.009766  0.008189        21       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.976      0.964      0.989      0.664\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        35/599     1.74G   0.02656  0.009601  0.007555        24       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.00it/s]\n                     all        395        395      0.954       0.98      0.983      0.653\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        36/599     1.74G   0.02595  0.009654  0.007568        23       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.00it/s]\n                     all        395        395      0.946      0.975       0.98      0.656\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        37/599     1.74G   0.02629  0.009721   0.00757        27       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.06it/s]\n                     all        395        395      0.952       0.97       0.98      0.667\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        38/599     1.74G   0.02595  0.009426  0.007534        27       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.06it/s]\n                     all        395        395      0.973       0.97      0.987      0.666\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        39/599     1.74G   0.02536  0.009648  0.007676        27       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.963      0.954      0.982      0.672\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        40/599     1.74G   0.02519  0.009536  0.006843        33       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.07it/s]\n                     all        395        395      0.961       0.97      0.985       0.68\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        41/599     1.74G   0.02544  0.009618  0.007503        30       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.951      0.982      0.987      0.679\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        42/599     1.74G   0.02557  0.009259  0.007165        22       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.05it/s]\n                     all        395        395      0.976      0.965      0.985      0.678\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        43/599     1.74G   0.02491  0.009615  0.007558        28       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.954      0.947      0.975      0.688\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        44/599     1.74G   0.02527  0.009555  0.006635        28       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.05it/s]\n                     all        395        395      0.965      0.934      0.979      0.681\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        45/599     1.74G   0.02473  0.009339  0.007376        26       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.07it/s]\n                     all        395        395      0.926      0.951      0.968      0.657\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        46/599     1.74G   0.02528  0.009329  0.006981        35       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.08it/s]\n                     all        395        395      0.973      0.957      0.969      0.682\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        47/599     1.74G   0.02489  0.009209  0.006547        26       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.05it/s]\n                     all        395        395      0.972      0.949      0.981      0.685\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        48/599     1.74G   0.02455  0.009184  0.006815        19       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.945      0.982      0.986      0.705\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        49/599     1.74G   0.02539  0.009327  0.007314        33       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.943      0.968      0.981       0.68\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        50/599     1.74G   0.02463  0.009467  0.006989        24       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.941      0.975      0.982      0.688\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        51/599     1.74G   0.02458  0.009318  0.006869        23       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.07it/s]\n                     all        395        395      0.962      0.945      0.974      0.683\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        52/599     1.74G   0.02456  0.009411  0.006634        26       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.948      0.972      0.974      0.682\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        53/599     1.74G   0.02406  0.009154  0.006741        24       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.05it/s]\n                     all        395        395      0.974      0.949      0.978      0.678\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        54/599     1.74G   0.02457   0.00933  0.007071        29       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.986      0.963      0.985      0.697\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        55/599     1.74G   0.02357  0.009057  0.006263        22       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.05it/s]\n                     all        395        395      0.958      0.971       0.98        0.7\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        56/599     1.74G   0.02389  0.008948  0.006609        32       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.962      0.951      0.979      0.685\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        57/599     1.74G   0.02406  0.009073  0.006724        23       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395       0.99      0.943      0.986      0.703\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        58/599     1.74G     0.024  0.008948  0.006251        19       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.972      0.945      0.977      0.692\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        59/599     1.74G   0.02374  0.009143  0.007082        27       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.941      0.964      0.974      0.697\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        60/599     1.74G   0.02438  0.009316  0.006084        27       640: 100% 99/99 [01:12<00:00,  1.37it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.05it/s]\n                     all        395        395      0.948      0.987      0.984      0.696\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        61/599     1.74G    0.0238  0.009186  0.006618        26       640: 100% 99/99 [01:12<00:00,  1.37it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.958      0.934      0.959      0.676\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        62/599     1.74G   0.02409  0.009133  0.006551        27       640: 100% 99/99 [01:12<00:00,  1.37it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.941       0.96      0.981      0.688\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        63/599     1.74G   0.02349  0.009284  0.006149        19       640: 100% 99/99 [01:12<00:00,  1.37it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.965      0.953      0.979        0.7\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        64/599     1.74G   0.02365  0.009179  0.006124        30       640: 100% 99/99 [01:12<00:00,  1.37it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.948      0.964      0.983       0.69\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        65/599     1.74G    0.0232  0.009003  0.006017        25       640: 100% 99/99 [01:12<00:00,  1.37it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.954      0.968      0.974      0.682\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        66/599     1.74G   0.02331  0.008943  0.006336        20       640: 100% 99/99 [01:12<00:00,  1.37it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.979      0.949      0.985      0.703\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        67/599     1.74G   0.02311   0.00893   0.00682        17       640: 100% 99/99 [01:12<00:00,  1.37it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.955      0.961      0.976      0.702\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        68/599     1.74G   0.02337  0.008925  0.006669        22       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.05it/s]\n                     all        395        395      0.974      0.953      0.981      0.698\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        69/599     1.74G   0.02308  0.008994  0.005657        20       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.985      0.967      0.987       0.71\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        70/599     1.74G   0.02348  0.008853  0.005779        20       640: 100% 99/99 [01:12<00:00,  1.37it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.00it/s]\n                     all        395        395      0.966      0.972       0.98      0.693\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        71/599     1.74G   0.02315  0.008783  0.005233        21       640: 100% 99/99 [01:12<00:00,  1.37it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  2.98it/s]\n                     all        395        395      0.988      0.939      0.985      0.687\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        72/599     1.74G   0.02246  0.008827  0.006569        30       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.967      0.976      0.982      0.702\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        73/599     1.74G    0.0229   0.00893  0.005909        30       640: 100% 99/99 [01:12<00:00,  1.37it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.943      0.983      0.982      0.706\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        74/599     1.74G   0.02283   0.00894   0.00561        23       640: 100% 99/99 [01:12<00:00,  1.37it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.974      0.965      0.987      0.715\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        75/599     1.74G   0.02364  0.009041  0.005973        23       640: 100% 99/99 [01:12<00:00,  1.37it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.932      0.981      0.982      0.699\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        76/599     1.74G   0.02248  0.008912   0.00528        26       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.953      0.963      0.979      0.687\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        77/599     1.74G   0.02248  0.008787  0.006526        17       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.05it/s]\n                     all        395        395      0.942       0.99      0.985       0.72\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        78/599     1.74G   0.02255  0.008759  0.005722        29       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.952       0.98      0.982      0.708\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        79/599     1.74G   0.02216  0.008708  0.005355        24       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.00it/s]\n                     all        395        395      0.993      0.957      0.989      0.719\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        80/599     1.74G   0.02254  0.008902   0.00524        19       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.989      0.953      0.987      0.703\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        81/599     1.74G   0.02275  0.008673  0.005183        22       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  2.99it/s]\n                     all        395        395       0.96      0.977      0.985      0.712\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        82/599     1.74G   0.02256  0.008701  0.006492        26       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.934      0.997      0.981      0.715\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        83/599     1.74G   0.02272  0.009144  0.006426        25       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.06it/s]\n                     all        395        395      0.977      0.965      0.983      0.715\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        84/599     1.74G   0.02268  0.008714  0.005719        28       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.959      0.971      0.981      0.714\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        85/599     1.74G   0.02222  0.008674  0.005513        31       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.955      0.979      0.985      0.708\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        86/599     1.74G   0.02227  0.008546   0.00571        28       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.976      0.947      0.986      0.723\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        87/599     1.74G   0.02182  0.008696   0.00578        17       640: 100% 99/99 [01:12<00:00,  1.37it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  2.94it/s]\n                     all        395        395      0.951      0.975      0.979      0.713\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        88/599     1.74G    0.0221  0.008706  0.005423        30       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.963      0.991      0.988       0.72\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        89/599     1.74G    0.0223  0.008642  0.005767        28       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.974      0.982       0.99      0.722\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        90/599     1.74G   0.02226  0.008818  0.005554        25       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.932      0.978      0.982      0.717\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        91/599     1.74G   0.02182  0.008824  0.005216        29       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  2.99it/s]\n                     all        395        395      0.945       0.96      0.977       0.71\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        92/599     1.74G   0.02161  0.008817  0.004797        28       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.974      0.961      0.982      0.718\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        93/599     1.74G   0.02189  0.008732  0.005854        27       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.00it/s]\n                     all        395        395       0.96      0.984      0.986       0.72\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        94/599     1.74G   0.02175  0.008338  0.005007        16       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.00it/s]\n                     all        395        395      0.966      0.981      0.988      0.726\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        95/599     1.74G   0.02211  0.008427  0.004715        27       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  2.99it/s]\n                     all        395        395      0.978      0.952      0.987      0.726\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        96/599     1.74G   0.02166  0.008638  0.005601        21       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.973      0.982      0.987      0.739\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        97/599     1.74G   0.02188  0.008611  0.005441        27       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.979       0.97      0.989      0.734\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        98/599     1.74G   0.02175   0.00862  0.006075        24       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.981      0.972      0.989      0.728\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n        99/599     1.74G   0.02187  0.008855  0.005044        29       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.956      0.982      0.989      0.725\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       100/599     1.74G   0.02158  0.008471  0.005167        28       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.00it/s]\n                     all        395        395      0.961      0.977      0.987      0.722\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       101/599     1.74G   0.02172   0.00871  0.005269        25       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.988      0.949      0.988       0.71\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       102/599     1.74G   0.02145  0.008713  0.004997        20       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  2.99it/s]\n                     all        395        395      0.976      0.955      0.986      0.725\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       103/599     1.74G   0.02171  0.008662  0.005079        25       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.974       0.98      0.989      0.738\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       104/599     1.74G   0.02161   0.00845  0.005505        30       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.05it/s]\n                     all        395        395      0.971      0.975      0.988      0.731\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       105/599     1.74G   0.02118  0.008513  0.005069        26       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.954      0.978      0.987      0.722\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       106/599     1.74G    0.0214  0.008394  0.005441        30       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.00it/s]\n                     all        395        395      0.983      0.958      0.986      0.738\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       107/599     1.74G   0.02143  0.008781  0.005214        21       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.957      0.974      0.985      0.722\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       108/599     1.74G   0.02114  0.008429   0.00478        23       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.985      0.943      0.988      0.729\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       109/599     1.74G   0.02123  0.008521  0.005378        26       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.05it/s]\n                     all        395        395      0.972      0.982       0.99      0.733\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       110/599     1.74G   0.02121  0.008363  0.005843        24       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.05it/s]\n                     all        395        395      0.968      0.969      0.986      0.728\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       111/599     1.74G    0.0218  0.008556  0.005583        22       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.953      0.981      0.986      0.721\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       112/599     1.74G   0.02171  0.008436  0.005526        21       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.977      0.934      0.981      0.727\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       113/599     1.74G   0.02157  0.008468  0.004876        24       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.978      0.973      0.989       0.73\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       114/599     1.74G   0.02133  0.008632  0.004618        22       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.975      0.931      0.979      0.729\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       115/599     1.74G   0.02128  0.008676  0.005073        22       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.977      0.969      0.989      0.725\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       116/599     1.74G   0.02075  0.008365  0.004651        23       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.968       0.99      0.988      0.734\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       117/599     1.74G    0.0214  0.008556  0.004971        32       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395       0.97      0.971      0.984      0.725\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       118/599     1.74G   0.02145  0.008593  0.004526        24       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.952      0.993       0.99      0.738\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       119/599     1.74G   0.02125  0.008546  0.005104        26       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  2.99it/s]\n                     all        395        395      0.974      0.979      0.991      0.735\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       120/599     1.74G   0.02167  0.008311  0.005943        26       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.949      0.981      0.987       0.74\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       121/599     1.74G   0.02156  0.008597  0.005047        25       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.949      0.976      0.983      0.731\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       122/599     1.74G   0.02085  0.008439   0.00458        24       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.978      0.963       0.99      0.733\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       123/599     1.74G   0.02115  0.008618  0.005536        18       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.984      0.981      0.992      0.741\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       124/599     1.74G   0.02134  0.008472  0.005039        32       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.976      0.976       0.99      0.733\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       125/599     1.74G   0.02133  0.008083  0.004746        19       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.00it/s]\n                     all        395        395      0.996      0.944      0.986      0.742\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       126/599     1.74G   0.02062  0.008347  0.004571        27       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.964      0.981      0.983      0.724\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       127/599     1.74G   0.02087  0.008376  0.004563        30       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.00it/s]\n                     all        395        395      0.986      0.942      0.985      0.729\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       128/599     1.74G   0.02066   0.00839  0.004845        33       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.943      0.974      0.978      0.727\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       129/599     1.74G   0.02069  0.008314  0.005539        27       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.05it/s]\n                     all        395        395      0.961      0.984      0.986      0.722\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       130/599     1.74G   0.02078  0.008419  0.004856        18       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.977      0.962      0.985      0.728\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       131/599     1.74G    0.0206  0.008237  0.005226        23       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.953      0.983      0.985      0.735\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       132/599     1.74G   0.02053  0.008231   0.00495        25       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.965       0.96      0.978      0.726\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       133/599     1.74G   0.02062  0.008392  0.004907        25       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.961      0.971      0.985       0.74\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       134/599     1.74G   0.02072  0.008363  0.004325        23       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.06it/s]\n                     all        395        395      0.947      0.973      0.981      0.727\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       135/599     1.74G   0.02104  0.008373  0.004463        30       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.954      0.979      0.983      0.733\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       136/599     1.74G   0.02056  0.008317  0.004873        25       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.958      0.957      0.979       0.73\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       137/599     1.74G   0.02069  0.008268  0.004759        25       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.06it/s]\n                     all        395        395      0.975       0.95      0.979      0.724\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       138/599     1.74G   0.02042  0.008448  0.004799        21       640: 100% 99/99 [01:10<00:00,  1.40it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.07it/s]\n                     all        395        395      0.953      0.988      0.988      0.748\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       139/599     1.74G    0.0207  0.008328  0.003883        25       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.984      0.968      0.989      0.739\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       140/599     1.74G   0.02018  0.008295  0.005182        24       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.982      0.958      0.985      0.738\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       141/599     1.74G   0.02023    0.0081  0.004072        26       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.957      0.978      0.982      0.733\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       142/599     1.74G   0.02038  0.008245  0.004543        33       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.00it/s]\n                     all        395        395      0.952      0.975      0.977      0.723\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       143/599     1.74G   0.02067   0.00845  0.004707        23       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  2.99it/s]\n                     all        395        395      0.959      0.984      0.983      0.731\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       144/599     1.74G   0.02027  0.008521  0.004265        28       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.969      0.966      0.985      0.736\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       145/599     1.74G   0.02043  0.008119  0.005062        25       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.939      0.987      0.983      0.732\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       146/599     1.74G   0.02007  0.008283  0.004236        28       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.07it/s]\n                     all        395        395      0.994      0.949      0.989      0.741\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       147/599     1.74G   0.02008  0.008197  0.004459        25       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.969      0.975      0.989      0.724\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       148/599     1.74G   0.02055  0.008364  0.004836        23       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.00it/s]\n                     all        395        395      0.983      0.945      0.984      0.726\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       149/599     1.74G   0.02057  0.008261  0.004813        22       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.976      0.947      0.981      0.734\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       150/599     1.74G   0.02075  0.008299  0.004311        22       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.941      0.991      0.986      0.745\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       151/599     1.74G   0.02089  0.008182  0.004934        29       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.01it/s]\n                     all        395        395      0.979      0.963      0.985      0.747\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       152/599     1.74G   0.02084  0.008295  0.005211        18       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.951      0.988      0.984      0.738\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       153/599     1.74G   0.02026  0.008249  0.004443        22       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395       0.96      0.982      0.983      0.737\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       154/599     1.74G   0.02035  0.008308  0.004759        22       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.966       0.96      0.985      0.739\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       155/599     1.74G    0.0201  0.008121   0.00468        24       640: 100% 99/99 [01:10<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.977      0.976      0.983      0.738\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       156/599     1.74G   0.02021  0.008252  0.004002        21       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.00it/s]\n                     all        395        395      0.957      0.986      0.986      0.741\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       157/599     1.74G   0.01997  0.008317  0.004164        26       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  2.99it/s]\n                     all        395        395       0.95      0.983      0.987      0.728\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       158/599     1.74G   0.02012  0.008256  0.004311        20       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.958      0.976      0.988      0.751\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       159/599     1.74G   0.02008   0.00813   0.00419        22       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.978      0.967      0.985      0.746\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       160/599     1.74G   0.02003  0.008076  0.004604        22       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.982      0.959      0.984      0.748\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       161/599     1.74G   0.02045  0.008456  0.004292        25       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.971       0.97      0.987      0.752\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       162/599     1.74G   0.02009  0.008252  0.003991        20       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.00it/s]\n                     all        395        395      0.974      0.986       0.99      0.744\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       163/599     1.74G   0.01986  0.008262   0.00459        26       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395       0.98      0.964      0.984      0.743\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       164/599     1.74G   0.02022  0.008126   0.00421        28       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.978      0.967      0.985      0.745\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       165/599     1.74G   0.02012  0.008067  0.004472        28       640: 100% 99/99 [01:11<00:00,  1.38it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.967      0.978      0.983      0.756\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       166/599     1.74G   0.01957   0.00818  0.003841        19       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.03it/s]\n                     all        395        395      0.945      0.982      0.979      0.743\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       167/599     1.74G   0.01973  0.008272  0.004133        20       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.05it/s]\n                     all        395        395      0.971      0.952      0.979      0.749\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       168/599     1.74G   0.01961  0.008119    0.0039        27       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.05it/s]\n                     all        395        395       0.95      0.975      0.973      0.741\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       169/599     1.74G   0.02014  0.008332  0.004771        31       640: 100% 99/99 [01:10<00:00,  1.40it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.04it/s]\n                     all        395        395      0.965      0.973      0.979       0.74\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       170/599     1.74G   0.02005  0.008266  0.004365        25       640: 100% 99/99 [01:10<00:00,  1.40it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395       0.97      0.976      0.987      0.747\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       171/599     1.74G   0.02015  0.008167  0.004157        32       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.05it/s]\n                     all        395        395      0.952      0.988      0.986      0.745\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       172/599     1.74G   0.01994  0.008248  0.004343        22       640: 100% 99/99 [01:11<00:00,  1.39it/s]\n                   Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 13/13 [00:04<00:00,  3.02it/s]\n                     all        395        395      0.959      0.985      0.988      0.741\n    \n         Epoch   gpu_mem       box       obj       cls    labels  img_size\n       173/599     1.74G   0.02012  0.008023  0.003782        33       640:  29% 29/99 [00:20<00:50,  1.39it/s]\n\n\n```python\n!pip install -U coremltools onnx scikit-learn==0.19.2\n```\n\n    Collecting coremltools\n      Downloading coremltools-5.1.0-cp37-none-manylinux1_x86_64.whl (1.6 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1.6 MB 5.3 MB/s \n    \u001b[?25hCollecting onnx\n      Downloading onnx-1.10.2-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (12.7 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 12.7 MB 32.1 MB/s \n    \u001b[?25hCollecting scikit-learn==0.19.2\n      Downloading scikit_learn-0.19.2-cp37-cp37m-manylinux1_x86_64.whl (4.9 MB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4.9 MB 34.5 MB/s \n    \u001b[?25hRequirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from coremltools) (21.3)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from coremltools) (1.7.1)\n    Requirement already satisfied: numpy>=1.14.5 in /usr/local/lib/python3.7/dist-packages (from coremltools) (1.19.5)\n    Requirement already satisfied: protobuf>=3.1.0 in /usr/local/lib/python3.7/dist-packages (from coremltools) (3.17.3)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from coremltools) (4.62.3)\n    Requirement already satisfied: six>=1.9 in /usr/local/lib/python3.7/dist-packages (from protobuf>=3.1.0->coremltools) (1.15.0)\n    Requirement already satisfied: typing-extensions>=3.6.2.1 in /usr/local/lib/python3.7/dist-packages (from onnx) (3.10.0.2)\n    Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->coremltools) (3.0.6)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->coremltools) (1.2.1)\n    Installing collected packages: scikit-learn, onnx, coremltools\n      Attempting uninstall: scikit-learn\n        Found existing installation: scikit-learn 1.0.1\n        Uninstalling scikit-learn-1.0.1:\n          Successfully uninstalled scikit-learn-1.0.1\n    \u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n    yellowbrick 1.3.post1 requires scikit-learn>=0.20, but you have scikit-learn 0.19.2 which is incompatible.\n    imbalanced-learn 0.8.1 requires scikit-learn>=0.24, but you have scikit-learn 0.19.2 which is incompatible.\u001b[0m\n    Successfully installed coremltools-5.1.0 onnx-1.10.2 scikit-learn-0.19.2\n\n\n\n```python\n!python export.py --weights runs/train/drowsy_result/weights/best.pt   --data data/data.yaml \n```\n\n    Downloading https://ultralytics.com/assets/Arial.ttf to /root/.config/Ultralytics/Arial.ttf...\n    \u001b[34m\u001b[1mexport: \u001b[0mdata=data/data.yaml, weights=runs/train/drowsy_result/weights/best.pt, imgsz=[640, 640], batch_size=1, device=cpu, half=False, inplace=False, train=False, optimize=False, int8=False, dynamic=False, simplify=False, opset=13, topk_per_class=100, topk_all=100, iou_thres=0.45, conf_thres=0.25, include=['torchscript', 'onnx']\n    YOLOv5 \ud83d\ude80 c726e14 torch 1.10.0+cu111 CPU\n    \n    Fusing layers... \n    /usr/local/lib/python3.7/dist-packages/torch/functional.py:445: UserWarning: torch.meshgrid: in an upcoming release, it will be required to pass the indexing argument. (Triggered internally at  ../aten/src/ATen/native/TensorShape.cpp:2157.)\n      return _VF.meshgrid(tensors, **kwargs)  # type: ignore[attr-defined]\n    Model Summary: 213 layers, 1764577 parameters, 0 gradients, 4.2 GFLOPs\n    \n    \u001b[34m\u001b[1mPyTorch:\u001b[0m starting from runs/train/drowsy_result/weights/best.pt (14.7 MB)\n    \n    \u001b[34m\u001b[1mTorchScript:\u001b[0m starting export with torch 1.10.0+cu111...\n    /content/drive/MyDrive/yolo_v5/models/yolo.py:60: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!\n      if self.grid[i].shape[2:4] != x[i].shape[2:4] or self.onnx_dynamic:\n    /content/drive/MyDrive/yolo_v5/models/yolo.py:60: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!\n      if self.grid[i].shape[2:4] != x[i].shape[2:4] or self.onnx_dynamic:\n    \u001b[34m\u001b[1mTorchScript:\u001b[0m export success, saved as runs/train/drowsy_result/weights/best.torchscript.pt (7.5 MB)\n    \n    \u001b[34m\u001b[1mONNX:\u001b[0m starting export with onnx 1.10.2...\n    /content/drive/MyDrive/yolo_v5/models/yolo.py:60: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!\n      if self.grid[i].shape[2:4] != x[i].shape[2:4] or self.onnx_dynamic:\n    WARNING: The shape inference of prim::Constant type is missing, so it may result in wrong shape inference for the exported graph. Please consider adding it in symbolic function.\n    WARNING: The shape inference of prim::Constant type is missing, so it may result in wrong shape inference for the exported graph. Please consider adding it in symbolic function.\n    WARNING: The shape inference of prim::Constant type is missing, so it may result in wrong shape inference for the exported graph. Please consider adding it in symbolic function.\n    WARNING: The shape inference of prim::Constant type is missing, so it may result in wrong shape inference for the exported graph. Please consider adding it in symbolic function.\n    WARNING: The shape inference of prim::Constant type is missing, so it may result in wrong shape inference for the exported graph. Please consider adding it in symbolic function.\n    WARNING: The shape inference of prim::Constant type is missing, so it may result in wrong shape inference for the exported graph. Please consider adding it in symbolic function.\n    \u001b[34m\u001b[1mONNX:\u001b[0m export success, saved as runs/train/drowsy_result/weights/best.onnx (7.5 MB)\n    \u001b[34m\u001b[1mONNX:\u001b[0m run --dynamic ONNX model inference with: 'python detect.py --weights runs/train/drowsy_result/weights/best.onnx'\n    \n    Export complete (11.34s)\n    Results saved to \u001b[1m/content/drive/My Drive/yolo_v5/runs/train/drowsy_result/weights\u001b[0m\n    Visualize with https://netron.app\n\n\n\n```python\n!python drowsy_detect.py --weights runs/train/drowsy_result/weights/best.pt --source data/test_videos/drowsy-01.mp4\n```\n\n    pygame 2.1.2 (SDL 2.0.16, Python 3.7.12)\n    Hello from the pygame community. https://www.pygame.org/contribute.html\n    Downloading https://ultralytics.com/assets/Arial.ttf to /root/.config/Ultralytics/Arial.ttf...\n    \u001b[34m\u001b[1mdrowsy_detect: \u001b[0mweights=['runs/train/drowsy_result/weights/best.pt'], source=data/test_videos/drowsy-01.mp4, imgsz=[640, 640], conf_thres=0.25, iou_thres=0.45, max_det=1000, device=, view_img=False, save_txt=False, save_conf=False, save_crop=False, nosave=False, classes=None, agnostic_nms=False, augment=False, visualize=False, update=False, project=runs/detect, name=exp, exist_ok=False, line_thickness=3, hide_labels=False, hide_conf=False, half=False, dnn=False\n    YOLOv5 \ud83d\ude80 2021-11-5 torch 1.10.0+cu111 CUDA:0 (Tesla K80, 11441.1875MB)\n    \n    Fusing layers... \n    /usr/local/lib/python3.7/dist-packages/torch/functional.py:445: UserWarning: torch.meshgrid: in an upcoming release, it will be required to pass the indexing argument. (Triggered internally at  ../aten/src/ATen/native/TensorShape.cpp:2157.)\n      return _VF.meshgrid(tensors, **kwargs)  # type: ignore[attr-defined]\n    Model Summary: 213 layers, 1764577 parameters, 0 gradients, 4.2 GFLOPs\n    video 1/1 (1/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.020s)\n    video 1/1 (2/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (3/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (4/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (5/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (6/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (7/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (8/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (9/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (10/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (11/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (12/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (13/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (14/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (15/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (16/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (17/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (18/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.019s)\n    video 1/1 (19/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (20/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.017s)\n    video 1/1 (21/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (22/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (23/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (24/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.017s)\n    video 1/1 (25/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (26/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (27/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (28/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (29/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (30/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    video 1/1 (31/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: 640x352 1 normal, Done. (0.018s)\n    ALSA lib confmisc.c:767:(parse_card) cannot find card '0'\n    ALSA lib conf.c:4528:(_snd_config_evaluate) function snd_func_card_driver returned error: No such file or directory\n    ALSA lib confmisc.c:392:(snd_func_concat) error evaluating strings\n    ALSA lib conf.c:4528:(_snd_config_evaluate) function snd_func_concat returned error: No such file or directory\n    ALSA lib confmisc.c:1246:(snd_func_refer) error evaluating name\n    ALSA lib conf.c:4528:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory\n    ALSA lib conf.c:5007:(snd_config_expand) Evaluate error: No such file or directory\n    ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM default\n    video 1/1 (32/326) /content/drive/My Drive/yolo_v5/data/test_videos/drowsy-01.mp4: Traceback (most recent call last):\n      File \"drowsy_detect.py\", line 528, in <module>\n        main(opt)\n      File \"drowsy_detect.py\", line 523, in main\n        run(**vars(opt))\n      File \"/usr/local/lib/python3.7/dist-packages/torch/autograd/grad_mode.py\", line 28, in decorate_context\n        return func(*args, **kwargs)\n      File \"drowsy_detect.py\", line 312, in run\n        pygame.mixer.music.load(\"5.mp3\")\n    pygame.error: mixer not initialized\n\n\n\n```python\n!python drowsy_detect.py --weights runs/train/drowsy_result/weights/best.pt --source data/drowsy_training/test/images --hide-conf\n```\n\n    \u001b[34m\u001b[1mdrowsy_detect: \u001b[0mweights=['runs/train/drowsy_result/weights/best.pt'], source=data/drowsy_training/test/images, imgsz=[640, 640], conf_thres=0.25, iou_thres=0.45, max_det=1000, device=, view_img=False, save_txt=False, save_conf=False, save_crop=False, nosave=False, classes=None, agnostic_nms=False, augment=False, visualize=False, update=False, project=runs/detect, name=exp, exist_ok=False, line_thickness=3, hide_labels=False, hide_conf=True, half=False, dnn=False\n    YOLOv5 \ud83d\ude80 2021-11-5 torch 1.10.0+cu111 CUDA:0 (Tesla K80, 11441.1875MB)\n    \n    Fusing layers... \n    /usr/local/lib/python3.7/dist-packages/torch/functional.py:445: UserWarning: torch.meshgrid: in an upcoming release, it will be required to pass the indexing argument. (Triggered internally at  ../aten/src/ATen/native/TensorShape.cpp:2157.)\n      return _VF.meshgrid(tensors, **kwargs)  # type: ignore[attr-defined]\n    Model Summary: 213 layers, 1764577 parameters, 0 gradients, 4.2 GFLOPs\n    image 1/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-1040.jpg: 640x384 1 drowsy, Done. (0.020s)\n    image 2/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-1064.jpg: 640x384 1 drowsy, Done. (0.018s)\n    image 3/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-1152.jpg: 640x384 1 drowsy, Done. (0.019s)\n    image 4/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-1208.jpg: 640x384 1 drowsy, Done. (0.044s)\n    image 5/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-1240.jpg: 640x384 1 drowsy, Done. (0.019s)\n    image 6/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-1304.jpg: 640x384 1 drowsy#2, Done. (0.018s)\n    image 7/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-1312.jpg: 640x384 1 drowsy#2, Done. (0.019s)\n    image 8/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-192.jpg: 640x384 1 normal, Done. (0.018s)\n    image 9/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-2132.jpg: 640x384 1 drowsy, Done. (0.018s)\n    image 10/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-2148.jpg: 640x384 1 yawning, Done. (0.018s)\n    image 11/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-2152.jpg: 640x384 1 yawning, Done. (0.019s)\n    image 12/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-2156.jpg: 640x384 1 yawning, Done. (0.019s)\n    image 13/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-2166.jpg: 640x384 1 yawning, Done. (0.018s)\n    image 14/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-2178.jpg: 640x384 1 yawning, Done. (0.019s)\n    image 15/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-2180.jpg: 640x384 1 yawning, Done. (0.019s)\n    image 16/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-2184.jpg: 640x384 1 yawning, Done. (0.018s)\n    image 17/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-2202.jpg: 640x384 1 yawning, Done. (0.018s)\n    image 18/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-2206.jpg: 640x384 1 yawning, Done. (0.018s)\n    image 19/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-224.jpg: 640x384 1 normal, Done. (0.018s)\n    image 20/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-288.jpg: 640x384 1 normal, Done. (0.026s)\n    image 21/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-296.jpg: 640x384 1 normal, Done. (0.019s)\n    image 22/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-8.jpg: 640x384 1 drowsy, Done. (0.019s)\n    image 23/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-80.jpg: 640x384 1 normal, Done. (0.018s)\n    image 24/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame00-96.jpg: 640x384 1 normal, Done. (0.018s)\n    image 25/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-1000.jpg: 640x352 1 normal, Done. (0.018s)\n    image 26/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-1040.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 27/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-1048.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 28/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-1104.jpg: 640x352 1 drowsy, Done. (0.018s)\n    image 29/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-112.jpg: 640x352 1 normal, Done. (0.018s)\n    image 30/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-1120.jpg: 640x352 1 normal, Done. (0.018s)\n    image 31/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-1192.jpg: 640x352 1 normal, Done. (0.018s)\n    image 32/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-1208.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 33/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-1264.jpg: 640x352 1 normal, Done. (0.018s)\n    image 34/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-1304.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 35/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-184.jpg: 640x352 1 normal, Done. (0.017s)\n    image 36/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-192.jpg: 640x352 1 normal, Done. (0.018s)\n    image 37/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-2032.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 38/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-2048.jpg: 640x352 1 yawning, Done. (0.022s)\n    image 39/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-2050.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 40/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-2068.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 41/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-2074.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 42/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-2086.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 43/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-2098.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 44/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-2110.jpg: 640x352 1 normal, Done. (0.018s)\n    image 45/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-2184.jpg: 640x352 1 normal, Done. (0.018s)\n    image 46/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-2186.jpg: 640x352 1 normal, Done. (0.018s)\n    image 47/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-24.jpg: 640x352 1 normal, Done. (0.018s)\n    image 48/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-296.jpg: 640x352 1 normal, Done. (0.018s)\n    image 49/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame01-80.jpg: 640x352 1 normal, Done. (0.018s)\n    image 50/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-0.jpg: 640x352 1 normal, Done. (0.018s)\n    image 51/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-1056.jpg: 640x352 1 drowsy, Done. (0.018s)\n    image 52/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-1072.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 53/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-1128.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 54/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-1168.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 55/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-120.jpg: 640x352 1 normal, Done. (0.018s)\n    image 56/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-1200.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 57/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-1264.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 58/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-1272.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 59/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-2096.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 60/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-2102.jpg: 640x352 1 yawning, Done. (0.022s)\n    image 61/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-2114.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 62/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-2126.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 63/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-2132.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 64/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-2150.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 65/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-2152.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 66/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-2168.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 67/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-2176.jpg: 640x352 1 yawning, Done. (0.017s)\n    image 68/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-2186.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 69/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-2200.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 70/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-2204.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 71/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-2230.jpg: 640x352 1 normal, Done. (0.018s)\n    image 72/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-2234.jpg: 640x352 1 normal, Done. (0.018s)\n    image 73/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-2246.jpg: 640x352 1 normal, Done. (0.017s)\n    image 74/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-2272.jpg: 640x352 1 normal, Done. (0.018s)\n    image 75/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-2280.jpg: 640x352 1 normal, Done. (0.018s)\n    image 76/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-2288.jpg: 640x352 1 normal, Done. (0.018s)\n    image 77/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-2296.jpg: 640x352 1 normal, Done. (0.018s)\n    image 78/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-2298.jpg: 640x352 1 normal, Done. (0.018s)\n    image 79/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-288.jpg: 640x352 1 normal, Done. (0.018s)\n    image 80/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-304.jpg: 640x352 1 normal, Done. (0.018s)\n    image 81/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame02-80.jpg: 640x352 1 normal, Done. (0.018s)\n    image 82/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-1024.jpg: 640x352 1 normal, Done. (0.018s)\n    image 83/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-1032.jpg: 640x352 1 normal, Done. (0.018s)\n    image 84/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-1040.jpg: 640x352 1 normal, Done. (0.018s)\n    image 85/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-1104.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 86/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-112.jpg: 640x352 1 normal, Done. (0.018s)\n    image 87/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-1136.jpg: 640x352 1 normal, Done. (0.018s)\n    image 88/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-1144.jpg: 640x352 1 normal, Done. (0.018s)\n    image 89/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-1176.jpg: 640x352 1 normal, Done. (0.018s)\n    image 90/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-1232.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 91/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-1248.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 92/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-1256.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 93/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-1320.jpg: 640x352 1 normal, Done. (0.018s)\n    image 94/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-176.jpg: 640x352 1 normal, Done. (0.018s)\n    image 95/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-2076.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 96/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-208.jpg: 640x352 1 normal, Done. (0.018s)\n    image 97/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-2090.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 98/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-2100.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 99/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-2108.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 100/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-232.jpg: 640x352 1 normal, Done. (0.018s)\n    image 101/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-256.jpg: 640x352 1 normal, Done. (0.018s)\n    image 102/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-80.jpg: 640x352 1 normal, Done. (0.018s)\n    image 103/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame03-88.jpg: 640x352 1 normal, Done. (0.018s)\n    image 104/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame04-1000.jpg: 640x352 1 normal, Done. (0.018s)\n    image 105/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame04-1064.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 106/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame04-1096.jpg: 640x352 1 normal, 1 drowsy#2, Done. (0.018s)\n    image 107/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame04-112.jpg: 640x352 1 normal, Done. (0.018s)\n    image 108/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame04-1136.jpg: 640x352 1 normal, Done. (0.018s)\n    image 109/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame04-1192.jpg: 640x352 1 normal, Done. (0.018s)\n    image 110/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame04-1208.jpg: 640x352 1 normal, Done. (0.018s)\n    image 111/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame04-128.jpg: 640x352 1 normal, Done. (0.018s)\n    image 112/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame04-1280.jpg: 640x352 1 normal, Done. (0.018s)\n    image 113/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame04-1296.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 114/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame04-1304.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 115/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame04-16.jpg: 640x352 1 normal, Done. (0.018s)\n    image 116/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame04-160.jpg: 640x352 1 normal, Done. (0.018s)\n    image 117/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame04-208.jpg: 640x352 1 normal, Done. (0.018s)\n    image 118/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame04-2168.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 119/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame04-2190.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 120/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame04-232.jpg: 640x352 1 normal, Done. (0.018s)\n    image 121/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame04-24.jpg: 640x352 1 normal, Done. (0.018s)\n    image 122/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame04-320.jpg: 640x352 1 normal, Done. (0.018s)\n    image 123/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame04-8.jpg: 640x352 1 normal, Done. (0.018s)\n    image 124/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame04-88.jpg: 640x352 1 normal, Done. (0.018s)\n    image 125/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-1040.jpg: 640x352 1 normal, Done. (0.018s)\n    image 126/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-1056.jpg: 640x352 1 normal, Done. (0.018s)\n    image 127/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-1080.jpg: 640x352 1 normal, Done. (0.018s)\n    image 128/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-1128.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 129/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-1144.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 130/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-1176.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 131/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-1192.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 132/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-1200.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 133/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-14.jpg: 640x352 1 normal, Done. (0.018s)\n    image 134/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-140.jpg: 640x352 1 normal, Done. (0.018s)\n    image 135/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-168.jpg: 640x352 1 normal, Done. (0.018s)\n    image 136/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-189.jpg: 640x352 1 normal, Done. (0.018s)\n    image 137/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-203.jpg: 640x352 1 normal, Done. (0.018s)\n    image 138/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-2092.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 139/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-2102.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 140/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-2110.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 141/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-2120.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 142/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-2122.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 143/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-2148.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 144/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-2150.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 145/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-77.jpg: 640x352 1 normal, Done. (0.018s)\n    image 146/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame05-84.jpg: 640x352 1 normal, Done. (0.018s)\n    image 147/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame06-1032.jpg: 640x352 1 drowsy, Done. (0.025s)\n    image 148/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame06-1128.jpg: 640x352 1 drowsy, Done. (0.018s)\n    image 149/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame06-120.jpg: 640x352 1 normal, Done. (0.021s)\n    image 150/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame06-1208.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 151/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame06-1232.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 152/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame06-1280.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 153/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame06-144.jpg: 640x352 1 normal, Done. (0.018s)\n    image 154/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame06-168.jpg: 640x352 1 normal, Done. (0.018s)\n    image 155/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame06-2084.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 156/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame06-2130.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 157/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame06-2132.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 158/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame06-2148.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 159/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame06-2156.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 160/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame06-2166.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 161/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame06-240.jpg: 640x352 1 normal, Done. (0.018s)\n    image 162/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame06-256.jpg: 640x352 1 normal, Done. (0.018s)\n    image 163/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame06-328.jpg: 640x352 1 normal, Done. (0.018s)\n    image 164/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame06-48.jpg: 640x352 1 normal, Done. (0.018s)\n    image 165/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame06-88.jpg: 640x352 1 normal, Done. (0.018s)\n    image 166/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-1032.jpg: 640x384 1 normal, Done. (0.020s)\n    image 167/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-1048.jpg: 640x384 1 drowsy, Done. (0.019s)\n    image 168/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-1088.jpg: 640x384 1 drowsy, Done. (0.018s)\n    image 169/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-1120.jpg: 640x384 1 normal, Done. (0.019s)\n    image 170/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-1144.jpg: 640x384 1 drowsy, Done. (0.018s)\n    image 171/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-1184.jpg: 640x384 1 normal, Done. (0.019s)\n    image 172/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-1192.jpg: 640x384 1 normal, Done. (0.018s)\n    image 173/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-1248.jpg: 640x384 1 drowsy, 1 drowsy#2, Done. (0.018s)\n    image 174/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-1264.jpg: 640x384 1 normal, Done. (0.018s)\n    image 175/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-1288.jpg: 640x384 1 normal, Done. (0.018s)\n    image 176/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-160.jpg: 640x384 1 normal, Done. (0.018s)\n    image 177/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-2082.jpg: 640x384 1 yawning, Done. (0.018s)\n    image 178/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-2088.jpg: 640x384 1 yawning, Done. (0.018s)\n    image 179/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-2094.jpg: 640x384 1 yawning, Done. (0.018s)\n    image 180/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-2100.jpg: 640x384 1 yawning, Done. (0.018s)\n    image 181/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-2118.jpg: 640x384 1 yawning, Done. (0.018s)\n    image 182/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-2120.jpg: 640x384 1 yawning, Done. (0.018s)\n    image 183/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-2244.jpg: 640x384 1 normal, Done. (0.018s)\n    image 184/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-288.jpg: 640x384 1 normal, Done. (0.017s)\n    image 185/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-320.jpg: 640x384 1 normal, Done. (0.018s)\n    image 186/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-72.jpg: 640x384 1 normal, Done. (0.018s)\n    image 187/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame07-96.jpg: 640x384 1 normal, Done. (0.018s)\n    image 188/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame08-0.jpg: 640x352 1 normal, Done. (0.019s)\n    image 189/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame08-1072.jpg: 640x352 1 drowsy, Done. (0.018s)\n    image 190/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame08-1088.jpg: 640x352 1 drowsy, Done. (0.018s)\n    image 191/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame08-1144.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 192/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame08-1184.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 193/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame08-1216.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 194/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame08-1280.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 195/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame08-1288.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 196/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame08-2092.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 197/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame08-2104.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 198/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame08-2166.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 199/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame08-296.jpg: 640x352 1 normal, Done. (0.018s)\n    image 200/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame08-88.jpg: 640x352 1 normal, Done. (0.018s)\n    image 201/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame09-0.jpg: 640x352 1 normal, Done. (0.018s)\n    image 202/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame09-1040.jpg: 640x352 1 drowsy, Done. (0.018s)\n    image 203/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame09-1072.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 204/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame09-1112.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 205/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame09-1120.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 206/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame09-1168.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 207/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame09-1184.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 208/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame09-1224.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 209/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame09-1256.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 210/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame09-1272.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 211/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame09-2052.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 212/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame09-2054.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 213/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame09-2062.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 214/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame09-2078.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 215/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame09-2092.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 216/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame09-2098.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 217/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame09-2112.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 218/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame09-240.jpg: 640x352 1 normal, Done. (0.018s)\n    image 219/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame09-264.jpg: 640x352 1 normal, Done. (0.018s)\n    image 220/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame09-40.jpg: 640x352 1 drowsy, Done. (0.018s)\n    image 221/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame10-1080.jpg: 640x352 1 normal, Done. (0.018s)\n    image 222/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame10-1144.jpg: 640x352 1 drowsy, Done. (0.018s)\n    image 223/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame10-1176.jpg: 640x352 1 drowsy#2, Done. (0.028s)\n    image 224/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame10-1272.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 225/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame10-128.jpg: 640x352 1 normal, Done. (0.018s)\n    image 226/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame10-2116.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 227/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame10-2120.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 228/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame10-2134.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 229/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame10-2144.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 230/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame10-2152.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 231/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame10-224.jpg: 640x352 1 normal, Done. (0.018s)\n    image 232/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame10-296.jpg: 640x352 1 normal, Done. (0.018s)\n    image 233/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame10-96.jpg: 640x352 1 normal, Done. (0.018s)\n    image 234/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-1040.jpg: 640x352 1 normal, Done. (0.018s)\n    image 235/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-1064.jpg: 640x352 1 normal, Done. (0.018s)\n    image 236/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-1136.jpg: 640x352 1 drowsy, Done. (0.018s)\n    image 237/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-1144.jpg: 640x352 1 drowsy, Done. (0.018s)\n    image 238/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-1152.jpg: 640x352 1 drowsy, Done. (0.018s)\n    image 239/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-1208.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 240/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-1216.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 241/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-1224.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 242/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-1240.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 243/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-1272.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 244/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-1280.jpg: 640x352 1 drowsy#2, Done. (0.017s)\n    image 245/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-1320.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 246/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-160.jpg: 640x352 1 normal, Done. (0.018s)\n    image 247/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-200.jpg: 640x352 1 normal, Done. (0.018s)\n    image 248/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-2108.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 249/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-2110.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 250/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-2114.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 251/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-2126.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 252/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-2132.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 253/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-2134.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 254/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-2136.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 255/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-2140.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 256/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-2152.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 257/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-2162.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 258/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-2164.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 259/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-2200.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 260/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-2224.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 261/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-2226.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 262/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-2228.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 263/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-2298.jpg: 640x352 1 drowsy, Done. (0.018s)\n    image 264/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-2306.jpg: 640x352 1 drowsy, Done. (0.018s)\n    image 265/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-32.jpg: 640x352 1 normal, Done. (0.018s)\n    image 266/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-320.jpg: 640x352 1 normal, Done. (0.018s)\n    image 267/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame11-40.jpg: 640x352 1 normal, Done. (0.018s)\n    image 268/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame12-1016.jpg: 640x352 1 normal, Done. (0.018s)\n    image 269/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame12-1024.jpg: 640x352 1 normal, Done. (0.019s)\n    image 270/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame12-1088.jpg: 640x352 1 drowsy, Done. (0.018s)\n    image 271/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame12-1120.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 272/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame12-1160.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 273/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame12-120.jpg: 640x352 1 normal, Done. (0.018s)\n    image 274/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame12-1216.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 275/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame12-1232.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 276/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame12-1304.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 277/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame12-1320.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 278/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame12-168.jpg: 640x352 1 normal, Done. (0.018s)\n    image 279/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame12-2142.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 280/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame12-2152.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 281/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame12-2160.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 282/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame12-2176.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 283/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame12-48.jpg: 640x352 1 normal, Done. (0.018s)\n    image 284/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame13-0.jpg: 640x352 1 normal, Done. (0.017s)\n    image 285/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame13-1008.jpg: 640x352 1 normal, Done. (0.018s)\n    image 286/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame13-1032.jpg: 640x352 1 normal, Done. (0.017s)\n    image 287/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame13-1080.jpg: 640x352 1 drowsy, Done. (0.018s)\n    image 288/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame13-1128.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 289/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame13-1152.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 290/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame13-1224.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 291/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame13-1232.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 292/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame13-1296.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 293/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame13-1328.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 294/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame13-2008.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 295/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame13-2022.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 296/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame13-2026.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 297/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame13-2238.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 298/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame13-2242.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 299/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame13-2256.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 300/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame13-2270.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 301/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame13-2278.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 302/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame14-1024.jpg: 640x352 1 normal, Done. (0.018s)\n    image 303/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame14-1072.jpg: 640x352 1 normal, Done. (0.018s)\n    image 304/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame14-1096.jpg: 640x352 1 normal, 1 drowsy, Done. (0.018s)\n    image 305/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame14-1176.jpg: 640x352 1 drowsy#2, Done. (0.017s)\n    image 306/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame14-120.jpg: 640x352 1 normal, Done. (0.018s)\n    image 307/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame14-1240.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 308/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame14-1272.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 309/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame14-128.jpg: 640x352 1 normal, Done. (0.018s)\n    image 310/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame14-2158.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 311/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame14-2176.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 312/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame14-2180.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 313/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame14-240.jpg: 640x352 1 normal, Done. (0.022s)\n    image 314/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame14-288.jpg: 640x352 1 normal, Done. (0.018s)\n    image 315/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame15-1048.jpg: 640x352 1 normal, Done. (0.018s)\n    image 316/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame15-1056.jpg: 640x352 1 drowsy, Done. (0.018s)\n    image 317/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame15-112.jpg: 640x352 1 normal, Done. (0.018s)\n    image 318/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame15-1128.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 319/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame15-1152.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 320/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame15-1200.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 321/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame15-1248.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 322/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame15-1272.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 323/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame15-128.jpg: 640x352 1 normal, Done. (0.018s)\n    image 324/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame15-192.jpg: 640x352 1 normal, Done. (0.018s)\n    image 325/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame15-2174.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 326/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame15-2176.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 327/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame15-264.jpg: 640x352 1 normal, Done. (0.018s)\n    image 328/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame15-304.jpg: 640x352 1 normal, Done. (0.018s)\n    image 329/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame16-1032.jpg: 640x384 1 normal, Done. (0.020s)\n    image 330/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame16-1048.jpg: 640x384 1 normal, Done. (0.018s)\n    image 331/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame16-1120.jpg: 640x384 1 normal, Done. (0.019s)\n    image 332/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame16-1136.jpg: 640x384 1 normal, Done. (0.018s)\n    image 333/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame16-1192.jpg: 640x384 1 drowsy, Done. (0.018s)\n    image 334/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame16-1232.jpg: 640x384 1 drowsy#2, Done. (0.018s)\n    image 335/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame16-1264.jpg: 640x384 1 drowsy#2, Done. (0.018s)\n    image 336/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame16-128.jpg: 640x384 1 normal, Done. (0.019s)\n    image 337/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame16-2114.jpg: 640x384 1 yawning, Done. (0.019s)\n    image 338/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame16-2116.jpg: 640x384 1 yawning, Done. (0.018s)\n    image 339/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame16-2134.jpg: 640x384 1 yawning, Done. (0.018s)\n    image 340/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame16-2140.jpg: 640x384 1 yawning, Done. (0.019s)\n    image 341/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame16-2152.jpg: 640x384 1 yawning, Done. (0.019s)\n    image 342/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame16-2166.jpg: 640x384 1 yawning, Done. (0.018s)\n    image 343/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame16-56.jpg: 640x384 1 normal, Done. (0.018s)\n    image 344/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame16-8.jpg: 640x384 1 normal, Done. (0.018s)\n    image 345/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame17-1016.jpg: 640x384 1 drowsy, Done. (0.019s)\n    image 346/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame17-1024.jpg: 640x384 1 drowsy, Done. (0.019s)\n    image 347/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame17-1120.jpg: 640x384 1 drowsy, Done. (0.019s)\n    image 348/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame17-1160.jpg: 640x384 1 drowsy#2, Done. (0.018s)\n    image 349/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame17-1216.jpg: 640x384 1 drowsy#2, Done. (0.025s)\n    image 350/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame17-1232.jpg: 640x384 1 drowsy#2, Done. (0.018s)\n    image 351/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame17-2078.jpg: 640x384 1 yawning, Done. (0.019s)\n    image 352/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame17-2082.jpg: 640x384 1 yawning, Done. (0.019s)\n    image 353/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame17-2096.jpg: 640x384 1 yawning, Done. (0.018s)\n    image 354/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame17-2106.jpg: 640x384 1 yawning, Done. (0.018s)\n    image 355/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame17-2128.jpg: 640x384 1 yawning, Done. (0.019s)\n    image 356/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame18-1008.jpg: 640x352 1 normal, Done. (0.019s)\n    image 357/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame18-1032.jpg: 640x352 1 normal, Done. (0.018s)\n    image 358/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame18-1080.jpg: 640x352 1 drowsy, Done. (0.020s)\n    image 359/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame18-1128.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 360/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame18-1152.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 361/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame18-1224.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 362/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame18-1232.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 363/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame18-1296.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 364/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame18-192.jpg: 640x352 1 normal, Done. (0.018s)\n    image 365/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame18-200.jpg: 640x352 1 normal, Done. (0.018s)\n    image 366/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame18-2032.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 367/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame18-2042.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 368/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame18-2056.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 369/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame18-2060.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 370/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame18-2090.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 371/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame18-2094.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 372/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame18-2112.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 373/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame18-2122.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 374/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame19-1000.jpg: 640x352 1 normal, Done. (0.018s)\n    image 375/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame19-1048.jpg: 640x352 1 normal, Done. (0.018s)\n    image 376/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame19-1096.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 377/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame19-1120.jpg: 640x352 1 drowsy#2, Done. (0.021s)\n    image 378/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame19-1192.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 379/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame19-1200.jpg: 640x352 1 drowsy#2, Done. (0.021s)\n    image 380/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame19-1264.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 381/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame19-1296.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 382/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame19-184.jpg: 640x352 1 normal, Done. (0.018s)\n    image 383/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame19-200.jpg: 640x352 1 normal, Done. (0.018s)\n    image 384/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame19-2040.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 385/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame19-2064.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 386/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame19-2068.jpg: 640x352 1 yawning, Done. (0.018s)\n    image 387/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame19-296.jpg: 640x352 1 normal, Done. (0.018s)\n    image 388/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame19-40.jpg: 640x352 1 drowsy, Done. (0.018s)\n    image 389/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame20-1024.jpg: 640x352 1 normal, Done. (0.018s)\n    image 390/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame20-1168.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 391/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame20-1240.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 392/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame20-1312.jpg: 640x352 1 drowsy#2, Done. (0.018s)\n    image 393/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame20-224.jpg: 640x352 1 normal, Done. (0.018s)\n    image 394/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame20-24.jpg: 640x352 1 normal, Done. (0.018s)\n    image 395/395 /content/drive/My Drive/yolo_v5/data/drowsy_training/test/images/frame20-56.jpg: 640x352 1 normal, Done. (0.018s)\n    Speed: 0.5ms pre-process, 18.3ms inference, 1.3ms NMS per image at shape (1, 3, 640, 640)\n    Results saved to \u001b[1mruns/detect/exp4\u001b[0m\n\n", "meta": {"hexsha": "6be8c7467318baf00f723bf882daeb5eb8e47c54", "size": 164641, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "drowsy_training_with_yolov5.ipynb", "max_stars_repo_name": "suhedaras/Drowsiness-Detection-with-YoloV5", "max_stars_repo_head_hexsha": "125b38ca0ed72e96da20ca04faa8d85104da1130", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-03-19T23:08:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T08:47:46.000Z", "max_issues_repo_path": "drowsy_training_with_yolov5.ipynb", "max_issues_repo_name": "suhedaras/Drowsiness-Detection-with-YoloV5", "max_issues_repo_head_hexsha": "125b38ca0ed72e96da20ca04faa8d85104da1130", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "drowsy_training_with_yolov5.ipynb", "max_forks_repo_name": "suhedaras/Drowsiness-Detection-with-YoloV5", "max_forks_repo_head_hexsha": "125b38ca0ed72e96da20ca04faa8d85104da1130", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-21T07:50:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T07:50:21.000Z", "avg_line_length": 164641.0, "max_line_length": 164641, "alphanum_fraction": 0.5970566262, "converted": true, "num_tokens": 56640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04535258442524595, "lm_q2_score": 0.037326884666868405, "lm_q1q2_score": 0.001692870688185568}}
{"text": "# Abstract\n\n4Chan is famous for it's anonymous and ephemeral boards. But is it really ephemeral? There are multiple internet archiving services that have been keeping copies of 4chan posts that go many years in the past. We looked into it to asnwer the following questions: Q1.) *Are 4chan archiving services reliable and offer a holistic view of the epehemeral 4chan threads?* q2.) *If (Q1) is true, does this provides any insights into the pseudo anonymity of the site?* \n\n\n\n```python\n%%capture\n# needed to support mongo+srv connection strings\n!pip install dnspython\n!pip install pymongo\n!pip install pandas\n!pip install numpy\n!pip install matplotlib\n!pip install scipy\n!pip install gensim\n!pip install langdetect\n!pip install tqdm\n!pip install nltk\n!pip install seaborn\n!pip install pyLDAvis\n!pip install wordcloud\n\n## Only run once per kernel environment\n##\u00a0Doesn't need to be re-run when kernel is restarted\n#import nltk\n#nltk.download('punkt')\n#nltk.download('averaged_perceptron_tagger')\n#nltk.download('wordnet')\n#nltk.download('stopwords')\n\n```\n\n\n```python\n%%capture\n\n\nfrom pymongo import MongoClient\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# Fixed period analysis - change these to extend/restrict the period\n# Date as a yyyymmddhhMMss string\ndate_from = '202105010000'\ndate_to =   '202111010000'\n\n# connectiong to mongodb cluster using a read only user\n\n## REMOTE REPLICA SET\nclient = MongoClient(\"mongodb+srv://<usr>:<pass>@rs.prifti.us/?ssl=false&authSource=chan\")\n\n## LOCAL SINGLE INSTANCE\n## 192.168.1.110 -- localhost\n## client = MongoClient(\"mongodb://<usr>:<pass>@localhost:27777/?ssl=false&serverSelectionTimeoutMS=5000&connectTimeoutMS=10000&authSource=chan&authMechanism=SCRAM-SHA-256\")\n\n# connection to chan database\ndb = client.chan\n\n# the threads collection contains API data collections from the 4chan api and 4pleb api\nthreads = db['y-threads']\n\n# the 'live-4chan' collection contains the OXPath data collection\nlivechan = db['y-live-4chan']\n\n```\n\n\n```python\n# %%capture\n\n# MongoDB aggregation query, joining data from thread and 'live-4chan' collection \n# for each discovered 4chan thread - retreive a boolean representing if the API data was found\n# Fixed period analysis - change these to extend/restrict the period\n# Date as a yyyymmddhhMMss string\ndate_from = '202105010000'\ndate_to =   '202111010000'\n\n\nq1_pipeline = [\n    # normalise nulls in $data \n    { \"$addFields\": { \"data\": { \"$cond\": [\n        {\"$and\":[ {\"$gt\": [\"$data\", None] }, {\"data\": {\"$type\": \"array\"} } ] }, \"$data\", [{ }]  \n      ] } } }\n    # only load required fields from 'live-4chan' collection\n    ,{ \"$project\": { \"_id\": 0, \"url\": 1, \"deleted\": \"$attributes.deleted\", \"archived\": \"$attributes.archived\" \n                    ,\"first_scan\": {\"$arrayElemAt\": [\"$scans\", 0 ] }\n                    ,\"last_scan\": {\"$arrayElemAt\": [\"$scans\", -1 ] }\n                    ,\"oxp_op\": { \"$arrayElemAt\": [ \"$data\", -1 ] } \n                  }\n    }\n    \n    # limit the data to fixed period\n   ,{ \"$match\": {\"$and\":[ {\"first_scan\": { \"$gt\": date_from} }, {\"last_scan\": { \"$lt\": date_to }} ] } }  \n    # join with 'threads' collection on thread unique URL\n   ,{ \"$lookup\": { \n               \"from\": \"y-threads\",\n               \"localField\": \"url\",\n               \"foreignField\": \"_id\",\n               \"as\": \"api_thread\"\n       }\n    }\n   # unwind/expand the joined array \n  ,{ \"$unwind\": \"$api_thread\" }\n   # remove items where the API scrap job has not been performed\n   # this should only affects threads that have not been archived/deleted yet \n  ,{ \"$match\": { \"api_thread.api_scrap\": True } }\n   #,{ \"$project\": { \"url\": 1 }}\n   # include the op thread scaped via 4Chan API\n  ,{ \"$addFields\": { \"chan_op\": { \"$cond\": [\n        {\"$and\":[ {\"$gt\": [\"$api_thread.chan.posts\", None] }] }, \"$api_thread.chan.posts\", [{ }]  \n      ] } } }\n   # add the boolean fields that check if chan api fields has data\n  ,{ \"$project\": { \"_id\": 0, \"url\": 1, \"deleted\": 1, \"archived\": 1, \"last_scan\": 1\n                    ,\"oxp_op\": \"$oxp_op.payload\"\n                    ,\"chan_op\": {\"$arrayElemAt\": [\"$chan_op\", 0]}\n                    ,\"chan\": {\"$gt\": [ \"$api_thread.chan.posts\", { } ] }\n                    ,\"pleb\": \"$api_thread.pleb\" \n        } \n   }\n   # keep the OP/thread from OXpath scrap\n  ,{\"$unwind\": {\"path\": \"$oxp_op\", \"preserveNullAndEmptyArrays\": True } }\n   # convert a document to array to better check relevant fields have values\n  ,{ \"$addFields\": {\n        \"pleb_array\": {\n                \"$ifNull\": [ {\"$objectToArray\": \"$pleb\"}, [ ] ] \n          }\n     } \n   }\n   # bring array fields one level up\n  ,{ \"$unwind\": { \"path\": \"$pleb_array\", \"preserveNullAndEmptyArrays\": True } }\n   # check the pleb api has data\n  ,{ \"$project\": { \"_id\": 0, \"url\": 1, \"deleted\": 1, \"archived\": 1, \"last_scan\": 1,\n                    \"oxp_op\":\"$oxp_op.thread.op\", \"oxp\": { \"$gt\": [\"$oxp_op\", {} ] }\n                  ,\"chan\": 1, \"chan_op\": 1\n                  ,\"pleb_op\": \"$pleb_array.v.op\"\n                  ,\"pleb\": { \"$gt\": [ \"$pleb_array.v.op\", { } ] } }\n   }\n  ,{ \"$unwind\": {\"path\": \"$oxp_op\", \"preserveNullAndEmptyArrays\": True } }\n  ,{ \"$unwind\": {\"path\": \"$oxp_op\", \"preserveNullAndEmptyArrays\": True } }\n #,{ \"$group\": { _id: null, \"count\": { $sum: 1 } } }\n  ,{ \"$sort\": {\"last_scan\": -1} } \n]\n\n# run the aggregation\nmatch_result = pd.DataFrame(livechan.aggregate(q1_pipeline, allowDiskUse=True))\n\n```\n\n\n```python\nmatch_result\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>url</th>\n      <th>deleted</th>\n      <th>archived</th>\n      <th>last_scan</th>\n      <th>chan_op</th>\n      <th>chan</th>\n      <th>oxp</th>\n      <th>pleb_op</th>\n      <th>pleb</th>\n      <th>oxp_op</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>https://boards.4chan.org/pol/thread/345511307</td>\n      <td>False</td>\n      <td>True</td>\n      <td>20211031235904</td>\n      <td>{}</td>\n      <td>False</td>\n      <td>False</td>\n      <td>{'doc_id': '321648245', 'num': '345511307', 's...</td>\n      <td>True</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>https://boards.4chan.org/pol/thread/345544668</td>\n      <td>False</td>\n      <td>True</td>\n      <td>20211031235904</td>\n      <td>{}</td>\n      <td>False</td>\n      <td>False</td>\n      <td>{'doc_id': '321681512', 'num': '345544668', 's...</td>\n      <td>True</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>https://boards.4chan.org/pol/thread/345545223</td>\n      <td>False</td>\n      <td>True</td>\n      <td>20211031235904</td>\n      <td>{}</td>\n      <td>False</td>\n      <td>False</td>\n      <td>{'doc_id': '321682079', 'num': '345545223', 's...</td>\n      <td>True</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>https://boards.4chan.org/pol/thread/345545415</td>\n      <td>False</td>\n      <td>True</td>\n      <td>20211031235904</td>\n      <td>{}</td>\n      <td>False</td>\n      <td>False</td>\n      <td>{'doc_id': '321682252', 'num': '345545415', 's...</td>\n      <td>True</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>https://boards.4chan.org/pol/thread/345537604</td>\n      <td>False</td>\n      <td>True</td>\n      <td>20211031235805</td>\n      <td>{}</td>\n      <td>False</td>\n      <td>False</td>\n      <td>{'doc_id': '321674445', 'num': '345537604', 's...</td>\n      <td>True</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>407931</th>\n      <td>https://boards.4chan.org/pol/thread/319461189</td>\n      <td>False</td>\n      <td>False</td>\n      <td>20210501002857</td>\n      <td>{}</td>\n      <td>False</td>\n      <td>True</td>\n      <td>{'doc_id': '295621738', 'num': '319461189', 's...</td>\n      <td>True</td>\n      <td>{'image': ['//i.4cdn.org/pol/1619828463836.jpg...</td>\n    </tr>\n    <tr>\n      <th>407932</th>\n      <td>https://boards.4chan.org/pol/thread/319459954</td>\n      <td>False</td>\n      <td>False</td>\n      <td>20210501002656</td>\n      <td>{'no': 319459954, 'closed': 1, 'now': '04/30/2...</td>\n      <td>True</td>\n      <td>True</td>\n      <td>{'doc_id': '295620477', 'num': '319459954', 's...</td>\n      <td>True</td>\n      <td>{'image': ['//i.4cdn.org/pol/1619827838385.jpg...</td>\n    </tr>\n    <tr>\n      <th>407933</th>\n      <td>https://boards.4chan.org/pol/thread/319458666</td>\n      <td>False</td>\n      <td>False</td>\n      <td>20210501002156</td>\n      <td>{'no': 319458666, 'closed': 1, 'now': '04/30/2...</td>\n      <td>True</td>\n      <td>True</td>\n      <td>{'doc_id': '295619151', 'num': '319458666', 's...</td>\n      <td>True</td>\n      <td>{'image': ['//i.4cdn.org/pol/1619827175027.png...</td>\n    </tr>\n    <tr>\n      <th>407934</th>\n      <td>https://boards.4chan.org/pol/thread/319458870</td>\n      <td>False</td>\n      <td>False</td>\n      <td>20210501001911</td>\n      <td>{'no': 319458870, 'closed': 1, 'now': '04/30/2...</td>\n      <td>True</td>\n      <td>True</td>\n      <td>{'doc_id': '295619448', 'num': '319458870', 's...</td>\n      <td>True</td>\n      <td>{'image': ['//i.4cdn.org/pol/1619827276328.jpg...</td>\n    </tr>\n    <tr>\n      <th>407935</th>\n      <td>https://boards.4chan.org/pol/thread/319458755</td>\n      <td>False</td>\n      <td>False</td>\n      <td>20210501001851</td>\n      <td>{'no': 319458755, 'closed': 1, 'now': '04/30/2...</td>\n      <td>True</td>\n      <td>True</td>\n      <td>{'doc_id': '295619230', 'num': '319458755', 's...</td>\n      <td>True</td>\n      <td>{'image': ['//i.4cdn.org/pol/1619827216254.png...</td>\n    </tr>\n  </tbody>\n</table>\n<p>407936 rows \u00d7 10 columns</p>\n</div>\n\n\n\n\n```python\n# %%capture\n\n## Length of the dataset where there is data from 4Chan API (chan), 4Pleb API (pleb) and OXPath Scrap (oxp)\nfull_match_len = len(match_result.query(\"chan & pleb & oxp\" ))\n\n\nprint(f'There are **{len(match_result)}** threads crawled during the period in question. ')\nprint(f'Of these there are **{match_result.pleb.sum()}** threads that have been found in 4pleb archiving API. This is equivalent to **{\"%.3f\" % (match_result.pleb.sum()/len(match_result)*100)}%** match.')\nprint(f'Nr of matching threads we have collected data from all three sources (OXPATH, 4CHAN, 4PLEB): {full_match_len}, that is **{\"%.3f\" % (full_match_len/len(match_result)*100)}%** ')\n\n# Select only items that have not been found on 4pleb\nf1 = match_result[match_result.pleb==False]\n# Of these, select only items that have not been scaped from 4chan\nf2 = f1 # ^ paused - f2 used as f1 later - do not change\n# Of these, select the items where we have a copy of the data from oxpath but not found on 4chan and 4pleb\nf3 = f2[f2.oxp == True]\n\n\n\n# Show the data  from original post scraped using OXPath\noxp_op = pd.DataFrame(list(f3['oxp_op']))\npost_date = oxp_op.explode('date_time')\n\npost_date['date_time'] = pd.to_datetime(post_date['date_time'], format='%m/%d/%y(%a)%X')\npost_date=post_date.sort_values(by='date_time')\n\ndates = post_date.date_time\n\ntimes = pd.DatetimeIndex(dates)\ngrp = dates.groupby([times.hour])\n\nprint('Plot showing the distribution of missed threads through out the 24 hour (UK Time)')\n\ncnt = grp.agg(['count'])\n\nmy_df = pd.DataFrame([cnt.index, cnt.values])\nmy_df = my_df.transpose()\nmy_df.columns = ['time_of_day','nr_missed_threads']\nmy_df = my_df.explode('nr_missed_threads')\n#my_df\n#grouped.agg(['count'])\nplt.hist(my_df.time_of_day, bins=24, weights=my_df.nr_missed_threads)\n#np.mean(my_df.nr_missed_threads)\n\n\n```\n\n\n```python\n# %%capture\n\nimport scipy.stats as st\nimport statistics as stat\n\ndef rolling(time_series):\n  diff, _d_from, _d_to = [],[],[]\n  for i in range(1, len(time_series)-1):\n      temp_diff = (time_series[i] - time_series[i-1]).total_seconds() / 60\n      diff.append(temp_diff)\n      _d_from.append(time_series[i-1])\n      _d_to.append(time_series[i])\n  return pd.DataFrame({\"Gap\": diff, \"From\": _d_from, \"To\": _d_to})\n\n\nsorted_freq = freq_dataset#.sort_values(by=[\"scan_num\"])\ncount = sorted_freq['count']\nscan = list(sorted_freq['scan'])\n_to_date = scan[0]\n_from_date = scan[len(scan) - 1]\n_minutes = (_from_date - _to_date).total_seconds() / 60\n_total_scans = count.sum()\n\nprint(f'Total scans {len(freq_dataset)}')\nprint(f'First Scan: {_from_date}, Last Scan: {_to_date}, Total Minutes {_minutes}')\nprint(f\"Total Scans {_total_scans}, Avg scans per minute {'%.2f' % (_total_scans/_minutes )}\")\nprint(f'Scan frequency mean {\"%.2f\" % stat.mean(count)}, geometric mean {\"%.2f\" % st.gmean(count)}, \\\nmedian {stat.median(count)}, std {\"%.2f\" % stat.stdev(count)}')\nrolling(scan).sort_values(by=[\"Gap\"], ascending=False).head(10)\n\nperc_match = (match_result.pleb.sum()/len(match_result))*100\nperc_not_match = (1-(match_result.pleb.sum()/len(match_result)))*100\nnot_pleb_match = match_result.query(\"pleb==False\")\nnot_pleb_yes_chan = not_pleb_match.query(\"chan\")\n\nresult_rolling = rolling(scan).sort_values(by=[\"Gap\"], ascending=False)#.head(10)\nresult_rolling\n```\n\n    Total scans 2516\n    First Scan: 2022-04-17 17:57:00, Last Scan: 2022-04-16 00:01:00, Total Minutes 2516.0\n    Total Scans 10942, Avg scans per minute 4.35\n    Scan frequency mean 4.35, geometric mean 4.20, median 4.0, std 1.04\n\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Gap</th>\n      <th>From</th>\n      <th>To</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>698</th>\n      <td>2.0</td>\n      <td>2022-04-16 11:39:00</td>\n      <td>2022-04-16 11:41:00</td>\n    </tr>\n    <tr>\n      <th>1669</th>\n      <td>1.0</td>\n      <td>2022-04-17 03:51:00</td>\n      <td>2022-04-17 03:52:00</td>\n    </tr>\n    <tr>\n      <th>1671</th>\n      <td>1.0</td>\n      <td>2022-04-17 03:53:00</td>\n      <td>2022-04-17 03:54:00</td>\n    </tr>\n    <tr>\n      <th>1672</th>\n      <td>1.0</td>\n      <td>2022-04-17 03:54:00</td>\n      <td>2022-04-17 03:55:00</td>\n    </tr>\n    <tr>\n      <th>1673</th>\n      <td>1.0</td>\n      <td>2022-04-17 03:55:00</td>\n      <td>2022-04-17 03:56:00</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>839</th>\n      <td>1.0</td>\n      <td>2022-04-16 14:01:00</td>\n      <td>2022-04-16 14:02:00</td>\n    </tr>\n    <tr>\n      <th>840</th>\n      <td>1.0</td>\n      <td>2022-04-16 14:02:00</td>\n      <td>2022-04-16 14:03:00</td>\n    </tr>\n    <tr>\n      <th>841</th>\n      <td>1.0</td>\n      <td>2022-04-16 14:03:00</td>\n      <td>2022-04-16 14:04:00</td>\n    </tr>\n    <tr>\n      <th>842</th>\n      <td>1.0</td>\n      <td>2022-04-16 14:04:00</td>\n      <td>2022-04-16 14:05:00</td>\n    </tr>\n    <tr>\n      <th>2513</th>\n      <td>1.0</td>\n      <td>2022-04-17 17:55:00</td>\n      <td>2022-04-17 17:56:00</td>\n    </tr>\n  </tbody>\n</table>\n<p>2514 rows \u00d7 3 columns</p>\n</div>\n\n\n\n\n```python\n# %%capture\n\nnot_pleb_not_chan_oxp = not_pleb_match.query(\"chan==False & oxp==True\")\nnot_pleb_yes_chan_or_oxp = not_pleb_match.query(\"chan | (chan==False & oxp==True)\")\nprint(f'Nr items that are not in 4pleb but are in 4chan {(len(not_pleb_yes_chan)/len(not_pleb_match))*100}')\n\ndef get_num(url: str) -> int:\n    return int(url.split('/')[-1])\n\ndef get_num_str(url: str) -> str:\n    return url.split('/')[-1]\n \npleb_qry = match_result.query(\"pleb & deleted==True\")\nchan_pleb_qry = pleb_qry.query(\"chan\")\n# Show the data  from original post\npleb_posts = pd.DataFrame(list(pleb_qry['pleb_op']))\nchan_posts = pd.DataFrame(list(chan_pleb_qry['chan_op']))\nprint('Pleb Deleted {}'.format(len(pleb_posts.query(\"deleted=='1'\"))))\nprint(f'Oxp Deleted {len(pleb_posts)}')\nid_chan_posts = list(chan_posts.query('filedeleted != \"NaN\"')['no'])\nmatch_result['num'] = match_result['url'].apply(get_num)\n#match_result\nnum_del_chan = len(match_result[match_result['num'].isin(id_chan_posts)].query('deleted==True'))\n\n\nid_pleb_posts = pleb_posts.query(\"deleted=='1'\")['num']\nmatch_result['num'] = match_result['url'].apply(get_num_str)\nprint(len(id_pleb_posts))\nprint(len(match_result[match_result['num'].isin(id_pleb_posts)].query('deleted==True')))\n\n\n\n```\n\n    Nr items that are not in 4pleb but are in 4chan 34.946236559139784\n    Pleb Deleted 6600\n    Oxp Deleted 11054\n    6600\n    6600\n\n\n# Introduction\n\nWe have been collecting posts from the the /pol board of 4chan with high frequency (scaning the board multiple times per minute). \n\nWe have done so by simulating an end user that connects to the side with a conventional borwser (Firefox), using [OXPath](https://github.com/oxpath/oxpath)\n\nWe have been taking multiple snapshots of each thread until the thread was archived. When a thread is archived we then have been taking a snapshot of the thread from the 4chan api and one from 4pleb.org, an 4chan archiving service, believed to be the most complete archiving service on 4chan. \n\nTwo type of agents have been used to collect the data using OXpath. \n\n- A discovery crawling agent that continuously crawls the /pol board looking for new threads and either a.) captures and queues the new thread URLs for scraping or b.) updates the *found* timestamp of a thread that had already been found by previous instances of the crawler. \n\n- A extraction scraping agent that continuously scrapes threads queued by the crawling agent and stores the state of the thread together with the timestamp, unless the agent finds the thread to be *archived* or *deleted*. When the thread is found in the *archived* / *deleted* state, its attributes are updated and the thread is removed from the crawling queue. \n\n\n# Data overview\n\n\nWhilst there is a continous stream of data, to ensure reproducibility, this analisys is specifically to the dates between {{date_from}} and {{date_to}}.\n\nThe data collected by scanning the 4chan /pol board has the following caracteristics: \n\n|Property   | Value   | Description   |\n|---|---|---|\n|Total Threads   |{{len(match_result)}}   | The number of total threads found   |\n|Total 4Pleb Threads   |{{match_result.pleb.sum()}}  / {{\"%.3f\" % (match_result.pleb.sum()/len(match_result)*100)}}% | Number/Percentage of threads also found on 4Pleb API  |\n|Three way Matched Threads   | {{full_match_len}} / {{\"%.3f\" % (full_match_len/len(match_result)*100) }}% | The number of threads where we have collected data from all three sources  |\n|First-Last scan | {{ _from_date.strftime(\"%d/%m/%Y, %H:%M:%S\") }} **-** {{ _to_date.strftime(\"%d/%m/%Y, %H:%M:%S\") }}  | The first and the last scan in the dataset   |\n|Total Minutes   | {{ _minutes }}   | The total minutes elapsed between the two dates   |\n|Total Scans   | {{_total_scans}}   | The total number of scans seen on the dataset. That is the number of times we crawled the /pol board to find new threads   |\n|Scans per minute| {{'%.2f' % (_total_scans/_minutes )}}  | The avg scans per minute based on the total minutes elapsed between the two dates |\n|Frequency mean| {{\"%.2f\" % stat.mean(count)}}  | The avg scans per minute based on the minutes where there has been scans (there are gaps in the dataset) |\n|Median | {{stat.median(count)}}   | The median value of scans per minute |\n|Standard Deviation| {{\"%.2f\" % stat.stdev(count)}} | The std of observed scans per minute |\n\n\n\n\n```python\n# %%capture\n\ndeleted_threads = match_result.query('pleb').query(\"deleted==True\")\ndeleted_threads = pd.DataFrame(list(deleted_threads['pleb_op']))\ndeleted_threads = deleted_threads.drop(columns=['doc_id', 'subnum', 'thread_num', 'op', 'capcode', 'email', 'name', 'exif'])\ndeleted_threads = deleted_threads.drop(columns=['trip','sticky', 'locked', 'poster_hash_processed', 'poster_country_name_processed', 'troll_country_code', 'troll_country_name', 'since4pass', 'unique_ips', 'extra_data', 'media', 'board'])\ndeleted_threads = deleted_threads.drop(columns=['trip_processed', 'email_processed', 'name_processed', 'formatted'])\n#document_corp = ', '.join(list(deleted_threads.query('title != None')['title']))\n\n#len(deleted_threads)\n#len(deleted_threads.query('deleted==\"1\"'))\ndeleted_threads = deleted_threads.query('deleted==\"0\"')\n```\n\n\n```python\n# %%capture\n\ndeleted_threads['articles'] = deleted_threads['title'] + ' ' + deleted_threads['comment']\ndocument_corp = list(deleted_threads['articles'])\ndocument_corp = [x for x in document_corp if x is not None]\ndocument_corp = pd.DataFrame(document_corp)\n#document_corp.shape\ndocument_corp.columns = ['articles']\ndocument_corp = document_corp.dropna().reset_index(drop=True)\n#temp_title = list(deleted_threads.query('title != None')['title'])\n#temp_title = [x for x in temp_title if x is not None]\n\n\n#temp_comments = list(deleted_threads.query('comment != None')['comment'])\n#temp_comments = [x for x in temp_comments if x is not None]\n#document_corp = temp_title + temp_comments\n#len(document_corp)\n\n```\n\n\n```python\n# %%capture\n\nfrom langdetect import detect\nfrom tqdm import notebook\nnotebook.tqdm().pandas()\ndata = document_corp.copy()\n\ndef try_detect(elem):\n    try: \n        return detect(elem)\n    except:\n        return 'n/a'\n\ndata['lang'] = data.articles.progress_map(try_detect)\ndata['lang'].head(5)\n\n```\n\n\n    HBox(children=(HTML(value=''), FloatProgress(value=1.0, bar_style='info', layout=Layout(width='20px'), max=1.0\u2026\n\n\n\n    HBox(children=(HTML(value=''), FloatProgress(value=0.0, max=2243.0), HTML(value='')))\n\n\n    \n    \n\n\n\n\n\n    0    en\n    1    en\n    2    en\n    3    en\n    4    en\n    Name: lang, dtype: object\n\n\n\n\n```python\n# %%capture\n\nfrom nltk.tokenize import sent_tokenize\n\n\ndata.lang.value_counts()\ndata_en = data.loc[data.lang=='en']\ndata['sentences'] = data.articles.progress_map(sent_tokenize)\ndata['sentences'].head(1).tolist()[0][:3] # Print the first 3 sentences of the 1st article\n```\n\n\n    HBox(children=(HTML(value=''), FloatProgress(value=0.0, max=2243.0), HTML(value='')))\n\n\n    \n\n\n\n\n\n    ['Australia health orders This thread is political as it is about current politically motivated restrictions in Australia.',\n     \"Aus bros I need some help here, I hear a lot about legal restrictions and confronting police about their legality (I'm in Vic but whatever state).\",\n     'Can you fellas help me and any other aussies with some solid things to say to cops and any advice in general?']\n\n\n\n\n```python\n# %%capture\n\nfrom nltk.tokenize import word_tokenize\ndata['tokens_sentences'] = data['sentences'].progress_map(lambda sentences: [word_tokenize(sentence) for sentence in sentences])\nprint(data['tokens_sentences'].head(1).tolist()[0][:3])\n\n```\n\n\n    HBox(children=(HTML(value=''), FloatProgress(value=0.0, max=2243.0), HTML(value='')))\n\n\n    \n    [['Australia', 'health', 'orders', 'This', 'thread', 'is', 'political', 'as', 'it', 'is', 'about', 'current', 'politically', 'motivated', 'restrictions', 'in', 'Australia', '.'], ['Aus', 'bros', 'I', 'need', 'some', 'help', 'here', ',', 'I', 'hear', 'a', 'lot', 'about', 'legal', 'restrictions', 'and', 'confronting', 'police', 'about', 'their', 'legality', '(', 'I', \"'m\", 'in', 'Vic', 'but', 'whatever', 'state', ')', '.'], ['Can', 'you', 'fellas', 'help', 'me', 'and', 'any', 'other', 'aussies', 'with', 'some', 'solid', 'things', 'to', 'say', 'to', 'cops', 'and', 'any', 'advice', 'in', 'general', '?']]\n\n\n\n```python\n# %%capture\n\nfrom nltk import pos_tag\ndata['POS_tokens'] = data['tokens_sentences'].progress_map(lambda tokens_sentences: [pos_tag(tokens) for tokens in tokens_sentences])\nprint(data['POS_tokens'].head(1).tolist()[0][:3])\n```\n\n\n    HBox(children=(HTML(value=''), FloatProgress(value=0.0, max=2243.0), HTML(value='')))\n\n\n    \n    [[('Australia', 'NNP'), ('health', 'NN'), ('orders', 'NNS'), ('This', 'DT'), ('thread', 'NN'), ('is', 'VBZ'), ('political', 'JJ'), ('as', 'IN'), ('it', 'PRP'), ('is', 'VBZ'), ('about', 'IN'), ('current', 'JJ'), ('politically', 'RB'), ('motivated', 'JJ'), ('restrictions', 'NNS'), ('in', 'IN'), ('Australia', 'NNP'), ('.', '.')], [('Aus', 'NNP'), ('bros', 'NN'), ('I', 'PRP'), ('need', 'VBP'), ('some', 'DT'), ('help', 'NN'), ('here', 'RB'), (',', ','), ('I', 'PRP'), ('hear', 'VBP'), ('a', 'DT'), ('lot', 'NN'), ('about', 'IN'), ('legal', 'JJ'), ('restrictions', 'NNS'), ('and', 'CC'), ('confronting', 'VBG'), ('police', 'NNS'), ('about', 'IN'), ('their', 'PRP$'), ('legality', 'NN'), ('(', '('), ('I', 'PRP'), (\"'m\", 'VBP'), ('in', 'IN'), ('Vic', 'NNP'), ('but', 'CC'), ('whatever', 'WDT'), ('state', 'NN'), (')', ')'), ('.', '.')], [('Can', 'MD'), ('you', 'PRP'), ('fellas', 'VB'), ('help', 'VB'), ('me', 'PRP'), ('and', 'CC'), ('any', 'DT'), ('other', 'JJ'), ('aussies', 'NNS'), ('with', 'IN'), ('some', 'DT'), ('solid', 'JJ'), ('things', 'NNS'), ('to', 'TO'), ('say', 'VB'), ('to', 'TO'), ('cops', 'NNS'), ('and', 'CC'), ('any', 'DT'), ('advice', 'NN'), ('in', 'IN'), ('general', 'JJ'), ('?', '.')]]\n\n\n\n```python\n# %%capture\n\n# Inspired from https://stackoverflow.com/a/15590384\nfrom nltk.corpus import wordnet\nfrom nltk.stem.wordnet import WordNetLemmatizer\n\n\ndef get_wordnet_pos(treebank_tag):\n\n    if treebank_tag.startswith('J'):\n        return wordnet.ADJ\n    elif treebank_tag.startswith('V'):\n        return wordnet.VERB\n    elif treebank_tag.startswith('N'):\n        return wordnet.NOUN\n    elif treebank_tag.startswith('R'):\n        return wordnet.ADV\n    else:\n        return ''\n\nlemmatizer = WordNetLemmatizer()\n\n# Lemmatizing each word with its POS tag, in each sentence\ndata['tokens_sentences_lemmatized'] = data['POS_tokens'].progress_map(\n    lambda list_tokens_POS: [\n        [\n            lemmatizer.lemmatize(el[0], get_wordnet_pos(el[1])) \n            if get_wordnet_pos(el[1]) != '' else el[0] for el in tokens_POS\n        ] \n        for tokens_POS in list_tokens_POS\n    ]\n)\n\ndata['tokens_sentences_lemmatized'].head(1).tolist()[0][:3]\n```\n\n\n    HBox(children=(HTML(value=''), FloatProgress(value=0.0, max=2243.0), HTML(value='')))\n\n\n    \n\n\n\n\n\n    [['Australia',\n      'health',\n      'order',\n      'This',\n      'thread',\n      'be',\n      'political',\n      'as',\n      'it',\n      'be',\n      'about',\n      'current',\n      'politically',\n      'motivated',\n      'restriction',\n      'in',\n      'Australia',\n      '.'],\n     ['Aus',\n      'bros',\n      'I',\n      'need',\n      'some',\n      'help',\n      'here',\n      ',',\n      'I',\n      'hear',\n      'a',\n      'lot',\n      'about',\n      'legal',\n      'restriction',\n      'and',\n      'confront',\n      'police',\n      'about',\n      'their',\n      'legality',\n      '(',\n      'I',\n      \"'m\",\n      'in',\n      'Vic',\n      'but',\n      'whatever',\n      'state',\n      ')',\n      '.'],\n     ['Can',\n      'you',\n      'fellas',\n      'help',\n      'me',\n      'and',\n      'any',\n      'other',\n      'aussie',\n      'with',\n      'some',\n      'solid',\n      'thing',\n      'to',\n      'say',\n      'to',\n      'cop',\n      'and',\n      'any',\n      'advice',\n      'in',\n      'general',\n      '?']]\n\n\n\n\n```python\n# %%capture\n\nfrom nltk.corpus import stopwords\n\nstopwords_verbs = ['https', 'http', 'say', 'get', 'go', 'know', 'may', 'need', 'like', 'make', 'see', 'want', 'come', 'take', 'use', 'would', 'can']\nstopwords_other = ['one', 'mr', 'image', 'getty', 'de', 'en', 'caption', 'also', 'copyright', 'something']\nmy_stopwords = stopwords.words('english') + stopwords_verbs + stopwords_other\n\n```\n\n\n```python\n# %%capture\n\nfrom itertools import chain # to flatten list of sentences of tokens into list of tokens\ndata['tokens'] = data['tokens_sentences_lemmatized'].map(lambda sentences: list(chain.from_iterable(sentences)))\ndata['tokens'] = data['tokens'].map(lambda tokens: [token.lower() for token in tokens if token.isalpha() \n                                                    and token.lower() not in my_stopwords and len(token)>1])\ndata['tokens'].head(1).tolist()[0][:30]\n\n```\n\n\n\n\n    ['australia',\n     'health',\n     'order',\n     'thread',\n     'political',\n     'current',\n     'politically',\n     'motivated',\n     'restriction',\n     'australia',\n     'aus',\n     'bros',\n     'help',\n     'hear',\n     'lot',\n     'legal',\n     'restriction',\n     'confront',\n     'police',\n     'legality',\n     'vic',\n     'whatever',\n     'state',\n     'fellas',\n     'help',\n     'aussie',\n     'solid',\n     'thing',\n     'cop',\n     'advice']\n\n\n\n\n```python\n# %%capture\n\nfrom gensim.models import Phrases\nfrom gensim import corpora\n\ntokens = data['tokens'].tolist()\nbigram_model = Phrases(tokens)\ntrigram_model = Phrases(bigram_model[tokens], min_count=1)\ntokens = list(trigram_model[bigram_model[tokens]])\n\ndictionary_LDA = corpora.Dictionary(tokens)\ndictionary_LDA.filter_extremes(no_below=3)\ncorpus = [dictionary_LDA.doc2bow(tok) for tok in tokens]\n\n```\n\n\n```python\n# %%capture\n\nfrom gensim import models\nimport numpy as np\n\nnp.random.seed(123456)\nnum_topics = 20\n%time lda_model = models.LdaModel(corpus, num_topics=num_topics, \\\n                                  id2word=dictionary_LDA, \\\n                                  passes=4, alpha=[0.01]*num_topics, \\\n                                  eta=[0.01]*len(dictionary_LDA.keys()))\n\n\n\n\n\n```\n\n    CPU times: user 9.72 s, sys: 0 ns, total: 9.72 s\n    Wall time: 9.73 s\n\n\n\n```python\n# %%capture\n\nimport seaborn as sns;\n\ntopics = [lda_model[corpus[i]] for i in range(len(data))]\n\ndef topics_document_to_dataframe(topics_document, num_topics):\n    res = pd.DataFrame(columns=range(num_topics))\n    for topic_weight in topics_document:\n        res.loc[0, topic_weight[0]] = topic_weight[1]\n    return res\n\n\n# Like TF-IDF, create a matrix of topic weighting, with documents as rows and topics as columns\ndocument_topic = pd.concat([topics_document_to_dataframe(topics_document, num_topics=num_topics) for topics_document in topics]) \\\n  .reset_index(drop=True).fillna(0)\n\n\n\n```\n\n\n```python\n# %%capture\n\ndocument_topic.head()\n\n%matplotlib inline\nsns.set(rc={'figure.figsize':(10,20)})\nsns.heatmap(document_topic.loc[document_topic.idxmax(axis=1).sort_values().index])\n```\n\n\n```python\n# %%capture\n\nsns.set(rc={'figure.figsize':(10,5)})\ndocument_topic.idxmax(axis=1).value_counts().plot.bar(color='lightblue')\n```\n\n\n```python\n# %%capture\n\n# https://cran.r-project.org/web/packages/LDAvis/vignettes/details.pdf\n# Here a short legend to explain the vis:\n# size of bubble: proportional to the proportions of the topics across the N total tokens in the corpus\n# red bars: estimated number of times a given term was generated by a given topic\n# blue bars: overall frequency of each term in the corpus\n# -- Relevance of words is computed with a parameter lambda\n# -- Lambda optimal value ~0.6 (https://nlp.stanford.edu/events/illvi2014/papers/sievert-illvi2014.pdf)\n%matplotlib inline\nimport pyLDAvis\nimport pyLDAvis.gensim\nvis = pyLDAvis.gensim.prepare(topic_model=lda_model, corpus=corpus, dictionary=dictionary_LDA)\npyLDAvis.enable_notebook()\npyLDAvis.display(vis)\n\n```\n\n\n\n\n\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdn.rawgit.com/bmabey/pyLDAvis/files/ldavis.v1.0.0.css\">\n\n\n<div id=\"ldavis_el39371406751055124482297732244\"></div>\n\n\n\n\n\n```python\n# %%capture\nfrom wordcloud import WordCloud,STOPWORDS\n\ndef showWordCloud(data):\n    words = ' '.join(data)\n    cleaned_word = \" \".join([word for word in words.split()])\n    wordcloud = WordCloud(stopwords = STOPWORDS,\n                         background_color = 'black',\n                         width = 2500,\n                         height = 2500\n                         ).generate(cleaned_word)\n    plt.figure(1,figsize = (13,13))\n    plt.imshow(wordcloud)\n    plt.axis('off')\n    plt.show()\n\nflat_list = [item for sublist in tokens for item in sublist]\n\n#flat_list\nshowWordCloud(flat_list)\n```\n\n# Comparison Questions\n\n### Q1.) ***What is the archiving service 4plen coverage of 4chan and what is the quality of the coverage?***\n\n\nBetween the dates of **{{_from_date.strftime(\"%d/%m/%Y, %H:%M:%S\") }}** and **{{_to_date.strftime(\"%d/%m/%Y, %H:%M:%S\") }}** we have crawled **{{ \"{:,}\".format(len(match_result)) }}** threads on 4chan /pol board. \n\nOf these, we have collected data from all three sources - 4chan scrap using OXPath, 4chan API and 4pleb API (i.e. scraped thread, posts content and metadata) on **{{full_match_len}} / {{\"%.3f\" % (full_match_len/len(match_result)*100)}} %** of the results.\n\nWe have found on the 4chan archiving service, 4pleb, **{{match_result.pleb.sum()}}  / {{\"%.3f\" % perc_match }}%** of the results.\n\nLooking into the remainder **{{ len(match_result) - match_result.pleb.sum() }} / {{\"%.3f\" % perc_not_match }}%** that are not found in the archiving service we have noticed that: \n\n- We have scraped **{{ len(not_pleb_yes_chan) }} / {{ \"%.3f\" % (len(not_pleb_yes_chan)/len(not_pleb_match)*100) }}%** threads from 4chan API but not found on 4pleb. \n- We have scraped **{{ len(not_pleb_yes_chan_or_oxp) }} / {{ \"%.3f\" % (len(not_pleb_yes_chan_or_oxp)/len(not_pleb_match)*100) }}** using OXPath or 4chan API scraping methods. Of these **{{ len(not_pleb_match.query(\"oxp\")) }}** is the number of items scraped using OXPath.\n\nThe analysis of the deleted threads could lead to insight on how threads are being monitored \n\n- There are **{{ \"{:,}\".format(len(match_result.query(\"deleted==True\"))) }}** threads that have been marked as deleted by the OXPath scraper. Of the deleted threads, **{{ \"{:,}\".format(len(match_result.query(\"pleb\").query(\"deleted==True\"))) }}** have been found been found on the 4pleb archiving API. \n- There are **{{ len(id_chan_posts) }}** threads found on 4chan API that have been marked as deleted. **{{ num_del_chan }}** have also been found and marked as deleted by OXpath scraper\n- There are **{{ len(pleb_posts.query(\"deleted=='1'\")) }}** threads marked as deleted in 4pleb. **{{len(match_result[match_result['num'].isin(id_pleb_posts)].query('deleted==True'))}}** have also been found and marked as deleted by OXpath scraper\n\nThe deleted threads seems to behave according to the following pattern:\n\n* Threads are posted by original poster (op)\n* There is some activity on the thread (replies and/or reads) \n* The thread becomes in-accessible and its URL return *404 - Page not found*\n    * The OXPath scraper marks the thread as deleted\n* Some threads are deleted permanently whilst others are returned on the main board and the activity continues\n    * We can assume that **{{ \"%.3f\" % ( (len(pleb_posts.query(\"deleted=='1'\")) / len(match_result.query(\"pleb\").query(\"deleted==True\"))) * 100)  }}%** of the cases that 4pleb also finds to be deleted, is the actual number of deleted threads\n    \n\n\n### Q1.1) - What topics of threads are being deleted and what is the difference between the ones permanently deleted and the ones put back on the board? \n\nWhen analysing deleted threads we have to take into consideration the following question: \n    ***How do we know when a thread has been deleted?*** \n\nThe question is non trivial because ultimately ***all*** threads get deleted from 4chan. We are interested in a ***deleted*** status of the thread outside of it's expected life cycle.  The live expectancy of a thread $L_t$ (i.e. the elapsed amount of time during which a thread is reachable by it's uniquer URL) is composed of two components: $E_b$ - *Elapsed* time on the *board* and $E_a$ - *Elapsed* time *archived*. \n\n\\begin{equation} \\label{eq1}\n    L_t = E_b + E_a \n\\end{equation}\n\nThe second component $E_a$ is expected to be constant. All threads remain available for three days after they are archived. <span class=\"mark\">(add reference)</span>\n\nThe first element, the elapsed time a thread spends on the board $E_b$, is an entity of time, and function of activity and janitor moderation. The activity on a thread is a combination of posts/images/authors. We can simplify this by only considering the number of posts (i.e. replies). Each new post bumps the thread up on the board, delaying it's archiving time <span class=\"mark\">(add reference)</span> . The bumping effect is also a function that decays with time. Alternatively, since $E_b$ already represents time, it can be expressed based on the number of posts $p$. Similarly, the rate of decay $\\beta$  grows as the number of posts on the thread grows (each posts bumps the thread up a bit, but every time less than the previous).\n\n\nFurthermore, emerging from data, at times threads gets removed from the board and appear to be deleted. This is expected as 4chan has various levels of moderation by its *janitors*. Since threads can also be in a deleted state and then put back in the live board we are going to consider $P(d)$ as the probability of a threat being deleted with it's values $P(d) \\in [0,1]  where  P(d)=0$ thread was not deleted, $P(d)=1$ thread was deleted, $P(d) \\in (0,1)$ thread was deleted for a certain amount of time as percentage of its elapsed time and then put back in the live board.\n\n\\begin{equation}\n    E_b = [log(np)(1-\\frac{p}{max_p})^{log(p)}]*(1-P(d))\n\\end{equation}\n\nSince we know that n = 200, and assuming $P(d)$ only affects threads in the live board\n\n\\begin{equation}\n    L_t = [log(200p)(1-\\frac{p}{max_p})^{log(p)}]*(1-P(d)) + E_a\n\\end{equation}\n\nwhere \n\n- $L_t$ Elapsed life (time) of a thread\n- $n$ Number of threads on the board\n- $p$ Number of posts on the thread\n- $max_p$ The maximum number of posts any thread on the board has\n- $\\beta = p/max_p$ rate of decay of the thread through out the board\n- $P(d)$ The probability that a thread has been deleted\n- $E_a$ The elapsed time during which the thread is available in the archived board\n\n<span class=\"burk\">Should a.) Load all threads, nr_replies, elapsed time between start date and last post, deleted flag b.) plot calculated time and observed time, c.) check difference and formula fit. \n</span>\n\n<span class=\"burk\">**(question outside of main quest - dropping it)**</span>\n\n\n\n```python\n# %%capture\nprint('Plot showing the distribution of number of replies for missed threads)')\n\nf2 = f1[f1.chan == True]\nchan_op = pd.DataFrame(list(f2['chan_op']))\nchan_op.drop(axis=1, inplace=True, columns=['md5', 'resto', 'imagelimit', 'troll_country'])#, 'm_img', 'tail_size', 'trip'])\nchan_op.drop(axis=1, inplace=True, columns=['ext',\t'w',\t'h',\t'tn_w',\t'tn_h',\t\n                      'tim',\t'time',\t'fsize',\t'country',\n                      'archived',\t'bumplimit',\t'semantic_url',\n                      'country_name',\t'images'])\nchan_op = chan_op.sort_values('replies', ascending=False)\nplt.hist(chan_op.replies, bins=20)\n\n```\n\n\n```python\n# %%capture\nimport time\nfrom datetime import datetime\n\nprint('Plot showing the time to being arcived of the threads not captured)')\n\ntime_op = pd.DataFrame([chan_op.no, chan_op.archived_on, chan_op.now])\ntime_op = time_op.transpose()\ntime_op['now'] = pd.to_datetime(time_op['now'] , format='%m/%d/%y(%a)%X')\n#time_op['archived_on'] = time_op['archived_on'].apply(time.localtime)\ntime_op['archived_on'] = time_op['archived_on'].apply(datetime.fromtimestamp)\ntime_op['length'] =  (time_op.archived_on - time_op.now).astype('timedelta64[h]')\ntime_op = time_op.sort_values(['length'])\nplt.hist(time_op.length, bins=20)\n\n```\n\n\n```python\n# %%capture\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams.update({'figure.figsize':(7,5), 'figure.dpi':100})\n\nplt.hist(count, bins=50)\nplt.gca().set(title='Frequency Histogram', ylabel='Frequency');\n\n\n```\n\n\n```python\n# %%capture\npipeline = [ \n            {\"$match\": {\"api_scrap\": True } }, { \"$addFields\": {\n        \"pleb_array\": {\n                \"$ifNull\": [ {\"$objectToArray\": \"$pleb\"}, [ ] ] \n        }\n    } },     \n    {\"$project\": {\"_id\": 0, \"url\": \"$_id\", \"api_chan_posts\": { \"$size\": { \"$ifNull\": [ \"$chan.posts\", [ ] ] } } ,\n                \"api_chan_op\": {\"$arrayElemAt\": [\"$chan.posts\", 0 ] }, \"pleb_array\": {\"$arrayElemAt\": [\"$pleb_array\", 0 ] } } },\n    {\"$project\": {\"url\": 1, \"api_chan_posts\": 1, \"api_chan_op\": 1\n                ,\"api_pleb_posts\":  {\"$ifNull\": [ {\"$objectToArray\": \"$pleb_array.v.posts\"}, [ ] ] } \n                ,\"api_pleb_op\": \"$pleb_array.v.op\"  } } ,\n     {\"$project\": {\"url\": 1, \"api_chan_posts\": 1, \"api_chan_op\": 1, \"api_pleb_op\": 1, \"api_pleb_posts\": {\"$size\": \"$api_pleb_posts\"} } }\n]\n\n\nthread_data = pd.DataFrame(threads.aggregate(pipeline, allowDiskUse=True))\n\n```\n\n\n```python\n# %%capture\npipeline = [\n    {\"$match\": {\"$and\": [{ \"data\": {\"$ne\": None } },{\"data\": {\"$type\": \"array\" } } ] } }\n   ,{\"$project\": { \"url\": 1, \"chan_posts\": {\"$arrayElemAt\": [\"$data\", -1 ] } } } \n   ,{\"$project\": { \"url\": 1, \"chan_posts\": {\"$arrayElemAt\": [\"$chan_posts.payload.thread\", 0] } } }\n   ,{\"$project\": { \"_id\":0, \"url\": 1, \"chan_posts\": {\"$size\": {\"$ifNull\": [ \"$chan_posts.replies\", [ ] ] } }, \n       \"chan_op\": \"$chan_posts.op\" } } \n   ,{\"$unwind\": \"$chan_op\"}\n]\n\noriginal_thread_data = pd.DataFrame(livechan.aggregate(pipeline, allowDiskUse=True))\nlen(original_thread_data)\n# sum(original_thread_data['chan_posts'])\n\n```\n\n\n```python\n# %%capture\nimport json\n#plt.plot(thread_data['api_chan_posts'] - thread_data['api_bleb_posts'])\nmerged_data = pd.merge(thread_data, original_thread_data, on=[\"url\"])\nmerged_data['diff_posts'] = abs(merged_data['api_chan_posts'] - merged_data['api_pleb_posts'])\nmerged_data = merged_data.sort_values(by=['diff_posts'], ascending=False)\nprint(f'OXpath Threads {len(original_thread_data)}')\nprint(f'4Pleb and 4 Chan Threads {len(thread_data)}')\nprint(f'Merged match {len(merged_data)}')\n\n# merged_data.api_chan_op[merged_data.api_chan_op == None]['api_chan_op'] = { }\n# merged_data.api_chan_op1 = pd.DataFrame(list(merged_data.api_chan_op))\n\n```\n\n\n```python\n# %%capture\nimport numpy\nimport scipy.stats as ss\nno_api_chan = merged_data[~merged_data.api_chan_op.isnull()].sort_values(by=['diff_posts'], ascending=False)\nno_api_pleb = no_api_chan[~no_api_chan.api_pleb_op.isnull()].sort_values(by=['diff_posts'], ascending=False)\n#no_api_pleb = no_api_pleb[no_api_pleb.diff_posts > 0]\n#print(no_api_pleb.diff_posts.mean())\n#print(no_api_pleb.diff_posts.std())\n#ss.describe(no_api_pleb.diff_posts)\n#diff_pdf = ss.norm.pdf(no_api_pleb.diff_posts, 0, 1)\n#plt.plot(no_api_pleb.diff_posts, diff_pdf, label='pdf')\n\nmu = 0\nsigma = 1\ndiff_cdf = ss.norm.cdf(no_api_pleb.diff_posts, mu, sigma)\ndiff_pdf = ss.norm.pdf(no_api_pleb.diff_posts, mu, sigma)\n\nfig=plt.figure()\nax=fig.add_subplot(111)\nax.plot(no_api_pleb.diff_posts, diff_pdf, label='pdf')\nax.plot(no_api_pleb.diff_posts, diff_cdf, label='cdf')\nax.set_xlim(xmin=0.0, xmax=10)\nax.legend()\nplt.show()\n\n```\n\n\n\n### Q2.) What is the persentage of posts that can be matched on all three crawling methods and what are the gaps\n\nWhilst looking at the thread coverage from the archiving sites, we can see promising results with matching results well above $95.00$% another question is around the quality of the coverage. That is, do the threads discovered and retrieved from the archiving services (in this case 4pleb API) have the same information as what retrieved from 4chan API and/or OXPath scraping method?\n\nThe best way to look at quality would be to: \n1. verify that the thread contains and matches some of the key metadata (such as date it was posted, date it was archived, author country) \n2. verify that the thread contains and matches its main content (such as subject, comment, media) and lastly \n3. verify that the linked posts match with what is reported from 4chan API and/or OXPath scraping method. \n\n\n\n\n### Q3.) What can be said about the significat amount of threads that get flagged/marked as \"deleted/404\" and either permanently deleted or returned to the board. What topics get permanently deleted? What topics get flagged? \n", "meta": {"hexsha": "01f23bab94cb8a465303d013037beb90b173c4ea", "size": 832518, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "jupyter/4chan-diff-threads.ipynb", "max_stars_repo_name": "yprift01/4chan-data-project", "max_stars_repo_head_hexsha": "4d95214d05f6deb813fdf7a000317214c3232bdd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jupyter/4chan-diff-threads.ipynb", "max_issues_repo_name": "yprift01/4chan-data-project", "max_issues_repo_head_hexsha": "4d95214d05f6deb813fdf7a000317214c3232bdd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jupyter/4chan-diff-threads.ipynb", "max_forks_repo_name": "yprift01/4chan-data-project", "max_forks_repo_head_hexsha": "4d95214d05f6deb813fdf7a000317214c3232bdd", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 385.425, "max_line_length": 418380, "alphanum_fraction": 0.8603922077, "converted": true, "num_tokens": 13073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05749328364515303, "lm_q2_score": 0.024053550795599548, "lm_q1q2_score": 0.001382917618564501}}
{"text": "<a href=\"https://colab.research.google.com/github/rameshveer/NLP_Projects_TSAI/blob/main/END_S5_RNN_LSTM.ipynb\" target=\"_parent\"></a>\n\n#Imports\n\n\n```\nimport numpy as np\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom IPython import display\nplt.style.use('seaborn-white')\n```\n\n# Read and process data. \n\nDownload the file from this URL: https://drive.google.com/file/d/1UWWIi-sz9g0x3LFvkIZjvK1r2ZaCqgGS/view?usp=sharing\n\n\n```\ndata = open('text.txt', 'r').read()\n```\n\n\n```\ndata\n```\n\n\n\n\n    'A coronavirus is a kind of common virus that causes an infection in your nose, sinuses, or upper throat. Most coronaviruses are not dangerous.\\n\\nSome types of coronaviruses are serious, though. About 858 people have died from Middle East respiratory syndrome (MERS), which first appeared in 2012 in Saudi Arabia and then in other countries in the Middle East, Africa, Asia, and Europe. In April 2014, the first American was hospitalized for MERS in Indiana and another case was reported in Florida. Both had just returned from Saudi Arabia. In May 2015, there was an outbreak of MERS in Korea, which was the largest outbreak outside of the Arabian Peninsula. In 2003, 774 people died from a severe acute respiratory syndrome (SARS) outbreak. As of 2015, there were no further reports of cases of SARS. \\n\\nBut in early 2020, following a December 2019 outbreak in China, the World Health Organization identified a new type, 2019 novel coronavirus (2019-nCoV).\\n\\nOften a coronavirus causes upper respiratory infection symptoms like a stuffy nose, cough, and sore throat. You can treat them with rest and over-the-counter medication. The coronavirus can also cause middle ear infections in children.\\n\\nWhat Is a Coronavirus?\\nCoronaviruses were first identified in the 1960s, but we don\\'t know where they come from. They get their name from their crown-like shape. Sometimes, but not often, a coronavirus can infect both animals and humans.\\n\\nMost coronaviruses spread the same way other cold-causing viruses do: through infected people coughing and sneezing, by touching an infected person\\'s hands or face, or by touching things such as doorknobs that infected people have touched.\\n\\nAlmost everyone gets a coronavirus infection at least once in their life, most likely as a young child. In the United States, coronaviruses are more common in the fall and winter, but anyone can come down with a coronavirus infection at any time.\\n\\nCommon Symptoms of Coronavirus\\nThe symptoms of most coronaviruses are similar to any other upper respiratory infection, including runny nose, coughing, sore throat, and sometimes a fever. In most cases, you won\\'t know whether you have a coronavirus or a different cold-causing virus, such as rhinovirus.\\n\\nYou could get lab tests, including nose and throat cultures and blood work, to find out whether your cold was caused by a coronavirus, but there\\'s no reason to. The test results wouldn\\'t change how you treat your symptoms, which typically go away in a few days.\\n\\nBut if a coronavirus infection spreads to the lower respiratory tract (your windpipe and your lungs), it can cause pneumonia, especially in older people, people with heart disease, or people with weakened immune systems.\\n\\nWhat to Do About Coronavirus\\nThere is no vaccine for coronavirus. To help prevent a coronavirus infection, do the same things you do to avoid the common cold:\\n\\nWash your hands thoroughly with soap and warm water or with an alcohol-based hand sanitizer.\\nKeep your hands and fingers away from your eyes, nose, and mouth.\\nAvoid close contact with people who are infected.\\nYou treat a coronavirus infection the same way you treat a cold:\\n\\nGet plenty of rest.\\nDrink fluids.\\nTake over-the-counter medicine for a sore throat and fever. But don\\'t give aspirin to children or teens younger than 19; use ibuprofen or acetaminophen instead.\\nA humidifier or steamy shower can also help ease a sore and scratchy throat.\\n\\nEven when a coronavirus causes MERS or SARS in other countries, the kind of coronavirus infection common in the U.S. isn\\'t a serious threat for an otherwise healthy adult. If you get sick, treat your symptoms and contact a doctor if they get worse or don\\'t go away.\\n\\nNews about the coronavirus outbreak that started in Wuhan, China, is changing rapidly. The respiratory infection, which is closely related to SARS and MERS, has been spreading across China, and cases have been diagnosed in several other countries, including the United States. We\u2019ll provide the latest updates on cases, deaths, travel restrictions, and more here.\\n\\nWhat is the latest news?\\nOn Wednesday, CDC medical officers and others met a group of about 210 U.S. citizens evacuated from China. Their plane landed at March Air Reserve Base in California, where the evacuees will be monitored for coronavirus symptoms for several days. Anyone showing signs of the disease will be taken to the hospital.\\n\\nSome airlines, including British Airways and United Airlines, are stopping or reducing flights to China as the number of cases continues to rise rapidly. Worldwide there are now more than 6,000 cases and 132 deaths, according to the European Centre for Disease Prevention and Control. While the majority of cases center in China, it has been found in the U.S. and these countries: Thailand, Hong Kong, Taiwan, Australia, Macau, Singapore, Japan, South Korea, Malaysia, France, Canada, Vietnam, Nepal, Cambodia, Germany and United Arab Emirates. There have been no deaths outside China.\\n\\nIn the U.S., the CDC is reporting five confirmed cases from these states: Washington, Illinois, California and Arizona. On Monday, Jan. 27, Nancy Messonnier, MD, Director of the agency\\'s National Center for Immunization and Respiratory Diseases, said it had 165 persons under investigation for coronavirus from 36 states. In addition to the 5 confirmed positive, 68 have tested negative. They are prioritizing the testing based on a person\u2019s risk.\\n\\nMessonnier said they had posted the blueprints for their diagnostic test on a public server and were working \"as fast as we can\" to get test kits out to states. \\n\\nRight now, all the testing for the new coronavirus is taking place at the CDC\\'s headquarters in Atlanta.\\n\\nShe said the CDC was mulling a change to its travel screening for the infection, but did not give further details.\\n\\nHow many people have been diagnosed with the virus, and how many have died?\\nAccording to European CDC, the majority of the confirmed cases \u2013 5,994 \u2013 are in China. Another 78 cases are confirmed outside of China in 16 countries. Countries with the most confirmed cases include Thailand with 14 and Taiwan and South Korea with 8 each. All reported deaths have been in China, and include 16 healthcare workers.\\n\\nWhen did the outbreak start?\\nChina first reported the outbreak in Wuhan on Dec. 30, 2019.\\n\\nWhat are public officials doing to contain the virus?\\nOn Tuesday, the CDC urged travelers to avoid non-essential travel to China.\\n\\nChinese officials have shut down all public transportation to 10 cities, affecting 35 million people. The first was Wuhan, which has a population of about 11 million. In Wuhan, that includes buses, subways, trains, and the airport.\\n\\nAll passengers flying into the United States from Wuhan will be routed through one of five airports and screened for fever and other signs of the virus. \u201cPatients of concern\ufffd\ufffd\ufffd will be referred to a facility and given a test to find out if they have the virus.\\n\\nWhat do we know about cases in the United States?\\nIn all U.S. cases so far, patients had recently traveled to Wuhan.\\n\\nCalifornia has two patients, one in Los Angeles County and one in Orange County. The patient from Orange County is a man in his 50s. He is in a local hospital in isolation and is in good condition, according to the Orange County Health Care Agency. Los Angeles County officials did not provide additional details about the patient there.\\n\\nArizona\\'s Department of Health Services said its patient is a Maricopa County resident and member of the Arizona State University community who did not live in student housing. The patient is not severely ill and is being kept in isolation. \\n\\nAnother case involves a woman in her 60s from Chicago. The Chicago Department of Public Health reported that she had visited Wuhan, China in December and returned to Chicago earlier this month. She is hospitalized in stable condition. \\n\\nThe first U.S. patient is a man in his 30s from Washington state. He had traveled from Wuhan and entered the country before the screening was in place. He started having symptoms and contacted his doctor. He is in good condition and is in isolation at Providence Regional Medical Center.\\n\\nIs travel to China safe?\\nWuhan is closed to travelers.\\n\\nThe CDC is advising that travelers avoid non-essential travel to China. Travelers who do go should:\\n\\nAvoid contact with sick people.\\nAvoid animals, animal markets, and products that come from animals.\\nWash their hands often with soap and water, or use an alcohol-based sanitizer if that\u2019s not available.\\nSeek medical care right away for a fever, cough, or difficulty breathing. Tell a health care professional about any travel.\\nWhat are the symptoms, and how is the virus diagnosed?\\nChina created a test for the virus and shared that information with other countries. The CDC has developed its own test.\\n\\nSymptoms include a fever, coughing, and shortness of breath. They may appear 2 to 14 days after you\u2019re exposed to the virus.\\n\\nWhat is the source of the virus, and how is it spread?\\nHealth officials are not sure of the source of the virus yet or how easily it can spread. Coronaviruses are found in many different animals, including camels, cattle, cats, and bats. One research paper also suggested snakes as a possible source. The new virus may be linked to a seafood and live animal market in Wuhan that has since been closed\\n\\nThe virus can spread from person to person. Health officials are seeing this happen most often where people are close together and in health care settings. To date, 16 health care workers have been infected.\\n\\nThe CDC believes that severe acute respiratory syndrome (SARS) and Middle East respiratory syndrome (MERS), two other types of coronavirus, are spread through droplets when someone coughs or sneezes.\\n\\nIs there a vaccine?\\nThere is no vaccine, but the National Institutes of Health is working on one and hopes to begin testing in several months. That testing would be for safety. If it\u2019s safe, there would be testing to see how well it works.\\n\\nHow is it treated?\\nThere is no specific treatment for the virus. Patients are generally given supportive care for their symptoms, such a fluids and pain relievers. Hospitalized patients may need support with breathing.'\n\n\n\nProcess data and calculate indices\n\n\n```\nchars = list(set(data))\nprint(chars)\ndata_size, X_size = len(data), len(chars)\nprint(\"Corona Virus article has %d characters, %d unique characters\" %(data_size, X_size))\nchar_to_idx = {ch:i for i,ch in enumerate(chars)}\nidx_to_char = {i:ch for i,ch in enumerate(chars)}\nprint(char_to_idx)\nprint(idx_to_char)\n```\n\n    ['V', '3', '\u2013', \"'\", ')', 'J', 'g', 'f', 'K', '8', 'Y', 'r', 'H', '6', 'W', 'a', '\u2019', 'i', 'S', '0', 'y', 'z', 'o', 'c', '2', 'R', 'm', 'P', 'O', 'I', 'l', 'N', '1', 'M', '4', ':', 'q', '\u201c', 'L', 'F', 'A', '\ufffd', 'C', 'j', 't', 'b', ',', 'E', 'e', 'B', 'x', 's', '-', '\"', 'w', '7', 'D', 'v', 'U', 'T', '?', ' ', '.', 'G', 'd', 'k', '5', ';', '(', 'n', '\\n', '9', 'h', 'u', 'p']\n    Corona Virus article has 10223 characters, 75 unique characters\n    {'V': 0, '3': 1, '\u2013': 2, \"'\": 3, ')': 4, 'J': 5, 'g': 6, 'f': 7, 'K': 8, '8': 9, 'Y': 10, 'r': 11, 'H': 12, '6': 13, 'W': 14, 'a': 15, '\u2019': 16, 'i': 17, 'S': 18, '0': 19, 'y': 20, 'z': 21, 'o': 22, 'c': 23, '2': 24, 'R': 25, 'm': 26, 'P': 27, 'O': 28, 'I': 29, 'l': 30, 'N': 31, '1': 32, 'M': 33, '4': 34, ':': 35, 'q': 36, '\u201c': 37, 'L': 38, 'F': 39, 'A': 40, '\ufffd': 41, 'C': 42, 'j': 43, 't': 44, 'b': 45, ',': 46, 'E': 47, 'e': 48, 'B': 49, 'x': 50, 's': 51, '-': 52, '\"': 53, 'w': 54, '7': 55, 'D': 56, 'v': 57, 'U': 58, 'T': 59, '?': 60, ' ': 61, '.': 62, 'G': 63, 'd': 64, 'k': 65, '5': 66, ';': 67, '(': 68, 'n': 69, '\\n': 70, '9': 71, 'h': 72, 'u': 73, 'p': 74}\n    {0: 'V', 1: '3', 2: '\u2013', 3: \"'\", 4: ')', 5: 'J', 6: 'g', 7: 'f', 8: 'K', 9: '8', 10: 'Y', 11: 'r', 12: 'H', 13: '6', 14: 'W', 15: 'a', 16: '\u2019', 17: 'i', 18: 'S', 19: '0', 20: 'y', 21: 'z', 22: 'o', 23: 'c', 24: '2', 25: 'R', 26: 'm', 27: 'P', 28: 'O', 29: 'I', 30: 'l', 31: 'N', 32: '1', 33: 'M', 34: '4', 35: ':', 36: 'q', 37: '\u201c', 38: 'L', 39: 'F', 40: 'A', 41: '\ufffd', 42: 'C', 43: 'j', 44: 't', 45: 'b', 46: ',', 47: 'E', 48: 'e', 49: 'B', 50: 'x', 51: 's', 52: '-', 53: '\"', 54: 'w', 55: '7', 56: 'D', 57: 'v', 58: 'U', 59: 'T', 60: '?', 61: ' ', 62: '.', 63: 'G', 64: 'd', 65: 'k', 66: '5', 67: ';', 68: '(', 69: 'n', 70: '\\n', 71: '9', 72: 'h', 73: 'u', 74: 'p'}\n\n\n# Constants and Hyperparameters\n\n\n```\nHidden_Layer_size = 100 #size of the hidden layer\nTime_steps = 40 # Number of time steps (length of the sequence) used for training\nlearning_rate = 1e-1 # Learning Rate\nweight_sd = 0.1 #Standard deviation of weights for initialization\nz_size = Hidden_Layer_size + X_size #Size of concatenation(H, X) vector\n```\n\n\n```\nz_size\n```\n\n\n\n\n    175\n\n\n\n# Activation Functions and Derivatives\n\n\n```\ndef sigmoid(x):\n    return np.exp(x) / (1 + np.exp(x))\n\ndef dsigmoid(x):\n    return x * (1 - x)\n\ndef tanh(x):\n    x = np.asarray(x)\n    return (np.exp(2*x) - 1) / (np.exp(2 * x) + 1)\n\ndef dtanh(x):\n    return 1 - x * x\n```\n\n# Quiz Question 1\n\nWhat is the value of sigmoid(0) calculated from  your code? (Answer up to 1 decimal point, e.g. 4.2 and NOT 4.29999999, no rounding off).\n\n# Quiz Question 2\n\nWhat is the value of dsigmoid(sigmoid(0)) calculated from your code?? (Answer up to 2 decimal point, e.g. 4.29 and NOT 4.29999999, no rounding off). \n\n# Quiz Question 3\n\nWhat is the value of tanh(dsigmoid(sigmoid(0))) calculated from your code?? (Answer up to 5 decimal point, e.g. 4.29999 and NOT 4.29999999, no rounding off).\n\n# Quiz Question 4\n\nWhat is the value of dtanh(tanh(dsigmoid(sigmoid(0)))) calculated from your code?? (Answer up to 5 decimal point, e.g. 4.29999 and NOT 4.29999999, no rounding off).\n\n\n```\n# Q1\nsigmoid(0)\n```\n\n\n\n\n    0.5\n\n\n\n\n```\n# Q2\ndsigmoid(sigmoid(0))\n```\n\n\n\n\n    0.25\n\n\n\n\n```\n# Q3\ntanh(dsigmoid(sigmoid(0)))\n```\n\n\n\n\n    0.24491866240370913\n\n\n\n\n```\n# Q4\ndtanh(tanh(dsigmoid(sigmoid(0))))\n```\n\n\n\n\n    0.940014848806378\n\n\n\n# Parameters\n\n\n```\nclass Param:\n    def __init__(self, name, value):\n      self.name = name\n      self.v = value # parameter value\n      self.d = np.zeros_like(value) # derivative\n      self.m = np.zeros_like(value) # momentum for Adagrad\n```\n\nWe use random weights with normal distribution (0, weight_sd) for  tanh  activation function and (0.5, weight_sd) for  `sigmoid`  activation function.\n\nBiases are initialized to zeros.\n\n# LSTM \nYou are making this network, please note f, i, c and o (also \"v\") in the image below:\n\n\nPlease note that we are concatenating the old_hidden_vector and new_input.\n\n# Quiz Question 4\n\nIn the class definition below, what should be size_a, size_b, and size_c? ONLY use the variables defined above.\n\n\n```\nsize_a = Hidden_Layer_size# write your code here\nsize_b = z_size# write your code here\nsize_c = X_size# write your code here\n\n\nclass Parameters:\n    def __init__(self):\n        self.W_f = Param('W_f', np.random.randn(size_a, size_b) * weight_sd + 0.5)\n        self.b_f = Param('b_f', np.zeros((size_a, 1)))\n\n        self.W_i = Param('W_i', np.random.randn(size_a, size_b) * weight_sd + 0.5)\n        self.b_i = Param('b_i', np.zeros((size_a, 1)))\n\n        self.W_C = Param('W_C', np.random.randn(size_a, size_b) * weight_sd)\n        self.b_C = Param('b_C', np.zeros((size_a, 1)))\n\n        self.W_o = Param('W_o', np.random.randn(size_a, size_b) * weight_sd + 0.5)\n        self.b_o = Param('b_o', np.zeros((size_a, 1)))\n\n        #For final layer to predict the next character\n        self.W_v = Param('W_v', np.random.randn(X_size, size_a) * weight_sd)\n        self.b_v = Param('b_v', np.zeros((size_c, 1)))\n        \n    def all(self):\n        return [self.W_f, self.W_i, self.W_C, self.W_o, self.W_v,\n               self.b_f, self.b_i, self.b_C, self.b_o, self.b_v]\n        \nparameters = Parameters()\n```\n\n\n```\nparameters.all()\n```\n\n\n\n\n    [<__main__.Param at 0x7f9fd7685cc0>,\n     <__main__.Param at 0x7f9fd767f550>,\n     <__main__.Param at 0x7f9fd767f5c0>,\n     <__main__.Param at 0x7f9fd767f630>,\n     <__main__.Param at 0x7f9fd767f6a0>,\n     <__main__.Param at 0x7f9fd767f4a8>,\n     <__main__.Param at 0x7f9fd767f588>,\n     <__main__.Param at 0x7f9fd767f5f8>,\n     <__main__.Param at 0x7f9fd767f668>,\n     <__main__.Param at 0x7f9fd767f6d8>]\n\n\n\nLook at these operations which we'll be writing:\n\n**Concatenation of h and x:**\n\n$z\\:=\\:\\left[h_{t-1},\\:x\\right]$\n\n$f_t=\\sigma\\left(W_f\\cdot z\\:+\\:b_f\\:\\right)$\n\n$i_i=\\sigma\\left(W_i\\cdot z\\:+\\:b_i\\right)$\n\n$\\overline{C_t}=\\tanh\\left(W_C\\cdot z\\:+\\:b_C\\right)$\n\n$C_t=f_t\\ast C_{t-1}+i_t\\ast \\overline{C}_t$\n\n$o_t=\\sigma\\left(W_o\\cdot z\\:+\\:b_i\\right)$\n\n$h_t=o_t\\ast\\tanh\\left(C_t\\right)$\n\n**Logits:**\n\n$v_t=W_v\\cdot h_t+b_v$\n\n**Softmax:**\n\n$\\hat{y}=softmax\\left(v_t\\right)$\n\n\n\n```\nparam_dict = {x.name: x.v for x in parameters.all()}\nparam_dict.keys()\n```\n\n\n\n\n    dict_keys(['W_f', 'W_i', 'W_C', 'W_o', 'W_v', 'b_f', 'b_i', 'b_C', 'b_o', 'b_v'])\n\n\n\n\n```\ndef forward(x, h_prev, C_prev, p = parameters):\n    assert x.shape == (X_size, 1)\n    assert h_prev.shape == (Hidden_Layer_size, 1)\n    assert C_prev.shape == (Hidden_Layer_size, 1)\n    param_dict = {x.name: x.v for x in parameters.all()}\n    W_f = param_dict['W_f']\n    W_i = param_dict['W_i']\n    W_C = param_dict['W_C']\n    b_f = param_dict['b_f']\n    b_i = param_dict['b_i']\n    b_C = param_dict['b_C']\n    W_o = param_dict['W_o']\n    b_o = param_dict['b_o']\n    W_v = param_dict['W_v']\n    b_v  = param_dict['b_v']\n    z = np.row_stack((h_prev, x))\n    f = sigmoid(np.dot(W_f, z) + b_f)# write your code here\n    i = sigmoid(np.dot(W_i, z) + b_i) # write your code here\n    C_bar =tanh(np.dot(W_C, z) + b_C)# write your code here\n\n    C = f * C_prev + i * C_bar# write your code here\n    o =  sigmoid(np.dot(W_o, z) + b_o )# write your code here\n    h = o * tanh(C)# write your code here\n\n    v = np.dot(W_v, h) + b_v# write your code here\n    y = np.exp(v) / (np.sum(np.exp(v)) + 1e-8) #softmax\n\n    return z, f, i, C_bar, C, o, h, v, y\n```\n\nYou must finish the function above before you can attempt the questions below. \n\n# Quiz Question 5\n\nWhat is the output of 'print(len(forward(np.zeros((X_size, 1)), np.zeros((Hidden_Layer_size, 1)), np.zeros((Hidden_Layer_size, 1)), parameters)))'?\n\n\n```\nprint(len(forward(np.zeros((X_size, 1)), np.zeros((Hidden_Layer_size, 1)), np.zeros((Hidden_Layer_size, 1)), parameters)))\n```\n\n    9\n\n\n# Quiz Question 6. \n\nAssuming you have fixed the forward function, run this command: \nz, f, i, C_bar, C, o, h, v, y = forward(np.zeros((X_size, 1)), np.zeros((Hidden_Layer_size, 1)), np.zeros((Hidden_Layer_size, 1)))\n\nNow, find these values:\n\n\n1.   print(z.shape)\n2.   print(np.sum(z))\n3.   print(np.sum(f))\n\nCopy and paste exact values you get in the logs into the quiz.\n\n\n\n\n```\nprint(z.shape)\nprint(np.sum(z))\nprint(np.sum(f))\n```\n\n    (175, 1)\n    0.0\n    50.0\n\n\n\n```\nz, f, i, C_bar, C, o, h, v, y = forward(np.zeros((X_size, 1)), np.zeros((Hidden_Layer_size, 1)), np.zeros((Hidden_Layer_size, 1)))\n```\n\n# Backpropagation\n\nHere we are defining the backpropagation. It's too complicated, here is the whole code. (Please note that this would work only if your earlier code is perfect).\n\n\n```\ndef backward(target, dh_next, dC_next, C_prev,\n             z, f, i, C_bar, C, o, h, v, y,\n             p = parameters):\n    \n    assert z.shape == (X_size + Hidden_Layer_size, 1)\n    assert v.shape == (X_size, 1)\n    assert y.shape == (X_size, 1)\n    \n    for param in [dh_next, dC_next, C_prev, f, i, C_bar, C, o, h]:\n        assert param.shape == (Hidden_Layer_size, 1)\n        \n    dv = np.copy(y)\n    dv[target] -= 1\n\n    p.W_v.d += np.dot(dv, h.T)\n    p.b_v.d += dv\n\n    dh = np.dot(p.W_v.v.T, dv)        \n    dh += dh_next\n    do = dh * tanh(C)\n    do = dsigmoid(o) * do\n    p.W_o.d += np.dot(do, z.T)\n    p.b_o.d += do\n\n    dC = np.copy(dC_next)\n    dC += dh * o * dtanh(tanh(C))\n    dC_bar = dC * i\n    dC_bar = dtanh(C_bar) * dC_bar\n    p.W_C.d += np.dot(dC_bar, z.T)\n    p.b_C.d += dC_bar\n\n    di = dC * C_bar\n    di = dsigmoid(i) * di\n    p.W_i.d += np.dot(di, z.T)\n    p.b_i.d += di\n\n    df = dC * C_prev\n    df = dsigmoid(f) * df\n    p.W_f.d += np.dot(df, z.T)\n    p.b_f.d += df\n\n    dz = (np.dot(p.W_f.v.T, df)\n         + np.dot(p.W_i.v.T, di)\n         + np.dot(p.W_C.v.T, dC_bar)\n         + np.dot(p.W_o.v.T, do))\n    dh_prev = dz[:Hidden_Layer_size, :]\n    dC_prev = f * dC\n    \n    return dh_prev, dC_prev\n```\n\n# Forward and Backward Combined Pass\n\nLet's first clear the gradients before each backward pass\n\n\n```\ndef clear_gradients(params = parameters):\n    for p in params.all():\n        p.d.fill(0)\n```\n\nClip gradients to mitigate exploding gradients\n\n\n```\ndef clip_gradients(params = parameters):\n    for p in params.all():\n        np.clip(p.d, -1, 1, out=p.d)\n```\n\nCalculate and store the values in forward pass. Accumulate gradients in backward pass and clip gradients to avoid exploding gradients.\n\ninput, target are list of integers, with character indexes.\nh_prev is the array of initial h at  h\u22121  (size H x 1)\nC_prev is the array of initial C at  C\u22121  (size H x 1)\nReturns loss, final  hT  and  CT\n\n\n```\ndef forward_backward(inputs, targets, h_prev, C_prev):\n    global paramters\n    \n    # To store the values for each time step\n    x_s, z_s, f_s, i_s,  = {}, {}, {}, {}\n    C_bar_s, C_s, o_s, h_s = {}, {}, {}, {}\n    v_s, y_s =  {}, {}\n    \n    # Values at t - 1\n    h_s[-1] = np.copy(h_prev)\n    C_s[-1] = np.copy(C_prev)\n    \n    loss = 0\n    # Loop through time steps\n    assert len(inputs) == Time_steps\n    for t in range(len(inputs)):\n        x_s[t] = np.zeros((X_size, 1))\n        x_s[t][inputs[t]] = 1 # Input character\n        \n        (z_s[t], f_s[t], i_s[t],\n        C_bar_s[t], C_s[t], o_s[t], h_s[t],\n        v_s[t], y_s[t]) = \\\n            forward(x_s[t], h_s[t - 1], C_s[t - 1]) # Forward pass\n            \n        loss += -np.log(y_s[t][targets[t], 0]) # Loss for at t\n        \n    clear_gradients()\n\n    dh_next = np.zeros_like(h_s[0]) #dh from the next character\n    dC_next = np.zeros_like(C_s[0]) #dh from the next character\n\n    for t in reversed(range(len(inputs))):\n        # Backward pass\n        dh_next, dC_next = \\\n            backward(target = targets[t], dh_next = dh_next,\n                     dC_next = dC_next, C_prev = C_s[t-1],\n                     z = z_s[t], f = f_s[t], i = i_s[t], C_bar = C_bar_s[t],\n                     C = C_s[t], o = o_s[t], h = h_s[t], v = v_s[t],\n                     y = y_s[t])\n\n    clip_gradients()\n        \n    return loss, h_s[len(inputs) - 1], C_s[len(inputs) - 1]\n```\n\n# Sample the next character\n\n\n```\ndef sample(h_prev, C_prev, first_char_idx, sentence_length):\n    x = np.zeros((X_size, 1))\n    x[first_char_idx] = 1\n\n    h = h_prev\n    C = C_prev\n\n    indexes = []\n    \n    for t in range(sentence_length):\n        _, _, _, _, C, _, h, _, p = forward(x, h, C)\n        idx = np.random.choice(range(X_size), p=p.ravel())\n        x = np.zeros((X_size, 1))\n        x[idx] = 1\n        indexes.append(idx)\n\n    return indexes\n```\n\n# Training (Adagrad)\n\nUpdate the graph and display a sample output\n\n\n\n\n```\ndef update_status(inputs, h_prev, C_prev):\n    #initialized later\n    global plot_iter, plot_loss\n    global smooth_loss\n    \n    # Get predictions for 200 letters with current model\n\n    sample_idx = sample(h_prev, C_prev, inputs[0], 200)\n    txt = ''.join(idx_to_char[idx] for idx in sample_idx)\n\n    # Clear and plot\n    plt.plot(plot_iter, plot_loss)\n    display.clear_output(wait=True)\n    plt.show()\n\n    #Print prediction and loss\n    print(\"----\\n %s \\n----\" % (txt, ))\n    print(\"iter %d, loss %f\" % (iteration, smooth_loss))\n```\n\n# Update Parameters\n\n\\begin{align}\n\\theta_i &= \\theta_i - \\eta\\frac{d\\theta_i}{\\sum dw_{\\tau}^2} \\\\\nd\\theta_i &= \\frac{\\partial L}{\\partial \\theta_i}\n\\end{align}\n\n\n```\ndef update_paramters(params = parameters):\n    for p in params.all():\n        p.m += p.d * p.d # Calculate sum of gradients\n        #print(learning_rate * dparam)\n        p.v += -(learning_rate * p.d / np.sqrt(p.m + 1e-8))\n```\n\nTo delay the keyboard interrupt to prevent the training from stopping in the middle of an iteration\n\n\n\n\n```\n# Exponential average of loss\n# Initialize to a error of a random model\nsmooth_loss = -np.log(1.0 / X_size) * Time_steps\n\niteration, pointer = 0, 0\n\n# For the graph\nplot_iter = np.zeros((0))\nplot_loss = np.zeros((0))\n```\n\n# Training Loop\n\n\n```\niter = 50000\nwhile iter > 0:\n  # Reset\n  if pointer + Time_steps >= len(data) or iteration == 0:\n      g_h_prev = np.zeros((Hidden_Layer_size, 1))\n      g_C_prev = np.zeros((Hidden_Layer_size, 1))\n      pointer = 0\n\n\n  inputs = ([char_to_idx[ch] \n              for ch in data[pointer: pointer + Time_steps]])\n  targets = ([char_to_idx[ch] \n              for ch in data[pointer + 1: pointer + Time_steps + 1]])\n\n  loss, g_h_prev, g_C_prev = \\\n      forward_backward(inputs, targets, g_h_prev, g_C_prev)\n  smooth_loss = smooth_loss * 0.999 + loss * 0.001\n\n  # Print every hundred steps\n  if iteration % 100 == 0:\n      update_status(inputs, g_h_prev, g_C_prev)\n\n  update_paramters()\n\n  plot_iter = np.append(plot_iter, [iteration])\n  plot_loss = np.append(plot_loss, [loss])\n\n  pointer += Time_steps\n  iteration += 1\n  iter = iter -1\n```\n\n# Quiz Question 7. \n\nRun the above code for 50000 iterations making sure that you have 100 hidden layers and time_steps is 40. What is the loss value you're seeing?\n\n6.42685\n", "meta": {"hexsha": "b6c1f5d5f1725b000751a0d9026a8a2e60d246ae", "size": 56903, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "END_S5_RNN_LSTM.ipynb", "max_stars_repo_name": "rameshveer/NLP_Projects_TSAI", "max_stars_repo_head_hexsha": "62672e742faa04d18e664f106906a2645d52aacd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "END_S5_RNN_LSTM.ipynb", "max_issues_repo_name": "rameshveer/NLP_Projects_TSAI", "max_issues_repo_head_hexsha": "62672e742faa04d18e664f106906a2645d52aacd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "END_S5_RNN_LSTM.ipynb", "max_forks_repo_name": "rameshveer/NLP_Projects_TSAI", "max_forks_repo_head_hexsha": "62672e742faa04d18e664f106906a2645d52aacd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.9427036705, "max_line_length": 12378, "alphanum_fraction": 0.6108289545, "converted": true, "num_tokens": 7749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08509904964767097, "lm_q2_score": 0.015906392644828796, "lm_q1q2_score": 0.001353618897397634}}
{"text": "<a href=\"https://colab.research.google.com/github/satyajitghana/TSAI-DeepVision-EVA4.0-Phase-2/blob/master/10-SequenceModels/EVA_P2S3.ipynb\" target=\"_parent\"></a>\n\n#Imports\n\n\n```\nimport numpy as np\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport gdown\nfrom IPython import display\nplt.style.use('seaborn-white')\n```\n\n# Read and process data. \n\nDownload the file from this URL: https://drive.google.com/file/d/1UWWIi-sz9g0x3LFvkIZjvK1r2ZaCqgGS/view?usp=sharing\n\n\n```\nurl = 'https://drive.google.com/uc?id=1UWWIi-sz9g0x3LFvkIZjvK1r2ZaCqgGS'\noutput = 'text.txt'\ngdown.download(url, output, quiet=False)\n```\n\n    Downloading...\n    From: https://drive.google.com/uc?id=1UWWIi-sz9g0x3LFvkIZjvK1r2ZaCqgGS\n    To: /content/text.txt\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 10.3k/10.3k [00:00<00:00, 2.14MB/s]\n\n\n\n\n\n    'text.txt'\n\n\n\n\n```\ndata = open('text.txt', 'r').read()\ndata\n```\n\n\n\n\n    'A coronavirus is a kind of common virus that causes an infection in your nose, sinuses, or upper throat. Most coronaviruses are not dangerous.\\n\\nSome types of coronaviruses are serious, though. About 858 people have died from Middle East respiratory syndrome (MERS), which first appeared in 2012 in Saudi Arabia and then in other countries in the Middle East, Africa, Asia, and Europe. In April 2014, the first American was hospitalized for MERS in Indiana and another case was reported in Florida. Both had just returned from Saudi Arabia. In May 2015, there was an outbreak of MERS in Korea, which was the largest outbreak outside of the Arabian Peninsula. In 2003, 774 people died from a severe acute respiratory syndrome (SARS) outbreak. As of 2015, there were no further reports of cases of SARS. \\n\\nBut in early 2020, following a December 2019 outbreak in China, the World Health Organization identified a new type, 2019 novel coronavirus (2019-nCoV).\\n\\nOften a coronavirus causes upper respiratory infection symptoms like a stuffy nose, cough, and sore throat. You can treat them with rest and over-the-counter medication. The coronavirus can also cause middle ear infections in children.\\n\\nWhat Is a Coronavirus?\\nCoronaviruses were first identified in the 1960s, but we don\\'t know where they come from. They get their name from their crown-like shape. Sometimes, but not often, a coronavirus can infect both animals and humans.\\n\\nMost coronaviruses spread the same way other cold-causing viruses do: through infected people coughing and sneezing, by touching an infected person\\'s hands or face, or by touching things such as doorknobs that infected people have touched.\\n\\nAlmost everyone gets a coronavirus infection at least once in their life, most likely as a young child. In the United States, coronaviruses are more common in the fall and winter, but anyone can come down with a coronavirus infection at any time.\\n\\nCommon Symptoms of Coronavirus\\nThe symptoms of most coronaviruses are similar to any other upper respiratory infection, including runny nose, coughing, sore throat, and sometimes a fever. In most cases, you won\\'t know whether you have a coronavirus or a different cold-causing virus, such as rhinovirus.\\n\\nYou could get lab tests, including nose and throat cultures and blood work, to find out whether your cold was caused by a coronavirus, but there\\'s no reason to. The test results wouldn\\'t change how you treat your symptoms, which typically go away in a few days.\\n\\nBut if a coronavirus infection spreads to the lower respiratory tract (your windpipe and your lungs), it can cause pneumonia, especially in older people, people with heart disease, or people with weakened immune systems.\\n\\nWhat to Do About Coronavirus\\nThere is no vaccine for coronavirus. To help prevent a coronavirus infection, do the same things you do to avoid the common cold:\\n\\nWash your hands thoroughly with soap and warm water or with an alcohol-based hand sanitizer.\\nKeep your hands and fingers away from your eyes, nose, and mouth.\\nAvoid close contact with people who are infected.\\nYou treat a coronavirus infection the same way you treat a cold:\\n\\nGet plenty of rest.\\nDrink fluids.\\nTake over-the-counter medicine for a sore throat and fever. But don\\'t give aspirin to children or teens younger than 19; use ibuprofen or acetaminophen instead.\\nA humidifier or steamy shower can also help ease a sore and scratchy throat.\\n\\nEven when a coronavirus causes MERS or SARS in other countries, the kind of coronavirus infection common in the U.S. isn\\'t a serious threat for an otherwise healthy adult. If you get sick, treat your symptoms and contact a doctor if they get worse or don\\'t go away.\\n\\nNews about the coronavirus outbreak that started in Wuhan, China, is changing rapidly. The respiratory infection, which is closely related to SARS and MERS, has been spreading across China, and cases have been diagnosed in several other countries, including the United States. We\u2019ll provide the latest updates on cases, deaths, travel restrictions, and more here.\\n\\nWhat is the latest news?\\nOn Wednesday, CDC medical officers and others met a group of about 210 U.S. citizens evacuated from China. Their plane landed at March Air Reserve Base in California, where the evacuees will be monitored for coronavirus symptoms for several days. Anyone showing signs of the disease will be taken to the hospital.\\n\\nSome airlines, including British Airways and United Airlines, are stopping or reducing flights to China as the number of cases continues to rise rapidly. Worldwide there are now more than 6,000 cases and 132 deaths, according to the European Centre for Disease Prevention and Control. While the majority of cases center in China, it has been found in the U.S. and these countries: Thailand, Hong Kong, Taiwan, Australia, Macau, Singapore, Japan, South Korea, Malaysia, France, Canada, Vietnam, Nepal, Cambodia, Germany and United Arab Emirates. There have been no deaths outside China.\\n\\nIn the U.S., the CDC is reporting five confirmed cases from these states: Washington, Illinois, California and Arizona. On Monday, Jan. 27, Nancy Messonnier, MD, Director of the agency\\'s National Center for Immunization and Respiratory Diseases, said it had 165 persons under investigation for coronavirus from 36 states. In addition to the 5 confirmed positive, 68 have tested negative. They are prioritizing the testing based on a person\u2019s risk.\\n\\nMessonnier said they had posted the blueprints for their diagnostic test on a public server and were working \"as fast as we can\" to get test kits out to states. \\n\\nRight now, all the testing for the new coronavirus is taking place at the CDC\\'s headquarters in Atlanta.\\n\\nShe said the CDC was mulling a change to its travel screening for the infection, but did not give further details.\\n\\nHow many people have been diagnosed with the virus, and how many have died?\\nAccording to European CDC, the majority of the confirmed cases \u2013 5,994 \u2013 are in China. Another 78 cases are confirmed outside of China in 16 countries. Countries with the most confirmed cases include Thailand with 14 and Taiwan and South Korea with 8 each. All reported deaths have been in China, and include 16 healthcare workers.\\n\\nWhen did the outbreak start?\\nChina first reported the outbreak in Wuhan on Dec. 30, 2019.\\n\\nWhat are public officials doing to contain the virus?\\nOn Tuesday, the CDC urged travelers to avoid non-essential travel to China.\\n\\nChinese officials have shut down all public transportation to 10 cities, affecting 35 million people. The first was Wuhan, which has a population of about 11 million. In Wuhan, that includes buses, subways, trains, and the airport.\\n\\nAll passengers flying into the United States from Wuhan will be routed through one of five airports and screened for fever and other signs of the virus. \u201cPatients of concern\ufffd\ufffd\ufffd will be referred to a facility and given a test to find out if they have the virus.\\n\\nWhat do we know about cases in the United States?\\nIn all U.S. cases so far, patients had recently traveled to Wuhan.\\n\\nCalifornia has two patients, one in Los Angeles County and one in Orange County. The patient from Orange County is a man in his 50s. He is in a local hospital in isolation and is in good condition, according to the Orange County Health Care Agency. Los Angeles County officials did not provide additional details about the patient there.\\n\\nArizona\\'s Department of Health Services said its patient is a Maricopa County resident and member of the Arizona State University community who did not live in student housing. The patient is not severely ill and is being kept in isolation. \\n\\nAnother case involves a woman in her 60s from Chicago. The Chicago Department of Public Health reported that she had visited Wuhan, China in December and returned to Chicago earlier this month. She is hospitalized in stable condition. \\n\\nThe first U.S. patient is a man in his 30s from Washington state. He had traveled from Wuhan and entered the country before the screening was in place. He started having symptoms and contacted his doctor. He is in good condition and is in isolation at Providence Regional Medical Center.\\n\\nIs travel to China safe?\\nWuhan is closed to travelers.\\n\\nThe CDC is advising that travelers avoid non-essential travel to China. Travelers who do go should:\\n\\nAvoid contact with sick people.\\nAvoid animals, animal markets, and products that come from animals.\\nWash their hands often with soap and water, or use an alcohol-based sanitizer if that\u2019s not available.\\nSeek medical care right away for a fever, cough, or difficulty breathing. Tell a health care professional about any travel.\\nWhat are the symptoms, and how is the virus diagnosed?\\nChina created a test for the virus and shared that information with other countries. The CDC has developed its own test.\\n\\nSymptoms include a fever, coughing, and shortness of breath. They may appear 2 to 14 days after you\u2019re exposed to the virus.\\n\\nWhat is the source of the virus, and how is it spread?\\nHealth officials are not sure of the source of the virus yet or how easily it can spread. Coronaviruses are found in many different animals, including camels, cattle, cats, and bats. One research paper also suggested snakes as a possible source. The new virus may be linked to a seafood and live animal market in Wuhan that has since been closed\\n\\nThe virus can spread from person to person. Health officials are seeing this happen most often where people are close together and in health care settings. To date, 16 health care workers have been infected.\\n\\nThe CDC believes that severe acute respiratory syndrome (SARS) and Middle East respiratory syndrome (MERS), two other types of coronavirus, are spread through droplets when someone coughs or sneezes.\\n\\nIs there a vaccine?\\nThere is no vaccine, but the National Institutes of Health is working on one and hopes to begin testing in several months. That testing would be for safety. If it\u2019s safe, there would be testing to see how well it works.\\n\\nHow is it treated?\\nThere is no specific treatment for the virus. Patients are generally given supportive care for their symptoms, such a fluids and pain relievers. Hospitalized patients may need support with breathing.'\n\n\n\nProcess data and calculate indices\n\n\n```\nchars = list(set(data))\ndata_size, X_size = len(data), len(chars)\nprint(\"Corona Virus article has %d characters, %d unique characters\" %(data_size, X_size))\nchar_to_idx = {ch:i for i,ch in enumerate(chars)}\nidx_to_char = {i:ch for i,ch in enumerate(chars)}\n```\n\n    Corona Virus article has 10223 characters, 75 unique characters\n\n\n# Constants and Hyperparameters\n\n\n```\nHidden_Layer_size = 10 #size of the hidden layer\nTime_steps = 10 # Number of time steps (length of the sequence) used for training\nlearning_rate = 1e-1 # Learning Rate\nweight_sd = 0.1 #Standard deviation of weights for initialization\nz_size = Hidden_Layer_size + X_size #Size of concatenation(H, X) vector\n```\n\n# Activation Functions and Derivatives\n\n\n```\ndef sigmoid(x): # sigmoid function\n    z = 1 / (1 + np.exp(-x))\n    return z\n\ndef dsigmoid(y): # derivative of sigmoid function\n    dz = y * (1 - y)\n    return dz\n\ndef tanh(x): # tanh function\n    z = np.tanh(x)\n    return z\n\ndef dtanh(y): # derivative of tanh\n    dz = 1 - y * y\n    return dz\n```\n\n#### Sigmoid\n\n\\begin{align}\n\\sigma(x) &= \\frac{1}{1 + e^{-x}}\\\\\n\\frac{d\\sigma(x)}{dx} &= \\sigma(x) \\cdot (1 - \\sigma(x))\n\\end{align}\n\n#### Tanh\n\n\\begin{align}\n\\frac{d\\text{tanh}(x)}{dx} &= 1 - \\text{tanh}^2(x)\n\\end{align}\n\n# Quiz Question 1\n\nWhat is the value of sigmoid(0) calculated from  your code? (Answer up to 1 decimal point, e.g. 4.2 and NOT 4.29999999, no rounding off).\n\n\n```\nsigmoid(0)\n```\n\n\n\n\n    0.5\n\n\n\n# Quiz Question 2\n\nWhat is the value of dsigmoid(sigmoid(0)) calculated from your code?? (Answer up to 2 decimal point, e.g. 4.29 and NOT 4.29999999, no rounding off). \n\n\n```\ndsigmoid(sigmoid(0))\n```\n\n\n\n\n    0.25\n\n\n\n# Quiz Question 3\n\nWhat is the value of tanh(dsigmoid(sigmoid(0))) calculated from your code?? (Answer up to 5 decimal point, e.g. 4.29999 and NOT 4.29999999, no rounding off).\n\n\n```\ntanh(dsigmoid(sigmoid(0)))\n```\n\n\n\n\n    0.24491866240370913\n\n\n\n\n\n\n\n\n\n# Quiz Question 4\n\nWhat is the value of dtanh(tanh(dsigmoid(sigmoid(0)))) calculated from your code?? (Answer up to 5 decimal point, e.g. 4.29999 and NOT 4.29999999, no rounding off).\n\n\n```\ndtanh(tanh(dsigmoid(sigmoid(0))))\n```\n\n\n\n\n    0.940014848806378\n\n\n\n# Parameters\n\n\n```\nclass Param:\n    def __init__(self, name, value):\n      self.name = name\n      self.v = value # parameter value\n      self.d = np.zeros_like(value) # derivative\n      self.m = np.zeros_like(value) # momentum for Adagrad\n```\n\nWe use random weights with normal distribution (0, weight_sd) for  tanh  activation function and (0.5, weight_sd) for  `sigmoid`  activation function.\n\nBiases are initialized to zeros.\n\n# LSTM \nYou are making this network, please note f, i, c and o (also \"v\") in the image below:\n\n\nPlease note that we are concatenating the old_hidden_vector and new_input.\n\n# Quiz Question 4\n\nIn the class definition below, what should be size_a, size_b, and size_c? ONLY use the variables defined above.\n\n\n```\nsize_a = Hidden_Layer_size\nsize_b = z_size\nsize_c = X_size\n\nclass Parameters:\n    def __init__(self):\n        self.W_f = Param('W_f', np.random.randn(size_a, size_b) * weight_sd + 0.5)\n        self.b_f = Param('b_f', np.zeros((size_a, 1)))\n\n        self.W_i = Param('W_i', np.random.randn(size_a, size_b) * weight_sd + 0.5)\n        self.b_i = Param('b_i', np.zeros((size_a, 1)))\n\n        self.W_C = Param('W_C', np.random.randn(size_a, size_b) * weight_sd)\n        self.b_C = Param('b_C', np.zeros((size_a, 1)))\n\n        self.W_o = Param('W_o', np.random.randn(size_a, size_b) * weight_sd + 0.5)\n        self.b_o = Param('b_o', np.zeros((size_a, 1)))\n\n        #For final layer to predict the next character\n        self.W_v = Param('W_v', np.random.randn(X_size, size_a) * weight_sd)\n        self.b_v = Param('b_v', np.zeros((size_c, 1)))\n        \n    def all(self):\n        return [self.W_f, self.W_i, self.W_C, self.W_o, self.W_v,\n               self.b_f, self.b_i, self.b_C, self.b_o, self.b_v]\n        \nparameters = Parameters()\n```\n\nLook at these operations which we'll be writing:\n\n**Concatenation of h and x:**\n\n$z\\:=\\:\\left[h_{t-1},\\:x\\right]$\n\n$f_t=\\sigma\\left(W_f\\cdot z\\:+\\:b_f\\:\\right)$\n\n$i_i=\\sigma\\left(W_i\\cdot z\\:+\\:b_i\\right)$\n\n$\\overline{C_t}=\\tanh\\left(W_C\\cdot z\\:+\\:b_C\\right)$\n\n$C_t=f_t\\ast C_{t-1}+i_t\\ast \\overline{C}_t$\n\n$o_t=\\sigma\\left(W_o\\cdot z\\:+\\:b_i\\right)$\n\n$h_t=o_t\\ast\\tanh\\left(C_t\\right)$\n\n**Logits:**\n\n$v_t=W_v\\cdot h_t+b_v$\n\n**Softmax:**\n\n$\\hat{y}=softmax\\left(v_t\\right)$\n\n\n\n```\ndef forward(x, h_prev, C_prev, p = parameters):\n    assert x.shape == (X_size, 1)\n    assert h_prev.shape == (Hidden_Layer_size, 1)\n    assert C_prev.shape == (Hidden_Layer_size, 1)\n    \n    z = np.row_stack((h_prev, x))\n    f = sigmoid(np.dot(p.W_f.v, z) + p.b_f.v)\n    i = sigmoid(np.dot(p.W_i.v, z) + p.b_i.v)\n    C_bar = tanh(np.dot(p.W_C.v, z) + p.b_C.v)\n\n    C = f * C_prev + i * C_bar\n    o = sigmoid(np.dot(p.W_o.v, z) + p.b_o.v)\n    h = o * tanh(C)\n\n    v = np.dot(p.W_v.v, h) + p.b_v.v\n    y = np.exp(v) / np.sum(np.exp(v)) # softmax\n\n    return z, f, i, C_bar, C, o, h, v, y\n```\n\nYou must finish the function above before you can attempt the questions below. \n\n# Quiz Question 5\n\nWhat is the output of 'print(len(forward(np.zeros((X_size, 1)), np.zeros((Hidden_Layer_size, 1)), np.zeros((Hidden_Layer_size, 1)), parameters)))'?\n\n\n```\nprint(len(forward(np.zeros((X_size, 1)), np.zeros((Hidden_Layer_size, 1)), np.zeros((Hidden_Layer_size, 1)), parameters)))\n```\n\n    9\n\n\n# Quiz Question 6. \n\nAssuming you have fixed the forward function, run this command: \nz, f, i, C_bar, C, o, h, v, y = forward(np.zeros((X_size, 1)), np.zeros((Hidden_Layer_size, 1)), np.zeros((Hidden_Layer_size, 1)))\n\nNow, find these values:\n\n\n1.   print(z.shape)\n2.   print(np.sum(z))\n3.   print(np.sum(f))\n\nCopy and paste exact values you get in the logs into the quiz.\n\n\n\n\n```\nz, f, i, C_bar, C, o, h, v, y = forward(np.zeros((X_size, 1)), np.zeros((Hidden_Layer_size, 1)), np.zeros((Hidden_Layer_size, 1)))\n```\n\n\n```\nz.shape, np.sum(z), np.sum(f)\n```\n\n\n\n\n    ((85, 1), 0.0, 5.0)\n\n\n\n# Backpropagation\n\nHere we are defining the backpropagation. It's too complicated, here is the whole code. (Please note that this would work only if your earlier code is perfect).\n\n\n```\ndef backward(target, dh_next, dC_next, C_prev,\n             z, f, i, C_bar, C, o, h, v, y,\n             p = parameters):\n    \n    assert z.shape == (X_size + Hidden_Layer_size, 1)\n    assert v.shape == (X_size, 1)\n    assert y.shape == (X_size, 1)\n    \n    for param in [dh_next, dC_next, C_prev, f, i, C_bar, C, o, h]:\n        assert param.shape == (Hidden_Layer_size, 1)\n        \n    dv = np.copy(y)\n    dv[target] -= 1\n\n    p.W_v.d += np.dot(dv, h.T)\n    p.b_v.d += dv\n\n    dh = np.dot(p.W_v.v.T, dv)        \n    dh += dh_next\n    do = dh * tanh(C)\n    do = dsigmoid(o) * do\n    p.W_o.d += np.dot(do, z.T)\n    p.b_o.d += do\n\n    dC = np.copy(dC_next)\n    dC += dh * o * dtanh(tanh(C))\n    dC_bar = dC * i\n    dC_bar = dtanh(C_bar) * dC_bar\n    p.W_C.d += np.dot(dC_bar, z.T)\n    p.b_C.d += dC_bar\n\n    di = dC * C_bar\n    di = dsigmoid(i) * di\n    p.W_i.d += np.dot(di, z.T)\n    p.b_i.d += di\n\n    df = dC * C_prev\n    df = dsigmoid(f) * df\n    p.W_f.d += np.dot(df, z.T)\n    p.b_f.d += df\n\n    dz = (np.dot(p.W_f.v.T, df)\n         + np.dot(p.W_i.v.T, di)\n         + np.dot(p.W_C.v.T, dC_bar)\n         + np.dot(p.W_o.v.T, do))\n    dh_prev = dz[:Hidden_Layer_size, :]\n    dC_prev = f * dC\n    \n    return dh_prev, dC_prev\n```\n\n# Forward and Backward Combined Pass\n\nLet's first clear the gradients before each backward pass\n\n\n```\ndef clear_gradients(params = parameters):\n    for p in params.all():\n        p.d.fill(0)\n```\n\nClip gradients to mitigate exploding gradients\n\n\n```\ndef clip_gradients(params = parameters):\n    for p in params.all():\n        np.clip(p.d, -1, 1, out=p.d)\n```\n\nCalculate and store the values in forward pass. Accumulate gradients in backward pass and clip gradients to avoid exploding gradients.\n\ninput, target are list of integers, with character indexes.\nh_prev is the array of initial h at  h\u22121  (size H x 1)\nC_prev is the array of initial C at  C\u22121  (size H x 1)\nReturns loss, final  hT  and  CT\n\n\n```\ndef forward_backward(inputs, targets, h_prev, C_prev):\n    global paramters\n    \n    # To store the values for each time step\n    x_s, z_s, f_s, i_s,  = {}, {}, {}, {}\n    C_bar_s, C_s, o_s, h_s = {}, {}, {}, {}\n    v_s, y_s =  {}, {}\n    \n    # Values at t - 1\n    h_s[-1] = np.copy(h_prev)\n    C_s[-1] = np.copy(C_prev)\n    \n    loss = 0\n    # Loop through time steps\n    assert len(inputs) == Time_steps\n    for t in range(len(inputs)):\n        x_s[t] = np.zeros((X_size, 1))\n        x_s[t][inputs[t]] = 1 # Input character\n        \n        (z_s[t], f_s[t], i_s[t],\n        C_bar_s[t], C_s[t], o_s[t], h_s[t],\n        v_s[t], y_s[t]) = \\\n            forward(x_s[t], h_s[t - 1], C_s[t - 1]) # Forward pass\n            \n        loss += -np.log(y_s[t][targets[t], 0]) # Loss for at t\n        \n    clear_gradients()\n\n    dh_next = np.zeros_like(h_s[0]) #dh from the next character\n    dC_next = np.zeros_like(C_s[0]) #dh from the next character\n\n    for t in reversed(range(len(inputs))):\n        # Backward pass\n        dh_next, dC_next = \\\n            backward(target = targets[t], dh_next = dh_next,\n                     dC_next = dC_next, C_prev = C_s[t-1],\n                     z = z_s[t], f = f_s[t], i = i_s[t], C_bar = C_bar_s[t],\n                     C = C_s[t], o = o_s[t], h = h_s[t], v = v_s[t],\n                     y = y_s[t])\n\n    clip_gradients()\n        \n    return loss, h_s[len(inputs) - 1], C_s[len(inputs) - 1]\n```\n\n# Sample the next character\n\n\n```\ndef sample(h_prev, C_prev, first_char_idx, sentence_length):\n    x = np.zeros((X_size, 1))\n    x[first_char_idx] = 1\n\n    h = h_prev\n    C = C_prev\n\n    indexes = []\n    \n    for t in range(sentence_length):\n        _, _, _, _, C, _, h, _, p = forward(x, h, C)\n        idx = np.random.choice(range(X_size), p=p.ravel())\n        x = np.zeros((X_size, 1))\n        x[idx] = 1\n        indexes.append(idx)\n\n    return indexes\n```\n\n# Training (Adagrad)\n\nUpdate the graph and display a sample output\n\n\n\n\n```\ndef update_status(inputs, h_prev, C_prev):\n    #initialized later\n    global plot_iter, plot_loss\n    global smooth_loss\n    \n    # Get predictions for 200 letters with current model\n\n    sample_idx = sample(h_prev, C_prev, inputs[0], 200)\n    txt = ''.join(idx_to_char[idx] for idx in sample_idx)\n\n    # Clear and plot\n    plt.plot(plot_iter, plot_loss)\n    display.clear_output(wait=True)\n    plt.show()\n\n    #Print prediction and loss\n    print(\"----\\n %s \\n----\" % (txt, ))\n    print(\"iter %d, loss %f\" % (iteration, smooth_loss))\n```\n\n# Update Parameters\n\n\\begin{align}\n\\theta_i &= \\theta_i - \\eta\\frac{d\\theta_i}{\\sum dw_{\\tau}^2} \\\\\nd\\theta_i &= \\frac{\\partial L}{\\partial \\theta_i}\n\\end{align}\n\n\n```\ndef update_paramters(params = parameters):\n    for p in params.all():\n        p.m += p.d * p.d # Calculate sum of gradients\n        #print(learning_rate * dparam)\n        p.v += -(learning_rate * p.d / np.sqrt(p.m + 1e-8))\n```\n\nTo delay the keyboard interrupt to prevent the training from stopping in the middle of an iteration\n\n\n\n\n```\n# Exponential average of loss\n# Initialize to a error of a random model\nsmooth_loss = -np.log(1.0 / X_size) * Time_steps\n\niteration, pointer = 0, 0\n\n# For the graph\nplot_iter = np.zeros((0))\nplot_loss = np.zeros((0))\n```\n\n# Training Loop\n\n\n```\niter = 1000\nwhile iter > 0:\n  # Reset\n  if pointer + Time_steps >= len(data) or iteration == 0:\n      g_h_prev = np.zeros((Hidden_Layer_size, 1))\n      g_C_prev = np.zeros((Hidden_Layer_size, 1))\n      pointer = 0\n\n\n  inputs = ([char_to_idx[ch] \n              for ch in data[pointer: pointer + Time_steps]])\n  targets = ([char_to_idx[ch] \n              for ch in data[pointer + 1: pointer + Time_steps + 1]])\n\n  loss, g_h_prev, g_C_prev = \\\n      forward_backward(inputs, targets, g_h_prev, g_C_prev)\n  smooth_loss = smooth_loss * 0.999 + loss * 0.001\n\n  # Print every hundred steps\n  if iteration % 100 == 0:\n      update_status(inputs, g_h_prev, g_C_prev)\n\n  update_paramters()\n\n  plot_iter = np.append(plot_iter, [iteration])\n  plot_loss = np.append(plot_loss, [loss])\n\n  pointer += Time_steps\n  iteration += 1\n  iter = iter -1\n```\n\n# Quiz Question 7. \n\nRun the above code for 50000 iterations making sure that you have 100 hidden layers and time_steps is 40. What is the loss value you're seeing?\n\n\n```\nHidden_Layer_size = 100 #size of the hidden layer\nTime_steps = 40 # Number of time steps (length of the sequence) used for training\nlearning_rate = 1e-1 # Learning Rate\nweight_sd = 0.1 #Standard deviation of weights for initialization\nz_size = Hidden_Layer_size + X_size #Size of concatenation(H, X) vector\n```\n\n\n```\nclass Param:\n    def __init__(self, name, value):\n      self.name = name\n      self.v = value # parameter value\n      self.d = np.zeros_like(value) # derivative\n      self.m = np.zeros_like(value) # momentum for Adagrad\n```\n\n\n```\nsize_a = Hidden_Layer_size\nsize_b = z_size\nsize_c = X_size\n\nclass Parameters:\n    def __init__(self):\n        self.W_f = Param('W_f', np.random.randn(size_a, size_b) * weight_sd + 0.5)\n        self.b_f = Param('b_f', np.zeros((size_a, 1)))\n\n        self.W_i = Param('W_i', np.random.randn(size_a, size_b) * weight_sd + 0.5)\n        self.b_i = Param('b_i', np.zeros((size_a, 1)))\n\n        self.W_C = Param('W_C', np.random.randn(size_a, size_b) * weight_sd)\n        self.b_C = Param('b_C', np.zeros((size_a, 1)))\n\n        self.W_o = Param('W_o', np.random.randn(size_a, size_b) * weight_sd + 0.5)\n        self.b_o = Param('b_o', np.zeros((size_a, 1)))\n\n        #For final layer to predict the next character\n        self.W_v = Param('W_v', np.random.randn(X_size, size_a) * weight_sd)\n        self.b_v = Param('b_v', np.zeros((size_c, 1)))\n        \n    def all(self):\n        return [self.W_f, self.W_i, self.W_C, self.W_o, self.W_v,\n               self.b_f, self.b_i, self.b_C, self.b_o, self.b_v]\n        \nparameters = Parameters()\n```\n\n\n```\ndef forward(x, h_prev, C_prev, p = parameters):\n    assert x.shape == (X_size, 1)\n    assert h_prev.shape == (Hidden_Layer_size, 1)\n    assert C_prev.shape == (Hidden_Layer_size, 1)\n    \n    z = np.row_stack((h_prev, x))\n    f = sigmoid(np.dot(p.W_f.v, z) + p.b_f.v)\n    i = sigmoid(np.dot(p.W_i.v, z) + p.b_i.v)\n    C_bar = tanh(np.dot(p.W_C.v, z) + p.b_C.v)\n\n    C = f * C_prev + i * C_bar\n    o = sigmoid(np.dot(p.W_o.v, z) + p.b_o.v)\n    h = o * tanh(C)\n\n    v = np.dot(p.W_v.v, h) + p.b_v.v\n    y = np.exp(v) / np.sum(np.exp(v)) # softmax\n\n    return z, f, i, C_bar, C, o, h, v, y\n```\n\n\n```\nz, f, i, C_bar, C, o, h, v, y = forward(np.zeros((X_size, 1)), np.zeros((Hidden_Layer_size, 1)), np.zeros((Hidden_Layer_size, 1)))\n```\n\n\n```\nz.shape, np.sum(z), np.sum(f)\n```\n\n\n\n\n    ((175, 1), 0.0, 50.0)\n\n\n\n\n```\ndef backward(target, dh_next, dC_next, C_prev,\n             z, f, i, C_bar, C, o, h, v, y,\n             p = parameters):\n    \n    assert z.shape == (X_size + Hidden_Layer_size, 1)\n    assert v.shape == (X_size, 1)\n    assert y.shape == (X_size, 1)\n    \n    for param in [dh_next, dC_next, C_prev, f, i, C_bar, C, o, h]:\n        assert param.shape == (Hidden_Layer_size, 1)\n        \n    dv = np.copy(y)\n    dv[target] -= 1\n\n    p.W_v.d += np.dot(dv, h.T)\n    p.b_v.d += dv\n\n    dh = np.dot(p.W_v.v.T, dv)        \n    dh += dh_next\n    do = dh * tanh(C)\n    do = dsigmoid(o) * do\n    p.W_o.d += np.dot(do, z.T)\n    p.b_o.d += do\n\n    dC = np.copy(dC_next)\n    dC += dh * o * dtanh(tanh(C))\n    dC_bar = dC * i\n    dC_bar = dtanh(C_bar) * dC_bar\n    p.W_C.d += np.dot(dC_bar, z.T)\n    p.b_C.d += dC_bar\n\n    di = dC * C_bar\n    di = dsigmoid(i) * di\n    p.W_i.d += np.dot(di, z.T)\n    p.b_i.d += di\n\n    df = dC * C_prev\n    df = dsigmoid(f) * df\n    p.W_f.d += np.dot(df, z.T)\n    p.b_f.d += df\n\n    dz = (np.dot(p.W_f.v.T, df)\n         + np.dot(p.W_i.v.T, di)\n         + np.dot(p.W_C.v.T, dC_bar)\n         + np.dot(p.W_o.v.T, do))\n    dh_prev = dz[:Hidden_Layer_size, :]\n    dC_prev = f * dC\n    \n    return dh_prev, dC_prev\n```\n\n\n```\ndef clear_gradients(params = parameters):\n    for p in params.all():\n        p.d.fill(0)\n```\n\n\n```\ndef clip_gradients(params = parameters):\n    for p in params.all():\n        np.clip(p.d, -1, 1, out=p.d)\n```\n\n\n```\ndef forward_backward(inputs, targets, h_prev, C_prev):\n    global paramters\n    \n    # To store the values for each time step\n    x_s, z_s, f_s, i_s,  = {}, {}, {}, {}\n    C_bar_s, C_s, o_s, h_s = {}, {}, {}, {}\n    v_s, y_s =  {}, {}\n    \n    # Values at t - 1\n    h_s[-1] = np.copy(h_prev)\n    C_s[-1] = np.copy(C_prev)\n    \n    loss = 0\n    # Loop through time steps\n    assert len(inputs) == Time_steps\n    for t in range(len(inputs)):\n        x_s[t] = np.zeros((X_size, 1))\n        x_s[t][inputs[t]] = 1 # Input character\n        \n        (z_s[t], f_s[t], i_s[t],\n        C_bar_s[t], C_s[t], o_s[t], h_s[t],\n        v_s[t], y_s[t]) = \\\n            forward(x_s[t], h_s[t - 1], C_s[t - 1]) # Forward pass\n            \n        loss += -np.log(y_s[t][targets[t], 0]) # Loss for at t\n        \n    clear_gradients()\n\n    dh_next = np.zeros_like(h_s[0]) #dh from the next character\n    dC_next = np.zeros_like(C_s[0]) #dh from the next character\n\n    for t in reversed(range(len(inputs))):\n        # Backward pass\n        dh_next, dC_next = \\\n            backward(target = targets[t], dh_next = dh_next,\n                     dC_next = dC_next, C_prev = C_s[t-1],\n                     z = z_s[t], f = f_s[t], i = i_s[t], C_bar = C_bar_s[t],\n                     C = C_s[t], o = o_s[t], h = h_s[t], v = v_s[t],\n                     y = y_s[t])\n\n    clip_gradients()\n        \n    return loss, h_s[len(inputs) - 1], C_s[len(inputs) - 1]\n```\n\n\n```\ndef sample(h_prev, C_prev, first_char_idx, sentence_length):\n    x = np.zeros((X_size, 1))\n    x[first_char_idx] = 1\n\n    h = h_prev\n    C = C_prev\n\n    indexes = []\n    \n    for t in range(sentence_length):\n        _, _, _, _, C, _, h, _, p = forward(x, h, C)\n        idx = np.random.choice(range(X_size), p=p.ravel())\n        x = np.zeros((X_size, 1))\n        x[idx] = 1\n        indexes.append(idx)\n\n    return indexes\n```\n\n\n```\ndef update_status(inputs, h_prev, C_prev):\n    #initialized later\n    global plot_iter, plot_loss\n    global smooth_loss\n    \n    # Get predictions for 200 letters with current model\n\n    sample_idx = sample(h_prev, C_prev, inputs[0], 200)\n    txt = ''.join(idx_to_char[idx] for idx in sample_idx)\n\n    # Clear and plot\n    plt.plot(plot_iter, plot_loss)\n    display.clear_output(wait=True)\n    plt.show()\n\n    #Print prediction and loss\n    print(\"----\\n %s \\n----\" % (txt, ))\n    print(\"iter %d, loss %f\" % (iteration, smooth_loss))\n```\n\n\n```\ndef update_paramters(params = parameters):\n    for p in params.all():\n        p.m += p.d * p.d # Calculate sum of gradients\n        #print(learning_rate * dparam)\n        p.v += -(learning_rate * p.d / np.sqrt(p.m + 1e-8))\n```\n\n\n```\n# Exponential average of loss\n# Initialize to a error of a random model\nsmooth_loss = -np.log(1.0 / X_size) * Time_steps\n\niteration, pointer = 0, 0\n\n# For the graph\nplot_iter = np.zeros((0))\nplot_loss = np.zeros((0))\n```\n\n\n```\niter = 50000\nwhile iter > 0:\n  # Reset\n  if pointer + Time_steps >= len(data) or iteration == 0:\n      g_h_prev = np.zeros((Hidden_Layer_size, 1))\n      g_C_prev = np.zeros((Hidden_Layer_size, 1))\n      pointer = 0\n\n\n  inputs = ([char_to_idx[ch] \n              for ch in data[pointer: pointer + Time_steps]])\n  targets = ([char_to_idx[ch] \n              for ch in data[pointer + 1: pointer + Time_steps + 1]])\n\n  loss, g_h_prev, g_C_prev = \\\n      forward_backward(inputs, targets, g_h_prev, g_C_prev)\n  smooth_loss = smooth_loss * 0.999 + loss * 0.001\n\n  # Print every hundred steps\n  if iteration % 100 == 0:\n      update_status(inputs, g_h_prev, g_C_prev)\n\n  update_paramters()\n\n  plot_iter = np.append(plot_iter, [iteration])\n  plot_loss = np.append(plot_loss, [loss])\n\n  pointer += Time_steps\n  iteration += 1\n  iter = iter -1\n```\n\n\n```\n\n```\n", "meta": {"hexsha": "0c3389f6d562541e1c91dee8b2bdc963733d2e62", "size": 97594, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "10-SequenceModels/EVA_P2S3.ipynb", "max_stars_repo_name": "amitkml/TSAI-DeepVision-EVA4.0-Phase-2", "max_stars_repo_head_hexsha": "f9e232b3eb6ce20f522136523e79208ed85a1f28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-21T08:45:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-21T08:45:05.000Z", "max_issues_repo_path": "10-SequenceModels/EVA_P2S3.ipynb", "max_issues_repo_name": "amitkml/TSAI-DeepVision-EVA4.0-Phase-2", "max_issues_repo_head_hexsha": "f9e232b3eb6ce20f522136523e79208ed85a1f28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "10-SequenceModels/EVA_P2S3.ipynb", "max_forks_repo_name": "amitkml/TSAI-DeepVision-EVA4.0-Phase-2", "max_forks_repo_head_hexsha": "f9e232b3eb6ce20f522136523e79208ed85a1f28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.828646174, "max_line_length": 27766, "alphanum_fraction": 0.6948890301, "converted": true, "num_tokens": 8892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.052618950376410435, "lm_q2_score": 0.025178842112067265, "lm_q1q2_score": 0.0013248842436303406}}
{"text": "```python\nfrom jupyterthemes import get_themes\nfrom jupyterthemes.stylefx import set_nb_theme\nthemes = get_themes()\nset_nb_theme(themes[1])\n```\n\n\n\n\n<style> @font-face {\n font-family: 'Droid Sans Mono';\n font-weight: normal;\n font-style: normal;\n src: local('Droid Sans Mono'), url('fonts/droid-sans-mono.woff') format('woff');\n}\n@font-face {\n font-family: 'Exo_2';\n font-weight: normal;\n font-style: normal;\n src: local('Exo_2'), url('fonts/exo-II-regular.ttf') format('truetype');\n}\n@font-face {\n font-family: 'Fira Code';\n font-weight: normal;\n font-style: normal;\n src: local('Fira Code'), url('fonts/firacode.otf') format('opentype');\n}\n@font-face {\n font-family: 'Lora';\n font-weight: normal;\n font-style: normal;\n src: local('Lora'), url('fonts/Lora-Regular.ttf') format('truetype');\n}\ndiv#notebook {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n line-height: 170%;\n color: #303030;\n}\nbody,\ndiv.body {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n color: #303030;\n background-color: #ffffff;\n background: #ffffff;\n}\nbody.notebook_app {\n padding: 0;\n background-color: #ffffff;\n background: #ffffff;\n padding-right: 0px !important;\n overflow-y: hidden;\n}\na {\n font-family: \"Exo_2\", sans-serif;\n color: #303030;\n}\na:hover,\na:focus {\n color: #2f2f2f;\n}\n.list_header,\ndiv#notebook_list_header.row.list_header {\n font-size: 14pt;\n color: #2f2f2f;\n background-color: #ffffff;\n}\ndiv#cluster_list_header.row.list_header,\ndiv#running .row.list_header {\n font-size: 14pt;\n color: #303030;\n background: #eeeeee;\n background-color: #eeeeee;\n border-bottom: 2px solid rgba(180,180,180,.30);\n}\ndiv#cluster_list > div.list_item.row,\ndiv#cluster_list > div.list_item.row:hover {\n background: #f7f7f7;\n background-color: #f7f7f7;\n}\ndiv#clusters.tab-pane.active {\n font-size: 12.0pt;\n padding: 4px 0 4px 0;\n}\n#running .panel-group .panel .panel-heading {\n font-size: 14pt;\n color: #303030;\n padding: 8px 8px;\n background: #eeeeee;\n background-color: #eeeeee;\n}\n#running .panel-group .panel .panel-heading a {\n font-size: 14pt;\n color: #303030;\n}\n#running .panel-group .panel .panel-heading a:focus,\n#running .panel-group .panel .panel-heading a:hover {\n font-size: 14pt;\n color: #303030;\n}\n#running .panel-group .panel .panel-body .list_container .list_item {\n background: #f7f7f7;\n background-color: #f7f7f7;\n padding: 2px;\n border-bottom: 2px solid rgba(180,180,180,.30);\n}\n#running .panel-group .panel .panel-body .list_container .list_item:hover {\n background: #f7f7f7;\n background-color: #f7f7f7;\n}\n#running .panel-group .panel .panel-body {\n padding: 2px;\n}\ndiv.running_list_info.toolbar_info {\n font-size: 12.0pt;\n padding: 4px 0 4px 0;\n height: inherit;\n line-height: inherit;\n text-shadow: none;\n}\n.list_placeholder {\n font-weight: normal;\n}\n#tree-selector {\n padding: 0px;\n}\n#project_name > ul > li > a > i.fa.fa-home {\n color: #ff7823;\n font-size: 17pt;\n display: inline-block;\n position: static;\n padding: 0px 0px;\n font-weight: normal;\n text-align: center;\n vertical-align: text-top;\n}\n#project_name {\n display: inline-flex;\n padding-left: 7px;\n margin-left: -2px;\n margin-bottom: -20px;\n text-align: -webkit-auto;\n vertical-align: text-top;\n}\ndiv#notebook_toolbar div.dynamic-instructions {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n}\n.toolbar_info {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n color: #303030;\n text-shadow: none;\n border: none;\n height: inherit;\n line-height: inherit;\n}\n.list_container {\n font-size: 12.0pt;\n color: #303030;\n border: none;\n text-shadow: none !important;\n}\n.list_container > div {\n border-bottom: 1px solid rgba(180,180,180,.14);\n font-size: 12.0pt;\n}\n.list_header > div,\n.list_item > div {\n padding-left: 0px;\n}\n.list_header > div input,\n.list_item > div input {\n top: 0px;\n}\n.list_header > div .item_link,\n.list_item > div .item_link {\n margin-left: -1px;\n vertical-align: middle;\n line-height: 22px;\n font-size: 12.0pt;\n}\n.item_icon {\n font-size: 12.0pt;\n vertical-align: middle;\n}\n.list_item input:not([type=\"checkbox\"]) {\n padding-right: 0px;\n height: auto;\n width: 20%;\n margin: 6px 0 0;\n margin-top: 1px;\n}\n#button-select-all {\n height: auto;\n font-size: 12.0pt;\n padding: 5px;\n min-width: 65px;\n z-index: 0;\n}\nbutton#tree-selector-btn {\n height: auto;\n font-size: 12.0pt;\n padding: 5px;\n}\ninput#select-all.pull-left.tree-selector {\n margin-left: 7px;\n margin-right: 2px;\n margin-top: 5px;\n}\ninput[type=\"radio\"],\ninput[type=\"checkbox\"] {\n margin: 6px 0 0;\n margin-top: 1px;\n line-height: normal;\n}\n.list_container a {\n font-size: 17px;\n color: #303030;\n border: none;\n text-shadow: none !important;\n font-weight: normal;\n font-style: normal;\n}\ndiv.list_container a:hover {\n color: #2f2f2f;\n}\ndiv.list_item:hover {\n background-color: #fafafa;\n}\n.breadcrumb > li {\n font-size: 12.0pt;\n color: #303030;\n border: none;\n text-shadow: none !important;\n}\nul#tabs a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n font-weight: normal;\n font-style: normal;\n border-color: transparent;\n text-shadow: none !important;\n}\n.nav-tabs {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n font-weight: normal;\n font-style: normal;\n background: #ffffff;\n text-shadow: none !important;\n border-color: transparent;\n border-bottom-color: rgba(180,180,180,.30);\n}\n.nav-tabs > li > a:hover {\n color: #2f2f2f;\n background-color: rgba(180,180,180,.14);\n}\n.nav-tabs > li > a:active,\n.nav-tabs > li > a:focus,\n.nav-tabs > li.active > a,\n.nav-tabs > li.active > a:focus,\n.nav-tabs > li.active > a:hover,\n.nav-tabs > li.active > a,\n.nav-tabs > li.active > a:hover,\n.nav-tabs > li.active > a:focus {\n color: #1c1c1c;\n background-color: #eeeeee;\n border: 1px solid transparent;\n border-bottom-color: transparent;\n cursor: default;\n}\n.nav > li > a:hover,\n.nav > li > a:focus {\n text-decoration: none;\n background-color: rgba(180,180,180,.14);\n}\n.nav > li.disabled > a,\n.nav > li.disabled > a:hover {\n color: #aaaaaa;\n}\ndiv#notebook {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n padding-top: 4px;\n}\n.notebook_app {\n background-color: #ffffff;\n}\n#notebook-container {\n padding: 13px;\n background-color: #ffffff;\n min-height: 0px;\n box-shadow: none;\n width: 980px;\n margin-right: auto;\n margin-left: auto;\n}\ndiv#ipython-main-app.container {\n width: 980px;\n margin-right: auto;\n margin-left: auto;\n margin-right: auto;\n margin-left: auto;\n}\n.container {\n width: 980px;\n margin-right: auto;\n margin-left: auto;\n}\n.notebook_app #header {\n box-shadow: none !important;\n background-color: #ffffff;\n border-bottom: 2px solid rgba(180,180,180,.14);\n}\n#header {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n box-shadow: none;\n background-color: #ffffff;\n}\n#header .header-bar {\n background: #ffffff;\n background-color: #ffffff;\n}\nbody > #header .header-bar {\n width: 100%;\n background: #ffffff;\n}\n#menubar {\n background-color: #ffffff;\n}\n#menubar .navbar,\n.navbar-default {\n background-color: #ffffff;\n margin-bottom: 0px;\n}\n.navbar {\n border: none;\n}\n.navbar-default {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n background-color: #ffffff;\n border-color: rgba(180,180,180,.14);\n line-height: 1.5em;\n padding-bottom: 0px;\n}\n.navbar-default .navbar-nav > li > a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n color: #303030;\n display: block;\n line-height: 1.5em;\n padding-top: 8px;\n padding-bottom: 6px;\n}\n.navbar-default .navbar-nav > li > a:hover,\n.navbar-default .navbar-nav > li > a:focus {\n color: #2f2f2f;\n background-color: rgba(180,180,180,.14);\n border-color: rgba(180,180,180,.14);\n line-height: 1.5em;\n}\n.navbar-default .navbar-nav > .open > a,\n.navbar-default .navbar-nav > .open > a:hover,\n.navbar-default .navbar-nav > .open > a:focus {\n color: #1c1c1c;\n background-color: rgba(180,180,180,.14);\n border-color: rgba(180,180,180,.14);\n line-height: 1.5em;\n}\n.edit_mode .modal_indicator:before {\n font-size: 13pt;\n color: #2c85f7;\n content: \"\\f040\";\n}\n.item_icon {\n color: #126dce;\n}\n.item_buttons .kernel-name {\n font-size: 13pt;\n color: #126dce;\n line-height: 22px;\n}\n.running_notebook_icon:before {\n color: #009e07 !important;\n}\n.item_buttons .running-indicator {\n padding-top: 2px;\n color: #009e07;\n}\n#modal_indicator {\n float: right !important;\n color: #126dce;\n background: #ffffff;\n background-color: #ffffff;\n}\n#kernel_indicator {\n float: right !important;\n color: #ff7823;\n background: #ffffff;\n background-color: #ffffff;\n font-size: 14.5pt;\n border-left: 2px solid #ff7823;\n padding-bottom: 2px;\n}\n#kernel_indicator .kernel_indicator_name {\n color: #ff7823;\n background: #ffffff;\n background-color: #ffffff;\n font-size: 14.5pt;\n padding-left: 5px;\n padding-right: 5px;\n}\ndiv.notification_widget.info,\n.notification_widget.info,\n.notification_widget:active:hover,\n.notification_widget.active:hover,\n.open > .dropdown-toggle.notification_widget:hover,\n.notification_widget:active:focus,\n.notification_widget.active:focus,\n.open > .dropdown-toggle.notification_widget:focus,\n.notification_widget:active.focus,\n.notification_widget.active.focus,\n.open > .dropdown-toggle.notification_widget.focus,\ndiv#notification_notebook.notification_widget.btn.btn-xs.navbar-btn,\ndiv#notification_notebook.notification_widget.btn.btn-xs.navbar-btn:hover,\ndiv#notification_notebook.notification_widget.btn.btn-xs.navbar-btn:focus {\n color: #126dce;\n background-color: #ffffff;\n border-color: #ffffff;\n}\n#notification_area,\ndiv.notification_area {\n float: right !important;\n position: static;\n}\n#kernel_logo_widget,\n#kernel_logo_widget .current_kernel_logo {\n display: none;\n}\ndiv#ipython_notebook {\n display: none;\n}\ni.fa.fa-icon {\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n text-rendering: auto;\n}\n.fa {\n display: inline-block;\n font: normal normal normal 12pt/1 \"FontAwesome\", \"Exo_2\", sans-serif;\n text-rendering: auto;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n.dropdown-menu {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n box-shadow: none;\n padding: 0px;\n text-align: left;\n border: 2px solid rgba(180,180,180,.30);\n background-color: #ffffff;\n background: #ffffff;\n line-height: 1.3;\n margin: 0px;\n}\n.dropdown-menu:hover {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n border: 2px solid rgba(180,180,180,.30);\n background-color: #ffffff;\n box-shadow: none;\n line-height: 1.3;\n}\n.dropdown-header {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n display: block;\n color: #ff7823;\n text-decoration: underline;\n white-space: nowrap;\n padding: 8px 0px 0px 6px;\n line-height: 1.3;\n}\n.dropdown-menu > li > a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n line-height: 1.3;\n display: block;\n padding: 10px 25px 10px 14px;\n color: #303030;\n background-color: #ffffff;\n background: #ffffff;\n}\n.dropdown-menu > li > a:hover {\n color: #2f2f2f;\n background-color: rgba(180,180,180,.14);\n background: rgba(180,180,180,.14);\n border-color: rgba(180,180,180,.14);\n}\n.dropdown-menu .divider {\n height: 2px;\n margin: 0px 0px;\n overflow: hidden;\n background-color: rgba(180,180,180,.30);\n}\n.dropdown-submenu > .dropdown-menu {\n top: 0;\n left: 100%;\n margin-top: -2px;\n margin-left: 0px;\n padding-top: 0px;\n}\n.dropdown-menu > .disabled > a,\n.dropdown-menu > .disabled > a:hover,\n.dropdown-menu > .disabled > a:focus {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n font-weight: normal;\n color: #aaaaaa;\n padding: none;\n display: block;\n clear: both;\n line-height: 1.2;\n white-space: nowrap;\n}\n.dropdown-submenu > a:after {\n color: #303030;\n margin-right: -16px;\n}\n.dropdown-submenu:hover > a:after,\n.dropdown-submenu:active > a:after,\n.dropdown-submenu:focus > a:after,\n.dropdown-submenu:visited > a:after {\n color: #ff7823;\n margin-right: -16px;\n}\ndiv.kse-dropdown > .dropdown-menu,\n.kse-dropdown > .dropdown-menu {\n min-width: 0;\n top: 94%;\n}\n.btn,\n.btn-default {\n font-family: \"Exo_2\", sans-serif;\n color: #303030;\n background: #ebebeb;\n background-color: #ebebeb;\n border: 2px solid #e8e8e8;\n font-weight: normal;\n box-shadow: none;\n text-shadow: none;\n border-radius: 2px;\n font-size: inherit;\n}\n.btn:hover,\n.btn:active:hover,\n.btn.active:hover,\n.btn-default:hover,\n.open > .dropdown-toggle.btn-default:hover,\n.open > .dropdown-toggle.btn:hover {\n color: #2f2f2f;\n background-color: #e4e4e4;\n background: #e4e4e4;\n border-color: #e4e4e4;\n background-image: none;\n box-shadow: none !important;\n border-radius: 2px;\n}\n.btn:active,\n.btn.active,\n.btn:active:focus,\n.btn.active:focus,\n.btn:active.focus,\n.btn.active.focus,\n.btn-default:focus,\n.btn-default.focus,\n.btn-default:active,\n.btn-default.active,\n.btn-default:active:hover,\n.btn-default.active:hover,\n.btn-default:active:focus,\n.btn-default.active:focus,\n.btn-default:active.focus,\n.btn-default.active.focus,\n.open > .dropdown-toggle.btn:focus,\n.open > .dropdown-toggle.btn.focus,\n.open > .dropdown-toggle.btn-default {\n color: #1c1c1c;\n background-color: #e4e4e4;\n background: #e4e4e4;\n border-color: #e4e4e4;\n background-image: none;\n box-shadow: none !important;\n border-radius: 2px;\n}\n.item_buttons > .btn,\n.item_buttons > .btn-group,\n.item_buttons > .input-group {\n margin-left: 5px;\n background: #eeeeee;\n background-color: #eeeeee;\n border: 2px solid #eeeeee;\n}\n.item_buttons > .btn:hover,\n.item_buttons > .btn-group:hover,\n.item_buttons > .input-group:hover {\n margin-left: 5px;\n background: #e9e9e9;\n background-color: #e9e9e9;\n border: 2px solid #e9e9e9;\n}\n.btn-group > .btn-mini,\n.btn-sm,\n.btn-group-sm > .btn,\n.btn-xs,\n.btn-group-xs > .btn,\n.alternate_upload .btn-upload,\n.btn-group,\n.btn-group-vertical {\n font-size: 12.0pt;\n font-weight: normal;\n}\n.btn-xs,\n.btn-group-xs > .btn {\n font-size: 12.0pt;\n background-image: none;\n font-weight: normal;\n text-shadow: none;\n display: inline-table;\n}\n.alternate_upload .btn-upload {\n display: none;\n}\n.alternate_upload input.fileinput {\n display: none;\n}\nbutton.close {\n border: 0px none;\n font-family: sans-serif;\n font-size: 25pt;\n}\n.dynamic-buttons {\n font-size: inherit;\n padding-top: 0px;\n display: inline-block;\n}\n.close {\n color: #de143d;\n opacity: .5;\n text-shadow: none;\n}\n.close:hover {\n color: #de143d;\n opacity: 1;\n}\ndiv.btn.btn-default.output_collapsed {\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: #eeeeee;\n}\ndiv.btn.btn-default.output_collapsed:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border-color: #e9e9e9;\n}\ndiv.nbext-enable-btns .btn[disabled],\ndiv.nbext-enable-btns .btn[disabled]:hover,\n.btn-default.disabled,\n.btn-default[disabled],\n.btn-default.disabled:hover,\n.btn-default[disabled]:hover,\nfieldset[disabled] .btn-default:hover,\n.btn-default.disabled:focus,\n.btn-default[disabled]:focus,\nfieldset[disabled] .btn-default:focus,\n.btn-default.disabled.focus,\n.btn-default[disabled].focus,\nfieldset[disabled] .btn-default.focus {\n color: #4a4a4a;\n background: #e8e8e8;\n background-color: #e8e8e8;\n border-color: #e8e8e8;\n}\n.input-group-addon {\n padding: 2px 5px;\n font-size: 12.0pt;\n font-weight: normal;\n height: auto;\n color: #303030;\n text-align: center;\n background-color: #ffffff;\n border: none;\n}\n.btn-group > .btn + .dropdown-toggle {\n padding-left: 8px;\n padding-right: 8px;\n height: 100%;\n border-left: 2px solid #ff7823 !important;\n}\n.btn-group > .btn + .dropdown-toggle:hover {\n border-left: 2px solid #ff7823 !important;\n}\n.input-group-btn {\n position: relative;\n font-size: inherit;\n white-space: nowrap;\n}\n.input-group-btn:first-child > .btn,\n.input-group-btn:first-child > .btn-group {\n background: #eeeeee;\n background-color: #eeeeee;\n border: 1px solid #e9e9e9;\n margin: 2px;\n font-size: inherit;\n}\n.input-group-btn:first-child > .btn:hover,\n.input-group-btn:first-child > .btn-group:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border: 1px solid #e9e9e9;\n margin: 2px;\n font-size: inherit;\n}\ndiv.modal .btn-group > .btn:first-child {\n background: #eeeeee;\n background-color: #eeeeee;\n border: 1px solid #e9e9e9;\n margin-top: 0px !important;\n margin-left: 0px;\n margin-bottom: 2px;\n}\ndiv.modal .btn-group > .btn:first-child:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border: 1px solid #e9e9e9;\n}\ndiv.modal > button,\ndiv.modal-footer > button {\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: #eeeeee;\n}\ndiv.modal > button:hover,\ndiv.modal-footer > button:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border-color: #e9e9e9;\n}\n.modal-content {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n position: relative;\n background: #eeeeee;\n background-color: #eeeeee;\n border: none;\n border-radius: 1px;\n background-clip: padding-box;\n outline: none;\n}\n.modal-header {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n color: #303030;\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: rgba(180,180,180,.30);\n padding: 12px;\n min-height: 16.4286px;\n}\n.modal-content h4 {\n font-family: \"Exo_2\", sans-serif;\n font-size: 16pt;\n color: #303030;\n padding: 5px;\n}\n.modal-body {\n background-color: #ffffff;\n position: relative;\n padding: 15px;\n}\n.modal-footer {\n padding: 10px;\n text-align: right;\n background-color: #f7f7f7;\n border-top: 1px solid rgba(180,180,180,.30);\n}\n.alert-info {\n background-color: #fdfdfd;\n border-color: rgba(180,180,180,.30);\n color: #303030;\n}\n.modal-header .close {\n margin-top: -5px;\n font-size: 25pt;\n}\n.modal-backdrop,\n.modal-backdrop.in {\n opacity: 0.75;\n background-color: #eeeeee;\n}\ndiv.panel,\ndiv.panel-default,\n.panel,\n.panel-default {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n background-color: #f7f7f7;\n color: #303030;\n margin-bottom: 14px;\n border: 0;\n box-shadow: none;\n}\ndiv.panel > .panel-heading,\ndiv.panel-default > .panel-heading {\n font-size: 14pt;\n color: #303030;\n background: #eeeeee;\n background-color: #eeeeee;\n border: 0;\n}\n.modal .modal-dialog {\n min-width: 950px;\n margin: 50px auto;\n}\ndiv.container-fluid {\n margin-right: auto;\n margin-left: auto;\n padding-left: 7px;\n padding-right: 12px;\n}\ndiv.form-control,\n.form-control {\n font-family: \"Exo_2\", sans-serif;\n font-size: inherit;\n color: #303030;\n background-color: #ffffff;\n border: 2px solid #e7e7e7;\n margin-left: 2px;\n height: auto;\n box-shadow: none;\n padding: 6px 12px;\n transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;\n}\n.form-group.list-group-item {\n color: #303030;\n background-color: #f7f7f7;\n border-color: rgba(180,180,180,.30);\n margin-bottom: 0px;\n}\ninput,\nbutton,\nselect,\ntextarea {\n background-color: #ffffff;\n font-weight: normal;\n border: 2px solid rgba(180,180,180,.30);\n}\nselect.form-control.select-xs {\n height: auto;\n}\ndiv.output.output_scroll {\n box-shadow: none;\n}\n::-webkit-scrollbar-track {\n -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.11);\n background-color: #d0d0d0;\n border-radius: 6px;\n}\n::-webkit-scrollbar {\n width: 14px;\n height: 10px;\n background-color: #d0d0d0;\n border-radius: 6px;\n}\n::-webkit-scrollbar-thumb {\n background-color: #ffffff;\n background-image: -webkit-gradient(linear,40% 0%,75% 86%,from(#ff6b0f ),color-stop(0.5,#ff8b42 ),to(#ff6b0f ));\n min-height: 60px;\n border-radius: 2px;\n}\ndiv.input_area {\n background-color: #efefef;\n padding-right: 1.2em;\n border: 0px;\n border-top-left-radius: 0px;\n border-top-right-radius: 2px;\n border-bottom-left-radius: 0px;\n border-bottom-right-radius: 0px;\n}\ndiv.cell {\n padding: 0px;\n background: #efefef;\n background-color: #efefef;\n border: medium solid #ffffff;\n border-top-right-radius: 2px;\n border-top-left-radius: 2px;\n}\ndiv.cell.selected {\n background: #efefef;\n background-color: #efefef;\n border: medium solid #ff7823;\n padding: 0px;\n border-top-right-radius: 2px;\n border-top-left-radius: 2px;\n}\n.edit_mode div.cell.selected {\n padding: 0px;\n background: #efefef;\n background-color: #efefef;\n border: medium solid #ffd5bb;\n border-top-right-radius: 2px;\n border-top-left-radius: 2px;\n}\ndiv.cell.edit_mode {\n padding: 0px;\n background: #efefef;\n background-color: #efefef;\n border: medium solid #ffd5bb;\n border-top-right-radius: 2px;\n border-top-left-radius: 2px;\n}\ndiv.prompt,\n.prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n font-weight: normal;\n color: #aaaaaa;\n line-height: 170%;\n padding: 0px;\n padding-top: 4px;\n padding-left: .25em;\n text-align: left !important;\n min-width: 12ex;\n width: 12ex;\n}\ndiv.prompt.input_prompt {\n background-color: #efefef;\n border-right: 2px solid rgba(240,147,43,.50);\n border-top-left-radius: 2px;\n border-top-right-radius: 0px;\n border-bottom-left-radius: 0px;\n border-bottom-right-radius: 0px;\n min-width: 12ex;\n width: 12ex !important;\n}\ndiv.output_wrapper {\n background-color: #ffffff;\n border: 0px;\n margin-bottom: 0em;\n margin-top: 0em;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-left-radius: 2px;\n border-bottom-right-radius: 2px;\n}\ndiv.output_subarea.output_text.output_stream.output_stdout,\ndiv.output_subarea.output_text {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 10.0pt;\n line-height: 150% !important;\n background-color: #ffffff;\n color: #303030;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-left-radius: 2px;\n border-bottom-right-radius: 2px;\n}\ndiv.output_area pre {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 10.0pt;\n line-height: 150% !important;\n color: #303030;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-left-radius: 2px;\n border-bottom-right-radius: 2px;\n}\ndiv.output_area {\n display: -webkit-box;\n}\ndiv.output_html {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 10.0pt;\n color: #353535;\n background-color: #ffffff;\n background: #ffffff;\n}\ndiv.output_subarea {\n overflow-x: auto;\n padding: .8em;\n -webkit-box-flex: 1;\n -moz-box-flex: 1;\n box-flex: 1;\n flex: 1;\n max-width: 90%;\n}\ndiv.prompt.output_prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n background-color: #ffffff;\n color: #ffffff;\n border-bottom-left-radius: 2px;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-right-radius: 0px;\n min-width: 12ex;\n width: 12ex;\n}\ndiv.out_prompt_overlay.prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n background-color: #ffffff;\n border-bottom-left-radius: 2px;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-right-radius: 0px;\n min-width: 12ex;\n width: 12ex;\n}\ndiv.out_prompt_overlay.prompt:hover {\n background-color: #ffffff;\n box-shadow: #e8e8e8 2px 1px 2px 2.5px inset;\n border-bottom-left-radius: 2px;\n -webkit-border-: 2px;\n -moz-border-radius: 2px;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n min-width: 12ex;\n width: 12ex !important;\n}\ndiv.text_cell,\ndiv.text_cell_render pre,\ndiv.text_cell_render {\n font-family: \"Lora\", serif;\n font-size: 13pt;\n line-height: 170% !important;\n color: #353535;\n background: #ffffff;\n background-color: #ffffff;\n border-radius: 2px;\n}\ndiv.cell.text_cell.rendered.selected {\n font-family: \"Lora\", serif;\n border: medium solid #126dce;\n line-height: 170% !important;\n background: #ffffff;\n background-color: #ffffff;\n border-radius: 2px;\n}\ndiv.cell.text_cell.unrendered.selected {\n font-family: \"Lora\", serif;\n line-height: 170% !important;\n background: #ffffff;\n background-color: #ffffff;\n border: medium solid #126dce;\n border-radius: 2px;\n}\ndiv.cell.text_cell.selected {\n font-family: \"Lora\", serif;\n line-height: 170% !important;\n border: medium solid #126dce;\n background: #ffffff;\n background-color: #ffffff;\n border-radius: 2px;\n}\n.edit_mode div.cell.text_cell.selected {\n font-family: \"Lora\", serif;\n line-height: 170% !important;\n background: #ffffff;\n background-color: #ffffff;\n border: medium solid #87b0db;\n border-radius: 2px;\n}\ndiv.text_cell.unrendered,\ndiv.text_cell.unrendered.selected,\ndiv.edit_mode div.text_cell.unrendered {\n font-family: \"Lora\", serif;\n line-height: 170% !important;\n background: #ffffff;\n background-color: #ffffff;\n border-radius: 2px;\n}\ndiv.cell.text_cell.rendered .input_prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n font-weight: normal;\n color: #aaaaaa;\n text-align: left !important;\n min-width: 0ex;\n width: 0ex !important;\n background-color: #ffffff;\n border-right: 2px solid transparent;\n}\ndiv.cell.text_cell.unrendered .input_prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n font-weight: normal;\n color: #aaaaaa;\n text-align: left !important;\n min-width: 0ex;\n width: 0ex !important;\n border-right: 2px solid transparent;\n}\ndiv.rendered_html code {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n padding-top: 3px;\n color: #303030;\n background: #efefef;\n background-color: #efefef;\n}\npre,\ncode,\nkbd,\nsamp {\n white-space: pre-wrap;\n}\ncode {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt !important;\n line-height: 170% !important;\n color: #353535;\n background: #efefef;\n background-color: #efefef;\n}\nkbd {\n padding: 4px;\n font-size: 11pt;\n color: #303030;\n background-color: #efefef;\n border: 0;\n box-shadow: none;\n}\npre {\n display: block;\n padding: 8.5px;\n margin: 0 0 9px;\n font-size: 12.0pt;\n line-height: 1.42857143;\n color: #303030;\n background-color: #efefef;\n border: 1px solid #e7e7e7;\n border-radius: 2px;\n}\ndiv.rendered_html {\n color: #353535;\n}\ndiv.rendered_html pre,\ndiv.text_cell_render pre {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt !important;\n line-height: 170% !important;\n color: #353535;\n background: #efefef;\n background-color: #efefef;\n border: 2px #e7e7e7  solid;\n max-width: 86%;\n border-radius: 2px;\n padding: 5px;\n}\ndiv.text_cell_render h1,\ndiv.rendered_html h1,\ndiv.text_cell_render h2,\ndiv.rendered_html h2,\ndiv.text_cell_render h3,\ndiv.rendered_html h3,\ndiv.text_cell_render h4,\ndiv.rendered_html h4,\ndiv.text_cell_render h5,\ndiv.rendered_html h5 {\n font-family: \"Exo_2\", sans-serif;\n}\n.rendered_html h1:first-child,\n.rendered_html h2:first-child,\n.rendered_html h3:first-child,\n.rendered_html h4:first-child,\n.rendered_html h5:first-child,\n.rendered_html h6:first-child {\n margin-top: 0.2em;\n}\n.rendered_html h1,\n.text_cell_render h1 {\n color: #126dce;\n font-size: 220%;\n text-align: center;\n font-weight: lighter;\n}\n.rendered_html h2,\n.text_cell_render h2 {\n text-align: left;\n font-size: 170%;\n color: #126dce;\n font-style: normal;\n font-weight: lighter;\n}\n.rendered_html h3,\n.text_cell_render h3 {\n font-size: 150%;\n color: #126dce;\n font-weight: lighter;\n text-decoration: italic;\n font-style: normal;\n}\n.rendered_html h4,\n.text_cell_render h4 {\n font-size: 120%;\n color: #126dce;\n font-weight: underline;\n font-style: normal;\n}\n.rendered_html h5,\n.text_cell_render h5 {\n font-size: 100%;\n color: #2f2f2f;\n font-weight: lighter;\n text-decoration: underline;\n}\n.rendered_html table,\n.rendered_html tr,\n.rendered_html td {\n font-family: \"Fira Code\", monospace;\n font-size: 10.0pt !important;\n line-height: 150% !important;\n border: 1px solid #d6d6d6;\n color: #353535;\n background-color: #ffffff;\n background: #ffffff;\n}\ntable.dataframe,\n.rendered_html tr,\n.dataframe * {\n font-family: \"Fira Code\", monospace;\n font-size: 10.0pt !important;\n border: 1px solid #d6d6d6;\n}\n.dataframe th,\n.rendered_html th {\n font-family: \"Exo_2\", sans-serif;\n font-size: 11pt !important;\n font-weight: bold;\n border: 1px solid #c4c4c4;\n background: #eeeeee;\n}\n.dataframe td,\n.rendered_html td {\n font-family: \"Fira Code\", monospace;\n font-size: 10.0pt !important;\n color: #353535;\n background: #ffffff;\n border: 1px solid #d6d6d6;\n text-align: left;\n min-width: 4em;\n}\n.dataframe-summary-row tr:last-child,\n.dataframe-summary-col td:last-child {\n font-family: \"Exo_2\", sans-serif;\n font-size: 11pt !important;\n font-weight: bold;\n color: #353535;\n border: 1px solid #d6d6d6;\n background: #eeeeee;\n}\ndiv.widget-area {\n background-color: #ffffff;\n background: #ffffff;\n color: #303030;\n}\ndiv.widget-area a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n font-weight: normal;\n font-style: normal;\n color: #303030;\n text-shadow: none !important;\n}\ndiv.widget-area a:hover,\ndiv.widget-area a:focus {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n font-weight: normal;\n font-style: normal;\n color: #2f2f2f;\n background: rgba(180,180,180,.14);\n background-color: rgba(180,180,180,.14);\n border-color: transparent;\n background-image: none;\n text-shadow: none !important;\n}\ndiv.widget_item.btn-group > button.btn.btn-default.widget-combo-btn,\ndiv.widget_item.btn-group > button.btn.btn-default.widget-combo-btn:hover {\n background: #eeeeee;\n background-color: #eeeeee;\n border: 2px solid #eeeeee !important;\n font-size: inherit;\n z-index: 0;\n}\ndiv.jupyter-widgets.widget-hprogress.widget-hbox,\ndiv.widget-hbox,\n.widget-hbox {\n display: inline-table;\n}\ndiv.jupyter-widgets.widget-hprogress.widget-hbox .widget-label,\ndiv.widget-hbox .widget-label,\n.widget-hbox .widget-label {\n font-size: 11pt;\n min-width: 100%;\n padding-top: 5px;\n padding-right: 10px;\n text-align: left;\n vertical-align: text-top;\n}\n.progress {\n overflow: hidden;\n height: 20px;\n margin-bottom: 10px;\n padding-left: 10px;\n background-color: #c6c6c6;\n border-radius: 4px;\n -webkit-box-shadow: none;\n box-shadow: none;\n}\n.rendered_html :link {\n font-family: \"Exo_2\", sans-serif;\n font-size: 100%;\n color: #2c85f7;\n text-decoration: underline;\n}\n.rendered_html :visited,\n.rendered_html :visited:active,\n.rendered_html :visited:focus {\n color: #2e6eb2;\n}\n.rendered_html :visited:hover,\n.rendered_html :link:hover {\n font-family: \"Exo_2\", sans-serif;\n font-size: 100%;\n color: #eb6a18;\n}\na.anchor-link:link:hover {\n font-size: inherit;\n color: #eb6a18;\n}\na.anchor-link:link {\n font-size: inherit;\n text-decoration: none;\n padding: 0px 20px;\n visibility: none;\n color: #126dce;\n}\ndiv#nbextensions-configurator-container.container {\n width: 980px;\n margin-right: 0;\n margin-left: 0;\n}\ndiv.nbext-selector > nav > .nav > li > a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12pt;\n}\ndiv.nbext-readme > .nbext-readme-contents > .rendered_html {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12pt;\n line-height: 145%;\n padding: 1em 1em;\n color: #353535;\n background-color: #ffffff;\n -webkit-box-shadow: none;\n -moz-box-shadow: none;\n box-shadow: none;\n}\n.nbext-icon,\n.nbext-desc,\n.nbext-compat-div,\n.nbext-enable-btns,\n.nbext-params {\n margin-bottom: 8px;\n font-size: 12pt;\n}\ndiv.nbext-readme > .nbext-readme-contents {\n padding: 0;\n overflow-y: hidden;\n}\ndiv.nbext-readme > .nbext-readme-contents:not(:empty) {\n margin-top: 0.5em;\n margin-bottom: 2em;\n border: none;\n border-top-color: rgba(180,180,180,.30);\n}\n.nbext-showhide-incompat {\n padding-bottom: 0.5em;\n color: #4a4a4a;\n font-size: 12.0pt;\n}\n.shortcut_key,\nspan.shortcut_key {\n display: inline-block;\n width: 16ex;\n text-align: right;\n font-family: monospace;\n}\nmark,\n.mark {\n background-color: #ffffff;\n color: #353535;\n padding: .15em;\n}\na.text-warning,\na.text-warning:hover {\n color: #aaaaaa;\n}\na.text-warning.bg-warning {\n background-color: #ffffff;\n}\nspan.bg-success.text-success {\n background-color: transparent;\n color: #009e07;\n}\nspan.bg-danger.text-danger {\n background-color: #ffffff;\n color: #de143d;\n}\n.has-success .input-group-addon {\n color: #009e07;\n border-color: transparent;\n background: inherit;\n background-color: rgba(83,180,115,.10);\n}\n.has-success .form-control {\n border-color: #009e07;\n -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.025);\n box-shadow: inset 0 1px 1px rgba(0,0,0,0.025);\n}\n.has-error .input-group-addon {\n color: #de143d;\n border-color: transparent;\n background: inherit;\n background-color: rgba(192,57,67,.10);\n}\n.has-error .form-control {\n border-color: #de143d;\n -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.025);\n box-shadow: inset 0 1px 1px rgba(0,0,0,0.025);\n}\n.kse-input-group-pretty > kbd {\n font-family: \"Droid Sans Mono\", monospace;\n color: #303030;\n font-weight: normal;\n background: transparent;\n}\n.kse-input-group-pretty > kbd {\n font-family: \"Droid Sans Mono\", monospace;\n color: #303030;\n font-weight: normal;\n background: transparent;\n}\ndiv.nbext-enable-btns .btn[disabled],\ndiv.nbext-enable-btns .btn[disabled]:hover,\n.btn-default.disabled,\n.btn-default[disabled] {\n background: #e8e8e8;\n background-color: #e8e8e8;\n color: #282828;\n}\nlabel#Keyword-Filter {\n display: none;\n}\n.nav-pills > li.active > a,\n.nav-pills > li.active > a:hover,\n.nav-pills > li.active > a:focus {\n color: #ffffff;\n background-color: #126dce;\n}\n.input-group .nbext-list-btn-add,\n.input-group-btn:last-child > .btn-group > .btn {\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: #eeeeee;\n}\n.input-group .nbext-list-btn-add:hover,\n.input-group-btn:last-child > .btn-group > .btn:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border-color: #e9e9e9;\n}\n#notebook-container > div.cell.code_cell.rendered.selected > div.widget-area > div.widget-subarea > div > div.widget_item.btn-group > button.btn.btn-default.dropdown-toggle.widget-combo-carrot-btn {\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: #eeeeee;\n}\n#notebook-container > div.cell.code_cell.rendered.selected > div.widget-area > div.widget-subarea > div > div.widget_item.btn-group > button.btn.btn-default.dropdown-toggle.widget-combo-carrot-btn:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border-color: #e9e9e9;\n}\ninput.raw_input {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt !important;\n color: #303030;\n background-color: #efefef;\n border-color: #ececec;\n background: #ececec;\n width: auto;\n vertical-align: baseline;\n padding: 0em 0.25em;\n margin: 0em 0.25em;\n -webkit-box-shadow: none;\n box-shadow: none;\n}\naudio,\nvideo {\n display: inline;\n vertical-align: middle;\n align-content: center;\n margin-left: 20%;\n}\n.cmd-palette .modal-body {\n padding: 0px;\n margin: 0px;\n}\n.cmd-palette form {\n background: #eeeeee;\n background-color: #eeeeee;\n}\n.typeahead-field input:last-child,\n.typeahead-hint {\n background: #eeeeee;\n background-color: #eeeeee;\n z-index: 1;\n}\n.typeahead-field input {\n font-family: \"Exo_2\", sans-serif;\n color: #303030;\n border: none;\n font-size: 28pt;\n display: inline-block;\n line-height: inherit;\n padding: 3px 10px;\n height: 70px;\n}\n.typeahead-select {\n background-color: #eeeeee;\n}\nbody > div.modal.cmd-palette.typeahead-field {\n display: table;\n border-collapse: separate;\n background-color: #f7f7f7;\n}\n.typeahead-container button {\n font-family: \"Exo_2\", sans-serif;\n font-size: 28pt;\n background-color: #d0d0d0;\n border: none;\n display: inline-block;\n line-height: inherit;\n padding: 3px 10px;\n height: 70px;\n}\n.typeahead-search-icon {\n min-width: 40px;\n min-height: 55px;\n display: block;\n vertical-align: middle;\n text-align: center;\n}\n.typeahead-container button:focus,\n.typeahead-container button:hover {\n color: #2f2f2f;\n background-color: #ff7823;\n border-color: #ff7823;\n}\n.typeahead-list > li.typeahead-group.active > a,\n.typeahead-list > li.typeahead-group > a,\n.typeahead-list > li.typeahead-group > a:focus,\n.typeahead-list > li.typeahead-group > a:hover {\n display: none;\n}\n.typeahead-dropdown > li > a,\n.typeahead-list > li > a {\n color: #303030;\n text-decoration: none;\n}\n.typeahead-dropdown,\n.typeahead-list {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n color: #303030;\n background-color: #ffffff;\n border: none;\n background-clip: padding-box;\n margin-top: 0px;\n padding: 3px 2px 3px 0px;\n line-height: 1.7;\n}\n.typeahead-dropdown > li.active > a,\n.typeahead-dropdown > li > a:focus,\n.typeahead-dropdown > li > a:hover,\n.typeahead-list > li.active > a,\n.typeahead-list > li > a:focus,\n.typeahead-list > li > a:hover {\n color: #2f2f2f;\n background-color: #f7f7f7;\n border-color: #f7f7f7;\n}\n.command-shortcut:before {\n content: \"(command)\";\n padding-right: 3px;\n color: #aaaaaa;\n}\n.edit-shortcut:before {\n content: \"(edit)\";\n padding-right: 3px;\n color: #aaaaaa;\n}\nul.typeahead-list i {\n margin-left: 1px;\n width: 18px;\n margin-right: 10px;\n}\nul.typeahead-list {\n max-height: 50vh;\n overflow: auto;\n}\n.typeahead-list > li {\n position: relative;\n border: none;\n}\ndiv.input.typeahead-hint,\ninput.typeahead-hint,\nbody > div.modal.cmd-palette.in > div > div > div > form > div > div.typeahead-field > span.typeahead-query > input.typeahead-hint {\n color: #aaaaaa !important;\n background-color: transparent;\n padding: 3px 10px;\n}\n.typeahead-dropdown > li > a,\n.typeahead-list > li > a {\n display: block;\n padding: 5px;\n clear: both;\n font-weight: 400;\n line-height: 1.7;\n border: 1px solid #ffffff;\n border-bottom-color: rgba(180,180,180,.30);\n}\nbody > div.modal.cmd-palette.in > div {\n min-width: 750px;\n margin: 150px auto;\n}\n.typeahead-container strong {\n font-weight: bolder;\n color: #ff7823;\n}\n#find-and-replace #replace-preview .match,\n#find-and-replace #replace-preview .insert {\n color: #ffffff;\n background-color: #ff7823;\n border-color: #ff7823;\n border-style: solid;\n border-width: 1px;\n border-radius: 0px;\n}\n#find-and-replace #replace-preview .replace .match {\n background-color: #de143d;\n border-color: #de143d;\n border-radius: 0px;\n}\n#find-and-replace #replace-preview .replace .insert {\n background-color: #009e07;\n border-color: #009e07;\n border-radius: 0px;\n}\ndiv.CodeMirror,\ndiv.CodeMirror pre {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n line-height: 170%;\n color: #303030;\n}\ndiv.CodeMirror-lines {\n padding-bottom: .6em;\n padding-left: .5em;\n padding-right: 1.5em;\n padding-top: 4px;\n}\nspan.ansiblack {\n color: #dc4384;\n}\nspan.ansiblue {\n color: #009e07;\n}\nspan.ansigray {\n color: #ff7823;\n}\nspan.ansigreen {\n color: #333333;\n}\nspan.ansipurple {\n color: #653bc5;\n}\nspan.ansicyan {\n color: #055be0;\n}\nspan.ansiyellow {\n color: #ff7823;\n}\nspan.ansired {\n color: #de143d;\n}\ndiv.output-stderr {\n background-color: #ebb5b7;\n}\ndiv.output-stderr pre {\n color: #000000;\n}\ndiv.js-error {\n color: #de143d;\n}\n.ipython_tooltip {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n line-height: 170%;\n border: 2px solid #dadada;\n background: #eeeeee;\n background-color: #eeeeee;\n border-radius: 2px;\n overflow-x: visible;\n overflow-y: visible;\n box-shadow: none;\n position: absolute;\n z-index: 1000;\n}\n.ipython_tooltip .tooltiptext pre {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n line-height: 170%;\n background: #eeeeee;\n background-color: #eeeeee;\n color: #303030;\n overflow-x: visible;\n overflow-y: visible;\n max-width: 900px;\n}\ndiv#tooltip.ipython_tooltip {\n overflow-x: wrap;\n overflow-y: visible;\n max-width: 800px;\n}\ndiv.tooltiptext.bigtooltip {\n overflow-x: visible;\n overflow-y: scroll;\n height: 400px;\n max-width: 800px;\n}\n.cm-s-ipython.CodeMirror {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n background: #efefef;\n color: #303030;\n border-radius: 2px;\n font-style: normal;\n font-weight: normal;\n}\n.cm-s-ipython div.CodeMirror-selected {\n background: #e0e1e3;\n}\n.cm-s-ipython .CodeMirror-gutters {\n background: #e0e1e3;\n border: none;\n border-radius: 0px;\n}\n.cm-s-ipython .CodeMirror-linenumber {\n color: #aaaaaa;\n}\n.cm-s-ipython .CodeMirror-cursor {\n border-left: 2px solid #ff711a;\n}\n.cm-s-ipython span.cm-comment {\n color: #8d8d8d;\n font-style: italic;\n}\n.cm-s-ipython span.cm-atom {\n color: #055be0;\n}\n.cm-s-ipython span.cm-number {\n color: #ff8132;\n}\n.cm-s-ipython span.cm-property {\n color: #e22978;\n}\n.cm-s-ipython span.cm-attribute {\n color: #de143d;\n}\n.cm-s-ipython span.cm-keyword {\n color: #713bc5;\n font-weight: normal;\n}\n.cm-s-ipython span.cm-string {\n color: #009e07;\n}\n.cm-s-ipython span.cm-meta {\n color: #aa22ff;\n}\n.cm-s-ipython span.cm-operator {\n color: #055be0;\n}\n.cm-s-ipython span.cm-builtin {\n color: #e22978;\n}\n.cm-s-ipython span.cm-variable {\n color: #303030;\n}\n.cm-s-ipython span.cm-variable-2 {\n color: #de143d;\n}\n.cm-s-ipython span.cm-variable-3 {\n color: #aa22ff;\n}\n.cm-s-ipython span.cm-def {\n color: #e22978;\n font-weight: normal;\n}\n.cm-s-ipython span.cm-error {\n background: rgba(191,97,106,.40);\n}\n.cm-s-ipython span.cm-tag {\n color: #e22978;\n}\n.cm-s-ipython span.cm-link {\n color: #ff7823;\n}\n.cm-s-ipython span.cm-storage {\n color: #055be0;\n}\n.cm-s-ipython span.cm-entity {\n color: #e22978;\n}\n.cm-s-ipython span.cm-quote {\n color: #009e07;\n}\ndiv.CodeMirror span.CodeMirror-matchingbracket {\n color: #1c1c1c;\n background-color: rgba(30,112,199,.30);\n}\ndiv.CodeMirror span.CodeMirror-nonmatchingbracket {\n color: #1c1c1c;\n background: rgba(191,97,106,.40) !important;\n}\ndiv.cell.text_cell .cm-s-default .cm-header {\n color: #126dce;\n}\ndiv.cell.text_cell .cm-s-default span.cm-variable-2 {\n color: #353535;\n}\ndiv.cell.text_cell .cm-s-default span.cm-variable-3 {\n color: #aa22ff;\n}\n.cm-s-default span.cm-comment {\n color: #8d8d8d;\n}\n.cm-s-default .cm-tag {\n color: #009fb7;\n}\n.cm-s-default .cm-builtin {\n color: #e22978;\n}\n.cm-s-default .cm-string {\n color: #009e07;\n}\n.cm-s-default .cm-keyword {\n color: #713bc5;\n}\n.cm-s-default .cm-number {\n color: #ff8132;\n}\n.cm-s-default .cm-error {\n color: #055be0;\n}\n.CodeMirror-cursor {\n border-left: 2px solid #ff711a;\n border-right: none;\n width: 0;\n}\n.cm-s-default div.CodeMirror-selected {\n background: #e0e1e3;\n}\n.cm-s-default .cm-selected {\n background: #e0e1e3;\n}\ndiv#maintoolbar {\n display: none !important;\n}\n#header-container {\n display: none !important;\n}\n\n/**********************************\n MathJax Settings and Style Script\n**********************************/\n.MathJax_Display,\n.MathJax nobr>span.math>span {\n    border: 0 !important;\n    font-size: 110% !important;\n    text-align: center !important;\n    margin: 0em !important;\n}\n/* Prevents MathJax from jittering */\n/* cell position when cell is selected */\n.MathJax:focus, body :focus .MathJax {\n    display: inline-block !important;\n}\n\n\n\n </style>\n\n\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import rankdata, spearmanr, pearsonr\n\n# 1. magic for inline plot\n# 2. magic to print version\n# 3. magic so that the notebook will reload external python modules\n%matplotlib inline\n%load_ext watermark\n%load_ext autoreload \n%autoreload 2\n\n%watermark -a 'Ethen' -d -t -v -p numpy,matplotlib,jupyterthemes\n```\n\n    Ethen 2017-02-05 15:35:19 \n    \n    CPython 3.5.2\n    IPython 4.2.0\n    \n    numpy 1.12.0\n    matplotlib 2.0.0\n    jupyterthemes 0.13.9\n\n\n# Correlation\n\nA correlation coefficient measures the extent to which two variables tend to change together. The coefficient describes both the strength and the direction of the relationship. The two most popular types of correlation are **Pearson correlation** and **Spearman correlation**.\n\nThe Pearson correlation evaluates the linear relationship between two continuous variables. A relationship is linear when a change in one variable is associated with a constant proportional change in the other variable. On the other hand, the Spearman correlation evaluates the monotonic relationship between two continuous or ordinal variables. In a monotonic relationship, the variables tend to change together, but not necessarily at a constant rate. The Spearman correlation coefficient is based on the ranked values for each variable rather than the raw data.\n\nThe Pearson and Spearman correlation coefficients can range in value from \u22121 to +1. For the Pearson correlation coefficient to be +1, when one variable increases then the other variable increases by a consistent amount. This relationship forms a perfect line. The Spearman correlation coefficient is also +1 in this case.\n\n\n```python\nplt.rcParams['figure.figsize'] = 8, 6\n\n# y1 is simply 3 times x, so 1 unit\n# increase in x increases y by 3 unit\nx = np.arange(1, 101)\ny1 = 3 * x\nplt.scatter(x, y1)\nplt.show()\n```\n\n\n```python\nprint( 'pearson: ', pearsonr(x, x)[0] )\nprint( 'spearman: ', spearmanr(x, x)[0] )\n```\n\n    pearson:  1.0\n    spearman:  1.0\n\n\nIf the relationship is that one variable increases when the other increases, but the amount is not consistent, the Pearson correlation coefficient is positive but less than +1. The Spearman coefficient still equals +1 in this case.\n\n\n```python\n# y2 is the exponential of x,\n# thus the despite the fact that\n# y2 will increase when x is increased\n# by a unit, but the relationship is not a constant\ny2 = np.exp(x)\nplt.scatter(x, y2)\nplt.show()\n```\n\n\n```python\nprint( 'pearson: ', pearsonr(x, y2)[0] )\nprint( 'spearman: ', spearmanr(x, y2)[0] )\n```\n\n    pearson:  0.252032033904\n    spearman:  1.0\n\n\nThe idea can be generalized to negative relationships and when a relationship is random or non-existent, then both correlation coefficients are nearly zero.\n\nIt is always a good idea to examine the relationship between variables with a scatterplot. Correlation coefficients only measure linear (Pearson) or monotonic (Spearman) relationships. Other relationships are possible.\n\n\n```python\n# create 1000 equally spaced points between -10 and 10\n# calculate the y value for each element of the x vector\nx3 = np.linspace(-10, 10, 1000)\ny3 = x3 ** 2 + 2 * x3 + np.random.normal(loc = 0, scale = 5)\nplt.scatter(x3, y3)\nplt.show()\n```\n\n\n```python\nprint( 'pearson: ', pearsonr(x3, y3)[0] )\nprint( 'spearman: ', spearmanr(x3, y3)[0] )\n```\n\n    pearson:  0.360844075487\n    spearman:  0.269785169785\n\n\nFrom the plot above, we can see an obvious parabola relationship, thus the Pearson coefficient and Spearman coefficient will not be very helpful in discovering the pattern.\n\nTo understand how Spearman coefficient is calculated, we need to know that it is a rank correlation coefficient. Rank correlations are performed on ranks instead of the raw data itself. This can be very advantageous when dealing with data with outliers. For example, given two sets of data, say x = [5.05, 6.75, 3.21, 2.66] and y = [1.65, 26.5, -5.93, 7.96], with some ordering (here numerical) we can give them the ranks [3, 4, 2, 1] and [2, 4, 1, 3] respectively.\n\nTied ranks are usually assigned using the midrank method, whereby those entries receive the mean of the ranks they would have received had they not been tied. Thus z = [1.65, 2.64, 2.64, 6.95] would yield ranks [1, 2.5, 2.5, 4] using the midrank method.\n\n\n```python\nx = [5.05, 6.75, 3.21, 2.66]\nrankdata(x)\n```\n\n\n\n\n    array([ 3.,  4.,  2.,  1.])\n\n\n\n\n```python\n# the default method is average (tied rank)\nz = [1.65, 2.64, 2.64, 6.95]\nrankdata(z, method = 'average')\n```\n\n\n\n\n    array([ 1. ,  2.5,  2.5,  4. ])\n\n\n\nAfter obtaining the rank of the data, we can then use the following formula to perform the computation.\n\n\\begin{align}\n\\rho &= 1 - \\frac{6 \\sum_i (d_i)^2 }{ n(n^2 - 1) }\n\\end{align}\n\nWhere $d$ is the difference between the two ranks and $n$ is the number of elements in the vector.\n\n\n```python\ndef compute_spearman(a, b):\n    \"\"\"pass in the two vectors a and b\"\"\"\n    rank1 = rankdata(a)\n    rank2 = rankdata(b)\n    n = rank1.shape[0]\n    spearman = 1 - 6 * np.sum( (rank2 - rank1) ** 2 ) / ( n * (n ** 2 - 1) )\n    return spearman\n```\n\n\n```python\ncompute_spearman(x3, y3)\n```\n\n\n\n\n    0.26978516978516975\n\n\n\n## Reference\n\n- [Blog: Using Python (and R) to calculate Rank Correlations](http://www2.warwick.ac.uk/fac/sci/moac/people/students/peter_cock/python/rank_correlations/)\n- [Blog: Spearman Rank Correlation (Spearman\u2019s Rho): Definition and How to Calculate it](http://www.statisticshowto.com/spearman-rank-correlation-definition-calculate/)\n- [StackExchange: How to choose between Pearson and Spearman correlation?](http://stats.stackexchange.com/questions/8071/how-to-choose-between-pearson-and-spearman-correlation)\n- [Minitab Support: A comparison of the Pearson and Spearman correlation methods](http://support.minitab.com/en-us/minitab-express/1/help-and-how-to/modeling-statistics/regression/supporting-topics/basics/a-comparison-of-the-pearson-and-spearman-correlation-methods/)\n", "meta": {"hexsha": "888669c8979da7bdb6554d64ae11a7c3054250f1", "size": 105006, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "frequentist_statistics/correlation.ipynb", "max_stars_repo_name": "swapnilawasthi/Business-Analytics", "max_stars_repo_head_hexsha": "30a8585f45865008ea01d2bf242bf77a9ca5b449", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 92, "max_stars_repo_stars_event_min_datetime": "2016-05-22T06:07:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T03:53:44.000Z", "max_issues_repo_path": "frequentist_statistics/correlation.ipynb", "max_issues_repo_name": "ethen8181/Business-Analytics", "max_issues_repo_head_hexsha": "0fd0fd167eff1c4db05cf53ed744871bb3307595", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "frequentist_statistics/correlation.ipynb", "max_forks_repo_name": "ethen8181/Business-Analytics", "max_forks_repo_head_hexsha": "0fd0fd167eff1c4db05cf53ed744871bb3307595", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 42, "max_forks_repo_forks_event_min_datetime": "2017-02-08T02:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-06T08:53:11.000Z", "avg_line_length": 45.4374729554, "max_line_length": 12754, "alphanum_fraction": 0.6236215073, "converted": true, "num_tokens": 14014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03963884023547297, "lm_q2_score": 0.032589747232468325, "lm_q1q2_score": 0.0012918197838622592}}
{"text": "```python\nfrom jupyterthemes import get_themes\nfrom jupyterthemes.stylefx import set_nb_theme\nthemes = get_themes()\nset_nb_theme(themes[1])\n```\n\n\n\n\n<style> @font-face {\n font-family: 'Droid Sans Mono';\n font-weight: normal;\n font-style: normal;\n src: local('Droid Sans Mono'), url('fonts/droid-sans-mono.woff') format('woff');\n}\n@font-face {\n font-family: 'Exo_2';\n font-weight: normal;\n font-style: normal;\n src: local('Exo_2'), url('fonts/exo-II-regular.ttf') format('truetype');\n}\n@font-face {\n font-family: 'Fira Code';\n font-weight: normal;\n font-style: normal;\n src: local('Fira Code'), url('fonts/firacode.otf') format('opentype');\n}\n@font-face {\n font-family: 'Lora';\n font-weight: normal;\n font-style: normal;\n src: local('Lora'), url('fonts/Lora-Regular.ttf') format('truetype');\n}\ndiv#notebook {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n line-height: 170%;\n color: #303030;\n}\nbody,\ndiv.body {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n color: #303030;\n background-color: #ffffff;\n background: #ffffff;\n}\nbody.notebook_app {\n padding: 0;\n background-color: #ffffff;\n background: #ffffff;\n padding-right: 0px !important;\n overflow-y: hidden;\n}\na {\n font-family: \"Exo_2\", sans-serif;\n color: #303030;\n}\na:hover,\na:focus {\n color: #2f2f2f;\n}\n.list_header,\ndiv#notebook_list_header.row.list_header {\n font-size: 14pt;\n color: #2f2f2f;\n background-color: #ffffff;\n}\ndiv#cluster_list_header.row.list_header,\ndiv#running .row.list_header {\n font-size: 14pt;\n color: #303030;\n background: #eeeeee;\n background-color: #eeeeee;\n border-bottom: 2px solid rgba(180,180,180,.30);\n}\ndiv#cluster_list > div.list_item.row,\ndiv#cluster_list > div.list_item.row:hover {\n background: #f7f7f7;\n background-color: #f7f7f7;\n}\ndiv#clusters.tab-pane.active {\n font-size: 12.0pt;\n padding: 4px 0 4px 0;\n}\n#running .panel-group .panel .panel-heading {\n font-size: 14pt;\n color: #303030;\n padding: 8px 8px;\n background: #eeeeee;\n background-color: #eeeeee;\n}\n#running .panel-group .panel .panel-heading a {\n font-size: 14pt;\n color: #303030;\n}\n#running .panel-group .panel .panel-heading a:focus,\n#running .panel-group .panel .panel-heading a:hover {\n font-size: 14pt;\n color: #303030;\n}\n#running .panel-group .panel .panel-body .list_container .list_item {\n background: #f7f7f7;\n background-color: #f7f7f7;\n padding: 2px;\n border-bottom: 2px solid rgba(180,180,180,.30);\n}\n#running .panel-group .panel .panel-body .list_container .list_item:hover {\n background: #f7f7f7;\n background-color: #f7f7f7;\n}\n#running .panel-group .panel .panel-body {\n padding: 2px;\n}\ndiv.running_list_info.toolbar_info {\n font-size: 12.0pt;\n padding: 4px 0 4px 0;\n height: inherit;\n line-height: inherit;\n text-shadow: none;\n}\n.list_placeholder {\n font-weight: normal;\n}\n#tree-selector {\n padding: 0px;\n}\n#project_name > ul > li > a > i.fa.fa-home {\n color: #ff7823;\n font-size: 17pt;\n display: inline-block;\n position: static;\n padding: 0px 0px;\n font-weight: normal;\n text-align: center;\n vertical-align: text-top;\n}\n#project_name {\n display: inline-flex;\n padding-left: 7px;\n margin-left: -2px;\n margin-bottom: -20px;\n text-align: -webkit-auto;\n vertical-align: text-top;\n}\ndiv#notebook_toolbar div.dynamic-instructions {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n}\n.toolbar_info {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n color: #303030;\n text-shadow: none;\n border: none;\n height: inherit;\n line-height: inherit;\n}\n.list_container {\n font-size: 12.0pt;\n color: #303030;\n border: none;\n text-shadow: none !important;\n}\n.list_container > div {\n border-bottom: 1px solid rgba(180,180,180,.14);\n font-size: 12.0pt;\n}\n.list_header > div,\n.list_item > div {\n padding-left: 0px;\n}\n.list_header > div input,\n.list_item > div input {\n top: 0px;\n}\n.list_header > div .item_link,\n.list_item > div .item_link {\n margin-left: -1px;\n vertical-align: middle;\n line-height: 22px;\n font-size: 12.0pt;\n}\n.item_icon {\n font-size: 12.0pt;\n vertical-align: middle;\n}\n.list_item input:not([type=\"checkbox\"]) {\n padding-right: 0px;\n height: auto;\n width: 20%;\n margin: 6px 0 0;\n margin-top: 1px;\n}\n#button-select-all {\n height: auto;\n font-size: 12.0pt;\n padding: 5px;\n min-width: 65px;\n z-index: 0;\n}\nbutton#tree-selector-btn {\n height: auto;\n font-size: 12.0pt;\n padding: 5px;\n}\ninput#select-all.pull-left.tree-selector {\n margin-left: 7px;\n margin-right: 2px;\n margin-top: 5px;\n}\ninput[type=\"radio\"],\ninput[type=\"checkbox\"] {\n margin: 6px 0 0;\n margin-top: 1px;\n line-height: normal;\n}\n.list_container a {\n font-size: 17px;\n color: #303030;\n border: none;\n text-shadow: none !important;\n font-weight: normal;\n font-style: normal;\n}\ndiv.list_container a:hover {\n color: #2f2f2f;\n}\ndiv.list_item:hover {\n background-color: #fafafa;\n}\n.breadcrumb > li {\n font-size: 12.0pt;\n color: #303030;\n border: none;\n text-shadow: none !important;\n}\nul#tabs a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n font-weight: normal;\n font-style: normal;\n border-color: transparent;\n text-shadow: none !important;\n}\n.nav-tabs {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n font-weight: normal;\n font-style: normal;\n background: #ffffff;\n text-shadow: none !important;\n border-color: transparent;\n border-bottom-color: rgba(180,180,180,.30);\n}\n.nav-tabs > li > a:hover {\n color: #2f2f2f;\n background-color: rgba(180,180,180,.14);\n}\n.nav-tabs > li > a:active,\n.nav-tabs > li > a:focus,\n.nav-tabs > li.active > a,\n.nav-tabs > li.active > a:focus,\n.nav-tabs > li.active > a:hover,\n.nav-tabs > li.active > a,\n.nav-tabs > li.active > a:hover,\n.nav-tabs > li.active > a:focus {\n color: #1c1c1c;\n background-color: #eeeeee;\n border: 1px solid transparent;\n border-bottom-color: transparent;\n cursor: default;\n}\n.nav > li > a:hover,\n.nav > li > a:focus {\n text-decoration: none;\n background-color: rgba(180,180,180,.14);\n}\n.nav > li.disabled > a,\n.nav > li.disabled > a:hover {\n color: #aaaaaa;\n}\ndiv#notebook {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n padding-top: 4px;\n}\n.notebook_app {\n background-color: #ffffff;\n}\n#notebook-container {\n padding: 13px;\n background-color: #ffffff;\n min-height: 0px;\n box-shadow: none;\n width: 980px;\n margin-right: auto;\n margin-left: auto;\n}\ndiv#ipython-main-app.container {\n width: 980px;\n margin-right: auto;\n margin-left: auto;\n margin-right: auto;\n margin-left: auto;\n}\n.container {\n width: 980px;\n margin-right: auto;\n margin-left: auto;\n}\n.notebook_app #header {\n box-shadow: none !important;\n background-color: #ffffff;\n border-bottom: 2px solid rgba(180,180,180,.14);\n}\n#header {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n box-shadow: none;\n background-color: #ffffff;\n}\n#header .header-bar {\n background: #ffffff;\n background-color: #ffffff;\n}\nbody > #header .header-bar {\n width: 100%;\n background: #ffffff;\n}\n#menubar {\n background-color: #ffffff;\n}\n#menubar .navbar,\n.navbar-default {\n background-color: #ffffff;\n margin-bottom: 0px;\n}\n.navbar {\n border: none;\n}\n.navbar-default {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n background-color: #ffffff;\n border-color: rgba(180,180,180,.14);\n line-height: 1.5em;\n padding-bottom: 0px;\n}\n.navbar-default .navbar-nav > li > a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n color: #303030;\n display: block;\n line-height: 1.5em;\n padding-top: 8px;\n padding-bottom: 6px;\n}\n.navbar-default .navbar-nav > li > a:hover,\n.navbar-default .navbar-nav > li > a:focus {\n color: #2f2f2f;\n background-color: rgba(180,180,180,.14);\n border-color: rgba(180,180,180,.14);\n line-height: 1.5em;\n}\n.navbar-default .navbar-nav > .open > a,\n.navbar-default .navbar-nav > .open > a:hover,\n.navbar-default .navbar-nav > .open > a:focus {\n color: #1c1c1c;\n background-color: rgba(180,180,180,.14);\n border-color: rgba(180,180,180,.14);\n line-height: 1.5em;\n}\n.edit_mode .modal_indicator:before {\n font-size: 13pt;\n color: #2c85f7;\n content: \"\\f040\";\n}\n.item_icon {\n color: #126dce;\n}\n.item_buttons .kernel-name {\n font-size: 13pt;\n color: #126dce;\n line-height: 22px;\n}\n.running_notebook_icon:before {\n color: #009e07 !important;\n}\n.item_buttons .running-indicator {\n padding-top: 2px;\n color: #009e07;\n}\n#modal_indicator {\n float: right !important;\n color: #126dce;\n background: #ffffff;\n background-color: #ffffff;\n}\n#kernel_indicator {\n float: right !important;\n color: #ff7823;\n background: #ffffff;\n background-color: #ffffff;\n font-size: 14.5pt;\n border-left: 2px solid #ff7823;\n padding-bottom: 2px;\n}\n#kernel_indicator .kernel_indicator_name {\n color: #ff7823;\n background: #ffffff;\n background-color: #ffffff;\n font-size: 14.5pt;\n padding-left: 5px;\n padding-right: 5px;\n}\ndiv.notification_widget.info,\n.notification_widget.info,\n.notification_widget:active:hover,\n.notification_widget.active:hover,\n.open > .dropdown-toggle.notification_widget:hover,\n.notification_widget:active:focus,\n.notification_widget.active:focus,\n.open > .dropdown-toggle.notification_widget:focus,\n.notification_widget:active.focus,\n.notification_widget.active.focus,\n.open > .dropdown-toggle.notification_widget.focus,\ndiv#notification_notebook.notification_widget.btn.btn-xs.navbar-btn,\ndiv#notification_notebook.notification_widget.btn.btn-xs.navbar-btn:hover,\ndiv#notification_notebook.notification_widget.btn.btn-xs.navbar-btn:focus {\n color: #126dce;\n background-color: #ffffff;\n border-color: #ffffff;\n}\n#notification_area,\ndiv.notification_area {\n float: right !important;\n position: static;\n}\n#kernel_logo_widget,\n#kernel_logo_widget .current_kernel_logo {\n display: none;\n}\ndiv#ipython_notebook {\n display: none;\n}\ni.fa.fa-icon {\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n text-rendering: auto;\n}\n.fa {\n display: inline-block;\n font: normal normal normal 12pt/1 \"FontAwesome\", \"Exo_2\", sans-serif;\n text-rendering: auto;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n.dropdown-menu {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n box-shadow: none;\n padding: 0px;\n text-align: left;\n border: 2px solid rgba(180,180,180,.30);\n background-color: #ffffff;\n background: #ffffff;\n line-height: 1.3;\n margin: 0px;\n}\n.dropdown-menu:hover {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n border: 2px solid rgba(180,180,180,.30);\n background-color: #ffffff;\n box-shadow: none;\n line-height: 1.3;\n}\n.dropdown-header {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n display: block;\n color: #ff7823;\n text-decoration: underline;\n white-space: nowrap;\n padding: 8px 0px 0px 6px;\n line-height: 1.3;\n}\n.dropdown-menu > li > a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n line-height: 1.3;\n display: block;\n padding: 10px 25px 10px 14px;\n color: #303030;\n background-color: #ffffff;\n background: #ffffff;\n}\n.dropdown-menu > li > a:hover {\n color: #2f2f2f;\n background-color: rgba(180,180,180,.14);\n background: rgba(180,180,180,.14);\n border-color: rgba(180,180,180,.14);\n}\n.dropdown-menu .divider {\n height: 2px;\n margin: 0px 0px;\n overflow: hidden;\n background-color: rgba(180,180,180,.30);\n}\n.dropdown-submenu > .dropdown-menu {\n top: 0;\n left: 100%;\n margin-top: -2px;\n margin-left: 0px;\n padding-top: 0px;\n}\n.dropdown-menu > .disabled > a,\n.dropdown-menu > .disabled > a:hover,\n.dropdown-menu > .disabled > a:focus {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n font-weight: normal;\n color: #aaaaaa;\n padding: none;\n display: block;\n clear: both;\n line-height: 1.2;\n white-space: nowrap;\n}\n.dropdown-submenu > a:after {\n color: #303030;\n margin-right: -16px;\n}\n.dropdown-submenu:hover > a:after,\n.dropdown-submenu:active > a:after,\n.dropdown-submenu:focus > a:after,\n.dropdown-submenu:visited > a:after {\n color: #ff7823;\n margin-right: -16px;\n}\ndiv.kse-dropdown > .dropdown-menu,\n.kse-dropdown > .dropdown-menu {\n min-width: 0;\n top: 94%;\n}\n.btn,\n.btn-default {\n font-family: \"Exo_2\", sans-serif;\n color: #303030;\n background: #ebebeb;\n background-color: #ebebeb;\n border: 2px solid #e8e8e8;\n font-weight: normal;\n box-shadow: none;\n text-shadow: none;\n border-radius: 2px;\n font-size: inherit;\n}\n.btn:hover,\n.btn:active:hover,\n.btn.active:hover,\n.btn-default:hover,\n.open > .dropdown-toggle.btn-default:hover,\n.open > .dropdown-toggle.btn:hover {\n color: #2f2f2f;\n background-color: #e4e4e4;\n background: #e4e4e4;\n border-color: #e4e4e4;\n background-image: none;\n box-shadow: none !important;\n border-radius: 2px;\n}\n.btn:active,\n.btn.active,\n.btn:active:focus,\n.btn.active:focus,\n.btn:active.focus,\n.btn.active.focus,\n.btn-default:focus,\n.btn-default.focus,\n.btn-default:active,\n.btn-default.active,\n.btn-default:active:hover,\n.btn-default.active:hover,\n.btn-default:active:focus,\n.btn-default.active:focus,\n.btn-default:active.focus,\n.btn-default.active.focus,\n.open > .dropdown-toggle.btn:focus,\n.open > .dropdown-toggle.btn.focus,\n.open > .dropdown-toggle.btn-default {\n color: #1c1c1c;\n background-color: #e4e4e4;\n background: #e4e4e4;\n border-color: #e4e4e4;\n background-image: none;\n box-shadow: none !important;\n border-radius: 2px;\n}\n.item_buttons > .btn,\n.item_buttons > .btn-group,\n.item_buttons > .input-group {\n margin-left: 5px;\n background: #eeeeee;\n background-color: #eeeeee;\n border: 2px solid #eeeeee;\n}\n.item_buttons > .btn:hover,\n.item_buttons > .btn-group:hover,\n.item_buttons > .input-group:hover {\n margin-left: 5px;\n background: #e9e9e9;\n background-color: #e9e9e9;\n border: 2px solid #e9e9e9;\n}\n.btn-group > .btn-mini,\n.btn-sm,\n.btn-group-sm > .btn,\n.btn-xs,\n.btn-group-xs > .btn,\n.alternate_upload .btn-upload,\n.btn-group,\n.btn-group-vertical {\n font-size: 12.0pt;\n font-weight: normal;\n}\n.btn-xs,\n.btn-group-xs > .btn {\n font-size: 12.0pt;\n background-image: none;\n font-weight: normal;\n text-shadow: none;\n display: inline-table;\n}\n.alternate_upload .btn-upload {\n display: none;\n}\n.alternate_upload input.fileinput {\n display: none;\n}\nbutton.close {\n border: 0px none;\n font-family: sans-serif;\n font-size: 25pt;\n}\n.dynamic-buttons {\n font-size: inherit;\n padding-top: 0px;\n display: inline-block;\n}\n.close {\n color: #de143d;\n opacity: .5;\n text-shadow: none;\n}\n.close:hover {\n color: #de143d;\n opacity: 1;\n}\ndiv.btn.btn-default.output_collapsed {\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: #eeeeee;\n}\ndiv.btn.btn-default.output_collapsed:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border-color: #e9e9e9;\n}\ndiv.nbext-enable-btns .btn[disabled],\ndiv.nbext-enable-btns .btn[disabled]:hover,\n.btn-default.disabled,\n.btn-default[disabled],\n.btn-default.disabled:hover,\n.btn-default[disabled]:hover,\nfieldset[disabled] .btn-default:hover,\n.btn-default.disabled:focus,\n.btn-default[disabled]:focus,\nfieldset[disabled] .btn-default:focus,\n.btn-default.disabled.focus,\n.btn-default[disabled].focus,\nfieldset[disabled] .btn-default.focus {\n color: #4a4a4a;\n background: #e8e8e8;\n background-color: #e8e8e8;\n border-color: #e8e8e8;\n}\n.input-group-addon {\n padding: 2px 5px;\n font-size: 12.0pt;\n font-weight: normal;\n height: auto;\n color: #303030;\n text-align: center;\n background-color: #ffffff;\n border: none;\n}\n.btn-group > .btn + .dropdown-toggle {\n padding-left: 8px;\n padding-right: 8px;\n height: 100%;\n border-left: 2px solid #ff7823 !important;\n}\n.btn-group > .btn + .dropdown-toggle:hover {\n border-left: 2px solid #ff7823 !important;\n}\n.input-group-btn {\n position: relative;\n font-size: inherit;\n white-space: nowrap;\n}\n.input-group-btn:first-child > .btn,\n.input-group-btn:first-child > .btn-group {\n background: #eeeeee;\n background-color: #eeeeee;\n border: 1px solid #e9e9e9;\n margin: 2px;\n font-size: inherit;\n}\n.input-group-btn:first-child > .btn:hover,\n.input-group-btn:first-child > .btn-group:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border: 1px solid #e9e9e9;\n margin: 2px;\n font-size: inherit;\n}\ndiv.modal .btn-group > .btn:first-child {\n background: #eeeeee;\n background-color: #eeeeee;\n border: 1px solid #e9e9e9;\n margin-top: 0px !important;\n margin-left: 0px;\n margin-bottom: 2px;\n}\ndiv.modal .btn-group > .btn:first-child:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border: 1px solid #e9e9e9;\n}\ndiv.modal > button,\ndiv.modal-footer > button {\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: #eeeeee;\n}\ndiv.modal > button:hover,\ndiv.modal-footer > button:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border-color: #e9e9e9;\n}\n.modal-content {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n position: relative;\n background: #eeeeee;\n background-color: #eeeeee;\n border: none;\n border-radius: 1px;\n background-clip: padding-box;\n outline: none;\n}\n.modal-header {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n color: #303030;\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: rgba(180,180,180,.30);\n padding: 12px;\n min-height: 16.4286px;\n}\n.modal-content h4 {\n font-family: \"Exo_2\", sans-serif;\n font-size: 16pt;\n color: #303030;\n padding: 5px;\n}\n.modal-body {\n background-color: #ffffff;\n position: relative;\n padding: 15px;\n}\n.modal-footer {\n padding: 10px;\n text-align: right;\n background-color: #f7f7f7;\n border-top: 1px solid rgba(180,180,180,.30);\n}\n.alert-info {\n background-color: #fdfdfd;\n border-color: rgba(180,180,180,.30);\n color: #303030;\n}\n.modal-header .close {\n margin-top: -5px;\n font-size: 25pt;\n}\n.modal-backdrop,\n.modal-backdrop.in {\n opacity: 0.75;\n background-color: #eeeeee;\n}\ndiv.panel,\ndiv.panel-default,\n.panel,\n.panel-default {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n background-color: #f7f7f7;\n color: #303030;\n margin-bottom: 14px;\n border: 0;\n box-shadow: none;\n}\ndiv.panel > .panel-heading,\ndiv.panel-default > .panel-heading {\n font-size: 14pt;\n color: #303030;\n background: #eeeeee;\n background-color: #eeeeee;\n border: 0;\n}\n.modal .modal-dialog {\n min-width: 950px;\n margin: 50px auto;\n}\ndiv.container-fluid {\n margin-right: auto;\n margin-left: auto;\n padding-left: 7px;\n padding-right: 12px;\n}\ndiv.form-control,\n.form-control {\n font-family: \"Exo_2\", sans-serif;\n font-size: inherit;\n color: #303030;\n background-color: #ffffff;\n border: 2px solid #e7e7e7;\n margin-left: 2px;\n height: auto;\n box-shadow: none;\n padding: 6px 12px;\n transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;\n}\n.form-group.list-group-item {\n color: #303030;\n background-color: #f7f7f7;\n border-color: rgba(180,180,180,.30);\n margin-bottom: 0px;\n}\ninput,\nbutton,\nselect,\ntextarea {\n background-color: #ffffff;\n font-weight: normal;\n border: 2px solid rgba(180,180,180,.30);\n}\nselect.form-control.select-xs {\n height: auto;\n}\ndiv.output.output_scroll {\n box-shadow: none;\n}\n::-webkit-scrollbar-track {\n -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.11);\n background-color: #d0d0d0;\n border-radius: 6px;\n}\n::-webkit-scrollbar {\n width: 14px;\n height: 10px;\n background-color: #d0d0d0;\n border-radius: 6px;\n}\n::-webkit-scrollbar-thumb {\n background-color: #ffffff;\n background-image: -webkit-gradient(linear,40% 0%,75% 86%,from(#ff6b0f ),color-stop(0.5,#ff8b42 ),to(#ff6b0f ));\n min-height: 60px;\n border-radius: 2px;\n}\ndiv.input_area {\n background-color: #efefef;\n padding-right: 1.2em;\n border: 0px;\n border-top-left-radius: 0px;\n border-top-right-radius: 2px;\n border-bottom-left-radius: 0px;\n border-bottom-right-radius: 0px;\n}\ndiv.cell {\n padding: 0px;\n background: #efefef;\n background-color: #efefef;\n border: medium solid #ffffff;\n border-top-right-radius: 2px;\n border-top-left-radius: 2px;\n}\ndiv.cell.selected {\n background: #efefef;\n background-color: #efefef;\n border: medium solid #ff7823;\n padding: 0px;\n border-top-right-radius: 2px;\n border-top-left-radius: 2px;\n}\n.edit_mode div.cell.selected {\n padding: 0px;\n background: #efefef;\n background-color: #efefef;\n border: medium solid #ffd5bb;\n border-top-right-radius: 2px;\n border-top-left-radius: 2px;\n}\ndiv.cell.edit_mode {\n padding: 0px;\n background: #efefef;\n background-color: #efefef;\n border: medium solid #ffd5bb;\n border-top-right-radius: 2px;\n border-top-left-radius: 2px;\n}\ndiv.prompt,\n.prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n font-weight: normal;\n color: #aaaaaa;\n line-height: 170%;\n padding: 0px;\n padding-top: 4px;\n padding-left: .25em;\n text-align: left !important;\n min-width: 12ex;\n width: 12ex;\n}\ndiv.prompt.input_prompt {\n background-color: #efefef;\n border-right: 2px solid rgba(240,147,43,.50);\n border-top-left-radius: 2px;\n border-top-right-radius: 0px;\n border-bottom-left-radius: 0px;\n border-bottom-right-radius: 0px;\n min-width: 12ex;\n width: 12ex !important;\n}\ndiv.output_wrapper {\n background-color: #ffffff;\n border: 0px;\n margin-bottom: 0em;\n margin-top: 0em;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-left-radius: 2px;\n border-bottom-right-radius: 2px;\n}\ndiv.output_subarea.output_text.output_stream.output_stdout,\ndiv.output_subarea.output_text {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 10.0pt;\n line-height: 150% !important;\n background-color: #ffffff;\n color: #303030;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-left-radius: 2px;\n border-bottom-right-radius: 2px;\n}\ndiv.output_area pre {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 10.0pt;\n line-height: 150% !important;\n color: #303030;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-left-radius: 2px;\n border-bottom-right-radius: 2px;\n}\ndiv.output_area {\n display: -webkit-box;\n}\ndiv.output_html {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 10.0pt;\n color: #353535;\n background-color: #ffffff;\n background: #ffffff;\n}\ndiv.output_subarea {\n overflow-x: auto;\n padding: .8em;\n -webkit-box-flex: 1;\n -moz-box-flex: 1;\n box-flex: 1;\n flex: 1;\n max-width: 90%;\n}\ndiv.prompt.output_prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n background-color: #ffffff;\n color: #ffffff;\n border-bottom-left-radius: 2px;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-right-radius: 0px;\n min-width: 12ex;\n width: 12ex;\n}\ndiv.out_prompt_overlay.prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n background-color: #ffffff;\n border-bottom-left-radius: 2px;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-right-radius: 0px;\n min-width: 12ex;\n width: 12ex;\n}\ndiv.out_prompt_overlay.prompt:hover {\n background-color: #ffffff;\n box-shadow: #e8e8e8 2px 1px 2px 2.5px inset;\n border-bottom-left-radius: 2px;\n -webkit-border-: 2px;\n -moz-border-radius: 2px;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n min-width: 12ex;\n width: 12ex !important;\n}\ndiv.text_cell,\ndiv.text_cell_render pre,\ndiv.text_cell_render {\n font-family: \"Lora\", serif;\n font-size: 13pt;\n line-height: 170% !important;\n color: #353535;\n background: #ffffff;\n background-color: #ffffff;\n border-radius: 2px;\n}\ndiv.cell.text_cell.rendered.selected {\n font-family: \"Lora\", serif;\n border: medium solid #126dce;\n line-height: 170% !important;\n background: #ffffff;\n background-color: #ffffff;\n border-radius: 2px;\n}\ndiv.cell.text_cell.unrendered.selected {\n font-family: \"Lora\", serif;\n line-height: 170% !important;\n background: #ffffff;\n background-color: #ffffff;\n border: medium solid #126dce;\n border-radius: 2px;\n}\ndiv.cell.text_cell.selected {\n font-family: \"Lora\", serif;\n line-height: 170% !important;\n border: medium solid #126dce;\n background: #ffffff;\n background-color: #ffffff;\n border-radius: 2px;\n}\n.edit_mode div.cell.text_cell.selected {\n font-family: \"Lora\", serif;\n line-height: 170% !important;\n background: #ffffff;\n background-color: #ffffff;\n border: medium solid #87b0db;\n border-radius: 2px;\n}\ndiv.text_cell.unrendered,\ndiv.text_cell.unrendered.selected,\ndiv.edit_mode div.text_cell.unrendered {\n font-family: \"Lora\", serif;\n line-height: 170% !important;\n background: #ffffff;\n background-color: #ffffff;\n border-radius: 2px;\n}\ndiv.cell.text_cell.rendered .input_prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n font-weight: normal;\n color: #aaaaaa;\n text-align: left !important;\n min-width: 0ex;\n width: 0ex !important;\n background-color: #ffffff;\n border-right: 2px solid transparent;\n}\ndiv.cell.text_cell.unrendered .input_prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n font-weight: normal;\n color: #aaaaaa;\n text-align: left !important;\n min-width: 0ex;\n width: 0ex !important;\n border-right: 2px solid transparent;\n}\ndiv.rendered_html code {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n padding-top: 3px;\n color: #303030;\n background: #efefef;\n background-color: #efefef;\n}\npre,\ncode,\nkbd,\nsamp {\n white-space: pre-wrap;\n}\ncode {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt !important;\n line-height: 170% !important;\n color: #353535;\n background: #efefef;\n background-color: #efefef;\n}\nkbd {\n padding: 4px;\n font-size: 11pt;\n color: #303030;\n background-color: #efefef;\n border: 0;\n box-shadow: none;\n}\npre {\n display: block;\n padding: 8.5px;\n margin: 0 0 9px;\n font-size: 12.0pt;\n line-height: 1.42857143;\n color: #303030;\n background-color: #efefef;\n border: 1px solid #e7e7e7;\n border-radius: 2px;\n}\ndiv.rendered_html {\n color: #353535;\n}\ndiv.rendered_html pre,\ndiv.text_cell_render pre {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt !important;\n line-height: 170% !important;\n color: #353535;\n background: #efefef;\n background-color: #efefef;\n border: 2px #e7e7e7  solid;\n max-width: 86%;\n border-radius: 2px;\n padding: 5px;\n}\ndiv.text_cell_render h1,\ndiv.rendered_html h1,\ndiv.text_cell_render h2,\ndiv.rendered_html h2,\ndiv.text_cell_render h3,\ndiv.rendered_html h3,\ndiv.text_cell_render h4,\ndiv.rendered_html h4,\ndiv.text_cell_render h5,\ndiv.rendered_html h5 {\n font-family: \"Exo_2\", sans-serif;\n}\n.rendered_html h1:first-child,\n.rendered_html h2:first-child,\n.rendered_html h3:first-child,\n.rendered_html h4:first-child,\n.rendered_html h5:first-child,\n.rendered_html h6:first-child {\n margin-top: 0.2em;\n}\n.rendered_html h1,\n.text_cell_render h1 {\n color: #126dce;\n font-size: 220%;\n text-align: center;\n font-weight: lighter;\n}\n.rendered_html h2,\n.text_cell_render h2 {\n text-align: left;\n font-size: 170%;\n color: #126dce;\n font-style: normal;\n font-weight: lighter;\n}\n.rendered_html h3,\n.text_cell_render h3 {\n font-size: 150%;\n color: #126dce;\n font-weight: lighter;\n text-decoration: italic;\n font-style: normal;\n}\n.rendered_html h4,\n.text_cell_render h4 {\n font-size: 120%;\n color: #126dce;\n font-weight: underline;\n font-style: normal;\n}\n.rendered_html h5,\n.text_cell_render h5 {\n font-size: 100%;\n color: #2f2f2f;\n font-weight: lighter;\n text-decoration: underline;\n}\n.rendered_html table,\n.rendered_html tr,\n.rendered_html td {\n font-family: \"Fira Code\", monospace;\n font-size: 10.0pt !important;\n line-height: 150% !important;\n border: 1px solid #d6d6d6;\n color: #353535;\n background-color: #ffffff;\n background: #ffffff;\n}\ntable.dataframe,\n.rendered_html tr,\n.dataframe * {\n font-family: \"Fira Code\", monospace;\n font-size: 10.0pt !important;\n border: 1px solid #d6d6d6;\n}\n.dataframe th,\n.rendered_html th {\n font-family: \"Exo_2\", sans-serif;\n font-size: 11pt !important;\n font-weight: bold;\n border: 1px solid #c4c4c4;\n background: #eeeeee;\n}\n.dataframe td,\n.rendered_html td {\n font-family: \"Fira Code\", monospace;\n font-size: 10.0pt !important;\n color: #353535;\n background: #ffffff;\n border: 1px solid #d6d6d6;\n text-align: left;\n min-width: 4em;\n}\n.dataframe-summary-row tr:last-child,\n.dataframe-summary-col td:last-child {\n font-family: \"Exo_2\", sans-serif;\n font-size: 11pt !important;\n font-weight: bold;\n color: #353535;\n border: 1px solid #d6d6d6;\n background: #eeeeee;\n}\ndiv.widget-area {\n background-color: #ffffff;\n background: #ffffff;\n color: #303030;\n}\ndiv.widget-area a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n font-weight: normal;\n font-style: normal;\n color: #303030;\n text-shadow: none !important;\n}\ndiv.widget-area a:hover,\ndiv.widget-area a:focus {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n font-weight: normal;\n font-style: normal;\n color: #2f2f2f;\n background: rgba(180,180,180,.14);\n background-color: rgba(180,180,180,.14);\n border-color: transparent;\n background-image: none;\n text-shadow: none !important;\n}\ndiv.widget_item.btn-group > button.btn.btn-default.widget-combo-btn,\ndiv.widget_item.btn-group > button.btn.btn-default.widget-combo-btn:hover {\n background: #eeeeee;\n background-color: #eeeeee;\n border: 2px solid #eeeeee !important;\n font-size: inherit;\n z-index: 0;\n}\ndiv.jupyter-widgets.widget-hprogress.widget-hbox,\ndiv.widget-hbox,\n.widget-hbox {\n display: inline-table;\n}\ndiv.jupyter-widgets.widget-hprogress.widget-hbox .widget-label,\ndiv.widget-hbox .widget-label,\n.widget-hbox .widget-label {\n font-size: 11pt;\n min-width: 100%;\n padding-top: 5px;\n padding-right: 10px;\n text-align: left;\n vertical-align: text-top;\n}\n.progress {\n overflow: hidden;\n height: 20px;\n margin-bottom: 10px;\n padding-left: 10px;\n background-color: #c6c6c6;\n border-radius: 4px;\n -webkit-box-shadow: none;\n box-shadow: none;\n}\n.rendered_html :link {\n font-family: \"Exo_2\", sans-serif;\n font-size: 100%;\n color: #2c85f7;\n text-decoration: underline;\n}\n.rendered_html :visited,\n.rendered_html :visited:active,\n.rendered_html :visited:focus {\n color: #2e6eb2;\n}\n.rendered_html :visited:hover,\n.rendered_html :link:hover {\n font-family: \"Exo_2\", sans-serif;\n font-size: 100%;\n color: #eb6a18;\n}\na.anchor-link:link:hover {\n font-size: inherit;\n color: #eb6a18;\n}\na.anchor-link:link {\n font-size: inherit;\n text-decoration: none;\n padding: 0px 20px;\n visibility: none;\n color: #126dce;\n}\ndiv#nbextensions-configurator-container.container {\n width: 980px;\n margin-right: 0;\n margin-left: 0;\n}\ndiv.nbext-selector > nav > .nav > li > a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12pt;\n}\ndiv.nbext-readme > .nbext-readme-contents > .rendered_html {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12pt;\n line-height: 145%;\n padding: 1em 1em;\n color: #353535;\n background-color: #ffffff;\n -webkit-box-shadow: none;\n -moz-box-shadow: none;\n box-shadow: none;\n}\n.nbext-icon,\n.nbext-desc,\n.nbext-compat-div,\n.nbext-enable-btns,\n.nbext-params {\n margin-bottom: 8px;\n font-size: 12pt;\n}\ndiv.nbext-readme > .nbext-readme-contents {\n padding: 0;\n overflow-y: hidden;\n}\ndiv.nbext-readme > .nbext-readme-contents:not(:empty) {\n margin-top: 0.5em;\n margin-bottom: 2em;\n border: none;\n border-top-color: rgba(180,180,180,.30);\n}\n.nbext-showhide-incompat {\n padding-bottom: 0.5em;\n color: #4a4a4a;\n font-size: 12.0pt;\n}\n.shortcut_key,\nspan.shortcut_key {\n display: inline-block;\n width: 16ex;\n text-align: right;\n font-family: monospace;\n}\nmark,\n.mark {\n background-color: #ffffff;\n color: #353535;\n padding: .15em;\n}\na.text-warning,\na.text-warning:hover {\n color: #aaaaaa;\n}\na.text-warning.bg-warning {\n background-color: #ffffff;\n}\nspan.bg-success.text-success {\n background-color: transparent;\n color: #009e07;\n}\nspan.bg-danger.text-danger {\n background-color: #ffffff;\n color: #de143d;\n}\n.has-success .input-group-addon {\n color: #009e07;\n border-color: transparent;\n background: inherit;\n background-color: rgba(83,180,115,.10);\n}\n.has-success .form-control {\n border-color: #009e07;\n -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.025);\n box-shadow: inset 0 1px 1px rgba(0,0,0,0.025);\n}\n.has-error .input-group-addon {\n color: #de143d;\n border-color: transparent;\n background: inherit;\n background-color: rgba(192,57,67,.10);\n}\n.has-error .form-control {\n border-color: #de143d;\n -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.025);\n box-shadow: inset 0 1px 1px rgba(0,0,0,0.025);\n}\n.kse-input-group-pretty > kbd {\n font-family: \"Droid Sans Mono\", monospace;\n color: #303030;\n font-weight: normal;\n background: transparent;\n}\n.kse-input-group-pretty > kbd {\n font-family: \"Droid Sans Mono\", monospace;\n color: #303030;\n font-weight: normal;\n background: transparent;\n}\ndiv.nbext-enable-btns .btn[disabled],\ndiv.nbext-enable-btns .btn[disabled]:hover,\n.btn-default.disabled,\n.btn-default[disabled] {\n background: #e8e8e8;\n background-color: #e8e8e8;\n color: #282828;\n}\nlabel#Keyword-Filter {\n display: none;\n}\n.nav-pills > li.active > a,\n.nav-pills > li.active > a:hover,\n.nav-pills > li.active > a:focus {\n color: #ffffff;\n background-color: #126dce;\n}\n.input-group .nbext-list-btn-add,\n.input-group-btn:last-child > .btn-group > .btn {\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: #eeeeee;\n}\n.input-group .nbext-list-btn-add:hover,\n.input-group-btn:last-child > .btn-group > .btn:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border-color: #e9e9e9;\n}\n#notebook-container > div.cell.code_cell.rendered.selected > div.widget-area > div.widget-subarea > div > div.widget_item.btn-group > button.btn.btn-default.dropdown-toggle.widget-combo-carrot-btn {\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: #eeeeee;\n}\n#notebook-container > div.cell.code_cell.rendered.selected > div.widget-area > div.widget-subarea > div > div.widget_item.btn-group > button.btn.btn-default.dropdown-toggle.widget-combo-carrot-btn:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border-color: #e9e9e9;\n}\ninput.raw_input {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt !important;\n color: #303030;\n background-color: #efefef;\n border-color: #ececec;\n background: #ececec;\n width: auto;\n vertical-align: baseline;\n padding: 0em 0.25em;\n margin: 0em 0.25em;\n -webkit-box-shadow: none;\n box-shadow: none;\n}\naudio,\nvideo {\n display: inline;\n vertical-align: middle;\n align-content: center;\n margin-left: 20%;\n}\n.cmd-palette .modal-body {\n padding: 0px;\n margin: 0px;\n}\n.cmd-palette form {\n background: #eeeeee;\n background-color: #eeeeee;\n}\n.typeahead-field input:last-child,\n.typeahead-hint {\n background: #eeeeee;\n background-color: #eeeeee;\n z-index: 1;\n}\n.typeahead-field input {\n font-family: \"Exo_2\", sans-serif;\n color: #303030;\n border: none;\n font-size: 28pt;\n display: inline-block;\n line-height: inherit;\n padding: 3px 10px;\n height: 70px;\n}\n.typeahead-select {\n background-color: #eeeeee;\n}\nbody > div.modal.cmd-palette.typeahead-field {\n display: table;\n border-collapse: separate;\n background-color: #f7f7f7;\n}\n.typeahead-container button {\n font-family: \"Exo_2\", sans-serif;\n font-size: 28pt;\n background-color: #d0d0d0;\n border: none;\n display: inline-block;\n line-height: inherit;\n padding: 3px 10px;\n height: 70px;\n}\n.typeahead-search-icon {\n min-width: 40px;\n min-height: 55px;\n display: block;\n vertical-align: middle;\n text-align: center;\n}\n.typeahead-container button:focus,\n.typeahead-container button:hover {\n color: #2f2f2f;\n background-color: #ff7823;\n border-color: #ff7823;\n}\n.typeahead-list > li.typeahead-group.active > a,\n.typeahead-list > li.typeahead-group > a,\n.typeahead-list > li.typeahead-group > a:focus,\n.typeahead-list > li.typeahead-group > a:hover {\n display: none;\n}\n.typeahead-dropdown > li > a,\n.typeahead-list > li > a {\n color: #303030;\n text-decoration: none;\n}\n.typeahead-dropdown,\n.typeahead-list {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n color: #303030;\n background-color: #ffffff;\n border: none;\n background-clip: padding-box;\n margin-top: 0px;\n padding: 3px 2px 3px 0px;\n line-height: 1.7;\n}\n.typeahead-dropdown > li.active > a,\n.typeahead-dropdown > li > a:focus,\n.typeahead-dropdown > li > a:hover,\n.typeahead-list > li.active > a,\n.typeahead-list > li > a:focus,\n.typeahead-list > li > a:hover {\n color: #2f2f2f;\n background-color: #f7f7f7;\n border-color: #f7f7f7;\n}\n.command-shortcut:before {\n content: \"(command)\";\n padding-right: 3px;\n color: #aaaaaa;\n}\n.edit-shortcut:before {\n content: \"(edit)\";\n padding-right: 3px;\n color: #aaaaaa;\n}\nul.typeahead-list i {\n margin-left: 1px;\n width: 18px;\n margin-right: 10px;\n}\nul.typeahead-list {\n max-height: 50vh;\n overflow: auto;\n}\n.typeahead-list > li {\n position: relative;\n border: none;\n}\ndiv.input.typeahead-hint,\ninput.typeahead-hint,\nbody > div.modal.cmd-palette.in > div > div > div > form > div > div.typeahead-field > span.typeahead-query > input.typeahead-hint {\n color: #aaaaaa !important;\n background-color: transparent;\n padding: 3px 10px;\n}\n.typeahead-dropdown > li > a,\n.typeahead-list > li > a {\n display: block;\n padding: 5px;\n clear: both;\n font-weight: 400;\n line-height: 1.7;\n border: 1px solid #ffffff;\n border-bottom-color: rgba(180,180,180,.30);\n}\nbody > div.modal.cmd-palette.in > div {\n min-width: 750px;\n margin: 150px auto;\n}\n.typeahead-container strong {\n font-weight: bolder;\n color: #ff7823;\n}\n#find-and-replace #replace-preview .match,\n#find-and-replace #replace-preview .insert {\n color: #ffffff;\n background-color: #ff7823;\n border-color: #ff7823;\n border-style: solid;\n border-width: 1px;\n border-radius: 0px;\n}\n#find-and-replace #replace-preview .replace .match {\n background-color: #de143d;\n border-color: #de143d;\n border-radius: 0px;\n}\n#find-and-replace #replace-preview .replace .insert {\n background-color: #009e07;\n border-color: #009e07;\n border-radius: 0px;\n}\ndiv.CodeMirror,\ndiv.CodeMirror pre {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n line-height: 170%;\n color: #303030;\n}\ndiv.CodeMirror-lines {\n padding-bottom: .6em;\n padding-left: .5em;\n padding-right: 1.5em;\n padding-top: 4px;\n}\nspan.ansiblack {\n color: #dc4384;\n}\nspan.ansiblue {\n color: #009e07;\n}\nspan.ansigray {\n color: #ff7823;\n}\nspan.ansigreen {\n color: #333333;\n}\nspan.ansipurple {\n color: #653bc5;\n}\nspan.ansicyan {\n color: #055be0;\n}\nspan.ansiyellow {\n color: #ff7823;\n}\nspan.ansired {\n color: #de143d;\n}\ndiv.output-stderr {\n background-color: #ebb5b7;\n}\ndiv.output-stderr pre {\n color: #000000;\n}\ndiv.js-error {\n color: #de143d;\n}\n.ipython_tooltip {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n line-height: 170%;\n border: 2px solid #dadada;\n background: #eeeeee;\n background-color: #eeeeee;\n border-radius: 2px;\n overflow-x: visible;\n overflow-y: visible;\n box-shadow: none;\n position: absolute;\n z-index: 1000;\n}\n.ipython_tooltip .tooltiptext pre {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n line-height: 170%;\n background: #eeeeee;\n background-color: #eeeeee;\n color: #303030;\n overflow-x: visible;\n overflow-y: visible;\n max-width: 900px;\n}\ndiv#tooltip.ipython_tooltip {\n overflow-x: wrap;\n overflow-y: visible;\n max-width: 800px;\n}\ndiv.tooltiptext.bigtooltip {\n overflow-x: visible;\n overflow-y: scroll;\n height: 400px;\n max-width: 800px;\n}\n.cm-s-ipython.CodeMirror {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n background: #efefef;\n color: #303030;\n border-radius: 2px;\n font-style: normal;\n font-weight: normal;\n}\n.cm-s-ipython div.CodeMirror-selected {\n background: #e0e1e3;\n}\n.cm-s-ipython .CodeMirror-gutters {\n background: #e0e1e3;\n border: none;\n border-radius: 0px;\n}\n.cm-s-ipython .CodeMirror-linenumber {\n color: #aaaaaa;\n}\n.cm-s-ipython .CodeMirror-cursor {\n border-left: 2px solid #ff711a;\n}\n.cm-s-ipython span.cm-comment {\n color: #8d8d8d;\n font-style: italic;\n}\n.cm-s-ipython span.cm-atom {\n color: #055be0;\n}\n.cm-s-ipython span.cm-number {\n color: #ff8132;\n}\n.cm-s-ipython span.cm-property {\n color: #e22978;\n}\n.cm-s-ipython span.cm-attribute {\n color: #de143d;\n}\n.cm-s-ipython span.cm-keyword {\n color: #713bc5;\n font-weight: normal;\n}\n.cm-s-ipython span.cm-string {\n color: #009e07;\n}\n.cm-s-ipython span.cm-meta {\n color: #aa22ff;\n}\n.cm-s-ipython span.cm-operator {\n color: #055be0;\n}\n.cm-s-ipython span.cm-builtin {\n color: #e22978;\n}\n.cm-s-ipython span.cm-variable {\n color: #303030;\n}\n.cm-s-ipython span.cm-variable-2 {\n color: #de143d;\n}\n.cm-s-ipython span.cm-variable-3 {\n color: #aa22ff;\n}\n.cm-s-ipython span.cm-def {\n color: #e22978;\n font-weight: normal;\n}\n.cm-s-ipython span.cm-error {\n background: rgba(191,97,106,.40);\n}\n.cm-s-ipython span.cm-tag {\n color: #e22978;\n}\n.cm-s-ipython span.cm-link {\n color: #ff7823;\n}\n.cm-s-ipython span.cm-storage {\n color: #055be0;\n}\n.cm-s-ipython span.cm-entity {\n color: #e22978;\n}\n.cm-s-ipython span.cm-quote {\n color: #009e07;\n}\ndiv.CodeMirror span.CodeMirror-matchingbracket {\n color: #1c1c1c;\n background-color: rgba(30,112,199,.30);\n}\ndiv.CodeMirror span.CodeMirror-nonmatchingbracket {\n color: #1c1c1c;\n background: rgba(191,97,106,.40) !important;\n}\ndiv.cell.text_cell .cm-s-default .cm-header {\n color: #126dce;\n}\ndiv.cell.text_cell .cm-s-default span.cm-variable-2 {\n color: #353535;\n}\ndiv.cell.text_cell .cm-s-default span.cm-variable-3 {\n color: #aa22ff;\n}\n.cm-s-default span.cm-comment {\n color: #8d8d8d;\n}\n.cm-s-default .cm-tag {\n color: #009fb7;\n}\n.cm-s-default .cm-builtin {\n color: #e22978;\n}\n.cm-s-default .cm-string {\n color: #009e07;\n}\n.cm-s-default .cm-keyword {\n color: #713bc5;\n}\n.cm-s-default .cm-number {\n color: #ff8132;\n}\n.cm-s-default .cm-error {\n color: #055be0;\n}\n.CodeMirror-cursor {\n border-left: 2px solid #ff711a;\n border-right: none;\n width: 0;\n}\n.cm-s-default div.CodeMirror-selected {\n background: #e0e1e3;\n}\n.cm-s-default .cm-selected {\n background: #e0e1e3;\n}\ndiv#maintoolbar {\n display: none !important;\n}\n#header-container {\n display: none !important;\n}\n\n/**********************************\n MathJax Settings and Style Script\n**********************************/\n.MathJax_Display,\n.MathJax nobr>span.math>span {\n    border: 0 !important;\n    font-size: 110% !important;\n    text-align: center !important;\n    margin: 0em !important;\n}\n/* Prevents MathJax from jittering */\n/* cell position when cell is selected */\n.MathJax:focus, body :focus .MathJax {\n    display: inline-block !important;\n}\n\n\n\n </style>\n\n\n\n\n```python\n# 1. magic for inline plot\n# 2. magic to print version\n# 3. magic so that the notebook will reload external python modules\n# 4. a ipython magic to enable retina (high resolution) plots\n# https://gist.github.com/minrk/3301035\n%matplotlib inline\n%load_ext watermark\n%load_ext autoreload\n%autoreload 2\n%config InlineBackend.figure_format = 'retina'\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.datasets import load_iris\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\n\n%watermark -a 'Ethen' -d -t -v -p numpy,pandas,matplotlib,sklearn\n```\n\n    Ethen 2017-10-07 14:49:39 \n    \n    CPython 3.5.2\n    IPython 6.1.0\n    \n    numpy 1.13.3\n    pandas 0.20.3\n    matplotlib 2.0.0\n    sklearn 0.19.0\n\n\n# Dimensionality Reduction\n\nThe starting point most data analysis problems is to perform some sort of exploratory data analysis on our raw data. This step is important because until we have basic understanding of the structure of our raw data, it might be hard to know whether the data is suitable for the task at hand or even derive insights that we can later share. During this exploratoy process, unsupervised methods such as dimensionality reduction can help us identify simpler and more compact representations of the original raw data to either aid our understanding or provide useful input to other stages of analysis. Here, we'll be focusing on a specific dimensionality reduction technique called **Principal Component Analysis (PCA)**.\n\nImagine that we're trying to understand some underlying phenomenon, in order to do so we measure various quantities potentially related to it. If we knew exactly what to measure in advance, we might be able to find some simple relationships in our data. But we typically don't, so we often measure anything that might be relevant and end up having irrelevant or redundant signals in our measurement. To make this a bit more concrete, we'll generate a toy 2-dimensional dataset to work with using the equation below.\n\n$$x_2 = 500 + 20 \\times x_1 + \\epsilon$$\n\n\n```python\nnp.random.seed(123)\nx1 = np.arange(12, 56, 0.5)\ne  = np.random.normal(0, 100, x1.shape[0])\nx2 = 500 + 20 * x1 + e\nX = np.c_[x1, x2]\n\n# change default style figure and font size\nplt.style.use('fivethirtyeight')\nplt.rcParams['figure.figsize'] = 8, 6\nplt.rcParams['font.size'] = 12\n\ndef plot2var(m):\n    plt.scatter(m[:, 0], m[:, 1], s = 40, alpha = 0.8)\n    plt.xlabel('x1')\n    plt.ylabel('x2')\n\nplot2var(X)\n```\n\nWe can clearly see from the plot that there's linear relationship between the two variables, thus we probably don't need to include both of them as $x_1$ can be easily explained by $x_2$ and vice versa.\n\n## PCA\n\nIf it is the case that one of the features is considered redundant, we should be able to summarize the data with less characteristics (features). So, the way PCA tackles this problem is: Instead of simply picking out the useful features and discarding the others, it uses a linear combination of the existing features and constructs some new features that are good alternative representation of the original data. In our 2D toy dataset, PCA will try to pick the best single direction, or often referred to as **first principal components** in 2D, and project our points onto that single direction. So the next question becomes, out of the many possible lines in 2D, what line should we pick?\n\nIt turns out, there are two different answers to this question. First answer is that we are looking for some features that strongly differ across data points, thus, PCA looks for features that captures as much variation across data points as possible. The second answer is that we are looking for the features that would allow us to \"reconstruct\" the original features. Imagine that we come up with a feature that has no relation to the original ones; If we were to use this new feature, there is no way we can relate this to the original ones. So PCA looks for features that minimizes the reconstruction error. These two notions can be depicted in the graph below, where the black dots represents the original data point, the black line represents the projected line, the red dot on the left shows the points on the projected line and the red line on the right shows the reconstruction error.\n\n\n\nSurprisingly, it turns out that these two aims are equivalent and PCA can kill two birds with one stone. To see why minimizing squared residuals is equivalent to maximizing variance consider the 2 dimensions visualization below.\n\n\n\nConsider a datapoint $a_i$. The contribution of this specific data point to the total variance is $a_i^Ta_i$, or equivalently the squared Euclidean length $\\lVert \\mathbf{a}_i \\lVert^2$. Applying the Pythagorean theorem shows that this total variance equals the sum of variance lost (the squared residual) and variance remaining. Thus, it is equivalent to either maximize remaining variance or minimize lost variance to find the principal components.\n\nBefore we go another deeper, let's build some intuition using the scikit-learn library. The following section standardizes the data, fits the PCA model and prints out some of the important informations.\n\n\n```python\n# we start by standardizing our dataset\nX_std = StandardScaler().fit_transform(X)\n\n# call PCA specifying we only want the\n# first two principal components (since\n# we only have a 2d datset)\npca = PCA(n_components = 2)\npca.fit(X_std)\n\n# important information\nprint('Components:\\n ', pca.components_)\nprint('Explained Variance Ratio:\\n ', pca.explained_variance_ratio_)\n```\n\n    Components:\n      [[-0.70710678 -0.70710678]\n     [ 0.70710678 -0.70710678]]\n    Explained Variance Ratio:\n      [ 0.95588995  0.04411005]\n\n\nAfter fitting the PCA on the dataset, the fit learns some quantities from the data, most importantly the \"components\", which is the principal components (the new direction that our data points will be projected upon) and \"explained variance ratio\", which corresponds to the percentage of variance explained by each of the principal components. To get a better sense of what these numbers mean, let's visualize them over our standardized input data.\n\n\n```python\ndef draw_vector(v0, v1):\n    \"\"\"draw principal components as vectors\"\"\"\n    ax = plt.gca()\n    arrowprops = dict(arrowstyle = '->',\n                      linewidth = 2, edgecolor = 'black',\n                      shrinkA = 0, shrinkB = 0)\n    plt.annotate('', v1, v0, arrowprops = arrowprops)\n\n# plot data\nplt.scatter(X_std[:, 0], X_std[:, 1], s = 40, alpha = 0.8)\nfor length, vector in zip(pca.explained_variance_, pca.components_):\n    # the larger the explained variance, the longer the\n    # annotated line will be\n    v = vector * 2 * np.sqrt(length)\n    draw_vector(pca.mean_, pca.mean_ + v)\n\nplt.axis('equal')\nplt.show()\n```\n\nFrom the plot, we see that our PCA model gives us two principal components (the black line) and the length of the lines indicate of how important that principal component is in describing the variation of the original data. So if we were to choose 1 principal component to summarize our 2d dataset, it will be line that has the longest length (largest explained variance ratio). There're two things worth noting:\n\n- The number of principal components matches the total number of features\n- The first and second principal components are orthogonal to each other\n\nThe reason for this is that principal components transform the data into a new set of dimensions, and these new dimensions have to be equal to the original amount of dimensions. And just like the original $x$, $y$ axis that we're used to, they have to be orthogonal to each other. Let's now reduce the dimension of our 2d dataset into 1d by transforming our data onto the most important principal component and plot it along with the original data.\n\n\n```python\n# dimensionality reduction, keeping only\n# the first principal component\npca = PCA(n_components = 1)\nX_pca = pca.fit_transform(X_std)\nprint(\"original shape:   \", X.shape)\nprint(\"transformed shape:\", X_pca.shape)\n\n# inverse transform to obtain the projected data\n# and compare with the original\nX_new = pca.inverse_transform(X_pca)\nplt.scatter(X_std[:, 0], X_std[:, 1], s = 40, alpha = 0.2)\nplt.scatter(X_new[:, 0], X_new[:, 1], s = 40, alpha = 0.8)\nplt.show()\n```\n\nIn the plot above, the lighter points are the original data and the darker points are the projected version. Looking at the projections we see that the points projected onto the first principal component all seem close to their initial representations and at the same time, it also captures most of the variations in our original data points.\n\nHopefully, this elucidate what a PCA dimensionality reduction is doing. In a nutshell, PCA aims to find the directions or so called the principal components of maximum variance in high-dimensional data and project it onto a smaller dimensional subspace while retaining most of the information. In our 2d example, the linear relationship between $x_1$ and $x_2$ is mostly preserved using only 1 feature instead of 2.\n\n## PCA From Scratch\n\nNow that we have a high level understanding of what PCA is accomplishing, let's now formalize this with some notations. Recall that PCA is trying the find the direction such that the projection of the data on it has the highest variance. So given $X$, the centered data matrix, the projection, $Xw$ (dot product between the data point, $X$ and the projection weight, $w$), its variance can be computed as follows:\n\n\\begin{align}\n\\frac{1}{n-1}(\\mathbf{Xw})^\\top \\mathbf{Xw} = \\mathbf w^\\top (\\frac{1}{n-1}\\mathbf X^\\top\\mathbf X) \\mathbf w = \\mathbf w^\\top \\mathbf{Cw}\n\\end{align}\n\nWhere $\\mathbf{C}$ is the covariance matrix of the data $\\mathbf{X}$. In case this looks unfamiliar, the covariance matrix is a $d \\times d$ matrix ($d$ is the total number of dimensions, features) where each element represents the covariance between two features. The covariance between two features $x_j$ and $x_k$ is calculated as follows:\n\n\\begin{align}\n\\sigma_{jk} = \\frac{1}{n-1} \\sum_{i=1}^{n} \\left( x_{ij} - \\bar{x}_j \\right) \\left( x_{ik} - \\bar{x}_k \\right)\n\\end{align}\n\nWhere $\\bar{x}_j$ is simply the mean of vector (feature) $\\bar{x}_j = \\sum \\limits_{i=1}^n x_{ij}$.\n\nWe can also express the calculation of the covariance matrix via the following matrix equation: \n\n\\begin{align}\n\\mathbf{C} = \\frac{1}{n-1} \\big( (X - \\bar{x})^\\top( X - \\bar{x}) \\big)\n\\end{align}\n\nBecause we already assume to data point $X$ has been centered, thus the $X - \\bar{x}$ part can be simplified into just $X$. And the formula above simply becomes:\n\n\\begin{align}\n\\mathbf{C} = \\frac{1}{n-1} X^\\top X\n\\end{align}\n\nNext, apart from the original objective function $\\mathbf w^\\top \\mathbf{Cw}$, we also introduce an additional constraint $\\|\\mathbf w\\|=\\mathbf w^\\top \\mathbf w=1$, saying our weight vector should have unit length. The intuition behind this is that: If we were to simply maximize the formula $\\mathbf w^\\top \\mathbf{Cw}$, we can multiply $w$ by any number and the objective function will increase by the square of this number. So the problem becomes ill-defined since the maximum of this expression is infinite. Given these two pieces of information, our objective function for PCA becomes:\n\n\\begin{align}\n&  \\underset{\\mathbf{w}}{\\text{maximize}}\n&& \\mathbf w^\\top \\mathbf{Cw} \\nonumber \\\\\n&  \\text{subject to}\n&& \\mathbf w^\\top \\mathbf w=1\n\\end{align}\n\nThis objective function can be solved by the Lagrange multiplier, minimizing the loss function:\n\n\\begin{align}\nL &= \\mathbf w^\\top \\mathbf{Cw}-\\lambda(\\mathbf w^\\top \\mathbf w-1)\n\\end{align}\n\nIf this looks unfamiliar, check out the following tutorial on Lagrange multiplier. [Khan Academy: Lagrange multipliers, examples](https://www.khanacademy.org/math/multivariable-calculus/applications-of-multivariable-derivatives/constrained-optimization/a/lagrange-multipliers-examples). Next, to solve for $w$, we set the partial derivative of $L$ with respect to $w$ to 0.\n\n\\begin{align}\n\\frac{\\partial L}{\\partial \\mathbf w} \n& \\implies \\mathbf{Cw} - \\lambda \\mathbf w = 0 \\\\\n& \\implies \\mathbf{Cw} = \\lambda \\mathbf w\n\\end{align}\n\nHopefully the formula above looks familar, since it's essentially an eigendecomposition problem. The notion of eigendecomposition is basically trying to solve the equation:\n\n\\begin{align}\nAx &= \\lambda x\n\\end{align}\n\nIn our case, $A$ is our covariance matrix correponding to $\\mathbf C$; $x$ is our eigenvector, correponding to $\\mathbf w$ and $\\lambda$ is our eigenvalue correponding to explained variance. After solving the equation above, we'll obtain eigenvector and eigenvalue pairs, where very eigenvector has a corresponding eigenvalue. An eigenvector is essentially the direction of each principal component and the eigenvalue is a number, telling us how much variance there is in the data in that direction, in other words, how spread out the data is on the line. For those interested, the following blog walks through the calculating eigenvalue and eigenvectors from scratch. [Blog: What are eigenvectors and eigenvalues?](http://www.visiondummy.com/2014/03/eigenvalues-eigenvectors/)\n\nGiven all of that, let's see how this works in code. Just to summarize, the general framework for computing PCA is as follows:\n\n- Standardize the data\n- Obtain the Eigenvectors and Eigenvalues from the covariance matrix\n- Sort eigenvalues in descending order and choose the $k$ eigenvectors that correspond to the $k$ largest eigenvalues where $k$ is the number of dimensions of the new feature subspace\n- Projection onto the new feature space. During this step we will take the top $k$ eigenvectors and use it to transform the original dataset $X$ to obtain a k-dimensional feature subspace $X'$\n\nFor the section below, we will be working with the famous \"Iris\" dataset. The iris dataset is a 150\u00d74 matrix where the columns are the different features (sepal length in cm, sepal width in cm, petal length in cm, petal width in cm) and every every row represents a separate flower sample. The three classes in the Iris dataset are: Iris-setosa (n=50), Iris-versicolor (n=50), Iris-virginica (n=50). We'll use histograms to get a feeling of how the 3 different flower classes are distributes along the 4 different features.\n\n\n```python\niris = load_iris()\nX = iris['data']\ny = iris['target']\n\nlabel_dict = {0: 'Iris-Setosa',\n              1: 'Iris-Versicolor',\n              2: 'Iris-Virgnica'}\n\nfeature_dict = {0: 'sepal length [cm]',\n                1: 'sepal width [cm]',\n                2: 'petal length [cm]',\n                3: 'petal width [cm]'}\n\nfig = plt.figure(figsize = (10, 6))\nfor feature in range(len(feature_dict)):\n    plt.subplot(2, 2, feature + 1)\n    for index, label in label_dict.items():\n        plt.hist(X[y == index, feature], label = label,\n                 bins = 10, alpha = 0.3)\n        plt.xlabel(feature_dict[feature])\n        \nplt.legend(loc = 'upper right', fancybox = True, fontsize = 12)\nplt.tight_layout()\nplt.show()\n```\n\n### Standardize\n\nIn general, it's important to standardize the data prior to a PCA on the covariance matrix depends on the measurement scales of the original features. Since PCA yields a feature subspace that maximizes the variance along the axes, it makes sense to standardize the data, especially if it was measured on different scales so different features will have equal contribution in terms of their scales.\n\n\n```python\n# subtract the mean and divide the\n# standard deviation of each features\nmean = np.mean(X, axis = 0)\nscale = np.std(X, axis = 0)\nX_std = (X - mean) / scale\n```\n\n### Eigendecomposition - Computing Eigenvectors and Eigenvalues\n\nThe eigenvectors and eigenvalues of a covariance matrix is the core of PCA: The eigenvectors (principal components) determine the directions of the new feature space, and the eigenvalues determine their magnitude (variance explained along the principal components).\n\n\n```python\n# for those unfamiliar with the @ syntax it\n# is equivalent of .dot, the dot product\nvec_mean = np.mean(X_std, axis = 0)\nvec_diff = X_std - vec_mean\ncov_mat  = vec_diff.T @ vec_diff / (X_std.shape[0] - 1)\nprint('Covariance matrix \\n {}'.format(cov_mat))\n\n# note that since we already standardize the data,\n# meaning the mean vector for each features, vec_mean \n# will be 0 (really small numbers if you were to print them out),\n# hence we don't have to substract the mean to standardize them\ncov_mat = X_std.T @ X_std / (X_std.shape[0] - 1)\nprint('Covariance matrix \\n {}'.format(cov_mat))\n\n# equivalently, we could have used the np.cov function:\n# since each row represents a variable for np.cov,\n# we'll need to transpose the matrix\nprint('NumPy covariance matrix: \\n {}'.format(np.cov(X_std.T)))\n```\n\n    Covariance matrix \n     [[ 1.00671141 -0.11010327  0.87760486  0.82344326]\n     [-0.11010327  1.00671141 -0.42333835 -0.358937  ]\n     [ 0.87760486 -0.42333835  1.00671141  0.96921855]\n     [ 0.82344326 -0.358937    0.96921855  1.00671141]]\n    Covariance matrix \n     [[ 1.00671141 -0.11010327  0.87760486  0.82344326]\n     [-0.11010327  1.00671141 -0.42333835 -0.358937  ]\n     [ 0.87760486 -0.42333835  1.00671141  0.96921855]\n     [ 0.82344326 -0.358937    0.96921855  1.00671141]]\n    NumPy covariance matrix: \n     [[ 1.00671141 -0.11010327  0.87760486  0.82344326]\n     [-0.11010327  1.00671141 -0.42333835 -0.358937  ]\n     [ 0.87760486 -0.42333835  1.00671141  0.96921855]\n     [ 0.82344326 -0.358937    0.96921855  1.00671141]]\n\n\nAfter obtaining the covariance matrix, we perform an eigendecomposition on it to obtain the eigenvalues and eigenvectors.\n\n\n```python\n# since computing this by hand can be quite tedious\n# we'll simply use the pre-implemented function\neig_vals, eig_vecs = np.linalg.eig(cov_mat)\nprint('Eigenvectors \\n%s' % eig_vecs)\nprint('\\nEigenvalues \\n%s' % eig_vals)\n```\n\n    Eigenvectors \n    [[ 0.52237162 -0.37231836 -0.72101681  0.26199559]\n     [-0.26335492 -0.92555649  0.24203288 -0.12413481]\n     [ 0.58125401 -0.02109478  0.14089226 -0.80115427]\n     [ 0.56561105 -0.06541577  0.6338014   0.52354627]]\n    \n    Eigenvalues \n    [ 2.93035378  0.92740362  0.14834223  0.02074601]\n\n\n### Choosing Top K Eigenvectors\n\nRecall that the typical goal of a PCA is to reduce the dimensionality of the original feature space by projecting it onto a smaller subspace. In order to decide which eigenvector(s) can dropped without losing too much information for the construction of lower-dimensional subspace, we need to inspect the corresponding eigenvalues. The idea is: eigenvectors with the lowest eigenvalues bear the least information about the distribution of the data and those are the ones can be dropped. In order to do so, the common approach is to rank the eigenvalues from highest to lowest in order choose the top $k$ eigenvectors.\n\nAfter sorting the eigenpairs, the next question is \"how many principal components are we going to choose for our new feature subspace?\" A useful measure is the so-called \u201cexplained variance,\u201d which can be calculated from the eigenvalues. The explained variance tells us how much extra information (variance) does each of the principal components contribute.\n\n\n```python\neig_vals_total = np.sum(eig_vals)\nvar_exp = eig_vals / eig_vals_total\ncum_var_exp = np.cumsum(var_exp)\nprint('Variance Explained: ', var_exp)\nprint('Cumulative Variance Explained: ', cum_var_exp)\n\nplt.bar(range(var_exp.shape[0]), var_exp, alpha = 0.5, \n        align = 'center', label = 'individual explained variance')\nplt.step(range(var_exp.shape[0]), cum_var_exp, \n         where = 'mid', label = 'cumulative explained variance')\nplt.ylabel('Explained variance ratio')\nplt.xlabel('Principal components')\nplt.ylim(0, 1.1)\nplt.legend(loc = 'best')\nplt.tight_layout()\n```\n\nThe plot above clearly shows that most of the variance (72.77% of the variance to be precise) can be explained by the first principal component alone. The second principal component still bears some information (23.03%) while the third and fourth principal components can safely be dropped without losing to much information. Together, the first two principal components explains 95.8% of the variance. Or in other words, it contain 95.8% of the information (95% or 99% are comon threshold that people use).\n\n### Projection Onto the New Feature Space\n\nIn the last step, we will use the 4\u00d72-dimensional eigenvectors to transform our samples onto the new subspace via the equation $Y=XW$, where Y will be our 150\u00d72 matrix of transformed samples (we reduce the dimension from the original 4 down to 2).\n\n\n```python\ndef plot_iris_pca(X_pca, y):\n    \"\"\"a scatter plot of the 2-dimensional iris data\"\"\"\n    markers = 's', 'x', 'o'\n    colors = list(plt.rcParams['axes.prop_cycle'])\n    target = np.unique(y)\n    for idx, (t, m) in enumerate( zip(target, markers) ):\n        subset = X_pca[y == t]\n        plt.scatter(subset[:, 0], subset[:, 1], s = 50,\n                    c = colors[idx]['color'], label = t, marker = m)\n\n    plt.xlabel('PC 1')\n    plt.ylabel('PC 2')\n    plt.legend(loc = 'lower left')\n    plt.tight_layout()\n    plt.show()\n```\n\n\n```python\nX_std_pca = X_std.dot(eig_vecs[:, 0:2])\nplot_iris_pca(X_std_pca, y)\n```\n\nWe'll put all of this into a single class, train it and confirm the result with scikit-learn's PCA model by printing out the explained variance ratio.\n\n\n```python\nclass PCAModel:\n    \"\"\"\n    Principal component analysis (PCA)\n    \n    Parameters\n    ----------\n    n_components : int\n        top number of principal components to keep\n    \"\"\"\n\n    def __init__(self, n_components):\n        self.n_components = n_components\n\n    def fit(self, X):\n        # standardize\n        X = X.copy()\n        self.mean = np.mean(X, axis = 0)\n        self.scale = np.std(X, axis = 0)\n        X = (X - self.mean) / self.scale\n        \n        # eigendecomposition\n        eig_vals, eig_vecs = np.linalg.eig(np.cov(X.T))\n        self.components = eig_vecs[:, :self.n_components]\n        var_exp = eig_vals / np.sum(eig_vals)\n        self.explained_variance_ratio = var_exp[:self.n_components]\n        return self\n\n    def transform(self, X):\n        X = X.copy()\n        X = (X - self.mean) / self.scale\n        X_pca = X @ self.components\n        return X_pca\n```\n\n\n```python\n# implementation from scratch\npca_model = PCAModel(n_components = 2).fit(X)\n\n# using library to confirm results\nscaler = StandardScaler()\nX_std = scaler.fit_transform(X)\npca = PCA(n_components = 2).fit(X_std)\n\n# print explained ratio to see if the matches\nprint('library: ', pca.explained_variance_ratio_)\nprint('from scratch: ', pca_model.explained_variance_ratio)\n```\n\n    library:  [ 0.72770452  0.23030523]\n    from scratch:  [ 0.72770452  0.23030523]\n\n\n## Takeaway\n\nLet's wrap this up with a summary of PCA and some of its applications. In order to identify patterns in our data, we often look for variation across observations to distinguish them from one another. Hence it seems reasonable to be able to find a succinct representation that best captures the variation in our initial data. PCA, in particular, look to explain our data via its maximum directions of variance. By compressing a higher dimensional dataset into lower one, while still retaining most of the variance this allows us to:\n\n- Perform Visualization: PCA summarizes our data along the principal components (or eigenvectors), which explains most the variance. Thus we can reduce the dataset to 2 or 3 dimensions and visualize our data's distribution. This can be helpful when we're performing clustering algorithm that needs to choose the cluster number beforehand.\n- Speed up machine learning algorithms: When dealing with Big Data, we might want to decompose the features into a lower dimension, without a significant loss in variance. By performing dimensionality reduction methods, we can reduce the amount of features we have to speed up the training algorithm and save memory. For this part, we'll use the Iris dataset again and show that by keeping the data's top 3 principal components we can obtain the same level of accuracy as keeping all 4 features.\n\n\n```python\n# split 30% of the iris data into a test set for evaluation\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, \n                                                    random_state = 1)\n\n# create the pipeline, where we'll\n# standardize the data, perform PCA and\n# fit the logistic regression\npipe1 = Pipeline([\n    ('standardize', StandardScaler()),\n    ('pca', PCA(n_components = 3)),\n    ('logistic', LogisticRegression(random_state = 1))\n])\npipe1.fit(X_train, y_train)\ny_pred1 = pipe1.predict(X_test)\n\n# pipeline without PCA\npipe2 = Pipeline([\n    ('standardize', StandardScaler()),\n    ('logistic', LogisticRegression(random_state = 1))\n])\npipe2.fit(X_train, y_train)\ny_pred2 = pipe2.predict(X_test)\n\n# access the prediction accuracy\nprint('PCA Accuracy %.3f' % accuracy_score(y_test, y_pred1))\nprint('Accuracy %.3f' % accuracy_score(y_test, y_pred2))\n```\n\n    PCA Accuracy 0.822\n    Accuracy 0.822\n\n\n# Reference\n\n- [Youtube: Dimensionality Reduction](https://www.youtube.com/playlist?list=PLnnr1O8OWc6aVexn2BY0qjklobY6TUEIy)\n- [Blog: What are eigenvectors and eigenvalues?](http://www.visiondummy.com/2014/03/eigenvalues-eigenvectors/)\n- [Blog: Principal Component Analysis 4 Dummies](https://georgemdallas.wordpress.com/2013/10/30/principal-component-analysis-4-dummies-eigenvectors-eigenvalues-and-dimension-reduction/)\n- [Blog: Everything you did and didn't know about PCA](http://alexhwilliams.info/itsneuronalblog/2016/03/27/pca/)\n- [Blog: Principal Component Analysis in 3 Simple Steps](http://sebastianraschka.com/Articles/2015_pca_in_3_steps.html)\n- [Notebook: In Depth: Principal Component Analysis](http://nbviewer.jupyter.org/github/jakevdp/PythonDataScienceHandbook/blob/95664b978439df948b2cd2f5f5b4e31f28b30394/notebooks/05.09-Principal-Component-Analysis.ipynb)\n- [StackExchange: Making sense of principal component analysis, eigenvectors & eigenvalues](http://stats.stackexchange.com/questions/2691/making-sense-of-principal-component-analysis-eigenvectors-eigenvalues)\n- [StackExchange: What is an intuitive explanation for how PCA turns from a geometric problem (with distances) to a linear algebra problem (with eigenvectors)?](http://stats.stackexchange.com/questions/217995/what-is-an-intuitive-explanation-for-how-pca-turns-from-a-geometric-problem-wit)\n", "meta": {"hexsha": "1eca626c43da5f3932ca153d9fd76d80c7cb3092", "size": 477568, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "dim_reduct/PCA.ipynb", "max_stars_repo_name": "DEVESHTARASIA/machine-learning", "max_stars_repo_head_hexsha": "ca8a3a108829dca2b883f9196b8dfbb7c280861d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dim_reduct/PCA.ipynb", "max_issues_repo_name": "DEVESHTARASIA/machine-learning", "max_issues_repo_head_hexsha": "ca8a3a108829dca2b883f9196b8dfbb7c280861d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dim_reduct/PCA.ipynb", "max_forks_repo_name": "DEVESHTARASIA/machine-learning", "max_forks_repo_head_hexsha": "ca8a3a108829dca2b883f9196b8dfbb7c280861d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 171.7870503597, "max_line_length": 78894, "alphanum_fraction": 0.8654139306, "converted": true, "num_tokens": 19153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03904829048965015, "lm_q2_score": 0.029760093300570407, "lm_q1q2_score": 0.0011620807681997647}}
{"text": "```python\nfrom jupyterthemes import get_themes\nfrom jupyterthemes.stylefx import set_nb_theme\nthemes = get_themes()\nset_nb_theme(themes[1])\n```\n\n\n\n\n<style> @font-face {\n font-family: 'Droid Sans Mono';\n font-weight: normal;\n font-style: normal;\n src: local('Droid Sans Mono'), url('fonts/droid-sans-mono.woff') format('woff');\n}\n@font-face {\n font-family: 'Exo_2';\n font-weight: normal;\n font-style: normal;\n src: local('Exo_2'), url('fonts/exo-II-regular.ttf') format('truetype');\n}\n@font-face {\n font-family: 'Fira Code';\n font-weight: normal;\n font-style: normal;\n src: local('Fira Code'), url('fonts/firacode.otf') format('opentype');\n}\n@font-face {\n font-family: 'Lora';\n font-weight: normal;\n font-style: normal;\n src: local('Lora'), url('fonts/Lora-Regular.ttf') format('truetype');\n}\ndiv#notebook {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n line-height: 170%;\n color: #303030;\n}\nbody,\ndiv.body {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n color: #303030;\n background-color: #ffffff;\n background: #ffffff;\n}\nbody.notebook_app {\n padding: 0;\n background-color: #ffffff;\n background: #ffffff;\n padding-right: 0px !important;\n overflow-y: hidden;\n}\na {\n font-family: \"Exo_2\", sans-serif;\n color: #303030;\n}\na:hover,\na:focus {\n color: #2f2f2f;\n}\n.list_header,\ndiv#notebook_list_header.row.list_header {\n font-size: 14pt;\n color: #2f2f2f;\n background-color: #ffffff;\n}\ndiv#cluster_list_header.row.list_header,\ndiv#running .row.list_header {\n font-size: 14pt;\n color: #303030;\n background: #eeeeee;\n background-color: #eeeeee;\n border-bottom: 2px solid rgba(180,180,180,.30);\n}\ndiv#cluster_list > div.list_item.row,\ndiv#cluster_list > div.list_item.row:hover {\n background: #f7f7f7;\n background-color: #f7f7f7;\n}\ndiv#clusters.tab-pane.active {\n font-size: 12.0pt;\n padding: 4px 0 4px 0;\n}\n#running .panel-group .panel .panel-heading {\n font-size: 14pt;\n color: #303030;\n padding: 8px 8px;\n background: #eeeeee;\n background-color: #eeeeee;\n}\n#running .panel-group .panel .panel-heading a {\n font-size: 14pt;\n color: #303030;\n}\n#running .panel-group .panel .panel-heading a:focus,\n#running .panel-group .panel .panel-heading a:hover {\n font-size: 14pt;\n color: #303030;\n}\n#running .panel-group .panel .panel-body .list_container .list_item {\n background: #f7f7f7;\n background-color: #f7f7f7;\n padding: 2px;\n border-bottom: 2px solid rgba(180,180,180,.30);\n}\n#running .panel-group .panel .panel-body .list_container .list_item:hover {\n background: #f7f7f7;\n background-color: #f7f7f7;\n}\n#running .panel-group .panel .panel-body {\n padding: 2px;\n}\ndiv.running_list_info.toolbar_info {\n font-size: 12.0pt;\n padding: 4px 0 4px 0;\n height: inherit;\n line-height: inherit;\n text-shadow: none;\n}\n.list_placeholder {\n font-weight: normal;\n}\n#tree-selector {\n padding: 0px;\n}\n#project_name > ul > li > a > i.fa.fa-home {\n color: #ff7823;\n font-size: 17pt;\n display: inline-block;\n position: static;\n padding: 0px 0px;\n font-weight: normal;\n text-align: center;\n vertical-align: text-top;\n}\n#project_name {\n display: inline-flex;\n padding-left: 7px;\n margin-left: -2px;\n margin-bottom: -20px;\n text-align: -webkit-auto;\n vertical-align: text-top;\n}\ndiv#notebook_toolbar div.dynamic-instructions {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n}\n.toolbar_info {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n color: #303030;\n text-shadow: none;\n border: none;\n height: inherit;\n line-height: inherit;\n}\n.list_container {\n font-size: 12.0pt;\n color: #303030;\n border: none;\n text-shadow: none !important;\n}\n.list_container > div {\n border-bottom: 1px solid rgba(180,180,180,.14);\n font-size: 12.0pt;\n}\n.list_header > div,\n.list_item > div {\n padding-left: 0px;\n}\n.list_header > div input,\n.list_item > div input {\n top: 0px;\n}\n.list_header > div .item_link,\n.list_item > div .item_link {\n margin-left: -1px;\n vertical-align: middle;\n line-height: 22px;\n font-size: 12.0pt;\n}\n.item_icon {\n font-size: 12.0pt;\n vertical-align: middle;\n}\n.list_item input:not([type=\"checkbox\"]) {\n padding-right: 0px;\n height: auto;\n width: 20%;\n margin: 6px 0 0;\n margin-top: 1px;\n}\n#button-select-all {\n height: auto;\n font-size: 12.0pt;\n padding: 5px;\n min-width: 65px;\n z-index: 0;\n}\nbutton#tree-selector-btn {\n height: auto;\n font-size: 12.0pt;\n padding: 5px;\n}\ninput#select-all.pull-left.tree-selector {\n margin-left: 7px;\n margin-right: 2px;\n margin-top: 5px;\n}\ninput[type=\"radio\"],\ninput[type=\"checkbox\"] {\n margin: 6px 0 0;\n margin-top: 1px;\n line-height: normal;\n}\n.list_container a {\n font-size: 17px;\n color: #303030;\n border: none;\n text-shadow: none !important;\n font-weight: normal;\n font-style: normal;\n}\ndiv.list_container a:hover {\n color: #2f2f2f;\n}\ndiv.list_item:hover {\n background-color: #fafafa;\n}\n.breadcrumb > li {\n font-size: 12.0pt;\n color: #303030;\n border: none;\n text-shadow: none !important;\n}\nul#tabs a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n font-weight: normal;\n font-style: normal;\n border-color: transparent;\n text-shadow: none !important;\n}\n.nav-tabs {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n font-weight: normal;\n font-style: normal;\n background: #ffffff;\n text-shadow: none !important;\n border-color: transparent;\n border-bottom-color: rgba(180,180,180,.30);\n}\n.nav-tabs > li > a:hover {\n color: #2f2f2f;\n background-color: rgba(180,180,180,.14);\n}\n.nav-tabs > li > a:active,\n.nav-tabs > li > a:focus,\n.nav-tabs > li.active > a,\n.nav-tabs > li.active > a:focus,\n.nav-tabs > li.active > a:hover,\n.nav-tabs > li.active > a,\n.nav-tabs > li.active > a:hover,\n.nav-tabs > li.active > a:focus {\n color: #1c1c1c;\n background-color: #eeeeee;\n border: 1px solid transparent;\n border-bottom-color: transparent;\n cursor: default;\n}\n.nav > li > a:hover,\n.nav > li > a:focus {\n text-decoration: none;\n background-color: rgba(180,180,180,.14);\n}\n.nav > li.disabled > a,\n.nav > li.disabled > a:hover {\n color: #aaaaaa;\n}\ndiv#notebook {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n padding-top: 4px;\n}\n.notebook_app {\n background-color: #ffffff;\n}\n#notebook-container {\n padding: 13px;\n background-color: #ffffff;\n min-height: 0px;\n box-shadow: none;\n width: 980px;\n margin-right: auto;\n margin-left: auto;\n}\ndiv#ipython-main-app.container {\n width: 980px;\n margin-right: auto;\n margin-left: auto;\n margin-right: auto;\n margin-left: auto;\n}\n.container {\n width: 980px;\n margin-right: auto;\n margin-left: auto;\n}\n.notebook_app #header {\n box-shadow: none !important;\n background-color: #ffffff;\n border-bottom: 2px solid rgba(180,180,180,.14);\n}\n#header {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n box-shadow: none;\n background-color: #ffffff;\n}\n#header .header-bar {\n background: #ffffff;\n background-color: #ffffff;\n}\nbody > #header .header-bar {\n width: 100%;\n background: #ffffff;\n}\n#menubar {\n background-color: #ffffff;\n}\n#menubar .navbar,\n.navbar-default {\n background-color: #ffffff;\n margin-bottom: 0px;\n}\n.navbar {\n border: none;\n}\n.navbar-default {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n background-color: #ffffff;\n border-color: rgba(180,180,180,.14);\n line-height: 1.5em;\n padding-bottom: 0px;\n}\n.navbar-default .navbar-nav > li > a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n color: #303030;\n display: block;\n line-height: 1.5em;\n padding-top: 8px;\n padding-bottom: 6px;\n}\n.navbar-default .navbar-nav > li > a:hover,\n.navbar-default .navbar-nav > li > a:focus {\n color: #2f2f2f;\n background-color: rgba(180,180,180,.14);\n border-color: rgba(180,180,180,.14);\n line-height: 1.5em;\n}\n.navbar-default .navbar-nav > .open > a,\n.navbar-default .navbar-nav > .open > a:hover,\n.navbar-default .navbar-nav > .open > a:focus {\n color: #1c1c1c;\n background-color: rgba(180,180,180,.14);\n border-color: rgba(180,180,180,.14);\n line-height: 1.5em;\n}\n.edit_mode .modal_indicator:before {\n font-size: 13pt;\n color: #2c85f7;\n content: \"\\f040\";\n}\n.item_icon {\n color: #126dce;\n}\n.item_buttons .kernel-name {\n font-size: 13pt;\n color: #126dce;\n line-height: 22px;\n}\n.running_notebook_icon:before {\n color: #009e07 !important;\n}\n.item_buttons .running-indicator {\n padding-top: 2px;\n color: #009e07;\n}\n#modal_indicator {\n float: right !important;\n color: #126dce;\n background: #ffffff;\n background-color: #ffffff;\n}\n#kernel_indicator {\n float: right !important;\n color: #ff7823;\n background: #ffffff;\n background-color: #ffffff;\n font-size: 14.5pt;\n border-left: 2px solid #ff7823;\n padding-bottom: 2px;\n}\n#kernel_indicator .kernel_indicator_name {\n color: #ff7823;\n background: #ffffff;\n background-color: #ffffff;\n font-size: 14.5pt;\n padding-left: 5px;\n padding-right: 5px;\n}\ndiv.notification_widget.info,\n.notification_widget.info,\n.notification_widget:active:hover,\n.notification_widget.active:hover,\n.open > .dropdown-toggle.notification_widget:hover,\n.notification_widget:active:focus,\n.notification_widget.active:focus,\n.open > .dropdown-toggle.notification_widget:focus,\n.notification_widget:active.focus,\n.notification_widget.active.focus,\n.open > .dropdown-toggle.notification_widget.focus,\ndiv#notification_notebook.notification_widget.btn.btn-xs.navbar-btn,\ndiv#notification_notebook.notification_widget.btn.btn-xs.navbar-btn:hover,\ndiv#notification_notebook.notification_widget.btn.btn-xs.navbar-btn:focus {\n color: #126dce;\n background-color: #ffffff;\n border-color: #ffffff;\n}\n#notification_area,\ndiv.notification_area {\n float: right !important;\n position: static;\n}\n#kernel_logo_widget,\n#kernel_logo_widget .current_kernel_logo {\n display: none;\n}\ndiv#ipython_notebook {\n display: none;\n}\ni.fa.fa-icon {\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n text-rendering: auto;\n}\n.fa {\n display: inline-block;\n font: normal normal normal 12pt/1 \"FontAwesome\", \"Exo_2\", sans-serif;\n text-rendering: auto;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n.dropdown-menu {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n box-shadow: none;\n padding: 0px;\n text-align: left;\n border: 2px solid rgba(180,180,180,.30);\n background-color: #ffffff;\n background: #ffffff;\n line-height: 1.3;\n margin: 0px;\n}\n.dropdown-menu:hover {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n border: 2px solid rgba(180,180,180,.30);\n background-color: #ffffff;\n box-shadow: none;\n line-height: 1.3;\n}\n.dropdown-header {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n display: block;\n color: #ff7823;\n text-decoration: underline;\n white-space: nowrap;\n padding: 8px 0px 0px 6px;\n line-height: 1.3;\n}\n.dropdown-menu > li > a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n line-height: 1.3;\n display: block;\n padding: 10px 25px 10px 14px;\n color: #303030;\n background-color: #ffffff;\n background: #ffffff;\n}\n.dropdown-menu > li > a:hover {\n color: #2f2f2f;\n background-color: rgba(180,180,180,.14);\n background: rgba(180,180,180,.14);\n border-color: rgba(180,180,180,.14);\n}\n.dropdown-menu .divider {\n height: 2px;\n margin: 0px 0px;\n overflow: hidden;\n background-color: rgba(180,180,180,.30);\n}\n.dropdown-submenu > .dropdown-menu {\n top: 0;\n left: 100%;\n margin-top: -2px;\n margin-left: 0px;\n padding-top: 0px;\n}\n.dropdown-menu > .disabled > a,\n.dropdown-menu > .disabled > a:hover,\n.dropdown-menu > .disabled > a:focus {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n font-weight: normal;\n color: #aaaaaa;\n padding: none;\n display: block;\n clear: both;\n line-height: 1.2;\n white-space: nowrap;\n}\n.dropdown-submenu > a:after {\n color: #303030;\n margin-right: -16px;\n}\n.dropdown-submenu:hover > a:after,\n.dropdown-submenu:active > a:after,\n.dropdown-submenu:focus > a:after,\n.dropdown-submenu:visited > a:after {\n color: #ff7823;\n margin-right: -16px;\n}\ndiv.kse-dropdown > .dropdown-menu,\n.kse-dropdown > .dropdown-menu {\n min-width: 0;\n top: 94%;\n}\n.btn,\n.btn-default {\n font-family: \"Exo_2\", sans-serif;\n color: #303030;\n background: #ebebeb;\n background-color: #ebebeb;\n border: 2px solid #e8e8e8;\n font-weight: normal;\n box-shadow: none;\n text-shadow: none;\n border-radius: 2px;\n font-size: inherit;\n}\n.btn:hover,\n.btn:active:hover,\n.btn.active:hover,\n.btn-default:hover,\n.open > .dropdown-toggle.btn-default:hover,\n.open > .dropdown-toggle.btn:hover {\n color: #2f2f2f;\n background-color: #e4e4e4;\n background: #e4e4e4;\n border-color: #e4e4e4;\n background-image: none;\n box-shadow: none !important;\n border-radius: 2px;\n}\n.btn:active,\n.btn.active,\n.btn:active:focus,\n.btn.active:focus,\n.btn:active.focus,\n.btn.active.focus,\n.btn-default:focus,\n.btn-default.focus,\n.btn-default:active,\n.btn-default.active,\n.btn-default:active:hover,\n.btn-default.active:hover,\n.btn-default:active:focus,\n.btn-default.active:focus,\n.btn-default:active.focus,\n.btn-default.active.focus,\n.open > .dropdown-toggle.btn:focus,\n.open > .dropdown-toggle.btn.focus,\n.open > .dropdown-toggle.btn-default {\n color: #1c1c1c;\n background-color: #e4e4e4;\n background: #e4e4e4;\n border-color: #e4e4e4;\n background-image: none;\n box-shadow: none !important;\n border-radius: 2px;\n}\n.item_buttons > .btn,\n.item_buttons > .btn-group,\n.item_buttons > .input-group {\n margin-left: 5px;\n background: #eeeeee;\n background-color: #eeeeee;\n border: 2px solid #eeeeee;\n}\n.item_buttons > .btn:hover,\n.item_buttons > .btn-group:hover,\n.item_buttons > .input-group:hover {\n margin-left: 5px;\n background: #e9e9e9;\n background-color: #e9e9e9;\n border: 2px solid #e9e9e9;\n}\n.btn-group > .btn-mini,\n.btn-sm,\n.btn-group-sm > .btn,\n.btn-xs,\n.btn-group-xs > .btn,\n.alternate_upload .btn-upload,\n.btn-group,\n.btn-group-vertical {\n font-size: 12.0pt;\n font-weight: normal;\n}\n.btn-xs,\n.btn-group-xs > .btn {\n font-size: 12.0pt;\n background-image: none;\n font-weight: normal;\n text-shadow: none;\n display: inline-table;\n}\n.alternate_upload .btn-upload {\n display: none;\n}\n.alternate_upload input.fileinput {\n display: none;\n}\nbutton.close {\n border: 0px none;\n font-family: sans-serif;\n font-size: 25pt;\n}\n.dynamic-buttons {\n font-size: inherit;\n padding-top: 0px;\n display: inline-block;\n}\n.close {\n color: #de143d;\n opacity: .5;\n text-shadow: none;\n}\n.close:hover {\n color: #de143d;\n opacity: 1;\n}\ndiv.btn.btn-default.output_collapsed {\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: #eeeeee;\n}\ndiv.btn.btn-default.output_collapsed:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border-color: #e9e9e9;\n}\ndiv.nbext-enable-btns .btn[disabled],\ndiv.nbext-enable-btns .btn[disabled]:hover,\n.btn-default.disabled,\n.btn-default[disabled],\n.btn-default.disabled:hover,\n.btn-default[disabled]:hover,\nfieldset[disabled] .btn-default:hover,\n.btn-default.disabled:focus,\n.btn-default[disabled]:focus,\nfieldset[disabled] .btn-default:focus,\n.btn-default.disabled.focus,\n.btn-default[disabled].focus,\nfieldset[disabled] .btn-default.focus {\n color: #4a4a4a;\n background: #e8e8e8;\n background-color: #e8e8e8;\n border-color: #e8e8e8;\n}\n.input-group-addon {\n padding: 2px 5px;\n font-size: 12.0pt;\n font-weight: normal;\n height: auto;\n color: #303030;\n text-align: center;\n background-color: #ffffff;\n border: none;\n}\n.btn-group > .btn + .dropdown-toggle {\n padding-left: 8px;\n padding-right: 8px;\n height: 100%;\n border-left: 2px solid #ff7823 !important;\n}\n.btn-group > .btn + .dropdown-toggle:hover {\n border-left: 2px solid #ff7823 !important;\n}\n.input-group-btn {\n position: relative;\n font-size: inherit;\n white-space: nowrap;\n}\n.input-group-btn:first-child > .btn,\n.input-group-btn:first-child > .btn-group {\n background: #eeeeee;\n background-color: #eeeeee;\n border: 1px solid #e9e9e9;\n margin: 2px;\n font-size: inherit;\n}\n.input-group-btn:first-child > .btn:hover,\n.input-group-btn:first-child > .btn-group:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border: 1px solid #e9e9e9;\n margin: 2px;\n font-size: inherit;\n}\ndiv.modal .btn-group > .btn:first-child {\n background: #eeeeee;\n background-color: #eeeeee;\n border: 1px solid #e9e9e9;\n margin-top: 0px !important;\n margin-left: 0px;\n margin-bottom: 2px;\n}\ndiv.modal .btn-group > .btn:first-child:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border: 1px solid #e9e9e9;\n}\ndiv.modal > button,\ndiv.modal-footer > button {\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: #eeeeee;\n}\ndiv.modal > button:hover,\ndiv.modal-footer > button:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border-color: #e9e9e9;\n}\n.modal-content {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n position: relative;\n background: #eeeeee;\n background-color: #eeeeee;\n border: none;\n border-radius: 1px;\n background-clip: padding-box;\n outline: none;\n}\n.modal-header {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n color: #303030;\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: rgba(180,180,180,.30);\n padding: 12px;\n min-height: 16.4286px;\n}\n.modal-content h4 {\n font-family: \"Exo_2\", sans-serif;\n font-size: 16pt;\n color: #303030;\n padding: 5px;\n}\n.modal-body {\n background-color: #ffffff;\n position: relative;\n padding: 15px;\n}\n.modal-footer {\n padding: 10px;\n text-align: right;\n background-color: #f7f7f7;\n border-top: 1px solid rgba(180,180,180,.30);\n}\n.alert-info {\n background-color: #fdfdfd;\n border-color: rgba(180,180,180,.30);\n color: #303030;\n}\n.modal-header .close {\n margin-top: -5px;\n font-size: 25pt;\n}\n.modal-backdrop,\n.modal-backdrop.in {\n opacity: 0.75;\n background-color: #eeeeee;\n}\ndiv.panel,\ndiv.panel-default,\n.panel,\n.panel-default {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n background-color: #f7f7f7;\n color: #303030;\n margin-bottom: 14px;\n border: 0;\n box-shadow: none;\n}\ndiv.panel > .panel-heading,\ndiv.panel-default > .panel-heading {\n font-size: 14pt;\n color: #303030;\n background: #eeeeee;\n background-color: #eeeeee;\n border: 0;\n}\n.modal .modal-dialog {\n min-width: 950px;\n margin: 50px auto;\n}\ndiv.container-fluid {\n margin-right: auto;\n margin-left: auto;\n padding-left: 7px;\n padding-right: 12px;\n}\ndiv.form-control,\n.form-control {\n font-family: \"Exo_2\", sans-serif;\n font-size: inherit;\n color: #303030;\n background-color: #ffffff;\n border: 2px solid #e7e7e7;\n margin-left: 2px;\n height: auto;\n box-shadow: none;\n padding: 6px 12px;\n transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;\n}\n.form-group.list-group-item {\n color: #303030;\n background-color: #f7f7f7;\n border-color: rgba(180,180,180,.30);\n margin-bottom: 0px;\n}\ninput,\nbutton,\nselect,\ntextarea {\n background-color: #ffffff;\n font-weight: normal;\n border: 2px solid rgba(180,180,180,.30);\n}\nselect.form-control.select-xs {\n height: auto;\n}\ndiv.output.output_scroll {\n box-shadow: none;\n}\n::-webkit-scrollbar-track {\n -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.11);\n background-color: #d0d0d0;\n border-radius: 6px;\n}\n::-webkit-scrollbar {\n width: 14px;\n height: 10px;\n background-color: #d0d0d0;\n border-radius: 6px;\n}\n::-webkit-scrollbar-thumb {\n background-color: #ffffff;\n background-image: -webkit-gradient(linear,40% 0%,75% 86%,from(#ff6b0f ),color-stop(0.5,#ff8b42 ),to(#ff6b0f ));\n min-height: 60px;\n border-radius: 2px;\n}\ndiv.input_area {\n background-color: #efefef;\n padding-right: 1.2em;\n border: 0px;\n border-top-left-radius: 0px;\n border-top-right-radius: 2px;\n border-bottom-left-radius: 0px;\n border-bottom-right-radius: 0px;\n}\ndiv.cell {\n padding: 0px;\n background: #efefef;\n background-color: #efefef;\n border: medium solid #ffffff;\n border-top-right-radius: 2px;\n border-top-left-radius: 2px;\n}\ndiv.cell.selected {\n background: #efefef;\n background-color: #efefef;\n border: medium solid #ff7823;\n padding: 0px;\n border-top-right-radius: 2px;\n border-top-left-radius: 2px;\n}\n.edit_mode div.cell.selected {\n padding: 0px;\n background: #efefef;\n background-color: #efefef;\n border: medium solid #ffd5bb;\n border-top-right-radius: 2px;\n border-top-left-radius: 2px;\n}\ndiv.cell.edit_mode {\n padding: 0px;\n background: #efefef;\n background-color: #efefef;\n border: medium solid #ffd5bb;\n border-top-right-radius: 2px;\n border-top-left-radius: 2px;\n}\ndiv.prompt,\n.prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n font-weight: normal;\n color: #aaaaaa;\n line-height: 170%;\n padding: 0px;\n padding-top: 4px;\n padding-left: .25em;\n text-align: left !important;\n min-width: 12ex;\n width: 12ex;\n}\ndiv.prompt.input_prompt {\n background-color: #efefef;\n border-right: 2px solid rgba(240,147,43,.50);\n border-top-left-radius: 2px;\n border-top-right-radius: 0px;\n border-bottom-left-radius: 0px;\n border-bottom-right-radius: 0px;\n min-width: 12ex;\n width: 12ex !important;\n}\ndiv.output_wrapper {\n background-color: #ffffff;\n border: 0px;\n margin-bottom: 0em;\n margin-top: 0em;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-left-radius: 2px;\n border-bottom-right-radius: 2px;\n}\ndiv.output_subarea.output_text.output_stream.output_stdout,\ndiv.output_subarea.output_text {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 10.0pt;\n line-height: 150% !important;\n background-color: #ffffff;\n color: #303030;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-left-radius: 2px;\n border-bottom-right-radius: 2px;\n}\ndiv.output_area pre {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 10.0pt;\n line-height: 150% !important;\n color: #303030;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-left-radius: 2px;\n border-bottom-right-radius: 2px;\n}\ndiv.output_area {\n display: -webkit-box;\n}\ndiv.output_html {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 10.0pt;\n color: #353535;\n background-color: #ffffff;\n background: #ffffff;\n}\ndiv.output_subarea {\n overflow-x: auto;\n padding: .8em;\n -webkit-box-flex: 1;\n -moz-box-flex: 1;\n box-flex: 1;\n flex: 1;\n max-width: 90%;\n}\ndiv.prompt.output_prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n background-color: #ffffff;\n color: #ffffff;\n border-bottom-left-radius: 2px;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-right-radius: 0px;\n min-width: 12ex;\n width: 12ex;\n}\ndiv.out_prompt_overlay.prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n background-color: #ffffff;\n border-bottom-left-radius: 2px;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-right-radius: 0px;\n min-width: 12ex;\n width: 12ex;\n}\ndiv.out_prompt_overlay.prompt:hover {\n background-color: #ffffff;\n box-shadow: #e8e8e8 2px 1px 2px 2.5px inset;\n border-bottom-left-radius: 2px;\n -webkit-border-: 2px;\n -moz-border-radius: 2px;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n min-width: 12ex;\n width: 12ex !important;\n}\ndiv.text_cell,\ndiv.text_cell_render pre,\ndiv.text_cell_render {\n font-family: \"Lora\", serif;\n font-size: 13pt;\n line-height: 170% !important;\n color: #353535;\n background: #ffffff;\n background-color: #ffffff;\n border-radius: 2px;\n}\ndiv.cell.text_cell.rendered.selected {\n font-family: \"Lora\", serif;\n border: medium solid #126dce;\n line-height: 170% !important;\n background: #ffffff;\n background-color: #ffffff;\n border-radius: 2px;\n}\ndiv.cell.text_cell.unrendered.selected {\n font-family: \"Lora\", serif;\n line-height: 170% !important;\n background: #ffffff;\n background-color: #ffffff;\n border: medium solid #126dce;\n border-radius: 2px;\n}\ndiv.cell.text_cell.selected {\n font-family: \"Lora\", serif;\n line-height: 170% !important;\n border: medium solid #126dce;\n background: #ffffff;\n background-color: #ffffff;\n border-radius: 2px;\n}\n.edit_mode div.cell.text_cell.selected {\n font-family: \"Lora\", serif;\n line-height: 170% !important;\n background: #ffffff;\n background-color: #ffffff;\n border: medium solid #87b0db;\n border-radius: 2px;\n}\ndiv.text_cell.unrendered,\ndiv.text_cell.unrendered.selected,\ndiv.edit_mode div.text_cell.unrendered {\n font-family: \"Lora\", serif;\n line-height: 170% !important;\n background: #ffffff;\n background-color: #ffffff;\n border-radius: 2px;\n}\ndiv.cell.text_cell.rendered .input_prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n font-weight: normal;\n color: #aaaaaa;\n text-align: left !important;\n min-width: 0ex;\n width: 0ex !important;\n background-color: #ffffff;\n border-right: 2px solid transparent;\n}\ndiv.cell.text_cell.unrendered .input_prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n font-weight: normal;\n color: #aaaaaa;\n text-align: left !important;\n min-width: 0ex;\n width: 0ex !important;\n border-right: 2px solid transparent;\n}\ndiv.rendered_html code {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n padding-top: 3px;\n color: #303030;\n background: #efefef;\n background-color: #efefef;\n}\npre,\ncode,\nkbd,\nsamp {\n white-space: pre-wrap;\n}\ncode {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt !important;\n line-height: 170% !important;\n color: #353535;\n background: #efefef;\n background-color: #efefef;\n}\nkbd {\n padding: 4px;\n font-size: 11pt;\n color: #303030;\n background-color: #efefef;\n border: 0;\n box-shadow: none;\n}\npre {\n display: block;\n padding: 8.5px;\n margin: 0 0 9px;\n font-size: 12.0pt;\n line-height: 1.42857143;\n color: #303030;\n background-color: #efefef;\n border: 1px solid #e7e7e7;\n border-radius: 2px;\n}\ndiv.rendered_html {\n color: #353535;\n}\ndiv.rendered_html pre,\ndiv.text_cell_render pre {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt !important;\n line-height: 170% !important;\n color: #353535;\n background: #efefef;\n background-color: #efefef;\n border: 2px #e7e7e7  solid;\n max-width: 86%;\n border-radius: 2px;\n padding: 5px;\n}\ndiv.text_cell_render h1,\ndiv.rendered_html h1,\ndiv.text_cell_render h2,\ndiv.rendered_html h2,\ndiv.text_cell_render h3,\ndiv.rendered_html h3,\ndiv.text_cell_render h4,\ndiv.rendered_html h4,\ndiv.text_cell_render h5,\ndiv.rendered_html h5 {\n font-family: \"Exo_2\", sans-serif;\n}\n.rendered_html h1:first-child,\n.rendered_html h2:first-child,\n.rendered_html h3:first-child,\n.rendered_html h4:first-child,\n.rendered_html h5:first-child,\n.rendered_html h6:first-child {\n margin-top: 0.2em;\n}\n.rendered_html h1,\n.text_cell_render h1 {\n color: #126dce;\n font-size: 220%;\n text-align: center;\n font-weight: lighter;\n}\n.rendered_html h2,\n.text_cell_render h2 {\n text-align: left;\n font-size: 170%;\n color: #126dce;\n font-style: normal;\n font-weight: lighter;\n}\n.rendered_html h3,\n.text_cell_render h3 {\n font-size: 150%;\n color: #126dce;\n font-weight: lighter;\n text-decoration: italic;\n font-style: normal;\n}\n.rendered_html h4,\n.text_cell_render h4 {\n font-size: 120%;\n color: #126dce;\n font-weight: underline;\n font-style: normal;\n}\n.rendered_html h5,\n.text_cell_render h5 {\n font-size: 100%;\n color: #2f2f2f;\n font-weight: lighter;\n text-decoration: underline;\n}\n.rendered_html table,\n.rendered_html tr,\n.rendered_html td {\n font-family: \"Fira Code\", monospace;\n font-size: 10.0pt !important;\n line-height: 150% !important;\n border: 1px solid #d6d6d6;\n color: #353535;\n background-color: #ffffff;\n background: #ffffff;\n}\ntable.dataframe,\n.rendered_html tr,\n.dataframe * {\n font-family: \"Fira Code\", monospace;\n font-size: 10.0pt !important;\n border: 1px solid #d6d6d6;\n}\n.dataframe th,\n.rendered_html th {\n font-family: \"Exo_2\", sans-serif;\n font-size: 11pt !important;\n font-weight: bold;\n border: 1px solid #c4c4c4;\n background: #eeeeee;\n}\n.dataframe td,\n.rendered_html td {\n font-family: \"Fira Code\", monospace;\n font-size: 10.0pt !important;\n color: #353535;\n background: #ffffff;\n border: 1px solid #d6d6d6;\n text-align: left;\n min-width: 4em;\n}\n.dataframe-summary-row tr:last-child,\n.dataframe-summary-col td:last-child {\n font-family: \"Exo_2\", sans-serif;\n font-size: 11pt !important;\n font-weight: bold;\n color: #353535;\n border: 1px solid #d6d6d6;\n background: #eeeeee;\n}\ndiv.widget-area {\n background-color: #ffffff;\n background: #ffffff;\n color: #303030;\n}\ndiv.widget-area a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n font-weight: normal;\n font-style: normal;\n color: #303030;\n text-shadow: none !important;\n}\ndiv.widget-area a:hover,\ndiv.widget-area a:focus {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n font-weight: normal;\n font-style: normal;\n color: #2f2f2f;\n background: rgba(180,180,180,.14);\n background-color: rgba(180,180,180,.14);\n border-color: transparent;\n background-image: none;\n text-shadow: none !important;\n}\ndiv.widget_item.btn-group > button.btn.btn-default.widget-combo-btn,\ndiv.widget_item.btn-group > button.btn.btn-default.widget-combo-btn:hover {\n background: #eeeeee;\n background-color: #eeeeee;\n border: 2px solid #eeeeee !important;\n font-size: inherit;\n z-index: 0;\n}\ndiv.jupyter-widgets.widget-hprogress.widget-hbox,\ndiv.widget-hbox,\n.widget-hbox {\n display: inline-table;\n}\ndiv.jupyter-widgets.widget-hprogress.widget-hbox .widget-label,\ndiv.widget-hbox .widget-label,\n.widget-hbox .widget-label {\n font-size: 11pt;\n min-width: 100%;\n padding-top: 5px;\n padding-right: 10px;\n text-align: left;\n vertical-align: text-top;\n}\n.progress {\n overflow: hidden;\n height: 20px;\n margin-bottom: 10px;\n padding-left: 10px;\n background-color: #c6c6c6;\n border-radius: 4px;\n -webkit-box-shadow: none;\n box-shadow: none;\n}\n.rendered_html :link {\n font-family: \"Exo_2\", sans-serif;\n font-size: 100%;\n color: #2c85f7;\n text-decoration: underline;\n}\n.rendered_html :visited,\n.rendered_html :visited:active,\n.rendered_html :visited:focus {\n color: #2e6eb2;\n}\n.rendered_html :visited:hover,\n.rendered_html :link:hover {\n font-family: \"Exo_2\", sans-serif;\n font-size: 100%;\n color: #eb6a18;\n}\na.anchor-link:link:hover {\n font-size: inherit;\n color: #eb6a18;\n}\na.anchor-link:link {\n font-size: inherit;\n text-decoration: none;\n padding: 0px 20px;\n visibility: none;\n color: #126dce;\n}\ndiv#nbextensions-configurator-container.container {\n width: 980px;\n margin-right: 0;\n margin-left: 0;\n}\ndiv.nbext-selector > nav > .nav > li > a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12pt;\n}\ndiv.nbext-readme > .nbext-readme-contents > .rendered_html {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12pt;\n line-height: 145%;\n padding: 1em 1em;\n color: #353535;\n background-color: #ffffff;\n -webkit-box-shadow: none;\n -moz-box-shadow: none;\n box-shadow: none;\n}\n.nbext-icon,\n.nbext-desc,\n.nbext-compat-div,\n.nbext-enable-btns,\n.nbext-params {\n margin-bottom: 8px;\n font-size: 12pt;\n}\ndiv.nbext-readme > .nbext-readme-contents {\n padding: 0;\n overflow-y: hidden;\n}\ndiv.nbext-readme > .nbext-readme-contents:not(:empty) {\n margin-top: 0.5em;\n margin-bottom: 2em;\n border: none;\n border-top-color: rgba(180,180,180,.30);\n}\n.nbext-showhide-incompat {\n padding-bottom: 0.5em;\n color: #4a4a4a;\n font-size: 12.0pt;\n}\n.shortcut_key,\nspan.shortcut_key {\n display: inline-block;\n width: 16ex;\n text-align: right;\n font-family: monospace;\n}\nmark,\n.mark {\n background-color: #ffffff;\n color: #353535;\n padding: .15em;\n}\na.text-warning,\na.text-warning:hover {\n color: #aaaaaa;\n}\na.text-warning.bg-warning {\n background-color: #ffffff;\n}\nspan.bg-success.text-success {\n background-color: transparent;\n color: #009e07;\n}\nspan.bg-danger.text-danger {\n background-color: #ffffff;\n color: #de143d;\n}\n.has-success .input-group-addon {\n color: #009e07;\n border-color: transparent;\n background: inherit;\n background-color: rgba(83,180,115,.10);\n}\n.has-success .form-control {\n border-color: #009e07;\n -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.025);\n box-shadow: inset 0 1px 1px rgba(0,0,0,0.025);\n}\n.has-error .input-group-addon {\n color: #de143d;\n border-color: transparent;\n background: inherit;\n background-color: rgba(192,57,67,.10);\n}\n.has-error .form-control {\n border-color: #de143d;\n -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.025);\n box-shadow: inset 0 1px 1px rgba(0,0,0,0.025);\n}\n.kse-input-group-pretty > kbd {\n font-family: \"Droid Sans Mono\", monospace;\n color: #303030;\n font-weight: normal;\n background: transparent;\n}\n.kse-input-group-pretty > kbd {\n font-family: \"Droid Sans Mono\", monospace;\n color: #303030;\n font-weight: normal;\n background: transparent;\n}\ndiv.nbext-enable-btns .btn[disabled],\ndiv.nbext-enable-btns .btn[disabled]:hover,\n.btn-default.disabled,\n.btn-default[disabled] {\n background: #e8e8e8;\n background-color: #e8e8e8;\n color: #282828;\n}\nlabel#Keyword-Filter {\n display: none;\n}\n.nav-pills > li.active > a,\n.nav-pills > li.active > a:hover,\n.nav-pills > li.active > a:focus {\n color: #ffffff;\n background-color: #126dce;\n}\n.input-group .nbext-list-btn-add,\n.input-group-btn:last-child > .btn-group > .btn {\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: #eeeeee;\n}\n.input-group .nbext-list-btn-add:hover,\n.input-group-btn:last-child > .btn-group > .btn:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border-color: #e9e9e9;\n}\n#notebook-container > div.cell.code_cell.rendered.selected > div.widget-area > div.widget-subarea > div > div.widget_item.btn-group > button.btn.btn-default.dropdown-toggle.widget-combo-carrot-btn {\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: #eeeeee;\n}\n#notebook-container > div.cell.code_cell.rendered.selected > div.widget-area > div.widget-subarea > div > div.widget_item.btn-group > button.btn.btn-default.dropdown-toggle.widget-combo-carrot-btn:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border-color: #e9e9e9;\n}\ninput.raw_input {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt !important;\n color: #303030;\n background-color: #efefef;\n border-color: #ececec;\n background: #ececec;\n width: auto;\n vertical-align: baseline;\n padding: 0em 0.25em;\n margin: 0em 0.25em;\n -webkit-box-shadow: none;\n box-shadow: none;\n}\naudio,\nvideo {\n display: inline;\n vertical-align: middle;\n align-content: center;\n margin-left: 20%;\n}\n.cmd-palette .modal-body {\n padding: 0px;\n margin: 0px;\n}\n.cmd-palette form {\n background: #eeeeee;\n background-color: #eeeeee;\n}\n.typeahead-field input:last-child,\n.typeahead-hint {\n background: #eeeeee;\n background-color: #eeeeee;\n z-index: 1;\n}\n.typeahead-field input {\n font-family: \"Exo_2\", sans-serif;\n color: #303030;\n border: none;\n font-size: 28pt;\n display: inline-block;\n line-height: inherit;\n padding: 3px 10px;\n height: 70px;\n}\n.typeahead-select {\n background-color: #eeeeee;\n}\nbody > div.modal.cmd-palette.typeahead-field {\n display: table;\n border-collapse: separate;\n background-color: #f7f7f7;\n}\n.typeahead-container button {\n font-family: \"Exo_2\", sans-serif;\n font-size: 28pt;\n background-color: #d0d0d0;\n border: none;\n display: inline-block;\n line-height: inherit;\n padding: 3px 10px;\n height: 70px;\n}\n.typeahead-search-icon {\n min-width: 40px;\n min-height: 55px;\n display: block;\n vertical-align: middle;\n text-align: center;\n}\n.typeahead-container button:focus,\n.typeahead-container button:hover {\n color: #2f2f2f;\n background-color: #ff7823;\n border-color: #ff7823;\n}\n.typeahead-list > li.typeahead-group.active > a,\n.typeahead-list > li.typeahead-group > a,\n.typeahead-list > li.typeahead-group > a:focus,\n.typeahead-list > li.typeahead-group > a:hover {\n display: none;\n}\n.typeahead-dropdown > li > a,\n.typeahead-list > li > a {\n color: #303030;\n text-decoration: none;\n}\n.typeahead-dropdown,\n.typeahead-list {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n color: #303030;\n background-color: #ffffff;\n border: none;\n background-clip: padding-box;\n margin-top: 0px;\n padding: 3px 2px 3px 0px;\n line-height: 1.7;\n}\n.typeahead-dropdown > li.active > a,\n.typeahead-dropdown > li > a:focus,\n.typeahead-dropdown > li > a:hover,\n.typeahead-list > li.active > a,\n.typeahead-list > li > a:focus,\n.typeahead-list > li > a:hover {\n color: #2f2f2f;\n background-color: #f7f7f7;\n border-color: #f7f7f7;\n}\n.command-shortcut:before {\n content: \"(command)\";\n padding-right: 3px;\n color: #aaaaaa;\n}\n.edit-shortcut:before {\n content: \"(edit)\";\n padding-right: 3px;\n color: #aaaaaa;\n}\nul.typeahead-list i {\n margin-left: 1px;\n width: 18px;\n margin-right: 10px;\n}\nul.typeahead-list {\n max-height: 50vh;\n overflow: auto;\n}\n.typeahead-list > li {\n position: relative;\n border: none;\n}\ndiv.input.typeahead-hint,\ninput.typeahead-hint,\nbody > div.modal.cmd-palette.in > div > div > div > form > div > div.typeahead-field > span.typeahead-query > input.typeahead-hint {\n color: #aaaaaa !important;\n background-color: transparent;\n padding: 3px 10px;\n}\n.typeahead-dropdown > li > a,\n.typeahead-list > li > a {\n display: block;\n padding: 5px;\n clear: both;\n font-weight: 400;\n line-height: 1.7;\n border: 1px solid #ffffff;\n border-bottom-color: rgba(180,180,180,.30);\n}\nbody > div.modal.cmd-palette.in > div {\n min-width: 750px;\n margin: 150px auto;\n}\n.typeahead-container strong {\n font-weight: bolder;\n color: #ff7823;\n}\n#find-and-replace #replace-preview .match,\n#find-and-replace #replace-preview .insert {\n color: #ffffff;\n background-color: #ff7823;\n border-color: #ff7823;\n border-style: solid;\n border-width: 1px;\n border-radius: 0px;\n}\n#find-and-replace #replace-preview .replace .match {\n background-color: #de143d;\n border-color: #de143d;\n border-radius: 0px;\n}\n#find-and-replace #replace-preview .replace .insert {\n background-color: #009e07;\n border-color: #009e07;\n border-radius: 0px;\n}\ndiv.CodeMirror,\ndiv.CodeMirror pre {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n line-height: 170%;\n color: #303030;\n}\ndiv.CodeMirror-lines {\n padding-bottom: .6em;\n padding-left: .5em;\n padding-right: 1.5em;\n padding-top: 4px;\n}\nspan.ansiblack {\n color: #dc4384;\n}\nspan.ansiblue {\n color: #009e07;\n}\nspan.ansigray {\n color: #ff7823;\n}\nspan.ansigreen {\n color: #333333;\n}\nspan.ansipurple {\n color: #653bc5;\n}\nspan.ansicyan {\n color: #055be0;\n}\nspan.ansiyellow {\n color: #ff7823;\n}\nspan.ansired {\n color: #de143d;\n}\ndiv.output-stderr {\n background-color: #ebb5b7;\n}\ndiv.output-stderr pre {\n color: #000000;\n}\ndiv.js-error {\n color: #de143d;\n}\n.ipython_tooltip {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n line-height: 170%;\n border: 2px solid #dadada;\n background: #eeeeee;\n background-color: #eeeeee;\n border-radius: 2px;\n overflow-x: visible;\n overflow-y: visible;\n box-shadow: none;\n position: absolute;\n z-index: 1000;\n}\n.ipython_tooltip .tooltiptext pre {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n line-height: 170%;\n background: #eeeeee;\n background-color: #eeeeee;\n color: #303030;\n overflow-x: visible;\n overflow-y: visible;\n max-width: 900px;\n}\ndiv#tooltip.ipython_tooltip {\n overflow-x: wrap;\n overflow-y: visible;\n max-width: 800px;\n}\ndiv.tooltiptext.bigtooltip {\n overflow-x: visible;\n overflow-y: scroll;\n height: 400px;\n max-width: 800px;\n}\n.cm-s-ipython.CodeMirror {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n background: #efefef;\n color: #303030;\n border-radius: 2px;\n font-style: normal;\n font-weight: normal;\n}\n.cm-s-ipython div.CodeMirror-selected {\n background: #e0e1e3;\n}\n.cm-s-ipython .CodeMirror-gutters {\n background: #e0e1e3;\n border: none;\n border-radius: 0px;\n}\n.cm-s-ipython .CodeMirror-linenumber {\n color: #aaaaaa;\n}\n.cm-s-ipython .CodeMirror-cursor {\n border-left: 2px solid #ff711a;\n}\n.cm-s-ipython span.cm-comment {\n color: #8d8d8d;\n font-style: italic;\n}\n.cm-s-ipython span.cm-atom {\n color: #055be0;\n}\n.cm-s-ipython span.cm-number {\n color: #ff8132;\n}\n.cm-s-ipython span.cm-property {\n color: #e22978;\n}\n.cm-s-ipython span.cm-attribute {\n color: #de143d;\n}\n.cm-s-ipython span.cm-keyword {\n color: #713bc5;\n font-weight: normal;\n}\n.cm-s-ipython span.cm-string {\n color: #009e07;\n}\n.cm-s-ipython span.cm-meta {\n color: #aa22ff;\n}\n.cm-s-ipython span.cm-operator {\n color: #055be0;\n}\n.cm-s-ipython span.cm-builtin {\n color: #e22978;\n}\n.cm-s-ipython span.cm-variable {\n color: #303030;\n}\n.cm-s-ipython span.cm-variable-2 {\n color: #de143d;\n}\n.cm-s-ipython span.cm-variable-3 {\n color: #aa22ff;\n}\n.cm-s-ipython span.cm-def {\n color: #e22978;\n font-weight: normal;\n}\n.cm-s-ipython span.cm-error {\n background: rgba(191,97,106,.40);\n}\n.cm-s-ipython span.cm-tag {\n color: #e22978;\n}\n.cm-s-ipython span.cm-link {\n color: #ff7823;\n}\n.cm-s-ipython span.cm-storage {\n color: #055be0;\n}\n.cm-s-ipython span.cm-entity {\n color: #e22978;\n}\n.cm-s-ipython span.cm-quote {\n color: #009e07;\n}\ndiv.CodeMirror span.CodeMirror-matchingbracket {\n color: #1c1c1c;\n background-color: rgba(30,112,199,.30);\n}\ndiv.CodeMirror span.CodeMirror-nonmatchingbracket {\n color: #1c1c1c;\n background: rgba(191,97,106,.40) !important;\n}\ndiv.cell.text_cell .cm-s-default .cm-header {\n color: #126dce;\n}\ndiv.cell.text_cell .cm-s-default span.cm-variable-2 {\n color: #353535;\n}\ndiv.cell.text_cell .cm-s-default span.cm-variable-3 {\n color: #aa22ff;\n}\n.cm-s-default span.cm-comment {\n color: #8d8d8d;\n}\n.cm-s-default .cm-tag {\n color: #009fb7;\n}\n.cm-s-default .cm-builtin {\n color: #e22978;\n}\n.cm-s-default .cm-string {\n color: #009e07;\n}\n.cm-s-default .cm-keyword {\n color: #713bc5;\n}\n.cm-s-default .cm-number {\n color: #ff8132;\n}\n.cm-s-default .cm-error {\n color: #055be0;\n}\n.CodeMirror-cursor {\n border-left: 2px solid #ff711a;\n border-right: none;\n width: 0;\n}\n.cm-s-default div.CodeMirror-selected {\n background: #e0e1e3;\n}\n.cm-s-default .cm-selected {\n background: #e0e1e3;\n}\ndiv#maintoolbar {\n display: none !important;\n}\n#header-container {\n display: none !important;\n}\n\n/**********************************\n MathJax Settings and Style Script\n**********************************/\n.MathJax_Display,\n.MathJax nobr>span.math>span {\n    border: 0 !important;\n    font-size: 110% !important;\n    text-align: center !important;\n    margin: 0em !important;\n}\n/* Prevents MathJax from jittering */\n/* cell position when cell is selected */\n.MathJax:focus, body :focus .MathJax {\n    display: inline-block !important;\n}\n\n\n\n </style>\n\n\n\n\n```python\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# 1. magic for inline plot\n# 2. magic to print version\n# 3. magic so that the notebook will reload external python modules\n%matplotlib inline\n%load_ext watermark\n%load_ext autoreload \n%autoreload 2\n\nfrom sklearn.decomposition import PCA\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.datasets import load_iris\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\n\n%watermark -a 'Ethen' -d -t -v -p numpy,pandas,matplotlib,sklearn\n```\n\n    Ethen 2017-03-13 15:07:11 \n    \n    CPython 3.5.2\n    IPython 4.2.0\n    \n    numpy 1.12.0\n    pandas 0.19.2\n    matplotlib 2.0.0\n    sklearn 0.18\n\n\n# Dimensionality Reduction\n\nThe starting point most data analysis problems is to perform some sort of exploratory data analysis on our raw data. This step is important because until we have basic understanding of the structure of our raw data, it might be hard to know whether the data is suitable for the task at hand or even derive insights that we can later share. During this exploratoy process, unsupervised methods such as dimensionality reduction can help us identify simpler and more compact representations of the original raw data to either aid our understanding or provide useful input to other stages of analysis. Here, we'll be focusing on a specific dimensionality reduction technique called **Principal Component Analysis (PCA)**.\n\nImagine that we're trying to understand some underlying phenomenon, in order to do so we measure various quantities potentially related to it. If we knew exactly what to measure in advance, we might be able to find some simple relationships in our data. But we typically don't, so we often measure anything that might be relevant and end up having irrelevant or redundant signals in our measurement. To make this a bit more concrete, we'll generate a toy 2-dimensional dataset to work with using the equation below.\n\n$$x_2 = 500 + 20 \\times x_1 + \\epsilon$$\n\n\n```python\nnp.random.seed(123)\nx1 = np.arange(12, 56, 0.5)\ne  = np.random.normal(0, 100, x1.shape[0])\nx2 = 500 + 20 * x1 + e\nX = np.c_[x1, x2]\n\n# change default style figure and font size\nplt.style.use('fivethirtyeight')\nplt.rcParams['figure.figsize'] = 8, 6\nplt.rcParams['font.size'] = 12\n\ndef plot2var(m):\n    plt.scatter(m[:, 0], m[:, 1], s = 40, alpha = 0.8)\n    plt.xlabel('x1')\n    plt.ylabel('x2')\n\nplot2var(X)\n```\n\nWe can clearly see from the plot that there's linear relationship between the two variables, thus we probably don't need to include both of them as $x_1$ can be easily explained by $x_2$ and vice versa.\n\n## PCA\n\nIf it is the case that one of the features is considered redundant, we should be able to summarize the data with less characteristics (features). So, the way PCA tackles this problem is: Instead of simply picking out the useful features and discarding the others, it uses a linear combination of the existing features and constructs some new features that are good alternative representation of the original data. In our 2D toy dataset, PCA will try to pick the best single direction, or often referred to as **first principal components** in 2D, and project our points onto that single direction. So the next question becomes, out of the many possible lines in 2D, what line should we pick?\n\nIt turns out, there are two different answers to this question. First answer is that we are looking for some features that strongly differ across data points, thus, PCA looks for features that captures as much variation across data points as possible. The second answer is that we are looking for the features that would allow us to \"reconstruct\" the original features. Imagine that we come up with a feature that has no relation to the original ones; If we were to use this new feature, there is no way we can relate this to the original ones. So PCA looks for features that minimizes the reconstruction error. These two notions can be depicted in the graph below, where the black dots represents the original data point, the black line represents the projected line, the red dot on the left shows the points on the projected line and the red line on the right shows the reconstruction error.\n\n\n\nSurprisingly, it turns out that these two aims are equivalent and PCA can kill two birds with one stone. To see why minimizing squared residuals is equivalent to maximizing variance consider the 2 dimensions visualization below.\n\n\n\nConsider a datapoint $a_i$. The contribution of this specific data point to the total variance is $a_i^Ta_i$, or equivalently the squared Euclidean length $\\lVert \\mathbf{a}_i \\lVert^2$. Applying the Pythagorean theorem shows that this total variance equals the sum of variance lost (the squared residual) and variance remaining. Thus, it is equivalent to either maximize remaining variance or minimize lost variance to find the principal components.\n\nBefore we go another deeper, let's build some intuition using the scikit-learn library. The following section standardizes the data, fits the PCA model and prints out some of the important informations.\n\n\n```python\n# we start by standardizing our dataset\nX_std = StandardScaler().fit_transform(X)\n\n# call PCA specifying we only want the\n# first two principal components (since\n# we only have a 2d datset)\npca = PCA(n_components = 2)\npca.fit(X_std)\n\n# important information\nprint('Components:\\n ', pca.components_)\nprint('Explained Variance Ratio:\\n ', pca.explained_variance_ratio_)\n```\n\n    Components:\n      [[-0.70710678 -0.70710678]\n     [ 0.70710678 -0.70710678]]\n    Explained Variance Ratio:\n      [ 0.95588995  0.04411005]\n\n\nAfter fitting the PCA on the dataset, the fit learns some quantities from the data, most importantly the \"components\", which is the principal components (the new direction that our data points will be projected upon) and \"explained variance ratio\", which corresponds to the percentage of variance explained by each of the principal components. To get a better sense of what these numbers mean, let's visualize them over our standardized input data.\n\n\n```python\ndef draw_vector(v0, v1):\n    \"\"\"draw principal components as vectors\"\"\"\n    ax = plt.gca()\n    arrowprops = dict(arrowstyle = '->',\n                      linewidth = 2, edgecolor = 'black',\n                      shrinkA = 0, shrinkB = 0)\n    plt.annotate('', v1, v0, arrowprops = arrowprops)\n\n# plot data\nplt.scatter(X_std[:, 0], X_std[:, 1], s = 40, alpha = 0.8)\nfor length, vector in zip(pca.explained_variance_, pca.components_):\n    # the larger the explained variance, the longer the\n    # annotated line will be\n    v = vector * 2 * np.sqrt(length)\n    draw_vector(pca.mean_, pca.mean_ + v)\n\nplt.axis('equal')\nplt.show()\n```\n\nFrom the plot, we see that our PCA model gives us two principal components (the black line) and the length of the lines indicate of how important that principal component is in describing the variation of the original data. So if we were to choose 1 principal component to summarize our 2d dataset, it will be line that has the longest length (largest explained variance ratio). There're two things worth noting:\n\n- The number of principal components matches the total number of features\n- The first and second principal components are orthogonal to each other\n\nThe reason for this is that principal components transform the data into a new set of dimensions, and these new dimensions have to be equal to the original amount of dimensions. And just like the original $x$, $y$ axis that we're used to, they have to be orthogonal to each other. Let's now reduce the dimension of our 2d dataset into 1d by transforming our data onto the most important principal component and plot it along with the original data.\n\n\n```python\n# dimensionality reduction, keeping only\n# the first principal component\npca = PCA(n_components = 1)\nX_pca = pca.fit_transform(X_std)\nprint(\"original shape:   \", X.shape)\nprint(\"transformed shape:\", X_pca.shape)\n\n# inverse transform to obtain the projected data\n# and compare with the original\nX_new = pca.inverse_transform(X_pca)\nplt.scatter(X_std[:, 0], X_std[:, 1], s = 40, alpha = 0.2)\nplt.scatter(X_new[:, 0], X_new[:, 1], s = 40, alpha = 0.8)\nplt.show()\n```\n\nIn the plot above, the lighter points are the original data and the darker points are the projected version. Looking at the projections we see that the points projected onto the first principal component all seem close to their initial representations and at the same time, it also captures most of the variations in our original data points.\n\nHopefully, this elucidate what a PCA dimensionality reduction is doing. In a nutshell, PCA aims to find the directions or so called the principal components of maximum variance in high-dimensional data and project it onto a smaller dimensional subspace while retaining most of the information. In our 2d example, the linear relationship between $x_1$ and $x_2$ is mostly preserved using only 1 feature instead of 2.\n\n## PCA From Scratch\n\nNow that we have a high level understanding of what PCA is accomplishing, let's now formalize this with some notations. Recall that PCA is trying the find the direction such that the projection of the data on it has the highest variance. So given $X$, the centered data matrix, the projection, $Xw$ (dot product between the data point, $X$ and the projection weight, $w$), its variance can be computed as follows:\n\n\\begin{align}\n\\frac{1}{n-1}(\\mathbf{Xw})^\\top \\mathbf{Xw} = \\mathbf w^\\top (\\frac{1}{n-1}\\mathbf X^\\top\\mathbf X) \\mathbf w = \\mathbf w^\\top \\mathbf{Cw}\n\\end{align}\n\nWhere $\\mathbf{C}$ is the covariance matrix of the data $\\mathbf{X}$. In case this looks unfamiliar, the covariance matrix is a $d \\times d$ matrix ($d$ is the total number of dimensions, features) where each element represents the covariance between two features. The covariance between two features $x_j$ and $x_k$ is calculated as follows:\n\n\\begin{align}\n\\sigma_{jk} = \\frac{1}{n-1} \\sum_{i=1}^{n} \\left( x_{ij} - \\bar{x}_j \\right) \\left( x_{ik} - \\bar{x}_k \\right)\n\\end{align}\n\nWhere $\\bar{x}_j$ is simply the mean of vector (feature) $\\bar{x}_j = \\sum \\limits_{i=1}^n x_{ij}$.\n\nWe can also express the calculation of the covariance matrix via the following matrix equation: \n\n\\begin{align}\n\\mathbf{C} = \\frac{1}{n-1} \\big( (X - \\bar{x})^\\top( X - \\bar{x}) \\big)\n\\end{align}\n\nBecause we already assume to data point $X$ has been centered, thus the $X - \\bar{x}$ part can be simplified into just $X$. And the formula above simply becomes:\n\n\\begin{align}\n\\mathbf{C} = \\frac{1}{n-1} X^\\top X\n\\end{align}\n\nNext, apart from the original objective function $\\mathbf w^\\top \\mathbf{Cw}$, we also introduce an additional constraint $\\|\\mathbf w\\|=\\mathbf w^\\top \\mathbf w=1$, saying our weight vector should have unit length. The intuition behind this is that: If we were to simply maximize the formula $\\mathbf w^\\top \\mathbf{Cw}$, we can multiply $w$ by any number and the objective function will increase by the square of this number. So the problem becomes ill-defined since the maximum of this expression is infinite. Given these two pieces of information, our objective function for PCA becomes:\n\n\\begin{align}\n&  \\underset{\\mathbf{w}}{\\text{maximize}}\n&& \\mathbf w^\\top \\mathbf{Cw} \\nonumber \\\\\n&  \\text{subject to}\n&& \\mathbf w^\\top \\mathbf w=1\n\\end{align}\n\nThis objective function can be solved by the Lagrange multiplier, minimizing the loss function:\n\n\\begin{align}\nL &= \\mathbf w^\\top \\mathbf{Cw}-\\lambda(\\mathbf w^\\top \\mathbf w-1)\n\\end{align}\n\nIf this looks unfamiliar, check out the following tutorial on Lagrange multiplier. [Khan Academy: Lagrange multipliers, examples](https://www.khanacademy.org/math/multivariable-calculus/applications-of-multivariable-derivatives/constrained-optimization/a/lagrange-multipliers-examples). Next, to solve for $w$, we set the partial derivative of $L$ with respect to $w$ to 0.\n\n\\begin{align}\n\\frac{\\partial L}{\\partial \\mathbf w} \n& \\implies \\mathbf{Cw} - \\lambda \\mathbf w = 0 \\\\\n& \\implies \\mathbf{Cw} = \\lambda \\mathbf w\n\\end{align}\n\nHopefully the formula above looks familar, since it's essentially an eigendecomposition problem. The notion of eigendecomposition is basically trying to solve the equation:\n\n\\begin{align}\nAx &= \\lambda x\n\\end{align}\n\nIn our case, $A$ is our covariance matrix correponding to $\\mathbf C$; $x$ is our eigenvector, correponding to $\\mathbf w$ and $\\lambda$ is our eigenvalue correponding to explained variance. After solving the equation above, we'll obtain eigenvector and eigenvalue pairs, where very eigenvector has a corresponding eigenvalue. An eigenvector is essentially the direction of each principal component and the eigenvalue is a number, telling us how much variance there is in the data in that direction, in other words, how spread out the data is on the line. For those interested, the following blog walks through the calculating eigenvalue and eigenvectors from scratch. [Blog: What are eigenvectors and eigenvalues?](http://www.visiondummy.com/2014/03/eigenvalues-eigenvectors/)\n\nGiven all of that, let's see how this works in code. Just to summarize, the general framework for computing PCA is as follows:\n\n- Standardize the data\n- Obtain the Eigenvectors and Eigenvalues from the covariance matrix\n- Sort eigenvalues in descending order and choose the $k$ eigenvectors that correspond to the $k$ largest eigenvalues where $k$ is the number of dimensions of the new feature subspace\n- Projection onto the new feature space. During this step we will take the top $k$ eigenvectors and use it to transform the original dataset $X$ to obtain a k-dimensional feature subspace $X'$\n\nFor the section below, we will be working with the famous \"Iris\" dataset. The iris dataset is a 150\u00d74 matrix where the columns are the different features (sepal length in cm, sepal width in cm, petal length in cm, petal width in cm) and every every row represents a separate flower sample. The three classes in the Iris dataset are: Iris-setosa (n=50), Iris-versicolor (n=50), Iris-virginica (n=50). We'll use histograms to get a feeling of how the 3 different flower classes are distributes along the 4 different features.\n\n\n```python\niris = load_iris()\nX = iris['data']\ny = iris['target']\n\nlabel_dict = {0: 'Iris-Setosa',\n              1: 'Iris-Versicolor',\n              2: 'Iris-Virgnica'}\n\nfeature_dict = {0: 'sepal length [cm]',\n                1: 'sepal width [cm]',\n                2: 'petal length [cm]',\n                3: 'petal width [cm]'}\n\nfig = plt.figure(figsize = (10, 6))\nfor feature in range(len(feature_dict)):\n    plt.subplot(2, 2, feature + 1)\n    for index, label in label_dict.items():\n        plt.hist( X[y == index, feature], label = label,\n                  bins = 10, alpha = 0.3 )\n        plt.xlabel(feature_dict[index])\n        \nplt.legend(loc = 'upper right', fancybox = True, fontsize = 12)\nplt.tight_layout()\nplt.show()\n```\n\n### Standardize\n\nIn general, it's important to standardize the data prior to a PCA on the covariance matrix depends on the measurement scales of the original features. Since PCA yields a feature subspace that maximizes the variance along the axes, it makes sense to standardize the data, especially if it was measured on different scales so different features will have equal contribution in terms of their scales.\n\n\n```python\n# subtract the mean and divide the\n# standard deviation of each features\nmean = np.mean(X, axis = 0)\nscale = np.std(X, axis = 0)\nX_std = (X - mean) / scale\n```\n\n### Eigendecomposition - Computing Eigenvectors and Eigenvalues\n\nThe eigenvectors and eigenvalues of a covariance matrix is the core of PCA: The eigenvectors (principal components) determine the directions of the new feature space, and the eigenvalues determine their magnitude (variance explained along the principal components).\n\n\n```python\n# for those unfamiliar with the @ syntax it\n# is equivalent of .dot, the dot product\nvec_mean = np.mean(X_std, axis = 0)\nvec_diff = X_std - vec_mean\ncov_mat  = vec_diff.T @ vec_diff / (X_std.shape[0] - 1)\nprint( 'Covariance matrix \\n {}'.format(cov_mat) )\n\n# note that since we already standardize the data,\n# meaning the mean vector for each features, vec_mean \n# will be 0 (really small numbers if you were to print them out),\n# hence we don't have to substract the mean to standardize them\ncov_mat = X_std.T @ X_std / (X_std.shape[0] - 1)\nprint('Covariance matrix \\n {}'.format(cov_mat) )\n\n# equivalently, we could have used the np.cov function:\n# since each row represents a variable for np.cov,\n# we'll need to transpose the matrix\nprint( 'NumPy covariance matrix: \\n {}'.format(np.cov(X_std.T)) )\n```\n\n    Covariance matrix \n     [[ 1.00671141 -0.11010327  0.87760486  0.82344326]\n     [-0.11010327  1.00671141 -0.42333835 -0.358937  ]\n     [ 0.87760486 -0.42333835  1.00671141  0.96921855]\n     [ 0.82344326 -0.358937    0.96921855  1.00671141]]\n    Covariance matrix \n     [[ 1.00671141 -0.11010327  0.87760486  0.82344326]\n     [-0.11010327  1.00671141 -0.42333835 -0.358937  ]\n     [ 0.87760486 -0.42333835  1.00671141  0.96921855]\n     [ 0.82344326 -0.358937    0.96921855  1.00671141]]\n    NumPy covariance matrix: \n     [[ 1.00671141 -0.11010327  0.87760486  0.82344326]\n     [-0.11010327  1.00671141 -0.42333835 -0.358937  ]\n     [ 0.87760486 -0.42333835  1.00671141  0.96921855]\n     [ 0.82344326 -0.358937    0.96921855  1.00671141]]\n\n\nAfter obtaining the covariance matrix, we perform an eigendecomposition on it to obtain the eigenvalues and eigenvectors.\n\n\n```python\n# since computing this by hand can be quite tedious\n# we'll simply use the pre-implemented function\neig_vals, eig_vecs = np.linalg.eig(cov_mat)\nprint('Eigenvectors \\n%s' % eig_vecs)\nprint('\\nEigenvalues \\n%s' % eig_vals)\n```\n\n    Eigenvectors \n    [[ 0.52237162 -0.37231836 -0.72101681  0.26199559]\n     [-0.26335492 -0.92555649  0.24203288 -0.12413481]\n     [ 0.58125401 -0.02109478  0.14089226 -0.80115427]\n     [ 0.56561105 -0.06541577  0.6338014   0.52354627]]\n    \n    Eigenvalues \n    [ 2.93035378  0.92740362  0.14834223  0.02074601]\n\n\n### Choosing Top K Eigenvectors\n\nRecall that the typical goal of a PCA is to reduce the dimensionality of the original feature space by projecting it onto a smaller subspace. In order to decide which eigenvector(s) can dropped without losing too much information for the construction of lower-dimensional subspace, we need to inspect the corresponding eigenvalues. The idea is: eigenvectors with the lowest eigenvalues bear the least information about the distribution of the data and those are the ones can be dropped. In order to do so, the common approach is to rank the eigenvalues from highest to lowest in order choose the top $k$ eigenvectors.\n\nAfter sorting the eigenpairs, the next question is \"how many principal components are we going to choose for our new feature subspace?\" A useful measure is the so-called \u201cexplained variance,\u201d which can be calculated from the eigenvalues. The explained variance tells us how much extra information (variance) does each of the principal components contribute.\n\n\n```python\neig_vals_total = np.sum(eig_vals)\nvar_exp = eig_vals / eig_vals_total\ncum_var_exp = np.cumsum(var_exp)\nprint('Variance Explained: ', var_exp)\nprint('Cumulative Variance Explained: ', cum_var_exp)\n\nplt.bar(range(var_exp.shape[0]), var_exp, alpha = 0.5, \n        align = 'center', label = 'individual explained variance')\nplt.step(range(var_exp.shape[0]), cum_var_exp, \n         where = 'mid', label = 'cumulative explained variance')\nplt.ylabel('Explained variance ratio')\nplt.xlabel('Principal components')\nplt.ylim(0, 1.1)\nplt.legend(loc = 'best')\nplt.tight_layout()\n```\n\nThe plot above clearly shows that most of the variance (72.77% of the variance to be precise) can be explained by the first principal component alone. The second principal component still bears some information (23.03%) while the third and fourth principal components can safely be dropped without losing to much information. Together, the first two principal components explains 95.8% of the variance. Or in other words, it contain 95.8% of the information (95% or 99% are comon threshold that people use).\n\n### Projection Onto the New Feature Space\n\nIn the last step, we will use the 4\u00d72-dimensional eigenvectors to transform our samples onto the new subspace via the equation $Y=XW$, where Y will be our 150\u00d72 matrix of transformed samples (we reduce the dimension from the original 4 down to 2).\n\n\n```python\ndef plot_iris_pca(X_pca, y):\n    \"\"\"a scatter plot of the 2-dimensional iris data\"\"\"\n    markers = 's', 'x', 'o'\n    colors = list(plt.rcParams['axes.prop_cycle'])\n    target = np.unique(y)\n    for idx, (t, m) in enumerate( zip(target, markers) ):\n        subset = X_pca[y == t]\n        plt.scatter( subset[:, 0], subset[:, 1], s = 50,\n                     c = colors[idx]['color'], label = t, marker = m )\n\n    plt.xlabel('PC 1')\n    plt.ylabel('PC 2')\n    plt.legend(loc = 'lower left')\n    plt.tight_layout()\n    plt.show()\n```\n\n\n```python\nX_std_pca = X_std.dot(eig_vecs[:, 0:2])\nplot_iris_pca(X_std_pca, y)\n```\n\nWe'll put all of this into a single class, train it and confirm the result with scikit-learn's PCA model by printing out the explained variance ratio.\n\n\n```python\nclass PCAModel:\n    \"\"\"\n    Principal component analysis (PCA)\n    \n    Parameters\n    ----------\n    n_components : int\n        top number of principal components to keep\n    \"\"\"    \n    def __init__(self, n_components):\n        self.n_components = n_components\n\n    def fit(self, X):\n        # standardize\n        X = X.copy()\n        self.mean = np.mean(X, axis = 0)\n        self.scale = np.std(X, axis = 0)\n        X = (X - self.mean) / self.scale\n        \n        # eigendecomposition\n        eig_vals, eig_vecs = np.linalg.eig(np.cov(X.T))\n        self.components = eig_vecs[:, :self.n_components]\n        var_exp = eig_vals / np.sum(eig_vals)\n        self.explained_variance_ratio = var_exp[:self.n_components]\n        return self\n\n    def transform(self, X):\n        X = X.copy()\n        X = (X - self.mean) / self.scale\n        X_pca = X @ self.components\n        return X_pca\n```\n\n\n```python\n# implementation from scratch\npca_model = PCAModel(n_components = 2).fit(X)\n\n# using library to confirm results\nscaler = StandardScaler()\nX_std = scaler.fit_transform(X)\npca = PCA(n_components = 2).fit(X_std)\n\n# print explained ratio to see if the matches\nprint('library: ', pca.explained_variance_ratio_)\nprint('from scratch: ', pca_model.explained_variance_ratio)\n```\n\n    library:  [ 0.72770452  0.23030523]\n    from scratch:  [ 0.72770452  0.23030523]\n\n\n## Takeaway\n\nLet's wrap this up with a summary of PCA and some of its applications. In order to identify patterns in our data, we often look for variation across observations to distinguish them from one another. Hence it seems reasonable to be able to find a succinct representation that best captures the variation in our initial data. PCA, in particular, look to explain our data via its maximum directions of variance. By compressing a higher dimensional dataset into lower one, while still retaining most of the variance this allows us to:\n\n- Perform Visualization: PCA summarizes our data along the principal components (or eigenvectors), which explains most the variance. Thus we can reduce the dataset to 2 or 3 dimensions and visualize our data's distribution. This can be helpful when we're performing clustering algorithm that needs to choose the cluster number beforehand.\n- Speed up machine learning algorithms: When dealing with Big Data, we might want to decompose the features into a lower dimension, without a significant loss in variance. By performing dimensionality reduction methods, we can reduce the amount of features we have to speed up the training algorithm and save memory. For this part, we'll use the Iris dataset again and show that by keeping the data's top 3 principal components we can obtain the same level of accuracy as keeping all 4 features.\n\n\n```python\n# split 30% of the iris data into a test set for evaluation\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, \n                                                    random_state = 1)\n\n# create the pipeline, where we'll\n# standardize the data, perform PCA and\n# fit the logistic regression\npipe1 = Pipeline([\n    ( 'sc', StandardScaler() ),\n    ( 'pca', PCA(n_components = 3) ),\n    ( 'logistic', LogisticRegression(random_state = 1) )\n])\npipe1.fit(X_train, y_train)\ny_pred1 = pipe1.predict(X_test)\n\n# pipeline without PCA\npipe2 = Pipeline([\n    ( 'sc', StandardScaler() ),\n    ( 'logistic', LogisticRegression(random_state = 1) )\n])\npipe2.fit(X_train, y_train)\ny_pred2 = pipe2.predict(X_test)\n\n# access the prediction accuracy\nprint( \"PCA Accuracy %.3f\" % accuracy_score(y_test, y_pred1) )\nprint( \"Accuracy %.3f\" % accuracy_score(y_test, y_pred2) )\n```\n\n    PCA Accuracy 0.822\n    Accuracy 0.822\n\n\n# Reference\n\n- [Youtube: Dimensionality Reduction](https://www.youtube.com/playlist?list=PLnnr1O8OWc6aVexn2BY0qjklobY6TUEIy)\n- [Blog: What are eigenvectors and eigenvalues?](http://www.visiondummy.com/2014/03/eigenvalues-eigenvectors/)\n- [Blog: Principal Component Analysis 4 Dummies](https://georgemdallas.wordpress.com/2013/10/30/principal-component-analysis-4-dummies-eigenvectors-eigenvalues-and-dimension-reduction/)\n- [Blog: Everything you did and didn't know about PCA](http://alexhwilliams.info/itsneuronalblog/2016/03/27/pca/)\n- [Blog: Principal Component Analysis in 3 Simple Steps](http://sebastianraschka.com/Articles/2015_pca_in_3_steps.html)\n- [Notebook: In Depth: Principal Component Analysis](http://nbviewer.jupyter.org/github/jakevdp/PythonDataScienceHandbook/blob/95664b978439df948b2cd2f5f5b4e31f28b30394/notebooks/05.09-Principal-Component-Analysis.ipynb)\n- [StackExchange: Making sense of principal component analysis, eigenvectors & eigenvalues](http://stats.stackexchange.com/questions/2691/making-sense-of-principal-component-analysis-eigenvectors-eigenvalues)\n- [StackExchange: What is an intuitive explanation for how PCA turns from a geometric problem (with distances) to a linear algebra problem (with eigenvectors)?](http://stats.stackexchange.com/questions/217995/what-is-an-intuitive-explanation-for-how-pca-turns-from-a-geometric-problem-wit)\n", "meta": {"hexsha": "e3aa4b592920cfcef2daf675b7bc7a36c749c767", "size": 239894, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "dim_reduct/PCA.ipynb", "max_stars_repo_name": "awesome-archive/machine-learning", "max_stars_repo_head_hexsha": "8494f3fe73db511f7b97d082c786097bfbe71463", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-07-05T09:32:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-05T09:32:31.000Z", "max_issues_repo_path": "dim_reduct/PCA.ipynb", "max_issues_repo_name": "awesome-archive/machine-learning", "max_issues_repo_head_hexsha": "8494f3fe73db511f7b97d082c786097bfbe71463", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dim_reduct/PCA.ipynb", "max_forks_repo_name": "awesome-archive/machine-learning", "max_forks_repo_head_hexsha": "8494f3fe73db511f7b97d082c786097bfbe71463", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 87.3294503094, "max_line_length": 36006, "alphanum_fraction": 0.7774058543, "converted": true, "num_tokens": 19128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.039638836831964216, "lm_q2_score": 0.0284360328390123, "lm_q1q2_score": 0.0011271712658539848}}
{"text": "<a href=\"https://colab.research.google.com/github/EduardoMoraesRitter/voice/blob/master/advanced_outputs.ipynb\" target=\"_parent\"></a>\n\n## Output Handling\n\nIn Colaboratory the output of each cell is hosted in a separate iframe sandbox with limited access to the global notebook environment. APIs are available to enable some Python to Javascript and Javascript to Python communications, these APIs are generally only available for outputs which have been executed in the current session.\n\n\n\n### Viewing Notebooks\n\nColaboratory attempts to provide a rich viewing experience where all resources needed to view outputs are persisted in the notebook itself and can be used for later viewing when not connected to a kernel.\n\nIn cases where outputs require execution to work properly this should be communicated to the user.\n\n## display.Javascript to execute JavaScript from Python\n\nThe Javascript is persisted in the outputs of the notebook document and will be executed when the document is reloaded.\n\n\n```\nimport IPython\njs_code = '''\ndocument.querySelector(\"#output-area\").appendChild(document.createTextNode(\"hello world!\"));\n'''\ndisplay(IPython.display.Javascript(js_code))\n```\n\n## Evaluate a Javascript expression from Python with eval_js\n\nEvaluates the Javascript expression within the context of the outputframe of the current cell.\n\nThis executes the Javascript as a blocking call from Python and returns the result of the expression.\n\nIf the Javascript expression results in a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) then the call will block until the promise has settled and use the resulting value.\n\n**Note:** This differs from `display.Javascript` in that the Javascript expression is not persisted in the notebook document and will not be executed when the document is reloaded.\n\n\n\n```\nimport IPython\nfrom google.colab import output\n\ndisplay(IPython.display.Javascript('''\n  window.someValue = new Promise(resolve => {\n    setTimeout(() => {\n      resolve(\"hello world!\");\n    }, 100);\n  });\n'''))\n\n\nvalue = output.eval_js('someValue');\nvalue\n```\n\n## Javascript to Python communication\n\nPython code can register callbacks which can be invoked by Javascript in the outputframe.\n\n**Note:** This is only available to 'trusted' outputs- outputs which have been executed within the current session.\n\n\n```\nimport IPython\nfrom google.colab import output\n\ndef Concat(a, b):\n  # Use display.JSON to transfer a structured result.\n  return IPython.display.JSON({'result': ' '.join((a, b))})\n\noutput.register_callback('notebook.Concat', Concat)\n```\n\n\n```javascript\n%%javascript\n(async function() {\n  const result = await google.colab.kernel.invokeFunction(\n    'notebook.Concat', // The callback name.\n    ['hello', 'world!'], // The arguments.\n    {}); // kwargs\n  const text = result.data['application/json'];\n  document.querySelector(\"#output-area\").appendChild(document.createTextNode(text.result));\n})();\n```\n\n### Persisting Updates\n\nSince `invokeFunction` is only available for outputs which have executed within the current session\nthen it may be desirable to update the notebook so the changes take effect on notebook reload. An example\nof doing this.\n\n\n```\nimport IPython\nfrom google.colab import output\n\ndisplay(IPython.display.HTML('''\n    The items:\n    <br><ol id=\"items\"></ol>\n    <button id='button'>Click to add</button>\n    \n    '''))\n\ndef add_list_item():\n  # Use redirect_to_element to direct the elements which are being written.\n  with output.redirect_to_element('#items'):\n    # Use display to add items which will be persisted on notebook reload.\n    display(IPython.display.HTML('<li> Another item</li>'))\n\noutput.register_callback('notebook.AddListItem', add_list_item)\n```\n\n### Using register_callback to make a button invoke a function\n\n\n```\nimport IPython\nimport uuid\nfrom google.colab import output\n\nclass InvokeButton(object):\n  def __init__(self, title, callback):\n    self._title = title\n    self._callback = callback\n\n  def _repr_html_(self):\n    callback_id = 'button-' + str(uuid.uuid4())\n    output.register_callback(callback_id, self._callback)\n\n    template = \"\"\"<button id=\"{callback_id}\">{title}</button>\n        \"\"\"\n    html = template.format(title=self._title, callback_id=callback_id)\n    return html\n\ndef do_something():\n  print('here')\n\nInvokeButton('click me', do_something)\n```\n\n## Tagged Outputs\n\nOutput tagging is useful for removing or replacing chunks of outputs from Python.\n\n\n```\nimport time\nimport sys\nfrom google.colab import output\n\nprint('Starting.')\n\nwith output.use_tags('some_outputs'):\n  sys.stdout.write('working....\\n')\n  sys.stdout.flush();\n  time.sleep(2)\n\n  sys.stdout.write('still working...\\n')\n  sys.stdout.flush();\n  time.sleep(2)\n\n# Now clear the previous outputs.\noutput.clear(output_tags='some_outputs')\nprint('All done!')\n\n```\n\n## Pausing output processing\n\nIf your Javascript code is doing an asynchronous operation (such as loading other resources), use `colab.output.pauseOutputUntil` to pause execution of subsequent output messages until the promise has completed.\n\nThis has an additional benefit that when the notebook is later loaded then output will wait for all messages and pauses to complete before resizing the cell, reducing the amount of jank when loading notebooks.\n\n\n```\nimport IPython\n\ndisplay(IPython.display.Javascript('''\n  const promise = new Promise((resolve, reject) => {\n    const script = document.createElement('script');\n    script.src = 'data:,window.value = \"hello world!\"';\n    script.onload = resolve;\n    script.onerror = reject;\n    document.head.appendChild(script);\n  });\n  // Pause subsequent outputs until the script has been loaded.\n  google.colab.output.pauseOutputUntil(promise);\n'''))\n\ndisplay(IPython.display.Javascript('''\n    // Can immediately reference scripts loaded earlier since\n    // output processing was blocked on them.\n    document.body.appendChild(document.createTextNode(window.value));\n'''))\n\n```\n\n## Serving resources\n\nOutputs in the browser can request resources from the kernel by requesting `https://localhost:{port}`. The protocol will automatically be translated from `https` to `http` and the `localhost` will be the kernel executing the code.\n\nBy default the responses to any kernel requests will be cached in the notebook JSON to make them available to viewers not connected to the kernel. To skip the caching of resources, set the HTTP header `x-colab-notebook-cache-control: no-cache` to any responses. See the 'Custom server' example below.\n\nOutputs can only request resources from the kernel if they have been executed in the current session, when viewed the outputs will only have access to the cached responses.\n\n### Jupyter nbextensions\nJupyter's nbextensions is a mechanism to bundle resources into Python libraries, see the [documentation](http://testnb.readthedocs.io/en/latest/examples/Notebook/Distributing%20Jupyter%20Extensions%20as%20Python%20Packages.html#Defining-the-server-extension-and-nbextension) for details.\n\nAn example of referencing these resources from outputs:\n\n\n```\n%%html\n<link rel=\"stylesheet\" href=\"/nbextensions/google.colab/tabbar.css\">\n<div class='goog-tab'>\n  Some content\n</div>\n```\n\n### Custom server\n\nA webserver can be started on the kernel to serve up arbitrary resources.\n\nThe client needs to reference the resource with `https://localhost:{port}` but this will automatically be translated to `http://localhost:{port}`.\n\nBy default responses will be cached in the notebook for offline access.\n\n\n```\nimport portpicker\nimport threading\nimport socket\nimport IPython\n\nfrom six.moves import socketserver\nfrom six.moves import SimpleHTTPServer\n\nclass V6Server(socketserver.TCPServer):\n  address_family = socket.AF_INET6\n\nclass Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):\n  def do_GET(self):\n    self.send_response(200)\n    # If the response should not be cached in the notebook for\n    # offline access:\n    # self.send_header('x-colab-notebook-cache-control', 'no-cache')\n    self.end_headers()\n    self.wfile.write(b'''\n      document.querySelector('#output-area').appendChild(document.createTextNode('Script result!'));\n    ''')\n\nport = portpicker.pick_unused_port()\n\ndef server_entry():\n    httpd = V6Server(('::', port), Handler)\n    # Handle a single request then exit the thread.\n    httpd.serve_forever()\n\nthread = threading.Thread(target=server_entry)\nthread.start()\n\n# Display some HTML referencing the resource.\ndisplay(IPython.display.HTML(''.format(port=port)))\n```\n\n## Cross-output communication\n\nThe output of each cell is hosted in a separate sandboxed iframe without direct access to the contents of other cells, but they can create [BroadcastChannel](https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel/BroadcastChannel)s to communicate between cells.\n\n\n```javascript\n%%javascript\nconst listenerChannel = new BroadcastChannel('channel');\nlistenerChannel.onmessage = (msg) => {\n  const div = document.createElement('div');\n  div.textContent = msg.data;\n  document.body.appendChild(div);\n};\n```\n\nThis second cell will be in a separate sandboxed iframe.\n\n\n\n```javascript\n%%javascript\nconst senderChannel = new BroadcastChannel('channel');\nsenderChannel.postMessage('Hello world!');\n```\n\n## Rendering SymPy in Colab\n\nRendering [SymPy](http://www.sympy.org) equations in Colab requires the MathJax javascript library to be available within each cell output. The following defines an execution hook that loads it automatically each time you execute a cell.\n\n\n```\nfrom IPython.display import Math, HTML\n\ndef load_mathjax_in_cell_output():\n  display(HTML(\"\"))\nget_ipython().events.register('pre_run_cell', load_mathjax_in_cell_output)\n```\n\n\n```\n# try it out:\nimport sympy\nsympy.init_printing()\nx = sympy.symbols('x')\nsympy.Integral(sympy.sqrt(1 / x), x)\n```\n\n## Camera Capture\nUsing a webcam to capture images for processing on the runtime.\n\n\n```\nfrom IPython.display import display, Javascript\nfrom google.colab.output import eval_js\nfrom base64 import b64decode\n\ndef take_photo(filename='photo.jpg', quality=0.8):\n  js = Javascript('''\n    async function takePhoto(quality) {\n      const div = document.createElement('div');\n      const capture = document.createElement('button');\n      capture.textContent = 'Capture';\n      div.appendChild(capture);\n\n      const video = document.createElement('video');\n      video.style.display = 'block';\n      const stream = await navigator.mediaDevices.getUserMedia({video: true});\n\n      document.body.appendChild(div);\n      div.appendChild(video);\n      video.srcObject = stream;\n      await video.play();\n\n      // Resize the output to fit the video element.\n      google.colab.output.setIframeHeight(document.documentElement.scrollHeight, true);\n\n      // Wait for Capture to be clicked.\n      await new Promise((resolve) => capture.onclick = resolve);\n\n      const canvas = document.createElement('canvas');\n      canvas.width = video.videoWidth;\n      canvas.height = video.videoHeight;\n      canvas.getContext('2d').drawImage(video, 0, 0);\n      stream.getVideoTracks()[0].stop();\n      div.remove();\n      return canvas.toDataURL('image/jpeg', quality);\n    }\n    ''')\n  display(js)\n  data = eval_js('takePhoto({})'.format(quality))\n  binary = b64decode(data.split(',')[1])\n  with open(filename, 'wb') as f:\n    f.write(binary)\n  return filename\n```\n\n\n\n\n\n\n```\nfrom IPython.display import Image\ntry:\n  filename = take_photo()\n  print('Saved to {}'.format(filename))\n  \n  # Show the image which was just taken.\n  display(Image(filename))\nexcept Exception as err:\n  # Errors will be thrown if the user does not have a webcam or if they do not\n  # grant the page permission to access it.\n  print(str(err))\n```\n\n\n\n\n\n\n    <IPython.core.display.Javascript object>\n\n\n    Saved to photo.jpg\n\n\n\n    \n\n    \n\n\n## Showing CV2 Images\n\nThe ``cv2.imshow()`` and ``cv.imshow()`` functions from the [opencv-python](https://github.com/skvark/opencv-python) package are incompatible with Jupyter notebook; see https://github.com/jupyter/notebook/issues/3935.\n\nAs a replacement, you can use the following function:\n\n\n```\nfrom google.colab.patches import cv2_imshow\n```\n\nFor example, here we download and display a PNG image of the Colab logo:\n\n\n```\n!curl -o logo.png https://colab.research.google.com/img/colab_favicon_256px.png\nimport cv2\nimg = cv2.imread('logo.png', cv2.IMREAD_UNCHANGED)\ncv2_imshow(img)\n```\n", "meta": {"hexsha": "3829a9fe5e78fd4454d8382751ab0671afd1ae14", "size": 71959, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "advanced_outputs.ipynb", "max_stars_repo_name": "EduardoMoraesRitter/voice", "max_stars_repo_head_hexsha": "e6a5add8a226e7ec26f58553a523510b1270aa6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "advanced_outputs.ipynb", "max_issues_repo_name": "EduardoMoraesRitter/voice", "max_issues_repo_head_hexsha": "e6a5add8a226e7ec26f58553a523510b1270aa6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "advanced_outputs.ipynb", "max_forks_repo_name": "EduardoMoraesRitter/voice", "max_forks_repo_head_hexsha": "e6a5add8a226e7ec26f58553a523510b1270aa6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 87.0120918984, "max_line_length": 44247, "alphanum_fraction": 0.7864617352, "converted": true, "num_tokens": 2683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05108273551243586, "lm_q2_score": 0.021948252635285725, "lm_q1q2_score": 0.001121176784328424}}
{"text": "<style  type=\"text/css\"> \ncool {\n  width: 100px;\n  height: 100px;\n  background-color: red;\n  position: relative;\n  -webkit-animation-name: example; /* Safari 4.0 - 8.0 */\n  -webkit-animation-duration: 4s; /* Safari 4.0 - 8.0 */\n  -webkit-animation-iteration-count: infinite; /* Safari 4.0 - 8.0 */\n  animation-name: example;\n  animation-duration: 4s;\n  animation-iteration-count: infinite;\n}\n\n/* Safari 4.0 - 8.0 */\n@-webkit-keyframes example {\n  0%   {background-color:red; left:0px; top:0px;}\n  25%  {background-color:yellow; left:200px; top:0px;}\n  50%  {background-color:blue; left:200px; top:200px;}\n  75%  {background-color:green; left:0px; top:200px;}\n  100% {background-color:red; left:0px; top:0px;}\n}\n\n/* Standard syntax */\n@keyframes example {\n  0%   {background-color:red; left:0px; top:0px;}\n  25%  {background-color:yellow; left:200px; top:0px;}\n  50%  {background-color:blue; left:200px; top:200px;}\n  75%  {background-color:green; left:0px; top:200px;}\n  100% {background-color:red; left:0px; top:0px;}\n}\n\n\n}\n\n</style>\n\n<b><center>\n    <span style=\"font-size: 24pt; line-height: 1.2;\">COMS W4111: Introduction to Databases</span><br>\n    <span style=\"font-size: 24pt; line-height: 1.2;\">Section 002/V02, Spring, 2022</span><br>\n</center></b>\n<br><br>\n<i><center>\n<span style=\"font-size: 20pt; line-height: 1.2;\">HW 1 Notebook</span>\n</center></i>\n\n\n\n# Introduction\n\nThis notebook has three top level sections:\n1. _Setup_ tests the environment setup, and should work assuming you completed HW0.\n1. _Common Tasks_ are the HW1 tasks for both the programming and non-programming track. All students complete this section.\n2. _Non-Programing Track_ contains the tasks that students in the non-programming track must complete.\n3. _Programming Track_ contains the tasks that students in the programming track must complete.\n\n\nSubmission format:\n\n- All students (both tracks) submit a completed version of this notebook. Students need to complete the setup section, the common section, and the section specific to their track. The submission format is a PDF generated from the notebook. Students can generate the PDF by:\n    - Choosing ```File->Print Preview``` in the notebook's menu bar. This will open a new browser tab.\n    - In the new browser tab, select ```File->Print``` and choose to save as PDF.\n    - **Make sure that everything renders properly in the generated PDF.** Troubleshoot/reach out if you have issues. Images/outputs that render incorrectly will not be graded.\n    \n    \n- All students submit a zip file containing their cloned HW0/1 project, which they got by cloning the [GitHub repository.](https://github.com/donald-f-ferguson/S22-W4111-HW-1-0) Students can:\n    - Open a command/terminal window in the root directory where they cloned the project.\n    - Enter ```git pull``` to retrieve any updates to the project, including required data files.\n    \n    \n- Students can edit the notebook using Anaconda Navigator to open Jupyter Notebook.\n\n\n\n- Students on the programming track also create and modify Python files in the sub-folder ```<UNI>_web_src```. Remember, you should be using a folder with your UNI. In my case, the folder would be ```dff9_web_src.```\n\n\n\n- The zip file you submit should contain __only__ the following sub-folders/files:\n    - ```<UNI>_src.``` (All students) This folder must container your version of this notebook.\n    - ```<UNI>_web_src.``` (Only programming track)\n    - To be clear: the zipped directory for non-programming track submissions should contain **one** file. The corresponding ``zip`` for the programming track should contain **two** files.\n\n\n- Make sure to submit your notebook in the PDF format separately from the zip file, based on your track as well. That is, you need to make __two__ submissions in total like below:\n    - Submit your notebook file in PDF format to ```Homework 1: Non-programming or Programming``` __(Make sure that you assigned pages properly).__\n    - Submit your zip file to ```Homework 1: Zip File Submission```\n\n# Setup\n\n__Note:__ You will have to put the correct user ID and password in the connection strings below, e.g. replace ```dbuser``` and ```dbuserdbuser.```\n\n## iPython-SQL\n\n\n```python\n%load_ext sql\n```\n\n\n```python\n%sql mysql+pymysql://dbuser:dbuserdbuser@localhost\n```\n\n\n\n\n    'Connected: dbuser@None'\n\n\n\n\n```python\n%sql select * from db_book.student where name like \"z%\" or name like \"sh%\"\n```\n\n     * mysql+pymysql://dbuser:***@localhost\n    2 rows affected.\n\n\n\n\n\n<table>\n    <tr>\n        <th>ID</th>\n        <th>name</th>\n        <th>dept_name</th>\n        <th>tot_cred</th>\n        <th>student_no</th>\n    </tr>\n    <tr>\n        <td>00128</td>\n        <td>Zhang</td>\n        <td>Comp. Sci.</td>\n        <td>102</td>\n        <td></td>\n    </tr>\n    <tr>\n        <td>12345</td>\n        <td>Shankar</td>\n        <td>Comp. Sci.</td>\n        <td>32</td>\n        <td></td>\n    </tr>\n</table>\n\n\n\n## PyMySQL\n\n\n```python\nimport pymysql\n```\n\n\n```python\nconn = pymysql.connect(host=\"localhost\", user=\"dbuser\", password=\"dbuserdbuser\")\n```\n\n\n```python\nsql = \"\"\"\n    select * from db_book.student where\n        name like %s or name like %s\n\"\"\"\n```\n\n\n```python\npattern_1 = \"z%\"\npattern_2 = \"sh%\"\n```\n\n\n```python\ncur = conn.cursor()\nres = cur.execute(\n    sql, args=(pattern_1, pattern_2)\n)\nres = cur.fetchall()\n```\n\n\n```python\nres\n```\n\n\n\n\n    (('00128', 'Zhang', 'Comp. Sci.', Decimal('102'), ''),\n     ('12345', 'Shankar', 'Comp. Sci.', Decimal('32'), ''))\n\n\n\n## Pandas\n\n\n```python\nimport pandas as pd\n```\n\n\n```python\n#\n#  Replace the path below with the path of your project directory.\n#  Use // instead of / if you're on Windows.\n#\nproject_root = \"/Users/donaldferguson/Dropbox/Columbia/W4111-Intro-to-DB-S22/HWs/S22-W4111-HW-1-0\"\n\n```\n\n\n```python\npeople_df = pd.read_csv(project_root + \"/data/People.csv\")\n```\n\n\n```python\npeople_df.loc[\n    (people_df['nameLast'] == \"Williams\") & (people_df['birthCity'] == 'San Diego'),\n    [\"playerID\", \"nameLast\", \"nameFirst\", \"birthYear\", 'birthCity', 'bats', 'throws']\n]\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>playerID</th>\n      <th>nameLast</th>\n      <th>nameFirst</th>\n      <th>birthYear</th>\n      <th>birthCity</th>\n      <th>bats</th>\n      <th>throws</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>19773</td>\n      <td>willite01</td>\n      <td>Williams</td>\n      <td>Ted</td>\n      <td>1918.0</td>\n      <td>San Diego</td>\n      <td>L</td>\n      <td>R</td>\n    </tr>\n    <tr>\n      <td>19776</td>\n      <td>willitr01</td>\n      <td>Williams</td>\n      <td>Trevor</td>\n      <td>1992.0</td>\n      <td>San Diego</td>\n      <td>R</td>\n      <td>R</td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n## SQLAlchemy\n\n\n```python\nfrom sqlalchemy import create_engine\n```\n\n\n```python\nengine = create_engine(\"mysql+pymysql://dbuser:dbuserdbuser@localhost\")\n```\n\n\n```python\nsql = \"\"\"\n    select * from db_book.student where\n        name like %s or name like %s\n\"\"\"\npattern_1 = \"z%\"\npattern_2 = \"sh%\"\n```\n\n\n```python\nanother_df = pd.read_sql(sql, params=(pattern_1, pattern_2), con=engine)\nanother_df\n```\n\n\n\n\n<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>ID</th>\n      <th>name</th>\n      <th>dept_name</th>\n      <th>tot_cred</th>\n      <th>student_no</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>0</td>\n      <td>00128</td>\n      <td>Zhang</td>\n      <td>Comp. Sci.</td>\n      <td>102.0</td>\n      <td></td>\n    </tr>\n    <tr>\n      <td>1</td>\n      <td>12345</td>\n      <td>Shankar</td>\n      <td>Comp. Sci.</td>\n      <td>32.0</td>\n      <td></td>\n    </tr>\n  </tbody>\n</table>\n</div>\n\n\n\n# Common Tasks\n\n## Schema and Data Modeling\n\n- There are three entity types:\n    1. Employee with attributes:\n        - employee_no\n        - last_name\n        - first_name\n    2. Department with attributes\n        - department_id\n        - department_name\n    3. Applicant with attributes:\n        - email\n        - last_name\n        - first_name\n        \n\n### Relational Schema\n\n- Using the notation from the textbook slides and lecture notes, define the relation definitions for each of the entity types. That is, the schema definition for the relations. You will need to choose a primary key.\n\n\n- The snippet below shows how to use under-bar.\n\n\\begin{equation}\nThis\\ is\\ a\\ sentence\\ with\\ someting\\_in\\_parentheses(\n    \\underline{something}, another\\_thing)\\  and\\ something\\ with\\ underbar.\n\\end{equation}\n\nYou can double click on the cell above to see the source, which is\n```\n\\begin{equation}\nThis\\ is\\ a\\ sentence\\ with\\ someting\\_in\\_parentheses(\n    \\underline{something}, another\\_thing)\\  and\\ something\\ with\\ underbar.\n\\end{equation}\n```\n\nPut your relation definitions below between the horizontal lines.\n\n<hr style=\"height: 1px\";>\n\n<br><br>\n\n<hr style=\"height: 1px\";>\n\n\n### ER Modeling\n\n- Continuing the example above:\n    - An _employee_ is a _member\\_of_ exactly one department.\n    - An _applicant_ has exactly one _employee_ who is _sponsor\\_of_ of the applicant.\n    - An _applicant_ may have specified a _department_ that is the _applicant's_ _preferred\\_dept._\n    \n    \n- Use [Lucidchart](https://www.lucidchart.com) to draw the logical diagram.\n\n\n- __Note:__ You may have to add columns/attributes to some tables to implement the relationships.\n\n\n- To submit the diagram, take a screen capture and modify the cell below to load your diagram from the file system. The following is an example for how to include the screenshot.\n    \n\n\n```python\ner_model_file_name = 'sample_diagram.png'\n\nprint(\"\\n\")\nfrom IPython.display import Image\nImage(filename=er_model_file_name)\n```\n\n## Relational Algebra\n\n### Instructions\n\n- You will use the [RelaX](https://dbis-uibk.github.io/relax/calc/gist/4f7866c17624ca9dfa85ed2482078be8/relax-silberschatz-english.txt/0) online relational algebra calculator.\n\n\n- You must use the dataset ```Silberschatz - UniversityDB.``` I demonstrated how to select a dataset during a lecture.\n\n\n- For submitting your answer, you must:\n    - Cut and paste your relational expression in text.\n    - Take a screenshot and include the image.\n    \n    \n- The following is an example question and answer.\n\n### Example\n\n__Question:__ Produce a table of the form ```(course_id, title, prereq_id, preqreq_title)``` that lists courses and their prereqs.\n\n\n<hr style=\"height:1px;\">\n\n```\n\u03c0 course_id, title, prereq_id, prereq_title\n\t(\n\t\t(\u03c0 course_id, title, prereq_id (course \u2a1d prereq))\n\t\t\u2a1d prereq_id=x\n\t\t(\u03c0 x\u2190course_id, prereq_title\u2190title (course))\n)\n```\n\n\n```python\ner_model_file_name = 'sample_answer_q.png'\n\nprint(\"\\n\")\nfrom IPython.display import Image\nImage(filename=er_model_file_name)\n```\n\n<hr style=\"height: 1px;\">\n\n### Relational Algebra Q1\n\n- Use ```student, advisor``` and ```instructor``` for this question.\n\n\n- Produce a table of the form ```(student.ID, student.name, instructor.ID, instructor.name)``` that shows students and their advisors.\n\n<hr style=\"height: 1px;\">\n\nPut you relational algebra and loading screenshot here.\n\n<hr style=\"height: 1px;\">\n\n### Relational Algebra Q2\n\n- Use ```student``` and ```takes``` for this question.\n\n\n- Produce a table of the form ```(student.ID, student.name, student,tot_cred, student_dept_name)``` for students that have not taken any course/section.\n\n<hr style=\"height: 1px;\">\n\nPut you relational algebra and loading screenshot here.\n\n<hr style=\"height: 1px;\">\n\n## SQL\n\n### Instructions\n\n- The questions in this section ask you to write and execute SQL statements.\n\n\n- Your answer should be a code cell with ```%sql``` and your query.\n\n\n- You must execute the query.\n\n### Example\n\n- This is the SQL version of the query from the relational algebra section above.\n\n\n<hr style=\"height: 1px;\">\n\n\n```sql\n%%sql\nuse db_book;\n\nselect a.course_id as course_id,\n       a.title as title,\n       prereq_id,\n       b.title as prereq_tiles\nfrom\n              (select course_id, title, prereq_id from course join prereq using(course_id)) as a\njoin\n    course as b on a.prereq_id=b.course_id\n```\n\n     * mysql+pymysql://dbuser:***@localhost\n    0 rows affected.\n    7 rows affected.\n\n\n\n\n\n<table>\n    <tr>\n        <th>course_id</th>\n        <th>title</th>\n        <th>prereq_id</th>\n        <th>prereq_tiles</th>\n    </tr>\n    <tr>\n        <td>BIO-301</td>\n        <td>Genetics</td>\n        <td>BIO-101</td>\n        <td>Intro. to Biology</td>\n    </tr>\n    <tr>\n        <td>BIO-399</td>\n        <td>Computational Biology</td>\n        <td>BIO-101</td>\n        <td>Intro. to Biology</td>\n    </tr>\n    <tr>\n        <td>CS-190</td>\n        <td>Game Design</td>\n        <td>CS-101</td>\n        <td>Intro. to Computer Science</td>\n    </tr>\n    <tr>\n        <td>CS-315</td>\n        <td>Robotics</td>\n        <td>CS-101</td>\n        <td>Intro. to Computer Science</td>\n    </tr>\n    <tr>\n        <td>CS-319</td>\n        <td>Image Processing</td>\n        <td>CS-101</td>\n        <td>Intro. to Computer Science</td>\n    </tr>\n    <tr>\n        <td>CS-347</td>\n        <td>Database System Concepts</td>\n        <td>CS-101</td>\n        <td>Intro. to Computer Science</td>\n    </tr>\n    <tr>\n        <td>EE-181</td>\n        <td>Intro. to Digital Systems</td>\n        <td>PHY-101</td>\n        <td>Physical Principles</td>\n    </tr>\n</table>\n\n\n\n<hr style=\"height: 1px;\">\n\n### SQL Question 1\n\n- Translate your answer from Relational Algebra Q1 into SQL.\n\n\n- Do not worry about correctly naming the columns.\n\n\n<hr style=\"height: 1px\">\n\n\n```sql\n%%sql\n\n```\n\n<hr style=\"height: 1px\">\n\n### SQL Question 2\n\n- You guessed it.\n\n\n- Translate your answer from Relational Algebra Q2 into SQL.\n\n\n- Do not worry about correctly naming the columns.\n\n\n<hr style=\"height: 1px\">\n\n\n```sql\n%%sql\n\n```\n\n<hr style=\"height: 1px\">\n\n### SQL Question 3\n\n\n- The following query makes a copy of the ```department``` table.\n\n\n```sql\n%%sql\n\ndrop table if exists hw1_department;\ncreate table hw1_department as select * from department\n```\n\n     * mysql+pymysql://dbuser:***@localhost\n    0 rows affected.\n    7 rows affected.\n\n\n\n\n\n    []\n\n\n\n- The next query shows the content.\n\n\n```python\n%sql select * from db_book.hw1_department\n```\n\n     * mysql+pymysql://dbuser:***@localhost\n    7 rows affected.\n\n\n\n\n\n<table>\n    <tr>\n        <th>dept_name</th>\n        <th>building</th>\n        <th>budget</th>\n    </tr>\n    <tr>\n        <td>Biology</td>\n        <td>Watson</td>\n        <td>90000.00</td>\n    </tr>\n    <tr>\n        <td>Comp. Sci.</td>\n        <td>Taylor</td>\n        <td>100000.00</td>\n    </tr>\n    <tr>\n        <td>Elec. Eng.</td>\n        <td>Taylor</td>\n        <td>85000.00</td>\n    </tr>\n    <tr>\n        <td>Finance</td>\n        <td>Painter</td>\n        <td>120000.00</td>\n    </tr>\n    <tr>\n        <td>History</td>\n        <td>Painter</td>\n        <td>50000.00</td>\n    </tr>\n    <tr>\n        <td>Music</td>\n        <td>Packard</td>\n        <td>80000.00</td>\n    </tr>\n    <tr>\n        <td>Physics</td>\n        <td>Watson</td>\n        <td>70000.00</td>\n    </tr>\n</table>\n\n\n\n- You have two tasks for this question.\n    1. Create a new table ```db_book.hw1_schools``` that has columns ```school_id``` and ```school_name.```\n    2. Modify table ```db_boot.hw1_department``` to contain a columns ```school_id.```\n    \n    \n- __Notes:__\n    - You do not have to worry about foreign keys.\n    - You do not need to populate any data or link ```school_id``` to the ```hw1_schools.```\n    - You can use DataGrip or another tool to produce the SQL DDL, but you must show successful execution on the code cells below.\n\n<hr style=\"height: 1px\">\n\n\n```sql\n%%sql\n\n```\n\n<hr style=\"height: 1px\">\n\n# Non-Programming Track\n\n## Tasks\n\n- There is a subdirectory in the project ```data/GoT``` that contains three CSV files:\n    - ```characters.csv```\n    - ```episodes.csv```\n    - ```character_relationships.csv```\n    \n    \n- Your first task is to create tables to hold the data.\n    - This means you must create three tables. Use a new schema and create the three tables:\n        - ```S22_W4111_HW1.characters```\n        - ```S22_W4111_HW1.episodes```\n        - ```S22_W4111_HW1.character_relationships.```\n    - The table must have a column for each of the columns in the CSV.\n    - You can use DataGrip or another tool to produce the create table statements, but you must execute the DDL statements in the code cells.\n    \n    \n- Your second task is to load the data from the CSV files into the newly created tables. Do do this, you use a ```LOAD``` statement.\n\n\n- Finally, you should examine the data and change column types to better reflect the actual values in the columns.\n    \n    \n- To make the instruction more clear, I do an example of the tasks for another table. This is ```got_imdb_names.csv.``` You will do similar steps for the files above.\n\n## Example\n\n- Manual examining the CSV file shows that the data has the following attributes.\n    - ```nconst```\n    - ```primaryName```\n    - ```birthYear```\n    - ```deathYear```\n    - ```primaryProfession```\n    - ```knownForTitles```\n    \n    \n- So, my first step is to create a table to hold the information.\n\n\n- __Note:__ I have dozens of schema. So, I am prefixing this one with ```aaaa_``` to make it easy for me to find. You can drop this prefix.\n\n\n- The following are the statements for creating the schema and table.\n\n\n```python\n# Create the schema if it does not exist.\n%sql create schema if not exists aaaa_S22_W4111_HW1;\n```\n\n\n```python\n# Drop the table if it exists.\n%sql drop table if exists aaaa_S22_W4111_HW1.got_imdb_actors;\n```\n\n- Now create the table.\n\n\n```sql\n%%sql\ncreate table if not exists aaaa_S22_W4111_HW1.got_imdb_actors\n(\n\tnconst text null,\n\tprimaryName text null,\n\tbirthYear text null,\n\tdeathYear text null,\n\tprimaryProfession text null,\n\tknownForTitles text null\n);\n```\n\n- This is where it gets real and you do some wizard stuff.\n\n\n```python\n# This command allows loading CSV files from the local disk.\n# This is set of OFF by default.\n# You should only have to run this once, that is if you execute the example, you do not need to do again.\n#\n%sql SET GLOBAL local_infile = 'ON';\n```\n\n\n```python\n# This is creating a connection to the database.\n# You need to replace the user and passsword with your values for your installation of MySQL.\n# Do not ask about the local_infile. That is Voldemort stuff.\n#\ncon = pymysql.connect(host=\"localhost\",\n                        user=\"dbuser\",\n                        password=\"dbuserdbuser\",\n                        autocommit=True,\n                        local_infile=1)\n```\n\n\n```python\n# This statement performs the load.\n# You will need to change the TABLE name and the INFILE to the correct values.\n#\nsql = \"\"\"\nLOAD DATA LOCAL INFILE\n'/Users/donaldferguson/Dropbox/Columbia/W4111-Intro-to-DB-S22/HWs/S22-W4111-HW-1-0/data/GoT/got_imdb_actors.csv'\nINTO TABLE aaaa_S22_W4111_HW1.got_imdb_actors\n    FIELDS TERMINATED BY ','\n    ENCLOSED BY '\"'\n    LINES TERMINATED BY '\\n'\n    IGNORE 1 LINES;\n\"\"\"\n```\n\n\n```python\n# Create a cursor. Again. Voldemort stuff, or maybe Sauron stuff.\n#\ncur = con.cursor()\n```\n\n\n```python\n# Run the sql\ncur.execute(sql)\n```\n\n\n```python\n# Close the cursor. Sort of like the opposite of alohomora\ncur.close()\n```\n\n\n```python\n# Now test that your loading worked.\n%sql select * from aaaa_S22_W4111_HW1.got_imdb_actors;\n```\n\n\n```python\n%sql select * from aaaa_S22_W4111_HW1.characters;\n```\n\n- The final part of the task for each of the tables will be making some corrections.\n\n\n- We would only ask you to do two or three corrections per table.\n\n\n- Mine for this example would be in the following.\n\n\n```sql\n%%sql\n\nuse aaaa_S22_W4111_HW1;\n\nalter table got_imdb_actors modify nconst varchar(12) null;\n\nalter table got_imdb_actors modify primaryName varchar(256) null;\n\nalter table got_imdb_actors modify birthYear char(4) null;\n\nalter table got_imdb_actors modify deathYear char(4) null;\n\n\n```\n\n## Characters\n\n- Perform the tasks for characters.\n\n## Episodes\n\n- Perform the tasks for episodes.\n\n## Characters Relatrionships\n\n- Perform the tasks for character_relationships.\n\n# Programming Track\n\nNote: If you have activated [student license](https://www.jetbrains.com/community/education/#students) when installing Datagrip, you can also use Pycharm [Professional version](https://www.jetbrains.com/pycharm/download/#section=mac) instead of Community edition.\n    \n\n## Tasks\n\n- You will create and modify files in the directory ```<uni>_web_src.```\n\n\n- You will use the database that comes with the book, e.g. ```db_book,``` that you previously installed.\n\n\n- Your web application will support ```GET``` on the path ```/api/db_book/students/<ID>.``` This means you have to implement two things:\n    1. A function in ```application.py``` that implements the path endpoint.\n    2. A method on a class ```Student``` that connects to the database, runs the SQL and returns the result. The project has been updated to have implementation templates for where your code goes.\n    \n    \n- For submission, you must copy your code from the Python file below to show your code.\n\n\n- You must include a screenshot of calling your application from a browser.\n\n## Modified application.py\n\n```\nfrom flask import Flask, Response, request\nimport json\nfrom datetime import datetime\nimport rest_utils\n\napp = Flask(__name__)\n\n\n##################################################################################################################\n\n# DFF TODO A real service would have more robust health check methods.\n# This path simply echoes to check that the app is working.\n# The path is /health and the only method is GETs\n@app.route(\"/health\", methods=[\"GET\"])\ndef health_check():\n    rsp_data = {\"status\": \"healthy\", \"time\": str(datetime.now())}\n    rsp_str = json.dumps(rsp_data)\n    rsp = Response(rsp_str, status=200, content_type=\"application/json\")\n    return rsp\n\n\n# TODO Remove later. Solely for explanatory purposes.\n# The method take any REST request, and produces a response indicating what\n# the parameters, headers, etc. are. This is simply for education purposes.\n#\n@app.route(\"/api/demo/<parameter1>\", methods=[\"GET\", \"POST\", \"PUT\", \"DELETE\"])\n@app.route(\"/api/demo/\", methods=[\"GET\", \"POST\", \"PUT\", \"DELETE\"])\ndef demo(parameter1=None):\n    \"\"\"\n    Returns a JSON object containing a description of the received request.\n\n    :param parameter1: The first path parameter.\n    :return: JSON document containing information about the request.\n    \"\"\"\n\n    # DFF TODO -- We should wrap with an exception pattern.\n    #\n\n    # Mostly for isolation. The rest of the method is isolated from the specifics of Flask.\n    inputs = rest_utils.RESTContext(request, {\"parameter1\": parameter1})\n\n    # DFF TODO -- We should replace with logging.\n    r_json = inputs.to_json()\n    msg = {\n        \"/demo received the following inputs\": inputs.to_json()\n    }\n    print(\"/api/demo/<parameter> received/returned:\\n\", msg)\n\n    rsp = Response(json.dumps(msg), status=200, content_type=\"application/json\")\n    return rsp\n\n##################################################################################################################\n\n\n@app.route(\"/api/db_book/students/<ID>\", methods=[\"GET\"])\ndef get_student_by_id(ID):\n    #\n    # Your code goes here.\n    #\n    pass\n\n\nif __name__ == '__main__':\n    app.run(host=\"0.0.0.0\", port=5000)\n\n```\n\n## Modified student_resource.py\n\n```\n\nclass Student:\n    \n    def __init__(self):\n        # You may have to put code here.\n        pass\n    \n    def get_by_id(self, ID):\n        # Connect to DB.\n        # Form SQL\n        # Run query\n        # return result\n        pass\n```\n\n## Screen Capture of Calling from Browser\n\n\n", "meta": {"hexsha": "7b4d9c9af2d3fe7aca22f3c8184c9921e4358747", "size": 237396, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "dff9_src/dff9_S22_W4111_HW1.ipynb", "max_stars_repo_name": "Victor4220/4111", "max_stars_repo_head_hexsha": "bf2aa4031afa31ec4b5063faef8817859b1b86e7", "max_stars_repo_licenses": ["OML"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dff9_src/dff9_S22_W4111_HW1.ipynb", "max_issues_repo_name": "Victor4220/4111", "max_issues_repo_head_hexsha": "bf2aa4031afa31ec4b5063faef8817859b1b86e7", "max_issues_repo_licenses": ["OML"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dff9_src/dff9_S22_W4111_HW1.ipynb", "max_forks_repo_name": "Victor4220/4111", "max_forks_repo_head_hexsha": "bf2aa4031afa31ec4b5063faef8817859b1b86e7", "max_forks_repo_licenses": ["OML"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 141.9832535885, "max_line_length": 126244, "alphanum_fraction": 0.8766028071, "converted": true, "num_tokens": 6529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.036220054824630414, "lm_q2_score": 0.029760096635105256, "lm_q1q2_score": 0.0010779123317098114}}
{"text": "**Installation**\r\n\r\nThis tutorial shows the details of installation on Google Golaboratory.\n\n**Step 1**\r\n\r\nInstall Anaconda and set PATH\n\n\n```\n!wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh\r\n!bash Miniconda3-latest-Linux-x86_64.sh -b -f -p /usr/local\r\nimport sys\r\nsys.path.append('/usr/local/lib/python3.6/site-packages/')\n```\n\n    --2021-01-29 10:32:09--  https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh\n    Resolving repo.continuum.io (repo.continuum.io)... 104.18.200.79, 104.18.201.79, 2606:4700::6812:c94f, ...\n    Connecting to repo.continuum.io (repo.continuum.io)|104.18.200.79|:443... connected.\n    HTTP request sent, awaiting response... 301 Moved Permanently\n    Location: https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh [following]\n    --2021-01-29 10:32:09--  https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh\n    Resolving repo.anaconda.com (repo.anaconda.com)... 104.16.131.3, 104.16.130.3, 2606:4700::6810:8203, ...\n    Connecting to repo.anaconda.com (repo.anaconda.com)|104.16.131.3|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 94235922 (90M) [application/x-sh]\n    Saving to: \u2018Miniconda3-latest-Linux-x86_64.sh\u2019\n    \n    Miniconda3-latest-L 100%[===================>]  89.87M   252MB/s    in 0.4s    \n    \n    2021-01-29 10:32:09 (252 MB/s) - \u2018Miniconda3-latest-Linux-x86_64.sh\u2019 saved [94235922/94235922]\n    \n    PREFIX=/usr/local\n    Unpacking payload ...\n    Collecting package metadata (current_repodata.json): - \b\b\\ \b\b| \b\bdone\n    Solving environment: - \b\b\\ \b\bdone\n    \n    ## Package Plan ##\n    \n      environment location: /usr/local\n    \n      added / updated specs:\n        - _libgcc_mutex==0.1=main\n        - brotlipy==0.7.0=py38h27cfd23_1003\n        - ca-certificates==2020.10.14=0\n        - certifi==2020.6.20=pyhd3eb1b0_3\n        - cffi==1.14.3=py38h261ae71_2\n        - chardet==3.0.4=py38h06a4308_1003\n        - conda-package-handling==1.7.2=py38h03888b9_0\n        - conda==4.9.2=py38h06a4308_0\n        - cryptography==3.2.1=py38h3c74f83_1\n        - idna==2.10=py_0\n        - ld_impl_linux-64==2.33.1=h53a641e_7\n        - libedit==3.1.20191231=h14c3975_1\n        - libffi==3.3=he6710b0_2\n        - libgcc-ng==9.1.0=hdf63c60_0\n        - libstdcxx-ng==9.1.0=hdf63c60_0\n        - ncurses==6.2=he6710b0_1\n        - openssl==1.1.1h=h7b6447c_0\n        - pip==20.2.4=py38h06a4308_0\n        - pycosat==0.6.3=py38h7b6447c_1\n        - pycparser==2.20=py_2\n        - pyopenssl==19.1.0=pyhd3eb1b0_1\n        - pysocks==1.7.1=py38h06a4308_0\n        - python==3.8.5=h7579374_1\n        - readline==8.0=h7b6447c_0\n        - requests==2.24.0=py_0\n        - ruamel_yaml==0.15.87=py38h7b6447c_1\n        - setuptools==50.3.1=py38h06a4308_1\n        - six==1.15.0=py38h06a4308_0\n        - sqlite==3.33.0=h62c20be_0\n        - tk==8.6.10=hbc83047_0\n        - tqdm==4.51.0=pyhd3eb1b0_0\n        - urllib3==1.25.11=py_0\n        - wheel==0.35.1=pyhd3eb1b0_0\n        - xz==5.2.5=h7b6447c_0\n        - yaml==0.2.5=h7b6447c_0\n        - zlib==1.2.11=h7b6447c_3\n    \n    \n    The following NEW packages will be INSTALLED:\n    \n      _libgcc_mutex      pkgs/main/linux-64::_libgcc_mutex-0.1-main\n      brotlipy           pkgs/main/linux-64::brotlipy-0.7.0-py38h27cfd23_1003\n      ca-certificates    pkgs/main/linux-64::ca-certificates-2020.10.14-0\n      certifi            pkgs/main/noarch::certifi-2020.6.20-pyhd3eb1b0_3\n      cffi               pkgs/main/linux-64::cffi-1.14.3-py38h261ae71_2\n      chardet            pkgs/main/linux-64::chardet-3.0.4-py38h06a4308_1003\n      conda              pkgs/main/linux-64::conda-4.9.2-py38h06a4308_0\n      conda-package-han~ pkgs/main/linux-64::conda-package-handling-1.7.2-py38h03888b9_0\n      cryptography       pkgs/main/linux-64::cryptography-3.2.1-py38h3c74f83_1\n      idna               pkgs/main/noarch::idna-2.10-py_0\n      ld_impl_linux-64   pkgs/main/linux-64::ld_impl_linux-64-2.33.1-h53a641e_7\n      libedit            pkgs/main/linux-64::libedit-3.1.20191231-h14c3975_1\n      libffi             pkgs/main/linux-64::libffi-3.3-he6710b0_2\n      libgcc-ng          pkgs/main/linux-64::libgcc-ng-9.1.0-hdf63c60_0\n      libstdcxx-ng       pkgs/main/linux-64::libstdcxx-ng-9.1.0-hdf63c60_0\n      ncurses            pkgs/main/linux-64::ncurses-6.2-he6710b0_1\n      openssl            pkgs/main/linux-64::openssl-1.1.1h-h7b6447c_0\n      pip                pkgs/main/linux-64::pip-20.2.4-py38h06a4308_0\n      pycosat            pkgs/main/linux-64::pycosat-0.6.3-py38h7b6447c_1\n      pycparser          pkgs/main/noarch::pycparser-2.20-py_2\n      pyopenssl          pkgs/main/noarch::pyopenssl-19.1.0-pyhd3eb1b0_1\n      pysocks            pkgs/main/linux-64::pysocks-1.7.1-py38h06a4308_0\n      python             pkgs/main/linux-64::python-3.8.5-h7579374_1\n      readline           pkgs/main/linux-64::readline-8.0-h7b6447c_0\n      requests           pkgs/main/noarch::requests-2.24.0-py_0\n      ruamel_yaml        pkgs/main/linux-64::ruamel_yaml-0.15.87-py38h7b6447c_1\n      setuptools         pkgs/main/linux-64::setuptools-50.3.1-py38h06a4308_1\n      six                pkgs/main/linux-64::six-1.15.0-py38h06a4308_0\n      sqlite             pkgs/main/linux-64::sqlite-3.33.0-h62c20be_0\n      tk                 pkgs/main/linux-64::tk-8.6.10-hbc83047_0\n      tqdm               pkgs/main/noarch::tqdm-4.51.0-pyhd3eb1b0_0\n      urllib3            pkgs/main/noarch::urllib3-1.25.11-py_0\n      wheel              pkgs/main/noarch::wheel-0.35.1-pyhd3eb1b0_0\n      xz                 pkgs/main/linux-64::xz-5.2.5-h7b6447c_0\n      yaml               pkgs/main/linux-64::yaml-0.2.5-h7b6447c_0\n      zlib               pkgs/main/linux-64::zlib-1.2.11-h7b6447c_3\n    \n    \n    Preparing transaction: / \b\b- \b\b\\ \b\bdone\n    Executing transaction: / \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\bdone\n    installation finished.\n    WARNING:\n        You currently have a PYTHONPATH environment variable set. This may cause\n        unexpected behavior when running the Python interpreter in Miniconda3.\n        For best results, please verify that your PYTHONPATH only points to\n        directories of packages that are compatible with the Python interpreter\n        in Miniconda3: /usr/local\n\n\n**step 2**\r\n\r\nInstall RDKit and check version.\n\n\n```\n!conda install -q -y -c rdkit rdkit=2020.3 python=3.6\r\nimport rdkit\r\nprint(rdkit.__version__)\n```\n\n    Collecting package metadata (current_repodata.json): ...working... done\n    Solving environment: ...working... failed with initial frozen solve. Retrying with flexible solve.\n    Solving environment: ...working... failed with repodata from current_repodata.json, will retry with next repodata source.\n    Collecting package metadata (repodata.json): ...working... done\n    Solving environment: ...working... done\n    \n    ## Package Plan ##\n    \n      environment location: /usr/local\n    \n      added / updated specs:\n        - python=3.6\n        - rdkit=2020.3\n    \n    \n    The following packages will be downloaded:\n    \n        package                    |            build\n        ---------------------------|-----------------\n        blas-1.0                   |              mkl           6 KB\n        brotlipy-0.7.0             |py36h27cfd23_1003         320 KB\n        bzip2-1.0.8                |       h7b6447c_0          78 KB\n        ca-certificates-2021.1.19  |       h06a4308_0         121 KB\n        cairo-1.14.12              |       h8948797_3         906 KB\n        certifi-2020.12.5          |   py36h06a4308_0         140 KB\n        cffi-1.14.4                |   py36h261ae71_0         223 KB\n        chardet-3.0.4              |py36h06a4308_1003         180 KB\n        conda-4.9.2                |   py36h06a4308_0         2.9 MB\n        conda-package-handling-1.7.2|   py36h03888b9_0         886 KB\n        cryptography-3.3.1         |   py36h3c74f83_0         557 KB\n        fontconfig-2.13.0          |       h9420a91_0         227 KB\n        freetype-2.10.4            |       h5ab3b9f_0         596 KB\n        glib-2.66.1                |       h92f7085_0         2.9 MB\n        icu-58.2                   |       he6710b0_3        10.5 MB\n        intel-openmp-2020.2        |              254         786 KB\n        jpeg-9b                    |       h024ee3a_2         214 KB\n        lcms2-2.11                 |       h396b838_0         307 KB\n        libboost-1.67.0            |       h46d08c1_4        13.0 MB\n        libpng-1.6.37              |       hbc83047_0         278 KB\n        libtiff-4.1.0              |       h2733197_1         449 KB\n        libuuid-1.0.3              |       h1bed415_2          15 KB\n        libxcb-1.14                |       h7b6447c_0         505 KB\n        libxml2-2.9.10             |       hb55368b_3         1.2 MB\n        lz4-c-1.9.3                |       h2531618_0         186 KB\n        mkl-2020.2                 |              256       138.3 MB\n        mkl-service-2.3.0          |   py36he8ac12f_0          52 KB\n        mkl_fft-1.2.0              |   py36h23d657b_0         149 KB\n        mkl_random-1.1.1           |   py36h0573a6f_0         327 KB\n        numpy-1.19.2               |   py36h54aff64_0          22 KB\n        numpy-base-1.19.2          |   py36hfa32c7d_0         4.1 MB\n        olefile-0.46               |           py36_0          48 KB\n        openssl-1.1.1i             |       h27cfd23_0         2.5 MB\n        pandas-1.1.5               |   py36ha9443f7_0         8.2 MB\n        pcre-8.44                  |       he6710b0_0         212 KB\n        pillow-8.1.0               |   py36he98fc37_0         626 KB\n        pip-20.3.3                 |   py36h06a4308_0         1.8 MB\n        pixman-0.40.0              |       h7b6447c_0         370 KB\n        py-boost-1.67.0            |   py36h04863e7_4         278 KB\n        pycosat-0.6.3              |   py36h27cfd23_0          82 KB\n        pysocks-1.7.1              |   py36h06a4308_0          31 KB\n        python-3.6.12              |       hcff3b4d_2        29.7 MB\n        python-dateutil-2.8.1      |             py_0         215 KB\n        pytz-2020.5                |     pyhd3eb1b0_0         182 KB\n        rdkit-2020.03.3.0          |   py36hc20afe1_1        24.7 MB  rdkit\n        ruamel_yaml-0.15.87        |   py36h7b6447c_1         244 KB\n        setuptools-52.0.0          |   py36h06a4308_0         724 KB\n        six-1.15.0                 |   py36h06a4308_0          27 KB\n        zstd-1.4.5                 |       h9ceee32_0         619 KB\n        ------------------------------------------------------------\n                                               Total:       250.7 MB\n    \n    The following NEW packages will be INSTALLED:\n    \n      blas               pkgs/main/linux-64::blas-1.0-mkl\n      bzip2              pkgs/main/linux-64::bzip2-1.0.8-h7b6447c_0\n      cairo              pkgs/main/linux-64::cairo-1.14.12-h8948797_3\n      fontconfig         pkgs/main/linux-64::fontconfig-2.13.0-h9420a91_0\n      freetype           pkgs/main/linux-64::freetype-2.10.4-h5ab3b9f_0\n      glib               pkgs/main/linux-64::glib-2.66.1-h92f7085_0\n      icu                pkgs/main/linux-64::icu-58.2-he6710b0_3\n      intel-openmp       pkgs/main/linux-64::intel-openmp-2020.2-254\n      jpeg               pkgs/main/linux-64::jpeg-9b-h024ee3a_2\n      lcms2              pkgs/main/linux-64::lcms2-2.11-h396b838_0\n      libboost           pkgs/main/linux-64::libboost-1.67.0-h46d08c1_4\n      libpng             pkgs/main/linux-64::libpng-1.6.37-hbc83047_0\n      libtiff            pkgs/main/linux-64::libtiff-4.1.0-h2733197_1\n      libuuid            pkgs/main/linux-64::libuuid-1.0.3-h1bed415_2\n      libxcb             pkgs/main/linux-64::libxcb-1.14-h7b6447c_0\n      libxml2            pkgs/main/linux-64::libxml2-2.9.10-hb55368b_3\n      lz4-c              pkgs/main/linux-64::lz4-c-1.9.3-h2531618_0\n      mkl                pkgs/main/linux-64::mkl-2020.2-256\n      mkl-service        pkgs/main/linux-64::mkl-service-2.3.0-py36he8ac12f_0\n      mkl_fft            pkgs/main/linux-64::mkl_fft-1.2.0-py36h23d657b_0\n      mkl_random         pkgs/main/linux-64::mkl_random-1.1.1-py36h0573a6f_0\n      numpy              pkgs/main/linux-64::numpy-1.19.2-py36h54aff64_0\n      numpy-base         pkgs/main/linux-64::numpy-base-1.19.2-py36hfa32c7d_0\n      olefile            pkgs/main/linux-64::olefile-0.46-py36_0\n      pandas             pkgs/main/linux-64::pandas-1.1.5-py36ha9443f7_0\n      pcre               pkgs/main/linux-64::pcre-8.44-he6710b0_0\n      pillow             pkgs/main/linux-64::pillow-8.1.0-py36he98fc37_0\n      pixman             pkgs/main/linux-64::pixman-0.40.0-h7b6447c_0\n      py-boost           pkgs/main/linux-64::py-boost-1.67.0-py36h04863e7_4\n      python-dateutil    pkgs/main/noarch::python-dateutil-2.8.1-py_0\n      pytz               pkgs/main/noarch::pytz-2020.5-pyhd3eb1b0_0\n      rdkit              rdkit/linux-64::rdkit-2020.03.3.0-py36hc20afe1_1\n      zstd               pkgs/main/linux-64::zstd-1.4.5-h9ceee32_0\n    \n    The following packages will be UPDATED:\n    \n      ca-certificates                              2020.10.14-0 --> 2021.1.19-h06a4308_0\n      certifi            pkgs/main/noarch::certifi-2020.6.20-p~ --> pkgs/main/linux-64::certifi-2020.12.5-py36h06a4308_0\n      cffi                                1.14.3-py38h261ae71_2 --> 1.14.4-py36h261ae71_0\n      cryptography                         3.2.1-py38h3c74f83_1 --> 3.3.1-py36h3c74f83_0\n      openssl                                 1.1.1h-h7b6447c_0 --> 1.1.1i-h27cfd23_0\n      pip                                 20.2.4-py38h06a4308_0 --> 20.3.3-py36h06a4308_0\n      setuptools                          50.3.1-py38h06a4308_1 --> 52.0.0-py36h06a4308_0\n    \n    The following packages will be DOWNGRADED:\n    \n      brotlipy                          0.7.0-py38h27cfd23_1003 --> 0.7.0-py36h27cfd23_1003\n      chardet                           3.0.4-py38h06a4308_1003 --> 3.0.4-py36h06a4308_1003\n      conda                                4.9.2-py38h06a4308_0 --> 4.9.2-py36h06a4308_0\n      conda-package-han~                   1.7.2-py38h03888b9_0 --> 1.7.2-py36h03888b9_0\n      pycosat                              0.6.3-py38h7b6447c_1 --> 0.6.3-py36h27cfd23_0\n      pysocks                              1.7.1-py38h06a4308_0 --> 1.7.1-py36h06a4308_0\n      python                                   3.8.5-h7579374_1 --> 3.6.12-hcff3b4d_2\n      ruamel_yaml                        0.15.87-py38h7b6447c_1 --> 0.15.87-py36h7b6447c_1\n      six                                 1.15.0-py38h06a4308_0 --> 1.15.0-py36h06a4308_0\n    \n    \n    Preparing transaction: ...working... done\n    Verifying transaction: ...working... done\n    Executing transaction: ...working... done\n    2020.03.3\n\n\n**step 3**\r\n\r\nInstall PyTorch and check version.\n\n\n```\n!conda install --yes pytorch torchvision torchaudio cudatoolkit=10.1 -c pytorch\r\nimport torch\r\nprint(torch.__version__)\n```\n\n    Collecting package metadata (current_repodata.json): - \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\bdone\n    Solving environment: \\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\bdone\n    \n    ## Package Plan ##\n    \n      environment location: /usr/local\n    \n      added / updated specs:\n        - cudatoolkit=10.1\n        - pytorch\n        - torchaudio\n        - torchvision\n    \n    \n    The following packages will be downloaded:\n    \n        package                    |            build\n        ---------------------------|-----------------\n        cudatoolkit-10.1.243       |       h6bb024c_0       347.4 MB\n        dataclasses-0.7            |           py36_0          30 KB\n        libuv-1.40.0               |       h7b6447c_0         736 KB\n        ninja-1.10.2               |   py36hff7bd54_0         1.4 MB\n        pytorch-1.7.1              |py3.6_cuda10.1.243_cudnn7.6.3_0       553.7 MB  pytorch\n        torchaudio-0.7.2           |             py36         9.8 MB  pytorch\n        torchvision-0.8.2          |       py36_cu101        17.8 MB  pytorch\n        typing_extensions-3.7.4.3  |     pyh06a4308_0          28 KB\n        ------------------------------------------------------------\n                                               Total:       931.1 MB\n    \n    The following NEW packages will be INSTALLED:\n    \n      cudatoolkit        pkgs/main/linux-64::cudatoolkit-10.1.243-h6bb024c_0\n      dataclasses        pkgs/main/linux-64::dataclasses-0.7-py36_0\n      libuv              pkgs/main/linux-64::libuv-1.40.0-h7b6447c_0\n      ninja              pkgs/main/linux-64::ninja-1.10.2-py36hff7bd54_0\n      pytorch            pytorch/linux-64::pytorch-1.7.1-py3.6_cuda10.1.243_cudnn7.6.3_0\n      torchaudio         pytorch/linux-64::torchaudio-0.7.2-py36\n      torchvision        pytorch/linux-64::torchvision-0.8.2-py36_cu101\n      typing_extensions  pkgs/main/noarch::typing_extensions-3.7.4.3-pyh06a4308_0\n    \n    \n    \n    Downloading and Extracting Packages\n    dataclasses-0.7      | 30 KB     | : 100% 1.0/1 [00:00<00:00, 13.71it/s]\n    pytorch-1.7.1        | 553.7 MB  | : 100% 1.0/1 [01:21<00:00, 81.14s/it]               \n    ninja-1.10.2         | 1.4 MB    | : 100% 1.0/1 [00:00<00:00,  1.87it/s]\n    libuv-1.40.0         | 736 KB    | : 100% 1.0/1 [00:00<00:00, 16.48it/s]\n    torchvision-0.8.2    | 17.8 MB   | : 100% 1.0/1 [00:03<00:00,  3.58s/it]\n    cudatoolkit-10.1.243 | 347.4 MB  | : 100% 1.0/1 [00:11<00:00, 11.07s/it]\n    typing_extensions-3. | 28 KB     | : 100% 1.0/1 [00:00<00:00,  3.31it/s]\n    torchaudio-0.7.2     | 9.8 MB    | : 100% 1.0/1 [00:02<00:00,  2.68s/it]               \n    Preparing transaction: \\ \b\b| \b\bdone\n    Verifying transaction: - \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\bdone\n    Executing transaction: \\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\bdone\n    1.7.0+cu101\n\n\n**step 4**\r\n\r\nInstall pymatgen and check version. \n\n\n```\n!conda install --yes --channel conda-forge pymatgen=2020.10.20\r\nimport pymatgen\r\nprint(pymatgen.__version__)\n```\n\n    Collecting package metadata (current_repodata.json): - \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\bdone\n    Solving environment: - \b\bfailed with initial frozen solve. Retrying with flexible solve.\n    Collecting package metadata (repodata.json): | \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\bdone\n    Solving environment: | \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \n    Warning: 2 possible package resolutions (only showing differing packages):\n      - conda-forge/linux-64::apscheduler-3.6.3-py36h5fab9bb_3, conda-forge/noarch::tzlocal-2.1-pyh9f0ad1d_0\n      - conda-forge/linux-64::apscheduler-3.7.0-py36h5fab9bb_0, conda-forge/noarch::tzlocal-2.0.0-py_0\b\b/ \b\bdone\n    \n    ## Package Plan ##\n    \n      environment location: /usr/local\n    \n      added / updated specs:\n        - pymatgen=2020.10.20\n    \n    \n    The following packages will be downloaded:\n    \n        package                    |            build\n        ---------------------------|-----------------\n        apscheduler-3.6.3          |   py36h5fab9bb_3          81 KB  conda-forge\n        ase-3.21.1                 |     pyhd8ed1ab_0         1.5 MB  conda-forge\n        beautifulsoup4-4.9.3       |     pyhb0f4dca_0          86 KB  conda-forge\n        c-ares-1.17.1              |       h36c2ea0_0         111 KB  conda-forge\n        ca-certificates-2020.12.5  |       ha878542_0         137 KB  conda-forge\n        certifi-2020.12.5          |   py36h5fab9bb_1         143 KB  conda-forge\n        cftime-1.3.0               |   py36ha112f06_0         292 KB  conda-forge\n        click-7.1.2                |     pyh9f0ad1d_0          64 KB  conda-forge\n        conda-4.9.2                |   py36h5fab9bb_0         3.0 MB  conda-forge\n        curl-7.71.1                |       he644dc0_8         139 KB  conda-forge\n        cycler-0.10.0              |             py_2           9 KB  conda-forge\n        decorator-4.4.2            |             py_0          11 KB  conda-forge\n        expat-2.2.9                |       he1b5a44_2         191 KB  conda-forge\n        flask-1.1.2                |     pyh9f0ad1d_0          70 KB  conda-forge\n        future-0.18.2              |   py36h5fab9bb_3         716 KB  conda-forge\n        gmp-6.2.1                  |       h58526e2_0         806 KB  conda-forge\n        gmpy2-2.1.0b1              |   py36hbea7ad4_1         206 KB  conda-forge\n        hdf4-4.2.13                |                0         969 KB  conda-forge\n        hdf5-1.10.2                |       hc401514_3         4.8 MB  conda-forge\n        itsdangerous-1.1.0         |             py_0          16 KB  conda-forge\n        jinja2-2.11.2              |     pyh9f0ad1d_0          93 KB  conda-forge\n        jsoncpp-1.8.4              |    hc9558a2_1002         162 KB  conda-forge\n        kiwisolver-1.3.1           |   py36h51d7077_0          86 KB  conda-forge\n        krb5-1.17.2                |       h926e7f8_0         1.4 MB  conda-forge\n        latexcodec-2.0.1           |     pyh9f0ad1d_0          18 KB  conda-forge\n        libcurl-7.71.1             |       hcdd3856_8         312 KB  conda-forge\n        libev-4.33                 |       h516909a_1         104 KB  conda-forge\n        libgfortran-3.0.0          |                1         281 KB  conda-forge\n        libgfortran-ng-7.5.0       |      h14aa051_18          22 KB  conda-forge\n        libgfortran4-7.5.0         |      h14aa051_18         1.3 MB  conda-forge\n        libnetcdf-4.6.1            |       h5e45101_3         1.3 MB  conda-forge\n        libnghttp2-1.41.0          |       h8cfc5f6_2         774 KB  conda-forge\n        libogg-1.3.2               |    h516909a_1002         206 KB  conda-forge\n        libssh2-1.9.0              |       hab1572f_5         225 KB  conda-forge\n        libtheora-1.1.1            |    h516909a_1004         773 KB  conda-forge\n        libvorbis-1.3.7            |       he1b5a44_0         287 KB  conda-forge\n        lz4-c-1.8.3                |    he1b5a44_1001         187 KB  conda-forge\n        markupsafe-1.1.1           |   py36he6145b8_2          27 KB  conda-forge\n        matplotlib-base-3.3.3      |   py36he12231b_0         6.8 MB  conda-forge\n        monty-4.0.2                |     pyh9f0ad1d_0          36 KB  conda-forge\n        mpc-1.1.0                  |    h04dde30_1009         105 KB  conda-forge\n        mpfr-4.0.2                 |       he80fd80_1         648 KB  conda-forge\n        mpmath-1.1.0               |             py_0         432 KB  conda-forge\n        netcdf4-1.4.1              | py36ha292673_200         1.9 MB  conda-forge\n        networkx-2.5               |             py_0         1.2 MB  conda-forge\n        palettable-3.3.0           |             py_0          86 KB  conda-forge\n        plotly-4.14.3              |     pyh44b312d_0         5.9 MB  conda-forge\n        pybtex-0.24.0              |   py36h5fab9bb_0         303 KB  conda-forge\n        pymatgen-2020.10.20        |   py36h51d7077_0         3.4 MB  conda-forge\n        pyparsing-2.4.7            |     pyh9f0ad1d_0          60 KB  conda-forge\n        python_abi-3.6             |          1_cp36m           4 KB  conda-forge\n        pyyaml-5.3.1               |   py36he6145b8_1         185 KB  conda-forge\n        retrying-1.3.3             |             py_2          11 KB  conda-forge\n        ruamel.yaml-0.16.12        |   py36h1d69622_1         167 KB  conda-forge\n        ruamel.yaml.clib-0.2.2     |   py36h1d69622_1         157 KB  conda-forge\n        scipy-1.5.2                |   py36h0b6359f_0        14.4 MB\n        soupsieve-2.0.1            |             py_1          30 KB  conda-forge\n        spglib-1.16.0              |   py36h68bb277_4         632 KB  conda-forge\n        sympy-1.7.1                |   py36h5fab9bb_1        10.9 MB  conda-forge\n        tabulate-0.8.7             |     pyh9f0ad1d_0          24 KB  conda-forge\n        tbb-2020.2                 |       hc9558a2_0         1.4 MB  conda-forge\n        tornado-6.1                |   py36h1d69622_0         644 KB  conda-forge\n        tzlocal-2.1                |     pyh9f0ad1d_0          18 KB  conda-forge\n        uncertainties-3.1.5        |     pyhd8ed1ab_0          75 KB  conda-forge\n        vtk-8.1.1                  | py36h4f1983a_204        26.1 MB\n        werkzeug-1.0.1             |     pyh9f0ad1d_0         239 KB  conda-forge\n        zstd-1.4.4                 |       h3b9ef0a_2         982 KB  conda-forge\n        ------------------------------------------------------------\n                                               Total:        97.7 MB\n    \n    The following NEW packages will be INSTALLED:\n    \n      apscheduler        conda-forge/linux-64::apscheduler-3.6.3-py36h5fab9bb_3\n      ase                conda-forge/noarch::ase-3.21.1-pyhd8ed1ab_0\n      beautifulsoup4     conda-forge/noarch::beautifulsoup4-4.9.3-pyhb0f4dca_0\n      c-ares             conda-forge/linux-64::c-ares-1.17.1-h36c2ea0_0\n      cftime             conda-forge/linux-64::cftime-1.3.0-py36ha112f06_0\n      click              conda-forge/noarch::click-7.1.2-pyh9f0ad1d_0\n      curl               conda-forge/linux-64::curl-7.71.1-he644dc0_8\n      cycler             conda-forge/noarch::cycler-0.10.0-py_2\n      decorator          conda-forge/noarch::decorator-4.4.2-py_0\n      expat              conda-forge/linux-64::expat-2.2.9-he1b5a44_2\n      flask              conda-forge/noarch::flask-1.1.2-pyh9f0ad1d_0\n      future             conda-forge/linux-64::future-0.18.2-py36h5fab9bb_3\n      gmp                conda-forge/linux-64::gmp-6.2.1-h58526e2_0\n      gmpy2              conda-forge/linux-64::gmpy2-2.1.0b1-py36hbea7ad4_1\n      hdf4               conda-forge/linux-64::hdf4-4.2.13-0\n      hdf5               conda-forge/linux-64::hdf5-1.10.2-hc401514_3\n      itsdangerous       conda-forge/noarch::itsdangerous-1.1.0-py_0\n      jinja2             conda-forge/noarch::jinja2-2.11.2-pyh9f0ad1d_0\n      jsoncpp            conda-forge/linux-64::jsoncpp-1.8.4-hc9558a2_1002\n      kiwisolver         conda-forge/linux-64::kiwisolver-1.3.1-py36h51d7077_0\n      krb5               conda-forge/linux-64::krb5-1.17.2-h926e7f8_0\n      latexcodec         conda-forge/noarch::latexcodec-2.0.1-pyh9f0ad1d_0\n      libcurl            conda-forge/linux-64::libcurl-7.71.1-hcdd3856_8\n      libev              conda-forge/linux-64::libev-4.33-h516909a_1\n      libgfortran        conda-forge/linux-64::libgfortran-3.0.0-1\n      libgfortran-ng     conda-forge/linux-64::libgfortran-ng-7.5.0-h14aa051_18\n      libgfortran4       conda-forge/linux-64::libgfortran4-7.5.0-h14aa051_18\n      libnetcdf          conda-forge/linux-64::libnetcdf-4.6.1-h5e45101_3\n      libnghttp2         conda-forge/linux-64::libnghttp2-1.41.0-h8cfc5f6_2\n      libogg             conda-forge/linux-64::libogg-1.3.2-h516909a_1002\n      libssh2            conda-forge/linux-64::libssh2-1.9.0-hab1572f_5\n      libtheora          conda-forge/linux-64::libtheora-1.1.1-h516909a_1004\n      libvorbis          conda-forge/linux-64::libvorbis-1.3.7-he1b5a44_0\n      markupsafe         conda-forge/linux-64::markupsafe-1.1.1-py36he6145b8_2\n      matplotlib-base    conda-forge/linux-64::matplotlib-base-3.3.3-py36he12231b_0\n      monty              conda-forge/noarch::monty-4.0.2-pyh9f0ad1d_0\n      mpc                conda-forge/linux-64::mpc-1.1.0-h04dde30_1009\n      mpfr               conda-forge/linux-64::mpfr-4.0.2-he80fd80_1\n      mpmath             conda-forge/noarch::mpmath-1.1.0-py_0\n      netcdf4            conda-forge/linux-64::netcdf4-1.4.1-py36ha292673_200\n      networkx           conda-forge/noarch::networkx-2.5-py_0\n      palettable         conda-forge/noarch::palettable-3.3.0-py_0\n      plotly             conda-forge/noarch::plotly-4.14.3-pyh44b312d_0\n      pybtex             conda-forge/linux-64::pybtex-0.24.0-py36h5fab9bb_0\n      pymatgen           conda-forge/linux-64::pymatgen-2020.10.20-py36h51d7077_0\n      pyparsing          conda-forge/noarch::pyparsing-2.4.7-pyh9f0ad1d_0\n      python_abi         conda-forge/linux-64::python_abi-3.6-1_cp36m\n      pyyaml             conda-forge/linux-64::pyyaml-5.3.1-py36he6145b8_1\n      retrying           conda-forge/noarch::retrying-1.3.3-py_2\n      ruamel.yaml        conda-forge/linux-64::ruamel.yaml-0.16.12-py36h1d69622_1\n      ruamel.yaml.clib   conda-forge/linux-64::ruamel.yaml.clib-0.2.2-py36h1d69622_1\n      scipy              pkgs/main/linux-64::scipy-1.5.2-py36h0b6359f_0\n      soupsieve          conda-forge/noarch::soupsieve-2.0.1-py_1\n      spglib             conda-forge/linux-64::spglib-1.16.0-py36h68bb277_4\n      sympy              conda-forge/linux-64::sympy-1.7.1-py36h5fab9bb_1\n      tabulate           conda-forge/noarch::tabulate-0.8.7-pyh9f0ad1d_0\n      tbb                conda-forge/linux-64::tbb-2020.2-hc9558a2_0\n      tornado            conda-forge/linux-64::tornado-6.1-py36h1d69622_0\n      tzlocal            conda-forge/noarch::tzlocal-2.1-pyh9f0ad1d_0\n      uncertainties      conda-forge/noarch::uncertainties-3.1.5-pyhd8ed1ab_0\n      vtk                pkgs/main/linux-64::vtk-8.1.1-py36h4f1983a_204\n      werkzeug           conda-forge/noarch::werkzeug-1.0.1-pyh9f0ad1d_0\n    \n    The following packages will be UPDATED:\n    \n      certifi            pkgs/main::certifi-2020.12.5-py36h06a~ --> conda-forge::certifi-2020.12.5-py36h5fab9bb_1\n    \n    The following packages will be SUPERSEDED by a higher-priority channel:\n    \n      ca-certificates    pkgs/main::ca-certificates-2021.1.19-~ --> conda-forge::ca-certificates-2020.12.5-ha878542_0\n      conda               pkgs/main::conda-4.9.2-py36h06a4308_0 --> conda-forge::conda-4.9.2-py36h5fab9bb_0\n      lz4-c                   pkgs/main::lz4-c-1.9.3-h2531618_0 --> conda-forge::lz4-c-1.8.3-he1b5a44_1001\n      zstd                     pkgs/main::zstd-1.4.5-h9ceee32_0 --> conda-forge::zstd-1.4.4-h3b9ef0a_2\n    \n    \n    \n    Downloading and Extracting Packages\n    ase-3.21.1           | 1.5 MB    | : 100% 1.0/1 [00:00<00:00,  2.10it/s]\n    pymatgen-2020.10.20  | 3.4 MB    | : 100% 1.0/1 [00:00<00:00,  1.34it/s]\n    latexcodec-2.0.1     | 18 KB     | : 100% 1.0/1 [00:00<00:00, 27.24it/s]\n    tzlocal-2.1          | 18 KB     | : 100% 1.0/1 [00:00<00:00, 27.31it/s]\n    hdf4-4.2.13          | 969 KB    | : 100% 1.0/1 [00:00<00:00,  5.63it/s]\n    markupsafe-1.1.1     | 27 KB     | : 100% 1.0/1 [00:00<00:00, 20.40it/s]\n    pyparsing-2.4.7      | 60 KB     | : 100% 1.0/1 [00:00<00:00, 21.46it/s]\n    jinja2-2.11.2        | 93 KB     | : 100% 1.0/1 [00:00<00:00, 20.74it/s]\n    libgfortran-3.0.0    | 281 KB    | : 100% 1.0/1 [00:00<00:00, 13.66it/s]\n    future-0.18.2        | 716 KB    | : 100% 1.0/1 [00:00<00:00,  5.53it/s]\n    networkx-2.5         | 1.2 MB    | : 100% 1.0/1 [00:00<00:00,  3.63it/s]\n    plotly-4.14.3        | 5.9 MB    | : 100% 1.0/1 [00:02<00:00,  2.46s/it]\n    mpmath-1.1.0         | 432 KB    | : 100% 1.0/1 [00:00<00:00,  8.28it/s]\n    krb5-1.17.2          | 1.4 MB    | : 100% 1.0/1 [00:00<00:00,  3.98it/s]\n    kiwisolver-1.3.1     | 86 KB     | : 100% 1.0/1 [00:00<00:00, 21.66it/s]\n    vtk-8.1.1            | 26.1 MB   | : 100% 1.0/1 [00:01<00:00,  1.39s/it]               \n    click-7.1.2          | 64 KB     | : 100% 1.0/1 [00:00<00:00, 18.74it/s]\n    tbb-2020.2           | 1.4 MB    | : 100% 1.0/1 [00:00<00:00,  4.36it/s]\n    python_abi-3.6       | 4 KB      | : 100% 1.0/1 [00:00<00:00, 30.33it/s]\n    sympy-1.7.1          | 10.9 MB   | : 100% 1.0/1 [00:02<00:00,  2.23s/it]               \n    palettable-3.3.0     | 86 KB     | : 100% 1.0/1 [00:00<00:00, 18.32it/s]\n    spglib-1.16.0        | 632 KB    | : 100% 1.0/1 [00:00<00:00,  3.46it/s]\n    libev-4.33           | 104 KB    | : 100% 1.0/1 [00:00<00:00, 19.07it/s]\n    netcdf4-1.4.1        | 1.9 MB    | : 100% 1.0/1 [00:00<00:00,  3.23it/s]\n    werkzeug-1.0.1       | 239 KB    | : 100% 1.0/1 [00:00<00:00, 14.20it/s]\n    apscheduler-3.6.3    | 81 KB     | : 100% 1.0/1 [00:00<00:00, 22.29it/s]\n    soupsieve-2.0.1      | 30 KB     | : 100% 1.0/1 [00:00<00:00, 30.26it/s]\n    curl-7.71.1          | 139 KB    | : 100% 1.0/1 [00:00<00:00, 20.66it/s]\n    lz4-c-1.8.3          | 187 KB    | : 100% 1.0/1 [00:00<00:00, 15.49it/s]\n    matplotlib-base-3.3. | 6.8 MB    | : 100% 1.0/1 [00:01<00:00,  1.18s/it]\n    libtheora-1.1.1      | 773 KB    | : 100% 1.0/1 [00:00<00:00,  6.63it/s]\n    gmpy2-2.1.0b1        | 206 KB    | : 100% 1.0/1 [00:00<00:00, 15.83it/s]\n    c-ares-1.17.1        | 111 KB    | : 100% 1.0/1 [00:00<00:00, 19.93it/s]\n    pybtex-0.24.0        | 303 KB    | : 100% 1.0/1 [00:00<00:00,  8.29it/s]\n    libvorbis-1.3.7      | 287 KB    | : 100% 1.0/1 [00:00<00:00, 13.73it/s]\n    cftime-1.3.0         | 292 KB    | : 100% 1.0/1 [00:00<00:00, 12.48it/s]\n    gmp-6.2.1            | 806 KB    | : 100% 1.0/1 [00:00<00:00,  6.15it/s]\n    pyyaml-5.3.1         | 185 KB    | : 100% 1.0/1 [00:00<00:00, 14.48it/s]\n    cycler-0.10.0        | 9 KB      | : 100% 1.0/1 [00:00<00:00, 38.44it/s]\n    decorator-4.4.2      | 11 KB     | : 100% 1.0/1 [00:00<00:00, 25.92it/s]\n    ca-certificates-2020 | 137 KB    | : 100% 1.0/1 [00:00<00:00, 23.58it/s]\n    libnghttp2-1.41.0    | 774 KB    | : 100% 1.0/1 [00:00<00:00,  7.29it/s]\n    libgfortran-ng-7.5.0 | 22 KB     | : 100% 1.0/1 [00:00<00:00, 29.38it/s]\n    libgfortran4-7.5.0   | 1.3 MB    | : 100% 1.0/1 [00:00<00:00,  4.17it/s]\n    zstd-1.4.4           | 982 KB    | : 100% 1.0/1 [00:00<00:00,  6.06it/s]\n    monty-4.0.2          | 36 KB     | : 100% 1.0/1 [00:00<00:00, 25.11it/s]\n    tornado-6.1          | 644 KB    | : 100% 1.0/1 [00:00<00:00,  6.40it/s]\n    mpfr-4.0.2           | 648 KB    | : 100% 1.0/1 [00:00<00:00,  4.73it/s]\n    conda-4.9.2          | 3.0 MB    | : 100% 1.0/1 [00:00<00:00,  1.76it/s]\n    uncertainties-3.1.5  | 75 KB     | : 100% 1.0/1 [00:00<00:00, 20.98it/s]\n    libogg-1.3.2         | 206 KB    | : 100% 1.0/1 [00:00<00:00, 17.08it/s]\n    libssh2-1.9.0        | 225 KB    | : 100% 1.0/1 [00:00<00:00, 12.78it/s]\n    libcurl-7.71.1       | 312 KB    | : 100% 1.0/1 [00:00<00:00, 13.70it/s]\n    jsoncpp-1.8.4        | 162 KB    | : 100% 1.0/1 [00:00<00:00, 15.46it/s]\n    hdf5-1.10.2          | 4.8 MB    | : 100% 1.0/1 [00:01<00:00,  1.00s/it]\n    certifi-2020.12.5    | 143 KB    | : 100% 1.0/1 [00:00<00:00, 21.71it/s]\n    scipy-1.5.2          | 14.4 MB   | : 100% 1.0/1 [00:00<00:00,  1.76it/s]\n    retrying-1.3.3       | 11 KB     | : 100% 1.0/1 [00:00<00:00, 30.15it/s]\n    flask-1.1.2          | 70 KB     | : 100% 1.0/1 [00:00<00:00, 22.70it/s]\n    beautifulsoup4-4.9.3 | 86 KB     | : 100% 1.0/1 [00:00<00:00, 22.62it/s]\n    libnetcdf-4.6.1      | 1.3 MB    | : 100% 1.0/1 [00:00<00:00,  4.44it/s]\n    mpc-1.1.0            | 105 KB    | : 100% 1.0/1 [00:00<00:00, 14.47it/s]\n    ruamel.yaml-0.16.12  | 167 KB    | : 100% 1.0/1 [00:00<00:00, 14.86it/s]\n    expat-2.2.9          | 191 KB    | : 100% 1.0/1 [00:00<00:00, 17.10it/s]\n    tabulate-0.8.7       | 24 KB     | : 100% 1.0/1 [00:00<00:00, 27.74it/s]\n    ruamel.yaml.clib-0.2 | 157 KB    | : 100% 1.0/1 [00:00<00:00, 19.09it/s]\n    itsdangerous-1.1.0   | 16 KB     | : 100% 1.0/1 [00:00<00:00, 27.30it/s]\n    Preparing transaction: \\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\bdone\n    Verifying transaction: - \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\bdone\n    Executing transaction: | \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\bdone\n    2020.10.20\n\n\n**step 5**\r\n\r\nInstall XenonPy and check version.\n\n\n```\n!wget https://raw.githubusercontent.com/by-student-2017/xenonpy-gcolab/main/0.4.4/conda_env/xepy36_cuda10.yml\r\n!conda create --yes -n xenonpy python=3.6\r\n!conda env update -n xenonpy -f xepy36_cuda10.yml\r\n!source activate xenonpy\r\n!pip3 install -U xenonpy==0.4.4\r\nimport xenonpy\r\nprint(xenonpy.__version__)\n```\n\n    --2021-01-29 10:38:09--  https://raw.githubusercontent.com/by-student-2017/xenonpy-gcolab/main/0.4.4/conda_env/xepy36_cuda10.yml\n    Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 151.101.0.133, 151.101.64.133, 151.101.128.133, ...\n    Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|151.101.0.133|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 524 [text/plain]\n    Saving to: \u2018xepy36_cuda10.yml\u2019\n    \n    xepy36_cuda10.yml   100%[===================>]     524  --.-KB/s    in 0s      \n    \n    2021-01-29 10:38:09 (26.0 MB/s) - \u2018xepy36_cuda10.yml\u2019 saved [524/524]\n    \n    Collecting package metadata (current_repodata.json): - \b\b\\ \b\b| \b\b/ \b\bdone\n    Solving environment: \\ \b\bdone\n    \n    ## Package Plan ##\n    \n      environment location: /usr/local/envs/xenonpy\n    \n      added / updated specs:\n        - python=3.6\n    \n    \n    The following packages will be downloaded:\n    \n        package                    |            build\n        ---------------------------|-----------------\n        readline-8.1               |       h27cfd23_0         362 KB\n        wheel-0.36.2               |     pyhd3eb1b0_0          33 KB\n        ------------------------------------------------------------\n                                               Total:         395 KB\n    \n    The following NEW packages will be INSTALLED:\n    \n      _libgcc_mutex      pkgs/main/linux-64::_libgcc_mutex-0.1-main\n      ca-certificates    pkgs/main/linux-64::ca-certificates-2021.1.19-h06a4308_0\n      certifi            pkgs/main/linux-64::certifi-2020.12.5-py36h06a4308_0\n      ld_impl_linux-64   pkgs/main/linux-64::ld_impl_linux-64-2.33.1-h53a641e_7\n      libedit            pkgs/main/linux-64::libedit-3.1.20191231-h14c3975_1\n      libffi             pkgs/main/linux-64::libffi-3.3-he6710b0_2\n      libgcc-ng          pkgs/main/linux-64::libgcc-ng-9.1.0-hdf63c60_0\n      libstdcxx-ng       pkgs/main/linux-64::libstdcxx-ng-9.1.0-hdf63c60_0\n      ncurses            pkgs/main/linux-64::ncurses-6.2-he6710b0_1\n      openssl            pkgs/main/linux-64::openssl-1.1.1i-h27cfd23_0\n      pip                pkgs/main/linux-64::pip-20.3.3-py36h06a4308_0\n      python             pkgs/main/linux-64::python-3.6.12-hcff3b4d_2\n      readline           pkgs/main/linux-64::readline-8.1-h27cfd23_0\n      setuptools         pkgs/main/linux-64::setuptools-52.0.0-py36h06a4308_0\n      sqlite             pkgs/main/linux-64::sqlite-3.33.0-h62c20be_0\n      tk                 pkgs/main/linux-64::tk-8.6.10-hbc83047_0\n      wheel              pkgs/main/noarch::wheel-0.36.2-pyhd3eb1b0_0\n      xz                 pkgs/main/linux-64::xz-5.2.5-h7b6447c_0\n      zlib               pkgs/main/linux-64::zlib-1.2.11-h7b6447c_3\n    \n    \n    \n    Downloading and Extracting Packages\n    readline-8.1         | 362 KB    | : 100% 1.0/1 [00:00<00:00,  8.84it/s]\n    wheel-0.36.2         | 33 KB     | : 100% 1.0/1 [00:00<00:00, 29.74it/s]\n    Preparing transaction: / \b\b- \b\b\\ \b\bdone\n    Verifying transaction: / \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\bdone\n    Executing transaction: \\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\bdone\n    #\n    # To activate this environment, use\n    #\n    #     $ conda activate xenonpy\n    #\n    # To deactivate an active environment, use\n    #\n    #     $ conda deactivate\n    \n    Collecting package metadata (repodata.json): - \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\bdone\n    Solving environment: | \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\bdone\n    \n    Downloading and Extracting Packages\n    async_generator-1.10 | 39 KB     | : 100% 1.0/1 [00:00<00:00,  8.61it/s]\n    urllib3-1.26.3       | 105 KB    | : 100% 1.0/1 [00:00<00:00, 13.34it/s]\n    apscheduler-3.6.3    | 85 KB     | : 100% 1.0/1 [00:00<00:00, 13.39it/s]\n    jupyter-1.0.0        | 6 KB      | : 100% 1.0/1 [00:00<00:00, 16.64it/s]\n    palettable-3.3.0     | 78 KB     | : 100% 1.0/1 [00:00<00:00, 12.29it/s]\n    bleach-3.2.3         | 113 KB    | : 100% 1.0/1 [00:00<00:00, 15.31it/s]\n    parso-0.8.1          | 69 KB     | : 100% 1.0/1 [00:00<00:00, 17.32it/s]\n    ptyprocess-0.7.0     | 17 KB     | : 100% 1.0/1 [00:00<00:00, 16.87it/s]\n    plotly-4.14.3        | 3.6 MB    | : 100% 1.0/1 [00:00<00:00,  1.10it/s]\n    backcall-0.2.0       | 15 KB     | : 100% 1.0/1 [00:00<00:00, 15.23it/s]\n    notebook-6.2.0       | 4.1 MB    | : 100% 1.0/1 [00:00<00:00,  2.35it/s]\n    jedi-0.18.0          | 909 KB    | : 100% 1.0/1 [00:00<00:00,  3.74it/s]\n    ruamel.yaml.clib-0.2 | 145 KB    | : 100% 1.0/1 [00:00<00:00, 14.58it/s]\n    ipykernel-5.3.4      | 181 KB    | : 100% 1.0/1 [00:00<00:00, 13.16it/s]\n    defusedxml-0.6.0     | 23 KB     | : 100% 1.0/1 [00:00<00:00, 16.86it/s]\n    pandoc-2.11          | 9.6 MB    | : 100% 1.0/1 [00:00<00:00,  2.61it/s]\n    libcurl-7.71.1       | 305 KB    | : 100% 1.0/1 [00:00<00:00,  9.95it/s]\n    hdf4-4.2.13          | 714 KB    | : 100% 1.0/1 [00:00<00:00,  6.29it/s]\n    requests-2.25.1      | 52 KB     | : 100% 1.0/1 [00:00<00:00, 15.18it/s]\n    pymatgen-2019.11.11  | 3.1 MB    | : 100% 1.0/1 [00:01<00:00,  1.30s/it]\n    qt-5.9.7             | 68.5 MB   | : 100% 1.0/1 [00:02<00:00,  2.56s/it]               \n    networkx-2.5         | 1.1 MB    | : 100% 1.0/1 [00:00<00:00,  5.81it/s]\n    webencodings-0.5.1   | 19 KB     | : 100% 1.0/1 [00:00<00:00, 14.42it/s]\n    flask-1.1.2          | 78 KB     | : 100% 1.0/1 [00:00<00:00, 13.09it/s]\n    jsonschema-3.2.0     | 47 KB     | : 100% 1.0/1 [00:00<00:00, 14.06it/s]\n    pygments-2.7.4       | 676 KB    | : 100% 1.0/1 [00:00<00:00, 10.36it/s]\n    wcwidth-0.2.5        | 29 KB     | : 100% 1.0/1 [00:00<00:00, 16.01it/s]\n    decorator-4.4.2      | 14 KB     | : 100% 1.0/1 [00:00<00:00, 10.63it/s]\n    scikit-learn-0.21.3  | 5.0 MB    | : 100% 1.0/1 [00:00<00:00,  3.18it/s]\n    jinja2-2.11.2        | 93 KB     | : 100% 1.0/1 [00:00<00:00, 21.75it/s]\n    prometheus_client-0. | 45 KB     | : 100% 1.0/1 [00:00<00:00, 14.21it/s]\n    retrying-1.3.3       | 16 KB     | : 100% 1.0/1 [00:00<00:00, 15.27it/s]\n    pyparsing-2.4.7      | 59 KB     | : 100% 1.0/1 [00:00<00:00, 26.14it/s]\n    nbclient-0.5.1       | 58 KB     | : 100% 1.0/1 [00:00<00:00, 14.12it/s]\n    matplotlib-base-3.3. | 5.1 MB    | : 100% 1.0/1 [00:00<00:00,  3.72it/s]\n    ruamel.yaml-0.16.12  | 172 KB    | : 100% 1.0/1 [00:00<00:00, 12.57it/s]\n    ipython_genutils-0.2 | 27 KB     | : 100% 1.0/1 [00:00<00:00, 15.00it/s]\n    joblib-1.0.0         | 208 KB    | : 100% 1.0/1 [00:00<00:00, 12.03it/s]\n    kiwisolver-1.3.0     | 80 KB     | : 100% 1.0/1 [00:00<00:00, 13.73it/s]\n    libssh2-1.9.0        | 269 KB    | : 100% 1.0/1 [00:00<00:00, 11.69it/s]\n    gmpy2-2.0.8          | 150 KB    | : 100% 1.0/1 [00:00<00:00, 15.48it/s]\n    libvorbis-1.3.7      | 398 KB    | : 100% 1.0/1 [00:00<00:00, 10.61it/s]\n    pickleshare-0.7.5    | 13 KB     | : 100% 1.0/1 [00:00<00:00, 15.26it/s]\n    prompt-toolkit-3.0.8 | 248 KB    | : 100% 1.0/1 [00:00<00:00, 12.10it/s]\n    pydispatcher-2.0.5   | 19 KB     | : 100% 1.0/1 [00:00<00:00, 14.29it/s]\n    idna-2.10            | 52 KB     | : 100% 1.0/1 [00:00<00:00, 35.46it/s]\n    sip-4.19.8           | 274 KB    | : 100% 1.0/1 [00:00<00:00, 13.74it/s]\n    traitlets-4.3.3      | 140 KB    | : 100% 1.0/1 [00:00<00:00, 14.30it/s]\n    gstreamer-1.14.0     | 3.2 MB    | : 100% 1.0/1 [00:00<00:00,  6.74it/s]\n    gmp-6.1.2            | 514 KB    | : 100% 1.0/1 [00:00<00:00, 11.70it/s]\n    ipython-7.16.1       | 999 KB    | : 100% 1.0/1 [00:00<00:00,  6.87it/s]\n    rdkit-2019.09.1.0    | 23.9 MB   | : 100% 1.0/1 [00:05<00:00,  5.27s/it]\n    tornado-6.1          | 581 KB    | : 100% 1.0/1 [00:00<00:00, 10.70it/s]\n    itsdangerous-1.1.0   | 28 KB     | : 100% 1.0/1 [00:00<00:00, 13.37it/s]\n    entrypoints-0.3      | 12 KB     | : 100% 1.0/1 [00:00<00:00, 16.15it/s]\n    argon2-cffi-20.1.0   | 46 KB     | : 100% 1.0/1 [00:00<00:00, 14.99it/s]\n    hdf5-1.10.4          | 3.9 MB    | : 100% 1.0/1 [00:00<00:00,  6.05it/s]\n    dbus-1.13.18         | 504 KB    | : 100% 1.0/1 [00:00<00:00, 10.78it/s]\n    mpc-1.1.0            | 90 KB     | : 100% 1.0/1 [00:00<00:00, 12.98it/s]\n    qtpy-1.9.0           | 38 KB     | : 100% 1.0/1 [00:00<00:00, 15.42it/s]\n    tbb-2020.3           | 1.1 MB    | : 100% 1.0/1 [00:00<00:00, 11.38it/s]\n    mistune-0.8.4        | 55 KB     | : 100% 1.0/1 [00:00<00:00, 13.98it/s]\n    chardet-4.0.0        | 199 KB    | : 100% 1.0/1 [00:00<00:00, 10.87it/s]\n    pyopenssl-20.0.1     | 49 KB     | : 100% 1.0/1 [00:00<00:00, 12.70it/s]\n    pandas-0.25.3        | 8.8 MB    | : 100% 1.0/1 [00:00<00:00,  1.95it/s]\n    future-0.18.2        | 639 KB    | : 100% 1.0/1 [00:00<00:00,  8.22it/s]\n    gst-plugins-base-1.1 | 4.9 MB    | : 100% 1.0/1 [00:00<00:00,  4.40it/s]\n    jsoncpp-1.8.4        | 132 KB    | : 100% 1.0/1 [00:00<00:00, 14.09it/s]\n    attrs-20.3.0         | 43 KB     | : 100% 1.0/1 [00:00<00:00, 13.30it/s]\n    expat-2.2.10         | 153 KB    | : 100% 1.0/1 [00:00<00:00, 12.58it/s]\n    prompt_toolkit-3.0.8 | 12 KB     | : 100% 1.0/1 [00:00<00:00, 16.33it/s]\n    libgfortran-ng-7.3.0 | 1006 KB   | : 100% 1.0/1 [00:00<00:00, 11.13it/s]\n    vtk-8.2.0            | 28.4 MB   | : 100% 1.0/1 [00:01<00:00,  1.32s/it]               \n    terminado-0.9.2      | 25 KB     | : 100% 1.0/1 [00:00<00:00, 13.07it/s]\n    libnetcdf-4.6.1      | 833 KB    | : 100% 1.0/1 [00:00<00:00, 10.17it/s]\n    pytorch-1.3.0        | 464.0 MB  | : 100% 1.0/1 [01:09<00:00, 69.07s/it]              \n    zipp-3.4.0           | 15 KB     | : 100% 1.0/1 [00:00<00:00, 14.21it/s]\n    cycler-0.10.0        | 13 KB     | : 100% 1.0/1 [00:00<00:00, 15.14it/s]\n    click-7.1.2          | 64 KB     | : 100% 1.0/1 [00:00<00:00, 30.28it/s]\n    importlib_metadata-2 | 11 KB     | : 100% 1.0/1 [00:00<00:00, 14.17it/s]\n    seaborn-0.11.1       | 212 KB    | : 100% 1.0/1 [00:00<00:00, 13.00it/s]\n    matplotlib-3.3.2     | 24 KB     | : 100% 1.0/1 [00:00<00:00, 14.73it/s]\n    testpath-0.4.4       | 82 KB     | : 100% 1.0/1 [00:00<00:00, 15.74it/s]\n    scipy-1.3.1          | 14.0 MB   | : 100% 1.0/1 [00:00<00:00,  1.58it/s]               \n    jupyter_client-6.1.7 | 77 KB     | : 100% 1.0/1 [00:00<00:00, 12.06it/s]\n    pyrsistent-0.17.3    | 89 KB     | : 100% 1.0/1 [00:00<00:00, 12.55it/s]\n    mpfr-4.0.2           | 487 KB    | : 100% 1.0/1 [00:00<00:00, 11.28it/s]\n    importlib-metadata-2 | 35 KB     | : 100% 1.0/1 [00:00<00:00, 13.16it/s]\n    mpmath-1.1.0         | 776 KB    | : 100% 1.0/1 [00:00<00:00, 10.20it/s]\n    lz4-c-1.8.1.2        | 130 KB    | : 100% 1.0/1 [00:00<00:00, 14.34it/s]\n    ipywidgets-7.6.3     | 105 KB    | : 100% 1.0/1 [00:00<00:00, 14.09it/s]\n    zstd-1.3.7           | 401 KB    | : 100% 1.0/1 [00:00<00:00, 13.29it/s]\n    libtheora-1.1.1      | 330 KB    | : 100% 1.0/1 [00:00<00:00, 11.83it/s]\n    jupyter_console-6.2. | 26 KB     | : 100% 1.0/1 [00:00<00:00, 14.12it/s]\n    jupyterlab_widgets-1 | 109 KB    | : 100% 1.0/1 [00:00<00:00, 13.55it/s]\n    magma-cuda101-2.5.1  | 52.4 MB   | : 100% 1.0/1 [00:08<00:00,  8.66s/it]               \n    torchvision-0.2.1    | 75 KB     | : 100% 1.0/1 [00:00<00:00, 13.52it/s]\n    pandocfilters-1.4.3  | 14 KB     | : 100% 1.0/1 [00:00<00:00, 11.88it/s]\n    cftime-1.3.1         | 269 KB    | : 100% 1.0/1 [00:00<00:00, 13.53it/s]\n    tzlocal-2.1          | 29 KB     | : 100% 1.0/1 [00:00<00:00, 11.69it/s]\n    tqdm-4.56.0          | 80 KB     | : 100% 1.0/1 [00:00<00:00, 11.70it/s]\n    werkzeug-1.0.1       | 240 KB    | : 100% 1.0/1 [00:00<00:00, 12.91it/s]\n    nbformat-5.1.2       | 68 KB     | : 100% 1.0/1 [00:00<00:00, 11.94it/s]\n    widgetsnbextension-3 | 862 KB    | : 100% 1.0/1 [00:00<00:00,  9.49it/s]\n    qtconsole-4.7.7      | 96 KB     | : 100% 1.0/1 [00:00<00:00, 14.11it/s]\n    pyyaml-5.4.1         | 170 KB    | : 100% 1.0/1 [00:00<00:00, 14.29it/s]\n    libsodium-1.0.18     | 244 KB    | : 100% 1.0/1 [00:00<00:00, 13.12it/s]\n    tabulate-0.8.7       | 40 KB     | : 100% 1.0/1 [00:00<00:00, 14.88it/s]\n    packaging-20.8       | 36 KB     | : 100% 1.0/1 [00:00<00:00, 14.09it/s]\n    jupyterlab_pygments- | 8 KB      | : 100% 1.0/1 [00:00<00:00, 15.42it/s]\n    sympy-1.7.1          | 8.9 MB    | : 100% 1.0/1 [00:00<00:00,  1.50it/s]\n    curl-7.71.1          | 140 KB    | : 100% 1.0/1 [00:00<00:00, 13.03it/s]\n    libogg-1.3.2         | 194 KB    | : 100% 1.0/1 [00:00<00:00, 12.07it/s]\n    zeromq-4.3.3         | 500 KB    | : 100% 1.0/1 [00:00<00:00, 11.88it/s]\n    pyqt-5.9.2           | 4.5 MB    | : 100% 1.0/1 [00:00<00:00,  4.09it/s]\n    markupsafe-1.1.1     | 29 KB     | : 100% 1.0/1 [00:00<00:00, 15.47it/s]\n    send2trash-1.5.0     | 14 KB     | : 100% 1.0/1 [00:00<00:00, 11.63it/s]\n    libtiff-4.1.0        | 447 KB    | : 100% 1.0/1 [00:00<00:00, 13.50it/s]\n    nbconvert-6.0.7      | 480 KB    | : 100% 1.0/1 [00:00<00:00,  9.17it/s]\n    pexpect-4.8.0        | 53 KB     | : 100% 1.0/1 [00:00<00:00, 14.97it/s]\n    jupyter_core-4.7.0   | 68 KB     | : 100% 1.0/1 [00:00<00:00, 13.58it/s]\n    krb5-1.18.2          | 1.3 MB    | : 100% 1.0/1 [00:00<00:00,  9.48it/s]\n    nest-asyncio-1.4.3   | 11 KB     | : 100% 1.0/1 [00:00<00:00, 14.05it/s]\n    netcdf4-1.4.2        | 480 KB    | : 100% 1.0/1 [00:00<00:00, 11.78it/s]\n    pyzmq-20.0.0         | 438 KB    | : 100% 1.0/1 [00:00<00:00,  9.85it/s]\n    Preparing transaction: - \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\bdone\n    Verifying transaction: \\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\bdone\n    Executing transaction: - \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\bdone\n    Installing pip dependencies: | \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- \b\b\\ \b\b| \b\b/ \b\b- Ran pip subprocess with arguments:\n    ['/usr/local/envs/xenonpy/bin/python', '-m', 'pip', 'install', '-U', '-r', '/content/condaenv.9rgmnghx.requirements.txt']\n    Pip subprocess output:\n    Requirement already satisfied: ruamel.yaml in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from -r /content/condaenv.9rgmnghx.requirements.txt (line 1)) (0.16.12)\n    Requirement already satisfied: pybtex in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from -r /content/condaenv.9rgmnghx.requirements.txt (line 6)) (0.24.0)\n    Requirement already satisfied: tqdm in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from -r /content/condaenv.9rgmnghx.requirements.txt (line 8)) (4.56.0)\n    Collecting jupyterlab\n      Downloading jupyterlab-3.0.6-py3-none-any.whl (8.3 MB)\n    Requirement already satisfied: packaging in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (20.8)\n    Requirement already satisfied: ipython in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (7.16.1)\n    Requirement already satisfied: jupyter-core in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (4.7.0)\n    Requirement already satisfied: jinja2>=2.10 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (2.11.2)\n    Requirement already satisfied: tornado>=6.1.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (6.1)\n    Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jinja2>=2.10->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (1.1.1)\n    Collecting jupyter-server~=1.2\n      Downloading jupyter_server-1.2.2-py3-none-any.whl (184 kB)\n    Requirement already satisfied: pyzmq>=17 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (20.0.0)\n    Requirement already satisfied: ipython-genutils in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (0.2.0)\n    Requirement already satisfied: traitlets>=4.2.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (4.3.3)\n    Requirement already satisfied: nbformat in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (5.1.2)\n    Requirement already satisfied: jupyter-client>=6.1.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (6.1.7)\n    Requirement already satisfied: terminado>=0.8.3 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (0.9.2)\n    Requirement already satisfied: Send2Trash in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (1.5.0)\n    Requirement already satisfied: prometheus-client in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (0.9.0)\n    Requirement already satisfied: nbconvert in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (6.0.7)\n    Collecting anyio>=2.0.2\n      Downloading anyio-2.0.2-py3-none-any.whl (62 kB)\n    Requirement already satisfied: async-generator in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from anyio>=2.0.2->jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (1.10)\n    Requirement already satisfied: dataclasses in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from anyio>=2.0.2->jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (0.7)\n    Requirement already satisfied: idna>=2.8 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from anyio>=2.0.2->jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (2.10)\n    Requirement already satisfied: python-dateutil>=2.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyter-client>=6.1.1->jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (2.8.1)\n    Collecting jupyterlab-server~=2.0\n      Downloading jupyterlab_server-2.1.3-py3-none-any.whl (47 kB)\n    Requirement already satisfied: requests in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyterlab-server~=2.0->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (2.25.1)\n    Requirement already satisfied: jsonschema>=3.0.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jupyterlab-server~=2.0->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (3.2.0)\n    Requirement already satisfied: importlib-metadata in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jsonschema>=3.0.1->jupyterlab-server~=2.0->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (2.0.0)\n    Requirement already satisfied: pyrsistent>=0.14.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jsonschema>=3.0.1->jupyterlab-server~=2.0->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (0.17.3)\n    Requirement already satisfied: setuptools in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jsonschema>=3.0.1->jupyterlab-server~=2.0->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (52.0.0.post20210125)\n    Requirement already satisfied: six>=1.11.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jsonschema>=3.0.1->jupyterlab-server~=2.0->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (1.15.0)\n    Requirement already satisfied: attrs>=17.4.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jsonschema>=3.0.1->jupyterlab-server~=2.0->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (20.3.0)\n    Collecting nbclassic~=0.2\n      Downloading nbclassic-0.2.6-py3-none-any.whl (18 kB)\n    Requirement already satisfied: notebook<7 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from nbclassic~=0.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (6.2.0)\n    Requirement already satisfied: argon2-cffi in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from notebook<7->nbclassic~=0.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (20.1.0)\n    Requirement already satisfied: ipykernel in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from notebook<7->nbclassic~=0.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (5.3.4)\n    Collecting sniffio>=1.1\n      Downloading sniffio-1.2.0-py3-none-any.whl (10 kB)\n    Collecting contextvars>=2.1\n      Downloading contextvars-2.4.tar.gz (9.6 kB)\n    Collecting immutables>=0.9\n      Downloading immutables-0.14-cp36-cp36m-manylinux1_x86_64.whl (98 kB)\n    Requirement already satisfied: ptyprocess in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from terminado>=0.8.3->jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (0.7.0)\n    Requirement already satisfied: decorator in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from traitlets>=4.2.1->jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (4.4.2)\n    Collecting matminer\n      Downloading matminer-0.6.4.tar.gz (5.7 MB)\n    Requirement already satisfied: numpy>=1.19.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.9rgmnghx.requirements.txt (line 3)) (1.19.2)\n    Requirement already satisfied: plotly>=4.8.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.9rgmnghx.requirements.txt (line 3)) (4.14.3)\n    Requirement already satisfied: future>=0.18.2 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.9rgmnghx.requirements.txt (line 3)) (0.18.2)\n    Requirement already satisfied: sympy>=1.6 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.9rgmnghx.requirements.txt (line 3)) (1.7.1)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matminer->-r /content/condaenv.9rgmnghx.requirements.txt (line 3)) (4.0.2)\n    Collecting pandas>=1.0.4\n      Downloading pandas-1.1.5-cp36-cp36m-manylinux1_x86_64.whl (9.5 MB)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pandas>=1.0.4->matminer->-r /content/condaenv.9rgmnghx.requirements.txt (line 3)) (2020.5)\n    Collecting pint>=0.11\n      Downloading Pint-0.16.1-py2.py3-none-any.whl (205 kB)\n    Requirement already satisfied: retrying>=1.3.3 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from plotly>=4.8.1->matminer->-r /content/condaenv.9rgmnghx.requirements.txt (line 3)) (1.3.3)\n    Collecting pymatgen>=2020.4.29\n      Downloading pymatgen-2020.12.31.tar.gz (2.8 MB)\n    Requirement already satisfied: tabulate in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pymatgen>=2020.4.29->matminer->-r /content/condaenv.9rgmnghx.requirements.txt (line 3)) (0.8.7)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pymatgen>=2020.4.29->matminer->-r /content/condaenv.9rgmnghx.requirements.txt (line 3)) (1.16.0)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pymatgen>=2020.4.29->matminer->-r /content/condaenv.9rgmnghx.requirements.txt (line 3)) (2.5)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pymatgen>=2020.4.29->matminer->-r /content/condaenv.9rgmnghx.requirements.txt (line 3)) (3.3.2)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pymatgen>=2020.4.29->matminer->-r /content/condaenv.9rgmnghx.requirements.txt (line 3)) (3.3.0)\n    Requirement already satisfied: ruamel.yaml.clib>=0.1.2 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from ruamel.yaml->-r /content/condaenv.9rgmnghx.requirements.txt (line 1)) (0.2.2)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2020.4.29->matminer->-r /content/condaenv.9rgmnghx.requirements.txt (line 3)) (0.10.0)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2020.4.29->matminer->-r /content/condaenv.9rgmnghx.requirements.txt (line 3)) (2.4.7)\n    Requirement already satisfied: pillow>=6.2.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2020.4.29->matminer->-r /content/condaenv.9rgmnghx.requirements.txt (line 3)) (8.1.0)\n    Requirement already satisfied: certifi>=2020.06.20 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2020.4.29->matminer->-r /content/condaenv.9rgmnghx.requirements.txt (line 3)) (2020.12.5)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2020.4.29->matminer->-r /content/condaenv.9rgmnghx.requirements.txt (line 3)) (1.3.0)\n    Collecting pymongo>=3.10.1\n      Downloading pymongo-3.11.2-cp36-cp36m-manylinux2014_x86_64.whl (509 kB)\n    Requirement already satisfied: chardet<5,>=3.0.2 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from requests->jupyterlab-server~=2.0->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (4.0.0)\n    Requirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from requests->jupyterlab-server~=2.0->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (1.26.3)\n    Collecting scikit_learn>=0.23.1\n      Downloading scikit_learn-0.24.1-cp36-cp36m-manylinux2010_x86_64.whl (22.2 MB)\n    Requirement already satisfied: joblib>=0.11 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from scikit_learn>=0.23.1->matminer->-r /content/condaenv.9rgmnghx.requirements.txt (line 3)) (1.0.0)\n    Collecting scipy>=1.5.0\n      Downloading scipy-1.5.4-cp36-cp36m-manylinux1_x86_64.whl (25.9 MB)\n    Requirement already satisfied: mpmath>=0.19 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from sympy>=1.6->matminer->-r /content/condaenv.9rgmnghx.requirements.txt (line 3)) (1.1.0)\n    Collecting threadpoolctl>=2.0.0\n      Downloading threadpoolctl-2.1.0-py3-none-any.whl (12 kB)\n    Collecting uncertainties>=3.1.4\n      Downloading uncertainties-3.1.5-py2.py3-none-any.whl (246 kB)\n    Collecting mordred\n      Downloading mordred-1.2.0.tar.gz (128 kB)\n    Requirement already satisfied: PyYAML>=3.01 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pybtex->-r /content/condaenv.9rgmnghx.requirements.txt (line 6)) (5.4.1)\n    Requirement already satisfied: latexcodec>=1.0.4 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from pybtex->-r /content/condaenv.9rgmnghx.requirements.txt (line 6)) (2.0.1)\n    Collecting Python-Deprecated\n      Downloading Python-Deprecated-1.1.0.tar.gz (2.9 kB)\n    Collecting torchtext\n      Downloading torchtext-0.8.1-cp36-cp36m-manylinux1_x86_64.whl (7.0 MB)\n    Collecting torch==1.7.1\n      Downloading torch-1.7.1-cp36-cp36m-manylinux1_x86_64.whl (776.8 MB)\n    Collecting xenonpy\n      Downloading xenonpy-0.5.0-py3-none-any.whl (131 kB)\n    Requirement already satisfied: seaborn in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from xenonpy->-r /content/condaenv.9rgmnghx.requirements.txt (line 9)) (0.11.1)\n    Requirement already satisfied: cffi>=1.0.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from argon2-cffi->notebook<7->nbclassic~=0.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (1.14.4)\n    Requirement already satisfied: pycparser in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from cffi>=1.0.0->argon2-cffi->notebook<7->nbclassic~=0.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (2.20)\n    Collecting babel\n      Downloading Babel-2.9.0-py2.py3-none-any.whl (8.8 MB)\n    Requirement already satisfied: zipp>=0.5 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from importlib-metadata->jsonschema>=3.0.1->jupyterlab-server~=2.0->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (3.4.0)\n    Collecting importlib-resources\n      Downloading importlib_resources-5.1.0-py3-none-any.whl (24 kB)\n    Requirement already satisfied: pickleshare in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from ipython->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (0.7.5)\n    Requirement already satisfied: pexpect in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from ipython->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (4.8.0)\n    Requirement already satisfied: jedi>=0.10 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from ipython->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (0.18.0)\n    Requirement already satisfied: backcall in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from ipython->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (0.2.0)\n    Requirement already satisfied: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from ipython->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (3.0.8)\n    Requirement already satisfied: pygments in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from ipython->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (2.7.4)\n    Requirement already satisfied: parso<0.9.0,>=0.8.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from jedi>=0.10->ipython->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (0.8.1)\n    Requirement already satisfied: wcwidth in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->ipython->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (0.2.5)\n    Collecting json5\n      Downloading json5-0.9.5-py2.py3-none-any.whl (17 kB)\n    Requirement already satisfied: mistune<2,>=0.8.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from nbconvert->jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (0.8.4)\n    Requirement already satisfied: bleach in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from nbconvert->jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (3.2.3)\n    Requirement already satisfied: testpath in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from nbconvert->jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (0.4.4)\n    Requirement already satisfied: pandocfilters>=1.4.1 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from nbconvert->jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (1.4.3)\n    Requirement already satisfied: jupyterlab-pygments in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from nbconvert->jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (0.1.2)\n    Requirement already satisfied: entrypoints>=0.2.2 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from nbconvert->jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (0.3)\n    Requirement already satisfied: defusedxml in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from nbconvert->jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (0.6.0)\n    Requirement already satisfied: nbclient<0.6.0,>=0.5.0 in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from nbconvert->jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (0.5.1)\n    Requirement already satisfied: nest-asyncio in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from nbclient<0.6.0,>=0.5.0->nbconvert->jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (1.4.3)\n    Requirement already satisfied: webencodings in /usr/local/envs/xenonpy/lib/python3.6/site-packages (from bleach->nbconvert->jupyter-server~=1.2->jupyterlab->-r /content/condaenv.9rgmnghx.requirements.txt (line 5)) (0.5.1)\n    Collecting typing-extensions\n      Downloading typing_extensions-3.7.4.3-py3-none-any.whl (22 kB)\n    Building wheels for collected packages: contextvars, matminer, pymatgen, mordred, Python-Deprecated\n      Building wheel for contextvars (setup.py): started\n      Building wheel for contextvars (setup.py): finished with status 'done'\n      Created wheel for contextvars: filename=contextvars-2.4-py3-none-any.whl size=7665 sha256=5742d72e99282c9f5b19d346c015caf560f8b91d25f745aa0f151244206e72af\n      Stored in directory: /root/.cache/pip/wheels/41/11/53/911724983aa48deb94792432e14e518447212dd6c5477d49d3\n      Building wheel for matminer (setup.py): started\n      Building wheel for matminer (setup.py): finished with status 'done'\n      Created wheel for matminer: filename=matminer-0.6.4-py3-none-any.whl size=1172376 sha256=d73d57654c92120819b705470d05b8c9bfb01b7079bcda848b8140686d7e1485\n      Stored in directory: /root/.cache/pip/wheels/32/6c/43/1106db220f1884faae6a9ffed65511395f7f2794fad32f4f71\n      Building wheel for pymatgen (setup.py): started\n      Building wheel for pymatgen (setup.py): finished with status 'done'\n      Created wheel for pymatgen: filename=pymatgen-2020.12.31-cp36-cp36m-linux_x86_64.whl size=3654340 sha256=361f481bc6c3407ccaabac49bb1ad95c50e458c3dbe90cb7d097c52513af78b0\n      Stored in directory: /root/.cache/pip/wheels/28/54/46/edfa529a7082955264def0558eddc2ce3d7459ef5a0d106e96\n      Building wheel for mordred (setup.py): started\n      Building wheel for mordred (setup.py): finished with status 'done'\n      Created wheel for mordred: filename=mordred-1.2.0-py3-none-any.whl size=176721 sha256=c7e02e12a06ab23f2da8f8592ddd939b429c05d8efa42a2ef9829d0098536e1f\n      Stored in directory: /root/.cache/pip/wheels/94/e8/c6/0561efc609b8b695a4c0a98e76e439a97f33eadfd0dba949ee\n      Building wheel for Python-Deprecated (setup.py): started\n      Building wheel for Python-Deprecated (setup.py): finished with status 'done'\n      Created wheel for Python-Deprecated: filename=Python_Deprecated-1.1.0-py2.py3-none-any.whl size=3069 sha256=25cfe9c71f1509ce887c95c6e967cc797bd8ddb7c07efb83d7cff6736fb4976f\n      Stored in directory: /root/.cache/pip/wheels/7b/77/f4/889fb222210030f42875d19bb55b64ea2b394428066fd3a6f4\n    Successfully built contextvars matminer pymatgen mordred Python-Deprecated\n    Installing collected packages: immutables, contextvars, typing-extensions, sniffio, anyio, uncertainties, threadpoolctl, scipy, pandas, jupyter-server, json5, importlib-resources, babel, torch, scikit-learn, Python-Deprecated, pymongo, pymatgen, pint, nbclassic, mordred, jupyterlab-server, xenonpy, torchtext, matminer, jupyterlab\n      Attempting uninstall: scipy\n        Found existing installation: scipy 1.3.1\n        Uninstalling scipy-1.3.1:\n          Successfully uninstalled scipy-1.3.1\n      Attempting uninstall: pandas\n        Found existing installation: pandas 0.25.3\n        Uninstalling pandas-0.25.3:\n          Successfully uninstalled pandas-0.25.3\n      Attempting uninstall: torch\n        Found existing installation: torch 1.3.0\n        Uninstalling torch-1.3.0:\n          Successfully uninstalled torch-1.3.0\n      Attempting uninstall: scikit-learn\n        Found existing installation: scikit-learn 0.21.3\n        Uninstalling scikit-learn-0.21.3:\n          Successfully uninstalled scikit-learn-0.21.3\n      Attempting uninstall: pymatgen\n        Found existing installation: pymatgen 2019.11.11\n        Uninstalling pymatgen-2019.11.11:\n          Successfully uninstalled pymatgen-2019.11.11\n    Successfully installed Python-Deprecated-1.1.0 anyio-2.0.2 babel-2.9.0 contextvars-2.4 immutables-0.14 importlib-resources-5.1.0 json5-0.9.5 jupyter-server-1.2.2 jupyterlab-3.0.6 jupyterlab-server-2.1.3 matminer-0.6.4 mordred-1.2.0 nbclassic-0.2.6 pandas-1.1.5 pint-0.16.1 pymatgen-2020.12.31 pymongo-3.11.2 scikit-learn-0.24.1 scipy-1.5.4 sniffio-1.2.0 threadpoolctl-2.1.0 torch-1.7.1 torchtext-0.8.1 typing-extensions-3.7.4.3 uncertainties-3.1.5 xenonpy-0.5.0\n    \n    \b\bdone\n    #\n    # To activate this environment, use\n    #\n    #     $ conda activate xenonpy\n    #\n    # To deactivate an active environment, use\n    #\n    #     $ conda deactivate\n    \n    Collecting xenonpy==0.4.4\n      Downloading xenonpy-0.4.4-py3-none-any.whl (120 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 120 kB 8.9 MB/s \n    \u001b[?25hRequirement already satisfied: numpy>=1.16.* in /usr/local/lib/python3.6/site-packages (from xenonpy==0.4.4) (1.19.2)\n    Requirement already satisfied: pandas>=0.24.* in /usr/local/lib/python3.6/site-packages (from xenonpy==0.4.4) (1.1.5)\n    Requirement already satisfied: plotly in /usr/local/lib/python3.6/site-packages (from xenonpy==0.4.4) (4.14.3)\n    Requirement already satisfied: torch==1.* in /usr/local/lib/python3.6/site-packages (from xenonpy==0.4.4) (1.7.1)\n    Requirement already satisfied: ruamel.yaml in /usr/local/lib/python3.6/site-packages (from xenonpy==0.4.4) (0.15.87)\n    Requirement already satisfied: tqdm in /usr/local/lib/python3.6/site-packages (from xenonpy==0.4.4) (4.51.0)\n    Requirement already satisfied: pymatgen>=2019.5.* in /usr/local/lib/python3.6/site-packages (from xenonpy==0.4.4) (2020.10.20)\n    Requirement already satisfied: scipy>=1.2.* in /usr/local/lib/python3.6/site-packages (from xenonpy==0.4.4) (1.5.2)\n    Requirement already satisfied: requests in /usr/local/lib/python3.6/site-packages (from xenonpy==0.4.4) (2.24.0)\n    Requirement already satisfied: typing_extensions in /usr/local/lib/python3.6/site-packages (from torch==1.*->xenonpy==0.4.4) (3.7.4.3)\n    Requirement already satisfied: dataclasses in /usr/local/lib/python3.6/site-packages (from torch==1.*->xenonpy==0.4.4) (0.7)\n    Collecting joblib>=0.13.*\n      Downloading joblib-1.0.0-py3-none-any.whl (302 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 302 kB 14.5 MB/s \n    \u001b[?25hRequirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.6/site-packages (from pandas>=0.24.*->xenonpy==0.4.4) (2.8.1)\n    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/site-packages (from pandas>=0.24.*->xenonpy==0.4.4) (2020.5)\n    Requirement already satisfied: spglib>=1.9.9.44 in /usr/local/lib/python3.6/site-packages (from pymatgen>=2019.5.*->xenonpy==0.4.4) (1.16.0)\n    Requirement already satisfied: palettable>=3.1.1 in /usr/local/lib/python3.6/site-packages (from pymatgen>=2019.5.*->xenonpy==0.4.4) (3.3.0)\n    Requirement already satisfied: sympy in /usr/local/lib/python3.6/site-packages (from pymatgen>=2019.5.*->xenonpy==0.4.4) (1.7.1)\n    Requirement already satisfied: matplotlib>=1.5 in /usr/local/lib/python3.6/site-packages (from pymatgen>=2019.5.*->xenonpy==0.4.4) (3.3.3)\n    Requirement already satisfied: networkx>=2.2 in /usr/local/lib/python3.6/site-packages (from pymatgen>=2019.5.*->xenonpy==0.4.4) (2.5)\n    Requirement already satisfied: tabulate in /usr/local/lib/python3.6/site-packages (from pymatgen>=2019.5.*->xenonpy==0.4.4) (0.8.7)\n    Requirement already satisfied: uncertainties>=3.1.4 in /usr/local/lib/python3.6/site-packages (from pymatgen>=2019.5.*->xenonpy==0.4.4) (3.1.5)\n    Requirement already satisfied: monty>=3.0.2 in /usr/local/lib/python3.6/site-packages (from pymatgen>=2019.5.*->xenonpy==0.4.4) (4.0.2)\n    Requirement already satisfied: pillow>=6.2.0 in /usr/local/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2019.5.*->xenonpy==0.4.4) (8.1.0)\n    Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2019.5.*->xenonpy==0.4.4) (1.3.1)\n    Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3 in /usr/local/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2019.5.*->xenonpy==0.4.4) (2.4.7)\n    Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/site-packages (from matplotlib>=1.5->pymatgen>=2019.5.*->xenonpy==0.4.4) (0.10.0)\n    Requirement already satisfied: six in /usr/local/lib/python3.6/site-packages (from cycler>=0.10->matplotlib>=1.5->pymatgen>=2019.5.*->xenonpy==0.4.4) (1.15.0)\n    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/site-packages (from networkx>=2.2->pymatgen>=2019.5.*->xenonpy==0.4.4) (4.4.2)\n    Requirement already satisfied: retrying>=1.3.3 in /usr/local/lib/python3.6/site-packages (from plotly->xenonpy==0.4.4) (1.3.3)\n    Collecting scikit-learn>=0.21.*\n      Using cached scikit_learn-0.24.1-cp36-cp36m-manylinux2010_x86_64.whl (22.2 MB)\n    Collecting threadpoolctl>=2.0.0\n      Using cached threadpoolctl-2.1.0-py3-none-any.whl (12 kB)\n    Requirement already satisfied: future in /usr/local/lib/python3.6/site-packages (from uncertainties>=3.1.4->pymatgen>=2019.5.*->xenonpy==0.4.4) (0.18.2)\n    Collecting mordred\n      Using cached mordred-1.2.0-py3-none-any.whl\n    Collecting Python-Deprecated\n      Using cached Python_Deprecated-1.1.0-py2.py3-none-any.whl\n    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/site-packages (from requests->xenonpy==0.4.4) (3.0.4)\n    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/site-packages (from requests->xenonpy==0.4.4) (2020.12.5)\n    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/site-packages (from requests->xenonpy==0.4.4) (1.25.11)\n    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/site-packages (from requests->xenonpy==0.4.4) (2.10)\n    Collecting seaborn\n      Downloading seaborn-0.11.1-py3-none-any.whl (285 kB)\n    \u001b[K     |\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 285 kB 17.5 MB/s \n    \u001b[?25hRequirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/site-packages (from sympy->pymatgen>=2019.5.*->xenonpy==0.4.4) (1.1.0)\n    Installing collected packages: threadpoolctl, joblib, seaborn, scikit-learn, Python-Deprecated, mordred, xenonpy\n    Successfully installed Python-Deprecated-1.1.0 joblib-1.0.0 mordred-1.2.0 scikit-learn-0.24.1 seaborn-0.11.1 threadpoolctl-2.1.0 xenonpy-0.4.4\n    0.4.4\n\n\n**step 6**\r\n\r\nInstall XenonPy samples\n\n\n```\n!git clone https://github.com/by-student-2017/xenonpy-gcolab.git\r\n%cd xenonpy-gcolab/0.4.4/samples\r\n!wget https://github.com/yoshida-lab/XenonPy/releases/download/v0.4.1/iQSPR_sample_data.csv\r\n!ls\n```\n\n    Cloning into 'xenonpy-gcolab'...\n    remote: Enumerating objects: 234, done.\u001b[K\n    remote: Counting objects: 100% (234/234), done.\u001b[K\n    remote: Compressing objects: 100% (130/130), done.\u001b[K\n    remote: Total 234 (delta 106), reused 217 (delta 92), pack-reused 0\n    Receiving objects: 100% (234/234), 5.46 MiB | 28.69 MiB/s, done.\n    Resolving deltas: 100% (106/106), done.\n    /content/xenonpy-gcolab/0.4.4/samples\n    --2021-01-29 10:42:43--  https://github.com/yoshida-lab/XenonPy/releases/download/v0.4.1/iQSPR_sample_data.csv\n    Resolving github.com (github.com)... 192.30.255.112\n    Connecting to github.com (github.com)|192.30.255.112|:443... connected.\n    HTTP request sent, awaiting response... 302 Found\n    Location: https://github-releases.githubusercontent.com/117819602/14925c00-e455-11e9-9065-7d987b463251?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20210129%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20210129T104243Z&X-Amz-Expires=300&X-Amz-Signature=3fc211243a700c3a1839e7d0073a6beccbbe5cefd2b8c6f772f4025b9e3e402f&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=117819602&response-content-disposition=attachment%3B%20filename%3DiQSPR_sample_data.csv&response-content-type=application%2Foctet-stream [following]\n    --2021-01-29 10:42:43--  https://github-releases.githubusercontent.com/117819602/14925c00-e455-11e9-9065-7d987b463251?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20210129%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20210129T104243Z&X-Amz-Expires=300&X-Amz-Signature=3fc211243a700c3a1839e7d0073a6beccbbe5cefd2b8c6f772f4025b9e3e402f&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=117819602&response-content-disposition=attachment%3B%20filename%3DiQSPR_sample_data.csv&response-content-type=application%2Foctet-stream\n    Resolving github-releases.githubusercontent.com (github-releases.githubusercontent.com)... 185.199.108.154, 185.199.109.154, 185.199.110.154, ...\n    Connecting to github-releases.githubusercontent.com (github-releases.githubusercontent.com)|185.199.108.154|:443... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 954073 (932K) [application/octet-stream]\n    Saving to: \u2018iQSPR_sample_data.csv\u2019\n    \n    iQSPR_sample_data.c 100%[===================>] 931.71K  --.-KB/s    in 0.07s   \n    \n    2021-01-29 10:42:43 (13.5 MB/s) - \u2018iQSPR_sample_data.csv\u2019 saved [954073/954073]\n    \n    calculate_descriptors.ipynb\t    random_nn_model_and_training.ipynb\n    custom_descriptor_calculator.ipynb  sample_data_building.ipynb\n    dataset_and_preset.ipynb\t    set1\n    installation.ipynb\t\t    set2\n    iQSPR.ipynb\t\t\t    storage.ipynb\n    iQSPR_sample_data.csv\t\t    tools.ipynb\n    mp_ids.txt\t\t\t    transfer_learning.ipynb\n    nn_model_build.ipynb\t\t    visualization.ipynb\n    pre-trained_model_library.ipynb\n\n\n**step 7**\r\n\r\nCheck versions one more.\n\n\n```\nimport rdkit\r\nprint(rdkit.__version__)\r\nimport torch\r\nprint(torch.__version__)\r\nimport pymatgen\r\nprint(pymatgen.__version__)\r\nimport xenonpy\r\nprint(xenonpy.__version__)\n```\n\n    2020.03.3\n    1.7.0+cu101\n    2020.10.20\n    0.4.4\n\n", "meta": {"hexsha": "2f2e72b93ce42acb0b54ca9c5b750f426a9b9843", "size": 114775, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "0.4.4/samples/installation.ipynb", "max_stars_repo_name": "by-student-2017/xenonpy-gcolab", "max_stars_repo_head_hexsha": "9a93121803f4f7e1af8b36a9b5e67daff02ac6c6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "0.4.4/samples/installation.ipynb", "max_issues_repo_name": "by-student-2017/xenonpy-gcolab", "max_issues_repo_head_hexsha": "9a93121803f4f7e1af8b36a9b5e67daff02ac6c6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0.4.4/samples/installation.ipynb", "max_forks_repo_name": "by-student-2017/xenonpy-gcolab", "max_forks_repo_head_hexsha": "9a93121803f4f7e1af8b36a9b5e67daff02ac6c6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 87.6145038168, "max_line_length": 5144, "alphanum_fraction": 0.4988194293, "converted": true, "num_tokens": 41410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03514484336903119, "lm_q2_score": 0.024798161411793702, "lm_q1q2_score": 0.000871527498657443}}
{"text": "```python\nfrom jupyterthemes import get_themes\nfrom jupyterthemes.stylefx import set_nb_theme\nthemes = get_themes()\nset_nb_theme(themes[1])\n```\n\n\n\n\n<style> @font-face {\n font-family: 'Droid Sans Mono';\n font-weight: normal;\n font-style: normal;\n src: local('Droid Sans Mono'), url('fonts/droid-sans-mono.woff') format('woff');\n}\n@font-face {\n font-family: 'Exo_2';\n font-weight: normal;\n font-style: normal;\n src: local('Exo_2'), url('fonts/exo-II-regular.ttf') format('truetype');\n}\n@font-face {\n font-family: 'Fira Code';\n font-weight: normal;\n font-style: normal;\n src: local('Fira Code'), url('fonts/firacode.otf') format('opentype');\n}\n@font-face {\n font-family: 'Lora';\n font-weight: normal;\n font-style: normal;\n src: local('Lora'), url('fonts/Lora-Regular.ttf') format('truetype');\n}\ndiv#notebook {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n line-height: 170%;\n color: #303030;\n}\nbody,\ndiv.body {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n color: #303030;\n background-color: #ffffff;\n background: #ffffff;\n}\nbody.notebook_app {\n padding: 0;\n background-color: #ffffff;\n background: #ffffff;\n padding-right: 0px !important;\n overflow-y: hidden;\n}\na {\n font-family: \"Exo_2\", sans-serif;\n color: #303030;\n}\na:hover,\na:focus {\n color: #2f2f2f;\n}\n.list_header,\ndiv#notebook_list_header.row.list_header {\n font-size: 14pt;\n color: #2f2f2f;\n background-color: #ffffff;\n}\ndiv#cluster_list_header.row.list_header,\ndiv#running .row.list_header {\n font-size: 14pt;\n color: #303030;\n background: #eeeeee;\n background-color: #eeeeee;\n border-bottom: 2px solid rgba(180,180,180,.30);\n}\ndiv#cluster_list > div.list_item.row,\ndiv#cluster_list > div.list_item.row:hover {\n background: #f7f7f7;\n background-color: #f7f7f7;\n}\ndiv#clusters.tab-pane.active {\n font-size: 12.0pt;\n padding: 4px 0 4px 0;\n}\n#running .panel-group .panel .panel-heading {\n font-size: 14pt;\n color: #303030;\n padding: 8px 8px;\n background: #eeeeee;\n background-color: #eeeeee;\n}\n#running .panel-group .panel .panel-heading a {\n font-size: 14pt;\n color: #303030;\n}\n#running .panel-group .panel .panel-heading a:focus,\n#running .panel-group .panel .panel-heading a:hover {\n font-size: 14pt;\n color: #303030;\n}\n#running .panel-group .panel .panel-body .list_container .list_item {\n background: #f7f7f7;\n background-color: #f7f7f7;\n padding: 2px;\n border-bottom: 2px solid rgba(180,180,180,.30);\n}\n#running .panel-group .panel .panel-body .list_container .list_item:hover {\n background: #f7f7f7;\n background-color: #f7f7f7;\n}\n#running .panel-group .panel .panel-body {\n padding: 2px;\n}\ndiv.running_list_info.toolbar_info {\n font-size: 12.0pt;\n padding: 4px 0 4px 0;\n height: inherit;\n line-height: inherit;\n text-shadow: none;\n}\n.list_placeholder {\n font-weight: normal;\n}\n#tree-selector {\n padding: 0px;\n}\n#project_name > ul > li > a > i.fa.fa-home {\n color: #ff7823;\n font-size: 17pt;\n display: inline-block;\n position: static;\n padding: 0px 0px;\n font-weight: normal;\n text-align: center;\n vertical-align: text-top;\n}\n#project_name {\n display: inline-flex;\n padding-left: 7px;\n margin-left: -2px;\n margin-bottom: -20px;\n text-align: -webkit-auto;\n vertical-align: text-top;\n}\ndiv#notebook_toolbar div.dynamic-instructions {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n}\n.toolbar_info {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n color: #303030;\n text-shadow: none;\n border: none;\n height: inherit;\n line-height: inherit;\n}\n.list_container {\n font-size: 12.0pt;\n color: #303030;\n border: none;\n text-shadow: none !important;\n}\n.list_container > div {\n border-bottom: 1px solid rgba(180,180,180,.14);\n font-size: 12.0pt;\n}\n.list_header > div,\n.list_item > div {\n padding-left: 0px;\n}\n.list_header > div input,\n.list_item > div input {\n top: 0px;\n}\n.list_header > div .item_link,\n.list_item > div .item_link {\n margin-left: -1px;\n vertical-align: middle;\n line-height: 22px;\n font-size: 12.0pt;\n}\n.item_icon {\n font-size: 12.0pt;\n vertical-align: middle;\n}\n.list_item input:not([type=\"checkbox\"]) {\n padding-right: 0px;\n height: auto;\n width: 20%;\n margin: 6px 0 0;\n margin-top: 1px;\n}\n#button-select-all {\n height: auto;\n font-size: 12.0pt;\n padding: 5px;\n min-width: 65px;\n z-index: 0;\n}\nbutton#tree-selector-btn {\n height: auto;\n font-size: 12.0pt;\n padding: 5px;\n}\ninput#select-all.pull-left.tree-selector {\n margin-left: 7px;\n margin-right: 2px;\n margin-top: 5px;\n}\ninput[type=\"radio\"],\ninput[type=\"checkbox\"] {\n margin: 6px 0 0;\n margin-top: 1px;\n line-height: normal;\n}\n.list_container a {\n font-size: 17px;\n color: #303030;\n border: none;\n text-shadow: none !important;\n font-weight: normal;\n font-style: normal;\n}\ndiv.list_container a:hover {\n color: #2f2f2f;\n}\ndiv.list_item:hover {\n background-color: #fafafa;\n}\n.breadcrumb > li {\n font-size: 12.0pt;\n color: #303030;\n border: none;\n text-shadow: none !important;\n}\nul#tabs a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n font-weight: normal;\n font-style: normal;\n border-color: transparent;\n text-shadow: none !important;\n}\n.nav-tabs {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n font-weight: normal;\n font-style: normal;\n background: #ffffff;\n text-shadow: none !important;\n border-color: transparent;\n border-bottom-color: rgba(180,180,180,.30);\n}\n.nav-tabs > li > a:hover {\n color: #2f2f2f;\n background-color: rgba(180,180,180,.14);\n}\n.nav-tabs > li > a:active,\n.nav-tabs > li > a:focus,\n.nav-tabs > li.active > a,\n.nav-tabs > li.active > a:focus,\n.nav-tabs > li.active > a:hover,\n.nav-tabs > li.active > a,\n.nav-tabs > li.active > a:hover,\n.nav-tabs > li.active > a:focus {\n color: #1c1c1c;\n background-color: #eeeeee;\n border: 1px solid transparent;\n border-bottom-color: transparent;\n cursor: default;\n}\n.nav > li > a:hover,\n.nav > li > a:focus {\n text-decoration: none;\n background-color: rgba(180,180,180,.14);\n}\n.nav > li.disabled > a,\n.nav > li.disabled > a:hover {\n color: #aaaaaa;\n}\ndiv#notebook {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n padding-top: 4px;\n}\n.notebook_app {\n background-color: #ffffff;\n}\n#notebook-container {\n padding: 13px;\n background-color: #ffffff;\n min-height: 0px;\n box-shadow: none;\n width: 980px;\n margin-right: auto;\n margin-left: auto;\n}\ndiv#ipython-main-app.container {\n width: 980px;\n margin-right: auto;\n margin-left: auto;\n margin-right: auto;\n margin-left: auto;\n}\n.container {\n width: 980px;\n margin-right: auto;\n margin-left: auto;\n}\n.notebook_app #header {\n box-shadow: none !important;\n background-color: #ffffff;\n border-bottom: 2px solid rgba(180,180,180,.14);\n}\n#header {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n box-shadow: none;\n background-color: #ffffff;\n}\n#header .header-bar {\n background: #ffffff;\n background-color: #ffffff;\n}\nbody > #header .header-bar {\n width: 100%;\n background: #ffffff;\n}\n#menubar {\n background-color: #ffffff;\n}\n#menubar .navbar,\n.navbar-default {\n background-color: #ffffff;\n margin-bottom: 0px;\n}\n.navbar {\n border: none;\n}\n.navbar-default {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n background-color: #ffffff;\n border-color: rgba(180,180,180,.14);\n line-height: 1.5em;\n padding-bottom: 0px;\n}\n.navbar-default .navbar-nav > li > a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n color: #303030;\n display: block;\n line-height: 1.5em;\n padding-top: 8px;\n padding-bottom: 6px;\n}\n.navbar-default .navbar-nav > li > a:hover,\n.navbar-default .navbar-nav > li > a:focus {\n color: #2f2f2f;\n background-color: rgba(180,180,180,.14);\n border-color: rgba(180,180,180,.14);\n line-height: 1.5em;\n}\n.navbar-default .navbar-nav > .open > a,\n.navbar-default .navbar-nav > .open > a:hover,\n.navbar-default .navbar-nav > .open > a:focus {\n color: #1c1c1c;\n background-color: rgba(180,180,180,.14);\n border-color: rgba(180,180,180,.14);\n line-height: 1.5em;\n}\n.edit_mode .modal_indicator:before {\n font-size: 13pt;\n color: #2c85f7;\n content: \"\\f040\";\n}\n.item_icon {\n color: #126dce;\n}\n.item_buttons .kernel-name {\n font-size: 13pt;\n color: #126dce;\n line-height: 22px;\n}\n.running_notebook_icon:before {\n color: #009e07 !important;\n}\n.item_buttons .running-indicator {\n padding-top: 2px;\n color: #009e07;\n}\n#modal_indicator {\n float: right !important;\n color: #126dce;\n background: #ffffff;\n background-color: #ffffff;\n}\n#kernel_indicator {\n float: right !important;\n color: #ff7823;\n background: #ffffff;\n background-color: #ffffff;\n font-size: 14.5pt;\n border-left: 2px solid #ff7823;\n padding-bottom: 2px;\n}\n#kernel_indicator .kernel_indicator_name {\n color: #ff7823;\n background: #ffffff;\n background-color: #ffffff;\n font-size: 14.5pt;\n padding-left: 5px;\n padding-right: 5px;\n}\ndiv.notification_widget.info,\n.notification_widget.info,\n.notification_widget:active:hover,\n.notification_widget.active:hover,\n.open > .dropdown-toggle.notification_widget:hover,\n.notification_widget:active:focus,\n.notification_widget.active:focus,\n.open > .dropdown-toggle.notification_widget:focus,\n.notification_widget:active.focus,\n.notification_widget.active.focus,\n.open > .dropdown-toggle.notification_widget.focus,\ndiv#notification_notebook.notification_widget.btn.btn-xs.navbar-btn,\ndiv#notification_notebook.notification_widget.btn.btn-xs.navbar-btn:hover,\ndiv#notification_notebook.notification_widget.btn.btn-xs.navbar-btn:focus {\n color: #126dce;\n background-color: #ffffff;\n border-color: #ffffff;\n}\n#notification_area,\ndiv.notification_area {\n float: right !important;\n position: static;\n}\n#kernel_logo_widget,\n#kernel_logo_widget .current_kernel_logo {\n display: none;\n}\ndiv#ipython_notebook {\n display: none;\n}\ni.fa.fa-icon {\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n text-rendering: auto;\n}\n.fa {\n display: inline-block;\n font: normal normal normal 12pt/1 \"FontAwesome\", \"Exo_2\", sans-serif;\n text-rendering: auto;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n.dropdown-menu {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n box-shadow: none;\n padding: 0px;\n text-align: left;\n border: 2px solid rgba(180,180,180,.30);\n background-color: #ffffff;\n background: #ffffff;\n line-height: 1.3;\n margin: 0px;\n}\n.dropdown-menu:hover {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n border: 2px solid rgba(180,180,180,.30);\n background-color: #ffffff;\n box-shadow: none;\n line-height: 1.3;\n}\n.dropdown-header {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n display: block;\n color: #ff7823;\n text-decoration: underline;\n white-space: nowrap;\n padding: 8px 0px 0px 6px;\n line-height: 1.3;\n}\n.dropdown-menu > li > a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n line-height: 1.3;\n display: block;\n padding: 10px 25px 10px 14px;\n color: #303030;\n background-color: #ffffff;\n background: #ffffff;\n}\n.dropdown-menu > li > a:hover {\n color: #2f2f2f;\n background-color: rgba(180,180,180,.14);\n background: rgba(180,180,180,.14);\n border-color: rgba(180,180,180,.14);\n}\n.dropdown-menu .divider {\n height: 2px;\n margin: 0px 0px;\n overflow: hidden;\n background-color: rgba(180,180,180,.30);\n}\n.dropdown-submenu > .dropdown-menu {\n top: 0;\n left: 100%;\n margin-top: -2px;\n margin-left: 0px;\n padding-top: 0px;\n}\n.dropdown-menu > .disabled > a,\n.dropdown-menu > .disabled > a:hover,\n.dropdown-menu > .disabled > a:focus {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n font-weight: normal;\n color: #aaaaaa;\n padding: none;\n display: block;\n clear: both;\n line-height: 1.2;\n white-space: nowrap;\n}\n.dropdown-submenu > a:after {\n color: #303030;\n margin-right: -16px;\n}\n.dropdown-submenu:hover > a:after,\n.dropdown-submenu:active > a:after,\n.dropdown-submenu:focus > a:after,\n.dropdown-submenu:visited > a:after {\n color: #ff7823;\n margin-right: -16px;\n}\ndiv.kse-dropdown > .dropdown-menu,\n.kse-dropdown > .dropdown-menu {\n min-width: 0;\n top: 94%;\n}\n.btn,\n.btn-default {\n font-family: \"Exo_2\", sans-serif;\n color: #303030;\n background: #ebebeb;\n background-color: #ebebeb;\n border: 2px solid #e8e8e8;\n font-weight: normal;\n box-shadow: none;\n text-shadow: none;\n border-radius: 2px;\n font-size: inherit;\n}\n.btn:hover,\n.btn:active:hover,\n.btn.active:hover,\n.btn-default:hover,\n.open > .dropdown-toggle.btn-default:hover,\n.open > .dropdown-toggle.btn:hover {\n color: #2f2f2f;\n background-color: #e4e4e4;\n background: #e4e4e4;\n border-color: #e4e4e4;\n background-image: none;\n box-shadow: none !important;\n border-radius: 2px;\n}\n.btn:active,\n.btn.active,\n.btn:active:focus,\n.btn.active:focus,\n.btn:active.focus,\n.btn.active.focus,\n.btn-default:focus,\n.btn-default.focus,\n.btn-default:active,\n.btn-default.active,\n.btn-default:active:hover,\n.btn-default.active:hover,\n.btn-default:active:focus,\n.btn-default.active:focus,\n.btn-default:active.focus,\n.btn-default.active.focus,\n.open > .dropdown-toggle.btn:focus,\n.open > .dropdown-toggle.btn.focus,\n.open > .dropdown-toggle.btn-default {\n color: #1c1c1c;\n background-color: #e4e4e4;\n background: #e4e4e4;\n border-color: #e4e4e4;\n background-image: none;\n box-shadow: none !important;\n border-radius: 2px;\n}\n.item_buttons > .btn,\n.item_buttons > .btn-group,\n.item_buttons > .input-group {\n margin-left: 5px;\n background: #eeeeee;\n background-color: #eeeeee;\n border: 2px solid #eeeeee;\n}\n.item_buttons > .btn:hover,\n.item_buttons > .btn-group:hover,\n.item_buttons > .input-group:hover {\n margin-left: 5px;\n background: #e9e9e9;\n background-color: #e9e9e9;\n border: 2px solid #e9e9e9;\n}\n.btn-group > .btn-mini,\n.btn-sm,\n.btn-group-sm > .btn,\n.btn-xs,\n.btn-group-xs > .btn,\n.alternate_upload .btn-upload,\n.btn-group,\n.btn-group-vertical {\n font-size: 12.0pt;\n font-weight: normal;\n}\n.btn-xs,\n.btn-group-xs > .btn {\n font-size: 12.0pt;\n background-image: none;\n font-weight: normal;\n text-shadow: none;\n display: inline-table;\n}\n.alternate_upload .btn-upload {\n display: none;\n}\n.alternate_upload input.fileinput {\n display: none;\n}\nbutton.close {\n border: 0px none;\n font-family: sans-serif;\n font-size: 25pt;\n}\n.dynamic-buttons {\n font-size: inherit;\n padding-top: 0px;\n display: inline-block;\n}\n.close {\n color: #de143d;\n opacity: .5;\n text-shadow: none;\n}\n.close:hover {\n color: #de143d;\n opacity: 1;\n}\ndiv.btn.btn-default.output_collapsed {\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: #eeeeee;\n}\ndiv.btn.btn-default.output_collapsed:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border-color: #e9e9e9;\n}\ndiv.nbext-enable-btns .btn[disabled],\ndiv.nbext-enable-btns .btn[disabled]:hover,\n.btn-default.disabled,\n.btn-default[disabled],\n.btn-default.disabled:hover,\n.btn-default[disabled]:hover,\nfieldset[disabled] .btn-default:hover,\n.btn-default.disabled:focus,\n.btn-default[disabled]:focus,\nfieldset[disabled] .btn-default:focus,\n.btn-default.disabled.focus,\n.btn-default[disabled].focus,\nfieldset[disabled] .btn-default.focus {\n color: #4a4a4a;\n background: #e8e8e8;\n background-color: #e8e8e8;\n border-color: #e8e8e8;\n}\n.input-group-addon {\n padding: 2px 5px;\n font-size: 12.0pt;\n font-weight: normal;\n height: auto;\n color: #303030;\n text-align: center;\n background-color: #ffffff;\n border: none;\n}\n.btn-group > .btn + .dropdown-toggle {\n padding-left: 8px;\n padding-right: 8px;\n height: 100%;\n border-left: 2px solid #ff7823 !important;\n}\n.btn-group > .btn + .dropdown-toggle:hover {\n border-left: 2px solid #ff7823 !important;\n}\n.input-group-btn {\n position: relative;\n font-size: inherit;\n white-space: nowrap;\n}\n.input-group-btn:first-child > .btn,\n.input-group-btn:first-child > .btn-group {\n background: #eeeeee;\n background-color: #eeeeee;\n border: 1px solid #e9e9e9;\n margin: 2px;\n font-size: inherit;\n}\n.input-group-btn:first-child > .btn:hover,\n.input-group-btn:first-child > .btn-group:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border: 1px solid #e9e9e9;\n margin: 2px;\n font-size: inherit;\n}\ndiv.modal .btn-group > .btn:first-child {\n background: #eeeeee;\n background-color: #eeeeee;\n border: 1px solid #e9e9e9;\n margin-top: 0px !important;\n margin-left: 0px;\n margin-bottom: 2px;\n}\ndiv.modal .btn-group > .btn:first-child:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border: 1px solid #e9e9e9;\n}\ndiv.modal > button,\ndiv.modal-footer > button {\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: #eeeeee;\n}\ndiv.modal > button:hover,\ndiv.modal-footer > button:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border-color: #e9e9e9;\n}\n.modal-content {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n position: relative;\n background: #eeeeee;\n background-color: #eeeeee;\n border: none;\n border-radius: 1px;\n background-clip: padding-box;\n outline: none;\n}\n.modal-header {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n color: #303030;\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: rgba(180,180,180,.30);\n padding: 12px;\n min-height: 16.4286px;\n}\n.modal-content h4 {\n font-family: \"Exo_2\", sans-serif;\n font-size: 16pt;\n color: #303030;\n padding: 5px;\n}\n.modal-body {\n background-color: #ffffff;\n position: relative;\n padding: 15px;\n}\n.modal-footer {\n padding: 10px;\n text-align: right;\n background-color: #f7f7f7;\n border-top: 1px solid rgba(180,180,180,.30);\n}\n.alert-info {\n background-color: #fdfdfd;\n border-color: rgba(180,180,180,.30);\n color: #303030;\n}\n.modal-header .close {\n margin-top: -5px;\n font-size: 25pt;\n}\n.modal-backdrop,\n.modal-backdrop.in {\n opacity: 0.75;\n background-color: #eeeeee;\n}\ndiv.panel,\ndiv.panel-default,\n.panel,\n.panel-default {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n background-color: #f7f7f7;\n color: #303030;\n margin-bottom: 14px;\n border: 0;\n box-shadow: none;\n}\ndiv.panel > .panel-heading,\ndiv.panel-default > .panel-heading {\n font-size: 14pt;\n color: #303030;\n background: #eeeeee;\n background-color: #eeeeee;\n border: 0;\n}\n.modal .modal-dialog {\n min-width: 950px;\n margin: 50px auto;\n}\ndiv.container-fluid {\n margin-right: auto;\n margin-left: auto;\n padding-left: 7px;\n padding-right: 12px;\n}\ndiv.form-control,\n.form-control {\n font-family: \"Exo_2\", sans-serif;\n font-size: inherit;\n color: #303030;\n background-color: #ffffff;\n border: 2px solid #e7e7e7;\n margin-left: 2px;\n height: auto;\n box-shadow: none;\n padding: 6px 12px;\n transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;\n}\n.form-group.list-group-item {\n color: #303030;\n background-color: #f7f7f7;\n border-color: rgba(180,180,180,.30);\n margin-bottom: 0px;\n}\ninput,\nbutton,\nselect,\ntextarea {\n background-color: #ffffff;\n font-weight: normal;\n border: 2px solid rgba(180,180,180,.30);\n}\nselect.form-control.select-xs {\n height: auto;\n}\ndiv.output.output_scroll {\n box-shadow: none;\n}\n::-webkit-scrollbar-track {\n -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.11);\n background-color: #d0d0d0;\n border-radius: 6px;\n}\n::-webkit-scrollbar {\n width: 14px;\n height: 10px;\n background-color: #d0d0d0;\n border-radius: 6px;\n}\n::-webkit-scrollbar-thumb {\n background-color: #ffffff;\n background-image: -webkit-gradient(linear,40% 0%,75% 86%,from(#ff6b0f ),color-stop(0.5,#ff8b42 ),to(#ff6b0f ));\n min-height: 60px;\n border-radius: 2px;\n}\ndiv.input_area {\n background-color: #efefef;\n padding-right: 1.2em;\n border: 0px;\n border-top-left-radius: 0px;\n border-top-right-radius: 2px;\n border-bottom-left-radius: 0px;\n border-bottom-right-radius: 0px;\n}\ndiv.cell {\n padding: 0px;\n background: #efefef;\n background-color: #efefef;\n border: medium solid #ffffff;\n border-top-right-radius: 2px;\n border-top-left-radius: 2px;\n}\ndiv.cell.selected {\n background: #efefef;\n background-color: #efefef;\n border: medium solid #ff7823;\n padding: 0px;\n border-top-right-radius: 2px;\n border-top-left-radius: 2px;\n}\n.edit_mode div.cell.selected {\n padding: 0px;\n background: #efefef;\n background-color: #efefef;\n border: medium solid #ffd5bb;\n border-top-right-radius: 2px;\n border-top-left-radius: 2px;\n}\ndiv.cell.edit_mode {\n padding: 0px;\n background: #efefef;\n background-color: #efefef;\n border: medium solid #ffd5bb;\n border-top-right-radius: 2px;\n border-top-left-radius: 2px;\n}\ndiv.prompt,\n.prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n font-weight: normal;\n color: #aaaaaa;\n line-height: 170%;\n padding: 0px;\n padding-top: 4px;\n padding-left: .25em;\n text-align: left !important;\n min-width: 12ex;\n width: 12ex;\n}\ndiv.prompt.input_prompt {\n background-color: #efefef;\n border-right: 2px solid rgba(240,147,43,.50);\n border-top-left-radius: 2px;\n border-top-right-radius: 0px;\n border-bottom-left-radius: 0px;\n border-bottom-right-radius: 0px;\n min-width: 12ex;\n width: 12ex !important;\n}\ndiv.output_wrapper {\n background-color: #ffffff;\n border: 0px;\n margin-bottom: 0em;\n margin-top: 0em;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-left-radius: 2px;\n border-bottom-right-radius: 2px;\n}\ndiv.output_subarea.output_text.output_stream.output_stdout,\ndiv.output_subarea.output_text {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 10.0pt;\n line-height: 150% !important;\n background-color: #ffffff;\n color: #303030;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-left-radius: 2px;\n border-bottom-right-radius: 2px;\n}\ndiv.output_area pre {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 10.0pt;\n line-height: 150% !important;\n color: #303030;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-left-radius: 2px;\n border-bottom-right-radius: 2px;\n}\ndiv.output_area {\n display: -webkit-box;\n}\ndiv.output_html {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 10.0pt;\n color: #353535;\n background-color: #ffffff;\n background: #ffffff;\n}\ndiv.output_subarea {\n overflow-x: auto;\n padding: .8em;\n -webkit-box-flex: 1;\n -moz-box-flex: 1;\n box-flex: 1;\n flex: 1;\n max-width: 90%;\n}\ndiv.prompt.output_prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n background-color: #ffffff;\n color: #ffffff;\n border-bottom-left-radius: 2px;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-right-radius: 0px;\n min-width: 12ex;\n width: 12ex;\n}\ndiv.out_prompt_overlay.prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n background-color: #ffffff;\n border-bottom-left-radius: 2px;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-right-radius: 0px;\n min-width: 12ex;\n width: 12ex;\n}\ndiv.out_prompt_overlay.prompt:hover {\n background-color: #ffffff;\n box-shadow: #e8e8e8 2px 1px 2px 2.5px inset;\n border-bottom-left-radius: 2px;\n -webkit-border-: 2px;\n -moz-border-radius: 2px;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n min-width: 12ex;\n width: 12ex !important;\n}\ndiv.text_cell,\ndiv.text_cell_render pre,\ndiv.text_cell_render {\n font-family: \"Lora\", serif;\n font-size: 13pt;\n line-height: 170% !important;\n color: #353535;\n background: #ffffff;\n background-color: #ffffff;\n border-radius: 2px;\n}\ndiv.cell.text_cell.rendered.selected {\n font-family: \"Lora\", serif;\n border: medium solid #126dce;\n line-height: 170% !important;\n background: #ffffff;\n background-color: #ffffff;\n border-radius: 2px;\n}\ndiv.cell.text_cell.unrendered.selected {\n font-family: \"Lora\", serif;\n line-height: 170% !important;\n background: #ffffff;\n background-color: #ffffff;\n border: medium solid #126dce;\n border-radius: 2px;\n}\ndiv.cell.text_cell.selected {\n font-family: \"Lora\", serif;\n line-height: 170% !important;\n border: medium solid #126dce;\n background: #ffffff;\n background-color: #ffffff;\n border-radius: 2px;\n}\n.edit_mode div.cell.text_cell.selected {\n font-family: \"Lora\", serif;\n line-height: 170% !important;\n background: #ffffff;\n background-color: #ffffff;\n border: medium solid #87b0db;\n border-radius: 2px;\n}\ndiv.text_cell.unrendered,\ndiv.text_cell.unrendered.selected,\ndiv.edit_mode div.text_cell.unrendered {\n font-family: \"Lora\", serif;\n line-height: 170% !important;\n background: #ffffff;\n background-color: #ffffff;\n border-radius: 2px;\n}\ndiv.cell.text_cell.rendered .input_prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n font-weight: normal;\n color: #aaaaaa;\n text-align: left !important;\n min-width: 0ex;\n width: 0ex !important;\n background-color: #ffffff;\n border-right: 2px solid transparent;\n}\ndiv.cell.text_cell.unrendered .input_prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n font-weight: normal;\n color: #aaaaaa;\n text-align: left !important;\n min-width: 0ex;\n width: 0ex !important;\n border-right: 2px solid transparent;\n}\ndiv.rendered_html code {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n padding-top: 3px;\n color: #303030;\n background: #efefef;\n background-color: #efefef;\n}\npre,\ncode,\nkbd,\nsamp {\n white-space: pre-wrap;\n}\ncode {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt !important;\n line-height: 170% !important;\n color: #353535;\n background: #efefef;\n background-color: #efefef;\n}\nkbd {\n padding: 4px;\n font-size: 11pt;\n color: #303030;\n background-color: #efefef;\n border: 0;\n box-shadow: none;\n}\npre {\n display: block;\n padding: 8.5px;\n margin: 0 0 9px;\n font-size: 12.0pt;\n line-height: 1.42857143;\n color: #303030;\n background-color: #efefef;\n border: 1px solid #e7e7e7;\n border-radius: 2px;\n}\ndiv.rendered_html {\n color: #353535;\n}\ndiv.rendered_html pre,\ndiv.text_cell_render pre {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt !important;\n line-height: 170% !important;\n color: #353535;\n background: #efefef;\n background-color: #efefef;\n border: 2px #e7e7e7  solid;\n max-width: 86%;\n border-radius: 2px;\n padding: 5px;\n}\ndiv.text_cell_render h1,\ndiv.rendered_html h1,\ndiv.text_cell_render h2,\ndiv.rendered_html h2,\ndiv.text_cell_render h3,\ndiv.rendered_html h3,\ndiv.text_cell_render h4,\ndiv.rendered_html h4,\ndiv.text_cell_render h5,\ndiv.rendered_html h5 {\n font-family: \"Exo_2\", sans-serif;\n}\n.rendered_html h1:first-child,\n.rendered_html h2:first-child,\n.rendered_html h3:first-child,\n.rendered_html h4:first-child,\n.rendered_html h5:first-child,\n.rendered_html h6:first-child {\n margin-top: 0.2em;\n}\n.rendered_html h1,\n.text_cell_render h1 {\n color: #126dce;\n font-size: 220%;\n text-align: center;\n font-weight: lighter;\n}\n.rendered_html h2,\n.text_cell_render h2 {\n text-align: left;\n font-size: 170%;\n color: #126dce;\n font-style: normal;\n font-weight: lighter;\n}\n.rendered_html h3,\n.text_cell_render h3 {\n font-size: 150%;\n color: #126dce;\n font-weight: lighter;\n text-decoration: italic;\n font-style: normal;\n}\n.rendered_html h4,\n.text_cell_render h4 {\n font-size: 120%;\n color: #126dce;\n font-weight: underline;\n font-style: normal;\n}\n.rendered_html h5,\n.text_cell_render h5 {\n font-size: 100%;\n color: #2f2f2f;\n font-weight: lighter;\n text-decoration: underline;\n}\n.rendered_html table,\n.rendered_html tr,\n.rendered_html td {\n font-family: \"Fira Code\", monospace;\n font-size: 10.0pt !important;\n line-height: 150% !important;\n border: 1px solid #d6d6d6;\n color: #353535;\n background-color: #ffffff;\n background: #ffffff;\n}\ntable.dataframe,\n.rendered_html tr,\n.dataframe * {\n font-family: \"Fira Code\", monospace;\n font-size: 10.0pt !important;\n border: 1px solid #d6d6d6;\n}\n.dataframe th,\n.rendered_html th {\n font-family: \"Exo_2\", sans-serif;\n font-size: 11pt !important;\n font-weight: bold;\n border: 1px solid #c4c4c4;\n background: #eeeeee;\n}\n.dataframe td,\n.rendered_html td {\n font-family: \"Fira Code\", monospace;\n font-size: 10.0pt !important;\n color: #353535;\n background: #ffffff;\n border: 1px solid #d6d6d6;\n text-align: left;\n min-width: 4em;\n}\n.dataframe-summary-row tr:last-child,\n.dataframe-summary-col td:last-child {\n font-family: \"Exo_2\", sans-serif;\n font-size: 11pt !important;\n font-weight: bold;\n color: #353535;\n border: 1px solid #d6d6d6;\n background: #eeeeee;\n}\ndiv.widget-area {\n background-color: #ffffff;\n background: #ffffff;\n color: #303030;\n}\ndiv.widget-area a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n font-weight: normal;\n font-style: normal;\n color: #303030;\n text-shadow: none !important;\n}\ndiv.widget-area a:hover,\ndiv.widget-area a:focus {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n font-weight: normal;\n font-style: normal;\n color: #2f2f2f;\n background: rgba(180,180,180,.14);\n background-color: rgba(180,180,180,.14);\n border-color: transparent;\n background-image: none;\n text-shadow: none !important;\n}\ndiv.widget_item.btn-group > button.btn.btn-default.widget-combo-btn,\ndiv.widget_item.btn-group > button.btn.btn-default.widget-combo-btn:hover {\n background: #eeeeee;\n background-color: #eeeeee;\n border: 2px solid #eeeeee !important;\n font-size: inherit;\n z-index: 0;\n}\ndiv.jupyter-widgets.widget-hprogress.widget-hbox,\ndiv.widget-hbox,\n.widget-hbox {\n display: inline-table;\n}\ndiv.jupyter-widgets.widget-hprogress.widget-hbox .widget-label,\ndiv.widget-hbox .widget-label,\n.widget-hbox .widget-label {\n font-size: 11pt;\n min-width: 100%;\n padding-top: 5px;\n padding-right: 10px;\n text-align: left;\n vertical-align: text-top;\n}\n.progress {\n overflow: hidden;\n height: 20px;\n margin-bottom: 10px;\n padding-left: 10px;\n background-color: #c6c6c6;\n border-radius: 4px;\n -webkit-box-shadow: none;\n box-shadow: none;\n}\n.rendered_html :link {\n font-family: \"Exo_2\", sans-serif;\n font-size: 100%;\n color: #2c85f7;\n text-decoration: underline;\n}\n.rendered_html :visited,\n.rendered_html :visited:active,\n.rendered_html :visited:focus {\n color: #2e6eb2;\n}\n.rendered_html :visited:hover,\n.rendered_html :link:hover {\n font-family: \"Exo_2\", sans-serif;\n font-size: 100%;\n color: #eb6a18;\n}\na.anchor-link:link:hover {\n font-size: inherit;\n color: #eb6a18;\n}\na.anchor-link:link {\n font-size: inherit;\n text-decoration: none;\n padding: 0px 20px;\n visibility: none;\n color: #126dce;\n}\ndiv#nbextensions-configurator-container.container {\n width: 980px;\n margin-right: 0;\n margin-left: 0;\n}\ndiv.nbext-selector > nav > .nav > li > a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12pt;\n}\ndiv.nbext-readme > .nbext-readme-contents > .rendered_html {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12pt;\n line-height: 145%;\n padding: 1em 1em;\n color: #353535;\n background-color: #ffffff;\n -webkit-box-shadow: none;\n -moz-box-shadow: none;\n box-shadow: none;\n}\n.nbext-icon,\n.nbext-desc,\n.nbext-compat-div,\n.nbext-enable-btns,\n.nbext-params {\n margin-bottom: 8px;\n font-size: 12pt;\n}\ndiv.nbext-readme > .nbext-readme-contents {\n padding: 0;\n overflow-y: hidden;\n}\ndiv.nbext-readme > .nbext-readme-contents:not(:empty) {\n margin-top: 0.5em;\n margin-bottom: 2em;\n border: none;\n border-top-color: rgba(180,180,180,.30);\n}\n.nbext-showhide-incompat {\n padding-bottom: 0.5em;\n color: #4a4a4a;\n font-size: 12.0pt;\n}\n.shortcut_key,\nspan.shortcut_key {\n display: inline-block;\n width: 16ex;\n text-align: right;\n font-family: monospace;\n}\nmark,\n.mark {\n background-color: #ffffff;\n color: #353535;\n padding: .15em;\n}\na.text-warning,\na.text-warning:hover {\n color: #aaaaaa;\n}\na.text-warning.bg-warning {\n background-color: #ffffff;\n}\nspan.bg-success.text-success {\n background-color: transparent;\n color: #009e07;\n}\nspan.bg-danger.text-danger {\n background-color: #ffffff;\n color: #de143d;\n}\n.has-success .input-group-addon {\n color: #009e07;\n border-color: transparent;\n background: inherit;\n background-color: rgba(83,180,115,.10);\n}\n.has-success .form-control {\n border-color: #009e07;\n -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.025);\n box-shadow: inset 0 1px 1px rgba(0,0,0,0.025);\n}\n.has-error .input-group-addon {\n color: #de143d;\n border-color: transparent;\n background: inherit;\n background-color: rgba(192,57,67,.10);\n}\n.has-error .form-control {\n border-color: #de143d;\n -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.025);\n box-shadow: inset 0 1px 1px rgba(0,0,0,0.025);\n}\n.kse-input-group-pretty > kbd {\n font-family: \"Droid Sans Mono\", monospace;\n color: #303030;\n font-weight: normal;\n background: transparent;\n}\n.kse-input-group-pretty > kbd {\n font-family: \"Droid Sans Mono\", monospace;\n color: #303030;\n font-weight: normal;\n background: transparent;\n}\ndiv.nbext-enable-btns .btn[disabled],\ndiv.nbext-enable-btns .btn[disabled]:hover,\n.btn-default.disabled,\n.btn-default[disabled] {\n background: #e8e8e8;\n background-color: #e8e8e8;\n color: #282828;\n}\nlabel#Keyword-Filter {\n display: none;\n}\n.nav-pills > li.active > a,\n.nav-pills > li.active > a:hover,\n.nav-pills > li.active > a:focus {\n color: #ffffff;\n background-color: #126dce;\n}\n.input-group .nbext-list-btn-add,\n.input-group-btn:last-child > .btn-group > .btn {\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: #eeeeee;\n}\n.input-group .nbext-list-btn-add:hover,\n.input-group-btn:last-child > .btn-group > .btn:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border-color: #e9e9e9;\n}\n#notebook-container > div.cell.code_cell.rendered.selected > div.widget-area > div.widget-subarea > div > div.widget_item.btn-group > button.btn.btn-default.dropdown-toggle.widget-combo-carrot-btn {\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: #eeeeee;\n}\n#notebook-container > div.cell.code_cell.rendered.selected > div.widget-area > div.widget-subarea > div > div.widget_item.btn-group > button.btn.btn-default.dropdown-toggle.widget-combo-carrot-btn:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border-color: #e9e9e9;\n}\ninput.raw_input {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt !important;\n color: #303030;\n background-color: #efefef;\n border-color: #ececec;\n background: #ececec;\n width: auto;\n vertical-align: baseline;\n padding: 0em 0.25em;\n margin: 0em 0.25em;\n -webkit-box-shadow: none;\n box-shadow: none;\n}\naudio,\nvideo {\n display: inline;\n vertical-align: middle;\n align-content: center;\n margin-left: 20%;\n}\n.cmd-palette .modal-body {\n padding: 0px;\n margin: 0px;\n}\n.cmd-palette form {\n background: #eeeeee;\n background-color: #eeeeee;\n}\n.typeahead-field input:last-child,\n.typeahead-hint {\n background: #eeeeee;\n background-color: #eeeeee;\n z-index: 1;\n}\n.typeahead-field input {\n font-family: \"Exo_2\", sans-serif;\n color: #303030;\n border: none;\n font-size: 28pt;\n display: inline-block;\n line-height: inherit;\n padding: 3px 10px;\n height: 70px;\n}\n.typeahead-select {\n background-color: #eeeeee;\n}\nbody > div.modal.cmd-palette.typeahead-field {\n display: table;\n border-collapse: separate;\n background-color: #f7f7f7;\n}\n.typeahead-container button {\n font-family: \"Exo_2\", sans-serif;\n font-size: 28pt;\n background-color: #d0d0d0;\n border: none;\n display: inline-block;\n line-height: inherit;\n padding: 3px 10px;\n height: 70px;\n}\n.typeahead-search-icon {\n min-width: 40px;\n min-height: 55px;\n display: block;\n vertical-align: middle;\n text-align: center;\n}\n.typeahead-container button:focus,\n.typeahead-container button:hover {\n color: #2f2f2f;\n background-color: #ff7823;\n border-color: #ff7823;\n}\n.typeahead-list > li.typeahead-group.active > a,\n.typeahead-list > li.typeahead-group > a,\n.typeahead-list > li.typeahead-group > a:focus,\n.typeahead-list > li.typeahead-group > a:hover {\n display: none;\n}\n.typeahead-dropdown > li > a,\n.typeahead-list > li > a {\n color: #303030;\n text-decoration: none;\n}\n.typeahead-dropdown,\n.typeahead-list {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n color: #303030;\n background-color: #ffffff;\n border: none;\n background-clip: padding-box;\n margin-top: 0px;\n padding: 3px 2px 3px 0px;\n line-height: 1.7;\n}\n.typeahead-dropdown > li.active > a,\n.typeahead-dropdown > li > a:focus,\n.typeahead-dropdown > li > a:hover,\n.typeahead-list > li.active > a,\n.typeahead-list > li > a:focus,\n.typeahead-list > li > a:hover {\n color: #2f2f2f;\n background-color: #f7f7f7;\n border-color: #f7f7f7;\n}\n.command-shortcut:before {\n content: \"(command)\";\n padding-right: 3px;\n color: #aaaaaa;\n}\n.edit-shortcut:before {\n content: \"(edit)\";\n padding-right: 3px;\n color: #aaaaaa;\n}\nul.typeahead-list i {\n margin-left: 1px;\n width: 18px;\n margin-right: 10px;\n}\nul.typeahead-list {\n max-height: 50vh;\n overflow: auto;\n}\n.typeahead-list > li {\n position: relative;\n border: none;\n}\ndiv.input.typeahead-hint,\ninput.typeahead-hint,\nbody > div.modal.cmd-palette.in > div > div > div > form > div > div.typeahead-field > span.typeahead-query > input.typeahead-hint {\n color: #aaaaaa !important;\n background-color: transparent;\n padding: 3px 10px;\n}\n.typeahead-dropdown > li > a,\n.typeahead-list > li > a {\n display: block;\n padding: 5px;\n clear: both;\n font-weight: 400;\n line-height: 1.7;\n border: 1px solid #ffffff;\n border-bottom-color: rgba(180,180,180,.30);\n}\nbody > div.modal.cmd-palette.in > div {\n min-width: 750px;\n margin: 150px auto;\n}\n.typeahead-container strong {\n font-weight: bolder;\n color: #ff7823;\n}\n#find-and-replace #replace-preview .match,\n#find-and-replace #replace-preview .insert {\n color: #ffffff;\n background-color: #ff7823;\n border-color: #ff7823;\n border-style: solid;\n border-width: 1px;\n border-radius: 0px;\n}\n#find-and-replace #replace-preview .replace .match {\n background-color: #de143d;\n border-color: #de143d;\n border-radius: 0px;\n}\n#find-and-replace #replace-preview .replace .insert {\n background-color: #009e07;\n border-color: #009e07;\n border-radius: 0px;\n}\ndiv.CodeMirror,\ndiv.CodeMirror pre {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n line-height: 170%;\n color: #303030;\n}\ndiv.CodeMirror-lines {\n padding-bottom: .6em;\n padding-left: .5em;\n padding-right: 1.5em;\n padding-top: 4px;\n}\nspan.ansiblack {\n color: #dc4384;\n}\nspan.ansiblue {\n color: #009e07;\n}\nspan.ansigray {\n color: #ff7823;\n}\nspan.ansigreen {\n color: #333333;\n}\nspan.ansipurple {\n color: #653bc5;\n}\nspan.ansicyan {\n color: #055be0;\n}\nspan.ansiyellow {\n color: #ff7823;\n}\nspan.ansired {\n color: #de143d;\n}\ndiv.output-stderr {\n background-color: #ebb5b7;\n}\ndiv.output-stderr pre {\n color: #000000;\n}\ndiv.js-error {\n color: #de143d;\n}\n.ipython_tooltip {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n line-height: 170%;\n border: 2px solid #dadada;\n background: #eeeeee;\n background-color: #eeeeee;\n border-radius: 2px;\n overflow-x: visible;\n overflow-y: visible;\n box-shadow: none;\n position: absolute;\n z-index: 1000;\n}\n.ipython_tooltip .tooltiptext pre {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n line-height: 170%;\n background: #eeeeee;\n background-color: #eeeeee;\n color: #303030;\n overflow-x: visible;\n overflow-y: visible;\n max-width: 900px;\n}\ndiv#tooltip.ipython_tooltip {\n overflow-x: wrap;\n overflow-y: visible;\n max-width: 800px;\n}\ndiv.tooltiptext.bigtooltip {\n overflow-x: visible;\n overflow-y: scroll;\n height: 400px;\n max-width: 800px;\n}\n.cm-s-ipython.CodeMirror {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n background: #efefef;\n color: #303030;\n border-radius: 2px;\n font-style: normal;\n font-weight: normal;\n}\n.cm-s-ipython div.CodeMirror-selected {\n background: #e0e1e3;\n}\n.cm-s-ipython .CodeMirror-gutters {\n background: #e0e1e3;\n border: none;\n border-radius: 0px;\n}\n.cm-s-ipython .CodeMirror-linenumber {\n color: #aaaaaa;\n}\n.cm-s-ipython .CodeMirror-cursor {\n border-left: 2px solid #ff711a;\n}\n.cm-s-ipython span.cm-comment {\n color: #8d8d8d;\n font-style: italic;\n}\n.cm-s-ipython span.cm-atom {\n color: #055be0;\n}\n.cm-s-ipython span.cm-number {\n color: #ff8132;\n}\n.cm-s-ipython span.cm-property {\n color: #e22978;\n}\n.cm-s-ipython span.cm-attribute {\n color: #de143d;\n}\n.cm-s-ipython span.cm-keyword {\n color: #713bc5;\n font-weight: normal;\n}\n.cm-s-ipython span.cm-string {\n color: #009e07;\n}\n.cm-s-ipython span.cm-meta {\n color: #aa22ff;\n}\n.cm-s-ipython span.cm-operator {\n color: #055be0;\n}\n.cm-s-ipython span.cm-builtin {\n color: #e22978;\n}\n.cm-s-ipython span.cm-variable {\n color: #303030;\n}\n.cm-s-ipython span.cm-variable-2 {\n color: #de143d;\n}\n.cm-s-ipython span.cm-variable-3 {\n color: #aa22ff;\n}\n.cm-s-ipython span.cm-def {\n color: #e22978;\n font-weight: normal;\n}\n.cm-s-ipython span.cm-error {\n background: rgba(191,97,106,.40);\n}\n.cm-s-ipython span.cm-tag {\n color: #e22978;\n}\n.cm-s-ipython span.cm-link {\n color: #ff7823;\n}\n.cm-s-ipython span.cm-storage {\n color: #055be0;\n}\n.cm-s-ipython span.cm-entity {\n color: #e22978;\n}\n.cm-s-ipython span.cm-quote {\n color: #009e07;\n}\ndiv.CodeMirror span.CodeMirror-matchingbracket {\n color: #1c1c1c;\n background-color: rgba(30,112,199,.30);\n}\ndiv.CodeMirror span.CodeMirror-nonmatchingbracket {\n color: #1c1c1c;\n background: rgba(191,97,106,.40) !important;\n}\ndiv.cell.text_cell .cm-s-default .cm-header {\n color: #126dce;\n}\ndiv.cell.text_cell .cm-s-default span.cm-variable-2 {\n color: #353535;\n}\ndiv.cell.text_cell .cm-s-default span.cm-variable-3 {\n color: #aa22ff;\n}\n.cm-s-default span.cm-comment {\n color: #8d8d8d;\n}\n.cm-s-default .cm-tag {\n color: #009fb7;\n}\n.cm-s-default .cm-builtin {\n color: #e22978;\n}\n.cm-s-default .cm-string {\n color: #009e07;\n}\n.cm-s-default .cm-keyword {\n color: #713bc5;\n}\n.cm-s-default .cm-number {\n color: #ff8132;\n}\n.cm-s-default .cm-error {\n color: #055be0;\n}\n.CodeMirror-cursor {\n border-left: 2px solid #ff711a;\n border-right: none;\n width: 0;\n}\n.cm-s-default div.CodeMirror-selected {\n background: #e0e1e3;\n}\n.cm-s-default .cm-selected {\n background: #e0e1e3;\n}\ndiv#maintoolbar {\n display: none !important;\n}\n#header-container {\n display: none !important;\n}\n\n/**********************************\n MathJax Settings and Style Script\n**********************************/\n.MathJax_Display,\n.MathJax nobr>span.math>span {\n    border: 0 !important;\n    font-size: 110% !important;\n    text-align: center !important;\n    margin: 0em !important;\n}\n/* Prevents MathJax from jittering */\n/* cell position when cell is selected */\n.MathJax:focus, body :focus .MathJax {\n    display: inline-block !important;\n}\n\n\n\n </style>\n\n\n\n\n```python\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# 1. magic for inline plot\n# 2. magic to print version\n# 3. magic so that the notebook will reload external python modules\n%matplotlib inline\n%load_ext watermark\n%load_ext autoreload \n%autoreload 2\n\nfrom sklearn.decomposition import PCA\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.datasets import load_iris\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\n\n%watermark -a 'Ethen' -d -t -v -p numpy,pandas,matplotlib,sklearn\n```\n\n    Ethen 2017-07-30 14:06:12 \n    \n    CPython 3.5.2\n    IPython 6.1.0\n    \n    numpy 1.13.1\n    pandas 0.19.2\n    matplotlib 2.0.0\n    sklearn 0.18.1\n\n\n# Dimensionality Reduction\n\nThe starting point most data analysis problems is to perform some sort of exploratory data analysis on our raw data. This step is important because until we have basic understanding of the structure of our raw data, it might be hard to know whether the data is suitable for the task at hand or even derive insights that we can later share. During this exploratoy process, unsupervised methods such as dimensionality reduction can help us identify simpler and more compact representations of the original raw data to either aid our understanding or provide useful input to other stages of analysis. Here, we'll be focusing on a specific dimensionality reduction technique called **Principal Component Analysis (PCA)**.\n\nImagine that we're trying to understand some underlying phenomenon, in order to do so we measure various quantities potentially related to it. If we knew exactly what to measure in advance, we might be able to find some simple relationships in our data. But we typically don't, so we often measure anything that might be relevant and end up having irrelevant or redundant signals in our measurement. To make this a bit more concrete, we'll generate a toy 2-dimensional dataset to work with using the equation below.\n\n$$x_2 = 500 + 20 \\times x_1 + \\epsilon$$\n\n\n```python\nnp.random.seed(123)\nx1 = np.arange(12, 56, 0.5)\ne  = np.random.normal(0, 100, x1.shape[0])\nx2 = 500 + 20 * x1 + e\nX = np.c_[x1, x2]\n\n# change default style figure and font size\nplt.style.use('fivethirtyeight')\nplt.rcParams['figure.figsize'] = 8, 6\nplt.rcParams['font.size'] = 12\n\ndef plot2var(m):\n    plt.scatter(m[:, 0], m[:, 1], s = 40, alpha = 0.8)\n    plt.xlabel('x1')\n    plt.ylabel('x2')\n\nplot2var(X)\n```\n\nWe can clearly see from the plot that there's linear relationship between the two variables, thus we probably don't need to include both of them as $x_1$ can be easily explained by $x_2$ and vice versa.\n\n## PCA\n\nIf it is the case that one of the features is considered redundant, we should be able to summarize the data with less characteristics (features). So, the way PCA tackles this problem is: Instead of simply picking out the useful features and discarding the others, it uses a linear combination of the existing features and constructs some new features that are good alternative representation of the original data. In our 2D toy dataset, PCA will try to pick the best single direction, or often referred to as **first principal components** in 2D, and project our points onto that single direction. So the next question becomes, out of the many possible lines in 2D, what line should we pick?\n\nIt turns out, there are two different answers to this question. First answer is that we are looking for some features that strongly differ across data points, thus, PCA looks for features that captures as much variation across data points as possible. The second answer is that we are looking for the features that would allow us to \"reconstruct\" the original features. Imagine that we come up with a feature that has no relation to the original ones; If we were to use this new feature, there is no way we can relate this to the original ones. So PCA looks for features that minimizes the reconstruction error. These two notions can be depicted in the graph below, where the black dots represents the original data point, the black line represents the projected line, the red dot on the left shows the points on the projected line and the red line on the right shows the reconstruction error.\n\n\n\nSurprisingly, it turns out that these two aims are equivalent and PCA can kill two birds with one stone. To see why minimizing squared residuals is equivalent to maximizing variance consider the 2 dimensions visualization below.\n\n\n\nConsider a datapoint $a_i$. The contribution of this specific data point to the total variance is $a_i^Ta_i$, or equivalently the squared Euclidean length $\\lVert \\mathbf{a}_i \\lVert^2$. Applying the Pythagorean theorem shows that this total variance equals the sum of variance lost (the squared residual) and variance remaining. Thus, it is equivalent to either maximize remaining variance or minimize lost variance to find the principal components.\n\nBefore we go another deeper, let's build some intuition using the scikit-learn library. The following section standardizes the data, fits the PCA model and prints out some of the important informations.\n\n\n```python\n# we start by standardizing our dataset\nX_std = StandardScaler().fit_transform(X)\n\n# call PCA specifying we only want the\n# first two principal components (since\n# we only have a 2d datset)\npca = PCA(n_components = 2)\npca.fit(X_std)\n\n# important information\nprint('Components:\\n ', pca.components_)\nprint('Explained Variance Ratio:\\n ', pca.explained_variance_ratio_)\n```\n\n    Components:\n      [[-0.70710678 -0.70710678]\n     [ 0.70710678 -0.70710678]]\n    Explained Variance Ratio:\n      [ 0.95588995  0.04411005]\n\n\nAfter fitting the PCA on the dataset, the fit learns some quantities from the data, most importantly the \"components\", which is the principal components (the new direction that our data points will be projected upon) and \"explained variance ratio\", which corresponds to the percentage of variance explained by each of the principal components. To get a better sense of what these numbers mean, let's visualize them over our standardized input data.\n\n\n```python\ndef draw_vector(v0, v1):\n    \"\"\"draw principal components as vectors\"\"\"\n    ax = plt.gca()\n    arrowprops = dict(arrowstyle = '->',\n                      linewidth = 2, edgecolor = 'black',\n                      shrinkA = 0, shrinkB = 0)\n    plt.annotate('', v1, v0, arrowprops = arrowprops)\n\n# plot data\nplt.scatter(X_std[:, 0], X_std[:, 1], s = 40, alpha = 0.8)\nfor length, vector in zip(pca.explained_variance_, pca.components_):\n    # the larger the explained variance, the longer the\n    # annotated line will be\n    v = vector * 2 * np.sqrt(length)\n    draw_vector(pca.mean_, pca.mean_ + v)\n\nplt.axis('equal')\nplt.show()\n```\n\nFrom the plot, we see that our PCA model gives us two principal components (the black line) and the length of the lines indicate of how important that principal component is in describing the variation of the original data. So if we were to choose 1 principal component to summarize our 2d dataset, it will be line that has the longest length (largest explained variance ratio). There're two things worth noting:\n\n- The number of principal components matches the total number of features\n- The first and second principal components are orthogonal to each other\n\nThe reason for this is that principal components transform the data into a new set of dimensions, and these new dimensions have to be equal to the original amount of dimensions. And just like the original $x$, $y$ axis that we're used to, they have to be orthogonal to each other. Let's now reduce the dimension of our 2d dataset into 1d by transforming our data onto the most important principal component and plot it along with the original data.\n\n\n```python\n# dimensionality reduction, keeping only\n# the first principal component\npca = PCA(n_components = 1)\nX_pca = pca.fit_transform(X_std)\nprint(\"original shape:   \", X.shape)\nprint(\"transformed shape:\", X_pca.shape)\n\n# inverse transform to obtain the projected data\n# and compare with the original\nX_new = pca.inverse_transform(X_pca)\nplt.scatter(X_std[:, 0], X_std[:, 1], s = 40, alpha = 0.2)\nplt.scatter(X_new[:, 0], X_new[:, 1], s = 40, alpha = 0.8)\nplt.show()\n```\n\nIn the plot above, the lighter points are the original data and the darker points are the projected version. Looking at the projections we see that the points projected onto the first principal component all seem close to their initial representations and at the same time, it also captures most of the variations in our original data points.\n\nHopefully, this elucidate what a PCA dimensionality reduction is doing. In a nutshell, PCA aims to find the directions or so called the principal components of maximum variance in high-dimensional data and project it onto a smaller dimensional subspace while retaining most of the information. In our 2d example, the linear relationship between $x_1$ and $x_2$ is mostly preserved using only 1 feature instead of 2.\n\n## PCA From Scratch\n\nNow that we have a high level understanding of what PCA is accomplishing, let's now formalize this with some notations. Recall that PCA is trying the find the direction such that the projection of the data on it has the highest variance. So given $X$, the centered data matrix, the projection, $Xw$ (dot product between the data point, $X$ and the projection weight, $w$), its variance can be computed as follows:\n\n\\begin{align}\n\\frac{1}{n-1}(\\mathbf{Xw})^\\top \\mathbf{Xw} = \\mathbf w^\\top (\\frac{1}{n-1}\\mathbf X^\\top\\mathbf X) \\mathbf w = \\mathbf w^\\top \\mathbf{Cw}\n\\end{align}\n\nWhere $\\mathbf{C}$ is the covariance matrix of the data $\\mathbf{X}$. In case this looks unfamiliar, the covariance matrix is a $d \\times d$ matrix ($d$ is the total number of dimensions, features) where each element represents the covariance between two features. The covariance between two features $x_j$ and $x_k$ is calculated as follows:\n\n\\begin{align}\n\\sigma_{jk} = \\frac{1}{n-1} \\sum_{i=1}^{n} \\left( x_{ij} - \\bar{x}_j \\right) \\left( x_{ik} - \\bar{x}_k \\right)\n\\end{align}\n\nWhere $\\bar{x}_j$ is simply the mean of vector (feature) $\\bar{x}_j = \\sum \\limits_{i=1}^n x_{ij}$.\n\nWe can also express the calculation of the covariance matrix via the following matrix equation: \n\n\\begin{align}\n\\mathbf{C} = \\frac{1}{n-1} \\big( (X - \\bar{x})^\\top( X - \\bar{x}) \\big)\n\\end{align}\n\nBecause we already assume to data point $X$ has been centered, thus the $X - \\bar{x}$ part can be simplified into just $X$. And the formula above simply becomes:\n\n\\begin{align}\n\\mathbf{C} = \\frac{1}{n-1} X^\\top X\n\\end{align}\n\nNext, apart from the original objective function $\\mathbf w^\\top \\mathbf{Cw}$, we also introduce an additional constraint $\\|\\mathbf w\\|=\\mathbf w^\\top \\mathbf w=1$, saying our weight vector should have unit length. The intuition behind this is that: If we were to simply maximize the formula $\\mathbf w^\\top \\mathbf{Cw}$, we can multiply $w$ by any number and the objective function will increase by the square of this number. So the problem becomes ill-defined since the maximum of this expression is infinite. Given these two pieces of information, our objective function for PCA becomes:\n\n\\begin{align}\n&  \\underset{\\mathbf{w}}{\\text{maximize}}\n&& \\mathbf w^\\top \\mathbf{Cw} \\nonumber \\\\\n&  \\text{subject to}\n&& \\mathbf w^\\top \\mathbf w=1\n\\end{align}\n\nThis objective function can be solved by the Lagrange multiplier, minimizing the loss function:\n\n\\begin{align}\nL &= \\mathbf w^\\top \\mathbf{Cw}-\\lambda(\\mathbf w^\\top \\mathbf w-1)\n\\end{align}\n\nIf this looks unfamiliar, check out the following tutorial on Lagrange multiplier. [Khan Academy: Lagrange multipliers, examples](https://www.khanacademy.org/math/multivariable-calculus/applications-of-multivariable-derivatives/constrained-optimization/a/lagrange-multipliers-examples). Next, to solve for $w$, we set the partial derivative of $L$ with respect to $w$ to 0.\n\n\\begin{align}\n\\frac{\\partial L}{\\partial \\mathbf w} \n& \\implies \\mathbf{Cw} - \\lambda \\mathbf w = 0 \\\\\n& \\implies \\mathbf{Cw} = \\lambda \\mathbf w\n\\end{align}\n\nHopefully the formula above looks familar, since it's essentially an eigendecomposition problem. The notion of eigendecomposition is basically trying to solve the equation:\n\n\\begin{align}\nAx &= \\lambda x\n\\end{align}\n\nIn our case, $A$ is our covariance matrix correponding to $\\mathbf C$; $x$ is our eigenvector, correponding to $\\mathbf w$ and $\\lambda$ is our eigenvalue correponding to explained variance. After solving the equation above, we'll obtain eigenvector and eigenvalue pairs, where very eigenvector has a corresponding eigenvalue. An eigenvector is essentially the direction of each principal component and the eigenvalue is a number, telling us how much variance there is in the data in that direction, in other words, how spread out the data is on the line. For those interested, the following blog walks through the calculating eigenvalue and eigenvectors from scratch. [Blog: What are eigenvectors and eigenvalues?](http://www.visiondummy.com/2014/03/eigenvalues-eigenvectors/)\n\nGiven all of that, let's see how this works in code. Just to summarize, the general framework for computing PCA is as follows:\n\n- Standardize the data\n- Obtain the Eigenvectors and Eigenvalues from the covariance matrix\n- Sort eigenvalues in descending order and choose the $k$ eigenvectors that correspond to the $k$ largest eigenvalues where $k$ is the number of dimensions of the new feature subspace\n- Projection onto the new feature space. During this step we will take the top $k$ eigenvectors and use it to transform the original dataset $X$ to obtain a k-dimensional feature subspace $X'$\n\nFor the section below, we will be working with the famous \"Iris\" dataset. The iris dataset is a 150\u00d74 matrix where the columns are the different features (sepal length in cm, sepal width in cm, petal length in cm, petal width in cm) and every every row represents a separate flower sample. The three classes in the Iris dataset are: Iris-setosa (n=50), Iris-versicolor (n=50), Iris-virginica (n=50). We'll use histograms to get a feeling of how the 3 different flower classes are distributes along the 4 different features.\n\n\n```python\niris = load_iris()\nX = iris['data']\ny = iris['target']\n\nlabel_dict = {0: 'Iris-Setosa',\n              1: 'Iris-Versicolor',\n              2: 'Iris-Virgnica'}\n\nfeature_dict = {0: 'sepal length [cm]',\n                1: 'sepal width [cm]',\n                2: 'petal length [cm]',\n                3: 'petal width [cm]'}\n\nfig = plt.figure(figsize = (10, 6))\nfor feature in range(len(feature_dict)):\n    plt.subplot(2, 2, feature + 1)\n    for index, label in label_dict.items():\n        plt.hist(X[y == index, feature], label = label,\n                 bins = 10, alpha = 0.3)\n        plt.xlabel(feature_dict[feature])\n        \nplt.legend(loc = 'upper right', fancybox = True, fontsize = 12)\nplt.tight_layout()\nplt.show()\n```\n\n### Standardize\n\nIn general, it's important to standardize the data prior to a PCA on the covariance matrix depends on the measurement scales of the original features. Since PCA yields a feature subspace that maximizes the variance along the axes, it makes sense to standardize the data, especially if it was measured on different scales so different features will have equal contribution in terms of their scales.\n\n\n```python\n# subtract the mean and divide the\n# standard deviation of each features\nmean = np.mean(X, axis = 0)\nscale = np.std(X, axis = 0)\nX_std = (X - mean) / scale\n```\n\n### Eigendecomposition - Computing Eigenvectors and Eigenvalues\n\nThe eigenvectors and eigenvalues of a covariance matrix is the core of PCA: The eigenvectors (principal components) determine the directions of the new feature space, and the eigenvalues determine their magnitude (variance explained along the principal components).\n\n\n```python\n# for those unfamiliar with the @ syntax it\n# is equivalent of .dot, the dot product\nvec_mean = np.mean(X_std, axis = 0)\nvec_diff = X_std - vec_mean\ncov_mat  = vec_diff.T @ vec_diff / (X_std.shape[0] - 1)\nprint('Covariance matrix \\n {}'.format(cov_mat))\n\n# note that since we already standardize the data,\n# meaning the mean vector for each features, vec_mean \n# will be 0 (really small numbers if you were to print them out),\n# hence we don't have to substract the mean to standardize them\ncov_mat = X_std.T @ X_std / (X_std.shape[0] - 1)\nprint('Covariance matrix \\n {}'.format(cov_mat))\n\n# equivalently, we could have used the np.cov function:\n# since each row represents a variable for np.cov,\n# we'll need to transpose the matrix\nprint('NumPy covariance matrix: \\n {}'.format(np.cov(X_std.T)))\n```\n\n    Covariance matrix \n     [[ 1.00671141 -0.11010327  0.87760486  0.82344326]\n     [-0.11010327  1.00671141 -0.42333835 -0.358937  ]\n     [ 0.87760486 -0.42333835  1.00671141  0.96921855]\n     [ 0.82344326 -0.358937    0.96921855  1.00671141]]\n    Covariance matrix \n     [[ 1.00671141 -0.11010327  0.87760486  0.82344326]\n     [-0.11010327  1.00671141 -0.42333835 -0.358937  ]\n     [ 0.87760486 -0.42333835  1.00671141  0.96921855]\n     [ 0.82344326 -0.358937    0.96921855  1.00671141]]\n    NumPy covariance matrix: \n     [[ 1.00671141 -0.11010327  0.87760486  0.82344326]\n     [-0.11010327  1.00671141 -0.42333835 -0.358937  ]\n     [ 0.87760486 -0.42333835  1.00671141  0.96921855]\n     [ 0.82344326 -0.358937    0.96921855  1.00671141]]\n\n\nAfter obtaining the covariance matrix, we perform an eigendecomposition on it to obtain the eigenvalues and eigenvectors.\n\n\n```python\n# since computing this by hand can be quite tedious\n# we'll simply use the pre-implemented function\neig_vals, eig_vecs = np.linalg.eig(cov_mat)\nprint('Eigenvectors \\n%s' % eig_vecs)\nprint('\\nEigenvalues \\n%s' % eig_vals)\n```\n\n    Eigenvectors \n    [[ 0.52237162 -0.37231836 -0.72101681  0.26199559]\n     [-0.26335492 -0.92555649  0.24203288 -0.12413481]\n     [ 0.58125401 -0.02109478  0.14089226 -0.80115427]\n     [ 0.56561105 -0.06541577  0.6338014   0.52354627]]\n    \n    Eigenvalues \n    [ 2.93035378  0.92740362  0.14834223  0.02074601]\n\n\n### Choosing Top K Eigenvectors\n\nRecall that the typical goal of a PCA is to reduce the dimensionality of the original feature space by projecting it onto a smaller subspace. In order to decide which eigenvector(s) can dropped without losing too much information for the construction of lower-dimensional subspace, we need to inspect the corresponding eigenvalues. The idea is: eigenvectors with the lowest eigenvalues bear the least information about the distribution of the data and those are the ones can be dropped. In order to do so, the common approach is to rank the eigenvalues from highest to lowest in order choose the top $k$ eigenvectors.\n\nAfter sorting the eigenpairs, the next question is \"how many principal components are we going to choose for our new feature subspace?\" A useful measure is the so-called \u201cexplained variance,\u201d which can be calculated from the eigenvalues. The explained variance tells us how much extra information (variance) does each of the principal components contribute.\n\n\n```python\neig_vals_total = np.sum(eig_vals)\nvar_exp = eig_vals / eig_vals_total\ncum_var_exp = np.cumsum(var_exp)\nprint('Variance Explained: ', var_exp)\nprint('Cumulative Variance Explained: ', cum_var_exp)\n\nplt.bar(range(var_exp.shape[0]), var_exp, alpha = 0.5, \n        align = 'center', label = 'individual explained variance')\nplt.step(range(var_exp.shape[0]), cum_var_exp, \n         where = 'mid', label = 'cumulative explained variance')\nplt.ylabel('Explained variance ratio')\nplt.xlabel('Principal components')\nplt.ylim(0, 1.1)\nplt.legend(loc = 'best')\nplt.tight_layout()\n```\n\nThe plot above clearly shows that most of the variance (72.77% of the variance to be precise) can be explained by the first principal component alone. The second principal component still bears some information (23.03%) while the third and fourth principal components can safely be dropped without losing to much information. Together, the first two principal components explains 95.8% of the variance. Or in other words, it contain 95.8% of the information (95% or 99% are comon threshold that people use).\n\n### Projection Onto the New Feature Space\n\nIn the last step, we will use the 4\u00d72-dimensional eigenvectors to transform our samples onto the new subspace via the equation $Y=XW$, where Y will be our 150\u00d72 matrix of transformed samples (we reduce the dimension from the original 4 down to 2).\n\n\n```python\ndef plot_iris_pca(X_pca, y):\n    \"\"\"a scatter plot of the 2-dimensional iris data\"\"\"\n    markers = 's', 'x', 'o'\n    colors = list(plt.rcParams['axes.prop_cycle'])\n    target = np.unique(y)\n    for idx, (t, m) in enumerate( zip(target, markers) ):\n        subset = X_pca[y == t]\n        plt.scatter(subset[:, 0], subset[:, 1], s = 50,\n                    c = colors[idx]['color'], label = t, marker = m)\n\n    plt.xlabel('PC 1')\n    plt.ylabel('PC 2')\n    plt.legend(loc = 'lower left')\n    plt.tight_layout()\n    plt.show()\n```\n\n\n```python\nX_std_pca = X_std.dot(eig_vecs[:, 0:2])\nplot_iris_pca(X_std_pca, y)\n```\n\nWe'll put all of this into a single class, train it and confirm the result with scikit-learn's PCA model by printing out the explained variance ratio.\n\n\n```python\nclass PCAModel:\n    \"\"\"\n    Principal component analysis (PCA)\n    \n    Parameters\n    ----------\n    n_components : int\n        top number of principal components to keep\n    \"\"\"    \n    def __init__(self, n_components):\n        self.n_components = n_components\n\n    def fit(self, X):\n        # standardize\n        X = X.copy()\n        self.mean = np.mean(X, axis = 0)\n        self.scale = np.std(X, axis = 0)\n        X = (X - self.mean) / self.scale\n        \n        # eigendecomposition\n        eig_vals, eig_vecs = np.linalg.eig(np.cov(X.T))\n        self.components = eig_vecs[:, :self.n_components]\n        var_exp = eig_vals / np.sum(eig_vals)\n        self.explained_variance_ratio = var_exp[:self.n_components]\n        return self\n\n    def transform(self, X):\n        X = X.copy()\n        X = (X - self.mean) / self.scale\n        X_pca = X @ self.components\n        return X_pca\n```\n\n\n```python\n# implementation from scratch\npca_model = PCAModel(n_components = 2).fit(X)\n\n# using library to confirm results\nscaler = StandardScaler()\nX_std = scaler.fit_transform(X)\npca = PCA(n_components = 2).fit(X_std)\n\n# print explained ratio to see if the matches\nprint('library: ', pca.explained_variance_ratio_)\nprint('from scratch: ', pca_model.explained_variance_ratio)\n```\n\n    library:  [ 0.72770452  0.23030523]\n    from scratch:  [ 0.72770452  0.23030523]\n\n\n## Takeaway\n\nLet's wrap this up with a summary of PCA and some of its applications. In order to identify patterns in our data, we often look for variation across observations to distinguish them from one another. Hence it seems reasonable to be able to find a succinct representation that best captures the variation in our initial data. PCA, in particular, look to explain our data via its maximum directions of variance. By compressing a higher dimensional dataset into lower one, while still retaining most of the variance this allows us to:\n\n- Perform Visualization: PCA summarizes our data along the principal components (or eigenvectors), which explains most the variance. Thus we can reduce the dataset to 2 or 3 dimensions and visualize our data's distribution. This can be helpful when we're performing clustering algorithm that needs to choose the cluster number beforehand.\n- Speed up machine learning algorithms: When dealing with Big Data, we might want to decompose the features into a lower dimension, without a significant loss in variance. By performing dimensionality reduction methods, we can reduce the amount of features we have to speed up the training algorithm and save memory. For this part, we'll use the Iris dataset again and show that by keeping the data's top 3 principal components we can obtain the same level of accuracy as keeping all 4 features.\n\n\n```python\n# split 30% of the iris data into a test set for evaluation\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, \n                                                    random_state = 1)\n\n# create the pipeline, where we'll\n# standardize the data, perform PCA and\n# fit the logistic regression\npipe1 = Pipeline([\n    ('standardize', StandardScaler()),\n    ('pca', PCA(n_components = 3)),\n    ('logistic', LogisticRegression(random_state = 1))\n])\npipe1.fit(X_train, y_train)\ny_pred1 = pipe1.predict(X_test)\n\n# pipeline without PCA\npipe2 = Pipeline([\n    ('standardize', StandardScaler()),\n    ('logistic', LogisticRegression(random_state = 1))\n])\npipe2.fit(X_train, y_train)\ny_pred2 = pipe2.predict(X_test)\n\n# access the prediction accuracy\nprint('PCA Accuracy %.3f' % accuracy_score(y_test, y_pred1))\nprint('Accuracy %.3f' % accuracy_score(y_test, y_pred2))\n```\n\n    PCA Accuracy 0.822\n    Accuracy 0.822\n\n\n# Reference\n\n- [Youtube: Dimensionality Reduction](https://www.youtube.com/playlist?list=PLnnr1O8OWc6aVexn2BY0qjklobY6TUEIy)\n- [Blog: What are eigenvectors and eigenvalues?](http://www.visiondummy.com/2014/03/eigenvalues-eigenvectors/)\n- [Blog: Principal Component Analysis 4 Dummies](https://georgemdallas.wordpress.com/2013/10/30/principal-component-analysis-4-dummies-eigenvectors-eigenvalues-and-dimension-reduction/)\n- [Blog: Everything you did and didn't know about PCA](http://alexhwilliams.info/itsneuronalblog/2016/03/27/pca/)\n- [Blog: Principal Component Analysis in 3 Simple Steps](http://sebastianraschka.com/Articles/2015_pca_in_3_steps.html)\n- [Notebook: In Depth: Principal Component Analysis](http://nbviewer.jupyter.org/github/jakevdp/PythonDataScienceHandbook/blob/95664b978439df948b2cd2f5f5b4e31f28b30394/notebooks/05.09-Principal-Component-Analysis.ipynb)\n- [StackExchange: Making sense of principal component analysis, eigenvectors & eigenvalues](http://stats.stackexchange.com/questions/2691/making-sense-of-principal-component-analysis-eigenvectors-eigenvalues)\n- [StackExchange: What is an intuitive explanation for how PCA turns from a geometric problem (with distances) to a linear algebra problem (with eigenvectors)?](http://stats.stackexchange.com/questions/217995/what-is-an-intuitive-explanation-for-how-pca-turns-from-a-geometric-problem-wit)\n", "meta": {"hexsha": "0f9d343074082af58d60aeeff8e18e586005fb1b", "size": 241067, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "dim_reduct/PCA.ipynb", "max_stars_repo_name": "Ani-singh/Insights---Data-Unicorn-12-Dec-17", "max_stars_repo_head_hexsha": "efdbde09e172613be96fbc5f069c9e3f893663d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dim_reduct/PCA.ipynb", "max_issues_repo_name": "Ani-singh/Insights---Data-Unicorn-12-Dec-17", "max_issues_repo_head_hexsha": "efdbde09e172613be96fbc5f069c9e3f893663d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dim_reduct/PCA.ipynb", "max_forks_repo_name": "Ani-singh/Insights---Data-Unicorn-12-Dec-17", "max_forks_repo_head_hexsha": "efdbde09e172613be96fbc5f069c9e3f893663d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-08T17:36:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-08T17:36:36.000Z", "avg_line_length": 87.7564615945, "max_line_length": 37988, "alphanum_fraction": 0.7775929513, "converted": true, "num_tokens": 19113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.02635535284611976, "lm_q2_score": 0.029312230433369, "lm_q1q2_score": 0.0007725341757782099}}
{"text": "```python\nfrom jupyterthemes import get_themes\nfrom jupyterthemes.stylefx import set_nb_theme\nthemes = get_themes()\nset_nb_theme(themes[1])\n```\n\n\n\n\n<style> @font-face {\n font-family: 'Droid Sans Mono';\n font-weight: normal;\n font-style: normal;\n src: local('Droid Sans Mono'), url('fonts/droid-sans-mono.woff') format('woff');\n}\n@font-face {\n font-family: 'Exo_2';\n font-weight: normal;\n font-style: normal;\n src: local('Exo_2'), url('fonts/exo-II-regular.ttf') format('truetype');\n}\n@font-face {\n font-family: 'Fira Code';\n font-weight: normal;\n font-style: normal;\n src: local('Fira Code'), url('fonts/firacode.otf') format('opentype');\n}\n@font-face {\n font-family: 'Lora';\n font-weight: normal;\n font-style: normal;\n src: local('Lora'), url('fonts/Lora-Regular.ttf') format('truetype');\n}\ndiv#notebook {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n line-height: 170%;\n color: #303030;\n}\nbody,\ndiv.body {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n color: #303030;\n background-color: #ffffff;\n background: #ffffff;\n}\nbody.notebook_app {\n padding: 0;\n background-color: #ffffff;\n background: #ffffff;\n padding-right: 0px !important;\n overflow-y: hidden;\n}\na {\n font-family: \"Exo_2\", sans-serif;\n color: #303030;\n}\na:hover,\na:focus {\n color: #2f2f2f;\n}\n.list_header,\ndiv#notebook_list_header.row.list_header {\n font-size: 14pt;\n color: #2f2f2f;\n background-color: #ffffff;\n}\ndiv#cluster_list_header.row.list_header,\ndiv#running .row.list_header {\n font-size: 14pt;\n color: #303030;\n background: #eeeeee;\n background-color: #eeeeee;\n border-bottom: 2px solid rgba(180,180,180,.30);\n}\ndiv#cluster_list > div.list_item.row,\ndiv#cluster_list > div.list_item.row:hover {\n background: #f7f7f7;\n background-color: #f7f7f7;\n}\ndiv#clusters.tab-pane.active {\n font-size: 12.0pt;\n padding: 4px 0 4px 0;\n}\n#running .panel-group .panel .panel-heading {\n font-size: 14pt;\n color: #303030;\n padding: 8px 8px;\n background: #eeeeee;\n background-color: #eeeeee;\n}\n#running .panel-group .panel .panel-heading a {\n font-size: 14pt;\n color: #303030;\n}\n#running .panel-group .panel .panel-heading a:focus,\n#running .panel-group .panel .panel-heading a:hover {\n font-size: 14pt;\n color: #303030;\n}\n#running .panel-group .panel .panel-body .list_container .list_item {\n background: #f7f7f7;\n background-color: #f7f7f7;\n padding: 2px;\n border-bottom: 2px solid rgba(180,180,180,.30);\n}\n#running .panel-group .panel .panel-body .list_container .list_item:hover {\n background: #f7f7f7;\n background-color: #f7f7f7;\n}\n#running .panel-group .panel .panel-body {\n padding: 2px;\n}\ndiv.running_list_info.toolbar_info {\n font-size: 12.0pt;\n padding: 4px 0 4px 0;\n height: inherit;\n line-height: inherit;\n text-shadow: none;\n}\n.list_placeholder {\n font-weight: normal;\n}\n#tree-selector {\n padding: 0px;\n}\n#project_name > ul > li > a > i.fa.fa-home {\n color: #ff7823;\n font-size: 17pt;\n display: inline-block;\n position: static;\n padding: 0px 0px;\n font-weight: normal;\n text-align: center;\n vertical-align: text-top;\n}\n#project_name {\n display: inline-flex;\n padding-left: 7px;\n margin-left: -2px;\n margin-bottom: -20px;\n text-align: -webkit-auto;\n vertical-align: text-top;\n}\ndiv#notebook_toolbar div.dynamic-instructions {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n}\n.toolbar_info {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n color: #303030;\n text-shadow: none;\n border: none;\n height: inherit;\n line-height: inherit;\n}\n.list_container {\n font-size: 12.0pt;\n color: #303030;\n border: none;\n text-shadow: none !important;\n}\n.list_container > div {\n border-bottom: 1px solid rgba(180,180,180,.14);\n font-size: 12.0pt;\n}\n.list_header > div,\n.list_item > div {\n padding-left: 0px;\n}\n.list_header > div input,\n.list_item > div input {\n top: 0px;\n}\n.list_header > div .item_link,\n.list_item > div .item_link {\n margin-left: -1px;\n vertical-align: middle;\n line-height: 22px;\n font-size: 12.0pt;\n}\n.item_icon {\n font-size: 12.0pt;\n vertical-align: middle;\n}\n.list_item input:not([type=\"checkbox\"]) {\n padding-right: 0px;\n height: auto;\n width: 20%;\n margin: 6px 0 0;\n margin-top: 1px;\n}\n#button-select-all {\n height: auto;\n font-size: 12.0pt;\n padding: 5px;\n min-width: 65px;\n z-index: 0;\n}\nbutton#tree-selector-btn {\n height: auto;\n font-size: 12.0pt;\n padding: 5px;\n}\ninput#select-all.pull-left.tree-selector {\n margin-left: 7px;\n margin-right: 2px;\n margin-top: 5px;\n}\ninput[type=\"radio\"],\ninput[type=\"checkbox\"] {\n margin: 6px 0 0;\n margin-top: 1px;\n line-height: normal;\n}\n.list_container a {\n font-size: 17px;\n color: #303030;\n border: none;\n text-shadow: none !important;\n font-weight: normal;\n font-style: normal;\n}\ndiv.list_container a:hover {\n color: #2f2f2f;\n}\ndiv.list_item:hover {\n background-color: #fafafa;\n}\n.breadcrumb > li {\n font-size: 12.0pt;\n color: #303030;\n border: none;\n text-shadow: none !important;\n}\nul#tabs a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n font-weight: normal;\n font-style: normal;\n border-color: transparent;\n text-shadow: none !important;\n}\n.nav-tabs {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n font-weight: normal;\n font-style: normal;\n background: #ffffff;\n text-shadow: none !important;\n border-color: transparent;\n border-bottom-color: rgba(180,180,180,.30);\n}\n.nav-tabs > li > a:hover {\n color: #2f2f2f;\n background-color: rgba(180,180,180,.14);\n}\n.nav-tabs > li > a:active,\n.nav-tabs > li > a:focus,\n.nav-tabs > li.active > a,\n.nav-tabs > li.active > a:focus,\n.nav-tabs > li.active > a:hover,\n.nav-tabs > li.active > a,\n.nav-tabs > li.active > a:hover,\n.nav-tabs > li.active > a:focus {\n color: #1c1c1c;\n background-color: #eeeeee;\n border: 1px solid transparent;\n border-bottom-color: transparent;\n cursor: default;\n}\n.nav > li > a:hover,\n.nav > li > a:focus {\n text-decoration: none;\n background-color: rgba(180,180,180,.14);\n}\n.nav > li.disabled > a,\n.nav > li.disabled > a:hover {\n color: #aaaaaa;\n}\ndiv#notebook {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n padding-top: 4px;\n}\n.notebook_app {\n background-color: #ffffff;\n}\n#notebook-container {\n padding: 13px;\n background-color: #ffffff;\n min-height: 0px;\n box-shadow: none;\n width: 980px;\n margin-right: auto;\n margin-left: auto;\n}\ndiv#ipython-main-app.container {\n width: 980px;\n margin-right: auto;\n margin-left: auto;\n margin-right: auto;\n margin-left: auto;\n}\n.container {\n width: 980px;\n margin-right: auto;\n margin-left: auto;\n}\n.notebook_app #header {\n box-shadow: none !important;\n background-color: #ffffff;\n border-bottom: 2px solid rgba(180,180,180,.14);\n}\n#header {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n box-shadow: none;\n background-color: #ffffff;\n}\n#header .header-bar {\n background: #ffffff;\n background-color: #ffffff;\n}\nbody > #header .header-bar {\n width: 100%;\n background: #ffffff;\n}\n#menubar {\n background-color: #ffffff;\n}\n#menubar .navbar,\n.navbar-default {\n background-color: #ffffff;\n margin-bottom: 0px;\n}\n.navbar {\n border: none;\n}\n.navbar-default {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n background-color: #ffffff;\n border-color: rgba(180,180,180,.14);\n line-height: 1.5em;\n padding-bottom: 0px;\n}\n.navbar-default .navbar-nav > li > a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n color: #303030;\n display: block;\n line-height: 1.5em;\n padding-top: 8px;\n padding-bottom: 6px;\n}\n.navbar-default .navbar-nav > li > a:hover,\n.navbar-default .navbar-nav > li > a:focus {\n color: #2f2f2f;\n background-color: rgba(180,180,180,.14);\n border-color: rgba(180,180,180,.14);\n line-height: 1.5em;\n}\n.navbar-default .navbar-nav > .open > a,\n.navbar-default .navbar-nav > .open > a:hover,\n.navbar-default .navbar-nav > .open > a:focus {\n color: #1c1c1c;\n background-color: rgba(180,180,180,.14);\n border-color: rgba(180,180,180,.14);\n line-height: 1.5em;\n}\n.edit_mode .modal_indicator:before {\n font-size: 13pt;\n color: #2c85f7;\n content: \"\\f040\";\n}\n.item_icon {\n color: #126dce;\n}\n.item_buttons .kernel-name {\n font-size: 13pt;\n color: #126dce;\n line-height: 22px;\n}\n.running_notebook_icon:before {\n color: #009e07 !important;\n}\n.item_buttons .running-indicator {\n padding-top: 2px;\n color: #009e07;\n}\n#modal_indicator {\n float: right !important;\n color: #126dce;\n background: #ffffff;\n background-color: #ffffff;\n}\n#kernel_indicator {\n float: right !important;\n color: #ff7823;\n background: #ffffff;\n background-color: #ffffff;\n font-size: 14.5pt;\n border-left: 2px solid #ff7823;\n padding-bottom: 2px;\n}\n#kernel_indicator .kernel_indicator_name {\n color: #ff7823;\n background: #ffffff;\n background-color: #ffffff;\n font-size: 14.5pt;\n padding-left: 5px;\n padding-right: 5px;\n}\ndiv.notification_widget.info,\n.notification_widget.info,\n.notification_widget:active:hover,\n.notification_widget.active:hover,\n.open > .dropdown-toggle.notification_widget:hover,\n.notification_widget:active:focus,\n.notification_widget.active:focus,\n.open > .dropdown-toggle.notification_widget:focus,\n.notification_widget:active.focus,\n.notification_widget.active.focus,\n.open > .dropdown-toggle.notification_widget.focus,\ndiv#notification_notebook.notification_widget.btn.btn-xs.navbar-btn,\ndiv#notification_notebook.notification_widget.btn.btn-xs.navbar-btn:hover,\ndiv#notification_notebook.notification_widget.btn.btn-xs.navbar-btn:focus {\n color: #126dce;\n background-color: #ffffff;\n border-color: #ffffff;\n}\n#notification_area,\ndiv.notification_area {\n float: right !important;\n position: static;\n}\n#kernel_logo_widget,\n#kernel_logo_widget .current_kernel_logo {\n display: none;\n}\ndiv#ipython_notebook {\n display: none;\n}\ni.fa.fa-icon {\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n text-rendering: auto;\n}\n.fa {\n display: inline-block;\n font: normal normal normal 12pt/1 \"FontAwesome\", \"Exo_2\", sans-serif;\n text-rendering: auto;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n.dropdown-menu {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n box-shadow: none;\n padding: 0px;\n text-align: left;\n border: 2px solid rgba(180,180,180,.30);\n background-color: #ffffff;\n background: #ffffff;\n line-height: 1.3;\n margin: 0px;\n}\n.dropdown-menu:hover {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n border: 2px solid rgba(180,180,180,.30);\n background-color: #ffffff;\n box-shadow: none;\n line-height: 1.3;\n}\n.dropdown-header {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n display: block;\n color: #ff7823;\n text-decoration: underline;\n white-space: nowrap;\n padding: 8px 0px 0px 6px;\n line-height: 1.3;\n}\n.dropdown-menu > li > a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n line-height: 1.3;\n display: block;\n padding: 10px 25px 10px 14px;\n color: #303030;\n background-color: #ffffff;\n background: #ffffff;\n}\n.dropdown-menu > li > a:hover {\n color: #2f2f2f;\n background-color: rgba(180,180,180,.14);\n background: rgba(180,180,180,.14);\n border-color: rgba(180,180,180,.14);\n}\n.dropdown-menu .divider {\n height: 2px;\n margin: 0px 0px;\n overflow: hidden;\n background-color: rgba(180,180,180,.30);\n}\n.dropdown-submenu > .dropdown-menu {\n top: 0;\n left: 100%;\n margin-top: -2px;\n margin-left: 0px;\n padding-top: 0px;\n}\n.dropdown-menu > .disabled > a,\n.dropdown-menu > .disabled > a:hover,\n.dropdown-menu > .disabled > a:focus {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n font-weight: normal;\n color: #aaaaaa;\n padding: none;\n display: block;\n clear: both;\n line-height: 1.2;\n white-space: nowrap;\n}\n.dropdown-submenu > a:after {\n color: #303030;\n margin-right: -16px;\n}\n.dropdown-submenu:hover > a:after,\n.dropdown-submenu:active > a:after,\n.dropdown-submenu:focus > a:after,\n.dropdown-submenu:visited > a:after {\n color: #ff7823;\n margin-right: -16px;\n}\ndiv.kse-dropdown > .dropdown-menu,\n.kse-dropdown > .dropdown-menu {\n min-width: 0;\n top: 94%;\n}\n.btn,\n.btn-default {\n font-family: \"Exo_2\", sans-serif;\n color: #303030;\n background: #ebebeb;\n background-color: #ebebeb;\n border: 2px solid #e8e8e8;\n font-weight: normal;\n box-shadow: none;\n text-shadow: none;\n border-radius: 2px;\n font-size: inherit;\n}\n.btn:hover,\n.btn:active:hover,\n.btn.active:hover,\n.btn-default:hover,\n.open > .dropdown-toggle.btn-default:hover,\n.open > .dropdown-toggle.btn:hover {\n color: #2f2f2f;\n background-color: #e4e4e4;\n background: #e4e4e4;\n border-color: #e4e4e4;\n background-image: none;\n box-shadow: none !important;\n border-radius: 2px;\n}\n.btn:active,\n.btn.active,\n.btn:active:focus,\n.btn.active:focus,\n.btn:active.focus,\n.btn.active.focus,\n.btn-default:focus,\n.btn-default.focus,\n.btn-default:active,\n.btn-default.active,\n.btn-default:active:hover,\n.btn-default.active:hover,\n.btn-default:active:focus,\n.btn-default.active:focus,\n.btn-default:active.focus,\n.btn-default.active.focus,\n.open > .dropdown-toggle.btn:focus,\n.open > .dropdown-toggle.btn.focus,\n.open > .dropdown-toggle.btn-default {\n color: #1c1c1c;\n background-color: #e4e4e4;\n background: #e4e4e4;\n border-color: #e4e4e4;\n background-image: none;\n box-shadow: none !important;\n border-radius: 2px;\n}\n.item_buttons > .btn,\n.item_buttons > .btn-group,\n.item_buttons > .input-group {\n margin-left: 5px;\n background: #eeeeee;\n background-color: #eeeeee;\n border: 2px solid #eeeeee;\n}\n.item_buttons > .btn:hover,\n.item_buttons > .btn-group:hover,\n.item_buttons > .input-group:hover {\n margin-left: 5px;\n background: #e9e9e9;\n background-color: #e9e9e9;\n border: 2px solid #e9e9e9;\n}\n.btn-group > .btn-mini,\n.btn-sm,\n.btn-group-sm > .btn,\n.btn-xs,\n.btn-group-xs > .btn,\n.alternate_upload .btn-upload,\n.btn-group,\n.btn-group-vertical {\n font-size: 12.0pt;\n font-weight: normal;\n}\n.btn-xs,\n.btn-group-xs > .btn {\n font-size: 12.0pt;\n background-image: none;\n font-weight: normal;\n text-shadow: none;\n display: inline-table;\n}\n.alternate_upload .btn-upload {\n display: none;\n}\n.alternate_upload input.fileinput {\n display: none;\n}\nbutton.close {\n border: 0px none;\n font-family: sans-serif;\n font-size: 25pt;\n}\n.dynamic-buttons {\n font-size: inherit;\n padding-top: 0px;\n display: inline-block;\n}\n.close {\n color: #de143d;\n opacity: .5;\n text-shadow: none;\n}\n.close:hover {\n color: #de143d;\n opacity: 1;\n}\ndiv.btn.btn-default.output_collapsed {\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: #eeeeee;\n}\ndiv.btn.btn-default.output_collapsed:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border-color: #e9e9e9;\n}\ndiv.nbext-enable-btns .btn[disabled],\ndiv.nbext-enable-btns .btn[disabled]:hover,\n.btn-default.disabled,\n.btn-default[disabled],\n.btn-default.disabled:hover,\n.btn-default[disabled]:hover,\nfieldset[disabled] .btn-default:hover,\n.btn-default.disabled:focus,\n.btn-default[disabled]:focus,\nfieldset[disabled] .btn-default:focus,\n.btn-default.disabled.focus,\n.btn-default[disabled].focus,\nfieldset[disabled] .btn-default.focus {\n color: #4a4a4a;\n background: #e8e8e8;\n background-color: #e8e8e8;\n border-color: #e8e8e8;\n}\n.input-group-addon {\n padding: 2px 5px;\n font-size: 12.0pt;\n font-weight: normal;\n height: auto;\n color: #303030;\n text-align: center;\n background-color: #ffffff;\n border: none;\n}\n.btn-group > .btn + .dropdown-toggle {\n padding-left: 8px;\n padding-right: 8px;\n height: 100%;\n border-left: 2px solid #ff7823 !important;\n}\n.btn-group > .btn + .dropdown-toggle:hover {\n border-left: 2px solid #ff7823 !important;\n}\n.input-group-btn {\n position: relative;\n font-size: inherit;\n white-space: nowrap;\n}\n.input-group-btn:first-child > .btn,\n.input-group-btn:first-child > .btn-group {\n background: #eeeeee;\n background-color: #eeeeee;\n border: 1px solid #e9e9e9;\n margin: 2px;\n font-size: inherit;\n}\n.input-group-btn:first-child > .btn:hover,\n.input-group-btn:first-child > .btn-group:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border: 1px solid #e9e9e9;\n margin: 2px;\n font-size: inherit;\n}\ndiv.modal .btn-group > .btn:first-child {\n background: #eeeeee;\n background-color: #eeeeee;\n border: 1px solid #e9e9e9;\n margin-top: 0px !important;\n margin-left: 0px;\n margin-bottom: 2px;\n}\ndiv.modal .btn-group > .btn:first-child:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border: 1px solid #e9e9e9;\n}\ndiv.modal > button,\ndiv.modal-footer > button {\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: #eeeeee;\n}\ndiv.modal > button:hover,\ndiv.modal-footer > button:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border-color: #e9e9e9;\n}\n.modal-content {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n position: relative;\n background: #eeeeee;\n background-color: #eeeeee;\n border: none;\n border-radius: 1px;\n background-clip: padding-box;\n outline: none;\n}\n.modal-header {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n color: #303030;\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: rgba(180,180,180,.30);\n padding: 12px;\n min-height: 16.4286px;\n}\n.modal-content h4 {\n font-family: \"Exo_2\", sans-serif;\n font-size: 16pt;\n color: #303030;\n padding: 5px;\n}\n.modal-body {\n background-color: #ffffff;\n position: relative;\n padding: 15px;\n}\n.modal-footer {\n padding: 10px;\n text-align: right;\n background-color: #f7f7f7;\n border-top: 1px solid rgba(180,180,180,.30);\n}\n.alert-info {\n background-color: #fdfdfd;\n border-color: rgba(180,180,180,.30);\n color: #303030;\n}\n.modal-header .close {\n margin-top: -5px;\n font-size: 25pt;\n}\n.modal-backdrop,\n.modal-backdrop.in {\n opacity: 0.75;\n background-color: #eeeeee;\n}\ndiv.panel,\ndiv.panel-default,\n.panel,\n.panel-default {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n background-color: #f7f7f7;\n color: #303030;\n margin-bottom: 14px;\n border: 0;\n box-shadow: none;\n}\ndiv.panel > .panel-heading,\ndiv.panel-default > .panel-heading {\n font-size: 14pt;\n color: #303030;\n background: #eeeeee;\n background-color: #eeeeee;\n border: 0;\n}\n.modal .modal-dialog {\n min-width: 950px;\n margin: 50px auto;\n}\ndiv.container-fluid {\n margin-right: auto;\n margin-left: auto;\n padding-left: 7px;\n padding-right: 12px;\n}\ndiv.form-control,\n.form-control {\n font-family: \"Exo_2\", sans-serif;\n font-size: inherit;\n color: #303030;\n background-color: #ffffff;\n border: 2px solid #e7e7e7;\n margin-left: 2px;\n height: auto;\n box-shadow: none;\n padding: 6px 12px;\n transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;\n}\n.form-group.list-group-item {\n color: #303030;\n background-color: #f7f7f7;\n border-color: rgba(180,180,180,.30);\n margin-bottom: 0px;\n}\ninput,\nbutton,\nselect,\ntextarea {\n background-color: #ffffff;\n font-weight: normal;\n border: 2px solid rgba(180,180,180,.30);\n}\nselect.form-control.select-xs {\n height: auto;\n}\ndiv.output.output_scroll {\n box-shadow: none;\n}\n::-webkit-scrollbar-track {\n -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.11);\n background-color: #d0d0d0;\n border-radius: 6px;\n}\n::-webkit-scrollbar {\n width: 14px;\n height: 10px;\n background-color: #d0d0d0;\n border-radius: 6px;\n}\n::-webkit-scrollbar-thumb {\n background-color: #ffffff;\n background-image: -webkit-gradient(linear,40% 0%,75% 86%,from(#ff6b0f ),color-stop(0.5,#ff8b42 ),to(#ff6b0f ));\n min-height: 60px;\n border-radius: 2px;\n}\ndiv.input_area {\n background-color: #efefef;\n padding-right: 1.2em;\n border: 0px;\n border-top-left-radius: 0px;\n border-top-right-radius: 2px;\n border-bottom-left-radius: 0px;\n border-bottom-right-radius: 0px;\n}\ndiv.cell {\n padding: 0px;\n background: #efefef;\n background-color: #efefef;\n border: medium solid #ffffff;\n border-top-right-radius: 2px;\n border-top-left-radius: 2px;\n}\ndiv.cell.selected {\n background: #efefef;\n background-color: #efefef;\n border: medium solid #ff7823;\n padding: 0px;\n border-top-right-radius: 2px;\n border-top-left-radius: 2px;\n}\n.edit_mode div.cell.selected {\n padding: 0px;\n background: #efefef;\n background-color: #efefef;\n border: medium solid #ffd5bb;\n border-top-right-radius: 2px;\n border-top-left-radius: 2px;\n}\ndiv.cell.edit_mode {\n padding: 0px;\n background: #efefef;\n background-color: #efefef;\n border: medium solid #ffd5bb;\n border-top-right-radius: 2px;\n border-top-left-radius: 2px;\n}\ndiv.prompt,\n.prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n font-weight: normal;\n color: #aaaaaa;\n line-height: 170%;\n padding: 0px;\n padding-top: 4px;\n padding-left: .25em;\n text-align: left !important;\n min-width: 12ex;\n width: 12ex;\n}\ndiv.prompt.input_prompt {\n background-color: #efefef;\n border-right: 2px solid rgba(240,147,43,.50);\n border-top-left-radius: 2px;\n border-top-right-radius: 0px;\n border-bottom-left-radius: 0px;\n border-bottom-right-radius: 0px;\n min-width: 12ex;\n width: 12ex !important;\n}\ndiv.output_wrapper {\n background-color: #ffffff;\n border: 0px;\n margin-bottom: 0em;\n margin-top: 0em;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-left-radius: 2px;\n border-bottom-right-radius: 2px;\n}\ndiv.output_subarea.output_text.output_stream.output_stdout,\ndiv.output_subarea.output_text {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 10.0pt;\n line-height: 150% !important;\n background-color: #ffffff;\n color: #303030;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-left-radius: 2px;\n border-bottom-right-radius: 2px;\n}\ndiv.output_area pre {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 10.0pt;\n line-height: 150% !important;\n color: #303030;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-left-radius: 2px;\n border-bottom-right-radius: 2px;\n}\ndiv.output_area {\n display: -webkit-box;\n}\ndiv.output_html {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 10.0pt;\n color: #353535;\n background-color: #ffffff;\n background: #ffffff;\n}\ndiv.output_subarea {\n overflow-x: auto;\n padding: .8em;\n -webkit-box-flex: 1;\n -moz-box-flex: 1;\n box-flex: 1;\n flex: 1;\n max-width: 90%;\n}\ndiv.prompt.output_prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n background-color: #ffffff;\n color: #ffffff;\n border-bottom-left-radius: 2px;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-right-radius: 0px;\n min-width: 12ex;\n width: 12ex;\n}\ndiv.out_prompt_overlay.prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n background-color: #ffffff;\n border-bottom-left-radius: 2px;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n border-bottom-right-radius: 0px;\n min-width: 12ex;\n width: 12ex;\n}\ndiv.out_prompt_overlay.prompt:hover {\n background-color: #ffffff;\n box-shadow: #e8e8e8 2px 1px 2px 2.5px inset;\n border-bottom-left-radius: 2px;\n -webkit-border-: 2px;\n -moz-border-radius: 2px;\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n min-width: 12ex;\n width: 12ex !important;\n}\ndiv.text_cell,\ndiv.text_cell_render pre,\ndiv.text_cell_render {\n font-family: \"Lora\", serif;\n font-size: 13pt;\n line-height: 170% !important;\n color: #353535;\n background: #ffffff;\n background-color: #ffffff;\n border-radius: 2px;\n}\ndiv.cell.text_cell.rendered.selected {\n font-family: \"Lora\", serif;\n border: medium solid #126dce;\n line-height: 170% !important;\n background: #ffffff;\n background-color: #ffffff;\n border-radius: 2px;\n}\ndiv.cell.text_cell.unrendered.selected {\n font-family: \"Lora\", serif;\n line-height: 170% !important;\n background: #ffffff;\n background-color: #ffffff;\n border: medium solid #126dce;\n border-radius: 2px;\n}\ndiv.cell.text_cell.selected {\n font-family: \"Lora\", serif;\n line-height: 170% !important;\n border: medium solid #126dce;\n background: #ffffff;\n background-color: #ffffff;\n border-radius: 2px;\n}\n.edit_mode div.cell.text_cell.selected {\n font-family: \"Lora\", serif;\n line-height: 170% !important;\n background: #ffffff;\n background-color: #ffffff;\n border: medium solid #87b0db;\n border-radius: 2px;\n}\ndiv.text_cell.unrendered,\ndiv.text_cell.unrendered.selected,\ndiv.edit_mode div.text_cell.unrendered {\n font-family: \"Lora\", serif;\n line-height: 170% !important;\n background: #ffffff;\n background-color: #ffffff;\n border-radius: 2px;\n}\ndiv.cell.text_cell.rendered .input_prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n font-weight: normal;\n color: #aaaaaa;\n text-align: left !important;\n min-width: 0ex;\n width: 0ex !important;\n background-color: #ffffff;\n border-right: 2px solid transparent;\n}\ndiv.cell.text_cell.unrendered .input_prompt {\n font-family: \"Fira Code\", monospace;\n font-size: 9.5pt;\n font-weight: normal;\n color: #aaaaaa;\n text-align: left !important;\n min-width: 0ex;\n width: 0ex !important;\n border-right: 2px solid transparent;\n}\ndiv.rendered_html code {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n padding-top: 3px;\n color: #303030;\n background: #efefef;\n background-color: #efefef;\n}\npre,\ncode,\nkbd,\nsamp {\n white-space: pre-wrap;\n}\ncode {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt !important;\n line-height: 170% !important;\n color: #353535;\n background: #efefef;\n background-color: #efefef;\n}\nkbd {\n padding: 4px;\n font-size: 11pt;\n color: #303030;\n background-color: #efefef;\n border: 0;\n box-shadow: none;\n}\npre {\n display: block;\n padding: 8.5px;\n margin: 0 0 9px;\n font-size: 12.0pt;\n line-height: 1.42857143;\n color: #303030;\n background-color: #efefef;\n border: 1px solid #e7e7e7;\n border-radius: 2px;\n}\ndiv.rendered_html {\n color: #353535;\n}\ndiv.rendered_html pre,\ndiv.text_cell_render pre {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt !important;\n line-height: 170% !important;\n color: #353535;\n background: #efefef;\n background-color: #efefef;\n border: 2px #e7e7e7  solid;\n max-width: 86%;\n border-radius: 2px;\n padding: 5px;\n}\ndiv.text_cell_render h1,\ndiv.rendered_html h1,\ndiv.text_cell_render h2,\ndiv.rendered_html h2,\ndiv.text_cell_render h3,\ndiv.rendered_html h3,\ndiv.text_cell_render h4,\ndiv.rendered_html h4,\ndiv.text_cell_render h5,\ndiv.rendered_html h5 {\n font-family: \"Exo_2\", sans-serif;\n}\n.rendered_html h1:first-child,\n.rendered_html h2:first-child,\n.rendered_html h3:first-child,\n.rendered_html h4:first-child,\n.rendered_html h5:first-child,\n.rendered_html h6:first-child {\n margin-top: 0.2em;\n}\n.rendered_html h1,\n.text_cell_render h1 {\n color: #126dce;\n font-size: 220%;\n text-align: center;\n font-weight: lighter;\n}\n.rendered_html h2,\n.text_cell_render h2 {\n text-align: left;\n font-size: 170%;\n color: #126dce;\n font-style: normal;\n font-weight: lighter;\n}\n.rendered_html h3,\n.text_cell_render h3 {\n font-size: 150%;\n color: #126dce;\n font-weight: lighter;\n text-decoration: italic;\n font-style: normal;\n}\n.rendered_html h4,\n.text_cell_render h4 {\n font-size: 120%;\n color: #126dce;\n font-weight: underline;\n font-style: normal;\n}\n.rendered_html h5,\n.text_cell_render h5 {\n font-size: 100%;\n color: #2f2f2f;\n font-weight: lighter;\n text-decoration: underline;\n}\n.rendered_html table,\n.rendered_html tr,\n.rendered_html td {\n font-family: \"Fira Code\", monospace;\n font-size: 10.0pt !important;\n line-height: 150% !important;\n border: 1px solid #d6d6d6;\n color: #353535;\n background-color: #ffffff;\n background: #ffffff;\n}\ntable.dataframe,\n.rendered_html tr,\n.dataframe * {\n font-family: \"Fira Code\", monospace;\n font-size: 10.0pt !important;\n border: 1px solid #d6d6d6;\n}\n.dataframe th,\n.rendered_html th {\n font-family: \"Exo_2\", sans-serif;\n font-size: 11pt !important;\n font-weight: bold;\n border: 1px solid #c4c4c4;\n background: #eeeeee;\n}\n.dataframe td,\n.rendered_html td {\n font-family: \"Fira Code\", monospace;\n font-size: 10.0pt !important;\n color: #353535;\n background: #ffffff;\n border: 1px solid #d6d6d6;\n text-align: left;\n min-width: 4em;\n}\n.dataframe-summary-row tr:last-child,\n.dataframe-summary-col td:last-child {\n font-family: \"Exo_2\", sans-serif;\n font-size: 11pt !important;\n font-weight: bold;\n color: #353535;\n border: 1px solid #d6d6d6;\n background: #eeeeee;\n}\ndiv.widget-area {\n background-color: #ffffff;\n background: #ffffff;\n color: #303030;\n}\ndiv.widget-area a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n font-weight: normal;\n font-style: normal;\n color: #303030;\n text-shadow: none !important;\n}\ndiv.widget-area a:hover,\ndiv.widget-area a:focus {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12.0pt;\n font-weight: normal;\n font-style: normal;\n color: #2f2f2f;\n background: rgba(180,180,180,.14);\n background-color: rgba(180,180,180,.14);\n border-color: transparent;\n background-image: none;\n text-shadow: none !important;\n}\ndiv.widget_item.btn-group > button.btn.btn-default.widget-combo-btn,\ndiv.widget_item.btn-group > button.btn.btn-default.widget-combo-btn:hover {\n background: #eeeeee;\n background-color: #eeeeee;\n border: 2px solid #eeeeee !important;\n font-size: inherit;\n z-index: 0;\n}\ndiv.jupyter-widgets.widget-hprogress.widget-hbox,\ndiv.widget-hbox,\n.widget-hbox {\n display: inline-table;\n}\ndiv.jupyter-widgets.widget-hprogress.widget-hbox .widget-label,\ndiv.widget-hbox .widget-label,\n.widget-hbox .widget-label {\n font-size: 11pt;\n min-width: 100%;\n padding-top: 5px;\n padding-right: 10px;\n text-align: left;\n vertical-align: text-top;\n}\n.progress {\n overflow: hidden;\n height: 20px;\n margin-bottom: 10px;\n padding-left: 10px;\n background-color: #c6c6c6;\n border-radius: 4px;\n -webkit-box-shadow: none;\n box-shadow: none;\n}\n.rendered_html :link {\n font-family: \"Exo_2\", sans-serif;\n font-size: 100%;\n color: #2c85f7;\n text-decoration: underline;\n}\n.rendered_html :visited,\n.rendered_html :visited:active,\n.rendered_html :visited:focus {\n color: #2e6eb2;\n}\n.rendered_html :visited:hover,\n.rendered_html :link:hover {\n font-family: \"Exo_2\", sans-serif;\n font-size: 100%;\n color: #eb6a18;\n}\na.anchor-link:link:hover {\n font-size: inherit;\n color: #eb6a18;\n}\na.anchor-link:link {\n font-size: inherit;\n text-decoration: none;\n padding: 0px 20px;\n visibility: none;\n color: #126dce;\n}\ndiv#nbextensions-configurator-container.container {\n width: 980px;\n margin-right: 0;\n margin-left: 0;\n}\ndiv.nbext-selector > nav > .nav > li > a {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12pt;\n}\ndiv.nbext-readme > .nbext-readme-contents > .rendered_html {\n font-family: \"Exo_2\", sans-serif;\n font-size: 12pt;\n line-height: 145%;\n padding: 1em 1em;\n color: #353535;\n background-color: #ffffff;\n -webkit-box-shadow: none;\n -moz-box-shadow: none;\n box-shadow: none;\n}\n.nbext-icon,\n.nbext-desc,\n.nbext-compat-div,\n.nbext-enable-btns,\n.nbext-params {\n margin-bottom: 8px;\n font-size: 12pt;\n}\ndiv.nbext-readme > .nbext-readme-contents {\n padding: 0;\n overflow-y: hidden;\n}\ndiv.nbext-readme > .nbext-readme-contents:not(:empty) {\n margin-top: 0.5em;\n margin-bottom: 2em;\n border: none;\n border-top-color: rgba(180,180,180,.30);\n}\n.nbext-showhide-incompat {\n padding-bottom: 0.5em;\n color: #4a4a4a;\n font-size: 12.0pt;\n}\n.shortcut_key,\nspan.shortcut_key {\n display: inline-block;\n width: 16ex;\n text-align: right;\n font-family: monospace;\n}\nmark,\n.mark {\n background-color: #ffffff;\n color: #353535;\n padding: .15em;\n}\na.text-warning,\na.text-warning:hover {\n color: #aaaaaa;\n}\na.text-warning.bg-warning {\n background-color: #ffffff;\n}\nspan.bg-success.text-success {\n background-color: transparent;\n color: #009e07;\n}\nspan.bg-danger.text-danger {\n background-color: #ffffff;\n color: #de143d;\n}\n.has-success .input-group-addon {\n color: #009e07;\n border-color: transparent;\n background: inherit;\n background-color: rgba(83,180,115,.10);\n}\n.has-success .form-control {\n border-color: #009e07;\n -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.025);\n box-shadow: inset 0 1px 1px rgba(0,0,0,0.025);\n}\n.has-error .input-group-addon {\n color: #de143d;\n border-color: transparent;\n background: inherit;\n background-color: rgba(192,57,67,.10);\n}\n.has-error .form-control {\n border-color: #de143d;\n -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.025);\n box-shadow: inset 0 1px 1px rgba(0,0,0,0.025);\n}\n.kse-input-group-pretty > kbd {\n font-family: \"Droid Sans Mono\", monospace;\n color: #303030;\n font-weight: normal;\n background: transparent;\n}\n.kse-input-group-pretty > kbd {\n font-family: \"Droid Sans Mono\", monospace;\n color: #303030;\n font-weight: normal;\n background: transparent;\n}\ndiv.nbext-enable-btns .btn[disabled],\ndiv.nbext-enable-btns .btn[disabled]:hover,\n.btn-default.disabled,\n.btn-default[disabled] {\n background: #e8e8e8;\n background-color: #e8e8e8;\n color: #282828;\n}\nlabel#Keyword-Filter {\n display: none;\n}\n.nav-pills > li.active > a,\n.nav-pills > li.active > a:hover,\n.nav-pills > li.active > a:focus {\n color: #ffffff;\n background-color: #126dce;\n}\n.input-group .nbext-list-btn-add,\n.input-group-btn:last-child > .btn-group > .btn {\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: #eeeeee;\n}\n.input-group .nbext-list-btn-add:hover,\n.input-group-btn:last-child > .btn-group > .btn:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border-color: #e9e9e9;\n}\n#notebook-container > div.cell.code_cell.rendered.selected > div.widget-area > div.widget-subarea > div > div.widget_item.btn-group > button.btn.btn-default.dropdown-toggle.widget-combo-carrot-btn {\n background: #eeeeee;\n background-color: #eeeeee;\n border-color: #eeeeee;\n}\n#notebook-container > div.cell.code_cell.rendered.selected > div.widget-area > div.widget-subarea > div > div.widget_item.btn-group > button.btn.btn-default.dropdown-toggle.widget-combo-carrot-btn:hover {\n background: #e9e9e9;\n background-color: #e9e9e9;\n border-color: #e9e9e9;\n}\ninput.raw_input {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt !important;\n color: #303030;\n background-color: #efefef;\n border-color: #ececec;\n background: #ececec;\n width: auto;\n vertical-align: baseline;\n padding: 0em 0.25em;\n margin: 0em 0.25em;\n -webkit-box-shadow: none;\n box-shadow: none;\n}\naudio,\nvideo {\n display: inline;\n vertical-align: middle;\n align-content: center;\n margin-left: 20%;\n}\n.cmd-palette .modal-body {\n padding: 0px;\n margin: 0px;\n}\n.cmd-palette form {\n background: #eeeeee;\n background-color: #eeeeee;\n}\n.typeahead-field input:last-child,\n.typeahead-hint {\n background: #eeeeee;\n background-color: #eeeeee;\n z-index: 1;\n}\n.typeahead-field input {\n font-family: \"Exo_2\", sans-serif;\n color: #303030;\n border: none;\n font-size: 28pt;\n display: inline-block;\n line-height: inherit;\n padding: 3px 10px;\n height: 70px;\n}\n.typeahead-select {\n background-color: #eeeeee;\n}\nbody > div.modal.cmd-palette.typeahead-field {\n display: table;\n border-collapse: separate;\n background-color: #f7f7f7;\n}\n.typeahead-container button {\n font-family: \"Exo_2\", sans-serif;\n font-size: 28pt;\n background-color: #d0d0d0;\n border: none;\n display: inline-block;\n line-height: inherit;\n padding: 3px 10px;\n height: 70px;\n}\n.typeahead-search-icon {\n min-width: 40px;\n min-height: 55px;\n display: block;\n vertical-align: middle;\n text-align: center;\n}\n.typeahead-container button:focus,\n.typeahead-container button:hover {\n color: #2f2f2f;\n background-color: #ff7823;\n border-color: #ff7823;\n}\n.typeahead-list > li.typeahead-group.active > a,\n.typeahead-list > li.typeahead-group > a,\n.typeahead-list > li.typeahead-group > a:focus,\n.typeahead-list > li.typeahead-group > a:hover {\n display: none;\n}\n.typeahead-dropdown > li > a,\n.typeahead-list > li > a {\n color: #303030;\n text-decoration: none;\n}\n.typeahead-dropdown,\n.typeahead-list {\n font-family: \"Exo_2\", sans-serif;\n font-size: 13pt;\n color: #303030;\n background-color: #ffffff;\n border: none;\n background-clip: padding-box;\n margin-top: 0px;\n padding: 3px 2px 3px 0px;\n line-height: 1.7;\n}\n.typeahead-dropdown > li.active > a,\n.typeahead-dropdown > li > a:focus,\n.typeahead-dropdown > li > a:hover,\n.typeahead-list > li.active > a,\n.typeahead-list > li > a:focus,\n.typeahead-list > li > a:hover {\n color: #2f2f2f;\n background-color: #f7f7f7;\n border-color: #f7f7f7;\n}\n.command-shortcut:before {\n content: \"(command)\";\n padding-right: 3px;\n color: #aaaaaa;\n}\n.edit-shortcut:before {\n content: \"(edit)\";\n padding-right: 3px;\n color: #aaaaaa;\n}\nul.typeahead-list i {\n margin-left: 1px;\n width: 18px;\n margin-right: 10px;\n}\nul.typeahead-list {\n max-height: 50vh;\n overflow: auto;\n}\n.typeahead-list > li {\n position: relative;\n border: none;\n}\ndiv.input.typeahead-hint,\ninput.typeahead-hint,\nbody > div.modal.cmd-palette.in > div > div > div > form > div > div.typeahead-field > span.typeahead-query > input.typeahead-hint {\n color: #aaaaaa !important;\n background-color: transparent;\n padding: 3px 10px;\n}\n.typeahead-dropdown > li > a,\n.typeahead-list > li > a {\n display: block;\n padding: 5px;\n clear: both;\n font-weight: 400;\n line-height: 1.7;\n border: 1px solid #ffffff;\n border-bottom-color: rgba(180,180,180,.30);\n}\nbody > div.modal.cmd-palette.in > div {\n min-width: 750px;\n margin: 150px auto;\n}\n.typeahead-container strong {\n font-weight: bolder;\n color: #ff7823;\n}\n#find-and-replace #replace-preview .match,\n#find-and-replace #replace-preview .insert {\n color: #ffffff;\n background-color: #ff7823;\n border-color: #ff7823;\n border-style: solid;\n border-width: 1px;\n border-radius: 0px;\n}\n#find-and-replace #replace-preview .replace .match {\n background-color: #de143d;\n border-color: #de143d;\n border-radius: 0px;\n}\n#find-and-replace #replace-preview .replace .insert {\n background-color: #009e07;\n border-color: #009e07;\n border-radius: 0px;\n}\ndiv.CodeMirror,\ndiv.CodeMirror pre {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n line-height: 170%;\n color: #303030;\n}\ndiv.CodeMirror-lines {\n padding-bottom: .6em;\n padding-left: .5em;\n padding-right: 1.5em;\n padding-top: 4px;\n}\nspan.ansiblack {\n color: #dc4384;\n}\nspan.ansiblue {\n color: #009e07;\n}\nspan.ansigray {\n color: #ff7823;\n}\nspan.ansigreen {\n color: #333333;\n}\nspan.ansipurple {\n color: #653bc5;\n}\nspan.ansicyan {\n color: #055be0;\n}\nspan.ansiyellow {\n color: #ff7823;\n}\nspan.ansired {\n color: #de143d;\n}\ndiv.output-stderr {\n background-color: #ebb5b7;\n}\ndiv.output-stderr pre {\n color: #000000;\n}\ndiv.js-error {\n color: #de143d;\n}\n.ipython_tooltip {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n line-height: 170%;\n border: 2px solid #dadada;\n background: #eeeeee;\n background-color: #eeeeee;\n border-radius: 2px;\n overflow-x: visible;\n overflow-y: visible;\n box-shadow: none;\n position: absolute;\n z-index: 1000;\n}\n.ipython_tooltip .tooltiptext pre {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n line-height: 170%;\n background: #eeeeee;\n background-color: #eeeeee;\n color: #303030;\n overflow-x: visible;\n overflow-y: visible;\n max-width: 900px;\n}\ndiv#tooltip.ipython_tooltip {\n overflow-x: wrap;\n overflow-y: visible;\n max-width: 800px;\n}\ndiv.tooltiptext.bigtooltip {\n overflow-x: visible;\n overflow-y: scroll;\n height: 400px;\n max-width: 800px;\n}\n.cm-s-ipython.CodeMirror {\n font-family: \"Droid Sans Mono\", monospace;\n font-size: 11pt;\n background: #efefef;\n color: #303030;\n border-radius: 2px;\n font-style: normal;\n font-weight: normal;\n}\n.cm-s-ipython div.CodeMirror-selected {\n background: #e0e1e3;\n}\n.cm-s-ipython .CodeMirror-gutters {\n background: #e0e1e3;\n border: none;\n border-radius: 0px;\n}\n.cm-s-ipython .CodeMirror-linenumber {\n color: #aaaaaa;\n}\n.cm-s-ipython .CodeMirror-cursor {\n border-left: 2px solid #ff711a;\n}\n.cm-s-ipython span.cm-comment {\n color: #8d8d8d;\n font-style: italic;\n}\n.cm-s-ipython span.cm-atom {\n color: #055be0;\n}\n.cm-s-ipython span.cm-number {\n color: #ff8132;\n}\n.cm-s-ipython span.cm-property {\n color: #e22978;\n}\n.cm-s-ipython span.cm-attribute {\n color: #de143d;\n}\n.cm-s-ipython span.cm-keyword {\n color: #713bc5;\n font-weight: normal;\n}\n.cm-s-ipython span.cm-string {\n color: #009e07;\n}\n.cm-s-ipython span.cm-meta {\n color: #aa22ff;\n}\n.cm-s-ipython span.cm-operator {\n color: #055be0;\n}\n.cm-s-ipython span.cm-builtin {\n color: #e22978;\n}\n.cm-s-ipython span.cm-variable {\n color: #303030;\n}\n.cm-s-ipython span.cm-variable-2 {\n color: #de143d;\n}\n.cm-s-ipython span.cm-variable-3 {\n color: #aa22ff;\n}\n.cm-s-ipython span.cm-def {\n color: #e22978;\n font-weight: normal;\n}\n.cm-s-ipython span.cm-error {\n background: rgba(191,97,106,.40);\n}\n.cm-s-ipython span.cm-tag {\n color: #e22978;\n}\n.cm-s-ipython span.cm-link {\n color: #ff7823;\n}\n.cm-s-ipython span.cm-storage {\n color: #055be0;\n}\n.cm-s-ipython span.cm-entity {\n color: #e22978;\n}\n.cm-s-ipython span.cm-quote {\n color: #009e07;\n}\ndiv.CodeMirror span.CodeMirror-matchingbracket {\n color: #1c1c1c;\n background-color: rgba(30,112,199,.30);\n}\ndiv.CodeMirror span.CodeMirror-nonmatchingbracket {\n color: #1c1c1c;\n background: rgba(191,97,106,.40) !important;\n}\ndiv.cell.text_cell .cm-s-default .cm-header {\n color: #126dce;\n}\ndiv.cell.text_cell .cm-s-default span.cm-variable-2 {\n color: #353535;\n}\ndiv.cell.text_cell .cm-s-default span.cm-variable-3 {\n color: #aa22ff;\n}\n.cm-s-default span.cm-comment {\n color: #8d8d8d;\n}\n.cm-s-default .cm-tag {\n color: #009fb7;\n}\n.cm-s-default .cm-builtin {\n color: #e22978;\n}\n.cm-s-default .cm-string {\n color: #009e07;\n}\n.cm-s-default .cm-keyword {\n color: #713bc5;\n}\n.cm-s-default .cm-number {\n color: #ff8132;\n}\n.cm-s-default .cm-error {\n color: #055be0;\n}\n.CodeMirror-cursor {\n border-left: 2px solid #ff711a;\n border-right: none;\n width: 0;\n}\n.cm-s-default div.CodeMirror-selected {\n background: #e0e1e3;\n}\n.cm-s-default .cm-selected {\n background: #e0e1e3;\n}\ndiv#maintoolbar {\n display: none !important;\n}\n#header-container {\n display: none !important;\n}\n\n/**********************************\n MathJax Settings and Style Script\n**********************************/\n.MathJax_Display,\n.MathJax nobr>span.math>span {\n    border: 0 !important;\n    font-size: 110% !important;\n    text-align: center !important;\n    margin: 0em !important;\n}\n/* Prevents MathJax from jittering */\n/* cell position when cell is selected */\n.MathJax:focus, body :focus .MathJax {\n    display: inline-block !important;\n}\n\n\n\n </style>\n\n\n\n\n```python\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# 1. magic for inline plot\n# 2. magic to print version\n# 3. magic so that the notebook will reload external python modules\n%matplotlib inline\n%load_ext watermark\n%load_ext autoreload \n%autoreload 2\n\nfrom tqdm import trange\nfrom scipy.stats import bernoulli, ttest_ind\n\n%watermark -a 'Ethen' -d -t -v -p numpy,pandas,matplotlib,tqdm\n```\n\n    Ethen 2017-04-23 14:48:05 \n    \n    CPython 3.5.2\n    IPython 5.3.0\n    \n    numpy 1.12.1\n    pandas 0.19.2\n    matplotlib 2.0.0\n    tqdm 4.11.2\n\n\n# The multiple hypothesis testing problem\n\nThis is simply walking through the content at following link. [Blog: The multiple hypothesis testing problem](http://www.claudiobellei.com/2016/10/30/multiple-testing-part1/).\n\nSuppose a particular event has a chance of 1% of happening at the first attempt. Now, if we make $N$ attempts what is the probability that this event will have happened at least once among the $N$ attempts? The answer is $1 \u2212 0.99^N$. For $N = 5$, the rare event already has an almost 5% chance of happening at least once in the five attempts. This is the rationale behind why multiple testings can complicate things in statistical inference.\n\nSuppose we formulate a hypothesis test by defining a null hypothesis $H_0$ and alternative hypothesis $H_1$. We then set a type-I error level $\\alpha$, which means that if the null hypothesis $H_0$ were true, we would incorrectly reject the null with probability $\\alpha$. Then given $N$ tests the probability of rejecting the null in any of the tests can be written as\n\n\\begin{align}\nP(\\mathrm{rejecting\\ the\\ null\\  in \\ any \\ of \\ the \\ tests}) = P(r_1 \\lor r_2 \\lor \\dots \\lor r_n)\n\\end{align}\n\nIn which $r_j$ denotes the event \"the null is rejected at the j-th test\". To compute the probability above we can convert it to:\n\n\\begin{align}\nP(r_1\\lor r_2\\lor\\dots\\lor r_n) = 1 - P(r_1^* \\land r_2^* \\land\\dots\\land r_n^* ) = 1 - \\prod_{j=1}^N P(r_j^*)\n\\end{align}\n\nWhere $r_j^*$ denotes the event \"the null is NOT rejected at the j-th test\".\n\nSuppose that we do a test where we fix the type-I error $\\alpha$ to 0.05 (0.05 is simply the conventionally used number). By definition, if we do one test only we will reject the null 5% of the times if the null is actually true. What if we make 2 tests? What are the chances of committing a type-I error then? The error will be:\n\n\\begin{align}\nP(r_1 \\lor r_2) = 1 - P(r_1^* \\land r_2^*) = 1-P(r_1^*)P(r_2^*) = 1-0.95 \\times 0.95 = 0.0975\n\\end{align}\n\nSo the consequence of doing $n$ multiple test is that the effective type-I error will become higher than expected, or to be more explicit, it will become:\n\n$$\\mathrm{Type \\ I \\ error} = 1-(1-\\alpha)^N$$\n\nTo prevent this from happening, we can:\n\n- In many cases, it is not even necessary to do multiple tests\n- If multiple testing is unavoidable (for example, we are testing multiple hypothesis in a single test because we have multiple groups), then we can just correct the type-I error as an effective type-I error $\u03b1_{effective}$. In order to recover the original type-I error (thereby \u201ccontrolling\u201d the multiple testing), we must ensure that:\n\n\\begin{align}\n1-(1-\\alpha_\\mathrm{effective})^N &= \\alpha \\ \\Rightarrow \\ \\alpha_\\mathrm{effective} = 1 - (1-\\alpha)^{1/N} \\approx \\frac{\\alpha}{N}\n\\end{align}\n\nFor the last part, we're assuming $\\alpha\\ll 1$ and using taylor expansion we can obtain $(1-x)^m \\approx 1-mx$. [StackExchange](http://math.stackexchange.com/questions/210110/whats-the-name-of-the-approximation-1xn-approx-1-xn). And this goes under the name of **Bonferroni correction**.\n\n## Example\n\nWe will draw samples from two Bernoulli distributions A and B, each with a probability $p=0.5$ of success. Each hypothesis test looks like:\n\n\\begin{eqnarray}\nH_0 &:& \\mu_B -\\mu_A = 0 \\nonumber \\\\\nH_1 &:& \\mu_B -\\mu_A \\neq 0 \\nonumber\n\\end{eqnarray}\n\nWhere $\\mu_A$ and $\\mu_B$ are the two sample means. By our definition, the null $H_0$ is true as we are going to set both $\\mu_A$ and $\\mu_B$ to 0.5. The section below computes the probability of committing a type-I error as a function of the number of independent t-tests, assuming $\\alpha=0.05$. \n\n\n```python\n# set parameters\nalpha = 0.05 # Type I error rate\np1 = 0.5 # Probability for population 1\np2 = 0.5 # Probability for population 2\n\n# simulation parameters\nn_samples = 500 # number of samples each test will use\nn_tests = 20 # max number of tests\nn_sims = 300 # number of simulations from which to draw average\n\ndef run_exp(n_tests, n_samples, p1, p2, alpha):\n    \"\"\"\n    simulations without Bonferroni correction, if it\n    committed a Type I error in any one of the test\n    return 1, else 0\n    \"\"\"\n    for i in range(n_tests):\n        testA = bernoulli(p1).rvs(n_samples)\n        testB = bernoulli(p2).rvs(n_samples)\n        _, pvalue = ttest_ind(testA, testB)\n        if pvalue < alpha:\n            return 1\n    \n    return 0\n\ndef run_exp_corrected(n_tests, n_samples, p1, p2, alpha):\n    \"\"\"simulations with Bonferroni correction\"\"\"\n    for i in range(n_tests):\n        testA = bernoulli(p1).rvs(n_samples)\n        testB = bernoulli(p2).rvs(n_samples)\n        _, pvalue = ttest_ind(testA, testB)\n        if pvalue < alpha / n_tests:\n            return 1\n    \n    return 0\n```\n\n\n```python\np_rejects = []\np_rejects_corrected = []\nfor n_test in trange(1, n_tests + 1):\n    # results without using Bonferroni correction\n    p_reject = [ run_exp(n_test, n_samples, p1, p2, alpha) \n                 for _ in range(n_sims) ]\n    p_reject_avg = np.mean(p_reject)\n    p_rejects.append(p_reject_avg)\n    \n    # results using Bonferroni correction\n    p_reject_corrected = [ run_exp_corrected(n_test, n_samples, p1, p2, alpha) \n                           for _ in range(n_sims) ]\n    p_reject_corrected_avg = np.mean(p_reject_corrected)\n    p_rejects_corrected.append(p_reject_corrected_avg)\n```\n\n    100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 20/20 [02:56<00:00, 14.28s/it]\n\n\n\n```python\n# change default figure size and font size\nplt.rcParams['figure.figsize'] = 10, 6\nplt.rcParams['font.size'] = 12\n\n# plot results\nn = np.arange(1, n_tests + 1)\nplt.semilogy(n, p_rejects, 'ko', markersize = 8, label = 'raw')\nplt.semilogy(n, 1 - (1 - alpha) ** n, linewidth = 3, label = r'$1-(1-\\alpha)^n$')\nplt.semilogy(n, p_rejects_corrected, 'ro', markersize = 8, label = 'corrected')\nticks = [0, 0.01, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]\nplt.yticks(ticks, ticks)\nplt.ylim([0, 0.8])\nplt.xlabel('Number of tests')\nplt.ylabel('Probability of Type I error')\nplt.legend(loc = 'best')\nplt.show()\n```\n\nFrom the plot we can see, without the correction, there's a rapid increase of the type-I error as the number of tests grows. Whereas applying the Bonferroni correction does succeed in controlling the error at the 5%.\n\n# Reference\n\n- [Blog: The multiple hypothesis testing problem](http://www.claudiobellei.com/2016/10/30/multiple-testing-part1/)\n", "meta": {"hexsha": "6748137039cac39c14406455eaadab4890a0588a", "size": 106008, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "frequentist_statistics/multiple_testing.ipynb", "max_stars_repo_name": "swapnilawasthi/Business-Analytics", "max_stars_repo_head_hexsha": "30a8585f45865008ea01d2bf242bf77a9ca5b449", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 92, "max_stars_repo_stars_event_min_datetime": "2016-05-22T06:07:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T03:53:44.000Z", "max_issues_repo_path": "frequentist_statistics/multiple_testing.ipynb", "max_issues_repo_name": "ethen8181/Business-Analytics", "max_issues_repo_head_hexsha": "0fd0fd167eff1c4db05cf53ed744871bb3307595", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "frequentist_statistics/multiple_testing.ipynb", "max_forks_repo_name": "ethen8181/Business-Analytics", "max_forks_repo_head_hexsha": "0fd0fd167eff1c4db05cf53ed744871bb3307595", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 42, "max_forks_repo_forks_event_min_datetime": "2017-02-08T02:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-06T08:53:11.000Z", "avg_line_length": 47.6440449438, "max_line_length": 30516, "alphanum_fraction": 0.6267451513, "converted": true, "num_tokens": 14402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.026759285513888918, "lm_q2_score": 0.025957359081569886, "lm_q1q2_score": 0.000694600382850266}}
{"text": "```python\nACM = r\"\"\"\n%%\n%% This is file `sample-sigconf.tex',\n%% generated with the docstrip utility.\n%%\n%% The original source files were:\n%%\n%% samples.dtx  (with options: `sigconf')\n%% \n%% IMPORTANT NOTICE:\n%% \n%% For the copyright see the source file.\n%% \n%% Any modified versions of this file must be renamed\n%% with new filenames distinct from sample-sigconf.tex.\n%% \n%% For distribution of the original source see the terms\n%% for copying and modification in the file samples.dtx.\n%% \n%% This generated file may be distributed as long as the\n%% original source files, as listed above, are part of the\n%% same distribution. (The sources need not necessarily be\n%% in the same archive or directory.)\n%%\n%% The first command in your LaTeX source must be the \\documentclass command.\n\\documentclass[sigconf]{acmart}\n\n%%\n%% \\BibTeX command to typeset BibTeX logo in the docs\n\\AtBeginDocument{%\n  \\providecommand\\BibTeX{{%\n    \\normalfont B\\kern-0.5em{\\scshape i\\kern-0.25em b}\\kern-0.8em\\TeX}}}\n\n%% Rights management information.  This information is sent to you\n%% when you complete the rights form.  These commands have SAMPLE\n%% values in them; it is your responsibility as an author to replace\n%% the commands and values with those provided to you when you\n%% complete the rights form.\n\\setcopyright{acmcopyright}\n\\copyrightyear{2018}\n\\acmYear{2018}\n\\acmDOI{10.1145/1122445.1122456}\n\n%% These commands are for a PROCEEDINGS abstract or paper.\n\\acmConference[Woodstock '18]{Woodstock '18: ACM Symposium on Neural\n  Gaze Detection}{June 03--05, 2018}{Woodstock, NY}\n\\acmBooktitle{Woodstock '18: ACM Symposium on Neural Gaze Detection,\n  June 03--05, 2018, Woodstock, NY}\n\\acmPrice{15.00}\n\\acmISBN{978-1-4503-XXXX-X/18/06}\n\n\n%%\n%% Submission ID.\n%% Use this when submitting an article to a sponsored event. You'll\n%% receive a unique submission ID from the organizers\n%% of the event, and this ID should be used as the parameter to this command.\n%%\\acmSubmissionID{123-A56-BU3}\n\n%%\n%% The majority of ACM publications use numbered citations and\n%% references.  The command \\citestyle{authoryear} switches to the\n%% \"author year\" style.\n%%\n%% If you are preparing content for an event\n%% sponsored by ACM SIGGRAPH, you must use the \"author year\" style of\n%% citations and references.\n%% Uncommenting\n%% the next command will enable that style.\n%%\\citestyle{acmauthoryear}\n\n%%\n%% end of the preamble, start of the body of the document source.\n\\begin{document}\n\n%%\n%% The \"title\" command has an optional parameter,\n%% allowing the author to define a \"short title\" to be used in page headers.\n\\title{The Name of the Title is Hope}\n\n%%\n%% The \"author\" command and its associated commands are used to define\n%% the authors and their affiliations.\n%% Of note is the shared affiliation of the first two authors, and the\n%% \"authornote\" and \"authornotemark\" commands\n%% used to denote shared contribution to the research.\n\\author{Ben Trovato}\n\\authornote{Both authors contributed equally to this research.}\n\\email{trovato@corporation.com}\n\\orcid{1234-5678-9012}\n\\author{G.K.M. Tobin}\n\\authornotemark[1]\n\\email{webmaster@marysville-ohio.com}\n\\affiliation{%\n  \\institution{Institute for Clarity in Documentation}\n  \\streetaddress{P.O. Box 1212}\n  \\city{Dublin}\n  \\state{Ohio}\n  \\postcode{43017-6221}\n}\n\n\\author{Lars Th{\\o}rv{\\\"a}ld}\n\\affiliation{%\n  \\institution{The Th{\\o}rv{\\\"a}ld Group}\n  \\streetaddress{1 Th{\\o}rv{\\\"a}ld Circle}\n  \\city{Hekla}\n  \\country{Iceland}}\n\\email{larst@affiliation.org}\n\n\\author{Valerie B\\'eranger}\n\\affiliation{%\n  \\institution{Inria Paris-Rocquencourt}\n  \\city{Rocquencourt}\n  \\country{France}\n}\n\n\\author{Aparna Patel}\n\\affiliation{%\n \\institution{Rajiv Gandhi University}\n \\streetaddress{Rono-Hills}\n \\city{Doimukh}\n \\state{Arunachal Pradesh}\n \\country{India}}\n\n\\author{Huifen Chan}\n\\affiliation{%\n  \\institution{Tsinghua University}\n  \\streetaddress{30 Shuangqing Rd}\n  \\city{Haidian Qu}\n  \\state{Beijing Shi}\n  \\country{China}}\n\n\\author{Charles Palmer}\n\\affiliation{%\n  \\institution{Palmer Research Laboratories}\n  \\streetaddress{8600 Datapoint Drive}\n  \\city{San Antonio}\n  \\state{Texas}\n  \\postcode{78229}}\n\\email{cpalmer@prl.com}\n\n\\author{John Smith}\n\\affiliation{\\institution{The Th{\\o}rv{\\\"a}ld Group}}\n\\email{jsmith@affiliation.org}\n\n\\author{Julius P. Kumquat}\n\\affiliation{\\institution{The Kumquat Consortium}}\n\\email{jpkumquat@consortium.net}\n\n%%\n%% By default, the full list of authors will be used in the page\n%% headers. Often, this list is too long, and will overlap\n%% other information printed in the page headers. This command allows\n%% the author to define a more concise list\n%% of authors' names for this purpose.\n\\renewcommand{\\shortauthors}{Trovato and Tobin, et al.}\n\n%%\n%% The abstract is a short summary of the work to be presented in the\n%% article.\n\\begin{abstract}\n  A clear and well-documented \\LaTeX\\ document is presented as an\n  article formatted for publication by ACM in a conference proceedings\n  or journal publication. Based on the ``acmart'' document class, this\n  article presents and explains many of the common variations, as well\n  as many of the formatting elements an author may use in the\n  preparation of the documentation of their work.\n\\end{abstract}\n\n%%\n%% The code below is generated by the tool at http://dl.acm.org/ccs.cfm.\n%% Please copy and paste the code instead of the example below.\n%%\n\\begin{CCSXML}\n<ccs2012>\n <concept>\n  <concept_id>10010520.10010553.10010562</concept_id>\n  <concept_desc>Computer systems organization~Embedded systems</concept_desc>\n  <concept_significance>500</concept_significance>\n </concept>\n <concept>\n  <concept_id>10010520.10010575.10010755</concept_id>\n  <concept_desc>Computer systems organization~Redundancy</concept_desc>\n  <concept_significance>300</concept_significance>\n </concept>\n <concept>\n  <concept_id>10010520.10010553.10010554</concept_id>\n  <concept_desc>Computer systems organization~Robotics</concept_desc>\n  <concept_significance>100</concept_significance>\n </concept>\n <concept>\n  <concept_id>10003033.10003083.10003095</concept_id>\n  <concept_desc>Networks~Network reliability</concept_desc>\n  <concept_significance>100</concept_significance>\n </concept>\n</ccs2012>\n\\end{CCSXML}\n\n\\ccsdesc[500]{Computer systems organization~Embedded systems}\n\\ccsdesc[300]{Computer systems organization~Redundancy}\n\\ccsdesc{Computer systems organization~Robotics}\n\\ccsdesc[100]{Networks~Network reliability}\n\n%%\n%% Keywords. The author(s) should pick words that accurately describe\n%% the work being presented. Separate the keywords with commas.\n\\keywords{datasets, neural networks, gaze detection, text tagging}\n\n%% A \"teaser\" image appears between the author and affiliation\n%% information and the body of the document, and typically spans the\n%% page.\n\\begin{teaserfigure}\n  \\includegraphics[width=\\textwidth]{sampleteaser}\n  \\caption{Seattle Mariners at Spring Training, 2010.}\n  \\Description{Enjoying the baseball game from the third-base\n  seats. Ichiro Suzuki preparing to bat.}\n  \\label{fig:teaser}\n\\end{teaserfigure}\n\n%%\n%% This command processes the author and affiliation and title\n%% information and builds the first part of the formatted document.\n\\maketitle\n\n\\section{Introduction}\nACM's consolidated article template, introduced in 2017, provides a\nconsistent \\LaTeX\\ style for use across ACM publications, and\nincorporates accessibility and metadata-extraction functionality\nnecessary for future Digital Library endeavors. Numerous ACM and\nSIG-specific \\LaTeX\\ templates have been examined, and their unique\nfeatures incorporated into this single new template.\n\nIf you are new to publishing with ACM, this document is a valuable\nguide to the process of preparing your work for publication. If you\nhave published with ACM before, this document provides insight and\ninstruction into more recent changes to the article template.\n\nThe ``\\verb|acmart|'' document class can be used to prepare articles\nfor any ACM publication --- conference or journal, and for any stage\nof publication, from review to final ``camera-ready'' copy, to the\nauthor's own version, with {\\itshape very} few changes to the source.\n\n\\section{Template Overview}\nAs noted in the introduction, the ``\\verb|acmart|'' document class can\nbe used to prepare many different kinds of documentation --- a\ndouble-blind initial submission of a full-length technical paper, a\ntwo-page SIGGRAPH Emerging Technologies abstract, a ``camera-ready''\njournal article, a SIGCHI Extended Abstract, and more --- all by\nselecting the appropriate {\\itshape template style} and {\\itshape\n  template parameters}.\n\nThis document will explain the major features of the document\nclass. For further information, the {\\itshape \\LaTeX\\ User's Guide} is\navailable from\n\\url{https://www.acm.org/publications/proceedings-template}.\n\n\\subsection{Template Styles}\n\nThe primary parameter given to the ``\\verb|acmart|'' document class is\nthe {\\itshape template style} which corresponds to the kind of publication\nor SIG publishing the work. This parameter is enclosed in square\nbrackets and is a part of the {\\verb|documentclass|} command:\n\\begin{verbatim}\n  \\documentclass[STYLE]{acmart}\n\\end{verbatim}\n\nJournals use one of three template styles. All but three ACM journals\nuse the {\\verb|acmsmall|} template style:\n\\begin{itemize}\n\\item {\\verb|acmsmall|}: The default journal template style.\n\\item {\\verb|acmlarge|}: Used by JOCCH and TAP.\n\\item {\\verb|acmtog|}: Used by TOG.\n\\end{itemize}\n\nThe majority of conference proceedings documentation will use the {\\verb|acmconf|} template style.\n\\begin{itemize}\n\\item {\\verb|acmconf|}: The default proceedings template style.\n\\item{\\verb|sigchi|}: Used for SIGCHI conference articles.\n\\item{\\verb|sigchi-a|}: Used for SIGCHI ``Extended Abstract'' articles.\n\\item{\\verb|sigplan|}: Used for SIGPLAN conference articles.\n\\end{itemize}\n\n\\subsection{Template Parameters}\n\nIn addition to specifying the {\\itshape template style} to be used in\nformatting your work, there are a number of {\\itshape template parameters}\nwhich modify some part of the applied template style. A complete list\nof these parameters can be found in the {\\itshape \\LaTeX\\ User's Guide.}\n\nFrequently-used parameters, or combinations of parameters, include:\n\\begin{itemize}\n\\item {\\verb|anonymous,review|}: Suitable for a ``double-blind''\n  conference submission. Anonymizes the work and includes line\n  numbers. Use with the \\verb|\\acmSubmissionID| command to print the\n  submission's unique ID on each page of the work.\n\\item{\\verb|authorversion|}: Produces a version of the work suitable\n  for posting by the author.\n\\item{\\verb|screen|}: Produces colored hyperlinks.\n\\end{itemize}\n\nThis document uses the following string as the first command in the\nsource file:\n\\begin{verbatim}\n\\documentclass[sigconf]{acmart}\n\\end{verbatim}\n\n\\section{Modifications}\n\nModifying the template --- including but not limited to: adjusting\nmargins, typeface sizes, line spacing, paragraph and list definitions,\nand the use of the \\verb|\\vspace| command to manually adjust the\nvertical spacing between elements of your work --- is not allowed.\n\n{\\bfseries Your document will be returned to you for revision if\n  modifications are discovered.}\n\n\\section{Typefaces}\n\nThe ``\\verb|acmart|'' document class requires the use of the\n``Libertine'' typeface family. Your \\TeX\\ installation should include\nthis set of packages. Please do not substitute other typefaces. The\n``\\verb|lmodern|'' and ``\\verb|ltimes|'' packages should not be used,\nas they will override the built-in typeface families.\n\n\\section{Title Information}\n\nThe title of your work should use capital letters appropriately -\n\\url{https://capitalizemytitle.com/} has useful rules for\ncapitalization. Use the {\\verb|title|} command to define the title of\nyour work. If your work has a subtitle, define it with the\n{\\verb|subtitle|} command.  Do not insert line breaks in your title.\n\nIf your title is lengthy, you must define a short version to be used\nin the page headers, to prevent overlapping text. The \\verb|title|\ncommand has a ``short title'' parameter:\n\\begin{verbatim}\n  \\title[short title]{full title}\n\\end{verbatim}\n\n\\section{Authors and Affiliations}\n\nEach author must be defined separately for accurate metadata\nidentification. Multiple authors may share one affiliation. Authors'\nnames should not be abbreviated; use full first names wherever\npossible. Include authors' e-mail addresses whenever possible.\n\nGrouping authors' names or e-mail addresses, or providing an ``e-mail\nalias,'' as shown below, is not acceptable:\n\\begin{verbatim}\n  \\author{Brooke Aster, David Mehldau}\n  \\email{dave,judy,steve@university.edu}\n  \\email{firstname.lastname@phillips.org}\n\\end{verbatim}\n\nThe \\verb|authornote| and \\verb|authornotemark| commands allow a note\nto apply to multiple authors --- for example, if the first two authors\nof an article contributed equally to the work.\n\nIf your author list is lengthy, you must define a shortened version of\nthe list of authors to be used in the page headers, to prevent\noverlapping text. The following command should be placed just after\nthe last \\verb|\\author{}| definition:\n\\begin{verbatim}\n  \\renewcommand{\\shortauthors}{McCartney, et al.}\n\\end{verbatim}\nOmitting this command will force the use of a concatenated list of all\nof the authors' names, which may result in overlapping text in the\npage headers.\n\nThe article template's documentation, available at\n\\url{https://www.acm.org/publications/proceedings-template}, has a\ncomplete explanation of these commands and tips for their effective\nuse.\n\nNote that authors' addresses are mandatory for journal articles.\n\n\\section{Rights Information}\n\nAuthors of any work published by ACM will need to complete a rights\nform. Depending on the kind of work, and the rights management choice\nmade by the author, this may be copyright transfer, permission,\nlicense, or an OA (open access) agreement.\n\nRegardless of the rights management choice, the author will receive a\ncopy of the completed rights form once it has been submitted. This\nform contains \\LaTeX\\ commands that must be copied into the source\ndocument. When the document source is compiled, these commands and\ntheir parameters add formatted text to several areas of the final\ndocument:\n\\begin{itemize}\n\\item the ``ACM Reference Format'' text on the first page.\n\\item the ``rights management'' text on the first page.\n\\item the conference information in the page header(s).\n\\end{itemize}\n\nRights information is unique to the work; if you are preparing several\nworks for an event, make sure to use the correct set of commands with\neach of the works.\n\nThe ACM Reference Format text is required for all articles over one\npage in length, and is optional for one-page articles (abstracts).\n\n\\section{CCS Concepts and User-Defined Keywords}\n\nTwo elements of the ``acmart'' document class provide powerful\ntaxonomic tools for you to help readers find your work in an online\nsearch.\n\nThe ACM Computing Classification System ---\n\\url{https://www.acm.org/publications/class-2012} --- is a set of\nclassifiers and concepts that describe the computing\ndiscipline. Authors can select entries from this classification\nsystem, via \\url{https://dl.acm.org/ccs/ccs.cfm}, and generate the\ncommands to be included in the \\LaTeX\\ source.\n\nUser-defined keywords are a comma-separated list of words and phrases\nof the authors' choosing, providing a more flexible way of describing\nthe research being presented.\n\nCCS concepts and user-defined keywords are required for for all\narticles over two pages in length, and are optional for one- and\ntwo-page articles (or abstracts).\n\n\\section{Sectioning Commands}\n\nYour work should use standard \\LaTeX\\ sectioning commands:\n\\verb|section|, \\verb|subsection|, \\verb|subsubsection|, and\n\\verb|paragraph|. They should be numbered; do not remove the numbering\nfrom the commands.\n\nSimulating a sectioning command by setting the first word or words of\na paragraph in boldface or italicized text is {\\bfseries not allowed.}\n\n\\section{Tables}\n\nThe ``\\verb|acmart|'' document class includes the ``\\verb|booktabs|''\npackage --- \\url{https://ctan.org/pkg/booktabs} --- for preparing\nhigh-quality tables.\n\nTable captions are placed {\\itshape above} the table.\n\nBecause tables cannot be split across pages, the best placement for\nthem is typically the top of the page nearest their initial cite.  To\nensure this proper ``floating'' placement of tables, use the\nenvironment \\textbf{table} to enclose the table's contents and the\ntable caption.  The contents of the table itself must go in the\n\\textbf{tabular} environment, to be aligned properly in rows and\ncolumns, with the desired horizontal and vertical rules.  Again,\ndetailed instructions on \\textbf{tabular} material are found in the\n\\textit{\\LaTeX\\ User's Guide}.\n\nImmediately following this sentence is the point at which\nTable~\\ref{tab:freq} is included in the input file; compare the\nplacement of the table here with the table in the printed output of\nthis document.\n\n\\begin{table}\n  \\caption{Frequency of Special Characters}\n  \\label{tab:freq}\n  \\begin{tabular}{ccl}\n    \\toprule\n    Non-English or Math&Frequency&Comments\\\\\n    \\midrule\n    \\O & 1 in 1,000& For Swedish names\\\\\n    $\\pi$ & 1 in 5& Common in math\\\\\n    \\$ & 4 in 5 & Used in business\\\\\n    $\\Psi^2_1$ & 1 in 40,000& Unexplained usage\\\\\n  \\bottomrule\n\\end{tabular}\n\\end{table}\n\nTo set a wider table, which takes up the whole width of the page's\nlive area, use the environment \\textbf{table*} to enclose the table's\ncontents and the table caption.  As with a single-column table, this\nwide table will ``float'' to a location deemed more\ndesirable. Immediately following this sentence is the point at which\nTable~\\ref{tab:commands} is included in the input file; again, it is\ninstructive to compare the placement of the table here with the table\nin the printed output of this document.\n\n\\begin{table*}\n  \\caption{Some Typical Commands}\n  \\label{tab:commands}\n  \\begin{tabular}{ccl}\n    \\toprule\n    Command &A Number & Comments\\\\\n    \\midrule\n    \\texttt{{\\char'134}author} & 100& Author \\\\\n    \\texttt{{\\char'134}table}& 300 & For tables\\\\\n    \\texttt{{\\char'134}table*}& 400& For wider tables\\\\\n    \\bottomrule\n  \\end{tabular}\n\\end{table*}\n\nAlways use midrule to separate table header rows from data rows, and\nuse it only for this purpose. This enables assistive technologies to\nrecognise table headers and support their users in navigating tables\nmore easily.\n\n\\section{Math Equations}\nYou may want to display math equations in three distinct styles:\ninline, numbered or non-numbered display.  Each of the three are\ndiscussed in the next sections.\n\n\\subsection{Inline (In-text) Equations}\nA formula that appears in the running text is called an inline or\nin-text formula.  It is produced by the \\textbf{math} environment,\nwhich can be invoked with the usual\n\\texttt{{\\char'134}begin\\,\\ldots{\\char'134}end} construction or with\nthe short form \\texttt{\\$\\,\\ldots\\$}. You can use any of the symbols\nand structures, from $\\alpha$ to $\\omega$, available in\n\\LaTeX~\\cite{Lamport:LaTeX}; this section will simply show a few\nexamples of in-text equations in context. Notice how this equation:\n\\begin{math}\n  \\lim_{n\\rightarrow \\infty}x=0\n\\end{math},\nset here in in-line math style, looks slightly different when\nset in display style.  (See next section).\n\n\\subsection{Display Equations}\nA numbered display equation---one set off by vertical space from the\ntext and centered horizontally---is produced by the \\textbf{equation}\nenvironment. An unnumbered display equation is produced by the\n\\textbf{displaymath} environment.\n\nAgain, in either environment, you can use any of the symbols and\nstructures available in \\LaTeX\\@; this section will just give a couple\nof examples of display equations in context.  First, consider the\nequation, shown as an inline equation above:\n\\begin{equation}\n  \\lim_{n\\rightarrow \\infty}x=0\n\\end{equation}\nNotice how it is formatted somewhat differently in\nthe \\textbf{displaymath}\nenvironment.  Now, we'll enter an unnumbered equation:\n\\begin{displaymath}\n  \\sum_{i=0}^{\\infty} x + 1\n\\end{displaymath}\nand follow it with another numbered equation:\n\\begin{equation}\n  \\sum_{i=0}^{\\infty}x_i=\\int_{0}^{\\pi+2} f\n\\end{equation}\njust to demonstrate \\LaTeX's able handling of numbering.\n\n\\section{Figures}\n\nThe ``\\verb|figure|'' environment should be used for figures. One or\nmore images can be placed within a figure. If your figure contains\nthird-party material, you must clearly identify it as such, as shown\nin the example below.\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=\\linewidth]{sample-franklin}\n  \\caption{1907 Franklin Model D roadster. Photograph by Harris \\&\n    Ewing, Inc. [Public domain], via Wikimedia\n    Commons. (\\url{https://goo.gl/VLCRBB}).}\n  \\Description{A woman and a girl in white dresses sit in an open car.}\n\\end{figure}\n\nYour figures should contain a caption which describes the figure to\nthe reader.\n\nFigure captions are placed {\\itshape below} the figure.\n\nEvery figure should also have a figure description unless it is purely\ndecorative. These descriptions convey what\u2019s in the image to someone\nwho cannot see it. They are also used by search engine crawlers for\nindexing images, and when images cannot be loaded.\n\nA figure description must be unformatted plain text less than 2000\ncharacters long (including spaces).  {\\bfseries Figure descriptions\n  should not repeat the figure caption \u2013 their purpose is to capture\n  important information that is not already provided in the caption or\n  the main text of the paper.} For figures that convey important and\ncomplex new information, a short text description may not be\nadequate. More complex alternative descriptions can be placed in an\nappendix and referenced in a short figure description. For example,\nprovide a data table capturing the information in a bar chart, or a\nstructured list representing a graph.  For additional information\nregarding how best to write figure descriptions and why doing this is\nso important, please see\n\\url{https://www.acm.org/publications/taps/describing-figures/}.\n\n\\subsection{The ``Teaser Figure''}\n\nA ``teaser figure'' is an image, or set of images in one figure, that\nare placed after all author and affiliation information, and before\nthe body of the article, spanning the page. If you wish to have such a\nfigure in your article, place the command immediately before the\n\\verb|\\maketitle| command:\n\\begin{verbatim}\n  \\begin{teaserfigure}\n    \\includegraphics[width=\\textwidth]{sampleteaser}\n    \\caption{figure caption}\n    \\Description{figure description}\n  \\end{teaserfigure}\n\\end{verbatim}\n\n\\section{Citations and Bibliographies}\n\nThe use of \\BibTeX\\ for the preparation and formatting of one's\nreferences is strongly recommended. Authors' names should be complete\n--- use full first names (``Donald E. Knuth'') not initials\n(``D. E. Knuth'') --- and the salient identifying features of a\nreference should be included: title, year, volume, number, pages,\narticle DOI, etc.\n\nThe bibliography is included in your source document with these two\ncommands, placed just before the \\verb|\\end{document}| command:\n\\begin{verbatim}\n  \\bibliographystyle{ACM-Reference-Format}\n  \\bibliography{bibfile}\n\\end{verbatim}\nwhere ``\\verb|bibfile|'' is the name, without the ``\\verb|.bib|''\nsuffix, of the \\BibTeX\\ file.\n\nCitations and references are numbered by default. A small number of\nACM publications have citations and references formatted in the\n``author year'' style; for these exceptions, please include this\ncommand in the {\\bfseries preamble} (before the command\n``\\verb|\\begin{document}|'') of your \\LaTeX\\ source:\n\\begin{verbatim}\n  \\citestyle{acmauthoryear}\n\\end{verbatim}\n\n  Some examples.  A paginated journal article \\cite{Abril07}, an\n  enumerated journal article \\cite{Cohen07}, a reference to an entire\n  issue \\cite{JCohen96}, a monograph (whole book) \\cite{Kosiur01}, a\n  monograph/whole book in a series (see 2a in spec. document)\n  \\cite{Harel79}, a divisible-book such as an anthology or compilation\n  \\cite{Editor00} followed by the same example, however we only output\n  the series if the volume number is given \\cite{Editor00a} (so\n  Editor00a's series should NOT be present since it has no vol. no.),\n  a chapter in a divisible book \\cite{Spector90}, a chapter in a\n  divisible book in a series \\cite{Douglass98}, a multi-volume work as\n  book \\cite{Knuth97}, a couple of articles in a proceedings (of a\n  conference, symposium, workshop for example) (paginated proceedings\n  article) \\cite{Andler79, Hagerup1993}, a proceedings article with\n  all possible elements \\cite{Smith10}, an example of an enumerated\n  proceedings article \\cite{VanGundy07}, an informally published work\n  \\cite{Harel78}, a couple of preprints \\cite{Bornmann2019,\n    AnzarootPBM14}, a doctoral dissertation \\cite{Clarkson85}, a\n  master's thesis: \\cite{anisi03}, an online document / world wide web\n  resource \\cite{Thornburg01, Ablamowicz07, Poker06}, a video game\n  (Case 1) \\cite{Obama08} and (Case 2) \\cite{Novak03} and \\cite{Lee05}\n  and (Case 3) a patent \\cite{JoeScientist001}, work accepted for\n  publication \\cite{rous08}, 'YYYYb'-test for prolific author\n  \\cite{SaeediMEJ10} and \\cite{SaeediJETC10}. Other cites might\n  contain 'duplicate' DOI and URLs (some SIAM articles)\n  \\cite{Kirschmer:2010:AEI:1958016.1958018}. Boris / Barbara Beeton:\n  multi-volume works as books \\cite{MR781536} and \\cite{MR781537}. A\n  couple of citations with DOIs:\n  \\cite{2004:ITE:1009386.1010128,Kirschmer:2010:AEI:1958016.1958018}. Online\n  citations: \\cite{TUGInstmem, Thornburg01, CTANacmart}. Artifacts:\n  \\cite{R} and \\cite{UMassCitations}.\n\n\\section{Acknowledgments}\n\nIdentification of funding sources and other support, and thanks to\nindividuals and groups that assisted in the research and the\npreparation of the work should be included in an acknowledgment\nsection, which is placed just before the reference section in your\ndocument.\n\nThis section has a special environment:\n\\begin{verbatim}\n  \\begin{acks}\n  ...\n  \\end{acks}\n\\end{verbatim}\nso that the information contained therein can be more easily collected\nduring the article metadata extraction phase, and to ensure\nconsistency in the spelling of the section heading.\n\nAuthors should not prepare this section as a numbered or unnumbered {\\verb|\\section|}; please use the ``{\\verb|acks|}'' environment.\n\n\\section{Appendices}\n\nIf your work needs an appendix, add it before the\n``\\verb|\\end{document}|'' command at the conclusion of your source\ndocument.\n\nStart the appendix with the ``\\verb|appendix|'' command:\n\\begin{verbatim}\n  \\appendix\n\\end{verbatim}\nand note that in the appendix, sections are lettered, not\nnumbered. This document has two appendices, demonstrating the section\nand subsection identification method.\n\n\\section{SIGCHI Extended Abstracts}\n\nThe ``\\verb|sigchi-a|'' template style (available only in \\LaTeX\\ and\nnot in Word) produces a landscape-orientation formatted article, with\na wide left margin. Three environments are available for use with the\n``\\verb|sigchi-a|'' template style, and produce formatted output in\nthe margin:\n\\begin{itemize}\n\\item {\\verb|sidebar|}:  Place formatted text in the margin.\n\\item {\\verb|marginfigure|}: Place a figure in the margin.\n\\item {\\verb|margintable|}: Place a table in the margin.\n\\end{itemize}\n\n%%\n%% The acknowledgments section is defined using the \"acks\" environment\n%% (and NOT an unnumbered section). This ensures the proper\n%% identification of the section in the article metadata, and the\n%% consistent spelling of the heading.\n\\begin{acks}\nTo Robert, for the bagels and explaining CMYK and color spaces.\n\\end{acks}\n\n%%\n%% The next two lines define the bibliography style to be used, and\n%% the bibliography file.\n\\bibliographystyle{ACM-Reference-Format}\n\\bibliography{sample-base}\n\n%%\n%% If your work has an appendix, this is the place to put it.\n\\appendix\n\n\\section{Research Methods}\n\n\\subsection{Part One}\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi\nmalesuada, quam in pulvinar varius, metus nunc fermentum urna, id\nsollicitudin purus odio sit amet enim. Aliquam ullamcorper eu ipsum\nvel mollis. Curabitur quis dictum nisl. Phasellus vel semper risus, et\nlacinia dolor. Integer ultricies commodo sem nec semper.\n\n\\subsection{Part Two}\n\nEtiam commodo feugiat nisl pulvinar pellentesque. Etiam auctor sodales\nligula, non varius nibh pulvinar semper. Suspendisse nec lectus non\nipsum convallis congue hendrerit vitae sapien. Donec at laoreet\neros. Vivamus non purus placerat, scelerisque diam eu, cursus\nante. Etiam aliquam tortor auctor efficitur mattis.\n\n\\section{Online Resources}\n\nNam id fermentum dui. Suspendisse sagittis tortor a nulla mollis, in\npulvinar ex pretium. Sed interdum orci quis metus euismod, et sagittis\nenim maximus. Vestibulum gravida massa ut felis suscipit\ncongue. Quisque mattis elit a risus ultrices commodo venenatis eget\ndui. Etiam sagittis eleifend elementum.\n\nNam interdum magna at lectus dignissim, ac dignissim lorem\nrhoncus. Maecenas eu arcu ac neque placerat aliquam. Nunc pulvinar\nmassa et mattis lacinia.\n\n\\end{document}\n\\endinput\n%%\n%% End of file `sample-sigconf.tex'.\"\"\"\n```\n\n\n```python\n%run fable/script.py\n```\n\n\n```python\nglow = load('/home/yu/glow.tex')\n```\n\n\n```python\npdf, output = run_entries(glow, 0)\n```\n\n    /tmp/tmp7sjcfwuw/text.tex\n\n\n\n```python\nis_small(pdf)\n```\n\n\n\n\n    True\n\n\n\n\n```python\nread = PdfFileReader(io.BytesIO(pdf))\n```\n\n\n```python\npage = read.getPage(0)\n```\n\n\n```python\npage.mediaBox.getHeight(), page.mediaBox.getWidth()\n```\n\n\n\n\n    (Decimal('29.4'), Decimal('28.08'))\n\n\n\n\n```python\nwith open('/tmp/tmpxrqls4u2/text.tex') as f:\n    print(f.read())\n```\n\n    \\documentclass[class=acmart,sigconf,10pt,varwidth=18.3cm,border={12pt 12pt 12pt 12pt}]{standalone}\n    \n    \\usepackage{xcolor}\n    \\newcommand\\TODO[1]{\\textcolor{red}{\\textbf{#1}}}\n    \\usepackage[outputdir=/tmp/tmpxrqls4u2]{minted}\n    \\usepackage{amsthm}\n    \\newtheorem{defintion}{Definition}\n    \n    \\begin{document}\n    \\title{CLOW: Static Language with Dynamic Generics Programming}\n    \\author{Yuri Rapoport}\n    \\email{r.yuri@alumni.technion.ac.il}\n    \\keywords{generic programming, dynamic languages, code generation, static languages}\n    \n    \\begin{abstract}\n    Generic programming allows developers to write abstract algorithms and specify separately the concrete use-cases to the compiler. The compilers can combine the two inputs to create the final program. The syntax and the semantics of generics are usually considered to be part of the programming language itself and generic instructions are written along the lines of the abstract algorithms. We propose to untie this bound and decouple the language of algorithmic abstractions and the language of concrete use-cases specifications. We introduce low-level programming language in which compile-time programming is separated from the core logic part of the program and is written in a dynamic high level object oriented language. This decoupling allows us to achieve high expressiveness, high efficiency and preserve clearness in both the compile-time part and the low level logic parts of the program.\n    \\end{abstract}\n    \\maketitle\n    \\end{document}\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "ea2557ce2e0d8a783d0cc917c3039d1f2136f383", "size": 40674, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Tests.ipynb", "max_stars_repo_name": "yrapop01/fable", "max_stars_repo_head_hexsha": "47a3bbb75a57db8927116ac46bfeaa3bceac2612", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tests.ipynb", "max_issues_repo_name": "yrapop01/fable", "max_issues_repo_head_hexsha": "47a3bbb75a57db8927116ac46bfeaa3bceac2612", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tests.ipynb", "max_forks_repo_name": "yrapop01/fable", "max_forks_repo_head_hexsha": "47a3bbb75a57db8927116ac46bfeaa3bceac2612", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.9244060475, "max_line_length": 910, "alphanum_fraction": 0.6296159709, "converted": true, "num_tokens": 8058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.044680875361038215, "lm_q2_score": 0.01016965967572989, "lm_q1q2_score": 0.0004543892964354635}}
